summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorwolfbeast <mcwerewolf@gmail.com>2018-05-14 10:50:01 +0200
committerwolfbeast <mcwerewolf@gmail.com>2018-05-14 10:50:01 +0200
commite9dd029f5d00590e1a53e63b0ab805110a10b54c (patch)
tree1126ca5dda925a62be3dc12c99c90e953d08afcf
parent9d6a7ae25d7f5da855a8f8df884de483b4e2a538 (diff)
parent36b8fd734f590eb726ca2e50f8d1ff9cc968b8e1 (diff)
downloadUXP-e9dd029f5d00590e1a53e63b0ab805110a10b54c.tar
UXP-e9dd029f5d00590e1a53e63b0ab805110a10b54c.tar.gz
UXP-e9dd029f5d00590e1a53e63b0ab805110a10b54c.tar.lz
UXP-e9dd029f5d00590e1a53e63b0ab805110a10b54c.tar.xz
UXP-e9dd029f5d00590e1a53e63b0ab805110a10b54c.zip
Merge branch 'master' into Basilisk-release
-rw-r--r--.eslintrc.js3
-rw-r--r--CLOBBER2
-rw-r--r--README.md6
-rw-r--r--accessible/base/nsAccessibilityService.h4
-rw-r--r--accessible/ipc/DocAccessibleParent.cpp25
-rw-r--r--accessible/jsat/PointerAdapter.jsm11
-rw-r--r--accessible/windows/msaa/HTMLWin32ObjectAccessible.cpp27
-rw-r--r--accessible/windows/msaa/HTMLWin32ObjectAccessible.h7
-rw-r--r--aclocal.m41
-rw-r--r--application/palemoon/app/Makefile.in2
-rw-r--r--application/palemoon/app/application.ini50
-rw-r--r--application/palemoon/app/macversion.py2
-rw-r--r--application/palemoon/app/nsBrowserApp.cpp35
-rw-r--r--application/palemoon/app/profile/palemoon.js15
-rw-r--r--application/palemoon/base/content/browser-fullScreen.js306
-rw-r--r--application/palemoon/base/content/browser-plugins.js20
-rw-r--r--application/palemoon/base/content/browser.css17
-rw-r--r--application/palemoon/base/content/browser.js393
-rw-r--r--application/palemoon/base/content/browser.xul14
-rw-r--r--application/palemoon/base/content/newtab/grid.js7
-rw-r--r--application/palemoon/base/content/nsContextMenu.js7
-rw-r--r--application/palemoon/base/content/openLocation.js77
-rw-r--r--application/palemoon/base/content/pageinfo/pageInfo.js3
-rw-r--r--application/palemoon/base/content/pageinfo/pageInfo.xul29
-rw-r--r--application/palemoon/base/content/pageinfo/permissions.js18
-rw-r--r--application/palemoon/base/content/tabbrowser.xml167
-rw-r--r--application/palemoon/base/content/urlbarBindings.xml160
-rw-r--r--application/palemoon/base/content/utilityOverlay.js54
-rw-r--r--application/palemoon/base/jar.mn2
-rw-r--r--application/palemoon/components/about/AboutRedirector.cpp9
-rw-r--r--application/palemoon/components/downloads/content/allDownloadsViewOverlay.js59
-rw-r--r--application/palemoon/components/downloads/content/downloads.js3
-rw-r--r--application/palemoon/components/downloads/content/indicator.js21
-rw-r--r--application/palemoon/components/feeds/FeedWriter.js2
-rw-r--r--application/palemoon/components/nsBrowserGlue.js270
-rw-r--r--application/palemoon/components/places/content/editBookmarkOverlay.js21
-rw-r--r--application/palemoon/components/preferences/aboutPermissions.js186
-rw-r--r--application/palemoon/components/preferences/aboutPermissions.xul63
-rw-r--r--application/palemoon/components/preferences/advanced.js49
-rw-r--r--application/palemoon/components/preferences/content.js22
-rw-r--r--application/palemoon/components/preferences/content.xul7
-rw-r--r--application/palemoon/components/preferences/cookies.js7
-rw-r--r--application/palemoon/components/preferences/handlers.xml2
-rw-r--r--application/palemoon/components/preferences/jar.mn6
-rw-r--r--application/palemoon/components/preferences/permissions.js308
-rw-r--r--application/palemoon/components/preferences/permissions.xul36
-rw-r--r--application/palemoon/components/preferences/security.js16
-rw-r--r--application/palemoon/components/sessionstore/SessionStore.jsm38
-rw-r--r--application/palemoon/confvars.sh14
-rw-r--r--application/palemoon/installer/package-manifest.in19
-rw-r--r--application/palemoon/locales/en-US/chrome/browser/browser.dtd3
-rw-r--r--application/palemoon/locales/en-US/chrome/browser/browser.properties15
-rw-r--r--application/palemoon/locales/en-US/chrome/browser/pageInfo.dtd2
-rw-r--r--application/palemoon/locales/en-US/chrome/browser/preferences/aboutPermissions.dtd4
-rw-r--r--application/palemoon/locales/en-US/chrome/browser/preferences/content.dtd2
-rw-r--r--application/palemoon/locales/en-US/chrome/browser/preferences/permissions.dtd8
-rw-r--r--application/palemoon/locales/en-US/chrome/browser/preferences/preferences.properties2
-rw-r--r--application/palemoon/modules/PopupNotifications.jsm66
-rw-r--r--application/palemoon/modules/webrtcUI.jsm130
-rw-r--r--application/palemoon/themes/linux/browser.css26
-rw-r--r--application/palemoon/themes/linux/jar.mn4
-rw-r--r--application/palemoon/themes/linux/notification-16.pngbin610 -> 0 bytes
-rw-r--r--application/palemoon/themes/linux/notification-64.pngbin3373 -> 0 bytes
-rw-r--r--application/palemoon/themes/linux/preferences/aboutPermissions.css8
-rw-r--r--application/palemoon/themes/linux/web-notifications-icon.svg15
-rw-r--r--application/palemoon/themes/linux/web-notifications-tray.svg23
-rw-r--r--application/palemoon/themes/osx/browser.css22
-rw-r--r--application/palemoon/themes/osx/jar.mn4
-rw-r--r--application/palemoon/themes/osx/notification-16.pngbin610 -> 0 bytes
-rw-r--r--application/palemoon/themes/osx/notification-64.pngbin3373 -> 0 bytes
-rw-r--r--application/palemoon/themes/osx/preferences/aboutPermissions.css8
-rw-r--r--application/palemoon/themes/osx/web-notifications-icon.svg15
-rw-r--r--application/palemoon/themes/osx/web-notifications-tray.svg23
-rw-r--r--application/palemoon/themes/windows/Push-16.pngbin0 -> 704 bytes
-rw-r--r--application/palemoon/themes/windows/Push-64.pngbin0 -> 8388 bytes
-rw-r--r--application/palemoon/themes/windows/browser.css22
-rw-r--r--application/palemoon/themes/windows/jar.mn4
-rw-r--r--application/palemoon/themes/windows/notification-16.pngbin610 -> 0 bytes
-rw-r--r--application/palemoon/themes/windows/notification-64.pngbin3373 -> 0 bytes
-rw-r--r--application/palemoon/themes/windows/preferences/aboutPermissions.css8
-rw-r--r--application/palemoon/themes/windows/web-notifications-icon.svg15
-rw-r--r--application/palemoon/themes/windows/web-notifications-tray.svg23
-rw-r--r--browser/app/application.ini50
-rw-r--r--browser/app/moz.build16
-rw-r--r--browser/app/nsBrowserApp.cpp35
-rw-r--r--browser/app/profile/firefox.js94
-rw-r--r--browser/base/content/browser-addons.js65
-rwxr-xr-xbrowser/base/content/browser.js83
-rw-r--r--browser/base/content/content.js6
-rw-r--r--browser/base/content/nsContextMenu.js5
-rw-r--r--browser/base/content/tabbrowser.xml6
-rw-r--r--browser/base/content/utilityOverlay.js22
-rw-r--r--browser/branding/shared/uaoverrides.inc3
-rw-r--r--browser/branding/unofficial/basilisk.VisualElementsManifest.xml (renamed from browser/branding/unofficial/serpent.VisualElementsManifest.xml)0
-rw-r--r--browser/components/feeds/FeedConverter.js2
-rw-r--r--browser/components/preferences/fonts.xul3
-rw-r--r--browser/components/sessionstore/ContentRestore.jsm5
-rw-r--r--browser/components/sessionstore/SessionHistory.jsm5
-rw-r--r--browser/components/sessionstore/SessionMigration.jsm14
-rw-r--r--browser/components/sessionstore/SessionStore.jsm4
-rw-r--r--browser/installer/package-manifest.in20
-rw-r--r--browser/locales/en-US/chrome/browser/browser.properties2
-rw-r--r--browser/locales/en-US/chrome/browser/preferences/fonts.dtd1
-rw-r--r--browser/modules/ContentClick.jsm1
-rw-r--r--browser/themes/osx/shared.inc2
-rw-r--r--browser/themes/shared/tabs.inc.css5
-rw-r--r--build/application.ini66
-rw-r--r--build/autoconf/icu.m438
-rw-r--r--build/autoconf/jemalloc.m4114
-rw-r--r--build/directive4.py1
-rw-r--r--build/gyp.mozbuild19
-rw-r--r--build/moz.build22
-rw-r--r--build/moz.configure/memory.configure38
-rw-r--r--build/moz.configure/old.configure2
-rw-r--r--chrome/nsChromeRegistry.cpp12
-rw-r--r--config/system-headers3
-rw-r--r--devtools/client/inspector/markup/test/browser.ini2
-rw-r--r--devtools/client/inspector/markup/test/browser_markup_update-on-navigtion.js5
-rw-r--r--devtools/client/inspector/markup/test/doc_markup_update-on-navigtion_1.html1
-rw-r--r--devtools/client/inspector/markup/test/doc_markup_update-on-navigtion_2.html1
-rw-r--r--devtools/client/locales/en-US/webConsole.dtd5
-rw-r--r--devtools/client/preferences/devtools.js2
-rw-r--r--devtools/client/responsive.html/browser/web-navigation.js8
-rw-r--r--devtools/client/shared/widgets/TableWidget.js9
-rwxr-xr-xdevtools/client/sourceeditor/tern/def.js5
-rw-r--r--devtools/client/storage/ui.js42
-rw-r--r--devtools/client/webconsole/webconsole.js45
-rw-r--r--devtools/client/webconsole/webconsole.xul4
-rw-r--r--devtools/moz.build12
-rw-r--r--devtools/server/actors/webconsole.js6
-rw-r--r--devtools/server/child.js2
-rw-r--r--devtools/server/main.js2
-rw-r--r--devtools/shared/css/generated/properties-db.js21
-rw-r--r--devtools/shared/discovery/discovery.js13
-rw-r--r--devtools/shared/heapsnapshot/moz.build19
-rw-r--r--docs/CONTRIBUTING.md (renamed from .github/CONTRIBUTING.md)0
-rw-r--r--docshell/base/crashtests/914521.html10
-rw-r--r--docshell/base/nsDocShell.cpp78
-rw-r--r--docshell/base/nsDocShell.h6
-rw-r--r--docshell/base/nsILinkHandler.h10
-rw-r--r--docshell/base/nsIWebNavigation.idl23
-rw-r--r--docshell/shistory/nsSHEntry.cpp3
-rw-r--r--docshell/shistory/nsSHistory.cpp3
-rw-r--r--docshell/test/browser/browser.ini3
-rw-r--r--docshell/test/browser/browser_click_link_within_view_source.js60
-rw-r--r--docshell/test/browser/browser_history_triggeringprincipal_viewsource.js50
-rw-r--r--docshell/test/browser/dummy_page.html6
-rw-r--r--docshell/test/browser/file_click_link_within_view_source.html6
-rw-r--r--docshell/test/chrome/test_bug364461.xul10
-rw-r--r--docshell/test/dummy_page.html6
-rw-r--r--docshell/test/file_bug598895_1.html1
-rw-r--r--docshell/test/file_bug598895_2.html1
-rw-r--r--docshell/test/file_bug637644_1.html1
-rw-r--r--docshell/test/file_bug637644_2.html1
-rw-r--r--docshell/test/mochitest.ini6
-rw-r--r--docshell/test/navigation/NavigationUtils.js20
-rw-r--r--docshell/test/navigation/file_scrollRestoration.html4
-rw-r--r--docshell/test/navigation/mochitest.ini2
-rw-r--r--docshell/test/navigation/navigation_target_popup_url.html1
-rw-r--r--docshell/test/navigation/navigation_target_url.html1
-rw-r--r--docshell/test/navigation/open.html2
-rw-r--r--docshell/test/navigation/test_triggeringprincipal_window_open.html28
-rw-r--r--docshell/test/test_bug598895.html5
-rw-r--r--docshell/test/test_bug637644.html5
-rw-r--r--docshell/test/test_triggeringprincipal_location_seturi.html102
-rw-r--r--dom/animation/Animation.cpp42
-rw-r--r--dom/animation/Animation.h10
-rw-r--r--dom/animation/AnimationEffectReadOnly.cpp18
-rw-r--r--dom/animation/ComputedTiming.h6
-rw-r--r--dom/animation/test/css-animations/file_event-dispatch.html252
-rw-r--r--dom/animation/test/css-animations/file_event-order.html160
-rw-r--r--dom/animation/test/css-animations/test_event-dispatch.html15
-rw-r--r--dom/animation/test/css-animations/test_event-order.html (renamed from dom/animation/test/css-transitions/test_csstransition-events.html)3
-rw-r--r--dom/animation/test/css-transitions/file_animation-cancel.html182
-rw-r--r--dom/animation/test/css-transitions/file_csstransition-events.html223
-rw-r--r--dom/animation/test/css-transitions/file_event-dispatch.html474
-rw-r--r--dom/animation/test/css-transitions/file_setting-effect.html9
-rw-r--r--dom/animation/test/css-transitions/test_event-dispatch.html14
-rw-r--r--dom/animation/test/mochitest.ini6
-rw-r--r--dom/apps/AppsUtils.jsm3
-rw-r--r--dom/audiochannel/AudioChannelService.cpp32
-rw-r--r--dom/audiochannel/AudioChannelService.h22
-rw-r--r--dom/base/Navigator.cpp6
-rw-r--r--dom/base/ScreenOrientation.cpp2
-rwxr-xr-xdom/base/moz.build5
-rw-r--r--dom/base/nsContentPermissionHelper.cpp3
-rw-r--r--dom/base/nsContentUtils.cpp12
-rw-r--r--dom/base/nsContentUtils.h9
-rw-r--r--dom/base/nsDOMNavigationTiming.cpp138
-rw-r--r--dom/base/nsDOMNavigationTiming.h125
-rw-r--r--dom/base/nsGkAtomList.h3
-rw-r--r--dom/base/nsGlobalWindow.cpp150
-rw-r--r--dom/base/nsGlobalWindow.h20
-rw-r--r--dom/base/nsISelectionPrivate.idl2
-rw-r--r--dom/base/nsPIDOMWindow.h20
-rw-r--r--dom/base/test/file_ipc_messagemanager_blob.html1
-rw-r--r--dom/base/test/file_simplecontentpolicy.js1
-rw-r--r--dom/base/test/mochitest.ini1
-rw-r--r--dom/base/test/test_ipc_messagemanager_blob.html3
-rw-r--r--dom/base/test/test_x-frame-options.html6
-rw-r--r--dom/bindings/BindingUtils.cpp20
-rw-r--r--dom/bindings/Codegen.py14
-rw-r--r--dom/bindings/ErrorResult.h2
-rw-r--r--dom/browser-element/mochitest/browserElementTestHelpers.js4
-rw-r--r--dom/browser-element/mochitest/browserElement_BrowserWindowResize.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_Close.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_ContextmenuEvents.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_CopyPaste.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_DataURI.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_Iconchange.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_Manifestchange.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_Metachange.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_Opensearch.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_PromptCheck.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_PromptConfirm.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_RemoveBrowserElement.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_ScrollEvent.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_Titlechange.js1
-rw-r--r--dom/browser-element/mochitest/browserElement_TopBarrier.js1
-rw-r--r--dom/canvas/CanvasRenderingContext2D.cpp4
-rw-r--r--dom/canvas/WebGLContext.cpp28
-rw-r--r--dom/canvas/test/webgl-mochitest/driver-info.js3
-rwxr-xr-xdom/console/Console.cpp5
-rw-r--r--dom/console/Console.h10
-rw-r--r--dom/downloads/DownloadsAPI.js517
-rw-r--r--dom/downloads/DownloadsAPI.jsm365
-rw-r--r--dom/downloads/DownloadsAPI.manifest6
-rw-r--r--dom/downloads/DownloadsIPC.jsm224
-rw-r--r--dom/downloads/moz.build21
-rw-r--r--dom/downloads/tests/clear_all_done_helper.js67
-rw-r--r--dom/downloads/tests/mochitest.ini15
-rw-r--r--dom/downloads/tests/serve_file.sjs170
-rw-r--r--dom/downloads/tests/test_downloads_bad_file.html93
-rw-r--r--dom/downloads/tests/test_downloads_basic.html128
-rw-r--r--dom/downloads/tests/test_downloads_large.html110
-rw-r--r--dom/downloads/tests/test_downloads_navigator_object.html75
-rw-r--r--dom/downloads/tests/test_downloads_pause_remove.html117
-rw-r--r--dom/downloads/tests/test_downloads_pause_resume.html121
-rw-r--r--dom/encoding/FallbackEncoding.cpp3
-rwxr-xr-xdom/events/Event.cpp7
-rw-r--r--dom/events/EventListenerManager.cpp42
-rw-r--r--dom/events/EventNameList.h30
-rw-r--r--dom/events/EventStateManager.cpp66
-rw-r--r--dom/events/EventStateManager.h10
-rw-r--r--dom/events/KeyNameList.h4
-rw-r--r--dom/events/TouchEvent.cpp2
-rw-r--r--dom/events/WheelHandlingHelper.cpp1
-rw-r--r--dom/events/moz.build5
-rw-r--r--dom/events/test/mochitest.ini1
-rw-r--r--dom/events/test/test_bug1304044.html133
-rw-r--r--dom/events/test/test_eventTimeStamp.html36
-rw-r--r--dom/events/test/test_legacy_event.html21
-rw-r--r--dom/geolocation/moz.build4
-rw-r--r--dom/geolocation/nsGeolocation.cpp13
-rw-r--r--dom/html/HTMLInputElement.cpp15
-rw-r--r--dom/html/nsIFormControl.h4
-rw-r--r--dom/html/test/test_fullscreen-api-race.html4
-rw-r--r--dom/indexedDB/ActorsParent.cpp40
-rw-r--r--dom/indexedDB/IDBCursor.cpp10
-rw-r--r--dom/indexedDB/IDBCursor.h2
-rw-r--r--dom/indexedDB/IDBObjectStore.cpp20
-rw-r--r--dom/indexedDB/IDBObjectStore.h2
-rw-r--r--dom/indexedDB/IndexedDatabaseManager.cpp6
-rw-r--r--dom/indexedDB/IndexedDatabaseManager.h4
-rw-r--r--dom/indexedDB/Key.cpp6
-rw-r--r--dom/indexedDB/Key.h4
-rw-r--r--dom/indexedDB/moz.build3
-rw-r--r--dom/indexedDB/test/unit/xpcshell-child-process.ini2
-rw-r--r--dom/indexedDB/test/unit/xpcshell-parent-process.ini1
-rw-r--r--dom/inputmethod/HardwareKeyHandler.cpp562
-rw-r--r--dom/inputmethod/HardwareKeyHandler.h224
-rw-r--r--dom/inputmethod/Keyboard.jsm16
-rw-r--r--dom/inputmethod/moz.build23
-rw-r--r--dom/inputmethod/nsIHardwareKeyHandler.idl142
-rw-r--r--dom/ipc/ContentChild.cpp248
-rw-r--r--dom/ipc/ContentChild.h21
-rw-r--r--dom/ipc/ContentParent.cpp199
-rw-r--r--dom/ipc/ContentParent.h11
-rw-r--r--dom/ipc/ContentProcess.cpp113
-rw-r--r--dom/ipc/ContentProcess.h8
-rw-r--r--dom/ipc/TabContext.cpp7
-rw-r--r--dom/ipc/moz.build13
-rw-r--r--dom/ipc/tests/test_cpow_cookies.html3
-rw-r--r--dom/jsurl/nsJSProtocolHandler.cpp49
-rw-r--r--dom/media/AudioStream.cpp4
-rw-r--r--dom/media/Benchmark.cpp2
-rw-r--r--dom/media/CubebUtils.cpp27
-rw-r--r--dom/media/CubebUtils.h3
-rwxr-xr-xdom/media/DOMMediaStream.cpp102
-rw-r--r--dom/media/DOMMediaStream.h11
-rw-r--r--dom/media/GraphDriver.cpp4
-rw-r--r--dom/media/MediaData.cpp53
-rw-r--r--dom/media/MediaManager.cpp25
-rw-r--r--dom/media/MediaPermissionGonk.cpp522
-rw-r--r--dom/media/MediaPermissionGonk.h39
-rw-r--r--dom/media/MediaStreamTrack.cpp12
-rw-r--r--dom/media/PeerConnection.js1
-rw-r--r--dom/media/android/AndroidMediaPluginHost.cpp8
-rw-r--r--dom/media/encoder/OpusTrackEncoder.cpp5
-rw-r--r--dom/media/encoder/TrackEncoder.cpp5
-rw-r--r--dom/media/encoder/fmp4_muxer/AMRBox.cpp84
-rw-r--r--dom/media/encoder/fmp4_muxer/AMRBox.h50
-rw-r--r--dom/media/encoder/fmp4_muxer/AVCBox.cpp87
-rw-r--r--dom/media/encoder/fmp4_muxer/AVCBox.h59
-rw-r--r--dom/media/encoder/fmp4_muxer/EVRCBox.cpp84
-rw-r--r--dom/media/encoder/fmp4_muxer/EVRCBox.h50
-rw-r--r--dom/media/encoder/fmp4_muxer/ISOControl.cpp415
-rw-r--r--dom/media/encoder/fmp4_muxer/ISOControl.h250
-rw-r--r--dom/media/encoder/fmp4_muxer/ISOMediaBoxes.cpp1550
-rw-r--r--dom/media/encoder/fmp4_muxer/ISOMediaBoxes.h781
-rw-r--r--dom/media/encoder/fmp4_muxer/ISOMediaWriter.cpp234
-rw-r--r--dom/media/encoder/fmp4_muxer/ISOMediaWriter.h108
-rw-r--r--dom/media/encoder/fmp4_muxer/ISOTrackMetadata.h131
-rw-r--r--dom/media/encoder/fmp4_muxer/MP4ESDS.cpp138
-rw-r--r--dom/media/encoder/fmp4_muxer/MP4ESDS.h87
-rw-r--r--dom/media/encoder/fmp4_muxer/MuxerOperation.h57
-rw-r--r--dom/media/encoder/moz.build13
-rw-r--r--dom/media/gmp/GMPChild.cpp131
-rw-r--r--dom/media/gmp/GMPChild.h4
-rw-r--r--dom/media/gmp/GMPLoader.cpp13
-rw-r--r--dom/media/gmp/GMPLoader.h17
-rw-r--r--dom/media/gmp/GMPParent.cpp11
-rw-r--r--dom/media/gmp/GMPProcessParent.cpp34
-rw-r--r--dom/media/gmp/GMPService.cpp11
-rw-r--r--dom/media/gmp/GMPServiceParent.cpp16
-rw-r--r--dom/media/gmp/rlz/GMPDeviceBinding.cpp8
-rw-r--r--dom/media/gmp/rlz/moz.build7
-rw-r--r--dom/media/moz.build13
-rw-r--r--dom/media/ogg/OggCodecState.cpp12
-rw-r--r--dom/media/ogg/OggWriter.cpp5
-rw-r--r--dom/media/platforms/ffmpeg/FFmpegDataDecoder.cpp6
-rw-r--r--dom/media/platforms/ffmpeg/FFmpegLibWrapper.cpp15
-rw-r--r--dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp4
-rw-r--r--dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp4
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/COPYING.LGPLv2.1504
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/avcodec.h6146
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/avfft.h118
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/vaapi.h86
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/vdpau.h176
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/version.h137
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/attributes.h167
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/avconfig.h6
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/avutil.h365
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/buffer.h291
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/channel_layout.h232
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/common.h560
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/cpu.h130
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/dict.h200
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/error.h126
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/frame.h893
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/hwcontext.h584
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/intfloat.h77
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/log.h362
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/macros.h50
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/mathematics.h242
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/mem.h700
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/pixfmt.h529
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/rational.h214
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/samplefmt.h272
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/version.h139
-rw-r--r--dom/media/platforms/ffmpeg/ffmpeg58/moz.build (renamed from dom/media/encoder/fmp4_muxer/moz.build)27
-rw-r--r--dom/media/platforms/ffmpeg/moz.build1
-rw-r--r--dom/media/platforms/gonk/GonkAudioDecoderManager.cpp268
-rw-r--r--dom/media/platforms/gonk/GonkAudioDecoderManager.h59
-rw-r--r--dom/media/platforms/gonk/GonkDecoderModule.cpp63
-rw-r--r--dom/media/platforms/gonk/GonkDecoderModule.h37
-rw-r--r--dom/media/platforms/gonk/GonkMediaDataDecoder.cpp385
-rw-r--r--dom/media/platforms/gonk/GonkMediaDataDecoder.h214
-rw-r--r--dom/media/platforms/gonk/GonkVideoDecoderManager.cpp772
-rw-r--r--dom/media/platforms/gonk/GonkVideoDecoderManager.h149
-rw-r--r--dom/media/platforms/gonk/moz.build39
-rw-r--r--dom/media/platforms/moz.build4
-rw-r--r--dom/media/platforms/omx/GonkOmxPlatformLayer.cpp667
-rw-r--r--dom/media/platforms/omx/GonkOmxPlatformLayer.h205
-rw-r--r--dom/media/platforms/omx/OmxPlatformLayer.cpp5
-rw-r--r--dom/media/platforms/omx/moz.build23
-rw-r--r--dom/media/standalone/moz.build2
-rw-r--r--dom/media/systemservices/CamerasChild.cpp15
-rw-r--r--dom/media/systemservices/CamerasChild.h11
-rw-r--r--dom/media/systemservices/MediaSystemResourceService.cpp17
-rw-r--r--dom/media/systemservices/moz.build10
-rw-r--r--dom/media/webrtc/MediaEngine.h5
-rw-r--r--dom/media/webrtc/MediaEngineCameraVideoSource.cpp2
-rw-r--r--dom/media/webrtc/MediaEngineDefault.cpp2
-rw-r--r--dom/media/webrtc/MediaEngineWebRTC.cpp2
-rw-r--r--dom/media/webrtc/MediaEngineWebRTCAudio.cpp4
-rw-r--r--dom/moz.build12
-rw-r--r--dom/network/EthernetManager.js655
-rw-r--r--dom/network/EthernetManager.manifest2
-rw-r--r--dom/network/NetUtils.cpp200
-rw-r--r--dom/network/NetUtils.h75
-rw-r--r--dom/network/NetworkStatsDB.jsm1285
-rw-r--r--dom/network/NetworkStatsManager.js388
-rw-r--r--dom/network/NetworkStatsManager.manifest14
-rw-r--r--dom/network/NetworkStatsService.jsm1171
-rw-r--r--dom/network/NetworkStatsServiceProxy.js90
-rw-r--r--dom/network/NetworkStatsServiceProxy.manifest2
-rw-r--r--dom/network/TCPSocket.cpp72
-rw-r--r--dom/network/TCPSocket.h17
-rw-r--r--dom/network/interfaces/moz.build6
-rw-r--r--dom/network/interfaces/nsIEthernetManager.idl137
-rw-r--r--dom/network/interfaces/nsINetworkStatsServiceProxy.idl64
-rw-r--r--dom/network/moz.build22
-rw-r--r--dom/notification/DesktopNotification.h4
-rwxr-xr-xdom/performance/Performance.cpp53
-rw-r--r--dom/performance/Performance.h36
-rw-r--r--dom/performance/PerformanceEntry.h21
-rw-r--r--dom/performance/PerformanceMainThread.cpp99
-rw-r--r--dom/performance/PerformanceMainThread.h21
-rw-r--r--dom/performance/PerformanceNavigationTiming.cpp96
-rw-r--r--dom/performance/PerformanceNavigationTiming.h71
-rw-r--r--dom/performance/PerformanceObserver.cpp14
-rw-r--r--dom/performance/PerformanceObserverEntryList.cpp15
-rw-r--r--dom/performance/PerformanceResourceTiming.cpp49
-rw-r--r--dom/performance/PerformanceResourceTiming.h12
-rw-r--r--dom/performance/PerformanceService.cpp46
-rw-r--r--dom/performance/PerformanceService.h48
-rwxr-xr-xdom/performance/PerformanceTiming.cpp71
-rwxr-xr-xdom/performance/PerformanceTiming.h18
-rw-r--r--dom/performance/PerformanceWorker.cpp35
-rw-r--r--dom/performance/PerformanceWorker.h14
-rw-r--r--dom/performance/moz.build4
-rw-r--r--dom/performance/tests/mochitest.ini3
-rw-r--r--dom/performance/tests/performance_observer.html74
-rw-r--r--dom/performance/tests/test_performance_observer.html52
-rw-r--r--dom/performance/tests/test_performance_user_timing.js21
-rw-r--r--dom/performance/tests/test_timeOrigin.html68
-rw-r--r--dom/performance/tests/test_worker_observer.html13
-rw-r--r--dom/performance/tests/worker_performance_observer.html32
-rw-r--r--dom/permission/tests/mochitest.ini1
-rw-r--r--dom/plugins/base/PluginPRLibrary.cpp6
-rw-r--r--dom/plugins/base/PluginPRLibrary.h2
-rw-r--r--dom/plugins/base/nsNPAPIPlugin.cpp1
-rw-r--r--dom/plugins/base/nsPluginInstanceOwner.cpp28
-rw-r--r--dom/plugins/base/nsPluginTags.cpp25
-rw-r--r--dom/plugins/base/nsPluginTags.h1
-rw-r--r--dom/plugins/ipc/PluginLibrary.h2
-rwxr-xr-xdom/plugins/ipc/PluginModuleParent.cpp4
-rw-r--r--dom/plugins/ipc/PluginModuleParent.h4
-rw-r--r--dom/plugins/ipc/PluginProcessChild.cpp10
-rw-r--r--dom/plugins/ipc/PluginProcessParent.cpp85
-rw-r--r--dom/plugins/ipc/moz.build6
-rw-r--r--dom/plugins/test/mochitest/test_bug813906.html22
-rw-r--r--dom/plugins/test/mochitest/test_pluginstream_err.html8
-rw-r--r--dom/presentation/PresentationSessionInfo.cpp49
-rw-r--r--dom/presentation/provider/PresentationDeviceProviderModule.cpp5
-rw-r--r--dom/secureelement/SEUtils.jsm116
-rw-r--r--dom/secureelement/gonk/ACEService.js139
-rw-r--r--dom/secureelement/gonk/ACEService.manifest2
-rw-r--r--dom/secureelement/gonk/GPAccessRulesManager.js436
-rw-r--r--dom/secureelement/gonk/GPAccessRulesManager.manifest2
-rw-r--r--dom/secureelement/gonk/SecureElement.js514
-rw-r--r--dom/secureelement/gonk/SecureElement.manifest18
-rw-r--r--dom/secureelement/gonk/UiccConnector.js360
-rw-r--r--dom/secureelement/gonk/UiccConnector.manifest17
-rw-r--r--dom/secureelement/gonk/gp_consts.js62
-rw-r--r--dom/secureelement/gonk/nsIAccessControlEnforcer.idl32
-rw-r--r--dom/secureelement/gonk/nsIAccessRulesManager.idl50
-rw-r--r--dom/secureelement/gonk/nsISecureElementConnector.idl124
-rw-r--r--dom/secureelement/gonk/se_consts.js68
-rw-r--r--dom/secureelement/moz.build24
-rw-r--r--dom/security/nsCSPContext.cpp9
-rw-r--r--dom/security/nsContentSecurityManager.cpp74
-rw-r--r--dom/settings/SettingsService.js358
-rw-r--r--dom/settings/SettingsService.manifest5
-rw-r--r--dom/settings/moz.build6
-rw-r--r--dom/settings/tests/chrome.ini6
-rw-r--r--dom/settings/tests/test_settings_service.js138
-rw-r--r--dom/settings/tests/test_settings_service.xul19
-rw-r--r--dom/settings/tests/test_settings_service_callback.js47
-rw-r--r--dom/settings/tests/test_settings_service_callback.xul19
-rw-r--r--dom/speakermanager/SpeakerManager.cpp217
-rw-r--r--dom/speakermanager/SpeakerManager.h66
-rw-r--r--dom/speakermanager/SpeakerManagerService.cpp224
-rw-r--r--dom/speakermanager/SpeakerManagerService.h79
-rw-r--r--dom/speakermanager/SpeakerManagerServiceChild.cpp121
-rw-r--r--dom/speakermanager/SpeakerManagerServiceChild.h44
-rw-r--r--dom/speakermanager/moz.build23
-rw-r--r--dom/speakermanager/tests/mochitest.ini3
-rw-r--r--dom/speakermanager/tests/test_speakermanager.html53
-rw-r--r--dom/system/OSFileConstants.cpp11
-rw-r--r--dom/system/gonk/AudioChannelManager.cpp181
-rw-r--r--dom/system/gonk/AudioChannelManager.h87
-rw-r--r--dom/system/gonk/AudioManager.cpp1412
-rw-r--r--dom/system/gonk/AudioManager.h180
-rw-r--r--dom/system/gonk/AutoMounter.cpp1496
-rw-r--r--dom/system/gonk/AutoMounter.h101
-rw-r--r--dom/system/gonk/AutoMounterSetting.cpp284
-rw-r--r--dom/system/gonk/AutoMounterSetting.h38
-rw-r--r--dom/system/gonk/DataCallInterfaceService.js276
-rw-r--r--dom/system/gonk/DataCallInterfaceService.manifest6
-rw-r--r--dom/system/gonk/DataCallManager.js1726
-rw-r--r--dom/system/gonk/DataCallManager.manifest4
-rw-r--r--dom/system/gonk/GeolocationUtil.cpp28
-rw-r--r--dom/system/gonk/GeolocationUtil.h13
-rw-r--r--dom/system/gonk/GonkGPSGeolocationProvider.cpp706
-rw-r--r--dom/system/gonk/GonkGPSGeolocationProvider.h103
-rw-r--r--dom/system/gonk/MozMtpCommon.h56
-rw-r--r--dom/system/gonk/MozMtpDatabase.cpp1542
-rw-r--r--dom/system/gonk/MozMtpDatabase.h288
-rw-r--r--dom/system/gonk/MozMtpServer.cpp263
-rw-r--r--dom/system/gonk/MozMtpServer.h61
-rw-r--r--dom/system/gonk/MozMtpStorage.cpp135
-rw-r--r--dom/system/gonk/MozMtpStorage.h47
-rw-r--r--dom/system/gonk/NetIdManager.cpp68
-rw-r--r--dom/system/gonk/NetIdManager.h45
-rw-r--r--dom/system/gonk/NetworkInterfaceListService.js110
-rw-r--r--dom/system/gonk/NetworkInterfaceListService.manifest17
-rw-r--r--dom/system/gonk/NetworkManager.js1219
-rw-r--r--dom/system/gonk/NetworkManager.manifest3
-rw-r--r--dom/system/gonk/NetworkService.js862
-rw-r--r--dom/system/gonk/NetworkService.manifest3
-rw-r--r--dom/system/gonk/NetworkUtils.cpp2973
-rw-r--r--dom/system/gonk/NetworkUtils.h498
-rw-r--r--dom/system/gonk/NetworkWorker.cpp271
-rw-r--r--dom/system/gonk/NetworkWorker.h37
-rw-r--r--dom/system/gonk/OpenFileFinder.cpp251
-rw-r--r--dom/system/gonk/OpenFileFinder.h63
-rw-r--r--dom/system/gonk/RILSystemMessenger.jsm338
-rw-r--r--dom/system/gonk/RILSystemMessengerHelper.js169
-rw-r--r--dom/system/gonk/RILSystemMessengerHelper.manifest6
-rw-r--r--dom/system/gonk/RadioInterfaceLayer.js1324
-rw-r--r--dom/system/gonk/RadioInterfaceLayer.manifest18
-rw-r--r--dom/system/gonk/SystemProperty.cpp98
-rw-r--r--dom/system/gonk/SystemProperty.h39
-rw-r--r--dom/system/gonk/SystemWorkerManager.cpp214
-rw-r--r--dom/system/gonk/SystemWorkerManager.h75
-rw-r--r--dom/system/gonk/TetheringService.js891
-rw-r--r--dom/system/gonk/TetheringService.manifest4
-rw-r--r--dom/system/gonk/TimeZoneSettingObserver.cpp239
-rw-r--r--dom/system/gonk/TimeZoneSettingObserver.h20
-rw-r--r--dom/system/gonk/Volume.cpp596
-rw-r--r--dom/system/gonk/Volume.h157
-rw-r--r--dom/system/gonk/VolumeCommand.cpp85
-rw-r--r--dom/system/gonk/VolumeCommand.h204
-rw-r--r--dom/system/gonk/VolumeManager.cpp591
-rw-r--r--dom/system/gonk/VolumeManager.h192
-rw-r--r--dom/system/gonk/VolumeManagerLog.h27
-rw-r--r--dom/system/gonk/VolumeServiceIOThread.cpp82
-rw-r--r--dom/system/gonk/VolumeServiceIOThread.h49
-rw-r--r--dom/system/gonk/VolumeServiceTest.cpp202
-rw-r--r--dom/system/gonk/VolumeServiceTest.h19
-rw-r--r--dom/system/gonk/android_audio/AudioSystem.h1134
-rw-r--r--dom/system/gonk/android_audio/AudioTrack.h489
-rw-r--r--dom/system/gonk/android_audio/EffectApi.h798
-rw-r--r--dom/system/gonk/android_audio/IAudioFlinger.h184
-rw-r--r--dom/system/gonk/android_audio/IAudioFlingerClient.h55
-rw-r--r--dom/system/gonk/android_audio/IAudioRecord.h68
-rw-r--r--dom/system/gonk/android_audio/IAudioTrack.h89
-rw-r--r--dom/system/gonk/android_audio/IEffect.h60
-rw-r--r--dom/system/gonk/android_audio/IEffectClient.h54
-rw-r--r--dom/system/gonk/moz.build107
-rw-r--r--dom/system/gonk/mozstumbler/MozStumbler.cpp426
-rw-r--r--dom/system/gonk/mozstumbler/MozStumbler.h47
-rw-r--r--dom/system/gonk/mozstumbler/StumblerLogging.cpp13
-rw-r--r--dom/system/gonk/mozstumbler/StumblerLogging.h18
-rw-r--r--dom/system/gonk/mozstumbler/UploadStumbleRunnable.cpp151
-rw-r--r--dom/system/gonk/mozstumbler/UploadStumbleRunnable.h46
-rw-r--r--dom/system/gonk/mozstumbler/WriteStumbleOnThread.cpp321
-rw-r--r--dom/system/gonk/mozstumbler/WriteStumbleOnThread.h91
-rw-r--r--dom/system/gonk/nsIAudioManager.idl58
-rw-r--r--dom/system/gonk/nsIDataCallInterfaceService.idl268
-rw-r--r--dom/system/gonk/nsIDataCallManager.idl81
-rw-r--r--dom/system/gonk/nsIGonkDataCallInterfaceService.idl18
-rw-r--r--dom/system/gonk/nsINetworkInterface.idl108
-rw-r--r--dom/system/gonk/nsINetworkInterfaceListService.idl40
-rw-r--r--dom/system/gonk/nsINetworkManager.idl135
-rw-r--r--dom/system/gonk/nsINetworkService.idl619
-rw-r--r--dom/system/gonk/nsINetworkWorker.idl18
-rw-r--r--dom/system/gonk/nsIRadioInterfaceLayer.idl53
-rw-r--r--dom/system/gonk/nsISystemWorkerManager.idl16
-rw-r--r--dom/system/gonk/nsITetheringService.idl39
-rw-r--r--dom/system/gonk/nsIVolume.idl114
-rw-r--r--dom/system/gonk/nsIVolumeMountLock.idl12
-rw-r--r--dom/system/gonk/nsIVolumeService.idl36
-rw-r--r--dom/system/gonk/nsIVolumeStat.idl12
-rw-r--r--dom/system/gonk/nsIWorkerHolder.idl11
-rw-r--r--dom/system/gonk/nsVolume.cpp467
-rw-r--r--dom/system/gonk/nsVolume.h114
-rw-r--r--dom/system/gonk/nsVolumeMountLock.cpp171
-rw-r--r--dom/system/gonk/nsVolumeMountLock.h56
-rw-r--r--dom/system/gonk/nsVolumeService.cpp553
-rw-r--r--dom/system/gonk/nsVolumeService.h78
-rw-r--r--dom/system/gonk/nsVolumeStat.cpp33
-rw-r--r--dom/system/gonk/nsVolumeStat.h33
-rw-r--r--dom/system/gonk/ril_consts.js3338
-rw-r--r--dom/system/gonk/ril_worker.js15206
-rw-r--r--dom/system/gonk/ril_worker_buf_object.js168
-rw-r--r--dom/system/gonk/ril_worker_telephony_request_queue.js157
-rw-r--r--dom/system/gonk/systemlibs.js201
-rw-r--r--dom/system/gonk/tests/header_helpers.js217
-rw-r--r--dom/system/gonk/tests/marionette/head.js345
-rw-r--r--dom/system/gonk/tests/marionette/manifest.ini19
-rw-r--r--dom/system/gonk/tests/marionette/ril_jshint/README.md9
-rw-r--r--dom/system/gonk/tests/marionette/ril_jshint/jshint.js11096
-rw-r--r--dom/system/gonk/tests/marionette/ril_jshint/jshintrc118
-rw-r--r--dom/system/gonk/tests/marionette/test_all_network_info.js106
-rw-r--r--dom/system/gonk/tests/marionette/test_data_connection.js70
-rw-r--r--dom/system/gonk/tests/marionette/test_data_connection_proxy.js99
-rw-r--r--dom/system/gonk/tests/marionette/test_dsds_numRadioInterfaces.js43
-rw-r--r--dom/system/gonk/tests/marionette/test_fakevolume.js25
-rw-r--r--dom/system/gonk/tests/marionette/test_geolocation.js117
-rw-r--r--dom/system/gonk/tests/marionette/test_multiple_data_connection.js89
-rw-r--r--dom/system/gonk/tests/marionette/test_network_active_changed.js52
-rw-r--r--dom/system/gonk/tests/marionette/test_network_interface_list_service.js95
-rw-r--r--dom/system/gonk/tests/marionette/test_network_interface_mtu.js100
-rw-r--r--dom/system/gonk/tests/marionette/test_ril_code_quality.py371
-rw-r--r--dom/system/gonk/tests/marionette/test_screen_state.js47
-rw-r--r--dom/system/gonk/tests/marionette/test_timezone_changes.js135
-rw-r--r--dom/system/gonk/tests/test_ril_system_messenger.js1187
-rw-r--r--dom/system/gonk/tests/test_ril_worker_barring_password.js61
-rw-r--r--dom/system/gonk/tests/test_ril_worker_buf.js187
-rw-r--r--dom/system/gonk/tests/test_ril_worker_cdma_info_rec.js234
-rw-r--r--dom/system/gonk/tests/test_ril_worker_cellbroadcast_config.js470
-rw-r--r--dom/system/gonk/tests/test_ril_worker_cellbroadcast_gsm.js230
-rw-r--r--dom/system/gonk/tests/test_ril_worker_cellbroadcast_umts.js105
-rw-r--r--dom/system/gonk/tests/test_ril_worker_cf.js126
-rw-r--r--dom/system/gonk/tests/test_ril_worker_clip.js59
-rw-r--r--dom/system/gonk/tests/test_ril_worker_clir.js122
-rw-r--r--dom/system/gonk/tests/test_ril_worker_cw.js104
-rw-r--r--dom/system/gonk/tests/test_ril_worker_ecm.js168
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_BerTlvHelper.js87
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_CardLock.js282
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_CardState.js210
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_GsmPDUHelper.js79
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_ICCContactHelper.js1042
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_ICCIOHelper.js173
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_ICCPDUHelper.js652
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_ICCRecordHelper.js1080
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_ICCUtilsHelper.js326
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_IconLoader.js771
-rw-r--r--dom/system/gonk/tests/test_ril_worker_icc_SimRecordHelper.js1648
-rw-r--r--dom/system/gonk/tests/test_ril_worker_ruim.js328
-rw-r--r--dom/system/gonk/tests/test_ril_worker_sms.js273
-rw-r--r--dom/system/gonk/tests/test_ril_worker_sms_cdma.js298
-rw-r--r--dom/system/gonk/tests/test_ril_worker_sms_cdmapduhelper.js210
-rw-r--r--dom/system/gonk/tests/test_ril_worker_sms_gsmpduhelper.js282
-rw-r--r--dom/system/gonk/tests/test_ril_worker_sms_nl_tables.js77
-rw-r--r--dom/system/gonk/tests/test_ril_worker_sms_segment_info.js115
-rw-r--r--dom/system/gonk/tests/test_ril_worker_smsc_address.js112
-rw-r--r--dom/system/gonk/tests/test_ril_worker_ssn.js104
-rw-r--r--dom/system/gonk/tests/test_ril_worker_stk.js1698
-rw-r--r--dom/system/gonk/tests/test_ril_worker_voiceprivacy.js94
-rw-r--r--dom/system/gonk/tests/xpcshell.ini43
-rw-r--r--dom/system/gonk/worker_buf.js623
-rw-r--r--dom/system/moz.build2
-rw-r--r--dom/tests/mochitest/bugs/test_resize_move_windows.html5
-rw-r--r--dom/tests/mochitest/general/test_interfaces.html8
-rw-r--r--dom/tethering/TetheringManager.js92
-rw-r--r--dom/tethering/TetheringManager.manifest4
-rw-r--r--dom/tethering/moz.build12
-rw-r--r--dom/tethering/tests/marionette/head.js768
-rw-r--r--dom/tethering/tests/marionette/manifest.ini7
-rw-r--r--dom/tethering/tests/marionette/test_wifi_tethering_dun.js37
-rw-r--r--dom/tethering/tests/marionette/test_wifi_tethering_enabled.js12
-rw-r--r--dom/webidl/EventHandler.webidl9
-rw-r--r--dom/webidl/MozApplicationEvent.webidl16
-rw-r--r--dom/webidl/MozNetworkStats.webidl73
-rw-r--r--dom/webidl/MozNetworkStatsAlarm.webidl13
-rw-r--r--dom/webidl/MozNetworkStatsData.webidl12
-rw-r--r--dom/webidl/MozNetworkStatsInterface.webidl26
-rw-r--r--dom/webidl/MozNetworkStatsManager.webidl96
-rw-r--r--dom/webidl/MozSpeakerManager.webidl18
-rw-r--r--dom/webidl/MozWifiCapabilities.webidl46
-rw-r--r--dom/webidl/MozWifiConnectionInfoEvent.webidl43
-rw-r--r--dom/webidl/MozWifiManager.webidl347
-rw-r--r--dom/webidl/MozWifiP2pManager.webidl147
-rw-r--r--dom/webidl/MozWifiP2pStatusChangeEvent.webidl20
-rw-r--r--dom/webidl/MozWifiStationInfoEvent.webidl19
-rw-r--r--dom/webidl/MozWifiStatusChangeEvent.webidl27
-rw-r--r--dom/webidl/Performance.webidl3
-rw-r--r--dom/webidl/PerformanceNavigationTiming.webidl33
-rw-r--r--dom/webidl/PerformanceObserver.webidl1
-rw-r--r--dom/webidl/PerformanceResourceTiming.webidl8
-rw-r--r--dom/webidl/PerformanceTiming.webidl6
-rw-r--r--dom/webidl/Window.webidl8
-rw-r--r--dom/webidl/moz.build36
-rw-r--r--dom/wifi/DOMWifiManager.js543
-rw-r--r--dom/wifi/DOMWifiManager.manifest18
-rw-r--r--dom/wifi/DOMWifiP2pManager.js328
-rw-r--r--dom/wifi/DOMWifiP2pManager.manifest6
-rw-r--r--dom/wifi/StateMachine.jsm205
-rw-r--r--dom/wifi/WifiCertService.cpp536
-rw-r--r--dom/wifi/WifiCertService.h40
-rw-r--r--dom/wifi/WifiCommand.jsm594
-rw-r--r--dom/wifi/WifiHotspotUtils.cpp188
-rw-r--r--dom/wifi/WifiHotspotUtils.h46
-rw-r--r--dom/wifi/WifiNetUtil.jsm154
-rw-r--r--dom/wifi/WifiP2pManager.jsm1649
-rw-r--r--dom/wifi/WifiP2pWorkerObserver.jsm319
-rw-r--r--dom/wifi/WifiProxyService.cpp357
-rw-r--r--dom/wifi/WifiProxyService.h49
-rw-r--r--dom/wifi/WifiUtils.cpp521
-rw-r--r--dom/wifi/WifiUtils.h107
-rw-r--r--dom/wifi/WifiWorker.h9
-rw-r--r--dom/wifi/WifiWorker.js3928
-rw-r--r--dom/wifi/WifiWorker.manifest1
-rw-r--r--dom/wifi/moz.build41
-rw-r--r--dom/wifi/nsIWifi.idl60
-rw-r--r--dom/wifi/nsIWifiCertService.idl54
-rw-r--r--dom/wifi/nsIWifiService.idl22
-rw-r--r--dom/wifi/test/marionette/head.js1486
-rw-r--r--dom/wifi/test/marionette/manifest.ini22
-rw-r--r--dom/wifi/test/marionette/test_wifi_associate.js35
-rw-r--r--dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_PEAP.js623
-rw-r--r--dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_TLS.js622
-rw-r--r--dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_TTLS.js623
-rw-r--r--dom/wifi/test/marionette/test_wifi_associate_wo_connect.js55
-rw-r--r--dom/wifi/test/marionette/test_wifi_auto_connect.js44
-rw-r--r--dom/wifi/test/marionette/test_wifi_enable.js11
-rw-r--r--dom/wifi/test/marionette/test_wifi_enable_api.js13
-rw-r--r--dom/wifi/test/marionette/test_wifi_manage_pkcs12_certificate.js338
-rw-r--r--dom/wifi/test/marionette/test_wifi_manage_server_certificate.js106
-rw-r--r--dom/wifi/test/marionette/test_wifi_manage_user_certificate.js34
-rw-r--r--dom/wifi/test/marionette/test_wifi_scan.js43
-rw-r--r--dom/wifi/test/marionette/test_wifi_static_ip.js65
-rw-r--r--dom/wifi/test/marionette/test_wifi_tethering_wifi_active.js74
-rw-r--r--dom/wifi/test/marionette/test_wifi_tethering_wifi_disabled.js11
-rw-r--r--dom/wifi/test/marionette/test_wifi_tethering_wifi_inactive.js21
-rw-r--r--dom/workers/ServiceWorkerEvents.cpp10
-rw-r--r--dom/workers/ServiceWorkerPrivate.cpp45
-rw-r--r--dom/workers/ServiceWorkerPrivate.h1
-rw-r--r--dom/workers/WorkerPrivate.cpp14
-rw-r--r--dom/workers/WorkerPrivate.h13
-rw-r--r--dom/workers/test/serviceworkers/chrome.ini3
-rw-r--r--dom/workers/test/serviceworkers/test_devtools_serviceworker_interception.html168
-rw-r--r--dom/workers/test/serviceworkers/test_serviceworker_interfaces.js6
-rw-r--r--dom/workers/test/test_worker_interfaces.js6
-rw-r--r--dom/xhr/tests/mochitest.ini7
-rw-r--r--dom/xslt/xpath/txXPCOMExtensionFunction.cpp2
-rw-r--r--editor/libeditor/tests/browser.ini4
-rw-r--r--editor/libeditor/tests/bug527935.html2
-rw-r--r--editor/libeditor/tests/bug527935_2.html1
-rw-r--r--editor/libeditor/tests/file_bug635636_2.html1
-rw-r--r--editor/libeditor/tests/file_bug966155.html1
-rw-r--r--editor/libeditor/tests/file_bug966552.html1
-rw-r--r--editor/libeditor/tests/test_bug966155.html15
-rw-r--r--editor/libeditor/tests/test_bug966552.html13
-rw-r--r--embedding/browser/nsIWebBrowserChrome3.idl9
-rw-r--r--embedding/browser/nsWebBrowser.cpp5
-rw-r--r--embedding/components/windowwatcher/nsWindowWatcher.cpp7
-rw-r--r--extensions/cookie/nsPermissionManager.cpp12
-rw-r--r--gfx/cairo/cairo/src/cairo-mutex-impl-private.h23
-rw-r--r--gfx/gl/GLContextProviderEGL.cpp2
-rw-r--r--gfx/gl/GLLibraryEGL.cpp8
-rw-r--r--gfx/gl/GLLibraryEGL.h20
-rw-r--r--gfx/layers/Compositor.cpp4
-rw-r--r--gfx/layers/apz/src/APZCTreeManager.cpp1
-rw-r--r--gfx/layers/ipc/LayerTransactionChild.cpp9
-rw-r--r--gfx/skia/skia/src/core/SkMask.cpp7
-rw-r--r--gfx/skia/skia/src/gpu/GrBufferAllocPool.cpp5
-rw-r--r--gfx/skia/skia/src/gpu/batches/GrAAHairLinePathRenderer.cpp9
-rw-r--r--gfx/tests/mochitest/test_acceleration.html2
-rw-r--r--gfx/thebes/gfxAndroidPlatform.cpp22
-rw-r--r--gfx/thebes/gfxFontConstants.h3
-rw-r--r--gfx/thebes/gfxFontFamilyList.h1
-rw-r--r--gfx/thebes/gfxHarfBuzzShaper.cpp30
-rw-r--r--gfx/thebes/gfxPlatform.cpp9
-rw-r--r--gfx/thebes/gfxPlatformFontList.cpp65
-rw-r--r--gfx/thebes/gfxPlatformFontList.h11
-rw-r--r--gfx/thebes/gfxPlatformGtk.cpp20
-rw-r--r--gfx/thebes/gfxPlatformMac.cpp23
-rw-r--r--gfx/thebes/gfxTextRun.cpp20
-rw-r--r--gfx/thebes/gfxTextRun.h3
-rwxr-xr-xgfx/thebes/gfxWindowsPlatform.cpp26
-rw-r--r--gfx/thebes/moz.build10
-rw-r--r--hal/Hal.cpp6
-rw-r--r--hal/gonk/GonkDiskSpaceWatcher.cpp324
-rw-r--r--hal/gonk/GonkHal.cpp2045
-rw-r--r--hal/gonk/GonkSensor.cpp861
-rw-r--r--hal/gonk/GonkSensorsHelpers.cpp112
-rw-r--r--hal/gonk/GonkSensorsHelpers.h226
-rw-r--r--hal/gonk/GonkSensorsInterface.cpp494
-rw-r--r--hal/gonk/GonkSensorsInterface.h191
-rw-r--r--hal/gonk/GonkSensorsPollInterface.cpp431
-rw-r--r--hal/gonk/GonkSensorsPollInterface.h340
-rw-r--r--hal/gonk/GonkSensorsRegistryInterface.cpp213
-rw-r--r--hal/gonk/GonkSensorsRegistryInterface.h182
-rw-r--r--hal/gonk/GonkSwitch.cpp479
-rw-r--r--hal/gonk/SensorsTypes.h140
-rw-r--r--hal/gonk/SystemService.cpp131
-rw-r--r--hal/gonk/UeventPoller.cpp312
-rw-r--r--hal/gonk/UeventPoller.h49
-rw-r--r--hal/gonk/fanotify.h118
-rw-r--r--hal/gonk/nsIRecoveryService.idl39
-rw-r--r--hal/gonk/tavarua.h484
-rw-r--r--hal/linux/LinuxPower.cpp31
-rw-r--r--hal/moz.build58
-rw-r--r--intl/lwbrk/nsJISx4051LineBreaker.cpp2
-rw-r--r--intl/unicharutil/moz.build10
-rw-r--r--intl/unicharutil/normalization_data.h5247
-rw-r--r--intl/unicharutil/nsUnicodeNormalizer.cpp742
-rw-r--r--intl/unicharutil/nsUnicodeNormalizer.h7
-rw-r--r--intl/unicharutil/nsUnicodeNormalizer_ICU.cpp98
-rw-r--r--intl/unicharutil/util/ICUUtils.cpp2
-rw-r--r--intl/unicharutil/util/ICUUtils.h4
-rw-r--r--intl/unicharutil/util/moz.build3
-rw-r--r--intl/unicharutil/util/nsUnicodeProperties.cpp184
-rw-r--r--intl/unicharutil/util/nsUnicodeProperties.h63
-rw-r--r--intl/unicharutil/util/nsUnicodePropertyData.cpp1497
-rw-r--r--intl/unicharutil/util/nsUnicodeScriptCodes.h29
-rw-r--r--intl/unicharutil/util/objs.mozbuild9
-rw-r--r--ipc/app/moz.build43
-rw-r--r--ipc/app/pie/moz.build11
-rw-r--r--ipc/chromium/moz.build2
-rw-r--r--ipc/chromium/src/base/platform_thread_posix.cc4
-rw-r--r--ipc/chromium/src/base/process_util_linux.cc45
-rw-r--r--ipc/contentproc/moz.build5
-rw-r--r--ipc/contentproc/plugin-container.cpp138
-rw-r--r--ipc/dbus/DBusHelpers.cpp5
-rw-r--r--ipc/dbus/DBusUtils.cpp5
-rw-r--r--ipc/glue/GeckoChildProcessHost.cpp269
-rw-r--r--ipc/glue/GeckoChildProcessHost.h13
-rw-r--r--ipc/glue/MessageChannel.cpp5
-rw-r--r--ipc/glue/ProtocolUtils.cpp16
-rw-r--r--ipc/glue/moz.build7
-rw-r--r--ipc/hal/DaemonRunnables.h950
-rw-r--r--ipc/hal/DaemonSocket.cpp263
-rw-r--r--ipc/hal/DaemonSocket.h63
-rw-r--r--ipc/hal/DaemonSocketConnector.cpp244
-rw-r--r--ipc/hal/DaemonSocketConnector.h61
-rw-r--r--ipc/hal/DaemonSocketConsumer.cpp33
-rw-r--r--ipc/hal/DaemonSocketConsumer.h68
-rw-r--r--ipc/hal/DaemonSocketMessageHandlers.h40
-rw-r--r--ipc/hal/DaemonSocketPDU.cpp202
-rw-r--r--ipc/hal/DaemonSocketPDU.h94
-rw-r--r--ipc/hal/DaemonSocketPDUHelpers.cpp335
-rw-r--r--ipc/hal/DaemonSocketPDUHelpers.h1283
-rw-r--r--ipc/hal/moz.build27
-rw-r--r--ipc/keystore/KeyStore.cpp986
-rw-r--r--ipc/keystore/KeyStore.h141
-rw-r--r--ipc/keystore/KeyStoreConnector.cpp239
-rw-r--r--ipc/keystore/KeyStoreConnector.h57
-rw-r--r--ipc/keystore/moz.build18
-rw-r--r--ipc/moz.build6
-rw-r--r--ipc/mscom/InterceptorLog.cpp5
-rw-r--r--ipc/netd/Netd.cpp374
-rw-r--r--ipc/netd/Netd.h81
-rw-r--r--ipc/netd/moz.build17
-rw-r--r--ipc/ril/Ril.cpp5
-rw-r--r--ipc/ril/RilConnector.cpp4
-rw-r--r--ipc/unixfd/UnixFdWatcher.cpp128
-rw-r--r--ipc/unixfd/UnixFdWatcher.h69
-rw-r--r--ipc/unixfd/UnixFileWatcher.cpp45
-rw-r--r--ipc/unixfd/UnixFileWatcher.h33
-rw-r--r--ipc/unixfd/UnixSocketWatcher.cpp136
-rw-r--r--ipc/unixfd/UnixSocketWatcher.h72
-rw-r--r--ipc/unixfd/moz.build21
-rw-r--r--ipc/unixsocket/ConnectionOrientedSocket.cpp202
-rw-r--r--ipc/unixsocket/ConnectionOrientedSocket.h122
-rw-r--r--ipc/unixsocket/DataSocket.cpp136
-rw-r--r--ipc/unixsocket/DataSocket.h145
-rw-r--r--ipc/unixsocket/ListenSocket.cpp432
-rw-r--r--ipc/unixsocket/ListenSocket.h93
-rw-r--r--ipc/unixsocket/ListenSocketConsumer.cpp20
-rw-r--r--ipc/unixsocket/ListenSocketConsumer.h46
-rw-r--r--ipc/unixsocket/SocketBase.cpp449
-rw-r--r--ipc/unixsocket/SocketBase.h585
-rw-r--r--ipc/unixsocket/StreamSocket.cpp482
-rw-r--r--ipc/unixsocket/StreamSocket.h95
-rw-r--r--ipc/unixsocket/StreamSocketConsumer.cpp20
-rw-r--r--ipc/unixsocket/StreamSocketConsumer.h60
-rw-r--r--ipc/unixsocket/UnixSocketConnector.cpp38
-rw-r--r--ipc/unixsocket/UnixSocketConnector.h102
-rw-r--r--ipc/unixsocket/moz.build31
-rw-r--r--js/public/Value.h55
-rw-r--r--js/src/aclocal.m41
-rw-r--r--js/src/builtin/Array.js8
-rw-r--r--js/src/builtin/Intl.cpp602
-rw-r--r--js/src/builtin/Intl.h4
-rw-r--r--js/src/builtin/Intl.js126
-rw-r--r--js/src/builtin/String.js6
-rw-r--r--js/src/builtin/TestingFunctions.cpp4
-rw-r--r--js/src/builtin/TypedArray.js8
-rw-r--r--js/src/gdb/moz.build2
-rw-r--r--js/src/jit/BaselineFrameInfo.h4
-rw-r--r--js/src/jit/RegisterSets.h8
-rw-r--r--js/src/jit/RematerializedFrame.cpp14
-rw-r--r--js/src/jsapi-tests/moz.build2
-rw-r--r--js/src/jsapi.h2
-rwxr-xr-xjs/src/jsdate.cpp77
-rw-r--r--js/src/jsnum.cpp206
-rw-r--r--js/src/jsnum.h8
-rw-r--r--js/src/jsprototypes.h4
-rw-r--r--js/src/jsstr.cpp43
-rw-r--r--js/src/jsstr.h8
-rwxr-xr-xjs/src/make-source-package.sh1
-rw-r--r--js/src/moz.build23
-rw-r--r--js/src/old-configure.in16
-rw-r--r--js/src/shell/js.cpp4
-rw-r--r--js/src/shell/moz.build2
-rw-r--r--js/src/threading/windows/ConditionVariable.cpp8
-rw-r--r--js/src/threading/windows/MutexImpl.cpp47
-rw-r--r--js/src/threading/windows/MutexPlatformData.h2
-rw-r--r--js/src/vm/DateTime.cpp6
-rw-r--r--js/src/vm/GlobalObject.cpp4
-rw-r--r--js/src/vm/Initialization.cpp10
-rw-r--r--js/src/vm/Runtime.cpp12
-rw-r--r--js/src/vm/Runtime.h7
-rw-r--r--js/src/vm/SelfHosting.cpp4
-rw-r--r--js/src/wasm/AsmJS.cpp10
-rw-r--r--js/xpconnect/shell/moz.build16
-rw-r--r--js/xpconnect/shell/xpcshell.cpp11
-rw-r--r--js/xpconnect/src/XPCJSContext.cpp16
-rw-r--r--js/xpconnect/src/XPCShellImpl.cpp18
-rw-r--r--js/xpconnect/src/XPCWrappedNative.cpp7
-rw-r--r--layout/base/FrameLayerBuilder.cpp10
-rw-r--r--layout/base/moz.build16
-rw-r--r--layout/base/nsBidi.cpp (renamed from layout/base/nsBidi_ICU.cpp)2
-rw-r--r--layout/base/nsBidi.h186
-rw-r--r--layout/base/nsBidi_ICU.h190
-rw-r--r--layout/base/nsBidi_noICU.cpp2089
-rw-r--r--layout/base/nsBidi_noICU.h709
-rw-r--r--layout/base/nsCSSFrameConstructor.cpp2
-rw-r--r--layout/base/nsIPresShell.h9
-rw-r--r--layout/base/nsLayoutUtils.cpp8
-rw-r--r--layout/base/nsPresShell.cpp68
-rw-r--r--layout/base/nsPresShell.h9
-rw-r--r--layout/build/moz.build5
-rw-r--r--layout/build/nsLayoutModule.cpp105
-rw-r--r--layout/build/nsLayoutStatics.cpp9
-rw-r--r--layout/forms/nsNumberControlFrame.cpp4
-rw-r--r--layout/generic/Selection.h5
-rw-r--r--layout/generic/nsGfxScrollFrame.cpp4
-rw-r--r--layout/generic/nsTextFrame.cpp30
-rw-r--r--layout/reftests/transform-3d/animate-backface-hidden.html10
-rw-r--r--layout/reftests/transform-3d/animate-preserve3d-parent.html10
-rwxr-xr-xlayout/reftests/w3c-css/submitted/check-for-references.sh2
-rw-r--r--layout/reftests/w3c-css/submitted/text3/reftest.list5
-rw-r--r--layout/reftests/w3c-css/submitted/text3/text-justify-distribute-001.html28
-rw-r--r--layout/reftests/w3c-css/submitted/text3/text-justify-inter-character-001-ref.html24
-rw-r--r--layout/reftests/w3c-css/submitted/text3/text-justify-inter-character-001.html28
-rw-r--r--layout/reftests/w3c-css/submitted/text3/text-justify-inter-word-001-ref.html25
-rw-r--r--layout/reftests/w3c-css/submitted/text3/text-justify-inter-word-001.html29
-rw-r--r--layout/reftests/w3c-css/submitted/text3/text-justify-none-001-ref.html22
-rw-r--r--layout/reftests/w3c-css/submitted/text3/text-justify-none-001.html29
-rw-r--r--layout/style/AnimationCommon.h20
-rw-r--r--layout/style/nsAnimationManager.cpp179
-rw-r--r--layout/style/nsAnimationManager.h27
-rw-r--r--layout/style/nsCSSKeywordList.h4
-rw-r--r--layout/style/nsCSSPropList.h11
-rw-r--r--layout/style/nsCSSProps.cpp11
-rw-r--r--layout/style/nsCSSProps.h1
-rw-r--r--layout/style/nsComputedDOMStyle.cpp10
-rw-r--r--layout/style/nsComputedDOMStyle.h1
-rw-r--r--layout/style/nsComputedDOMStylePropertyList.h1
-rw-r--r--layout/style/nsRuleNode.cpp7
-rw-r--r--layout/style/nsStyleConsts.h8
-rw-r--r--layout/style/nsStyleStruct.cpp3
-rw-r--r--layout/style/nsStyleStruct.h1
-rw-r--r--layout/style/nsTransitionManager.cpp113
-rw-r--r--layout/style/nsTransitionManager.h11
-rw-r--r--layout/style/test/property_database.js11
-rw-r--r--layout/style/test/test_animations.html3
-rw-r--r--layout/style/test/test_animations_event_handler_attribute.html40
-rw-r--r--layout/style/test/test_animations_event_order.html117
-rw-r--r--layout/style/test/test_animations_omta.html3
-rw-r--r--layout/tools/reftest/bootstrap.js9
-rw-r--r--layout/tools/reftest/reftest.jsm8
-rw-r--r--layout/tools/reftest/runreftest.py7
-rw-r--r--media/ffvpx/COPYING.GPLv2339
-rw-r--r--media/ffvpx/COPYING.GPLv3674
-rw-r--r--media/ffvpx/CREDITS6
-rw-r--r--media/ffvpx/Changelog1476
-rw-r--r--media/ffvpx/FILES282
-rw-r--r--media/ffvpx/INSTALL.md17
-rw-r--r--media/ffvpx/LICENSE.md114
-rw-r--r--media/ffvpx/MAINTAINERS619
-rw-r--r--media/ffvpx/README.md49
-rw-r--r--media/ffvpx/README_MCP48
-rw-r--r--media/ffvpx/README_MOZILLA39
-rw-r--r--media/ffvpx/RELEASE1
-rw-r--r--media/ffvpx/RELEASE_NOTES15
-rw-r--r--media/ffvpx/changes.patch13
-rw-r--r--media/ffvpx/compat/atomics/win32/stdatomic.h181
-rw-r--r--media/ffvpx/compat/w32pthreads.h38
-rw-r--r--media/ffvpx/config_common.h1
-rw-r--r--media/ffvpx/config_darwin32.h1570
-rw-r--r--media/ffvpx/config_darwin64.asm1754
-rw-r--r--media/ffvpx/config_darwin64.h1762
-rw-r--r--media/ffvpx/config_unix32.h1750
-rw-r--r--media/ffvpx/config_unix64.asm1752
-rw-r--r--media/ffvpx/config_unix64.h1759
-rw-r--r--media/ffvpx/config_win32.asm1752
-rw-r--r--media/ffvpx/config_win32.h1761
-rw-r--r--media/ffvpx/config_win64.asm1754
-rw-r--r--media/ffvpx/config_win64.h1760
-rw-r--r--media/ffvpx/defaults_disabled.asm1674
-rw-r--r--media/ffvpx/defaults_disabled.h1674
-rw-r--r--media/ffvpx/ffvpxcommon.mozbuild5
-rw-r--r--media/ffvpx/libavcodec/allcodecs.c81
-rw-r--r--media/ffvpx/libavcodec/avcodec.h322
-rw-r--r--media/ffvpx/libavcodec/avdct.h84
-rw-r--r--media/ffvpx/libavcodec/avpacket.c64
-rw-r--r--media/ffvpx/libavcodec/bitstream.c20
-rw-r--r--media/ffvpx/libavcodec/bitstream_filter.c185
-rw-r--r--media/ffvpx/libavcodec/bitstream_filters.c91
-rw-r--r--media/ffvpx/libavcodec/blockdsp.h3
-rw-r--r--media/ffvpx/libavcodec/bsf.c542
-rw-r--r--media/ffvpx/libavcodec/bsf_list.c3
-rw-r--r--media/ffvpx/libavcodec/bytestream.h2
-rw-r--r--media/ffvpx/libavcodec/codec_desc.c269
-rw-r--r--media/ffvpx/libavcodec/dct.h68
-rw-r--r--media/ffvpx/libavcodec/decode.c1761
-rw-r--r--media/ffvpx/libavcodec/decode.h39
-rw-r--r--media/ffvpx/libavcodec/dummy_funcs.c73
-rw-r--r--media/ffvpx/libavcodec/error_resilience.h4
-rw-r--r--media/ffvpx/libavcodec/flac.c11
-rw-r--r--media/ffvpx/libavcodec/flac.h4
-rw-r--r--media/ffvpx/libavcodec/flac_parser.c4
-rw-r--r--media/ffvpx/libavcodec/flacdec.c34
-rw-r--r--media/ffvpx/libavcodec/flacdsp.c12
-rw-r--r--media/ffvpx/libavcodec/flacdsp.h1
-rw-r--r--media/ffvpx/libavcodec/flacdsp_template.c2
-rw-r--r--media/ffvpx/libavcodec/get_bits.h20
-rw-r--r--media/ffvpx/libavcodec/golomb.h55
-rw-r--r--media/ffvpx/libavcodec/h264chroma.h3
-rw-r--r--media/ffvpx/libavcodec/hpeldsp.h2
-rw-r--r--media/ffvpx/libavcodec/hwaccel.h24
-rw-r--r--media/ffvpx/libavcodec/idctdsp.h20
-rw-r--r--media/ffvpx/libavcodec/internal.h70
-rw-r--r--media/ffvpx/libavcodec/mathops.h19
-rw-r--r--media/ffvpx/libavcodec/me_cmp.h2
-rw-r--r--media/ffvpx/libavcodec/moz.build11
-rw-r--r--media/ffvpx/libavcodec/mpegvideo.h3
-rw-r--r--media/ffvpx/libavcodec/null_bsf.c (renamed from media/ffvpx/libavutil/wchar_filename.h)40
-rw-r--r--media/ffvpx/libavcodec/options.c48
-rw-r--r--media/ffvpx/libavcodec/options_table.h594
-rw-r--r--media/ffvpx/libavcodec/parser.c7
-rw-r--r--media/ffvpx/libavcodec/pixblockdsp.h15
-rw-r--r--media/ffvpx/libavcodec/profiles.c12
-rw-r--r--media/ffvpx/libavcodec/profiles.h1
-rw-r--r--media/ffvpx/libavcodec/pthread_frame.c318
-rw-r--r--media/ffvpx/libavcodec/pthread_slice.c146
-rw-r--r--media/ffvpx/libavcodec/put_bits.h109
-rw-r--r--media/ffvpx/libavcodec/ratecontrol.h4
-rw-r--r--media/ffvpx/libavcodec/raw.c14
-rw-r--r--media/ffvpx/libavcodec/thread.h6
-rw-r--r--media/ffvpx/libavcodec/utils.c2040
-rw-r--r--media/ffvpx/libavcodec/version.h23
-rw-r--r--media/ffvpx/libavcodec/videodsp.c2
-rw-r--r--media/ffvpx/libavcodec/videodsp.h1
-rw-r--r--media/ffvpx/libavcodec/vlc.h20
-rw-r--r--media/ffvpx/libavcodec/vorbis_parser.h3
-rw-r--r--media/ffvpx/libavcodec/vp3dsp.h10
-rw-r--r--media/ffvpx/libavcodec/vp56.h12
-rw-r--r--media/ffvpx/libavcodec/vp56dsp.h18
-rw-r--r--media/ffvpx/libavcodec/vp56rac.c5
-rw-r--r--media/ffvpx/libavcodec/vp8.c158
-rw-r--r--media/ffvpx/libavcodec/vp8.h31
-rw-r--r--media/ffvpx/libavcodec/vp8_parser.c49
-rw-r--r--media/ffvpx/libavcodec/vp8dsp.c38
-rw-r--r--media/ffvpx/libavcodec/vp8dsp.h4
-rw-r--r--media/ffvpx/libavcodec/vp9.c3972
-rw-r--r--media/ffvpx/libavcodec/vp9.h142
-rw-r--r--media/ffvpx/libavcodec/vp9_mc_template.c210
-rw-r--r--media/ffvpx/libavcodec/vp9block.c1449
-rw-r--r--media/ffvpx/libavcodec/vp9data.c2247
-rw-r--r--media/ffvpx/libavcodec/vp9data.h2292
-rw-r--r--media/ffvpx/libavcodec/vp9dec.h240
-rw-r--r--media/ffvpx/libavcodec/vp9dsp.c58
-rw-r--r--media/ffvpx/libavcodec/vp9dsp.h10
-rw-r--r--media/ffvpx/libavcodec/vp9dsp_template.c63
-rw-r--r--media/ffvpx/libavcodec/vp9lpf.c202
-rw-r--r--media/ffvpx/libavcodec/vp9mvs.c364
-rw-r--r--media/ffvpx/libavcodec/vp9prob.c274
-rw-r--r--media/ffvpx/libavcodec/vp9recon.c644
-rw-r--r--media/ffvpx/libavcodec/vp9shared.h169
-rw-r--r--media/ffvpx/libavcodec/x86/constants.h1
-rw-r--r--media/ffvpx/libavcodec/x86/flacdsp_init.c4
-rw-r--r--media/ffvpx/libavcodec/x86/h264_i386.h212
-rw-r--r--media/ffvpx/libavcodec/x86/h264_intrapred.asm102
-rw-r--r--media/ffvpx/libavcodec/x86/h264_intrapred_10bit.asm77
-rw-r--r--media/ffvpx/libavcodec/x86/h264_intrapred_init.c7
-rw-r--r--media/ffvpx/libavcodec/x86/videodsp.asm2
-rw-r--r--media/ffvpx/libavcodec/x86/videodsp_init.c8
-rw-r--r--media/ffvpx/libavcodec/x86/vp8dsp.asm31
-rw-r--r--media/ffvpx/libavcodec/x86/vp8dsp_init.c21
-rw-r--r--media/ffvpx/libavcodec/x86/vp8dsp_loopfilter.asm6
-rw-r--r--media/ffvpx/libavcodec/x86/vp9dsp_init.c16
-rw-r--r--media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp.c18
-rw-r--r--media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp_template.c8
-rw-r--r--media/ffvpx/libavcodec/x86/vp9intrapred_16bpp.asm257
-rw-r--r--media/ffvpx/libavcodec/x86/vp9itxfm.asm188
-rw-r--r--media/ffvpx/libavcodec/x86/vp9mc.asm7
-rw-r--r--media/ffvpx/libavutil/atomic_gcc.h17
-rw-r--r--media/ffvpx/libavutil/atomic_suncc.h54
-rw-r--r--media/ffvpx/libavutil/attributes.h5
-rw-r--r--media/ffvpx/libavutil/avconfig.h1
-rw-r--r--media/ffvpx/libavutil/avstring.c23
-rw-r--r--media/ffvpx/libavutil/avstring.h5
-rw-r--r--media/ffvpx/libavutil/avutil.h20
-rw-r--r--media/ffvpx/libavutil/avutil.symbols11
-rw-r--r--media/ffvpx/libavutil/buffer.c96
-rw-r--r--media/ffvpx/libavutil/buffer.h7
-rw-r--r--media/ffvpx/libavutil/buffer_internal.h7
-rw-r--r--media/ffvpx/libavutil/channel_layout.c22
-rw-r--r--media/ffvpx/libavutil/channel_layout.h21
-rw-r--r--media/ffvpx/libavutil/cpu.c61
-rw-r--r--media/ffvpx/libavutil/cpu.h16
-rw-r--r--media/ffvpx/libavutil/cpu_internal.h5
-rw-r--r--media/ffvpx/libavutil/display.c73
-rw-r--r--media/ffvpx/libavutil/display.h87
-rw-r--r--media/ffvpx/libavutil/dummy_funcs.c67
-rw-r--r--media/ffvpx/libavutil/eval.c18
-rw-r--r--media/ffvpx/libavutil/ffversion.h2
-rw-r--r--media/ffvpx/libavutil/float_dsp.c9
-rw-r--r--media/ffvpx/libavutil/float_dsp.h16
-rw-r--r--media/ffvpx/libavutil/frame.c173
-rw-r--r--media/ffvpx/libavutil/frame.h130
-rw-r--r--media/ffvpx/libavutil/hwcontext.h161
-rw-r--r--media/ffvpx/libavutil/imgutils.c271
-rw-r--r--media/ffvpx/libavutil/imgutils.h70
-rw-r--r--media/ffvpx/libavutil/imgutils_internal.h30
-rw-r--r--media/ffvpx/libavutil/internal.h15
-rw-r--r--media/ffvpx/libavutil/intreadwrite.h29
-rw-r--r--media/ffvpx/libavutil/log.c6
-rw-r--r--media/ffvpx/libavutil/lzo.c205
-rw-r--r--media/ffvpx/libavutil/lzo.h66
-rw-r--r--media/ffvpx/libavutil/mathematics.c4
-rw-r--r--media/ffvpx/libavutil/mem.c36
-rw-r--r--media/ffvpx/libavutil/mem.h5
-rw-r--r--media/ffvpx/libavutil/motion_vector.h57
-rw-r--r--media/ffvpx/libavutil/moz.build3
-rw-r--r--media/ffvpx/libavutil/opt.c2025
-rw-r--r--media/ffvpx/libavutil/opt.h1
-rw-r--r--media/ffvpx/libavutil/parseutils.c28
-rw-r--r--media/ffvpx/libavutil/pixdesc.c308
-rw-r--r--media/ffvpx/libavutil/pixdesc.h36
-rw-r--r--media/ffvpx/libavutil/pixfmt.h68
-rw-r--r--media/ffvpx/libavutil/reverse.h (renamed from media/ffvpx/libavcodec/ff_options_table.h)14
-rw-r--r--media/ffvpx/libavutil/slicethread.c259
-rw-r--r--media/ffvpx/libavutil/slicethread.h52
-rw-r--r--media/ffvpx/libavutil/thread.h9
-rw-r--r--media/ffvpx/libavutil/threadmessage.c2
-rw-r--r--media/ffvpx/libavutil/time.c18
-rw-r--r--media/ffvpx/libavutil/timecode.c3
-rw-r--r--media/ffvpx/libavutil/timecode.h2
-rw-r--r--media/ffvpx/libavutil/timer.h71
-rw-r--r--media/ffvpx/libavutil/utils.c25
-rw-r--r--media/ffvpx/libavutil/version.h6
-rw-r--r--media/ffvpx/libavutil/x86/cpu.c37
-rw-r--r--media/ffvpx/libavutil/x86/cpu.h6
-rw-r--r--media/ffvpx/libavutil/x86/emms.asm4
-rw-r--r--media/ffvpx/libavutil/x86/emms.h4
-rw-r--r--media/ffvpx/libavutil/x86/float_dsp.asm86
-rw-r--r--media/ffvpx/libavutil/x86/float_dsp_init.c17
-rw-r--r--media/ffvpx/libavutil/x86/imgutils.asm53
-rw-r--r--media/ffvpx/libavutil/x86/imgutils_init.c49
-rw-r--r--media/ffvpx/libavutil/x86/moz.build2
-rw-r--r--media/ffvpx/libavutil/x86/x86inc.asm94
-rw-r--r--media/ffvpx/libavutil/x86/x86util.asm161
-rw-r--r--media/ffvpx/libavutil_visibility.h9
-rw-r--r--media/libcubeb/src/cubeb_opensl.c5
-rw-r--r--media/libcubeb/src/moz.build21
-rw-r--r--media/libpng/pnglibconf.h13
-rw-r--r--media/mtransport/common.build5
-rw-r--r--media/mtransport/gonk_addrs.cpp170
-rw-r--r--media/mtransport/test/moz.build2
-rw-r--r--media/omx-plugin/OmxPlugin.cpp26
-rw-r--r--media/omx-plugin/lib/ics/libstagefright/moz.build15
-rw-r--r--media/omx-plugin/lib/ics/libutils/moz.build7
-rw-r--r--media/omx-plugin/lib/ics/libvideoeditorplayer/moz.build7
-rw-r--r--media/omx-plugin/moz.build33
-rw-r--r--media/webrtc/moz.build35
-rw-r--r--media/webrtc/signaling/src/media-conduit/WebrtcOMXH264VideoCodec.cpp17
-rw-r--r--media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp4
-rw-r--r--media/webrtc/signaling/test/moz.build2
-rw-r--r--media/webrtc/trunk/webrtc/modules/audio_device/android/audio_device_utility_android.h2
-rw-r--r--media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.cc28
-rw-r--r--media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.h8
-rw-r--r--media/webrtc/trunk/webrtc/video_engine/include/vie_base.h4
-rw-r--r--memory/build/jemalloc_config.cpp154
-rw-r--r--memory/build/moz.build16
-rw-r--r--memory/build/mozjemalloc_compat.c182
-rw-r--r--memory/build/mozmemory_wrap.h64
-rw-r--r--memory/build/replace_malloc.c4
-rw-r--r--memory/jemalloc/README.mozilla9
-rwxr-xr-xmemory/jemalloc/helper/git8
-rw-r--r--memory/jemalloc/moz.build81
-rw-r--r--memory/jemalloc/src/.appveyor.yml28
-rw-r--r--memory/jemalloc/src/.travis.yml29
-rw-r--r--memory/jemalloc/src/COPYING27
-rw-r--r--memory/jemalloc/src/ChangeLog981
-rw-r--r--memory/jemalloc/src/INSTALL414
-rw-r--r--memory/jemalloc/src/Makefile.in506
-rw-r--r--memory/jemalloc/src/README20
-rw-r--r--memory/jemalloc/src/VERSION1
-rwxr-xr-xmemory/jemalloc/src/autogen.sh17
-rw-r--r--memory/jemalloc/src/bin/jemalloc-config.in79
-rw-r--r--memory/jemalloc/src/bin/jemalloc.sh.in9
-rw-r--r--memory/jemalloc/src/bin/jeprof.in5611
-rwxr-xr-xmemory/jemalloc/src/build-aux/config.guess1420
-rwxr-xr-xmemory/jemalloc/src/build-aux/config.sub1797
-rwxr-xr-xmemory/jemalloc/src/build-aux/install-sh250
-rw-r--r--memory/jemalloc/src/config.stamp.in0
-rwxr-xr-xmemory/jemalloc/src/configure10773
-rw-r--r--memory/jemalloc/src/configure.ac1970
-rwxr-xr-xmemory/jemalloc/src/coverage.sh16
-rw-r--r--memory/jemalloc/src/doc/html.xsl.in5
-rw-r--r--memory/jemalloc/src/doc/jemalloc.xml.in2966
-rw-r--r--memory/jemalloc/src/doc/manpages.xsl.in4
-rw-r--r--memory/jemalloc/src/doc/stylesheet.xsl10
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/arena.h1516
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/assert.h45
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/atomic.h651
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/base.h25
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/bitmap.h274
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/chunk.h96
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/chunk_dss.h37
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/chunk_mmap.h21
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/ckh.h86
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/ctl.h118
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/extent.h239
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/hash.h357
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/huge.h35
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal.h.in1288
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_decls.h75
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_defs.h.in307
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_macros.h57
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/mb.h115
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/mutex.h147
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/nstime.h48
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/pages.h27
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/ph.h345
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/internal/private_namespace.sh5
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/private_symbols.txt626
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/internal/private_unnamespace.sh5
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/prng.h207
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/prof.h547
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/internal/public_namespace.sh6
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/internal/public_unnamespace.sh6
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/ql.h81
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/qr.h69
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/quarantine.h60
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/rb.h1003
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/rtree.h366
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/internal/size_classes.sh318
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/smoothstep.h246
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/internal/smoothstep.sh115
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/spin.h51
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/stats.h201
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/tcache.h469
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/ticker.h75
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/tsd.h787
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/util.h338
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/valgrind.h114
-rw-r--r--memory/jemalloc/src/include/jemalloc/internal/witness.h266
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/jemalloc.sh28
-rw-r--r--memory/jemalloc/src/include/jemalloc/jemalloc_defs.h.in45
-rw-r--r--memory/jemalloc/src/include/jemalloc/jemalloc_macros.h.in103
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/jemalloc_mangle.sh45
-rw-r--r--memory/jemalloc/src/include/jemalloc/jemalloc_protos.h.in66
-rwxr-xr-xmemory/jemalloc/src/include/jemalloc/jemalloc_rename.sh22
-rw-r--r--memory/jemalloc/src/include/jemalloc/jemalloc_typedefs.h.in57
-rw-r--r--memory/jemalloc/src/include/msvc_compat/C99/stdbool.h20
-rw-r--r--memory/jemalloc/src/include/msvc_compat/C99/stdint.h247
-rw-r--r--memory/jemalloc/src/include/msvc_compat/strings.h59
-rw-r--r--memory/jemalloc/src/include/msvc_compat/windows_extra.h6
-rw-r--r--memory/jemalloc/src/jemalloc.pc.in12
-rw-r--r--memory/jemalloc/src/msvc/ReadMe.txt24
-rw-r--r--memory/jemalloc/src/msvc/jemalloc_vc2015.sln63
-rw-r--r--memory/jemalloc/src/msvc/projects/vc2015/jemalloc/jemalloc.vcxproj402
-rw-r--r--memory/jemalloc/src/msvc/projects/vc2015/jemalloc/jemalloc.vcxproj.filters272
-rw-r--r--memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.cpp89
-rw-r--r--memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.h3
-rw-r--r--memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.vcxproj327
-rw-r--r--memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.vcxproj.filters26
-rw-r--r--memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads_main.cpp12
-rw-r--r--memory/jemalloc/src/src/arena.c3781
-rw-r--r--memory/jemalloc/src/src/atomic.c2
-rw-r--r--memory/jemalloc/src/src/base.c177
-rw-r--r--memory/jemalloc/src/src/bitmap.c111
-rw-r--r--memory/jemalloc/src/src/chunk.c783
-rw-r--r--memory/jemalloc/src/src/chunk_dss.c237
-rw-r--r--memory/jemalloc/src/src/chunk_mmap.c78
-rw-r--r--memory/jemalloc/src/src/ckh.c569
-rw-r--r--memory/jemalloc/src/src/ctl.c2254
-rw-r--r--memory/jemalloc/src/src/extent.c53
-rw-r--r--memory/jemalloc/src/src/hash.c2
-rw-r--r--memory/jemalloc/src/src/huge.c473
-rw-r--r--memory/jemalloc/src/src/jemalloc.c2897
-rw-r--r--memory/jemalloc/src/src/mb.c2
-rw-r--r--memory/jemalloc/src/src/mutex.c158
-rw-r--r--memory/jemalloc/src/src/nstime.c194
-rw-r--r--memory/jemalloc/src/src/pages.c273
-rw-r--r--memory/jemalloc/src/src/prng.c2
-rw-r--r--memory/jemalloc/src/src/prof.c2355
-rw-r--r--memory/jemalloc/src/src/quarantine.c183
-rw-r--r--memory/jemalloc/src/src/rtree.c132
-rw-r--r--memory/jemalloc/src/src/spin.c2
-rw-r--r--memory/jemalloc/src/src/stats.c1153
-rw-r--r--memory/jemalloc/src/src/tcache.c555
-rw-r--r--memory/jemalloc/src/src/ticker.c2
-rw-r--r--memory/jemalloc/src/src/tsd.c197
-rw-r--r--memory/jemalloc/src/src/util.c666
-rw-r--r--memory/jemalloc/src/src/valgrind.c34
-rw-r--r--memory/jemalloc/src/src/witness.c136
-rw-r--r--memory/jemalloc/src/src/zone.c330
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-alti.h186
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params.h132
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params11213.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params1279.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params132049.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params19937.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params216091.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params2281.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params4253.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params44497.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params607.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-params86243.h81
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT-sse2.h157
-rw-r--r--memory/jemalloc/src/test/include/test/SFMT.h171
-rw-r--r--memory/jemalloc/src/test/include/test/btalloc.h31
-rw-r--r--memory/jemalloc/src/test/include/test/jemalloc_test.h.in163
-rw-r--r--memory/jemalloc/src/test/include/test/jemalloc_test_defs.h.in9
-rw-r--r--memory/jemalloc/src/test/include/test/math.h311
-rw-r--r--memory/jemalloc/src/test/include/test/mq.h109
-rw-r--r--memory/jemalloc/src/test/include/test/mtx.h23
-rw-r--r--memory/jemalloc/src/test/include/test/test.h333
-rw-r--r--memory/jemalloc/src/test/include/test/thd.h9
-rw-r--r--memory/jemalloc/src/test/include/test/timer.h11
-rw-r--r--memory/jemalloc/src/test/integration/MALLOCX_ARENA.c69
-rw-r--r--memory/jemalloc/src/test/integration/aligned_alloc.c139
-rw-r--r--memory/jemalloc/src/test/integration/allocated.c125
-rw-r--r--memory/jemalloc/src/test/integration/chunk.c293
-rw-r--r--memory/jemalloc/src/test/integration/mallocx.c234
-rw-r--r--memory/jemalloc/src/test/integration/overflow.c49
-rw-r--r--memory/jemalloc/src/test/integration/posix_memalign.c133
-rw-r--r--memory/jemalloc/src/test/integration/rallocx.c259
-rw-r--r--memory/jemalloc/src/test/integration/sdallocx.c57
-rw-r--r--memory/jemalloc/src/test/integration/thread_arena.c79
-rw-r--r--memory/jemalloc/src/test/integration/thread_tcache_enabled.c113
-rw-r--r--memory/jemalloc/src/test/integration/xallocx.c497
-rw-r--r--memory/jemalloc/src/test/src/SFMT.c719
-rw-r--r--memory/jemalloc/src/test/src/btalloc.c8
-rw-r--r--memory/jemalloc/src/test/src/btalloc_0.c3
-rw-r--r--memory/jemalloc/src/test/src/btalloc_1.c3
-rw-r--r--memory/jemalloc/src/test/src/math.c2
-rw-r--r--memory/jemalloc/src/test/src/mq.c29
-rw-r--r--memory/jemalloc/src/test/src/mtx.c73
-rw-r--r--memory/jemalloc/src/test/src/test.c133
-rw-r--r--memory/jemalloc/src/test/src/thd.c39
-rw-r--r--memory/jemalloc/src/test/src/timer.c60
-rw-r--r--memory/jemalloc/src/test/stress/microbench.c182
-rw-r--r--memory/jemalloc/src/test/test.sh.in53
-rw-r--r--memory/jemalloc/src/test/unit/SFMT.c1605
-rw-r--r--memory/jemalloc/src/test/unit/a0.c19
-rw-r--r--memory/jemalloc/src/test/unit/arena_reset.c159
-rw-r--r--memory/jemalloc/src/test/unit/atomic.c122
-rw-r--r--memory/jemalloc/src/test/unit/bitmap.c163
-rw-r--r--memory/jemalloc/src/test/unit/ckh.c214
-rw-r--r--memory/jemalloc/src/test/unit/decay.c374
-rw-r--r--memory/jemalloc/src/test/unit/fork.c64
-rw-r--r--memory/jemalloc/src/test/unit/hash.c185
-rw-r--r--memory/jemalloc/src/test/unit/junk.c253
-rw-r--r--memory/jemalloc/src/test/unit/junk_alloc.c3
-rw-r--r--memory/jemalloc/src/test/unit/junk_free.c3
-rw-r--r--memory/jemalloc/src/test/unit/lg_chunk.c26
-rw-r--r--memory/jemalloc/src/test/unit/mallctl.c731
-rw-r--r--memory/jemalloc/src/test/unit/math.c398
-rw-r--r--memory/jemalloc/src/test/unit/mq.c93
-rw-r--r--memory/jemalloc/src/test/unit/mtx.c60
-rw-r--r--memory/jemalloc/src/test/unit/nstime.c227
-rw-r--r--memory/jemalloc/src/test/unit/ph.c290
-rw-r--r--memory/jemalloc/src/test/unit/prng.c263
-rw-r--r--memory/jemalloc/src/test/unit/prof_accum.c91
-rw-r--r--memory/jemalloc/src/test/unit/prof_active.c136
-rw-r--r--memory/jemalloc/src/test/unit/prof_gdump.c81
-rw-r--r--memory/jemalloc/src/test/unit/prof_idump.c51
-rw-r--r--memory/jemalloc/src/test/unit/prof_reset.c303
-rw-r--r--memory/jemalloc/src/test/unit/prof_thread_name.c129
-rw-r--r--memory/jemalloc/src/test/unit/ql.c209
-rw-r--r--memory/jemalloc/src/test/unit/qr.c248
-rw-r--r--memory/jemalloc/src/test/unit/quarantine.c108
-rw-r--r--memory/jemalloc/src/test/unit/rb.c354
-rw-r--r--memory/jemalloc/src/test/unit/rtree.c151
-rw-r--r--memory/jemalloc/src/test/unit/run_quantize.c149
-rw-r--r--memory/jemalloc/src/test/unit/size_classes.c184
-rw-r--r--memory/jemalloc/src/test/unit/smoothstep.c106
-rw-r--r--memory/jemalloc/src/test/unit/stats.c447
-rw-r--r--memory/jemalloc/src/test/unit/ticker.c76
-rw-r--r--memory/jemalloc/src/test/unit/tsd.c112
-rw-r--r--memory/jemalloc/src/test/unit/util.c317
-rw-r--r--memory/jemalloc/src/test/unit/witness.c278
-rw-r--r--memory/jemalloc/src/test/unit/zero.c80
-rwxr-xr-xmemory/jemalloc/update.sh20
-rw-r--r--memory/jemalloc/upstream.info2
-rw-r--r--memory/moz.build4
-rw-r--r--memory/mozjemalloc/Makefile.in2
-rw-r--r--memory/mozjemalloc/jemalloc.c398
-rw-r--r--memory/mozjemalloc/jemalloc_types.h2
-rw-r--r--memory/mozjemalloc/linkedlist.h2
-rw-r--r--memory/mozjemalloc/moz.build19
-rw-r--r--memory/mozjemalloc/osx_zone_types.h2
-rw-r--r--memory/mozjemalloc/ql.h2
-rw-r--r--memory/mozjemalloc/qr.h2
-rw-r--r--memory/mozjemalloc/rb.h2
-rw-r--r--memory/replace/jemalloc/moz.build31
-rw-r--r--memory/replace/jemalloc/pthread_atfork.c10
-rw-r--r--memory/replace/logalloc/replay/Replay.cpp4
-rw-r--r--memory/replace/moz.build4
-rw-r--r--memory/volatile/tests/TestVolatileBuffer.cpp9
-rw-r--r--mfbt/TextUtils.h58
-rw-r--r--mfbt/moz.build1
-rw-r--r--mfbt/tests/TestTextUtils.cpp106
-rw-r--r--mfbt/tests/moz.build1
-rw-r--r--mobile/android/chrome/content/InputWidgetHelper.js2
-rw-r--r--mobile/android/installer/package-manifest.in5
-rw-r--r--modules/libpref/Preferences.cpp2
-rw-r--r--modules/libpref/init/all.js167
-rw-r--r--modules/libpref/prefapi.cpp8
-rw-r--r--moz.configure32
-rw-r--r--mozglue/build/BionicGlue.cpp17
-rw-r--r--mozglue/build/cpuacct.c61
-rw-r--r--mozglue/build/cpuacct.h41
-rw-r--r--mozglue/build/moz.build7
-rw-r--r--mozglue/misc/TimeStamp.h7
-rw-r--r--netwerk/base/Tickler.h2
-rw-r--r--netwerk/base/moz.build5
-rw-r--r--netwerk/base/nsINetworkInterceptController.idl28
-rw-r--r--netwerk/base/nsIOService.cpp5
-rw-r--r--netwerk/base/nsITimedChannel.idl18
-rw-r--r--netwerk/base/nsIncrementalDownload.cpp21
-rw-r--r--netwerk/base/nsNetUtil.cpp19
-rw-r--r--netwerk/base/nsUDPSocket.cpp37
-rw-r--r--netwerk/base/nsUDPSocket.h8
-rw-r--r--netwerk/dns/mdns/libmdns/moz.build10
-rw-r--r--netwerk/dns/mdns/libmdns/nsDNSServiceDiscovery.cpp27
-rw-r--r--netwerk/dns/mdns/libmdns/nsMulticastDNSModule.cpp2
-rw-r--r--netwerk/dns/moz.build8
-rw-r--r--netwerk/dns/nameprep.c347
-rw-r--r--netwerk/dns/nameprep_template.c139
-rw-r--r--netwerk/dns/nameprepdata.c2588
-rw-r--r--netwerk/dns/nsIDNService.cpp120
-rw-r--r--netwerk/dns/nsIDNService.h10
-rw-r--r--netwerk/ipc/NeckoChannelParams.ipdlh7
-rw-r--r--netwerk/protocol/ftp/nsFtpConnectionThread.cpp47
-rw-r--r--netwerk/protocol/ftp/nsFtpConnectionThread.h9
-rw-r--r--netwerk/protocol/http/HttpBaseChannel.cpp156
-rw-r--r--netwerk/protocol/http/HttpBaseChannel.h10
-rw-r--r--netwerk/protocol/http/HttpChannelChild.cpp7
-rw-r--r--netwerk/protocol/http/HttpChannelParent.cpp25
-rw-r--r--netwerk/protocol/http/HttpChannelParent.h8
-rw-r--r--netwerk/protocol/http/InterceptedChannel.cpp35
-rw-r--r--netwerk/protocol/http/InterceptedChannel.h51
-rw-r--r--netwerk/protocol/http/NullHttpChannel.cpp106
-rw-r--r--netwerk/protocol/http/nsHttpChannel.cpp2
-rw-r--r--netwerk/protocol/http/nsHttpHandler.cpp25
-rw-r--r--netwerk/protocol/http/nsHttpTransaction.cpp46
-rw-r--r--netwerk/protocol/http/nsHttpTransaction.h8
-rw-r--r--netwerk/protocol/websocket/WebSocketChannel.cpp48
-rw-r--r--netwerk/protocol/websocket/WebSocketChannel.h8
-rw-r--r--netwerk/standalone/moz.build3
-rw-r--r--netwerk/system/linux/nsNotifyAddrListener_Linux.cpp10
-rw-r--r--netwerk/test/moz.build2
-rw-r--r--netwerk/wifi/moz.build11
-rw-r--r--netwerk/wifi/nsWifiMonitor.h30
-rw-r--r--netwerk/wifi/nsWifiMonitorGonk.cpp181
-rw-r--r--old-configure.in329
-rw-r--r--python/mozbuild/mozbuild/backend/cpp_eclipse.py25
-rw-r--r--python/mozbuild/mozbuild/base.py5
-rwxr-xr-xpython/mozbuild/mozbuild/mozinfo.py10
-rw-r--r--python/mozbuild/mozbuild/test/test_testing.py4
-rw-r--r--security/manager/.eslintrc.js3
-rw-r--r--security/manager/pki/nsNSSDialogHelper.cpp6
-rw-r--r--security/sandbox/chromium-shim/base/MissingBasicTypes.h25
-rw-r--r--security/sandbox/chromium-shim/base/debug/debugging_flags.h19
-rw-r--r--security/sandbox/chromium-shim/base/file_version_info_win.h29
-rw-r--r--security/sandbox/chromium-shim/base/files/file_path.cpp19
-rw-r--r--security/sandbox/chromium-shim/base/gtest_prod_util.h17
-rw-r--r--security/sandbox/chromium-shim/base/logging.cpp156
-rw-r--r--security/sandbox/chromium-shim/base/third_party/nspr/prtime.h8
-rw-r--r--security/sandbox/chromium-shim/base/third_party/nspr/prtypes.h8
-rw-r--r--security/sandbox/chromium-shim/base/tracked_objects.h19
-rw-r--r--security/sandbox/chromium-shim/base/win/registry.h34
-rw-r--r--security/sandbox/chromium-shim/base/win/sdkdecls.h191
-rw-r--r--security/sandbox/chromium-shim/sandbox/win/loggingCallbacks.h107
-rw-r--r--security/sandbox/chromium-shim/sandbox/win/loggingTypes.h27
-rw-r--r--security/sandbox/chromium-shim/sandbox/win/sandboxLogging.cpp82
-rw-r--r--security/sandbox/chromium-shim/sandbox/win/sandboxLogging.h51
-rw-r--r--security/sandbox/chromium/LICENSE27
-rw-r--r--security/sandbox/chromium/base/at_exit.cc82
-rw-r--r--security/sandbox/chromium/base/at_exit.h76
-rw-r--r--security/sandbox/chromium/base/atomic_ref_count.h66
-rw-r--r--security/sandbox/chromium/base/atomic_sequence_num.h60
-rw-r--r--security/sandbox/chromium/base/atomicops.h161
-rw-r--r--security/sandbox/chromium/base/atomicops_internals_portable.h229
-rw-r--r--security/sandbox/chromium/base/atomicops_internals_x86_msvc.h196
-rw-r--r--security/sandbox/chromium/base/base_export.h29
-rw-r--r--security/sandbox/chromium/base/base_paths.h55
-rw-r--r--security/sandbox/chromium/base/base_paths_win.h54
-rw-r--r--security/sandbox/chromium/base/base_switches.cc95
-rw-r--r--security/sandbox/chromium/base/base_switches.h41
-rw-r--r--security/sandbox/chromium/base/bind.h101
-rw-r--r--security/sandbox/chromium/base/bind_helpers.h658
-rw-r--r--security/sandbox/chromium/base/bind_internal.h425
-rw-r--r--security/sandbox/chromium/base/bind_internal_win.h69
-rw-r--r--security/sandbox/chromium/base/bit_cast.h71
-rw-r--r--security/sandbox/chromium/base/callback.h405
-rw-r--r--security/sandbox/chromium/base/callback_forward.h19
-rw-r--r--security/sandbox/chromium/base/callback_internal.cc46
-rw-r--r--security/sandbox/chromium/base/callback_internal.h234
-rw-r--r--security/sandbox/chromium/base/compiler_specific.h190
-rw-r--r--security/sandbox/chromium/base/containers/hash_tables.h281
-rw-r--r--security/sandbox/chromium/base/cpu.cc296
-rw-r--r--security/sandbox/chromium/base/cpu.h92
-rw-r--r--security/sandbox/chromium/base/debug/alias.cc23
-rw-r--r--security/sandbox/chromium/base/debug/alias.h21
-rw-r--r--security/sandbox/chromium/base/debug/debugger.h44
-rw-r--r--security/sandbox/chromium/base/debug/leak_annotations.h46
-rw-r--r--security/sandbox/chromium/base/debug/profiler.cc221
-rw-r--r--security/sandbox/chromium/base/debug/profiler.h91
-rw-r--r--security/sandbox/chromium/base/file_descriptor_posix.h59
-rw-r--r--security/sandbox/chromium/base/files/file_path.h477
-rw-r--r--security/sandbox/chromium/base/guid.h33
-rw-r--r--security/sandbox/chromium/base/hash.cc18
-rw-r--r--security/sandbox/chromium/base/hash.h40
-rw-r--r--security/sandbox/chromium/base/lazy_instance.cc54
-rw-r--r--security/sandbox/chromium/base/lazy_instance.h207
-rw-r--r--security/sandbox/chromium/base/location.cc106
-rw-r--r--security/sandbox/chromium/base/location.h110
-rw-r--r--security/sandbox/chromium/base/logging.h976
-rw-r--r--security/sandbox/chromium/base/macros.h87
-rw-r--r--security/sandbox/chromium/base/memory/aligned_memory.h117
-rw-r--r--security/sandbox/chromium/base/memory/raw_scoped_refptr_mismatch_checker.h64
-rw-r--r--security/sandbox/chromium/base/memory/ref_counted.cc53
-rw-r--r--security/sandbox/chromium/base/memory/ref_counted.h446
-rw-r--r--security/sandbox/chromium/base/memory/scoped_ptr.h607
-rw-r--r--security/sandbox/chromium/base/memory/singleton.cc34
-rw-r--r--security/sandbox/chromium/base/memory/singleton.h284
-rw-r--r--security/sandbox/chromium/base/memory/weak_ptr.h345
-rw-r--r--security/sandbox/chromium/base/move.h57
-rw-r--r--security/sandbox/chromium/base/numerics/safe_conversions.h165
-rw-r--r--security/sandbox/chromium/base/numerics/safe_conversions_impl.h264
-rw-r--r--security/sandbox/chromium/base/numerics/safe_math.h299
-rw-r--r--security/sandbox/chromium/base/numerics/safe_math_impl.h545
-rw-r--r--security/sandbox/chromium/base/os_compat_android.h28
-rw-r--r--security/sandbox/chromium/base/path_service.h97
-rw-r--r--security/sandbox/chromium/base/posix/eintr_wrapper.h67
-rw-r--r--security/sandbox/chromium/base/process/process_handle.h81
-rw-r--r--security/sandbox/chromium/base/rand_util.h62
-rw-r--r--security/sandbox/chromium/base/scoped_clear_errno.h34
-rw-r--r--security/sandbox/chromium/base/sequence_checker.h62
-rw-r--r--security/sandbox/chromium/base/sequence_checker_impl.h52
-rw-r--r--security/sandbox/chromium/base/sequenced_task_runner.h159
-rw-r--r--security/sandbox/chromium/base/sequenced_task_runner_helpers.h113
-rw-r--r--security/sandbox/chromium/base/single_thread_task_runner.h38
-rw-r--r--security/sandbox/chromium/base/stl_util.h262
-rw-r--r--security/sandbox/chromium/base/strings/nullable_string16.cc17
-rw-r--r--security/sandbox/chromium/base/strings/nullable_string16.h46
-rw-r--r--security/sandbox/chromium/base/strings/safe_sprintf.cc686
-rw-r--r--security/sandbox/chromium/base/strings/safe_sprintf.h246
-rw-r--r--security/sandbox/chromium/base/strings/safe_sprintf_unittest.cc763
-rw-r--r--security/sandbox/chromium/base/strings/string16.cc82
-rw-r--r--security/sandbox/chromium/base/strings/string16.h187
-rw-r--r--security/sandbox/chromium/base/strings/string_number_conversions.cc485
-rw-r--r--security/sandbox/chromium/base/strings/string_number_conversions.h137
-rw-r--r--security/sandbox/chromium/base/strings/string_piece.cc452
-rw-r--r--security/sandbox/chromium/base/strings/string_piece.h469
-rw-r--r--security/sandbox/chromium/base/strings/string_split.cc264
-rw-r--r--security/sandbox/chromium/base/strings/string_split.h129
-rw-r--r--security/sandbox/chromium/base/strings/string_util.cc1001
-rw-r--r--security/sandbox/chromium/base/strings/string_util.h461
-rw-r--r--security/sandbox/chromium/base/strings/string_util_constants.cc67
-rw-r--r--security/sandbox/chromium/base/strings/string_util_posix.h37
-rw-r--r--security/sandbox/chromium/base/strings/string_util_win.h44
-rw-r--r--security/sandbox/chromium/base/strings/stringprintf.cc189
-rw-r--r--security/sandbox/chromium/base/strings/stringprintf.h66
-rw-r--r--security/sandbox/chromium/base/strings/utf_string_conversion_utils.cc148
-rw-r--r--security/sandbox/chromium/base/strings/utf_string_conversion_utils.h99
-rw-r--r--security/sandbox/chromium/base/strings/utf_string_conversions.cc231
-rw-r--r--security/sandbox/chromium/base/strings/utf_string_conversions.h54
-rw-r--r--security/sandbox/chromium/base/synchronization/condition_variable.h118
-rw-r--r--security/sandbox/chromium/base/synchronization/condition_variable_posix.cc137
-rw-r--r--security/sandbox/chromium/base/synchronization/lock.cc38
-rw-r--r--security/sandbox/chromium/base/synchronization/lock.h140
-rw-r--r--security/sandbox/chromium/base/synchronization/lock_impl.h60
-rw-r--r--security/sandbox/chromium/base/synchronization/lock_impl_posix.cc55
-rw-r--r--security/sandbox/chromium/base/synchronization/lock_impl_win.cc36
-rw-r--r--security/sandbox/chromium/base/synchronization/waitable_event.h189
-rw-r--r--security/sandbox/chromium/base/synchronization/waitable_event_posix.cc417
-rw-r--r--security/sandbox/chromium/base/task_runner.h154
-rw-r--r--security/sandbox/chromium/base/template_util.h122
-rw-r--r--security/sandbox/chromium/base/third_party/dmg_fp/LICENSE18
-rw-r--r--security/sandbox/chromium/base/third_party/dmg_fp/dmg_fp.h30
-rw-r--r--security/sandbox/chromium/base/third_party/dmg_fp/dtoa.cc4234
-rw-r--r--security/sandbox/chromium/base/third_party/dmg_fp/g_fmt.cc102
-rw-r--r--security/sandbox/chromium/base/third_party/dynamic_annotations/LICENSE28
-rw-r--r--security/sandbox/chromium/base/third_party/dynamic_annotations/dynamic_annotations.h595
-rw-r--r--security/sandbox/chromium/base/third_party/icu/LICENSE32
-rw-r--r--security/sandbox/chromium/base/third_party/icu/icu_utf.cc227
-rw-r--r--security/sandbox/chromium/base/third_party/icu/icu_utf.h400
-rw-r--r--security/sandbox/chromium/base/third_party/superfasthash/LICENSE27
-rw-r--r--security/sandbox/chromium/base/third_party/superfasthash/README.chromium29
-rw-r--r--security/sandbox/chromium/base/third_party/superfasthash/superfasthash.c84
-rw-r--r--security/sandbox/chromium/base/third_party/valgrind/LICENSE39
-rw-r--r--security/sandbox/chromium/base/third_party/valgrind/valgrind.h4792
-rw-r--r--security/sandbox/chromium/base/threading/platform_thread.h199
-rw-r--r--security/sandbox/chromium/base/threading/platform_thread_internal_posix.cc35
-rw-r--r--security/sandbox/chromium/base/threading/platform_thread_internal_posix.h43
-rw-r--r--security/sandbox/chromium/base/threading/platform_thread_linux.cc120
-rw-r--r--security/sandbox/chromium/base/threading/platform_thread_posix.cc263
-rw-r--r--security/sandbox/chromium/base/threading/platform_thread_win.cc284
-rw-r--r--security/sandbox/chromium/base/threading/sequenced_worker_pool.h384
-rw-r--r--security/sandbox/chromium/base/threading/thread_checker_impl.h44
-rw-r--r--security/sandbox/chromium/base/threading/thread_collision_warner.cc64
-rw-r--r--security/sandbox/chromium/base/threading/thread_collision_warner.h245
-rw-r--r--security/sandbox/chromium/base/threading/thread_id_name_manager.cc112
-rw-r--r--security/sandbox/chromium/base/threading/thread_id_name_manager.h68
-rw-r--r--security/sandbox/chromium/base/threading/thread_local.h134
-rw-r--r--security/sandbox/chromium/base/threading/thread_local_posix.cc43
-rw-r--r--security/sandbox/chromium/base/threading/thread_local_storage.h148
-rw-r--r--security/sandbox/chromium/base/threading/thread_local_win.cc40
-rw-r--r--security/sandbox/chromium/base/threading/thread_restrictions.cc85
-rw-r--r--security/sandbox/chromium/base/threading/thread_restrictions.h266
-rw-r--r--security/sandbox/chromium/base/time/time.cc349
-rw-r--r--security/sandbox/chromium/base/time/time.h768
-rw-r--r--security/sandbox/chromium/base/time/time_posix.cc363
-rw-r--r--security/sandbox/chromium/base/time/time_win.cc616
-rw-r--r--security/sandbox/chromium/base/tuple.h306
-rw-r--r--security/sandbox/chromium/base/values.h567
-rw-r--r--security/sandbox/chromium/base/version.h72
-rw-r--r--security/sandbox/chromium/base/win/pe_image.cc580
-rw-r--r--security/sandbox/chromium/base/win/pe_image.h265
-rw-r--r--security/sandbox/chromium/base/win/scoped_handle.cc248
-rw-r--r--security/sandbox/chromium/base/win/scoped_handle.h182
-rw-r--r--security/sandbox/chromium/base/win/scoped_process_information.cc147
-rw-r--r--security/sandbox/chromium/base/win/scoped_process_information.h83
-rw-r--r--security/sandbox/chromium/base/win/startup_information.cc109
-rw-r--r--security/sandbox/chromium/base/win/startup_information.h51
-rw-r--r--security/sandbox/chromium/base/win/windows_version.cc225
-rw-r--r--security/sandbox/chromium/base/win/windows_version.h133
-rw-r--r--security/sandbox/chromium/build/build_config.h168
-rw-r--r--security/sandbox/chromium/build/buildflag.h47
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.cc348
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.h335
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl_forward.h42
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl_impl.h69
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/codegen.cc161
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/codegen.h122
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/cons.h139
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/dump_bpf.cc159
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/dump_bpf.h24
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/errorcode.h37
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/linux_syscall_ranges.h57
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/policy.cc19
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/policy.h37
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/policy_compiler.cc466
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/policy_compiler.h153
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/seccomp_macros.h294
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/syscall_set.cc146
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/syscall_set.h103
-rw-r--r--security/sandbox/chromium/sandbox/linux/bpf_dsl/trap_registry.h73
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tester_compatibility_delegate.h55
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tests.h122
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tests_unittest.cc154
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/die.cc93
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/die.h68
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf.cc280
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf.h114
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.cc65
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.h61
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall.cc421
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall.h166
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall_unittest.cc244
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/trap.cc387
-rw-r--r--security/sandbox/chromium/sandbox/linux/seccomp-bpf/trap.h86
-rw-r--r--security/sandbox/chromium/sandbox/linux/services/syscall_wrappers.cc261
-rw-r--r--security/sandbox/chromium/sandbox/linux/services/syscall_wrappers.h85
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/arm_linux_syscalls.h1418
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/arm_linux_ucontext.h69
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/capability.h42
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/i386_linux_ucontext.h96
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/linux_filter.h140
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/linux_futex.h84
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/linux_seccomp.h107
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/linux_signal.h146
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/linux_syscalls.h37
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/linux_ucontext.h28
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/x86_32_linux_syscalls.h1494
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_syscalls.h1294
-rw-r--r--security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_ucontext.h90
-rw-r--r--security/sandbox/chromium/sandbox/sandbox_export.h26
-rw-r--r--security/sandbox/chromium/sandbox/win/src/Wow64.cc226
-rw-r--r--security/sandbox/chromium/sandbox/win/src/Wow64.h52
-rw-r--r--security/sandbox/chromium/sandbox/win/src/Wow64_64.cc22
-rw-r--r--security/sandbox/chromium/sandbox/win/src/acl.cc125
-rw-r--r--security/sandbox/chromium/sandbox/win/src/acl.h44
-rw-r--r--security/sandbox/chromium/sandbox/win/src/app_container.cc184
-rw-r--r--security/sandbox/chromium/sandbox/win/src/app_container.h70
-rw-r--r--security/sandbox/chromium/sandbox/win/src/app_container_test.cc161
-rw-r--r--security/sandbox/chromium/sandbox/win/src/app_container_unittest.cc58
-rw-r--r--security/sandbox/chromium/sandbox/win/src/broker_services.cc558
-rw-r--r--security/sandbox/chromium/sandbox/win/src/broker_services.h112
-rw-r--r--security/sandbox/chromium/sandbox/win/src/crosscall_client.h526
-rw-r--r--security/sandbox/chromium/sandbox/win/src/crosscall_params.h287
-rw-r--r--security/sandbox/chromium/sandbox/win/src/crosscall_server.cc314
-rw-r--r--security/sandbox/chromium/sandbox/win/src/crosscall_server.h228
-rw-r--r--security/sandbox/chromium/sandbox/win/src/eat_resolver.cc88
-rw-r--r--security/sandbox/chromium/sandbox/win/src/eat_resolver.h50
-rw-r--r--security/sandbox/chromium/sandbox/win/src/file_policy_test.cc673
-rw-r--r--security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.cc318
-rw-r--r--security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.h74
-rw-r--r--security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc402
-rw-r--r--security/sandbox/chromium/sandbox/win/src/filesystem_interception.h53
-rw-r--r--security/sandbox/chromium/sandbox/win/src/filesystem_policy.cc435
-rw-r--r--security/sandbox/chromium/sandbox/win/src/filesystem_policy.h113
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_closer.cc196
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_closer.h76
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_closer_agent.cc203
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_closer_agent.h47
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_closer_test.cc300
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_dispatcher.cc92
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_dispatcher.h41
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_inheritance_test.cc52
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_interception.cc48
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_interception.h24
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_policy.cc92
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_policy.h39
-rw-r--r--security/sandbox/chromium/sandbox/win/src/handle_policy_test.cc114
-rw-r--r--security/sandbox/chromium/sandbox/win/src/integrity_level_test.cc91
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interception.cc560
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interception.h286
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interception_agent.cc235
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interception_agent.h87
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interception_internal.h78
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interception_unittest.cc260
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interceptors.h55
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interceptors_64.cc278
-rw-r--r--security/sandbox/chromium/sandbox/win/src/interceptors_64.h175
-rw-r--r--security/sandbox/chromium/sandbox/win/src/internal_types.h76
-rw-r--r--security/sandbox/chromium/sandbox/win/src/ipc_ping_test.cc58
-rw-r--r--security/sandbox/chromium/sandbox/win/src/ipc_tags.h40
-rw-r--r--security/sandbox/chromium/sandbox/win/src/ipc_unittest.cc632
-rw-r--r--security/sandbox/chromium/sandbox/win/src/job.cc119
-rw-r--r--security/sandbox/chromium/sandbox/win/src/job.h67
-rw-r--r--security/sandbox/chromium/sandbox/win/src/job_unittest.cc204
-rw-r--r--security/sandbox/chromium/sandbox/win/src/named_pipe_dispatcher.cc103
-rw-r--r--security/sandbox/chromium/sandbox/win/src/named_pipe_dispatcher.h44
-rw-r--r--security/sandbox/chromium/sandbox/win/src/named_pipe_interception.cc76
-rw-r--r--security/sandbox/chromium/sandbox/win/src/named_pipe_interception.h36
-rw-r--r--security/sandbox/chromium/sandbox/win/src/named_pipe_policy.cc86
-rw-r--r--security/sandbox/chromium/sandbox/win/src/named_pipe_policy.h45
-rw-r--r--security/sandbox/chromium/sandbox/win/src/named_pipe_policy_test.cc140
-rw-r--r--security/sandbox/chromium/sandbox/win/src/nt_internals.h703
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_broker.cc126
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_broker.h26
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_engine_opcodes.cc446
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_engine_opcodes.h388
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_engine_params.h202
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_engine_processor.cc110
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_engine_processor.h148
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_engine_unittest.cc105
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_low_level.cc360
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_low_level.h193
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_low_level_unittest.cc621
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_opcodes_unittest.cc372
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_params.h67
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_target.cc129
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_target.h45
-rw-r--r--security/sandbox/chromium/sandbox/win/src/policy_target_test.cc417
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations.cc333
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations.h44
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations_test.cc252
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc57
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.h31
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_interception.cc29
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_interception.h45
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_policy.cc24
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_policy.h34
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_policy_test.cc385
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_thread_dispatcher.cc247
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_thread_dispatcher.h59
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_thread_interception.cc423
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_thread_interception.h90
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_thread_policy.cc241
-rw-r--r--security/sandbox/chromium/sandbox/win/src/process_thread_policy.h84
-rw-r--r--security/sandbox/chromium/sandbox/win/src/registry_dispatcher.cc175
-rw-r--r--security/sandbox/chromium/sandbox/win/src/registry_dispatcher.h49
-rw-r--r--security/sandbox/chromium/sandbox/win/src/registry_interception.cc251
-rw-r--r--security/sandbox/chromium/sandbox/win/src/registry_interception.h38
-rw-r--r--security/sandbox/chromium/sandbox/win/src/registry_policy.cc228
-rw-r--r--security/sandbox/chromium/sandbox/win/src/registry_policy.h59
-rw-r--r--security/sandbox/chromium/sandbox/win/src/registry_policy_test.cc289
-rw-r--r--security/sandbox/chromium/sandbox/win/src/resolver.cc64
-rw-r--r--security/sandbox/chromium/sandbox/win/src/resolver.h107
-rw-r--r--security/sandbox/chromium/sandbox/win/src/resolver_32.cc94
-rw-r--r--security/sandbox/chromium/sandbox/win/src/resolver_64.cc66
-rw-r--r--security/sandbox/chromium/sandbox/win/src/restricted_token.cc458
-rw-r--r--security/sandbox/chromium/sandbox/win/src/restricted_token.h201
-rw-r--r--security/sandbox/chromium/sandbox/win/src/restricted_token_unittest.cc620
-rw-r--r--security/sandbox/chromium/sandbox/win/src/restricted_token_utils.cc323
-rw-r--r--security/sandbox/chromium/sandbox/win/src/restricted_token_utils.h75
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox.cc48
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox.h164
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox.vcproj658
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_factory.h51
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_globals.cc18
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_nt_types.h46
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.cc676
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h196
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_policy.h259
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc770
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.h177
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_rand.cc22
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_rand.h16
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_types.h95
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_utils.cc32
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sandbox_utils.h25
-rw-r--r--security/sandbox/chromium/sandbox/win/src/security_level.h209
-rw-r--r--security/sandbox/chromium/sandbox/win/src/service_resolver.cc46
-rw-r--r--security/sandbox/chromium/sandbox/win/src/service_resolver.h159
-rw-r--r--security/sandbox/chromium/sandbox/win/src/service_resolver_32.cc478
-rw-r--r--security/sandbox/chromium/sandbox/win/src/service_resolver_64.cc252
-rw-r--r--security/sandbox/chromium/sandbox/win/src/service_resolver_unittest.cc268
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_client.cc153
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_client.h139
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_server.cc430
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_server.h134
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sid.cc26
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sid.h29
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sid_unittest.cc71
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep/ia32_modrm_map.cpp92
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep/ia32_opcode_map.cpp1159
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler.cpp395
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler.h156
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler_types.h197
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep/preamble_patcher.h111
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep/preamble_patcher_with_stub.cpp181
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep_resolver.cc204
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sidestep_resolver.h75
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sync_dispatcher.cc82
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sync_dispatcher.h42
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sync_interception.cc178
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sync_interception.h46
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sync_policy.cc246
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sync_policy.h52
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sync_policy_test.cc149
-rw-r--r--security/sandbox/chromium/sandbox/win/src/sync_policy_test.h18
-rw-r--r--security/sandbox/chromium/sandbox/win/src/target_interceptions.cc100
-rw-r--r--security/sandbox/chromium/sandbox/win/src/target_interceptions.h35
-rw-r--r--security/sandbox/chromium/sandbox/win/src/target_process.cc368
-rw-r--r--security/sandbox/chromium/sandbox/win/src/target_process.h143
-rw-r--r--security/sandbox/chromium/sandbox/win/src/target_services.cc261
-rw-r--r--security/sandbox/chromium/sandbox/win/src/target_services.h71
-rw-r--r--security/sandbox/chromium/sandbox/win/src/threadpool_unittest.cc97
-rw-r--r--security/sandbox/chromium/sandbox/win/src/top_level_dispatcher.cc146
-rw-r--r--security/sandbox/chromium/sandbox/win/src/top_level_dispatcher.h51
-rw-r--r--security/sandbox/chromium/sandbox/win/src/unload_dll_test.cc93
-rw-r--r--security/sandbox/chromium/sandbox/win/src/win2k_threadpool.cc66
-rw-r--r--security/sandbox/chromium/sandbox/win/src/win2k_threadpool.h61
-rw-r--r--security/sandbox/chromium/sandbox/win/src/win_utils.cc437
-rw-r--r--security/sandbox/chromium/sandbox/win/src/win_utils.h117
-rw-r--r--security/sandbox/chromium/sandbox/win/src/win_utils_unittest.cc111
-rw-r--r--security/sandbox/chromium/sandbox/win/src/window.cc161
-rw-r--r--security/sandbox/chromium/sandbox/win/src/window.h40
-rw-r--r--security/sandbox/chromium/sandbox/win/wow_helper/service64_resolver.cc346
-rw-r--r--security/sandbox/chromium/sandbox/win/wow_helper/service64_resolver.h75
-rw-r--r--security/sandbox/chromium/sandbox/win/wow_helper/target_code.cc38
-rw-r--r--security/sandbox/chromium/sandbox/win/wow_helper/target_code.h41
-rw-r--r--security/sandbox/chromium/sandbox/win/wow_helper/wow_helper.cc87
-rw-r--r--security/sandbox/linux/LinuxCapabilities.cpp28
-rw-r--r--security/sandbox/linux/LinuxCapabilities.h128
-rw-r--r--security/sandbox/linux/LinuxSched.h35
-rw-r--r--security/sandbox/linux/Sandbox.cpp693
-rw-r--r--security/sandbox/linux/Sandbox.h39
-rw-r--r--security/sandbox/linux/SandboxBrokerClient.cpp247
-rw-r--r--security/sandbox/linux/SandboxBrokerClient.h58
-rw-r--r--security/sandbox/linux/SandboxChroot.cpp212
-rw-r--r--security/sandbox/linux/SandboxChroot.h66
-rw-r--r--security/sandbox/linux/SandboxFilter.cpp961
-rw-r--r--security/sandbox/linux/SandboxFilter.h38
-rw-r--r--security/sandbox/linux/SandboxFilterUtil.cpp121
-rw-r--r--security/sandbox/linux/SandboxFilterUtil.h148
-rw-r--r--security/sandbox/linux/SandboxHooks.cpp72
-rw-r--r--security/sandbox/linux/SandboxInfo.cpp272
-rw-r--r--security/sandbox/linux/SandboxInfo.h81
-rw-r--r--security/sandbox/linux/SandboxInternal.h28
-rw-r--r--security/sandbox/linux/SandboxLogging.cpp60
-rw-r--r--security/sandbox/linux/SandboxLogging.h52
-rw-r--r--security/sandbox/linux/SandboxUtil.cpp106
-rw-r--r--security/sandbox/linux/SandboxUtil.h21
-rw-r--r--security/sandbox/linux/broker/SandboxBroker.cpp731
-rw-r--r--security/sandbox/linux/broker/SandboxBroker.h132
-rw-r--r--security/sandbox/linux/broker/SandboxBrokerCommon.cpp120
-rw-r--r--security/sandbox/linux/broker/SandboxBrokerCommon.h72
-rw-r--r--security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp194
-rw-r--r--security/sandbox/linux/broker/SandboxBrokerPolicyFactory.h32
-rw-r--r--security/sandbox/linux/broker/SandboxBrokerUtils.h30
-rw-r--r--security/sandbox/linux/broker/moz.build37
-rw-r--r--security/sandbox/linux/glue/SandboxCrash.cpp131
-rw-r--r--security/sandbox/linux/glue/moz.build29
-rw-r--r--security/sandbox/linux/gtest/TestBroker.cpp626
-rw-r--r--security/sandbox/linux/gtest/TestBrokerPolicy.cpp98
-rw-r--r--security/sandbox/linux/gtest/TestSandboxUtil.cpp44
-rw-r--r--security/sandbox/linux/gtest/moz.build27
-rw-r--r--security/sandbox/linux/moz.build116
-rw-r--r--security/sandbox/mac/Sandbox.h65
-rw-r--r--security/sandbox/mac/Sandbox.mm489
-rw-r--r--security/sandbox/mac/moz.build15
-rw-r--r--security/sandbox/modifications-to-chromium-to-reapply-after-upstream-merge.txt9
-rw-r--r--security/sandbox/moz-chromium-commit-status.txt4
-rw-r--r--security/sandbox/moz.build176
-rw-r--r--security/sandbox/test/browser.ini11
-rw-r--r--security/sandbox/test/browser_content_sandbox_fs.js169
-rw-r--r--security/sandbox/test/browser_content_sandbox_syscalls.js223
-rw-r--r--security/sandbox/test/browser_content_sandbox_utils.js57
-rw-r--r--security/sandbox/win/SandboxInitialization.cpp81
-rw-r--r--security/sandbox/win/SandboxInitialization.h47
-rw-r--r--security/sandbox/win/src/sandboxbroker/moz.build33
-rw-r--r--security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp595
-rw-r--r--security/sandbox/win/src/sandboxbroker/sandboxBroker.h63
-rw-r--r--security/sandbox/win/src/sandboxtarget/moz.build20
-rw-r--r--security/sandbox/win/src/sandboxtarget/sandboxTarget.cpp21
-rw-r--r--security/sandbox/win/src/sandboxtarget/sandboxTarget.h83
-rw-r--r--security/sandbox/win/wow_helper/Makefile.in47
-rw-r--r--security/sandbox/win/wow_helper/moz.build30
-rw-r--r--services/fxaccounts/FxAccountsManager.jsm654
-rw-r--r--services/fxaccounts/FxAccountsProfileClient.jsm4
-rw-r--r--services/fxaccounts/FxAccountsStorage.jsm9
-rw-r--r--services/fxaccounts/moz.build3
-rw-r--r--services/sync/modules/record.js4
-rw-r--r--services/sync/modules/service.js2
-rw-r--r--services/sync/tps/extensions/mozmill/resource/driver/controller.js2
-rw-r--r--services/sync/tps/extensions/mozmill/resource/modules/assertions.js2
-rw-r--r--startupcache/moz.build3
-rw-r--r--storage/moz.build3
-rw-r--r--testing/marionette/assert.js2
-rw-r--r--testing/marionette/harness/marionette_harness/tests/webapi-tests.ini3
-rw-r--r--testing/mochitest/runtests.py5
-rw-r--r--testing/modules/tests/xpcshell/xpcshell.ini2
-rwxr-xr-xtesting/mozbase/mozrunner/mozrunner/utils.py5
-rw-r--r--testing/profiles/prefs_general.js3
-rw-r--r--testing/specialpowers/content/specialpowersAPI.js4
-rw-r--r--testing/talos/talos/test.py1
-rw-r--r--testing/testsuite-targets.mk4
-rw-r--r--testing/web-platform/meta/MANIFEST.json4
-rw-r--r--testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini3
-rw-r--r--testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/no-redirect/no-opt-in-blocks.https.html.ini3
-rw-r--r--testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini3
-rw-r--r--testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini3
-rw-r--r--testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/no-redirect/no-opt-in-blocks.https.html.ini3
-rw-r--r--testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini3
-rw-r--r--testing/web-platform/meta/service-workers/service-worker/resource-timing.https.html.ini7
-rw-r--r--testing/web-platform/tests/service-workers/service-worker/fetch-frame-resource.https.html6
-rw-r--r--testing/web-platform/tests/service-workers/service-worker/resource-timing.https.html4
-rw-r--r--testing/web-platform/tests/service-workers/service-worker/resources/resource-timing-worker.js6
-rw-r--r--testing/web-platform/tests/user-timing/resources/webperftestharness.js2
-rw-r--r--testing/web-platform/tests/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.html32
-rw-r--r--testing/web-platform/tests/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.js14
-rw-r--r--testing/web-platform/tests/websockets/unload-a-document/001-1.html2
-rw-r--r--testing/web-platform/tests/websockets/unload-a-document/001-2.html4
-rw-r--r--testing/web-platform/tests/websockets/unload-a-document/001.html2
-rw-r--r--testing/web-platform/tests/websockets/unload-a-document/002-1.html2
-rw-r--r--testing/web-platform/tests/websockets/unload-a-document/002-2.html4
-rw-r--r--testing/web-platform/tests/websockets/unload-a-document/002.html2
-rw-r--r--testing/xpcshell/example/unit/xpcshell.ini2
-rw-r--r--toolkit/.eslintrc.js3
-rw-r--r--toolkit/components/alerts/resources/content/alert.js2
-rw-r--r--toolkit/components/build/nsToolkitCompsModule.cpp2
-rw-r--r--toolkit/components/captivedetect/captivedetect.js2
-rw-r--r--toolkit/components/diskspacewatcher/DiskSpaceWatcher.cpp3
-rw-r--r--toolkit/components/jsdownloads/src/DownloadIntegration.jsm9
-rw-r--r--toolkit/components/jsdownloads/src/DownloadPlatform.cpp2
-rw-r--r--toolkit/components/jsdownloads/src/DownloadUIHelper.jsm7
-rw-r--r--toolkit/components/moz.build3
-rw-r--r--toolkit/components/osfile/modules/osfile_async_front.jsm4
-rw-r--r--toolkit/components/osfile/modules/osfile_unix_front.jsm4
-rw-r--r--toolkit/components/osfile/modules/osfile_win_front.jsm4
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_constants.js7
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js6
-rw-r--r--toolkit/components/osfile/tests/xpcshell/test_path_constants.js2
-rw-r--r--toolkit/components/printing/tests/browser.ini3
-rw-r--r--toolkit/components/printing/tests/browser_page_change_print_original.js13
-rw-r--r--toolkit/components/printing/tests/file_page_change_print_original_1.html8
-rw-r--r--toolkit/components/printing/tests/file_page_change_print_original_2.html1
-rw-r--r--toolkit/components/reader/.eslintrc.js3
-rw-r--r--toolkit/components/search/nsSearchService.js9
-rw-r--r--toolkit/components/startup/nsAppStartup.cpp4
-rw-r--r--toolkit/components/telemetry/Telemetry.cpp2
-rw-r--r--toolkit/components/telemetry/TelemetryEnvironment.jsm44
-rw-r--r--toolkit/components/telemetry/TelemetryHistogram.cpp38
-rw-r--r--toolkit/components/telemetry/TelemetrySession.jsm2
-rw-r--r--toolkit/components/telemetry/TelemetryStorage.jsm2
-rw-r--r--toolkit/components/telemetry/tests/unit/head.js2
-rw-r--r--toolkit/components/viewsource/content/viewSource-content.js2
-rw-r--r--toolkit/components/webextensions/.eslintrc.js3
-rw-r--r--toolkit/content/aboutSupport.js21
-rw-r--r--toolkit/content/aboutSupport.xhtml14
-rw-r--r--toolkit/content/license.html41
-rw-r--r--toolkit/content/widgets/browser.xml6
-rw-r--r--toolkit/content/widgets/datetimepopup.xml4
-rw-r--r--toolkit/crashreporter/crashreporter.mozbuild3
-rw-r--r--toolkit/crashreporter/google-breakpad/src/client/linux/moz.build3
-rw-r--r--toolkit/crashreporter/nsExceptionHandler.cpp21
-rw-r--r--toolkit/identity/FirefoxAccounts.jsm9
-rw-r--r--toolkit/identity/tests/unit/xpcshell.ini2
-rw-r--r--toolkit/jetpack/dev/volcan.js2
-rw-r--r--toolkit/jetpack/moz.build189
-rw-r--r--toolkit/jetpack/sdk/lang/weak-set.js4
-rw-r--r--toolkit/jetpack/sdk/ui/buttons.js2
-rw-r--r--toolkit/library/moz.build34
-rw-r--r--toolkit/locales/en-US/chrome/global/aboutSupport.dtd2
-rw-r--r--toolkit/locales/en-US/chrome/global/aboutSupport.properties8
-rw-r--r--toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd3
-rw-r--r--toolkit/modules/AppConstants.jsm33
-rw-r--r--toolkit/modules/Sqlite.jsm2
-rw-r--r--toolkit/modules/Troubleshoot.jsm25
-rw-r--r--toolkit/modules/UpdateUtils.jsm18
-rw-r--r--toolkit/modules/sessionstore/Utils.jsm5
-rw-r--r--toolkit/modules/tests/browser/browser_Troubleshoot.js4
-rw-r--r--toolkit/moz.configure9
-rw-r--r--toolkit/mozapps/extensions/AddonManager.jsm2
-rw-r--r--toolkit/mozapps/extensions/AddonPathService.cpp10
-rw-r--r--toolkit/mozapps/extensions/amIAddonPathService.idl8
-rw-r--r--toolkit/mozapps/extensions/content/extensions.js4
-rw-r--r--toolkit/mozapps/extensions/content/extensions.xml8
-rw-r--r--toolkit/mozapps/extensions/content/extensions.xul6
-rw-r--r--toolkit/mozapps/extensions/extensions.manifest2
-rw-r--r--toolkit/mozapps/extensions/internal/AddonUpdateChecker.jsm13
-rw-r--r--toolkit/mozapps/extensions/internal/XPIProvider.jsm102
-rw-r--r--toolkit/mozapps/extensions/internal/XPIProviderUtils.js6
-rw-r--r--toolkit/mozapps/extensions/nsBlocklistService.js2
-rw-r--r--toolkit/mozapps/extensions/test/xpcshell/test_mapURIToAddonID.js4
-rw-r--r--toolkit/mozapps/extensions/test/xpcshell/xpcshell-shared.ini2
-rw-r--r--toolkit/mozapps/extensions/test/xpcshell/xpcshell-unpack.ini2
-rw-r--r--toolkit/mozapps/extensions/test/xpcshell/xpcshell.ini2
-rw-r--r--toolkit/mozapps/extensions/test/xpinstall/browser_datauri.js8
-rw-r--r--toolkit/mozapps/update/nsUpdateService.js334
-rw-r--r--toolkit/mozapps/update/updater/automounter_gonk.cpp251
-rw-r--r--toolkit/mozapps/update/updater/automounter_gonk.h48
-rw-r--r--toolkit/mozapps/update/updater/progressui_gonk.cpp53
-rw-r--r--toolkit/mozapps/update/updater/updater-common.build11
-rw-r--r--toolkit/mozapps/update/updater/updater.cpp137
-rw-r--r--toolkit/mozapps/webextensions/extensions.manifest2
-rw-r--r--toolkit/mozapps/webextensions/internal/AddonUpdateChecker.jsm13
-rw-r--r--toolkit/mozapps/webextensions/nsBlocklistService.js11
-rw-r--r--toolkit/profile/nsProfileLock.cpp23
-rw-r--r--toolkit/themes/linux/global/inContentUI.css41
-rw-r--r--toolkit/themes/linux/global/jar.mn1
-rw-r--r--toolkit/themes/osx/global/inContentUI.css144
-rw-r--r--toolkit/themes/osx/global/jar.mn1
-rw-r--r--toolkit/themes/shared/alert-common.css2
-rw-r--r--toolkit/themes/windows/global/inContentUI.css159
-rw-r--r--toolkit/themes/windows/global/jar.mn1
-rw-r--r--toolkit/toolkit.mozbuild11
-rw-r--r--toolkit/xre/EventTracer.cpp35
-rw-r--r--toolkit/xre/moz.build6
-rw-r--r--toolkit/xre/nsAppRunner.cpp53
-rw-r--r--toolkit/xre/nsEmbedFunctions.cpp40
-rw-r--r--toolkit/xre/nsUpdateDriver.cpp144
-rw-r--r--toolkit/xre/nsXREDirProvider.cpp253
-rw-r--r--toolkit/xre/nsXREDirProvider.h14
-rw-r--r--tools/profiler/core/GeckoSampler.cpp8
-rw-r--r--tools/profiler/core/platform.cpp21
-rw-r--r--tools/profiler/core/platform.h5
-rw-r--r--tools/profiler/core/shared-libraries-linux.cc18
-rw-r--r--tools/profiler/gecko/SaveProfileTask.cpp2
-rw-r--r--tools/profiler/lul/AutoObjectMapper.cpp6
-rw-r--r--tools/profiler/lul/AutoObjectMapper.h4
-rw-r--r--tools/profiler/lul/platform-linux-lul.cpp2
-rw-r--r--tools/profiler/moz.build3
-rw-r--r--tools/profiler/public/GeckoProfilerImpl.h7
-rw-r--r--tools/rewriting/ThirdPartyPaths.txt1
-rw-r--r--uriloader/base/nsURILoader.cpp12
-rw-r--r--uriloader/exthandler/gonk/nsOSHelperAppService.cpp56
-rw-r--r--uriloader/exthandler/gonk/nsOSHelperAppService.h39
-rw-r--r--uriloader/exthandler/moz.build2
-rw-r--r--uriloader/exthandler/nsExternalHelperAppService.cpp17
-rw-r--r--uriloader/exthandler/win/nsMIMEInfoWin.cpp3
-rw-r--r--widget/BasicEvents.h1
-rw-r--r--widget/EventMessageList.h5
-rw-r--r--widget/NativeKeyToDOMKeyName.h21
-rw-r--r--widget/PuppetWidget.cpp5
-rw-r--r--widget/WidgetEventImpl.cpp1
-rw-r--r--widget/gonk/GeckoTouchDispatcher.cpp358
-rw-r--r--widget/gonk/GeckoTouchDispatcher.h99
-rw-r--r--widget/gonk/GfxInfo.cpp194
-rw-r--r--widget/gonk/GfxInfo.h69
-rw-r--r--widget/gonk/GonkClipboardData.cpp75
-rw-r--r--widget/gonk/GonkClipboardData.h49
-rw-r--r--widget/gonk/GonkKeyMapping.h301
-rw-r--r--widget/gonk/GonkMemoryPressureMonitoring.cpp359
-rw-r--r--widget/gonk/GonkMemoryPressureMonitoring.h14
-rw-r--r--widget/gonk/GonkPermission.cpp195
-rw-r--r--widget/gonk/GonkPermission.h86
-rw-r--r--widget/gonk/HwcComposer2D.cpp971
-rw-r--r--widget/gonk/HwcComposer2D.h123
-rw-r--r--widget/gonk/HwcUtils.cpp169
-rw-r--r--widget/gonk/HwcUtils.h135
-rw-r--r--widget/gonk/OrientationObserver.cpp332
-rw-r--r--widget/gonk/OrientationObserver.h71
-rw-r--r--widget/gonk/ProcessOrientation.cpp519
-rw-r--r--widget/gonk/ProcessOrientation.h111
-rw-r--r--widget/gonk/WidgetTraceEvent.cpp96
-rw-r--r--widget/gonk/hwchal/HwcHAL.cpp214
-rw-r--r--widget/gonk/hwchal/HwcHAL.h70
-rw-r--r--widget/gonk/hwchal/HwcHALBase.h134
-rw-r--r--widget/gonk/libdisplay/BootAnimation.cpp726
-rw-r--r--widget/gonk/libdisplay/BootAnimation.h30
-rw-r--r--widget/gonk/libdisplay/DisplaySurface.h112
-rw-r--r--widget/gonk/libdisplay/FramebufferSurface.cpp207
-rw-r--r--widget/gonk/libdisplay/FramebufferSurface.h93
-rw-r--r--widget/gonk/libdisplay/GonkDisplay.h91
-rw-r--r--widget/gonk/libdisplay/GonkDisplayJB.cpp461
-rw-r--r--widget/gonk/libdisplay/GonkDisplayJB.h85
-rw-r--r--widget/gonk/libdisplay/GraphicBufferAlloc.cpp53
-rw-r--r--widget/gonk/libdisplay/GraphicBufferAlloc.h44
-rw-r--r--widget/gonk/libdisplay/VirtualDisplaySurface.cpp635
-rw-r--r--widget/gonk/libdisplay/VirtualDisplaySurface.h250
-rw-r--r--widget/gonk/libdisplay/moz.build59
-rw-r--r--widget/gonk/libui/EventHub.cpp1549
-rw-r--r--widget/gonk/libui/EventHub.h435
-rw-r--r--widget/gonk/libui/Input.cpp635
-rw-r--r--widget/gonk/libui/Input.h622
-rw-r--r--widget/gonk/libui/InputApplication.cpp42
-rw-r--r--widget/gonk/libui/InputApplication.h83
-rw-r--r--widget/gonk/libui/InputDevice.cpp184
-rw-r--r--widget/gonk/libui/InputDevice.h156
-rw-r--r--widget/gonk/libui/InputDispatcher.cpp4430
-rw-r--r--widget/gonk/libui/InputDispatcher.h1117
-rw-r--r--widget/gonk/libui/InputListener.cpp182
-rw-r--r--widget/gonk/libui/InputListener.h196
-rw-r--r--widget/gonk/libui/InputManager.cpp93
-rw-r--r--widget/gonk/libui/InputManager.h109
-rw-r--r--widget/gonk/libui/InputReader.cpp6510
-rw-r--r--widget/gonk/libui/InputReader.h1811
-rw-r--r--widget/gonk/libui/InputTransport.cpp957
-rw-r--r--widget/gonk/libui/InputTransport.h443
-rw-r--r--widget/gonk/libui/InputWindow.cpp64
-rw-r--r--widget/gonk/libui/InputWindow.h205
-rw-r--r--widget/gonk/libui/KeyCharacterMap.cpp1153
-rw-r--r--widget/gonk/libui/KeyCharacterMap.h257
-rw-r--r--widget/gonk/libui/KeyLayoutMap.cpp446
-rw-r--r--widget/gonk/libui/KeyLayoutMap.h117
-rw-r--r--widget/gonk/libui/Keyboard.cpp300
-rw-r--r--widget/gonk/libui/Keyboard.h122
-rw-r--r--widget/gonk/libui/KeycodeLabels.h380
-rw-r--r--widget/gonk/libui/PointerController.cpp604
-rw-r--r--widget/gonk/libui/PointerController.h266
-rw-r--r--widget/gonk/libui/PowerManager.h33
-rw-r--r--widget/gonk/libui/SpriteController.cpp515
-rw-r--r--widget/gonk/libui/SpriteController.h319
-rw-r--r--widget/gonk/libui/Tokenizer.cpp175
-rw-r--r--widget/gonk/libui/Tokenizer.h136
-rw-r--r--widget/gonk/libui/Trace.h64
-rw-r--r--widget/gonk/libui/VelocityControl.cpp110
-rw-r--r--widget/gonk/libui/VelocityControl.h107
-rw-r--r--widget/gonk/libui/VelocityTracker.cpp929
-rw-r--r--widget/gonk/libui/VelocityTracker.h269
-rw-r--r--widget/gonk/libui/VirtualKeyMap.cpp171
-rw-r--r--widget/gonk/libui/VirtualKeyMap.h81
-rw-r--r--widget/gonk/libui/android_input.h850
-rw-r--r--widget/gonk/libui/android_keycodes.h315
-rw-r--r--widget/gonk/libui/cutils_log.h569
-rw-r--r--widget/gonk/libui/cutils_trace.h276
-rw-r--r--widget/gonk/libui/linux_input.h1029
-rw-r--r--widget/gonk/libui/sha1.c289
-rw-r--r--widget/gonk/libui/sha1.h31
-rw-r--r--widget/gonk/moz.build96
-rw-r--r--widget/gonk/nativewindow/FakeSurfaceComposer.cpp703
-rw-r--r--widget/gonk/nativewindow/FakeSurfaceComposer.h175
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueue.h22
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueJB.cpp1036
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueJB.h653
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueKK.cpp1265
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueKK.h583
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.cpp193
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.h101
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.cpp559
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.h173
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp243
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.h251
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueDefs.h36
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.cpp96
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.h94
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp886
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.h216
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.cpp32
-rw-r--r--widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.h132
-rw-r--r--widget/gonk/nativewindow/GonkConsumerBaseJB.cpp245
-rw-r--r--widget/gonk/nativewindow/GonkConsumerBaseJB.h239
-rw-r--r--widget/gonk/nativewindow/GonkConsumerBaseKK.cpp252
-rw-r--r--widget/gonk/nativewindow/GonkConsumerBaseKK.h240
-rw-r--r--widget/gonk/nativewindow/GonkConsumerBaseLL.cpp257
-rw-r--r--widget/gonk/nativewindow/GonkConsumerBaseLL.h245
-rw-r--r--widget/gonk/nativewindow/GonkNativeWindow.h22
-rw-r--r--widget/gonk/nativewindow/GonkNativeWindowJB.cpp180
-rw-r--r--widget/gonk/nativewindow/GonkNativeWindowJB.h133
-rw-r--r--widget/gonk/nativewindow/GonkNativeWindowKK.cpp182
-rw-r--r--widget/gonk/nativewindow/GonkNativeWindowKK.h135
-rw-r--r--widget/gonk/nativewindow/GonkNativeWindowLL.cpp204
-rw-r--r--widget/gonk/nativewindow/GonkNativeWindowLL.h133
-rw-r--r--widget/gonk/nativewindow/IGonkGraphicBufferConsumer.h20
-rw-r--r--widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.cpp480
-rw-r--r--widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.h228
-rw-r--r--widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.cpp565
-rw-r--r--widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.h337
-rw-r--r--widget/gonk/nativewindow/moz.build104
-rw-r--r--widget/gonk/nsAppShell.cpp1087
-rw-r--r--widget/gonk/nsAppShell.h112
-rw-r--r--widget/gonk/nsClipboard.cpp366
-rw-r--r--widget/gonk/nsClipboard.h27
-rw-r--r--widget/gonk/nsIdleServiceGonk.cpp33
-rw-r--r--widget/gonk/nsIdleServiceGonk.h47
-rw-r--r--widget/gonk/nsLookAndFeel.cpp465
-rw-r--r--widget/gonk/nsLookAndFeel.h40
-rw-r--r--widget/gonk/nsScreenManagerGonk.cpp1081
-rw-r--r--widget/gonk/nsScreenManagerGonk.h228
-rw-r--r--widget/gonk/nsWidgetFactory.cpp128
-rw-r--r--widget/gonk/nsWindow.cpp744
-rw-r--r--widget/gonk/nsWindow.h154
-rw-r--r--widget/moz.build9
-rw-r--r--widget/nsBaseWidget.cpp1
-rw-r--r--widget/nsContentProcessWidgetFactory.cpp3
-rw-r--r--widget/tests/TestAppShellSteadyState.cpp2
-rw-r--r--widget/windows/WinUtils.cpp3
-rw-r--r--xpcom/base/nsMemoryReporterManager.cpp6
-rw-r--r--xpcom/base/nsSystemInfo.cpp71
-rw-r--r--xpcom/build/BinaryPath.h5
-rw-r--r--xpcom/build/XPCOMInit.cpp15
-rw-r--r--xpcom/build/XREChildData.h21
-rw-r--r--xpcom/build/XREShellData.h29
-rw-r--r--xpcom/build/moz.build1
-rw-r--r--xpcom/build/nsXREAppData.h13
-rw-r--r--xpcom/build/nsXULAppAPI.h4
-rw-r--r--xpcom/glue/AppData.cpp4
-rw-r--r--xpcom/glue/FileUtils.h11
-rwxr-xr-xxpcom/idl-parser/xpidl/xpidl.py2
-rw-r--r--xpcom/io/SpecialSystemDirectory.cpp6
-rw-r--r--xpcom/io/SpecialSystemDirectory.h3
-rw-r--r--xpcom/io/nsAppDirectoryServiceDefs.h29
-rw-r--r--xpcom/io/nsDirectoryService.cpp27
-rw-r--r--xpcom/io/nsDirectoryServiceAtomList.h4
-rw-r--r--xpcom/io/nsDirectoryServiceDefs.h4
-rw-r--r--xpcom/reflect/xptcall/xptcall.h2
-rw-r--r--xpcom/threads/ThreadStackHelper.cpp5
-rw-r--r--xpcom/threads/moz.build2
-rw-r--r--xpfe/appshell/nsAppShellService.cpp7
-rw-r--r--xpfe/appshell/nsContentTreeOwner.cpp5
-rw-r--r--xpfe/appshell/nsIXULBrowserWindow.idl6
-rw-r--r--xpfe/appshell/nsWindowMediator.cpp4
2243 files changed, 42861 insertions, 397183 deletions
diff --git a/.eslintrc.js b/.eslintrc.js
index a7a886292..3d3ad2b80 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -7,6 +7,9 @@ module.exports = {
],
"rules": {
"mozilla/import-globals": "warn",
+
+ // No (!foo in bar) or (!object instanceof Class)
+ "no-unsafe-negation": "error",
},
"env": {
"es6": true
diff --git a/CLOBBER b/CLOBBER
index 5dd4ee07f..ebe3d9f8c 100644
--- a/CLOBBER
+++ b/CLOBBER
@@ -22,4 +22,4 @@
# changes to stick? As of bug 928195, this shouldn't be necessary! Please
# don't change CLOBBER for WebIDL changes any more.
-Clobber for un-folding browsercomps \ No newline at end of file
+Clobber for updating ffvpx
diff --git a/README.md b/README.md
index 32cdf9b04..69f81ca3b 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,12 @@ applications.
This repository will contain at least one application to demonstrate and make use
of the platform: The Basilisk web browser, a close twin to Mozilla's Firefox.
+## Additional documentation
+
+Additional documentation relevant to this source code can be found in the `/docs`
+directory. This will contain relevant documentation regarding contributing,
+using and distributing this code and its binaries.
+
### A note about trademarks and branding
Although this repository is licensed under Mozilla Public License v2.0, the
diff --git a/accessible/base/nsAccessibilityService.h b/accessible/base/nsAccessibilityService.h
index 562150592..1f32fc677 100644
--- a/accessible/base/nsAccessibilityService.h
+++ b/accessible/base/nsAccessibilityService.h
@@ -336,12 +336,8 @@ void MaybeShutdownAccService(uint32_t aFormerConsumer);
inline bool
IPCAccessibilityActive()
{
-#ifdef MOZ_B2G
- return false;
-#else
return XRE_IsContentProcess() &&
mozilla::Preferences::GetBool("accessibility.ipc_architecture.enabled", true);
-#endif
}
/**
diff --git a/accessible/ipc/DocAccessibleParent.cpp b/accessible/ipc/DocAccessibleParent.cpp
index 0e9dfc080..4d368b1bc 100644
--- a/accessible/ipc/DocAccessibleParent.cpp
+++ b/accessible/ipc/DocAccessibleParent.cpp
@@ -492,32 +492,7 @@ bool
DocAccessibleParent::RecvGetWindowedPluginIAccessible(
const WindowsHandle& aHwnd, IAccessibleHolder* aPluginCOMProxy)
{
-#if defined(MOZ_CONTENT_SANDBOX)
- // We don't actually want the accessible object for aHwnd, but rather the
- // one that belongs to its child (see HTMLWin32ObjectAccessible).
- HWND childWnd = ::GetWindow(reinterpret_cast<HWND>(aHwnd), GW_CHILD);
- if (!childWnd) {
- // We're seeing this in the wild - the plugin is windowed but we no longer
- // have a window.
- return true;
- }
-
- IAccessible* rawAccPlugin = nullptr;
- HRESULT hr = ::AccessibleObjectFromWindow(childWnd, OBJID_WINDOW,
- IID_IAccessible,
- (void**)&rawAccPlugin);
- if (FAILED(hr)) {
- // This might happen if the plugin doesn't handle WM_GETOBJECT properly.
- // We should not consider that a failure.
- return true;
- }
-
- aPluginCOMProxy->Set(IAccessibleHolder::COMPtrType(rawAccPlugin));
-
- return true;
-#else
return false;
-#endif
}
#endif // defined(XP_WIN)
diff --git a/accessible/jsat/PointerAdapter.jsm b/accessible/jsat/PointerAdapter.jsm
index ff54976b7..1fb77646b 100644
--- a/accessible/jsat/PointerAdapter.jsm
+++ b/accessible/jsat/PointerAdapter.jsm
@@ -46,17 +46,6 @@ var PointerRelay = { // jshint ignore:line
'touchend' : true };
break;
- case 'gonk':
- this._eventsOfInterest = {
- 'touchstart' : true,
- 'touchmove' : true,
- 'touchend' : true,
- 'mousedown' : false,
- 'mousemove' : false,
- 'mouseup': false,
- 'click': false };
- break;
-
default:
// Desktop.
this._eventsOfInterest = {
diff --git a/accessible/windows/msaa/HTMLWin32ObjectAccessible.cpp b/accessible/windows/msaa/HTMLWin32ObjectAccessible.cpp
index 3644db68d..75a6f647b 100644
--- a/accessible/windows/msaa/HTMLWin32ObjectAccessible.cpp
+++ b/accessible/windows/msaa/HTMLWin32ObjectAccessible.cpp
@@ -62,25 +62,6 @@ HTMLWin32ObjectAccessible::HTMLWin32ObjectAccessible(void* aHwnd,
{
mHwnd = aHwnd;
if (mHwnd) {
-#if defined(MOZ_CONTENT_SANDBOX)
- if (XRE_IsContentProcess()) {
- DocAccessibleChild* ipcDoc = aDoc->IPCDoc();
- MOZ_ASSERT(ipcDoc);
- if (!ipcDoc) {
- return;
- }
-
- IAccessibleHolder proxyHolder;
- if (!ipcDoc->SendGetWindowedPluginIAccessible(
- reinterpret_cast<uintptr_t>(mHwnd), &proxyHolder)) {
- return;
- }
-
- mCOMProxy.reset(proxyHolder.Release());
- return;
- }
-#endif
-
// The plugin is not windowless. In this situation we use
// use its inner child owned by the plugin so that we don't get
// in an infinite loop, where the WM_GETOBJECT's get forwarded
@@ -92,14 +73,6 @@ HTMLWin32ObjectAccessible::HTMLWin32ObjectAccessible(void* aHwnd,
void
HTMLWin32ObjectAccessible::GetNativeInterface(void** aNativeAccessible)
{
-#if defined(MOZ_CONTENT_SANDBOX)
- if (XRE_IsContentProcess()) {
- RefPtr<IAccessible> addRefed = mCOMProxy.get();
- addRefed.forget(aNativeAccessible);
- return;
- }
-#endif
-
if (mHwnd) {
::AccessibleObjectFromWindow(static_cast<HWND>(mHwnd),
OBJID_WINDOW, IID_IAccessible,
diff --git a/accessible/windows/msaa/HTMLWin32ObjectAccessible.h b/accessible/windows/msaa/HTMLWin32ObjectAccessible.h
index 786d52191..b473061a2 100644
--- a/accessible/windows/msaa/HTMLWin32ObjectAccessible.h
+++ b/accessible/windows/msaa/HTMLWin32ObjectAccessible.h
@@ -8,10 +8,6 @@
#include "BaseAccessibles.h"
-#if defined(MOZ_CONTENT_SANDBOX)
-#include "mozilla/mscom/Ptr.h"
-#endif
-
struct IAccessible;
namespace mozilla {
@@ -59,9 +55,6 @@ public:
protected:
void* mHwnd;
-#if defined(MOZ_CONTENT_SANDBOX)
- mscom::ProxyUniquePtr<IAccessible> mCOMProxy;
-#endif
};
} // namespace a11y
diff --git a/aclocal.m4 b/aclocal.m4
index fe8419da2..a4c84a386 100644
--- a/aclocal.m4
+++ b/aclocal.m4
@@ -27,7 +27,6 @@ builtin(include, build/autoconf/icu.m4)dnl
builtin(include, build/autoconf/clang-plugin.m4)dnl
builtin(include, build/autoconf/alloc.m4)dnl
builtin(include, build/autoconf/ios.m4)dnl
-builtin(include, build/autoconf/jemalloc.m4)dnl
builtin(include, build/autoconf/sanitize.m4)dnl
MOZ_PROG_CHECKMSYS()
diff --git a/application/palemoon/app/Makefile.in b/application/palemoon/app/Makefile.in
index 6f9bbfaf0..c0f01212c 100644
--- a/application/palemoon/app/Makefile.in
+++ b/application/palemoon/app/Makefile.in
@@ -76,7 +76,7 @@ AB := $(firstword $(subst -, ,$(AB_CD)))
clean clobber repackage::
$(RM) -r $(dist_dest)
-MAC_BUNDLE_VERSION = $(shell $(PYTHON) $(srcdir)/macversion.py --version=$(MOZ_APP_VERSION) --buildid=$(DEPTH)/config/buildid)
+MAC_BUNDLE_VERSION = $(shell $(PYTHON) $(srcdir)/macversion.py --version=$(MOZ_APP_VERSION) --buildid=$(DEPTH)/buildid.h)
.PHONY: repackage
tools repackage:: $(PROGRAM)
diff --git a/application/palemoon/app/application.ini b/application/palemoon/app/application.ini
new file mode 100644
index 000000000..c64ed9079
--- /dev/null
+++ b/application/palemoon/app/application.ini
@@ -0,0 +1,50 @@
+#if MOZ_APP_STATIC_INI
+#ifdef MOZ_BUILD_APP_IS_BROWSER
+; This file is not used. If you modify it and want the application to use
+; your modifications, move it under the browser/ subdirectory and start with
+; the "-app /path/to/browser/application.ini" argument.
+#else
+; This file is not used. If you modify it and want the application to use
+; your modifications, start with the "-app /path/to/application.ini"
+; argument.
+#endif
+#endif
+#if 0
+; This Source Code Form is subject to the terms of the Mozilla Public
+; License, v. 2.0. If a copy of the MPL was not distributed with this
+; file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#endif
+#filter substitution
+#include @TOPOBJDIR@/buildid.h
+#include @TOPOBJDIR@/source-repo.h
+
+[App]
+# Vendor=@MOZ_APP_VENDOR@
+Vendor=Moonchild Productions
+# Name=@MOZ_APP_BASENAME@
+Name=Pale Moon
+RemotingName=@MOZ_APP_REMOTINGNAME@
+#ifdef MOZ_APP_DISPLAYNAME
+CodeName=@MOZ_APP_DISPLAYNAME@
+#endif
+Version=@MOZ_APP_VERSION@
+#ifdef MOZ_APP_PROFILE
+Profile=@MOZ_APP_PROFILE@
+#endif
+BuildID=@MOZ_BUILDID@
+#ifdef MOZ_SOURCE_REPO
+SourceRepository=@MOZ_SOURCE_REPO@
+#endif
+#ifdef MOZ_SOURCE_STAMP
+SourceStamp=@MOZ_SOURCE_STAMP@
+#endif
+ID=@MOZ_APP_ID@
+
+[Gecko]
+MinVersion=@GRE_MILESTONE@
+MaxVersion=@GRE_MILESTONE@
+
+[XRE]
+#ifdef MOZ_PROFILE_MIGRATOR
+EnableProfileMigrator=1
+#endif \ No newline at end of file
diff --git a/application/palemoon/app/macversion.py b/application/palemoon/app/macversion.py
index 8c360368e..839aac1ff 100644
--- a/application/palemoon/app/macversion.py
+++ b/application/palemoon/app/macversion.py
@@ -28,7 +28,7 @@ if not options.version:
# builds), but also so that newly-built older versions (e.g. beta build) aren't
# considered "newer" than previously-built newer versions (e.g. a trunk nightly)
-buildid = open(options.buildid, 'r').read()
+define, MOZ_BUILDID, buildid = open(options.buildid, 'r').read().split()
# extract only the major version (i.e. "14" from "14.0b1")
majorVersion = re.match(r'^(\d+)[^\d].*', options.version).group(1)
diff --git a/application/palemoon/app/nsBrowserApp.cpp b/application/palemoon/app/nsBrowserApp.cpp
index 5b866d6b4..8b0613528 100644
--- a/application/palemoon/app/nsBrowserApp.cpp
+++ b/application/palemoon/app/nsBrowserApp.cpp
@@ -26,9 +26,6 @@
#ifdef XP_WIN
#define XRE_WANT_ENVIRON
#define strcasecmp _stricmp
-#ifdef MOZ_SANDBOX
-#include "mozilla/sandboxing/SandboxInitialization.h"
-#endif
#endif
#include "BinaryPath.h"
@@ -38,8 +35,7 @@
#include "mozilla/Telemetry.h"
#include "mozilla/WindowsDllBlocklist.h"
-#if !defined(MOZ_WIDGET_COCOA) && !defined(MOZ_WIDGET_ANDROID) \
- && !(defined(XP_LINUX) && defined(MOZ_SANDBOX))
+#if !defined(MOZ_WIDGET_COCOA) && !defined(MOZ_WIDGET_ANDROID)
#define MOZ_BROWSER_CAN_BE_CONTENTPROC
#include "../../ipc/contentproc/plugin-container.cpp"
#endif
@@ -201,13 +197,7 @@ static int do_main(int argc, char* argv[], char* envp[], nsIFile *xreDirectory)
argv[i] = argv[i + 1];
}
- XREShellData shellData;
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- shellData.sandboxBrokerServices =
- sandboxing::GetInitializedBrokerServices();
-#endif
-
- return XRE_XPCShellMain(--argc, argv, envp, &shellData);
+ return XRE_XPCShellMain(--argc, argv, envp);
}
if (appini) {
@@ -257,18 +247,6 @@ static int do_main(int argc, char* argv[], char* envp[], nsIFile *xreDirectory)
DllBlocklist_CheckStatus() ? NS_XRE_DLL_BLOCKLIST_ENABLED : 0;
#endif
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- sandbox::BrokerServices* brokerServices =
- sandboxing::GetInitializedBrokerServices();
-#if defined(MOZ_CONTENT_SANDBOX)
- if (!brokerServices) {
- Output("Couldn't initialize the broker services.\n");
- return 255;
- }
-#endif
- appData.sandboxBrokerServices = brokerServices;
-#endif
-
#ifdef LIBFUZZER
if (getenv("LIBFUZZER"))
XRE_LibFuzzerSetMain(argc, argv, libfuzzer_main);
@@ -370,15 +348,6 @@ int main(int argc, char* argv[], char* envp[])
// We are launching as a content process, delegate to the appropriate
// main
if (argc > 1 && IsArg(argv[1], "contentproc")) {
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- // We need to initialize the sandbox TargetServices before InitXPCOMGlue
- // because we might need the sandbox broker to give access to some files.
- if (IsSandboxedProcess() && !sandboxing::GetInitializedTargetServices()) {
- Output("Failed to initialize the sandbox target services.");
- return 255;
- }
-#endif
-
nsresult rv = InitXPCOMGlue(argv[0], nullptr);
if (NS_FAILED(rv)) {
return 255;
diff --git a/application/palemoon/app/profile/palemoon.js b/application/palemoon/app/profile/palemoon.js
index ee4a95d38..90b4949b9 100644
--- a/application/palemoon/app/profile/palemoon.js
+++ b/application/palemoon/app/profile/palemoon.js
@@ -236,6 +236,15 @@ pref("general.useragent.complexOverride.moodle", false); // bug 797703
// At startup, check if we're the default browser and prompt user if not.
pref("browser.shell.checkDefaultBrowser", true);
pref("browser.shell.shortcutFavicons",true);
+pref("browser.shell.mostRecentDateSetAsDefault", "");
+#ifdef RELEASE_OR_BETA
+pref("browser.shell.skipDefaultBrowserCheckOnFirstRun", false);
+#else
+pref("browser.shell.skipDefaultBrowserCheckOnFirstRun", true);
+#endif
+pref("browser.shell.skipDefaultBrowserCheck", true);
+pref("browser.shell.defaultBrowserCheckCount", 0);
+pref("browser.defaultbrowser.notificationbar", false);
// 0 = blank, 1 = home (browser.startup.homepage), 2 = last visited page, 3 = resume previous browser session
// The behavior of option 3 is detailed at: http://wiki.mozilla.org/Session_Restore
@@ -756,6 +765,7 @@ pref("goanna.handlerService.allowRegisterFromDifferentHost", false);
pref("browser.geolocation.warning.infoURL", "http://www.palemoon.org/info-url/geolocation.shtml");
pref("browser.mixedcontent.warning.infoURL", "http://www.palemoon.org/info-url/mixedcontent.shtml");
+pref("browser.push.warning.infoURL", "https://www.mozilla.org/%LOCALE%/firefox/push/");
pref("browser.EULA.version", 3);
pref("browser.rights.version", 3);
@@ -1048,11 +1058,6 @@ pref("browser.newtabpage.rows", 4);
// Enable the DOM fullscreen API.
pref("full-screen-api.enabled", true);
-// True if the fullscreen API requires approval upon a domain entering fullscreen.
-// Domains that have already had fullscreen permission granted won't re-request
-// approval.
-pref("full-screen-api.approval-required", true);
-
// about:permissions
// Maximum number of sites to return from the places database.
// 0-100 (currently)
diff --git a/application/palemoon/base/content/browser-fullScreen.js b/application/palemoon/base/content/browser-fullScreen.js
index 400340e77..6afd247be 100644
--- a/application/palemoon/base/content/browser-fullScreen.js
+++ b/application/palemoon/base/content/browser-fullScreen.js
@@ -5,16 +5,9 @@
var FullScreen = {
_XULNS: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
- get _fullScrToggler() {
- delete this._fullScrToggler;
- return this._fullScrToggler = document.getElementById("fullscr-toggler");
- },
- toggle: function (event) {
- var enterFS = window.fullScreen;
- // We get the fullscreen event _before_ the window transitions into or out of FS mode.
- if (event && event.type == "fullscreen")
- enterFS = !enterFS;
+ toggle: function () {
+ var enterFS = window.fullScreen;
// Toggle the View:FullScreen command, which controls elements like the
// fullscreen menuitem, menubars, and the appmenu.
@@ -31,6 +24,12 @@ var FullScreen = {
document.getElementById("exitFullScreenItem").hidden = !enterFS;
#endif
+ if (!this._fullScrToggler) {
+ this._fullScrToggler = document.getElementById("fullscr-toggler");
+ this._fullScrToggler.addEventListener("mouseover", this._expandCallback, false);
+ this._fullScrToggler.addEventListener("dragenter", this._expandCallback, false);
+ }
+
// On OS X Lion we don't want to hide toolbars when entering fullscreen, unless
// we're entering DOM fullscreen, in which case we should hide the toolbars.
// If we're leaving fullscreen, then we'll go through the exit code below to
@@ -50,36 +49,17 @@ var FullScreen = {
this.showXULChrome("toolbar", !enterFS);
if (enterFS) {
- // Add a tiny toolbar to receive mouseover and dragenter events, and provide affordance.
- // This will help simulate the "collapse" metaphor while also requiring less code and
- // events than raw listening of mouse coords. We don't add the toolbar in DOM full-screen
- // mode, only browser full-screen mode.
- if (!document.mozFullScreen) {
- this._fullScrToggler.addEventListener("mouseover", this._expandCallback, false);
- this._fullScrToggler.addEventListener("dragenter", this._expandCallback, false);
- }
- if (gPrefService.getBoolPref("browser.fullscreen.autohide"))
- gBrowser.mPanelContainer.addEventListener("mousemove",
- this._collapseCallback, false);
-
document.addEventListener("keypress", this._keyToggleCallback, false);
document.addEventListener("popupshown", this._setPopupOpen, false);
document.addEventListener("popuphidden", this._setPopupOpen, false);
+ this._shouldAnimate = true;
// We don't animate the toolbar collapse if in DOM full-screen mode,
// as the size of the content area would still be changing after the
// mozfullscreenchange event fired, which could confuse content script.
- this._shouldAnimate = !document.mozFullScreen;
- this.mouseoverToggle(false);
-
- // Autohide prefs
- gPrefService.addObserver("browser.fullscreen", this, false);
+ this.hideNavToolbox(document.mozFullScreen);
}
else {
- // The user may quit fullscreen during an animation
- this._cancelAnimation();
- gNavToolbox.style.marginTop = "";
- if (this._isChromeCollapsed)
- this.mouseoverToggle(true);
+ this.showNavToolbox(false);
// This is needed if they use the context menu to quit fullscreen
this._isPopupOpen = false;
@@ -111,7 +91,7 @@ var FullScreen = {
if (!document.mozFullScreen)
return;
- // However, if we receive a "MozEnteredDomFullScreen" event for a document
+ // However, if we receive a "MozDOMFullscreen:NewOrigin" event for a document
// which is not a subdocument of a currently active (ie. visible) browser
// or iframe, we know that we've switched to a different frame since the
// request to enter full-screen was made, so we should exit full-screen
@@ -152,26 +132,16 @@ var FullScreen = {
// Cancel any "hide the toolbar" animation which is in progress, and make
// the toolbar hide immediately.
- this._cancelAnimation();
- this.mouseoverToggle(false);
-
- // Remove listeners on the full-screen toggler, so that mouseover
- // the top of the screen will not cause the toolbar to re-appear.
- this._fullScrToggler.removeEventListener("mouseover", this._expandCallback, false);
- this._fullScrToggler.removeEventListener("dragenter", this._expandCallback, false);
+ this.hideNavToolbox(true);
},
cleanup: function () {
- if (window.fullScreen) {
- gBrowser.mPanelContainer.removeEventListener("mousemove",
- this._collapseCallback, false);
+ if (!window.fullScreen) {
+ MousePosTracker.removeListener(this);
document.removeEventListener("keypress", this._keyToggleCallback, false);
document.removeEventListener("popupshown", this._setPopupOpen, false);
document.removeEventListener("popuphidden", this._setPopupOpen, false);
- gPrefService.removeObserver("browser.fullscreen", this);
- this._fullScrToggler.removeEventListener("mouseover", this._expandCallback, false);
- this._fullScrToggler.removeEventListener("dragenter", this._expandCallback, false);
this.cancelWarning();
gBrowser.tabContainer.removeEventListener("TabOpen", this.exitDomFullScreen);
gBrowser.tabContainer.removeEventListener("TabClose", this.exitDomFullScreen);
@@ -182,40 +152,30 @@ var FullScreen = {
}
},
- observe: function(aSubject, aTopic, aData)
+ getMouseTargetRect: function()
{
- if (aData == "browser.fullscreen.autohide") {
- if (gPrefService.getBoolPref("browser.fullscreen.autohide")) {
- gBrowser.mPanelContainer.addEventListener("mousemove",
- this._collapseCallback, false);
- }
- else {
- gBrowser.mPanelContainer.removeEventListener("mousemove",
- this._collapseCallback, false);
- }
- }
+ return this._mouseTargetRect;
},
// Event callbacks
_expandCallback: function()
{
- FullScreen.mouseoverToggle(true);
+ FullScreen.showNavToolbox();
},
- _collapseCallback: function()
+ onMouseEnter: function()
{
- FullScreen.mouseoverToggle(false);
+ FullScreen.hideNavToolbox();
},
_keyToggleCallback: function(aEvent)
{
// if we can use the keyboard (eg Ctrl+L or Ctrl+E) to open the toolbars, we
// should provide a way to collapse them too.
if (aEvent.keyCode == aEvent.DOM_VK_ESCAPE) {
- FullScreen._shouldAnimate = false;
- FullScreen.mouseoverToggle(false, true);
+ FullScreen.hideNavToolbox(true);
}
// F6 is another shortcut to the address bar, but its not covered in OpenLocation()
else if (aEvent.keyCode == aEvent.DOM_VK_F6)
- FullScreen.mouseoverToggle(true);
+ FullScreen.showNavToolbox();
},
// Checks whether we are allowed to collapse the chrome
@@ -269,47 +229,6 @@ var FullScreen = {
// Animate the toolbars disappearing
_shouldAnimate: true,
- _isAnimating: false,
- _animationTimeout: 0,
- _animationHandle: 0,
- _animateUp: function() {
- // check again, the user may have done something before the animation was due to start
- if (!window.fullScreen || !this._safeToCollapse(false)) {
- this._isAnimating = false;
- this._shouldAnimate = true;
- return;
- }
-
- this._animateStartTime = window.mozAnimationStartTime;
- if (!this._animationHandle)
- this._animationHandle = window.mozRequestAnimationFrame(this);
- },
-
- sample: function (timeStamp) {
- const duration = 1500;
- const timePassed = timeStamp - this._animateStartTime;
- const pos = timePassed >= duration ? 1 :
- 1 - Math.pow(1 - timePassed / duration, 4);
-
- if (pos >= 1) {
- // We've animated enough
- this._cancelAnimation();
- gNavToolbox.style.marginTop = "";
- this.mouseoverToggle(false);
- return;
- }
-
- gNavToolbox.style.marginTop = (gNavToolbox.boxObject.height * pos * -1) + "px";
- this._animationHandle = window.mozRequestAnimationFrame(this);
- },
-
- _cancelAnimation: function() {
- window.cancelAnimationFrame(this._animationHandle);
- this._animationHandle = 0;
- clearTimeout(this._animationTimeout);
- this._isAnimating = false;
- this._shouldAnimate = false;
- },
cancelWarning: function(event) {
if (!this.warningBox)
@@ -328,67 +247,20 @@ var FullScreen = {
this.warningBox.setAttribute("hidden", true);
this.warningBox.removeAttribute("fade-warning-out");
- this.warningBox.removeAttribute("obscure-browser");
this.warningBox = null;
},
- setFullscreenAllowed: function(isApproved) {
- // The "remember decision" checkbox is hidden when showing for documents that
- // the permission manager can't handle (documents with URIs without a host).
- // We simply require those to be approved every time instead.
- let rememberCheckbox = document.getElementById("full-screen-remember-decision");
- let uri = this.fullscreenDoc.nodePrincipal.URI;
- if (!rememberCheckbox.hidden) {
- if (rememberCheckbox.checked)
- Services.perms.add(uri,
- "fullscreen",
- isApproved ? Services.perms.ALLOW_ACTION : Services.perms.DENY_ACTION,
- Services.perms.EXPIRE_NEVER);
- else if (isApproved) {
- // The user has only temporarily approved fullscren for this fullscreen
- // session only. Add the permission (so Goanna knows to approve any further
- // fullscreen requests for this host in this fullscreen session) but add
- // a listener to revoke the permission when the chrome document exits
- // fullscreen.
- Services.perms.add(uri,
- "fullscreen",
- Services.perms.ALLOW_ACTION,
- Services.perms.EXPIRE_SESSION);
- let host = uri.host;
- var onFullscreenchange = function onFullscreenchange(event) {
- if (event.target == document && document.mozFullScreenElement == null) {
- // The chrome document has left fullscreen. Remove the temporary permission grant.
- Services.perms.remove(host, "fullscreen");
- document.removeEventListener("mozfullscreenchange", onFullscreenchange);
- }
- }
- document.addEventListener("mozfullscreenchange", onFullscreenchange);
- }
- }
- if (this.warningBox)
- this.warningBox.setAttribute("fade-warning-out", "true");
- // If the document has been granted fullscreen, notify Goanna so it can resume
- // any pending pointer lock requests, otherwise exit fullscreen; the user denied
- // the fullscreen request.
- if (isApproved)
- Services.obs.notifyObservers(this.fullscreenDoc, "fullscreen-approved", "");
- else
- document.mozCancelFullScreen();
- },
-
warningBox: null,
warningFadeOutTimeout: null,
fullscreenDoc: null,
- // Shows the fullscreen approval UI, or if the domain has already been approved
- // for fullscreen, shows a warning that the site has entered fullscreen for a short
- // duration.
+ // Shows a warning that the site has entered fullscreen for a short duration.
showWarning: function(targetDoc) {
- if (!document.mozFullScreen ||
- !gPrefService.getBoolPref("full-screen-api.approval-required"))
+ let timeout = gPrefService.getIntPref("full-screen-api.warning.timeout");
+ if (!document.mozFullScreen || timeout <= 0)
return;
- // Set the strings on the fullscreen approval UI.
+ // Set the strings on the fullscreen warning UI.
this.fullscreenDoc = targetDoc;
let uri = this.fullscreenDoc.nodePrincipal.URI;
let host = null;
@@ -396,11 +268,8 @@ var FullScreen = {
host = uri.host;
} catch (e) { }
let hostLabel = document.getElementById("full-screen-domain-text");
- let rememberCheckbox = document.getElementById("full-screen-remember-decision");
- let isApproved = false;
if (host) {
- // Document's principal's URI has a host. Display a warning including the hostname and
- // show UI to enable the user to permanently grant this host permission to enter fullscreen.
+ // Document's principal's URI has a host. Display a warning including the hostname.
let utils = {};
Cu.import("resource://gre/modules/DownloadUtils.jsm", utils);
let displayHost = utils.DownloadUtils.getURIHost(uri.spec)[0];
@@ -408,17 +277,8 @@ var FullScreen = {
hostLabel.textContent = bundle.formatStringFromName("fullscreen.entered", [displayHost], 1);
hostLabel.removeAttribute("hidden");
-
- rememberCheckbox.label = bundle.formatStringFromName("fullscreen.rememberDecision", [displayHost], 1);
- rememberCheckbox.checked = false;
- rememberCheckbox.removeAttribute("hidden");
-
- // Note we only allow documents whose principal's URI has a host to
- // store permission grants.
- isApproved = Services.perms.testPermission(uri, "fullscreen") == Services.perms.ALLOW_ACTION;
} else {
hostLabel.setAttribute("hidden", "true");
- rememberCheckbox.setAttribute("hidden", "true");
}
// Note: the warning box can be non-null if the warning box from the previous request
@@ -436,77 +296,77 @@ var FullScreen = {
this.warningBox.removeAttribute("fade-warning-out");
}
- // If fullscreen mode has not yet been approved for the fullscreen
- // document's domain, show the approval UI and don't auto fade out the
- // fullscreen warning box. Otherwise, we're just notifying of entry into
- // fullscreen mode. Note if the resource's host is null, we must be
- // showing a local file or a local data URI, and we require explicit
- // approval every time.
- let authUI = document.getElementById("full-screen-approval-pane");
- if (isApproved) {
- authUI.setAttribute("hidden", "true");
- this.warningBox.removeAttribute("obscure-browser");
- } else {
- // Partially obscure the <browser> element underneath the approval UI.
- this.warningBox.setAttribute("obscure-browser", "true");
- authUI.removeAttribute("hidden");
+ // Set a timeout to fade the warning out after a few moments.
+ this.warningFadeOutTimeout = setTimeout(() => {
+ if (this.warningBox) {
+ this.warningBox.setAttribute("fade-warning-out", "true");
+ }
+ }, timeout);
+ },
+
+ showNavToolbox: function(trackMouse = true) {
+ this._fullScrToggler.hidden = true;
+ gNavToolbox.removeAttribute("fullscreenShouldAnimate");
+ gNavToolbox.style.marginTop = "";
+
+ if (!this._isChromeCollapsed) {
+ return;
}
- // If we're not showing the fullscreen approval UI, we're just notifying the user
- // of the transition, so set a timeout to fade the warning out after a few moments.
- if (isApproved)
- this.warningFadeOutTimeout =
- setTimeout(
- function() {
- if (this.warningBox)
- this.warningBox.setAttribute("fade-warning-out", "true");
- }.bind(this),
- 3000);
+ // Track whether mouse is near the toolbox
+ this._isChromeCollapsed = false;
+ if (trackMouse) {
+ let rect = gBrowser.mPanelContainer.getBoundingClientRect();
+ this._mouseTargetRect = {
+ top: rect.top + 50,
+ bottom: rect.bottom,
+ left: rect.left,
+ right: rect.right
+ };
+ MousePosTracker.addListener(this);
+ }
},
- mouseoverToggle: function(aShow, forceHide)
- {
- // Don't do anything if:
- // a) we're already in the state we want,
- // b) we're animating and will become collapsed soon, or
- // c) we can't collapse because it would be undesirable right now
- if (aShow != this._isChromeCollapsed || (!aShow && this._isAnimating) ||
- (!aShow && !this._safeToCollapse(forceHide)))
+ hideNavToolbox: function(forceHide = false) {
+ this._fullScrToggler.hidden = document.mozFullScreen;
+ if (this._isChromeCollapsed) {
+ if (forceHide) {
+ gNavToolbox.removeAttribute("fullscreenShouldAnimate");
+ }
return;
+ }
+ if (!this._safeToCollapse(forceHide)) {
+ this._fullScrToggler.hidden = true;
+ return;
+ }
// browser.fullscreen.animateUp
// 0 - never animate up
// 1 - animate only for first collapse after entering fullscreen (default for perf's sake)
// 2 - animate every time it collapses
- if (gPrefService.getIntPref("browser.fullscreen.animateUp") == 0)
+ let animateUp = gPrefService.getIntPref("browser.fullscreen.animateUp");
+ if (animateUp == 0) {
this._shouldAnimate = false;
-
- if (!aShow && this._shouldAnimate) {
- this._isAnimating = true;
- this._shouldAnimate = false;
- this._animationTimeout = setTimeout(this._animateUp.bind(this), 800);
- return;
- }
-
- // The chrome is collapsed so don't spam needless mousemove events
- if (aShow) {
- gBrowser.mPanelContainer.addEventListener("mousemove",
- this._collapseCallback, false);
+ } else if (animateUp == 2) {
+ this._shouldAnimate = true;
}
- else {
- gBrowser.mPanelContainer.removeEventListener("mousemove",
- this._collapseCallback, false);
+ if (this._shouldAnimate && !forceHide) {
+ gNavToolbox.setAttribute("fullscreenShouldAnimate", true);
+ this._shouldAnimate = false;
+ // Hide the fullscreen toggler until the transition ends.
+ let listener = () => {
+ gNavToolbox.removeEventListener("transitionend", listener, true);
+ if (this._isChromeCollapsed)
+ this._fullScrToggler.hidden = false;
+ };
+ gNavToolbox.addEventListener("transitionend", listener, true);
+ this._fullScrToggler.hidden = true;
}
- // Hiding/collapsing the toolbox interferes with the tab bar's scrollbox,
- // so we just move it off-screen instead. See bug 430687.
gNavToolbox.style.marginTop =
- aShow ? "" : -gNavToolbox.getBoundingClientRect().height + "px";
-
- this._fullScrToggler.collapsed = aShow;
- this._isChromeCollapsed = !aShow;
- if (gPrefService.getIntPref("browser.fullscreen.animateUp") == 2)
- this._shouldAnimate = true;
+ -gNavToolbox.getBoundingClientRect().height + "px";
+ this._isChromeCollapsed = true;
+ MousePosTracker.removeListener(this);
},
showXULChrome: function(aTag, aShow)
diff --git a/application/palemoon/base/content/browser-plugins.js b/application/palemoon/base/content/browser-plugins.js
index 769ac6d8a..838268203 100644
--- a/application/palemoon/base/content/browser-plugins.js
+++ b/application/palemoon/base/content/browser-plugins.js
@@ -470,28 +470,12 @@ var gPluginHandler = {
}
},
- // Match the behaviour of nsPermissionManager
- _getHostFromPrincipal: function PH_getHostFromPrincipal(principal) {
- if (!principal.URI || principal.URI.schemeIs("moz-nullprincipal")) {
- return "(null)";
- }
-
- try {
- if (principal.URI.host)
- return principal.URI.host;
- } catch (e) {}
-
- return principal.origin;
- },
-
_makeCenterActions: function PH_makeCenterActions(notification) {
let contentWindow = notification.browser.contentWindow;
let cwu = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
let principal = contentWindow.document.nodePrincipal;
- // This matches the behavior of nsPermssionManager, used for display purposes only
- let principalHost = this._getHostFromPrincipal(principal);
let centerActions = [];
let pluginsFound = new Set();
@@ -517,11 +501,11 @@ var gPluginHandler = {
let permissionObj = Services.perms.
getPermissionObject(principal, pluginInfo.permissionString, false);
if (permissionObj) {
- pluginInfo.pluginPermissionHost = permissionObj.host;
+ pluginInfo.pluginPermissionPrePath = permissionObj.principal.originNoSuffix;
pluginInfo.pluginPermissionType = permissionObj.expireType;
}
else {
- pluginInfo.pluginPermissionHost = principalHost;
+ pluginInfo.pluginPermissionPrePath = principal.originNoSuffix;
pluginInfo.pluginPermissionType = undefined;
}
diff --git a/application/palemoon/base/content/browser.css b/application/palemoon/base/content/browser.css
index 658655970..a2970aefc 100644
--- a/application/palemoon/base/content/browser.css
+++ b/application/palemoon/base/content/browser.css
@@ -504,6 +504,7 @@ window[chromehidden~="toolbar"] toolbar:not(.toolbar-primary):not(#nav-bar):not(
width: 100%;
height: 100%;
z-index: 2147483647 !important;
+ pointer-events: none;
}
#full-screen-warning-container[fade-warning-out] {
@@ -512,22 +513,13 @@ window[chromehidden~="toolbar"] toolbar:not(.toolbar-primary):not(#nav-bar):not(
opacity: 0.0;
}
-/* When the modal fullscreen approval UI is showing, don't allow interaction
- with the page, but when we're just showing the warning upon entering
- fullscreen on an already approved page, do allow interaction with the page.
- */
-#full-screen-warning-container:not([obscure-browser]) {
- pointer-events: none;
-}
-
#full-screen-warning-message {
/* We must specify a max-width, otherwise word-wrap:break-word doesn't
work in descendant <description> and <label> elements. Bug 630864. */
max-width: 800px;
}
-#full-screen-domain-text,
-#full-screen-remember-decision > .checkbox-label-box > .checkbox-label {
+#full-screen-domain-text {
word-wrap: break-word;
/* We must specify a min-width, otherwise word-wrap:break-word doesn't work. Bug 630864. */
min-width: 1px;
@@ -760,3 +752,8 @@ toolbarbutton[pmkit-button="true"] > .toolbarbutton-badge-stack > .toolbarbutton
#main-window[inFullscreen] #high-priority-global-notificationbox {
visibility: collapse;
}
+
+#navigator-toolbox[fullscreenShouldAnimate] {
+ transition: 0.7s margin-top ease-out;
+ transition-delay: 0.8s;
+}
diff --git a/application/palemoon/base/content/browser.js b/application/palemoon/base/content/browser.js
index c9f0aa4aa..c1643caa4 100644
--- a/application/palemoon/base/content/browser.js
+++ b/application/palemoon/base/content/browser.js
@@ -10,6 +10,9 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource:///modules/RecentWindow.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Task",
+ "resource://gre/modules/Task.jsm");
+
XPCOMUtils.defineLazyModuleGetter(this, "CharsetMenu",
"resource:///modules/CharsetMenu.jsm");
@@ -83,14 +86,8 @@ this.__defineSetter__("AddonManager", function (val) {
return this.AddonManager = val;
});
-this.__defineGetter__("PluralForm", function() {
- Cu.import("resource://gre/modules/PluralForm.jsm");
- return this.PluralForm;
-});
-this.__defineSetter__("PluralForm", function (val) {
- delete this.PluralForm;
- return this.PluralForm = val;
-});
+XPCOMUtils.defineLazyModuleGetter(this, "PluralForm",
+ "resource://gre/modules/PluralForm.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "AboutHomeUtils",
"resource:///modules/AboutHomeUtils.jsm");
@@ -125,7 +122,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils",
XPCOMUtils.defineLazyModuleGetter(this, "FormValidationHandler",
"resource:///modules/FormValidationHandler.jsm");
-let gInitialPages = [
+var gInitialPages = [
"about:blank",
"about:newtab",
"about:home",
@@ -993,12 +990,23 @@ var gBrowserInit = {
gBrowser.swapBrowsersAndCloseOther(gBrowser.selectedTab, uriToLoad);
}
- // window.arguments[2]: referrer (nsIURI)
+ // window.arguments[2]: referrer (nsIURI | string)
// [3]: postData (nsIInputStream)
// [4]: allowThirdPartyFixup (bool)
+ // [5]: referrerPolicy (int)
else if (window.arguments.length >= 3) {
- loadURI(uriToLoad, window.arguments[2], window.arguments[3] || null,
- window.arguments[4] || false);
+ let referrerURI = window.arguments[2];
+ if (typeof(referrerURI) == "string") {
+ try {
+ referrerURI = makeURI(referrerURI);
+ } catch (e) {
+ referrerURI = null;
+ }
+ }
+ let referrerPolicy = (window.arguments[5] != undefined ?
+ window.arguments[5] : Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT);
+ loadURI(uriToLoad, referrerURI, window.arguments[3] || null,
+ window.arguments[4] || false, referrerPolicy);
window.focus();
}
// Note: loadOneOrMoreURIs *must not* be called if window.arguments.length >= 3.
@@ -1149,7 +1157,7 @@ var gBrowserInit = {
// Called when we enter DOM full-screen mode. Note we can already be in browser
// full-screen mode when we enter DOM full-screen mode.
- window.addEventListener("MozEnteredDomFullscreen", onMozEnteredDomFullscreen, true);
+ window.addEventListener("MozDOMFullscreen:NewOrigin", onMozEnteredDomFullscreen, true);
if (window.fullScreen)
onFullScreen();
@@ -1733,7 +1741,7 @@ function loadOneOrMoreURIs(aURIString)
function focusAndSelectUrlBar() {
if (gURLBar) {
if (window.fullScreen)
- FullScreen.mouseoverToggle(true);
+ FullScreen.showNavToolbox();
gURLBar.select();
if (document.activeElement == gURLBar.inputField)
@@ -1886,7 +1894,7 @@ function BrowserTryToCloseWindow()
window.close(); // WindowIsClosing does all the necessary checks
}
-function loadURI(uri, referrer, postData, allowThirdPartyFixup) {
+function loadURI(uri, referrer, postData, allowThirdPartyFixup, referrerPolicy) {
if (postData === undefined)
postData = null;
@@ -1897,92 +1905,135 @@ function loadURI(uri, referrer, postData, allowThirdPartyFixup) {
}
try {
- gBrowser.loadURIWithFlags(uri, flags, referrer, null, postData);
+ gBrowser.loadURIWithFlags(uri, {
+ flags: flags,
+ referrerURI: referrer,
+ referrerPolicy: referrerPolicy,
+ postData: postData,
+ });
} catch (e) {}
}
-function getShortcutOrURI(aURL, aPostDataRef, aMayInheritPrincipal) {
- // Initialize outparam to false
- if (aMayInheritPrincipal)
- aMayInheritPrincipal.value = false;
+/**
+ * Given a urlbar value, discerns between URIs, keywords and aliases.
+ *
+ * @param url
+ * The urlbar value.
+ * @param callback (optional, deprecated)
+ * The callback function invoked when done. This parameter is
+ * deprecated, please use the Promise that is returned.
+ *
+ * @return Promise<{ postData, url, mayInheritPrincipal }>
+ */
+function getShortcutOrURIAndPostData(url, callback = null) {
+ if (callback) {
+ Deprecated.warning("Please use the Promise returned by " +
+ "getShortcutOrURIAndPostData() instead of passing a " +
+ "callback",
+ "https://bugzilla.mozilla.org/show_bug.cgi?id=1100294");
+ }
- var shortcutURL = null;
- var keyword = aURL;
- var param = "";
+ return Task.spawn(function* () {
+ let mayInheritPrincipal = false;
+ let postData = null;
+ let shortcutURL = null;
+ let keyword = url;
+ let param = "";
- var offset = aURL.indexOf(" ");
- if (offset > 0) {
- keyword = aURL.substr(0, offset);
- param = aURL.substr(offset + 1);
- }
+ let offset = url.indexOf(" ");
+ if (offset > 0) {
+ keyword = url.substr(0, offset);
+ param = url.substr(offset + 1);
+ }
- if (!aPostDataRef)
- aPostDataRef = {};
+ let engine = Services.search.getEngineByAlias(keyword);
+ if (engine) {
+ let submission = engine.getSubmission(param, null, "keyword");
+ postData = submission.postData;
+ return { postData: submission.postData, url: submission.uri.spec,
+ mayInheritPrincipal };
+ }
- var engine = Services.search.getEngineByAlias(keyword);
- if (engine) {
- var submission = engine.getSubmission(param);
- aPostDataRef.value = submission.postData;
- return submission.uri.spec;
- }
+ let entry = yield PlacesUtils.keywords.fetch(keyword);
+ if (entry) {
+ shortcutURL = entry.url.href;
+ postData = entry.postData;
+ }
- [shortcutURL, aPostDataRef.value] =
- PlacesUtils.getURLAndPostDataForKeyword(keyword);
+ if (!shortcutURL) {
+ return { postData, url, mayInheritPrincipal };
+ }
- if (!shortcutURL)
- return aURL;
+ let escapedPostData = "";
+ if (postData)
+ escapedPostData = unescape(postData);
- var postData = "";
- if (aPostDataRef.value)
- postData = unescape(aPostDataRef.value);
+ if (/%s/i.test(shortcutURL) || /%s/i.test(escapedPostData)) {
+ let charset = "";
+ const re = /^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/;
+ let matches = shortcutURL.match(re);
- if (/%s/i.test(shortcutURL) || /%s/i.test(postData)) {
- var charset = "";
- const re = /^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/;
- var matches = shortcutURL.match(re);
- if (matches)
- [, shortcutURL, charset] = matches;
- else {
- // Try to get the saved character-set.
- try {
- // makeURI throws if URI is invalid.
- // Will return an empty string if character-set is not found.
- charset = PlacesUtils.history.getCharsetForURI(makeURI(shortcutURL));
- } catch (e) {}
- }
+ if (matches) {
+ [, shortcutURL, charset] = matches;
+ } else {
+ let uri;
+ try {
+ // makeURI() throws if URI is invalid.
+ uri = makeURI(shortcutURL);
+ } catch (ex) {}
+
+ if (uri) {
+ // Try to get the saved character-set.
+ // Will return an empty string if character-set is not found.
+ charset = yield PlacesUtils.getCharsetForURI(uri);
+ }
+ }
- // encodeURIComponent produces UTF-8, and cannot be used for other charsets.
- // escape() works in those cases, but it doesn't uri-encode +, @, and /.
- // Therefore we need to manually replace these ASCII characters by their
- // encodeURIComponent result, to match the behavior of nsEscape() with
- // url_XPAlphas
- var encodedParam = "";
- if (charset && charset != "UTF-8")
- encodedParam = escape(convertFromUnicode(charset, param)).
- replace(/[+@\/]+/g, encodeURIComponent);
- else // Default charset is UTF-8
- encodedParam = encodeURIComponent(param);
+ // encodeURIComponent produces UTF-8, and cannot be used for other charsets.
+ // escape() works in those cases, but it doesn't uri-encode +, @, and /.
+ // Therefore we need to manually replace these ASCII characters by their
+ // encodeURIComponent result, to match the behavior of nsEscape() with
+ // url_XPAlphas
+ let encodedParam = "";
+ if (charset && charset != "UTF-8")
+ encodedParam = escape(convertFromUnicode(charset, param)).
+ replace(/[+@\/]+/g, encodeURIComponent);
+ else // Default charset is UTF-8
+ encodedParam = encodeURIComponent(param);
- shortcutURL = shortcutURL.replace(/%s/g, encodedParam).replace(/%S/g, param);
+ shortcutURL = shortcutURL.replace(/%s/g, encodedParam).replace(/%S/g, param);
- if (/%s/i.test(postData)) // POST keyword
- aPostDataRef.value = getPostDataStream(postData, param, encodedParam,
- "application/x-www-form-urlencoded");
- }
- else if (param) {
- // This keyword doesn't take a parameter, but one was provided. Just return
- // the original URL.
- aPostDataRef.value = null;
+ if (/%s/i.test(escapedPostData)) // POST keyword
+ postData = getPostDataStream(escapedPostData, param, encodedParam,
+ "application/x-www-form-urlencoded");
- return aURL;
- }
+ // This URL came from a bookmark, so it's safe to let it inherit the current
+ // document's principal.
+ mayInheritPrincipal = true;
+
+ return { postData, url: shortcutURL, mayInheritPrincipal };
+ }
+
+ if (param) {
+ // This keyword doesn't take a parameter, but one was provided. Just return
+ // the original URL.
+ postData = null;
- // This URL came from a bookmark, so it's safe to let it inherit the current
- // document's principal.
- if (aMayInheritPrincipal)
- aMayInheritPrincipal.value = true;
+ return { postData, url, mayInheritPrincipal };
+ }
+
+ // This URL came from a bookmark, so it's safe to let it inherit the current
+ // document's principal.
+ mayInheritPrincipal = true;
- return shortcutURL;
+ return { postData, url: shortcutURL, mayInheritPrincipal };
+ }).then(data => {
+ if (callback) {
+ callback(data);
+ }
+
+ return data;
+ });
}
function getPostDataStream(aStringData, aKeyword, aEncKeyword, aType) {
@@ -2482,8 +2533,8 @@ function BrowserFullScreen()
window.fullScreen = !window.fullScreen;
}
-function onFullScreen(event) {
- FullScreen.toggle(event);
+function onFullScreen() {
+ FullScreen.toggle();
}
function onMozEnteredDomFullscreen(event) {
@@ -2641,8 +2692,8 @@ var browserDragAndDrop = {
}
},
- drop: function (aEvent, aName, aDisallowInherit) {
- return Services.droppedLinkHandler.dropLink(aEvent, aName, aDisallowInherit);
+ dropLinks: function (aEvent, aDisallowInherit) {
+ return Services.droppedLinkHandler.dropLinks(aEvent, aDisallowInherit);
}
};
@@ -2650,8 +2701,10 @@ var homeButtonObserver = {
onDrop: function (aEvent)
{
// disallow setting home pages that inherit the principal
- let url = browserDragAndDrop.drop(aEvent, {}, true);
- setTimeout(openHomeDialog, 0, url);
+ let links = browserDragAndDrop.dropLinks(aEvent, true);
+ if (links.length) {
+ setTimeout(openHomeDialog, 0, links.map(link => link.url).join("|"));
+ }
},
onDragOver: function (aEvent)
@@ -2667,18 +2720,24 @@ var homeButtonObserver = {
function openHomeDialog(aURL)
{
var promptTitle = gNavigatorBundle.getString("droponhometitle");
- var promptMsg = gNavigatorBundle.getString("droponhomemsg");
+ var promptMsg;
+ if (aURL.includes("|")) {
+ promptMsg = gNavigatorBundle.getString("droponhomemsgMultiple");
+ } else {
+ promptMsg = gNavigatorBundle.getString("droponhomemsg");
+ }
+
var pressedVal = Services.prompt.confirmEx(window, promptTitle, promptMsg,
Services.prompt.STD_YES_NO_BUTTONS,
null, null, null, null, {value:0});
if (pressedVal == 0) {
try {
- var str = Components.classes["@mozilla.org/supports-string;1"]
- .createInstance(Components.interfaces.nsISupportsString);
- str.data = aURL;
+ var homepageStr = Components.classes["@mozilla.org/supports-string;1"]
+ .createInstance(Components.interfaces.nsISupportsString);
+ homepageStr.data = aURL;
gPrefService.setComplexValue("browser.startup.homepage",
- Components.interfaces.nsISupportsString, str);
+ Components.interfaces.nsISupportsString, homepageStr);
} catch (ex) {
dump("Failed to set the home page.\n"+ex+"\n");
}
@@ -2726,13 +2785,16 @@ var newTabButtonObserver = {
onDrop: function (aEvent)
{
- let url = browserDragAndDrop.drop(aEvent, { });
- var postData = {};
- url = getShortcutOrURI(url, postData);
- if (url) {
- // allow third-party services to fixup this URL
- openNewTabWith(url, null, postData.value, aEvent, true);
- }
+ let links = browserDragAndDrop.dropLinks(aEvent);
+ Task.spawn(function*() {
+ for (let link of links) {
+ let data = yield getShortcutOrURIAndPostData(link.url);
+ if (data.url) {
+ // allow third-party services to fixup this URL
+ openNewTabWith(data.url, null, data.postData, aEvent, true);
+ }
+ }
+ });
}
}
@@ -2746,13 +2808,16 @@ var newWindowButtonObserver = {
},
onDrop: function (aEvent)
{
- let url = browserDragAndDrop.drop(aEvent, { });
- var postData = {};
- url = getShortcutOrURI(url, postData);
- if (url) {
- // allow third-party services to fixup this URL
- openNewWindowWith(url, null, postData.value, true);
- }
+ let links = browserDragAndDrop.dropLinks(aEvent);
+ Task.spawn(function*() {
+ for (let link of links) {
+ let data = yield getShortcutOrURIAndPostData(link.url);
+ if (data.url) {
+ // allow third-party services to fixup this URL
+ openNewWindowWith(data.url, null, data.postData, true);
+ }
+ }
+ });
}
}
@@ -2950,7 +3015,7 @@ const BrowserSearch = {
#endif
var searchBar = this.searchBar;
if (searchBar && window.fullScreen)
- FullScreen.mouseoverToggle(true);
+ FullScreen.showNavToolbox();
if (searchBar)
searchBar.select();
if (!searchBar || document.activeElement != searchBar.textbox.inputField)
@@ -4239,6 +4304,13 @@ nsBrowserAccess.prototype = {
else
aWhere = gPrefService.getIntPref("browser.link.open_newwindow");
}
+
+ let referrer = aOpener ? makeURI(aOpener.location.href) : null;
+ let referrerPolicy = Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT;
+ if (aOpener && aOpener.document) {
+ referrerPolicy = aOpener.document.referrerPolicy;
+ }
+
switch (aWhere) {
case Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW :
// FIXME: Bug 408379. So how come this doesn't send the
@@ -4277,6 +4349,7 @@ nsBrowserAccess.prototype = {
let tab = win.gBrowser.loadOneTab(aURI ? aURI.spec : "about:blank", {
referrerURI: referrer,
+ referrerPolicy: referrerPolicy,
fromExternal: isExternal,
inBackground: loadInBackground});
let browser = win.gBrowser.getBrowserForTab(tab);
@@ -4292,11 +4365,14 @@ nsBrowserAccess.prototype = {
default : // OPEN_CURRENTWINDOW or an illegal value
newWindow = content;
if (aURI) {
- let referrer = aOpener ? makeURI(aOpener.location.href) : null;
let loadflags = isExternal ?
Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL :
Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
- gBrowser.loadURIWithFlags(aURI.spec, loadflags, referrer, null, null);
+ gBrowser.loadURIWithFlags(aURI.spec, {
+ flags: loadflags,
+ referrerURI: referrer,
+ referrerPolicy: referrerPolicy,
+ });
}
if (!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground"))
window.focus();
@@ -5026,7 +5102,8 @@ function handleLinkClick(event, href, linkNode) {
urlSecurityCheck(href, doc.nodePrincipal);
openLinkIn(href, where, { referrerURI: doc.documentURIObject,
- charset: doc.characterSet });
+ charset: doc.characterSet,
+ referrerPolicy: doc.referrerPolicy });
event.preventDefault();
return true;
}
@@ -5040,36 +5117,81 @@ function middleMousePaste(event) {
// bar's behavior (stripsurroundingwhitespace)
clipboard = clipboard.replace(/\s*\n\s*/g, "");
- let mayInheritPrincipal = { value: false };
- let url = getShortcutOrURI(clipboard, mayInheritPrincipal);
- try {
- makeURI(url);
- } catch (ex) {
- // Not a valid URI.
- return;
+ // if it's not the current tab, we don't need to do anything because the
+ // browser doesn't exist.
+ let where = whereToOpenLink(event, true, false);
+ let lastLocationChange;
+ if (where == "current") {
+ lastLocationChange = gBrowser.selectedBrowser.lastLocationChange;
}
- try {
- addToUrlbarHistory(url);
- } catch (ex) {
- // Things may go wrong when adding url to session history,
- // but don't let that interfere with the loading of the url.
- Cu.reportError(ex);
- }
+ getShortcutOrURIAndPostData(clipboard).then(data => {
+ try {
+ makeURI(data.url);
+ } catch (ex) {
+ // Not a valid URI.
+ return;
+ }
+
+ try {
+ addToUrlbarHistory(data.url);
+ } catch (ex) {
+ // Things may go wrong when adding url to session history,
+ // but don't let that interfere with the loading of the url.
+ Cu.reportError(ex);
+ }
- openUILink(url, event,
- { ignoreButton: true,
- disallowInheritPrincipal: !mayInheritPrincipal.value });
+ if (where != "current" ||
+ lastLocationChange == gBrowser.selectedBrowser.lastLocationChange) {
+ openUILink(data.url, event,
+ { ignoreButton: true,
+ disallowInheritPrincipal: !data.mayInheritPrincipal,
+ initiatingDoc: event ? event.target.ownerDocument : null });
+ }
+ });
event.stopPropagation();
}
-function handleDroppedLink(event, url, name)
+// handleDroppedLink has the following 2 overloads:
+// handleDroppedLink(event, url, name)
+// handleDroppedLink(event, links)
+function handleDroppedLink(event, urlOrLinks, name)
{
- let postData = { };
- let uri = getShortcutOrURI(url, postData);
- if (uri)
- loadURI(uri, null, postData.value, false);
+ let links;
+ if (Array.isArray(urlOrLinks)) {
+ links = urlOrLinks;
+ } else {
+ links = [{ url: urlOrLinks, name, type: "" }];
+ }
+
+ let lastLocationChange = gBrowser.selectedBrowser.lastLocationChange;
+
+ let userContextId = gBrowser.selectedBrowser
+ .getAttribute("usercontextid") || 0;
+
+ let inBackground = Services.prefs.getBoolPref("browser.tabs.loadInBackground");
+ if (event.shiftKey)
+ inBackground = !inBackground;
+
+ Task.spawn(function*() {
+ let urls = [];
+ let postDatas = [];
+ for (let link of links) {
+ let data = yield getShortcutOrURIAndPostData(link.url);
+ urls.push(data.url);
+ postDatas.push(data.postData);
+ }
+ if (lastLocationChange == gBrowser.selectedBrowser.lastLocationChange) {
+ gBrowser.loadTabs(urls, {
+ inBackground,
+ replace: true,
+ allowThirdPartyFixup: false,
+ postDatas,
+ userContextId,
+ });
+ }
+ });
// Keep the event from being handled by the dragDrop listeners
// built-in to goanna if they happen to be above us.
@@ -5184,7 +5306,6 @@ function charsetLoadListener() {
}
}
-
var gPageStyleMenu = {
_getAllStyleSheets: function (frameset) {
diff --git a/application/palemoon/base/content/browser.xul b/application/palemoon/base/content/browser.xul
index c2553f295..f9030056e 100644
--- a/application/palemoon/base/content/browser.xul
+++ b/application/palemoon/base/content/browser.xul
@@ -941,7 +941,7 @@
</toolbarpalette>
</toolbox>
- <hbox id="fullscr-toggler" collapsed="true"/>
+ <hbox id="fullscr-toggler" hidden="true"/>
<hbox flex="1" id="browser">
<vbox id="browser-border-start" hidden="true" layer="true"/>
@@ -974,18 +974,6 @@
<vbox id="full-screen-warning-message" align="center">
<description id="full-screen-domain-text"/>
<description class="full-screen-description" value="&fullscreenExitHint.value;"/>
- <vbox id="full-screen-approval-pane" align="center">
- <description class="full-screen-description" value="&fullscreenApproval.value;"/>
- <hbox>
- <button label="&fullscreenAllowButton.label;"
- oncommand="FullScreen.setFullscreenAllowed(true);"
- class="full-screen-approval-button"/>
- <button label="&fullscreenExitButton.label;"
- oncommand="FullScreen.setFullscreenAllowed(false);"
- class="full-screen-approval-button"/>
- </hbox>
- <checkbox id="full-screen-remember-decision"/>
- </vbox>
</vbox>
</hbox>
</hbox>
diff --git a/application/palemoon/base/content/newtab/grid.js b/application/palemoon/base/content/newtab/grid.js
index 46e0b804b..a614d0396 100644
--- a/application/palemoon/base/content/newtab/grid.js
+++ b/application/palemoon/base/content/newtab/grid.js
@@ -59,8 +59,13 @@ var gGrid = {
* Refreshes the grid and re-creates all sites.
*/
refresh: function Grid_refresh() {
+ let cells = this.cells;
+ if (!cells) {
+ return;
+ }
+
// Remove all sites.
- this.cells.forEach(function (cell) {
+ cells.forEach(function (cell) {
let node = cell.node;
let child = node.firstElementChild;
diff --git a/application/palemoon/base/content/nsContextMenu.js b/application/palemoon/base/content/nsContextMenu.js
index 830c20998..f389491d3 100644
--- a/application/palemoon/base/content/nsContextMenu.js
+++ b/application/palemoon/base/content/nsContextMenu.js
@@ -753,7 +753,8 @@ nsContextMenu.prototype = {
urlSecurityCheck(this.linkURL, doc.nodePrincipal);
openLinkIn(this.linkURL, "window",
{ charset: doc.characterSet,
- referrerURI: doc.documentURIObject });
+ referrerURI: doc.documentURIObject,
+ referrerPolicy: doc.referrerPolicy });
},
// Open linked-to URL in a new private window.
@@ -763,6 +764,7 @@ nsContextMenu.prototype = {
openLinkIn(this.linkURL, "window",
{ charset: doc.characterSet,
referrerURI: doc.documentURIObject,
+ referrerPolicy: doc.referrerPolicy,
private: true });
},
@@ -772,7 +774,8 @@ nsContextMenu.prototype = {
urlSecurityCheck(this.linkURL, doc.nodePrincipal);
openLinkIn(this.linkURL, "tab",
{ charset: doc.characterSet,
- referrerURI: doc.documentURIObject });
+ referrerURI: doc.documentURIObject,
+ referrerPolicy: doc.referrerPolicy });
},
// open URL in current tab
diff --git a/application/palemoon/base/content/openLocation.js b/application/palemoon/base/content/openLocation.js
index 316dfac70..f39e34666 100644
--- a/application/palemoon/base/content/openLocation.js
+++ b/application/palemoon/base/content/openLocation.js
@@ -61,45 +61,52 @@ function doEnabling()
function open()
{
- var url;
- var postData = {};
- var mayInheritPrincipal = {value: false};
- if (browser)
- url = browser.getShortcutOrURI(dialog.input.value, postData, mayInheritPrincipal);
- else
- url = dialog.input.value;
+ getShortcutOrURIAndPostData(dialog.input.value).then(data => {
+ let url;
+ let postData = null;
+ let mayInheritPrincipal = false;
+
+ if (browser) {
+ url = data.url;
+ postData = data.postData;
+ mayInheritPrincipal = data.mayInheritPrincipal;
+ } else {
+ url = dialog.input.value;
+ }
- try {
- // Whichever target we use for the load, we allow third-party services to
- // fixup the URI
- switch (dialog.openWhereList.value) {
- case "0":
- var webNav = Components.interfaces.nsIWebNavigation;
- var flags = webNav.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
- webNav.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
- if (!mayInheritPrincipal.value)
- flags |= webNav.LOAD_FLAGS_DISALLOW_INHERIT_OWNER;
- browser.gBrowser.loadURIWithFlags(url, flags, null, null, postData.value);
- break;
- case "1":
- window.opener.delayedOpenWindow(getBrowserURL(), "all,dialog=no",
- url, postData.value, null, null, true);
- break;
- case "3":
- browser.delayedOpenTab(url, null, null, postData.value, true);
- break;
+ try {
+ // Whichever target we use for the load, we allow third-party services to
+ // fixup the URI
+ switch (dialog.openWhereList.value) {
+ case "0":
+ var webNav = Components.interfaces.nsIWebNavigation;
+ var flags = webNav.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
+ webNav.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
+ if (!mayInheritPrincipal)
+ flags |= webNav.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL;
+ browser.gBrowser.loadURIWithFlags(url, flags, null, null, postData);
+ break;
+ case "1":
+ window.opener.delayedOpenWindow(getBrowserURL(), "all,dialog=no",
+ url, postData, null, null, true);
+ break;
+ case "3":
+ browser.delayedOpenTab(url, null, null, postData, true);
+ break;
+ }
+ }
+ catch(exception) {
}
- }
- catch(exception) {
- }
- if (pref) {
- gOpenLocationLastURL.value = dialog.input.value;
- pref.setIntPref("general.open_location.last_window_choice", dialog.openWhereList.value);
- }
+ if (pref) {
+ gOpenLocationLastURL.value = dialog.input.value;
+ pref.setIntPref("general.open_location.last_window_choice", dialog.openWhereList.value);
+ }
+
+ // Delay closing slightly to avoid timing bug on Linux.
+ window.close();
+ });
- // Delay closing slightly to avoid timing bug on Linux.
- window.close();
return false;
}
diff --git a/application/palemoon/base/content/pageinfo/pageInfo.js b/application/palemoon/base/content/pageinfo/pageInfo.js
index 83f0ddb91..6b02bc370 100644
--- a/application/palemoon/base/content/pageinfo/pageInfo.js
+++ b/application/palemoon/base/content/pageinfo/pageInfo.js
@@ -1112,8 +1112,9 @@ var imagePermissionObserver = {
var row = getSelectedRow(imageTree);
var item = gImageView.data[row][COL_IMAGE_NODE];
var url = gImageView.data[row][COL_IMAGE_ADDRESS];
- if (makeURI(url).host == permission.host)
+ if (permission.matchesURI(makeURI(url), true)) {
makeBlockImage(url);
+ }
}
}
}
diff --git a/application/palemoon/base/content/pageinfo/pageInfo.xul b/application/palemoon/base/content/pageinfo/pageInfo.xul
index 5bca1b495..943fa805c 100644
--- a/application/palemoon/base/content/pageinfo/pageInfo.xul
+++ b/application/palemoon/base/content/pageinfo/pageInfo.xul
@@ -52,7 +52,6 @@
<command id="cmd_cookieDef" oncommand="onCheckboxClick('cookie');"/>
<command id="cmd_desktop-notificationDef" oncommand="onCheckboxClick('desktop-notification');"/>
<command id="cmd_installDef" oncommand="onCheckboxClick('install');"/>
- <command id="cmd_fullscreenDef" oncommand="onCheckboxClick('fullscreen');"/>
<command id="cmd_geoDef" oncommand="onCheckboxClick('geo');"/>
<command id="cmd_indexedDBDef" oncommand="onCheckboxClick('indexedDB');"/>
<command id="cmd_pluginsDef" oncommand="onCheckboxClick('plugins');"/>
@@ -61,12 +60,9 @@
<command id="cmd_cookieToggle" oncommand="onRadioClick('cookie');"/>
<command id="cmd_desktop-notificationToggle" oncommand="onRadioClick('desktop-notification');"/>
<command id="cmd_installToggle" oncommand="onRadioClick('install');"/>
- <command id="cmd_fullscreenToggle" oncommand="onRadioClick('fullscreen');"/>
<command id="cmd_geoToggle" oncommand="onRadioClick('geo');"/>
<command id="cmd_indexedDBToggle" oncommand="onRadioClick('indexedDB');"/>
<command id="cmd_pluginsToggle" oncommand="onPluginRadioClick(event);"/>
- <command id="cmd_pointerLockDef" oncommand="onCheckboxClick('pointerLock');"/>
- <command id="cmd_pointerLockToggle" oncommand="onRadioClick('pointerLock');"/>
</commandset>
<keyset id="pageInfoKeySet">
@@ -405,31 +401,6 @@
</radiogroup>
</hbox>
</vbox>
- <vbox class="permission" id="permFullscreenRow">
- <label class="permissionLabel" id="permFullscreenLabel"
- value="&permFullscreen;" control="fullscreenRadioGroup"/>
- <hbox id="permFullscreenBox" role="group" aria-labelledby="permFullscreenLabel">
- <checkbox id="fullscreenDef" command="cmd_fullscreenDef" label="&permUseDefault;"/>
- <spacer flex="1"/>
- <radiogroup id="fullscreenRadioGroup" orient="horizontal">
- <radio id="fullscreen#0" command="cmd_fullscreenToggle" label="&permAskAlways;"/>
- <radio id="fullscreen#1" command="cmd_fullscreenToggle" label="&permAllow;"/>
- <radio id="fullscreen#2" command="cmd_fullscreenToggle" label="&permBlock;"/>
- </radiogroup>
- </hbox>
- </vbox>
- <vbox class="permission" id="permPointerLockRow" >
- <label class="permissionLabel" id="permPointerLockLabel"
- value="&permPointerLock2;" control="pointerLockRadioGroup"/>
- <hbox id="permPointerLockBox" role="group" aria-labelledby="permPointerLockLabel">
- <checkbox id="pointerLockDef" command="cmd_pointerLockDef" label="&permAskAlways;"/>
- <spacer flex="1"/>
- <radiogroup id="pointerLockRadioGroup" orient="horizontal">
- <radio id="pointerLock#1" command="cmd_pointerLockToggle" label="&permAllow;"/>
- <radio id="pointerLock#2" command="cmd_pointerLockToggle" label="&permBlock;"/>
- </radiogroup>
- </hbox>
- </vbox>
</vbox>
</vbox>
diff --git a/application/palemoon/base/content/pageinfo/permissions.js b/application/palemoon/base/content/pageinfo/permissions.js
index 2fa0cc303..e0fb01f76 100644
--- a/application/palemoon/base/content/pageinfo/permissions.js
+++ b/application/palemoon/base/content/pageinfo/permissions.js
@@ -76,20 +76,6 @@ var gPermObj = {
{
return UNKNOWN;
},
- fullscreen: function getFullscreenDefaultPermissions()
- {
- if (!gPrefs.getBoolPref("full-screen-api.enabled")) {
- return DENY;
- }
- return UNKNOWN;
- },
- pointerLock: function getPointerLockPermissions()
- {
- if (!gPrefs.getBoolPref("full-screen-api.pointer-lock.enabled")) {
- return DENY;
- }
- return ALLOW;
- },
};
var permissionObserver = {
@@ -98,7 +84,7 @@ var permissionObserver = {
if (aTopic == "perm-changed") {
var permission = aSubject.QueryInterface(
Components.interfaces.nsIPermission);
- if (permission.host == gPermURI.host) {
+ if (permission.matchesURI(gPermURI, true)) {
if (permission.type in gPermObj)
initRow(permission.type);
else if (permission.type.startsWith("plugin"))
@@ -119,7 +105,7 @@ function onLoadPermission(principal)
gPermURI = uri;
gPermPrincipal = principal;
var hostText = document.getElementById("hostText");
- hostText.value = gPermURI.host;
+ hostText.value = gPermURI.prePath;
for (var i in gPermObj)
initRow(i);
diff --git a/application/palemoon/base/content/tabbrowser.xml b/application/palemoon/base/content/tabbrowser.xml
index a7cc6deea..1b8099785 100644
--- a/application/palemoon/base/content/tabbrowser.xml
+++ b/application/palemoon/base/content/tabbrowser.xml
@@ -570,6 +570,12 @@
const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
const nsIChannel = Components.interfaces.nsIChannel;
+ let location, originalLocation;
+ try {
+ aRequest.QueryInterface(nsIChannel)
+ location = aRequest.URI;
+ originalLocation = aRequest.originalURI;
+ } catch (ex) {}
if (aStateFlags & nsIWebProgressListener.STATE_START) {
this.mRequestCount++;
@@ -588,16 +594,8 @@
if (aStateFlags & nsIWebProgressListener.STATE_START &&
aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) {
- // It's okay to clear what the user typed when we start
- // loading a document. If the user types, this counter gets
- // set to zero, if the document load ends without an
- // onLocationChange, this counter gets decremented
- // (so we keep it while switching tabs after failed loads)
- // We need to add 2 because loadURIWithFlags may have
- // cancelled a pending load which would have cleared
- // its anchor scroll detection temporary increment.
if (aWebProgress.isTopLevel)
- this.mBrowser.userTypedClear += 2;
+ this.mBrowser.urlbarChangeTracker.startedLoad();
if (this._shouldShowProgress(aRequest)) {
if (!(aStateFlags & nsIWebProgressListener.STATE_RESTORING)) {
@@ -625,8 +623,8 @@
this.mTab.removeAttribute("progress");
if (aWebProgress.isTopLevel) {
- if (!Components.isSuccessCode(aStatus) &&
- !isTabEmpty(this.mTab)) {
+ let isSuccessful = Components.isSuccessCode(aStatus);
+ if (!isSuccessful && !isTabEmpty(this.mTab)) {
// Restore the current document's location in case the
// request was stopped (possibly from a content script)
// before the location changed.
@@ -635,14 +633,8 @@
if (this.mTab.selected && gURLBar)
URLBarSetURI();
- } else {
- // The document is done loading, we no longer want the
- // value cleared.
-
- if (this.mBrowser.userTypedClear > 1)
- this.mBrowser.userTypedClear -= 2;
- else if (this.mBrowser.userTypedClear > 0)
- this.mBrowser.userTypedClear--;
+ } else if (isSuccessful) {
+ this.mBrowser.urlbarChangeTracker.finishedLoad();
}
if (!this.mBrowser.mIconURL)
@@ -652,8 +644,6 @@
if (this.mBlank)
this.mBlank = false;
- var location = aRequest.QueryInterface(nsIChannel).URI;
-
// For keyword URIs clear the user typed value since they will be changed into real URIs
if (location.scheme == "keyword")
this.mBrowser.userTypedValue = null;
@@ -696,13 +686,12 @@
let topLevel = aWebProgress.isTopLevel;
if (topLevel) {
- // If userTypedClear > 0, the document loaded correctly and we should be
- // clearing the user typed value. We also need to clear the typed value
+ // We need to clear the typed value
// if the document failed to load, to make sure the urlbar reflects the
// failed URI (particularly for SSL errors). However, don't clear the value
// if the error page's URI is about:blank, because that causes complete
// loss of urlbar contents for invalid URI errors (see bug 867957).
- if (this.mBrowser.userTypedClear > 0 ||
+ if (this.mBrowser.didStartLoadSinceLastUserTyping() ||
((aFlags & Ci.nsIWebProgressListener.LOCATION_CHANGE_ERROR_PAGE) &&
aLocation.spec != "about:blank"))
this.mBrowser.userTypedValue = null;
@@ -738,8 +727,10 @@
aFlags]);
}
- if (topLevel)
+ if (topLevel) {
this.mBrowser.lastURI = aLocation;
+ this.mBrowser.lastLocationChange = Date.now();
+ }
},
onStatusChange: function (aWebProgress, aRequest, aStatus, aMessage) {
@@ -1273,6 +1264,7 @@
<parameter name="aAllowThirdPartyFixup"/>
<body>
<![CDATA[
+ var aReferrerPolicy;
var aFromExternal;
var aRelatedToCurrent;
if (arguments.length == 2 &&
@@ -1280,6 +1272,7 @@
!(arguments[1] instanceof Ci.nsIURI)) {
let params = arguments[1];
aReferrerURI = params.referrerURI;
+ aReferrerPolicy = params.referrerPolicy;
aCharset = params.charset;
aPostData = params.postData;
aLoadInBackground = params.inBackground;
@@ -1293,6 +1286,7 @@
var owner = bgLoad ? null : this.selectedTab;
var tab = this.addTab(aURI, {
referrerURI: aReferrerURI,
+ referrerPolicy: aReferrerPolicy,
charset: aCharset,
postData: aPostData,
ownerTab: owner,
@@ -1312,6 +1306,24 @@
<parameter name="aLoadInBackground"/>
<parameter name="aReplace"/>
<body><![CDATA[
+ let aAllowThirdPartyFixup;
+ let aTargetTab;
+ let aNewIndex = -1;
+ let aPostDatas = [];
+ let aUserContextId;
+ if (arguments.length == 2 &&
+ typeof arguments[1] == "object") {
+ let params = arguments[1];
+ aLoadInBackground = params.inBackground;
+ aReplace = params.replace;
+ aAllowThirdPartyFixup = params.allowThirdPartyFixup;
+ aTargetTab = params.targetTab;
+ aNewIndex = typeof params.newIndex === "number" ?
+ params.newIndex : aNewIndex;
+ aPostDatas = params.postDatas || aPostDatas;
+ aUserContextId = params.userContextId;
+ }
+
if (!aURIs.length)
return;
@@ -1329,22 +1341,53 @@
var multiple = aURIs.length > 1;
var owner = multiple || aLoadInBackground ? null : this.selectedTab;
var firstTabAdded = null;
+ var targetTabIndex = -1;
if (aReplace) {
+ let browser;
+ if (aTargetTab) {
+ browser = this.getBrowserForTab(aTargetTab);
+ targetTabIndex = aTargetTab._tPos;
+ } else {
+ browser = this.mCurrentBrowser;
+ targetTabIndex = this.tabContainer.selectedIndex;
+ }
+ let flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
+ if (aAllowThirdPartyFixup) {
+ flags |= Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
+ Ci.nsIWebNavigation.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
+ }
try {
- this.loadURI(aURIs[0], null, null);
+ browser.loadURIWithFlags(aURIs[0], {
+ flags, postData: aPostDatas[0]
+ });
} catch (e) {
// Ignore failure in case a URI is wrong, so we can continue
// opening the next ones.
}
+ } else {
+ firstTabAdded = this.addTab(aURIs[0], {
+ ownerTab: owner,
+ skipAnimation: multiple,
+ allowThirdPartyFixup: aAllowThirdPartyFixup,
+ postData: aPostDatas[0],
+ userContextId: aUserContextId
+ });
+ if (aNewIndex !== -1) {
+ this.moveTabTo(firstTabAdded, aNewIndex);
+ targetTabIndex = firstTabAdded._tPos;
+ }
}
- else
- firstTabAdded = this.addTab(aURIs[0], {ownerTab: owner, skipAnimation: multiple});
- var tabNum = this.tabContainer.selectedIndex;
+ let tabNum = targetTabIndex;
for (let i = 1; i < aURIs.length; ++i) {
- let tab = this.addTab(aURIs[i], {skipAnimation: true});
- if (aReplace)
+ let tab = this.addTab(aURIs[i], {
+ skipAnimation: true,
+ allowThirdPartyFixup: aAllowThirdPartyFixup,
+ postData: aPostDatas[i],
+ userContextId: aUserContextId
+ });
+ if (targetTabIndex !== -1)
this.moveTabTo(tab, ++tabNum);
}
@@ -1369,6 +1412,7 @@
<body>
<![CDATA[
const NS_XUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
+ var aReferrerPolicy;
var aFromExternal;
var aRelatedToCurrent;
var aSkipAnimation;
@@ -1377,6 +1421,7 @@
!(arguments[1] instanceof Ci.nsIURI)) {
let params = arguments[1];
aReferrerURI = params.referrerURI;
+ aReferrerPolicy = params.referrerPolicy;
aCharset = params.charset;
aPostData = params.postData;
aOwner = params.ownerTab;
@@ -1548,7 +1593,13 @@
if (aFromExternal)
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL;
try {
- b.loadURIWithFlags(aURI, flags, aReferrerURI, aCharset, aPostData);
+ b.loadURIWithFlags(aURI, {
+ flags: flags,
+ referrerURI: aReferrerURI,
+ referrerPolicy: aReferrerPolicy,
+ charset: aCharset,
+ postData: aPostData,
+ });
} catch (ex) {
Cu.reportError(ex);
}
@@ -2660,6 +2711,11 @@
<parameter name="aPostData"/>
<body>
<![CDATA[
+ // Note - the callee understands both:
+ // (a) loadURIWithFlags(aURI, aFlags, ...)
+ // (b) loadURIWithFlags(aURI, { flags: aFlags, ... })
+ // Forwarding it as (a) here actually supports both (a) and (b),
+ // so you can call us either way too.
return this.mCurrentBrowser.loadURIWithFlags(aURI, aFlags, aReferrerURI, aCharset, aPostData);
]]>
</body>
@@ -2976,10 +3032,6 @@
]]></body>
</method>
- <property name="userTypedClear"
- onget="return this.mCurrentBrowser.userTypedClear;"
- onset="return this.mCurrentBrowser.userTypedClear = val;"/>
-
<property name="userTypedValue"
onget="return this.mCurrentBrowser.userTypedValue;"
onset="return this.mCurrentBrowser.userTypedValue = val;"/>
@@ -4456,40 +4508,35 @@
this.tabbrowser.updateCurrentBrowser(true);
} else {
// Pass true to disallow dropping javascript: or data: urls
- let url;
+ let links;
try {
- url = browserDragAndDrop.drop(event, { }, true);
+ links = browserDragAndDrop.dropLinks(event, true);
} catch (ex) {}
// // valid urls don't contain spaces ' '; if we have a space it isn't a valid url.
// if (!url || url.includes(" ")) //PMed
- if (!url) //FF
+ if (!links || links.length === 0) //FF
return;
- let bgLoad = Services.prefs.getBoolPref("browser.tabs.loadInBackground");
+ let inBackground = Services.prefs.getBoolPref("browser.tabs.loadInBackground");
if (event.shiftKey)
- bgLoad = !bgLoad;
+ inBackground = !inBackground;
- let tab = this._getDragTargetTab(event);
- if (!tab || dropEffect == "copy") {
- // We're adding a new tab.
- let newIndex = this._getDropIndex(event);
- let newTab = this.tabbrowser.loadOneTab(url, {inBackground: bgLoad, allowThirdPartyFixup: true});
- this.tabbrowser.moveTabTo(newTab, newIndex);
- } else {
- // Load in an existing tab.
- try {
- let webNav = Ci.nsIWebNavigation;
- let flags = webNav.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
- webNav.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
- this.tabbrowser.getBrowserForTab(tab).loadURIWithFlags(url, flags);
- if (!bgLoad)
- this.selectedItem = tab;
- } catch(ex) {
- // Just ignore invalid urls
- }
- }
+ let targetTab = this._getDragTargetTab(event);
+ let userContextId = this.selectedItem
+ .getAttribute("usercontextid") || 0;
+ let replace = !(!targetTab || dropEffect == "copy");
+ let newIndex = this._getDropIndex(event);
+ let urls = links.map(link => link.url);
+ this.tabbrowser.loadTabs(urls, {
+ inBackground,
+ replace,
+ allowThirdPartyFixup: true,
+ targetTab,
+ newIndex,
+ userContextId,
+ });
}
if (draggedTab) {
diff --git a/application/palemoon/base/content/urlbarBindings.xml b/application/palemoon/base/content/urlbarBindings.xml
index bf59ea164..d188e6658 100644
--- a/application/palemoon/base/content/urlbarBindings.xml
+++ b/application/palemoon/base/content/urlbarBindings.xml
@@ -263,6 +263,9 @@
var postData = null;
var action = this._parseActionUrl(url);
+ let lastLocationChange = gBrowser.selectedBrowser.lastLocationChange;
+
+ let matchLastLocationChange = true;
if (action) {
url = action.param;
if (this.hasAttribute("actiontype")) {
@@ -275,82 +278,94 @@
}
return;
}
+ continueOperation.call(this);
}
else {
- [url, postData, mayInheritPrincipal] = this._canonizeURL(aTriggeringEvent);
- if (!url)
- return;
- }
-
- this.value = url;
- gBrowser.userTypedValue = url;
- try {
- addToUrlbarHistory(url);
- } catch (ex) {
- // Things may go wrong when adding url to session history,
- // but don't let that interfere with the loading of the url.
- Cu.reportError(ex);
+ this._canonizeURL(aTriggeringEvent, response => {
+ [url, postData, mayInheritPrincipal] = response;
+ if (url) {
+ matchLastLocationChange = (lastLocationChange ==
+ gBrowser.selectedBrowser.lastLocationChange);
+ continueOperation.call(this);
+ }
+ });
}
- function loadCurrent() {
- let webnav = Ci.nsIWebNavigation;
- let flags = webnav.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP |
- webnav.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
- // Pass LOAD_FLAGS_DISALLOW_INHERIT_OWNER to prevent any loads from
- // inheriting the currently loaded document's principal, unless this
- // URL is marked as safe to inherit (e.g. came from a bookmark
- // keyword).
- if (!mayInheritPrincipal)
- flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_OWNER;
- gBrowser.loadURIWithFlags(url, flags, null, null, postData);
- }
+ function continueOperation()
+ {
+ this.value = url;
+ gBrowser.userTypedValue = url;
+ try {
+ addToUrlbarHistory(url);
+ } catch (ex) {
+ // Things may go wrong when adding url to session history,
+ // but don't let that interfere with the loading of the url.
+ Cu.reportError(ex);
+ }
- // Focus the content area before triggering loads, since if the load
- // occurs in a new tab, we want focus to be restored to the content
- // area when the current tab is re-selected.
- gBrowser.selectedBrowser.focus();
+ function loadCurrent() {
+ let flags = Ci.nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
+ // Pass LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL to prevent any loads from
+ // inheriting the currently loaded document's principal, unless this
+ // URL is marked as safe to inherit (e.g. came from a bookmark
+ // keyword).
+ if (!mayInheritPrincipal)
+ flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL;
+ // If the value wasn't typed, we know that we decoded the value as
+ // UTF-8 (see losslessDecodeURI)
+ if (!this.valueIsTyped)
+ flags |= Ci.nsIWebNavigation.LOAD_FLAGS_URI_IS_UTF8;
+ gBrowser.loadURIWithFlags(url, flags, null, null, postData);
+ }
- let isMouseEvent = aTriggeringEvent instanceof MouseEvent;
- let altEnter = !isMouseEvent && aTriggeringEvent && aTriggeringEvent.altKey;
+ // Focus the content area before triggering loads, since if the load
+ // occurs in a new tab, we want focus to be restored to the content
+ // area when the current tab is re-selected.
+ gBrowser.selectedBrowser.focus();
- if (altEnter) {
- // XXX This was added a long time ago, and I'm not sure why it is
- // necessary. Alt+Enter's default action might cause a system beep,
- // or something like that?
- aTriggeringEvent.preventDefault();
- aTriggeringEvent.stopPropagation();
- }
+ let isMouseEvent = aTriggeringEvent instanceof MouseEvent;
- // If the current tab is empty, ignore Alt+Enter (just reuse this tab)
- altEnter = altEnter && !isTabEmpty(gBrowser.selectedTab);
+ // If the current tab is empty, ignore Alt+Enter (just reuse this tab)
+ let altEnter = !isMouseEvent && aTriggeringEvent &&
+ aTriggeringEvent.altKey && !isTabEmpty(gBrowser.selectedTab);
- if (isMouseEvent || altEnter) {
- // Use the standard UI link behaviors for clicks or Alt+Enter
- let where = "tab";
- if (isMouseEvent)
- where = whereToOpenLink(aTriggeringEvent, false, false);
+ if (isMouseEvent || altEnter) {
+ // Use the standard UI link behaviors for clicks or Alt+Enter
+ let where = "tab";
+ if (isMouseEvent)
+ where = whereToOpenLink(aTriggeringEvent, false, false);
- if (where == "current") {
- loadCurrent();
+ if (where == "current") {
+ if (matchLastLocationChange) {
+ loadCurrent();
+ }
+ } else {
+ this.handleRevert();
+ let params = { allowThirdPartyFixup: true,
+ postData: postData,
+ initiatingDoc: document };
+ if (!this.valueIsTyped)
+ params.isUTF8 = true;
+ openUILinkIn(url, where, params);
+ }
} else {
- this.handleRevert();
- let params = { allowThirdPartyFixup: true,
- postData: postData,
- initiatingDoc: document };
- openUILinkIn(url, where, params);
+ if (matchLastLocationChange) {
+ loadCurrent();
+ }
}
- } else {
- loadCurrent();
}
]]></body>
</method>
<method name="_canonizeURL">
<parameter name="aTriggeringEvent"/>
+ <parameter name="aCallback"/>
<body><![CDATA[
var url = this.value;
- if (!url)
- return ["", null, false];
+ if (!url) {
+ aCallback(["", null, false]);
+ return;
+ }
// Only add the suffix when the URL bar value isn't already "URL-like",
// and only if we get a keyboard event, to match user expectations.
@@ -403,11 +418,9 @@
}
}
- var postData = {};
- var mayInheritPrincipal = { value: false };
- url = getShortcutOrURI(url, postData, mayInheritPrincipal);
-
- return [url, postData.value, mayInheritPrincipal.value];
+ getShortcutOrURIAndPostData(url).then(data => {
+ aCallback([data.url, data.postData, data.mayInheritPrincipal]);
+ });
]]></body>
</method>
@@ -442,11 +455,12 @@
<method name="onDrop">
<parameter name="aEvent"/>
<body><![CDATA[
- let url = browserDragAndDrop.drop(aEvent, { })
+ let links = browserDragAndDrop.dropLinks(aEvent);
// The URL bar automatically handles inputs with newline characters,
// so we can get away with treating text/x-moz-url flavours as text/plain.
- if (url) {
+ if (links.length > 0 && links[0].url) {
+ let url = links[0].url;
aEvent.preventDefault();
this.value = url;
SetPageProxyState("invalid");
@@ -1356,8 +1370,8 @@
return;
}
- let host = gPluginHandler._getHostFromPrincipal(this.notification.browser.contentWindow.document.nodePrincipal);
- this._setupDescription("pluginActivateMultiple.message", null, host);
+ let prePath = this.notification.browser.contentWindow.document.nodePrincipal.URI.prePath;
+ this._setupDescription("pluginActivateMultiple.message", null, prePath);
var showBox = document.getAnonymousElementByAttribute(this, "anonid", "plugin-notification-showbox");
@@ -1396,7 +1410,7 @@
<method name="_setupSingleState">
<body><![CDATA[
var action = this.notification.options.centerActions[0];
- var host = action.pluginPermissionHost;
+ var prePath = action.pluginPermissionPrePath;
let label, linkLabel, linkUrl, button1, button2;
@@ -1491,7 +1505,7 @@
Cu.reportError(Error("Unexpected blocklist state"));
}
}
- this._setupDescription(label, action.pluginName, host);
+ this._setupDescription(label, action.pluginName, prePath);
this._setupLink(linkLabel, action.detailsLink);
this._primaryButton.label = gNavigatorBundle.getString(button1.label);
@@ -1512,7 +1526,7 @@
<method name="_setupDescription">
<parameter name="baseString" />
<parameter name="pluginName" /> <!-- null for the multiple-plugin case -->
- <parameter name="host" />
+ <parameter name="prePath" />
<body><![CDATA[
var bsn = this._brandShortName;
var span = document.getAnonymousElementByAttribute(this, "anonid", "click-to-play-plugins-notification-description");
@@ -1520,17 +1534,17 @@
span.removeChild(span.lastChild);
}
- var args = ["__host__", this._brandShortName];
+ var args = ["__prepath__", this._brandShortName];
if (pluginName) {
args.unshift(pluginName);
}
var bases = gNavigatorBundle.getFormattedString(baseString, args).
- split("__host__", 2);
+ split("__prepath__", 2);
span.appendChild(document.createTextNode(bases[0]));
- var hostSpan = document.createElementNS("http://www.w3.org/1999/xhtml", "em");
- hostSpan.appendChild(document.createTextNode(host));
- span.appendChild(hostSpan);
+ var prePathSpan = document.createElementNS("http://www.w3.org/1999/xhtml", "em");
+ prePathSpan.appendChild(document.createTextNode(prePath));
+ span.appendChild(prePathSpan);
span.appendChild(document.createTextNode(bases[1] + " "));
]]></body>
</method>
diff --git a/application/palemoon/base/content/utilityOverlay.js b/application/palemoon/base/content/utilityOverlay.js
index 86cc5cea5..633cb8853 100644
--- a/application/palemoon/base/content/utilityOverlay.js
+++ b/application/palemoon/base/content/utilityOverlay.js
@@ -104,7 +104,8 @@ function openUILink(url, event, aIgnoreButton, aIgnoreAlt, aAllowThirdPartyFixup
allowThirdPartyFixup: aAllowThirdPartyFixup,
postData: aPostData,
referrerURI: aReferrerURI,
- initiatingDoc: event ? event.target.ownerDocument : null
+ referrerPolicy: Components.interfaces.nsIHttpChannel.REFERRER_POLICY_DEFAULT,
+ initiatingDoc: event ? event.target.ownerDocument : null,
};
}
@@ -196,7 +197,8 @@ function openUILinkIn(url, where, aAllowThirdPartyFixup, aPostData, aReferrerURI
params = {
allowThirdPartyFixup: aAllowThirdPartyFixup,
postData: aPostData,
- referrerURI: aReferrerURI
+ referrerURI: aReferrerURI,
+ referrerPolicy: Components.interfaces.nsIHttpChannel.REFERRER_POLICY_DEFAULT,
};
}
@@ -209,12 +211,16 @@ function openUILinkIn(url, where, aAllowThirdPartyFixup, aPostData, aReferrerURI
function openLinkIn(url, where, params) {
if (!where || !url)
return;
+ const Cc = Components.classes;
+ const Ci = Components.interfaces;
var aFromChrome = params.fromChrome;
var aAllowThirdPartyFixup = params.allowThirdPartyFixup;
var aPostData = params.postData;
var aCharset = params.charset;
var aReferrerURI = params.referrerURI;
+ var aReferrerPolicy = ('referrerPolicy' in params ?
+ params.referrerPolicy : Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT);
var aRelatedToCurrent = params.relatedToCurrent;
var aForceAllowDataURI = params.forceAllowDataURI;
var aInBackground = params.inBackground;
@@ -229,11 +235,10 @@ function openLinkIn(url, where, params) {
"where == 'save' but without initiatingDoc. See bug 814264.");
return;
}
+ // TODO(1073187): propagate referrerPolicy.
saveURL(url, null, null, true, null, aReferrerURI, aInitiatingDoc);
return;
}
- const Cc = Components.classes;
- const Ci = Components.interfaces;
var w = getTopWin();
if ((where == "tab" || where == "tabshifted") &&
@@ -243,6 +248,7 @@ function openLinkIn(url, where, params) {
}
if (!w || where == "window") {
+ // This propagates to window.arguments.
// Strip referrer data when opening a new private window, to prevent
// regular browsing data from leaking into it.
if (aIsPrivate) {
@@ -267,12 +273,23 @@ function openLinkIn(url, where, params) {
createInstance(Ci.nsISupportsPRBool);
allowThirdPartyFixupSupports.data = aAllowThirdPartyFixup;
+ var referrerURISupports = null;
+ if (aReferrerURI && sendReferrerURI) {
+ referrerURISupports = Cc["@mozilla.org/supports-string;1"].
+ createInstance(Ci.nsISupportsString);
+ referrerURISupports.data = aReferrerURI.spec;
+ }
+
+ var referrerPolicySupports = Cc["@mozilla.org/supports-PRUint32;1"].
+ createInstance(Ci.nsISupportsPRUint32);
+ referrerPolicySupports.data = aReferrerPolicy;
+
sa.AppendElement(wuri);
sa.AppendElement(charset);
- if (sendReferrerURI)
- sa.AppendElement(aReferrerURI);
+ sa.AppendElement(referrerURISupports);
sa.AppendElement(aPostData);
sa.AppendElement(allowThirdPartyFixupSupports);
+ sa.AppendElement(referrerPolicySupports);
let features = "chrome,dialog=no,all";
if (aIsPrivate) {
@@ -316,11 +333,16 @@ function openLinkIn(url, where, params) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FIXUP_SCHEME_TYPOS;
}
if (aDisallowInheritPrincipal)
- flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_OWNER;
+ flags |= Ci.nsIWebNavigation.LOAD_FLAGS_DISALLOW_INHERIT_PRINCIPAL;
if (aForceAllowDataURI) {
flags |= Ci.nsIWebNavigation.LOAD_FLAGS_FORCE_ALLOW_DATA_URI;
}
- w.gBrowser.loadURIWithFlags(url, flags, aReferrerURI, null, aPostData);
+ w.gBrowser.loadURIWithFlags(url, {
+ flags: flags,
+ referrerURI: aReferrerURI,
+ referrerPolicy: aReferrerPolicy,
+ postData: aPostData,
+ });
break;
case "tabshifted":
loadInBackground = !loadInBackground;
@@ -329,6 +351,7 @@ function openLinkIn(url, where, params) {
let browser = w.gBrowser;
browser.loadOneTab(url, {
referrerURI: aReferrerURI,
+ referrerPolicy: aReferrerPolicy,
charset: aCharset,
postData: aPostData,
inBackground: loadInBackground,
@@ -577,9 +600,11 @@ function makeURLAbsolute(aBase, aUrl)
* @param [optional] aReferrer
* If aDocument is null, then this will be used as the referrer.
* There will be no security check.
+ * @param [optional] aReferrerPolicy
+ * Referrer policy - Ci.nsIHttpChannel.REFERRER_POLICY_*.
*/
function openNewTabWith(aURL, aDocument, aPostData, aEvent,
- aAllowThirdPartyFixup, aReferrer) {
+ aAllowThirdPartyFixup, aReferrer, aReferrerPolicy) {
if (aDocument)
urlSecurityCheck(aURL, aDocument.nodePrincipal);
@@ -594,10 +619,13 @@ function openNewTabWith(aURL, aDocument, aPostData, aEvent,
{ charset: originCharset,
postData: aPostData,
allowThirdPartyFixup: aAllowThirdPartyFixup,
- referrerURI: aDocument ? aDocument.documentURIObject : aReferrer });
+ referrerURI: aDocument ? aDocument.documentURIObject : aReferrer,
+ referrerPolicy: aReferrerPolicy,
+ });
}
-function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup, aReferrer) {
+function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup,
+ aReferrer, aReferrerPolicy) {
if (aDocument)
urlSecurityCheck(aURL, aDocument.nodePrincipal);
@@ -614,7 +642,9 @@ function openNewWindowWith(aURL, aDocument, aPostData, aAllowThirdPartyFixup, aR
{ charset: originCharset,
postData: aPostData,
allowThirdPartyFixup: aAllowThirdPartyFixup,
- referrerURI: aDocument ? aDocument.documentURIObject : aReferrer });
+ referrerURI: aDocument ? aDocument.documentURIObject : aReferrer,
+ referrerPolicy: aReferrerPolicy,
+ });
}
/**
diff --git a/application/palemoon/base/jar.mn b/application/palemoon/base/jar.mn
index fd2df79e1..622d8e0da 100644
--- a/application/palemoon/base/jar.mn
+++ b/application/palemoon/base/jar.mn
@@ -108,7 +108,7 @@ browser.jar:
* content/browser/sanitize.xul (content/sanitize.xul)
* content/browser/sanitizeDialog.js (content/sanitizeDialog.js)
content/browser/sanitizeDialog.css (content/sanitizeDialog.css)
-* content/browser/autocomplete.css (content/autocomplete.css)
+ content/browser/autocomplete.css (content/autocomplete.css)
* content/browser/autocomplete.xml (content/autocomplete.xml)
content/browser/tabbrowser.css (content/tabbrowser.css)
* content/browser/tabbrowser.xml (content/tabbrowser.xml)
diff --git a/application/palemoon/components/about/AboutRedirector.cpp b/application/palemoon/components/about/AboutRedirector.cpp
index d52b873b9..27f6540b2 100644
--- a/application/palemoon/components/about/AboutRedirector.cpp
+++ b/application/palemoon/components/about/AboutRedirector.cpp
@@ -137,8 +137,13 @@ AboutRedirector::NewChannel(nsIURI* aURI,
for (int i = 0; i < kRedirTotal; i++) {
if (!strcmp(path.get(), kRedirMap[i].id)) {
nsCOMPtr<nsIChannel> tempChannel;
- rv = ioService->NewChannel(nsDependentCString(kRedirMap[i].url),
- nullptr, nullptr, getter_AddRefs(tempChannel));
+ nsCOMPtr<nsIURI> tempURI;
+ rv = NS_NewURI(getter_AddRefs(tempURI),
+ nsDependentCString(kRedirMap[i].url));
+ NS_ENSURE_SUCCESS(rv, rv);
+ rv = NS_NewChannelInternal(getter_AddRefs(tempChannel),
+ tempURI,
+ aLoadInfo);
NS_ENSURE_SUCCESS(rv, rv);
tempChannel->SetOriginalURI(aURI);
diff --git a/application/palemoon/components/downloads/content/allDownloadsViewOverlay.js b/application/palemoon/components/downloads/content/allDownloadsViewOverlay.js
index 46e867068..054f0405f 100644
--- a/application/palemoon/components/downloads/content/allDownloadsViewOverlay.js
+++ b/application/palemoon/components/downloads/content/allDownloadsViewOverlay.js
@@ -41,22 +41,6 @@ const DOWNLOAD_VIEW_SUPPORTED_COMMANDS =
const NOT_AVAILABLE = Number.MAX_VALUE;
/**
- * Download a URL.
- *
- * @param aURL
- * the url to download (nsIURI object)
- * @param [optional] aFileName
- * the destination file name
- */
-function DownloadURL(aURL, aFileName) {
- // For private browsing, try to get document out of the most recent browser
- // window, or provide our own if there's no browser window.
- let browserWin = RecentWindow.getMostRecentBrowserWindow();
- let initiatingDoc = browserWin ? browserWin.document : document;
- saveURL(aURL, aFileName, null, true, true, undefined, initiatingDoc);
-}
-
-/**
* A download element shell is responsible for handling the commands and the
* displayed data for a single download view element. The download element
* could represent either a past download (for which we get data from places) or
@@ -654,7 +638,10 @@ DownloadElementShell.prototype = {
// In future we may try to download into the same original target uri, when
// we have it. Though that requires verifying the path is still valid and
// may surprise the user if he wants to be requested every time.
- DownloadURL(this.downloadURI, this.getDownloadMetaData().fileName);
+ let browserWin = RecentWindow.getMostRecentBrowserWindow();
+ let initiatingDoc = browserWin ? browserWin.document : document;
+ DownloadURL(this.downloadURI, this.getDownloadMetaData().fileName,
+ initiatingDoc);
},
/* nsIController */
@@ -1407,16 +1394,11 @@ DownloadsPlacesView.prototype = {
_copySelectedDownloadsToClipboard:
function DPV__copySelectedDownloadsToClipboard() {
- let selectedElements = this._richlistbox.selectedItems;
- // Tycho: let urls = [e._shell.downloadURI for each (e in selectedElements)];
- let urls = [];
-
- for each (e in selectedElements) {
- urls.push(e._shell.downloadURI);
- }
+ let urls = [for (element of this._richlistbox.selectedItems)
+ element._shell.downloadURI];
Cc["@mozilla.org/widget/clipboardhelper;1"].
- getService(Ci.nsIClipboardHelper).copyString(urls.join("\n"), document);
+ getService(Ci.nsIClipboardHelper).copyString(urls.join("\n"));
},
_getURLFromClipboardData: function DPV__getURLFromClipboardData() {
@@ -1450,10 +1432,16 @@ DownloadsPlacesView.prototype = {
_downloadURLFromClipboard: function DPV__downloadURLFromClipboard() {
let [url, name] = this._getURLFromClipboardData();
- DownloadURL(url, name);
+ let browserWin = RecentWindow.getMostRecentBrowserWindow();
+ let initiatingDoc = browserWin ? browserWin.document : document;
+ DownloadURL(url, name, initiatingDoc);
},
doCommand: function DPV_doCommand(aCommand) {
+ // Commands may be invoked with keyboard shortcuts even if disabled.
+ if (!this.isCommandEnabled(aCommand)) {
+ return;
+ }
switch (aCommand) {
case "cmd_copy":
this._copySelectedDownloadsToClipboard();
@@ -1504,6 +1492,11 @@ DownloadsPlacesView.prototype = {
else
contextMenu.removeAttribute("state");
+ if (state == nsIDM.DOWNLOAD_DOWNLOADING) {
+ // The resumable property of a download may change at any time, so
+ // ensure we update the related command now.
+ goUpdateCommand("downloadsCmd_pauseResume");
+ }
return true;
},
@@ -1594,10 +1587,16 @@ DownloadsPlacesView.prototype = {
if (dt.mozGetDataAt("application/x-moz-file", 0))
return;
- let name = { };
- let url = Services.droppedLinkHandler.dropLink(aEvent, name);
- if (url)
- DownloadURL(url, name.value);
+ let links = Services.droppedLinkHandler.dropLinks(aEvent);
+ if (!links.length)
+ return;
+ let browserWin = RecentWindow.getMostRecentBrowserWindow();
+ let initiatingDoc = browserWin ? browserWin.document : document;
+ for (let link of links) {
+ if (link.url.startsWith("about:"))
+ continue;
+ DownloadURL(link.url, link.name, initiatingDoc);
+ }
}
};
diff --git a/application/palemoon/components/downloads/content/downloads.js b/application/palemoon/components/downloads/content/downloads.js
index 0412344bc..833d7d72f 100644
--- a/application/palemoon/components/downloads/content/downloads.js
+++ b/application/palemoon/components/downloads/content/downloads.js
@@ -507,8 +507,7 @@ const DownloadsPanel = {
let uri = NetUtil.newURI(url);
DownloadsCommon.log("Pasted URL seems valid. Starting download.");
- saveURL(uri.spec, name || uri.spec, null, true, true,
- undefined, document);
+ DownloadURL(uri.spec, name, document);
} catch (ex) {}
},
diff --git a/application/palemoon/components/downloads/content/indicator.js b/application/palemoon/components/downloads/content/indicator.js
index e6a5bd012..1a2175a92 100644
--- a/application/palemoon/components/downloads/content/indicator.js
+++ b/application/palemoon/components/downloads/content/indicator.js
@@ -548,15 +548,18 @@ const DownloadsIndicatorView = {
if (dt.mozGetDataAt("application/x-moz-file", 0))
return;
- let name = {};
- let url = browserDragAndDrop.drop(aEvent, name);
- if (url) {
- if (url.startsWith("about:")) {
- return;
- }
-
- let sourceDoc = dt.mozSourceNode ? dt.mozSourceNode.ownerDocument : document;
- saveURL(url, name.value, null, true, true, null, sourceDoc);
+ let links = browserDragAndDrop.dropLinks(aEvent);
+ if (!links.length)
+ return;
+ let sourceDoc = dt.mozSourceNode ? dt.mozSourceNode.ownerDocument : document;
+ let handled = false;
+ for (let link of links) {
+ if (link.url.startsWith("about:"))
+ continue;
+ saveURL(link.url, link.name, null, true, true, null, sourceDoc);
+ handled = true;
+ }
+ if (handled) {
aEvent.preventDefault();
}
},
diff --git a/application/palemoon/components/feeds/FeedWriter.js b/application/palemoon/components/feeds/FeedWriter.js
index cbb146564..2ae31dffa 100644
--- a/application/palemoon/components/feeds/FeedWriter.js
+++ b/application/palemoon/components/feeds/FeedWriter.js
@@ -1173,7 +1173,7 @@ FeedWriter.prototype = {
var secman = Cc["@mozilla.org/scriptsecuritymanager;1"].
getService(Ci.nsIScriptSecurityManager);
- this._feedPrincipal = secman.getSimpleCodebasePrincipal(this._feedURI);
+ this._feedPrincipal = secman.createCodebasePrincipal(this._feedURI, {});
LOG("Subscribe Preview: feed uri = " + this._window.location.href);
diff --git a/application/palemoon/components/nsBrowserGlue.js b/application/palemoon/components/nsBrowserGlue.js
index 225cddd52..aa24d88ef 100644
--- a/application/palemoon/components/nsBrowserGlue.js
+++ b/application/palemoon/components/nsBrowserGlue.js
@@ -13,7 +13,11 @@ const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
-// Define Lazy Module Gitters
+// Define Lazy Service Getters
+XPCOMUtils.defineLazyServiceGetter(this, "AlertsService",
+ "@mozilla.org/alerts-service;1", "nsIAlertsService");
+
+// Define Lazy Module Getters
[
["AddonManager", "resource://gre/modules/AddonManager.jsm"],
["NetUtil", "resource://gre/modules/NetUtil.jsm"],
@@ -37,8 +41,19 @@ Cu.import("resource://gre/modules/Services.jsm");
["FormValidationHandler", "resource:///modules/FormValidationHandler.jsm"],
["AutoCompletePopup", "resource:///modules/AutoCompletePopup.jsm"],
["DateTimePickerHelper", "resource://gre/modules/DateTimePickerHelper.jsm"],
+ ["ShellService", "resource:///modules/ShellService.jsm"],
].forEach(([name, resource]) => XPCOMUtils.defineLazyModuleGetter(this, name, resource));
+// Define Lazy Getters
+
+XPCOMUtils.defineLazyGetter(this, "gBrandBundle", function() {
+ return Services.strings.createBundle('chrome://branding/locale/brand.properties');
+});
+
+XPCOMUtils.defineLazyGetter(this, "gBrowserBundle", function() {
+ return Services.strings.createBundle('chrome://browser/locale/browser.properties');
+});
+
const PREF_PLUGINS_NOTIFYUSER = "plugins.update.notifyUser";
const PREF_PLUGINS_UPDATEURL = "plugins.update.url";
@@ -460,9 +475,7 @@ BrowserGlue.prototype = {
if (!win)
return;
- let productName = Services.strings
- .createBundle("chrome://branding/locale/brand.properties")
- .GetStringFromName("brandFullName");
+ let productName = gBrandBundle.GetStringFromName("brandFullName");
let message = win.gNavigatorBundle.getFormattedString("slowStartup.message", [productName]);
let buttons = [
@@ -559,17 +572,17 @@ BrowserGlue.prototype = {
}
// Perform default browser checking.
- var shell;
- try {
- shell = Components.classes["@mozilla.org/browser/shell-service;1"]
- .getService(Components.interfaces.nsIShellService);
- } catch (e) { }
- if (shell) {
-#ifdef DEBUG
- let shouldCheck = false;
-#else
- let shouldCheck = shell.shouldCheckDefaultBrowser;
-#endif
+ if (ShellService) {
+ let shouldCheck = ShellService.shouldCheckDefaultBrowser;
+
+ const skipDefaultBrowserCheck =
+ Services.prefs.getBoolPref("browser.shell.skipDefaultBrowserCheckOnFirstRun") &&
+ Services.prefs.getBoolPref("browser.shell.skipDefaultBrowserCheck");
+
+ const usePromptLimit = false;
+ let promptCount =
+ usePromptLimit ? Services.prefs.getIntPref("browser.shell.defaultBrowserCheckCount") : 0;
+
let willRecoverSession = false;
try {
let ss = Cc["@mozilla.org/browser/sessionstartup;1"].
@@ -579,9 +592,25 @@ BrowserGlue.prototype = {
}
catch (ex) { /* never mind; suppose SessionStore is broken */ }
- let isDefault = shell.isDefaultBrowser(true, false); // startup check, check all assoc
+ // startup check, check all assoc
+ let isDefault = false;
+ let isDefaultError = false;
+ try {
+ isDefault = ShellService.isDefaultBrowser(true, false);
+ } catch (ex) {
+ isDefaultError = true;
+ }
- if (shouldCheck && !isDefault && !willRecoverSession) {
+ if (isDefault) {
+ let now = (Math.floor(Date.now() / 1000)).toString();
+ Services.prefs.setCharPref("browser.shell.mostRecentDateSetAsDefault", now);
+ }
+
+ let willPrompt = shouldCheck && !isDefault && !willRecoverSession;
+
+ // Skip the "Set Default Browser" check during first-run or after the
+ // browser has been run a few times.
+ if (willPrompt) {
Services.tm.mainThread.dispatch(function() {
var win = this.getMostRecentBrowserWindow();
var brandBundle = win.document.getElementById("bundle_brand");
@@ -610,9 +639,9 @@ BrowserGlue.prototype = {
claimAllTypes = (parseFloat(version) < 6.2);
} catch (ex) { }
#endif
- shell.setDefaultBrowser(claimAllTypes, false);
+ ShellService.setDefaultBrowser(claimAllTypes, false);
}
- shell.shouldCheckDefaultBrowser = checkEveryTime.value;
+ ShellService.shouldCheckDefaultBrowser = checkEveryTime.value;
}.bind(this), Ci.nsIThread.DISPATCH_NORMAL);
}
}
@@ -693,9 +722,8 @@ BrowserGlue.prototype = {
let prompt = Services.prompt;
let quitBundle = Services.strings.createBundle("chrome://browser/locale/quitDialog.properties");
- let brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
- let appName = brandBundle.GetStringFromName("brandShortName");
+ let appName = gBrandBundle.GetStringFromName("brandShortName");
let quitDialogTitle = quitBundle.formatStringFromName("quitDialogTitle",
[appName], 1);
let neverAskText = quitBundle.GetStringFromName("neverAsk2");
@@ -772,9 +800,7 @@ BrowserGlue.prototype = {
var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].
getService(Ci.nsIURLFormatter);
- var browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");
- var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
- var appName = brandBundle.GetStringFromName("brandShortName");
+ var appName = gBrandBundle.GetStringFromName("brandShortName");
function getNotifyString(aPropData) {
var propValue = update.getProperty(aPropData.propName);
@@ -782,11 +808,11 @@ BrowserGlue.prototype = {
if (aPropData.prefName)
propValue = formatter.formatURLPref(aPropData.prefName);
else if (aPropData.stringParams)
- propValue = browserBundle.formatStringFromName(aPropData.stringName,
- aPropData.stringParams,
- aPropData.stringParams.length);
+ propValue = gBrowserBundle.formatStringFromName(aPropData.stringName,
+ aPropData.stringParams,
+ aPropData.stringParams.length);
else
- propValue = browserBundle.GetStringFromName(aPropData.stringName);
+ propValue = gBrowserBundle.GetStringFromName(aPropData.stringName);
}
return propValue;
}
@@ -825,16 +851,6 @@ BrowserGlue.prototype = {
if (actions.indexOf("showAlert") == -1)
return;
- let notifier;
- try {
- notifier = Cc["@mozilla.org/alerts-service;1"].
- getService(Ci.nsIAlertsService);
- }
- catch (e) {
- // nsIAlertsService is not available for this platform
- return;
- }
-
let title = getNotifyString({propName: "alertTitle",
stringName: "puAlertTitle",
stringParams: [appName]});
@@ -856,10 +872,11 @@ BrowserGlue.prototype = {
try {
// This will throw NS_ERROR_NOT_AVAILABLE if the notification cannot
// be displayed per the idl.
- notifier.showAlertNotification(null, title, text,
- true, url, clickCallback);
+ AlertsService.showAlertNotification(null, title, text,
+ true, url, clickCallback);
}
catch (e) {
+ Cu.reportError(e);
}
},
@@ -1156,8 +1173,7 @@ BrowserGlue.prototype = {
* Show the notificationBox for a locked places database.
*/
_showPlacesLockedNotificationBox: function BG__showPlacesLockedNotificationBox() {
- var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
- var applicationName = brandBundle.GetStringFromName("brandShortName");
+ var applicationName = gBrandBundle.GetStringFromName("brandShortName");
var placesBundle = Services.strings.createBundle("chrome://browser/locale/places/places.properties");
var title = placesBundle.GetStringFromName("lockPrompt.title");
var text = placesBundle.formatStringFromName("lockPrompt.text", [applicationName], 1);
@@ -1191,7 +1207,7 @@ BrowserGlue.prototype = {
},
_migrateUI: function BG__migrateUI() {
- const UI_VERSION = 15;
+ const UI_VERSION = 17;
const BROWSER_DOCURL = "chrome://browser/content/browser.xul#";
let currentUIVersion = 0;
try {
@@ -1386,6 +1402,10 @@ BrowserGlue.prototype = {
}
}
+ if (currentUIVersion < 17) {
+ this._notifyNotificationsUpgrade();
+ }
+
if (this._dirty)
this._dataSource.QueryInterface(Ci.nsIRDFRemoteDataSource).Flush();
@@ -1396,6 +1416,52 @@ BrowserGlue.prototype = {
Services.prefs.setIntPref("browser.migration.version", UI_VERSION);
},
+ _hasExistingNotificationPermission: function BG__hasExistingNotificationPermission() {
+ let enumerator = Services.perms.enumerator;
+ while (enumerator.hasMoreElements()) {
+ let permission = enumerator.getNext().QueryInterface(Ci.nsIPermission);
+ if (permission.type == "desktop-notification") {
+ return true;
+ }
+ }
+ return false;
+ },
+
+ _notifyNotificationsUpgrade: function BG__notifyNotificationsUpgrade() {
+ if (!this._hasExistingNotificationPermission()) {
+ return;
+ }
+ function clickCallback(subject, topic, data) {
+ if (topic != "alertclickcallback")
+ return;
+ let win = RecentWindow.getMostRecentBrowserWindow();
+ win.openUILinkIn(data, "tab");
+ }
+ // Show the application icon for XUL notifications. We assume system-level
+ // notifications will include their own icon.
+ let imageURL = this._hasSystemAlertsService() ? "" :
+ "chrome://branding/content/about-logo.png";
+ let title = gBrowserBundle.GetStringFromName("webNotifications.upgradeTitle");
+ let text = gBrowserBundle.GetStringFromName("webNotifications.upgradeBody");
+ let url = Services.urlFormatter.formatURLPref("browser.push.warning.infoURL");
+
+ try {
+ AlertsService.showAlertNotification(imageURL, title, text,
+ true, url, clickCallback);
+ }
+ catch (e) {
+ Cu.reportError(e);
+ }
+ },
+
+ _hasSystemAlertsService: function() {
+ try {
+ return !!Cc["@mozilla.org/system-alerts-service;1"].getService(
+ Ci.nsIAlertsService);
+ } catch (e) {}
+ return false;
+ },
+
_getPersist: function BG__getPersist(aSource, aProperty) {
var target = this._dataSource.GetTarget(aSource, aProperty, true);
if (target instanceof Ci.nsIRDFLiteral)
@@ -1645,6 +1711,16 @@ ContentPermissionPrompt.prototype = {
return chromeWin;
},
+ _getBrowserForRequest: function (aRequest) {
+ let requestingWindow = aRequest.window.top;
+ // find the requesting browser or iframe
+ let browser = requestingWindow.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebNavigation)
+ .QueryInterface(Ci.nsIDocShell)
+ .chromeEventHandler;
+ return browser;
+ },
+
/**
* Show a permission prompt.
*
@@ -1665,8 +1741,6 @@ ContentPermissionPrompt.prototype = {
popup.remove();
}
- var browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");
-
var requestingWindow = aRequest.window.top;
var chromeWin = this._getChromeWindow(requestingWindow).wrappedJSObject;
var browser = chromeWin.gBrowser.getBrowserForDocument(requestingWindow.document);
@@ -1692,8 +1766,8 @@ ContentPermissionPrompt.prototype = {
}
var action = {
- label: browserBundle.GetStringFromName(promptAction.stringId),
- accessKey: browserBundle.GetStringFromName(promptAction.stringId + ".accesskey"),
+ label: gBrowserBundle.GetStringFromName(promptAction.stringId),
+ accessKey: gBrowserBundle.GetStringFromName(promptAction.stringId + ".accesskey"),
callback: function() {
if (promptAction.callback) {
promptAction.callback();
@@ -1752,7 +1826,6 @@ ContentPermissionPrompt.prototype = {
},
_promptGeo : function(aRequest) {
- var browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");
var requestingURI = aRequest.principal.URI;
var message;
@@ -1768,11 +1841,11 @@ ContentPermissionPrompt.prototype = {
}];
if (requestingURI.schemeIs("file")) {
- message = browserBundle.formatStringFromName("geolocation.shareWithFile",
- [requestingURI.path], 1);
+ message = gBrowserBundle.formatStringFromName("geolocation.shareWithFile",
+ [requestingURI.path], 1);
} else {
- message = browserBundle.formatStringFromName("geolocation.shareWithSite",
- [requestingURI.host], 1);
+ message = gBrowserBundle.formatStringFromName("geolocation.shareWithSite",
+ [requestingURI.host], 1);
// Always share location action.
actions.push({
stringId: "geolocation.alwaysShareLocation",
@@ -1803,47 +1876,63 @@ ContentPermissionPrompt.prototype = {
},
_promptWebNotifications : function(aRequest) {
- var browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");
var requestingURI = aRequest.principal.URI;
- var message = browserBundle.formatStringFromName("webNotifications.showFromSite",
- [requestingURI.host], 1);
+ var message = gBrowserBundle.formatStringFromName("webNotifications.showFromSite",
+ [requestingURI.host], 1);
- var actions = [
- {
- stringId: "webNotifications.showForSession",
- action: Ci.nsIPermissionManager.ALLOW_ACTION,
- expireType: Ci.nsIPermissionManager.EXPIRE_SESSION,
- callback: function() {},
- },
- {
- stringId: "webNotifications.alwaysShow",
- action: Ci.nsIPermissionManager.ALLOW_ACTION,
- expireType: null,
- callback: function() {},
- },
- {
- stringId: "webNotifications.neverShow",
- action: Ci.nsIPermissionManager.DENY_ACTION,
- expireType: null,
- callback: function() {},
- },
- ];
+ var actions;
+
+ var browser = this._getBrowserForRequest(aRequest);
+ // Only show "allow for session" in PB mode, we don't
+ // support "allow for session" in non-PB mode.
+ if (PrivateBrowsingUtils.isBrowserPrivate(browser)) {
+ actions = [
+ {
+ stringId: "webNotifications.showForSession",
+ action: Ci.nsIPermissionManager.ALLOW_ACTION,
+ expireType: Ci.nsIPermissionManager.EXPIRE_SESSION,
+ callback: function() {},
+ },
+ ];
+ } else {
+ actions = [
+ {
+ stringId: "webNotifications.showForSession",
+ action: Ci.nsIPermissionManager.ALLOW_ACTION,
+ expireType: Ci.nsIPermissionManager.EXPIRE_SESSION,
+ callback: function() {},
+ },
+ {
+ stringId: "webNotifications.alwaysShow",
+ action: Ci.nsIPermissionManager.ALLOW_ACTION,
+ expireType: null,
+ callback: function() {},
+ },
+ {
+ stringId: "webNotifications.neverShow",
+ action: Ci.nsIPermissionManager.DENY_ACTION,
+ expireType: null,
+ callback: function() {},
+ },
+ ];
+ }
+ var options = {
+ learnMoreURL: Services.urlFormatter.formatURLPref("browser.push.warning.infoURL"),
+ };
this._showPrompt(aRequest, message, "desktop-notification", actions,
"web-notifications",
- "web-notifications-notification-icon", null);
+ "web-notifications-notification-icon", options);
},
_promptPointerLock: function CPP_promtPointerLock(aRequest, autoAllow) {
-
- let browserBundle = Services.strings.createBundle("chrome://browser/locale/browser.properties");
let requestingURI = aRequest.principal.URI;
let originString = requestingURI.schemeIs("file") ? requestingURI.path : requestingURI.host;
- let message = browserBundle.formatStringFromName(autoAllow ?
- "pointerLock.autoLock.title2" : "pointerLock.title2",
- [originString], 1);
+ let message = gBrowserBundle.formatStringFromName(autoAllow ?
+ "pointerLock.autoLock.title2" : "pointerLock.title2",
+ [originString], 1);
// If this is an autoAllow info prompt, offer no actions.
// _showPrompt() will allow the request when it's dismissed.
let actions = [];
@@ -1875,7 +1964,6 @@ ContentPermissionPrompt.prototype = {
},
prompt: function CPP_prompt(request) {
-
// Only allow exactly one permission rquest here.
let types = request.types.QueryInterface(Ci.nsIArray);
if (types.length != 1) {
@@ -1921,15 +2009,15 @@ ContentPermissionPrompt.prototype = {
// Show the prompt.
switch (perm.type) {
- case "geolocation":
- this._promptGeo(request);
- break;
- case "desktop-notification":
- this._promptWebNotifications(request);
- break;
- case "pointerLock":
- this._promptPointerLock(request, autoAllow);
- break;
+ case "geolocation":
+ this._promptGeo(request);
+ break;
+ case "desktop-notification":
+ this._promptWebNotifications(request);
+ break;
+ case "pointerLock":
+ this._promptPointerLock(request, autoAllow);
+ break;
}
},
diff --git a/application/palemoon/components/places/content/editBookmarkOverlay.js b/application/palemoon/components/places/content/editBookmarkOverlay.js
index 43645cc73..69d7d32eb 100644
--- a/application/palemoon/components/places/content/editBookmarkOverlay.js
+++ b/application/palemoon/components/places/content/editBookmarkOverlay.js
@@ -12,6 +12,7 @@ var gEditItemOverlay = {
_uris: [],
_tags: [],
_allTags: [],
+ _keyword: null,
_multiEdit: false,
_itemType: -1,
_readOnly: false,
@@ -139,9 +140,8 @@ var gEditItemOverlay = {
this._itemType = PlacesUtils.bookmarks.getItemType(this._itemId);
if (this._itemType == Ci.nsINavBookmarksService.TYPE_BOOKMARK) {
this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._itemId);
- this._initTextField("keywordField",
- PlacesUtils.bookmarks
- .getKeywordForBookmark(this._itemId));
+ this._keyword = PlacesUtils.bookmarks.getKeywordForBookmark(this._itemId);
+ this._initTextField("keywordField", this._keyword);
this._element("loadInSidebarCheckbox").checked =
PlacesUtils.annotations.itemHasAnnotation(this._itemId,
PlacesUIUtils.LOAD_IN_SIDEBAR_ANNO);
@@ -610,9 +610,13 @@ var gEditItemOverlay = {
},
onKeywordFieldBlur: function EIO_onKeywordFieldBlur() {
- var keyword = this._element("keywordField").value;
- if (keyword != PlacesUtils.bookmarks.getKeywordForBookmark(this._itemId)) {
- var txn = new PlacesEditBookmarkKeywordTransaction(this._itemId, keyword);
+ let oldKeyword = this._keyword;
+ let keyword = this._keyword = this._element("keywordField").value;
+ if (keyword != oldKeyword) {
+ let txn = new PlacesEditBookmarkKeywordTransaction(this._itemId,
+ keyword,
+ null,
+ oldKeyword);
PlacesUtils.transactionManager.doTransaction(txn);
}
},
@@ -1004,9 +1008,8 @@ var gEditItemOverlay = {
}
break;
case "keyword":
- this._initTextField("keywordField",
- PlacesUtils.bookmarks
- .getKeywordForBookmark(this._itemId));
+ this._keyword = PlacesUtils.bookmarks.getKeywordForBookmark(this._itemId);
+ this._initTextField("keywordField", this._keyword);
break;
case PlacesUIUtils.DESCRIPTION_ANNO:
this._initTextField("descriptionField",
diff --git a/application/palemoon/components/preferences/aboutPermissions.js b/application/palemoon/components/preferences/aboutPermissions.js
index 31b48f88e..9fb12d081 100644
--- a/application/palemoon/components/preferences/aboutPermissions.js
+++ b/application/palemoon/components/preferences/aboutPermissions.js
@@ -2,17 +2,25 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
var Ci = Components.interfaces;
var Cc = Components.classes;
var Cu = Components.utils;
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/PluralForm.jsm");
Cu.import("resource://gre/modules/DownloadUtils.jsm");
Cu.import("resource://gre/modules/AddonManager.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/ForgetAboutSite.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PluralForm",
+ "resource://gre/modules/PluralForm.jsm");
+
+var gSecMan = Cc["@mozilla.org/scriptsecuritymanager;1"].
+ getService(Ci.nsIScriptSecurityManager);
+
var gFaviconService = Cc["@mozilla.org/browser/favicon-service;1"].
getService(Ci.nsIFaviconService);
@@ -22,7 +30,7 @@ var gPlacesDatabase = Cc["@mozilla.org/browser/nav-history-service;1"].
clone(true);
var gSitesStmt = gPlacesDatabase.createAsyncStatement(
- "SELECT get_unreversed_host(rev_host) AS host " +
+ "SELECT url " +
"FROM moz_places " +
"WHERE rev_host > '.' " +
"AND visit_count > 0 " +
@@ -54,14 +62,11 @@ const MASTER_PASSWORD_MESSAGE = "User canceled master password entry";
const TEST_EXACT_PERM_TYPES = ["desktop-notification", "geo", "pointerLock"];
/**
- * Site object represents a single site, uniquely identified by a host.
+ * Site object represents a single site, uniquely identified by a principal.
*/
-function Site(host) {
- this.host = host;
+function Site(principal) {
+ this.principal = principal;
this.listitem = null;
-
- this.httpURI = NetUtil.newURI("http://" + this.host);
- this.httpsURI = NetUtil.newURI("https://" + this.host);
}
Site.prototype = {
@@ -83,16 +88,10 @@ Site.prototype = {
}
}
- // Try to find favicon for both URIs, but always prefer the https favicon.
- gFaviconService.getFaviconURLForPage(this.httpsURI, function(aURI) {
+ // Get the favicon for the origin
+ gFaviconService.getFaviconURLForPage(this.principal.URI, function (aURI) {
if (aURI) {
invokeCallback(aURI);
- } else {
- gFaviconService.getFaviconURLForPage(this.httpURI, function(aURI) {
- if (aURI) {
- invokeCallback(aURI);
- }
- });
}
}.bind(this));
},
@@ -104,7 +103,9 @@ Site.prototype = {
* A function that takes the visit count (a number) as a parameter.
*/
getVisitCount: function Site_getVisitCount(aCallback) {
- let rev_host = this.host.split("").reverse().join("") + ".";
+ // XXX This won't be a very reliable system, as it will count both http: and https: visits
+ // Unfortunately, I don't think that there is a much better way to do it right now.
+ let rev_host = this.principal.URI.host.split("").reverse().join("") + ".";
gVisitStmt.params.rev_host = rev_host;
gVisitStmt.executeAsync({
handleResult: function(aResults) {
@@ -147,9 +148,9 @@ Site.prototype = {
let permissionValue;
if (TEST_EXACT_PERM_TYPES.indexOf(aType) == -1) {
- permissionValue = Services.perms.testPermission(this.httpURI, aType);
+ permissionValue = Services.perms.testPermissionFromPrincipal(this.principal, aType);
} else {
- permissionValue = Services.perms.testExactPermission(this.httpURI, aType);
+ permissionValue = Services.perms.testExactPermissionFromPrincipal(this.principal, aType);
}
aResultObj.value = permissionValue;
@@ -187,9 +188,7 @@ Site.prototype = {
}
}
- // Using httpURI is kind of bogus, but the permission manager stores
- // the permission for the host, so the right thing happens in the end.
- Services.perms.add(this.httpURI, aType, aPerm);
+ Services.perms.addFromPrincipal(this.principal, aType, aPerm);
},
/**
@@ -200,7 +199,7 @@ Site.prototype = {
* e.g. "cookie", "geo", "indexedDB", "popup", "image"
*/
clearPermission: function Site_clearPermission(aType) {
- Services.perms.remove(this.host, aType);
+ Services.perms.removeFromPrincipal(this.principal, aType);
},
/**
@@ -210,11 +209,9 @@ Site.prototype = {
*/
get logins() {
try {
- let httpLogins = Services.logins.findLogins(
- {}, this.httpURI.prePath, "", "");
- let httpsLogins = Services.logins.findLogins(
- {}, this.httpsURI.prePath, "", "");
- return httpLogins.concat(httpsLogins);
+ let logins = Services.logins.findLogins({},
+ this.principal.originNoSuffix, "", "");
+ return logins;
} catch (e) {
if (!e.message.includes(MASTER_PASSWORD_MESSAGE)) {
Cu.reportError("AboutPermissions: " + e);
@@ -227,8 +224,7 @@ Site.prototype = {
// Only say that login saving is blocked if it is blocked for both
// http and https.
try {
- return Services.logins.getLoginSavingEnabled(this.httpURI.prePath) &&
- Services.logins.getLoginSavingEnabled(this.httpsURI.prePath);
+ return Services.logins.getLoginSavingEnabled(this.principal.originNoSuffix);
} catch (e) {
if (!e.message.includes(MASTER_PASSWORD_MESSAGE)) {
Cu.reportError("AboutPermissions: " + e);
@@ -239,8 +235,7 @@ Site.prototype = {
set loginSavingEnabled(isEnabled) {
try {
- Services.logins.setLoginSavingEnabled(this.httpURI.prePath, isEnabled);
- Services.logins.setLoginSavingEnabled(this.httpsURI.prePath, isEnabled);
+ Services.logins.setLoginSavingEnabled(this.principal.originNoSuffix, isEnabled);
} catch (e) {
if (!e.message.includes(MASTER_PASSWORD_MESSAGE)) {
Cu.reportError("AboutPermissions: " + e);
@@ -279,7 +274,11 @@ Site.prototype = {
* Removes all data from the browser corresponding to the site.
*/
forgetSite: function Site_forgetSite() {
- ForgetAboutSite.removeDataFromDomain(this.host)
+ // XXX This removes data for an entire domain, rather than just
+ // an origin. This may produce confusing results, as data will
+ // be cleared for the http:// as well as the https:// domain
+ // if you try to forget the https:// site.
+ ForgetAboutSite.removeDataFromDomain(this.principal.URI.host)
.catch(Cu.reportError);
}
}
@@ -419,31 +418,6 @@ var PermissionDefaults = {
Services.prefs.setBoolPref("dom.indexedDB.enabled", value);
},
- get fullscreen() {
- if (!Services.prefs.getBoolPref("full-screen-api.enabled")) {
- return this.DENY;
- }
- // We always ask for permission to fullscreen with a specific site,
- // so there is no global ALLOW.
- return this.UNKNOWN;
- },
- set fullscreen(aValue) {
- let value = (aValue != this.DENY);
- Services.prefs.setBoolPref("full-screen-api.enabled", value);
- },
-
- get pointerLock() {
- if (!Services.prefs.getBoolPref("full-screen-api.pointer-lock.enabled")) {
- return this.DENY;
- }
- // We always ask for permission to hide the mouse pointer
- // with a specific site, so there is no global ALLOW.
- return this.UNKNOWN;
- },
- set pointerLock(aValue) {
- let value = (aValue != this.DENY);
- Services.prefs.setBoolPref("full-screen-api.pointer-lock.enabled", value);
- },
}
/**
@@ -461,10 +435,18 @@ var AboutPermissions = {
LIST_BUILD_DELAY: 100, // delay between intervals
/**
- * Stores a mapping of host strings to Site objects.
+ * Stores a mapping of origin strings to Site objects.
*/
_sites: {},
+ /**
+ * Using a getter for sitesFilter to avoid races with tests.
+ */
+ get sitesFilter () {
+ delete this.sitesFilter;
+ return this.sitesFilter = document.getElementById("sites-filter");
+ },
+
sitesList: null,
_selectedSite: null,
@@ -482,14 +464,12 @@ var AboutPermissions = {
* Potential future additions: "sts/use", "sts/subd"
*/
_supportedPermissions: ["password", "image", "popup", "cookie",
- "desktop-notification", "install", "geo", "indexedDB",
- "fullscreen", "pointerLock"],
+ "desktop-notification", "install", "geo", "indexedDB"],
/**
* Permissions that don't have a global "Allow" option.
*/
- _noGlobalAllow: ["desktop-notification", "geo", "indexedDB", "fullscreen",
- "pointerLock"],
+ _noGlobalAllow: ["desktop-notification", "geo", "indexedDB"],
/**
* Permissions that don't have a global "Deny" option.
@@ -536,8 +516,6 @@ var AboutPermissions = {
Services.prefs.addObserver("geo.enabled", this, false);
Services.prefs.addObserver("dom.indexedDB.enabled", this, false);
Services.prefs.addObserver("plugins.click_to_play", this, false);
- Services.prefs.addObserver("full-screen-api.enabled", this, false);
- Services.prefs.addObserver("full-screen-api.pointer-lock.enabled", this, false);
Services.prefs.addObserver("permissions.places-sites-limit", this, false);
Services.obs.addObserver(this, "perm-changed", false);
@@ -688,8 +666,6 @@ var AboutPermissions = {
Services.prefs.removeObserver("geo.enabled", this, false);
Services.prefs.removeObserver("dom.indexedDB.enabled", this, false);
Services.prefs.removeObserver("plugins.click_to_play", this, false);
- Services.prefs.removeObserver("full-screen-api.enabled", this, false);
- Services.prefs.removeObserver("full-screen-api.pointer-lock.enabled", this, false);
Services.prefs.removeObserver("permissions.places-sites-limit", this, false);
Services.obs.removeObserver(this, "perm-changed");
@@ -721,9 +697,9 @@ var AboutPermissions = {
break;
}
let permission = aSubject.QueryInterface(Ci.nsIPermission);
- // We can't compare selectedSite.host and permission.host here because
- // we need to handle the case where a parent domain was changed in
- // a way that affects the subdomain.
+ // We can't compare selectedSite.principal and permission.principal here
+ // because we need to handle the case where a parent domain was changed
+ // in a way that affects the subdomain.
if (this._supportedPermissions.indexOf(permission.type) != -1) {
this.updatePermission(permission.type);
}
@@ -798,8 +774,11 @@ var AboutPermissions = {
AboutPermissions.startSitesListBatch();
let row;
while (row = aResults.getNextRow()) {
- let host = row.getResultByName("host");
- AboutPermissions.addHost(host);
+ let spec = row.getResultByName("url");
+ let uri = NetUtil.newURI(spec);
+ let principal = gSecMan.getNoAppCodebasePrincipal(uri);
+
+ AboutPermissions.addPrincipal(principal);
}
AboutPermissions.endSitesListBatch();
},
@@ -853,7 +832,8 @@ var AboutPermissions = {
// i.e.: "chrome://weave" (Sync)
if (!aLogin.hostname.startsWith(schemeChrome + ":")) {
let uri = NetUtil.newURI(aLogin.hostname);
- this.addHost(uri.host);
+ let principal = gSecMan.getNoAppCodebasePrincipal(uri);
+ this.addPrincipal(principal);
}
} catch (e) {
Cu.reportError("AboutPermissions: " + e);
@@ -869,7 +849,8 @@ var AboutPermissions = {
// i.e.: "chrome://weave" (Sync)
if (!aHostname.startsWith(schemeChrome + ":")) {
let uri = NetUtil.newURI(aHostname);
- this.addHost(uri.host);
+ let principal = gSecMan.getNoAppCodebasePrincipal(uri);
+ this.addPrincipal(principal);
}
} catch (e) {
Cu.reportError("AboutPermissions: " + e);
@@ -887,7 +868,7 @@ var AboutPermissions = {
let permission = enumerator.getNext().QueryInterface(Ci.nsIPermission);
// Only include sites with exceptions set for supported permission types.
if (this._supportedPermissions.indexOf(permission.type) != -1) {
- this.addHost(permission.host);
+ this.addPrincipal(permission.principal);
}
itemCnt++;
}
@@ -898,15 +879,15 @@ var AboutPermissions = {
/**
* Creates a new Site and adds it to _sites if it's not already there.
*
- * @param aHost
- * A host string.
+ * @param aPrincipal
+ * A principal.
*/
- addHost: function(aHost) {
- if (aHost in this._sites) {
+ addPrincipal: function(aPrincipal) {
+ if (aPrincipal.origin in this._sites) {
return;
}
- let site = new Site(aHost);
- this._sites[aHost] = site;
+ let site = new Site(aPrincipal);
+ this._sites[aPrincipal.origin] = site;
this.addToSitesList(site);
},
@@ -919,7 +900,7 @@ var AboutPermissions = {
addToSitesList: function(aSite) {
let item = document.createElement("richlistitem");
item.setAttribute("class", "site");
- item.setAttribute("value", aSite.host);
+ item.setAttribute("value", aSite.principal.origin);
aSite.getFavicon(function(aURL) {
item.setAttribute("favicon", aURL);
@@ -927,9 +908,8 @@ var AboutPermissions = {
aSite.listitem = item;
// Make sure to only display relevant items when list is filtered.
- let filterValue =
- document.getElementById("sites-filter").value.toLowerCase();
- item.collapsed = aSite.host.toLowerCase().indexOf(filterValue) == -1;
+ let filterValue = this.sitesFilter.value.toLowerCase();
+ item.collapsed = aSite.principal.origin.toLowerCase().indexOf(filterValue) == -1;
(this._listFragment || this.sitesList).appendChild(item);
},
@@ -951,8 +931,7 @@ var AboutPermissions = {
*/
filterSitesList: function() {
let siteItems = this.sitesList.children;
- let filterValue =
- document.getElementById("sites-filter").value.toLowerCase();
+ let filterValue = this.sitesFilter.value.toLowerCase();
if (filterValue == "") {
for (let i = 0, iLen = siteItems.length; i < iLen; i++) {
@@ -983,9 +962,9 @@ var AboutPermissions = {
* The host string corresponding to the site to delete.
*/
deleteFromSitesList: function(aHost) {
- for (let host in this._sites) {
- let site = this._sites[host];
- if (site.host.hasRootDomain(aHost)) {
+ for (let origin in this._sites) {
+ let site = this._sites[origin];
+ if (site.principal.URI.host.hasRootDomain(aHost)) {
if (site == this._selectedSite) {
// Replace site-specific interface with "All Sites" interface.
this.sitesList.selectedItem =
@@ -993,7 +972,7 @@ var AboutPermissions = {
}
this.sitesList.removeChild(site.listitem);
- delete this._sites[site.host];
+ delete this._sites[site.principal.origin];
}
}
},
@@ -1009,9 +988,9 @@ var AboutPermissions = {
return;
}
- let host = event.target.value;
- let site = this._selectedSite = this._sites[host];
- document.getElementById("site-label").value = host;
+ let origin = event.target.value;
+ let site = this._selectedSite = this._sites[origin];
+ document.getElementById("site-label").value = origin;
document.getElementById("header-deck").selectedPanel =
document.getElementById("site-header");
@@ -1245,19 +1224,19 @@ var AboutPermissions = {
* Opens password manager dialog.
*/
managePasswords: function() {
- let selectedHost = "";
+ let selectedOrigin = "";
if (this._selectedSite) {
- selectedHost = this._selectedSite.host;
+ selectedOrigin = this._selectedSite.principal.URI.prePath;
}
let win = Services.wm.getMostRecentWindow("Toolkit:PasswordManager");
if (win) {
- win.setFilter(selectedHost);
+ win.setFilter(selectedOrigin);
win.focus();
} else {
window.openDialog("chrome://passwordmgr/content/passwordManager.xul",
"Toolkit:PasswordManager", "",
- {filterString : selectedHost});
+ {filterString : selectedOrigin});
}
},
@@ -1313,10 +1292,12 @@ var AboutPermissions = {
* Opens cookie manager dialog.
*/
manageCookies: function() {
+ // Cookies are stored by-host, and thus we filter the cookie window
+ // using only the host of the selected principal's origin
let selectedHost = "";
let selectedDomain = "";
if (this._selectedSite) {
- selectedHost = this._selectedSite.host;
+ selectedHost = this._selectedSite.principal.URI.host;
selectedDomain = this.domainFromHost(selectedHost);
}
@@ -1328,6 +1309,13 @@ var AboutPermissions = {
window.openDialog("chrome://browser/content/preferences/cookies.xul",
"Browser:Cookies", "", {filterString : selectedDomain});
}
+ },
+
+ /**
+ * Focusses the filter box.
+ */
+ focusFilterBox: function() {
+ this.sitesFilter.focus();
}
}
diff --git a/application/palemoon/components/preferences/aboutPermissions.xul b/application/palemoon/components/preferences/aboutPermissions.xul
index bd5a205c7..56d6cfbbf 100644
--- a/application/palemoon/components/preferences/aboutPermissions.xul
+++ b/application/palemoon/components/preferences/aboutPermissions.xul
@@ -25,6 +25,10 @@
<script type="application/javascript"
src="chrome://browser/content/preferences/aboutPermissions.js"/>
+ <keyset>
+ <key key="&focusSearch.key;" modifiers="accel" oncommand="AboutPermissions.focusFilterBox();"/>
+ </keyset>
+
<hbox flex="1" id="permissions-header">
<label id="permissions-pagetitle">&permissionsManager.title;</label>
</hbox>
@@ -332,65 +336,6 @@
<vbox id="plugins-box"/>
</vbox>
</hbox>
-
- <!-- Fullscreen -->
- <hbox id="fullscreen-pref-item"
- class="pref-item" align="top">
- <image class="pref-icon" type="fullscreen"/>
- <vbox>
- <hbox>
- <label class="pref-title" value="&fullscreen.label;"/>
- <label id="fullscreen-default" class="pref-default" value="*"/>
- </hbox>
- <hbox align="center">
- <menulist id="fullscreen-menulist"
- class="pref-menulist"
- type="fullscreen"
- oncommand="AboutPermissions.onPermissionCommand(event, false);">
- <menupopup>
- <menuitem id="fullscreen-0" value="0" label="&permission.alwaysAsk;"/>
- <menuitem id="fullscreen-1" value="1" label="&permission.allow;"/>
- <menuitem id="fullscreen-2" value="2" label="&permission.block;"/>
- </menupopup>
- </menulist>
- <button id="fullscreen-set-default"
- class="pref-set-default"
- label="&permission.default;"
- type="fullscreen"
- oncommand="AboutPermissions.onPermissionCommand(event, true);"/>
- </hbox>
- </vbox>
- </hbox>
-
- <!-- PointerLock -->
- <hbox id="pointerLock-pref-item"
- class="pref-item" align="top">
- <image class="pref-icon" type="pointerLock"/>
- <vbox>
- <hbox>
- <label class="pref-title" value="&pointerLock.label;"/>
- <label id="pointerLock-default" class="pref-default" value="*"/>
- </hbox>
- <hbox>
- <menulist id="pointerLock-menulist"
- class="pref-menulist"
- type="pointerLock"
- oncommand="AboutPermissions.onPermissionCommand(event, false);">
- <menupopup>
- <menuitem id="pointerLock-0" value="0" label="&permission.alwaysAsk;"/>
- <menuitem id="pointerLock-1" value="1" label="&permission.allow;"/>
- <menuitem id="pointerLock-2" value="2" label="&permission.block;"/>
- </menupopup>
- </menulist>
- <button id="pointerLock-set-default"
- class="pref-set-default"
- label="&permission.default;"
- type="pointerLock"
- oncommand="AboutPermissions.onPermissionCommand(event, true);"/>
- </hbox>
- </vbox>
- </hbox>
-
</vbox>
</hbox>
diff --git a/application/palemoon/components/preferences/advanced.js b/application/palemoon/components/preferences/advanced.js
index 429a0c419..0803496fe 100644
--- a/application/palemoon/components/preferences/advanced.js
+++ b/application/palemoon/components/preferences/advanced.js
@@ -8,6 +8,7 @@ Components.utils.import("resource://gre/modules/DownloadUtils.jsm");
Components.utils.import("resource://gre/modules/ctypes.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/LoadContextInfo.jsm");
+Components.utils.import("resource://gre/modules/BrowserUtils.jsm");
var gAdvancedPane = {
_inited: false,
@@ -377,7 +378,7 @@ var gAdvancedPane = {
},
// XXX: duplicated in browser.js
- _getOfflineAppUsage: function (host, groups)
+ _getOfflineAppUsage: function (perm, groups)
{
var cacheService = Components.classes["@mozilla.org/network/application-cache-service;1"].
getService(Components.interfaces.nsIApplicationCacheService);
@@ -390,7 +391,7 @@ var gAdvancedPane = {
var usage = 0;
for (var i = 0; i < groups.length; i++) {
var uri = ios.newURI(groups[i], null, null);
- if (uri.asciiHost == host) {
+ if (perm.matchesURI(uri, true)) {
var cache = cacheService.getActiveCache(groups[i]);
usage += cache.usage;
}
@@ -427,9 +428,9 @@ var gAdvancedPane = {
var row = document.createElement("listitem");
row.id = "";
row.className = "offlineapp";
- row.setAttribute("host", perm.host);
+ row.setAttribute("origin", perm.principal.origin);
var converted = DownloadUtils.
- convertByteUnits(this._getOfflineAppUsage(perm.host, groups));
+ convertByteUnits(this._getOfflineAppUsage(perm, groups));
row.setAttribute("usage",
bundle.getFormattedString("offlineAppUsage",
converted));
@@ -453,7 +454,8 @@ var gAdvancedPane = {
{
var list = document.getElementById("offlineAppsList");
var item = list.selectedItem;
- var host = item.getAttribute("host");
+ var origin = item.getAttribute("origin");
+ var principal = BrowserUtils.principalFromOrigin(origin);
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
@@ -462,35 +464,34 @@ var gAdvancedPane = {
var bundle = document.getElementById("bundlePreferences");
var title = bundle.getString("offlineAppRemoveTitle");
- var prompt = bundle.getFormattedString("offlineAppRemovePrompt", [host]);
+ var prompt = bundle.getFormattedString("offlineAppRemovePrompt", [principal.URI.prePath]);
var confirm = bundle.getString("offlineAppRemoveConfirm");
var result = prompts.confirmEx(window, title, prompt, flags, confirm,
null, null, null, {});
if (result != 0)
return;
- // clear offline cache entries
- var cacheService = Components.classes["@mozilla.org/network/application-cache-service;1"].
- getService(Components.interfaces.nsIApplicationCacheService);
- var ios = Components.classes["@mozilla.org/network/io-service;1"].
- getService(Components.interfaces.nsIIOService);
- var groups = cacheService.getGroups();
- for (var i = 0; i < groups.length; i++) {
- var uri = ios.newURI(groups[i], null, null);
- if (uri.asciiHost == host) {
+ // get the permission
+ var pm = Components.classes["@mozilla.org/permissionmanager;1"]
+ .getService(Components.interfaces.nsIPermissionManager);
+ var perm = pm.getPermissionObject(principal, "offline-app");
+ if (perm) {
+ // clear offline cache entries
+ try {
+ var cacheService = Components.classes["@mozilla.org/network/application-cache-service;1"].
+ getService(Components.interfaces.nsIApplicationCacheService);
+ var groups = cacheService.getGroups();
+ for (var i = 0; i < groups.length; i++) {
+ var uri = Services.io.newURI(groups[i], null, null);
+ if (perm.matchesURI(uri, true)) {
var cache = cacheService.getActiveCache(groups[i]);
cache.discard();
+ }
}
- }
-
- // remove the permission
- var pm = Components.classes["@mozilla.org/permissionmanager;1"]
- .getService(Components.interfaces.nsIPermissionManager);
- pm.remove(host, "offline-app",
- Components.interfaces.nsIPermissionManager.ALLOW_ACTION);
- pm.remove(host, "offline-app",
- Components.interfaces.nsIOfflineCacheUpdateService.ALLOW_NO_WARN);
+ } catch (e) {}
+ pm.removePermission(perm);
+ }
list.removeChild(item);
gAdvancedPane.offlineAppSelected();
this.updateActualAppCacheSize();
diff --git a/application/palemoon/components/preferences/content.js b/application/palemoon/components/preferences/content.js
index 0775c6270..5ae84c2f7 100644
--- a/application/palemoon/components/preferences/content.js
+++ b/application/palemoon/components/preferences/content.js
@@ -38,33 +38,11 @@ var gContentPane = {
*/
updateMSE: function ()
{
- var checkboxMSENFR = document.getElementById('videoMSENFR');
var checkboxMSEMP4 = document.getElementById('videoMSEMP4');
var checkboxMSEWebM = document.getElementById('videoMSEWebM');
var preference = document.getElementById('media.mediasource.enabled');
- checkboxMSENFR.disabled = preference.value != true;
checkboxMSEMP4.disabled = preference.value != true;
checkboxMSEWebM.disabled = preference.value != true;
- // Check and disable WebM if necessary
- if (preference.value == true) {
- this.updateMSEWebM();
- }
- },
-
- /**
- * Utility function to enable/disable the checkbox for MSE+WebM depending
- * on the value of media.mediasource.format-reader.
- */
- updateMSEWebM: function ()
- {
- var checkboxMSEWebM = document.getElementById('videoMSEWebM');
- var preference = document.getElementById('media.mediasource.format-reader');
- checkboxMSEWebM.disabled = preference.value == true;
- if (preference.value == true) {
- // Switch off incompatible format
- Services.prefs.setBoolPref('media.mediasource.webm.enabled', false);
- checkboxMSEWebM.checked = false;
- }
},
// BEGIN UI CODE
diff --git a/application/palemoon/components/preferences/content.xul b/application/palemoon/components/preferences/content.xul
index 22b6ce229..23d942e45 100644
--- a/application/palemoon/components/preferences/content.xul
+++ b/application/palemoon/components/preferences/content.xul
@@ -33,10 +33,7 @@
onchange="gContentPane._rebuildFonts();"/>
<!-- VIDEO -->
- <preference id="media.mediasource.enabled" name="media.mediasource.enabled" type="bool"
- onchange="gContentPane.updateMSE();" />
- <preference id="media.mediasource.format-reader" name="media.mediasource.format-reader" type="bool"
- onchange="gContentPane.updateMSEWebM();" />
+ <preference id="media.mediasource.enabled" name="media.mediasource.enabled" type="bool"/>
<preference id="media.mediasource.mp4.enabled" name="media.mediasource.mp4.enabled" type="bool"/>
<preference id="media.mediasource.webm.enabled" name="media.mediasource.webm.enabled" type="bool"/>
@@ -163,8 +160,6 @@
<checkbox id="videoMSE" preference="media.mediasource.enabled"
label="&videoMSE.label;" accesskey="&videoMSE.accesskey;"
onsyncfrompreference="gContentPane.updateMSE();"/>
- <checkbox class="indent" id="videoMSENFR" preference="media.mediasource.format-reader"
- label="&videoMSENFR.label;" accesskey="&videoMSENFR.accesskey;"/>
<checkbox class="indent" id="videoMSEMP4" preference="media.mediasource.mp4.enabled"
label="&videoMSEMP4.label;" accesskey="&videoMSEMP4.accesskey;"/>
<checkbox class="indent" id="videoMSEWebM" preference="media.mediasource.webm.enabled"
diff --git a/application/palemoon/components/preferences/cookies.js b/application/palemoon/components/preferences/cookies.js
index 543aeb186..4ef30d48e 100644
--- a/application/palemoon/components/preferences/cookies.js
+++ b/application/palemoon/components/preferences/cookies.js
@@ -732,8 +732,13 @@ var gCookiesWindow = {
},
onCookieKeyPress: function (aEvent) {
- if (aEvent.keyCode == 46)
+ if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE
+#ifdef XP_MACOSX
+ || aEvent.keyCode == KeyEvent.DOM_VK_BACK_SPACE
+#endif
+ ) {
this.deleteCookie();
+ }
},
_lastSortProperty : "",
diff --git a/application/palemoon/components/preferences/handlers.xml b/application/palemoon/components/preferences/handlers.xml
index d60792803..5fb915cee 100644
--- a/application/palemoon/components/preferences/handlers.xml
+++ b/application/palemoon/components/preferences/handlers.xml
@@ -72,7 +72,7 @@
extends="chrome://global/content/bindings/listbox.xml#listitem">
<content>
<children>
- <xul:listcell xbl:inherits="label=host"/>
+ <xul:listcell xbl:inherits="label=origin"/>
<xul:listcell xbl:inherits="label=usage"/>
</children>
</content>
diff --git a/application/palemoon/components/preferences/jar.mn b/application/palemoon/components/preferences/jar.mn
index a27784305..798a2dae4 100644
--- a/application/palemoon/components/preferences/jar.mn
+++ b/application/palemoon/components/preferences/jar.mn
@@ -15,7 +15,7 @@ browser.jar:
* content/browser/preferences/applicationManager.js
* content/browser/preferences/colors.xul
* content/browser/preferences/cookies.xul
- content/browser/preferences/cookies.js
+* content/browser/preferences/cookies.js
content/browser/preferences/content.xul
content/browser/preferences/content.js
* content/browser/preferences/connection.xul
@@ -28,8 +28,8 @@ browser.jar:
content/browser/preferences/languages.js
* content/browser/preferences/main.xul
content/browser/preferences/main.js
-* content/browser/preferences/permissions.xul
- content/browser/preferences/permissions.js
+ content/browser/preferences/permissions.xul
+* content/browser/preferences/permissions.js
* content/browser/preferences/preferences.xul
content/browser/preferences/privacy.xul
content/browser/preferences/privacy.js
diff --git a/application/palemoon/components/preferences/permissions.js b/application/palemoon/components/preferences/permissions.js
index 785e26d5e..4b1bf41b2 100644
--- a/application/palemoon/components/preferences/permissions.js
+++ b/application/palemoon/components/preferences/permissions.js
@@ -3,38 +3,40 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+Components.utils.import("resource://gre/modules/Services.jsm");
+
const nsIPermissionManager = Components.interfaces.nsIPermissionManager;
const nsICookiePermission = Components.interfaces.nsICookiePermission;
const NOTIFICATION_FLUSH_PERMISSIONS = "flush-pending-permissions";
-function Permission(host, rawHost, type, capability, perm)
+function Permission(principal, type, capability)
{
- this.host = host;
- this.rawHost = rawHost;
+ this.principal = principal;
+ this.origin = principal.origin;
this.type = type;
this.capability = capability;
- this.perm = perm;
}
var gPermissionManager = {
- _type : "",
- _permissions : [],
- _pm : Components.classes["@mozilla.org/permissionmanager;1"]
- .getService(Components.interfaces.nsIPermissionManager),
- _bundle : null,
- _tree : null,
-
+ _type : "",
+ _permissions : [],
+ _permissionsToAdd : new Map(),
+ _permissionsToDelete : new Map(),
+ _bundle : null,
+ _tree : null,
+ _observerRemoved : false,
+
_view: {
_rowCount: 0,
- get rowCount()
- {
- return this._rowCount;
+ get rowCount()
+ {
+ return this._rowCount;
},
getCellText: function (aRow, aColumn)
{
if (aColumn.id == "siteCol")
- return gPermissionManager._permissions[aRow].rawHost;
+ return gPermissionManager._permissions[aRow].origin;
else if (aColumn.id == "statusCol")
return gPermissionManager._permissions[aRow].capability;
return "";
@@ -57,7 +59,7 @@ var gPermissionManager = {
return "";
}
},
-
+
_getCapabilityString: function (aCapability)
{
var stringKey = null;
@@ -77,44 +79,66 @@ var gPermissionManager = {
}
return this._bundle.getString(stringKey);
},
-
+
addPermission: function (aCapability)
{
var textbox = document.getElementById("url");
- var host = textbox.value.replace(/^\s*([-\w]*:\/+)?/, ""); // trim any leading space and scheme
+ var input_url = textbox.value.replace(/^\s*/, ""); // trim any leading space
+ let principal;
try {
- var ioService = Components.classes["@mozilla.org/network/io-service;1"]
- .getService(Components.interfaces.nsIIOService);
- var uri = ioService.newURI("http://"+host, null, null);
- host = uri.host;
+ // The origin accessor on the principal object will throw if the
+ // principal doesn't have a canonical origin representation. This will
+ // help catch cases where the URI parser parsed something like
+ // `localhost:8080` as having the scheme `localhost`, rather than being
+ // an invalid URI. A canonical origin representation is required by the
+ // permission manager for storage, so this won't prevent any valid
+ // permissions from being entered by the user.
+ let uri;
+ try {
+ uri = Services.io.newURI(input_url, null, null);
+ principal = Services.scriptSecurityManager.getNoAppCodebasePrincipal(uri);
+ // If we have ended up with an unknown scheme, the following will throw.
+ principal.origin;
+ } catch(ex) {
+ uri = Services.io.newURI("http://" + input_url, null, null);
+ principal = Services.scriptSecurityManager.getNoAppCodebasePrincipal(uri);
+ // If we have ended up with an unknown scheme, the following will throw.
+ principal.origin;
+ }
} catch(ex) {
- var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
- .getService(Components.interfaces.nsIPromptService);
var message = this._bundle.getString("invalidURI");
var title = this._bundle.getString("invalidURITitle");
- promptService.alert(window, title, message);
+ Services.prompt.alert(window, title, message);
return;
}
var capabilityString = this._getCapabilityString(aCapability);
// check whether the permission already exists, if not, add it
- var exists = false;
+ let permissionExists = false;
+ let capabilityExists = false;
for (var i = 0; i < this._permissions.length; ++i) {
- if (this._permissions[i].rawHost == host) {
- // Avoid calling the permission manager if the capability settings are
- // the same. Otherwise allow the call to the permissions manager to
- // update the listbox for us.
- exists = this._permissions[i].perm == aCapability;
+ if (this._permissions[i].principal.equals(principal)) {
+ permissionExists = true;
+ capabilityExists = this._permissions[i].capability == capabilityString;
+ if (!capabilityExists) {
+ this._permissions[i].capability = capabilityString;
+ }
break;
}
}
- if (!exists) {
- host = (host.charAt(0) == ".") ? host.substring(1,host.length) : host;
- var uri = ioService.newURI("http://" + host, null, null);
- this._pm.add(uri, this._type, aCapability);
+
+ let permissionParams = {principal: principal, type: this._type, capability: aCapability};
+ if (!permissionExists) {
+ this._permissionsToAdd.set(principal.origin, permissionParams);
+ this._addPermission(permissionParams);
+ }
+ else if (!capabilityExists) {
+ this._permissionsToAdd.set(principal.origin, permissionParams);
+ this._handleCapabilityChange();
}
+
textbox.value = "";
textbox.focus();
@@ -124,14 +148,58 @@ var gPermissionManager = {
// enable "remove all" button as needed
document.getElementById("removeAllPermissions").disabled = this._permissions.length == 0;
},
-
+
+ _removePermission: function(aPermission)
+ {
+ this._removePermissionFromList(aPermission.principal);
+
+ // If this permission was added during this session, let's remove
+ // it from the pending adds list to prevent calls to the
+ // permission manager.
+ let isNewPermission = this._permissionsToAdd.delete(aPermission.principal.origin);
+
+ if (!isNewPermission) {
+ this._permissionsToDelete.set(aPermission.principal.origin, aPermission);
+ }
+
+ },
+
+ _handleCapabilityChange: function ()
+ {
+ // Re-do the sort, if the status changed from Block to Allow
+ // or vice versa, since if we're sorted on status, we may no
+ // longer be in order.
+ if (this._lastPermissionSortColumn == "statusCol") {
+ this._resortPermissions();
+ }
+ this._tree.treeBoxObject.invalidate();
+ },
+
+ _addPermission: function(aPermission)
+ {
+ this._addPermissionToList(aPermission);
+ ++this._view._rowCount;
+ this._tree.treeBoxObject.rowCountChanged(this._view.rowCount - 1, 1);
+ // Re-do the sort, since we inserted this new item at the end.
+ this._resortPermissions();
+ },
+
+ _resortPermissions: function()
+ {
+ gTreeUtils.sort(this._tree, this._view, this._permissions,
+ this._lastPermissionSortColumn,
+ this._permissionsComparator,
+ this._lastPermissionSortColumn,
+ !this._lastPermissionSortAscending); // keep sort direction
+ },
+
onHostInput: function (aSiteField)
{
document.getElementById("btnSession").disabled = !aSiteField.value;
document.getElementById("btnBlock").disabled = !aSiteField.value;
document.getElementById("btnAllow").disabled = !aSiteField.value;
},
-
+
onWindowKeyPress: function (aEvent)
{
if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE)
@@ -143,14 +211,14 @@ var gPermissionManager = {
if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN)
document.getElementById("btnAllow").click();
},
-
+
onLoad: function ()
{
this._bundle = document.getElementById("bundlePreferences");
var params = window.arguments[0];
this.init(params);
},
-
+
init: function (aParams)
{
if (this._type) {
@@ -160,14 +228,14 @@ var gPermissionManager = {
this._type = aParams.permissionType;
this._manageCapability = aParams.manageCapability;
-
+
var permissionsText = document.getElementById("permissionsText");
while (permissionsText.hasChildNodes())
permissionsText.removeChild(permissionsText.firstChild);
permissionsText.appendChild(document.createTextNode(aParams.introText));
document.title = aParams.windowTitle;
-
+
document.getElementById("btnBlock").hidden = !aParams.blockVisible;
document.getElementById("btnSession").hidden = !aParams.sessionVisible;
document.getElementById("btnAllow").hidden = !aParams.allowVisible;
@@ -183,64 +251,64 @@ var gPermissionManager = {
var urlLabel = document.getElementById("urlLabel");
urlLabel.hidden = !urlFieldVisible;
- var os = Components.classes["@mozilla.org/observer-service;1"]
- .getService(Components.interfaces.nsIObserverService);
- os.notifyObservers(null, NOTIFICATION_FLUSH_PERMISSIONS, this._type);
- os.addObserver(this, "perm-changed", false);
+ let treecols = document.getElementsByTagName("treecols")[0];
+ treecols.addEventListener("click", event => {
+ if (event.target.nodeName != "treecol" || event.button != 0) {
+ return;
+ }
+
+ let sortField = event.target.getAttribute("data-field-name");
+ if (!sortField) {
+ return;
+ }
+
+ gPermissionManager.onPermissionSort(sortField);
+ });
+
+ Services.obs.notifyObservers(null, NOTIFICATION_FLUSH_PERMISSIONS, this._type);
+ Services.obs.addObserver(this, "perm-changed", false);
this._loadPermissions();
-
+
urlField.focus();
},
-
+
uninit: function ()
{
- var os = Components.classes["@mozilla.org/observer-service;1"]
- .getService(Components.interfaces.nsIObserverService);
- os.removeObserver(this, "perm-changed");
+ if (!this._observerRemoved) {
+ Services.obs.removeObserver(this, "perm-changed");
+
+ this._observerRemoved = true;
+ }
},
-
+
observe: function (aSubject, aTopic, aData)
{
if (aTopic == "perm-changed") {
var permission = aSubject.QueryInterface(Components.interfaces.nsIPermission);
+
+ // Ignore unrelated permission types.
+ if (permission.type != this._type)
+ return;
+
if (aData == "added") {
- this._addPermissionToList(permission);
- ++this._view._rowCount;
- this._tree.treeBoxObject.rowCountChanged(this._view.rowCount - 1, 1);
- // Re-do the sort, since we inserted this new item at the end.
- gTreeUtils.sort(this._tree, this._view, this._permissions,
- this._lastPermissionSortColumn,
- this._permissionsComparator,
- this._lastPermissionSortColumn,
- !this._lastPermissionSortAscending); // keep sort direction
+ this._addPermission(permission);
}
else if (aData == "changed") {
for (var i = 0; i < this._permissions.length; ++i) {
- if (this._permissions[i].host == permission.host) {
+ if (permission.matches(this._permissions[i].principal, true)) {
this._permissions[i].capability = this._getCapabilityString(permission.capability);
break;
}
}
- // Re-do the sort, if the status changed from Block to Allow
- // or vice versa, since if we're sorted on status, we may no
- // longer be in order.
- if (this._lastPermissionSortColumn == "statusCol") {
- gTreeUtils.sort(this._tree, this._view, this._permissions,
- this._lastPermissionSortColumn,
- this._permissionsComparator,
- this._lastPermissionSortColumn,
- !this._lastPermissionSortAscending); // keep sort direction
- }
- this._tree.treeBoxObject.invalidate();
+ this._handleCapabilityChange();
+ }
+ else if (aData == "deleted") {
+ this._removePermissionFromList(permission.principal);
}
- // No UI other than this window causes this method to be sent a "deleted"
- // notification, so we don't need to implement it since Delete is handled
- // directly by the Permission Removal handlers. If that ever changes, those
- // implementations will have to move into here.
}
},
-
+
onPermissionSelected: function ()
{
var hasSelection = this._tree.view.selection.count > 0;
@@ -257,8 +325,8 @@ var gPermissionManager = {
gTreeUtils.deleteSelectedItems(this._tree, this._view, this._permissions, removedPermissions);
for (var i = 0; i < removedPermissions.length; ++i) {
var p = removedPermissions[i];
- this._pm.remove(p.host, p.type);
- }
+ this._removePermission(p);
+ }
document.getElementById("removePermission").disabled = !this._permissions.length;
document.getElementById("removeAllPermissions").disabled = !this._permissions.length;
},
@@ -271,18 +339,23 @@ var gPermissionManager = {
gTreeUtils.deleteAll(this._tree, this._view, this._permissions, removedPermissions);
for (var i = 0; i < removedPermissions.length; ++i) {
var p = removedPermissions[i];
- this._pm.remove(p.host, p.type);
- }
+ this._removePermission(p);
+ }
document.getElementById("removePermission").disabled = true;
document.getElementById("removeAllPermissions").disabled = true;
},
-
+
onPermissionKeyPress: function (aEvent)
{
- if (aEvent.keyCode == 46)
+ if (aEvent.keyCode == KeyEvent.DOM_VK_DELETE
+#ifdef XP_MACOSX
+ || aEvent.keyCode == KeyEvent.DOM_VK_BACK_SPACE
+#endif
+ ) {
this.onPermissionDeleted();
+ }
},
-
+
_lastPermissionSortColumn: "",
_lastPermissionSortAscending: false,
_permissionsComparator : function (a, b)
@@ -293,16 +366,34 @@ var gPermissionManager = {
onPermissionSort: function (aColumn)
{
- this._lastPermissionSortAscending = gTreeUtils.sort(this._tree,
- this._view,
+ this._lastPermissionSortAscending = gTreeUtils.sort(this._tree,
+ this._view,
this._permissions,
aColumn,
this._permissionsComparator,
- this._lastPermissionSortColumn,
+ this._lastPermissionSortColumn,
this._lastPermissionSortAscending);
this._lastPermissionSortColumn = aColumn;
},
-
+
+ onApplyChanges: function()
+ {
+ // Stop observing permission changes since we are about
+ // to write out the pending adds/deletes and don't need
+ // to update the UI
+ this.uninit();
+
+ for (let permissionParams of this._permissionsToAdd.values()) {
+ Services.perms.addFromPrincipal(permissionParams.principal, permissionParams.type, permissionParams.capability);
+ }
+
+ for (let p of this._permissionsToDelete.values()) {
+ Services.perms.removeFromPrincipal(p.principal, p.type);
+ }
+
+ window.close();
+ },
+
_loadPermissions: function ()
{
this._tree = document.getElementById("permissionsTree");
@@ -310,48 +401,59 @@ var gPermissionManager = {
// load permissions into a table
var count = 0;
- var enumerator = this._pm.enumerator;
+ var enumerator = Services.perms.enumerator;
while (enumerator.hasMoreElements()) {
var nextPermission = enumerator.getNext().QueryInterface(Components.interfaces.nsIPermission);
this._addPermissionToList(nextPermission);
}
-
+
this._view._rowCount = this._permissions.length;
// sort and display the table
this._tree.view = this._view;
- this.onPermissionSort("rawHost");
+ this.onPermissionSort("origin");
// disable "remove all" button if there are none
document.getElementById("removeAllPermissions").disabled = this._permissions.length == 0;
},
-
+
_addPermissionToList: function (aPermission)
{
if (aPermission.type == this._type &&
(!this._manageCapability ||
(aPermission.capability == this._manageCapability))) {
- var host = aPermission.host;
+ var principal = aPermission.principal;
var capabilityString = this._getCapabilityString(aPermission.capability);
- var p = new Permission(host,
- (host.charAt(0) == ".") ? host.substring(1,host.length) : host,
+ var p = new Permission(principal,
aPermission.type,
- capabilityString,
- aPermission.capability);
+ capabilityString);
this._permissions.push(p);
- }
+ }
},
-
- setHost: function (aHost)
+
+ _removePermissionFromList: function (aPrincipal)
+ {
+ for (let i = 0; i < this._permissions.length; ++i) {
+ if (this._permissions[i].principal.equals(aPrincipal)) {
+ this._permissions.splice(i, 1);
+ this._view._rowCount--;
+ this._tree.treeBoxObject.rowCountChanged(this._view.rowCount - 1, -1);
+ this._tree.treeBoxObject.invalidate();
+ break;
+ }
+ }
+ },
+
+ setOrigin: function (aOrigin)
{
- document.getElementById("url").value = aHost;
+ document.getElementById("url").value = aOrigin;
}
};
-function setHost(aHost)
+function setOrigin(aOrigin)
{
- gPermissionManager.setHost(aHost);
+ gPermissionManager.setOrigin(aOrigin);
}
function initWithParams(aParams)
diff --git a/application/palemoon/components/preferences/permissions.xul b/application/palemoon/components/preferences/permissions.xul
index fd550e8f7..33806cc27 100644
--- a/application/palemoon/components/preferences/permissions.xul
+++ b/application/palemoon/components/preferences/permissions.xul
@@ -1,12 +1,12 @@
<?xml version="1.0"?>
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- -->
+<!-- This Source Code Form is subject to the terms of the Mozilla Public
+ - License, v. 2.0. If a copy of the MPL was not distributed with this
+ - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/skin/preferences/preferences.css" type="text/css"?>
+<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
+<?xml-stylesheet href="chrome://browser/skin/preferences/preferences.css" type="text/css"?>
<!DOCTYPE dialog SYSTEM "chrome://browser/locale/preferences/permissions.dtd" >
@@ -35,7 +35,7 @@
<separator class="thin"/>
<label id="urlLabel" control="url" value="&address.label;" accesskey="&address.accesskey;"/>
<hbox align="start">
- <textbox id="url" flex="1"
+ <textbox id="url" flex="1"
oninput="gPermissionManager.onHostInput(event.target);"
onkeypress="gPermissionManager.onHostKeyPress(event);"/>
</hbox>
@@ -54,30 +54,32 @@
onselect="gPermissionManager.onPermissionSelected();">
<treecols>
<treecol id="siteCol" label="&treehead.sitename.label;" flex="3"
- onclick="gPermissionManager.onPermissionSort('rawHost');" persist="width"/>
+ data-field-name="origin" persist="width"/>
<splitter class="tree-splitter"/>
<treecol id="statusCol" label="&treehead.status.label;" flex="1"
- onclick="gPermissionManager.onPermissionSort('capability');" persist="width"/>
+ data-field-name="capability" persist="width"/>
</treecols>
<treechildren/>
</tree>
</vbox>
- <hbox align="end">
- <hbox class="actionButtons" flex="1">
+ <vbox>
+ <hbox class="actionButtons" align="left" flex="1">
<button id="removePermission" disabled="true"
accesskey="&removepermission.accesskey;"
icon="remove" label="&removepermission.label;"
oncommand="gPermissionManager.onPermissionDeleted();"/>
<button id="removeAllPermissions"
icon="clear" label="&removeallpermissions.label;"
- accesskey="&removeallpermissions.accesskey;"
+ accesskey="&removeallpermissions.accesskey;"
oncommand="gPermissionManager.onAllPermissionsDeleted();"/>
- <spacer flex="1"/>
-#ifndef XP_MACOSX
+ </hbox>
+ <spacer flex="1"/>
+ <hbox class="actionButtons" align="right" flex="1">
<button oncommand="close();" icon="close"
- label="&button.close.label;" accesskey="&button.close.accesskey;"/>
-#endif
+ label="&button.cancel.label;" accesskey="&button.cancel.accesskey;" />
+ <button id="btnApplyChanges" oncommand="gPermissionManager.onApplyChanges();" icon="save"
+ label="&button.ok.label;" accesskey="&button.ok.accesskey;"/>
</hbox>
<resizer type="window" dir="bottomend"/>
- </hbox>
+ </vbox>
</window>
diff --git a/application/palemoon/components/preferences/security.js b/application/palemoon/components/preferences/security.js
index 56664bf66..9d5f302a2 100644
--- a/application/palemoon/components/preferences/security.js
+++ b/application/palemoon/components/preferences/security.js
@@ -131,9 +131,21 @@ var gSecurityPane = {
*/
showPasswordExceptions: function ()
{
+ let bundlePrefs = document.getElementById("bundlePreferences");
+ let params = {
+ blockVisible: true,
+ sessionVisible: false,
+ allowVisible: false,
+ hideStatusColumn: true,
+ prefilledHost: "",
+ permissionType: "login-saving",
+ windowTitle: bundlePrefs.getString("savedLoginsExceptions_title"),
+ introText: bundlePrefs.getString("savedLoginsExceptions_desc")
+ };
+
document.documentElement.openWindow("Toolkit:PasswordManagerExceptions",
- "chrome://passwordmgr/content/passwordManagerExceptions.xul",
- "", null);
+ "chrome://browser/content/preferences/permissions.xul",
+ null, params);
},
/**
diff --git a/application/palemoon/components/sessionstore/SessionStore.jsm b/application/palemoon/components/sessionstore/SessionStore.jsm
index f7c495be8..4f95f10a7 100644
--- a/application/palemoon/components/sessionstore/SessionStore.jsm
+++ b/application/palemoon/components/sessionstore/SessionStore.jsm
@@ -1951,7 +1951,13 @@ var SessionStoreInternal = {
// userTypedValue.
if (browser.userTypedValue) {
tabData.userTypedValue = browser.userTypedValue;
- tabData.userTypedClear = browser.userTypedClear;
+ // We always used to keep track of the loading state as an integer, where
+ // '0' indicated the user had typed since the last load (or no load was
+ // ongoing), and any positive value indicated we had started a load since
+ // the last time the user typed in the URL bar. Mimic this to keep the
+ // session store representation in sync, even though we now represent this
+ // more explicitly:
+ tabData.userTypedClear = browser.didStartLoadSinceLastUserTyping() ? 1 : 0;
} else {
delete tabData.userTypedValue;
delete tabData.userTypedClear;
@@ -2079,7 +2085,7 @@ var SessionStoreInternal = {
}
catch (ex) { debug(ex); } // POSTDATA is tricky - especially since some extensions don't get it right
- if (aEntry.owner) {
+ if (aEntry.triggeringPrincipal) {
// Not catching anything specific here, just possible errors
// from writeCompoundObject and the like.
try {
@@ -2088,19 +2094,19 @@ var SessionStoreInternal = {
var pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
pipe.init(false, false, 0, 0xffffffff, null);
binaryStream.setOutputStream(pipe.outputStream);
- binaryStream.writeCompoundObject(aEntry.owner, Ci.nsISupports, true);
+ binaryStream.writeCompoundObject(aEntry.triggeringPrincipal, Ci.nsIPrincipal, true);
binaryStream.close();
// Now we want to read the data from the pipe's input end and encode it.
var scriptableStream = Cc["@mozilla.org/binaryinputstream;1"].
createInstance(Ci.nsIBinaryInputStream);
scriptableStream.setInputStream(pipe.inputStream);
- var ownerBytes =
+ var triggeringPrincipalBytes =
scriptableStream.readByteArray(scriptableStream.available());
// We can stop doing base64 encoding once our serialization into JSON
// is guaranteed to handle all chars in strings, including embedded
// nulls.
- entry.owner_b64 = btoa(String.fromCharCode.apply(null, ownerBytes));
+ entry.triggeringPrincipal_b64 = btoa(String.fromCharCode.apply(null, triggeringPrincipalBytes));
}
catch (ex) { debug(ex); }
}
@@ -3394,16 +3400,24 @@ var SessionStoreInternal = {
}
}
- if (aEntry.owner_b64) {
- var ownerInput = Cc["@mozilla.org/io/string-input-stream;1"].
- createInstance(Ci.nsIStringInputStream);
- var binaryData = atob(aEntry.owner_b64);
- ownerInput.setData(binaryData, binaryData.length);
+ // The field aEntry.owner_b64 got renamed to aEntry.triggeringPricipal_b64 in
+ // Bug 1286472. To remain backward compatible we still have to support that
+ // field for a few cycles before we can remove it within Bug 1289785.
+ if (aEntry.owner_b64) {
+ aEntry.triggeringPrincipal_b64 = aEntry.owner_b64;
+ delete aEntry.owner_b64;
+ }
+
+ if (aEntry.triggeringPrincipal_b64) {
+ var triggeringPrincipalInput = Cc["@mozilla.org/io/string-input-stream;1"].
+ createInstance(Ci.nsIStringInputStream);
+ var binaryData = atob(aEntry.triggeringPrincipal_b64);
+ triggeringPrincipalInput.setData(binaryData, binaryData.length);
var binaryStream = Cc["@mozilla.org/binaryinputstream;1"].
createInstance(Ci.nsIObjectInputStream);
- binaryStream.setInputStream(ownerInput);
+ binaryStream.setInputStream(triggeringPrincipalInput);
try { // Catch possible deserialization exceptions
- shEntry.owner = binaryStream.readObject(true);
+ shEntry.triggeringPrincipal = binaryStream.readObject(true);
} catch (ex) { debug(ex); }
}
diff --git a/application/palemoon/confvars.sh b/application/palemoon/confvars.sh
index 8a1d00c68..5109c0829 100644
--- a/application/palemoon/confvars.sh
+++ b/application/palemoon/confvars.sh
@@ -79,12 +79,6 @@ MOZ_JSDOWNLOADS=1
# conformant implementations.
MOZ_WEBGL_CONFORMANT=1
-# Platform Feature: Windows Maintaince Service
-# XXX: This is never used
-if test "$OS_ARCH" = "WINNT"; then
- MOZ_MAINTENANCE_SERVICE=
-fi
-
# Set the chrome packing format
# Possible values are omni, jar, and flat
# Currently, only omni and flat are supported
@@ -103,3 +97,11 @@ if test "$OS_ARCH" = "WINNT" -o \
"$OS_ARCH" = "Linux"; then
MOZ_BUNDLED_FONTS=1
fi
+
+# Short-circuit a few services to be removed
+MOZ_MAINTENANCE_SERVICE=
+MOZ_SERVICES_HEALTHREPORT=
+MOZ_ADDON_SIGNING=0
+MOZ_REQUIRE_SIGNING=0
+MOZ_PROFILE_MIGRATOR=
+
diff --git a/application/palemoon/installer/package-manifest.in b/application/palemoon/installer/package-manifest.in
index f7b12838b..e6a4d49db 100644
--- a/application/palemoon/installer/package-manifest.in
+++ b/application/palemoon/installer/package-manifest.in
@@ -35,11 +35,9 @@
#ifdef XP_MACOSX
; Mac bundle stuff
@APPNAME@/Contents/Info.plist
-@APPNAME@/Contents/Library/LaunchServices
@APPNAME@/Contents/PkgInfo
@RESPATH@/firefox.icns
@RESPATH@/document.icns
-@RESPATH@/@LPROJ_ROOT@.lproj/*
#endif
[@AB_CD@]
@@ -176,8 +174,6 @@
#endif
#ifdef MOZ_ENABLE_PROFILER_SPS
#endif
-#ifdef ENABLE_INTL_API
-#endif
#ifdef NECKO_WIFI
#endif
#ifdef MOZ_WEBRTC
@@ -334,21 +330,6 @@
@RESPATH@/chrome/pippki@JAREXT@
@RESPATH@/chrome/pippki.manifest
-; For process sandboxing
-#if defined(MOZ_SANDBOX)
-#if defined(XP_WIN)
-#if defined(WOW_HELPER)
-@BINPATH@/wow_helper.exe
-#endif
-#endif
-#endif
-
-#if defined(MOZ_SANDBOX)
-#if defined(XP_LINUX)
-@BINPATH@/@DLL_PREFIX@mozsandbox@DLL_SUFFIX@
-#endif
-#endif
-
; for Solaris SPARC
#ifdef SOLARIS
bin/libfreebl_32fpu_3.so
diff --git a/application/palemoon/locales/en-US/chrome/browser/browser.dtd b/application/palemoon/locales/en-US/chrome/browser/browser.dtd
index 65cc34fa0..3d5f22b33 100644
--- a/application/palemoon/locales/en-US/chrome/browser/browser.dtd
+++ b/application/palemoon/locales/en-US/chrome/browser/browser.dtd
@@ -107,9 +107,6 @@ These should match what Safari and other Apple applications use on OS X Lion. --
<!ENTITY fullScreenAutohide.accesskey "H">
<!ENTITY fullScreenExit.label "Exit Full Screen Mode">
<!ENTITY fullScreenExit.accesskey "F">
-<!ENTITY fullscreenAllowButton.label "Allow">
-<!ENTITY fullscreenExitButton.label "Deny">
-<!ENTITY fullscreenApproval.value "Allow fullscreen?">
<!ENTITY fullscreenExitHint.value "Press ESC at any time to exit fullscreen.">
<!ENTITY leaveDOMFullScreen.label "Exit Full Screen">
diff --git a/application/palemoon/locales/en-US/chrome/browser/browser.properties b/application/palemoon/locales/en-US/chrome/browser/browser.properties
index bf363d103..5dce994fe 100644
--- a/application/palemoon/locales/en-US/chrome/browser/browser.properties
+++ b/application/palemoon/locales/en-US/chrome/browser/browser.properties
@@ -7,6 +7,7 @@ openFile=Open File
droponhometitle=Set Home Page
droponhomemsg=Do you want this document to be your new home page?
+droponhomemsgMultiple=Do you want these documents to be your new home pages?
# context menu strings
@@ -58,7 +59,8 @@ addonError-1=The add-on could not be downloaded because of a connection failure
addonError-2=The add-on from #2 could not be installed because it does not match the add-on #3 expected.
addonError-3=The add-on downloaded from #2 could not be installed because it appears to be corrupt.
addonError-4=#1 could not be installed because #3 cannot modify the needed file.
-addonError-5=The add-on downloaded from #2 could not be installed because #3 does not support WebExtensions.
+addonError-8=The add-on downloaded from #2 could not be installed because #3 does not support Jetpack (SDK) extensions.
+addonError-9=The add-on downloaded from #2 could not be installed because #3 does not support WebExtensions.
# LOCALIZATION NOTE (addonLocalError-1, addonLocalError-2, addonLocalError-3, addonLocalError-4, addonErrorIncompatible, addonErrorBlocklisted):
# #1 is the add-on name, #3 is the application name, #4 is the application version
@@ -66,10 +68,11 @@ addonLocalError-1=This add-on could not be installed because of a filesystem err
addonLocalError-2=This add-on could not be installed because it does not match the add-on #3 expected.
addonLocalError-3=This add-on could not be installed because it appears to be corrupt.
addonLocalError-4=#1 could not be installed because #3 cannot modify the needed file.
-addonLocalError-5=This add-on could not be installed because #3 does not support WebExtensions.
+addonLocalError-8=This add-on could not be installed because #3 does not support Jetpack (SDK) extensions.
+addonLocalError-9=This add-on could not be installed because #3 does not support WebExtensions.
addonErrorIncompatible=#1 could not be installed because it is not compatible with #3 #4.
addonErrorBlocklisted=#1 could not be installed because it has a high risk of causing stability or security problems.
-addonErrorJetSDK=#1 could not be installed because it is a Jetpack/SDK extension which are not supported in #3 #4.
+
# LOCALIZATION NOTE (lwthemeInstallRequest.message): %S will be replaced with
# the host name of the site.
@@ -304,6 +307,10 @@ webNotifications.alwaysShow.accesskey=A
webNotifications.neverShow=Always Block Notifications
webNotifications.neverShow.accesskey=N
webNotifications.showFromSite=Would you like to show notifications from %S?
+# LOCALIZATION NOTE (webNotifications.upgradeTitle): When using native notifications on OS X, the title may be truncated around 32 characters.
+webNotifications.upgradeTitle=Upgraded notifications
+# LOCALIZATION NOTE (webNotifications.upgradeBody): When using native notifications on OS X, the body may be truncated around 100 characters in some views.
+webNotifications.upgradeBody=You can now receive notifications from sites that are not currently loaded. Click to learn more.
# Pointer lock UI
@@ -370,8 +377,6 @@ dataReportingNotification.button.accessKey = C
# LOCALIZATION NOTE (fullscreen.entered): displayed when we enter HTML5 fullscreen mode, %S is the domain name of the focused website (e.g. mozilla.com).
fullscreen.entered=%S is now fullscreen.
-# LOCALIZATION NOTE (fullscreen.rememberDecision): displayed when we enter HTML5 fullscreen mode, %S is the domain name of the focused website (e.g. mozilla.com).
-fullscreen.rememberDecision=Remember decision for %S
# LOCALIZATION NOTE (getUserMedia.shareCamera.message, getUserMedia.shareMicrophone.message, getUserMedia.shareCameraAndMicrophone.message): %S is the website origin (e.g. www.mozilla.org)
# LOCALIZATION NOTE (getUserMedia.shareSelectedDevices.label):
diff --git a/application/palemoon/locales/en-US/chrome/browser/pageInfo.dtd b/application/palemoon/locales/en-US/chrome/browser/pageInfo.dtd
index 7f3797276..70c2bbc13 100644
--- a/application/palemoon/locales/en-US/chrome/browser/pageInfo.dtd
+++ b/application/palemoon/locales/en-US/chrome/browser/pageInfo.dtd
@@ -66,8 +66,6 @@
<!ENTITY permInstall "Install Extensions or Themes">
<!ENTITY permGeo "Share Location">
<!ENTITY permPlugins "Activate Plugins">
-<!ENTITY permFullscreen "Enter Fullscreen">
-<!ENTITY permPointerLock2 "Hide the Mouse Pointer">
<!ENTITY permIndexedDB "Maintain Offline Storage">
<!ENTITY permClearStorage "Clear Storage">
diff --git a/application/palemoon/locales/en-US/chrome/browser/preferences/aboutPermissions.dtd b/application/palemoon/locales/en-US/chrome/browser/preferences/aboutPermissions.dtd
index ff1da3dd0..14412607a 100644
--- a/application/palemoon/locales/en-US/chrome/browser/preferences/aboutPermissions.dtd
+++ b/application/palemoon/locales/en-US/chrome/browser/preferences/aboutPermissions.dtd
@@ -51,6 +51,4 @@
<!ENTITY popup.label "Open Pop-up Windows">
-<!ENTITY fullscreen.label "Fullscreen">
-
-<!ENTITY pointerLock.label "Hide the Mouse Pointer">
+<!ENTITY focusSearch.key "f">
diff --git a/application/palemoon/locales/en-US/chrome/browser/preferences/content.dtd b/application/palemoon/locales/en-US/chrome/browser/preferences/content.dtd
index 928e599d8..91abab069 100644
--- a/application/palemoon/locales/en-US/chrome/browser/preferences/content.dtd
+++ b/application/palemoon/locales/en-US/chrome/browser/preferences/content.dtd
@@ -33,8 +33,6 @@
<!ENTITY video.label "Video">
<!ENTITY videoMSE.label "Enable Media Source Extensions (MSE)">
<!ENTITY videoMSE.accesskey "M">
-<!ENTITY videoMSENFR.label "Use MSE asynchronously">
-<!ENTITY videoMSENFR.accesskey "U">
<!ENTITY videoMSEMP4.label "Enable MSE for MP4 video">
<!ENTITY videoMSEMP4.accesskey "4">
<!ENTITY videoMSEWebM.label "Enable MSE for WebM video">
diff --git a/application/palemoon/locales/en-US/chrome/browser/preferences/permissions.dtd b/application/palemoon/locales/en-US/chrome/browser/preferences/permissions.dtd
index f6a9c466c..e61228b76 100644
--- a/application/palemoon/locales/en-US/chrome/browser/preferences/permissions.dtd
+++ b/application/palemoon/locales/en-US/chrome/browser/preferences/permissions.dtd
@@ -3,7 +3,7 @@
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!ENTITY window.title "Exceptions">
-<!ENTITY window.width "36em">
+<!ENTITY window.width "45em">
<!ENTITY treehead.sitename.label "Site">
<!ENTITY treehead.status.label "Status">
@@ -21,6 +21,8 @@
<!ENTITY allow.accesskey "A">
<!ENTITY windowClose.key "w">
-<!ENTITY button.close.label "Close">
-<!ENTITY button.close.accesskey "C">
+<!ENTITY button.cancel.label "Cancel">
+<!ENTITY button.cancel.accesskey "C">
+<!ENTITY button.ok.label "Save Changes">
+<!ENTITY button.ok.accesskey "S">
diff --git a/application/palemoon/locales/en-US/chrome/browser/preferences/preferences.properties b/application/palemoon/locales/en-US/chrome/browser/preferences/preferences.properties
index 356922982..3eebbcbec 100644
--- a/application/palemoon/locales/en-US/chrome/browser/preferences/preferences.properties
+++ b/application/palemoon/locales/en-US/chrome/browser/preferences/preferences.properties
@@ -23,6 +23,8 @@ popuppermissionstext=You can specify which websites are allowed to open pop-up w
popuppermissionstitle=Allowed Sites - Pop-ups
invalidURI=Please enter a valid hostname
invalidURITitle=Invalid Hostname Entered
+savedLoginsExceptions_title=Exceptions - Saved Logins
+savedLoginsExceptions_desc=Logins for the following sites will not be saved:
#### Master Password
diff --git a/application/palemoon/modules/PopupNotifications.jsm b/application/palemoon/modules/PopupNotifications.jsm
index 15c8915ed..0cb970230 100644
--- a/application/palemoon/modules/PopupNotifications.jsm
+++ b/application/palemoon/modules/PopupNotifications.jsm
@@ -12,6 +12,7 @@ const NOTIFICATION_EVENT_DISMISSED = "dismissed";
const NOTIFICATION_EVENT_REMOVED = "removed";
const NOTIFICATION_EVENT_SHOWING = "showing";
const NOTIFICATION_EVENT_SHOWN = "shown";
+const NOTIFICATION_EVENT_SWAPPING = "swapping";
const ICON_SELECTOR = ".notification-anchor-icon";
const ICON_ATTRIBUTE_SHOWING = "showing";
@@ -237,9 +238,23 @@ PopupNotifications.prototype = {
* tabs)
* "removed": notification has been removed (due to
* location change or user action)
+ * "showing": notification is about to be shown
+ * (this can be fired multiple times as
+ * notifications are dismissed and re-shown)
* "shown": notification has been shown (this can be fired
* multiple times as notifications are dismissed
* and re-shown)
+ * "swapping": the docshell of the browser that created
+ * the notification is about to be swapped to
+ * another browser. A second parameter contains
+ * the browser that is receiving the docshell,
+ * so that the event callback can transfer stuff
+ * specific to this notification.
+ * If the callback returns true, the notification
+ * will be moved to the new browser.
+ * If the callback isn't implemented, returns false,
+ * or doesn't return any value, the notification
+ * will be removed.
* neverShow: Indicate that no popup should be shown for this
* notification. Useful for just showing the anchor icon.
* removeOnDismissal:
@@ -829,13 +844,60 @@ PopupNotifications.prototype = {
this._update(notifications, anchor);
},
- _fireCallback: function PopupNotifications_fireCallback(n, event) {
+ _swapBrowserNotifications: function PopupNotifications_swapBrowserNoficications(ourBrowser, otherBrowser) {
+ // When swaping browser docshells (e.g. dragging tab to new window) we need
+ // to update our notification map.
+
+ let ourNotifications = this._getNotificationsForBrowser(ourBrowser);
+ let other = otherBrowser.ownerDocument.defaultView.PopupNotifications;
+ if (!other) {
+ if (ourNotifications.length > 0)
+ Cu.reportError("unable to swap notifications: otherBrowser doesn't support notifications");
+ return;
+ }
+ let otherNotifications = other._getNotificationsForBrowser(otherBrowser);
+ if (ourNotifications.length < 1 && otherNotifications.length < 1) {
+ // No notification to swap.
+ return;
+ }
+
+ otherNotifications = otherNotifications.filter(n => {
+ if (this._fireCallback(n, NOTIFICATION_EVENT_SWAPPING, ourBrowser)) {
+ n.browser = ourBrowser;
+ n.owner = this;
+ return true;
+ }
+ other._fireCallback(n, NOTIFICATION_EVENT_REMOVED);
+ return false;
+ });
+
+ ourNotifications = ourNotifications.filter(n => {
+ if (this._fireCallback(n, NOTIFICATION_EVENT_SWAPPING, otherBrowser)) {
+ n.browser = otherBrowser;
+ n.owner = other;
+ return true;
+ }
+ this._fireCallback(n, NOTIFICATION_EVENT_REMOVED);
+ return false;
+ });
+
+ this._setNotificationsForBrowser(otherBrowser, ourNotifications);
+ other._setNotificationsForBrowser(ourBrowser, otherNotifications);
+
+ if (otherNotifications.length > 0)
+ this._update(otherNotifications, otherNotifications[0].anchorElement);
+ if (ourNotifications.length > 0)
+ other._update(ourNotifications, ourNotifications[0].anchorElement);
+ },
+
+ _fireCallback: function PopupNotifications_fireCallback(n, event, ...args) {
try {
if (n.options.eventCallback)
- n.options.eventCallback.call(n, event);
+ return n.options.eventCallback.call(n, event, ...args);
} catch (error) {
Cu.reportError(error);
}
+ return undefined;
},
_onPopupHidden: function PopupNotifications_onPopupHidden(event) {
diff --git a/application/palemoon/modules/webrtcUI.jsm b/application/palemoon/modules/webrtcUI.jsm
index c957bfd9a..819ca181f 100644
--- a/application/palemoon/modules/webrtcUI.jsm
+++ b/application/palemoon/modules/webrtcUI.jsm
@@ -11,9 +11,11 @@ const Cc = Components.classes;
const Ci = Components.interfaces;
Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/PluralForm.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PluralForm",
+ "resource://gre/modules/PluralForm.jsm");
+
XPCOMUtils.defineLazyServiceGetter(this, "MediaManagerService",
"@mozilla.org/mediaManagerService;1",
"nsIMediaManagerService");
@@ -128,62 +130,14 @@ function prompt(aWindowID, aCallID, aAudioRequested, aVideoRequested, aDevices)
let message = stringBundle.getFormattedString("getUserMedia.share" + requestType + ".message",
[ host ]);
- function listDevices(menupopup, devices) {
- while (menupopup.lastChild)
- menupopup.removeChild(menupopup.lastChild);
-
- let deviceIndex = 0;
- for (let device of devices) {
- addDeviceToList(menupopup, device.name, deviceIndex);
- deviceIndex++;
- }
- }
-
- function addDeviceToList(menupopup, deviceName, deviceIndex) {
- let menuitem = chromeDoc.createElement("menuitem");
- menuitem.setAttribute("value", deviceIndex);
- menuitem.setAttribute("label", deviceName);
- menuitem.setAttribute("tooltiptext", deviceName);
- menupopup.appendChild(menuitem);
- }
-
- chromeDoc.getElementById("webRTC-selectCamera").hidden = !videoDevices.length;
- chromeDoc.getElementById("webRTC-selectMicrophone").hidden = !audioDevices.length;
-
- let camMenupopup = chromeDoc.getElementById("webRTC-selectCamera-menupopup");
- let micMenupopup = chromeDoc.getElementById("webRTC-selectMicrophone-menupopup");
- listDevices(camMenupopup, videoDevices);
- listDevices(micMenupopup, audioDevices);
- if (requestType == "CameraAndMicrophone") {
- addDeviceToList(camMenupopup, stringBundle.getString("getUserMedia.noVideo.label"), "-1");
- addDeviceToList(micMenupopup, stringBundle.getString("getUserMedia.noAudio.label"), "-1");
- }
-
let mainAction = {
label: PluralForm.get(requestType == "CameraAndMicrophone" ? 2 : 1,
stringBundle.getString("getUserMedia.shareSelectedDevices.label")),
accessKey: stringBundle.getString("getUserMedia.shareSelectedDevices.accesskey"),
- callback: function () {
- let allowedDevices = Cc["@mozilla.org/supports-array;1"]
- .createInstance(Ci.nsISupportsArray);
- if (videoDevices.length) {
- let videoDeviceIndex = chromeDoc.getElementById("webRTC-selectCamera-menulist").value;
- if (videoDeviceIndex != "-1")
- allowedDevices.AppendElement(videoDevices[videoDeviceIndex]);
- }
- if (audioDevices.length) {
- let audioDeviceIndex = chromeDoc.getElementById("webRTC-selectMicrophone-menulist").value;
- if (audioDeviceIndex != "-1")
- allowedDevices.AppendElement(audioDevices[audioDeviceIndex]);
- }
-
- if (allowedDevices.Count() == 0) {
- denyRequest(aCallID);
- return;
- }
-
- Services.obs.notifyObservers(allowedDevices, "getUserMedia:response:allow", aCallID);
- }
+ // The real callback will be set during the "showing" event. The
+ // empty function here is so that PopupNotifications.show doesn't
+ // reject the action.
+ callback: function() {}
};
let secondaryActions = [{
@@ -194,7 +148,72 @@ function prompt(aWindowID, aCallID, aAudioRequested, aVideoRequested, aDevices)
}
}];
- let options = null;
+ let options = {
+ eventCallback: function(aTopic, aNewBrowser) {
+ if (aTopic == "swapping")
+ return true;
+
+ if (aTopic != "showing")
+ return false;
+
+ let chromeDoc = this.browser.ownerDocument;
+
+ function listDevices(menupopup, devices) {
+ while (menupopup.lastChild)
+ menupopup.removeChild(menupopup.lastChild);
+
+ let deviceIndex = 0;
+ for (let device of devices) {
+ addDeviceToList(menupopup, device.name, deviceIndex);
+ deviceIndex++;
+ }
+ }
+
+ function addDeviceToList(menupopup, deviceName, deviceIndex) {
+ let menuitem = chromeDoc.createElement("menuitem");
+ menuitem.setAttribute("value", deviceIndex);
+ menuitem.setAttribute("label", deviceName);
+ menuitem.setAttribute("tooltiptext", deviceName);
+ menupopup.appendChild(menuitem);
+ }
+
+ chromeDoc.getElementById("webRTC-selectCamera").hidden = !videoDevices.length;
+ chromeDoc.getElementById("webRTC-selectMicrophone").hidden = !audioDevices.length;
+
+ let camMenupopup = chromeDoc.getElementById("webRTC-selectCamera-menupopup");
+ let micMenupopup = chromeDoc.getElementById("webRTC-selectMicrophone-menupopup");
+ listDevices(camMenupopup, videoDevices);
+ listDevices(micMenupopup, audioDevices);
+ if (requestType == "CameraAndMicrophone") {
+ let stringBundle = chromeDoc.defaultView.gNavigatorBundle;
+ addDeviceToList(camMenupopup, stringBundle.getString("getUserMedia.noVideo.label"), "-1");
+ addDeviceToList(micMenupopup, stringBundle.getString("getUserMedia.noAudio.label"), "-1");
+ }
+
+ this.mainAction.callback = function() {
+ let allowedDevices = Cc["@mozilla.org/supports-array;1"]
+ .createInstance(Ci.nsISupportsArray);
+ if (videoDevices.length) {
+ let videoDeviceIndex = chromeDoc.getElementById("webRTC-selectCamera-menulist").value;
+ if (videoDeviceIndex != "-1")
+ allowedDevices.AppendElement(videoDevices[videoDeviceIndex]);
+ }
+ if (audioDevices.length) {
+ let audioDeviceIndex = chromeDoc.getElementById("webRTC-selectMicrophone-menulist").value;
+ if (audioDeviceIndex != "-1")
+ allowedDevices.AppendElement(audioDevices[audioDeviceIndex]);
+ }
+
+ if (allowedDevices.Count() == 0) {
+ denyRequest(aCallID);
+ return;
+ }
+
+ Services.obs.notifyObservers(allowedDevices, "getUserMedia:response:allow", aCallID);
+ };
+ return true;
+ }
+ };
chromeWin.PopupNotifications.show(browser, "webRTC-shareDevices", message,
"webRTC-shareDevices-notification-icon", mainAction,
@@ -254,7 +273,8 @@ function showBrowserSpecificIndicator(aBrowser) {
}];
let options = {
hideNotNow: true,
- dismissed: true
+ dismissed: true,
+ eventCallback: function(aTopic) aTopic == "swapping"
};
chromeWin.PopupNotifications.show(aBrowser, "webRTC-sharingDevices", message,
"webRTC-sharingDevices-notification-icon", mainAction,
diff --git a/application/palemoon/themes/linux/browser.css b/application/palemoon/themes/linux/browser.css
index 4f4964db8..dbdc06235 100644
--- a/application/palemoon/themes/linux/browser.css
+++ b/application/palemoon/themes/linux/browser.css
@@ -1169,6 +1169,10 @@ toolbar[iconsize="small"] #webrtc-status-button {
list-style-image: url(chrome://browser/skin/Geolocation-64.png);
}
+.popup-notification-icon[popupid="push"] {
+ list-style-image: url(chrome://browser/skin/Push-64.png);
+}
+
.popup-notification-icon[popupid="xpinstall-disabled"],
.popup-notification-icon[popupid="addon-progress"],
.popup-notification-icon[popupid="addon-install-cancelled"],
@@ -1374,7 +1378,18 @@ toolbar[iconsize="small"] #webrtc-status-button {
.web-notifications-notification-icon,
#web-notifications-notification-icon {
- list-style-image: url(chrome://browser/skin/notification-16.png);
+ list-style-image: url(chrome://browser/skin/web-notifications-tray.svg);
+ -moz-image-region: rect(0, 16px, 16px, 0);
+}
+
+.web-notifications-notification-icon:hover,
+#web-notifications-notification-icon:hover {
+ -moz-image-region: rect(0, 32px, 16px, 16px);
+}
+
+.web-notifications-notification-icon:hover:active,
+#web-notifications-notification-icon:hover:active {
+ -moz-image-region: rect(0, 48px, 16px, 32px);
}
#pointerLock-notification-icon {
@@ -2052,10 +2067,6 @@ toolbar[mode="text"] toolbarbutton.chevron > .toolbarbutton-icon {
box-shadow: 0 0 2px white;
}
-#full-screen-warning-container[obscure-browser] {
- background-color: rgba(0,0,0,0.3);
-}
-
.full-screen-description {
font-size: 150%;
}
@@ -2064,11 +2075,6 @@ toolbar[mode="text"] toolbarbutton.chevron > .toolbarbutton-icon {
font-size: 300%;
}
-.full-screen-approval-button,
-#full-screen-remember-decision {
- font-size: 120%;
-}
-
%ifdef MOZ_DEVTOOLS
%include ../../../../devtools/client/themes/responsivedesign.inc.css
%include ../../../../devtools/client/themes/commandline.inc.css
diff --git a/application/palemoon/themes/linux/jar.mn b/application/palemoon/themes/linux/jar.mn
index 7e67d0129..3c2ac406e 100644
--- a/application/palemoon/themes/linux/jar.mn
+++ b/application/palemoon/themes/linux/jar.mn
@@ -36,8 +36,6 @@ browser.jar:
skin/classic/browser/mixed-content-blocked-64.png
skin/classic/browser/monitor.png
skin/classic/browser/monitor_16-10.png
- skin/classic/browser/notification-16.png
- skin/classic/browser/notification-64.png
* skin/classic/browser/pageInfo.css
skin/classic/browser/pageInfo.png
skin/classic/browser/page-livemarks.png
@@ -54,6 +52,8 @@ browser.jar:
skin/classic/browser/Toolbar.png
skin/classic/browser/Toolbar-small.png
skin/classic/browser/urlbar-arrow.png
+ skin/classic/browser/web-notifications-icon.svg
+ skin/classic/browser/web-notifications-tray.svg
#ifdef MOZ_WEBRTC
skin/classic/browser/webRTC-shareDevice-16.png
skin/classic/browser/webRTC-shareDevice-64.png
diff --git a/application/palemoon/themes/linux/notification-16.png b/application/palemoon/themes/linux/notification-16.png
deleted file mode 100644
index 6b2df7341..000000000
--- a/application/palemoon/themes/linux/notification-16.png
+++ /dev/null
Binary files differ
diff --git a/application/palemoon/themes/linux/notification-64.png b/application/palemoon/themes/linux/notification-64.png
deleted file mode 100644
index a01d0ab77..000000000
--- a/application/palemoon/themes/linux/notification-64.png
+++ /dev/null
Binary files differ
diff --git a/application/palemoon/themes/linux/preferences/aboutPermissions.css b/application/palemoon/themes/linux/preferences/aboutPermissions.css
index 406568831..2ad833fb2 100644
--- a/application/palemoon/themes/linux/preferences/aboutPermissions.css
+++ b/application/palemoon/themes/linux/preferences/aboutPermissions.css
@@ -90,7 +90,7 @@
list-style-image: url(chrome://global/skin/icons/question-64.png);
}
.pref-icon[type="desktop-notification"] {
- list-style-image: url(chrome://browser/skin/notification-64.png);
+ list-style-image: url(chrome://browser/skin/web-notifications-icon.svg);
}
.pref-icon[type="install"] {
list-style-image: url(chrome://mozapps/skin/extensions/extensionGeneric.png);
@@ -104,12 +104,6 @@
.pref-icon[type="plugins"] {
list-style-image: url(chrome://mozapps/skin/plugins/pluginGeneric.png);
}
-.pref-icon[type="fullscreen"] {
- list-style-image: url(chrome://global/skin/icons/question-64.png);
-}
-.pref-icon[type="pointerLock"] {
- list-style-image: url(chrome://global/skin/icons/question-64.png);
-}
.pref-title {
font-size: 125%;
diff --git a/application/palemoon/themes/linux/web-notifications-icon.svg b/application/palemoon/themes/linux/web-notifications-icon.svg
new file mode 100644
index 000000000..f7186c727
--- /dev/null
+++ b/application/palemoon/themes/linux/web-notifications-icon.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid" width="64" height="64" viewBox="0 0 64 64">
+ <defs>
+ <style>
+ .icon {
+ fill: #a6a6a6;
+ fill-rule: evenodd;
+ }
+ </style>
+ </defs>
+ <path d="M57,48 L46,48 L46,60.016 L32.482,48 L7,48 C5.343,48 4,46.657 4,45 L4,11.031 C4,9.374 5.343,8.031 7,8.031 L57,8.031 C58.657,8.031 60,9.374 60,11.031 L60,45 C60,46.657 58.657,48 57,48 ZM36,16.031 C36,14.927 35.105,14.031 34,14.031 L30,14.031 C28.895,14.031 28,14.927 28,16.031 L28,30.031 C28,31.136 28.895,32.031 30,32.031 L34,32.031 C35.105,32.031 36,31.136 36,30.031 L36,16.031 ZM36,37.5 C36,36.672 35.328,36 34.5,36 L29.5,36 C28.672,36 28,36.672 28,37.5 L28,40.5 C28,41.328 28.672,42 29.5,42 L34.5,42 C35.328,42 36,41.328 36,40.5 L36,37.5 Z" class="icon"/>
+</svg>
diff --git a/application/palemoon/themes/linux/web-notifications-tray.svg b/application/palemoon/themes/linux/web-notifications-tray.svg
new file mode 100644
index 000000000..314026a10
--- /dev/null
+++ b/application/palemoon/themes/linux/web-notifications-tray.svg
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="48" height="16" viewBox="0 0 96 32">
+ <defs>
+ <style>
+ .style-icon-notification {
+ fill: #666666;
+ }
+ .style-icon-notification.hover {
+ fill: #808080;
+ }
+ .style-icon-notification.active {
+ fill: #4d4d4d;
+ }
+ </style>
+ <path id="shape-notifcations-push" d="M27,23.969 L24,23.969 L24,29.977 L17.241,23.969 L5,23.969 C3.343,23.969 2,22.626 2,20.969 L2,6.969 C2,5.312 3.343,3.969 5,3.969 L27,3.969 C28.657,3.969 30,5.312 30,6.969 L30,20.969 C30,22.626 28.657,23.969 27,23.969 ZM18,8.969 C18,7.864 17.105,6.969 16,6.969 C14.895,6.969 14,7.864 14,8.969 L14,13.969 C14,15.073 14.895,15.969 16,15.969 C17.105,15.969 18,15.073 18,13.969 L18,8.969 ZM16.5,17.969 L15.5,17.969 C14.672,17.969 14,18.640 14,19.469 C14,20.297 14.672,20.969 15.5,20.969 L16.5,20.969 C17.328,20.969 18,20.297 18,19.469 C18,18.640 17.328,17.969 16.5,17.969 Z"/>
+ </defs>
+ <use xlink:href="#shape-notifcations-push" class="style-icon-notification"/>
+ <use xlink:href="#shape-notifcations-push" transform="translate(32)" class="style-icon-notification hover"/>
+ <use xlink:href="#shape-notifcations-push" transform="translate(64)" class="style-icon-notification active"/>
+</svg>
diff --git a/application/palemoon/themes/osx/browser.css b/application/palemoon/themes/osx/browser.css
index 8d709d8e1..6307c5f58 100644
--- a/application/palemoon/themes/osx/browser.css
+++ b/application/palemoon/themes/osx/browser.css
@@ -2061,7 +2061,18 @@ toolbarbutton.bookmark-item[dragover="true"][open="true"] {
.web-notifications-notification-icon,
#web-notifications-notification-icon {
- list-style-image: url(chrome://browser/skin/notification-16.png);
+ list-style-image: url(chrome://browser/skin/web-notifications-tray.svg);
+ -moz-image-region: rect(0, 16px, 16px, 0);
+}
+
+.web-notifications-notification-icon:hover,
+#web-notifications-notification-icon:hover {
+ -moz-image-region: rect(0, 32px, 16px, 16px);
+}
+
+.web-notifications-notification-icon:hover:active,
+#web-notifications-notification-icon:hover:active {
+ -moz-image-region: rect(0, 48px, 16px, 32px);
}
#pointerLock-notification-icon {
@@ -2335,10 +2346,6 @@ toolbar[brighttext] #addonbar-closebutton {
box-shadow: 0 0 2px white;
}
-#full-screen-warning-container[obscure-browser] {
- background-color: rgba(0,0,0,0.3);
-}
-
.full-screen-description {
font-size: 150%;
}
@@ -2347,11 +2354,6 @@ toolbar[brighttext] #addonbar-closebutton {
font-size: 300%;
}
-.full-screen-approval-button,
-#full-screen-remember-decision {
- font-size: 120%;
-}
-
%ifdef MOZ_DEVTOOLS
%include ../../../../devtools/client/themes/responsivedesign.inc.css
%include ../../../../devtools/client/themes/commandline.inc.css
diff --git a/application/palemoon/themes/osx/jar.mn b/application/palemoon/themes/osx/jar.mn
index 186cd8a75..a085c5f81 100644
--- a/application/palemoon/themes/osx/jar.mn
+++ b/application/palemoon/themes/osx/jar.mn
@@ -41,8 +41,6 @@ browser.jar:
skin/classic/browser/mixed-content-blocked-64.png
skin/classic/browser/monitor.png
skin/classic/browser/monitor_16-10.png
- skin/classic/browser/notification-16.png
- skin/classic/browser/notification-64.png
skin/classic/browser/pageInfo.css
skin/classic/browser/pageInfo.png
skin/classic/browser/page-livemarks.png
@@ -70,6 +68,8 @@ browser.jar:
skin/classic/browser/urlbar-history-dropmarker.png
skin/classic/browser/webapps-16.png
skin/classic/browser/webapps-64.png
+ skin/classic/browser/web-notifications-icon.svg
+ skin/classic/browser/web-notifications-tray.svg
skin/classic/browser/notification-pluginNormal.png (../shared/plugins/notification-pluginNormal.png)
skin/classic/browser/notification-pluginAlert.png (../shared/plugins/notification-pluginAlert.png)
skin/classic/browser/notification-pluginBlocked.png (../shared/plugins/notification-pluginBlocked.png)
diff --git a/application/palemoon/themes/osx/notification-16.png b/application/palemoon/themes/osx/notification-16.png
deleted file mode 100644
index 6b2df7341..000000000
--- a/application/palemoon/themes/osx/notification-16.png
+++ /dev/null
Binary files differ
diff --git a/application/palemoon/themes/osx/notification-64.png b/application/palemoon/themes/osx/notification-64.png
deleted file mode 100644
index a01d0ab77..000000000
--- a/application/palemoon/themes/osx/notification-64.png
+++ /dev/null
Binary files differ
diff --git a/application/palemoon/themes/osx/preferences/aboutPermissions.css b/application/palemoon/themes/osx/preferences/aboutPermissions.css
index cfb941bbb..de636f5c4 100644
--- a/application/palemoon/themes/osx/preferences/aboutPermissions.css
+++ b/application/palemoon/themes/osx/preferences/aboutPermissions.css
@@ -93,7 +93,7 @@
list-style-image: url(chrome://global/skin/icons/question-64.png);
}
.pref-icon[type="desktop-notification"] {
- list-style-image: url(chrome://browser/skin/notification-64.png);
+ list-style-image: url(chrome://browser/skin/web-notifications-icon.svg);
}
.pref-icon[type="install"] {
list-style-image: url(chrome://mozapps/skin/extensions/extensionGeneric.png);
@@ -107,12 +107,6 @@
.pref-icon[type="plugins"] {
list-style-image: url(chrome://mozapps/skin/plugins/pluginGeneric.png);
}
-.pref-icon[type="fullscreen"] {
- list-style-image: url(chrome://global/skin/icons/question-64.png);
-}
-.pref-icon[type="pointerLock"] {
- list-style-image: url(chrome://global/skin/icons/question-64.png);
-}
.pref-title {
font-size: 125%;
diff --git a/application/palemoon/themes/osx/web-notifications-icon.svg b/application/palemoon/themes/osx/web-notifications-icon.svg
new file mode 100644
index 000000000..f7186c727
--- /dev/null
+++ b/application/palemoon/themes/osx/web-notifications-icon.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid" width="64" height="64" viewBox="0 0 64 64">
+ <defs>
+ <style>
+ .icon {
+ fill: #a6a6a6;
+ fill-rule: evenodd;
+ }
+ </style>
+ </defs>
+ <path d="M57,48 L46,48 L46,60.016 L32.482,48 L7,48 C5.343,48 4,46.657 4,45 L4,11.031 C4,9.374 5.343,8.031 7,8.031 L57,8.031 C58.657,8.031 60,9.374 60,11.031 L60,45 C60,46.657 58.657,48 57,48 ZM36,16.031 C36,14.927 35.105,14.031 34,14.031 L30,14.031 C28.895,14.031 28,14.927 28,16.031 L28,30.031 C28,31.136 28.895,32.031 30,32.031 L34,32.031 C35.105,32.031 36,31.136 36,30.031 L36,16.031 ZM36,37.5 C36,36.672 35.328,36 34.5,36 L29.5,36 C28.672,36 28,36.672 28,37.5 L28,40.5 C28,41.328 28.672,42 29.5,42 L34.5,42 C35.328,42 36,41.328 36,40.5 L36,37.5 Z" class="icon"/>
+</svg>
diff --git a/application/palemoon/themes/osx/web-notifications-tray.svg b/application/palemoon/themes/osx/web-notifications-tray.svg
new file mode 100644
index 000000000..314026a10
--- /dev/null
+++ b/application/palemoon/themes/osx/web-notifications-tray.svg
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="48" height="16" viewBox="0 0 96 32">
+ <defs>
+ <style>
+ .style-icon-notification {
+ fill: #666666;
+ }
+ .style-icon-notification.hover {
+ fill: #808080;
+ }
+ .style-icon-notification.active {
+ fill: #4d4d4d;
+ }
+ </style>
+ <path id="shape-notifcations-push" d="M27,23.969 L24,23.969 L24,29.977 L17.241,23.969 L5,23.969 C3.343,23.969 2,22.626 2,20.969 L2,6.969 C2,5.312 3.343,3.969 5,3.969 L27,3.969 C28.657,3.969 30,5.312 30,6.969 L30,20.969 C30,22.626 28.657,23.969 27,23.969 ZM18,8.969 C18,7.864 17.105,6.969 16,6.969 C14.895,6.969 14,7.864 14,8.969 L14,13.969 C14,15.073 14.895,15.969 16,15.969 C17.105,15.969 18,15.073 18,13.969 L18,8.969 ZM16.5,17.969 L15.5,17.969 C14.672,17.969 14,18.640 14,19.469 C14,20.297 14.672,20.969 15.5,20.969 L16.5,20.969 C17.328,20.969 18,20.297 18,19.469 C18,18.640 17.328,17.969 16.5,17.969 Z"/>
+ </defs>
+ <use xlink:href="#shape-notifcations-push" class="style-icon-notification"/>
+ <use xlink:href="#shape-notifcations-push" transform="translate(32)" class="style-icon-notification hover"/>
+ <use xlink:href="#shape-notifcations-push" transform="translate(64)" class="style-icon-notification active"/>
+</svg>
diff --git a/application/palemoon/themes/windows/Push-16.png b/application/palemoon/themes/windows/Push-16.png
new file mode 100644
index 000000000..d710e7336
--- /dev/null
+++ b/application/palemoon/themes/windows/Push-16.png
Binary files differ
diff --git a/application/palemoon/themes/windows/Push-64.png b/application/palemoon/themes/windows/Push-64.png
new file mode 100644
index 000000000..27fecb858
--- /dev/null
+++ b/application/palemoon/themes/windows/Push-64.png
Binary files differ
diff --git a/application/palemoon/themes/windows/browser.css b/application/palemoon/themes/windows/browser.css
index 1c51accae..b87b50732 100644
--- a/application/palemoon/themes/windows/browser.css
+++ b/application/palemoon/themes/windows/browser.css
@@ -2548,7 +2548,18 @@ toolbarbutton.bookmark-item[dragover="true"][open="true"] {
.web-notifications-notification-icon,
#web-notifications-notification-icon {
- list-style-image: url(chrome://browser/skin/notification-16.png);
+ list-style-image: url(chrome://browser/skin/web-notifications-tray.svg);
+ -moz-image-region: rect(0, 16px, 16px, 0);
+}
+
+.web-notifications-notification-icon:hover,
+#web-notifications-notification-icon:hover {
+ -moz-image-region: rect(0, 32px, 16px, 16px);
+}
+
+.web-notifications-notification-icon:hover:active,
+#web-notifications-notification-icon:hover:active {
+ -moz-image-region: rect(0, 48px, 16px, 32px);
}
#pointerLock-notification-icon {
@@ -2809,10 +2820,6 @@ toolbar[brighttext] #addonbar-closebutton {
box-shadow: 0 0 2px white;
}
-#full-screen-warning-container[obscure-browser] {
- background-color: rgba(0,0,0,0.3);
-}
-
.full-screen-description {
font-size: 150%;
}
@@ -2821,11 +2828,6 @@ toolbar[brighttext] #addonbar-closebutton {
font-size: 300%;
}
-.full-screen-approval-button,
-#full-screen-remember-decision {
- font-size: 120%;
-}
-
%ifdef MOZ_DEVTOOLS
%include ../../../../devtools/client/themes/responsivedesign.inc.css
%include ../../../../devtools/client/themes/commandline.inc.css
diff --git a/application/palemoon/themes/windows/jar.mn b/application/palemoon/themes/windows/jar.mn
index a66714b13..8c0d9a5cc 100644
--- a/application/palemoon/themes/windows/jar.mn
+++ b/application/palemoon/themes/windows/jar.mn
@@ -42,8 +42,6 @@ browser.jar:
skin/classic/browser/mixed-content-blocked-64.png
skin/classic/browser/monitor.png
skin/classic/browser/monitor_16-10.png
- skin/classic/browser/notification-16.png
- skin/classic/browser/notification-64.png
skin/classic/browser/pageInfo.css
skin/classic/browser/pageInfo.png
skin/classic/browser/page-livemarks.png (feeds/feedIcon16.png)
@@ -72,6 +70,8 @@ browser.jar:
skin/classic/browser/urlbar-history-dropmarker.png
skin/classic/browser/webapps-16.png
skin/classic/browser/webapps-64.png
+ skin/classic/browser/web-notifications-icon.svg
+ skin/classic/browser/web-notifications-tray.svg
skin/classic/browser/notification-pluginNormal.png (../shared/plugins/notification-pluginNormal.png)
skin/classic/browser/notification-pluginAlert.png (../shared/plugins/notification-pluginAlert.png)
skin/classic/browser/notification-pluginBlocked.png (../shared/plugins/notification-pluginBlocked.png)
diff --git a/application/palemoon/themes/windows/notification-16.png b/application/palemoon/themes/windows/notification-16.png
deleted file mode 100644
index 6b2df7341..000000000
--- a/application/palemoon/themes/windows/notification-16.png
+++ /dev/null
Binary files differ
diff --git a/application/palemoon/themes/windows/notification-64.png b/application/palemoon/themes/windows/notification-64.png
deleted file mode 100644
index a01d0ab77..000000000
--- a/application/palemoon/themes/windows/notification-64.png
+++ /dev/null
Binary files differ
diff --git a/application/palemoon/themes/windows/preferences/aboutPermissions.css b/application/palemoon/themes/windows/preferences/aboutPermissions.css
index d9db6ccbf..c985150de 100644
--- a/application/palemoon/themes/windows/preferences/aboutPermissions.css
+++ b/application/palemoon/themes/windows/preferences/aboutPermissions.css
@@ -93,7 +93,7 @@
list-style-image: url(chrome://global/skin/icons/question-48.png);
}
.pref-icon[type="desktop-notification"] {
- list-style-image: url(chrome://browser/skin/notification-64.png);
+ list-style-image: url(chrome://browser/skin/web-notifications-icon.svg);
}
.pref-icon[type="install"] {
list-style-image: url(chrome://mozapps/skin/extensions/extensionGeneric-48.png);
@@ -107,12 +107,6 @@
.pref-icon[type="plugins"] {
list-style-image: url(chrome://mozapps/skin/plugins/pluginGeneric-48.png);
}
-.pref-icon[type="fullscreen"] {
- list-style-image: url(chrome://global/skin/icons/question-48.png);
-}
-.pref-icon[type="pointerLock"] {
- list-style-image: url(chrome://global/skin/icons/question-48.png);
-}
.pref-title {
font-size: 125%;
diff --git a/application/palemoon/themes/windows/web-notifications-icon.svg b/application/palemoon/themes/windows/web-notifications-icon.svg
new file mode 100644
index 000000000..f7186c727
--- /dev/null
+++ b/application/palemoon/themes/windows/web-notifications-icon.svg
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid" width="64" height="64" viewBox="0 0 64 64">
+ <defs>
+ <style>
+ .icon {
+ fill: #a6a6a6;
+ fill-rule: evenodd;
+ }
+ </style>
+ </defs>
+ <path d="M57,48 L46,48 L46,60.016 L32.482,48 L7,48 C5.343,48 4,46.657 4,45 L4,11.031 C4,9.374 5.343,8.031 7,8.031 L57,8.031 C58.657,8.031 60,9.374 60,11.031 L60,45 C60,46.657 58.657,48 57,48 ZM36,16.031 C36,14.927 35.105,14.031 34,14.031 L30,14.031 C28.895,14.031 28,14.927 28,16.031 L28,30.031 C28,31.136 28.895,32.031 30,32.031 L34,32.031 C35.105,32.031 36,31.136 36,30.031 L36,16.031 ZM36,37.5 C36,36.672 35.328,36 34.5,36 L29.5,36 C28.672,36 28,36.672 28,37.5 L28,40.5 C28,41.328 28.672,42 29.5,42 L34.5,42 C35.328,42 36,41.328 36,40.5 L36,37.5 Z" class="icon"/>
+</svg>
diff --git a/application/palemoon/themes/windows/web-notifications-tray.svg b/application/palemoon/themes/windows/web-notifications-tray.svg
new file mode 100644
index 000000000..314026a10
--- /dev/null
+++ b/application/palemoon/themes/windows/web-notifications-tray.svg
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-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/. -->
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="48" height="16" viewBox="0 0 96 32">
+ <defs>
+ <style>
+ .style-icon-notification {
+ fill: #666666;
+ }
+ .style-icon-notification.hover {
+ fill: #808080;
+ }
+ .style-icon-notification.active {
+ fill: #4d4d4d;
+ }
+ </style>
+ <path id="shape-notifcations-push" d="M27,23.969 L24,23.969 L24,29.977 L17.241,23.969 L5,23.969 C3.343,23.969 2,22.626 2,20.969 L2,6.969 C2,5.312 3.343,3.969 5,3.969 L27,3.969 C28.657,3.969 30,5.312 30,6.969 L30,20.969 C30,22.626 28.657,23.969 27,23.969 ZM18,8.969 C18,7.864 17.105,6.969 16,6.969 C14.895,6.969 14,7.864 14,8.969 L14,13.969 C14,15.073 14.895,15.969 16,15.969 C17.105,15.969 18,15.073 18,13.969 L18,8.969 ZM16.5,17.969 L15.5,17.969 C14.672,17.969 14,18.640 14,19.469 C14,20.297 14.672,20.969 15.5,20.969 L16.5,20.969 C17.328,20.969 18,20.297 18,19.469 C18,18.640 17.328,17.969 16.5,17.969 Z"/>
+ </defs>
+ <use xlink:href="#shape-notifcations-push" class="style-icon-notification"/>
+ <use xlink:href="#shape-notifcations-push" transform="translate(32)" class="style-icon-notification hover"/>
+ <use xlink:href="#shape-notifcations-push" transform="translate(64)" class="style-icon-notification active"/>
+</svg>
diff --git a/browser/app/application.ini b/browser/app/application.ini
new file mode 100644
index 000000000..05317eee9
--- /dev/null
+++ b/browser/app/application.ini
@@ -0,0 +1,50 @@
+#if MOZ_APP_STATIC_INI
+#ifdef MOZ_BUILD_APP_IS_BROWSER
+; This file is not used. If you modify it and want the application to use
+; your modifications, move it under the browser/ subdirectory and start with
+; the "-app /path/to/browser/application.ini" argument.
+#else
+; This file is not used. If you modify it and want the application to use
+; your modifications, start with the "-app /path/to/application.ini"
+; argument.
+#endif
+#endif
+#if 0
+; This Source Code Form is subject to the terms of the Mozilla Public
+; License, v. 2.0. If a copy of the MPL was not distributed with this
+; file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#endif
+#filter substitution
+#include @TOPOBJDIR@/buildid.h
+#include @TOPOBJDIR@/source-repo.h
+
+[App]
+# Vendor=@MOZ_APP_VENDOR@
+Vendor=Moonchild Productions
+# Name=@MOZ_APP_BASENAME@
+Name=Basilisk
+RemotingName=@MOZ_APP_REMOTINGNAME@
+#ifdef MOZ_APP_DISPLAYNAME
+CodeName=@MOZ_APP_DISPLAYNAME@
+#endif
+Version=@MOZ_APP_VERSION@
+#ifdef MOZ_APP_PROFILE
+Profile=@MOZ_APP_PROFILE@
+#endif
+BuildID=@MOZ_BUILDID@
+#ifdef MOZ_SOURCE_REPO
+SourceRepository=@MOZ_SOURCE_REPO@
+#endif
+#ifdef MOZ_SOURCE_STAMP
+SourceStamp=@MOZ_SOURCE_STAMP@
+#endif
+ID=@MOZ_APP_ID@
+
+[Gecko]
+MinVersion=@GRE_MILESTONE@
+MaxVersion=@GRE_MILESTONE@
+
+[XRE]
+#ifdef MOZ_PROFILE_MIGRATOR
+EnableProfileMigrator=1
+#endif \ No newline at end of file
diff --git a/browser/app/moz.build b/browser/app/moz.build
index 520ce4425..1004e280c 100644
--- a/browser/app/moz.build
+++ b/browser/app/moz.build
@@ -48,22 +48,6 @@ if CONFIG['OS_ARCH'] == 'WINNT':
for cdm in CONFIG['MOZ_EME_MODULES']:
DEFINES['MOZ_%s_EME' % cdm.upper()] = True
-if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_ARCH'] == 'WINNT':
- # For sandbox includes and the include dependencies those have
- LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
- ]
-
- USE_LIBS += [
- 'sandbox_s',
- ]
-
- DELAYLOAD_DLLS += [
- 'winmm.dll',
- 'user32.dll',
- ]
-
# 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.
diff --git a/browser/app/nsBrowserApp.cpp b/browser/app/nsBrowserApp.cpp
index 184b1fc2e..66ea8aed5 100644
--- a/browser/app/nsBrowserApp.cpp
+++ b/browser/app/nsBrowserApp.cpp
@@ -26,9 +26,6 @@
#ifdef XP_WIN
#define XRE_WANT_ENVIRON
#define strcasecmp _stricmp
-#ifdef MOZ_SANDBOX
-#include "mozilla/sandboxing/SandboxInitialization.h"
-#endif
#endif
#include "BinaryPath.h"
@@ -38,8 +35,7 @@
#include "mozilla/Telemetry.h"
#include "mozilla/WindowsDllBlocklist.h"
-#if !defined(MOZ_WIDGET_COCOA) && !defined(MOZ_WIDGET_ANDROID) \
- && !(defined(XP_LINUX) && defined(MOZ_SANDBOX))
+#if !defined(MOZ_WIDGET_COCOA) && !defined(MOZ_WIDGET_ANDROID)
#define MOZ_BROWSER_CAN_BE_CONTENTPROC
#include "../../ipc/contentproc/plugin-container.cpp"
#endif
@@ -201,13 +197,7 @@ static int do_main(int argc, char* argv[], char* envp[], nsIFile *xreDirectory)
argv[i] = argv[i + 1];
}
- XREShellData shellData;
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- shellData.sandboxBrokerServices =
- sandboxing::GetInitializedBrokerServices();
-#endif
-
- return XRE_XPCShellMain(--argc, argv, envp, &shellData);
+ return XRE_XPCShellMain(--argc, argv, envp);
}
if (appini) {
@@ -257,18 +247,6 @@ static int do_main(int argc, char* argv[], char* envp[], nsIFile *xreDirectory)
DllBlocklist_CheckStatus() ? NS_XRE_DLL_BLOCKLIST_ENABLED : 0;
#endif
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- sandbox::BrokerServices* brokerServices =
- sandboxing::GetInitializedBrokerServices();
-#if defined(MOZ_CONTENT_SANDBOX)
- if (!brokerServices) {
- Output("Couldn't initialize the broker services.\n");
- return 255;
- }
-#endif
- appData.sandboxBrokerServices = brokerServices;
-#endif
-
#ifdef LIBFUZZER
if (getenv("LIBFUZZER"))
XRE_LibFuzzerSetMain(argc, argv, libfuzzer_main);
@@ -370,15 +348,6 @@ int main(int argc, char* argv[], char* envp[])
// We are launching as a content process, delegate to the appropriate
// main
if (argc > 1 && IsArg(argv[1], "contentproc")) {
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- // We need to initialize the sandbox TargetServices before InitXPCOMGlue
- // because we might need the sandbox broker to give access to some files.
- if (IsSandboxedProcess() && !sandboxing::GetInitializedTargetServices()) {
- Output("Failed to initialize the sandbox target services.");
- return 255;
- }
-#endif
-
nsresult rv = InitXPCOMGlue(argv[0], nullptr);
if (NS_FAILED(rv)) {
return 255;
diff --git a/browser/app/profile/firefox.js b/browser/app/profile/firefox.js
index fb85a9fb9..1182741bd 100644
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -909,100 +909,6 @@ pref("dom.ipc.shims.enabledWarnings", false);
pref("browser.tabs.remote.autostart", false);
pref("browser.tabs.remote.desktopbehavior", true);
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-// When this pref is true the Windows process sandbox will set up dummy
-// interceptions and log to the browser console when calls fail in the sandboxed
-// process and also if they are subsequently allowed by the broker process.
-// This will require a restart.
-pref("security.sandbox.windows.log", false);
-
-// Controls whether and how the Windows NPAPI plugin process is sandboxed.
-// To get a different setting for a particular plugin replace "default", with
-// the plugin's nice file name, see: nsPluginTag::GetNiceFileName.
-// On windows these levels are:
-// 0 - no sandbox
-// 1 - sandbox with USER_NON_ADMIN access token level
-// 2 - a more strict sandbox, which might cause functionality issues. This now
-// includes running at low integrity.
-// 3 - the strongest settings we seem to be able to use without breaking
-// everything, but will probably cause some functionality restrictions
-pref("dom.ipc.plugins.sandbox-level.default", 0);
-#if defined(_AMD64_)
-// The lines in PluginModuleParent.cpp should be changed in line with this.
-pref("dom.ipc.plugins.sandbox-level.flash", 2);
-#else
-pref("dom.ipc.plugins.sandbox-level.flash", 0);
-#endif
-
-#if defined(MOZ_CONTENT_SANDBOX)
-// This controls the strength of the Windows content process sandbox for testing
-// purposes. This will require a restart.
-// On windows these levels are:
-// See - security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp
-// SetSecurityLevelForContentProcess() for what the different settings mean.
-#if defined(NIGHTLY_BUILD)
-pref("security.sandbox.content.level", 2);
-#else
-pref("security.sandbox.content.level", 1);
-#endif
-
-// This controls the depth of stack trace that is logged when Windows sandbox
-// logging is turned on. This is only currently available for the content
-// process because the only other sandbox (for GMP) has too strict a policy to
-// allow stack tracing. This does not require a restart to take effect.
-pref("security.sandbox.windows.log.stackTraceDepth", 0);
-#endif
-#endif
-
-#if defined(XP_MACOSX) && defined(MOZ_SANDBOX) && defined(MOZ_CONTENT_SANDBOX)
-// This pref is discussed in bug 1083344, the naming is inspired from its
-// Windows counterpart, but on Mac it's an integer which means:
-// 0 -> "no sandbox"
-// 1 -> "preliminary content sandboxing enabled: write access to
-// home directory is prevented"
-// 2 -> "preliminary content sandboxing enabled with profile protection:
-// write access to home directory is prevented, read and write access
-// to ~/Library and profile directories are prevented (excluding
-// $PROFILE/{extensions,weave})"
-// This setting is read when the content process is started. On Mac the content
-// process is killed when all windows are closed, so a change will take effect
-// when the 1st window is opened.
-#if defined(NIGHTLY_BUILD)
-pref("security.sandbox.content.level", 2);
-#else
-pref("security.sandbox.content.level", 1);
-#endif
-#endif
-
-#if defined(XP_LINUX) && defined(MOZ_SANDBOX) && defined(MOZ_CONTENT_SANDBOX)
-// This pref is introduced as part of bug 742434, the naming is inspired from
-// its Windows/Mac counterpart, but on Linux it's an integer which means:
-// 0 -> "no sandbox"
-// 1 -> "content sandbox using seccomp-bpf when available"
-// 2 -> "seccomp-bpf + file broker"
-// Content sandboxing on Linux is currently in the stage of
-// 'just getting it enabled', which includes a very permissive whitelist. We
-// enable seccomp-bpf on nightly to see if everything is running, or if we need
-// to whitelist more system calls.
-//
-// So the purpose of this setting is to allow nightly users to disable the
-// sandbox while we fix their problems. This way, they won't have to wait for
-// another nightly release which disables seccomp-bpf again.
-//
-// This setting may not be required anymore once we decide to permanently
-// enable the content sandbox.
-pref("security.sandbox.content.level", 2);
-#endif
-
-#if defined(XP_MACOSX) || defined(XP_WIN)
-#if defined(MOZ_SANDBOX) && defined(MOZ_CONTENT_SANDBOX)
-// ID (a UUID when set by gecko) that is used to form the name of a
-// sandbox-writable temporary directory to be used by content processes
-// when a temporary writable file is required in a level 1 sandbox.
-pref("security.sandbox.content.tempDirSuffix", "");
-#endif
-#endif
-
// This pref governs whether we attempt to work around problems caused by
// plugins using OS calls to manipulate the cursor while running out-of-
// process. These workarounds all involve intercepting (hooking) certain
diff --git a/browser/base/content/browser-addons.js b/browser/base/content/browser-addons.js
index 1f81d1fb0..1d881536a 100644
--- a/browser/base/content/browser-addons.js
+++ b/browser/base/content/browser-addons.js
@@ -459,15 +459,15 @@ var LightWeightThemeWebInstaller = {
switch (message.name) {
case "LightWeightThemeWebInstaller:Install": {
- this._installRequest(data.themeData, data.baseURI);
+ this._installRequest(data.themeData, data.principal, data.baseURI);
break;
}
case "LightWeightThemeWebInstaller:Preview": {
- this._preview(data.themeData, data.baseURI);
+ this._preview(data.themeData, data.principal, data.baseURI);
break;
}
case "LightWeightThemeWebInstaller:ResetPreview": {
- this._resetPreview(data && data.baseURI);
+ this._resetPreview(data && data.principal);
break;
}
}
@@ -489,33 +489,24 @@ var LightWeightThemeWebInstaller = {
return this._manager = temp.LightweightThemeManager;
},
- _installRequest: function (dataString, baseURI) {
+ _installRequest(dataString, principal, baseURI) {
+ // Don't allow installing off null principals.
+ if (!principal.URI) {
+ return;
+ }
+
let data = this._manager.parseTheme(dataString, baseURI);
if (!data) {
return;
}
- let uri = makeURI(baseURI);
-
// A notification bar with the option to undo is normally shown after a
// theme is installed. But the discovery pane served from the url(s)
// below has its own toggle switch for quick undos, so don't show the
// notification in that case.
- let notify = uri.prePath != "https://discovery.addons.mozilla.org";
- if (notify) {
- try {
- if (Services.prefs.getBoolPref("extensions.webapi.testing")
- && (uri.prePath == "https://discovery.addons.allizom.org"
- || uri.prePath == "https://discovery.addons-dev.allizom.org")) {
- notify = false;
- }
- } catch (e) {
- // getBoolPref() throws if the testing pref isn't set. ignore it.
- }
- }
-
- if (this._isAllowed(baseURI)) {
+ let notify = this._shouldShowUndoPrompt(principal);
+ if (this._isAllowed(principal)) {
this._install(data, notify);
return;
}
@@ -526,7 +517,7 @@ var LightWeightThemeWebInstaller = {
gNavigatorBundle.getString("lwthemeInstallRequest.allowButton.accesskey");
let message =
gNavigatorBundle.getFormattedString("lwthemeInstallRequest.message",
- [uri.host]);
+ [principal.URI.host]);
let buttons = [{
label: allowButtonText,
accessKey: allowButtonAccesskey,
@@ -629,8 +620,8 @@ var LightWeightThemeWebInstaller = {
});
},
- _preview: function (dataString, baseURI) {
- if (!this._isAllowed(baseURI))
+ _preview(dataString, principal, baseURI) {
+ if (!this._isAllowed(principal))
return;
let data = this._manager.parseTheme(dataString, baseURI);
@@ -642,29 +633,33 @@ var LightWeightThemeWebInstaller = {
this._manager.previewTheme(data);
},
- _resetPreview: function (baseURI) {
- if (baseURI && !this._isAllowed(baseURI))
+ _resetPreview(principal) {
+ if (!this._isAllowed(principal))
return;
gBrowser.tabContainer.removeEventListener("TabSelect", this, false);
this._manager.resetPreview();
},
- _isAllowed: function (srcURIString) {
- let uri;
- try {
- uri = makeURI(srcURIString);
- }
- catch (e) {
- // makeURI fails if srcURIString is a nonsense URI
+ _isAllowed(principal) {
+ if (!principal || !principal.URI || !principal.URI.schemeIs("https")) {
return false;
}
- if (!uri.schemeIs("https")) {
+ let pm = Services.perms;
+ return pm.testPermission(principal.URI, "install") == pm.ALLOW_ACTION;
+ },
+
+ _shouldShowUndoPrompt(principal) {
+ if (!principal || !principal.URI) {
+ return true;
+ }
+
+ let prePath = principal.URI.prePath;
+ if (prePath == "https://addons.palemoon.org") {
return false;
}
- let pm = Services.perms;
- return pm.testPermission(uri, "install") == pm.ALLOW_ACTION;
+ return true;
}
};
diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js
index 696a2871a..2380f5d21 100755
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -71,6 +71,10 @@ XPCOMUtils.defineLazyModuleGetter(this, "SafeBrowsing",
["gDNSService", "@mozilla.org/network/dns-service;1", "nsIDNSService"],
].forEach(([name, cc, ci]) => XPCOMUtils.defineLazyServiceGetter(this, name, cc, ci));
+XPCOMUtils.defineLazyServiceGetter(this, "gSerializationHelper",
+ "@mozilla.org/network/serialization-helper;1",
+ "nsISerializationHelper");
+
XPCOMUtils.defineLazyGetter(this, "BrowserToolboxProcess", function() {
let tmp = {};
Cu.import("resource://devtools/client/framework/ToolboxProcess.jsm", tmp);
@@ -807,6 +811,7 @@ function _loadURIWithFlags(browser, uri, params) {
if (!uri) {
uri = "about:blank";
}
+ let triggeringPrincipal = params.triggeringPrincipal || null;
let flags = params.flags || 0;
let referrer = params.referrerURI;
let referrerPolicy = ('referrerPolicy' in params ? params.referrerPolicy :
@@ -831,7 +836,7 @@ function _loadURIWithFlags(browser, uri, params) {
browser.webNavigation.loadURIWithOptions(uri, flags,
referrer, referrerPolicy,
- postData, null, null);
+ postData, null, null, triggeringPrincipal);
} else {
// Check if the current browser is allowed to unload.
let {permitUnload, timedOut} = browser.permitUnload();
@@ -845,6 +850,9 @@ function _loadURIWithFlags(browser, uri, params) {
let loadParams = {
uri: uri,
+ triggeringPrincipal: triggeringPrincipal
+ ? gSerializationHelper.serializeToString(triggeringPrincipal)
+ : null,
flags: flags,
referrer: referrer ? referrer.spec : null,
referrerPolicy: referrerPolicy,
@@ -872,7 +880,7 @@ function _loadURIWithFlags(browser, uri, params) {
}
browser.webNavigation.loadURIWithOptions(uri, flags, referrer, referrerPolicy,
- postData, null, null);
+ postData, null, null, triggeringPrincipal);
} else {
throw e;
}
@@ -1164,6 +1172,7 @@ var gBrowserInit = {
// [5]: referrerPolicy (int)
// [6]: userContextId (int)
// [7]: originPrincipal (nsIPrincipal)
+ // [8]: triggeringPrincipal (nsIPrincipal)
else if (window.arguments.length >= 3) {
let referrerURI = window.arguments[2];
if (typeof(referrerURI) == "string") {
@@ -1181,7 +1190,7 @@ var gBrowserInit = {
window.arguments[4] || false, referrerPolicy, userContextId,
// pass the origin principal (if any) and force its use to create
// an initial about:blank viewer if present:
- window.arguments[7], !!window.arguments[7]);
+ window.arguments[7], !!window.arguments[7], window.arguments[8]);
window.focus();
}
// Note: loadOneOrMoreURIs *must not* be called if window.arguments.length >= 3.
@@ -2067,7 +2076,8 @@ function BrowserTryToCloseWindow()
}
function loadURI(uri, referrer, postData, allowThirdPartyFixup, referrerPolicy,
- userContextId, originPrincipal, forceAboutBlankViewerInCurrent) {
+ userContextId, originPrincipal, forceAboutBlankViewerInCurrent,
+ triggeringPrincipal) {
try {
openLinkIn(uri, "current",
{ referrerURI: referrer,
@@ -2076,6 +2086,7 @@ function loadURI(uri, referrer, postData, allowThirdPartyFixup, referrerPolicy,
allowThirdPartyFixup: allowThirdPartyFixup,
userContextId: userContextId,
originPrincipal,
+ triggeringPrincipal,
forceAboutBlankViewerInCurrent,
});
} catch (e) {}
@@ -2779,24 +2790,6 @@ var BrowserOnClick = {
}
},
- handleEvent: function (event) {
- if (!event.isTrusted || // Don't trust synthetic events
- event.button == 2) {
- return;
- }
-
- let originalTarget = event.originalTarget;
- let ownerDoc = originalTarget.ownerDocument;
- if (!ownerDoc) {
- return;
- }
-
- if (gMultiProcessBrowser &&
- ownerDoc.documentURI.toLowerCase() == "about:newtab") {
- this.onE10sAboutNewTab(event, ownerDoc);
- }
- },
-
receiveMessage: function (msg) {
switch (msg.name) {
case "Browser:CertExceptionError":
@@ -2990,28 +2983,6 @@ var BrowserOnClick = {
}
},
- /**
- * This functions prevents navigation from happening directly through the <a>
- * link in about:newtab (which is loaded in the parent and therefore would load
- * the next page also in the parent) and instructs the browser to open the url
- * in the current tab which will make it update the remoteness of the tab.
- */
- onE10sAboutNewTab: function(event, ownerDoc) {
- let isTopFrame = (ownerDoc.defaultView.parent === ownerDoc.defaultView);
- if (!isTopFrame) {
- return;
- }
-
- let anchorTarget = event.originalTarget.parentNode;
-
- if (anchorTarget instanceof HTMLAnchorElement &&
- anchorTarget.classList.contains("newtab-link")) {
- event.preventDefault();
- let where = whereToOpenLink(event, false, false);
- openLinkIn(anchorTarget.href, where, { charset: ownerDoc.characterSet, referrerURI: ownerDoc.documentURIObject });
- }
- },
-
ignoreWarningButton: function (reason) {
// Allow users to override and continue through to the site,
// but add a notify bar as a reminder, so that they don't lose
@@ -4809,13 +4780,9 @@ var TabsProgressListener = {
}
}
- // Attach a listener to watch for "click" events bubbling up from error
- // pages and other similar pages (like about:newtab). This lets us fix bugs
- // like 401575 which require error page UI to do privileged things, without
- // letting error pages have any privilege themselves.
- // We can't look for this during onLocationChange since at that point the
- // document URI is not yet the about:-uri of the error page.
-
+ // We used to listen for clicks in the browser here, but when that
+ // became unnecessary, removing the code below caused focus issues.
+ // This code should be removed. Tracked in bug 1337794.
let isRemoteBrowser = aBrowser.isRemoteBrowser;
// We check isRemoteBrowser here to avoid requesting the doc CPOW
let doc = isRemoteBrowser ? null : aWebProgress.DOMWindow.document;
@@ -4830,11 +4797,9 @@ var TabsProgressListener = {
// STATE_STOP may be received twice for documents, thus store an
// attribute to ensure handling it just once.
doc.documentElement.setAttribute("hasBrowserHandlers", "true");
- aBrowser.addEventListener("click", BrowserOnClick, true);
aBrowser.addEventListener("pagehide", function onPageHide(event) {
if (event.target.defaultView.frameElement)
return;
- aBrowser.removeEventListener("click", BrowserOnClick, true);
aBrowser.removeEventListener("pagehide", onPageHide, true);
if (event.target.documentElement)
event.target.documentElement.removeAttribute("hasBrowserHandlers");
@@ -4883,7 +4848,7 @@ nsBrowserAccess.prototype = {
_openURIInNewTab: function(aURI, aReferrer, aReferrerPolicy, aIsPrivate,
aIsExternal, aForceNotRemote=false,
aUserContextId=Ci.nsIScriptSecurityManager.DEFAULT_USER_CONTEXT_ID,
- aOpener=null) {
+ aOpener = null, aTriggeringPrincipal = null) {
let win, needToFocusWin;
// try the current window. if we're in a popup, fall back on the most recent browser window
@@ -4908,6 +4873,7 @@ nsBrowserAccess.prototype = {
let loadInBackground = gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground");
let tab = win.gBrowser.loadOneTab(aURI ? aURI.spec : "about:blank", {
+ triggeringPrincipal: aTriggeringPrincipal,
referrerURI: aReferrer,
referrerPolicy: aReferrerPolicy,
userContextId: aUserContextId,
@@ -4956,9 +4922,11 @@ nsBrowserAccess.prototype = {
}
let referrer = aOpener ? makeURI(aOpener.location.href) : null;
+ let triggeringPrincipal = null;
let referrerPolicy = Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT;
if (aOpener && aOpener.document) {
referrerPolicy = aOpener.document.referrerPolicy;
+ triggeringPrincipal = aOpener.document.nodePrincipal;
}
let isPrivate = aOpener
? PrivateBrowsingUtils.isContentWindowPrivate(aOpener)
@@ -4992,7 +4960,7 @@ nsBrowserAccess.prototype = {
let browser = this._openURIInNewTab(aURI, referrer, referrerPolicy,
isPrivate, isExternal,
forceNotRemote, userContextId,
- openerWindow);
+ openerWindow, triggeringPrincipal);
if (browser)
newWindow = browser.contentWindow;
break;
@@ -5003,6 +4971,7 @@ nsBrowserAccess.prototype = {
Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL :
Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
gBrowser.loadURIWithFlags(aURI.spec, {
+ triggeringPrincipal,
flags: loadflags,
referrerURI: referrer,
referrerPolicy: referrerPolicy,
@@ -5031,7 +5000,8 @@ nsBrowserAccess.prototype = {
aParams.referrerPolicy,
aParams.isPrivate,
isExternal, false,
- userContextId);
+ userContextId, null,
+ aParams.triggeringPrincipal);
if (browser)
return browser.QueryInterface(Ci.nsIFrameLoaderOwner);
@@ -5584,6 +5554,7 @@ function handleLinkClick(event, href, linkNode) {
referrerPolicy: referrerPolicy,
noReferrer: BrowserUtils.linkHasNoReferrer(linkNode),
originPrincipal: doc.nodePrincipal,
+ triggeringPrincipal: doc.nodePrincipal,
};
// The new tab/window must use the same userContextId
diff --git a/browser/base/content/content.js b/browser/base/content/content.js
index 8d6f0745e..496e0d111 100644
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -482,6 +482,7 @@ var ClickEventHandler = {
ctrlKey: event.ctrlKey, metaKey: event.metaKey,
altKey: event.altKey, href: null, title: null,
bookmark: false, referrerPolicy: referrerPolicy,
+ triggeringPrincipal: principal,
originAttributes: principal ? principal.originAttributes : {},
isContentWindowPrivate: PrivateBrowsingUtils.isContentWindowPrivate(ownerDoc.defaultView)};
@@ -521,6 +522,7 @@ var ClickEventHandler = {
} catch (e) {}
}
json.originPrincipal = ownerDoc.nodePrincipal;
+ json.triggeringPrincipal = ownerDoc.nodePrincipal;
sendAsyncMessage("Content:Click", json);
return;
@@ -894,6 +896,7 @@ var LightWeightThemeWebInstallListener = {
case "InstallBrowserTheme": {
sendAsyncMessage("LightWeightThemeWebInstaller:Install", {
baseURI: event.target.baseURI,
+ principal: event.target.nodePrincipal,
themeData: event.target.getAttribute("data-browsertheme"),
});
break;
@@ -901,6 +904,7 @@ var LightWeightThemeWebInstallListener = {
case "PreviewBrowserTheme": {
sendAsyncMessage("LightWeightThemeWebInstaller:Preview", {
baseURI: event.target.baseURI,
+ principal: event.target.nodePrincipal,
themeData: event.target.getAttribute("data-browsertheme"),
});
this._previewWindow = event.target.ownerGlobal;
@@ -915,7 +919,7 @@ var LightWeightThemeWebInstallListener = {
case "ResetBrowserThemePreview": {
if (this._previewWindow) {
sendAsyncMessage("LightWeightThemeWebInstaller:ResetPreview",
- {baseURI: event.target.baseURI});
+ {principal: event.target.nodePrincipal});
this._resetPreviewWindow();
}
break;
diff --git a/browser/base/content/nsContextMenu.js b/browser/base/content/nsContextMenu.js
index ddf695202..955184f64 100644
--- a/browser/base/content/nsContextMenu.js
+++ b/browser/base/content/nsContextMenu.js
@@ -968,6 +968,7 @@ nsContextMenu.prototype = {
_openLinkInParameters : function (extra) {
let params = { charset: gContextMenuContentData.charSet,
originPrincipal: this.principal,
+ triggeringPrincipal: this.principal,
referrerURI: gContextMenuContentData.documentURIObject,
referrerPolicy: gContextMenuContentData.referrerPolicy,
noReferrer: this.linkHasNoReferrer };
@@ -1147,10 +1148,12 @@ nsContextMenu.prototype = {
// Change current window to the URL of the image, video, or audio.
viewMedia: function(e) {
let referrerURI = gContextMenuContentData.documentURIObject;
+ let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
if (this.onCanvas) {
this._canvasToBlobURL(this.target).then(function(blobURL) {
openUILink(blobURL, e, { disallowInheritPrincipal: true,
- referrerURI: referrerURI });
+ referrerURI: referrerURI,
+ triggeringPrincipal: systemPrincipal});
}, Cu.reportError);
}
else {
diff --git a/browser/base/content/tabbrowser.xml b/browser/base/content/tabbrowser.xml
index b27846835..463e74a52 100644
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -1513,6 +1513,7 @@
<parameter name="aAllowThirdPartyFixup"/>
<body>
<![CDATA[
+ var aTriggeringPrincipal;
var aReferrerPolicy;
var aFromExternal;
var aRelatedToCurrent;
@@ -1528,6 +1529,7 @@
typeof arguments[1] == "object" &&
!(arguments[1] instanceof Ci.nsIURI)) {
let params = arguments[1];
+ aTriggeringPrincipal = params.triggeringPrincipal
aReferrerURI = params.referrerURI;
aReferrerPolicy = params.referrerPolicy;
aCharset = params.charset;
@@ -1550,6 +1552,7 @@
Services.prefs.getBoolPref("browser.tabs.loadInBackground");
var owner = bgLoad ? null : this.selectedTab;
var tab = this.addTab(aURI, {
+ triggeringPrincipal: aTriggeringPrincipal,
referrerURI: aReferrerURI,
referrerPolicy: aReferrerPolicy,
charset: aCharset,
@@ -2120,6 +2123,7 @@
"use strict";
const NS_XUL = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
+ var aTriggeringPrincipal;
var aReferrerPolicy;
var aFromExternal;
var aRelatedToCurrent;
@@ -2136,6 +2140,7 @@
typeof arguments[1] == "object" &&
!(arguments[1] instanceof Ci.nsIURI)) {
let params = arguments[1];
+ aTriggeringPrincipal = params.triggeringPrincipal;
aReferrerURI = params.referrerURI;
aReferrerPolicy = params.referrerPolicy;
aCharset = params.charset;
@@ -2267,6 +2272,7 @@
try {
b.loadURIWithFlags(aURI, {
flags,
+ triggeringPrincipal: aTriggeringPrincipal,
referrerURI: aNoReferrer ? null: aReferrerURI,
referrerPolicy: aReferrerPolicy,
charset: aCharset,
diff --git a/browser/base/content/utilityOverlay.js b/browser/base/content/utilityOverlay.js
index 6ceaf773e..b041915a7 100644
--- a/browser/base/content/utilityOverlay.js
+++ b/browser/base/content/utilityOverlay.js
@@ -225,6 +225,7 @@ function openLinkIn(url, where, params) {
var aUserContextId = params.userContextId;
var aIndicateErrorPageLoad = params.indicateErrorPageLoad;
var aPrincipal = params.originPrincipal;
+ var aTriggeringPrincipal = params.triggeringPrincipal;
var aForceAboutBlankViewerInCurrent =
params.forceAboutBlankViewerInCurrent;
@@ -259,6 +260,24 @@ function openLinkIn(url, where, params) {
return;
}
+ // Teach the principal about the right OA to use, e.g. in case when
+ // opening a link in a new private window, or in a new container tab.
+ // Please note we do not have to do that for SystemPrincipals and we
+ // can not do it for NullPrincipals since NullPrincipals are only
+ // identical if they actually are the same object (See Bug: 1346759)
+ function useOAForPrincipal(principal) {
+ if (principal && principal.isCodebasePrincipal) {
+ let attrs = {
+ userContextId: aUserContextId,
+ privateBrowsingId: aIsPrivate || (w && PrivateBrowsingUtils.isWindowPrivate(w)),
+ };
+ return Services.scriptSecurityManager.createCodebasePrincipal(principal.URI, attrs);
+ }
+ return principal;
+ }
+ aPrincipal = useOAForPrincipal(aPrincipal);
+ aTriggeringPrincipal = useOAForPrincipal(aTriggeringPrincipal);
+
if (!w || where == "window") {
// Strip referrer data when opening a new private window, to prevent
// regular browsing data from leaking into it.
@@ -308,6 +327,7 @@ function openLinkIn(url, where, params) {
sa.appendElement(referrerPolicySupports, /* weak =*/ false);
sa.appendElement(userContextIdSupports, /* weak =*/ false);
sa.appendElement(aPrincipal, /* weak =*/ false);
+ sa.appendElement(aTriggeringPrincipal, /* weak =*/ false);
let features = "chrome,dialog=no,all";
if (aIsPrivate) {
@@ -394,6 +414,7 @@ function openLinkIn(url, where, params) {
}
aCurrentBrowser.loadURIWithFlags(url, {
+ triggeringPrincipal: aTriggeringPrincipal,
flags: flags,
referrerURI: aNoReferrer ? null : aReferrerURI,
referrerPolicy: aReferrerPolicy,
@@ -419,6 +440,7 @@ function openLinkIn(url, where, params) {
noReferrer: aNoReferrer,
userContextId: aUserContextId,
originPrincipal: aPrincipal,
+ triggeringPrincipal: aTriggeringPrincipal,
});
browserUsedForLoad = tabUsedForLoad.linkedBrowser;
break;
diff --git a/browser/branding/shared/uaoverrides.inc b/browser/branding/shared/uaoverrides.inc
index 59e413728..f7f7fafa3 100644
--- a/browser/branding/shared/uaoverrides.inc
+++ b/browser/branding/shared/uaoverrides.inc
@@ -19,8 +19,9 @@
#define OS_SLICE Windows NT 6.1; WOW64;
#endif
-// FxA override
+// Mozilla overrides
pref("@GUAO_PREF@.accounts.firefox.com", "Mozilla/5.0 (@OS_SLICE@ rv:@GK_VERSION@) @GK_SLICE@ @FX_SLICE@");
+pref("@GUAO_PREF@.addons.mozilla.org", "Mozilla/5.0 (@OS_SLICE@ rv:@GK_VERSION@) @GK_SLICE@ @FX_SLICE@");
// Required for domains that have proven unresponsive to requests from users
diff --git a/browser/branding/unofficial/serpent.VisualElementsManifest.xml b/browser/branding/unofficial/basilisk.VisualElementsManifest.xml
index 5046ee7da..5046ee7da 100644
--- a/browser/branding/unofficial/serpent.VisualElementsManifest.xml
+++ b/browser/branding/unofficial/basilisk.VisualElementsManifest.xml
diff --git a/browser/components/feeds/FeedConverter.js b/browser/components/feeds/FeedConverter.js
index aa70620d4..c2c565608 100644
--- a/browser/components/feeds/FeedConverter.js
+++ b/browser/components/feeds/FeedConverter.js
@@ -264,7 +264,7 @@ FeedConverter.prototype = {
}
chromeChannel.loadGroup = this._request.loadGroup;
- chromeChannel.asyncOpen(this._listener, null);
+ chromeChannel.asyncOpen2(this._listener);
}
finally {
this._releaseHandles();
diff --git a/browser/components/preferences/fonts.xul b/browser/components/preferences/fonts.xul
index ed1d1ecc2..26b1c6547 100644
--- a/browser/components/preferences/fonts.xul
+++ b/browser/components/preferences/fonts.xul
@@ -255,7 +255,8 @@
control="DefaultCharsetList"/>
<menulist id="DefaultCharsetList" preference="intl.charset.fallback.override">
<menupopup>
- <menuitem label="&languages.customize.Fallback.auto;" value=""/>
+ <menuitem label="&languages.customize.Fallback.auto;" value="*"/>
+ <menuitem label="&languages.customize.Fallback.utf8;" value="UTF-8"/>
<menuitem label="&languages.customize.Fallback.arabic;" value="windows-1256"/>
<menuitem label="&languages.customize.Fallback.baltic;" value="windows-1257"/>
<menuitem label="&languages.customize.Fallback.ceiso;" value="ISO-8859-2"/>
diff --git a/browser/components/sessionstore/ContentRestore.jsm b/browser/components/sessionstore/ContentRestore.jsm
index 976016770..d4972bcaf 100644
--- a/browser/components/sessionstore/ContentRestore.jsm
+++ b/browser/components/sessionstore/ContentRestore.jsm
@@ -204,6 +204,9 @@ ContentRestoreInternal.prototype = {
: Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT);
let postData = loadArguments.postData ?
Utils.makeInputStream(loadArguments.postData) : null;
+ let triggeringPrincipal = loadArguments.triggeringPrincipal
+ ? Utils.deserializePrincipal(loadArguments.triggeringPrincipal)
+ : null;
if (loadArguments.userContextId) {
webNavigation.setOriginAttributesBeforeLoading({ userContextId: loadArguments.userContextId });
@@ -211,7 +214,7 @@ ContentRestoreInternal.prototype = {
webNavigation.loadURIWithOptions(loadArguments.uri, loadArguments.flags,
referrer, referrerPolicy, postData,
- null, null);
+ null, null, triggeringPrincipal);
} else if (tabData.userTypedValue && tabData.userTypedClear) {
// If the user typed a URL into the URL bar and hit enter right before
// we crashed, we want to start loading that page again. A non-zero
diff --git a/browser/components/sessionstore/SessionHistory.jsm b/browser/components/sessionstore/SessionHistory.jsm
index aa9c10379..3d28d87db 100644
--- a/browser/components/sessionstore/SessionHistory.jsm
+++ b/browser/components/sessionstore/SessionHistory.jsm
@@ -95,7 +95,10 @@ var SessionHistoryInternal = {
// record it. For about:blank we explicitly want an empty array without
// an 'index' property to denote that there are no history entries.
if (uri != "about:blank" || (body && body.hasChildNodes())) {
- data.entries.push({ url: uri });
+ data.entries.push({
+ url: uri,
+ triggeringPrincipal_base64: Utils.SERIALIZED_SYSTEMPRINCIPAL
+ });
data.index = 1;
}
}
diff --git a/browser/components/sessionstore/SessionMigration.jsm b/browser/components/sessionstore/SessionMigration.jsm
index ff339eba9..1aa22f1a9 100644
--- a/browser/components/sessionstore/SessionMigration.jsm
+++ b/browser/components/sessionstore/SessionMigration.jsm
@@ -11,6 +11,9 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
Cu.import("resource://gre/modules/Task.jsm", this);
Cu.import("resource://gre/modules/osfile.jsm", this);
+XPCOMUtils.defineLazyModuleGetter(this, "Utils",
+ "resource://gre/modules/sessionstore/Utils.jsm");
+
// An encoder to UTF-8.
XPCOMUtils.defineLazyGetter(this, "gEncoder", function () {
return new TextEncoder();
@@ -27,7 +30,7 @@ var SessionMigrationInternal = {
* only contain:
* - open windows
* - with tabs
- * - with history entries with only title, url
+ * - with history entries with only title, url, triggeringPrincipal
* - with pinned state
* - with tab group info (hidden + group id)
* - with selected tab info
@@ -45,9 +48,11 @@ var SessionMigrationInternal = {
var win = {extData: {}};
win.tabs = oldWin.tabs.map(function(oldTab) {
var tab = {};
- // Keep only titles and urls for history entries
+ // Keep only titles, urls and triggeringPrincipals for history entries
tab.entries = oldTab.entries.map(function(entry) {
- return {url: entry.url, title: entry.title};
+ return { url: entry.url,
+ triggeringPrincipal_base64: entry.triggeringPrincipal_base64,
+ title: entry.title };
});
tab.index = oldTab.index;
tab.hidden = oldTab.hidden;
@@ -60,7 +65,8 @@ var SessionMigrationInternal = {
});
let url = "about:welcomeback";
let formdata = {id: {sessionData: state}, url};
- return {windows: [{tabs: [{entries: [{url}], formdata}]}]};
+ let entry = { url, triggeringPrincipal_base64: Utils.SERIALIZED_SYSTEMPRINCIPAL };
+ return { windows: [{ tabs: [{ entries: [ entry ], formdata}]}]};
},
/**
* Asynchronously read session restore state (JSON) from a path
diff --git a/browser/components/sessionstore/SessionStore.jsm b/browser/components/sessionstore/SessionStore.jsm
index 93e21357f..6b30943f3 100644
--- a/browser/components/sessionstore/SessionStore.jsm
+++ b/browser/components/sessionstore/SessionStore.jsm
@@ -603,12 +603,14 @@ var SessionStoreInternal = {
// replace the crashed session with a restore-page-only session
let url = "about:sessionrestore";
let formdata = {id: {sessionData: state}, url};
- state = { windows: [{ tabs: [{ entries: [{url}], formdata }] }] };
+ let entry = {url, triggeringPrincipal_base64: Utils.SERIALIZED_SYSTEMPRINCIPAL };
+ state = { windows: [{ tabs: [{ entries: [entry], formdata }] }] };
} else if (this._hasSingleTabWithURL(state.windows,
"about:welcomeback")) {
// On a single about:welcomeback URL that crashed, replace about:welcomeback
// with about:sessionrestore, to make clear to the user that we crashed.
state.windows[0].tabs[0].entries[0].url = "about:sessionrestore";
+ state.windows[0].tabs[0].entries[0].triggeringPrincipal_base64 = Utils.SERIALIZED_SYSTEMPRINCIPAL;
}
}
diff --git a/browser/installer/package-manifest.in b/browser/installer/package-manifest.in
index 5540feed9..4ef8942b5 100644
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -2,7 +2,7 @@
; License, v. 2.0. If a copy of the MPL was not distributed with this
; file, You can obtain one at http://mozilla.org/MPL/2.0/.
-; Package file for the Firefox build.
+; Package file for the Basilisk build.
;
; Packaging manifest is used to copy files from dist/bin
; to the staging directory.
@@ -260,9 +260,6 @@
@RESPATH@/browser/components/migration.xpt
@RESPATH@/components/mimetype.xpt
@RESPATH@/components/mozfind.xpt
-#ifdef ENABLE_INTL_API
-@RESPATH@/components/mozintl.xpt
-#endif
@RESPATH@/components/necko_about.xpt
@RESPATH@/components/necko_cache.xpt
@RESPATH@/components/necko_cache2.xpt
@@ -740,21 +737,6 @@
@RESPATH@/components/pipnss.xpt
@RESPATH@/components/pippki.xpt
-; For process sandboxing
-#if defined(MOZ_SANDBOX)
-#if defined(XP_WIN)
-#if defined(WOW_HELPER)
-@BINPATH@/wow_helper.exe
-#endif
-#endif
-#endif
-
-#if defined(MOZ_SANDBOX)
-#if defined(XP_LINUX)
-@BINPATH@/@DLL_PREFIX@mozsandbox@DLL_SUFFIX@
-#endif
-#endif
-
; for Solaris SPARC
#ifdef SOLARIS
bin/libfreebl_32fpu_3.so
diff --git a/browser/locales/en-US/chrome/browser/browser.properties b/browser/locales/en-US/chrome/browser/browser.properties
index 31f61632b..f7f3e9339 100644
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -85,12 +85,14 @@ addonInstallError-2=The add-on could not be installed because it does not match
addonInstallError-3=The add-on downloaded from this site could not be installed because it appears to be corrupt.
addonInstallError-4=%2$S could not be installed because %1$S cannot modify the needed file.
addonInstallError-5=%1$S has prevented this site from installing an unverified add-on.
+addonInstallError-8=%2$S could not be installed because %1$S does not support Jetpack (SDK) extensions.
addonInstallError-9=%2$S could not be installed because %1$S does not support WebExtensions.
addonLocalInstallError-1=This add-on could not be installed because of a filesystem error.
addonLocalInstallError-2=This add-on could not be installed because it does not match the add-on %1$S expected.
addonLocalInstallError-3=This add-on could not be installed because it appears to be corrupt.
addonLocalInstallError-4=%2$S could not be installed because %1$S cannot modify the needed file.
addonLocalInstallError-5=This add-on could not be installed because it has not been verified.
+addonLocalInstallError-8=%2$S could not be installed because %1$S does not support Jetpack (SDK) extensions.
addonLocalInstallError-9=%2$S could not be installed because %1$S does not support WebExtensions.
diff --git a/browser/locales/en-US/chrome/browser/preferences/fonts.dtd b/browser/locales/en-US/chrome/browser/preferences/fonts.dtd
index 98d697d35..d55bcde8b 100644
--- a/browser/locales/en-US/chrome/browser/preferences/fonts.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/fonts.dtd
@@ -70,6 +70,7 @@
<!ENTITY languages.customize.Fallback2.desc "This text encoding is used for legacy content that fails to declare its encoding.">
<!ENTITY languages.customize.Fallback.auto "Default for Current Locale">
+<!ENTITY languages.customize.Fallback.utf8 "UTF-8">
<!-- LOCALIZATION NOTE (languages.customize.Fallback.arabic):
Translate "Arabic" as an adjective for an encoding, not as the name of the language. -->
<!ENTITY languages.customize.Fallback.arabic "Arabic">
diff --git a/browser/modules/ContentClick.jsm b/browser/modules/ContentClick.jsm
index 8abc32525..40101d5d3 100644
--- a/browser/modules/ContentClick.jsm
+++ b/browser/modules/ContentClick.jsm
@@ -85,6 +85,7 @@ var ContentClick = {
allowMixedContent: json.allowMixedContent,
isContentWindowPrivate: json.isContentWindowPrivate,
originPrincipal: json.originPrincipal,
+ triggeringPrincipal: json.triggeringPrincipal,
};
// The new tab/window must use the same userContextId.
diff --git a/browser/themes/osx/shared.inc b/browser/themes/osx/shared.inc
index 3076450e2..b3ea4e199 100644
--- a/browser/themes/osx/shared.inc
+++ b/browser/themes/osx/shared.inc
@@ -1,4 +1,4 @@
-%include ../../../../toolkit/themes/osx/global/shared.inc
+%include ../../../toolkit/themes/osx/global/shared.inc
%include ../shared/browser.inc
%filter substitution
diff --git a/browser/themes/shared/tabs.inc.css b/browser/themes/shared/tabs.inc.css
index 632a6e606..c505416e4 100644
--- a/browser/themes/shared/tabs.inc.css
+++ b/browser/themes/shared/tabs.inc.css
@@ -55,8 +55,9 @@
.tab-background-middle {
-moz-box-flex: 1;
background-clip: padding-box;
- border-left: @tabCurveHalfWidth@ solid transparent;
- border-right: @tabCurveHalfWidth@ solid transparent;
+ /* Deliberately create a 1px overlap left/right to cover rounding gaps */
+ border-left: calc(@tabCurveHalfWidth@ - 1px) solid transparent;
+ border-right: calc(@tabCurveHalfWidth@ - 1px) solid transparent;
margin: 0 -@tabCurveHalfWidth@;
}
diff --git a/build/application.ini b/build/application.ini
index 8f65421ed..80cad7e9b 100644
--- a/build/application.ini
+++ b/build/application.ini
@@ -1,62 +1,6 @@
-#if MOZ_APP_STATIC_INI
-#ifdef MOZ_BUILD_APP_IS_BROWSER
-; This file is not used. If you modify it and want the application to use
-; your modifications, move it under the browser/ subdirectory and start with
-; the "-app /path/to/browser/application.ini" argument.
-#else
-; This file is not used. If you modify it and want the application to use
-; your modifications, start with the "-app /path/to/application.ini"
-; argument.
-#endif
-#endif
-#if 0
-; This Source Code Form is subject to the terms of the Mozilla Public
-; License, v. 2.0. If a copy of the MPL was not distributed with this
-; file, You can obtain one at http://mozilla.org/MPL/2.0/.
-#endif
+# Global application.ini template is not conducive to a codebase that
+# is used for multiple applications especially if they have multiple
+# branding OR spaces in their Vendor or Name so include one from the
+# application source directory instead.
#filter substitution
-#include @TOPOBJDIR@/buildid.h
-#include @TOPOBJDIR@/source-repo.h
-[App]
-#ifdef MC_OFFICIAL
-#if defined(MC_PALEMOON) || defined(MC_BASILISK)
-Vendor=Moonchild Productions
-#elif defined(BINOC_BOREALIS)
-Vendor=Binary Outcast
-#else
-Vendor=@MOZ_APP_VENDOR@
-#endif
-#else
-Vendor=@MOZ_APP_VENDOR@
-#endif
-#ifdef MC_PALEMOON
-Name=Pale Moon
-#else
-Name=@MOZ_APP_BASENAME@
-#endif
-RemotingName=@MOZ_APP_REMOTINGNAME@
-#ifdef MOZ_APP_DISPLAYNAME
-CodeName=@MOZ_APP_DISPLAYNAME@
-#endif
-Version=@MOZ_APP_VERSION@
-#ifdef MOZ_APP_PROFILE
-Profile=@MOZ_APP_PROFILE@
-#endif
-BuildID=@MOZ_BUILDID@
-#ifdef MOZ_SOURCE_REPO
-SourceRepository=@MOZ_SOURCE_REPO@
-#endif
-#ifdef MOZ_SOURCE_STAMP
-SourceStamp=@MOZ_SOURCE_STAMP@
-#endif
-ID=@MOZ_APP_ID@
-
-[Gecko]
-MinVersion=@GRE_MILESTONE@
-MaxVersion=@GRE_MILESTONE@
-
-[XRE]
-#ifdef MOZ_PROFILE_MIGRATOR
-EnableProfileMigrator=1
-#endif
-
+#include @TOPSRCDIR@/@MOZ_BUILD_APP@/app/application.ini
diff --git a/build/autoconf/icu.m4 b/build/autoconf/icu.m4
index 794ddcdf4..89c53c52c 100644
--- a/build/autoconf/icu.m4
+++ b/build/autoconf/icu.m4
@@ -22,42 +22,8 @@ fi
AC_SUBST(MOZ_SYSTEM_ICU)
-MOZ_ARG_WITH_STRING(intl-api,
-[ --with-intl-api, --with-intl-api=build, --without-intl-api
- Determine the status of the ECMAScript Internationalization API. The first
- (or lack of any of these) builds and exposes the API. The second builds it
- but doesn't use ICU or expose the API to script. The third doesn't build
- ICU at all.],
- _INTL_API=$withval)
-
-ENABLE_INTL_API=
-EXPOSE_INTL_API=
-case "$_INTL_API" in
-no)
- ;;
-build)
- ENABLE_INTL_API=1
- ;;
-yes)
- ENABLE_INTL_API=1
- EXPOSE_INTL_API=1
- ;;
-*)
- AC_MSG_ERROR([Invalid value passed to --with-intl-api: $_INTL_API])
- ;;
-esac
-
-if test -n "$ENABLE_INTL_API"; then
- USE_ICU=1
-fi
-
-if test -n "$EXPOSE_INTL_API"; then
- AC_DEFINE(EXPOSE_INTL_API)
-fi
-
-if test -n "$ENABLE_INTL_API"; then
- AC_DEFINE(ENABLE_INTL_API)
-fi
+dnl We always use ICU.
+USE_ICU=1
dnl Settings for the implementation of the ECMAScript Internationalization API
if test -n "$USE_ICU"; then
diff --git a/build/autoconf/jemalloc.m4 b/build/autoconf/jemalloc.m4
deleted file mode 100644
index 3b9c603f7..000000000
--- a/build/autoconf/jemalloc.m4
+++ /dev/null
@@ -1,114 +0,0 @@
-dnl This Source Code Form is subject to the terms of the Mozilla Public
-dnl License, v. 2.0. If a copy of the MPL was not distributed with this
-dnl file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-AC_DEFUN([MOZ_SUBCONFIGURE_JEMALLOC], [
-
-if test "$MOZ_BUILD_APP" != js -o -n "$JS_STANDALONE"; then
-
- # Run jemalloc configure script
-
- if test -z "$MOZ_SYSTEM_JEMALLOC" -a "$MOZ_MEMORY" && test -n "$MOZ_JEMALLOC4" -o -n "$MOZ_REPLACE_MALLOC"; then
- ac_configure_args="--build=$build --host=$target --enable-stats --with-jemalloc-prefix=je_ --disable-valgrind"
- # We're using memalign for _aligned_malloc in memory/build/mozmemory_wrap.c
- # on Windows, so just export memalign on all platforms.
- ac_configure_args="$ac_configure_args ac_cv_func_memalign=yes"
- if test -n "$MOZ_REPLACE_MALLOC"; then
- # When using replace_malloc, we always want valloc exported from jemalloc.
- ac_configure_args="$ac_configure_args ac_cv_func_valloc=yes"
- if test "${OS_ARCH}" = Darwin; then
- # We also need to enable pointer validation on Mac because jemalloc's
- # zone allocator is not used.
- ac_configure_args="$ac_configure_args --enable-ivsalloc"
- fi
- fi
- if test -n "$MOZ_JEMALLOC4"; then
- case "${OS_ARCH}" in
- WINNT|Darwin)
- # We want jemalloc functions to be kept hidden on both Mac and Windows
- # See memory/build/mozmemory_wrap.h for details.
- ac_configure_args="$ac_configure_args --without-export"
- ;;
- esac
- if test "${OS_ARCH}" = WINNT; then
- # Lazy lock initialization doesn't play well with lazy linking of
- # mozglue.dll on Windows XP (leads to startup crash), so disable it.
- ac_configure_args="$ac_configure_args --disable-lazy-lock"
-
- # 64-bit Windows builds require a minimum 16-byte alignment.
- if test -n "$HAVE_64BIT_BUILD"; then
- ac_configure_args="$ac_configure_args --with-lg-tiny-min=4"
- fi
- fi
- elif test "${OS_ARCH}" = Darwin; then
- # When building as a replace-malloc lib, disabling the zone allocator
- # forces to use pthread_atfork.
- ac_configure_args="$ac_configure_args --disable-zone-allocator"
- fi
- _MANGLE="malloc posix_memalign aligned_alloc calloc realloc free memalign valloc malloc_usable_size"
- JEMALLOC_WRAPPER=
- if test -z "$MOZ_REPLACE_MALLOC"; then
- case "$OS_ARCH" in
- Linux|DragonFly|FreeBSD|NetBSD|OpenBSD)
- MANGLE=$_MANGLE
- ;;
- esac
- elif test -z "$MOZ_JEMALLOC4"; then
- MANGLE=$_MANGLE
- JEMALLOC_WRAPPER=replace_
- fi
- if test -n "$MANGLE"; then
- MANGLED=
- for mangle in ${MANGLE}; do
- if test -n "$MANGLED"; then
- MANGLED="$mangle:$JEMALLOC_WRAPPER$mangle,$MANGLED"
- else
- MANGLED="$mangle:$JEMALLOC_WRAPPER$mangle"
- fi
- done
- ac_configure_args="$ac_configure_args --with-mangling=$MANGLED"
- fi
- unset CONFIG_FILES
- if test -z "$MOZ_TLS"; then
- ac_configure_args="$ac_configure_args --disable-tls"
- fi
- EXTRA_CFLAGS="$CFLAGS"
- for var in AS CC CXX CPP LD AR RANLIB STRIP CPPFLAGS EXTRA_CFLAGS LDFLAGS; do
- ac_configure_args="$ac_configure_args $var='`eval echo \\${${var}}`'"
- done
-
- # jemalloc's configure assumes that if you have CFLAGS set at all, you set
- # all the flags necessary to configure jemalloc, which is not likely to be
- # the case on Windows if someone is building Firefox with flags set in
- # their mozconfig.
- if test "$_MSC_VER"; then
- ac_configure_args="$ac_configure_args CFLAGS="
- fi
-
- # Force disable DSS support in jemalloc.
- ac_configure_args="$ac_configure_args ac_cv_func_sbrk=false"
-
- # Make Linux builds munmap freed chunks instead of recycling them.
- ac_configure_args="$ac_configure_args --enable-munmap"
-
- # Disable cache oblivious behavior that appears to have a performance
- # impact on Firefox.
- ac_configure_args="$ac_configure_args --disable-cache-oblivious"
-
- if ! test -e memory/jemalloc; then
- mkdir -p memory/jemalloc
- fi
-
- # jemalloc's configure runs git to determine the version. But when building
- # from a gecko git clone, the git commands it uses is going to pick gecko's
- # information, not jemalloc's, which is useless. So pretend we don't have git
- # at all. That will make jemalloc's configure pick the in-tree VERSION file.
- (PATH="$srcdir/memory/jemalloc/helper:$PATH";
- AC_OUTPUT_SUBDIRS(memory/jemalloc/src)
- ) || exit 1
- ac_configure_args="$_SUBDIR_CONFIG_ARGS"
- fi
-
-fi
-
-])
diff --git a/build/directive4.py b/build/directive4.py
index dd8c111cf..28d84973e 100644
--- a/build/directive4.py
+++ b/build/directive4.py
@@ -33,7 +33,6 @@ if ('MOZ_OFFICIAL_BRANDING' in listConfig) or (strBrandingDirectory.endswith("br
# Applies to Pale Moon and Basilisk
if ('MC_BASILISK' in listConfig) or ('MC_PALEMOON' in listConfig):
listViolations += [
- 'MOZ_SANDBOX',
'MOZ_SYSTEM_LIBEVENT',
'MOZ_SYSTEM_NSS',
'MOZ_SYSTEM_NSPR',
diff --git a/build/gyp.mozbuild b/build/gyp.mozbuild
index ff04f6aac..10c3af95d 100644
--- a/build/gyp.mozbuild
+++ b/build/gyp.mozbuild
@@ -79,22 +79,15 @@ if os == 'WINNT':
MSVS_OS_BITS=64 if CONFIG['HAVE_64BIT_BUILD'] else 32,
)
elif os == 'Android':
- if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- gyp_vars['build_with_gonk'] = 1
- gyp_vars['moz_widget_toolkit_gonk'] = 1
- gyp_vars['opus_complexity'] = 1
- if int(CONFIG['ANDROID_VERSION']) >= 18:
- gyp_vars['moz_webrtc_omx'] = 1
- else:
- gyp_vars.update(
- gtest_target_type='executable',
- moz_webrtc_mediacodec=1,
- android_toolchain=CONFIG.get('ANDROID_TOOLCHAIN', ''),
- )
+ gyp_vars.update(
+ gtest_target_type='executable',
+ moz_webrtc_mediacodec=1,
+ android_toolchain=CONFIG.get('ANDROID_TOOLCHAIN', ''),
+ )
flavors = {
'WINNT': 'win',
- 'Android': 'linux' if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' else 'android',
+ 'Android': 'android',
'Linux': 'linux',
'Darwin': 'mac' if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa' else 'ios',
'SunOS': 'solaris',
diff --git a/build/moz.build b/build/moz.build
index d96724cad..616a64c3f 100644
--- a/build/moz.build
+++ b/build/moz.build
@@ -18,9 +18,15 @@ else:
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
DIRS += ['annotationProcessors']
-for var in ('GRE_MILESTONE', 'MOZ_APP_VERSION', 'MOZ_APP_BASENAME',
- 'MOZ_APP_VENDOR', 'MOZ_APP_ID', 'MAR_CHANNEL_ID',
- 'ACCEPTED_MAR_CHANNEL_IDS', 'MOZ_APP_REMOTINGNAME'):
+for var in ('GRE_MILESTONE',
+ 'MOZ_APP_VERSION',
+ 'MOZ_APP_BASENAME',
+ 'MOZ_APP_VENDOR',
+ 'MOZ_APP_ID',
+ 'MAR_CHANNEL_ID',
+ 'ACCEPTED_MAR_CHANNEL_IDS',
+ 'MOZ_APP_REMOTINGNAME',
+ 'MOZ_BUILD_APP'):
DEFINES[var] = CONFIG[var]
if CONFIG['MOZ_APP_DISPLAYNAME'] != CONFIG['MOZ_APP_BASENAME']:
@@ -33,15 +39,6 @@ if CONFIG['MOZ_PHOENIX']:
if CONFIG['MC_OFFICIAL']:
DEFINES['MC_OFFICIAL'] = CONFIG['MC_OFFICIAL']
-if CONFIG['MC_BASILISK']:
- DEFINES['MC_BASILISK'] = CONFIG['MC_BASILISK']
-
-if CONFIG['MC_PALEMOON']:
- DEFINES['MC_PALEMOON'] = CONFIG['MC_PALEMOON']
-
-if CONFIG['BINOC_BOREALIS']:
- DEFINES['BINOC_BOREALIS'] = CONFIG['BINOC_BOREALIS']
-
if CONFIG['MOZ_APP_PROFILE']:
DEFINES['MOZ_APP_PROFILE'] = CONFIG['MOZ_APP_PROFILE']
@@ -86,6 +83,7 @@ if CONFIG['MOZ_APP_BASENAME']:
appini.script = 'appini_header.py'
appini.inputs = ['!/dist/bin/application.ini']
+DEFINES['TOPSRCDIR'] = TOPSRCDIR
DEFINES['TOPOBJDIR'] = TOPOBJDIR
# NOTE: Keep .gdbinit in the topsrcdir for people who run gdb from the topsrcdir.
diff --git a/build/moz.configure/memory.configure b/build/moz.configure/memory.configure
index 3beed2fb2..398413b62 100644
--- a/build/moz.configure/memory.configure
+++ b/build/moz.configure/memory.configure
@@ -5,12 +5,13 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-option(env='MOZ_JEMALLOC4', help='Enable jemalloc 4')
-imply_option('--enable-jemalloc', depends_if('MOZ_JEMALLOC4')(lambda x: '4'))
+@deprecated_option(env='MOZ_JEMALLOC4')
+def moz_jemalloc4(value):
+ die('MOZ_JEMALLOC4 is no longer supported')
-option('--enable-jemalloc', nargs='?', choices=('4', 'moz'), env='MOZ_MEMORY',
- help='Replace memory allocator with jemalloc')
+option('--enable-jemalloc', env='MOZ_MEMORY',
+ help='Replace system memory allocator with jemalloc')
@depends('--enable-jemalloc', target, build_project, c_compiler)
def jemalloc(value, target, build_project, c_compiler):
@@ -30,36 +31,25 @@ def jemalloc(value, target, build_project, c_compiler):
if target.kernel == 'Linux':
return True
-@depends('--enable-jemalloc')
-def jemalloc4(jemalloc):
- if len(jemalloc) and jemalloc[0] == '4':
- return True
-
set_config('MOZ_MEMORY', jemalloc)
set_define('MOZ_MEMORY', jemalloc)
add_old_configure_assignment('MOZ_MEMORY', jemalloc)
-set_config('MOZ_JEMALLOC4', jemalloc4)
-set_define('MOZ_JEMALLOC4', jemalloc4)
-add_old_configure_assignment('MOZ_JEMALLOC4', jemalloc4)
-
# Because --enable-jemalloc doesn't use a default because of the dependency
# on the target, we can't use a js_option for it to propagate to js/src
# through the old-configure.
-@depends(jemalloc, jemalloc4)
-def jemalloc_for_old_configure(jemalloc, jemalloc4):
- if jemalloc:
- return '--enable-jemalloc=4' if jemalloc4 else '--enable-jemalloc'
- return '--disable-jemalloc'
+@depends(jemalloc)
+def jemalloc_for_old_configure(jemalloc):
+ return '--%s-jemalloc' % ('enable' if jemalloc else 'disable')
add_old_configure_arg(jemalloc_for_old_configure)
-@depends(jemalloc, jemalloc4, target)
-def jemalloc_os_define(jemalloc, jemalloc4, target):
- if jemalloc and not jemalloc4:
+@depends(jemalloc, target)
+def jemalloc_os_define(jemalloc, target):
+ if jemalloc:
if target.kernel == 'WINNT':
return 'MOZ_MEMORY_WINDOWS'
if target.kernel == 'Linux':
@@ -72,9 +62,9 @@ def jemalloc_os_define(jemalloc, jemalloc4, target):
set_define(jemalloc_os_define, '1')
-@depends(jemalloc, jemalloc4, target)
-def jemalloc_os_define_android(jemalloc, jemalloc4, target):
- if jemalloc and not jemalloc4 and target.os == 'Android':
+@depends(jemalloc, target)
+def jemalloc_os_define_android(jemalloc, target):
+ if jemalloc and target.os == 'Android':
return 'MOZ_MEMORY_ANDROID'
set_define(jemalloc_os_define_android, '1')
diff --git a/build/moz.configure/old.configure b/build/moz.configure/old.configure
index ffdea81b0..c1ad71d5f 100644
--- a/build/moz.configure/old.configure
+++ b/build/moz.configure/old.configure
@@ -235,6 +235,7 @@ def old_configure_options(*options):
'--enable-system-pixman',
'--enable-system-sqlite',
'--enable-tasktracer',
+ '--enable-tests',
'--enable-thread-sanitizer',
'--enable-trace-logging',
'--enable-ui-locale',
@@ -269,7 +270,6 @@ def old_configure_options(*options):
'--with-doc-output-dir',
'--with-float-abi',
'--with-fpu',
- '--with-intl-api',
'--with-ios-sdk',
'--with-jitreport-granularity',
'--with-macbundlename-prefix',
diff --git a/chrome/nsChromeRegistry.cpp b/chrome/nsChromeRegistry.cpp
index 0302b9997..485ca002c 100644
--- a/chrome/nsChromeRegistry.cpp
+++ b/chrome/nsChromeRegistry.cpp
@@ -32,9 +32,7 @@
#include "mozilla/StyleSheet.h"
#include "mozilla/StyleSheetInlines.h"
-#ifdef ENABLE_INTL_API
#include "unicode/uloc.h"
-#endif
nsChromeRegistry* nsChromeRegistry::gChromeRegistry;
@@ -720,7 +718,6 @@ nsChromeRegistry::GetSingleton()
void
nsChromeRegistry::SanitizeForBCP47(nsACString& aLocale)
{
-#ifdef ENABLE_INTL_API
// Currently, the only locale code we use that's not BCP47-conformant is
// "ja-JP-mac" on OS X, but let's try to be more general than just
// hard-coding that here.
@@ -735,13 +732,4 @@ nsChromeRegistry::SanitizeForBCP47(nsACString& aLocale)
if (U_SUCCESS(err) && len > 0) {
aLocale.Assign(langTag, len);
}
-#else
- // This is only really needed for Intl API purposes, AFAIK,
- // so probably won't be used in a non-ENABLE_INTL_API build.
- // But let's fix up the single anomalous code we actually ship,
- // just in case:
- if (aLocale.EqualsLiteral("ja-JP-mac")) {
- aLocale.AssignLiteral("ja-JP");
- }
-#endif
}
diff --git a/config/system-headers b/config/system-headers
index be3162f58..683c9d337 100644
--- a/config/system-headers
+++ b/config/system-headers
@@ -391,9 +391,6 @@ DiskInit.h
dlfcn.h
dlgs.h
dl.h
-#ifdef MOZ_WIDGET_GONK
-dns_sd.h
-#endif
docobj.h
dos/dosextens.h
dos.h
diff --git a/devtools/client/inspector/markup/test/browser.ini b/devtools/client/inspector/markup/test/browser.ini
index 3116e4beb..9ff73a6c6 100644
--- a/devtools/client/inspector/markup/test/browser.ini
+++ b/devtools/client/inspector/markup/test/browser.ini
@@ -32,6 +32,8 @@ support-files =
doc_markup_void_elements.xhtml
doc_markup_whitespace.html
doc_markup_xul.xul
+ doc_markup_update-on-navigtion_1.html
+ doc_markup_update-on-navigtion_2.html
head.js
helper_attributes_test_runner.js
helper_events_test_runner.js
diff --git a/devtools/client/inspector/markup/test/browser_markup_update-on-navigtion.js b/devtools/client/inspector/markup/test/browser_markup_update-on-navigtion.js
index 241cea672..c298878c3 100644
--- a/devtools/client/inspector/markup/test/browser_markup_update-on-navigtion.js
+++ b/devtools/client/inspector/markup/test/browser_markup_update-on-navigtion.js
@@ -5,9 +5,8 @@
// Test that markup view handles page navigation correctly.
-const SCHEMA = "data:text/html;charset=UTF-8,";
-const URL_1 = SCHEMA + "<div id='one' style='color:red;'>ONE</div>";
-const URL_2 = SCHEMA + "<div id='two' style='color:green;'>TWO</div>";
+const URL_1 = URL_ROOT + "doc_markup_update-on-navigtion_1.html";
+const URL_2 = URL_ROOT + "doc_markup_update-on-navigtion_2.html";
add_task(function* () {
let {inspector, testActor} = yield openInspectorForURL(URL_1);
diff --git a/devtools/client/inspector/markup/test/doc_markup_update-on-navigtion_1.html b/devtools/client/inspector/markup/test/doc_markup_update-on-navigtion_1.html
new file mode 100644
index 000000000..d2fdb1629
--- /dev/null
+++ b/devtools/client/inspector/markup/test/doc_markup_update-on-navigtion_1.html
@@ -0,0 +1 @@
+<div id='one' style='color:red;'>ONE</div>
diff --git a/devtools/client/inspector/markup/test/doc_markup_update-on-navigtion_2.html b/devtools/client/inspector/markup/test/doc_markup_update-on-navigtion_2.html
new file mode 100644
index 000000000..93d84a088
--- /dev/null
+++ b/devtools/client/inspector/markup/test/doc_markup_update-on-navigtion_2.html
@@ -0,0 +1 @@
+<div id='two' style='color:green;'>TWO</div>
diff --git a/devtools/client/locales/en-US/webConsole.dtd b/devtools/client/locales/en-US/webConsole.dtd
index 17ae02699..7d2eb1faa 100644
--- a/devtools/client/locales/en-US/webConsole.dtd
+++ b/devtools/client/locales/en-US/webConsole.dtd
@@ -11,6 +11,11 @@
<!ENTITY window.title "Web Console">
<!ENTITY browserConsole.title "Browser Console">
+<!-- LOCALIZATION NOTE (saveBodies.label): You can see this string in
+ - the Web Console and Browser Console menu. -->
+<!ENTITY saveBodies.label "Log Request and Response Bodies">
+<!ENTITY saveBodies.accesskey "L">
+
<!-- LOCALIZATION NOTE (openURL.label): You can see this string in the Web
- Console context menu. -->
<!ENTITY openURL.label "Open URL in New Tab">
diff --git a/devtools/client/preferences/devtools.js b/devtools/client/preferences/devtools.js
index 9de9cd34a..2f6ca2104 100644
--- a/devtools/client/preferences/devtools.js
+++ b/devtools/client/preferences/devtools.js
@@ -248,6 +248,7 @@ pref("devtools.webconsole.filter.log", true);
pref("devtools.webconsole.filter.debug", true);
pref("devtools.webconsole.filter.net", false);
pref("devtools.webconsole.filter.netxhr", false);
+pref("devtools.webconsole.filter.saveBodies", true);
// Deprecated - old console frontend
pref("devtools.webconsole.filter.network", true);
pref("devtools.webconsole.filter.networkinfo", false);
@@ -273,6 +274,7 @@ pref("devtools.browserconsole.filter.network", true);
pref("devtools.browserconsole.filter.networkinfo", false);
pref("devtools.browserconsole.filter.netwarn", true);
pref("devtools.browserconsole.filter.netxhr", false);
+pref("devtools.browserconsole.filter.saveBodies", false);
pref("devtools.browserconsole.filter.csserror", true);
pref("devtools.browserconsole.filter.cssparser", false);
pref("devtools.browserconsole.filter.csslog", false);
diff --git a/devtools/client/responsive.html/browser/web-navigation.js b/devtools/client/responsive.html/browser/web-navigation.js
index 4519df0bd..eee24993a 100644
--- a/devtools/client/responsive.html/browser/web-navigation.js
+++ b/devtools/client/responsive.html/browser/web-navigation.js
@@ -8,6 +8,7 @@ const { Ci, Cu, Cr } = require("chrome");
const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
const Services = require("Services");
const { NetUtil } = require("resource://gre/modules/NetUtil.jsm");
+const { Utils } = require("resource://gre/modules/sessionstore/Utils.jsm");
function readInputStreamToString(stream) {
return NetUtil.readInputStreamToString(stream, stream.available());
@@ -61,11 +62,11 @@ BrowserElementWebNavigation.prototype = {
// No equivalent in the current BrowserElement API
this.loadURIWithOptions(uri, flags, referrer,
Ci.nsIHttpChannel.REFERRER_POLICY_DEFAULT,
- postData, headers, null);
+ postData, headers, null, null);
},
loadURIWithOptions(uri, flags, referrer, referrerPolicy, postData, headers,
- baseURI) {
+ baseURI, triggeringPrincipal) {
// No equivalent in the current BrowserElement API
this._sendMessage("WebNavigation:LoadURI", {
uri,
@@ -75,6 +76,9 @@ BrowserElementWebNavigation.prototype = {
postData: postData ? readInputStreamToString(postData) : null,
headers: headers ? readInputStreamToString(headers) : null,
baseURI: baseURI ? baseURI.spec : null,
+ triggeringPrincipal: triggeringPrincipal
+ ? Utils.serializePrincipal(triggeringPrincipal)
+ : null,
});
},
diff --git a/devtools/client/shared/widgets/TableWidget.js b/devtools/client/shared/widgets/TableWidget.js
index a0f0dfc11..57d2914d5 100644
--- a/devtools/client/shared/widgets/TableWidget.js
+++ b/devtools/client/shared/widgets/TableWidget.js
@@ -463,7 +463,14 @@ TableWidget.prototype = {
return;
}
- let selectedCell = this.tbody.querySelector(".theme-selected");
+ // We need to get the first *visible* selected cell. Some columns are hidden
+ // e.g. because they contain a unique compound key for cookies that is never
+ // displayed in the UI. To do this we get all selected cells and filter out
+ // any that are hidden.
+ let selectedCells = [...this.tbody.querySelectorAll(".theme-selected")]
+ .filter(cell => cell.clientWidth > 0);
+ // Select the first visible selected cell.
+ let selectedCell = selectedCells[0];
if (!selectedCell) {
return;
}
diff --git a/devtools/client/sourceeditor/tern/def.js b/devtools/client/sourceeditor/tern/def.js
index 71f6e7991..f4a7ba9c8 100755
--- a/devtools/client/sourceeditor/tern/def.js
+++ b/devtools/client/sourceeditor/tern/def.js
@@ -77,7 +77,8 @@
}
},
word: function(re) {
- var word = "", ch, re = re || /[\w$]/;
+ var word = "", ch;
+ re = re || /[\w$]/;
while ((ch = this.spec.charAt(this.pos)) && re.test(ch)) { word += ch; ++this.pos; }
return word;
},
@@ -187,7 +188,7 @@
if (top && this.forceNew) return new infer.Obj(base);
return infer.getInstance(base);
} else if (this.eat(":")) {
- var name = this.word(/[\w$\.]/)
+ name = this.word(/[\w$\.]/)
return infer.getSymbol(name)
} else if (comp && this.eat("!")) {
var arg = this.word(/\d/);
diff --git a/devtools/client/storage/ui.js b/devtools/client/storage/ui.js
index 7745c8da9..5bd29d297 100644
--- a/devtools/client/storage/ui.js
+++ b/devtools/client/storage/ui.js
@@ -482,24 +482,27 @@ StorageUI.prototype = {
* @param {object} See onUpdate docs
*/
handleChangedItems: function (changed) {
- if (this.tree.selectedItem) {
- let [type, host, db, objectStore] = this.tree.selectedItem;
- if (!changed[type] || !changed[type][host] ||
- changed[type][host].length == 0) {
- return;
- }
- try {
- let toUpdate = [];
- for (let name of changed[type][host]) {
- let names = JSON.parse(name);
- if (names[0] == db && names[1] == objectStore && names[2]) {
- toUpdate.push(name);
- }
+ let selectedItem = this.tree.selectedItem;
+ if (!selectedItem) {
+ return;
+ }
+
+ let [type, host, db, objectStore] = selectedItem;
+ if (!changed[type] || !changed[type][host] ||
+ changed[type][host].length == 0) {
+ return;
+ }
+ try {
+ let toUpdate = [];
+ for (let name of changed[type][host]) {
+ let names = JSON.parse(name);
+ if (names[0] == db && names[1] == objectStore && names[2]) {
+ toUpdate.push(name);
}
- this.fetchStorageObjects(type, host, toUpdate, REASON.UPDATE);
- } catch (ex) {
- this.fetchStorageObjects(type, host, changed[type][host], REASON.UPDATE);
}
+ this.fetchStorageObjects(type, host, toUpdate, REASON.UPDATE);
+ } catch (ex) {
+ this.fetchStorageObjects(type, host, changed[type][host], REASON.UPDATE);
}
},
@@ -830,6 +833,7 @@ StorageUI.prototype = {
if (!item) {
return;
}
+
this.table.clear();
this.hideSidebar();
this.searchBox.value = "";
@@ -1136,11 +1140,13 @@ StorageUI.prototype = {
* Handles adding an item from the storage
*/
onAddItem: function () {
- if (!this.tree.selectedItem) {
+ let selectedItem = this.tree.selectedItem;
+ if (!selectedItem) {
return;
}
+
let front = this.getCurrentFront();
- let [, host] = this.tree.selectedItem;
+ let [, host] = selectedItem;
// Prepare to scroll into view.
this.table.scrollIntoViewOnUpdate = true;
diff --git a/devtools/client/webconsole/webconsole.js b/devtools/client/webconsole/webconsole.js
index bd7f90a0e..f2031f18a 100644
--- a/devtools/client/webconsole/webconsole.js
+++ b/devtools/client/webconsole/webconsole.js
@@ -555,6 +555,19 @@ WebConsoleFrame.prototype = {
// calculations.
this._updateCharSize();
+ let saveBodiesDisabled = !this.getFilterState("networkinfo") &&
+ !this.getFilterState("netxhr") &&
+ !this.getFilterState("network");
+
+ let saveBodies = this.document.getElementById("saveBodies");
+ saveBodies.disabled = saveBodiesDisabled;
+
+ saveBodies.parentNode.addEventListener("popupshowing", () => {
+ saveBodies.disabled = !this.getFilterState("networkinfo") &&
+ !this.getFilterState("netxhr") &&
+ !this.getFilterState("network");
+ });
+
this.jsterm = new JSTerm(this);
this.jsterm.init();
@@ -684,9 +697,9 @@ WebConsoleFrame.prototype = {
_initDefaultFilterPrefs: function () {
let prefs = ["network", "networkinfo", "csserror", "cssparser", "csslog",
"exception", "jswarn", "jslog", "error", "info", "warn", "log",
- "secerror", "secwarn", "netwarn", "netxhr", "sharedworkers",
- "serviceworkers", "windowlessworkers", "servererror",
- "serverwarn", "serverinfo", "serverlog"];
+ "secerror", "secwarn", "netwarn", "netxhr", "saveBodies",
+ "sharedworkers", "serviceworkers", "windowlessworkers",
+ "servererror", "serverwarn", "serverinfo", "serverlog"];
for (let pref of prefs) {
this.filterPrefs[pref] = Services.prefs.getBoolPref(
@@ -954,6 +967,16 @@ WebConsoleFrame.prototype = {
let prefKey = target.getAttribute("prefKey");
this.setFilterState(prefKey, state);
+ // Disable the log response and request body if network logging is off.
+ if (prefKey == "networkinfo" ||
+ prefKey == "netxhr" ||
+ prefKey == "network") {
+ let checkState = !this.getFilterState("networkinfo") &&
+ !this.getFilterState("netxhr") &&
+ !this.getFilterState("network");
+ this.document.getElementById("saveBodies").disabled = checkState;
+ }
+
// Adjust the state of the button appropriately.
let menuPopup = target.parentNode;
@@ -987,9 +1010,12 @@ WebConsoleFrame.prototype = {
_setMenuState: function (target, state) {
let menuItems = target.querySelectorAll("menuitem");
Array.forEach(menuItems, (item) => {
- item.setAttribute("checked", state);
let prefKey = item.getAttribute("prefKey");
- this.setFilterState(prefKey, state);
+ // If not a separate switch only.
+ if (prefKey != "saveBodies") {
+ item.setAttribute("checked", state);
+ this.setFilterState(prefKey, state);
+ }
});
},
@@ -1006,6 +1032,10 @@ WebConsoleFrame.prototype = {
Services.prefs.setBoolPref(this._filterPrefsPrefix + toggleType, state);
+ if (toggleType == "saveBodies") {
+ this.setSaveRequestAndResponseBodies(state);
+ }
+
if (this._updateListenersTimeout) {
clearTimeout(this._updateListenersTimeout);
}
@@ -3245,9 +3275,8 @@ WebConsoleConnectionProxy.prototype = {
this.webConsoleClient = webConsoleClient;
this._hasNativeConsoleAPI = response.nativeConsoleAPI;
- // There is no way to view response bodies from the Browser Console, so do
- // not waste the memory.
- let saveBodies = !this.webConsoleFrame.isBrowserConsole;
+ let saveBodiesPref = this.webConsoleFrame._filterPrefsPrefix + "saveBodies";
+ let saveBodies = Services.prefs.getBoolPref(saveBodiesPref);
this.webConsoleFrame.setSaveRequestAndResponseBodies(saveBodies);
this.webConsoleClient.on("networkEvent", this._onNetworkEvent);
diff --git a/devtools/client/webconsole/webconsole.xul b/devtools/client/webconsole/webconsole.xul
index 1310fb57d..36f9f03bf 100644
--- a/devtools/client/webconsole/webconsole.xul
+++ b/devtools/client/webconsole/webconsole.xul
@@ -96,6 +96,10 @@ function goUpdateConsoleCommands() {
prefKey="netxhr"/>
<menuitem label="&btnConsoleLog;" type="checkbox" autocheck="false"
prefKey="networkinfo"/>
+ <menuseparator id="saveBodiesSeparator" />
+ <menuitem id="saveBodies" type="checkbox" label="&saveBodies.label;"
+ accesskey="&saveBodies.accesskey;" autocheck="false"
+ prefKey="saveBodies"/>
</menupopup>
</toolbarbutton>
<toolbarbutton label="&btnPageCSS.label;" type="menu-button"
diff --git a/devtools/moz.build b/devtools/moz.build
index 8e368facb..dd9f90c5a 100644
--- a/devtools/moz.build
+++ b/devtools/moz.build
@@ -7,11 +7,13 @@
if CONFIG['MOZ_DEVTOOLS']:
DIRS += ['client']
-
-DIRS += [
- 'server',
- 'shared',
-]
+if CONFIG['MOZ_DEVTOOLS_SERVER']:
+ DIRS += [
+ 'server',
+ 'shared',
+ ]
+else:
+ DIRS += ['shared/heapsnapshot/']
# /browser uses DIST_SUBDIR. We opt-in to this treatment when building
# DevTools for the browser to keep the root omni.ja slim for use by external XUL
diff --git a/devtools/server/actors/webconsole.js b/devtools/server/actors/webconsole.js
index 9712ff32d..a1eba84ed 100644
--- a/devtools/server/actors/webconsole.js
+++ b/devtools/server/actors/webconsole.js
@@ -778,8 +778,8 @@ WebConsoleActor.prototype =
}
// See `window` definition. It isn't always a DOM Window.
- let requestStartTime = this.window && this.window.performance ?
- this.window.performance.timing.requestStart : 0;
+ let winStartTime = this.window && this.window.performance ?
+ this.window.performance.timing.navigationStart : 0;
let cache = this.consoleAPIListener
.getCachedMessages(!this.parentActor.isRootActor);
@@ -787,7 +787,7 @@ WebConsoleActor.prototype =
// Filter out messages that came from a ServiceWorker but happened
// before the page was requested.
if (aMessage.innerID === "ServiceWorker" &&
- requestStartTime > aMessage.timeStamp) {
+ winStartTime > aMessage.timeStamp) {
return;
}
diff --git a/devtools/server/child.js b/devtools/server/child.js
index e2838f08d..c69b0a3fb 100644
--- a/devtools/server/child.js
+++ b/devtools/server/child.js
@@ -61,7 +61,7 @@ try {
try {
m = require(module);
- if (!setupChild in m) {
+ if (!(setupChild in m)) {
dumpn(`ERROR: module '${module}' does not export '${setupChild}'`);
return false;
}
diff --git a/devtools/server/main.js b/devtools/server/main.js
index 475995493..ac76adb83 100644
--- a/devtools/server/main.js
+++ b/devtools/server/main.js
@@ -1040,7 +1040,7 @@ var DebuggerServer = {
try {
m = require(module);
- if (!setupParent in m) {
+ if (!(setupParent in m)) {
dumpn(`ERROR: module '${module}' does not export '${setupParent}'`);
return false;
}
diff --git a/devtools/shared/css/generated/properties-db.js b/devtools/shared/css/generated/properties-db.js
index 83b3efafc..070167496 100644
--- a/devtools/shared/css/generated/properties-db.js
+++ b/devtools/shared/css/generated/properties-db.js
@@ -3064,6 +3064,7 @@ exports.CSS_PROPERTIES = {
"text-emphasis-style",
"-webkit-text-fill-color",
"text-indent",
+ "text-justify",
"text-orientation",
"text-overflow",
"text-rendering",
@@ -3240,6 +3241,7 @@ exports.CSS_PROPERTIES = {
"dialog",
"difference",
"disabled",
+ "distribute",
"dotted",
"double",
"drag",
@@ -3299,6 +3301,8 @@ exports.CSS_PROPERTIES = {
"inline-table",
"inset",
"inside",
+ "inter-character",
+ "inter-word",
"intersect",
"isolate",
"italic",
@@ -8865,6 +8869,23 @@ exports.CSS_PROPERTIES = {
"unset"
]
},
+ "text-justify": {
+ "isInherited": true,
+ "subproperties": [
+ "text-justify"
+ ],
+ "supports": [],
+ "values": [
+ "auto",
+ "distribute",
+ "inherit",
+ "initial",
+ "inter-character",
+ "inter-word",
+ "none",
+ "unset"
+ ]
+ },
"text-orientation": {
"isInherited": true,
"subproperties": [
diff --git a/devtools/shared/discovery/discovery.js b/devtools/shared/discovery/discovery.js
index d0b49f129..3aa82ef6e 100644
--- a/devtools/shared/discovery/discovery.js
+++ b/devtools/shared/discovery/discovery.js
@@ -181,18 +181,7 @@ LocalDevice.prototype = {
* Triggers the |name| setter to persist if needed.
*/
_generate: function () {
- if (Services.appinfo.widgetToolkit == "gonk") {
- // For Firefox OS devices, create one from the device name plus a little
- // randomness. The goal is just to distinguish devices in an office
- // environment where many people may have the same device model for
- // testing purposes (which would otherwise all report the same name).
- let name = libcutils.property_get("ro.product.device");
- // Pick a random number from [0, 2^32)
- let randomID = Math.floor(Math.random() * Math.pow(2, 32));
- // To hex and zero pad
- randomID = ("00000000" + randomID.toString(16)).slice(-8);
- this.name = name + "-" + randomID;
- } else if (Services.appinfo.widgetToolkit == "android") {
+ if (Services.appinfo.widgetToolkit == "android") {
// For Firefox for Android, use the device's model name.
// TODO: Bug 1180997: Find the right way to expose an editable name
this.name = sysInfo.get("device");
diff --git a/devtools/shared/heapsnapshot/moz.build b/devtools/shared/heapsnapshot/moz.build
index d020da727..fa9ef3915 100644
--- a/devtools/shared/heapsnapshot/moz.build
+++ b/devtools/shared/heapsnapshot/moz.build
@@ -48,15 +48,16 @@ DEFINES['GOOGLE_PROTOBUF_NO_RTTI'] = True
FINAL_LIBRARY = 'xul'
-DevToolsModules(
- 'census-tree-node.js',
- 'CensusUtils.js',
- 'DominatorTreeNode.js',
- 'HeapAnalysesClient.js',
- 'HeapAnalysesWorker.js',
- 'HeapSnapshotFileUtils.js',
- 'shortest-paths.js',
-)
+if CONFIG['MOZ_DEVTOOLS_SERVER']:
+ DevToolsModules(
+ 'census-tree-node.js',
+ 'CensusUtils.js',
+ 'DominatorTreeNode.js',
+ 'HeapAnalysesClient.js',
+ 'HeapAnalysesWorker.js',
+ 'HeapSnapshotFileUtils.js',
+ 'shortest-paths.js',
+ )
if CONFIG['GNU_CXX']:
CXXFLAGS += ['-Wno-error=shadow']
diff --git a/.github/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index 7acdedb4f..7acdedb4f 100644
--- a/.github/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
diff --git a/docshell/base/crashtests/914521.html b/docshell/base/crashtests/914521.html
index 9ae18b860..eb0a43749 100644
--- a/docshell/base/crashtests/914521.html
+++ b/docshell/base/crashtests/914521.html
@@ -20,6 +20,14 @@ function f()
finish();
}
+function init()
+{
+ SpecialPowers.pushPrefEnv({"set": [
+ ["security.data_uri.block_toplevel_data_uri_navigations", false],
+ ]}, start);
+
+}
+
function start()
{
var html = "<script>" + f + "<\/script><body onload=f()>";
@@ -29,5 +37,5 @@ function start()
</script>
</head>
-<body onload="start();"></body>
+<body onload="init();"></body>
</html>
diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp
index bd2a8a433..b3e26da33 100644
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -1644,7 +1644,7 @@ nsDocShell::LoadStream(nsIInputStream* aStream, nsIURI* aURI,
uri,
aStream,
triggeringPrincipal,
- nsILoadInfo::SEC_NORMAL,
+ nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
nsIContentPolicy::TYPE_OTHER,
aContentType,
aContentCharset);
@@ -4732,7 +4732,7 @@ nsDocShell::LoadURI(const char16_t* aURI,
{
return LoadURIWithOptions(aURI, aLoadFlags, aReferringURI,
mozilla::net::RP_Default, aPostStream,
- aHeaderStream, nullptr);
+ aHeaderStream, nullptr, nullptr);
}
NS_IMETHODIMP
@@ -4742,7 +4742,8 @@ nsDocShell::LoadURIWithOptions(const char16_t* aURI,
uint32_t aReferrerPolicy,
nsIInputStream* aPostStream,
nsIInputStream* aHeaderStream,
- nsIURI* aBaseURI)
+ nsIURI* aBaseURI,
+ nsIPrincipal* aTriggeringPrincipal)
{
NS_ASSERTION((aLoadFlags & 0xf) == 0, "Unexpected flags");
@@ -4861,6 +4862,7 @@ nsDocShell::LoadURIWithOptions(const char16_t* aURI,
loadInfo->SetReferrerPolicy(aReferrerPolicy);
loadInfo->SetHeadersStream(aHeaderStream);
loadInfo->SetBaseURI(aBaseURI);
+ loadInfo->SetTriggeringPrincipal(aTriggeringPrincipal);
loadInfo->SetForceAllowDataURI(forceAllowDataURI);
if (fixupInfo) {
@@ -5687,6 +5689,11 @@ nsDocShell::LoadPage(nsISupports* aPageDescriptor, uint32_t aDisplayType)
}
shEntry->SetURI(newUri);
shEntry->SetOriginalURI(nullptr);
+ // shEntry's current triggering principal is whoever loaded that page initially.
+ // But now we're doing another load of the page, via an API that is only exposed
+ // to system code. The triggering principal for this load should be the system
+ // principal.
+ shEntry->SetTriggeringPrincipal(nsContentUtils::GetSystemPrincipal());
}
rv = LoadHistoryEntry(shEntry, LOAD_HISTORY);
@@ -9145,8 +9152,13 @@ nsDocShell::CreateContentViewer(const nsACString& aContentType,
// Make sure we have a URI to set currentURI.
nsCOMPtr<nsIURI> failedURI;
+ nsCOMPtr<nsIPrincipal> triggeringPrincipal;
if (failedChannel) {
NS_GetFinalChannelURI(failedChannel, getter_AddRefs(failedURI));
+ } else {
+ // if there is no failed channel we have to explicitly provide
+ // a triggeringPrincipal for the history entry.
+ triggeringPrincipal = nsContentUtils::GetSystemPrincipal();
}
if (!failedURI) {
@@ -9167,7 +9179,8 @@ nsDocShell::CreateContentViewer(const nsACString& aContentType,
// Create an shistory entry for the old load.
if (failedURI) {
bool errorOnLocationChangeNeeded = OnNewURI(
- failedURI, failedChannel, nullptr, nullptr, mLoadType, false, false, false);
+ failedURI, failedChannel, triggeringPrincipal,
+ nullptr, mLoadType, false, false, false);
if (errorOnLocationChangeNeeded) {
FireOnLocationChange(this, failedChannel, failedURI,
@@ -10394,10 +10407,13 @@ nsDocShell::InternalLoad(nsIURI* aURI,
* call OnNewURI() so that, this traversal will be
* recorded in session and global history.
*/
- nsCOMPtr<nsIPrincipal> triggeringPrincipal, principalToInherit;
+ nsCOMPtr<nsIPrincipal> newURITriggeringPrincipal, newURIPrincipalToInherit;
if (mOSHE) {
- mOSHE->GetTriggeringPrincipal(getter_AddRefs(triggeringPrincipal));
- mOSHE->GetPrincipalToInherit(getter_AddRefs(principalToInherit));
+ mOSHE->GetTriggeringPrincipal(getter_AddRefs(newURITriggeringPrincipal));
+ mOSHE->GetPrincipalToInherit(getter_AddRefs(newURIPrincipalToInherit));
+ } else {
+ newURITriggeringPrincipal = aTriggeringPrincipal;
+ newURIPrincipalToInherit = doc->NodePrincipal();
}
// Pass true for aCloneSHChildren, since we're not
// changing documents here, so all of our subframes are
@@ -10407,7 +10423,7 @@ nsDocShell::InternalLoad(nsIURI* aURI,
// flag on firing onLocationChange(...).
// Anyway, aCloneSHChildren param is simply reflecting
// doShortCircuitedLoad in this scope.
- OnNewURI(aURI, nullptr, triggeringPrincipal, principalToInherit,
+ OnNewURI(aURI, nullptr, newURITriggeringPrincipal, newURIPrincipalToInherit,
mLoadType, true, true, true);
nsCOMPtr<nsIInputStream> postData;
@@ -10606,7 +10622,7 @@ nsDocShell::InternalLoad(nsIURI* aURI,
}
bool shouldLoad;
rv = browserChrome3->ShouldLoadURI(this, uriForShouldLoadCheck, aReferrer,
- &shouldLoad);
+ aTriggeringPrincipal, &shouldLoad);
if (NS_SUCCEEDED(rv) && !shouldLoad) {
return NS_OK;
}
@@ -10961,7 +10977,8 @@ nsDocShell::DoURILoad(nsIURI* aURI,
}
nsLoadFlags loadFlags = mDefaultLoadFlags;
- nsSecurityFlags securityFlags = nsILoadInfo::SEC_NORMAL;
+ nsSecurityFlags securityFlags =
+ nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL;
if (aFirstParty) {
// tag first party URL loads
@@ -12123,7 +12140,9 @@ nsDocShell::AddState(JS::Handle<JS::Value> aData, const nsAString& aTitle,
// Since we're not changing which page we have loaded, pass
// true for aCloneChildren.
- rv = AddToSessionHistory(newURI, nullptr, nullptr, nullptr, true,
+ rv = AddToSessionHistory(newURI, nullptr,
+ document->NodePrincipal(), // triggeringPrincipal
+ nullptr, true,
getter_AddRefs(newSHEntry));
NS_ENSURE_SUCCESS(rv, rv);
@@ -12399,11 +12418,6 @@ nsDocShell::AddToSessionHistory(nsIURI* aURI, nsIChannel* aChannel,
discardLayoutState = ShouldDiscardLayoutState(httpChannel);
}
- // XXX Bug 1286838: Replace channel owner with loadInfo triggeringPrincipal
- nsCOMPtr<nsISupports> owner;
- aChannel->GetOwner(getter_AddRefs(owner));
- triggeringPrincipal = do_QueryInterface(owner);
-
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->GetLoadInfo();
if (loadInfo) {
if (!triggeringPrincipal) {
@@ -12649,10 +12663,6 @@ nsDocShell::LoadHistoryEntry(nsISHEntry* aEntry, uint32_t aLoadType)
srcdoc = NullString();
}
- // If there is no triggeringPrincipal we can fall back to using the
- // SystemPrincipal as the triggeringPrincipal for loading the history
- // entry, since the history entry can only end up in history if security
- // checks passed in the initial loading phase.
if (!triggeringPrincipal) {
triggeringPrincipal = nsContentUtils::GetSystemPrincipal();
}
@@ -13917,7 +13927,8 @@ public:
const nsAString& aFileName,
nsIInputStream* aPostDataStream,
nsIInputStream* aHeadersDataStream,
- bool aIsTrusted);
+ bool aIsTrusted,
+ nsIPrincipal* aTriggeringPrincipal);
NS_IMETHOD Run() override
{
@@ -13933,7 +13944,7 @@ public:
mHandler->OnLinkClickSync(mContent, mURI,
mTargetSpec.get(), mFileName,
mPostDataStream, mHeadersDataStream,
- nullptr, nullptr);
+ nullptr, nullptr, mTriggeringPrincipal);
}
return NS_OK;
}
@@ -13948,6 +13959,7 @@ private:
nsCOMPtr<nsIContent> mContent;
PopupControlState mPopupState;
bool mIsTrusted;
+ nsCOMPtr<nsIPrincipal> mTriggeringPrincipal;
};
OnLinkClickEvent::OnLinkClickEvent(nsDocShell* aHandler,
@@ -13957,7 +13969,8 @@ OnLinkClickEvent::OnLinkClickEvent(nsDocShell* aHandler,
const nsAString& aFileName,
nsIInputStream* aPostDataStream,
nsIInputStream* aHeadersDataStream,
- bool aIsTrusted)
+ bool aIsTrusted,
+ nsIPrincipal* aTriggeringPrincipal)
: mHandler(aHandler)
, mURI(aURI)
, mTargetSpec(aTargetSpec)
@@ -13967,6 +13980,7 @@ OnLinkClickEvent::OnLinkClickEvent(nsDocShell* aHandler,
, mContent(aContent)
, mPopupState(mHandler->mScriptGlobal->GetPopupControlState())
, mIsTrusted(aIsTrusted)
+ , mTriggeringPrincipal(aTriggeringPrincipal)
{
}
@@ -13977,7 +13991,8 @@ nsDocShell::OnLinkClick(nsIContent* aContent,
const nsAString& aFileName,
nsIInputStream* aPostDataStream,
nsIInputStream* aHeadersDataStream,
- bool aIsTrusted)
+ bool aIsTrusted,
+ nsIPrincipal* aTriggeringPrincipal)
{
NS_ASSERTION(NS_IsMainThread(), "wrong thread");
@@ -14016,7 +14031,8 @@ nsDocShell::OnLinkClick(nsIContent* aContent,
nsCOMPtr<nsIRunnable> ev =
new OnLinkClickEvent(this, aContent, aURI, target.get(), aFileName,
- aPostDataStream, aHeadersDataStream, aIsTrusted);
+ aPostDataStream, aHeadersDataStream,
+ aIsTrusted, aTriggeringPrincipal);
return NS_DispatchToCurrentThread(ev);
}
@@ -14028,7 +14044,8 @@ nsDocShell::OnLinkClickSync(nsIContent* aContent,
nsIInputStream* aPostDataStream,
nsIInputStream* aHeadersDataStream,
nsIDocShell** aDocShell,
- nsIRequest** aRequest)
+ nsIRequest** aRequest,
+ nsIPrincipal* aTriggeringPrincipal)
{
// Initialize the DocShell / Request
if (aDocShell) {
@@ -14151,13 +14168,18 @@ nsDocShell::OnLinkClickSync(nsIContent* aContent,
return NS_ERROR_OUT_OF_MEMORY;
}
+ // if the triggeringPrincipal is not passed explicitly, then we
+ // fall back to using doc->NodePrincipal() as the triggeringPrincipal.
+ nsCOMPtr<nsIPrincipal> triggeringPrincipal =
+ aTriggeringPrincipal ? aTriggeringPrincipal
+ : aContent->NodePrincipal();
+
nsresult rv = InternalLoad(clonedURI, // New URI
nullptr, // Original URI
false, // LoadReplace
referer, // Referer URI
refererPolicy, // Referer policy
- aContent->NodePrincipal(), // Triggering is our node's
- // principal
+ triggeringPrincipal,
aContent->NodePrincipal(),
flags,
target, // Window target
diff --git a/docshell/base/nsDocShell.h b/docshell/base/nsDocShell.h
index 63a4e3358..f510a15b0 100644
--- a/docshell/base/nsDocShell.h
+++ b/docshell/base/nsDocShell.h
@@ -201,7 +201,8 @@ public:
const nsAString& aFileName,
nsIInputStream* aPostDataStream,
nsIInputStream* aHeadersDataStream,
- bool aIsTrusted) override;
+ bool aIsTrusted,
+ nsIPrincipal* aTriggeringPrincipal) override;
NS_IMETHOD OnLinkClickSync(nsIContent* aContent,
nsIURI* aURI,
const char16_t* aTargetSpec,
@@ -209,7 +210,8 @@ public:
nsIInputStream* aPostDataStream = 0,
nsIInputStream* aHeadersDataStream = 0,
nsIDocShell** aDocShell = 0,
- nsIRequest** aRequest = 0) override;
+ nsIRequest** aRequest = 0,
+ nsIPrincipal* aTriggeringPrincipal = nullptr) override;
NS_IMETHOD OnOverLink(nsIContent* aContent,
nsIURI* aURI,
const char16_t* aTargetSpec) override;
diff --git a/docshell/base/nsILinkHandler.h b/docshell/base/nsILinkHandler.h
index 7cdcd566d..7069f1f1d 100644
--- a/docshell/base/nsILinkHandler.h
+++ b/docshell/base/nsILinkHandler.h
@@ -37,6 +37,8 @@ public:
* @param aFileName non-null when the link should be downloaded as the given file
* @param aHeadersDataStream ???
* @param aIsTrusted false if the triggerer is an untrusted DOM event.
+ * @param aTriggeringPrincipal, if not passed explicitly we fall back to
+ * the document's principal.
*/
NS_IMETHOD OnLinkClick(nsIContent* aContent,
nsIURI* aURI,
@@ -44,7 +46,8 @@ public:
const nsAString& aFileName,
nsIInputStream* aPostDataStream,
nsIInputStream* aHeadersDataStream,
- bool aIsTrusted) = 0;
+ bool aIsTrusted,
+ nsIPrincipal* aTriggeringPrincipal) = 0;
/**
* Process a click on a link.
@@ -61,6 +64,8 @@ public:
* @param aHeadersDataStream ???
* @param aDocShell (out-param) the DocShell that the request was opened on
* @param aRequest the request that was opened
+ * @param aTriggeringPrincipal, if not passed explicitly we fall back to
+ * the document's principal.
*/
NS_IMETHOD OnLinkClickSync(nsIContent* aContent,
nsIURI* aURI,
@@ -69,7 +74,8 @@ public:
nsIInputStream* aPostDataStream = 0,
nsIInputStream* aHeadersDataStream = 0,
nsIDocShell** aDocShell = 0,
- nsIRequest** aRequest = 0) = 0;
+ nsIRequest** aRequest = 0,
+ nsIPrincipal* aTriggeringPrincipal = nullptr) = 0;
/**
* Process a mouse-over a link.
diff --git a/docshell/base/nsIWebNavigation.idl b/docshell/base/nsIWebNavigation.idl
index 241d0731c..c3e2fc550 100644
--- a/docshell/base/nsIWebNavigation.idl
+++ b/docshell/base/nsIWebNavigation.idl
@@ -9,6 +9,7 @@ interface nsIDOMDocument;
interface nsIInputStream;
interface nsISHistory;
interface nsIURI;
+interface nsIPrincipal;
/**
* The nsIWebNavigation interface defines an interface for navigating the web.
@@ -288,14 +289,20 @@ interface nsIWebNavigation : nsISupports
* that at present this argument is only used with view-source aURIs
* and cannot be used to resolve aURI.
* This parameter is optional and may be null.
- */
- void loadURIWithOptions(in wstring aURI,
- in unsigned long aLoadFlags,
- in nsIURI aReferrer,
- in unsigned long aReferrerPolicy,
- in nsIInputStream aPostData,
- in nsIInputStream aHeaders,
- in nsIURI aBaseURI);
+ * @param aTriggeringPrincipal
+ * The principal that initiated the load of aURI. If omitted docShell
+ * tries to create a codeBasePrincipal from aReferrer if not null. If
+ * aReferrer is also null docShell peforms a load using the
+ * SystemPrincipal as the triggeringPrincipal.
+ */
+ void loadURIWithOptions(in wstring aURI,
+ in unsigned long aLoadFlags,
+ in nsIURI aReferrer,
+ in unsigned long aReferrerPolicy,
+ in nsIInputStream aPostData,
+ in nsIInputStream aHeaders,
+ in nsIURI aBaseURI,
+ [optional] in nsIPrincipal aTriggeringPrincipal);
/**
* Tells the Object to reload the current page. There may be cases where the
diff --git a/docshell/shistory/nsSHEntry.cpp b/docshell/shistory/nsSHEntry.cpp
index 9d972136f..6b0b066d9 100644
--- a/docshell/shistory/nsSHEntry.cpp
+++ b/docshell/shistory/nsSHEntry.cpp
@@ -416,6 +416,9 @@ nsSHEntry::Create(nsIURI* aURI, const nsAString& aTitle,
uint64_t aDocShellID,
bool aDynamicCreation)
{
+ MOZ_ASSERT(aTriggeringPrincipal,
+ "need a valid triggeringPrincipal to create a session history entry");
+
mURI = aURI;
mTitle = aTitle;
mPostData = aInputStream;
diff --git a/docshell/shistory/nsSHistory.cpp b/docshell/shistory/nsSHistory.cpp
index 7c148ffcc..9443b92bc 100644
--- a/docshell/shistory/nsSHistory.cpp
+++ b/docshell/shistory/nsSHistory.cpp
@@ -1582,7 +1582,8 @@ nsSHistory::LoadURIWithOptions(const char16_t* aURI,
uint32_t aReferrerPolicy,
nsIInputStream* aPostStream,
nsIInputStream* aExtraHeaderStream,
- nsIURI* aBaseURI)
+ nsIURI* aBaseURI,
+ nsIPrincipal* aTriggeringPrincipal)
{
return NS_OK;
}
diff --git a/docshell/test/browser/browser.ini b/docshell/test/browser/browser.ini
index 9211092a4..300caff1a 100644
--- a/docshell/test/browser/browser.ini
+++ b/docshell/test/browser/browser.ini
@@ -1,5 +1,6 @@
[DEFAULT]
support-files =
+ dummy_page.html
favicon_bug655270.ico
file_bug234628-1-child.html
file_bug234628-1.html
@@ -45,6 +46,7 @@ support-files =
browser_timelineMarkers-frame-05.js
head.js
frame-head.js
+ file_click_link_within_view_source.html
[browser_bug1206879.js]
[browser_bug1309900_crossProcessHistoryNavigation.js]
@@ -91,3 +93,4 @@ skip-if = true # Bug 1220415
[browser_timelineMarkers-04.js]
[browser_timelineMarkers-05.js]
[browser_ua_emulation.js]
+[browser_click_link_within_view_source.js]
diff --git a/docshell/test/browser/browser_click_link_within_view_source.js b/docshell/test/browser/browser_click_link_within_view_source.js
new file mode 100644
index 000000000..84cfc1f0f
--- /dev/null
+++ b/docshell/test/browser/browser_click_link_within_view_source.js
@@ -0,0 +1,60 @@
+"use strict";
+
+/**
+ * Test for Bug 1359204
+ *
+ * Loading a local file, then view-source on that file. Make sure that
+ * clicking a link within that view-source page is not blocked by security checks.
+ */
+
+add_task(function* test_click_link_within_view_source() {
+ let TEST_FILE = "file_click_link_within_view_source.html";
+ let TEST_FILE_URI = getChromeDir(getResolvedURI(gTestPath));
+ TEST_FILE_URI.append(TEST_FILE);
+ TEST_FILE_URI = Services.io.newFileURI(TEST_FILE_URI).spec;
+
+ let DUMMY_FILE = "dummy_page.html";
+ let DUMMY_FILE_URI = getChromeDir(getResolvedURI(gTestPath));
+ DUMMY_FILE_URI.append(DUMMY_FILE);
+ DUMMY_FILE_URI = Services.io.newFileURI(DUMMY_FILE_URI).spec;
+
+ yield BrowserTestUtils.withNewTab(TEST_FILE_URI, function*(aBrowser) {
+ let tabSpec = gBrowser.selectedBrowser.currentURI.spec;
+ info("loading: " + tabSpec);
+ ok(tabSpec.startsWith("file://") && tabSpec.endsWith(TEST_FILE),
+ "sanity check to make sure html loaded");
+
+ info("click view-source of html");
+ let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser);
+ document.getElementById("View:PageSource").doCommand();
+
+ let tab = yield tabPromise;
+ tabSpec = gBrowser.selectedBrowser.currentURI.spec;
+ info("loading: " + tabSpec);
+ ok(tabSpec.startsWith("view-source:file://") && tabSpec.endsWith(TEST_FILE),
+ "loading view-source of html succeeded");
+
+ info("click testlink within view-source page");
+ let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, url => url.endsWith("dummy_page.html"));
+ yield ContentTask.spawn(gBrowser.selectedBrowser, {}, function*() {
+ if (content.document.readyState != "complete") {
+ yield ContentTaskUtils.waitForEvent(content.document, "readystatechange", false, () =>
+ content.document.readyState == "complete");
+ }
+ // document.getElementById() does not work on a view-source page, hence we use document.links
+ let linksOnPage = content.document.links;
+ is (linksOnPage.length, 1, "sanity check: make sure only one link is present on page");
+ let myLink = content.document.links[0];
+ myLink.click();
+ });
+
+ yield loadPromise;
+
+ tabSpec = gBrowser.selectedBrowser.currentURI.spec;
+ info("loading: " + tabSpec);
+ ok(tabSpec.startsWith("view-source:file://") && tabSpec.endsWith(DUMMY_FILE),
+ "loading view-source of html succeeded");
+
+ yield BrowserTestUtils.removeTab(tab);
+ });
+});
diff --git a/docshell/test/browser/browser_history_triggeringprincipal_viewsource.js b/docshell/test/browser/browser_history_triggeringprincipal_viewsource.js
new file mode 100644
index 000000000..96908bbc2
--- /dev/null
+++ b/docshell/test/browser/browser_history_triggeringprincipal_viewsource.js
@@ -0,0 +1,50 @@
+"use strict";
+
+const TEST_PATH = getRootDirectory(gTestPath).replace("chrome://mochitests/content", "http://example.com");
+const HTML_URI = TEST_PATH + "dummy_page.html";
+const VIEW_SRC_URI = "view-source:" + HTML_URI;
+
+add_task(function*() {
+ info("load baseline html in new tab");
+ yield BrowserTestUtils.withNewTab(HTML_URI, function*(aBrowser) {
+ is(gBrowser.selectedBrowser.currentURI.spec, HTML_URI,
+ "sanity check to make sure html loaded");
+
+ info("right-click -> view-source of html");
+ let vSrcCtxtMenu = document.getElementById("contentAreaContextMenu");
+ let popupPromise = BrowserTestUtils.waitForEvent(vSrcCtxtMenu, "popupshown");
+ BrowserTestUtils.synthesizeMouseAtCenter("body", { type: "contextmenu", button: 2 }, aBrowser);
+ yield popupPromise;
+ let tabPromise = BrowserTestUtils.waitForNewTab(gBrowser, VIEW_SRC_URI);
+ let vSrcItem = vSrcCtxtMenu.getElementsByAttribute("id", "context-viewsource")[0];
+ vSrcItem.click();
+ vSrcCtxtMenu.hidePopup();
+ let tab = yield tabPromise;
+ is(gBrowser.selectedBrowser.currentURI.spec, VIEW_SRC_URI,
+ "loading view-source of html succeeded");
+
+ info ("load html file again before going .back()");
+ let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, HTML_URI);
+ yield ContentTask.spawn(tab.linkedBrowser, HTML_URI, HTML_URI => {
+ content.document.location = HTML_URI;
+ });
+ yield loadPromise;
+ is(gBrowser.selectedBrowser.currentURI.spec, HTML_URI,
+ "loading html another time succeeded");
+
+ info("click .back() to view-source of html again and make sure the history entry has a triggeringPrincipal");
+ let backCtxtMenu = document.getElementById("contentAreaContextMenu");
+ popupPromise = BrowserTestUtils.waitForEvent(backCtxtMenu, "popupshown");
+ BrowserTestUtils.synthesizeMouseAtCenter("body", { type: "contextmenu", button: 2 }, aBrowser);
+ yield popupPromise;
+ loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser, false, VIEW_SRC_URI);
+ let backItem = backCtxtMenu.getElementsByAttribute("id", "context-back")[0];
+ backItem.click();
+ backCtxtMenu.hidePopup();
+ yield loadPromise;
+ is(gBrowser.selectedBrowser.currentURI.spec, VIEW_SRC_URI,
+ "clicking .back() to view-source of html succeeded");
+
+ yield BrowserTestUtils.removeTab(tab);
+ });
+});
diff --git a/docshell/test/browser/dummy_page.html b/docshell/test/browser/dummy_page.html
new file mode 100644
index 000000000..59bf2a5f8
--- /dev/null
+++ b/docshell/test/browser/dummy_page.html
@@ -0,0 +1,6 @@
+<html>
+<head> <meta charset="utf-8"> </head>
+ <body>
+ just a dummy html file
+ </body>
+</html>
diff --git a/docshell/test/browser/file_click_link_within_view_source.html b/docshell/test/browser/file_click_link_within_view_source.html
new file mode 100644
index 000000000..d78e4ba0f
--- /dev/null
+++ b/docshell/test/browser/file_click_link_within_view_source.html
@@ -0,0 +1,6 @@
+<html>
+<head> <meta charset="utf-8"> </head>
+ <body>
+ <a id="testlink" href="dummy_page.html">clickme</a>
+ </body>
+</html>
diff --git a/docshell/test/chrome/test_bug364461.xul b/docshell/test/chrome/test_bug364461.xul
index 85154f9d7..9e45ce971 100644
--- a/docshell/test/chrome/test_bug364461.xul
+++ b/docshell/test/chrome/test_bug364461.xul
@@ -29,9 +29,15 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=364461
/** Test for Bug 364461 **/
SimpleTest.waitForExplicitFinish();
-window.open("bug364461_window.xul", "bug364461",
- "chrome,width=600,height=600");
+SpecialPowers.pushPrefEnv({
+ "set":[["security.data_uri.block_toplevel_data_uri_navigations", false]]
+}, runTests);
+
+function runTests() {
+ window.open("bug364461_window.xul", "bug364461",
+ "chrome,width=600,height=600");
+}
]]>
</script>
diff --git a/docshell/test/dummy_page.html b/docshell/test/dummy_page.html
new file mode 100644
index 000000000..59bf2a5f8
--- /dev/null
+++ b/docshell/test/dummy_page.html
@@ -0,0 +1,6 @@
+<html>
+<head> <meta charset="utf-8"> </head>
+ <body>
+ just a dummy html file
+ </body>
+</html>
diff --git a/docshell/test/file_bug598895_1.html b/docshell/test/file_bug598895_1.html
new file mode 100644
index 000000000..6fbb13a02
--- /dev/null
+++ b/docshell/test/file_bug598895_1.html
@@ -0,0 +1 @@
+<script>window.onload = function() { opener.postMessage('loaded', '*'); }</script><body>Should show</body>
diff --git a/docshell/test/file_bug598895_2.html b/docshell/test/file_bug598895_2.html
new file mode 100644
index 000000000..0822c566b
--- /dev/null
+++ b/docshell/test/file_bug598895_2.html
@@ -0,0 +1 @@
+<script>window.onload = function() { opener.postMessage('loaded', '*'); }</script><body></body>
diff --git a/docshell/test/file_bug637644_1.html b/docshell/test/file_bug637644_1.html
new file mode 100644
index 000000000..6fbb13a02
--- /dev/null
+++ b/docshell/test/file_bug637644_1.html
@@ -0,0 +1 @@
+<script>window.onload = function() { opener.postMessage('loaded', '*'); }</script><body>Should show</body>
diff --git a/docshell/test/file_bug637644_2.html b/docshell/test/file_bug637644_2.html
new file mode 100644
index 000000000..0822c566b
--- /dev/null
+++ b/docshell/test/file_bug637644_2.html
@@ -0,0 +1 @@
+<script>window.onload = function() { opener.postMessage('loaded', '*'); }</script><body></body>
diff --git a/docshell/test/mochitest.ini b/docshell/test/mochitest.ini
index 7b27908fb..d2e378928 100644
--- a/docshell/test/mochitest.ini
+++ b/docshell/test/mochitest.ini
@@ -11,6 +11,7 @@ support-files =
bug668513_redirect.html
bug668513_redirect.html^headers^
bug691547_frame.html
+ dummy_page.html
file_anchor_scroll_after_document_open.html
file_bug385434_1.html
file_bug385434_2.html
@@ -20,9 +21,13 @@ support-files =
file_bug540462.html
file_bug580069_1.html
file_bug580069_2.sjs
+ file_bug598895_1.html
+ file_bug598895_2.html
file_bug590573_1.html
file_bug590573_2.html
file_bug634834.html
+ file_bug637644_1.html
+ file_bug637644_2.html
file_bug640387.html
file_bug653741.html
file_bug660404
@@ -94,3 +99,4 @@ skip-if = toolkit == 'android' # bug 784321
support-files = file_framedhistoryframes.html
[test_pushState_after_document_open.html]
[test_windowedhistoryframes.html]
+[test_triggeringprincipal_location_seturi.html]
diff --git a/docshell/test/navigation/NavigationUtils.js b/docshell/test/navigation/NavigationUtils.js
index c90ea74d5..72bea7dde 100644
--- a/docshell/test/navigation/NavigationUtils.js
+++ b/docshell/test/navigation/NavigationUtils.js
@@ -9,10 +9,10 @@
///////////////////////////////////////////////////////////////////////////
var body = "This frame was navigated.";
-var target_url = "data:text/html,<html><body>" + body + "</body></html>";
+var target_url = "navigation_target_url.html"
var popup_body = "This is a popup";
-var target_popup_url = "data:text/html,<html><body>" + popup_body + "</body></html>";
+var target_popup_url = "navigation_target_popup_url.html";
///////////////////////////////////////////////////////////////////////////
// Functions that navigate frames
@@ -58,7 +58,7 @@ function navigateByHyperlink(name) {
function isNavigated(wnd, message) {
var result = null;
try {
- result = SpecialPowers.wrap(wnd).document.body.innerHTML;
+ result = SpecialPowers.wrap(wnd).document.body.innerHTML.trim();
} catch(ex) {
result = ex;
}
@@ -68,7 +68,7 @@ function isNavigated(wnd, message) {
function isBlank(wnd, message) {
var result = null;
try {
- result = wnd.document.body.innerHTML;
+ result = wnd.document.body.innerHTML.trim();
} catch(ex) {
result = ex;
}
@@ -146,7 +146,9 @@ function xpcGetFramesByName(name) {
function xpcCleanupWindows() {
xpcEnumerateContentWindows(function(win) {
- if (win.location && win.location.protocol == "data:")
+ if (win.location &&
+ (win.location.href.endsWith(target_url) ||
+ win.location.href.endsWith(target_popup_url))) {
win.close();
});
}
@@ -177,12 +179,12 @@ function xpcWaitForFinishedFrames(callback, numFrames) {
}
function searchForFinishedFrames(win) {
- if ((escape(unescape(win.location)) == escape(target_url) ||
- escape(unescape(win.location)) == escape(target_popup_url)) &&
+ if ((win.location.href.endsWith(target_url) ||
+ win.location.href.endsWith(target_popup_url)) &&
win.document &&
win.document.body &&
- (win.document.body.textContent == body ||
- win.document.body.textContent == popup_body) &&
+ (win.document.body.textContent.trim() == body ||
+ win.document.body.textContent.trim() == popup_body) &&
win.document.readyState == "complete") {
var util = win.QueryInterface(SpecialPowers.Ci.nsIInterfaceRequestor)
diff --git a/docshell/test/navigation/file_scrollRestoration.html b/docshell/test/navigation/file_scrollRestoration.html
index 92e43d7fb..766949d13 100644
--- a/docshell/test/navigation/file_scrollRestoration.html
+++ b/docshell/test/navigation/file_scrollRestoration.html
@@ -40,7 +40,7 @@
document.getElementById("bottom").scrollIntoView();
window.onunload = null; // Should get bfcache behavior.
opener.setTimeout("testWindow.history.back();", 250);
- window.location.href = 'data:text/html,';
+ window.location.href = 'about:blank';
break;
}
case 4: {
@@ -57,7 +57,7 @@
opener.is(history.scrollRestoration, "manual", "Should have the same scrollRestoration mode as before fragment navigation.");
window.onunload = function() {} // Disable bfcache.
opener.setTimeout("is(testWindow.history.scrollRestoration, 'auto'); testWindow.history.back();", 250);
- window.location.href = 'data:text/html,';
+ window.location.href = 'about:blank';
break;
}
case 6: {
diff --git a/docshell/test/navigation/mochitest.ini b/docshell/test/navigation/mochitest.ini
index 764e400a8..1b5f33c7f 100644
--- a/docshell/test/navigation/mochitest.ini
+++ b/docshell/test/navigation/mochitest.ini
@@ -1,6 +1,8 @@
[DEFAULT]
support-files =
NavigationUtils.js
+ navigation_target_url.html
+ navigation_target_popup_url.html
blank.html
file_bug462076_1.html
file_bug462076_2.html
diff --git a/docshell/test/navigation/navigation_target_popup_url.html b/docshell/test/navigation/navigation_target_popup_url.html
new file mode 100644
index 000000000..cfe6de009
--- /dev/null
+++ b/docshell/test/navigation/navigation_target_popup_url.html
@@ -0,0 +1 @@
+<html><body>This is a popup</body></html>
diff --git a/docshell/test/navigation/navigation_target_url.html b/docshell/test/navigation/navigation_target_url.html
new file mode 100644
index 000000000..a485e8133
--- /dev/null
+++ b/docshell/test/navigation/navigation_target_url.html
@@ -0,0 +1 @@
+<html><body>This frame was navigated.</body></html>
diff --git a/docshell/test/navigation/open.html b/docshell/test/navigation/open.html
index 1bb70f865..97eb9b76e 100644
--- a/docshell/test/navigation/open.html
+++ b/docshell/test/navigation/open.html
@@ -3,7 +3,7 @@
<script>
var target = window.location.hash.substring(1);
document.write("target=" + target);
-window.open("data:text/html,<html><body>This is a popup</body></html>", target, "width=10,height=10");
+window.open("navigation_target_popup_url.html", target, "width=10,height=10");
</script>
</body>
</html>
diff --git a/docshell/test/navigation/test_triggeringprincipal_window_open.html b/docshell/test/navigation/test_triggeringprincipal_window_open.html
index d5d7f210b..dbee21777 100644
--- a/docshell/test/navigation/test_triggeringprincipal_window_open.html
+++ b/docshell/test/navigation/test_triggeringprincipal_window_open.html
@@ -13,8 +13,7 @@
/* We call window.open() using different URIs and make sure the triggeringPrincipal
* loadingPrincipal are correct.
* Test1: window.open(http:)
- * Test2: window.open(data:)
- * Test3: window.open(javascript:)
+ * Test2: window.open(javascript:)
*/
const TRIGGERING_PRINCIPAL_URI =
@@ -22,7 +21,7 @@ const TRIGGERING_PRINCIPAL_URI =
SimpleTest.waitForExplicitFinish();
-const NUM_TESTS = 3;
+const NUM_TESTS = 2;
var test_counter = 0;
function checkFinish() {
@@ -54,28 +53,7 @@ httpWin.onload = function() {
}
// ----------------------------------------------------------------------------
-// Test 2: window.open(data:)
-var dataWin = window.open("data:text/html,<html><body>data</body></html>", "_blank", "width=10,height=10");
-dataWin.onload = function() {
- var dataChannel = SpecialPowers.wrap(dataWin.document).docShell.currentDocumentChannel;
- var dataTriggeringPrincipal = dataChannel.loadInfo.triggeringPrincipal.URI.asciiSpec;
- var dataLoadingPrincipal = dataChannel.loadInfo.loadingPrincipal;
-
- is(dataTriggeringPrincipal, TRIGGERING_PRINCIPAL_URI,
- "TriggeringPrincipal for window.open(data:) should be the principal of the document");
-
- is(dataWin.document.referrer, "",
- "Referrer for window.open(data:) should be empty");
-
- is(dataLoadingPrincipal, null,
- "LoadingPrincipal for window.open(data:) should be null");
-
- dataWin.close();
- checkFinish();
-}
-
-// ----------------------------------------------------------------------------
-// Test 3: window.open(javascript:)
+// Test 2: window.open(javascript:)
var jsWin = window.open("javascript:'<html><body>js</body></html>';", "_blank", "width=10,height=10");
jsWin.onload = function() {
var jsChannel = SpecialPowers.wrap(jsWin.document).docShell.currentDocumentChannel;
diff --git a/docshell/test/test_bug598895.html b/docshell/test/test_bug598895.html
index 52b9537be..5cc74e42c 100644
--- a/docshell/test/test_bug598895.html
+++ b/docshell/test/test_bug598895.html
@@ -43,9 +43,8 @@ window.onmessage = function (ev) {
}
}
-var win2 = window.open("data:text/html,<script>window.onload = function() { opener.postMessage('loaded', '*'); }</" + "script><body>Should show</body>");
-
-var win3 = window.open("data:text/html,<script>window.onload = function() { opener.postMessage('loaded', '*'); }</" + "script><body></body>");
+var win2 = window.open("file_bug598895_1.html");
+var win3 = window.open("file_bug598895_2.html");
});
</script>
</pre>
diff --git a/docshell/test/test_bug637644.html b/docshell/test/test_bug637644.html
index d172ada4a..4192fae22 100644
--- a/docshell/test/test_bug637644.html
+++ b/docshell/test/test_bug637644.html
@@ -43,9 +43,8 @@ window.onmessage = function (ev) {
}
}
-var win2 = window.open("data:text/html,<script>window.onload = function() { opener.postMessage('loaded', '*'); }</" + "script><body>Should show</body>", "", "height=500,width=500");
-
-var win3 = window.open("data:text/html,<script>window.onload = function() { opener.postMessage('loaded', '*'); }</" + "script><body></body>", "", "height=500,width=500");
+var win2 = window.open("file_bug637644_1.html", "", "height=500,width=500");
+var win3 = window.open("file_bug637644_2.html", "", "height=500,width=500");
});
</script>
</pre>
diff --git a/docshell/test/test_triggeringprincipal_location_seturi.html b/docshell/test/test_triggeringprincipal_location_seturi.html
new file mode 100644
index 000000000..3b0c7bac5
--- /dev/null
+++ b/docshell/test/test_triggeringprincipal_location_seturi.html
@@ -0,0 +1,102 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+
+<script type="text/javascript">
+
+SimpleTest.waitForExplicitFinish();
+
+const SAME_ORIGIN_URI = "http://mochi.test:8888/tests/docshell/test/dummy_page.html";
+const CROSS_ORIGIN_URI = "http://example.com/tests/docshell/test/dummy_page.html";
+const NUMBER_OF_TESTS = 3;
+let testCounter = 0;
+
+function checkFinish() {
+ testCounter++;
+ if (testCounter < NUMBER_OF_TESTS) {
+ return;
+ }
+ SimpleTest.finish();
+}
+
+// ---- test 1 ----
+
+let myFrame1 = document.createElement("iframe");
+myFrame1.src = SAME_ORIGIN_URI;
+myFrame1.addEventListener("load", checkLoadFrame1);
+document.documentElement.appendChild(myFrame1);
+
+function checkLoadFrame1() {
+ myFrame1.removeEventListener('load', checkLoadFrame1, false);
+ // window.location.href is no longer cross-origin accessible in gecko.
+ is(SpecialPowers.wrap(myFrame1.contentWindow).location.href, SAME_ORIGIN_URI,
+ "initial same origin dummy loaded into frame1");
+
+ SpecialPowers.wrap(myFrame1.contentWindow).location.hash = "#bar";
+ is(SpecialPowers.wrap(myFrame1.contentWindow).location.href, SAME_ORIGIN_URI + "#bar",
+ "initial same origin dummy#bar loaded into iframe1");
+
+ myFrame1.addEventListener("load", checkNavFrame1);
+ myFrame1.src = CROSS_ORIGIN_URI;
+}
+
+function checkNavFrame1() {
+ myFrame1.removeEventListener('load', checkNavFrame1, false);
+ is(SpecialPowers.wrap(myFrame1.contentWindow).location.href, CROSS_ORIGIN_URI,
+ "cross origin dummy loaded into frame1");
+
+ myFrame1.addEventListener("load", checkBackNavFrame1);
+ myFrame1.src = SAME_ORIGIN_URI + "#bar";
+}
+
+function checkBackNavFrame1() {
+ myFrame1.removeEventListener('load', checkBackNavFrame1, false);
+ is(SpecialPowers.wrap(myFrame1.contentWindow).location.href, SAME_ORIGIN_URI + "#bar",
+ "navagiating back to same origin dummy for frame1");
+ checkFinish();
+}
+
+// ---- test 2 ----
+
+let myFrame2 = document.createElement("iframe");
+myFrame2.src = "about:blank";
+myFrame2.addEventListener("load", checkLoadFrame2);
+document.documentElement.appendChild(myFrame2);
+
+function checkLoadFrame2() {
+ myFrame2.removeEventListener('load', checkLoadFrame2, false);
+ is(SpecialPowers.wrap(myFrame2.contentWindow).location.href, "about:blank",
+ "initial about:blank frame loaded");
+
+ myFrame2.contentWindow.location.hash = "#foo";
+ is(SpecialPowers.wrap(myFrame2.contentWindow).location.href, "about:blank#foo",
+ "about:blank#foo frame loaded");
+
+ myFrame2.addEventListener('load', checkHistoryFrame2);
+ myFrame2.src = "about:blank";
+}
+
+function checkHistoryFrame2() {
+ myFrame2.removeEventListener('load', checkHistoryFrame2, false);
+ is(SpecialPowers.wrap(myFrame2.contentWindow).location.href, "about:blank",
+ "about:blank frame loaded again");
+ checkFinish();
+}
+
+// ---- test 3 ----
+
+let myFrame3 = document.createElement("frame");
+document.documentElement.appendChild(myFrame3);
+myFrame3.contentWindow.location.hash = "#foo";
+
+is(myFrame3.contentWindow.location.href, "about:blank#foo",
+ "created history entry with about:blank#foo");
+checkFinish();
+
+</script>
+</body>
+</html>
diff --git a/dom/animation/Animation.cpp b/dom/animation/Animation.cpp
index 6dd583ed1..bd318f79e 100644
--- a/dom/animation/Animation.cpp
+++ b/dom/animation/Animation.cpp
@@ -230,6 +230,10 @@ Animation::SetTimelineNoUpdate(AnimationTimeline* aTimeline)
return;
}
+ StickyTimeDuration activeTime = mEffect
+ ? mEffect->GetComputedTiming().mActiveTime
+ : StickyTimeDuration();
+
RefPtr<AnimationTimeline> oldTimeline = mTimeline;
if (oldTimeline) {
oldTimeline->RemoveAnimation(this);
@@ -240,6 +244,9 @@ Animation::SetTimelineNoUpdate(AnimationTimeline* aTimeline)
mHoldTime.SetNull();
}
+ if (!aTimeline) {
+ MaybeQueueCancelEvent(activeTime);
+ }
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
}
@@ -722,8 +729,10 @@ TimeStamp
Animation::ElapsedTimeToTimeStamp(
const StickyTimeDuration& aElapsedTime) const
{
- return AnimationTimeToTimeStamp(aElapsedTime +
- mEffect->SpecifiedTiming().mDelay);
+ TimeDuration delay = mEffect
+ ? mEffect->SpecifiedTiming().mDelay
+ : TimeDuration();
+ return AnimationTimeToTimeStamp(aElapsedTime + delay);
}
@@ -771,14 +780,28 @@ Animation::CancelNoUpdate()
DispatchPlaybackEvent(NS_LITERAL_STRING("cancel"));
+ StickyTimeDuration activeTime = mEffect
+ ? mEffect->GetComputedTiming().mActiveTime
+ : StickyTimeDuration();
+
mHoldTime.SetNull();
mStartTime.SetNull();
- UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
-
if (mTimeline) {
mTimeline->RemoveAnimation(this);
}
+ MaybeQueueCancelEvent(activeTime);
+
+ // When an animation is cancelled it no longer needs further ticks from the
+ // timeline. However, if we queued a cancel event and this was the last
+ // animation attached to the timeline, the timeline will stop observing the
+ // refresh driver and there may be no subsequent refresh driver tick for
+ // dispatching the queued event.
+ //
+ // By calling UpdateTiming *after* removing ourselves from our timeline, we
+ // ensure the timeline will register with the refresh driver for at least one
+ // more tick.
+ UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
}
void
@@ -819,6 +842,17 @@ Animation::HasLowerCompositeOrderThan(const Animation& aOther) const
return thisTransition->HasLowerCompositeOrderThan(*otherTransition);
}
if (thisTransition || otherTransition) {
+ // Cancelled transitions no longer have an owning element. To be strictly
+ // correct we should store a strong reference to the owning element
+ // so that if we arrive here while sorting cancel events, we can sort
+ // them in the correct order.
+ //
+ // However, given that cancel events are almost always queued
+ // synchronously in some deterministic manner, we can be fairly sure
+ // that cancel events will be dispatched in a deterministic order
+ // (which is our only hard requirement until specs say otherwise).
+ // Furthermore, we only reach here when we have events with equal
+ // timestamps so this is an edge case we can probably ignore for now.
return thisTransition;
}
}
diff --git a/dom/animation/Animation.h b/dom/animation/Animation.h
index c59d7d6ce..3263b30c4 100644
--- a/dom/animation/Animation.h
+++ b/dom/animation/Animation.h
@@ -326,6 +326,16 @@ public:
void NotifyEffectTimingUpdated();
+ /**
+ * Used by subclasses to synchronously queue a cancel event in situations
+ * where the Animation may have been cancelled.
+ *
+ * We need to do this synchronously because after a CSS animation/transition
+ * is canceled, it will be released by its owning element and may not still
+ * exist when we would normally go to queue events on the next tick.
+ */
+ virtual void MaybeQueueCancelEvent(StickyTimeDuration aActiveTime) {};
+
protected:
void SilentlySetCurrentTime(const TimeDuration& aNewCurrentTime);
void SilentlySetPlaybackRate(double aPlaybackRate);
diff --git a/dom/animation/AnimationEffectReadOnly.cpp b/dom/animation/AnimationEffectReadOnly.cpp
index aff28a37b..bf2e2197d 100644
--- a/dom/animation/AnimationEffectReadOnly.cpp
+++ b/dom/animation/AnimationEffectReadOnly.cpp
@@ -127,10 +127,6 @@ AnimationEffectReadOnly::GetComputedTimingAt(
}
const TimeDuration& localTime = aLocalTime.Value();
- // Calculate the time within the active interval.
- // https://w3c.github.io/web-animations/#active-time
- StickyTimeDuration activeTime;
-
StickyTimeDuration beforeActiveBoundary =
std::max(std::min(StickyTimeDuration(aTiming.mDelay), result.mEndTime),
zeroDuration);
@@ -148,7 +144,7 @@ AnimationEffectReadOnly::GetComputedTimingAt(
// The animation isn't active or filling at this time.
return result;
}
- activeTime =
+ result.mActiveTime =
std::max(std::min(StickyTimeDuration(localTime - aTiming.mDelay),
result.mActiveDuration),
zeroDuration);
@@ -159,13 +155,14 @@ AnimationEffectReadOnly::GetComputedTimingAt(
// The animation isn't active or filling at this time.
return result;
}
- activeTime = std::max(StickyTimeDuration(localTime - aTiming.mDelay),
- zeroDuration);
+ result.mActiveTime
+ = std::max(StickyTimeDuration(localTime - aTiming.mDelay),
+ zeroDuration);
} else {
MOZ_ASSERT(result.mActiveDuration != zeroDuration,
"How can we be in the middle of a zero-duration interval?");
result.mPhase = ComputedTiming::AnimationPhase::Active;
- activeTime = localTime - aTiming.mDelay;
+ result.mActiveTime = localTime - aTiming.mDelay;
}
// Convert active time to a multiple of iterations.
@@ -176,7 +173,7 @@ AnimationEffectReadOnly::GetComputedTimingAt(
? 0.0
: result.mIterations;
} else {
- overallProgress = activeTime / result.mDuration;
+ overallProgress = result.mActiveTime / result.mDuration;
}
// Factor in iteration start offset.
@@ -208,7 +205,8 @@ AnimationEffectReadOnly::GetComputedTimingAt(
if (result.mPhase == ComputedTiming::AnimationPhase::After &&
progress == 0.0 &&
result.mIterations != 0.0 &&
- (activeTime != zeroDuration || result.mDuration == zeroDuration)) {
+ (result.mActiveTime != zeroDuration ||
+ result.mDuration == zeroDuration)) {
// The only way we can be in the after phase with a progress of zero and
// a current iteration of zero, is if we have a zero iteration count or
// were clipped using a negative end delay--both of which we should have
diff --git a/dom/animation/ComputedTiming.h b/dom/animation/ComputedTiming.h
index 4a98e3933..b1c6674a5 100644
--- a/dom/animation/ComputedTiming.h
+++ b/dom/animation/ComputedTiming.h
@@ -29,6 +29,8 @@ struct ComputedTiming
// Will equal StickyTimeDuration::Forever() if the animation repeats
// indefinitely.
StickyTimeDuration mActiveDuration;
+ // The time within the active interval.
+ StickyTimeDuration mActiveTime;
// The effect end time in local time (i.e. an offset from the effect's
// start time). Will equal StickyTimeDuration::Forever() if the animation
// plays indefinitely.
@@ -62,12 +64,12 @@ struct ComputedTiming
}
enum class AnimationPhase {
- Null, // Not sampled (null sample time)
+ Idle, // Not sampled (null sample time)
Before, // Sampled prior to the start of the active interval
Active, // Sampled within the active interval
After // Sampled after (or at) the end of the active interval
};
- AnimationPhase mPhase = AnimationPhase::Null;
+ AnimationPhase mPhase = AnimationPhase::Idle;
ComputedTimingFunction::BeforeFlag mBeforeFlag =
ComputedTimingFunction::BeforeFlag::Unset;
diff --git a/dom/animation/test/css-animations/file_event-dispatch.html b/dom/animation/test/css-animations/file_event-dispatch.html
new file mode 100644
index 000000000..266205bc3
--- /dev/null
+++ b/dom/animation/test/css-animations/file_event-dispatch.html
@@ -0,0 +1,252 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>Tests for CSS animation event dispatch</title>
+<link rel="help" href="https://drafts.csswg.org/css-animations-2/#event-dispatch"/>
+<script src="../testcommon.js"></script>
+<style>
+ @keyframes anim {
+ from { margin-left: 0px; }
+ to { margin-left: 100px; }
+ }
+</style>
+<body>
+<script>
+'use strict';
+
+/**
+ * Helper class to record the elapsedTime member of each event.
+ * The EventWatcher class in testharness.js allows us to wait on
+ * multiple events in a certain order but only records the event
+ * parameters of the most recent event.
+ */
+function AnimationEventHandler(target) {
+ this.target = target;
+ this.target.onanimationstart = function(evt) {
+ this.animationstart = evt.elapsedTime;
+ }.bind(this);
+ this.target.onanimationiteration = function(evt) {
+ this.animationiteration = evt.elapsedTime;
+ }.bind(this);
+ this.target.onanimationend = function(evt) {
+ this.animationend = evt.elapsedTime;
+ }.bind(this);
+}
+AnimationEventHandler.prototype.clear = function() {
+ this.animationstart = undefined;
+ this.animationiteration = undefined;
+ this.animationend = undefined;
+}
+
+function setupAnimation(t, animationStyle) {
+ var div = addDiv(t, { style: "animation: " + animationStyle });
+ var watcher = new EventWatcher(t, div, [ 'animationstart',
+ 'animationiteration',
+ 'animationend' ]);
+ var handler = new AnimationEventHandler(div);
+ var animation = div.getAnimations()[0];
+
+ return [animation, watcher, handler, div];
+}
+
+promise_test(function(t) {
+ // Add 1ms delay to ensure that the delay is not included in the elapsedTime.
+ const [animation, watcher] = setupAnimation(t, 'anim 100s 1ms');
+
+ return watcher.wait_for('animationstart').then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Idle -> Active');
+
+promise_test(function(t) {
+ const [animation, watcher, handler] = setupAnimation(t, 'anim 100s');
+
+ // Seek to After phase.
+ animation.finish();
+ return watcher.wait_for([ 'animationstart',
+ 'animationend' ]).then(function() {
+ assert_equals(handler.animationstart, 0.0);
+ assert_equals(handler.animationend, 100);
+ });
+}, 'Idle -> After');
+
+promise_test(function(t) {
+ const [animation, watcher, handler] =
+ setupAnimation(t, 'anim 100s 100s paused');
+
+ return animation.ready.then(function() {
+ // Seek to Active phase.
+ animation.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for('animationstart');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Before -> Active');
+
+promise_test(function(t) {
+ const [animation, watcher, handler] =
+ setupAnimation(t, 'anim 100s 100s paused');
+
+ return animation.ready.then(function() {
+ // Seek to After phase.
+ animation.finish();
+ return watcher.wait_for([ 'animationstart', 'animationend' ]);
+ }).then(function(evt) {
+ assert_equals(handler.animationstart, 0.0);
+ assert_equals(handler.animationend, 100.0);
+ });
+}, 'Before -> After');
+
+promise_test(function(t) {
+ const [animation, watcher, handler] =
+ setupAnimation(t, 'anim 100s 100s paused');
+
+ // Seek to Active phase.
+ animation.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for('animationstart').then(function() {
+ // Seek to Before phase.
+ animation.currentTime = 0;
+ return watcher.wait_for('animationend');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Active -> Before');
+
+promise_test(function(t) {
+ const [animation, watcher, handler] = setupAnimation(t, 'anim 100s paused');
+
+ return watcher.wait_for('animationstart').then(function(evt) {
+ // Seek to After phase.
+ animation.finish();
+ return watcher.wait_for('animationend');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 100.0);
+ });
+}, 'Active -> After');
+
+promise_test(function(t) {
+ const [animation, watcher, handler] =
+ setupAnimation(t, 'anim 100s 100s paused');
+
+ // Seek to After phase.
+ animation.finish();
+ return watcher.wait_for([ 'animationstart',
+ 'animationend' ]).then(function() {
+ // Seek to Before phase.
+ animation.currentTime = 0;
+ handler.clear();
+ return watcher.wait_for([ 'animationstart', 'animationend' ]);
+ }).then(function() {
+ assert_equals(handler.animationstart, 100.0);
+ assert_equals(handler.animationend, 0.0);
+ });
+}, 'After -> Before');
+
+promise_test(function(t) {
+ const [animation, watcher, handler] =
+ setupAnimation(t, 'anim 100s 100s paused');
+
+ // Seek to After phase.
+ animation.finish();
+ return watcher.wait_for([ 'animationstart',
+ 'animationend' ]).then(function() {
+ // Seek to Active phase.
+ animation.currentTime = 100 * MS_PER_SEC;
+ handler.clear();
+ return watcher.wait_for('animationstart');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 100.0);
+ });
+}, 'After -> Active');
+
+promise_test(function(t) {
+ const [animation, watcher, handler]
+ = setupAnimation(t, 'anim 100s 100s 3 paused');
+
+ return animation.ready.then(function() {
+ // Seek to iteration 0 (no animationiteration event should be dispatched)
+ animation.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for('animationstart');
+ }).then(function(evt) {
+ // Seek to iteration 2
+ animation.currentTime = 300 * MS_PER_SEC;
+ handler.clear();
+ return watcher.wait_for('animationiteration');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 200);
+ // Seek to After phase (no animationiteration event should be dispatched)
+ animation.currentTime = 400 * MS_PER_SEC;
+ return watcher.wait_for('animationend');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 300);
+ });
+}, 'Active -> Active (forwards)');
+
+promise_test(function(t) {
+ const [animation, watcher, handler] = setupAnimation(t, 'anim 100s 100s 3');
+
+ // Seek to After phase.
+ animation.finish();
+ return watcher.wait_for([ 'animationstart',
+ 'animationend' ]).then(function() {
+ // Seek to iteration 2 (no animationiteration event should be dispatched)
+ animation.pause();
+ animation.currentTime = 300 * MS_PER_SEC;
+ return watcher.wait_for('animationstart');
+ }).then(function() {
+ // Seek to mid of iteration 0 phase.
+ animation.currentTime = 200 * MS_PER_SEC;
+ return watcher.wait_for('animationiteration');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 200.0);
+ // Seek to before phase (no animationiteration event should be dispatched)
+ animation.currentTime = 0;
+ return watcher.wait_for('animationend');
+ });
+}, 'Active -> Active (backwards)');
+
+promise_test(function(t) {
+ const [animation, watcher, handler, div] =
+ setupAnimation(t, 'anim 100s paused');
+ return watcher.wait_for('animationstart').then(function(evt) {
+ // Seek to Idle phase.
+ div.style.display = 'none';
+ flushComputedStyle(div);
+
+ // FIXME: bug 1302648: Add test for animationcancel event here.
+
+ // Restart this animation.
+ div.style.display = '';
+ return watcher.wait_for('animationstart');
+ });
+}, 'Active -> Idle -> Active: animationstart is fired by restarting animation');
+
+promise_test(function(t) {
+ const [animation, watcher, handler, div] =
+ setupAnimation(t, 'anim 100s 100s 2 paused');
+
+ // Make After.
+ animation.finish();
+ return watcher.wait_for([ 'animationstart',
+ 'animationend' ]).then(function(evt) {
+ animation.playbackRate = -1;
+ return watcher.wait_for('animationstart');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 200);
+ // Seek to 1st iteration
+ animation.currentTime = 200 * MS_PER_SEC - 1;
+ return watcher.wait_for('animationiteration');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 100);
+ // Seek to before
+ animation.currentTime = 100 * MS_PER_SEC - 1;
+ return watcher.wait_for('animationend');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0);
+ assert_equals(animation.playState, 'running'); // delay
+ });
+}, 'Negative playbackRate sanity test(Before -> Active -> Before)');
+
+done();
+</script>
+</body>
+</html>
diff --git a/dom/animation/test/css-animations/file_event-order.html b/dom/animation/test/css-animations/file_event-order.html
new file mode 100644
index 000000000..da78b6541
--- /dev/null
+++ b/dom/animation/test/css-animations/file_event-order.html
@@ -0,0 +1,160 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>Tests for CSS animation event order</title>
+<link rel="help" href="https://drafts.csswg.org/css-animations-2/#event-dispatch"/>
+<script src="../testcommon.js"></script>
+<style>
+ @keyframes anim {
+ from { margin-left: 0px; }
+ to { margin-left: 100px; }
+ }
+</style>
+<body>
+<script type='text/javascript'>
+'use strict';
+
+/**
+ * Asserts that the set of actual and received events match.
+ * @param actualEvents An array of the received AnimationEvent objects.
+ * @param expectedEvents A series of array objects representing the expected
+ * events, each having the form:
+ * [ event type, target element, elapsed time ]
+ */
+function checkEvents(actualEvents, ...expectedEvents) {
+ assert_equals(actualEvents.length, expectedEvents.length,
+ `Number of actual events (${actualEvents.length}: \
+${actualEvents.map(event => event.type).join(', ')}) should match expected \
+events (${expectedEvents.map(event => event.type).join(', ')})`);
+
+ actualEvents.forEach((actualEvent, i) => {
+ assert_equals(expectedEvents[i][0], actualEvent.type,
+ 'Event type should match');
+ assert_equals(expectedEvents[i][1], actualEvent.target,
+ 'Event target should match');
+ assert_equals(expectedEvents[i][2], actualEvent.elapsedTime,
+ 'Event\'s elapsed time should match');
+ });
+}
+
+function setupAnimation(t, animationStyle, receiveEvents) {
+ const div = addDiv(t, { style: "animation: " + animationStyle });
+ const watcher = new EventWatcher(t, div, [ 'animationstart',
+ 'animationiteration',
+ 'animationend' ]);
+
+ ['start', 'iteration', 'end'].forEach(name => {
+ div['onanimation' + name] = function(evt) {
+ receiveEvents.push({ type: evt.type,
+ target: evt.target,
+ elapsedTime: evt.elapsedTime });
+ }.bind(this);
+ });
+
+ const animation = div.getAnimations()[0];
+
+ return [animation, watcher, div];
+}
+
+promise_test(function(t) {
+ let events = [];
+ const [animation1, watcher1, div1] =
+ setupAnimation(t, 'anim 100s 2 paused', events);
+ const [animation2, watcher2, div2] =
+ setupAnimation(t, 'anim 100s 2 paused', events);
+
+ return Promise.all([ watcher1.wait_for('animationstart'),
+ watcher2.wait_for('animationstart') ]).then(function() {
+ checkEvents(events, ['animationstart', div1, 0],
+ ['animationstart', div2, 0]);
+
+ events.length = 0; // Clear received event array
+
+ animation1.currentTime = 100 * MS_PER_SEC;
+ animation2.currentTime = 100 * MS_PER_SEC;
+ return Promise.all([ watcher1.wait_for('animationiteration'),
+ watcher2.wait_for('animationiteration') ]);
+ }).then(function() {
+ checkEvents(events, ['animationiteration', div1, 100],
+ ['animationiteration', div2, 100]);
+
+ events.length = 0; // Clear received event array
+
+ animation1.finish();
+ animation2.finish();
+
+ return Promise.all([ watcher1.wait_for('animationend'),
+ watcher2.wait_for('animationend') ]);
+ }).then(function() {
+ checkEvents(events, ['animationend', div1, 200],
+ ['animationend', div2, 200]);
+ });
+}, 'Test same events are ordered by elements.');
+
+promise_test(function(t) {
+ let events = [];
+ const [animation1, watcher1, div1] =
+ setupAnimation(t, 'anim 200s 400s', events);
+ const [animation2, watcher2, div2] =
+ setupAnimation(t, 'anim 300s 2', events);
+
+ return watcher2.wait_for('animationstart').then(function(evt) {
+ animation1.currentTime = 400 * MS_PER_SEC;
+ animation2.currentTime = 400 * MS_PER_SEC;
+
+ events.length = 0; // Clear received event array
+
+ return Promise.all([ watcher1.wait_for('animationstart'),
+ watcher2.wait_for('animationiteration') ]);
+ }).then(function() {
+ checkEvents(events, ['animationiteration', div2, 300],
+ ['animationstart', div1, 0]);
+ });
+}, 'Test start and iteration events are ordered by time.');
+
+promise_test(function(t) {
+ let events = [];
+ const [animation1, watcher1, div1] =
+ setupAnimation(t, 'anim 150s', events);
+ const [animation2, watcher2, div2] =
+ setupAnimation(t, 'anim 100s 2', events);
+
+ return Promise.all([ watcher1.wait_for('animationstart'),
+ watcher2.wait_for('animationstart') ]).then(function() {
+ animation1.currentTime = 150 * MS_PER_SEC;
+ animation2.currentTime = 150 * MS_PER_SEC;
+
+ events.length = 0; // Clear received event array
+
+ return Promise.all([ watcher1.wait_for('animationend'),
+ watcher2.wait_for('animationiteration') ]);
+ }).then(function() {
+ checkEvents(events, ['animationiteration', div2, 100],
+ ['animationend', div1, 150]);
+ });
+}, 'Test iteration and end events are ordered by time.');
+
+promise_test(function(t) {
+ let events = [];
+ const [animation1, watcher1, div1] =
+ setupAnimation(t, 'anim 100s 100s', events);
+ const [animation2, watcher2, div2] =
+ setupAnimation(t, 'anim 100s 2', events);
+
+ animation1.finish();
+ animation2.finish();
+
+ return Promise.all([ watcher1.wait_for([ 'animationstart',
+ 'animationend' ]),
+ watcher2.wait_for([ 'animationstart',
+ 'animationend' ]) ]).then(function() {
+ checkEvents(events, ['animationstart', div2, 0],
+ ['animationstart', div1, 0],
+ ['animationend', div1, 100],
+ ['animationend', div2, 200]);
+ });
+}, 'Test start and end events are sorted correctly when fired simultaneously');
+
+done();
+</script>
+</body>
+</html>
diff --git a/dom/animation/test/css-animations/test_event-dispatch.html b/dom/animation/test/css-animations/test_event-dispatch.html
new file mode 100644
index 000000000..de3be0301
--- /dev/null
+++ b/dom/animation/test/css-animations/test_event-dispatch.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset=utf-8>
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id="log"></div>
+<script>
+'use strict';
+setup({explicit_done: true});
+SpecialPowers.pushPrefEnv(
+ { "set": [["dom.animations-api.core.enabled", true]]},
+ function() {
+ window.open("file_event-dispatch.html");
+ });
+</script>
+</html>
diff --git a/dom/animation/test/css-transitions/test_csstransition-events.html b/dom/animation/test/css-animations/test_event-order.html
index 92559ad67..57f1f3876 100644
--- a/dom/animation/test/css-transitions/test_csstransition-events.html
+++ b/dom/animation/test/css-animations/test_event-order.html
@@ -9,6 +9,7 @@ setup({explicit_done: true});
SpecialPowers.pushPrefEnv(
{ "set": [["dom.animations-api.core.enabled", true]]},
function() {
- window.open("file_csstransition-events.html");
+ window.open("file_event-order.html");
});
</script>
+</html>
diff --git a/dom/animation/test/css-transitions/file_animation-cancel.html b/dom/animation/test/css-transitions/file_animation-cancel.html
index 6094b383f..71f02fb11 100644
--- a/dom/animation/test/css-transitions/file_animation-cancel.html
+++ b/dom/animation/test/css-transitions/file_animation-cancel.html
@@ -11,13 +11,12 @@ promise_test(function(t) {
div.style.transition = 'margin-left 100s';
div.style.marginLeft = '1000px';
- flushComputedStyle(div);
- var animation = div.getAnimations()[0];
- return animation.ready.then(waitForFrame).then(function() {
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(waitForFrame).then(function() {
assert_not_equals(getComputedStyle(div).marginLeft, '1000px',
'transform style is animated before cancelling');
- animation.cancel();
+ transition.cancel();
assert_equals(getComputedStyle(div).marginLeft, div.style.marginLeft,
'transform style is no longer animated after cancelling');
});
@@ -29,45 +28,21 @@ promise_test(function(t) {
div.style.transition = 'margin-left 100s';
div.style.marginLeft = '1000px';
- flushComputedStyle(div);
-
- div.addEventListener('transitionend', function() {
- assert_unreached('Got unexpected end event on cancelled transition');
- });
-
- var animation = div.getAnimations()[0];
- return animation.ready.then(function() {
- // Seek to just before the end then cancel
- animation.currentTime = 99.9 * 1000;
- animation.cancel();
- // Then wait a couple of frames and check that no event was dispatched
- return waitForAnimationFrames(2);
- });
-}, 'Cancelled CSS transitions do not dispatch events');
-
-promise_test(function(t) {
- var div = addDiv(t, { style: 'margin-left: 0px' });
- flushComputedStyle(div);
-
- div.style.transition = 'margin-left 100s';
- div.style.marginLeft = '1000px';
- flushComputedStyle(div);
-
- var animation = div.getAnimations()[0];
- return animation.ready.then(function() {
- animation.cancel();
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(function() {
+ transition.cancel();
assert_equals(getComputedStyle(div).marginLeft, '1000px',
'margin-left style is not animated after cancelling');
- animation.play();
+ transition.play();
assert_equals(getComputedStyle(div).marginLeft, '0px',
'margin-left style is animated after re-starting transition');
- return animation.ready;
+ return transition.ready;
}).then(function() {
- assert_equals(animation.playState, 'running',
+ assert_equals(transition.playState, 'running',
'Transition succeeds in running after being re-started');
});
-}, 'After cancelling a transition, it can still be re-used');
+}, 'After canceling a transition, it can still be re-used');
promise_test(function(t) {
var div = addDiv(t, { style: 'margin-left: 0px' });
@@ -75,20 +50,19 @@ promise_test(function(t) {
div.style.transition = 'margin-left 100s';
div.style.marginLeft = '1000px';
- flushComputedStyle(div);
- var animation = div.getAnimations()[0];
- return animation.ready.then(function() {
- animation.finish();
- animation.cancel();
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(function() {
+ transition.finish();
+ transition.cancel();
assert_equals(getComputedStyle(div).marginLeft, '1000px',
'margin-left style is not animated after cancelling');
- animation.play();
+ transition.play();
assert_equals(getComputedStyle(div).marginLeft, '0px',
'margin-left style is animated after re-starting transition');
- return animation.ready;
+ return transition.ready;
}).then(function() {
- assert_equals(animation.playState, 'running',
+ assert_equals(transition.playState, 'running',
'Transition succeeds in running after being re-started');
});
}, 'After cancelling a finished transition, it can still be re-used');
@@ -99,10 +73,9 @@ test(function(t) {
div.style.transition = 'margin-left 100s';
div.style.marginLeft = '1000px';
- flushComputedStyle(div);
- var animation = div.getAnimations()[0];
- animation.cancel();
+ var transition = div.getAnimations()[0];
+ transition.cancel();
assert_equals(getComputedStyle(div).marginLeft, '1000px',
'margin-left style is not animated after cancelling');
@@ -113,7 +86,7 @@ test(function(t) {
assert_equals(getComputedStyle(div).marginLeft, '1000px',
'margin-left style is still not animated after updating'
+ ' transition-duration');
- assert_equals(animation.playState, 'idle',
+ assert_equals(transition.playState, 'idle',
'Transition is still idle after updating transition-duration');
}, 'After cancelling a transition, updating transition properties doesn\'t make'
+ ' it live again');
@@ -124,15 +97,14 @@ promise_test(function(t) {
div.style.transition = 'margin-left 100s';
div.style.marginLeft = '1000px';
- flushComputedStyle(div);
- var animation = div.getAnimations()[0];
- return animation.ready.then(function() {
- assert_equals(animation.playState, 'running');
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(function() {
+ assert_equals(transition.playState, 'running');
div.style.display = 'none';
return waitForFrame();
}).then(function() {
- assert_equals(animation.playState, 'idle');
+ assert_equals(transition.playState, 'idle');
assert_equals(getComputedStyle(div).marginLeft, '1000px');
});
}, 'Setting display:none on an element cancels its transitions');
@@ -147,19 +119,115 @@ promise_test(function(t) {
childDiv.style.transition = 'margin-left 100s';
childDiv.style.marginLeft = '1000px';
- flushComputedStyle(childDiv);
- var animation = childDiv.getAnimations()[0];
- return animation.ready.then(function() {
- assert_equals(animation.playState, 'running');
+ var transition = childDiv.getAnimations()[0];
+ return transition.ready.then(function() {
+ assert_equals(transition.playState, 'running');
parentDiv.style.display = 'none';
return waitForFrame();
}).then(function() {
- assert_equals(animation.playState, 'idle');
+ assert_equals(transition.playState, 'idle');
assert_equals(getComputedStyle(childDiv).marginLeft, '1000px');
});
}, 'Setting display:none cancels transitions on a child element');
+promise_test(function(t) {
+ var div = addDiv(t, { style: 'margin-left: 0px' });
+ flushComputedStyle(div);
+
+ div.style.transition = 'margin-left 100s';
+ div.style.marginLeft = '1000px';
+
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(function() {
+ assert_equals(transition.playState, 'running');
+ // Set an unrecognized property value
+ div.style.transitionProperty = 'none';
+ flushComputedStyle(div);
+ return waitForFrame();
+ }).then(function() {
+ assert_equals(transition.playState, 'idle');
+ assert_equals(getComputedStyle(div).marginLeft, '1000px');
+ });
+}, 'Removing a property from transition-property cancels transitions on that '+
+ 'property');
+
+promise_test(function(t) {
+ var div = addDiv(t, { style: 'margin-left: 0px' });
+ flushComputedStyle(div);
+
+ div.style.transition = 'margin-left 100s';
+ div.style.marginLeft = '1000px';
+
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(function() {
+ assert_equals(transition.playState, 'running');
+ div.style.transition = 'margin-top 10s -10s'; // combined duration is zero
+ flushComputedStyle(div);
+ return waitForFrame();
+ }).then(function() {
+ assert_equals(transition.playState, 'idle');
+ assert_equals(getComputedStyle(div).marginLeft, '1000px');
+ });
+}, 'Setting zero combined duration');
+
+promise_test(function(t) {
+ var div = addDiv(t, { style: 'margin-left: 0px' });
+ flushComputedStyle(div);
+
+ div.style.transition = 'margin-left 100s';
+ div.style.marginLeft = '1000px';
+
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(function() {
+ assert_equals(transition.playState, 'running');
+ div.style.marginLeft = '2000px';
+ flushComputedStyle(div);
+ return waitForFrame();
+ }).then(function() {
+ assert_equals(transition.playState, 'idle');
+ });
+}, 'Changing style to another interpolable value cancels the original ' +
+ 'transition');
+
+promise_test(function(t) {
+ var div = addDiv(t, { style: 'margin-left: 0px' });
+ flushComputedStyle(div);
+
+ div.style.transition = 'margin-left 100s';
+ div.style.marginLeft = '1000px';
+
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(function() {
+ assert_equals(transition.playState, 'running');
+ div.style.marginLeft = 'auto';
+ flushComputedStyle(div);
+ return waitForFrame();
+ }).then(function() {
+ assert_equals(div.getAnimations().length, 0,
+ 'There should be no transitions');
+ assert_equals(transition.playState, 'idle');
+ });
+}, 'An after-change style value can\'t be interpolated');
+
+promise_test(function(t) {
+ var div = addDiv(t, { style: 'margin-left: 0px' });
+ flushComputedStyle(div);
+
+ div.style.transition = 'margin-left 100s';
+ div.style.marginLeft = '1000px';
+
+ var transition = div.getAnimations()[0];
+ return transition.ready.then(function() {
+ assert_equals(transition.playState, 'running');
+ div.style.marginLeft = '0px';
+ flushComputedStyle(div);
+ return waitForFrame();
+ }).then(function() {
+ assert_equals(transition.playState, 'idle');
+ });
+}, 'Reversing a running transition cancels the original transition');
+
done();
</script>
</body>
diff --git a/dom/animation/test/css-transitions/file_csstransition-events.html b/dom/animation/test/css-transitions/file_csstransition-events.html
deleted file mode 100644
index 5011bc130..000000000
--- a/dom/animation/test/css-transitions/file_csstransition-events.html
+++ /dev/null
@@ -1,223 +0,0 @@
-<!doctype html>
-<meta charset=utf-8>
-<title>Tests for CSS-Transition events</title>
-<link rel="help" href="https://drafts.csswg.org/css-transitions-2/#transition-events">
-<script src="../testcommon.js"></script>
-<body>
-<script>
-'use strict';
-
-/**
- * Helper class to record the elapsedTime member of each event.
- * The EventWatcher class in testharness.js allows us to wait on
- * multiple events in a certain order but only records the event
- * parameters of the most recent event.
- */
-function TransitionEventHandler(target) {
- this.target = target;
- this.target.ontransitionrun = function(evt) {
- this.transitionrun = evt.elapsedTime;
- }.bind(this);
- this.target.ontransitionstart = function(evt) {
- this.transitionstart = evt.elapsedTime;
- }.bind(this);
- this.target.ontransitionend = function(evt) {
- this.transitionend = evt.elapsedTime;
- }.bind(this);
-}
-
-TransitionEventHandler.prototype.clear = function() {
- this.transitionrun = undefined;
- this.transitionstart = undefined;
- this.transitionend = undefined;
-};
-
-function setupTransition(t, transitionStyle) {
- var div, watcher, handler, transition;
- transitionStyle = transitionStyle || 'transition: margin-left 100s 100s';
- div = addDiv(t, { style: transitionStyle });
- watcher = new EventWatcher(t, div, [ 'transitionrun',
- 'transitionstart',
- 'transitionend' ]);
- handler = new TransitionEventHandler(div);
- flushComputedStyle(div);
-
- div.style.marginLeft = '100px';
- flushComputedStyle(div);
-
- transition = div.getAnimations()[0];
-
- return [transition, watcher, handler];
-}
-
-// On the next frame (i.e. when events are queued), whether or not the
-// transition is still pending depends on the implementation.
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- return watcher.wait_for('transitionrun').then(function(evt) {
- assert_equals(evt.elapsedTime, 0.0);
- });
-}, 'Idle -> Pending or Before');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- // Force the transition to leave the idle phase
- transition.startTime = document.timeline.currentTime;
- return watcher.wait_for('transitionrun').then(function(evt) {
- assert_equals(evt.elapsedTime, 0.0);
- });
-}, 'Idle -> Before');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- // Seek to Active phase.
- transition.currentTime = 100 * MS_PER_SEC;
- transition.pause();
- return watcher.wait_for([ 'transitionrun',
- 'transitionstart' ]).then(function(evt) {
- assert_equals(handler.transitionrun, 0.0);
- assert_equals(handler.transitionstart, 0.0);
- });
-}, 'Idle or Pending -> Active');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- // Seek to After phase.
- transition.finish();
- return watcher.wait_for([ 'transitionrun',
- 'transitionstart',
- 'transitionend' ]).then(function(evt) {
- assert_equals(handler.transitionrun, 0.0);
- assert_equals(handler.transitionstart, 0.0);
- assert_equals(handler.transitionend, 100.0);
- });
-}, 'Idle or Pending -> After');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
-
- return Promise.all([ watcher.wait_for('transitionrun'),
- transition.ready ]).then(function() {
- transition.currentTime = 100 * MS_PER_SEC;
- return watcher.wait_for('transitionstart');
- }).then(function() {
- assert_equals(handler.transitionstart, 0.0);
- });
-}, 'Before -> Active');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- return Promise.all([ watcher.wait_for('transitionrun'),
- transition.ready ]).then(function() {
- // Seek to After phase.
- transition.currentTime = 200 * MS_PER_SEC;
- return watcher.wait_for([ 'transitionstart', 'transitionend' ]);
- }).then(function(evt) {
- assert_equals(handler.transitionstart, 0.0);
- assert_equals(handler.transitionend, 100.0);
- });
-}, 'Before -> After');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- // Seek to Active phase.
- transition.currentTime = 100 * MS_PER_SEC;
- return watcher.wait_for([ 'transitionrun',
- 'transitionstart' ]).then(function(evt) {
- // Seek to Before phase.
- transition.currentTime = 0;
- return watcher.wait_for('transitionend');
- }).then(function(evt) {
- assert_equals(evt.elapsedTime, 0.0);
- });
-}, 'Active -> Before');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- // Seek to Active phase.
- transition.currentTime = 100 * MS_PER_SEC;
- return watcher.wait_for([ 'transitionrun',
- 'transitionstart' ]).then(function(evt) {
- // Seek to After phase.
- transition.currentTime = 200 * MS_PER_SEC;
- return watcher.wait_for('transitionend');
- }).then(function(evt) {
- assert_equals(evt.elapsedTime, 100.0);
- });
-}, 'Active -> After');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- // Seek to After phase.
- transition.finish();
- return watcher.wait_for([ 'transitionrun',
- 'transitionstart',
- 'transitionend' ]).then(function(evt) {
- // Seek to Before phase.
- transition.currentTime = 0;
- return watcher.wait_for([ 'transitionstart', 'transitionend' ]);
- }).then(function(evt) {
- assert_equals(handler.transitionstart, 100.0);
- assert_equals(handler.transitionend, 0.0);
- });
-}, 'After -> Before');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
- // Seek to After phase.
- transition.finish();
- return watcher.wait_for([ 'transitionrun',
- 'transitionstart',
- 'transitionend' ]).then(function(evt) {
- // Seek to Active phase.
- transition.currentTime = 100 * MS_PER_SEC;
- return watcher.wait_for('transitionstart');
- }).then(function(evt) {
- assert_equals(evt.elapsedTime, 100.0);
- });
-}, 'After -> Active');
-
-promise_test(function(t) {
- var [transition, watcher, handler] =
- setupTransition(t, 'transition: margin-left 100s -50s');
-
- return watcher.wait_for([ 'transitionrun',
- 'transitionstart' ]).then(function() {
- assert_equals(handler.transitionrun, 50.0);
- assert_equals(handler.transitionstart, 50.0);
- transition.finish();
- return watcher.wait_for('transitionend');
- }).then(function(evt) {
- assert_equals(evt.elapsedTime, 100.0);
- });
-}, 'Calculating the interval start and end time with negative start delay.');
-
-promise_test(function(t) {
- var [transition, watcher, handler] = setupTransition(t);
-
- return watcher.wait_for('transitionrun').then(function(evt) {
- // We can't set the end delay via generated effect timing.
- // Because CSS-Transition use the AnimationEffectTimingReadOnly.
- transition.effect = new KeyframeEffect(handler.target,
- { marginleft: [ '0px', '100px' ]},
- { duration: 100 * MS_PER_SEC,
- endDelay: -50 * MS_PER_SEC });
- // Seek to Before and play.
- transition.cancel();
- transition.play();
- return watcher.wait_for('transitionstart');
- }).then(function() {
- assert_equals(handler.transitionstart, 0.0);
-
- // Seek to After phase.
- transition.finish();
- return watcher.wait_for('transitionend');
- }).then(function(evt) {
- assert_equals(evt.elapsedTime, 50.0);
- });
-}, 'Calculating the interval start and end time with negative end delay.');
-
-done();
-</script>
-</body>
-</html>
diff --git a/dom/animation/test/css-transitions/file_event-dispatch.html b/dom/animation/test/css-transitions/file_event-dispatch.html
new file mode 100644
index 000000000..7140cda36
--- /dev/null
+++ b/dom/animation/test/css-transitions/file_event-dispatch.html
@@ -0,0 +1,474 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>Tests for CSS-Transition events</title>
+<link rel="help" href="https://drafts.csswg.org/css-transitions-2/#transition-events">
+<script src="../testcommon.js"></script>
+<body>
+<script>
+'use strict';
+
+/**
+ * Helper class to record the elapsedTime member of each event.
+ * The EventWatcher class in testharness.js allows us to wait on
+ * multiple events in a certain order but only records the event
+ * parameters of the most recent event.
+ */
+function TransitionEventHandler(target) {
+ this.target = target;
+ this.target.ontransitionrun = function(evt) {
+ this.transitionrun = evt.elapsedTime;
+ }.bind(this);
+ this.target.ontransitionstart = function(evt) {
+ this.transitionstart = evt.elapsedTime;
+ }.bind(this);
+ this.target.ontransitionend = function(evt) {
+ this.transitionend = evt.elapsedTime;
+ }.bind(this);
+ this.target.ontransitioncancel = function(evt) {
+ this.transitioncancel = evt.elapsedTime;
+ }.bind(this);
+}
+
+TransitionEventHandler.prototype.clear = function() {
+ this.transitionrun = undefined;
+ this.transitionstart = undefined;
+ this.transitionend = undefined;
+ this.transitioncancel = undefined;
+};
+
+function setupTransition(t, transitionStyle) {
+ var div = addDiv(t, { style: 'transition: ' + transitionStyle });
+ var watcher = new EventWatcher(t, div, [ 'transitionrun',
+ 'transitionstart',
+ 'transitionend',
+ 'transitioncancel' ]);
+ flushComputedStyle(div);
+
+ div.style.marginLeft = '100px';
+ var transition = div.getAnimations()[0];
+
+ return [transition, watcher, div];
+}
+
+// On the next frame (i.e. when events are queued), whether or not the
+// transition is still pending depends on the implementation.
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s 100s');
+ return watcher.wait_for('transitionrun').then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Idle -> Pending or Before');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s 100s');
+ // Force the transition to leave the idle phase
+ transition.startTime = document.timeline.currentTime;
+ return watcher.wait_for('transitionrun').then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Idle -> Before');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+ var handler = new TransitionEventHandler(div);
+
+ // Seek to Active phase.
+ transition.currentTime = 100 * MS_PER_SEC;
+ transition.pause();
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ assert_equals(handler.transitionrun, 0.0);
+ assert_equals(handler.transitionstart, 0.0);
+ });
+}, 'Idle or Pending -> Active');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+ var handler = new TransitionEventHandler(div);
+
+ // Seek to After phase.
+ transition.finish();
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart',
+ 'transitionend' ]).then(function(evt) {
+ assert_equals(handler.transitionrun, 0.0);
+ assert_equals(handler.transitionstart, 0.0);
+ assert_equals(handler.transitionend, 100.0);
+ });
+}, 'Idle or Pending -> After');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+
+ return Promise.all([ watcher.wait_for('transitionrun'),
+ transition.ready ]).then(function() {
+ // Make idle
+ div.style.display = 'none';
+ flushComputedStyle(div);
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Before -> Idle (display: none)');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s 100s');
+
+ return Promise.all([ watcher.wait_for('transitionrun'),
+ transition.ready ]).then(function() {
+ // Make idle
+ transition.timeline = null;
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Before -> Idle (Animation.timeline = null)');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s 100s');
+
+ return Promise.all([ watcher.wait_for('transitionrun'),
+ transition.ready ]).then(function() {
+ transition.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for('transitionstart');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Before -> Active');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+ var handler = new TransitionEventHandler(div);
+
+ return Promise.all([ watcher.wait_for('transitionrun'),
+ transition.ready ]).then(function() {
+ // Seek to After phase.
+ transition.currentTime = 200 * MS_PER_SEC;
+ return watcher.wait_for([ 'transitionstart', 'transitionend' ]);
+ }).then(function(evt) {
+ assert_equals(handler.transitionstart, 0.0);
+ assert_equals(handler.transitionend, 100.0);
+ });
+}, 'Before -> After');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s');
+
+ // Seek to Active start position.
+ transition.pause();
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Make idle
+ div.style.display = 'none';
+ flushComputedStyle(div);
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Active -> Idle, no delay (display: none)');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s');
+
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Make idle
+ transition.currentTime = 0;
+ transition.timeline = null;
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Active -> Idle, no delay (Animation.timeline = null)');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+ // Pause so the currentTime is fixed and we can accurately compare the event
+ // time in transition cancel events.
+ transition.pause();
+
+ // Seek to Active phase.
+ transition.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Make idle
+ div.style.display = 'none';
+ flushComputedStyle(div);
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Active -> Idle, with positive delay (display: none)');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s 100s');
+
+ // Seek to Active phase.
+ transition.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Make idle
+ transition.currentTime = 100 * MS_PER_SEC;
+ transition.timeline = null;
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Active -> Idle, with positive delay (Animation.timeline = null)');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s -50s');
+
+ // Pause so the currentTime is fixed and we can accurately compare the event
+ // time in transition cancel events.
+ transition.pause();
+
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Make idle
+ div.style.display = 'none';
+ flushComputedStyle(div);
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 50.0);
+ });
+}, 'Active -> Idle, with negative delay (display: none)');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s -50s');
+
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Make idle
+ transition.currentTime = 50 * MS_PER_SEC;
+ transition.timeline = null;
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Active -> Idle, with negative delay (Animation.timeline = null)');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s 100s');
+ // Seek to Active phase.
+ transition.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Seek to Before phase.
+ transition.currentTime = 0;
+ return watcher.wait_for('transitionend');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 0.0);
+ });
+}, 'Active -> Before');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s 100s');
+ // Seek to Active phase.
+ transition.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Seek to After phase.
+ transition.currentTime = 200 * MS_PER_SEC;
+ return watcher.wait_for('transitionend');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 100.0);
+ });
+}, 'Active -> After');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+ var handler = new TransitionEventHandler(div);
+
+ // Seek to After phase.
+ transition.finish();
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart',
+ 'transitionend' ]).then(function(evt) {
+ // Seek to Before phase.
+ transition.currentTime = 0;
+ return watcher.wait_for([ 'transitionstart', 'transitionend' ]);
+ }).then(function(evt) {
+ assert_equals(handler.transitionstart, 100.0);
+ assert_equals(handler.transitionend, 0.0);
+ });
+}, 'After -> Before');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s 100s');
+ // Seek to After phase.
+ transition.finish();
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart',
+ 'transitionend' ]).then(function(evt) {
+ // Seek to Active phase.
+ transition.currentTime = 100 * MS_PER_SEC;
+ return watcher.wait_for('transitionstart');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 100.0);
+ });
+}, 'After -> Active');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s -50s');
+ var handler = new TransitionEventHandler(div);
+
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function() {
+ assert_equals(handler.transitionrun, 50.0);
+ assert_equals(handler.transitionstart, 50.0);
+ transition.finish();
+ return watcher.wait_for('transitionend');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 100.0);
+ });
+}, 'Calculating the interval start and end time with negative start delay.');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+ var handler = new TransitionEventHandler(div);
+
+ return watcher.wait_for('transitionrun').then(function(evt) {
+ // We can't set the end delay via generated effect timing.
+ // Because CSS-Transition use the AnimationEffectTimingReadOnly.
+ transition.effect = new KeyframeEffect(div,
+ { marginleft: [ '0px', '100px' ]},
+ { duration: 100 * MS_PER_SEC,
+ endDelay: -50 * MS_PER_SEC });
+ // Seek to Before and play.
+ transition.cancel();
+ transition.play();
+ return watcher.wait_for([ 'transitioncancel',
+ 'transitionrun',
+ 'transitionstart' ]);
+ }).then(function() {
+ assert_equals(handler.transitionstart, 0.0);
+
+ // Seek to After phase.
+ transition.finish();
+ return watcher.wait_for('transitionend');
+ }).then(function(evt) {
+ assert_equals(evt.elapsedTime, 50.0);
+ });
+}, 'Calculating the interval start and end time with negative end delay.');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+
+ return watcher.wait_for('transitionrun').then(function() {
+ // Make idle
+ div.style.display = 'none';
+ flushComputedStyle(div);
+ return watcher.wait_for('transitioncancel');
+ }).then(function() {
+ transition.cancel();
+ // Then wait a couple of frames and check that no event was dispatched
+ return waitForAnimationFrames(2);
+ });
+}, 'Call Animation.cancel after cancelling transition.');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+
+ return watcher.wait_for('transitionrun').then(function(evt) {
+ // Make idle
+ div.style.display = 'none';
+ flushComputedStyle(div);
+ transition.play();
+ watcher.wait_for([ 'transitioncancel',
+ 'transitionrun',
+ 'transitionstart' ]);
+ });
+}, 'Restart transition after cancelling transition immediately');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s 100s');
+
+ return watcher.wait_for('transitionrun').then(function(evt) {
+ // Make idle
+ div.style.display = 'none';
+ flushComputedStyle(div);
+ transition.play();
+ transition.cancel();
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ // Then wait a couple of frames and check that no event was dispatched
+ return waitForAnimationFrames(2);
+ });
+}, 'Call Animation.cancel after restarting transition immediately');
+
+promise_test(function(t) {
+ var [transition, watcher] =
+ setupTransition(t, 'margin-left 100s');
+
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ // Make idle
+ transition.timeline = null;
+ return watcher.wait_for('transitioncancel');
+ }).then(function(evt) {
+ transition.timeline = document.timeline;
+ transition.play();
+
+ return watcher.wait_for(['transitionrun', 'transitionstart']);
+ });
+}, 'Set timeline and play transition after clear the timeline');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s');
+
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function() {
+ transition.cancel();
+ return watcher.wait_for('transitioncancel');
+ }).then(function() {
+ // Make After phase
+ transition.effect = null;
+
+ // Then wait a couple of frames and check that no event was dispatched
+ return waitForAnimationFrames(2);
+ });
+}, 'Set null target effect after cancel the transition');
+
+promise_test(function(t) {
+ var [transition, watcher, div] =
+ setupTransition(t, 'margin-left 100s');
+
+ return watcher.wait_for([ 'transitionrun',
+ 'transitionstart' ]).then(function(evt) {
+ transition.effect = null;
+ return watcher.wait_for('transitionend');
+ }).then(function(evt) {
+ transition.cancel();
+ return watcher.wait_for('transitioncancel');
+ });
+}, 'Cancel the transition after clearing the target effect');
+
+done();
+</script>
+</body>
+</html>
diff --git a/dom/animation/test/css-transitions/file_setting-effect.html b/dom/animation/test/css-transitions/file_setting-effect.html
index c61877194..81279ea55 100644
--- a/dom/animation/test/css-transitions/file_setting-effect.html
+++ b/dom/animation/test/css-transitions/file_setting-effect.html
@@ -7,6 +7,8 @@
promise_test(function(t) {
var div = addDiv(t);
+ var watcher = new EventWatcher(t, div, [ 'transitionend',
+ 'transitioncancel' ]);
div.style.left = '0px';
div.style.transition = 'left 100s';
@@ -20,11 +22,14 @@ promise_test(function(t) {
assert_equals(transition.transitionProperty, 'left');
assert_equals(transition.playState, 'finished');
assert_equals(window.getComputedStyle(div).left, '100px');
+ return watcher.wait_for('transitionend');
});
}, 'Test for removing a transition effect');
promise_test(function(t) {
var div = addDiv(t);
+ var watcher = new EventWatcher(t, div, [ 'transitionend',
+ 'transitioncancel' ]);
div.style.left = '0px';
div.style.transition = 'left 100s';
@@ -46,6 +51,8 @@ promise_test(function(t) {
promise_test(function(t) {
var div = addDiv(t);
+ var watcher = new EventWatcher(t, div, [ 'transitionend',
+ 'transitioncancel' ]);
div.style.left = '0px';
div.style.width = '0px';
@@ -65,6 +72,8 @@ promise_test(function(t) {
promise_test(function(t) {
var div = addDiv(t);
+ var watcher = new EventWatcher(t, div, [ 'transitionend',
+ 'transitioncancel' ]);
div.style.left = '0px';
div.style.width = '0px';
diff --git a/dom/animation/test/css-transitions/test_event-dispatch.html b/dom/animation/test/css-transitions/test_event-dispatch.html
new file mode 100644
index 000000000..c90431cd1
--- /dev/null
+++ b/dom/animation/test/css-transitions/test_event-dispatch.html
@@ -0,0 +1,14 @@
+<!doctype html>
+<meta charset=utf-8>
+<script src="/resources/testharness.js"></script>
+<script src="/resources/testharnessreport.js"></script>
+<div id="log"></div>
+<script>
+'use strict';
+setup({explicit_done: true});
+SpecialPowers.pushPrefEnv(
+ { "set": [["dom.animations-api.core.enabled", true]]},
+ function() {
+ window.open("file_event-dispatch.html");
+ });
+</script>
diff --git a/dom/animation/test/mochitest.ini b/dom/animation/test/mochitest.ini
index feb424518..db6dffada 100644
--- a/dom/animation/test/mochitest.ini
+++ b/dom/animation/test/mochitest.ini
@@ -19,6 +19,8 @@ support-files =
css-animations/file_document-get-animations.html
css-animations/file_effect-target.html
css-animations/file_element-get-animations.html
+ css-animations/file_event-dispatch.html
+ css-animations/file_event-order.html
css-animations/file_keyframeeffect-getkeyframes.html
css-animations/file_pseudoElement-get-animations.html
css-transitions/file_animation-cancel.html
@@ -32,6 +34,7 @@ support-files =
css-transitions/file_document-get-animations.html
css-transitions/file_effect-target.html
css-transitions/file_element-get-animations.html
+ css-transitions/file_event-dispatch.html
css-transitions/file_keyframeeffect-getkeyframes.html
css-transitions/file_pseudoElement-get-animations.html
css-transitions/file_setting-effect.html
@@ -72,6 +75,8 @@ support-files =
[css-animations/test_document-get-animations.html]
[css-animations/test_effect-target.html]
[css-animations/test_element-get-animations.html]
+[css-animations/test_event-dispatch.html]
+[css-animations/test_event-order.html]
[css-animations/test_keyframeeffect-getkeyframes.html]
[css-animations/test_pseudoElement-get-animations.html]
[css-transitions/test_animation-cancel.html]
@@ -85,6 +90,7 @@ support-files =
[css-transitions/test_document-get-animations.html]
[css-transitions/test_effect-target.html]
[css-transitions/test_element-get-animations.html]
+[css-transitions/test_event-dispatch.html]
[css-transitions/test_keyframeeffect-getkeyframes.html]
[css-transitions/test_pseudoElement-get-animations.html]
[css-transitions/test_setting-effect.html]
diff --git a/dom/apps/AppsUtils.jsm b/dom/apps/AppsUtils.jsm
index 3ca3f8552..2bd6a4133 100644
--- a/dom/apps/AppsUtils.jsm
+++ b/dom/apps/AppsUtils.jsm
@@ -312,9 +312,6 @@ this.AppsUtils = {
// Instead, we check if the app is installed under /system/b2g
let isCoreApp = false;
-#ifdef MOZ_WIDGET_GONK
- isCoreApp = app.basePath == this.getCoreAppsBasePath();
-#endif
debug(app.basePath + " isCoreApp: " + isCoreApp);
return { "path": app.basePath + "/" + app.id,
diff --git a/dom/audiochannel/AudioChannelService.cpp b/dom/audiochannel/AudioChannelService.cpp
index 87cde41e9..db6f2037b 100644
--- a/dom/audiochannel/AudioChannelService.cpp
+++ b/dom/audiochannel/AudioChannelService.cpp
@@ -27,11 +27,6 @@
#include "nsServiceManagerUtils.h"
#include "mozilla/dom/SettingChangeNotificationBinding.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsJSUtils.h"
-#include "SpeakerManagerService.h"
-#endif
-
#include "mozilla/Preferences.h"
using namespace mozilla;
@@ -237,20 +232,12 @@ AudioChannelService::Shutdown()
if (IsParentProcess()) {
obs->RemoveObserver(gAudioChannelService, "ipc:content-shutdown");
-
-#ifdef MOZ_WIDGET_GONK
- // To monitor the volume settings based on audio channel.
- obs->RemoveObserver(gAudioChannelService, "mozsettings-changed");
-#endif
}
}
gAudioChannelService->mWindows.Clear();
gAudioChannelService->mPlayingChildren.Clear();
gAudioChannelService->mTabParents.Clear();
-#ifdef MOZ_WIDGET_GONK
- gAudioChannelService->mSpeakerManager.Clear();
-#endif
gAudioChannelService = nullptr;
}
@@ -284,11 +271,6 @@ AudioChannelService::AudioChannelService()
obs->AddObserver(this, "outer-window-destroyed", false);
if (IsParentProcess()) {
obs->AddObserver(this, "ipc:content-shutdown", false);
-
-#ifdef MOZ_WIDGET_GONK
- // To monitor the volume settings based on audio channel.
- obs->AddObserver(this, "mozsettings-changed", false);
-#endif
}
}
@@ -342,13 +324,6 @@ AudioChannelService::UnregisterAudioChannelAgent(AudioChannelAgent* aAgent)
RefPtr<AudioChannelAgent> kungFuDeathGrip(aAgent);
winData->RemoveAgent(aAgent);
-#ifdef MOZ_WIDGET_GONK
- bool active = AnyAudioChannelIsActive();
- for (uint32_t i = 0; i < mSpeakerManager.Length(); i++) {
- mSpeakerManager[i]->SetAudioChannelActive(active);
- }
-#endif
-
MaybeSendStatusUpdate();
}
@@ -573,13 +548,6 @@ AudioChannelService::Observe(nsISupports* aSubject, const char* aTopic,
iter.GetNext()->WindowVolumeChanged();
}
}
-
-#ifdef MOZ_WIDGET_GONK
- bool active = AnyAudioChannelIsActive();
- for (uint32_t i = 0; i < mSpeakerManager.Length(); i++) {
- mSpeakerManager[i]->SetAudioChannelActive(active);
- }
-#endif
} else if (!strcmp(aTopic, "ipc:content-shutdown")) {
nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(aSubject);
if (!props) {
diff --git a/dom/audiochannel/AudioChannelService.h b/dom/audiochannel/AudioChannelService.h
index b16832b5f..7d3de8a46 100644
--- a/dom/audiochannel/AudioChannelService.h
+++ b/dom/audiochannel/AudioChannelService.h
@@ -25,10 +25,6 @@ struct PRLogModuleInfo;
namespace mozilla {
namespace dom {
-#ifdef MOZ_WIDGET_GONK
-class SpeakerManagerService;
-#endif
-
class TabParent;
#define NUMBER_OF_AUDIO_CHANNELS (uint32_t)AudioChannel::EndGuard_
@@ -189,20 +185,6 @@ public:
uint64_t aInnerWindowID,
bool aCapture);
-#ifdef MOZ_WIDGET_GONK
- void RegisterSpeakerManager(SpeakerManagerService* aSpeakerManager)
- {
- if (!mSpeakerManager.Contains(aSpeakerManager)) {
- mSpeakerManager.AppendElement(aSpeakerManager);
- }
- }
-
- void UnregisterSpeakerManager(SpeakerManagerService* aSpeakerManager)
- {
- mSpeakerManager.RemoveElement(aSpeakerManager);
- }
-#endif
-
static const nsAttrValue::EnumTable* GetAudioChannelTable();
static AudioChannel GetAudioChannel(const nsAString& aString);
static AudioChannel GetDefaultAudioChannel();
@@ -347,10 +329,6 @@ private:
nsTObserverArray<nsAutoPtr<AudioChannelChildStatus>> mPlayingChildren;
-#ifdef MOZ_WIDGET_GONK
- nsTArray<SpeakerManagerService*> mSpeakerManager;
-#endif
-
// Raw pointers because TabParents must unregister themselves.
nsTArray<TabParent*> mTabParents;
diff --git a/dom/base/Navigator.cpp b/dom/base/Navigator.cpp
index 5c315517c..ed96ee23b 100644
--- a/dom/base/Navigator.cpp
+++ b/dom/base/Navigator.cpp
@@ -767,12 +767,6 @@ StaticRefPtr<VibrateWindowListener> gVibrateWindowListener;
static bool
MayVibrate(nsIDocument* doc) {
-#if MOZ_WIDGET_GONK
- if (XRE_IsParentProcess()) {
- return true; // The system app can always vibrate
- }
-#endif // MOZ_WIDGET_GONK
-
// Hidden documents cannot start or stop a vibration.
return (doc && !doc->Hidden());
}
diff --git a/dom/base/ScreenOrientation.cpp b/dom/base/ScreenOrientation.cpp
index bb3ccf5c3..ec9c4fa29 100644
--- a/dom/base/ScreenOrientation.cpp
+++ b/dom/base/ScreenOrientation.cpp
@@ -309,7 +309,7 @@ ScreenOrientation::LockInternal(ScreenOrientationInternal aOrientation, ErrorRes
return nullptr;
}
-#if !defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if !defined(MOZ_WIDGET_ANDROID)
// User agent does not support locking the screen orientation.
p->MaybeReject(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return p.forget();
diff --git a/dom/base/moz.build b/dom/base/moz.build
index 76c765b1c..77eb01ba6 100755
--- a/dom/base/moz.build
+++ b/dom/base/moz.build
@@ -462,11 +462,6 @@ LOCAL_INCLUDES += [
'/xpcom/ds',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- LOCAL_INCLUDES += [
- '../system/gonk',
- ]
-
if CONFIG['MOZ_WEBRTC']:
LOCAL_INCLUDES += [
'/netwerk/sctp/datachannel',
diff --git a/dom/base/nsContentPermissionHelper.cpp b/dom/base/nsContentPermissionHelper.cpp
index fd04b1013..c57fc6233 100644
--- a/dom/base/nsContentPermissionHelper.cpp
+++ b/dom/base/nsContentPermissionHelper.cpp
@@ -5,9 +5,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <map>
-#ifdef MOZ_WIDGET_GONK
-#include "GonkPermission.h"
-#endif // MOZ_WIDGET_GONK
#include "nsCOMPtr.h"
#include "nsIDOMElement.h"
#include "nsIPrincipal.h"
diff --git a/dom/base/nsContentUtils.cpp b/dom/base/nsContentUtils.cpp
index ef87a250e..34c7d23b8 100644
--- a/dom/base/nsContentUtils.cpp
+++ b/dom/base/nsContentUtils.cpp
@@ -281,6 +281,7 @@ bool nsContentUtils::sIsCutCopyAllowed = true;
bool nsContentUtils::sIsFrameTimingPrefEnabled = false;
bool nsContentUtils::sIsPerformanceTimingEnabled = false;
bool nsContentUtils::sIsResourceTimingEnabled = false;
+bool nsContentUtils::sIsPerformanceNavigationTimingEnabled = false;
bool nsContentUtils::sIsUserTimingLoggingEnabled = false;
bool nsContentUtils::sIsExperimentalAutocompleteEnabled = false;
bool nsContentUtils::sEncodeDecodeURLHash = false;
@@ -571,6 +572,9 @@ nsContentUtils::Init()
Preferences::AddBoolVarCache(&sIsResourceTimingEnabled,
"dom.enable_resource_timing", true);
+ Preferences::AddBoolVarCache(&sIsPerformanceNavigationTimingEnabled,
+ "dom.enable_performance_navigation_timing", true);
+
Preferences::AddBoolVarCache(&sIsUserTimingLoggingEnabled,
"dom.performance.enable_user_timing_logging", false);
@@ -5100,7 +5104,7 @@ nsContentUtils::TriggerLink(nsIContent *aContent, nsPresContext *aPresContext,
handler->OnLinkClick(aContent, aLinkURI,
fileName.IsVoid() ? aTargetSpec.get() : EmptyString().get(),
- fileName, nullptr, nullptr, aIsTrusted);
+ fileName, nullptr, nullptr, aIsTrusted, aContent->NodePrincipal());
}
}
@@ -9772,9 +9776,13 @@ nsContentUtils::AttemptLargeAllocationLoad(nsIHttpChannel* aChannel)
rv = aChannel->GetReferrer(getter_AddRefs(referrer));
NS_ENSURE_SUCCESS(rv, false);
+ nsCOMPtr<nsILoadInfo> loadInfo = aChannel->GetLoadInfo();
+ nsCOMPtr<nsIPrincipal> triggeringPrincipal = loadInfo->TriggeringPrincipal();
+
// Actually perform the cross process load
bool reloadSucceeded = false;
- rv = wbc3->ReloadInFreshProcess(docShell, uri, referrer, &reloadSucceeded);
+ rv = wbc3->ReloadInFreshProcess(docShell, uri, referrer,
+ triggeringPrincipal, &reloadSucceeded);
NS_ENSURE_SUCCESS(rv, false);
return reloadSucceeded;
diff --git a/dom/base/nsContentUtils.h b/dom/base/nsContentUtils.h
index 0932f451e..9ae6d2155 100644
--- a/dom/base/nsContentUtils.h
+++ b/dom/base/nsContentUtils.h
@@ -2033,6 +2033,14 @@ public:
}
/*
+ * Returns true if the performance timing APIs are enabled.
+ */
+ static bool IsPerformanceNavigationTimingEnabled()
+ {
+ return sIsPerformanceNavigationTimingEnabled;
+ }
+
+ /*
* Returns true if notification should be sent for peformance timing events.
*/
static bool SendPerformanceTimingNotifications()
@@ -2825,6 +2833,7 @@ private:
static uint32_t sHandlingInputTimeout;
static bool sIsPerformanceTimingEnabled;
static bool sIsResourceTimingEnabled;
+ static bool sIsPerformanceNavigationTimingEnabled;
static bool sIsUserTimingLoggingEnabled;
static bool sIsFrameTimingPrefEnabled;
static bool sIsExperimentalAutocompleteEnabled;
diff --git a/dom/base/nsDOMNavigationTiming.cpp b/dom/base/nsDOMNavigationTiming.cpp
index 31b2932fb..32ce8a8cb 100644
--- a/dom/base/nsDOMNavigationTiming.cpp
+++ b/dom/base/nsDOMNavigationTiming.cpp
@@ -15,6 +15,9 @@
#include "nsPrintfCString.h"
#include "mozilla/dom/PerformanceNavigation.h"
#include "mozilla/TimeStamp.h"
+#include "mozilla/Telemetry.h"
+
+using namespace mozilla;
nsDOMNavigationTiming::nsDOMNavigationTiming()
{
@@ -30,47 +33,36 @@ nsDOMNavigationTiming::Clear()
{
mNavigationType = TYPE_RESERVED;
mNavigationStartHighRes = 0;
- mBeforeUnloadStart = 0;
- mUnloadStart = 0;
- mUnloadEnd = 0;
- mLoadEventStart = 0;
- mLoadEventEnd = 0;
- mDOMLoading = 0;
- mDOMInteractive = 0;
- mDOMContentLoadedEventStart = 0;
- mDOMContentLoadedEventEnd = 0;
- mDOMComplete = 0;
-
- mLoadEventStartSet = false;
- mLoadEventEndSet = false;
- mDOMLoadingSet = false;
- mDOMInteractiveSet = false;
- mDOMContentLoadedEventStartSet = false;
- mDOMContentLoadedEventEndSet = false;
- mDOMCompleteSet = false;
+ mBeforeUnloadStart = TimeStamp();
+ mUnloadStart = TimeStamp();
+ mUnloadEnd = TimeStamp();
+ mLoadEventStart = TimeStamp();
+ mLoadEventEnd = TimeStamp();
+ mDOMLoading = TimeStamp();
+ mDOMInteractive = TimeStamp();
+ mDOMContentLoadedEventStart = TimeStamp();
+ mDOMContentLoadedEventEnd = TimeStamp();
+ mDOMComplete = TimeStamp();
+
mDocShellHasBeenActiveSinceNavigationStart = false;
}
DOMTimeMilliSec
-nsDOMNavigationTiming::TimeStampToDOM(mozilla::TimeStamp aStamp) const
+nsDOMNavigationTiming::TimeStampToDOM(TimeStamp aStamp) const
{
if (aStamp.IsNull()) {
return 0;
}
- mozilla::TimeDuration duration = aStamp - mNavigationStartTimeStamp;
- return GetNavigationStart() + static_cast<int64_t>(duration.ToMilliseconds());
-}
-DOMTimeMilliSec nsDOMNavigationTiming::DurationFromStart()
-{
- return TimeStampToDOM(mozilla::TimeStamp::Now());
+ TimeDuration duration = aStamp - mNavigationStart;
+ return GetNavigationStart() + static_cast<int64_t>(duration.ToMilliseconds());
}
void
nsDOMNavigationTiming::NotifyNavigationStart(DocShellState aDocShellState)
{
mNavigationStartHighRes = (double)PR_Now() / PR_USEC_PER_MSEC;
- mNavigationStartTimeStamp = mozilla::TimeStamp::Now();
+ mNavigationStart = TimeStamp::Now();
mDocShellHasBeenActiveSinceNavigationStart = (aDocShellState == DocShellState::eActive);
}
@@ -86,7 +78,7 @@ nsDOMNavigationTiming::NotifyFetchStart(nsIURI* aURI, Type aNavigationType)
void
nsDOMNavigationTiming::NotifyBeforeUnload()
{
- mBeforeUnloadStart = DurationFromStart();
+ mBeforeUnloadStart = TimeStamp::Now();
}
void
@@ -99,105 +91,107 @@ nsDOMNavigationTiming::NotifyUnloadAccepted(nsIURI* aOldURI)
void
nsDOMNavigationTiming::NotifyUnloadEventStart()
{
- mUnloadStart = DurationFromStart();
+ mUnloadStart = TimeStamp::Now();
}
void
nsDOMNavigationTiming::NotifyUnloadEventEnd()
{
- mUnloadEnd = DurationFromStart();
+ mUnloadEnd = TimeStamp::Now();
}
void
nsDOMNavigationTiming::NotifyLoadEventStart()
{
- if (!mLoadEventStartSet) {
- mLoadEventStart = DurationFromStart();
- mLoadEventStartSet = true;
+ if (!mLoadEventStart.IsNull()) {
+ return;
}
+ mLoadEventStart = TimeStamp::Now();
}
void
nsDOMNavigationTiming::NotifyLoadEventEnd()
{
- if (!mLoadEventEndSet) {
- mLoadEventEnd = DurationFromStart();
- mLoadEventEndSet = true;
+ if (!mLoadEventEnd.IsNull()) {
+ return;
}
+ mLoadEventEnd = TimeStamp::Now();
}
void
-nsDOMNavigationTiming::SetDOMLoadingTimeStamp(nsIURI* aURI, mozilla::TimeStamp aValue)
+nsDOMNavigationTiming::SetDOMLoadingTimeStamp(nsIURI* aURI, TimeStamp aValue)
{
- if (!mDOMLoadingSet) {
- mLoadedURI = aURI;
- mDOMLoading = TimeStampToDOM(aValue);
- mDOMLoadingSet = true;
+ if (!mDOMLoading.IsNull()) {
+ return;
}
+ mLoadedURI = aURI;
+ mDOMLoading = aValue;
}
void
nsDOMNavigationTiming::NotifyDOMLoading(nsIURI* aURI)
{
- if (!mDOMLoadingSet) {
- mLoadedURI = aURI;
- mDOMLoading = DurationFromStart();
- mDOMLoadingSet = true;
+ if (!mDOMLoading.IsNull()) {
+ return;
}
+ mLoadedURI = aURI;
+ mDOMLoading = TimeStamp::Now();
}
void
nsDOMNavigationTiming::NotifyDOMInteractive(nsIURI* aURI)
{
- if (!mDOMInteractiveSet) {
- mLoadedURI = aURI;
- mDOMInteractive = DurationFromStart();
- mDOMInteractiveSet = true;
+ if (!mDOMInteractive.IsNull()) {
+ return;
}
+ mLoadedURI = aURI;
+ mDOMInteractive = TimeStamp::Now();
}
void
nsDOMNavigationTiming::NotifyDOMComplete(nsIURI* aURI)
{
- if (!mDOMCompleteSet) {
- mLoadedURI = aURI;
- mDOMComplete = DurationFromStart();
- mDOMCompleteSet = true;
+ if (!mDOMComplete.IsNull()) {
+ return;
}
+ mLoadedURI = aURI;
+ mDOMComplete = TimeStamp::Now();
}
void
nsDOMNavigationTiming::NotifyDOMContentLoadedStart(nsIURI* aURI)
{
- if (!mDOMContentLoadedEventStartSet) {
- mLoadedURI = aURI;
- mDOMContentLoadedEventStart = DurationFromStart();
- mDOMContentLoadedEventStartSet = true;
+ if (!mDOMContentLoadedEventStart.IsNull()) {
+ return;
}
+
+ mLoadedURI = aURI;
+ mDOMContentLoadedEventStart = TimeStamp::Now();
}
void
nsDOMNavigationTiming::NotifyDOMContentLoadedEnd(nsIURI* aURI)
{
- if (!mDOMContentLoadedEventEndSet) {
- mLoadedURI = aURI;
- mDOMContentLoadedEventEnd = DurationFromStart();
- mDOMContentLoadedEventEndSet = true;
+ if (!mDOMContentLoadedEventEnd.IsNull()) {
+ return;
}
+
+ mLoadedURI = aURI;
+ mDOMContentLoadedEventEnd = TimeStamp::Now();
}
void
nsDOMNavigationTiming::NotifyNonBlankPaintForRootContentDocument()
{
MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!mNavigationStartTimeStamp.IsNull());
+ MOZ_ASSERT(!mNavigationStart.IsNull());
- if (!mNonBlankPaintTimeStamp.IsNull()) {
+ if (!mNonBlankPaint.IsNull()) {
return;
}
- mNonBlankPaintTimeStamp = TimeStamp::Now();
- TimeDuration elapsed = mNonBlankPaintTimeStamp - mNavigationStartTimeStamp;
+ mNonBlankPaint = TimeStamp::Now();
+ TimeDuration elapsed = mNonBlankPaint - mNavigationStart;
if (profiler_is_active()) {
nsAutoCString spec;
@@ -212,8 +206,8 @@ nsDOMNavigationTiming::NotifyNonBlankPaintForRootContentDocument()
if (mDocShellHasBeenActiveSinceNavigationStart) {
Telemetry::AccumulateTimeDelta(Telemetry::TIME_TO_NON_BLANK_PAINT_MS,
- mNavigationStartTimeStamp,
- mNonBlankPaintTimeStamp);
+ mNavigationStart,
+ mNonBlankPaint);
}
}
@@ -224,24 +218,24 @@ nsDOMNavigationTiming::NotifyDocShellStateChanged(DocShellState aDocShellState)
(aDocShellState == DocShellState::eActive);
}
-DOMTimeMilliSec
-nsDOMNavigationTiming::GetUnloadEventStart()
+mozilla::TimeStamp
+nsDOMNavigationTiming::GetUnloadEventStartTimeStamp() const
{
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
nsresult rv = ssm->CheckSameOriginURI(mLoadedURI, mUnloadedURI, false);
if (NS_SUCCEEDED(rv)) {
return mUnloadStart;
}
- return 0;
+ return mozilla::TimeStamp();
}
-DOMTimeMilliSec
-nsDOMNavigationTiming::GetUnloadEventEnd()
+mozilla::TimeStamp
+nsDOMNavigationTiming::GetUnloadEventEndTimeStamp() const
{
nsIScriptSecurityManager* ssm = nsContentUtils::GetSecurityManager();
nsresult rv = ssm->CheckSameOriginURI(mLoadedURI, mUnloadedURI, false);
if (NS_SUCCEEDED(rv)) {
return mUnloadEnd;
}
- return 0;
+ return mozilla::TimeStamp();
}
diff --git a/dom/base/nsDOMNavigationTiming.h b/dom/base/nsDOMNavigationTiming.h
index 9babece96..3be2527ca 100644
--- a/dom/base/nsDOMNavigationTiming.h
+++ b/dom/base/nsDOMNavigationTiming.h
@@ -47,38 +47,91 @@ public:
mozilla::TimeStamp GetNavigationStartTimeStamp() const
{
- return mNavigationStartTimeStamp;
+ return mNavigationStart;
+ }
+
+ DOMTimeMilliSec GetUnloadEventStart()
+ {
+ return TimeStampToDOM(GetUnloadEventStartTimeStamp());
+ }
+
+ DOMTimeMilliSec GetUnloadEventEnd()
+ {
+ return TimeStampToDOM(GetUnloadEventEndTimeStamp());
}
- DOMTimeMilliSec GetUnloadEventStart();
- DOMTimeMilliSec GetUnloadEventEnd();
DOMTimeMilliSec GetDomLoading() const
{
- return mDOMLoading;
+ return TimeStampToDOM(mDOMLoading);
}
DOMTimeMilliSec GetDomInteractive() const
{
- return mDOMInteractive;
+ return TimeStampToDOM(mDOMInteractive);
}
DOMTimeMilliSec GetDomContentLoadedEventStart() const
{
- return mDOMContentLoadedEventStart;
+ return TimeStampToDOM(mDOMContentLoadedEventStart);
}
DOMTimeMilliSec GetDomContentLoadedEventEnd() const
{
- return mDOMContentLoadedEventEnd;
+ return TimeStampToDOM(mDOMContentLoadedEventEnd);
}
DOMTimeMilliSec GetDomComplete() const
{
- return mDOMComplete;
+ return TimeStampToDOM(mDOMComplete);
}
DOMTimeMilliSec GetLoadEventStart() const
{
- return mLoadEventStart;
+ return TimeStampToDOM(mLoadEventStart);
}
DOMTimeMilliSec GetLoadEventEnd() const
{
- return mLoadEventEnd;
+ return TimeStampToDOM(mLoadEventEnd);
+ }
+ DOMTimeMilliSec GetTimeToNonBlankPaint() const
+ {
+ return TimeStampToDOM(mNonBlankPaint);
+ }
+
+ DOMHighResTimeStamp GetUnloadEventStartHighRes()
+ {
+ mozilla::TimeStamp stamp = GetUnloadEventStartTimeStamp();
+ if (stamp.IsNull()) {
+ return 0;
+ }
+ return TimeStampToDOMHighRes(stamp);
+ }
+ DOMHighResTimeStamp GetUnloadEventEndHighRes()
+ {
+ mozilla::TimeStamp stamp = GetUnloadEventEndTimeStamp();
+ if (stamp.IsNull()) {
+ return 0;
+ }
+ return TimeStampToDOMHighRes(stamp);
+ }
+ DOMHighResTimeStamp GetDomInteractiveHighRes() const
+ {
+ return TimeStampToDOMHighRes(mDOMInteractive);
+ }
+ DOMHighResTimeStamp GetDomContentLoadedEventStartHighRes() const
+ {
+ return TimeStampToDOMHighRes(mDOMContentLoadedEventStart);
+ }
+ DOMHighResTimeStamp GetDomContentLoadedEventEndHighRes() const
+ {
+ return TimeStampToDOMHighRes(mDOMContentLoadedEventEnd);
+ }
+ DOMHighResTimeStamp GetDomCompleteHighRes() const
+ {
+ return TimeStampToDOMHighRes(mDOMComplete);
+ }
+ DOMHighResTimeStamp GetLoadEventStartHighRes() const
+ {
+ return TimeStampToDOMHighRes(mLoadEventStart);
+ }
+ DOMHighResTimeStamp GetLoadEventEndHighRes() const
+ {
+ return TimeStampToDOMHighRes(mLoadEventEnd);
}
enum class DocShellState : uint8_t {
@@ -108,9 +161,13 @@ public:
DOMTimeMilliSec TimeStampToDOM(mozilla::TimeStamp aStamp) const;
- inline DOMHighResTimeStamp TimeStampToDOMHighRes(mozilla::TimeStamp aStamp)
+ inline DOMHighResTimeStamp TimeStampToDOMHighRes(mozilla::TimeStamp aStamp) const
{
- mozilla::TimeDuration duration = aStamp - mNavigationStartTimeStamp;
+ MOZ_ASSERT(!aStamp.IsNull(), "The timestamp should not be null");
+ if (aStamp.IsNull()) {
+ return 0;
+ }
+ mozilla::TimeDuration duration = aStamp - mNavigationStart;
return duration.ToMilliseconds();
}
@@ -120,37 +177,29 @@ private:
void Clear();
+ mozilla::TimeStamp GetUnloadEventStartTimeStamp() const;
+ mozilla::TimeStamp GetUnloadEventEndTimeStamp() const;
+
nsCOMPtr<nsIURI> mUnloadedURI;
nsCOMPtr<nsIURI> mLoadedURI;
Type mNavigationType;
DOMHighResTimeStamp mNavigationStartHighRes;
- mozilla::TimeStamp mNavigationStartTimeStamp;
- mozilla::TimeStamp mNonBlankPaintTimeStamp;
- DOMTimeMilliSec DurationFromStart();
-
- DOMTimeMilliSec mBeforeUnloadStart;
- DOMTimeMilliSec mUnloadStart;
- DOMTimeMilliSec mUnloadEnd;
- DOMTimeMilliSec mLoadEventStart;
- DOMTimeMilliSec mLoadEventEnd;
-
- DOMTimeMilliSec mDOMLoading;
- DOMTimeMilliSec mDOMInteractive;
- DOMTimeMilliSec mDOMContentLoadedEventStart;
- DOMTimeMilliSec mDOMContentLoadedEventEnd;
- DOMTimeMilliSec mDOMComplete;
-
- // Booleans to keep track of what things we've already been notified
- // about. We don't update those once we've been notified about them
- // once.
- bool mLoadEventStartSet : 1;
- bool mLoadEventEndSet : 1;
- bool mDOMLoadingSet : 1;
- bool mDOMInteractiveSet : 1;
- bool mDOMContentLoadedEventStartSet : 1;
- bool mDOMContentLoadedEventEndSet : 1;
- bool mDOMCompleteSet : 1;
+ mozilla::TimeStamp mNavigationStart;
+ mozilla::TimeStamp mNonBlankPaint;
+
+ mozilla::TimeStamp mBeforeUnloadStart;
+ mozilla::TimeStamp mUnloadStart;
+ mozilla::TimeStamp mUnloadEnd;
+ mozilla::TimeStamp mLoadEventStart;
+ mozilla::TimeStamp mLoadEventEnd;
+
+ mozilla::TimeStamp mDOMLoading;
+ mozilla::TimeStamp mDOMInteractive;
+ mozilla::TimeStamp mDOMContentLoadedEventStart;
+ mozilla::TimeStamp mDOMContentLoadedEventEnd;
+ mozilla::TimeStamp mDOMComplete;
+
bool mDocShellHasBeenActiveSinceNavigationStart : 1;
};
diff --git a/dom/base/nsGkAtomList.h b/dom/base/nsGkAtomList.h
index e4ae7ede8..50b4449ec 100644
--- a/dom/base/nsGkAtomList.h
+++ b/dom/base/nsGkAtomList.h
@@ -694,6 +694,7 @@ GK_ATOM(onadapterremoved, "onadapterremoved")
GK_ATOM(onafterprint, "onafterprint")
GK_ATOM(onafterscriptexecute, "onafterscriptexecute")
GK_ATOM(onalerting, "onalerting")
+GK_ATOM(onanimationcancel, "onanimationcancel")
GK_ATOM(onanimationend, "onanimationend")
GK_ATOM(onanimationiteration, "onanimationiteration")
GK_ATOM(onanimationstart, "onanimationstart")
@@ -704,6 +705,7 @@ GK_ATOM(onattributechanged, "onattributechanged")
GK_ATOM(onattributereadreq, "onattributereadreq")
GK_ATOM(onattributewritereq, "onattributewritereq")
GK_ATOM(onaudioprocess, "onaudioprocess")
+GK_ATOM(onauxclick, "onauxclick")
GK_ATOM(onbeforecopy, "onbeforecopy")
GK_ATOM(onbeforecut, "onbeforecut")
GK_ATOM(onbeforepaste, "onbeforepaste")
@@ -941,6 +943,7 @@ GK_ATOM(ontouchstart, "ontouchstart")
GK_ATOM(ontouchend, "ontouchend")
GK_ATOM(ontouchmove, "ontouchmove")
GK_ATOM(ontouchcancel, "ontouchcancel")
+GK_ATOM(ontransitioncancel, "ontransitioncancel")
GK_ATOM(ontransitionend, "ontransitionend")
GK_ATOM(ontransitionrun, "ontransitionrun")
GK_ATOM(ontransitionstart, "ontransitionstart")
diff --git a/dom/base/nsGlobalWindow.cpp b/dom/base/nsGlobalWindow.cpp
index 3d5c44a78..4e384c4d2 100644
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -25,7 +25,7 @@
#include "mozilla/dom/Timeout.h"
#include "mozilla/dom/TimeoutHandler.h"
#include "mozilla/IntegerPrintfMacros.h"
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
#include "mozilla/dom/WindowOrientationObserver.h"
#endif
#include "nsDOMOfflineResourceList.h"
@@ -249,10 +249,6 @@
#include "mozilla/dom/SpeechSynthesis.h"
#endif
-#ifdef MOZ_B2G
-#include "nsPISocketTransportService.h"
-#endif
-
// Apple system headers seem to have a check() macro. <sigh>
#ifdef check
class nsIScriptTimeoutHandler;
@@ -1557,10 +1553,6 @@ nsGlobalWindow::nsGlobalWindow(nsGlobalWindow *aOuterWindow)
#ifdef DEBUG
mSetOpenerWindowCalled(false),
#endif
-#ifdef MOZ_B2G
- mNetworkUploadObserverEnabled(false),
- mNetworkDownloadObserverEnabled(false),
-#endif
mCleanedUp(false),
mDialogAbuseCount(0),
mAreDialogsEnabled(true),
@@ -1913,11 +1905,6 @@ nsGlobalWindow::CleanUp()
os->RemoveObserver(mObserver, "dom-storage2-changed");
}
-#ifdef MOZ_B2G
- DisableNetworkEvent(eNetworkUpload);
- DisableNetworkEvent(eNetworkDownload);
-#endif // MOZ_B2G
-
if (mIdleService) {
mIdleService->RemoveIdleObserver(mObserver, MIN_IDLE_NOTIFICATION_TIME_S);
}
@@ -1961,7 +1948,7 @@ nsGlobalWindow::CleanUp()
mSpeechSynthesis = nullptr;
#endif
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
mOrientationChangeObserver = nullptr;
#endif
@@ -1986,9 +1973,6 @@ nsGlobalWindow::CleanUp()
mHasGamepad = false;
DisableVRUpdates();
mHasVREvents = false;
-#ifdef MOZ_B2G
- DisableTimeChangeNotifications();
-#endif
DisableIdleCallbackRequests();
} else {
MOZ_ASSERT(!mHasGamepad);
@@ -2092,7 +2076,7 @@ nsGlobalWindow::FreeInnerObjects()
mScreen = nullptr;
}
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
mOrientationChangeObserver = nullptr;
#endif
@@ -2521,8 +2505,13 @@ nsGlobalWindow::WouldReuseInnerWindow(nsIDocument* aNewDocument)
return false;
}
- NS_ASSERTION(NS_IsAboutBlank(mDoc->GetDocumentURI()),
- "How'd this happen?");
+#ifdef DEBUG
+{
+ nsCOMPtr<nsIURI> uri;
+ mDoc->GetDocumentURI()->CloneIgnoringRef(getter_AddRefs(uri));
+ NS_ASSERTION(NS_IsAboutBlank(uri), "How'd this happen?");
+}
+#endif
// Great, we're the original document, check for one of the other
// conditions.
@@ -3124,8 +3113,7 @@ nsGlobalWindow::SetNewDocument(nsIDocument* aDocument,
newInnerWindow->mPerformance =
Performance::CreateForMainThread(newInnerWindow->AsInner(),
currentInner->mPerformance->GetDOMTiming(),
- currentInner->mPerformance->GetChannel(),
- currentInner->mPerformance->GetParentPerformance());
+ currentInner->mPerformance->GetChannel());
}
}
@@ -4339,22 +4327,7 @@ nsPIDOMWindowInner::CreatePerformanceObjectIfNeeded()
timedChannel = nullptr;
}
if (timing) {
- // If we are dealing with an iframe, we will need the parent's performance
- // object (so we can add the iframe as a resource of that page).
- Performance* parentPerformance = nullptr;
- nsCOMPtr<nsPIDOMWindowOuter> parentWindow = GetScriptableParentOrNull();
- if (parentWindow) {
- nsPIDOMWindowInner* parentInnerWindow = nullptr;
- if (parentWindow) {
- parentInnerWindow = parentWindow->GetCurrentInnerWindow();
- }
- if (parentInnerWindow) {
- parentPerformance = parentInnerWindow->GetPerformance();
- }
- }
- mPerformance =
- Performance::CreateForMainThread(this, timing, timedChannel,
- parentPerformance);
+ mPerformance = Performance::CreateForMainThread(this, timing, timedChannel);
}
}
@@ -12144,27 +12117,6 @@ nsGlobalWindow::Observe(nsISupports* aSubject, const char* aTopic,
return NS_OK;
}
-#ifdef MOZ_B2G
- if (!nsCRT::strcmp(aTopic, NS_NETWORK_ACTIVITY_BLIP_UPLOAD_TOPIC) ||
- !nsCRT::strcmp(aTopic, NS_NETWORK_ACTIVITY_BLIP_DOWNLOAD_TOPIC)) {
- MOZ_ASSERT(IsInnerWindow());
- if (!AsInner()->IsCurrentInnerWindow()) {
- return NS_OK;
- }
-
- RefPtr<Event> event = NS_NewDOMEvent(this, nullptr, nullptr);
- event->InitEvent(
- !nsCRT::strcmp(aTopic, NS_NETWORK_ACTIVITY_BLIP_UPLOAD_TOPIC)
- ? NETWORK_UPLOAD_EVENT_NAME
- : NETWORK_DOWNLOAD_EVENT_NAME,
- false, false);
- event->SetTrusted(true);
-
- bool dummy;
- return DispatchEvent(event, &dummy);
- }
-#endif // MOZ_B2G
-
if (!nsCRT::strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
MOZ_ASSERT(!NS_strcmp(aData, u"intl.accept_languages"));
MOZ_ASSERT(IsInnerWindow());
@@ -14057,7 +14009,7 @@ nsGlobalWindow::DisableDeviceSensor(uint32_t aType)
}
}
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
void
nsGlobalWindow::EnableOrientationChangeListener()
{
@@ -14950,7 +14902,7 @@ nsGlobalWindow::IsModalContentWindow(JSContext* aCx, JSObject* aGlobal)
return xpc::WindowOrNull(aGlobal)->IsModalContentWindow();
}
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
int16_t
nsGlobalWindow::Orientation(CallerType aCallerType) const
{
@@ -15064,80 +15016,6 @@ nsGlobalWindow::GetIsPrerendered()
return docShell && docShell->GetIsPrerendered();
}
-#ifdef MOZ_B2G
-void
-nsGlobalWindow::EnableNetworkEvent(EventMessage aEventMessage)
-{
- MOZ_ASSERT(IsInnerWindow());
-
- nsCOMPtr<nsIPermissionManager> permMgr =
- services::GetPermissionManager();
- if (!permMgr) {
- NS_ERROR("No PermissionManager available!");
- return;
- }
-
- uint32_t permission = nsIPermissionManager::DENY_ACTION;
- permMgr->TestExactPermissionFromPrincipal(GetPrincipal(), "network-events",
- &permission);
-
- if (permission != nsIPermissionManager::ALLOW_ACTION) {
- return;
- }
-
- nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
- if (!os) {
- NS_ERROR("ObserverService should be available!");
- return;
- }
-
- switch (aEventMessage) {
- case eNetworkUpload:
- if (!mNetworkUploadObserverEnabled) {
- mNetworkUploadObserverEnabled = true;
- os->AddObserver(mObserver, NS_NETWORK_ACTIVITY_BLIP_UPLOAD_TOPIC, false);
- }
- break;
- case eNetworkDownload:
- if (!mNetworkDownloadObserverEnabled) {
- mNetworkDownloadObserverEnabled = true;
- os->AddObserver(mObserver, NS_NETWORK_ACTIVITY_BLIP_DOWNLOAD_TOPIC, false);
- }
- break;
- default:
- break;
- }
-}
-
-void
-nsGlobalWindow::DisableNetworkEvent(EventMessage aEventMessage)
-{
- MOZ_ASSERT(IsInnerWindow());
-
- nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
- if (!os) {
- return;
- }
-
- switch (aEventMessage) {
- case eNetworkUpload:
- if (mNetworkUploadObserverEnabled) {
- mNetworkUploadObserverEnabled = false;
- os->RemoveObserver(mObserver, NS_NETWORK_ACTIVITY_BLIP_UPLOAD_TOPIC);
- }
- break;
- case eNetworkDownload:
- if (mNetworkDownloadObserverEnabled) {
- mNetworkDownloadObserverEnabled = false;
- os->RemoveObserver(mObserver, NS_NETWORK_ACTIVITY_BLIP_DOWNLOAD_TOPIC);
- }
- break;
- default:
- break;
- }
-}
-#endif // MOZ_B2G
-
void
nsGlobalWindow::RedefineProperty(JSContext* aCx, const char* aPropName,
JS::Handle<JS::Value> aValue,
diff --git a/dom/base/nsGlobalWindow.h b/dom/base/nsGlobalWindow.h
index 78bee63a1..467bc6796 100644
--- a/dom/base/nsGlobalWindow.h
+++ b/dom/base/nsGlobalWindow.h
@@ -138,7 +138,7 @@ class U2F;
class VRDisplay;
class VREventObserver;
class WakeLock;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
class WindowOrientationObserver;
#endif
class Worklet;
@@ -631,7 +631,7 @@ public:
virtual void EnableDeviceSensor(uint32_t aType) override;
virtual void DisableDeviceSensor(uint32_t aType) override;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
virtual void EnableOrientationChangeListener() override;
virtual void DisableOrientationChangeListener() override;
#endif
@@ -639,13 +639,6 @@ public:
virtual void EnableTimeChangeNotifications() override;
virtual void DisableTimeChangeNotifications() override;
-#ifdef MOZ_B2G
- // Inner windows only.
- virtual void EnableNetworkEvent(mozilla::EventMessage aEventMessage) override;
- virtual void DisableNetworkEvent(
- mozilla::EventMessage aEventMessage) override;
-#endif // MOZ_B2G
-
virtual nsresult SetArguments(nsIArray* aArguments) override;
void MaybeForgiveSpamCount();
@@ -912,7 +905,7 @@ public:
nsIDOMOfflineResourceList* GetApplicationCache(mozilla::ErrorResult& aError);
already_AddRefed<nsIDOMOfflineResourceList> GetApplicationCache() override;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
int16_t Orientation(mozilla::dom::CallerType aCallerType) const;
#endif
@@ -1941,11 +1934,6 @@ protected:
nsCOMPtr<nsIURI> mLastOpenedURI;
#endif
-#ifdef MOZ_B2G
- bool mNetworkUploadObserverEnabled;
- bool mNetworkDownloadObserverEnabled;
-#endif // MOZ_B2G
-
bool mCleanedUp;
nsCOMPtr<nsIDOMOfflineResourceList> mApplicationCache;
@@ -1983,7 +1971,7 @@ protected:
nsTArray<uint32_t> mEnabledSensors;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
nsAutoPtr<mozilla::dom::WindowOrientationObserver> mOrientationChangeObserver;
#endif
diff --git a/dom/base/nsISelectionPrivate.idl b/dom/base/nsISelectionPrivate.idl
index 68412885e..049873b28 100644
--- a/dom/base/nsISelectionPrivate.idl
+++ b/dom/base/nsISelectionPrivate.idl
@@ -29,7 +29,7 @@ native nsDirection(nsDirection);
native ScrollAxis(nsIPresShell::ScrollAxis);
[scriptable, builtinclass, uuid(0c9f4f74-ee7e-4fe9-be6b-0ba856368178)]
-interface nsISelectionPrivate : nsISelection
+interface nsISelectionPrivate : nsISupports
{
const short ENDOFPRECEDINGLINE=0;
const short STARTOFNEXTLINE=1;
diff --git a/dom/base/nsPIDOMWindow.h b/dom/base/nsPIDOMWindow.h
index 45823057a..47affbb06 100644
--- a/dom/base/nsPIDOMWindow.h
+++ b/dom/base/nsPIDOMWindow.h
@@ -444,7 +444,7 @@ public:
*/
virtual void DisableDeviceSensor(uint32_t aType) = 0;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
virtual void EnableOrientationChangeListener() = 0;
virtual void DisableOrientationChangeListener() = 0;
#endif
@@ -452,24 +452,6 @@ public:
virtual void EnableTimeChangeNotifications() = 0;
virtual void DisableTimeChangeNotifications() = 0;
-#ifdef MOZ_B2G
- /**
- * Tell the window that it should start to listen to the network event of the
- * given aType.
- *
- * Inner windows only.
- */
- virtual void EnableNetworkEvent(mozilla::EventMessage aEventMessage) = 0;
-
- /**
- * Tell the window that it should stop to listen to the network event of the
- * given aType.
- *
- * Inner windows only.
- */
- virtual void DisableNetworkEvent(mozilla::EventMessage aEventMessage) = 0;
-#endif // MOZ_B2G
-
/**
* Tell this window that there is an observer for gamepad input
*
diff --git a/dom/base/test/file_ipc_messagemanager_blob.html b/dom/base/test/file_ipc_messagemanager_blob.html
new file mode 100644
index 000000000..dbdd64a34
--- /dev/null
+++ b/dom/base/test/file_ipc_messagemanager_blob.html
@@ -0,0 +1 @@
+<!DOCTYPE HTML><html><body></body></html>
diff --git a/dom/base/test/file_simplecontentpolicy.js b/dom/base/test/file_simplecontentpolicy.js
index 1f9606c49..2727b9530 100644
--- a/dom/base/test/file_simplecontentpolicy.js
+++ b/dom/base/test/file_simplecontentpolicy.js
@@ -39,7 +39,6 @@ var policy = {
{
// Remember last content type seen for the test url
if (contentLocation.spec.endsWith(urlSuffix)) {
- assert.ok(frame === browserElement, "correct <browser> element");
sendAsyncMessage("shouldLoad", {contentType: contentType, isTopLevel: isTopLevel});
return Ci.nsIContentPolicy.REJECT_REQUEST;
}
diff --git a/dom/base/test/mochitest.ini b/dom/base/test/mochitest.ini
index ddfd57443..b3b804ce4 100644
--- a/dom/base/test/mochitest.ini
+++ b/dom/base/test/mochitest.ini
@@ -676,6 +676,7 @@ skip-if = (toolkit == 'android') # Android: Bug 775227
[test_intersectionobservers.html]
skip-if = true # Track Bug 1320704
[test_ipc_messagemanager_blob.html]
+support-files = file_ipc_messagemanager_blob.html
[test_link_prefetch.html]
skip-if = !e10s # Track Bug 1281415
[test_link_stylesheet.html]
diff --git a/dom/base/test/test_ipc_messagemanager_blob.html b/dom/base/test/test_ipc_messagemanager_blob.html
index 74eab2945..77d6c767f 100644
--- a/dom/base/test/test_ipc_messagemanager_blob.html
+++ b/dom/base/test/test_ipc_messagemanager_blob.html
@@ -14,8 +14,7 @@
SimpleTest.waitForExplicitFinish();
- const childFrameURL =
- "data:text/html,<!DOCTYPE HTML><html><body></body></html>";
+ const childFrameURL = "file_ipc_messagemanager_blob.html";
function childFrameScript() {
"use strict";
diff --git a/dom/base/test/test_x-frame-options.html b/dom/base/test/test_x-frame-options.html
index 8e24d8a78..a0c7acdc3 100644
--- a/dom/base/test/test_x-frame-options.html
+++ b/dom/base/test/test_x-frame-options.html
@@ -147,7 +147,11 @@ var testFrameInDataURI = function() {
SimpleTest.waitForExplicitFinish();
// load the test harness
-document.getElementById("harness").src = "file_x-frame-options_main.html";
+SpecialPowers.pushPrefEnv({
+ "set": [["security.data_uri.block_toplevel_data_uri_navigations", false],]
+}, function() {
+ document.getElementById("harness").src = "file_x-frame-options_main.html";
+});
</script>
</pre>
diff --git a/dom/bindings/BindingUtils.cpp b/dom/bindings/BindingUtils.cpp
index 33f5f7a44..7056658a7 100644
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -259,8 +259,8 @@ TErrorResult<CleanupPolicy>::ThrowJSException(JSContext* cx, JS::Handle<JS::Valu
// Make sure mJSException is initialized _before_ we try to root it. But
// don't set it to exn yet, because we don't want to do that until after we
// root.
- mJSException.setUndefined();
- if (!js::AddRawValueRoot(cx, &mJSException, "TErrorResult::mJSException")) {
+ mJSException.asValueRef().setUndefined();
+ if (!js::AddRawValueRoot(cx, &mJSException.asValueRef(), "TErrorResult::mJSException")) {
// Don't use NS_ERROR_DOM_JS_EXCEPTION, because that indicates we have
// in fact rooted mJSException.
mResult = NS_ERROR_OUT_OF_MEMORY;
@@ -289,7 +289,7 @@ TErrorResult<CleanupPolicy>::SetPendingJSException(JSContext* cx)
mJSException = exception;
// If JS_WrapValue failed, not much we can do about it... No matter
// what, go ahead and unroot mJSException.
- js::RemoveRawValueRoot(cx, &mJSException);
+ js::RemoveRawValueRoot(cx, &mJSException.asValueRef());
mResult = NS_OK;
#ifdef DEBUG
@@ -395,8 +395,8 @@ TErrorResult<CleanupPolicy>::ClearUnionData()
if (IsJSException()) {
JSContext* cx = dom::danger::GetJSContext();
MOZ_ASSERT(cx);
- mJSException.setUndefined();
- js::RemoveRawValueRoot(cx, &mJSException);
+ mJSException.asValueRef().setUndefined();
+ js::RemoveRawValueRoot(cx, &mJSException.asValueRef());
#ifdef DEBUG
mUnionState = HasNothing;
#endif // DEBUG
@@ -439,13 +439,13 @@ TErrorResult<CleanupPolicy>::operator=(TErrorResult<CleanupPolicy>&& aRHS)
} else if (aRHS.IsJSException()) {
JSContext* cx = dom::danger::GetJSContext();
MOZ_ASSERT(cx);
- mJSException.setUndefined();
- if (!js::AddRawValueRoot(cx, &mJSException, "TErrorResult::mJSException")) {
+ mJSException.asValueRef().setUndefined();
+ if (!js::AddRawValueRoot(cx, &mJSException.asValueRef(), "TErrorResult::mJSException")) {
MOZ_CRASH("Could not root mJSException, we're about to OOM");
}
mJSException = aRHS.mJSException;
- aRHS.mJSException.setUndefined();
- js::RemoveRawValueRoot(cx, &aRHS.mJSException);
+ aRHS.mJSException.asValueRef().setUndefined();
+ js::RemoveRawValueRoot(cx, &aRHS.mJSException.asValueRef());
} else if (aRHS.IsDOMException()) {
mDOMExceptionInfo = aRHS.mDOMExceptionInfo;
aRHS.mDOMExceptionInfo = nullptr;
@@ -497,7 +497,7 @@ TErrorResult<CleanupPolicy>::CloneTo(TErrorResult& aRv) const
aRv.mUnionState = HasJSException;
#endif
JSContext* cx = dom::danger::GetJSContext();
- JS::Rooted<JS::Value> exception(cx, mJSException);
+ JS::Rooted<JS::Value> exception(cx, mJSException.asValueRef());
aRv.ThrowJSException(cx, exception);
}
}
diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py
index 3174c37dd..7a6668687 100644
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -1069,6 +1069,20 @@ class CGHeaders(CGWrapper):
if parent:
ancestors.append(parent)
interfaceDeps.extend(ancestors)
+
+ # Include parent interface headers needed for jsonifier code.
+ jsonInterfaceParents = []
+ for desc in descriptors:
+ if not desc.operations['Jsonifier']:
+ continue
+ parent = desc.interface.parent
+ while parent:
+ parentDesc = desc.getDescriptor(parent.identifier.name)
+ if parentDesc.operations['Jsonifier']:
+ jsonInterfaceParents.append(parentDesc.interface)
+ parent = parent.parent
+ interfaceDeps.extend(jsonInterfaceParents)
+
bindingIncludes = set(self.getDeclarationFilename(d) for d in interfaceDeps)
# Grab all the implementation declaration files we need.
diff --git a/dom/bindings/ErrorResult.h b/dom/bindings/ErrorResult.h
index c45e7ea3b..7c3fc9e2f 100644
--- a/dom/bindings/ErrorResult.h
+++ b/dom/bindings/ErrorResult.h
@@ -461,7 +461,7 @@ private:
// (and deallocated) by SetPendingDOMException.
union {
Message* mMessage; // valid when IsErrorWithMessage()
- JS::Value mJSException; // valid when IsJSException()
+ JS::UninitializedValue mJSException; // valid when IsJSException()
DOMExceptionInfo* mDOMExceptionInfo; // valid when IsDOMException()
};
diff --git a/dom/browser-element/mochitest/browserElementTestHelpers.js b/dom/browser-element/mochitest/browserElementTestHelpers.js
index 004b25333..8df1476ac 100644
--- a/dom/browser-element/mochitest/browserElementTestHelpers.js
+++ b/dom/browser-element/mochitest/browserElementTestHelpers.js
@@ -84,6 +84,10 @@ const browserElementTestHelpers = {
this.unlockTestReady.bind(this));
},
+ allowTopLevelDataURINavigation: function() {
+ this._setPref("security.data_uri.block_toplevel_data_uri_navigations", false);
+ },
+
_observers: [],
// This function is a wrapper which lets you register an observer to one of
diff --git a/dom/browser-element/mochitest/browserElement_BrowserWindowResize.js b/dom/browser-element/mochitest/browserElement_BrowserWindowResize.js
index 420b4bc34..65a777861 100644
--- a/dom/browser-element/mochitest/browserElement_BrowserWindowResize.js
+++ b/dom/browser-element/mochitest/browserElement_BrowserWindowResize.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function runTest() {
var srcResizeTo = "data:text/html, \
diff --git a/dom/browser-element/mochitest/browserElement_Close.js b/dom/browser-element/mochitest/browserElement_Close.js
index 57bdf384d..103805404 100644
--- a/dom/browser-element/mochitest/browserElement_Close.js
+++ b/dom/browser-element/mochitest/browserElement_Close.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function runTest() {
var iframe = document.createElement('iframe');
diff --git a/dom/browser-element/mochitest/browserElement_ContextmenuEvents.js b/dom/browser-element/mochitest/browserElement_ContextmenuEvents.js
index 66aa8e015..a8c361ebd 100644
--- a/dom/browser-element/mochitest/browserElement_ContextmenuEvents.js
+++ b/dom/browser-element/mochitest/browserElement_ContextmenuEvents.js
@@ -4,6 +4,7 @@ SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.setClipboardPlainTextOnlyPref(false);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
var audioUrl = 'http://mochi.test:8888/tests/dom/browser-element/mochitest/audio.ogg';
var videoUrl = 'http://mochi.test:8888/tests/dom/browser-element/mochitest/short-video.ogv';
diff --git a/dom/browser-element/mochitest/browserElement_CopyPaste.js b/dom/browser-element/mochitest/browserElement_CopyPaste.js
index b23feef59..97a37be8b 100644
--- a/dom/browser-element/mochitest/browserElement_CopyPaste.js
+++ b/dom/browser-element/mochitest/browserElement_CopyPaste.js
@@ -9,6 +9,7 @@ SimpleTest.requestFlakyTimeout("untriaged");
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.setupAccessibleCaretPref();
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
const { Services } = SpecialPowers.Cu.import('resource://gre/modules/Services.jsm');
var gTextarea = null;
diff --git a/dom/browser-element/mochitest/browserElement_DataURI.js b/dom/browser-element/mochitest/browserElement_DataURI.js
index f57f4566a..d31678f89 100644
--- a/dom/browser-element/mochitest/browserElement_DataURI.js
+++ b/dom/browser-element/mochitest/browserElement_DataURI.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function runTest() {
var iframe1 = document.createElement('iframe');
diff --git a/dom/browser-element/mochitest/browserElement_Iconchange.js b/dom/browser-element/mochitest/browserElement_Iconchange.js
index 367a2de15..283331d3c 100644
--- a/dom/browser-element/mochitest/browserElement_Iconchange.js
+++ b/dom/browser-element/mochitest/browserElement_Iconchange.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function createHtml(link) {
return 'data:text/html,<html><head>' + link + '<body></body></html>';
diff --git a/dom/browser-element/mochitest/browserElement_Manifestchange.js b/dom/browser-element/mochitest/browserElement_Manifestchange.js
index 22cf8fe7c..5b3733d14 100644
--- a/dom/browser-element/mochitest/browserElement_Manifestchange.js
+++ b/dom/browser-element/mochitest/browserElement_Manifestchange.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function createHtml(manifest) {
return 'data:text/html,<html xmlns:xml="http://www.w3.org/XML/1998/namespace"><head>' + manifest + '<body></body></html>';
diff --git a/dom/browser-element/mochitest/browserElement_Metachange.js b/dom/browser-element/mochitest/browserElement_Metachange.js
index 7789a3e18..53c8d2397 100644
--- a/dom/browser-element/mochitest/browserElement_Metachange.js
+++ b/dom/browser-element/mochitest/browserElement_Metachange.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function createHtml(meta) {
return 'data:text/html,<html xmlns:xml="http://www.w3.org/XML/1998/namespace"><head>' + meta + '<body></body></html>';
diff --git a/dom/browser-element/mochitest/browserElement_Opensearch.js b/dom/browser-element/mochitest/browserElement_Opensearch.js
index 8df44d2a9..5762e6f0e 100644
--- a/dom/browser-element/mochitest/browserElement_Opensearch.js
+++ b/dom/browser-element/mochitest/browserElement_Opensearch.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function createHtml(link) {
return 'data:text/html,<html><head>' + link + '<body></body></html>';
diff --git a/dom/browser-element/mochitest/browserElement_PromptCheck.js b/dom/browser-element/mochitest/browserElement_PromptCheck.js
index d6edde09f..952f4468e 100644
--- a/dom/browser-element/mochitest/browserElement_PromptCheck.js
+++ b/dom/browser-element/mochitest/browserElement_PromptCheck.js
@@ -13,6 +13,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function runTest()
{
diff --git a/dom/browser-element/mochitest/browserElement_PromptConfirm.js b/dom/browser-element/mochitest/browserElement_PromptConfirm.js
index c01836a25..b920a6d26 100644
--- a/dom/browser-element/mochitest/browserElement_PromptConfirm.js
+++ b/dom/browser-element/mochitest/browserElement_PromptConfirm.js
@@ -11,6 +11,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function runTest() {
var iframe = document.createElement('iframe');
diff --git a/dom/browser-element/mochitest/browserElement_RemoveBrowserElement.js b/dom/browser-element/mochitest/browserElement_RemoveBrowserElement.js
index 583d58734..3ab206388 100644
--- a/dom/browser-element/mochitest/browserElement_RemoveBrowserElement.js
+++ b/dom/browser-element/mochitest/browserElement_RemoveBrowserElement.js
@@ -9,6 +9,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function runTest() {
var iframe = document.createElement('iframe');
diff --git a/dom/browser-element/mochitest/browserElement_ScrollEvent.js b/dom/browser-element/mochitest/browserElement_ScrollEvent.js
index 06dc91b86..5230c524a 100644
--- a/dom/browser-element/mochitest/browserElement_ScrollEvent.js
+++ b/dom/browser-element/mochitest/browserElement_ScrollEvent.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function runTest() {
var iframe = document.createElement('iframe');
diff --git a/dom/browser-element/mochitest/browserElement_Titlechange.js b/dom/browser-element/mochitest/browserElement_Titlechange.js
index 78c939ad8..145e9baa8 100644
--- a/dom/browser-element/mochitest/browserElement_Titlechange.js
+++ b/dom/browser-element/mochitest/browserElement_Titlechange.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
function runTest() {
var iframe1 = document.createElement('iframe');
diff --git a/dom/browser-element/mochitest/browserElement_TopBarrier.js b/dom/browser-element/mochitest/browserElement_TopBarrier.js
index 3bd68854c..186622b33 100644
--- a/dom/browser-element/mochitest/browserElement_TopBarrier.js
+++ b/dom/browser-element/mochitest/browserElement_TopBarrier.js
@@ -7,6 +7,7 @@
SimpleTest.waitForExplicitFinish();
browserElementTestHelpers.setEnabledPref(true);
browserElementTestHelpers.addPermission();
+browserElementTestHelpers.allowTopLevelDataURINavigation();
var iframe;
function runTest() {
diff --git a/dom/canvas/CanvasRenderingContext2D.cpp b/dom/canvas/CanvasRenderingContext2D.cpp
index a38c38293..f4c4259f6 100644
--- a/dom/canvas/CanvasRenderingContext2D.cpp
+++ b/dom/canvas/CanvasRenderingContext2D.cpp
@@ -141,10 +141,6 @@ using mozilla::gl::GLContextProvider;
#include "gfxWindowsPlatform.h"
#endif
-#ifdef MOZ_WIDGET_GONK
-#include "mozilla/layers/ShadowLayers.h"
-#endif
-
// windows.h (included by chromium code) defines this, in its infinite wisdom
#undef DrawText
diff --git a/dom/canvas/WebGLContext.cpp b/dom/canvas/WebGLContext.cpp
index 176d56f8c..2a92084b4 100644
--- a/dom/canvas/WebGLContext.cpp
+++ b/dom/canvas/WebGLContext.cpp
@@ -51,10 +51,6 @@
#include "VRManagerChild.h"
#include "mozilla/layers/TextureClientSharedSurface.h"
-#ifdef MOZ_WIDGET_GONK
-#include "mozilla/layers/ShadowLayers.h"
-#endif
-
// Local
#include "CanvasUtils.h"
#include "WebGL1Context.h"
@@ -545,30 +541,6 @@ BaseCaps(const WebGLContextOptions& options, WebGLContext* webgl)
// for now it's just behind a pref for testing/evaluation.
baseCaps.bpp16 = gfxPrefs::WebGLPrefer16bpp();
-#ifdef MOZ_WIDGET_GONK
- do {
- auto canvasElement = webgl->GetCanvas();
- if (!canvasElement)
- break;
-
- auto ownerDoc = canvasElement->OwnerDoc();
- nsIWidget* docWidget = nsContentUtils::WidgetForDocument(ownerDoc);
- if (!docWidget)
- break;
-
- layers::LayerManager* layerManager = docWidget->GetLayerManager();
- if (!layerManager)
- break;
-
- // XXX we really want "AsSurfaceAllocator" here for generality
- layers::ShadowLayerForwarder* forwarder = layerManager->AsShadowForwarder();
- if (!forwarder)
- break;
-
- baseCaps.surfaceAllocator = forwarder->GetTextureForwarder();
- } while (false);
-#endif
-
// Done with baseCaps construction.
if (!gfxPrefs::WebGLForceMSAA()) {
diff --git a/dom/canvas/test/webgl-mochitest/driver-info.js b/dom/canvas/test/webgl-mochitest/driver-info.js
index e2f6e003a..3f2fe102c 100644
--- a/dom/canvas/test/webgl-mochitest/driver-info.js
+++ b/dom/canvas/test/webgl-mochitest/driver-info.js
@@ -81,9 +81,6 @@ DriverInfo = (function() {
var versionMatch = /Mac OS X (\d+.\d+)/.exec(navigator.userAgent);
version = versionMatch ? parseFloat(versionMatch[1]) : null;
- } else if (runtime.widgetToolkit == 'gonk') {
- os = OS.B2G;
-
} else if (navigator.appVersion.indexOf('Android') != -1) {
os = OS.ANDROID;
// From layout/tools/reftest/reftest.js:
diff --git a/dom/console/Console.cpp b/dom/console/Console.cpp
index 79e3eadc5..ff5a92167 100755
--- a/dom/console/Console.cpp
+++ b/dom/console/Console.cpp
@@ -1336,10 +1336,7 @@ Console::MethodInternal(JSContext* aCx, MethodName aMethodName,
WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
MOZ_ASSERT(workerPrivate);
- TimeDuration duration =
- mozilla::TimeStamp::Now() - workerPrivate->NowBaseTimeStamp();
-
- monotonicTimer = TimerClamping::ReduceMsTimeValue(duration.ToMilliseconds());
+ monotonicTimer = workerPrivate->TimeStampToDOMHighRes(TimeStamp::Now());
}
}
diff --git a/dom/console/Console.h b/dom/console/Console.h
index b334d79f9..2f375c8eb 100644
--- a/dom/console/Console.h
+++ b/dom/console/Console.h
@@ -258,9 +258,8 @@ private:
// the max number of timers is reached.
// * aCx - the JSContext rooting aName.
// * aName - this is (should be) the name of the timer as JS::Value.
- // * aTimestamp - the monotonicTimer for this context (taken from
- // window->performance.now() or from Now() -
- // workerPrivate->NowBaseTimeStamp() in workers.
+ // * aTimestamp - the monotonicTimer for this context taken from
+ // performance.now().
// * aTimerLabel - This label will be populated with the aName converted to a
// string.
// * aTimerValue - the StartTimer value stored into (or taken from)
@@ -290,9 +289,8 @@ private:
// the aName timer doesn't exist in the mTimerRegistry.
// * aCx - the JSContext rooting aName.
// * aName - this is (should be) the name of the timer as JS::Value.
- // * aTimestamp - the monotonicTimer for this context (taken from
- // window->performance.now() or from Now() -
- // workerPrivate->NowBaseTimeStamp() in workers.
+ // * aTimestamp - the monotonicTimer for this context taken from
+ // performance.now().
// * aTimerLabel - This label will be populated with the aName converted to a
// string.
// * aTimerDuration - the difference between aTimestamp and when the timer
diff --git a/dom/downloads/DownloadsAPI.js b/dom/downloads/DownloadsAPI.js
deleted file mode 100644
index 8294e2a3e..000000000
--- a/dom/downloads/DownloadsAPI.js
+++ /dev/null
@@ -1,517 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-const Cr = Components.results;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
-Cu.import("resource://gre/modules/DownloadsIPC.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
- "@mozilla.org/childprocessmessagemanager;1",
- "nsIMessageSender");
-XPCOMUtils.defineLazyServiceGetter(this, "volumeService",
- "@mozilla.org/telephony/volume-service;1",
- "nsIVolumeService");
-
-/**
- * The content process implementations of navigator.mozDownloadManager and its
- * DOMDownload download objects. Uses DownloadsIPC.jsm to communicate with
- * DownloadsAPI.jsm in the parent process.
- */
-
-function debug(aStr) {
-#ifdef MOZ_DEBUG
- dump("-*- DownloadsAPI.js : " + aStr + "\n");
-#endif
-}
-
-function DOMDownloadManagerImpl() {
- debug("DOMDownloadManagerImpl constructor");
-}
-
-DOMDownloadManagerImpl.prototype = {
- __proto__: DOMRequestIpcHelper.prototype,
-
- // nsIDOMGlobalPropertyInitializer implementation
- init: function(aWindow) {
- debug("DownloadsManager init");
- this.initDOMRequestHelper(aWindow,
- ["Downloads:Added",
- "Downloads:Removed"]);
-
- // Get the manifest URL if this is an installed app
- let appsService = Cc["@mozilla.org/AppsService;1"]
- .getService(Ci.nsIAppsService);
- let principal = aWindow.document.nodePrincipal;
- // This returns the empty string if we're not an installed app. Coerce to
- // null.
- this._manifestURL = appsService.getManifestURLByLocalId(principal.appId) ||
- null;
- },
-
- uninit: function() {
- debug("uninit");
- downloadsCache.evict(this._window);
- },
-
- set ondownloadstart(aHandler) {
- this.__DOM_IMPL__.setEventHandler("ondownloadstart", aHandler);
- },
-
- get ondownloadstart() {
- return this.__DOM_IMPL__.getEventHandler("ondownloadstart");
- },
-
- getDownloads: function() {
- debug("getDownloads()");
-
- return this.createPromise(function (aResolve, aReject) {
- DownloadsIPC.getDownloads().then(
- function(aDownloads) {
- // Turn the list of download objects into DOM objects and
- // send them.
- let array = new this._window.Array();
- for (let id in aDownloads) {
- let dom = createDOMDownloadObject(this._window, aDownloads[id]);
- array.push(this._prepareForContent(dom));
- }
- aResolve(array);
- }.bind(this),
- function() {
- aReject("GetDownloadsError");
- }
- );
- }.bind(this));
- },
-
- clearAllDone: function() {
- debug("clearAllDone()");
- // This is a void function; we just kick it off. No promises, etc.
- DownloadsIPC.clearAllDone();
- },
-
- remove: function(aDownload) {
- debug("remove " + aDownload.url + " " + aDownload.id);
- return this.createPromise(function (aResolve, aReject) {
- if (!downloadsCache.has(this._window, aDownload.id)) {
- debug("no download " + aDownload.id);
- aReject("InvalidDownload");
- return;
- }
-
- DownloadsIPC.remove(aDownload.id).then(
- function(aResult) {
- let dom = createDOMDownloadObject(this._window, aResult);
- // Change the state right away to not race against the update message.
- dom.wrappedJSObject.state = "finalized";
- aResolve(this._prepareForContent(dom));
- }.bind(this),
- function() {
- aReject("RemoveError");
- }
- );
- }.bind(this));
- },
-
- adoptDownload: function(aAdoptDownloadDict) {
- // Our AdoptDownloadDict only includes simple types, which WebIDL enforces.
- // We have no object/any types so we do not need to worry about invoking
- // JSON.stringify (and it inheriting our security privileges).
- debug("adoptDownload");
- return this.createPromise(function (aResolve, aReject) {
- if (!aAdoptDownloadDict) {
- debug("Download dictionary is required!");
- aReject("InvalidDownload");
- return;
- }
- if (!aAdoptDownloadDict.storageName || !aAdoptDownloadDict.storagePath ||
- !aAdoptDownloadDict.contentType) {
- debug("Missing one of: storageName, storagePath, contentType");
- aReject("InvalidDownload");
- return;
- }
-
- // Convert storageName/storagePath to a local filesystem path.
- let volume;
- // getVolumeByName throws if you give it something it doesn't like
- // because XPConnect converts the NS_ERROR_NOT_AVAILABLE to an
- // exception. So catch it.
- try {
- volume = volumeService.getVolumeByName(aAdoptDownloadDict.storageName);
- } catch (ex) {}
- if (!volume) {
- debug("Invalid storage name: " + aAdoptDownloadDict.storageName);
- aReject("InvalidDownload");
- return;
- }
- let computedPath = volume.mountPoint + '/' +
- aAdoptDownloadDict.storagePath;
- // We validate that there is actually a file at the given path in the
- // parent process in DownloadsAPI.js because that's where the file
- // access would actually occur either way.
-
- // Create a DownloadsAPI.jsm 'jsonDownload' style representation.
- let jsonDownload = {
- url: aAdoptDownloadDict.url,
- path: computedPath,
- contentType: aAdoptDownloadDict.contentType,
- startTime: aAdoptDownloadDict.startTime.valueOf() || Date.now(),
- sourceAppManifestURL: this._manifestURL
- };
-
- DownloadsIPC.adoptDownload(jsonDownload).then(
- function(aResult) {
- let domDownload = createDOMDownloadObject(this._window, aResult);
- aResolve(this._prepareForContent(domDownload));
- }.bind(this),
- function(aResult) {
- // This will be one of: AdoptError (generic catch-all),
- // AdoptNoSuchFile, AdoptFileIsDirectory
- aReject(aResult.error);
- }
- );
- }.bind(this));
- },
-
-
- /**
- * Turns a chrome download object into a content accessible one.
- * When we have __DOM_IMPL__ available we just use that, otherwise
- * we run _create() with the wrapped js object.
- */
- _prepareForContent: function(aChromeObject) {
- if (aChromeObject.__DOM_IMPL__) {
- return aChromeObject.__DOM_IMPL__;
- }
- let res = this._window.DOMDownload._create(this._window,
- aChromeObject.wrappedJSObject);
- return res;
- },
-
- receiveMessage: function(aMessage) {
- let data = aMessage.data;
- switch(aMessage.name) {
- case "Downloads:Added":
- debug("Adding " + uneval(data));
- let event = new this._window.DownloadEvent("downloadstart", {
- download:
- this._prepareForContent(createDOMDownloadObject(this._window, data))
- });
- this.__DOM_IMPL__.dispatchEvent(event);
- break;
- }
- },
-
- classID: Components.ID("{c6587afa-0696-469f-9eff-9dac0dd727fe}"),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
- Ci.nsISupportsWeakReference,
- Ci.nsIObserver,
- Ci.nsIDOMGlobalPropertyInitializer]),
-
-};
-
-/**
- * Keep track of download objects per window.
- */
-var downloadsCache = {
- init: function() {
- this.cache = new WeakMap();
- },
-
- has: function(aWindow, aId) {
- let downloads = this.cache.get(aWindow);
- return !!(downloads && downloads[aId]);
- },
-
- get: function(aWindow, aDownload) {
- let downloads = this.cache.get(aWindow);
- if (!(downloads && downloads[aDownload.id])) {
- debug("Adding download " + aDownload.id + " to cache.");
- if (!downloads) {
- this.cache.set(aWindow, {});
- downloads = this.cache.get(aWindow);
- }
- // Create the object and add it to the cache.
- let impl = Cc["@mozilla.org/downloads/download;1"]
- .createInstance(Ci.nsISupports);
- impl.wrappedJSObject._init(aWindow, aDownload);
- downloads[aDownload.id] = impl;
- }
- return downloads[aDownload.id];
- },
-
- evict: function(aWindow) {
- this.cache.delete(aWindow);
- }
-};
-
-downloadsCache.init();
-
-/**
- * The DOM facade of a download object.
- */
-
-function createDOMDownloadObject(aWindow, aDownload) {
- return downloadsCache.get(aWindow, aDownload);
-}
-
-function DOMDownloadImpl() {
- debug("DOMDownloadImpl constructor ");
-
- this.wrappedJSObject = this;
- this.totalBytes = 0;
- this.currentBytes = 0;
- this.url = null;
- this.path = null;
- this.storageName = null;
- this.storagePath = null;
- this.contentType = null;
-
- /* fields that require getters/setters */
- this._error = null;
- this._startTime = new Date();
- this._state = "stopped";
-
- /* private fields */
- this.id = null;
-}
-
-DOMDownloadImpl.prototype = {
-
- createPromise: function(aPromiseInit) {
- return new this._window.Promise(aPromiseInit);
- },
-
- pause: function() {
- debug("DOMDownloadImpl pause");
- let id = this.id;
- // We need to wrap the Promise.jsm promise in a "real" DOM promise...
- return this.createPromise(function(aResolve, aReject) {
- DownloadsIPC.pause(id).then(aResolve, aReject);
- });
- },
-
- resume: function() {
- debug("DOMDownloadImpl resume");
- let id = this.id;
- // We need to wrap the Promise.jsm promise in a "real" DOM promise...
- return this.createPromise(function(aResolve, aReject) {
- DownloadsIPC.resume(id).then(aResolve, aReject);
- });
- },
-
- set onstatechange(aHandler) {
- this.__DOM_IMPL__.setEventHandler("onstatechange", aHandler);
- },
-
- get onstatechange() {
- return this.__DOM_IMPL__.getEventHandler("onstatechange");
- },
-
- get error() {
- return this._error;
- },
-
- set error(aError) {
- this._error = aError;
- },
-
- get startTime() {
- return this._startTime;
- },
-
- set startTime(aStartTime) {
- if (aStartTime instanceof Date) {
- this._startTime = aStartTime;
- }
- else {
- this._startTime = new Date(aStartTime);
- }
- },
-
- get state() {
- return this._state;
- },
-
- // We require a setter here to simplify the internals of the Download Manager
- // since we actually pass dummy JSON objects to the child process and update
- // them. This is the case for all other setters for read-only attributes
- // implemented in this object.
- set state(aState) {
- // We need to ensure that XPCOM consumers of this API respect the enum
- // values as well.
- if (["downloading",
- "stopped",
- "succeeded",
- "finalized"].indexOf(aState) != -1) {
- this._state = aState;
- }
- },
-
- /**
- * Initialize a DOMDownload instance for the given window using the
- * 'jsonDownload' serialized format of the download encoded by
- * DownloadsAPI.jsm.
- */
- _init: function(aWindow, aDownload) {
- this._window = aWindow;
- this.id = aDownload.id;
- this._update(aDownload);
- Services.obs.addObserver(this, "downloads-state-change-" + this.id,
- /* ownsWeak */ true);
- debug("observer set for " + this.id);
- },
-
- /**
- * Updates the state of the object and fires the statechange event.
- */
- _update: function(aDownload) {
- debug("update " + uneval(aDownload));
- if (this.id != aDownload.id) {
- return;
- }
-
- let props = ["totalBytes", "currentBytes", "url", "path", "storageName",
- "storagePath", "state", "contentType", "startTime",
- "sourceAppManifestURL"];
- let changed = false;
- let changedProps = {};
-
- props.forEach((prop) => {
- if (prop in aDownload && (aDownload[prop] != this[prop])) {
- this[prop] = aDownload[prop];
- changedProps[prop] = changed = true;
- }
- });
-
- // When the path changes, we should update the storage name and
- // storage path used for our downloaded file in case our download
- // was re-targetted to a different storage and/or filename.
- if (changedProps["path"]) {
- let storages = this._window.navigator.getDeviceStorages("sdcard");
- let preferredStorageName;
- // Use the first one or the default storage. Just like jsdownloads picks
- // the default / preferred download directory.
- storages.forEach((aStorage) => {
- if (aStorage.default || !preferredStorageName) {
- preferredStorageName = aStorage.storageName;
- }
- });
- // Now get the path for this storage area.
- let volume;
- if (preferredStorageName) {
- let volume = volumeService.getVolumeByName(preferredStorageName);
- if (volume) {
- // Finally, create the relative path of the file that can be used
- // later on to retrieve the file via DeviceStorage. Our path
- // needs to omit the starting '/'.
- this.storageName = preferredStorageName;
- this.storagePath =
- this.path.substring(this.path.indexOf(volume.mountPoint) +
- volume.mountPoint.length + 1);
- }
- }
- }
-
- if (aDownload.error) {
- //
- // When we get a generic error failure back from the js downloads api
- // we will verify the status of device storage to see if we can't provide
- // a better error result value.
- //
- // XXX If these checks expand further, consider moving them into their
- // own function.
- //
- let result = aDownload.error.result;
- let storage = this._window.navigator.getDeviceStorage("sdcard");
-
- // If we don't have access to device storage we'll opt out of these
- // extra checks as they are all dependent on the state of the storage.
- if (result == Cr.NS_ERROR_FAILURE && storage) {
- // We will delay sending the notification until we've inferred which
- // error is really happening.
- changed = false;
- debug("Attempting to infer error via device storage sanity checks.");
- // Get device storage and request availability status.
- let available = storage.available();
- available.onsuccess = (function() {
- debug("Storage Status = '" + available.result + "'");
- let inferredError = result;
- switch (available.result) {
- case "unavailable":
- inferredError = Cr.NS_ERROR_FILE_NOT_FOUND;
- break;
- case "shared":
- inferredError = Cr.NS_ERROR_FILE_ACCESS_DENIED;
- break;
- }
- this._updateWithError(aDownload, inferredError);
- }).bind(this);
- available.onerror = (function() {
- this._updateWithError(aDownload, result);
- }).bind(this);
- }
-
- this.error =
- new this._window.DOMError("DownloadError", result);
- } else {
- this.error = null;
- }
-
- // The visible state has not changed, so no need to fire an event.
- if (!changed) {
- return;
- }
-
- this._sendStateChange();
- },
-
- _updateWithError: function(aDownload, aError) {
- this.error =
- new this._window.DOMError("DownloadError", aError);
- this._sendStateChange();
- },
-
- _sendStateChange: function() {
- // __DOM_IMPL__ may not be available at first update.
- if (this.__DOM_IMPL__) {
- let event = new this._window.DownloadEvent("statechange", {
- download: this.__DOM_IMPL__
- });
- debug("Dispatching statechange event. state=" + this.state);
- this.__DOM_IMPL__.dispatchEvent(event);
- }
- },
-
- observe: function(aSubject, aTopic, aData) {
- debug("DOMDownloadImpl observe " + aTopic);
- if (aTopic !== "downloads-state-change-" + this.id) {
- return;
- }
-
- try {
- let download = JSON.parse(aData);
- // We get the start time as milliseconds, not as a Date object.
- if (download.startTime) {
- download.startTime = new Date(download.startTime);
- }
- this._update(download);
- } catch(e) {}
- },
-
- classID: Components.ID("{96b81b99-aa96-439d-8c59-92eeed34705f}"),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
- Ci.nsIObserver,
- Ci.nsISupportsWeakReference])
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([DOMDownloadManagerImpl,
- DOMDownloadImpl]);
diff --git a/dom/downloads/DownloadsAPI.jsm b/dom/downloads/DownloadsAPI.jsm
deleted file mode 100644
index dfb8286fe..000000000
--- a/dom/downloads/DownloadsAPI.jsm
+++ /dev/null
@@ -1,365 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
-this.EXPORTED_SYMBOLS = [];
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Downloads.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/osfile.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
- "@mozilla.org/parentprocessmessagemanager;1",
- "nsIMessageBroadcaster");
-
-/**
- * Parent process logic that services download API requests from the
- * DownloadAPI.js instances in content processeses. The actual work of managing
- * downloads is done by Toolkit's Downloads.jsm. This module is loaded by B2G's
- * shell.js
- */
-
-function debug(aStr) {
-#ifdef MOZ_DEBUG
- dump("-*- DownloadsAPI.jsm : " + aStr + "\n");
-#endif
-}
-
-function sendPromiseMessage(aMm, aMessageName, aData, aError) {
- debug("sendPromiseMessage " + aMessageName);
- let msg = {
- id: aData.id,
- promiseId: aData.promiseId
- };
-
- if (aError) {
- msg.error = aError;
- }
-
- aMm.sendAsyncMessage(aMessageName, msg);
-}
-
-var DownloadsAPI = {
- init: function() {
- debug("init");
-
- this._ids = new WeakMap(); // Maps toolkit download objects to ids.
- this._index = {}; // Maps ids to downloads.
-
- ["Downloads:GetList",
- "Downloads:ClearAllDone",
- "Downloads:Remove",
- "Downloads:Pause",
- "Downloads:Resume",
- "Downloads:Adopt"].forEach((msgName) => {
- ppmm.addMessageListener(msgName, this);
- });
-
- let self = this;
- Task.spawn(function () {
- let list = yield Downloads.getList(Downloads.ALL);
- yield list.addView(self);
-
- debug("view added to download list.");
- }).then(null, Components.utils.reportError);
-
- this._currentId = 0;
- },
-
- /**
- * Returns a unique id for each download, hashing the url and the path.
- */
- downloadId: function(aDownload) {
- let id = this._ids.get(aDownload, null);
- if (!id) {
- id = "download-" + this._currentId++;
- this._ids.set(aDownload, id);
- this._index[id] = aDownload;
- }
- return id;
- },
-
- getDownloadById: function(aId) {
- return this._index[aId];
- },
-
- /**
- * Converts a download object into a plain json object that we'll
- * send to the DOM side.
- */
- jsonDownload: function(aDownload) {
- let res = {
- totalBytes: aDownload.totalBytes,
- currentBytes: aDownload.currentBytes,
- url: aDownload.source.url,
- path: aDownload.target.path,
- contentType: aDownload.contentType,
- startTime: aDownload.startTime.getTime(),
- sourceAppManifestURL: aDownload._unknownProperties &&
- aDownload._unknownProperties.sourceAppManifestURL
- };
-
- if (aDownload.error) {
- res.error = aDownload.error;
- }
-
- res.id = this.downloadId(aDownload);
-
- // The state of the download. Can be any of "downloading", "stopped",
- // "succeeded", finalized".
-
- // Default to "stopped"
- res.state = "stopped";
- if (!aDownload.stopped &&
- !aDownload.canceled &&
- !aDownload.succeeded &&
- !aDownload.DownloadError) {
- res.state = "downloading";
- } else if (aDownload.succeeded) {
- res.state = "succeeded";
- }
- return res;
- },
-
- /**
- * download view methods.
- */
- onDownloadAdded: function(aDownload) {
- let download = this.jsonDownload(aDownload);
- debug("onDownloadAdded " + uneval(download));
- ppmm.broadcastAsyncMessage("Downloads:Added", download);
- },
-
- onDownloadRemoved: function(aDownload) {
- let download = this.jsonDownload(aDownload);
- download.state = "finalized";
- debug("onDownloadRemoved " + uneval(download));
- ppmm.broadcastAsyncMessage("Downloads:Removed", download);
- this._index[this._ids.get(aDownload)] = null;
- this._ids.delete(aDownload);
- },
-
- onDownloadChanged: function(aDownload) {
- let download = this.jsonDownload(aDownload);
- debug("onDownloadChanged " + uneval(download));
- ppmm.broadcastAsyncMessage("Downloads:Changed", download);
- },
-
- receiveMessage: function(aMessage) {
- if (!aMessage.target.assertPermission("downloads")) {
- debug("No 'downloads' permission!");
- return;
- }
-
- debug("message: " + aMessage.name);
-
- switch (aMessage.name) {
- case "Downloads:GetList":
- this.getList(aMessage.data, aMessage.target);
- break;
- case "Downloads:ClearAllDone":
- this.clearAllDone(aMessage.data, aMessage.target);
- break;
- case "Downloads:Remove":
- this.remove(aMessage.data, aMessage.target);
- break;
- case "Downloads:Pause":
- this.pause(aMessage.data, aMessage.target);
- break;
- case "Downloads:Resume":
- this.resume(aMessage.data, aMessage.target);
- break;
- case "Downloads:Adopt":
- this.adoptDownload(aMessage.data, aMessage.target);
- break;
- default:
- debug("Invalid message: " + aMessage.name);
- }
- },
-
- getList: function(aData, aMm) {
- debug("getList called!");
- let self = this;
- Task.spawn(function () {
- let list = yield Downloads.getList(Downloads.ALL);
- let downloads = yield list.getAll();
- let res = [];
- downloads.forEach((aDownload) => {
- res.push(self.jsonDownload(aDownload));
- });
- aMm.sendAsyncMessage("Downloads:GetList:Return", res);
- }).then(null, Components.utils.reportError);
- },
-
- clearAllDone: function(aData, aMm) {
- debug("clearAllDone called!");
- Task.spawn(function () {
- let list = yield Downloads.getList(Downloads.ALL);
- list.removeFinished();
- }).then(null, Components.utils.reportError);
- },
-
- remove: function(aData, aMm) {
- debug("remove id " + aData.id);
- let download = this.getDownloadById(aData.id);
- if (!download) {
- sendPromiseMessage(aMm, "Downloads:Remove:Return",
- aData, "NoSuchDownload");
- return;
- }
-
- Task.spawn(function() {
- yield download.finalize(true);
- let list = yield Downloads.getList(Downloads.ALL);
- yield list.remove(download);
- }).then(
- function() {
- sendPromiseMessage(aMm, "Downloads:Remove:Return", aData);
- },
- function() {
- sendPromiseMessage(aMm, "Downloads:Remove:Return",
- aData, "RemoveError");
- }
- );
- },
-
- pause: function(aData, aMm) {
- debug("pause id " + aData.id);
- let download = this.getDownloadById(aData.id);
- if (!download) {
- sendPromiseMessage(aMm, "Downloads:Pause:Return",
- aData, "NoSuchDownload");
- return;
- }
-
- download.cancel().then(
- function() {
- sendPromiseMessage(aMm, "Downloads:Pause:Return", aData);
- },
- function() {
- sendPromiseMessage(aMm, "Downloads:Pause:Return",
- aData, "PauseError");
- }
- );
- },
-
- resume: function(aData, aMm) {
- debug("resume id " + aData.id);
- let download = this.getDownloadById(aData.id);
- if (!download) {
- sendPromiseMessage(aMm, "Downloads:Resume:Return",
- aData, "NoSuchDownload");
- return;
- }
-
- download.start().then(
- function() {
- sendPromiseMessage(aMm, "Downloads:Resume:Return", aData);
- },
- function() {
- sendPromiseMessage(aMm, "Downloads:Resume:Return",
- aData, "ResumeError");
- }
- );
- },
-
- /**
- * Receive a download to adopt in the same representation we produce from
- * our "jsonDownload" normalizer and add it to the list of downloads.
- */
- adoptDownload: function(aData, aMm) {
- let adoptJsonRep = aData.jsonDownload;
- debug("adoptDownload " + uneval(adoptJsonRep));
-
- Task.spawn(function* () {
- // Verify that the file exists on disk. This will result in a rejection
- // if the file does not exist. We will also use this information for the
- // file size to avoid weird inconsistencies. We ignore the filesystem
- // timestamp in favor of whatever the caller is telling us.
- let fileInfo = yield OS.File.stat(adoptJsonRep.path);
-
- // We also require that the file is not a directory.
- if (fileInfo.isDir) {
- throw new Error("AdoptFileIsDirectory");
- }
-
- // We need to create a Download instance to add to the list. Create a
- // serialized representation and then from there the instance.
- let serializedRep = {
- // explicit initializations in toSerializable
- source: {
- url: adoptJsonRep.url
- // This is where isPrivate would go if adoption supported private
- // browsing.
- },
- target: {
- path: adoptJsonRep.path,
- },
- startTime: adoptJsonRep.startTime,
- // kPlainSerializableDownloadProperties propagations
- succeeded: true, // (all adopted downloads are required to be completed)
- totalBytes: fileInfo.size,
- contentType: adoptJsonRep.contentType,
- // unknown properties added/used by the DownloadsAPI
- currentBytes: fileInfo.size,
- sourceAppManifestURL: adoptJsonRep.sourceAppManifestURL
- };
-
- let download = yield Downloads.createDownload(serializedRep);
-
- // The ALL list is a DownloadCombinedList instance that combines the
- // PUBLIC (persisted to disk) and PRIVATE (ephemeral) download lists..
- // When we call add on it, it dispatches to the appropriate list based on
- // the 'isPrivate' field of the source. (Which we don't initialize and
- // defaults to false.)
- let allDownloadList = yield Downloads.getList(Downloads.ALL);
-
- // This add will automatically notify all views of the added download,
- // including DownloadsAPI instances and the DownloadAutoSaveView that's
- // subscribed to the PUBLIC list and will save the download.
- yield allDownloadList.add(download);
-
- debug("download adopted");
- // The notification above occurred synchronously, and so we will have
- // already dispatched an added notification for our download to the child
- // process in question. As such, we only need to relay the download id
- // since the download will already have been cached.
- return download;
- }.bind(this)).then(
- (download) => {
- sendPromiseMessage(aMm, "Downloads:Adopt:Return",
- {
- id: this.downloadId(download),
- promiseId: aData.promiseId
- });
- },
- (ex) => {
- let reportAs = "AdoptError";
- // Provide better error codes for expected errors.
- if (ex instanceof OS.File.Error && ex.becauseNoSuchFile) {
- reportAs = "AdoptNoSuchFile";
- } else if (ex.message === "AdoptFileIsDirectory") {
- reportAs = ex.message;
- } else {
- // Anything else is unexpected and should be reported to help track
- // down what's going wrong.
- debug("unexpected download error: " + ex);
- Cu.reportError(ex);
- }
- sendPromiseMessage(aMm, "Downloads:Adopt:Return",
- {
- promiseId: aData.promiseId
- },
- reportAs);
- });
- }
-};
-
-DownloadsAPI.init();
diff --git a/dom/downloads/DownloadsAPI.manifest b/dom/downloads/DownloadsAPI.manifest
deleted file mode 100644
index 8d6dc9396..000000000
--- a/dom/downloads/DownloadsAPI.manifest
+++ /dev/null
@@ -1,6 +0,0 @@
-# DownloadsAPI.js
-component {c6587afa-0696-469f-9eff-9dac0dd727fe} DownloadsAPI.js
-contract @mozilla.org/downloads/manager;1 {c6587afa-0696-469f-9eff-9dac0dd727fe}
-
-component {96b81b99-aa96-439d-8c59-92eeed34705f} DownloadsAPI.js
-contract @mozilla.org/downloads/download;1 {96b81b99-aa96-439d-8c59-92eeed34705f}
diff --git a/dom/downloads/DownloadsIPC.jsm b/dom/downloads/DownloadsIPC.jsm
deleted file mode 100644
index 0e290abf4..000000000
--- a/dom/downloads/DownloadsIPC.jsm
+++ /dev/null
@@ -1,224 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const Cc = Components.classes;
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
-this.EXPORTED_SYMBOLS = ["DownloadsIPC"];
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
- "@mozilla.org/childprocessmessagemanager;1",
- "nsIMessageSender");
-
-/**
- * This module lives in the child process and receives the ipc messages
- * from the parent. It saves the download's state and redispatch changes
- * to DOM objects using an observer notification.
- *
- * This module needs to be loaded once and only once per process.
- */
-
-function debug(aStr) {
-#ifdef MOZ_DEBUG
- dump("-*- DownloadsIPC.jsm : " + aStr + "\n");
-#endif
-}
-
-const ipcMessages = ["Downloads:Added",
- "Downloads:Removed",
- "Downloads:Changed",
- "Downloads:GetList:Return",
- "Downloads:Remove:Return",
- "Downloads:Pause:Return",
- "Downloads:Resume:Return",
- "Downloads:Adopt:Return"];
-
-this.DownloadsIPC = {
- downloads: {},
-
- init: function() {
- debug("init");
- Services.obs.addObserver(this, "xpcom-shutdown", false);
- ipcMessages.forEach((aMessage) => {
- cpmm.addMessageListener(aMessage, this);
- });
-
- // We need to get the list of current downloads.
- this.ready = false;
- this.getListPromises = [];
- this.downloadPromises = {};
- cpmm.sendAsyncMessage("Downloads:GetList", {});
- this._promiseId = 0;
- },
-
- notifyChanges: function(aId) {
- // TODO: use the subject instead of stringifying.
- if (this.downloads[aId]) {
- debug("notifyChanges notifying changes for " + aId);
- Services.obs.notifyObservers(null, "downloads-state-change-" + aId,
- JSON.stringify(this.downloads[aId]));
- } else {
- debug("notifyChanges failed for " + aId)
- }
- },
-
- _updateDownloadsArray: function(aDownloads) {
- this.downloads = [];
- // We actually have an array of downloads.
- aDownloads.forEach((aDownload) => {
- this.downloads[aDownload.id] = aDownload;
- });
- },
-
- receiveMessage: function(aMessage) {
- let download = aMessage.data;
- debug("message: " + aMessage.name);
- switch(aMessage.name) {
- case "Downloads:GetList:Return":
- this._updateDownloadsArray(download);
-
- if (!this.ready) {
- this.getListPromises.forEach(aPromise =>
- aPromise.resolve(this.downloads));
- this.getListPromises.length = 0;
- }
- this.ready = true;
- break;
- case "Downloads:Added":
- this.downloads[download.id] = download;
- this.notifyChanges(download.id);
- break;
- case "Downloads:Removed":
- if (this.downloads[download.id]) {
- this.downloads[download.id] = download;
- this.notifyChanges(download.id);
- delete this.downloads[download.id];
- }
- break;
- case "Downloads:Changed":
- // Only update properties that actually changed.
- let cached = this.downloads[download.id];
- if (!cached) {
- debug("No download found for " + download.id);
- return;
- }
- let props = ["totalBytes", "currentBytes", "url", "path", "state",
- "contentType", "startTime"];
- let changed = false;
-
- props.forEach((aProp) => {
- if (download[aProp] && (download[aProp] != cached[aProp])) {
- cached[aProp] = download[aProp];
- changed = true;
- }
- });
-
- // Updating the error property. We always get a 'state' change as
- // well.
- cached.error = download.error;
-
- if (changed) {
- this.notifyChanges(download.id);
- }
- break;
- case "Downloads:Remove:Return":
- case "Downloads:Pause:Return":
- case "Downloads:Resume:Return":
- case "Downloads:Adopt:Return":
- if (this.downloadPromises[download.promiseId]) {
- if (!download.error) {
- this.downloadPromises[download.promiseId].resolve(download);
- } else {
- this.downloadPromises[download.promiseId].reject(download);
- }
- delete this.downloadPromises[download.promiseId];
- }
- break;
- }
- },
-
- /**
- * Returns a promise that is resolved with the list of current downloads.
- */
- getDownloads: function() {
- debug("getDownloads()");
- let deferred = Promise.defer();
- if (this.ready) {
- debug("Returning existing list.");
- deferred.resolve(this.downloads);
- } else {
- this.getListPromises.push(deferred);
- }
- return deferred.promise;
- },
-
- /**
- * Void function to trigger removal of completed downloads.
- */
- clearAllDone: function() {
- debug("clearAllDone");
- cpmm.sendAsyncMessage("Downloads:ClearAllDone", {});
- },
-
- promiseId: function() {
- return this._promiseId++;
- },
-
- remove: function(aId) {
- debug("remove " + aId);
- let deferred = Promise.defer();
- let pId = this.promiseId();
- this.downloadPromises[pId] = deferred;
- cpmm.sendAsyncMessage("Downloads:Remove",
- { id: aId, promiseId: pId });
- return deferred.promise;
- },
-
- pause: function(aId) {
- debug("pause " + aId);
- let deferred = Promise.defer();
- let pId = this.promiseId();
- this.downloadPromises[pId] = deferred;
- cpmm.sendAsyncMessage("Downloads:Pause",
- { id: aId, promiseId: pId });
- return deferred.promise;
- },
-
- resume: function(aId) {
- debug("resume " + aId);
- let deferred = Promise.defer();
- let pId = this.promiseId();
- this.downloadPromises[pId] = deferred;
- cpmm.sendAsyncMessage("Downloads:Resume",
- { id: aId, promiseId: pId });
- return deferred.promise;
- },
-
- adoptDownload: function(aJsonDownload) {
- debug("adoptDownload");
- let deferred = Promise.defer();
- let pId = this.promiseId();
- this.downloadPromises[pId] = deferred;
- cpmm.sendAsyncMessage("Downloads:Adopt",
- { jsonDownload: aJsonDownload, promiseId: pId });
- return deferred.promise;
- },
-
- observe: function(aSubject, aTopic, aData) {
- if (aTopic == "xpcom-shutdown") {
- ipcMessages.forEach((aMessage) => {
- cpmm.removeMessageListener(aMessage, this);
- });
- }
- }
-};
-
-DownloadsIPC.init();
diff --git a/dom/downloads/moz.build b/dom/downloads/moz.build
deleted file mode 100644
index 07bda1c4f..000000000
--- a/dom/downloads/moz.build
+++ /dev/null
@@ -1,21 +0,0 @@
-# -*- 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_B2G"]:
- MOCHITEST_MANIFESTS += ['tests/mochitest.ini']
-
-EXTRA_COMPONENTS += [
- 'DownloadsAPI.manifest',
-]
-
-EXTRA_PP_COMPONENTS += [
- 'DownloadsAPI.js',
-]
-
-EXTRA_PP_JS_MODULES += [
- 'DownloadsAPI.jsm',
- 'DownloadsIPC.jsm',
-]
diff --git a/dom/downloads/tests/clear_all_done_helper.js b/dom/downloads/tests/clear_all_done_helper.js
deleted file mode 100644
index 62fa1a2f3..000000000
--- a/dom/downloads/tests/clear_all_done_helper.js
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * A helper to clear out the existing downloads known to the mozDownloadManager
- * / downloads.js.
- *
- * It exists because previously mozDownloadManager.clearAllDone() thought that
- * when it returned that all the completed downloads would be cleared out. It
- * was wrong and this led to various intermittent test failurse. In discussion
- * on https://bugzil.la/979446#c13 and onwards, it was decided that
- * clearAllDone() was in the wrong and that the jsdownloads API it depends on
- * was not going to change to make it be in the right.
- *
- * The existing uses of clearAllDone() in tests seemed to be about:
- * - Exploding if there was somehow still a download in progress
- * - Clearing out the download list at the start of a test so that calls to
- * getDownloads() wouldn't have to worry about existing downloads, etc.
- *
- * From discussion, the right way to handle clearing is to wait for the expected
- * removal events to occur for the existing downloads. So that's what we do.
- * We still generate a test failure if there are any in-progress downloads.
- *
- * @param {Boolean} [getDownloads=false]
- * If true, invoke getDownloads after clearing the download list and return
- * its value.
- */
-function clearAllDoneHelper(getDownloads) {
- var clearedPromise = new Promise(function(resolve, reject) {
- function gotDownloads(downloads) {
- // If there are no downloads, we're already done.
- if (downloads.length === 0) {
- resolve();
- return;
- }
-
- // Track the set of expected downloads that will be finalized.
- var expectedIds = new Set();
- function changeHandler(evt) {
- var download = evt.download;
- if (download.state === "finalized") {
- expectedIds.delete(download.id);
- if (expectedIds.size === 0) {
- resolve();
- }
- }
- }
- downloads.forEach(function(download) {
- if (download.state === "downloading") {
- ok(false, "A download is still active: " + download.path);
- reject("Active download");
- }
- download.onstatechange = changeHandler;
- expectedIds.add(download.id);
- });
- navigator.mozDownloadManager.clearAllDone();
- }
- function gotBadNews(err) {
- ok(false, "Problem clearing all downloads: " + err);
- reject(err);
- }
- navigator.mozDownloadManager.getDownloads().then(gotDownloads, gotBadNews);
- });
- if (!getDownloads) {
- return clearedPromise;
- }
- return clearedPromise.then(function() {
- return navigator.mozDownloadManager.getDownloads();
- });
-}
diff --git a/dom/downloads/tests/mochitest.ini b/dom/downloads/tests/mochitest.ini
deleted file mode 100644
index e13e4d887..000000000
--- a/dom/downloads/tests/mochitest.ini
+++ /dev/null
@@ -1,15 +0,0 @@
-[DEFAULT]
-# The actual requirement for mozDownloadManager is MOZ_GONK because of
-# the nsIVolumeService dependency. Until https://bugzil.la/1130264 is
-# addressed, there is no way for mulet to run these tests.
-run-if = toolkit == 'gonk'
-support-files =
- serve_file.sjs
- clear_all_done_helper.js
-
-[test_downloads_navigator_object.html]
-[test_downloads_basic.html]
-[test_downloads_large.html]
-[test_downloads_bad_file.html]
-[test_downloads_pause_remove.html]
-[test_downloads_pause_resume.html]
diff --git a/dom/downloads/tests/serve_file.sjs b/dom/downloads/tests/serve_file.sjs
deleted file mode 100644
index d0171d7ca..000000000
--- a/dom/downloads/tests/serve_file.sjs
+++ /dev/null
@@ -1,170 +0,0 @@
-// Serves a file with a given mime type and size at an optionally given rate.
-
-function getQuery(request) {
- var query = {};
- request.queryString.split('&').forEach(function (val) {
- var [name, value] = val.split('=');
- query[name] = unescape(value);
- });
- return query;
-}
-
-function handleResponse() {
- // Is this a rate limited response?
- if (this.state.rate > 0) {
- // Calculate how many bytes we have left to send.
- var bytesToWrite = this.state.totalBytes - this.state.sentBytes;
-
- // Do we have any bytes left to send? If not we'll just fall thru and
- // cancel our repeating timer and finalize the response.
- if (bytesToWrite > 0) {
- // Figure out how many bytes to send, based on the rate limit.
- bytesToWrite =
- (bytesToWrite > this.state.rate) ? this.state.rate : bytesToWrite;
-
- for (let i = 0; i < bytesToWrite; i++) {
- try {
- this.response.bodyOutputStream.write("0", 1);
- } catch (e) {
- // Connection was closed by client.
- if (e == Components.results.NS_ERROR_NOT_AVAILABLE) {
- // There's no harm in calling this multiple times.
- this.response.finish();
-
- // It's possible that our timer wasn't cancelled in time
- // and we'll be called again.
- if (this.timer) {
- this.timer.cancel();
- this.timer = null;
- }
-
- return;
- }
- }
- }
-
- // Update the number of bytes we've sent to the client.
- this.state.sentBytes += bytesToWrite;
-
- // Wait until the next call to do anything else.
- return;
- }
- }
- else {
- // Not rate limited, write it all out.
- for (let i = 0; i < this.state.totalBytes; i++) {
- this.response.write("0");
- }
- }
-
- // Finalize the response.
- this.response.finish();
-
- // All done sending, go ahead and cancel our repeating timer.
- this.timer.cancel();
-
- // Clear the timer.
- this.timer = null;
-}
-
-function handleRequest(request, response) {
- var query = getQuery(request);
-
- // sending at a specific rate requires our response to be asynchronous so
- // we handle all requests asynchronously. See handleResponse().
- response.processAsync();
-
- // Default status when responding.
- var version = "1.1";
- var statusCode = 200;
- var description = "OK";
-
- // Default values for content type, size and rate.
- var contentType = "text/plain";
- var contentRange = null;
- var size = 1024;
- var rate = 0;
-
- // optional content type to be used by our response.
- if ("contentType" in query) {
- contentType = query["contentType"];
- }
-
- // optional size (in bytes) for generated file.
- if ("size" in query) {
- size = parseInt(query["size"]);
- }
-
- // optional range request check.
- if (request.hasHeader("range")) {
- version = "1.1";
- statusCode = 206;
- description = "Partial Content";
-
- // We'll only support simple range byte style requests.
- var [offset, total] = request.getHeader("range").slice("bytes=".length).split("-");
- // Enforce valid Number values.
- offset = parseInt(offset);
- offset = isNaN(offset) ? 0 : offset;
- // Same.
- total = parseInt(total);
- total = isNaN(total) ? 0 : total;
-
- // We'll need to original total size as part of the Content-Range header
- // value in our response.
- var originalSize = size;
-
- // If we have a total size requested, we must make sure to send that number
- // of bytes only (minus the start offset).
- if (total && total < size) {
- size = total - offset;
- } else if (offset) {
- // Looks like we just have a byte offset to deal with.
- size = size - offset;
- }
-
- // We specifically need to add a Content-Range header to all responses for
- // requests that include a range request header.
- contentRange = "bytes " + offset + "-" + (size - 1) + "/" + originalSize;
- }
-
- // optional rate (in bytes/s) at which to send the file.
- if ("rate" in query) {
- rate = parseInt(query["rate"]);
- }
-
- // The context for the responseHandler.
- var context = {
- response: response,
- state: {
- contentType: contentType,
- totalBytes: size,
- sentBytes: 0,
- rate: rate
- },
- timer: null
- };
-
- // The notify implementation for the timer.
- context.notify = handleResponse.bind(context);
-
- context.timer =
- Components.classes["@mozilla.org/timer;1"]
- .createInstance(Components.interfaces.nsITimer);
-
- // generate the content.
- response.setStatusLine(version, statusCode, description);
- response.setHeader("Content-Type", contentType, false);
- if (contentRange) {
- response.setHeader("Content-Range", contentRange, false);
- }
- response.setHeader("Content-Length", size.toString(), false);
-
- // initialize the timer and start writing out the response.
- context.timer.initWithCallback(
- context,
- 1000,
- Components.interfaces.nsITimer.TYPE_REPEATING_SLACK
- );
-
-}
diff --git a/dom/downloads/tests/test_downloads_bad_file.html b/dom/downloads/tests/test_downloads_bad_file.html
deleted file mode 100644
index a2b3992e6..000000000
--- a/dom/downloads/tests/test_downloads_bad_file.html
+++ /dev/null
@@ -1,93 +0,0 @@
-<!DOCTYPE html>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=960749
--->
-<head>
- <title>Test for Bug 960749 Downloads API</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=960749">Mozilla Bug 960749</a>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<a href="serve_file.sjs?contentType=application/octet-stream&size=1024" download=".&lt;.EVIL.&gt;\ / : * ? &quot; |file.bin" id="download1">Download #1</a>
-<pre id="test">
-<script class="testbody" type="text/javascript;version=1.7">
-
-// Testing a simple download, waiting for it to be done.
-
-SimpleTest.waitForExplicitFinish();
-
-var index = -1;
-var expected = "_.EVIL.__ _ _ _ _ _ _file.bin";
-
-function next() {
- index += 1;
- if (index >= steps.length) {
- ok(false, "Shouldn't get here!");
- return;
- }
- try {
- steps[index]();
- } catch(ex) {
- ok(false, "Caught exception", ex);
- }
-}
-
-function checkTargetFilename(download) {
- ok(download.path.endsWith(expected),
- "Download path leaf name '" + download.path +
- "' should match '" + expected + "' filename.");
-
- SimpleTest.finish();
-}
-
-function downloadChange(evt) {
- var download = evt.download;
-
- if (download.state === "succeeded") {
- checkTargetFilename(download);
- }
-}
-
-function downloadStart(evt) {
- var download = evt.download;
- download.onstatechange = downloadChange;
-}
-
-var steps = [
- // Start by setting the pref to true.
- function() {
- SpecialPowers.pushPrefEnv({
- set: [["dom.mozDownloads.enabled", true]]
- }, next);
- },
-
- // Setup the event listeners.
- function() {
- SpecialPowers.pushPermissions([
- {type: "downloads", allow: true, context: document}
- ], function() {
- navigator.mozDownloadManager.ondownloadstart = downloadStart;
- next();
- });
- },
-
- // Click on the <a download> to start the download.
- function() {
- document.getElementById("download1").click();
- }
-];
-
-next();
-
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/dom/downloads/tests/test_downloads_basic.html b/dom/downloads/tests/test_downloads_basic.html
deleted file mode 100644
index 051a1faa1..000000000
--- a/dom/downloads/tests/test_downloads_basic.html
+++ /dev/null
@@ -1,128 +0,0 @@
-<!DOCTYPE html>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=938023
--->
-<head>
- <title>Test for Bug 938023 Downloads API</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=938023">Mozilla Bug 938023</a>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<a href="serve_file.sjs?contentType=application/octet-stream&size=1024" download="test.bin" id="download1">Download #1</a>
-<pre id="test">
-<script class="testbody" type="text/javascript;version=1.7">
-
-// Testing a simple download, waiting for it to be done.
-
-SimpleTest.waitForExplicitFinish();
-
-var index = -1;
-var todayDate = new Date();
-var baseServeURL = "http://mochi.test:8888/tests/dom/downloads/tests/";
-var lastKnownCurrentBytes = 0;
-
-function next() {
- index += 1;
- if (index >= steps.length) {
- ok(false, "Shouldn't get here!");
- return;
- }
- try {
- steps[index]();
- } catch(ex) {
- ok(false, "Caught exception", ex);
- }
-}
-
-function checkConsistentDownloadAttributes(download) {
- var href = document.getElementById("download1").getAttribute("href");
- var expectedServeURL = baseServeURL + href;
- var destinationRegEx = /test\(?[0-9]*\)?\.bin$/;
-
- // bug 945323: Download path isn't honoring download attribute
- ok(destinationRegEx.test(download.path),
- "Download path '" + download.path +
- "' should match '" + destinationRegEx + "' regexp.");
-
- ok(download.startTime >= todayDate,
- "Download start time should be greater than or equal to today");
-
- is(download.error, null, "Download does not have an error");
-
- is(download.url, expectedServeURL,
- "Download URL = " + expectedServeURL);
- ok(download.id !== null, "Download id is defined");
- is(download.contentType, "application/octet-stream",
- "Download content type is application/octet-stream");
-}
-
-function downloadChange(evt) {
- var download = evt.download;
- checkConsistentDownloadAttributes(download);
- is(download.totalBytes, 1024, "Download total size is 1024 bytes");
-
- if (download.state === "succeeded") {
- is(download.currentBytes, 1024, "Download current size is 1024 bytes");
- SimpleTest.finish();
- } else if (download.state === "downloading") {
- // Note that this case may or may not trigger, depending on whether the
- // download is initially reported with 0 bytes (we should happen) or with
- // 1024 bytes (we should not happen). If we do happen, an additional 8
- // TEST-PASS events should be logged.
- ok(download.currentBytes > lastKnownCurrentBytes,
- "Download current size is larger than last download change event");
- lastKnownCurrentBytes = download.currentBytes;
- } else {
- ok(false, "Unexpected download state = " + download.state);
- }
-}
-
-function downloadStart(evt) {
- var download = evt.download;
- checkConsistentDownloadAttributes(download);
-
- // We used to check that the currentBytes was 0. This was incorrect. It
- // is very common to first hear about the download already at 1024 bytes.
- is(download.state, "downloading", "Download state is downloading");
-
- download.onstatechange = downloadChange;
-}
-
-var steps = [
- // Start by setting the pref to true.
- function() {
- SpecialPowers.pushPrefEnv({
- set: [["dom.mozDownloads.enabled", true]]
- }, next);
- },
-
- // Setup the event listeners.
- function() {
- SpecialPowers.pushPermissions([
- {type: "downloads", allow: true, context: document}
- ], function() {
- navigator.mozDownloadManager.ondownloadstart = downloadStart;
- next();
- });
- },
-
- // Click on the <a download> to start the download.
- function() {
- document.getElementById("download1").click();
- }
-];
-
-next();
-
-</script>
-</pre>
-</body>
-</html>
-
diff --git a/dom/downloads/tests/test_downloads_large.html b/dom/downloads/tests/test_downloads_large.html
deleted file mode 100644
index 9f7f73c19..000000000
--- a/dom/downloads/tests/test_downloads_large.html
+++ /dev/null
@@ -1,110 +0,0 @@
-<!DOCTYPE html>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=938023
--->
-<head>
- <title>Test for Bug 938023 Downloads API</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="clear_all_done_helper.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=938023">Mozilla Bug 938023</a>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<a href="serve_file.sjs?contentType=application/octet-stream&size=102400" download="test.bin" id="download1">Large Download</a>
-<pre id="test">
-<script class="testbody" type="text/javascript;version=1.7">
-
-// Testing downloading a file, then checking getDownloads() and clearAllDone().
-
-SimpleTest.waitForExplicitFinish();
-
-var index = -1;
-
-function next(args) {
- index += 1;
- if (index >= steps.length) {
- ok(false, "Shouldn't get here!");
- return;
- }
- try {
- steps[index](args);
- } catch(ex) {
- ok(false, "Caught exception", ex);
- }
-}
-
-// Catch all error function.
-function error() {
- ok(false, "API failure");
- SimpleTest.finish();
-}
-
-function getDownloads(downloads) {
- ok(downloads.length == 1, "One downloads after getDownloads");
- clearAllDoneHelper(true).then(clearAllDone, error);
-}
-
-function clearAllDone(downloads) {
- ok(downloads.length == 0, "No downloads after clearAllDone");
- SimpleTest.finish();
-}
-
-function downloadChange(evt) {
- var download = evt.download;
-
- if (download.state == "succeeded") {
- ok(download.totalBytes == 102400, "Download size is 100k bytes.");
- navigator.mozDownloadManager.getDownloads().then(getDownloads, error);
- }
-}
-
-var steps = [
- // Start by setting the pref to true.
- function() {
- SpecialPowers.pushPrefEnv({
- set: [["dom.mozDownloads.enabled", true]]
- }, next);
- },
-
- // Setup permission and clear current list.
- function() {
- SpecialPowers.pushPermissions([
- {type: "downloads", allow: true, context: document}
- ], function() {
- clearAllDoneHelper(true).then(next, error);
- });
- },
-
- function(downloads) {
- ok(downloads.length == 0, "Start with an empty download list.");
- next();
- },
-
- // Setup the event listeners.
- function() {
- navigator.mozDownloadManager.ondownloadstart =
- function(evt) {
- ok(true, "Download started");
- evt.download.addEventListener("statechange", downloadChange);
- }
- next();
- },
-
- // Click on the <a download> to start the download.
- function() {
- document.getElementById("download1").click();
- }
-];
-
-next();
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/dom/downloads/tests/test_downloads_navigator_object.html b/dom/downloads/tests/test_downloads_navigator_object.html
deleted file mode 100644
index 1c38388b7..000000000
--- a/dom/downloads/tests/test_downloads_navigator_object.html
+++ /dev/null
@@ -1,75 +0,0 @@
-<!DOCTYPE html>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=938023
--->
-<head>
- <title>Test for Bug 938023 Downloads API</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=938023">Mozilla Bug 938023</a>
-<p id="display"></p>
-<div id="content" style="display: none">
-<iframe></iframe>
-</div>
-<pre id="test">
-<script class="testbody" type="text/javascript;version=1.7">
-
-SimpleTest.waitForExplicitFinish();
-
-var index = -1;
-
-function next() {
- index += 1;
- if (index >= steps.length) {
- ok(false, "Shouldn't get here!");
- return;
- }
- try {
- steps[index]();
- } catch(ex) {
- ok(false, "Caught exception", ex);
- }
-}
-
-var steps = [
- // Start by setting the pref to true.
- function() {
- SpecialPowers.pushPrefEnv({
- set: [["dom.mozDownloads.enabled", true]]
- }, next);
- },
-
- function() {
- SpecialPowers.pushPermissions([
- {type: "downloads", allow: 0, context: document}
- ], function() {
- is(frames[0].navigator.mozDownloadManager, null, "navigator.mozDownloadManager is null when the page doesn't have permissions");
- next();
- });
- },
-
- function() {
- SpecialPowers.pushPrefEnv({
- set: [["dom.mozDownloads.enabled", false]]
- }, function() {
- is(navigator.mozDownloadManager, undefined, "navigator.mozDownloadManager is undefined");
- next();
- });
- },
-
- function() {
- SimpleTest.finish();
- }
-];
-
-next();
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/dom/downloads/tests/test_downloads_pause_remove.html b/dom/downloads/tests/test_downloads_pause_remove.html
deleted file mode 100644
index 3b410a667..000000000
--- a/dom/downloads/tests/test_downloads_pause_remove.html
+++ /dev/null
@@ -1,117 +0,0 @@
-<!DOCTYPE html>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=938023
--->
-<head>
- <title>Test for Bug 938023 Downloads API</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="clear_all_done_helper.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=938023">Mozilla Bug 938023</a>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<a href="serve_file.sjs?contentType=application/octet-stream&size=102400&rate=1024" download="test.bin" id="download1">Large Download</a>
-<pre id="test">
-<script class="testbody" type="text/javascript;version=1.7">
-
-// Testing pausing a download and then removing it.
-
-SimpleTest.waitForExplicitFinish();
-
-var index = -1;
-
-function next(args) {
- index += 1;
- if (index >= steps.length) {
- ok(false, "Shouldn't get here!");
- return;
- }
- try {
- steps[index](args);
- } catch(ex) {
- ok(false, "Caught exception", ex);
- }
-}
-
-var pausing = false;
-
-// Catch all error function.
-function error() {
- ok(false, "API failure");
- SimpleTest.finish();
-}
-
-function checkDownloadList(downloads) {
- ok(downloads.length == 0, "No downloads left");
- SimpleTest.finish();
-}
-
-function checkRemoved(download) {
- ok(download.state == "finalized", "Download removed.");
- navigator.mozDownloadManager.getDownloads()
- .then(checkDownloadList, error);
-}
-
-function downloadChange(evt) {
- var download = evt.download;
-
- if (download.state == "downloading" && !pausing) {
- pausing = true;
- download.pause();
- } else if (download.state == "stopped") {
- ok(pausing, "Download stopped by pause()");
- navigator.mozDownloadManager.remove(download)
- .then(checkRemoved, error);
- }
-}
-
-var steps = [
- // Start by setting the pref to true.
- function() {
- SpecialPowers.pushPrefEnv({
- set: [["dom.mozDownloads.enabled", true]]
- }, next);
- },
-
- // Setup permission and clear current list.
- function() {
- SpecialPowers.pushPermissions([
- {type: "downloads", allow: true, context: document}
- ], function() {
- clearAllDoneHelper(true).then(next, error);
- });
- },
-
- function(downloads) {
- ok(downloads.length == 0, "Start with an empty download list.");
- next();
- },
-
- // Setup the event listeners.
- function() {
- navigator.mozDownloadManager.ondownloadstart =
- function(evt) {
- ok(true, "Download started");
- evt.download.addEventListener("statechange", downloadChange);
- }
- next();
- },
-
- // Click on the <a download> to start the download.
- function() {
- document.getElementById("download1").click();
- }
-];
-
-next();
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/dom/downloads/tests/test_downloads_pause_resume.html b/dom/downloads/tests/test_downloads_pause_resume.html
deleted file mode 100644
index 76e249e5a..000000000
--- a/dom/downloads/tests/test_downloads_pause_resume.html
+++ /dev/null
@@ -1,121 +0,0 @@
-<!DOCTYPE html>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=938023
--->
-<head>
- <title>Test for Bug 938023 Downloads API</title>
- <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
- <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
- <script type="text/javascript" src="clear_all_done_helper.js"></script>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
-</head>
-<body>
-
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=938023">Mozilla Bug 938023</a>
-<p id="display"></p>
-<div id="content" style="display: none">
-</div>
-<a href="serve_file.sjs?contentType=application/octet-stream&size=102400&rate=1024" download="test.bin" id="download1">Large Download</a>
-<pre id="test">
-<script class="testbody" type="text/javascript;version=1.7">
-
-// Testing pausing a download and then resuming it.
-
-SimpleTest.waitForExplicitFinish();
-
-var index = -1;
-
-function next(args) {
- index += 1;
- if (index >= steps.length) {
- ok(false, "Shouldn't get here!");
- return;
- }
- try {
- steps[index](args);
- } catch(ex) {
- ok(false, "Caught exception", ex);
- }
-}
-
-var pausing = false;
-var resuming = false;
-
-// Catch all error function.
-function error() {
- ok(false, "API failure");
- SimpleTest.finish();
-}
-
-function checkDownloadList(downloads) {
- ok(downloads.length == 0, "No downloads left");
- SimpleTest.finish();
-}
-
-function checkResumeSucceeded(download) {
- ok(download.state == "succeeded", "Download resumed successfully.");
- clearAllDoneHelper(true).then(checkDownloadList, error);
-}
-
-function downloadChange(evt) {
- var download = evt.download;
-
- info("got download event, state: " + download.state +
- " current bytes: " + download.currentBytes +
- " pausing?: " + pausing + " resuming?: " + resuming);
- if (download.state == "downloading" && !pausing) {
- pausing = true;
- download.pause();
- } else if (download.state == "stopped" && !resuming) {
- resuming = true;
- ok(pausing, "Download stopped by pause()");
- download.resume()
- .then(function() { checkResumeSucceeded(download); }, error);
- }
-}
-
-var steps = [
- // Start by setting the pref to true.
- function() {
- SpecialPowers.pushPrefEnv({
- set: [["dom.mozDownloads.enabled", true]]
- }, next);
- },
-
- // Setup permission and clear current list.
- function() {
- SpecialPowers.pushPermissions([
- {type: "downloads", allow: true, context: document}
- ], function() {
- clearAllDoneHelper(true).then(next, error);
- });
- },
-
- function(downloads) {
- ok(downloads.length == 0, "Start with an empty download list.");
- next();
- },
-
- // Setup the event listeners.
- function() {
- navigator.mozDownloadManager.ondownloadstart =
- function(evt) {
- ok(true, "Download started");
- evt.download.addEventListener("statechange", downloadChange);
- }
- next();
- },
-
- // Click on the <a download> to start the download.
- function() {
- document.getElementById("download1").click();
- }
-];
-
-next();
-
-</script>
-</pre>
-</body>
-</html>
diff --git a/dom/encoding/FallbackEncoding.cpp b/dom/encoding/FallbackEncoding.cpp
index 93fe0f8cb..29411412e 100644
--- a/dom/encoding/FallbackEncoding.cpp
+++ b/dom/encoding/FallbackEncoding.cpp
@@ -55,8 +55,7 @@ FallbackEncoding::Get(nsACString& aFallback)
// Don't let the user break things by setting the override to unreasonable
// values via about:config
if (!EncodingUtils::FindEncodingForLabel(override, mFallback) ||
- !EncodingUtils::IsAsciiCompatible(mFallback) ||
- mFallback.EqualsLiteral("UTF-8")) {
+ !EncodingUtils::IsAsciiCompatible(mFallback)) {
mFallback.Truncate();
}
diff --git a/dom/events/Event.cpp b/dom/events/Event.cpp
index 7e19cd74d..4b9776c0a 100755
--- a/dom/events/Event.cpp
+++ b/dom/events/Event.cpp
@@ -1146,16 +1146,11 @@ Event::TimeStampImpl() const
return perf->GetDOMTiming()->TimeStampToDOMHighRes(mEvent->mTimeStamp);
}
- // For dedicated workers, we should make times relative to the navigation
- // start of the document that created the worker, which is the same as the
- // timebase for performance.now().
workers::WorkerPrivate* workerPrivate =
workers::GetCurrentThreadWorkerPrivate();
MOZ_ASSERT(workerPrivate);
- TimeDuration duration =
- mEvent->mTimeStamp - workerPrivate->NowBaseTimeStamp();
- return duration.ToMilliseconds();
+ return workerPrivate->TimeStampToDOMHighRes(mEvent->mTimeStamp);
}
bool
diff --git a/dom/events/EventListenerManager.cpp b/dom/events/EventListenerManager.cpp
index a8c48ede8..fe896870c 100644
--- a/dom/events/EventListenerManager.cpp
+++ b/dom/events/EventListenerManager.cpp
@@ -13,9 +13,6 @@
#include "mozilla/DOMEventTargetHelper.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventListenerManager.h"
-#ifdef MOZ_B2G
-#include "mozilla/Hal.h"
-#endif // #ifdef MOZ_B2G
#include "mozilla/HalSensor.h"
#include "mozilla/InternalMutationEvent.h"
#include "mozilla/JSEventHandler.h"
@@ -355,18 +352,10 @@ EventListenerManager::AddEventListenerInternal(
EnableDevice(eDeviceLight);
} else if (aTypeAtom == nsGkAtoms::ondevicemotion) {
EnableDevice(eDeviceMotion);
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
} else if (aTypeAtom == nsGkAtoms::onorientationchange) {
EnableDevice(eOrientationChange);
#endif
-#ifdef MOZ_B2G
- } else if (aTypeAtom == nsGkAtoms::onmoztimechange) {
- EnableDevice(eTimeChange);
- } else if (aTypeAtom == nsGkAtoms::onmoznetworkupload) {
- EnableDevice(eNetworkUpload);
- } else if (aTypeAtom == nsGkAtoms::onmoznetworkdownload) {
- EnableDevice(eNetworkDownload);
-#endif // MOZ_B2G
} else if (aTypeAtom == nsGkAtoms::ontouchstart ||
aTypeAtom == nsGkAtoms::ontouchend ||
aTypeAtom == nsGkAtoms::ontouchmove ||
@@ -492,14 +481,9 @@ EventListenerManager::IsDeviceType(EventMessage aEventMessage)
case eDeviceLight:
case eDeviceProximity:
case eUserProximity:
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
case eOrientationChange:
#endif
-#ifdef MOZ_B2G
- case eTimeChange:
- case eNetworkUpload:
- case eNetworkDownload:
-#endif
return true;
default:
break;
@@ -545,20 +529,11 @@ EventListenerManager::EnableDevice(EventMessage aEventMessage)
window->EnableDeviceSensor(SENSOR_LINEAR_ACCELERATION);
window->EnableDeviceSensor(SENSOR_GYROSCOPE);
break;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
case eOrientationChange:
window->EnableOrientationChangeListener();
break;
#endif
-#ifdef MOZ_B2G
- case eTimeChange:
- window->EnableTimeChangeNotifications();
- break;
- case eNetworkUpload:
- case eNetworkDownload:
- window->EnableNetworkEvent(aEventMessage);
- break;
-#endif
default:
NS_WARNING("Enabling an unknown device sensor.");
break;
@@ -600,20 +575,11 @@ EventListenerManager::DisableDevice(EventMessage aEventMessage)
case eDeviceLight:
window->DisableDeviceSensor(SENSOR_LIGHT);
break;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
case eOrientationChange:
window->DisableOrientationChangeListener();
break;
#endif
-#ifdef MOZ_B2G
- case eTimeChange:
- window->DisableTimeChangeNotifications();
- break;
- case eNetworkUpload:
- case eNetworkDownload:
- window->DisableNetworkEvent(aEventMessage);
- break;
-#endif // MOZ_B2G
default:
NS_WARNING("Disabling an unknown device sensor.");
break;
diff --git a/dom/events/EventNameList.h b/dom/events/EventNameList.h
index ba2427623..214b844e7 100644
--- a/dom/events/EventNameList.h
+++ b/dom/events/EventNameList.h
@@ -164,6 +164,10 @@ EVENT(change,
eFormChange,
EventNameType_HTMLXUL,
eBasicEventClass)
+EVENT(auxclick,
+ eMouseAuxClick,
+ EventNameType_All,
+ eMouseEventClass)
EVENT(click,
eMouseClick,
EventNameType_All,
@@ -559,7 +563,7 @@ WINDOW_EVENT(online,
eOnline,
EventNameType_XUL | EventNameType_HTMLBodyOrFramesetOnly,
eBasicEventClass)
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
WINDOW_EVENT(orientationchange,
eOrientationChange,
EventNameType_HTMLBodyOrFramesetOnly,
@@ -633,22 +637,6 @@ WINDOW_ONLY_EVENT(appinstalled,
EventNameType_None,
eBasicEventClass)
-
-#ifdef MOZ_B2G
-WINDOW_ONLY_EVENT(moztimechange,
- eTimeChange,
- EventNameType_None,
- eBasicEventClass)
-WINDOW_ONLY_EVENT(moznetworkupload,
- eNetworkUpload,
- EventNameType_None,
- eBasicEventClass)
-WINDOW_ONLY_EVENT(moznetworkdownload,
- eNetworkDownload,
- EventNameType_None,
- eBasicEventClass)
-#endif // MOZ_B2G
-
TOUCH_EVENT(touchstart,
eTouchStart,
EventNameType_All,
@@ -1003,6 +991,10 @@ EVENT(transitionend,
eTransitionEnd,
EventNameType_All,
eTransitionEventClass)
+EVENT(transitioncancel,
+ eTransitionCancel,
+ EventNameType_All,
+ eTransitionEventClass)
EVENT(animationstart,
eAnimationStart,
EventNameType_All,
@@ -1015,6 +1007,10 @@ EVENT(animationiteration,
eAnimationIteration,
EventNameType_All,
eAnimationEventClass)
+EVENT(animationcancel,
+ eAnimationCancel,
+ EventNameType_All,
+ eAnimationEventClass)
// Webkit-prefixed versions of Transition & Animation events, for web compat:
EVENT(webkitAnimationEnd,
diff --git a/dom/events/EventStateManager.cpp b/dom/events/EventStateManager.cpp
index c6b304183..7bbfe21b7 100644
--- a/dom/events/EventStateManager.cpp
+++ b/dom/events/EventStateManager.cpp
@@ -492,6 +492,7 @@ IsMessageMouseUserActivity(EventMessage aMessage)
return aMessage == eMouseMove ||
aMessage == eMouseUp ||
aMessage == eMouseDown ||
+ aMessage == eMouseAuxClick ||
aMessage == eMouseDoubleClick ||
aMessage == eMouseClick ||
aMessage == eMouseActivate ||
@@ -4633,6 +4634,32 @@ EventStateManager::SetClickCount(WidgetMouseEvent* aEvent,
}
nsresult
+EventStateManager::InitAndDispatchClickEvent(WidgetMouseEvent* aEvent,
+ nsEventStatus* aStatus,
+ EventMessage aMessage,
+ nsIPresShell* aPresShell,
+ nsIContent* aMouseTarget,
+ nsWeakFrame aCurrentTarget,
+ bool aNoContentDispatch)
+{
+ WidgetMouseEvent event(aEvent->IsTrusted(), aMessage,
+ aEvent->mWidget, WidgetMouseEvent::eReal);
+
+ event.mRefPoint = aEvent->mRefPoint;
+ event.mClickCount = aEvent->mClickCount;
+ event.mModifiers = aEvent->mModifiers;
+ event.buttons = aEvent->buttons;
+ event.mTime = aEvent->mTime;
+ event.mTimeStamp = aEvent->mTimeStamp;
+ event.mFlags.mNoContentDispatch = aNoContentDispatch;
+ event.button = aEvent->button;
+ event.inputSource = aEvent->inputSource;
+
+ return aPresShell->HandleEventWithTarget(&event, aCurrentTarget,
+ aMouseTarget, aStatus);
+}
+
+nsresult
EventStateManager::CheckForAndDispatchClick(WidgetMouseEvent* aEvent,
nsEventStatus* aStatus)
{
@@ -4651,17 +4678,7 @@ EventStateManager::CheckForAndDispatchClick(WidgetMouseEvent* aEvent,
(aEvent->button == WidgetMouseEvent::eMiddleButton ||
aEvent->button == WidgetMouseEvent::eRightButton);
- WidgetMouseEvent event(aEvent->IsTrusted(), eMouseClick,
- aEvent->mWidget, WidgetMouseEvent::eReal);
- event.mRefPoint = aEvent->mRefPoint;
- event.mClickCount = aEvent->mClickCount;
- event.mModifiers = aEvent->mModifiers;
- event.buttons = aEvent->buttons;
- event.mTime = aEvent->mTime;
- event.mTimeStamp = aEvent->mTimeStamp;
- event.mFlags.mNoContentDispatch = notDispatchToContents;
- event.button = aEvent->button;
- event.inputSource = aEvent->inputSource;
+ bool fireAuxClick = notDispatchToContents;
nsCOMPtr<nsIPresShell> presShell = mPresContext->GetPresShell();
if (presShell) {
@@ -4680,23 +4697,22 @@ EventStateManager::CheckForAndDispatchClick(WidgetMouseEvent* aEvent,
// HandleEvent clears out mCurrentTarget which we might need again
nsWeakFrame currentTarget = mCurrentTarget;
- ret = presShell->HandleEventWithTarget(&event, currentTarget,
- mouseContent, aStatus);
+ ret = InitAndDispatchClickEvent(aEvent, aStatus, eMouseClick,
+ presShell, mouseContent, currentTarget,
+ notDispatchToContents);
+
if (NS_SUCCEEDED(ret) && aEvent->mClickCount == 2 &&
mouseContent && mouseContent->IsInComposedDoc()) {
//fire double click
- WidgetMouseEvent event2(aEvent->IsTrusted(), eMouseDoubleClick,
- aEvent->mWidget, WidgetMouseEvent::eReal);
- event2.mRefPoint = aEvent->mRefPoint;
- event2.mClickCount = aEvent->mClickCount;
- event2.mModifiers = aEvent->mModifiers;
- event2.buttons = aEvent->buttons;
- event2.mFlags.mNoContentDispatch = notDispatchToContents;
- event2.button = aEvent->button;
- event2.inputSource = aEvent->inputSource;
-
- ret = presShell->HandleEventWithTarget(&event2, currentTarget,
- mouseContent, aStatus);
+ ret = InitAndDispatchClickEvent(aEvent, aStatus, eMouseDoubleClick,
+ presShell, mouseContent, currentTarget,
+ notDispatchToContents);
+ }
+ if (NS_SUCCEEDED(ret) && mouseContent && fireAuxClick &&
+ mouseContent->IsInComposedDoc()) {
+ ret = InitAndDispatchClickEvent(aEvent, aStatus, eMouseAuxClick,
+ presShell, mouseContent, currentTarget,
+ false);
}
}
}
diff --git a/dom/events/EventStateManager.h b/dom/events/EventStateManager.h
index 49ecf0586..d0461e7fa 100644
--- a/dom/events/EventStateManager.h
+++ b/dom/events/EventStateManager.h
@@ -415,6 +415,13 @@ protected:
*/
void UpdateDragDataTransfer(WidgetDragEvent* dragEvent);
+ static nsresult InitAndDispatchClickEvent(WidgetMouseEvent* aEvent,
+ nsEventStatus* aStatus,
+ EventMessage aMessage,
+ nsIPresShell* aPresShell,
+ nsIContent* aMouseTarget,
+ nsWeakFrame aCurrentTarget,
+ bool aNoContentDispatch);
nsresult SetClickCount(WidgetMouseEvent* aEvent, nsEventStatus* aStatus);
nsresult CheckForAndDispatchClick(WidgetMouseEvent* aEvent,
nsEventStatus* aStatus);
@@ -1046,6 +1053,7 @@ private:
#define NS_EVENT_NEEDS_FRAME(event) \
(!(event)->HasPluginActivationEventMessage() && \
(event)->mMessage != eMouseClick && \
- (event)->mMessage != eMouseDoubleClick)
+ (event)->mMessage != eMouseDoubleClick && \
+ (event)->mMessage != eMouseAuxClick)
#endif // mozilla_EventStateManager_h_
diff --git a/dom/events/KeyNameList.h b/dom/events/KeyNameList.h
index 35fbe2d5f..361122ec7 100644
--- a/dom/events/KeyNameList.h
+++ b/dom/events/KeyNameList.h
@@ -32,10 +32,6 @@ DEFINE_KEYNAME_INTERNAL(PrintableKey, "MozPrintableKey")
DEFINE_KEYNAME_INTERNAL(SoftLeft, "MozSoftLeft")
DEFINE_KEYNAME_INTERNAL(SoftRight, "MozSoftRight")
-#ifdef MOZ_B2G
-DEFINE_KEYNAME_INTERNAL(HomeScreen, "MozHomeScreen")
-#endif // #ifdef MOZ_B2G
-
/******************************************************************************
* Modifier Keys
*****************************************************************************/
diff --git a/dom/events/TouchEvent.cpp b/dom/events/TouchEvent.cpp
index cc9684eb3..9b7a74ac2 100644
--- a/dom/events/TouchEvent.cpp
+++ b/dom/events/TouchEvent.cpp
@@ -203,7 +203,7 @@ TouchEvent::PrefEnabled(nsIDocShell* aDocShell)
enabled = false;
} else {
if (sPrefCacheValue == 2) {
-#if defined(MOZ_B2G) || defined(MOZ_WIDGET_ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
// Touch support is always enabled on B2G and android.
enabled = true;
#elif defined(XP_WIN) || MOZ_WIDGET_GTK == 3
diff --git a/dom/events/WheelHandlingHelper.cpp b/dom/events/WheelHandlingHelper.cpp
index 7665ee922..81f2b6bfa 100644
--- a/dom/events/WheelHandlingHelper.cpp
+++ b/dom/events/WheelHandlingHelper.cpp
@@ -257,6 +257,7 @@ WheelTransaction::OnEvent(WidgetEvent* aEvent)
case eMouseUp:
case eMouseDown:
case eMouseDoubleClick:
+ case eMouseAuxClick:
case eMouseClick:
case eContextMenu:
case eDrop:
diff --git a/dom/events/moz.build b/dom/events/moz.build
index ee4946038..ec3813207 100644
--- a/dom/events/moz.build
+++ b/dom/events/moz.build
@@ -153,10 +153,5 @@ LOCAL_INCLUDES += [
'/layout/xul/tree/',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- LOCAL_INCLUDES += [
- '/dom/wifi',
- ]
-
if CONFIG['GNU_CXX']:
CXXFLAGS += ['-Wno-error=shadow']
diff --git a/dom/events/test/mochitest.ini b/dom/events/test/mochitest.ini
index e100e60a1..0397487bb 100644
--- a/dom/events/test/mochitest.ini
+++ b/dom/events/test/mochitest.ini
@@ -184,3 +184,4 @@ skip-if = toolkit == 'android' #CRASH_DUMP, RANDOM
[test_wheel_default_action.html]
[test_bug687787.html]
[test_bug1298970.html]
+[test_bug1304044.html]
diff --git a/dom/events/test/test_bug1304044.html b/dom/events/test/test_bug1304044.html
new file mode 100644
index 000000000..0911dcf73
--- /dev/null
+++ b/dom/events/test/test_bug1304044.html
@@ -0,0 +1,133 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=1304044
+-->
+<head>
+ <meta charset="utf-8">
+ <title>Test for Bug 1304044</title>
+ <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+ <script type="application/javascript">
+ var eventsFired = [];
+ var target;
+ var eventsExpected;
+
+ function GetNodeString(node) {
+ if (node == window)
+ return "window";
+ if (node == document)
+ return "document";
+ if (node.id)
+ return node.id;
+ if (node.nodeName)
+ return node.nodeName;
+ return node;
+ }
+
+ function TargetAndListener(listener, target) {
+ this.listener = listener;
+ this.target = target;
+ }
+
+ TargetAndListener.prototype.toString = function() {
+ var targetName = GetNodeString(this.target);
+ var listenerName = GetNodeString(this.listener);
+ return "(listener: " + listenerName + ", target: " + targetName + ")";
+ }
+
+ var tests = [
+ TestAuxClickBubblesForEventListener,
+ TestAuxClickBubblesForOnAuxClick,
+ ];
+
+ function CompareEvents(evt, expected) {
+ return evt && expected && evt.listener == expected.listener &&
+ evt.target == expected.target;
+ }
+
+ function ResetEventsFired() {
+ eventsFired = [];
+ }
+
+ function ClearEventListeners() {
+ for (i in arguments) {
+ arguments[i].removeEventListener("auxclick", log_event);
+ }
+ }
+
+ function ClickTarget(tgt) {
+ synthesizeMouseAtCenter(tgt, {type : "mousedown", button: 2}, window);
+ synthesizeMouseAtCenter(tgt, {type : "mouseup", button: 2}, window);
+ }
+
+ function log_event(e) {
+ eventsFired[eventsFired.length] = new TargetAndListener(this, e.target);
+ }
+
+ function CompareEventsToExpected(expected, actual) {
+ for (var i = 0; i < expected.length || i < actual.length; i++) {
+ ok(CompareEvents(actual[i], expected[i]),
+ "Auxclick receiver's don't match: TargetAndListener " +
+ i + ": Expected: " + expected[i] + ", Actual: " + actual[i]);
+ }
+ }
+
+ function TestAuxClickBubblesForEventListener() {
+ target.addEventListener("auxclick", log_event);
+ document.addEventListener("auxclick", log_event);
+ window.addEventListener("auxclick", log_event);
+
+ ClickTarget(target)
+ CompareEventsToExpected(eventsExpected, eventsFired);
+ ResetEventsFired();
+ ClearEventListeners(target, document, window);
+ }
+
+ function TestAuxClickBubblesForOnAuxClick() {
+ target.onauxclick = log_event;
+ document.onauxclick = log_event;
+ window.onauxclick = log_event;
+
+ ClickTarget(target);
+ CompareEventsToExpected(eventsExpected, eventsFired);
+ ResetEventsFired();
+ }
+
+ function RunTests(){
+ for (var i = 0; i < tests.length; i++) {
+ tests[i]();
+ }
+ }
+
+ function Begin() {
+ target = document.getElementById("target");
+ eventsExpected = [
+ new TargetAndListener(target, target),
+ new TargetAndListener(document, target),
+ new TargetAndListener(window, target),
+ ];
+ RunTests();
+ target.remove();
+ SimpleTest.finish();
+ }
+
+ window.onload = function() {
+ SimpleTest.waitForExplicitFinish();
+ SimpleTest.executeSoon(Begin);
+ }
+ </script>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1304044">Mozilla Bug 1304044</a>
+<p id="display">
+ <div id="target">Target</div>
+</p>
+<div id="content" style:"display:none">
+
+</div>
+<pre id="test">
+</pre>
+</body>
+</html>
diff --git a/dom/events/test/test_eventTimeStamp.html b/dom/events/test/test_eventTimeStamp.html
index 107a21f87..056203e92 100644
--- a/dom/events/test/test_eventTimeStamp.html
+++ b/dom/events/test/test_eventTimeStamp.html
@@ -17,7 +17,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=77992
<script type="text/js-worker" id="worker-src">
// Simply returns the event timestamp
onmessage = function(evt) {
- postMessage(evt.timeStamp);
+ postMessage(evt.timeStamp + performance.timeOrigin);
}
</script>
<script type="text/js-worker" id="shared-worker-src">
@@ -25,7 +25,7 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=77992
onconnect = function(evt) {
var port = evt.ports[0];
port.onmessage = function(messageEvt) {
- port.postMessage(messageEvt.timeStamp);
+ port.postMessage(messageEvt.timeStamp + performance.timeOrigin);
};
};
</script>
@@ -57,9 +57,9 @@ function testRegularEvents() {
finishTests();
return;
}
- var timeBeforeEvent = window.performance.now();
- window.addEventListener("load", function(evt) {
- var timeAfterEvent = window.performance.now();
+ var timeBeforeEvent = performance.now();
+ addEventListener("load", function(evt) {
+ var timeAfterEvent = performance.now();
ok(evt.timeStamp >= timeBeforeEvent &&
evt.timeStamp <= timeAfterEvent,
"Event timestamp (" + evt.timeStamp + ") is in expected range: (" +
@@ -71,19 +71,18 @@ function testRegularEvents() {
function testWorkerEvents() {
var blob = new Blob([ document.getElementById("worker-src").textContent ],
{ type: "text/javascript" });
- var worker = new Worker(window.URL.createObjectURL(blob));
+ var worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = function(evt) {
- var timeAfterEvent = window.performance.now();
- // Comparing times across timelines may break now
- // ok(evt.data >= timeBeforeEvent &&
- // evt.data <= timeAfterEvent,
+ var timeAfterEvent = performance.now() + performance.timeOrigin;
+ ok(evt.data >= timeBeforeEvent &&
+ evt.data <= timeAfterEvent,
// "Event timestamp in dedicated worker (" + evt.data +
// ") is in expected range: (" +
// timeBeforeEvent + ", " + timeAfterEvent + ")");
worker.terminate();
testSharedWorkerEvents();
};
- var timeBeforeEvent = window.performance.now();
+ var timeBeforeEvent = performance.now() + performance.timeOrigin;
worker.postMessage("");
}
@@ -93,17 +92,16 @@ function testSharedWorkerEvents() {
{ type: "text/javascript" });
// Delay creation of worker slightly so it is easier to distinguish
// shared worker creation time from this document's navigation start
- window.setTimeout(function() {
- var timeBeforeWorkerCreation = window.performance.now();
- var worker = new SharedWorker(window.URL.createObjectURL(blob));
+ setTimeout(function() {
+ var timeBeforeEvent = performance.now() + performance.timeOrigin;
+ var worker = new SharedWorker(URL.createObjectURL(blob));
worker.port.onmessage = function(evt) {
- var timeAfterEvent = window.performance.now();
- // Comparing times across timelines may break now
- // ok(evt.data >= 0 &&
- // evt.data <= timeAfterEvent - timeBeforeWorkerCreation,
+ var timeAfterEvent = performance.now() + performance.timeOrigin;
+ ok(evt.data >= timeBeforeEvent &&
+ evt.data <= timeAfterEvent,
// "Event timestamp in shared worker (" + evt.data +
// ") is in expected range: (0, " +
- // (timeAfterEvent - timeBeforeWorkerCreation) + ")");
+ // timeBeforeEvent + ", " + timeAfterEvent + ")");
worker.port.close();
finishTests();
};
diff --git a/dom/events/test/test_legacy_event.html b/dom/events/test/test_legacy_event.html
index d772be106..b2105a6df 100644
--- a/dom/events/test/test_legacy_event.html
+++ b/dom/events/test/test_legacy_event.html
@@ -73,22 +73,15 @@ function triggerShortAnimation(node) {
node.style.animation = "anim1 1ms linear";
}
-// This function triggers a long animation with two iterations, which is
-// *nearly* at the end of its first iteration. It will hit the end of that
-// iteration (firing an event) almost immediately, 1ms in the future.
+// This function triggers a very short (10ms long) animation with many
+// iterations, which will cause a start event followed by an iteration event
+// on each subsequent tick, to fire.
//
-// NOTE: It's important that this animation have a *long* duration. If it were
-// short (e.g. 1ms duration), then we might jump past all its iterations in
-// a single refresh-driver tick. And if that were to happens, we'd *never* fire
-// any animationiteration events -- the CSS Animations spec says this event
-// must not be fired "...when an animationend event would fire at the same time"
-// (which would be the case in this example with a 1ms duration). So, to make
-// sure our event does fire, we use a long duration and a nearly-as-long
-// negative delay. This ensures we hit the end of the first iteration right
-// away, and that we don't risk hitting the end of the second iteration at the
-// same time.
+// NOTE: We need the many iterations since if an animation frame coincides
+// with the animation starting or ending we dispatch only the start or end
+// event and not the iteration event.
function triggerAnimationIteration(node) {
- node.style.animation = "anim1 300s -299.999s linear 2";
+ node.style.animation = "anim1 10ms linear 20000";
}
// GENERAL UTILITY FUNCTIONS
diff --git a/dom/geolocation/moz.build b/dom/geolocation/moz.build
index bb3fcb583..4339d5a7f 100644
--- a/dom/geolocation/moz.build
+++ b/dom/geolocation/moz.build
@@ -30,10 +30,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
LOCAL_INCLUDES += [
'/dom/system/android',
]
-elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- LOCAL_INCLUDES += [
- '/dom/system/gonk',
- ]
elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
LOCAL_INCLUDES += [
'/dom/system/mac',
diff --git a/dom/geolocation/nsGeolocation.cpp b/dom/geolocation/nsGeolocation.cpp
index 9fcdb350a..2d84a3e11 100644
--- a/dom/geolocation/nsGeolocation.cpp
+++ b/dom/geolocation/nsGeolocation.cpp
@@ -33,10 +33,6 @@ class nsIPrincipal;
#include "AndroidLocationProvider.h"
#endif
-#ifdef MOZ_WIDGET_GONK
-#include "GonkGPSGeolocationProvider.h"
-#endif
-
#ifdef MOZ_GPSD
#include "GpsdLocationProvider.h"
#endif
@@ -688,15 +684,6 @@ nsresult nsGeolocationService::Init()
mProvider = new AndroidLocationProvider();
#endif
-#ifdef MOZ_WIDGET_GONK
- // GonkGPSGeolocationProvider can be started at boot up time for initialization reasons.
- // do_getService gets hold of the already initialized component and starts
- // processing location requests immediately.
- // do_Createinstance will create multiple instances of the provider which is not right.
- // bug 993041
- mProvider = do_GetService(GONK_GPS_GEOLOCATION_PROVIDER_CONTRACTID);
-#endif
-
#ifdef MOZ_WIDGET_GTK
#ifdef MOZ_GPSD
if (Preferences::GetBool("geo.provider.use_gpsd", false)) {
diff --git a/dom/html/HTMLInputElement.cpp b/dom/html/HTMLInputElement.cpp
index 52062c4b9..d09bc3103 100644
--- a/dom/html/HTMLInputElement.cpp
+++ b/dom/html/HTMLInputElement.cpp
@@ -959,13 +959,6 @@ UploadLastDir::FetchDirectoryAndDisplayPicker(nsIDocument* aDoc,
nsCOMPtr<nsIContentPrefCallback2> prefCallback =
new UploadLastDir::ContentPrefCallback(aFilePicker, aFpCallback);
-#ifdef MOZ_B2G
- if (XRE_IsContentProcess()) {
- prefCallback->HandleCompletion(nsIContentPrefCallback2::COMPLETE_ERROR);
- return NS_OK;
- }
-#endif
-
// Attempt to get the CPS, if it's not present we'll fallback to use the Desktop folder
nsCOMPtr<nsIContentPrefService2> contentPrefService =
do_GetService(NS_CONTENT_PREF_SERVICE_CONTRACTID);
@@ -990,12 +983,6 @@ UploadLastDir::StoreLastUsedDirectory(nsIDocument* aDoc, nsIFile* aDir)
return NS_OK;
}
-#ifdef MOZ_B2G
- if (XRE_IsContentProcess()) {
- return NS_OK;
- }
-#endif
-
nsCOMPtr<nsIURI> docURI = aDoc->GetDocumentURI();
NS_PRECONDITION(docURI, "docURI is null");
@@ -6013,7 +6000,7 @@ HTMLInputElement::ChooseDirectory(ErrorResult& aRv)
// "Pick Folder..." button on platforms that don't have a directory picker
// we have to redirect to the file picker here.
InitFilePicker(
-#if defined(ANDROID) || defined(MOZ_B2G)
+#if defined(ANDROID)
// No native directory picker - redirect to plain file picker
FILE_PICKER_FILE
#else
diff --git a/dom/html/nsIFormControl.h b/dom/html/nsIFormControl.h
index e07f7c829..34380bc67 100644
--- a/dom/html/nsIFormControl.h
+++ b/dom/html/nsIFormControl.h
@@ -267,8 +267,8 @@ nsIFormControl::IsSingleLineTextControl(bool aExcludePassword, uint32_t aType)
aType == NS_FORM_INPUT_TEL ||
aType == NS_FORM_INPUT_URL ||
// TODO: those are temporary until bug 773205 is fixed.
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
- // On Android/B2G, date/time input appears as a normal text box.
+#if defined(MOZ_WIDGET_ANDROID)
+ // On Android, date/time input appears as a normal text box.
aType == NS_FORM_INPUT_TIME ||
aType == NS_FORM_INPUT_DATE ||
#endif
diff --git a/dom/html/test/test_fullscreen-api-race.html b/dom/html/test/test_fullscreen-api-race.html
index 03c6c6da3..6664e2ab5 100644
--- a/dom/html/test/test_fullscreen-api-race.html
+++ b/dom/html/test/test_fullscreen-api-race.html
@@ -35,7 +35,9 @@ addLoadEvent(function () {
SpecialPowers.pushPrefEnv({
"set": [
["full-screen-api.unprefix.enabled", true],
- ["full-screen-api.allow-trusted-requests-only", false]
+ ["full-screen-api.allow-trusted-requests-only", false],
+ // Use legacy data: URI behavior to run test.
+ ["security.data_uri.block_toplevel_data_uri_navigations", false]
]
}, next);
});
diff --git a/dom/indexedDB/ActorsParent.cpp b/dom/indexedDB/ActorsParent.cpp
index 9d4e72f2f..9678fb49f 100644
--- a/dom/indexedDB/ActorsParent.cpp
+++ b/dom/indexedDB/ActorsParent.cpp
@@ -121,7 +121,7 @@
LogLevel::Debug, \
_args )
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
#define IDB_MOBILE
#endif
@@ -3694,8 +3694,6 @@ UpgradeSchemaFrom18_0To19_0(mozIStorageConnection* aConnection)
return NS_OK;
}
-#if !defined(MOZ_B2G)
-
class NormalJSContext;
class UpgradeFileIdsFunction final
@@ -3731,8 +3729,6 @@ private:
nsIVariant** aResult) override;
};
-#endif // MOZ_B2G
-
nsresult
UpgradeSchemaFrom19_0To20_0(nsIFile* aFMDirectory,
mozIStorageConnection* aConnection)
@@ -3744,20 +3740,6 @@ UpgradeSchemaFrom19_0To20_0(nsIFile* aFMDirectory,
"UpgradeSchemaFrom19_0To20_0",
js::ProfileEntry::Category::STORAGE);
-#if defined(MOZ_B2G)
-
- // We don't have to do the upgrade of file ids on B2G. The old format was
- // only used by the previous single process implementation and B2G was
- // always multi process. This is a nice optimization since the upgrade needs
- // to deserialize all structured clones which reference a stored file or
- // a mutable file.
- nsresult rv = aConnection->SetSchemaVersion(MakeSchemaVersion(20, 0));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
-
-#else // MOZ_B2G
-
nsCOMPtr<mozIStorageStatement> stmt;
nsresult rv = aConnection->CreateStatement(NS_LITERAL_CSTRING(
"SELECT count(*) "
@@ -3856,8 +3838,6 @@ UpgradeSchemaFrom19_0To20_0(nsIFile* aFMDirectory,
return rv;
}
-#endif // MOZ_B2G
-
return NS_OK;
}
@@ -7767,12 +7747,10 @@ private:
virtual void
SendResults() override;
-#ifdef ENABLE_INTL_API
static nsresult
UpdateLocaleAwareIndex(mozIStorageConnection* aConnection,
const IndexMetadata& aIndexMetadata,
const nsCString& aLocale);
-#endif
};
class OpenDatabaseOp::VersionChangeOp final
@@ -19666,8 +19644,6 @@ AutoProgressHandler::OnProgress(mozIStorageConnection* aConnection,
NS_IMPL_ISUPPORTS(CompressDataBlobsFunction, mozIStorageFunction)
NS_IMPL_ISUPPORTS(EncodeKeysFunction, mozIStorageFunction)
-#if !defined(MOZ_B2G)
-
nsresult
UpgradeFileIdsFunction::Init(nsIFile* aFMDirectory,
mozIStorageConnection* aConnection)
@@ -19762,8 +19738,6 @@ UpgradeFileIdsFunction::OnFunctionCall(mozIStorageValueArray* aArguments,
return NS_OK;
}
-#endif // MOZ_B2G
-
// static
void
DatabaseOperationBase::GetBindingClauseForKeyRange(
@@ -20064,9 +20038,6 @@ DatabaseOperationBase::BindKeyRangeToStatement(
mozIStorageStatement* aStatement,
const nsCString& aLocale)
{
-#ifndef ENABLE_INTL_API
- return BindKeyRangeToStatement(aKeyRange, aStatement);
-#else
MOZ_ASSERT(!IsOnBackgroundThread());
MOZ_ASSERT(aStatement);
MOZ_ASSERT(!aLocale.IsEmpty());
@@ -20104,7 +20075,6 @@ DatabaseOperationBase::BindKeyRangeToStatement(
}
return NS_OK;
-#endif
}
// static
@@ -22197,7 +22167,6 @@ OpenDatabaseOp::LoadDatabaseInformation(mozIStorageConnection* aConnection)
indexMetadata->mCommonMetadata.multiEntry() = !!scratch;
-#ifdef ENABLE_INTL_API
const bool localeAware = !stmt->IsNull(6);
if (localeAware) {
rv = stmt->GetUTF8String(6, indexMetadata->mCommonMetadata.locale());
@@ -22227,7 +22196,6 @@ OpenDatabaseOp::LoadDatabaseInformation(mozIStorageConnection* aConnection)
}
}
}
-#endif
if (NS_WARN_IF(!objectStoreMetadata->mIndexes.Put(indexId, indexMetadata,
fallible))) {
@@ -22253,7 +22221,6 @@ OpenDatabaseOp::LoadDatabaseInformation(mozIStorageConnection* aConnection)
return NS_OK;
}
-#ifdef ENABLE_INTL_API
/* static */
nsresult
OpenDatabaseOp::UpdateLocaleAwareIndex(mozIStorageConnection* aConnection,
@@ -22371,7 +22338,6 @@ OpenDatabaseOp::UpdateLocaleAwareIndex(mozIStorageConnection* aConnection,
rv = metaStmt->Execute();
return rv;
}
-#endif
nsresult
OpenDatabaseOp::BeginVersionChange()
@@ -28191,15 +28157,12 @@ OpenOp::GetRangeKeyInfo(bool aLowerBound, Key* aKey, bool* aOpen)
if (range.isOnly()) {
*aKey = range.lower();
*aOpen = false;
-#ifdef ENABLE_INTL_API
if (mCursor->IsLocaleAware()) {
range.lower().ToLocaleBasedKey(*aKey, mCursor->mLocale);
}
-#endif
} else {
*aKey = aLowerBound ? range.lower() : range.upper();
*aOpen = aLowerBound ? range.lowerOpen() : range.upperOpen();
-#ifdef ENABLE_INTL_API
if (mCursor->IsLocaleAware()) {
if (aLowerBound) {
range.lower().ToLocaleBasedKey(*aKey, mCursor->mLocale);
@@ -28207,7 +28170,6 @@ OpenOp::GetRangeKeyInfo(bool aLowerBound, Key* aKey, bool* aOpen)
range.upper().ToLocaleBasedKey(*aKey, mCursor->mLocale);
}
}
-#endif
}
} else {
*aOpen = false;
diff --git a/dom/indexedDB/IDBCursor.cpp b/dom/indexedDB/IDBCursor.cpp
index e5d8913f9..7ae35e981 100644
--- a/dom/indexedDB/IDBCursor.cpp
+++ b/dom/indexedDB/IDBCursor.cpp
@@ -65,13 +65,11 @@ IDBCursor::IDBCursor(Type aType,
}
}
-#ifdef ENABLE_INTL_API
bool
IDBCursor::IsLocaleAware() const
{
return mSourceIndex && !mSourceIndex->Locale().IsEmpty();
}
-#endif
IDBCursor::~IDBCursor()
{
@@ -437,7 +435,6 @@ IDBCursor::Continue(JSContext* aCx,
return;
}
-#ifdef ENABLE_INTL_API
if (IsLocaleAware() && !key.IsUnset()) {
Key tmp;
aRv = key.ToLocaleBasedKey(tmp, mSourceIndex->Locale());
@@ -448,9 +445,6 @@ IDBCursor::Continue(JSContext* aCx,
}
const Key& sortKey = IsLocaleAware() ? mSortKey : mKey;
-#else
- const Key& sortKey = mKey;
-#endif
if (!key.IsUnset()) {
switch (mDirection) {
@@ -547,7 +541,6 @@ IDBCursor::ContinuePrimaryKey(JSContext* aCx,
return;
}
-#ifdef ENABLE_INTL_API
if (IsLocaleAware() && !key.IsUnset()) {
Key tmp;
aRv = key.ToLocaleBasedKey(tmp, mSourceIndex->Locale());
@@ -558,9 +551,6 @@ IDBCursor::ContinuePrimaryKey(JSContext* aCx,
}
const Key& sortKey = IsLocaleAware() ? mSortKey : mKey;
-#else
- const Key& sortKey = mKey;
-#endif
if (key.IsUnset()) {
aRv.Throw(NS_ERROR_DOM_INDEXEDDB_DATA_ERR);
diff --git a/dom/indexedDB/IDBCursor.h b/dom/indexedDB/IDBCursor.h
index 25be16bee..3a4bedcda 100644
--- a/dom/indexedDB/IDBCursor.h
+++ b/dom/indexedDB/IDBCursor.h
@@ -205,11 +205,9 @@ private:
~IDBCursor();
-#ifdef ENABLE_INTL_API
// Checks if this is a locale aware cursor (ie. the index's sortKey is unset)
bool
IsLocaleAware() const;
-#endif
void
DropJSObjects();
diff --git a/dom/indexedDB/IDBObjectStore.cpp b/dom/indexedDB/IDBObjectStore.cpp
index c9ab24970..a6d6c5f06 100644
--- a/dom/indexedDB/IDBObjectStore.cpp
+++ b/dom/indexedDB/IDBObjectStore.cpp
@@ -859,10 +859,6 @@ public:
}
};
-// We don't need to upgrade database on B2G. See the comment in ActorsParent.cpp,
-// UpgradeSchemaFrom18_0To19_0()
-#if !defined(MOZ_B2G)
-
class UpgradeDeserializationHelper
{
public:
@@ -929,8 +925,6 @@ public:
}
};
-#endif // MOZ_B2G
-
template <class Traits>
JSObject*
CommonStructuredCloneReadCallback(JSContext* aCx,
@@ -1086,9 +1080,7 @@ IDBObjectStore::AppendIndexUpdateInfo(
{
nsresult rv;
-#ifdef ENABLE_INTL_API
const bool localeAware = !aLocale.IsEmpty();
-#endif
if (!aMultiEntry) {
Key key;
@@ -1106,14 +1098,12 @@ IDBObjectStore::AppendIndexUpdateInfo(
IndexUpdateInfo* updateInfo = aUpdateInfoArray.AppendElement();
updateInfo->indexId() = aIndexID;
updateInfo->value() = key;
-#ifdef ENABLE_INTL_API
if (localeAware) {
rv = key.ToLocaleBasedKey(updateInfo->localizedValue(), aLocale);
if (NS_WARN_IF(NS_FAILED(rv))) {
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
}
-#endif
return NS_OK;
}
@@ -1153,14 +1143,12 @@ IDBObjectStore::AppendIndexUpdateInfo(
IndexUpdateInfo* updateInfo = aUpdateInfoArray.AppendElement();
updateInfo->indexId() = aIndexID;
updateInfo->value() = value;
-#ifdef ENABLE_INTL_API
if (localeAware) {
rv = value.ToLocaleBasedKey(updateInfo->localizedValue(), aLocale);
if (NS_WARN_IF(NS_FAILED(rv))) {
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
}
-#endif
}
}
else {
@@ -1174,14 +1162,12 @@ IDBObjectStore::AppendIndexUpdateInfo(
IndexUpdateInfo* updateInfo = aUpdateInfoArray.AppendElement();
updateInfo->indexId() = aIndexID;
updateInfo->value() = value;
-#ifdef ENABLE_INTL_API
if (localeAware) {
rv = value.ToLocaleBasedKey(updateInfo->localizedValue(), aLocale);
if (NS_WARN_IF(NS_FAILED(rv))) {
return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
}
}
-#endif
}
return NS_OK;
@@ -1271,8 +1257,6 @@ IDBObjectStore::DeserializeIndexValue(JSContext* aCx,
return true;
}
-#if !defined(MOZ_B2G)
-
// static
bool
IDBObjectStore::DeserializeUpgradeValue(JSContext* aCx,
@@ -1309,8 +1293,6 @@ IDBObjectStore::DeserializeUpgradeValue(JSContext* aCx,
return true;
}
-#endif // MOZ_B2G
-
#ifdef DEBUG
void
@@ -2052,11 +2034,9 @@ IDBObjectStore::CreateIndex(const nsAString& aName,
// Valid locale names are always ASCII as per BCP-47.
nsCString locale = NS_LossyConvertUTF16toASCII(aOptionalParameters.mLocale);
bool autoLocale = locale.EqualsASCII("auto");
-#ifdef ENABLE_INTL_API
if (autoLocale) {
locale = IndexedDatabaseManager::GetLocale();
}
-#endif
IndexMetadata* metadata = indexes.AppendElement(
IndexMetadata(transaction->NextIndexId(), nsString(aName), keyPath,
diff --git a/dom/indexedDB/IDBObjectStore.h b/dom/indexedDB/IDBObjectStore.h
index 7a255a4af..994931afa 100644
--- a/dom/indexedDB/IDBObjectStore.h
+++ b/dom/indexedDB/IDBObjectStore.h
@@ -101,12 +101,10 @@ public:
StructuredCloneReadInfo& aCloneReadInfo,
JS::MutableHandle<JS::Value> aValue);
-#if !defined(MOZ_B2G)
static bool
DeserializeUpgradeValue(JSContext* aCx,
StructuredCloneReadInfo& aCloneReadInfo,
JS::MutableHandle<JS::Value> aValue);
-#endif
static const JSClass*
DummyPropClass()
diff --git a/dom/indexedDB/IndexedDatabaseManager.cpp b/dom/indexedDB/IndexedDatabaseManager.cpp
index 2590b0127..f65381fe8 100644
--- a/dom/indexedDB/IndexedDatabaseManager.cpp
+++ b/dom/indexedDB/IndexedDatabaseManager.cpp
@@ -59,10 +59,8 @@
#include "mozilla/dom/IDBTransactionBinding.h"
#include "mozilla/dom/IDBVersionChangeEventBinding.h"
-#ifdef ENABLE_INTL_API
#include "nsCharSeparatedTokenizer.h"
#include "unicode/locid.h"
-#endif
#define IDB_STR "indexedDB"
@@ -430,7 +428,6 @@ IndexedDatabaseManager::Init()
Preferences::RegisterCallbackAndCall(MaxSerializedMsgSizePrefChangeCallback,
kPrefMaxSerilizedMsgSize);
-#ifdef ENABLE_INTL_API
const nsAdoptingCString& acceptLang =
Preferences::GetLocalizedCString("intl.accept_languages");
@@ -449,7 +446,6 @@ IndexedDatabaseManager::Init()
if (mLocale.IsEmpty()) {
mLocale.AssignLiteral("en_US");
}
-#endif
return NS_OK;
}
@@ -1088,7 +1084,6 @@ IndexedDatabaseManager::LoggingModePrefChangedCallback(
}
}
-#ifdef ENABLE_INTL_API
// static
const nsCString&
IndexedDatabaseManager::GetLocale()
@@ -1098,7 +1093,6 @@ IndexedDatabaseManager::GetLocale()
return idbManager->mLocale;
}
-#endif
NS_IMPL_ADDREF(IndexedDatabaseManager)
NS_IMPL_RELEASE_WITH_DESTROY(IndexedDatabaseManager, Destroy())
diff --git a/dom/indexedDB/IndexedDatabaseManager.h b/dom/indexedDB/IndexedDatabaseManager.h
index 8bb9d7003..d63c548ec 100644
--- a/dom/indexedDB/IndexedDatabaseManager.h
+++ b/dom/indexedDB/IndexedDatabaseManager.h
@@ -186,10 +186,8 @@ public:
nsresult
FlushPendingFileDeletions();
-#ifdef ENABLE_INTL_API
static const nsCString&
GetLocale();
-#endif
static mozilla::Mutex&
FileMutex()
@@ -238,9 +236,7 @@ private:
// and FileInfo.mSliceRefCnt
mozilla::Mutex mFileMutex;
-#ifdef ENABLE_INTL_API
nsCString mLocale;
-#endif
indexedDB::BackgroundUtilsChild* mBackgroundActor;
diff --git a/dom/indexedDB/Key.cpp b/dom/indexedDB/Key.cpp
index 945320dd5..0f693b2c6 100644
--- a/dom/indexedDB/Key.cpp
+++ b/dom/indexedDB/Key.cpp
@@ -22,9 +22,7 @@
#include "ReportInternalError.h"
#include "xpcpublic.h"
-#ifdef ENABLE_INTL_API
#include "unicode/ucol.h"
-#endif
namespace mozilla {
namespace dom {
@@ -108,7 +106,6 @@ namespace indexedDB {
[1, 2] // 0x60 bf f0 0 0 0 0 0 0 0x10 c0
[[]] // 0x80
*/
-#ifdef ENABLE_INTL_API
nsresult
Key::ToLocaleBasedKey(Key& aTarget, const nsCString& aLocale) const
{
@@ -202,7 +199,6 @@ Key::ToLocaleBasedKey(Key& aTarget, const nsCString& aLocale) const
aTarget.TrimBuffer();
return NS_OK;
}
-#endif
nsresult
Key::EncodeJSValInternal(JSContext* aCx, JS::Handle<JS::Value> aVal,
@@ -483,7 +479,6 @@ Key::EncodeAsString(const T* aStart, const T* aEnd, uint8_t aType)
NS_ASSERTION(buffer == mBuffer.EndReading(), "Wrote wrong number of bytes");
}
-#ifdef ENABLE_INTL_API
nsresult
Key::EncodeLocaleString(const nsDependentString& aString, uint8_t aTypeOffset,
const nsCString& aLocale)
@@ -522,7 +517,6 @@ Key::EncodeLocaleString(const nsDependentString& aString, uint8_t aTypeOffset,
aTypeOffset);
return NS_OK;
}
-#endif
// static
nsresult
diff --git a/dom/indexedDB/Key.h b/dom/indexedDB/Key.h
index 856089c97..9d70ce6ad 100644
--- a/dom/indexedDB/Key.h
+++ b/dom/indexedDB/Key.h
@@ -214,10 +214,8 @@ public:
nsresult
AppendItem(JSContext* aCx, bool aFirstOfArray, JS::Handle<JS::Value> aVal);
-#ifdef ENABLE_INTL_API
nsresult
ToLocaleBasedKey(Key& aTarget, const nsCString& aLocale) const;
-#endif
void
FinishArray()
@@ -298,11 +296,9 @@ private:
void
EncodeAsString(const T* aStart, const T* aEnd, uint8_t aType);
-#ifdef ENABLE_INTL_API
nsresult
EncodeLocaleString(const nsDependentString& aString, uint8_t aTypeOffset,
const nsCString& aLocale);
-#endif
void
EncodeNumber(double aFloat, uint8_t aType);
diff --git a/dom/indexedDB/moz.build b/dom/indexedDB/moz.build
index 1fb01135c..d8c217f38 100644
--- a/dom/indexedDB/moz.build
+++ b/dom/indexedDB/moz.build
@@ -17,8 +17,7 @@ XPCSHELL_TESTS_MANIFESTS += [
'test/unit/xpcshell-parent-process.ini'
]
-if CONFIG['ENABLE_INTL_API']:
- MOCHITEST_MANIFESTS += ['test/mochitest-intl-api.ini']
+MOCHITEST_MANIFESTS += ['test/mochitest-intl-api.ini']
EXPORTS.mozilla.dom += [
'IDBCursor.h',
diff --git a/dom/indexedDB/test/unit/xpcshell-child-process.ini b/dom/indexedDB/test/unit/xpcshell-child-process.ini
index 970fe8c3d..5918471ea 100644
--- a/dom/indexedDB/test/unit/xpcshell-child-process.ini
+++ b/dom/indexedDB/test/unit/xpcshell-child-process.ini
@@ -6,7 +6,7 @@
dupe-manifest =
head = xpcshell-head-child-process.js
tail =
-skip-if = toolkit == 'android' || toolkit == 'gonk'
+skip-if = toolkit == 'android'
support-files =
GlobalObjectsChild.js
GlobalObjectsComponent.js
diff --git a/dom/indexedDB/test/unit/xpcshell-parent-process.ini b/dom/indexedDB/test/unit/xpcshell-parent-process.ini
index 22bc861cc..04df5f552 100644
--- a/dom/indexedDB/test/unit/xpcshell-parent-process.ini
+++ b/dom/indexedDB/test/unit/xpcshell-parent-process.ini
@@ -6,7 +6,6 @@
dupe-manifest =
head = xpcshell-head-parent-process.js
tail =
-skip-if = toolkit == 'gonk'
support-files =
bug1056939_profile.zip
defaultStorageUpgrade_profile.zip
diff --git a/dom/inputmethod/HardwareKeyHandler.cpp b/dom/inputmethod/HardwareKeyHandler.cpp
deleted file mode 100644
index 737c30e5b..000000000
--- a/dom/inputmethod/HardwareKeyHandler.cpp
+++ /dev/null
@@ -1,562 +0,0 @@
-/* -*- 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 "HardwareKeyHandler.h"
-#include "mozilla/BasicEvents.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/dom/KeyboardEvent.h"
-#include "mozilla/dom/TabParent.h"
-#include "mozilla/EventDispatcher.h"
-#include "mozilla/EventStateManager.h"
-#include "mozilla/TextEvents.h"
-#include "nsDeque.h"
-#include "nsFocusManager.h"
-#include "nsFrameLoader.h"
-#include "nsIContent.h"
-#include "nsIDOMHTMLDocument.h"
-#include "nsIDOMHTMLElement.h"
-#include "nsPIDOMWindow.h"
-#include "nsPresContext.h"
-#include "nsPresShell.h"
-
-namespace mozilla {
-
-using namespace dom;
-
-NS_IMPL_ISUPPORTS(HardwareKeyHandler, nsIHardwareKeyHandler)
-
-StaticRefPtr<HardwareKeyHandler> HardwareKeyHandler::sInstance;
-
-HardwareKeyHandler::HardwareKeyHandler()
- : mInputMethodAppConnected(false)
-{
-}
-
-HardwareKeyHandler::~HardwareKeyHandler()
-{
-}
-
-NS_IMETHODIMP
-HardwareKeyHandler::OnInputMethodAppConnected()
-{
- if (NS_WARN_IF(mInputMethodAppConnected)) {
- return NS_ERROR_UNEXPECTED;
- }
-
- mInputMethodAppConnected = true;
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-HardwareKeyHandler::OnInputMethodAppDisconnected()
-{
- if (NS_WARN_IF(!mInputMethodAppConnected)) {
- return NS_ERROR_UNEXPECTED;
- }
-
- mInputMethodAppConnected = false;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-HardwareKeyHandler::RegisterListener(nsIHardwareKeyEventListener* aListener)
-{
- // Make sure the listener is not nullptr and there is no available
- // hardwareKeyEventListener now
- if (NS_WARN_IF(!aListener)) {
- return NS_ERROR_NULL_POINTER;
- }
-
- if (NS_WARN_IF(mHardwareKeyEventListener)) {
- return NS_ERROR_ALREADY_INITIALIZED;
- }
-
- mHardwareKeyEventListener = do_GetWeakReference(aListener);
-
- if (NS_WARN_IF(!mHardwareKeyEventListener)) {
- return NS_ERROR_NULL_POINTER;
- }
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-HardwareKeyHandler::UnregisterListener()
-{
- // Clear the HardwareKeyEventListener
- mHardwareKeyEventListener = nullptr;
- return NS_OK;
-}
-
-bool
-HardwareKeyHandler::ForwardKeyToInputMethodApp(nsINode* aTarget,
- WidgetKeyboardEvent* aEvent,
- nsEventStatus* aEventStatus)
-{
- MOZ_ASSERT(aTarget, "No target provided");
- MOZ_ASSERT(aEvent, "No event provided");
-
- // No need to forward hardware key event to IME
- // if key's defaultPrevented is true
- if (aEvent->mFlags.mDefaultPrevented) {
- return false;
- }
-
- // No need to forward hardware key event to IME if IME is disabled
- if (!mInputMethodAppConnected) {
- return false;
- }
-
- // No need to forward hardware key event to IME
- // if this key event is generated by IME itself(from nsITextInputProcessor)
- if (aEvent->mIsSynthesizedByTIP) {
- return false;
- }
-
- // No need to forward hardware key event to IME
- // if the key event is handling or already handled
- if (aEvent->mInputMethodAppState != WidgetKeyboardEvent::eNotHandled) {
- return false;
- }
-
- // No need to forward hardware key event to IME
- // if there is no nsIHardwareKeyEventListener in use
- nsCOMPtr<nsIHardwareKeyEventListener>
- keyHandler(do_QueryReferent(mHardwareKeyEventListener));
- if (!keyHandler) {
- return false;
- }
-
- // Set the flags to specify the keyboard event is in forwarding phase.
- aEvent->mInputMethodAppState = WidgetKeyboardEvent::eHandling;
-
- // For those keypress events coming after their heading keydown's reply
- // already arrives, they should be dispatched directly instead of
- // being stored into the event queue. Otherwise, without the heading keydown
- // in the event queue, the stored keypress will never be withdrawn to be fired.
- if (aEvent->mMessage == eKeyPress && mEventQueue.IsEmpty()) {
- DispatchKeyPress(aTarget, *aEvent, *aEventStatus);
- return true;
- }
-
- // Push the key event into queue for reuse when its reply arrives.
- KeyboardInfo* copiedInfo =
- new KeyboardInfo(aTarget,
- *aEvent,
- aEventStatus ? *aEventStatus : nsEventStatus_eIgnore);
-
- // No need to forward hardware key event to IME if the event queue is full
- if (!mEventQueue.Push(copiedInfo)) {
- delete copiedInfo;
- return false;
- }
-
- // We only forward keydown and keyup event to input-method-app
- // because input-method-app will generate keypress by itself.
- if (aEvent->mMessage == eKeyPress) {
- return true;
- }
-
- // Create a keyboard event to pass into
- // nsIHardwareKeyEventListener.onHardwareKey
- nsCOMPtr<EventTarget> eventTarget = do_QueryInterface(aTarget);
- nsPresContext* presContext = GetPresContext(aTarget);
- RefPtr<KeyboardEvent> keyboardEvent =
- NS_NewDOMKeyboardEvent(eventTarget, presContext, aEvent->AsKeyboardEvent());
- // Duplicate the internal event data in the heap for the keyboardEvent,
- // or the internal data from |aEvent| in the stack may be destroyed by others.
- keyboardEvent->DuplicatePrivateData();
-
- // Forward the created keyboard event to input-method-app
- bool isSent = false;
- keyHandler->OnHardwareKey(keyboardEvent, &isSent);
-
- // Pop the pending key event if it can't be forwarded
- if (!isSent) {
- mEventQueue.RemoveFront();
- }
-
- return isSent;
-}
-
-NS_IMETHODIMP
-HardwareKeyHandler::OnHandledByInputMethodApp(const nsAString& aType,
- uint16_t aDefaultPrevented)
-{
- // We can not handle this reply because the pending events had been already
- // removed from the forwarding queue before this reply arrives.
- if (mEventQueue.IsEmpty()) {
- return NS_OK;
- }
-
- RefPtr<KeyboardInfo> keyInfo = mEventQueue.PopFront();
-
- // Only allow keydown and keyup to call this method
- if (NS_WARN_IF(aType.EqualsLiteral("keydown") &&
- keyInfo->mEvent.mMessage != eKeyDown) ||
- NS_WARN_IF(aType.EqualsLiteral("keyup") &&
- keyInfo->mEvent.mMessage != eKeyUp)) {
- return NS_ERROR_INVALID_ARG;
- }
-
- // The value of defaultPrevented depends on whether or not
- // the key is consumed by input-method-app
- SetDefaultPrevented(keyInfo->mEvent, aDefaultPrevented);
-
- // Set the flag to specify the reply phase
- keyInfo->mEvent.mInputMethodAppState = WidgetKeyboardEvent::eHandled;
-
- // Check whether the event is still valid to be fired
- if (CanDispatchEvent(keyInfo->mTarget, keyInfo->mEvent)) {
- // If the key's defaultPrevented is true, it means that the
- // input-method-app has already consumed this key,
- // so we can dispatch |mozbrowserafterkey*| directly if
- // preference "dom.beforeAfterKeyboardEvent.enabled" is enabled.
- if (keyInfo->mEvent.mFlags.mDefaultPrevented) {
- DispatchAfterKeyEvent(keyInfo->mTarget, keyInfo->mEvent);
- // Otherwise, it means that input-method-app doesn't handle this key,
- // so we need to dispatch it to its current event target.
- } else {
- DispatchToTargetApp(keyInfo->mTarget,
- keyInfo->mEvent,
- keyInfo->mStatus);
- }
- }
-
- // No need to do further processing if the event is not keydown
- if (keyInfo->mEvent.mMessage != eKeyDown) {
- return NS_OK;
- }
-
- // Update the latest keydown data:
- // Release the holding reference to the previous keydown's data and
- // add a reference count to the current keydown's data.
- mLatestKeyDownInfo = keyInfo;
-
- // Handle the pending keypress event once keydown's reply arrives:
- // It may have many keypress events per keydown on some platforms,
- // so we use loop to dispatch keypress events.
- // (But Gonk dispatch only one keypress per keydown)
- // However, if there is no keypress after this keydown,
- // then those following keypress will be handled in
- // ForwardKeyToInputMethodApp directly.
- for (KeyboardInfo* keypressInfo;
- !mEventQueue.IsEmpty() &&
- (keypressInfo = mEventQueue.PeekFront()) &&
- keypressInfo->mEvent.mMessage == eKeyPress;
- mEventQueue.RemoveFront()) {
- DispatchKeyPress(keypressInfo->mTarget,
- keypressInfo->mEvent,
- keypressInfo->mStatus);
- }
-
- return NS_OK;
-}
-
-bool
-HardwareKeyHandler::DispatchKeyPress(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus& aStatus)
-{
- MOZ_ASSERT(aTarget, "No target provided");
- MOZ_ASSERT(aEvent.mMessage == eKeyPress, "Event is not keypress");
-
- // No need to dispatch keypress to the event target
- // if the keydown event is consumed by the input-method-app.
- if (mLatestKeyDownInfo &&
- mLatestKeyDownInfo->mEvent.mFlags.mDefaultPrevented) {
- return false;
- }
-
- // No need to dispatch keypress to the event target
- // if the previous keydown event is modifier key's
- if (mLatestKeyDownInfo &&
- mLatestKeyDownInfo->mEvent.IsModifierKeyEvent()) {
- return false;
- }
-
- // No need to dispatch keypress to the event target
- // if it's invalid to be dispatched
- if (!CanDispatchEvent(aTarget, aEvent)) {
- return false;
- }
-
- // Set the flag to specify the reply phase.
- aEvent.mInputMethodAppState = WidgetKeyboardEvent::eHandled;
-
- // Dispatch the pending keypress event
- bool ret = DispatchToTargetApp(aTarget, aEvent, aStatus);
-
- // Re-trigger EventStateManager::PostHandleKeyboardEvent for keypress
- PostHandleKeyboardEvent(aTarget, aEvent, aStatus);
-
- return ret;
-}
-
-void
-HardwareKeyHandler::DispatchAfterKeyEvent(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent)
-{
- MOZ_ASSERT(aTarget, "No target provided");
-
- if (!PresShell::BeforeAfterKeyboardEventEnabled() ||
- aEvent.mMessage == eKeyPress) {
- return;
- }
-
- nsCOMPtr<nsIPresShell> presShell = GetPresShell(aTarget);
- if (NS_WARN_IF(presShell)) {
- presShell->DispatchAfterKeyboardEvent(aTarget,
- aEvent,
- aEvent.mFlags.mDefaultPrevented);
- }
-}
-
-bool
-HardwareKeyHandler::DispatchToTargetApp(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus& aStatus)
-{
- MOZ_ASSERT(aTarget, "No target provided");
-
- // Get current focused element as the event target
- nsCOMPtr<nsIContent> currentTarget = GetCurrentTarget();
- if (NS_WARN_IF(!currentTarget)) {
- return false;
- }
-
- // The event target should be set to the current focused element.
- // However, it might have security issue if the event is dispatched to
- // the unexpected application, and it might cause unexpected operation
- // in the new app.
- nsCOMPtr<nsPIDOMWindowOuter> originalRootWindow = GetRootWindow(aTarget);
- nsCOMPtr<nsPIDOMWindowOuter> currentRootWindow = GetRootWindow(currentTarget);
- if (currentRootWindow != originalRootWindow) {
- NS_WARNING("The root window is changed during the event is dispatching");
- return false;
- }
-
- // If the current focused element is still in the same app,
- // then we can use it as the current target to dispatch event.
- nsCOMPtr<nsIPresShell> presShell = GetPresShell(currentTarget);
- if (!presShell) {
- return false;
- }
-
- if (!presShell->CanDispatchEvent(&aEvent)) {
- return false;
- }
-
- // In-process case: the event target is in the current process
- if (!PresShell::IsTargetIframe(currentTarget)) {
- DispatchToCurrentProcess(presShell, currentTarget, aEvent, aStatus);
-
- if (presShell->CanDispatchEvent(&aEvent)) {
- DispatchAfterKeyEvent(aTarget, aEvent);
- }
-
- return true;
- }
-
- // OOP case: the event target is in the child process
- return DispatchToCrossProcess(aTarget, aEvent);
-
- // After the oop target receives the event from TabChild::RecvRealKeyEvent
- // and return the result through TabChild::SendDispatchAfterKeyboardEvent,
- // the |mozbrowserafterkey*| will be fired from
- // TabParent::RecvDispatchAfterKeyboardEvent, so we don't need to dispatch
- // |mozbrowserafterkey*| by ourselves in this module.
-}
-
-void
-HardwareKeyHandler::DispatchToCurrentProcess(nsIPresShell* presShell,
- nsIContent* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus& aStatus)
-{
- EventDispatcher::Dispatch(aTarget, presShell->GetPresContext(),
- &aEvent, nullptr, &aStatus, nullptr);
-}
-
-bool
-HardwareKeyHandler::DispatchToCrossProcess(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent)
-{
- nsCOMPtr<nsIFrameLoaderOwner> remoteLoaderOwner = do_QueryInterface(aTarget);
- if (NS_WARN_IF(!remoteLoaderOwner)) {
- return false;
- }
-
- RefPtr<nsFrameLoader> remoteFrameLoader =
- remoteLoaderOwner->GetFrameLoader();
- if (NS_WARN_IF(!remoteFrameLoader)) {
- return false;
- }
-
- uint32_t eventMode;
- remoteFrameLoader->GetEventMode(&eventMode);
- if (eventMode == nsIFrameLoader::EVENT_MODE_DONT_FORWARD_TO_CHILD) {
- return false;
- }
-
- PBrowserParent* remoteBrowser = remoteFrameLoader->GetRemoteBrowser();
- TabParent* remote = static_cast<TabParent*>(remoteBrowser);
- if (NS_WARN_IF(!remote)) {
- return false;
- }
-
- return remote->SendRealKeyEvent(aEvent);
-}
-
-void
-HardwareKeyHandler::PostHandleKeyboardEvent(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus& aStatus)
-{
- MOZ_ASSERT(aTarget, "No target provided");
-
- nsPresContext* presContext = GetPresContext(aTarget);
-
- RefPtr<mozilla::EventStateManager> esm = presContext->EventStateManager();
- bool dispatchedToChildProcess = PresShell::IsTargetIframe(aTarget);
- esm->PostHandleKeyboardEvent(&aEvent, aStatus, dispatchedToChildProcess);
-}
-
-void
-HardwareKeyHandler::SetDefaultPrevented(WidgetKeyboardEvent& aEvent,
- uint16_t aDefaultPrevented) {
- if (aDefaultPrevented & DEFAULT_PREVENTED) {
- aEvent.mFlags.mDefaultPrevented = true;
- }
-
- if (aDefaultPrevented & DEFAULT_PREVENTED_BY_CHROME) {
- aEvent.mFlags.mDefaultPreventedByChrome = true;
- }
-
- if (aDefaultPrevented & DEFAULT_PREVENTED_BY_CONTENT) {
- aEvent.mFlags.mDefaultPreventedByContent = true;
- }
-}
-
-bool
-HardwareKeyHandler::CanDispatchEvent(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent)
-{
- nsCOMPtr<nsIPresShell> presShell = GetPresShell(aTarget);
- if (NS_WARN_IF(!presShell)) {
- return false;
- }
- return presShell->CanDispatchEvent(&aEvent);
-}
-
-already_AddRefed<nsPIDOMWindowOuter>
-HardwareKeyHandler::GetRootWindow(nsINode* aNode)
-{
- // Get nsIPresShell's pointer first
- nsCOMPtr<nsIPresShell> presShell = GetPresShell(aNode);
- if (NS_WARN_IF(!presShell)) {
- return nullptr;
- }
- nsCOMPtr<nsPIDOMWindowOuter> rootWindow = presShell->GetRootWindow();
- return rootWindow.forget();
-}
-
-already_AddRefed<nsIContent>
-HardwareKeyHandler::GetCurrentTarget()
-{
- nsFocusManager* fm = nsFocusManager::GetFocusManager();
- if (NS_WARN_IF(!fm)) {
- return nullptr;
- }
-
- nsCOMPtr<mozIDOMWindowProxy> focusedWindow;
- fm->GetFocusedWindow(getter_AddRefs(focusedWindow));
- if (NS_WARN_IF(!focusedWindow)) {
- return nullptr;
- }
-
- auto* ourWindow = nsPIDOMWindowOuter::From(focusedWindow);
-
- nsCOMPtr<nsPIDOMWindowOuter> rootWindow = ourWindow->GetPrivateRoot();
- if (NS_WARN_IF(!rootWindow)) {
- return nullptr;
- }
-
- nsCOMPtr<nsPIDOMWindowOuter> focusedFrame;
- nsCOMPtr<nsIContent> focusedContent =
- fm->GetFocusedDescendant(rootWindow, true, getter_AddRefs(focusedFrame));
-
- // If there is no focus, then we use document body instead
- if (NS_WARN_IF(!focusedContent || !focusedContent->GetPrimaryFrame())) {
- nsIDocument* document = ourWindow->GetExtantDoc();
- if (NS_WARN_IF(!document)) {
- return nullptr;
- }
-
- focusedContent = document->GetRootElement();
-
- nsCOMPtr<nsIDOMHTMLDocument> htmlDocument = do_QueryInterface(document);
- if (htmlDocument) {
- nsCOMPtr<nsIDOMHTMLElement> body;
- htmlDocument->GetBody(getter_AddRefs(body));
- nsCOMPtr<nsIContent> bodyContent = do_QueryInterface(body);
- if (bodyContent) {
- focusedContent = bodyContent;
- }
- }
- }
-
- return focusedContent ? focusedContent.forget() : nullptr;
-}
-
-nsPresContext*
-HardwareKeyHandler::GetPresContext(nsINode* aNode)
-{
- // Get nsIPresShell's pointer first
- nsCOMPtr<nsIPresShell> presShell = GetPresShell(aNode);
- if (NS_WARN_IF(!presShell)) {
- return nullptr;
- }
-
- // then use nsIPresShell to get nsPresContext's pointer
- return presShell->GetPresContext();
-}
-
-already_AddRefed<nsIPresShell>
-HardwareKeyHandler::GetPresShell(nsINode* aNode)
-{
- nsIDocument* doc = aNode->OwnerDoc();
- if (NS_WARN_IF(!doc)) {
- return nullptr;
- }
-
- nsCOMPtr<nsIPresShell> presShell = doc->GetShell();
- if (NS_WARN_IF(!presShell)) {
- return nullptr;
- }
-
- return presShell.forget();
-}
-
-/* static */
-already_AddRefed<HardwareKeyHandler>
-HardwareKeyHandler::GetInstance()
-{
- if (!XRE_IsParentProcess()) {
- return nullptr;
- }
-
- if (!sInstance) {
- sInstance = new HardwareKeyHandler();
- ClearOnShutdown(&sInstance);
- }
-
- RefPtr<HardwareKeyHandler> service = sInstance.get();
- return service.forget();
-}
-
-} // namespace mozilla
diff --git a/dom/inputmethod/HardwareKeyHandler.h b/dom/inputmethod/HardwareKeyHandler.h
deleted file mode 100644
index 7520c40cd..000000000
--- a/dom/inputmethod/HardwareKeyHandler.h
+++ /dev/null
@@ -1,224 +0,0 @@
-/* -*- 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_HardwareKeyHandler_h_
-#define mozilla_HardwareKeyHandler_h_
-
-#include "mozilla/EventForwards.h" // for nsEventStatus
-#include "mozilla/StaticPtr.h"
-#include "mozilla/TextEvents.h"
-#include "nsCOMPtr.h"
-#include "nsDeque.h"
-#include "nsIHardwareKeyHandler.h"
-#include "nsIWeakReferenceUtils.h" // for nsWeakPtr
-
-class nsIContent;
-class nsINode;
-class nsIPresShell;
-class nsPIDOMWindowOuter;
-class nsPresContext;
-
-namespace mozilla {
-
-// This module will copy the events' data into its event queue for reuse
-// after receiving input-method-app's reply, so we use the following struct
-// for storing these information.
-// RefCounted<T> is a helper class for adding reference counting mechanism.
-struct KeyboardInfo : public RefCounted<KeyboardInfo>
-{
- MOZ_DECLARE_REFCOUNTED_TYPENAME(KeyboardInfo)
-
- nsINode* mTarget;
- WidgetKeyboardEvent mEvent;
- nsEventStatus mStatus;
-
- KeyboardInfo(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus aStatus)
- : mTarget(aTarget)
- , mEvent(aEvent)
- , mStatus(aStatus)
- {
- }
-};
-
-// The following is the type-safe wrapper around nsDeque
-// for storing events' data.
-// The T must be one class that supports reference counting mechanism.
-// The EventQueueDeallocator will be called in nsDeque::~nsDeque() or
-// nsDeque::Erase() to deallocate the objects. nsDeque::Erase() will remove
-// and delete all items in the queue. See more from nsDeque.h.
-template <class T>
-class EventQueueDeallocator : public nsDequeFunctor
-{
- virtual void* operator() (void* aObject)
- {
- RefPtr<T> releaseMe = dont_AddRef(static_cast<T*>(aObject));
- return nullptr;
- }
-};
-
-// The type-safe queue to be used to store the KeyboardInfo data
-template <class T>
-class EventQueue : private nsDeque
-{
-public:
- EventQueue()
- : nsDeque(new EventQueueDeallocator<T>())
- {
- };
-
- ~EventQueue()
- {
- Clear();
- }
-
- inline size_t GetSize()
- {
- return nsDeque::GetSize();
- }
-
- bool IsEmpty()
- {
- return !nsDeque::GetSize();
- }
-
- inline bool Push(T* aItem)
- {
- MOZ_ASSERT(aItem);
- NS_ADDREF(aItem);
- size_t sizeBefore = GetSize();
- nsDeque::Push(aItem);
- if (GetSize() != sizeBefore + 1) {
- NS_RELEASE(aItem);
- return false;
- }
- return true;
- }
-
- inline already_AddRefed<T> PopFront()
- {
- RefPtr<T> rv = dont_AddRef(static_cast<T*>(nsDeque::PopFront()));
- return rv.forget();
- }
-
- inline void RemoveFront()
- {
- RefPtr<T> releaseMe = PopFront();
- }
-
- inline T* PeekFront()
- {
- return static_cast<T*>(nsDeque::PeekFront());
- }
-
- void Clear()
- {
- while (GetSize() > 0) {
- RemoveFront();
- }
- }
-};
-
-class HardwareKeyHandler : public nsIHardwareKeyHandler
-{
-public:
- HardwareKeyHandler();
-
- NS_DECL_ISUPPORTS
- NS_DECL_NSIHARDWAREKEYHANDLER
-
- static already_AddRefed<HardwareKeyHandler> GetInstance();
-
- virtual bool ForwardKeyToInputMethodApp(nsINode* aTarget,
- WidgetKeyboardEvent* aEvent,
- nsEventStatus* aEventStatus) override;
-
-private:
- virtual ~HardwareKeyHandler();
-
- // Return true if the keypress is successfully dispatched.
- // Otherwise, return false.
- bool DispatchKeyPress(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus& aStatus);
-
- void DispatchAfterKeyEvent(nsINode* aTarget, WidgetKeyboardEvent& aEvent);
-
- void DispatchToCurrentProcess(nsIPresShell* aPresShell,
- nsIContent* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus& aStatus);
-
- bool DispatchToCrossProcess(nsINode* aTarget, WidgetKeyboardEvent& aEvent);
-
- // This method will dispatch not only key* event to its event target,
- // no mather it's in the current process or in its child process,
- // but also mozbrowserafterkey* to the corresponding target if it needs.
- // Return true if the key is successfully dispatched.
- // Otherwise, return false.
- bool DispatchToTargetApp(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus& aStatus);
-
- // This method will be called after dispatching keypress to its target,
- // if the input-method-app doesn't handle the key.
- // In normal dispatching path, EventStateManager::PostHandleKeyboardEvent
- // will be called when event is keypress.
- // However, the ::PostHandleKeyboardEvent mentioned above will be aborted
- // when we try to forward key event to the input-method-app.
- // If the input-method-app consumes the key, then we don't need to do anything
- // because the input-method-app will generate a new key event by itself.
- // On the other hand, if the input-method-app doesn't consume the key,
- // then we need to dispatch the key event by ourselves
- // and call ::PostHandleKeyboardEvent again after the event is forwarded.
- // Note that the EventStateManager::PreHandleEvent is already called before
- // forwarding, so we don't need to call it in this module.
- void PostHandleKeyboardEvent(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus& aStatus);
-
- void SetDefaultPrevented(WidgetKeyboardEvent& aEvent,
- uint16_t aDefaultPrevented);
-
- // Check whether the event is valid to be fired.
- // This method should be called every time before dispatching next event.
- bool CanDispatchEvent(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent);
-
- already_AddRefed<nsPIDOMWindowOuter> GetRootWindow(nsINode* aNode);
-
- already_AddRefed<nsIContent> GetCurrentTarget();
-
- nsPresContext* GetPresContext(nsINode* aNode);
-
- already_AddRefed<nsIPresShell> GetPresShell(nsINode* aNode);
-
- static StaticRefPtr<HardwareKeyHandler> sInstance;
-
- // The event queue is used to store the forwarded keyboard events.
- // Those stored events will be dispatched if input-method-app doesn't
- // consume them.
- EventQueue<KeyboardInfo> mEventQueue;
-
- // Hold the pointer to the latest keydown's data
- RefPtr<KeyboardInfo> mLatestKeyDownInfo;
-
- // input-method-app needs to register a listener by
- // |nsIHardwareKeyHandler.registerListener| to receive
- // the hardware keyboard event, and |nsIHardwareKeyHandler.registerListener|
- // will set an nsIHardwareKeyEventListener to mHardwareKeyEventListener.
- // Then, mHardwareKeyEventListener is used to forward the event
- // to the input-method-app.
- nsWeakPtr mHardwareKeyEventListener;
-
- // To keep tracking the input-method-app is active or disabled.
- bool mInputMethodAppConnected;
-};
-
-} // namespace mozilla
-
-#endif // #ifndef mozilla_HardwareKeyHandler_h_
diff --git a/dom/inputmethod/Keyboard.jsm b/dom/inputmethod/Keyboard.jsm
index 22f87ffbc..51506c41f 100644
--- a/dom/inputmethod/Keyboard.jsm
+++ b/dom/inputmethod/Keyboard.jsm
@@ -24,12 +24,7 @@ XPCOMUtils.defineLazyGetter(this, "appsService", function() {
});
XPCOMUtils.defineLazyGetter(this, "hardwareKeyHandler", function() {
-#ifdef MOZ_B2G
- return Cc["@mozilla.org/HardwareKeyHandler;1"]
- .getService(Ci.nsIHardwareKeyHandler);
-#else
return null;
-#endif
});
var Utils = {
@@ -50,17 +45,6 @@ var Utils = {
};
this.Keyboard = {
-#ifdef MOZ_B2G
- // For receving keyboard event fired from hardware before it's dispatched,
- // |this| object is used to be the listener to get the forwarded event.
- // As the listener, |this| object must implement nsIHardwareKeyEventListener
- // and nsSupportsWeakReference.
- // Please see nsIHardwareKeyHandler.idl to get more information.
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIHardwareKeyEventListener,
- Ci.nsISupportsWeakReference
- ]),
-#endif
_isConnectedToHardwareKeyHandler: false,
_formMM: null, // The current web page message manager.
_keyboardMM: null, // The keyboard app message manager.
diff --git a/dom/inputmethod/moz.build b/dom/inputmethod/moz.build
index 504e2ebfc..84b3cb8ab 100644
--- a/dom/inputmethod/moz.build
+++ b/dom/inputmethod/moz.build
@@ -4,29 +4,6 @@
# License, v. 2.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_B2G']:
- XPIDL_SOURCES += [
- 'nsIHardwareKeyHandler.idl',
- ]
-
- XPIDL_MODULE = 'inputmethod'
-
- EXPORTS.mozilla += [
- 'HardwareKeyHandler.h',
- ]
-
- SOURCES += [
- 'HardwareKeyHandler.cpp'
- ]
-
- include('/ipc/chromium/chromium-config.mozbuild')
-
- FINAL_LIBRARY = 'xul'
- LOCAL_INCLUDES += [
- '/dom/base',
- '/layout/base',
- ]
-
EXTRA_COMPONENTS += [
'InputMethod.manifest',
'MozKeyboard.js',
diff --git a/dom/inputmethod/nsIHardwareKeyHandler.idl b/dom/inputmethod/nsIHardwareKeyHandler.idl
deleted file mode 100644
index 5bce4d980..000000000
--- a/dom/inputmethod/nsIHardwareKeyHandler.idl
+++ /dev/null
@@ -1,142 +0,0 @@
-/* -*- 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 "nsISupports.idl"
-
-interface nsIDOMKeyEvent;
-
-%{C++
-#define NS_HARDWARE_KEY_HANDLER_CID \
- { 0xfb45921b, 0xe0a5, 0x45c6, \
- { 0x90, 0xd0, 0xa6, 0x97, 0xa7, 0x72, 0xc4, 0x2a } }
-#define NS_HARDWARE_KEY_HANDLER_CONTRACTID \
- "@mozilla.org/HardwareKeyHandler;1"
-
-#include "mozilla/EventForwards.h" /* For nsEventStatus */
-
-namespace mozilla {
-class WidgetKeyboardEvent;
-}
-
-using mozilla::WidgetKeyboardEvent;
-
-class nsINode;
-%}
-
-/**
- * This interface is used to be registered to the nsIHardwareKeyHandler through
- * |nsIHardwareKeyHandler.registerListener|.
- */
-[scriptable, function, uuid(cd5aeee3-b4b9-459d-85e7-c0671c7a8a2e)]
-interface nsIHardwareKeyEventListener : nsISupports
-{
- /**
- * This method will be invoked by nsIHardwareKeyHandler to forward the native
- * keyboard event to the active input method
- */
- bool onHardwareKey(in nsIDOMKeyEvent aEvent);
-};
-
-/**
- * This interface has two main roles. One is to send a hardware keyboard event
- * to the active input method app and the other is to receive its reply result.
- * If a keyboard event is triggered from a hardware keyboard when an editor has
- * focus, the event target should be the editor. However, the text input
- * processor algorithm is implemented in an input method app and it should
- * handle the event earlier than the real event target to do the mapping such
- * as character conversion according to the language setting or the type of a
- * hardware keyboard.
- */
-[scriptable, builtinclass, uuid(25b34270-caad-4d18-a910-860351690639)]
-interface nsIHardwareKeyHandler : nsISupports
-{
- /**
- * Flags used to set the defaultPrevented's result. The default result
- * from input-method-app should be set to NO_DEFAULT_PREVENTED.
- * (It means the forwarded event isn't consumed by input-method-app.)
- * If the input-method-app consumes the forwarded event,
- * then the result should be set by DEFAULT_PREVENTED* before reply.
- */
- const unsigned short NO_DEFAULT_PREVENTED = 0x0000;
- const unsigned short DEFAULT_PREVENTED = 0x0001;
- const unsigned short DEFAULT_PREVENTED_BY_CHROME = 0x0002;
- const unsigned short DEFAULT_PREVENTED_BY_CONTENT = 0x0004;
-
- /**
- * Registers a listener in input-method-app to receive
- * the forwarded hardware keyboard events
- *
- * @param aListener Listener object to be notified for receiving
- * the keyboard event fired from hardware
- * @note A listener object must implement
- * nsIHardwareKeyEventListener and
- * nsSupportsWeakReference
- * @see nsIHardwareKeyEventListener
- * @see nsSupportsWeakReference
- */
- void registerListener(in nsIHardwareKeyEventListener aListener);
-
- /**
- * Unregisters the current listener from input-method-app
- */
- void unregisterListener();
-
- /**
- * Notifies nsIHardwareKeyHandler that input-method-app is active.
- */
- void onInputMethodAppConnected();
-
- /**
- * Notifies nsIHardwareKeyHandler that input-method-app is disabled.
- */
- void onInputMethodAppDisconnected();
-
- /**
- * Input-method-app will pass the processing result that the forwarded
- * event is handled or not through this method, and the nsIHardwareKeyHandler
- * can use this to receive the reply of |forwardKeyToInputMethodApp|
- * from the active input method.
- *
- * The result should contain the original event type and the info whether
- * the default is prevented, also, it is prevented by chrome or content.
- *
- * @param aEventType The type of an original event.
- * @param aDefaultPrevented State that |evt.preventDefault|
- * is called by content, chrome or not.
- */
- void onHandledByInputMethodApp(in DOMString aType,
- in unsigned short aDefaultPrevented);
-
- /**
- * Sends the native keyboard events triggered from hardware to the
- * active input method before dispatching to its event target.
- * This method only forwards keydown and keyup events.
- * If the event isn't allowed to be forwarded, we should continue the
- * normal event processing. For those forwarded keydown and keyup events
- * We will pause the further event processing to wait for the completion
- * of the event handling in the active input method app.
- * Once |onHandledByInputMethodApp| is called by the input method app,
- * the pending event processing can be resumed according to its reply.
- * On the other hand, the keypress will never be sent to the input-method-app.
- * Depending on whether the keydown's reply arrives before the keypress event
- * comes, the keypress event will be handled directly or pushed into
- * the event queue to wait for its heading keydown's reply.
- *
- * This implementation will call |nsIHardwareKeyEventListener.onHardwareKey|,
- * which is registered through |nsIHardwareKeyEventListener.registerListener|,
- * to forward the events.
- *
- * Returns true, if the event is handled in this module.
- * Returns false, otherwise.
- *
- * If it returns false, we should continue the normal event processing.
- */
- %{C++
- virtual bool ForwardKeyToInputMethodApp(nsINode* aTarget,
- WidgetKeyboardEvent* aEvent,
- nsEventStatus* aEventStatus) = 0;
- %}
-};
diff --git a/dom/ipc/ContentChild.cpp b/dom/ipc/ContentChild.cpp
index 75678ca96..9e1c7e8cb 100644
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -65,21 +65,6 @@
#include "imgLoader.h"
#include "GMPServiceChild.h"
-#if defined(MOZ_CONTENT_SANDBOX)
-#if defined(XP_WIN)
-#define TARGET_SANDBOX_EXPORTS
-#include "mozilla/sandboxTarget.h"
-#elif defined(XP_LINUX)
-#include "mozilla/Sandbox.h"
-#include "mozilla/SandboxInfo.h"
-
-// Remove this include with Bug 1104619
-#include "CubebUtils.h"
-#elif defined(XP_MACOSX)
-#include "mozilla/Sandbox.h"
-#endif
-#endif
-
#include "mozilla/Unused.h"
#include "mozInlineSpellChecker.h"
@@ -152,12 +137,6 @@
#include "APKOpen.h"
#endif
-#if defined(MOZ_WIDGET_GONK)
-#include "nsVolume.h"
-#include "nsVolumeService.h"
-#include "SpeakerManagerService.h"
-#endif
-
#ifdef XP_WIN
#include <process.h>
#define getpid _getpid
@@ -211,9 +190,6 @@ using namespace mozilla::net;
using namespace mozilla::jsipc;
using namespace mozilla::psm;
using namespace mozilla::widget;
-#if defined(MOZ_WIDGET_GONK)
-using namespace mozilla::system;
-#endif
using namespace mozilla::widget;
namespace mozilla {
@@ -600,15 +576,7 @@ ContentChild::Init(MessageLoop* aIOLoop,
void
ContentChild::InitProcessAttributes()
{
-#ifdef MOZ_WIDGET_GONK
- if (mIsForApp && !mIsForBrowser) {
- SetProcessName(NS_LITERAL_STRING("(Preallocated app)"), false);
- } else {
- SetProcessName(NS_LITERAL_STRING("Browser"), false);
- }
-#else
SetProcessName(NS_LITERAL_STRING("Web Content"), true);
-#endif
}
void
@@ -1250,192 +1218,11 @@ ContentChild::AllocPProcessHangMonitorChild(Transport* aTransport,
return CreateHangMonitorChild(aTransport, aOtherProcess);
}
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
-
-#include <stdlib.h>
-
-static bool
-GetAppPaths(nsCString &aAppPath, nsCString &aAppBinaryPath, nsCString &aAppDir)
-{
- nsAutoCString appPath;
- nsAutoCString appBinaryPath(
- (CommandLine::ForCurrentProcess()->argv()[0]).c_str());
-
- nsAutoCString::const_iterator start, end;
- appBinaryPath.BeginReading(start);
- appBinaryPath.EndReading(end);
- if (RFindInReadable(NS_LITERAL_CSTRING(".app/Contents/MacOS/"), start, end)) {
- end = start;
- ++end; ++end; ++end; ++end;
- appBinaryPath.BeginReading(start);
- appPath.Assign(Substring(start, end));
- } else {
- return false;
- }
-
- nsCOMPtr<nsIFile> app, appBinary;
- nsresult rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(appPath),
- true, getter_AddRefs(app));
- if (NS_FAILED(rv)) {
- return false;
- }
- rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(appBinaryPath),
- true, getter_AddRefs(appBinary));
- if (NS_FAILED(rv)) {
- return false;
- }
-
- nsCOMPtr<nsIFile> appDir;
- nsCOMPtr<nsIProperties> dirSvc =
- do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
- if (!dirSvc) {
- return false;
- }
- rv = dirSvc->Get(NS_XPCOM_CURRENT_PROCESS_DIR,
- NS_GET_IID(nsIFile), getter_AddRefs(appDir));
- if (NS_FAILED(rv)) {
- return false;
- }
- bool exists;
- rv = appDir->Exists(&exists);
- if (NS_FAILED(rv) || !exists) {
- return false;
- }
-
- bool isLink;
- app->IsSymlink(&isLink);
- if (isLink) {
- app->GetNativeTarget(aAppPath);
- } else {
- app->GetNativePath(aAppPath);
- }
- appBinary->IsSymlink(&isLink);
- if (isLink) {
- appBinary->GetNativeTarget(aAppBinaryPath);
- } else {
- appBinary->GetNativePath(aAppBinaryPath);
- }
- appDir->IsSymlink(&isLink);
- if (isLink) {
- appDir->GetNativeTarget(aAppDir);
- } else {
- appDir->GetNativePath(aAppDir);
- }
-
- return true;
-}
-
-static bool
-StartMacOSContentSandbox()
-{
- int sandboxLevel = Preferences::GetInt("security.sandbox.content.level");
- if (sandboxLevel < 1) {
- return false;
- }
-
- nsAutoCString appPath, appBinaryPath, appDir;
- if (!GetAppPaths(appPath, appBinaryPath, appDir)) {
- MOZ_CRASH("Error resolving child process path");
- }
-
- // During sandboxed content process startup, before reaching
- // this point, NS_OS_TEMP_DIR is modified to refer to a sandbox-
- // writable temporary directory
- nsCOMPtr<nsIFile> tempDir;
- nsresult rv = nsDirectoryService::gService->Get(NS_OS_TEMP_DIR,
- NS_GET_IID(nsIFile), getter_AddRefs(tempDir));
- if (NS_FAILED(rv)) {
- MOZ_CRASH("Failed to get NS_OS_TEMP_DIR");
- }
-
- nsAutoCString tempDirPath;
- tempDir->Normalize();
- rv = tempDir->GetNativePath(tempDirPath);
- if (NS_FAILED(rv)) {
- MOZ_CRASH("Failed to get NS_OS_TEMP_DIR path");
- }
-
- nsCOMPtr<nsIFile> profileDir;
- ContentChild::GetSingleton()->GetProfileDir(getter_AddRefs(profileDir));
- nsCString profileDirPath;
- if (profileDir) {
- rv = profileDir->GetNativePath(profileDirPath);
- if (NS_FAILED(rv) || profileDirPath.IsEmpty()) {
- MOZ_CRASH("Failed to get profile path");
- }
- }
-
- MacSandboxInfo info;
- info.type = MacSandboxType_Content;
- info.level = info.level = sandboxLevel;
- info.appPath.assign(appPath.get());
- info.appBinaryPath.assign(appBinaryPath.get());
- info.appDir.assign(appDir.get());
- info.appTempDir.assign(tempDirPath.get());
-
- if (profileDir) {
- info.hasSandboxedProfile = true;
- info.profileDir.assign(profileDirPath.get());
- } else {
- info.hasSandboxedProfile = false;
- }
-
- std::string err;
- if (!mozilla::StartMacSandbox(info, err)) {
- NS_WARNING(err.c_str());
- MOZ_CRASH("sandbox_init() failed");
- }
-
- return true;
-}
-#endif
-
bool
ContentChild::RecvSetProcessSandbox(const MaybeFileDesc& aBroker)
{
// We may want to move the sandbox initialization somewhere else
// at some point; see bug 880808.
-#if defined(MOZ_CONTENT_SANDBOX)
- bool sandboxEnabled = true;
-#if defined(XP_LINUX)
-#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 19
- // For B2G >= KitKat, sandboxing is mandatory; this has already
- // been enforced by ContentParent::StartUp().
- MOZ_ASSERT(SandboxInfo::Get().CanSandboxContent());
-#else
- // Otherwise, sandboxing is best-effort.
- if (!SandboxInfo::Get().CanSandboxContent()) {
- sandboxEnabled = false;
- } else {
- // This triggers the initialization of cubeb, which needs to happen
- // before seccomp is enabled (Bug 1259508). It also increases the startup
- // time of the content process, because cubeb is usually initialized
- // when it is actually needed. This call here is no longer required
- // once Bug 1104619 (remoting audio) is resolved.
- Unused << CubebUtils::GetCubebContext();
- }
-
-#endif /* MOZ_WIDGET_GONK && ANDROID_VERSION >= 19 */
- if (sandboxEnabled) {
- int brokerFd = -1;
- if (aBroker.type() == MaybeFileDesc::TFileDescriptor) {
- auto fd = aBroker.get_FileDescriptor().ClonePlatformHandle();
- brokerFd = fd.release();
- // brokerFd < 0 means to allow direct filesystem access, so
- // make absolutely sure that doesn't happen if the parent
- // didn't intend it.
- MOZ_RELEASE_ASSERT(brokerFd >= 0);
- }
- sandboxEnabled = SetContentProcessSandbox(brokerFd);
- }
-#elif defined(XP_WIN)
- mozilla::SandboxTarget::Instance()->StartSandbox();
-#elif defined(XP_MACOSX)
- sandboxEnabled = StartMacOSContentSandbox();
-#endif
-
-#endif /* MOZ_CONTENT_SANDBOX */
-
return true;
}
@@ -1453,15 +1240,6 @@ ContentChild::RecvNotifyLayerAllocated(const dom::TabId& aTabId, const uint64_t&
bool
ContentChild::RecvSpeakerManagerNotify()
{
-#ifdef MOZ_WIDGET_GONK
- // Only notify the process which has the SpeakerManager instance.
- RefPtr<SpeakerManagerService> service =
- SpeakerManagerService::GetSpeakerManagerService();
- if (service) {
- service->Notify();
- }
- return true;
-#endif
return false;
}
@@ -2480,12 +2258,6 @@ ContentChild::RecvLastPrivateDocShellDestroyed()
bool
ContentChild::RecvVolumes(nsTArray<VolumeInfo>&& aVolumes)
{
-#ifdef MOZ_WIDGET_GONK
- RefPtr<nsVolumeService> vs = nsVolumeService::GetSingleton();
- if (vs) {
- vs->RecvVolumesFromParent(aVolumes);
- }
-#endif
return true;
}
@@ -2502,17 +2274,6 @@ ContentChild::RecvFileSystemUpdate(const nsString& aFsName,
const bool& aIsRemovable,
const bool& aIsHotSwappable)
{
-#ifdef MOZ_WIDGET_GONK
- RefPtr<nsVolume> volume = new nsVolume(aFsName, aVolumeName, aState,
- aMountGeneration, aIsMediaPresent,
- aIsSharing, aIsFormatting, aIsFake,
- aIsUnmounting, aIsRemovable, aIsHotSwappable);
-
- RefPtr<nsVolumeService> vs = nsVolumeService::GetSingleton();
- if (vs) {
- vs->UpdateVolume(volume);
- }
-#else
// Remove warnings about unused arguments
Unused << aFsName;
Unused << aVolumeName;
@@ -2525,22 +2286,15 @@ ContentChild::RecvFileSystemUpdate(const nsString& aFsName,
Unused << aIsUnmounting;
Unused << aIsRemovable;
Unused << aIsHotSwappable;
-#endif
+
return true;
}
bool
ContentChild::RecvVolumeRemoved(const nsString& aFsName)
{
-#ifdef MOZ_WIDGET_GONK
- RefPtr<nsVolumeService> vs = nsVolumeService::GetSingleton();
- if (vs) {
- vs->RemoveVolumeByName(aFsName);
- }
-#else
// Remove warnings about unused arguments
Unused << aFsName;
-#endif
return true;
}
diff --git a/dom/ipc/ContentChild.h b/dom/ipc/ContentChild.h
index cb718aff9..c78f951f0 100644
--- a/dom/ipc/ContentChild.h
+++ b/dom/ipc/ContentChild.h
@@ -21,10 +21,6 @@
#include "nsWeakPtr.h"
#include "nsIWindowProvider.h"
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
-#include "nsIFile.h"
-#endif
-
struct ChromePackage;
class nsIObserver;
struct SubstitutionMapping;
@@ -118,19 +114,6 @@ public:
void GetProcessName(nsACString& aName) const;
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
- void GetProfileDir(nsIFile** aProfileDir) const
- {
- *aProfileDir = mProfileDir;
- NS_IF_ADDREF(*aProfileDir);
- }
-
- void SetProfileDir(nsIFile* aProfileDir)
- {
- mProfileDir = aProfileDir;
- }
-#endif
-
bool IsAlive() const;
bool IsShuttingDown() const;
@@ -679,10 +662,6 @@ private:
nsCOMPtr<nsIDomainPolicy> mPolicy;
nsCOMPtr<nsITimer> mForceKillTimer;
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
- nsCOMPtr<nsIFile> mProfileDir;
-#endif
-
// Hashtable to keep track of the pending GetFilesHelper objects.
// This GetFilesHelperChild objects are removed when RecvGetFilesResponse is
// received.
diff --git a/dom/ipc/ContentParent.cpp b/dom/ipc/ContentParent.cpp
index 286f1d851..8b9ab4442 100644
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -16,11 +16,6 @@
# include <sys/resource.h>
#endif
-#ifdef MOZ_WIDGET_GONK
-#include <sys/types.h>
-#include <sys/wait.h>
-#endif
-
#include "chrome/common/process_watcher.h"
#include "mozilla/a11y/PDocAccessible.h"
@@ -210,14 +205,6 @@
# include "AndroidBridge.h"
#endif
-#ifdef MOZ_WIDGET_GONK
-#include "nsIVolume.h"
-#include "nsVolumeService.h"
-#include "nsIVolumeService.h"
-#include "SpeakerManagerService.h"
-using namespace mozilla::system;
-#endif
-
#ifdef MOZ_WIDGET_GTK
#include <gdk/gdk.h>
#endif
@@ -230,12 +217,6 @@ using namespace mozilla::system;
#include "mozilla/dom/SpeechSynthesisParent.h"
#endif
-#if defined(MOZ_CONTENT_SANDBOX) && defined(XP_LINUX)
-#include "mozilla/SandboxInfo.h"
-#include "mozilla/SandboxBroker.h"
-#include "mozilla/SandboxBrokerPolicyFactory.h"
-#endif
-
#ifdef MOZ_TOOLKIT_SEARCH
#include "nsIBrowserSearchService.h"
#endif
@@ -503,9 +484,6 @@ nsTArray<ContentParent*>* ContentParent::sNonAppContentParents;
nsTArray<ContentParent*>* ContentParent::sLargeAllocationContentParents;
nsTArray<ContentParent*>* ContentParent::sPrivateContent;
StaticAutoPtr<LinkedList<ContentParent> > ContentParent::sContentParents;
-#if defined(XP_LINUX) && defined(MOZ_CONTENT_SANDBOX)
-UniquePtr<SandboxBrokerPolicyFactory> ContentParent::sSandboxBrokerPolicyFactory;
-#endif
// This is true when subprocess launching is enabled. This is the
// case between StartUp() and ShutDown() or JoinAllSubprocesses().
@@ -535,11 +513,6 @@ static const char* sObserverTopics[] = {
"child-mmu-request",
"last-pb-context-exited",
"file-watcher-update",
-#ifdef MOZ_WIDGET_GONK
- NS_VOLUME_STATE_CHANGED,
- NS_VOLUME_REMOVED,
- "phone-state-changed",
-#endif
#ifdef ACCESSIBILITY
"a11y-init-or-shutdown",
#endif
@@ -637,18 +610,6 @@ ContentParent::StartUp()
return;
}
-#if defined(MOZ_CONTENT_SANDBOX) && defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 19
- // Require sandboxing on B2G >= KitKat. This condition must stay
- // in sync with ContentChild::RecvSetProcessSandbox.
- if (!SandboxInfo::Get().CanSandboxContent()) {
- // MOZ_CRASH strings are only for debug builds; make sure the
- // message is clear on non-debug builds as well:
- printf_stderr("Sandboxing support is required on this platform. "
- "Recompile kernel with CONFIG_SECCOMP_FILTER=y\n");
- MOZ_CRASH("Sandboxing support is required on this platform.");
- }
-#endif
-
// Note: This reporter measures all ContentParents.
RegisterStrongMemoryReporter(new ContentParentsMemoryReporter());
@@ -662,10 +623,6 @@ ContentParent::StartUp()
PreallocatedProcessManager::AllocateAfterDelay();
sDisableUnsafeCPOWWarnings = PR_GetEnv("DISABLE_UNSAFE_CPOW_WARNINGS");
-
-#if defined(XP_LINUX) && defined(MOZ_CONTENT_SANDBOX)
- sSandboxBrokerPolicyFactory = MakeUnique<SandboxBrokerPolicyFactory>();
-#endif
}
/*static*/ void
@@ -674,10 +631,6 @@ ContentParent::ShutDown()
// No-op for now. We rely on normal process shutdown and
// ClearOnShutdown() to clean up our state.
sCanLaunchSubprocesses = false;
-
-#if defined(XP_LINUX) && defined(MOZ_CONTENT_SANDBOX)
- sSandboxBrokerPolicyFactory = nullptr;
-#endif
}
/*static*/ void
@@ -1384,14 +1337,6 @@ ContentParent::ForwardKnownInfo()
if (!mMetamorphosed) {
return;
}
-#ifdef MOZ_WIDGET_GONK
- InfallibleTArray<VolumeInfo> volumeInfo;
- RefPtr<nsVolumeService> vs = nsVolumeService::GetSingleton();
- if (vs) {
- vs->GetVolumesForIPC(&volumeInfo);
- Unused << SendVolumes(volumeInfo);
- }
-#endif /* MOZ_WIDGET_GONK */
}
namespace {
@@ -1439,23 +1384,6 @@ bool
ContentParent::SetPriorityAndCheckIsAlive(ProcessPriority aPriority)
{
ProcessPriorityManager::SetProcessPriority(this, aPriority);
-
- // Now that we've set this process's priority, check whether the process is
- // still alive. Hopefully we've set the priority to FOREGROUND*, so the
- // process won't unexpectedly crash after this point!
- //
- // Bug 943174: use waitid() with WNOWAIT so that, if the process
- // did exit, we won't consume its zombie and confuse the
- // GeckoChildProcessHost dtor.
-#ifdef MOZ_WIDGET_GONK
- siginfo_t info;
- info.si_pid = 0;
- if (waitid(P_PID, Pid(), &info, WNOWAIT | WNOHANG | WEXITED) == 0
- && info.si_pid != 0) {
- return false;
- }
-#endif
-
return true;
}
@@ -2106,7 +2034,7 @@ ContentParent::ContentParent(mozIApplication* aApp,
// PID along with the warning.
nsDebugImpl::SetMultiprocessMode("Parent");
-#if defined(XP_WIN) && !defined(MOZ_B2G)
+#if defined(XP_WIN)
// Request Windows message deferral behavior on our side of the PContent
// channel. Generally only applies to the situation where we get caught in
// a deadlock with the plugin process when sending CPOWs.
@@ -2244,37 +2172,6 @@ ContentParent::InitInternal(ProcessPriority aInitialPriority,
}
}
-#ifdef MOZ_CONTENT_SANDBOX
- bool shouldSandbox = true;
- MaybeFileDesc brokerFd = void_t();
-#ifdef XP_LINUX
- // XXX: Checking the pref here makes it possible to enable/disable sandboxing
- // during an active session. Currently the pref is only used for testing
- // purpose. If the decision is made to permanently rely on the pref, this
- // should be changed so that it is required to restart firefox for the change
- // of value to take effect.
- shouldSandbox = (Preferences::GetInt("security.sandbox.content.level") > 0) &&
- !PR_GetEnv("MOZ_DISABLE_CONTENT_SANDBOX");
-
- if (shouldSandbox) {
- MOZ_ASSERT(!mSandboxBroker);
- UniquePtr<SandboxBroker::Policy> policy =
- sSandboxBrokerPolicyFactory->GetContentPolicy(Pid());
- if (policy) {
- brokerFd = FileDescriptor();
- mSandboxBroker = SandboxBroker::Create(Move(policy), Pid(), brokerFd);
- if (!mSandboxBroker) {
- KillHard("SandboxBroker::Create failed");
- return;
- }
- MOZ_ASSERT(static_cast<const FileDescriptor&>(brokerFd).IsValid());
- }
- }
-#endif
- if (shouldSandbox && !SendSetProcessSandbox(brokerFd)) {
- KillHard("SandboxInitFailed");
- }
-#endif
#if defined(XP_WIN)
// Send the info needed to join the browser process's audio session.
nsID id;
@@ -2746,50 +2643,6 @@ ContentParent::Observe(nsISupports* aSubject,
else if (!strcmp(aTopic, "last-pb-context-exited")) {
Unused << SendLastPrivateDocShellDestroyed();
}
-#ifdef MOZ_WIDGET_GONK
- else if(!strcmp(aTopic, NS_VOLUME_STATE_CHANGED)) {
- nsCOMPtr<nsIVolume> vol = do_QueryInterface(aSubject);
- if (!vol) {
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- nsString volName;
- nsString mountPoint;
- int32_t state;
- int32_t mountGeneration;
- bool isMediaPresent;
- bool isSharing;
- bool isFormatting;
- bool isFake;
- bool isUnmounting;
- bool isRemovable;
- bool isHotSwappable;
-
- vol->GetName(volName);
- vol->GetMountPoint(mountPoint);
- vol->GetState(&state);
- vol->GetMountGeneration(&mountGeneration);
- vol->GetIsMediaPresent(&isMediaPresent);
- vol->GetIsSharing(&isSharing);
- vol->GetIsFormatting(&isFormatting);
- vol->GetIsFake(&isFake);
- vol->GetIsUnmounting(&isUnmounting);
- vol->GetIsRemovable(&isRemovable);
- vol->GetIsHotSwappable(&isHotSwappable);
-
- Unused << SendFileSystemUpdate(volName, mountPoint, state,
- mountGeneration, isMediaPresent,
- isSharing, isFormatting, isFake,
- isUnmounting, isRemovable, isHotSwappable);
- } else if (!strcmp(aTopic, "phone-state-changed")) {
- nsString state(aData);
- Unused << SendNotifyPhoneStateChange(state);
- }
- else if(!strcmp(aTopic, NS_VOLUME_REMOVED)) {
- nsString volName(aData);
- Unused << SendVolumeRemoved(volName);
- }
-#endif
#ifdef ACCESSIBILITY
else if (aData && !strcmp(aTopic, "a11y-init-or-shutdown")) {
if (*aData == '1') {
@@ -3458,29 +3311,12 @@ ContentParent::RecvPSpeechSynthesisConstructor(PSpeechSynthesisParent* aActor)
bool
ContentParent::RecvSpeakerManagerGetSpeakerStatus(bool* aValue)
{
-#ifdef MOZ_WIDGET_GONK
- *aValue = false;
- RefPtr<SpeakerManagerService> service =
- SpeakerManagerService::GetOrCreateSpeakerManagerService();
- MOZ_ASSERT(service);
-
- *aValue = service->GetSpeakerStatus();
- return true;
-#endif
return false;
}
bool
ContentParent::RecvSpeakerManagerForceSpeaker(const bool& aEnable)
{
-#ifdef MOZ_WIDGET_GONK
- RefPtr<SpeakerManagerService> service =
- SpeakerManagerService::GetOrCreateSpeakerManagerService();
- MOZ_ASSERT(service);
- service->ForceSpeaker(aEnable, mChildID);
-
- return true;
-#endif
return false;
}
@@ -4036,49 +3872,22 @@ bool
ContentParent::RecvCreateFakeVolume(const nsString& fsName,
const nsString& mountPoint)
{
-#ifdef MOZ_WIDGET_GONK
- nsresult rv;
- nsCOMPtr<nsIVolumeService> vs = do_GetService(NS_VOLUMESERVICE_CONTRACTID, &rv);
- if (vs) {
- vs->CreateFakeVolume(fsName, mountPoint);
- }
- return true;
-#else
- NS_WARNING("ContentParent::RecvCreateFakeVolume shouldn't be called when MOZ_WIDGET_GONK is not defined");
+ NS_WARNING("ContentParent::RecvCreateFakeVolume shouldn't be called");
return false;
-#endif
}
bool
ContentParent::RecvSetFakeVolumeState(const nsString& fsName, const int32_t& fsState)
{
-#ifdef MOZ_WIDGET_GONK
- nsresult rv;
- nsCOMPtr<nsIVolumeService> vs = do_GetService(NS_VOLUMESERVICE_CONTRACTID, &rv);
- if (vs) {
- vs->SetFakeVolumeState(fsName, fsState);
- }
- return true;
-#else
- NS_WARNING("ContentParent::RecvSetFakeVolumeState shouldn't be called when MOZ_WIDGET_GONK is not defined");
+ NS_WARNING("ContentParent::RecvSetFakeVolumeState shouldn't be called");
return false;
-#endif
}
bool
ContentParent::RecvRemoveFakeVolume(const nsString& fsName)
{
-#ifdef MOZ_WIDGET_GONK
- nsresult rv;
- nsCOMPtr<nsIVolumeService> vs = do_GetService(NS_VOLUMESERVICE_CONTRACTID, &rv);
- if (vs) {
- vs->RemoveFakeVolume(fsName);
- }
- return true;
-#else
- NS_WARNING("ContentParent::RecvRemoveFakeVolume shouldn't be called when MOZ_WIDGET_GONK is not defined");
+ NS_WARNING("ContentParent::RecvRemoveFakeVolume shouldn't be called");
return false;
-#endif
}
bool
diff --git a/dom/ipc/ContentParent.h b/dom/ipc/ContentParent.h
index a3750de1a..3f74b10e1 100644
--- a/dom/ipc/ContentParent.h
+++ b/dom/ipc/ContentParent.h
@@ -46,11 +46,6 @@ class PRemoteSpellcheckEngineParent;
class ProfileGatherer;
#endif
-#if defined(XP_LINUX) && defined(MOZ_CONTENT_SANDBOX)
-class SandboxBroker;
-class SandboxBrokerPolicyFactory;
-#endif
-
namespace embedding {
class PrintingParent;
}
@@ -1152,12 +1147,6 @@ private:
UniquePtr<gfx::DriverCrashGuard> mDriverCrashGuard;
-#if defined(XP_LINUX) && defined(MOZ_CONTENT_SANDBOX)
- mozilla::UniquePtr<SandboxBroker> mSandboxBroker;
- static mozilla::UniquePtr<SandboxBrokerPolicyFactory>
- sSandboxBrokerPolicyFactory;
-#endif
-
#ifdef NS_PRINTING
RefPtr<embedding::PrintingParent> mPrintingParent;
#endif
diff --git a/dom/ipc/ContentProcess.cpp b/dom/ipc/ContentProcess.cpp
index 2413d8808..986617f55 100644
--- a/dom/ipc/ContentProcess.cpp
+++ b/dom/ipc/ContentProcess.cpp
@@ -8,122 +8,17 @@
#include "ContentProcess.h"
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
-#include <stdlib.h>
-#endif
-
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
-#include "mozilla/Preferences.h"
-#include "nsAppDirectoryServiceDefs.h"
-#include "nsDirectoryService.h"
-#include "nsDirectoryServiceDefs.h"
-#endif
-
using mozilla::ipc::IOThreadChild;
namespace mozilla {
namespace dom {
-#if defined(XP_WIN) && defined(MOZ_CONTENT_SANDBOX)
-static bool
-IsSandboxTempDirRequired()
-{
- // On Windows, a sandbox-writable temp directory is only used
- // when sandbox pref level >= 1.
- return Preferences::GetInt("security.sandbox.content.level") >= 1;
-}
-
-static void
-SetTmpEnvironmentVariable(nsIFile* aValue)
-{
- // Save the TMP environment variable so that is is picked up by GetTempPath().
- // Note that we specifically write to the TMP variable, as that is the first
- // variable that is checked by GetTempPath() to determine its output.
- nsAutoString fullTmpPath;
- nsresult rv = aValue->GetPath(fullTmpPath);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
- Unused << NS_WARN_IF(!SetEnvironmentVariableW(L"TMP", fullTmpPath.get()));
- // We also set TEMP in case there is naughty third-party code that is
- // referencing the environment variable directly.
- Unused << NS_WARN_IF(!SetEnvironmentVariableW(L"TEMP", fullTmpPath.get()));
-}
-#endif
-
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
-static bool
-IsSandboxTempDirRequired()
-{
- // On OSX, use the sandbox-writable temp when the pref level >= 1.
- return (Preferences::GetInt("security.sandbox.content.level") >= 1);
-}
-
-static void
-SetTmpEnvironmentVariable(nsIFile* aValue)
-{
- nsAutoCString fullTmpPath;
- nsresult rv = aValue->GetNativePath(fullTmpPath);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
- Unused << NS_WARN_IF(setenv("TMPDIR", fullTmpPath.get(), 1) != 0);
-}
-#endif
-
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
-static void
-SetUpSandboxEnvironment()
-{
- MOZ_ASSERT(nsDirectoryService::gService,
- "SetUpSandboxEnvironment relies on nsDirectoryService being initialized");
-
- if (!IsSandboxTempDirRequired()) {
- return;
- }
-
- nsCOMPtr<nsIFile> sandboxedContentTemp;
- nsresult rv =
- nsDirectoryService::gService->Get(NS_APP_CONTENT_PROCESS_TEMP_DIR,
- NS_GET_IID(nsIFile),
- getter_AddRefs(sandboxedContentTemp));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- // Change the gecko defined temp directory to our sandbox-writable one.
- // Undefine returns a failure if the property is not already set.
- Unused << nsDirectoryService::gService->Undefine(NS_OS_TEMP_DIR);
- rv = nsDirectoryService::gService->Set(NS_OS_TEMP_DIR, sandboxedContentTemp);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- SetTmpEnvironmentVariable(sandboxedContentTemp);
-}
-#endif
-
void
ContentProcess::SetAppDir(const nsACString& aPath)
{
mXREEmbed.SetAppDir(aPath);
}
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
-void
-ContentProcess::SetProfile(const nsACString& aProfile)
-{
- bool flag;
- nsresult rv =
- XRE_GetFileFromPath(aProfile.BeginReading(), getter_AddRefs(mProfileDir));
- if (NS_FAILED(rv) ||
- NS_FAILED(mProfileDir->Exists(&flag)) || !flag) {
- NS_WARNING("Invalid profile directory passed to content process.");
- mProfileDir = nullptr;
- }
-}
-#endif
-
bool
ContentProcess::Init()
{
@@ -134,14 +29,6 @@ ContentProcess::Init()
mContent.InitXPCOM();
mContent.InitGraphicsDeviceData();
-#if (defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
- mContent.SetProfileDir(mProfileDir);
-#endif
-
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
- SetUpSandboxEnvironment();
-#endif
-
return true;
}
diff --git a/dom/ipc/ContentProcess.h b/dom/ipc/ContentProcess.h
index bf9968f8c..3950368bd 100644
--- a/dom/ipc/ContentProcess.h
+++ b/dom/ipc/ContentProcess.h
@@ -39,18 +39,10 @@ public:
void SetAppDir(const nsACString& aPath);
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
- void SetProfile(const nsACString& aProfile);
-#endif
-
private:
ContentChild mContent;
mozilla::ipc::ScopedXREEmbed mXREEmbed;
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
- nsCOMPtr<nsIFile> mProfileDir;
-#endif
-
#if defined(XP_WIN)
// This object initializes and configures COM.
mozilla::mscom::MainThreadRuntime mCOMRuntime;
diff --git a/dom/ipc/TabContext.cpp b/dom/ipc/TabContext.cpp
index b36dbc5eb..362bce3a4 100644
--- a/dom/ipc/TabContext.cpp
+++ b/dom/ipc/TabContext.cpp
@@ -358,12 +358,7 @@ MaybeInvalidTabContext::MaybeInvalidTabContext(const IPCTabContext& aParams)
case IPCTabContext::TUnsafeIPCTabContext: {
// XXXcatalinb: This used *only* by ServiceWorkerClients::OpenWindow.
// It is meant as a temporary solution until service workers can
- // provide a TabChild equivalent. Don't allow this on b2g since
- // it might be used to escalate privileges.
-#ifdef MOZ_B2G
- mInvalidReason = "ServiceWorkerClients::OpenWindow is not supported.";
- return;
-#endif
+ // provide a TabChild equivalent.
if (!Preferences::GetBool("dom.serviceWorkers.enabled", false)) {
mInvalidReason = "ServiceWorkers should be enabled.";
return;
diff --git a/dom/ipc/moz.build b/dom/ipc/moz.build
index 71d193d44..c34ac5d48 100644
--- a/dom/ipc/moz.build
+++ b/dom/ipc/moz.build
@@ -112,11 +112,6 @@ if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_TARGET'] == 'Darwin':
'mozsandbox',
]
-if CONFIG['MOZ_CONTENT_SANDBOX'] and CONFIG['OS_ARCH'] == 'Linux':
- USE_LIBS += [
- 'mozsandbox',
- ]
-
LOCAL_INCLUDES += [
'/caps',
'/chrome',
@@ -145,12 +140,6 @@ LOCAL_INCLUDES += [
'/xpcom/threads',
]
-if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_ARCH'] == 'WINNT':
- LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
- ]
-
if CONFIG['OS_ARCH'] != 'WINNT':
LOCAL_INCLUDES += [
'/modules/libjar',
@@ -158,7 +147,7 @@ if CONFIG['OS_ARCH'] != 'WINNT':
DEFINES['BIN_SUFFIX'] = '"%s"' % CONFIG['BIN_SUFFIX']
-if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gtk2', 'gonk'):
+if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gtk2'):
DEFINES['MOZ_ENABLE_FREETYPE'] = True
if CONFIG['MOZ_TOOLKIT_SEARCH']:
diff --git a/dom/ipc/tests/test_cpow_cookies.html b/dom/ipc/tests/test_cpow_cookies.html
index 1e55d3878..d8f87cced 100644
--- a/dom/ipc/tests/test_cpow_cookies.html
+++ b/dom/ipc/tests/test_cpow_cookies.html
@@ -81,7 +81,8 @@
["dom.ipc.browser_frames.oop_by_default", true],
["dom.mozBrowserFramesEnabled", true],
["network.disable.ipc.security", true],
- ["browser.pagethumbnails.capturing_disabled", true]
+ ["browser.pagethumbnails.capturing_disabled", true],
+ ["security.data_uri.block_toplevel_data_uri_navigations", false],
]
}, runTests);
});
diff --git a/dom/jsurl/nsJSProtocolHandler.cpp b/dom/jsurl/nsJSProtocolHandler.cpp
index cdb63f890..90171db10 100644
--- a/dom/jsurl/nsJSProtocolHandler.cpp
+++ b/dom/jsurl/nsJSProtocolHandler.cpp
@@ -36,7 +36,6 @@
#include "nsIContentViewer.h"
#include "nsIXPConnect.h"
#include "nsContentUtils.h"
-#include "nsNullPrincipal.h"
#include "nsJSUtils.h"
#include "nsThreadUtils.h"
#include "nsIScriptChannel.h"
@@ -336,7 +335,7 @@ public:
NS_FORWARD_SAFE_NSIPROPERTYBAG(mPropertyBag)
NS_FORWARD_SAFE_NSIPROPERTYBAG2(mPropertyBag)
- nsresult Init(nsIURI *aURI);
+ nsresult Init(nsIURI *aURI, nsILoadInfo* aLoadInfo);
// Actually evaluate the script.
void EvaluateScript();
@@ -354,17 +353,16 @@ protected:
nsCOMPtr<nsIChannel> mStreamChannel;
nsCOMPtr<nsIPropertyBag2> mPropertyBag;
nsCOMPtr<nsIStreamListener> mListener; // Our final listener
- nsCOMPtr<nsISupports> mContext; // The context passed to AsyncOpen
nsCOMPtr<nsPIDOMWindowInner> mOriginalInnerWindow; // The inner window our load
// started against.
- // If we blocked onload on a document in AsyncOpen, this is the document we
+ // If we blocked onload on a document in AsyncOpen2, this is the document we
// did it on.
nsCOMPtr<nsIDocument> mDocumentOnloadBlockedOn;
nsresult mStatus; // Our status
nsLoadFlags mLoadFlags;
- nsLoadFlags mActualLoadFlags; // See AsyncOpen
+ nsLoadFlags mActualLoadFlags; // See AsyncOpen2
RefPtr<nsJSThunk> mIOThunk;
PopupControlState mPopupState;
@@ -404,7 +402,7 @@ nsresult nsJSChannel::StopAll()
return rv;
}
-nsresult nsJSChannel::Init(nsIURI *aURI)
+nsresult nsJSChannel::Init(nsIURI* aURI, nsILoadInfo* aLoadInfo)
{
RefPtr<nsJSURI> jsURI;
nsresult rv = aURI->QueryInterface(kJSURICID,
@@ -418,21 +416,13 @@ nsresult nsJSChannel::Init(nsIURI *aURI)
// Remember, until AsyncOpen is called, the script will not be evaluated
// and the underlying Input Stream will not be created...
nsCOMPtr<nsIChannel> channel;
-
- nsCOMPtr<nsIPrincipal> nullPrincipal = nsNullPrincipal::Create();
-
- // If the resultant script evaluation actually does return a value, we
- // treat it as html.
- // The following channel is never openend, so it does not matter what
- // securityFlags we pass; let's follow the principle of least privilege.
- rv = NS_NewInputStreamChannel(getter_AddRefs(channel),
- aURI,
- mIOThunk,
- nullPrincipal,
- nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED,
- nsIContentPolicy::TYPE_OTHER,
- NS_LITERAL_CSTRING("text/html"));
- if (NS_FAILED(rv)) return rv;
+ rv = NS_NewInputStreamChannelInternal(getter_AddRefs(channel),
+ aURI,
+ mIOThunk,
+ NS_LITERAL_CSTRING("text/html"),
+ EmptyCString(),
+ aLoadInfo);
+ NS_ENSURE_SUCCESS(rv, rv);
rv = mIOThunk->Init(aURI);
if (NS_SUCCEEDED(rv)) {
@@ -563,6 +553,7 @@ nsJSChannel::AsyncOpen(nsIStreamListener *aListener, nsISupports *aContext)
"security flags in loadInfo but asyncOpen2() not called");
}
#endif
+ MOZ_RELEASE_ASSERT(!aContext, "please call AsyncOpen2()");
NS_ENSURE_ARG(aListener);
@@ -584,7 +575,6 @@ nsJSChannel::AsyncOpen(nsIStreamListener *aListener, nsISupports *aContext)
}
mListener = aListener;
- mContext = aContext;
mIsActive = true;
@@ -655,7 +645,7 @@ nsJSChannel::AsyncOpen(nsIStreamListener *aListener, nsISupports *aContext)
return mStatus;
}
- // We're returning success from asyncOpen(), but we didn't open a
+ // We're returning success from asyncOpen2(), but we didn't open a
// stream channel. We'll have to notify ourselves, but make sure to do
// it asynchronously.
method = &nsJSChannel::NotifyListener;
@@ -772,7 +762,7 @@ nsJSChannel::EvaluateScript()
return;
}
- mStatus = mStreamChannel->AsyncOpen(this, mContext);
+ mStatus = mStreamChannel->AsyncOpen2(this);
if (NS_SUCCEEDED(mStatus)) {
// mStreamChannel will call OnStartRequest and OnStopRequest on
// us, so we'll be sure to call them on our listener.
@@ -800,8 +790,8 @@ nsJSChannel::EvaluateScript()
void
nsJSChannel::NotifyListener()
{
- mListener->OnStartRequest(this, mContext);
- mListener->OnStopRequest(this, mContext, mStatus);
+ mListener->OnStartRequest(this, nullptr);
+ mListener->OnStopRequest(this, nullptr, mStatus);
CleanupStrongRefs();
}
@@ -810,7 +800,6 @@ void
nsJSChannel::CleanupStrongRefs()
{
mListener = nullptr;
- mContext = nullptr;
mOriginalInnerWindow = nullptr;
if (mDocumentOnloadBlockedOn) {
mDocumentOnloadBlockedOn->UnblockOnload(false);
@@ -1240,11 +1229,7 @@ nsJSProtocolHandler::NewChannel2(nsIURI* uri,
return NS_ERROR_OUT_OF_MEMORY;
}
- rv = channel->Init(uri);
- NS_ENSURE_SUCCESS(rv, rv);
-
- // set the loadInfo on the new channel
- rv = channel->SetLoadInfo(aLoadInfo);
+ rv = channel->Init(uri, aLoadInfo);
NS_ENSURE_SUCCESS(rv, rv);
if (NS_SUCCEEDED(rv)) {
diff --git a/dom/media/AudioStream.cpp b/dom/media/AudioStream.cpp
index 82ae3ee86..54cf7b965 100644
--- a/dom/media/AudioStream.cpp
+++ b/dom/media/AudioStream.cpp
@@ -333,11 +333,7 @@ AudioStream::Init(uint32_t aNumChannels, uint32_t aRate,
params.rate = aRate;
params.channels = mOutChannels;
#if defined(__ANDROID__)
-#if defined(MOZ_B2G)
- params.stream_type = CubebUtils::ConvertChannelToCubebType(aAudioChannel);
-#else
params.stream_type = CUBEB_STREAM_TYPE_MUSIC;
-#endif
if (params.stream_type == CUBEB_STREAM_TYPE_MAX) {
return NS_ERROR_INVALID_ARG;
diff --git a/dom/media/Benchmark.cpp b/dom/media/Benchmark.cpp
index 1ba6e561c..fdbedeca5 100644
--- a/dom/media/Benchmark.cpp
+++ b/dom/media/Benchmark.cpp
@@ -22,7 +22,7 @@ namespace mozilla {
// Update this version number to force re-running the benchmark. Such as when
// an improvement to FFVP9 or LIBVPX is deemed worthwhile.
-const uint32_t VP9Benchmark::sBenchmarkVersionID = 2;
+const uint32_t VP9Benchmark::sBenchmarkVersionID = 3;
const char* VP9Benchmark::sBenchmarkFpsPref = "media.benchmark.vp9.fps";
const char* VP9Benchmark::sBenchmarkFpsVersionCheck = "media.benchmark.vp9.versioncheck";
diff --git a/dom/media/CubebUtils.cpp b/dom/media/CubebUtils.cpp
index d1b4bae99..fe94264ee 100644
--- a/dom/media/CubebUtils.cpp
+++ b/dom/media/CubebUtils.cpp
@@ -342,33 +342,6 @@ uint32_t MaxNumberOfChannels()
return 0;
}
-#if defined(__ANDROID__) && defined(MOZ_B2G)
-cubeb_stream_type ConvertChannelToCubebType(dom::AudioChannel aChannel)
-{
- switch(aChannel) {
- case dom::AudioChannel::Normal:
- /* FALLTHROUGH */
- case dom::AudioChannel::Content:
- return CUBEB_STREAM_TYPE_MUSIC;
- case dom::AudioChannel::Notification:
- return CUBEB_STREAM_TYPE_NOTIFICATION;
- case dom::AudioChannel::Alarm:
- return CUBEB_STREAM_TYPE_ALARM;
- case dom::AudioChannel::Telephony:
- return CUBEB_STREAM_TYPE_VOICE_CALL;
- case dom::AudioChannel::Ringer:
- return CUBEB_STREAM_TYPE_RING;
- case dom::AudioChannel::System:
- return CUBEB_STREAM_TYPE_SYSTEM;
- case dom::AudioChannel::Publicnotification:
- return CUBEB_STREAM_TYPE_SYSTEM_ENFORCED;
- default:
- NS_ERROR("The value of AudioChannel is invalid");
- return CUBEB_STREAM_TYPE_MAX;
- }
-}
-#endif
-
void GetCurrentBackend(nsAString& aBackend)
{
cubeb* cubebContext = GetCubebContext();
diff --git a/dom/media/CubebUtils.h b/dom/media/CubebUtils.h
index 171c244b7..fa5fc2294 100644
--- a/dom/media/CubebUtils.h
+++ b/dom/media/CubebUtils.h
@@ -40,9 +40,6 @@ void ReportCubebBackendUsed();
uint32_t GetCubebPlaybackLatencyInMilliseconds();
Maybe<uint32_t> GetCubebMSGLatencyInFrames();
bool CubebLatencyPrefSet();
-#if defined(__ANDROID__) && defined(MOZ_B2G)
-cubeb_stream_type ConvertChannelToCubebType(dom::AudioChannel aChannel);
-#endif
void GetCurrentBackend(nsAString& aBackend);
} // namespace CubebUtils
diff --git a/dom/media/DOMMediaStream.cpp b/dom/media/DOMMediaStream.cpp
index c1d451035..118d845a3 100755
--- a/dom/media/DOMMediaStream.cpp
+++ b/dom/media/DOMMediaStream.cpp
@@ -1505,20 +1505,6 @@ DOMAudioNodeMediaStream::CreateTrackUnionStreamAsInput(nsPIDOMWindowInner* aWind
DOMHwMediaStream::DOMHwMediaStream(nsPIDOMWindowInner* aWindow)
: DOMLocalMediaStream(aWindow, nullptr)
{
-#ifdef MOZ_WIDGET_GONK
- if (!mWindow) {
- NS_ERROR("Expected window here.");
- mPrincipalHandle = PRINCIPAL_HANDLE_NONE;
- return;
- }
- nsIDocument* doc = mWindow->GetExtantDoc();
- if (!doc) {
- NS_ERROR("Expected document here.");
- mPrincipalHandle = PRINCIPAL_HANDLE_NONE;
- return;
- }
- mPrincipalHandle = MakePrincipalHandle(doc->NodePrincipal());
-#endif
}
DOMHwMediaStream::~DOMHwMediaStream()
@@ -1545,31 +1531,8 @@ DOMHwMediaStream::Init(MediaStream* stream, OverlayImage* aImage)
{
SourceMediaStream* srcStream = stream->AsSourceStream();
-#ifdef MOZ_WIDGET_GONK
- if (aImage) {
- mOverlayImage = aImage;
- } else {
- Data imageData;
- imageData.mOverlayId = DEFAULT_IMAGE_ID;
- imageData.mSize.width = DEFAULT_IMAGE_WIDTH;
- imageData.mSize.height = DEFAULT_IMAGE_HEIGHT;
-
- mOverlayImage = new OverlayImage();
- mOverlayImage->SetData(imageData);
- }
-#endif
-
if (srcStream) {
VideoSegment segment;
-#ifdef MOZ_WIDGET_GONK
- const StreamTime delta = STREAM_TIME_MAX; // Because MediaStreamGraph will run out frames in non-autoplay mode,
- // we must give it bigger frame length to cover this situation.
-
- RefPtr<Image> image = static_cast<Image*>(mOverlayImage.get());
- mozilla::gfx::IntSize size = image->GetSize();
-
- segment.AppendFrame(image.forget(), delta, size, mPrincipalHandle);
-#endif
srcStream->AddTrack(TRACK_VIDEO_PRIMARY, 0, new VideoSegment());
srcStream->AppendToTrack(TRACK_VIDEO_PRIMARY, &segment);
srcStream->AdvanceKnownTracksTime(STREAM_TIME_MAX);
@@ -1579,30 +1542,13 @@ DOMHwMediaStream::Init(MediaStream* stream, OverlayImage* aImage)
int32_t
DOMHwMediaStream::RequestOverlayId()
{
-#ifdef MOZ_WIDGET_GONK
- return mOverlayImage->GetOverlayId();
-#else
+ /*** STUB ***/
return -1;
-#endif
}
void
DOMHwMediaStream::SetImageSize(uint32_t width, uint32_t height)
{
-#ifdef MOZ_WIDGET_GONK
- if (mOverlayImage->GetSidebandStream().IsValid()) {
- OverlayImage::SidebandStreamData imgData;
- imgData.mStream = mOverlayImage->GetSidebandStream();
- imgData.mSize = IntSize(width, height);
- mOverlayImage->SetData(imgData);
- } else {
- OverlayImage::Data imgData;
- imgData.mOverlayId = mOverlayImage->GetOverlayId();
- imgData.mSize = IntSize(width, height);
- mOverlayImage->SetData(imgData);
- }
-#endif
-
SourceMediaStream* srcStream = GetInputStream()->AsSourceStream();
StreamTracks::Track* track = srcStream->FindTrack(TRACK_VIDEO_PRIMARY);
@@ -1610,23 +1556,6 @@ DOMHwMediaStream::SetImageSize(uint32_t width, uint32_t height)
return;
}
-#ifdef MOZ_WIDGET_GONK
- // Clear the old segment.
- // Changing the existing content of segment is a Very BAD thing, and this way will
- // confuse consumers of MediaStreams.
- // It is only acceptable for DOMHwMediaStream
- // because DOMHwMediaStream doesn't have consumers of TV streams currently.
- track->GetSegment()->Clear();
-
- // Change the image size.
- const StreamTime delta = STREAM_TIME_MAX;
- RefPtr<Image> image = static_cast<Image*>(mOverlayImage.get());
- mozilla::gfx::IntSize size = image->GetSize();
- VideoSegment segment;
-
- segment.AppendFrame(image.forget(), delta, size, mPrincipalHandle);
- srcStream->AppendToTrack(TRACK_VIDEO_PRIMARY, &segment);
-#endif
}
void
@@ -1635,9 +1564,6 @@ DOMHwMediaStream::SetOverlayImage(OverlayImage* aImage)
if (!aImage) {
return;
}
-#ifdef MOZ_WIDGET_GONK
- mOverlayImage = aImage;
-#endif
SourceMediaStream* srcStream = GetInputStream()->AsSourceStream();
StreamTracks::Track* track = srcStream->FindTrack(TRACK_VIDEO_PRIMARY);
@@ -1646,34 +1572,10 @@ DOMHwMediaStream::SetOverlayImage(OverlayImage* aImage)
return;
}
-#ifdef MOZ_WIDGET_GONK
- // Clear the old segment.
- // Changing the existing content of segment is a Very BAD thing, and this way will
- // confuse consumers of MediaStreams.
- // It is only acceptable for DOMHwMediaStream
- // because DOMHwMediaStream doesn't have consumers of TV streams currently.
- track->GetSegment()->Clear();
-
- // Change the image size.
- const StreamTime delta = STREAM_TIME_MAX;
- RefPtr<Image> image = static_cast<Image*>(mOverlayImage.get());
- mozilla::gfx::IntSize size = image->GetSize();
- VideoSegment segment;
-
- segment.AppendFrame(image.forget(), delta, size, mPrincipalHandle);
- srcStream->AppendToTrack(TRACK_VIDEO_PRIMARY, &segment);
-#endif
}
void
DOMHwMediaStream::SetOverlayId(int32_t aOverlayId)
{
-#ifdef MOZ_WIDGET_GONK
- OverlayImage::Data imgData;
-
- imgData.mOverlayId = aOverlayId;
- imgData.mSize = mOverlayImage->GetSize();
-
- mOverlayImage->SetData(imgData);
-#endif
+ /*** STUB ***/
}
diff --git a/dom/media/DOMMediaStream.h b/dom/media/DOMMediaStream.h
index 12f3529a8..5618f8b00 100644
--- a/dom/media/DOMMediaStream.h
+++ b/dom/media/DOMMediaStream.h
@@ -833,9 +833,6 @@ class DOMHwMediaStream : public DOMLocalMediaStream
{
typedef mozilla::gfx::IntSize IntSize;
typedef layers::OverlayImage OverlayImage;
-#ifdef MOZ_WIDGET_GONK
- typedef layers::OverlayImage::Data Data;
-#endif
public:
explicit DOMHwMediaStream(nsPIDOMWindowInner* aWindow);
@@ -853,14 +850,6 @@ protected:
private:
void Init(MediaStream* aStream, OverlayImage* aImage);
-
-#ifdef MOZ_WIDGET_GONK
- const int DEFAULT_IMAGE_ID = 0x01;
- const int DEFAULT_IMAGE_WIDTH = 400;
- const int DEFAULT_IMAGE_HEIGHT = 300;
- RefPtr<OverlayImage> mOverlayImage;
- PrincipalHandle mPrincipalHandle;
-#endif
};
} // namespace mozilla
diff --git a/dom/media/GraphDriver.cpp b/dom/media/GraphDriver.cpp
index 40e3b72cf..cae15eb8c 100644
--- a/dom/media/GraphDriver.cpp
+++ b/dom/media/GraphDriver.cpp
@@ -640,11 +640,7 @@ AudioCallbackDriver::Init()
mSampleRate = output.rate = CubebUtils::PreferredSampleRate();
#if defined(__ANDROID__)
-#if defined(MOZ_B2G)
- output.stream_type = CubebUtils::ConvertChannelToCubebType(mAudioChannel);
-#else
output.stream_type = CUBEB_STREAM_TYPE_MUSIC;
-#endif
if (output.stream_type == CUBEB_STREAM_TYPE_MAX) {
NS_WARNING("Bad stream type");
return;
diff --git a/dom/media/MediaData.cpp b/dom/media/MediaData.cpp
index 4a52c22ae..94f5f32a0 100644
--- a/dom/media/MediaData.cpp
+++ b/dom/media/MediaData.cpp
@@ -9,9 +9,6 @@
#include "VideoUtils.h"
#include "ImageContainer.h"
-#ifdef MOZ_WIDGET_GONK
-#include <cutils/properties.h>
-#endif
#include <stdint.h>
namespace mozilla {
@@ -93,31 +90,6 @@ ValidatePlane(const VideoData::YCbCrBuffer::Plane& aPlane)
aPlane.mStride > 0 && aPlane.mWidth <= aPlane.mStride;
}
-#ifdef MOZ_WIDGET_GONK
-static bool
-IsYV12Format(const VideoData::YCbCrBuffer::Plane& aYPlane,
- const VideoData::YCbCrBuffer::Plane& aCbPlane,
- const VideoData::YCbCrBuffer::Plane& aCrPlane)
-{
- return
- aYPlane.mWidth % 2 == 0 &&
- aYPlane.mHeight % 2 == 0 &&
- aYPlane.mWidth / 2 == aCbPlane.mWidth &&
- aYPlane.mHeight / 2 == aCbPlane.mHeight &&
- aCbPlane.mWidth == aCrPlane.mWidth &&
- aCbPlane.mHeight == aCrPlane.mHeight;
-}
-
-static bool
-IsInEmulator()
-{
- char propQemu[PROPERTY_VALUE_MAX];
- property_get("ro.kernel.qemu", propQemu, "");
- return !strncmp(propQemu, "1", 1);
-}
-
-#endif
-
VideoData::VideoData(int64_t aOffset,
int64_t aTime,
int64_t aDuration,
@@ -310,19 +282,8 @@ VideoData::CreateAndCopyData(const VideoInfo& aInfo,
aTimecode,
aInfo.mDisplay,
0));
-#ifdef MOZ_WIDGET_GONK
- const YCbCrBuffer::Plane &Y = aBuffer.mPlanes[0];
- const YCbCrBuffer::Plane &Cb = aBuffer.mPlanes[1];
- const YCbCrBuffer::Plane &Cr = aBuffer.mPlanes[2];
-#endif
-
// Currently our decoder only knows how to output to ImageFormat::PLANAR_YCBCR
// format.
-#ifdef MOZ_WIDGET_GONK
- if (IsYV12Format(Y, Cb, Cr) && !IsInEmulator()) {
- v->mImage = new layers::GrallocImage();
- }
-#endif
if (!v->mImage) {
v->mImage = aContainer->CreatePlanarYCbCrImage();
}
@@ -341,20 +302,6 @@ VideoData::CreateAndCopyData(const VideoInfo& aInfo,
return nullptr;
}
-#ifdef MOZ_WIDGET_GONK
- if (!videoImage->IsValid() && IsYV12Format(Y, Cb, Cr)) {
- // Failed to allocate gralloc. Try fallback.
- v->mImage = aContainer->CreatePlanarYCbCrImage();
- if (!v->mImage) {
- return nullptr;
- }
- videoImage = v->mImage->AsPlanarYCbCrImage();
- if (!VideoData::SetVideoDataToImage(videoImage, aInfo, aBuffer, aPicture,
- true /* aCopyData */)) {
- return nullptr;
- }
- }
-#endif
return v.forget();
}
diff --git a/dom/media/MediaManager.cpp b/dom/media/MediaManager.cpp
index 97a6855d9..ba6b4cd47 100644
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -13,9 +13,6 @@
#include "nsArray.h"
#include "nsContentUtils.h"
#include "nsHashPropertyBag.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsIAudioManager.h"
-#endif
#include "nsIEventTarget.h"
#include "nsIUUIDGenerator.h"
#include "nsIScriptGlobalObject.h"
@@ -73,10 +70,6 @@
#include "browser_logging/WebRtcLog.h"
#endif
-#ifdef MOZ_B2G
-#include "MediaPermissionGonk.h"
-#endif
-
#if defined (XP_WIN)
#include "mozilla/WindowsVersion.h"
#include <winsock2.h>
@@ -1573,7 +1566,7 @@ private:
RefPtr<MediaManager> mManager; // get ref to this when creating the runnable
};
-#if defined(ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID)
class GetUserMediaRunnableWrapper : public Runnable
{
public:
@@ -1819,10 +1812,6 @@ MediaManager::Get() {
__LINE__,
NS_LITERAL_STRING("Media shutdown"));
MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
-#ifdef MOZ_B2G
- // Init MediaPermissionManager before sending out any permission requests.
- (void) MediaPermissionManager::GetInstance();
-#endif //MOZ_B2G
}
return sSingleton;
}
@@ -3050,18 +3039,6 @@ MediaManager::Observe(nsISupports* aSubject, const char* aTopic,
}
return NS_OK;
}
-#ifdef MOZ_WIDGET_GONK
- else if (!strcmp(aTopic, "phone-state-changed")) {
- nsString state(aData);
- nsresult rv;
- uint32_t phoneState = state.ToInteger(&rv);
-
- if (NS_SUCCEEDED(rv) && phoneState == nsIAudioManager::PHONE_STATE_IN_CALL) {
- StopMediaStreams();
- }
- return NS_OK;
- }
-#endif
return NS_OK;
}
diff --git a/dom/media/MediaPermissionGonk.cpp b/dom/media/MediaPermissionGonk.cpp
deleted file mode 100644
index 2a9cbf331..000000000
--- a/dom/media/MediaPermissionGonk.cpp
+++ /dev/null
@@ -1,522 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "MediaManager.h"
-#include "MediaPermissionGonk.h"
-
-#include "nsArray.h"
-#include "nsCOMPtr.h"
-#include "nsIContentPermissionPrompt.h"
-#include "nsIDocument.h"
-#include "nsIDOMNavigatorUserMedia.h"
-#include "nsIStringEnumerator.h"
-#include "nsJSUtils.h"
-#include "nsQueryObject.h"
-#include "nsPIDOMWindow.h"
-#include "nsTArray.h"
-#include "GetUserMediaRequest.h"
-#include "mozilla/dom/PBrowserChild.h"
-#include "mozilla/dom/MediaStreamTrackBinding.h"
-#include "mozilla/dom/MediaStreamError.h"
-#include "nsISupportsPrimitives.h"
-#include "nsServiceManagerUtils.h"
-#include "nsArrayUtils.h"
-#include "nsContentPermissionHelper.h"
-#include "mozilla/dom/PermissionMessageUtils.h"
-
-#define AUDIO_PERMISSION_NAME "audio-capture"
-#define VIDEO_PERMISSION_NAME "video-capture"
-
-using namespace mozilla::dom;
-
-namespace mozilla {
-
-static MediaPermissionManager *gMediaPermMgr = nullptr;
-
-static void
-CreateDeviceNameList(nsTArray<nsCOMPtr<nsIMediaDevice> > &aDevices,
- nsTArray<nsString> &aDeviceNameList)
-{
- for (uint32_t i = 0; i < aDevices.Length(); ++i) {
- nsString name;
- nsresult rv = aDevices[i]->GetName(name);
- NS_ENSURE_SUCCESS_VOID(rv);
- aDeviceNameList.AppendElement(name);
- }
-}
-
-static already_AddRefed<nsIMediaDevice>
-FindDeviceByName(nsTArray<nsCOMPtr<nsIMediaDevice> > &aDevices,
- const nsAString &aDeviceName)
-{
- for (uint32_t i = 0; i < aDevices.Length(); ++i) {
- nsCOMPtr<nsIMediaDevice> device = aDevices[i];
- nsString deviceName;
- device->GetName(deviceName);
- if (deviceName.Equals(aDeviceName)) {
- return device.forget();
- }
- }
-
- return nullptr;
-}
-
-// Helper function for notifying permission granted
-static nsresult
-NotifyPermissionAllow(const nsAString &aCallID, nsTArray<nsCOMPtr<nsIMediaDevice> > &aDevices)
-{
- nsresult rv;
- nsCOMPtr<nsIMutableArray> array = nsArray::Create();
-
- for (uint32_t i = 0; i < aDevices.Length(); ++i) {
- rv = array->AppendElement(aDevices.ElementAt(i), /*weak =*/ false);
- NS_ENSURE_SUCCESS(rv, rv);
- }
-
- nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
- NS_ENSURE_TRUE(obs, NS_ERROR_FAILURE);
-
- return obs->NotifyObservers(array, "getUserMedia:response:allow",
- aCallID.BeginReading());
-}
-
-// Helper function for notifying permision denial or error
-static nsresult
-NotifyPermissionDeny(const nsAString &aCallID, const nsAString &aErrorMsg)
-{
- nsresult rv;
- nsCOMPtr<nsISupportsString> supportsString =
- do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv);
- NS_ENSURE_SUCCESS(rv, rv);
-
- rv = supportsString->SetData(aErrorMsg);
- NS_ENSURE_SUCCESS(rv, rv);
-
- nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
- NS_ENSURE_TRUE(obs, NS_ERROR_FAILURE);
-
- return obs->NotifyObservers(supportsString, "getUserMedia:response:deny",
- aCallID.BeginReading());
-}
-
-namespace {
-
-/**
- * MediaPermissionRequest will send a prompt ipdl request to b2g process according
- * to its owned type.
- */
-class MediaPermissionRequest : public nsIContentPermissionRequest
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSICONTENTPERMISSIONREQUEST
-
- MediaPermissionRequest(RefPtr<dom::GetUserMediaRequest> &aRequest,
- nsTArray<nsCOMPtr<nsIMediaDevice> > &aDevices);
-
- already_AddRefed<nsPIDOMWindowInner> GetOwner();
-
-protected:
- virtual ~MediaPermissionRequest() {}
-
-private:
- nsresult DoAllow(const nsString &audioDevice, const nsString &videoDevice);
-
- bool mAudio; // Request for audio permission
- bool mVideo; // Request for video permission
- RefPtr<dom::GetUserMediaRequest> mRequest;
- nsTArray<nsCOMPtr<nsIMediaDevice> > mAudioDevices; // candidate audio devices
- nsTArray<nsCOMPtr<nsIMediaDevice> > mVideoDevices; // candidate video devices
- nsCOMPtr<nsIContentPermissionRequester> mRequester;
-};
-
-// MediaPermissionRequest
-NS_IMPL_ISUPPORTS(MediaPermissionRequest, nsIContentPermissionRequest)
-
-MediaPermissionRequest::MediaPermissionRequest(RefPtr<dom::GetUserMediaRequest> &aRequest,
- nsTArray<nsCOMPtr<nsIMediaDevice> > &aDevices)
- : mRequest(aRequest)
-{
- dom::MediaStreamConstraints constraints;
- mRequest->GetConstraints(constraints);
-
- mAudio = !constraints.mAudio.IsBoolean() || constraints.mAudio.GetAsBoolean();
- mVideo = !constraints.mVideo.IsBoolean() || constraints.mVideo.GetAsBoolean();
-
- for (uint32_t i = 0; i < aDevices.Length(); ++i) {
- nsCOMPtr<nsIMediaDevice> device(aDevices[i]);
- nsAutoString deviceType;
- device->GetType(deviceType);
- if (mAudio && deviceType.EqualsLiteral("audio")) {
- mAudioDevices.AppendElement(device);
- }
- if (mVideo && deviceType.EqualsLiteral("video")) {
- mVideoDevices.AppendElement(device);
- }
- }
-
- nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
- mRequester = new nsContentPermissionRequester(window);
-}
-
-// nsIContentPermissionRequest methods
-NS_IMETHODIMP
-MediaPermissionRequest::GetTypes(nsIArray** aTypes)
-{
- nsCOMPtr<nsIMutableArray> types = do_CreateInstance(NS_ARRAY_CONTRACTID);
- //XXX append device list
- if (mAudio) {
- nsTArray<nsString> audioDeviceNames;
- CreateDeviceNameList(mAudioDevices, audioDeviceNames);
- nsCOMPtr<nsISupports> AudioType =
- new ContentPermissionType(NS_LITERAL_CSTRING(AUDIO_PERMISSION_NAME),
- NS_LITERAL_CSTRING("unused"),
- audioDeviceNames);
- types->AppendElement(AudioType, false);
- }
- if (mVideo) {
- nsTArray<nsString> videoDeviceNames;
- CreateDeviceNameList(mVideoDevices, videoDeviceNames);
- nsCOMPtr<nsISupports> VideoType =
- new ContentPermissionType(NS_LITERAL_CSTRING(VIDEO_PERMISSION_NAME),
- NS_LITERAL_CSTRING("unused"),
- videoDeviceNames);
- types->AppendElement(VideoType, false);
- }
- NS_IF_ADDREF(*aTypes = types);
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-MediaPermissionRequest::GetPrincipal(nsIPrincipal **aRequestingPrincipal)
-{
- NS_ENSURE_ARG_POINTER(aRequestingPrincipal);
-
- nsCOMPtr<nsPIDOMWindowInner> window =
- nsGlobalWindow::GetInnerWindowWithId(mRequest->InnerWindowID())->AsInner();
- NS_ENSURE_TRUE(window, NS_ERROR_FAILURE);
-
- nsCOMPtr<nsIDocument> doc = window->GetExtantDoc();
- NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);
-
- NS_ADDREF(*aRequestingPrincipal = doc->NodePrincipal());
- return NS_OK;
-}
-
-NS_IMETHODIMP
-MediaPermissionRequest::GetWindow(mozIDOMWindow** aRequestingWindow)
-{
- NS_ENSURE_ARG_POINTER(aRequestingWindow);
- nsCOMPtr<nsPIDOMWindowInner> window =
- nsGlobalWindow::GetInnerWindowWithId(mRequest->InnerWindowID())->AsInner();
- window.forget(aRequestingWindow);
- return NS_OK;
-}
-
-NS_IMETHODIMP
-MediaPermissionRequest::GetElement(nsIDOMElement** aRequestingElement)
-{
- NS_ENSURE_ARG_POINTER(aRequestingElement);
- *aRequestingElement = nullptr;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-MediaPermissionRequest::Cancel()
-{
- nsString callID;
- mRequest->GetCallID(callID);
- NotifyPermissionDeny(callID, NS_LITERAL_STRING("SecurityError"));
- return NS_OK;
-}
-
-NS_IMETHODIMP
-MediaPermissionRequest::Allow(JS::HandleValue aChoices)
-{
- // check if JS object
- if (!aChoices.isObject()) {
- MOZ_ASSERT(false, "Not a correct format of PermissionChoice");
- return NS_ERROR_INVALID_ARG;
- }
- // iterate through audio-capture and video-capture
- AutoJSAPI jsapi;
- if (!jsapi.Init(&aChoices.toObject())) {
- return NS_ERROR_UNEXPECTED;
- }
- JSContext* cx = jsapi.cx();
- JS::Rooted<JSObject*> obj(cx, &aChoices.toObject());
- JS::Rooted<JS::Value> v(cx);
-
- // get selected audio device name
- nsString audioDevice;
- if (mAudio) {
- if (!JS_GetProperty(cx, obj, AUDIO_PERMISSION_NAME, &v) || !v.isString()) {
- return NS_ERROR_FAILURE;
- }
- nsAutoJSString deviceName;
- if (!deviceName.init(cx, v)) {
- MOZ_ASSERT(false, "Couldn't initialize string from aChoices");
- return NS_ERROR_FAILURE;
- }
- audioDevice = deviceName;
- }
-
- // get selected video device name
- nsString videoDevice;
- if (mVideo) {
- if (!JS_GetProperty(cx, obj, VIDEO_PERMISSION_NAME, &v) || !v.isString()) {
- return NS_ERROR_FAILURE;
- }
- nsAutoJSString deviceName;
- if (!deviceName.init(cx, v)) {
- MOZ_ASSERT(false, "Couldn't initialize string from aChoices");
- return NS_ERROR_FAILURE;
- }
- videoDevice = deviceName;
- }
-
- return DoAllow(audioDevice, videoDevice);
-}
-
-NS_IMETHODIMP
-MediaPermissionRequest::GetRequester(nsIContentPermissionRequester** aRequester)
-{
- NS_ENSURE_ARG_POINTER(aRequester);
-
- nsCOMPtr<nsIContentPermissionRequester> requester = mRequester;
- requester.forget(aRequester);
- return NS_OK;
-}
-
-nsresult
-MediaPermissionRequest::DoAllow(const nsString &audioDevice,
- const nsString &videoDevice)
-{
- nsTArray<nsCOMPtr<nsIMediaDevice> > selectedDevices;
- if (mAudio) {
- nsCOMPtr<nsIMediaDevice> device =
- FindDeviceByName(mAudioDevices, audioDevice);
- if (device) {
- selectedDevices.AppendElement(device);
- }
- }
-
- if (mVideo) {
- nsCOMPtr<nsIMediaDevice> device =
- FindDeviceByName(mVideoDevices, videoDevice);
- if (device) {
- selectedDevices.AppendElement(device);
- }
- }
-
- nsString callID;
- mRequest->GetCallID(callID);
- return NotifyPermissionAllow(callID, selectedDevices);
-}
-
-already_AddRefed<nsPIDOMWindowInner>
-MediaPermissionRequest::GetOwner()
-{
- nsCOMPtr<nsPIDOMWindowInner> window =
- nsGlobalWindow::GetInnerWindowWithId(mRequest->InnerWindowID())->AsInner();
- return window.forget();
-}
-
-// Success callback for MediaManager::GetUserMediaDevices().
-class MediaDeviceSuccessCallback: public nsIGetUserMediaDevicesSuccessCallback
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIGETUSERMEDIADEVICESSUCCESSCALLBACK
-
- explicit MediaDeviceSuccessCallback(RefPtr<dom::GetUserMediaRequest> &aRequest)
- : mRequest(aRequest) {}
-
-protected:
- virtual ~MediaDeviceSuccessCallback() {}
-
-private:
- nsresult DoPrompt(RefPtr<MediaPermissionRequest> &req);
- RefPtr<dom::GetUserMediaRequest> mRequest;
-};
-
-NS_IMPL_ISUPPORTS(MediaDeviceSuccessCallback, nsIGetUserMediaDevicesSuccessCallback)
-
-// nsIGetUserMediaDevicesSuccessCallback method
-NS_IMETHODIMP
-MediaDeviceSuccessCallback::OnSuccess(nsIVariant* aDevices)
-{
- nsIID elementIID;
- uint16_t elementType;
- void* rawArray;
- uint32_t arrayLen;
-
- nsresult rv;
- rv = aDevices->GetAsArray(&elementType, &elementIID, &arrayLen, &rawArray);
- NS_ENSURE_SUCCESS(rv, rv);
-
- if (elementType != nsIDataType::VTYPE_INTERFACE) {
- free(rawArray);
- return NS_ERROR_FAILURE;
- }
-
- // Create array for nsIMediaDevice
- nsTArray<nsCOMPtr<nsIMediaDevice> > devices;
-
- nsISupports **supportsArray = reinterpret_cast<nsISupports **>(rawArray);
- for (uint32_t i = 0; i < arrayLen; ++i) {
- nsCOMPtr<nsIMediaDevice> device(do_QueryInterface(supportsArray[i]));
- devices.AppendElement(device);
- NS_IF_RELEASE(supportsArray[i]); // explicitly decrease reference count for raw pointer
- }
- free(rawArray); // explicitly free for the memory from nsIVariant::GetAsArray
-
- // Send MediaPermissionRequest
- RefPtr<MediaPermissionRequest> req = new MediaPermissionRequest(mRequest, devices);
- rv = DoPrompt(req);
-
- NS_ENSURE_SUCCESS(rv, rv);
- return NS_OK;
-}
-
-// Trigger permission prompt UI
-nsresult
-MediaDeviceSuccessCallback::DoPrompt(RefPtr<MediaPermissionRequest> &req)
-{
- nsCOMPtr<nsPIDOMWindowInner> window(req->GetOwner());
- return dom::nsContentPermissionUtils::AskPermission(req, window);
-}
-
-// Error callback for MediaManager::GetUserMediaDevices()
-class MediaDeviceErrorCallback: public nsIDOMGetUserMediaErrorCallback
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIDOMGETUSERMEDIAERRORCALLBACK
-
- explicit MediaDeviceErrorCallback(const nsAString &aCallID)
- : mCallID(aCallID) {}
-
-protected:
- virtual ~MediaDeviceErrorCallback() {}
-
-private:
- const nsString mCallID;
-};
-
-NS_IMPL_ISUPPORTS(MediaDeviceErrorCallback, nsIDOMGetUserMediaErrorCallback)
-
-// nsIDOMGetUserMediaErrorCallback method
-NS_IMETHODIMP
-MediaDeviceErrorCallback::OnError(nsISupports* aError)
-{
- RefPtr<MediaStreamError> error = do_QueryObject(aError);
- if (!error) {
- return NS_ERROR_NO_INTERFACE;
- }
-
- nsString name;
- error->GetName(name);
- return NotifyPermissionDeny(mCallID, name);
-}
-
-} // namespace anonymous
-
-// MediaPermissionManager
-NS_IMPL_ISUPPORTS(MediaPermissionManager, nsIObserver)
-
-MediaPermissionManager*
-MediaPermissionManager::GetInstance()
-{
- if (!gMediaPermMgr) {
- gMediaPermMgr = new MediaPermissionManager();
- }
-
- return gMediaPermMgr;
-}
-
-MediaPermissionManager::MediaPermissionManager()
-{
- nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
- if (obs) {
- obs->AddObserver(this, "getUserMedia:request", false);
- obs->AddObserver(this, "xpcom-shutdown", false);
- }
-}
-
-MediaPermissionManager::~MediaPermissionManager()
-{
- this->Deinit();
-}
-
-nsresult
-MediaPermissionManager::Deinit()
-{
- nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
- if (obs) {
- obs->RemoveObserver(this, "getUserMedia:request");
- obs->RemoveObserver(this, "xpcom-shutdown");
- }
- return NS_OK;
-}
-
-// nsIObserver method
-NS_IMETHODIMP
-MediaPermissionManager::Observe(nsISupports* aSubject, const char* aTopic,
- const char16_t* aData)
-{
- nsresult rv;
- if (!strcmp(aTopic, "getUserMedia:request")) {
- RefPtr<dom::GetUserMediaRequest> req =
- static_cast<dom::GetUserMediaRequest*>(aSubject);
- rv = HandleRequest(req);
-
- if (NS_FAILED(rv)) {
- nsString callID;
- req->GetCallID(callID);
- NotifyPermissionDeny(callID, NS_LITERAL_STRING("unable to enumerate media device"));
- }
- } else if (!strcmp(aTopic, "xpcom-shutdown")) {
- rv = this->Deinit();
- } else {
- // not reachable
- rv = NS_ERROR_FAILURE;
- }
- return rv;
-}
-
-// Handle GetUserMediaRequest, query available media device first.
-nsresult
-MediaPermissionManager::HandleRequest(RefPtr<dom::GetUserMediaRequest> &req)
-{
- nsString callID;
- req->GetCallID(callID);
- uint64_t innerWindowID = req->InnerWindowID();
-
- nsCOMPtr<nsPIDOMWindowInner> innerWindow =
- nsGlobalWindow::GetInnerWindowWithId(innerWindowID)->AsInner();
- if (!innerWindow) {
- MOZ_ASSERT(false, "No inner window");
- return NS_ERROR_FAILURE;
- }
-
- nsCOMPtr<nsIGetUserMediaDevicesSuccessCallback> onSuccess =
- new MediaDeviceSuccessCallback(req);
- nsCOMPtr<nsIDOMGetUserMediaErrorCallback> onError =
- new MediaDeviceErrorCallback(callID);
-
- dom::MediaStreamConstraints constraints;
- req->GetConstraints(constraints);
-
- RefPtr<MediaManager> MediaMgr = MediaManager::GetInstance();
- nsresult rv = MediaMgr->GetUserMediaDevices(innerWindow, constraints,
- onSuccess, onError,
- innerWindowID, callID);
- NS_ENSURE_SUCCESS(rv, rv);
-
- return NS_OK;
-}
-
-} // namespace mozilla
diff --git a/dom/media/MediaPermissionGonk.h b/dom/media/MediaPermissionGonk.h
deleted file mode 100644
index 0a2fac056..000000000
--- a/dom/media/MediaPermissionGonk.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_MEDIA_MEDIAPERMISSIONGONK_H
-#define DOM_MEDIA_MEDIAPERMISSIONGONK_H
-
-#include "nsError.h"
-#include "nsIObserver.h"
-#include "nsISupportsImpl.h"
-#include "GetUserMediaRequest.h"
-
-namespace mozilla {
-
-/**
- * The observer to create the MediaPermissionMgr. This is the entry point of
- * permission request on b2g.
- */
-class MediaPermissionManager : public nsIObserver
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIOBSERVER
-
- static MediaPermissionManager* GetInstance();
-
-protected:
- virtual ~MediaPermissionManager();
-
-private:
- MediaPermissionManager();
- nsresult Deinit();
- nsresult HandleRequest(RefPtr<dom::GetUserMediaRequest> &req);
-};
-
-} // namespace mozilla
-
-#endif // DOM_MEDIA_MEDIAPERMISSIONGONK_H
-
diff --git a/dom/media/MediaStreamTrack.cpp b/dom/media/MediaStreamTrack.cpp
index 8ccdeb90c..75cdeb1d1 100644
--- a/dom/media/MediaStreamTrack.cpp
+++ b/dom/media/MediaStreamTrack.cpp
@@ -165,11 +165,15 @@ MediaStreamTrack::Destroy()
mPrincipalHandleListener->Forget();
mPrincipalHandleListener = nullptr;
}
- for (auto l : mTrackListeners) {
- RemoveListener(l);
+ // Remove all listeners -- avoid iterating over the list we're removing from
+ const nsTArray<RefPtr<MediaStreamTrackListener>> trackListeners(mTrackListeners);
+ for (auto listener : trackListeners) {
+ RemoveListener(listener);
}
- for (auto l : mDirectTrackListeners) {
- RemoveDirectListener(l);
+ // Do the same as above for direct listeners
+ const nsTArray<RefPtr<DirectMediaStreamTrackListener>> directTrackListeners(mDirectTrackListeners);
+ for (auto listener : directTrackListeners) {
+ RemoveDirectListener(listener);
}
}
diff --git a/dom/media/PeerConnection.js b/dom/media/PeerConnection.js
index 98b8debbe..0c3021799 100644
--- a/dom/media/PeerConnection.js
+++ b/dom/media/PeerConnection.js
@@ -791,7 +791,6 @@ RTCPeerConnection.prototype = {
return this._havePermission;
}
if (this._isChrome ||
- AppConstants.MOZ_B2G ||
Services.prefs.getBoolPref("media.navigator.permission.disabled")) {
return this._havePermission = Promise.resolve();
}
diff --git a/dom/media/android/AndroidMediaPluginHost.cpp b/dom/media/android/AndroidMediaPluginHost.cpp
index d3dce2b93..cc3adbbd3 100644
--- a/dom/media/android/AndroidMediaPluginHost.cpp
+++ b/dom/media/android/AndroidMediaPluginHost.cpp
@@ -22,7 +22,7 @@
#include "nsIPropertyBag2.h"
-#if defined(ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID)
#include "android/log.h"
#define ALOG(args...) __android_log_print(ANDROID_LOG_INFO, "AndroidMediaPluginHost" , ## args)
#else
@@ -134,7 +134,7 @@ static bool IsOmxSupported()
// nullptr is returned if Omx decoding is not supported on the device,
static const char* GetOmxLibraryName()
{
-#if defined(ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID)
nsCOMPtr<nsIPropertyBag2> infoService = do_GetService("@mozilla.org/system-info;1");
NS_ASSERTION(infoService, "Could not find a system info service");
@@ -172,7 +172,7 @@ static const char* GetOmxLibraryName()
if (!IsOmxSupported())
return nullptr;
-#if defined(ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID)
if (version >= 17) {
return "libomxpluginkk.so";
}
@@ -180,8 +180,6 @@ static const char* GetOmxLibraryName()
// Ice Cream Sandwich and Jellybean
return "libomxplugin.so";
-#elif defined(ANDROID) && defined(MOZ_WIDGET_GONK)
- return "libomxplugin.so";
#else
return nullptr;
#endif
diff --git a/dom/media/encoder/OpusTrackEncoder.cpp b/dom/media/encoder/OpusTrackEncoder.cpp
index c65d57788..4b55b3954 100644
--- a/dom/media/encoder/OpusTrackEncoder.cpp
+++ b/dom/media/encoder/OpusTrackEncoder.cpp
@@ -9,12 +9,7 @@
#include <opus/opus.h>
#undef LOG
-#ifdef MOZ_WIDGET_GONK
-#include <android/log.h>
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "MediaEncoder", ## args);
-#else
#define LOG(args, ...)
-#endif
namespace mozilla {
diff --git a/dom/media/encoder/TrackEncoder.cpp b/dom/media/encoder/TrackEncoder.cpp
index ea39bb5a6..df6b24409 100644
--- a/dom/media/encoder/TrackEncoder.cpp
+++ b/dom/media/encoder/TrackEncoder.cpp
@@ -10,12 +10,7 @@
#include "VideoUtils.h"
#undef LOG
-#ifdef MOZ_WIDGET_GONK
-#include <android/log.h>
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "MediaEncoder", ## args);
-#else
#define LOG(args, ...)
-#endif
namespace mozilla {
diff --git a/dom/media/encoder/fmp4_muxer/AMRBox.cpp b/dom/media/encoder/fmp4_muxer/AMRBox.cpp
deleted file mode 100644
index cd1a34fae..000000000
--- a/dom/media/encoder/fmp4_muxer/AMRBox.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-/* -*- 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 "ISOControl.h"
-#include "ISOMediaBoxes.h"
-#include "AMRBox.h"
-#include "ISOTrackMetadata.h"
-
-namespace mozilla {
-
-nsresult
-AMRSampleEntry::Generate(uint32_t* aBoxSize)
-{
- uint32_t box_size;
- nsresult rv = amr_special_box->Generate(&box_size);
- NS_ENSURE_SUCCESS(rv, rv);
- size += box_size;
-
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-AMRSampleEntry::Write()
-{
- BoxSizeChecker checker(mControl, size);
- nsresult rv;
- rv = AudioSampleEntry::Write();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = amr_special_box->Write();
- NS_ENSURE_SUCCESS(rv, rv);
-
- return NS_OK;
-}
-
-AMRSampleEntry::AMRSampleEntry(ISOControl* aControl)
- : AudioSampleEntry(NS_LITERAL_CSTRING("samr"), aControl)
-{
- amr_special_box = new AMRSpecificBox(aControl);
- MOZ_COUNT_CTOR(AMRSampleEntry);
-}
-
-AMRSampleEntry::~AMRSampleEntry()
-{
- MOZ_COUNT_DTOR(AMRSampleEntry);
-}
-
-nsresult
-AMRSpecificBox::Generate(uint32_t* aBoxSize)
-{
- nsresult rv;
- FragmentBuffer* frag = mControl->GetFragment(Audio_Track);
- rv = frag->GetCSD(amrDecSpecInfo);
- NS_ENSURE_SUCCESS(rv, rv);
-
- size += amrDecSpecInfo.Length();
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-AMRSpecificBox::Write()
-{
- BoxSizeChecker checker(mControl, size);
- Box::Write();
- mControl->Write(amrDecSpecInfo.Elements(), amrDecSpecInfo.Length());
- return NS_OK;
-}
-
-AMRSpecificBox::AMRSpecificBox(ISOControl* aControl)
- : Box(NS_LITERAL_CSTRING("damr"), aControl)
-{
- MOZ_COUNT_CTOR(AMRSpecificBox);
-}
-
-AMRSpecificBox::~AMRSpecificBox()
-{
- MOZ_COUNT_DTOR(AMRSpecificBox);
-}
-
-}
diff --git a/dom/media/encoder/fmp4_muxer/AMRBox.h b/dom/media/encoder/fmp4_muxer/AMRBox.h
deleted file mode 100644
index 645d7f89c..000000000
--- a/dom/media/encoder/fmp4_muxer/AMRBox.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/* -*- 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/. */
-
-#ifndef AMRBOX_h_
-#define AMRBOX_h_
-
-#include "nsTArray.h"
-#include "MuxerOperation.h"
-
-namespace mozilla {
-
-class ISOControl;
-
-// 3GPP TS 26.244 6.7 'AMRSpecificBox field for AMRSampleEntry box'
-// Box type: 'damr'
-class AMRSpecificBox : public Box {
-public:
- // 3GPP members
- nsTArray<uint8_t> amrDecSpecInfo;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // AMRSpecificBox methods
- AMRSpecificBox(ISOControl* aControl);
- ~AMRSpecificBox();
-};
-
-// 3GPP TS 26.244 6.5 'AMRSampleEntry box'
-// Box type: 'sawb'
-class AMRSampleEntry : public AudioSampleEntry {
-public:
- // 3GPP members
- RefPtr<AMRSpecificBox> amr_special_box;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // AMRSampleEntry methods
- AMRSampleEntry(ISOControl* aControl);
- ~AMRSampleEntry();
-};
-
-}
-
-#endif // AMRBOX_h_
diff --git a/dom/media/encoder/fmp4_muxer/AVCBox.cpp b/dom/media/encoder/fmp4_muxer/AVCBox.cpp
deleted file mode 100644
index a45cda8b7..000000000
--- a/dom/media/encoder/fmp4_muxer/AVCBox.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/* -*- 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 <climits>
-#include "ISOControl.h"
-#include "ISOMediaBoxes.h"
-#include "AVCBox.h"
-
-namespace mozilla {
-
-nsresult
-AVCSampleEntry::Generate(uint32_t* aBoxSize)
-{
- uint32_t avc_box_size = 0;
- nsresult rv;
- rv = avcConfigBox->Generate(&avc_box_size);
- NS_ENSURE_SUCCESS(rv, rv);
-
- size += avc_box_size;
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-AVCSampleEntry::Write()
-{
- BoxSizeChecker checker(mControl, size);
- nsresult rv;
- rv = VisualSampleEntry::Write();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = avcConfigBox->Write();
- NS_ENSURE_SUCCESS(rv, rv);
-
- return NS_OK;
-}
-
-AVCSampleEntry::AVCSampleEntry(ISOControl* aControl)
- : VisualSampleEntry(NS_LITERAL_CSTRING("avc1"), aControl)
-{
- avcConfigBox = new AVCConfigurationBox(aControl);
- MOZ_COUNT_CTOR(AVCSampleEntry);
-}
-
-AVCSampleEntry::~AVCSampleEntry()
-{
- MOZ_COUNT_DTOR(AVCSampleEntry);
-}
-
-AVCConfigurationBox::AVCConfigurationBox(ISOControl* aControl)
- : Box(NS_LITERAL_CSTRING("avcC"), aControl)
-{
- MOZ_COUNT_CTOR(AVCConfigurationBox);
-}
-
-AVCConfigurationBox::~AVCConfigurationBox()
-{
- MOZ_COUNT_DTOR(AVCConfigurationBox);
-}
-
-nsresult
-AVCConfigurationBox::Generate(uint32_t* aBoxSize)
-{
- nsresult rv;
- FragmentBuffer* frag = mControl->GetFragment(Video_Track);
- rv = frag->GetCSD(avcConfig);
- NS_ENSURE_SUCCESS(rv, rv);
- size += avcConfig.Length();
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-AVCConfigurationBox::Write()
-{
- BoxSizeChecker checker(mControl, size);
- Box::Write();
-
- mControl->Write(avcConfig.Elements(), avcConfig.Length());
-
- return NS_OK;
-}
-
-}
diff --git a/dom/media/encoder/fmp4_muxer/AVCBox.h b/dom/media/encoder/fmp4_muxer/AVCBox.h
deleted file mode 100644
index 9640d9e8f..000000000
--- a/dom/media/encoder/fmp4_muxer/AVCBox.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/* -*- 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/. */
-
-#ifndef AVCBox_h_
-#define AVCBox_h_
-
-#include "nsTArray.h"
-#include "ISOMediaBoxes.h"
-
-namespace mozilla {
-
-class ISOControl;
-
-// 14496-12 8.5.2.2
-#define resolution_72_dpi 0x00480000
-#define video_depth 0x0018
-
-// 14496-15 5.3.4.1 'Sample description name and format'
-// Box type: 'avcC'
-class AVCConfigurationBox : public Box {
-public:
- // ISO BMFF members
-
- // avcConfig is CodecSpecificData from 14496-15 '5.3.4.1 Sample description
- // name and format.
- // These data are generated by encoder and we encapsulated the generated
- // bitstream into box directly.
- nsTArray<uint8_t> avcConfig;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // AVCConfigurationBox methods
- AVCConfigurationBox(ISOControl* aControl);
- ~AVCConfigurationBox();
-};
-
-// 14496-15 5.3.4.1 'Sample description name and format'
-// Box type: 'avc1'
-class AVCSampleEntry : public VisualSampleEntry {
-public:
- // ISO BMFF members
- RefPtr<AVCConfigurationBox> avcConfigBox;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // VisualSampleEntry methods
- AVCSampleEntry(ISOControl* aControl);
- ~AVCSampleEntry();
-};
-
-}
-
-#endif // AVCBox_h_
diff --git a/dom/media/encoder/fmp4_muxer/EVRCBox.cpp b/dom/media/encoder/fmp4_muxer/EVRCBox.cpp
deleted file mode 100644
index 096e4013d..000000000
--- a/dom/media/encoder/fmp4_muxer/EVRCBox.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-/* -*- 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 "ISOControl.h"
-#include "ISOMediaBoxes.h"
-#include "EVRCBox.h"
-#include "ISOTrackMetadata.h"
-
-namespace mozilla {
-
-nsresult
-EVRCSampleEntry::Generate(uint32_t* aBoxSize)
-{
- uint32_t box_size;
- nsresult rv = evrc_special_box->Generate(&box_size);
- NS_ENSURE_SUCCESS(rv, rv);
- size += box_size;
-
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-EVRCSampleEntry::Write()
-{
- BoxSizeChecker checker(mControl, size);
- nsresult rv;
- rv = AudioSampleEntry::Write();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = evrc_special_box->Write();
- NS_ENSURE_SUCCESS(rv, rv);
-
- return NS_OK;
-}
-
-EVRCSampleEntry::EVRCSampleEntry(ISOControl* aControl)
- : AudioSampleEntry(NS_LITERAL_CSTRING("sevc"), aControl)
-{
- evrc_special_box = new EVRCSpecificBox(aControl);
- MOZ_COUNT_CTOR(EVRCSampleEntry);
-}
-
-EVRCSampleEntry::~EVRCSampleEntry()
-{
- MOZ_COUNT_DTOR(EVRCSampleEntry);
-}
-
-nsresult
-EVRCSpecificBox::Generate(uint32_t* aBoxSize)
-{
- nsresult rv;
- FragmentBuffer* frag = mControl->GetFragment(Audio_Track);
- rv = frag->GetCSD(evrcDecSpecInfo);
- NS_ENSURE_SUCCESS(rv, rv);
-
- size += evrcDecSpecInfo.Length();
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-EVRCSpecificBox::Write()
-{
- BoxSizeChecker checker(mControl, size);
- Box::Write();
- mControl->Write(evrcDecSpecInfo.Elements(), evrcDecSpecInfo.Length());
- return NS_OK;
-}
-
-EVRCSpecificBox::EVRCSpecificBox(ISOControl* aControl)
- : Box(NS_LITERAL_CSTRING("devc"), aControl)
-{
- MOZ_COUNT_CTOR(EVRCSpecificBox);
-}
-
-EVRCSpecificBox::~EVRCSpecificBox()
-{
- MOZ_COUNT_DTOR(EVRCSpecificBox);
-}
-
-}
diff --git a/dom/media/encoder/fmp4_muxer/EVRCBox.h b/dom/media/encoder/fmp4_muxer/EVRCBox.h
deleted file mode 100644
index 31355849a..000000000
--- a/dom/media/encoder/fmp4_muxer/EVRCBox.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/* -*- 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/. */
-
-#ifndef EVRCBOX_h_
-#define EVRCBOX_h_
-
-#include "nsTArray.h"
-#include "MuxerOperation.h"
-
-namespace mozilla {
-
-class ISOControl;
-
-// 3GPP TS 26.244 6.7 'EVRCSpecificBox field for EVRCSampleEntry box'
-// Box type: 'devc'
-class EVRCSpecificBox : public Box {
-public:
- // 3GPP members
- nsTArray<uint8_t> evrcDecSpecInfo;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // EVRCSpecificBox methods
- EVRCSpecificBox(ISOControl* aControl);
- ~EVRCSpecificBox();
-};
-
-// 3GPP TS 26.244 6.5 'EVRCSampleEntry box'
-// Box type: 'sevc'
-class EVRCSampleEntry : public AudioSampleEntry {
-public:
- // 3GPP members
- RefPtr<EVRCSpecificBox> evrc_special_box;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // EVRCSampleEntry methods
- EVRCSampleEntry(ISOControl* aControl);
- ~EVRCSampleEntry();
-};
-
-}
-
-#endif // EVRCBOX_h_
diff --git a/dom/media/encoder/fmp4_muxer/ISOControl.cpp b/dom/media/encoder/fmp4_muxer/ISOControl.cpp
deleted file mode 100644
index 6addaeb30..000000000
--- a/dom/media/encoder/fmp4_muxer/ISOControl.cpp
+++ /dev/null
@@ -1,415 +0,0 @@
-/* -*- 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 <time.h>
-#include "nsAutoPtr.h"
-#include "ISOControl.h"
-#include "ISOMediaBoxes.h"
-#include "EncodedFrameContainer.h"
-
-namespace mozilla {
-
-// For MP4 creation_time and modification_time offset from January 1, 1904 to
-// January 1, 1970.
-#define iso_time_offset 2082844800
-
-FragmentBuffer::FragmentBuffer(uint32_t aTrackType, uint32_t aFragDuration)
- : mTrackType(aTrackType)
- , mFragDuration(aFragDuration)
- , mMediaStartTime(0)
- , mFragmentNumber(0)
- , mLastFrameTimeOfLastFragment(0)
- , mEOS(false)
-{
- mFragArray.AppendElement();
- MOZ_COUNT_CTOR(FragmentBuffer);
-}
-
-FragmentBuffer::~FragmentBuffer()
-{
- MOZ_COUNT_DTOR(FragmentBuffer);
-}
-
-bool
-FragmentBuffer::HasEnoughData()
-{
- // Audio or video frame is enough to form a moof.
- return (mFragArray.Length() > 1);
-}
-
-nsresult
-FragmentBuffer::GetCSD(nsTArray<uint8_t>& aCSD)
-{
- if (!mCSDFrame) {
- return NS_ERROR_FAILURE;
- }
- aCSD.AppendElements(mCSDFrame->GetFrameData().Elements(),
- mCSDFrame->GetFrameData().Length());
-
- return NS_OK;
-}
-
-nsresult
-FragmentBuffer::AddFrame(EncodedFrame* aFrame)
-{
- // already EOS, it rejects all new data.
- if (mEOS) {
- MOZ_ASSERT(0);
- return NS_OK;
- }
-
- EncodedFrame::FrameType type = aFrame->GetFrameType();
- if (type == EncodedFrame::AAC_CSD || type == EncodedFrame::AVC_CSD ||
- type == EncodedFrame::AMR_AUDIO_CSD || type == EncodedFrame::EVRC_AUDIO_CSD) {
- mCSDFrame = aFrame;
- // Use CSD's timestamp as the start time. Encoder should send CSD frame first
- // and then data frames.
- mMediaStartTime = aFrame->GetTimeStamp();
- mFragmentNumber = 1;
- return NS_OK;
- }
-
- // if the timestamp is incorrect, abort it.
- if (aFrame->GetTimeStamp() < mMediaStartTime) {
- MOZ_ASSERT(false);
- return NS_ERROR_FAILURE;
- }
-
- mFragArray.LastElement().AppendElement(aFrame);
-
- // check if current fragment is reach the fragment duration.
- if ((aFrame->GetTimeStamp() - mMediaStartTime) >= (mFragDuration * mFragmentNumber)) {
- mFragArray.AppendElement();
- mFragmentNumber++;
- }
-
- return NS_OK;
-}
-
-nsresult
-FragmentBuffer::GetFirstFragment(nsTArray<RefPtr<EncodedFrame>>& aFragment,
- bool aFlush)
-{
- // It should be called only if there is a complete fragment in mFragArray.
- if (mFragArray.Length() <= 1 && !mEOS) {
- MOZ_ASSERT(false);
- return NS_ERROR_FAILURE;
- }
-
- if (aFlush) {
- aFragment.SwapElements(mFragArray.ElementAt(0));
- mFragArray.RemoveElementAt(0);
- } else {
- aFragment.AppendElements(mFragArray.ElementAt(0));
- }
- return NS_OK;
-}
-
-uint32_t
-FragmentBuffer::GetFirstFragmentSampleNumber()
-{
- return mFragArray.ElementAt(0).Length();
-}
-
-uint32_t
-FragmentBuffer::GetFirstFragmentSampleSize()
-{
- uint32_t size = 0;
- uint32_t len = mFragArray.ElementAt(0).Length();
- for (uint32_t i = 0; i < len; i++) {
- size += mFragArray.ElementAt(0).ElementAt(i)->GetFrameData().Length();
- }
- return size;
-}
-
-ISOControl::ISOControl(uint32_t aMuxingType)
- : mMuxingType(aMuxingType)
- , mAudioFragmentBuffer(nullptr)
- , mVideoFragmentBuffer(nullptr)
- , mFragNum(0)
- , mOutputSize(0)
- , mBitCount(0)
- , mBit(0)
-{
- // Create a data array for first mp4 Box, ftyp.
- mOutBuffers.SetLength(1);
- MOZ_COUNT_CTOR(ISOControl);
-}
-
-ISOControl::~ISOControl()
-{
- MOZ_COUNT_DTOR(ISOControl);
-}
-
-uint32_t
-ISOControl::GetNextTrackID()
-{
- return (mMetaArray.Length() + 1);
-}
-
-uint32_t
-ISOControl::GetTrackID(TrackMetadataBase::MetadataKind aKind)
-{
- for (uint32_t i = 0; i < mMetaArray.Length(); i++) {
- if (mMetaArray[i]->GetKind() == aKind) {
- return (i + 1);
- }
- }
-
- // Track ID shouldn't be 0. It must be something wrong here.
- MOZ_ASSERT(0);
- return 0;
-}
-
-nsresult
-ISOControl::SetMetadata(TrackMetadataBase* aTrackMeta)
-{
- if (aTrackMeta->GetKind() == TrackMetadataBase::METADATA_AAC ||
- aTrackMeta->GetKind() == TrackMetadataBase::METADATA_AMR ||
- aTrackMeta->GetKind() == TrackMetadataBase::METADATA_AVC ||
- aTrackMeta->GetKind() == TrackMetadataBase::METADATA_EVRC) {
- mMetaArray.AppendElement(aTrackMeta);
- return NS_OK;
- }
- return NS_ERROR_FAILURE;
-}
-
-nsresult
-ISOControl::GetAudioMetadata(RefPtr<AudioTrackMetadata>& aAudMeta)
-{
- for (uint32_t i = 0; i < mMetaArray.Length() ; i++) {
- if (mMetaArray[i]->GetKind() == TrackMetadataBase::METADATA_AAC ||
- mMetaArray[i]->GetKind() == TrackMetadataBase::METADATA_AMR ||
- mMetaArray[i]->GetKind() == TrackMetadataBase::METADATA_EVRC) {
- aAudMeta = static_cast<AudioTrackMetadata*>(mMetaArray[i].get());
- return NS_OK;
- }
- }
- return NS_ERROR_FAILURE;
-}
-
-nsresult
-ISOControl::GetVideoMetadata(RefPtr<VideoTrackMetadata>& aVidMeta)
-{
- for (uint32_t i = 0; i < mMetaArray.Length() ; i++) {
- if (mMetaArray[i]->GetKind() == TrackMetadataBase::METADATA_AVC) {
- aVidMeta = static_cast<VideoTrackMetadata*>(mMetaArray[i].get());
- return NS_OK;
- }
- }
- return NS_ERROR_FAILURE;
-}
-
-bool
-ISOControl::HasAudioTrack()
-{
- RefPtr<AudioTrackMetadata> audMeta;
- GetAudioMetadata(audMeta);
- return audMeta;
-}
-
-bool
-ISOControl::HasVideoTrack()
-{
- RefPtr<VideoTrackMetadata> vidMeta;
- GetVideoMetadata(vidMeta);
- return vidMeta;
-}
-
-nsresult
-ISOControl::SetFragment(FragmentBuffer* aFragment)
-{
- if (aFragment->GetType() == Audio_Track) {
- mAudioFragmentBuffer = aFragment;
- } else {
- mVideoFragmentBuffer = aFragment;
- }
- return NS_OK;
-}
-
-FragmentBuffer*
-ISOControl::GetFragment(uint32_t aType)
-{
- if (aType == Audio_Track) {
- return mAudioFragmentBuffer;
- } else if (aType == Video_Track){
- return mVideoFragmentBuffer;
- }
- MOZ_ASSERT(0);
- return nullptr;
-}
-
-nsresult
-ISOControl::GetBufs(nsTArray<nsTArray<uint8_t>>* aOutputBufs)
-{
- uint32_t len = mOutBuffers.Length();
- for (uint32_t i = 0; i < len; i++) {
- mOutBuffers[i].SwapElements(*aOutputBufs->AppendElement());
- }
- return FlushBuf();
-}
-
-nsresult
-ISOControl::FlushBuf()
-{
- mOutBuffers.SetLength(1);
- return NS_OK;
-}
-
-uint32_t
-ISOControl::WriteAVData(nsTArray<uint8_t>& aArray)
-{
- MOZ_ASSERT(!mBitCount);
-
- uint32_t len = aArray.Length();
- if (!len) {
- return 0;
- }
-
- mOutputSize += len;
-
- // The last element already has data, allocated a new element for pointer
- // swapping.
- if (mOutBuffers.LastElement().Length()) {
- mOutBuffers.AppendElement();
- }
- // Swap the video/audio data pointer.
- mOutBuffers.LastElement().SwapElements(aArray);
- // Following data could be boxes, so appending a new uint8_t array here.
- mOutBuffers.AppendElement();
-
- return len;
-}
-
-uint32_t
-ISOControl::WriteBits(uint64_t aBits, size_t aNumBits)
-{
- uint8_t output_byte = 0;
-
- MOZ_ASSERT(aNumBits <= 64);
- // TODO: rewritten following with bitset?
- for (size_t i = aNumBits; i > 0; i--) {
- mBit |= (((aBits >> (i - 1)) & 1) << (8 - ++mBitCount));
- if (mBitCount == 8) {
- Write(&mBit, sizeof(uint8_t));
- mBit = 0;
- mBitCount = 0;
- output_byte++;
- }
- }
- return output_byte;
-}
-
-uint32_t
-ISOControl::Write(uint8_t* aBuf, uint32_t aSize)
-{
- mOutBuffers.LastElement().AppendElements(aBuf, aSize);
- mOutputSize += aSize;
- return aSize;
-}
-
-uint32_t
-ISOControl::Write(uint8_t aData)
-{
- MOZ_ASSERT(!mBitCount);
- Write((uint8_t*)&aData, sizeof(uint8_t));
- return sizeof(uint8_t);
-}
-
-uint32_t
-ISOControl::GetBufPos()
-{
- uint32_t len = mOutBuffers.Length();
- uint32_t pos = 0;
- for (uint32_t i = 0; i < len; i++) {
- pos += mOutBuffers.ElementAt(i).Length();
- }
- return pos;
-}
-
-uint32_t
-ISOControl::WriteFourCC(const char* aType)
-{
- // Bit operation should be aligned to byte before writing any byte data.
- MOZ_ASSERT(!mBitCount);
-
- uint32_t size = strlen(aType);
- if (size == 4) {
- return Write((uint8_t*)aType, size);
- }
-
- return 0;
-}
-
-nsresult
-ISOControl::GenerateFtyp()
-{
- nsresult rv;
- uint32_t size;
- nsAutoPtr<FileTypeBox> type_box(new FileTypeBox(this));
- rv = type_box->Generate(&size);
- NS_ENSURE_SUCCESS(rv, rv);
- rv = type_box->Write();
- NS_ENSURE_SUCCESS(rv, rv);
- return NS_OK;
-}
-
-nsresult
-ISOControl::GenerateMoov()
-{
- nsresult rv;
- uint32_t size;
- nsAutoPtr<MovieBox> moov_box(new MovieBox(this));
- rv = moov_box->Generate(&size);
- NS_ENSURE_SUCCESS(rv, rv);
- rv = moov_box->Write();
- NS_ENSURE_SUCCESS(rv, rv);
- return NS_OK;
-}
-
-nsresult
-ISOControl::GenerateMoof(uint32_t aTrackType)
-{
- mFragNum++;
-
- nsresult rv;
- uint32_t size;
- uint64_t first_sample_offset = mOutputSize;
- nsAutoPtr<MovieFragmentBox> moof_box(new MovieFragmentBox(aTrackType, this));
- nsAutoPtr<MediaDataBox> mdat_box(new MediaDataBox(aTrackType, this));
-
- rv = moof_box->Generate(&size);
- NS_ENSURE_SUCCESS(rv, rv);
- first_sample_offset += size;
- rv = mdat_box->Generate(&size);
- NS_ENSURE_SUCCESS(rv, rv);
- first_sample_offset += mdat_box->FirstSampleOffsetInMediaDataBox();
-
- // correct offset info
- nsTArray<RefPtr<MuxerOperation>> tfhds;
- rv = moof_box->Find(NS_LITERAL_CSTRING("tfhd"), tfhds);
- NS_ENSURE_SUCCESS(rv, rv);
- uint32_t len = tfhds.Length();
- for (uint32_t i = 0; i < len; i++) {
- TrackFragmentHeaderBox* tfhd = (TrackFragmentHeaderBox*) tfhds.ElementAt(i).get();
- rv = tfhd->UpdateBaseDataOffset(first_sample_offset);
- NS_ENSURE_SUCCESS(rv, rv);
- }
-
- rv = moof_box->Write();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = mdat_box->Write();
- NS_ENSURE_SUCCESS(rv, rv);
-
- return NS_OK;
-}
-
-uint32_t
-ISOControl::GetTime()
-{
- return (uint64_t)time(nullptr) + iso_time_offset;
-}
-
-}
diff --git a/dom/media/encoder/fmp4_muxer/ISOControl.h b/dom/media/encoder/fmp4_muxer/ISOControl.h
deleted file mode 100644
index 3c445caee..000000000
--- a/dom/media/encoder/fmp4_muxer/ISOControl.h
+++ /dev/null
@@ -1,250 +0,0 @@
-/* -*- 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/. */
-
-#ifndef ISOCOMPOSITOR_H_
-#define ISOCOMPOSITOR_H_
-
-#include "mozilla/EndianUtils.h"
-#include "nsTArray.h"
-#include "ISOTrackMetadata.h"
-#include "EncodedFrameContainer.h"
-
-namespace mozilla {
-
-class Box;
-class ISOControl;
-
-/**
- * This class collects elementary stream data to form a fragment.
- * ISOMediaWriter will check if the data is enough; if yes, the corresponding
- * moof will be created and write to ISOControl.
- * Each audio and video has its own fragment and only one during the whole
- * life cycle, when a fragment is formed in ISOControl, Flush() needs to
- * be called to reset it.
- */
-class FragmentBuffer {
-public:
- // aTrackType: it could be Audio_Track or Video_Track.
- // aFragDuration: it is the fragment duration. (microsecond per unit)
- // Audio and video have the same fragment duration.
- FragmentBuffer(uint32_t aTrackType, uint32_t aFragDuration);
- ~FragmentBuffer();
-
- // Get samples of first fragment, that will swap all the elements in the
- // mFragArray[0] when aFlush = true, and caller is responsible for drop
- // EncodedFrame reference count.
- nsresult GetFirstFragment(nsTArray<RefPtr<EncodedFrame>>& aFragment,
- bool aFlush = false);
-
- // Add sample frame to the last element fragment of mFragArray. If sample
- // number is enough, it will append a new fragment element. And the new
- // sample will be added to the new fragment element of mFragArray.
- nsresult AddFrame(EncodedFrame* aFrame);
-
- // Get total sample size of first complete fragment size.
- uint32_t GetFirstFragmentSampleSize();
-
- // Get sample number of first complete fragment.
- uint32_t GetFirstFragmentSampleNumber();
-
- // Check if it accumulates enough frame data.
- // It returns true when data is enough to form a fragment.
- bool HasEnoughData();
-
- // Called by ISOMediaWriter when TrackEncoder has sent the last frame. The
- // remains frame data will form the last moof and move the state machine to
- // in ISOMediaWriter to last phrase.
- nsresult SetEndOfStream() {
- mEOS = true;
- return NS_OK;
- }
- bool EOS() { return mEOS; }
-
- // CSD (codec specific data), it is generated by encoder and the data depends
- // on codec type. This data will be sent as a special frame from encoder to
- // ISOMediaWriter and pass to this class via AddFrame().
- nsresult GetCSD(nsTArray<uint8_t>& aCSD);
-
- bool HasCSD() { return mCSDFrame; }
-
- uint32_t GetType() { return mTrackType; }
-
- void SetLastFragmentLastFrameTime(uint32_t aTime) {
- mLastFrameTimeOfLastFragment = aTime;
- }
-
- uint32_t GetLastFragmentLastFrameTime() {
- return mLastFrameTimeOfLastFragment;
- }
-
-private:
- uint32_t mTrackType;
-
- // Fragment duration, microsecond per unit.
- uint32_t mFragDuration;
-
- // Media start time, microsecond per unit.
- // Together with mFragDuration, mFragmentNumber and EncodedFrame->GetTimeStamp(),
- // when the difference between current frame time and mMediaStartTime is
- // exceeded current fragment ceiling timeframe, that means current fragment has
- // enough data and a new element in mFragArray will be added.
- uint64_t mMediaStartTime;
-
- // Current fragment number. It will be increase when a new element of
- // mFragArray is created.
- // Note:
- // It only means the fragment number of current accumulated frames, not
- // the current 'creating' fragment mFragNum in ISOControl.
- uint32_t mFragmentNumber;
-
- // The last frame time stamp of last fragment. It is for calculating the
- // play duration of first frame in current fragment. The frame duration is
- // defined as "current frame timestamp - last frame timestamp" here. So it
- // needs to keep the last timestamp of last fragment.
- uint32_t mLastFrameTimeOfLastFragment;
-
- // Array of fragments, each element has enough samples to form a
- // complete fragment.
- nsTArray<nsTArray<RefPtr<EncodedFrame>>> mFragArray;
-
- // Codec specific data frame, it will be generated by encoder and send to
- // ISOMediaWriter through WriteEncodedTrack(). The data will be vary depends
- // on codec type.
- RefPtr<EncodedFrame> mCSDFrame;
-
- // END_OF_STREAM from ContainerWriter
- bool mEOS;
-};
-
-/**
- * ISOControl will be carried to each box when box is created. It is the main
- * bridge for box to output stream to ContainerWriter and retrieve information.
- * ISOControl acts 3 different roles:
- * 1. Holds the pointer of audio metadata, video metadata, fragment and
- * pass them to boxes.
- * 2. Provide the functions to generate the base structure of MP4; they are
- * GenerateFtyp, GenerateMoov, GenerateMoof, and GenerateMfra.
- * 3. The actually writer used by MuxOperation::Write() in each box. It provides
- * writing methods for different kind of data; they are Write, WriteArray,
- * WriteBits...etc.
- */
-class ISOControl {
-
-friend class Box;
-
-public:
- ISOControl(uint32_t aMuxingType);
- ~ISOControl();
-
- nsresult GenerateFtyp();
- nsresult GenerateMoov();
- nsresult GenerateMoof(uint32_t aTrackType);
-
- // Swap elementary stream pointer to output buffers.
- uint32_t WriteAVData(nsTArray<uint8_t>& aArray);
-
- uint32_t Write(uint8_t* aBuf, uint32_t aSize);
-
- uint32_t Write(uint8_t aData);
-
- template <typename T>
- uint32_t Write(T aData) {
- MOZ_ASSERT(!mBitCount);
-
- aData = NativeEndian::swapToNetworkOrder(aData);
- Write((uint8_t*)&aData, sizeof(T));
- return sizeof(T);
- }
-
- template <typename T>
- uint32_t WriteArray(const T &aArray, uint32_t aSize) {
- MOZ_ASSERT(!mBitCount);
-
- uint32_t size = 0;
- for (uint32_t i = 0; i < aSize; i++) {
- size += Write(aArray[i]);
- }
- return size;
- }
-
- uint32_t WriteFourCC(const char* aType);
-
- // Bit writing. Note: it needs to be byte-boundary before using
- // others non-bit writing function.
- uint32_t WriteBits(uint64_t aBits, size_t aNumBits);
-
- // This is called by GetContainerData and swap all the buffers to aOutputBuffers.
- nsresult GetBufs(nsTArray<nsTArray<uint8_t>>* aOutputBufs);
-
- // Presentation time in seconds since midnight, Jan. 1, 1904, in UTC time.
- uint32_t GetTime();
-
- // current fragment number
- uint32_t GetCurFragmentNumber() { return mFragNum; }
-
- nsresult SetFragment(FragmentBuffer* aFragment);
- FragmentBuffer* GetFragment(uint32_t aType);
-
- uint32_t GetMuxingType() { return mMuxingType; }
-
- nsresult SetMetadata(TrackMetadataBase* aTrackMeta);
- nsresult GetAudioMetadata(RefPtr<AudioTrackMetadata>& aAudMeta);
- nsresult GetVideoMetadata(RefPtr<VideoTrackMetadata>& aVidMeta);
-
- // Track ID is the Metadata index in mMetaArray. It allows only 1 audio
- // track and 1 video track in this muxer. In this muxer, it is prohibt to have
- // mutiple audio track or video track in the same file.
- uint32_t GetTrackID(TrackMetadataBase::MetadataKind aKind);
- uint32_t GetNextTrackID();
-
- bool HasAudioTrack();
- bool HasVideoTrack();
-
-private:
- uint32_t GetBufPos();
- nsresult FlushBuf();
-
- // One of value in TYPE_XXX, defined in ISOMediaWriter.
- uint32_t mMuxingType;
-
- // Audio and video fragments are owned by ISOMediaWriter.
- // They don't need to worry about pointer going stale because ISOMediaWriter's
- // lifetime is longer than ISOControl.
- FragmentBuffer* mAudioFragmentBuffer;
- FragmentBuffer* mVideoFragmentBuffer;
-
- // Generated fragment number
- uint32_t mFragNum;
-
- // The (index + 1) will be the track ID.
- nsTArray<RefPtr<TrackMetadataBase>> mMetaArray;
-
- // Array of output buffers.
- // To save memory usage, audio/video sample will be swapped into a new element
- // of this array.
- //
- // For example,
- // mOutBuffers[0] --> boxes (allocated by muxer)
- // mOutBuffers[1] --> video raw data (allocated by encoder)
- // mOutBuffers[2] --> video raw data (allocated by encoder)
- // mOutBuffers[3] --> video raw data (allocated by encoder)
- // mOutBuffers[4] --> boxes (allocated by muxer)
- // mOutBuffers[5] --> audio raw data (allocated by encoder)
- // ...etc.
- //
- nsTArray<nsTArray<uint8_t>> mOutBuffers;
-
- // Accumulate output size from Write().
- uint64_t mOutputSize;
-
- // Bit writing operation. Note: the mBitCount should be 0 before any
- // byte-boundary writing method be called (Write(uint32_t), Write(uint16_t)...etc);
- // otherwise, there will be assertion on these functions.
- uint8_t mBitCount;
- uint8_t mBit;
-};
-
-}
-#endif
diff --git a/dom/media/encoder/fmp4_muxer/ISOMediaBoxes.cpp b/dom/media/encoder/fmp4_muxer/ISOMediaBoxes.cpp
deleted file mode 100644
index 32a0c577b..000000000
--- a/dom/media/encoder/fmp4_muxer/ISOMediaBoxes.cpp
+++ /dev/null
@@ -1,1550 +0,0 @@
-/* -*- 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 <climits>
-#include "TrackMetadataBase.h"
-#include "ISOMediaBoxes.h"
-#include "ISOControl.h"
-#include "ISOMediaWriter.h"
-#include "EncodedFrameContainer.h"
-#include "ISOTrackMetadata.h"
-#include "MP4ESDS.h"
-#include "AMRBox.h"
-#include "AVCBox.h"
-#include "EVRCBox.h"
-#include "VideoUtils.h"
-
-namespace mozilla {
-
-// 14496-12 6.2.2 'Data Types and fields'
-const uint32_t iso_matrix[] = { 0x00010000, 0, 0,
- 0, 0x00010000, 0,
- 0, 0, 0x40000000 };
-
-uint32_t
-set_sample_flags(bool aSync)
-{
- std::bitset<32> flags;
- flags.set(16, !aSync);
- return flags.to_ulong();
-}
-
-Box::BoxSizeChecker::BoxSizeChecker(ISOControl* aControl, uint32_t aSize)
-{
- mControl = aControl;
- ori_size = mControl->GetBufPos();
- box_size = aSize;
- MOZ_COUNT_CTOR(BoxSizeChecker);
-}
-
-Box::BoxSizeChecker::~BoxSizeChecker()
-{
- uint32_t cur_size = mControl->GetBufPos();
- if ((cur_size - ori_size) != box_size) {
- MOZ_ASSERT(false);
- }
-
- MOZ_COUNT_DTOR(BoxSizeChecker);
-}
-
-nsresult
-MediaDataBox::Generate(uint32_t* aBoxSize)
-{
- mFirstSampleOffset = size;
- mAllSampleSize = 0;
-
- if (mTrackType & Audio_Track) {
- FragmentBuffer* frag = mControl->GetFragment(Audio_Track);
- mAllSampleSize += frag->GetFirstFragmentSampleSize();
- }
- if (mTrackType & Video_Track) {
- FragmentBuffer* frag = mControl->GetFragment(Video_Track);
- mAllSampleSize += frag->GetFirstFragmentSampleSize();
- }
-
- size += mAllSampleSize;
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-MediaDataBox::Write()
-{
- nsresult rv;
- BoxSizeChecker checker(mControl, size);
- Box::Write();
- nsTArray<uint32_t> types;
- types.AppendElement(Audio_Track);
- types.AppendElement(Video_Track);
-
- for (uint32_t l = 0; l < types.Length(); l++) {
- if (mTrackType & types[l]) {
- FragmentBuffer* frag = mControl->GetFragment(types[l]);
- nsTArray<RefPtr<EncodedFrame>> frames;
-
- // Here is the last time we get fragment frames, flush it!
- rv = frag->GetFirstFragment(frames, true);
- NS_ENSURE_SUCCESS(rv, rv);
-
- uint32_t len = frames.Length();
- for (uint32_t i = 0; i < len; i++) {
- nsTArray<uint8_t> frame_buffer;
- frames.ElementAt(i)->SwapOutFrameData(frame_buffer);
- mControl->WriteAVData(frame_buffer);
- }
- }
- }
-
- return NS_OK;
-}
-
-MediaDataBox::MediaDataBox(uint32_t aTrackType, ISOControl* aControl)
- : Box(NS_LITERAL_CSTRING("mdat"), aControl)
- , mAllSampleSize(0)
- , mFirstSampleOffset(0)
- , mTrackType(aTrackType)
-{
- MOZ_COUNT_CTOR(MediaDataBox);
-}
-
-MediaDataBox::~MediaDataBox()
-{
- MOZ_COUNT_DTOR(MediaDataBox);
-}
-
-uint32_t
-TrackRunBox::fillSampleTable()
-{
- uint32_t table_size = 0;
- nsresult rv;
- nsTArray<RefPtr<EncodedFrame>> frames;
- FragmentBuffer* frag = mControl->GetFragment(mTrackType);
-
- rv = frag->GetFirstFragment(frames);
- if (NS_FAILED(rv)) {
- return 0;
- }
- uint32_t len = frames.Length();
- sample_info_table = MakeUnique<tbl[]>(len);
- // Create sample table according to 14496-12 8.8.8.2.
- for (uint32_t i = 0; i < len; i++) {
- // Sample size.
- sample_info_table[i].sample_size = 0;
- if (flags.to_ulong() & flags_sample_size_present) {
- sample_info_table[i].sample_size = frames.ElementAt(i)->GetFrameData().Length();
- mAllSampleSize += sample_info_table[i].sample_size;
- table_size += sizeof(uint32_t);
- }
-
- // Sample flags.
- sample_info_table[i].sample_flags = 0;
- if (flags.to_ulong() & flags_sample_flags_present) {
- sample_info_table[i].sample_flags =
- set_sample_flags(
- (frames.ElementAt(i)->GetFrameType() == EncodedFrame::AVC_I_FRAME));
- table_size += sizeof(uint32_t);
- }
-
- // Sample duration.
- sample_info_table[i].sample_duration = 0;
- if (flags.to_ulong() & flags_sample_duration_present) {
- // Calculate each frame's duration, it is decided by "current frame
- // timestamp - last frame timestamp".
- uint64_t frame_time = 0;
- if (i == 0) {
- frame_time = frames.ElementAt(i)->GetTimeStamp() -
- frag->GetLastFragmentLastFrameTime();
- } else {
- frame_time = frames.ElementAt(i)->GetTimeStamp() -
- frames.ElementAt(i - 1)->GetTimeStamp();
- // Keep the last frame time of current fagment, it will be used to calculate
- // the first frame duration of next fragment.
- if ((len - 1) == i) {
- frag->SetLastFragmentLastFrameTime(frames.ElementAt(i)->GetTimeStamp());
- }
- }
-
- // In TrackRunBox, there should be exactly one type, either audio or video.
- MOZ_ASSERT((mTrackType & Video_Track) ^ (mTrackType & Audio_Track));
- sample_info_table[i].sample_duration = (mTrackType & Video_Track ?
- frame_time * mVideoMeta->GetVideoClockRate() / USECS_PER_S :
- frame_time * mAudioMeta->GetAudioSampleRate() / USECS_PER_S);
-
- table_size += sizeof(uint32_t);
- }
-
- sample_info_table[i].sample_composition_time_offset = 0;
- }
- return table_size;
-}
-
-nsresult
-TrackRunBox::Generate(uint32_t* aBoxSize)
-{
- FragmentBuffer* frag = mControl->GetFragment(mTrackType);
- sample_count = frag->GetFirstFragmentSampleNumber();
- size += sizeof(sample_count);
-
- // data_offset needs to be updated if there is other
- // TrackRunBox before this one.
- if (flags.to_ulong() & flags_data_offset_present) {
- data_offset = 0;
- size += sizeof(data_offset);
- }
- size += fillSampleTable();
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-TrackRunBox::SetDataOffset(uint32_t aOffset)
-{
- data_offset = aOffset;
- return NS_OK;
-}
-
-nsresult
-TrackRunBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(sample_count);
- if (flags.to_ulong() & flags_data_offset_present) {
- mControl->Write(data_offset);
- }
- for (uint32_t i = 0; i < sample_count; i++) {
- if (flags.to_ulong() & flags_sample_duration_present) {
- mControl->Write(sample_info_table[i].sample_duration);
- }
- if (flags.to_ulong() & flags_sample_size_present) {
- mControl->Write(sample_info_table[i].sample_size);
- }
- if (flags.to_ulong() & flags_sample_flags_present) {
- mControl->Write(sample_info_table[i].sample_flags);
- }
- }
-
- return NS_OK;
-}
-
-TrackRunBox::TrackRunBox(uint32_t aType, uint32_t aFlags, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("trun"), 0, aFlags, aControl)
- , sample_count(0)
- , data_offset(0)
- , first_sample_flags(0)
- , mAllSampleSize(0)
- , mTrackType(aType)
-{
- MOZ_COUNT_CTOR(TrackRunBox);
-}
-
-TrackRunBox::~TrackRunBox()
-{
- MOZ_COUNT_DTOR(TrackRunBox);
-}
-
-nsresult
-TrackFragmentHeaderBox::UpdateBaseDataOffset(uint64_t aOffset)
-{
- base_data_offset = aOffset;
- return NS_OK;
-}
-
-nsresult
-TrackFragmentHeaderBox::Generate(uint32_t* aBoxSize)
-{
- track_ID = (mTrackType == Audio_Track ?
- mControl->GetTrackID(mAudioMeta->GetKind()) :
- mControl->GetTrackID(mVideoMeta->GetKind()));
- size += sizeof(track_ID);
-
- if (flags.to_ulong() & base_data_offset_present) {
- // base_data_offset needs to add size of 'trun', 'tfhd' and
- // header of 'mdat' later.
- base_data_offset = 0;
- size += sizeof(base_data_offset);
- }
- if (flags.to_ulong() & default_sample_duration_present) {
- if (mTrackType == Video_Track) {
- if (!mVideoMeta->GetVideoFrameRate()) {
- // 0 means frame rate is variant, so it is wrong to write
- // default_sample_duration.
- MOZ_ASSERT(0);
- default_sample_duration = 0;
- } else {
- default_sample_duration = mVideoMeta->GetVideoClockRate() / mVideoMeta->GetVideoFrameRate();
- }
- } else if (mTrackType == Audio_Track) {
- default_sample_duration = mAudioMeta->GetAudioFrameDuration();
- } else {
- MOZ_ASSERT(0);
- return NS_ERROR_FAILURE;
- }
- size += sizeof(default_sample_duration);
- }
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-TrackFragmentHeaderBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(track_ID);
- if (flags.to_ulong() & base_data_offset_present) {
- mControl->Write(base_data_offset);
- }
- if (flags.to_ulong() & default_sample_duration_present) {
- mControl->Write(default_sample_duration);
- }
- return NS_OK;
-}
-
-TrackFragmentHeaderBox::TrackFragmentHeaderBox(uint32_t aType,
- uint32_t aFlags,
- ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("tfhd"), 0, aFlags, aControl)
- , track_ID(0)
- , base_data_offset(0)
- , default_sample_duration(0)
-{
- mTrackType = aType;
- MOZ_COUNT_CTOR(TrackFragmentHeaderBox);
-}
-
-TrackFragmentHeaderBox::~TrackFragmentHeaderBox()
-{
- MOZ_COUNT_DTOR(TrackFragmentHeaderBox);
-}
-
-TrackFragmentBox::TrackFragmentBox(uint32_t aType, ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("traf"), aControl)
- , mTrackType(aType)
-{
- // Flags in TrackFragmentHeaderBox.
- uint32_t tf_flags = base_data_offset_present;
-
- // Ideally, audio encoder generates audio frame in const rate. However, some
- // audio encoders don't do it so the audio frame duration needs to be checked
- // here.
- if ((mTrackType & Audio_Track) && mAudioMeta->GetAudioFrameDuration()) {
- tf_flags |= default_sample_duration_present;
- }
-
- boxes.AppendElement(new TrackFragmentHeaderBox(aType, tf_flags, aControl));
-
- // Always adds flags_data_offset_present in each TrackRunBox, Android
- // parser requires this flag to calculate the correct bitstream offset.
- uint32_t tr_flags = flags_sample_size_present | flags_data_offset_present;
-
- // Flags in TrackRunBox.
- // If there is no default sample duration exists, each frame duration needs to
- // be recored in the TrackRunBox.
- tr_flags |= (tf_flags & default_sample_duration_present ? 0 : flags_sample_duration_present);
-
- // For video, add sample_flags to record I frame.
- tr_flags |= (mTrackType & Video_Track ? flags_sample_flags_present : 0);
-
- boxes.AppendElement(new TrackRunBox(mTrackType, tr_flags, aControl));
- MOZ_COUNT_CTOR(TrackFragmentBox);
-}
-
-TrackFragmentBox::~TrackFragmentBox()
-{
- MOZ_COUNT_DTOR(TrackFragmentBox);
-}
-
-nsresult
-MovieFragmentHeaderBox::Generate(uint32_t* aBoxSize)
-{
- sequence_number = mControl->GetCurFragmentNumber();
- size += sizeof(sequence_number);
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-MovieFragmentHeaderBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(sequence_number);
- return NS_OK;
-}
-
-MovieFragmentHeaderBox::MovieFragmentHeaderBox(uint32_t aTrackType,
- ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("mfhd"), 0, 0, aControl)
- , sequence_number(0)
- , mTrackType(aTrackType)
-{
- MOZ_COUNT_CTOR(MovieFragmentHeaderBox);
-}
-
-MovieFragmentHeaderBox::~MovieFragmentHeaderBox()
-{
- MOZ_COUNT_DTOR(MovieFragmentHeaderBox);
-}
-
-MovieFragmentBox::MovieFragmentBox(uint32_t aType, ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("moof"), aControl)
- , mTrackType(aType)
-{
- boxes.AppendElement(new MovieFragmentHeaderBox(mTrackType, aControl));
-
- if (mTrackType & Audio_Track) {
- boxes.AppendElement(
- new TrackFragmentBox(Audio_Track, aControl));
- }
- if (mTrackType & Video_Track) {
- boxes.AppendElement(
- new TrackFragmentBox(Video_Track, aControl));
- }
- MOZ_COUNT_CTOR(MovieFragmentBox);
-}
-
-MovieFragmentBox::~MovieFragmentBox()
-{
- MOZ_COUNT_DTOR(MovieFragmentBox);
-}
-
-nsresult
-MovieFragmentBox::Generate(uint32_t* aBoxSize)
-{
- nsresult rv = DefaultContainerImpl::Generate(aBoxSize);
- NS_ENSURE_SUCCESS(rv, rv);
-
- // Correct data_offset if there are both audio and video track in
- // this fragment. This offset means the offset in the MediaDataBox.
- if (mTrackType & (Audio_Track | Video_Track)) {
- nsTArray<RefPtr<MuxerOperation>> truns;
- rv = Find(NS_LITERAL_CSTRING("trun"), truns);
- NS_ENSURE_SUCCESS(rv, rv);
- uint32_t len = truns.Length();
- uint32_t data_offset = 0;
- for (uint32_t i = 0; i < len; i++) {
- TrackRunBox* trun = (TrackRunBox*) truns.ElementAt(i).get();
- rv = trun->SetDataOffset(data_offset);
- NS_ENSURE_SUCCESS(rv, rv);
- data_offset += trun->GetAllSampleSize();
- }
- }
-
- return NS_OK;
-}
-
-nsresult
-TrackExtendsBox::Generate(uint32_t* aBoxSize)
-{
- track_ID = (mTrackType == Audio_Track ?
- mControl->GetTrackID(mAudioMeta->GetKind()) :
- mControl->GetTrackID(mVideoMeta->GetKind()));
-
- if (mTrackType == Audio_Track) {
- default_sample_description_index = 1;
- default_sample_duration = mAudioMeta->GetAudioFrameDuration();
- default_sample_size = mAudioMeta->GetAudioFrameSize();
- default_sample_flags = set_sample_flags(1);
- } else if (mTrackType == Video_Track) {
- default_sample_description_index = 1;
- // Video meta data has assigned framerate, it implies that this video's
- // frame rate should be fixed.
- if (mVideoMeta->GetVideoFrameRate()) {
- default_sample_duration =
- mVideoMeta->GetVideoClockRate() / mVideoMeta->GetVideoFrameRate();
- }
- default_sample_size = 0;
- default_sample_flags = set_sample_flags(0);
- } else {
- MOZ_ASSERT(0);
- return NS_ERROR_FAILURE;
- }
-
- size += sizeof(track_ID) +
- sizeof(default_sample_description_index) +
- sizeof(default_sample_duration) +
- sizeof(default_sample_size) +
- sizeof(default_sample_flags);
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-TrackExtendsBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(track_ID);
- mControl->Write(default_sample_description_index);
- mControl->Write(default_sample_duration);
- mControl->Write(default_sample_size);
- mControl->Write(default_sample_flags);
-
- return NS_OK;
-}
-
-TrackExtendsBox::TrackExtendsBox(uint32_t aType, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("trex"), 0, 0, aControl)
- , track_ID(0)
- , default_sample_description_index(0)
- , default_sample_duration(0)
- , default_sample_size(0)
- , default_sample_flags(0)
- , mTrackType(aType)
-{
- MOZ_COUNT_CTOR(TrackExtendsBox);
-}
-
-TrackExtendsBox::~TrackExtendsBox()
-{
- MOZ_COUNT_DTOR(TrackExtendsBox);
-}
-
-MovieExtendsBox::MovieExtendsBox(ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("mvex"), aControl)
-{
- if (mAudioMeta) {
- boxes.AppendElement(new TrackExtendsBox(Audio_Track, aControl));
- }
- if (mVideoMeta) {
- boxes.AppendElement(new TrackExtendsBox(Video_Track, aControl));
- }
- MOZ_COUNT_CTOR(MovieExtendsBox);
-}
-
-MovieExtendsBox::~MovieExtendsBox()
-{
- MOZ_COUNT_DTOR(MovieExtendsBox);
-}
-
-nsresult
-ChunkOffsetBox::Generate(uint32_t* aBoxSize)
-{
- // We don't need time to sample table in fragmented mp4.
- entry_count = 0;
- size += sizeof(entry_count);
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-ChunkOffsetBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(entry_count);
- return NS_OK;
-}
-
-ChunkOffsetBox::ChunkOffsetBox(uint32_t aType, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("stco"), 0, 0, aControl)
- , entry_count(0)
-{
- MOZ_COUNT_CTOR(ChunkOffsetBox);
-}
-
-ChunkOffsetBox::~ChunkOffsetBox()
-{
- MOZ_COUNT_DTOR(ChunkOffsetBox);
-}
-
-nsresult
-SampleToChunkBox::Generate(uint32_t* aBoxSize)
-{
- // We don't need time to sample table in fragmented mp4
- entry_count = 0;
- size += sizeof(entry_count);
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-SampleToChunkBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(entry_count);
- return NS_OK;
-}
-
-SampleToChunkBox::SampleToChunkBox(uint32_t aType, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("stsc"), 0, 0, aControl)
- , entry_count(0)
-{
- MOZ_COUNT_CTOR(SampleToChunkBox);
-}
-
-SampleToChunkBox::~SampleToChunkBox()
-{
- MOZ_COUNT_DTOR(SampleToChunkBox);
-}
-
-nsresult
-TimeToSampleBox::Generate(uint32_t* aBoxSize)
-{
- // We don't need time to sample table in fragmented mp4.
- entry_count = 0;
- size += sizeof(entry_count);
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-TimeToSampleBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(entry_count);
- return NS_OK;
-}
-
-TimeToSampleBox::TimeToSampleBox(uint32_t aType, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("stts"), 0, 0, aControl)
- , entry_count(0)
-{
- MOZ_COUNT_CTOR(TimeToSampleBox);
-}
-
-TimeToSampleBox::~TimeToSampleBox()
-{
- MOZ_COUNT_DTOR(TimeToSampleBox);
-}
-
-nsresult
-SampleDescriptionBox::Generate(uint32_t* aBoxSize)
-{
- entry_count = 1;
- size += sizeof(entry_count);
-
- nsresult rv;
- uint32_t box_size;
- rv = sample_entry_box->Generate(&box_size);
- NS_ENSURE_SUCCESS(rv, rv);
- size += box_size;
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-SampleDescriptionBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- nsresult rv;
- mControl->Write(entry_count);
- rv = sample_entry_box->Write();
- NS_ENSURE_SUCCESS(rv, rv);
-
- return NS_OK;
-}
-
-SampleDescriptionBox::SampleDescriptionBox(uint32_t aType, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("stsd"), 0, 0, aControl)
- , entry_count(0)
-{
- mTrackType = aType;
-
- switch (mTrackType) {
- case Audio_Track:
- {
- CreateAudioSampleEntry(sample_entry_box);
- }
- break;
- case Video_Track:
- {
- CreateVideoSampleEntry(sample_entry_box);
- }
- break;
- }
- MOZ_ASSERT(sample_entry_box);
- MOZ_COUNT_CTOR(SampleDescriptionBox);
-}
-
-nsresult
-SampleDescriptionBox::CreateAudioSampleEntry(RefPtr<SampleEntryBox>& aSampleEntry)
-{
- if (mAudioMeta->GetKind() == TrackMetadataBase::METADATA_AMR) {
- aSampleEntry = new AMRSampleEntry(mControl);
- } else if (mAudioMeta->GetKind() == TrackMetadataBase::METADATA_AAC) {
- aSampleEntry = new MP4AudioSampleEntry(mControl);
- } else if (mAudioMeta->GetKind() == TrackMetadataBase::METADATA_EVRC) {
- aSampleEntry = new EVRCSampleEntry(mControl);
- } else {
- MOZ_ASSERT(0);
- }
- return NS_OK;
-}
-
-nsresult
-SampleDescriptionBox::CreateVideoSampleEntry(RefPtr<SampleEntryBox>& aSampleEntry)
-{
- if (mVideoMeta->GetKind() == TrackMetadataBase::METADATA_AVC) {
- aSampleEntry = new AVCSampleEntry(mControl);
- } else {
- MOZ_ASSERT(0);
- }
- return NS_OK;
-}
-
-SampleDescriptionBox::~SampleDescriptionBox()
-{
- MOZ_COUNT_DTOR(SampleDescriptionBox);
-}
-
-nsresult
-SampleSizeBox::Generate(uint32_t* aBoxSize)
-{
- size += sizeof(sample_size) +
- sizeof(sample_count);
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-SampleSizeBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(sample_size);
- mControl->Write(sample_count);
- return NS_OK;
-}
-
-SampleSizeBox::SampleSizeBox(ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("stsz"), 0, 0, aControl)
- , sample_size(0)
- , sample_count(0)
-{
- MOZ_COUNT_CTOR(SampleSizeBox);
-}
-
-SampleSizeBox::~SampleSizeBox()
-{
- MOZ_COUNT_DTOR(SampleSizeBox);
-}
-
-SampleTableBox::SampleTableBox(uint32_t aType, ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("stbl"), aControl)
-{
- boxes.AppendElement(new SampleDescriptionBox(aType, aControl));
- boxes.AppendElement(new TimeToSampleBox(aType, aControl));
- boxes.AppendElement(new SampleToChunkBox(aType, aControl));
- boxes.AppendElement(new SampleSizeBox(aControl));
- boxes.AppendElement(new ChunkOffsetBox(aType, aControl));
- MOZ_COUNT_CTOR(SampleTableBox);
-}
-
-SampleTableBox::~SampleTableBox()
-{
- MOZ_COUNT_DTOR(SampleTableBox);
-}
-
-nsresult
-DataEntryUrlBox::Generate(uint32_t* aBoxSize)
-{
- // location is null here, do nothing
- size += location.Length();
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-DataEntryUrlBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- return NS_OK;
-}
-
-DataEntryUrlBox::DataEntryUrlBox()
- : FullBox(NS_LITERAL_CSTRING("url "), 0, 0, (ISOControl*) nullptr)
-{
- MOZ_COUNT_CTOR(DataEntryUrlBox);
-}
-
-DataEntryUrlBox::DataEntryUrlBox(ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("url "), 0, flags_media_at_the_same_file, aControl)
-{
- MOZ_COUNT_CTOR(DataEntryUrlBox);
-}
-
-DataEntryUrlBox::DataEntryUrlBox(const DataEntryUrlBox& aBox)
- : FullBox(aBox.boxType, aBox.version, aBox.flags.to_ulong(), aBox.mControl)
-{
- location = aBox.location;
- MOZ_COUNT_CTOR(DataEntryUrlBox);
-}
-
-DataEntryUrlBox::~DataEntryUrlBox()
-{
- MOZ_COUNT_DTOR(DataEntryUrlBox);
-}
-
-nsresult DataReferenceBox::Generate(uint32_t* aBoxSize)
-{
- entry_count = 1; // only allow on entry here
- size += sizeof(uint32_t);
-
- for (uint32_t i = 0; i < entry_count; i++) {
- uint32_t box_size = 0;
- DataEntryUrlBox* url = new DataEntryUrlBox(mControl);
- url->Generate(&box_size);
- size += box_size;
- urls.AppendElement(url);
- }
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult DataReferenceBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(entry_count);
-
- for (uint32_t i = 0; i < entry_count; i++) {
- urls[i]->Write();
- }
-
- return NS_OK;
-}
-
-DataReferenceBox::DataReferenceBox(ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("dref"), 0, 0, aControl)
- , entry_count(0)
-{
- MOZ_COUNT_CTOR(DataReferenceBox);
-}
-
-DataReferenceBox::~DataReferenceBox()
-{
- MOZ_COUNT_DTOR(DataReferenceBox);
-}
-
-DataInformationBox::DataInformationBox(ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("dinf"), aControl)
-{
- boxes.AppendElement(new DataReferenceBox(aControl));
- MOZ_COUNT_CTOR(DataInformationBox);
-}
-
-DataInformationBox::~DataInformationBox()
-{
- MOZ_COUNT_DTOR(DataInformationBox);
-}
-
-nsresult
-VideoMediaHeaderBox::Generate(uint32_t* aBoxSize)
-{
- size += sizeof(graphicsmode) +
- sizeof(opcolor);
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-VideoMediaHeaderBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(graphicsmode);
- mControl->WriteArray(opcolor, 3);
- return NS_OK;
-}
-
-VideoMediaHeaderBox::VideoMediaHeaderBox(ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("vmhd"), 0, 1, aControl)
- , graphicsmode(0)
-{
- memset(opcolor, 0 , sizeof(opcolor));
- MOZ_COUNT_CTOR(VideoMediaHeaderBox);
-}
-
-VideoMediaHeaderBox::~VideoMediaHeaderBox()
-{
- MOZ_COUNT_DTOR(VideoMediaHeaderBox);
-}
-
-nsresult
-SoundMediaHeaderBox::Generate(uint32_t* aBoxSize)
-{
- balance = 0;
- reserved = 0;
- size += sizeof(balance) +
- sizeof(reserved);
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-SoundMediaHeaderBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(balance);
- mControl->Write(reserved);
-
- return NS_OK;
-}
-
-SoundMediaHeaderBox::SoundMediaHeaderBox(ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("smhd"), 0, 0, aControl)
-{
- MOZ_COUNT_CTOR(SoundMediaHeaderBox);
-}
-
-SoundMediaHeaderBox::~SoundMediaHeaderBox()
-{
- MOZ_COUNT_DTOR(SoundMediaHeaderBox);
-}
-
-MediaInformationBox::MediaInformationBox(uint32_t aType, ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("minf"), aControl)
-{
- mTrackType = aType;
-
- if (mTrackType == Audio_Track) {
- boxes.AppendElement(new SoundMediaHeaderBox(aControl));
- } else if (mTrackType == Video_Track) {
- boxes.AppendElement(new VideoMediaHeaderBox(aControl));
- } else {
- MOZ_ASSERT(0);
- }
-
- boxes.AppendElement(new DataInformationBox(aControl));
- boxes.AppendElement(new SampleTableBox(aType, aControl));
- MOZ_COUNT_CTOR(MediaInformationBox);
-}
-
-MediaInformationBox::~MediaInformationBox()
-{
- MOZ_COUNT_DTOR(MediaInformationBox);
-}
-
-nsresult
-HandlerBox::Generate(uint32_t* aBoxSize)
-{
- pre_defined = 0;
- if (mTrackType == Audio_Track) {
- handler_type = FOURCC('s', 'o', 'u', 'n');
- } else if (mTrackType == Video_Track) {
- handler_type = FOURCC('v', 'i', 'd', 'e');
- }
-
- size += sizeof(pre_defined) +
- sizeof(handler_type) +
- sizeof(reserved);
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-HandlerBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(pre_defined);
- mControl->Write(handler_type);
- mControl->WriteArray(reserved, 3);
-
- return NS_OK;
-}
-
-HandlerBox::HandlerBox(uint32_t aType, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("hdlr"), 0, 0, aControl)
- , pre_defined(0)
- , handler_type(0)
-{
- mTrackType = aType;
- memset(reserved, 0 , sizeof(reserved));
- MOZ_COUNT_CTOR(HandlerBox);
-}
-
-HandlerBox::~HandlerBox()
-{
- MOZ_COUNT_DTOR(HandlerBox);
-}
-
-MediaHeaderBox::MediaHeaderBox(uint32_t aType, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("mdhd"), 0, 0, aControl)
- , creation_time(0)
- , modification_time(0)
- , timescale(0)
- , duration(0)
- , pad(0)
- , lang1(0)
- , lang2(0)
- , lang3(0)
- , pre_defined(0)
-{
- mTrackType = aType;
- MOZ_COUNT_CTOR(MediaHeaderBox);
-}
-
-MediaHeaderBox::~MediaHeaderBox()
-{
- MOZ_COUNT_DTOR(MediaHeaderBox);
-}
-
-uint32_t
-MediaHeaderBox::GetTimeScale()
-{
- if (mTrackType == Audio_Track) {
- return mAudioMeta->GetAudioSampleRate();
- }
-
- return mVideoMeta->GetVideoClockRate();
-}
-
-nsresult
-MediaHeaderBox::Generate(uint32_t* aBoxSize)
-{
- creation_time = mControl->GetTime();
- modification_time = mControl->GetTime();
- timescale = GetTimeScale();
- duration = 0; // fragmented mp4
-
- pad = 0;
- lang1 = 'u' - 0x60; // "und" underdetermined language
- lang2 = 'n' - 0x60;
- lang3 = 'd' - 0x60;
- size += (pad.size() + lang1.size() + lang2.size() + lang3.size()) / CHAR_BIT;
-
- pre_defined = 0;
- size += sizeof(creation_time) +
- sizeof(modification_time) +
- sizeof(timescale) +
- sizeof(duration) +
- sizeof(pre_defined);
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-MediaHeaderBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(creation_time);
- mControl->Write(modification_time);
- mControl->Write(timescale);
- mControl->Write(duration);
- mControl->WriteBits(pad.to_ulong(), pad.size());
- mControl->WriteBits(lang1.to_ulong(), lang1.size());
- mControl->WriteBits(lang2.to_ulong(), lang2.size());
- mControl->WriteBits(lang3.to_ulong(), lang3.size());
- mControl->Write(pre_defined);
-
- return NS_OK;
-}
-
-MovieBox::MovieBox(ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("moov"), aControl)
-{
- boxes.AppendElement(new MovieHeaderBox(aControl));
- if (aControl->HasAudioTrack()) {
- boxes.AppendElement(new TrackBox(Audio_Track, aControl));
- }
- if (aControl->HasVideoTrack()) {
- boxes.AppendElement(new TrackBox(Video_Track, aControl));
- }
- boxes.AppendElement(new MovieExtendsBox(aControl));
- MOZ_COUNT_CTOR(MovieBox);
-}
-
-MovieBox::~MovieBox()
-{
- MOZ_COUNT_DTOR(MovieBox);
-}
-
-nsresult
-MovieHeaderBox::Generate(uint32_t* aBoxSize)
-{
- creation_time = mControl->GetTime();
- modification_time = mControl->GetTime();
- timescale = GetTimeScale();
- duration = 0; // The duration is always 0 in fragmented mp4.
- next_track_ID = mControl->GetNextTrackID();
-
- size += sizeof(next_track_ID) +
- sizeof(creation_time) +
- sizeof(modification_time) +
- sizeof(timescale) +
- sizeof(duration) +
- sizeof(rate) +
- sizeof(volume) +
- sizeof(reserved16) +
- sizeof(reserved32) +
- sizeof(matrix) +
- sizeof(pre_defined);
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-MovieHeaderBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(creation_time);
- mControl->Write(modification_time);
- mControl->Write(timescale);
- mControl->Write(duration);
- mControl->Write(rate);
- mControl->Write(volume);
- mControl->Write(reserved16);
- mControl->WriteArray(reserved32, 2);
- mControl->WriteArray(matrix, 9);
- mControl->WriteArray(pre_defined, 6);
- mControl->Write(next_track_ID);
-
- return NS_OK;
-}
-
-uint32_t
-MovieHeaderBox::GetTimeScale()
-{
- // Only audio track in container.
- if (mAudioMeta && !mVideoMeta) {
- return mAudioMeta->GetAudioSampleRate();
- }
-
- // return video rate
- return mVideoMeta->GetVideoClockRate();
-}
-
-MovieHeaderBox::~MovieHeaderBox()
-{
- MOZ_COUNT_DTOR(MovieHeaderBox);
-}
-
-MovieHeaderBox::MovieHeaderBox(ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("mvhd"), 0, 0, aControl)
- , creation_time(0)
- , modification_time(0)
- , timescale(90000)
- , duration(0)
- , rate(0x00010000)
- , volume(0x0100)
- , reserved16(0)
- , next_track_ID(1)
-{
- memcpy(matrix, iso_matrix, sizeof(matrix));
- memset(reserved32, 0, sizeof(reserved32));
- memset(pre_defined, 0, sizeof(pre_defined));
- MOZ_COUNT_CTOR(MovieHeaderBox);
-}
-
-TrackHeaderBox::TrackHeaderBox(uint32_t aType, ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("tkhd"), 0,
- flags_track_enabled | flags_track_in_movie | flags_track_in_preview,
- aControl)
- , creation_time(0)
- , modification_time(0)
- , track_ID(0)
- , reserved(0)
- , duration(0)
- , layer(0)
- , alternate_group(0)
- , volume(0)
- , reserved3(0)
- , width(0)
- , height(0)
-{
- mTrackType = aType;
- memcpy(matrix, iso_matrix, sizeof(matrix));
- memset(reserved2, 0, sizeof(reserved2));
- MOZ_COUNT_CTOR(TrackHeaderBox);
-}
-
-TrackHeaderBox::~TrackHeaderBox()
-{
- MOZ_COUNT_DTOR(TrackHeaderBox);
-}
-
-nsresult
-TrackHeaderBox::Generate(uint32_t* aBoxSize)
-{
- creation_time = mControl->GetTime();
- modification_time = mControl->GetTime();
- track_ID = (mTrackType == Audio_Track ?
- mControl->GetTrackID(mAudioMeta->GetKind()) :
- mControl->GetTrackID(mVideoMeta->GetKind()));
- // fragmented mp4
- duration = 0;
-
- // volume, audiotrack is always 0x0100 in 14496-12 8.3.2.2
- volume = (mTrackType == Audio_Track ? 0x0100 : 0);
-
- if (mTrackType == Video_Track) {
- width = mVideoMeta->GetVideoDisplayWidth() << 16;
- height = mVideoMeta->GetVideoDisplayHeight() << 16;
- // Check display size, using the pixel size if any of them is invalid.
- if (!width || !height) {
- width = mVideoMeta->GetVideoWidth() << 16;
- height = mVideoMeta->GetVideoHeight() << 16;
- }
- }
-
- size += sizeof(creation_time) +
- sizeof(modification_time) +
- sizeof(track_ID) +
- sizeof(reserved) +
- sizeof(duration) +
- sizeof(reserved2) +
- sizeof(layer) +
- sizeof(alternate_group) +
- sizeof(volume) +
- sizeof(reserved3) +
- sizeof(matrix) +
- sizeof(width) +
- sizeof(height);
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-TrackHeaderBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- mControl->Write(creation_time);
- mControl->Write(modification_time);
- mControl->Write(track_ID);
- mControl->Write(reserved);
- mControl->Write(duration);
- mControl->WriteArray(reserved2, 2);
- mControl->Write(layer);
- mControl->Write(alternate_group);
- mControl->Write(volume);
- mControl->Write(reserved3);
- mControl->WriteArray(matrix, 9);
- mControl->Write(width);
- mControl->Write(height);
-
- return NS_OK;
-}
-
-nsresult
-FileTypeBox::Generate(uint32_t* aBoxSize)
-{
- minor_version = 0;
-
- if (mControl->GetMuxingType() == ISOMediaWriter::TYPE_FRAG_MP4) {
- if (!mControl->HasVideoTrack() && mControl->HasAudioTrack()) {
- major_brand = "M4A ";
- } else {
- major_brand = "MP42";
- }
- compatible_brands.AppendElement("mp42");
- compatible_brands.AppendElement("isom");
- } else if (mControl->GetMuxingType() == ISOMediaWriter::TYPE_FRAG_3GP) {
- major_brand = "3gp9";
- // According to 3GPP TS 26.244 V12.2.0, section 5.3.4, it's recommended to
- // list all compatible brands here. 3GP spec supports fragment from '3gp6'.
- compatible_brands.AppendElement("3gp9");
- compatible_brands.AppendElement("3gp8");
- compatible_brands.AppendElement("3gp7");
- compatible_brands.AppendElement("3gp6");
- compatible_brands.AppendElement("isom");
- } else if (mControl->GetMuxingType() == ISOMediaWriter::TYPE_FRAG_3G2) {
- major_brand = "3g2a";
- // 3GPP2 Release 0 and A and 3GPP Release 6 allow movie fragmentation
- compatible_brands.AppendElement("3gp9");
- compatible_brands.AppendElement("3gp8");
- compatible_brands.AppendElement("3gp7");
- compatible_brands.AppendElement("3gp6");
- compatible_brands.AppendElement("isom");
- compatible_brands.AppendElement("3g2c");
- compatible_brands.AppendElement("3g2b");
- compatible_brands.AppendElement("3g2a");
- } else {
- MOZ_ASSERT(0);
- }
-
- size += major_brand.Length() +
- sizeof(minor_version) +
- compatible_brands.Length() * 4;
-
- *aBoxSize = size;
-
- return NS_OK;
-}
-
-nsresult
-FileTypeBox::Write()
-{
- BoxSizeChecker checker(mControl, size);
- Box::Write();
- mControl->WriteFourCC(major_brand.get());
- mControl->Write(minor_version);
- uint32_t len = compatible_brands.Length();
- for (uint32_t i = 0; i < len; i++) {
- mControl->WriteFourCC(compatible_brands[i].get());
- }
-
- return NS_OK;
-}
-
-FileTypeBox::FileTypeBox(ISOControl* aControl)
- : Box(NS_LITERAL_CSTRING("ftyp"), aControl)
- , minor_version(0)
-{
- MOZ_COUNT_CTOR(FileTypeBox);
-}
-
-FileTypeBox::~FileTypeBox()
-{
- MOZ_COUNT_DTOR(FileTypeBox);
-}
-
-MediaBox::MediaBox(uint32_t aType, ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("mdia"), aControl)
-{
- mTrackType = aType;
- boxes.AppendElement(new MediaHeaderBox(aType, aControl));
- boxes.AppendElement(new HandlerBox(aType, aControl));
- boxes.AppendElement(new MediaInformationBox(aType, aControl));
- MOZ_COUNT_CTOR(MediaBox);
-}
-
-MediaBox::~MediaBox()
-{
- MOZ_COUNT_DTOR(MediaBox);
-}
-
-nsresult
-DefaultContainerImpl::Generate(uint32_t* aBoxSize)
-{
- nsresult rv;
- uint32_t box_size;
- uint32_t len = boxes.Length();
- for (uint32_t i = 0; i < len; i++) {
- rv = boxes.ElementAt(i)->Generate(&box_size);
- NS_ENSURE_SUCCESS(rv, rv);
- size += box_size;
- }
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-DefaultContainerImpl::Find(const nsACString& aType,
- nsTArray<RefPtr<MuxerOperation>>& aOperations)
-{
- nsresult rv = Box::Find(aType, aOperations);
- NS_ENSURE_SUCCESS(rv, rv);
-
- uint32_t len = boxes.Length();
- for (uint32_t i = 0; i < len; i++) {
- rv = boxes.ElementAt(i)->Find(aType, aOperations);
- NS_ENSURE_SUCCESS(rv, rv);
- }
- return NS_OK;
-}
-
-nsresult
-DefaultContainerImpl::Write()
-{
- BoxSizeChecker checker(mControl, size);
- Box::Write();
-
- nsresult rv;
- uint32_t len = boxes.Length();
- for (uint32_t i = 0; i < len; i++) {
- rv = boxes.ElementAt(i)->Write();
- NS_ENSURE_SUCCESS(rv, rv);
- }
-
- return NS_OK;
-}
-
-DefaultContainerImpl::DefaultContainerImpl(const nsACString& aType,
- ISOControl* aControl)
- : Box(aType, aControl)
-{
-}
-
-nsresult
-Box::Write()
-{
- mControl->Write(size);
- mControl->WriteFourCC(boxType.get());
- return NS_OK;
-}
-
-nsresult
-Box::Find(const nsACString& aType, nsTArray<RefPtr<MuxerOperation>>& aOperations)
-{
- if (boxType == aType) {
- aOperations.AppendElement(this);
- }
- return NS_OK;
-}
-
-Box::Box(const nsACString& aType, ISOControl* aControl)
- : size(8), mControl(aControl)
-{
- MOZ_ASSERT(aType.Length() == 4);
- boxType = aType;
- aControl->GetAudioMetadata(mAudioMeta);
- aControl->GetVideoMetadata(mVideoMeta);
-}
-
-FullBox::FullBox(const nsACString& aType, uint8_t aVersion, uint32_t aFlags,
- ISOControl* aControl)
- : Box(aType, aControl)
-{
- std::bitset<24> tmp_flags(aFlags);
- version = aVersion;
- flags = tmp_flags;
- size += sizeof(version) + flags.size() / CHAR_BIT;
-}
-
-nsresult
-FullBox::Write()
-{
- Box::Write();
- mControl->Write(version);
- mControl->WriteBits(flags.to_ulong(), flags.size());
- return NS_OK;
-}
-
-TrackBox::TrackBox(uint32_t aTrackType, ISOControl* aControl)
- : DefaultContainerImpl(NS_LITERAL_CSTRING("trak"), aControl)
-{
- boxes.AppendElement(new TrackHeaderBox(aTrackType, aControl));
- boxes.AppendElement(new MediaBox(aTrackType, aControl));
- MOZ_COUNT_CTOR(TrackBox);
-}
-
-TrackBox::~TrackBox()
-{
- MOZ_COUNT_DTOR(TrackBox);
-}
-
-SampleEntryBox::SampleEntryBox(const nsACString& aFormat, ISOControl* aControl)
- : Box(aFormat, aControl)
- , data_reference_index(0)
-{
- data_reference_index = 1; // There is only one data reference in each track.
- size += sizeof(reserved) +
- sizeof(data_reference_index);
- memset(reserved, 0, sizeof(reserved));
-}
-
-nsresult
-SampleEntryBox::Write()
-{
- Box::Write();
- mControl->Write(reserved, sizeof(reserved));
- mControl->Write(data_reference_index);
- return NS_OK;
-}
-
-nsresult
-AudioSampleEntry::Write()
-{
- SampleEntryBox::Write();
- mControl->Write(sound_version);
- mControl->Write(reserved2, sizeof(reserved2));
- mControl->Write(channels);
- mControl->Write(sample_size);
- mControl->Write(compressionId);
- mControl->Write(packet_size);
- mControl->Write(timeScale);
- return NS_OK;
-}
-
-AudioSampleEntry::AudioSampleEntry(const nsACString& aFormat, ISOControl* aControl)
- : SampleEntryBox(aFormat, aControl)
- , sound_version(0)
- , channels(2)
- , sample_size(16)
- , compressionId(0)
- , packet_size(0)
- , timeScale(0)
-{
- memset(reserved2, 0 , sizeof(reserved2));
- channels = mAudioMeta->GetAudioChannels();
- timeScale = mAudioMeta->GetAudioSampleRate() << 16;
-
- size += sizeof(sound_version) +
- sizeof(reserved2) +
- sizeof(sample_size) +
- sizeof(channels) +
- sizeof(packet_size) +
- sizeof(compressionId) +
- sizeof(timeScale);
-
- MOZ_COUNT_CTOR(AudioSampleEntry);
-}
-
-AudioSampleEntry::~AudioSampleEntry()
-{
- MOZ_COUNT_DTOR(AudioSampleEntry);
-}
-
-nsresult
-VisualSampleEntry::Write()
-{
- SampleEntryBox::Write();
-
- mControl->Write(reserved, sizeof(reserved));
- mControl->Write(width);
- mControl->Write(height);
- mControl->Write(horizresolution);
- mControl->Write(vertresolution);
- mControl->Write(reserved2);
- mControl->Write(frame_count);
- mControl->Write(compressorName, sizeof(compressorName));
- mControl->Write(depth);
- mControl->Write(pre_defined);
-
- return NS_OK;
-}
-
-VisualSampleEntry::VisualSampleEntry(const nsACString& aFormat, ISOControl* aControl)
- : SampleEntryBox(aFormat, aControl)
- , width(0)
- , height(0)
- , horizresolution(resolution_72_dpi)
- , vertresolution(resolution_72_dpi)
- , reserved2(0)
- , frame_count(1)
- , depth(video_depth)
- , pre_defined(-1)
-{
- memset(reserved, 0 , sizeof(reserved));
- memset(compressorName, 0 , sizeof(compressorName));
-
- // both fields occupy 16 bits defined in 14496-2 6.2.3.
- width = mVideoMeta->GetVideoWidth();
- height = mVideoMeta->GetVideoHeight();
-
- size += sizeof(reserved) +
- sizeof(width) +
- sizeof(height) +
- sizeof(horizresolution) +
- sizeof(vertresolution) +
- sizeof(reserved2) +
- sizeof(frame_count) +
- sizeof(compressorName) +
- sizeof(depth) +
- sizeof(pre_defined);
-
- MOZ_COUNT_CTOR(VisualSampleEntry);
-}
-
-VisualSampleEntry::~VisualSampleEntry()
-{
- MOZ_COUNT_DTOR(VisualSampleEntry);
-}
-
-}
diff --git a/dom/media/encoder/fmp4_muxer/ISOMediaBoxes.h b/dom/media/encoder/fmp4_muxer/ISOMediaBoxes.h
deleted file mode 100644
index a6dc1b046..000000000
--- a/dom/media/encoder/fmp4_muxer/ISOMediaBoxes.h
+++ /dev/null
@@ -1,781 +0,0 @@
-/* -*- 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/. */
-
-#ifndef ISOMediaBoxes_h_
-#define ISOMediaBoxes_h_
-
-#include <bitset>
-#include "nsString.h"
-#include "nsTArray.h"
-#include "nsAutoPtr.h"
-#include "MuxerOperation.h"
-#include "mozilla/UniquePtr.h"
-
-#define WRITE_FULLBOX(_compositor, _size) \
- BoxSizeChecker checker(_compositor, _size); \
- FullBox::Write();
-
-#define FOURCC(a, b, c, d) ( ((a) << 24) | ((b) << 16) | ((c) << 8) | (d) )
-
-namespace mozilla {
-
-/**
- * track type from spec 8.4.3.3
- */
-#define Audio_Track 0x01
-#define Video_Track 0x02
-
-class AudioTrackMetadata;
-class VideoTrackMetadata;
-class ISOControl;
-
-/**
- * This is the base class for all ISO media format boxes.
- * It provides the fields of box type(four CC) and size.
- * The data members in the beginning of a Box (or its descendants)
- * are the 14496-12 defined member. Other members prefix with 'm'
- * are private control data.
- *
- * This class is for inherited only, it shouldn't be instanced directly.
- */
-class Box : public MuxerOperation {
-protected:
- // ISO BMFF members
- uint32_t size; // 14496-12 4-2 'Object Structure'. Size of this box.
- nsCString boxType; // four CC name, all table names are listed in
- // 14496-12 table 1.
-
-public:
- // MuxerOperation methods
- nsresult Write() override;
- nsresult Find(const nsACString& aType,
- nsTArray<RefPtr<MuxerOperation>>& aOperations) override;
-
- // This helper class will compare the written size in Write() and the size in
- // Generate(). If their are not equal, it will assert.
- class BoxSizeChecker {
- public:
- BoxSizeChecker(ISOControl* aControl, uint32_t aSize);
- ~BoxSizeChecker();
-
- uint32_t ori_size;
- uint32_t box_size;
- ISOControl* mControl;
- };
-
-protected:
- Box() = delete;
- Box(const nsACString& aType, ISOControl* aControl);
-
- ISOControl* mControl;
- RefPtr<AudioTrackMetadata> mAudioMeta;
- RefPtr<VideoTrackMetadata> mVideoMeta;
-};
-
-/**
- * FullBox (and its descendants) is the box which contains the 'real' data
- * members. It is the edge in the ISO box structure and it doesn't contain
- * any box.
- *
- * This class is for inherited only, it shouldn't be instanced directly.
- */
-class FullBox : public Box {
-public:
- // ISO BMFF members
- uint8_t version; // 14496-12 4.2 'Object Structure'
- std::bitset<24> flags; //
-
- // MuxerOperation methods
- nsresult Write() override;
-
-protected:
- // FullBox methods
- FullBox(const nsACString& aType, uint8_t aVersion, uint32_t aFlags,
- ISOControl* aControl);
- FullBox() = delete;
-};
-
-/**
- * The default implementation of the container box.
- * Basically, the container box inherits this class and overrides the
- * constructor only.
- *
- * According to 14496-12 3.1.1 'container box', a container box is
- * 'box whose sole purpose is to contain and group a set of related boxes'
- *
- * This class is for inherited only, it shouldn't be instanced directly.
- */
-class DefaultContainerImpl : public Box {
-public:
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
- nsresult Find(const nsACString& aType,
- nsTArray<RefPtr<MuxerOperation>>& aOperations) override;
-
-protected:
- // DefaultContainerImpl methods
- DefaultContainerImpl(const nsACString& aType, ISOControl* aControl);
- DefaultContainerImpl() = delete;
-
- nsTArray<RefPtr<MuxerOperation>> boxes;
-};
-
-// 14496-12 4.3 'File Type Box'
-// Box type: 'ftyp'
-class FileTypeBox : public Box {
-public:
- // ISO BMFF members
- nsCString major_brand; // four chars
- uint32_t minor_version;
- nsTArray<nsCString> compatible_brands;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // FileTypeBox methods
- FileTypeBox(ISOControl* aControl);
- ~FileTypeBox();
-};
-
-// 14496-12 8.2.1 'Movie Box'
-// Box type: 'moov'
-// MovieBox contains MovieHeaderBox, TrackBox and MovieExtendsBox.
-class MovieBox : public DefaultContainerImpl {
-public:
- MovieBox(ISOControl* aControl);
- ~MovieBox();
-};
-
-// 14496-12 8.2.2 'Movie Header Box'
-// Box type: 'mvhd'
-class MovieHeaderBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t creation_time;
- uint32_t modification_time;
- uint32_t timescale;
- uint32_t duration;
- uint32_t rate;
- uint16_t volume;
- uint16_t reserved16;
- uint32_t reserved32[2];
- uint32_t matrix[9];
- uint32_t pre_defined[6];
- uint32_t next_track_ID;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // MovieHeaderBox methods
- MovieHeaderBox(ISOControl* aControl);
- ~MovieHeaderBox();
- uint32_t GetTimeScale();
-};
-
-// 14496-12 8.4.2 'Media Header Box'
-// Box type: 'mdhd'
-class MediaHeaderBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t creation_time;
- uint32_t modification_time;
- uint32_t timescale;
- uint32_t duration;
- std::bitset<1> pad;
- std::bitset<5> lang1;
- std::bitset<5> lang2;
- std::bitset<5> lang3;
- uint16_t pre_defined;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // MediaHeaderBox methods
- MediaHeaderBox(uint32_t aType, ISOControl* aControl);
- ~MediaHeaderBox();
- uint32_t GetTimeScale();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.3.1 'Track Box'
-// Box type: 'trak'
-// TrackBox contains TrackHeaderBox and MediaBox.
-class TrackBox : public DefaultContainerImpl {
-public:
- TrackBox(uint32_t aTrackType, ISOControl* aControl);
- ~TrackBox();
-};
-
-// 14496-12 8.1.1 'Media Data Box'
-// Box type: 'mdat'
-class MediaDataBox : public Box {
-public:
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // MediaDataBox methods
- uint32_t GetAllSampleSize() { return mAllSampleSize; }
- uint32_t FirstSampleOffsetInMediaDataBox() { return mFirstSampleOffset; }
- MediaDataBox(uint32_t aTrackType, ISOControl* aControl);
- ~MediaDataBox();
-
-protected:
- uint32_t mAllSampleSize; // All audio and video sample size in this box.
- uint32_t mFirstSampleOffset; // The offset of first sample in this box from
- // the beginning of this mp4 file.
- uint32_t mTrackType;
-};
-
-// flags for TrackRunBox::flags, 14496-12 8.8.8.1.
-#define flags_data_offset_present 0x000001
-#define flags_first_sample_flags_present 0x000002
-#define flags_sample_duration_present 0x000100
-#define flags_sample_size_present 0x000200
-#define flags_sample_flags_present 0x000400
-#define flags_sample_composition_time_offsets_present 0x000800
-
-// flag for TrackRunBox::tbl::sample_flags and TrackExtendsBox::default_sample_flags
-// which is defined in 14496-12 8.8.3.1.
-uint32_t set_sample_flags(bool aSync);
-
-// 14496-12 8.8.8 'Track Fragment Run Box'
-// Box type: 'trun'
-class TrackRunBox : public FullBox {
-public:
- // ISO BMFF members
- typedef struct {
- uint32_t sample_duration;
- uint32_t sample_size;
- uint32_t sample_flags;
- uint32_t sample_composition_time_offset;
- } tbl;
-
- uint32_t sample_count;
- // the following are optional fields
- uint32_t data_offset; // data offset exists when audio/video are present in file.
- uint32_t first_sample_flags;
- UniquePtr<tbl[]> sample_info_table;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // TrackRunBox methods
- uint32_t GetAllSampleSize() { return mAllSampleSize; }
- nsresult SetDataOffset(uint32_t aOffset);
-
- TrackRunBox(uint32_t aType, uint32_t aFlags, ISOControl* aControl);
- ~TrackRunBox();
-
-protected:
- uint32_t fillSampleTable();
-
- uint32_t mAllSampleSize;
- uint32_t mTrackType;
-};
-
-// tf_flags in TrackFragmentHeaderBox, 14496-12 8.8.7.1.
-#define base_data_offset_present 0x000001
-#define sample_description_index_present 0x000002
-#define default_sample_duration_present 0x000008
-#define default_sample_size_present 0x000010
-#define default_sample_flags_present 0x000020
-#define duration_is_empty 0x010000
-#define default_base_is_moof 0x020000
-
-// 14496-12 8.8.7 'Track Fragment Header Box'
-// Box type: 'tfhd'
-class TrackFragmentHeaderBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t track_ID;
- uint64_t base_data_offset;
- uint32_t default_sample_duration;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // TrackFragmentHeaderBox methods
- nsresult UpdateBaseDataOffset(uint64_t aOffset); // The offset of the first
- // sample in file.
-
- TrackFragmentHeaderBox(uint32_t aType, uint32_t aFlags, ISOControl* aControl);
- ~TrackFragmentHeaderBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.8.6 'Track Fragment Box'
-// Box type: 'traf'
-// TrackFragmentBox cotains TrackFragmentHeaderBox and TrackRunBox.
-class TrackFragmentBox : public DefaultContainerImpl {
-public:
- TrackFragmentBox(uint32_t aType, ISOControl* aControl);
- ~TrackFragmentBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.8.5 'Movie Fragment Header Box'
-// Box type: 'mfhd'
-class MovieFragmentHeaderBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t sequence_number;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // MovieFragmentHeaderBox methods
- MovieFragmentHeaderBox(uint32_t aType, ISOControl* aControl);
- ~MovieFragmentHeaderBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.8.4 'Movie Fragment Box'
-// Box type: 'moof'
-// MovieFragmentBox contains MovieFragmentHeaderBox and TrackFragmentBox.
-class MovieFragmentBox : public DefaultContainerImpl {
-public:
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
-
- // MovieFragmentBox methods
- MovieFragmentBox(uint32_t aType, ISOControl* aControl);
- ~MovieFragmentBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.8.3 'Track Extends Box'
-// Box type: 'trex'
-class TrackExtendsBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t track_ID;
- uint32_t default_sample_description_index;
- uint32_t default_sample_duration;
- uint32_t default_sample_size;
- uint32_t default_sample_flags;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // TrackExtendsBox methods
- TrackExtendsBox(uint32_t aType, ISOControl* aControl);
- ~TrackExtendsBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.8.1 'Movie Extends Box'
-// Box type: 'mvex'
-// MovieExtendsBox contains TrackExtendsBox.
-class MovieExtendsBox : public DefaultContainerImpl {
-public:
- MovieExtendsBox(ISOControl* aControl);
- ~MovieExtendsBox();
-};
-
-// 14496-12 8.7.5 'Chunk Offset Box'
-// Box type: 'stco'
-class ChunkOffsetBox : public FullBox {
-public:
- // ISO BMFF members
- typedef struct {
- uint32_t chunk_offset;
- } tbl;
-
- uint32_t entry_count;
- UniquePtr<tbl[]> sample_tbl;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // ChunkOffsetBox methods
- ChunkOffsetBox(uint32_t aType, ISOControl* aControl);
- ~ChunkOffsetBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.7.4 'Sample To Chunk Box'
-// Box type: 'stsc'
-class SampleToChunkBox : public FullBox {
-public:
- // ISO BMFF members
- typedef struct {
- uint32_t first_chunk;
- uint32_t sample_per_chunk;
- uint32_t sample_description_index;
- } tbl;
-
- uint32_t entry_count;
- UniquePtr<tbl[]> sample_tbl;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // SampleToChunkBox methods
- SampleToChunkBox(uint32_t aType, ISOControl* aControl);
- ~SampleToChunkBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.6.1.2 'Decoding Time to Sample Box'
-// Box type: 'stts'
-class TimeToSampleBox : public FullBox {
-public:
- // ISO BMFF members
- typedef struct {
- uint32_t sample_count;
- uint32_t sample_delta;
- } tbl;
-
- uint32_t entry_count;
- UniquePtr<tbl[]> sample_tbl;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // TimeToSampleBox methods
- TimeToSampleBox(uint32_t aType, ISOControl* aControl);
- ~TimeToSampleBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-/**
- * 14496-12 8.5.2 'Sample Description Box'
- * This is the base class for VisualSampleEntry and AudioSampleEntry.
- *
- * This class is for inherited only, it shouldn't be instanced directly.
- *
- * The inhertied tree of a codec box should be:
- *
- * +--> AVCSampleEntry
- * +--> VisualSampleEntryBox +
- * | +--> ...
- * SampleEntryBox +
- * | +--> MP4AudioSampleEntry
- * +--> AudioSampleEntryBox +
- * +--> AMRSampleEntry
- * +
- * +--> ...
- *
- */
-class SampleEntryBox : public Box {
-public:
- // ISO BMFF members
- uint8_t reserved[6];
- uint16_t data_reference_index;
-
- // sampleentrybox methods
- SampleEntryBox(const nsACString& aFormat, ISOControl* aControl);
-
- // MuxerOperation methods
- nsresult Write() override;
-
-protected:
- SampleEntryBox() = delete;
-};
-
-// 14496-12 8.5.2 'Sample Description Box'
-// Box type: 'stsd'
-class SampleDescriptionBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t entry_count;
- RefPtr<SampleEntryBox> sample_entry_box;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // SampleDescriptionBox methods
- SampleDescriptionBox(uint32_t aType, ISOControl* aControl);
- ~SampleDescriptionBox();
-
-protected:
- nsresult CreateAudioSampleEntry(RefPtr<SampleEntryBox>& aSampleEntry);
- nsresult CreateVideoSampleEntry(RefPtr<SampleEntryBox>& aSampleEntry);
-
- uint32_t mTrackType;
-};
-
-// 14496-12 8.5.2.2
-// The base class for audio codec box.
-// This class is for inherited only, it shouldn't be instanced directly.
-class AudioSampleEntry : public SampleEntryBox {
-public:
- // ISO BMFF members
- uint16_t sound_version;
- uint8_t reserved2[6];
- uint16_t channels;
- uint16_t sample_size;
- uint16_t compressionId;
- uint16_t packet_size;
- uint32_t timeScale; // (sample rate of media) <<16
-
- // MuxerOperation methods
- nsresult Write() override;
-
- ~AudioSampleEntry();
-
-protected:
- AudioSampleEntry(const nsACString& aFormat, ISOControl* aControl);
-};
-
-// 14496-12 8.5.2.2
-// The base class for video codec box.
-// This class is for inherited only, it shouldn't be instanced directly.
-class VisualSampleEntry : public SampleEntryBox {
-public:
- // ISO BMFF members
- uint8_t reserved[16];
- uint16_t width;
- uint16_t height;
-
- uint32_t horizresolution; // 72 dpi
- uint32_t vertresolution; // 72 dpi
- uint32_t reserved2;
- uint16_t frame_count; // 1, defined in 14496-12 8.5.2.2
-
- uint8_t compressorName[32];
- uint16_t depth; // 0x0018, defined in 14496-12 8.5.2.2;
- uint16_t pre_defined; // -1, defined in 14496-12 8.5.2.2;
-
- // MuxerOperation methods
- nsresult Write() override;
-
- // VisualSampleEntry methods
- ~VisualSampleEntry();
-
-protected:
- VisualSampleEntry(const nsACString& aFormat, ISOControl* aControl);
-};
-
-// 14496-12 8.7.3.2 'Sample Size Box'
-// Box type: 'stsz'
-class SampleSizeBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t sample_size;
- uint32_t sample_count;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // SampleSizeBox methods
- SampleSizeBox(ISOControl* aControl);
- ~SampleSizeBox();
-};
-
-// 14496-12 8.5.1 'Sample Table Box'
-// Box type: 'stbl'
-//
-// SampleTableBox contains SampleDescriptionBox,
-// TimeToSampleBox,
-// SampleToChunkBox,
-// SampleSizeBox and
-// ChunkOffsetBox.
-class SampleTableBox : public DefaultContainerImpl {
-public:
- SampleTableBox(uint32_t aType, ISOControl* aControl);
- ~SampleTableBox();
-};
-
-// 14496-12 8.7.2 'Data Reference Box'
-// Box type: 'url '
-class DataEntryUrlBox : public FullBox {
-public:
- // ISO BMFF members
- // flags in DataEntryUrlBox::flags
- const static uint16_t flags_media_at_the_same_file = 0x0001;
-
- nsCString location;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // DataEntryUrlBox methods
- DataEntryUrlBox();
- DataEntryUrlBox(ISOControl* aControl);
- DataEntryUrlBox(const DataEntryUrlBox& aBox);
- ~DataEntryUrlBox();
-};
-
-// 14496-12 8.7.2 'Data Reference Box'
-// Box type: 'dref'
-class DataReferenceBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t entry_count;
- nsTArray<nsAutoPtr<DataEntryUrlBox>> urls;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // DataReferenceBox methods
- DataReferenceBox(ISOControl* aControl);
- ~DataReferenceBox();
-};
-
-// 14496-12 8.7.1 'Data Information Box'
-// Box type: 'dinf'
-// DataInformationBox contains DataReferenceBox.
-class DataInformationBox : public DefaultContainerImpl {
-public:
- DataInformationBox(ISOControl* aControl);
- ~DataInformationBox();
-};
-
-// 14496-12 8.4.5.2 'Video Media Header Box'
-// Box type: 'vmhd'
-class VideoMediaHeaderBox : public FullBox {
-public:
- // ISO BMFF members
- uint16_t graphicsmode;
- uint16_t opcolor[3];
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // VideoMediaHeaderBox methods
- VideoMediaHeaderBox(ISOControl* aControl);
- ~VideoMediaHeaderBox();
-};
-
-// 14496-12 8.4.5.3 'Sound Media Header Box'
-// Box type: 'smhd'
-class SoundMediaHeaderBox : public FullBox {
-public:
- // ISO BMFF members
- uint16_t balance;
- uint16_t reserved;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // SoundMediaHeaderBox methods
- SoundMediaHeaderBox(ISOControl* aControl);
- ~SoundMediaHeaderBox();
-};
-
-// 14496-12 8.4.4 'Media Information Box'
-// Box type: 'minf'
-// MediaInformationBox contains SoundMediaHeaderBox, DataInformationBox and
-// SampleTableBox.
-class MediaInformationBox : public DefaultContainerImpl {
-public:
- MediaInformationBox(uint32_t aType, ISOControl* aControl);
- ~MediaInformationBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// flags for TrackHeaderBox::flags.
-#define flags_track_enabled 0x000001
-#define flags_track_in_movie 0x000002
-#define flags_track_in_preview 0x000004
-
-// 14496-12 8.3.2 'Track Header Box'
-// Box type: 'tkhd'
-class TrackHeaderBox : public FullBox {
-public:
- // ISO BMFF members
- // version = 0
- uint32_t creation_time;
- uint32_t modification_time;
- uint32_t track_ID;
- uint32_t reserved;
- uint32_t duration;
-
- uint32_t reserved2[2];
- uint16_t layer;
- uint16_t alternate_group;
- uint16_t volume;
- uint16_t reserved3;
- uint32_t matrix[9];
- uint32_t width;
- uint32_t height;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // TrackHeaderBox methods
- TrackHeaderBox(uint32_t aType, ISOControl* aControl);
- ~TrackHeaderBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.4.3 'Handler Reference Box'
-// Box type: 'hdlr'
-class HandlerBox : public FullBox {
-public:
- // ISO BMFF members
- uint32_t pre_defined;
- uint32_t handler_type;
- uint32_t reserved[3];
- nsCString name;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // HandlerBox methods
- HandlerBox(uint32_t aType, ISOControl* aControl);
- ~HandlerBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-// 14496-12 8.4.1 'Media Box'
-// Box type: 'mdia'
-// MediaBox contains MediaHeaderBox, HandlerBox, and MediaInformationBox.
-class MediaBox : public DefaultContainerImpl {
-public:
- MediaBox(uint32_t aType, ISOControl* aControl);
- ~MediaBox();
-
-protected:
- uint32_t mTrackType;
-};
-
-}
-#endif // ISOMediaBoxes_h_
diff --git a/dom/media/encoder/fmp4_muxer/ISOMediaWriter.cpp b/dom/media/encoder/fmp4_muxer/ISOMediaWriter.cpp
deleted file mode 100644
index fa23616e9..000000000
--- a/dom/media/encoder/fmp4_muxer/ISOMediaWriter.cpp
+++ /dev/null
@@ -1,234 +0,0 @@
-/* -*- 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 "ISOMediaWriter.h"
-#include "ISOControl.h"
-#include "ISOMediaBoxes.h"
-#include "ISOTrackMetadata.h"
-#include "nsThreadUtils.h"
-#include "MediaEncoder.h"
-#include "VideoUtils.h"
-#include "GeckoProfiler.h"
-
-#undef LOG
-#ifdef MOZ_WIDGET_GONK
-#include <android/log.h>
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "MediaEncoder", ## args);
-#else
-#define LOG(args, ...)
-#endif
-
-namespace mozilla {
-
-const static uint32_t FRAG_DURATION = 2 * USECS_PER_S; // microsecond per unit
-
-ISOMediaWriter::ISOMediaWriter(uint32_t aType, uint32_t aHint)
- : ContainerWriter()
- , mState(MUXING_HEAD)
- , mBlobReady(false)
- , mType(0)
-{
- if (aType & CREATE_AUDIO_TRACK) {
- mType |= Audio_Track;
- }
- if (aType & CREATE_VIDEO_TRACK) {
- mType |= Video_Track;
- }
- mControl = new ISOControl(aHint);
- MOZ_COUNT_CTOR(ISOMediaWriter);
-}
-
-ISOMediaWriter::~ISOMediaWriter()
-{
- MOZ_COUNT_DTOR(ISOMediaWriter);
-}
-
-nsresult
-ISOMediaWriter::RunState()
-{
- nsresult rv;
- switch (mState) {
- case MUXING_HEAD:
- {
- rv = mControl->GenerateFtyp();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = mControl->GenerateMoov();
- NS_ENSURE_SUCCESS(rv, rv);
- mState = MUXING_FRAG;
- break;
- }
- case MUXING_FRAG:
- {
- rv = mControl->GenerateMoof(mType);
- NS_ENSURE_SUCCESS(rv, rv);
-
- bool EOS;
- if (ReadyToRunState(EOS) && EOS) {
- mState = MUXING_DONE;
- }
- break;
- }
- case MUXING_DONE:
- {
- break;
- }
- }
- mBlobReady = true;
- return NS_OK;
-}
-
-nsresult
-ISOMediaWriter::WriteEncodedTrack(const EncodedFrameContainer& aData,
- uint32_t aFlags)
-{
- PROFILER_LABEL("ISOMediaWriter", "WriteEncodedTrack",
- js::ProfileEntry::Category::OTHER);
- // Muxing complete, it doesn't allowed to reentry again.
- if (mState == MUXING_DONE) {
- MOZ_ASSERT(false);
- return NS_ERROR_FAILURE;
- }
-
- FragmentBuffer* frag = nullptr;
- uint32_t len = aData.GetEncodedFrames().Length();
-
- if (!len) {
- // no frame? why bother to WriteEncodedTrack
- return NS_OK;
- }
- for (uint32_t i = 0; i < len; i++) {
- RefPtr<EncodedFrame> frame(aData.GetEncodedFrames()[i]);
- EncodedFrame::FrameType type = frame->GetFrameType();
- if (type == EncodedFrame::AAC_AUDIO_FRAME ||
- type == EncodedFrame::AAC_CSD ||
- type == EncodedFrame::AMR_AUDIO_FRAME ||
- type == EncodedFrame::AMR_AUDIO_CSD ||
- type == EncodedFrame::EVRC_AUDIO_FRAME ||
- type == EncodedFrame::EVRC_AUDIO_CSD) {
- frag = mAudioFragmentBuffer;
- } else if (type == EncodedFrame::AVC_I_FRAME ||
- type == EncodedFrame::AVC_P_FRAME ||
- type == EncodedFrame::AVC_B_FRAME ||
- type == EncodedFrame::AVC_CSD) {
- frag = mVideoFragmentBuffer;
- } else {
- MOZ_ASSERT(0);
- return NS_ERROR_FAILURE;
- }
-
- frag->AddFrame(frame);
- }
-
- // Encoder should send CSD (codec specific data) frame before sending the
- // audio/video frames. When CSD data is ready, it is sufficient to generate a
- // moov data. If encoder doesn't send CSD yet, muxer needs to wait before
- // generating anything.
- if (mType & Audio_Track && (!mAudioFragmentBuffer ||
- !mAudioFragmentBuffer->HasCSD())) {
- return NS_OK;
- }
- if (mType & Video_Track && (!mVideoFragmentBuffer ||
- !mVideoFragmentBuffer->HasCSD())) {
- return NS_OK;
- }
-
- // Only one FrameType in EncodedFrameContainer so it doesn't need to be
- // inside the for-loop.
- if (frag && (aFlags & END_OF_STREAM)) {
- frag->SetEndOfStream();
- }
-
- nsresult rv;
- bool EOS;
- if (ReadyToRunState(EOS)) {
- // Because track encoder won't generate new data after EOS, it needs to make
- // sure the state reaches MUXING_DONE when EOS is signaled.
- do {
- rv = RunState();
- } while (EOS && mState != MUXING_DONE);
- NS_ENSURE_SUCCESS(rv, rv);
- }
-
- return NS_OK;
-}
-
-bool
-ISOMediaWriter::ReadyToRunState(bool& aEOS)
-{
- aEOS = false;
- bool bReadyToMux = true;
- if ((mType & Audio_Track) && (mType & Video_Track)) {
- if (!mAudioFragmentBuffer->HasEnoughData()) {
- bReadyToMux = false;
- }
- if (!mVideoFragmentBuffer->HasEnoughData()) {
- bReadyToMux = false;
- }
-
- if (mAudioFragmentBuffer->EOS() && mVideoFragmentBuffer->EOS()) {
- aEOS = true;
- bReadyToMux = true;
- }
- } else if (mType == Audio_Track) {
- if (!mAudioFragmentBuffer->HasEnoughData()) {
- bReadyToMux = false;
- }
- if (mAudioFragmentBuffer->EOS()) {
- aEOS = true;
- bReadyToMux = true;
- }
- } else if (mType == Video_Track) {
- if (!mVideoFragmentBuffer->HasEnoughData()) {
- bReadyToMux = false;
- }
- if (mVideoFragmentBuffer->EOS()) {
- aEOS = true;
- bReadyToMux = true;
- }
- }
-
- return bReadyToMux;
-}
-
-nsresult
-ISOMediaWriter::GetContainerData(nsTArray<nsTArray<uint8_t>>* aOutputBufs,
- uint32_t aFlags)
-{
- PROFILER_LABEL("ISOMediaWriter", "GetContainerData",
- js::ProfileEntry::Category::OTHER);
- if (mBlobReady) {
- if (mState == MUXING_DONE) {
- mIsWritingComplete = true;
- }
- mBlobReady = false;
- return mControl->GetBufs(aOutputBufs);
- }
- return NS_OK;
-}
-
-nsresult
-ISOMediaWriter::SetMetadata(TrackMetadataBase* aMetadata)
-{
- PROFILER_LABEL("ISOMediaWriter", "SetMetadata",
- js::ProfileEntry::Category::OTHER);
- if (aMetadata->GetKind() == TrackMetadataBase::METADATA_AAC ||
- aMetadata->GetKind() == TrackMetadataBase::METADATA_AMR ||
- aMetadata->GetKind() == TrackMetadataBase::METADATA_EVRC) {
- mControl->SetMetadata(aMetadata);
- mAudioFragmentBuffer = new FragmentBuffer(Audio_Track, FRAG_DURATION);
- mControl->SetFragment(mAudioFragmentBuffer);
- return NS_OK;
- }
- if (aMetadata->GetKind() == TrackMetadataBase::METADATA_AVC) {
- mControl->SetMetadata(aMetadata);
- mVideoFragmentBuffer = new FragmentBuffer(Video_Track, FRAG_DURATION);
- mControl->SetFragment(mVideoFragmentBuffer);
- return NS_OK;
- }
-
- return NS_ERROR_FAILURE;
-}
-
-} // namespace mozilla
diff --git a/dom/media/encoder/fmp4_muxer/ISOMediaWriter.h b/dom/media/encoder/fmp4_muxer/ISOMediaWriter.h
deleted file mode 100644
index cccbbe3cb..000000000
--- a/dom/media/encoder/fmp4_muxer/ISOMediaWriter.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/* -*- 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/. */
-
-#ifndef ISOMediaWriter_h_
-#define ISOMediaWriter_h_
-
-#include "ContainerWriter.h"
-#include "nsAutoPtr.h"
-#include "nsIRunnable.h"
-
-namespace mozilla {
-
-class ISOControl;
-class FragmentBuffer;
-
-class ISOMediaWriter : public ContainerWriter
-{
-public:
- // Generate an fragmented MP4 stream, ISO/IEC 14496-12.
- // Brand names in 'ftyp' box are 'isom' and 'mp42'.
- const static uint32_t TYPE_FRAG_MP4 = 1 << 0;
-
- // Generate an fragmented 3GP stream, 3GPP TS 26.244,
- // '5.4.3 Basic profile'.
- // Brand names in 'ftyp' box are '3gp9' and 'isom'.
- const static uint32_t TYPE_FRAG_3GP = 1 << 1;
-
- // Generate an fragmented 3G2 stream, 3GPP2 C.S0050-B
- // Brand names in 'ftyp' box are '3g2c' and 'isom'
- const static uint32_t TYPE_FRAG_3G2 = 1 << 2;
-
- // aType is the combination of CREATE_AUDIO_TRACK and CREATE_VIDEO_TRACK.
- // It is a hint to muxer that the output streaming contains audio, video
- // or both.
- //
- // aHint is one of the value in TYPE_XXXXXXXX. It is a hint to muxer what kind
- // of ISO format should be generated.
- ISOMediaWriter(uint32_t aType, uint32_t aHint = TYPE_FRAG_MP4);
- ~ISOMediaWriter();
-
- // ContainerWriter methods
- nsresult WriteEncodedTrack(const EncodedFrameContainer &aData,
- uint32_t aFlags = 0) override;
-
- nsresult GetContainerData(nsTArray<nsTArray<uint8_t>>* aOutputBufs,
- uint32_t aFlags = 0) override;
-
- nsresult SetMetadata(TrackMetadataBase* aMetadata) override;
-
-protected:
- /**
- * The state of each state will generate one or more blob.
- * Each blob will be a moov, moof, moof... until receiving EOS.
- * The generated sequence is:
- *
- * moov -> moof -> moof -> ... -> moof -> moof
- *
- * Following is the details of each state.
- * MUXING_HEAD:
- * It collects the metadata to generate a moov. The state transits to
- * MUXING_HEAD after output moov blob.
- *
- * MUXING_FRAG:
- * It collects enough audio/video data to generate a fragment blob. This
- * will be repeated until END_OF_STREAM and then transiting to MUXING_DONE.
- *
- * MUXING_DONE:
- * End of ISOMediaWriter life cycle.
- */
- enum MuxState {
- MUXING_HEAD,
- MUXING_FRAG,
- MUXING_DONE,
- };
-
-private:
- nsresult RunState();
-
- // True if one of following conditions hold:
- // 1. Audio/Video accumulates enough data to generate a moof.
- // 2. Get EOS signal.
- // aEOS will be assigned to true if it gets EOS signal.
- bool ReadyToRunState(bool& aEOS);
-
- // The main class to generate and iso box. Its life time is same as
- // ISOMediaWriter and deleted only if ISOMediaWriter is destroyed.
- nsAutoPtr<ISOControl> mControl;
-
- // Buffers to keep audio/video data frames, they are created when metadata is
- // received. Only one instance for each media type is allowed and they will be
- // deleted only if ISOMediaWriter is destroyed.
- nsAutoPtr<FragmentBuffer> mAudioFragmentBuffer;
- nsAutoPtr<FragmentBuffer> mVideoFragmentBuffer;
-
- MuxState mState;
-
- // A flag to indicate the output buffer is ready to blob out.
- bool mBlobReady;
-
- // Combination of Audio_Track or Video_Track.
- uint32_t mType;
-};
-
-} // namespace mozilla
-
-#endif // ISOMediaWriter_h_
diff --git a/dom/media/encoder/fmp4_muxer/ISOTrackMetadata.h b/dom/media/encoder/fmp4_muxer/ISOTrackMetadata.h
deleted file mode 100644
index 3613e1e9e..000000000
--- a/dom/media/encoder/fmp4_muxer/ISOTrackMetadata.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/* -*- 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/. */
-
-#ifndef ISOTrackMetadata_h_
-#define ISOTrackMetadata_h_
-
-#include "TrackMetadataBase.h"
-
-namespace mozilla {
-
-class AACTrackMetadata : public AudioTrackMetadata {
-public:
- // AudioTrackMetadata members
- uint32_t GetAudioFrameDuration() override { return mFrameDuration; }
- uint32_t GetAudioFrameSize() override { return mFrameSize; }
- uint32_t GetAudioSampleRate() override { return mSampleRate; }
- uint32_t GetAudioChannels() override { return mChannels; }
-
- // TrackMetadataBase member
- MetadataKind GetKind() const override { return METADATA_AAC; }
-
- // AACTrackMetadata members
- AACTrackMetadata()
- : mSampleRate(0)
- , mFrameDuration(0)
- , mFrameSize(0)
- , mChannels(0) {
- MOZ_COUNT_CTOR(AACTrackMetadata);
- }
- ~AACTrackMetadata() { MOZ_COUNT_DTOR(AACTrackMetadata); }
-
- uint32_t mSampleRate; // From 14496-3 table 1.16, it could be 7350 ~ 96000.
- uint32_t mFrameDuration; // Audio frame duration based on SampleRate.
- uint32_t mFrameSize; // Audio frame size, 0 is variant size.
- uint32_t mChannels; // Channel number, it should be 1 or 2.
-};
-
-// AVC clock rate is 90k Hz.
-#define AVC_CLOCK_RATE 90000
-
-class AVCTrackMetadata : public VideoTrackMetadata {
-public:
- // VideoTrackMetadata members
- uint32_t GetVideoHeight() override { return mHeight; }
- uint32_t GetVideoWidth() override {return mWidth; }
- uint32_t GetVideoDisplayHeight() override { return mDisplayHeight; }
- uint32_t GetVideoDisplayWidth() override { return mDisplayWidth; }
- uint32_t GetVideoClockRate() override { return AVC_CLOCK_RATE; }
- uint32_t GetVideoFrameRate() override { return mFrameRate; }
-
- // TrackMetadataBase member
- MetadataKind GetKind() const override { return METADATA_AVC; }
-
- // AVCTrackMetadata
- AVCTrackMetadata()
- : mHeight(0)
- , mWidth(0)
- , mDisplayHeight(0)
- , mDisplayWidth(0)
- , mFrameRate(0) {
- MOZ_COUNT_CTOR(AVCTrackMetadata);
- }
- ~AVCTrackMetadata() { MOZ_COUNT_DTOR(AVCTrackMetadata); }
-
- uint32_t mHeight;
- uint32_t mWidth;
- uint32_t mDisplayHeight;
- uint32_t mDisplayWidth;
- uint32_t mFrameRate; // frames per second
-};
-
-
-// AMR sample rate is 8000 samples/s.
-#define AMR_SAMPLE_RATE 8000
-
-// Channel number is always 1.
-#define AMR_CHANNELS 1
-
-// AMR speech codec, 3GPP TS 26.071. Encoder and continer support AMR-NB only
-// currently.
-class AMRTrackMetadata : public AudioTrackMetadata {
-public:
- // AudioTrackMetadata members
- //
- // The number of sample sets generates by encoder is variant. So the
- // frame duration and frame size are both 0.
- uint32_t GetAudioFrameDuration() override { return 0; }
- uint32_t GetAudioFrameSize() override { return 0; }
- uint32_t GetAudioSampleRate() override { return AMR_SAMPLE_RATE; }
- uint32_t GetAudioChannels() override { return AMR_CHANNELS; }
-
- // TrackMetadataBase member
- MetadataKind GetKind() const override { return METADATA_AMR; }
-
- // AMRTrackMetadata members
- AMRTrackMetadata() { MOZ_COUNT_CTOR(AMRTrackMetadata); }
- ~AMRTrackMetadata() { MOZ_COUNT_DTOR(AMRTrackMetadata); }
-};
-
-// EVRC sample rate is 8000 samples/s.
-#define EVRC_SAMPLE_RATE 8000
-
-class EVRCTrackMetadata : public AudioTrackMetadata {
-public:
- // AudioTrackMetadata members
- //
- // The number of sample sets generates by encoder is variant. So the
- // frame duration and frame size are both 0.
- uint32_t GetAudioFrameDuration() override { return 0; }
- uint32_t GetAudioFrameSize() override { return 0; }
- uint32_t GetAudioSampleRate() override { return EVRC_SAMPLE_RATE; }
- uint32_t GetAudioChannels() override { return mChannels; }
-
- // TrackMetadataBase member
- MetadataKind GetKind() const override { return METADATA_EVRC; }
-
- // EVRCTrackMetadata members
- EVRCTrackMetadata()
- : mChannels(0) {
- MOZ_COUNT_CTOR(EVRCTrackMetadata);
- }
- ~EVRCTrackMetadata() { MOZ_COUNT_DTOR(EVRCTrackMetadata); }
-
- uint32_t mChannels; // Channel number, it should be 1 or 2.
-};
-
-}
-
-#endif // ISOTrackMetadata_h_
diff --git a/dom/media/encoder/fmp4_muxer/MP4ESDS.cpp b/dom/media/encoder/fmp4_muxer/MP4ESDS.cpp
deleted file mode 100644
index 72880b5cb..000000000
--- a/dom/media/encoder/fmp4_muxer/MP4ESDS.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/* -*- 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 <climits>
-#include "ISOControl.h"
-#include "ISOMediaBoxes.h"
-#include "MP4ESDS.h"
-
-namespace mozilla {
-
-nsresult
-MP4AudioSampleEntry::Generate(uint32_t* aBoxSize)
-{
- uint32_t box_size;
- nsresult rv = es->Generate(&box_size);
- NS_ENSURE_SUCCESS(rv, rv);
- size += box_size;
-
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-MP4AudioSampleEntry::Write()
-{
- BoxSizeChecker checker(mControl, size);
- nsresult rv;
- rv = AudioSampleEntry::Write();
- NS_ENSURE_SUCCESS(rv, rv);
- rv = es->Write();
- NS_ENSURE_SUCCESS(rv, rv);
-
- return NS_OK;
-}
-
-MP4AudioSampleEntry::MP4AudioSampleEntry(ISOControl* aControl)
- : AudioSampleEntry(NS_LITERAL_CSTRING("mp4a"), aControl)
-{
- es = new ESDBox(aControl);
- MOZ_COUNT_CTOR(MP4AudioSampleEntry);
-}
-
-MP4AudioSampleEntry::~MP4AudioSampleEntry()
-{
- MOZ_COUNT_DTOR(MP4AudioSampleEntry);
-}
-
-nsresult
-ESDBox::Generate(uint32_t* aBoxSize)
-{
- uint32_t box_size;
- es_descriptor->Generate(&box_size);
- size += box_size;
- *aBoxSize = size;
- return NS_OK;
-}
-
-nsresult
-ESDBox::Write()
-{
- WRITE_FULLBOX(mControl, size)
- es_descriptor->Write();
- return NS_OK;
-}
-
-ESDBox::ESDBox(ISOControl* aControl)
- : FullBox(NS_LITERAL_CSTRING("esds"), 0, 0, aControl)
-{
- es_descriptor = new ES_Descriptor(aControl);
- MOZ_COUNT_CTOR(ESDBox);
-}
-
-ESDBox::~ESDBox()
-{
- MOZ_COUNT_DTOR(ESDBox);
-}
-
-nsresult
-ES_Descriptor::Find(const nsACString& aType,
- nsTArray<RefPtr<MuxerOperation>>& aOperations)
-{
- // ES_Descriptor is not a real ISOMediaBox, so we return nothing here.
- return NS_OK;
-}
-
-nsresult
-ES_Descriptor::Write()
-{
- mControl->Write(tag);
- mControl->Write(length);
- mControl->Write(ES_ID);
- mControl->WriteBits(streamDependenceFlag.to_ulong(), streamDependenceFlag.size());
- mControl->WriteBits(URL_Flag.to_ulong(), URL_Flag.size());
- mControl->WriteBits(reserved.to_ulong(), reserved.size());
- mControl->WriteBits(streamPriority.to_ulong(), streamPriority.size());
- mControl->Write(DecodeSpecificInfo.Elements(), DecodeSpecificInfo.Length());
-
- return NS_OK;
-}
-
-nsresult
-ES_Descriptor::Generate(uint32_t* aBoxSize)
-{
- nsresult rv;
- // 14496-1 '8.3.4 DecoderConfigDescriptor'
- // 14496-1 '10.2.3 SL Packet Header Configuration'
- FragmentBuffer* frag = mControl->GetFragment(Audio_Track);
- rv = frag->GetCSD(DecodeSpecificInfo);
- NS_ENSURE_SUCCESS(rv, rv);
-
- length = sizeof(ES_ID) + 1;
- length += DecodeSpecificInfo.Length();
-
- *aBoxSize = sizeof(tag) + sizeof(length) + length;
- return NS_OK;
-}
-
-ES_Descriptor::ES_Descriptor(ISOControl* aControl)
- : tag(ESDescrTag)
- , length(0)
- , ES_ID(0)
- , streamDependenceFlag(0)
- , URL_Flag(0)
- , reserved(0)
- , streamPriority(0)
- , mControl(aControl)
-{
- MOZ_COUNT_CTOR(ES_Descriptor);
-}
-
-ES_Descriptor::~ES_Descriptor()
-{
- MOZ_COUNT_DTOR(ES_Descriptor);
-}
-
-}
diff --git a/dom/media/encoder/fmp4_muxer/MP4ESDS.h b/dom/media/encoder/fmp4_muxer/MP4ESDS.h
deleted file mode 100644
index ee91312c1..000000000
--- a/dom/media/encoder/fmp4_muxer/MP4ESDS.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/* -*- 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/. */
-
-#ifndef MP4ESDS_h_
-#define MP4ESDS_h_
-
-#include "nsTArray.h"
-#include "MuxerOperation.h"
-
-namespace mozilla {
-
-class ISOControl;
-
-/**
- * ESDS tag
- */
-#define ESDescrTag 0x03
-
-/**
- * 14496-1 '8.3.3 ES_Descriptor'.
- * It will get DecoderConfigDescriptor and SLConfigDescriptor from
- * AAC CSD data.
- */
-class ES_Descriptor : public MuxerOperation {
-public:
- // ISO BMFF members
- uint8_t tag; // ESDescrTag
- uint8_t length;
- uint16_t ES_ID;
- std::bitset<1> streamDependenceFlag;
- std::bitset<1> URL_Flag;
- std::bitset<1> reserved;
- std::bitset<5> streamPriority;
-
- nsTArray<uint8_t> DecodeSpecificInfo;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
- nsresult Find(const nsACString& aType,
- nsTArray<RefPtr<MuxerOperation>>& aOperations) override;
-
- // ES_Descriptor methods
- ES_Descriptor(ISOControl* aControl);
- ~ES_Descriptor();
-
-protected:
- ISOControl* mControl;
-};
-
-// 14496-14 5.6 'Sample Description Boxes'
-// Box type: 'esds'
-class ESDBox : public FullBox {
-public:
- // ISO BMFF members
- RefPtr<ES_Descriptor> es_descriptor;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // ESDBox methods
- ESDBox(ISOControl* aControl);
- ~ESDBox();
-};
-
-// 14496-14 5.6 'Sample Description Boxes'
-// Box type: 'mp4a'
-class MP4AudioSampleEntry : public AudioSampleEntry {
-public:
- // ISO BMFF members
- RefPtr<ESDBox> es;
-
- // MuxerOperation methods
- nsresult Generate(uint32_t* aBoxSize) override;
- nsresult Write() override;
-
- // MP4AudioSampleEntry methods
- MP4AudioSampleEntry(ISOControl* aControl);
- ~MP4AudioSampleEntry();
-};
-
-}
-
-#endif // MP4ESDS_h_
diff --git a/dom/media/encoder/fmp4_muxer/MuxerOperation.h b/dom/media/encoder/fmp4_muxer/MuxerOperation.h
deleted file mode 100644
index 0b83c89b0..000000000
--- a/dom/media/encoder/fmp4_muxer/MuxerOperation.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* -*- 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 "nsString.h"
-#include "nsTArray.h"
-
-#ifndef MuxerOperation_h_
-#define MuxerOperation_h_
-
-namespace mozilla {
-
-/**
- * The interface for ISO box. All Boxes inherit from this interface.
- * Generate() and Write() are needed to be called to produce a complete box.
- *
- * Generate() will generate all the data structures and their size.
- *
- * Write() will write all data into muxing output stream (ISOControl actually)
- * and update the data which can't be known at Generate() (for example, the
- * offset of the video data in mp4 file).
- *
- * ISO base media format is composed of several container boxes and the contained
- * boxes. The container boxes hold a list of MuxerOperation which is implemented
- * by contained boxes. The contained boxes will be called via the list.
- * For example:
- * MovieBox (container) ---> boxes (array of MuxerOperation)
- * |---> MovieHeaderBox (full box)
- * |---> TrakBox (container)
- * |---> MovieExtendsBox (container)
- *
- * The complete box structure can be found at 14496-12 E.2 "The‘isom’brand".
- */
-class MuxerOperation {
-public:
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(MuxerOperation)
-
- // Generate data of this box and its contained box, and calculate box size.
- virtual nsresult Generate(uint32_t* aBoxSize) = 0;
-
- // Write data to stream.
- virtual nsresult Write() = 0;
-
- // Find the box type via its name (name is the box type defined in 14496-12;
- // for example, 'moov' is the name of MovieBox).
- // It can only look child boxes including itself and the box in the boxes
- // list if exists. It can't look parent boxes.
- virtual nsresult Find(const nsACString& aType,
- nsTArray<RefPtr<MuxerOperation>>& aOperations) = 0;
-
-protected:
- virtual ~MuxerOperation() {}
-};
-
-}
-#endif
diff --git a/dom/media/encoder/moz.build b/dom/media/encoder/moz.build
index 0d5cdc16f..f29430cb0 100644
--- a/dom/media/encoder/moz.build
+++ b/dom/media/encoder/moz.build
@@ -7,9 +7,6 @@
with Files('*'):
BUG_COMPONENT = ('Core', 'Video/Audio: Recording')
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DIRS += ['fmp4_muxer']
-
EXPORTS += [
'ContainerWriter.h',
'EncodedFrameContainer.h',
@@ -37,16 +34,6 @@ FINAL_LIBRARY = 'xul'
# These includes are from Android JB, for use of MediaCodec.
LOCAL_INCLUDES += ['/ipc/chromium/src']
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and CONFIG['ANDROID_VERSION'] > '15':
- LOCAL_INCLUDES += [
- '%' + '%s/%s' % (CONFIG['ANDROID_SOURCE'], d) for d in [
- 'frameworks/av/include/media',
- 'frameworks/native/include',
- 'frameworks/native/opengl/include',
- ]
-
- ]
-
include('/ipc/chromium/chromium-config.mozbuild')
# Suppress some GCC warnings being treated as errors:
diff --git a/dom/media/gmp/GMPChild.cpp b/dom/media/gmp/GMPChild.cpp
index f8e75e299..f83a927ca 100644
--- a/dom/media/gmp/GMPChild.cpp
+++ b/dom/media/gmp/GMPChild.cpp
@@ -36,12 +36,6 @@ static const int MAX_VOUCHER_LENGTH = 500000;
#include <unistd.h> // for _exit()
#endif
-#if defined(MOZ_GMP_SANDBOX)
-#if defined(XP_MACOSX)
-#include "mozilla/Sandbox.h"
-#endif
-#endif
-
namespace mozilla {
#undef LOG
@@ -131,7 +125,6 @@ GetPluginFile(const nsAString& aPluginPath,
return true;
}
-#if !defined(XP_MACOSX) || !defined(MOZ_GMP_SANDBOX)
static bool
GetPluginFile(const nsAString& aPluginPath,
nsCOMPtr<nsIFile>& aLibFile)
@@ -139,110 +132,6 @@ GetPluginFile(const nsAString& aPluginPath,
nsCOMPtr<nsIFile> unusedlibDir;
return GetPluginFile(aPluginPath, unusedlibDir, aLibFile);
}
-#endif
-
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
-static nsCString
-GetNativeTarget(nsIFile* aFile)
-{
- bool isLink;
- nsCString path;
- aFile->IsSymlink(&isLink);
- if (isLink) {
- aFile->GetNativeTarget(path);
- } else {
- aFile->GetNativePath(path);
- }
- return path;
-}
-
-static bool
-GetPluginPaths(const nsAString& aPluginPath,
- nsCString &aPluginDirectoryPath,
- nsCString &aPluginFilePath)
-{
- nsCOMPtr<nsIFile> libDirectory, libFile;
- if (!GetPluginFile(aPluginPath, libDirectory, libFile)) {
- return false;
- }
-
- // Mac sandbox rules expect paths to actual files and directories -- not
- // soft links.
- libDirectory->Normalize();
- aPluginDirectoryPath = GetNativeTarget(libDirectory);
-
- libFile->Normalize();
- aPluginFilePath = GetNativeTarget(libFile);
-
- return true;
-}
-
-static bool
-GetAppPaths(nsCString &aAppPath, nsCString &aAppBinaryPath)
-{
- nsAutoCString appPath;
- nsAutoCString appBinaryPath(
- (CommandLine::ForCurrentProcess()->argv()[0]).c_str());
-
- nsAutoCString::const_iterator start, end;
- appBinaryPath.BeginReading(start);
- appBinaryPath.EndReading(end);
- if (RFindInReadable(NS_LITERAL_CSTRING(".app/Contents/MacOS/"), start, end)) {
- end = start;
- ++end; ++end; ++end; ++end;
- appBinaryPath.BeginReading(start);
- appPath.Assign(Substring(start, end));
- } else {
- return false;
- }
-
- nsCOMPtr<nsIFile> app, appBinary;
- nsresult rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(appPath),
- true, getter_AddRefs(app));
- if (NS_FAILED(rv)) {
- return false;
- }
- rv = NS_NewLocalFile(NS_ConvertUTF8toUTF16(appBinaryPath),
- true, getter_AddRefs(appBinary));
- if (NS_FAILED(rv)) {
- return false;
- }
-
- // Mac sandbox rules expect paths to actual files and directories -- not
- // soft links.
- aAppPath = GetNativeTarget(app);
- appBinaryPath = GetNativeTarget(appBinary);
-
- return true;
-}
-
-bool
-GMPChild::SetMacSandboxInfo(MacSandboxPluginType aPluginType)
-{
- if (!mGMPLoader) {
- return false;
- }
- nsAutoCString pluginDirectoryPath, pluginFilePath;
- if (!GetPluginPaths(mPluginPath, pluginDirectoryPath, pluginFilePath)) {
- return false;
- }
- nsAutoCString appPath, appBinaryPath;
- if (!GetAppPaths(appPath, appBinaryPath)) {
- return false;
- }
-
- MacSandboxInfo info;
- info.type = MacSandboxType_Plugin;
- info.pluginInfo.type = aPluginType;
- info.pluginInfo.pluginPath.assign(pluginDirectoryPath.get());
- info.pluginInfo.pluginBinaryPath.assign(pluginFilePath.get());
- info.appPath.assign(appPath.get());
- info.appBinaryPath.assign(appBinaryPath.get());
-
- mGMPLoader->SetSandboxInfo(&info);
- return true;
-}
-#endif // XP_MACOSX && MOZ_GMP_SANDBOX
bool
GMPChild::Init(const nsAString& aPluginPath,
@@ -324,14 +213,6 @@ GMPChild::RecvPreloadLibs(const nsCString& aLibs)
bool
GMPChild::GetUTF8LibPath(nsACString& aOutLibPath)
{
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
- nsAutoCString pluginDirectoryPath, pluginFilePath;
- if (!GetPluginPaths(mPluginPath, pluginDirectoryPath, pluginFilePath)) {
- MOZ_CRASH("Error scanning plugin path");
- }
- aOutLibPath.Assign(pluginFilePath);
- return true;
-#else
nsCOMPtr<nsIFile> libFile;
if (!GetPluginFile(mPluginPath, libFile)) {
return false;
@@ -347,7 +228,6 @@ GMPChild::GetUTF8LibPath(nsACString& aOutLibPath)
aOutLibPath = NS_ConvertUTF16toUTF8(path);
return true;
-#endif
}
bool
@@ -377,17 +257,6 @@ GMPChild::AnswerStartPlugin(const nsString& aAdapter)
}
bool isWidevine = aAdapter.EqualsLiteral("widevine");
-#if defined(MOZ_GMP_SANDBOX) && defined(XP_MACOSX)
- MacSandboxPluginType pluginType = MacSandboxPluginType_GMPlugin_Default;
- if (isWidevine) {
- pluginType = MacSandboxPluginType_GMPlugin_EME_Widevine;
- }
- if (!SetMacSandboxInfo(pluginType)) {
- NS_WARNING("Failed to set Mac GMP sandbox info");
- delete platformAPI;
- return false;
- }
-#endif
GMPAdapter* adapter = (isWidevine) ? new WidevineAdapter() : nullptr;
if (!mGMPLoader->Load(libPath.get(),
diff --git a/dom/media/gmp/GMPChild.h b/dom/media/gmp/GMPChild.h
index d5314cf96..a4f688901 100644
--- a/dom/media/gmp/GMPChild.h
+++ b/dom/media/gmp/GMPChild.h
@@ -40,10 +40,6 @@ public:
// GMPAsyncShutdownHost
void ShutdownComplete() override;
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
- bool SetMacSandboxInfo(MacSandboxPluginType aPluginType);
-#endif
-
private:
friend class GMPContentChild;
diff --git a/dom/media/gmp/GMPLoader.cpp b/dom/media/gmp/GMPLoader.cpp
index c10208a49..0bccdd0b1 100644
--- a/dom/media/gmp/GMPLoader.cpp
+++ b/dom/media/gmp/GMPLoader.cpp
@@ -44,10 +44,6 @@ public:
void Shutdown() override;
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
- void SetSandboxInfo(MacSandboxInfo* aSandboxInfo) override;
-#endif
-
private:
SandboxStarter* mSandboxStarter;
UniquePtr<GMPAdapter> mAdapter;
@@ -208,15 +204,6 @@ GMPLoaderImpl::Shutdown()
}
}
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
-void
-GMPLoaderImpl::SetSandboxInfo(MacSandboxInfo* aSandboxInfo)
-{
- if (mSandboxStarter) {
- mSandboxStarter->SetSandboxInfo(aSandboxInfo);
- }
-}
-#endif
} // namespace gmp
} // namespace mozilla
diff --git a/dom/media/gmp/GMPLoader.h b/dom/media/gmp/GMPLoader.h
index 60581be2d..8e6b3cfac 100644
--- a/dom/media/gmp/GMPLoader.h
+++ b/dom/media/gmp/GMPLoader.h
@@ -12,10 +12,6 @@
#include "gmp-entrypoints.h"
#include "mozilla/UniquePtr.h"
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
-#include "mozilla/Sandbox.h"
-#endif
-
namespace mozilla {
namespace gmp {
@@ -23,12 +19,6 @@ class SandboxStarter {
public:
virtual ~SandboxStarter() {}
virtual bool Start(const char* aLibPath) = 0;
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
- // On OS X we need to set Mac-specific sandbox info just before we start the
- // sandbox, which we don't yet know when the GMPLoader and SandboxStarter
- // objects are created.
- virtual void SetSandboxInfo(MacSandboxInfo* aSandboxInfo) = 0;
-#endif
};
// Interface that adapts a plugin to the GMP API.
@@ -94,13 +84,6 @@ public:
// Calls the GMPShutdown function exported by the GMP lib, and unloads the
// plugin library.
virtual void Shutdown() = 0;
-
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
- // On OS X we need to set Mac-specific sandbox info just before we start the
- // sandbox, which we don't yet know when the GMPLoader and SandboxStarter
- // objects are created.
- virtual void SetSandboxInfo(MacSandboxInfo* aSandboxInfo) = 0;
-#endif
};
// On Desktop, this function resides in plugin-container.
diff --git a/dom/media/gmp/GMPParent.cpp b/dom/media/gmp/GMPParent.cpp
index 00bc97777..851634ce7 100644
--- a/dom/media/gmp/GMPParent.cpp
+++ b/dom/media/gmp/GMPParent.cpp
@@ -18,9 +18,6 @@
#include "nsIObserverService.h"
#include "GMPTimerParent.h"
#include "runnable_utils.h"
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
-#include "mozilla/SandboxInfo.h"
-#endif
#include "GMPContentParent.h"
#include "MediaPrefs.h"
#include "VideoUtils.h"
@@ -749,14 +746,6 @@ GMPParent::ReadGMPInfoFile(nsIFile* aFile)
if (cap.mAPIName.EqualsLiteral(GMP_API_DECRYPTOR)) {
mCanDecrypt = true;
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
- if (!mozilla::SandboxInfo::Get().CanSandboxMedia()) {
- printf_stderr("GMPParent::ReadGMPMetaData: Plugin \"%s\" is an EME CDM"
- " but this system can't sandbox it; not loading.\n",
- mDisplayName.get());
- return GenericPromise::CreateAndReject(NS_ERROR_FAILURE, __func__);
- }
-#endif
#ifdef XP_WIN
// Adobe GMP doesn't work without SSE2. Check the tags to see if
// the decryptor is for the Adobe GMP, and refuse to load it if
diff --git a/dom/media/gmp/GMPProcessParent.cpp b/dom/media/gmp/GMPProcessParent.cpp
index 2fe7306a4..ef58175e8 100644
--- a/dom/media/gmp/GMPProcessParent.cpp
+++ b/dom/media/gmp/GMPProcessParent.cpp
@@ -8,9 +8,6 @@
#include "GMPUtils.h"
#include "nsIFile.h"
#include "nsIRunnable.h"
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-#include "WinUtils.h"
-#endif
#include "base/string_util.h"
#include "base/process_util.h"
@@ -56,38 +53,7 @@ GMPProcessParent::Launch(int32_t aTimeoutMs)
vector<string> args;
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- std::wstring wGMPPath = UTF8ToWide(mGMPPath.c_str());
-
- // The sandbox doesn't allow file system rules where the paths contain
- // symbolic links or junction points. Sometimes the Users folder has been
- // moved to another drive using a junction point, so allow for this specific
- // case. See bug 1236680 for details.
- if (!widget::WinUtils::ResolveJunctionPointsAndSymLinks(wGMPPath)) {
- GMP_LOG("ResolveJunctionPointsAndSymLinks failed for GMP path=%S",
- wGMPPath.c_str());
- NS_WARNING("ResolveJunctionPointsAndSymLinks failed for GMP path.");
- return false;
- }
- GMP_LOG("GMPProcessParent::Launch() resolved path to %S", wGMPPath.c_str());
-
- // If the GMP path is a network path that is not mapped to a drive letter,
- // then we need to fix the path format for the sandbox rule.
- wchar_t volPath[MAX_PATH];
- if (::GetVolumePathNameW(wGMPPath.c_str(), volPath, MAX_PATH) &&
- ::GetDriveTypeW(volPath) == DRIVE_REMOTE &&
- wGMPPath.compare(0, 2, L"\\\\") == 0) {
- std::wstring sandboxGMPPath(wGMPPath);
- sandboxGMPPath.insert(1, L"??\\UNC");
- mAllowedFilesRead.push_back(sandboxGMPPath + L"\\*");
- } else {
- mAllowedFilesRead.push_back(wGMPPath + L"\\*");
- }
-
- args.push_back(WideToUTF8(wGMPPath));
-#else
args.push_back(mGMPPath);
-#endif
args.push_back(string(voucherPath.BeginReading(), voucherPath.EndReading()));
diff --git a/dom/media/gmp/GMPService.cpp b/dom/media/gmp/GMPService.cpp
index 65f4037ee..1901210da 100644
--- a/dom/media/gmp/GMPService.cpp
+++ b/dom/media/gmp/GMPService.cpp
@@ -25,9 +25,6 @@
#include "nsComponentManagerUtils.h"
#include "runnable_utils.h"
#include "VideoUtils.h"
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
-#include "mozilla/SandboxInfo.h"
-#endif
#include "nsAppDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
@@ -485,14 +482,6 @@ GeckoMediaPluginService::GetGMPDecryptor(GMPCrashHelper* aHelper,
const nsACString& aNodeId,
UniquePtr<GetGMPDecryptorCallback>&& aCallback)
{
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
- if (!SandboxInfo::Get().CanSandboxMedia()) {
- NS_WARNING("GeckoMediaPluginService::GetGMPDecryptor: "
- "EME decryption not available without sandboxing support.");
- return NS_ERROR_NOT_AVAILABLE;
- }
-#endif
-
MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread);
NS_ENSURE_ARG(aTags && aTags->Length() > 0);
NS_ENSURE_ARG(aCallback);
diff --git a/dom/media/gmp/GMPServiceParent.cpp b/dom/media/gmp/GMPServiceParent.cpp
index f25c36811..2b4831cd6 100644
--- a/dom/media/gmp/GMPServiceParent.cpp
+++ b/dom/media/gmp/GMPServiceParent.cpp
@@ -27,9 +27,6 @@
#include "nsComponentManagerUtils.h"
#include "runnable_utils.h"
#include "VideoUtils.h"
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
-#include "mozilla/SandboxInfo.h"
-#endif
#include "nsAppDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
@@ -273,11 +270,7 @@ GeckoMediaPluginServiceParent::InitStorage()
// Directory service is main thread only, so cache the profile dir here
// so that we can use it off main thread.
-#ifdef MOZ_WIDGET_GONK
- nsresult rv = NS_NewLocalFile(NS_LITERAL_STRING("/data/b2g/mozilla"), false, getter_AddRefs(mStorageBaseDir));
-#else
nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(mStorageBaseDir));
-#endif
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
@@ -960,15 +953,6 @@ GeckoMediaPluginServiceParent::SelectPluginForAPI(const nsACString& aNodeId,
RefPtr<GMPParent>
CreateGMPParent()
{
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
- if (!SandboxInfo::Get().CanSandboxMedia()) {
- if (!MediaPrefs::GMPAllowInsecure()) {
- NS_WARNING("Denying media plugin load due to lack of sandboxing.");
- return nullptr;
- }
- NS_WARNING("Loading media plugin despite lack of sandboxing.");
- }
-#endif
return new GMPParent();
}
diff --git a/dom/media/gmp/rlz/GMPDeviceBinding.cpp b/dom/media/gmp/rlz/GMPDeviceBinding.cpp
index c8aee2bcd..3525f0462 100644
--- a/dom/media/gmp/rlz/GMPDeviceBinding.cpp
+++ b/dom/media/gmp/rlz/GMPDeviceBinding.cpp
@@ -12,10 +12,6 @@
#ifdef XP_WIN
#include "windows.h"
-#ifdef MOZ_SANDBOX
-#include <intrin.h>
-#include <assert.h>
-#endif
#endif
#if defined(HASH_NODE_ID_WITH_DEVICE_ID)
@@ -35,10 +31,6 @@
#ifdef XP_WIN
#include "windows.h"
-#ifdef MOZ_SANDBOX
-#include <intrin.h>
-#include <assert.h>
-#endif
#endif
#ifdef XP_MACOSX
diff --git a/dom/media/gmp/rlz/moz.build b/dom/media/gmp/rlz/moz.build
index f366c2b5d..5e85357f1 100644
--- a/dom/media/gmp/rlz/moz.build
+++ b/dom/media/gmp/rlz/moz.build
@@ -13,13 +13,6 @@ UNIFIED_SOURCES += [
'GMPDeviceBinding.cpp',
]
-if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_TARGET'] in ['WINNT', 'Darwin']:
- DEFINES['HASH_NODE_ID_WITH_DEVICE_ID'] = 1;
- UNIFIED_SOURCES += [
- 'lib/string_utils.cc',
- 'sha256.c',
- ]
-
if CONFIG['OS_TARGET'] == 'WINNT':
UNIFIED_SOURCES += [
'win/lib/machine_id_win.cc',
diff --git a/dom/media/moz.build b/dom/media/moz.build
index d1885793b..4d036a5f6 100644
--- a/dom/media/moz.build
+++ b/dom/media/moz.build
@@ -169,11 +169,6 @@ IPDL_SOURCES += [
'webrtc/PWebrtcGlobal.ipdl'
]
-if CONFIG['MOZ_B2G']:
- EXPORTS.mozilla += [
- 'MediaPermissionGonk.h',
- ]
-
EXPORTS.mozilla.dom += [
'AudioStreamTrack.h',
'AudioTrack.h',
@@ -270,11 +265,6 @@ UNIFIED_SOURCES += [
if CONFIG['OS_TARGET'] == 'WINNT':
SOURCES += [ 'ThreadPoolCOMListener.cpp' ]
-if CONFIG['MOZ_B2G']:
- SOURCES += [
- 'MediaPermissionGonk.cpp',
- ]
-
# DecoderTraits.cpp needs to be built separately because of Mac OS X headers.
SOURCES += [
'DecoderTraits.cpp',
@@ -325,9 +315,6 @@ else:
if CONFIG['ANDROID_VERSION'] > '15':
DEFINES['MOZ_OMX_WEBM_DECODER'] = True
-if CONFIG['MOZ_GONK_MEDIACODEC']:
- DEFINES['MOZ_GONK_MEDIACODEC'] = True
-
include('/ipc/chromium/chromium-config.mozbuild')
# Suppress some GCC warnings being treated as errors:
diff --git a/dom/media/ogg/OggCodecState.cpp b/dom/media/ogg/OggCodecState.cpp
index 6830639e8..e7e1ca4a3 100644
--- a/dom/media/ogg/OggCodecState.cpp
+++ b/dom/media/ogg/OggCodecState.cpp
@@ -18,18 +18,6 @@
#include <opus/opus.h>
#include "opus/opus_multistream.h"
-// On Android JellyBean, the hardware.h header redefines version_major and
-// version_minor, which breaks our build. See:
-// https://bugzilla.mozilla.org/show_bug.cgi?id=912702#c6
-#ifdef MOZ_WIDGET_GONK
-#ifdef version_major
-#undef version_major
-#endif
-#ifdef version_minor
-#undef version_minor
-#endif
-#endif
-
namespace mozilla {
extern LazyLogModule gMediaDecoderLog;
diff --git a/dom/media/ogg/OggWriter.cpp b/dom/media/ogg/OggWriter.cpp
index bb0dca67b..e1aa93eaf 100644
--- a/dom/media/ogg/OggWriter.cpp
+++ b/dom/media/ogg/OggWriter.cpp
@@ -7,12 +7,7 @@
#include "GeckoProfiler.h"
#undef LOG
-#ifdef MOZ_WIDGET_GONK
-#include <android/log.h>
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "MediaEncoder", ## args);
-#else
#define LOG(args, ...)
-#endif
namespace mozilla {
diff --git a/dom/media/platforms/ffmpeg/FFmpegDataDecoder.cpp b/dom/media/platforms/ffmpeg/FFmpegDataDecoder.cpp
index 0b31fb0f9..8cb5c8578 100644
--- a/dom/media/platforms/ffmpeg/FFmpegDataDecoder.cpp
+++ b/dom/media/platforms/ffmpeg/FFmpegDataDecoder.cpp
@@ -69,15 +69,21 @@ FFmpegDataDecoder<LIBAV_VER>::InitDecoder()
mCodecContext->extradata_size = mExtraData->Length();
// FFmpeg may use SIMD instructions to access the data which reads the
// data in 32 bytes block. Must ensure we have enough data to read.
+#if LIBAVCODEC_VERSION_MAJOR >= 58
+ mExtraData->AppendElements(AV_INPUT_BUFFER_PADDING_SIZE);
+#else
mExtraData->AppendElements(FF_INPUT_BUFFER_PADDING_SIZE);
+#endif
mCodecContext->extradata = mExtraData->Elements();
} else {
mCodecContext->extradata_size = 0;
}
+#if LIBAVCODEC_VERSION_MAJOR < 57
if (codec->capabilities & CODEC_CAP_DR1) {
mCodecContext->flags |= CODEC_FLAG_EMU_EDGE;
}
+#endif
if (mLib->avcodec_open2(mCodecContext, codec, nullptr) < 0) {
NS_WARNING("Couldn't initialise ffmpeg decoder");
diff --git a/dom/media/platforms/ffmpeg/FFmpegLibWrapper.cpp b/dom/media/platforms/ffmpeg/FFmpegLibWrapper.cpp
index f3dc00ad7..6302882a6 100644
--- a/dom/media/platforms/ffmpeg/FFmpegLibWrapper.cpp
+++ b/dom/media/platforms/ffmpeg/FFmpegLibWrapper.cpp
@@ -69,12 +69,14 @@ FFmpegLibWrapper::Link()
AV_FUNC_55 = 1 << 2,
AV_FUNC_56 = 1 << 3,
AV_FUNC_57 = 1 << 4,
+ AV_FUNC_58 = 1 << 5,
AV_FUNC_AVUTIL_53 = AV_FUNC_53 | AV_FUNC_AVUTIL_MASK,
AV_FUNC_AVUTIL_54 = AV_FUNC_54 | AV_FUNC_AVUTIL_MASK,
AV_FUNC_AVUTIL_55 = AV_FUNC_55 | AV_FUNC_AVUTIL_MASK,
AV_FUNC_AVUTIL_56 = AV_FUNC_56 | AV_FUNC_AVUTIL_MASK,
AV_FUNC_AVUTIL_57 = AV_FUNC_57 | AV_FUNC_AVUTIL_MASK,
- AV_FUNC_AVCODEC_ALL = AV_FUNC_53 | AV_FUNC_54 | AV_FUNC_55 | AV_FUNC_56 | AV_FUNC_57,
+ AV_FUNC_AVUTIL_58 = AV_FUNC_58 | AV_FUNC_AVUTIL_MASK,
+ AV_FUNC_AVCODEC_ALL = AV_FUNC_53 | AV_FUNC_54 | AV_FUNC_55 | AV_FUNC_56 | AV_FUNC_57 | AV_FUNC_58,
AV_FUNC_AVUTIL_ALL = AV_FUNC_AVCODEC_ALL | AV_FUNC_AVUTIL_MASK
};
@@ -94,6 +96,9 @@ FFmpegLibWrapper::Link()
case 57:
version = AV_FUNC_57;
break;
+ case 58:
+ version = AV_FUNC_58;
+ break;
default:
FFMPEG_LOG("Unknown avcodec version");
Unlink();
@@ -142,9 +147,9 @@ FFmpegLibWrapper::Link()
AV_FUNC(av_log_set_level, AV_FUNC_AVUTIL_ALL)
AV_FUNC(av_malloc, AV_FUNC_AVUTIL_ALL)
AV_FUNC(av_freep, AV_FUNC_AVUTIL_ALL)
- AV_FUNC(av_frame_alloc, (AV_FUNC_AVUTIL_55 | AV_FUNC_AVUTIL_56 | AV_FUNC_AVUTIL_57))
- AV_FUNC(av_frame_free, (AV_FUNC_AVUTIL_55 | AV_FUNC_AVUTIL_56 | AV_FUNC_AVUTIL_57))
- AV_FUNC(av_frame_unref, (AV_FUNC_AVUTIL_55 | AV_FUNC_AVUTIL_56 | AV_FUNC_AVUTIL_57))
+ AV_FUNC(av_frame_alloc, (AV_FUNC_AVUTIL_55 | AV_FUNC_AVUTIL_56 | AV_FUNC_AVUTIL_57 | AV_FUNC_AVUTIL_58))
+ AV_FUNC(av_frame_free, (AV_FUNC_AVUTIL_55 | AV_FUNC_AVUTIL_56 | AV_FUNC_AVUTIL_57 | AV_FUNC_AVUTIL_58))
+ AV_FUNC(av_frame_unref, (AV_FUNC_AVUTIL_55 | AV_FUNC_AVUTIL_56 | AV_FUNC_AVUTIL_57 | AV_FUNC_AVUTIL_58))
AV_FUNC_OPTION(av_frame_get_colorspace, AV_FUNC_AVUTIL_ALL)
#undef AV_FUNC
#undef AV_FUNC_OPTION
@@ -175,4 +180,4 @@ FFmpegLibWrapper::Unlink()
PodZero(this);
}
-} // namespace mozilla \ No newline at end of file
+} // namespace mozilla
diff --git a/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp b/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp
index fdbe77ef7..4671499e5 100644
--- a/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp
+++ b/dom/media/platforms/ffmpeg/FFmpegRuntimeLinker.cpp
@@ -27,12 +27,15 @@ static FFmpegLibWrapper sLibAV;
static const char* sLibs[] = {
#if defined(XP_DARWIN)
+ "libavcodec.58.dylib",
"libavcodec.57.dylib",
"libavcodec.56.dylib",
"libavcodec.55.dylib",
"libavcodec.54.dylib",
"libavcodec.53.dylib",
#else
+ "libavcodec.so.58",
+ "libavcodec-ffmpeg.so.58",
"libavcodec-ffmpeg.so.57",
"libavcodec-ffmpeg.so.56",
"libavcodec.so.57",
@@ -134,6 +137,7 @@ FFmpegRuntimeLinker::CreateDecoderModule()
case 55:
case 56: module = FFmpegDecoderModule<55>::Create(&sLibAV); break;
case 57: module = FFmpegDecoderModule<57>::Create(&sLibAV); break;
+ case 58: module = FFmpegDecoderModule<58>::Create(&sLibAV); break;
default: module = nullptr;
}
return module.forget();
diff --git a/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp b/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp
index 5c1b6c97b..aec1e9136 100644
--- a/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp
+++ b/dom/media/platforms/ffmpeg/FFmpegVideoDecoder.cpp
@@ -181,8 +181,8 @@ FFmpegVideoDecoder<LIBAV_VER>::DoDecode(MediaRawData* aSample, bool* aGotFrame)
#endif
)) {
while (inputSize) {
- uint8_t* data;
- int size;
+ uint8_t* data = inputData;
+ int size = inputSize;
int len = mLib->av_parser_parse2(mCodecParser, mCodecContext, &data, &size,
inputData, inputSize,
aSample->mTime, aSample->mTimecode,
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/COPYING.LGPLv2.1 b/dom/media/platforms/ffmpeg/ffmpeg58/include/COPYING.LGPLv2.1
new file mode 100644
index 000000000..00b4fedfe
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/COPYING.LGPLv2.1
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library 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
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/avcodec.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/avcodec.h
new file mode 100644
index 000000000..fb0c6fae7
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/avcodec.h
@@ -0,0 +1,6146 @@
+/*
+ * copyright (c) 2001 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AVCODEC_H
+#define AVCODEC_AVCODEC_H
+
+/**
+ * @file
+ * @ingroup libavc
+ * Libavcodec external API header
+ */
+
+#include <errno.h>
+#include "libavutil/samplefmt.h"
+#include "libavutil/attributes.h"
+#include "libavutil/avutil.h"
+#include "libavutil/buffer.h"
+#include "libavutil/cpu.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/dict.h"
+#include "libavutil/frame.h"
+#include "libavutil/hwcontext.h"
+#include "libavutil/log.h"
+#include "libavutil/pixfmt.h"
+#include "libavutil/rational.h"
+
+#include "version.h"
+
+/**
+ * @defgroup libavc libavcodec
+ * Encoding/Decoding Library
+ *
+ * @{
+ *
+ * @defgroup lavc_decoding Decoding
+ * @{
+ * @}
+ *
+ * @defgroup lavc_encoding Encoding
+ * @{
+ * @}
+ *
+ * @defgroup lavc_codec Codecs
+ * @{
+ * @defgroup lavc_codec_native Native Codecs
+ * @{
+ * @}
+ * @defgroup lavc_codec_wrappers External library wrappers
+ * @{
+ * @}
+ * @defgroup lavc_codec_hwaccel Hardware Accelerators bridge
+ * @{
+ * @}
+ * @}
+ * @defgroup lavc_internal Internal
+ * @{
+ * @}
+ * @}
+ */
+
+/**
+ * @ingroup libavc
+ * @defgroup lavc_encdec send/receive encoding and decoding API overview
+ * @{
+ *
+ * The avcodec_send_packet()/avcodec_receive_frame()/avcodec_send_frame()/
+ * avcodec_receive_packet() functions provide an encode/decode API, which
+ * decouples input and output.
+ *
+ * The API is very similar for encoding/decoding and audio/video, and works as
+ * follows:
+ * - Set up and open the AVCodecContext as usual.
+ * - Send valid input:
+ * - For decoding, call avcodec_send_packet() to give the decoder raw
+ * compressed data in an AVPacket.
+ * - For encoding, call avcodec_send_frame() to give the encoder an AVFrame
+ * containing uncompressed audio or video.
+ * In both cases, it is recommended that AVPackets and AVFrames are
+ * refcounted, or libavcodec might have to copy the input data. (libavformat
+ * always returns refcounted AVPackets, and av_frame_get_buffer() allocates
+ * refcounted AVFrames.)
+ * - Receive output in a loop. Periodically call one of the avcodec_receive_*()
+ * functions and process their output:
+ * - For decoding, call avcodec_receive_frame(). On success, it will return
+ * an AVFrame containing uncompressed audio or video data.
+ * - For encoding, call avcodec_receive_packet(). On success, it will return
+ * an AVPacket with a compressed frame.
+ * Repeat this call until it returns AVERROR(EAGAIN) or an error. The
+ * AVERROR(EAGAIN) return value means that new input data is required to
+ * return new output. In this case, continue with sending input. For each
+ * input frame/packet, the codec will typically return 1 output frame/packet,
+ * but it can also be 0 or more than 1.
+ *
+ * At the beginning of decoding or encoding, the codec might accept multiple
+ * input frames/packets without returning a frame, until its internal buffers
+ * are filled. This situation is handled transparently if you follow the steps
+ * outlined above.
+ *
+ * In theory, sending input can result in EAGAIN - this should happen only if
+ * not all output was received. You can use this to structure alternative decode
+ * or encode loops other than the one suggested above. For example, you could
+ * try sending new input on each iteration, and try to receive output if that
+ * returns EAGAIN.
+ *
+ * End of stream situations. These require "flushing" (aka draining) the codec,
+ * as the codec might buffer multiple frames or packets internally for
+ * performance or out of necessity (consider B-frames).
+ * This is handled as follows:
+ * - Instead of valid input, send NULL to the avcodec_send_packet() (decoding)
+ * or avcodec_send_frame() (encoding) functions. This will enter draining
+ * mode.
+ * - Call avcodec_receive_frame() (decoding) or avcodec_receive_packet()
+ * (encoding) in a loop until AVERROR_EOF is returned. The functions will
+ * not return AVERROR(EAGAIN), unless you forgot to enter draining mode.
+ * - Before decoding can be resumed again, the codec has to be reset with
+ * avcodec_flush_buffers().
+ *
+ * Using the API as outlined above is highly recommended. But it is also
+ * possible to call functions outside of this rigid schema. For example, you can
+ * call avcodec_send_packet() repeatedly without calling
+ * avcodec_receive_frame(). In this case, avcodec_send_packet() will succeed
+ * until the codec's internal buffer has been filled up (which is typically of
+ * size 1 per output frame, after initial input), and then reject input with
+ * AVERROR(EAGAIN). Once it starts rejecting input, you have no choice but to
+ * read at least some output.
+ *
+ * Not all codecs will follow a rigid and predictable dataflow; the only
+ * guarantee is that an AVERROR(EAGAIN) return value on a send/receive call on
+ * one end implies that a receive/send call on the other end will succeed, or
+ * at least will not fail with AVERROR(EAGAIN). In general, no codec will
+ * permit unlimited buffering of input or output.
+ *
+ * This API replaces the following legacy functions:
+ * - avcodec_decode_video2() and avcodec_decode_audio4():
+ * Use avcodec_send_packet() to feed input to the decoder, then use
+ * avcodec_receive_frame() to receive decoded frames after each packet.
+ * Unlike with the old video decoding API, multiple frames might result from
+ * a packet. For audio, splitting the input packet into frames by partially
+ * decoding packets becomes transparent to the API user. You never need to
+ * feed an AVPacket to the API twice (unless it is rejected with AVERROR(EAGAIN) - then
+ * no data was read from the packet).
+ * Additionally, sending a flush/draining packet is required only once.
+ * - avcodec_encode_video2()/avcodec_encode_audio2():
+ * Use avcodec_send_frame() to feed input to the encoder, then use
+ * avcodec_receive_packet() to receive encoded packets.
+ * Providing user-allocated buffers for avcodec_receive_packet() is not
+ * possible.
+ * - The new API does not handle subtitles yet.
+ *
+ * Mixing new and old function calls on the same AVCodecContext is not allowed,
+ * and will result in undefined behavior.
+ *
+ * Some codecs might require using the new API; using the old API will return
+ * an error when calling it. All codecs support the new API.
+ *
+ * A codec is not allowed to return AVERROR(EAGAIN) for both sending and receiving. This
+ * would be an invalid state, which could put the codec user into an endless
+ * loop. The API has no concept of time either: it cannot happen that trying to
+ * do avcodec_send_packet() results in AVERROR(EAGAIN), but a repeated call 1 second
+ * later accepts the packet (with no other receive/flush API calls involved).
+ * The API is a strict state machine, and the passage of time is not supposed
+ * to influence it. Some timing-dependent behavior might still be deemed
+ * acceptable in certain cases. But it must never result in both send/receive
+ * returning EAGAIN at the same time at any point. It must also absolutely be
+ * avoided that the current state is "unstable" and can "flip-flop" between
+ * the send/receive APIs allowing progress. For example, it's not allowed that
+ * the codec randomly decides that it actually wants to consume a packet now
+ * instead of returning a frame, after it just returned AVERROR(EAGAIN) on an
+ * avcodec_send_packet() call.
+ * @}
+ */
+
+/**
+ * @defgroup lavc_core Core functions/structures.
+ * @ingroup libavc
+ *
+ * Basic definitions, functions for querying libavcodec capabilities,
+ * allocating core structures, etc.
+ * @{
+ */
+
+
+/**
+ * Identify the syntax and semantics of the bitstream.
+ * The principle is roughly:
+ * Two decoders with the same ID can decode the same streams.
+ * Two encoders with the same ID can encode compatible streams.
+ * There may be slight deviations from the principle due to implementation
+ * details.
+ *
+ * If you add a codec ID to this list, add it so that
+ * 1. no value of an existing codec ID changes (that would break ABI),
+ * 2. it is as close as possible to similar codecs
+ *
+ * After adding new codec IDs, do not forget to add an entry to the codec
+ * descriptor list and bump libavcodec minor version.
+ */
+enum AVCodecID {
+ AV_CODEC_ID_NONE,
+
+ /* video codecs */
+ AV_CODEC_ID_MPEG1VIDEO,
+ AV_CODEC_ID_MPEG2VIDEO, ///< preferred ID for MPEG-1/2 video decoding
+ AV_CODEC_ID_H261,
+ AV_CODEC_ID_H263,
+ AV_CODEC_ID_RV10,
+ AV_CODEC_ID_RV20,
+ AV_CODEC_ID_MJPEG,
+ AV_CODEC_ID_MJPEGB,
+ AV_CODEC_ID_LJPEG,
+ AV_CODEC_ID_SP5X,
+ AV_CODEC_ID_JPEGLS,
+ AV_CODEC_ID_MPEG4,
+ AV_CODEC_ID_RAWVIDEO,
+ AV_CODEC_ID_MSMPEG4V1,
+ AV_CODEC_ID_MSMPEG4V2,
+ AV_CODEC_ID_MSMPEG4V3,
+ AV_CODEC_ID_WMV1,
+ AV_CODEC_ID_WMV2,
+ AV_CODEC_ID_H263P,
+ AV_CODEC_ID_H263I,
+ AV_CODEC_ID_FLV1,
+ AV_CODEC_ID_SVQ1,
+ AV_CODEC_ID_SVQ3,
+ AV_CODEC_ID_DVVIDEO,
+ AV_CODEC_ID_HUFFYUV,
+ AV_CODEC_ID_CYUV,
+ AV_CODEC_ID_H264,
+ AV_CODEC_ID_INDEO3,
+ AV_CODEC_ID_VP3,
+ AV_CODEC_ID_THEORA,
+ AV_CODEC_ID_ASV1,
+ AV_CODEC_ID_ASV2,
+ AV_CODEC_ID_FFV1,
+ AV_CODEC_ID_4XM,
+ AV_CODEC_ID_VCR1,
+ AV_CODEC_ID_CLJR,
+ AV_CODEC_ID_MDEC,
+ AV_CODEC_ID_ROQ,
+ AV_CODEC_ID_INTERPLAY_VIDEO,
+ AV_CODEC_ID_XAN_WC3,
+ AV_CODEC_ID_XAN_WC4,
+ AV_CODEC_ID_RPZA,
+ AV_CODEC_ID_CINEPAK,
+ AV_CODEC_ID_WS_VQA,
+ AV_CODEC_ID_MSRLE,
+ AV_CODEC_ID_MSVIDEO1,
+ AV_CODEC_ID_IDCIN,
+ AV_CODEC_ID_8BPS,
+ AV_CODEC_ID_SMC,
+ AV_CODEC_ID_FLIC,
+ AV_CODEC_ID_TRUEMOTION1,
+ AV_CODEC_ID_VMDVIDEO,
+ AV_CODEC_ID_MSZH,
+ AV_CODEC_ID_ZLIB,
+ AV_CODEC_ID_QTRLE,
+ AV_CODEC_ID_TSCC,
+ AV_CODEC_ID_ULTI,
+ AV_CODEC_ID_QDRAW,
+ AV_CODEC_ID_VIXL,
+ AV_CODEC_ID_QPEG,
+ AV_CODEC_ID_PNG,
+ AV_CODEC_ID_PPM,
+ AV_CODEC_ID_PBM,
+ AV_CODEC_ID_PGM,
+ AV_CODEC_ID_PGMYUV,
+ AV_CODEC_ID_PAM,
+ AV_CODEC_ID_FFVHUFF,
+ AV_CODEC_ID_RV30,
+ AV_CODEC_ID_RV40,
+ AV_CODEC_ID_VC1,
+ AV_CODEC_ID_WMV3,
+ AV_CODEC_ID_LOCO,
+ AV_CODEC_ID_WNV1,
+ AV_CODEC_ID_AASC,
+ AV_CODEC_ID_INDEO2,
+ AV_CODEC_ID_FRAPS,
+ AV_CODEC_ID_TRUEMOTION2,
+ AV_CODEC_ID_BMP,
+ AV_CODEC_ID_CSCD,
+ AV_CODEC_ID_MMVIDEO,
+ AV_CODEC_ID_ZMBV,
+ AV_CODEC_ID_AVS,
+ AV_CODEC_ID_SMACKVIDEO,
+ AV_CODEC_ID_NUV,
+ AV_CODEC_ID_KMVC,
+ AV_CODEC_ID_FLASHSV,
+ AV_CODEC_ID_CAVS,
+ AV_CODEC_ID_JPEG2000,
+ AV_CODEC_ID_VMNC,
+ AV_CODEC_ID_VP5,
+ AV_CODEC_ID_VP6,
+ AV_CODEC_ID_VP6F,
+ AV_CODEC_ID_TARGA,
+ AV_CODEC_ID_DSICINVIDEO,
+ AV_CODEC_ID_TIERTEXSEQVIDEO,
+ AV_CODEC_ID_TIFF,
+ AV_CODEC_ID_GIF,
+ AV_CODEC_ID_DXA,
+ AV_CODEC_ID_DNXHD,
+ AV_CODEC_ID_THP,
+ AV_CODEC_ID_SGI,
+ AV_CODEC_ID_C93,
+ AV_CODEC_ID_BETHSOFTVID,
+ AV_CODEC_ID_PTX,
+ AV_CODEC_ID_TXD,
+ AV_CODEC_ID_VP6A,
+ AV_CODEC_ID_AMV,
+ AV_CODEC_ID_VB,
+ AV_CODEC_ID_PCX,
+ AV_CODEC_ID_SUNRAST,
+ AV_CODEC_ID_INDEO4,
+ AV_CODEC_ID_INDEO5,
+ AV_CODEC_ID_MIMIC,
+ AV_CODEC_ID_RL2,
+ AV_CODEC_ID_ESCAPE124,
+ AV_CODEC_ID_DIRAC,
+ AV_CODEC_ID_BFI,
+ AV_CODEC_ID_CMV,
+ AV_CODEC_ID_MOTIONPIXELS,
+ AV_CODEC_ID_TGV,
+ AV_CODEC_ID_TGQ,
+ AV_CODEC_ID_TQI,
+ AV_CODEC_ID_AURA,
+ AV_CODEC_ID_AURA2,
+ AV_CODEC_ID_V210X,
+ AV_CODEC_ID_TMV,
+ AV_CODEC_ID_V210,
+ AV_CODEC_ID_DPX,
+ AV_CODEC_ID_MAD,
+ AV_CODEC_ID_FRWU,
+ AV_CODEC_ID_FLASHSV2,
+ AV_CODEC_ID_CDGRAPHICS,
+ AV_CODEC_ID_R210,
+ AV_CODEC_ID_ANM,
+ AV_CODEC_ID_BINKVIDEO,
+ AV_CODEC_ID_IFF_ILBM,
+#define AV_CODEC_ID_IFF_BYTERUN1 AV_CODEC_ID_IFF_ILBM
+ AV_CODEC_ID_KGV1,
+ AV_CODEC_ID_YOP,
+ AV_CODEC_ID_VP8,
+ AV_CODEC_ID_PICTOR,
+ AV_CODEC_ID_ANSI,
+ AV_CODEC_ID_A64_MULTI,
+ AV_CODEC_ID_A64_MULTI5,
+ AV_CODEC_ID_R10K,
+ AV_CODEC_ID_MXPEG,
+ AV_CODEC_ID_LAGARITH,
+ AV_CODEC_ID_PRORES,
+ AV_CODEC_ID_JV,
+ AV_CODEC_ID_DFA,
+ AV_CODEC_ID_WMV3IMAGE,
+ AV_CODEC_ID_VC1IMAGE,
+ AV_CODEC_ID_UTVIDEO,
+ AV_CODEC_ID_BMV_VIDEO,
+ AV_CODEC_ID_VBLE,
+ AV_CODEC_ID_DXTORY,
+ AV_CODEC_ID_V410,
+ AV_CODEC_ID_XWD,
+ AV_CODEC_ID_CDXL,
+ AV_CODEC_ID_XBM,
+ AV_CODEC_ID_ZEROCODEC,
+ AV_CODEC_ID_MSS1,
+ AV_CODEC_ID_MSA1,
+ AV_CODEC_ID_TSCC2,
+ AV_CODEC_ID_MTS2,
+ AV_CODEC_ID_CLLC,
+ AV_CODEC_ID_MSS2,
+ AV_CODEC_ID_VP9,
+ AV_CODEC_ID_AIC,
+ AV_CODEC_ID_ESCAPE130,
+ AV_CODEC_ID_G2M,
+ AV_CODEC_ID_WEBP,
+ AV_CODEC_ID_HNM4_VIDEO,
+ AV_CODEC_ID_HEVC,
+#define AV_CODEC_ID_H265 AV_CODEC_ID_HEVC
+ AV_CODEC_ID_FIC,
+ AV_CODEC_ID_ALIAS_PIX,
+ AV_CODEC_ID_BRENDER_PIX,
+ AV_CODEC_ID_PAF_VIDEO,
+ AV_CODEC_ID_EXR,
+ AV_CODEC_ID_VP7,
+ AV_CODEC_ID_SANM,
+ AV_CODEC_ID_SGIRLE,
+ AV_CODEC_ID_MVC1,
+ AV_CODEC_ID_MVC2,
+ AV_CODEC_ID_HQX,
+ AV_CODEC_ID_TDSC,
+ AV_CODEC_ID_HQ_HQA,
+ AV_CODEC_ID_HAP,
+ AV_CODEC_ID_DDS,
+ AV_CODEC_ID_DXV,
+ AV_CODEC_ID_SCREENPRESSO,
+ AV_CODEC_ID_RSCC,
+
+ AV_CODEC_ID_Y41P = 0x8000,
+ AV_CODEC_ID_AVRP,
+ AV_CODEC_ID_012V,
+ AV_CODEC_ID_AVUI,
+ AV_CODEC_ID_AYUV,
+ AV_CODEC_ID_TARGA_Y216,
+ AV_CODEC_ID_V308,
+ AV_CODEC_ID_V408,
+ AV_CODEC_ID_YUV4,
+ AV_CODEC_ID_AVRN,
+ AV_CODEC_ID_CPIA,
+ AV_CODEC_ID_XFACE,
+ AV_CODEC_ID_SNOW,
+ AV_CODEC_ID_SMVJPEG,
+ AV_CODEC_ID_APNG,
+ AV_CODEC_ID_DAALA,
+ AV_CODEC_ID_CFHD,
+ AV_CODEC_ID_TRUEMOTION2RT,
+ AV_CODEC_ID_M101,
+ AV_CODEC_ID_MAGICYUV,
+ AV_CODEC_ID_SHEERVIDEO,
+ AV_CODEC_ID_YLC,
+ AV_CODEC_ID_PSD,
+ AV_CODEC_ID_PIXLET,
+ AV_CODEC_ID_SPEEDHQ,
+ AV_CODEC_ID_FMVC,
+ AV_CODEC_ID_SCPR,
+ AV_CODEC_ID_CLEARVIDEO,
+ AV_CODEC_ID_XPM,
+ AV_CODEC_ID_AV1,
+ AV_CODEC_ID_BITPACKED,
+ AV_CODEC_ID_MSCC,
+ AV_CODEC_ID_SRGC,
+ AV_CODEC_ID_SVG,
+ AV_CODEC_ID_GDV,
+ AV_CODEC_ID_FITS,
+
+ /* various PCM "codecs" */
+ AV_CODEC_ID_FIRST_AUDIO = 0x10000, ///< A dummy id pointing at the start of audio codecs
+ AV_CODEC_ID_PCM_S16LE = 0x10000,
+ AV_CODEC_ID_PCM_S16BE,
+ AV_CODEC_ID_PCM_U16LE,
+ AV_CODEC_ID_PCM_U16BE,
+ AV_CODEC_ID_PCM_S8,
+ AV_CODEC_ID_PCM_U8,
+ AV_CODEC_ID_PCM_MULAW,
+ AV_CODEC_ID_PCM_ALAW,
+ AV_CODEC_ID_PCM_S32LE,
+ AV_CODEC_ID_PCM_S32BE,
+ AV_CODEC_ID_PCM_U32LE,
+ AV_CODEC_ID_PCM_U32BE,
+ AV_CODEC_ID_PCM_S24LE,
+ AV_CODEC_ID_PCM_S24BE,
+ AV_CODEC_ID_PCM_U24LE,
+ AV_CODEC_ID_PCM_U24BE,
+ AV_CODEC_ID_PCM_S24DAUD,
+ AV_CODEC_ID_PCM_ZORK,
+ AV_CODEC_ID_PCM_S16LE_PLANAR,
+ AV_CODEC_ID_PCM_DVD,
+ AV_CODEC_ID_PCM_F32BE,
+ AV_CODEC_ID_PCM_F32LE,
+ AV_CODEC_ID_PCM_F64BE,
+ AV_CODEC_ID_PCM_F64LE,
+ AV_CODEC_ID_PCM_BLURAY,
+ AV_CODEC_ID_PCM_LXF,
+ AV_CODEC_ID_S302M,
+ AV_CODEC_ID_PCM_S8_PLANAR,
+ AV_CODEC_ID_PCM_S24LE_PLANAR,
+ AV_CODEC_ID_PCM_S32LE_PLANAR,
+ AV_CODEC_ID_PCM_S16BE_PLANAR,
+
+ AV_CODEC_ID_PCM_S64LE = 0x10800,
+ AV_CODEC_ID_PCM_S64BE,
+ AV_CODEC_ID_PCM_F16LE,
+ AV_CODEC_ID_PCM_F24LE,
+
+ /* various ADPCM codecs */
+ AV_CODEC_ID_ADPCM_IMA_QT = 0x11000,
+ AV_CODEC_ID_ADPCM_IMA_WAV,
+ AV_CODEC_ID_ADPCM_IMA_DK3,
+ AV_CODEC_ID_ADPCM_IMA_DK4,
+ AV_CODEC_ID_ADPCM_IMA_WS,
+ AV_CODEC_ID_ADPCM_IMA_SMJPEG,
+ AV_CODEC_ID_ADPCM_MS,
+ AV_CODEC_ID_ADPCM_4XM,
+ AV_CODEC_ID_ADPCM_XA,
+ AV_CODEC_ID_ADPCM_ADX,
+ AV_CODEC_ID_ADPCM_EA,
+ AV_CODEC_ID_ADPCM_G726,
+ AV_CODEC_ID_ADPCM_CT,
+ AV_CODEC_ID_ADPCM_SWF,
+ AV_CODEC_ID_ADPCM_YAMAHA,
+ AV_CODEC_ID_ADPCM_SBPRO_4,
+ AV_CODEC_ID_ADPCM_SBPRO_3,
+ AV_CODEC_ID_ADPCM_SBPRO_2,
+ AV_CODEC_ID_ADPCM_THP,
+ AV_CODEC_ID_ADPCM_IMA_AMV,
+ AV_CODEC_ID_ADPCM_EA_R1,
+ AV_CODEC_ID_ADPCM_EA_R3,
+ AV_CODEC_ID_ADPCM_EA_R2,
+ AV_CODEC_ID_ADPCM_IMA_EA_SEAD,
+ AV_CODEC_ID_ADPCM_IMA_EA_EACS,
+ AV_CODEC_ID_ADPCM_EA_XAS,
+ AV_CODEC_ID_ADPCM_EA_MAXIS_XA,
+ AV_CODEC_ID_ADPCM_IMA_ISS,
+ AV_CODEC_ID_ADPCM_G722,
+ AV_CODEC_ID_ADPCM_IMA_APC,
+ AV_CODEC_ID_ADPCM_VIMA,
+
+ AV_CODEC_ID_ADPCM_AFC = 0x11800,
+ AV_CODEC_ID_ADPCM_IMA_OKI,
+ AV_CODEC_ID_ADPCM_DTK,
+ AV_CODEC_ID_ADPCM_IMA_RAD,
+ AV_CODEC_ID_ADPCM_G726LE,
+ AV_CODEC_ID_ADPCM_THP_LE,
+ AV_CODEC_ID_ADPCM_PSX,
+ AV_CODEC_ID_ADPCM_AICA,
+ AV_CODEC_ID_ADPCM_IMA_DAT4,
+ AV_CODEC_ID_ADPCM_MTAF,
+
+ /* AMR */
+ AV_CODEC_ID_AMR_NB = 0x12000,
+ AV_CODEC_ID_AMR_WB,
+
+ /* RealAudio codecs*/
+ AV_CODEC_ID_RA_144 = 0x13000,
+ AV_CODEC_ID_RA_288,
+
+ /* various DPCM codecs */
+ AV_CODEC_ID_ROQ_DPCM = 0x14000,
+ AV_CODEC_ID_INTERPLAY_DPCM,
+ AV_CODEC_ID_XAN_DPCM,
+ AV_CODEC_ID_SOL_DPCM,
+
+ AV_CODEC_ID_SDX2_DPCM = 0x14800,
+ AV_CODEC_ID_GREMLIN_DPCM,
+
+ /* audio codecs */
+ AV_CODEC_ID_MP2 = 0x15000,
+ AV_CODEC_ID_MP3, ///< preferred ID for decoding MPEG audio layer 1, 2 or 3
+ AV_CODEC_ID_AAC,
+ AV_CODEC_ID_AC3,
+ AV_CODEC_ID_DTS,
+ AV_CODEC_ID_VORBIS,
+ AV_CODEC_ID_DVAUDIO,
+ AV_CODEC_ID_WMAV1,
+ AV_CODEC_ID_WMAV2,
+ AV_CODEC_ID_MACE3,
+ AV_CODEC_ID_MACE6,
+ AV_CODEC_ID_VMDAUDIO,
+ AV_CODEC_ID_FLAC,
+ AV_CODEC_ID_MP3ADU,
+ AV_CODEC_ID_MP3ON4,
+ AV_CODEC_ID_SHORTEN,
+ AV_CODEC_ID_ALAC,
+ AV_CODEC_ID_WESTWOOD_SND1,
+ AV_CODEC_ID_GSM, ///< as in Berlin toast format
+ AV_CODEC_ID_QDM2,
+ AV_CODEC_ID_COOK,
+ AV_CODEC_ID_TRUESPEECH,
+ AV_CODEC_ID_TTA,
+ AV_CODEC_ID_SMACKAUDIO,
+ AV_CODEC_ID_QCELP,
+ AV_CODEC_ID_WAVPACK,
+ AV_CODEC_ID_DSICINAUDIO,
+ AV_CODEC_ID_IMC,
+ AV_CODEC_ID_MUSEPACK7,
+ AV_CODEC_ID_MLP,
+ AV_CODEC_ID_GSM_MS, /* as found in WAV */
+ AV_CODEC_ID_ATRAC3,
+ AV_CODEC_ID_APE,
+ AV_CODEC_ID_NELLYMOSER,
+ AV_CODEC_ID_MUSEPACK8,
+ AV_CODEC_ID_SPEEX,
+ AV_CODEC_ID_WMAVOICE,
+ AV_CODEC_ID_WMAPRO,
+ AV_CODEC_ID_WMALOSSLESS,
+ AV_CODEC_ID_ATRAC3P,
+ AV_CODEC_ID_EAC3,
+ AV_CODEC_ID_SIPR,
+ AV_CODEC_ID_MP1,
+ AV_CODEC_ID_TWINVQ,
+ AV_CODEC_ID_TRUEHD,
+ AV_CODEC_ID_MP4ALS,
+ AV_CODEC_ID_ATRAC1,
+ AV_CODEC_ID_BINKAUDIO_RDFT,
+ AV_CODEC_ID_BINKAUDIO_DCT,
+ AV_CODEC_ID_AAC_LATM,
+ AV_CODEC_ID_QDMC,
+ AV_CODEC_ID_CELT,
+ AV_CODEC_ID_G723_1,
+ AV_CODEC_ID_G729,
+ AV_CODEC_ID_8SVX_EXP,
+ AV_CODEC_ID_8SVX_FIB,
+ AV_CODEC_ID_BMV_AUDIO,
+ AV_CODEC_ID_RALF,
+ AV_CODEC_ID_IAC,
+ AV_CODEC_ID_ILBC,
+ AV_CODEC_ID_OPUS,
+ AV_CODEC_ID_COMFORT_NOISE,
+ AV_CODEC_ID_TAK,
+ AV_CODEC_ID_METASOUND,
+ AV_CODEC_ID_PAF_AUDIO,
+ AV_CODEC_ID_ON2AVC,
+ AV_CODEC_ID_DSS_SP,
+ AV_CODEC_ID_CODEC2,
+
+ AV_CODEC_ID_FFWAVESYNTH = 0x15800,
+ AV_CODEC_ID_SONIC,
+ AV_CODEC_ID_SONIC_LS,
+ AV_CODEC_ID_EVRC,
+ AV_CODEC_ID_SMV,
+ AV_CODEC_ID_DSD_LSBF,
+ AV_CODEC_ID_DSD_MSBF,
+ AV_CODEC_ID_DSD_LSBF_PLANAR,
+ AV_CODEC_ID_DSD_MSBF_PLANAR,
+ AV_CODEC_ID_4GV,
+ AV_CODEC_ID_INTERPLAY_ACM,
+ AV_CODEC_ID_XMA1,
+ AV_CODEC_ID_XMA2,
+ AV_CODEC_ID_DST,
+ AV_CODEC_ID_ATRAC3AL,
+ AV_CODEC_ID_ATRAC3PAL,
+ AV_CODEC_ID_DOLBY_E,
+ AV_CODEC_ID_APTX,
+ AV_CODEC_ID_APTX_HD,
+ AV_CODEC_ID_SBC,
+
+ /* subtitle codecs */
+ AV_CODEC_ID_FIRST_SUBTITLE = 0x17000, ///< A dummy ID pointing at the start of subtitle codecs.
+ AV_CODEC_ID_DVD_SUBTITLE = 0x17000,
+ AV_CODEC_ID_DVB_SUBTITLE,
+ AV_CODEC_ID_TEXT, ///< raw UTF-8 text
+ AV_CODEC_ID_XSUB,
+ AV_CODEC_ID_SSA,
+ AV_CODEC_ID_MOV_TEXT,
+ AV_CODEC_ID_HDMV_PGS_SUBTITLE,
+ AV_CODEC_ID_DVB_TELETEXT,
+ AV_CODEC_ID_SRT,
+
+ AV_CODEC_ID_MICRODVD = 0x17800,
+ AV_CODEC_ID_EIA_608,
+ AV_CODEC_ID_JACOSUB,
+ AV_CODEC_ID_SAMI,
+ AV_CODEC_ID_REALTEXT,
+ AV_CODEC_ID_STL,
+ AV_CODEC_ID_SUBVIEWER1,
+ AV_CODEC_ID_SUBVIEWER,
+ AV_CODEC_ID_SUBRIP,
+ AV_CODEC_ID_WEBVTT,
+ AV_CODEC_ID_MPL2,
+ AV_CODEC_ID_VPLAYER,
+ AV_CODEC_ID_PJS,
+ AV_CODEC_ID_ASS,
+ AV_CODEC_ID_HDMV_TEXT_SUBTITLE,
+
+ /* other specific kind of codecs (generally used for attachments) */
+ AV_CODEC_ID_FIRST_UNKNOWN = 0x18000, ///< A dummy ID pointing at the start of various fake codecs.
+ AV_CODEC_ID_TTF = 0x18000,
+
+ AV_CODEC_ID_SCTE_35, ///< Contain timestamp estimated through PCR of program stream.
+ AV_CODEC_ID_BINTEXT = 0x18800,
+ AV_CODEC_ID_XBIN,
+ AV_CODEC_ID_IDF,
+ AV_CODEC_ID_OTF,
+ AV_CODEC_ID_SMPTE_KLV,
+ AV_CODEC_ID_DVD_NAV,
+ AV_CODEC_ID_TIMED_ID3,
+ AV_CODEC_ID_BIN_DATA,
+
+
+ AV_CODEC_ID_PROBE = 0x19000, ///< codec_id is not known (like AV_CODEC_ID_NONE) but lavf should attempt to identify it
+
+ AV_CODEC_ID_MPEG2TS = 0x20000, /**< _FAKE_ codec to indicate a raw MPEG-2 TS
+ * stream (only used by libavformat) */
+ AV_CODEC_ID_MPEG4SYSTEMS = 0x20001, /**< _FAKE_ codec to indicate a MPEG-4 Systems
+ * stream (only used by libavformat) */
+ AV_CODEC_ID_FFMETADATA = 0x21000, ///< Dummy codec for streams containing only metadata information.
+ AV_CODEC_ID_WRAPPED_AVFRAME = 0x21001, ///< Passthrough codec, AVFrames wrapped in AVPacket
+};
+
+/**
+ * This struct describes the properties of a single codec described by an
+ * AVCodecID.
+ * @see avcodec_descriptor_get()
+ */
+typedef struct AVCodecDescriptor {
+ enum AVCodecID id;
+ enum AVMediaType type;
+ /**
+ * Name of the codec described by this descriptor. It is non-empty and
+ * unique for each codec descriptor. It should contain alphanumeric
+ * characters and '_' only.
+ */
+ const char *name;
+ /**
+ * A more descriptive name for this codec. May be NULL.
+ */
+ const char *long_name;
+ /**
+ * Codec properties, a combination of AV_CODEC_PROP_* flags.
+ */
+ int props;
+ /**
+ * MIME type(s) associated with the codec.
+ * May be NULL; if not, a NULL-terminated array of MIME types.
+ * The first item is always non-NULL and is the preferred MIME type.
+ */
+ const char *const *mime_types;
+ /**
+ * If non-NULL, an array of profiles recognized for this codec.
+ * Terminated with FF_PROFILE_UNKNOWN.
+ */
+ const struct AVProfile *profiles;
+} AVCodecDescriptor;
+
+/**
+ * Codec uses only intra compression.
+ * Video and audio codecs only.
+ */
+#define AV_CODEC_PROP_INTRA_ONLY (1 << 0)
+/**
+ * Codec supports lossy compression. Audio and video codecs only.
+ * @note a codec may support both lossy and lossless
+ * compression modes
+ */
+#define AV_CODEC_PROP_LOSSY (1 << 1)
+/**
+ * Codec supports lossless compression. Audio and video codecs only.
+ */
+#define AV_CODEC_PROP_LOSSLESS (1 << 2)
+/**
+ * Codec supports frame reordering. That is, the coded order (the order in which
+ * the encoded packets are output by the encoders / stored / input to the
+ * decoders) may be different from the presentation order of the corresponding
+ * frames.
+ *
+ * For codecs that do not have this property set, PTS and DTS should always be
+ * equal.
+ */
+#define AV_CODEC_PROP_REORDER (1 << 3)
+/**
+ * Subtitle codec is bitmap based
+ * Decoded AVSubtitle data can be read from the AVSubtitleRect->pict field.
+ */
+#define AV_CODEC_PROP_BITMAP_SUB (1 << 16)
+/**
+ * Subtitle codec is text based.
+ * Decoded AVSubtitle data can be read from the AVSubtitleRect->ass field.
+ */
+#define AV_CODEC_PROP_TEXT_SUB (1 << 17)
+
+/**
+ * @ingroup lavc_decoding
+ * Required number of additionally allocated bytes at the end of the input bitstream for decoding.
+ * This is mainly needed because some optimized bitstream readers read
+ * 32 or 64 bit at once and could read over the end.<br>
+ * Note: If the first 23 bits of the additional bytes are not 0, then damaged
+ * MPEG bitstreams could cause overread and segfault.
+ */
+#define AV_INPUT_BUFFER_PADDING_SIZE 64
+
+/**
+ * @ingroup lavc_encoding
+ * minimum encoding buffer size
+ * Used to avoid some checks during header writing.
+ */
+#define AV_INPUT_BUFFER_MIN_SIZE 16384
+
+/**
+ * @ingroup lavc_decoding
+ */
+enum AVDiscard{
+ /* We leave some space between them for extensions (drop some
+ * keyframes for intra-only or drop just some bidir frames). */
+ AVDISCARD_NONE =-16, ///< discard nothing
+ AVDISCARD_DEFAULT = 0, ///< discard useless packets like 0 size packets in avi
+ AVDISCARD_NONREF = 8, ///< discard all non reference
+ AVDISCARD_BIDIR = 16, ///< discard all bidirectional frames
+ AVDISCARD_NONINTRA= 24, ///< discard all non intra frames
+ AVDISCARD_NONKEY = 32, ///< discard all frames except keyframes
+ AVDISCARD_ALL = 48, ///< discard all
+};
+
+enum AVAudioServiceType {
+ AV_AUDIO_SERVICE_TYPE_MAIN = 0,
+ AV_AUDIO_SERVICE_TYPE_EFFECTS = 1,
+ AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED = 2,
+ AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED = 3,
+ AV_AUDIO_SERVICE_TYPE_DIALOGUE = 4,
+ AV_AUDIO_SERVICE_TYPE_COMMENTARY = 5,
+ AV_AUDIO_SERVICE_TYPE_EMERGENCY = 6,
+ AV_AUDIO_SERVICE_TYPE_VOICE_OVER = 7,
+ AV_AUDIO_SERVICE_TYPE_KARAOKE = 8,
+ AV_AUDIO_SERVICE_TYPE_NB , ///< Not part of ABI
+};
+
+/**
+ * @ingroup lavc_encoding
+ */
+typedef struct RcOverride{
+ int start_frame;
+ int end_frame;
+ int qscale; // If this is 0 then quality_factor will be used instead.
+ float quality_factor;
+} RcOverride;
+
+/* encoding support
+ These flags can be passed in AVCodecContext.flags before initialization.
+ Note: Not everything is supported yet.
+*/
+
+/**
+ * Allow decoders to produce frames with data planes that are not aligned
+ * to CPU requirements (e.g. due to cropping).
+ */
+#define AV_CODEC_FLAG_UNALIGNED (1 << 0)
+/**
+ * Use fixed qscale.
+ */
+#define AV_CODEC_FLAG_QSCALE (1 << 1)
+/**
+ * 4 MV per MB allowed / advanced prediction for H.263.
+ */
+#define AV_CODEC_FLAG_4MV (1 << 2)
+/**
+ * Output even those frames that might be corrupted.
+ */
+#define AV_CODEC_FLAG_OUTPUT_CORRUPT (1 << 3)
+/**
+ * Use qpel MC.
+ */
+#define AV_CODEC_FLAG_QPEL (1 << 4)
+/**
+ * Use internal 2pass ratecontrol in first pass mode.
+ */
+#define AV_CODEC_FLAG_PASS1 (1 << 9)
+/**
+ * Use internal 2pass ratecontrol in second pass mode.
+ */
+#define AV_CODEC_FLAG_PASS2 (1 << 10)
+/**
+ * loop filter.
+ */
+#define AV_CODEC_FLAG_LOOP_FILTER (1 << 11)
+/**
+ * Only decode/encode grayscale.
+ */
+#define AV_CODEC_FLAG_GRAY (1 << 13)
+/**
+ * error[?] variables will be set during encoding.
+ */
+#define AV_CODEC_FLAG_PSNR (1 << 15)
+/**
+ * Input bitstream might be truncated at a random location
+ * instead of only at frame boundaries.
+ */
+#define AV_CODEC_FLAG_TRUNCATED (1 << 16)
+/**
+ * Use interlaced DCT.
+ */
+#define AV_CODEC_FLAG_INTERLACED_DCT (1 << 18)
+/**
+ * Force low delay.
+ */
+#define AV_CODEC_FLAG_LOW_DELAY (1 << 19)
+/**
+ * Place global headers in extradata instead of every keyframe.
+ */
+#define AV_CODEC_FLAG_GLOBAL_HEADER (1 << 22)
+/**
+ * Use only bitexact stuff (except (I)DCT).
+ */
+#define AV_CODEC_FLAG_BITEXACT (1 << 23)
+/* Fx : Flag for H.263+ extra options */
+/**
+ * H.263 advanced intra coding / MPEG-4 AC prediction
+ */
+#define AV_CODEC_FLAG_AC_PRED (1 << 24)
+/**
+ * interlaced motion estimation
+ */
+#define AV_CODEC_FLAG_INTERLACED_ME (1 << 29)
+#define AV_CODEC_FLAG_CLOSED_GOP (1U << 31)
+
+/**
+ * Allow non spec compliant speedup tricks.
+ */
+#define AV_CODEC_FLAG2_FAST (1 << 0)
+/**
+ * Skip bitstream encoding.
+ */
+#define AV_CODEC_FLAG2_NO_OUTPUT (1 << 2)
+/**
+ * Place global headers at every keyframe instead of in extradata.
+ */
+#define AV_CODEC_FLAG2_LOCAL_HEADER (1 << 3)
+
+/**
+ * timecode is in drop frame format. DEPRECATED!!!!
+ */
+#define AV_CODEC_FLAG2_DROP_FRAME_TIMECODE (1 << 13)
+
+/**
+ * Input bitstream might be truncated at a packet boundaries
+ * instead of only at frame boundaries.
+ */
+#define AV_CODEC_FLAG2_CHUNKS (1 << 15)
+/**
+ * Discard cropping information from SPS.
+ */
+#define AV_CODEC_FLAG2_IGNORE_CROP (1 << 16)
+
+/**
+ * Show all frames before the first keyframe
+ */
+#define AV_CODEC_FLAG2_SHOW_ALL (1 << 22)
+/**
+ * Export motion vectors through frame side data
+ */
+#define AV_CODEC_FLAG2_EXPORT_MVS (1 << 28)
+/**
+ * Do not skip samples and export skip information as frame side data
+ */
+#define AV_CODEC_FLAG2_SKIP_MANUAL (1 << 29)
+/**
+ * Do not reset ASS ReadOrder field on flush (subtitles decoding)
+ */
+#define AV_CODEC_FLAG2_RO_FLUSH_NOOP (1 << 30)
+
+/* Unsupported options :
+ * Syntax Arithmetic coding (SAC)
+ * Reference Picture Selection
+ * Independent Segment Decoding */
+/* /Fx */
+/* codec capabilities */
+
+/**
+ * Decoder can use draw_horiz_band callback.
+ */
+#define AV_CODEC_CAP_DRAW_HORIZ_BAND (1 << 0)
+/**
+ * Codec uses get_buffer() for allocating buffers and supports custom allocators.
+ * If not set, it might not use get_buffer() at all or use operations that
+ * assume the buffer was allocated by avcodec_default_get_buffer.
+ */
+#define AV_CODEC_CAP_DR1 (1 << 1)
+#define AV_CODEC_CAP_TRUNCATED (1 << 3)
+/**
+ * Encoder or decoder requires flushing with NULL input at the end in order to
+ * give the complete and correct output.
+ *
+ * NOTE: If this flag is not set, the codec is guaranteed to never be fed with
+ * with NULL data. The user can still send NULL data to the public encode
+ * or decode function, but libavcodec will not pass it along to the codec
+ * unless this flag is set.
+ *
+ * Decoders:
+ * The decoder has a non-zero delay and needs to be fed with avpkt->data=NULL,
+ * avpkt->size=0 at the end to get the delayed data until the decoder no longer
+ * returns frames.
+ *
+ * Encoders:
+ * The encoder needs to be fed with NULL data at the end of encoding until the
+ * encoder no longer returns data.
+ *
+ * NOTE: For encoders implementing the AVCodec.encode2() function, setting this
+ * flag also means that the encoder must set the pts and duration for
+ * each output packet. If this flag is not set, the pts and duration will
+ * be determined by libavcodec from the input frame.
+ */
+#define AV_CODEC_CAP_DELAY (1 << 5)
+/**
+ * Codec can be fed a final frame with a smaller size.
+ * This can be used to prevent truncation of the last audio samples.
+ */
+#define AV_CODEC_CAP_SMALL_LAST_FRAME (1 << 6)
+
+/**
+ * Codec can output multiple frames per AVPacket
+ * Normally demuxers return one frame at a time, demuxers which do not do
+ * are connected to a parser to split what they return into proper frames.
+ * This flag is reserved to the very rare category of codecs which have a
+ * bitstream that cannot be split into frames without timeconsuming
+ * operations like full decoding. Demuxers carrying such bitstreams thus
+ * may return multiple frames in a packet. This has many disadvantages like
+ * prohibiting stream copy in many cases thus it should only be considered
+ * as a last resort.
+ */
+#define AV_CODEC_CAP_SUBFRAMES (1 << 8)
+/**
+ * Codec is experimental and is thus avoided in favor of non experimental
+ * encoders
+ */
+#define AV_CODEC_CAP_EXPERIMENTAL (1 << 9)
+/**
+ * Codec should fill in channel configuration and samplerate instead of container
+ */
+#define AV_CODEC_CAP_CHANNEL_CONF (1 << 10)
+/**
+ * Codec supports frame-level multithreading.
+ */
+#define AV_CODEC_CAP_FRAME_THREADS (1 << 12)
+/**
+ * Codec supports slice-based (or partition-based) multithreading.
+ */
+#define AV_CODEC_CAP_SLICE_THREADS (1 << 13)
+/**
+ * Codec supports changed parameters at any point.
+ */
+#define AV_CODEC_CAP_PARAM_CHANGE (1 << 14)
+/**
+ * Codec supports avctx->thread_count == 0 (auto).
+ */
+#define AV_CODEC_CAP_AUTO_THREADS (1 << 15)
+/**
+ * Audio encoder supports receiving a different number of samples in each call.
+ */
+#define AV_CODEC_CAP_VARIABLE_FRAME_SIZE (1 << 16)
+/**
+ * Decoder is not a preferred choice for probing.
+ * This indicates that the decoder is not a good choice for probing.
+ * It could for example be an expensive to spin up hardware decoder,
+ * or it could simply not provide a lot of useful information about
+ * the stream.
+ * A decoder marked with this flag should only be used as last resort
+ * choice for probing.
+ */
+#define AV_CODEC_CAP_AVOID_PROBING (1 << 17)
+/**
+ * Codec is intra only.
+ */
+#define AV_CODEC_CAP_INTRA_ONLY 0x40000000
+/**
+ * Codec is lossless.
+ */
+#define AV_CODEC_CAP_LOSSLESS 0x80000000
+
+/**
+ * Codec is backed by a hardware implementation. Typically used to
+ * identify a non-hwaccel hardware decoder. For information about hwaccels, use
+ * avcodec_get_hw_config() instead.
+ */
+#define AV_CODEC_CAP_HARDWARE (1 << 18)
+
+/**
+ * Codec is potentially backed by a hardware implementation, but not
+ * necessarily. This is used instead of AV_CODEC_CAP_HARDWARE, if the
+ * implementation provides some sort of internal fallback.
+ */
+#define AV_CODEC_CAP_HYBRID (1 << 19)
+
+/**
+ * Pan Scan area.
+ * This specifies the area which should be displayed.
+ * Note there may be multiple such areas for one frame.
+ */
+typedef struct AVPanScan {
+ /**
+ * id
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ int id;
+
+ /**
+ * width and height in 1/16 pel
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ int width;
+ int height;
+
+ /**
+ * position of the top left corner in 1/16 pel for up to 3 fields/frames
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ int16_t position[3][2];
+} AVPanScan;
+
+/**
+ * This structure describes the bitrate properties of an encoded bitstream. It
+ * roughly corresponds to a subset the VBV parameters for MPEG-2 or HRD
+ * parameters for H.264/HEVC.
+ */
+typedef struct AVCPBProperties {
+ /**
+ * Maximum bitrate of the stream, in bits per second.
+ * Zero if unknown or unspecified.
+ */
+ int max_bitrate;
+ /**
+ * Minimum bitrate of the stream, in bits per second.
+ * Zero if unknown or unspecified.
+ */
+ int min_bitrate;
+ /**
+ * Average bitrate of the stream, in bits per second.
+ * Zero if unknown or unspecified.
+ */
+ int avg_bitrate;
+
+ /**
+ * The size of the buffer to which the ratecontrol is applied, in bits.
+ * Zero if unknown or unspecified.
+ */
+ int buffer_size;
+
+ /**
+ * The delay between the time the packet this structure is associated with
+ * is received and the time when it should be decoded, in periods of a 27MHz
+ * clock.
+ *
+ * UINT64_MAX when unknown or unspecified.
+ */
+ uint64_t vbv_delay;
+} AVCPBProperties;
+
+/**
+ * The decoder will keep a reference to the frame and may reuse it later.
+ */
+#define AV_GET_BUFFER_FLAG_REF (1 << 0)
+
+/**
+ * @defgroup lavc_packet AVPacket
+ *
+ * Types and functions for working with AVPacket.
+ * @{
+ */
+enum AVPacketSideDataType {
+ /**
+ * An AV_PKT_DATA_PALETTE side data packet contains exactly AVPALETTE_SIZE
+ * bytes worth of palette. This side data signals that a new palette is
+ * present.
+ */
+ AV_PKT_DATA_PALETTE,
+
+ /**
+ * The AV_PKT_DATA_NEW_EXTRADATA is used to notify the codec or the format
+ * that the extradata buffer was changed and the receiving side should
+ * act upon it appropriately. The new extradata is embedded in the side
+ * data buffer and should be immediately used for processing the current
+ * frame or packet.
+ */
+ AV_PKT_DATA_NEW_EXTRADATA,
+
+ /**
+ * An AV_PKT_DATA_PARAM_CHANGE side data packet is laid out as follows:
+ * @code
+ * u32le param_flags
+ * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT)
+ * s32le channel_count
+ * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT)
+ * u64le channel_layout
+ * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE)
+ * s32le sample_rate
+ * if (param_flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS)
+ * s32le width
+ * s32le height
+ * @endcode
+ */
+ AV_PKT_DATA_PARAM_CHANGE,
+
+ /**
+ * An AV_PKT_DATA_H263_MB_INFO side data packet contains a number of
+ * structures with info about macroblocks relevant to splitting the
+ * packet into smaller packets on macroblock edges (e.g. as for RFC 2190).
+ * That is, it does not necessarily contain info about all macroblocks,
+ * as long as the distance between macroblocks in the info is smaller
+ * than the target payload size.
+ * Each MB info structure is 12 bytes, and is laid out as follows:
+ * @code
+ * u32le bit offset from the start of the packet
+ * u8 current quantizer at the start of the macroblock
+ * u8 GOB number
+ * u16le macroblock address within the GOB
+ * u8 horizontal MV predictor
+ * u8 vertical MV predictor
+ * u8 horizontal MV predictor for block number 3
+ * u8 vertical MV predictor for block number 3
+ * @endcode
+ */
+ AV_PKT_DATA_H263_MB_INFO,
+
+ /**
+ * This side data should be associated with an audio stream and contains
+ * ReplayGain information in form of the AVReplayGain struct.
+ */
+ AV_PKT_DATA_REPLAYGAIN,
+
+ /**
+ * This side data contains a 3x3 transformation matrix describing an affine
+ * transformation that needs to be applied to the decoded video frames for
+ * correct presentation.
+ *
+ * See libavutil/display.h for a detailed description of the data.
+ */
+ AV_PKT_DATA_DISPLAYMATRIX,
+
+ /**
+ * This side data should be associated with a video stream and contains
+ * Stereoscopic 3D information in form of the AVStereo3D struct.
+ */
+ AV_PKT_DATA_STEREO3D,
+
+ /**
+ * This side data should be associated with an audio stream and corresponds
+ * to enum AVAudioServiceType.
+ */
+ AV_PKT_DATA_AUDIO_SERVICE_TYPE,
+
+ /**
+ * This side data contains quality related information from the encoder.
+ * @code
+ * u32le quality factor of the compressed frame. Allowed range is between 1 (good) and FF_LAMBDA_MAX (bad).
+ * u8 picture type
+ * u8 error count
+ * u16 reserved
+ * u64le[error count] sum of squared differences between encoder in and output
+ * @endcode
+ */
+ AV_PKT_DATA_QUALITY_STATS,
+
+ /**
+ * This side data contains an integer value representing the stream index
+ * of a "fallback" track. A fallback track indicates an alternate
+ * track to use when the current track can not be decoded for some reason.
+ * e.g. no decoder available for codec.
+ */
+ AV_PKT_DATA_FALLBACK_TRACK,
+
+ /**
+ * This side data corresponds to the AVCPBProperties struct.
+ */
+ AV_PKT_DATA_CPB_PROPERTIES,
+
+ /**
+ * Recommmends skipping the specified number of samples
+ * @code
+ * u32le number of samples to skip from start of this packet
+ * u32le number of samples to skip from end of this packet
+ * u8 reason for start skip
+ * u8 reason for end skip (0=padding silence, 1=convergence)
+ * @endcode
+ */
+ AV_PKT_DATA_SKIP_SAMPLES,
+
+ /**
+ * An AV_PKT_DATA_JP_DUALMONO side data packet indicates that
+ * the packet may contain "dual mono" audio specific to Japanese DTV
+ * and if it is true, recommends only the selected channel to be used.
+ * @code
+ * u8 selected channels (0=mail/left, 1=sub/right, 2=both)
+ * @endcode
+ */
+ AV_PKT_DATA_JP_DUALMONO,
+
+ /**
+ * A list of zero terminated key/value strings. There is no end marker for
+ * the list, so it is required to rely on the side data size to stop.
+ */
+ AV_PKT_DATA_STRINGS_METADATA,
+
+ /**
+ * Subtitle event position
+ * @code
+ * u32le x1
+ * u32le y1
+ * u32le x2
+ * u32le y2
+ * @endcode
+ */
+ AV_PKT_DATA_SUBTITLE_POSITION,
+
+ /**
+ * Data found in BlockAdditional element of matroska container. There is
+ * no end marker for the data, so it is required to rely on the side data
+ * size to recognize the end. 8 byte id (as found in BlockAddId) followed
+ * by data.
+ */
+ AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
+
+ /**
+ * The optional first identifier line of a WebVTT cue.
+ */
+ AV_PKT_DATA_WEBVTT_IDENTIFIER,
+
+ /**
+ * The optional settings (rendering instructions) that immediately
+ * follow the timestamp specifier of a WebVTT cue.
+ */
+ AV_PKT_DATA_WEBVTT_SETTINGS,
+
+ /**
+ * A list of zero terminated key/value strings. There is no end marker for
+ * the list, so it is required to rely on the side data size to stop. This
+ * side data includes updated metadata which appeared in the stream.
+ */
+ AV_PKT_DATA_METADATA_UPDATE,
+
+ /**
+ * MPEGTS stream ID, this is required to pass the stream ID
+ * information from the demuxer to the corresponding muxer.
+ */
+ AV_PKT_DATA_MPEGTS_STREAM_ID,
+
+ /**
+ * Mastering display metadata (based on SMPTE-2086:2014). This metadata
+ * should be associated with a video stream and contains data in the form
+ * of the AVMasteringDisplayMetadata struct.
+ */
+ AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
+
+ /**
+ * This side data should be associated with a video stream and corresponds
+ * to the AVSphericalMapping structure.
+ */
+ AV_PKT_DATA_SPHERICAL,
+
+ /**
+ * Content light level (based on CTA-861.3). This metadata should be
+ * associated with a video stream and contains data in the form of the
+ * AVContentLightMetadata struct.
+ */
+ AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
+
+ /**
+ * ATSC A53 Part 4 Closed Captions. This metadata should be associated with
+ * a video stream. A53 CC bitstream is stored as uint8_t in AVPacketSideData.data.
+ * The number of bytes of CC data is AVPacketSideData.size.
+ */
+ AV_PKT_DATA_A53_CC,
+
+ /**
+ * This side data is encryption initialization data.
+ * The format is not part of ABI, use av_encryption_init_info_* methods to
+ * access.
+ */
+ AV_PKT_DATA_ENCRYPTION_INIT_INFO,
+
+ /**
+ * This side data contains encryption info for how to decrypt the packet.
+ * The format is not part of ABI, use av_encryption_info_* methods to access.
+ */
+ AV_PKT_DATA_ENCRYPTION_INFO,
+
+ /**
+ * The number of side data types.
+ * This is not part of the public API/ABI in the sense that it may
+ * change when new side data types are added.
+ * This must stay the last enum value.
+ * If its value becomes huge, some code using it
+ * needs to be updated as it assumes it to be smaller than other limits.
+ */
+ AV_PKT_DATA_NB
+};
+
+#define AV_PKT_DATA_QUALITY_FACTOR AV_PKT_DATA_QUALITY_STATS //DEPRECATED
+
+typedef struct AVPacketSideData {
+ uint8_t *data;
+ int size;
+ enum AVPacketSideDataType type;
+} AVPacketSideData;
+
+/**
+ * This structure stores compressed data. It is typically exported by demuxers
+ * and then passed as input to decoders, or received as output from encoders and
+ * then passed to muxers.
+ *
+ * For video, it should typically contain one compressed frame. For audio it may
+ * contain several compressed frames. Encoders are allowed to output empty
+ * packets, with no compressed data, containing only side data
+ * (e.g. to update some stream parameters at the end of encoding).
+ *
+ * AVPacket is one of the few structs in FFmpeg, whose size is a part of public
+ * ABI. Thus it may be allocated on stack and no new fields can be added to it
+ * without libavcodec and libavformat major bump.
+ *
+ * The semantics of data ownership depends on the buf field.
+ * If it is set, the packet data is dynamically allocated and is
+ * valid indefinitely until a call to av_packet_unref() reduces the
+ * reference count to 0.
+ *
+ * If the buf field is not set av_packet_ref() would make a copy instead
+ * of increasing the reference count.
+ *
+ * The side data is always allocated with av_malloc(), copied by
+ * av_packet_ref() and freed by av_packet_unref().
+ *
+ * @see av_packet_ref
+ * @see av_packet_unref
+ */
+typedef struct AVPacket {
+ /**
+ * A reference to the reference-counted buffer where the packet data is
+ * stored.
+ * May be NULL, then the packet data is not reference-counted.
+ */
+ AVBufferRef *buf;
+ /**
+ * Presentation timestamp in AVStream->time_base units; the time at which
+ * the decompressed packet will be presented to the user.
+ * Can be AV_NOPTS_VALUE if it is not stored in the file.
+ * pts MUST be larger or equal to dts as presentation cannot happen before
+ * decompression, unless one wants to view hex dumps. Some formats misuse
+ * the terms dts and pts/cts to mean something different. Such timestamps
+ * must be converted to true pts/dts before they are stored in AVPacket.
+ */
+ int64_t pts;
+ /**
+ * Decompression timestamp in AVStream->time_base units; the time at which
+ * the packet is decompressed.
+ * Can be AV_NOPTS_VALUE if it is not stored in the file.
+ */
+ int64_t dts;
+ uint8_t *data;
+ int size;
+ int stream_index;
+ /**
+ * A combination of AV_PKT_FLAG values
+ */
+ int flags;
+ /**
+ * Additional packet data that can be provided by the container.
+ * Packet can contain several types of side information.
+ */
+ AVPacketSideData *side_data;
+ int side_data_elems;
+
+ /**
+ * Duration of this packet in AVStream->time_base units, 0 if unknown.
+ * Equals next_pts - this_pts in presentation order.
+ */
+ int64_t duration;
+
+ int64_t pos; ///< byte position in stream, -1 if unknown
+
+#if FF_API_CONVERGENCE_DURATION
+ /**
+ * @deprecated Same as the duration field, but as int64_t. This was required
+ * for Matroska subtitles, whose duration values could overflow when the
+ * duration field was still an int.
+ */
+ attribute_deprecated
+ int64_t convergence_duration;
+#endif
+} AVPacket;
+#define AV_PKT_FLAG_KEY 0x0001 ///< The packet contains a keyframe
+#define AV_PKT_FLAG_CORRUPT 0x0002 ///< The packet content is corrupted
+/**
+ * Flag is used to discard packets which are required to maintain valid
+ * decoder state but are not required for output and should be dropped
+ * after decoding.
+ **/
+#define AV_PKT_FLAG_DISCARD 0x0004
+/**
+ * The packet comes from a trusted source.
+ *
+ * Otherwise-unsafe constructs such as arbitrary pointers to data
+ * outside the packet may be followed.
+ */
+#define AV_PKT_FLAG_TRUSTED 0x0008
+/**
+ * Flag is used to indicate packets that contain frames that can
+ * be discarded by the decoder. I.e. Non-reference frames.
+ */
+#define AV_PKT_FLAG_DISPOSABLE 0x0010
+
+
+enum AVSideDataParamChangeFlags {
+ AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT = 0x0001,
+ AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT = 0x0002,
+ AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE = 0x0004,
+ AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS = 0x0008,
+};
+/**
+ * @}
+ */
+
+struct AVCodecInternal;
+
+enum AVFieldOrder {
+ AV_FIELD_UNKNOWN,
+ AV_FIELD_PROGRESSIVE,
+ AV_FIELD_TT, //< Top coded_first, top displayed first
+ AV_FIELD_BB, //< Bottom coded first, bottom displayed first
+ AV_FIELD_TB, //< Top coded first, bottom displayed first
+ AV_FIELD_BT, //< Bottom coded first, top displayed first
+};
+
+/**
+ * main external API structure.
+ * New fields can be added to the end with minor version bumps.
+ * Removal, reordering and changes to existing fields require a major
+ * version bump.
+ * You can use AVOptions (av_opt* / av_set/get*()) to access these fields from user
+ * applications.
+ * The name string for AVOptions options matches the associated command line
+ * parameter name and can be found in libavcodec/options_table.h
+ * The AVOption/command line parameter names differ in some cases from the C
+ * structure field names for historic reasons or brevity.
+ * sizeof(AVCodecContext) must not be used outside libav*.
+ */
+typedef struct AVCodecContext {
+ /**
+ * information on struct for av_log
+ * - set by avcodec_alloc_context3
+ */
+ const AVClass *av_class;
+ int log_level_offset;
+
+ enum AVMediaType codec_type; /* see AVMEDIA_TYPE_xxx */
+ const struct AVCodec *codec;
+ enum AVCodecID codec_id; /* see AV_CODEC_ID_xxx */
+
+ /**
+ * fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
+ * This is used to work around some encoder bugs.
+ * A demuxer should set this to what is stored in the field used to identify the codec.
+ * If there are multiple such fields in a container then the demuxer should choose the one
+ * which maximizes the information about the used codec.
+ * If the codec tag field in a container is larger than 32 bits then the demuxer should
+ * remap the longer ID to 32 bits with a table or other structure. Alternatively a new
+ * extra_codec_tag + size could be added but for this a clear advantage must be demonstrated
+ * first.
+ * - encoding: Set by user, if not then the default based on codec_id will be used.
+ * - decoding: Set by user, will be converted to uppercase by libavcodec during init.
+ */
+ unsigned int codec_tag;
+
+ void *priv_data;
+
+ /**
+ * Private context used for internal data.
+ *
+ * Unlike priv_data, this is not codec-specific. It is used in general
+ * libavcodec functions.
+ */
+ struct AVCodecInternal *internal;
+
+ /**
+ * Private data of the user, can be used to carry app specific stuff.
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ void *opaque;
+
+ /**
+ * the average bitrate
+ * - encoding: Set by user; unused for constant quantizer encoding.
+ * - decoding: Set by user, may be overwritten by libavcodec
+ * if this info is available in the stream
+ */
+ int64_t bit_rate;
+
+ /**
+ * number of bits the bitstream is allowed to diverge from the reference.
+ * the reference can be CBR (for CBR pass1) or VBR (for pass2)
+ * - encoding: Set by user; unused for constant quantizer encoding.
+ * - decoding: unused
+ */
+ int bit_rate_tolerance;
+
+ /**
+ * Global quality for codecs which cannot change it per frame.
+ * This should be proportional to MPEG-1/2/4 qscale.
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int global_quality;
+
+ /**
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int compression_level;
+#define FF_COMPRESSION_DEFAULT -1
+
+ /**
+ * AV_CODEC_FLAG_*.
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ int flags;
+
+ /**
+ * AV_CODEC_FLAG2_*
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ int flags2;
+
+ /**
+ * some codecs need / can use extradata like Huffman tables.
+ * MJPEG: Huffman tables
+ * rv10: additional flags
+ * MPEG-4: global headers (they can be in the bitstream or here)
+ * The allocated memory should be AV_INPUT_BUFFER_PADDING_SIZE bytes larger
+ * than extradata_size to avoid problems if it is read with the bitstream reader.
+ * The bytewise contents of extradata must not depend on the architecture or CPU endianness.
+ * - encoding: Set/allocated/freed by libavcodec.
+ * - decoding: Set/allocated/freed by user.
+ */
+ uint8_t *extradata;
+ int extradata_size;
+
+ /**
+ * This is the fundamental unit of time (in seconds) in terms
+ * of which frame timestamps are represented. For fixed-fps content,
+ * timebase should be 1/framerate and timestamp increments should be
+ * identically 1.
+ * This often, but not always is the inverse of the frame rate or field rate
+ * for video. 1/time_base is not the average frame rate if the frame rate is not
+ * constant.
+ *
+ * Like containers, elementary streams also can store timestamps, 1/time_base
+ * is the unit in which these timestamps are specified.
+ * As example of such codec time base see ISO/IEC 14496-2:2001(E)
+ * vop_time_increment_resolution and fixed_vop_rate
+ * (fixed_vop_rate == 0 implies that it is different from the framerate)
+ *
+ * - encoding: MUST be set by user.
+ * - decoding: the use of this field for decoding is deprecated.
+ * Use framerate instead.
+ */
+ AVRational time_base;
+
+ /**
+ * For some codecs, the time base is closer to the field rate than the frame rate.
+ * Most notably, H.264 and MPEG-2 specify time_base as half of frame duration
+ * if no telecine is used ...
+ *
+ * Set to time_base ticks per frame. Default 1, e.g., H.264/MPEG-2 set it to 2.
+ */
+ int ticks_per_frame;
+
+ /**
+ * Codec delay.
+ *
+ * Encoding: Number of frames delay there will be from the encoder input to
+ * the decoder output. (we assume the decoder matches the spec)
+ * Decoding: Number of frames delay in addition to what a standard decoder
+ * as specified in the spec would produce.
+ *
+ * Video:
+ * Number of frames the decoded output will be delayed relative to the
+ * encoded input.
+ *
+ * Audio:
+ * For encoding, this field is unused (see initial_padding).
+ *
+ * For decoding, this is the number of samples the decoder needs to
+ * output before the decoder's output is valid. When seeking, you should
+ * start decoding this many samples prior to your desired seek point.
+ *
+ * - encoding: Set by libavcodec.
+ * - decoding: Set by libavcodec.
+ */
+ int delay;
+
+
+ /* video only */
+ /**
+ * picture width / height.
+ *
+ * @note Those fields may not match the values of the last
+ * AVFrame output by avcodec_decode_video2 due frame
+ * reordering.
+ *
+ * - encoding: MUST be set by user.
+ * - decoding: May be set by the user before opening the decoder if known e.g.
+ * from the container. Some decoders will require the dimensions
+ * to be set by the caller. During decoding, the decoder may
+ * overwrite those values as required while parsing the data.
+ */
+ int width, height;
+
+ /**
+ * Bitstream width / height, may be different from width/height e.g. when
+ * the decoded frame is cropped before being output or lowres is enabled.
+ *
+ * @note Those field may not match the value of the last
+ * AVFrame output by avcodec_receive_frame() due frame
+ * reordering.
+ *
+ * - encoding: unused
+ * - decoding: May be set by the user before opening the decoder if known
+ * e.g. from the container. During decoding, the decoder may
+ * overwrite those values as required while parsing the data.
+ */
+ int coded_width, coded_height;
+
+ /**
+ * the number of pictures in a group of pictures, or 0 for intra_only
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int gop_size;
+
+ /**
+ * Pixel format, see AV_PIX_FMT_xxx.
+ * May be set by the demuxer if known from headers.
+ * May be overridden by the decoder if it knows better.
+ *
+ * @note This field may not match the value of the last
+ * AVFrame output by avcodec_receive_frame() due frame
+ * reordering.
+ *
+ * - encoding: Set by user.
+ * - decoding: Set by user if known, overridden by libavcodec while
+ * parsing the data.
+ */
+ enum AVPixelFormat pix_fmt;
+
+ /**
+ * If non NULL, 'draw_horiz_band' is called by the libavcodec
+ * decoder to draw a horizontal band. It improves cache usage. Not
+ * all codecs can do that. You must check the codec capabilities
+ * beforehand.
+ * When multithreading is used, it may be called from multiple threads
+ * at the same time; threads might draw different parts of the same AVFrame,
+ * or multiple AVFrames, and there is no guarantee that slices will be drawn
+ * in order.
+ * The function is also used by hardware acceleration APIs.
+ * It is called at least once during frame decoding to pass
+ * the data needed for hardware render.
+ * In that mode instead of pixel data, AVFrame points to
+ * a structure specific to the acceleration API. The application
+ * reads the structure and can change some fields to indicate progress
+ * or mark state.
+ * - encoding: unused
+ * - decoding: Set by user.
+ * @param height the height of the slice
+ * @param y the y position of the slice
+ * @param type 1->top field, 2->bottom field, 3->frame
+ * @param offset offset into the AVFrame.data from which the slice should be read
+ */
+ void (*draw_horiz_band)(struct AVCodecContext *s,
+ const AVFrame *src, int offset[AV_NUM_DATA_POINTERS],
+ int y, int type, int height);
+
+ /**
+ * callback to negotiate the pixelFormat
+ * @param fmt is the list of formats which are supported by the codec,
+ * it is terminated by -1 as 0 is a valid format, the formats are ordered by quality.
+ * The first is always the native one.
+ * @note The callback may be called again immediately if initialization for
+ * the selected (hardware-accelerated) pixel format failed.
+ * @warning Behavior is undefined if the callback returns a value not
+ * in the fmt list of formats.
+ * @return the chosen format
+ * - encoding: unused
+ * - decoding: Set by user, if not set the native format will be chosen.
+ */
+ enum AVPixelFormat (*get_format)(struct AVCodecContext *s, const enum AVPixelFormat * fmt);
+
+ /**
+ * maximum number of B-frames between non-B-frames
+ * Note: The output will be delayed by max_b_frames+1 relative to the input.
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int max_b_frames;
+
+ /**
+ * qscale factor between IP and B-frames
+ * If > 0 then the last P-frame quantizer will be used (q= lastp_q*factor+offset).
+ * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset).
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float b_quant_factor;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int b_frame_strategy;
+#endif
+
+ /**
+ * qscale offset between IP and B-frames
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float b_quant_offset;
+
+ /**
+ * Size of the frame reordering buffer in the decoder.
+ * For MPEG-2 it is 1 IPB or 0 low delay IP.
+ * - encoding: Set by libavcodec.
+ * - decoding: Set by libavcodec.
+ */
+ int has_b_frames;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int mpeg_quant;
+#endif
+
+ /**
+ * qscale factor between P- and I-frames
+ * If > 0 then the last P-frame quantizer will be used (q = lastp_q * factor + offset).
+ * If < 0 then normal ratecontrol will be done (q= -normal_q*factor+offset).
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float i_quant_factor;
+
+ /**
+ * qscale offset between P and I-frames
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float i_quant_offset;
+
+ /**
+ * luminance masking (0-> disabled)
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float lumi_masking;
+
+ /**
+ * temporary complexity masking (0-> disabled)
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float temporal_cplx_masking;
+
+ /**
+ * spatial complexity masking (0-> disabled)
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float spatial_cplx_masking;
+
+ /**
+ * p block masking (0-> disabled)
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float p_masking;
+
+ /**
+ * darkness masking (0-> disabled)
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ float dark_masking;
+
+ /**
+ * slice count
+ * - encoding: Set by libavcodec.
+ * - decoding: Set by user (or 0).
+ */
+ int slice_count;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int prediction_method;
+#define FF_PRED_LEFT 0
+#define FF_PRED_PLANE 1
+#define FF_PRED_MEDIAN 2
+#endif
+
+ /**
+ * slice offsets in the frame in bytes
+ * - encoding: Set/allocated by libavcodec.
+ * - decoding: Set/allocated by user (or NULL).
+ */
+ int *slice_offset;
+
+ /**
+ * sample aspect ratio (0 if unknown)
+ * That is the width of a pixel divided by the height of the pixel.
+ * Numerator and denominator must be relatively prime and smaller than 256 for some video standards.
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ AVRational sample_aspect_ratio;
+
+ /**
+ * motion estimation comparison function
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int me_cmp;
+ /**
+ * subpixel motion estimation comparison function
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int me_sub_cmp;
+ /**
+ * macroblock comparison function (not supported yet)
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int mb_cmp;
+ /**
+ * interlaced DCT comparison function
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int ildct_cmp;
+#define FF_CMP_SAD 0
+#define FF_CMP_SSE 1
+#define FF_CMP_SATD 2
+#define FF_CMP_DCT 3
+#define FF_CMP_PSNR 4
+#define FF_CMP_BIT 5
+#define FF_CMP_RD 6
+#define FF_CMP_ZERO 7
+#define FF_CMP_VSAD 8
+#define FF_CMP_VSSE 9
+#define FF_CMP_NSSE 10
+#define FF_CMP_W53 11
+#define FF_CMP_W97 12
+#define FF_CMP_DCTMAX 13
+#define FF_CMP_DCT264 14
+#define FF_CMP_MEDIAN_SAD 15
+#define FF_CMP_CHROMA 256
+
+ /**
+ * ME diamond size & shape
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int dia_size;
+
+ /**
+ * amount of previous MV predictors (2a+1 x 2a+1 square)
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int last_predictor_count;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int pre_me;
+#endif
+
+ /**
+ * motion estimation prepass comparison function
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int me_pre_cmp;
+
+ /**
+ * ME prepass diamond size & shape
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int pre_dia_size;
+
+ /**
+ * subpel ME quality
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int me_subpel_quality;
+
+ /**
+ * maximum motion estimation search range in subpel units
+ * If 0 then no limit.
+ *
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int me_range;
+
+ /**
+ * slice flags
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ int slice_flags;
+#define SLICE_FLAG_CODED_ORDER 0x0001 ///< draw_horiz_band() is called in coded order instead of display
+#define SLICE_FLAG_ALLOW_FIELD 0x0002 ///< allow draw_horiz_band() with field slices (MPEG-2 field pics)
+#define SLICE_FLAG_ALLOW_PLANE 0x0004 ///< allow draw_horiz_band() with 1 component at a time (SVQ1)
+
+ /**
+ * macroblock decision mode
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int mb_decision;
+#define FF_MB_DECISION_SIMPLE 0 ///< uses mb_cmp
+#define FF_MB_DECISION_BITS 1 ///< chooses the one which needs the fewest bits
+#define FF_MB_DECISION_RD 2 ///< rate distortion
+
+ /**
+ * custom intra quantization matrix
+ * - encoding: Set by user, can be NULL.
+ * - decoding: Set by libavcodec.
+ */
+ uint16_t *intra_matrix;
+
+ /**
+ * custom inter quantization matrix
+ * - encoding: Set by user, can be NULL.
+ * - decoding: Set by libavcodec.
+ */
+ uint16_t *inter_matrix;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int scenechange_threshold;
+
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int noise_reduction;
+#endif
+
+ /**
+ * precision of the intra DC coefficient - 8
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec
+ */
+ int intra_dc_precision;
+
+ /**
+ * Number of macroblock rows at the top which are skipped.
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ int skip_top;
+
+ /**
+ * Number of macroblock rows at the bottom which are skipped.
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ int skip_bottom;
+
+ /**
+ * minimum MB Lagrange multiplier
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int mb_lmin;
+
+ /**
+ * maximum MB Lagrange multiplier
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int mb_lmax;
+
+#if FF_API_PRIVATE_OPT
+ /**
+ * @deprecated use encoder private options instead
+ */
+ attribute_deprecated
+ int me_penalty_compensation;
+#endif
+
+ /**
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int bidir_refine;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int brd_scale;
+#endif
+
+ /**
+ * minimum GOP size
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int keyint_min;
+
+ /**
+ * number of reference frames
+ * - encoding: Set by user.
+ * - decoding: Set by lavc.
+ */
+ int refs;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int chromaoffset;
+#endif
+
+ /**
+ * Note: Value depends upon the compare function used for fullpel ME.
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int mv0_threshold;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int b_sensitivity;
+#endif
+
+ /**
+ * Chromaticity coordinates of the source primaries.
+ * - encoding: Set by user
+ * - decoding: Set by libavcodec
+ */
+ enum AVColorPrimaries color_primaries;
+
+ /**
+ * Color Transfer Characteristic.
+ * - encoding: Set by user
+ * - decoding: Set by libavcodec
+ */
+ enum AVColorTransferCharacteristic color_trc;
+
+ /**
+ * YUV colorspace type.
+ * - encoding: Set by user
+ * - decoding: Set by libavcodec
+ */
+ enum AVColorSpace colorspace;
+
+ /**
+ * MPEG vs JPEG YUV range.
+ * - encoding: Set by user
+ * - decoding: Set by libavcodec
+ */
+ enum AVColorRange color_range;
+
+ /**
+ * This defines the location of chroma samples.
+ * - encoding: Set by user
+ * - decoding: Set by libavcodec
+ */
+ enum AVChromaLocation chroma_sample_location;
+
+ /**
+ * Number of slices.
+ * Indicates number of picture subdivisions. Used for parallelized
+ * decoding.
+ * - encoding: Set by user
+ * - decoding: unused
+ */
+ int slices;
+
+ /** Field order
+ * - encoding: set by libavcodec
+ * - decoding: Set by user.
+ */
+ enum AVFieldOrder field_order;
+
+ /* audio only */
+ int sample_rate; ///< samples per second
+ int channels; ///< number of audio channels
+
+ /**
+ * audio sample format
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ enum AVSampleFormat sample_fmt; ///< sample format
+
+ /* The following data should not be initialized. */
+ /**
+ * Number of samples per channel in an audio frame.
+ *
+ * - encoding: set by libavcodec in avcodec_open2(). Each submitted frame
+ * except the last must contain exactly frame_size samples per channel.
+ * May be 0 when the codec has AV_CODEC_CAP_VARIABLE_FRAME_SIZE set, then the
+ * frame size is not restricted.
+ * - decoding: may be set by some decoders to indicate constant frame size
+ */
+ int frame_size;
+
+ /**
+ * Frame counter, set by libavcodec.
+ *
+ * - decoding: total number of frames returned from the decoder so far.
+ * - encoding: total number of frames passed to the encoder so far.
+ *
+ * @note the counter is not incremented if encoding/decoding resulted in
+ * an error.
+ */
+ int frame_number;
+
+ /**
+ * number of bytes per packet if constant and known or 0
+ * Used by some WAV based audio codecs.
+ */
+ int block_align;
+
+ /**
+ * Audio cutoff bandwidth (0 means "automatic")
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int cutoff;
+
+ /**
+ * Audio channel layout.
+ * - encoding: set by user.
+ * - decoding: set by user, may be overwritten by libavcodec.
+ */
+ uint64_t channel_layout;
+
+ /**
+ * Request decoder to use this channel layout if it can (0 for default)
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ uint64_t request_channel_layout;
+
+ /**
+ * Type of service that the audio stream conveys.
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ enum AVAudioServiceType audio_service_type;
+
+ /**
+ * desired sample format
+ * - encoding: Not used.
+ * - decoding: Set by user.
+ * Decoder will decode to this format if it can.
+ */
+ enum AVSampleFormat request_sample_fmt;
+
+ /**
+ * This callback is called at the beginning of each frame to get data
+ * buffer(s) for it. There may be one contiguous buffer for all the data or
+ * there may be a buffer per each data plane or anything in between. What
+ * this means is, you may set however many entries in buf[] you feel necessary.
+ * Each buffer must be reference-counted using the AVBuffer API (see description
+ * of buf[] below).
+ *
+ * The following fields will be set in the frame before this callback is
+ * called:
+ * - format
+ * - width, height (video only)
+ * - sample_rate, channel_layout, nb_samples (audio only)
+ * Their values may differ from the corresponding values in
+ * AVCodecContext. This callback must use the frame values, not the codec
+ * context values, to calculate the required buffer size.
+ *
+ * This callback must fill the following fields in the frame:
+ * - data[]
+ * - linesize[]
+ * - extended_data:
+ * * if the data is planar audio with more than 8 channels, then this
+ * callback must allocate and fill extended_data to contain all pointers
+ * to all data planes. data[] must hold as many pointers as it can.
+ * extended_data must be allocated with av_malloc() and will be freed in
+ * av_frame_unref().
+ * * otherwise extended_data must point to data
+ * - buf[] must contain one or more pointers to AVBufferRef structures. Each of
+ * the frame's data and extended_data pointers must be contained in these. That
+ * is, one AVBufferRef for each allocated chunk of memory, not necessarily one
+ * AVBufferRef per data[] entry. See: av_buffer_create(), av_buffer_alloc(),
+ * and av_buffer_ref().
+ * - extended_buf and nb_extended_buf must be allocated with av_malloc() by
+ * this callback and filled with the extra buffers if there are more
+ * buffers than buf[] can hold. extended_buf will be freed in
+ * av_frame_unref().
+ *
+ * If AV_CODEC_CAP_DR1 is not set then get_buffer2() must call
+ * avcodec_default_get_buffer2() instead of providing buffers allocated by
+ * some other means.
+ *
+ * Each data plane must be aligned to the maximum required by the target
+ * CPU.
+ *
+ * @see avcodec_default_get_buffer2()
+ *
+ * Video:
+ *
+ * If AV_GET_BUFFER_FLAG_REF is set in flags then the frame may be reused
+ * (read and/or written to if it is writable) later by libavcodec.
+ *
+ * avcodec_align_dimensions2() should be used to find the required width and
+ * height, as they normally need to be rounded up to the next multiple of 16.
+ *
+ * Some decoders do not support linesizes changing between frames.
+ *
+ * If frame multithreading is used and thread_safe_callbacks is set,
+ * this callback may be called from a different thread, but not from more
+ * than one at once. Does not need to be reentrant.
+ *
+ * @see avcodec_align_dimensions2()
+ *
+ * Audio:
+ *
+ * Decoders request a buffer of a particular size by setting
+ * AVFrame.nb_samples prior to calling get_buffer2(). The decoder may,
+ * however, utilize only part of the buffer by setting AVFrame.nb_samples
+ * to a smaller value in the output frame.
+ *
+ * As a convenience, av_samples_get_buffer_size() and
+ * av_samples_fill_arrays() in libavutil may be used by custom get_buffer2()
+ * functions to find the required data size and to fill data pointers and
+ * linesize. In AVFrame.linesize, only linesize[0] may be set for audio
+ * since all planes must be the same size.
+ *
+ * @see av_samples_get_buffer_size(), av_samples_fill_arrays()
+ *
+ * - encoding: unused
+ * - decoding: Set by libavcodec, user can override.
+ */
+ int (*get_buffer2)(struct AVCodecContext *s, AVFrame *frame, int flags);
+
+ /**
+ * If non-zero, the decoded audio and video frames returned from
+ * avcodec_decode_video2() and avcodec_decode_audio4() are reference-counted
+ * and are valid indefinitely. The caller must free them with
+ * av_frame_unref() when they are not needed anymore.
+ * Otherwise, the decoded frames must not be freed by the caller and are
+ * only valid until the next decode call.
+ *
+ * This is always automatically enabled if avcodec_receive_frame() is used.
+ *
+ * - encoding: unused
+ * - decoding: set by the caller before avcodec_open2().
+ */
+ attribute_deprecated
+ int refcounted_frames;
+
+ /* - encoding parameters */
+ float qcompress; ///< amount of qscale change between easy & hard scenes (0.0-1.0)
+ float qblur; ///< amount of qscale smoothing over time (0.0-1.0)
+
+ /**
+ * minimum quantizer
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int qmin;
+
+ /**
+ * maximum quantizer
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int qmax;
+
+ /**
+ * maximum quantizer difference between frames
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int max_qdiff;
+
+ /**
+ * decoder bitstream buffer size
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int rc_buffer_size;
+
+ /**
+ * ratecontrol override, see RcOverride
+ * - encoding: Allocated/set/freed by user.
+ * - decoding: unused
+ */
+ int rc_override_count;
+ RcOverride *rc_override;
+
+ /**
+ * maximum bitrate
+ * - encoding: Set by user.
+ * - decoding: Set by user, may be overwritten by libavcodec.
+ */
+ int64_t rc_max_rate;
+
+ /**
+ * minimum bitrate
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int64_t rc_min_rate;
+
+ /**
+ * Ratecontrol attempt to use, at maximum, <value> of what can be used without an underflow.
+ * - encoding: Set by user.
+ * - decoding: unused.
+ */
+ float rc_max_available_vbv_use;
+
+ /**
+ * Ratecontrol attempt to use, at least, <value> times the amount needed to prevent a vbv overflow.
+ * - encoding: Set by user.
+ * - decoding: unused.
+ */
+ float rc_min_vbv_overflow_use;
+
+ /**
+ * Number of bits which should be loaded into the rc buffer before decoding starts.
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int rc_initial_buffer_occupancy;
+
+#if FF_API_CODER_TYPE
+#define FF_CODER_TYPE_VLC 0
+#define FF_CODER_TYPE_AC 1
+#define FF_CODER_TYPE_RAW 2
+#define FF_CODER_TYPE_RLE 3
+ /**
+ * @deprecated use encoder private options instead
+ */
+ attribute_deprecated
+ int coder_type;
+#endif /* FF_API_CODER_TYPE */
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int context_model;
+#endif
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int frame_skip_threshold;
+
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int frame_skip_factor;
+
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int frame_skip_exp;
+
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int frame_skip_cmp;
+#endif /* FF_API_PRIVATE_OPT */
+
+ /**
+ * trellis RD quantization
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int trellis;
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int min_prediction_order;
+
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int max_prediction_order;
+
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int64_t timecode_frame_start;
+#endif
+
+#if FF_API_RTP_CALLBACK
+ /**
+ * @deprecated unused
+ */
+ /* The RTP callback: This function is called */
+ /* every time the encoder has a packet to send. */
+ /* It depends on the encoder if the data starts */
+ /* with a Start Code (it should). H.263 does. */
+ /* mb_nb contains the number of macroblocks */
+ /* encoded in the RTP payload. */
+ attribute_deprecated
+ void (*rtp_callback)(struct AVCodecContext *avctx, void *data, int size, int mb_nb);
+#endif
+
+#if FF_API_PRIVATE_OPT
+ /** @deprecated use encoder private options instead */
+ attribute_deprecated
+ int rtp_payload_size; /* The size of the RTP payload: the coder will */
+ /* do its best to deliver a chunk with size */
+ /* below rtp_payload_size, the chunk will start */
+ /* with a start code on some codecs like H.263. */
+ /* This doesn't take account of any particular */
+ /* headers inside the transmitted RTP payload. */
+#endif
+
+#if FF_API_STAT_BITS
+ /* statistics, used for 2-pass encoding */
+ attribute_deprecated
+ int mv_bits;
+ attribute_deprecated
+ int header_bits;
+ attribute_deprecated
+ int i_tex_bits;
+ attribute_deprecated
+ int p_tex_bits;
+ attribute_deprecated
+ int i_count;
+ attribute_deprecated
+ int p_count;
+ attribute_deprecated
+ int skip_count;
+ attribute_deprecated
+ int misc_bits;
+
+ /** @deprecated this field is unused */
+ attribute_deprecated
+ int frame_bits;
+#endif
+
+ /**
+ * pass1 encoding statistics output buffer
+ * - encoding: Set by libavcodec.
+ * - decoding: unused
+ */
+ char *stats_out;
+
+ /**
+ * pass2 encoding statistics input buffer
+ * Concatenated stuff from stats_out of pass1 should be placed here.
+ * - encoding: Allocated/set/freed by user.
+ * - decoding: unused
+ */
+ char *stats_in;
+
+ /**
+ * Work around bugs in encoders which sometimes cannot be detected automatically.
+ * - encoding: Set by user
+ * - decoding: Set by user
+ */
+ int workaround_bugs;
+#define FF_BUG_AUTODETECT 1 ///< autodetection
+#define FF_BUG_XVID_ILACE 4
+#define FF_BUG_UMP4 8
+#define FF_BUG_NO_PADDING 16
+#define FF_BUG_AMV 32
+#define FF_BUG_QPEL_CHROMA 64
+#define FF_BUG_STD_QPEL 128
+#define FF_BUG_QPEL_CHROMA2 256
+#define FF_BUG_DIRECT_BLOCKSIZE 512
+#define FF_BUG_EDGE 1024
+#define FF_BUG_HPEL_CHROMA 2048
+#define FF_BUG_DC_CLIP 4096
+#define FF_BUG_MS 8192 ///< Work around various bugs in Microsoft's broken decoders.
+#define FF_BUG_TRUNCATED 16384
+#define FF_BUG_IEDGE 32768
+
+ /**
+ * strictly follow the standard (MPEG-4, ...).
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ * Setting this to STRICT or higher means the encoder and decoder will
+ * generally do stupid things, whereas setting it to unofficial or lower
+ * will mean the encoder might produce output that is not supported by all
+ * spec-compliant decoders. Decoders don't differentiate between normal,
+ * unofficial and experimental (that is, they always try to decode things
+ * when they can) unless they are explicitly asked to behave stupidly
+ * (=strictly conform to the specs)
+ */
+ int strict_std_compliance;
+#define FF_COMPLIANCE_VERY_STRICT 2 ///< Strictly conform to an older more strict version of the spec or reference software.
+#define FF_COMPLIANCE_STRICT 1 ///< Strictly conform to all the things in the spec no matter what consequences.
+#define FF_COMPLIANCE_NORMAL 0
+#define FF_COMPLIANCE_UNOFFICIAL -1 ///< Allow unofficial extensions
+#define FF_COMPLIANCE_EXPERIMENTAL -2 ///< Allow nonstandardized experimental things.
+
+ /**
+ * error concealment flags
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ int error_concealment;
+#define FF_EC_GUESS_MVS 1
+#define FF_EC_DEBLOCK 2
+#define FF_EC_FAVOR_INTER 256
+
+ /**
+ * debug
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ int debug;
+#define FF_DEBUG_PICT_INFO 1
+#define FF_DEBUG_RC 2
+#define FF_DEBUG_BITSTREAM 4
+#define FF_DEBUG_MB_TYPE 8
+#define FF_DEBUG_QP 16
+#if FF_API_DEBUG_MV
+/**
+ * @deprecated this option does nothing
+ */
+#define FF_DEBUG_MV 32
+#endif
+#define FF_DEBUG_DCT_COEFF 0x00000040
+#define FF_DEBUG_SKIP 0x00000080
+#define FF_DEBUG_STARTCODE 0x00000100
+#define FF_DEBUG_ER 0x00000400
+#define FF_DEBUG_MMCO 0x00000800
+#define FF_DEBUG_BUGS 0x00001000
+#if FF_API_DEBUG_MV
+#define FF_DEBUG_VIS_QP 0x00002000
+#define FF_DEBUG_VIS_MB_TYPE 0x00004000
+#endif
+#define FF_DEBUG_BUFFERS 0x00008000
+#define FF_DEBUG_THREADS 0x00010000
+#define FF_DEBUG_GREEN_MD 0x00800000
+#define FF_DEBUG_NOMC 0x01000000
+
+#if FF_API_DEBUG_MV
+ /**
+ * debug
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ int debug_mv;
+#define FF_DEBUG_VIS_MV_P_FOR 0x00000001 // visualize forward predicted MVs of P-frames
+#define FF_DEBUG_VIS_MV_B_FOR 0x00000002 // visualize forward predicted MVs of B-frames
+#define FF_DEBUG_VIS_MV_B_BACK 0x00000004 // visualize backward predicted MVs of B-frames
+#endif
+
+ /**
+ * Error recognition; may misdetect some more or less valid parts as errors.
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ int err_recognition;
+
+/**
+ * Verify checksums embedded in the bitstream (could be of either encoded or
+ * decoded data, depending on the codec) and print an error message on mismatch.
+ * If AV_EF_EXPLODE is also set, a mismatching checksum will result in the
+ * decoder returning an error.
+ */
+#define AV_EF_CRCCHECK (1<<0)
+#define AV_EF_BITSTREAM (1<<1) ///< detect bitstream specification deviations
+#define AV_EF_BUFFER (1<<2) ///< detect improper bitstream length
+#define AV_EF_EXPLODE (1<<3) ///< abort decoding on minor error detection
+
+#define AV_EF_IGNORE_ERR (1<<15) ///< ignore errors and continue
+#define AV_EF_CAREFUL (1<<16) ///< consider things that violate the spec, are fast to calculate and have not been seen in the wild as errors
+#define AV_EF_COMPLIANT (1<<17) ///< consider all spec non compliances as errors
+#define AV_EF_AGGRESSIVE (1<<18) ///< consider things that a sane encoder should not do as an error
+
+
+ /**
+ * opaque 64-bit number (generally a PTS) that will be reordered and
+ * output in AVFrame.reordered_opaque
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ int64_t reordered_opaque;
+
+ /**
+ * Hardware accelerator in use
+ * - encoding: unused.
+ * - decoding: Set by libavcodec
+ */
+ const struct AVHWAccel *hwaccel;
+
+ /**
+ * Hardware accelerator context.
+ * For some hardware accelerators, a global context needs to be
+ * provided by the user. In that case, this holds display-dependent
+ * data FFmpeg cannot instantiate itself. Please refer to the
+ * FFmpeg HW accelerator documentation to know how to fill this
+ * is. e.g. for VA API, this is a struct vaapi_context.
+ * - encoding: unused
+ * - decoding: Set by user
+ */
+ void *hwaccel_context;
+
+ /**
+ * error
+ * - encoding: Set by libavcodec if flags & AV_CODEC_FLAG_PSNR.
+ * - decoding: unused
+ */
+ uint64_t error[AV_NUM_DATA_POINTERS];
+
+ /**
+ * DCT algorithm, see FF_DCT_* below
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int dct_algo;
+#define FF_DCT_AUTO 0
+#define FF_DCT_FASTINT 1
+#define FF_DCT_INT 2
+#define FF_DCT_MMX 3
+#define FF_DCT_ALTIVEC 5
+#define FF_DCT_FAAN 6
+
+ /**
+ * IDCT algorithm, see FF_IDCT_* below.
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ int idct_algo;
+#define FF_IDCT_AUTO 0
+#define FF_IDCT_INT 1
+#define FF_IDCT_SIMPLE 2
+#define FF_IDCT_SIMPLEMMX 3
+#define FF_IDCT_ARM 7
+#define FF_IDCT_ALTIVEC 8
+#define FF_IDCT_SIMPLEARM 10
+#define FF_IDCT_XVID 14
+#define FF_IDCT_SIMPLEARMV5TE 16
+#define FF_IDCT_SIMPLEARMV6 17
+#define FF_IDCT_FAAN 20
+#define FF_IDCT_SIMPLENEON 22
+#define FF_IDCT_NONE 24 /* Used by XvMC to extract IDCT coefficients with FF_IDCT_PERM_NONE */
+#define FF_IDCT_SIMPLEAUTO 128
+
+ /**
+ * bits per sample/pixel from the demuxer (needed for huffyuv).
+ * - encoding: Set by libavcodec.
+ * - decoding: Set by user.
+ */
+ int bits_per_coded_sample;
+
+ /**
+ * Bits per sample/pixel of internal libavcodec pixel/sample format.
+ * - encoding: set by user.
+ * - decoding: set by libavcodec.
+ */
+ int bits_per_raw_sample;
+
+#if FF_API_LOWRES
+ /**
+ * low resolution decoding, 1-> 1/2 size, 2->1/4 size
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ int lowres;
+#endif
+
+#if FF_API_CODED_FRAME
+ /**
+ * the picture in the bitstream
+ * - encoding: Set by libavcodec.
+ * - decoding: unused
+ *
+ * @deprecated use the quality factor packet side data instead
+ */
+ attribute_deprecated AVFrame *coded_frame;
+#endif
+
+ /**
+ * thread count
+ * is used to decide how many independent tasks should be passed to execute()
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ int thread_count;
+
+ /**
+ * Which multithreading methods to use.
+ * Use of FF_THREAD_FRAME will increase decoding delay by one frame per thread,
+ * so clients which cannot provide future frames should not use it.
+ *
+ * - encoding: Set by user, otherwise the default is used.
+ * - decoding: Set by user, otherwise the default is used.
+ */
+ int thread_type;
+#define FF_THREAD_FRAME 1 ///< Decode more than one frame at once
+#define FF_THREAD_SLICE 2 ///< Decode more than one part of a single frame at once
+
+ /**
+ * Which multithreading methods are in use by the codec.
+ * - encoding: Set by libavcodec.
+ * - decoding: Set by libavcodec.
+ */
+ int active_thread_type;
+
+ /**
+ * Set by the client if its custom get_buffer() callback can be called
+ * synchronously from another thread, which allows faster multithreaded decoding.
+ * draw_horiz_band() will be called from other threads regardless of this setting.
+ * Ignored if the default get_buffer() is used.
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ int thread_safe_callbacks;
+
+ /**
+ * The codec may call this to execute several independent things.
+ * It will return only after finishing all tasks.
+ * The user may replace this with some multithreaded implementation,
+ * the default implementation will execute the parts serially.
+ * @param count the number of things to execute
+ * - encoding: Set by libavcodec, user can override.
+ * - decoding: Set by libavcodec, user can override.
+ */
+ int (*execute)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg), void *arg2, int *ret, int count, int size);
+
+ /**
+ * The codec may call this to execute several independent things.
+ * It will return only after finishing all tasks.
+ * The user may replace this with some multithreaded implementation,
+ * the default implementation will execute the parts serially.
+ * Also see avcodec_thread_init and e.g. the --enable-pthread configure option.
+ * @param c context passed also to func
+ * @param count the number of things to execute
+ * @param arg2 argument passed unchanged to func
+ * @param ret return values of executed functions, must have space for "count" values. May be NULL.
+ * @param func function that will be called count times, with jobnr from 0 to count-1.
+ * threadnr will be in the range 0 to c->thread_count-1 < MAX_THREADS and so that no
+ * two instances of func executing at the same time will have the same threadnr.
+ * @return always 0 currently, but code should handle a future improvement where when any call to func
+ * returns < 0 no further calls to func may be done and < 0 is returned.
+ * - encoding: Set by libavcodec, user can override.
+ * - decoding: Set by libavcodec, user can override.
+ */
+ int (*execute2)(struct AVCodecContext *c, int (*func)(struct AVCodecContext *c2, void *arg, int jobnr, int threadnr), void *arg2, int *ret, int count);
+
+ /**
+ * noise vs. sse weight for the nsse comparison function
+ * - encoding: Set by user.
+ * - decoding: unused
+ */
+ int nsse_weight;
+
+ /**
+ * profile
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ int profile;
+#define FF_PROFILE_UNKNOWN -99
+#define FF_PROFILE_RESERVED -100
+
+#define FF_PROFILE_AAC_MAIN 0
+#define FF_PROFILE_AAC_LOW 1
+#define FF_PROFILE_AAC_SSR 2
+#define FF_PROFILE_AAC_LTP 3
+#define FF_PROFILE_AAC_HE 4
+#define FF_PROFILE_AAC_HE_V2 28
+#define FF_PROFILE_AAC_LD 22
+#define FF_PROFILE_AAC_ELD 38
+#define FF_PROFILE_MPEG2_AAC_LOW 128
+#define FF_PROFILE_MPEG2_AAC_HE 131
+
+#define FF_PROFILE_DNXHD 0
+#define FF_PROFILE_DNXHR_LB 1
+#define FF_PROFILE_DNXHR_SQ 2
+#define FF_PROFILE_DNXHR_HQ 3
+#define FF_PROFILE_DNXHR_HQX 4
+#define FF_PROFILE_DNXHR_444 5
+
+#define FF_PROFILE_DTS 20
+#define FF_PROFILE_DTS_ES 30
+#define FF_PROFILE_DTS_96_24 40
+#define FF_PROFILE_DTS_HD_HRA 50
+#define FF_PROFILE_DTS_HD_MA 60
+#define FF_PROFILE_DTS_EXPRESS 70
+
+#define FF_PROFILE_MPEG2_422 0
+#define FF_PROFILE_MPEG2_HIGH 1
+#define FF_PROFILE_MPEG2_SS 2
+#define FF_PROFILE_MPEG2_SNR_SCALABLE 3
+#define FF_PROFILE_MPEG2_MAIN 4
+#define FF_PROFILE_MPEG2_SIMPLE 5
+
+#define FF_PROFILE_H264_CONSTRAINED (1<<9) // 8+1; constraint_set1_flag
+#define FF_PROFILE_H264_INTRA (1<<11) // 8+3; constraint_set3_flag
+
+#define FF_PROFILE_H264_BASELINE 66
+#define FF_PROFILE_H264_CONSTRAINED_BASELINE (66|FF_PROFILE_H264_CONSTRAINED)
+#define FF_PROFILE_H264_MAIN 77
+#define FF_PROFILE_H264_EXTENDED 88
+#define FF_PROFILE_H264_HIGH 100
+#define FF_PROFILE_H264_HIGH_10 110
+#define FF_PROFILE_H264_HIGH_10_INTRA (110|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_MULTIVIEW_HIGH 118
+#define FF_PROFILE_H264_HIGH_422 122
+#define FF_PROFILE_H264_HIGH_422_INTRA (122|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_STEREO_HIGH 128
+#define FF_PROFILE_H264_HIGH_444 144
+#define FF_PROFILE_H264_HIGH_444_PREDICTIVE 244
+#define FF_PROFILE_H264_HIGH_444_INTRA (244|FF_PROFILE_H264_INTRA)
+#define FF_PROFILE_H264_CAVLC_444 44
+
+#define FF_PROFILE_VC1_SIMPLE 0
+#define FF_PROFILE_VC1_MAIN 1
+#define FF_PROFILE_VC1_COMPLEX 2
+#define FF_PROFILE_VC1_ADVANCED 3
+
+#define FF_PROFILE_MPEG4_SIMPLE 0
+#define FF_PROFILE_MPEG4_SIMPLE_SCALABLE 1
+#define FF_PROFILE_MPEG4_CORE 2
+#define FF_PROFILE_MPEG4_MAIN 3
+#define FF_PROFILE_MPEG4_N_BIT 4
+#define FF_PROFILE_MPEG4_SCALABLE_TEXTURE 5
+#define FF_PROFILE_MPEG4_SIMPLE_FACE_ANIMATION 6
+#define FF_PROFILE_MPEG4_BASIC_ANIMATED_TEXTURE 7
+#define FF_PROFILE_MPEG4_HYBRID 8
+#define FF_PROFILE_MPEG4_ADVANCED_REAL_TIME 9
+#define FF_PROFILE_MPEG4_CORE_SCALABLE 10
+#define FF_PROFILE_MPEG4_ADVANCED_CODING 11
+#define FF_PROFILE_MPEG4_ADVANCED_CORE 12
+#define FF_PROFILE_MPEG4_ADVANCED_SCALABLE_TEXTURE 13
+#define FF_PROFILE_MPEG4_SIMPLE_STUDIO 14
+#define FF_PROFILE_MPEG4_ADVANCED_SIMPLE 15
+
+#define FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0 1
+#define FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1 2
+#define FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION 32768
+#define FF_PROFILE_JPEG2000_DCINEMA_2K 3
+#define FF_PROFILE_JPEG2000_DCINEMA_4K 4
+
+#define FF_PROFILE_VP9_0 0
+#define FF_PROFILE_VP9_1 1
+#define FF_PROFILE_VP9_2 2
+#define FF_PROFILE_VP9_3 3
+
+#define FF_PROFILE_HEVC_MAIN 1
+#define FF_PROFILE_HEVC_MAIN_10 2
+#define FF_PROFILE_HEVC_MAIN_STILL_PICTURE 3
+#define FF_PROFILE_HEVC_REXT 4
+
+#define FF_PROFILE_AV1_MAIN 0
+#define FF_PROFILE_AV1_HIGH 1
+#define FF_PROFILE_AV1_PROFESSIONAL 2
+
+#define FF_PROFILE_MJPEG_HUFFMAN_BASELINE_DCT 0xc0
+#define FF_PROFILE_MJPEG_HUFFMAN_EXTENDED_SEQUENTIAL_DCT 0xc1
+#define FF_PROFILE_MJPEG_HUFFMAN_PROGRESSIVE_DCT 0xc2
+#define FF_PROFILE_MJPEG_HUFFMAN_LOSSLESS 0xc3
+#define FF_PROFILE_MJPEG_JPEG_LS 0xf7
+
+#define FF_PROFILE_SBC_MSBC 1
+
+ /**
+ * level
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ int level;
+#define FF_LEVEL_UNKNOWN -99
+
+ /**
+ * Skip loop filtering for selected frames.
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ enum AVDiscard skip_loop_filter;
+
+ /**
+ * Skip IDCT/dequantization for selected frames.
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ enum AVDiscard skip_idct;
+
+ /**
+ * Skip decoding for selected frames.
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ enum AVDiscard skip_frame;
+
+ /**
+ * Header containing style information for text subtitles.
+ * For SUBTITLE_ASS subtitle type, it should contain the whole ASS
+ * [Script Info] and [V4+ Styles] section, plus the [Events] line and
+ * the Format line following. It shouldn't include any Dialogue line.
+ * - encoding: Set/allocated/freed by user (before avcodec_open2())
+ * - decoding: Set/allocated/freed by libavcodec (by avcodec_open2())
+ */
+ uint8_t *subtitle_header;
+ int subtitle_header_size;
+
+#if FF_API_VBV_DELAY
+ /**
+ * VBV delay coded in the last frame (in periods of a 27 MHz clock).
+ * Used for compliant TS muxing.
+ * - encoding: Set by libavcodec.
+ * - decoding: unused.
+ * @deprecated this value is now exported as a part of
+ * AV_PKT_DATA_CPB_PROPERTIES packet side data
+ */
+ attribute_deprecated
+ uint64_t vbv_delay;
+#endif
+
+#if FF_API_SIDEDATA_ONLY_PKT
+ /**
+ * Encoding only and set by default. Allow encoders to output packets
+ * that do not contain any encoded data, only side data.
+ *
+ * Some encoders need to output such packets, e.g. to update some stream
+ * parameters at the end of encoding.
+ *
+ * @deprecated this field disables the default behaviour and
+ * it is kept only for compatibility.
+ */
+ attribute_deprecated
+ int side_data_only_packets;
+#endif
+
+ /**
+ * Audio only. The number of "priming" samples (padding) inserted by the
+ * encoder at the beginning of the audio. I.e. this number of leading
+ * decoded samples must be discarded by the caller to get the original audio
+ * without leading padding.
+ *
+ * - decoding: unused
+ * - encoding: Set by libavcodec. The timestamps on the output packets are
+ * adjusted by the encoder so that they always refer to the
+ * first sample of the data actually contained in the packet,
+ * including any added padding. E.g. if the timebase is
+ * 1/samplerate and the timestamp of the first input sample is
+ * 0, the timestamp of the first output packet will be
+ * -initial_padding.
+ */
+ int initial_padding;
+
+ /**
+ * - decoding: For codecs that store a framerate value in the compressed
+ * bitstream, the decoder may export it here. { 0, 1} when
+ * unknown.
+ * - encoding: May be used to signal the framerate of CFR content to an
+ * encoder.
+ */
+ AVRational framerate;
+
+ /**
+ * Nominal unaccelerated pixel format, see AV_PIX_FMT_xxx.
+ * - encoding: unused.
+ * - decoding: Set by libavcodec before calling get_format()
+ */
+ enum AVPixelFormat sw_pix_fmt;
+
+ /**
+ * Timebase in which pkt_dts/pts and AVPacket.dts/pts are.
+ * - encoding unused.
+ * - decoding set by user.
+ */
+ AVRational pkt_timebase;
+
+ /**
+ * AVCodecDescriptor
+ * - encoding: unused.
+ * - decoding: set by libavcodec.
+ */
+ const AVCodecDescriptor *codec_descriptor;
+
+#if !FF_API_LOWRES
+ /**
+ * low resolution decoding, 1-> 1/2 size, 2->1/4 size
+ * - encoding: unused
+ * - decoding: Set by user.
+ */
+ int lowres;
+#endif
+
+ /**
+ * Current statistics for PTS correction.
+ * - decoding: maintained and used by libavcodec, not intended to be used by user apps
+ * - encoding: unused
+ */
+ int64_t pts_correction_num_faulty_pts; /// Number of incorrect PTS values so far
+ int64_t pts_correction_num_faulty_dts; /// Number of incorrect DTS values so far
+ int64_t pts_correction_last_pts; /// PTS of the last frame
+ int64_t pts_correction_last_dts; /// DTS of the last frame
+
+ /**
+ * Character encoding of the input subtitles file.
+ * - decoding: set by user
+ * - encoding: unused
+ */
+ char *sub_charenc;
+
+ /**
+ * Subtitles character encoding mode. Formats or codecs might be adjusting
+ * this setting (if they are doing the conversion themselves for instance).
+ * - decoding: set by libavcodec
+ * - encoding: unused
+ */
+ int sub_charenc_mode;
+#define FF_SUB_CHARENC_MODE_DO_NOTHING -1 ///< do nothing (demuxer outputs a stream supposed to be already in UTF-8, or the codec is bitmap for instance)
+#define FF_SUB_CHARENC_MODE_AUTOMATIC 0 ///< libavcodec will select the mode itself
+#define FF_SUB_CHARENC_MODE_PRE_DECODER 1 ///< the AVPacket data needs to be recoded to UTF-8 before being fed to the decoder, requires iconv
+#define FF_SUB_CHARENC_MODE_IGNORE 2 ///< neither convert the subtitles, nor check them for valid UTF-8
+
+ /**
+ * Skip processing alpha if supported by codec.
+ * Note that if the format uses pre-multiplied alpha (common with VP6,
+ * and recommended due to better video quality/compression)
+ * the image will look as if alpha-blended onto a black background.
+ * However for formats that do not use pre-multiplied alpha
+ * there might be serious artefacts (though e.g. libswscale currently
+ * assumes pre-multiplied alpha anyway).
+ *
+ * - decoding: set by user
+ * - encoding: unused
+ */
+ int skip_alpha;
+
+ /**
+ * Number of samples to skip after a discontinuity
+ * - decoding: unused
+ * - encoding: set by libavcodec
+ */
+ int seek_preroll;
+
+#if !FF_API_DEBUG_MV
+ /**
+ * debug motion vectors
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ int debug_mv;
+#define FF_DEBUG_VIS_MV_P_FOR 0x00000001 //visualize forward predicted MVs of P frames
+#define FF_DEBUG_VIS_MV_B_FOR 0x00000002 //visualize forward predicted MVs of B frames
+#define FF_DEBUG_VIS_MV_B_BACK 0x00000004 //visualize backward predicted MVs of B frames
+#endif
+
+ /**
+ * custom intra quantization matrix
+ * - encoding: Set by user, can be NULL.
+ * - decoding: unused.
+ */
+ uint16_t *chroma_intra_matrix;
+
+ /**
+ * dump format separator.
+ * can be ", " or "\n " or anything else
+ * - encoding: Set by user.
+ * - decoding: Set by user.
+ */
+ uint8_t *dump_separator;
+
+ /**
+ * ',' separated list of allowed decoders.
+ * If NULL then all are allowed
+ * - encoding: unused
+ * - decoding: set by user
+ */
+ char *codec_whitelist;
+
+ /**
+ * Properties of the stream that gets decoded
+ * - encoding: unused
+ * - decoding: set by libavcodec
+ */
+ unsigned properties;
+#define FF_CODEC_PROPERTY_LOSSLESS 0x00000001
+#define FF_CODEC_PROPERTY_CLOSED_CAPTIONS 0x00000002
+
+ /**
+ * Additional data associated with the entire coded stream.
+ *
+ * - decoding: unused
+ * - encoding: may be set by libavcodec after avcodec_open2().
+ */
+ AVPacketSideData *coded_side_data;
+ int nb_coded_side_data;
+
+ /**
+ * A reference to the AVHWFramesContext describing the input (for encoding)
+ * or output (decoding) frames. The reference is set by the caller and
+ * afterwards owned (and freed) by libavcodec - it should never be read by
+ * the caller after being set.
+ *
+ * - decoding: This field should be set by the caller from the get_format()
+ * callback. The previous reference (if any) will always be
+ * unreffed by libavcodec before the get_format() call.
+ *
+ * If the default get_buffer2() is used with a hwaccel pixel
+ * format, then this AVHWFramesContext will be used for
+ * allocating the frame buffers.
+ *
+ * - encoding: For hardware encoders configured to use a hwaccel pixel
+ * format, this field should be set by the caller to a reference
+ * to the AVHWFramesContext describing input frames.
+ * AVHWFramesContext.format must be equal to
+ * AVCodecContext.pix_fmt.
+ *
+ * This field should be set before avcodec_open2() is called.
+ */
+ AVBufferRef *hw_frames_ctx;
+
+ /**
+ * Control the form of AVSubtitle.rects[N]->ass
+ * - decoding: set by user
+ * - encoding: unused
+ */
+ int sub_text_format;
+#define FF_SUB_TEXT_FMT_ASS 0
+#if FF_API_ASS_TIMING
+#define FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS 1
+#endif
+
+ /**
+ * Audio only. The amount of padding (in samples) appended by the encoder to
+ * the end of the audio. I.e. this number of decoded samples must be
+ * discarded by the caller from the end of the stream to get the original
+ * audio without any trailing padding.
+ *
+ * - decoding: unused
+ * - encoding: unused
+ */
+ int trailing_padding;
+
+ /**
+ * The number of pixels per image to maximally accept.
+ *
+ * - decoding: set by user
+ * - encoding: set by user
+ */
+ int64_t max_pixels;
+
+ /**
+ * A reference to the AVHWDeviceContext describing the device which will
+ * be used by a hardware encoder/decoder. The reference is set by the
+ * caller and afterwards owned (and freed) by libavcodec.
+ *
+ * This should be used if either the codec device does not require
+ * hardware frames or any that are used are to be allocated internally by
+ * libavcodec. If the user wishes to supply any of the frames used as
+ * encoder input or decoder output then hw_frames_ctx should be used
+ * instead. When hw_frames_ctx is set in get_format() for a decoder, this
+ * field will be ignored while decoding the associated stream segment, but
+ * may again be used on a following one after another get_format() call.
+ *
+ * For both encoders and decoders this field should be set before
+ * avcodec_open2() is called and must not be written to thereafter.
+ *
+ * Note that some decoders may require this field to be set initially in
+ * order to support hw_frames_ctx at all - in that case, all frames
+ * contexts used must be created on the same device.
+ */
+ AVBufferRef *hw_device_ctx;
+
+ /**
+ * Bit set of AV_HWACCEL_FLAG_* flags, which affect hardware accelerated
+ * decoding (if active).
+ * - encoding: unused
+ * - decoding: Set by user (either before avcodec_open2(), or in the
+ * AVCodecContext.get_format callback)
+ */
+ int hwaccel_flags;
+
+ /**
+ * Video decoding only. Certain video codecs support cropping, meaning that
+ * only a sub-rectangle of the decoded frame is intended for display. This
+ * option controls how cropping is handled by libavcodec.
+ *
+ * When set to 1 (the default), libavcodec will apply cropping internally.
+ * I.e. it will modify the output frame width/height fields and offset the
+ * data pointers (only by as much as possible while preserving alignment, or
+ * by the full amount if the AV_CODEC_FLAG_UNALIGNED flag is set) so that
+ * the frames output by the decoder refer only to the cropped area. The
+ * crop_* fields of the output frames will be zero.
+ *
+ * When set to 0, the width/height fields of the output frames will be set
+ * to the coded dimensions and the crop_* fields will describe the cropping
+ * rectangle. Applying the cropping is left to the caller.
+ *
+ * @warning When hardware acceleration with opaque output frames is used,
+ * libavcodec is unable to apply cropping from the top/left border.
+ *
+ * @note when this option is set to zero, the width/height fields of the
+ * AVCodecContext and output AVFrames have different meanings. The codec
+ * context fields store display dimensions (with the coded dimensions in
+ * coded_width/height), while the frame fields store the coded dimensions
+ * (with the display dimensions being determined by the crop_* fields).
+ */
+ int apply_cropping;
+
+ /*
+ * Video decoding only. Sets the number of extra hardware frames which
+ * the decoder will allocate for use by the caller. This must be set
+ * before avcodec_open2() is called.
+ *
+ * Some hardware decoders require all frames that they will use for
+ * output to be defined in advance before decoding starts. For such
+ * decoders, the hardware frame pool must therefore be of a fixed size.
+ * The extra frames set here are on top of any number that the decoder
+ * needs internally in order to operate normally (for example, frames
+ * used as reference pictures).
+ */
+ int extra_hw_frames;
+} AVCodecContext;
+
+#if FF_API_CODEC_GET_SET
+/**
+ * Accessors for some AVCodecContext fields. These used to be provided for ABI
+ * compatibility, and do not need to be used anymore.
+ */
+attribute_deprecated
+AVRational av_codec_get_pkt_timebase (const AVCodecContext *avctx);
+attribute_deprecated
+void av_codec_set_pkt_timebase (AVCodecContext *avctx, AVRational val);
+
+attribute_deprecated
+const AVCodecDescriptor *av_codec_get_codec_descriptor(const AVCodecContext *avctx);
+attribute_deprecated
+void av_codec_set_codec_descriptor(AVCodecContext *avctx, const AVCodecDescriptor *desc);
+
+attribute_deprecated
+unsigned av_codec_get_codec_properties(const AVCodecContext *avctx);
+
+#if FF_API_LOWRES
+attribute_deprecated
+int av_codec_get_lowres(const AVCodecContext *avctx);
+attribute_deprecated
+void av_codec_set_lowres(AVCodecContext *avctx, int val);
+#endif
+
+attribute_deprecated
+int av_codec_get_seek_preroll(const AVCodecContext *avctx);
+attribute_deprecated
+void av_codec_set_seek_preroll(AVCodecContext *avctx, int val);
+
+attribute_deprecated
+uint16_t *av_codec_get_chroma_intra_matrix(const AVCodecContext *avctx);
+attribute_deprecated
+void av_codec_set_chroma_intra_matrix(AVCodecContext *avctx, uint16_t *val);
+#endif
+
+/**
+ * AVProfile.
+ */
+typedef struct AVProfile {
+ int profile;
+ const char *name; ///< short name for the profile
+} AVProfile;
+
+enum {
+ /**
+ * The codec supports this format via the hw_device_ctx interface.
+ *
+ * When selecting this format, AVCodecContext.hw_device_ctx should
+ * have been set to a device of the specified type before calling
+ * avcodec_open2().
+ */
+ AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX = 0x01,
+ /**
+ * The codec supports this format via the hw_frames_ctx interface.
+ *
+ * When selecting this format for a decoder,
+ * AVCodecContext.hw_frames_ctx should be set to a suitable frames
+ * context inside the get_format() callback. The frames context
+ * must have been created on a device of the specified type.
+ */
+ AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX = 0x02,
+ /**
+ * The codec supports this format by some internal method.
+ *
+ * This format can be selected without any additional configuration -
+ * no device or frames context is required.
+ */
+ AV_CODEC_HW_CONFIG_METHOD_INTERNAL = 0x04,
+ /**
+ * The codec supports this format by some ad-hoc method.
+ *
+ * Additional settings and/or function calls are required. See the
+ * codec-specific documentation for details. (Methods requiring
+ * this sort of configuration are deprecated and others should be
+ * used in preference.)
+ */
+ AV_CODEC_HW_CONFIG_METHOD_AD_HOC = 0x08,
+};
+
+typedef struct AVCodecHWConfig {
+ /**
+ * A hardware pixel format which the codec can use.
+ */
+ enum AVPixelFormat pix_fmt;
+ /**
+ * Bit set of AV_CODEC_HW_CONFIG_METHOD_* flags, describing the possible
+ * setup methods which can be used with this configuration.
+ */
+ int methods;
+ /**
+ * The device type associated with the configuration.
+ *
+ * Must be set for AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX and
+ * AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX, otherwise unused.
+ */
+ enum AVHWDeviceType device_type;
+} AVCodecHWConfig;
+
+typedef struct AVCodecDefault AVCodecDefault;
+
+struct AVSubtitle;
+
+/**
+ * AVCodec.
+ */
+typedef struct AVCodec {
+ /**
+ * Name of the codec implementation.
+ * The name is globally unique among encoders and among decoders (but an
+ * encoder and a decoder can share the same name).
+ * This is the primary way to find a codec from the user perspective.
+ */
+ const char *name;
+ /**
+ * Descriptive name for the codec, meant to be more human readable than name.
+ * You should use the NULL_IF_CONFIG_SMALL() macro to define it.
+ */
+ const char *long_name;
+ enum AVMediaType type;
+ enum AVCodecID id;
+ /**
+ * Codec capabilities.
+ * see AV_CODEC_CAP_*
+ */
+ int capabilities;
+ const AVRational *supported_framerates; ///< array of supported framerates, or NULL if any, array is terminated by {0,0}
+ const enum AVPixelFormat *pix_fmts; ///< array of supported pixel formats, or NULL if unknown, array is terminated by -1
+ const int *supported_samplerates; ///< array of supported audio samplerates, or NULL if unknown, array is terminated by 0
+ const enum AVSampleFormat *sample_fmts; ///< array of supported sample formats, or NULL if unknown, array is terminated by -1
+ const uint64_t *channel_layouts; ///< array of support channel layouts, or NULL if unknown. array is terminated by 0
+ uint8_t max_lowres; ///< maximum value for lowres supported by the decoder
+ const AVClass *priv_class; ///< AVClass for the private context
+ const AVProfile *profiles; ///< array of recognized profiles, or NULL if unknown, array is terminated by {FF_PROFILE_UNKNOWN}
+
+ /**
+ * Group name of the codec implementation.
+ * This is a short symbolic name of the wrapper backing this codec. A
+ * wrapper uses some kind of external implementation for the codec, such
+ * as an external library, or a codec implementation provided by the OS or
+ * the hardware.
+ * If this field is NULL, this is a builtin, libavcodec native codec.
+ * If non-NULL, this will be the suffix in AVCodec.name in most cases
+ * (usually AVCodec.name will be of the form "<codec_name>_<wrapper_name>").
+ */
+ const char *wrapper_name;
+
+ /*****************************************************************
+ * No fields below this line are part of the public API. They
+ * may not be used outside of libavcodec and can be changed and
+ * removed at will.
+ * New public fields should be added right above.
+ *****************************************************************
+ */
+ int priv_data_size;
+ struct AVCodec *next;
+ /**
+ * @name Frame-level threading support functions
+ * @{
+ */
+ /**
+ * If defined, called on thread contexts when they are created.
+ * If the codec allocates writable tables in init(), re-allocate them here.
+ * priv_data will be set to a copy of the original.
+ */
+ int (*init_thread_copy)(AVCodecContext *);
+ /**
+ * Copy necessary context variables from a previous thread context to the current one.
+ * If not defined, the next thread will start automatically; otherwise, the codec
+ * must call ff_thread_finish_setup().
+ *
+ * dst and src will (rarely) point to the same context, in which case memcpy should be skipped.
+ */
+ int (*update_thread_context)(AVCodecContext *dst, const AVCodecContext *src);
+ /** @} */
+
+ /**
+ * Private codec-specific defaults.
+ */
+ const AVCodecDefault *defaults;
+
+ /**
+ * Initialize codec static data, called from avcodec_register().
+ *
+ * This is not intended for time consuming operations as it is
+ * run for every codec regardless of that codec being used.
+ */
+ void (*init_static_data)(struct AVCodec *codec);
+
+ int (*init)(AVCodecContext *);
+ int (*encode_sub)(AVCodecContext *, uint8_t *buf, int buf_size,
+ const struct AVSubtitle *sub);
+ /**
+ * Encode data to an AVPacket.
+ *
+ * @param avctx codec context
+ * @param avpkt output AVPacket (may contain a user-provided buffer)
+ * @param[in] frame AVFrame containing the raw data to be encoded
+ * @param[out] got_packet_ptr encoder sets to 0 or 1 to indicate that a
+ * non-empty packet was returned in avpkt.
+ * @return 0 on success, negative error code on failure
+ */
+ int (*encode2)(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame,
+ int *got_packet_ptr);
+ int (*decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt);
+ int (*close)(AVCodecContext *);
+ /**
+ * Encode API with decoupled packet/frame dataflow. The API is the
+ * same as the avcodec_ prefixed APIs (avcodec_send_frame() etc.), except
+ * that:
+ * - never called if the codec is closed or the wrong type,
+ * - if AV_CODEC_CAP_DELAY is not set, drain frames are never sent,
+ * - only one drain frame is ever passed down,
+ */
+ int (*send_frame)(AVCodecContext *avctx, const AVFrame *frame);
+ int (*receive_packet)(AVCodecContext *avctx, AVPacket *avpkt);
+
+ /**
+ * Decode API with decoupled packet/frame dataflow. This function is called
+ * to get one output frame. It should call ff_decode_get_packet() to obtain
+ * input data.
+ */
+ int (*receive_frame)(AVCodecContext *avctx, AVFrame *frame);
+ /**
+ * Flush buffers.
+ * Will be called when seeking
+ */
+ void (*flush)(AVCodecContext *);
+ /**
+ * Internal codec capabilities.
+ * See FF_CODEC_CAP_* in internal.h
+ */
+ int caps_internal;
+
+ /**
+ * Decoding only, a comma-separated list of bitstream filters to apply to
+ * packets before decoding.
+ */
+ const char *bsfs;
+
+ /**
+ * Array of pointers to hardware configurations supported by the codec,
+ * or NULL if no hardware supported. The array is terminated by a NULL
+ * pointer.
+ *
+ * The user can only access this field via avcodec_get_hw_config().
+ */
+ const struct AVCodecHWConfigInternal **hw_configs;
+} AVCodec;
+
+#if FF_API_CODEC_GET_SET
+attribute_deprecated
+int av_codec_get_max_lowres(const AVCodec *codec);
+#endif
+
+struct MpegEncContext;
+
+/**
+ * Retrieve supported hardware configurations for a codec.
+ *
+ * Values of index from zero to some maximum return the indexed configuration
+ * descriptor; all other values return NULL. If the codec does not support
+ * any hardware configurations then it will always return NULL.
+ */
+const AVCodecHWConfig *avcodec_get_hw_config(const AVCodec *codec, int index);
+
+/**
+ * @defgroup lavc_hwaccel AVHWAccel
+ *
+ * @note Nothing in this structure should be accessed by the user. At some
+ * point in future it will not be externally visible at all.
+ *
+ * @{
+ */
+typedef struct AVHWAccel {
+ /**
+ * Name of the hardware accelerated codec.
+ * The name is globally unique among encoders and among decoders (but an
+ * encoder and a decoder can share the same name).
+ */
+ const char *name;
+
+ /**
+ * Type of codec implemented by the hardware accelerator.
+ *
+ * See AVMEDIA_TYPE_xxx
+ */
+ enum AVMediaType type;
+
+ /**
+ * Codec implemented by the hardware accelerator.
+ *
+ * See AV_CODEC_ID_xxx
+ */
+ enum AVCodecID id;
+
+ /**
+ * Supported pixel format.
+ *
+ * Only hardware accelerated formats are supported here.
+ */
+ enum AVPixelFormat pix_fmt;
+
+ /**
+ * Hardware accelerated codec capabilities.
+ * see AV_HWACCEL_CODEC_CAP_*
+ */
+ int capabilities;
+
+ /*****************************************************************
+ * No fields below this line are part of the public API. They
+ * may not be used outside of libavcodec and can be changed and
+ * removed at will.
+ * New public fields should be added right above.
+ *****************************************************************
+ */
+
+ /**
+ * Allocate a custom buffer
+ */
+ int (*alloc_frame)(AVCodecContext *avctx, AVFrame *frame);
+
+ /**
+ * Called at the beginning of each frame or field picture.
+ *
+ * Meaningful frame information (codec specific) is guaranteed to
+ * be parsed at this point. This function is mandatory.
+ *
+ * Note that buf can be NULL along with buf_size set to 0.
+ * Otherwise, this means the whole frame is available at this point.
+ *
+ * @param avctx the codec context
+ * @param buf the frame data buffer base
+ * @param buf_size the size of the frame in bytes
+ * @return zero if successful, a negative value otherwise
+ */
+ int (*start_frame)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size);
+
+ /**
+ * Callback for parameter data (SPS/PPS/VPS etc).
+ *
+ * Useful for hardware decoders which keep persistent state about the
+ * video parameters, and need to receive any changes to update that state.
+ *
+ * @param avctx the codec context
+ * @param type the nal unit type
+ * @param buf the nal unit data buffer
+ * @param buf_size the size of the nal unit in bytes
+ * @return zero if successful, a negative value otherwise
+ */
+ int (*decode_params)(AVCodecContext *avctx, int type, const uint8_t *buf, uint32_t buf_size);
+
+ /**
+ * Callback for each slice.
+ *
+ * Meaningful slice information (codec specific) is guaranteed to
+ * be parsed at this point. This function is mandatory.
+ * The only exception is XvMC, that works on MB level.
+ *
+ * @param avctx the codec context
+ * @param buf the slice data buffer base
+ * @param buf_size the size of the slice in bytes
+ * @return zero if successful, a negative value otherwise
+ */
+ int (*decode_slice)(AVCodecContext *avctx, const uint8_t *buf, uint32_t buf_size);
+
+ /**
+ * Called at the end of each frame or field picture.
+ *
+ * The whole picture is parsed at this point and can now be sent
+ * to the hardware accelerator. This function is mandatory.
+ *
+ * @param avctx the codec context
+ * @return zero if successful, a negative value otherwise
+ */
+ int (*end_frame)(AVCodecContext *avctx);
+
+ /**
+ * Size of per-frame hardware accelerator private data.
+ *
+ * Private data is allocated with av_mallocz() before
+ * AVCodecContext.get_buffer() and deallocated after
+ * AVCodecContext.release_buffer().
+ */
+ int frame_priv_data_size;
+
+ /**
+ * Called for every Macroblock in a slice.
+ *
+ * XvMC uses it to replace the ff_mpv_reconstruct_mb().
+ * Instead of decoding to raw picture, MB parameters are
+ * stored in an array provided by the video driver.
+ *
+ * @param s the mpeg context
+ */
+ void (*decode_mb)(struct MpegEncContext *s);
+
+ /**
+ * Initialize the hwaccel private data.
+ *
+ * This will be called from ff_get_format(), after hwaccel and
+ * hwaccel_context are set and the hwaccel private data in AVCodecInternal
+ * is allocated.
+ */
+ int (*init)(AVCodecContext *avctx);
+
+ /**
+ * Uninitialize the hwaccel private data.
+ *
+ * This will be called from get_format() or avcodec_close(), after hwaccel
+ * and hwaccel_context are already uninitialized.
+ */
+ int (*uninit)(AVCodecContext *avctx);
+
+ /**
+ * Size of the private data to allocate in
+ * AVCodecInternal.hwaccel_priv_data.
+ */
+ int priv_data_size;
+
+ /**
+ * Internal hwaccel capabilities.
+ */
+ int caps_internal;
+
+ /**
+ * Fill the given hw_frames context with current codec parameters. Called
+ * from get_format. Refer to avcodec_get_hw_frames_parameters() for
+ * details.
+ *
+ * This CAN be called before AVHWAccel.init is called, and you must assume
+ * that avctx->hwaccel_priv_data is invalid.
+ */
+ int (*frame_params)(AVCodecContext *avctx, AVBufferRef *hw_frames_ctx);
+} AVHWAccel;
+
+/**
+ * HWAccel is experimental and is thus avoided in favor of non experimental
+ * codecs
+ */
+#define AV_HWACCEL_CODEC_CAP_EXPERIMENTAL 0x0200
+
+/**
+ * Hardware acceleration should be used for decoding even if the codec level
+ * used is unknown or higher than the maximum supported level reported by the
+ * hardware driver.
+ *
+ * It's generally a good idea to pass this flag unless you have a specific
+ * reason not to, as hardware tends to under-report supported levels.
+ */
+#define AV_HWACCEL_FLAG_IGNORE_LEVEL (1 << 0)
+
+/**
+ * Hardware acceleration can output YUV pixel formats with a different chroma
+ * sampling than 4:2:0 and/or other than 8 bits per component.
+ */
+#define AV_HWACCEL_FLAG_ALLOW_HIGH_DEPTH (1 << 1)
+
+/**
+ * Hardware acceleration should still be attempted for decoding when the
+ * codec profile does not match the reported capabilities of the hardware.
+ *
+ * For example, this can be used to try to decode baseline profile H.264
+ * streams in hardware - it will often succeed, because many streams marked
+ * as baseline profile actually conform to constrained baseline profile.
+ *
+ * @warning If the stream is actually not supported then the behaviour is
+ * undefined, and may include returning entirely incorrect output
+ * while indicating success.
+ */
+#define AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH (1 << 2)
+
+/**
+ * @}
+ */
+
+#if FF_API_AVPICTURE
+/**
+ * @defgroup lavc_picture AVPicture
+ *
+ * Functions for working with AVPicture
+ * @{
+ */
+
+/**
+ * Picture data structure.
+ *
+ * Up to four components can be stored into it, the last component is
+ * alpha.
+ * @deprecated use AVFrame or imgutils functions instead
+ */
+typedef struct AVPicture {
+ attribute_deprecated
+ uint8_t *data[AV_NUM_DATA_POINTERS]; ///< pointers to the image data planes
+ attribute_deprecated
+ int linesize[AV_NUM_DATA_POINTERS]; ///< number of bytes per line
+} AVPicture;
+
+/**
+ * @}
+ */
+#endif
+
+enum AVSubtitleType {
+ SUBTITLE_NONE,
+
+ SUBTITLE_BITMAP, ///< A bitmap, pict will be set
+
+ /**
+ * Plain text, the text field must be set by the decoder and is
+ * authoritative. ass and pict fields may contain approximations.
+ */
+ SUBTITLE_TEXT,
+
+ /**
+ * Formatted text, the ass field must be set by the decoder and is
+ * authoritative. pict and text fields may contain approximations.
+ */
+ SUBTITLE_ASS,
+};
+
+#define AV_SUBTITLE_FLAG_FORCED 0x00000001
+
+typedef struct AVSubtitleRect {
+ int x; ///< top left corner of pict, undefined when pict is not set
+ int y; ///< top left corner of pict, undefined when pict is not set
+ int w; ///< width of pict, undefined when pict is not set
+ int h; ///< height of pict, undefined when pict is not set
+ int nb_colors; ///< number of colors in pict, undefined when pict is not set
+
+#if FF_API_AVPICTURE
+ /**
+ * @deprecated unused
+ */
+ attribute_deprecated
+ AVPicture pict;
+#endif
+ /**
+ * data+linesize for the bitmap of this subtitle.
+ * Can be set for text/ass as well once they are rendered.
+ */
+ uint8_t *data[4];
+ int linesize[4];
+
+ enum AVSubtitleType type;
+
+ char *text; ///< 0 terminated plain UTF-8 text
+
+ /**
+ * 0 terminated ASS/SSA compatible event line.
+ * The presentation of this is unaffected by the other values in this
+ * struct.
+ */
+ char *ass;
+
+ int flags;
+} AVSubtitleRect;
+
+typedef struct AVSubtitle {
+ uint16_t format; /* 0 = graphics */
+ uint32_t start_display_time; /* relative to packet pts, in ms */
+ uint32_t end_display_time; /* relative to packet pts, in ms */
+ unsigned num_rects;
+ AVSubtitleRect **rects;
+ int64_t pts; ///< Same as packet pts, in AV_TIME_BASE
+} AVSubtitle;
+
+/**
+ * This struct describes the properties of an encoded stream.
+ *
+ * sizeof(AVCodecParameters) is not a part of the public ABI, this struct must
+ * be allocated with avcodec_parameters_alloc() and freed with
+ * avcodec_parameters_free().
+ */
+typedef struct AVCodecParameters {
+ /**
+ * General type of the encoded data.
+ */
+ enum AVMediaType codec_type;
+ /**
+ * Specific type of the encoded data (the codec used).
+ */
+ enum AVCodecID codec_id;
+ /**
+ * Additional information about the codec (corresponds to the AVI FOURCC).
+ */
+ uint32_t codec_tag;
+
+ /**
+ * Extra binary data needed for initializing the decoder, codec-dependent.
+ *
+ * Must be allocated with av_malloc() and will be freed by
+ * avcodec_parameters_free(). The allocated size of extradata must be at
+ * least extradata_size + AV_INPUT_BUFFER_PADDING_SIZE, with the padding
+ * bytes zeroed.
+ */
+ uint8_t *extradata;
+ /**
+ * Size of the extradata content in bytes.
+ */
+ int extradata_size;
+
+ /**
+ * - video: the pixel format, the value corresponds to enum AVPixelFormat.
+ * - audio: the sample format, the value corresponds to enum AVSampleFormat.
+ */
+ int format;
+
+ /**
+ * The average bitrate of the encoded data (in bits per second).
+ */
+ int64_t bit_rate;
+
+ /**
+ * The number of bits per sample in the codedwords.
+ *
+ * This is basically the bitrate per sample. It is mandatory for a bunch of
+ * formats to actually decode them. It's the number of bits for one sample in
+ * the actual coded bitstream.
+ *
+ * This could be for example 4 for ADPCM
+ * For PCM formats this matches bits_per_raw_sample
+ * Can be 0
+ */
+ int bits_per_coded_sample;
+
+ /**
+ * This is the number of valid bits in each output sample. If the
+ * sample format has more bits, the least significant bits are additional
+ * padding bits, which are always 0. Use right shifts to reduce the sample
+ * to its actual size. For example, audio formats with 24 bit samples will
+ * have bits_per_raw_sample set to 24, and format set to AV_SAMPLE_FMT_S32.
+ * To get the original sample use "(int32_t)sample >> 8"."
+ *
+ * For ADPCM this might be 12 or 16 or similar
+ * Can be 0
+ */
+ int bits_per_raw_sample;
+
+ /**
+ * Codec-specific bitstream restrictions that the stream conforms to.
+ */
+ int profile;
+ int level;
+
+ /**
+ * Video only. The dimensions of the video frame in pixels.
+ */
+ int width;
+ int height;
+
+ /**
+ * Video only. The aspect ratio (width / height) which a single pixel
+ * should have when displayed.
+ *
+ * When the aspect ratio is unknown / undefined, the numerator should be
+ * set to 0 (the denominator may have any value).
+ */
+ AVRational sample_aspect_ratio;
+
+ /**
+ * Video only. The order of the fields in interlaced video.
+ */
+ enum AVFieldOrder field_order;
+
+ /**
+ * Video only. Additional colorspace characteristics.
+ */
+ enum AVColorRange color_range;
+ enum AVColorPrimaries color_primaries;
+ enum AVColorTransferCharacteristic color_trc;
+ enum AVColorSpace color_space;
+ enum AVChromaLocation chroma_location;
+
+ /**
+ * Video only. Number of delayed frames.
+ */
+ int video_delay;
+
+ /**
+ * Audio only. The channel layout bitmask. May be 0 if the channel layout is
+ * unknown or unspecified, otherwise the number of bits set must be equal to
+ * the channels field.
+ */
+ uint64_t channel_layout;
+ /**
+ * Audio only. The number of audio channels.
+ */
+ int channels;
+ /**
+ * Audio only. The number of audio samples per second.
+ */
+ int sample_rate;
+ /**
+ * Audio only. The number of bytes per coded audio frame, required by some
+ * formats.
+ *
+ * Corresponds to nBlockAlign in WAVEFORMATEX.
+ */
+ int block_align;
+ /**
+ * Audio only. Audio frame size, if known. Required by some formats to be static.
+ */
+ int frame_size;
+
+ /**
+ * Audio only. The amount of padding (in samples) inserted by the encoder at
+ * the beginning of the audio. I.e. this number of leading decoded samples
+ * must be discarded by the caller to get the original audio without leading
+ * padding.
+ */
+ int initial_padding;
+ /**
+ * Audio only. The amount of padding (in samples) appended by the encoder to
+ * the end of the audio. I.e. this number of decoded samples must be
+ * discarded by the caller from the end of the stream to get the original
+ * audio without any trailing padding.
+ */
+ int trailing_padding;
+ /**
+ * Audio only. Number of samples to skip after a discontinuity.
+ */
+ int seek_preroll;
+} AVCodecParameters;
+
+/**
+ * Iterate over all registered codecs.
+ *
+ * @param opaque a pointer where libavcodec will store the iteration state. Must
+ * point to NULL to start the iteration.
+ *
+ * @return the next registered codec or NULL when the iteration is
+ * finished
+ */
+const AVCodec *av_codec_iterate(void **opaque);
+
+#if FF_API_NEXT
+/**
+ * If c is NULL, returns the first registered codec,
+ * if c is non-NULL, returns the next registered codec after c,
+ * or NULL if c is the last one.
+ */
+attribute_deprecated
+AVCodec *av_codec_next(const AVCodec *c);
+#endif
+
+/**
+ * Return the LIBAVCODEC_VERSION_INT constant.
+ */
+unsigned avcodec_version(void);
+
+/**
+ * Return the libavcodec build-time configuration.
+ */
+const char *avcodec_configuration(void);
+
+/**
+ * Return the libavcodec license.
+ */
+const char *avcodec_license(void);
+
+#if FF_API_NEXT
+/**
+ * Register the codec codec and initialize libavcodec.
+ *
+ * @warning either this function or avcodec_register_all() must be called
+ * before any other libavcodec functions.
+ *
+ * @see avcodec_register_all()
+ */
+attribute_deprecated
+void avcodec_register(AVCodec *codec);
+
+/**
+ * Register all the codecs, parsers and bitstream filters which were enabled at
+ * configuration time. If you do not call this function you can select exactly
+ * which formats you want to support, by using the individual registration
+ * functions.
+ *
+ * @see avcodec_register
+ * @see av_register_codec_parser
+ * @see av_register_bitstream_filter
+ */
+attribute_deprecated
+void avcodec_register_all(void);
+#endif
+
+/**
+ * Allocate an AVCodecContext and set its fields to default values. The
+ * resulting struct should be freed with avcodec_free_context().
+ *
+ * @param codec if non-NULL, allocate private data and initialize defaults
+ * for the given codec. It is illegal to then call avcodec_open2()
+ * with a different codec.
+ * If NULL, then the codec-specific defaults won't be initialized,
+ * which may result in suboptimal default settings (this is
+ * important mainly for encoders, e.g. libx264).
+ *
+ * @return An AVCodecContext filled with default values or NULL on failure.
+ */
+AVCodecContext *avcodec_alloc_context3(const AVCodec *codec);
+
+/**
+ * Free the codec context and everything associated with it and write NULL to
+ * the provided pointer.
+ */
+void avcodec_free_context(AVCodecContext **avctx);
+
+#if FF_API_GET_CONTEXT_DEFAULTS
+/**
+ * @deprecated This function should not be used, as closing and opening a codec
+ * context multiple time is not supported. A new codec context should be
+ * allocated for each new use.
+ */
+int avcodec_get_context_defaults3(AVCodecContext *s, const AVCodec *codec);
+#endif
+
+/**
+ * Get the AVClass for AVCodecContext. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avcodec_get_class(void);
+
+#if FF_API_COPY_CONTEXT
+/**
+ * Get the AVClass for AVFrame. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avcodec_get_frame_class(void);
+
+/**
+ * Get the AVClass for AVSubtitleRect. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *avcodec_get_subtitle_rect_class(void);
+
+/**
+ * Copy the settings of the source AVCodecContext into the destination
+ * AVCodecContext. The resulting destination codec context will be
+ * unopened, i.e. you are required to call avcodec_open2() before you
+ * can use this AVCodecContext to decode/encode video/audio data.
+ *
+ * @param dest target codec context, should be initialized with
+ * avcodec_alloc_context3(NULL), but otherwise uninitialized
+ * @param src source codec context
+ * @return AVERROR() on error (e.g. memory allocation error), 0 on success
+ *
+ * @deprecated The semantics of this function are ill-defined and it should not
+ * be used. If you need to transfer the stream parameters from one codec context
+ * to another, use an intermediate AVCodecParameters instance and the
+ * avcodec_parameters_from_context() / avcodec_parameters_to_context()
+ * functions.
+ */
+attribute_deprecated
+int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src);
+#endif
+
+/**
+ * Allocate a new AVCodecParameters and set its fields to default values
+ * (unknown/invalid/0). The returned struct must be freed with
+ * avcodec_parameters_free().
+ */
+AVCodecParameters *avcodec_parameters_alloc(void);
+
+/**
+ * Free an AVCodecParameters instance and everything associated with it and
+ * write NULL to the supplied pointer.
+ */
+void avcodec_parameters_free(AVCodecParameters **par);
+
+/**
+ * Copy the contents of src to dst. Any allocated fields in dst are freed and
+ * replaced with newly allocated duplicates of the corresponding fields in src.
+ *
+ * @return >= 0 on success, a negative AVERROR code on failure.
+ */
+int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src);
+
+/**
+ * Fill the parameters struct based on the values from the supplied codec
+ * context. Any allocated fields in par are freed and replaced with duplicates
+ * of the corresponding fields in codec.
+ *
+ * @return >= 0 on success, a negative AVERROR code on failure
+ */
+int avcodec_parameters_from_context(AVCodecParameters *par,
+ const AVCodecContext *codec);
+
+/**
+ * Fill the codec context based on the values from the supplied codec
+ * parameters. Any allocated fields in codec that have a corresponding field in
+ * par are freed and replaced with duplicates of the corresponding field in par.
+ * Fields in codec that do not have a counterpart in par are not touched.
+ *
+ * @return >= 0 on success, a negative AVERROR code on failure.
+ */
+int avcodec_parameters_to_context(AVCodecContext *codec,
+ const AVCodecParameters *par);
+
+/**
+ * Initialize the AVCodecContext to use the given AVCodec. Prior to using this
+ * function the context has to be allocated with avcodec_alloc_context3().
+ *
+ * The functions avcodec_find_decoder_by_name(), avcodec_find_encoder_by_name(),
+ * avcodec_find_decoder() and avcodec_find_encoder() provide an easy way for
+ * retrieving a codec.
+ *
+ * @warning This function is not thread safe!
+ *
+ * @note Always call this function before using decoding routines (such as
+ * @ref avcodec_receive_frame()).
+ *
+ * @code
+ * avcodec_register_all();
+ * av_dict_set(&opts, "b", "2.5M", 0);
+ * codec = avcodec_find_decoder(AV_CODEC_ID_H264);
+ * if (!codec)
+ * exit(1);
+ *
+ * context = avcodec_alloc_context3(codec);
+ *
+ * if (avcodec_open2(context, codec, opts) < 0)
+ * exit(1);
+ * @endcode
+ *
+ * @param avctx The context to initialize.
+ * @param codec The codec to open this context for. If a non-NULL codec has been
+ * previously passed to avcodec_alloc_context3() or
+ * for this context, then this parameter MUST be either NULL or
+ * equal to the previously passed codec.
+ * @param options A dictionary filled with AVCodecContext and codec-private options.
+ * On return this object will be filled with options that were not found.
+ *
+ * @return zero on success, a negative value on error
+ * @see avcodec_alloc_context3(), avcodec_find_decoder(), avcodec_find_encoder(),
+ * av_dict_set(), av_opt_find().
+ */
+int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options);
+
+/**
+ * Close a given AVCodecContext and free all the data associated with it
+ * (but not the AVCodecContext itself).
+ *
+ * Calling this function on an AVCodecContext that hasn't been opened will free
+ * the codec-specific data allocated in avcodec_alloc_context3() with a non-NULL
+ * codec. Subsequent calls will do nothing.
+ *
+ * @note Do not use this function. Use avcodec_free_context() to destroy a
+ * codec context (either open or closed). Opening and closing a codec context
+ * multiple times is not supported anymore -- use multiple codec contexts
+ * instead.
+ */
+int avcodec_close(AVCodecContext *avctx);
+
+/**
+ * Free all allocated data in the given subtitle struct.
+ *
+ * @param sub AVSubtitle to free.
+ */
+void avsubtitle_free(AVSubtitle *sub);
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavc_packet
+ * @{
+ */
+
+/**
+ * Allocate an AVPacket and set its fields to default values. The resulting
+ * struct must be freed using av_packet_free().
+ *
+ * @return An AVPacket filled with default values or NULL on failure.
+ *
+ * @note this only allocates the AVPacket itself, not the data buffers. Those
+ * must be allocated through other means such as av_new_packet.
+ *
+ * @see av_new_packet
+ */
+AVPacket *av_packet_alloc(void);
+
+/**
+ * Create a new packet that references the same data as src.
+ *
+ * This is a shortcut for av_packet_alloc()+av_packet_ref().
+ *
+ * @return newly created AVPacket on success, NULL on error.
+ *
+ * @see av_packet_alloc
+ * @see av_packet_ref
+ */
+AVPacket *av_packet_clone(const AVPacket *src);
+
+/**
+ * Free the packet, if the packet is reference counted, it will be
+ * unreferenced first.
+ *
+ * @param pkt packet to be freed. The pointer will be set to NULL.
+ * @note passing NULL is a no-op.
+ */
+void av_packet_free(AVPacket **pkt);
+
+/**
+ * Initialize optional fields of a packet with default values.
+ *
+ * Note, this does not touch the data and size members, which have to be
+ * initialized separately.
+ *
+ * @param pkt packet
+ */
+void av_init_packet(AVPacket *pkt);
+
+/**
+ * Allocate the payload of a packet and initialize its fields with
+ * default values.
+ *
+ * @param pkt packet
+ * @param size wanted payload size
+ * @return 0 if OK, AVERROR_xxx otherwise
+ */
+int av_new_packet(AVPacket *pkt, int size);
+
+/**
+ * Reduce packet size, correctly zeroing padding
+ *
+ * @param pkt packet
+ * @param size new size
+ */
+void av_shrink_packet(AVPacket *pkt, int size);
+
+/**
+ * Increase packet size, correctly zeroing padding
+ *
+ * @param pkt packet
+ * @param grow_by number of bytes by which to increase the size of the packet
+ */
+int av_grow_packet(AVPacket *pkt, int grow_by);
+
+/**
+ * Initialize a reference-counted packet from av_malloc()ed data.
+ *
+ * @param pkt packet to be initialized. This function will set the data, size,
+ * buf and destruct fields, all others are left untouched.
+ * @param data Data allocated by av_malloc() to be used as packet data. If this
+ * function returns successfully, the data is owned by the underlying AVBuffer.
+ * The caller may not access the data through other means.
+ * @param size size of data in bytes, without the padding. I.e. the full buffer
+ * size is assumed to be size + AV_INPUT_BUFFER_PADDING_SIZE.
+ *
+ * @return 0 on success, a negative AVERROR on error
+ */
+int av_packet_from_data(AVPacket *pkt, uint8_t *data, int size);
+
+#if FF_API_AVPACKET_OLD_API
+/**
+ * @warning This is a hack - the packet memory allocation stuff is broken. The
+ * packet is allocated if it was not really allocated.
+ *
+ * @deprecated Use av_packet_ref or av_packet_make_refcounted
+ */
+attribute_deprecated
+int av_dup_packet(AVPacket *pkt);
+/**
+ * Copy packet, including contents
+ *
+ * @return 0 on success, negative AVERROR on fail
+ *
+ * @deprecated Use av_packet_ref
+ */
+attribute_deprecated
+int av_copy_packet(AVPacket *dst, const AVPacket *src);
+
+/**
+ * Copy packet side data
+ *
+ * @return 0 on success, negative AVERROR on fail
+ *
+ * @deprecated Use av_packet_copy_props
+ */
+attribute_deprecated
+int av_copy_packet_side_data(AVPacket *dst, const AVPacket *src);
+
+/**
+ * Free a packet.
+ *
+ * @deprecated Use av_packet_unref
+ *
+ * @param pkt packet to free
+ */
+attribute_deprecated
+void av_free_packet(AVPacket *pkt);
+#endif
+/**
+ * Allocate new information of a packet.
+ *
+ * @param pkt packet
+ * @param type side information type
+ * @param size side information size
+ * @return pointer to fresh allocated data or NULL otherwise
+ */
+uint8_t* av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+ int size);
+
+/**
+ * Wrap an existing array as a packet side data.
+ *
+ * @param pkt packet
+ * @param type side information type
+ * @param data the side data array. It must be allocated with the av_malloc()
+ * family of functions. The ownership of the data is transferred to
+ * pkt.
+ * @param size side information size
+ * @return a non-negative number on success, a negative AVERROR code on
+ * failure. On failure, the packet is unchanged and the data remains
+ * owned by the caller.
+ */
+int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+ uint8_t *data, size_t size);
+
+/**
+ * Shrink the already allocated side data buffer
+ *
+ * @param pkt packet
+ * @param type side information type
+ * @param size new side information size
+ * @return 0 on success, < 0 on failure
+ */
+int av_packet_shrink_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+ int size);
+
+/**
+ * Get side information from packet.
+ *
+ * @param pkt packet
+ * @param type desired side information type
+ * @param size pointer for side information size to store (optional)
+ * @return pointer to data if present or NULL otherwise
+ */
+uint8_t* av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type,
+ int *size);
+
+#if FF_API_MERGE_SD_API
+attribute_deprecated
+int av_packet_merge_side_data(AVPacket *pkt);
+
+attribute_deprecated
+int av_packet_split_side_data(AVPacket *pkt);
+#endif
+
+const char *av_packet_side_data_name(enum AVPacketSideDataType type);
+
+/**
+ * Pack a dictionary for use in side_data.
+ *
+ * @param dict The dictionary to pack.
+ * @param size pointer to store the size of the returned data
+ * @return pointer to data if successful, NULL otherwise
+ */
+uint8_t *av_packet_pack_dictionary(AVDictionary *dict, int *size);
+/**
+ * Unpack a dictionary from side_data.
+ *
+ * @param data data from side_data
+ * @param size size of the data
+ * @param dict the metadata storage dictionary
+ * @return 0 on success, < 0 on failure
+ */
+int av_packet_unpack_dictionary(const uint8_t *data, int size, AVDictionary **dict);
+
+
+/**
+ * Convenience function to free all the side data stored.
+ * All the other fields stay untouched.
+ *
+ * @param pkt packet
+ */
+void av_packet_free_side_data(AVPacket *pkt);
+
+/**
+ * Setup a new reference to the data described by a given packet
+ *
+ * If src is reference-counted, setup dst as a new reference to the
+ * buffer in src. Otherwise allocate a new buffer in dst and copy the
+ * data from src into it.
+ *
+ * All the other fields are copied from src.
+ *
+ * @see av_packet_unref
+ *
+ * @param dst Destination packet
+ * @param src Source packet
+ *
+ * @return 0 on success, a negative AVERROR on error.
+ */
+int av_packet_ref(AVPacket *dst, const AVPacket *src);
+
+/**
+ * Wipe the packet.
+ *
+ * Unreference the buffer referenced by the packet and reset the
+ * remaining packet fields to their default values.
+ *
+ * @param pkt The packet to be unreferenced.
+ */
+void av_packet_unref(AVPacket *pkt);
+
+/**
+ * Move every field in src to dst and reset src.
+ *
+ * @see av_packet_unref
+ *
+ * @param src Source packet, will be reset
+ * @param dst Destination packet
+ */
+void av_packet_move_ref(AVPacket *dst, AVPacket *src);
+
+/**
+ * Copy only "properties" fields from src to dst.
+ *
+ * Properties for the purpose of this function are all the fields
+ * beside those related to the packet data (buf, data, size)
+ *
+ * @param dst Destination packet
+ * @param src Source packet
+ *
+ * @return 0 on success AVERROR on failure.
+ */
+int av_packet_copy_props(AVPacket *dst, const AVPacket *src);
+
+/**
+ * Ensure the data described by a given packet is reference counted.
+ *
+ * @note This function does not ensure that the reference will be writable.
+ * Use av_packet_make_writable instead for that purpose.
+ *
+ * @see av_packet_ref
+ * @see av_packet_make_writable
+ *
+ * @param pkt packet whose data should be made reference counted.
+ *
+ * @return 0 on success, a negative AVERROR on error. On failure, the
+ * packet is unchanged.
+ */
+int av_packet_make_refcounted(AVPacket *pkt);
+
+/**
+ * Create a writable reference for the data described by a given packet,
+ * avoiding data copy if possible.
+ *
+ * @param pkt Packet whose data should be made writable.
+ *
+ * @return 0 on success, a negative AVERROR on failure. On failure, the
+ * packet is unchanged.
+ */
+int av_packet_make_writable(AVPacket *pkt);
+
+/**
+ * Convert valid timing fields (timestamps / durations) in a packet from one
+ * timebase to another. Timestamps with unknown values (AV_NOPTS_VALUE) will be
+ * ignored.
+ *
+ * @param pkt packet on which the conversion will be performed
+ * @param tb_src source timebase, in which the timing fields in pkt are
+ * expressed
+ * @param tb_dst destination timebase, to which the timing fields will be
+ * converted
+ */
+void av_packet_rescale_ts(AVPacket *pkt, AVRational tb_src, AVRational tb_dst);
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavc_decoding
+ * @{
+ */
+
+/**
+ * Find a registered decoder with a matching codec ID.
+ *
+ * @param id AVCodecID of the requested decoder
+ * @return A decoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_decoder(enum AVCodecID id);
+
+/**
+ * Find a registered decoder with the specified name.
+ *
+ * @param name name of the requested decoder
+ * @return A decoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_decoder_by_name(const char *name);
+
+/**
+ * The default callback for AVCodecContext.get_buffer2(). It is made public so
+ * it can be called by custom get_buffer2() implementations for decoders without
+ * AV_CODEC_CAP_DR1 set.
+ */
+int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags);
+
+/**
+ * Modify width and height values so that they will result in a memory
+ * buffer that is acceptable for the codec if you do not use any horizontal
+ * padding.
+ *
+ * May only be used if a codec with AV_CODEC_CAP_DR1 has been opened.
+ */
+void avcodec_align_dimensions(AVCodecContext *s, int *width, int *height);
+
+/**
+ * Modify width and height values so that they will result in a memory
+ * buffer that is acceptable for the codec if you also ensure that all
+ * line sizes are a multiple of the respective linesize_align[i].
+ *
+ * May only be used if a codec with AV_CODEC_CAP_DR1 has been opened.
+ */
+void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
+ int linesize_align[AV_NUM_DATA_POINTERS]);
+
+/**
+ * Converts AVChromaLocation to swscale x/y chroma position.
+ *
+ * The positions represent the chroma (0,0) position in a coordinates system
+ * with luma (0,0) representing the origin and luma(1,1) representing 256,256
+ *
+ * @param xpos horizontal chroma sample position
+ * @param ypos vertical chroma sample position
+ */
+int avcodec_enum_to_chroma_pos(int *xpos, int *ypos, enum AVChromaLocation pos);
+
+/**
+ * Converts swscale x/y chroma position to AVChromaLocation.
+ *
+ * The positions represent the chroma (0,0) position in a coordinates system
+ * with luma (0,0) representing the origin and luma(1,1) representing 256,256
+ *
+ * @param xpos horizontal chroma sample position
+ * @param ypos vertical chroma sample position
+ */
+enum AVChromaLocation avcodec_chroma_pos_to_enum(int xpos, int ypos);
+
+/**
+ * Decode the audio frame of size avpkt->size from avpkt->data into frame.
+ *
+ * Some decoders may support multiple frames in a single AVPacket. Such
+ * decoders would then just decode the first frame and the return value would be
+ * less than the packet size. In this case, avcodec_decode_audio4 has to be
+ * called again with an AVPacket containing the remaining data in order to
+ * decode the second frame, etc... Even if no frames are returned, the packet
+ * needs to be fed to the decoder with remaining data until it is completely
+ * consumed or an error occurs.
+ *
+ * Some decoders (those marked with AV_CODEC_CAP_DELAY) have a delay between input
+ * and output. This means that for some packets they will not immediately
+ * produce decoded output and need to be flushed at the end of decoding to get
+ * all the decoded data. Flushing is done by calling this function with packets
+ * with avpkt->data set to NULL and avpkt->size set to 0 until it stops
+ * returning samples. It is safe to flush even those decoders that are not
+ * marked with AV_CODEC_CAP_DELAY, then no samples will be returned.
+ *
+ * @warning The input buffer, avpkt->data must be AV_INPUT_BUFFER_PADDING_SIZE
+ * larger than the actual read bytes because some optimized bitstream
+ * readers read 32 or 64 bits at once and could read over the end.
+ *
+ * @note The AVCodecContext MUST have been opened with @ref avcodec_open2()
+ * before packets may be fed to the decoder.
+ *
+ * @param avctx the codec context
+ * @param[out] frame The AVFrame in which to store decoded audio samples.
+ * The decoder will allocate a buffer for the decoded frame by
+ * calling the AVCodecContext.get_buffer2() callback.
+ * When AVCodecContext.refcounted_frames is set to 1, the frame is
+ * reference counted and the returned reference belongs to the
+ * caller. The caller must release the frame using av_frame_unref()
+ * when the frame is no longer needed. The caller may safely write
+ * to the frame if av_frame_is_writable() returns 1.
+ * When AVCodecContext.refcounted_frames is set to 0, the returned
+ * reference belongs to the decoder and is valid only until the
+ * next call to this function or until closing or flushing the
+ * decoder. The caller may not write to it.
+ * @param[out] got_frame_ptr Zero if no frame could be decoded, otherwise it is
+ * non-zero. Note that this field being set to zero
+ * does not mean that an error has occurred. For
+ * decoders with AV_CODEC_CAP_DELAY set, no given decode
+ * call is guaranteed to produce a frame.
+ * @param[in] avpkt The input AVPacket containing the input buffer.
+ * At least avpkt->data and avpkt->size should be set. Some
+ * decoders might also require additional fields to be set.
+ * @return A negative error code is returned if an error occurred during
+ * decoding, otherwise the number of bytes consumed from the input
+ * AVPacket is returned.
+ *
+* @deprecated Use avcodec_send_packet() and avcodec_receive_frame().
+ */
+attribute_deprecated
+int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame,
+ int *got_frame_ptr, const AVPacket *avpkt);
+
+/**
+ * Decode the video frame of size avpkt->size from avpkt->data into picture.
+ * Some decoders may support multiple frames in a single AVPacket, such
+ * decoders would then just decode the first frame.
+ *
+ * @warning The input buffer must be AV_INPUT_BUFFER_PADDING_SIZE larger than
+ * the actual read bytes because some optimized bitstream readers read 32 or 64
+ * bits at once and could read over the end.
+ *
+ * @warning The end of the input buffer buf should be set to 0 to ensure that
+ * no overreading happens for damaged MPEG streams.
+ *
+ * @note Codecs which have the AV_CODEC_CAP_DELAY capability set have a delay
+ * between input and output, these need to be fed with avpkt->data=NULL,
+ * avpkt->size=0 at the end to return the remaining frames.
+ *
+ * @note The AVCodecContext MUST have been opened with @ref avcodec_open2()
+ * before packets may be fed to the decoder.
+ *
+ * @param avctx the codec context
+ * @param[out] picture The AVFrame in which the decoded video frame will be stored.
+ * Use av_frame_alloc() to get an AVFrame. The codec will
+ * allocate memory for the actual bitmap by calling the
+ * AVCodecContext.get_buffer2() callback.
+ * When AVCodecContext.refcounted_frames is set to 1, the frame is
+ * reference counted and the returned reference belongs to the
+ * caller. The caller must release the frame using av_frame_unref()
+ * when the frame is no longer needed. The caller may safely write
+ * to the frame if av_frame_is_writable() returns 1.
+ * When AVCodecContext.refcounted_frames is set to 0, the returned
+ * reference belongs to the decoder and is valid only until the
+ * next call to this function or until closing or flushing the
+ * decoder. The caller may not write to it.
+ *
+ * @param[in] avpkt The input AVPacket containing the input buffer.
+ * You can create such packet with av_init_packet() and by then setting
+ * data and size, some decoders might in addition need other fields like
+ * flags&AV_PKT_FLAG_KEY. All decoders are designed to use the least
+ * fields possible.
+ * @param[in,out] got_picture_ptr Zero if no frame could be decompressed, otherwise, it is nonzero.
+ * @return On error a negative value is returned, otherwise the number of bytes
+ * used or zero if no frame could be decompressed.
+ *
+ * @deprecated Use avcodec_send_packet() and avcodec_receive_frame().
+ */
+attribute_deprecated
+int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
+ int *got_picture_ptr,
+ const AVPacket *avpkt);
+
+/**
+ * Decode a subtitle message.
+ * Return a negative value on error, otherwise return the number of bytes used.
+ * If no subtitle could be decompressed, got_sub_ptr is zero.
+ * Otherwise, the subtitle is stored in *sub.
+ * Note that AV_CODEC_CAP_DR1 is not available for subtitle codecs. This is for
+ * simplicity, because the performance difference is expect to be negligible
+ * and reusing a get_buffer written for video codecs would probably perform badly
+ * due to a potentially very different allocation pattern.
+ *
+ * Some decoders (those marked with AV_CODEC_CAP_DELAY) have a delay between input
+ * and output. This means that for some packets they will not immediately
+ * produce decoded output and need to be flushed at the end of decoding to get
+ * all the decoded data. Flushing is done by calling this function with packets
+ * with avpkt->data set to NULL and avpkt->size set to 0 until it stops
+ * returning subtitles. It is safe to flush even those decoders that are not
+ * marked with AV_CODEC_CAP_DELAY, then no subtitles will be returned.
+ *
+ * @note The AVCodecContext MUST have been opened with @ref avcodec_open2()
+ * before packets may be fed to the decoder.
+ *
+ * @param avctx the codec context
+ * @param[out] sub The Preallocated AVSubtitle in which the decoded subtitle will be stored,
+ * must be freed with avsubtitle_free if *got_sub_ptr is set.
+ * @param[in,out] got_sub_ptr Zero if no subtitle could be decompressed, otherwise, it is nonzero.
+ * @param[in] avpkt The input AVPacket containing the input buffer.
+ */
+int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
+ int *got_sub_ptr,
+ AVPacket *avpkt);
+
+/**
+ * Supply raw packet data as input to a decoder.
+ *
+ * Internally, this call will copy relevant AVCodecContext fields, which can
+ * influence decoding per-packet, and apply them when the packet is actually
+ * decoded. (For example AVCodecContext.skip_frame, which might direct the
+ * decoder to drop the frame contained by the packet sent with this function.)
+ *
+ * @warning The input buffer, avpkt->data must be AV_INPUT_BUFFER_PADDING_SIZE
+ * larger than the actual read bytes because some optimized bitstream
+ * readers read 32 or 64 bits at once and could read over the end.
+ *
+ * @warning Do not mix this API with the legacy API (like avcodec_decode_video2())
+ * on the same AVCodecContext. It will return unexpected results now
+ * or in future libavcodec versions.
+ *
+ * @note The AVCodecContext MUST have been opened with @ref avcodec_open2()
+ * before packets may be fed to the decoder.
+ *
+ * @param avctx codec context
+ * @param[in] avpkt The input AVPacket. Usually, this will be a single video
+ * frame, or several complete audio frames.
+ * Ownership of the packet remains with the caller, and the
+ * decoder will not write to the packet. The decoder may create
+ * a reference to the packet data (or copy it if the packet is
+ * not reference-counted).
+ * Unlike with older APIs, the packet is always fully consumed,
+ * and if it contains multiple frames (e.g. some audio codecs),
+ * will require you to call avcodec_receive_frame() multiple
+ * times afterwards before you can send a new packet.
+ * It can be NULL (or an AVPacket with data set to NULL and
+ * size set to 0); in this case, it is considered a flush
+ * packet, which signals the end of the stream. Sending the
+ * first flush packet will return success. Subsequent ones are
+ * unnecessary and will return AVERROR_EOF. If the decoder
+ * still has frames buffered, it will return them after sending
+ * a flush packet.
+ *
+ * @return 0 on success, otherwise negative error code:
+ * AVERROR(EAGAIN): input is not accepted in the current state - user
+ * must read output with avcodec_receive_frame() (once
+ * all output is read, the packet should be resent, and
+ * the call will not fail with EAGAIN).
+ * AVERROR_EOF: the decoder has been flushed, and no new packets can
+ * be sent to it (also returned if more than 1 flush
+ * packet is sent)
+ * AVERROR(EINVAL): codec not opened, it is an encoder, or requires flush
+ * AVERROR(ENOMEM): failed to add packet to internal queue, or similar
+ * other errors: legitimate decoding errors
+ */
+int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt);
+
+/**
+ * Return decoded output data from a decoder.
+ *
+ * @param avctx codec context
+ * @param frame This will be set to a reference-counted video or audio
+ * frame (depending on the decoder type) allocated by the
+ * decoder. Note that the function will always call
+ * av_frame_unref(frame) before doing anything else.
+ *
+ * @return
+ * 0: success, a frame was returned
+ * AVERROR(EAGAIN): output is not available in this state - user must try
+ * to send new input
+ * AVERROR_EOF: the decoder has been fully flushed, and there will be
+ * no more output frames
+ * AVERROR(EINVAL): codec not opened, or it is an encoder
+ * other negative values: legitimate decoding errors
+ */
+int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame);
+
+/**
+ * Supply a raw video or audio frame to the encoder. Use avcodec_receive_packet()
+ * to retrieve buffered output packets.
+ *
+ * @param avctx codec context
+ * @param[in] frame AVFrame containing the raw audio or video frame to be encoded.
+ * Ownership of the frame remains with the caller, and the
+ * encoder will not write to the frame. The encoder may create
+ * a reference to the frame data (or copy it if the frame is
+ * not reference-counted).
+ * It can be NULL, in which case it is considered a flush
+ * packet. This signals the end of the stream. If the encoder
+ * still has packets buffered, it will return them after this
+ * call. Once flushing mode has been entered, additional flush
+ * packets are ignored, and sending frames will return
+ * AVERROR_EOF.
+ *
+ * For audio:
+ * If AV_CODEC_CAP_VARIABLE_FRAME_SIZE is set, then each frame
+ * can have any number of samples.
+ * If it is not set, frame->nb_samples must be equal to
+ * avctx->frame_size for all frames except the last.
+ * The final frame may be smaller than avctx->frame_size.
+ * @return 0 on success, otherwise negative error code:
+ * AVERROR(EAGAIN): input is not accepted in the current state - user
+ * must read output with avcodec_receive_packet() (once
+ * all output is read, the packet should be resent, and
+ * the call will not fail with EAGAIN).
+ * AVERROR_EOF: the encoder has been flushed, and no new frames can
+ * be sent to it
+ * AVERROR(EINVAL): codec not opened, refcounted_frames not set, it is a
+ * decoder, or requires flush
+ * AVERROR(ENOMEM): failed to add packet to internal queue, or similar
+ * other errors: legitimate decoding errors
+ */
+int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame);
+
+/**
+ * Read encoded data from the encoder.
+ *
+ * @param avctx codec context
+ * @param avpkt This will be set to a reference-counted packet allocated by the
+ * encoder. Note that the function will always call
+ * av_frame_unref(frame) before doing anything else.
+ * @return 0 on success, otherwise negative error code:
+ * AVERROR(EAGAIN): output is not available in the current state - user
+ * must try to send input
+ * AVERROR_EOF: the encoder has been fully flushed, and there will be
+ * no more output packets
+ * AVERROR(EINVAL): codec not opened, or it is an encoder
+ * other errors: legitimate decoding errors
+ */
+int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt);
+
+/**
+ * Create and return a AVHWFramesContext with values adequate for hardware
+ * decoding. This is meant to get called from the get_format callback, and is
+ * a helper for preparing a AVHWFramesContext for AVCodecContext.hw_frames_ctx.
+ * This API is for decoding with certain hardware acceleration modes/APIs only.
+ *
+ * The returned AVHWFramesContext is not initialized. The caller must do this
+ * with av_hwframe_ctx_init().
+ *
+ * Calling this function is not a requirement, but makes it simpler to avoid
+ * codec or hardware API specific details when manually allocating frames.
+ *
+ * Alternatively to this, an API user can set AVCodecContext.hw_device_ctx,
+ * which sets up AVCodecContext.hw_frames_ctx fully automatically, and makes
+ * it unnecessary to call this function or having to care about
+ * AVHWFramesContext initialization at all.
+ *
+ * There are a number of requirements for calling this function:
+ *
+ * - It must be called from get_format with the same avctx parameter that was
+ * passed to get_format. Calling it outside of get_format is not allowed, and
+ * can trigger undefined behavior.
+ * - The function is not always supported (see description of return values).
+ * Even if this function returns successfully, hwaccel initialization could
+ * fail later. (The degree to which implementations check whether the stream
+ * is actually supported varies. Some do this check only after the user's
+ * get_format callback returns.)
+ * - The hw_pix_fmt must be one of the choices suggested by get_format. If the
+ * user decides to use a AVHWFramesContext prepared with this API function,
+ * the user must return the same hw_pix_fmt from get_format.
+ * - The device_ref passed to this function must support the given hw_pix_fmt.
+ * - After calling this API function, it is the user's responsibility to
+ * initialize the AVHWFramesContext (returned by the out_frames_ref parameter),
+ * and to set AVCodecContext.hw_frames_ctx to it. If done, this must be done
+ * before returning from get_format (this is implied by the normal
+ * AVCodecContext.hw_frames_ctx API rules).
+ * - The AVHWFramesContext parameters may change every time time get_format is
+ * called. Also, AVCodecContext.hw_frames_ctx is reset before get_format. So
+ * you are inherently required to go through this process again on every
+ * get_format call.
+ * - It is perfectly possible to call this function without actually using
+ * the resulting AVHWFramesContext. One use-case might be trying to reuse a
+ * previously initialized AVHWFramesContext, and calling this API function
+ * only to test whether the required frame parameters have changed.
+ * - Fields that use dynamically allocated values of any kind must not be set
+ * by the user unless setting them is explicitly allowed by the documentation.
+ * If the user sets AVHWFramesContext.free and AVHWFramesContext.user_opaque,
+ * the new free callback must call the potentially set previous free callback.
+ * This API call may set any dynamically allocated fields, including the free
+ * callback.
+ *
+ * The function will set at least the following fields on AVHWFramesContext
+ * (potentially more, depending on hwaccel API):
+ *
+ * - All fields set by av_hwframe_ctx_alloc().
+ * - Set the format field to hw_pix_fmt.
+ * - Set the sw_format field to the most suited and most versatile format. (An
+ * implication is that this will prefer generic formats over opaque formats
+ * with arbitrary restrictions, if possible.)
+ * - Set the width/height fields to the coded frame size, rounded up to the
+ * API-specific minimum alignment.
+ * - Only _if_ the hwaccel requires a pre-allocated pool: set the initial_pool_size
+ * field to the number of maximum reference surfaces possible with the codec,
+ * plus 1 surface for the user to work (meaning the user can safely reference
+ * at most 1 decoded surface at a time), plus additional buffering introduced
+ * by frame threading. If the hwaccel does not require pre-allocation, the
+ * field is left to 0, and the decoder will allocate new surfaces on demand
+ * during decoding.
+ * - Possibly AVHWFramesContext.hwctx fields, depending on the underlying
+ * hardware API.
+ *
+ * Essentially, out_frames_ref returns the same as av_hwframe_ctx_alloc(), but
+ * with basic frame parameters set.
+ *
+ * The function is stateless, and does not change the AVCodecContext or the
+ * device_ref AVHWDeviceContext.
+ *
+ * @param avctx The context which is currently calling get_format, and which
+ * implicitly contains all state needed for filling the returned
+ * AVHWFramesContext properly.
+ * @param device_ref A reference to the AVHWDeviceContext describing the device
+ * which will be used by the hardware decoder.
+ * @param hw_pix_fmt The hwaccel format you are going to return from get_format.
+ * @param out_frames_ref On success, set to a reference to an _uninitialized_
+ * AVHWFramesContext, created from the given device_ref.
+ * Fields will be set to values required for decoding.
+ * Not changed if an error is returned.
+ * @return zero on success, a negative value on error. The following error codes
+ * have special semantics:
+ * AVERROR(ENOENT): the decoder does not support this functionality. Setup
+ * is always manual, or it is a decoder which does not
+ * support setting AVCodecContext.hw_frames_ctx at all,
+ * or it is a software format.
+ * AVERROR(EINVAL): it is known that hardware decoding is not supported for
+ * this configuration, or the device_ref is not supported
+ * for the hwaccel referenced by hw_pix_fmt.
+ */
+int avcodec_get_hw_frames_parameters(AVCodecContext *avctx,
+ AVBufferRef *device_ref,
+ enum AVPixelFormat hw_pix_fmt,
+ AVBufferRef **out_frames_ref);
+
+
+
+/**
+ * @defgroup lavc_parsing Frame parsing
+ * @{
+ */
+
+enum AVPictureStructure {
+ AV_PICTURE_STRUCTURE_UNKNOWN, //< unknown
+ AV_PICTURE_STRUCTURE_TOP_FIELD, //< coded as top field
+ AV_PICTURE_STRUCTURE_BOTTOM_FIELD, //< coded as bottom field
+ AV_PICTURE_STRUCTURE_FRAME, //< coded as frame
+};
+
+typedef struct AVCodecParserContext {
+ void *priv_data;
+ struct AVCodecParser *parser;
+ int64_t frame_offset; /* offset of the current frame */
+ int64_t cur_offset; /* current offset
+ (incremented by each av_parser_parse()) */
+ int64_t next_frame_offset; /* offset of the next frame */
+ /* video info */
+ int pict_type; /* XXX: Put it back in AVCodecContext. */
+ /**
+ * This field is used for proper frame duration computation in lavf.
+ * It signals, how much longer the frame duration of the current frame
+ * is compared to normal frame duration.
+ *
+ * frame_duration = (1 + repeat_pict) * time_base
+ *
+ * It is used by codecs like H.264 to display telecined material.
+ */
+ int repeat_pict; /* XXX: Put it back in AVCodecContext. */
+ int64_t pts; /* pts of the current frame */
+ int64_t dts; /* dts of the current frame */
+
+ /* private data */
+ int64_t last_pts;
+ int64_t last_dts;
+ int fetch_timestamp;
+
+#define AV_PARSER_PTS_NB 4
+ int cur_frame_start_index;
+ int64_t cur_frame_offset[AV_PARSER_PTS_NB];
+ int64_t cur_frame_pts[AV_PARSER_PTS_NB];
+ int64_t cur_frame_dts[AV_PARSER_PTS_NB];
+
+ int flags;
+#define PARSER_FLAG_COMPLETE_FRAMES 0x0001
+#define PARSER_FLAG_ONCE 0x0002
+/// Set if the parser has a valid file offset
+#define PARSER_FLAG_FETCHED_OFFSET 0x0004
+#define PARSER_FLAG_USE_CODEC_TS 0x1000
+
+ int64_t offset; ///< byte offset from starting packet start
+ int64_t cur_frame_end[AV_PARSER_PTS_NB];
+
+ /**
+ * Set by parser to 1 for key frames and 0 for non-key frames.
+ * It is initialized to -1, so if the parser doesn't set this flag,
+ * old-style fallback using AV_PICTURE_TYPE_I picture type as key frames
+ * will be used.
+ */
+ int key_frame;
+
+#if FF_API_CONVERGENCE_DURATION
+ /**
+ * @deprecated unused
+ */
+ attribute_deprecated
+ int64_t convergence_duration;
+#endif
+
+ // Timestamp generation support:
+ /**
+ * Synchronization point for start of timestamp generation.
+ *
+ * Set to >0 for sync point, 0 for no sync point and <0 for undefined
+ * (default).
+ *
+ * For example, this corresponds to presence of H.264 buffering period
+ * SEI message.
+ */
+ int dts_sync_point;
+
+ /**
+ * Offset of the current timestamp against last timestamp sync point in
+ * units of AVCodecContext.time_base.
+ *
+ * Set to INT_MIN when dts_sync_point unused. Otherwise, it must
+ * contain a valid timestamp offset.
+ *
+ * Note that the timestamp of sync point has usually a nonzero
+ * dts_ref_dts_delta, which refers to the previous sync point. Offset of
+ * the next frame after timestamp sync point will be usually 1.
+ *
+ * For example, this corresponds to H.264 cpb_removal_delay.
+ */
+ int dts_ref_dts_delta;
+
+ /**
+ * Presentation delay of current frame in units of AVCodecContext.time_base.
+ *
+ * Set to INT_MIN when dts_sync_point unused. Otherwise, it must
+ * contain valid non-negative timestamp delta (presentation time of a frame
+ * must not lie in the past).
+ *
+ * This delay represents the difference between decoding and presentation
+ * time of the frame.
+ *
+ * For example, this corresponds to H.264 dpb_output_delay.
+ */
+ int pts_dts_delta;
+
+ /**
+ * Position of the packet in file.
+ *
+ * Analogous to cur_frame_pts/dts
+ */
+ int64_t cur_frame_pos[AV_PARSER_PTS_NB];
+
+ /**
+ * Byte position of currently parsed frame in stream.
+ */
+ int64_t pos;
+
+ /**
+ * Previous frame byte position.
+ */
+ int64_t last_pos;
+
+ /**
+ * Duration of the current frame.
+ * For audio, this is in units of 1 / AVCodecContext.sample_rate.
+ * For all other types, this is in units of AVCodecContext.time_base.
+ */
+ int duration;
+
+ enum AVFieldOrder field_order;
+
+ /**
+ * Indicate whether a picture is coded as a frame, top field or bottom field.
+ *
+ * For example, H.264 field_pic_flag equal to 0 corresponds to
+ * AV_PICTURE_STRUCTURE_FRAME. An H.264 picture with field_pic_flag
+ * equal to 1 and bottom_field_flag equal to 0 corresponds to
+ * AV_PICTURE_STRUCTURE_TOP_FIELD.
+ */
+ enum AVPictureStructure picture_structure;
+
+ /**
+ * Picture number incremented in presentation or output order.
+ * This field may be reinitialized at the first picture of a new sequence.
+ *
+ * For example, this corresponds to H.264 PicOrderCnt.
+ */
+ int output_picture_number;
+
+ /**
+ * Dimensions of the decoded video intended for presentation.
+ */
+ int width;
+ int height;
+
+ /**
+ * Dimensions of the coded video.
+ */
+ int coded_width;
+ int coded_height;
+
+ /**
+ * The format of the coded data, corresponds to enum AVPixelFormat for video
+ * and for enum AVSampleFormat for audio.
+ *
+ * Note that a decoder can have considerable freedom in how exactly it
+ * decodes the data, so the format reported here might be different from the
+ * one returned by a decoder.
+ */
+ int format;
+} AVCodecParserContext;
+
+typedef struct AVCodecParser {
+ int codec_ids[5]; /* several codec IDs are permitted */
+ int priv_data_size;
+ int (*parser_init)(AVCodecParserContext *s);
+ /* This callback never returns an error, a negative value means that
+ * the frame start was in a previous packet. */
+ int (*parser_parse)(AVCodecParserContext *s,
+ AVCodecContext *avctx,
+ const uint8_t **poutbuf, int *poutbuf_size,
+ const uint8_t *buf, int buf_size);
+ void (*parser_close)(AVCodecParserContext *s);
+ int (*split)(AVCodecContext *avctx, const uint8_t *buf, int buf_size);
+ struct AVCodecParser *next;
+} AVCodecParser;
+
+/**
+ * Iterate over all registered codec parsers.
+ *
+ * @param opaque a pointer where libavcodec will store the iteration state. Must
+ * point to NULL to start the iteration.
+ *
+ * @return the next registered codec parser or NULL when the iteration is
+ * finished
+ */
+const AVCodecParser *av_parser_iterate(void **opaque);
+
+attribute_deprecated
+AVCodecParser *av_parser_next(const AVCodecParser *c);
+
+attribute_deprecated
+void av_register_codec_parser(AVCodecParser *parser);
+AVCodecParserContext *av_parser_init(int codec_id);
+
+/**
+ * Parse a packet.
+ *
+ * @param s parser context.
+ * @param avctx codec context.
+ * @param poutbuf set to pointer to parsed buffer or NULL if not yet finished.
+ * @param poutbuf_size set to size of parsed buffer or zero if not yet finished.
+ * @param buf input buffer.
+ * @param buf_size buffer size in bytes without the padding. I.e. the full buffer
+ size is assumed to be buf_size + AV_INPUT_BUFFER_PADDING_SIZE.
+ To signal EOF, this should be 0 (so that the last frame
+ can be output).
+ * @param pts input presentation timestamp.
+ * @param dts input decoding timestamp.
+ * @param pos input byte position in stream.
+ * @return the number of bytes of the input bitstream used.
+ *
+ * Example:
+ * @code
+ * while(in_len){
+ * len = av_parser_parse2(myparser, AVCodecContext, &data, &size,
+ * in_data, in_len,
+ * pts, dts, pos);
+ * in_data += len;
+ * in_len -= len;
+ *
+ * if(size)
+ * decode_frame(data, size);
+ * }
+ * @endcode
+ */
+int av_parser_parse2(AVCodecParserContext *s,
+ AVCodecContext *avctx,
+ uint8_t **poutbuf, int *poutbuf_size,
+ const uint8_t *buf, int buf_size,
+ int64_t pts, int64_t dts,
+ int64_t pos);
+
+/**
+ * @return 0 if the output buffer is a subset of the input, 1 if it is allocated and must be freed
+ * @deprecated use AVBitStreamFilter
+ */
+int av_parser_change(AVCodecParserContext *s,
+ AVCodecContext *avctx,
+ uint8_t **poutbuf, int *poutbuf_size,
+ const uint8_t *buf, int buf_size, int keyframe);
+void av_parser_close(AVCodecParserContext *s);
+
+/**
+ * @}
+ * @}
+ */
+
+/**
+ * @addtogroup lavc_encoding
+ * @{
+ */
+
+/**
+ * Find a registered encoder with a matching codec ID.
+ *
+ * @param id AVCodecID of the requested encoder
+ * @return An encoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_encoder(enum AVCodecID id);
+
+/**
+ * Find a registered encoder with the specified name.
+ *
+ * @param name name of the requested encoder
+ * @return An encoder if one was found, NULL otherwise.
+ */
+AVCodec *avcodec_find_encoder_by_name(const char *name);
+
+/**
+ * Encode a frame of audio.
+ *
+ * Takes input samples from frame and writes the next output packet, if
+ * available, to avpkt. The output packet does not necessarily contain data for
+ * the most recent frame, as encoders can delay, split, and combine input frames
+ * internally as needed.
+ *
+ * @param avctx codec context
+ * @param avpkt output AVPacket.
+ * The user can supply an output buffer by setting
+ * avpkt->data and avpkt->size prior to calling the
+ * function, but if the size of the user-provided data is not
+ * large enough, encoding will fail. If avpkt->data and
+ * avpkt->size are set, avpkt->destruct must also be set. All
+ * other AVPacket fields will be reset by the encoder using
+ * av_init_packet(). If avpkt->data is NULL, the encoder will
+ * allocate it. The encoder will set avpkt->size to the size
+ * of the output packet.
+ *
+ * If this function fails or produces no output, avpkt will be
+ * freed using av_packet_unref().
+ * @param[in] frame AVFrame containing the raw audio data to be encoded.
+ * May be NULL when flushing an encoder that has the
+ * AV_CODEC_CAP_DELAY capability set.
+ * If AV_CODEC_CAP_VARIABLE_FRAME_SIZE is set, then each frame
+ * can have any number of samples.
+ * If it is not set, frame->nb_samples must be equal to
+ * avctx->frame_size for all frames except the last.
+ * The final frame may be smaller than avctx->frame_size.
+ * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the
+ * output packet is non-empty, and to 0 if it is
+ * empty. If the function returns an error, the
+ * packet can be assumed to be invalid, and the
+ * value of got_packet_ptr is undefined and should
+ * not be used.
+ * @return 0 on success, negative error code on failure
+ *
+ * @deprecated use avcodec_send_frame()/avcodec_receive_packet() instead
+ */
+attribute_deprecated
+int avcodec_encode_audio2(AVCodecContext *avctx, AVPacket *avpkt,
+ const AVFrame *frame, int *got_packet_ptr);
+
+/**
+ * Encode a frame of video.
+ *
+ * Takes input raw video data from frame and writes the next output packet, if
+ * available, to avpkt. The output packet does not necessarily contain data for
+ * the most recent frame, as encoders can delay and reorder input frames
+ * internally as needed.
+ *
+ * @param avctx codec context
+ * @param avpkt output AVPacket.
+ * The user can supply an output buffer by setting
+ * avpkt->data and avpkt->size prior to calling the
+ * function, but if the size of the user-provided data is not
+ * large enough, encoding will fail. All other AVPacket fields
+ * will be reset by the encoder using av_init_packet(). If
+ * avpkt->data is NULL, the encoder will allocate it.
+ * The encoder will set avpkt->size to the size of the
+ * output packet. The returned data (if any) belongs to the
+ * caller, he is responsible for freeing it.
+ *
+ * If this function fails or produces no output, avpkt will be
+ * freed using av_packet_unref().
+ * @param[in] frame AVFrame containing the raw video data to be encoded.
+ * May be NULL when flushing an encoder that has the
+ * AV_CODEC_CAP_DELAY capability set.
+ * @param[out] got_packet_ptr This field is set to 1 by libavcodec if the
+ * output packet is non-empty, and to 0 if it is
+ * empty. If the function returns an error, the
+ * packet can be assumed to be invalid, and the
+ * value of got_packet_ptr is undefined and should
+ * not be used.
+ * @return 0 on success, negative error code on failure
+ *
+ * @deprecated use avcodec_send_frame()/avcodec_receive_packet() instead
+ */
+attribute_deprecated
+int avcodec_encode_video2(AVCodecContext *avctx, AVPacket *avpkt,
+ const AVFrame *frame, int *got_packet_ptr);
+
+int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
+ const AVSubtitle *sub);
+
+
+/**
+ * @}
+ */
+
+#if FF_API_AVPICTURE
+/**
+ * @addtogroup lavc_picture
+ * @{
+ */
+
+/**
+ * @deprecated unused
+ */
+attribute_deprecated
+int avpicture_alloc(AVPicture *picture, enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
+ * @deprecated unused
+ */
+attribute_deprecated
+void avpicture_free(AVPicture *picture);
+
+/**
+ * @deprecated use av_image_fill_arrays() instead.
+ */
+attribute_deprecated
+int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
+ enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
+ * @deprecated use av_image_copy_to_buffer() instead.
+ */
+attribute_deprecated
+int avpicture_layout(const AVPicture *src, enum AVPixelFormat pix_fmt,
+ int width, int height,
+ unsigned char *dest, int dest_size);
+
+/**
+ * @deprecated use av_image_get_buffer_size() instead.
+ */
+attribute_deprecated
+int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
+ * @deprecated av_image_copy() instead.
+ */
+attribute_deprecated
+void av_picture_copy(AVPicture *dst, const AVPicture *src,
+ enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
+ * @deprecated unused
+ */
+attribute_deprecated
+int av_picture_crop(AVPicture *dst, const AVPicture *src,
+ enum AVPixelFormat pix_fmt, int top_band, int left_band);
+
+/**
+ * @deprecated unused
+ */
+attribute_deprecated
+int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width, enum AVPixelFormat pix_fmt,
+ int padtop, int padbottom, int padleft, int padright, int *color);
+
+/**
+ * @}
+ */
+#endif
+
+/**
+ * @defgroup lavc_misc Utility functions
+ * @ingroup libavc
+ *
+ * Miscellaneous utility functions related to both encoding and decoding
+ * (or neither).
+ * @{
+ */
+
+/**
+ * @defgroup lavc_misc_pixfmt Pixel formats
+ *
+ * Functions for working with pixel formats.
+ * @{
+ */
+
+#if FF_API_GETCHROMA
+/**
+ * @deprecated Use av_pix_fmt_get_chroma_sub_sample
+ */
+
+attribute_deprecated
+void avcodec_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift);
+#endif
+
+/**
+ * Return a value representing the fourCC code associated to the
+ * pixel format pix_fmt, or 0 if no associated fourCC code can be
+ * found.
+ */
+unsigned int avcodec_pix_fmt_to_codec_tag(enum AVPixelFormat pix_fmt);
+
+/**
+ * @deprecated see av_get_pix_fmt_loss()
+ */
+int avcodec_get_pix_fmt_loss(enum AVPixelFormat dst_pix_fmt, enum AVPixelFormat src_pix_fmt,
+ int has_alpha);
+
+/**
+ * Find the best pixel format to convert to given a certain source pixel
+ * format. When converting from one pixel format to another, information loss
+ * may occur. For example, when converting from RGB24 to GRAY, the color
+ * information will be lost. Similarly, other losses occur when converting from
+ * some formats to other formats. avcodec_find_best_pix_fmt_of_2() searches which of
+ * the given pixel formats should be used to suffer the least amount of loss.
+ * The pixel formats from which it chooses one, are determined by the
+ * pix_fmt_list parameter.
+ *
+ *
+ * @param[in] pix_fmt_list AV_PIX_FMT_NONE terminated array of pixel formats to choose from
+ * @param[in] src_pix_fmt source pixel format
+ * @param[in] has_alpha Whether the source pixel format alpha channel is used.
+ * @param[out] loss_ptr Combination of flags informing you what kind of losses will occur.
+ * @return The best pixel format to convert to or -1 if none was found.
+ */
+enum AVPixelFormat avcodec_find_best_pix_fmt_of_list(const enum AVPixelFormat *pix_fmt_list,
+ enum AVPixelFormat src_pix_fmt,
+ int has_alpha, int *loss_ptr);
+
+/**
+ * @deprecated see av_find_best_pix_fmt_of_2()
+ */
+enum AVPixelFormat avcodec_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
+ enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr);
+
+attribute_deprecated
+enum AVPixelFormat avcodec_find_best_pix_fmt2(enum AVPixelFormat dst_pix_fmt1, enum AVPixelFormat dst_pix_fmt2,
+ enum AVPixelFormat src_pix_fmt, int has_alpha, int *loss_ptr);
+
+enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat * fmt);
+
+/**
+ * @}
+ */
+
+#if FF_API_TAG_STRING
+/**
+ * Put a string representing the codec tag codec_tag in buf.
+ *
+ * @param buf buffer to place codec tag in
+ * @param buf_size size in bytes of buf
+ * @param codec_tag codec tag to assign
+ * @return the length of the string that would have been generated if
+ * enough space had been available, excluding the trailing null
+ *
+ * @deprecated see av_fourcc_make_string() and av_fourcc2str().
+ */
+attribute_deprecated
+size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag);
+#endif
+
+void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode);
+
+/**
+ * Return a name for the specified profile, if available.
+ *
+ * @param codec the codec that is searched for the given profile
+ * @param profile the profile value for which a name is requested
+ * @return A name for the profile if found, NULL otherwise.
+ */
+const char *av_get_profile_name(const AVCodec *codec, int profile);
+
+/**
+ * Return a name for the specified profile, if available.
+ *
+ * @param codec_id the ID of the codec to which the requested profile belongs
+ * @param profile the profile value for which a name is requested
+ * @return A name for the profile if found, NULL otherwise.
+ *
+ * @note unlike av_get_profile_name(), which searches a list of profiles
+ * supported by a specific decoder or encoder implementation, this
+ * function searches the list of profiles from the AVCodecDescriptor
+ */
+const char *avcodec_profile_name(enum AVCodecID codec_id, int profile);
+
+int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2),void *arg, int *ret, int count, int size);
+int avcodec_default_execute2(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2, int, int),void *arg, int *ret, int count);
+//FIXME func typedef
+
+/**
+ * Fill AVFrame audio data and linesize pointers.
+ *
+ * The buffer buf must be a preallocated buffer with a size big enough
+ * to contain the specified samples amount. The filled AVFrame data
+ * pointers will point to this buffer.
+ *
+ * AVFrame extended_data channel pointers are allocated if necessary for
+ * planar audio.
+ *
+ * @param frame the AVFrame
+ * frame->nb_samples must be set prior to calling the
+ * function. This function fills in frame->data,
+ * frame->extended_data, frame->linesize[0].
+ * @param nb_channels channel count
+ * @param sample_fmt sample format
+ * @param buf buffer to use for frame data
+ * @param buf_size size of buffer
+ * @param align plane size sample alignment (0 = default)
+ * @return >=0 on success, negative error code on failure
+ * @todo return the size in bytes required to store the samples in
+ * case of success, at the next libavutil bump
+ */
+int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
+ enum AVSampleFormat sample_fmt, const uint8_t *buf,
+ int buf_size, int align);
+
+/**
+ * Reset the internal decoder state / flush internal buffers. Should be called
+ * e.g. when seeking or when switching to a different stream.
+ *
+ * @note when refcounted frames are not used (i.e. avctx->refcounted_frames is 0),
+ * this invalidates the frames previously returned from the decoder. When
+ * refcounted frames are used, the decoder just releases any references it might
+ * keep internally, but the caller's reference remains valid.
+ */
+void avcodec_flush_buffers(AVCodecContext *avctx);
+
+/**
+ * Return codec bits per sample.
+ *
+ * @param[in] codec_id the codec
+ * @return Number of bits per sample or zero if unknown for the given codec.
+ */
+int av_get_bits_per_sample(enum AVCodecID codec_id);
+
+/**
+ * Return the PCM codec associated with a sample format.
+ * @param be endianness, 0 for little, 1 for big,
+ * -1 (or anything else) for native
+ * @return AV_CODEC_ID_PCM_* or AV_CODEC_ID_NONE
+ */
+enum AVCodecID av_get_pcm_codec(enum AVSampleFormat fmt, int be);
+
+/**
+ * Return codec bits per sample.
+ * Only return non-zero if the bits per sample is exactly correct, not an
+ * approximation.
+ *
+ * @param[in] codec_id the codec
+ * @return Number of bits per sample or zero if unknown for the given codec.
+ */
+int av_get_exact_bits_per_sample(enum AVCodecID codec_id);
+
+/**
+ * Return audio frame duration.
+ *
+ * @param avctx codec context
+ * @param frame_bytes size of the frame, or 0 if unknown
+ * @return frame duration, in samples, if known. 0 if not able to
+ * determine.
+ */
+int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes);
+
+/**
+ * This function is the same as av_get_audio_frame_duration(), except it works
+ * with AVCodecParameters instead of an AVCodecContext.
+ */
+int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes);
+
+#if FF_API_OLD_BSF
+typedef struct AVBitStreamFilterContext {
+ void *priv_data;
+ const struct AVBitStreamFilter *filter;
+ AVCodecParserContext *parser;
+ struct AVBitStreamFilterContext *next;
+ /**
+ * Internal default arguments, used if NULL is passed to av_bitstream_filter_filter().
+ * Not for access by library users.
+ */
+ char *args;
+} AVBitStreamFilterContext;
+#endif
+
+typedef struct AVBSFInternal AVBSFInternal;
+
+/**
+ * The bitstream filter state.
+ *
+ * This struct must be allocated with av_bsf_alloc() and freed with
+ * av_bsf_free().
+ *
+ * The fields in the struct will only be changed (by the caller or by the
+ * filter) as described in their documentation, and are to be considered
+ * immutable otherwise.
+ */
+typedef struct AVBSFContext {
+ /**
+ * A class for logging and AVOptions
+ */
+ const AVClass *av_class;
+
+ /**
+ * The bitstream filter this context is an instance of.
+ */
+ const struct AVBitStreamFilter *filter;
+
+ /**
+ * Opaque libavcodec internal data. Must not be touched by the caller in any
+ * way.
+ */
+ AVBSFInternal *internal;
+
+ /**
+ * Opaque filter-specific private data. If filter->priv_class is non-NULL,
+ * this is an AVOptions-enabled struct.
+ */
+ void *priv_data;
+
+ /**
+ * Parameters of the input stream. This field is allocated in
+ * av_bsf_alloc(), it needs to be filled by the caller before
+ * av_bsf_init().
+ */
+ AVCodecParameters *par_in;
+
+ /**
+ * Parameters of the output stream. This field is allocated in
+ * av_bsf_alloc(), it is set by the filter in av_bsf_init().
+ */
+ AVCodecParameters *par_out;
+
+ /**
+ * The timebase used for the timestamps of the input packets. Set by the
+ * caller before av_bsf_init().
+ */
+ AVRational time_base_in;
+
+ /**
+ * The timebase used for the timestamps of the output packets. Set by the
+ * filter in av_bsf_init().
+ */
+ AVRational time_base_out;
+} AVBSFContext;
+
+typedef struct AVBitStreamFilter {
+ const char *name;
+
+ /**
+ * A list of codec ids supported by the filter, terminated by
+ * AV_CODEC_ID_NONE.
+ * May be NULL, in that case the bitstream filter works with any codec id.
+ */
+ const enum AVCodecID *codec_ids;
+
+ /**
+ * A class for the private data, used to declare bitstream filter private
+ * AVOptions. This field is NULL for bitstream filters that do not declare
+ * any options.
+ *
+ * If this field is non-NULL, the first member of the filter private data
+ * must be a pointer to AVClass, which will be set by libavcodec generic
+ * code to this class.
+ */
+ const AVClass *priv_class;
+
+ /*****************************************************************
+ * No fields below this line are part of the public API. They
+ * may not be used outside of libavcodec and can be changed and
+ * removed at will.
+ * New public fields should be added right above.
+ *****************************************************************
+ */
+
+ int priv_data_size;
+ int (*init)(AVBSFContext *ctx);
+ int (*filter)(AVBSFContext *ctx, AVPacket *pkt);
+ void (*close)(AVBSFContext *ctx);
+} AVBitStreamFilter;
+
+#if FF_API_OLD_BSF
+/**
+ * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext)
+ * is deprecated. Use the new bitstream filtering API (using AVBSFContext).
+ */
+attribute_deprecated
+void av_register_bitstream_filter(AVBitStreamFilter *bsf);
+/**
+ * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext)
+ * is deprecated. Use av_bsf_get_by_name(), av_bsf_alloc(), and av_bsf_init()
+ * from the new bitstream filtering API (using AVBSFContext).
+ */
+attribute_deprecated
+AVBitStreamFilterContext *av_bitstream_filter_init(const char *name);
+/**
+ * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext)
+ * is deprecated. Use av_bsf_send_packet() and av_bsf_receive_packet() from the
+ * new bitstream filtering API (using AVBSFContext).
+ */
+attribute_deprecated
+int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc,
+ AVCodecContext *avctx, const char *args,
+ uint8_t **poutbuf, int *poutbuf_size,
+ const uint8_t *buf, int buf_size, int keyframe);
+/**
+ * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext)
+ * is deprecated. Use av_bsf_free() from the new bitstream filtering API (using
+ * AVBSFContext).
+ */
+attribute_deprecated
+void av_bitstream_filter_close(AVBitStreamFilterContext *bsf);
+/**
+ * @deprecated the old bitstream filtering API (using AVBitStreamFilterContext)
+ * is deprecated. Use av_bsf_iterate() from the new bitstream filtering API (using
+ * AVBSFContext).
+ */
+attribute_deprecated
+const AVBitStreamFilter *av_bitstream_filter_next(const AVBitStreamFilter *f);
+#endif
+
+/**
+ * @return a bitstream filter with the specified name or NULL if no such
+ * bitstream filter exists.
+ */
+const AVBitStreamFilter *av_bsf_get_by_name(const char *name);
+
+/**
+ * Iterate over all registered bitstream filters.
+ *
+ * @param opaque a pointer where libavcodec will store the iteration state. Must
+ * point to NULL to start the iteration.
+ *
+ * @return the next registered bitstream filter or NULL when the iteration is
+ * finished
+ */
+const AVBitStreamFilter *av_bsf_iterate(void **opaque);
+#if FF_API_NEXT
+attribute_deprecated
+const AVBitStreamFilter *av_bsf_next(void **opaque);
+#endif
+
+/**
+ * Allocate a context for a given bitstream filter. The caller must fill in the
+ * context parameters as described in the documentation and then call
+ * av_bsf_init() before sending any data to the filter.
+ *
+ * @param filter the filter for which to allocate an instance.
+ * @param ctx a pointer into which the pointer to the newly-allocated context
+ * will be written. It must be freed with av_bsf_free() after the
+ * filtering is done.
+ *
+ * @return 0 on success, a negative AVERROR code on failure
+ */
+int av_bsf_alloc(const AVBitStreamFilter *filter, AVBSFContext **ctx);
+
+/**
+ * Prepare the filter for use, after all the parameters and options have been
+ * set.
+ */
+int av_bsf_init(AVBSFContext *ctx);
+
+/**
+ * Submit a packet for filtering.
+ *
+ * After sending each packet, the filter must be completely drained by calling
+ * av_bsf_receive_packet() repeatedly until it returns AVERROR(EAGAIN) or
+ * AVERROR_EOF.
+ *
+ * @param pkt the packet to filter. The bitstream filter will take ownership of
+ * the packet and reset the contents of pkt. pkt is not touched if an error occurs.
+ * This parameter may be NULL, which signals the end of the stream (i.e. no more
+ * packets will be sent). That will cause the filter to output any packets it
+ * may have buffered internally.
+ *
+ * @return 0 on success, a negative AVERROR on error.
+ */
+int av_bsf_send_packet(AVBSFContext *ctx, AVPacket *pkt);
+
+/**
+ * Retrieve a filtered packet.
+ *
+ * @param[out] pkt this struct will be filled with the contents of the filtered
+ * packet. It is owned by the caller and must be freed using
+ * av_packet_unref() when it is no longer needed.
+ * This parameter should be "clean" (i.e. freshly allocated
+ * with av_packet_alloc() or unreffed with av_packet_unref())
+ * when this function is called. If this function returns
+ * successfully, the contents of pkt will be completely
+ * overwritten by the returned data. On failure, pkt is not
+ * touched.
+ *
+ * @return 0 on success. AVERROR(EAGAIN) if more packets need to be sent to the
+ * filter (using av_bsf_send_packet()) to get more output. AVERROR_EOF if there
+ * will be no further output from the filter. Another negative AVERROR value if
+ * an error occurs.
+ *
+ * @note one input packet may result in several output packets, so after sending
+ * a packet with av_bsf_send_packet(), this function needs to be called
+ * repeatedly until it stops returning 0. It is also possible for a filter to
+ * output fewer packets than were sent to it, so this function may return
+ * AVERROR(EAGAIN) immediately after a successful av_bsf_send_packet() call.
+ */
+int av_bsf_receive_packet(AVBSFContext *ctx, AVPacket *pkt);
+
+/**
+ * Free a bitstream filter context and everything associated with it; write NULL
+ * into the supplied pointer.
+ */
+void av_bsf_free(AVBSFContext **ctx);
+
+/**
+ * Get the AVClass for AVBSFContext. It can be used in combination with
+ * AV_OPT_SEARCH_FAKE_OBJ for examining options.
+ *
+ * @see av_opt_find().
+ */
+const AVClass *av_bsf_get_class(void);
+
+/**
+ * Structure for chain/list of bitstream filters.
+ * Empty list can be allocated by av_bsf_list_alloc().
+ */
+typedef struct AVBSFList AVBSFList;
+
+/**
+ * Allocate empty list of bitstream filters.
+ * The list must be later freed by av_bsf_list_free()
+ * or finalized by av_bsf_list_finalize().
+ *
+ * @return Pointer to @ref AVBSFList on success, NULL in case of failure
+ */
+AVBSFList *av_bsf_list_alloc(void);
+
+/**
+ * Free list of bitstream filters.
+ *
+ * @param lst Pointer to pointer returned by av_bsf_list_alloc()
+ */
+void av_bsf_list_free(AVBSFList **lst);
+
+/**
+ * Append bitstream filter to the list of bitstream filters.
+ *
+ * @param lst List to append to
+ * @param bsf Filter context to be appended
+ *
+ * @return >=0 on success, negative AVERROR in case of failure
+ */
+int av_bsf_list_append(AVBSFList *lst, AVBSFContext *bsf);
+
+/**
+ * Construct new bitstream filter context given it's name and options
+ * and append it to the list of bitstream filters.
+ *
+ * @param lst List to append to
+ * @param bsf_name Name of the bitstream filter
+ * @param options Options for the bitstream filter, can be set to NULL
+ *
+ * @return >=0 on success, negative AVERROR in case of failure
+ */
+int av_bsf_list_append2(AVBSFList *lst, const char * bsf_name, AVDictionary **options);
+/**
+ * Finalize list of bitstream filters.
+ *
+ * This function will transform @ref AVBSFList to single @ref AVBSFContext,
+ * so the whole chain of bitstream filters can be treated as single filter
+ * freshly allocated by av_bsf_alloc().
+ * If the call is successful, @ref AVBSFList structure is freed and lst
+ * will be set to NULL. In case of failure, caller is responsible for
+ * freeing the structure by av_bsf_list_free()
+ *
+ * @param lst Filter list structure to be transformed
+ * @param[out] bsf Pointer to be set to newly created @ref AVBSFContext structure
+ * representing the chain of bitstream filters
+ *
+ * @return >=0 on success, negative AVERROR in case of failure
+ */
+int av_bsf_list_finalize(AVBSFList **lst, AVBSFContext **bsf);
+
+/**
+ * Parse string describing list of bitstream filters and create single
+ * @ref AVBSFContext describing the whole chain of bitstream filters.
+ * Resulting @ref AVBSFContext can be treated as any other @ref AVBSFContext freshly
+ * allocated by av_bsf_alloc().
+ *
+ * @param str String describing chain of bitstream filters in format
+ * `bsf1[=opt1=val1:opt2=val2][,bsf2]`
+ * @param[out] bsf Pointer to be set to newly created @ref AVBSFContext structure
+ * representing the chain of bitstream filters
+ *
+ * @return >=0 on success, negative AVERROR in case of failure
+ */
+int av_bsf_list_parse_str(const char *str, AVBSFContext **bsf);
+
+/**
+ * Get null/pass-through bitstream filter.
+ *
+ * @param[out] bsf Pointer to be set to new instance of pass-through bitstream filter
+ *
+ * @return
+ */
+int av_bsf_get_null_filter(AVBSFContext **bsf);
+
+/* memory */
+
+/**
+ * Same behaviour av_fast_malloc but the buffer has additional
+ * AV_INPUT_BUFFER_PADDING_SIZE at the end which will always be 0.
+ *
+ * In addition the whole buffer will initially and after resizes
+ * be 0-initialized so that no uninitialized data will ever appear.
+ */
+void av_fast_padded_malloc(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Same behaviour av_fast_padded_malloc except that buffer will always
+ * be 0-initialized after call.
+ */
+void av_fast_padded_mallocz(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Encode extradata length to a buffer. Used by xiph codecs.
+ *
+ * @param s buffer to write to; must be at least (v/255+1) bytes long
+ * @param v size of extradata in bytes
+ * @return number of bytes written to the buffer.
+ */
+unsigned int av_xiphlacing(unsigned char *s, unsigned int v);
+
+#if FF_API_USER_VISIBLE_AVHWACCEL
+/**
+ * Register the hardware accelerator hwaccel.
+ *
+ * @deprecated This function doesn't do anything.
+ */
+attribute_deprecated
+void av_register_hwaccel(AVHWAccel *hwaccel);
+
+/**
+ * If hwaccel is NULL, returns the first registered hardware accelerator,
+ * if hwaccel is non-NULL, returns the next registered hardware accelerator
+ * after hwaccel, or NULL if hwaccel is the last one.
+ *
+ * @deprecated AVHWaccel structures contain no user-serviceable parts, so
+ * this function should not be used.
+ */
+attribute_deprecated
+AVHWAccel *av_hwaccel_next(const AVHWAccel *hwaccel);
+#endif
+
+#if FF_API_LOCKMGR
+/**
+ * Lock operation used by lockmgr
+ *
+ * @deprecated Deprecated together with av_lockmgr_register().
+ */
+enum AVLockOp {
+ AV_LOCK_CREATE, ///< Create a mutex
+ AV_LOCK_OBTAIN, ///< Lock the mutex
+ AV_LOCK_RELEASE, ///< Unlock the mutex
+ AV_LOCK_DESTROY, ///< Free mutex resources
+};
+
+/**
+ * Register a user provided lock manager supporting the operations
+ * specified by AVLockOp. The "mutex" argument to the function points
+ * to a (void *) where the lockmgr should store/get a pointer to a user
+ * allocated mutex. It is NULL upon AV_LOCK_CREATE and equal to the
+ * value left by the last call for all other ops. If the lock manager is
+ * unable to perform the op then it should leave the mutex in the same
+ * state as when it was called and return a non-zero value. However,
+ * when called with AV_LOCK_DESTROY the mutex will always be assumed to
+ * have been successfully destroyed. If av_lockmgr_register succeeds
+ * it will return a non-negative value, if it fails it will return a
+ * negative value and destroy all mutex and unregister all callbacks.
+ * av_lockmgr_register is not thread-safe, it must be called from a
+ * single thread before any calls which make use of locking are used.
+ *
+ * @param cb User defined callback. av_lockmgr_register invokes calls
+ * to this callback and the previously registered callback.
+ * The callback will be used to create more than one mutex
+ * each of which must be backed by its own underlying locking
+ * mechanism (i.e. do not use a single static object to
+ * implement your lock manager). If cb is set to NULL the
+ * lockmgr will be unregistered.
+ *
+ * @deprecated This function does nothing, and always returns 0. Be sure to
+ * build with thread support to get basic thread safety.
+ */
+attribute_deprecated
+int av_lockmgr_register(int (*cb)(void **mutex, enum AVLockOp op));
+#endif
+
+/**
+ * Get the type of the given codec.
+ */
+enum AVMediaType avcodec_get_type(enum AVCodecID codec_id);
+
+/**
+ * Get the name of a codec.
+ * @return a static string identifying the codec; never NULL
+ */
+const char *avcodec_get_name(enum AVCodecID id);
+
+/**
+ * @return a positive value if s is open (i.e. avcodec_open2() was called on it
+ * with no corresponding avcodec_close()), 0 otherwise.
+ */
+int avcodec_is_open(AVCodecContext *s);
+
+/**
+ * @return a non-zero number if codec is an encoder, zero otherwise
+ */
+int av_codec_is_encoder(const AVCodec *codec);
+
+/**
+ * @return a non-zero number if codec is a decoder, zero otherwise
+ */
+int av_codec_is_decoder(const AVCodec *codec);
+
+/**
+ * @return descriptor for given codec ID or NULL if no descriptor exists.
+ */
+const AVCodecDescriptor *avcodec_descriptor_get(enum AVCodecID id);
+
+/**
+ * Iterate over all codec descriptors known to libavcodec.
+ *
+ * @param prev previous descriptor. NULL to get the first descriptor.
+ *
+ * @return next descriptor or NULL after the last descriptor
+ */
+const AVCodecDescriptor *avcodec_descriptor_next(const AVCodecDescriptor *prev);
+
+/**
+ * @return codec descriptor with the given name or NULL if no such descriptor
+ * exists.
+ */
+const AVCodecDescriptor *avcodec_descriptor_get_by_name(const char *name);
+
+/**
+ * Allocate a CPB properties structure and initialize its fields to default
+ * values.
+ *
+ * @param size if non-NULL, the size of the allocated struct will be written
+ * here. This is useful for embedding it in side data.
+ *
+ * @return the newly allocated struct or NULL on failure
+ */
+AVCPBProperties *av_cpb_properties_alloc(size_t *size);
+
+/**
+ * @}
+ */
+
+#endif /* AVCODEC_AVCODEC_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/avfft.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/avfft.h
new file mode 100644
index 000000000..0c0f9b8d8
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/avfft.h
@@ -0,0 +1,118 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_AVFFT_H
+#define AVCODEC_AVFFT_H
+
+/**
+ * @file
+ * @ingroup lavc_fft
+ * FFT functions
+ */
+
+/**
+ * @defgroup lavc_fft FFT functions
+ * @ingroup lavc_misc
+ *
+ * @{
+ */
+
+typedef float FFTSample;
+
+typedef struct FFTComplex {
+ FFTSample re, im;
+} FFTComplex;
+
+typedef struct FFTContext FFTContext;
+
+/**
+ * Set up a complex FFT.
+ * @param nbits log2 of the length of the input array
+ * @param inverse if 0 perform the forward transform, if 1 perform the inverse
+ */
+FFTContext *av_fft_init(int nbits, int inverse);
+
+/**
+ * Do the permutation needed BEFORE calling ff_fft_calc().
+ */
+void av_fft_permute(FFTContext *s, FFTComplex *z);
+
+/**
+ * Do a complex FFT with the parameters defined in av_fft_init(). The
+ * input data must be permuted before. No 1.0/sqrt(n) normalization is done.
+ */
+void av_fft_calc(FFTContext *s, FFTComplex *z);
+
+void av_fft_end(FFTContext *s);
+
+FFTContext *av_mdct_init(int nbits, int inverse, double scale);
+void av_imdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_imdct_half(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_mdct_calc(FFTContext *s, FFTSample *output, const FFTSample *input);
+void av_mdct_end(FFTContext *s);
+
+/* Real Discrete Fourier Transform */
+
+enum RDFTransformType {
+ DFT_R2C,
+ IDFT_C2R,
+ IDFT_R2C,
+ DFT_C2R,
+};
+
+typedef struct RDFTContext RDFTContext;
+
+/**
+ * Set up a real FFT.
+ * @param nbits log2 of the length of the input array
+ * @param trans the type of transform
+ */
+RDFTContext *av_rdft_init(int nbits, enum RDFTransformType trans);
+void av_rdft_calc(RDFTContext *s, FFTSample *data);
+void av_rdft_end(RDFTContext *s);
+
+/* Discrete Cosine Transform */
+
+typedef struct DCTContext DCTContext;
+
+enum DCTTransformType {
+ DCT_II = 0,
+ DCT_III,
+ DCT_I,
+ DST_I,
+};
+
+/**
+ * Set up DCT.
+ *
+ * @param nbits size of the input array:
+ * (1 << nbits) for DCT-II, DCT-III and DST-I
+ * (1 << nbits) + 1 for DCT-I
+ * @param type the type of transform
+ *
+ * @note the first element of the input of DST-I is ignored
+ */
+DCTContext *av_dct_init(int nbits, enum DCTTransformType type);
+void av_dct_calc(DCTContext *s, FFTSample *data);
+void av_dct_end (DCTContext *s);
+
+/**
+ * @}
+ */
+
+#endif /* AVCODEC_AVFFT_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/vaapi.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/vaapi.h
new file mode 100644
index 000000000..2cf7da588
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/vaapi.h
@@ -0,0 +1,86 @@
+/*
+ * Video Acceleration API (shared data between FFmpeg and the video player)
+ * HW decode acceleration for MPEG-2, MPEG-4, H.264 and VC-1
+ *
+ * Copyright (C) 2008-2009 Splitted-Desktop Systems
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VAAPI_H
+#define AVCODEC_VAAPI_H
+
+/**
+ * @file
+ * @ingroup lavc_codec_hwaccel_vaapi
+ * Public libavcodec VA API header.
+ */
+
+#include <stdint.h>
+#include "libavutil/attributes.h"
+#include "version.h"
+
+#if FF_API_STRUCT_VAAPI_CONTEXT
+
+/**
+ * @defgroup lavc_codec_hwaccel_vaapi VA API Decoding
+ * @ingroup lavc_codec_hwaccel
+ * @{
+ */
+
+/**
+ * This structure is used to share data between the FFmpeg library and
+ * the client video application.
+ * This shall be zero-allocated and available as
+ * AVCodecContext.hwaccel_context. All user members can be set once
+ * during initialization or through each AVCodecContext.get_buffer()
+ * function call. In any case, they must be valid prior to calling
+ * decoding functions.
+ *
+ * Deprecated: use AVCodecContext.hw_frames_ctx instead.
+ */
+struct attribute_deprecated vaapi_context {
+ /**
+ * Window system dependent data
+ *
+ * - encoding: unused
+ * - decoding: Set by user
+ */
+ void *display;
+
+ /**
+ * Configuration ID
+ *
+ * - encoding: unused
+ * - decoding: Set by user
+ */
+ uint32_t config_id;
+
+ /**
+ * Context ID (video decode pipeline)
+ *
+ * - encoding: unused
+ * - decoding: Set by user
+ */
+ uint32_t context_id;
+};
+
+/* @} */
+
+#endif /* FF_API_STRUCT_VAAPI_CONTEXT */
+
+#endif /* AVCODEC_VAAPI_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/vdpau.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/vdpau.h
new file mode 100644
index 000000000..4d9994336
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/vdpau.h
@@ -0,0 +1,176 @@
+/*
+ * The Video Decode and Presentation API for UNIX (VDPAU) is used for
+ * hardware-accelerated decoding of MPEG-1/2, H.264 and VC-1.
+ *
+ * Copyright (C) 2008 NVIDIA
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VDPAU_H
+#define AVCODEC_VDPAU_H
+
+/**
+ * @file
+ * @ingroup lavc_codec_hwaccel_vdpau
+ * Public libavcodec VDPAU header.
+ */
+
+
+/**
+ * @defgroup lavc_codec_hwaccel_vdpau VDPAU Decoder and Renderer
+ * @ingroup lavc_codec_hwaccel
+ *
+ * VDPAU hardware acceleration has two modules
+ * - VDPAU decoding
+ * - VDPAU presentation
+ *
+ * The VDPAU decoding module parses all headers using FFmpeg
+ * parsing mechanisms and uses VDPAU for the actual decoding.
+ *
+ * As per the current implementation, the actual decoding
+ * and rendering (API calls) are done as part of the VDPAU
+ * presentation (vo_vdpau.c) module.
+ *
+ * @{
+ */
+
+#include <vdpau/vdpau.h>
+
+#include "libavutil/avconfig.h"
+#include "libavutil/attributes.h"
+
+#include "avcodec.h"
+#include "version.h"
+
+struct AVCodecContext;
+struct AVFrame;
+
+typedef int (*AVVDPAU_Render2)(struct AVCodecContext *, struct AVFrame *,
+ const VdpPictureInfo *, uint32_t,
+ const VdpBitstreamBuffer *);
+
+/**
+ * This structure is used to share data between the libavcodec library and
+ * the client video application.
+ * The user shall allocate the structure via the av_alloc_vdpau_hwaccel
+ * function and make it available as
+ * AVCodecContext.hwaccel_context. Members can be set by the user once
+ * during initialization or through each AVCodecContext.get_buffer()
+ * function call. In any case, they must be valid prior to calling
+ * decoding functions.
+ *
+ * The size of this structure is not a part of the public ABI and must not
+ * be used outside of libavcodec. Use av_vdpau_alloc_context() to allocate an
+ * AVVDPAUContext.
+ */
+typedef struct AVVDPAUContext {
+ /**
+ * VDPAU decoder handle
+ *
+ * Set by user.
+ */
+ VdpDecoder decoder;
+
+ /**
+ * VDPAU decoder render callback
+ *
+ * Set by the user.
+ */
+ VdpDecoderRender *render;
+
+ AVVDPAU_Render2 render2;
+} AVVDPAUContext;
+
+/**
+ * @brief allocation function for AVVDPAUContext
+ *
+ * Allows extending the struct without breaking API/ABI
+ */
+AVVDPAUContext *av_alloc_vdpaucontext(void);
+
+AVVDPAU_Render2 av_vdpau_hwaccel_get_render2(const AVVDPAUContext *);
+void av_vdpau_hwaccel_set_render2(AVVDPAUContext *, AVVDPAU_Render2);
+
+/**
+ * Associate a VDPAU device with a codec context for hardware acceleration.
+ * This function is meant to be called from the get_format() codec callback,
+ * or earlier. It can also be called after avcodec_flush_buffers() to change
+ * the underlying VDPAU device mid-stream (e.g. to recover from non-transparent
+ * display preemption).
+ *
+ * @note get_format() must return AV_PIX_FMT_VDPAU if this function completes
+ * successfully.
+ *
+ * @param avctx decoding context whose get_format() callback is invoked
+ * @param device VDPAU device handle to use for hardware acceleration
+ * @param get_proc_address VDPAU device driver
+ * @param flags zero of more OR'd AV_HWACCEL_FLAG_* flags
+ *
+ * @return 0 on success, an AVERROR code on failure.
+ */
+int av_vdpau_bind_context(AVCodecContext *avctx, VdpDevice device,
+ VdpGetProcAddress *get_proc_address, unsigned flags);
+
+/**
+ * Gets the parameters to create an adequate VDPAU video surface for the codec
+ * context using VDPAU hardware decoding acceleration.
+ *
+ * @note Behavior is undefined if the context was not successfully bound to a
+ * VDPAU device using av_vdpau_bind_context().
+ *
+ * @param avctx the codec context being used for decoding the stream
+ * @param type storage space for the VDPAU video surface chroma type
+ * (or NULL to ignore)
+ * @param width storage space for the VDPAU video surface pixel width
+ * (or NULL to ignore)
+ * @param height storage space for the VDPAU video surface pixel height
+ * (or NULL to ignore)
+ *
+ * @return 0 on success, a negative AVERROR code on failure.
+ */
+int av_vdpau_get_surface_parameters(AVCodecContext *avctx, VdpChromaType *type,
+ uint32_t *width, uint32_t *height);
+
+/**
+ * Allocate an AVVDPAUContext.
+ *
+ * @return Newly-allocated AVVDPAUContext or NULL on failure.
+ */
+AVVDPAUContext *av_vdpau_alloc_context(void);
+
+#if FF_API_VDPAU_PROFILE
+/**
+ * Get a decoder profile that should be used for initializing a VDPAU decoder.
+ * Should be called from the AVCodecContext.get_format() callback.
+ *
+ * @deprecated Use av_vdpau_bind_context() instead.
+ *
+ * @param avctx the codec context being used for decoding the stream
+ * @param profile a pointer into which the result will be written on success.
+ * The contents of profile are undefined if this function returns
+ * an error.
+ *
+ * @return 0 on success (non-negative), a negative AVERROR on failure.
+ */
+attribute_deprecated
+int av_vdpau_get_profile(AVCodecContext *avctx, VdpDecoderProfile *profile);
+#endif
+
+/* @}*/
+
+#endif /* AVCODEC_VDPAU_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/version.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/version.h
new file mode 100644
index 000000000..6895f1a46
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavcodec/version.h
@@ -0,0 +1,137 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VERSION_H
+#define AVCODEC_VERSION_H
+
+/**
+ * @file
+ * @ingroup libavc
+ * Libavcodec version macros.
+ */
+
+#include "libavutil/version.h"
+
+#define LIBAVCODEC_VERSION_MAJOR 58
+#define LIBAVCODEC_VERSION_MINOR 18
+#define LIBAVCODEC_VERSION_MICRO 100
+
+#define LIBAVCODEC_VERSION_INT AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
+ LIBAVCODEC_VERSION_MINOR, \
+ LIBAVCODEC_VERSION_MICRO)
+#define LIBAVCODEC_VERSION AV_VERSION(LIBAVCODEC_VERSION_MAJOR, \
+ LIBAVCODEC_VERSION_MINOR, \
+ LIBAVCODEC_VERSION_MICRO)
+#define LIBAVCODEC_BUILD LIBAVCODEC_VERSION_INT
+
+#define LIBAVCODEC_IDENT "Lavc" AV_STRINGIFY(LIBAVCODEC_VERSION)
+
+/**
+ * FF_API_* defines may be placed below to indicate public API that will be
+ * dropped at a future version bump. The defines themselves are not part of
+ * the public API and may change, break or disappear at any time.
+ *
+ * @note, when bumping the major version it is recommended to manually
+ * disable each FF_API_* in its own commit instead of disabling them all
+ * at once through the bump. This improves the git bisect-ability of the change.
+ */
+
+#ifndef FF_API_LOWRES
+#define FF_API_LOWRES (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_DEBUG_MV
+#define FF_API_DEBUG_MV (LIBAVCODEC_VERSION_MAJOR < 58)
+#endif
+#ifndef FF_API_AVCTX_TIMEBASE
+#define FF_API_AVCTX_TIMEBASE (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_CODED_FRAME
+#define FF_API_CODED_FRAME (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_SIDEDATA_ONLY_PKT
+#define FF_API_SIDEDATA_ONLY_PKT (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_VDPAU_PROFILE
+#define FF_API_VDPAU_PROFILE (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_CONVERGENCE_DURATION
+#define FF_API_CONVERGENCE_DURATION (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_AVPICTURE
+#define FF_API_AVPICTURE (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_AVPACKET_OLD_API
+#define FF_API_AVPACKET_OLD_API (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_RTP_CALLBACK
+#define FF_API_RTP_CALLBACK (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_VBV_DELAY
+#define FF_API_VBV_DELAY (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_CODER_TYPE
+#define FF_API_CODER_TYPE (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_STAT_BITS
+#define FF_API_STAT_BITS (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_PRIVATE_OPT
+#define FF_API_PRIVATE_OPT (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_ASS_TIMING
+#define FF_API_ASS_TIMING (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_OLD_BSF
+#define FF_API_OLD_BSF (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_COPY_CONTEXT
+#define FF_API_COPY_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_GET_CONTEXT_DEFAULTS
+#define FF_API_GET_CONTEXT_DEFAULTS (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_NVENC_OLD_NAME
+#define FF_API_NVENC_OLD_NAME (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_STRUCT_VAAPI_CONTEXT
+#define FF_API_STRUCT_VAAPI_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_MERGE_SD_API
+#define FF_API_MERGE_SD_API (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_TAG_STRING
+#define FF_API_TAG_STRING (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_GETCHROMA
+#define FF_API_GETCHROMA (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_CODEC_GET_SET
+#define FF_API_CODEC_GET_SET (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_USER_VISIBLE_AVHWACCEL
+#define FF_API_USER_VISIBLE_AVHWACCEL (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_LOCKMGR
+#define FF_API_LOCKMGR (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_NEXT
+#define FF_API_NEXT (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+
+
+#endif /* AVCODEC_VERSION_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/attributes.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/attributes.h
new file mode 100644
index 000000000..ced108aa2
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/attributes.h
@@ -0,0 +1,167 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Macro definitions for various function/variable attributes
+ */
+
+#ifndef AVUTIL_ATTRIBUTES_H
+#define AVUTIL_ATTRIBUTES_H
+
+#ifdef __GNUC__
+# define AV_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > (x) || __GNUC__ == (x) && __GNUC_MINOR__ >= (y))
+# define AV_GCC_VERSION_AT_MOST(x,y) (__GNUC__ < (x) || __GNUC__ == (x) && __GNUC_MINOR__ <= (y))
+#else
+# define AV_GCC_VERSION_AT_LEAST(x,y) 0
+# define AV_GCC_VERSION_AT_MOST(x,y) 0
+#endif
+
+#ifndef av_always_inline
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+# define av_always_inline __attribute__((always_inline)) inline
+#elif defined(_MSC_VER)
+# define av_always_inline __forceinline
+#else
+# define av_always_inline inline
+#endif
+#endif
+
+#ifndef av_extern_inline
+#if defined(__ICL) && __ICL >= 1210 || defined(__GNUC_STDC_INLINE__)
+# define av_extern_inline extern inline
+#else
+# define av_extern_inline inline
+#endif
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,4)
+# define av_warn_unused_result __attribute__((warn_unused_result))
+#else
+# define av_warn_unused_result
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+# define av_noinline __attribute__((noinline))
+#elif defined(_MSC_VER)
+# define av_noinline __declspec(noinline)
+#else
+# define av_noinline
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,1) || defined(__clang__)
+# define av_pure __attribute__((pure))
+#else
+# define av_pure
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(2,6) || defined(__clang__)
+# define av_const __attribute__((const))
+#else
+# define av_const
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(4,3) || defined(__clang__)
+# define av_cold __attribute__((cold))
+#else
+# define av_cold
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(4,1) && !defined(__llvm__)
+# define av_flatten __attribute__((flatten))
+#else
+# define av_flatten
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+# define attribute_deprecated __attribute__((deprecated))
+#elif defined(_MSC_VER)
+# define attribute_deprecated __declspec(deprecated)
+#else
+# define attribute_deprecated
+#endif
+
+/**
+ * Disable warnings about deprecated features
+ * This is useful for sections of code kept for backward compatibility and
+ * scheduled for removal.
+ */
+#ifndef AV_NOWARN_DEPRECATED
+#if AV_GCC_VERSION_AT_LEAST(4,6)
+# define AV_NOWARN_DEPRECATED(code) \
+ _Pragma("GCC diagnostic push") \
+ _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") \
+ code \
+ _Pragma("GCC diagnostic pop")
+#elif defined(_MSC_VER)
+# define AV_NOWARN_DEPRECATED(code) \
+ __pragma(warning(push)) \
+ __pragma(warning(disable : 4996)) \
+ code; \
+ __pragma(warning(pop))
+#else
+# define AV_NOWARN_DEPRECATED(code) code
+#endif
+#endif
+
+#if defined(__GNUC__) || defined(__clang__)
+# define av_unused __attribute__((unused))
+#else
+# define av_unused
+#endif
+
+/**
+ * Mark a variable as used and prevent the compiler from optimizing it
+ * away. This is useful for variables accessed only from inline
+ * assembler without the compiler being aware.
+ */
+#if AV_GCC_VERSION_AT_LEAST(3,1) || defined(__clang__)
+# define av_used __attribute__((used))
+#else
+# define av_used
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(3,3) || defined(__clang__)
+# define av_alias __attribute__((may_alias))
+#else
+# define av_alias
+#endif
+
+#if (defined(__GNUC__) || defined(__clang__)) && !defined(__INTEL_COMPILER)
+# define av_uninit(x) x=x
+#else
+# define av_uninit(x) x
+#endif
+
+#if defined(__GNUC__) || defined(__clang__)
+# define av_builtin_constant_p __builtin_constant_p
+# define av_printf_format(fmtpos, attrpos) __attribute__((__format__(__printf__, fmtpos, attrpos)))
+#else
+# define av_builtin_constant_p(x) 0
+# define av_printf_format(fmtpos, attrpos)
+#endif
+
+#if AV_GCC_VERSION_AT_LEAST(2,5) || defined(__clang__)
+# define av_noreturn __attribute__((noreturn))
+#else
+# define av_noreturn
+#endif
+
+#endif /* AVUTIL_ATTRIBUTES_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/avconfig.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/avconfig.h
new file mode 100644
index 000000000..c289fbb55
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/avconfig.h
@@ -0,0 +1,6 @@
+/* Generated by ffmpeg configure */
+#ifndef AVUTIL_AVCONFIG_H
+#define AVUTIL_AVCONFIG_H
+#define AV_HAVE_BIGENDIAN 0
+#define AV_HAVE_FAST_UNALIGNED 1
+#endif /* AVUTIL_AVCONFIG_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/avutil.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/avutil.h
new file mode 100644
index 000000000..4d633156d
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/avutil.h
@@ -0,0 +1,365 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_AVUTIL_H
+#define AVUTIL_AVUTIL_H
+
+/**
+ * @file
+ * @ingroup lavu
+ * Convenience header that includes @ref lavu "libavutil"'s core.
+ */
+
+/**
+ * @mainpage
+ *
+ * @section ffmpeg_intro Introduction
+ *
+ * This document describes the usage of the different libraries
+ * provided by FFmpeg.
+ *
+ * @li @ref libavc "libavcodec" encoding/decoding library
+ * @li @ref lavfi "libavfilter" graph-based frame editing library
+ * @li @ref libavf "libavformat" I/O and muxing/demuxing library
+ * @li @ref lavd "libavdevice" special devices muxing/demuxing library
+ * @li @ref lavu "libavutil" common utility library
+ * @li @ref lswr "libswresample" audio resampling, format conversion and mixing
+ * @li @ref lpp "libpostproc" post processing library
+ * @li @ref libsws "libswscale" color conversion and scaling library
+ *
+ * @section ffmpeg_versioning Versioning and compatibility
+ *
+ * Each of the FFmpeg libraries contains a version.h header, which defines a
+ * major, minor and micro version number with the
+ * <em>LIBRARYNAME_VERSION_{MAJOR,MINOR,MICRO}</em> macros. The major version
+ * number is incremented with backward incompatible changes - e.g. removing
+ * parts of the public API, reordering public struct members, etc. The minor
+ * version number is incremented for backward compatible API changes or major
+ * new features - e.g. adding a new public function or a new decoder. The micro
+ * version number is incremented for smaller changes that a calling program
+ * might still want to check for - e.g. changing behavior in a previously
+ * unspecified situation.
+ *
+ * FFmpeg guarantees backward API and ABI compatibility for each library as long
+ * as its major version number is unchanged. This means that no public symbols
+ * will be removed or renamed. Types and names of the public struct members and
+ * values of public macros and enums will remain the same (unless they were
+ * explicitly declared as not part of the public API). Documented behavior will
+ * not change.
+ *
+ * In other words, any correct program that works with a given FFmpeg snapshot
+ * should work just as well without any changes with any later snapshot with the
+ * same major versions. This applies to both rebuilding the program against new
+ * FFmpeg versions or to replacing the dynamic FFmpeg libraries that a program
+ * links against.
+ *
+ * However, new public symbols may be added and new members may be appended to
+ * public structs whose size is not part of public ABI (most public structs in
+ * FFmpeg). New macros and enum values may be added. Behavior in undocumented
+ * situations may change slightly (and be documented). All those are accompanied
+ * by an entry in doc/APIchanges and incrementing either the minor or micro
+ * version number.
+ */
+
+/**
+ * @defgroup lavu libavutil
+ * Common code shared across all FFmpeg libraries.
+ *
+ * @note
+ * libavutil is designed to be modular. In most cases, in order to use the
+ * functions provided by one component of libavutil you must explicitly include
+ * the specific header containing that feature. If you are only using
+ * media-related components, you could simply include libavutil/avutil.h, which
+ * brings in most of the "core" components.
+ *
+ * @{
+ *
+ * @defgroup lavu_crypto Crypto and Hashing
+ *
+ * @{
+ * @}
+ *
+ * @defgroup lavu_math Mathematics
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_string String Manipulation
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_mem Memory Management
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_data Data Structures
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_video Video related
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_audio Audio related
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_error Error Codes
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_log Logging Facility
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup lavu_misc Other
+ *
+ * @{
+ *
+ * @defgroup preproc_misc Preprocessor String Macros
+ *
+ * @{
+ *
+ * @}
+ *
+ * @defgroup version_utils Library Version Macros
+ *
+ * @{
+ *
+ * @}
+ */
+
+
+/**
+ * @addtogroup lavu_ver
+ * @{
+ */
+
+/**
+ * Return the LIBAVUTIL_VERSION_INT constant.
+ */
+unsigned avutil_version(void);
+
+/**
+ * Return an informative version string. This usually is the actual release
+ * version number or a git commit description. This string has no fixed format
+ * and can change any time. It should never be parsed by code.
+ */
+const char *av_version_info(void);
+
+/**
+ * Return the libavutil build-time configuration.
+ */
+const char *avutil_configuration(void);
+
+/**
+ * Return the libavutil license.
+ */
+const char *avutil_license(void);
+
+/**
+ * @}
+ */
+
+/**
+ * @addtogroup lavu_media Media Type
+ * @brief Media Type
+ */
+
+enum AVMediaType {
+ AVMEDIA_TYPE_UNKNOWN = -1, ///< Usually treated as AVMEDIA_TYPE_DATA
+ AVMEDIA_TYPE_VIDEO,
+ AVMEDIA_TYPE_AUDIO,
+ AVMEDIA_TYPE_DATA, ///< Opaque data information usually continuous
+ AVMEDIA_TYPE_SUBTITLE,
+ AVMEDIA_TYPE_ATTACHMENT, ///< Opaque data information usually sparse
+ AVMEDIA_TYPE_NB
+};
+
+/**
+ * Return a string describing the media_type enum, NULL if media_type
+ * is unknown.
+ */
+const char *av_get_media_type_string(enum AVMediaType media_type);
+
+/**
+ * @defgroup lavu_const Constants
+ * @{
+ *
+ * @defgroup lavu_enc Encoding specific
+ *
+ * @note those definition should move to avcodec
+ * @{
+ */
+
+#define FF_LAMBDA_SHIFT 7
+#define FF_LAMBDA_SCALE (1<<FF_LAMBDA_SHIFT)
+#define FF_QP2LAMBDA 118 ///< factor to convert from H.263 QP to lambda
+#define FF_LAMBDA_MAX (256*128-1)
+
+#define FF_QUALITY_SCALE FF_LAMBDA_SCALE //FIXME maybe remove
+
+/**
+ * @}
+ * @defgroup lavu_time Timestamp specific
+ *
+ * FFmpeg internal timebase and timestamp definitions
+ *
+ * @{
+ */
+
+/**
+ * @brief Undefined timestamp value
+ *
+ * Usually reported by demuxer that work on containers that do not provide
+ * either pts or dts.
+ */
+
+#define AV_NOPTS_VALUE ((int64_t)UINT64_C(0x8000000000000000))
+
+/**
+ * Internal time base represented as integer
+ */
+
+#define AV_TIME_BASE 1000000
+
+/**
+ * Internal time base represented as fractional value
+ */
+
+#define AV_TIME_BASE_Q (AVRational){1, AV_TIME_BASE}
+
+/**
+ * @}
+ * @}
+ * @defgroup lavu_picture Image related
+ *
+ * AVPicture types, pixel formats and basic image planes manipulation.
+ *
+ * @{
+ */
+
+enum AVPictureType {
+ AV_PICTURE_TYPE_NONE = 0, ///< Undefined
+ AV_PICTURE_TYPE_I, ///< Intra
+ AV_PICTURE_TYPE_P, ///< Predicted
+ AV_PICTURE_TYPE_B, ///< Bi-dir predicted
+ AV_PICTURE_TYPE_S, ///< S(GMC)-VOP MPEG-4
+ AV_PICTURE_TYPE_SI, ///< Switching Intra
+ AV_PICTURE_TYPE_SP, ///< Switching Predicted
+ AV_PICTURE_TYPE_BI, ///< BI type
+};
+
+/**
+ * Return a single letter to describe the given picture type
+ * pict_type.
+ *
+ * @param[in] pict_type the picture type @return a single character
+ * representing the picture type, '?' if pict_type is unknown
+ */
+char av_get_picture_type_char(enum AVPictureType pict_type);
+
+/**
+ * @}
+ */
+
+#include "common.h"
+#include "error.h"
+#include "rational.h"
+#include "version.h"
+#include "macros.h"
+#include "mathematics.h"
+#include "log.h"
+#include "pixfmt.h"
+
+/**
+ * Return x default pointer in case p is NULL.
+ */
+static inline void *av_x_if_null(const void *p, const void *x)
+{
+ return (void *)(intptr_t)(p ? p : x);
+}
+
+/**
+ * Compute the length of an integer list.
+ *
+ * @param elsize size in bytes of each list element (only 1, 2, 4 or 8)
+ * @param term list terminator (usually 0 or -1)
+ * @param list pointer to the list
+ * @return length of the list, in elements, not counting the terminator
+ */
+unsigned av_int_list_length_for_size(unsigned elsize,
+ const void *list, uint64_t term) av_pure;
+
+/**
+ * Compute the length of an integer list.
+ *
+ * @param term list terminator (usually 0 or -1)
+ * @param list pointer to the list
+ * @return length of the list, in elements, not counting the terminator
+ */
+#define av_int_list_length(list, term) \
+ av_int_list_length_for_size(sizeof(*(list)), list, term)
+
+/**
+ * Open a file using a UTF-8 filename.
+ * The API of this function matches POSIX fopen(), errors are returned through
+ * errno.
+ */
+FILE *av_fopen_utf8(const char *path, const char *mode);
+
+/**
+ * Return the fractional representation of the internal time base.
+ */
+AVRational av_get_time_base_q(void);
+
+#define AV_FOURCC_MAX_STRING_SIZE 32
+
+#define av_fourcc2str(fourcc) av_fourcc_make_string((char[AV_FOURCC_MAX_STRING_SIZE]){0}, fourcc)
+
+/**
+ * Fill the provided buffer with a string containing a FourCC (four-character
+ * code) representation.
+ *
+ * @param buf a buffer with size in bytes of at least AV_FOURCC_MAX_STRING_SIZE
+ * @param fourcc the fourcc to represent
+ * @return the buffer in input
+ */
+char *av_fourcc_make_string(char *buf, uint32_t fourcc);
+
+/**
+ * @}
+ * @}
+ */
+
+#endif /* AVUTIL_AVUTIL_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/buffer.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/buffer.h
new file mode 100644
index 000000000..73b6bd0b1
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/buffer.h
@@ -0,0 +1,291 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @ingroup lavu_buffer
+ * refcounted data buffer API
+ */
+
+#ifndef AVUTIL_BUFFER_H
+#define AVUTIL_BUFFER_H
+
+#include <stdint.h>
+
+/**
+ * @defgroup lavu_buffer AVBuffer
+ * @ingroup lavu_data
+ *
+ * @{
+ * AVBuffer is an API for reference-counted data buffers.
+ *
+ * There are two core objects in this API -- AVBuffer and AVBufferRef. AVBuffer
+ * represents the data buffer itself; it is opaque and not meant to be accessed
+ * by the caller directly, but only through AVBufferRef. However, the caller may
+ * e.g. compare two AVBuffer pointers to check whether two different references
+ * are describing the same data buffer. AVBufferRef represents a single
+ * reference to an AVBuffer and it is the object that may be manipulated by the
+ * caller directly.
+ *
+ * There are two functions provided for creating a new AVBuffer with a single
+ * reference -- av_buffer_alloc() to just allocate a new buffer, and
+ * av_buffer_create() to wrap an existing array in an AVBuffer. From an existing
+ * reference, additional references may be created with av_buffer_ref().
+ * Use av_buffer_unref() to free a reference (this will automatically free the
+ * data once all the references are freed).
+ *
+ * The convention throughout this API and the rest of FFmpeg is such that the
+ * buffer is considered writable if there exists only one reference to it (and
+ * it has not been marked as read-only). The av_buffer_is_writable() function is
+ * provided to check whether this is true and av_buffer_make_writable() will
+ * automatically create a new writable buffer when necessary.
+ * Of course nothing prevents the calling code from violating this convention,
+ * however that is safe only when all the existing references are under its
+ * control.
+ *
+ * @note Referencing and unreferencing the buffers is thread-safe and thus
+ * may be done from multiple threads simultaneously without any need for
+ * additional locking.
+ *
+ * @note Two different references to the same buffer can point to different
+ * parts of the buffer (i.e. their AVBufferRef.data will not be equal).
+ */
+
+/**
+ * A reference counted buffer type. It is opaque and is meant to be used through
+ * references (AVBufferRef).
+ */
+typedef struct AVBuffer AVBuffer;
+
+/**
+ * A reference to a data buffer.
+ *
+ * The size of this struct is not a part of the public ABI and it is not meant
+ * to be allocated directly.
+ */
+typedef struct AVBufferRef {
+ AVBuffer *buffer;
+
+ /**
+ * The data buffer. It is considered writable if and only if
+ * this is the only reference to the buffer, in which case
+ * av_buffer_is_writable() returns 1.
+ */
+ uint8_t *data;
+ /**
+ * Size of data in bytes.
+ */
+ int size;
+} AVBufferRef;
+
+/**
+ * Allocate an AVBuffer of the given size using av_malloc().
+ *
+ * @return an AVBufferRef of given size or NULL when out of memory
+ */
+AVBufferRef *av_buffer_alloc(int size);
+
+/**
+ * Same as av_buffer_alloc(), except the returned buffer will be initialized
+ * to zero.
+ */
+AVBufferRef *av_buffer_allocz(int size);
+
+/**
+ * Always treat the buffer as read-only, even when it has only one
+ * reference.
+ */
+#define AV_BUFFER_FLAG_READONLY (1 << 0)
+
+/**
+ * Create an AVBuffer from an existing array.
+ *
+ * If this function is successful, data is owned by the AVBuffer. The caller may
+ * only access data through the returned AVBufferRef and references derived from
+ * it.
+ * If this function fails, data is left untouched.
+ * @param data data array
+ * @param size size of data in bytes
+ * @param free a callback for freeing this buffer's data
+ * @param opaque parameter to be got for processing or passed to free
+ * @param flags a combination of AV_BUFFER_FLAG_*
+ *
+ * @return an AVBufferRef referring to data on success, NULL on failure.
+ */
+AVBufferRef *av_buffer_create(uint8_t *data, int size,
+ void (*free)(void *opaque, uint8_t *data),
+ void *opaque, int flags);
+
+/**
+ * Default free callback, which calls av_free() on the buffer data.
+ * This function is meant to be passed to av_buffer_create(), not called
+ * directly.
+ */
+void av_buffer_default_free(void *opaque, uint8_t *data);
+
+/**
+ * Create a new reference to an AVBuffer.
+ *
+ * @return a new AVBufferRef referring to the same AVBuffer as buf or NULL on
+ * failure.
+ */
+AVBufferRef *av_buffer_ref(AVBufferRef *buf);
+
+/**
+ * Free a given reference and automatically free the buffer if there are no more
+ * references to it.
+ *
+ * @param buf the reference to be freed. The pointer is set to NULL on return.
+ */
+void av_buffer_unref(AVBufferRef **buf);
+
+/**
+ * @return 1 if the caller may write to the data referred to by buf (which is
+ * true if and only if buf is the only reference to the underlying AVBuffer).
+ * Return 0 otherwise.
+ * A positive answer is valid until av_buffer_ref() is called on buf.
+ */
+int av_buffer_is_writable(const AVBufferRef *buf);
+
+/**
+ * @return the opaque parameter set by av_buffer_create.
+ */
+void *av_buffer_get_opaque(const AVBufferRef *buf);
+
+int av_buffer_get_ref_count(const AVBufferRef *buf);
+
+/**
+ * Create a writable reference from a given buffer reference, avoiding data copy
+ * if possible.
+ *
+ * @param buf buffer reference to make writable. On success, buf is either left
+ * untouched, or it is unreferenced and a new writable AVBufferRef is
+ * written in its place. On failure, buf is left untouched.
+ * @return 0 on success, a negative AVERROR on failure.
+ */
+int av_buffer_make_writable(AVBufferRef **buf);
+
+/**
+ * Reallocate a given buffer.
+ *
+ * @param buf a buffer reference to reallocate. On success, buf will be
+ * unreferenced and a new reference with the required size will be
+ * written in its place. On failure buf will be left untouched. *buf
+ * may be NULL, then a new buffer is allocated.
+ * @param size required new buffer size.
+ * @return 0 on success, a negative AVERROR on failure.
+ *
+ * @note the buffer is actually reallocated with av_realloc() only if it was
+ * initially allocated through av_buffer_realloc(NULL) and there is only one
+ * reference to it (i.e. the one passed to this function). In all other cases
+ * a new buffer is allocated and the data is copied.
+ */
+int av_buffer_realloc(AVBufferRef **buf, int size);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lavu_bufferpool AVBufferPool
+ * @ingroup lavu_data
+ *
+ * @{
+ * AVBufferPool is an API for a lock-free thread-safe pool of AVBuffers.
+ *
+ * Frequently allocating and freeing large buffers may be slow. AVBufferPool is
+ * meant to solve this in cases when the caller needs a set of buffers of the
+ * same size (the most obvious use case being buffers for raw video or audio
+ * frames).
+ *
+ * At the beginning, the user must call av_buffer_pool_init() to create the
+ * buffer pool. Then whenever a buffer is needed, call av_buffer_pool_get() to
+ * get a reference to a new buffer, similar to av_buffer_alloc(). This new
+ * reference works in all aspects the same way as the one created by
+ * av_buffer_alloc(). However, when the last reference to this buffer is
+ * unreferenced, it is returned to the pool instead of being freed and will be
+ * reused for subsequent av_buffer_pool_get() calls.
+ *
+ * When the caller is done with the pool and no longer needs to allocate any new
+ * buffers, av_buffer_pool_uninit() must be called to mark the pool as freeable.
+ * Once all the buffers are released, it will automatically be freed.
+ *
+ * Allocating and releasing buffers with this API is thread-safe as long as
+ * either the default alloc callback is used, or the user-supplied one is
+ * thread-safe.
+ */
+
+/**
+ * The buffer pool. This structure is opaque and not meant to be accessed
+ * directly. It is allocated with av_buffer_pool_init() and freed with
+ * av_buffer_pool_uninit().
+ */
+typedef struct AVBufferPool AVBufferPool;
+
+/**
+ * Allocate and initialize a buffer pool.
+ *
+ * @param size size of each buffer in this pool
+ * @param alloc a function that will be used to allocate new buffers when the
+ * pool is empty. May be NULL, then the default allocator will be used
+ * (av_buffer_alloc()).
+ * @return newly created buffer pool on success, NULL on error.
+ */
+AVBufferPool *av_buffer_pool_init(int size, AVBufferRef* (*alloc)(int size));
+
+/**
+ * Allocate and initialize a buffer pool with a more complex allocator.
+ *
+ * @param size size of each buffer in this pool
+ * @param opaque arbitrary user data used by the allocator
+ * @param alloc a function that will be used to allocate new buffers when the
+ * pool is empty.
+ * @param pool_free a function that will be called immediately before the pool
+ * is freed. I.e. after av_buffer_pool_uninit() is called
+ * by the caller and all the frames are returned to the pool
+ * and freed. It is intended to uninitialize the user opaque
+ * data.
+ * @return newly created buffer pool on success, NULL on error.
+ */
+AVBufferPool *av_buffer_pool_init2(int size, void *opaque,
+ AVBufferRef* (*alloc)(void *opaque, int size),
+ void (*pool_free)(void *opaque));
+
+/**
+ * Mark the pool as being available for freeing. It will actually be freed only
+ * once all the allocated buffers associated with the pool are released. Thus it
+ * is safe to call this function while some of the allocated buffers are still
+ * in use.
+ *
+ * @param pool pointer to the pool to be freed. It will be set to NULL.
+ */
+void av_buffer_pool_uninit(AVBufferPool **pool);
+
+/**
+ * Allocate a new AVBuffer, reusing an old buffer from the pool when available.
+ * This function may be called simultaneously from multiple threads.
+ *
+ * @return a reference to the new buffer on success, NULL on error.
+ */
+AVBufferRef *av_buffer_pool_get(AVBufferPool *pool);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_BUFFER_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/channel_layout.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/channel_layout.h
new file mode 100644
index 000000000..50bb8f03c
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/channel_layout.h
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ * Copyright (c) 2008 Peter Ross
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_CHANNEL_LAYOUT_H
+#define AVUTIL_CHANNEL_LAYOUT_H
+
+#include <stdint.h>
+
+/**
+ * @file
+ * audio channel layout utility functions
+ */
+
+/**
+ * @addtogroup lavu_audio
+ * @{
+ */
+
+/**
+ * @defgroup channel_masks Audio channel masks
+ *
+ * A channel layout is a 64-bits integer with a bit set for every channel.
+ * The number of bits set must be equal to the number of channels.
+ * The value 0 means that the channel layout is not known.
+ * @note this data structure is not powerful enough to handle channels
+ * combinations that have the same channel multiple times, such as
+ * dual-mono.
+ *
+ * @{
+ */
+#define AV_CH_FRONT_LEFT 0x00000001
+#define AV_CH_FRONT_RIGHT 0x00000002
+#define AV_CH_FRONT_CENTER 0x00000004
+#define AV_CH_LOW_FREQUENCY 0x00000008
+#define AV_CH_BACK_LEFT 0x00000010
+#define AV_CH_BACK_RIGHT 0x00000020
+#define AV_CH_FRONT_LEFT_OF_CENTER 0x00000040
+#define AV_CH_FRONT_RIGHT_OF_CENTER 0x00000080
+#define AV_CH_BACK_CENTER 0x00000100
+#define AV_CH_SIDE_LEFT 0x00000200
+#define AV_CH_SIDE_RIGHT 0x00000400
+#define AV_CH_TOP_CENTER 0x00000800
+#define AV_CH_TOP_FRONT_LEFT 0x00001000
+#define AV_CH_TOP_FRONT_CENTER 0x00002000
+#define AV_CH_TOP_FRONT_RIGHT 0x00004000
+#define AV_CH_TOP_BACK_LEFT 0x00008000
+#define AV_CH_TOP_BACK_CENTER 0x00010000
+#define AV_CH_TOP_BACK_RIGHT 0x00020000
+#define AV_CH_STEREO_LEFT 0x20000000 ///< Stereo downmix.
+#define AV_CH_STEREO_RIGHT 0x40000000 ///< See AV_CH_STEREO_LEFT.
+#define AV_CH_WIDE_LEFT 0x0000000080000000ULL
+#define AV_CH_WIDE_RIGHT 0x0000000100000000ULL
+#define AV_CH_SURROUND_DIRECT_LEFT 0x0000000200000000ULL
+#define AV_CH_SURROUND_DIRECT_RIGHT 0x0000000400000000ULL
+#define AV_CH_LOW_FREQUENCY_2 0x0000000800000000ULL
+
+/** Channel mask value used for AVCodecContext.request_channel_layout
+ to indicate that the user requests the channel order of the decoder output
+ to be the native codec channel order. */
+#define AV_CH_LAYOUT_NATIVE 0x8000000000000000ULL
+
+/**
+ * @}
+ * @defgroup channel_mask_c Audio channel layouts
+ * @{
+ * */
+#define AV_CH_LAYOUT_MONO (AV_CH_FRONT_CENTER)
+#define AV_CH_LAYOUT_STEREO (AV_CH_FRONT_LEFT|AV_CH_FRONT_RIGHT)
+#define AV_CH_LAYOUT_2POINT1 (AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_2_1 (AV_CH_LAYOUT_STEREO|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_SURROUND (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER)
+#define AV_CH_LAYOUT_3POINT1 (AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_4POINT0 (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_4POINT1 (AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_2_2 (AV_CH_LAYOUT_STEREO|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT)
+#define AV_CH_LAYOUT_QUAD (AV_CH_LAYOUT_STEREO|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_5POINT0 (AV_CH_LAYOUT_SURROUND|AV_CH_SIDE_LEFT|AV_CH_SIDE_RIGHT)
+#define AV_CH_LAYOUT_5POINT1 (AV_CH_LAYOUT_5POINT0|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_5POINT0_BACK (AV_CH_LAYOUT_SURROUND|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_5POINT1_BACK (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_6POINT0 (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT0_FRONT (AV_CH_LAYOUT_2_2|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_HEXAGONAL (AV_CH_LAYOUT_5POINT0_BACK|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1 (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_BACK_CENTER)
+#define AV_CH_LAYOUT_6POINT1_FRONT (AV_CH_LAYOUT_6POINT0_FRONT|AV_CH_LOW_FREQUENCY)
+#define AV_CH_LAYOUT_7POINT0 (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_7POINT0_FRONT (AV_CH_LAYOUT_5POINT0|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_7POINT1 (AV_CH_LAYOUT_5POINT1|AV_CH_BACK_LEFT|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_7POINT1_WIDE (AV_CH_LAYOUT_5POINT1|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_7POINT1_WIDE_BACK (AV_CH_LAYOUT_5POINT1_BACK|AV_CH_FRONT_LEFT_OF_CENTER|AV_CH_FRONT_RIGHT_OF_CENTER)
+#define AV_CH_LAYOUT_OCTAGONAL (AV_CH_LAYOUT_5POINT0|AV_CH_BACK_LEFT|AV_CH_BACK_CENTER|AV_CH_BACK_RIGHT)
+#define AV_CH_LAYOUT_HEXADECAGONAL (AV_CH_LAYOUT_OCTAGONAL|AV_CH_WIDE_LEFT|AV_CH_WIDE_RIGHT|AV_CH_TOP_BACK_LEFT|AV_CH_TOP_BACK_RIGHT|AV_CH_TOP_BACK_CENTER|AV_CH_TOP_FRONT_CENTER|AV_CH_TOP_FRONT_LEFT|AV_CH_TOP_FRONT_RIGHT)
+#define AV_CH_LAYOUT_STEREO_DOWNMIX (AV_CH_STEREO_LEFT|AV_CH_STEREO_RIGHT)
+
+enum AVMatrixEncoding {
+ AV_MATRIX_ENCODING_NONE,
+ AV_MATRIX_ENCODING_DOLBY,
+ AV_MATRIX_ENCODING_DPLII,
+ AV_MATRIX_ENCODING_DPLIIX,
+ AV_MATRIX_ENCODING_DPLIIZ,
+ AV_MATRIX_ENCODING_DOLBYEX,
+ AV_MATRIX_ENCODING_DOLBYHEADPHONE,
+ AV_MATRIX_ENCODING_NB
+};
+
+/**
+ * Return a channel layout id that matches name, or 0 if no match is found.
+ *
+ * name can be one or several of the following notations,
+ * separated by '+' or '|':
+ * - the name of an usual channel layout (mono, stereo, 4.0, quad, 5.0,
+ * 5.0(side), 5.1, 5.1(side), 7.1, 7.1(wide), downmix);
+ * - the name of a single channel (FL, FR, FC, LFE, BL, BR, FLC, FRC, BC,
+ * SL, SR, TC, TFL, TFC, TFR, TBL, TBC, TBR, DL, DR);
+ * - a number of channels, in decimal, followed by 'c', yielding
+ * the default channel layout for that number of channels (@see
+ * av_get_default_channel_layout);
+ * - a channel layout mask, in hexadecimal starting with "0x" (see the
+ * AV_CH_* macros).
+ *
+ * Example: "stereo+FC" = "2c+FC" = "2c+1c" = "0x7"
+ */
+uint64_t av_get_channel_layout(const char *name);
+
+/**
+ * Return a channel layout and the number of channels based on the specified name.
+ *
+ * This function is similar to (@see av_get_channel_layout), but can also parse
+ * unknown channel layout specifications.
+ *
+ * @param[in] name channel layout specification string
+ * @param[out] channel_layout parsed channel layout (0 if unknown)
+ * @param[out] nb_channels number of channels
+ *
+ * @return 0 on success, AVERROR(EINVAL) if the parsing fails.
+ */
+int av_get_extended_channel_layout(const char *name, uint64_t* channel_layout, int* nb_channels);
+
+/**
+ * Return a description of a channel layout.
+ * If nb_channels is <= 0, it is guessed from the channel_layout.
+ *
+ * @param buf put here the string containing the channel layout
+ * @param buf_size size in bytes of the buffer
+ */
+void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout);
+
+struct AVBPrint;
+/**
+ * Append a description of a channel layout to a bprint buffer.
+ */
+void av_bprint_channel_layout(struct AVBPrint *bp, int nb_channels, uint64_t channel_layout);
+
+/**
+ * Return the number of channels in the channel layout.
+ */
+int av_get_channel_layout_nb_channels(uint64_t channel_layout);
+
+/**
+ * Return default channel layout for a given number of channels.
+ */
+int64_t av_get_default_channel_layout(int nb_channels);
+
+/**
+ * Get the index of a channel in channel_layout.
+ *
+ * @param channel a channel layout describing exactly one channel which must be
+ * present in channel_layout.
+ *
+ * @return index of channel in channel_layout on success, a negative AVERROR
+ * on error.
+ */
+int av_get_channel_layout_channel_index(uint64_t channel_layout,
+ uint64_t channel);
+
+/**
+ * Get the channel with the given index in channel_layout.
+ */
+uint64_t av_channel_layout_extract_channel(uint64_t channel_layout, int index);
+
+/**
+ * Get the name of a given channel.
+ *
+ * @return channel name on success, NULL on error.
+ */
+const char *av_get_channel_name(uint64_t channel);
+
+/**
+ * Get the description of a given channel.
+ *
+ * @param channel a channel layout with a single channel
+ * @return channel description on success, NULL on error
+ */
+const char *av_get_channel_description(uint64_t channel);
+
+/**
+ * Get the value and name of a standard channel layout.
+ *
+ * @param[in] index index in an internal list, starting at 0
+ * @param[out] layout channel layout mask
+ * @param[out] name name of the layout
+ * @return 0 if the layout exists,
+ * <0 if index is beyond the limits
+ */
+int av_get_standard_channel_layout(unsigned index, uint64_t *layout,
+ const char **name);
+
+/**
+ * @}
+ * @}
+ */
+
+#endif /* AVUTIL_CHANNEL_LAYOUT_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/common.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/common.h
new file mode 100644
index 000000000..0fffa6771
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/common.h
@@ -0,0 +1,560 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * common internal and external API header
+ */
+
+#ifndef AVUTIL_COMMON_H
+#define AVUTIL_COMMON_H
+
+#if defined(__cplusplus) && !defined(__STDC_CONSTANT_MACROS) && !defined(UINT64_C)
+#error missing -D__STDC_CONSTANT_MACROS / #define __STDC_CONSTANT_MACROS
+#endif
+
+#include <errno.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <math.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "attributes.h"
+#include "macros.h"
+#include "version.h"
+#include "libavutil/avconfig.h"
+
+#if AV_HAVE_BIGENDIAN
+# define AV_NE(be, le) (be)
+#else
+# define AV_NE(be, le) (le)
+#endif
+
+//rounded division & shift
+#define RSHIFT(a,b) ((a) > 0 ? ((a) + ((1<<(b))>>1))>>(b) : ((a) + ((1<<(b))>>1)-1)>>(b))
+/* assume b>0 */
+#define ROUNDED_DIV(a,b) (((a)>0 ? (a) + ((b)>>1) : (a) - ((b)>>1))/(b))
+/* Fast a/(1<<b) rounded toward +inf. Assume a>=0 and b>=0 */
+#define AV_CEIL_RSHIFT(a,b) (!av_builtin_constant_p(b) ? -((-(a)) >> (b)) \
+ : ((a) + (1<<(b)) - 1) >> (b))
+/* Backwards compat. */
+#define FF_CEIL_RSHIFT AV_CEIL_RSHIFT
+
+#define FFUDIV(a,b) (((a)>0 ?(a):(a)-(b)+1) / (b))
+#define FFUMOD(a,b) ((a)-(b)*FFUDIV(a,b))
+
+/**
+ * Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they
+ * are not representable as absolute values of their type. This is the same
+ * as with *abs()
+ * @see FFNABS()
+ */
+#define FFABS(a) ((a) >= 0 ? (a) : (-(a)))
+#define FFSIGN(a) ((a) > 0 ? 1 : -1)
+
+/**
+ * Negative Absolute value.
+ * this works for all integers of all types.
+ * As with many macros, this evaluates its argument twice, it thus must not have
+ * a sideeffect, that is FFNABS(x++) has undefined behavior.
+ */
+#define FFNABS(a) ((a) <= 0 ? (a) : (-(a)))
+
+/**
+ * Comparator.
+ * For two numerical expressions x and y, gives 1 if x > y, -1 if x < y, and 0
+ * if x == y. This is useful for instance in a qsort comparator callback.
+ * Furthermore, compilers are able to optimize this to branchless code, and
+ * there is no risk of overflow with signed types.
+ * As with many macros, this evaluates its argument multiple times, it thus
+ * must not have a side-effect.
+ */
+#define FFDIFFSIGN(x,y) (((x)>(y)) - ((x)<(y)))
+
+#define FFMAX(a,b) ((a) > (b) ? (a) : (b))
+#define FFMAX3(a,b,c) FFMAX(FFMAX(a,b),c)
+#define FFMIN(a,b) ((a) > (b) ? (b) : (a))
+#define FFMIN3(a,b,c) FFMIN(FFMIN(a,b),c)
+
+#define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0)
+#define FF_ARRAY_ELEMS(a) (sizeof(a) / sizeof((a)[0]))
+
+/* misc math functions */
+
+#ifdef HAVE_AV_CONFIG_H
+# include "config.h"
+# include "intmath.h"
+#endif
+
+/* Pull in unguarded fallback defines at the end of this file. */
+#include "common.h"
+
+#ifndef av_log2
+av_const int av_log2(unsigned v);
+#endif
+
+#ifndef av_log2_16bit
+av_const int av_log2_16bit(unsigned v);
+#endif
+
+/**
+ * Clip a signed integer value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const int av_clip_c(int a, int amin, int amax)
+{
+#if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2
+ if (amin > amax) abort();
+#endif
+ if (a < amin) return amin;
+ else if (a > amax) return amax;
+ else return a;
+}
+
+/**
+ * Clip a signed 64bit integer value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const int64_t av_clip64_c(int64_t a, int64_t amin, int64_t amax)
+{
+#if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2
+ if (amin > amax) abort();
+#endif
+ if (a < amin) return amin;
+ else if (a > amax) return amax;
+ else return a;
+}
+
+/**
+ * Clip a signed integer value into the 0-255 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const uint8_t av_clip_uint8_c(int a)
+{
+ if (a&(~0xFF)) return (~a)>>31;
+ else return a;
+}
+
+/**
+ * Clip a signed integer value into the -128,127 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int8_t av_clip_int8_c(int a)
+{
+ if ((a+0x80U) & ~0xFF) return (a>>31) ^ 0x7F;
+ else return a;
+}
+
+/**
+ * Clip a signed integer value into the 0-65535 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const uint16_t av_clip_uint16_c(int a)
+{
+ if (a&(~0xFFFF)) return (~a)>>31;
+ else return a;
+}
+
+/**
+ * Clip a signed integer value into the -32768,32767 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int16_t av_clip_int16_c(int a)
+{
+ if ((a+0x8000U) & ~0xFFFF) return (a>>31) ^ 0x7FFF;
+ else return a;
+}
+
+/**
+ * Clip a signed 64-bit integer value into the -2147483648,2147483647 range.
+ * @param a value to clip
+ * @return clipped value
+ */
+static av_always_inline av_const int32_t av_clipl_int32_c(int64_t a)
+{
+ if ((a+0x80000000u) & ~UINT64_C(0xFFFFFFFF)) return (int32_t)((a>>63) ^ 0x7FFFFFFF);
+ else return (int32_t)a;
+}
+
+/**
+ * Clip a signed integer into the -(2^p),(2^p-1) range.
+ * @param a value to clip
+ * @param p bit position to clip at
+ * @return clipped value
+ */
+static av_always_inline av_const int av_clip_intp2_c(int a, int p)
+{
+ if (((unsigned)a + (1 << p)) & ~((2 << p) - 1))
+ return (a >> 31) ^ ((1 << p) - 1);
+ else
+ return a;
+}
+
+/**
+ * Clip a signed integer to an unsigned power of two range.
+ * @param a value to clip
+ * @param p bit position to clip at
+ * @return clipped value
+ */
+static av_always_inline av_const unsigned av_clip_uintp2_c(int a, int p)
+{
+ if (a & ~((1<<p) - 1)) return -a >> 31 & ((1<<p) - 1);
+ else return a;
+}
+
+/**
+ * Clear high bits from an unsigned integer starting with specific bit position
+ * @param a value to clip
+ * @param p bit position to clip at
+ * @return clipped value
+ */
+static av_always_inline av_const unsigned av_mod_uintp2_c(unsigned a, unsigned p)
+{
+ return a & ((1 << p) - 1);
+}
+
+/**
+ * Add two signed 32-bit values with saturation.
+ *
+ * @param a one value
+ * @param b another value
+ * @return sum with signed saturation
+ */
+static av_always_inline int av_sat_add32_c(int a, int b)
+{
+ return av_clipl_int32((int64_t)a + b);
+}
+
+/**
+ * Add a doubled value to another value with saturation at both stages.
+ *
+ * @param a first value
+ * @param b value doubled and added to a
+ * @return sum sat(a + sat(2*b)) with signed saturation
+ */
+static av_always_inline int av_sat_dadd32_c(int a, int b)
+{
+ return av_sat_add32(a, av_sat_add32(b, b));
+}
+
+/**
+ * Subtract two signed 32-bit values with saturation.
+ *
+ * @param a one value
+ * @param b another value
+ * @return difference with signed saturation
+ */
+static av_always_inline int av_sat_sub32_c(int a, int b)
+{
+ return av_clipl_int32((int64_t)a - b);
+}
+
+/**
+ * Subtract a doubled value from another value with saturation at both stages.
+ *
+ * @param a first value
+ * @param b value doubled and subtracted from a
+ * @return difference sat(a - sat(2*b)) with signed saturation
+ */
+static av_always_inline int av_sat_dsub32_c(int a, int b)
+{
+ return av_sat_sub32(a, av_sat_add32(b, b));
+}
+
+/**
+ * Clip a float value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const float av_clipf_c(float a, float amin, float amax)
+{
+#if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2
+ if (amin > amax) abort();
+#endif
+ if (a < amin) return amin;
+ else if (a > amax) return amax;
+ else return a;
+}
+
+/**
+ * Clip a double value into the amin-amax range.
+ * @param a value to clip
+ * @param amin minimum value of the clip range
+ * @param amax maximum value of the clip range
+ * @return clipped value
+ */
+static av_always_inline av_const double av_clipd_c(double a, double amin, double amax)
+{
+#if defined(HAVE_AV_CONFIG_H) && defined(ASSERT_LEVEL) && ASSERT_LEVEL >= 2
+ if (amin > amax) abort();
+#endif
+ if (a < amin) return amin;
+ else if (a > amax) return amax;
+ else return a;
+}
+
+/** Compute ceil(log2(x)).
+ * @param x value used to compute ceil(log2(x))
+ * @return computed ceiling of log2(x)
+ */
+static av_always_inline av_const int av_ceil_log2_c(int x)
+{
+ return av_log2((x - 1) << 1);
+}
+
+/**
+ * Count number of bits set to one in x
+ * @param x value to count bits of
+ * @return the number of bits set to one in x
+ */
+static av_always_inline av_const int av_popcount_c(uint32_t x)
+{
+ x -= (x >> 1) & 0x55555555;
+ x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
+ x = (x + (x >> 4)) & 0x0F0F0F0F;
+ x += x >> 8;
+ return (x + (x >> 16)) & 0x3F;
+}
+
+/**
+ * Count number of bits set to one in x
+ * @param x value to count bits of
+ * @return the number of bits set to one in x
+ */
+static av_always_inline av_const int av_popcount64_c(uint64_t x)
+{
+ return av_popcount((uint32_t)x) + av_popcount((uint32_t)(x >> 32));
+}
+
+static av_always_inline av_const int av_parity_c(uint32_t v)
+{
+ return av_popcount(v) & 1;
+}
+
+#define MKTAG(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((unsigned)(d) << 24))
+#define MKBETAG(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((unsigned)(a) << 24))
+
+/**
+ * Convert a UTF-8 character (up to 4 bytes) to its 32-bit UCS-4 encoded form.
+ *
+ * @param val Output value, must be an lvalue of type uint32_t.
+ * @param GET_BYTE Expression reading one byte from the input.
+ * Evaluated up to 7 times (4 for the currently
+ * assigned Unicode range). With a memory buffer
+ * input, this could be *ptr++.
+ * @param ERROR Expression to be evaluated on invalid input,
+ * typically a goto statement.
+ *
+ * @warning ERROR should not contain a loop control statement which
+ * could interact with the internal while loop, and should force an
+ * exit from the macro code (e.g. through a goto or a return) in order
+ * to prevent undefined results.
+ */
+#define GET_UTF8(val, GET_BYTE, ERROR)\
+ val= (GET_BYTE);\
+ {\
+ uint32_t top = (val & 128) >> 1;\
+ if ((val & 0xc0) == 0x80 || val >= 0xFE)\
+ ERROR\
+ while (val & top) {\
+ int tmp= (GET_BYTE) - 128;\
+ if(tmp>>6)\
+ ERROR\
+ val= (val<<6) + tmp;\
+ top <<= 5;\
+ }\
+ val &= (top << 1) - 1;\
+ }
+
+/**
+ * Convert a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form.
+ *
+ * @param val Output value, must be an lvalue of type uint32_t.
+ * @param GET_16BIT Expression returning two bytes of UTF-16 data converted
+ * to native byte order. Evaluated one or two times.
+ * @param ERROR Expression to be evaluated on invalid input,
+ * typically a goto statement.
+ */
+#define GET_UTF16(val, GET_16BIT, ERROR)\
+ val = GET_16BIT;\
+ {\
+ unsigned int hi = val - 0xD800;\
+ if (hi < 0x800) {\
+ val = GET_16BIT - 0xDC00;\
+ if (val > 0x3FFU || hi > 0x3FFU)\
+ ERROR\
+ val += (hi<<10) + 0x10000;\
+ }\
+ }\
+
+/**
+ * @def PUT_UTF8(val, tmp, PUT_BYTE)
+ * Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
+ * @param val is an input-only argument and should be of type uint32_t. It holds
+ * a UCS-4 encoded Unicode character that is to be converted to UTF-8. If
+ * val is given as a function it is executed only once.
+ * @param tmp is a temporary variable and should be of type uint8_t. It
+ * represents an intermediate value during conversion that is to be
+ * output by PUT_BYTE.
+ * @param PUT_BYTE writes the converted UTF-8 bytes to any proper destination.
+ * It could be a function or a statement, and uses tmp as the input byte.
+ * For example, PUT_BYTE could be "*output++ = tmp;" PUT_BYTE will be
+ * executed up to 4 times for values in the valid UTF-8 range and up to
+ * 7 times in the general case, depending on the length of the converted
+ * Unicode character.
+ */
+#define PUT_UTF8(val, tmp, PUT_BYTE)\
+ {\
+ int bytes, shift;\
+ uint32_t in = val;\
+ if (in < 0x80) {\
+ tmp = in;\
+ PUT_BYTE\
+ } else {\
+ bytes = (av_log2(in) + 4) / 5;\
+ shift = (bytes - 1) * 6;\
+ tmp = (256 - (256 >> bytes)) | (in >> shift);\
+ PUT_BYTE\
+ while (shift >= 6) {\
+ shift -= 6;\
+ tmp = 0x80 | ((in >> shift) & 0x3f);\
+ PUT_BYTE\
+ }\
+ }\
+ }
+
+/**
+ * @def PUT_UTF16(val, tmp, PUT_16BIT)
+ * Convert a 32-bit Unicode character to its UTF-16 encoded form (2 or 4 bytes).
+ * @param val is an input-only argument and should be of type uint32_t. It holds
+ * a UCS-4 encoded Unicode character that is to be converted to UTF-16. If
+ * val is given as a function it is executed only once.
+ * @param tmp is a temporary variable and should be of type uint16_t. It
+ * represents an intermediate value during conversion that is to be
+ * output by PUT_16BIT.
+ * @param PUT_16BIT writes the converted UTF-16 data to any proper destination
+ * in desired endianness. It could be a function or a statement, and uses tmp
+ * as the input byte. For example, PUT_BYTE could be "*output++ = tmp;"
+ * PUT_BYTE will be executed 1 or 2 times depending on input character.
+ */
+#define PUT_UTF16(val, tmp, PUT_16BIT)\
+ {\
+ uint32_t in = val;\
+ if (in < 0x10000) {\
+ tmp = in;\
+ PUT_16BIT\
+ } else {\
+ tmp = 0xD800 | ((in - 0x10000) >> 10);\
+ PUT_16BIT\
+ tmp = 0xDC00 | ((in - 0x10000) & 0x3FF);\
+ PUT_16BIT\
+ }\
+ }\
+
+
+
+#include "mem.h"
+
+#ifdef HAVE_AV_CONFIG_H
+# include "internal.h"
+#endif /* HAVE_AV_CONFIG_H */
+
+#endif /* AVUTIL_COMMON_H */
+
+/*
+ * The following definitions are outside the multiple inclusion guard
+ * to ensure they are immediately available in intmath.h.
+ */
+
+#ifndef av_ceil_log2
+# define av_ceil_log2 av_ceil_log2_c
+#endif
+#ifndef av_clip
+# define av_clip av_clip_c
+#endif
+#ifndef av_clip64
+# define av_clip64 av_clip64_c
+#endif
+#ifndef av_clip_uint8
+# define av_clip_uint8 av_clip_uint8_c
+#endif
+#ifndef av_clip_int8
+# define av_clip_int8 av_clip_int8_c
+#endif
+#ifndef av_clip_uint16
+# define av_clip_uint16 av_clip_uint16_c
+#endif
+#ifndef av_clip_int16
+# define av_clip_int16 av_clip_int16_c
+#endif
+#ifndef av_clipl_int32
+# define av_clipl_int32 av_clipl_int32_c
+#endif
+#ifndef av_clip_intp2
+# define av_clip_intp2 av_clip_intp2_c
+#endif
+#ifndef av_clip_uintp2
+# define av_clip_uintp2 av_clip_uintp2_c
+#endif
+#ifndef av_mod_uintp2
+# define av_mod_uintp2 av_mod_uintp2_c
+#endif
+#ifndef av_sat_add32
+# define av_sat_add32 av_sat_add32_c
+#endif
+#ifndef av_sat_dadd32
+# define av_sat_dadd32 av_sat_dadd32_c
+#endif
+#ifndef av_sat_sub32
+# define av_sat_sub32 av_sat_sub32_c
+#endif
+#ifndef av_sat_dsub32
+# define av_sat_dsub32 av_sat_dsub32_c
+#endif
+#ifndef av_clipf
+# define av_clipf av_clipf_c
+#endif
+#ifndef av_clipd
+# define av_clipd av_clipd_c
+#endif
+#ifndef av_popcount
+# define av_popcount av_popcount_c
+#endif
+#ifndef av_popcount64
+# define av_popcount64 av_popcount64_c
+#endif
+#ifndef av_parity
+# define av_parity av_parity_c
+#endif
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/cpu.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/cpu.h
new file mode 100644
index 000000000..8bb9eb606
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/cpu.h
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_CPU_H
+#define AVUTIL_CPU_H
+
+#include <stddef.h>
+
+#include "attributes.h"
+
+#define AV_CPU_FLAG_FORCE 0x80000000 /* force usage of selected flags (OR) */
+
+ /* lower 16 bits - CPU features */
+#define AV_CPU_FLAG_MMX 0x0001 ///< standard MMX
+#define AV_CPU_FLAG_MMXEXT 0x0002 ///< SSE integer functions or AMD MMX ext
+#define AV_CPU_FLAG_MMX2 0x0002 ///< SSE integer functions or AMD MMX ext
+#define AV_CPU_FLAG_3DNOW 0x0004 ///< AMD 3DNOW
+#define AV_CPU_FLAG_SSE 0x0008 ///< SSE functions
+#define AV_CPU_FLAG_SSE2 0x0010 ///< PIV SSE2 functions
+#define AV_CPU_FLAG_SSE2SLOW 0x40000000 ///< SSE2 supported, but usually not faster
+ ///< than regular MMX/SSE (e.g. Core1)
+#define AV_CPU_FLAG_3DNOWEXT 0x0020 ///< AMD 3DNowExt
+#define AV_CPU_FLAG_SSE3 0x0040 ///< Prescott SSE3 functions
+#define AV_CPU_FLAG_SSE3SLOW 0x20000000 ///< SSE3 supported, but usually not faster
+ ///< than regular MMX/SSE (e.g. Core1)
+#define AV_CPU_FLAG_SSSE3 0x0080 ///< Conroe SSSE3 functions
+#define AV_CPU_FLAG_SSSE3SLOW 0x4000000 ///< SSSE3 supported, but usually not faster
+#define AV_CPU_FLAG_ATOM 0x10000000 ///< Atom processor, some SSSE3 instructions are slower
+#define AV_CPU_FLAG_SSE4 0x0100 ///< Penryn SSE4.1 functions
+#define AV_CPU_FLAG_SSE42 0x0200 ///< Nehalem SSE4.2 functions
+#define AV_CPU_FLAG_AESNI 0x80000 ///< Advanced Encryption Standard functions
+#define AV_CPU_FLAG_AVX 0x4000 ///< AVX functions: requires OS support even if YMM registers aren't used
+#define AV_CPU_FLAG_AVXSLOW 0x8000000 ///< AVX supported, but slow when using YMM registers (e.g. Bulldozer)
+#define AV_CPU_FLAG_XOP 0x0400 ///< Bulldozer XOP functions
+#define AV_CPU_FLAG_FMA4 0x0800 ///< Bulldozer FMA4 functions
+#define AV_CPU_FLAG_CMOV 0x1000 ///< supports cmov instruction
+#define AV_CPU_FLAG_AVX2 0x8000 ///< AVX2 functions: requires OS support even if YMM registers aren't used
+#define AV_CPU_FLAG_FMA3 0x10000 ///< Haswell FMA3 functions
+#define AV_CPU_FLAG_BMI1 0x20000 ///< Bit Manipulation Instruction Set 1
+#define AV_CPU_FLAG_BMI2 0x40000 ///< Bit Manipulation Instruction Set 2
+#define AV_CPU_FLAG_AVX512 0x100000 ///< AVX-512 functions: requires OS support even if YMM/ZMM registers aren't used
+
+#define AV_CPU_FLAG_ALTIVEC 0x0001 ///< standard
+#define AV_CPU_FLAG_VSX 0x0002 ///< ISA 2.06
+#define AV_CPU_FLAG_POWER8 0x0004 ///< ISA 2.07
+
+#define AV_CPU_FLAG_ARMV5TE (1 << 0)
+#define AV_CPU_FLAG_ARMV6 (1 << 1)
+#define AV_CPU_FLAG_ARMV6T2 (1 << 2)
+#define AV_CPU_FLAG_VFP (1 << 3)
+#define AV_CPU_FLAG_VFPV3 (1 << 4)
+#define AV_CPU_FLAG_NEON (1 << 5)
+#define AV_CPU_FLAG_ARMV8 (1 << 6)
+#define AV_CPU_FLAG_VFP_VM (1 << 7) ///< VFPv2 vector mode, deprecated in ARMv7-A and unavailable in various CPUs implementations
+#define AV_CPU_FLAG_SETEND (1 <<16)
+
+/**
+ * Return the flags which specify extensions supported by the CPU.
+ * The returned value is affected by av_force_cpu_flags() if that was used
+ * before. So av_get_cpu_flags() can easily be used in an application to
+ * detect the enabled cpu flags.
+ */
+int av_get_cpu_flags(void);
+
+/**
+ * Disables cpu detection and forces the specified flags.
+ * -1 is a special case that disables forcing of specific flags.
+ */
+void av_force_cpu_flags(int flags);
+
+/**
+ * Set a mask on flags returned by av_get_cpu_flags().
+ * This function is mainly useful for testing.
+ * Please use av_force_cpu_flags() and av_get_cpu_flags() instead which are more flexible
+ */
+attribute_deprecated void av_set_cpu_flags_mask(int mask);
+
+/**
+ * Parse CPU flags from a string.
+ *
+ * The returned flags contain the specified flags as well as related unspecified flags.
+ *
+ * This function exists only for compatibility with libav.
+ * Please use av_parse_cpu_caps() when possible.
+ * @return a combination of AV_CPU_* flags, negative on error.
+ */
+attribute_deprecated
+int av_parse_cpu_flags(const char *s);
+
+/**
+ * Parse CPU caps from a string and update the given AV_CPU_* flags based on that.
+ *
+ * @return negative on error.
+ */
+int av_parse_cpu_caps(unsigned *flags, const char *s);
+
+/**
+ * @return the number of logical CPU cores present.
+ */
+int av_cpu_count(void);
+
+/**
+ * Get the maximum data alignment that may be required by FFmpeg.
+ *
+ * Note that this is affected by the build configuration and the CPU flags mask,
+ * so e.g. if the CPU supports AVX, but libavutil has been built with
+ * --disable-avx or the AV_CPU_FLAG_AVX flag has been disabled through
+ * av_set_cpu_flags_mask(), then this function will behave as if AVX is not
+ * present.
+ */
+size_t av_cpu_max_align(void);
+
+#endif /* AVUTIL_CPU_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/dict.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/dict.h
new file mode 100644
index 000000000..118f1f00e
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/dict.h
@@ -0,0 +1,200 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * Public dictionary API.
+ * @deprecated
+ * AVDictionary is provided for compatibility with libav. It is both in
+ * implementation as well as API inefficient. It does not scale and is
+ * extremely slow with large dictionaries.
+ * It is recommended that new code uses our tree container from tree.c/h
+ * where applicable, which uses AVL trees to achieve O(log n) performance.
+ */
+
+#ifndef AVUTIL_DICT_H
+#define AVUTIL_DICT_H
+
+#include <stdint.h>
+
+#include "version.h"
+
+/**
+ * @addtogroup lavu_dict AVDictionary
+ * @ingroup lavu_data
+ *
+ * @brief Simple key:value store
+ *
+ * @{
+ * Dictionaries are used for storing key:value pairs. To create
+ * an AVDictionary, simply pass an address of a NULL pointer to
+ * av_dict_set(). NULL can be used as an empty dictionary wherever
+ * a pointer to an AVDictionary is required.
+ * Use av_dict_get() to retrieve an entry or iterate over all
+ * entries and finally av_dict_free() to free the dictionary
+ * and all its contents.
+ *
+ @code
+ AVDictionary *d = NULL; // "create" an empty dictionary
+ AVDictionaryEntry *t = NULL;
+
+ av_dict_set(&d, "foo", "bar", 0); // add an entry
+
+ char *k = av_strdup("key"); // if your strings are already allocated,
+ char *v = av_strdup("value"); // you can avoid copying them like this
+ av_dict_set(&d, k, v, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL);
+
+ while (t = av_dict_get(d, "", t, AV_DICT_IGNORE_SUFFIX)) {
+ <....> // iterate over all entries in d
+ }
+ av_dict_free(&d);
+ @endcode
+ */
+
+#define AV_DICT_MATCH_CASE 1 /**< Only get an entry with exact-case key match. Only relevant in av_dict_get(). */
+#define AV_DICT_IGNORE_SUFFIX 2 /**< Return first entry in a dictionary whose first part corresponds to the search key,
+ ignoring the suffix of the found key string. Only relevant in av_dict_get(). */
+#define AV_DICT_DONT_STRDUP_KEY 4 /**< Take ownership of a key that's been
+ allocated with av_malloc() or another memory allocation function. */
+#define AV_DICT_DONT_STRDUP_VAL 8 /**< Take ownership of a value that's been
+ allocated with av_malloc() or another memory allocation function. */
+#define AV_DICT_DONT_OVERWRITE 16 ///< Don't overwrite existing entries.
+#define AV_DICT_APPEND 32 /**< If the entry already exists, append to it. Note that no
+ delimiter is added, the strings are simply concatenated. */
+#define AV_DICT_MULTIKEY 64 /**< Allow to store several equal keys in the dictionary */
+
+typedef struct AVDictionaryEntry {
+ char *key;
+ char *value;
+} AVDictionaryEntry;
+
+typedef struct AVDictionary AVDictionary;
+
+/**
+ * Get a dictionary entry with matching key.
+ *
+ * The returned entry key or value must not be changed, or it will
+ * cause undefined behavior.
+ *
+ * To iterate through all the dictionary entries, you can set the matching key
+ * to the null string "" and set the AV_DICT_IGNORE_SUFFIX flag.
+ *
+ * @param prev Set to the previous matching element to find the next.
+ * If set to NULL the first matching element is returned.
+ * @param key matching key
+ * @param flags a collection of AV_DICT_* flags controlling how the entry is retrieved
+ * @return found entry or NULL in case no matching entry was found in the dictionary
+ */
+AVDictionaryEntry *av_dict_get(const AVDictionary *m, const char *key,
+ const AVDictionaryEntry *prev, int flags);
+
+/**
+ * Get number of entries in dictionary.
+ *
+ * @param m dictionary
+ * @return number of entries in dictionary
+ */
+int av_dict_count(const AVDictionary *m);
+
+/**
+ * Set the given entry in *pm, overwriting an existing entry.
+ *
+ * Note: If AV_DICT_DONT_STRDUP_KEY or AV_DICT_DONT_STRDUP_VAL is set,
+ * these arguments will be freed on error.
+ *
+ * Warning: Adding a new entry to a dictionary invalidates all existing entries
+ * previously returned with av_dict_get.
+ *
+ * @param pm pointer to a pointer to a dictionary struct. If *pm is NULL
+ * a dictionary struct is allocated and put in *pm.
+ * @param key entry key to add to *pm (will either be av_strduped or added as a new key depending on flags)
+ * @param value entry value to add to *pm (will be av_strduped or added as a new key depending on flags).
+ * Passing a NULL value will cause an existing entry to be deleted.
+ * @return >= 0 on success otherwise an error code <0
+ */
+int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags);
+
+/**
+ * Convenience wrapper for av_dict_set that converts the value to a string
+ * and stores it.
+ *
+ * Note: If AV_DICT_DONT_STRDUP_KEY is set, key will be freed on error.
+ */
+int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags);
+
+/**
+ * Parse the key/value pairs list and add the parsed entries to a dictionary.
+ *
+ * In case of failure, all the successfully set entries are stored in
+ * *pm. You may need to manually free the created dictionary.
+ *
+ * @param key_val_sep a 0-terminated list of characters used to separate
+ * key from value
+ * @param pairs_sep a 0-terminated list of characters used to separate
+ * two pairs from each other
+ * @param flags flags to use when adding to dictionary.
+ * AV_DICT_DONT_STRDUP_KEY and AV_DICT_DONT_STRDUP_VAL
+ * are ignored since the key/value tokens will always
+ * be duplicated.
+ * @return 0 on success, negative AVERROR code on failure
+ */
+int av_dict_parse_string(AVDictionary **pm, const char *str,
+ const char *key_val_sep, const char *pairs_sep,
+ int flags);
+
+/**
+ * Copy entries from one AVDictionary struct into another.
+ * @param dst pointer to a pointer to a AVDictionary struct. If *dst is NULL,
+ * this function will allocate a struct for you and put it in *dst
+ * @param src pointer to source AVDictionary struct
+ * @param flags flags to use when setting entries in *dst
+ * @note metadata is read using the AV_DICT_IGNORE_SUFFIX flag
+ * @return 0 on success, negative AVERROR code on failure. If dst was allocated
+ * by this function, callers should free the associated memory.
+ */
+int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags);
+
+/**
+ * Free all the memory allocated for an AVDictionary struct
+ * and all keys and values.
+ */
+void av_dict_free(AVDictionary **m);
+
+/**
+ * Get dictionary entries as a string.
+ *
+ * Create a string containing dictionary's entries.
+ * Such string may be passed back to av_dict_parse_string().
+ * @note String is escaped with backslashes ('\').
+ *
+ * @param[in] m dictionary
+ * @param[out] buffer Pointer to buffer that will be allocated with string containg entries.
+ * Buffer must be freed by the caller when is no longer needed.
+ * @param[in] key_val_sep character used to separate key from value
+ * @param[in] pairs_sep character used to separate two pairs from each other
+ * @return >= 0 on success, negative on error
+ * @warning Separators cannot be neither '\\' nor '\0'. They also cannot be the same.
+ */
+int av_dict_get_string(const AVDictionary *m, char **buffer,
+ const char key_val_sep, const char pairs_sep);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_DICT_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/error.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/error.h
new file mode 100644
index 000000000..71df4da35
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/error.h
@@ -0,0 +1,126 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * error code definitions
+ */
+
+#ifndef AVUTIL_ERROR_H
+#define AVUTIL_ERROR_H
+
+#include <errno.h>
+#include <stddef.h>
+
+/**
+ * @addtogroup lavu_error
+ *
+ * @{
+ */
+
+
+/* error handling */
+#if EDOM > 0
+#define AVERROR(e) (-(e)) ///< Returns a negative error code from a POSIX error code, to return from library functions.
+#define AVUNERROR(e) (-(e)) ///< Returns a POSIX error code from a library function error return value.
+#else
+/* Some platforms have E* and errno already negated. */
+#define AVERROR(e) (e)
+#define AVUNERROR(e) (e)
+#endif
+
+#define FFERRTAG(a, b, c, d) (-(int)MKTAG(a, b, c, d))
+
+#define AVERROR_BSF_NOT_FOUND FFERRTAG(0xF8,'B','S','F') ///< Bitstream filter not found
+#define AVERROR_BUG FFERRTAG( 'B','U','G','!') ///< Internal bug, also see AVERROR_BUG2
+#define AVERROR_BUFFER_TOO_SMALL FFERRTAG( 'B','U','F','S') ///< Buffer too small
+#define AVERROR_DECODER_NOT_FOUND FFERRTAG(0xF8,'D','E','C') ///< Decoder not found
+#define AVERROR_DEMUXER_NOT_FOUND FFERRTAG(0xF8,'D','E','M') ///< Demuxer not found
+#define AVERROR_ENCODER_NOT_FOUND FFERRTAG(0xF8,'E','N','C') ///< Encoder not found
+#define AVERROR_EOF FFERRTAG( 'E','O','F',' ') ///< End of file
+#define AVERROR_EXIT FFERRTAG( 'E','X','I','T') ///< Immediate exit was requested; the called function should not be restarted
+#define AVERROR_EXTERNAL FFERRTAG( 'E','X','T',' ') ///< Generic error in an external library
+#define AVERROR_FILTER_NOT_FOUND FFERRTAG(0xF8,'F','I','L') ///< Filter not found
+#define AVERROR_INVALIDDATA FFERRTAG( 'I','N','D','A') ///< Invalid data found when processing input
+#define AVERROR_MUXER_NOT_FOUND FFERRTAG(0xF8,'M','U','X') ///< Muxer not found
+#define AVERROR_OPTION_NOT_FOUND FFERRTAG(0xF8,'O','P','T') ///< Option not found
+#define AVERROR_PATCHWELCOME FFERRTAG( 'P','A','W','E') ///< Not yet implemented in FFmpeg, patches welcome
+#define AVERROR_PROTOCOL_NOT_FOUND FFERRTAG(0xF8,'P','R','O') ///< Protocol not found
+
+#define AVERROR_STREAM_NOT_FOUND FFERRTAG(0xF8,'S','T','R') ///< Stream not found
+/**
+ * This is semantically identical to AVERROR_BUG
+ * it has been introduced in Libav after our AVERROR_BUG and with a modified value.
+ */
+#define AVERROR_BUG2 FFERRTAG( 'B','U','G',' ')
+#define AVERROR_UNKNOWN FFERRTAG( 'U','N','K','N') ///< Unknown error, typically from an external library
+#define AVERROR_EXPERIMENTAL (-0x2bb2afa8) ///< Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it.
+#define AVERROR_INPUT_CHANGED (-0x636e6701) ///< Input changed between calls. Reconfiguration is required. (can be OR-ed with AVERROR_OUTPUT_CHANGED)
+#define AVERROR_OUTPUT_CHANGED (-0x636e6702) ///< Output changed between calls. Reconfiguration is required. (can be OR-ed with AVERROR_INPUT_CHANGED)
+/* HTTP & RTSP errors */
+#define AVERROR_HTTP_BAD_REQUEST FFERRTAG(0xF8,'4','0','0')
+#define AVERROR_HTTP_UNAUTHORIZED FFERRTAG(0xF8,'4','0','1')
+#define AVERROR_HTTP_FORBIDDEN FFERRTAG(0xF8,'4','0','3')
+#define AVERROR_HTTP_NOT_FOUND FFERRTAG(0xF8,'4','0','4')
+#define AVERROR_HTTP_OTHER_4XX FFERRTAG(0xF8,'4','X','X')
+#define AVERROR_HTTP_SERVER_ERROR FFERRTAG(0xF8,'5','X','X')
+
+#define AV_ERROR_MAX_STRING_SIZE 64
+
+/**
+ * Put a description of the AVERROR code errnum in errbuf.
+ * In case of failure the global variable errno is set to indicate the
+ * error. Even in case of failure av_strerror() will print a generic
+ * error message indicating the errnum provided to errbuf.
+ *
+ * @param errnum error code to describe
+ * @param errbuf buffer to which description is written
+ * @param errbuf_size the size in bytes of errbuf
+ * @return 0 on success, a negative value if a description for errnum
+ * cannot be found
+ */
+int av_strerror(int errnum, char *errbuf, size_t errbuf_size);
+
+/**
+ * Fill the provided buffer with a string containing an error string
+ * corresponding to the AVERROR code errnum.
+ *
+ * @param errbuf a buffer
+ * @param errbuf_size size in bytes of errbuf
+ * @param errnum error code to describe
+ * @return the buffer in input, filled with the error description
+ * @see av_strerror()
+ */
+static inline char *av_make_error_string(char *errbuf, size_t errbuf_size, int errnum)
+{
+ av_strerror(errnum, errbuf, errbuf_size);
+ return errbuf;
+}
+
+/**
+ * Convenience macro, the return value should be used only directly in
+ * function arguments but never stand-alone.
+ */
+#define av_err2str(errnum) \
+ av_make_error_string((char[AV_ERROR_MAX_STRING_SIZE]){0}, AV_ERROR_MAX_STRING_SIZE, errnum)
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_ERROR_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/frame.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/frame.h
new file mode 100644
index 000000000..9d57d6ce6
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/frame.h
@@ -0,0 +1,893 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @ingroup lavu_frame
+ * reference-counted frame API
+ */
+
+#ifndef AVUTIL_FRAME_H
+#define AVUTIL_FRAME_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "avutil.h"
+#include "buffer.h"
+#include "dict.h"
+#include "rational.h"
+#include "samplefmt.h"
+#include "pixfmt.h"
+#include "version.h"
+
+
+/**
+ * @defgroup lavu_frame AVFrame
+ * @ingroup lavu_data
+ *
+ * @{
+ * AVFrame is an abstraction for reference-counted raw multimedia data.
+ */
+
+enum AVFrameSideDataType {
+ /**
+ * The data is the AVPanScan struct defined in libavcodec.
+ */
+ AV_FRAME_DATA_PANSCAN,
+ /**
+ * ATSC A53 Part 4 Closed Captions.
+ * A53 CC bitstream is stored as uint8_t in AVFrameSideData.data.
+ * The number of bytes of CC data is AVFrameSideData.size.
+ */
+ AV_FRAME_DATA_A53_CC,
+ /**
+ * Stereoscopic 3d metadata.
+ * The data is the AVStereo3D struct defined in libavutil/stereo3d.h.
+ */
+ AV_FRAME_DATA_STEREO3D,
+ /**
+ * The data is the AVMatrixEncoding enum defined in libavutil/channel_layout.h.
+ */
+ AV_FRAME_DATA_MATRIXENCODING,
+ /**
+ * Metadata relevant to a downmix procedure.
+ * The data is the AVDownmixInfo struct defined in libavutil/downmix_info.h.
+ */
+ AV_FRAME_DATA_DOWNMIX_INFO,
+ /**
+ * ReplayGain information in the form of the AVReplayGain struct.
+ */
+ AV_FRAME_DATA_REPLAYGAIN,
+ /**
+ * This side data contains a 3x3 transformation matrix describing an affine
+ * transformation that needs to be applied to the frame for correct
+ * presentation.
+ *
+ * See libavutil/display.h for a detailed description of the data.
+ */
+ AV_FRAME_DATA_DISPLAYMATRIX,
+ /**
+ * Active Format Description data consisting of a single byte as specified
+ * in ETSI TS 101 154 using AVActiveFormatDescription enum.
+ */
+ AV_FRAME_DATA_AFD,
+ /**
+ * Motion vectors exported by some codecs (on demand through the export_mvs
+ * flag set in the libavcodec AVCodecContext flags2 option).
+ * The data is the AVMotionVector struct defined in
+ * libavutil/motion_vector.h.
+ */
+ AV_FRAME_DATA_MOTION_VECTORS,
+ /**
+ * Recommmends skipping the specified number of samples. This is exported
+ * only if the "skip_manual" AVOption is set in libavcodec.
+ * This has the same format as AV_PKT_DATA_SKIP_SAMPLES.
+ * @code
+ * u32le number of samples to skip from start of this packet
+ * u32le number of samples to skip from end of this packet
+ * u8 reason for start skip
+ * u8 reason for end skip (0=padding silence, 1=convergence)
+ * @endcode
+ */
+ AV_FRAME_DATA_SKIP_SAMPLES,
+ /**
+ * This side data must be associated with an audio frame and corresponds to
+ * enum AVAudioServiceType defined in avcodec.h.
+ */
+ AV_FRAME_DATA_AUDIO_SERVICE_TYPE,
+ /**
+ * Mastering display metadata associated with a video frame. The payload is
+ * an AVMasteringDisplayMetadata type and contains information about the
+ * mastering display color volume.
+ */
+ AV_FRAME_DATA_MASTERING_DISPLAY_METADATA,
+ /**
+ * The GOP timecode in 25 bit timecode format. Data format is 64-bit integer.
+ * This is set on the first frame of a GOP that has a temporal reference of 0.
+ */
+ AV_FRAME_DATA_GOP_TIMECODE,
+
+ /**
+ * The data represents the AVSphericalMapping structure defined in
+ * libavutil/spherical.h.
+ */
+ AV_FRAME_DATA_SPHERICAL,
+
+ /**
+ * Content light level (based on CTA-861.3). This payload contains data in
+ * the form of the AVContentLightMetadata struct.
+ */
+ AV_FRAME_DATA_CONTENT_LIGHT_LEVEL,
+
+ /**
+ * The data contains an ICC profile as an opaque octet buffer following the
+ * format described by ISO 15076-1 with an optional name defined in the
+ * metadata key entry "name".
+ */
+ AV_FRAME_DATA_ICC_PROFILE,
+
+#if FF_API_FRAME_QP
+ /**
+ * Implementation-specific description of the format of AV_FRAME_QP_TABLE_DATA.
+ * The contents of this side data are undocumented and internal; use
+ * av_frame_set_qp_table() and av_frame_get_qp_table() to access this in a
+ * meaningful way instead.
+ */
+ AV_FRAME_DATA_QP_TABLE_PROPERTIES,
+
+ /**
+ * Raw QP table data. Its format is described by
+ * AV_FRAME_DATA_QP_TABLE_PROPERTIES. Use av_frame_set_qp_table() and
+ * av_frame_get_qp_table() to access this instead.
+ */
+ AV_FRAME_DATA_QP_TABLE_DATA,
+#endif
+};
+
+enum AVActiveFormatDescription {
+ AV_AFD_SAME = 8,
+ AV_AFD_4_3 = 9,
+ AV_AFD_16_9 = 10,
+ AV_AFD_14_9 = 11,
+ AV_AFD_4_3_SP_14_9 = 13,
+ AV_AFD_16_9_SP_14_9 = 14,
+ AV_AFD_SP_4_3 = 15,
+};
+
+
+/**
+ * Structure to hold side data for an AVFrame.
+ *
+ * sizeof(AVFrameSideData) is not a part of the public ABI, so new fields may be added
+ * to the end with a minor bump.
+ */
+typedef struct AVFrameSideData {
+ enum AVFrameSideDataType type;
+ uint8_t *data;
+ int size;
+ AVDictionary *metadata;
+ AVBufferRef *buf;
+} AVFrameSideData;
+
+/**
+ * This structure describes decoded (raw) audio or video data.
+ *
+ * AVFrame must be allocated using av_frame_alloc(). Note that this only
+ * allocates the AVFrame itself, the buffers for the data must be managed
+ * through other means (see below).
+ * AVFrame must be freed with av_frame_free().
+ *
+ * AVFrame is typically allocated once and then reused multiple times to hold
+ * different data (e.g. a single AVFrame to hold frames received from a
+ * decoder). In such a case, av_frame_unref() will free any references held by
+ * the frame and reset it to its original clean state before it
+ * is reused again.
+ *
+ * The data described by an AVFrame is usually reference counted through the
+ * AVBuffer API. The underlying buffer references are stored in AVFrame.buf /
+ * AVFrame.extended_buf. An AVFrame is considered to be reference counted if at
+ * least one reference is set, i.e. if AVFrame.buf[0] != NULL. In such a case,
+ * every single data plane must be contained in one of the buffers in
+ * AVFrame.buf or AVFrame.extended_buf.
+ * There may be a single buffer for all the data, or one separate buffer for
+ * each plane, or anything in between.
+ *
+ * sizeof(AVFrame) is not a part of the public ABI, so new fields may be added
+ * to the end with a minor bump.
+ *
+ * Fields can be accessed through AVOptions, the name string used, matches the
+ * C structure field name for fields accessible through AVOptions. The AVClass
+ * for AVFrame can be obtained from avcodec_get_frame_class()
+ */
+typedef struct AVFrame {
+#define AV_NUM_DATA_POINTERS 8
+ /**
+ * pointer to the picture/channel planes.
+ * This might be different from the first allocated byte
+ *
+ * Some decoders access areas outside 0,0 - width,height, please
+ * see avcodec_align_dimensions2(). Some filters and swscale can read
+ * up to 16 bytes beyond the planes, if these filters are to be used,
+ * then 16 extra bytes must be allocated.
+ *
+ * NOTE: Except for hwaccel formats, pointers not needed by the format
+ * MUST be set to NULL.
+ */
+ uint8_t *data[AV_NUM_DATA_POINTERS];
+
+ /**
+ * For video, size in bytes of each picture line.
+ * For audio, size in bytes of each plane.
+ *
+ * For audio, only linesize[0] may be set. For planar audio, each channel
+ * plane must be the same size.
+ *
+ * For video the linesizes should be multiples of the CPUs alignment
+ * preference, this is 16 or 32 for modern desktop CPUs.
+ * Some code requires such alignment other code can be slower without
+ * correct alignment, for yet other it makes no difference.
+ *
+ * @note The linesize may be larger than the size of usable data -- there
+ * may be extra padding present for performance reasons.
+ */
+ int linesize[AV_NUM_DATA_POINTERS];
+
+ /**
+ * pointers to the data planes/channels.
+ *
+ * For video, this should simply point to data[].
+ *
+ * For planar audio, each channel has a separate data pointer, and
+ * linesize[0] contains the size of each channel buffer.
+ * For packed audio, there is just one data pointer, and linesize[0]
+ * contains the total size of the buffer for all channels.
+ *
+ * Note: Both data and extended_data should always be set in a valid frame,
+ * but for planar audio with more channels that can fit in data,
+ * extended_data must be used in order to access all channels.
+ */
+ uint8_t **extended_data;
+
+ /**
+ * @name Video dimensions
+ * Video frames only. The coded dimensions (in pixels) of the video frame,
+ * i.e. the size of the rectangle that contains some well-defined values.
+ *
+ * @note The part of the frame intended for display/presentation is further
+ * restricted by the @ref cropping "Cropping rectangle".
+ * @{
+ */
+ int width, height;
+ /**
+ * @}
+ */
+
+ /**
+ * number of audio samples (per channel) described by this frame
+ */
+ int nb_samples;
+
+ /**
+ * format of the frame, -1 if unknown or unset
+ * Values correspond to enum AVPixelFormat for video frames,
+ * enum AVSampleFormat for audio)
+ */
+ int format;
+
+ /**
+ * 1 -> keyframe, 0-> not
+ */
+ int key_frame;
+
+ /**
+ * Picture type of the frame.
+ */
+ enum AVPictureType pict_type;
+
+ /**
+ * Sample aspect ratio for the video frame, 0/1 if unknown/unspecified.
+ */
+ AVRational sample_aspect_ratio;
+
+ /**
+ * Presentation timestamp in time_base units (time when frame should be shown to user).
+ */
+ int64_t pts;
+
+#if FF_API_PKT_PTS
+ /**
+ * PTS copied from the AVPacket that was decoded to produce this frame.
+ * @deprecated use the pts field instead
+ */
+ attribute_deprecated
+ int64_t pkt_pts;
+#endif
+
+ /**
+ * DTS copied from the AVPacket that triggered returning this frame. (if frame threading isn't used)
+ * This is also the Presentation time of this AVFrame calculated from
+ * only AVPacket.dts values without pts values.
+ */
+ int64_t pkt_dts;
+
+ /**
+ * picture number in bitstream order
+ */
+ int coded_picture_number;
+ /**
+ * picture number in display order
+ */
+ int display_picture_number;
+
+ /**
+ * quality (between 1 (good) and FF_LAMBDA_MAX (bad))
+ */
+ int quality;
+
+ /**
+ * for some private data of the user
+ */
+ void *opaque;
+
+#if FF_API_ERROR_FRAME
+ /**
+ * @deprecated unused
+ */
+ attribute_deprecated
+ uint64_t error[AV_NUM_DATA_POINTERS];
+#endif
+
+ /**
+ * When decoding, this signals how much the picture must be delayed.
+ * extra_delay = repeat_pict / (2*fps)
+ */
+ int repeat_pict;
+
+ /**
+ * The content of the picture is interlaced.
+ */
+ int interlaced_frame;
+
+ /**
+ * If the content is interlaced, is top field displayed first.
+ */
+ int top_field_first;
+
+ /**
+ * Tell user application that palette has changed from previous frame.
+ */
+ int palette_has_changed;
+
+ /**
+ * reordered opaque 64 bits (generally an integer or a double precision float
+ * PTS but can be anything).
+ * The user sets AVCodecContext.reordered_opaque to represent the input at
+ * that time,
+ * the decoder reorders values as needed and sets AVFrame.reordered_opaque
+ * to exactly one of the values provided by the user through AVCodecContext.reordered_opaque
+ * @deprecated in favor of pkt_pts
+ */
+ int64_t reordered_opaque;
+
+ /**
+ * Sample rate of the audio data.
+ */
+ int sample_rate;
+
+ /**
+ * Channel layout of the audio data.
+ */
+ uint64_t channel_layout;
+
+ /**
+ * AVBuffer references backing the data for this frame. If all elements of
+ * this array are NULL, then this frame is not reference counted. This array
+ * must be filled contiguously -- if buf[i] is non-NULL then buf[j] must
+ * also be non-NULL for all j < i.
+ *
+ * There may be at most one AVBuffer per data plane, so for video this array
+ * always contains all the references. For planar audio with more than
+ * AV_NUM_DATA_POINTERS channels, there may be more buffers than can fit in
+ * this array. Then the extra AVBufferRef pointers are stored in the
+ * extended_buf array.
+ */
+ AVBufferRef *buf[AV_NUM_DATA_POINTERS];
+
+ /**
+ * For planar audio which requires more than AV_NUM_DATA_POINTERS
+ * AVBufferRef pointers, this array will hold all the references which
+ * cannot fit into AVFrame.buf.
+ *
+ * Note that this is different from AVFrame.extended_data, which always
+ * contains all the pointers. This array only contains the extra pointers,
+ * which cannot fit into AVFrame.buf.
+ *
+ * This array is always allocated using av_malloc() by whoever constructs
+ * the frame. It is freed in av_frame_unref().
+ */
+ AVBufferRef **extended_buf;
+ /**
+ * Number of elements in extended_buf.
+ */
+ int nb_extended_buf;
+
+ AVFrameSideData **side_data;
+ int nb_side_data;
+
+/**
+ * @defgroup lavu_frame_flags AV_FRAME_FLAGS
+ * @ingroup lavu_frame
+ * Flags describing additional frame properties.
+ *
+ * @{
+ */
+
+/**
+ * The frame data may be corrupted, e.g. due to decoding errors.
+ */
+#define AV_FRAME_FLAG_CORRUPT (1 << 0)
+/**
+ * A flag to mark the frames which need to be decoded, but shouldn't be output.
+ */
+#define AV_FRAME_FLAG_DISCARD (1 << 2)
+/**
+ * @}
+ */
+
+ /**
+ * Frame flags, a combination of @ref lavu_frame_flags
+ */
+ int flags;
+
+ /**
+ * MPEG vs JPEG YUV range.
+ * - encoding: Set by user
+ * - decoding: Set by libavcodec
+ */
+ enum AVColorRange color_range;
+
+ enum AVColorPrimaries color_primaries;
+
+ enum AVColorTransferCharacteristic color_trc;
+
+ /**
+ * YUV colorspace type.
+ * - encoding: Set by user
+ * - decoding: Set by libavcodec
+ */
+ enum AVColorSpace colorspace;
+
+ enum AVChromaLocation chroma_location;
+
+ /**
+ * frame timestamp estimated using various heuristics, in stream time base
+ * - encoding: unused
+ * - decoding: set by libavcodec, read by user.
+ */
+ int64_t best_effort_timestamp;
+
+ /**
+ * reordered pos from the last AVPacket that has been input into the decoder
+ * - encoding: unused
+ * - decoding: Read by user.
+ */
+ int64_t pkt_pos;
+
+ /**
+ * duration of the corresponding packet, expressed in
+ * AVStream->time_base units, 0 if unknown.
+ * - encoding: unused
+ * - decoding: Read by user.
+ */
+ int64_t pkt_duration;
+
+ /**
+ * metadata.
+ * - encoding: Set by user.
+ * - decoding: Set by libavcodec.
+ */
+ AVDictionary *metadata;
+
+ /**
+ * decode error flags of the frame, set to a combination of
+ * FF_DECODE_ERROR_xxx flags if the decoder produced a frame, but there
+ * were errors during the decoding.
+ * - encoding: unused
+ * - decoding: set by libavcodec, read by user.
+ */
+ int decode_error_flags;
+#define FF_DECODE_ERROR_INVALID_BITSTREAM 1
+#define FF_DECODE_ERROR_MISSING_REFERENCE 2
+
+ /**
+ * number of audio channels, only used for audio.
+ * - encoding: unused
+ * - decoding: Read by user.
+ */
+ int channels;
+
+ /**
+ * size of the corresponding packet containing the compressed
+ * frame.
+ * It is set to a negative value if unknown.
+ * - encoding: unused
+ * - decoding: set by libavcodec, read by user.
+ */
+ int pkt_size;
+
+#if FF_API_FRAME_QP
+ /**
+ * QP table
+ */
+ attribute_deprecated
+ int8_t *qscale_table;
+ /**
+ * QP store stride
+ */
+ attribute_deprecated
+ int qstride;
+
+ attribute_deprecated
+ int qscale_type;
+
+ attribute_deprecated
+ AVBufferRef *qp_table_buf;
+#endif
+ /**
+ * For hwaccel-format frames, this should be a reference to the
+ * AVHWFramesContext describing the frame.
+ */
+ AVBufferRef *hw_frames_ctx;
+
+ /**
+ * AVBufferRef for free use by the API user. FFmpeg will never check the
+ * contents of the buffer ref. FFmpeg calls av_buffer_unref() on it when
+ * the frame is unreferenced. av_frame_copy_props() calls create a new
+ * reference with av_buffer_ref() for the target frame's opaque_ref field.
+ *
+ * This is unrelated to the opaque field, although it serves a similar
+ * purpose.
+ */
+ AVBufferRef *opaque_ref;
+
+ /**
+ * @anchor cropping
+ * @name Cropping
+ * Video frames only. The number of pixels to discard from the the
+ * top/bottom/left/right border of the frame to obtain the sub-rectangle of
+ * the frame intended for presentation.
+ * @{
+ */
+ size_t crop_top;
+ size_t crop_bottom;
+ size_t crop_left;
+ size_t crop_right;
+ /**
+ * @}
+ */
+
+ /**
+ * AVBufferRef for internal use by a single libav* library.
+ * Must not be used to transfer data between libraries.
+ * Has to be NULL when ownership of the frame leaves the respective library.
+ *
+ * Code outside the FFmpeg libs should never check or change the contents of the buffer ref.
+ *
+ * FFmpeg calls av_buffer_unref() on it when the frame is unreferenced.
+ * av_frame_copy_props() calls create a new reference with av_buffer_ref()
+ * for the target frame's private_ref field.
+ */
+ AVBufferRef *private_ref;
+} AVFrame;
+
+#if FF_API_FRAME_GET_SET
+/**
+ * Accessors for some AVFrame fields. These used to be provided for ABI
+ * compatibility, and do not need to be used anymore.
+ */
+attribute_deprecated
+int64_t av_frame_get_best_effort_timestamp(const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_best_effort_timestamp(AVFrame *frame, int64_t val);
+attribute_deprecated
+int64_t av_frame_get_pkt_duration (const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_pkt_duration (AVFrame *frame, int64_t val);
+attribute_deprecated
+int64_t av_frame_get_pkt_pos (const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_pkt_pos (AVFrame *frame, int64_t val);
+attribute_deprecated
+int64_t av_frame_get_channel_layout (const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_channel_layout (AVFrame *frame, int64_t val);
+attribute_deprecated
+int av_frame_get_channels (const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_channels (AVFrame *frame, int val);
+attribute_deprecated
+int av_frame_get_sample_rate (const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_sample_rate (AVFrame *frame, int val);
+attribute_deprecated
+AVDictionary *av_frame_get_metadata (const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_metadata (AVFrame *frame, AVDictionary *val);
+attribute_deprecated
+int av_frame_get_decode_error_flags (const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_decode_error_flags (AVFrame *frame, int val);
+attribute_deprecated
+int av_frame_get_pkt_size(const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_pkt_size(AVFrame *frame, int val);
+#if FF_API_FRAME_QP
+attribute_deprecated
+int8_t *av_frame_get_qp_table(AVFrame *f, int *stride, int *type);
+attribute_deprecated
+int av_frame_set_qp_table(AVFrame *f, AVBufferRef *buf, int stride, int type);
+#endif
+attribute_deprecated
+enum AVColorSpace av_frame_get_colorspace(const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_colorspace(AVFrame *frame, enum AVColorSpace val);
+attribute_deprecated
+enum AVColorRange av_frame_get_color_range(const AVFrame *frame);
+attribute_deprecated
+void av_frame_set_color_range(AVFrame *frame, enum AVColorRange val);
+#endif
+
+/**
+ * Get the name of a colorspace.
+ * @return a static string identifying the colorspace; can be NULL.
+ */
+const char *av_get_colorspace_name(enum AVColorSpace val);
+
+/**
+ * Allocate an AVFrame and set its fields to default values. The resulting
+ * struct must be freed using av_frame_free().
+ *
+ * @return An AVFrame filled with default values or NULL on failure.
+ *
+ * @note this only allocates the AVFrame itself, not the data buffers. Those
+ * must be allocated through other means, e.g. with av_frame_get_buffer() or
+ * manually.
+ */
+AVFrame *av_frame_alloc(void);
+
+/**
+ * Free the frame and any dynamically allocated objects in it,
+ * e.g. extended_data. If the frame is reference counted, it will be
+ * unreferenced first.
+ *
+ * @param frame frame to be freed. The pointer will be set to NULL.
+ */
+void av_frame_free(AVFrame **frame);
+
+/**
+ * Set up a new reference to the data described by the source frame.
+ *
+ * Copy frame properties from src to dst and create a new reference for each
+ * AVBufferRef from src.
+ *
+ * If src is not reference counted, new buffers are allocated and the data is
+ * copied.
+ *
+ * @warning: dst MUST have been either unreferenced with av_frame_unref(dst),
+ * or newly allocated with av_frame_alloc() before calling this
+ * function, or undefined behavior will occur.
+ *
+ * @return 0 on success, a negative AVERROR on error
+ */
+int av_frame_ref(AVFrame *dst, const AVFrame *src);
+
+/**
+ * Create a new frame that references the same data as src.
+ *
+ * This is a shortcut for av_frame_alloc()+av_frame_ref().
+ *
+ * @return newly created AVFrame on success, NULL on error.
+ */
+AVFrame *av_frame_clone(const AVFrame *src);
+
+/**
+ * Unreference all the buffers referenced by frame and reset the frame fields.
+ */
+void av_frame_unref(AVFrame *frame);
+
+/**
+ * Move everything contained in src to dst and reset src.
+ *
+ * @warning: dst is not unreferenced, but directly overwritten without reading
+ * or deallocating its contents. Call av_frame_unref(dst) manually
+ * before calling this function to ensure that no memory is leaked.
+ */
+void av_frame_move_ref(AVFrame *dst, AVFrame *src);
+
+/**
+ * Allocate new buffer(s) for audio or video data.
+ *
+ * The following fields must be set on frame before calling this function:
+ * - format (pixel format for video, sample format for audio)
+ * - width and height for video
+ * - nb_samples and channel_layout for audio
+ *
+ * This function will fill AVFrame.data and AVFrame.buf arrays and, if
+ * necessary, allocate and fill AVFrame.extended_data and AVFrame.extended_buf.
+ * For planar formats, one buffer will be allocated for each plane.
+ *
+ * @warning: if frame already has been allocated, calling this function will
+ * leak memory. In addition, undefined behavior can occur in certain
+ * cases.
+ *
+ * @param frame frame in which to store the new buffers.
+ * @param align Required buffer size alignment. If equal to 0, alignment will be
+ * chosen automatically for the current CPU. It is highly
+ * recommended to pass 0 here unless you know what you are doing.
+ *
+ * @return 0 on success, a negative AVERROR on error.
+ */
+int av_frame_get_buffer(AVFrame *frame, int align);
+
+/**
+ * Check if the frame data is writable.
+ *
+ * @return A positive value if the frame data is writable (which is true if and
+ * only if each of the underlying buffers has only one reference, namely the one
+ * stored in this frame). Return 0 otherwise.
+ *
+ * If 1 is returned the answer is valid until av_buffer_ref() is called on any
+ * of the underlying AVBufferRefs (e.g. through av_frame_ref() or directly).
+ *
+ * @see av_frame_make_writable(), av_buffer_is_writable()
+ */
+int av_frame_is_writable(AVFrame *frame);
+
+/**
+ * Ensure that the frame data is writable, avoiding data copy if possible.
+ *
+ * Do nothing if the frame is writable, allocate new buffers and copy the data
+ * if it is not.
+ *
+ * @return 0 on success, a negative AVERROR on error.
+ *
+ * @see av_frame_is_writable(), av_buffer_is_writable(),
+ * av_buffer_make_writable()
+ */
+int av_frame_make_writable(AVFrame *frame);
+
+/**
+ * Copy the frame data from src to dst.
+ *
+ * This function does not allocate anything, dst must be already initialized and
+ * allocated with the same parameters as src.
+ *
+ * This function only copies the frame data (i.e. the contents of the data /
+ * extended data arrays), not any other properties.
+ *
+ * @return >= 0 on success, a negative AVERROR on error.
+ */
+int av_frame_copy(AVFrame *dst, const AVFrame *src);
+
+/**
+ * Copy only "metadata" fields from src to dst.
+ *
+ * Metadata for the purpose of this function are those fields that do not affect
+ * the data layout in the buffers. E.g. pts, sample rate (for audio) or sample
+ * aspect ratio (for video), but not width/height or channel layout.
+ * Side data is also copied.
+ */
+int av_frame_copy_props(AVFrame *dst, const AVFrame *src);
+
+/**
+ * Get the buffer reference a given data plane is stored in.
+ *
+ * @param plane index of the data plane of interest in frame->extended_data.
+ *
+ * @return the buffer reference that contains the plane or NULL if the input
+ * frame is not valid.
+ */
+AVBufferRef *av_frame_get_plane_buffer(AVFrame *frame, int plane);
+
+/**
+ * Add a new side data to a frame.
+ *
+ * @param frame a frame to which the side data should be added
+ * @param type type of the added side data
+ * @param size size of the side data
+ *
+ * @return newly added side data on success, NULL on error
+ */
+AVFrameSideData *av_frame_new_side_data(AVFrame *frame,
+ enum AVFrameSideDataType type,
+ int size);
+
+/**
+ * Add a new side data to a frame from an existing AVBufferRef
+ *
+ * @param frame a frame to which the side data should be added
+ * @param type the type of the added side data
+ * @param buf an AVBufferRef to add as side data. The ownership of
+ * the reference is transferred to the frame.
+ *
+ * @return newly added side data on success, NULL on error. On failure
+ * the frame is unchanged and the AVBufferRef remains owned by
+ * the caller.
+ */
+AVFrameSideData *av_frame_new_side_data_from_buf(AVFrame *frame,
+ enum AVFrameSideDataType type,
+ AVBufferRef *buf);
+
+/**
+ * @return a pointer to the side data of a given type on success, NULL if there
+ * is no side data with such type in this frame.
+ */
+AVFrameSideData *av_frame_get_side_data(const AVFrame *frame,
+ enum AVFrameSideDataType type);
+
+/**
+ * If side data of the supplied type exists in the frame, free it and remove it
+ * from the frame.
+ */
+void av_frame_remove_side_data(AVFrame *frame, enum AVFrameSideDataType type);
+
+
+/**
+ * Flags for frame cropping.
+ */
+enum {
+ /**
+ * Apply the maximum possible cropping, even if it requires setting the
+ * AVFrame.data[] entries to unaligned pointers. Passing unaligned data
+ * to FFmpeg API is generally not allowed, and causes undefined behavior
+ * (such as crashes). You can pass unaligned data only to FFmpeg APIs that
+ * are explicitly documented to accept it. Use this flag only if you
+ * absolutely know what you are doing.
+ */
+ AV_FRAME_CROP_UNALIGNED = 1 << 0,
+};
+
+/**
+ * Crop the given video AVFrame according to its crop_left/crop_top/crop_right/
+ * crop_bottom fields. If cropping is successful, the function will adjust the
+ * data pointers and the width/height fields, and set the crop fields to 0.
+ *
+ * In all cases, the cropping boundaries will be rounded to the inherent
+ * alignment of the pixel format. In some cases, such as for opaque hwaccel
+ * formats, the left/top cropping is ignored. The crop fields are set to 0 even
+ * if the cropping was rounded or ignored.
+ *
+ * @param frame the frame which should be cropped
+ * @param flags Some combination of AV_FRAME_CROP_* flags, or 0.
+ *
+ * @return >= 0 on success, a negative AVERROR on error. If the cropping fields
+ * were invalid, AVERROR(ERANGE) is returned, and nothing is changed.
+ */
+int av_frame_apply_cropping(AVFrame *frame, int flags);
+
+/**
+ * @return a string identifying the side data type
+ */
+const char *av_frame_side_data_name(enum AVFrameSideDataType type);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_FRAME_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/hwcontext.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/hwcontext.h
new file mode 100644
index 000000000..f5a4b6238
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/hwcontext.h
@@ -0,0 +1,584 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_HWCONTEXT_H
+#define AVUTIL_HWCONTEXT_H
+
+#include "buffer.h"
+#include "frame.h"
+#include "log.h"
+#include "pixfmt.h"
+
+enum AVHWDeviceType {
+ AV_HWDEVICE_TYPE_NONE,
+ AV_HWDEVICE_TYPE_VDPAU,
+ AV_HWDEVICE_TYPE_CUDA,
+ AV_HWDEVICE_TYPE_VAAPI,
+ AV_HWDEVICE_TYPE_DXVA2,
+ AV_HWDEVICE_TYPE_QSV,
+ AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
+ AV_HWDEVICE_TYPE_D3D11VA,
+ AV_HWDEVICE_TYPE_DRM,
+ AV_HWDEVICE_TYPE_OPENCL,
+ AV_HWDEVICE_TYPE_MEDIACODEC,
+};
+
+typedef struct AVHWDeviceInternal AVHWDeviceInternal;
+
+/**
+ * This struct aggregates all the (hardware/vendor-specific) "high-level" state,
+ * i.e. state that is not tied to a concrete processing configuration.
+ * E.g., in an API that supports hardware-accelerated encoding and decoding,
+ * this struct will (if possible) wrap the state that is common to both encoding
+ * and decoding and from which specific instances of encoders or decoders can be
+ * derived.
+ *
+ * This struct is reference-counted with the AVBuffer mechanism. The
+ * av_hwdevice_ctx_alloc() constructor yields a reference, whose data field
+ * points to the actual AVHWDeviceContext. Further objects derived from
+ * AVHWDeviceContext (such as AVHWFramesContext, describing a frame pool with
+ * specific properties) will hold an internal reference to it. After all the
+ * references are released, the AVHWDeviceContext itself will be freed,
+ * optionally invoking a user-specified callback for uninitializing the hardware
+ * state.
+ */
+typedef struct AVHWDeviceContext {
+ /**
+ * A class for logging. Set by av_hwdevice_ctx_alloc().
+ */
+ const AVClass *av_class;
+
+ /**
+ * Private data used internally by libavutil. Must not be accessed in any
+ * way by the caller.
+ */
+ AVHWDeviceInternal *internal;
+
+ /**
+ * This field identifies the underlying API used for hardware access.
+ *
+ * This field is set when this struct is allocated and never changed
+ * afterwards.
+ */
+ enum AVHWDeviceType type;
+
+ /**
+ * The format-specific data, allocated and freed by libavutil along with
+ * this context.
+ *
+ * Should be cast by the user to the format-specific context defined in the
+ * corresponding header (hwcontext_*.h) and filled as described in the
+ * documentation before calling av_hwdevice_ctx_init().
+ *
+ * After calling av_hwdevice_ctx_init() this struct should not be modified
+ * by the caller.
+ */
+ void *hwctx;
+
+ /**
+ * This field may be set by the caller before calling av_hwdevice_ctx_init().
+ *
+ * If non-NULL, this callback will be called when the last reference to
+ * this context is unreferenced, immediately before it is freed.
+ *
+ * @note when other objects (e.g an AVHWFramesContext) are derived from this
+ * struct, this callback will be invoked after all such child objects
+ * are fully uninitialized and their respective destructors invoked.
+ */
+ void (*free)(struct AVHWDeviceContext *ctx);
+
+ /**
+ * Arbitrary user data, to be used e.g. by the free() callback.
+ */
+ void *user_opaque;
+} AVHWDeviceContext;
+
+typedef struct AVHWFramesInternal AVHWFramesInternal;
+
+/**
+ * This struct describes a set or pool of "hardware" frames (i.e. those with
+ * data not located in normal system memory). All the frames in the pool are
+ * assumed to be allocated in the same way and interchangeable.
+ *
+ * This struct is reference-counted with the AVBuffer mechanism and tied to a
+ * given AVHWDeviceContext instance. The av_hwframe_ctx_alloc() constructor
+ * yields a reference, whose data field points to the actual AVHWFramesContext
+ * struct.
+ */
+typedef struct AVHWFramesContext {
+ /**
+ * A class for logging.
+ */
+ const AVClass *av_class;
+
+ /**
+ * Private data used internally by libavutil. Must not be accessed in any
+ * way by the caller.
+ */
+ AVHWFramesInternal *internal;
+
+ /**
+ * A reference to the parent AVHWDeviceContext. This reference is owned and
+ * managed by the enclosing AVHWFramesContext, but the caller may derive
+ * additional references from it.
+ */
+ AVBufferRef *device_ref;
+
+ /**
+ * The parent AVHWDeviceContext. This is simply a pointer to
+ * device_ref->data provided for convenience.
+ *
+ * Set by libavutil in av_hwframe_ctx_init().
+ */
+ AVHWDeviceContext *device_ctx;
+
+ /**
+ * The format-specific data, allocated and freed automatically along with
+ * this context.
+ *
+ * Should be cast by the user to the format-specific context defined in the
+ * corresponding header (hwframe_*.h) and filled as described in the
+ * documentation before calling av_hwframe_ctx_init().
+ *
+ * After any frames using this context are created, the contents of this
+ * struct should not be modified by the caller.
+ */
+ void *hwctx;
+
+ /**
+ * This field may be set by the caller before calling av_hwframe_ctx_init().
+ *
+ * If non-NULL, this callback will be called when the last reference to
+ * this context is unreferenced, immediately before it is freed.
+ */
+ void (*free)(struct AVHWFramesContext *ctx);
+
+ /**
+ * Arbitrary user data, to be used e.g. by the free() callback.
+ */
+ void *user_opaque;
+
+ /**
+ * A pool from which the frames are allocated by av_hwframe_get_buffer().
+ * This field may be set by the caller before calling av_hwframe_ctx_init().
+ * The buffers returned by calling av_buffer_pool_get() on this pool must
+ * have the properties described in the documentation in the corresponding hw
+ * type's header (hwcontext_*.h). The pool will be freed strictly before
+ * this struct's free() callback is invoked.
+ *
+ * This field may be NULL, then libavutil will attempt to allocate a pool
+ * internally. Note that certain device types enforce pools allocated at
+ * fixed size (frame count), which cannot be extended dynamically. In such a
+ * case, initial_pool_size must be set appropriately.
+ */
+ AVBufferPool *pool;
+
+ /**
+ * Initial size of the frame pool. If a device type does not support
+ * dynamically resizing the pool, then this is also the maximum pool size.
+ *
+ * May be set by the caller before calling av_hwframe_ctx_init(). Must be
+ * set if pool is NULL and the device type does not support dynamic pools.
+ */
+ int initial_pool_size;
+
+ /**
+ * The pixel format identifying the underlying HW surface type.
+ *
+ * Must be a hwaccel format, i.e. the corresponding descriptor must have the
+ * AV_PIX_FMT_FLAG_HWACCEL flag set.
+ *
+ * Must be set by the user before calling av_hwframe_ctx_init().
+ */
+ enum AVPixelFormat format;
+
+ /**
+ * The pixel format identifying the actual data layout of the hardware
+ * frames.
+ *
+ * Must be set by the caller before calling av_hwframe_ctx_init().
+ *
+ * @note when the underlying API does not provide the exact data layout, but
+ * only the colorspace/bit depth, this field should be set to the fully
+ * planar version of that format (e.g. for 8-bit 420 YUV it should be
+ * AV_PIX_FMT_YUV420P, not AV_PIX_FMT_NV12 or anything else).
+ */
+ enum AVPixelFormat sw_format;
+
+ /**
+ * The allocated dimensions of the frames in this pool.
+ *
+ * Must be set by the user before calling av_hwframe_ctx_init().
+ */
+ int width, height;
+} AVHWFramesContext;
+
+/**
+ * Look up an AVHWDeviceType by name.
+ *
+ * @param name String name of the device type (case-insensitive).
+ * @return The type from enum AVHWDeviceType, or AV_HWDEVICE_TYPE_NONE if
+ * not found.
+ */
+enum AVHWDeviceType av_hwdevice_find_type_by_name(const char *name);
+
+/** Get the string name of an AVHWDeviceType.
+ *
+ * @param type Type from enum AVHWDeviceType.
+ * @return Pointer to a static string containing the name, or NULL if the type
+ * is not valid.
+ */
+const char *av_hwdevice_get_type_name(enum AVHWDeviceType type);
+
+/**
+ * Iterate over supported device types.
+ *
+ * @param type AV_HWDEVICE_TYPE_NONE initially, then the previous type
+ * returned by this function in subsequent iterations.
+ * @return The next usable device type from enum AVHWDeviceType, or
+ * AV_HWDEVICE_TYPE_NONE if there are no more.
+ */
+enum AVHWDeviceType av_hwdevice_iterate_types(enum AVHWDeviceType prev);
+
+/**
+ * Allocate an AVHWDeviceContext for a given hardware type.
+ *
+ * @param type the type of the hardware device to allocate.
+ * @return a reference to the newly created AVHWDeviceContext on success or NULL
+ * on failure.
+ */
+AVBufferRef *av_hwdevice_ctx_alloc(enum AVHWDeviceType type);
+
+/**
+ * Finalize the device context before use. This function must be called after
+ * the context is filled with all the required information and before it is
+ * used in any way.
+ *
+ * @param ref a reference to the AVHWDeviceContext
+ * @return 0 on success, a negative AVERROR code on failure
+ */
+int av_hwdevice_ctx_init(AVBufferRef *ref);
+
+/**
+ * Open a device of the specified type and create an AVHWDeviceContext for it.
+ *
+ * This is a convenience function intended to cover the simple cases. Callers
+ * who need to fine-tune device creation/management should open the device
+ * manually and then wrap it in an AVHWDeviceContext using
+ * av_hwdevice_ctx_alloc()/av_hwdevice_ctx_init().
+ *
+ * The returned context is already initialized and ready for use, the caller
+ * should not call av_hwdevice_ctx_init() on it. The user_opaque/free fields of
+ * the created AVHWDeviceContext are set by this function and should not be
+ * touched by the caller.
+ *
+ * @param device_ctx On success, a reference to the newly-created device context
+ * will be written here. The reference is owned by the caller
+ * and must be released with av_buffer_unref() when no longer
+ * needed. On failure, NULL will be written to this pointer.
+ * @param type The type of the device to create.
+ * @param device A type-specific string identifying the device to open.
+ * @param opts A dictionary of additional (type-specific) options to use in
+ * opening the device. The dictionary remains owned by the caller.
+ * @param flags currently unused
+ *
+ * @return 0 on success, a negative AVERROR code on failure.
+ */
+int av_hwdevice_ctx_create(AVBufferRef **device_ctx, enum AVHWDeviceType type,
+ const char *device, AVDictionary *opts, int flags);
+
+/**
+ * Create a new device of the specified type from an existing device.
+ *
+ * If the source device is a device of the target type or was originally
+ * derived from such a device (possibly through one or more intermediate
+ * devices of other types), then this will return a reference to the
+ * existing device of the same type as is requested.
+ *
+ * Otherwise, it will attempt to derive a new device from the given source
+ * device. If direct derivation to the new type is not implemented, it will
+ * attempt the same derivation from each ancestor of the source device in
+ * turn looking for an implemented derivation method.
+ *
+ * @param dst_ctx On success, a reference to the newly-created
+ * AVHWDeviceContext.
+ * @param type The type of the new device to create.
+ * @param src_ctx A reference to an existing AVHWDeviceContext which will be
+ * used to create the new device.
+ * @param flags Currently unused; should be set to zero.
+ * @return Zero on success, a negative AVERROR code on failure.
+ */
+int av_hwdevice_ctx_create_derived(AVBufferRef **dst_ctx,
+ enum AVHWDeviceType type,
+ AVBufferRef *src_ctx, int flags);
+
+
+/**
+ * Allocate an AVHWFramesContext tied to a given device context.
+ *
+ * @param device_ctx a reference to a AVHWDeviceContext. This function will make
+ * a new reference for internal use, the one passed to the
+ * function remains owned by the caller.
+ * @return a reference to the newly created AVHWFramesContext on success or NULL
+ * on failure.
+ */
+AVBufferRef *av_hwframe_ctx_alloc(AVBufferRef *device_ctx);
+
+/**
+ * Finalize the context before use. This function must be called after the
+ * context is filled with all the required information and before it is attached
+ * to any frames.
+ *
+ * @param ref a reference to the AVHWFramesContext
+ * @return 0 on success, a negative AVERROR code on failure
+ */
+int av_hwframe_ctx_init(AVBufferRef *ref);
+
+/**
+ * Allocate a new frame attached to the given AVHWFramesContext.
+ *
+ * @param hwframe_ctx a reference to an AVHWFramesContext
+ * @param frame an empty (freshly allocated or unreffed) frame to be filled with
+ * newly allocated buffers.
+ * @param flags currently unused, should be set to zero
+ * @return 0 on success, a negative AVERROR code on failure
+ */
+int av_hwframe_get_buffer(AVBufferRef *hwframe_ctx, AVFrame *frame, int flags);
+
+/**
+ * Copy data to or from a hw surface. At least one of dst/src must have an
+ * AVHWFramesContext attached.
+ *
+ * If src has an AVHWFramesContext attached, then the format of dst (if set)
+ * must use one of the formats returned by av_hwframe_transfer_get_formats(src,
+ * AV_HWFRAME_TRANSFER_DIRECTION_FROM).
+ * If dst has an AVHWFramesContext attached, then the format of src must use one
+ * of the formats returned by av_hwframe_transfer_get_formats(dst,
+ * AV_HWFRAME_TRANSFER_DIRECTION_TO)
+ *
+ * dst may be "clean" (i.e. with data/buf pointers unset), in which case the
+ * data buffers will be allocated by this function using av_frame_get_buffer().
+ * If dst->format is set, then this format will be used, otherwise (when
+ * dst->format is AV_PIX_FMT_NONE) the first acceptable format will be chosen.
+ *
+ * The two frames must have matching allocated dimensions (i.e. equal to
+ * AVHWFramesContext.width/height), since not all device types support
+ * transferring a sub-rectangle of the whole surface. The display dimensions
+ * (i.e. AVFrame.width/height) may be smaller than the allocated dimensions, but
+ * also have to be equal for both frames. When the display dimensions are
+ * smaller than the allocated dimensions, the content of the padding in the
+ * destination frame is unspecified.
+ *
+ * @param dst the destination frame. dst is not touched on failure.
+ * @param src the source frame.
+ * @param flags currently unused, should be set to zero
+ * @return 0 on success, a negative AVERROR error code on failure.
+ */
+int av_hwframe_transfer_data(AVFrame *dst, const AVFrame *src, int flags);
+
+enum AVHWFrameTransferDirection {
+ /**
+ * Transfer the data from the queried hw frame.
+ */
+ AV_HWFRAME_TRANSFER_DIRECTION_FROM,
+
+ /**
+ * Transfer the data to the queried hw frame.
+ */
+ AV_HWFRAME_TRANSFER_DIRECTION_TO,
+};
+
+/**
+ * Get a list of possible source or target formats usable in
+ * av_hwframe_transfer_data().
+ *
+ * @param hwframe_ctx the frame context to obtain the information for
+ * @param dir the direction of the transfer
+ * @param formats the pointer to the output format list will be written here.
+ * The list is terminated with AV_PIX_FMT_NONE and must be freed
+ * by the caller when no longer needed using av_free().
+ * If this function returns successfully, the format list will
+ * have at least one item (not counting the terminator).
+ * On failure, the contents of this pointer are unspecified.
+ * @param flags currently unused, should be set to zero
+ * @return 0 on success, a negative AVERROR code on failure.
+ */
+int av_hwframe_transfer_get_formats(AVBufferRef *hwframe_ctx,
+ enum AVHWFrameTransferDirection dir,
+ enum AVPixelFormat **formats, int flags);
+
+
+/**
+ * This struct describes the constraints on hardware frames attached to
+ * a given device with a hardware-specific configuration. This is returned
+ * by av_hwdevice_get_hwframe_constraints() and must be freed by
+ * av_hwframe_constraints_free() after use.
+ */
+typedef struct AVHWFramesConstraints {
+ /**
+ * A list of possible values for format in the hw_frames_ctx,
+ * terminated by AV_PIX_FMT_NONE. This member will always be filled.
+ */
+ enum AVPixelFormat *valid_hw_formats;
+
+ /**
+ * A list of possible values for sw_format in the hw_frames_ctx,
+ * terminated by AV_PIX_FMT_NONE. Can be NULL if this information is
+ * not known.
+ */
+ enum AVPixelFormat *valid_sw_formats;
+
+ /**
+ * The minimum size of frames in this hw_frames_ctx.
+ * (Zero if not known.)
+ */
+ int min_width;
+ int min_height;
+
+ /**
+ * The maximum size of frames in this hw_frames_ctx.
+ * (INT_MAX if not known / no limit.)
+ */
+ int max_width;
+ int max_height;
+} AVHWFramesConstraints;
+
+/**
+ * Allocate a HW-specific configuration structure for a given HW device.
+ * After use, the user must free all members as required by the specific
+ * hardware structure being used, then free the structure itself with
+ * av_free().
+ *
+ * @param device_ctx a reference to the associated AVHWDeviceContext.
+ * @return The newly created HW-specific configuration structure on
+ * success or NULL on failure.
+ */
+void *av_hwdevice_hwconfig_alloc(AVBufferRef *device_ctx);
+
+/**
+ * Get the constraints on HW frames given a device and the HW-specific
+ * configuration to be used with that device. If no HW-specific
+ * configuration is provided, returns the maximum possible capabilities
+ * of the device.
+ *
+ * @param ref a reference to the associated AVHWDeviceContext.
+ * @param hwconfig a filled HW-specific configuration structure, or NULL
+ * to return the maximum possible capabilities of the device.
+ * @return AVHWFramesConstraints structure describing the constraints
+ * on the device, or NULL if not available.
+ */
+AVHWFramesConstraints *av_hwdevice_get_hwframe_constraints(AVBufferRef *ref,
+ const void *hwconfig);
+
+/**
+ * Free an AVHWFrameConstraints structure.
+ *
+ * @param constraints The (filled or unfilled) AVHWFrameConstraints structure.
+ */
+void av_hwframe_constraints_free(AVHWFramesConstraints **constraints);
+
+
+/**
+ * Flags to apply to frame mappings.
+ */
+enum {
+ /**
+ * The mapping must be readable.
+ */
+ AV_HWFRAME_MAP_READ = 1 << 0,
+ /**
+ * The mapping must be writeable.
+ */
+ AV_HWFRAME_MAP_WRITE = 1 << 1,
+ /**
+ * The mapped frame will be overwritten completely in subsequent
+ * operations, so the current frame data need not be loaded. Any values
+ * which are not overwritten are unspecified.
+ */
+ AV_HWFRAME_MAP_OVERWRITE = 1 << 2,
+ /**
+ * The mapping must be direct. That is, there must not be any copying in
+ * the map or unmap steps. Note that performance of direct mappings may
+ * be much lower than normal memory.
+ */
+ AV_HWFRAME_MAP_DIRECT = 1 << 3,
+};
+
+/**
+ * Map a hardware frame.
+ *
+ * This has a number of different possible effects, depending on the format
+ * and origin of the src and dst frames. On input, src should be a usable
+ * frame with valid buffers and dst should be blank (typically as just created
+ * by av_frame_alloc()). src should have an associated hwframe context, and
+ * dst may optionally have a format and associated hwframe context.
+ *
+ * If src was created by mapping a frame from the hwframe context of dst,
+ * then this function undoes the mapping - dst is replaced by a reference to
+ * the frame that src was originally mapped from.
+ *
+ * If both src and dst have an associated hwframe context, then this function
+ * attempts to map the src frame from its hardware context to that of dst and
+ * then fill dst with appropriate data to be usable there. This will only be
+ * possible if the hwframe contexts and associated devices are compatible -
+ * given compatible devices, av_hwframe_ctx_create_derived() can be used to
+ * create a hwframe context for dst in which mapping should be possible.
+ *
+ * If src has a hwframe context but dst does not, then the src frame is
+ * mapped to normal memory and should thereafter be usable as a normal frame.
+ * If the format is set on dst, then the mapping will attempt to create dst
+ * with that format and fail if it is not possible. If format is unset (is
+ * AV_PIX_FMT_NONE) then dst will be mapped with whatever the most appropriate
+ * format to use is (probably the sw_format of the src hwframe context).
+ *
+ * A return value of AVERROR(ENOSYS) indicates that the mapping is not
+ * possible with the given arguments and hwframe setup, while other return
+ * values indicate that it failed somehow.
+ *
+ * @param dst Destination frame, to contain the mapping.
+ * @param src Source frame, to be mapped.
+ * @param flags Some combination of AV_HWFRAME_MAP_* flags.
+ * @return Zero on success, negative AVERROR code on failure.
+ */
+int av_hwframe_map(AVFrame *dst, const AVFrame *src, int flags);
+
+
+/**
+ * Create and initialise an AVHWFramesContext as a mapping of another existing
+ * AVHWFramesContext on a different device.
+ *
+ * av_hwframe_ctx_init() should not be called after this.
+ *
+ * @param derived_frame_ctx On success, a reference to the newly created
+ * AVHWFramesContext.
+ * @param derived_device_ctx A reference to the device to create the new
+ * AVHWFramesContext on.
+ * @param source_frame_ctx A reference to an existing AVHWFramesContext
+ * which will be mapped to the derived context.
+ * @param flags Some combination of AV_HWFRAME_MAP_* flags, defining the
+ * mapping parameters to apply to frames which are allocated
+ * in the derived device.
+ * @return Zero on success, negative AVERROR code on failure.
+ */
+int av_hwframe_ctx_create_derived(AVBufferRef **derived_frame_ctx,
+ enum AVPixelFormat format,
+ AVBufferRef *derived_device_ctx,
+ AVBufferRef *source_frame_ctx,
+ int flags);
+
+#endif /* AVUTIL_HWCONTEXT_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/intfloat.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/intfloat.h
new file mode 100644
index 000000000..fe3d7ec4a
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/intfloat.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2011 Mans Rullgard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_INTFLOAT_H
+#define AVUTIL_INTFLOAT_H
+
+#include <stdint.h>
+#include "attributes.h"
+
+union av_intfloat32 {
+ uint32_t i;
+ float f;
+};
+
+union av_intfloat64 {
+ uint64_t i;
+ double f;
+};
+
+/**
+ * Reinterpret a 32-bit integer as a float.
+ */
+static av_always_inline float av_int2float(uint32_t i)
+{
+ union av_intfloat32 v;
+ v.i = i;
+ return v.f;
+}
+
+/**
+ * Reinterpret a float as a 32-bit integer.
+ */
+static av_always_inline uint32_t av_float2int(float f)
+{
+ union av_intfloat32 v;
+ v.f = f;
+ return v.i;
+}
+
+/**
+ * Reinterpret a 64-bit integer as a double.
+ */
+static av_always_inline double av_int2double(uint64_t i)
+{
+ union av_intfloat64 v;
+ v.i = i;
+ return v.f;
+}
+
+/**
+ * Reinterpret a double as a 64-bit integer.
+ */
+static av_always_inline uint64_t av_double2int(double f)
+{
+ union av_intfloat64 v;
+ v.f = f;
+ return v.i;
+}
+
+#endif /* AVUTIL_INTFLOAT_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/log.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/log.h
new file mode 100644
index 000000000..d9554e609
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/log.h
@@ -0,0 +1,362 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_LOG_H
+#define AVUTIL_LOG_H
+
+#include <stdarg.h>
+#include "avutil.h"
+#include "attributes.h"
+#include "version.h"
+
+typedef enum {
+ AV_CLASS_CATEGORY_NA = 0,
+ AV_CLASS_CATEGORY_INPUT,
+ AV_CLASS_CATEGORY_OUTPUT,
+ AV_CLASS_CATEGORY_MUXER,
+ AV_CLASS_CATEGORY_DEMUXER,
+ AV_CLASS_CATEGORY_ENCODER,
+ AV_CLASS_CATEGORY_DECODER,
+ AV_CLASS_CATEGORY_FILTER,
+ AV_CLASS_CATEGORY_BITSTREAM_FILTER,
+ AV_CLASS_CATEGORY_SWSCALER,
+ AV_CLASS_CATEGORY_SWRESAMPLER,
+ AV_CLASS_CATEGORY_DEVICE_VIDEO_OUTPUT = 40,
+ AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
+ AV_CLASS_CATEGORY_DEVICE_AUDIO_OUTPUT,
+ AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT,
+ AV_CLASS_CATEGORY_DEVICE_OUTPUT,
+ AV_CLASS_CATEGORY_DEVICE_INPUT,
+ AV_CLASS_CATEGORY_NB ///< not part of ABI/API
+}AVClassCategory;
+
+#define AV_IS_INPUT_DEVICE(category) \
+ (((category) == AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT) || \
+ ((category) == AV_CLASS_CATEGORY_DEVICE_AUDIO_INPUT) || \
+ ((category) == AV_CLASS_CATEGORY_DEVICE_INPUT))
+
+#define AV_IS_OUTPUT_DEVICE(category) \
+ (((category) == AV_CLASS_CATEGORY_DEVICE_VIDEO_OUTPUT) || \
+ ((category) == AV_CLASS_CATEGORY_DEVICE_AUDIO_OUTPUT) || \
+ ((category) == AV_CLASS_CATEGORY_DEVICE_OUTPUT))
+
+struct AVOptionRanges;
+
+/**
+ * Describe the class of an AVClass context structure. That is an
+ * arbitrary struct of which the first field is a pointer to an
+ * AVClass struct (e.g. AVCodecContext, AVFormatContext etc.).
+ */
+typedef struct AVClass {
+ /**
+ * The name of the class; usually it is the same name as the
+ * context structure type to which the AVClass is associated.
+ */
+ const char* class_name;
+
+ /**
+ * A pointer to a function which returns the name of a context
+ * instance ctx associated with the class.
+ */
+ const char* (*item_name)(void* ctx);
+
+ /**
+ * a pointer to the first option specified in the class if any or NULL
+ *
+ * @see av_set_default_options()
+ */
+ const struct AVOption *option;
+
+ /**
+ * LIBAVUTIL_VERSION with which this structure was created.
+ * This is used to allow fields to be added without requiring major
+ * version bumps everywhere.
+ */
+
+ int version;
+
+ /**
+ * Offset in the structure where log_level_offset is stored.
+ * 0 means there is no such variable
+ */
+ int log_level_offset_offset;
+
+ /**
+ * Offset in the structure where a pointer to the parent context for
+ * logging is stored. For example a decoder could pass its AVCodecContext
+ * to eval as such a parent context, which an av_log() implementation
+ * could then leverage to display the parent context.
+ * The offset can be NULL.
+ */
+ int parent_log_context_offset;
+
+ /**
+ * Return next AVOptions-enabled child or NULL
+ */
+ void* (*child_next)(void *obj, void *prev);
+
+ /**
+ * Return an AVClass corresponding to the next potential
+ * AVOptions-enabled child.
+ *
+ * The difference between child_next and this is that
+ * child_next iterates over _already existing_ objects, while
+ * child_class_next iterates over _all possible_ children.
+ */
+ const struct AVClass* (*child_class_next)(const struct AVClass *prev);
+
+ /**
+ * Category used for visualization (like color)
+ * This is only set if the category is equal for all objects using this class.
+ * available since version (51 << 16 | 56 << 8 | 100)
+ */
+ AVClassCategory category;
+
+ /**
+ * Callback to return the category.
+ * available since version (51 << 16 | 59 << 8 | 100)
+ */
+ AVClassCategory (*get_category)(void* ctx);
+
+ /**
+ * Callback to return the supported/allowed ranges.
+ * available since version (52.12)
+ */
+ int (*query_ranges)(struct AVOptionRanges **, void *obj, const char *key, int flags);
+} AVClass;
+
+/**
+ * @addtogroup lavu_log
+ *
+ * @{
+ *
+ * @defgroup lavu_log_constants Logging Constants
+ *
+ * @{
+ */
+
+/**
+ * Print no output.
+ */
+#define AV_LOG_QUIET -8
+
+/**
+ * Something went really wrong and we will crash now.
+ */
+#define AV_LOG_PANIC 0
+
+/**
+ * Something went wrong and recovery is not possible.
+ * For example, no header was found for a format which depends
+ * on headers or an illegal combination of parameters is used.
+ */
+#define AV_LOG_FATAL 8
+
+/**
+ * Something went wrong and cannot losslessly be recovered.
+ * However, not all future data is affected.
+ */
+#define AV_LOG_ERROR 16
+
+/**
+ * Something somehow does not look correct. This may or may not
+ * lead to problems. An example would be the use of '-vstrict -2'.
+ */
+#define AV_LOG_WARNING 24
+
+/**
+ * Standard information.
+ */
+#define AV_LOG_INFO 32
+
+/**
+ * Detailed information.
+ */
+#define AV_LOG_VERBOSE 40
+
+/**
+ * Stuff which is only useful for libav* developers.
+ */
+#define AV_LOG_DEBUG 48
+
+/**
+ * Extremely verbose debugging, useful for libav* development.
+ */
+#define AV_LOG_TRACE 56
+
+#define AV_LOG_MAX_OFFSET (AV_LOG_TRACE - AV_LOG_QUIET)
+
+/**
+ * @}
+ */
+
+/**
+ * Sets additional colors for extended debugging sessions.
+ * @code
+ av_log(ctx, AV_LOG_DEBUG|AV_LOG_C(134), "Message in purple\n");
+ @endcode
+ * Requires 256color terminal support. Uses outside debugging is not
+ * recommended.
+ */
+#define AV_LOG_C(x) ((x) << 8)
+
+/**
+ * Send the specified message to the log if the level is less than or equal
+ * to the current av_log_level. By default, all logging messages are sent to
+ * stderr. This behavior can be altered by setting a different logging callback
+ * function.
+ * @see av_log_set_callback
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct or NULL if general log.
+ * @param level The importance level of the message expressed using a @ref
+ * lavu_log_constants "Logging Constant".
+ * @param fmt The format string (printf-compatible) that specifies how
+ * subsequent arguments are converted to output.
+ */
+void av_log(void *avcl, int level, const char *fmt, ...) av_printf_format(3, 4);
+
+
+/**
+ * Send the specified message to the log if the level is less than or equal
+ * to the current av_log_level. By default, all logging messages are sent to
+ * stderr. This behavior can be altered by setting a different logging callback
+ * function.
+ * @see av_log_set_callback
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct.
+ * @param level The importance level of the message expressed using a @ref
+ * lavu_log_constants "Logging Constant".
+ * @param fmt The format string (printf-compatible) that specifies how
+ * subsequent arguments are converted to output.
+ * @param vl The arguments referenced by the format string.
+ */
+void av_vlog(void *avcl, int level, const char *fmt, va_list vl);
+
+/**
+ * Get the current log level
+ *
+ * @see lavu_log_constants
+ *
+ * @return Current log level
+ */
+int av_log_get_level(void);
+
+/**
+ * Set the log level
+ *
+ * @see lavu_log_constants
+ *
+ * @param level Logging level
+ */
+void av_log_set_level(int level);
+
+/**
+ * Set the logging callback
+ *
+ * @note The callback must be thread safe, even if the application does not use
+ * threads itself as some codecs are multithreaded.
+ *
+ * @see av_log_default_callback
+ *
+ * @param callback A logging function with a compatible signature.
+ */
+void av_log_set_callback(void (*callback)(void*, int, const char*, va_list));
+
+/**
+ * Default logging callback
+ *
+ * It prints the message to stderr, optionally colorizing it.
+ *
+ * @param avcl A pointer to an arbitrary struct of which the first field is a
+ * pointer to an AVClass struct.
+ * @param level The importance level of the message expressed using a @ref
+ * lavu_log_constants "Logging Constant".
+ * @param fmt The format string (printf-compatible) that specifies how
+ * subsequent arguments are converted to output.
+ * @param vl The arguments referenced by the format string.
+ */
+void av_log_default_callback(void *avcl, int level, const char *fmt,
+ va_list vl);
+
+/**
+ * Return the context name
+ *
+ * @param ctx The AVClass context
+ *
+ * @return The AVClass class_name
+ */
+const char* av_default_item_name(void* ctx);
+AVClassCategory av_default_get_category(void *ptr);
+
+/**
+ * Format a line of log the same way as the default callback.
+ * @param line buffer to receive the formatted line
+ * @param line_size size of the buffer
+ * @param print_prefix used to store whether the prefix must be printed;
+ * must point to a persistent integer initially set to 1
+ */
+void av_log_format_line(void *ptr, int level, const char *fmt, va_list vl,
+ char *line, int line_size, int *print_prefix);
+
+/**
+ * Format a line of log the same way as the default callback.
+ * @param line buffer to receive the formatted line;
+ * may be NULL if line_size is 0
+ * @param line_size size of the buffer; at most line_size-1 characters will
+ * be written to the buffer, plus one null terminator
+ * @param print_prefix used to store whether the prefix must be printed;
+ * must point to a persistent integer initially set to 1
+ * @return Returns a negative value if an error occurred, otherwise returns
+ * the number of characters that would have been written for a
+ * sufficiently large buffer, not including the terminating null
+ * character. If the return value is not less than line_size, it means
+ * that the log message was truncated to fit the buffer.
+ */
+int av_log_format_line2(void *ptr, int level, const char *fmt, va_list vl,
+ char *line, int line_size, int *print_prefix);
+
+/**
+ * Skip repeated messages, this requires the user app to use av_log() instead of
+ * (f)printf as the 2 would otherwise interfere and lead to
+ * "Last message repeated x times" messages below (f)printf messages with some
+ * bad luck.
+ * Also to receive the last, "last repeated" line if any, the user app must
+ * call av_log(NULL, AV_LOG_QUIET, "%s", ""); at the end
+ */
+#define AV_LOG_SKIP_REPEATED 1
+
+/**
+ * Include the log severity in messages originating from codecs.
+ *
+ * Results in messages such as:
+ * [rawvideo @ 0xDEADBEEF] [error] encode did not produce valid pts
+ */
+#define AV_LOG_PRINT_LEVEL 2
+
+void av_log_set_flags(int arg);
+int av_log_get_flags(void);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_LOG_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/macros.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/macros.h
new file mode 100644
index 000000000..2007ee561
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/macros.h
@@ -0,0 +1,50 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @ingroup lavu
+ * Utility Preprocessor macros
+ */
+
+#ifndef AVUTIL_MACROS_H
+#define AVUTIL_MACROS_H
+
+/**
+ * @addtogroup preproc_misc Preprocessor String Macros
+ *
+ * String manipulation macros
+ *
+ * @{
+ */
+
+#define AV_STRINGIFY(s) AV_TOSTRING(s)
+#define AV_TOSTRING(s) #s
+
+#define AV_GLUE(a, b) a ## b
+#define AV_JOIN(a, b) AV_GLUE(a, b)
+
+/**
+ * @}
+ */
+
+#define AV_PRAGMA(s) _Pragma(#s)
+
+#define FFALIGN(x, a) (((x)+(a)-1)&~((a)-1))
+
+#endif /* AVUTIL_MACROS_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/mathematics.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/mathematics.h
new file mode 100644
index 000000000..54901800b
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/mathematics.h
@@ -0,0 +1,242 @@
+/*
+ * copyright (c) 2005-2012 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @addtogroup lavu_math
+ * Mathematical utilities for working with timestamp and time base.
+ */
+
+#ifndef AVUTIL_MATHEMATICS_H
+#define AVUTIL_MATHEMATICS_H
+
+#include <stdint.h>
+#include <math.h>
+#include "attributes.h"
+#include "rational.h"
+#include "intfloat.h"
+
+#ifndef M_E
+#define M_E 2.7182818284590452354 /* e */
+#endif
+#ifndef M_LN2
+#define M_LN2 0.69314718055994530942 /* log_e 2 */
+#endif
+#ifndef M_LN10
+#define M_LN10 2.30258509299404568402 /* log_e 10 */
+#endif
+#ifndef M_LOG2_10
+#define M_LOG2_10 3.32192809488736234787 /* log_2 10 */
+#endif
+#ifndef M_PHI
+#define M_PHI 1.61803398874989484820 /* phi / golden ratio */
+#endif
+#ifndef M_PI
+#define M_PI 3.14159265358979323846 /* pi */
+#endif
+#ifndef M_PI_2
+#define M_PI_2 1.57079632679489661923 /* pi/2 */
+#endif
+#ifndef M_SQRT1_2
+#define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */
+#endif
+#ifndef M_SQRT2
+#define M_SQRT2 1.41421356237309504880 /* sqrt(2) */
+#endif
+#ifndef NAN
+#define NAN av_int2float(0x7fc00000)
+#endif
+#ifndef INFINITY
+#define INFINITY av_int2float(0x7f800000)
+#endif
+
+/**
+ * @addtogroup lavu_math
+ *
+ * @{
+ */
+
+/**
+ * Rounding methods.
+ */
+enum AVRounding {
+ AV_ROUND_ZERO = 0, ///< Round toward zero.
+ AV_ROUND_INF = 1, ///< Round away from zero.
+ AV_ROUND_DOWN = 2, ///< Round toward -infinity.
+ AV_ROUND_UP = 3, ///< Round toward +infinity.
+ AV_ROUND_NEAR_INF = 5, ///< Round to nearest and halfway cases away from zero.
+ /**
+ * Flag telling rescaling functions to pass `INT64_MIN`/`MAX` through
+ * unchanged, avoiding special cases for #AV_NOPTS_VALUE.
+ *
+ * Unlike other values of the enumeration AVRounding, this value is a
+ * bitmask that must be used in conjunction with another value of the
+ * enumeration through a bitwise OR, in order to set behavior for normal
+ * cases.
+ *
+ * @code{.c}
+ * av_rescale_rnd(3, 1, 2, AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
+ * // Rescaling 3:
+ * // Calculating 3 * 1 / 2
+ * // 3 / 2 is rounded up to 2
+ * // => 2
+ *
+ * av_rescale_rnd(AV_NOPTS_VALUE, 1, 2, AV_ROUND_UP | AV_ROUND_PASS_MINMAX);
+ * // Rescaling AV_NOPTS_VALUE:
+ * // AV_NOPTS_VALUE == INT64_MIN
+ * // AV_NOPTS_VALUE is passed through
+ * // => AV_NOPTS_VALUE
+ * @endcode
+ */
+ AV_ROUND_PASS_MINMAX = 8192,
+};
+
+/**
+ * Compute the greatest common divisor of two integer operands.
+ *
+ * @param a,b Operands
+ * @return GCD of a and b up to sign; if a >= 0 and b >= 0, return value is >= 0;
+ * if a == 0 and b == 0, returns 0.
+ */
+int64_t av_const av_gcd(int64_t a, int64_t b);
+
+/**
+ * Rescale a 64-bit integer with rounding to nearest.
+ *
+ * The operation is mathematically equivalent to `a * b / c`, but writing that
+ * directly can overflow.
+ *
+ * This function is equivalent to av_rescale_rnd() with #AV_ROUND_NEAR_INF.
+ *
+ * @see av_rescale_rnd(), av_rescale_q(), av_rescale_q_rnd()
+ */
+int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const;
+
+/**
+ * Rescale a 64-bit integer with specified rounding.
+ *
+ * The operation is mathematically equivalent to `a * b / c`, but writing that
+ * directly can overflow, and does not support different rounding methods.
+ *
+ * @see av_rescale(), av_rescale_q(), av_rescale_q_rnd()
+ */
+int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd) av_const;
+
+/**
+ * Rescale a 64-bit integer by 2 rational numbers.
+ *
+ * The operation is mathematically equivalent to `a * bq / cq`.
+ *
+ * This function is equivalent to av_rescale_q_rnd() with #AV_ROUND_NEAR_INF.
+ *
+ * @see av_rescale(), av_rescale_rnd(), av_rescale_q_rnd()
+ */
+int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const;
+
+/**
+ * Rescale a 64-bit integer by 2 rational numbers with specified rounding.
+ *
+ * The operation is mathematically equivalent to `a * bq / cq`.
+ *
+ * @see av_rescale(), av_rescale_rnd(), av_rescale_q()
+ */
+int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq,
+ enum AVRounding rnd) av_const;
+
+/**
+ * Compare two timestamps each in its own time base.
+ *
+ * @return One of the following values:
+ * - -1 if `ts_a` is before `ts_b`
+ * - 1 if `ts_a` is after `ts_b`
+ * - 0 if they represent the same position
+ *
+ * @warning
+ * The result of the function is undefined if one of the timestamps is outside
+ * the `int64_t` range when represented in the other's timebase.
+ */
+int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b);
+
+/**
+ * Compare the remainders of two integer operands divided by a common divisor.
+ *
+ * In other words, compare the least significant `log2(mod)` bits of integers
+ * `a` and `b`.
+ *
+ * @code{.c}
+ * av_compare_mod(0x11, 0x02, 0x10) < 0 // since 0x11 % 0x10 (0x1) < 0x02 % 0x10 (0x2)
+ * av_compare_mod(0x11, 0x02, 0x20) > 0 // since 0x11 % 0x20 (0x11) > 0x02 % 0x20 (0x02)
+ * @endcode
+ *
+ * @param a,b Operands
+ * @param mod Divisor; must be a power of 2
+ * @return
+ * - a negative value if `a % mod < b % mod`
+ * - a positive value if `a % mod > b % mod`
+ * - zero if `a % mod == b % mod`
+ */
+int64_t av_compare_mod(uint64_t a, uint64_t b, uint64_t mod);
+
+/**
+ * Rescale a timestamp while preserving known durations.
+ *
+ * This function is designed to be called per audio packet to scale the input
+ * timestamp to a different time base. Compared to a simple av_rescale_q()
+ * call, this function is robust against possible inconsistent frame durations.
+ *
+ * The `last` parameter is a state variable that must be preserved for all
+ * subsequent calls for the same stream. For the first call, `*last` should be
+ * initialized to #AV_NOPTS_VALUE.
+ *
+ * @param[in] in_tb Input time base
+ * @param[in] in_ts Input timestamp
+ * @param[in] fs_tb Duration time base; typically this is finer-grained
+ * (greater) than `in_tb` and `out_tb`
+ * @param[in] duration Duration till the next call to this function (i.e.
+ * duration of the current packet/frame)
+ * @param[in,out] last Pointer to a timestamp expressed in terms of
+ * `fs_tb`, acting as a state variable
+ * @param[in] out_tb Output timebase
+ * @return Timestamp expressed in terms of `out_tb`
+ *
+ * @note In the context of this function, "duration" is in term of samples, not
+ * seconds.
+ */
+int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts, AVRational fs_tb, int duration, int64_t *last, AVRational out_tb);
+
+/**
+ * Add a value to a timestamp.
+ *
+ * This function guarantees that when the same value is repeatly added that
+ * no accumulation of rounding errors occurs.
+ *
+ * @param[in] ts Input timestamp
+ * @param[in] ts_tb Input timestamp time base
+ * @param[in] inc Value to be added
+ * @param[in] inc_tb Time base of `inc`
+ */
+int64_t av_add_stable(AVRational ts_tb, int64_t ts, AVRational inc_tb, int64_t inc);
+
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_MATHEMATICS_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/mem.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/mem.h
new file mode 100644
index 000000000..7e0b12a8a
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/mem.h
@@ -0,0 +1,700 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @ingroup lavu_mem
+ * Memory handling functions
+ */
+
+#ifndef AVUTIL_MEM_H
+#define AVUTIL_MEM_H
+
+#include <limits.h>
+#include <stdint.h>
+
+#include "attributes.h"
+#include "error.h"
+#include "avutil.h"
+
+/**
+ * @addtogroup lavu_mem
+ * Utilities for manipulating memory.
+ *
+ * FFmpeg has several applications of memory that are not required of a typical
+ * program. For example, the computing-heavy components like video decoding and
+ * encoding can be sped up significantly through the use of aligned memory.
+ *
+ * However, for each of FFmpeg's applications of memory, there might not be a
+ * recognized or standardized API for that specific use. Memory alignment, for
+ * instance, varies wildly depending on operating systems, architectures, and
+ * compilers. Hence, this component of @ref libavutil is created to make
+ * dealing with memory consistently possible on all platforms.
+ *
+ * @{
+ *
+ * @defgroup lavu_mem_macros Alignment Macros
+ * Helper macros for declaring aligned variables.
+ * @{
+ */
+
+/**
+ * @def DECLARE_ALIGNED(n,t,v)
+ * Declare a variable that is aligned in memory.
+ *
+ * @code{.c}
+ * DECLARE_ALIGNED(16, uint16_t, aligned_int) = 42;
+ * DECLARE_ALIGNED(32, uint8_t, aligned_array)[128];
+ *
+ * // The default-alignment equivalent would be
+ * uint16_t aligned_int = 42;
+ * uint8_t aligned_array[128];
+ * @endcode
+ *
+ * @param n Minimum alignment in bytes
+ * @param t Type of the variable (or array element)
+ * @param v Name of the variable
+ */
+
+/**
+ * @def DECLARE_ASM_ALIGNED(n,t,v)
+ * Declare an aligned variable appropriate for use in inline assembly code.
+ *
+ * @code{.c}
+ * DECLARE_ASM_ALIGNED(16, uint64_t, pw_08) = UINT64_C(0x0008000800080008);
+ * @endcode
+ *
+ * @param n Minimum alignment in bytes
+ * @param t Type of the variable (or array element)
+ * @param v Name of the variable
+ */
+
+/**
+ * @def DECLARE_ASM_CONST(n,t,v)
+ * Declare a static constant aligned variable appropriate for use in inline
+ * assembly code.
+ *
+ * @code{.c}
+ * DECLARE_ASM_CONST(16, uint64_t, pw_08) = UINT64_C(0x0008000800080008);
+ * @endcode
+ *
+ * @param n Minimum alignment in bytes
+ * @param t Type of the variable (or array element)
+ * @param v Name of the variable
+ */
+
+#if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 1110 || defined(__SUNPRO_C)
+ #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v
+ #define DECLARE_ASM_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v
+ #define DECLARE_ASM_CONST(n,t,v) const t __attribute__ ((aligned (n))) v
+#elif defined(__DJGPP__)
+ #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (FFMIN(n, 16)))) v
+ #define DECLARE_ASM_ALIGNED(n,t,v) t av_used __attribute__ ((aligned (FFMIN(n, 16)))) v
+ #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (FFMIN(n, 16)))) v
+#elif defined(__GNUC__) || defined(__clang__)
+ #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v
+ #define DECLARE_ASM_ALIGNED(n,t,v) t av_used __attribute__ ((aligned (n))) v
+ #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (n))) v
+#elif defined(_MSC_VER)
+ #define DECLARE_ALIGNED(n,t,v) __declspec(align(n)) t v
+ #define DECLARE_ASM_ALIGNED(n,t,v) __declspec(align(n)) t v
+ #define DECLARE_ASM_CONST(n,t,v) __declspec(align(n)) static const t v
+#else
+ #define DECLARE_ALIGNED(n,t,v) t v
+ #define DECLARE_ASM_ALIGNED(n,t,v) t v
+ #define DECLARE_ASM_CONST(n,t,v) static const t v
+#endif
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lavu_mem_attrs Function Attributes
+ * Function attributes applicable to memory handling functions.
+ *
+ * These function attributes can help compilers emit more useful warnings, or
+ * generate better code.
+ * @{
+ */
+
+/**
+ * @def av_malloc_attrib
+ * Function attribute denoting a malloc-like function.
+ *
+ * @see <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-g_t_0040code_007bmalloc_007d-function-attribute-3251">Function attribute `malloc` in GCC's documentation</a>
+ */
+
+#if AV_GCC_VERSION_AT_LEAST(3,1)
+ #define av_malloc_attrib __attribute__((__malloc__))
+#else
+ #define av_malloc_attrib
+#endif
+
+/**
+ * @def av_alloc_size(...)
+ * Function attribute used on a function that allocates memory, whose size is
+ * given by the specified parameter(s).
+ *
+ * @code{.c}
+ * void *av_malloc(size_t size) av_alloc_size(1);
+ * void *av_calloc(size_t nmemb, size_t size) av_alloc_size(1, 2);
+ * @endcode
+ *
+ * @param ... One or two parameter indexes, separated by a comma
+ *
+ * @see <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-g_t_0040code_007balloc_005fsize_007d-function-attribute-3220">Function attribute `alloc_size` in GCC's documentation</a>
+ */
+
+#if AV_GCC_VERSION_AT_LEAST(4,3)
+ #define av_alloc_size(...) __attribute__((alloc_size(__VA_ARGS__)))
+#else
+ #define av_alloc_size(...)
+#endif
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lavu_mem_funcs Heap Management
+ * Functions responsible for allocating, freeing, and copying memory.
+ *
+ * All memory allocation functions have a built-in upper limit of `INT_MAX`
+ * bytes. This may be changed with av_max_alloc(), although exercise extreme
+ * caution when doing so.
+ *
+ * @{
+ */
+
+/**
+ * Allocate a memory block with alignment suitable for all memory accesses
+ * (including vectors if available on the CPU).
+ *
+ * @param size Size in bytes for the memory block to be allocated
+ * @return Pointer to the allocated block, or `NULL` if the block cannot
+ * be allocated
+ * @see av_mallocz()
+ */
+void *av_malloc(size_t size) av_malloc_attrib av_alloc_size(1);
+
+/**
+ * Allocate a memory block with alignment suitable for all memory accesses
+ * (including vectors if available on the CPU) and zero all the bytes of the
+ * block.
+ *
+ * @param size Size in bytes for the memory block to be allocated
+ * @return Pointer to the allocated block, or `NULL` if it cannot be allocated
+ * @see av_malloc()
+ */
+void *av_mallocz(size_t size) av_malloc_attrib av_alloc_size(1);
+
+/**
+ * Allocate a memory block for an array with av_malloc().
+ *
+ * The allocated memory will have size `size * nmemb` bytes.
+ *
+ * @param nmemb Number of element
+ * @param size Size of a single element
+ * @return Pointer to the allocated block, or `NULL` if the block cannot
+ * be allocated
+ * @see av_malloc()
+ */
+av_alloc_size(1, 2) void *av_malloc_array(size_t nmemb, size_t size);
+
+/**
+ * Allocate a memory block for an array with av_mallocz().
+ *
+ * The allocated memory will have size `size * nmemb` bytes.
+ *
+ * @param nmemb Number of elements
+ * @param size Size of the single element
+ * @return Pointer to the allocated block, or `NULL` if the block cannot
+ * be allocated
+ *
+ * @see av_mallocz()
+ * @see av_malloc_array()
+ */
+av_alloc_size(1, 2) void *av_mallocz_array(size_t nmemb, size_t size);
+
+/**
+ * Non-inlined equivalent of av_mallocz_array().
+ *
+ * Created for symmetry with the calloc() C function.
+ */
+void *av_calloc(size_t nmemb, size_t size) av_malloc_attrib;
+
+/**
+ * Allocate, reallocate, or free a block of memory.
+ *
+ * If `ptr` is `NULL` and `size` > 0, allocate a new block. If `size` is
+ * zero, free the memory block pointed to by `ptr`. Otherwise, expand or
+ * shrink that block of memory according to `size`.
+ *
+ * @param ptr Pointer to a memory block already allocated with
+ * av_realloc() or `NULL`
+ * @param size Size in bytes of the memory block to be allocated or
+ * reallocated
+ *
+ * @return Pointer to a newly-reallocated block or `NULL` if the block
+ * cannot be reallocated or the function is used to free the memory block
+ *
+ * @warning Unlike av_malloc(), the returned pointer is not guaranteed to be
+ * correctly aligned.
+ * @see av_fast_realloc()
+ * @see av_reallocp()
+ */
+void *av_realloc(void *ptr, size_t size) av_alloc_size(2);
+
+/**
+ * Allocate, reallocate, or free a block of memory through a pointer to a
+ * pointer.
+ *
+ * If `*ptr` is `NULL` and `size` > 0, allocate a new block. If `size` is
+ * zero, free the memory block pointed to by `*ptr`. Otherwise, expand or
+ * shrink that block of memory according to `size`.
+ *
+ * @param[in,out] ptr Pointer to a pointer to a memory block already allocated
+ * with av_realloc(), or a pointer to `NULL`. The pointer
+ * is updated on success, or freed on failure.
+ * @param[in] size Size in bytes for the memory block to be allocated or
+ * reallocated
+ *
+ * @return Zero on success, an AVERROR error code on failure
+ *
+ * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be
+ * correctly aligned.
+ */
+av_warn_unused_result
+int av_reallocp(void *ptr, size_t size);
+
+/**
+ * Allocate, reallocate, or free a block of memory.
+ *
+ * This function does the same thing as av_realloc(), except:
+ * - It takes two size arguments and allocates `nelem * elsize` bytes,
+ * after checking the result of the multiplication for integer overflow.
+ * - It frees the input block in case of failure, thus avoiding the memory
+ * leak with the classic
+ * @code{.c}
+ * buf = realloc(buf);
+ * if (!buf)
+ * return -1;
+ * @endcode
+ * pattern.
+ */
+void *av_realloc_f(void *ptr, size_t nelem, size_t elsize);
+
+/**
+ * Allocate, reallocate, or free an array.
+ *
+ * If `ptr` is `NULL` and `nmemb` > 0, allocate a new block. If
+ * `nmemb` is zero, free the memory block pointed to by `ptr`.
+ *
+ * @param ptr Pointer to a memory block already allocated with
+ * av_realloc() or `NULL`
+ * @param nmemb Number of elements in the array
+ * @param size Size of the single element of the array
+ *
+ * @return Pointer to a newly-reallocated block or NULL if the block
+ * cannot be reallocated or the function is used to free the memory block
+ *
+ * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be
+ * correctly aligned.
+ * @see av_reallocp_array()
+ */
+av_alloc_size(2, 3) void *av_realloc_array(void *ptr, size_t nmemb, size_t size);
+
+/**
+ * Allocate, reallocate, or free an array through a pointer to a pointer.
+ *
+ * If `*ptr` is `NULL` and `nmemb` > 0, allocate a new block. If `nmemb` is
+ * zero, free the memory block pointed to by `*ptr`.
+ *
+ * @param[in,out] ptr Pointer to a pointer to a memory block already
+ * allocated with av_realloc(), or a pointer to `NULL`.
+ * The pointer is updated on success, or freed on failure.
+ * @param[in] nmemb Number of elements
+ * @param[in] size Size of the single element
+ *
+ * @return Zero on success, an AVERROR error code on failure
+ *
+ * @warning Unlike av_malloc(), the allocated memory is not guaranteed to be
+ * correctly aligned.
+ */
+av_alloc_size(2, 3) int av_reallocp_array(void *ptr, size_t nmemb, size_t size);
+
+/**
+ * Reallocate the given buffer if it is not large enough, otherwise do nothing.
+ *
+ * If the given buffer is `NULL`, then a new uninitialized buffer is allocated.
+ *
+ * If the given buffer is not large enough, and reallocation fails, `NULL` is
+ * returned and `*size` is set to 0, but the original buffer is not changed or
+ * freed.
+ *
+ * A typical use pattern follows:
+ *
+ * @code{.c}
+ * uint8_t *buf = ...;
+ * uint8_t *new_buf = av_fast_realloc(buf, &current_size, size_needed);
+ * if (!new_buf) {
+ * // Allocation failed; clean up original buffer
+ * av_freep(&buf);
+ * return AVERROR(ENOMEM);
+ * }
+ * @endcode
+ *
+ * @param[in,out] ptr Already allocated buffer, or `NULL`
+ * @param[in,out] size Pointer to current size of buffer `ptr`. `*size` is
+ * changed to `min_size` in case of success or 0 in
+ * case of failure
+ * @param[in] min_size New size of buffer `ptr`
+ * @return `ptr` if the buffer is large enough, a pointer to newly reallocated
+ * buffer if the buffer was not large enough, or `NULL` in case of
+ * error
+ * @see av_realloc()
+ * @see av_fast_malloc()
+ */
+void *av_fast_realloc(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Allocate a buffer, reusing the given one if large enough.
+ *
+ * Contrary to av_fast_realloc(), the current buffer contents might not be
+ * preserved and on error the old buffer is freed, thus no special handling to
+ * avoid memleaks is necessary.
+ *
+ * `*ptr` is allowed to be `NULL`, in which case allocation always happens if
+ * `size_needed` is greater than 0.
+ *
+ * @code{.c}
+ * uint8_t *buf = ...;
+ * av_fast_malloc(&buf, &current_size, size_needed);
+ * if (!buf) {
+ * // Allocation failed; buf already freed
+ * return AVERROR(ENOMEM);
+ * }
+ * @endcode
+ *
+ * @param[in,out] ptr Pointer to pointer to an already allocated buffer.
+ * `*ptr` will be overwritten with pointer to new
+ * buffer on success or `NULL` on failure
+ * @param[in,out] size Pointer to current size of buffer `*ptr`. `*size` is
+ * changed to `min_size` in case of success or 0 in
+ * case of failure
+ * @param[in] min_size New size of buffer `*ptr`
+ * @see av_realloc()
+ * @see av_fast_mallocz()
+ */
+void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Allocate and clear a buffer, reusing the given one if large enough.
+ *
+ * Like av_fast_malloc(), but all newly allocated space is initially cleared.
+ * Reused buffer is not cleared.
+ *
+ * `*ptr` is allowed to be `NULL`, in which case allocation always happens if
+ * `size_needed` is greater than 0.
+ *
+ * @param[in,out] ptr Pointer to pointer to an already allocated buffer.
+ * `*ptr` will be overwritten with pointer to new
+ * buffer on success or `NULL` on failure
+ * @param[in,out] size Pointer to current size of buffer `*ptr`. `*size` is
+ * changed to `min_size` in case of success or 0 in
+ * case of failure
+ * @param[in] min_size New size of buffer `*ptr`
+ * @see av_fast_malloc()
+ */
+void av_fast_mallocz(void *ptr, unsigned int *size, size_t min_size);
+
+/**
+ * Free a memory block which has been allocated with a function of av_malloc()
+ * or av_realloc() family.
+ *
+ * @param ptr Pointer to the memory block which should be freed.
+ *
+ * @note `ptr = NULL` is explicitly allowed.
+ * @note It is recommended that you use av_freep() instead, to prevent leaving
+ * behind dangling pointers.
+ * @see av_freep()
+ */
+void av_free(void *ptr);
+
+/**
+ * Free a memory block which has been allocated with a function of av_malloc()
+ * or av_realloc() family, and set the pointer pointing to it to `NULL`.
+ *
+ * @code{.c}
+ * uint8_t *buf = av_malloc(16);
+ * av_free(buf);
+ * // buf now contains a dangling pointer to freed memory, and accidental
+ * // dereference of buf will result in a use-after-free, which may be a
+ * // security risk.
+ *
+ * uint8_t *buf = av_malloc(16);
+ * av_freep(&buf);
+ * // buf is now NULL, and accidental dereference will only result in a
+ * // NULL-pointer dereference.
+ * @endcode
+ *
+ * @param ptr Pointer to the pointer to the memory block which should be freed
+ * @note `*ptr = NULL` is safe and leads to no action.
+ * @see av_free()
+ */
+void av_freep(void *ptr);
+
+/**
+ * Duplicate a string.
+ *
+ * @param s String to be duplicated
+ * @return Pointer to a newly-allocated string containing a
+ * copy of `s` or `NULL` if the string cannot be allocated
+ * @see av_strndup()
+ */
+char *av_strdup(const char *s) av_malloc_attrib;
+
+/**
+ * Duplicate a substring of a string.
+ *
+ * @param s String to be duplicated
+ * @param len Maximum length of the resulting string (not counting the
+ * terminating byte)
+ * @return Pointer to a newly-allocated string containing a
+ * substring of `s` or `NULL` if the string cannot be allocated
+ */
+char *av_strndup(const char *s, size_t len) av_malloc_attrib;
+
+/**
+ * Duplicate a buffer with av_malloc().
+ *
+ * @param p Buffer to be duplicated
+ * @param size Size in bytes of the buffer copied
+ * @return Pointer to a newly allocated buffer containing a
+ * copy of `p` or `NULL` if the buffer cannot be allocated
+ */
+void *av_memdup(const void *p, size_t size);
+
+/**
+ * Overlapping memcpy() implementation.
+ *
+ * @param dst Destination buffer
+ * @param back Number of bytes back to start copying (i.e. the initial size of
+ * the overlapping window); must be > 0
+ * @param cnt Number of bytes to copy; must be >= 0
+ *
+ * @note `cnt > back` is valid, this will copy the bytes we just copied,
+ * thus creating a repeating pattern with a period length of `back`.
+ */
+void av_memcpy_backptr(uint8_t *dst, int back, int cnt);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lavu_mem_dynarray Dynamic Array
+ *
+ * Utilities to make an array grow when needed.
+ *
+ * Sometimes, the programmer would want to have an array that can grow when
+ * needed. The libavutil dynamic array utilities fill that need.
+ *
+ * libavutil supports two systems of appending elements onto a dynamically
+ * allocated array, the first one storing the pointer to the value in the
+ * array, and the second storing the value directly. In both systems, the
+ * caller is responsible for maintaining a variable containing the length of
+ * the array, as well as freeing of the array after use.
+ *
+ * The first system stores pointers to values in a block of dynamically
+ * allocated memory. Since only pointers are stored, the function does not need
+ * to know the size of the type. Both av_dynarray_add() and
+ * av_dynarray_add_nofree() implement this system.
+ *
+ * @code
+ * type **array = NULL; //< an array of pointers to values
+ * int nb = 0; //< a variable to keep track of the length of the array
+ *
+ * type to_be_added = ...;
+ * type to_be_added2 = ...;
+ *
+ * av_dynarray_add(&array, &nb, &to_be_added);
+ * if (nb == 0)
+ * return AVERROR(ENOMEM);
+ *
+ * av_dynarray_add(&array, &nb, &to_be_added2);
+ * if (nb == 0)
+ * return AVERROR(ENOMEM);
+ *
+ * // Now:
+ * // nb == 2
+ * // &to_be_added == array[0]
+ * // &to_be_added2 == array[1]
+ *
+ * av_freep(&array);
+ * @endcode
+ *
+ * The second system stores the value directly in a block of memory. As a
+ * result, the function has to know the size of the type. av_dynarray2_add()
+ * implements this mechanism.
+ *
+ * @code
+ * type *array = NULL; //< an array of values
+ * int nb = 0; //< a variable to keep track of the length of the array
+ *
+ * type to_be_added = ...;
+ * type to_be_added2 = ...;
+ *
+ * type *addr = av_dynarray2_add((void **)&array, &nb, sizeof(*array), NULL);
+ * if (!addr)
+ * return AVERROR(ENOMEM);
+ * memcpy(addr, &to_be_added, sizeof(to_be_added));
+ *
+ * // Shortcut of the above.
+ * type *addr = av_dynarray2_add((void **)&array, &nb, sizeof(*array),
+ * (const void *)&to_be_added2);
+ * if (!addr)
+ * return AVERROR(ENOMEM);
+ *
+ * // Now:
+ * // nb == 2
+ * // to_be_added == array[0]
+ * // to_be_added2 == array[1]
+ *
+ * av_freep(&array);
+ * @endcode
+ *
+ * @{
+ */
+
+/**
+ * Add the pointer to an element to a dynamic array.
+ *
+ * The array to grow is supposed to be an array of pointers to
+ * structures, and the element to add must be a pointer to an already
+ * allocated structure.
+ *
+ * The array is reallocated when its size reaches powers of 2.
+ * Therefore, the amortized cost of adding an element is constant.
+ *
+ * In case of success, the pointer to the array is updated in order to
+ * point to the new grown array, and the number pointed to by `nb_ptr`
+ * is incremented.
+ * In case of failure, the array is freed, `*tab_ptr` is set to `NULL` and
+ * `*nb_ptr` is set to 0.
+ *
+ * @param[in,out] tab_ptr Pointer to the array to grow
+ * @param[in,out] nb_ptr Pointer to the number of elements in the array
+ * @param[in] elem Element to add
+ * @see av_dynarray_add_nofree(), av_dynarray2_add()
+ */
+void av_dynarray_add(void *tab_ptr, int *nb_ptr, void *elem);
+
+/**
+ * Add an element to a dynamic array.
+ *
+ * Function has the same functionality as av_dynarray_add(),
+ * but it doesn't free memory on fails. It returns error code
+ * instead and leave current buffer untouched.
+ *
+ * @return >=0 on success, negative otherwise
+ * @see av_dynarray_add(), av_dynarray2_add()
+ */
+av_warn_unused_result
+int av_dynarray_add_nofree(void *tab_ptr, int *nb_ptr, void *elem);
+
+/**
+ * Add an element of size `elem_size` to a dynamic array.
+ *
+ * The array is reallocated when its number of elements reaches powers of 2.
+ * Therefore, the amortized cost of adding an element is constant.
+ *
+ * In case of success, the pointer to the array is updated in order to
+ * point to the new grown array, and the number pointed to by `nb_ptr`
+ * is incremented.
+ * In case of failure, the array is freed, `*tab_ptr` is set to `NULL` and
+ * `*nb_ptr` is set to 0.
+ *
+ * @param[in,out] tab_ptr Pointer to the array to grow
+ * @param[in,out] nb_ptr Pointer to the number of elements in the array
+ * @param[in] elem_size Size in bytes of an element in the array
+ * @param[in] elem_data Pointer to the data of the element to add. If
+ * `NULL`, the space of the newly added element is
+ * allocated but left uninitialized.
+ *
+ * @return Pointer to the data of the element to copy in the newly allocated
+ * space
+ * @see av_dynarray_add(), av_dynarray_add_nofree()
+ */
+void *av_dynarray2_add(void **tab_ptr, int *nb_ptr, size_t elem_size,
+ const uint8_t *elem_data);
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lavu_mem_misc Miscellaneous Functions
+ *
+ * Other functions related to memory allocation.
+ *
+ * @{
+ */
+
+/**
+ * Multiply two `size_t` values checking for overflow.
+ *
+ * @param[in] a,b Operands of multiplication
+ * @param[out] r Pointer to the result of the operation
+ * @return 0 on success, AVERROR(EINVAL) on overflow
+ */
+static inline int av_size_mult(size_t a, size_t b, size_t *r)
+{
+ size_t t = a * b;
+ /* Hack inspired from glibc: don't try the division if nelem and elsize
+ * are both less than sqrt(SIZE_MAX). */
+ if ((a | b) >= ((size_t)1 << (sizeof(size_t) * 4)) && a && t / a != b)
+ return AVERROR(EINVAL);
+ *r = t;
+ return 0;
+}
+
+/**
+ * Set the maximum size that may be allocated in one block.
+ *
+ * The value specified with this function is effective for all libavutil's @ref
+ * lavu_mem_funcs "heap management functions."
+ *
+ * By default, the max value is defined as `INT_MAX`.
+ *
+ * @param max Value to be set as the new maximum size
+ *
+ * @warning Exercise extreme caution when using this function. Don't touch
+ * this if you do not understand the full consequence of doing so.
+ */
+void av_max_alloc(size_t max);
+
+/**
+ * @}
+ * @}
+ */
+
+#endif /* AVUTIL_MEM_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/pixfmt.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/pixfmt.h
new file mode 100644
index 000000000..e184a5667
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/pixfmt.h
@@ -0,0 +1,529 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_PIXFMT_H
+#define AVUTIL_PIXFMT_H
+
+/**
+ * @file
+ * pixel format definitions
+ */
+
+#include "libavutil/avconfig.h"
+#include "version.h"
+
+#define AVPALETTE_SIZE 1024
+#define AVPALETTE_COUNT 256
+
+/**
+ * Pixel format.
+ *
+ * @note
+ * AV_PIX_FMT_RGB32 is handled in an endian-specific manner. An RGBA
+ * color is put together as:
+ * (A << 24) | (R << 16) | (G << 8) | B
+ * This is stored as BGRA on little-endian CPU architectures and ARGB on
+ * big-endian CPUs.
+ *
+ * @par
+ * When the pixel format is palettized RGB32 (AV_PIX_FMT_PAL8), the palettized
+ * image data is stored in AVFrame.data[0]. The palette is transported in
+ * AVFrame.data[1], is 1024 bytes long (256 4-byte entries) and is
+ * formatted the same as in AV_PIX_FMT_RGB32 described above (i.e., it is
+ * also endian-specific). Note also that the individual RGB32 palette
+ * components stored in AVFrame.data[1] should be in the range 0..255.
+ * This is important as many custom PAL8 video codecs that were designed
+ * to run on the IBM VGA graphics adapter use 6-bit palette components.
+ *
+ * @par
+ * For all the 8 bits per pixel formats, an RGB32 palette is in data[1] like
+ * for pal8. This palette is filled in automatically by the function
+ * allocating the picture.
+ */
+enum AVPixelFormat {
+ AV_PIX_FMT_NONE = -1,
+ AV_PIX_FMT_YUV420P, ///< planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
+ AV_PIX_FMT_YUYV422, ///< packed YUV 4:2:2, 16bpp, Y0 Cb Y1 Cr
+ AV_PIX_FMT_RGB24, ///< packed RGB 8:8:8, 24bpp, RGBRGB...
+ AV_PIX_FMT_BGR24, ///< packed RGB 8:8:8, 24bpp, BGRBGR...
+ AV_PIX_FMT_YUV422P, ///< planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
+ AV_PIX_FMT_YUV444P, ///< planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
+ AV_PIX_FMT_YUV410P, ///< planar YUV 4:1:0, 9bpp, (1 Cr & Cb sample per 4x4 Y samples)
+ AV_PIX_FMT_YUV411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples)
+ AV_PIX_FMT_GRAY8, ///< Y , 8bpp
+ AV_PIX_FMT_MONOWHITE, ///< Y , 1bpp, 0 is white, 1 is black, in each byte pixels are ordered from the msb to the lsb
+ AV_PIX_FMT_MONOBLACK, ///< Y , 1bpp, 0 is black, 1 is white, in each byte pixels are ordered from the msb to the lsb
+ AV_PIX_FMT_PAL8, ///< 8 bits with AV_PIX_FMT_RGB32 palette
+ AV_PIX_FMT_YUVJ420P, ///< planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting color_range
+ AV_PIX_FMT_YUVJ422P, ///< planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting color_range
+ AV_PIX_FMT_YUVJ444P, ///< planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting color_range
+ AV_PIX_FMT_UYVY422, ///< packed YUV 4:2:2, 16bpp, Cb Y0 Cr Y1
+ AV_PIX_FMT_UYYVYY411, ///< packed YUV 4:1:1, 12bpp, Cb Y0 Y1 Cr Y2 Y3
+ AV_PIX_FMT_BGR8, ///< packed RGB 3:3:2, 8bpp, (msb)2B 3G 3R(lsb)
+ AV_PIX_FMT_BGR4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1B 2G 1R(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+ AV_PIX_FMT_BGR4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1B 2G 1R(lsb)
+ AV_PIX_FMT_RGB8, ///< packed RGB 3:3:2, 8bpp, (msb)2R 3G 3B(lsb)
+ AV_PIX_FMT_RGB4, ///< packed RGB 1:2:1 bitstream, 4bpp, (msb)1R 2G 1B(lsb), a byte contains two pixels, the first pixel in the byte is the one composed by the 4 msb bits
+ AV_PIX_FMT_RGB4_BYTE, ///< packed RGB 1:2:1, 8bpp, (msb)1R 2G 1B(lsb)
+ AV_PIX_FMT_NV12, ///< planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (first byte U and the following byte V)
+ AV_PIX_FMT_NV21, ///< as above, but U and V bytes are swapped
+
+ AV_PIX_FMT_ARGB, ///< packed ARGB 8:8:8:8, 32bpp, ARGBARGB...
+ AV_PIX_FMT_RGBA, ///< packed RGBA 8:8:8:8, 32bpp, RGBARGBA...
+ AV_PIX_FMT_ABGR, ///< packed ABGR 8:8:8:8, 32bpp, ABGRABGR...
+ AV_PIX_FMT_BGRA, ///< packed BGRA 8:8:8:8, 32bpp, BGRABGRA...
+
+ AV_PIX_FMT_GRAY16BE, ///< Y , 16bpp, big-endian
+ AV_PIX_FMT_GRAY16LE, ///< Y , 16bpp, little-endian
+ AV_PIX_FMT_YUV440P, ///< planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
+ AV_PIX_FMT_YUVJ440P, ///< planar YUV 4:4:0 full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV440P and setting color_range
+ AV_PIX_FMT_YUVA420P, ///< planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
+ AV_PIX_FMT_RGB48BE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as big-endian
+ AV_PIX_FMT_RGB48LE, ///< packed RGB 16:16:16, 48bpp, 16R, 16G, 16B, the 2-byte value for each R/G/B component is stored as little-endian
+
+ AV_PIX_FMT_RGB565BE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian
+ AV_PIX_FMT_RGB565LE, ///< packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian
+ AV_PIX_FMT_RGB555BE, ///< packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian , X=unused/undefined
+ AV_PIX_FMT_RGB555LE, ///< packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused/undefined
+
+ AV_PIX_FMT_BGR565BE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), big-endian
+ AV_PIX_FMT_BGR565LE, ///< packed BGR 5:6:5, 16bpp, (msb) 5B 6G 5R(lsb), little-endian
+ AV_PIX_FMT_BGR555BE, ///< packed BGR 5:5:5, 16bpp, (msb)1X 5B 5G 5R(lsb), big-endian , X=unused/undefined
+ AV_PIX_FMT_BGR555LE, ///< packed BGR 5:5:5, 16bpp, (msb)1X 5B 5G 5R(lsb), little-endian, X=unused/undefined
+
+#if FF_API_VAAPI
+ /** @name Deprecated pixel formats */
+ /**@{*/
+ AV_PIX_FMT_VAAPI_MOCO, ///< HW acceleration through VA API at motion compensation entry-point, Picture.data[3] contains a vaapi_render_state struct which contains macroblocks as well as various fields extracted from headers
+ AV_PIX_FMT_VAAPI_IDCT, ///< HW acceleration through VA API at IDCT entry-point, Picture.data[3] contains a vaapi_render_state struct which contains fields extracted from headers
+ AV_PIX_FMT_VAAPI_VLD, ///< HW decoding through VA API, Picture.data[3] contains a VASurfaceID
+ /**@}*/
+ AV_PIX_FMT_VAAPI = AV_PIX_FMT_VAAPI_VLD,
+#else
+ /**
+ * Hardware acceleration through VA-API, data[3] contains a
+ * VASurfaceID.
+ */
+ AV_PIX_FMT_VAAPI,
+#endif
+
+ AV_PIX_FMT_YUV420P16LE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+ AV_PIX_FMT_YUV420P16BE, ///< planar YUV 4:2:0, 24bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+ AV_PIX_FMT_YUV422P16LE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+ AV_PIX_FMT_YUV422P16BE, ///< planar YUV 4:2:2, 32bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+ AV_PIX_FMT_YUV444P16LE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+ AV_PIX_FMT_YUV444P16BE, ///< planar YUV 4:4:4, 48bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+ AV_PIX_FMT_DXVA2_VLD, ///< HW decoding through DXVA2, Picture.data[3] contains a LPDIRECT3DSURFACE9 pointer
+
+ AV_PIX_FMT_RGB444LE, ///< packed RGB 4:4:4, 16bpp, (msb)4X 4R 4G 4B(lsb), little-endian, X=unused/undefined
+ AV_PIX_FMT_RGB444BE, ///< packed RGB 4:4:4, 16bpp, (msb)4X 4R 4G 4B(lsb), big-endian, X=unused/undefined
+ AV_PIX_FMT_BGR444LE, ///< packed BGR 4:4:4, 16bpp, (msb)4X 4B 4G 4R(lsb), little-endian, X=unused/undefined
+ AV_PIX_FMT_BGR444BE, ///< packed BGR 4:4:4, 16bpp, (msb)4X 4B 4G 4R(lsb), big-endian, X=unused/undefined
+ AV_PIX_FMT_YA8, ///< 8 bits gray, 8 bits alpha
+
+ AV_PIX_FMT_Y400A = AV_PIX_FMT_YA8, ///< alias for AV_PIX_FMT_YA8
+ AV_PIX_FMT_GRAY8A= AV_PIX_FMT_YA8, ///< alias for AV_PIX_FMT_YA8
+
+ AV_PIX_FMT_BGR48BE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as big-endian
+ AV_PIX_FMT_BGR48LE, ///< packed RGB 16:16:16, 48bpp, 16B, 16G, 16R, the 2-byte value for each R/G/B component is stored as little-endian
+
+ /**
+ * The following 12 formats have the disadvantage of needing 1 format for each bit depth.
+ * Notice that each 9/10 bits sample is stored in 16 bits with extra padding.
+ * If you want to support multiple bit depths, then using AV_PIX_FMT_YUV420P16* with the bpp stored separately is better.
+ */
+ AV_PIX_FMT_YUV420P9BE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+ AV_PIX_FMT_YUV420P9LE, ///< planar YUV 4:2:0, 13.5bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+ AV_PIX_FMT_YUV420P10BE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+ AV_PIX_FMT_YUV420P10LE,///< planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+ AV_PIX_FMT_YUV422P10BE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+ AV_PIX_FMT_YUV422P10LE,///< planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+ AV_PIX_FMT_YUV444P9BE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+ AV_PIX_FMT_YUV444P9LE, ///< planar YUV 4:4:4, 27bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+ AV_PIX_FMT_YUV444P10BE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+ AV_PIX_FMT_YUV444P10LE,///< planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+ AV_PIX_FMT_YUV422P9BE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+ AV_PIX_FMT_YUV422P9LE, ///< planar YUV 4:2:2, 18bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+ AV_PIX_FMT_GBRP, ///< planar GBR 4:4:4 24bpp
+ AV_PIX_FMT_GBR24P = AV_PIX_FMT_GBRP, // alias for #AV_PIX_FMT_GBRP
+ AV_PIX_FMT_GBRP9BE, ///< planar GBR 4:4:4 27bpp, big-endian
+ AV_PIX_FMT_GBRP9LE, ///< planar GBR 4:4:4 27bpp, little-endian
+ AV_PIX_FMT_GBRP10BE, ///< planar GBR 4:4:4 30bpp, big-endian
+ AV_PIX_FMT_GBRP10LE, ///< planar GBR 4:4:4 30bpp, little-endian
+ AV_PIX_FMT_GBRP16BE, ///< planar GBR 4:4:4 48bpp, big-endian
+ AV_PIX_FMT_GBRP16LE, ///< planar GBR 4:4:4 48bpp, little-endian
+ AV_PIX_FMT_YUVA422P, ///< planar YUV 4:2:2 24bpp, (1 Cr & Cb sample per 2x1 Y & A samples)
+ AV_PIX_FMT_YUVA444P, ///< planar YUV 4:4:4 32bpp, (1 Cr & Cb sample per 1x1 Y & A samples)
+ AV_PIX_FMT_YUVA420P9BE, ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), big-endian
+ AV_PIX_FMT_YUVA420P9LE, ///< planar YUV 4:2:0 22.5bpp, (1 Cr & Cb sample per 2x2 Y & A samples), little-endian
+ AV_PIX_FMT_YUVA422P9BE, ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), big-endian
+ AV_PIX_FMT_YUVA422P9LE, ///< planar YUV 4:2:2 27bpp, (1 Cr & Cb sample per 2x1 Y & A samples), little-endian
+ AV_PIX_FMT_YUVA444P9BE, ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), big-endian
+ AV_PIX_FMT_YUVA444P9LE, ///< planar YUV 4:4:4 36bpp, (1 Cr & Cb sample per 1x1 Y & A samples), little-endian
+ AV_PIX_FMT_YUVA420P10BE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big-endian)
+ AV_PIX_FMT_YUVA420P10LE, ///< planar YUV 4:2:0 25bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little-endian)
+ AV_PIX_FMT_YUVA422P10BE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big-endian)
+ AV_PIX_FMT_YUVA422P10LE, ///< planar YUV 4:2:2 30bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little-endian)
+ AV_PIX_FMT_YUVA444P10BE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big-endian)
+ AV_PIX_FMT_YUVA444P10LE, ///< planar YUV 4:4:4 40bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian)
+ AV_PIX_FMT_YUVA420P16BE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, big-endian)
+ AV_PIX_FMT_YUVA420P16LE, ///< planar YUV 4:2:0 40bpp, (1 Cr & Cb sample per 2x2 Y & A samples, little-endian)
+ AV_PIX_FMT_YUVA422P16BE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, big-endian)
+ AV_PIX_FMT_YUVA422P16LE, ///< planar YUV 4:2:2 48bpp, (1 Cr & Cb sample per 2x1 Y & A samples, little-endian)
+ AV_PIX_FMT_YUVA444P16BE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, big-endian)
+ AV_PIX_FMT_YUVA444P16LE, ///< planar YUV 4:4:4 64bpp, (1 Cr & Cb sample per 1x1 Y & A samples, little-endian)
+
+ AV_PIX_FMT_VDPAU, ///< HW acceleration through VDPAU, Picture.data[3] contains a VdpVideoSurface
+
+ AV_PIX_FMT_XYZ12LE, ///< packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as little-endian, the 4 lower bits are set to 0
+ AV_PIX_FMT_XYZ12BE, ///< packed XYZ 4:4:4, 36 bpp, (msb) 12X, 12Y, 12Z (lsb), the 2-byte value for each X/Y/Z is stored as big-endian, the 4 lower bits are set to 0
+ AV_PIX_FMT_NV16, ///< interleaved chroma YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
+ AV_PIX_FMT_NV20LE, ///< interleaved chroma YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+ AV_PIX_FMT_NV20BE, ///< interleaved chroma YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+
+ AV_PIX_FMT_RGBA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+ AV_PIX_FMT_RGBA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16R, 16G, 16B, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+ AV_PIX_FMT_BGRA64BE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as big-endian
+ AV_PIX_FMT_BGRA64LE, ///< packed RGBA 16:16:16:16, 64bpp, 16B, 16G, 16R, 16A, the 2-byte value for each R/G/B/A component is stored as little-endian
+
+ AV_PIX_FMT_YVYU422, ///< packed YUV 4:2:2, 16bpp, Y0 Cr Y1 Cb
+
+ AV_PIX_FMT_YA16BE, ///< 16 bits gray, 16 bits alpha (big-endian)
+ AV_PIX_FMT_YA16LE, ///< 16 bits gray, 16 bits alpha (little-endian)
+
+ AV_PIX_FMT_GBRAP, ///< planar GBRA 4:4:4:4 32bpp
+ AV_PIX_FMT_GBRAP16BE, ///< planar GBRA 4:4:4:4 64bpp, big-endian
+ AV_PIX_FMT_GBRAP16LE, ///< planar GBRA 4:4:4:4 64bpp, little-endian
+ /**
+ * HW acceleration through QSV, data[3] contains a pointer to the
+ * mfxFrameSurface1 structure.
+ */
+ AV_PIX_FMT_QSV,
+ /**
+ * HW acceleration though MMAL, data[3] contains a pointer to the
+ * MMAL_BUFFER_HEADER_T structure.
+ */
+ AV_PIX_FMT_MMAL,
+
+ AV_PIX_FMT_D3D11VA_VLD, ///< HW decoding through Direct3D11 via old API, Picture.data[3] contains a ID3D11VideoDecoderOutputView pointer
+
+ /**
+ * HW acceleration through CUDA. data[i] contain CUdeviceptr pointers
+ * exactly as for system memory frames.
+ */
+ AV_PIX_FMT_CUDA,
+
+ AV_PIX_FMT_0RGB, ///< packed RGB 8:8:8, 32bpp, XRGBXRGB... X=unused/undefined
+ AV_PIX_FMT_RGB0, ///< packed RGB 8:8:8, 32bpp, RGBXRGBX... X=unused/undefined
+ AV_PIX_FMT_0BGR, ///< packed BGR 8:8:8, 32bpp, XBGRXBGR... X=unused/undefined
+ AV_PIX_FMT_BGR0, ///< packed BGR 8:8:8, 32bpp, BGRXBGRX... X=unused/undefined
+
+ AV_PIX_FMT_YUV420P12BE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+ AV_PIX_FMT_YUV420P12LE, ///< planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+ AV_PIX_FMT_YUV420P14BE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), big-endian
+ AV_PIX_FMT_YUV420P14LE, ///< planar YUV 4:2:0,21bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
+ AV_PIX_FMT_YUV422P12BE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+ AV_PIX_FMT_YUV422P12LE, ///< planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+ AV_PIX_FMT_YUV422P14BE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), big-endian
+ AV_PIX_FMT_YUV422P14LE, ///< planar YUV 4:2:2,28bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
+ AV_PIX_FMT_YUV444P12BE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+ AV_PIX_FMT_YUV444P12LE, ///< planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+ AV_PIX_FMT_YUV444P14BE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), big-endian
+ AV_PIX_FMT_YUV444P14LE, ///< planar YUV 4:4:4,42bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
+ AV_PIX_FMT_GBRP12BE, ///< planar GBR 4:4:4 36bpp, big-endian
+ AV_PIX_FMT_GBRP12LE, ///< planar GBR 4:4:4 36bpp, little-endian
+ AV_PIX_FMT_GBRP14BE, ///< planar GBR 4:4:4 42bpp, big-endian
+ AV_PIX_FMT_GBRP14LE, ///< planar GBR 4:4:4 42bpp, little-endian
+ AV_PIX_FMT_YUVJ411P, ///< planar YUV 4:1:1, 12bpp, (1 Cr & Cb sample per 4x1 Y samples) full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV411P and setting color_range
+
+ AV_PIX_FMT_BAYER_BGGR8, ///< bayer, BGBG..(odd line), GRGR..(even line), 8-bit samples */
+ AV_PIX_FMT_BAYER_RGGB8, ///< bayer, RGRG..(odd line), GBGB..(even line), 8-bit samples */
+ AV_PIX_FMT_BAYER_GBRG8, ///< bayer, GBGB..(odd line), RGRG..(even line), 8-bit samples */
+ AV_PIX_FMT_BAYER_GRBG8, ///< bayer, GRGR..(odd line), BGBG..(even line), 8-bit samples */
+ AV_PIX_FMT_BAYER_BGGR16LE, ///< bayer, BGBG..(odd line), GRGR..(even line), 16-bit samples, little-endian */
+ AV_PIX_FMT_BAYER_BGGR16BE, ///< bayer, BGBG..(odd line), GRGR..(even line), 16-bit samples, big-endian */
+ AV_PIX_FMT_BAYER_RGGB16LE, ///< bayer, RGRG..(odd line), GBGB..(even line), 16-bit samples, little-endian */
+ AV_PIX_FMT_BAYER_RGGB16BE, ///< bayer, RGRG..(odd line), GBGB..(even line), 16-bit samples, big-endian */
+ AV_PIX_FMT_BAYER_GBRG16LE, ///< bayer, GBGB..(odd line), RGRG..(even line), 16-bit samples, little-endian */
+ AV_PIX_FMT_BAYER_GBRG16BE, ///< bayer, GBGB..(odd line), RGRG..(even line), 16-bit samples, big-endian */
+ AV_PIX_FMT_BAYER_GRBG16LE, ///< bayer, GRGR..(odd line), BGBG..(even line), 16-bit samples, little-endian */
+ AV_PIX_FMT_BAYER_GRBG16BE, ///< bayer, GRGR..(odd line), BGBG..(even line), 16-bit samples, big-endian */
+
+ AV_PIX_FMT_XVMC,///< XVideo Motion Acceleration via common packet passing
+
+ AV_PIX_FMT_YUV440P10LE, ///< planar YUV 4:4:0,20bpp, (1 Cr & Cb sample per 1x2 Y samples), little-endian
+ AV_PIX_FMT_YUV440P10BE, ///< planar YUV 4:4:0,20bpp, (1 Cr & Cb sample per 1x2 Y samples), big-endian
+ AV_PIX_FMT_YUV440P12LE, ///< planar YUV 4:4:0,24bpp, (1 Cr & Cb sample per 1x2 Y samples), little-endian
+ AV_PIX_FMT_YUV440P12BE, ///< planar YUV 4:4:0,24bpp, (1 Cr & Cb sample per 1x2 Y samples), big-endian
+ AV_PIX_FMT_AYUV64LE, ///< packed AYUV 4:4:4,64bpp (1 Cr & Cb sample per 1x1 Y & A samples), little-endian
+ AV_PIX_FMT_AYUV64BE, ///< packed AYUV 4:4:4,64bpp (1 Cr & Cb sample per 1x1 Y & A samples), big-endian
+
+ AV_PIX_FMT_VIDEOTOOLBOX, ///< hardware decoding through Videotoolbox
+
+ AV_PIX_FMT_P010LE, ///< like NV12, with 10bpp per component, data in the high bits, zeros in the low bits, little-endian
+ AV_PIX_FMT_P010BE, ///< like NV12, with 10bpp per component, data in the high bits, zeros in the low bits, big-endian
+
+ AV_PIX_FMT_GBRAP12BE, ///< planar GBR 4:4:4:4 48bpp, big-endian
+ AV_PIX_FMT_GBRAP12LE, ///< planar GBR 4:4:4:4 48bpp, little-endian
+
+ AV_PIX_FMT_GBRAP10BE, ///< planar GBR 4:4:4:4 40bpp, big-endian
+ AV_PIX_FMT_GBRAP10LE, ///< planar GBR 4:4:4:4 40bpp, little-endian
+
+ AV_PIX_FMT_MEDIACODEC, ///< hardware decoding through MediaCodec
+
+ AV_PIX_FMT_GRAY12BE, ///< Y , 12bpp, big-endian
+ AV_PIX_FMT_GRAY12LE, ///< Y , 12bpp, little-endian
+ AV_PIX_FMT_GRAY10BE, ///< Y , 10bpp, big-endian
+ AV_PIX_FMT_GRAY10LE, ///< Y , 10bpp, little-endian
+
+ AV_PIX_FMT_P016LE, ///< like NV12, with 16bpp per component, little-endian
+ AV_PIX_FMT_P016BE, ///< like NV12, with 16bpp per component, big-endian
+
+ /**
+ * Hardware surfaces for Direct3D11.
+ *
+ * This is preferred over the legacy AV_PIX_FMT_D3D11VA_VLD. The new D3D11
+ * hwaccel API and filtering support AV_PIX_FMT_D3D11 only.
+ *
+ * data[0] contains a ID3D11Texture2D pointer, and data[1] contains the
+ * texture array index of the frame as intptr_t if the ID3D11Texture2D is
+ * an array texture (or always 0 if it's a normal texture).
+ */
+ AV_PIX_FMT_D3D11,
+
+ AV_PIX_FMT_GRAY9BE, ///< Y , 9bpp, big-endian
+ AV_PIX_FMT_GRAY9LE, ///< Y , 9bpp, little-endian
+
+ AV_PIX_FMT_GBRPF32BE, ///< IEEE-754 single precision planar GBR 4:4:4, 96bpp, big-endian
+ AV_PIX_FMT_GBRPF32LE, ///< IEEE-754 single precision planar GBR 4:4:4, 96bpp, little-endian
+ AV_PIX_FMT_GBRAPF32BE, ///< IEEE-754 single precision planar GBRA 4:4:4:4, 128bpp, big-endian
+ AV_PIX_FMT_GBRAPF32LE, ///< IEEE-754 single precision planar GBRA 4:4:4:4, 128bpp, little-endian
+
+ /**
+ * DRM-managed buffers exposed through PRIME buffer sharing.
+ *
+ * data[0] points to an AVDRMFrameDescriptor.
+ */
+ AV_PIX_FMT_DRM_PRIME,
+ /**
+ * Hardware surfaces for OpenCL.
+ *
+ * data[i] contain 2D image objects (typed in C as cl_mem, used
+ * in OpenCL as image2d_t) for each plane of the surface.
+ */
+ AV_PIX_FMT_OPENCL,
+
+ AV_PIX_FMT_NB ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions
+};
+
+#if AV_HAVE_BIGENDIAN
+# define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##be
+#else
+# define AV_PIX_FMT_NE(be, le) AV_PIX_FMT_##le
+#endif
+
+#define AV_PIX_FMT_RGB32 AV_PIX_FMT_NE(ARGB, BGRA)
+#define AV_PIX_FMT_RGB32_1 AV_PIX_FMT_NE(RGBA, ABGR)
+#define AV_PIX_FMT_BGR32 AV_PIX_FMT_NE(ABGR, RGBA)
+#define AV_PIX_FMT_BGR32_1 AV_PIX_FMT_NE(BGRA, ARGB)
+#define AV_PIX_FMT_0RGB32 AV_PIX_FMT_NE(0RGB, BGR0)
+#define AV_PIX_FMT_0BGR32 AV_PIX_FMT_NE(0BGR, RGB0)
+
+#define AV_PIX_FMT_GRAY9 AV_PIX_FMT_NE(GRAY9BE, GRAY9LE)
+#define AV_PIX_FMT_GRAY10 AV_PIX_FMT_NE(GRAY10BE, GRAY10LE)
+#define AV_PIX_FMT_GRAY12 AV_PIX_FMT_NE(GRAY12BE, GRAY12LE)
+#define AV_PIX_FMT_GRAY16 AV_PIX_FMT_NE(GRAY16BE, GRAY16LE)
+#define AV_PIX_FMT_YA16 AV_PIX_FMT_NE(YA16BE, YA16LE)
+#define AV_PIX_FMT_RGB48 AV_PIX_FMT_NE(RGB48BE, RGB48LE)
+#define AV_PIX_FMT_RGB565 AV_PIX_FMT_NE(RGB565BE, RGB565LE)
+#define AV_PIX_FMT_RGB555 AV_PIX_FMT_NE(RGB555BE, RGB555LE)
+#define AV_PIX_FMT_RGB444 AV_PIX_FMT_NE(RGB444BE, RGB444LE)
+#define AV_PIX_FMT_RGBA64 AV_PIX_FMT_NE(RGBA64BE, RGBA64LE)
+#define AV_PIX_FMT_BGR48 AV_PIX_FMT_NE(BGR48BE, BGR48LE)
+#define AV_PIX_FMT_BGR565 AV_PIX_FMT_NE(BGR565BE, BGR565LE)
+#define AV_PIX_FMT_BGR555 AV_PIX_FMT_NE(BGR555BE, BGR555LE)
+#define AV_PIX_FMT_BGR444 AV_PIX_FMT_NE(BGR444BE, BGR444LE)
+#define AV_PIX_FMT_BGRA64 AV_PIX_FMT_NE(BGRA64BE, BGRA64LE)
+
+#define AV_PIX_FMT_YUV420P9 AV_PIX_FMT_NE(YUV420P9BE , YUV420P9LE)
+#define AV_PIX_FMT_YUV422P9 AV_PIX_FMT_NE(YUV422P9BE , YUV422P9LE)
+#define AV_PIX_FMT_YUV444P9 AV_PIX_FMT_NE(YUV444P9BE , YUV444P9LE)
+#define AV_PIX_FMT_YUV420P10 AV_PIX_FMT_NE(YUV420P10BE, YUV420P10LE)
+#define AV_PIX_FMT_YUV422P10 AV_PIX_FMT_NE(YUV422P10BE, YUV422P10LE)
+#define AV_PIX_FMT_YUV440P10 AV_PIX_FMT_NE(YUV440P10BE, YUV440P10LE)
+#define AV_PIX_FMT_YUV444P10 AV_PIX_FMT_NE(YUV444P10BE, YUV444P10LE)
+#define AV_PIX_FMT_YUV420P12 AV_PIX_FMT_NE(YUV420P12BE, YUV420P12LE)
+#define AV_PIX_FMT_YUV422P12 AV_PIX_FMT_NE(YUV422P12BE, YUV422P12LE)
+#define AV_PIX_FMT_YUV440P12 AV_PIX_FMT_NE(YUV440P12BE, YUV440P12LE)
+#define AV_PIX_FMT_YUV444P12 AV_PIX_FMT_NE(YUV444P12BE, YUV444P12LE)
+#define AV_PIX_FMT_YUV420P14 AV_PIX_FMT_NE(YUV420P14BE, YUV420P14LE)
+#define AV_PIX_FMT_YUV422P14 AV_PIX_FMT_NE(YUV422P14BE, YUV422P14LE)
+#define AV_PIX_FMT_YUV444P14 AV_PIX_FMT_NE(YUV444P14BE, YUV444P14LE)
+#define AV_PIX_FMT_YUV420P16 AV_PIX_FMT_NE(YUV420P16BE, YUV420P16LE)
+#define AV_PIX_FMT_YUV422P16 AV_PIX_FMT_NE(YUV422P16BE, YUV422P16LE)
+#define AV_PIX_FMT_YUV444P16 AV_PIX_FMT_NE(YUV444P16BE, YUV444P16LE)
+
+#define AV_PIX_FMT_GBRP9 AV_PIX_FMT_NE(GBRP9BE , GBRP9LE)
+#define AV_PIX_FMT_GBRP10 AV_PIX_FMT_NE(GBRP10BE, GBRP10LE)
+#define AV_PIX_FMT_GBRP12 AV_PIX_FMT_NE(GBRP12BE, GBRP12LE)
+#define AV_PIX_FMT_GBRP14 AV_PIX_FMT_NE(GBRP14BE, GBRP14LE)
+#define AV_PIX_FMT_GBRP16 AV_PIX_FMT_NE(GBRP16BE, GBRP16LE)
+#define AV_PIX_FMT_GBRAP10 AV_PIX_FMT_NE(GBRAP10BE, GBRAP10LE)
+#define AV_PIX_FMT_GBRAP12 AV_PIX_FMT_NE(GBRAP12BE, GBRAP12LE)
+#define AV_PIX_FMT_GBRAP16 AV_PIX_FMT_NE(GBRAP16BE, GBRAP16LE)
+
+#define AV_PIX_FMT_BAYER_BGGR16 AV_PIX_FMT_NE(BAYER_BGGR16BE, BAYER_BGGR16LE)
+#define AV_PIX_FMT_BAYER_RGGB16 AV_PIX_FMT_NE(BAYER_RGGB16BE, BAYER_RGGB16LE)
+#define AV_PIX_FMT_BAYER_GBRG16 AV_PIX_FMT_NE(BAYER_GBRG16BE, BAYER_GBRG16LE)
+#define AV_PIX_FMT_BAYER_GRBG16 AV_PIX_FMT_NE(BAYER_GRBG16BE, BAYER_GRBG16LE)
+
+#define AV_PIX_FMT_GBRPF32 AV_PIX_FMT_NE(GBRPF32BE, GBRPF32LE)
+#define AV_PIX_FMT_GBRAPF32 AV_PIX_FMT_NE(GBRAPF32BE, GBRAPF32LE)
+
+#define AV_PIX_FMT_YUVA420P9 AV_PIX_FMT_NE(YUVA420P9BE , YUVA420P9LE)
+#define AV_PIX_FMT_YUVA422P9 AV_PIX_FMT_NE(YUVA422P9BE , YUVA422P9LE)
+#define AV_PIX_FMT_YUVA444P9 AV_PIX_FMT_NE(YUVA444P9BE , YUVA444P9LE)
+#define AV_PIX_FMT_YUVA420P10 AV_PIX_FMT_NE(YUVA420P10BE, YUVA420P10LE)
+#define AV_PIX_FMT_YUVA422P10 AV_PIX_FMT_NE(YUVA422P10BE, YUVA422P10LE)
+#define AV_PIX_FMT_YUVA444P10 AV_PIX_FMT_NE(YUVA444P10BE, YUVA444P10LE)
+#define AV_PIX_FMT_YUVA420P16 AV_PIX_FMT_NE(YUVA420P16BE, YUVA420P16LE)
+#define AV_PIX_FMT_YUVA422P16 AV_PIX_FMT_NE(YUVA422P16BE, YUVA422P16LE)
+#define AV_PIX_FMT_YUVA444P16 AV_PIX_FMT_NE(YUVA444P16BE, YUVA444P16LE)
+
+#define AV_PIX_FMT_XYZ12 AV_PIX_FMT_NE(XYZ12BE, XYZ12LE)
+#define AV_PIX_FMT_NV20 AV_PIX_FMT_NE(NV20BE, NV20LE)
+#define AV_PIX_FMT_AYUV64 AV_PIX_FMT_NE(AYUV64BE, AYUV64LE)
+#define AV_PIX_FMT_P010 AV_PIX_FMT_NE(P010BE, P010LE)
+#define AV_PIX_FMT_P016 AV_PIX_FMT_NE(P016BE, P016LE)
+
+/**
+ * Chromaticity coordinates of the source primaries.
+ * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.1.
+ */
+enum AVColorPrimaries {
+ AVCOL_PRI_RESERVED0 = 0,
+ AVCOL_PRI_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP177 Annex B
+ AVCOL_PRI_UNSPECIFIED = 2,
+ AVCOL_PRI_RESERVED = 3,
+ AVCOL_PRI_BT470M = 4, ///< also FCC Title 47 Code of Federal Regulations 73.682 (a)(20)
+
+ AVCOL_PRI_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM
+ AVCOL_PRI_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
+ AVCOL_PRI_SMPTE240M = 7, ///< functionally identical to above
+ AVCOL_PRI_FILM = 8, ///< colour filters using Illuminant C
+ AVCOL_PRI_BT2020 = 9, ///< ITU-R BT2020
+ AVCOL_PRI_SMPTE428 = 10, ///< SMPTE ST 428-1 (CIE 1931 XYZ)
+ AVCOL_PRI_SMPTEST428_1 = AVCOL_PRI_SMPTE428,
+ AVCOL_PRI_SMPTE431 = 11, ///< SMPTE ST 431-2 (2011) / DCI P3
+ AVCOL_PRI_SMPTE432 = 12, ///< SMPTE ST 432-1 (2010) / P3 D65 / Display P3
+ AVCOL_PRI_JEDEC_P22 = 22, ///< JEDEC P22 phosphors
+ AVCOL_PRI_NB ///< Not part of ABI
+};
+
+/**
+ * Color Transfer Characteristic.
+ * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.2.
+ */
+enum AVColorTransferCharacteristic {
+ AVCOL_TRC_RESERVED0 = 0,
+ AVCOL_TRC_BT709 = 1, ///< also ITU-R BT1361
+ AVCOL_TRC_UNSPECIFIED = 2,
+ AVCOL_TRC_RESERVED = 3,
+ AVCOL_TRC_GAMMA22 = 4, ///< also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM
+ AVCOL_TRC_GAMMA28 = 5, ///< also ITU-R BT470BG
+ AVCOL_TRC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 or 625 / ITU-R BT1358 525 or 625 / ITU-R BT1700 NTSC
+ AVCOL_TRC_SMPTE240M = 7,
+ AVCOL_TRC_LINEAR = 8, ///< "Linear transfer characteristics"
+ AVCOL_TRC_LOG = 9, ///< "Logarithmic transfer characteristic (100:1 range)"
+ AVCOL_TRC_LOG_SQRT = 10, ///< "Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)"
+ AVCOL_TRC_IEC61966_2_4 = 11, ///< IEC 61966-2-4
+ AVCOL_TRC_BT1361_ECG = 12, ///< ITU-R BT1361 Extended Colour Gamut
+ AVCOL_TRC_IEC61966_2_1 = 13, ///< IEC 61966-2-1 (sRGB or sYCC)
+ AVCOL_TRC_BT2020_10 = 14, ///< ITU-R BT2020 for 10-bit system
+ AVCOL_TRC_BT2020_12 = 15, ///< ITU-R BT2020 for 12-bit system
+ AVCOL_TRC_SMPTE2084 = 16, ///< SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems
+ AVCOL_TRC_SMPTEST2084 = AVCOL_TRC_SMPTE2084,
+ AVCOL_TRC_SMPTE428 = 17, ///< SMPTE ST 428-1
+ AVCOL_TRC_SMPTEST428_1 = AVCOL_TRC_SMPTE428,
+ AVCOL_TRC_ARIB_STD_B67 = 18, ///< ARIB STD-B67, known as "Hybrid log-gamma"
+ AVCOL_TRC_NB ///< Not part of ABI
+};
+
+/**
+ * YUV colorspace type.
+ * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.3.
+ */
+enum AVColorSpace {
+ AVCOL_SPC_RGB = 0, ///< order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB)
+ AVCOL_SPC_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B
+ AVCOL_SPC_UNSPECIFIED = 2,
+ AVCOL_SPC_RESERVED = 3,
+ AVCOL_SPC_FCC = 4, ///< FCC Title 47 Code of Federal Regulations 73.682 (a)(20)
+ AVCOL_SPC_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
+ AVCOL_SPC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
+ AVCOL_SPC_SMPTE240M = 7, ///< functionally identical to above
+ AVCOL_SPC_YCGCO = 8, ///< Used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16
+ AVCOL_SPC_YCOCG = AVCOL_SPC_YCGCO,
+ AVCOL_SPC_BT2020_NCL = 9, ///< ITU-R BT2020 non-constant luminance system
+ AVCOL_SPC_BT2020_CL = 10, ///< ITU-R BT2020 constant luminance system
+ AVCOL_SPC_SMPTE2085 = 11, ///< SMPTE 2085, Y'D'zD'x
+ AVCOL_SPC_CHROMA_DERIVED_NCL = 12, ///< Chromaticity-derived non-constant luminance system
+ AVCOL_SPC_CHROMA_DERIVED_CL = 13, ///< Chromaticity-derived constant luminance system
+ AVCOL_SPC_ICTCP = 14, ///< ITU-R BT.2100-0, ICtCp
+ AVCOL_SPC_NB ///< Not part of ABI
+};
+
+/**
+ * MPEG vs JPEG YUV range.
+ */
+enum AVColorRange {
+ AVCOL_RANGE_UNSPECIFIED = 0,
+ AVCOL_RANGE_MPEG = 1, ///< the normal 219*2^(n-8) "MPEG" YUV ranges
+ AVCOL_RANGE_JPEG = 2, ///< the normal 2^n-1 "JPEG" YUV ranges
+ AVCOL_RANGE_NB ///< Not part of ABI
+};
+
+/**
+ * Location of chroma samples.
+ *
+ * Illustration showing the location of the first (top left) chroma sample of the
+ * image, the left shows only luma, the right
+ * shows the location of the chroma sample, the 2 could be imagined to overlay
+ * each other but are drawn separately due to limitations of ASCII
+ *
+ * 1st 2nd 1st 2nd horizontal luma sample positions
+ * v v v v
+ * ______ ______
+ *1st luma line > |X X ... |3 4 X ... X are luma samples,
+ * | |1 2 1-6 are possible chroma positions
+ *2nd luma line > |X X ... |5 6 X ... 0 is undefined/unknown position
+ */
+enum AVChromaLocation {
+ AVCHROMA_LOC_UNSPECIFIED = 0,
+ AVCHROMA_LOC_LEFT = 1, ///< MPEG-2/4 4:2:0, H.264 default for 4:2:0
+ AVCHROMA_LOC_CENTER = 2, ///< MPEG-1 4:2:0, JPEG 4:2:0, H.263 4:2:0
+ AVCHROMA_LOC_TOPLEFT = 3, ///< ITU-R 601, SMPTE 274M 296M S314M(DV 4:1:1), mpeg2 4:2:2
+ AVCHROMA_LOC_TOP = 4,
+ AVCHROMA_LOC_BOTTOMLEFT = 5,
+ AVCHROMA_LOC_BOTTOM = 6,
+ AVCHROMA_LOC_NB ///< Not part of ABI
+};
+
+#endif /* AVUTIL_PIXFMT_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/rational.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/rational.h
new file mode 100644
index 000000000..5c6b67b4e
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/rational.h
@@ -0,0 +1,214 @@
+/*
+ * rational numbers
+ * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @ingroup lavu_math_rational
+ * Utilties for rational number calculation.
+ * @author Michael Niedermayer <michaelni@gmx.at>
+ */
+
+#ifndef AVUTIL_RATIONAL_H
+#define AVUTIL_RATIONAL_H
+
+#include <stdint.h>
+#include <limits.h>
+#include "attributes.h"
+
+/**
+ * @defgroup lavu_math_rational AVRational
+ * @ingroup lavu_math
+ * Rational number calculation.
+ *
+ * While rational numbers can be expressed as floating-point numbers, the
+ * conversion process is a lossy one, so are floating-point operations. On the
+ * other hand, the nature of FFmpeg demands highly accurate calculation of
+ * timestamps. This set of rational number utilities serves as a generic
+ * interface for manipulating rational numbers as pairs of numerators and
+ * denominators.
+ *
+ * Many of the functions that operate on AVRational's have the suffix `_q`, in
+ * reference to the mathematical symbol "ℚ" (Q) which denotes the set of all
+ * rational numbers.
+ *
+ * @{
+ */
+
+/**
+ * Rational number (pair of numerator and denominator).
+ */
+typedef struct AVRational{
+ int num; ///< Numerator
+ int den; ///< Denominator
+} AVRational;
+
+/**
+ * Create an AVRational.
+ *
+ * Useful for compilers that do not support compound literals.
+ *
+ * @note The return value is not reduced.
+ * @see av_reduce()
+ */
+static inline AVRational av_make_q(int num, int den)
+{
+ AVRational r = { num, den };
+ return r;
+}
+
+/**
+ * Compare two rationals.
+ *
+ * @param a First rational
+ * @param b Second rational
+ *
+ * @return One of the following values:
+ * - 0 if `a == b`
+ * - 1 if `a > b`
+ * - -1 if `a < b`
+ * - `INT_MIN` if one of the values is of the form `0 / 0`
+ */
+static inline int av_cmp_q(AVRational a, AVRational b){
+ const int64_t tmp= a.num * (int64_t)b.den - b.num * (int64_t)a.den;
+
+ if(tmp) return (int)((tmp ^ a.den ^ b.den)>>63)|1;
+ else if(b.den && a.den) return 0;
+ else if(a.num && b.num) return (a.num>>31) - (b.num>>31);
+ else return INT_MIN;
+}
+
+/**
+ * Convert an AVRational to a `double`.
+ * @param a AVRational to convert
+ * @return `a` in floating-point form
+ * @see av_d2q()
+ */
+static inline double av_q2d(AVRational a){
+ return a.num / (double) a.den;
+}
+
+/**
+ * Reduce a fraction.
+ *
+ * This is useful for framerate calculations.
+ *
+ * @param[out] dst_num Destination numerator
+ * @param[out] dst_den Destination denominator
+ * @param[in] num Source numerator
+ * @param[in] den Source denominator
+ * @param[in] max Maximum allowed values for `dst_num` & `dst_den`
+ * @return 1 if the operation is exact, 0 otherwise
+ */
+int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max);
+
+/**
+ * Multiply two rationals.
+ * @param b First rational
+ * @param c Second rational
+ * @return b*c
+ */
+AVRational av_mul_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Divide one rational by another.
+ * @param b First rational
+ * @param c Second rational
+ * @return b/c
+ */
+AVRational av_div_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Add two rationals.
+ * @param b First rational
+ * @param c Second rational
+ * @return b+c
+ */
+AVRational av_add_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Subtract one rational from another.
+ * @param b First rational
+ * @param c Second rational
+ * @return b-c
+ */
+AVRational av_sub_q(AVRational b, AVRational c) av_const;
+
+/**
+ * Invert a rational.
+ * @param q value
+ * @return 1 / q
+ */
+static av_always_inline AVRational av_inv_q(AVRational q)
+{
+ AVRational r = { q.den, q.num };
+ return r;
+}
+
+/**
+ * Convert a double precision floating point number to a rational.
+ *
+ * In case of infinity, the returned value is expressed as `{1, 0}` or
+ * `{-1, 0}` depending on the sign.
+ *
+ * @param d `double` to convert
+ * @param max Maximum allowed numerator and denominator
+ * @return `d` in AVRational form
+ * @see av_q2d()
+ */
+AVRational av_d2q(double d, int max) av_const;
+
+/**
+ * Find which of the two rationals is closer to another rational.
+ *
+ * @param q Rational to be compared against
+ * @param q1,q2 Rationals to be tested
+ * @return One of the following values:
+ * - 1 if `q1` is nearer to `q` than `q2`
+ * - -1 if `q2` is nearer to `q` than `q1`
+ * - 0 if they have the same distance
+ */
+int av_nearer_q(AVRational q, AVRational q1, AVRational q2);
+
+/**
+ * Find the value in a list of rationals nearest a given reference rational.
+ *
+ * @param q Reference rational
+ * @param q_list Array of rationals terminated by `{0, 0}`
+ * @return Index of the nearest value found in the array
+ */
+int av_find_nearest_q_idx(AVRational q, const AVRational* q_list);
+
+/**
+ * Convert an AVRational to a IEEE 32-bit `float` expressed in fixed-point
+ * format.
+ *
+ * @param q Rational to be converted
+ * @return Equivalent floating-point value, expressed as an unsigned 32-bit
+ * integer.
+ * @note The returned value is platform-indepedant.
+ */
+uint32_t av_q2intfloat(AVRational q);
+
+/**
+ * @}
+ */
+
+#endif /* AVUTIL_RATIONAL_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/samplefmt.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/samplefmt.h
new file mode 100644
index 000000000..8cd43ae85
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/samplefmt.h
@@ -0,0 +1,272 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_SAMPLEFMT_H
+#define AVUTIL_SAMPLEFMT_H
+
+#include <stdint.h>
+
+#include "avutil.h"
+#include "attributes.h"
+
+/**
+ * @addtogroup lavu_audio
+ * @{
+ *
+ * @defgroup lavu_sampfmts Audio sample formats
+ *
+ * Audio sample format enumeration and related convenience functions.
+ * @{
+ */
+
+/**
+ * Audio sample formats
+ *
+ * - The data described by the sample format is always in native-endian order.
+ * Sample values can be expressed by native C types, hence the lack of a signed
+ * 24-bit sample format even though it is a common raw audio data format.
+ *
+ * - The floating-point formats are based on full volume being in the range
+ * [-1.0, 1.0]. Any values outside this range are beyond full volume level.
+ *
+ * - The data layout as used in av_samples_fill_arrays() and elsewhere in FFmpeg
+ * (such as AVFrame in libavcodec) is as follows:
+ *
+ * @par
+ * For planar sample formats, each audio channel is in a separate data plane,
+ * and linesize is the buffer size, in bytes, for a single plane. All data
+ * planes must be the same size. For packed sample formats, only the first data
+ * plane is used, and samples for each channel are interleaved. In this case,
+ * linesize is the buffer size, in bytes, for the 1 plane.
+ *
+ */
+enum AVSampleFormat {
+ AV_SAMPLE_FMT_NONE = -1,
+ AV_SAMPLE_FMT_U8, ///< unsigned 8 bits
+ AV_SAMPLE_FMT_S16, ///< signed 16 bits
+ AV_SAMPLE_FMT_S32, ///< signed 32 bits
+ AV_SAMPLE_FMT_FLT, ///< float
+ AV_SAMPLE_FMT_DBL, ///< double
+
+ AV_SAMPLE_FMT_U8P, ///< unsigned 8 bits, planar
+ AV_SAMPLE_FMT_S16P, ///< signed 16 bits, planar
+ AV_SAMPLE_FMT_S32P, ///< signed 32 bits, planar
+ AV_SAMPLE_FMT_FLTP, ///< float, planar
+ AV_SAMPLE_FMT_DBLP, ///< double, planar
+ AV_SAMPLE_FMT_S64, ///< signed 64 bits
+ AV_SAMPLE_FMT_S64P, ///< signed 64 bits, planar
+
+ AV_SAMPLE_FMT_NB ///< Number of sample formats. DO NOT USE if linking dynamically
+};
+
+/**
+ * Return the name of sample_fmt, or NULL if sample_fmt is not
+ * recognized.
+ */
+const char *av_get_sample_fmt_name(enum AVSampleFormat sample_fmt);
+
+/**
+ * Return a sample format corresponding to name, or AV_SAMPLE_FMT_NONE
+ * on error.
+ */
+enum AVSampleFormat av_get_sample_fmt(const char *name);
+
+/**
+ * Return the planar<->packed alternative form of the given sample format, or
+ * AV_SAMPLE_FMT_NONE on error. If the passed sample_fmt is already in the
+ * requested planar/packed format, the format returned is the same as the
+ * input.
+ */
+enum AVSampleFormat av_get_alt_sample_fmt(enum AVSampleFormat sample_fmt, int planar);
+
+/**
+ * Get the packed alternative form of the given sample format.
+ *
+ * If the passed sample_fmt is already in packed format, the format returned is
+ * the same as the input.
+ *
+ * @return the packed alternative form of the given sample format or
+ AV_SAMPLE_FMT_NONE on error.
+ */
+enum AVSampleFormat av_get_packed_sample_fmt(enum AVSampleFormat sample_fmt);
+
+/**
+ * Get the planar alternative form of the given sample format.
+ *
+ * If the passed sample_fmt is already in planar format, the format returned is
+ * the same as the input.
+ *
+ * @return the planar alternative form of the given sample format or
+ AV_SAMPLE_FMT_NONE on error.
+ */
+enum AVSampleFormat av_get_planar_sample_fmt(enum AVSampleFormat sample_fmt);
+
+/**
+ * Generate a string corresponding to the sample format with
+ * sample_fmt, or a header if sample_fmt is negative.
+ *
+ * @param buf the buffer where to write the string
+ * @param buf_size the size of buf
+ * @param sample_fmt the number of the sample format to print the
+ * corresponding info string, or a negative value to print the
+ * corresponding header.
+ * @return the pointer to the filled buffer or NULL if sample_fmt is
+ * unknown or in case of other errors
+ */
+char *av_get_sample_fmt_string(char *buf, int buf_size, enum AVSampleFormat sample_fmt);
+
+/**
+ * Return number of bytes per sample.
+ *
+ * @param sample_fmt the sample format
+ * @return number of bytes per sample or zero if unknown for the given
+ * sample format
+ */
+int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt);
+
+/**
+ * Check if the sample format is planar.
+ *
+ * @param sample_fmt the sample format to inspect
+ * @return 1 if the sample format is planar, 0 if it is interleaved
+ */
+int av_sample_fmt_is_planar(enum AVSampleFormat sample_fmt);
+
+/**
+ * Get the required buffer size for the given audio parameters.
+ *
+ * @param[out] linesize calculated linesize, may be NULL
+ * @param nb_channels the number of channels
+ * @param nb_samples the number of samples in a single channel
+ * @param sample_fmt the sample format
+ * @param align buffer size alignment (0 = default, 1 = no alignment)
+ * @return required buffer size, or negative error code on failure
+ */
+int av_samples_get_buffer_size(int *linesize, int nb_channels, int nb_samples,
+ enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * @}
+ *
+ * @defgroup lavu_sampmanip Samples manipulation
+ *
+ * Functions that manipulate audio samples
+ * @{
+ */
+
+/**
+ * Fill plane data pointers and linesize for samples with sample
+ * format sample_fmt.
+ *
+ * The audio_data array is filled with the pointers to the samples data planes:
+ * for planar, set the start point of each channel's data within the buffer,
+ * for packed, set the start point of the entire buffer only.
+ *
+ * The value pointed to by linesize is set to the aligned size of each
+ * channel's data buffer for planar layout, or to the aligned size of the
+ * buffer for all channels for packed layout.
+ *
+ * The buffer in buf must be big enough to contain all the samples
+ * (use av_samples_get_buffer_size() to compute its minimum size),
+ * otherwise the audio_data pointers will point to invalid data.
+ *
+ * @see enum AVSampleFormat
+ * The documentation for AVSampleFormat describes the data layout.
+ *
+ * @param[out] audio_data array to be filled with the pointer for each channel
+ * @param[out] linesize calculated linesize, may be NULL
+ * @param buf the pointer to a buffer containing the samples
+ * @param nb_channels the number of channels
+ * @param nb_samples the number of samples in a single channel
+ * @param sample_fmt the sample format
+ * @param align buffer size alignment (0 = default, 1 = no alignment)
+ * @return >=0 on success or a negative error code on failure
+ * @todo return minimum size in bytes required for the buffer in case
+ * of success at the next bump
+ */
+int av_samples_fill_arrays(uint8_t **audio_data, int *linesize,
+ const uint8_t *buf,
+ int nb_channels, int nb_samples,
+ enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Allocate a samples buffer for nb_samples samples, and fill data pointers and
+ * linesize accordingly.
+ * The allocated samples buffer can be freed by using av_freep(&audio_data[0])
+ * Allocated data will be initialized to silence.
+ *
+ * @see enum AVSampleFormat
+ * The documentation for AVSampleFormat describes the data layout.
+ *
+ * @param[out] audio_data array to be filled with the pointer for each channel
+ * @param[out] linesize aligned size for audio buffer(s), may be NULL
+ * @param nb_channels number of audio channels
+ * @param nb_samples number of samples per channel
+ * @param align buffer size alignment (0 = default, 1 = no alignment)
+ * @return >=0 on success or a negative error code on failure
+ * @todo return the size of the allocated buffer in case of success at the next bump
+ * @see av_samples_fill_arrays()
+ * @see av_samples_alloc_array_and_samples()
+ */
+int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels,
+ int nb_samples, enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Allocate a data pointers array, samples buffer for nb_samples
+ * samples, and fill data pointers and linesize accordingly.
+ *
+ * This is the same as av_samples_alloc(), but also allocates the data
+ * pointers array.
+ *
+ * @see av_samples_alloc()
+ */
+int av_samples_alloc_array_and_samples(uint8_t ***audio_data, int *linesize, int nb_channels,
+ int nb_samples, enum AVSampleFormat sample_fmt, int align);
+
+/**
+ * Copy samples from src to dst.
+ *
+ * @param dst destination array of pointers to data planes
+ * @param src source array of pointers to data planes
+ * @param dst_offset offset in samples at which the data will be written to dst
+ * @param src_offset offset in samples at which the data will be read from src
+ * @param nb_samples number of samples to be copied
+ * @param nb_channels number of audio channels
+ * @param sample_fmt audio sample format
+ */
+int av_samples_copy(uint8_t **dst, uint8_t * const *src, int dst_offset,
+ int src_offset, int nb_samples, int nb_channels,
+ enum AVSampleFormat sample_fmt);
+
+/**
+ * Fill an audio buffer with silence.
+ *
+ * @param audio_data array of pointers to data planes
+ * @param offset offset in samples at which to start filling
+ * @param nb_samples number of samples to fill
+ * @param nb_channels number of audio channels
+ * @param sample_fmt audio sample format
+ */
+int av_samples_set_silence(uint8_t **audio_data, int offset, int nb_samples,
+ int nb_channels, enum AVSampleFormat sample_fmt);
+
+/**
+ * @}
+ * @}
+ */
+#endif /* AVUTIL_SAMPLEFMT_H */
diff --git a/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/version.h b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/version.h
new file mode 100644
index 000000000..3a63e6355
--- /dev/null
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/include/libavutil/version.h
@@ -0,0 +1,139 @@
+/*
+ * copyright (c) 2003 Fabrice Bellard
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * @ingroup lavu
+ * Libavutil version macros
+ */
+
+#ifndef AVUTIL_VERSION_H
+#define AVUTIL_VERSION_H
+
+#include "macros.h"
+
+/**
+ * @addtogroup version_utils
+ *
+ * Useful to check and match library version in order to maintain
+ * backward compatibility.
+ *
+ * The FFmpeg libraries follow a versioning sheme very similar to
+ * Semantic Versioning (http://semver.org/)
+ * The difference is that the component called PATCH is called MICRO in FFmpeg
+ * and its value is reset to 100 instead of 0 to keep it above or equal to 100.
+ * Also we do not increase MICRO for every bugfix or change in git master.
+ *
+ * Prior to FFmpeg 3.2 point releases did not change any lib version number to
+ * avoid aliassing different git master checkouts.
+ * Starting with FFmpeg 3.2, the released library versions will occupy
+ * a separate MAJOR.MINOR that is not used on the master development branch.
+ * That is if we branch a release of master 55.10.123 we will bump to 55.11.100
+ * for the release and master will continue at 55.12.100 after it. Each new
+ * point release will then bump the MICRO improving the usefulness of the lib
+ * versions.
+ *
+ * @{
+ */
+
+#define AV_VERSION_INT(a, b, c) ((a)<<16 | (b)<<8 | (c))
+#define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c
+#define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c)
+
+/**
+ * Extract version components from the full ::AV_VERSION_INT int as returned
+ * by functions like ::avformat_version() and ::avcodec_version()
+ */
+#define AV_VERSION_MAJOR(a) ((a) >> 16)
+#define AV_VERSION_MINOR(a) (((a) & 0x00FF00) >> 8)
+#define AV_VERSION_MICRO(a) ((a) & 0xFF)
+
+/**
+ * @}
+ */
+
+/**
+ * @defgroup lavu_ver Version and Build diagnostics
+ *
+ * Macros and function useful to check at compiletime and at runtime
+ * which version of libavutil is in use.
+ *
+ * @{
+ */
+
+#define LIBAVUTIL_VERSION_MAJOR 56
+#define LIBAVUTIL_VERSION_MINOR 14
+#define LIBAVUTIL_VERSION_MICRO 100
+
+#define LIBAVUTIL_VERSION_INT AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
+ LIBAVUTIL_VERSION_MINOR, \
+ LIBAVUTIL_VERSION_MICRO)
+#define LIBAVUTIL_VERSION AV_VERSION(LIBAVUTIL_VERSION_MAJOR, \
+ LIBAVUTIL_VERSION_MINOR, \
+ LIBAVUTIL_VERSION_MICRO)
+#define LIBAVUTIL_BUILD LIBAVUTIL_VERSION_INT
+
+#define LIBAVUTIL_IDENT "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION)
+
+/**
+ * @defgroup lavu_depr_guards Deprecation Guards
+ * FF_API_* defines may be placed below to indicate public API that will be
+ * dropped at a future version bump. The defines themselves are not part of
+ * the public API and may change, break or disappear at any time.
+ *
+ * @note, when bumping the major version it is recommended to manually
+ * disable each FF_API_* in its own commit instead of disabling them all
+ * at once through the bump. This improves the git bisect-ability of the change.
+ *
+ * @{
+ */
+
+#ifndef FF_API_VAAPI
+#define FF_API_VAAPI (LIBAVUTIL_VERSION_MAJOR < 57)
+#endif
+#ifndef FF_API_FRAME_QP
+#define FF_API_FRAME_QP (LIBAVUTIL_VERSION_MAJOR < 57)
+#endif
+#ifndef FF_API_PLUS1_MINUS1
+#define FF_API_PLUS1_MINUS1 (LIBAVUTIL_VERSION_MAJOR < 57)
+#endif
+#ifndef FF_API_ERROR_FRAME
+#define FF_API_ERROR_FRAME (LIBAVUTIL_VERSION_MAJOR < 57)
+#endif
+#ifndef FF_API_PKT_PTS
+#define FF_API_PKT_PTS (LIBAVUTIL_VERSION_MAJOR < 57)
+#endif
+#ifndef FF_API_CRYPTO_SIZE_T
+#define FF_API_CRYPTO_SIZE_T (LIBAVUTIL_VERSION_MAJOR < 57)
+#endif
+#ifndef FF_API_FRAME_GET_SET
+#define FF_API_FRAME_GET_SET (LIBAVUTIL_VERSION_MAJOR < 57)
+#endif
+#ifndef FF_API_PSEUDOPAL
+#define FF_API_PSEUDOPAL (LIBAVUTIL_VERSION_MAJOR < 57)
+#endif
+
+
+/**
+ * @}
+ * @}
+ */
+
+#endif /* AVUTIL_VERSION_H */
diff --git a/dom/media/encoder/fmp4_muxer/moz.build b/dom/media/platforms/ffmpeg/ffmpeg58/moz.build
index 5ff274be5..6bd5db8d7 100644
--- a/dom/media/encoder/fmp4_muxer/moz.build
+++ b/dom/media/platforms/ffmpeg/ffmpeg58/moz.build
@@ -4,19 +4,22 @@
# License, v. 2.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 += [
- 'ISOMediaWriter.h',
- 'ISOTrackMetadata.h',
-]
-
UNIFIED_SOURCES += [
- 'AMRBox.cpp',
- 'AVCBox.cpp',
- 'EVRCBox.cpp',
- 'ISOControl.cpp',
- 'ISOMediaBoxes.cpp',
- 'ISOMediaWriter.cpp',
- 'MP4ESDS.cpp',
+ '../FFmpegAudioDecoder.cpp',
+ '../FFmpegDataDecoder.cpp',
+ '../FFmpegDecoderModule.cpp',
+ '../FFmpegVideoDecoder.cpp',
]
+LOCAL_INCLUDES += [
+ '..',
+ 'include',
+]
+
+if CONFIG['GNU_CXX']:
+ CXXFLAGS += [ '-Wno-deprecated-declarations' ]
+if CONFIG['CLANG_CXX']:
+ CXXFLAGS += [
+ '-Wno-unknown-attributes',
+ ]
FINAL_LIBRARY = 'xul'
diff --git a/dom/media/platforms/ffmpeg/moz.build b/dom/media/platforms/ffmpeg/moz.build
index 604e445aa..af96fb521 100644
--- a/dom/media/platforms/ffmpeg/moz.build
+++ b/dom/media/platforms/ffmpeg/moz.build
@@ -13,6 +13,7 @@ DIRS += [
'libav54',
'libav55',
'ffmpeg57',
+ 'ffmpeg58',
]
UNIFIED_SOURCES += [
diff --git a/dom/media/platforms/gonk/GonkAudioDecoderManager.cpp b/dom/media/platforms/gonk/GonkAudioDecoderManager.cpp
deleted file mode 100644
index 0bc3fbea9..000000000
--- a/dom/media/platforms/gonk/GonkAudioDecoderManager.cpp
+++ /dev/null
@@ -1,268 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "MediaCodecProxy.h"
-#include <OMX_IVCommon.h>
-#include <gui/Surface.h>
-#include <ICrypto.h>
-#include "GonkAudioDecoderManager.h"
-#include "MediaDecoderReader.h"
-#include "VideoUtils.h"
-#include "nsTArray.h"
-#include "mozilla/Logging.h"
-#include "stagefright/MediaBuffer.h"
-#include "stagefright/MetaData.h"
-#include "stagefright/MediaErrors.h"
-#include <stagefright/foundation/AMessage.h>
-#include <stagefright/foundation/ALooper.h>
-#include "media/openmax/OMX_Audio.h"
-#include "MediaData.h"
-#include "MediaInfo.h"
-
-#define CODECCONFIG_TIMEOUT_US 10000LL
-#define READ_OUTPUT_BUFFER_TIMEOUT_US 0LL
-
-#include <android/log.h>
-#define GADM_LOG(...) __android_log_print(ANDROID_LOG_DEBUG, "GonkAudioDecoderManager", __VA_ARGS__)
-
-#define LOG(...) MOZ_LOG(sPDMLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
-
-using namespace android;
-typedef android::MediaCodecProxy MediaCodecProxy;
-
-namespace mozilla {
-
-GonkAudioDecoderManager::GonkAudioDecoderManager(const AudioInfo& aConfig)
- : mAudioChannels(aConfig.mChannels)
- , mAudioRate(aConfig.mRate)
- , mAudioProfile(aConfig.mProfile)
- , mAudioCompactor(mAudioQueue)
-{
- MOZ_COUNT_CTOR(GonkAudioDecoderManager);
- MOZ_ASSERT(mAudioChannels);
- mCodecSpecificData = aConfig.mCodecSpecificConfig;
- mMimeType = aConfig.mMimeType;
-}
-
-GonkAudioDecoderManager::~GonkAudioDecoderManager()
-{
- MOZ_COUNT_DTOR(GonkAudioDecoderManager);
-}
-
-RefPtr<MediaDataDecoder::InitPromise>
-GonkAudioDecoderManager::Init()
-{
- if (InitMediaCodecProxy()) {
- return InitPromise::CreateAndResolve(TrackType::kAudioTrack, __func__);
- } else {
- return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
- }
-}
-
-bool
-GonkAudioDecoderManager::InitMediaCodecProxy()
-{
- status_t rv = OK;
- if (!InitLoopers(MediaData::AUDIO_DATA)) {
- return false;
- }
-
- mDecoder = MediaCodecProxy::CreateByType(mDecodeLooper, mMimeType.get(), false);
- if (!mDecoder.get()) {
- return false;
- }
- if (!mDecoder->AllocateAudioMediaCodec())
- {
- mDecoder = nullptr;
- return false;
- }
- sp<AMessage> format = new AMessage;
- // Fixed values
- GADM_LOG("Configure audio mime type:%s, chan no:%d, sample-rate:%d, profile:%d",
- mMimeType.get(), mAudioChannels, mAudioRate, mAudioProfile);
- format->setString("mime", mMimeType.get());
- format->setInt32("channel-count", mAudioChannels);
- format->setInt32("sample-rate", mAudioRate);
- format->setInt32("aac-profile", mAudioProfile);
- status_t err = mDecoder->configure(format, nullptr, nullptr, 0);
- if (err != OK || !mDecoder->Prepare()) {
- return false;
- }
-
- if (mMimeType.EqualsLiteral("audio/mp4a-latm")) {
- rv = mDecoder->Input(mCodecSpecificData->Elements(), mCodecSpecificData->Length(), 0,
- android::MediaCodec::BUFFER_FLAG_CODECCONFIG,
- CODECCONFIG_TIMEOUT_US);
- }
-
- if (rv == OK) {
- return true;
- } else {
- GADM_LOG("Failed to input codec specific data!");
- return false;
- }
-}
-
-nsresult
-GonkAudioDecoderManager::CreateAudioData(MediaBuffer* aBuffer, int64_t aStreamOffset)
-{
- if (!(aBuffer != nullptr && aBuffer->data() != nullptr)) {
- GADM_LOG("Audio Buffer is not valid!");
- return NS_ERROR_UNEXPECTED;
- }
-
- int64_t timeUs;
- if (!aBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
- return NS_ERROR_UNEXPECTED;
- }
-
- if (aBuffer->range_length() == 0) {
- // Some decoders may return spurious empty buffers that we just want to ignore
- // quoted from Android's AwesomePlayer.cpp
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- if (mLastTime > timeUs) {
- GADM_LOG("Output decoded sample time is revert. time=%lld", timeUs);
- MOZ_ASSERT(false);
- return NS_ERROR_NOT_AVAILABLE;
- }
- mLastTime = timeUs;
-
- const uint8_t *data = static_cast<const uint8_t*>(aBuffer->data());
- size_t dataOffset = aBuffer->range_offset();
- size_t size = aBuffer->range_length();
-
- uint32_t frames = size / (2 * mAudioChannels);
-
- CheckedInt64 duration = FramesToUsecs(frames, mAudioRate);
- if (!duration.isValid()) {
- return NS_ERROR_UNEXPECTED;
- }
-
- typedef AudioCompactor::NativeCopy OmxCopy;
- mAudioCompactor.Push(aStreamOffset,
- timeUs,
- mAudioRate,
- frames,
- mAudioChannels,
- OmxCopy(data+dataOffset,
- size,
- mAudioChannels));
- return NS_OK;
-}
-
-nsresult
-GonkAudioDecoderManager::Output(int64_t aStreamOffset,
- RefPtr<MediaData>& aOutData)
-{
- aOutData = nullptr;
- if (mAudioQueue.GetSize() > 0) {
- aOutData = mAudioQueue.PopFront();
- return mAudioQueue.AtEndOfStream() ? NS_ERROR_ABORT : NS_OK;
- }
-
- status_t err;
- MediaBuffer* audioBuffer = nullptr;
- err = mDecoder->Output(&audioBuffer, READ_OUTPUT_BUFFER_TIMEOUT_US);
- AutoReleaseMediaBuffer a(audioBuffer, mDecoder.get());
-
- switch (err) {
- case OK:
- {
- nsresult rv = CreateAudioData(audioBuffer, aStreamOffset);
- NS_ENSURE_SUCCESS(rv, rv);
- break;
- }
- case android::INFO_FORMAT_CHANGED:
- {
- // If the format changed, update our cached info.
- GADM_LOG("Decoder format changed");
- sp<AMessage> audioCodecFormat;
-
- if (mDecoder->getOutputFormat(&audioCodecFormat) != OK ||
- audioCodecFormat == nullptr) {
- return NS_ERROR_UNEXPECTED;
- }
-
- int32_t codec_channel_count = 0;
- int32_t codec_sample_rate = 0;
-
- if (!audioCodecFormat->findInt32("channel-count", &codec_channel_count) ||
- !audioCodecFormat->findInt32("sample-rate", &codec_sample_rate)) {
- return NS_ERROR_UNEXPECTED;
- }
-
- // Update AudioInfo
- AudioConfig::ChannelLayout layout(codec_channel_count);
- if (!layout.IsValid()) {
- return NS_ERROR_FAILURE;
- }
- mAudioChannels = codec_channel_count;
- mAudioRate = codec_sample_rate;
-
- return Output(aStreamOffset, aOutData);
- }
- case android::INFO_OUTPUT_BUFFERS_CHANGED:
- {
- GADM_LOG("Info Output Buffers Changed");
- if (mDecoder->UpdateOutputBuffers()) {
- return Output(aStreamOffset, aOutData);
- }
- return NS_ERROR_FAILURE;
- }
- case -EAGAIN:
- {
- return NS_ERROR_NOT_AVAILABLE;
- }
- case android::ERROR_END_OF_STREAM:
- {
- GADM_LOG("Got EOS frame!");
- nsresult rv = CreateAudioData(audioBuffer, aStreamOffset);
- NS_ENSURE_SUCCESS(rv, NS_ERROR_ABORT);
- MOZ_ASSERT(mAudioQueue.GetSize() > 0);
- mAudioQueue.Finish();
- break;
- }
- case -ETIMEDOUT:
- {
- GADM_LOG("Timeout. can try again next time");
- return NS_ERROR_UNEXPECTED;
- }
- default:
- {
- GADM_LOG("Decoder failed, err=%d", err);
- return NS_ERROR_UNEXPECTED;
- }
- }
-
- if (mAudioQueue.GetSize() > 0) {
- aOutData = mAudioQueue.PopFront();
- // Return NS_ERROR_ABORT at the last sample.
- return mAudioQueue.AtEndOfStream() ? NS_ERROR_ABORT : NS_OK;
- }
-
- return NS_ERROR_NOT_AVAILABLE;
-}
-
-void
-GonkAudioDecoderManager::ProcessFlush()
-{
- GADM_LOG("FLUSH<<<");
- mAudioQueue.Reset();
- GADM_LOG(">>>FLUSH");
- GonkDecoderManager::ProcessFlush();
-}
-
-void
-GonkAudioDecoderManager::ResetEOS()
-{
- GADM_LOG("ResetEOS(<<<");
- mAudioQueue.Reset();
- GADM_LOG(">>>ResetEOS(");
- GonkDecoderManager::ResetEOS();
-}
-
-} // namespace mozilla
diff --git a/dom/media/platforms/gonk/GonkAudioDecoderManager.h b/dom/media/platforms/gonk/GonkAudioDecoderManager.h
deleted file mode 100644
index aa35d620e..000000000
--- a/dom/media/platforms/gonk/GonkAudioDecoderManager.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(GonkAudioDecoderManager_h_)
-#define GonkAudioDecoderManager_h_
-
-#include "AudioCompactor.h"
-#include "mozilla/RefPtr.h"
-#include "GonkMediaDataDecoder.h"
-
-using namespace android;
-
-namespace android {
-class MOZ_EXPORT MediaBuffer;
-} // namespace android
-
-namespace mozilla {
-
-class GonkAudioDecoderManager : public GonkDecoderManager {
-typedef android::MediaCodecProxy MediaCodecProxy;
-public:
- GonkAudioDecoderManager(const AudioInfo& aConfig);
-
- virtual ~GonkAudioDecoderManager();
-
- RefPtr<InitPromise> Init() override;
-
- nsresult Output(int64_t aStreamOffset,
- RefPtr<MediaData>& aOutput) override;
-
- void ProcessFlush() override;
- virtual void ResetEOS() override;
-
- const char* GetDescriptionName() const override
- {
- return "gonk audio decoder";
- }
-
-private:
- bool InitMediaCodecProxy();
-
- nsresult CreateAudioData(MediaBuffer* aBuffer, int64_t aStreamOffset);
-
- uint32_t mAudioChannels;
- uint32_t mAudioRate;
- const uint32_t mAudioProfile;
-
- MediaQueue<AudioData> mAudioQueue;
-
- AudioCompactor mAudioCompactor;
-
-};
-
-} // namespace mozilla
-
-#endif // GonkAudioDecoderManager_h_
diff --git a/dom/media/platforms/gonk/GonkDecoderModule.cpp b/dom/media/platforms/gonk/GonkDecoderModule.cpp
deleted file mode 100644
index 537bc299c..000000000
--- a/dom/media/platforms/gonk/GonkDecoderModule.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "GonkDecoderModule.h"
-#include "GonkVideoDecoderManager.h"
-#include "GonkAudioDecoderManager.h"
-#include "mozilla/DebugOnly.h"
-#include "GonkMediaDataDecoder.h"
-
-namespace mozilla {
-GonkDecoderModule::GonkDecoderModule()
-{
-}
-
-GonkDecoderModule::~GonkDecoderModule()
-{
-}
-
-already_AddRefed<MediaDataDecoder>
-GonkDecoderModule::CreateVideoDecoder(const CreateDecoderParams& aParams)
-{
- RefPtr<MediaDataDecoder> decoder =
- new GonkMediaDataDecoder(new GonkVideoDecoderManager(aParams.mImageContainer, aParams.VideoConfig()),
- aParams.mCallback);
- return decoder.forget();
-}
-
-already_AddRefed<MediaDataDecoder>
-GonkDecoderModule::CreateAudioDecoder(const CreateDecoderParams& aParams)
-{
- RefPtr<MediaDataDecoder> decoder =
- new GonkMediaDataDecoder(new GonkAudioDecoderManager(aParams.AudioConfig()),
- aParams.mCallback);
- return decoder.forget();
-}
-
-PlatformDecoderModule::ConversionRequired
-GonkDecoderModule::DecoderNeedsConversion(const TrackInfo& aConfig) const
-{
- if (aConfig.IsVideo()) {
- return ConversionRequired::kNeedAnnexB;
- } else {
- return ConversionRequired::kNeedNone;
- }
-}
-
-bool
-GonkDecoderModule::SupportsMimeType(const nsACString& aMimeType,
- DecoderDoctorDiagnostics* aDiagnostics) const
-{
- return aMimeType.EqualsLiteral("audio/mp4a-latm") ||
- aMimeType.EqualsLiteral("audio/3gpp") ||
- aMimeType.EqualsLiteral("audio/amr-wb") ||
- aMimeType.EqualsLiteral("audio/mpeg") ||
- aMimeType.EqualsLiteral("video/mp4") ||
- aMimeType.EqualsLiteral("video/mp4v-es") ||
- aMimeType.EqualsLiteral("video/avc") ||
- aMimeType.EqualsLiteral("video/3gpp");
-}
-
-} // namespace mozilla
diff --git a/dom/media/platforms/gonk/GonkDecoderModule.h b/dom/media/platforms/gonk/GonkDecoderModule.h
deleted file mode 100644
index 4f29f0e75..000000000
--- a/dom/media/platforms/gonk/GonkDecoderModule.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(GonkPlatformDecoderModule_h_)
-#define GonkPlatformDecoderModule_h_
-
-#include "PlatformDecoderModule.h"
-
-namespace mozilla {
-
-class GonkDecoderModule : public PlatformDecoderModule {
-public:
- GonkDecoderModule();
- virtual ~GonkDecoderModule();
-
- // Decode thread.
- already_AddRefed<MediaDataDecoder>
- CreateVideoDecoder(const CreateDecoderParams& aParams) override;
-
- // Decode thread.
- already_AddRefed<MediaDataDecoder>
- CreateAudioDecoder(const CreateDecoderParams& aParams) override;
-
- ConversionRequired
- DecoderNeedsConversion(const TrackInfo& aConfig) const override;
-
- bool SupportsMimeType(const nsACString& aMimeType,
- DecoderDoctorDiagnostics* aDiagnostics) const override;
-
-};
-
-} // namespace mozilla
-
-#endif
diff --git a/dom/media/platforms/gonk/GonkMediaDataDecoder.cpp b/dom/media/platforms/gonk/GonkMediaDataDecoder.cpp
deleted file mode 100644
index 6d59d72e1..000000000
--- a/dom/media/platforms/gonk/GonkMediaDataDecoder.cpp
+++ /dev/null
@@ -1,385 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "GonkMediaDataDecoder.h"
-#include "VideoUtils.h"
-#include "nsTArray.h"
-#include "MediaCodecProxy.h"
-
-#include <stagefright/foundation/ADebug.h>
-
-#include "mozilla/Logging.h"
-#include <android/log.h>
-#define GMDD_LOG(...) __android_log_print(ANDROID_LOG_DEBUG, "GonkMediaDataDecoder", __VA_ARGS__)
-#define INPUT_TIMEOUT_US 0LL // Don't wait for buffer if none is available.
-#define MIN_QUEUED_SAMPLES 2
-
-#ifdef DEBUG
-#include <utils/AndroidThreads.h>
-#endif
-
-#define LOG(...) MOZ_LOG(sPDMLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
-
-using namespace android;
-
-namespace mozilla {
-
-bool
-GonkDecoderManager::InitLoopers(MediaData::Type aType)
-{
- MOZ_ASSERT(mDecodeLooper.get() == nullptr && mTaskLooper.get() == nullptr);
- MOZ_ASSERT(aType == MediaData::VIDEO_DATA || aType == MediaData::AUDIO_DATA);
-
- const char* suffix = (aType == MediaData::VIDEO_DATA ? "video" : "audio");
- mDecodeLooper = new ALooper;
- android::AString name("MediaCodecProxy/");
- name.append(suffix);
- mDecodeLooper->setName(name.c_str());
-
- mTaskLooper = new ALooper;
- name.setTo("GonkDecoderManager/");
- name.append(suffix);
- mTaskLooper->setName(name.c_str());
- mTaskLooper->registerHandler(this);
-
-#ifdef DEBUG
- sp<AMessage> findThreadId(new AMessage(kNotifyFindLooperId, id()));
- findThreadId->post();
-#endif
-
- return mDecodeLooper->start() == OK && mTaskLooper->start() == OK;
-}
-
-nsresult
-GonkDecoderManager::Input(MediaRawData* aSample)
-{
- RefPtr<MediaRawData> sample;
-
- if (aSample) {
- sample = aSample;
- } else {
- // It means EOS with empty sample.
- sample = new MediaRawData();
- }
- {
- MutexAutoLock lock(mMutex);
- mQueuedSamples.AppendElement(sample);
- }
-
- sp<AMessage> input = new AMessage(kNotifyProcessInput, id());
- if (!aSample) {
- input->setInt32("input-eos", 1);
- }
- input->post();
- return NS_OK;
-}
-
-int32_t
-GonkDecoderManager::ProcessQueuedSamples()
-{
- MOZ_ASSERT(OnTaskLooper());
-
- MutexAutoLock lock(mMutex);
- status_t rv;
- while (mQueuedSamples.Length()) {
- RefPtr<MediaRawData> data = mQueuedSamples.ElementAt(0);
- rv = mDecoder->Input(reinterpret_cast<const uint8_t*>(data->Data()),
- data->Size(),
- data->mTime,
- 0,
- INPUT_TIMEOUT_US);
- if (rv == OK) {
- mQueuedSamples.RemoveElementAt(0);
- mWaitOutput.AppendElement(WaitOutputInfo(data->mOffset, data->mTime,
- /* eos */ data->Data() == nullptr));
- } else if (rv == -EAGAIN || rv == -ETIMEDOUT) {
- // In most cases, EAGAIN or ETIMEOUT are safe because OMX can't fill
- // buffer on time.
- break;
- } else {
- return rv;
- }
- }
- return mQueuedSamples.Length();
-}
-
-nsresult
-GonkDecoderManager::Flush()
-{
- if (mDecoder == nullptr) {
- GMDD_LOG("Decoder is not initialized");
- return NS_ERROR_UNEXPECTED;
- }
-
- if (!mInitPromise.IsEmpty()) {
- return NS_OK;
- }
-
- {
- MutexAutoLock lock(mMutex);
- mQueuedSamples.Clear();
- }
-
- MonitorAutoLock lock(mFlushMonitor);
- mIsFlushing = true;
- sp<AMessage> flush = new AMessage(kNotifyProcessFlush, id());
- flush->post();
- while (mIsFlushing) {
- lock.Wait();
- }
- return NS_OK;
-}
-
-nsresult
-GonkDecoderManager::Shutdown()
-{
- if (mDecoder.get()) {
- mDecoder->stop();
- mDecoder->ReleaseMediaResources();
- mDecoder = nullptr;
- }
-
- mInitPromise.RejectIfExists(NS_ERROR_DOM_MEDIA_CANCELED, __func__);
-
- return NS_OK;
-}
-
-size_t
-GonkDecoderManager::NumQueuedSamples()
-{
- MutexAutoLock lock(mMutex);
- return mQueuedSamples.Length();
-}
-
-void
-GonkDecoderManager::ProcessInput(bool aEndOfStream)
-{
- MOZ_ASSERT(OnTaskLooper());
-
- status_t rv = ProcessQueuedSamples();
- if (rv >= 0) {
- if (!aEndOfStream && rv <= MIN_QUEUED_SAMPLES) {
- mDecodeCallback->InputExhausted();
- }
-
- if (mToDo.get() == nullptr) {
- mToDo = new AMessage(kNotifyDecoderActivity, id());
- if (aEndOfStream) {
- mToDo->setInt32("input-eos", 1);
- }
- mDecoder->requestActivityNotification(mToDo);
- } else if (aEndOfStream) {
- mToDo->setInt32("input-eos", 1);
- }
- } else {
- GMDD_LOG("input processed: error#%d", rv);
- mDecodeCallback->Error(MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR,
- __func__));
- }
-}
-
-void
-GonkDecoderManager::ProcessFlush()
-{
- MOZ_ASSERT(OnTaskLooper());
-
- mLastTime = INT64_MIN;
- MonitorAutoLock lock(mFlushMonitor);
- mWaitOutput.Clear();
- if (mDecoder->flush() != OK) {
- GMDD_LOG("flush error");
- mDecodeCallback->Error(MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR,
- __func__));
- }
- mIsFlushing = false;
- lock.NotifyAll();
-}
-
-// Use output timestamp to determine which output buffer is already returned
-// and remove corresponding info, except for EOS, from the waiting list.
-// This method handles the cases that audio decoder sends multiple output
-// buffers for one input.
-void
-GonkDecoderManager::UpdateWaitingList(int64_t aForgetUpTo)
-{
- MOZ_ASSERT(OnTaskLooper());
-
- size_t i;
- for (i = 0; i < mWaitOutput.Length(); i++) {
- const auto& item = mWaitOutput.ElementAt(i);
- if (item.mEOS || item.mTimestamp > aForgetUpTo) {
- break;
- }
- }
- if (i > 0) {
- mWaitOutput.RemoveElementsAt(0, i);
- }
-}
-
-void
-GonkDecoderManager::ProcessToDo(bool aEndOfStream)
-{
- MOZ_ASSERT(OnTaskLooper());
-
- MOZ_ASSERT(mToDo.get() != nullptr);
- mToDo.clear();
-
- if (NumQueuedSamples() > 0 && ProcessQueuedSamples() < 0) {
- mDecodeCallback->Error(MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR,
- __func__));
- return;
- }
-
- while (mWaitOutput.Length() > 0) {
- RefPtr<MediaData> output;
- WaitOutputInfo wait = mWaitOutput.ElementAt(0);
- nsresult rv = Output(wait.mOffset, output);
- if (rv == NS_OK) {
- MOZ_ASSERT(output);
- mDecodeCallback->Output(output);
- UpdateWaitingList(output->mTime);
- } else if (rv == NS_ERROR_ABORT) {
- // EOS
- MOZ_ASSERT(mQueuedSamples.IsEmpty());
- if (output) {
- mDecodeCallback->Output(output);
- UpdateWaitingList(output->mTime);
- }
- MOZ_ASSERT(mWaitOutput.Length() == 1);
- mWaitOutput.RemoveElementAt(0);
- mDecodeCallback->DrainComplete();
- ResetEOS();
- return;
- } else if (rv == NS_ERROR_NOT_AVAILABLE) {
- break;
- } else {
- mDecodeCallback->Error(MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR,
- __func__));
- return;
- }
- }
-
- if (!aEndOfStream && NumQueuedSamples() <= MIN_QUEUED_SAMPLES) {
- mDecodeCallback->InputExhausted();
- // No need to shedule todo task this time because InputExhausted() will
- // cause Input() to be invoked and do it for us.
- return;
- }
-
- if (NumQueuedSamples() || mWaitOutput.Length() > 0) {
- mToDo = new AMessage(kNotifyDecoderActivity, id());
- if (aEndOfStream) {
- mToDo->setInt32("input-eos", 1);
- }
- mDecoder->requestActivityNotification(mToDo);
- }
-}
-
-void
-GonkDecoderManager::ResetEOS()
-{
- // After eos, android::MediaCodec needs to be flushed to receive next input
- mWaitOutput.Clear();
- if (mDecoder->flush() != OK) {
- GMDD_LOG("flush error");
- mDecodeCallback->Error(MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR,
- __func__));
- }
-}
-
-void
-GonkDecoderManager::onMessageReceived(const sp<AMessage> &aMessage)
-{
- switch (aMessage->what()) {
- case kNotifyProcessInput:
- {
- int32_t eos = 0;
- ProcessInput(aMessage->findInt32("input-eos", &eos) && eos);
- break;
- }
- case kNotifyProcessFlush:
- {
- ProcessFlush();
- break;
- }
- case kNotifyDecoderActivity:
- {
- int32_t eos = 0;
- ProcessToDo(aMessage->findInt32("input-eos", &eos) && eos);
- break;
- }
-#ifdef DEBUG
- case kNotifyFindLooperId:
- {
- mTaskLooperId = androidGetThreadId();
- MOZ_ASSERT(mTaskLooperId);
- break;
- }
-#endif
- default:
- {
- TRESPASS();
- break;
- }
- }
-}
-
-#ifdef DEBUG
-bool
-GonkDecoderManager::OnTaskLooper()
-{
- return androidGetThreadId() == mTaskLooperId;
-}
-#endif
-
-GonkMediaDataDecoder::GonkMediaDataDecoder(GonkDecoderManager* aManager,
- MediaDataDecoderCallback* aCallback)
- : mManager(aManager)
-{
- MOZ_COUNT_CTOR(GonkMediaDataDecoder);
- mManager->SetDecodeCallback(aCallback);
-}
-
-GonkMediaDataDecoder::~GonkMediaDataDecoder()
-{
- MOZ_COUNT_DTOR(GonkMediaDataDecoder);
-}
-
-RefPtr<MediaDataDecoder::InitPromise>
-GonkMediaDataDecoder::Init()
-{
- return mManager->Init();
-}
-
-void
-GonkMediaDataDecoder::Shutdown()
-{
- mManager->Shutdown();
-
- // Because codec allocated runnable and init promise is at reader TaskQueue,
- // so manager needs to be destroyed at reader TaskQueue to prevent racing.
- mManager = nullptr;
-}
-
-// Inserts data into the decoder's pipeline.
-void
-GonkMediaDataDecoder::Input(MediaRawData* aSample)
-{
- mManager->Input(aSample);
-}
-
-void
-GonkMediaDataDecoder::Flush()
-{
- mManager->Flush();
-}
-
-void
-GonkMediaDataDecoder::Drain()
-{
- mManager->Input(nullptr);
-}
-
-} // namespace mozilla
diff --git a/dom/media/platforms/gonk/GonkMediaDataDecoder.h b/dom/media/platforms/gonk/GonkMediaDataDecoder.h
deleted file mode 100644
index bba2a8645..000000000
--- a/dom/media/platforms/gonk/GonkMediaDataDecoder.h
+++ /dev/null
@@ -1,214 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(GonkMediaDataDecoder_h_)
-#define GonkMediaDataDecoder_h_
-#include "PlatformDecoderModule.h"
-#include <stagefright/foundation/AHandler.h>
-
-namespace android {
-struct ALooper;
-class MediaBuffer;
-class MediaCodecProxy;
-} // namespace android
-
-namespace mozilla {
-class MediaRawData;
-
-// Manage the data flow from inputting encoded data and outputting decode data.
-class GonkDecoderManager : public android::AHandler {
-public:
- typedef TrackInfo::TrackType TrackType;
- typedef MediaDataDecoder::InitPromise InitPromise;
-
- virtual ~GonkDecoderManager() {}
-
- virtual RefPtr<InitPromise> Init() = 0;
- virtual const char* GetDescriptionName() const = 0;
-
- // Asynchronously send sample into mDecoder. If out of input buffer, aSample
- // will be queued for later re-send.
- nsresult Input(MediaRawData* aSample);
-
- // Flush the queued samples and signal decoder to throw all pending input/output away.
- nsresult Flush();
-
- // Shutdown decoder and rejects the init promise.
- virtual nsresult Shutdown();
-
- // How many samples are waiting for processing.
- size_t NumQueuedSamples();
-
- // Set callback for decoder events, such as requesting more input,
- // returning output, or reporting error.
- void SetDecodeCallback(MediaDataDecoderCallback* aCallback)
- {
- mDecodeCallback = aCallback;
- }
-
-protected:
- GonkDecoderManager()
- : mMutex("GonkDecoderManager")
- , mLastTime(INT64_MIN)
- , mFlushMonitor("GonkDecoderManager::Flush")
- , mIsFlushing(false)
- , mDecodeCallback(nullptr)
- {}
-
- bool InitLoopers(MediaData::Type aType);
-
- void onMessageReceived(const android::sp<android::AMessage> &aMessage) override;
-
- // Produces decoded output. It returns NS_OK on success, or NS_ERROR_NOT_AVAILABLE
- // when output is not produced yet.
- // If this returns a failure code other than NS_ERROR_NOT_AVAILABLE, an error
- // will be reported through mDecodeCallback.
- virtual nsresult Output(int64_t aStreamOffset,
- RefPtr<MediaData>& aOutput) = 0;
-
- // Send queued samples to OMX. It returns how many samples are still in
- // queue after processing, or negative error code if failed.
- int32_t ProcessQueuedSamples();
-
- void ProcessInput(bool aEndOfStream);
- virtual void ProcessFlush();
- void ProcessToDo(bool aEndOfStream);
- virtual void ResetEOS();
-
- RefPtr<MediaByteBuffer> mCodecSpecificData;
-
- nsAutoCString mMimeType;
-
- // MediaCodedc's wrapper that performs the decoding.
- android::sp<android::MediaCodecProxy> mDecoder;
- // Looper for mDecoder to run on.
- android::sp<android::ALooper> mDecodeLooper;
- // Looper to run decode tasks such as processing input, output, flush, and
- // recycling output buffers.
- android::sp<android::ALooper> mTaskLooper;
- // Message codes for tasks running on mTaskLooper.
- enum {
- // Decoder will send this to indicate internal state change such as input or
- // output buffers availability. Used to run pending input & output tasks.
- kNotifyDecoderActivity = 'nda ',
- // Signal the decoder to flush.
- kNotifyProcessFlush = 'npf ',
- // Used to process queued samples when there is new input.
- kNotifyProcessInput = 'npi ',
-#ifdef DEBUG
- kNotifyFindLooperId = 'nfli',
-#endif
- };
-
- MozPromiseHolder<InitPromise> mInitPromise;
-
- Mutex mMutex; // Protects mQueuedSamples.
- // A queue that stores the samples waiting to be sent to mDecoder.
- // Empty element means EOS and there shouldn't be any sample be queued after it.
- // Samples are queued in caller's thread and dequeued in mTaskLooper.
- nsTArray<RefPtr<MediaRawData>> mQueuedSamples;
-
- // The last decoded frame presentation time. Only accessed on mTaskLooper.
- int64_t mLastTime;
-
- Monitor mFlushMonitor; // Waits for flushing to complete.
- bool mIsFlushing; // Protected by mFlushMonitor.
-
- // Remembers the notification that is currently waiting for the decoder event
- // to avoid requesting more than one notification at the time, which is
- // forbidden by mDecoder.
- android::sp<android::AMessage> mToDo;
-
- // Stores sample info for output buffer processing later.
- struct WaitOutputInfo {
- WaitOutputInfo(int64_t aOffset, int64_t aTimestamp, bool aEOS)
- : mOffset(aOffset)
- , mTimestamp(aTimestamp)
- , mEOS(aEOS)
- {}
- const int64_t mOffset;
- const int64_t mTimestamp;
- const bool mEOS;
- };
-
- nsTArray<WaitOutputInfo> mWaitOutput;
-
- MediaDataDecoderCallback* mDecodeCallback; // Reports decoder output or error.
-
-private:
- void UpdateWaitingList(int64_t aForgetUpTo);
-
-#ifdef DEBUG
- typedef void* LooperId;
-
- bool OnTaskLooper();
- LooperId mTaskLooperId;
-#endif
-};
-
-class AutoReleaseMediaBuffer
-{
-public:
- AutoReleaseMediaBuffer(android::MediaBuffer* aBuffer, android::MediaCodecProxy* aCodec)
- : mBuffer(aBuffer)
- , mCodec(aCodec)
- {}
-
- ~AutoReleaseMediaBuffer()
- {
- MOZ_ASSERT(mCodec.get());
- if (mBuffer) {
- mCodec->ReleaseMediaBuffer(mBuffer);
- }
- }
-
- android::MediaBuffer* forget()
- {
- android::MediaBuffer* tmp = mBuffer;
- mBuffer = nullptr;
- return tmp;
- }
-
-private:
- android::MediaBuffer* mBuffer;
- android::sp<android::MediaCodecProxy> mCodec;
-};
-
-// Samples are decoded using the GonkDecoder (MediaCodec)
-// created by the GonkDecoderManager. This class implements
-// the higher-level logic that drives mapping the Gonk to the async
-// MediaDataDecoder interface. The specifics of decoding the exact stream
-// type are handled by GonkDecoderManager and the GonkDecoder it creates.
-class GonkMediaDataDecoder : public MediaDataDecoder {
-public:
- GonkMediaDataDecoder(GonkDecoderManager* aDecoderManager,
- MediaDataDecoderCallback* aCallback);
-
- ~GonkMediaDataDecoder();
-
- RefPtr<InitPromise> Init() override;
-
- void Input(MediaRawData* aSample) override;
-
- void Flush() override;
-
- void Drain() override;
-
- void Shutdown() override;
-
- const char* GetDescriptionName() const override
- {
- return "gonk decoder";
- }
-
-private:
-
- android::sp<GonkDecoderManager> mManager;
-};
-
-} // namespace mozilla
-
-#endif // GonkMediaDataDecoder_h_
diff --git a/dom/media/platforms/gonk/GonkVideoDecoderManager.cpp b/dom/media/platforms/gonk/GonkVideoDecoderManager.cpp
deleted file mode 100644
index 0c7b3b6af..000000000
--- a/dom/media/platforms/gonk/GonkVideoDecoderManager.cpp
+++ /dev/null
@@ -1,772 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "MediaCodecProxy.h"
-#include <OMX_IVCommon.h>
-#include <gui/Surface.h>
-#include <ICrypto.h>
-#include "GonkVideoDecoderManager.h"
-#include "GrallocImages.h"
-#include "MediaDecoderReader.h"
-#include "ImageContainer.h"
-#include "VideoUtils.h"
-#include "nsThreadUtils.h"
-#include "Layers.h"
-#include "mozilla/Logging.h"
-#include <stagefright/MediaBuffer.h>
-#include <stagefright/MetaData.h>
-#include <stagefright/MediaErrors.h>
-#include <stagefright/foundation/AString.h>
-#include "GonkNativeWindow.h"
-#include "mozilla/layers/GrallocTextureClient.h"
-#include "mozilla/layers/ImageBridgeChild.h"
-#include "mozilla/layers/TextureClient.h"
-#include "mozilla/layers/TextureClientRecycleAllocator.h"
-#include <cutils/properties.h>
-
-#define CODECCONFIG_TIMEOUT_US 10000LL
-#define READ_OUTPUT_BUFFER_TIMEOUT_US 0LL
-
-#include <android/log.h>
-#define GVDM_LOG(...) __android_log_print(ANDROID_LOG_DEBUG, "GonkVideoDecoderManager", __VA_ARGS__)
-
-#define LOG(...) MOZ_LOG(sPDMLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
-using namespace mozilla::layers;
-using namespace android;
-typedef android::MediaCodecProxy MediaCodecProxy;
-
-namespace mozilla {
-
-class GonkTextureClientAllocationHelper : public layers::ITextureClientAllocationHelper
-{
-public:
- GonkTextureClientAllocationHelper(uint32_t aGrallocFormat,
- gfx::IntSize aSize)
- : ITextureClientAllocationHelper(gfx::SurfaceFormat::UNKNOWN,
- aSize,
- BackendSelector::Content,
- TextureFlags::DEALLOCATE_CLIENT,
- ALLOC_DISALLOW_BUFFERTEXTURECLIENT)
- , mGrallocFormat(aGrallocFormat)
- {}
-
- already_AddRefed<TextureClient> Allocate(KnowsCompositor* aAllocator) override
- {
- uint32_t usage = android::GraphicBuffer::USAGE_SW_READ_OFTEN |
- android::GraphicBuffer::USAGE_SW_WRITE_OFTEN |
- android::GraphicBuffer::USAGE_HW_TEXTURE;
-
- GrallocTextureData* texData = GrallocTextureData::Create(mSize, mGrallocFormat,
- gfx::BackendType::NONE,
- usage, aAllocator->GetTextureForwarder());
- if (!texData) {
- return nullptr;
- }
- sp<GraphicBuffer> graphicBuffer = texData->GetGraphicBuffer();
- if (!graphicBuffer.get()) {
- return nullptr;
- }
- RefPtr<TextureClient> textureClient =
- TextureClient::CreateWithData(texData, TextureFlags::DEALLOCATE_CLIENT, aAllocator->GetTextureForwarder());
- return textureClient.forget();
- }
-
- bool IsCompatible(TextureClient* aTextureClient) override
- {
- if (!aTextureClient) {
- return false;
- }
- sp<GraphicBuffer> graphicBuffer =
- static_cast<GrallocTextureData*>(aTextureClient->GetInternalData())->GetGraphicBuffer();
- if (!graphicBuffer.get() ||
- static_cast<uint32_t>(graphicBuffer->getPixelFormat()) != mGrallocFormat ||
- aTextureClient->GetSize() != mSize) {
- return false;
- }
- return true;
- }
-
-private:
- uint32_t mGrallocFormat;
-};
-
-GonkVideoDecoderManager::GonkVideoDecoderManager(
- mozilla::layers::ImageContainer* aImageContainer,
- const VideoInfo& aConfig)
- : mConfig(aConfig)
- , mImageContainer(aImageContainer)
- , mColorConverterBufferSize(0)
- , mPendingReleaseItemsLock("GonkVideoDecoderManager::mPendingReleaseItemsLock")
- , mNeedsCopyBuffer(false)
-{
- MOZ_COUNT_CTOR(GonkVideoDecoderManager);
-}
-
-GonkVideoDecoderManager::~GonkVideoDecoderManager()
-{
- MOZ_COUNT_DTOR(GonkVideoDecoderManager);
-}
-
-nsresult
-GonkVideoDecoderManager::Shutdown()
-{
- mVideoCodecRequest.DisconnectIfExists();
- return GonkDecoderManager::Shutdown();
-}
-
-RefPtr<MediaDataDecoder::InitPromise>
-GonkVideoDecoderManager::Init()
-{
- mNeedsCopyBuffer = false;
-
- uint32_t maxWidth, maxHeight;
- char propValue[PROPERTY_VALUE_MAX];
- property_get("ro.moz.omx.hw.max_width", propValue, "-1");
- maxWidth = -1 == atoi(propValue) ? MAX_VIDEO_WIDTH : atoi(propValue);
- property_get("ro.moz.omx.hw.max_height", propValue, "-1");
- maxHeight = -1 == atoi(propValue) ? MAX_VIDEO_HEIGHT : atoi(propValue) ;
-
- if (uint32_t(mConfig.mImage.width * mConfig.mImage.height) > maxWidth * maxHeight) {
- GVDM_LOG("Video resolution exceeds hw codec capability");
- return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
- }
-
- // Validate the container-reported frame and pictureRect sizes. This ensures
- // that our video frame creation code doesn't overflow.
- if (!IsValidVideoRegion(mConfig.mImage, mConfig.ImageRect(), mConfig.mDisplay)) {
- GVDM_LOG("It is not a valid region");
- return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
- }
-
- mReaderTaskQueue = AbstractThread::GetCurrent()->AsTaskQueue();
- MOZ_ASSERT(mReaderTaskQueue);
-
- if (mDecodeLooper.get() != nullptr) {
- return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
- }
-
- if (!InitLoopers(MediaData::VIDEO_DATA)) {
- return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
- }
-
- RefPtr<InitPromise> p = mInitPromise.Ensure(__func__);
- android::sp<GonkVideoDecoderManager> self = this;
- mDecoder = MediaCodecProxy::CreateByType(mDecodeLooper,
- mConfig.mMimeType.get(),
- false);
-
- uint32_t capability = MediaCodecProxy::kEmptyCapability;
- if (mDecoder->getCapability(&capability) == OK && (capability &
- MediaCodecProxy::kCanExposeGraphicBuffer)) {
-#if ANDROID_VERSION >= 21
- sp<IGonkGraphicBufferConsumer> consumer;
- GonkBufferQueue::createBufferQueue(&mGraphicBufferProducer, &consumer);
- mNativeWindow = new GonkNativeWindow(consumer);
-#else
- mNativeWindow = new GonkNativeWindow();
-#endif
- }
-
- mVideoCodecRequest.Begin(mDecoder->AsyncAllocateVideoMediaCodec()
- ->Then(mReaderTaskQueue, __func__,
- [self] (bool) -> void {
- self->mVideoCodecRequest.Complete();
- self->codecReserved();
- }, [self] (bool) -> void {
- self->mVideoCodecRequest.Complete();
- self->codecCanceled();
- }));
-
- return p;
-}
-
-nsresult
-GonkVideoDecoderManager::CreateVideoData(MediaBuffer* aBuffer,
- int64_t aStreamOffset,
- VideoData **v)
-{
- *v = nullptr;
- RefPtr<VideoData> data;
- int64_t timeUs;
- int32_t keyFrame;
-
- if (aBuffer == nullptr) {
- GVDM_LOG("Video Buffer is not valid!");
- return NS_ERROR_UNEXPECTED;
- }
-
- AutoReleaseMediaBuffer autoRelease(aBuffer, mDecoder.get());
-
- if (!aBuffer->meta_data()->findInt64(kKeyTime, &timeUs)) {
- GVDM_LOG("Decoder did not return frame time");
- return NS_ERROR_UNEXPECTED;
- }
-
- if (mLastTime > timeUs) {
- GVDM_LOG("Output decoded sample time is revert. time=%lld", timeUs);
- return NS_ERROR_NOT_AVAILABLE;
- }
- mLastTime = timeUs;
-
- if (aBuffer->range_length() == 0) {
- // Some decoders may return spurious empty buffers that we just want to ignore
- // quoted from Android's AwesomePlayer.cpp
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- if (!aBuffer->meta_data()->findInt32(kKeyIsSyncFrame, &keyFrame)) {
- keyFrame = 0;
- }
-
- gfx::IntRect picture =
- mConfig.ScaledImageRect(mFrameInfo.mWidth, mFrameInfo.mHeight);
- if (aBuffer->graphicBuffer().get()) {
- data = CreateVideoDataFromGraphicBuffer(aBuffer, picture);
- if (data && !mNeedsCopyBuffer) {
- // RecycleCallback() will be responsible for release the buffer.
- autoRelease.forget();
- }
- mNeedsCopyBuffer = false;
- } else {
- data = CreateVideoDataFromDataBuffer(aBuffer, picture);
- }
-
- if (!data) {
- return NS_ERROR_UNEXPECTED;
- }
- // Fill necessary info.
- data->mOffset = aStreamOffset;
- data->mTime = timeUs;
- data->mKeyframe = keyFrame;
-
- data.forget(v);
- return NS_OK;
-}
-
-// Copy pixels from one planar YUV to another.
-static void
-CopyYUV(PlanarYCbCrData& aSource, PlanarYCbCrData& aDestination)
-{
- // Fill Y plane.
- uint8_t* srcY = aSource.mYChannel;
- gfx::IntSize ySize = aSource.mYSize;
- uint8_t* destY = aDestination.mYChannel;
- // Y plane.
- for (int i = 0; i < ySize.height; i++) {
- memcpy(destY, srcY, ySize.width);
- srcY += aSource.mYStride;
- destY += aDestination.mYStride;
- }
-
- // Fill UV plane.
- // Line start
- uint8_t* srcU = aSource.mCbChannel;
- uint8_t* srcV = aSource.mCrChannel;
- uint8_t* destU = aDestination.mCbChannel;
- uint8_t* destV = aDestination.mCrChannel;
-
- gfx::IntSize uvSize = aSource.mCbCrSize;
- for (int i = 0; i < uvSize.height; i++) {
- uint8_t* su = srcU;
- uint8_t* sv = srcV;
- uint8_t* du = destU;
- uint8_t* dv =destV;
- for (int j = 0; j < uvSize.width; j++) {
- *du++ = *su++;
- *dv++ = *sv++;
- // Move to next pixel.
- su += aSource.mCbSkip;
- sv += aSource.mCrSkip;
- du += aDestination.mCbSkip;
- dv += aDestination.mCrSkip;
- }
- // Move to next line.
- srcU += aSource.mCbCrStride;
- srcV += aSource.mCbCrStride;
- destU += aDestination.mCbCrStride;
- destV += aDestination.mCbCrStride;
- }
-}
-
-inline static int
-Align(int aX, int aAlign)
-{
- return (aX + aAlign - 1) & ~(aAlign - 1);
-}
-
-// Venus formats are doucmented in kernel/include/media/msm_media_info.h:
-// * Y_Stride : Width aligned to 128
-// * UV_Stride : Width aligned to 128
-// * Y_Scanlines: Height aligned to 32
-// * UV_Scanlines: Height/2 aligned to 16
-// * Total size = align((Y_Stride * Y_Scanlines
-// * + UV_Stride * UV_Scanlines + 4096), 4096)
-static void
-CopyVenus(uint8_t* aSrc, uint8_t* aDest, uint32_t aWidth, uint32_t aHeight)
-{
- size_t yStride = Align(aWidth, 128);
- uint8_t* s = aSrc;
- uint8_t* d = aDest;
- for (size_t i = 0; i < aHeight; i++) {
- memcpy(d, s, aWidth);
- s += yStride;
- d += yStride;
- }
- size_t uvStride = yStride;
- size_t uvLines = (aHeight + 1) / 2;
- size_t ySize = yStride * Align(aHeight, 32);
- s = aSrc + ySize;
- d = aDest + ySize;
- for (size_t i = 0; i < uvLines; i++) {
- memcpy(d, s, aWidth);
- s += uvStride;
- d += uvStride;
- }
-}
-
-static void
-CopyGraphicBuffer(sp<GraphicBuffer>& aSource, sp<GraphicBuffer>& aDestination)
-{
- void* srcPtr = nullptr;
- aSource->lock(GraphicBuffer::USAGE_SW_READ_OFTEN, &srcPtr);
- void* destPtr = nullptr;
- aDestination->lock(GraphicBuffer::USAGE_SW_WRITE_OFTEN, &destPtr);
- MOZ_ASSERT(srcPtr && destPtr);
-
- // Build PlanarYCbCrData for source buffer.
- PlanarYCbCrData srcData;
- switch (aSource->getPixelFormat()) {
- case HAL_PIXEL_FORMAT_YV12: {
- // Android YV12 format is defined in system/core/include/system/graphics.h
- srcData.mYChannel = static_cast<uint8_t*>(srcPtr);
- srcData.mYSkip = 0;
- srcData.mYSize.width = aSource->getWidth();
- srcData.mYSize.height = aSource->getHeight();
- srcData.mYStride = aSource->getStride();
- // 4:2:0.
- srcData.mCbCrSize.width = srcData.mYSize.width / 2;
- srcData.mCbCrSize.height = srcData.mYSize.height / 2;
- srcData.mCrChannel = srcData.mYChannel + (srcData.mYStride * srcData.mYSize.height);
- // Aligned to 16 bytes boundary.
- srcData.mCbCrStride = Align(srcData.mYStride / 2, 16);
- srcData.mCrSkip = 0;
- srcData.mCbChannel = srcData.mCrChannel + (srcData.mCbCrStride * srcData.mCbCrSize.height);
- srcData.mCbSkip = 0;
-
- // Build PlanarYCbCrData for destination buffer.
- PlanarYCbCrData destData;
- destData.mYChannel = static_cast<uint8_t*>(destPtr);
- destData.mYSkip = 0;
- destData.mYSize.width = aDestination->getWidth();
- destData.mYSize.height = aDestination->getHeight();
- destData.mYStride = aDestination->getStride();
- // 4:2:0.
- destData.mCbCrSize.width = destData.mYSize.width / 2;
- destData.mCbCrSize.height = destData.mYSize.height / 2;
- destData.mCrChannel = destData.mYChannel + (destData.mYStride * destData.mYSize.height);
- // Aligned to 16 bytes boundary.
- destData.mCbCrStride = Align(destData.mYStride / 2, 16);
- destData.mCrSkip = 0;
- destData.mCbChannel = destData.mCrChannel + (destData.mCbCrStride * destData.mCbCrSize.height);
- destData.mCbSkip = 0;
-
- CopyYUV(srcData, destData);
- break;
- }
- case GrallocImage::HAL_PIXEL_FORMAT_YCbCr_420_SP_VENUS:
- CopyVenus(static_cast<uint8_t*>(srcPtr),
- static_cast<uint8_t*>(destPtr),
- aSource->getWidth(),
- aSource->getHeight());
- break;
- default:
- NS_ERROR("Unsupported input gralloc image type. Should never be here.");
- }
-
-
- aSource->unlock();
- aDestination->unlock();
-}
-
-already_AddRefed<VideoData>
-GonkVideoDecoderManager::CreateVideoDataFromGraphicBuffer(MediaBuffer* aSource,
- gfx::IntRect& aPicture)
-{
- sp<GraphicBuffer> srcBuffer(aSource->graphicBuffer());
- RefPtr<TextureClient> textureClient;
-
- if (mNeedsCopyBuffer) {
- // Copy buffer contents for bug 1199809.
- if (!mCopyAllocator) {
- RefPtr<layers::ImageBridgeChild> bridge = layers::ImageBridgeChild::GetSingleton();
- mCopyAllocator = new TextureClientRecycleAllocator(bridge);
- }
- if (!mCopyAllocator) {
- GVDM_LOG("Create buffer allocator failed!");
- return nullptr;
- }
-
- gfx::IntSize size(srcBuffer->getWidth(), srcBuffer->getHeight());
- GonkTextureClientAllocationHelper helper(srcBuffer->getPixelFormat(), size);
- textureClient = mCopyAllocator->CreateOrRecycle(helper);
- if (!textureClient) {
- GVDM_LOG("Copy buffer allocation failed!");
- return nullptr;
- }
-
- sp<GraphicBuffer> destBuffer =
- static_cast<GrallocTextureData*>(textureClient->GetInternalData())->GetGraphicBuffer();
-
- CopyGraphicBuffer(srcBuffer, destBuffer);
- } else {
- textureClient = mNativeWindow->getTextureClientFromBuffer(srcBuffer.get());
- textureClient->SetRecycleCallback(GonkVideoDecoderManager::RecycleCallback, this);
- static_cast<GrallocTextureData*>(textureClient->GetInternalData())->SetMediaBuffer(aSource);
- }
-
- RefPtr<VideoData> data =
- VideoData::CreateAndCopyIntoTextureClient(mConfig,
- 0, // Filled later by caller.
- 0, // Filled later by caller.
- 1, // No way to pass sample duration from muxer to
- // OMX codec, so we hardcode the duration here.
- textureClient,
- false, // Filled later by caller.
- -1,
- aPicture);
- return data.forget();
-}
-
-already_AddRefed<VideoData>
-GonkVideoDecoderManager::CreateVideoDataFromDataBuffer(MediaBuffer* aSource, gfx::IntRect& aPicture)
-{
- if (!aSource->data()) {
- GVDM_LOG("No data in Video Buffer!");
- return nullptr;
- }
- uint8_t *yuv420p_buffer = (uint8_t *)aSource->data();
- int32_t stride = mFrameInfo.mStride;
- int32_t slice_height = mFrameInfo.mSliceHeight;
-
- // Converts to OMX_COLOR_FormatYUV420Planar
- if (mFrameInfo.mColorFormat != OMX_COLOR_FormatYUV420Planar) {
- ARect crop;
- crop.top = 0;
- crop.bottom = mFrameInfo.mHeight;
- crop.left = 0;
- crop.right = mFrameInfo.mWidth;
- yuv420p_buffer = GetColorConverterBuffer(mFrameInfo.mWidth, mFrameInfo.mHeight);
- if (mColorConverter.convertDecoderOutputToI420(aSource->data(),
- mFrameInfo.mWidth, mFrameInfo.mHeight, crop, yuv420p_buffer) != OK) {
- GVDM_LOG("Color conversion failed!");
- return nullptr;
- }
- stride = mFrameInfo.mWidth;
- slice_height = mFrameInfo.mHeight;
- }
-
- size_t yuv420p_y_size = stride * slice_height;
- size_t yuv420p_u_size = ((stride + 1) / 2) * ((slice_height + 1) / 2);
- uint8_t *yuv420p_y = yuv420p_buffer;
- uint8_t *yuv420p_u = yuv420p_y + yuv420p_y_size;
- uint8_t *yuv420p_v = yuv420p_u + yuv420p_u_size;
-
- VideoData::YCbCrBuffer b;
- b.mPlanes[0].mData = yuv420p_y;
- b.mPlanes[0].mWidth = mFrameInfo.mWidth;
- b.mPlanes[0].mHeight = mFrameInfo.mHeight;
- b.mPlanes[0].mStride = stride;
- b.mPlanes[0].mOffset = 0;
- b.mPlanes[0].mSkip = 0;
-
- b.mPlanes[1].mData = yuv420p_u;
- b.mPlanes[1].mWidth = (mFrameInfo.mWidth + 1) / 2;
- b.mPlanes[1].mHeight = (mFrameInfo.mHeight + 1) / 2;
- b.mPlanes[1].mStride = (stride + 1) / 2;
- b.mPlanes[1].mOffset = 0;
- b.mPlanes[1].mSkip = 0;
-
- b.mPlanes[2].mData = yuv420p_v;
- b.mPlanes[2].mWidth =(mFrameInfo.mWidth + 1) / 2;
- b.mPlanes[2].mHeight = (mFrameInfo.mHeight + 1) / 2;
- b.mPlanes[2].mStride = (stride + 1) / 2;
- b.mPlanes[2].mOffset = 0;
- b.mPlanes[2].mSkip = 0;
-
- RefPtr<VideoData> data =
- VideoData::CreateAndCopyData(mConfig,
- mImageContainer,
- 0, // Filled later by caller.
- 0, // Filled later by caller.
- 1, // We don't know the duration.
- b,
- 0, // Filled later by caller.
- -1,
- aPicture);
-
- return data.forget();
-}
-
-bool
-GonkVideoDecoderManager::SetVideoFormat()
-{
- // read video metadata from MediaCodec
- sp<AMessage> codecFormat;
- if (mDecoder->getOutputFormat(&codecFormat) == OK) {
- AString mime;
- int32_t width = 0;
- int32_t height = 0;
- int32_t stride = 0;
- int32_t slice_height = 0;
- int32_t color_format = 0;
- int32_t crop_left = 0;
- int32_t crop_top = 0;
- int32_t crop_right = 0;
- int32_t crop_bottom = 0;
- if (!codecFormat->findString("mime", &mime) ||
- !codecFormat->findInt32("width", &width) ||
- !codecFormat->findInt32("height", &height) ||
- !codecFormat->findInt32("stride", &stride) ||
- !codecFormat->findInt32("slice-height", &slice_height) ||
- !codecFormat->findInt32("color-format", &color_format) ||
- !codecFormat->findRect("crop", &crop_left, &crop_top, &crop_right, &crop_bottom)) {
- GVDM_LOG("Failed to find values");
- return false;
- }
- mFrameInfo.mWidth = width;
- mFrameInfo.mHeight = height;
- mFrameInfo.mStride = stride;
- mFrameInfo.mSliceHeight = slice_height;
- mFrameInfo.mColorFormat = color_format;
-
- nsIntSize displaySize(width, height);
- if (!IsValidVideoRegion(mConfig.mDisplay,
- mConfig.ScaledImageRect(width, height),
- displaySize)) {
- GVDM_LOG("It is not a valid region");
- return false;
- }
- return true;
- }
- GVDM_LOG("Fail to get output format");
- return false;
-}
-
-// Blocks until decoded sample is produced by the deoder.
-nsresult
-GonkVideoDecoderManager::Output(int64_t aStreamOffset,
- RefPtr<MediaData>& aOutData)
-{
- aOutData = nullptr;
- status_t err;
- if (mDecoder == nullptr) {
- GVDM_LOG("Decoder is not inited");
- return NS_ERROR_UNEXPECTED;
- }
- MediaBuffer* outputBuffer = nullptr;
- err = mDecoder->Output(&outputBuffer, READ_OUTPUT_BUFFER_TIMEOUT_US);
-
- switch (err) {
- case OK:
- {
- RefPtr<VideoData> data;
- nsresult rv = CreateVideoData(outputBuffer, aStreamOffset, getter_AddRefs(data));
- if (rv == NS_ERROR_NOT_AVAILABLE) {
- // Decoder outputs a empty video buffer, try again
- return NS_ERROR_NOT_AVAILABLE;
- } else if (rv != NS_OK || data == nullptr) {
- GVDM_LOG("Failed to create VideoData");
- return NS_ERROR_UNEXPECTED;
- }
- aOutData = data;
- return NS_OK;
- }
- case android::INFO_FORMAT_CHANGED:
- {
- // If the format changed, update our cached info.
- GVDM_LOG("Decoder format changed");
- if (!SetVideoFormat()) {
- return NS_ERROR_UNEXPECTED;
- }
- return Output(aStreamOffset, aOutData);
- }
- case android::INFO_OUTPUT_BUFFERS_CHANGED:
- {
- if (mDecoder->UpdateOutputBuffers()) {
- return Output(aStreamOffset, aOutData);
- }
- GVDM_LOG("Fails to update output buffers!");
- return NS_ERROR_FAILURE;
- }
- case -EAGAIN:
- {
-// GVDM_LOG("Need to try again!");
- return NS_ERROR_NOT_AVAILABLE;
- }
- case android::ERROR_END_OF_STREAM:
- {
- GVDM_LOG("Got the EOS frame!");
- RefPtr<VideoData> data;
- nsresult rv = CreateVideoData(outputBuffer, aStreamOffset, getter_AddRefs(data));
- if (rv == NS_ERROR_NOT_AVAILABLE) {
- // For EOS, no need to do any thing.
- return NS_ERROR_ABORT;
- }
- if (rv != NS_OK || data == nullptr) {
- GVDM_LOG("Failed to create video data");
- return NS_ERROR_UNEXPECTED;
- }
- aOutData = data;
- return NS_ERROR_ABORT;
- }
- case -ETIMEDOUT:
- {
- GVDM_LOG("Timeout. can try again next time");
- return NS_ERROR_UNEXPECTED;
- }
- default:
- {
- GVDM_LOG("Decoder failed, err=%d", err);
- return NS_ERROR_UNEXPECTED;
- }
- }
-
- return NS_OK;
-}
-
-void
-GonkVideoDecoderManager::codecReserved()
-{
- if (mInitPromise.IsEmpty()) {
- return;
- }
- GVDM_LOG("codecReserved");
- sp<AMessage> format = new AMessage;
- sp<Surface> surface;
- status_t rv = OK;
- // Fixed values
- GVDM_LOG("Configure video mime type: %s, width:%d, height:%d", mConfig.mMimeType.get(), mConfig.mImage.width, mConfig.mImage.height);
- format->setString("mime", mConfig.mMimeType.get());
- format->setInt32("width", mConfig.mImage.width);
- format->setInt32("height", mConfig.mImage.height);
- // Set the "moz-use-undequeued-bufs" to use the undeque buffers to accelerate
- // the video decoding.
- format->setInt32("moz-use-undequeued-bufs", 1);
- if (mNativeWindow != nullptr) {
-#if ANDROID_VERSION >= 21
- surface = new Surface(mGraphicBufferProducer);
-#else
- surface = new Surface(mNativeWindow->getBufferQueue());
-#endif
- }
- mDecoder->configure(format, surface, nullptr, 0);
- mDecoder->Prepare();
-
- if (mConfig.mMimeType.EqualsLiteral("video/mp4v-es")) {
- rv = mDecoder->Input(mConfig.mCodecSpecificConfig->Elements(),
- mConfig.mCodecSpecificConfig->Length(), 0,
- android::MediaCodec::BUFFER_FLAG_CODECCONFIG,
- CODECCONFIG_TIMEOUT_US);
- }
-
- if (rv != OK) {
- GVDM_LOG("Failed to configure codec!!!!");
- mInitPromise.Reject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
- return;
- }
-
- mInitPromise.Resolve(TrackType::kVideoTrack, __func__);
-}
-
-void
-GonkVideoDecoderManager::codecCanceled()
-{
- GVDM_LOG("codecCanceled");
- mInitPromise.RejectIfExists(NS_ERROR_DOM_MEDIA_CANCELED, __func__);
-}
-
-// Called on GonkDecoderManager::mTaskLooper thread.
-void
-GonkVideoDecoderManager::onMessageReceived(const sp<AMessage> &aMessage)
-{
- switch (aMessage->what()) {
- case kNotifyPostReleaseBuffer:
- {
- ReleaseAllPendingVideoBuffers();
- break;
- }
-
- default:
- {
- GonkDecoderManager::onMessageReceived(aMessage);
- break;
- }
- }
-}
-
-uint8_t *
-GonkVideoDecoderManager::GetColorConverterBuffer(int32_t aWidth, int32_t aHeight)
-{
- // Allocate a temporary YUV420Planer buffer.
- size_t yuv420p_y_size = aWidth * aHeight;
- size_t yuv420p_u_size = ((aWidth + 1) / 2) * ((aHeight + 1) / 2);
- size_t yuv420p_v_size = yuv420p_u_size;
- size_t yuv420p_size = yuv420p_y_size + yuv420p_u_size + yuv420p_v_size;
- if (mColorConverterBufferSize != yuv420p_size) {
- mColorConverterBuffer = MakeUnique<uint8_t[]>(yuv420p_size);
- mColorConverterBufferSize = yuv420p_size;
- }
- return mColorConverterBuffer.get();
-}
-
-/* static */
-void
-GonkVideoDecoderManager::RecycleCallback(TextureClient* aClient, void* aClosure)
-{
- MOZ_ASSERT(aClient && !aClient->IsDead());
- GonkVideoDecoderManager* videoManager = static_cast<GonkVideoDecoderManager*>(aClosure);
- GrallocTextureData* client = static_cast<GrallocTextureData*>(aClient->GetInternalData());
- aClient->ClearRecycleCallback();
- FenceHandle handle = aClient->GetAndResetReleaseFenceHandle();
- videoManager->PostReleaseVideoBuffer(client->GetMediaBuffer(), handle);
-}
-
-void GonkVideoDecoderManager::PostReleaseVideoBuffer(
- android::MediaBuffer *aBuffer,
- FenceHandle aReleaseFence)
-{
- {
- MutexAutoLock autoLock(mPendingReleaseItemsLock);
- if (aBuffer) {
- mPendingReleaseItems.AppendElement(ReleaseItem(aBuffer, aReleaseFence));
- }
- }
- sp<AMessage> notify =
- new AMessage(kNotifyPostReleaseBuffer, id());
- notify->post();
-
-}
-
-void GonkVideoDecoderManager::ReleaseAllPendingVideoBuffers()
-{
- nsTArray<ReleaseItem> releasingItems;
- {
- MutexAutoLock autoLock(mPendingReleaseItemsLock);
- releasingItems.AppendElements(mPendingReleaseItems);
- mPendingReleaseItems.Clear();
- }
-
- // Free all pending video buffers without holding mPendingReleaseItemsLock.
- size_t size = releasingItems.Length();
- for (size_t i = 0; i < size; i++) {
- RefPtr<FenceHandle::FdObj> fdObj = releasingItems[i].mReleaseFence.GetAndResetFdObj();
- sp<Fence> fence = new Fence(fdObj->GetAndResetFd());
- fence->waitForever("GonkVideoDecoderManager");
- mDecoder->ReleaseMediaBuffer(releasingItems[i].mBuffer);
- }
- releasingItems.Clear();
-}
-
-} // namespace mozilla
diff --git a/dom/media/platforms/gonk/GonkVideoDecoderManager.h b/dom/media/platforms/gonk/GonkVideoDecoderManager.h
deleted file mode 100644
index 343bb2a5c..000000000
--- a/dom/media/platforms/gonk/GonkVideoDecoderManager.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(GonkVideoDecoderManager_h_)
-#define GonkVideoDecoderManager_h_
-
-#include "nsRect.h"
-#include "GonkMediaDataDecoder.h"
-#include "mozilla/RefPtr.h"
-#include "I420ColorConverterHelper.h"
-#include "MediaCodecProxy.h"
-#include "GonkNativeWindow.h"
-#include "mozilla/layers/FenceUtils.h"
-#include "mozilla/UniquePtr.h"
-#include <ui/Fence.h>
-
-using namespace android;
-
-namespace android {
-class MediaBuffer;
-struct MOZ_EXPORT AString;
-class GonkNativeWindow;
-} // namespace android
-
-namespace mozilla {
-
-namespace layers {
-class TextureClient;
-class TextureClientRecycleAllocator;
-} // namespace mozilla::layers
-
-class GonkVideoDecoderManager : public GonkDecoderManager {
-typedef android::MediaCodecProxy MediaCodecProxy;
-typedef mozilla::layers::TextureClient TextureClient;
-
-public:
- GonkVideoDecoderManager(mozilla::layers::ImageContainer* aImageContainer,
- const VideoInfo& aConfig);
-
- virtual ~GonkVideoDecoderManager();
-
- RefPtr<InitPromise> Init() override;
-
- nsresult Output(int64_t aStreamOffset,
- RefPtr<MediaData>& aOutput) override;
-
- nsresult Shutdown() override;
-
- const char* GetDescriptionName() const override
- {
- return "gonk video decoder";
- }
-
- static void RecycleCallback(TextureClient* aClient, void* aClosure);
-
-protected:
- // Bug 1199809: workaround to avoid sending the graphic buffer by making a
- // copy of output buffer after calling flush(). Bug 1203859 was created to
- // reimplementing Gonk PDM on top of OpenMax IL directly. Its buffer
- // management will work better with Gecko and solve problems like this.
- void ProcessFlush() override
- {
- mNeedsCopyBuffer = true;
- GonkDecoderManager::ProcessFlush();
- }
-
-private:
- struct FrameInfo
- {
- int32_t mWidth = 0;
- int32_t mHeight = 0;
- int32_t mStride = 0;
- int32_t mSliceHeight = 0;
- int32_t mColorFormat = 0;
- int32_t mCropLeft = 0;
- int32_t mCropTop = 0;
- int32_t mCropRight = 0;
- int32_t mCropBottom = 0;
- };
-
- void onMessageReceived(const android::sp<android::AMessage> &aMessage) override;
-
- bool SetVideoFormat();
-
- nsresult CreateVideoData(MediaBuffer* aBuffer, int64_t aStreamOffset, VideoData** aOutData);
- already_AddRefed<VideoData> CreateVideoDataFromGraphicBuffer(android::MediaBuffer* aSource,
- gfx::IntRect& aPicture);
- already_AddRefed<VideoData> CreateVideoDataFromDataBuffer(android::MediaBuffer* aSource,
- gfx::IntRect& aPicture);
-
- uint8_t* GetColorConverterBuffer(int32_t aWidth, int32_t aHeight);
-
- // For codec resource management
- void codecReserved();
- void codecCanceled();
-
- void ReleaseAllPendingVideoBuffers();
- void PostReleaseVideoBuffer(android::MediaBuffer *aBuffer,
- layers::FenceHandle mReleaseFence);
-
- VideoInfo mConfig;
-
- RefPtr<layers::ImageContainer> mImageContainer;
- RefPtr<layers::TextureClientRecycleAllocator> mCopyAllocator;
-
- MozPromiseRequestHolder<android::MediaCodecProxy::CodecPromise> mVideoCodecRequest;
- FrameInfo mFrameInfo;
-
- // color converter
- android::I420ColorConverterHelper mColorConverter;
- UniquePtr<uint8_t[]> mColorConverterBuffer;
- size_t mColorConverterBufferSize;
-
- android::sp<android::GonkNativeWindow> mNativeWindow;
-#if ANDROID_VERSION >= 21
- android::sp<android::IGraphicBufferProducer> mGraphicBufferProducer;
-#endif
-
- enum {
- kNotifyPostReleaseBuffer = 'nprb',
- };
-
- struct ReleaseItem {
- ReleaseItem(android::MediaBuffer* aBuffer, layers::FenceHandle& aFence)
- : mBuffer(aBuffer)
- , mReleaseFence(aFence) {}
- android::MediaBuffer* mBuffer;
- layers::FenceHandle mReleaseFence;
- };
- nsTArray<ReleaseItem> mPendingReleaseItems;
-
- // The lock protects mPendingReleaseItems.
- Mutex mPendingReleaseItemsLock;
-
- // This TaskQueue should be the same one in mDecodeCallback->OnReaderTaskQueue().
- // It is for codec resource mangement, decoding task should not dispatch to it.
- RefPtr<TaskQueue> mReaderTaskQueue;
-
- // Bug 1199809: do we need to make a copy of output buffer? Used only when
- // the decoder outputs graphic buffers.
- bool mNeedsCopyBuffer;
-};
-
-} // namespace mozilla
-
-#endif // GonkVideoDecoderManager_h_
diff --git a/dom/media/platforms/gonk/moz.build b/dom/media/platforms/gonk/moz.build
deleted file mode 100644
index 014594977..000000000
--- a/dom/media/platforms/gonk/moz.build
+++ /dev/null
@@ -1,39 +0,0 @@
-# -*- 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 += [
- 'GonkAudioDecoderManager.h',
- 'GonkDecoderModule.h',
- 'GonkMediaDataDecoder.h',
- 'GonkVideoDecoderManager.h',
-]
-UNIFIED_SOURCES += [
- 'GonkAudioDecoderManager.cpp',
- 'GonkDecoderModule.cpp',
- 'GonkMediaDataDecoder.cpp',
- 'GonkVideoDecoderManager.cpp',
-]
-LOCAL_INCLUDES += [
- '/dom/media/omx/',
-]
-include('/ipc/chromium/chromium-config.mozbuild')
-
-# Suppress some GCC/clang warnings being treated as errors:
-# - about attributes on forward declarations for types that are already
-# defined, which complains about an important MOZ_EXPORT for android::AString
-# - about multi-character constants which are used in codec-related code
-if CONFIG['GNU_CC'] or CONFIG['CLANG_CL']:
- CXXFLAGS += [
- '-Wno-error=attributes',
- '-Wno-error=multichar'
- ]
-
-FINAL_LIBRARY = 'xul'
-
-LOCAL_INCLUDES += [
- '%' + '%s/%s' % (CONFIG['ANDROID_SOURCE'], d) for d in [
- 'frameworks/native/opengl/include',]
-]
diff --git a/dom/media/platforms/moz.build b/dom/media/platforms/moz.build
index 310820c91..3fb0cc842 100644
--- a/dom/media/platforms/moz.build
+++ b/dom/media/platforms/moz.build
@@ -70,10 +70,6 @@ if CONFIG['MOZ_APPLEMEDIA']:
'-framework AudioToolbox',
]
-if CONFIG['MOZ_GONK_MEDIACODEC']:
- DEFINES['MOZ_GONK_MEDIACODEC'] = True
- DIRS += ['gonk']
-
include('/ipc/chromium/chromium-config.mozbuild')
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
diff --git a/dom/media/platforms/omx/GonkOmxPlatformLayer.cpp b/dom/media/platforms/omx/GonkOmxPlatformLayer.cpp
deleted file mode 100644
index 870566cf5..000000000
--- a/dom/media/platforms/omx/GonkOmxPlatformLayer.cpp
+++ /dev/null
@@ -1,667 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "GonkOmxPlatformLayer.h"
-
-#include <binder/MemoryDealer.h>
-#include <cutils/properties.h>
-#include <media/IOMX.h>
-#include <media/stagefright/MediaCodecList.h>
-#include <utils/List.h>
-
-#include "mozilla/Monitor.h"
-#include "mozilla/layers/TextureClient.h"
-#include "mozilla/layers/GrallocTextureClient.h"
-#include "mozilla/layers/ImageBridgeChild.h"
-#include "mozilla/layers/TextureClientRecycleAllocator.h"
-
-#include "ImageContainer.h"
-#include "MediaInfo.h"
-#include "OmxDataDecoder.h"
-
-
-#ifdef LOG
-#undef LOG
-#endif
-
-#define LOG(arg, ...) MOZ_LOG(sPDMLog, mozilla::LogLevel::Debug, ("GonkOmxPlatformLayer(%p)::%s: " arg, this, __func__, ##__VA_ARGS__))
-
-#define CHECK_ERR(err) \
- if (err != OK) { \
- LOG("error %d at %s", err, __func__); \
- return NS_ERROR_FAILURE; \
- } \
-
-// Android proprietary value.
-#define ANDROID_OMX_VIDEO_CodingVP8 (static_cast<OMX_VIDEO_CODINGTYPE>(9))
-
-using namespace android;
-
-namespace mozilla {
-
-// In Gonk, the software component name has prefix "OMX.google". It needs to
-// have a way to use hardware codec first.
-bool IsSoftwareCodec(const char* aComponentName)
-{
- nsAutoCString str(aComponentName);
- return (str.Find(NS_LITERAL_CSTRING("OMX.google.")) == -1 ? false : true);
-}
-
-bool IsInEmulator()
-{
- char propQemu[PROPERTY_VALUE_MAX];
- property_get("ro.kernel.qemu", propQemu, "");
- return !strncmp(propQemu, "1", 1);
-}
-
-class GonkOmxObserver : public BnOMXObserver {
-public:
- void onMessage(const omx_message& aMsg)
- {
- switch (aMsg.type) {
- case omx_message::EVENT:
- {
- sp<GonkOmxObserver> self = this;
- nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction([self, aMsg] () {
- if (self->mClient && self->mClient->Event(aMsg.u.event_data.event,
- aMsg.u.event_data.data1,
- aMsg.u.event_data.data2))
- {
- return;
- }
- });
- mTaskQueue->Dispatch(r.forget());
- break;
- }
- case omx_message::EMPTY_BUFFER_DONE:
- {
- sp<GonkOmxObserver> self = this;
- nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction([self, aMsg] () {
- if (!self->mPromiseLayer) {
- return;
- }
- BufferData::BufferID id = (BufferData::BufferID)aMsg.u.buffer_data.buffer;
- self->mPromiseLayer->EmptyFillBufferDone(OMX_DirInput, id);
- });
- mTaskQueue->Dispatch(r.forget());
- break;
- }
- case omx_message::FILL_BUFFER_DONE:
- {
- sp<GonkOmxObserver> self = this;
- nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction([self, aMsg] () {
- if (!self->mPromiseLayer) {
- return;
- }
-
- // TODO: these codes look a little ugly, it'd be better to improve them.
- RefPtr<BufferData> buf;
- BufferData::BufferID id = (BufferData::BufferID)aMsg.u.extended_buffer_data.buffer;
- buf = self->mPromiseLayer->FindAndRemoveBufferHolder(OMX_DirOutput, id);
- MOZ_RELEASE_ASSERT(buf);
- GonkBufferData* gonkBuffer = static_cast<GonkBufferData*>(buf.get());
-
- // Copy the critical information to local buffer.
- if (gonkBuffer->IsLocalBuffer()) {
- gonkBuffer->mBuffer->nOffset = aMsg.u.extended_buffer_data.range_offset;
- gonkBuffer->mBuffer->nFilledLen = aMsg.u.extended_buffer_data.range_length;
- gonkBuffer->mBuffer->nFlags = aMsg.u.extended_buffer_data.flags;
- gonkBuffer->mBuffer->nTimeStamp = aMsg.u.extended_buffer_data.timestamp;
- }
- self->mPromiseLayer->EmptyFillBufferDone(OMX_DirOutput, buf);
- });
- mTaskQueue->Dispatch(r.forget());
- break;
- }
- default:
- {
- LOG("Unhandle event %d", aMsg.type);
- }
- }
- }
-
- void Shutdown()
- {
- MOZ_ASSERT(mTaskQueue->IsCurrentThreadIn());
- mPromiseLayer = nullptr;
- mClient = nullptr;
- }
-
- GonkOmxObserver(TaskQueue* aTaskQueue, OmxPromiseLayer* aPromiseLayer, OmxDataDecoder* aDataDecoder)
- : mTaskQueue(aTaskQueue)
- , mPromiseLayer(aPromiseLayer)
- , mClient(aDataDecoder)
- {}
-
-protected:
- RefPtr<TaskQueue> mTaskQueue;
- // TODO:
- // we should combine both event handlers into one. And we should provide
- // an unified way for event handling in OmxPlatformLayer class.
- RefPtr<OmxPromiseLayer> mPromiseLayer;
- RefPtr<OmxDataDecoder> mClient;
-};
-
-// This class allocates Gralloc buffer and manages TextureClient's recycle.
-class GonkTextureClientRecycleHandler : public layers::ITextureClientRecycleAllocator
-{
- typedef MozPromise<layers::TextureClient*, nsresult, /* IsExclusive = */ true> TextureClientRecyclePromise;
-
-public:
- GonkTextureClientRecycleHandler(OMX_VIDEO_PORTDEFINITIONTYPE& aDef)
- : ITextureClientRecycleAllocator()
- , mMonitor("GonkTextureClientRecycleHandler")
- {
- RefPtr<layers::ImageBridgeChild> bridge = layers::ImageBridgeChild::GetSingleton();
-
- // Allocate Gralloc texture memory.
- layers::GrallocTextureData* textureData =
- layers::GrallocTextureData::Create(gfx::IntSize(aDef.nFrameWidth, aDef.nFrameHeight),
- aDef.eColorFormat,
- gfx::BackendType::NONE,
- GraphicBuffer::USAGE_HW_TEXTURE | GraphicBuffer::USAGE_SW_READ_OFTEN,
- bridge);
-
- mGraphBuffer = textureData->GetGraphicBuffer();
- MOZ_ASSERT(mGraphBuffer.get());
-
- mTextureClient =
- layers::TextureClient::CreateWithData(textureData,
- layers::TextureFlags::DEALLOCATE_CLIENT | layers::TextureFlags::RECYCLE,
- bridge);
- MOZ_ASSERT(mTextureClient);
-
- mPromise.SetMonitor(&mMonitor);
- }
-
- RefPtr<TextureClientRecyclePromise> WaitforRecycle()
- {
- MonitorAutoLock lock(mMonitor);
- MOZ_ASSERT(!!mGraphBuffer.get());
-
- mTextureClient->SetRecycleAllocator(this);
- return mPromise.Ensure(__func__);
- }
-
- // DO NOT use smart pointer to receive TextureClient; otherwise it will
- // distrupt the reference count.
- layers::TextureClient* GetTextureClient()
- {
- return mTextureClient;
- }
-
- GraphicBuffer* GetGraphicBuffer()
- {
- MonitorAutoLock lock(mMonitor);
- return mGraphBuffer.get();
- }
-
- // This function is called from layers thread.
- void RecycleTextureClient(layers::TextureClient* aClient) override
- {
- MOZ_ASSERT(mTextureClient == aClient);
-
- // Clearing the recycle allocator drops a reference, so make sure we stay alive
- // for the duration of this function.
- RefPtr<GonkTextureClientRecycleHandler> kungFuDeathGrip(this);
- aClient->SetRecycleAllocator(nullptr);
-
- {
- MonitorAutoLock lock(mMonitor);
- mPromise.ResolveIfExists(mTextureClient, __func__);
- }
- }
-
- void Shutdown()
- {
- MonitorAutoLock lock(mMonitor);
-
- mPromise.RejectIfExists(NS_ERROR_FAILURE, __func__);
-
- // DO NOT clear TextureClient here.
- // The ref count could be 1 and RecycleCallback will be called if we clear
- // the ref count here. That breaks the whole mechanism. (RecycleCallback
- // should be called from layers)
- mGraphBuffer = nullptr;
- }
-
-private:
- // Because TextureClient calls RecycleCallbackl when ref count is 1, so we
- // should hold only one reference here and use raw pointer when out of this
- // class.
- RefPtr<layers::TextureClient> mTextureClient;
-
- // It is protected by mMonitor.
- sp<android::GraphicBuffer> mGraphBuffer;
-
- // It is protected by mMonitor.
- MozPromiseHolder<TextureClientRecyclePromise> mPromise;
-
- Monitor mMonitor;
-};
-
-GonkBufferData::GonkBufferData(bool aLiveInLocal,
- GonkOmxPlatformLayer* aGonkPlatformLayer)
- : BufferData(nullptr)
- , mId(0)
- , mGonkPlatformLayer(aGonkPlatformLayer)
-{
- if (!aLiveInLocal) {
- mMirrorBuffer = new OMX_BUFFERHEADERTYPE;
- PodZero(mMirrorBuffer.get());
- mBuffer = mMirrorBuffer.get();
- }
-}
-
-void
-GonkBufferData::ReleaseBuffer()
-{
- if (mTextureClientRecycleHandler) {
- mTextureClientRecycleHandler->Shutdown();
- mTextureClientRecycleHandler = nullptr;
- }
-}
-
-nsresult
-GonkBufferData::InitSharedMemory(android::IMemory* aMemory)
-{
- MOZ_RELEASE_ASSERT(mMirrorBuffer.get());
-
- // aMemory is a IPC memory, it is safe to use it here.
- mBuffer->pBuffer = (OMX_U8*)aMemory->pointer();
- mBuffer->nAllocLen = aMemory->size();
- return NS_OK;
-}
-
-nsresult
-GonkBufferData::InitLocalBuffer(IOMX::buffer_id aId)
-{
- MOZ_RELEASE_ASSERT(!mMirrorBuffer.get());
-
- mBuffer = (OMX_BUFFERHEADERTYPE*)aId;
- return NS_OK;
-}
-
-nsresult
-GonkBufferData::InitGraphicBuffer(OMX_VIDEO_PORTDEFINITIONTYPE& aDef)
-{
- mTextureClientRecycleHandler = new GonkTextureClientRecycleHandler(aDef);
-
- if (!mTextureClientRecycleHandler->GetGraphicBuffer()) {
- return NS_ERROR_FAILURE;
- }
-
- return NS_OK;
-}
-
-already_AddRefed<MediaData>
-GonkBufferData::GetPlatformMediaData()
-{
- if (mGonkPlatformLayer->GetTrackInfo()->GetAsAudioInfo()) {
- // This is audio decoding.
- return nullptr;
- }
-
- if (!mTextureClientRecycleHandler) {
- // There is no GraphicBuffer, it should fallback to normal YUV420 VideoData.
- return nullptr;
- }
-
- VideoInfo info(*mGonkPlatformLayer->GetTrackInfo()->GetAsVideoInfo());
- RefPtr<VideoData> data =
- VideoData::CreateAndCopyIntoTextureClient(info,
- 0,
- mBuffer->nTimeStamp,
- 1,
- mTextureClientRecycleHandler->GetTextureClient(),
- false,
- 0,
- info.ImageRect());
- LOG("%p, disp width %d, height %d, pic width %d, height %d, time %ld",
- this, info.mDisplay.width, info.mDisplay.height,
- info.mImage.width, info.mImage.height, mBuffer->nTimeStamp);
-
- // Get TextureClient Promise here to wait for resolved.
- RefPtr<GonkBufferData> self(this);
- mTextureClientRecycleHandler->WaitforRecycle()
- ->Then(mGonkPlatformLayer->GetTaskQueue(), __func__,
- [self] () {
- self->mPromise.ResolveIfExists(self, __func__);
- },
- [self] () {
- OmxBufferFailureHolder failure(OMX_ErrorUndefined, self);
- self->mPromise.RejectIfExists(failure, __func__);
- });
-
- return data.forget();
-}
-
-GonkOmxPlatformLayer::GonkOmxPlatformLayer(OmxDataDecoder* aDataDecoder,
- OmxPromiseLayer* aPromiseLayer,
- TaskQueue* aTaskQueue,
- layers::ImageContainer* aImageContainer)
- : mTaskQueue(aTaskQueue)
- , mImageContainer(aImageContainer)
- , mNode(0)
-{
- mOmxObserver = new GonkOmxObserver(mTaskQueue, aPromiseLayer, aDataDecoder);
-}
-
-nsresult
-GonkOmxPlatformLayer::AllocateOmxBuffer(OMX_DIRTYPE aType,
- BUFFERLIST* aBufferList)
-{
- MOZ_ASSERT(!mMemoryDealer[aType].get());
-
- // Get port definition.
- OMX_PARAM_PORTDEFINITIONTYPE def;
- nsTArray<uint32_t> portindex;
- GetPortIndices(portindex);
- for (auto idx : portindex) {
- InitOmxParameter(&def);
- def.nPortIndex = idx;
-
- OMX_ERRORTYPE err = GetParameter(OMX_IndexParamPortDefinition,
- &def,
- sizeof(OMX_PARAM_PORTDEFINITIONTYPE));
- if (err != OMX_ErrorNone) {
- return NS_ERROR_FAILURE;
- } else if (def.eDir == aType) {
- LOG("Get OMX_IndexParamPortDefinition: port: %d, type: %d", def.nPortIndex, def.eDir);
- break;
- }
- }
-
- size_t t = 0;
-
- // Configure video output GraphicBuffer for video decoding acceleration.
- bool useGralloc = false;
- if (aType == OMX_DirOutput && mQuirks.test(kRequiresAllocateBufferOnOutputPorts) &&
- (def.eDomain == OMX_PortDomainVideo)) {
- if (NS_FAILED(EnableOmxGraphicBufferPort(def))) {
- return NS_ERROR_FAILURE;
- }
-
- LOG("Enable OMX GraphicBuffer port, number %d, width %d, height %d", def.nBufferCountActual,
- def.format.video.nFrameWidth, def.format.video.nFrameHeight);
-
- useGralloc = true;
-
- t = 1024; // MemoryDealer doesn't like 0, it's just for MemoryDealer happy.
- } else {
- t = def.nBufferCountActual * def.nBufferSize;
- LOG("Buffer count %d, buffer size %d", def.nBufferCountActual, def.nBufferSize);
- }
-
- bool liveinlocal = mOmx->livesLocally(mNode, getpid());
-
- // MemoryDealer is a IPC buffer allocator in Gonk because IOMX is actually
- // lives in mediaserver.
- mMemoryDealer[aType] = new MemoryDealer(t, "Gecko-OMX");
- for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
- RefPtr<GonkBufferData> buffer;
- IOMX::buffer_id bufferID;
- status_t st;
- nsresult rv;
-
- buffer = new GonkBufferData(liveinlocal, this);
- if (useGralloc) {
- // Buffer is lived remotely. Use GraphicBuffer for decoded video frame display.
- rv = buffer->InitGraphicBuffer(def.format.video);
- NS_ENSURE_SUCCESS(rv, rv);
- st = mOmx->useGraphicBuffer(mNode,
- def.nPortIndex,
- buffer->mTextureClientRecycleHandler->GetGraphicBuffer(),
- &bufferID);
- CHECK_ERR(st);
- } else {
- sp<IMemory> mem = mMemoryDealer[aType]->allocate(def.nBufferSize);
- MOZ_ASSERT(mem.get());
-
- if ((mQuirks.test(kRequiresAllocateBufferOnInputPorts) && aType == OMX_DirInput) ||
- (mQuirks.test(kRequiresAllocateBufferOnOutputPorts) && aType == OMX_DirOutput)) {
- // Buffer is lived remotely. We allocate a local OMX_BUFFERHEADERTYPE
- // as the mirror of the remote OMX_BUFFERHEADERTYPE.
- st = mOmx->allocateBufferWithBackup(mNode, aType, mem, &bufferID);
- CHECK_ERR(st);
- rv = buffer->InitSharedMemory(mem.get());
- NS_ENSURE_SUCCESS(rv, rv);
- } else {
- // Buffer is lived locally, bufferID is the actually OMX_BUFFERHEADERTYPE
- // pointer.
- st = mOmx->useBuffer(mNode, aType, mem, &bufferID);
- CHECK_ERR(st);
- rv = buffer->InitLocalBuffer(bufferID);
- NS_ENSURE_SUCCESS(rv, rv);
- }
- }
-
- rv = buffer->SetBufferId(bufferID);
- NS_ENSURE_SUCCESS(rv, rv);
-
- aBufferList->AppendElement(buffer);
- }
-
- return NS_OK;
-}
-
-nsresult
-GonkOmxPlatformLayer::ReleaseOmxBuffer(OMX_DIRTYPE aType,
- BUFFERLIST* aBufferList)
-{
- status_t st;
- uint32_t len = aBufferList->Length();
- for (uint32_t i = 0; i < len; i++) {
- GonkBufferData* buffer = static_cast<GonkBufferData*>(aBufferList->ElementAt(i).get());
- IOMX::buffer_id id = (OMX_BUFFERHEADERTYPE*) buffer->ID();
- st = mOmx->freeBuffer(mNode, aType, id);
- if (st != OK) {
- return NS_ERROR_FAILURE;
- }
- buffer->ReleaseBuffer();
- }
- aBufferList->Clear();
- mMemoryDealer[aType].clear();
-
- return NS_OK;
-}
-
-nsresult
-GonkOmxPlatformLayer::EnableOmxGraphicBufferPort(OMX_PARAM_PORTDEFINITIONTYPE& aDef)
-{
- status_t st;
-
- st = mOmx->enableGraphicBuffers(mNode, aDef.nPortIndex, OMX_TRUE);
- CHECK_ERR(st);
-
- return NS_OK;
-}
-
-OMX_ERRORTYPE
-GonkOmxPlatformLayer::GetState(OMX_STATETYPE* aType)
-{
- return (OMX_ERRORTYPE)mOmx->getState(mNode, aType);
-}
-
-OMX_ERRORTYPE
-GonkOmxPlatformLayer::GetParameter(OMX_INDEXTYPE aParamIndex,
- OMX_PTR aComponentParameterStructure,
- OMX_U32 aComponentParameterSize)
-{
- return (OMX_ERRORTYPE)mOmx->getParameter(mNode,
- aParamIndex,
- aComponentParameterStructure,
- aComponentParameterSize);
-}
-
-OMX_ERRORTYPE
-GonkOmxPlatformLayer::SetParameter(OMX_INDEXTYPE aParamIndex,
- OMX_PTR aComponentParameterStructure,
- OMX_U32 aComponentParameterSize)
-{
- return (OMX_ERRORTYPE)mOmx->setParameter(mNode,
- aParamIndex,
- aComponentParameterStructure,
- aComponentParameterSize);
-}
-
-nsresult
-GonkOmxPlatformLayer::Shutdown()
-{
- mOmx->freeNode(mNode);
- mOmxObserver->Shutdown();
- mOmxObserver = nullptr;
- mOmxClient.disconnect();
-
- return NS_OK;
-}
-
-OMX_ERRORTYPE
-GonkOmxPlatformLayer::InitOmxToStateLoaded(const TrackInfo* aInfo)
-{
- mInfo = aInfo;
- status_t err = mOmxClient.connect();
- if (err != OK) {
- return OMX_ErrorUndefined;
- }
- mOmx = mOmxClient.interface();
- if (!mOmx.get()) {
- return OMX_ErrorUndefined;
- }
-
- LOG("find componenet for mime type %s", mInfo->mMimeType.Data());
-
- nsTArray<ComponentInfo> components;
- if (FindComponents(mInfo->mMimeType, &components)) {
- for (auto comp : components) {
- if (LoadComponent(comp)) {
- return OMX_ErrorNone;
- }
- }
- }
-
- LOG("no component is loaded");
- return OMX_ErrorUndefined;
-}
-
-OMX_ERRORTYPE
-GonkOmxPlatformLayer::EmptyThisBuffer(BufferData* aData)
-{
- return (OMX_ERRORTYPE)mOmx->emptyBuffer(mNode,
- (IOMX::buffer_id)aData->ID(),
- aData->mBuffer->nOffset,
- aData->mBuffer->nFilledLen,
- aData->mBuffer->nFlags,
- aData->mBuffer->nTimeStamp);
-}
-
-OMX_ERRORTYPE
-GonkOmxPlatformLayer::FillThisBuffer(BufferData* aData)
-{
- return (OMX_ERRORTYPE)mOmx->fillBuffer(mNode, (IOMX::buffer_id)aData->ID());
-}
-
-OMX_ERRORTYPE
-GonkOmxPlatformLayer::SendCommand(OMX_COMMANDTYPE aCmd,
- OMX_U32 aParam1,
- OMX_PTR aCmdData)
-{
- return (OMX_ERRORTYPE)mOmx->sendCommand(mNode, aCmd, aParam1);
-}
-
-bool
-GonkOmxPlatformLayer::LoadComponent(const ComponentInfo& aComponent)
-{
- status_t err = mOmx->allocateNode(aComponent.mName, mOmxObserver, &mNode);
- if (err == OK) {
- mQuirks = aComponent.mQuirks;
- LOG("Load OpenMax component %s, alloc input %d, alloc output %d, live locally %d",
- aComponent.mName, mQuirks.test(kRequiresAllocateBufferOnInputPorts),
- mQuirks.test(kRequiresAllocateBufferOnOutputPorts),
- mOmx->livesLocally(mNode, getpid()));
- return true;
- }
- return false;
-}
-
-layers::ImageContainer*
-GonkOmxPlatformLayer::GetImageContainer()
-{
- return mImageContainer;
-}
-
-const TrackInfo*
-GonkOmxPlatformLayer::GetTrackInfo()
-{
- return mInfo;
-}
-
-bool
-GonkOmxPlatformLayer::FindComponents(const nsACString& aMimeType,
- nsTArray<ComponentInfo>* aComponents)
-{
- static const MediaCodecList* codecs = MediaCodecList::getInstance();
-
- bool useHardwareCodecOnly = false;
-
- // H264 and H263 has different profiles, software codec doesn't support high profile.
- // So we use hardware codec only.
- if (!IsInEmulator() &&
- (aMimeType.EqualsLiteral("video/avc") ||
- aMimeType.EqualsLiteral("video/mp4") ||
- aMimeType.EqualsLiteral("video/mp4v-es") ||
- aMimeType.EqualsLiteral("video/3gp"))) {
- useHardwareCodecOnly = true;
- }
-
- const char* mime = aMimeType.Data();
- // Translate VP8 MIME type to Android format.
- if (aMimeType.EqualsLiteral("video/webm; codecs=vp8")) {
- mime = "video/x-vnd.on2.vp8";
- }
-
- size_t start = 0;
- bool found = false;
- while (true) {
- ssize_t index = codecs->findCodecByType(mime, false /* encoder */, start);
- if (index < 0) {
- break;
- }
- start = index + 1;
-
- const char* name = codecs->getCodecName(index);
- if (IsSoftwareCodec(name) && useHardwareCodecOnly) {
- continue;
- }
-
- found = true;
-
- if (!aComponents) {
- continue;
- }
- ComponentInfo* comp = aComponents->AppendElement();
- comp->mName = name;
- if (codecs->codecHasQuirk(index, "requires-allocate-on-input-ports")) {
- comp->mQuirks.set(kRequiresAllocateBufferOnInputPorts);
- }
- if (codecs->codecHasQuirk(index, "requires-allocate-on-output-ports")) {
- comp->mQuirks.set(kRequiresAllocateBufferOnOutputPorts);
- }
- }
-
- return found;
-}
-
-OMX_VIDEO_CODINGTYPE
-GonkOmxPlatformLayer::CompressionFormat()
-{
- MOZ_ASSERT(mInfo);
-
- return mInfo->mMimeType.EqualsLiteral("video/webm; codecs=vp8") ?
- ANDROID_OMX_VIDEO_CodingVP8 : OmxPlatformLayer::CompressionFormat();
-}
-
-} // mozilla
diff --git a/dom/media/platforms/omx/GonkOmxPlatformLayer.h b/dom/media/platforms/omx/GonkOmxPlatformLayer.h
deleted file mode 100644
index aaa8c654d..000000000
--- a/dom/media/platforms/omx/GonkOmxPlatformLayer.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(GonkOmxPlatformLayer_h_)
-#define GonkOmxPlatformLayer_h_
-
-#pragma GCC visibility push(default)
-
-#include <bitset>
-
-#include <utils/RefBase.h>
-#include <media/stagefright/OMXClient.h>
-#include "nsAutoPtr.h"
-
-#include "OMX_Component.h"
-
-#include "OmxPlatformLayer.h"
-
-class nsACString;
-
-namespace android {
-class IMemory;
-class MemoryDealer;
-}
-
-namespace mozilla {
-
-class GonkOmxObserver;
-class GonkOmxPlatformLayer;
-class GonkTextureClientRecycleHandler;
-
-/*
- * Due to Android's omx node could live in local process (client) or remote
- * process (mediaserver). And there are 3 kinds of buffer in Android OMX.
- *
- * 1.
- * When buffer is in local process, the IOMX::buffer_id is OMX_BUFFERHEADERTYPE
- * pointer actually, it is safe to use it directly.
- *
- * 2.
- * When buffer is in remote process, the OMX_BUFFERHEADERTYPE pointer is 'IN' the
- * remote process. It can't be used in local process, so here it allocates a
- * local OMX_BUFFERHEADERTYPE. The raw/decoded data is in the android shared
- * memory, IMemory.
- *
- * 3.
- * When buffer is in remote process for the display output port. It uses
- * GraphicBuffer to accelerate the decoding and display.
- *
- */
-class GonkBufferData : public OmxPromiseLayer::BufferData {
-protected:
- virtual ~GonkBufferData() {}
-
-public:
- GonkBufferData(bool aLiveInLocal,
- GonkOmxPlatformLayer* aLayer);
-
- BufferID ID() override
- {
- return mId;
- }
-
- already_AddRefed<MediaData> GetPlatformMediaData() override;
-
- bool IsLocalBuffer()
- {
- return !!mMirrorBuffer.get();
- }
-
- void ReleaseBuffer();
-
- nsresult SetBufferId(android::IOMX::buffer_id aId)
- {
- mId = aId;
- return NS_OK;
- }
-
- // The mBuffer is in local process. And aId is actually the OMX_BUFFERHEADERTYPE
- // pointer. It doesn't need a mirror buffer.
- nsresult InitLocalBuffer(android::IOMX::buffer_id aId);
-
- // aMemory is an IPC based memory which will be used as the pBuffer in
- // mBuffer. And the mBuffer will be the mirror OMX_BUFFERHEADERTYPE
- // of the one in the remote process.
- nsresult InitSharedMemory(android::IMemory* aMemory);
-
- // GraphicBuffer is for video decoding acceleration on output port.
- // Then mBuffer is the mirror OMX_BUFFERHEADERTYPE of the one in the remote
- // process.
- nsresult InitGraphicBuffer(OMX_VIDEO_PORTDEFINITIONTYPE& aDef);
-
- // Android OMX uses this id to pass the buffer between OMX component and
- // client.
- android::IOMX::buffer_id mId;
-
- // mMirrorBuffer are used only when the omx node is in mediaserver.
- // Due to IPC problem, the mId is the OMX_BUFFERHEADERTYPE address in mediaserver.
- // It can't mapping to client process, so we need a local OMX_BUFFERHEADERTYPE
- // here to mirror the remote OMX_BUFFERHEADERTYPE in mediaserver.
- nsAutoPtr<OMX_BUFFERHEADERTYPE> mMirrorBuffer;
-
- // It creates GraphicBuffer and manages TextureClient.
- RefPtr<GonkTextureClientRecycleHandler> mTextureClientRecycleHandler;
-
- GonkOmxPlatformLayer* mGonkPlatformLayer;
-};
-
-class GonkOmxPlatformLayer : public OmxPlatformLayer {
-public:
- enum {
- kRequiresAllocateBufferOnInputPorts = 0,
- kRequiresAllocateBufferOnOutputPorts,
- QUIRKS,
- };
- typedef std::bitset<QUIRKS> Quirks;
-
- struct ComponentInfo {
- const char* mName;
- Quirks mQuirks;
- };
-
- GonkOmxPlatformLayer(OmxDataDecoder* aDataDecoder,
- OmxPromiseLayer* aPromiseLayer,
- TaskQueue* aTaskQueue,
- layers::ImageContainer* aImageContainer);
-
- nsresult AllocateOmxBuffer(OMX_DIRTYPE aType, BUFFERLIST* aBufferList) override;
-
- nsresult ReleaseOmxBuffer(OMX_DIRTYPE aType, BUFFERLIST* aBufferList) override;
-
- OMX_ERRORTYPE GetState(OMX_STATETYPE* aType) override;
-
- OMX_ERRORTYPE GetParameter(OMX_INDEXTYPE aParamIndex,
- OMX_PTR aComponentParameterStructure,
- OMX_U32 aComponentParameterSize) override;
-
- OMX_ERRORTYPE SetParameter(OMX_INDEXTYPE nIndex,
- OMX_PTR aComponentParameterStructure,
- OMX_U32 aComponentParameterSize) override;
-
- OMX_ERRORTYPE InitOmxToStateLoaded(const TrackInfo* aInfo) override;
-
- OMX_ERRORTYPE EmptyThisBuffer(BufferData* aData) override;
-
- OMX_ERRORTYPE FillThisBuffer(BufferData* aData) override;
-
- OMX_ERRORTYPE SendCommand(OMX_COMMANDTYPE aCmd,
- OMX_U32 aParam1,
- OMX_PTR aCmdData) override;
-
- nsresult Shutdown() override;
-
- static bool FindComponents(const nsACString& aMimeType,
- nsTArray<ComponentInfo>* aComponents = nullptr);
-
- // Android/QCOM decoder uses its own OMX_VIDEO_CodingVP8 definition in
- // frameworks/native/media/include/openmax/OMX_Video.h, not the one defined
- // in OpenMAX v1.1.2 OMX_VideoExt.h
- OMX_VIDEO_CODINGTYPE CompressionFormat() override;
-
-protected:
- friend GonkBufferData;
-
- layers::ImageContainer* GetImageContainer();
-
- const TrackInfo* GetTrackInfo();
-
- TaskQueue* GetTaskQueue()
- {
- return mTaskQueue;
- }
-
- nsresult EnableOmxGraphicBufferPort(OMX_PARAM_PORTDEFINITIONTYPE& aDef);
-
- bool LoadComponent(const ComponentInfo& aComponent);
-
- friend class GonkOmxObserver;
-
- RefPtr<TaskQueue> mTaskQueue;
-
- RefPtr<layers::ImageContainer> mImageContainer;
-
- // OMX_DirInput is 0, OMX_DirOutput is 1.
- android::sp<android::MemoryDealer> mMemoryDealer[2];
-
- android::sp<GonkOmxObserver> mOmxObserver;
-
- android::sp<android::IOMX> mOmx;
-
- android::IOMX::node_id mNode;
-
- android::OMXClient mOmxClient;
-
- Quirks mQuirks;
-};
-
-}
-
-#pragma GCC visibility pop
-
-#endif // GonkOmxPlatformLayer_h_
diff --git a/dom/media/platforms/omx/OmxPlatformLayer.cpp b/dom/media/platforms/omx/OmxPlatformLayer.cpp
index d1f43144d..039b4a22f 100644
--- a/dom/media/platforms/omx/OmxPlatformLayer.cpp
+++ b/dom/media/platforms/omx/OmxPlatformLayer.cpp
@@ -8,11 +8,6 @@
#include "OMX_VideoExt.h" // For VP8.
-#if defined(MOZ_WIDGET_GONK) && (ANDROID_VERSION == 20 || ANDROID_VERSION == 19)
-#define OMX_PLATFORM_GONK
-#include "GonkOmxPlatformLayer.h"
-#endif
-
#include "VPXDecoder.h"
#ifdef LOG
diff --git a/dom/media/platforms/omx/moz.build b/dom/media/platforms/omx/moz.build
index 9f641d937..661e280e0 100644
--- a/dom/media/platforms/omx/moz.build
+++ b/dom/media/platforms/omx/moz.build
@@ -21,29 +21,6 @@ LOCAL_INCLUDES += [
include('/ipc/chromium/chromium-config.mozbuild')
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and (CONFIG['ANDROID_VERSION'] == '19' or CONFIG['ANDROID_VERSION'] == '20'):
- # Suppress some GCC/clang warnings being treated as errors:
- # - about attributes on forward declarations for types that are already
- # defined, which complains about an important MOZ_EXPORT for android::AString
- # - about multi-character constants which are used in codec-related code
- if CONFIG['GNU_CC'] or CONFIG['CLANG_CL']:
- CXXFLAGS += [
- '-Wno-error=attributes',
- '-Wno-error=multichar'
- ]
- CXXFLAGS += [
- '-I%s/%s' % (CONFIG['ANDROID_SOURCE'], d) for d in [
- 'frameworks/base/include/binder',
- 'frameworks/base/include/utils',
- ]
- ]
- UNIFIED_SOURCES += [
- 'GonkOmxPlatformLayer.cpp',
- ]
- EXTRA_DSO_LDOPTS += [
- '-libbinder',
- ]
-
FINAL_LIBRARY = 'xul'
if CONFIG['GNU_CXX']:
diff --git a/dom/media/standalone/moz.build b/dom/media/standalone/moz.build
index 5d2c5a6e7..959703765 100644
--- a/dom/media/standalone/moz.build
+++ b/dom/media/standalone/moz.build
@@ -4,7 +4,7 @@
# License, v. 2.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['OS_TARGET'] != 'WINNT' and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
+if CONFIG['OS_TARGET'] != 'WINNT':
Library('media_standalone')
UNIFIED_SOURCES += [
diff --git a/dom/media/systemservices/CamerasChild.cpp b/dom/media/systemservices/CamerasChild.cpp
index 0f7d1c1df..a3fbec850 100644
--- a/dom/media/systemservices/CamerasChild.cpp
+++ b/dom/media/systemservices/CamerasChild.cpp
@@ -35,7 +35,9 @@ CamerasSingleton::CamerasSingleton()
: mCamerasMutex("CamerasSingleton::mCamerasMutex"),
mCameras(nullptr),
mCamerasChildThread(nullptr),
- mFakeDeviceChangeEventThread(nullptr) {
+ mFakeDeviceChangeEventThread(nullptr),
+ mInShutdown(false)
+{
LOG(("CamerasSingleton: %p", this));
}
@@ -285,6 +287,7 @@ CamerasChild::NumberOfCapabilities(CaptureEngine aCapEngine,
LOG((__PRETTY_FUNCTION__));
LOG(("NumberOfCapabilities for %s", deviceUniqueIdUTF8));
nsCString unique_id(deviceUniqueIdUTF8);
+ RefPtr<CamerasChild> deathGrip = this;
nsCOMPtr<nsIRunnable> runnable =
mozilla::NewNonOwningRunnableMethod<CaptureEngine, nsCString>
(this, &CamerasChild::SendNumberOfCapabilities, aCapEngine, unique_id);
@@ -321,6 +324,7 @@ int
CamerasChild::EnsureInitialized(CaptureEngine aCapEngine)
{
LOG((__PRETTY_FUNCTION__));
+ RefPtr<CamerasChild> deathGrip = this;
nsCOMPtr<nsIRunnable> runnable =
mozilla::NewNonOwningRunnableMethod<CaptureEngine>
(this, &CamerasChild::SendEnsureInitialized, aCapEngine);
@@ -336,6 +340,7 @@ CamerasChild::GetCaptureCapability(CaptureEngine aCapEngine,
webrtc::CaptureCapability& capability)
{
LOG(("GetCaptureCapability: %s %d", unique_idUTF8, capability_number));
+ RefPtr<CamerasChild> deathGrip = this;
nsCString unique_id(unique_idUTF8);
nsCOMPtr<nsIRunnable> runnable =
mozilla::NewNonOwningRunnableMethod<CaptureEngine, nsCString, unsigned int>
@@ -374,6 +379,7 @@ CamerasChild::GetCaptureDevice(CaptureEngine aCapEngine,
bool* scary)
{
LOG((__PRETTY_FUNCTION__));
+ RefPtr<CamerasChild> deathGrip = this;
nsCOMPtr<nsIRunnable> runnable =
mozilla::NewNonOwningRunnableMethod<CaptureEngine, unsigned int>
(this, &CamerasChild::SendGetCaptureDevice, aCapEngine, list_number);
@@ -413,6 +419,7 @@ CamerasChild::AllocateCaptureDevice(CaptureEngine aCapEngine,
const nsACString& aOrigin)
{
LOG((__PRETTY_FUNCTION__));
+ RefPtr<CamerasChild> deathGrip = this;
nsCString unique_id(unique_idUTF8);
nsCString origin(aOrigin);
nsCOMPtr<nsIRunnable> runnable =
@@ -444,6 +451,7 @@ CamerasChild::ReleaseCaptureDevice(CaptureEngine aCapEngine,
const int capture_id)
{
LOG((__PRETTY_FUNCTION__));
+ RefPtr<CamerasChild> deathGrip = this;
nsCOMPtr<nsIRunnable> runnable =
mozilla::NewNonOwningRunnableMethod<CaptureEngine, int>
(this, &CamerasChild::SendReleaseCaptureDevice, aCapEngine, capture_id);
@@ -491,6 +499,7 @@ CamerasChild::StartCapture(CaptureEngine aCapEngine,
webrtcCaps.rawType,
webrtcCaps.codecType,
webrtcCaps.interlaced);
+ RefPtr<CamerasChild> deathGrip = this;
nsCOMPtr<nsIRunnable> runnable =
mozilla::NewNonOwningRunnableMethod<CaptureEngine, int, CaptureCapability>
(this, &CamerasChild::SendStartCapture, aCapEngine, capture_id, capCap);
@@ -502,6 +511,7 @@ int
CamerasChild::StopCapture(CaptureEngine aCapEngine, const int capture_id)
{
LOG((__PRETTY_FUNCTION__));
+ RefPtr<CamerasChild> deathGrip = this;
nsCOMPtr<nsIRunnable> runnable =
mozilla::NewNonOwningRunnableMethod<CaptureEngine, int>
(this, &CamerasChild::SendStopCapture, aCapEngine, capture_id);
@@ -567,6 +577,7 @@ CamerasChild::ShutdownParent()
// Delete the parent actor.
// CamerasChild (this) will remain alive and is only deleted by the
// IPC layer when SendAllDone returns.
+ RefPtr<CamerasChild> deathGrip = this;
nsCOMPtr<nsIRunnable> deleteRunnable =
mozilla::NewNonOwningRunnableMethod(this, &CamerasChild::SendAllDone);
CamerasSingleton::Thread()->Dispatch(deleteRunnable, NS_DISPATCH_NORMAL);
@@ -695,7 +706,7 @@ CamerasChild::~CamerasChild()
{
LOG(("~CamerasChild: %p", this));
- {
+ if (!CamerasSingleton::InShutdown()) {
OffTheBooksMutexAutoLock lock(CamerasSingleton::Mutex());
// In normal circumstances we've already shut down and the
// following does nothing. But on fatal IPC errors we will
diff --git a/dom/media/systemservices/CamerasChild.h b/dom/media/systemservices/CamerasChild.h
index 1530714e9..9ca125cfd 100644
--- a/dom/media/systemservices/CamerasChild.h
+++ b/dom/media/systemservices/CamerasChild.h
@@ -89,6 +89,14 @@ public:
return gTheInstance.get()->mFakeDeviceChangeEventThread;
}
+ static bool InShutdown() {
+ return gTheInstance.get()->mInShutdown;
+ }
+
+ static void StartShutdown() {
+ gTheInstance.get()->mInShutdown = true;
+ }
+
private:
static Singleton<CamerasSingleton> gTheInstance;
@@ -106,6 +114,7 @@ private:
CamerasChild* mCameras;
nsCOMPtr<nsIThread> mCamerasChildThread;
nsCOMPtr<nsIThread> mFakeDeviceChangeEventThread;
+ Atomic<bool> mInShutdown;
};
// Get a pointer to a CamerasChild object we can use to do IPC with.
@@ -145,7 +154,7 @@ class CamerasChild final : public PCamerasChild
public:
// We are owned by the PBackground thread only. CamerasSingleton
// takes a non-owning reference.
- NS_INLINE_DECL_REFCOUNTING(CamerasChild)
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(CamerasChild)
// IPC messages recevied, received on the PBackground thread
// these are the actual callbacks with data
diff --git a/dom/media/systemservices/MediaSystemResourceService.cpp b/dom/media/systemservices/MediaSystemResourceService.cpp
index 0e5d6a50c..4434c54c2 100644
--- a/dom/media/systemservices/MediaSystemResourceService.cpp
+++ b/dom/media/systemservices/MediaSystemResourceService.cpp
@@ -47,23 +47,6 @@ MediaSystemResourceService::MediaSystemResourceService()
: mDestroyed(false)
{
MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
-#ifdef MOZ_WIDGET_GONK
- // The maximum number of hardware resoureces available.
- // XXX need to hange to a dynamic way.
- enum
- {
- VIDEO_DECODER_COUNT = 1,
- VIDEO_ENCODER_COUNT = 1
- };
-
- MediaSystemResource* resource;
-
- resource = new MediaSystemResource(VIDEO_DECODER_COUNT);
- mResources.Put(static_cast<uint32_t>(MediaSystemResourceType::VIDEO_DECODER), resource);
-
- resource = new MediaSystemResource(VIDEO_ENCODER_COUNT);
- mResources.Put(static_cast<uint32_t>(MediaSystemResourceType::VIDEO_ENCODER), resource);
-#endif
}
MediaSystemResourceService::~MediaSystemResourceService()
diff --git a/dom/media/systemservices/moz.build b/dom/media/systemservices/moz.build
index 33e5ed1f1..82a5c5e72 100644
--- a/dom/media/systemservices/moz.build
+++ b/dom/media/systemservices/moz.build
@@ -42,16 +42,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
UNIFIED_SOURCES += ['OSXRunLoopSingleton.cpp']
EXPORTS += ['OSXRunLoopSingleton.h']
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- if CONFIG['ANDROID_VERSION'] >= '17':
- LOCAL_INCLUDES += [
- '%' + '%s/frameworks/wilhelm/include' % CONFIG['ANDROID_SOURCE'],
- ]
- else:
- LOCAL_INCLUDES += [
- '%' + '%s/system/media/wilhelm/include' % CONFIG['ANDROID_SOURCE'],
- ]
-
if CONFIG['_MSC_VER']:
DEFINES['__PRETTY_FUNCTION__'] = '__FUNCSIG__'
diff --git a/dom/media/webrtc/MediaEngine.h b/dom/media/webrtc/MediaEngine.h
index ff2a6e25a..6a6988544 100644
--- a/dom/media/webrtc/MediaEngine.h
+++ b/dom/media/webrtc/MediaEngine.h
@@ -54,11 +54,8 @@ public:
static const int DEFAULT_169_VIDEO_WIDTH = 1280;
static const int DEFAULT_169_VIDEO_HEIGHT = 720;
-#ifndef MOZ_B2G
static const int DEFAULT_SAMPLE_RATE = 32000;
-#else
- static const int DEFAULT_SAMPLE_RATE = 16000;
-#endif
+
// This allows using whatever rate the graph is using for the
// MediaStreamTrack. This is useful for microphone data, we know it's already
// at the correct rate for insertion in the MSG.
diff --git a/dom/media/webrtc/MediaEngineCameraVideoSource.cpp b/dom/media/webrtc/MediaEngineCameraVideoSource.cpp
index a0f31d937..e1e572724 100644
--- a/dom/media/webrtc/MediaEngineCameraVideoSource.cpp
+++ b/dom/media/webrtc/MediaEngineCameraVideoSource.cpp
@@ -325,7 +325,7 @@ MediaEngineCameraVideoSource::SetName(nsString aName)
VideoFacingModeEnum facingMode = VideoFacingModeEnum::User;
// Set facing mode based on device name.
-#if defined(ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID)
// Names are generated. Example: "Camera 0, Facing back, Orientation 90"
//
// See media/webrtc/trunk/webrtc/modules/video_capture/android/java/src/org/
diff --git a/dom/media/webrtc/MediaEngineDefault.cpp b/dom/media/webrtc/MediaEngineDefault.cpp
index 9c97d197f..eb0ac2b6f 100644
--- a/dom/media/webrtc/MediaEngineDefault.cpp
+++ b/dom/media/webrtc/MediaEngineDefault.cpp
@@ -192,7 +192,7 @@ MediaEngineDefaultVideoSource::Start(SourceMediaStream* aStream, TrackID aID,
mTrackID = aID;
// Start timer for subsequent frames
-#if (defined(MOZ_WIDGET_GONK) || defined(MOZ_WIDGET_ANDROID)) && defined(DEBUG)
+#if defined(MOZ_WIDGET_ANDROID) && defined(DEBUG)
// emulator debug is very, very slow and has problems dealing with realtime audio inputs
mTimer->InitWithCallback(this, (1000 / mOpts.mFPS)*10, nsITimer::TYPE_REPEATING_SLACK);
#else
diff --git a/dom/media/webrtc/MediaEngineWebRTC.cpp b/dom/media/webrtc/MediaEngineWebRTC.cpp
index 1a2dc9a04..a77800424 100644
--- a/dom/media/webrtc/MediaEngineWebRTC.cpp
+++ b/dom/media/webrtc/MediaEngineWebRTC.cpp
@@ -335,7 +335,7 @@ MediaEngineWebRTC::EnumerateAudioDevices(dom::MediaSourceEnum aMediaSource,
int nDevices = 0;
mAudioInput->GetNumOfRecordingDevices(nDevices);
int i;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
i = 0; // Bug 1037025 - let the OS handle defaulting for now on android/b2g
#else
// -1 is "default communications device" depending on OS in webrtc.org code
diff --git a/dom/media/webrtc/MediaEngineWebRTCAudio.cpp b/dom/media/webrtc/MediaEngineWebRTCAudio.cpp
index 0b8796aa8..1e2e13d01 100644
--- a/dom/media/webrtc/MediaEngineWebRTCAudio.cpp
+++ b/dom/media/webrtc/MediaEngineWebRTCAudio.cpp
@@ -741,9 +741,6 @@ MediaEngineWebRTCMicrophoneSource::AllocChannel()
// Check for availability.
if (!mAudioInput->SetRecordingDevice(mCapIndex)) {
-#ifndef MOZ_B2G
- // Because of the permission mechanism of B2G, we need to skip the status
- // check here.
bool avail = false;
mAudioInput->GetRecordingDeviceStatus(avail);
if (!avail) {
@@ -752,7 +749,6 @@ MediaEngineWebRTCMicrophoneSource::AllocChannel()
}
return false;
}
-#endif // MOZ_B2G
// Set "codec" to PCM, 32kHz on 1 channel
ScopedCustomReleasePtr<webrtc::VoECodec> ptrVoECodec(webrtc::VoECodec::GetInterface(mVoiceEngine));
diff --git a/dom/moz.build b/dom/moz.build
index 6242b4fbc..358fc6411 100644
--- a/dom/moz.build
+++ b/dom/moz.build
@@ -105,21 +105,9 @@ DIRS += [
if CONFIG['OS_ARCH'] == 'WINNT':
DIRS += ['plugins/ipc/hangui']
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DIRS += [
- 'speakermanager',
- 'tethering',
- 'wifi',
- ]
-
if CONFIG['MOZ_SECUREELEMENT']:
DIRS += ['secureelement']
-if CONFIG['MOZ_B2G']:
- DIRS += [
- 'downloads',
- ]
-
DIRS += ['presentation']
TEST_DIRS += [
diff --git a/dom/network/EthernetManager.js b/dom/network/EthernetManager.js
deleted file mode 100644
index 4b11e5666..000000000
--- a/dom/network/EthernetManager.js
+++ /dev/null
@@ -1,655 +0,0 @@
-/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-const TOPIC_INTERFACE_STATE_CHANGED = "network-interface-state-changed";
-
-const ETHERNET_NETWORK_IFACE_PREFIX = "eth";
-const DEFAULT_ETHERNET_NETWORK_IFACE = "eth0";
-
-const INTERFACE_IPADDR_NULL = "0.0.0.0";
-const INTERFACE_GATEWAY_NULL = "0.0.0.0";
-const INTERFACE_PREFIX_NULL = 0;
-const INTERFACE_MACADDR_NULL = "00:00:00:00:00:00";
-
-const NETWORK_INTERFACE_UP = "up";
-const NETWORK_INTERFACE_DOWN = "down";
-
-const IP_MODE_DHCP = "dhcp";
-const IP_MODE_STATIC = "static";
-
-const PREF_NETWORK_DEBUG_ENABLED = "network.debugging.enabled";
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
- "@mozilla.org/network/manager;1",
- "nsINetworkManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkService",
- "@mozilla.org/network/service;1",
- "nsINetworkService");
-
-let debug;
-function updateDebug() {
- let debugPref = false; // set default value here.
- try {
- debugPref = debugPref || Services.prefs.getBoolPref(PREF_NETWORK_DEBUG_ENABLED);
- } catch (e) {}
-
- if (debugPref) {
- debug = function(s) {
- dump("-*- EthernetManager: " + s + "\n");
- };
- } else {
- debug = function(s) {};
- }
-}
-updateDebug();
-
-// nsINetworkInterface
-
-function EthernetInterface(attr) {
- this.info.state = attr.state;
- this.info.type = attr.type;
- this.info.name = attr.name;
- this.info.ipMode = attr.ipMode;
- this.info.ips = [attr.ip];
- this.info.prefixLengths = [attr.prefixLength];
- this.info.gateways = [attr.gateway];
- this.info.dnses = attr.dnses;
- this.httpProxyHost = "";
- this.httpProxyPort = 0;
-}
-EthernetInterface.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterface]),
-
- updateConfig: function(config) {
- debug("Interface " + this.info.name + " updateConfig " + JSON.stringify(config));
- this.info.state = (config.state != undefined) ?
- config.state : this.info.state;
- this.info.ips = (config.ip != undefined) ? [config.ip] : this.info.ips;
- this.info.prefixLengths = (config.prefixLength != undefined) ?
- [config.prefixLength] : this.info.prefixLengths;
- this.info.gateways = (config.gateway != undefined) ?
- [config.gateway] : this.info.gateways;
- this.info.dnses = (config.dnses != undefined) ? config.dnses : this.info.dnses;
- this.httpProxyHost = (config.httpProxyHost != undefined) ?
- config.httpProxyHost : this.httpProxyHost;
- this.httpProxyPort = (config.httpProxyPort != undefined) ?
- config.httpProxyPort : this.httpProxyPort;
- this.info.ipMode = (config.ipMode != undefined) ?
- config.ipMode : this.info.ipMode;
- },
-
- info: {
- getAddresses: function(ips, prefixLengths) {
- ips.value = this.ips.slice();
- prefixLengths.value = this.prefixLengths.slice();
-
- return this.ips.length;
- },
-
- getGateways: function(count) {
- if (count) {
- count.value = this.gateways.length;
- }
- return this.gateways.slice();
- },
-
- getDnses: function(count) {
- if (count) {
- count.value = this.dnses.length;
- }
- return this.dnses.slice();
- }
- }
-};
-
-// nsIEthernetManager
-
-/*
- * Network state transition diagram
- *
- * ---------- enable --------- connect ----------- disconnect --------------
- * | Disabled | -----> | Enabled | -------> | Connected | <----------> | Disconnected |
- * ---------- --------- ----------- connect --------------
- * ^ | | |
- * | disable | | |
- * -----------------------------------------------------------------------
- */
-
-function EthernetManager() {
- debug("EthernetManager start");
-
- // Interface list.
- this.ethernetInterfaces = {};
-
- // Used to memorize last connection information.
- this.lastStaticConfig = {};
-
- Services.obs.addObserver(this, "xpcom-shutdown", false);
-}
-
-EthernetManager.prototype = {
- classID: Components.ID("a96441dd-36b3-4f7f-963b-2c032e28a039"),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIEthernetManager]),
-
- ethernetInterfaces: null,
- lastStaticConfig: null,
-
- observer: function(subject, topic, data) {
- switch (topic) {
- case "xpcom-shutdown":
- debug("xpcom-shutdown");
-
- this._shutdown();
-
- Services.obs.removeObserver(this, "xpcom-shutdown");
- break;
- }
- },
-
- _shutdown: function() {
- debug("Shuting down");
- (function onRemove(ifnameList) {
- if (!ifnameList.length) {
- return;
- }
-
- let ifname = ifnameList.shift();
- this.removeInterface(ifname, { notify: onRemove.bind(this, ifnameList) });
- }).call(this, Object.keys(this.ethernetInterfaces));
- },
-
- get interfaceList() {
- return Object.keys(this.ethernetInterfaces);
- },
-
- scan: function(callback) {
- debug("Scan");
-
- gNetworkService.getInterfaces(function(success, list) {
- let ethList = [];
-
- if (!success) {
- if (callback) {
- callback.notify(ethList);
- }
- return;
- }
-
- for (let i = 0; i < list.length; i++) {
- debug("Found interface " + list[i]);
- if (!list[i].startsWith(ETHERNET_NETWORK_IFACE_PREFIX)) {
- continue;
- }
- ethList.push(list[i]);
- }
-
- if (callback) {
- callback.notify(ethList);
- }
- });
- },
-
- addInterface: function(ifname, callback) {
- debug("Add interface " + ifname);
-
- if (!ifname || !ifname.startsWith(ETHERNET_NETWORK_IFACE_PREFIX)) {
- if (callback) {
- callback.notify(false, "Invalid interface.");
- }
- return;
- }
-
- if (this.ethernetInterfaces[ifname]) {
- if (callback) {
- callback.notify(true, "Interface already exists.");
- }
- return;
- }
-
- gNetworkService.getInterfaceConfig(ifname, function(success, result) {
- if (!success) {
- if (callback) {
- callback.notify(false, "Netd error.");
- }
- return;
- }
-
- // Since the operation may still succeed with an invalid interface name,
- // check the mac address as well.
- if (result.macAddr == INTERFACE_MACADDR_NULL) {
- if (callback) {
- callback.notify(false, "Interface not found.");
- }
- return;
- }
-
- this.ethernetInterfaces[ifname] = new EthernetInterface({
- state: result.link == NETWORK_INTERFACE_UP ?
- Ci.nsINetworkInfo.NETWORK_STATE_DISABLED :
- Ci.nsINetworkInfo.NETWORK_STATE_ENABLED,
- name: ifname,
- type: Ci.nsINetworkInfo.NETWORK_TYPE_ETHERNET,
- ip: result.ip,
- prefixLength: result.prefix,
- ipMode: IP_MODE_DHCP
- });
-
- // Register the interface to NetworkManager.
- gNetworkManager.registerNetworkInterface(this.ethernetInterfaces[ifname]);
-
- debug("Add interface " + ifname + " succeeded with " +
- JSON.stringify(this.ethernetInterfaces[ifname]));
-
- if (callback) {
- callback.notify(true, "ok");
- }
- }.bind(this));
- },
-
- removeInterface: function(ifname, callback) {
- debug("Remove interface " + ifname);
-
- if (!ifname || !ifname.startsWith(ETHERNET_NETWORK_IFACE_PREFIX)) {
- if (callback) {
- callback.notify(false, "Invalid interface.");
- }
- return;
- }
-
- if (!this.ethernetInterfaces[ifname]) {
- if (callback) {
- callback.notify(true, "Interface does not exist.");
- }
- return;
- }
-
- // Make sure interface is disable before removing.
- this.disable(ifname, { notify: function(success, message) {
- // Unregister the interface from NetworkManager and also remove it from
- // the interface list.
- gNetworkManager.unregisterNetworkInterface(this.ethernetInterfaces[ifname]);
- delete this.ethernetInterfaces[ifname];
-
- debug("Remove interface " + ifname + " succeeded.");
-
- if (callback) {
- callback.notify(true, "ok");
- }
- }.bind(this)});
- },
-
- updateInterfaceConfig: function(ifname, config, callback) {
- debug("Update interface config with " + ifname);
-
- this._ensureIfname(ifname, callback, function(iface) {
- if (!config) {
- if (callback) {
- callback.notify(false, "No config to update.");
- }
- return;
- }
-
- // Network state can not be modified externally.
- if (config.state) {
- delete config.state;
- }
-
- let currentIpMode = iface.info.ipMode;
-
- // Update config.
- this.ethernetInterfaces[iface.info.name].updateConfig(config);
-
- // Do not automatically re-connect if the interface is not in connected
- // state.
- if (iface.info.state != Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- if (callback) {
- callback.notify(true, "ok");
- }
- return;
- }
-
- let newIpMode = this.ethernetInterfaces[iface.info.name].info.ipMode;
-
- if (newIpMode == IP_MODE_STATIC) {
- this._setStaticIP(iface.info.name, callback);
- return;
- }
- if ((currentIpMode == IP_MODE_STATIC) && (newIpMode == IP_MODE_DHCP)) {
- gNetworkService.stopDhcp(iface.info.name, function(success) {
- if (success) {
- debug("DHCP for " + iface.info.name + " stopped.");
- }
- });
-
- // Clear the current network settings before do dhcp request, otherwise
- // dhcp settings could fail.
- this.disconnect(iface.info.name, { notify: function(success, message) {
- if (!success) {
- if (callback) {
- callback.notify("Disconnect failed.");
- }
- return;
- }
- this._runDhcp(iface.info.name, callback);
- }.bind(this) });
- return;
- }
-
- if (callback) {
- callback.notify(true, "ok");
- }
- }.bind(this));
- },
-
- enable: function(ifname, callback) {
- debug("Enable interface " + ifname);
-
- this._ensureIfname(ifname, callback, function(iface) {
- // Interface can be only enabled in the state of disabled.
- if (iface.info.state != Ci.nsINetworkInfo.NETWORK_STATE_DISABLED) {
- if (callback) {
- callback.notify(true, "Interface already enabled.");
- }
- return;
- }
-
- let ips = {};
- let prefixLengths = {};
- iface.info.getAddresses(ips, prefixLengths);
- let config = { ifname: iface.info.name,
- ip: ips.value[0],
- prefix: prefixLengths.value[0],
- link: NETWORK_INTERFACE_UP };
- gNetworkService.setInterfaceConfig(config, function(success) {
- if (!success) {
- if (callback) {
- callback.notify(false, "Netd Error.");
- }
- return;
- }
-
- this.ethernetInterfaces[iface.info.name].updateConfig({
- state: Ci.nsINetworkInfo.NETWORK_STATE_ENABLED
- });
-
- debug("Enable interface " + iface.info.name + " succeeded.");
-
- if (callback) {
- callback.notify(true, "ok");
- }
- }.bind(this));
- }.bind(this));
- },
-
- disable: function(ifname, callback) {
- debug("Disable interface " + ifname);
-
- this._ensureIfname(ifname, callback, function(iface) {
- if (iface.info.state == Ci.nsINetworkInfo.NETWORK_STATE_DISABLED) {
- if (callback) {
- callback.notify(true, "Interface already disabled.");
- }
- return;
- }
-
- if (iface.info.state == Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- gNetworkService.stopDhcp(iface.info.name, function(success) {
- if (success) {
- debug("DHCP for " + iface.info.name + " stopped.");
- }
- });
- }
-
- let ips = {};
- let prefixLengths = {};
- iface.info.getAddresses(ips, prefixLengths);
- let config = { ifname: iface.info.name,
- ip: ips.value[0],
- prefix: prefixLengths.value[0],
- link: NETWORK_INTERFACE_DOWN };
- gNetworkService.setInterfaceConfig(config, function(success) {
- if (!success) {
- if (callback) {
- callback.notify(false, "Netd Error.");
- }
- return;
- }
-
- this.ethernetInterfaces[iface.info.name].updateConfig({
- state: Ci.nsINetworkInfo.NETWORK_STATE_DISABLED
- });
-
- debug("Disable interface " + iface.info.name + " succeeded.");
-
- if (callback) {
- callback.notify(true, "ok");
- }
- }.bind(this));
- }.bind(this));
- },
-
- connect: function(ifname, callback) {
- debug("Connect interface " + ifname);
-
- this._ensureIfname(ifname, callback, function(iface) {
- // Interface can only be connected in the state of enabled or
- // disconnected.
- if (iface.info.state == Ci.nsINetworkInfo.NETWORK_STATE_DISABLED ||
- iface.info.state == Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- if (callback) {
- callback.notify(true, "Interface " + ifname + " is not available or "
- + " already connected.");
- }
- return;
- }
-
- if (iface.info.ipMode == IP_MODE_DHCP) {
- this._runDhcp(iface.info.name, callback);
- return;
- }
-
- if (iface.info.ipMode == IP_MODE_STATIC) {
- if (this._checkConfigNull(iface) && this.lastStaticConfig[iface.info.name]) {
- debug("Connect with lastStaticConfig " +
- JSON.stringify(this.lastStaticConfig[iface.info.name]));
- this.ethernetInterfaces[iface.info.name].updateConfig(
- this.lastStaticConfig[iface.info.name]);
- }
- this._setStaticIP(iface.info.name, callback);
- return;
- }
-
- if (callback) {
- callback.notify(false, "IP mode is wrong or not set.");
- }
- }.bind(this));
- },
-
- disconnect: function(ifname, callback) {
- debug("Disconnect interface " + ifname);
-
- this._ensureIfname(ifname, callback, function(iface) {
- // Interface can be only disconnected in the state of connected.
- if (iface.info.state != Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- if (callback) {
- callback.notify(true, "Interface is already disconnected");
- }
- return;
- }
-
- let config = { ifname: iface.info.name,
- ip: INTERFACE_IPADDR_NULL,
- prefix: INTERFACE_PREFIX_NULL,
- link: NETWORK_INTERFACE_UP };
- gNetworkService.setInterfaceConfig(config, function(success) {
- if (!success) {
- if (callback) {
- callback.notify(false, "Netd error.");
- }
- return;
- }
-
- // Stop dhcp daemon.
- gNetworkService.stopDhcp(iface.info.name, function(success) {
- if (success) {
- debug("DHCP for " + iface.info.name + " stopped.");
- }
- });
-
- this.ethernetInterfaces[iface.info.name].updateConfig({
- state: Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED,
- ip: INTERFACE_IPADDR_NULL,
- prefixLength: INTERFACE_PREFIX_NULL,
- gateway: INTERFACE_GATEWAY_NULL
- });
-
- gNetworkManager.updateNetworkInterface(this.ethernetInterfaces[ifname]);
-
- debug("Disconnect interface " + iface.info.name + " succeeded.");
-
- if (callback) {
- callback.notify(true, "ok");
- }
- }.bind(this));
- }.bind(this));
- },
-
- _checkConfigNull: function(iface) {
- let ips = {};
- let prefixLengths = {};
- let gateways = iface.info.getGateways();
- iface.info.getAddresses(ips, prefixLengths);
-
- if (ips.value[0] == INTERFACE_IPADDR_NULL &&
- prefixLengths.value[0] == INTERFACE_PREFIX_NULL &&
- gateways[0] == INTERFACE_GATEWAY_NULL) {
- return true;
- }
-
- return false;
- },
-
- _ensureIfname: function(ifname, callback, func) {
- // If no given ifname, use the default one.
- if (!ifname) {
- ifname = DEFAULT_ETHERNET_NETWORK_IFACE;
- }
-
- let iface = this.ethernetInterfaces[ifname];
- if (!iface) {
- if (callback) {
- callback.notify(true, "Interface " + ifname + " is not available.");
- }
- return;
- }
-
- func.call(this, iface);
- },
-
- _runDhcp: function(ifname, callback) {
- debug("runDhcp with " + ifname);
-
- if (!this.ethernetInterfaces[ifname]) {
- if (callback) {
- callback.notify(false, "Invalid interface.");
- }
- return;
- }
-
- gNetworkService.dhcpRequest(ifname, function(success, result) {
- if (!success) {
- if (callback) {
- callback.notify(false, "DHCP failed.");
- }
- return;
- }
-
- debug("DHCP succeeded with " + JSON.stringify(result));
-
- // Clear last static network information when connecting with dhcp mode.
- if (this.lastStaticConfig[ifname]) {
- this.lastStaticConfig[ifname] = null;
- }
-
- this.ethernetInterfaces[ifname].updateConfig({
- state: Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED,
- ip: result.ipaddr_str,
- gateway: result.gateway_str,
- prefixLength: result.prefixLength,
- dnses: [result.dns1_str, result.dns2_str]
- });
-
- gNetworkManager.updateNetworkInterface(this.ethernetInterfaces[ifname]);
-
- debug("Connect interface " + ifname + " with DHCP succeeded.");
-
- if (callback) {
- callback.notify(true, "ok");
- }
- }.bind(this));
- },
-
- _setStaticIP: function(ifname, callback) {
- let iface = this.ethernetInterfaces[ifname];
- if (!iface) {
- if (callback) {
- callback.notify(false, "Invalid interface.");
- }
- return;
- }
-
- let ips = {};
- let prefixLengths = {};
- iface.info.getAddresses(ips, prefixLengths);
-
- let config = { ifname: iface.info.name,
- ip: ips.value[0],
- prefix: prefixLengths.value[0],
- link: NETWORK_INTERFACE_UP };
- gNetworkService.setInterfaceConfig(config, function(success) {
- if (!success) {
- if (callback) {
- callback.notify(false, "Netd Error.");
- }
- return;
- }
-
- // Keep the lastest static network information.
- let ips = {};
- let prefixLengths = {};
- let gateways = iface.info.getGateways();
- iface.info.getAddresses(ips, prefixLengths);
-
- this.lastStaticConfig[iface.info.name] = {
- ip: ips.value[0],
- prefixLength: prefixLengths.value[0],
- gateway: gateways[0]
- };
-
- this.ethernetInterfaces[ifname].updateConfig({
- state: Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED,
- });
-
- gNetworkManager.updateNetworkInterface(this.ethernetInterfaces[ifname]);
-
- debug("Connect interface " + ifname + " with static ip succeeded.");
-
- if (callback) {
- callback.notify(true, "ok");
- }
- }.bind(this));
- },
-}
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([EthernetManager]);
diff --git a/dom/network/EthernetManager.manifest b/dom/network/EthernetManager.manifest
deleted file mode 100644
index d25a069e1..000000000
--- a/dom/network/EthernetManager.manifest
+++ /dev/null
@@ -1,2 +0,0 @@
-component {a96441dd-36b3-4f7f-963b-2c032e28a039} EthernetManager.js
-contract @mozilla.org/ethernetManager;1 {a96441dd-36b3-4f7f-963b-2c032e28a039}
diff --git a/dom/network/NetUtils.cpp b/dom/network/NetUtils.cpp
deleted file mode 100644
index 78c5be802..000000000
--- a/dom/network/NetUtils.cpp
+++ /dev/null
@@ -1,200 +0,0 @@
-/* -*- 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 "NetUtils.h"
-#include <dlfcn.h>
-#include <errno.h>
-#include "prinit.h"
-#include "mozilla/Assertions.h"
-#include "nsDebug.h"
-#include "SystemProperty.h"
-
-using mozilla::system::Property;
-
-static void* sNetUtilsLib;
-static PRCallOnceType sInitNetUtilsLib;
-
-static PRStatus
-InitNetUtilsLib()
-{
- sNetUtilsLib = dlopen("/system/lib/libnetutils.so", RTLD_LAZY);
- // We might fail to open the hardware lib. That's OK.
- return PR_SUCCESS;
-}
-
-static void*
-GetNetUtilsLibHandle()
-{
- PR_CallOnce(&sInitNetUtilsLib, InitNetUtilsLib);
- return sNetUtilsLib;
-}
-
-// static
-void*
-NetUtils::GetSharedLibrary()
-{
- void* netLib = GetNetUtilsLibHandle();
- if (!netLib) {
- NS_WARNING("No /system/lib/libnetutils.so");
- }
- return netLib;
-}
-
-// static
-int32_t
-NetUtils::SdkVersion()
-{
- char propVersion[Property::VALUE_MAX_LENGTH];
- Property::Get("ro.build.version.sdk", propVersion, "0");
- int32_t version = strtol(propVersion, nullptr, 10);
- return version;
-}
-
-DEFINE_DLFUNC(ifc_enable, int32_t, const char*)
-DEFINE_DLFUNC(ifc_disable, int32_t, const char*)
-DEFINE_DLFUNC(ifc_configure, int32_t, const char*, in_addr_t, uint32_t,
- in_addr_t, in_addr_t, in_addr_t)
-DEFINE_DLFUNC(ifc_reset_connections, int32_t, const char*, const int32_t)
-DEFINE_DLFUNC(ifc_set_default_route, int32_t, const char*, in_addr_t)
-DEFINE_DLFUNC(ifc_add_route, int32_t, const char*, const char*, uint32_t, const char*)
-DEFINE_DLFUNC(ifc_remove_route, int32_t, const char*, const char*, uint32_t, const char*)
-DEFINE_DLFUNC(ifc_remove_host_routes, int32_t, const char*)
-DEFINE_DLFUNC(ifc_remove_default_route, int32_t, const char*)
-DEFINE_DLFUNC(dhcp_stop, int32_t, const char*)
-
-NetUtils::NetUtils()
-{
-}
-
-int32_t NetUtils::do_ifc_enable(const char *ifname)
-{
- USE_DLFUNC(ifc_enable)
- return ifc_enable(ifname);
-}
-
-int32_t NetUtils::do_ifc_disable(const char *ifname)
-{
- USE_DLFUNC(ifc_disable)
- return ifc_disable(ifname);
-}
-
-int32_t NetUtils::do_ifc_configure(const char *ifname,
- in_addr_t address,
- uint32_t prefixLength,
- in_addr_t gateway,
- in_addr_t dns1,
- in_addr_t dns2)
-{
- USE_DLFUNC(ifc_configure)
- int32_t ret = ifc_configure(ifname, address, prefixLength, gateway, dns1, dns2);
- return ret;
-}
-
-int32_t NetUtils::do_ifc_reset_connections(const char *ifname,
- const int32_t resetMask)
-{
- USE_DLFUNC(ifc_reset_connections)
- return ifc_reset_connections(ifname, resetMask);
-}
-
-int32_t NetUtils::do_ifc_set_default_route(const char *ifname,
- in_addr_t gateway)
-{
- USE_DLFUNC(ifc_set_default_route)
- return ifc_set_default_route(ifname, gateway);
-}
-
-int32_t NetUtils::do_ifc_add_route(const char *ifname,
- const char *dst,
- uint32_t prefixLength,
- const char *gateway)
-{
- USE_DLFUNC(ifc_add_route)
- return ifc_add_route(ifname, dst, prefixLength, gateway);
-}
-
-int32_t NetUtils::do_ifc_remove_route(const char *ifname,
- const char *dst,
- uint32_t prefixLength,
- const char *gateway)
-{
- USE_DLFUNC(ifc_remove_route)
- return ifc_remove_route(ifname, dst, prefixLength, gateway);
-}
-
-int32_t NetUtils::do_ifc_remove_host_routes(const char *ifname)
-{
- USE_DLFUNC(ifc_remove_host_routes)
- return ifc_remove_host_routes(ifname);
-}
-
-int32_t NetUtils::do_ifc_remove_default_route(const char *ifname)
-{
- USE_DLFUNC(ifc_remove_default_route)
- return ifc_remove_default_route(ifname);
-}
-
-int32_t NetUtils::do_dhcp_stop(const char *ifname)
-{
- USE_DLFUNC(dhcp_stop)
- return dhcp_stop(ifname);
-}
-
-int32_t NetUtils::do_dhcp_do_request(const char *ifname,
- char *ipaddr,
- char *gateway,
- uint32_t *prefixLength,
- char *dns1,
- char *dns2,
- char *server,
- uint32_t *lease,
- char* vendorinfo)
-{
- int32_t ret = -1;
- uint32_t sdkVersion = SdkVersion();
-
- if (sdkVersion == 15) {
- // ICS
- // http://androidxref.com/4.0.4/xref/system/core/libnetutils/dhcp_utils.c#149
- DEFINE_DLFUNC(dhcp_do_request, int32_t, const char*, char*, char*, uint32_t*, char*, char*, char*, uint32_t*)
- USE_DLFUNC(dhcp_do_request)
- vendorinfo[0] = '\0';
-
- ret = dhcp_do_request(ifname, ipaddr, gateway, prefixLength, dns1, dns2,
- server, lease);
- } else if (sdkVersion == 16 || sdkVersion == 17) {
- // JB 4.1 and 4.2
- // http://androidxref.com/4.1.2/xref/system/core/libnetutils/dhcp_utils.c#175
- // http://androidxref.com/4.2.2_r1/xref/system/core/include/netutils/dhcp.h#26
- DEFINE_DLFUNC(dhcp_do_request, int32_t, const char*, char*, char*, uint32_t*, char*, char*, char*, uint32_t*, char*)
- USE_DLFUNC(dhcp_do_request)
- ret = dhcp_do_request(ifname, ipaddr, gateway, prefixLength, dns1, dns2,
- server, lease, vendorinfo);
- } else if (sdkVersion == 18) {
- // JB 4.3
- // http://androidxref.com/4.3_r2.1/xref/system/core/libnetutils/dhcp_utils.c#181
- DEFINE_DLFUNC(dhcp_do_request, int32_t, const char*, char*, char*, uint32_t*, char**, char*, uint32_t*, char*, char*)
- USE_DLFUNC(dhcp_do_request)
- char *dns[3] = {dns1, dns2, nullptr};
- char domains[Property::VALUE_MAX_LENGTH];
- ret = dhcp_do_request(ifname, ipaddr, gateway, prefixLength, dns,
- server, lease, vendorinfo, domains);
- } else if (sdkVersion >= 19) {
- // KitKat 4.4.X
- // http://androidxref.com/4.4_r1/xref/system/core/libnetutils/dhcp_utils.c#18
- // Lollipop 5.0
- //http://androidxref.com/5.0.0_r2/xref/system/core/libnetutils/dhcp_utils.c#186
- DEFINE_DLFUNC(dhcp_do_request, int32_t, const char*, char*, char*, uint32_t*, char**, char*, uint32_t*, char*, char*, char*)
- USE_DLFUNC(dhcp_do_request)
- char *dns[3] = {dns1, dns2, nullptr};
- char domains[Property::VALUE_MAX_LENGTH];
- char mtu[Property::VALUE_MAX_LENGTH];
- ret = dhcp_do_request(ifname, ipaddr, gateway, prefixLength, dns, server, lease, vendorinfo, domains, mtu);
- } else {
- NS_WARNING("Unable to perform do_dhcp_request: unsupported sdk version!");
- }
- return ret;
-}
diff --git a/dom/network/NetUtils.h b/dom/network/NetUtils.h
deleted file mode 100644
index 4af365406..000000000
--- a/dom/network/NetUtils.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/* -*- 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/. */
-
-/**
- * Abstraction on top of the network support from libnetutils that we
- * use to set up network connections.
- */
-
-#ifndef NetUtils_h
-#define NetUtils_h
-
-#include "arpa/inet.h"
-
-// Copied from ifc.h
-#define RESET_IPV4_ADDRESSES 0x01
-#define RESET_IPV6_ADDRESSES 0x02
-#define RESET_ALL_ADDRESSES (RESET_IPV4_ADDRESSES | RESET_IPV6_ADDRESSES)
-
-// Implements netutils functions. No need for an abstract class here since we
-// only have a one sdk specific method (dhcp_do_request)
-class NetUtils
-{
-public:
- static void* GetSharedLibrary();
-
- NetUtils();
-
- int32_t do_ifc_enable(const char *ifname);
- int32_t do_ifc_disable(const char *ifname);
- int32_t do_ifc_configure(const char *ifname,
- in_addr_t address,
- uint32_t prefixLength,
- in_addr_t gateway,
- in_addr_t dns1,
- in_addr_t dns2);
- int32_t do_ifc_reset_connections(const char *ifname, const int32_t resetMask);
- int32_t do_ifc_set_default_route(const char *ifname, in_addr_t gateway);
- int32_t do_ifc_add_route(const char *ifname,
- const char *dst,
- uint32_t prefixLength,
- const char *gateway);
- int32_t do_ifc_remove_route(const char *ifname,
- const char *dst,
- uint32_t prefixLength,
- const char *gateway);
- int32_t do_ifc_remove_host_routes(const char *ifname);
- int32_t do_ifc_remove_default_route(const char *ifname);
- int32_t do_dhcp_stop(const char *ifname);
- int32_t do_dhcp_do_request(const char *ifname,
- char *ipaddr,
- char *gateway,
- uint32_t *prefixLength,
- char *dns1,
- char *dns2,
- char *server,
- uint32_t *lease,
- char* vendorinfo);
-
- static int32_t SdkVersion();
-};
-
-// Defines a function type with the right arguments and return type.
-#define DEFINE_DLFUNC(name, ret, args...) typedef ret (*FUNC##name)(args);
-
-// Set up a dlsymed function ready to use.
-#define USE_DLFUNC(name) \
- FUNC##name name = (FUNC##name) dlsym(GetSharedLibrary(), #name); \
- if (!name) { \
- MOZ_CRASH("Symbol not found in shared library : " #name); \
- }
-
-#endif // NetUtils_h
diff --git a/dom/network/NetworkStatsDB.jsm b/dom/network/NetworkStatsDB.jsm
deleted file mode 100644
index aa74d40ad..000000000
--- a/dom/network/NetworkStatsDB.jsm
+++ /dev/null
@@ -1,1285 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = ['NetworkStatsDB'];
-
-const DEBUG = false;
-function debug(s) { dump("-*- NetworkStatsDB: " + s + "\n"); }
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/IndexedDBHelper.jsm");
-Cu.importGlobalProperties(["indexedDB"]);
-
-XPCOMUtils.defineLazyServiceGetter(this, "appsService",
- "@mozilla.org/AppsService;1",
- "nsIAppsService");
-
-const DB_NAME = "net_stats";
-const DB_VERSION = 9;
-const DEPRECATED_STATS_STORE_NAME =
- [
- "net_stats_v2", // existed only in DB version 2
- "net_stats", // existed in DB version 1 and 3 to 5
- "net_stats_store", // existed in DB version 6 to 8
- ];
-const STATS_STORE_NAME = "net_stats_store_v3"; // since DB version 9
-const ALARMS_STORE_NAME = "net_alarm";
-
-// Constant defining the maximum values allowed per interface. If more, older
-// will be erased.
-const VALUES_MAX_LENGTH = 6 * 30;
-
-// Constant defining the rate of the samples. Daily.
-const SAMPLE_RATE = 1000 * 60 * 60 * 24;
-
-this.NetworkStatsDB = function NetworkStatsDB() {
- if (DEBUG) {
- debug("Constructor");
- }
- this.initDBHelper(DB_NAME, DB_VERSION, [STATS_STORE_NAME, ALARMS_STORE_NAME]);
-}
-
-NetworkStatsDB.prototype = {
- __proto__: IndexedDBHelper.prototype,
-
- dbNewTxn: function dbNewTxn(store_name, txn_type, callback, txnCb) {
- function successCb(result) {
- txnCb(null, result);
- }
- function errorCb(error) {
- txnCb(error, null);
- }
- return this.newTxn(txn_type, store_name, callback, successCb, errorCb);
- },
-
- /**
- * The onupgradeneeded handler of the IDBOpenDBRequest.
- * This function is called in IndexedDBHelper open() method.
- *
- * @param {IDBTransaction} aTransaction
- * {IDBDatabase} aDb
- * {64-bit integer} aOldVersion The version number on local storage.
- * {64-bit integer} aNewVersion The version number to be upgraded to.
- *
- * @note Be careful with the database upgrade pattern.
- * Because IndexedDB operations are performed asynchronously, we must
- * apply a recursive approach instead of an iterative approach while
- * upgrading versions.
- */
- upgradeSchema: function upgradeSchema(aTransaction, aDb, aOldVersion, aNewVersion) {
- if (DEBUG) {
- debug("upgrade schema from: " + aOldVersion + " to " + aNewVersion + " called!");
- }
- let db = aDb;
- let objectStore;
-
- // An array of upgrade functions for each version.
- let upgradeSteps = [
- function upgrade0to1() {
- if (DEBUG) debug("Upgrade 0 to 1: Create object stores and indexes.");
-
- // Create the initial database schema.
- objectStore = db.createObjectStore(DEPRECATED_STATS_STORE_NAME[1],
- { keyPath: ["connectionType", "timestamp"] });
- objectStore.createIndex("connectionType", "connectionType", { unique: false });
- objectStore.createIndex("timestamp", "timestamp", { unique: false });
- objectStore.createIndex("rxBytes", "rxBytes", { unique: false });
- objectStore.createIndex("txBytes", "txBytes", { unique: false });
- objectStore.createIndex("rxTotalBytes", "rxTotalBytes", { unique: false });
- objectStore.createIndex("txTotalBytes", "txTotalBytes", { unique: false });
-
- upgradeNextVersion();
- },
-
- function upgrade1to2() {
- if (DEBUG) debug("Upgrade 1 to 2: Do nothing.");
- upgradeNextVersion();
- },
-
- function upgrade2to3() {
- if (DEBUG) debug("Upgrade 2 to 3: Add keyPath appId to object store.");
-
- // In order to support per-app traffic data storage, the original
- // objectStore needs to be replaced by a new objectStore with new
- // key path ("appId") and new index ("appId").
- // Also, since now networks are identified by their
- // [networkId, networkType] not just by their connectionType,
- // to modify the keyPath is mandatory to delete the object store
- // and create it again. Old data is going to be deleted because the
- // networkId for each sample can not be set.
-
- // In version 1.2 objectStore name was 'net_stats_v2', to avoid errors when
- // upgrading from 1.2 to 1.3 objectStore name should be checked.
- let stores = db.objectStoreNames;
- let deprecatedName = DEPRECATED_STATS_STORE_NAME[0];
- let storeName = DEPRECATED_STATS_STORE_NAME[1];
- if(stores.contains(deprecatedName)) {
- // Delete the obsolete stats store.
- db.deleteObjectStore(deprecatedName);
- } else {
- // Re-create stats object store without copying records.
- db.deleteObjectStore(storeName);
- }
-
- objectStore = db.createObjectStore(storeName, { keyPath: ["appId", "network", "timestamp"] });
- objectStore.createIndex("appId", "appId", { unique: false });
- objectStore.createIndex("network", "network", { unique: false });
- objectStore.createIndex("networkType", "networkType", { unique: false });
- objectStore.createIndex("timestamp", "timestamp", { unique: false });
- objectStore.createIndex("rxBytes", "rxBytes", { unique: false });
- objectStore.createIndex("txBytes", "txBytes", { unique: false });
- objectStore.createIndex("rxTotalBytes", "rxTotalBytes", { unique: false });
- objectStore.createIndex("txTotalBytes", "txTotalBytes", { unique: false });
-
- upgradeNextVersion();
- },
-
- function upgrade3to4() {
- if (DEBUG) debug("Upgrade 3 to 4: Delete redundant indexes.");
-
- // Delete redundant indexes (leave "network" only).
- objectStore = aTransaction.objectStore(DEPRECATED_STATS_STORE_NAME[1]);
- if (objectStore.indexNames.contains("appId")) {
- objectStore.deleteIndex("appId");
- }
- if (objectStore.indexNames.contains("networkType")) {
- objectStore.deleteIndex("networkType");
- }
- if (objectStore.indexNames.contains("timestamp")) {
- objectStore.deleteIndex("timestamp");
- }
- if (objectStore.indexNames.contains("rxBytes")) {
- objectStore.deleteIndex("rxBytes");
- }
- if (objectStore.indexNames.contains("txBytes")) {
- objectStore.deleteIndex("txBytes");
- }
- if (objectStore.indexNames.contains("rxTotalBytes")) {
- objectStore.deleteIndex("rxTotalBytes");
- }
- if (objectStore.indexNames.contains("txTotalBytes")) {
- objectStore.deleteIndex("txTotalBytes");
- }
-
- upgradeNextVersion();
- },
-
- function upgrade4to5() {
- if (DEBUG) debug("Upgrade 4 to 5: Create object store for alarms.");
-
- // In order to manage alarms, it is necessary to use a global counter
- // (totalBytes) that will increase regardless of the system reboot.
- objectStore = aTransaction.objectStore(DEPRECATED_STATS_STORE_NAME[1]);
-
- // Now, systemBytes will hold the old totalBytes and totalBytes will
- // keep the increasing counter. |counters| will keep the track of
- // accumulated values.
- let counters = {};
-
- objectStore.openCursor().onsuccess = function(event) {
- let cursor = event.target.result;
- if (!cursor){
- // upgrade4to5 completed now.
- upgradeNextVersion();
- return;
- }
-
- cursor.value.rxSystemBytes = cursor.value.rxTotalBytes;
- cursor.value.txSystemBytes = cursor.value.txTotalBytes;
-
- if (cursor.value.appId == 0) {
- let netId = cursor.value.network[0] + '' + cursor.value.network[1];
- if (!counters[netId]) {
- counters[netId] = {
- rxCounter: 0,
- txCounter: 0,
- lastRx: 0,
- lastTx: 0
- };
- }
-
- let rxDiff = cursor.value.rxSystemBytes - counters[netId].lastRx;
- let txDiff = cursor.value.txSystemBytes - counters[netId].lastTx;
- if (rxDiff < 0 || txDiff < 0) {
- // System reboot between samples, so take the current one.
- rxDiff = cursor.value.rxSystemBytes;
- txDiff = cursor.value.txSystemBytes;
- }
-
- counters[netId].rxCounter += rxDiff;
- counters[netId].txCounter += txDiff;
- cursor.value.rxTotalBytes = counters[netId].rxCounter;
- cursor.value.txTotalBytes = counters[netId].txCounter;
-
- counters[netId].lastRx = cursor.value.rxSystemBytes;
- counters[netId].lastTx = cursor.value.txSystemBytes;
- } else {
- cursor.value.rxTotalBytes = cursor.value.rxSystemBytes;
- cursor.value.txTotalBytes = cursor.value.txSystemBytes;
- }
-
- cursor.update(cursor.value);
- cursor.continue();
- };
-
- // Create object store for alarms.
- objectStore = db.createObjectStore(ALARMS_STORE_NAME, { keyPath: "id", autoIncrement: true });
- objectStore.createIndex("alarm", ['networkId','threshold'], { unique: false });
- objectStore.createIndex("manifestURL", "manifestURL", { unique: false });
- },
-
- function upgrade5to6() {
- if (DEBUG) debug("Upgrade 5 to 6: Add keyPath serviceType to object store.");
-
- // In contrast to "per-app" traffic data, "system-only" traffic data
- // refers to data which can not be identified by any applications.
- // To further support "system-only" data storage, the data can be
- // saved by service type (e.g., Tethering, OTA). Thus it's needed to
- // have a new key ("serviceType") for the ojectStore.
- let newObjectStore;
- let deprecatedName = DEPRECATED_STATS_STORE_NAME[1];
- newObjectStore = db.createObjectStore(DEPRECATED_STATS_STORE_NAME[2],
- { keyPath: ["appId", "serviceType", "network", "timestamp"] });
- newObjectStore.createIndex("network", "network", { unique: false });
-
- // Copy the data from the original objectStore to the new objectStore.
- objectStore = aTransaction.objectStore(deprecatedName);
- objectStore.openCursor().onsuccess = function(event) {
- let cursor = event.target.result;
- if (!cursor) {
- db.deleteObjectStore(deprecatedName);
- // upgrade5to6 completed now.
- upgradeNextVersion();
- return;
- }
-
- let newStats = cursor.value;
- newStats.serviceType = "";
- newObjectStore.put(newStats);
- cursor.continue();
- };
- },
-
- function upgrade6to7() {
- if (DEBUG) debug("Upgrade 6 to 7: Replace alarm threshold by relativeThreshold.");
-
- // Replace threshold attribute of alarm index by relativeThreshold in alarms DB.
- // Now alarms are indexed by relativeThreshold, which is the threshold relative
- // to current system stats.
- let alarmsStore = aTransaction.objectStore(ALARMS_STORE_NAME);
-
- // Delete "alarm" index.
- if (alarmsStore.indexNames.contains("alarm")) {
- alarmsStore.deleteIndex("alarm");
- }
-
- // Create new "alarm" index.
- alarmsStore.createIndex("alarm", ['networkId','relativeThreshold'], { unique: false });
-
- // Populate new "alarm" index attributes.
- alarmsStore.openCursor().onsuccess = function(event) {
- let cursor = event.target.result;
- if (!cursor) {
- upgrade6to7_updateTotalBytes();
- return;
- }
-
- cursor.value.relativeThreshold = cursor.value.threshold;
- cursor.value.absoluteThreshold = cursor.value.threshold;
- delete cursor.value.threshold;
-
- cursor.update(cursor.value);
- cursor.continue();
- }
-
- function upgrade6to7_updateTotalBytes() {
- if (DEBUG) debug("Upgrade 6 to 7: Update TotalBytes.");
- // Previous versions save accumulative totalBytes, increasing although the system
- // reboots or resets stats. But is necessary to reset the total counters when reset
- // through 'clearInterfaceStats'.
- let statsStore = aTransaction.objectStore(DEPRECATED_STATS_STORE_NAME[2]);
- let networks = [];
-
- // Find networks stored in the database.
- statsStore.index("network").openKeyCursor(null, "nextunique").onsuccess = function(event) {
- let cursor = event.target.result;
-
- // Store each network into an array.
- if (cursor) {
- networks.push(cursor.key);
- cursor.continue();
- return;
- }
-
- // Start to deal with each network.
- let pending = networks.length;
-
- if (pending === 0) {
- // Found no records of network. upgrade6to7 completed now.
- upgradeNextVersion();
- return;
- }
-
- networks.forEach(function(network) {
- let lowerFilter = [0, "", network, 0];
- let upperFilter = [0, "", network, ""];
- let range = IDBKeyRange.bound(lowerFilter, upperFilter, false, false);
-
- // Find number of samples for a given network.
- statsStore.count(range).onsuccess = function(event) {
- let recordCount = event.target.result;
-
- // If there are more samples than the max allowed, there is no way to know
- // when does reset take place.
- if (recordCount === 0 || recordCount >= VALUES_MAX_LENGTH) {
- pending--;
- if (pending === 0) {
- upgradeNextVersion();
- }
- return;
- }
-
- let last = null;
- // Reset detected if the first sample totalCounters are different than bytes
- // counters. If so, the total counters should be recalculated.
- statsStore.openCursor(range).onsuccess = function(event) {
- let cursor = event.target.result;
- if (!cursor) {
- pending--;
- if (pending === 0) {
- upgradeNextVersion();
- }
- return;
- }
- if (!last) {
- if (cursor.value.rxTotalBytes == cursor.value.rxBytes &&
- cursor.value.txTotalBytes == cursor.value.txBytes) {
- pending--;
- if (pending === 0) {
- upgradeNextVersion();
- }
- return;
- }
-
- cursor.value.rxTotalBytes = cursor.value.rxBytes;
- cursor.value.txTotalBytes = cursor.value.txBytes;
- cursor.update(cursor.value);
- last = cursor.value;
- cursor.continue();
- return;
- }
-
- // Recalculate the total counter for last / current sample
- cursor.value.rxTotalBytes = last.rxTotalBytes + cursor.value.rxBytes;
- cursor.value.txTotalBytes = last.txTotalBytes + cursor.value.txBytes;
- cursor.update(cursor.value);
- last = cursor.value;
- cursor.continue();
- }
- }
- }, this); // end of networks.forEach()
- }; // end of statsStore.index("network").openKeyCursor().onsuccess callback
- } // end of function upgrade6to7_updateTotalBytes
- },
-
- function upgrade7to8() {
- if (DEBUG) debug("Upgrade 7 to 8: Create index serviceType.");
-
- // Create index for 'ServiceType' in order to make it retrievable.
- let statsStore = aTransaction.objectStore(DEPRECATED_STATS_STORE_NAME[2]);
- statsStore.createIndex("serviceType", "serviceType", { unique: false });
-
- upgradeNextVersion();
- },
-
- function upgrade8to9() {
- if (DEBUG) debug("Upgrade 8 to 9: Add keyPath isInBrowser to " +
- "network stats object store");
-
- // Since B2G v2.0, there is no stand-alone browser app anymore.
- // The browser app is a mozbrowser iframe element owned by system app.
- // In order to separate traffic generated from system and browser, we
- // have to add a new attribute |isInBrowser| as keyPath.
- // Refer to bug 1070944 for more detail.
- let newObjectStore;
- let deprecatedName = DEPRECATED_STATS_STORE_NAME[2];
- newObjectStore = db.createObjectStore(STATS_STORE_NAME,
- { keyPath: ["appId", "isInBrowser", "serviceType",
- "network", "timestamp"] });
- newObjectStore.createIndex("network", "network", { unique: false });
- newObjectStore.createIndex("serviceType", "serviceType", { unique: false });
-
- // Copy records from the current object store to the new one.
- objectStore = aTransaction.objectStore(deprecatedName);
- objectStore.openCursor().onsuccess = function (event) {
- let cursor = event.target.result;
- if (!cursor) {
- db.deleteObjectStore(deprecatedName);
- // upgrade8to9 completed now.
- return;
- }
- let newStats = cursor.value;
- // Augment records by adding the new isInBrowser attribute.
- // Notes:
- // 1. Key value cannot be boolean type. Use 1/0 instead of true/false.
- // 2. Most traffic of system app should come from its browser iframe,
- // thus assign isInBrowser as 1 for system app.
- let manifestURL = appsService.getManifestURLByLocalId(newStats.appId);
- if (manifestURL && manifestURL.search(/app:\/\/system\./) === 0) {
- newStats.isInBrowser = 1;
- } else {
- newStats.isInBrowser = 0;
- }
- newObjectStore.put(newStats);
- cursor.continue();
- };
- }
- ];
-
- let index = aOldVersion;
- let outer = this;
-
- function upgradeNextVersion() {
- if (index == aNewVersion) {
- debug("Upgrade finished.");
- return;
- }
-
- try {
- var i = index++;
- if (DEBUG) debug("Upgrade step: " + i + "\n");
- upgradeSteps[i].call(outer);
- } catch (ex) {
- dump("Caught exception " + ex);
- throw ex;
- return;
- }
- }
-
- if (aNewVersion > upgradeSteps.length) {
- debug("No migration steps for the new version!");
- aTransaction.abort();
- return;
- }
-
- upgradeNextVersion();
- },
-
- importData: function importData(aStats) {
- let stats = { appId: aStats.appId,
- isInBrowser: aStats.isInBrowser ? 1 : 0,
- serviceType: aStats.serviceType,
- network: [aStats.networkId, aStats.networkType],
- timestamp: aStats.timestamp,
- rxBytes: aStats.rxBytes,
- txBytes: aStats.txBytes,
- rxSystemBytes: aStats.rxSystemBytes,
- txSystemBytes: aStats.txSystemBytes,
- rxTotalBytes: aStats.rxTotalBytes,
- txTotalBytes: aStats.txTotalBytes };
-
- return stats;
- },
-
- exportData: function exportData(aStats) {
- let stats = { appId: aStats.appId,
- isInBrowser: aStats.isInBrowser ? true : false,
- serviceType: aStats.serviceType,
- networkId: aStats.network[0],
- networkType: aStats.network[1],
- timestamp: aStats.timestamp,
- rxBytes: aStats.rxBytes,
- txBytes: aStats.txBytes,
- rxTotalBytes: aStats.rxTotalBytes,
- txTotalBytes: aStats.txTotalBytes };
-
- return stats;
- },
-
- normalizeDate: function normalizeDate(aDate) {
- // Convert to UTC according to timezone and
- // filter timestamp to get SAMPLE_RATE precission
- let timestamp = aDate.getTime() - aDate.getTimezoneOffset() * 60 * 1000;
- timestamp = Math.floor(timestamp / SAMPLE_RATE) * SAMPLE_RATE;
- return timestamp;
- },
-
- saveStats: function saveStats(aStats, aResultCb) {
- let isAccumulative = aStats.isAccumulative;
- let timestamp = this.normalizeDate(aStats.date);
-
- let stats = { appId: aStats.appId,
- isInBrowser: aStats.isInBrowser,
- serviceType: aStats.serviceType,
- networkId: aStats.networkId,
- networkType: aStats.networkType,
- timestamp: timestamp,
- rxBytes: isAccumulative ? 0 : aStats.rxBytes,
- txBytes: isAccumulative ? 0 : aStats.txBytes,
- rxSystemBytes: isAccumulative ? aStats.rxBytes : 0,
- txSystemBytes: isAccumulative ? aStats.txBytes : 0,
- rxTotalBytes: isAccumulative ? aStats.rxBytes : 0,
- txTotalBytes: isAccumulative ? aStats.txBytes : 0 };
-
- stats = this.importData(stats);
-
- this.dbNewTxn(STATS_STORE_NAME, "readwrite", function(aTxn, aStore) {
- if (DEBUG) {
- debug("Filtered time: " + new Date(timestamp));
- debug("New stats: " + JSON.stringify(stats));
- }
-
- let lowerFilter = [stats.appId, stats.isInBrowser, stats.serviceType,
- stats.network, 0];
- let upperFilter = [stats.appId, stats.isInBrowser, stats.serviceType,
- stats.network, ""];
- let range = IDBKeyRange.bound(lowerFilter, upperFilter, false, false);
-
- let request = aStore.openCursor(range, 'prev');
- request.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (!cursor) {
- // Empty, so save first element.
-
- if (!isAccumulative) {
- this._saveStats(aTxn, aStore, stats);
- return;
- }
-
- // There could be a time delay between the point when the network
- // interface comes up and the point when the database is initialized.
- // In this short interval some traffic data are generated but are not
- // registered by the first sample.
- stats.rxBytes = stats.rxTotalBytes;
- stats.txBytes = stats.txTotalBytes;
-
- // However, if the interface is not switched on after the database is
- // initialized (dual sim use case) stats should be set to 0.
- let req = aStore.index("network").openKeyCursor(null, "nextunique");
- req.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor) {
- if (cursor.key[1] == stats.network[1]) {
- stats.rxBytes = 0;
- stats.txBytes = 0;
- this._saveStats(aTxn, aStore, stats);
- return;
- }
-
- cursor.continue();
- return;
- }
-
- this._saveStats(aTxn, aStore, stats);
- }.bind(this);
-
- return;
- }
-
- // There are old samples
- if (DEBUG) {
- debug("Last value " + JSON.stringify(cursor.value));
- }
-
- // Remove stats previous to now - VALUE_MAX_LENGTH
- this._removeOldStats(aTxn, aStore, stats.appId, stats.isInBrowser,
- stats.serviceType, stats.network, stats.timestamp);
-
- // Process stats before save
- this._processSamplesDiff(aTxn, aStore, cursor, stats, isAccumulative);
- }.bind(this);
- }.bind(this), aResultCb);
- },
-
- /*
- * This function check that stats are saved in the database following the sample rate.
- * In this way is easier to find elements when stats are requested.
- */
- _processSamplesDiff: function _processSamplesDiff(aTxn,
- aStore,
- aLastSampleCursor,
- aNewSample,
- aIsAccumulative) {
- let lastSample = aLastSampleCursor.value;
-
- // Get difference between last and new sample.
- let diff = (aNewSample.timestamp - lastSample.timestamp) / SAMPLE_RATE;
- if (diff % 1) {
- // diff is decimal, so some error happened because samples are stored as a multiple
- // of SAMPLE_RATE
- aTxn.abort();
- throw new Error("Error processing samples");
- }
-
- if (DEBUG) {
- debug("New: " + aNewSample.timestamp + " - Last: " +
- lastSample.timestamp + " - diff: " + diff);
- }
-
- // If the incoming data has a accumulation feature, the new
- // |txBytes|/|rxBytes| is assigend by differnces between the new
- // |txTotalBytes|/|rxTotalBytes| and the last |txTotalBytes|/|rxTotalBytes|.
- // Else, if incoming data is non-accumulative, the |txBytes|/|rxBytes|
- // is the new |txBytes|/|rxBytes|.
- let rxDiff = 0;
- let txDiff = 0;
- if (aIsAccumulative) {
- rxDiff = aNewSample.rxSystemBytes - lastSample.rxSystemBytes;
- txDiff = aNewSample.txSystemBytes - lastSample.txSystemBytes;
- if (rxDiff < 0 || txDiff < 0) {
- rxDiff = aNewSample.rxSystemBytes;
- txDiff = aNewSample.txSystemBytes;
- }
- aNewSample.rxBytes = rxDiff;
- aNewSample.txBytes = txDiff;
-
- aNewSample.rxTotalBytes = lastSample.rxTotalBytes + rxDiff;
- aNewSample.txTotalBytes = lastSample.txTotalBytes + txDiff;
- } else {
- rxDiff = aNewSample.rxBytes;
- txDiff = aNewSample.txBytes;
- }
-
- if (diff == 1) {
- // New element.
-
- // If the incoming data is non-accumulative, the new
- // |rxTotalBytes|/|txTotalBytes| needs to be updated by adding new
- // |rxBytes|/|txBytes| to the last |rxTotalBytes|/|txTotalBytes|.
- if (!aIsAccumulative) {
- aNewSample.rxTotalBytes = aNewSample.rxBytes + lastSample.rxTotalBytes;
- aNewSample.txTotalBytes = aNewSample.txBytes + lastSample.txTotalBytes;
- }
-
- this._saveStats(aTxn, aStore, aNewSample);
- return;
- }
- if (diff > 1) {
- // Some samples lost. Device off during one or more samplerate periods.
- // Time or timezone changed
- // Add lost samples with 0 bytes and the actual one.
- if (diff > VALUES_MAX_LENGTH) {
- diff = VALUES_MAX_LENGTH;
- }
-
- let data = [];
- for (let i = diff - 2; i >= 0; i--) {
- let time = aNewSample.timestamp - SAMPLE_RATE * (i + 1);
- let sample = { appId: aNewSample.appId,
- isInBrowser: aNewSample.isInBrowser,
- serviceType: aNewSample.serviceType,
- network: aNewSample.network,
- timestamp: time,
- rxBytes: 0,
- txBytes: 0,
- rxSystemBytes: lastSample.rxSystemBytes,
- txSystemBytes: lastSample.txSystemBytes,
- rxTotalBytes: lastSample.rxTotalBytes,
- txTotalBytes: lastSample.txTotalBytes };
-
- data.push(sample);
- }
-
- data.push(aNewSample);
- this._saveStats(aTxn, aStore, data);
- return;
- }
- if (diff == 0 || diff < 0) {
- // New element received before samplerate period. It means that device has
- // been restarted (or clock / timezone change).
- // Update element. If diff < 0, clock or timezone changed back. Place data
- // in the last sample.
-
- // Old |rxTotalBytes|/|txTotalBytes| needs to get updated by adding the
- // last |rxTotalBytes|/|txTotalBytes|.
- lastSample.rxBytes += rxDiff;
- lastSample.txBytes += txDiff;
- lastSample.rxSystemBytes = aNewSample.rxSystemBytes;
- lastSample.txSystemBytes = aNewSample.txSystemBytes;
- lastSample.rxTotalBytes += rxDiff;
- lastSample.txTotalBytes += txDiff;
-
- if (DEBUG) {
- debug("Update: " + JSON.stringify(lastSample));
- }
- let req = aLastSampleCursor.update(lastSample);
- }
- },
-
- _saveStats: function _saveStats(aTxn, aStore, aNetworkStats) {
- if (DEBUG) {
- debug("_saveStats: " + JSON.stringify(aNetworkStats));
- }
-
- if (Array.isArray(aNetworkStats)) {
- let len = aNetworkStats.length - 1;
- for (let i = 0; i <= len; i++) {
- aStore.put(aNetworkStats[i]);
- }
- } else {
- aStore.put(aNetworkStats);
- }
- },
-
- _removeOldStats: function _removeOldStats(aTxn, aStore, aAppId, aIsInBrowser,
- aServiceType, aNetwork, aDate) {
- // Callback function to remove old items when new ones are added.
- let filterDate = aDate - (SAMPLE_RATE * VALUES_MAX_LENGTH - 1);
- let lowerFilter = [aAppId, aIsInBrowser, aServiceType, aNetwork, 0];
- let upperFilter = [aAppId, aIsInBrowser, aServiceType, aNetwork, filterDate];
- let range = IDBKeyRange.bound(lowerFilter, upperFilter, false, false);
- let lastSample = null;
- let self = this;
-
- aStore.openCursor(range).onsuccess = function(event) {
- var cursor = event.target.result;
- if (cursor) {
- lastSample = cursor.value;
- cursor.delete();
- cursor.continue();
- return;
- }
-
- // If all samples for a network are removed, an empty sample
- // has to be saved to keep the totalBytes in order to compute
- // future samples because system counters are not set to 0.
- // Thus, if there are no samples left, the last sample removed
- // will be saved again after setting its bytes to 0.
- let request = aStore.index("network").openCursor(aNetwork);
- request.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (!cursor && lastSample != null) {
- let timestamp = new Date();
- timestamp = self.normalizeDate(timestamp);
- lastSample.timestamp = timestamp;
- lastSample.rxBytes = 0;
- lastSample.txBytes = 0;
- self._saveStats(aTxn, aStore, lastSample);
- }
- };
- };
- },
-
- clearInterfaceStats: function clearInterfaceStats(aNetwork, aResultCb) {
- let network = [aNetwork.network.id, aNetwork.network.type];
- let self = this;
-
- // Clear and save an empty sample to keep sync with system counters
- this.dbNewTxn(STATS_STORE_NAME, "readwrite", function(aTxn, aStore) {
- let sample = null;
- let request = aStore.index("network").openCursor(network, "prev");
- request.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor) {
- if (!sample && cursor.value.appId == 0) {
- sample = cursor.value;
- }
-
- cursor.delete();
- cursor.continue();
- return;
- }
-
- if (sample) {
- let timestamp = new Date();
- timestamp = self.normalizeDate(timestamp);
- sample.timestamp = timestamp;
- sample.appId = 0;
- sample.isInBrowser = 0;
- sample.serviceType = "";
- sample.rxBytes = 0;
- sample.txBytes = 0;
- sample.rxTotalBytes = 0;
- sample.txTotalBytes = 0;
-
- self._saveStats(aTxn, aStore, sample);
- }
- };
- }, this._resetAlarms.bind(this, aNetwork.networkId, aResultCb));
- },
-
- clearStats: function clearStats(aNetworks, aResultCb) {
- let index = 0;
- let stats = [];
- let self = this;
-
- let callback = function(aError, aResult) {
- index++;
-
- if (!aError && index < aNetworks.length) {
- self.clearInterfaceStats(aNetworks[index], callback);
- return;
- }
-
- aResultCb(aError, aResult);
- };
-
- if (!aNetworks[index]) {
- aResultCb(null, true);
- return;
- }
- this.clearInterfaceStats(aNetworks[index], callback);
- },
-
- getCurrentStats: function getCurrentStats(aNetwork, aDate, aResultCb) {
- if (DEBUG) {
- debug("Get current stats for " + JSON.stringify(aNetwork) + " since " + aDate);
- }
-
- let network = [aNetwork.id, aNetwork.type];
- if (aDate) {
- this._getCurrentStatsFromDate(network, aDate, aResultCb);
- return;
- }
-
- this._getCurrentStats(network, aResultCb);
- },
-
- _getCurrentStats: function _getCurrentStats(aNetwork, aResultCb) {
- this.dbNewTxn(STATS_STORE_NAME, "readonly", function(txn, store) {
- let request = null;
- let upperFilter = [0, 1, "", aNetwork, Date.now()];
- let range = IDBKeyRange.upperBound(upperFilter, false);
- let result = { rxBytes: 0, txBytes: 0,
- rxTotalBytes: 0, txTotalBytes: 0 };
-
- request = store.openCursor(range, "prev");
-
- request.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor) {
- result.rxBytes = result.rxTotalBytes = cursor.value.rxTotalBytes;
- result.txBytes = result.txTotalBytes = cursor.value.txTotalBytes;
- }
-
- txn.result = result;
- };
- }.bind(this), aResultCb);
- },
-
- _getCurrentStatsFromDate: function _getCurrentStatsFromDate(aNetwork, aDate, aResultCb) {
- aDate = new Date(aDate);
- this.dbNewTxn(STATS_STORE_NAME, "readonly", function(txn, store) {
- let request = null;
- let start = this.normalizeDate(aDate);
- let upperFilter = [0, 1, "", aNetwork, Date.now()];
- let range = IDBKeyRange.upperBound(upperFilter, false);
- let result = { rxBytes: 0, txBytes: 0,
- rxTotalBytes: 0, txTotalBytes: 0 };
-
- request = store.openCursor(range, "prev");
-
- request.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor) {
- result.rxBytes = result.rxTotalBytes = cursor.value.rxTotalBytes;
- result.txBytes = result.txTotalBytes = cursor.value.txTotalBytes;
- }
-
- let timestamp = cursor.value.timestamp;
- let range = IDBKeyRange.lowerBound(lowerFilter, false);
- request = store.openCursor(range);
-
- request.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor) {
- if (cursor.value.timestamp == timestamp) {
- // There is one sample only.
- result.rxBytes = cursor.value.rxBytes;
- result.txBytes = cursor.value.txBytes;
- } else {
- result.rxBytes -= cursor.value.rxTotalBytes;
- result.txBytes -= cursor.value.txTotalBytes;
- }
- }
-
- txn.result = result;
- };
- };
- }.bind(this), aResultCb);
- },
-
- find: function find(aResultCb, aAppId, aBrowsingTrafficOnly, aServiceType,
- aNetwork, aStart, aEnd, aAppManifestURL) {
- let offset = (new Date()).getTimezoneOffset() * 60 * 1000;
- let start = this.normalizeDate(aStart);
- let end = this.normalizeDate(aEnd);
-
- if (DEBUG) {
- debug("Find samples for appId: " + aAppId +
- " browsingTrafficOnly: " + aBrowsingTrafficOnly +
- " serviceType: " + aServiceType +
- " network: " + JSON.stringify(aNetwork) + " from " + start +
- " until " + end);
- debug("Start time: " + new Date(start));
- debug("End time: " + new Date(end));
- }
-
- // Find samples of browsing traffic (isInBrowser = 1) first since they are
- // needed no matter browsingTrafficOnly is true or false.
- // We have to make two queries to database because we cannot filter correct
- // records by a single query that sets ranges for two keys (isInBrowser and
- // timestamp). We think it is because the keyPath contains an array
- // (network) so such query does not work.
- this.dbNewTxn(STATS_STORE_NAME, "readonly", function(aTxn, aStore) {
- let network = [aNetwork.id, aNetwork.type];
- let lowerFilter = [aAppId, 1, aServiceType, network, start];
- let upperFilter = [aAppId, 1, aServiceType, network, end];
- let range = IDBKeyRange.bound(lowerFilter, upperFilter, false, false);
-
- let data = [];
-
- if (!aTxn.result) {
- aTxn.result = {};
- }
- aTxn.result.appManifestURL = aAppManifestURL;
- aTxn.result.browsingTrafficOnly = aBrowsingTrafficOnly;
- aTxn.result.serviceType = aServiceType;
- aTxn.result.network = aNetwork;
- aTxn.result.start = aStart;
- aTxn.result.end = aEnd;
-
- let request = aStore.openCursor(range).onsuccess = function(event) {
- var cursor = event.target.result;
- if (cursor){
- // We use rxTotalBytes/txTotalBytes instead of rxBytes/txBytes for
- // the first (oldest) sample. The rx/txTotalBytes fields record
- // accumulative usage amount, which means even if old samples were
- // expired and removed from the Database, we can still obtain the
- // correct network usage.
- if (data.length == 0) {
- data.push({ rxBytes: cursor.value.rxTotalBytes,
- txBytes: cursor.value.txTotalBytes,
- date: new Date(cursor.value.timestamp + offset) });
- } else {
- data.push({ rxBytes: cursor.value.rxBytes,
- txBytes: cursor.value.txBytes,
- date: new Date(cursor.value.timestamp + offset) });
- }
- cursor.continue();
- return;
- }
-
- if (aBrowsingTrafficOnly) {
- this.fillResultSamples(start + offset, end + offset, data);
- aTxn.result.data = data;
- return;
- }
-
- // Find samples of app traffic (isInBrowser = 0) as well if
- // browsingTrafficOnly is false.
- lowerFilter = [aAppId, 0, aServiceType, network, start];
- upperFilter = [aAppId, 0, aServiceType, network, end];
- range = IDBKeyRange.bound(lowerFilter, upperFilter, false, false);
- request = aStore.openCursor(range).onsuccess = function(event) {
- cursor = event.target.result;
- if (cursor) {
- var date = new Date(cursor.value.timestamp + offset);
- var foundData = data.find(function (element, index, array) {
- if (element.date.getTime() !== date.getTime()) {
- return false;
- }
- return element;
- }, date);
-
- if (foundData) {
- foundData.rxBytes += cursor.value.rxBytes;
- foundData.txBytes += cursor.value.txBytes;
- } else {
- // We use rxTotalBytes/txTotalBytes instead of rxBytes/txBytes
- // for the first (oldest) sample. The rx/txTotalBytes fields
- // record accumulative usage amount, which means even if old
- // samples were expired and removed from the Database, we can
- // still obtain the correct network usage.
- if (data.length == 0) {
- data.push({ rxBytes: cursor.value.rxTotalBytes,
- txBytes: cursor.value.txTotalBytes,
- date: new Date(cursor.value.timestamp + offset) });
- } else {
- data.push({ rxBytes: cursor.value.rxBytes,
- txBytes: cursor.value.txBytes,
- date: new Date(cursor.value.timestamp + offset) });
- }
- }
- cursor.continue();
- return;
- }
- this.fillResultSamples(start + offset, end + offset, data);
- aTxn.result.data = data;
- }.bind(this); // openCursor(range).onsuccess() callback
- }.bind(this); // openCursor(range).onsuccess() callback
- }.bind(this), aResultCb);
- },
-
- /*
- * Fill data array (samples from database) with empty samples to match
- * requested start / end dates.
- */
- fillResultSamples: function fillResultSamples(aStart, aEnd, aData) {
- if (aData.length == 0) {
- aData.push({ rxBytes: undefined,
- txBytes: undefined,
- date: new Date(aStart) });
- }
-
- while (aStart < aData[0].date.getTime()) {
- aData.unshift({ rxBytes: undefined,
- txBytes: undefined,
- date: new Date(aData[0].date.getTime() - SAMPLE_RATE) });
- }
-
- while (aEnd > aData[aData.length - 1].date.getTime()) {
- aData.push({ rxBytes: undefined,
- txBytes: undefined,
- date: new Date(aData[aData.length - 1].date.getTime() + SAMPLE_RATE) });
- }
- },
-
- getAvailableNetworks: function getAvailableNetworks(aResultCb) {
- this.dbNewTxn(STATS_STORE_NAME, "readonly", function(aTxn, aStore) {
- if (!aTxn.result) {
- aTxn.result = [];
- }
-
- let request = aStore.index("network").openKeyCursor(null, "nextunique");
- request.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor) {
- aTxn.result.push({ id: cursor.key[0],
- type: cursor.key[1] });
- cursor.continue();
- return;
- }
- };
- }, aResultCb);
- },
-
- isNetworkAvailable: function isNetworkAvailable(aNetwork, aResultCb) {
- this.dbNewTxn(STATS_STORE_NAME, "readonly", function(aTxn, aStore) {
- if (!aTxn.result) {
- aTxn.result = false;
- }
-
- let network = [aNetwork.id, aNetwork.type];
- let request = aStore.index("network").openKeyCursor(IDBKeyRange.only(network));
- request.onsuccess = function onsuccess(event) {
- if (event.target.result) {
- aTxn.result = true;
- }
- };
- }, aResultCb);
- },
-
- getAvailableServiceTypes: function getAvailableServiceTypes(aResultCb) {
- this.dbNewTxn(STATS_STORE_NAME, "readonly", function(aTxn, aStore) {
- if (!aTxn.result) {
- aTxn.result = [];
- }
-
- let request = aStore.index("serviceType").openKeyCursor(null, "nextunique");
- request.onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor && cursor.key != "") {
- aTxn.result.push({ serviceType: cursor.key });
- cursor.continue();
- return;
- }
- };
- }, aResultCb);
- },
-
- get sampleRate () {
- return SAMPLE_RATE;
- },
-
- get maxStorageSamples () {
- return VALUES_MAX_LENGTH;
- },
-
- logAllRecords: function logAllRecords(aResultCb) {
- this.dbNewTxn(STATS_STORE_NAME, "readonly", function(aTxn, aStore) {
- aStore.mozGetAll().onsuccess = function onsuccess(event) {
- aTxn.result = event.target.result;
- };
- }, aResultCb);
- },
-
- alarmToRecord: function alarmToRecord(aAlarm) {
- let record = { networkId: aAlarm.networkId,
- absoluteThreshold: aAlarm.absoluteThreshold,
- relativeThreshold: aAlarm.relativeThreshold,
- startTime: aAlarm.startTime,
- data: aAlarm.data,
- manifestURL: aAlarm.manifestURL,
- pageURL: aAlarm.pageURL };
-
- if (aAlarm.id) {
- record.id = aAlarm.id;
- }
-
- return record;
- },
-
- recordToAlarm: function recordToalarm(aRecord) {
- let alarm = { networkId: aRecord.networkId,
- absoluteThreshold: aRecord.absoluteThreshold,
- relativeThreshold: aRecord.relativeThreshold,
- startTime: aRecord.startTime,
- data: aRecord.data,
- manifestURL: aRecord.manifestURL,
- pageURL: aRecord.pageURL };
-
- if (aRecord.id) {
- alarm.id = aRecord.id;
- }
-
- return alarm;
- },
-
- addAlarm: function addAlarm(aAlarm, aResultCb) {
- this.dbNewTxn(ALARMS_STORE_NAME, "readwrite", function(txn, store) {
- if (DEBUG) {
- debug("Going to add " + JSON.stringify(aAlarm));
- }
-
- let record = this.alarmToRecord(aAlarm);
- store.put(record).onsuccess = function setResult(aEvent) {
- txn.result = aEvent.target.result;
- if (DEBUG) {
- debug("Request successful. New record ID: " + txn.result);
- }
- };
- }.bind(this), aResultCb);
- },
-
- getFirstAlarm: function getFirstAlarm(aNetworkId, aResultCb) {
- let self = this;
-
- this.dbNewTxn(ALARMS_STORE_NAME, "readonly", function(txn, store) {
- if (DEBUG) {
- debug("Get first alarm for network " + aNetworkId);
- }
-
- let lowerFilter = [aNetworkId, 0];
- let upperFilter = [aNetworkId, ""];
- let range = IDBKeyRange.bound(lowerFilter, upperFilter);
-
- store.index("alarm").openCursor(range).onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- txn.result = null;
- if (cursor) {
- txn.result = self.recordToAlarm(cursor.value);
- }
- };
- }, aResultCb);
- },
-
- removeAlarm: function removeAlarm(aAlarmId, aManifestURL, aResultCb) {
- this.dbNewTxn(ALARMS_STORE_NAME, "readwrite", function(txn, store) {
- if (DEBUG) {
- debug("Remove alarm " + aAlarmId);
- }
-
- store.get(aAlarmId).onsuccess = function onsuccess(event) {
- let record = event.target.result;
- txn.result = false;
- if (!record || (aManifestURL && record.manifestURL != aManifestURL)) {
- return;
- }
-
- store.delete(aAlarmId);
- txn.result = true;
- }
- }, aResultCb);
- },
-
- removeAlarms: function removeAlarms(aManifestURL, aResultCb) {
- this.dbNewTxn(ALARMS_STORE_NAME, "readwrite", function(txn, store) {
- if (DEBUG) {
- debug("Remove alarms of " + aManifestURL);
- }
-
- store.index("manifestURL").openCursor(aManifestURL)
- .onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor) {
- cursor.delete();
- cursor.continue();
- }
- }
- }, aResultCb);
- },
-
- updateAlarm: function updateAlarm(aAlarm, aResultCb) {
- let self = this;
- this.dbNewTxn(ALARMS_STORE_NAME, "readwrite", function(txn, store) {
- if (DEBUG) {
- debug("Update alarm " + aAlarm.id);
- }
-
- let record = self.alarmToRecord(aAlarm);
- store.openCursor(record.id).onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- txn.result = false;
- if (cursor) {
- cursor.update(record);
- txn.result = true;
- }
- }
- }, aResultCb);
- },
-
- getAlarms: function getAlarms(aNetworkId, aManifestURL, aResultCb) {
- let self = this;
- this.dbNewTxn(ALARMS_STORE_NAME, "readonly", function(txn, store) {
- if (DEBUG) {
- debug("Get alarms for " + aManifestURL);
- }
-
- txn.result = [];
- store.index("manifestURL").openCursor(aManifestURL)
- .onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (!cursor) {
- return;
- }
-
- if (!aNetworkId || cursor.value.networkId == aNetworkId) {
- txn.result.push(self.recordToAlarm(cursor.value));
- }
-
- cursor.continue();
- }
- }, aResultCb);
- },
-
- _resetAlarms: function _resetAlarms(aNetworkId, aResultCb) {
- this.dbNewTxn(ALARMS_STORE_NAME, "readwrite", function(txn, store) {
- if (DEBUG) {
- debug("Reset alarms for network " + aNetworkId);
- }
-
- let lowerFilter = [aNetworkId, 0];
- let upperFilter = [aNetworkId, ""];
- let range = IDBKeyRange.bound(lowerFilter, upperFilter);
-
- store.index("alarm").openCursor(range).onsuccess = function onsuccess(event) {
- let cursor = event.target.result;
- if (cursor) {
- if (cursor.value.startTime) {
- cursor.value.relativeThreshold = cursor.value.threshold;
- cursor.update(cursor.value);
- }
- cursor.continue();
- return;
- }
- };
- }, aResultCb);
- }
-};
diff --git a/dom/network/NetworkStatsManager.js b/dom/network/NetworkStatsManager.js
deleted file mode 100644
index b963aba2b..000000000
--- a/dom/network/NetworkStatsManager.js
+++ /dev/null
@@ -1,388 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const DEBUG = false;
-function debug(s) { dump("-*- NetworkStatsManager: " + s + "\n"); }
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
-
-// Ensure NetworkStatsService and NetworkStatsDB are loaded in the parent process
-// to receive messages from the child processes.
-var appInfo = Cc["@mozilla.org/xre/app-info;1"];
-var isParentProcess = !appInfo || appInfo.getService(Ci.nsIXULRuntime)
- .processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
-if (isParentProcess) {
- Cu.import("resource://gre/modules/NetworkStatsService.jsm");
-}
-
-XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
- "@mozilla.org/childprocessmessagemanager;1",
- "nsISyncMessageSender");
-
-// NetworkStatsData
-const nsIClassInfo = Ci.nsIClassInfo;
-const NETWORKSTATSDATA_CID = Components.ID("{3b16fe17-5583-483a-b486-b64a3243221c}");
-
-function NetworkStatsData(aWindow, aData) {
- this.rxBytes = aData.rxBytes;
- this.txBytes = aData.txBytes;
- this.date = new aWindow.Date(aData.date.getTime());
-}
-
-NetworkStatsData.prototype = {
- classID : NETWORKSTATSDATA_CID,
-
- QueryInterface : XPCOMUtils.generateQI([])
-};
-
-// NetworkStatsInterface
-const NETWORKSTATSINTERFACE_CONTRACTID = "@mozilla.org/networkstatsinterface;1";
-const NETWORKSTATSINTERFACE_CID = Components.ID("{f540615b-d803-43ff-8200-2a9d145a5645}");
-
-function NetworkStatsInterface() {
- if (DEBUG) {
- debug("NetworkStatsInterface Constructor");
- }
-}
-
-NetworkStatsInterface.prototype = {
- __init: function(aNetwork) {
- this.type = aNetwork.type;
- this.id = aNetwork.id;
- },
-
- classID : NETWORKSTATSINTERFACE_CID,
-
- contractID: NETWORKSTATSINTERFACE_CONTRACTID,
- QueryInterface : XPCOMUtils.generateQI([])
-}
-
-// NetworkStats
-const NETWORKSTATS_CID = Components.ID("{28904f59-8497-4ac0-904f-2af14b7fd3de}");
-
-function NetworkStats(aWindow, aStats) {
- if (DEBUG) {
- debug("NetworkStats Constructor");
- }
- this.appManifestURL = aStats.appManifestURL || null;
- this.browsingTrafficOnly = aStats.browsingTrafficOnly || false;
- this.serviceType = aStats.serviceType || null;
- this.network = new aWindow.MozNetworkStatsInterface(aStats.network);
- this.start = aStats.start ? new aWindow.Date(aStats.start.getTime()) : null;
- this.end = aStats.end ? new aWindow.Date(aStats.end.getTime()) : null;
-
- let samples = this.data = new aWindow.Array();
- for (let i = 0; i < aStats.data.length; i++) {
- samples.push(aWindow.MozNetworkStatsData._create(
- aWindow, new NetworkStatsData(aWindow, aStats.data[i])));
- }
-}
-
-NetworkStats.prototype = {
- classID : NETWORKSTATS_CID,
-
- QueryInterface : XPCOMUtils.generateQI()
-}
-
-// NetworkStatsAlarm
-const NETWORKSTATSALARM_CID = Components.ID("{a93ea13e-409c-4189-9b1e-95fff220be55}");
-
-function NetworkStatsAlarm(aWindow, aAlarm) {
- this.alarmId = aAlarm.id;
- this.network = new aWindow.MozNetworkStatsInterface(aAlarm.network);
- this.threshold = aAlarm.threshold;
- this.data = aAlarm.data;
-}
-
-NetworkStatsAlarm.prototype = {
- classID : NETWORKSTATSALARM_CID,
-
- QueryInterface : XPCOMUtils.generateQI([])
-};
-
-// NetworkStatsManager
-
-const NETWORKSTATSMANAGER_CONTRACTID = "@mozilla.org/networkStatsManager;1";
-const NETWORKSTATSMANAGER_CID = Components.ID("{ceb874cd-cc1a-4e65-b404-cc2d3e42425f}");
-
-function NetworkStatsManager() {
- if (DEBUG) {
- debug("Constructor");
- }
-}
-
-NetworkStatsManager.prototype = {
- __proto__: DOMRequestIpcHelper.prototype,
-
- getSamples: function getSamples(aNetwork, aStart, aEnd, aOptions) {
- if (aStart > aEnd) {
- throw Components.results.NS_ERROR_INVALID_ARG;
- }
-
- // appManifestURL is used to query network statistics by app;
- // serviceType is used to query network statistics by system service.
- // It is illegal to specify both of them at the same time.
- if (aOptions.appManifestURL && aOptions.serviceType) {
- throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
- }
- // browsingTrafficOnly is meaningful only when querying by app.
- if (!aOptions.appManifestURL && aOptions.browsingTrafficOnly) {
- throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
- }
-
- let appManifestURL = aOptions.appManifestURL;
- let serviceType = aOptions.serviceType;
- let browsingTrafficOnly = aOptions.browsingTrafficOnly;
-
- // TODO Bug 929410 Date object cannot correctly pass through cpmm/ppmm IPC
- // This is just a work-around by passing timestamp numbers.
- aStart = aStart.getTime();
- aEnd = aEnd.getTime();
-
- let request = this.createRequest();
- cpmm.sendAsyncMessage("NetworkStats:Get",
- { network: aNetwork.toJSON(),
- start: aStart,
- end: aEnd,
- appManifestURL: appManifestURL,
- browsingTrafficOnly: browsingTrafficOnly,
- serviceType: serviceType,
- id: this.getRequestId(request) });
- return request;
- },
-
- clearStats: function clearStats(aNetwork) {
- let request = this.createRequest();
- cpmm.sendAsyncMessage("NetworkStats:Clear",
- { network: aNetwork.toJSON(),
- id: this.getRequestId(request) });
- return request;
- },
-
- clearAllStats: function clearAllStats() {
- let request = this.createRequest();
- cpmm.sendAsyncMessage("NetworkStats:ClearAll",
- {id: this.getRequestId(request)});
- return request;
- },
-
- addAlarm: function addAlarm(aNetwork, aThreshold, aOptions) {
- let request = this.createRequest();
- cpmm.sendAsyncMessage("NetworkStats:SetAlarm",
- {id: this.getRequestId(request),
- data: {network: aNetwork.toJSON(),
- threshold: aThreshold,
- startTime: aOptions.startTime,
- data: aOptions.data,
- manifestURL: this.manifestURL,
- pageURL: this.pageURL}});
- return request;
- },
-
- getAllAlarms: function getAllAlarms(aNetwork) {
- let network = null;
- if (aNetwork) {
- network = aNetwork.toJSON();
- }
-
- let request = this.createRequest();
- cpmm.sendAsyncMessage("NetworkStats:GetAlarms",
- {id: this.getRequestId(request),
- data: {network: network,
- manifestURL: this.manifestURL}});
- return request;
- },
-
- removeAlarms: function removeAlarms(aAlarmId) {
- if (aAlarmId == 0) {
- aAlarmId = -1;
- }
-
- let request = this.createRequest();
- cpmm.sendAsyncMessage("NetworkStats:RemoveAlarms",
- {id: this.getRequestId(request),
- data: {alarmId: aAlarmId,
- manifestURL: this.manifestURL}});
-
- return request;
- },
-
- getAvailableNetworks: function getAvailableNetworks() {
- let request = this.createRequest();
- cpmm.sendAsyncMessage("NetworkStats:GetAvailableNetworks",
- { id: this.getRequestId(request) });
- return request;
- },
-
- getAvailableServiceTypes: function getAvailableServiceTypes() {
- let request = this.createRequest();
- cpmm.sendAsyncMessage("NetworkStats:GetAvailableServiceTypes",
- { id: this.getRequestId(request) });
- return request;
- },
-
- get sampleRate() {
- return cpmm.sendSyncMessage("NetworkStats:SampleRate")[0];
- },
-
- get maxStorageAge() {
- return cpmm.sendSyncMessage("NetworkStats:MaxStorageAge")[0];
- },
-
- receiveMessage: function(aMessage) {
- if (DEBUG) {
- debug("NetworkStatsmanager::receiveMessage: " + aMessage.name);
- }
-
- let msg = aMessage.json;
- let req = this.takeRequest(msg.id);
- if (!req) {
- if (DEBUG) {
- debug("No request stored with id " + msg.id);
- }
- return;
- }
-
- switch (aMessage.name) {
- case "NetworkStats:Get:Return":
- if (msg.error) {
- Services.DOMRequest.fireError(req, msg.error);
- return;
- }
-
- let result = this._window.MozNetworkStats._create(
- this._window, new NetworkStats(this._window, msg.result));
- if (DEBUG) {
- debug("result: " + JSON.stringify(result));
- }
- Services.DOMRequest.fireSuccess(req, result);
- break;
-
- case "NetworkStats:GetAvailableNetworks:Return":
- if (msg.error) {
- Services.DOMRequest.fireError(req, msg.error);
- return;
- }
-
- let networks = new this._window.Array();
- for (let i = 0; i < msg.result.length; i++) {
- let network = new this._window.MozNetworkStatsInterface(msg.result[i]);
- networks.push(network);
- }
-
- Services.DOMRequest.fireSuccess(req, networks);
- break;
-
- case "NetworkStats:GetAvailableServiceTypes:Return":
- if (msg.error) {
- Services.DOMRequest.fireError(req, msg.error);
- return;
- }
-
- let serviceTypes = new this._window.Array();
- for (let i = 0; i < msg.result.length; i++) {
- serviceTypes.push(msg.result[i]);
- }
-
- Services.DOMRequest.fireSuccess(req, serviceTypes);
- break;
-
- case "NetworkStats:Clear:Return":
- case "NetworkStats:ClearAll:Return":
- if (msg.error) {
- Services.DOMRequest.fireError(req, msg.error);
- return;
- }
-
- Services.DOMRequest.fireSuccess(req, true);
- break;
-
- case "NetworkStats:SetAlarm:Return":
- case "NetworkStats:RemoveAlarms:Return":
- if (msg.error) {
- Services.DOMRequest.fireError(req, msg.error);
- return;
- }
-
- Services.DOMRequest.fireSuccess(req, msg.result);
- break;
-
- case "NetworkStats:GetAlarms:Return":
- if (msg.error) {
- Services.DOMRequest.fireError(req, msg.error);
- return;
- }
-
- let alarms = new this._window.Array();
- for (let i = 0; i < msg.result.length; i++) {
- // The WebIDL type of data is any, so we should manually clone it
- // into the content window.
- if ("data" in msg.result[i]) {
- msg.result[i].data = Cu.cloneInto(msg.result[i].data, this._window);
- }
- let alarm = new NetworkStatsAlarm(this._window, msg.result[i]);
- alarms.push(this._window.MozNetworkStatsAlarm._create(this._window, alarm));
- }
-
- Services.DOMRequest.fireSuccess(req, alarms);
- break;
-
- default:
- if (DEBUG) {
- debug("Wrong message: " + aMessage.name);
- }
- }
- },
-
- init: function(aWindow) {
- let principal = aWindow.document.nodePrincipal;
-
- this.initDOMRequestHelper(aWindow, ["NetworkStats:Get:Return",
- "NetworkStats:GetAvailableNetworks:Return",
- "NetworkStats:GetAvailableServiceTypes:Return",
- "NetworkStats:Clear:Return",
- "NetworkStats:ClearAll:Return",
- "NetworkStats:SetAlarm:Return",
- "NetworkStats:GetAlarms:Return",
- "NetworkStats:RemoveAlarms:Return"]);
-
- // Init app properties.
- let appsService = Cc["@mozilla.org/AppsService;1"]
- .getService(Ci.nsIAppsService);
-
- this.manifestURL = appsService.getManifestURLByLocalId(principal.appId);
-
- let isApp = !!this.manifestURL.length;
- if (isApp) {
- this.pageURL = principal.URI.spec;
- }
-
- this.window = aWindow;
- },
-
- // Called from DOMRequestIpcHelper
- uninit: function uninit() {
- if (DEBUG) {
- debug("uninit call");
- }
- },
-
- classID : NETWORKSTATSMANAGER_CID,
- contractID : NETWORKSTATSMANAGER_CONTRACTID,
- QueryInterface : XPCOMUtils.generateQI([Ci.nsIDOMGlobalPropertyInitializer,
- Ci.nsISupportsWeakReference,
- Ci.nsIObserver]),
-}
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NetworkStatsAlarm,
- NetworkStatsData,
- NetworkStatsInterface,
- NetworkStats,
- NetworkStatsManager]);
diff --git a/dom/network/NetworkStatsManager.manifest b/dom/network/NetworkStatsManager.manifest
deleted file mode 100644
index 8e8700910..000000000
--- a/dom/network/NetworkStatsManager.manifest
+++ /dev/null
@@ -1,14 +0,0 @@
-component {3b16fe17-5583-483a-b486-b64a3243221c} NetworkStatsManager.js
-contract @mozilla.org/networkStatsdata;1 {3b16fe17-5583-483a-b486-b64a3243221c}
-
-component {28904f59-8497-4ac0-904f-2af14b7fd3de} NetworkStatsManager.js
-contract @mozilla.org/networkStats;1 {28904f59-8497-4ac0-904f-2af14b7fd3de}
-
-component {f540615b-d803-43ff-8200-2a9d145a5645} NetworkStatsManager.js
-contract @mozilla.org/networkstatsinterface;1 {f540615b-d803-43ff-8200-2a9d145a5645}
-
-component {a93ea13e-409c-4189-9b1e-95fff220be55} NetworkStatsManager.js
-contract @mozilla.org/networkstatsalarm;1 {a93ea13e-409c-4189-9b1e-95fff220be55}
-
-component {ceb874cd-cc1a-4e65-b404-cc2d3e42425f} NetworkStatsManager.js
-contract @mozilla.org/networkStatsManager;1 {ceb874cd-cc1a-4e65-b404-cc2d3e42425f}
diff --git a/dom/network/NetworkStatsService.jsm b/dom/network/NetworkStatsService.jsm
deleted file mode 100644
index 4b6d69498..000000000
--- a/dom/network/NetworkStatsService.jsm
+++ /dev/null
@@ -1,1171 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const DEBUG = false;
-function debug(s) {
- if (DEBUG) {
- dump("-*- NetworkStatsService: " + s + "\n");
- }
-}
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-this.EXPORTED_SYMBOLS = ["NetworkStatsService"];
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/NetworkStatsDB.jsm");
-Cu.import("resource://gre/modules/Timer.jsm");
-
-const NET_NETWORKSTATSSERVICE_CONTRACTID = "@mozilla.org/network/netstatsservice;1";
-const NET_NETWORKSTATSSERVICE_CID = Components.ID("{18725604-e9ac-488a-8aa0-2471e7f6c0a4}");
-
-const TOPIC_BANDWIDTH_CONTROL = "netd-bandwidth-control"
-
-const TOPIC_CONNECTION_STATE_CHANGED = "network-connection-state-changed";
-const NET_TYPE_WIFI = Ci.nsINetworkInfo.NETWORK_TYPE_WIFI;
-const NET_TYPE_MOBILE = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE;
-
-// Networks have different status that NetworkStats API needs to be aware of.
-// Network is present and ready, so NetworkManager provides the whole info.
-const NETWORK_STATUS_READY = 0;
-// Network is present but hasn't established a connection yet (e.g. SIM that has not
-// enabled 3G since boot).
-const NETWORK_STATUS_STANDBY = 1;
-// Network is not present, but stored in database by the previous connections.
-const NETWORK_STATUS_AWAY = 2;
-
-// The maximum traffic amount can be saved in the |cachedStats|.
-const MAX_CACHED_TRAFFIC = 500 * 1000 * 1000; // 500 MB
-
-const QUEUE_TYPE_UPDATE_STATS = 0;
-const QUEUE_TYPE_UPDATE_CACHE = 1;
-const QUEUE_TYPE_WRITE_CACHE = 2;
-
-XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
- "@mozilla.org/parentprocessmessagemanager;1",
- "nsIMessageListenerManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gRil",
- "@mozilla.org/ril;1",
- "nsIRadioInterfaceLayer");
-
-XPCOMUtils.defineLazyServiceGetter(this, "networkService",
- "@mozilla.org/network/service;1",
- "nsINetworkService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "appsService",
- "@mozilla.org/AppsService;1",
- "nsIAppsService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
- "@mozilla.org/settingsService;1",
- "nsISettingsService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "messenger",
- "@mozilla.org/system-message-internal;1",
- "nsISystemMessagesInternal");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gIccService",
- "@mozilla.org/icc/iccservice;1",
- "nsIIccService");
-
-this.NetworkStatsService = {
- init: function() {
- debug("Service started");
-
- Services.obs.addObserver(this, "xpcom-shutdown", false);
- Services.obs.addObserver(this, TOPIC_CONNECTION_STATE_CHANGED, false);
- Services.obs.addObserver(this, TOPIC_BANDWIDTH_CONTROL, false);
- Services.obs.addObserver(this, "profile-after-change", false);
-
- this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-
- // Object to store network interfaces, each network interface is composed
- // by a network object (network type and network Id) and a interfaceName
- // that contains the name of the physical interface (wlan0, rmnet0, etc.).
- // The network type can be 0 for wifi or 1 for mobile. On the other hand,
- // the network id is '0' for wifi or the iccid for mobile (SIM).
- // Each networkInterface is placed in the _networks object by the index of
- // 'networkId + networkType'.
- //
- // _networks object allows to map available network interfaces at low level
- // (wlan0, rmnet0, etc.) to a network. It's not mandatory to have a
- // networkInterface per network but can't exist a networkInterface not
- // being mapped to a network.
-
- this._networks = Object.create(null);
-
- // There is no way to know a priori if wifi connection is available,
- // just when the wifi driver is loaded, but it is unloaded when
- // wifi is switched off. So wifi connection is hardcoded
- let netId = this.getNetworkId('0', NET_TYPE_WIFI);
- this._networks[netId] = { network: { id: '0',
- type: NET_TYPE_WIFI },
- interfaceName: null,
- status: NETWORK_STATUS_STANDBY };
-
- this.messages = ["NetworkStats:Get",
- "NetworkStats:Clear",
- "NetworkStats:ClearAll",
- "NetworkStats:SetAlarm",
- "NetworkStats:GetAlarms",
- "NetworkStats:RemoveAlarms",
- "NetworkStats:GetAvailableNetworks",
- "NetworkStats:GetAvailableServiceTypes",
- "NetworkStats:SampleRate",
- "NetworkStats:MaxStorageAge"];
-
- this.messages.forEach(function(aMsgName) {
- ppmm.addMessageListener(aMsgName, this);
- }, this);
-
- this._db = new NetworkStatsDB();
-
- // Stats for all interfaces are updated periodically
- this.timer.initWithCallback(this, this._db.sampleRate,
- Ci.nsITimer.TYPE_REPEATING_PRECISE_CAN_SKIP);
-
- // Stats not from netd are firstly stored in the cached.
- this.cachedStats = Object.create(null);
- this.cachedStatsDate = new Date();
-
- this.updateQueue = [];
- this.isQueueRunning = false;
-
- this._currentAlarms = {};
- this.initAlarms();
- },
-
- receiveMessage: function(aMessage) {
- if (!aMessage.target.assertPermission("networkstats-manage")) {
- return;
- }
-
- debug("receiveMessage " + aMessage.name);
-
- let mm = aMessage.target;
- let msg = aMessage.json;
-
- switch (aMessage.name) {
- case "NetworkStats:Get":
- this.getSamples(mm, msg);
- break;
- case "NetworkStats:Clear":
- this.clearInterfaceStats(mm, msg);
- break;
- case "NetworkStats:ClearAll":
- this.clearDB(mm, msg);
- break;
- case "NetworkStats:SetAlarm":
- this.setAlarm(mm, msg);
- break;
- case "NetworkStats:GetAlarms":
- this.getAlarms(mm, msg);
- break;
- case "NetworkStats:RemoveAlarms":
- this.removeAlarms(mm, msg);
- break;
- case "NetworkStats:GetAvailableNetworks":
- this.getAvailableNetworks(mm, msg);
- break;
- case "NetworkStats:GetAvailableServiceTypes":
- this.getAvailableServiceTypes(mm, msg);
- break;
- case "NetworkStats:SampleRate":
- // This message is sync.
- return this._db.sampleRate;
- case "NetworkStats:MaxStorageAge":
- // This message is sync.
- return this._db.maxStorageSamples * this._db.sampleRate;
- }
- },
-
- observe: function observe(aSubject, aTopic, aData) {
- switch (aTopic) {
- case TOPIC_CONNECTION_STATE_CHANGED:
-
- // If new interface is registered (notified from NetworkService),
- // the stats are updated for the new interface without waiting to
- // complete the updating period.
-
- let networkInfo = aSubject.QueryInterface(Ci.nsINetworkInfo);
- debug("Network " + networkInfo.name + " of type " + networkInfo.type + " status change");
-
- let netId = this.convertNetworkInfo(networkInfo);
- if (!netId) {
- break;
- }
-
- this._updateCurrentAlarm(netId);
-
- debug("NetId: " + netId);
- this.updateStats(netId);
- break;
-
- case TOPIC_BANDWIDTH_CONTROL:
- debug("Bandwidth message from netd: " + JSON.stringify(aData));
-
- let interfaceName = aData.substring(aData.lastIndexOf(" ") + 1);
- for (let networkId in this._networks) {
- if (interfaceName == this._networks[networkId].interfaceName) {
- let currentAlarm = this._currentAlarms[networkId];
- if (Object.getOwnPropertyNames(currentAlarm).length !== 0) {
- this._fireAlarm(currentAlarm.alarm);
- }
- break;
- }
- }
- break;
-
- case "xpcom-shutdown":
- debug("Service shutdown");
-
- this.messages.forEach(function(aMsgName) {
- ppmm.removeMessageListener(aMsgName, this);
- }, this);
-
- Services.obs.removeObserver(this, "xpcom-shutdown");
- Services.obs.removeObserver(this, "profile-after-change");
- Services.obs.removeObserver(this, TOPIC_CONNECTION_STATE_CHANGED);
- Services.obs.removeObserver(this, TOPIC_BANDWIDTH_CONTROL);
-
- this.timer.cancel();
- this.timer = null;
-
- // Update stats before shutdown
- this.updateAllStats();
- break;
- }
- },
-
- /*
- * nsITimerCallback
- * Timer triggers the update of all stats
- */
- notify: function(aTimer) {
- this.updateAllStats();
- },
-
- /*
- * nsINetworkStatsService
- */
- getRilNetworks: function() {
- let networks = {};
- let numRadioInterfaces = gRil.numRadioInterfaces;
- for (let i = 0; i < numRadioInterfaces; i++) {
- let icc = gIccService.getIccByServiceId(i);
- let radioInterface = gRil.getRadioInterface(i);
- if (icc && icc.iccInfo) {
- let netId = this.getNetworkId(icc.iccInfo.iccid,
- NET_TYPE_MOBILE);
- networks[netId] = { id : icc.iccInfo.iccid,
- type: NET_TYPE_MOBILE };
- }
- }
- return networks;
- },
-
- convertNetworkInfo: function(aNetworkInfo) {
- if (aNetworkInfo.type != NET_TYPE_MOBILE &&
- aNetworkInfo.type != NET_TYPE_WIFI) {
- return null;
- }
-
- let id = '0';
- if (aNetworkInfo.type == NET_TYPE_MOBILE) {
- if (!(aNetworkInfo instanceof Ci.nsIRilNetworkInfo)) {
- debug("Error! Mobile network should be an nsIRilNetworkInfo!");
- return null;
- }
-
- let rilNetwork = aNetworkInfo.QueryInterface(Ci.nsIRilNetworkInfo);
- id = rilNetwork.iccId;
- }
-
- let netId = this.getNetworkId(id, aNetworkInfo.type);
-
- if (!this._networks[netId]) {
- this._networks[netId] = Object.create(null);
- this._networks[netId].network = { id: id,
- type: aNetworkInfo.type };
- }
-
- this._networks[netId].status = NETWORK_STATUS_READY;
- this._networks[netId].interfaceName = aNetworkInfo.name;
- return netId;
- },
-
- getNetworkId: function getNetworkId(aIccId, aNetworkType) {
- return aIccId + '' + aNetworkType;
- },
-
- /* Function to ensure that one network is valid. The network is valid if its status is
- * NETWORK_STATUS_READY, NETWORK_STATUS_STANDBY or NETWORK_STATUS_AWAY.
- *
- * The result is |netId| or null in case of a non-valid network
- * aCallback is signatured as |function(netId)|.
- */
- validateNetwork: function validateNetwork(aNetwork, aCallback) {
- let netId = this.getNetworkId(aNetwork.id, aNetwork.type);
-
- if (this._networks[netId]) {
- aCallback(netId);
- return;
- }
-
- // Check if network is valid (RIL entry) but has not established a connection yet.
- // If so add to networks list with empty interfaceName.
- let rilNetworks = this.getRilNetworks();
- if (rilNetworks[netId]) {
- this._networks[netId] = Object.create(null);
- this._networks[netId].network = rilNetworks[netId];
- this._networks[netId].status = NETWORK_STATUS_STANDBY;
- this._currentAlarms[netId] = Object.create(null);
- aCallback(netId);
- return;
- }
-
- // Check if network is available in the DB.
- this._db.isNetworkAvailable(aNetwork, function(aError, aResult) {
- if (aResult) {
- this._networks[netId] = Object.create(null);
- this._networks[netId].network = aNetwork;
- this._networks[netId].status = NETWORK_STATUS_AWAY;
- this._currentAlarms[netId] = Object.create(null);
- aCallback(netId);
- return;
- }
-
- aCallback(null);
- }.bind(this));
- },
-
- getAvailableNetworks: function getAvailableNetworks(mm, msg) {
- let self = this;
- let rilNetworks = this.getRilNetworks();
- this._db.getAvailableNetworks(function onGetNetworks(aError, aResult) {
-
- // Also return the networks that are valid but have not
- // established connections yet.
- for (let netId in rilNetworks) {
- let found = false;
- for (let i = 0; i < aResult.length; i++) {
- if (netId == self.getNetworkId(aResult[i].id, aResult[i].type)) {
- found = true;
- break;
- }
- }
- if (!found) {
- aResult.push(rilNetworks[netId]);
- }
- }
-
- mm.sendAsyncMessage("NetworkStats:GetAvailableNetworks:Return",
- { id: msg.id, error: aError, result: aResult });
- });
- },
-
- getAvailableServiceTypes: function getAvailableServiceTypes(mm, msg) {
- this._db.getAvailableServiceTypes(function onGetServiceTypes(aError, aResult) {
- mm.sendAsyncMessage("NetworkStats:GetAvailableServiceTypes:Return",
- { id: msg.id, error: aError, result: aResult });
- });
- },
-
- initAlarms: function initAlarms() {
- debug("Init usage alarms");
- let self = this;
-
- for (let netId in this._networks) {
- this._currentAlarms[netId] = Object.create(null);
-
- this._db.getFirstAlarm(netId, function getResult(error, result) {
- if (!error && result) {
- self._setAlarm(result, function onSet(error, success) {
- if (error == "InvalidStateError") {
- self._fireAlarm(result);
- }
- });
- }
- });
- }
- },
-
- /*
- * Function called from manager to get stats from database.
- * In order to return updated stats, first is performed a call to
- * updateAllStats function, which will get last stats from netd
- * and update the database.
- * Then, depending on the request (stats per appId or total stats)
- * it retrieve them from database and return to the manager.
- */
- getSamples: function getSamples(mm, msg) {
- let network = msg.network;
- let netId = this.getNetworkId(network.id, network.type);
-
- let appId = 0;
- let appManifestURL = msg.appManifestURL;
- if (appManifestURL) {
- appId = appsService.getAppLocalIdByManifestURL(appManifestURL);
-
- if (!appId) {
- mm.sendAsyncMessage("NetworkStats:Get:Return",
- { id: msg.id,
- error: "Invalid appManifestURL", result: null });
- return;
- }
- }
-
- let browsingTrafficOnly = msg.browsingTrafficOnly || false;
- let serviceType = msg.serviceType || "";
-
- let start = new Date(msg.start);
- let end = new Date(msg.end);
-
- let callback = (function (aError, aResult) {
- this._db.find(function onStatsFound(aError, aResult) {
- mm.sendAsyncMessage("NetworkStats:Get:Return",
- { id: msg.id, error: aError, result: aResult });
- }, appId, browsingTrafficOnly, serviceType, network, start, end, appManifestURL);
- }).bind(this);
-
- this.validateNetwork(network, function onValidateNetwork(aNetId) {
- if (!aNetId) {
- mm.sendAsyncMessage("NetworkStats:Get:Return",
- { id: msg.id, error: "Invalid connectionType", result: null });
- return;
- }
-
- // If network is currently active we need to update the cached stats first before
- // retrieving stats from the DB.
- if (this._networks[aNetId].status == NETWORK_STATUS_READY) {
- debug("getstats for network " + network.id + " of type " + network.type);
- debug("appId: " + appId + " from appManifestURL: " + appManifestURL);
- debug("browsingTrafficOnly: " + browsingTrafficOnly);
- debug("serviceType: " + serviceType);
-
- if (appId || serviceType) {
- this.updateCachedStats(callback);
- return;
- }
-
- this.updateStats(aNetId, function onStatsUpdated(aResult, aMessage) {
- this.updateCachedStats(callback);
- }.bind(this));
- return;
- }
-
- // Network not active, so no need to update
- this._db.find(function onStatsFound(aError, aResult) {
- mm.sendAsyncMessage("NetworkStats:Get:Return",
- { id: msg.id, error: aError, result: aResult });
- }, appId, browsingTrafficOnly, serviceType, network, start, end, appManifestURL);
- }.bind(this));
- },
-
- clearInterfaceStats: function clearInterfaceStats(mm, msg) {
- let self = this;
- let network = msg.network;
-
- debug("clear stats for network " + network.id + " of type " + network.type);
-
- this.validateNetwork(network, function onValidateNetwork(aNetId) {
- if (!aNetId) {
- mm.sendAsyncMessage("NetworkStats:Clear:Return",
- { id: msg.id, error: "Invalid connectionType", result: null });
- return;
- }
-
- network = {network: network, networkId: aNetId};
- self.updateStats(aNetId, function onUpdate(aResult, aMessage) {
- if (!aResult) {
- mm.sendAsyncMessage("NetworkStats:Clear:Return",
- { id: msg.id, error: aMessage, result: null });
- return;
- }
-
- self._db.clearInterfaceStats(network, function onDBCleared(aError, aResult) {
- self._updateCurrentAlarm(aNetId);
- mm.sendAsyncMessage("NetworkStats:Clear:Return",
- { id: msg.id, error: aError, result: aResult });
- });
- });
- });
- },
-
- clearDB: function clearDB(mm, msg) {
- let self = this;
- this._db.getAvailableNetworks(function onGetNetworks(aError, aResult) {
- if (aError) {
- mm.sendAsyncMessage("NetworkStats:ClearAll:Return",
- { id: msg.id, error: aError, result: aResult });
- return;
- }
-
- let networks = aResult;
- networks.forEach(function(network, index) {
- networks[index] = {network: network, networkId: self.getNetworkId(network.id, network.type)};
- }, self);
-
- self.updateAllStats(function onUpdate(aResult, aMessage){
- if (!aResult) {
- mm.sendAsyncMessage("NetworkStats:ClearAll:Return",
- { id: msg.id, error: aMessage, result: null });
- return;
- }
-
- self._db.clearStats(networks, function onDBCleared(aError, aResult) {
- networks.forEach(function(network, index) {
- self._updateCurrentAlarm(network.networkId);
- }, self);
- mm.sendAsyncMessage("NetworkStats:ClearAll:Return",
- { id: msg.id, error: aError, result: aResult });
- });
- });
- });
- },
-
- updateAllStats: function updateAllStats(aCallback) {
- let elements = [];
- let lastElement = null;
- let callback = (function (success, message) {
- this.updateCachedStats(aCallback);
- }).bind(this);
-
- // For each connectionType create an object containning the type
- // and the 'queueIndex', the 'queueIndex' is an integer representing
- // the index of a connection type in the global queue array. So, if
- // the connection type is already in the queue it is not appended again,
- // else it is pushed in 'elements' array, which later will be pushed to
- // the queue array.
- for (let netId in this._networks) {
- if (this._networks[netId].status != NETWORK_STATUS_READY) {
- continue;
- }
-
- lastElement = { netId: netId,
- queueIndex: this.updateQueueIndex(netId) };
-
- if (lastElement.queueIndex == -1) {
- elements.push({ netId: lastElement.netId,
- callbacks: [],
- queueType: QUEUE_TYPE_UPDATE_STATS });
- }
- }
-
- if (!lastElement) {
- // No elements need to be updated, probably because status is different than
- // NETWORK_STATUS_READY.
- if (aCallback) {
- aCallback(true, "OK");
- }
- return;
- }
-
- if (elements.length > 0) {
- // If length of elements is greater than 0, callback is set to
- // the last element.
- elements[elements.length - 1].callbacks.push(callback);
- this.updateQueue = this.updateQueue.concat(elements);
- } else {
- // Else, it means that all connection types are already in the queue to
- // be updated, so callback for this request is added to
- // the element in the main queue with the index of the last 'lastElement'.
- // But before is checked that element is still in the queue because it can
- // be processed while generating 'elements' array.
- let element = this.updateQueue[lastElement.queueIndex];
- if (aCallback &&
- (!element || element.netId != lastElement.netId)) {
- aCallback();
- return;
- }
-
- this.updateQueue[lastElement.queueIndex].callbacks.push(callback);
- }
-
- // Call the function that process the elements of the queue.
- this.processQueue();
-
- if (DEBUG) {
- this.logAllRecords();
- }
- },
-
- updateStats: function updateStats(aNetId, aCallback) {
- // Check if the connection is in the main queue, push a new element
- // if it is not being processed or add a callback if it is.
- let index = this.updateQueueIndex(aNetId);
- if (index == -1) {
- this.updateQueue.push({ netId: aNetId,
- callbacks: [aCallback],
- queueType: QUEUE_TYPE_UPDATE_STATS });
- } else {
- this.updateQueue[index].callbacks.push(aCallback);
- return;
- }
-
- // Call the function that process the elements of the queue.
- this.processQueue();
- },
-
- /*
- * Find if a connection is in the main queue array and return its
- * index, if it is not in the array return -1.
- */
- updateQueueIndex: function updateQueueIndex(aNetId) {
- return this.updateQueue.map(function(e) { return e.netId; }).indexOf(aNetId);
- },
-
- /*
- * Function responsible of process all requests in the queue.
- */
- processQueue: function processQueue(aResult, aMessage) {
- // If aResult is not undefined, the caller of the function is the result
- // of processing an element, so remove that element and call the callbacks
- // it has.
- let self = this;
-
- if (aResult != undefined) {
- let item = this.updateQueue.shift();
- for (let callback of item.callbacks) {
- if (callback) {
- callback(aResult, aMessage);
- }
- }
- } else {
- // The caller is a function that has pushed new elements to the queue,
- // if isQueueRunning is false it means there is no processing currently
- // being done, so start.
- if (this.isQueueRunning) {
- return;
- } else {
- this.isQueueRunning = true;
- }
- }
-
- // Check length to determine if queue is empty and stop processing.
- if (this.updateQueue.length < 1) {
- this.isQueueRunning = false;
- return;
- }
-
- // Process the next item as soon as possible.
- setTimeout(function () {
- self.run(self.updateQueue[0]);
- }, 0);
- },
-
- run: function run(item) {
- switch (item.queueType) {
- case QUEUE_TYPE_UPDATE_STATS:
- this.update(item.netId, this.processQueue.bind(this));
- break;
- case QUEUE_TYPE_UPDATE_CACHE:
- this.updateCache(this.processQueue.bind(this));
- break;
- case QUEUE_TYPE_WRITE_CACHE:
- this.writeCache(item.stats, this.processQueue.bind(this));
- break;
- }
- },
-
- update: function update(aNetId, aCallback) {
- // Check if connection type is valid.
- if (!this._networks[aNetId]) {
- if (aCallback) {
- aCallback(false, "Invalid network " + aNetId);
- }
- return;
- }
-
- let interfaceName = this._networks[aNetId].interfaceName;
- debug("Update stats for " + interfaceName);
-
- // Request stats to NetworkService, which will get stats from netd, passing
- // 'networkStatsAvailable' as a callback.
- if (interfaceName) {
- networkService.getNetworkInterfaceStats(interfaceName,
- this.networkStatsAvailable.bind(this, aCallback, aNetId));
- return;
- }
-
- if (aCallback) {
- aCallback(true, "ok");
- }
- },
-
- /*
- * Callback of request stats. Store stats in database.
- */
- networkStatsAvailable: function networkStatsAvailable(aCallback, aNetId,
- aResult, aRxBytes,
- aTxBytes, aTimestamp) {
- if (!aResult) {
- if (aCallback) {
- aCallback(false, "Netd IPC error");
- }
- return;
- }
-
- let stats = { appId: 0,
- isInBrowser: false,
- serviceType: "",
- networkId: this._networks[aNetId].network.id,
- networkType: this._networks[aNetId].network.type,
- date: new Date(aTimestamp),
- rxBytes: aTxBytes,
- txBytes: aRxBytes,
- isAccumulative: true };
-
- debug("Update stats for: " + JSON.stringify(stats));
-
- this._db.saveStats(stats, function onSavedStats(aError, aResult) {
- if (aCallback) {
- if (aError) {
- aCallback(false, aError);
- return;
- }
-
- aCallback(true, "OK");
- }
- });
- },
-
- /*
- * Function responsible for receiving stats which are not from netd.
- */
- saveStats: function saveStats(aAppId, aIsInIsolatedMozBrowser, aServiceType,
- aNetworkInfo, aTimeStamp, aRxBytes, aTxBytes,
- aIsAccumulative, aCallback) {
- let netId = this.convertNetworkInfo(aNetworkInfo);
- if (!netId) {
- if (aCallback) {
- aCallback(false, "Invalid network type");
- }
- return;
- }
-
- // Check if |aConnectionType|, |aAppId| and |aServiceType| are valid.
- // There are two invalid cases for the combination of |aAppId| and
- // |aServiceType|:
- // a. Both |aAppId| is non-zero and |aServiceType| is non-empty.
- // b. Both |aAppId| is zero and |aServiceType| is empty.
- if (!this._networks[netId] || (aAppId && aServiceType) ||
- (!aAppId && !aServiceType)) {
- debug("Invalid network interface, appId or serviceType");
- return;
- }
-
- let stats = { appId: aAppId,
- isInBrowser: aIsInIsolatedMozBrowser,
- serviceType: aServiceType,
- networkId: this._networks[netId].network.id,
- networkType: this._networks[netId].network.type,
- date: new Date(aTimeStamp),
- rxBytes: aRxBytes,
- txBytes: aTxBytes,
- isAccumulative: aIsAccumulative };
-
- this.updateQueue.push({ stats: stats,
- callbacks: [aCallback],
- queueType: QUEUE_TYPE_WRITE_CACHE });
-
- this.processQueue();
- },
-
- /*
- *
- */
- writeCache: function writeCache(aStats, aCallback) {
- debug("saveStats: " + aStats.appId + " " + aStats.isInBrowser + " " +
- aStats.serviceType + " " + aStats.networkId + " " +
- aStats.networkType + " " + aStats.date + " " +
- aStats.rxBytes + " " + aStats.txBytes);
-
- // Generate an unique key from |appId|, |isInBrowser|, |serviceType| and
- // |netId|, which is used to retrieve data in |cachedStats|.
- let netId = this.getNetworkId(aStats.networkId, aStats.networkType);
- let key = aStats.appId + "" + aStats.isInBrowser + "" +
- aStats.serviceType + "" + netId;
-
- // |cachedStats| only keeps the data with the same date.
- // If the incoming date is different from |cachedStatsDate|,
- // both |cachedStats| and |cachedStatsDate| will get updated.
- let diff = (this._db.normalizeDate(aStats.date) -
- this._db.normalizeDate(this.cachedStatsDate)) /
- this._db.sampleRate;
- if (diff != 0) {
- this.updateCache(function onUpdated(success, message) {
- this.cachedStatsDate = aStats.date;
- this.cachedStats[key] = aStats;
-
- if (aCallback) {
- aCallback(true, "ok");
- }
- }.bind(this));
- return;
- }
-
- // Try to find the matched row in the cached by |appId| and |connectionType|.
- // If not found, save the incoming data into the cached.
- let cachedStats = this.cachedStats[key];
- if (!cachedStats) {
- this.cachedStats[key] = aStats;
- if (aCallback) {
- aCallback(true, "ok");
- }
- return;
- }
-
- // Find matched row, accumulate the traffic amount.
- cachedStats.rxBytes += aStats.rxBytes;
- cachedStats.txBytes += aStats.txBytes;
-
- // If new rxBytes or txBytes exceeds MAX_CACHED_TRAFFIC
- // the corresponding row will be saved to indexedDB.
- // Then, the row will be removed from the cached.
- if (cachedStats.rxBytes > MAX_CACHED_TRAFFIC ||
- cachedStats.txBytes > MAX_CACHED_TRAFFIC) {
- this._db.saveStats(cachedStats, function (error, result) {
- debug("Application stats inserted in indexedDB");
- if (aCallback) {
- aCallback(true, "ok");
- }
- });
- delete this.cachedStats[key];
- return;
- }
-
- if (aCallback) {
- aCallback(true, "ok");
- }
- },
-
- updateCachedStats: function updateCachedStats(aCallback) {
- this.updateQueue.push({ callbacks: [aCallback],
- queueType: QUEUE_TYPE_UPDATE_CACHE });
-
- this.processQueue();
- },
-
- updateCache: function updateCache(aCallback) {
- debug("updateCache: " + this.cachedStatsDate);
-
- let stats = Object.keys(this.cachedStats);
- if (stats.length == 0) {
- // |cachedStats| is empty, no need to update.
- if (aCallback) {
- aCallback(true, "no need to update");
- }
- return;
- }
-
- let index = 0;
- this._db.saveStats(this.cachedStats[stats[index]],
- function onSavedStats(error, result) {
- debug("Application stats inserted in indexedDB");
-
- // Clean up the |cachedStats| after updating.
- if (index == stats.length - 1) {
- this.cachedStats = Object.create(null);
-
- if (aCallback) {
- aCallback(true, "ok");
- }
- return;
- }
-
- // Update is not finished, keep updating.
- index += 1;
- this._db.saveStats(this.cachedStats[stats[index]],
- onSavedStats.bind(this, error, result));
- }.bind(this));
- },
-
- get maxCachedTraffic () {
- return MAX_CACHED_TRAFFIC;
- },
-
- logAllRecords: function logAllRecords() {
- this._db.logAllRecords(function onResult(aError, aResult) {
- if (aError) {
- debug("Error: " + aError);
- return;
- }
-
- debug("===== LOG =====");
- debug("There are " + aResult.length + " items");
- debug(JSON.stringify(aResult));
- });
- },
-
- getAlarms: function getAlarms(mm, msg) {
- let self = this;
- let network = msg.data.network;
- let manifestURL = msg.data.manifestURL;
-
- if (network) {
- this.validateNetwork(network, function onValidateNetwork(aNetId) {
- if (!aNetId) {
- mm.sendAsyncMessage("NetworkStats:GetAlarms:Return",
- { id: msg.id, error: "InvalidInterface", result: null });
- return;
- }
-
- self._getAlarms(mm, msg, aNetId, manifestURL);
- });
- return;
- }
-
- this._getAlarms(mm, msg, null, manifestURL);
- },
-
- _getAlarms: function _getAlarms(mm, msg, aNetId, aManifestURL) {
- let self = this;
- this._db.getAlarms(aNetId, aManifestURL, function onCompleted(error, result) {
- if (error) {
- mm.sendAsyncMessage("NetworkStats:GetAlarms:Return",
- { id: msg.id, error: error, result: result });
- return;
- }
-
- let alarms = []
- // NetworkStatsManager must return the network instead of the networkId.
- for (let i = 0; i < result.length; i++) {
- let alarm = result[i];
- alarms.push({ id: alarm.id,
- network: self._networks[alarm.networkId].network,
- threshold: alarm.absoluteThreshold,
- data: alarm.data });
- }
-
- mm.sendAsyncMessage("NetworkStats:GetAlarms:Return",
- { id: msg.id, error: null, result: alarms });
- });
- },
-
- removeAlarms: function removeAlarms(mm, msg) {
- let alarmId = msg.data.alarmId;
- let manifestURL = msg.data.manifestURL;
-
- let self = this;
- let callback = function onRemove(error, result) {
- if (error) {
- mm.sendAsyncMessage("NetworkStats:RemoveAlarms:Return",
- { id: msg.id, error: error, result: result });
- return;
- }
-
- for (let i in self._currentAlarms) {
- let currentAlarm = self._currentAlarms[i].alarm;
- if (currentAlarm && ((alarmId == currentAlarm.id) ||
- (alarmId == -1 && currentAlarm.manifestURL == manifestURL))) {
-
- self._updateCurrentAlarm(currentAlarm.networkId);
- }
- }
-
- mm.sendAsyncMessage("NetworkStats:RemoveAlarms:Return",
- { id: msg.id, error: error, result: true });
- };
-
- if (alarmId == -1) {
- this._db.removeAlarms(manifestURL, callback);
- } else {
- this._db.removeAlarm(alarmId, manifestURL, callback);
- }
- },
-
- /*
- * Function called from manager to set an alarm.
- */
- setAlarm: function setAlarm(mm, msg) {
- let options = msg.data;
- let network = options.network;
- let threshold = options.threshold;
-
- debug("Set alarm at " + threshold + " for " + JSON.stringify(network));
-
- if (threshold < 0) {
- mm.sendAsyncMessage("NetworkStats:SetAlarm:Return",
- { id: msg.id, error: "InvalidThresholdValue", result: null });
- return;
- }
-
- let self = this;
- this.validateNetwork(network, function onValidateNetwork(aNetId) {
- if (!aNetId) {
- mm.sendAsyncMessage("NetworkStats:SetAlarm:Return",
- { id: msg.id, error: "InvalidiConnectionType", result: null });
- return;
- }
-
- let newAlarm = {
- id: null,
- networkId: aNetId,
- absoluteThreshold: threshold,
- relativeThreshold: null,
- startTime: options.startTime,
- data: options.data,
- pageURL: options.pageURL,
- manifestURL: options.manifestURL
- };
-
- self._getAlarmQuota(newAlarm, function onUpdate(error, quota) {
- if (error) {
- mm.sendAsyncMessage("NetworkStats:SetAlarm:Return",
- { id: msg.id, error: error, result: null });
- return;
- }
-
- self._db.addAlarm(newAlarm, function addSuccessCb(error, newId) {
- if (error) {
- mm.sendAsyncMessage("NetworkStats:SetAlarm:Return",
- { id: msg.id, error: error, result: null });
- return;
- }
-
- newAlarm.id = newId;
- self._setAlarm(newAlarm, function onSet(error, success) {
- mm.sendAsyncMessage("NetworkStats:SetAlarm:Return",
- { id: msg.id, error: error, result: newId });
-
- if (error == "InvalidStateError") {
- self._fireAlarm(newAlarm);
- }
- });
- });
- });
- });
- },
-
- _setAlarm: function _setAlarm(aAlarm, aCallback) {
- let currentAlarm = this._currentAlarms[aAlarm.networkId];
- if ((Object.getOwnPropertyNames(currentAlarm).length !== 0 &&
- aAlarm.relativeThreshold > currentAlarm.alarm.relativeThreshold) ||
- this._networks[aAlarm.networkId].status != NETWORK_STATUS_READY) {
- aCallback(null, true);
- return;
- }
-
- let self = this;
-
- this._getAlarmQuota(aAlarm, function onUpdate(aError, aQuota) {
- if (aError) {
- aCallback(aError, null);
- return;
- }
-
- let callback = function onAlarmSet(aError) {
- if (aError) {
- debug("Set alarm error: " + aError);
- aCallback("netdError", null);
- return;
- }
-
- self._currentAlarms[aAlarm.networkId].alarm = aAlarm;
-
- aCallback(null, true);
- };
-
- debug("Set alarm " + JSON.stringify(aAlarm));
- let interfaceName = self._networks[aAlarm.networkId].interfaceName;
- if (interfaceName) {
- networkService.setNetworkInterfaceAlarm(interfaceName,
- aQuota,
- callback);
- return;
- }
-
- aCallback(null, true);
- });
- },
-
- _getAlarmQuota: function _getAlarmQuota(aAlarm, aCallback) {
- let self = this;
- this.updateStats(aAlarm.networkId, function onStatsUpdated(aResult, aMessage) {
- self._db.getCurrentStats(self._networks[aAlarm.networkId].network,
- aAlarm.startTime,
- function onStatsFound(error, result) {
- if (error) {
- debug("Error getting stats for " +
- JSON.stringify(self._networks[aAlarm.networkId]) + ": " + error);
- aCallback(error, result);
- return;
- }
-
- let quota = aAlarm.absoluteThreshold - result.rxBytes - result.txBytes;
-
- // Alarm set to a threshold lower than current rx/tx bytes.
- if (quota <= 0) {
- aCallback("InvalidStateError", null);
- return;
- }
-
- aAlarm.relativeThreshold = aAlarm.startTime
- ? result.rxTotalBytes + result.txTotalBytes + quota
- : aAlarm.absoluteThreshold;
-
- aCallback(null, quota);
- });
- });
- },
-
- _fireAlarm: function _fireAlarm(aAlarm) {
- debug("Fire alarm");
-
- let self = this;
- this._db.removeAlarm(aAlarm.id, null, function onRemove(aError, aResult){
- if (!aError && !aResult) {
- return;
- }
-
- self._fireSystemMessage(aAlarm);
- self._updateCurrentAlarm(aAlarm.networkId);
- });
- },
-
- _updateCurrentAlarm: function _updateCurrentAlarm(aNetworkId) {
- this._currentAlarms[aNetworkId] = Object.create(null);
-
- let self = this;
- this._db.getFirstAlarm(aNetworkId, function onGet(error, result){
- if (error) {
- debug("Error getting the first alarm");
- return;
- }
-
- if (!result) {
- let interfaceName = self._networks[aNetworkId].interfaceName;
- networkService.setNetworkInterfaceAlarm(interfaceName, -1,
- function onComplete(){});
- return;
- }
-
- self._setAlarm(result, function onSet(error, success){
- if (error == "InvalidStateError") {
- self._fireAlarm(result);
- return;
- }
- });
- });
- },
-
- _fireSystemMessage: function _fireSystemMessage(aAlarm) {
- debug("Fire system message: " + JSON.stringify(aAlarm));
-
- let manifestURI = Services.io.newURI(aAlarm.manifestURL, null, null);
- let pageURI = Services.io.newURI(aAlarm.pageURL, null, null);
-
- let alarm = { "id": aAlarm.id,
- "threshold": aAlarm.absoluteThreshold,
- "data": aAlarm.data };
- messenger.sendMessage("networkstats-alarm", alarm, pageURI, manifestURI);
- }
-};
-
-NetworkStatsService.init();
diff --git a/dom/network/NetworkStatsServiceProxy.js b/dom/network/NetworkStatsServiceProxy.js
deleted file mode 100644
index f3df4344d..000000000
--- a/dom/network/NetworkStatsServiceProxy.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const DEBUG = false;
-function debug(s) { dump("-*- NetworkStatsServiceProxy: " + s + "\n"); }
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-this.EXPORTED_SYMBOLS = ["NetworkStatsServiceProxy"];
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/NetworkStatsService.jsm");
-
-const NETWORKSTATSSERVICEPROXY_CONTRACTID = "@mozilla.org/networkstatsServiceProxy;1";
-const NETWORKSTATSSERVICEPROXY_CID = Components.ID("98fd8f69-784e-4626-aa59-56d6436a3c24");
-const nsINetworkStatsServiceProxy = Ci.nsINetworkStatsServiceProxy;
-
-function NetworkStatsServiceProxy() {
- if (DEBUG) {
- debug("Proxy started");
- }
-}
-
-NetworkStatsServiceProxy.prototype = {
- /*
- * Function called in the protocol layer (HTTP, FTP, WebSocket ...etc)
- * to pass the per-app stats to NetworkStatsService.
- */
- saveAppStats: function saveAppStats(aAppId, aIsInIsolatedMozBrowser, aNetworkInfo, aTimeStamp,
- aRxBytes, aTxBytes, aIsAccumulative,
- aCallback) {
- if (!aNetworkInfo) {
- if (DEBUG) {
- debug("|aNetworkInfo| is not specified. Failed to save stats. Returning.");
- }
- return;
- }
-
- if (DEBUG) {
- debug("saveAppStats: " + aAppId + " " + aIsInIsolatedMozBrowser + " " +
- aNetworkInfo.type + " " + aTimeStamp + " " +
- aRxBytes + " " + aTxBytes + " " + aIsAccumulative);
- }
-
- if (aCallback) {
- aCallback = aCallback.notify;
- }
-
- NetworkStatsService.saveStats(aAppId, aIsInIsolatedMozBrowser, "", aNetworkInfo,
- aTimeStamp, aRxBytes, aTxBytes,
- aIsAccumulative, aCallback);
- },
-
- /*
- * Function called in the points of different system services
- * to pass the per-service stats to NetworkStatsService.
- */
- saveServiceStats: function saveServiceStats(aServiceType, aNetworkInfo,
- aTimeStamp, aRxBytes, aTxBytes,
- aIsAccumulative, aCallback) {
- if (!aNetworkInfo) {
- if (DEBUG) {
- debug("|aNetworkInfo| is not specified. Failed to save stats. Returning.");
- }
- return;
- }
-
- if (DEBUG) {
- debug("saveServiceStats: " + aServiceType + " " + aNetworkInfo.type + " " +
- aTimeStamp + " " + aRxBytes + " " + aTxBytes + " " +
- aIsAccumulative);
- }
-
- if (aCallback) {
- aCallback = aCallback.notify;
- }
-
- NetworkStatsService.saveStats(0, false, aServiceType , aNetworkInfo, aTimeStamp,
- aRxBytes, aTxBytes, aIsAccumulative,
- aCallback);
- },
-
- classID : NETWORKSTATSSERVICEPROXY_CID,
- QueryInterface : XPCOMUtils.generateQI([nsINetworkStatsServiceProxy]),
-}
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NetworkStatsServiceProxy]);
diff --git a/dom/network/NetworkStatsServiceProxy.manifest b/dom/network/NetworkStatsServiceProxy.manifest
deleted file mode 100644
index 24f09f088..000000000
--- a/dom/network/NetworkStatsServiceProxy.manifest
+++ /dev/null
@@ -1,2 +0,0 @@
-component {98fd8f69-784e-4626-aa59-56d6436a3c24} NetworkStatsServiceProxy.js
-contract @mozilla.org/networkstatsServiceProxy;1 {98fd8f69-784e-4626-aa59-56d6436a3c24}
diff --git a/dom/network/TCPSocket.cpp b/dom/network/TCPSocket.cpp
index 4eb2f72f6..38827a9ac 100644
--- a/dom/network/TCPSocket.cpp
+++ b/dom/network/TCPSocket.cpp
@@ -33,11 +33,6 @@
#include "nsStringStream.h"
#include "secerr.h"
#include "sslerr.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsINetworkStatsServiceProxy.h"
-#include "nsINetworkManager.h"
-#include "nsINetworkInterface.h"
-#endif
#define BUFFER_SIZE 65536
#define NETWORK_STATS_THRESHOLD 65536
@@ -163,12 +158,6 @@ TCPSocket::TCPSocket(nsIGlobalObject* aGlobal, const nsAString& aHost, uint16_t
, mTrackingNumber(0)
, mWaitingForStartTLS(false)
, mObserversActive(false)
-#ifdef MOZ_WIDGET_GONK
- , mTxBytes(0)
- , mRxBytes(0)
- , mAppId(nsIScriptSecurityManager::UNKNOWN_APP_ID)
- , mInIsolatedMozBrowser(false)
-#endif
{
if (aGlobal) {
nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(aGlobal);
@@ -323,13 +312,6 @@ TCPSocket::InitWithTransport(nsISocketTransport* aTransport)
mTransport->GetPort(&port);
mPort = port;
-#ifdef MOZ_WIDGET_GONK
- nsCOMPtr<nsINetworkManager> networkManager = do_GetService("@mozilla.org/network/manager;1");
- if (networkManager) {
- networkManager->GetActiveNetworkInfo(getter_AddRefs(mActiveNetworkInfo));
- }
-#endif
-
return NS_OK;
}
@@ -651,12 +633,6 @@ TCPSocket::Resume(mozilla::ErrorResult& aRv)
nsresult
TCPSocket::MaybeReportErrorAndCloseIfOpen(nsresult status) {
-#ifdef MOZ_WIDGET_GONK
- // Save network statistics once the connection is closed.
- // For now this function is Gonk-specific.
- SaveNetworkStats(true);
-#endif
-
// If we're closed, we've already reported the error or just don't need to
// report the error.
if (mReadyState == TCPReadyState::Closed) {
@@ -941,12 +917,6 @@ TCPSocket::Send(nsIInputStream* aStream, uint32_t aByteLength)
EnsureCopying();
-#ifdef MOZ_WIDGET_GONK
- // Collect transmitted amount for network statistics.
- mTxBytes += aByteLength;
- SaveNetworkStats(false);
-#endif
-
return !bufferFull;
}
@@ -1069,12 +1039,6 @@ NS_IMETHODIMP
TCPSocket::OnDataAvailable(nsIRequest* aRequest, nsISupports* aContext, nsIInputStream* aStream,
uint64_t aOffset, uint32_t aCount)
{
-#ifdef MOZ_WIDGET_GONK
- // Collect received amount for network statistics.
- mRxBytes += aCount;
- SaveNetworkStats(false);
-#endif
-
if (mUseArrayBuffers) {
nsTArray<uint8_t> buffer;
buffer.SetCapacity(aCount);
@@ -1160,10 +1124,7 @@ TCPSocket::SetSocketBridgeParent(TCPSocketParent* aBridgeParent)
void
TCPSocket::SetAppIdAndBrowser(uint32_t aAppId, bool aInIsolatedMozBrowser)
{
-#ifdef MOZ_WIDGET_GONK
- mAppId = aAppId;
- mInIsolatedMozBrowser = aInIsolatedMozBrowser;
-#endif
+ /*** STUB ***/
}
NS_IMETHODIMP
@@ -1190,37 +1151,6 @@ TCPSocket::UpdateBufferedAmount(uint32_t aBufferedAmount, uint32_t aTrackingNumb
return NS_OK;
}
-#ifdef MOZ_WIDGET_GONK
-void
-TCPSocket::SaveNetworkStats(bool aEnforce)
-{
- if (!mTxBytes && !mRxBytes) {
- // There is no traffic at all. No need to save statistics.
- return;
- }
-
- // If "enforce" is false, the traffic amount is saved to NetworkStatsServiceProxy
- // only when the total amount exceeds the predefined threshold value.
- // The purpose is to avoid too much overhead for collecting statistics.
- uint32_t totalBytes = mTxBytes + mRxBytes;
- if (!aEnforce && totalBytes < NETWORK_STATS_THRESHOLD) {
- return;
- }
-
- nsCOMPtr<nsINetworkStatsServiceProxy> nssProxy =
- do_GetService("@mozilla.org/networkstatsServiceProxy;1");
- if (!nssProxy) {
- return;
- }
-
- nssProxy->SaveAppStats(mAppId, mInIsolatedMozBrowser, mActiveNetworkInfo,
- PR_Now(), mRxBytes, mTxBytes, false, nullptr);
-
- // Reset the counters once the statistics is saved to NetworkStatsServiceProxy.
- mTxBytes = mRxBytes = 0;
-}
-#endif
-
NS_IMETHODIMP
TCPSocket::Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData)
{
diff --git a/dom/network/TCPSocket.h b/dom/network/TCPSocket.h
index e98c03ca5..4ad425b9e 100644
--- a/dom/network/TCPSocket.h
+++ b/dom/network/TCPSocket.h
@@ -179,10 +179,6 @@ private:
void ActivateTLS();
// Dispatch an error event if necessary, then dispatch a "close" event.
nsresult MaybeReportErrorAndCloseIfOpen(nsresult status);
-#ifdef MOZ_WIDGET_GONK
- // Store and reset any saved network stats for this socket.
- void SaveNetworkStats(bool aEnforce);
-#endif
// Helper for FireDataStringEvent/FireDataArrayEvent.
nsresult FireDataEvent(JSContext* aCx, const nsAString& aType,
@@ -246,19 +242,6 @@ private:
nsTArray<nsCOMPtr<nsIInputStream>> mPendingDataWhileCopierActive;
bool mObserversActive;
-
-#ifdef MOZ_WIDGET_GONK
- // Number of bytes sent.
- uint32_t mTxBytes;
- // Number of bytes received.
- uint32_t mRxBytes;
- // The app that owns this socket.
- uint32_t mAppId;
- // Was this socket created inside of an isolated browser frame?
- bool mInIsolatedMozBrowser;
- // The name of the active network used by this socket.
- nsCOMPtr<nsINetworkInfo> mActiveNetworkInfo;
-#endif
};
} // namespace dom
diff --git a/dom/network/interfaces/moz.build b/dom/network/interfaces/moz.build
index add687542..ad2e56bd6 100644
--- a/dom/network/interfaces/moz.build
+++ b/dom/network/interfaces/moz.build
@@ -10,10 +10,4 @@ XPIDL_SOURCES += [
'nsIUDPSocketChild.idl',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- XPIDL_SOURCES += [
- 'nsIEthernetManager.idl',
- 'nsINetworkStatsServiceProxy.idl',
- ]
-
XPIDL_MODULE = 'dom_network'
diff --git a/dom/network/interfaces/nsIEthernetManager.idl b/dom/network/interfaces/nsIEthernetManager.idl
deleted file mode 100644
index 2b92dc88f..000000000
--- a/dom/network/interfaces/nsIEthernetManager.idl
+++ /dev/null
@@ -1,137 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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, function, uuid(2a3ad56c-edc0-439f-8aae-900b331ddf49)]
-interface nsIEthernetManagerCallback : nsISupports
-{
- /**
- * Callback function used to report the success of different operations.
- *
- * @param success
- * Boolean value indicates the success of an operation.
- * @prarm message
- * Message reported in the end of operation.
- */
- void notify(in boolean success, in DOMString message);
-};
-
-[scriptable, function, uuid(1746e7dd-92d4-43fa-8ef4-bc13d0b60353)]
-interface nsIEthernetManagerScanCallback : nsISupports
-{
- /**
- * Callback function used to report the result of scan function.
- *
- * @param list
- * List of available ethernet interfaces.
- */
- void notify(in jsval list);
-};
-
-/**
- * An internal idl provides control to ethernet interfaces.
- */
-[scriptable, uuid(81750c87-bb3b-4724-b955-834eafa53fd1)]
-interface nsIEthernetManager : nsISupports
-{
- /**
- * List of exisiting interface name.
- */
- readonly attribute jsval interfaceList;
-
- /**
- * Scan available ethernet interfaces on device.
- *
- * @param callback
- * Callback function.
- */
- void scan(in nsIEthernetManagerScanCallback callback);
-
- /**
- * Add a new interface to the interface list.
- *
- * @param ifname
- * Interface name. Should be the form of "eth*".
- * @param callback
- * Callback function.
- */
- void addInterface(in DOMString ifname,
- in nsIEthernetManagerCallback callback);
-
- /**
- * Remove an existing interface from the interface list.
- *
- * @param ifname
- * Interface name.
- * @param Callback
- * Callback function.
- */
- void removeInterface(in DOMString ifname,
- in nsIEthernetManagerCallback callback);
-
- /**
- * Update a conifg of an existing interface in the interface list.
- *
- * @param ifname
- * Interface name.
- * @param config
- * .ip: IP address.
- * .prefixLength: Mask length.
- * .gateway: Gateway.
- * .dnses: DNS addresses.
- * .httpProxyHost: HTTP proxy host.
- * .httpProxyPort: HTTP proxy port.
- * .ipMode: IP mode, can be 'dhcp' or 'static'.
- * @param callback
- * Callback function.
- */
- void updateInterfaceConfig(in DOMString ifname,
- in jsval config,
- in nsIEthernetManagerCallback callback);
-
- /**
- * Enable networking of an existing interface in the interface list.
- *
- * @param ifname
- * Interface name.
- * @param callback
- * Callback function.
- */
- void enable(in DOMString ifname,
- in nsIEthernetManagerCallback callback);
-
- /**
- * Disable networking of an existing interface in the interface list.
- *
- * @param ifname
- * Interface name.
- * @param callback
- * Callback function.
- */
- void disable(in DOMString ifname,
- in nsIEthernetManagerCallback callback);
-
- /**
- * Make an existing interface connect to network.
- *
- * @param ifname
- * Interface name.
- * @param callback
- * Callback function.
- */
- void connect(in DOMString ifname,
- in nsIEthernetManagerCallback callback);
-
- /**
- * Disconnect a connected interface in the interface list.
- *
- * @param ifname
- * Interface name.
- * @param callback
- * Callback function.
- */
- void disconnect(in DOMString ifname,
- in nsIEthernetManagerCallback callback);
-};
diff --git a/dom/network/interfaces/nsINetworkStatsServiceProxy.idl b/dom/network/interfaces/nsINetworkStatsServiceProxy.idl
deleted file mode 100644
index cd6765c68..000000000
--- a/dom/network/interfaces/nsINetworkStatsServiceProxy.idl
+++ /dev/null
@@ -1,64 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
-* License, v. 2.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"
-
-interface nsINetworkInfo;
-
-[scriptable, function, uuid(5f821529-1d80-4ab5-a933-4e1b3585b6bc)]
-interface nsINetworkStatsServiceProxyCallback : nsISupports
-{
- /*
- * @param aResult callback result with boolean value
- * @param aMessage message
- */
- void notify(in boolean aResult, in jsval aMessage);
-};
-
-[scriptable, uuid(f4f3e901-e102-499d-9d37-dc9951f52df7)]
-interface nsINetworkStatsServiceProxy : nsISupports
-{
- /*
- * An interface used to record per-app traffic data.
- * @param aAppId app id
- * @param aIsInIsolatedMozBrowser
- * true if the frame is an isolated mozbrowser element. <iframe
- * mozbrowser mozapp> and <xul:browser> are not considered to be
- * mozbrowser elements. <iframe mozbrowser noisolation> does not count
- * as isolated since isolation is disabled. Isolation can only be
- * disabled if the containing document is chrome.
- * @param aNetworkInterface network
- * @param aTimeStamp time stamp
- * @param aRxBytes received data amount
- * @param aTxBytes transmitted data amount
- * @param aIsAccumulative is stats accumulative
- * @param aCallback an optional callback
- */
- void saveAppStats(in unsigned long aAppId,
- in boolean aIsInIsolatedMozBrowser,
- in nsINetworkInfo aNetworkInfo,
- in unsigned long long aTimeStamp,
- in unsigned long long aRxBytes,
- in unsigned long long aTxBytes,
- in boolean aIsAccumulative,
- [optional] in nsINetworkStatsServiceProxyCallback aCallback);
-
- /*
- * An interface used to record per-system service traffic data.
- * @param aServiceType system service type
- * @param aNetworkInterface network
- * @param aTimeStamp time stamp
- * @param aRxBytes received data amount
- * @param aTxBytes transmitted data amount
- * @param aIsAccumulative is stats accumulative
- * @param aCallback an optional callback
- */
- void saveServiceStats(in string aServiceType,
- in nsINetworkInfo aNetworkInfo,
- in unsigned long long aTimeStamp,
- in unsigned long long aRxBytes,
- in unsigned long long aTxBytes,
- in boolean aIsAccumulative,
- [optional] in nsINetworkStatsServiceProxyCallback aCallback);
-};
diff --git a/dom/network/moz.build b/dom/network/moz.build
index 63e5c75c0..ffb90d116 100644
--- a/dom/network/moz.build
+++ b/dom/network/moz.build
@@ -40,28 +40,6 @@ UNIFIED_SOURCES += [
'UDPSocketParent.cpp',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- EXTRA_JS_MODULES += [
- 'NetworkStatsDB.jsm',
- 'NetworkStatsService.jsm',
- ]
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- EXTRA_COMPONENTS += [
- 'EthernetManager.js',
- 'EthernetManager.manifest',
- 'NetworkStatsManager.js',
- 'NetworkStatsManager.manifest',
- 'NetworkStatsServiceProxy.js',
- 'NetworkStatsServiceProxy.manifest',
- ]
- EXPORTS.mozilla.dom.network += [
- 'NetUtils.h',
- ]
- UNIFIED_SOURCES += [
- 'NetUtils.cpp',
- ]
-
IPDL_SOURCES += [
'PTCPServerSocket.ipdl',
'PTCPSocket.ipdl',
diff --git a/dom/notification/DesktopNotification.h b/dom/notification/DesktopNotification.h
index e1cb2efbc..5fd5e4c03 100644
--- a/dom/notification/DesktopNotification.h
+++ b/dom/notification/DesktopNotification.h
@@ -159,10 +159,6 @@ class AlertServiceObserver: public nsIObserver
// forward to parent
if (mNotification) {
-#ifdef MOZ_B2G
- if (NS_FAILED(mNotification->CheckInnerWindowCorrectness()))
- return NS_ERROR_NOT_AVAILABLE;
-#endif
mNotification->HandleAlertServiceNotification(aTopic);
}
return NS_OK;
diff --git a/dom/performance/Performance.cpp b/dom/performance/Performance.cpp
index 8dc239b05..a1e28bc55 100755
--- a/dom/performance/Performance.cpp
+++ b/dom/performance/Performance.cpp
@@ -13,23 +13,21 @@
#include "PerformanceMeasure.h"
#include "PerformanceObserver.h"
#include "PerformanceResourceTiming.h"
+#include "PerformanceService.h"
#include "PerformanceWorker.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/dom/PerformanceBinding.h"
#include "mozilla/dom/PerformanceEntryEvent.h"
#include "mozilla/dom/PerformanceNavigationBinding.h"
#include "mozilla/dom/PerformanceObserverBinding.h"
+#include "mozilla/dom/PerformanceNavigationTiming.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Preferences.h"
#include "mozilla/TimerClamping.h"
#include "WorkerPrivate.h"
#include "WorkerRunnable.h"
-#ifdef MOZ_WIDGET_GONK
-#define PERFLOG(msg, ...) __android_log_print(ANDROID_LOG_INFO, "PerformanceTiming", msg, ##__VA_ARGS__)
-#else
#define PERFLOG(msg, ...) printf_stderr(msg, ##__VA_ARGS__)
-#endif
namespace mozilla {
namespace dom {
@@ -38,27 +36,6 @@ using namespace workers;
namespace {
-// Helper classes
-class MOZ_STACK_CLASS PerformanceEntryComparator final
-{
-public:
- bool Equals(const PerformanceEntry* aElem1,
- const PerformanceEntry* aElem2) const
- {
- MOZ_ASSERT(aElem1 && aElem2,
- "Trying to compare null performance entries");
- return aElem1->StartTime() == aElem2->StartTime();
- }
-
- bool LessThan(const PerformanceEntry* aElem1,
- const PerformanceEntry* aElem2) const
- {
- MOZ_ASSERT(aElem1 && aElem2,
- "Trying to compare null performance entries");
- return aElem1->StartTime() < aElem2->StartTime();
- }
-};
-
class PrefEnabledRunnable final
: public WorkerCheckAPIExposureOnMainThreadRunnable
{
@@ -103,14 +80,12 @@ NS_IMPL_RELEASE_INHERITED(Performance, DOMEventTargetHelper)
/* static */ already_AddRefed<Performance>
Performance::CreateForMainThread(nsPIDOMWindowInner* aWindow,
nsDOMNavigationTiming* aDOMTiming,
- nsITimedChannel* aChannel,
- Performance* aParentPerformance)
+ nsITimedChannel* aChannel)
{
MOZ_ASSERT(NS_IsMainThread());
RefPtr<Performance> performance =
- new PerformanceMainThread(aWindow, aDOMTiming, aChannel,
- aParentPerformance);
+ new PerformanceMainThread(aWindow, aDOMTiming, aChannel);
return performance.forget();
}
@@ -142,6 +117,24 @@ Performance::Performance(nsPIDOMWindowInner* aWindow)
Performance::~Performance()
{}
+DOMHighResTimeStamp
+Performance::Now() const
+{
+ TimeDuration duration = TimeStamp::Now() - CreationTimeStamp();
+ return RoundTime(duration.ToMilliseconds());
+}
+
+DOMHighResTimeStamp
+Performance::TimeOrigin()
+{
+ if (!mPerformanceService) {
+ mPerformanceService = PerformanceService::GetOrCreate();
+ }
+
+ MOZ_ASSERT(mPerformanceService);
+ return mPerformanceService->TimeOrigin(CreationTimeStamp());
+}
+
JSObject*
Performance::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
@@ -266,7 +259,7 @@ Performance::ClearMarks(const Optional<nsAString>& aName)
DOMHighResTimeStamp
Performance::ResolveTimestampFromName(const nsAString& aName,
- ErrorResult& aRv)
+ ErrorResult& aRv)
{
AutoTArray<RefPtr<PerformanceEntry>, 1> arr;
DOMHighResTimeStamp ts;
diff --git a/dom/performance/Performance.h b/dom/performance/Performance.h
index bc70589a5..4debecc90 100644
--- a/dom/performance/Performance.h
+++ b/dom/performance/Performance.h
@@ -24,6 +24,7 @@ namespace dom {
class PerformanceEntry;
class PerformanceNavigation;
class PerformanceObserver;
+class PerformanceService;
class PerformanceTiming;
namespace workers {
@@ -45,8 +46,7 @@ public:
static already_AddRefed<Performance>
CreateForMainThread(nsPIDOMWindowInner* aWindow,
nsDOMNavigationTiming* aDOMTiming,
- nsITimedChannel* aChannel,
- Performance* aParentPerformance);
+ nsITimedChannel* aChannel);
static already_AddRefed<Performance>
CreateForWorker(workers::WorkerPrivate* aWorkerPrivate);
@@ -54,21 +54,23 @@ public:
JSObject* WrapObject(JSContext *cx,
JS::Handle<JSObject*> aGivenProto) override;
- void GetEntries(nsTArray<RefPtr<PerformanceEntry>>& aRetval);
+ virtual void GetEntries(nsTArray<RefPtr<PerformanceEntry>>& aRetval);
- void GetEntriesByType(const nsAString& aEntryType,
- nsTArray<RefPtr<PerformanceEntry>>& aRetval);
+ virtual void GetEntriesByType(const nsAString& aEntryType,
+ nsTArray<RefPtr<PerformanceEntry>>& aRetval);
- void GetEntriesByName(const nsAString& aName,
- const Optional<nsAString>& aEntryType,
- nsTArray<RefPtr<PerformanceEntry>>& aRetval);
+ virtual void GetEntriesByName(const nsAString& aName,
+ const Optional<nsAString>& aEntryType,
+ nsTArray<RefPtr<PerformanceEntry>>& aRetval);
virtual void AddEntry(nsIHttpChannel* channel,
nsITimedChannel* timedChannel) = 0;
void ClearResourceTimings();
- virtual DOMHighResTimeStamp Now() const = 0;
+ DOMHighResTimeStamp Now() const;
+
+ DOMHighResTimeStamp TimeOrigin();
void Mark(const nsAString& aName, ErrorResult& aRv);
@@ -101,8 +103,6 @@ public:
virtual nsITimedChannel* GetChannel() const = 0;
- virtual Performance* GetParentPerformance() const = 0;
-
protected:
Performance();
explicit Performance(nsPIDOMWindowInner* aWindow);
@@ -126,10 +126,16 @@ protected:
virtual DOMHighResTimeStamp CreationTime() const = 0;
- virtual bool IsPerformanceTimingAttribute(const nsAString& aName) = 0;
+ virtual bool IsPerformanceTimingAttribute(const nsAString& aName)
+ {
+ return false;
+ }
virtual DOMHighResTimeStamp
- GetPerformanceTimingFromString(const nsAString& aTimingName) = 0;
+ GetPerformanceTimingFromString(const nsAString& aTimingName)
+ {
+ return 0;
+ }
bool IsResourceEntryLimitReached() const
{
@@ -147,13 +153,15 @@ protected:
nsTObserverArray<PerformanceObserver*> mObservers;
-private:
+protected:
nsTArray<RefPtr<PerformanceEntry>> mUserEntries;
nsTArray<RefPtr<PerformanceEntry>> mResourceEntries;
uint64_t mResourceTimingBufferSize;
static const uint64_t kDefaultResourceTimingBufferSize = 150;
bool mPendingNotificationObserversTask;
+
+ RefPtr<PerformanceService> mPerformanceService;
};
} // namespace dom
diff --git a/dom/performance/PerformanceEntry.h b/dom/performance/PerformanceEntry.h
index bc4f84f1c..0af9f669e 100644
--- a/dom/performance/PerformanceEntry.h
+++ b/dom/performance/PerformanceEntry.h
@@ -90,6 +90,27 @@ protected:
nsString mEntryType;
};
+// Helper classes
+class MOZ_STACK_CLASS PerformanceEntryComparator final
+{
+public:
+ bool Equals(const PerformanceEntry* aElem1,
+ const PerformanceEntry* aElem2) const
+ {
+ MOZ_ASSERT(aElem1 && aElem2,
+ "Trying to compare null performance entries");
+ return aElem1->StartTime() == aElem2->StartTime();
+ }
+
+ bool LessThan(const PerformanceEntry* aElem1,
+ const PerformanceEntry* aElem2) const
+ {
+ MOZ_ASSERT(aElem1 && aElem2,
+ "Trying to compare null performance entries");
+ return aElem1->StartTime() < aElem2->StartTime();
+ }
+};
+
} // namespace dom
} // namespace mozilla
diff --git a/dom/performance/PerformanceMainThread.cpp b/dom/performance/PerformanceMainThread.cpp
index 86d42c5f8..64c06d3ea 100644
--- a/dom/performance/PerformanceMainThread.cpp
+++ b/dom/performance/PerformanceMainThread.cpp
@@ -6,6 +6,7 @@
#include "PerformanceMainThread.h"
#include "PerformanceNavigation.h"
+#include "nsICacheInfoChannel.h"
namespace mozilla {
namespace dom {
@@ -16,7 +17,7 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(PerformanceMainThread,
Performance)
NS_IMPL_CYCLE_COLLECTION_UNLINK(mTiming,
mNavigation,
- mParentPerformance)
+ mDocEntry)
tmp->mMozMemory = nullptr;
mozilla::DropJSObjects(this);
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
@@ -25,7 +26,7 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(PerformanceMainThread,
Performance)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTiming,
mNavigation,
- mParentPerformance)
+ mDocEntry)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
@@ -45,12 +46,10 @@ NS_INTERFACE_MAP_END_INHERITING(Performance)
PerformanceMainThread::PerformanceMainThread(nsPIDOMWindowInner* aWindow,
nsDOMNavigationTiming* aDOMTiming,
- nsITimedChannel* aChannel,
- Performance* aParentPerformance)
+ nsITimedChannel* aChannel)
: Performance(aWindow)
, mDOMTiming(aDOMTiming)
, mChannel(aChannel)
- , mParentPerformance(aParentPerformance)
{
MOZ_ASSERT(aWindow, "Parent window object should be provided");
}
@@ -78,7 +77,7 @@ PerformanceTiming*
PerformanceMainThread::Timing()
{
if (!mTiming) {
- // For navigation timing, the third argument (an nsIHtttpChannel) is null
+ // For navigation timing, the third argument (an nsIHttpChannel) is null
// since the cross-domain redirect were already checked. The last argument
// (zero time) for performance.timing is the navigation start value.
mTiming = new PerformanceTiming(this, mChannel, nullptr,
@@ -108,12 +107,6 @@ PerformanceMainThread::Navigation()
return mNavigation;
}
-DOMHighResTimeStamp
-PerformanceMainThread::Now() const
-{
- return RoundTime(GetDOMTiming()->TimeStampToDOMHighRes(TimeStamp::Now()));
-}
-
/**
* An entry should be added only after the resource is loaded.
* This method is not thread safe and can only be called on the main thread.
@@ -161,27 +154,7 @@ PerformanceMainThread::AddEntry(nsIHttpChannel* channel,
// The PerformanceResourceTiming object will use the PerformanceTiming
// object to get all the required timings.
RefPtr<PerformanceResourceTiming> performanceEntry =
- new PerformanceResourceTiming(performanceTiming, this, entryName);
-
- nsAutoCString protocol;
- channel->GetProtocolVersion(protocol);
- performanceEntry->SetNextHopProtocol(NS_ConvertUTF8toUTF16(protocol));
-
- uint64_t encodedBodySize = 0;
- channel->GetEncodedBodySize(&encodedBodySize);
- performanceEntry->SetEncodedBodySize(encodedBodySize);
-
- uint64_t transferSize = 0;
- channel->GetTransferSize(&transferSize);
- performanceEntry->SetTransferSize(transferSize);
-
- uint64_t decodedBodySize = 0;
- channel->GetDecodedBodySize(&decodedBodySize);
- if (decodedBodySize == 0) {
- decodedBodySize = encodedBodySize;
- }
- performanceEntry->SetDecodedBodySize(decodedBodySize);
-
+ new PerformanceResourceTiming(performanceTiming, this, entryName, channel);
// If the initiator type had no valid value, then set it to the default
// ("other") value.
if (initiatorType.IsEmpty()) {
@@ -335,5 +308,65 @@ PerformanceMainThread::CreationTime() const
return GetDOMTiming()->GetNavigationStart();
}
+void
+PerformanceMainThread::EnsureDocEntry()
+{
+ if (!mDocEntry && nsContentUtils::IsPerformanceNavigationTimingEnabled()) {
+ nsCOMPtr<nsIHttpChannel> httpChannel = do_QueryInterface(mChannel);
+ RefPtr<PerformanceTiming> timing =
+ new PerformanceTiming(this, mChannel, nullptr, 0);
+ mDocEntry = new PerformanceNavigationTiming(timing, this,
+ httpChannel);
+ }
+}
+
+
+void
+PerformanceMainThread::GetEntries(nsTArray<RefPtr<PerformanceEntry>>& aRetval)
+{
+ aRetval = mResourceEntries;
+ aRetval.AppendElements(mUserEntries);
+
+ EnsureDocEntry();
+ if (mDocEntry) {
+ aRetval.AppendElement(mDocEntry);
+ }
+
+ aRetval.Sort(PerformanceEntryComparator());
+}
+
+void
+PerformanceMainThread::GetEntriesByType(const nsAString& aEntryType,
+ nsTArray<RefPtr<PerformanceEntry>>& aRetval)
+{
+ if (aEntryType.EqualsLiteral("navigation")) {
+ aRetval.Clear();
+ EnsureDocEntry();
+ if (mDocEntry) {
+ aRetval.AppendElement(mDocEntry);
+ }
+ return;
+ }
+
+ Performance::GetEntriesByType(aEntryType, aRetval);
+}
+
+void
+PerformanceMainThread::GetEntriesByName(const nsAString& aName,
+ const Optional<nsAString>& aEntryType,
+ nsTArray<RefPtr<PerformanceEntry>>& aRetval)
+{
+ if (aName.EqualsLiteral("document")) {
+ aRetval.Clear();
+ EnsureDocEntry();
+ if (mDocEntry) {
+ aRetval.AppendElement(mDocEntry);
+ }
+ return;
+ }
+
+ Performance::GetEntriesByName(aName, aEntryType, aRetval);
+}
+
} // dom namespace
} // mozilla namespace
diff --git a/dom/performance/PerformanceMainThread.h b/dom/performance/PerformanceMainThread.h
index 84773f29b..9f0e185fc 100644
--- a/dom/performance/PerformanceMainThread.h
+++ b/dom/performance/PerformanceMainThread.h
@@ -17,16 +17,12 @@ class PerformanceMainThread final : public Performance
public:
PerformanceMainThread(nsPIDOMWindowInner* aWindow,
nsDOMNavigationTiming* aDOMTiming,
- nsITimedChannel* aChannel,
- Performance* aParentPerformance);
+ nsITimedChannel* aChannel);
NS_DECL_ISUPPORTS_INHERITED
NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(PerformanceMainThread,
Performance)
- // Performance WebIDL methods
- DOMHighResTimeStamp Now() const override;
-
virtual PerformanceTiming* Timing() override;
virtual PerformanceNavigation* Navigation() override;
@@ -51,10 +47,14 @@ public:
return mChannel;
}
- virtual Performance* GetParentPerformance() const override
- {
- return mParentPerformance;
- }
+ // The GetEntries* methods need to be overriden in order to add the
+ // the document entry of type navigation.
+ virtual void GetEntries(nsTArray<RefPtr<PerformanceEntry>>& aRetval) override;
+ virtual void GetEntriesByType(const nsAString& aEntryType,
+ nsTArray<RefPtr<PerformanceEntry>>& aRetval) override;
+ virtual void GetEntriesByName(const nsAString& aName,
+ const Optional<nsAString>& aEntryType,
+ nsTArray<RefPtr<PerformanceEntry>>& aRetval) override;
protected:
~PerformanceMainThread();
@@ -72,12 +72,13 @@ protected:
GetPerformanceTimingFromString(const nsAString& aTimingName) override;
void DispatchBufferFullEvent() override;
+ void EnsureDocEntry();
+ RefPtr<PerformanceEntry> mDocEntry;
RefPtr<nsDOMNavigationTiming> mDOMTiming;
nsCOMPtr<nsITimedChannel> mChannel;
RefPtr<PerformanceTiming> mTiming;
RefPtr<PerformanceNavigation> mNavigation;
- RefPtr<Performance> mParentPerformance;
JS::Heap<JSObject*> mMozMemory;
};
diff --git a/dom/performance/PerformanceNavigationTiming.cpp b/dom/performance/PerformanceNavigationTiming.cpp
new file mode 100644
index 000000000..4e00b2bb2
--- /dev/null
+++ b/dom/performance/PerformanceNavigationTiming.cpp
@@ -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: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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/dom/PerformanceNavigationTiming.h"
+#include "mozilla/dom/PerformanceNavigationTimingBinding.h"
+
+using namespace mozilla::dom;
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(PerformanceNavigationTiming)
+NS_INTERFACE_MAP_END_INHERITING(PerformanceResourceTiming)
+
+NS_IMPL_ADDREF_INHERITED(PerformanceNavigationTiming, PerformanceResourceTiming)
+NS_IMPL_RELEASE_INHERITED(PerformanceNavigationTiming, PerformanceResourceTiming)
+
+JSObject*
+PerformanceNavigationTiming::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
+{
+ return PerformanceNavigationTimingBinding::Wrap(aCx, this, aGivenProto);
+}
+
+DOMHighResTimeStamp
+PerformanceNavigationTiming::UnloadEventStart() const
+{
+ return mTiming->GetDOMTiming()->GetUnloadEventStartHighRes();
+}
+
+DOMHighResTimeStamp
+PerformanceNavigationTiming::UnloadEventEnd() const
+{
+ return mTiming->GetDOMTiming()->GetUnloadEventEndHighRes();
+}
+
+DOMHighResTimeStamp
+PerformanceNavigationTiming::DomInteractive() const
+{
+ return mTiming->GetDOMTiming()->GetDomInteractiveHighRes();
+}
+
+DOMHighResTimeStamp
+PerformanceNavigationTiming::DomContentLoadedEventStart() const
+{
+ return mTiming->GetDOMTiming()->GetDomContentLoadedEventStartHighRes();
+}
+
+DOMHighResTimeStamp
+PerformanceNavigationTiming::DomContentLoadedEventEnd() const
+{
+ return mTiming->GetDOMTiming()->GetDomContentLoadedEventEndHighRes();
+}
+
+DOMHighResTimeStamp
+PerformanceNavigationTiming::DomComplete() const
+{
+ return mTiming->GetDOMTiming()->GetDomCompleteHighRes();
+}
+
+DOMHighResTimeStamp
+PerformanceNavigationTiming::LoadEventStart() const
+{
+ return mTiming->GetDOMTiming()->GetLoadEventStartHighRes();
+}
+
+DOMHighResTimeStamp
+PerformanceNavigationTiming::LoadEventEnd() const
+{
+ return mTiming->GetDOMTiming()->GetLoadEventEndHighRes();
+}
+
+NavigationType
+PerformanceNavigationTiming::Type() const
+{
+ switch(mTiming->GetDOMTiming()->GetType()) {
+ case nsDOMNavigationTiming::TYPE_NAVIGATE:
+ return NavigationType::Navigate;
+ break;
+ case nsDOMNavigationTiming::TYPE_RELOAD:
+ return NavigationType::Reload;
+ break;
+ case nsDOMNavigationTiming::TYPE_BACK_FORWARD:
+ return NavigationType::Back_forward;
+ break;
+ default:
+ // The type is TYPE_RESERVED or some other value that was later added.
+ // We fallback to the default of Navigate.
+ return NavigationType::Navigate;
+ }
+}
+
+uint16_t
+PerformanceNavigationTiming::RedirectCount() const
+{
+ return mTiming->GetRedirectCount();
+}
diff --git a/dom/performance/PerformanceNavigationTiming.h b/dom/performance/PerformanceNavigationTiming.h
new file mode 100644
index 000000000..8555f1987
--- /dev/null
+++ b/dom/performance/PerformanceNavigationTiming.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/. */
+
+#ifndef mozilla_dom_PerformanceNavigationTiming_h___
+#define mozilla_dom_PerformanceNavigationTiming_h___
+
+#include "nsCOMPtr.h"
+#include "nsIChannel.h"
+#include "nsITimedChannel.h"
+#include "mozilla/dom/PerformanceResourceTiming.h"
+#include "mozilla/dom/PerformanceNavigationTimingBinding.h"
+#include "nsIHttpChannel.h"
+
+namespace mozilla {
+namespace dom {
+
+// https://www.w3.org/TR/navigation-timing-2/#sec-PerformanceNavigationTiming
+class PerformanceNavigationTiming final
+ : public PerformanceResourceTiming
+{
+public:
+ NS_DECL_ISUPPORTS_INHERITED
+
+ // Note that aPerformanceTiming must be initalized with zeroTime = 0
+ // so that timestamps are relative to startTime, as opposed to the
+ // performance.timing object for which timestamps are absolute and has a
+ // zeroTime initialized to navigationStart
+ explicit PerformanceNavigationTiming(PerformanceTiming* aPerformanceTiming,
+ Performance* aPerformance,
+ nsIHttpChannel* aChannel)
+ : PerformanceResourceTiming(aPerformanceTiming, aPerformance,
+ NS_LITERAL_STRING("document"), aChannel) {
+ SetEntryType(NS_LITERAL_STRING("navigation"));
+ SetInitiatorType(NS_LITERAL_STRING("navigation"));
+ }
+
+ DOMHighResTimeStamp Duration() const override
+ {
+ return LoadEventEnd() - StartTime();
+ }
+
+ DOMHighResTimeStamp StartTime() const override
+ {
+ return 0;
+ }
+
+ JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
+
+ DOMHighResTimeStamp UnloadEventStart() const;
+ DOMHighResTimeStamp UnloadEventEnd() const;
+
+ DOMHighResTimeStamp DomInteractive() const;
+ DOMHighResTimeStamp DomContentLoadedEventStart() const;
+ DOMHighResTimeStamp DomContentLoadedEventEnd() const;
+ DOMHighResTimeStamp DomComplete() const;
+ DOMHighResTimeStamp LoadEventStart() const;
+ DOMHighResTimeStamp LoadEventEnd() const;
+ NavigationType Type() const;
+ uint16_t RedirectCount() const;
+
+private:
+ ~PerformanceNavigationTiming() {}
+};
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_PerformanceNavigationTiming_h___
diff --git a/dom/performance/PerformanceObserver.cpp b/dom/performance/PerformanceObserver.cpp
index 11dd30ac2..d02acfb09 100644
--- a/dom/performance/PerformanceObserver.cpp
+++ b/dom/performance/PerformanceObserver.cpp
@@ -114,12 +114,13 @@ PerformanceObserver::Notify()
RefPtr<PerformanceObserverEntryList> list =
new PerformanceObserverEntryList(this, mQueuedEntries);
+ mQueuedEntries.Clear();
+
ErrorResult rv;
mCallback->Call(this, *list, *this, rv);
if (NS_WARN_IF(rv.Failed())) {
rv.SuppressException();
}
- mQueuedEntries.Clear();
}
void
@@ -170,6 +171,17 @@ PerformanceObserver::Observe(const PerformanceObserverInit& aOptions,
mEntryTypes.SwapElements(validEntryTypes);
mPerformance->AddObserver(this);
+
+ if (aOptions.mBuffered) {
+ for (auto entryType : mEntryTypes) {
+ nsTArray<RefPtr<PerformanceEntry>> existingEntries;
+ mPerformance->GetEntriesByType(entryType, existingEntries);
+ if (!existingEntries.IsEmpty()) {
+ mQueuedEntries.AppendElements(existingEntries);
+ }
+ }
+ }
+
mConnected = true;
}
diff --git a/dom/performance/PerformanceObserverEntryList.cpp b/dom/performance/PerformanceObserverEntryList.cpp
index 349103f08..20e818f3d 100644
--- a/dom/performance/PerformanceObserverEntryList.cpp
+++ b/dom/performance/PerformanceObserverEntryList.cpp
@@ -66,6 +66,7 @@ PerformanceObserverEntryList::GetEntries(
aRetval.AppendElement(entry);
}
+ aRetval.Sort(PerformanceEntryComparator());
}
void
@@ -79,6 +80,7 @@ PerformanceObserverEntryList::GetEntriesByType(
aRetval.AppendElement(entry);
}
}
+ aRetval.Sort(PerformanceEntryComparator());
}
void
@@ -88,9 +90,18 @@ PerformanceObserverEntryList::GetEntriesByName(
nsTArray<RefPtr<PerformanceEntry>>& aRetval)
{
aRetval.Clear();
+ const bool typePassed = aEntryType.WasPassed();
for (const RefPtr<PerformanceEntry>& entry : mEntries) {
- if (entry->GetName().Equals(aName)) {
- aRetval.AppendElement(entry);
+ if (!entry->GetName().Equals(aName)) {
+ continue;
}
+
+ if (typePassed &&
+ !entry->GetEntryType().Equals(aEntryType.Value())) {
+ continue;
+ }
+
+ aRetval.AppendElement(entry);
}
+ aRetval.Sort(PerformanceEntryComparator());
}
diff --git a/dom/performance/PerformanceResourceTiming.cpp b/dom/performance/PerformanceResourceTiming.cpp
index 60a20ca28..2eaa4eb9a 100644
--- a/dom/performance/PerformanceResourceTiming.cpp
+++ b/dom/performance/PerformanceResourceTiming.cpp
@@ -25,7 +25,8 @@ NS_IMPL_RELEASE_INHERITED(PerformanceResourceTiming, PerformanceEntry)
PerformanceResourceTiming::PerformanceResourceTiming(PerformanceTiming* aPerformanceTiming,
Performance* aPerformance,
- const nsAString& aName)
+ const nsAString& aName,
+ nsIHttpChannel* aChannel)
: PerformanceEntry(aPerformance, aName, NS_LITERAL_STRING("resource")),
mTiming(aPerformanceTiming),
mEncodedBodySize(0),
@@ -33,6 +34,34 @@ PerformanceResourceTiming::PerformanceResourceTiming(PerformanceTiming* aPerform
mDecodedBodySize(0)
{
MOZ_ASSERT(aPerformance, "Parent performance object should be provided");
+ SetPropertiesFromChannel(aChannel);
+}
+
+void
+PerformanceResourceTiming::SetPropertiesFromChannel(nsIHttpChannel* aChannel)
+{
+ if (!aChannel) {
+ return;
+ }
+
+ nsAutoCString protocol;
+ Unused << aChannel->GetProtocolVersion(protocol);
+ SetNextHopProtocol(NS_ConvertUTF8toUTF16(protocol));
+
+ uint64_t encodedBodySize = 0;
+ Unused << aChannel->GetEncodedBodySize(&encodedBodySize);
+ SetEncodedBodySize(encodedBodySize);
+
+ uint64_t transferSize = 0;
+ Unused << aChannel->GetTransferSize(&transferSize);
+ SetTransferSize(transferSize);
+
+ uint64_t decodedBodySize = 0;
+ Unused << aChannel->GetDecodedBodySize(&decodedBodySize);
+ if (decodedBodySize == 0) {
+ decodedBodySize = encodedBodySize;
+ }
+ SetDecodedBodySize(decodedBodySize);
}
PerformanceResourceTiming::~PerformanceResourceTiming()
@@ -42,8 +71,22 @@ PerformanceResourceTiming::~PerformanceResourceTiming()
DOMHighResTimeStamp
PerformanceResourceTiming::StartTime() const
{
- DOMHighResTimeStamp startTime = mTiming->RedirectStartHighRes();
- return startTime ? startTime : mTiming->FetchStartHighRes();
+ // Force the start time to be the earliest of:
+ // - RedirectStart
+ // - WorkerStart
+ // - AsyncOpen
+ // Ignore zero values. The RedirectStart and WorkerStart values
+ // can come from earlier redirected channels prior to the AsyncOpen
+ // time being recorded.
+ DOMHighResTimeStamp redirect = mTiming->RedirectStartHighRes();
+ redirect = redirect ? redirect : DBL_MAX;
+
+ DOMHighResTimeStamp worker = mTiming->WorkerStartHighRes();
+ worker = worker ? worker : DBL_MAX;
+
+ DOMHighResTimeStamp asyncOpen = mTiming->AsyncOpenHighRes();
+
+ return std::min(asyncOpen, std::min(redirect, worker));
}
JSObject*
diff --git a/dom/performance/PerformanceResourceTiming.h b/dom/performance/PerformanceResourceTiming.h
index 2dd6b4a06..98a03327e 100644
--- a/dom/performance/PerformanceResourceTiming.h
+++ b/dom/performance/PerformanceResourceTiming.h
@@ -18,7 +18,7 @@ namespace mozilla {
namespace dom {
// http://www.w3.org/TR/resource-timing/#performanceresourcetiming
-class PerformanceResourceTiming final : public PerformanceEntry
+class PerformanceResourceTiming : public PerformanceEntry
{
public:
typedef mozilla::TimeStamp TimeStamp;
@@ -30,7 +30,8 @@ public:
PerformanceResourceTiming(PerformanceTiming* aPerformanceTiming,
Performance* aPerformance,
- const nsAString& aName);
+ const nsAString& aName,
+ nsIHttpChannel* aChannel = nullptr);
virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
@@ -62,6 +63,12 @@ public:
mNextHopProtocol = aNextHopProtocol;
}
+ DOMHighResTimeStamp WorkerStart() const {
+ return mTiming && mTiming->TimingAllowed()
+ ? mTiming->WorkerStartHighRes()
+ : 0;
+ }
+
DOMHighResTimeStamp FetchStart() const {
return mTiming
? mTiming->FetchStartHighRes()
@@ -170,6 +177,7 @@ public:
protected:
virtual ~PerformanceResourceTiming();
+ void SetPropertiesFromChannel(nsIHttpChannel* aChannel);
nsString mInitiatorType;
nsString mNextHopProtocol;
diff --git a/dom/performance/PerformanceService.cpp b/dom/performance/PerformanceService.cpp
new file mode 100644
index 000000000..cf119af89
--- /dev/null
+++ b/dom/performance/PerformanceService.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 "PerformanceService.h"
+
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/StaticMutex.h"
+#include "mozilla/StaticPtr.h"
+
+namespace mozilla {
+namespace dom {
+
+static StaticRefPtr<PerformanceService> gPerformanceService;
+static StaticMutex gPerformanceServiceMutex;
+
+/* static */ PerformanceService*
+PerformanceService::GetOrCreate()
+{
+ StaticMutexAutoLock al(gPerformanceServiceMutex);
+
+ if (!gPerformanceService) {
+ gPerformanceService = new PerformanceService();
+ ClearOnShutdown(&gPerformanceService);
+ }
+
+ return gPerformanceService;
+}
+
+DOMHighResTimeStamp
+PerformanceService::TimeOrigin(const TimeStamp& aCreationTimeStamp) const
+{
+ return (aCreationTimeStamp - mCreationTimeStamp).ToMilliseconds() +
+ (mCreationEpochTime / PR_USEC_PER_MSEC);
+}
+
+PerformanceService::PerformanceService()
+{
+ mCreationTimeStamp = TimeStamp::Now();
+ mCreationEpochTime = PR_Now();
+}
+
+} // dom namespace
+} // mozilla namespace
diff --git a/dom/performance/PerformanceService.h b/dom/performance/PerformanceService.h
new file mode 100644
index 000000000..9abbd674d
--- /dev/null
+++ b/dom/performance/PerformanceService.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 dom_performance_PerformanceService_h
+#define dom_performance_PerformanceService_h
+
+#include "mozilla/TimeStamp.h"
+#include "nsCOMPtr.h"
+#include "nsDOMNavigationTiming.h"
+
+namespace mozilla {
+namespace dom {
+
+// This class is thread-safe.
+
+// We use this singleton for having the correct value of performance.timeOrigin.
+// This value must be calculated on top of the pair:
+// - mCreationTimeStamp (monotonic clock)
+// - mCreationEpochTime (unix epoch time)
+// These 2 values must be taken "at the same time" in order to be used
+// correctly.
+
+class PerformanceService
+{
+public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(PerformanceService)
+
+ static PerformanceService*
+ GetOrCreate();
+
+ DOMHighResTimeStamp
+ TimeOrigin(const TimeStamp& aCreationTimeStamp) const;
+
+private:
+ PerformanceService();
+ ~PerformanceService() = default;
+
+ TimeStamp mCreationTimeStamp;
+ PRTime mCreationEpochTime;
+};
+
+} // dom namespace
+} // mozilla namespace
+
+#endif // dom_performance_PerformanceService_h
diff --git a/dom/performance/PerformanceTiming.cpp b/dom/performance/PerformanceTiming.cpp
index e2f76a21f..887a23938 100755
--- a/dom/performance/PerformanceTiming.cpp
+++ b/dom/performance/PerformanceTiming.cpp
@@ -73,6 +73,7 @@ PerformanceTiming::InitializeTimingInfo(nsITimedChannel* aChannel)
{
if (aChannel) {
aChannel->GetAsyncOpen(&mAsyncOpen);
+ aChannel->GetDispatchFetchEventStart(&mWorkerStart);
aChannel->GetAllRedirectsSameOrigin(&mAllRedirectsSameOrigin);
aChannel->GetRedirectCount(&mRedirectCount);
aChannel->GetRedirectStart(&mRedirectStart);
@@ -88,31 +89,39 @@ PerformanceTiming::InitializeTimingInfo(nsITimedChannel* aChannel)
aChannel->GetResponseEnd(&mResponseEnd);
aChannel->GetCacheReadEnd(&mCacheReadEnd);
- // the performance timing api essentially requires that the event timestamps
- // are >= asyncOpen().. but in truth the browser engages in a number of
- // speculative activities that sometimes mean connections and lookups begin
- // earlier. Workaround that here by just using asyncOpen as the minimum
- // timestamp for dns and connection info.
+ // The performance timing api essentially requires that the event timestamps
+ // have a strict relation with each other. The truth, however, is the browser
+ // engages in a number of speculative activities that sometimes mean connections
+ // and lookups begin at different times. Workaround that here by clamping
+ // these values to what we expect FetchStart to be. This means the later of
+ // AsyncOpen or WorkerStart times.
if (!mAsyncOpen.IsNull()) {
- if (!mDomainLookupStart.IsNull() && mDomainLookupStart < mAsyncOpen) {
- mDomainLookupStart = mAsyncOpen;
+ // We want to clamp to the expected FetchStart value. This is later of
+ // the AsyncOpen and WorkerStart values.
+ const TimeStamp* clampTime = &mAsyncOpen;
+ if (!mWorkerStart.IsNull() && mWorkerStart > mAsyncOpen) {
+ clampTime = &mWorkerStart;
}
- if (!mDomainLookupEnd.IsNull() && mDomainLookupEnd < mAsyncOpen) {
- mDomainLookupEnd = mAsyncOpen;
+ if (!mDomainLookupStart.IsNull() && mDomainLookupStart < *clampTime) {
+ mDomainLookupStart = *clampTime;
}
- if (!mConnectStart.IsNull() && mConnectStart < mAsyncOpen) {
- mConnectStart = mAsyncOpen;
+ if (!mDomainLookupEnd.IsNull() && mDomainLookupEnd < *clampTime) {
+ mDomainLookupEnd = *clampTime;
+ }
+
+ if (!mConnectStart.IsNull() && mConnectStart < *clampTime) {
+ mConnectStart = *clampTime;
}
if (mSecureConnection && !mSecureConnectionStart.IsNull() &&
- mSecureConnectionStart < mAsyncOpen) {
- mSecureConnectionStart = mAsyncOpen;
+ mSecureConnectionStart < *clampTime) {
+ mSecureConnectionStart = *clampTime;
}
- if (!mConnectEnd.IsNull() && mConnectEnd < mAsyncOpen) {
- mConnectEnd = mAsyncOpen;
+ if (!mConnectEnd.IsNull() && mConnectEnd < *clampTime) {
+ mConnectEnd = *clampTime;
}
}
}
@@ -131,9 +140,13 @@ PerformanceTiming::FetchStartHighRes()
}
MOZ_ASSERT(!mAsyncOpen.IsNull(), "The fetch start time stamp should always be "
"valid if the performance timing is enabled");
- mFetchStart = (!mAsyncOpen.IsNull())
- ? TimeStampToDOMHighRes(mAsyncOpen)
- : 0.0;
+ if (!mAsyncOpen.IsNull()) {
+ if (!mWorkerStart.IsNull() && mWorkerStart > mAsyncOpen) {
+ mFetchStart = TimeStampToDOMHighRes(mWorkerStart);
+ } else {
+ mFetchStart = TimeStampToDOMHighRes(mAsyncOpen);
+ }
+ }
}
return TimerClamping::ReduceMsTimeValue(mFetchStart);
}
@@ -180,7 +193,7 @@ PerformanceTiming::TimingAllowed() const
return mTimingAllowed;
}
-uint16_t
+uint8_t
PerformanceTiming::GetRedirectCount() const
{
if (!nsContentUtils::IsPerformanceTimingEnabled() || !IsInitialized()) {
@@ -205,6 +218,26 @@ PerformanceTiming::ShouldReportCrossOriginRedirect() const
return (mRedirectCount != 0) && mReportCrossOriginRedirect;
}
+DOMHighResTimeStamp
+PerformanceTiming::AsyncOpenHighRes()
+{
+ if (!nsContentUtils::IsPerformanceTimingEnabled() || !IsInitialized() ||
+ mAsyncOpen.IsNull()) {
+ return mZeroTime;
+ }
+ return TimeStampToReducedDOMHighResOrFetchStart(mAsyncOpen);
+}
+
+DOMHighResTimeStamp
+PerformanceTiming::WorkerStartHighRes()
+{
+ if (!nsContentUtils::IsPerformanceTimingEnabled() || !IsInitialized() ||
+ mWorkerStart.IsNull()) {
+ return mZeroTime;
+ }
+ return TimeStampToReducedDOMHighResOrFetchStart(mWorkerStart);
+}
+
/**
* RedirectStartHighRes() is used by both the navigation timing and the
* resource timing. Since, navigation timing and resource timing check and
diff --git a/dom/performance/PerformanceTiming.h b/dom/performance/PerformanceTiming.h
index fc7e7d5bd..435e1bca1 100755
--- a/dom/performance/PerformanceTiming.h
+++ b/dom/performance/PerformanceTiming.h
@@ -139,7 +139,7 @@ public:
return TimerClamping::ReduceMsTimeValue(GetDOMTiming()->GetUnloadEventEnd());
}
- uint16_t GetRedirectCount() const;
+ uint8_t GetRedirectCount() const;
// Checks if the resource is either same origin as the page that started
// the load, or if the response contains the Timing-Allow-Origin header
@@ -155,7 +155,12 @@ public:
// the timing-allow-origin check in HttpBaseChannel::TimingAllowCheck
bool ShouldReportCrossOriginRedirect() const;
+ // The last channel's AsyncOpen time. This may occur before the FetchStart
+ // in some cases.
+ DOMHighResTimeStamp AsyncOpenHighRes();
+
// High resolution (used by resource timing)
+ DOMHighResTimeStamp WorkerStartHighRes();
DOMHighResTimeStamp FetchStartHighRes();
DOMHighResTimeStamp RedirectStartHighRes();
DOMHighResTimeStamp RedirectEndHighRes();
@@ -237,6 +242,14 @@ public:
return TimerClamping::ReduceMsTimeValue(GetDOMTiming()->GetLoadEventEnd());
}
+ DOMTimeMilliSec TimeToNonBlankPaint() const
+ {
+ if (!nsContentUtils::IsPerformanceTimingEnabled()) {
+ return 0;
+ }
+ return TimerClamping::ReduceMsTimeValue(GetDOMTiming()->GetTimeToNonBlankPaint());
+ }
+
private:
~PerformanceTiming();
@@ -253,6 +266,7 @@ private:
DOMHighResTimeStamp mZeroTime;
TimeStamp mAsyncOpen;
+ TimeStamp mWorkerStart;
TimeStamp mRedirectStart;
TimeStamp mRedirectEnd;
TimeStamp mDomainLookupStart;
@@ -265,7 +279,7 @@ private:
TimeStamp mCacheReadStart;
TimeStamp mResponseEnd;
TimeStamp mCacheReadEnd;
- uint16_t mRedirectCount;
+ uint8_t mRedirectCount;
bool mTimingAllowed;
bool mAllRedirectsSameOrigin;
bool mInitialized;
diff --git a/dom/performance/PerformanceWorker.cpp b/dom/performance/PerformanceWorker.cpp
index 85ca2ccd8..f10c58446 100644
--- a/dom/performance/PerformanceWorker.cpp
+++ b/dom/performance/PerformanceWorker.cpp
@@ -23,37 +23,6 @@ PerformanceWorker::~PerformanceWorker()
mWorkerPrivate->AssertIsOnWorkerThread();
}
-DOMHighResTimeStamp
-PerformanceWorker::Now() const
-{
- TimeDuration duration =
- TimeStamp::Now() - mWorkerPrivate->NowBaseTimeStamp();
- return RoundTime(duration.ToMilliseconds());
-}
-
-// To be removed once bug 1124165 lands
-bool
-PerformanceWorker::IsPerformanceTimingAttribute(const nsAString& aName)
-{
- // In workers we just support navigationStart.
- return aName.EqualsASCII("navigationStart");
-}
-
-DOMHighResTimeStamp
-PerformanceWorker::GetPerformanceTimingFromString(const nsAString& aProperty)
-{
- if (!IsPerformanceTimingAttribute(aProperty)) {
- return 0;
- }
-
- if (aProperty.EqualsLiteral("navigationStart")) {
- return mWorkerPrivate->NowBaseTime();
- }
-
- MOZ_CRASH("IsPerformanceTimingAttribute and GetPerformanceTimingFromString are out of sync");
- return 0;
-}
-
void
PerformanceWorker::InsertUserEntry(PerformanceEntry* aEntry)
{
@@ -72,13 +41,13 @@ PerformanceWorker::InsertUserEntry(PerformanceEntry* aEntry)
TimeStamp
PerformanceWorker::CreationTimeStamp() const
{
- return mWorkerPrivate->NowBaseTimeStamp();
+ return mWorkerPrivate->CreationTimeStamp();
}
DOMHighResTimeStamp
PerformanceWorker::CreationTime() const
{
- return mWorkerPrivate->NowBaseTime();
+ return mWorkerPrivate->CreationTime();
}
} // dom namespace
diff --git a/dom/performance/PerformanceWorker.h b/dom/performance/PerformanceWorker.h
index 7eef0d974..346bdd026 100644
--- a/dom/performance/PerformanceWorker.h
+++ b/dom/performance/PerformanceWorker.h
@@ -21,9 +21,6 @@ class PerformanceWorker final : public Performance
public:
explicit PerformanceWorker(workers::WorkerPrivate* aWorkerPrivate);
- // Performance WebIDL methods
- DOMHighResTimeStamp Now() const override;
-
virtual PerformanceTiming* Timing() override
{
MOZ_CRASH("This should not be called on workers.");
@@ -64,12 +61,6 @@ public:
return nullptr;
}
- virtual Performance* GetParentPerformance() const override
- {
- MOZ_CRASH("This should not be called on workers.");
- return nullptr;
- }
-
protected:
~PerformanceWorker();
@@ -80,11 +71,6 @@ protected:
void InsertUserEntry(PerformanceEntry* aEntry) override;
- bool IsPerformanceTimingAttribute(const nsAString& aName) override;
-
- DOMHighResTimeStamp
- GetPerformanceTimingFromString(const nsAString& aTimingName) override;
-
void DispatchBufferFullEvent() override
{
MOZ_CRASH("This should not be called on workers.");
diff --git a/dom/performance/moz.build b/dom/performance/moz.build
index 3286a0a4c..e1f96fec8 100644
--- a/dom/performance/moz.build
+++ b/dom/performance/moz.build
@@ -10,9 +10,11 @@ EXPORTS.mozilla.dom += [
'PerformanceMark.h',
'PerformanceMeasure.h',
'PerformanceNavigation.h',
+ 'PerformanceNavigationTiming.h',
'PerformanceObserver.h',
'PerformanceObserverEntryList.h',
'PerformanceResourceTiming.h',
+ 'PerformanceService.h',
'PerformanceTiming.h',
]
@@ -23,9 +25,11 @@ UNIFIED_SOURCES += [
'PerformanceMark.cpp',
'PerformanceMeasure.cpp',
'PerformanceNavigation.cpp',
+ 'PerformanceNavigationTiming.cpp',
'PerformanceObserver.cpp',
'PerformanceObserverEntryList.cpp',
'PerformanceResourceTiming.cpp',
+ 'PerformanceService.cpp',
'PerformanceTiming.cpp',
'PerformanceWorker.cpp',
]
diff --git a/dom/performance/tests/mochitest.ini b/dom/performance/tests/mochitest.ini
index 18f7f0e45..bee0b2e70 100644
--- a/dom/performance/tests/mochitest.ini
+++ b/dom/performance/tests/mochitest.ini
@@ -1,13 +1,11 @@
[DEFAULT]
support-files =
- performance_observer.html
test_performance_observer.js
test_performance_user_timing.js
test_worker_performance_now.js
worker_performance_user_timing.js
worker_performance_observer.js
sharedworker_performance_user_timing.js
- worker_performance_observer.html
[test_performance_observer.html]
[test_performance_user_timing.html]
@@ -15,3 +13,4 @@ support-files =
[test_worker_observer.html]
[test_sharedWorker_performance_user_timing.html]
[test_worker_performance_now.html]
+[test_timeOrigin.html]
diff --git a/dom/performance/tests/performance_observer.html b/dom/performance/tests/performance_observer.html
deleted file mode 100644
index b8ced9296..000000000
--- a/dom/performance/tests/performance_observer.html
+++ /dev/null
@@ -1,74 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<!DOCTYPE html>
-<meta charset=utf-8>
-<html>
-<head>
-<title>Test for performance observer</title>
-<script>
-'use strict';
-[
- "promise_test", "test", "setup",
- "assert_true", "assert_equals", "assert_array_equals",
- "assert_throws", "assert_unreached"
-].forEach(func => {
- window[func] = opener[func].bind(opener);
-});
-function done() {
- opener.add_completion_callback(() => {
- self.close();
- });
- opener.done();
-}
-
-</script>
-<script src="test_performance_observer.js"></script>
-</head>
-<body>
-<div id="log"></div>
-<script>
-function makeXHR(aUrl) {
- var xmlhttp = new XMLHttpRequest();
- xmlhttp.open("get", aUrl, true);
- xmlhttp.send();
-}
-
-promise_test(t => {
- var promise = new Promise(resolve => {
- performance.clearResourceTimings();
-
- var observer = new PerformanceObserver(list => resolve(list));
- observer.observe({entryTypes: ['resource']});
- t.add_cleanup(() => observer.disconnect());
- });
-
- makeXHR("test-data.json");
-
- return promise.then(list => {
- assert_equals(list.getEntries().length, 1);
- assert_array_equals(list.getEntries(),
- performance.getEntriesByType("resource"),
- "Observed 'resource' entries should equal to entries obtained by getEntriesByType.");
-
- // getEntries filtering tests
- assert_array_equals(list.getEntries({name: "http://mochi.test:8888/tests/dom/base/test/test-data.json"}),
- performance.getEntriesByName("http://mochi.test:8888/tests/dom/base/test/test-data.json"),
- "getEntries with name filter should return correct results.");
- assert_array_equals(list.getEntries({entryType: "resource"}),
- performance.getEntriesByType("resource"),
- "getEntries with entryType filter should return correct results.");
- assert_array_equals(list.getEntries({initiatorType: "xmlhttprequest"}),
- performance.getEntriesByType("resource"),
- "getEntries with initiatorType filter should return correct results.");
- assert_array_equals(list.getEntries({initiatorType: "link"}),
- [],
- "getEntries with non-existent initiatorType filter should return an empty array.");
- });
-}, "resource-timing test");
-
-done();
-
-</script>
-</body>
diff --git a/dom/performance/tests/test_performance_observer.html b/dom/performance/tests/test_performance_observer.html
index d36878315..7df881bd4 100644
--- a/dom/performance/tests/test_performance_observer.html
+++ b/dom/performance/tests/test_performance_observer.html
@@ -3,15 +3,55 @@
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE html>
+<html>
+<head>
<meta charset=utf-8>
<title>Test for performance observer</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
-<div id=log></div>
+</head>
+<body>
+<div id="log"></div>
+<script src="test_performance_observer.js"></script>
<script>
-'use strict';
-SpecialPowers.pushPrefEnv({"set": [["dom.enable_performance_observer", true]]},
- function() {
- window.open("performance_observer.html");
- });
+function makeXHR(aUrl) {
+ var xmlhttp = new XMLHttpRequest();
+ xmlhttp.open("get", aUrl, true);
+ xmlhttp.send();
+}
+
+promise_test(t => {
+ var promise = new Promise(resolve => {
+ performance.clearResourceTimings();
+
+ var observer = new PerformanceObserver(list => resolve(list));
+ observer.observe({entryTypes: ['resource']});
+ t.add_cleanup(() => observer.disconnect());
+ });
+
+ makeXHR("test-data.json");
+
+ return promise.then(list => {
+ assert_equals(list.getEntries().length, 1);
+ assert_array_equals(list.getEntries(),
+ performance.getEntriesByType("resource"),
+ "Observed 'resource' entries should equal to entries obtained by getEntriesByType.");
+
+ // getEntries filtering tests
+ assert_array_equals(list.getEntries({name: "http://mochi.test:8888/tests/dom/base/test/test-data.json"}),
+ performance.getEntriesByName("http://mochi.test:8888/tests/dom/base/test/test-data.json"),
+ "getEntries with name filter should return correct results.");
+ assert_array_equals(list.getEntries({entryType: "resource"}),
+ performance.getEntriesByType("resource"),
+ "getEntries with entryType filter should return correct results.");
+ assert_array_equals(list.getEntries({initiatorType: "xmlhttprequest"}),
+ performance.getEntriesByType("resource"),
+ "getEntries with initiatorType filter should return correct results.");
+ assert_array_equals(list.getEntries({initiatorType: "link"}),
+ [],
+ "getEntries with non-existent initiatorType filter should return an empty array.");
+ });
+}, "resource-timing test");
+
</script>
+</body>
diff --git a/dom/performance/tests/test_performance_user_timing.js b/dom/performance/tests/test_performance_user_timing.js
index cd8261bbd..a15dbebb6 100644
--- a/dom/performance/tests/test_performance_user_timing.js
+++ b/dom/performance/tests/test_performance_user_timing.js
@@ -126,15 +126,18 @@ var steps = [
},
// Test measure
function () {
- ok(true, "Running measure addition with no start/end time test");
- performance.measure("test");
- var measures = performance.getEntriesByType("measure");
- is(measures.length, 1, "number of measures should be 1");
- var measure = measures[0];
- is(measure.name, "test", "measure name should be 'test'");
- is(measure.entryType, "measure", "measure type should be 'measure'");
- is(measure.startTime, 0, "measure start time should be zero");
- ok(measure.duration >= 0, "measure duration should not be negative");
+ // We don't have navigationStart in workers.
+ if ("window" in self) {
+ ok(true, "Running measure addition with no start/end time test");
+ performance.measure("test", "navigationStart");
+ var measures = performance.getEntriesByType("measure");
+ is(measures.length, 1, "number of measures should be 1");
+ var measure = measures[0];
+ is(measure.name, "test", "measure name should be 'test'");
+ is(measure.entryType, "measure", "measure type should be 'measure'");
+ is(measure.startTime, 0, "measure start time should be zero");
+ ok(measure.duration >= 0, "measure duration should not be negative");
+ }
},
function () {
ok(true, "Running measure addition with only start time test");
diff --git a/dom/performance/tests/test_timeOrigin.html b/dom/performance/tests/test_timeOrigin.html
new file mode 100644
index 000000000..5a8a461f3
--- /dev/null
+++ b/dom/performance/tests/test_timeOrigin.html
@@ -0,0 +1,68 @@
+<!DOCTYPE HTML>
+<html>
+ <head>
+ <title>Test for performance.timeOrigin</title>
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8">
+ <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script type="text/javascript" src="test_performance_user_timing.js"></script>
+ </head>
+ <body>
+ <script type="text/js-worker" id="worker-src">
+ postMessage({ now: performance.now(), timeOrigin: performance.timeOrigin });
+ </script>
+
+ <script type="text/js-worker" id="shared-worker-src">
+ onconnect = function(evt) {
+ evt.ports[0].postMessage({ now: performance.now(), timeOrigin: performance.timeOrigin });
+ };
+ </script>
+
+ <script class="testbody" type="text/javascript">
+
+function testBasic() {
+ ok("timeOrigin" in performance, "Performance.timeOrigin exists.");
+ ok(performance.timeOrigin > 0, "TimeOrigin must be greater than 0.");
+ next();
+}
+
+function testWorker() {
+ var now = performance.now();
+
+ var blob = new Blob([ document.getElementById("worker-src").textContent ],
+ { type: "text/javascript" });
+ var w = new Worker(URL.createObjectURL(blob));
+ w.onmessage = function(e) {
+ ok (e.now + e.timeOrigin > now + performance.now, "Comparing worker.now and window.now");
+ next();
+ }
+}
+
+function testSharedWorker() {
+ var now = performance.now();
+
+ var blob = new Blob([ document.getElementById("shared-worker-src").textContent ],
+ { type: "text/javascript" });
+ var w = new SharedWorker(URL.createObjectURL(blob));
+ w.port.onmessage = function(e) {
+ ok (e.now + e.timeOrigin > now + performance.now, "Comparing worker.now and window.now");
+ next();
+ }
+}
+
+var tests = [ testBasic, testWorker, testSharedWorker ];
+function next() {
+ if (!tests.length) {
+ SimpleTest.finish();
+ return;
+ }
+
+ var test = tests.shift();
+ test();
+}
+
+SimpleTest.waitForExplicitFinish();
+addLoadEvent(next);
+ </script>
+ </pre>
+ </body>
+</html>
diff --git a/dom/performance/tests/test_worker_observer.html b/dom/performance/tests/test_worker_observer.html
index b9ed0c964..9a55ef1d5 100644
--- a/dom/performance/tests/test_worker_observer.html
+++ b/dom/performance/tests/test_worker_observer.html
@@ -3,15 +3,16 @@
http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE html>
+<html>
+<head>
<meta charset=utf-8>
<title>Test for performance observer in worker</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
-<div id=log></div>
+</head>
+<body>
+<div id="log"></div>
<script>
-'use strict';
-SpecialPowers.pushPrefEnv({"set": [["dom.enable_performance_observer", true]]},
- function() {
- window.open("worker_performance_observer.html");
- });
+fetch_tests_from_worker(new Worker("worker_performance_observer.js"));
</script>
+</body>
diff --git a/dom/performance/tests/worker_performance_observer.html b/dom/performance/tests/worker_performance_observer.html
deleted file mode 100644
index 613762f52..000000000
--- a/dom/performance/tests/worker_performance_observer.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<!--
- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/
--->
-<!DOCTYPE html>
-<meta charset=utf-8>
-<html>
-<head>
-<title>Test for performance observer in worker</title>
-</head>
-<body>
-<div id="log"></div>
-<script>
-[
- "async_test", "test", "setup",
- "assert_true", "assert_equals", "assert_array_equals",
- "assert_throws", "fetch_tests_from_worker"
-].forEach(func => {
- window[func] = opener[func].bind(opener);
-});
-
-function done() {
- opener.add_completion_callback(() => {
- self.close();
- });
- opener.done();
-}
-
-fetch_tests_from_worker(new Worker("worker_performance_observer.js"));
-done();
-</script>
-</body>
diff --git a/dom/permission/tests/mochitest.ini b/dom/permission/tests/mochitest.ini
index 58fd048ca..2d4208e1f 100644
--- a/dom/permission/tests/mochitest.ini
+++ b/dom/permission/tests/mochitest.ini
@@ -7,7 +7,6 @@ support-files =
[test_browser.html]
skip-if = true
[test_idle.html]
-# skip-if = (toolkit == 'gonk' && debug) #debug-only failure
skip-if = true
[test_permissions.html]
skip-if = true
diff --git a/dom/plugins/base/PluginPRLibrary.cpp b/dom/plugins/base/PluginPRLibrary.cpp
index a7ad76ea4..ecc55d455 100644
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -57,12 +57,6 @@ PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
mNPP_GetSitesWithData = pFuncs->getsiteswithdata;
return NS_OK;
}
-#elif defined(MOZ_WIDGET_GONK)
-nsresult
-PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error)
-{
- return NS_OK;
-}
#elif defined(XP_UNIX) && !defined(XP_MACOSX)
nsresult
PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
diff --git a/dom/plugins/base/PluginPRLibrary.h b/dom/plugins/base/PluginPRLibrary.h
index 602ad8cf8..ffd3de934 100644
--- a/dom/plugins/base/PluginPRLibrary.h
+++ b/dom/plugins/base/PluginPRLibrary.h
@@ -81,7 +81,7 @@ public:
return true;
}
-#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+#if defined(XP_UNIX) && !defined(XP_MACOSX)
virtual nsresult NP_Initialize(NPNetscapeFuncs* aNetscapeFuncs,
NPPluginFuncs* aFuncs, NPError* aError) override;
#else
diff --git a/dom/plugins/base/nsNPAPIPlugin.cpp b/dom/plugins/base/nsNPAPIPlugin.cpp
index 1bea269cd..697bfacd4 100644
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -320,7 +320,6 @@ nsNPAPIPlugin::CreatePlugin(nsPluginTag *aPluginTag, nsNPAPIPlugin** aResult)
if (rv != NS_OK || pluginCallError != NPERR_NO_ERROR) {
return NS_ERROR_FAILURE;
}
-#elif defined(MOZ_WIDGET_GONK)
#else
NPError pluginCallError;
nsresult rv = pluginLib->NP_Initialize(&sBrowserFuncs, &plugin->mPluginFuncs, &pluginCallError);
diff --git a/dom/plugins/base/nsPluginInstanceOwner.cpp b/dom/plugins/base/nsPluginInstanceOwner.cpp
index b7651be1a..d5b1eb9ea 100644
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -535,16 +535,6 @@ NS_IMETHODIMP nsPluginInstanceOwner::GetURL(const char *aURL,
nsresult rv = NS_NewURI(getter_AddRefs(uri), aURL, baseURI);
NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
- if (aDoCheckLoadURIChecks) {
- nsCOMPtr<nsIScriptSecurityManager> secMan(
- do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv));
- NS_ENSURE_TRUE(secMan, NS_ERROR_FAILURE);
-
- rv = secMan->CheckLoadURIWithPrincipal(content->NodePrincipal(), uri,
- nsIScriptSecurityManager::STANDARD);
- NS_ENSURE_SUCCESS(rv, rv);
- }
-
nsCOMPtr<nsIInputStream> headersDataStream;
if (aPostStream && aHeadersData) {
if (!aHeadersDataLen)
@@ -563,8 +553,21 @@ NS_IMETHODIMP nsPluginInstanceOwner::GetURL(const char *aURL,
Preferences::GetInt("privacy.popups.disable_from_plugins");
nsAutoPopupStatePusher popupStatePusher((PopupControlState)blockPopups);
+
+ // if security checks (in particular CheckLoadURIWithPrincipal) needs
+ // to be skipped we are creating a codebasePrincipal to make sure
+ // that security check succeeds. Please note that we do not want to
+ // fall back to using the systemPrincipal, because that would also
+ // bypass ContentPolicy checks which should still be enforced.
+ nsCOMPtr<nsIPrincipal> triggeringPrincipal;
+ if (!aDoCheckLoadURIChecks) {
+ mozilla::PrincipalOriginAttributes attrs =
+ BasePrincipal::Cast(content->NodePrincipal())->OriginAttributesRef();
+ triggeringPrincipal = BasePrincipal::CreateCodebasePrincipal(uri, attrs);
+ }
+
rv = lh->OnLinkClick(content, uri, unitarget.get(), NullString(),
- aPostStream, headersDataStream, true);
+ aPostStream, headersDataStream, true, triggeringPrincipal);
return rv;
}
@@ -2532,6 +2535,7 @@ nsEventStatus nsPluginInstanceOwner::ProcessEvent(const WidgetGUIEvent& anEvent)
NS_ASSERTION(anEvent.mMessage == eMouseDown ||
anEvent.mMessage == eMouseUp ||
anEvent.mMessage == eMouseDoubleClick ||
+ anEvent.mMessage == eMouseAuxClick ||
anEvent.mMessage == eMouseOver ||
anEvent.mMessage == eMouseOut ||
anEvent.mMessage == eMouseMove ||
@@ -2594,6 +2598,7 @@ nsEventStatus nsPluginInstanceOwner::ProcessEvent(const WidgetGUIEvent& anEvent)
switch (anEvent.mMessage) {
case eMouseClick:
case eMouseDoubleClick:
+ case eMouseAuxClick:
// Button up/down events sent instead.
return rv;
default:
@@ -2797,6 +2802,7 @@ nsEventStatus nsPluginInstanceOwner::ProcessEvent(const WidgetGUIEvent& anEvent)
switch (anEvent.mMessage) {
case eMouseClick:
case eMouseDoubleClick:
+ case eMouseAuxClick:
// Button up/down events sent instead.
return rv;
default:
diff --git a/dom/plugins/base/nsPluginTags.cpp b/dom/plugins/base/nsPluginTags.cpp
index ddc3968fd..a794c416c 100644
--- a/dom/plugins/base/nsPluginTags.cpp
+++ b/dom/plugins/base/nsPluginTags.cpp
@@ -248,7 +248,6 @@ nsPluginTag::nsPluginTag(nsPluginInfo* aPluginInfo,
aPluginInfo->fMimeDescriptionArray,
aPluginInfo->fExtensionArray,
aPluginInfo->fVariantCount);
- InitSandboxLevel();
EnsureMembersAreUTF8();
FixupVersion();
}
@@ -283,7 +282,6 @@ nsPluginTag::nsPluginTag(const char* aName,
{
InitMime(aMimeTypes, aMimeDescriptions, aExtensions,
static_cast<uint32_t>(aVariants));
- InitSandboxLevel();
if (!aArgsAreUTF8)
EnsureMembersAreUTF8();
FixupVersion();
@@ -424,29 +422,6 @@ void nsPluginTag::InitMime(const char* const* aMimeTypes,
}
}
-void
-nsPluginTag::InitSandboxLevel()
-{
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- nsAutoCString sandboxPref("dom.ipc.plugins.sandbox-level.");
- sandboxPref.Append(GetNiceFileName());
- if (NS_FAILED(Preferences::GetInt(sandboxPref.get(), &mSandboxLevel))) {
- mSandboxLevel = Preferences::GetInt("dom.ipc.plugins.sandbox-level.default"
-);
- }
-
-#if defined(_AMD64_)
- // As level 2 is now the default NPAPI sandbox level for 64-bit flash, we
- // don't want to allow a lower setting unless this environment variable is
- // set. This should be changed if the firefox.js pref file is changed.
- if (mIsFlashPlugin &&
- !PR_GetEnv("MOZ_ALLOW_WEAKER_SANDBOX") && mSandboxLevel < 2) {
- mSandboxLevel = 2;
- }
-#endif
-#endif
-}
-
#if !defined(XP_WIN) && !defined(XP_MACOSX)
static nsresult ConvertToUTF8(nsIUnicodeDecoder *aUnicodeDecoder,
nsAFlatCString& aString)
diff --git a/dom/plugins/base/nsPluginTags.h b/dom/plugins/base/nsPluginTags.h
index f1f03169b..9686d7e7a 100644
--- a/dom/plugins/base/nsPluginTags.h
+++ b/dom/plugins/base/nsPluginTags.h
@@ -190,7 +190,6 @@ private:
const char* const* aMimeDescriptions,
const char* const* aExtensions,
uint32_t aVariantCount);
- void InitSandboxLevel();
nsresult EnsureMembersAreUTF8();
void FixupVersion();
diff --git a/dom/plugins/ipc/PluginLibrary.h b/dom/plugins/ipc/PluginLibrary.h
index c9499ee0d..2f9a3f81b 100644
--- a/dom/plugins/ipc/PluginLibrary.h
+++ b/dom/plugins/ipc/PluginLibrary.h
@@ -57,7 +57,7 @@ public:
virtual bool HasRequiredFunctions() = 0;
-#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+#if defined(XP_UNIX) && !defined(XP_MACOSX)
virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error) = 0;
#else
virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error) = 0;
diff --git a/dom/plugins/ipc/PluginModuleParent.cpp b/dom/plugins/ipc/PluginModuleParent.cpp
index 73f9c1025..ae6da8787 100755
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -529,7 +529,7 @@ PluginModuleChromeParent::OnProcessLaunched(const bool aSucceeded)
if (NS_SUCCEEDED(mAsyncInitRv))
#endif
{
-#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+#if defined(XP_UNIX) && !defined(XP_MACOSX)
mAsyncInitRv = NP_Initialize(mNPNIface,
mNPPIface,
&mAsyncInitError);
@@ -1745,7 +1745,7 @@ PluginModuleChromeParent::CachedSettingChanged(const char* aPref, void* aModule)
module->CachedSettingChanged();
}
-#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+#if defined(XP_UNIX) && !defined(XP_MACOSX)
nsresult
PluginModuleParent::NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error)
{
diff --git a/dom/plugins/ipc/PluginModuleParent.h b/dom/plugins/ipc/PluginModuleParent.h
index 946d4c236..d00a01401 100644
--- a/dom/plugins/ipc/PluginModuleParent.h
+++ b/dom/plugins/ipc/PluginModuleParent.h
@@ -267,7 +267,7 @@ protected:
const mozilla::NativeEventData& aNativeKeyData,
bool aIsConsumed) override;
-#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+#if defined(XP_UNIX) && !defined(XP_MACOSX)
virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error) override;
#else
virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error) override;
@@ -517,7 +517,7 @@ private:
PluginProcessParent* Process() const { return mSubprocess; }
base::ProcessHandle ChildProcessHandle() { return mSubprocess->GetChildProcessHandle(); }
-#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+#if defined(XP_UNIX) && !defined(XP_MACOSX)
virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error) override;
#else
virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error) override;
diff --git a/dom/plugins/ipc/PluginProcessChild.cpp b/dom/plugins/ipc/PluginProcessChild.cpp
index eb698e8af..32bf06215 100644
--- a/dom/plugins/ipc/PluginProcessChild.cpp
+++ b/dom/plugins/ipc/PluginProcessChild.cpp
@@ -22,10 +22,6 @@ extern "C" CGError CGSSetDebugOptions(int options);
#ifdef XP_WIN
bool ShouldProtectPluginCurrentDirectory(char16ptr_t pluginFilePath);
-#if defined(MOZ_SANDBOX)
-#define TARGET_SANDBOX_EXPORTS
-#include "mozilla/sandboxTarget.h"
-#endif
#endif
using mozilla::ipc::IOThreadChild;
@@ -107,12 +103,6 @@ PluginProcessChild::Init()
pluginFilename = WideToUTF8(values[0]);
-#if defined(MOZ_SANDBOX)
- // This is probably the earliest we would want to start the sandbox.
- // As we attempt to tighten the sandbox, we may need to consider moving this
- // to later in the plugin initialization.
- mozilla::SandboxTarget::Instance()->StartSandbox();
-#endif
#else
# error Sorry
#endif
diff --git a/dom/plugins/ipc/PluginProcessParent.cpp b/dom/plugins/ipc/PluginProcessParent.cpp
index 2a73bce51..fb0e18246 100644
--- a/dom/plugins/ipc/PluginProcessParent.cpp
+++ b/dom/plugins/ipc/PluginProcessParent.cpp
@@ -14,10 +14,6 @@
#include "mozilla/Telemetry.h"
#include "nsThreadUtils.h"
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-#include "nsDirectoryServiceDefs.h"
-#endif
-
using std::vector;
using std::string;
@@ -40,95 +36,14 @@ PluginProcessParent::~PluginProcessParent()
{
}
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-static void
-AddSandboxAllowedFile(vector<std::wstring>& aAllowedFiles, nsIProperties* aDirSvc,
- const char* aDir, const nsAString& aSuffix = EmptyString())
-{
- nsCOMPtr<nsIFile> userDir;
- nsresult rv = aDirSvc->Get(aDir, NS_GET_IID(nsIFile), getter_AddRefs(userDir));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- nsAutoString userDirPath;
- rv = userDir->GetPath(userDirPath);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- if (!aSuffix.IsEmpty()) {
- userDirPath.Append(aSuffix);
- }
- aAllowedFiles.push_back(std::wstring(userDirPath.get()));
- return;
-}
-
-static void
-AddSandboxAllowedFiles(int32_t aSandboxLevel,
- vector<std::wstring>& aAllowedFilesRead,
- vector<std::wstring>& aAllowedFilesReadWrite,
- vector<std::wstring>& aAllowedDirectories)
-{
- if (aSandboxLevel < 2) {
- return;
- }
-
- nsresult rv;
- nsCOMPtr<nsIProperties> dirSvc =
- do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- // Higher than level 2 currently removes the users own rights.
- if (aSandboxLevel > 2) {
- AddSandboxAllowedFile(aAllowedFilesRead, dirSvc, NS_WIN_HOME_DIR);
- AddSandboxAllowedFile(aAllowedFilesRead, dirSvc, NS_WIN_HOME_DIR,
- NS_LITERAL_STRING("\\*"));
- }
-
- // Level 2 and above is now using low integrity, so we need to give write
- // access to the Flash directories.
- // This should be made Flash specific (Bug 1171396).
- AddSandboxAllowedFile(aAllowedFilesReadWrite, dirSvc, NS_WIN_APPDATA_DIR,
- NS_LITERAL_STRING("\\Macromedia\\Flash Player\\*"));
- AddSandboxAllowedFile(aAllowedFilesReadWrite, dirSvc, NS_WIN_LOCAL_APPDATA_DIR,
- NS_LITERAL_STRING("\\Macromedia\\Flash Player\\*"));
- AddSandboxAllowedFile(aAllowedFilesReadWrite, dirSvc, NS_WIN_APPDATA_DIR,
- NS_LITERAL_STRING("\\Adobe\\Flash Player\\*"));
-
- // Access also has to be given to create the parent directories as they may
- // not exist.
- AddSandboxAllowedFile(aAllowedDirectories, dirSvc, NS_WIN_APPDATA_DIR,
- NS_LITERAL_STRING("\\Macromedia"));
- AddSandboxAllowedFile(aAllowedDirectories, dirSvc, NS_WIN_APPDATA_DIR,
- NS_LITERAL_STRING("\\Macromedia\\Flash Player"));
- AddSandboxAllowedFile(aAllowedDirectories, dirSvc, NS_WIN_LOCAL_APPDATA_DIR,
- NS_LITERAL_STRING("\\Macromedia"));
- AddSandboxAllowedFile(aAllowedDirectories, dirSvc, NS_WIN_LOCAL_APPDATA_DIR,
- NS_LITERAL_STRING("\\Macromedia\\Flash Player"));
- AddSandboxAllowedFile(aAllowedDirectories, dirSvc, NS_WIN_APPDATA_DIR,
- NS_LITERAL_STRING("\\Adobe"));
- AddSandboxAllowedFile(aAllowedDirectories, dirSvc, NS_WIN_APPDATA_DIR,
- NS_LITERAL_STRING("\\Adobe\\Flash Player"));
-}
-#endif
-
bool
PluginProcessParent::Launch(mozilla::UniquePtr<LaunchCompleteTask> aLaunchCompleteTask,
int32_t aSandboxLevel)
{
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- mSandboxLevel = aSandboxLevel;
- AddSandboxAllowedFiles(mSandboxLevel, mAllowedFilesRead,
- mAllowedFilesReadWrite, mAllowedDirectories);
-#else
if (aSandboxLevel != 0) {
MOZ_ASSERT(false,
"Can't enable an NPAPI process sandbox for platform/build.");
}
-#endif
ProcessArchitecture currentArchitecture = base::GetCurrentProcessArchitecture();
uint32_t containerArchitectures = GetSupportedArchitecturesForProcessType(GeckoProcessType_Plugin);
diff --git a/dom/plugins/ipc/moz.build b/dom/plugins/ipc/moz.build
index b569aeb4c..15ed6410d 100644
--- a/dom/plugins/ipc/moz.build
+++ b/dom/plugins/ipc/moz.build
@@ -125,12 +125,6 @@ LOCAL_INCLUDES += [
'/xpcom/base/',
]
-if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_ARCH'] == 'WINNT':
- LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
- ]
-
DEFINES['FORCE_PR_LOG'] = True
if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gtk3':
diff --git a/dom/plugins/test/mochitest/test_bug813906.html b/dom/plugins/test/mochitest/test_bug813906.html
index 04c34daaf..d18dbbff2 100644
--- a/dom/plugins/test/mochitest/test_bug813906.html
+++ b/dom/plugins/test/mochitest/test_bug813906.html
@@ -18,21 +18,35 @@ function f() {
</script>
<script type="application/javascript">
+SimpleTest.requestFlakyTimeout(
+ "Blocking an iframe does not cause the onerror event to be fired");
+
SimpleTest.waitForExplicitFinish();
setTestPluginEnabledState(SpecialPowers.Ci.nsIPluginTag.STATE_ENABLED);
var frameLoadCount = 0;
+
+function frameNavBlocked() {
+ isnot(SpecialPowers.wrap(window.frame1).location.href.indexOf('chrome://'),
+ 0, 'plugin shouldnt be able to cause navigation to chrome URLs');
+ SimpleTest.finish();
+}
+
function frameLoaded() {
frameLoadCount++;
if (frameLoadCount == 1) {
document.getElementsByTagName("object")[0].type = "application/x-test";
document.getElementsByTagName("use")[0].setAttributeNS("http://www.w3.org/1999/xlink", "href", location.href + "#a");
- } else if (frameLoadCount == 2) {
- isnot(SpecialPowers.wrap(window.frame1).location.href.indexOf('chrome://'),
- 0, 'plugin shouldnt be able to cause navigation to chrome URLs');
- SimpleTest.finish();
+
+ // wait two seconds and verify that frame navigation did not succeed
+ setTimeout(frameNavBlocked, 2000);
+ return;
}
+ // we should never get here, but just in case, make sure the test fails in that case.
+ ok(false, "onload() event should not fire for blocked navigation");
+ SimpleTest.finish();
}
+
</script>
<!-- Note that <svg:use> ends up creating an anonymous subtree, which means that the plugin
diff --git a/dom/plugins/test/mochitest/test_pluginstream_err.html b/dom/plugins/test/mochitest/test_pluginstream_err.html
index 0ac2a5efc..79f06154c 100644
--- a/dom/plugins/test/mochitest/test_pluginstream_err.html
+++ b/dom/plugins/test/mochitest/test_pluginstream_err.html
@@ -13,7 +13,7 @@ Tests for plugin stream error conditions.
<link rel="stylesheet" type="text/css"
href="/tests/SimpleTest/test.css" />
</head>
-<body onload="runNextTest()">
+<body onload="startTests()">
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=517078">
Mozilla Bug 517078</a> - Plugin Stream Error Tests
<p id="display"></p>
@@ -158,6 +158,12 @@ function continueTest() {
index++;
}
+function startTests() {
+ SpecialPowers.pushPrefEnv({"set": [
+ ["security.data_uri.block_toplevel_data_uri_navigations", false],
+ ]}, runNextTest);
+}
+
</script>
</div>
</body>
diff --git a/dom/presentation/PresentationSessionInfo.cpp b/dom/presentation/PresentationSessionInfo.cpp
index f93909864..1dd92ab69 100644
--- a/dom/presentation/PresentationSessionInfo.cpp
+++ b/dom/presentation/PresentationSessionInfo.cpp
@@ -31,11 +31,6 @@
#include "nsIPresentationNetworkHelper.h"
#endif // MOZ_WIDGET_ANDROID
-#ifdef MOZ_WIDGET_GONK
-#include "nsINetworkInterface.h"
-#include "nsINetworkManager.h"
-#endif
-
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::services;
@@ -647,49 +642,7 @@ PresentationControllingInfo::Shutdown(nsresult aReason)
nsresult
PresentationControllingInfo::GetAddress()
{
-#if defined(MOZ_WIDGET_GONK)
- nsCOMPtr<nsINetworkManager> networkManager =
- do_GetService("@mozilla.org/network/manager;1");
- if (NS_WARN_IF(!networkManager)) {
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- nsCOMPtr<nsINetworkInfo> activeNetworkInfo;
- networkManager->GetActiveNetworkInfo(getter_AddRefs(activeNetworkInfo));
- if (NS_WARN_IF(!activeNetworkInfo)) {
- return NS_ERROR_FAILURE;
- }
-
- char16_t** ips = nullptr;
- uint32_t* prefixes = nullptr;
- uint32_t count = 0;
- activeNetworkInfo->GetAddresses(&ips, &prefixes, &count);
- if (NS_WARN_IF(!count)) {
- NS_Free(prefixes);
- NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, ips);
- return NS_ERROR_FAILURE;
- }
-
- // TODO bug 1228504 Take all IP addresses in PresentationChannelDescription
- // into account. And at the first stage Presentation API is only exposed on
- // Firefox OS where the first IP appears enough for most scenarios.
-
- nsAutoString ip;
- ip.Assign(ips[0]);
-
- // On Android platform, the IP address is retrieved from a callback function.
- // To make consistent code sequence, following function call is dispatched
- // into main thread instead of calling it directly.
- NS_DispatchToMainThread(
- NewRunnableMethod<nsCString>(
- this,
- &PresentationControllingInfo::OnGetAddress,
- NS_ConvertUTF16toUTF8(ip)));
-
- NS_Free(prefixes);
- NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, ips);
-
-#elif defined(MOZ_WIDGET_ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
RefPtr<PresentationNetworkHelper> networkHelper =
new PresentationNetworkHelper(this,
&PresentationControllingInfo::OnGetAddress);
diff --git a/dom/presentation/provider/PresentationDeviceProviderModule.cpp b/dom/presentation/provider/PresentationDeviceProviderModule.cpp
index 9100fa49b..9c084e7db 100644
--- a/dom/presentation/provider/PresentationDeviceProviderModule.cpp
+++ b/dom/presentation/provider/PresentationDeviceProviderModule.cpp
@@ -68,12 +68,9 @@ static const mozilla::Module::ContractIDEntry kPresentationDeviceProviderContrac
};
static const mozilla::Module::CategoryEntry kPresentationDeviceProviderCategories[] = {
-#if defined(MOZ_WIDGET_COCOA) || defined(MOZ_WIDGET_ANDROID) || (defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 16)
+#if defined(MOZ_WIDGET_COCOA) || defined(MOZ_WIDGET_ANDROID)
{ PRESENTATION_DEVICE_PROVIDER_CATEGORY, "MulticastDNSDeviceProvider", MULTICAST_DNS_PROVIDER_CONTRACT_ID },
#endif
-#if defined(MOZ_WIDGET_GONK)
- { PRESENTATION_DEVICE_PROVIDER_CATEGORY, "DisplayDeviceProvider", DISPLAY_DEVICE_PROVIDER_CONTRACT_ID },
-#endif
#ifdef MOZ_WIDGET_ANDROID
{ PRESENTATION_DEVICE_PROVIDER_CATEGORY, "LegacyMDNSDeviceProvider", LEGACY_MDNS_PROVIDER_CONTRACT_ID },
#endif //MOZ_WIDGET_ANDROID
diff --git a/dom/secureelement/SEUtils.jsm b/dom/secureelement/SEUtils.jsm
deleted file mode 100644
index d5980b19c..000000000
--- a/dom/secureelement/SEUtils.jsm
+++ /dev/null
@@ -1,116 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Copyright © 2015, Deutsche Telekom, Inc. */
-
-"use strict";
-
-this.SEUtils = {
- byteArrayToHexString: function byteArrayToHexString(array) {
- let hexStr = "";
-
- let len = array ? array.length : 0;
- for (let i = 0; i < len; i++) {
- let hex = (array[i] & 0xff).toString(16);
- hex = (hex.length === 1) ? "0" + hex : hex;
- hexStr += hex;
- }
-
- return hexStr.toUpperCase();
- },
-
- hexStringToByteArray: function hexStringToByteArray(hexStr) {
- if (typeof hexStr !== "string" || hexStr.length % 2 !== 0) {
- return [];
- }
-
- let array = [];
- for (let i = 0, len = hexStr.length; i < len; i += 2) {
- array.push(parseInt(hexStr.substr(i, 2), 16));
- }
-
- return array;
- },
-
- arraysEqual: function arraysEqual(a1, a2) {
- if (!a1 || !a2) {
- return false;
- }
-
- if (a1.length !== a2.length) {
- return false;
- }
-
- for (let i = 0, len = a1.length; i < len; i++) {
- if (a1[i] !== a2[i]) {
- return false;
- }
- }
-
- return true;
- },
-
- ensureIsArray: function ensureIsArray(obj) {
- return Array.isArray(obj) ? obj : [obj];
- },
-
- /**
- * parseTLV is intended primarily to be used to parse Global Platform Device
- * Technology secure element access control data.
- *
- * The parsed result value is an internal format only.
- *
- * All tags will be treated as simple Tag Length Values (TLV), (i.e. with a
- * plain value, not subject to further unpacking), unless those tags are
- * listed in the containerTags array.
- *
- * @param bytes - byte array
- * @param containerTags - byte array of tags
- */
- parseTLV: function parseTLV(bytes, containerTags) {
- let result = {};
-
- if (typeof bytes === "string") {
- bytes = this.hexStringToByteArray(bytes);
- }
-
- if (!Array.isArray(bytes)) {
- debug("Passed value is not an array nor a string.");
- return null;
- }
-
- for (let pos = 0; pos < bytes.length; ) {
- let tag = bytes[pos],
- length = bytes[pos + 1],
- value = bytes.slice(pos + 2, pos + 2 + length),
- parsed = null;
-
- // Support for 0xFF padded files (GPD 7.1.2)
- if (tag === 0xFF) {
- break;
- }
-
- if (containerTags.indexOf(tag) >= 0) {
- parsed = this.parseTLV(value, containerTags);
- } else {
- parsed = value;
- }
-
- // Internal parsed format.
- if (!result[tag]) {
- result[tag] = parsed;
- } else if (Array.isArray(result[tag])) {
- result[tag].push(parsed);
- } else {
- result[tag] = [result[tag], parsed];
- }
-
- pos = pos + 2 + length;
- }
-
- return result;
- }
-};
-
-this.EXPORTED_SYMBOLS = ["SEUtils"];
diff --git a/dom/secureelement/gonk/ACEService.js b/dom/secureelement/gonk/ACEService.js
deleted file mode 100644
index b52ba5fab..000000000
--- a/dom/secureelement/gonk/ACEService.js
+++ /dev/null
@@ -1,139 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Copyright © 2015, Deutsche Telekom, Inc. */
-
-"use strict";
-
-const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-XPCOMUtils.defineLazyModuleGetter(this, "SEUtils",
- "resource://gre/modules/SEUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "SE", function() {
- let obj = {};
- Cu.import("resource://gre/modules/se_consts.js", obj);
- return obj;
-});
-
-var DEBUG = SE.DEBUG_ACE;
-function debug(msg) {
- if (DEBUG) {
- dump("ACEservice: " + msg + "\n");
- }
-}
-
-/**
- * Implements decision making algorithm as described in GPD specification,
- * mostly in 3.1, 3.2 and 4.2.3.
- *
- * TODO: Bug 1137533: Implement GPAccessRulesManager APDU filters
- */
-function GPAccessDecision(rules, certHash, aid) {
- this.rules = rules;
- this.certHash = certHash;
- this.aid = aid;
-}
-
-GPAccessDecision.prototype = {
- isAccessAllowed: function isAccessAllowed() {
- // GPD SE Access Control v1.1, 3.4.1, Table 3-2: (Conflict resolution)
- // If a specific rule allows, all other non-specific access is denied.
- // Conflicting specific rules will resolve to the first Allowed == "true"
- // match. Given no specific rule, the global "All" rules will determine
- // access. "Some", skips further processing if access Allowed == "true".
- //
- // Access must be decided before the SE connector openChannel, and the
- // exchangeAPDU call.
- //
- // NOTE: This implementation may change with the introduction of APDU
- // filters.
- let decision = this.rules.some(this._decideAppAccess.bind(this));
- return decision;
- },
-
- _decideAppAccess: function _decideAppAccess(rule) {
- let appMatched, appletMatched;
-
- // GPD SE AC 4.2.3: Algorithm for Applying Rules
- // Specific rule overrides global rule.
- //
- // DeviceAppID is the application hash, and the AID is SE Applet ID:
- //
- // GPD SE AC 4.2.3 A:
- // SearchRuleFor(DeviceAppID, AID)
- // GPD SE AC 4.2.3 B: If no rule fits A:
- // SearchRuleFor(<AllDeviceApplications>, AID)
- // GPD SE AC 4.2.3 C: If no rule fits A or B:
- // SearchRuleFor(DeviceAppID, <AllSEApplications>)
- // GPD SE AC 4.2.3 D: If no rule fits A, B, or C:
- // SearchRuleFor(<AllDeviceApplications>, <AllSEApplications>)
-
- // Device App
- appMatched = Array.isArray(rule.application) ?
- // GPD SE AC 4.2.3 A and 4.2.3 C (DeviceAppID rule)
- this._appCertHashMatches(rule.application) :
- // GPD SE AC 4.2.3 B and 4.2.3 D (All Device Applications)
- rule.application === Ci.nsIAccessRulesManager.ALLOW_ALL;
-
- if (!appMatched) {
- return false; // bail out early.
- }
-
- // SE Applet
- appletMatched = Array.isArray(rule.applet) ?
- // GPD SE AC 4.2.3 A and 4.2.3 B (AID rule)
- SEUtils.arraysEqual(rule.applet, this.aid) :
- // GPD SE AC 4.2.3 C and 4.2.3 D (All AID)
- rule.applet === Ci.nsIAccessRulesManager.ALL_APPLET;
-
- return appletMatched;
- },
-
- _appCertHashMatches: function _appCertHashMatches(hashArray) {
- if (!Array.isArray(hashArray)) {
- return false;
- }
-
- return !!(hashArray.find((hash) => {
- return SEUtils.arraysEqual(hash, this.certHash);
- }));
- }
-};
-
-function ACEService() {
- this._rulesManagers = new Map();
-
- this._rulesManagers.set(
- SE.TYPE_UICC,
- Cc["@mozilla.org/secureelement/access-control/rules-manager;1"]
- .createInstance(Ci.nsIAccessRulesManager));
-}
-
-ACEService.prototype = {
- _rulesManagers: null,
-
- isAccessAllowed: function isAccessAllowed(localId, seType, aid) {
- if(!Services.prefs.getBoolPref("devtools.debugger.forbid-certified-apps")) {
- debug("Certified apps debug enabled, allowing access");
- return Promise.resolve(true);
- }
-
- throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
- },
-
- _getDevCertHashForApp: function getDevCertHashForApp(manifestURL) {
- throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
- },
-
- classID: Components.ID("{882a7463-2ca7-4d61-a89a-10eb6fd70478}"),
- contractID: "@mozilla.org/secureelement/access-control/ace;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessControlEnforcer])
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([ACEService]);
-
diff --git a/dom/secureelement/gonk/ACEService.manifest b/dom/secureelement/gonk/ACEService.manifest
deleted file mode 100644
index 40949c83d..000000000
--- a/dom/secureelement/gonk/ACEService.manifest
+++ /dev/null
@@ -1,2 +0,0 @@
-component {882a7463-2ca7-4d61-a89a-10eb6fd70478} ACEService.js
-contract @mozilla.org/secureelement/access-control/ace;1 {882a7463-2ca7-4d61-a89a-10eb6fd70478} \ No newline at end of file
diff --git a/dom/secureelement/gonk/GPAccessRulesManager.js b/dom/secureelement/gonk/GPAccessRulesManager.js
deleted file mode 100644
index dce11ec09..000000000
--- a/dom/secureelement/gonk/GPAccessRulesManager.js
+++ /dev/null
@@ -1,436 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Copyright © 2015, Deutsche Telekom, Inc. */
-
-"use strict";
-
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/Task.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-
-XPCOMUtils.defineLazyServiceGetter(this, "UiccConnector",
- "@mozilla.org/secureelement/connector/uicc;1",
- "nsISecureElementConnector");
-
-XPCOMUtils.defineLazyModuleGetter(this, "SEUtils",
- "resource://gre/modules/SEUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "SE", function() {
- let obj = {};
- Cu.import("resource://gre/modules/se_consts.js", obj);
- return obj;
-});
-
-XPCOMUtils.defineLazyGetter(this, "GP", function() {
- let obj = {};
- Cu.import("resource://gre/modules/gp_consts.js", obj);
- return obj;
-});
-
-var DEBUG = SE.DEBUG_ACE;
-function debug(msg) {
- if (DEBUG) {
- dump("-*- GPAccessRulesManager " + msg);
- }
-}
-
-/**
- * Based on [1] - "GlobalPlatform Device Technology
- * Secure Element Access Control Version 1.0".
- * GPAccessRulesManager reads and parses access rules from SE file system
- * as defined in section #7 of [1]: "Structure of Access Rule Files (ARF)".
- * Rules retrieval from ARA-M applet is not implmented due to lack of
- * commercial implemenations of ARA-M.
- * @todo Bug 1137537: Implement ARA-M support according to section #4 of [1]
- */
-function GPAccessRulesManager() {}
-
-GPAccessRulesManager.prototype = {
- // source [1] section 7.1.3 PKCS#15 Selection
- PKCS_AID: "a000000063504b43532d3135",
-
- // APDUs (ISO 7816-4) for accessing rules on SE file system
- // see for more details: http://www.cardwerk.com/smartcards/
- // smartcard_standard_ISO7816-4_6_basic_interindustry_commands.aspx
- READ_BINARY: [GP.CLA_SM, GP.INS_RB, GP.P1_RB, GP.P2_RB],
- GET_RESPONSE: [GP.CLA_SM, GP.INS_GR, GP.P1_GR, GP.P2_GR],
- SELECT_BY_DF: [GP.CLA_SM, GP.INS_SF, GP.P1_SF_DF, GP.P2_SF_FCP],
-
- // Non-null if there is a channel open
- channel: null,
-
- // Refresh tag path in the acMain file as described in GPD spec,
- // sections 7.1.5 and C.1.
- REFRESH_TAG_PATH: [GP.TAG_SEQUENCE, GP.TAG_OCTETSTRING],
- refreshTag: null,
-
- // Contains rules as read from the SE
- rules: [],
-
- // Returns the latest rules. Results are cached.
- getAccessRules: function getAccessRules() {
- debug("getAccessRules");
-
- return new Promise((resolve, reject) => {
- this._readAccessRules(() => resolve(this.rules));
- });
- },
-
- _readAccessRules: Task.async(function*(done) {
- try {
- yield this._openChannel(this.PKCS_AID);
-
- let odf = yield this._readODF();
- let dodf = yield this._readDODF(odf);
-
- let acmf = yield this._readACMF(dodf);
- let refreshTag = acmf[this.REFRESH_TAG_PATH[0]]
- [this.REFRESH_TAG_PATH[1]];
-
- // Update cached rules based on refreshTag.
- if (SEUtils.arraysEqual(this.refreshTag, refreshTag)) {
- debug("_readAccessRules: refresh tag equals to the one saved.");
- yield this._closeChannel();
- return done();
- }
-
- this.refreshTag = refreshTag;
- debug("_readAccessRules: refresh tag saved: " + this.refreshTag);
-
- let acrf = yield this._readACRules(acmf);
- let accf = yield this._readACConditions(acrf);
- this.rules = yield this._parseRules(acrf, accf);
-
- DEBUG && debug("_readAccessRules: " + JSON.stringify(this.rules, 0, 2));
-
- yield this._closeChannel();
- done();
- } catch (error) {
- debug("_readAccessRules: " + error);
- this.rules = [];
- yield this._closeChannel();
- done();
- }
- }),
-
- _openChannel: function _openChannel(aid) {
- if (this.channel !== null) {
- debug("_openChannel: Channel already opened, rejecting.");
- return Promise.reject();
- }
-
- return new Promise((resolve, reject) => {
- UiccConnector.openChannel(aid, {
- notifyOpenChannelSuccess: (channel, openResponse) => {
- debug("_openChannel/notifyOpenChannelSuccess: Channel " + channel +
- " opened, open response: " + openResponse);
- this.channel = channel;
- resolve();
- },
- notifyError: (error) => {
- debug("_openChannel/notifyError: failed to open channel, error: " +
- error);
- reject(error);
- }
- });
- });
- },
-
- _closeChannel: function _closeChannel() {
- if (this.channel === null) {
- debug("_closeChannel: Channel not opened, rejecting.");
- return Promise.reject();
- }
-
- return new Promise((resolve, reject) => {
- UiccConnector.closeChannel(this.channel, {
- notifyCloseChannelSuccess: () => {
- debug("_closeChannel/notifyCloseChannelSuccess: chanel " +
- this.channel + " closed");
- this.channel = null;
- resolve();
- },
- notifyError: (error) => {
- debug("_closeChannel/notifyError: error closing channel, error" +
- error);
- reject(error);
- }
- });
- });
- },
-
- _exchangeAPDU: function _exchangeAPDU(bytes) {
- DEBUG && debug("apdu " + JSON.stringify(bytes));
-
- let apdu = this._bytesToAPDU(bytes);
- return new Promise((resolve, reject) => {
- UiccConnector.exchangeAPDU(this.channel, apdu.cla,
- apdu.ins, apdu.p1, apdu.p2, apdu.data, apdu.le,
- {
- notifyExchangeAPDUResponse: (sw1, sw2, data) => {
- debug("APDU response is " + sw1.toString(16) + sw2.toString(16) +
- " data: " + data);
-
- // 90 00 is "success"
- if (sw1 !== 0x90 && sw2 !== 0x00) {
- debug("rejecting APDU response");
- reject(new Error("Response " + sw1 + "," + sw2));
- return;
- }
-
- resolve(this._parseTLV(data));
- },
-
- notifyError: (error) => {
- debug("_exchangeAPDU/notifyError " + error);
- reject(error);
- }
- }
- );
- });
- },
-
- _readBinaryFile: function _readBinaryFile(selectResponse) {
- DEBUG && debug("Select response: " + JSON.stringify(selectResponse));
- // 0x80 tag parameter - get the elementary file (EF) length
- // without structural information.
- let fileLength = selectResponse[GP.TAG_FCP][0x80];
-
- // If file is empty, no need to attempt to read it.
- if (fileLength[0] === 0 && fileLength[1] === 0) {
- return Promise.resolve(null);
- }
-
- // TODO READ BINARY with filelength not supported
- // let readApdu = this.READ_BINARY.concat(fileLength);
- return this._exchangeAPDU(this.READ_BINARY);
- },
-
- _selectAndRead: function _selectAndRead(df) {
- return this._exchangeAPDU(this.SELECT_BY_DF.concat(df.length & 0xFF, df))
- .then((resp) => this._readBinaryFile(resp));
- },
-
- _readODF: function _readODF() {
- debug("_readODF");
- return this._selectAndRead(GP.ODF_DF);
- },
-
- _readDODF: function _readDODF(odfFile) {
- debug("_readDODF, ODF file: " + odfFile);
-
- // Data Object Directory File (DODF) is used as an entry point to the
- // Access Control data. It is specified in PKCS#15 section 6.7.6.
- // DODF is referenced by the ODF file, which looks as follows:
- // A7 06
- // 30 04
- // 04 02 XY WZ
- // where [0xXY, 0xWZ] is a DF of DODF file.
- let DODF_DF = odfFile[GP.TAG_EF_ODF][GP.TAG_SEQUENCE][GP.TAG_OCTETSTRING];
- return this._selectAndRead(DODF_DF);
- },
-
- _readACMF: function _readACMF(dodfFile) {
- debug("_readACMF, DODF file: " + dodfFile);
-
- // ACMF file DF is referenced in DODF file, which looks like this:
- //
- // A1 29
- // 30 00
- // 30 0F
- // 0C 0D 47 50 20 53 45 20 41 63 63 20 43 74 6C
- // A1 14
- // 30 12
- // 06 0A 2A 86 48 86 FC 6B 81 48 01 01 <-- GPD registered OID
- // 30 04
- // 04 02 AB CD <-- ACMF DF
- // A1 2B
- // 30 00
- // 30 0F
- // 0C 0D 53 41 54 53 41 20 47 54 4F 20 31 2E 31
- // A1 16
- // 30 14
- // 06 0C 2B 06 01 04 01 2A 02 6E 03 01 01 01 <-- some other OID
- // 30 04
- // 04 02 XY WZ <-- some other file's DF
- //
- // DODF file consists of DataTypes with oidDO entries. Entry with OID
- // equal to "1.2.840.114283.200.1.1" ("2A 86 48 86 FC 6B 81 48 01 01")
- // contains DF of the ACMF. In the file above, it means that ACMF DF
- // equals to [0xAB, 0xCD], and not [0xXY, 0xWZ].
- //
- // Algorithm used to encode OID to an byte array:
- // http://www.snmpsharpnet.com/?p=153
-
- let gpdOid = [0x2A, // 1.2
- 0x86, 0x48, // 840
- 0x86, 0xFC, 0x6B, // 114283
- 0x81, 0x48, // 129
- 0x01, // 1
- 0x01]; // 1
-
- let records = SEUtils.ensureIsArray(dodfFile[GP.TAG_EXTERNALDO]);
-
- // Look for the OID registered for GPD SE.
- let gpdRecords = records.filter((record) => {
- let oid = record[GP.TAG_EXTERNALDO][GP.TAG_SEQUENCE][GP.TAG_OID];
- return SEUtils.arraysEqual(oid, gpdOid);
- });
-
- // [1] 7.1.5: "There shall be only one ACMF file per Secure Element.
- // If a Secure Element contains several ACMF files, then the security shall
- // be considered compromised and the Access Control enforcer shall forbid
- // access to all (...) apps."
- if (gpdRecords.length !== 1) {
- return Promise.reject(new Error(gpdRecords.length + " ACMF files found"));
- }
-
- let ACMain_DF = gpdRecords[0][GP.TAG_EXTERNALDO][GP.TAG_SEQUENCE]
- [GP.TAG_SEQUENCE][GP.TAG_OCTETSTRING];
- return this._selectAndRead(ACMain_DF);
- },
-
- _readACRules: function _readACRules(acMainFile) {
- debug("_readACRules, ACMain file: " + acMainFile);
-
- // ACMF looks like this:
- //
- // 30 10
- // 04 08 XX XX XX XX XX XX XX XX
- // 30 04
- // 04 02 XY WZ
- //
- // where [XY, WZ] is a DF of ACRF, and XX XX XX XX XX XX XX XX is a refresh
- // tag.
-
- let ACRules_DF = acMainFile[GP.TAG_SEQUENCE][GP.TAG_SEQUENCE][GP.TAG_OCTETSTRING];
- return this._selectAndRead(ACRules_DF);
- },
-
- _readACConditions: function _readACConditions(acRulesFile) {
- debug("_readACCondition, ACRules file: " + acRulesFile);
-
- let acRules = SEUtils.ensureIsArray(acRulesFile[GP.TAG_SEQUENCE]);
- if (acRules.length === 0) {
- debug("No rules found in ACRules file.");
- return Promise.reject(new Error("No rules found in ACRules file"));
- }
-
- // We first read all the condition files referenced in the ACRules file,
- // because ACRules file might reference one ACCondition file more than
- // once. Since reading it isn't exactly fast, we optimize here.
- let acReadQueue = Promise.resolve({});
-
- acRules.forEach((ruleEntry) => {
- let df = ruleEntry[GP.TAG_SEQUENCE][GP.TAG_OCTETSTRING];
-
- // Promise chain read condition entries:
- let readAcCondition = (acConditionFiles) => {
- if (acConditionFiles[df] !== undefined) {
- debug("Skipping previously read acCondition df: " + df);
- return acConditionFiles;
- }
-
- return this._selectAndRead(df)
- .then((acConditionFileContents) => {
- acConditionFiles[df] = acConditionFileContents;
- return acConditionFiles;
- });
- }
-
- acReadQueue = acReadQueue.then(readAcCondition);
- });
-
- return acReadQueue;
- },
-
- _parseRules: function _parseRules(acRulesFile, acConditionFiles) {
- DEBUG && debug("_parseRules: acConditionFiles " + JSON.stringify(acConditionFiles));
- let rules = [];
-
- let acRules = SEUtils.ensureIsArray(acRulesFile[GP.TAG_SEQUENCE]);
- acRules.forEach((ruleEntry) => {
- DEBUG && debug("Parsing one rule: " + JSON.stringify(ruleEntry));
- let rule = {};
-
- // 0xA0 and 0x82 tags as per GPD spec sections C.1 - C.3. 0xA0 means
- // that rule describes access to one SE applet only (and its AID is
- // given). 0x82 means that rule describes acccess to all SE applets.
- let oneApplet = ruleEntry[GP.TAG_GPD_AID];
- let allApplets = ruleEntry[GP.TAG_GPD_ALL];
-
- if (oneApplet) {
- rule.applet = oneApplet[GP.TAG_OCTETSTRING];
- } else if (allApplets) {
- rule.applet = Ci.nsIAccessRulesManager.ALL_APPLET;
- } else {
- throw Error("Unknown applet definition");
- }
-
- let df = ruleEntry[GP.TAG_SEQUENCE][GP.TAG_OCTETSTRING];
- let condition = acConditionFiles[df];
- if (condition === null) {
- rule.application = Ci.nsIAccessRulesManager.DENY_ALL;
- } else if (condition[GP.TAG_SEQUENCE]) {
- if (!Array.isArray(condition[GP.TAG_SEQUENCE]) &&
- !condition[GP.TAG_SEQUENCE][GP.TAG_OCTETSTRING]) {
- rule.application = Ci.nsIAccessRulesManager.ALLOW_ALL;
- } else {
- rule.application = SEUtils.ensureIsArray(condition[GP.TAG_SEQUENCE])
- .map((conditionEntry) => {
- return conditionEntry[GP.TAG_OCTETSTRING];
- });
- }
- } else {
- throw Error("Unknown application definition");
- }
-
- DEBUG && debug("Rule parsed, adding to the list: " + JSON.stringify(rule));
- rules.push(rule);
- });
-
- DEBUG && debug("All rules parsed, we have those in total: " + JSON.stringify(rules));
- return rules;
- },
-
- _parseTLV: function _parseTLV(bytes) {
- let containerTags = [
- GP.TAG_SEQUENCE,
- GP.TAG_FCP,
- GP.TAG_GPD_AID,
- GP.TAG_EXTERNALDO,
- GP.TAG_INDIRECT,
- GP.TAG_EF_ODF
- ];
- return SEUtils.parseTLV(bytes, containerTags);
- },
-
- // TODO consider removing if better format for storing
- // APDU consts will be introduced
- _bytesToAPDU: function _bytesToAPDU(arr) {
- let apdu = {
- cla: arr[0] & 0xFF,
- ins: arr[1] & 0xFF,
- p1: arr[2] & 0xFF,
- p2: arr[3] & 0xFF,
- p3: arr[4] & 0xFF,
- le: 0
- };
-
- let data = (apdu.p3 > 0) ? (arr.slice(5)) : [];
- apdu.data = (data.length) ? SEUtils.byteArrayToHexString(data) : null;
- return apdu;
- },
-
- classID: Components.ID("{3e046b4b-9e66-439a-97e0-98a69f39f55f}"),
- contractID: "@mozilla.org/secureelement/access-control/rules-manager;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIAccessRulesManager])
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([GPAccessRulesManager]);
diff --git a/dom/secureelement/gonk/GPAccessRulesManager.manifest b/dom/secureelement/gonk/GPAccessRulesManager.manifest
deleted file mode 100644
index 2d7ea038b..000000000
--- a/dom/secureelement/gonk/GPAccessRulesManager.manifest
+++ /dev/null
@@ -1,2 +0,0 @@
-component {3e046b4b-9e66-439a-97e0-98a69f39f55f} GPAccessRulesManager.js
-contract @mozilla.org/secureelement/access-control/rules-manager;1 {3e046b4b-9e66-439a-97e0-98a69f39f55f}
diff --git a/dom/secureelement/gonk/SecureElement.js b/dom/secureelement/gonk/SecureElement.js
deleted file mode 100644
index 144c6d8d6..000000000
--- a/dom/secureelement/gonk/SecureElement.js
+++ /dev/null
@@ -1,514 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* Copyright © 2014, Deutsche Telekom, Inc. */
-
-"use strict";
-
-/* globals dump, Components, XPCOMUtils, SE, Services, UiccConnector,
- SEUtils, ppmm, gMap, UUIDGenerator */
-
-const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-
-XPCOMUtils.defineLazyGetter(this, "SE", () => {
- let obj = {};
- Cu.import("resource://gre/modules/se_consts.js", obj);
- return obj;
-});
-
-// set to true in se_consts.js to see debug messages
-var DEBUG = SE.DEBUG_SE;
-function debug(s) {
- if (DEBUG) {
- dump("-*- SecureElement: " + s + "\n");
- }
-}
-
-const SE_IPC_SECUREELEMENT_MSG_NAMES = [
- "SE:GetSEReaders",
- "SE:OpenChannel",
- "SE:CloseChannel",
- "SE:TransmitAPDU"
-];
-
-const SECUREELEMENTMANAGER_CONTRACTID =
- "@mozilla.org/secureelement/parent-manager;1";
-const SECUREELEMENTMANAGER_CID =
- Components.ID("{48f4e650-28d2-11e4-8c21-0800200c9a66}");
-const NS_XPCOM_SHUTDOWN_OBSERVER_ID = "xpcom-shutdown";
-
-XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
- "@mozilla.org/parentprocessmessagemanager;1",
- "nsIMessageBroadcaster");
-
-XPCOMUtils.defineLazyServiceGetter(this, "UUIDGenerator",
- "@mozilla.org/uuid-generator;1",
- "nsIUUIDGenerator");
-
-XPCOMUtils.defineLazyModuleGetter(this, "SEUtils",
- "resource://gre/modules/SEUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "UiccConnector", () => {
- let uiccClass = Cc["@mozilla.org/secureelement/connector/uicc;1"];
- return uiccClass ? uiccClass.getService(Ci.nsISecureElementConnector) : null;
-});
-
-function getConnector(type) {
- switch (type) {
- case SE.TYPE_UICC:
- return UiccConnector;
- case SE.TYPE_ESE:
- default:
- debug("Unsupported SEConnector : " + type);
- return null;
- }
-}
-
-/**
- * 'gMap' is a nested dictionary object that manages all the information
- * pertaining to channels for a given application (appId). It manages the
- * relationship between given application and its opened channels.
- */
-XPCOMUtils.defineLazyGetter(this, "gMap", function() {
- return {
- // example structure of AppInfoMap
- // {
- // "appId1": {
- // target: target1,
- // channels: {
- // "channelToken1": {
- // seType: "uicc",
- // aid: "aid1",
- // channelNumber: 1
- // },
- // "channelToken2": { ... }
- // }
- // },
- // "appId2": { ... }
- // }
- appInfoMap: {},
-
- registerSecureElementTarget: function(appId, target) {
- if (this.isAppIdRegistered(appId)) {
- debug("AppId: " + appId + "already registered");
- return;
- }
-
- this.appInfoMap[appId] = {
- target: target,
- channels: {}
- };
-
- debug("Registered a new SE target " + appId);
- },
-
- unregisterSecureElementTarget: function(target) {
- let appId = Object.keys(this.appInfoMap).find((id) => {
- return this.appInfoMap[id].target === target;
- });
-
- if (!appId) {
- return;
- }
-
- debug("Unregistered SE Target for AppId: " + appId);
- delete this.appInfoMap[appId];
- },
-
- isAppIdRegistered: function(appId) {
- return this.appInfoMap[appId] !== undefined;
- },
-
- getChannelCountByAppIdType: function(appId, type) {
- return Object.keys(this.appInfoMap[appId].channels)
- .reduce((cnt, ch) => ch.type === type ? ++cnt : cnt, 0);
- },
-
- // Add channel to the appId. Upon successfully adding the entry
- // this function will return the 'token'
- addChannel: function(appId, type, aid, channelNumber) {
- let token = UUIDGenerator.generateUUID().toString();
- this.appInfoMap[appId].channels[token] = {
- seType: type,
- aid: aid,
- channelNumber: channelNumber
- };
- return token;
- },
-
- removeChannel: function(appId, channelToken) {
- if (this.appInfoMap[appId].channels[channelToken]) {
- debug("Deleting channel with token : " + channelToken);
- delete this.appInfoMap[appId].channels[channelToken];
- }
- },
-
- getChannel: function(appId, channelToken) {
- if (!this.appInfoMap[appId].channels[channelToken]) {
- return null;
- }
-
- return this.appInfoMap[appId].channels[channelToken];
- },
-
- getChannelsByTarget: function(target) {
- let appId = Object.keys(this.appInfoMap).find((id) => {
- return this.appInfoMap[id].target === target;
- });
-
- if (!appId) {
- return [];
- }
-
- return Object.keys(this.appInfoMap[appId].channels)
- .map(token => this.appInfoMap[appId].channels[token]);
- },
-
- getTargets: function() {
- return Object.keys(this.appInfoMap)
- .map(appId => this.appInfoMap[appId].target);
- },
- };
-});
-
-/**
- * 'SecureElementManager' is the main object that handles IPC messages from
- * child process. It interacts with other objects such as 'gMap' & 'Connector
- * instances (UiccConnector, eSEConnector)' to perform various
- * SE-related (open, close, transmit) operations.
- * @TODO: Bug 1118097 Support slot based SE/reader names
- * @TODO: Bug 1118101 Introduce SE type specific permissions
- */
-function SecureElementManager() {
- this._registerMessageListeners();
- this._registerSEListeners();
- Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
- this._acEnforcer =
- Cc["@mozilla.org/secureelement/access-control/ace;1"]
- .getService(Ci.nsIAccessControlEnforcer);
-}
-
-SecureElementManager.prototype = {
- QueryInterface: XPCOMUtils.generateQI([
- Ci.nsIMessageListener,
- Ci.nsISEListener,
- Ci.nsIObserver]),
- classID: SECUREELEMENTMANAGER_CID,
- classInfo: XPCOMUtils.generateCI({
- classID: SECUREELEMENTMANAGER_CID,
- classDescription: "SecureElementManager",
- interfaces: [Ci.nsIMessageListener,
- Ci.nsISEListener,
- Ci.nsIObserver]
- }),
-
- // Stores information about supported SE types and their presence.
- // key: secure element type, value: (Boolean) is present/accessible
- _sePresence: {},
-
- _acEnforcer: null,
-
- _shutdown: function() {
- this._acEnforcer = null;
- this.secureelement = null;
- Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
- this._unregisterMessageListeners();
- this._unregisterSEListeners();
- },
-
- _registerMessageListeners: function() {
- ppmm.addMessageListener("child-process-shutdown", this);
- for (let msgname of SE_IPC_SECUREELEMENT_MSG_NAMES) {
- ppmm.addMessageListener(msgname, this);
- }
- },
-
- _unregisterMessageListeners: function() {
- ppmm.removeMessageListener("child-process-shutdown", this);
- for (let msgname of SE_IPC_SECUREELEMENT_MSG_NAMES) {
- ppmm.removeMessageListener(msgname, this);
- }
- ppmm = null;
- },
-
- _registerSEListeners: function() {
- let connector = getConnector(SE.TYPE_UICC);
- if (!connector) {
- return;
- }
-
- this._sePresence[SE.TYPE_UICC] = false;
- connector.registerListener(this);
- },
-
- _unregisterSEListeners: function() {
- Object.keys(this._sePresence).forEach((type) => {
- let connector = getConnector(type);
- if (connector) {
- connector.unregisterListener(this);
- }
- });
-
- this._sePresence = {};
- },
-
- notifySEPresenceChanged: function(type, isPresent) {
- // we need to notify all targets, even those without open channels,
- // app could've stored the reader without actually using it
- debug("notifying DOM about SE state change");
- this._sePresence[type] = isPresent;
- gMap.getTargets().forEach(target => {
- let result = { type: type, isPresent: isPresent };
- target.sendAsyncMessage("SE:ReaderPresenceChanged", { result: result });
- });
- },
-
- _canOpenChannel: function(appId, type) {
- let opened = gMap.getChannelCountByAppIdType(appId, type);
- let limit = SE.MAX_CHANNELS_ALLOWED_PER_SESSION;
- // UICC basic channel is not accessible see comment in se_consts.js
- limit = type === SE.TYPE_UICC ? limit - 1 : limit;
- return opened < limit;
- },
-
- _handleOpenChannel: function(msg, callback) {
- if (!this._canOpenChannel(msg.appId, msg.type)) {
- debug("Max channels per session exceed");
- callback({ error: SE.ERROR_GENERIC });
- return;
- }
-
- let connector = getConnector(msg.type);
- if (!connector) {
- debug("No SE connector available");
- callback({ error: SE.ERROR_NOTPRESENT });
- return;
- }
-
- this._acEnforcer.isAccessAllowed(msg.appId, msg.type, msg.aid)
- .then((allowed) => {
- if (!allowed) {
- callback({ error: SE.ERROR_SECURITY });
- return;
- }
- connector.openChannel(SEUtils.byteArrayToHexString(msg.aid), {
-
- notifyOpenChannelSuccess: (channelNumber, openResponse) => {
- // Add the new 'channel' to the map upon success
- let channelToken =
- gMap.addChannel(msg.appId, msg.type, msg.aid, channelNumber);
- if (channelToken) {
- callback({
- error: SE.ERROR_NONE,
- channelToken: channelToken,
- isBasicChannel: (channelNumber === SE.BASIC_CHANNEL),
- openResponse: SEUtils.hexStringToByteArray(openResponse)
- });
- } else {
- callback({ error: SE.ERROR_GENERIC });
- }
- },
-
- notifyError: (reason) => {
- debug("Failed to open the channel to AID : " +
- SEUtils.byteArrayToHexString(msg.aid) +
- ", Rejected with Reason : " + reason);
- callback({ error: SE.ERROR_GENERIC, reason: reason, response: [] });
- }
- });
- })
- .catch((error) => {
- debug("Failed to get info from accessControlEnforcer " + error);
- callback({ error: SE.ERROR_SECURITY });
- });
- },
-
- _handleTransmit: function(msg, callback) {
- let channel = gMap.getChannel(msg.appId, msg.channelToken);
- if (!channel) {
- debug("Invalid token:" + msg.channelToken + ", appId: " + msg.appId);
- callback({ error: SE.ERROR_GENERIC });
- return;
- }
-
- let connector = getConnector(channel.seType);
- if (!connector) {
- debug("No SE connector available");
- callback({ error: SE.ERROR_NOTPRESENT });
- return;
- }
-
- // Bug 1137533 - ACE GPAccessRulesManager APDU filters
- connector.exchangeAPDU(channel.channelNumber, msg.apdu.cla, msg.apdu.ins,
- msg.apdu.p1, msg.apdu.p2,
- SEUtils.byteArrayToHexString(msg.apdu.data),
- msg.apdu.le, {
- notifyExchangeAPDUResponse: (sw1, sw2, response) => {
- callback({
- error: SE.ERROR_NONE,
- sw1: sw1,
- sw2: sw2,
- response: SEUtils.hexStringToByteArray(response)
- });
- },
-
- notifyError: (reason) => {
- debug("Transmit failed, rejected with Reason : " + reason);
- callback({ error: SE.ERROR_INVALIDAPPLICATION, reason: reason });
- }
- });
- },
-
- _handleCloseChannel: function(msg, callback) {
- let channel = gMap.getChannel(msg.appId, msg.channelToken);
- if (!channel) {
- debug("Invalid token:" + msg.channelToken + ", appId:" + msg.appId);
- callback({ error: SE.ERROR_GENERIC });
- return;
- }
-
- let connector = getConnector(channel.seType);
- if (!connector) {
- debug("No SE connector available");
- callback({ error: SE.ERROR_NOTPRESENT });
- return;
- }
-
- connector.closeChannel(channel.channelNumber, {
- notifyCloseChannelSuccess: () => {
- gMap.removeChannel(msg.appId, msg.channelToken);
- callback({ error: SE.ERROR_NONE });
- },
-
- notifyError: (reason) => {
- debug("Failed to close channel with token: " + msg.channelToken +
- ", reason: "+ reason);
- callback({ error: SE.ERROR_BADSTATE, reason: reason });
- }
- });
- },
-
- _handleGetSEReadersRequest: function(msg, target, callback) {
- gMap.registerSecureElementTarget(msg.appId, target);
- let readers = Object.keys(this._sePresence).map(type => {
- return { type: type, isPresent: this._sePresence[type] };
- });
- callback({ readers: readers, error: SE.ERROR_NONE });
- },
-
- _handleChildProcessShutdown: function(target) {
- let channels = gMap.getChannelsByTarget(target);
-
- let createCb = (seType, channelNumber) => {
- return {
- notifyCloseChannelSuccess: () => {
- debug("closed " + seType + ", channel " + channelNumber);
- },
-
- notifyError: (reason) => {
- debug("Failed to close " + seType + " channel " +
- channelNumber + ", reason: " + reason);
- }
- };
- };
-
- channels.forEach((channel) => {
- let connector = getConnector(channel.seType);
- if (!connector) {
- return;
- }
-
- connector.closeChannel(channel.channelNumber,
- createCb(channel.seType, channel.channelNumber));
- });
-
- gMap.unregisterSecureElementTarget(target);
- },
-
- _sendSEResponse: function(msg, result) {
- let promiseStatus = (result.error === SE.ERROR_NONE) ? "Resolved" : "Rejected";
- result.resolverId = msg.data.resolverId;
- msg.target.sendAsyncMessage(msg.name + promiseStatus, {result: result});
- },
-
- _isValidMessage: function(msg) {
- let appIdValid = gMap.isAppIdRegistered(msg.data.appId);
- return msg.name === "SE:GetSEReaders" ? true : appIdValid;
- },
-
- /**
- * nsIMessageListener interface methods.
- */
-
- receiveMessage: function(msg) {
- DEBUG && debug("Received '" + msg.name + "' message from content process" +
- ": " + JSON.stringify(msg.data));
-
- if (msg.name === "child-process-shutdown") {
- this._handleChildProcessShutdown(msg.target);
- return null;
- }
-
- if (SE_IPC_SECUREELEMENT_MSG_NAMES.indexOf(msg.name) !== -1) {
- if (!msg.target.assertPermission("secureelement-manage")) {
- debug("SecureElement message " + msg.name + " from a content process " +
- "with no 'secureelement-manage' privileges.");
- return null;
- }
- } else {
- debug("Ignoring unknown message type: " + msg.name);
- return null;
- }
-
- let callback = (result) => this._sendSEResponse(msg, result);
- if (!this._isValidMessage(msg)) {
- debug("Message not valid");
- callback({ error: SE.ERROR_GENERIC });
- return null;
- }
-
- switch (msg.name) {
- case "SE:GetSEReaders":
- this._handleGetSEReadersRequest(msg.data, msg.target, callback);
- break;
- case "SE:OpenChannel":
- this._handleOpenChannel(msg.data, callback);
- break;
- case "SE:CloseChannel":
- this._handleCloseChannel(msg.data, callback);
- break;
- case "SE:TransmitAPDU":
- this._handleTransmit(msg.data, callback);
- break;
- }
- return null;
- },
-
- /**
- * nsIObserver interface methods.
- */
-
- observe: function(subject, topic, data) {
- if (topic === NS_XPCOM_SHUTDOWN_OBSERVER_ID) {
- this._shutdown();
- }
- }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SecureElementManager]);
diff --git a/dom/secureelement/gonk/SecureElement.manifest b/dom/secureelement/gonk/SecureElement.manifest
deleted file mode 100644
index a76fcfc11..000000000
--- a/dom/secureelement/gonk/SecureElement.manifest
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright 2012 Mozilla Foundation and Mozilla contributors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# SecureElementManager
-component {48f4e650-28d2-11e4-8c21-0800200c9a66} SecureElement.js
-contract @mozilla.org/secureelement/parent-manager;1 {48f4e650-28d2-11e4-8c21-0800200c9a66}
-category profile-after-change SecureElementManager @mozilla.org/secureelement/parent-manager;1
diff --git a/dom/secureelement/gonk/UiccConnector.js b/dom/secureelement/gonk/UiccConnector.js
deleted file mode 100644
index 517303de2..000000000
--- a/dom/secureelement/gonk/UiccConnector.js
+++ /dev/null
@@ -1,360 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* Copyright © 2014, Deutsche Telekom, Inc. */
-
-"use strict";
-
-/* globals Components, XPCOMUtils, SE, dump, libcutils, Services,
- iccService, SEUtils */
-
-const { interfaces: Ci, utils: Cu, results: Cr } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-
-XPCOMUtils.defineLazyGetter(this, "SE", function() {
- let obj = {};
- Cu.import("resource://gre/modules/se_consts.js", obj);
- return obj;
-});
-
-// set to true in se_consts.js to see debug messages
-var DEBUG = SE.DEBUG_CONNECTOR;
-function debug(s) {
- if (DEBUG) {
- dump("-*- UiccConnector: " + s + "\n");
- }
-}
-
-XPCOMUtils.defineLazyModuleGetter(this, "SEUtils",
- "resource://gre/modules/SEUtils.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "iccService",
- "@mozilla.org/icc/iccservice;1",
- "nsIIccService");
-
-const UICCCONNECTOR_CONTRACTID =
- "@mozilla.org/secureelement/connector/uicc;1";
-const UICCCONNECTOR_CID =
- Components.ID("{8e040e5d-c8c3-4c1b-ac82-c00d25d8c4a4}");
-const NS_XPCOM_SHUTDOWN_OBSERVER_ID = "xpcom-shutdown";
-
-// TODO: Bug 1118099 - Add multi-sim support.
-// In the Multi-sim, there is more than one client.
-// For now, use default clientID as 0. Ideally, SE parent process would like to
-// know which clients (uicc slot) are connected to CLF over SWP interface.
-const PREFERRED_UICC_CLIENTID =
- libcutils.property_get("ro.moz.se.def_client_id", "0");
-
-/**
- * 'UiccConnector' object is a wrapper over iccService's channel management
- * related interfaces that implements nsISecureElementConnector interface.
- */
-function UiccConnector() {
- this._init();
-}
-
-UiccConnector.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISecureElementConnector,
- Ci.nsIIccListener]),
- classID: UICCCONNECTOR_CID,
- classInfo: XPCOMUtils.generateCI({
- classID: UICCCONNECTOR_CID,
- contractID: UICCCONNECTOR_CONTRACTID,
- classDescription: "UiccConnector",
- interfaces: [Ci.nsISecureElementConnector,
- Ci.nsIIccListener,
- Ci.nsIObserver]
- }),
-
- _SEListeners: [],
- _isPresent: false,
-
- _init: function() {
- Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
- let icc = iccService.getIccByServiceId(PREFERRED_UICC_CLIENTID);
- icc.registerListener(this);
-
- // Update the state in order to avoid race condition.
- // By this time, 'notifyCardStateChanged (with proper card state)'
- // may have occurred already before this module initialization.
- this._updatePresenceState();
- },
-
- _shutdown: function() {
- Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
- let icc = iccService.getIccByServiceId(PREFERRED_UICC_CLIENTID);
- icc.unregisterListener(this);
- },
-
- _updatePresenceState: function() {
- let uiccNotReadyStates = [
- Ci.nsIIcc.CARD_STATE_UNKNOWN,
- Ci.nsIIcc.CARD_STATE_ILLEGAL,
- Ci.nsIIcc.CARD_STATE_PERSONALIZATION_IN_PROGRESS,
- Ci.nsIIcc.CARD_STATE_PERMANENT_BLOCKED,
- Ci.nsIIcc.CARD_STATE_UNDETECTED
- ];
-
- let cardState = iccService.getIccByServiceId(PREFERRED_UICC_CLIENTID).cardState;
- let uiccPresent = cardState !== null &&
- uiccNotReadyStates.indexOf(cardState) == -1;
-
- if (this._isPresent === uiccPresent) {
- return;
- }
-
- debug("Uicc presence changed " + this._isPresent + " -> " + uiccPresent);
- this._isPresent = uiccPresent;
- this._SEListeners.forEach((listener) => {
- listener.notifySEPresenceChanged(SE.TYPE_UICC, this._isPresent);
- });
- },
-
- // See GP Spec, 11.1.4 Class Byte Coding
- _setChannelToCLAByte: function(cla, channel) {
- if (channel < SE.LOGICAL_CHANNEL_NUMBER_LIMIT) {
- // b7 = 0 indicates the first interindustry class byte coding
- cla = (cla & 0x9C) & 0xFF | channel;
- } else if (channel < SE.SUPPLEMENTARY_LOGICAL_CHANNEL_NUMBER_LIMIT) {
- // b7 = 1 indicates the further interindustry class byte coding
- cla = (cla & 0xB0) & 0xFF | 0x40 | (channel - SE.LOGICAL_CHANNEL_NUMBER_LIMIT);
- } else {
- debug("Channel number must be within [0..19]");
- return SE.ERROR_GENERIC;
- }
- return cla;
- },
-
- _doGetOpenResponse: function(channel, length, callback) {
- // Le value is set. It means that this is a request for all available
- // response bytes.
- let cla = this._setChannelToCLAByte(SE.CLA_GET_RESPONSE, channel);
- this.exchangeAPDU(channel, cla, SE.INS_GET_RESPONSE, 0x00, 0x00,
- null, length, {
- notifyExchangeAPDUResponse: function(sw1, sw2, response) {
- debug("GET Response : " + response);
- if (callback) {
- callback({
- error: SE.ERROR_NONE,
- sw1: sw1,
- sw2: sw2,
- response: response
- });
- }
- },
-
- notifyError: function(reason) {
- debug("Failed to get open response: " +
- ", Rejected with Reason : " + reason);
- if (callback) {
- callback({ error: SE.ERROR_INVALIDAPPLICATION, reason: reason });
- }
- }
- });
- },
-
- _doIccExchangeAPDU: function(channel, cla, ins, p1, p2, p3,
- data, appendResp, callback) {
- let icc = iccService.getIccByServiceId(PREFERRED_UICC_CLIENTID);
- icc.iccExchangeAPDU(channel, cla & 0xFC, ins, p1, p2, p3, data, {
- notifyExchangeAPDUResponse: (sw1, sw2, response) => {
- debug("sw1 : " + sw1 + ", sw2 : " + sw2 + ", response : " + response);
-
- // According to ETSI TS 102 221 , Section 7.2.2.3.1,
- // Enforce 'Procedure bytes' checks before notifying the callback.
- // Note that 'Procedure bytes'are special cases.
- // There is no need to handle '0x60' procedure byte as it implies
- // no-action from SE stack perspective. This procedure byte is not
- // notified to application layer.
- if (sw1 === 0x6C) {
- // Use the previous command header with length as second procedure
- // byte (SW2) as received and repeat the procedure.
-
- // Recursive! and Pass empty response '' as args, since '0x6C'
- // procedure does not have to deal with appended responses.
- this._doIccExchangeAPDU(channel, cla, ins, p1, p2,
- sw2, data, "", callback);
- } else if (sw1 === 0x61) {
- // Since the terminal waited for a second procedure byte and
- // received it (sw2), send a GET RESPONSE command header to the UICC
- // with a maximum length of 'XX', where 'XX' is the value of the
- // second procedure byte (SW2).
-
- let claWithChannel = this._setChannelToCLAByte(SE.CLA_GET_RESPONSE,
- channel);
-
- // Recursive, with GET RESPONSE bytes and '0x61' procedure IS interested
- // in appended responses. Pass appended response and note that p3=sw2.
- this._doIccExchangeAPDU(channel, claWithChannel, SE.INS_GET_RESPONSE,
- 0x00, 0x00, sw2, null,
- (response ? response + appendResp : appendResp),
- callback);
- } else if (callback) {
- callback.notifyExchangeAPDUResponse(sw1, sw2, response);
- }
- },
-
- notifyError: (reason) => {
- debug("Failed to trasmit C-APDU over the channel # : " + channel +
- ", Rejected with Reason : " + reason);
- if (callback) {
- callback.notifyError(reason);
- }
- }
- });
- },
-
- /**
- * nsISecureElementConnector interface methods.
- */
-
- /**
- * Opens a channel on a default clientId
- */
- openChannel: function(aid, callback) {
- if (!this._isPresent) {
- callback.notifyError(SE.ERROR_NOTPRESENT);
- return;
- }
-
- // TODO: Bug 1118106: Handle Resource management / leaks by persisting
- // the newly opened channel in some persistent storage so that when this
- // module gets restarted (say after opening a channel) in the event of
- // some erroneous conditions such as gecko restart /, crash it can read
- // the persistent storage to check if there are any held resources
- // (opened channels) and close them.
- let icc = iccService.getIccByServiceId(PREFERRED_UICC_CLIENTID);
- icc.iccOpenChannel(aid, {
- notifyOpenChannelSuccess: (channel) => {
- this._doGetOpenResponse(channel, 0x00, function(result) {
- if (callback) {
- callback.notifyOpenChannelSuccess(channel, result.response);
- }
- });
- },
-
- notifyError: (reason) => {
- debug("Failed to open the channel to AID : " + aid +
- ", Rejected with Reason : " + reason);
- if (callback) {
- callback.notifyError(reason);
- }
- }
- });
- },
-
- /**
- * Transmit the C-APDU (command) on default clientId.
- */
- exchangeAPDU: function(channel, cla, ins, p1, p2, data, le, callback) {
- if (!this._isPresent) {
- callback.notifyError(SE.ERROR_NOTPRESENT);
- return;
- }
-
- if (data && data.length % 2 !== 0) {
- callback.notifyError("Data should be a hex string with length % 2 === 0");
- return;
- }
-
- cla = this._setChannelToCLAByte(cla, channel);
- let lc = data ? data.length / 2 : 0;
- let p3 = lc || le;
-
- if (lc && (le !== -1)) {
- data += SEUtils.byteArrayToHexString([le]);
- }
-
- // Pass empty response '' as args as we are not interested in appended
- // responses yet!
- debug("exchangeAPDU on Channel # " + channel);
- this._doIccExchangeAPDU(channel, cla, ins, p1, p2, p3, data, "",
- callback);
- },
-
- /**
- * Closes the channel on default clientId.
- */
- closeChannel: function(channel, callback) {
- if (!this._isPresent) {
- callback.notifyError(SE.ERROR_NOTPRESENT);
- return;
- }
-
- let icc = iccService.getIccByServiceId(PREFERRED_UICC_CLIENTID);
- icc.iccCloseChannel(channel, {
- notifyCloseChannelSuccess: function() {
- debug("closeChannel successfully closed the channel # : " + channel);
- if (callback) {
- callback.notifyCloseChannelSuccess();
- }
- },
-
- notifyError: function(reason) {
- debug("Failed to close the channel # : " + channel +
- ", Rejected with Reason : " + reason);
- if (callback) {
- callback.notifyError(reason);
- }
- }
- });
- },
-
- registerListener: function(listener) {
- if (this._SEListeners.indexOf(listener) !== -1) {
- throw Cr.NS_ERROR_UNEXPECTED;
- }
-
- this._SEListeners.push(listener);
- // immediately notify listener about the current state
- listener.notifySEPresenceChanged(SE.TYPE_UICC, this._isPresent);
- },
-
- unregisterListener: function(listener) {
- let idx = this._SEListeners.indexOf(listener);
- if (idx !== -1) {
- this._SEListeners.splice(idx, 1);
- }
- },
-
- /**
- * nsIIccListener interface methods.
- */
- notifyStkCommand: function() {},
-
- notifyStkSessionEnd: function() {},
-
- notifyIccInfoChanged: function() {},
-
- notifyCardStateChanged: function() {
- debug("Card state changed, updating UICC presence.");
- this._updatePresenceState();
- },
-
- /**
- * nsIObserver interface methods.
- */
-
- observe: function(subject, topic, data) {
- if (topic === NS_XPCOM_SHUTDOWN_OBSERVER_ID) {
- this._shutdown();
- }
- }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([UiccConnector]);
diff --git a/dom/secureelement/gonk/UiccConnector.manifest b/dom/secureelement/gonk/UiccConnector.manifest
deleted file mode 100644
index 5ac8b3b7b..000000000
--- a/dom/secureelement/gonk/UiccConnector.manifest
+++ /dev/null
@@ -1,17 +0,0 @@
-# Copyright 2012 Mozilla Foundation and Mozilla contributors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# UiccConnector
-component {8e040e5d-c8c3-4c1b-ac82-c00d25d8c4a4} UiccConnector.js
-contract @mozilla.org/secureelement/connector/uicc;1 {8e040e5d-c8c3-4c1b-ac82-c00d25d8c4a4}
diff --git a/dom/secureelement/gonk/gp_consts.js b/dom/secureelement/gonk/gp_consts.js
deleted file mode 100644
index 7c3bc7165..000000000
--- a/dom/secureelement/gonk/gp_consts.js
+++ /dev/null
@@ -1,62 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Copyright © 2015, Deutsche Telekom, Inc. */
-
-/* Object Directory File (ODF) is an elementary file which contain
- pointers to other EFs. It is specified in PKCS#15 section 6.7. */
-this.ODF_DF = [0x50, 0x31];
-
-/* ISO 7816-4: secure messaging */
-this.CLA_SM = 0x00;
-
-/* ISO 7816-4, 5.4.1 table 11 */
-this.INS_SF = 0xA4; // select file
-this.INS_GR = 0xC0; // get response
-this.INS_RB = 0xB0; // read binary
-
-/* ISO 7816-4: select file, see 6.11.3, table 58 & 59 */
-this.P1_SF_DF = 0x00; // select DF
-this.P2_SF_FCP = 0x04; // return FCP
-
-/* ISO 7816-4: read binary, 6.1.3. P1 and P2 describe offset of the first byte
- to be read. We always read the whole files at the moment. */
-this.P1_RB = 0x00;
-this.P2_RB = 0x00;
-
-/* ISO 7816-4: get response, 7.1.3 table 74, P1-P2 '0000' (other values RFU) */
-this.P1_GR = 0x00;
-this.P2_GR = 0x00;
-
-/* ISO 7816-4: 5.1.5 File Control Information, Table 1. For FCP and FMD. */
-this.TAG_PROPRIETARY = 0x00;
-this.TAG_NON_TLV = 0x53;
-this.TAG_BER_TLV = 0x73;
-
-/* ASN.1 tags */
-this.TAG_SEQUENCE = 0x30;
-this.TAG_OCTETSTRING = 0x04;
-this.TAG_OID = 0x06; // Object Identifier
-
-/* ISO 7816-4: 5.1.5 File Control Information, Templates. */
-this.TAG_FCP = 0x62; // File control parameters template
-this.TAG_FMD = 0x64; // File management data template
-this.TAG_FCI = 0x6F; // File control information template
-
-/* EF_DIR tags */
-this.TAG_APPLTEMPLATE = 0x61;
-this.TAG_APPLIDENTIFIER = 0x4F;
-this.TAG_APPLLABEL = 0x50;
-this.TAG_APPLPATH = 0x51;
-
-this.TAG_GPD_ALL = 0x82; // EF-ACRules - GPD spec. "all applets"
-
-/* Generic TLVs that are parsed */
-this.TAG_GPD_AID = 0xA0; // AID in the EF-ACRules - GPD spec, "one applet"
-this.TAG_EXTERNALDO = 0xA1; // External data objects - PKCS#15
-this.TAG_INDIRECT = 0xA5; // Indirect value.
-this.TAG_EF_ODF = 0xA7; // Elemenetary File Object Directory File
-
-// Allow this file to be imported via Components.utils.import().
-this.EXPORTED_SYMBOLS = Object.keys(this);
diff --git a/dom/secureelement/gonk/nsIAccessControlEnforcer.idl b/dom/secureelement/gonk/nsIAccessControlEnforcer.idl
deleted file mode 100644
index 7ad1a97f6..000000000
--- a/dom/secureelement/gonk/nsIAccessControlEnforcer.idl
+++ /dev/null
@@ -1,32 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Copyright © 2015, Deutsche Telekom, Inc. */
-
-#include "nsISupports.idl"
-
-interface nsIVariant;
-
-[scriptable, uuid(4994a960-26d9-4d71-82dd-4505bd97bf2a)]
-interface nsIAccessControlEnforcer : nsISupports
-{
- /**
- * Determines whether application identified by its ID should be allowed
- * to access Secure Element's applet identified by its AID. Decision
- * is made according to the GPD specification.
- *
- * @param localId
- * ID of an application accessing SE
- * @param seType
- * Type of the SE.
- * @param aid
- * AID of a SE applet
- * @return Promise which is resolved to true if access should be allowed,
- * false otherwise, and rejected if the application contains
- * no developer certificate.
- */
- jsval isAccessAllowed(in unsigned long localId,
- in DOMString seType,
- in DOMString aid);
-};
diff --git a/dom/secureelement/gonk/nsIAccessRulesManager.idl b/dom/secureelement/gonk/nsIAccessRulesManager.idl
deleted file mode 100644
index 173f57c90..000000000
--- a/dom/secureelement/gonk/nsIAccessRulesManager.idl
+++ /dev/null
@@ -1,50 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Copyright © 2015, Deutsche Telekom, Inc. */
-
-#include "nsISupports.idl"
-
-[scriptable, uuid(7baedd2a-3189-4b03-b2a3-34016043b5e2)]
-interface nsIAccessRulesManager : nsISupports
-{
- /* Wildcard: rule allows all applications to access an SE applet */
- const unsigned short ALLOW_ALL = 1;
- /* Wildcard: rule denies all applications to access an SE applet */
- const unsigned short DENY_ALL = 2;
- /* Wildcard: rule allows application(s) access to all SE applets */
- const unsigned short ALL_APPLET = 3;
-
- /**
- * Initiates Access Rules Manager, this should perform the initial
- * reading of rules from access rule source
- * @return Promise which is resolved if init is successful or rejected
- * otherwise
- */
- jsval init();
-
- /**
- * Retrieves all access rules.
- *
- * Rules are stored in an array. Each rule contains the following properties:
- * - applet - describes an SE applet referenced by this rule. Might equal
- * to an applet AID (as a byte array), or to a wildcard "all"
- * meaning all applets.
- * - application - describes an application referenced by this rule. Might
- * be an array of developer certificate hashes (each as
- * a byte array) in which case it lists all applications
- * allowed access. Alternatively, might equal to wildcard
- * "allowed-all" or "denied-all".
- *
- * Example rule format:
- * [{ applet: ALL_APPLET,
- * application: [[0x01, 0x02, ..., 0x20],
- * [0x20, 0x19, ...., 0x01]],
- * { applet: [0x00, 0x01, ..., 0x05],
- * application: ALLOW_ALL}}]
- *
- * @return Promise which resolves with Array containing parsed access rules
- */
- jsval getAccessRules();
-};
diff --git a/dom/secureelement/gonk/nsISecureElementConnector.idl b/dom/secureelement/gonk/nsISecureElementConnector.idl
deleted file mode 100644
index 92cc1eb2b..000000000
--- a/dom/secureelement/gonk/nsISecureElementConnector.idl
+++ /dev/null
@@ -1,124 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(1ff3f35a-1b6f-4e65-a89e-a363b8604cd7)]
-interface nsISEChannelCallback : nsISupports
-{
- /**
- * Callback function to notify on successfully opening a logical channel.
- *
- * @param channel
- * The Channel Number/Handle that is successfully opened.
- * @param openResponse
- * Response from SE for OpenChannel operation.
- */
- void notifyOpenChannelSuccess(in long channel, in DOMString openResponse);
-
- /**
- * Callback function to notify on successfully closing the logical channel.
- *
- */
- void notifyCloseChannelSuccess();
-
- /**
- * Callback function to notify the status of 'seExchangeAPDU' command.
- *
- * @param sw1
- * Response's First Status Byte
- * @param sw2
- * Response's Second Status Byte
- * @param data
- * Response's data
- */
- void notifyExchangeAPDUResponse(in octet sw1,
- in octet sw2,
- in DOMString data);
-
- /**
- * Callback function to notify error
- *
- * @param error
- * Error describing the reason for failure.
- */
- void notifyError(in DOMString error);
-};
-
-[scriptable, uuid(417f59ee-f582-45b9-9a4e-e9dcefecb4f7)]
-interface nsISEListener : nsISupports
-{
- void notifySEPresenceChanged(in DOMString seType, in boolean isPresent);
-};
-
-[scriptable, uuid(3cef313a-1d01-432d-9cd2-6610a80911f3)]
-interface nsISecureElementConnector : nsISupports
-{
- /**
- * Open a logical communication channel with the specific secure element type
- *
- * @param aid
- * Application Identifier of the Card Applet on the secure element.
- * @param callback
- * callback to notify the result of the operation.
- */
- void openChannel(in DOMString aid,
- in nsISEChannelCallback callback);
-
- /**
- * Exchanges APDU channel with the specific secure element type
- *
- * @param channel
- * Channel on which C-APDU to be transmitted.
- * @param cla
- Class Byte.
- * @param ins
- Instruction Byte
- * @param p1
- Reference parameter first byte
- * @param p2
- Reference parameter second byte
- * Refer to 3G TS 31.101 , 10.2 'Command APDU Structure' for all the cases.
- * @param data
- Sequence of C-APDU data octets
- * @param le [optional]
- * le is the length of expected response. If the response is not expected,
- it should be explicitly set to -1.
- * @param callback
- * callback to notify the result of the operation.
- */
- void exchangeAPDU(in long channel,
- in octet cla,
- in octet ins,
- in octet p1,
- in octet p2,
- in DOMString data,
- in short le,
- in nsISEChannelCallback callback);
-
- /**
- * Closes the logical communication channel to the specific secure element type
- *
- * @param channel
- * Channel to be closed.
- * @param callback
- * callback to notify the result of the operation.
- */
- void closeChannel(in long channel,
- in nsISEChannelCallback callback);
-
- /**
- * Register a Secure Element listener
- *
- * @param listener
- */
- void registerListener(in nsISEListener listener);
-
- /**
- * Unregister a Secure Element listener
- *
- * @param listener
- */
- void unregisterListener(in nsISEListener listener);
-};
diff --git a/dom/secureelement/gonk/se_consts.js b/dom/secureelement/gonk/se_consts.js
deleted file mode 100644
index 13489b7ae..000000000
--- a/dom/secureelement/gonk/se_consts.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* Copyright © 2014, Deutsche Telekom, Inc. */
-
-// Set to true to debug SecureElement (SE) stack
-this.DEBUG_ALL = false;
-
-// Set individually to debug specific layers
-this.DEBUG_CONNECTOR = DEBUG_ALL || false;
-this.DEBUG_ACE = DEBUG_ALL || false ;
-this.DEBUG_SE = DEBUG_ALL || false ;
-
-// Maximun logical channels per session.
-// For 'uicc' SE type this value is 3, as opening a basic channel' : 0
-// is not allowed for security reasons. In such scenarios, possible
-// supplementary logical channels available are : [1, 2, or 3].
-// However,Other SE types may support upto max 4 (including '0').
-this.MAX_CHANNELS_ALLOWED_PER_SESSION = 4;
-
-this.BASIC_CHANNEL = 0;
-
-// According GPCardSpec 2.2
-this.MAX_APDU_LEN = 255; // including APDU header
-
-// CLA (1 byte) + INS (1 byte) + P1 (1 byte) + P2 (1 byte)
-this.APDU_HEADER_LEN = 4;
-
-this.LOGICAL_CHANNEL_NUMBER_LIMIT = 4;
-this.SUPPLEMENTARY_LOGICAL_CHANNEL_NUMBER_LIMIT = 20;
-
-this.MIN_AID_LEN = 5;
-this.MAX_AID_LEN = 16;
-
-this.CLA_GET_RESPONSE = 0x00;
-
-this.INS_SELECT = 0xA4;
-this.INS_MANAGE_CHANNEL = 0x70;
-this.INS_GET_RESPONSE = 0xC0;
-
-// Match the following errors with SecureElement.webidl's SEError enum values
-this.ERROR_NONE = "";
-this.ERROR_SECURITY = "SESecurityError";
-this.ERROR_IO = "SEIoError";
-this.ERROR_BADSTATE = "SEBadStateError";
-this.ERROR_INVALIDCHANNEL = "SEInvalidChannelError";
-this.ERROR_INVALIDAPPLICATION = "SEInvalidApplicationError";
-this.ERROR_GENERIC = "SEGenericError";
-this.ERROR_NOTPRESENT = "SENotPresentError";
-this.ERROR_ILLEGALPARAMETER = "SEIllegalParameterError";
-
-this.TYPE_UICC = "uicc";
-this.TYPE_ESE = "eSE";
-
-// Allow this file to be imported via Components.utils.import().
-this.EXPORTED_SYMBOLS = Object.keys(this);
diff --git a/dom/secureelement/moz.build b/dom/secureelement/moz.build
index a2c87b014..973000512 100644
--- a/dom/secureelement/moz.build
+++ b/dom/secureelement/moz.build
@@ -11,30 +11,6 @@ if CONFIG['MOZ_SECUREELEMENT']:
'DOMSecureElement.manifest',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and CONFIG['MOZ_SECUREELEMENT']:
- EXTRA_COMPONENTS += [
- 'gonk/ACEService.js',
- 'gonk/ACEService.manifest',
- 'gonk/GPAccessRulesManager.js',
- 'gonk/GPAccessRulesManager.manifest',
- 'gonk/SecureElement.js',
- 'gonk/SecureElement.manifest',
- ]
- XPIDL_MODULE = 'dom_secureelement'
- XPIDL_SOURCES += [
- 'gonk/nsIAccessControlEnforcer.idl',
- 'gonk/nsIAccessRulesManager.idl',
- 'gonk/nsISecureElementConnector.idl',
- ]
- EXTRA_JS_MODULES += [
- 'gonk/gp_consts.js',
- 'gonk/se_consts.js',
- 'SEUtils.jsm'
- ]
- XPCSHELL_TESTS_MANIFESTS += [
- 'tests/unit/xpcshell.ini'
- ]
-
include('/ipc/chromium/chromium-config.mozbuild')
FINAL_LIBRARY = 'xul'
diff --git a/dom/security/nsCSPContext.cpp b/dom/security/nsCSPContext.cpp
index 979bd915f..65be02809 100644
--- a/dom/security/nsCSPContext.cpp
+++ b/dom/security/nsCSPContext.cpp
@@ -817,15 +817,6 @@ nsCSPContext::SendReports(nsISupports* aBlockedContentSource,
{
NS_ENSURE_ARG_MAX(aViolatedPolicyIndex, mPolicies.Length() - 1);
-#ifdef MOZ_B2G
- // load group information (on process-split necko implementations like b2g).
- // (fix this in bug 1011086)
- if (!mCallingChannelLoadGroup) {
- NS_WARNING("Load group required but not present for report sending; cannot send CSP violation reports");
- return NS_ERROR_FAILURE;
- }
-#endif
-
dom::CSPReport report;
nsresult rv;
diff --git a/dom/security/nsContentSecurityManager.cpp b/dom/security/nsContentSecurityManager.cpp
index 0cc4933fe..c6558fc93 100644
--- a/dom/security/nsContentSecurityManager.cpp
+++ b/dom/security/nsContentSecurityManager.cpp
@@ -10,6 +10,8 @@
#include "nsIStreamListener.h"
#include "nsIDocument.h"
#include "nsMixedContentBlocker.h"
+#include "nsCDefaultURIFixup.h"
+#include "nsIURIFixup.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/TabChild.h"
@@ -244,10 +246,6 @@ DoCORSChecks(nsIChannel* aChannel, nsILoadInfo* aLoadInfo,
static nsresult
DoContentSecurityChecks(nsIChannel* aChannel, nsILoadInfo* aLoadInfo)
{
- nsCOMPtr<nsIURI> uri;
- nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
- NS_ENSURE_SUCCESS(rv, rv);
-
nsContentPolicyType contentPolicyType =
aLoadInfo->GetExternalContentPolicyType();
nsContentPolicyType internalContentPolicyType =
@@ -255,12 +253,24 @@ DoContentSecurityChecks(nsIChannel* aChannel, nsILoadInfo* aLoadInfo)
nsCString mimeTypeGuess;
nsCOMPtr<nsISupports> requestingContext = nullptr;
-#ifdef DEBUG
- // Don't enforce TYPE_DOCUMENT assertions for loads
- // initiated by javascript tests.
- bool skipContentTypeCheck = false;
- skipContentTypeCheck = Preferences::GetBool("network.loadinfo.skip_type_assertion");
-#endif
+ nsCOMPtr<nsIURI> uri;
+ nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ if (contentPolicyType == nsIContentPolicy::TYPE_DOCUMENT ||
+ contentPolicyType == nsIContentPolicy::TYPE_SUBDOCUMENT) {
+ // TYPE_DOCUMENT and TYPE_SUBDOCUMENT loads might potentially
+ // be wyciwyg:// channels. Let's fix up the URI so we can
+ // perform proper security checks.
+ nsCOMPtr<nsIURIFixup> urifixup(do_GetService(NS_URIFIXUP_CONTRACTID, &rv));
+ if (NS_SUCCEEDED(rv) && urifixup) {
+ nsCOMPtr<nsIURI> fixedURI;
+ rv = urifixup->CreateExposableURI(uri, getter_AddRefs(fixedURI));
+ if (NS_SUCCEEDED(rv)) {
+ uri = fixedURI;
+ }
+ }
+ }
switch(contentPolicyType) {
case nsIContentPolicy::TYPE_OTHER: {
@@ -294,16 +304,14 @@ DoContentSecurityChecks(nsIChannel* aChannel, nsILoadInfo* aLoadInfo)
}
case nsIContentPolicy::TYPE_DOCUMENT: {
- MOZ_ASSERT(skipContentTypeCheck || false, "contentPolicyType not supported yet");
+ mimeTypeGuess = EmptyCString();
+ requestingContext = aLoadInfo->LoadingNode();
break;
}
case nsIContentPolicy::TYPE_SUBDOCUMENT: {
mimeTypeGuess = NS_LITERAL_CSTRING("text/html");
requestingContext = aLoadInfo->LoadingNode();
- MOZ_ASSERT(!requestingContext ||
- requestingContext->NodeType() == nsIDOMNode::DOCUMENT_NODE,
- "type_subdocument requires requestingContext of type Document");
break;
}
@@ -470,18 +478,32 @@ DoContentSecurityChecks(nsIChannel* aChannel, nsILoadInfo* aLoadInfo)
MOZ_ASSERT(false, "can not perform security check without a valid contentType");
}
+ // For document loads we use the triggeringPrincipal as the originPrincipal.
+ // Note the the loadingPrincipal for loads of TYPE_DOCUMENT is a nullptr.
+ nsCOMPtr<nsIPrincipal> principal =
+ (contentPolicyType == nsIContentPolicy::TYPE_DOCUMENT ||
+ contentPolicyType == nsIContentPolicy::TYPE_SUBDOCUMENT)
+ ? aLoadInfo->TriggeringPrincipal()
+ : aLoadInfo->LoadingPrincipal();
+
int16_t shouldLoad = nsIContentPolicy::ACCEPT;
rv = NS_CheckContentLoadPolicy(internalContentPolicyType,
uri,
- aLoadInfo->LoadingPrincipal(),
+ principal,
requestingContext,
mimeTypeGuess,
nullptr, //extra,
&shouldLoad,
nsContentUtils::GetContentPolicy(),
nsContentUtils::GetSecurityManager());
- NS_ENSURE_SUCCESS(rv, rv);
- if (NS_CP_REJECTED(shouldLoad)) {
+
+ if (NS_FAILED(rv) || NS_CP_REJECTED(shouldLoad)) {
+ if ((NS_SUCCEEDED(rv) && shouldLoad == nsIContentPolicy::REJECT_TYPE) &&
+ (contentPolicyType == nsIContentPolicy::TYPE_DOCUMENT ||
+ contentPolicyType == nsIContentPolicy::TYPE_SUBDOCUMENT)) {
+ // for docshell loads we might have to return SHOW_ALT.
+ return NS_ERROR_CONTENT_BLOCKED_SHOW_ALT;
+ }
return NS_ERROR_CONTENT_BLOCKED;
}
@@ -629,6 +651,24 @@ nsContentSecurityManager::CheckChannel(nsIChannel* aChannel)
nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
NS_ENSURE_SUCCESS(rv, rv);
+ nsContentPolicyType contentPolicyType =
+ loadInfo->GetExternalContentPolicyType();
+
+ if (contentPolicyType == nsIContentPolicy::TYPE_DOCUMENT ||
+ contentPolicyType == nsIContentPolicy::TYPE_SUBDOCUMENT) {
+ // TYPE_DOCUMENT and TYPE_SUBDOCUMENT loads might potentially
+ // be wyciwyg:// channels. Let's fix up the URI so we can
+ // perform proper security checks.
+ nsCOMPtr<nsIURIFixup> urifixup(do_GetService(NS_URIFIXUP_CONTRACTID, &rv));
+ if (NS_SUCCEEDED(rv) && urifixup) {
+ nsCOMPtr<nsIURI> fixedURI;
+ rv = urifixup->CreateExposableURI(uri, getter_AddRefs(fixedURI));
+ if (NS_SUCCEEDED(rv)) {
+ uri = fixedURI;
+ }
+ }
+ }
+
// Handle cookie policies
uint32_t cookiePolicy = loadInfo->GetCookiePolicy();
if (cookiePolicy == nsILoadInfo::SEC_COOKIES_SAME_ORIGIN) {
diff --git a/dom/settings/SettingsService.js b/dom/settings/SettingsService.js
deleted file mode 100644
index 09bd3ca72..000000000
--- a/dom/settings/SettingsService.js
+++ /dev/null
@@ -1,358 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const Ci = Components.interfaces;
-const Cu = Components.utils;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import('resource://gre/modules/SettingsRequestManager.jsm');
-
-/* static functions */
-var DEBUG = false;
-var VERBOSE = false;
-
-try {
- DEBUG =
- Services.prefs.getBoolPref("dom.mozSettings.SettingsService.debug.enabled");
- VERBOSE =
- Services.prefs.getBoolPref("dom.mozSettings.SettingsService.verbose.enabled");
-} catch (ex) { }
-
-function debug(s) {
- dump("-*- SettingsService: " + s + "\n");
-}
-
-XPCOMUtils.defineLazyServiceGetter(this, "uuidgen",
- "@mozilla.org/uuid-generator;1",
- "nsIUUIDGenerator");
-XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
- "@mozilla.org/childprocessmessagemanager;1",
- "nsIMessageSender");
-XPCOMUtils.defineLazyServiceGetter(this, "mrm",
- "@mozilla.org/memory-reporter-manager;1",
- "nsIMemoryReporterManager");
-
-const nsIClassInfo = Ci.nsIClassInfo;
-const kXpcomShutdownObserverTopic = "xpcom-shutdown";
-
-const SETTINGSSERVICELOCK_CONTRACTID = "@mozilla.org/settingsServiceLock;1";
-const SETTINGSSERVICELOCK_CID = Components.ID("{d7a395a0-e292-11e1-834e-1761d57f5f99}");
-const nsISettingsServiceLock = Ci.nsISettingsServiceLock;
-
-function makeSettingsServiceRequest(aCallback, aName, aValue) {
- return {
- callback: aCallback,
- name: aName,
- value: aValue
- };
-};
-
-const kLockListeners = ["Settings:Get:OK", "Settings:Get:KO",
- "Settings:Clear:OK", "Settings:Clear:KO",
- "Settings:Set:OK", "Settings:Set:KO",
- "Settings:Finalize:OK", "Settings:Finalize:KO"];
-
-function SettingsServiceLock(aSettingsService, aTransactionCallback) {
- if (VERBOSE) debug("settingsServiceLock constr!");
- this._open = true;
- this._settingsService = aSettingsService;
- this._id = uuidgen.generateUUID().toString();
- this._transactionCallback = aTransactionCallback;
- this._requests = {};
- let closeHelper = function() {
- if (VERBOSE) debug("closing lock " + this._id);
- this._open = false;
- this.runOrFinalizeQueries();
- }.bind(this);
-
- this.addListeners();
-
- let createLockPayload = {
- lockID: this._id,
- isServiceLock: true,
- windowID: undefined,
- lockStack: (new Error).stack
- };
-
- this.returnMessage("Settings:CreateLock", createLockPayload);
- Services.tm.currentThread.dispatch(closeHelper, Ci.nsIThread.DISPATCH_NORMAL);
-}
-
-SettingsServiceLock.prototype = {
- get closed() {
- return !this._open;
- },
-
- addListeners: function() {
- for (let msg of kLockListeners) {
- cpmm.addMessageListener(msg, this);
- }
- },
-
- removeListeners: function() {
- for (let msg of kLockListeners) {
- cpmm.removeMessageListener(msg, this);
- }
- },
-
- returnMessage: function(aMessage, aData) {
- SettingsRequestManager.receiveMessage({
- name: aMessage,
- data: aData,
- target: undefined,
- principal: Services.scriptSecurityManager.getSystemPrincipal()
- });
- },
-
- runOrFinalizeQueries: function() {
- if (!this._requests || Object.keys(this._requests).length == 0) {
- this.returnMessage("Settings:Finalize", {lockID: this._id});
- } else {
- this.returnMessage("Settings:Run", {lockID: this._id});
- }
- },
-
- receiveMessage: function(aMessage) {
-
- let msg = aMessage.data;
- // SettingsRequestManager broadcasts changes to all locks in the child. If
- // our lock isn't being addressed, just return.
- if(msg.lockID != this._id) {
- return;
- }
- if (VERBOSE) debug("receiveMessage (" + this._id + "): " + aMessage.name);
- // Finalizing a transaction does not return a request ID since we are
- // supposed to fire callbacks.
- if (!msg.requestID) {
- switch (aMessage.name) {
- case "Settings:Finalize:OK":
- if (VERBOSE) debug("Lock finalize ok!");
- this.callTransactionHandle();
- break;
- case "Settings:Finalize:KO":
- if (DEBUG) debug("Lock finalize failed!");
- this.callAbort();
- break;
- default:
- if (DEBUG) debug("Message type " + aMessage.name + " is missing a requestID");
- }
-
- this._settingsService.unregisterLock(this._id);
- return;
- }
-
- let req = this._requests[msg.requestID];
- if (!req) {
- if (DEBUG) debug("Matching request not found.");
- return;
- }
- delete this._requests[msg.requestID];
- switch (aMessage.name) {
- case "Settings:Get:OK":
- this._open = true;
- let settings_names = Object.keys(msg.settings);
- if (settings_names.length > 0) {
- let name = settings_names[0];
- if (DEBUG && settings_names.length > 1) {
- debug("Warning: overloaded setting:" + name);
- }
- let result = msg.settings[name];
- this.callHandle(req.callback, name, result);
- } else {
- this.callHandle(req.callback, req.name, null);
- }
- this._open = false;
- break;
- case "Settings:Set:OK":
- this._open = true;
- // We don't pass values back from sets in SettingsManager...
- this.callHandle(req.callback, req.name, req.value);
- this._open = false;
- break;
- case "Settings:Get:KO":
- case "Settings:Set:KO":
- if (DEBUG) debug("error:" + msg.errorMsg);
- this.callError(req.callback, msg.error);
- break;
- default:
- if (DEBUG) debug("Wrong message: " + aMessage.name);
- }
- this.runOrFinalizeQueries();
- },
-
- get: function get(aName, aCallback) {
- if (VERBOSE) debug("get (" + this._id + "): " + aName);
- if (!this._open) {
- if (DEBUG) debug("Settings lock not open!\n");
- throw Components.results.NS_ERROR_ABORT;
- }
- let reqID = uuidgen.generateUUID().toString();
- this._requests[reqID] = makeSettingsServiceRequest(aCallback, aName);
- this.returnMessage("Settings:Get", {requestID: reqID,
- lockID: this._id,
- name: aName});
- },
-
- set: function set(aName, aValue, aCallback) {
- if (VERBOSE) debug("set: " + aName + " " + aValue);
- if (!this._open) {
- throw "Settings lock not open";
- }
- let reqID = uuidgen.generateUUID().toString();
- this._requests[reqID] = makeSettingsServiceRequest(aCallback, aName, aValue);
- let settings = {};
- settings[aName] = aValue;
- this.returnMessage("Settings:Set", {requestID: reqID,
- lockID: this._id,
- settings: settings});
- },
-
- callHandle: function callHandle(aCallback, aName, aValue) {
- try {
- aCallback && aCallback.handle ? aCallback.handle(aName, aValue) : null;
- } catch (e) {
- if (DEBUG) debug("settings 'handle' for " + aName + " callback threw an exception, dropping: " + e + "\n");
- }
- },
-
- callAbort: function callAbort(aCallback, aMessage) {
- try {
- aCallback && aCallback.handleAbort ? aCallback.handleAbort(aMessage) : null;
- } catch (e) {
- if (DEBUG) debug("settings 'abort' callback threw an exception, dropping: " + e + "\n");
- }
- },
-
- callError: function callError(aCallback, aMessage) {
- try {
- aCallback && aCallback.handleError ? aCallback.handleError(aMessage) : null;
- } catch (e) {
- if (DEBUG) debug("settings 'error' callback threw an exception, dropping: " + e + "\n");
- }
- },
-
- callTransactionHandle: function callTransactionHandle() {
- try {
- this._transactionCallback && this._transactionCallback.handle ? this._transactionCallback.handle() : null;
- } catch (e) {
- if (DEBUG) debug("settings 'Transaction handle' callback threw an exception, dropping: " + e + "\n");
- }
- },
-
- classID : SETTINGSSERVICELOCK_CID,
- QueryInterface : XPCOMUtils.generateQI([nsISettingsServiceLock])
-};
-
-const SETTINGSSERVICE_CID = Components.ID("{f656f0c0-f776-11e1-a21f-0800200c9a66}");
-
-function SettingsService()
-{
- if (VERBOSE) debug("settingsService Constructor");
- this._locks = [];
- this._serviceLocks = {};
- this._createdLocks = 0;
- this._unregisteredLocks = 0;
- this.init();
-}
-
-SettingsService.prototype = {
-
- init: function() {
- Services.obs.addObserver(this, kXpcomShutdownObserverTopic, false);
- mrm.registerStrongReporter(this);
- },
-
- uninit: function() {
- Services.obs.removeObserver(this, kXpcomShutdownObserverTopic);
- mrm.unregisterStrongReporter(this);
- },
-
- observe: function(aSubject, aTopic, aData) {
- if (VERBOSE) debug("observe: " + aTopic);
- if (aTopic === kXpcomShutdownObserverTopic) {
- this.uninit();
- }
- },
-
- receiveMessage: function(aMessage) {
- if (VERBOSE) debug("Entering receiveMessage");
-
- let lockID = aMessage.data.lockID;
- if (!lockID) {
- if (DEBUG) debug("No lock ID");
- return;
- }
-
- if (!(lockID in this._serviceLocks)) {
- if (DEBUG) debug("Received message for lock " + lockID + " but no lock");
- return;
- }
-
- if (VERBOSE) debug("Delivering message");
- this._serviceLocks[lockID].receiveMessage(aMessage);
- },
-
- createLock: function createLock(aCallback) {
- if (VERBOSE) debug("Calling createLock");
- var lock = new SettingsServiceLock(this, aCallback);
- if (VERBOSE) debug("Created lock " + lock._id);
- this.registerLock(lock);
- return lock;
- },
-
- registerLock: function(aLock) {
- if (VERBOSE) debug("Registering lock " + aLock._id);
- this._locks.push(aLock._id);
- this._serviceLocks[aLock._id] = aLock;
- this._createdLocks++;
- },
-
- unregisterLock: function(aLockID) {
- let lock_index = this._locks.indexOf(aLockID);
- if (lock_index != -1) {
- if (VERBOSE) debug("Unregistering lock " + aLockID);
- this._locks.splice(lock_index, 1);
- this._serviceLocks[aLockID].removeListeners();
- this._serviceLocks[aLockID] = null;
- delete this._serviceLocks[aLockID];
- this._unregisteredLocks++;
- }
- },
-
- collectReports: function(aCallback, aData, aAnonymize) {
- aCallback.callback("",
- "settings-service-locks/alive",
- Ci.nsIMemoryReporter.KIND_OTHER,
- Ci.nsIMemoryReporter.UNITS_COUNT,
- this._locks.length,
- "The number of service locks that are currently alives.",
- aData);
-
- aCallback.callback("",
- "settings-service-locks/created",
- Ci.nsIMemoryReporter.KIND_OTHER,
- Ci.nsIMemoryReporter.UNITS_COUNT,
- this._createdLocks,
- "The number of service locks that were created.",
- aData);
-
- aCallback.callback("",
- "settings-service-locks/deleted",
- Ci.nsIMemoryReporter.KIND_OTHER,
- Ci.nsIMemoryReporter.UNITS_COUNT,
- this._unregisteredLocks,
- "The number of service locks that were deleted.",
- aData);
- },
-
- classID : SETTINGSSERVICE_CID,
- QueryInterface : XPCOMUtils.generateQI([Ci.nsISettingsService,
- Ci.nsIObserver,
- Ci.nsIMemoryReporter])
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([SettingsService, SettingsServiceLock]);
diff --git a/dom/settings/SettingsService.manifest b/dom/settings/SettingsService.manifest
deleted file mode 100644
index ae464f921..000000000
--- a/dom/settings/SettingsService.manifest
+++ /dev/null
@@ -1,5 +0,0 @@
-component {d7a395a0-e292-11e1-834e-1761d57f5f99} SettingsService.js
-contract @mozilla.org/settingsServiceLock;1 {d7a395a0-e292-11e1-834e-1761d57f5f99}
-
-component {f656f0c0-f776-11e1-a21f-0800200c9a66} SettingsService.js
-contract @mozilla.org/settingsService;1 {f656f0c0-f776-11e1-a21f-0800200c9a66}
diff --git a/dom/settings/moz.build b/dom/settings/moz.build
index 426edcbce..580a55e6a 100644
--- a/dom/settings/moz.build
+++ b/dom/settings/moz.build
@@ -12,12 +12,6 @@ EXTRA_PP_COMPONENTS += [
'SettingsManager.js'
]
-if CONFIG['MOZ_B2G']:
- EXTRA_COMPONENTS += [
- 'SettingsService.js',
- 'SettingsService.manifest',
- ]
-
EXTRA_JS_MODULES += [
'SettingsDB.jsm',
'SettingsRequestManager.jsm'
diff --git a/dom/settings/tests/chrome.ini b/dom/settings/tests/chrome.ini
index 92b1554a0..5b0db9e40 100644
--- a/dom/settings/tests/chrome.ini
+++ b/dom/settings/tests/chrome.ini
@@ -4,13 +4,7 @@ support-files =
file_loadserver.js
file_bug1110872.js
file_bug1110872.html
- test_settings_service.js
- test_settings_service_callback.js
-[test_settings_service.xul]
-run-if = buildapp == 'b2g' || buildapp == 'mulet'
-[test_settings_service_callback.xul]
-run-if = buildapp == 'b2g' || buildapp == 'mulet'
[test_settings_basics.html]
[test_settings_permissions.html]
[test_settings_blobs.html]
diff --git a/dom/settings/tests/test_settings_service.js b/dom/settings/tests/test_settings_service.js
deleted file mode 100644
index 132877a5d..000000000
--- a/dom/settings/tests/test_settings_service.js
+++ /dev/null
@@ -1,138 +0,0 @@
-"use strict";
-
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-if (SpecialPowers.isMainProcess()) {
- SpecialPowers.Cu.import("resource://gre/modules/SettingsRequestManager.jsm");
-}
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-SimpleTest.waitForExplicitFinish();
-
-XPCOMUtils.defineLazyServiceGetter(this, "SettingsService",
- "@mozilla.org/settingsService;1",
- "nsISettingsService");
-
-var tests = [
- /* Callback tests */
- function() {
- let callbackCount = 10;
-
- let callback = {
- handle: function(name, result) {
- switch (callbackCount) {
- case 10:
- case 9:
- is(result, true, "result is true");
- break;
- case 8:
- case 7:
- is(result, false, "result is false");
- break;
- case 6:
- case 5:
- is(result, 9, "result is 9");
- break;
- case 4:
- case 3:
- is(result, 9.4, "result is 9.4");
- break;
- case 2:
- is(result, false, "result is false");
- break;
- case 1:
- is(result, null, "result is null");
- break;
- default:
- ok(false, "Unexpected call: " + callbackCount);
- }
-
- --callbackCount;
- if (callbackCount === 0) {
- next();
- }
- },
-
- handleError: function(name) {
- ok(false, "error: " + name);
- }
- };
-
- let lock = SettingsService.createLock();
- let lock1 = SettingsService.createLock();
-
- lock.set("asdf", true, callback, null);
- lock1.get("asdf", callback);
- lock.get("asdf", callback);
- lock.set("asdf", false, callback, null);
- lock.get("asdf", callback);
- lock.set("int", 9, callback, null);
- lock.get("int", callback);
- lock.set("doub", 9.4, callback, null);
- lock.get("doub", callback);
- lock1.get("asdfxxx", callback);
- },
-
- /* Observer tests */
- function() {
- const MOZSETTINGS_CHANGED = "mozsettings-changed";
- const TEST_OBSERVER_KEY = "test.observer.key";
- const TEST_OBSERVER_VALUE = true;
- const TEST_OBSERVER_MESSAGE = "test.observer.message";
-
- var obs = {
- observe: function (subject, topic, data) {
-
- if (topic !== MOZSETTINGS_CHANGED) {
- ok(false, "Event is not mozsettings-changed.");
- return;
- }
- // Data is now stored in subject
- if ("wrappedJSObject" in subject) {
- ok(true, "JS object wrapped into subject");
- subject = subject.wrappedJSObject;
- }
- if (subject["key"] != TEST_OBSERVER_KEY) {
- return;
- }
-
- function checkProp(name, type, value) {
- ok(name in subject, "subject." + name + " is present");
- is(typeof subject[name], type, "subject." + name + " is " + type);
- is(subject[name], value, "subject." + name + " is " + value);
- }
-
- checkProp("key", "string", TEST_OBSERVER_KEY);
- checkProp("value", "boolean", TEST_OBSERVER_VALUE);
- checkProp("isInternalChange", "boolean", true);
-
- Services.obs.removeObserver(this, MOZSETTINGS_CHANGED);
- next();
- }
- };
-
- Services.obs.addObserver(obs, MOZSETTINGS_CHANGED, false);
-
- let lock = SettingsService.createLock();
- lock.set(TEST_OBSERVER_KEY, TEST_OBSERVER_VALUE, null);
- }
-];
-
-function next() {
- let step = tests.shift();
- if (step) {
- try {
- step();
- } catch(e) {
- ok(false, "Test threw: " + e);
- }
- } else {
- SimpleTest.finish();
- }
-}
-
-next();
diff --git a/dom/settings/tests/test_settings_service.xul b/dom/settings/tests/test_settings_service.xul
deleted file mode 100644
index 58a9efad9..000000000
--- a/dom/settings/tests/test_settings_service.xul
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="/tests/SimpleTest/test.css"?>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=678695
--->
-<window title="Mozilla Bug 678695"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml">
- <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=678695"
- target="_blank">Mozilla Bug 678695</a>
- </body>
-
- <script type="application/javascript;version=1.7" src="test_settings_service.js" />
-</window>
diff --git a/dom/settings/tests/test_settings_service_callback.js b/dom/settings/tests/test_settings_service_callback.js
deleted file mode 100644
index a780bb9c3..000000000
--- a/dom/settings/tests/test_settings_service_callback.js
+++ /dev/null
@@ -1,47 +0,0 @@
-"use strict";
-
-var Cu = Components.utils;
-var Cc = Components.classes;
-var Ci = Components.interfaces;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-
-SimpleTest.waitForExplicitFinish();
-
-XPCOMUtils.defineLazyServiceGetter(this, "SettingsService",
- "@mozilla.org/settingsService;1",
- "nsISettingsService");
-
-var tests = [
- function () {
- let callback = {
- handle: function() {
- ok(true, "handle called!");
- next();
- },
-
- handleAbort: function(name) {
- ok(false, "error: " + name);
- next();
- }
- }
- let lock = SettingsService.createLock(callback);
- lock.set("xasdf", true, null, null);
- }
-];
-
-function next() {
- let step = tests.shift();
- if (step) {
- try {
- step();
- } catch(e) {
- ok(false, "Test threw: " + e);
- }
- } else {
- SimpleTest.finish();
- }
-}
-
-next();
diff --git a/dom/settings/tests/test_settings_service_callback.xul b/dom/settings/tests/test_settings_service_callback.xul
deleted file mode 100644
index 3e4d27751..000000000
--- a/dom/settings/tests/test_settings_service_callback.xul
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
-<?xml-stylesheet type="text/css" href="/tests/SimpleTest/test.css"?>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=1012214
--->
-<window title="Mozilla Bug 1012214"
- xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/javascript"
- src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
-
- <!-- test results are displayed in the html:body -->
- <body xmlns="http://www.w3.org/1999/xhtml">
- <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1012214"
- target="_blank">Mozilla Bug 1012214</a>
- </body>
-
- <script type="application/javascript;version=1.7" src="test_settings_service_callback.js" />
-</window>
diff --git a/dom/speakermanager/SpeakerManager.cpp b/dom/speakermanager/SpeakerManager.cpp
deleted file mode 100644
index 2b30fa72c..000000000
--- a/dom/speakermanager/SpeakerManager.cpp
+++ /dev/null
@@ -1,217 +0,0 @@
-/* -*- 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 "SpeakerManager.h"
-
-#include "mozilla/Services.h"
-
-#include "mozilla/dom/Event.h"
-
-#include "AudioChannelService.h"
-#include "nsIDocShell.h"
-#include "nsIDOMClassInfo.h"
-#include "nsIDOMEventListener.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsIPermissionManager.h"
-#include "SpeakerManagerService.h"
-
-namespace mozilla {
-namespace dom {
-
-NS_IMPL_QUERY_INTERFACE_INHERITED(SpeakerManager, DOMEventTargetHelper,
- nsIDOMEventListener)
-NS_IMPL_ADDREF_INHERITED(SpeakerManager, DOMEventTargetHelper)
-NS_IMPL_RELEASE_INHERITED(SpeakerManager, DOMEventTargetHelper)
-
-SpeakerManager::SpeakerManager()
- : mForcespeaker(false)
- , mVisible(false)
-{
- SpeakerManagerService *service =
- SpeakerManagerService::GetOrCreateSpeakerManagerService();
- MOZ_ASSERT(service);
- service->RegisterSpeakerManager(this);
-}
-
-SpeakerManager::~SpeakerManager()
-{
- SpeakerManagerService *service = SpeakerManagerService::GetOrCreateSpeakerManagerService();
- MOZ_ASSERT(service);
-
- service->UnRegisterSpeakerManager(this);
- nsCOMPtr<EventTarget> target = do_QueryInterface(GetOwner());
- NS_ENSURE_TRUE_VOID(target);
-
- target->RemoveSystemEventListener(NS_LITERAL_STRING("visibilitychange"),
- this,
- /* useCapture = */ true);
-}
-
-bool
-SpeakerManager::Speakerforced()
-{
- // If a background app calls forcespeaker=true that doesn't change anything.
- // 'speakerforced' remains false everywhere.
- if (mForcespeaker && !mVisible) {
- return false;
- }
- SpeakerManagerService *service = SpeakerManagerService::GetOrCreateSpeakerManagerService();
- MOZ_ASSERT(service);
- return service->GetSpeakerStatus();
-
-}
-
-bool
-SpeakerManager::Forcespeaker()
-{
- return mForcespeaker;
-}
-
-void
-SpeakerManager::SetForcespeaker(bool aEnable)
-{
- SpeakerManagerService *service = SpeakerManagerService::GetOrCreateSpeakerManagerService();
- MOZ_ASSERT(service);
-
- service->ForceSpeaker(aEnable, mVisible);
- mForcespeaker = aEnable;
-}
-
-void
-SpeakerManager::DispatchSimpleEvent(const nsAString& aStr)
-{
- MOZ_ASSERT(NS_IsMainThread(), "Not running on main thread");
- nsresult rv = CheckInnerWindowCorrectness();
- if (NS_FAILED(rv)) {
- return;
- }
-
- RefPtr<Event> event = NS_NewDOMEvent(this, nullptr, nullptr);
- event->InitEvent(aStr, false, false);
- event->SetTrusted(true);
-
- rv = DispatchDOMEvent(nullptr, event, nullptr, nullptr);
- if (NS_FAILED(rv)) {
- NS_ERROR("Failed to dispatch the event!!!");
- return;
- }
-}
-
-void
-SpeakerManager::Init(nsPIDOMWindowInner* aWindow)
-{
- BindToOwner(aWindow);
-
- nsCOMPtr<nsIDocShell> docshell = GetOwner()->GetDocShell();
- NS_ENSURE_TRUE_VOID(docshell);
- docshell->GetIsActive(&mVisible);
-
- nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(GetOwner());
- NS_ENSURE_TRUE_VOID(target);
-
- target->AddSystemEventListener(NS_LITERAL_STRING("visibilitychange"),
- this,
- /* useCapture = */ true,
- /* wantsUntrusted = */ false);
-}
-
-nsPIDOMWindowInner*
-SpeakerManager::GetParentObject() const
-{
- return GetOwner();
-}
-
-/* static */ already_AddRefed<SpeakerManager>
-SpeakerManager::Constructor(const GlobalObject& aGlobal, ErrorResult& aRv)
-{
- nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(aGlobal.GetAsSupports());
- if (!sgo) {
- aRv.Throw(NS_ERROR_FAILURE);
- return nullptr;
- }
-
- nsCOMPtr<nsPIDOMWindowInner> ownerWindow = do_QueryInterface(aGlobal.GetAsSupports());
- if (!ownerWindow) {
- aRv.Throw(NS_ERROR_FAILURE);
- return nullptr;
- }
-
- nsCOMPtr<nsIPermissionManager> permMgr = services::GetPermissionManager();
- NS_ENSURE_TRUE(permMgr, nullptr);
-
- uint32_t permission = nsIPermissionManager::DENY_ACTION;
- nsresult rv =
- permMgr->TestPermissionFromWindow(ownerWindow, "speaker-control",
- &permission);
- NS_ENSURE_SUCCESS(rv, nullptr);
-
- if (permission != nsIPermissionManager::ALLOW_ACTION) {
- aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
- return nullptr;
- }
-
- RefPtr<SpeakerManager> object = new SpeakerManager();
- object->Init(ownerWindow);
- return object.forget();
-}
-
-JSObject*
-SpeakerManager::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
- return MozSpeakerManagerBinding::Wrap(aCx, this, aGivenProto);
-}
-
-NS_IMETHODIMP
-SpeakerManager::HandleEvent(nsIDOMEvent* aEvent)
-{
- nsAutoString type;
- aEvent->GetType(type);
-
- if (!type.EqualsLiteral("visibilitychange")) {
- return NS_ERROR_FAILURE;
- }
-
- nsCOMPtr<nsIDocShell> docshell = do_GetInterface(GetOwner());
- NS_ENSURE_TRUE(docshell, NS_ERROR_FAILURE);
- docshell->GetIsActive(&mVisible);
-
- // If an app that has called forcespeaker=true is switched
- // from the background to the foreground 'speakerforced'
- // switches to true in all apps. I.e. the app doesn't have to
- // call forcespeaker=true again when it comes into foreground.
- SpeakerManagerService *service =
- SpeakerManagerService::GetOrCreateSpeakerManagerService();
- MOZ_ASSERT(service);
-
- if (mVisible && mForcespeaker) {
- service->ForceSpeaker(mForcespeaker, mVisible);
- }
- // If an application that has called forcespeaker=true, but no audio is
- // currently playing in the app itself, if application switch to
- // the background, we switch 'speakerforced' to false.
- if (!mVisible && mForcespeaker) {
- RefPtr<AudioChannelService> audioChannelService =
- AudioChannelService::GetOrCreate();
- if (audioChannelService && !audioChannelService->AnyAudioChannelIsActive()) {
- service->ForceSpeaker(false, mVisible);
- }
- }
- return NS_OK;
-}
-
-void
-SpeakerManager::SetAudioChannelActive(bool isActive)
-{
- if (mForcespeaker) {
- SpeakerManagerService *service =
- SpeakerManagerService::GetOrCreateSpeakerManagerService();
- MOZ_ASSERT(service);
- service->ForceSpeaker(isActive, mVisible);
- }
-}
-
-} // namespace dom
-} // namespace mozilla
diff --git a/dom/speakermanager/SpeakerManager.h b/dom/speakermanager/SpeakerManager.h
deleted file mode 100644
index bf084dfd9..000000000
--- a/dom/speakermanager/SpeakerManager.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/* -*- 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_dom_SpeakerManager_h
-#define mozilla_dom_SpeakerManager_h
-
-#include "mozilla/DOMEventTargetHelper.h"
-#include "mozilla/dom/MozSpeakerManagerBinding.h"
-
-namespace mozilla {
-namespace dom {
-/* This class is used for UA to control devices's speaker status.
- * After UA set the speaker status, the UA should handle the
- * forcespeakerchange event and change the speaker status in UI.
- * The device's speaker status would set back to normal when UA close the application.
- */
-class SpeakerManager final
- : public DOMEventTargetHelper
- , public nsIDOMEventListener
-{
- friend class SpeakerManagerService;
- friend class SpeakerManagerServiceChild;
-
- NS_DECL_ISUPPORTS_INHERITED
- NS_DECL_NSIDOMEVENTLISTENER
-
-public:
- void Init(nsPIDOMWindowInner* aWindow);
-
- nsPIDOMWindowInner* GetParentObject() const;
-
- virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
- /**
- * WebIDL Interface
- */
- // Get this api's force speaker setting.
- bool Forcespeaker();
- // Force acoustic sound go through speaker. Don't force to speaker if application
- // stay in the background and re-force when application
- // go to foreground
- void SetForcespeaker(bool aEnable);
- // Get the device's speaker forced setting.
- bool Speakerforced();
-
- void SetAudioChannelActive(bool aIsActive);
- IMPL_EVENT_HANDLER(speakerforcedchange)
-
- static already_AddRefed<SpeakerManager>
- Constructor(const GlobalObject& aGlobal, ErrorResult& aRv);
-
-protected:
- SpeakerManager();
- ~SpeakerManager();
- void DispatchSimpleEvent(const nsAString& aStr);
- // This api's force speaker setting
- bool mForcespeaker;
- bool mVisible;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_SpeakerManager_h
diff --git a/dom/speakermanager/SpeakerManagerService.cpp b/dom/speakermanager/SpeakerManagerService.cpp
deleted file mode 100644
index a444f7163..000000000
--- a/dom/speakermanager/SpeakerManagerService.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/* -*- 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 "SpeakerManagerService.h"
-#include "SpeakerManagerServiceChild.h"
-#include "mozilla/Services.h"
-#include "mozilla/StaticPtr.h"
-#include "mozilla/Unused.h"
-#include "mozilla/dom/ContentParent.h"
-#include "nsIPropertyBag2.h"
-#include "nsThreadUtils.h"
-#include "nsServiceManagerUtils.h"
-#include "AudioChannelService.h"
-#include <cutils/properties.h>
-
-#define NS_AUDIOMANAGER_CONTRACTID "@mozilla.org/telephony/audiomanager;1"
-#include "nsIAudioManager.h"
-
-using namespace mozilla;
-using namespace mozilla::dom;
-
-StaticRefPtr<SpeakerManagerService> gSpeakerManagerService;
-
-// static
-SpeakerManagerService*
-SpeakerManagerService::GetOrCreateSpeakerManagerService()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!XRE_IsParentProcess()) {
- return SpeakerManagerServiceChild::GetOrCreateSpeakerManagerService();
- }
-
- // If we already exist, exit early
- if (gSpeakerManagerService) {
- return gSpeakerManagerService;
- }
-
- // Create new instance, register, return
- RefPtr<SpeakerManagerService> service = new SpeakerManagerService();
-
- gSpeakerManagerService = service;
-
- return gSpeakerManagerService;
-}
-
-SpeakerManagerService*
-SpeakerManagerService::GetSpeakerManagerService()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!XRE_IsParentProcess()) {
- return SpeakerManagerServiceChild::GetSpeakerManagerService();
- }
-
- return gSpeakerManagerService;
-}
-
-void
-SpeakerManagerService::Shutdown()
-{
- if (!XRE_IsParentProcess()) {
- return SpeakerManagerServiceChild::Shutdown();
- }
-
- if (gSpeakerManagerService) {
- gSpeakerManagerService = nullptr;
- }
-}
-
-NS_IMPL_ISUPPORTS(SpeakerManagerService, nsIObserver)
-
-void
-SpeakerManagerService::ForceSpeaker(bool aEnable, uint64_t aChildId)
-{
- TurnOnSpeaker(aEnable);
- if (aEnable) {
- mSpeakerStatusSet.Put(aChildId);
- }
- Notify();
- return;
-}
-
-void
-SpeakerManagerService::ForceSpeaker(bool aEnable, bool aVisible)
-{
- // b2g main process without oop
- TurnOnSpeaker(aEnable && aVisible);
- mVisible = aVisible;
- mOrgSpeakerStatus = aEnable;
- Notify();
-}
-
-void
-SpeakerManagerService::TurnOnSpeaker(bool aOn)
-{
- nsCOMPtr<nsIAudioManager> audioManager = do_GetService(NS_AUDIOMANAGER_CONTRACTID);
- NS_ENSURE_TRUE_VOID(audioManager);
- int32_t phoneState;
- audioManager->GetPhoneState(&phoneState);
- int32_t forceuse = (phoneState == nsIAudioManager::PHONE_STATE_IN_CALL ||
- phoneState == nsIAudioManager::PHONE_STATE_IN_COMMUNICATION)
- ? nsIAudioManager::USE_COMMUNICATION : nsIAudioManager::USE_MEDIA;
- if (aOn) {
- audioManager->SetForceForUse(forceuse, nsIAudioManager::FORCE_SPEAKER);
- } else {
- audioManager->SetForceForUse(forceuse, nsIAudioManager::FORCE_NONE);
- }
-}
-
-bool
-SpeakerManagerService::GetSpeakerStatus()
-{
- char propQemu[PROPERTY_VALUE_MAX];
- property_get("ro.kernel.qemu", propQemu, "");
- if (!strncmp(propQemu, "1", 1)) {
- return mOrgSpeakerStatus;
- }
- nsCOMPtr<nsIAudioManager> audioManager = do_GetService(NS_AUDIOMANAGER_CONTRACTID);
- NS_ENSURE_TRUE(audioManager, false);
- int32_t usage;
- audioManager->GetForceForUse(nsIAudioManager::USE_MEDIA, &usage);
- return usage == nsIAudioManager::FORCE_SPEAKER;
-}
-
-void
-SpeakerManagerService::Notify()
-{
- // Parent Notify to all the child processes.
- nsTArray<ContentParent*> children;
- ContentParent::GetAll(children);
- for (uint32_t i = 0; i < children.Length(); i++) {
- Unused << children[i]->SendSpeakerManagerNotify();
- }
-
- for (uint32_t i = 0; i < mRegisteredSpeakerManagers.Length(); i++) {
- mRegisteredSpeakerManagers[i]->
- DispatchSimpleEvent(NS_LITERAL_STRING("speakerforcedchange"));
- }
-}
-
-void
-SpeakerManagerService::SetAudioChannelActive(bool aIsActive)
-{
- if (!aIsActive && !mVisible) {
- ForceSpeaker(!mOrgSpeakerStatus, mVisible);
- }
-}
-
-NS_IMETHODIMP
-SpeakerManagerService::Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData)
-{
- if (!strcmp(aTopic, "ipc:content-shutdown")) {
- nsCOMPtr<nsIPropertyBag2> props = do_QueryInterface(aSubject);
- if (!props) {
- NS_WARNING("ipc:content-shutdown message without property bag as subject");
- return NS_OK;
- }
-
- uint64_t childID = 0;
- nsresult rv = props->GetPropertyAsUint64(NS_LITERAL_STRING("childID"),
- &childID);
- if (NS_SUCCEEDED(rv)) {
- // If the audio has paused by audiochannel,
- // the enable flag should be false and don't need to handle.
- if (mSpeakerStatusSet.Contains(childID)) {
- TurnOnSpeaker(false);
- mSpeakerStatusSet.Remove(childID);
- }
- if (mOrgSpeakerStatus) {
- TurnOnSpeaker(!mOrgSpeakerStatus);
- mOrgSpeakerStatus = false;
- }
- } else {
- NS_WARNING("ipc:content-shutdown message without childID property");
- }
- } else if (!strcmp(aTopic, "xpcom-will-shutdown")) {
- // Note that we need to do this before xpcom-shutdown, since the
- // AudioChannelService cannot be used past that point.
- RefPtr<AudioChannelService> audioChannelService =
- AudioChannelService::GetOrCreate();
- if (audioChannelService) {
- audioChannelService->UnregisterSpeakerManager(this);
- }
-
- nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
- if (obs) {
- obs->RemoveObserver(this, "ipc:content-shutdown");
- obs->RemoveObserver(this, "xpcom-will-shutdown");
- }
-
- Shutdown();
- }
- return NS_OK;
-}
-
-SpeakerManagerService::SpeakerManagerService()
- : mOrgSpeakerStatus(false),
- mVisible(false)
-{
- MOZ_COUNT_CTOR(SpeakerManagerService);
- if (XRE_IsParentProcess()) {
- nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
- if (obs) {
- obs->AddObserver(this, "ipc:content-shutdown", false);
- obs->AddObserver(this, "xpcom-will-shutdown", false);
- }
- }
- RefPtr<AudioChannelService> audioChannelService =
- AudioChannelService::GetOrCreate();
- if (audioChannelService) {
- audioChannelService->RegisterSpeakerManager(this);
- }
-}
-
-SpeakerManagerService::~SpeakerManagerService()
-{
- MOZ_COUNT_DTOR(SpeakerManagerService);
-}
diff --git a/dom/speakermanager/SpeakerManagerService.h b/dom/speakermanager/SpeakerManagerService.h
deleted file mode 100644
index 5f3506ae2..000000000
--- a/dom/speakermanager/SpeakerManagerService.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/* -*- 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_dom_SpeakerManagerService_h__
-#define mozilla_dom_SpeakerManagerService_h__
-
-#include "nsIObserver.h"
-#include "nsTArray.h"
-#include "SpeakerManager.h"
-#include "nsIAudioManager.h"
-#include "nsCheapSets.h"
-#include "nsHashKeys.h"
-
-namespace mozilla {
-namespace dom {
-
-class SpeakerManagerService : public nsIObserver
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIOBSERVER
- /*
- * Return null or instance which has been created.
- */
- static SpeakerManagerService* GetSpeakerManagerService();
- /*
- * Return SpeakerManagerService instance.
- * If SpeakerManagerService is not exist, create and return new one.
- */
- static SpeakerManagerService* GetOrCreateSpeakerManagerService();
- virtual void ForceSpeaker(bool aEnable, bool aVisible);
- virtual bool GetSpeakerStatus();
- virtual void SetAudioChannelActive(bool aIsActive);
- // Called by child
- void ForceSpeaker(bool enable, uint64_t aChildid);
- // Register the SpeakerManager to service for notify the speakerforcedchange event
- void RegisterSpeakerManager(SpeakerManager* aSpeakerManager)
- {
- mRegisteredSpeakerManagers.AppendElement(aSpeakerManager);
- }
- void UnRegisterSpeakerManager(SpeakerManager* aSpeakerManager)
- {
- mRegisteredSpeakerManagers.RemoveElement(aSpeakerManager);
- }
-
-protected:
- SpeakerManagerService();
-
- virtual ~SpeakerManagerService();
- // Notify to UA if device speaker status changed
- virtual void Notify();
-
- void TurnOnSpeaker(bool aEnable);
-
- /**
- * Shutdown the singleton.
- */
- static void Shutdown();
-
- nsTArray<RefPtr<SpeakerManager> > mRegisteredSpeakerManagers;
- // Set for remember all the child speaker status
- nsCheapSet<nsUint64HashKey> mSpeakerStatusSet;
- // The Speaker status assign by UA
- bool mOrgSpeakerStatus;
-
- bool mVisible;
- // This is needed for IPC communication between
- // SpeakerManagerServiceChild and this class.
- friend class ContentParent;
- friend class ContentChild;
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif
diff --git a/dom/speakermanager/SpeakerManagerServiceChild.cpp b/dom/speakermanager/SpeakerManagerServiceChild.cpp
deleted file mode 100644
index 6c1e30b78..000000000
--- a/dom/speakermanager/SpeakerManagerServiceChild.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/* -*- 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 "SpeakerManagerServiceChild.h"
-#include "mozilla/Services.h"
-#include "mozilla/StaticPtr.h"
-#include "mozilla/Unused.h"
-#include "mozilla/dom/ContentChild.h"
-#include "mozilla/dom/ContentParent.h"
-#include "nsIObserverService.h"
-#include "nsThreadUtils.h"
-#include "AudioChannelService.h"
-#include <cutils/properties.h>
-
-using namespace mozilla;
-using namespace mozilla::dom;
-
-StaticRefPtr<SpeakerManagerServiceChild> gSpeakerManagerServiceChild;
-
-// static
-SpeakerManagerService*
-SpeakerManagerServiceChild::GetOrCreateSpeakerManagerService()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- // If we already exist, exit early
- if (gSpeakerManagerServiceChild) {
- return gSpeakerManagerServiceChild;
- }
-
- // Create new instance, register, return
- RefPtr<SpeakerManagerServiceChild> service = new SpeakerManagerServiceChild();
-
- gSpeakerManagerServiceChild = service;
-
- return gSpeakerManagerServiceChild;
-}
-
-// static
-SpeakerManagerService*
-SpeakerManagerServiceChild::GetSpeakerManagerService()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- return gSpeakerManagerServiceChild;
-}
-
-void
-SpeakerManagerServiceChild::ForceSpeaker(bool aEnable, bool aVisible)
-{
- mVisible = aVisible;
- mOrgSpeakerStatus = aEnable;
- ContentChild *cc = ContentChild::GetSingleton();
- if (cc) {
- cc->SendSpeakerManagerForceSpeaker(aEnable && aVisible);
- }
-}
-
-bool
-SpeakerManagerServiceChild::GetSpeakerStatus()
-{
- ContentChild *cc = ContentChild::GetSingleton();
- bool status = false;
- if (cc) {
- cc->SendSpeakerManagerGetSpeakerStatus(&status);
- }
- char propQemu[PROPERTY_VALUE_MAX];
- property_get("ro.kernel.qemu", propQemu, "");
- if (!strncmp(propQemu, "1", 1)) {
- return mOrgSpeakerStatus;
- }
- return status;
-}
-
-void
-SpeakerManagerServiceChild::Shutdown()
-{
- if (gSpeakerManagerServiceChild) {
- gSpeakerManagerServiceChild = nullptr;
- }
-}
-
-void
-SpeakerManagerServiceChild::SetAudioChannelActive(bool aIsActive)
-{
- // Content process and switch to background with no audio and speaker forced.
- // Then disable speaker
- for (uint32_t i = 0; i < mRegisteredSpeakerManagers.Length(); i++) {
- mRegisteredSpeakerManagers[i]->SetAudioChannelActive(aIsActive);
- }
-}
-
-SpeakerManagerServiceChild::SpeakerManagerServiceChild()
-{
- MOZ_ASSERT(NS_IsMainThread());
- RefPtr<AudioChannelService> audioChannelService = AudioChannelService::GetOrCreate();
- if (audioChannelService) {
- audioChannelService->RegisterSpeakerManager(this);
- }
- MOZ_COUNT_CTOR(SpeakerManagerServiceChild);
-}
-
-SpeakerManagerServiceChild::~SpeakerManagerServiceChild()
-{
- RefPtr<AudioChannelService> audioChannelService = AudioChannelService::GetOrCreate();
- if (audioChannelService) {
- audioChannelService->UnregisterSpeakerManager(this);
- }
- MOZ_COUNT_DTOR(SpeakerManagerServiceChild);
-}
-
-void
-SpeakerManagerServiceChild::Notify()
-{
- for (uint32_t i = 0; i < mRegisteredSpeakerManagers.Length(); i++) {
- mRegisteredSpeakerManagers[i]->DispatchSimpleEvent(NS_LITERAL_STRING("speakerforcedchange"));
- }
-}
diff --git a/dom/speakermanager/SpeakerManagerServiceChild.h b/dom/speakermanager/SpeakerManagerServiceChild.h
deleted file mode 100644
index 5eb1c6afa..000000000
--- a/dom/speakermanager/SpeakerManagerServiceChild.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/* -*- 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_dom_SpeakerManagerServicechild_h__
-#define mozilla_dom_SpeakerManagerServicechild_h__
-
-#include "nsISupports.h"
-#include "SpeakerManagerService.h"
-
-namespace mozilla {
-namespace dom {
-/* This class is used to do the IPC to enable/disable speaker status
- Also handle the application speaker competition problem
-*/
-class SpeakerManagerServiceChild : public SpeakerManagerService
-{
-public:
- /*
- * Return null or instance which has been created.
- */
- static SpeakerManagerService* GetSpeakerManagerService();
- /*
- * Return SpeakerManagerServiceChild instance.
- * If SpeakerManagerServiceChild is not exist, create and return new one.
- */
- static SpeakerManagerService* GetOrCreateSpeakerManagerService();
- static void Shutdown();
- virtual void ForceSpeaker(bool aEnable, bool aVisible) override;
- virtual bool GetSpeakerStatus() override;
- virtual void SetAudioChannelActive(bool aIsActive) override;
- virtual void Notify() override;
-protected:
- SpeakerManagerServiceChild();
- virtual ~SpeakerManagerServiceChild();
-};
-
-} // namespace dom
-} // namespace mozilla
-
-#endif
-
diff --git a/dom/speakermanager/moz.build b/dom/speakermanager/moz.build
deleted file mode 100644
index 22ed849fb..000000000
--- a/dom/speakermanager/moz.build
+++ /dev/null
@@ -1,23 +0,0 @@
-# -*- 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/.
-
-MOCHITEST_MANIFESTS += ['tests/mochitest.ini']
-
-EXPORTS += [
- 'SpeakerManager.h',
- 'SpeakerManagerService.h',
- 'SpeakerManagerServiceChild.h',
-]
-
-UNIFIED_SOURCES += [
- 'SpeakerManager.cpp',
- 'SpeakerManagerService.cpp',
- 'SpeakerManagerServiceChild.cpp',
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
diff --git a/dom/speakermanager/tests/mochitest.ini b/dom/speakermanager/tests/mochitest.ini
deleted file mode 100644
index bb272adc0..000000000
--- a/dom/speakermanager/tests/mochitest.ini
+++ /dev/null
@@ -1,3 +0,0 @@
-[DEFAULT]
-
-[test_speakermanager.html]
diff --git a/dom/speakermanager/tests/test_speakermanager.html b/dom/speakermanager/tests/test_speakermanager.html
deleted file mode 100644
index 509df5e84..000000000
--- a/dom/speakermanager/tests/test_speakermanager.html
+++ /dev/null
@@ -1,53 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<head>
- <meta charset="utf-8">
- <title>Test MozSpeakerManager API</title>
- <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
- <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-</head>
-<body>
-<p id="display"></p>
-<div id="content" style="display: none"></div>
-<pre id="test">
- <script type="application/javascript">
-
- "use strict";
-
- function testObject() {
- var mgr = new MozSpeakerManager();
- var spkforced = false;
- mgr.onspeakerforcedchange = function() {
- if (spkforced) {
- is(mgr.speakerforced, true, 'speaker should be true');
- spkforced = false;
- mgr.forcespeaker = false;
- } else {
- is(mgr.speakerforced, false, 'speaker should be false');
- SimpleTest.finish();
- }
- }
- spkforced = true;
- mgr.forcespeaker = true;
- }
-
- function startTests() {
- // Currently applicable only on FxOS
- if (navigator.userAgent.indexOf("Mobile") != -1 &&
- navigator.appVersion.indexOf("Android") == -1) {
- testObject();
- } else {
- ok(true, "MozSpeakerManager on Firefox OS only.");
- SimpleTest.finish();
- }
- }
-
- SimpleTest.waitForExplicitFinish();
- SpecialPowers.pushPermissions(
- [{ "type": "speaker-control", "allow": 1, "context": document }],
- startTests);
-
- </script>
-</pre>
-</body>
-</html>
diff --git a/dom/system/OSFileConstants.cpp b/dom/system/OSFileConstants.cpp
index 945233f4c..86377e75a 100644
--- a/dom/system/OSFileConstants.cpp
+++ b/dom/system/OSFileConstants.cpp
@@ -924,16 +924,6 @@ bool DefineOSFileConstants(JSContext *cx, JS::Handle<JSObject*> global)
return false;
}
-#if defined(MOZ_WIDGET_GONK)
- JSString* strVersion = JS_NewStringCopyZ(cx, "Gonk");
- if (!strVersion){
- return false;
- }
- JS::Rooted<JS::Value> valVersion(cx, JS::StringValue(strVersion));
- if (!JS_SetProperty(cx, objSys, "Name", valVersion)) {
- return false;
- }
-#else
nsCOMPtr<nsIXULRuntime> runtime = do_GetService(XULRUNTIME_SERVICE_CONTRACTID);
if (runtime) {
nsAutoCString os;
@@ -950,7 +940,6 @@ bool DefineOSFileConstants(JSContext *cx, JS::Handle<JSObject*> global)
return false;
}
}
-#endif // defined(MOZ_WIDGET_GONK)
#if defined(DEBUG)
JS::Rooted<JS::Value> valDebug(cx, JS::TrueValue());
diff --git a/dom/system/gonk/AudioChannelManager.cpp b/dom/system/gonk/AudioChannelManager.cpp
deleted file mode 100644
index 977715a29..000000000
--- a/dom/system/gonk/AudioChannelManager.cpp
+++ /dev/null
@@ -1,181 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsIDocument.h"
-#include "nsIDOMClassInfo.h"
-#include "nsIDOMEvent.h"
-#include "nsIDOMEventListener.h"
-#include "nsPIDOMWindow.h"
-#include "nsIDocShell.h"
-#include "nsIPermissionManager.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "AudioChannelManager.h"
-#include "mozilla/dom/AudioChannelManagerBinding.h"
-#include "mozilla/dom/nsBrowserElement.h"
-#include "mozilla/Services.h"
-
-namespace mozilla {
-namespace dom {
-namespace system {
-
-NS_IMPL_QUERY_INTERFACE_INHERITED(AudioChannelManager, DOMEventTargetHelper,
- nsIDOMEventListener)
-NS_IMPL_ADDREF_INHERITED(AudioChannelManager, DOMEventTargetHelper)
-NS_IMPL_RELEASE_INHERITED(AudioChannelManager, DOMEventTargetHelper)
-
-AudioChannelManager::AudioChannelManager()
- : mVolumeChannel(-1)
-{
- hal::RegisterSwitchObserver(hal::SWITCH_HEADPHONES, this);
-}
-
-AudioChannelManager::~AudioChannelManager()
-{
- hal::UnregisterSwitchObserver(hal::SWITCH_HEADPHONES, this);
-
- nsCOMPtr<EventTarget> target = do_QueryInterface(GetOwner());
- NS_ENSURE_TRUE_VOID(target);
-
- target->RemoveSystemEventListener(NS_LITERAL_STRING("visibilitychange"),
- this,
- /* useCapture = */ true);
-}
-
-void
-AudioChannelManager::Init(nsPIDOMWindowInner* aWindow)
-{
- BindToOwner(aWindow);
-
- nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(GetOwner());
- NS_ENSURE_TRUE_VOID(target);
-
- target->AddSystemEventListener(NS_LITERAL_STRING("visibilitychange"),
- this,
- /* useCapture = */ true,
- /* wantsUntrusted = */ false);
-}
-
-JSObject*
-AudioChannelManager::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
-{
- return AudioChannelManagerBinding::Wrap(aCx, this, aGivenProto);
-}
-
-void
-AudioChannelManager::Notify(const hal::SwitchEvent& aEvent)
-{
- mState = Some(aEvent.status());
-
- DispatchTrustedEvent(NS_LITERAL_STRING("headphoneschange"));
-}
-
-bool
-AudioChannelManager::SetVolumeControlChannel(const nsAString& aChannel)
-{
- if (aChannel.EqualsASCII("publicnotification")) {
- return false;
- }
-
- AudioChannel newChannel = AudioChannelService::GetAudioChannel(aChannel);
-
- // Only normal channel doesn't need permission.
- if (newChannel != AudioChannel::Normal) {
- nsCOMPtr<nsIPermissionManager> permissionManager =
- services::GetPermissionManager();
- if (!permissionManager) {
- return false;
- }
- uint32_t perm = nsIPermissionManager::UNKNOWN_ACTION;
- permissionManager->TestPermissionFromWindow(GetOwner(),
- nsCString(NS_LITERAL_CSTRING("audio-channel-") +
- NS_ConvertUTF16toUTF8(aChannel)).get(), &perm);
- if (perm != nsIPermissionManager::ALLOW_ACTION) {
- return false;
- }
- }
-
- if (mVolumeChannel == (int32_t)newChannel) {
- return true;
- }
-
- mVolumeChannel = (int32_t)newChannel;
-
- NotifyVolumeControlChannelChanged();
- return true;
-}
-
-bool
-AudioChannelManager::GetVolumeControlChannel(nsAString & aChannel)
-{
- if (mVolumeChannel >= 0) {
- AudioChannelService::GetAudioChannelString(
- static_cast<AudioChannel>(mVolumeChannel),
- aChannel);
- } else {
- aChannel.AssignASCII("");
- }
-
- return true;
-}
-
-void
-AudioChannelManager::NotifyVolumeControlChannelChanged()
-{
- nsCOMPtr<nsIDocShell> docshell = do_GetInterface(GetOwner());
- NS_ENSURE_TRUE_VOID(docshell);
-
- bool isActive = false;
- docshell->GetIsActive(&isActive);
-
- RefPtr<AudioChannelService> service = AudioChannelService::GetOrCreate();
- if (!service) {
- return;
- }
-
- if (isActive) {
- service->SetDefaultVolumeControlChannel(mVolumeChannel, isActive);
- } else {
- service->SetDefaultVolumeControlChannel(-1, isActive);
- }
-}
-
-NS_IMETHODIMP
-AudioChannelManager::HandleEvent(nsIDOMEvent* aEvent)
-{
- nsAutoString type;
- aEvent->GetType(type);
-
- if (type.EqualsLiteral("visibilitychange")) {
- NotifyVolumeControlChannelChanged();
- }
- return NS_OK;
-}
-
-void
-AudioChannelManager::GetAllowedAudioChannels(
- nsTArray<RefPtr<BrowserElementAudioChannel>>& aAudioChannels,
- ErrorResult& aRv)
-{
- MOZ_ASSERT(aAudioChannels.IsEmpty());
-
- // Only main process is supported.
- if (XRE_GetProcessType() != GeckoProcessType_Default) {
- aRv.Throw(NS_ERROR_FAILURE);
- return;
- }
-
- nsCOMPtr<nsPIDOMWindowInner> window = GetOwner();
- if (NS_WARN_IF(!window)) {
- aRv.Throw(NS_ERROR_FAILURE);
- return;
- }
-
- nsBrowserElement::GenerateAllowedAudioChannels(window, nullptr, nullptr,
- aAudioChannels, aRv);
- NS_WARNING_ASSERTION(!aRv.Failed(), "GenerateAllowedAudioChannels failed");
-}
-
-} // namespace system
-} // namespace dom
-} // namespace mozilla
diff --git a/dom/system/gonk/AudioChannelManager.h b/dom/system/gonk/AudioChannelManager.h
deleted file mode 100644
index a460651e7..000000000
--- a/dom/system/gonk/AudioChannelManager.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_dom_system_AudioChannelManager_h
-#define mozilla_dom_system_AudioChannelManager_h
-
-#include "mozilla/dom/BrowserElementAudioChannel.h"
-#include "mozilla/DOMEventTargetHelper.h"
-#include "mozilla/Hal.h"
-#include "mozilla/HalTypes.h"
-#include "mozilla/Maybe.h"
-#include "AudioChannelService.h"
-
-namespace mozilla {
-namespace hal {
-class SwitchEvent;
-typedef Observer<SwitchEvent> SwitchObserver;
-} // namespace hal
-
-namespace dom {
-namespace system {
-
-class AudioChannelManager final
- : public DOMEventTargetHelper
- , public hal::SwitchObserver
- , public nsIDOMEventListener
-{
-public:
- AudioChannelManager();
-
- NS_DECL_ISUPPORTS_INHERITED
- NS_DECL_NSIDOMEVENTLISTENER
-
- void Notify(const hal::SwitchEvent& aEvent);
-
- void Init(nsPIDOMWindowInner* aWindow);
-
- /**
- * WebIDL Interface
- */
-
- nsPIDOMWindowInner* GetParentObject() const
- {
- return GetOwner();
- }
-
- virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
-
- bool Headphones()
- {
- // Bug 929139 - Remove the assert check for SWITCH_STATE_UNKNOWN.
- // If any devices (ex: emulator) didn't have the corresponding sys node for
- // headset switch state then GonkSwitch will report the unknown state.
- // So it is possible to get unknown state here.
- if (mState.isNothing()) {
- mState = Some(hal::GetCurrentSwitchState(hal::SWITCH_HEADPHONES));
- }
- return mState.value() != hal::SWITCH_STATE_OFF &&
- mState.value() != hal::SWITCH_STATE_UNKNOWN;
- }
-
- bool SetVolumeControlChannel(const nsAString& aChannel);
-
- bool GetVolumeControlChannel(nsAString& aChannel);
-
- IMPL_EVENT_HANDLER(headphoneschange)
-
- void GetAllowedAudioChannels(
- nsTArray<RefPtr<mozilla::dom::BrowserElementAudioChannel>>& aAudioChannels,
- mozilla::ErrorResult& aRv);
-
-protected:
- virtual ~AudioChannelManager();
-
-private:
- void NotifyVolumeControlChannelChanged();
-
- Maybe<hal::SwitchState> mState;
- int32_t mVolumeChannel;
-};
-
-} // namespace system
-} // namespace dom
-} // namespace mozilla
-
-#endif // mozilla_dom_system_AudioChannelManager_h
diff --git a/dom/system/gonk/AudioManager.cpp b/dom/system/gonk/AudioManager.cpp
deleted file mode 100644
index 88dff13f7..000000000
--- a/dom/system/gonk/AudioManager.cpp
+++ /dev/null
@@ -1,1412 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <android/log.h>
-#include <cutils/properties.h>
-#include <binder/IServiceManager.h>
-
-#include "AudioChannelService.h"
-#include "AudioManager.h"
-
-#include "nsIObserverService.h"
-#include "nsISettingsService.h"
-#include "nsPrintfCString.h"
-
-#include "mozilla/Hal.h"
-#include "mozilla/Services.h"
-#include "mozilla/StaticPtr.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/MozPromise.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "base/message_loop.h"
-
-#include "BluetoothCommon.h"
-#include "BluetoothHfpManagerBase.h"
-
-#include "nsJSUtils.h"
-#include "nsThreadUtils.h"
-#include "nsServiceManagerUtils.h"
-#include "nsComponentManagerUtils.h"
-#include "nsContentUtils.h"
-#include "nsXULAppAPI.h"
-#include "mozilla/dom/BindingUtils.h"
-#include "mozilla/dom/SettingChangeNotificationBinding.h"
-
-using namespace mozilla::dom;
-using namespace mozilla::dom::gonk;
-using namespace android;
-using namespace mozilla;
-using namespace mozilla::dom::bluetooth;
-
-#undef LOG
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "AudioManager" , ## args)
-
-#define HEADPHONES_STATUS_HEADSET u"headset"
-#define HEADPHONES_STATUS_HEADPHONE u"headphone"
-#define HEADPHONES_STATUS_OFF u"off"
-#define HEADPHONES_STATUS_UNKNOWN u"unknown"
-#define HEADPHONES_STATUS_CHANGED "headphones-status-changed"
-#define MOZ_SETTINGS_CHANGE_ID "mozsettings-changed"
-#define AUDIO_CHANNEL_PROCESS_CHANGED "audio-channel-process-changed"
-#define AUDIO_POLICY_SERVICE_NAME "media.audio_policy"
-#define SETTINGS_SERVICE "@mozilla.org/settingsService;1"
-
-// Refer AudioService.java from Android
-static const uint32_t sMaxStreamVolumeTbl[AUDIO_STREAM_CNT] = {
- 5, // voice call
- 15, // system
- 15, // ring
- 15, // music
- 15, // alarm
- 15, // notification
- 15, // BT SCO
- 15, // enforced audible
- 15, // DTMF
- 15, // TTS
-#if ANDROID_VERSION < 19
- 15, // FM
-#endif
-};
-
-static const uint32_t sDefaultStreamVolumeTbl[AUDIO_STREAM_CNT] = {
- 3, // voice call
- 8, // system
- 8, // ring
- 8, // music
- 8, // alarm
- 8, // notification
- 8, // BT SCO
- 15, // enforced audible // XXX Handle as fixed maximum audio setting
- 8, // DTMF
- 8, // TTS
-#if ANDROID_VERSION < 19
- 8, // FM
-#endif
-};
-
-static const int32_t sStreamVolumeAliasTbl[AUDIO_STREAM_CNT] = {
- AUDIO_STREAM_VOICE_CALL, // voice call
- AUDIO_STREAM_NOTIFICATION, // system
- AUDIO_STREAM_NOTIFICATION, // ring
- AUDIO_STREAM_MUSIC, // music
- AUDIO_STREAM_ALARM, // alarm
- AUDIO_STREAM_NOTIFICATION, // notification
- AUDIO_STREAM_BLUETOOTH_SCO, // BT SCO
- AUDIO_STREAM_ENFORCED_AUDIBLE,// enforced audible
- AUDIO_STREAM_DTMF, // DTMF
- AUDIO_STREAM_TTS, // TTS
-#if ANDROID_VERSION < 19
- AUDIO_STREAM_MUSIC, // FM
-#endif
-};
-
-static const uint32_t sChannelStreamTbl[NUMBER_OF_AUDIO_CHANNELS] = {
- AUDIO_STREAM_MUSIC, // AudioChannel::Normal
- AUDIO_STREAM_MUSIC, // AudioChannel::Content
- AUDIO_STREAM_NOTIFICATION, // AudioChannel::Notification
- AUDIO_STREAM_ALARM, // AudioChannel::Alarm
- AUDIO_STREAM_VOICE_CALL, // AudioChannel::Telephony
- AUDIO_STREAM_RING, // AudioChannel::Ringer
- AUDIO_STREAM_ENFORCED_AUDIBLE,// AudioChannel::Publicnotification
- AUDIO_STREAM_SYSTEM, // AudioChannel::System
-};
-
-
-struct AudioDeviceInfo {
- /** The string the value maps to */
- const char* tag;
- /** The enum value that maps to this string */
- uint32_t value;
-};
-
-// Mappings audio output devices to strings.
-static const AudioDeviceInfo kAudioDeviceInfos[] = {
- { "earpiece", AUDIO_DEVICE_OUT_EARPIECE },
- { "speaker", AUDIO_DEVICE_OUT_SPEAKER },
- { "wired_headset", AUDIO_DEVICE_OUT_WIRED_HEADSET },
- { "wired_headphone", AUDIO_DEVICE_OUT_WIRED_HEADPHONE },
- { "bt_scoheadset", AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET },
- { "bt_a2dp", AUDIO_DEVICE_OUT_BLUETOOTH_A2DP },
-};
-
-static const int kBtSampleRate = 8000;
-
-typedef MozPromise<bool, const char*, true> VolumeInitPromise;
-
-namespace mozilla {
-namespace dom {
-namespace gonk {
-
-/**
- * We have five sound volume settings from UX spec,
- * You can see more informations in Bug1068219.
- * (1) Media : music, video, FM ...
- * (2) Notification : ringer, notification ...
- * (3) Alarm : alarm
- * (4) Telephony : GSM call, WebRTC call
- * (5) Bluetooth SCO : SCO call
- **/
-struct VolumeData {
- const char* mChannelName;
- int32_t mStreamType;
-};
-
-static const VolumeData gVolumeData[] = {
- {"audio.volume.content", AUDIO_STREAM_MUSIC},
- {"audio.volume.notification", AUDIO_STREAM_NOTIFICATION},
- {"audio.volume.alarm", AUDIO_STREAM_ALARM},
- {"audio.volume.telephony", AUDIO_STREAM_VOICE_CALL},
- {"audio.volume.bt_sco", AUDIO_STREAM_BLUETOOTH_SCO}
-};
-
-class RunnableCallTask : public Runnable
-{
-public:
- explicit RunnableCallTask(nsIRunnable* aRunnable)
- : mRunnable(aRunnable) {}
-
- NS_IMETHOD Run() override
- {
- return mRunnable->Run();
- }
-protected:
- nsCOMPtr<nsIRunnable> mRunnable;
-};
-
-nsCOMPtr<nsISettingsServiceLock>
-GetSettingServiceLock()
-{
- nsresult rv;
- nsCOMPtr<nsISettingsService> service = do_GetService(SETTINGS_SERVICE, &rv);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return nullptr;
- }
-
- nsCOMPtr<nsISettingsServiceLock> lock;
- rv = service->CreateLock(nullptr, getter_AddRefs(lock));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return nullptr;
- }
- return lock.forget();
-}
-
-#if ANDROID_VERSION >= 21
-class GonkAudioPortCallback : public AudioSystem::AudioPortCallback
-{
-public:
- virtual void onAudioPortListUpdate()
- {
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([]() {
- MOZ_ASSERT(NS_IsMainThread());
- RefPtr<AudioManager> audioManager = AudioManager::GetInstance();
- NS_ENSURE_TRUE(audioManager.get(), );
- audioManager->UpdateCachedActiveDevicesForStreams();
- audioManager->MaybeUpdateVolumeSettingToDatabase();
- });
- NS_DispatchToMainThread(runnable);
- }
- virtual void onAudioPatchListUpdate() { }
- virtual void onServiceDied() { }
-};
-#endif
-
-void
-AudioManager::HandleAudioFlingerDied()
-{
- //Disable volume change notification
- mIsVolumeInited = false;
-
- uint32_t attempt;
- for (attempt = 0; attempt < 50; attempt++) {
- if (defaultServiceManager()->checkService(String16(AUDIO_POLICY_SERVICE_NAME)) != 0) {
- break;
- }
- LOG("AudioPolicyService is dead! attempt=%d", attempt);
- usleep(1000 * 200);
- }
-
- MOZ_RELEASE_ASSERT(attempt < 50);
-
- // Indicate to audio HAL that we start the reconfiguration phase after a media
- // server crash
- AudioSystem::setParameters(0, String8("restarting=true"));
-
- // Restore device connection states
- SetAllDeviceConnectionStates();
-
- // Restore call state
-#if ANDROID_VERSION < 17
- AudioSystem::setPhoneState(mPhoneState);
-#else
- AudioSystem::setPhoneState(static_cast<audio_mode_t>(mPhoneState));
-#endif
-
- // Restore master volume
- AudioSystem::setMasterVolume(1.0);
-
- // Restore stream volumes
- for (uint32_t streamType = 0; streamType < AUDIO_STREAM_CNT; ++streamType) {
- mStreamStates[streamType]->InitStreamVolume();
- mStreamStates[streamType]->RestoreVolumeIndexToAllDevices();
- }
-
- // Indicate the end of reconfiguration phase to audio HAL
- AudioSystem::setParameters(0, String8("restarting=true"));
-
- // Enable volume change notification
- mIsVolumeInited = true;
- mAudioOutDevicesUpdated = 0;
- MaybeUpdateVolumeSettingToDatabase(true);
-}
-
-class VolumeInitCallback final : public nsISettingsServiceCallback
-{
-public:
- NS_DECL_ISUPPORTS
-
- VolumeInitCallback()
- : mInitCounter(0)
- {
- mPromise = mPromiseHolder.Ensure(__func__);
- }
-
- RefPtr<VolumeInitPromise> GetPromise() const
- {
- return mPromise;
- }
-
- NS_IMETHOD Handle(const nsAString& aName, JS::Handle<JS::Value> aResult)
- {
- RefPtr<AudioManager> audioManager = AudioManager::GetInstance();
- MOZ_ASSERT(audioManager);
- for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) {
- NS_ConvertASCIItoUTF16 volumeType(gVolumeData[idx].mChannelName);
- if (StringBeginsWith(aName, volumeType)) {
- uint32_t device = GetDeviceFromSettingName(aName);
- MOZ_ASSERT(device != AUDIO_DEVICE_NONE);
- if (aResult.isInt32()) {
- int32_t stream = gVolumeData[idx].mStreamType;
- uint32_t volIndex = aResult.toInt32();
- nsresult rv = audioManager->ValidateVolumeIndex(stream, volIndex);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- mPromiseHolder.Reject("Error : invalid volume index.", __func__);
- return rv;
- }
- audioManager->SetStreamVolumeForDevice(stream, volIndex, device);
- }
-
- if (++mInitCounter == MOZ_ARRAY_LENGTH(kAudioDeviceInfos) * MOZ_ARRAY_LENGTH(gVolumeData)) {
- mPromiseHolder.Resolve(true, __func__);
- }
- return NS_OK;
- }
- }
- mPromiseHolder.Reject("Error : unexpected audio init event.", __func__);
- return NS_OK;
- }
-
- NS_IMETHOD HandleError(const nsAString& aName)
- {
- mPromiseHolder.Reject(NS_ConvertUTF16toUTF8(aName).get(), __func__);
- return NS_OK;
- }
-
-protected:
- ~VolumeInitCallback() {}
-
- uint32_t GetDeviceFromSettingName(const nsAString& aName) const
- {
- for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(kAudioDeviceInfos); ++idx) {
- NS_ConvertASCIItoUTF16 device(kAudioDeviceInfos[idx].tag);
- if (StringEndsWith(aName, device)) {
- return kAudioDeviceInfos[idx].value;
- }
- }
- return AUDIO_DEVICE_NONE;
- }
-
- RefPtr<VolumeInitPromise> mPromise;
- MozPromiseHolder<VolumeInitPromise> mPromiseHolder;
- uint32_t mInitCounter;
-};
-
-NS_IMPL_ISUPPORTS(VolumeInitCallback, nsISettingsServiceCallback)
-
-static void
-BinderDeadCallback(status_t aErr)
-{
- if (aErr != DEAD_OBJECT) {
- return;
- }
-
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([]() {
- MOZ_ASSERT(NS_IsMainThread());
- RefPtr<AudioManager> audioManager = AudioManager::GetInstance();
- NS_ENSURE_TRUE(audioManager.get(), );
- audioManager->HandleAudioFlingerDied();
- });
-
- NS_DispatchToMainThread(runnable);
-}
-
-bool
-AudioManager::IsFmOutConnected()
-{
- return mConnectedDevices.Get(AUDIO_DEVICE_OUT_FM, nullptr);
-}
-
-NS_IMPL_ISUPPORTS(AudioManager, nsIAudioManager, nsIObserver)
-
-void
-AudioManager::AudioOutDeviceUpdated(uint32_t aDevice)
-{
- MOZ_ASSERT(audio_is_output_device(aDevice));
- mAudioOutDevicesUpdated |= aDevice;
-}
-
-void
-AudioManager::UpdateHeadsetConnectionState(hal::SwitchState aState)
-{
- bool headphoneConnected = mConnectedDevices.Get(AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
- nullptr);
- bool headsetConnected = mConnectedDevices.Get(AUDIO_DEVICE_OUT_WIRED_HEADSET,
- nullptr);
- if (aState == hal::SWITCH_STATE_HEADSET) {
- UpdateDeviceConnectionState(true,
- AUDIO_DEVICE_OUT_WIRED_HEADSET,
- NS_LITERAL_CSTRING(""));
- } else if (aState == hal::SWITCH_STATE_HEADPHONE) {
- UpdateDeviceConnectionState(true,
- AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
- NS_LITERAL_CSTRING(""));
- } else if (aState == hal::SWITCH_STATE_OFF) {
- if (headsetConnected) {
- UpdateDeviceConnectionState(false,
- AUDIO_DEVICE_OUT_WIRED_HEADSET,
- NS_LITERAL_CSTRING(""));
- }
- if (headphoneConnected) {
- UpdateDeviceConnectionState(false,
- AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
- NS_LITERAL_CSTRING(""));
- }
- }
-}
-
-void
-AudioManager::UpdateDeviceConnectionState(bool aIsConnected, uint32_t aDevice, const nsCString& aDeviceName)
-{
-#if ANDROID_VERSION >= 15
- bool isConnected = mConnectedDevices.Get(aDevice, nullptr);
- if (isConnected && !aIsConnected) {
- AudioSystem::setDeviceConnectionState(static_cast<audio_devices_t>(aDevice),
- AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
- aDeviceName.get());
- mConnectedDevices.Remove(aDevice);
- } else if(!isConnected && aIsConnected) {
- AudioSystem::setDeviceConnectionState(static_cast<audio_devices_t>(aDevice),
- AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
- aDeviceName.get());
- mConnectedDevices.Put(aDevice, aDeviceName);
- }
-#if ANDROID_VERSION < 21
- // Manually call it, since AudioPortCallback is not supported.
- // Current volumes might be changed by updating active devices in android
- // AudioPolicyManager.
- MaybeUpdateVolumeSettingToDatabase();
-#endif
-#else
- NS_NOTREACHED("Doesn't support audio routing on GB version");
-#endif
-}
-
-void
-AudioManager::SetAllDeviceConnectionStates()
-{
- for (auto iter = mConnectedDevices.Iter(); !iter.Done(); iter.Next()) {
- const uint32_t& device = iter.Key();
- nsCString& deviceAddress = iter.Data();
- AudioSystem::setDeviceConnectionState(static_cast<audio_devices_t>(device),
- AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
- deviceAddress.get());
- }
-#if ANDROID_VERSION < 21
- // Manually call it, since AudioPortCallback is not supported.
- // Current volumes might be changed by updating active devices in android
- // AudioPolicyManager.
- MaybeUpdateVolumeSettingToDatabase(true);
-#endif
-}
-
-void
-AudioManager::HandleBluetoothStatusChanged(nsISupports* aSubject,
- const char* aTopic,
- const nsCString aAddress)
-{
-#ifdef MOZ_B2G_BT
- bool isConnected = false;
- if (!strcmp(aTopic, BLUETOOTH_SCO_STATUS_CHANGED_ID)) {
- BluetoothHfpManagerBase* hfp =
- static_cast<BluetoothHfpManagerBase*>(aSubject);
- isConnected = hfp->IsScoConnected();
- } else {
- BluetoothProfileManagerBase* profile =
- static_cast<BluetoothProfileManagerBase*>(aSubject);
- isConnected = profile->IsConnected();
- }
-
- if (!strcmp(aTopic, BLUETOOTH_SCO_STATUS_CHANGED_ID)) {
- if (isConnected) {
- String8 cmd;
- cmd.appendFormat("bt_samplerate=%d", kBtSampleRate);
- AudioSystem::setParameters(0, cmd);
- SetForceForUse(nsIAudioManager::USE_COMMUNICATION, nsIAudioManager::FORCE_BT_SCO);
- } else {
- int32_t force;
- GetForceForUse(nsIAudioManager::USE_COMMUNICATION, &force);
- if (force == nsIAudioManager::FORCE_BT_SCO) {
- SetForceForUse(nsIAudioManager::USE_COMMUNICATION, nsIAudioManager::FORCE_NONE);
- }
- }
- } else if (!strcmp(aTopic, BLUETOOTH_A2DP_STATUS_CHANGED_ID)) {
- if (!isConnected && mA2dpSwitchDone) {
- RefPtr<AudioManager> self = this;
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([self, isConnected, aAddress]() {
- if (self->mA2dpSwitchDone) {
- return;
- }
- self->UpdateDeviceConnectionState(isConnected,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
- aAddress);
-
- String8 cmd("bluetooth_enabled=false");
- AudioSystem::setParameters(0, cmd);
- cmd.setTo("A2dpSuspended=true");
- AudioSystem::setParameters(0, cmd);
- self->mA2dpSwitchDone = true;
- });
- MessageLoop::current()->PostDelayedTask(
- MakeAndAddRef<RunnableCallTask>(runnable), 1000);
-
- mA2dpSwitchDone = false;
- } else {
- UpdateDeviceConnectionState(isConnected,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
- aAddress);
- String8 cmd("bluetooth_enabled=true");
- AudioSystem::setParameters(0, cmd);
- cmd.setTo("A2dpSuspended=false");
- AudioSystem::setParameters(0, cmd);
- mA2dpSwitchDone = true;
-#if ANDROID_VERSION >= 17
- if (AudioSystem::getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA) == AUDIO_POLICY_FORCE_NO_BT_A2DP) {
- SetForceForUse(AUDIO_POLICY_FORCE_FOR_MEDIA, AUDIO_POLICY_FORCE_NONE);
- }
-#endif
- }
- mBluetoothA2dpEnabled = isConnected;
- } else if (!strcmp(aTopic, BLUETOOTH_HFP_STATUS_CHANGED_ID)) {
- UpdateDeviceConnectionState(isConnected,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET,
- aAddress);
- UpdateDeviceConnectionState(isConnected,
- AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
- aAddress);
- } else if (!strcmp(aTopic, BLUETOOTH_HFP_NREC_STATUS_CHANGED_ID)) {
- String8 cmd;
- BluetoothHfpManagerBase* hfp =
- static_cast<BluetoothHfpManagerBase*>(aSubject);
- if (hfp->IsNrecEnabled()) {
- cmd.setTo("bt_headset_name=<unknown>;bt_headset_nrec=on");
- AudioSystem::setParameters(0, cmd);
- } else {
- cmd.setTo("bt_headset_name=<unknown>;bt_headset_nrec=off");
- AudioSystem::setParameters(0, cmd);
- }
- }
-#endif
-}
-
-void
-AudioManager::HandleAudioChannelProcessChanged()
-{
- // Note: If the user answers a VoIP call (e.g. WebRTC calls) during the
- // telephony call (GSM/CDMA calls) the audio manager won't set the
- // PHONE_STATE_IN_COMMUNICATION audio state. Once the telephony call finishes
- // the RIL plumbing sets the PHONE_STATE_NORMAL audio state. This seems to be
- // an issue for the VoIP call but it is not. Once the RIL plumbing sets the
- // the PHONE_STATE_NORMAL audio state the AudioManager::mPhoneAudioAgent
- // member will call the NotifyStoppedPlaying() method causing that this function will
- // be called again and therefore the audio manager sets the
- // PHONE_STATE_IN_COMMUNICATION audio state.
-
- if ((mPhoneState == PHONE_STATE_IN_CALL) ||
- (mPhoneState == PHONE_STATE_RINGTONE)) {
- return;
- }
-
- RefPtr<AudioChannelService> service = AudioChannelService::GetOrCreate();
- bool telephonyChannelIsActive = service && service->TelephonyChannelIsActive();
- telephonyChannelIsActive ? SetPhoneState(PHONE_STATE_IN_COMMUNICATION) :
- SetPhoneState(PHONE_STATE_NORMAL);
-}
-
-nsresult
-AudioManager::Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData)
-{
- if ((strcmp(aTopic, BLUETOOTH_SCO_STATUS_CHANGED_ID) == 0) ||
- (strcmp(aTopic, BLUETOOTH_HFP_STATUS_CHANGED_ID) == 0) ||
- (strcmp(aTopic, BLUETOOTH_HFP_NREC_STATUS_CHANGED_ID) == 0) ||
- (strcmp(aTopic, BLUETOOTH_A2DP_STATUS_CHANGED_ID) == 0)) {
- nsCString address = NS_ConvertUTF16toUTF8(nsDependentString(aData));
- if (address.IsEmpty()) {
- NS_WARNING(nsPrintfCString("Invalid address of %s", aTopic).get());
- return NS_ERROR_FAILURE;
- }
-
- HandleBluetoothStatusChanged(aSubject, aTopic, address);
- return NS_OK;
- }
-
- else if (!strcmp(aTopic, AUDIO_CHANNEL_PROCESS_CHANGED)) {
- HandleAudioChannelProcessChanged();
- return NS_OK;
- }
-
- // To process the volume control on each volume categories according to
- // change of settings
- else if (!strcmp(aTopic, MOZ_SETTINGS_CHANGE_ID)) {
- RootedDictionary<dom::SettingChangeNotification> setting(RootingCx());
- if (!WrappedJSToDictionary(aSubject, setting)) {
- return NS_OK;
- }
- if (!StringBeginsWith(setting.mKey, NS_LITERAL_STRING("audio.volume."))) {
- return NS_OK;
- }
- if (!setting.mValue.isNumber()) {
- return NS_OK;
- }
-
- uint32_t volIndex = setting.mValue.toNumber();
- for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) {
- if (setting.mKey.EqualsASCII(gVolumeData[idx].mChannelName)) {
- SetStreamVolumeIndex(gVolumeData[idx].mStreamType, volIndex);
- return NS_OK;
- }
- }
- }
-
- NS_WARNING("Unexpected topic in AudioManager");
- return NS_ERROR_FAILURE;
-}
-
-static void
-NotifyHeadphonesStatus(hal::SwitchState aState)
-{
- nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
- if (obs) {
- if (aState == hal::SWITCH_STATE_HEADSET) {
- obs->NotifyObservers(nullptr, HEADPHONES_STATUS_CHANGED, HEADPHONES_STATUS_HEADSET);
- } else if (aState == hal::SWITCH_STATE_HEADPHONE) {
- obs->NotifyObservers(nullptr, HEADPHONES_STATUS_CHANGED, HEADPHONES_STATUS_HEADPHONE);
- } else if (aState == hal::SWITCH_STATE_OFF) {
- obs->NotifyObservers(nullptr, HEADPHONES_STATUS_CHANGED, HEADPHONES_STATUS_OFF);
- } else {
- obs->NotifyObservers(nullptr, HEADPHONES_STATUS_CHANGED, HEADPHONES_STATUS_UNKNOWN);
- }
- }
-}
-
-class HeadphoneSwitchObserver : public hal::SwitchObserver
-{
-public:
- void Notify(const hal::SwitchEvent& aEvent) {
- RefPtr<AudioManager> audioManager = AudioManager::GetInstance();
- MOZ_ASSERT(audioManager);
- audioManager->HandleHeadphoneSwitchEvent(aEvent);
- }
-};
-
-void
-AudioManager::HandleHeadphoneSwitchEvent(const hal::SwitchEvent& aEvent)
-{
- NotifyHeadphonesStatus(aEvent.status());
- // When user pulled out the headset, a delay of routing here can avoid the leakage of audio from speaker.
- if (aEvent.status() == hal::SWITCH_STATE_OFF && mSwitchDone) {
-
- RefPtr<AudioManager> self = this;
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([self]() {
- if (self->mSwitchDone) {
- return;
- }
- self->UpdateHeadsetConnectionState(hal::SWITCH_STATE_OFF);
- self->mSwitchDone = true;
- });
- MessageLoop::current()->PostDelayedTask(
- MakeAndAddRef<RunnableCallTask>(runnable), 1000);
- mSwitchDone = false;
- } else if (aEvent.status() != hal::SWITCH_STATE_OFF) {
- UpdateHeadsetConnectionState(aEvent.status());
- mSwitchDone = true;
- }
- // Handle the coexistence of a2dp / headset device, latest one wins.
-#if ANDROID_VERSION >= 17
- int32_t forceUse = 0;
- GetForceForUse(AUDIO_POLICY_FORCE_FOR_MEDIA, &forceUse);
- if (aEvent.status() != hal::SWITCH_STATE_OFF && mBluetoothA2dpEnabled) {
- SetForceForUse(AUDIO_POLICY_FORCE_FOR_MEDIA, AUDIO_POLICY_FORCE_NO_BT_A2DP);
- } else if (forceUse == AUDIO_POLICY_FORCE_NO_BT_A2DP) {
- SetForceForUse(AUDIO_POLICY_FORCE_FOR_MEDIA, AUDIO_POLICY_FORCE_NONE);
- }
-#endif
-}
-
-AudioManager::AudioManager()
- : mPhoneState(PHONE_STATE_CURRENT)
- , mIsVolumeInited(false)
- , mAudioOutDevicesUpdated(0)
- , mSwitchDone(true)
-#if defined(MOZ_B2G_BT) || ANDROID_VERSION >= 17
- , mBluetoothA2dpEnabled(false)
-#endif
-#ifdef MOZ_B2G_BT
- , mA2dpSwitchDone(true)
-#endif
- , mObserver(new HeadphoneSwitchObserver())
-{
- for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(kAudioDeviceInfos); ++idx) {
- mAudioDeviceTableIdMaps.Put(kAudioDeviceInfos[idx].value, idx);
- }
-
- AudioSystem::setErrorCallback(BinderDeadCallback);
-#if ANDROID_VERSION >= 21
- android::sp<GonkAudioPortCallback> callback = new GonkAudioPortCallback();
- AudioSystem::setAudioPortCallback(callback);
-#endif
-
- // Create VolumeStreamStates
- for (uint32_t loop = 0; loop < AUDIO_STREAM_CNT; ++loop) {
- VolumeStreamState* streamState =
- new VolumeStreamState(*this, static_cast<audio_stream_type_t>(loop));
- mStreamStates.AppendElement(streamState);
- }
- // Initialize stream volumes with default values
- for (int32_t streamType = 0; streamType < AUDIO_STREAM_MAX; streamType++) {
- uint32_t volIndex = sDefaultStreamVolumeTbl[streamType];
- SetStreamVolumeForDevice(streamType, volIndex, AUDIO_DEVICE_OUT_DEFAULT);
- }
- UpdateCachedActiveDevicesForStreams();
-
- RegisterSwitchObserver(hal::SWITCH_HEADPHONES, mObserver);
- // Initialize headhone/heaset status
- UpdateHeadsetConnectionState(hal::GetCurrentSwitchState(hal::SWITCH_HEADPHONES));
- NotifyHeadphonesStatus(hal::GetCurrentSwitchState(hal::SWITCH_HEADPHONES));
-
- // Get the initial volume index from settings DB during boot up.
- InitVolumeFromDatabase();
-
- // Gecko only control stream volume not master so set to default value
- // directly.
- AudioSystem::setMasterVolume(1.0);
-
- nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
- NS_ENSURE_TRUE_VOID(obs);
- if (NS_FAILED(obs->AddObserver(this, BLUETOOTH_SCO_STATUS_CHANGED_ID, false))) {
- NS_WARNING("Failed to add bluetooth sco status changed observer!");
- }
- if (NS_FAILED(obs->AddObserver(this, BLUETOOTH_A2DP_STATUS_CHANGED_ID, false))) {
- NS_WARNING("Failed to add bluetooth a2dp status changed observer!");
- }
- if (NS_FAILED(obs->AddObserver(this, BLUETOOTH_HFP_STATUS_CHANGED_ID, false))) {
- NS_WARNING("Failed to add bluetooth hfp status changed observer!");
- }
- if (NS_FAILED(obs->AddObserver(this, BLUETOOTH_HFP_NREC_STATUS_CHANGED_ID, false))) {
- NS_WARNING("Failed to add bluetooth hfp NREC status changed observer!");
- }
- if (NS_FAILED(obs->AddObserver(this, MOZ_SETTINGS_CHANGE_ID, false))) {
- NS_WARNING("Failed to add mozsettings-changed observer!");
- }
- if (NS_FAILED(obs->AddObserver(this, AUDIO_CHANNEL_PROCESS_CHANGED, false))) {
- NS_WARNING("Failed to add audio-channel-process-changed observer!");
- }
-
-}
-
-AudioManager::~AudioManager() {
- AudioSystem::setErrorCallback(nullptr);
-#if ANDROID_VERSION >= 21
- AudioSystem::setAudioPortCallback(nullptr);
-#endif
- hal::UnregisterSwitchObserver(hal::SWITCH_HEADPHONES, mObserver);
-
- nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
- NS_ENSURE_TRUE_VOID(obs);
- if (NS_FAILED(obs->RemoveObserver(this, BLUETOOTH_SCO_STATUS_CHANGED_ID))) {
- NS_WARNING("Failed to remove bluetooth sco status changed observer!");
- }
- if (NS_FAILED(obs->RemoveObserver(this, BLUETOOTH_A2DP_STATUS_CHANGED_ID))) {
- NS_WARNING("Failed to remove bluetooth a2dp status changed observer!");
- }
- if (NS_FAILED(obs->RemoveObserver(this, BLUETOOTH_HFP_STATUS_CHANGED_ID))) {
- NS_WARNING("Failed to remove bluetooth hfp status changed observer!");
- }
- if (NS_FAILED(obs->RemoveObserver(this, BLUETOOTH_HFP_NREC_STATUS_CHANGED_ID))) {
- NS_WARNING("Failed to remove bluetooth hfp NREC status changed observer!");
- }
- if (NS_FAILED(obs->RemoveObserver(this, MOZ_SETTINGS_CHANGE_ID))) {
- NS_WARNING("Failed to remove mozsettings-changed observer!");
- }
- if (NS_FAILED(obs->RemoveObserver(this, AUDIO_CHANNEL_PROCESS_CHANGED))) {
- NS_WARNING("Failed to remove audio-channel-process-changed!");
- }
-}
-
-static StaticRefPtr<AudioManager> sAudioManager;
-
-already_AddRefed<AudioManager>
-AudioManager::GetInstance()
-{
- // Avoid createing AudioManager from content process.
- if (!XRE_IsParentProcess()) {
- MOZ_CRASH("Non-chrome processes should not get here.");
- }
-
- // Avoid createing multiple AudioManager instance inside main process.
- if (!sAudioManager) {
- sAudioManager = new AudioManager();
- ClearOnShutdown(&sAudioManager);
- }
-
- RefPtr<AudioManager> audioMgr = sAudioManager.get();
- return audioMgr.forget();
-}
-
-NS_IMETHODIMP
-AudioManager::GetMicrophoneMuted(bool* aMicrophoneMuted)
-{
-
- if (AudioSystem::isMicrophoneMuted(aMicrophoneMuted)) {
- return NS_ERROR_FAILURE;
- }
- return NS_OK;
-}
-
-NS_IMETHODIMP
-AudioManager::SetMicrophoneMuted(bool aMicrophoneMuted)
-{
- if (!AudioSystem::muteMicrophone(aMicrophoneMuted)) {
- return NS_OK;
- }
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-AudioManager::GetPhoneState(int32_t* aState)
-{
- *aState = mPhoneState;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-AudioManager::SetPhoneState(int32_t aState)
-{
- if (mPhoneState == aState) {
- return NS_OK;
- }
-
- nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
- if (obs) {
- nsString state;
- state.AppendInt(aState);
- obs->NotifyObservers(nullptr, "phone-state-changed", state.get());
- }
-
-#if ANDROID_VERSION < 17
- if (AudioSystem::setPhoneState(aState)) {
-#else
- if (AudioSystem::setPhoneState(static_cast<audio_mode_t>(aState))) {
-#endif
- return NS_ERROR_FAILURE;
- }
-
-#if ANDROID_VERSION < 21
- // Manually call it, since AudioPortCallback is not supported.
- // Current volumes might be changed by updating active devices in android
- // AudioPolicyManager.
- MaybeUpdateVolumeSettingToDatabase();
-#endif
- mPhoneState = aState;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-AudioManager::SetForceForUse(int32_t aUsage, int32_t aForce)
-{
-#if ANDROID_VERSION >= 15
- status_t status = AudioSystem::setForceUse(
- (audio_policy_force_use_t)aUsage,
- (audio_policy_forced_cfg_t)aForce);
-#if ANDROID_VERSION < 21
- // Manually call it, since AudioPortCallback is not supported.
- // Current volumes might be changed by updating active devices in android
- // AudioPolicyManager.
- MaybeUpdateVolumeSettingToDatabase();
-#endif
- return status ? NS_ERROR_FAILURE : NS_OK;
-#else
- NS_NOTREACHED("Doesn't support force routing on GB version");
- return NS_ERROR_UNEXPECTED;
-#endif
-}
-
-NS_IMETHODIMP
-AudioManager::GetForceForUse(int32_t aUsage, int32_t* aForce) {
-#if ANDROID_VERSION >= 15
- *aForce = AudioSystem::getForceUse((audio_policy_force_use_t)aUsage);
- return NS_OK;
-#else
- NS_NOTREACHED("Doesn't support force routing on GB version");
- return NS_ERROR_UNEXPECTED;
-#endif
-}
-
-NS_IMETHODIMP
-AudioManager::SetAudioChannelVolume(uint32_t aChannel, uint32_t aIndex)
-{
- if (aChannel >= NUMBER_OF_AUDIO_CHANNELS) {
- return NS_ERROR_INVALID_ARG;
- }
-
- return SetStreamVolumeIndex(sChannelStreamTbl[aChannel], aIndex);
-}
-
-NS_IMETHODIMP
-AudioManager::GetAudioChannelVolume(uint32_t aChannel, uint32_t* aIndex)
-{
- if (aChannel >= NUMBER_OF_AUDIO_CHANNELS) {
- return NS_ERROR_INVALID_ARG;
- }
-
- if (!aIndex) {
- return NS_ERROR_NULL_POINTER;
- }
-
- return GetStreamVolumeIndex(sChannelStreamTbl[aChannel], aIndex);
-}
-
-NS_IMETHODIMP
-AudioManager::GetMaxAudioChannelVolume(uint32_t aChannel, uint32_t* aMaxIndex)
-{
- if (aChannel >= NUMBER_OF_AUDIO_CHANNELS) {
- return NS_ERROR_INVALID_ARG;
- }
-
- if (!aMaxIndex) {
- return NS_ERROR_NULL_POINTER;
- }
-
- *aMaxIndex = mStreamStates[sChannelStreamTbl[aChannel]]->GetMaxIndex();
- return NS_OK;
-}
-
-nsresult
-AudioManager::ValidateVolumeIndex(int32_t aStream, uint32_t aIndex) const
-{
- if (aStream <= AUDIO_STREAM_DEFAULT || aStream >= AUDIO_STREAM_MAX) {
- return NS_ERROR_INVALID_ARG;
- }
-
- uint32_t maxIndex = mStreamStates[aStream]->GetMaxIndex();
- if (aIndex > maxIndex) {
- return NS_ERROR_FAILURE;
- }
- return NS_OK;
-}
-
-nsresult
-AudioManager::SetStreamVolumeForDevice(int32_t aStream,
- uint32_t aIndex,
- uint32_t aDevice)
-{
- if (aStream <= AUDIO_STREAM_DEFAULT || aStream >= AUDIO_STREAM_MAX) {
- return NS_ERROR_INVALID_ARG;
- }
-
- int32_t streamAlias = sStreamVolumeAliasTbl[aStream];
- VolumeStreamState* streamState = mStreamStates[streamAlias].get();
- return streamState->SetVolumeIndexToAliasStreams(aIndex, aDevice);
-}
-
-nsresult
-AudioManager::SetStreamVolumeIndex(int32_t aStream, uint32_t aIndex)
-{
- if (aStream <= AUDIO_STREAM_DEFAULT || aStream >= AUDIO_STREAM_MAX) {
- return NS_ERROR_INVALID_ARG;
- }
-
- int32_t streamAlias = sStreamVolumeAliasTbl[aStream];
-
- nsresult rv;
- for (int32_t streamType = 0; streamType < AUDIO_STREAM_MAX; streamType++) {
- if (streamAlias == sStreamVolumeAliasTbl[streamType]) {
- rv = mStreamStates[streamType]->SetVolumeIndexToActiveDevices(aIndex);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
- }
- }
-
- // AUDIO_STREAM_FM is not used on recent gonk.
- // AUDIO_STREAM_MUSIC is used for FM radio volume control.
-#if ANDROID_VERSION < 19
- if (streamAlias == AUDIO_STREAM_MUSIC && IsFmOutConnected()) {
- rv = mStreamStates[AUDIO_STREAM_FM]->
- SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_FM);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
- }
-#endif
-
- MaybeUpdateVolumeSettingToDatabase();
- return NS_OK;
-}
-
-nsresult
-AudioManager::GetStreamVolumeIndex(int32_t aStream, uint32_t *aIndex)
-{
- if (!aIndex) {
- return NS_ERROR_INVALID_ARG;
- }
-
- if (aStream <= AUDIO_STREAM_DEFAULT || aStream >= AUDIO_STREAM_MAX) {
- return NS_ERROR_INVALID_ARG;
- }
-
- *aIndex = mStreamStates[aStream]->GetVolumeIndex();
- return NS_OK;
-}
-
-nsAutoCString
-AudioManager::AppendDeviceToVolumeSetting(const char* aName, uint32_t aDevice)
-{
- nsAutoCString topic;
- topic.Assign(aName);
- topic.Append(".");
- uint32_t index = 0;
- DebugOnly<bool> exist = mAudioDeviceTableIdMaps.Get(aDevice, &index);
- MOZ_ASSERT(exist);
- topic.Append(kAudioDeviceInfos[index].tag);
- return topic;
-}
-
-void
-AudioManager::InitVolumeFromDatabase()
-{
- nsresult rv;
- nsCOMPtr<nsISettingsService> service = do_GetService(SETTINGS_SERVICE, &rv);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- nsCOMPtr<nsISettingsServiceLock> lock;
- rv = service->CreateLock(nullptr, getter_AddRefs(lock));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- RefPtr<VolumeInitCallback> callback = new VolumeInitCallback();
- MOZ_ASSERT(callback);
- callback->GetPromise()->Then(AbstractThread::MainThread(), __func__, this,
- &AudioManager::InitDeviceVolumeSucceeded,
- &AudioManager::InitDeviceVolumeFailed);
-
- for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) {
- for (uint32_t idx2 = 0; idx2 < MOZ_ARRAY_LENGTH(kAudioDeviceInfos); ++idx2) {
- lock->Get(AppendDeviceToVolumeSetting(gVolumeData[idx].mChannelName,
- kAudioDeviceInfos[idx2].value).get(),
- callback);
- }
- }
-}
-
-void
-AudioManager::InitDeviceVolumeSucceeded()
-{
- mIsVolumeInited = true;
- MaybeUpdateVolumeSettingToDatabase(true);
-}
-
-void
-AudioManager::InitDeviceVolumeFailed(const char* aError)
-{
- // Default volume of AUDIO_DEVICE_OUT_DEFAULT is already set.
- mIsVolumeInited = true;
- MaybeUpdateVolumeSettingToDatabase(true);
- NS_WARNING(aError);
-}
-
-void
-AudioManager::MaybeUpdateVolumeSettingToDatabase(bool aForce)
-{
- if (!mIsVolumeInited) {
- return;
- }
-
- nsCOMPtr<nsISettingsServiceLock> lock = GetSettingServiceLock();
- if (NS_WARN_IF(!lock)) {
- return;
- }
-
- // Send events to update the Gaia volumes
- JS::Rooted<JS::Value> value(RootingCx());
- uint32_t volume = 0;
- for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) {
- int32_t streamType = gVolumeData[idx].mStreamType;
- VolumeStreamState* streamState = mStreamStates[streamType].get();
- if(!aForce && !streamState->IsDevicesChanged()) {
- continue;
- }
- // Get volume index of active device.
- volume = streamState->GetVolumeIndex();
- value.setInt32(volume);
- lock->Set(gVolumeData[idx].mChannelName, value, nullptr, nullptr);
- }
-
- // For reducing the code dependency, Gaia doesn't need to know the
- // device volume, it only need to care about different volume categories.
- // However, we need to send the setting volume to the permanent database,
- // so that we can store the volume setting even if the phone reboots.
-
- for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) {
- int32_t streamType = gVolumeData[idx].mStreamType;
- VolumeStreamState* streamState = mStreamStates[streamType].get();
-
- if(!streamState->IsVolumeIndexesChanged()) {
- continue;
- }
-
- uint32_t remainingDevices = mAudioOutDevicesUpdated;
- for (uint32_t i = 0; remainingDevices != 0; i++) {
- uint32_t device = (1 << i);
- if ((device & remainingDevices) == 0) {
- continue;
- }
- remainingDevices &= ~device;
- if (!mAudioDeviceTableIdMaps.Get(device, nullptr)) {
- continue;
- }
- volume = streamState->GetVolumeIndex(device);
- value.setInt32(volume);
- lock->Set(AppendDeviceToVolumeSetting(gVolumeData[idx].mChannelName,
- device).get(),
- value, nullptr, nullptr);
- }
- }
-
- // Clear changed flags
- for (uint32_t idx = 0; idx < MOZ_ARRAY_LENGTH(gVolumeData); ++idx) {
- int32_t streamType = gVolumeData[idx].mStreamType;
- mStreamStates[streamType]->ClearDevicesChanged();
- mStreamStates[streamType]->ClearVolumeIndexesChanged();
- }
- // Clear mAudioOutDevicesUpdated
- mAudioOutDevicesUpdated = 0;
-}
-
-void
-AudioManager::UpdateCachedActiveDevicesForStreams()
-{
- // This function updates cached active devices for streams.
- // It is used for optimization of GetDevicesForStream() since L.
- // AudioManager could know when active devices
- // are changed in AudioPolicyManager by onAudioPortListUpdate().
- // Except it, AudioManager normally do not need to ask AuidoPolicyManager
- // about current active devices of streams and could use cached values.
- // Before L, onAudioPortListUpdate() does not exist and GetDevicesForStream()
- // does not use the cache. Therefore this function do nothing.
-#if ANDROID_VERSION >= 21
- for (int32_t streamType = 0; streamType < AUDIO_STREAM_MAX; streamType++) {
- // Update cached active devices of stream
- mStreamStates[streamType]->IsDevicesChanged(false /* aFromCache */);
- }
-#endif
-}
-
-uint32_t
-AudioManager::GetDevicesForStream(int32_t aStream, bool aFromCache)
-{
-#if ANDROID_VERSION >= 21
- // Since Lollipop, devices update could be notified by AudioPortCallback.
- // Cached values can be used if there is no update.
- if (aFromCache) {
- return mStreamStates[aStream]->GetLastDevices();
- }
-#endif
-
-#if ANDROID_VERSION >= 17
- audio_devices_t devices =
- AudioSystem::getDevicesForStream(static_cast<audio_stream_type_t>(aStream));
-
- return static_cast<uint32_t>(devices);
-#else
- // Per audio out device volume is not supported.
- // Use AUDIO_DEVICE_OUT_SPEAKER just to store audio volume to DB.
- return AUDIO_DEVICE_OUT_SPEAKER;
-#endif
-}
-
-uint32_t
-AudioManager::GetDeviceForStream(int32_t aStream)
-{
- uint32_t devices =
- GetDevicesForStream(static_cast<audio_stream_type_t>(aStream));
- uint32_t device = SelectDeviceFromDevices(devices);
- return device;
-}
-
-/* static */ uint32_t
-AudioManager::SelectDeviceFromDevices(uint32_t aOutDevices)
-{
- uint32_t device = aOutDevices;
-
- // See android AudioService.getDeviceForStream().
- // AudioPolicyManager expects it.
- // See also android AudioPolicyManager::getDeviceForVolume().
- if ((device & (device - 1)) != 0) {
- // Multiple device selection.
- if ((device & AUDIO_DEVICE_OUT_SPEAKER) != 0) {
- device = AUDIO_DEVICE_OUT_SPEAKER;
-#if ANDROID_VERSION >= 21
- } else if ((device & AUDIO_DEVICE_OUT_HDMI_ARC) != 0) {
- device = AUDIO_DEVICE_OUT_HDMI_ARC;
- } else if ((device & AUDIO_DEVICE_OUT_SPDIF) != 0) {
- device = AUDIO_DEVICE_OUT_SPDIF;
- } else if ((device & AUDIO_DEVICE_OUT_AUX_LINE) != 0) {
- device = AUDIO_DEVICE_OUT_AUX_LINE;
-#endif
- } else {
- device &= AUDIO_DEVICE_OUT_ALL_A2DP;
- }
- }
- MOZ_ASSERT(audio_is_output_device(device));
- return device;
-}
-AudioManager::VolumeStreamState::VolumeStreamState(AudioManager& aManager,
- int32_t aStreamType)
- : mManager(aManager)
- , mStreamType(aStreamType)
- , mLastDevices(0)
- , mIsDevicesChanged(true)
- , mIsVolumeIndexesChanged(true)
-{
- InitStreamVolume();
-}
-
-bool
-AudioManager::VolumeStreamState::IsDevicesChanged(bool aFromCache)
-{
- uint32_t devices = mManager.GetDevicesForStream(mStreamType, aFromCache);
- if (devices != mLastDevices) {
- mLastDevices = devices;
- mIsDevicesChanged = true;
- }
- return mIsDevicesChanged;
-}
-
-void
-AudioManager::VolumeStreamState::ClearDevicesChanged()
-{
- mIsDevicesChanged = false;
-}
-
-bool
-AudioManager::VolumeStreamState::IsVolumeIndexesChanged()
-{
- return mIsVolumeIndexesChanged;
-}
-
-void
-AudioManager::VolumeStreamState::ClearVolumeIndexesChanged()
-{
- mIsVolumeIndexesChanged = false;
-}
-
-void
-AudioManager::VolumeStreamState::InitStreamVolume()
-{
- AudioSystem::initStreamVolume(static_cast<audio_stream_type_t>(mStreamType),
- 0,
- GetMaxIndex());
-}
-
-uint32_t
-AudioManager::VolumeStreamState::GetMaxIndex()
-{
- return sMaxStreamVolumeTbl[mStreamType];
-}
-
-uint32_t
-AudioManager::VolumeStreamState::GetDefaultIndex()
-{
- return sDefaultStreamVolumeTbl[mStreamType];
-}
-
-uint32_t
-AudioManager::VolumeStreamState::GetVolumeIndex()
-{
- uint32_t device = mManager.GetDeviceForStream(mStreamType);
- return GetVolumeIndex(device);
-}
-
-uint32_t
-AudioManager::VolumeStreamState::GetVolumeIndex(uint32_t aDevice)
-{
- uint32_t index = 0;
- bool ret = mVolumeIndexes.Get(aDevice, &index);
- if (!ret) {
- index = mVolumeIndexes.Get(AUDIO_DEVICE_OUT_DEFAULT);
- }
- return index;
-}
-
-nsresult
-AudioManager::VolumeStreamState::SetVolumeIndexToActiveDevices(uint32_t aIndex)
-{
- uint32_t device = mManager.GetDeviceForStream(mStreamType);
-
- // Update volume index for device
- uint32_t oldVolumeIndex = 0;
- bool exist = mVolumeIndexes.Get(device, &oldVolumeIndex);
- if (exist && aIndex == oldVolumeIndex) {
- // No update
- return NS_OK;
- }
-
- // AudioPolicyManager::setStreamVolumeIndex() set volumes of all active
- // devices for stream.
- nsresult rv;
- rv = SetVolumeIndexToConsistentDeviceIfNeeded(aIndex, device);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
-
- return NS_OK;
-}
-
-nsresult
-AudioManager::VolumeStreamState::SetVolumeIndexToAliasStreams(uint32_t aIndex,
- uint32_t aDevice)
-{
- uint32_t oldVolumeIndex = 0;
- bool exist = mVolumeIndexes.Get(aDevice, &oldVolumeIndex);
- if (exist && aIndex == oldVolumeIndex) {
- // No update
- return NS_OK;
- }
-
- nsresult rv = SetVolumeIndexToConsistentDeviceIfNeeded(aIndex, aDevice);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
-
- for (int32_t streamType = 0; streamType < AUDIO_STREAM_MAX; streamType++) {
- if ((streamType != mStreamType) &&
- sStreamVolumeAliasTbl[streamType] == mStreamType) {
- // Rescaling of index is not necessary.
- rv = mManager.mStreamStates[streamType]->
- SetVolumeIndexToAliasStreams(aIndex, aDevice);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
- }
- }
-
- return NS_OK;
-}
-
-nsresult
-AudioManager::VolumeStreamState::SetVolumeIndexToConsistentDeviceIfNeeded(uint32_t aIndex, uint32_t aDevice)
-{
- nsresult rv;
- if (aDevice == AUDIO_DEVICE_OUT_SPEAKER || aDevice == AUDIO_DEVICE_OUT_EARPIECE) {
- // Set AUDIO_DEVICE_OUT_SPEAKER and AUDIO_DEVICE_OUT_EARPIECE to same volume.
- rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_SPEAKER);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
- rv = SetVolumeIndex(aIndex, AUDIO_DEVICE_OUT_EARPIECE);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
- } else {
- // No alias device
- rv = SetVolumeIndex(aIndex, aDevice);
- }
- return rv;
-}
-
-nsresult
-AudioManager::VolumeStreamState::SetVolumeIndex(uint32_t aIndex,
- uint32_t aDevice,
- bool aUpdateCache)
-{
- status_t rv;
-#if ANDROID_VERSION >= 17
- if (aUpdateCache) {
- mVolumeIndexes.Put(aDevice, aIndex);
- mIsVolumeIndexesChanged = true;
- mManager.AudioOutDeviceUpdated(aDevice);
- }
-
- rv = AudioSystem::setStreamVolumeIndex(
- static_cast<audio_stream_type_t>(mStreamType),
- aIndex,
- aDevice);
- return rv ? NS_ERROR_FAILURE : NS_OK;
-#else
- if (aUpdateCache) {
- // Per audio out device volume is not supported.
- // Use AUDIO_DEVICE_OUT_SPEAKER just to store audio volume to DB.
- mVolumeIndexes.Put(AUDIO_DEVICE_OUT_SPEAKER, aIndex);
- mIsVolumeIndexesChanged = true;
- mManager.AudioOutDeviceUpdated(AUDIO_DEVICE_OUT_SPEAKER);
- }
- rv = AudioSystem::setStreamVolumeIndex(
- static_cast<audio_stream_type_t>(mStreamType),
- aIndex);
- return rv ? NS_ERROR_FAILURE : NS_OK;
-#endif
-}
-
-void
-AudioManager::VolumeStreamState::RestoreVolumeIndexToAllDevices()
-{
- for (auto iter = mVolumeIndexes.Iter(); !iter.Done(); iter.Next()) {
- const uint32_t& key = iter.Key();
- uint32_t& index = iter.Data();
- SetVolumeIndex(key, index, /* aUpdateCache */ false);
- }
-}
-
-} /* namespace gonk */
-} /* namespace dom */
-} /* namespace mozilla */
diff --git a/dom/system/gonk/AudioManager.h b/dom/system/gonk/AudioManager.h
deleted file mode 100644
index f56eaad6c..000000000
--- a/dom/system/gonk/AudioManager.h
+++ /dev/null
@@ -1,180 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef mozilla_dom_system_b2g_audiomanager_h__
-#define mozilla_dom_system_b2g_audiomanager_h__
-
-#include "mozilla/HalTypes.h"
-#include "mozilla/Observer.h"
-#include "mozilla/UniquePtr.h"
-#include "nsAutoPtr.h"
-#include "nsDataHashtable.h"
-#include "nsIAudioManager.h"
-#include "nsIObserver.h"
-#include "android_audio/AudioSystem.h"
-
-// {b2b51423-502d-4d77-89b3-7786b562b084}
-#define NS_AUDIOMANAGER_CID {0x94f6fd70, 0x7615, 0x4af9, \
- {0x89, 0x10, 0xf9, 0x3c, 0x55, 0xe6, 0x62, 0xec}}
-#define NS_AUDIOMANAGER_CONTRACTID "@mozilla.org/telephony/audiomanager;1"
-
-class nsISettingsServiceLock;
-
-namespace mozilla {
-namespace hal {
-class SwitchEvent;
-typedef Observer<SwitchEvent> SwitchObserver;
-} // namespace hal
-
-namespace dom {
-namespace gonk {
-
-class VolumeInitCallback;
-
-class AudioManager final : public nsIAudioManager
- , public nsIObserver
-{
-public:
- static already_AddRefed<AudioManager> GetInstance();
-
- NS_DECL_ISUPPORTS
- NS_DECL_NSIAUDIOMANAGER
- NS_DECL_NSIOBSERVER
-
- // Validate whether the volume index is within the range
- nsresult ValidateVolumeIndex(int32_t aStream, uint32_t aIndex) const;
-
- // Called when android AudioFlinger in mediaserver is died
- void HandleAudioFlingerDied();
-
- void HandleHeadphoneSwitchEvent(const hal::SwitchEvent& aEvent);
-
- class VolumeStreamState {
- public:
- explicit VolumeStreamState(AudioManager& aManager, int32_t aStreamType);
- int32_t GetStreamType()
- {
- return mStreamType;
- }
- bool IsDevicesChanged(bool aFromCache = true);
- void ClearDevicesChanged();
- uint32_t GetLastDevices()
- {
- return mLastDevices;
- }
- bool IsVolumeIndexesChanged();
- void ClearVolumeIndexesChanged();
- void InitStreamVolume();
- uint32_t GetMaxIndex();
- uint32_t GetDefaultIndex();
- uint32_t GetVolumeIndex();
- uint32_t GetVolumeIndex(uint32_t aDevice);
- void ClearCurrentVolumeUpdated();
- // Set volume index to all active devices.
- // Active devices are chosen by android AudioPolicyManager.
- nsresult SetVolumeIndexToActiveDevices(uint32_t aIndex);
- // Set volume index to all alias streams for device. Alias streams have same volume.
- nsresult SetVolumeIndexToAliasStreams(uint32_t aIndex, uint32_t aDevice);
- nsresult SetVolumeIndexToConsistentDeviceIfNeeded(uint32_t aIndex, uint32_t aDevice);
- nsresult SetVolumeIndex(uint32_t aIndex, uint32_t aDevice, bool aUpdateCache = true);
- // Restore volume index to all devices. Called when AudioFlinger is restarted.
- void RestoreVolumeIndexToAllDevices();
- private:
- AudioManager& mManager;
- const int32_t mStreamType;
- uint32_t mLastDevices;
- bool mIsDevicesChanged;
- bool mIsVolumeIndexesChanged;
- nsDataHashtable<nsUint32HashKey, uint32_t> mVolumeIndexes;
- };
-
-protected:
- int32_t mPhoneState;
-
- bool mIsVolumeInited;
-
- // A bitwise variable for volume update of audio output devices,
- // clear it after store the value into database.
- uint32_t mAudioOutDevicesUpdated;
-
- // Connected devices that are controlled by setDeviceConnectionState()
- nsDataHashtable<nsUint32HashKey, nsCString> mConnectedDevices;
-
- nsDataHashtable<nsUint32HashKey, uint32_t> mAudioDeviceTableIdMaps;
-
- bool mSwitchDone;
-
-#if defined(MOZ_B2G_BT) || ANDROID_VERSION >= 17
- bool mBluetoothA2dpEnabled;
-#endif
-#ifdef MOZ_B2G_BT
- bool mA2dpSwitchDone;
-#endif
- nsTArray<UniquePtr<VolumeStreamState> > mStreamStates;
- uint32_t mLastChannelVolume[AUDIO_STREAM_CNT];
-
- bool IsFmOutConnected();
-
- nsresult SetStreamVolumeForDevice(int32_t aStream,
- uint32_t aIndex,
- uint32_t aDevice);
- nsresult SetStreamVolumeIndex(int32_t aStream, uint32_t aIndex);
- nsresult GetStreamVolumeIndex(int32_t aStream, uint32_t* aIndex);
-
- void UpdateCachedActiveDevicesForStreams();
- uint32_t GetDevicesForStream(int32_t aStream, bool aFromCache = true);
- uint32_t GetDeviceForStream(int32_t aStream);
- // Choose one device as representative of active devices.
- static uint32_t SelectDeviceFromDevices(uint32_t aOutDevices);
-
-private:
- nsAutoPtr<mozilla::hal::SwitchObserver> mObserver;
-
- void HandleBluetoothStatusChanged(nsISupports* aSubject,
- const char* aTopic,
- const nsCString aAddress);
- void HandleAudioChannelProcessChanged();
-
- // Append the audio output device to the volume setting string.
- nsAutoCString AppendDeviceToVolumeSetting(const char* aName,
- uint32_t aDevice);
-
- // We store the volume setting in the database, these are related functions.
- void InitVolumeFromDatabase();
- void MaybeUpdateVolumeSettingToDatabase(bool aForce = false);
-
- // Promise functions.
- void InitDeviceVolumeSucceeded();
- void InitDeviceVolumeFailed(const char* aError);
-
- void AudioOutDeviceUpdated(uint32_t aDevice);
-
- void UpdateHeadsetConnectionState(hal::SwitchState aState);
- void UpdateDeviceConnectionState(bool aIsConnected, uint32_t aDevice, const nsCString& aDeviceName);
- void SetAllDeviceConnectionStates();
-
- AudioManager();
- ~AudioManager();
-
- friend class VolumeInitCallback;
- friend class VolumeStreamState;
- friend class GonkAudioPortCallback;
-};
-
-} /* namespace gonk */
-} /* namespace dom */
-} /* namespace mozilla */
-
-#endif // mozilla_dom_system_b2g_audiomanager_h__
diff --git a/dom/system/gonk/AutoMounter.cpp b/dom/system/gonk/AutoMounter.cpp
deleted file mode 100644
index 52c4554fb..000000000
--- a/dom/system/gonk/AutoMounter.cpp
+++ /dev/null
@@ -1,1496 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 <fcntl.h>
-#include <pthread.h>
-#include <signal.h>
-#include <string.h>
-#include <strings.h>
-#include <unistd.h>
-#include <sys/statfs.h>
-
-#include <arpa/inet.h>
-#include <linux/types.h>
-#include <linux/netlink.h>
-#include <netinet/in.h>
-#include <sys/socket.h>
-#include <android/log.h>
-#include <cutils/properties.h>
-
-#include "AutoMounter.h"
-#include "nsVolumeService.h"
-#include "AutoMounterSetting.h"
-#include "base/message_loop.h"
-#include "base/task.h"
-#include "mozilla/AutoRestore.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/Hal.h"
-#include "mozilla/StaticPtr.h"
-#include "MozMtpServer.h"
-#include "MozMtpStorage.h"
-#include "nsCharSeparatedTokenizer.h"
-#include "nsMemory.h"
-#include "nsString.h"
-#include "nsThreadUtils.h"
-#include "nsXULAppAPI.h"
-#include "OpenFileFinder.h"
-#include "Volume.h"
-#include "VolumeManager.h"
-#include "nsIStatusReporter.h"
-
-USING_MTP_NAMESPACE
-
-/**************************************************************************
-*
-* The following "switch" files are available for monitoring usb
-* connections:
-*
-* /sys/devices/virtual/switch/usb_connected/state
-* /sys/devices/virtual/switch/usb_configuration/state
-*
-* Under gingerbread, only the usb_configuration seems to be available.
-* Starting with honeycomb, usb_connected was also added.
-*
-* When a cable insertion/removal occurs, then a uevent similar to the
-* following will be generted:
-*
-* change@/devices/virtual/switch/usb_configuration
-* ACTION=change
-* DEVPATH=/devices/virtual/switch/usb_configuration
-* SUBSYSTEM=switch
-* SWITCH_NAME=usb_configuration
-* SWITCH_STATE=0
-* SEQNUM=5038
-*
-* SWITCH_STATE will be 0 after a removal and 1 after an insertion
-*
-**************************************************************************/
-
-#define USB_CONFIGURATION_SWITCH_NAME NS_LITERAL_STRING("usb_configuration")
-
-#define GB_SYS_UMS_ENABLE "/sys/devices/virtual/usb_composite/usb_mass_storage/enable"
-#define GB_SYS_USB_CONFIGURED "/sys/devices/virtual/switch/usb_configuration/state"
-
-#define ICS_SYS_USB_FUNCTIONS "/sys/devices/virtual/android_usb/android0/functions"
-#define ICS_SYS_UMS_DIRECTORY "/sys/devices/virtual/android_usb/android0/f_mass_storage"
-#define ICS_SYS_MTP_DIRECTORY "/sys/devices/virtual/android_usb/android0/f_mtp"
-#define ICS_SYS_USB_STATE "/sys/devices/virtual/android_usb/android0/state"
-
-#undef USE_DEBUG // MozMtpDatabase.h also defines USE_DEBUG
-#define USE_DEBUG 0
-
-#undef LOG
-#undef LOGW
-#undef ERR
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "AutoMounter", ## args)
-#define LOGW(args...) __android_log_print(ANDROID_LOG_WARN, "AutoMounter", ## args)
-#define ERR(args...) __android_log_print(ANDROID_LOG_ERROR, "AutoMounter", ## args)
-
-#undef DBG
-#if USE_DEBUG
-#define DBG(args...) __android_log_print(ANDROID_LOG_DEBUG, "AutoMounter" , ## args)
-#else
-#define DBG(args...)
-#endif
-
-namespace mozilla {
-namespace system {
-
-#define SYS_USB_CONFIG "sys.usb.config"
-#define PERSIST_SYS_USB_CONFIG "persist.sys.usb.config"
-
-#define USB_FUNC_ADB "adb"
-#define USB_FUNC_MTP "mtp"
-#define USB_FUNC_NONE "none"
-#define USB_FUNC_RNDIS "rndis"
-#define USB_FUNC_UMS "mass_storage"
-#define USB_FUNC_DEFAULT "default"
-
-class AutoMounter;
-
-static void SetAutoMounterStatus(int32_t aStatus);
-
-/***************************************************************************/
-
-inline const char* SwitchStateStr(const hal::SwitchEvent& aEvent)
-{
- return aEvent.status() == hal::SWITCH_STATE_ON ? "plugged" : "unplugged";
-}
-
-/***************************************************************************/
-
-static bool
-IsUsbCablePluggedIn()
-{
-#if 0
- // Use this code when bug 745078 gets fixed (or use whatever the
- // appropriate method is)
- return GetCurrentSwitchEvent(SWITCH_USB) == hal::SWITCH_STATE_ON;
-#else
- // Until then, just go read the file directly
- if (access(ICS_SYS_USB_STATE, F_OK) == 0) {
- char usbState[20];
- if (ReadSysFile(ICS_SYS_USB_STATE, usbState, sizeof(usbState))) {
- DBG("IsUsbCablePluggedIn: state = '%s'", usbState);
- return strcmp(usbState, "CONFIGURED") == 0 ||
- strcmp(usbState, "CONNECTED") == 0;
- }
- ERR("Error reading file '%s': %s", ICS_SYS_USB_STATE, strerror(errno));
- return false;
- }
- bool configured;
- if (ReadSysFile(GB_SYS_USB_CONFIGURED, &configured)) {
- return configured;
- }
- ERR("Error reading file '%s': %s", GB_SYS_USB_CONFIGURED, strerror(errno));
- return false;
-#endif
-}
-
-static bool
-IsUsbConfigured()
-{
- if (access(ICS_SYS_USB_STATE, F_OK) == 0) {
- char usbState[20];
- if (ReadSysFile(ICS_SYS_USB_STATE, usbState, sizeof(usbState))) {
- DBG("IsUsbConfigured: state = '%s'", usbState);
- return strcmp(usbState, "CONFIGURED") == 0;
- }
- ERR("Error reading file '%s': %s", ICS_SYS_USB_STATE, strerror(errno));
- return false;
- }
- bool configured;
- if (ReadSysFile(GB_SYS_USB_CONFIGURED, &configured)) {
- return configured;
- }
- ERR("Error reading file '%s': %s", GB_SYS_USB_CONFIGURED, strerror(errno));
- return false;
-}
-
-/***************************************************************************/
-
-// The AutoVolumeManagerStateObserver allows the AutoMounter to know when
-// the volume manager changes state (i.e. it has finished initialization)
-class AutoVolumeManagerStateObserver : public VolumeManager::StateObserver
-{
-public:
- virtual void Notify(const VolumeManager::StateChangedEvent& aEvent);
-};
-
-// The AutoVolumeEventObserver allows the AutoMounter to know about card
-// insertion and removal, as well as state changes in the volume.
-class AutoVolumeEventObserver : public Volume::EventObserver
-{
-public:
- virtual void Notify(Volume* const& aEvent);
-};
-
-class AutoMounterResponseCallback : public VolumeResponseCallback
-{
-public:
- AutoMounterResponseCallback()
- : mErrorCount(0)
- {
- }
-
-protected:
- virtual void ResponseReceived(const VolumeCommand* aCommand);
-
-private:
- const static int kMaxErrorCount = 3; // Max number of errors before we give up
-
- int mErrorCount;
-};
-
-/***************************************************************************/
-
-class AutoMounter
-{
-public:
- NS_INLINE_DECL_REFCOUNTING(AutoMounter)
-
- typedef nsTArray<RefPtr<Volume>> VolumeArray;
-
- AutoMounter()
- : mState(STATE_IDLE),
- mResponseCallback(new AutoMounterResponseCallback),
- mMode(AUTOMOUNTER_DISABLE)
- {
- VolumeManager::RegisterStateObserver(&mVolumeManagerStateObserver);
- Volume::RegisterVolumeObserver(&mVolumeEventObserver, "AutoMounter");
-
- // It's possible that the VolumeManager is already in the READY state,
- // so we call CheckVolumeSettings here to cover that case. Otherwise,
- // we'll pick it up when the VolumeManage state changes to VOLUMES_READY.
- CheckVolumeSettings();
-
- DBG("Calling UpdateState from constructor");
- UpdateState();
- }
-
- void CheckVolumeSettings()
- {
- if (VolumeManager::State() != VolumeManager::VOLUMES_READY) {
- DBG("CheckVolumeSettings: VolumeManager is NOT READY yet");
- return;
- }
- DBG("CheckVolumeSettings: VolumeManager is READY");
-
- // The VolumeManager knows about all of the volumes from vold. We now
- // know the names of all of the volumes, so we can find out what the
- // initial sharing settings are set to.
-
- VolumeManager::VolumeArray::size_type numVolumes = VolumeManager::NumVolumes();
- VolumeManager::VolumeArray::index_type i;
- for (i = 0; i < numVolumes; i++) {
- RefPtr<Volume> vol = VolumeManager::GetVolume(i);
- if (vol) {
- // We need to pick up the intial value of the
- // ums.volume.NAME.enabled setting.
- AutoMounterSetting::CheckVolumeSettings(vol->Name());
-
- // Note: eventually CheckVolumeSettings will call
- // AutoMounter::SetSharingMode, which will in turn call
- // UpdateState if needed.
- }
- }
- }
-
- void UpdateState();
- void GetStatus(bool& umsAvail, bool& umsConfigured, bool& umsEnabled, bool& mtpAvail,
- bool& mtpConfigured, bool& mtpEnabled, bool& rndisConfigured);
-
- nsresult Dump(nsACString& desc);
-
- void ConfigureUsbFunction(const char* aUsbFunc);
-
- bool StartMtpServer();
- void StopMtpServer();
-
- void StartUmsSharing();
- void StopUmsSharing();
-
-
- const char* ModeStr(int32_t aMode)
- {
- switch (aMode) {
- case AUTOMOUNTER_DISABLE: return "Disable";
- case AUTOMOUNTER_ENABLE_UMS: return "Enable-UMS";
- case AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED: return "DisableWhenUnplugged";
- case AUTOMOUNTER_ENABLE_MTP: return "Enable-MTP";
- }
- return "??? Unknown ???";
- }
-
- bool IsModeEnabled(int32_t aMode)
- {
- return aMode == AUTOMOUNTER_ENABLE_MTP ||
- aMode == AUTOMOUNTER_ENABLE_UMS;
- }
-
- void SetMode(int32_t aMode)
- {
- if ((aMode == AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED) &&
- (mMode == AUTOMOUNTER_DISABLE)) {
- // If it's already disabled, then leave it as disabled.
- // AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED implies "enabled until unplugged"
- aMode = AUTOMOUNTER_DISABLE;
- }
-
- if (aMode == AUTOMOUNTER_DISABLE &&
- mMode == AUTOMOUNTER_ENABLE_UMS && IsUsbCablePluggedIn()) {
- // On many devices (esp non-Samsung), we can't force the disable, so we
- // need to defer until the USB cable is actually unplugged.
- // See bug 777043.
- //
- // Otherwise our attempt to disable it will fail, and we'll wind up in a bad
- // state where the AutoMounter thinks that Sharing has been turned off, but
- // the files are actually still being Shared because the attempt to unshare
- // failed.
- LOG("Attempting to disable UMS. Deferring until USB cable is unplugged.");
- aMode = AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED;
- }
-
- if (aMode != mMode) {
- LOG("Changing mode from '%s' to '%s'", ModeStr(mMode), ModeStr(aMode));
- mMode = aMode;
- DBG("Calling UpdateState due to mode set to %d", mMode);
- UpdateState();
- }
- }
-
- void SetSharingMode(const nsACString& aVolumeName, bool aAllowSharing)
- {
- RefPtr<Volume> vol = VolumeManager::FindVolumeByName(aVolumeName);
- if (!vol) {
- return;
- }
- if (vol->IsSharingEnabled() == aAllowSharing) {
- return;
- }
- vol->SetUnmountRequested(false);
- vol->SetMountRequested(false);
- vol->SetSharingEnabled(aAllowSharing);
- DBG("Calling UpdateState due to volume %s sharing set to %d",
- vol->NameStr(), (int)aAllowSharing);
- UpdateState();
- }
-
- void FormatVolume(const nsACString& aVolumeName)
- {
- RefPtr<Volume> vol = VolumeManager::FindVolumeByName(aVolumeName);
- if (!vol) {
- return;
- }
- if (vol->IsFormatRequested()) {
- return;
- }
- vol->SetUnmountRequested(false);
- vol->SetMountRequested(false);
- vol->SetFormatRequested(true);
- DBG("Calling UpdateState due to volume %s formatting set to %d",
- vol->NameStr(), (int)vol->IsFormatRequested());
- UpdateState();
- }
-
- void MountVolume(const nsACString& aVolumeName)
- {
- RefPtr<Volume> vol = VolumeManager::FindVolumeByName(aVolumeName);
- if (!vol) {
- return;
- }
- vol->SetUnmountRequested(false);
- if (vol->IsMountRequested() || vol->mState == nsIVolume::STATE_MOUNTED) {
- return;
- }
- vol->SetMountRequested(true);
- DBG("Calling UpdateState due to volume %s mounting set to %d",
- vol->NameStr(), (int)vol->IsMountRequested());
- UpdateState();
- }
-
- void UnmountVolume(const nsACString& aVolumeName)
- {
- RefPtr<Volume> vol = VolumeManager::FindVolumeByName(aVolumeName);
- if (!vol) {
- return;
- }
- if (vol->IsUnmountRequested()) {
- return;
- }
- vol->SetMountRequested(false);
- vol->SetUnmountRequested(true);
- DBG("Calling UpdateState due to volume %s unmounting set to %d",
- vol->NameStr(), (int)vol->IsUnmountRequested());
- UpdateState();
- }
-
-protected:
- ~AutoMounter()
- {
- Volume::UnregisterVolumeObserver(&mVolumeEventObserver, "AutoMounter");
- VolumeManager::UnregisterStateObserver(&mVolumeManagerStateObserver);
- }
-
-private:
-
- enum STATE
- {
- // IDLE - Nothing is being shared
- STATE_IDLE,
-
- // We've detected that conditions are right to enable mtp. So we've
- // set sys.usb.config to include mtp, and we're waiting for the USB
- // subsystem to be "configured". Once mtp shows up in
- // then we know
- // that its been configured and we can open /dev/mtp_usb
- STATE_MTP_CONFIGURING,
-
- // mtp has been configured (i.e. mtp now shows up in
- // /sys/devices/virtual/android_usb/android0/functions so we can start
- // the mtp server.
- STATE_MTP_STARTED,
-
- // The mtp server has reported sessionStarted. We'll leave this state
- // when we receive sessionEnded.
- STATE_MTP_CONNECTED,
-
- // We've added mass_storage (aka UMS) to sys.usb.config and we're waiting for
- // mass_storage to appear in /sys/devices/virtual/android_usb/android0/functions
- STATE_UMS_CONFIGURING,
-
- // mass_storage has been configured and we can start sharing once the user
- // enables it.
- STATE_UMS_CONFIGURED,
-
- // USB Tethering is enabled
- STATE_RNDIS_CONFIGURED,
- };
-
- const char *StateStr(STATE aState)
- {
- switch (aState) {
- case STATE_IDLE: return "IDLE";
- case STATE_MTP_CONFIGURING: return "MTP_CONFIGURING";
- case STATE_MTP_CONNECTED: return "MTP_CONNECTED";
- case STATE_MTP_STARTED: return "MTP_STARTED";
- case STATE_UMS_CONFIGURING: return "UMS_CONFIGURING";
- case STATE_UMS_CONFIGURED: return "UMS_CONFIGURED";
- case STATE_RNDIS_CONFIGURED: return "RNDIS_CONFIGURED";
- }
- return "STATE_???";
- }
-
- void SetState(STATE aState)
- {
- const char *oldStateStr = StateStr(mState);
- mState = aState;
- const char *newStateStr = StateStr(mState);
- LOG("AutoMounter state changed from %s to %s", oldStateStr, newStateStr);
- }
-
- STATE mState;
-
- AutoVolumeEventObserver mVolumeEventObserver;
- AutoVolumeManagerStateObserver mVolumeManagerStateObserver;
- RefPtr<VolumeResponseCallback> mResponseCallback;
- int32_t mMode;
- MozMtpStorage::Array mMozMtpStorage;
-};
-
-static StaticRefPtr<AutoMounter> sAutoMounter;
-static StaticRefPtr<MozMtpServer> sMozMtpServer;
-
-// The following is for status reporter
-enum STATE_REPORTER_STATE
-{
- REPORTER_UNREGISTERED,
- REPORTER_REGISTERED
-};
-
-static int status_reporter_progress = REPORTER_UNREGISTERED;
-nsresult getState(nsACString &desc)
-{
- sAutoMounter->Dump(desc);
- return NS_OK;
-}
-NS_STATUS_REPORTER_IMPLEMENT(AutoMounter, "AutoMounter", getState);
-
-/***************************************************************************/
-
-void
-AutoVolumeManagerStateObserver::Notify(const VolumeManager::StateChangedEvent &)
-{
- LOG("VolumeManager state changed event: %s", VolumeManager::StateStr());
-
- if (!sAutoMounter) {
- return;
- }
-
- // In the event that the VolumeManager just entered the VOLUMES_READY state,
- // we call CheckVolumeSettings here (it's possible that this method never
- // gets called if the VolumeManager was already in the VOLUMES_READY state
- // by the time the AutoMounter was constructed).
- sAutoMounter->CheckVolumeSettings();
-
- DBG("Calling UpdateState due to VolumeManagerStateObserver");
- sAutoMounter->UpdateState();
-}
-
-void
-AutoVolumeEventObserver::Notify(Volume * const &)
-{
- if (!sAutoMounter) {
- return;
- }
- DBG("Calling UpdateState due to VolumeEventStateObserver");
- sAutoMounter->UpdateState();
-}
-
-void
-AutoMounterResponseCallback::ResponseReceived(const VolumeCommand* aCommand)
-{
-
- if (WasSuccessful()) {
- DBG("Calling UpdateState due to Volume::OnSuccess");
- mErrorCount = 0;
- sAutoMounter->UpdateState();
- return;
- }
- ERR("Command '%s' failed: %d '%s'",
- aCommand->CmdStr(), ResponseCode(), ResponseStr().get());
-
- if (++mErrorCount < kMaxErrorCount) {
- DBG("Calling UpdateState due to VolumeResponseCallback::OnError");
- sAutoMounter->UpdateState();
- }
-}
-
-static bool
-IsUsbFunctionEnabled(const char* aConfig, const char* aUsbFunc)
-{
- nsAutoCString config(aConfig);
- nsCCharSeparatedTokenizer tokenizer(config, ',');
-
- while (tokenizer.hasMoreTokens()) {
- nsAutoCString token(tokenizer.nextToken());
- if (token.Equals(aUsbFunc)) {
- DBG("IsUsbFunctionEnabled('%s', '%s'): returning true", aConfig, aUsbFunc);
- return true;
- }
- }
- DBG("IsUsbFunctionEnabled('%s', '%s'): returning false", aConfig, aUsbFunc);
- return false;
-}
-
-static void
-SetUsbFunction(const char* aUsbFunc)
-{
- char oldSysUsbConfig[PROPERTY_VALUE_MAX];
- property_get(SYS_USB_CONFIG, oldSysUsbConfig, "");
-
- if (strcmp(oldSysUsbConfig, USB_FUNC_NONE) == 0) {
- // It's quite possible that sys.usb.config may have the value "none". We
- // convert that to an empty string here, and at the end we convert the
- // empty string back to "none".
- oldSysUsbConfig[0] = '\0';
- }
-
- if (IsUsbFunctionEnabled(oldSysUsbConfig, aUsbFunc)) {
- // The function is already configured. Nothing else to do.
- DBG("SetUsbFunction('%s') - already set - nothing to do", aUsbFunc);
- return;
- }
-
- char newSysUsbConfig[PROPERTY_VALUE_MAX];
-
- if (strcmp(aUsbFunc, USB_FUNC_MTP) == 0) {
- // We're enabling MTP. For this we'll wind up using mtp, or mtp,adb
- strlcpy(newSysUsbConfig, USB_FUNC_MTP, sizeof(newSysUsbConfig));
- } else if (strcmp(aUsbFunc, USB_FUNC_UMS) == 0) {
- // We're enabling UMS. For this we make the assumption that the persisted
- // property has mass_storage enabled.
- property_get(PERSIST_SYS_USB_CONFIG, newSysUsbConfig, "");
- } else if (strcmp(aUsbFunc, USB_FUNC_DEFAULT) == 0) {
- // Set the property as PERSIST_SYS_USB_CONFIG
- property_get(PERSIST_SYS_USB_CONFIG, newSysUsbConfig, "");
- } else {
- printf_stderr("AutoMounter::SetUsbFunction Unrecognized aUsbFunc '%s'\n", aUsbFunc);
- MOZ_ASSERT(0);
- return;
- }
-
- // Make sure the new value that we write into sys.usb.config keeps the adb
- // (or non-adb) of the current string.
-
- if (IsUsbFunctionEnabled(oldSysUsbConfig, USB_FUNC_ADB)) {
- // ADB was turned on - keep it on.
- if (!IsUsbFunctionEnabled(newSysUsbConfig, USB_FUNC_ADB)) {
- // Add adb to the new string
- strlcat(newSysUsbConfig, ",", sizeof(newSysUsbConfig));
- strlcat(newSysUsbConfig, USB_FUNC_ADB, sizeof(newSysUsbConfig));
- }
- } else {
- // ADB was turned off - keep it off
- if (IsUsbFunctionEnabled(newSysUsbConfig, USB_FUNC_ADB)) {
- // Remove ADB from the new string.
- if (strcmp(newSysUsbConfig, USB_FUNC_ADB) == 0) {
- newSysUsbConfig[0] = '\0';
- } else {
- nsAutoCString withoutAdb(newSysUsbConfig);
- withoutAdb.ReplaceSubstring( "," USB_FUNC_ADB, "");
- strlcpy(newSysUsbConfig, withoutAdb.get(), sizeof(newSysUsbConfig));
- }
- }
- }
-
- // If the persisted function didn't have mass_storage (this happens on
- // the nexus 4/5, then we can get to here and have oldSysUsbConfig equal
- // to newSysUsbConfig. So we need to check for that.
-
- if (strcmp(oldSysUsbConfig, newSysUsbConfig) == 0) {
- DBG("SetUsbFunction('%s') %s is already set to '%s' - nothing to do",
- aUsbFunc, SYS_USB_CONFIG, newSysUsbConfig);
- return;
- }
-
- if (newSysUsbConfig[0] == '\0') {
- // Convert the empty string back to the string "none"
- strlcpy(newSysUsbConfig, USB_FUNC_NONE, sizeof(newSysUsbConfig));
- }
- LOG("SetUsbFunction(%s) %s from '%s' to '%s'", aUsbFunc, SYS_USB_CONFIG,
- oldSysUsbConfig, newSysUsbConfig);
- property_set(SYS_USB_CONFIG, newSysUsbConfig);
-}
-
-bool
-AutoMounter::StartMtpServer()
-{
- if (sMozMtpServer) {
- // Mtp Server is already running - nothing to do
- return true;
- }
- LOG("Starting MtpServer");
-
- // For debugging, Change the #if 0 to #if 1, and then attach gdb during
- // the 5 second interval below. Otherwise, configuring MTP will cause adb
- // (and thus gdb) to get bounced.
-#if 0
- LOG("Sleeping");
- PRTime now = PR_Now();
- PRTime stopTime = now + 5000000;
- while (PR_Now() < stopTime) {
- LOG("Sleeping...");
- sleep(1);
- }
- LOG("Sleep done");
-#endif
-
- sMozMtpServer = new MozMtpServer();
- if (!sMozMtpServer->Init()) {
- sMozMtpServer = nullptr;
- return false;
- }
-
- VolumeArray::index_type volIndex;
- VolumeArray::size_type numVolumes = VolumeManager::NumVolumes();
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = VolumeManager::GetVolume(volIndex);
- RefPtr<MozMtpStorage> storage = new MozMtpStorage(vol, sMozMtpServer);
- mMozMtpStorage.AppendElement(storage);
- }
-
- sMozMtpServer->Run();
- return true;
-}
-
-void
-AutoMounter::StopMtpServer()
-{
- LOG("Stopping MtpServer");
-
- mMozMtpStorage.Clear();
- sMozMtpServer = nullptr;
-}
-
-/***************************************************************************/
-
-void
-AutoMounter::UpdateState()
-{
- static bool inUpdateState = false;
- if (inUpdateState) {
- // When UpdateState calls SetISharing, this causes a volume state
- // change to occur, which would normally cause UpdateState to be called
- // again. We want the volume state change to go out (so that device
- // storage will see the change in sharing state), but since we're
- // already in UpdateState we just want to prevent recursion from screwing
- // things up.
- return;
- }
- AutoRestore<bool> inUpdateStateDetector(inUpdateState);
- inUpdateState = true;
-
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- // If the following preconditions are met:
- // - UMS is available (i.e. compiled into the kernel)
- // - UMS is enabled
- // - AutoMounter is enabled
- // - USB cable is plugged in
- // then we will try to unmount and share
- // otherwise we will try to unshare and mount.
-
- if (VolumeManager::State() != VolumeManager::VOLUMES_READY) {
- // The volume manager isn't in a ready state, so there
- // isn't anything else that we can do.
- LOG("UpdateState: VolumeManager not ready yet");
- return;
- }
-
- if (mResponseCallback->IsPending()) {
- // We only deal with one outstanding volume command at a time,
- // so we need to wait for it to finish.
- return;
- }
-
- // Calling setprop sys.usb.config mtp,adb (or adding mass_storage) will
- // cause /sys/devices/virtual/android_usb/android0/state to go:
- // CONFIGURED -> DISCONNECTED -> CONNECTED -> CONFIGURED
- //
- // Since IsUsbCablePluggedIn returns state == CONFIGURED, it will look
- // like a cable pull and replugin.
- bool umsAvail, umsConfigured, umsEnabled;
- bool mtpAvail, mtpConfigured, mtpEnabled;
- bool rndisConfigured;
- bool usbCablePluggedIn = IsUsbCablePluggedIn();
- GetStatus(umsAvail, umsConfigured, umsEnabled, mtpAvail,
- mtpConfigured, mtpEnabled, rndisConfigured);
- bool enabled = mtpEnabled || umsEnabled;
-
- if (mMode == AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED) {
- // DISABLE_WHEN_UNPLUGGED implies already enabled.
- enabled = usbCablePluggedIn;
- if (!usbCablePluggedIn) {
- mMode = AUTOMOUNTER_DISABLE;
- mtpEnabled = false;
- umsEnabled = false;
- }
- }
-
- DBG("UpdateState: ums:A%dC%dE%d mtp:A%dC%dE%d rndis:%d mode:%d usb:%d mState:%s",
- umsAvail, umsConfigured, umsEnabled,
- mtpAvail, mtpConfigured, mtpEnabled, rndisConfigured,
- mMode, usbCablePluggedIn, StateStr(mState));
-
- switch (mState) {
-
- case STATE_IDLE:
- if (!usbCablePluggedIn) {
- // Stay in the IDLE state. We'll get a CONNECTED or CONFIGURED
- // UEvent when the usb cable is plugged in.
- break;
- }
- if (rndisConfigured) {
- // USB Tethering uses RNDIS. We'll just wait until its turned off.
- SetState(STATE_RNDIS_CONFIGURED);
- break;
- }
- if (mtpEnabled) {
- if (mtpConfigured) {
- // The USB layer has already been configured. Now we can go ahead
- // and start the MTP server. This particular codepath will not
- // normally be taken, but it could happen if you stop and restart
- // b2g while sys.usb.config is set to enable mtp.
- if (StartMtpServer()) {
- SetState(STATE_MTP_STARTED);
- } else {
- if (umsAvail) {
- // Unable to start MTP. Go back to UMS.
- LOG("UpdateState: StartMtpServer failed, switch to UMS");
- SetUsbFunction(USB_FUNC_UMS);
- SetState(STATE_UMS_CONFIGURING);
- } else {
- LOG("UpdateState: StartMtpServer failed, keep idle state");
- SetUsbFunction(USB_FUNC_DEFAULT);
- }
- }
- } else {
- // We need to configure USB to use mtp. Wait for it to be configured
- // before we start the MTP server.
- SetUsbFunction(USB_FUNC_MTP);
- SetState(STATE_MTP_CONFIGURING);
- }
- } else if (umsConfigured) {
- // UMS is already configured.
- SetState(STATE_UMS_CONFIGURED);
- } else if (umsAvail) {
- // We do this whether or not UMS is enabled. With UMS, it's the
- // sharing of the volume which is significant. What is important
- // is that we don't leave it in MTP mode when MTP isn't enabled.
- SetUsbFunction(USB_FUNC_UMS);
- SetState(STATE_UMS_CONFIGURING);
- }
- break;
-
- case STATE_MTP_CONFIGURING:
- // While configuring, the USB configuration state will change from
- // CONFIGURED -> CONNECTED -> DISCONNECTED -> CONNECTED -> CONFIGURED
- // so we don't check for cable unplugged here.
- if (mtpEnabled && mtpConfigured) {
- // The USB layer has been configured. Now we can go ahead and start
- // the MTP server.
- if (StartMtpServer()) {
- SetState(STATE_MTP_STARTED);
- } else {
- // Unable to start MTP. Go back to UMS.
- SetUsbFunction(USB_FUNC_UMS);
- SetState(STATE_UMS_CONFIGURING);
- }
- break;
- }
- if (rndisConfigured) {
- SetState(STATE_RNDIS_CONFIGURED);
- break;
- }
- break;
-
- case STATE_MTP_STARTED:
- if (usbCablePluggedIn && mtpConfigured && mtpEnabled) {
- // Everything is still good. Leave the MTP server running
- break;
- }
- DBG("STATE_MTP_STARTED: About to StopMtpServer "
- "mtpConfigured = %d mtpEnabled = %d usbCablePluggedIn: %d",
- mtpConfigured, mtpEnabled, usbCablePluggedIn);
- StopMtpServer();
- if (rndisConfigured) {
- SetState(STATE_RNDIS_CONFIGURED);
- break;
- }
- if (umsAvail) {
- // Switch back to UMS
- SetUsbFunction(USB_FUNC_UMS);
- SetState(STATE_UMS_CONFIGURING);
- break;
- }
-
- // if ums/rndis is not available and mtp is disable,
- // restore the usb function as PERSIST_SYS_USB_CONFIG.
- SetUsbFunction(USB_FUNC_DEFAULT);
- SetState(STATE_IDLE);
- break;
-
- case STATE_UMS_CONFIGURING:
- if (mtpEnabled) {
- // MTP was enabled. Start reconfiguring.
- SetState(STATE_MTP_CONFIGURING);
- SetUsbFunction(USB_FUNC_MTP);
- break;
- }
- if (rndisConfigured) {
- SetState(STATE_RNDIS_CONFIGURED);
- break;
- }
- // While configuring, the USB configuration state will change from
- // CONFIGURED -> CONNECTED -> DISCONNECTED -> CONNECTED -> CONFIGURED
- // so we don't check for cable unplugged here. However, having said
- // that, we'll often sit in this state while the cable is unplugged,
- // since we might not get any events until the cable gets plugged back
- // in. This is why we need to check for mtpEnabled once we get the
- // configured event.
- if (umsConfigured) {
- SetState(STATE_UMS_CONFIGURED);
- }
- break;
-
- case STATE_UMS_CONFIGURED:
- if (usbCablePluggedIn) {
- if (mtpEnabled) {
- // MTP was enabled. Start reconfiguring.
- SetState(STATE_MTP_CONFIGURING);
- SetUsbFunction(USB_FUNC_MTP);
- break;
- }
- if (umsConfigured && umsEnabled) {
- // This is the normal state when UMS is enabled.
- break;
- }
- }
- if (rndisConfigured) {
- SetState(STATE_RNDIS_CONFIGURED);
- break;
- }
- SetState(STATE_IDLE);
- break;
-
- case STATE_RNDIS_CONFIGURED:
- if (usbCablePluggedIn && rndisConfigured) {
- // Normal state when RNDIS is enabled.
- break;
- }
- SetState(STATE_IDLE);
- break;
-
- default:
- SetState(STATE_IDLE);
- break;
- }
-
- bool tryToShare = umsEnabled && usbCablePluggedIn;
- LOG("UpdateState: ums:A%dC%dE%d mtp:A%dC%dE%d mode:%d usb:%d tryToShare:%d state:%s",
- umsAvail, umsConfigured, umsEnabled,
- mtpAvail, mtpConfigured, mtpEnabled,
- mMode, usbCablePluggedIn, tryToShare, StateStr(mState));
-
- bool filesOpen = false;
- static unsigned filesOpenDelayCount = 0;
- VolumeArray::index_type volIndex;
- VolumeArray::size_type numVolumes = VolumeManager::NumVolumes();
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = VolumeManager::GetVolume(volIndex);
- Volume::STATE volState = vol->State();
-
- if (vol->State() == nsIVolume::STATE_MOUNTED) {
- LOG("UpdateState: Volume %s is %s and %s @ %s gen %d locked %d sharing %s",
- vol->NameStr(), vol->StateStr(),
- vol->MediaPresent() ? "inserted" : "missing",
- vol->MountPoint().get(), vol->MountGeneration(),
- (int)vol->IsMountLocked(),
- vol->CanBeShared() ? (vol->IsSharingEnabled() ?
- (vol->IsSharing() ? "en-y" : "en-n") : "dis") : "x");
- if (vol->IsSharing() && !usbCablePluggedIn) {
- // We call SetIsSharing(true) below to indicate intent to share. This
- // causes a state change which notifys apps, and they'll close any
- // open files, which will initiate the change away from the mounted
- // state and into the sharing state. Normally, when the volume
- // transitions back to the mounted state, then vol->mIsSharing gets set
- // to false. However, if the user pulls the USB cable before we
- // actually start sharing, then the volume never actually leaves
- // the mounted state (and hence never transitions from
- // sharing -> mounted), and mIsSharing never gets set back to false.
- // So we clear mIsSharing here.
- vol->SetIsSharing(false);
- }
- } else {
- LOG("UpdateState: Volume %s is %s and %s", vol->NameStr(), vol->StateStr(),
- vol->MediaPresent() ? "inserted" : "missing");
- }
- if (!vol->MediaPresent()) {
- // No media - nothing we can do
- continue;
- }
-
- if (vol->State() == nsIVolume::STATE_CHECKMNT) {
- // vold reports the volume is "Mounted". Need to check if the volume is
- // accessible by statfs(). Once it can be accessed, set the volume as
- // STATE_MOUNTED, otherwise, post a delay task of UpdateState to check it
- // again.
- struct statfs fsbuf;
- int rc = MOZ_TEMP_FAILURE_RETRY(statfs(vol->MountPoint().get(), &fsbuf));
- if (rc == -1) {
- // statfs() failed. Stay in STATE_CHECKMNT. Any failures here
- // are probably non-recoverable, so we need to wait until
- // something else changes the state back to IDLE/UNMOUNTED, etc.
- ERR("statfs failed for '%s': errno = %d (%s)", vol->NameStr(), errno, strerror(errno));
- continue;
- }
- static int delay = 250;
- if (fsbuf.f_blocks == 0) {
- if (delay <= 4000) {
- LOG("UpdateState: Volume '%s' is inaccessible, checking again in %d msec", vol->NameStr(), delay);
- MessageLoopForIO::current()->
- PostDelayedTask(NewRunnableMethod(this, &AutoMounter::UpdateState),
- delay);
- delay *= 2;
- } else {
- LOG("UpdateState: Volume '%s' is inaccessible, giving up", vol->NameStr());
- }
- continue;
- } else {
- delay = 250;
- vol->SetState(nsIVolume::STATE_MOUNTED);
- }
- }
-
- if ((tryToShare && vol->IsSharingEnabled()) ||
- vol->IsFormatRequested() ||
- vol->IsUnmountRequested()) {
- switch (volState) {
- // We're going to try to unmount the volume
- case nsIVolume::STATE_MOUNTED: {
- if (vol->IsMountLocked()) {
- // The volume is currently locked, so leave it in the mounted
- // state.
- LOGW("UpdateState: Mounted volume %s is locked, not sharing or formatting",
- vol->NameStr());
- break;
- }
-
- // Mark the volume as if we've started sharing/formatting/unmmounting.
- // This will cause apps which watch device storage notifications to see
- // the volume go into the different state, and prompt them to close any
- // open files that they might have.
- if (tryToShare && vol->IsSharingEnabled()) {
- vol->SetIsSharing(true);
- } else if (vol->IsFormatRequested()){
- vol->SetIsFormatting(true);
- } else if (vol->IsUnmountRequested()){
- vol->SetIsUnmounting(true);
- }
-
- // Check to see if there are any open files on the volume and
- // don't initiate the unmount while there are open files.
- OpenFileFinder::Info fileInfo;
- OpenFileFinder fileFinder(vol->MountPoint());
- if (fileFinder.First(&fileInfo)) {
- LOGW("The following files are open under '%s'",
- vol->MountPoint().get());
- do {
- LOGW(" PID: %d file: '%s' app: '%s' comm: '%s' exe: '%s'\n",
- fileInfo.mPid,
- fileInfo.mFileName.get(),
- fileInfo.mAppName.get(),
- fileInfo.mComm.get(),
- fileInfo.mExe.get());
- } while (fileFinder.Next(&fileInfo));
- LOGW("UpdateState: Mounted volume %s has open files, not sharing or formatting",
- vol->NameStr());
-
- // Check again in a few seconds to see if the files are closed.
- // Since we're trying to share the volume, this implies that we're
- // plugged into the PC via USB and this in turn implies that the
- // battery is charging, so we don't need to be too concerned about
- // wasting battery here.
- //
- // If we just detected that there were files open, then we use
- // a short timer. We will have told the apps that we're trying
- // trying to share, and they'll be closing their files. This makes
- // the sharing more responsive. If after a few seconds, the apps
- // haven't closed their files, then we back off.
-
- int delay = 1000;
- if (filesOpenDelayCount > 10) {
- delay = 5000;
- }
- MessageLoopForIO::current()->
- PostDelayedTask(NewRunnableMethod(this, &AutoMounter::UpdateState),
- delay);
- filesOpen = true;
- break;
- }
-
- // Volume is mounted, we need to unmount before
- // we can share.
- LOG("UpdateState: Unmounting %s", vol->NameStr());
- vol->StartUnmount(mResponseCallback);
- return; // UpdateState will be called again when the Unmount command completes
- }
- case nsIVolume::STATE_IDLE:
- case nsIVolume::STATE_MOUNT_FAIL: {
- LOG("UpdateState: Volume %s is %s", vol->NameStr(), vol->StateStr());
- if (vol->IsFormatting() && !vol->IsFormatRequested()) {
- vol->SetFormatRequested(false);
- if (!(tryToShare && vol->IsSharingEnabled()) && volState == nsIVolume::STATE_IDLE) {
- LOG("UpdateState: Mounting %s", vol->NameStr());
- vol->StartMount(mResponseCallback);
- break;
- }
- }
-
- // If there are format and share requests in the same time,
- // we should do format first then share.
- if (vol->IsFormatRequested()) {
- // Volume is unmounted. We can go ahead and format.
- LOG("UpdateState: Formatting %s", vol->NameStr());
- vol->StartFormat(mResponseCallback);
- } else if (tryToShare && vol->IsSharingEnabled() && volState == nsIVolume::STATE_IDLE) {
- // Volume is unmounted. We can go ahead and share.
- LOG("UpdateState: Sharing %s", vol->NameStr());
- vol->StartShare(mResponseCallback);
- }
- return; // UpdateState will be called again when the Share/Format command completes
- }
- default: {
- // Not in a state that we can do anything about.
- break;
- }
- }
- } else {
- // We're going to try and unshare and remount the volumes
- switch (volState) {
- case nsIVolume::STATE_SHARED: {
- // Volume is shared. We can go ahead and unshare.
- LOG("UpdateState: Unsharing %s", vol->NameStr());
- vol->StartUnshare(mResponseCallback);
- return; // UpdateState will be called again when the Unshare command completes
- }
- case nsIVolume::STATE_IDLE: {
- if (!vol->IsUnmountRequested()) {
- // Volume is unmounted and mount-requested, try to mount.
-
- LOG("UpdateState: Mounting %s", vol->NameStr());
- vol->StartMount(mResponseCallback);
- }
- return; // UpdateState will be called again when Mount command completes
- }
- default: {
- // Not in a state that we can do anything about.
- break;
- }
- }
- }
- }
-
- int32_t status = AUTOMOUNTER_STATUS_DISABLED;
- if (filesOpen) {
- filesOpenDelayCount++;
- status = AUTOMOUNTER_STATUS_FILES_OPEN;
- } else if (enabled) {
- filesOpenDelayCount = 0;
- status = AUTOMOUNTER_STATUS_ENABLED;
- }
- SetAutoMounterStatus(status);
-}
-
-/***************************************************************************/
-
-void AutoMounter::GetStatus(bool& umsAvail, bool& umsConfigured, bool& umsEnabled,
- bool& mtpAvail, bool& mtpConfigured, bool& mtpEnabled,
- bool& rndisConfigured)
-{
- umsAvail = false;
- umsConfigured = false;
- umsEnabled = false;
- mtpAvail = false;
- mtpConfigured = false;
- mtpEnabled = false;
- rndisConfigured = false;
-
- if (access(ICS_SYS_USB_FUNCTIONS, F_OK) != 0) {
- return;
- }
-
- char functionsStr[60];
- if (!ReadSysFile(ICS_SYS_USB_FUNCTIONS, functionsStr, sizeof(functionsStr))) {
- ERR("Error reading file '%s': %s", ICS_SYS_USB_FUNCTIONS, strerror(errno));
- functionsStr[0] = '\0';
- }
- DBG("GetStatus: USB functions: '%s'", functionsStr);
-
- bool usbConfigured = IsUsbConfigured();
-
- // On the Nexus 4/5, it advertises that the UMS usb function is available,
- // but we have a further requirement that mass_storage be in the
- // persist.sys.usb.config property.
- char persistSysUsbConfig[PROPERTY_VALUE_MAX];
- property_get(PERSIST_SYS_USB_CONFIG, persistSysUsbConfig, "");
- if (IsUsbFunctionEnabled(persistSysUsbConfig, USB_FUNC_UMS)) {
- umsAvail = (access(ICS_SYS_UMS_DIRECTORY, F_OK) == 0);
- }
- if (umsAvail) {
- umsConfigured = usbConfigured && strstr(functionsStr, USB_FUNC_UMS) != nullptr;
- umsEnabled = (mMode == AUTOMOUNTER_ENABLE_UMS) ||
- ((mMode == AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED) && umsConfigured);
- } else {
- umsConfigured = false;
- umsEnabled = false;
- }
-
- mtpAvail = (access(ICS_SYS_MTP_DIRECTORY, F_OK) == 0);
- if (mtpAvail) {
- mtpConfigured = usbConfigured && strstr(functionsStr, USB_FUNC_MTP) != nullptr;
- mtpEnabled = (mMode == AUTOMOUNTER_ENABLE_MTP) ||
- ((mMode == AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED) && mtpConfigured);
- } else {
- mtpConfigured = false;
- mtpEnabled = false;
- }
-
- rndisConfigured = strstr(functionsStr, USB_FUNC_RNDIS) != nullptr;
-}
-
-
-nsresult AutoMounter::Dump(nsACString& desc)
-{
- DBG("GetState!");
- bool umsAvail, umsConfigured, umsEnabled;
- bool mtpAvail, mtpConfigured, mtpEnabled;
- bool rndisConfigured;
- GetStatus(umsAvail, umsConfigured, umsEnabled, mtpAvail,
- mtpConfigured, mtpEnabled, rndisConfigured);
- if (mMode == AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED) {
- // DISABLE_WHEN_UNPLUGGED implies already enabled.
- if (!IsUsbCablePluggedIn()) {
- mMode = AUTOMOUNTER_DISABLE;
- mtpEnabled = false;
- umsEnabled = false;
- }
- }
-
- // Automounter information
- desc += "Current Mode:";
- desc += ModeStr(mMode);
- desc += "|";
-
-
- desc += "Current State:";
- desc += StateStr(mState);
- desc += "|";
-
- desc += "UMS Status:";
- if (umsAvail) {
- desc += "Available";
- } else {
- desc += "UnAvailable";
- }
- desc += ",";
- if (umsConfigured) {
- desc += "Configured";
- } else {
- desc += "Un-Configured";
- }
- desc += ",";
- if (umsEnabled) {
- desc += "Enabled";
- } else {
- desc += "Disabled";
- }
- desc += "|";
-
-
- desc += "MTP Status:";
- if (mtpAvail) {
- desc += "Available";
- } else {
- desc += "UnAvailable";
- }
- desc += ",";
- if (mtpConfigured) {
- desc += "Configured";
- } else {
- desc += "Un-Configured";
- }
- desc += ",";
- if (mtpEnabled) {
- desc += "Enabled";
- } else {
- desc += "Disabled";
- }
-
-
- // Volume information
- VolumeArray::index_type volIndex;
- VolumeArray::size_type numVolumes = VolumeManager::NumVolumes();
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = VolumeManager::GetVolume(volIndex);
-
- desc += "|";
- desc += vol->NameStr();
- desc += ":";
- desc += vol->StateStr();
- desc += "@";
- desc += vol->MountPoint().get();
-
- if (!vol->MediaPresent()) {
- continue;
- }
-
- if (vol->CanBeShared()) {
- desc += ",CanBeShared";
- }
- if (vol->CanBeFormatted()) {
- desc += ",CanBeFormatted";
- }
- if (vol->CanBeMounted()) {
- desc += ",CanBeMounted";
- }
- if (vol->IsRemovable()) {
- desc += ",Removable";
- }
- if (vol->IsHotSwappable()) {
- desc += ",HotSwappable";
- }
- }
-
- return NS_OK;
-}
-
-
-static void
-InitAutoMounterIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(!sAutoMounter);
-
- sAutoMounter = new AutoMounter();
-}
-
-static void
-ShutdownAutoMounterIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- sAutoMounter = nullptr;
- ShutdownVolumeManager();
-}
-
-static void
-SetAutoMounterModeIOThread(const int32_t& aMode)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(sAutoMounter);
-
- sAutoMounter->SetMode(aMode);
-}
-
-static void
-SetAutoMounterSharingModeIOThread(const nsCString& aVolumeName, const bool& aAllowSharing)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(sAutoMounter);
-
- sAutoMounter->SetSharingMode(aVolumeName, aAllowSharing);
-}
-
-static void
-AutoMounterFormatVolumeIOThread(const nsCString& aVolumeName)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(sAutoMounter);
-
- sAutoMounter->FormatVolume(aVolumeName);
-}
-
-static void
-AutoMounterMountVolumeIOThread(const nsCString& aVolumeName)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(sAutoMounter);
-
- sAutoMounter->MountVolume(aVolumeName);
-}
-
-static void
-AutoMounterUnmountVolumeIOThread(const nsCString& aVolumeName)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(sAutoMounter);
-
- sAutoMounter->UnmountVolume(aVolumeName);
-}
-
-static void
-UsbCableEventIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- if (!sAutoMounter) {
- return;
- }
- DBG("Calling UpdateState due to USBCableEvent");
- sAutoMounter->UpdateState();
-}
-
-/**************************************************************************
-*
-* Public API
-*
-* Since the AutoMounter runs in IO Thread context, we need to switch
-* to IOThread context before we can do anything.
-*
-**************************************************************************/
-
-class UsbCableObserver final : public hal::SwitchObserver
-{
- ~UsbCableObserver()
- {
- hal::UnregisterSwitchObserver(hal::SWITCH_USB, this);
- }
-
-public:
- NS_INLINE_DECL_REFCOUNTING(UsbCableObserver)
-
- UsbCableObserver()
- {
- hal::RegisterSwitchObserver(hal::SWITCH_USB, this);
- }
-
- virtual void Notify(const hal::SwitchEvent& aEvent)
- {
- DBG("UsbCable switch device: %d state: %s\n",
- aEvent.device(), SwitchStateStr(aEvent));
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(UsbCableEventIOThread));
- }
-};
-
-static StaticRefPtr<UsbCableObserver> sUsbCableObserver;
-static StaticRefPtr<AutoMounterSetting> sAutoMounterSetting;
-
-void
-InitAutoMounter()
-{
- InitVolumeManager();
- sAutoMounterSetting = new AutoMounterSetting();
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(InitAutoMounterIOThread));
-
- // Switch Observers need to run on the main thread, so we need to
- // start it here and have it send events to the AutoMounter running
- // on the IO Thread.
- sUsbCableObserver = new UsbCableObserver();
-
- // Register status reporter into reporter manager
- if(status_reporter_progress == REPORTER_UNREGISTERED) {
- NS_RegisterStatusReporter(new NS_STATUS_REPORTER_NAME(AutoMounter));
- }
- status_reporter_progress = REPORTER_REGISTERED;
-}
-
-int32_t
-GetAutoMounterStatus()
-{
- if (sAutoMounterSetting) {
- return sAutoMounterSetting->GetStatus();
- }
- return AUTOMOUNTER_STATUS_DISABLED;
-}
-
-//static
-void
-SetAutoMounterStatus(int32_t aStatus)
-{
- if (sAutoMounterSetting) {
- sAutoMounterSetting->SetStatus(aStatus);
- }
-}
-
-void
-SetAutoMounterMode(int32_t aMode)
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(SetAutoMounterModeIOThread, aMode));
-}
-
-void
-SetAutoMounterSharingMode(const nsCString& aVolumeName, bool aAllowSharing)
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(SetAutoMounterSharingModeIOThread,
- aVolumeName, aAllowSharing));
-}
-
-void
-AutoMounterFormatVolume(const nsCString& aVolumeName)
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(AutoMounterFormatVolumeIOThread,
- aVolumeName));
-}
-
-void
-AutoMounterMountVolume(const nsCString& aVolumeName)
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(AutoMounterMountVolumeIOThread,
- aVolumeName));
-}
-
-void
-AutoMounterUnmountVolume(const nsCString& aVolumeName)
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(AutoMounterUnmountVolumeIOThread,
- aVolumeName));
-}
-
-void
-ShutdownAutoMounter()
-{
- if (sAutoMounter) {
- DBG("ShutdownAutoMounter: About to StopMtpServer");
- sAutoMounter->StopMtpServer();
- // Unregister status reporter into reporter manager
- if(status_reporter_progress == REPORTER_REGISTERED) {
- NS_UnregisterStatusReporter(new NS_STATUS_REPORTER_NAME(AutoMounter));
- }
- status_reporter_progress = REPORTER_UNREGISTERED;
- }
- sAutoMounterSetting = nullptr;
- sUsbCableObserver = nullptr;
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(ShutdownAutoMounterIOThread));
-}
-
-} // system
-} // mozilla
diff --git a/dom/system/gonk/AutoMounter.h b/dom/system/gonk/AutoMounter.h
deleted file mode 100644
index ea98cadf1..000000000
--- a/dom/system/gonk/AutoMounter.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_automounter_h__
-#define mozilla_system_automounter_h__
-
-#include <stdint.h>
-
-class nsCString;
-
-namespace mozilla {
-namespace system {
-
-// AutoMounter modes
-#define AUTOMOUNTER_DISABLE 0
-#define AUTOMOUNTER_ENABLE_UMS 1
-#define AUTOMOUNTER_DISABLE_WHEN_UNPLUGGED 2
-#define AUTOMOUNTER_ENABLE_MTP 3
-
-// Automounter statuses
-#define AUTOMOUNTER_STATUS_DISABLED 0
-#define AUTOMOUNTER_STATUS_ENABLED 1
-#define AUTOMOUNTER_STATUS_FILES_OPEN 2
-
-/**
- * Initialize the automounter. This causes some of the phone's
- * directories to show up on the host when the phone is plugged
- * into the host via USB.
- *
- * When the AutoMounter starts, it will poll the current state
- * of affairs (usb cable plugged in, automounter enabled, etc)
- * and try to make the state of the volumes match.
- */
-void
-InitAutoMounter();
-
-/**
- * Sets the enabled state of the automounter.
- *
- * This will in turn cause the automounter to re-evaluate
- * whether it should mount/unmount/share/unshare volumes.
- */
-void
-SetAutoMounterMode(int32_t aMode);
-
-/**
- * Reports the status of the automounter.
- */
-int32_t
-GetAutoMounterStatus();
-
-/**
- * Sets the sharing mode of an individual volume.
- *
- * If a volume is enabled for sharing, and the autmounter
- * is in a state to share, then the volume will be shared
- * with the PC.
- */
-void
-SetAutoMounterSharingMode(const nsCString& aVolumeName, bool aAllowSharing);
-
-/**
- * Formats the volume with specified volume name.
- *
- * If the volume is ready to format, automounter
- * will unmount it, format it and then mount it again.
- */
-void
-AutoMounterFormatVolume(const nsCString& aVolumeName);
-
-/**
- * Mounts the volume with specified volume name.
- *
- * If the volume is already unmounted, automounter
- * will mount it. Otherwise automounter will skip this.
- */
-void
-AutoMounterMountVolume(const nsCString& aVolumeName);
-
-/**
- * Unmounts the volume with specified volume name.
- *
- * If the volume is already mounted, automounter
- * will unmount it. Otherwise automounter will skip this.
- */
-void
-AutoMounterUnmountVolume(const nsCString& aVolumeName);
-
-/**
- * Shuts down the automounter.
- *
- * This leaves the volumes in whatever state they're in.
- */
-void
-ShutdownAutoMounter();
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_automounter_h__
diff --git a/dom/system/gonk/AutoMounterSetting.cpp b/dom/system/gonk/AutoMounterSetting.cpp
deleted file mode 100644
index 606bcce04..000000000
--- a/dom/system/gonk/AutoMounterSetting.cpp
+++ /dev/null
@@ -1,284 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "AutoMounter.h"
-#include "AutoMounterSetting.h"
-
-#include "base/message_loop.h"
-#include "jsapi.h"
-#include "mozilla/Services.h"
-#include "nsCOMPtr.h"
-#include "nsContentUtils.h"
-#include "nsDebug.h"
-#include "nsIObserverService.h"
-#include "nsISettingsService.h"
-#include "nsJSUtils.h"
-#include "nsPrintfCString.h"
-#include "nsServiceManagerUtils.h"
-#include "nsString.h"
-#include "nsThreadUtils.h"
-#include "xpcpublic.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "mozilla/Attributes.h"
-#include "mozilla/dom/BindingUtils.h"
-#include "mozilla/dom/SettingChangeNotificationBinding.h"
-
-#undef LOG
-#undef ERR
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "AutoMounterSetting" , ## args)
-#define ERR(args...) __android_log_print(ANDROID_LOG_ERROR, "AutoMounterSetting" , ## args)
-
-#define UMS_MODE "ums.mode"
-#define UMS_STATUS "ums.status"
-#define UMS_VOLUME_ENABLED_PREFIX "ums.volume."
-#define UMS_VOLUME_ENABLED_SUFFIX ".enabled"
-#define MOZSETTINGS_CHANGED "mozsettings-changed"
-
-using namespace mozilla::dom;
-
-namespace mozilla {
-namespace system {
-
-class SettingsServiceCallback final : public nsISettingsServiceCallback
-{
-public:
- NS_DECL_THREADSAFE_ISUPPORTS
-
- SettingsServiceCallback() {}
-
- NS_IMETHOD Handle(const nsAString& aName, JS::Handle<JS::Value> aResult)
- {
- if (aResult.isInt32()) {
- int32_t mode = aResult.toInt32();
- SetAutoMounterMode(mode);
- }
- return NS_OK;
- }
-
- NS_IMETHOD HandleError(const nsAString& aName)
- {
- ERR("SettingsCallback::HandleError: %s\n", NS_LossyConvertUTF16toASCII(aName).get());
- return NS_OK;
- }
-
-protected:
- ~SettingsServiceCallback() {}
-};
-
-NS_IMPL_ISUPPORTS(SettingsServiceCallback, nsISettingsServiceCallback)
-
-class CheckVolumeSettingsCallback final : public nsISettingsServiceCallback
-{
-public:
- NS_DECL_THREADSAFE_ISUPPORTS
-
- CheckVolumeSettingsCallback(const nsACString& aVolumeName)
- : mVolumeName(aVolumeName) {}
-
- NS_IMETHOD Handle(const nsAString& aName, JS::Handle<JS::Value> aResult)
- {
- if (aResult.isBoolean()) {
- bool isSharingEnabled = aResult.toBoolean();
- SetAutoMounterSharingMode(mVolumeName, isSharingEnabled);
- }
- return NS_OK;
- }
-
- NS_IMETHOD HandleError(const nsAString& aName)
- {
- ERR("CheckVolumeSettingsCallback::HandleError: %s\n", NS_LossyConvertUTF16toASCII(aName).get());
- return NS_OK;
- }
-
-protected:
- ~CheckVolumeSettingsCallback() {}
-
-private:
- nsCString mVolumeName;
-};
-
-NS_IMPL_ISUPPORTS(CheckVolumeSettingsCallback, nsISettingsServiceCallback)
-
-AutoMounterSetting::AutoMounterSetting()
- : mStatus(AUTOMOUNTER_STATUS_DISABLED)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- // Setup an observer to watch changes to the setting
- nsCOMPtr<nsIObserverService> observerService =
- mozilla::services::GetObserverService();
- if (!observerService) {
- ERR("GetObserverService failed");
- return;
- }
- nsresult rv;
- rv = observerService->AddObserver(this, MOZSETTINGS_CHANGED, false);
- if (NS_FAILED(rv)) {
- ERR("AddObserver failed");
- return;
- }
-
- // Force ums.mode to be 0 initially. We do this because settings are persisted.
- // We don't want UMS to be enabled until such time as the phone is unlocked,
- // and gaia/apps/system/js/storage.js takes care of detecting when the phone
- // becomes unlocked and changes ums.mode appropriately.
- nsCOMPtr<nsISettingsService> settingsService =
- do_GetService("@mozilla.org/settingsService;1");
- if (!settingsService) {
- ERR("Failed to get settingsLock service!");
- return;
- }
- nsCOMPtr<nsISettingsServiceLock> lock;
- settingsService->CreateLock(nullptr, getter_AddRefs(lock));
- nsCOMPtr<nsISettingsServiceCallback> callback = new SettingsServiceCallback();
- JS::Rooted<JS::Value> value(RootingCx());
- value.setInt32(AUTOMOUNTER_DISABLE);
- lock->Set(UMS_MODE, value, callback, nullptr);
- value.setInt32(mStatus);
- lock->Set(UMS_STATUS, value, nullptr, nullptr);
-}
-
-AutoMounterSetting::~AutoMounterSetting()
-{
- nsCOMPtr<nsIObserverService> observerService =
- mozilla::services::GetObserverService();
- if (observerService) {
- observerService->RemoveObserver(this, MOZSETTINGS_CHANGED);
- }
-}
-
-NS_IMPL_ISUPPORTS(AutoMounterSetting, nsIObserver)
-
-const char *
-AutoMounterSetting::StatusStr(int32_t aStatus)
-{
- switch (aStatus) {
- case AUTOMOUNTER_STATUS_DISABLED: return "Disabled";
- case AUTOMOUNTER_STATUS_ENABLED: return "Enabled";
- case AUTOMOUNTER_STATUS_FILES_OPEN: return "FilesOpen";
- }
- return "??? Unknown ???";
-}
-
-class CheckVolumeSettingsRunnable : public Runnable
-{
-public:
- CheckVolumeSettingsRunnable(const nsACString& aVolumeName)
- : mVolumeName(aVolumeName) {}
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
- nsCOMPtr<nsISettingsService> settingsService =
- do_GetService("@mozilla.org/settingsService;1");
- NS_ENSURE_TRUE(settingsService, NS_ERROR_FAILURE);
- nsCOMPtr<nsISettingsServiceLock> lock;
- settingsService->CreateLock(nullptr, getter_AddRefs(lock));
- nsCOMPtr<nsISettingsServiceCallback> callback =
- new CheckVolumeSettingsCallback(mVolumeName);
- nsPrintfCString setting(UMS_VOLUME_ENABLED_PREFIX "%s" UMS_VOLUME_ENABLED_SUFFIX,
- mVolumeName.get());
- lock->Get(setting.get(), callback);
- return NS_OK;
- }
-
-private:
- nsCString mVolumeName;
-};
-
-//static
-void
-AutoMounterSetting::CheckVolumeSettings(const nsACString& aVolumeName)
-{
- NS_DispatchToMainThread(new CheckVolumeSettingsRunnable(aVolumeName));
-}
-
-class SetStatusRunnable : public Runnable
-{
-public:
- SetStatusRunnable(int32_t aStatus) : mStatus(aStatus) {}
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
- nsCOMPtr<nsISettingsService> settingsService =
- do_GetService("@mozilla.org/settingsService;1");
- NS_ENSURE_TRUE(settingsService, NS_ERROR_FAILURE);
- nsCOMPtr<nsISettingsServiceLock> lock;
- settingsService->CreateLock(nullptr, getter_AddRefs(lock));
- // lock may be null if this gets called during shutdown.
- if (lock) {
- JS::Rooted<JS::Value> value(RootingCx(),
- JS::Int32Value(mStatus));
- lock->Set(UMS_STATUS, value, nullptr, nullptr);
- }
- return NS_OK;
- }
-
-private:
- int32_t mStatus;
-};
-
-//static
-void
-AutoMounterSetting::SetStatus(int32_t aStatus)
-{
- if (aStatus != mStatus) {
- LOG("Changing status from '%s' to '%s'",
- StatusStr(mStatus), StatusStr(aStatus));
- mStatus = aStatus;
- NS_DispatchToMainThread(new SetStatusRunnable(aStatus));
- }
-}
-
-NS_IMETHODIMP
-AutoMounterSetting::Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData)
-{
- if (strcmp(aTopic, MOZSETTINGS_CHANGED) != 0) {
- return NS_OK;
- }
-
- // Note that this function gets called for any and all settings changes,
- // so we need to carefully check if we have the one we're interested in.
- //
- // The string that we're interested in will be a JSON string that looks like:
- // {"key":"ums.autoMount","value":true}
-
- RootedDictionary<SettingChangeNotification> setting(RootingCx());
- if (!WrappedJSToDictionary(aSubject, setting)) {
- return NS_OK;
- }
-
- // Check for ums.mode changes
- if (setting.mKey.EqualsASCII(UMS_MODE)) {
- if (!setting.mValue.isInt32()) {
- return NS_OK;
- }
- int32_t mode = setting.mValue.toInt32();
- SetAutoMounterMode(mode);
- return NS_OK;
- }
-
- // Check for ums.volume.NAME.enabled
- if (StringBeginsWith(setting.mKey, NS_LITERAL_STRING(UMS_VOLUME_ENABLED_PREFIX)) &&
- StringEndsWith(setting.mKey, NS_LITERAL_STRING(UMS_VOLUME_ENABLED_SUFFIX))) {
- if (!setting.mValue.isBoolean()) {
- return NS_OK;
- }
- const size_t prefixLen = sizeof(UMS_VOLUME_ENABLED_PREFIX) - 1;
- const size_t suffixLen = sizeof(UMS_VOLUME_ENABLED_SUFFIX) - 1;
- nsDependentSubstring volumeName =
- Substring(setting.mKey, prefixLen, setting.mKey.Length() - prefixLen - suffixLen);
- bool isSharingEnabled = setting.mValue.toBoolean();
- SetAutoMounterSharingMode(NS_LossyConvertUTF16toASCII(volumeName), isSharingEnabled);
- return NS_OK;
- }
-
- return NS_OK;
-}
-
-} // namespace system
-} // namespace mozilla
diff --git a/dom/system/gonk/AutoMounterSetting.h b/dom/system/gonk/AutoMounterSetting.h
deleted file mode 100644
index 7972de379..000000000
--- a/dom/system/gonk/AutoMounterSetting.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_automountersetting_h__
-#define mozilla_system_automountersetting_h__
-
-#include "nsIObserver.h"
-
-namespace mozilla {
-namespace system {
-
-class AutoMounterSetting : public nsIObserver
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIOBSERVER
-
- AutoMounterSetting();
-
- static void CheckVolumeSettings(const nsACString& aVolumeName);
-
- int32_t GetStatus() { return mStatus; }
- void SetStatus(int32_t aStatus);
- const char *StatusStr(int32_t aStatus);
-
-protected:
- virtual ~AutoMounterSetting();
-
-private:
- int32_t mStatus;
-};
-
-} // namespace system
-} // namespace mozilla
-
-#endif // mozilla_system_automountersetting_h__
-
diff --git a/dom/system/gonk/DataCallInterfaceService.js b/dom/system/gonk/DataCallInterfaceService.js
deleted file mode 100644
index 0f0e7101c..000000000
--- a/dom/system/gonk/DataCallInterfaceService.js
+++ /dev/null
@@ -1,276 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-const DATACALLINTERFACE_CONTRACTID = "@mozilla.org/datacall/interface;1";
-const DATACALLINTERFACESERVICE_CONTRACTID =
- "@mozilla.org/datacall/interfaceservice;1";
-const DATACALLINTERFACE_CID =
- Components.ID("{ff669306-4390-462a-989b-ba37fc42153f}");
-const DATACALLINTERFACESERVICE_CID =
- Components.ID("{e23e9337-592d-40b9-8cef-7bd47c28b72e}");
-
-const TOPIC_XPCOM_SHUTDOWN = "xpcom-shutdown";
-const TOPIC_PREF_CHANGED = "nsPref:changed";
-const PREF_RIL_DEBUG_ENABLED = "ril.debugging.enabled";
-
-XPCOMUtils.defineLazyGetter(this, "RIL", function () {
- let obj = {};
- Cu.import("resource://gre/modules/ril_consts.js", obj);
- return obj;
-});
-
-XPCOMUtils.defineLazyServiceGetter(this, "gRil",
- "@mozilla.org/ril;1",
- "nsIRadioInterfaceLayer");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileConnectionService",
- "@mozilla.org/mobileconnection/mobileconnectionservice;1",
- "nsIMobileConnectionService");
-
-var DEBUG = RIL.DEBUG_RIL;
-
-function updateDebugFlag() {
- // Read debug setting from pref
- let debugPref;
- try {
- debugPref = Services.prefs.getBoolPref(PREF_RIL_DEBUG_ENABLED);
- } catch (e) {
- debugPref = false;
- }
- DEBUG = debugPref || RIL.DEBUG_RIL;
-}
-updateDebugFlag();
-
-function DataCall(aAttributes) {
- for (let key in aAttributes) {
- if (key === "pdpType") {
- // Convert pdp type into constant int value.
- this[key] = RIL.RIL_DATACALL_PDP_TYPES.indexOf(aAttributes[key]);
- continue;
- }
-
- this[key] = aAttributes[key];
- }
-}
-DataCall.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCall]),
-
- failCause: Ci.nsIDataCallInterface.DATACALL_FAIL_NONE,
- suggestedRetryTime: -1,
- cid: -1,
- active: -1,
- pdpType: -1,
- ifname: null,
- addreses: null,
- dnses: null,
- gateways: null,
- pcscf: null,
- mtu: -1
-};
-
-function DataCallInterfaceService() {
- this._dataCallInterfaces = [];
-
- let numClients = gRil.numRadioInterfaces;
- for (let i = 0; i < numClients; i++) {
- this._dataCallInterfaces.push(new DataCallInterface(i));
- }
-
- Services.obs.addObserver(this, TOPIC_XPCOM_SHUTDOWN, false);
- Services.prefs.addObserver(PREF_RIL_DEBUG_ENABLED, this, false);
-}
-DataCallInterfaceService.prototype = {
- classID: DATACALLINTERFACESERVICE_CID,
- classInfo: XPCOMUtils.generateCI({
- classID: DATACALLINTERFACESERVICE_CID,
- contractID: DATACALLINTERFACESERVICE_CONTRACTID,
- classDescription: "Data Call Interface Service",
- interfaces: [Ci.nsIDataCallInterfaceService,
- Ci.nsIGonkDataCallInterfaceService]
- }),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallInterfaceService,
- Ci.nsIGonkDataCallInterfaceService],
- Ci.nsIObserver),
-
- // An array of DataCallInterface instances.
- _dataCallInterfaces: null,
-
- debug: function(aMessage) {
- dump("-*- DataCallInterfaceService: " + aMessage + "\n");
- },
-
- // nsIDataCallInterfaceService
-
- getDataCallInterface: function(aClientId) {
- let dataCallInterface = this._dataCallInterfaces[aClientId];
- if (!dataCallInterface) {
- throw Cr.NS_ERROR_UNEXPECTED;
- }
-
- return dataCallInterface;
- },
-
- // nsIGonkDataCallInterfaceService
-
- notifyDataCallListChanged: function(aClientId, aCount, aDataCalls) {
- let dataCallInterface = this.getDataCallInterface(aClientId);
- dataCallInterface.handleDataCallListChanged(aCount, aDataCalls);
- },
-
- // nsIObserver
-
- observe: function(aSubject, aTopic, aData) {
- switch (aTopic) {
- case TOPIC_PREF_CHANGED:
- if (aData === PREF_RIL_DEBUG_ENABLED) {
- updateDebugFlag();
- }
- break;
- case TOPIC_XPCOM_SHUTDOWN:
- Services.prefs.removeObserver(PREF_RIL_DEBUG_ENABLED, this);
- Services.obs.removeObserver(this, TOPIC_XPCOM_SHUTDOWN);
- break;
- }
- },
-};
-
-function DataCallInterface(aClientId) {
- this._clientId = aClientId;
- this._radioInterface = gRil.getRadioInterface(aClientId);
- this._listeners = [];
-
- if (DEBUG) this.debug("DataCallInterface: " + aClientId);
-}
-DataCallInterface.prototype = {
- classID: DATACALLINTERFACE_CID,
- classInfo: XPCOMUtils.generateCI({classID: DATACALLINTERFACE_CID,
- contractID: DATACALLINTERFACE_CONTRACTID,
- classDescription: "Data Call Interface",
- interfaces: [Ci.nsIDataCallInterface]}),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallInterface]),
-
- debug: function(aMessage) {
- dump("-*- DataCallInterface[" + this._clientId + "]: " + aMessage + "\n");
- },
-
- _clientId: -1,
-
- _radioInterface: null,
-
- _listeners: null,
-
- // nsIDataCallInterface
-
- setupDataCall: function(aApn, aUsername, aPassword, aAuthType, aPdpType,
- aCallback) {
- let connection =
- gMobileConnectionService.getItemByServiceId(this._clientId);
- let dataInfo = connection && connection.data;
- let radioTechType = dataInfo.type;
- let radioTechnology = RIL.GECKO_RADIO_TECH.indexOf(radioTechType);
- // Convert pdp type into string value.
- let pdpType = RIL.RIL_DATACALL_PDP_TYPES[aPdpType];
-
- this._radioInterface.sendWorkerMessage("setupDataCall", {
- radioTech: radioTechnology,
- apn: aApn,
- user: aUsername,
- passwd: aPassword,
- chappap: aAuthType,
- pdptype: pdpType
- }, (aResponse) => {
- if (aResponse.errorMsg) {
- aCallback.notifyError(aResponse.errorMsg);
- } else {
- let dataCall = new DataCall(aResponse);
- aCallback.notifySetupDataCallSuccess(dataCall);
- }
- });
- },
-
- deactivateDataCall: function(aCid, aReason, aCallback) {
- this._radioInterface.sendWorkerMessage("deactivateDataCall", {
- cid: aCid,
- reason: aReason
- }, (aResponse) => {
- if (aResponse.errorMsg) {
- aCallback.notifyError(aResponse.errorMsg);
- } else {
- aCallback.notifySuccess();
- }
- });
- },
-
- getDataCallList: function(aCallback) {
- this._radioInterface.sendWorkerMessage("getDataCallList", null,
- (aResponse) => {
- if (aResponse.errorMsg) {
- aCallback.notifyError(aResponse.errorMsg);
- } else {
- let dataCalls = aResponse.datacalls.map(
- dataCall => new DataCall(dataCall));
- aCallback.notifyGetDataCallListSuccess(dataCalls.length, dataCalls);
- }
- });
- },
-
- setDataRegistration: function(aAttach, aCallback) {
- this._radioInterface.sendWorkerMessage("setDataRegistration", {
- attach: aAttach
- }, (aResponse) => {
- if (aResponse.errorMsg) {
- aCallback.notifyError(aResponse.errorMsg);
- } else {
- aCallback.notifySuccess();
- }
- });
- },
-
- handleDataCallListChanged: function(aCount, aDataCalls) {
- this._notifyAllListeners("notifyDataCallListChanged", [aCount, aDataCalls]);
- },
-
- _notifyAllListeners: function(aMethodName, aArgs) {
- let listeners = this._listeners.slice();
- for (let listener of listeners) {
- if (this._listeners.indexOf(listener) == -1) {
- // Listener has been unregistered in previous run.
- continue;
- }
-
- let handler = listener[aMethodName];
- try {
- handler.apply(listener, aArgs);
- } catch (e) {
- if (DEBUG) {
- this.debug("listener for " + aMethodName + " threw an exception: " + e);
- }
- }
- }
- },
-
- registerListener: function(aListener) {
- if (this._listeners.indexOf(aListener) >= 0) {
- return;
- }
-
- this._listeners.push(aListener);
- },
-
- unregisterListener: function(aListener) {
- let index = this._listeners.indexOf(aListener);
- if (index >= 0) {
- this._listeners.splice(index, 1);
- }
- },
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([DataCallInterfaceService]); \ No newline at end of file
diff --git a/dom/system/gonk/DataCallInterfaceService.manifest b/dom/system/gonk/DataCallInterfaceService.manifest
deleted file mode 100644
index bf062c7e9..000000000
--- a/dom/system/gonk/DataCallInterfaceService.manifest
+++ /dev/null
@@ -1,6 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-component {e23e9337-592d-40b9-8cef-7bd47c28b72e} DataCallInterfaceService.js
-contract @mozilla.org/datacall/interfaceservice;1 {e23e9337-592d-40b9-8cef-7bd47c28b72e} \ No newline at end of file
diff --git a/dom/system/gonk/DataCallManager.js b/dom/system/gonk/DataCallManager.js
deleted file mode 100644
index 5411987cd..000000000
--- a/dom/system/gonk/DataCallManager.js
+++ /dev/null
@@ -1,1726 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
- "@mozilla.org/settingsService;1",
- "nsISettingsService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
- "@mozilla.org/network/manager;1",
- "nsINetworkManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileConnectionService",
- "@mozilla.org/mobileconnection/mobileconnectionservice;1",
- "nsIMobileConnectionService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gIccService",
- "@mozilla.org/icc/iccservice;1",
- "nsIIccService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gDataCallInterfaceService",
- "@mozilla.org/datacall/interfaceservice;1",
- "nsIDataCallInterfaceService");
-
-XPCOMUtils.defineLazyGetter(this, "RIL", function() {
- let obj = {};
- Cu.import("resource://gre/modules/ril_consts.js", obj);
- return obj;
-});
-
-// Ril quirk to attach data registration on demand.
-var RILQUIRKS_DATA_REGISTRATION_ON_DEMAND =
- libcutils.property_get("ro.moz.ril.data_reg_on_demand", "false") == "true";
-
-// Ril quirk to control the uicc/data subscription.
-var RILQUIRKS_SUBSCRIPTION_CONTROL =
- libcutils.property_get("ro.moz.ril.subscription_control", "false") == "true";
-
-// Ril quirk to enable IPv6 protocol/roaming protocol in APN settings.
-var RILQUIRKS_HAVE_IPV6 =
- libcutils.property_get("ro.moz.ril.ipv6", "false") == "true";
-
-const DATACALLMANAGER_CID =
- Components.ID("{35b9efa2-e42c-45ce-8210-0a13e6f4aadc}");
-const DATACALLHANDLER_CID =
- Components.ID("{132b650f-c4d8-4731-96c5-83785cb31dee}");
-const RILNETWORKINTERFACE_CID =
- Components.ID("{9574ee84-5d0d-4814-b9e6-8b279e03dcf4}");
-const RILNETWORKINFO_CID =
- Components.ID("{dd6cf2f0-f0e3-449f-a69e-7c34fdcb8d4b}");
-
-const TOPIC_XPCOM_SHUTDOWN = "xpcom-shutdown";
-const TOPIC_MOZSETTINGS_CHANGED = "mozsettings-changed";
-const TOPIC_PREF_CHANGED = "nsPref:changed";
-const TOPIC_DATA_CALL_ERROR = "data-call-error";
-const PREF_RIL_DEBUG_ENABLED = "ril.debugging.enabled";
-
-const NETWORK_TYPE_UNKNOWN = Ci.nsINetworkInfo.NETWORK_TYPE_UNKNOWN;
-const NETWORK_TYPE_WIFI = Ci.nsINetworkInfo.NETWORK_TYPE_WIFI;
-const NETWORK_TYPE_MOBILE = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE;
-const NETWORK_TYPE_MOBILE_MMS = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS;
-const NETWORK_TYPE_MOBILE_SUPL = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_SUPL;
-const NETWORK_TYPE_MOBILE_IMS = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_IMS;
-const NETWORK_TYPE_MOBILE_DUN = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN;
-const NETWORK_TYPE_MOBILE_FOTA = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_FOTA;
-
-const NETWORK_STATE_UNKNOWN = Ci.nsINetworkInfo.NETWORK_STATE_UNKNOWN;
-const NETWORK_STATE_CONNECTING = Ci.nsINetworkInfo.NETWORK_STATE_CONNECTING;
-const NETWORK_STATE_CONNECTED = Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED;
-const NETWORK_STATE_DISCONNECTING = Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTING;
-const NETWORK_STATE_DISCONNECTED = Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED;
-
-const INT32_MAX = 2147483647;
-
-// set to true in ril_consts.js to see debug messages
-var DEBUG = RIL.DEBUG_RIL;
-
-function updateDebugFlag() {
- // Read debug setting from pref
- let debugPref;
- try {
- debugPref = Services.prefs.getBoolPref(PREF_RIL_DEBUG_ENABLED);
- } catch (e) {
- debugPref = false;
- }
- DEBUG = debugPref || RIL.DEBUG_RIL;
-}
-updateDebugFlag();
-
-function DataCallManager() {
- this._connectionHandlers = [];
-
- let numRadioInterfaces = gMobileConnectionService.numItems;
- for (let clientId = 0; clientId < numRadioInterfaces; clientId++) {
- this._connectionHandlers.push(new DataCallHandler(clientId));
- }
-
- let lock = gSettingsService.createLock();
- // Read the APN data from the settings DB.
- lock.get("ril.data.apnSettings", this);
- // Read the data enabled setting from DB.
- lock.get("ril.data.enabled", this);
- lock.get("ril.data.roaming_enabled", this);
- // Read the default client id for data call.
- lock.get("ril.data.defaultServiceId", this);
-
- Services.obs.addObserver(this, TOPIC_XPCOM_SHUTDOWN, false);
- Services.obs.addObserver(this, TOPIC_MOZSETTINGS_CHANGED, false);
- Services.prefs.addObserver(PREF_RIL_DEBUG_ENABLED, this, false);
-}
-DataCallManager.prototype = {
- classID: DATACALLMANAGER_CID,
- classInfo: XPCOMUtils.generateCI({classID: DATACALLMANAGER_CID,
- classDescription: "Data Call Manager",
- interfaces: [Ci.nsIDataCallManager]}),
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallManager,
- Ci.nsIObserver,
- Ci.nsISettingsServiceCallback]),
-
- _connectionHandlers: null,
-
- // Flag to determine the data state to start with when we boot up. It
- // corresponds to the 'ril.data.enabled' setting from the UI.
- _dataEnabled: false,
-
- // Flag to record the default client id for data call. It corresponds to
- // the 'ril.data.defaultServiceId' setting from the UI.
- _dataDefaultClientId: -1,
-
- // Flag to record the current default client id for data call.
- // It differs from _dataDefaultClientId in that it is set only when
- // the switch of client id process is done.
- _currentDataClientId: -1,
-
- // Pending function to execute when we are notified that another data call has
- // been disconnected.
- _pendingDataCallRequest: null,
-
- debug: function(aMsg) {
- dump("-*- DataCallManager: " + aMsg + "\n");
- },
-
- get dataDefaultServiceId() {
- return this._dataDefaultClientId;
- },
-
- getDataCallHandler: function(aClientId) {
- let handler = this._connectionHandlers[aClientId]
- if (!handler) {
- throw Cr.NS_ERROR_UNEXPECTED;
- }
-
- return handler;
- },
-
- _setDataRegistration: function(aDataCallInterface, aAttach) {
- return new Promise(function(aResolve, aReject) {
- let callback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallCallback]),
- notifySuccess: function() {
- aResolve();
- },
- notifyError: function(aErrorMsg) {
- aReject(aErrorMsg);
- }
- };
-
- aDataCallInterface.setDataRegistration(aAttach, callback);
- });
- },
-
- _handleDataClientIdChange: function(aNewClientId) {
- if (this._dataDefaultClientId === aNewClientId) {
- return;
- }
- this._dataDefaultClientId = aNewClientId;
-
- // This is to handle boot up stage.
- if (this._currentDataClientId == -1) {
- this._currentDataClientId = this._dataDefaultClientId;
- let connHandler = this._connectionHandlers[this._currentDataClientId];
- let dcInterface = connHandler.dataCallInterface;
- if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND ||
- RILQUIRKS_SUBSCRIPTION_CONTROL) {
- this._setDataRegistration(dcInterface, true);
- }
- if (this._dataEnabled) {
- let settings = connHandler.dataCallSettings;
- settings.oldEnabled = settings.enabled;
- settings.enabled = true;
- connHandler.updateRILNetworkInterface();
- }
- return;
- }
-
- let oldConnHandler = this._connectionHandlers[this._currentDataClientId];
- let oldIface = oldConnHandler.dataCallInterface;
- let oldSettings = oldConnHandler.dataCallSettings;
- let newConnHandler = this._connectionHandlers[this._dataDefaultClientId];
- let newIface = newConnHandler.dataCallInterface;
- let newSettings = newConnHandler.dataCallSettings;
-
- let applyPendingDataSettings = () => {
- if (DEBUG) {
- this.debug("Apply pending data registration and settings.");
- }
-
- if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND ||
- RILQUIRKS_SUBSCRIPTION_CONTROL) {
- this._setDataRegistration(oldIface, false).then(() => {
- if (this._dataEnabled) {
- newSettings.oldEnabled = newSettings.enabled;
- newSettings.enabled = true;
- }
- this._currentDataClientId = this._dataDefaultClientId;
-
- this._setDataRegistration(newIface, true).then(() => {
- newConnHandler.updateRILNetworkInterface();
- });
- });
- return;
- }
-
- if (this._dataEnabled) {
- newSettings.oldEnabled = newSettings.enabled;
- newSettings.enabled = true;
- }
-
- this._currentDataClientId = this._dataDefaultClientId;
- newConnHandler.updateRILNetworkInterface();
- };
-
- if (this._dataEnabled) {
- oldSettings.oldEnabled = oldSettings.enabled;
- oldSettings.enabled = false;
- }
-
- oldConnHandler.deactivateDataCallsAndWait().then(() => {
- applyPendingDataSettings();
- });
- },
-
- _shutdown: function() {
- for (let handler of this._connectionHandlers) {
- handler.shutdown();
- }
- this._connectionHandlers = null;
- Services.prefs.removeObserver(PREF_RIL_DEBUG_ENABLED, this);
- Services.obs.removeObserver(this, TOPIC_XPCOM_SHUTDOWN);
- Services.obs.removeObserver(this, TOPIC_MOZSETTINGS_CHANGED);
- },
-
- /**
- * nsISettingsServiceCallback
- */
- handle: function(aName, aResult) {
- switch (aName) {
- case "ril.data.apnSettings":
- if (DEBUG) {
- this.debug("'ril.data.apnSettings' is now " +
- JSON.stringify(aResult));
- }
- if (!aResult) {
- break;
- }
- for (let clientId in this._connectionHandlers) {
- let handler = this._connectionHandlers[clientId];
- let apnSetting = aResult[clientId];
- if (handler && apnSetting) {
- handler.updateApnSettings(apnSetting);
- }
- }
- break;
- case "ril.data.enabled":
- if (DEBUG) {
- this.debug("'ril.data.enabled' is now " + aResult);
- }
- if (this._dataEnabled === aResult) {
- break;
- }
- this._dataEnabled = aResult;
-
- if (DEBUG) {
- this.debug("Default id for data call: " + this._dataDefaultClientId);
- }
- if (this._dataDefaultClientId === -1) {
- // We haven't got the default id for data from db.
- break;
- }
-
- let connHandler = this._connectionHandlers[this._dataDefaultClientId];
- let settings = connHandler.dataCallSettings;
- settings.oldEnabled = settings.enabled;
- settings.enabled = aResult;
- connHandler.updateRILNetworkInterface();
- break;
- case "ril.data.roaming_enabled":
- if (DEBUG) {
- this.debug("'ril.data.roaming_enabled' is now " + aResult);
- this.debug("Default id for data call: " + this._dataDefaultClientId);
- }
- for (let clientId = 0; clientId < this._connectionHandlers.length; clientId++) {
- let connHandler = this._connectionHandlers[clientId];
- let settings = connHandler.dataCallSettings;
- settings.roamingEnabled = Array.isArray(aResult) ? aResult[clientId]
- : aResult;
- }
- if (this._dataDefaultClientId === -1) {
- // We haven't got the default id for data from db.
- break;
- }
- this._connectionHandlers[this._dataDefaultClientId].updateRILNetworkInterface();
- break;
- case "ril.data.defaultServiceId":
- aResult = aResult || 0;
- if (DEBUG) {
- this.debug("'ril.data.defaultServiceId' is now " + aResult);
- }
- this._handleDataClientIdChange(aResult);
- break;
- }
- },
-
- handleError: function(aErrorMessage) {
- if (DEBUG) {
- this.debug("There was an error while reading RIL settings.");
- }
- },
-
- /**
- * nsIObserver interface methods.
- */
- observe: function(aSubject, aTopic, aData) {
- switch (aTopic) {
- case TOPIC_MOZSETTINGS_CHANGED:
- if ("wrappedJSObject" in aSubject) {
- aSubject = aSubject.wrappedJSObject;
- }
- this.handle(aSubject.key, aSubject.value);
- break;
- case TOPIC_PREF_CHANGED:
- if (aData === PREF_RIL_DEBUG_ENABLED) {
- updateDebugFlag();
- }
- break;
- case TOPIC_XPCOM_SHUTDOWN:
- this._shutdown();
- break;
- }
- },
-};
-
-function DataCallHandler(aClientId) {
- // Initial owning attributes.
- this.clientId = aClientId;
- this.dataCallSettings = {
- oldEnabled: false,
- enabled: false,
- roamingEnabled: false
- };
- this._dataCalls = [];
- this._listeners = [];
-
- // This map is used to collect all the apn types and its corresponding
- // RILNetworkInterface.
- this.dataNetworkInterfaces = new Map();
-
- this.dataCallInterface = gDataCallInterfaceService.getDataCallInterface(aClientId);
- this.dataCallInterface.registerListener(this);
-
- let mobileConnection = gMobileConnectionService.getItemByServiceId(aClientId);
- mobileConnection.registerListener(this);
-
- this._dataInfo = {
- state: mobileConnection.data.state,
- type: mobileConnection.data.type,
- roaming: mobileConnection.data.roaming
- }
-}
-DataCallHandler.prototype = {
- classID: DATACALLHANDLER_CID,
- classInfo: XPCOMUtils.generateCI({classID: DATACALLHANDLER_CID,
- classDescription: "Data Call Handler",
- interfaces: [Ci.nsIDataCallHandler]}),
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallHandler,
- Ci.nsIDataCallInterfaceListener,
- Ci.nsIMobileConnectionListener]),
-
- clientId: 0,
- dataCallInterface: null,
- dataCallSettings: null,
- dataNetworkInterfaces: null,
- _dataCalls: null,
- _dataInfo: null,
-
- // Apn settings to be setup after data call are cleared.
- _pendingApnSettings: null,
-
- debug: function(aMsg) {
- dump("-*- DataCallHandler[" + this.clientId + "]: " + aMsg + "\n");
- },
-
- shutdown: function() {
- // Shutdown all RIL network interfaces
- this.dataNetworkInterfaces.forEach(function(networkInterface) {
- gNetworkManager.unregisterNetworkInterface(networkInterface);
- networkInterface.shutdown();
- networkInterface = null;
- });
- this.dataNetworkInterfaces.clear();
- this._dataCalls = [];
- this.clientId = null;
-
- this.dataCallInterface.unregisterListener(this);
- this.dataCallInterface = null;
-
- let mobileConnection =
- gMobileConnectionService.getItemByServiceId(this.clientId);
- mobileConnection.unregisterListener(this);
- },
-
- /**
- * Check if we get all necessary APN data.
- */
- _validateApnSetting: function(aApnSetting) {
- return (aApnSetting &&
- aApnSetting.apn &&
- aApnSetting.types &&
- aApnSetting.types.length);
- },
-
- _convertApnType: function(aApnType) {
- switch (aApnType) {
- case "default":
- return NETWORK_TYPE_MOBILE;
- case "mms":
- return NETWORK_TYPE_MOBILE_MMS;
- case "supl":
- return NETWORK_TYPE_MOBILE_SUPL;
- case "ims":
- return NETWORK_TYPE_MOBILE_IMS;
- case "dun":
- return NETWORK_TYPE_MOBILE_DUN;
- case "fota":
- return NETWORK_TYPE_MOBILE_FOTA;
- default:
- return NETWORK_TYPE_UNKNOWN;
- }
- },
-
- _compareDataCallOptions: function(aDataCall, aNewDataCall) {
- return aDataCall.apnProfile.apn == aNewDataCall.apnProfile.apn &&
- aDataCall.apnProfile.user == aNewDataCall.apnProfile.user &&
- aDataCall.apnProfile.password == aNewDataCall.apnProfile.passwd &&
- aDataCall.apnProfile.authType == aNewDataCall.apnProfile.authType &&
- aDataCall.apnProfile.protocol == aNewDataCall.apnProfile.protocol &&
- aDataCall.apnProfile.roaming_protocol == aNewDataCall.apnProfile.roaming_protocol;
- },
-
- /**
- * This function will do the following steps:
- * 1. Clear the cached APN settings in the RIL.
- * 2. Combine APN, user name, and password as the key of |byApn| object to
- * refer to the corresponding APN setting.
- * 3. Use APN type as the index of |byType| object to refer to the
- * corresponding APN setting.
- * 4. Create RilNetworkInterface for each APN setting created at step 2.
- */
- _setupApnSettings: function(aNewApnSettings) {
- if (!aNewApnSettings) {
- return;
- }
- if (DEBUG) this.debug("setupApnSettings: " + JSON.stringify(aNewApnSettings));
-
- // Shutdown all network interfaces and clear data calls.
- this.dataNetworkInterfaces.forEach(function(networkInterface) {
- gNetworkManager.unregisterNetworkInterface(networkInterface);
- networkInterface.shutdown();
- networkInterface = null;
- });
- this.dataNetworkInterfaces.clear();
- this._dataCalls = [];
-
- // Cache the APN settings by APNs and by types in the RIL.
- for (let inputApnSetting of aNewApnSettings) {
- if (!this._validateApnSetting(inputApnSetting)) {
- continue;
- }
-
- // Use APN type as the key of dataNetworkInterfaces to refer to the
- // corresponding RILNetworkInterface.
- for (let i = 0; i < inputApnSetting.types.length; i++) {
- let apnType = inputApnSetting.types[i];
- let networkType = this._convertApnType(apnType);
- if (networkType === NETWORK_TYPE_UNKNOWN) {
- if (DEBUG) this.debug("Invalid apn type: " + apnType);
- continue;
- }
-
- if (DEBUG) this.debug("Preparing RILNetworkInterface for type: " + apnType);
- // Create DataCall for RILNetworkInterface or reuse one that is shareable.
- let dataCall;
- for (let i = 0; i < this._dataCalls.length; i++) {
- if (this._dataCalls[i].canHandleApn(inputApnSetting)) {
- if (DEBUG) this.debug("Found shareable DataCall, reusing it.");
- dataCall = this._dataCalls[i];
- break;
- }
- }
-
- if (!dataCall) {
- if (DEBUG) this.debug("No shareable DataCall found, creating one.");
- dataCall = new DataCall(this.clientId, inputApnSetting, this);
- this._dataCalls.push(dataCall);
- }
-
- try {
- let networkInterface = new RILNetworkInterface(this, networkType,
- inputApnSetting,
- dataCall);
- gNetworkManager.registerNetworkInterface(networkInterface);
- this.dataNetworkInterfaces.set(networkType, networkInterface);
- } catch (e) {
- if (DEBUG) {
- this.debug("Error setting up RILNetworkInterface for type " +
- apnType + ": " + e);
- }
- }
- }
- }
- },
-
- /**
- * Check if all data is disconnected.
- */
- allDataDisconnected: function() {
- for (let i = 0; i < this._dataCalls.length; i++) {
- let dataCall = this._dataCalls[i];
- if (dataCall.state != NETWORK_STATE_UNKNOWN &&
- dataCall.state != NETWORK_STATE_DISCONNECTED) {
- return false;
- }
- }
- return true;
- },
-
- deactivateDataCallsAndWait: function() {
- return new Promise((aResolve, aReject) => {
- this.deactivateDataCalls({
- notifyDataCallsDisconnected: function() {
- aResolve();
- }
- });
- });
- },
-
- updateApnSettings: function(aNewApnSettings) {
- if (!aNewApnSettings) {
- return;
- }
- if (this._pendingApnSettings) {
- // Change of apn settings in process, just update to the newest.
- this._pengingApnSettings = aNewApnSettings;
- return;
- }
-
- this._pendingApnSettings = aNewApnSettings;
- this.deactivateDataCallsAndWait().then(() => {
- this._setupApnSettings(this._pendingApnSettings);
- this._pendingApnSettings = null;
- this.updateRILNetworkInterface();
- });
- },
-
- updateRILNetworkInterface: function() {
- let networkInterface = this.dataNetworkInterfaces.get(NETWORK_TYPE_MOBILE);
- if (!networkInterface) {
- if (DEBUG) {
- this.debug("No network interface for default data.");
- }
- return;
- }
-
- let connection =
- gMobileConnectionService.getItemByServiceId(this.clientId);
-
- // This check avoids data call connection if the radio is not ready
- // yet after toggling off airplane mode.
- let radioState = connection && connection.radioState;
- if (radioState != Ci.nsIMobileConnection.MOBILE_RADIO_STATE_ENABLED) {
- if (DEBUG) {
- this.debug("RIL is not ready for data connection: radio's not ready");
- }
- return;
- }
-
- // We only watch at "ril.data.enabled" flag changes for connecting or
- // disconnecting the data call. If the value of "ril.data.enabled" is
- // true and any of the remaining flags change the setting application
- // should turn this flag to false and then to true in order to reload
- // the new values and reconnect the data call.
- if (this.dataCallSettings.oldEnabled === this.dataCallSettings.enabled) {
- if (DEBUG) {
- this.debug("No changes for ril.data.enabled flag. Nothing to do.");
- }
- return;
- }
-
- let dataInfo = connection && connection.data;
- let isRegistered =
- dataInfo &&
- dataInfo.state == RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED;
- let haveDataConnection =
- dataInfo &&
- dataInfo.type != RIL.GECKO_MOBILE_CONNECTION_STATE_UNKNOWN;
- if (!isRegistered || !haveDataConnection) {
- if (DEBUG) {
- this.debug("RIL is not ready for data connection: Phone's not " +
- "registered or doesn't have data connection.");
- }
- return;
- }
- let wifi_active = false;
- if (gNetworkManager.activeNetworkInfo &&
- gNetworkManager.activeNetworkInfo.type == NETWORK_TYPE_WIFI) {
- wifi_active = true;
- }
-
- let defaultDataCallConnected = networkInterface.connected;
-
- // We have moved part of the decision making into DataCall, the rest will be
- // moved after Bug 904514 - [meta] NetworkManager enhancement.
- if (networkInterface.enabled &&
- (!this.dataCallSettings.enabled ||
- (dataInfo.roaming && !this.dataCallSettings.roamingEnabled))) {
- if (DEBUG) {
- this.debug("Data call settings: disconnect data call.");
- }
- networkInterface.disconnect();
- return;
- }
-
- if (networkInterface.enabled && wifi_active) {
- if (DEBUG) {
- this.debug("Disconnect data call when Wifi is connected.");
- }
- networkInterface.disconnect();
- return;
- }
-
- if (!this.dataCallSettings.enabled || defaultDataCallConnected) {
- if (DEBUG) {
- this.debug("Data call settings: nothing to do.");
- }
- return;
- }
- if (dataInfo.roaming && !this.dataCallSettings.roamingEnabled) {
- if (DEBUG) {
- this.debug("We're roaming, but data roaming is disabled.");
- }
- return;
- }
- if (wifi_active) {
- if (DEBUG) {
- this.debug("Don't connect data call when Wifi is connected.");
- }
- return;
- }
- if (this._pendingApnSettings) {
- if (DEBUG) this.debug("We're changing apn settings, ignore any changes.");
- return;
- }
-
- if (this._deactivatingDataCalls) {
- if (DEBUG) this.debug("We're deactivating all data calls, ignore any changes.");
- return;
- }
-
- if (DEBUG) {
- this.debug("Data call settings: connect data call.");
- }
- networkInterface.connect();
- },
-
- _isMobileNetworkType: function(aNetworkType) {
- if (aNetworkType === NETWORK_TYPE_MOBILE ||
- aNetworkType === NETWORK_TYPE_MOBILE_MMS ||
- aNetworkType === NETWORK_TYPE_MOBILE_SUPL ||
- aNetworkType === NETWORK_TYPE_MOBILE_IMS ||
- aNetworkType === NETWORK_TYPE_MOBILE_DUN ||
- aNetworkType === NETWORK_TYPE_MOBILE_FOTA) {
- return true;
- }
-
- return false;
- },
-
- getDataCallStateByType: function(aNetworkType) {
- if (!this._isMobileNetworkType(aNetworkType)) {
- if (DEBUG) this.debug(aNetworkType + " is not a mobile network type!");
- throw Cr.NS_ERROR_INVALID_ARG;
- }
-
- let networkInterface = this.dataNetworkInterfaces.get(aNetworkType);
- if (!networkInterface) {
- return NETWORK_STATE_UNKNOWN;
- }
- return networkInterface.info.state;
- },
-
- setupDataCallByType: function(aNetworkType) {
- if (DEBUG) {
- this.debug("setupDataCallByType: " + aNetworkType);
- }
-
- if (!this._isMobileNetworkType(aNetworkType)) {
- if (DEBUG) this.debug(aNetworkType + " is not a mobile network type!");
- throw Cr.NS_ERROR_INVALID_ARG;
- }
-
- let networkInterface = this.dataNetworkInterfaces.get(aNetworkType);
- if (!networkInterface) {
- if (DEBUG) {
- this.debug("No network interface for type: " + aNetworkType);
- }
- return;
- }
-
- networkInterface.connect();
- },
-
- deactivateDataCallByType: function(aNetworkType) {
- if (DEBUG) {
- this.debug("deactivateDataCallByType: " + aNetworkType);
- }
-
- if (!this._isMobileNetworkType(aNetworkType)) {
- if (DEBUG) this.debug(aNetworkType + " is not a mobile network type!");
- throw Cr.NS_ERROR_INVALID_ARG;
- }
-
- let networkInterface = this.dataNetworkInterfaces.get(aNetworkType);
- if (!networkInterface) {
- if (DEBUG) {
- this.debug("No network interface for type: " + aNetworkType);
- }
- return;
- }
-
- networkInterface.disconnect();
- },
-
- _deactivatingDataCalls: false,
-
- deactivateDataCalls: function(aCallback) {
- let dataDisconnecting = false;
- this.dataNetworkInterfaces.forEach(function(networkInterface) {
- if (networkInterface.enabled) {
- if (networkInterface.info.state != NETWORK_STATE_UNKNOWN &&
- networkInterface.info.state != NETWORK_STATE_DISCONNECTED) {
- dataDisconnecting = true;
- }
- networkInterface.disconnect();
- }
- });
-
- this._deactivatingDataCalls = dataDisconnecting;
- if (!dataDisconnecting) {
- aCallback.notifyDataCallsDisconnected();
- return;
- }
-
- let callback = {
- notifyAllDataDisconnected: () => {
- this._unregisterListener(callback);
- aCallback.notifyDataCallsDisconnected();
- }
- };
- this._registerListener(callback);
- },
-
- _listeners: null,
-
- _notifyListeners: function(aMethodName, aArgs) {
- let listeners = this._listeners.slice();
- for (let listener of listeners) {
- if (this._listeners.indexOf(listener) == -1) {
- // Listener has been unregistered in previous run.
- continue;
- }
-
- let handler = listener[aMethodName];
- try {
- handler.apply(listener, aArgs);
- } catch (e) {
- this.debug("listener for " + aMethodName + " threw an exception: " + e);
- }
- }
- },
-
- _registerListener: function(aListener) {
- if (this._listeners.indexOf(aListener) >= 0) {
- return;
- }
-
- this._listeners.push(aListener);
- },
-
- _unregisterListener: function(aListener) {
- let index = this._listeners.indexOf(aListener);
- if (index >= 0) {
- this._listeners.splice(index, 1);
- }
- },
-
- _findDataCallByCid: function(aCid) {
- if (aCid === undefined || aCid < 0) {
- return -1;
- }
-
- for (let i = 0; i < this._dataCalls.length; i++) {
- let datacall = this._dataCalls[i];
- if (datacall.linkInfo.cid != null &&
- datacall.linkInfo.cid == aCid) {
- return i;
- }
- }
-
- return -1;
- },
-
- /**
- * Notify about data call setup error, called from DataCall.
- */
- notifyDataCallError: function(aDataCall, aErrorMsg) {
- // Notify data call error only for data APN
- let networkInterface = this.dataNetworkInterfaces.get(NETWORK_TYPE_MOBILE);
- if (networkInterface && networkInterface.enabled) {
- let dataCall = networkInterface.dataCall;
- if (this._compareDataCallOptions(dataCall, aDataCall)) {
- Services.obs.notifyObservers(networkInterface.info,
- TOPIC_DATA_CALL_ERROR, aErrorMsg);
- }
- }
- },
-
- /**
- * Notify about data call changed, called from DataCall.
- */
- notifyDataCallChanged: function(aUpdatedDataCall) {
- // Process pending radio power off request after all data calls
- // are disconnected.
- if (aUpdatedDataCall.state == NETWORK_STATE_DISCONNECTED ||
- aUpdatedDataCall.state == NETWORK_STATE_UNKNOWN &&
- this.allDataDisconnected() && this._deactivatingDataCalls) {
- this._deactivatingDataCalls = false;
- this._notifyListeners("notifyAllDataDisconnected", {
- clientId: this.clientId
- });
- }
- },
-
- // nsIDataCallInterfaceListener
-
- notifyDataCallListChanged: function(aCount, aDataCallList) {
- let currentDataCalls = this._dataCalls.slice();
- for (let i = 0; i < aDataCallList.length; i++) {
- let dataCall = aDataCallList[i];
- let index = this._findDataCallByCid(dataCall.cid);
- if (index == -1) {
- if (DEBUG) {
- this.debug("Unexpected new data call: " + JSON.stringify(dataCall));
- }
- continue;
- }
- currentDataCalls[index].onDataCallChanged(dataCall);
- currentDataCalls[index] = null;
- }
-
- // If there is any CONNECTED DataCall left in currentDataCalls, means that
- // it is missing in dataCallList, we should send a DISCONNECTED event to
- // notify about this.
- for (let i = 0; i < currentDataCalls.length; i++) {
- let currentDataCall = currentDataCalls[i];
- if (currentDataCall && currentDataCall.linkInfo.cid != null &&
- currentDataCall.state == NETWORK_STATE_CONNECTED) {
- if (DEBUG) {
- this.debug("Expected data call missing: " + JSON.stringify(
- currentDataCall.apnProfile) + ", must have been DISCONNECTED.");
- }
- currentDataCall.onDataCallChanged({
- state: NETWORK_STATE_DISCONNECTED
- });
- }
- }
- },
-
- // nsIMobileConnectionListener
-
- notifyVoiceChanged: function() {},
-
- notifyDataChanged: function () {
- let connection = gMobileConnectionService.getItemByServiceId(this.clientId);
- let newDataInfo = connection.data;
-
- if (this._dataInfo.state == newDataInfo.state &&
- this._dataInfo.type == newDataInfo.type &&
- this._dataInfo.roaming == newDataInfo.roaming) {
- return;
- }
-
- this._dataInfo.state = newDataInfo.state;
- this._dataInfo.type = newDataInfo.type;
- this._dataInfo.roaming = newDataInfo.roaming;
- this.updateRILNetworkInterface();
- },
-
- notifyDataError: function (aMessage) {},
-
- notifyCFStateChanged: function(aAction, aReason, aNumber, aTimeSeconds, aServiceClass) {},
-
- notifyEmergencyCbModeChanged: function(aActive, aTimeoutMs) {},
-
- notifyOtaStatusChanged: function(aStatus) {},
-
- notifyRadioStateChanged: function() {},
-
- notifyClirModeChanged: function(aMode) {},
-
- notifyLastKnownNetworkChanged: function() {},
-
- notifyLastKnownHomeNetworkChanged: function() {},
-
- notifyNetworkSelectionModeChanged: function() {},
-
- notifyDeviceIdentitiesChanged: function() {}
-};
-
-function DataCall(aClientId, aApnSetting, aDataCallHandler) {
- this.clientId = aClientId;
- this.dataCallHandler = aDataCallHandler;
- this.apnProfile = {
- apn: aApnSetting.apn,
- user: aApnSetting.user,
- password: aApnSetting.password,
- authType: aApnSetting.authtype,
- protocol: aApnSetting.protocol,
- roaming_protocol: aApnSetting.roaming_protocol
- };
- this.linkInfo = {
- cid: null,
- ifname: null,
- addresses: [],
- dnses: [],
- gateways: [],
- pcscf: [],
- mtu: null
- };
- this.state = NETWORK_STATE_UNKNOWN;
- this.requestedNetworkIfaces = [];
-}
-DataCall.prototype = {
- /**
- * Standard values for the APN connection retry process
- * Retry funcion: time(secs) = A * numer_of_retries^2 + B
- */
- NETWORK_APNRETRY_FACTOR: 8,
- NETWORK_APNRETRY_ORIGIN: 3,
- NETWORK_APNRETRY_MAXRETRIES: 10,
-
- dataCallHandler: null,
-
- // Event timer for connection retries
- timer: null,
-
- // APN failed connections. Retry counter
- apnRetryCounter: 0,
-
- // Array to hold RILNetworkInterfaces that requested this DataCall.
- requestedNetworkIfaces: null,
-
- /**
- * @return "deactivate" if <ifname> changes or one of the aCurrentDataCall
- * addresses is missing in updatedDataCall, or "identical" if no
- * changes found, or "changed" otherwise.
- */
- _compareDataCallLink: function(aUpdatedDataCall, aCurrentDataCall) {
- // If network interface is changed, report as "deactivate".
- if (aUpdatedDataCall.ifname != aCurrentDataCall.ifname) {
- return "deactivate";
- }
-
- // If any existing address is missing, report as "deactivate".
- for (let i = 0; i < aCurrentDataCall.addresses.length; i++) {
- let address = aCurrentDataCall.addresses[i];
- if (aUpdatedDataCall.addresses.indexOf(address) < 0) {
- return "deactivate";
- }
- }
-
- if (aCurrentDataCall.addresses.length != aUpdatedDataCall.addresses.length) {
- // Since now all |aCurrentDataCall.addresses| are found in
- // |aUpdatedDataCall.addresses|, this means one or more new addresses are
- // reported.
- return "changed";
- }
-
- let fields = ["gateways", "dnses"];
- for (let i = 0; i < fields.length; i++) {
- // Compare <datacall>.<field>.
- let field = fields[i];
- let lhs = aUpdatedDataCall[field], rhs = aCurrentDataCall[field];
- if (lhs.length != rhs.length) {
- return "changed";
- }
- for (let i = 0; i < lhs.length; i++) {
- if (lhs[i] != rhs[i]) {
- return "changed";
- }
- }
- }
-
- if (aCurrentDataCall.mtu != aUpdatedDataCall.mtu) {
- return "changed";
- }
-
- return "identical";
- },
-
- _getGeckoDataCallState:function (aDataCall) {
- if (aDataCall.active == Ci.nsIDataCallInterface.DATACALL_STATE_ACTIVE_UP ||
- aDataCall.active == Ci.nsIDataCallInterface.DATACALL_STATE_ACTIVE_DOWN) {
- return NETWORK_STATE_CONNECTED;
- }
-
- return NETWORK_STATE_DISCONNECTED;
- },
-
- onSetupDataCallResult: function(aDataCall) {
- this.debug("onSetupDataCallResult: " + JSON.stringify(aDataCall));
- let errorMsg = aDataCall.errorMsg;
- if (aDataCall.failCause &&
- aDataCall.failCause != Ci.nsIDataCallInterface.DATACALL_FAIL_NONE) {
- errorMsg =
- RIL.RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[aDataCall.failCause];
- }
-
- if (errorMsg) {
- if (DEBUG) {
- this.debug("SetupDataCall error for apn " + this.apnProfile.apn + ": " +
- errorMsg + " (" + aDataCall.failCause + "), retry time: " +
- aDataCall.suggestedRetryTime);
- }
-
- this.state = NETWORK_STATE_DISCONNECTED;
-
- if (this.requestedNetworkIfaces.length === 0) {
- if (DEBUG) this.debug("This DataCall is not requested anymore.");
- return;
- }
-
- // Let DataCallHandler notify MobileConnectionService
- this.dataCallHandler.notifyDataCallError(this, errorMsg);
-
- // For suggestedRetryTime, the value of INT32_MAX(0x7fffffff) means no retry.
- if (aDataCall.suggestedRetryTime === INT32_MAX ||
- this.isPermanentFail(aDataCall.failCause, errorMsg)) {
- if (DEBUG) this.debug("Data call error: no retry needed.");
- return;
- }
-
- this.retry(aDataCall.suggestedRetryTime);
- return;
- }
-
- this.apnRetryCounter = 0;
- this.linkInfo.cid = aDataCall.cid;
-
- if (this.requestedNetworkIfaces.length === 0) {
- if (DEBUG) {
- this.debug("State is connected, but no network interface requested" +
- " this DataCall");
- }
- this.deactivate();
- return;
- }
-
- this.linkInfo.ifname = aDataCall.ifname;
- this.linkInfo.addresses = aDataCall.addresses ? aDataCall.addresses.split(" ") : [];
- this.linkInfo.gateways = aDataCall.gateways ? aDataCall.gateways.split(" ") : [];
- this.linkInfo.dnses = aDataCall.dnses ? aDataCall.dnses.split(" ") : [];
- this.linkInfo.pcscf = aDataCall.pcscf ? aDataCall.pcscf.split(" ") : [];
- this.linkInfo.mtu = aDataCall.mtu > 0 ? aDataCall.mtu : 0;
- this.state = this._getGeckoDataCallState(aDataCall);
-
- // Notify DataCallHandler about data call connected.
- this.dataCallHandler.notifyDataCallChanged(this);
-
- for (let i = 0; i < this.requestedNetworkIfaces.length; i++) {
- this.requestedNetworkIfaces[i].notifyRILNetworkInterface();
- }
- },
-
- onDeactivateDataCallResult: function() {
- if (DEBUG) this.debug("onDeactivateDataCallResult");
-
- this.reset();
-
- if (this.requestedNetworkIfaces.length > 0) {
- if (DEBUG) {
- this.debug("State is disconnected/unknown, but this DataCall is" +
- " requested.");
- }
- this.setup();
- return;
- }
-
- // Notify DataCallHandler about data call disconnected.
- this.dataCallHandler.notifyDataCallChanged(this);
- },
-
- onDataCallChanged: function(aUpdatedDataCall) {
- if (DEBUG) {
- this.debug("onDataCallChanged: " + JSON.stringify(aUpdatedDataCall));
- }
-
- if (this.state == NETWORK_STATE_CONNECTING ||
- this.state == NETWORK_STATE_DISCONNECTING) {
- if (DEBUG) {
- this.debug("We are in connecting/disconnecting state, ignore any " +
- "unsolicited event for now.");
- }
- return;
- }
-
- let dataCallState = this._getGeckoDataCallState(aUpdatedDataCall);
- if (this.state == dataCallState &&
- dataCallState != NETWORK_STATE_CONNECTED) {
- return;
- }
-
- let newLinkInfo = {
- ifname: aUpdatedDataCall.ifname,
- addresses: aUpdatedDataCall.addresses ? aUpdatedDataCall.addresses.split(" ") : [],
- dnses: aUpdatedDataCall.dnses ? aUpdatedDataCall.dnses.split(" ") : [],
- gateways: aUpdatedDataCall.gateways ? aUpdatedDataCall.gateways.split(" ") : [],
- pcscf: aUpdatedDataCall.pcscf ? aUpdatedDataCall.pcscf.split(" ") : [],
- mtu: aUpdatedDataCall.mtu > 0 ? aUpdatedDataCall.mtu : 0
- };
-
- switch (dataCallState) {
- case NETWORK_STATE_CONNECTED:
- if (this.state == NETWORK_STATE_CONNECTED) {
- let result =
- this._compareDataCallLink(newLinkInfo, this.linkInfo);
-
- if (result == "identical") {
- if (DEBUG) this.debug("No changes in data call.");
- return;
- }
- if (result == "deactivate") {
- if (DEBUG) this.debug("Data link changed, cleanup.");
- this.deactivate();
- return;
- }
- // Minor change, just update and notify.
- if (DEBUG) {
- this.debug("Data link minor change, just update and notify.");
- }
-
- this.linkInfo.addresses = newLinkInfo.addresses.slice();
- this.linkInfo.gateways = newLinkInfo.gateways.slice();
- this.linkInfo.dnses = newLinkInfo.dnses.slice();
- this.linkInfo.pcscf = newLinkInfo.pcscf.slice();
- this.linkInfo.mtu = newLinkInfo.mtu;
- }
- break;
- case NETWORK_STATE_DISCONNECTED:
- case NETWORK_STATE_UNKNOWN:
- if (this.state == NETWORK_STATE_CONNECTED) {
- // Notify first on unexpected data call disconnection.
- this.state = dataCallState;
- for (let i = 0; i < this.requestedNetworkIfaces.length; i++) {
- this.requestedNetworkIfaces[i].notifyRILNetworkInterface();
- }
- }
- this.reset();
-
- if (this.requestedNetworkIfaces.length > 0) {
- if (DEBUG) {
- this.debug("State is disconnected/unknown, but this DataCall is" +
- " requested.");
- }
- this.setup();
- return;
- }
- break;
- }
-
- this.state = dataCallState;
-
- // Notify DataCallHandler about data call changed.
- this.dataCallHandler.notifyDataCallChanged(this);
-
- for (let i = 0; i < this.requestedNetworkIfaces.length; i++) {
- this.requestedNetworkIfaces[i].notifyRILNetworkInterface();
- }
- },
-
- // Helpers
-
- debug: function(aMsg) {
- dump("-*- DataCall[" + this.clientId + ":" + this.apnProfile.apn + "]: " +
- aMsg + "\n");
- },
-
- get connected() {
- return this.state == NETWORK_STATE_CONNECTED;
- },
-
- isPermanentFail: function(aDataFailCause, aErrorMsg) {
- // Check ril.h for 'no retry' data call fail causes.
- if (aErrorMsg === RIL.GECKO_ERROR_RADIO_NOT_AVAILABLE ||
- aErrorMsg === RIL.GECKO_ERROR_INVALID_PARAMETER ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_OPERATOR_BARRED ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_MISSING_UKNOWN_APN ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_UNKNOWN_PDP_ADDRESS_TYPE ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_USER_AUTHENTICATION ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_ACTIVATION_REJECT_GGSN ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_SERVICE_OPTION_NOT_SUPPORTED ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_SERVICE_OPTION_NOT_SUBSCRIBED ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_NSAPI_IN_USE ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_ONLY_IPV4_ALLOWED ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_ONLY_IPV6_ALLOWED ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_PROTOCOL_ERRORS ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_RADIO_POWER_OFF ||
- aDataFailCause === Ci.nsIDataCallInterface.DATACALL_FAIL_TETHERED_CALL_ACTIVE) {
- return true;
- }
-
- return false;
- },
-
- inRequestedTypes: function(aType) {
- for (let i = 0; i < this.requestedNetworkIfaces.length; i++) {
- if (this.requestedNetworkIfaces[i].info.type == aType) {
- return true;
- }
- }
- return false;
- },
-
- canHandleApn: function(aApnSetting) {
- let isIdentical = this.apnProfile.apn == aApnSetting.apn &&
- (this.apnProfile.user || '') == (aApnSetting.user || '') &&
- (this.apnProfile.password || '') == (aApnSetting.password || '') &&
- (this.apnProfile.authType || '') == (aApnSetting.authtype || '');
-
- if (RILQUIRKS_HAVE_IPV6) {
- isIdentical = isIdentical &&
- (this.apnProfile.protocol || '') == (aApnSetting.protocol || '') &&
- (this.apnProfile.roaming_protocol || '') == (aApnSetting.roaming_protocol || '');
- }
-
- return isIdentical;
- },
-
- resetLinkInfo: function() {
- this.linkInfo.cid = null;
- this.linkInfo.ifname = null;
- this.linkInfo.addresses = [];
- this.linkInfo.dnses = [];
- this.linkInfo.gateways = [];
- this.linkInfo.pcscf = [];
- this.linkInfo.mtu = null;
- },
-
- reset: function() {
- this.resetLinkInfo();
-
- this.state = NETWORK_STATE_UNKNOWN;
- },
-
- connect: function(aNetworkInterface) {
- if (DEBUG) this.debug("connect: " + aNetworkInterface.info.type);
-
- if (this.requestedNetworkIfaces.indexOf(aNetworkInterface) == -1) {
- this.requestedNetworkIfaces.push(aNetworkInterface);
- }
-
- if (this.state == NETWORK_STATE_CONNECTING ||
- this.state == NETWORK_STATE_DISCONNECTING) {
- return;
- }
- if (this.state == NETWORK_STATE_CONNECTED) {
- // This needs to run asynchronously, to behave the same way as the case of
- // non-shared apn, see bug 1059110.
- Services.tm.currentThread.dispatch(() => {
- // Do not notify if state changed while this event was being dispatched,
- // the state probably was notified already or need not to be notified.
- if (aNetworkInterface.info.state == RIL.GECKO_NETWORK_STATE_CONNECTED) {
- aNetworkInterface.notifyRILNetworkInterface();
- }
- }, Ci.nsIEventTarget.DISPATCH_NORMAL);
- return;
- }
-
- // If retry mechanism is running on background, stop it since we are going
- // to setup data call now.
- if (this.timer) {
- this.timer.cancel();
- }
-
- this.setup();
- },
-
- setup: function() {
- if (DEBUG) {
- this.debug("Going to set up data connection with APN " +
- this.apnProfile.apn);
- }
-
- let connection =
- gMobileConnectionService.getItemByServiceId(this.clientId);
- let dataInfo = connection && connection.data;
- if (dataInfo == null ||
- dataInfo.state != RIL.GECKO_MOBILE_CONNECTION_STATE_REGISTERED ||
- dataInfo.type == RIL.GECKO_MOBILE_CONNECTION_STATE_UNKNOWN) {
- return;
- }
-
- let radioTechType = dataInfo.type;
- let radioTechnology = RIL.GECKO_RADIO_TECH.indexOf(radioTechType);
- let authType = RIL.RIL_DATACALL_AUTH_TO_GECKO.indexOf(this.apnProfile.authType);
- // Use the default authType if the value in database is invalid.
- // For the case that user might not select the authentication type.
- if (authType == -1) {
- if (DEBUG) {
- this.debug("Invalid authType '" + this.apnProfile.authtype +
- "', using '" + RIL.GECKO_DATACALL_AUTH_DEFAULT + "'");
- }
- authType = RIL.RIL_DATACALL_AUTH_TO_GECKO.indexOf(RIL.GECKO_DATACALL_AUTH_DEFAULT);
- }
-
- let pdpType = Ci.nsIDataCallInterface.DATACALL_PDP_TYPE_IPV4;
- if (RILQUIRKS_HAVE_IPV6) {
- pdpType = !dataInfo.roaming
- ? RIL.RIL_DATACALL_PDP_TYPES.indexOf(this.apnProfile.protocol)
- : RIL.RIL_DATACALL_PDP_TYPES.indexOf(this.apnProfile.roaming_protocol);
- if (pdpType == -1) {
- if (DEBUG) {
- this.debug("Invalid pdpType '" + (!dataInfo.roaming
- ? this.apnProfile.protocol
- : this.apnProfile.roaming_protocol) +
- "', using '" + RIL.GECKO_DATACALL_PDP_TYPE_DEFAULT + "'");
- }
- pdpType = RIL.RIL_DATACALL_PDP_TYPES.indexOf(RIL.GECKO_DATACALL_PDP_TYPE_DEFAULT);
- }
- }
-
- let dcInterface = this.dataCallHandler.dataCallInterface;
- dcInterface.setupDataCall(
- this.apnProfile.apn, this.apnProfile.user, this.apnProfile.password,
- authType, pdpType, {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallCallback]),
- notifySetupDataCallSuccess: (aDataCall) => {
- this.onSetupDataCallResult(aDataCall);
- },
- notifyError: (aErrorMsg) => {
- this.onSetupDataCallResult({errorMsg: aErrorMsg});
- }
- });
- this.state = NETWORK_STATE_CONNECTING;
- },
-
- retry: function(aSuggestedRetryTime) {
- let apnRetryTimer;
-
- // We will retry the connection in increasing times
- // based on the function: time = A * numer_of_retries^2 + B
- if (this.apnRetryCounter >= this.NETWORK_APNRETRY_MAXRETRIES) {
- this.apnRetryCounter = 0;
- this.timer = null;
- if (DEBUG) this.debug("Too many APN Connection retries - STOP retrying");
- return;
- }
-
- // If there is a valid aSuggestedRetryTime, override the retry timer.
- if (aSuggestedRetryTime !== undefined && aSuggestedRetryTime >= 0) {
- apnRetryTimer = aSuggestedRetryTime / 1000;
- } else {
- apnRetryTimer = this.NETWORK_APNRETRY_FACTOR *
- (this.apnRetryCounter * this.apnRetryCounter) +
- this.NETWORK_APNRETRY_ORIGIN;
- }
- this.apnRetryCounter++;
- if (DEBUG) {
- this.debug("Data call - APN Connection Retry Timer (secs-counter): " +
- apnRetryTimer + "-" + this.apnRetryCounter);
- }
-
- if (this.timer == null) {
- // Event timer for connection retries
- this.timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- }
- this.timer.initWithCallback(this, apnRetryTimer * 1000,
- Ci.nsITimer.TYPE_ONE_SHOT);
- },
-
- disconnect: function(aNetworkInterface) {
- if (DEBUG) this.debug("disconnect: " + aNetworkInterface.info.type);
-
- let index = this.requestedNetworkIfaces.indexOf(aNetworkInterface);
- if (index != -1) {
- this.requestedNetworkIfaces.splice(index, 1);
-
- if (this.state == NETWORK_STATE_DISCONNECTED ||
- this.state == NETWORK_STATE_UNKNOWN) {
- if (this.timer) {
- this.timer.cancel();
- }
- this.reset();
- return;
- }
-
- // Notify the DISCONNECTED event immediately after network interface is
- // removed from requestedNetworkIfaces, to make the DataCall, shared or
- // not, to have the same behavior.
- Services.tm.currentThread.dispatch(() => {
- // Do not notify if state changed while this event was being dispatched,
- // the state probably was notified already or need not to be notified.
- if (aNetworkInterface.info.state == RIL.GECKO_NETWORK_STATE_DISCONNECTED) {
- aNetworkInterface.notifyRILNetworkInterface();
-
- // Clear link info after notifying NetworkManager.
- if (this.requestedNetworkIfaces.length === 0) {
- this.resetLinkInfo();
- }
- }
- }, Ci.nsIEventTarget.DISPATCH_NORMAL);
- }
-
- // Only deactivate data call if no more network interface needs this
- // DataCall and if state is CONNECTED, for other states, we simply remove
- // the network interface from requestedNetworkIfaces.
- if (this.requestedNetworkIfaces.length > 0 ||
- this.state != NETWORK_STATE_CONNECTED) {
- return;
- }
-
- this.deactivate();
- },
-
- deactivate: function() {
- let reason = Ci.nsIDataCallInterface.DATACALL_DEACTIVATE_NO_REASON;
- if (DEBUG) {
- this.debug("Going to disconnect data connection cid " + this.linkInfo.cid);
- }
-
- let dcInterface = this.dataCallHandler.dataCallInterface;
- dcInterface.deactivateDataCall(this.linkInfo.cid, reason, {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCallCallback]),
- notifySuccess: () => {
- this.onDeactivateDataCallResult();
- },
- notifyError: (aErrorMsg) => {
- this.onDeactivateDataCallResult();
- }
- });
-
- this.state = NETWORK_STATE_DISCONNECTING;
- },
-
- // Entry method for timer events. Used to reconnect to a failed APN
- notify: function(aTimer) {
- this.setup();
- },
-
- shutdown: function() {
- if (this.timer) {
- this.timer.cancel();
- this.timer = null;
- }
- }
-};
-
-function RILNetworkInfo(aClientId, aType, aNetworkInterface)
-{
- this.serviceId = aClientId;
- this.type = aType;
-
- this.networkInterface = aNetworkInterface;
-}
-RILNetworkInfo.prototype = {
- classID: RILNETWORKINFO_CID,
- classInfo: XPCOMUtils.generateCI({classID: RILNETWORKINFO_CID,
- classDescription: "RILNetworkInfo",
- interfaces: [Ci.nsINetworkInfo,
- Ci.nsIRilNetworkInfo]}),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInfo,
- Ci.nsIRilNetworkInfo]),
-
- networkInterface: null,
-
- getDataCall: function() {
- return this.networkInterface.dataCall;
- },
-
- getApnSetting: function() {
- return this.networkInterface.apnSetting;
- },
-
- debug: function(aMsg) {
- dump("-*- RILNetworkInfo[" + this.serviceId + ":" + this.type + "]: " +
- aMsg + "\n");
- },
-
- /**
- * nsINetworkInfo Implementation
- */
- get state() {
- let dataCall = this.getDataCall();
- if (!dataCall.inRequestedTypes(this.type)) {
- return NETWORK_STATE_DISCONNECTED;
- }
- return dataCall.state;
- },
-
- type: null,
-
- get name() {
- return this.getDataCall().linkInfo.ifname;
- },
-
- getAddresses: function(aIps, aPrefixLengths) {
- let addresses = this.getDataCall().linkInfo.addresses;
-
- let ips = [];
- let prefixLengths = [];
- for (let i = 0; i < addresses.length; i++) {
- let [ip, prefixLength] = addresses[i].split("/");
- ips.push(ip);
- prefixLengths.push(prefixLength);
- }
-
- aIps.value = ips.slice();
- aPrefixLengths.value = prefixLengths.slice();
-
- return ips.length;
- },
-
- getGateways: function(aCount) {
- let linkInfo = this.getDataCall().linkInfo;
-
- if (aCount) {
- aCount.value = linkInfo.gateways.length;
- }
-
- return linkInfo.gateways.slice();
- },
-
- getDnses: function(aCount) {
- let linkInfo = this.getDataCall().linkInfo;
-
- if (aCount) {
- aCount.value = linkInfo.dnses.length;
- }
-
- return linkInfo.dnses.slice();
- },
-
- /**
- * nsIRilNetworkInfo Implementation
- */
-
- serviceId: 0,
-
- get iccId() {
- let icc = gIccService.getIccByServiceId(this.serviceId);
- let iccInfo = icc && icc.iccInfo;
-
- return iccInfo && iccInfo.iccid;
- },
-
- get mmsc() {
- if (this.type != NETWORK_TYPE_MOBILE_MMS) {
- if (DEBUG) this.debug("Error! Only MMS network can get MMSC.");
- throw Cr.NS_ERROR_UNEXPECTED;
- }
-
- return this.getApnSetting().mmsc || "";
- },
-
- get mmsProxy() {
- if (this.type != NETWORK_TYPE_MOBILE_MMS) {
- if (DEBUG) this.debug("Error! Only MMS network can get MMS proxy.");
- throw Cr.NS_ERROR_UNEXPECTED;
- }
-
- return this.getApnSetting().mmsproxy || "";
- },
-
- get mmsPort() {
- if (this.type != NETWORK_TYPE_MOBILE_MMS) {
- if (DEBUG) this.debug("Error! Only MMS network can get MMS port.");
- throw Cr.NS_ERROR_UNEXPECTED;
- }
-
- // Note: Port 0 is reserved, so we treat it as invalid as well.
- // See http://www.iana.org/assignments/port-numbers
- return this.getApnSetting().mmsport || -1;
- },
-
- getPcscf: function(aCount) {
- if (this.type != NETWORK_TYPE_MOBILE_IMS) {
- if (DEBUG) this.debug("Error! Only IMS network can get pcscf.");
- throw Cr.NS_ERROR_UNEXPECTED;
- }
-
- let linkInfo = this.getDataCall().linkInfo;
-
- if (aCount) {
- aCount.value = linkInfo.pcscf.length;
- }
- return linkInfo.pcscf.slice();
- },
-};
-
-function RILNetworkInterface(aDataCallHandler, aType, aApnSetting, aDataCall) {
- if (!aDataCall) {
- throw new Error("No dataCall for RILNetworkInterface: " + type);
- }
-
- this.dataCallHandler = aDataCallHandler;
- this.enabled = false;
- this.dataCall = aDataCall;
- this.apnSetting = aApnSetting;
-
- this.info = new RILNetworkInfo(aDataCallHandler.clientId, aType, this);
-}
-
-RILNetworkInterface.prototype = {
- classID: RILNETWORKINTERFACE_CID,
- classInfo: XPCOMUtils.generateCI({classID: RILNETWORKINTERFACE_CID,
- classDescription: "RILNetworkInterface",
- interfaces: [Ci.nsINetworkInterface]}),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterface]),
-
- // If this RILNetworkInterface type is enabled or not.
- enabled: null,
-
- apnSetting: null,
-
- dataCall: null,
-
- /**
- * nsINetworkInterface Implementation
- */
-
- info: null,
-
- get httpProxyHost() {
- return this.apnSetting.proxy || "";
- },
-
- get httpProxyPort() {
- return this.apnSetting.port || "";
- },
-
- get mtu() {
- // Value provided by network has higher priority than apn settings.
- return this.dataCall.linkInfo.mtu || this.apnSetting.mtu || -1;
- },
-
- // Helpers
-
- debug: function(aMsg) {
- dump("-*- RILNetworkInterface[" + this.dataCallHandler.clientId + ":" +
- this.info.type + "]: " + aMsg + "\n");
- },
-
- get connected() {
- return this.info.state == NETWORK_STATE_CONNECTED;
- },
-
- notifyRILNetworkInterface: function() {
- if (DEBUG) {
- this.debug("notifyRILNetworkInterface type: " + this.info.type +
- ", state: " + this.info.state);
- }
-
- gNetworkManager.updateNetworkInterface(this);
- },
-
- connect: function() {
- this.enabled = true;
-
- this.dataCall.connect(this);
- },
-
- disconnect: function() {
- if (!this.enabled) {
- return;
- }
- this.enabled = false;
-
- this.dataCall.disconnect(this);
- },
-
- shutdown: function() {
- this.dataCall.shutdown();
- this.dataCall = null;
- }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([DataCallManager]); \ No newline at end of file
diff --git a/dom/system/gonk/DataCallManager.manifest b/dom/system/gonk/DataCallManager.manifest
deleted file mode 100644
index 2a982415e..000000000
--- a/dom/system/gonk/DataCallManager.manifest
+++ /dev/null
@@ -1,4 +0,0 @@
-# DataCallManager.js
-component {35b9efa2-e42c-45ce-8210-0a13e6f4aadc} DataCallManager.js
-contract @mozilla.org/datacall/manager;1 {35b9efa2-e42c-45ce-8210-0a13e6f4aadc}
-category profile-after-change DataCallManager @mozilla.org/datacall/manager;1 \ No newline at end of file
diff --git a/dom/system/gonk/GeolocationUtil.cpp b/dom/system/gonk/GeolocationUtil.cpp
deleted file mode 100644
index 99d484a19..000000000
--- a/dom/system/gonk/GeolocationUtil.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "GeolocationUtil.h"
-
-double CalculateDeltaInMeter(double aLat, double aLon, double aLastLat, double aLastLon)
-{
- // Use spherical law of cosines to calculate difference
- // Not quite as correct as the Haversine but simpler and cheaper
- const double radsInDeg = M_PI / 180.0;
- const double rNewLat = aLat * radsInDeg;
- const double rNewLon = aLon * radsInDeg;
- const double rOldLat = aLastLat * radsInDeg;
- const double rOldLon = aLastLon * radsInDeg;
- // WGS84 equatorial radius of earth = 6378137m
- double cosDelta = (sin(rNewLat) * sin(rOldLat)) +
- (cos(rNewLat) * cos(rOldLat) * cos(rOldLon - rNewLon));
- if (cosDelta > 1.0) {
- cosDelta = 1.0;
- } else if (cosDelta < -1.0) {
- cosDelta = -1.0;
- }
- return acos(cosDelta) * 6378137;
-}
-
diff --git a/dom/system/gonk/GeolocationUtil.h b/dom/system/gonk/GeolocationUtil.h
deleted file mode 100644
index fde337fb8..000000000
--- a/dom/system/gonk/GeolocationUtil.h
+++ /dev/null
@@ -1,13 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef GEOLOCATIONUTIL_H
-#define GEOLOCATIONUTIL_H
-
-double CalculateDeltaInMeter(double aLat, double aLon, double aLastLat, double aLastLon);
-
-#endif
-
diff --git a/dom/system/gonk/GonkGPSGeolocationProvider.cpp b/dom/system/gonk/GonkGPSGeolocationProvider.cpp
deleted file mode 100644
index 9ce6ce2e5..000000000
--- a/dom/system/gonk/GonkGPSGeolocationProvider.cpp
+++ /dev/null
@@ -1,706 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "GonkGPSGeolocationProvider.h"
-
-#include <cmath>
-#include <pthread.h>
-#include <hardware/gps.h>
-
-#include "base/task.h"
-#include "GeolocationUtil.h"
-#include "mozstumbler/MozStumbler.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/Services.h"
-#include "nsContentUtils.h"
-#include "nsGeoPosition.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsINetworkInterface.h"
-#include "nsIObserverService.h"
-#include "nsJSUtils.h"
-#include "nsPrintfCString.h"
-#include "nsServiceManagerUtils.h"
-#include "nsThreadUtils.h"
-#include "prtime.h"
-#include "mozilla/dom/BindingUtils.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "mozilla/dom/SettingChangeNotificationBinding.h"
-
-#ifdef AGPS_TYPE_INVALID
-#define AGPS_HAVE_DUAL_APN
-#endif
-
-#define FLUSH_AIDE_DATA 0
-
-#undef LOG
-#undef ERR
-#undef DBG
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "GonkGPSGeolocationProvider", ## args)
-#define ERR(args...) __android_log_print(ANDROID_LOG_ERROR, "GonkGPSGeolocationProvider", ## args)
-#define DBG(args...) __android_log_print(ANDROID_LOG_DEBUG, "GonkGPSGeolocationProvider" , ## args)
-
-using namespace mozilla;
-using namespace mozilla::dom;
-
-static const int kDefaultPeriod = 1000; // ms
-static bool gDebug_isLoggingEnabled = false;
-static bool gDebug_isGPSLocationIgnored = false;
-static const char* kMozSettingsChangedTopic = "mozsettings-changed";
-// Both of these settings can be toggled in the Gaia Developer settings screen.
-static const char* kSettingDebugEnabled = "geolocation.debugging.enabled";
-static const char* kSettingDebugGpsIgnored = "geolocation.debugging.gps-locations-ignored";
-
-// While most methods of GonkGPSGeolocationProvider should only be
-// called from main thread, we deliberately put the Init and ShutdownGPS
-// methods off main thread to avoid blocking.
-NS_IMPL_ISUPPORTS(GonkGPSGeolocationProvider,
- nsIGeolocationProvider,
- nsIObserver,
- nsISettingsServiceCallback)
-
-/* static */ GonkGPSGeolocationProvider* GonkGPSGeolocationProvider::sSingleton = nullptr;
-GpsCallbacks GonkGPSGeolocationProvider::mCallbacks;
-
-
-void
-GonkGPSGeolocationProvider::LocationCallback(GpsLocation* location)
-{
- if (gDebug_isGPSLocationIgnored) {
- return;
- }
-
- class UpdateLocationEvent : public Runnable {
- public:
- UpdateLocationEvent(nsGeoPosition* aPosition)
- : mPosition(aPosition)
- {}
- NS_IMETHOD Run() override {
- RefPtr<GonkGPSGeolocationProvider> provider =
- GonkGPSGeolocationProvider::GetSingleton();
- nsCOMPtr<nsIGeolocationUpdate> callback = provider->mLocationCallback;
- provider->mLastGPSPosition = mPosition;
- if (callback) {
- callback->Update(mPosition);
- }
- return NS_OK;
- }
- private:
- RefPtr<nsGeoPosition> mPosition;
- };
-
- MOZ_ASSERT(location);
-
- const float kImpossibleAccuracy_m = 0.001;
- if (location->accuracy < kImpossibleAccuracy_m) {
- return;
- }
-
- RefPtr<nsGeoPosition> somewhere = new nsGeoPosition(location->latitude,
- location->longitude,
- location->altitude,
- location->accuracy,
- location->accuracy,
- location->bearing,
- location->speed,
- PR_Now() / PR_USEC_PER_MSEC);
- // Note above: Can't use location->timestamp as the time from the satellite is a
- // minimum of 16 secs old (see http://leapsecond.com/java/gpsclock.htm).
- // All code from this point on expects the gps location to be timestamped with the
- // current time, most notably: the geolocation service which respects maximumAge
- // set in the DOM JS.
-
- if (gDebug_isLoggingEnabled) {
- DBG("geo: GPS got a fix (%f, %f). accuracy: %f",
- location->latitude,
- location->longitude,
- location->accuracy);
- }
-
- RefPtr<UpdateLocationEvent> event = new UpdateLocationEvent(somewhere);
- NS_DispatchToMainThread(event);
-
-}
-
-class NotifyObserversGPSTask final : public Runnable
-{
-public:
- explicit NotifyObserversGPSTask(const char16_t* aData)
- : mData(aData)
- {}
- NS_IMETHOD Run() override {
- RefPtr<nsIGeolocationProvider> provider =
- GonkGPSGeolocationProvider::GetSingleton();
- nsCOMPtr<nsIObserverService> obsService = services::GetObserverService();
- obsService->NotifyObservers(provider, "geolocation-device-events", mData);
- return NS_OK;
- }
-private:
- const char16_t* mData;
-};
-
-void
-GonkGPSGeolocationProvider::StatusCallback(GpsStatus* status)
-{
- const char* msgStream=0;
- switch (status->status) {
- case GPS_STATUS_NONE:
- msgStream = "geo: GPS_STATUS_NONE\n";
- break;
- case GPS_STATUS_SESSION_BEGIN:
- msgStream = "geo: GPS_STATUS_SESSION_BEGIN\n";
- break;
- case GPS_STATUS_SESSION_END:
- msgStream = "geo: GPS_STATUS_SESSION_END\n";
- break;
- case GPS_STATUS_ENGINE_ON:
- msgStream = "geo: GPS_STATUS_ENGINE_ON\n";
- NS_DispatchToMainThread(new NotifyObserversGPSTask(u"GPSStarting"));
- break;
- case GPS_STATUS_ENGINE_OFF:
- msgStream = "geo: GPS_STATUS_ENGINE_OFF\n";
- NS_DispatchToMainThread(new NotifyObserversGPSTask(u"GPSShutdown"));
- break;
- default:
- msgStream = "geo: Unknown GPS status\n";
- break;
- }
- if (gDebug_isLoggingEnabled){
- DBG("%s", msgStream);
- }
-}
-
-void
-GonkGPSGeolocationProvider::SvStatusCallback(GpsSvStatus* sv_info)
-{
- if (gDebug_isLoggingEnabled) {
- static int numSvs = 0;
- static uint32_t numEphemeris = 0;
- static uint32_t numAlmanac = 0;
- static uint32_t numUsedInFix = 0;
-
- unsigned int i = 1;
- uint32_t svAlmanacCount = 0;
- for (i = 1; i > 0; i <<= 1) {
- if (i & sv_info->almanac_mask) {
- svAlmanacCount++;
- }
- }
-
- uint32_t svEphemerisCount = 0;
- for (i = 1; i > 0; i <<= 1) {
- if (i & sv_info->ephemeris_mask) {
- svEphemerisCount++;
- }
- }
-
- uint32_t svUsedCount = 0;
- for (i = 1; i > 0; i <<= 1) {
- if (i & sv_info->used_in_fix_mask) {
- svUsedCount++;
- }
- }
-
- // Log the message only if the the status changed.
- if (sv_info->num_svs != numSvs ||
- svAlmanacCount != numAlmanac ||
- svEphemerisCount != numEphemeris ||
- svUsedCount != numUsedInFix) {
-
- LOG(
- "geo: Number of SVs have (visibility, almanac, ephemeris): (%d, %d, %d)."
- " %d of these SVs were used in fix.\n",
- sv_info->num_svs, svAlmanacCount, svEphemerisCount, svUsedCount);
-
- numSvs = sv_info->num_svs;
- numAlmanac = svAlmanacCount;
- numEphemeris = svEphemerisCount;
- numUsedInFix = svUsedCount;
- }
- }
-}
-
-void
-GonkGPSGeolocationProvider::NmeaCallback(GpsUtcTime timestamp, const char* nmea, int length)
-{
- if (gDebug_isLoggingEnabled) {
- DBG("NMEA: timestamp:\t%lld, length: %d, %s", timestamp, length, nmea);
- }
-}
-
-void
-GonkGPSGeolocationProvider::SetCapabilitiesCallback(uint32_t capabilities)
-{
- class UpdateCapabilitiesEvent : public Runnable {
- public:
- UpdateCapabilitiesEvent(uint32_t aCapabilities)
- : mCapabilities(aCapabilities)
- {}
- NS_IMETHOD Run() override {
- RefPtr<GonkGPSGeolocationProvider> provider =
- GonkGPSGeolocationProvider::GetSingleton();
-
- provider->mSupportsScheduling = mCapabilities & GPS_CAPABILITY_SCHEDULING;
- provider->mSupportsSingleShot = mCapabilities & GPS_CAPABILITY_SINGLE_SHOT;
-#ifdef GPS_CAPABILITY_ON_DEMAND_TIME
- provider->mSupportsTimeInjection = mCapabilities & GPS_CAPABILITY_ON_DEMAND_TIME;
-#endif
- return NS_OK;
- }
- private:
- uint32_t mCapabilities;
- };
-
- NS_DispatchToMainThread(new UpdateCapabilitiesEvent(capabilities));
-}
-
-void
-GonkGPSGeolocationProvider::AcquireWakelockCallback()
-{
-}
-
-void
-GonkGPSGeolocationProvider::ReleaseWakelockCallback()
-{
-}
-
-typedef void *(*pthread_func)(void *);
-
-/** Callback for creating a thread that can call into the JS codes.
- */
-pthread_t
-GonkGPSGeolocationProvider::CreateThreadCallback(const char* name, void (*start)(void *), void* arg)
-{
- pthread_t thread;
- pthread_attr_t attr;
-
- pthread_attr_init(&attr);
-
- /* Unfortunately pthread_create and the callback disagreed on what
- * start function should return.
- */
- pthread_create(&thread, &attr, reinterpret_cast<pthread_func>(start), arg);
-
- return thread;
-}
-
-void
-GonkGPSGeolocationProvider::RequestUtcTimeCallback()
-{
-}
-
-GonkGPSGeolocationProvider::GonkGPSGeolocationProvider()
- : mStarted(false)
- , mSupportsScheduling(false)
- , mObservingSettingsChange(false)
- , mSupportsSingleShot(false)
- , mSupportsTimeInjection(false)
- , mGpsInterface(nullptr)
-{
-}
-
-GonkGPSGeolocationProvider::~GonkGPSGeolocationProvider()
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!mStarted, "Must call Shutdown before destruction");
-
- sSingleton = nullptr;
-}
-
-already_AddRefed<GonkGPSGeolocationProvider>
-GonkGPSGeolocationProvider::GetSingleton()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!sSingleton)
- sSingleton = new GonkGPSGeolocationProvider();
-
- RefPtr<GonkGPSGeolocationProvider> provider = sSingleton;
- return provider.forget();
-}
-
-const GpsInterface*
-GonkGPSGeolocationProvider::GetGPSInterface()
-{
- hw_module_t* module;
-
- if (hw_get_module(GPS_HARDWARE_MODULE_ID, (hw_module_t const**)&module))
- return nullptr;
-
- hw_device_t* device;
- if (module->methods->open(module, GPS_HARDWARE_MODULE_ID, &device))
- return nullptr;
-
- gps_device_t* gps_device = (gps_device_t *)device;
- const GpsInterface* result = gps_device->get_gps_interface(gps_device);
-
- if (result->size != sizeof(GpsInterface)) {
- return nullptr;
- }
- return result;
-}
-
-void
-GonkGPSGeolocationProvider::RequestSettingValue(const char* aKey)
-{
- MOZ_ASSERT(aKey);
- nsCOMPtr<nsISettingsService> ss = do_GetService("@mozilla.org/settingsService;1");
- if (!ss) {
- MOZ_ASSERT(ss);
- return;
- }
-
- nsCOMPtr<nsISettingsServiceLock> lock;
- nsresult rv = ss->CreateLock(nullptr, getter_AddRefs(lock));
- if (NS_FAILED(rv)) {
- ERR("error while createLock setting '%s': %d\n", aKey, uint32_t(rv));
- return;
- }
-
- rv = lock->Get(aKey, this);
- if (NS_FAILED(rv)) {
- ERR("error while get setting '%s': %d\n", aKey, uint32_t(rv));
- return;
- }
-}
-
-void
-GonkGPSGeolocationProvider::InjectLocation(double latitude,
- double longitude,
- float accuracy)
-{
- if (gDebug_isLoggingEnabled) {
- DBG("injecting location (%f, %f) accuracy: %f", latitude, longitude, accuracy);
- }
-
- MOZ_ASSERT(NS_IsMainThread());
- if (!mGpsInterface) {
- return;
- }
-
- mGpsInterface->inject_location(latitude, longitude, accuracy);
-}
-
-void
-GonkGPSGeolocationProvider::Init()
-{
- // Must not be main thread. Some GPS driver's first init takes very long.
- MOZ_ASSERT(!NS_IsMainThread());
-
- mGpsInterface = GetGPSInterface();
- if (!mGpsInterface) {
- return;
- }
-
- if (!mCallbacks.size) {
- mCallbacks.size = sizeof(GpsCallbacks);
- mCallbacks.location_cb = LocationCallback;
- mCallbacks.status_cb = StatusCallback;
- mCallbacks.sv_status_cb = SvStatusCallback;
- mCallbacks.nmea_cb = NmeaCallback;
- mCallbacks.set_capabilities_cb = SetCapabilitiesCallback;
- mCallbacks.acquire_wakelock_cb = AcquireWakelockCallback;
- mCallbacks.release_wakelock_cb = ReleaseWakelockCallback;
- mCallbacks.create_thread_cb = CreateThreadCallback;
-
-#ifdef GPS_CAPABILITY_ON_DEMAND_TIME
- mCallbacks.request_utc_time_cb = RequestUtcTimeCallback;
-#endif
-
- }
-
- if (mGpsInterface->init(&mCallbacks) != 0) {
- return;
- }
-
- NS_DispatchToMainThread(NewRunnableMethod(this, &GonkGPSGeolocationProvider::StartGPS));
-}
-
-void
-GonkGPSGeolocationProvider::StartGPS()
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(mGpsInterface);
-
- int32_t update = Preferences::GetInt("geo.default.update", kDefaultPeriod);
-
- int positionMode = GPS_POSITION_MODE_STANDALONE;
-
- if (!mSupportsScheduling) {
- update = kDefaultPeriod;
- }
-
- mGpsInterface->set_position_mode(positionMode,
- GPS_POSITION_RECURRENCE_PERIODIC,
- update, 0, 0);
-#if FLUSH_AIDE_DATA
- // Delete cached data
- mGpsInterface->delete_aiding_data(GPS_DELETE_ALL);
-#endif
-
- mGpsInterface->start();
-}
-
-
-NS_IMPL_ISUPPORTS(GonkGPSGeolocationProvider::NetworkLocationUpdate,
- nsIGeolocationUpdate)
-
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::NetworkLocationUpdate::Update(nsIDOMGeoPosition *position)
-{
- RefPtr<GonkGPSGeolocationProvider> provider =
- GonkGPSGeolocationProvider::GetSingleton();
-
- nsCOMPtr<nsIDOMGeoPositionCoords> coords;
- position->GetCoords(getter_AddRefs(coords));
- if (!coords) {
- return NS_ERROR_FAILURE;
- }
-
- double lat, lon, acc;
- coords->GetLatitude(&lat);
- coords->GetLongitude(&lon);
- coords->GetAccuracy(&acc);
-
- double delta = -1.0;
-
- static double sLastMLSPosLat = 0;
- static double sLastMLSPosLon = 0;
-
- if (0 != sLastMLSPosLon || 0 != sLastMLSPosLat) {
- delta = CalculateDeltaInMeter(lat, lon, sLastMLSPosLat, sLastMLSPosLon);
- }
-
- sLastMLSPosLat = lat;
- sLastMLSPosLon = lon;
-
- // if the MLS coord change is smaller than this arbitrarily small value
- // assume the MLS coord is unchanged, and stick with the GPS location
- const double kMinMLSCoordChangeInMeters = 10;
-
- DOMTimeStamp time_ms = 0;
- if (provider->mLastGPSPosition) {
- provider->mLastGPSPosition->GetTimestamp(&time_ms);
- }
- const int64_t diff_ms = (PR_Now() / PR_USEC_PER_MSEC) - time_ms;
-
- // We want to distinguish between the GPS being inactive completely
- // and temporarily inactive. In the former case, we would use a low
- // accuracy network location; in the latter, we only want a network
- // location that appears to updating with movement.
-
- const bool isGPSFullyInactive = diff_ms > 1000 * 60 * 2; // two mins
- const bool isGPSTempInactive = diff_ms > 1000 * 10; // 10 secs
-
- if (provider->mLocationCallback) {
- if (isGPSFullyInactive ||
- (isGPSTempInactive && delta > kMinMLSCoordChangeInMeters))
- {
- if (gDebug_isLoggingEnabled) {
- DBG("Using MLS, GPS age:%fs, MLS Delta:%fm\n", diff_ms / 1000.0, delta);
- }
- provider->mLocationCallback->Update(position);
- } else if (provider->mLastGPSPosition) {
- if (gDebug_isLoggingEnabled) {
- DBG("Using old GPS age:%fs\n", diff_ms / 1000.0);
- }
-
- // This is a fallback case so that the GPS provider responds with its last
- // location rather than waiting for a more recent GPS or network location.
- // The service decides if the location is too old, not the provider.
- provider->mLocationCallback->Update(provider->mLastGPSPosition);
- }
- }
- provider->InjectLocation(lat, lon, acc);
- return NS_OK;
-}
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::NetworkLocationUpdate::NotifyError(uint16_t error)
-{
- return NS_OK;
-}
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::Startup()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- if (mStarted) {
- return NS_OK;
- }
-
- RequestSettingValue(kSettingDebugEnabled);
- RequestSettingValue(kSettingDebugGpsIgnored);
-
- // Setup an observer to watch changes to the setting.
- nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
- if (observerService) {
- MOZ_ASSERT(!mObservingSettingsChange);
- nsresult rv = observerService->AddObserver(this, kMozSettingsChangedTopic, false);
- if (NS_FAILED(rv)) {
- NS_WARNING("geo: Gonk GPS AddObserver failed");
- } else {
- mObservingSettingsChange = true;
- }
- }
-
- if (!mInitThread) {
- nsresult rv = NS_NewThread(getter_AddRefs(mInitThread));
- NS_ENSURE_SUCCESS(rv, rv);
- }
-
- mInitThread->Dispatch(NewRunnableMethod(this, &GonkGPSGeolocationProvider::Init),
- NS_DISPATCH_NORMAL);
-
- mNetworkLocationProvider = do_CreateInstance("@mozilla.org/geolocation/mls-provider;1");
- if (mNetworkLocationProvider) {
- nsresult rv = mNetworkLocationProvider->Startup();
- if (NS_SUCCEEDED(rv)) {
- RefPtr<NetworkLocationUpdate> update = new NetworkLocationUpdate();
- mNetworkLocationProvider->Watch(update);
- }
- }
-
- mStarted = true;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::Watch(nsIGeolocationUpdate* aCallback)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- mLocationCallback = aCallback;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::Shutdown()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!mStarted) {
- return NS_OK;
- }
-
- mStarted = false;
- if (mNetworkLocationProvider) {
- mNetworkLocationProvider->Shutdown();
- mNetworkLocationProvider = nullptr;
- }
-
- nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
- if (obs) {
- nsresult rv;
- rv = obs->RemoveObserver(this, kMozSettingsChangedTopic);
- if (NS_FAILED(rv)) {
- NS_WARNING("geo: Gonk GPS mozsettings RemoveObserver failed");
- } else {
- mObservingSettingsChange = false;
- }
- }
-
- mInitThread->Dispatch(NewRunnableMethod(this, &GonkGPSGeolocationProvider::ShutdownGPS),
- NS_DISPATCH_NORMAL);
-
- return NS_OK;
-}
-
-void
-GonkGPSGeolocationProvider::ShutdownGPS()
-{
- MOZ_ASSERT(!mStarted, "Should only be called after Shutdown");
-
- if (mGpsInterface) {
- mGpsInterface->stop();
- mGpsInterface->cleanup();
- }
-}
-
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::SetHighAccuracy(bool)
-{
- return NS_OK;
-}
-
-namespace {
-int
-ConvertToGpsNetworkType(int aNetworkInterfaceType)
-{
- switch (aNetworkInterfaceType) {
- case nsINetworkInfo::NETWORK_TYPE_WIFI:
- return AGPS_RIL_NETWORK_TYPE_WIFI;
- case nsINetworkInfo::NETWORK_TYPE_MOBILE:
- return AGPS_RIL_NETWORK_TYPE_MOBILE;
- case nsINetworkInfo::NETWORK_TYPE_MOBILE_MMS:
- return AGPS_RIL_NETWORK_TYPE_MOBILE_MMS;
- case nsINetworkInfo::NETWORK_TYPE_MOBILE_SUPL:
- return AGPS_RIL_NETWORK_TYPE_MOBILE_SUPL;
- case nsINetworkInfo::NETWORK_TYPE_MOBILE_DUN:
- return AGPS_RIL_NETWORK_TTYPE_MOBILE_DUN;
- default:
- NS_WARNING(nsPrintfCString("Unknown network type mapping %d",
- aNetworkInterfaceType).get());
- return -1;
- }
-}
-} // namespace
-
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!strcmp(aTopic, kMozSettingsChangedTopic)) {
- // Read changed setting value
- RootedDictionary<SettingChangeNotification> setting(RootingCx());
- if (!WrappedJSToDictionary(aSubject, setting)) {
- return NS_OK;
- }
-
- if (setting.mKey.EqualsASCII(kSettingDebugGpsIgnored)) {
- LOG("received mozsettings-changed: ignoring\n");
- gDebug_isGPSLocationIgnored =
- setting.mValue.isBoolean() ? setting.mValue.toBoolean() : false;
- if (gDebug_isLoggingEnabled) {
- DBG("GPS ignored %d\n", gDebug_isGPSLocationIgnored);
- }
- return NS_OK;
- } else if (setting.mKey.EqualsASCII(kSettingDebugEnabled)) {
- LOG("received mozsettings-changed: logging\n");
- gDebug_isLoggingEnabled =
- setting.mValue.isBoolean() ? setting.mValue.toBoolean() : false;
- return NS_OK;
- }
- }
-
- return NS_OK;
-}
-
-/** nsISettingsServiceCallback **/
-
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::Handle(const nsAString& aName,
- JS::Handle<JS::Value> aResult)
-{
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GonkGPSGeolocationProvider::HandleError(const nsAString& aErrorMessage)
-{
- return NS_OK;
-}
diff --git a/dom/system/gonk/GonkGPSGeolocationProvider.h b/dom/system/gonk/GonkGPSGeolocationProvider.h
deleted file mode 100644
index 514398edf..000000000
--- a/dom/system/gonk/GonkGPSGeolocationProvider.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef GonkGPSGeolocationProvider_h
-#define GonkGPSGeolocationProvider_h
-
-#include <hardware/gps.h> // for GpsInterface
-#include "nsCOMPtr.h"
-#include "nsIGeolocationProvider.h"
-#include "nsIObserver.h"
-#include "nsIDOMGeoPosition.h"
-#include "nsISettingsService.h"
-
-class nsIThread;
-
-#define GONK_GPS_GEOLOCATION_PROVIDER_CID \
-{ 0x48525ec5, 0x5a7f, 0x490a, { 0x92, 0x77, 0xba, 0x66, 0xe0, 0xd2, 0x2c, 0x8b } }
-
-#define GONK_GPS_GEOLOCATION_PROVIDER_CONTRACTID \
-"@mozilla.org/gonk-gps-geolocation-provider;1"
-
-class GonkGPSGeolocationProvider : public nsIGeolocationProvider
- , public nsIObserver
- , public nsISettingsServiceCallback
-{
-public:
- NS_DECL_THREADSAFE_ISUPPORTS
- NS_DECL_NSIGEOLOCATIONPROVIDER
- NS_DECL_NSIOBSERVER
- NS_DECL_NSISETTINGSSERVICECALLBACK
-
- static already_AddRefed<GonkGPSGeolocationProvider> GetSingleton();
-
-private:
-
- /* Client should use GetSingleton() to get the provider instance. */
- GonkGPSGeolocationProvider();
- GonkGPSGeolocationProvider(const GonkGPSGeolocationProvider &);
- GonkGPSGeolocationProvider & operator = (const GonkGPSGeolocationProvider &);
- virtual ~GonkGPSGeolocationProvider();
-
- static void LocationCallback(GpsLocation* location);
- static void StatusCallback(GpsStatus* status);
- static void SvStatusCallback(GpsSvStatus* sv_info);
- static void NmeaCallback(GpsUtcTime timestamp, const char* nmea, int length);
- static void SetCapabilitiesCallback(uint32_t capabilities);
- static void AcquireWakelockCallback();
- static void ReleaseWakelockCallback();
- static pthread_t CreateThreadCallback(const char* name, void (*start)(void*), void* arg);
- static void RequestUtcTimeCallback();
-
- static GpsCallbacks mCallbacks;
-
- void Init();
- void StartGPS();
- void ShutdownGPS();
- void InjectLocation(double latitude, double longitude, float accuracy);
- void RequestSettingValue(const char* aKey);
-
- const GpsInterface* GetGPSInterface();
-
- static GonkGPSGeolocationProvider* sSingleton;
-
- bool mStarted;
-
- bool mSupportsScheduling;
- bool mObservingSettingsChange;
- bool mSupportsSingleShot;
- bool mSupportsTimeInjection;
-
- const GpsInterface* mGpsInterface;
- nsCOMPtr<nsIGeolocationUpdate> mLocationCallback;
- nsCOMPtr<nsIThread> mInitThread;
- nsCOMPtr<nsIGeolocationProvider> mNetworkLocationProvider;
- nsCOMPtr<nsIDOMGeoPosition> mLastGPSPosition;
-
- class NetworkLocationUpdate : public nsIGeolocationUpdate
- {
- public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIGEOLOCATIONUPDATE
-
- NetworkLocationUpdate() {}
-
- private:
- virtual ~NetworkLocationUpdate() {}
- };
-};
-
-#endif /* GonkGPSGeolocationProvider_h */
diff --git a/dom/system/gonk/MozMtpCommon.h b/dom/system/gonk/MozMtpCommon.h
deleted file mode 100644
index 81c0a3a74..000000000
--- a/dom/system/gonk/MozMtpCommon.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_system_mozmtpcommon_h__
-#define mozilla_system_mozmtpcommon_h__
-
-#include "mozilla/Types.h"
-#include <android/log.h>
-
-#define USE_DEBUG 0
-
-#if USE_DEBUG
-#define MTP_DBG(msg, ...) \
- __android_log_print(ANDROID_LOG_DEBUG, "MozMtp", \
- "%s: " msg, __FUNCTION__, ##__VA_ARGS__)
-#else
-#define MTP_DBG(msg, ...)
-#endif
-
-#define MTP_LOG(msg, ...) \
- __android_log_print(ANDROID_LOG_INFO, "MozMtp", \
- "%s: " msg, __FUNCTION__, ##__VA_ARGS__)
-
-#define MTP_ERR(msg, ...) \
- __android_log_print(ANDROID_LOG_ERROR, "MozMtp", \
- "%s: " msg, __FUNCTION__, ##__VA_ARGS__)
-
-#define BEGIN_MTP_NAMESPACE \
- namespace mozilla { namespace system { namespace mtp {
-#define END_MTP_NAMESPACE \
- } /* namespace mtp */ } /* namespace system */ } /* namespace mozilla */
-#define USING_MTP_NAMESPACE \
- using namespace mozilla::system::mtp;
-
-namespace android {
- class MOZ_EXPORT MtpServer;
- class MOZ_EXPORT MtpStorage;
- class MOZ_EXPORT MtpStringBuffer;
- class MOZ_EXPORT MtpDatabase;
- class MOZ_EXPORT MtpDataPacket;
- class MOZ_EXPORT MtpProperty;
-}
-
-#include <mtp.h>
-#include <MtpDatabase.h>
-#include <MtpObjectInfo.h>
-#include <MtpProperty.h>
-#include <MtpServer.h>
-#include <MtpStorage.h>
-#include <MtpStringBuffer.h>
-#include <MtpTypes.h>
-
-#endif // mozilla_system_mtpcommon_h__
diff --git a/dom/system/gonk/MozMtpDatabase.cpp b/dom/system/gonk/MozMtpDatabase.cpp
deleted file mode 100644
index 29fe23e8d..000000000
--- a/dom/system/gonk/MozMtpDatabase.cpp
+++ /dev/null
@@ -1,1542 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "MozMtpDatabase.h"
-#include "MozMtpServer.h"
-
-#include "base/message_loop.h"
-#include "DeviceStorage.h"
-#include "mozilla/ArrayUtils.h"
-#include "mozilla/AutoRestore.h"
-#include "mozilla/Scoped.h"
-#include "mozilla/Services.h"
-#include "nsIFile.h"
-#include "nsIObserverService.h"
-#include "nsPrintfCString.h"
-#include "nsString.h"
-#include "prio.h"
-
-#include <dirent.h>
-#include <libgen.h>
-#include <utime.h>
-#include <sys/stat.h>
-
-using namespace android;
-using namespace mozilla;
-
-namespace mozilla {
-MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedCloseDir, PRDir, PR_CloseDir)
-}
-
-BEGIN_MTP_NAMESPACE
-
-static const char* kMtpWatcherNotify = "mtp-watcher-notify";
-
-#if 0
-// Some debug code for figuring out deadlocks, if you happen to run into
-// that scenario
-
-class DebugMutexAutoLock: public MutexAutoLock
-{
-public:
- DebugMutexAutoLock(mozilla::Mutex& aMutex)
- : MutexAutoLock(aMutex)
- {
- MTP_LOG("Mutex acquired");
- }
-
- ~DebugMutexAutoLock()
- {
- MTP_LOG("Releasing mutex");
- }
-};
-#define MutexAutoLock MTP_LOG("About to enter mutex"); DebugMutexAutoLock
-
-#endif
-
-static const char *
-ObjectPropertyAsStr(MtpObjectProperty aProperty)
-{
- switch (aProperty) {
- case MTP_PROPERTY_STORAGE_ID: return "MTP_PROPERTY_STORAGE_ID";
- case MTP_PROPERTY_OBJECT_FORMAT: return "MTP_PROPERTY_OBJECT_FORMAT";
- case MTP_PROPERTY_PROTECTION_STATUS: return "MTP_PROPERTY_PROTECTION_STATUS";
- case MTP_PROPERTY_OBJECT_SIZE: return "MTP_PROPERTY_OBJECT_SIZE";
- case MTP_PROPERTY_OBJECT_FILE_NAME: return "MTP_PROPERTY_OBJECT_FILE_NAME";
- case MTP_PROPERTY_DATE_CREATED: return "MTP_PROPERTY_DATE_CREATED";
- case MTP_PROPERTY_DATE_MODIFIED: return "MTP_PROPERTY_DATE_MODIFIED";
- case MTP_PROPERTY_PARENT_OBJECT: return "MTP_PROPERTY_PARENT_OBJECT";
- case MTP_PROPERTY_PERSISTENT_UID: return "MTP_PROPERTY_PERSISTENT_UID";
- case MTP_PROPERTY_NAME: return "MTP_PROPERTY_NAME";
- case MTP_PROPERTY_DATE_ADDED: return "MTP_PROPERTY_DATE_ADDED";
- case MTP_PROPERTY_WIDTH: return "MTP_PROPERTY_WIDTH";
- case MTP_PROPERTY_HEIGHT: return "MTP_PROPERTY_HEIGHT";
- case MTP_PROPERTY_IMAGE_BIT_DEPTH: return "MTP_PROPERTY_IMAGE_BIT_DEPTH";
- case MTP_PROPERTY_DISPLAY_NAME: return "MTP_PROPERTY_DISPLAY_NAME";
- }
- return "MTP_PROPERTY_???";
-}
-
-static char*
-FormatDate(time_t aTime, char *aDateStr, size_t aDateStrSize)
-{
- struct tm tm;
- localtime_r(&aTime, &tm);
- MTP_LOG("(%ld) tm_zone = %s off = %ld", aTime, tm.tm_zone, tm.tm_gmtoff);
- strftime(aDateStr, aDateStrSize, "%Y%m%dT%H%M%S", &tm);
- return aDateStr;
-}
-
-MozMtpDatabase::MozMtpDatabase()
- : mMutex("MozMtpDatabase::mMutex"),
- mDb(mMutex),
- mStorage(mMutex),
- mBeginSendObjectCalled(false)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- // We use the index into the array as the handle. Since zero isn't a valid
- // index, we stick a dummy entry there.
-
- RefPtr<DbEntry> dummy;
-
- MutexAutoLock lock(mMutex);
- mDb.AppendElement(dummy);
-}
-
-//virtual
-MozMtpDatabase::~MozMtpDatabase()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-}
-
-void
-MozMtpDatabase::AddEntry(DbEntry *entry)
-{
- MutexAutoLock lock(mMutex);
-
- entry->mHandle = GetNextHandle();
- MOZ_ASSERT(mDb.Length() == entry->mHandle);
- mDb.AppendElement(entry);
-
- MTP_DBG("Handle: 0x%08x Parent: 0x%08x Path:'%s'",
- entry->mHandle, entry->mParent, entry->mPath.get());
-}
-
-void
-MozMtpDatabase::AddEntryAndNotify(DbEntry* entry, RefCountedMtpServer* aMtpServer)
-{
- AddEntry(entry);
- aMtpServer->sendObjectAdded(entry->mHandle);
-}
-
-void
-MozMtpDatabase::DumpEntries(const char* aLabel)
-{
- MutexAutoLock lock(mMutex);
-
- ProtectedDbArray::size_type numEntries = mDb.Length();
- MTP_LOG("%s: numEntries = %d", aLabel, numEntries);
- ProtectedDbArray::index_type entryIndex;
- for (entryIndex = 1; entryIndex < numEntries; entryIndex++) {
- RefPtr<DbEntry> entry = mDb[entryIndex];
- if (entry) {
- MTP_LOG("%s: mDb[%d]: mHandle: 0x%08x mParent: 0x%08x StorageID: 0x%08x path: '%s'",
- aLabel, entryIndex, entry->mHandle, entry->mParent, entry->mStorageID, entry->mPath.get());
- } else {
- MTP_LOG("%s: mDb[%2d]: entry is NULL", aLabel, entryIndex);
- }
- }
-}
-
-MtpObjectHandle
-MozMtpDatabase::FindEntryByPath(const nsACString& aPath)
-{
- MutexAutoLock lock(mMutex);
-
- ProtectedDbArray::size_type numEntries = mDb.Length();
- ProtectedDbArray::index_type entryIndex;
- for (entryIndex = 1; entryIndex < numEntries; entryIndex++) {
- RefPtr<DbEntry> entry = mDb[entryIndex];
- if (entry && entry->mPath.Equals(aPath)) {
- return entryIndex;
- }
- }
- return 0;
-}
-
-already_AddRefed<MozMtpDatabase::DbEntry>
-MozMtpDatabase::GetEntry(MtpObjectHandle aHandle)
-{
- MutexAutoLock lock(mMutex);
-
- RefPtr<DbEntry> entry;
-
- if (aHandle > 0 && aHandle < mDb.Length()) {
- entry = mDb[aHandle];
- }
- return entry.forget();
-}
-
-void
-MozMtpDatabase::RemoveEntry(MtpObjectHandle aHandle)
-{
- MutexAutoLock lock(mMutex);
- if (!IsValidHandle(aHandle)) {
- return;
- }
-
- RefPtr<DbEntry> removedEntry = mDb[aHandle];
- mDb[aHandle] = nullptr;
- MTP_DBG("0x%08x removed", aHandle);
- // if the entry is not a folder, just return.
- if (removedEntry->mObjectFormat != MTP_FORMAT_ASSOCIATION) {
- return;
- }
-
- // Find out and remove the children of aHandle.
- // Since the index for a directory will always be less than the index of any of its children,
- // we can remove the entire subtree in one pass.
- ProtectedDbArray::size_type numEntries = mDb.Length();
- ProtectedDbArray::index_type entryIndex;
- for (entryIndex = aHandle+1; entryIndex < numEntries; entryIndex++) {
- RefPtr<DbEntry> entry = mDb[entryIndex];
- if (entry && IsValidHandle(entry->mParent) && !mDb[entry->mParent]) {
- mDb[entryIndex] = nullptr;
- MTP_DBG("0x%08x removed", aHandle);
- }
- }
-}
-
-void
-MozMtpDatabase::RemoveEntryAndNotify(MtpObjectHandle aHandle, RefCountedMtpServer* aMtpServer)
-{
- RemoveEntry(aHandle);
- aMtpServer->sendObjectRemoved(aHandle);
-}
-
-void
-MozMtpDatabase::UpdateEntryAndNotify(MtpObjectHandle aHandle, DeviceStorageFile* aFile, RefCountedMtpServer* aMtpServer)
-{
- UpdateEntry(aHandle, aFile);
- aMtpServer->sendObjectAdded(aHandle);
-}
-
-
-void
-MozMtpDatabase::UpdateEntry(MtpObjectHandle aHandle, DeviceStorageFile* aFile)
-{
- MutexAutoLock lock(mMutex);
-
- RefPtr<DbEntry> entry = mDb[aHandle];
-
- int64_t fileSize = 0;
- aFile->mFile->GetFileSize(&fileSize);
- entry->mObjectSize = fileSize;
-
- PRTime dateModifiedMsecs;
- // GetLastModifiedTime returns msecs
- aFile->mFile->GetLastModifiedTime(&dateModifiedMsecs);
- entry->mDateModified = dateModifiedMsecs / PR_MSEC_PER_SEC;
- entry->mDateCreated = entry->mDateModified;
- entry->mDateAdded = entry->mDateModified;
-
- #if USE_DEBUG
- char dateStr[20];
- MTP_DBG("UpdateEntry (0x%08x file %s) modified (%ld) %s",
- entry->mHandle, entry->mPath.get(),
- entry->mDateModified,
- FormatDate(entry->mDateModified, dateStr, sizeof(dateStr)));
- #endif
-}
-
-
-class MtpWatcherNotifyRunnable final : public Runnable
-{
-public:
- MtpWatcherNotifyRunnable(nsACString& aStorageName,
- nsACString& aPath,
- const char* aEventType)
- : mStorageName(aStorageName),
- mPath(aPath),
- mEventType(aEventType)
- {}
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- NS_ConvertUTF8toUTF16 storageName(mStorageName);
- NS_ConvertUTF8toUTF16 path(mPath);
-
- RefPtr<DeviceStorageFile> dsf(
- new DeviceStorageFile(NS_LITERAL_STRING(DEVICESTORAGE_SDCARD),
- storageName, path));
- NS_ConvertUTF8toUTF16 eventType(mEventType);
- nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
-
- MTP_DBG("Sending mtp-watcher-notify %s %s %s",
- mEventType.get(), mStorageName.get(), mPath.get());
-
- obs->NotifyObservers(dsf, kMtpWatcherNotify, eventType.get());
- return NS_OK;
- }
-
-private:
- nsCString mStorageName;
- nsCString mPath;
- nsCString mEventType;
-};
-
-// MtpWatcherNotify is used to tell DeviceStorage when a file was changed
-// through the MTP server.
-void
-MozMtpDatabase::MtpWatcherNotify(DbEntry* aEntry, const char* aEventType)
-{
- // This function gets called from the MozMtpServer::mServerThread
- MOZ_ASSERT(!NS_IsMainThread());
-
- MTP_DBG("file: %s %s", aEntry->mPath.get(), aEventType);
-
- // Tell interested parties that a file was created, deleted, or modified.
-
- RefPtr<StorageEntry> storageEntry;
- {
- MutexAutoLock lock(mMutex);
-
- // FindStorage and the mStorage[] access both need to have the mutex held.
- StorageArray::index_type storageIndex = FindStorage(aEntry->mStorageID);
- if (storageIndex == StorageArray::NoIndex) {
- return;
- }
- storageEntry = mStorage[storageIndex];
- }
-
- // DeviceStorage wants the storageName and the path relative to the root
- // of the storage area, so we need to strip off the storagePath
-
- nsAutoCString relPath(Substring(aEntry->mPath,
- storageEntry->mStoragePath.Length() + 1));
-
- RefPtr<MtpWatcherNotifyRunnable> r =
- new MtpWatcherNotifyRunnable(storageEntry->mStorageName, relPath, aEventType);
- DebugOnly<nsresult> rv = NS_DispatchToMainThread(r);
- MOZ_ASSERT(NS_SUCCEEDED(rv));
-}
-
-// Called to tell the MTP server about new or deleted files,
-void
-MozMtpDatabase::MtpWatcherUpdate(RefCountedMtpServer* aMtpServer,
- DeviceStorageFile* aFile,
- const nsACString& aEventType)
-{
- // Runs on the MtpWatcherUpdate->mIOThread (see MozMtpServer.cpp)
- MOZ_ASSERT(!NS_IsMainThread());
-
- // Figure out which storage the belongs to (if any)
-
- if (!aFile->mFile) {
- // No path - don't bother looking.
- return;
- }
- nsString wideFilePath;
- aFile->mFile->GetPath(wideFilePath);
- NS_ConvertUTF16toUTF8 filePath(wideFilePath);
-
- nsCString evtType(aEventType);
- MTP_LOG("file %s %s", filePath.get(), evtType.get());
-
- MtpObjectHandle entryHandle = FindEntryByPath(filePath);
-
- if (aEventType.EqualsLiteral("modified")) {
- // To update the file information to the newest, we remove the entry for
- // the existing file, then re-add the entry for the file.
-
- if (entryHandle != 0) {
- // Update entry for the file and tell MTP.
- MTP_LOG("About to update handle 0x%08x file %s", entryHandle, filePath.get());
- UpdateEntryAndNotify(entryHandle, aFile, aMtpServer);
- }
- else {
- // Create entry for the file and tell MTP.
- CreateEntryForFileAndNotify(filePath, aFile, aMtpServer);
- }
- return;
- }
-
- if (aEventType.EqualsLiteral("deleted")) {
- if (entryHandle == 0) {
- // The entry has already been removed. We can't tell MTP.
- return;
- }
- MTP_LOG("About to call sendObjectRemoved Handle 0x%08x file %s", entryHandle, filePath.get());
- RemoveEntryAndNotify(entryHandle, aMtpServer);
- return;
- }
-}
-
-nsCString
-MozMtpDatabase::BaseName(const nsCString& path)
-{
- nsCOMPtr<nsIFile> file;
- NS_NewNativeLocalFile(path, false, getter_AddRefs(file));
- if (file) {
- nsCString leafName;
- file->GetNativeLeafName(leafName);
- return leafName;
- }
- return path;
-}
-
-static nsCString
-GetPathWithoutFileName(const nsCString& aFullPath)
-{
- nsCString path;
-
- int32_t offset = aFullPath.RFindChar('/');
- if (offset != kNotFound) {
- // The trailing slash will be as part of 'path'
- path = StringHead(aFullPath, offset + 1);
- }
-
- MTP_LOG("returning '%s'", path.get());
-
- return path;
-}
-
-void
-MozMtpDatabase::CreateEntryForFileAndNotify(const nsACString& aPath,
- DeviceStorageFile* aFile,
- RefCountedMtpServer* aMtpServer)
-{
- // Find the StorageID that this path corresponds to.
-
- nsCString remainder;
- MtpStorageID storageID = FindStorageIDFor(aPath, remainder);
- if (storageID == 0) {
- // The path in question isn't for a storage area we're monitoring.
- nsCString path(aPath);
- return;
- }
-
- bool exists = false;
- aFile->mFile->Exists(&exists);
- if (!exists) {
- // File doesn't exist, no sense telling MTP about it.
- // This could happen if Device Storage created and deleted a file right
- // away. Since the notifications wind up being async, the file might
- // not exist any more.
- return;
- }
-
- // Now walk the remaining directories, finding or creating as required.
-
- MtpObjectHandle parent = MTP_PARENT_ROOT;
- bool doFind = true;
- int32_t offset = aPath.Length() - remainder.Length();
- int32_t slash;
-
- do {
- nsDependentCSubstring component;
- slash = aPath.FindChar('/', offset);
- if (slash == kNotFound) {
- component.Rebind(aPath, 0, aPath.Length());
- } else {
- component.Rebind(aPath, 0 , slash);
- }
- if (doFind) {
- MtpObjectHandle entryHandle = FindEntryByPath(component);
- if (entryHandle != 0) {
- // We found an entry.
- parent = entryHandle;
- offset = slash + 1 ;
- continue;
- }
- }
-
- // We've got a directory component that doesn't exist. This means that all
- // further subdirectories won't exist either, so we can skip searching
- // for them.
- doFind = false;
-
- // This directory and the file don't exist, create them
-
- RefPtr<DbEntry> entry = new DbEntry;
-
- entry->mStorageID = storageID;
- entry->mObjectName = Substring(aPath, offset, slash - offset);
- entry->mParent = parent;
- entry->mDisplayName = entry->mObjectName;
- entry->mPath = component;
-
- if (slash == kNotFound) {
- // No slash - this is the file component
- entry->mObjectFormat = MTP_FORMAT_DEFINED;
-
- int64_t fileSize = 0;
- aFile->mFile->GetFileSize(&fileSize);
- entry->mObjectSize = fileSize;
-
- // Note: Even though PRTime records usec, GetLastModifiedTime returns
- // msecs.
- PRTime dateModifiedMsecs;
- aFile->mFile->GetLastModifiedTime(&dateModifiedMsecs);
- entry->mDateModified = dateModifiedMsecs / PR_MSEC_PER_SEC;
- } else {
- // Found a slash, this makes this a directory component
- entry->mObjectFormat = MTP_FORMAT_ASSOCIATION;
- entry->mObjectSize = 0;
- time(&entry->mDateModified);
- }
- entry->mDateCreated = entry->mDateModified;
- entry->mDateAdded = entry->mDateModified;
-
- AddEntryAndNotify(entry, aMtpServer);
- MTP_LOG("About to call sendObjectAdded Handle 0x%08x file %s", entry->mHandle, entry->mPath.get());
-
- parent = entry->mHandle;
- offset = slash + 1;
- } while (slash != kNotFound);
-
- return;
-}
-
-void
-MozMtpDatabase::AddDirectory(MtpStorageID aStorageID,
- const char* aPath,
- MtpObjectHandle aParent)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- ScopedCloseDir dir;
-
- if (!(dir = PR_OpenDir(aPath))) {
- MTP_ERR("Unable to open directory '%s'", aPath);
- return;
- }
-
- PRDirEntry* dirEntry;
- while ((dirEntry = PR_ReadDir(dir, PR_SKIP_BOTH))) {
- nsPrintfCString filename("%s/%s", aPath, dirEntry->name);
- PRFileInfo64 fileInfo;
- if (PR_GetFileInfo64(filename.get(), &fileInfo) != PR_SUCCESS) {
- MTP_ERR("Unable to retrieve file information for '%s'", filename.get());
- continue;
- }
-
- RefPtr<DbEntry> entry = new DbEntry;
-
- entry->mStorageID = aStorageID;
- entry->mParent = aParent;
- entry->mObjectName = dirEntry->name;
- entry->mDisplayName = dirEntry->name;
- entry->mPath = filename;
-
- // PR_GetFileInfo64 returns timestamps in usecs
- entry->mDateModified = fileInfo.modifyTime / PR_USEC_PER_SEC;
- entry->mDateCreated = fileInfo.creationTime / PR_USEC_PER_SEC;
- time(&entry->mDateAdded);
-
- if (fileInfo.type == PR_FILE_FILE) {
- entry->mObjectFormat = MTP_FORMAT_DEFINED;
- //TODO: Check how 64-bit filesize are dealt with
- entry->mObjectSize = fileInfo.size;
- AddEntry(entry);
- } else if (fileInfo.type == PR_FILE_DIRECTORY) {
- entry->mObjectFormat = MTP_FORMAT_ASSOCIATION;
- entry->mObjectSize = 0;
- AddEntry(entry);
- AddDirectory(aStorageID, filename.get(), entry->mHandle);
- }
- }
-}
-
-MozMtpDatabase::StorageArray::index_type
-MozMtpDatabase::FindStorage(MtpStorageID aStorageID)
-{
- // Currently, this routine is called from MozMtpDatabase::RemoveStorage
- // and MozMtpDatabase::MtpWatcherNotify, which both hold mMutex.
-
- StorageArray::size_type numStorages = mStorage.Length();
- StorageArray::index_type storageIndex;
-
- for (storageIndex = 0; storageIndex < numStorages; storageIndex++) {
- RefPtr<StorageEntry> storage = mStorage[storageIndex];
- if (storage->mStorageID == aStorageID) {
- return storageIndex;
- }
- }
- return StorageArray::NoIndex;
-}
-
-// Find the storage ID for the storage area that contains aPath.
-MtpStorageID
-MozMtpDatabase::FindStorageIDFor(const nsACString& aPath, nsCSubstring& aRemainder)
-{
- MutexAutoLock lock(mMutex);
-
- aRemainder.Truncate();
-
- StorageArray::size_type numStorages = mStorage.Length();
- StorageArray::index_type storageIndex;
-
- for (storageIndex = 0; storageIndex < numStorages; storageIndex++) {
- RefPtr<StorageEntry> storage = mStorage[storageIndex];
- if (StringHead(aPath, storage->mStoragePath.Length()).Equals(storage->mStoragePath)) {
- if (aPath.Length() == storage->mStoragePath.Length()) {
- return storage->mStorageID;
- }
- if (aPath[storage->mStoragePath.Length()] == '/') {
- aRemainder = Substring(aPath, storage->mStoragePath.Length() + 1);
- return storage->mStorageID;
- }
- }
- }
- return 0;
-}
-
-void
-MozMtpDatabase::AddStorage(MtpStorageID aStorageID,
- const char* aPath,
- const char* aName)
-{
- // This is called on the IOThread from MozMtpStorage::StorageAvailable
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- MTP_DBG("StorageID: 0x%08x aPath: '%s' aName: '%s'",
- aStorageID, aPath, aName);
-
- PRFileInfo fileInfo;
- if (PR_GetFileInfo(aPath, &fileInfo) != PR_SUCCESS) {
- MTP_ERR("'%s' doesn't exist", aPath);
- return;
- }
- if (fileInfo.type != PR_FILE_DIRECTORY) {
- MTP_ERR("'%s' isn't a directory", aPath);
- return;
- }
-
- RefPtr<StorageEntry> storageEntry = new StorageEntry;
-
- storageEntry->mStorageID = aStorageID;
- storageEntry->mStoragePath = aPath;
- storageEntry->mStorageName = aName;
- {
- MutexAutoLock lock(mMutex);
- mStorage.AppendElement(storageEntry);
- }
-
- AddDirectory(aStorageID, aPath, MTP_PARENT_ROOT);
- {
- MutexAutoLock lock(mMutex);
- MTP_LOG("added %d items from tree '%s'", mDb.Length(), aPath);
- }
-}
-
-void
-MozMtpDatabase::RemoveStorage(MtpStorageID aStorageID)
-{
- MutexAutoLock lock(mMutex);
-
- // This is called on the IOThread from MozMtpStorage::StorageAvailable
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- ProtectedDbArray::size_type numEntries = mDb.Length();
- ProtectedDbArray::index_type entryIndex;
- for (entryIndex = 1; entryIndex < numEntries; entryIndex++) {
- RefPtr<DbEntry> entry = mDb[entryIndex];
- if (entry && entry->mStorageID == aStorageID) {
- mDb[entryIndex] = nullptr;
- }
- }
- StorageArray::index_type storageIndex = FindStorage(aStorageID);
- if (storageIndex != StorageArray::NoIndex) {
- mStorage.RemoveElementAt(storageIndex);
- }
-}
-
-// called from SendObjectInfo to reserve a database entry for the incoming file
-//virtual
-MtpObjectHandle
-MozMtpDatabase::beginSendObject(const char* aPath,
- MtpObjectFormat aFormat,
- MtpObjectHandle aParent,
- MtpStorageID aStorageID,
- uint64_t aSize,
- time_t aModified)
-{
- // If MtpServer::doSendObjectInfo receives a request with a parent of
- // MTP_PARENT_ROOT, then it fills in aPath with the fully qualified path
- // and then passes in a parent of zero.
-
- if (aParent == 0) {
- // Undo what doSendObjectInfo did
- aParent = MTP_PARENT_ROOT;
- }
-
- RefPtr<DbEntry> entry = new DbEntry;
-
- entry->mStorageID = aStorageID;
- entry->mParent = aParent;
- entry->mPath = aPath;
- entry->mObjectName = BaseName(entry->mPath);
- entry->mDisplayName = entry->mObjectName;
- entry->mObjectFormat = aFormat;
- entry->mObjectSize = aSize;
-
- if (aModified != 0) {
- // Currently, due to the way that parseDateTime is coded in
- // frameworks/av/media/mtp/MtpUtils.cpp, aModified winds up being the number
- // of seconds from the epoch in local time, rather than UTC time. So we
- // need to convert it back to being relative to UTC since that's what linux
- // expects time_t to contain.
- //
- // In more concrete testable terms, if the host parses 2015-08-02 02:22:00
- // as a local time in the Pacific timezone, aModified will come to us as
- // 1438482120.
- //
- // What we want is what mktime would pass us with the same date. Using python
- // (because its simple) with the current timezone set to be America/Vancouver:
- //
- // >>> import time
- // >>> time.mktime((2015, 8, 2, 2, 22, 0, 0, 0, -1))
- // 1438507320.0
- // >>> time.localtime(1438507320)
- // time.struct_time(tm_year=2015, tm_mon=8, tm_mday=2, tm_hour=2, tm_min=22, tm_sec=0, tm_wday=6, tm_yday=214, tm_isdst=1)
- //
- // Currently, when a file has a modification time of 2015-08-22 02:22:00 PDT
- // then aModified will come in as 1438482120 which corresponds to
- // 2015-08-22 02:22:00 UTC
-
- struct tm tm;
- if (gmtime_r(&aModified, &tm) != NULL) {
- // GMT always comes back with tm_isdst = 0, so we set it to -1 in order
- // to have mktime figure out dst based on the date.
- tm.tm_isdst = -1;
- aModified = mktime(&tm);
- if (aModified == (time_t)-1) {
- aModified = 0;
- }
- } else {
- aModified = 0;
- }
- }
- if (aModified == 0) {
- // The ubuntu host doesn't pass in the modified/created times in the
- // SENDOBJECT packet, so aModified winds up being zero. About the best
- // we can do with that is to use the current time.
- time(&aModified);
- }
-
- // And just an FYI for anybody else looking at timestamps. Under OSX you
- // need to use the Android File Transfer program to copy files into the
- // phone. That utility passes in both date modified and date created
- // timestamps, but they're both equal to the time that the file was copied
- // and not the times that are associated with the files.
-
- // Now we have aModified in a traditional time_t format, which is the number
- // of seconds from the UTC epoch.
-
- entry->mDateModified = aModified;
- entry->mDateCreated = entry->mDateModified;
- entry->mDateAdded = entry->mDateModified;
-
- AddEntry(entry);
-
- #if USE_DEBUG
- char dateStr[20];
- MTP_LOG("Handle: 0x%08x Parent: 0x%08x Path: '%s' aModified %ld %s",
- entry->mHandle, aParent, aPath, aModified,
- FormatDate(entry->mDateModified, dateStr, sizeof(dateStr)));
- #endif
-
- mBeginSendObjectCalled = true;
- return entry->mHandle;
-}
-
-// called to report success or failure of the SendObject file transfer
-// success should signal a notification of the new object's creation,
-// failure should remove the database entry created in beginSendObject
-
-//virtual
-void
-MozMtpDatabase::endSendObject(const char* aPath,
- MtpObjectHandle aHandle,
- MtpObjectFormat aFormat,
- bool aSucceeded)
-{
- MTP_LOG("Handle: 0x%08x Path: '%s'", aHandle, aPath);
-
- if (aSucceeded) {
- RefPtr<DbEntry> entry = GetEntry(aHandle);
- if (entry) {
- // The android MTP server only copies the data in, it doesn't set the
- // modified timestamp, so we do that here.
-
- struct utimbuf new_times;
- struct stat sb;
-
- char dateStr[20];
- MTP_LOG("Path: '%s' setting modified time to (%ld) %s",
- entry->mPath.get(), entry->mDateModified,
- FormatDate(entry->mDateModified, dateStr, sizeof(dateStr)));
-
- stat(entry->mPath.get(), &sb);
- new_times.actime = sb.st_atime; // Preserve atime
- new_times.modtime = entry->mDateModified;
- utime(entry->mPath.get(), &new_times);
-
- MtpWatcherNotify(entry, "modified");
- }
- } else {
- RemoveEntry(aHandle);
- }
- mBeginSendObjectCalled = false;
-}
-
-//virtual
-MtpObjectHandleList*
-MozMtpDatabase::getObjectList(MtpStorageID aStorageID,
- MtpObjectFormat aFormat,
- MtpObjectHandle aParent)
-{
- MTP_LOG("StorageID: 0x%08x Format: 0x%04x Parent: 0x%08x",
- aStorageID, aFormat, aParent);
-
- // aStorageID == 0xFFFFFFFF for all storage
- // aFormat == 0 for all formats
- // aParent == 0xFFFFFFFF for objects with no parents
- // aParent == 0 for all objects
-
- //TODO: Optimize
-
- UniquePtr<MtpObjectHandleList> list(new MtpObjectHandleList());
-
- MutexAutoLock lock(mMutex);
-
- ProtectedDbArray::size_type numEntries = mDb.Length();
- ProtectedDbArray::index_type entryIndex;
- for (entryIndex = 1; entryIndex < numEntries; entryIndex++) {
- RefPtr<DbEntry> entry = mDb[entryIndex];
- if (entry &&
- (aStorageID == 0xFFFFFFFF || entry->mStorageID == aStorageID) &&
- (aFormat == 0 || entry->mObjectFormat == aFormat) &&
- (aParent == 0 || entry->mParent == aParent)) {
- list->push(entry->mHandle);
- }
- }
- MTP_LOG(" returning %d items", list->size());
- return list.release();
-}
-
-//virtual
-int
-MozMtpDatabase::getNumObjects(MtpStorageID aStorageID,
- MtpObjectFormat aFormat,
- MtpObjectHandle aParent)
-{
- MTP_LOG("");
-
- // aStorageID == 0xFFFFFFFF for all storage
- // aFormat == 0 for all formats
- // aParent == 0xFFFFFFFF for objects with no parents
- // aParent == 0 for all objects
-
- int count = 0;
-
- MutexAutoLock lock(mMutex);
-
- ProtectedDbArray::size_type numEntries = mDb.Length();
- ProtectedDbArray::index_type entryIndex;
- for (entryIndex = 1; entryIndex < numEntries; entryIndex++) {
- RefPtr<DbEntry> entry = mDb[entryIndex];
- if (entry &&
- (aStorageID == 0xFFFFFFFF || entry->mStorageID == aStorageID) &&
- (aFormat == 0 || entry->mObjectFormat == aFormat) &&
- (aParent == 0 || entry->mParent == aParent)) {
- count++;
- }
- }
-
- MTP_LOG(" returning %d items", count);
- return count;
-}
-
-//virtual
-MtpObjectFormatList*
-MozMtpDatabase::getSupportedPlaybackFormats()
-{
- static const uint16_t init_data[] = {MTP_FORMAT_UNDEFINED, MTP_FORMAT_ASSOCIATION,
- MTP_FORMAT_TEXT, MTP_FORMAT_HTML, MTP_FORMAT_WAV,
- MTP_FORMAT_MP3, MTP_FORMAT_MPEG, MTP_FORMAT_EXIF_JPEG,
- MTP_FORMAT_TIFF_EP, MTP_FORMAT_BMP, MTP_FORMAT_GIF,
- MTP_FORMAT_PNG, MTP_FORMAT_TIFF, MTP_FORMAT_WMA,
- MTP_FORMAT_OGG, MTP_FORMAT_AAC, MTP_FORMAT_MP4_CONTAINER,
- MTP_FORMAT_MP2, MTP_FORMAT_3GP_CONTAINER, MTP_FORMAT_FLAC};
-
- MtpObjectFormatList *list = new MtpObjectFormatList();
- list->appendArray(init_data, MOZ_ARRAY_LENGTH(init_data));
-
- MTP_LOG("returning Supported Playback Formats");
- return list;
-}
-
-//virtual
-MtpObjectFormatList*
-MozMtpDatabase::getSupportedCaptureFormats()
-{
- static const uint16_t init_data[] = {MTP_FORMAT_ASSOCIATION, MTP_FORMAT_PNG};
-
- MtpObjectFormatList *list = new MtpObjectFormatList();
- list->appendArray(init_data, MOZ_ARRAY_LENGTH(init_data));
- MTP_LOG("returning MTP_FORMAT_ASSOCIATION, MTP_FORMAT_PNG");
- return list;
-}
-
-static const MtpObjectProperty sSupportedObjectProperties[] =
-{
- MTP_PROPERTY_STORAGE_ID,
- MTP_PROPERTY_OBJECT_FORMAT,
- MTP_PROPERTY_PROTECTION_STATUS, // UINT16 - always 0
- MTP_PROPERTY_OBJECT_SIZE,
- MTP_PROPERTY_OBJECT_FILE_NAME, // just the filename - no directory
- MTP_PROPERTY_NAME,
- MTP_PROPERTY_DATE_CREATED,
- MTP_PROPERTY_DATE_MODIFIED,
- MTP_PROPERTY_PARENT_OBJECT,
- MTP_PROPERTY_PERSISTENT_UID,
- MTP_PROPERTY_DATE_ADDED,
-};
-
-//virtual
-MtpObjectPropertyList*
-MozMtpDatabase::getSupportedObjectProperties(MtpObjectFormat aFormat)
-{
- MTP_LOG("");
- MtpObjectPropertyList *list = new MtpObjectPropertyList();
- list->appendArray(sSupportedObjectProperties,
- MOZ_ARRAY_LENGTH(sSupportedObjectProperties));
- return list;
-}
-
-//virtual
-MtpDevicePropertyList*
-MozMtpDatabase::getSupportedDeviceProperties()
-{
- MTP_LOG("");
- static const uint16_t init_data[] = { MTP_DEVICE_PROPERTY_UNDEFINED };
-
- MtpDevicePropertyList *list = new MtpDevicePropertyList();
- list->appendArray(init_data, MOZ_ARRAY_LENGTH(init_data));
- return list;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::getObjectPropertyValue(MtpObjectHandle aHandle,
- MtpObjectProperty aProperty,
- MtpDataPacket& aPacket)
-{
- RefPtr<DbEntry> entry = GetEntry(aHandle);
- if (!entry) {
- MTP_ERR("Invalid Handle: 0x%08x", aHandle);
- return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
- }
-
- MTP_LOG("Handle: 0x%08x '%s' Property: %s 0x%08x",
- aHandle, entry->mDisplayName.get(), ObjectPropertyAsStr(aProperty), aProperty);
-
- switch (aProperty)
- {
- case MTP_PROPERTY_STORAGE_ID: aPacket.putUInt32(entry->mStorageID); break;
- case MTP_PROPERTY_PARENT_OBJECT: aPacket.putUInt32(entry->mParent); break;
- case MTP_PROPERTY_OBJECT_FORMAT: aPacket.putUInt16(entry->mObjectFormat); break;
- case MTP_PROPERTY_OBJECT_SIZE: aPacket.putUInt64(entry->mObjectSize); break;
- case MTP_PROPERTY_DISPLAY_NAME: aPacket.putString(entry->mDisplayName.get()); break;
- case MTP_PROPERTY_PERSISTENT_UID:
- // the same as aPacket.putUInt128
- aPacket.putUInt64(entry->mHandle);
- aPacket.putUInt64(entry->mStorageID);
- break;
- case MTP_PROPERTY_NAME: aPacket.putString(entry->mDisplayName.get()); break;
-
- default:
- MTP_LOG("Invalid Property: 0x%08x", aProperty);
- return MTP_RESPONSE_INVALID_OBJECT_PROP_CODE;
- }
-
- return MTP_RESPONSE_OK;
-}
-
-static int
-GetTypeOfObjectProp(MtpObjectProperty aProperty)
-{
- struct PropertyTableEntry {
- MtpObjectProperty property;
- int type;
- };
-
- static const PropertyTableEntry kObjectPropertyTable[] = {
- {MTP_PROPERTY_STORAGE_ID, MTP_TYPE_UINT32 },
- {MTP_PROPERTY_OBJECT_FORMAT, MTP_TYPE_UINT16 },
- {MTP_PROPERTY_PROTECTION_STATUS, MTP_TYPE_UINT16 },
- {MTP_PROPERTY_OBJECT_SIZE, MTP_TYPE_UINT64 },
- {MTP_PROPERTY_OBJECT_FILE_NAME, MTP_TYPE_STR },
- {MTP_PROPERTY_DATE_CREATED, MTP_TYPE_STR },
- {MTP_PROPERTY_DATE_MODIFIED, MTP_TYPE_STR },
- {MTP_PROPERTY_PARENT_OBJECT, MTP_TYPE_UINT32 },
- {MTP_PROPERTY_DISPLAY_NAME, MTP_TYPE_STR },
- {MTP_PROPERTY_NAME, MTP_TYPE_STR },
- {MTP_PROPERTY_PERSISTENT_UID, MTP_TYPE_UINT128 },
- {MTP_PROPERTY_DATE_ADDED, MTP_TYPE_STR },
- };
-
- int count = sizeof(kObjectPropertyTable) / sizeof(kObjectPropertyTable[0]);
- const PropertyTableEntry* entryProp = kObjectPropertyTable;
- int type = 0;
-
- for (int i = 0; i < count; ++i, ++entryProp) {
- if (entryProp->property == aProperty) {
- type = entryProp->type;
- break;
- }
- }
-
- return type;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::setObjectPropertyValue(MtpObjectHandle aHandle,
- MtpObjectProperty aProperty,
- MtpDataPacket& aPacket)
-{
- MTP_LOG("Handle: 0x%08x Property: 0x%08x", aHandle, aProperty);
-
- // Only support file name change
- if (aProperty != MTP_PROPERTY_OBJECT_FILE_NAME) {
- MTP_ERR("property 0x%x not supported", aProperty);
- return MTP_RESPONSE_OBJECT_PROP_NOT_SUPPORTED;
- }
-
- if (GetTypeOfObjectProp(aProperty) != MTP_TYPE_STR) {
- MTP_ERR("property type 0x%x not supported", GetTypeOfObjectProp(aProperty));
- return MTP_RESPONSE_GENERAL_ERROR;
- }
-
- RefPtr<DbEntry> entry = GetEntry(aHandle);
- if (!entry) {
- MTP_ERR("Invalid Handle: 0x%08x", aHandle);
- return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
- }
-
- MtpStringBuffer buf;
- aPacket.getString(buf);
-
- nsDependentCString newFileName(buf);
- nsCString newFileFullPath(GetPathWithoutFileName(entry->mPath) + newFileName);
-
- if (PR_Rename(entry->mPath.get(), newFileFullPath.get()) != PR_SUCCESS) {
- MTP_ERR("Failed to rename '%s' to '%s'",
- entry->mPath.get(), newFileFullPath.get());
- return MTP_RESPONSE_GENERAL_ERROR;
- }
-
- MTP_LOG("renamed '%s' to '%s'", entry->mPath.get(), newFileFullPath.get());
-
- entry->mPath = newFileFullPath;
- entry->mObjectName = BaseName(entry->mPath);
- entry->mDisplayName = entry->mObjectName;
-
- return MTP_RESPONSE_OK;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::getDevicePropertyValue(MtpDeviceProperty aProperty,
- MtpDataPacket& aPacket)
-{
- MTP_LOG("(GENERAL ERROR)");
- return MTP_RESPONSE_GENERAL_ERROR;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::setDevicePropertyValue(MtpDeviceProperty aProperty,
- MtpDataPacket& aPacket)
-{
- MTP_LOG("(NOT SUPPORTED)");
- return MTP_RESPONSE_OPERATION_NOT_SUPPORTED;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::resetDeviceProperty(MtpDeviceProperty aProperty)
-{
- MTP_LOG("(NOT SUPPORTED)");
- return MTP_RESPONSE_OPERATION_NOT_SUPPORTED;
-}
-
-void
-MozMtpDatabase::QueryEntries(MozMtpDatabase::MatchType aMatchType,
- uint32_t aMatchField1,
- uint32_t aMatchField2,
- UnprotectedDbArray &result)
-{
- MutexAutoLock lock(mMutex);
-
- ProtectedDbArray::size_type numEntries = mDb.Length();
- ProtectedDbArray::index_type entryIdx;
- RefPtr<DbEntry> entry;
-
- result.Clear();
-
- switch (aMatchType) {
-
- case MatchAll:
- for (entryIdx = 0; entryIdx < numEntries; entryIdx++) {
- if (mDb[entryIdx]) {
- result.AppendElement(mDb[entryIdx]);
- }
- }
- break;
-
- case MatchHandle:
- for (entryIdx = 0; entryIdx < numEntries; entryIdx++) {
- entry = mDb[entryIdx];
- if (entry && entry->mHandle == aMatchField1) {
- result.AppendElement(entry);
- // Handles are unique - return the one that we found.
- return;
- }
- }
- break;
-
- case MatchParent:
- for (entryIdx = 0; entryIdx < numEntries; entryIdx++) {
- entry = mDb[entryIdx];
- if (entry && entry->mParent == aMatchField1) {
- result.AppendElement(entry);
- }
- }
- break;
-
- case MatchFormat:
- for (entryIdx = 0; entryIdx < numEntries; entryIdx++) {
- entry = mDb[entryIdx];
- if (entry && entry->mObjectFormat == aMatchField1) {
- result.AppendElement(entry);
- }
- }
- break;
-
- case MatchHandleFormat:
- for (entryIdx = 0; entryIdx < numEntries; entryIdx++) {
- entry = mDb[entryIdx];
- if (entry && entry->mHandle == aMatchField1) {
- if (entry->mObjectFormat == aMatchField2) {
- result.AppendElement(entry);
- }
- // Only 1 entry can match my aHandle. So we can return early.
- return;
- }
- }
- break;
-
- case MatchParentFormat:
- for (entryIdx = 0; entryIdx < numEntries; entryIdx++) {
- entry = mDb[entryIdx];
- if (entry && entry->mParent == aMatchField1 && entry->mObjectFormat == aMatchField2) {
- result.AppendElement(entry);
- }
- }
- break;
-
- default:
- MOZ_ASSERT(!"Invalid MatchType");
- }
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::getObjectPropertyList(MtpObjectHandle aHandle,
- uint32_t aFormat,
- uint32_t aProperty,
- int aGroupCode,
- int aDepth,
- MtpDataPacket& aPacket)
-{
- MTP_LOG("Handle: 0x%08x Format: 0x%08x aProperty: 0x%08x aGroupCode: %d aDepth %d",
- aHandle, aFormat, aProperty, aGroupCode, aDepth);
-
- if (aDepth > 1) {
- return MTP_RESPONSE_SPECIFICATION_BY_DEPTH_UNSUPPORTED;
- }
- if (aGroupCode != 0) {
- return MTP_RESPONSE_SPECIFICATION_BY_GROUP_UNSUPPORTED;
- }
-
- MatchType matchType = MatchAll;
- uint32_t matchField1 = 0;
- uint32_t matchField2 = 0;
-
- // aHandle == 0 implies all objects at the root level
- // further specificed by aFormat and/or aDepth
-
- if (aFormat == 0) {
- if (aHandle == 0xffffffff) {
- // select all objects
- matchType = MatchAll;
- } else {
- if (aDepth == 1) {
- // select objects whose Parent matches aHandle
- matchType = MatchParent;
- matchField1 = aHandle;
- } else {
- // select object whose handle matches aHandle
- matchType = MatchHandle;
- matchField1 = aHandle;
- }
- }
- } else {
- if (aHandle == 0xffffffff) {
- // select all objects whose format matches aFormat
- matchType = MatchFormat;
- matchField1 = aFormat;
- } else {
- if (aDepth == 1) {
- // select objects whose Parent is aHandle and format matches aFormat
- matchType = MatchParentFormat;
- matchField1 = aHandle;
- matchField2 = aFormat;
- } else {
- // select objects whose handle is aHandle and format matches aFormat
- matchType = MatchHandleFormat;
- matchField1 = aHandle;
- matchField2 = aFormat;
- }
- }
- }
-
- UnprotectedDbArray result;
- QueryEntries(matchType, matchField1, matchField2, result);
-
- const MtpObjectProperty *objectPropertyList;
- size_t numObjectProperties = 0;
- MtpObjectProperty objectProperty;
-
- if (aProperty == 0xffffffff) {
- // return all supported properties
- numObjectProperties = MOZ_ARRAY_LENGTH(sSupportedObjectProperties);
- objectPropertyList = sSupportedObjectProperties;
- } else {
- // return property indicated by aProperty
- numObjectProperties = 1;
- objectProperty = aProperty;
- objectPropertyList = &objectProperty;
- }
-
- UnprotectedDbArray::size_type numEntries = result.Length();
- UnprotectedDbArray::index_type entryIdx;
-
- char dateStr[20];
-
- aPacket.putUInt32(numObjectProperties * numEntries);
- for (entryIdx = 0; entryIdx < numEntries; entryIdx++) {
- RefPtr<DbEntry> entry = result[entryIdx];
-
- for (size_t propertyIdx = 0; propertyIdx < numObjectProperties; propertyIdx++) {
- aPacket.putUInt32(entry->mHandle);
- MtpObjectProperty prop = objectPropertyList[propertyIdx];
- aPacket.putUInt16(prop);
- switch (prop) {
-
- case MTP_PROPERTY_STORAGE_ID:
- aPacket.putUInt16(MTP_TYPE_UINT32);
- aPacket.putUInt32(entry->mStorageID);
- break;
-
- case MTP_PROPERTY_PARENT_OBJECT:
- aPacket.putUInt16(MTP_TYPE_UINT32);
- aPacket.putUInt32(entry->mParent);
- break;
-
- case MTP_PROPERTY_PERSISTENT_UID:
- aPacket.putUInt16(MTP_TYPE_UINT128);
- // the same as aPacket.putUInt128
- aPacket.putUInt64(entry->mHandle);
- aPacket.putUInt64(entry->mStorageID);
- break;
-
- case MTP_PROPERTY_OBJECT_FORMAT:
- aPacket.putUInt16(MTP_TYPE_UINT16);
- aPacket.putUInt16(entry->mObjectFormat);
- break;
-
- case MTP_PROPERTY_OBJECT_SIZE:
- aPacket.putUInt16(MTP_TYPE_UINT64);
- aPacket.putUInt64(entry->mObjectSize);
- break;
-
- case MTP_PROPERTY_OBJECT_FILE_NAME:
- case MTP_PROPERTY_NAME:
- aPacket.putUInt16(MTP_TYPE_STR);
- aPacket.putString(entry->mObjectName.get());
- break;
-
- case MTP_PROPERTY_PROTECTION_STATUS:
- aPacket.putUInt16(MTP_TYPE_UINT16);
- aPacket.putUInt16(0); // 0 = No Protection
- break;
-
- case MTP_PROPERTY_DATE_CREATED: {
- aPacket.putUInt16(MTP_TYPE_STR);
- aPacket.putString(FormatDate(entry->mDateCreated, dateStr, sizeof(dateStr)));
- MTP_LOG("mDateCreated: (%ld) %s", entry->mDateCreated, dateStr);
- break;
- }
-
- case MTP_PROPERTY_DATE_MODIFIED: {
- aPacket.putUInt16(MTP_TYPE_STR);
- aPacket.putString(FormatDate(entry->mDateModified, dateStr, sizeof(dateStr)));
- MTP_LOG("mDateModified: (%ld) %s", entry->mDateModified, dateStr);
- break;
- }
-
- case MTP_PROPERTY_DATE_ADDED: {
- aPacket.putUInt16(MTP_TYPE_STR);
- aPacket.putString(FormatDate(entry->mDateAdded, dateStr, sizeof(dateStr)));
- MTP_LOG("mDateAdded: (%ld) %s", entry->mDateAdded, dateStr);
- break;
- }
-
- default:
- MTP_ERR("Unrecognized property code: %u", prop);
- return MTP_RESPONSE_GENERAL_ERROR;
- }
- }
- }
- return MTP_RESPONSE_OK;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::getObjectInfo(MtpObjectHandle aHandle,
- MtpObjectInfo& aInfo)
-{
- RefPtr<DbEntry> entry = GetEntry(aHandle);
- if (!entry) {
- MTP_ERR("Handle 0x%08x is invalid", aHandle);
- return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
- }
-
- MTP_LOG("Handle: 0x%08x Display:'%s' Object:'%s'", aHandle, entry->mDisplayName.get(), entry->mObjectName.get());
-
- aInfo.mHandle = aHandle;
- aInfo.mStorageID = entry->mStorageID;
- aInfo.mFormat = entry->mObjectFormat;
- aInfo.mProtectionStatus = 0x0;
-
- if (entry->mObjectSize > 0xFFFFFFFFuLL) {
- aInfo.mCompressedSize = 0xFFFFFFFFuLL;
- } else {
- aInfo.mCompressedSize = entry->mObjectSize;
- }
-
- aInfo.mThumbFormat = MTP_FORMAT_UNDEFINED;
- aInfo.mThumbCompressedSize = 0;
- aInfo.mThumbPixWidth = 0;
- aInfo.mThumbPixHeight = 0;
- aInfo.mImagePixWidth = 0;
- aInfo.mImagePixHeight = 0;
- aInfo.mImagePixDepth = 0;
- aInfo.mParent = entry->mParent;
- aInfo.mAssociationType = 0;
- aInfo.mAssociationDesc = 0;
- aInfo.mSequenceNumber = 0;
- aInfo.mName = ::strdup(entry->mObjectName.get());
- aInfo.mDateCreated = entry->mDateCreated;
- aInfo.mDateModified = entry->mDateModified;
-
- MTP_LOG("aInfo.mDateCreated = %ld entry->mDateCreated = %ld",
- aInfo.mDateCreated, entry->mDateCreated);
- MTP_LOG("aInfo.mDateModified = %ld entry->mDateModified = %ld",
- aInfo.mDateModified, entry->mDateModified);
-
- aInfo.mKeywords = ::strdup("fxos,touch");
-
- return MTP_RESPONSE_OK;
-}
-
-//virtual
-void*
-MozMtpDatabase::getThumbnail(MtpObjectHandle aHandle, size_t& aOutThumbSize)
-{
- MTP_LOG("Handle: 0x%08x (returning nullptr)", aHandle);
-
- aOutThumbSize = 0;
-
- return nullptr;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::getObjectFilePath(MtpObjectHandle aHandle,
- MtpString& aOutFilePath,
- int64_t& aOutFileLength,
- MtpObjectFormat& aOutFormat)
-{
- RefPtr<DbEntry> entry = GetEntry(aHandle);
- if (!entry) {
- MTP_ERR("Handle 0x%08x is invalid", aHandle);
- return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
- }
-
- MTP_LOG("Handle: 0x%08x FilePath: '%s'", aHandle, entry->mPath.get());
-
- aOutFilePath = entry->mPath.get();
- aOutFileLength = entry->mObjectSize;
- aOutFormat = entry->mObjectFormat;
-
- return MTP_RESPONSE_OK;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::deleteFile(MtpObjectHandle aHandle)
-{
- RefPtr<DbEntry> entry = GetEntry(aHandle);
- if (!entry) {
- MTP_ERR("Invalid Handle: 0x%08x", aHandle);
- return MTP_RESPONSE_INVALID_OBJECT_HANDLE;
- }
-
- MTP_LOG("Handle: 0x%08x '%s'", aHandle, entry->mPath.get());
-
- // File deletion will happen in lower level implementation.
- // The only thing we need to do is removing the entry from the db.
- RemoveEntry(aHandle);
-
- // Tell Device Storage that the file is gone.
- MtpWatcherNotify(entry, "deleted");
-
- return MTP_RESPONSE_OK;
-}
-
-#if 0
-//virtual
-MtpResponseCode
-MozMtpDatabase::moveFile(MtpObjectHandle aHandle, MtpObjectHandle aNewParent)
-{
- MTP_LOG("Handle: 0x%08x NewParent: 0x%08x", aHandle, aNewParent);
-
- // change parent
-
- return MTP_RESPONSE_OK
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::copyFile(MtpObjectHandle aHandle, MtpObjectHandle aNewParent)
-{
- MTP_LOG("Handle: 0x%08x NewParent: 0x%08x", aHandle, aNewParent);
-
- // duplicate DbEntry
- // change parent
-
- return MTP_RESPONSE_OK
-}
-#endif
-
-//virtual
-MtpObjectHandleList*
-MozMtpDatabase::getObjectReferences(MtpObjectHandle aHandle)
-{
- MTP_LOG("Handle: 0x%08x (returning nullptr)", aHandle);
- return nullptr;
-}
-
-//virtual
-MtpResponseCode
-MozMtpDatabase::setObjectReferences(MtpObjectHandle aHandle,
- MtpObjectHandleList* aReferences)
-{
- MTP_LOG("Handle: 0x%08x (NOT SUPPORTED)", aHandle);
- return MTP_RESPONSE_OPERATION_NOT_SUPPORTED;
-}
-
-//virtual
-MtpProperty*
-MozMtpDatabase::getObjectPropertyDesc(MtpObjectProperty aProperty,
- MtpObjectFormat aFormat)
-{
- MTP_LOG("Property: %s 0x%08x", ObjectPropertyAsStr(aProperty), aProperty);
-
- MtpProperty* result = nullptr;
- switch (aProperty)
- {
- case MTP_PROPERTY_PROTECTION_STATUS:
- result = new MtpProperty(aProperty, MTP_TYPE_UINT16);
- break;
- case MTP_PROPERTY_OBJECT_FORMAT:
- result = new MtpProperty(aProperty, MTP_TYPE_UINT16, false, aFormat);
- break;
- case MTP_PROPERTY_STORAGE_ID:
- case MTP_PROPERTY_PARENT_OBJECT:
- case MTP_PROPERTY_WIDTH:
- case MTP_PROPERTY_HEIGHT:
- case MTP_PROPERTY_IMAGE_BIT_DEPTH:
- result = new MtpProperty(aProperty, MTP_TYPE_UINT32);
- break;
- case MTP_PROPERTY_OBJECT_SIZE:
- result = new MtpProperty(aProperty, MTP_TYPE_UINT64);
- break;
- case MTP_PROPERTY_DISPLAY_NAME:
- case MTP_PROPERTY_NAME:
- result = new MtpProperty(aProperty, MTP_TYPE_STR);
- break;
- case MTP_PROPERTY_OBJECT_FILE_NAME:
- result = new MtpProperty(aProperty, MTP_TYPE_STR, true);
- break;
- case MTP_PROPERTY_DATE_CREATED:
- case MTP_PROPERTY_DATE_MODIFIED:
- case MTP_PROPERTY_DATE_ADDED:
- result = new MtpProperty(aProperty, MTP_TYPE_STR);
- result->setFormDateTime();
- break;
- case MTP_PROPERTY_PERSISTENT_UID:
- result = new MtpProperty(aProperty, MTP_TYPE_UINT128);
- break;
- default:
- break;
- }
-
- return result;
-}
-
-//virtual
-MtpProperty*
-MozMtpDatabase::getDevicePropertyDesc(MtpDeviceProperty aProperty)
-{
- MTP_LOG("(returning MTP_DEVICE_PROPERTY_UNDEFINED)");
- return new MtpProperty(MTP_DEVICE_PROPERTY_UNDEFINED, MTP_TYPE_UNDEFINED);
-}
-
-//virtual
-void
-MozMtpDatabase::sessionStarted()
-{
- MTP_LOG("");
-}
-
-//virtual
-void
-MozMtpDatabase::sessionEnded()
-{
- MTP_LOG("");
-}
-
-END_MTP_NAMESPACE
diff --git a/dom/system/gonk/MozMtpDatabase.h b/dom/system/gonk/MozMtpDatabase.h
deleted file mode 100644
index 8b308762e..000000000
--- a/dom/system/gonk/MozMtpDatabase.h
+++ /dev/null
@@ -1,288 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_system_mozmtpdatabase_h__
-#define mozilla_system_mozmtpdatabase_h__
-
-#include "MozMtpCommon.h"
-
-#include "mozilla/Mutex.h"
-#include "mozilla/RefPtr.h"
-#include "nsCOMPtr.h"
-#include "nsString.h"
-#include "nsIThread.h"
-#include "nsTArray.h"
-
-class DeviceStorageFile;
-
-BEGIN_MTP_NAMESPACE // mozilla::system::mtp
-
-class RefCountedMtpServer;
-
-using namespace android;
-
-class MozMtpDatabase final : public MtpDatabase
-{
-public:
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(MozMtpDatabase)
-
- MozMtpDatabase();
-
- // called from SendObjectInfo to reserve a database entry for the incoming file
- virtual MtpObjectHandle beginSendObject(const char* aPath,
- MtpObjectFormat aFormat,
- MtpObjectHandle aParent,
- MtpStorageID aStorageID,
- uint64_t aSize,
- time_t aModified);
-
- // called to report success or failure of the SendObject file transfer
- // success should signal a notification of the new object's creation,
- // failure should remove the database entry created in beginSendObject
- virtual void endSendObject(const char* aPath,
- MtpObjectHandle aHandle,
- MtpObjectFormat aFormat,
- bool aSucceeded);
-
- virtual MtpObjectHandleList* getObjectList(MtpStorageID aStorageID,
- MtpObjectFormat aFormat,
- MtpObjectHandle aParent);
-
- virtual int getNumObjects(MtpStorageID aStorageID,
- MtpObjectFormat aFormat,
- MtpObjectHandle aParent);
-
- virtual MtpObjectFormatList* getSupportedPlaybackFormats();
-
- virtual MtpObjectFormatList* getSupportedCaptureFormats();
-
- virtual MtpObjectPropertyList* getSupportedObjectProperties(MtpObjectFormat aFormat);
-
- virtual MtpDevicePropertyList* getSupportedDeviceProperties();
-
- virtual MtpResponseCode getObjectPropertyValue(MtpObjectHandle aHandle,
- MtpObjectProperty aProperty,
- MtpDataPacket& aPacket);
-
- virtual MtpResponseCode setObjectPropertyValue(MtpObjectHandle aHandle,
- MtpObjectProperty aProperty,
- MtpDataPacket& aPacket);
-
- virtual MtpResponseCode getDevicePropertyValue(MtpDeviceProperty aProperty,
- MtpDataPacket& aPacket);
-
- virtual MtpResponseCode setDevicePropertyValue(MtpDeviceProperty aProperty,
- MtpDataPacket& aPacket);
-
- virtual MtpResponseCode resetDeviceProperty(MtpDeviceProperty aProperty);
-
- virtual MtpResponseCode getObjectPropertyList(MtpObjectHandle aHandle,
- uint32_t aFormat,
- uint32_t aProperty,
- int aGroupCode,
- int aDepth,
- MtpDataPacket& aPacket);
-
- virtual MtpResponseCode getObjectInfo(MtpObjectHandle aHandle,
- MtpObjectInfo& aInfo);
-
- virtual void* getThumbnail(MtpObjectHandle aHandle, size_t& aOutThumbSize);
-
- virtual MtpResponseCode getObjectFilePath(MtpObjectHandle aHandle,
- MtpString& aOutFilePath,
- int64_t& aOutFileLength,
- MtpObjectFormat& aOutFormat);
-
- virtual MtpResponseCode deleteFile(MtpObjectHandle aHandle);
-
- virtual MtpObjectHandleList* getObjectReferences(MtpObjectHandle aHandle);
-
- virtual MtpResponseCode setObjectReferences(MtpObjectHandle aHandle,
- MtpObjectHandleList* aReferences);
-
- virtual MtpProperty* getObjectPropertyDesc(MtpObjectProperty aProperty,
- MtpObjectFormat aFormat);
-
- virtual MtpProperty* getDevicePropertyDesc(MtpDeviceProperty aProperty);
-
- virtual void sessionStarted();
-
- virtual void sessionEnded();
-
- void AddStorage(MtpStorageID aStorageID, const char* aPath, const char *aName);
- void RemoveStorage(MtpStorageID aStorageID);
-
- void MtpWatcherUpdate(RefCountedMtpServer* aMtpServer,
- DeviceStorageFile* aFile,
- const nsACString& aEventType);
-
-protected:
- virtual ~MozMtpDatabase();
-
-private:
-
- struct DbEntry final
- {
- DbEntry()
- : mHandle(0),
- mStorageID(0),
- mObjectFormat(MTP_FORMAT_DEFINED),
- mParent(0),
- mObjectSize(0),
- mDateCreated(0),
- mDateModified(0),
- mDateAdded(0) {}
-
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(DbEntry)
-
- MtpObjectHandle mHandle; // uint32_t
- MtpStorageID mStorageID; // uint32_t
- nsCString mObjectName;
- MtpObjectFormat mObjectFormat; // uint16_t
- MtpObjectHandle mParent; // uint32_t
- uint64_t mObjectSize;
- nsCString mDisplayName;
- nsCString mPath;
- time_t mDateCreated;
- time_t mDateModified;
- time_t mDateAdded;
-
- protected:
- ~DbEntry() {}
- };
-
- template<class T>
- class ProtectedTArray : private nsTArray<T>
- {
- public:
- typedef T elem_type;
- typedef typename nsTArray<T>::size_type size_type;
- typedef typename nsTArray<T>::index_type index_type;
- typedef nsTArray<T> base_type;
-
- static const index_type NoIndex = base_type::NoIndex;
-
- ProtectedTArray(mozilla::Mutex& aMutex)
- : mMutex(aMutex)
- {}
-
- size_type Length() const
- {
- // GRR - This assert prints to stderr and won't show up in logcat.
- mMutex.AssertCurrentThreadOwns();
- return base_type::Length();
- }
-
- template <class Item>
- elem_type* AppendElement(const Item& aItem)
- {
- mMutex.AssertCurrentThreadOwns();
- return base_type::AppendElement(aItem);
- }
-
- void Clear()
- {
- mMutex.AssertCurrentThreadOwns();
- base_type::Clear();
- }
-
- void RemoveElementAt(index_type aIndex)
- {
- mMutex.AssertCurrentThreadOwns();
- base_type::RemoveElementAt(aIndex);
- }
-
- elem_type& operator[](index_type aIndex)
- {
- mMutex.AssertCurrentThreadOwns();
- return base_type::ElementAt(aIndex);
- }
-
- const elem_type& operator[](index_type aIndex) const
- {
- mMutex.AssertCurrentThreadOwns();
- return base_type::ElementAt(aIndex);
- }
-
- private:
- mozilla::Mutex& mMutex;
- };
- typedef nsTArray<RefPtr<DbEntry> > UnprotectedDbArray;
- typedef ProtectedTArray<RefPtr<DbEntry> > ProtectedDbArray;
-
- struct StorageEntry final
- {
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(StorageEntry)
-
- MtpStorageID mStorageID;
- nsCString mStoragePath;
- nsCString mStorageName;
-
- protected:
- ~StorageEntry() {}
- };
- typedef ProtectedTArray<RefPtr<StorageEntry> > StorageArray;
-
- enum MatchType
- {
- MatchAll,
- MatchHandle,
- MatchParent,
- MatchFormat,
- MatchHandleFormat,
- MatchParentFormat,
- };
-
- bool IsValidHandle(MtpObjectHandle aHandle)
- {
- return aHandle > 0 && aHandle < mDb.Length();
- }
-
- void AddEntry(DbEntry* aEntry);
- void AddEntryAndNotify(DbEntry* aEntr, RefCountedMtpServer* aMtpServer);
- void DumpEntries(const char* aLabel);
- MtpObjectHandle FindEntryByPath(const nsACString& aPath);
- already_AddRefed<DbEntry> GetEntry(MtpObjectHandle aHandle);
- void RemoveEntry(MtpObjectHandle aHandle);
- void RemoveEntryAndNotify(MtpObjectHandle aHandle, RefCountedMtpServer* aMtpServer);
- void UpdateEntry(MtpObjectHandle aHandle, DeviceStorageFile* aFile);
- void UpdateEntryAndNotify(MtpObjectHandle aHandle, DeviceStorageFile* aFile,
- RefCountedMtpServer* aMtpServer);
- void QueryEntries(MatchType aMatchType, uint32_t aMatchField1,
- uint32_t aMatchField2, UnprotectedDbArray& aResult);
-
- nsCString BaseName(const nsCString& aPath);
-
-
- MtpObjectHandle GetNextHandle()
- {
- return mDb.Length();
- }
-
- void AddDirectory(MtpStorageID aStorageID, const char *aPath, MtpObjectHandle aParent);
-
- void CreateEntryForFileAndNotify(const nsACString& aPath,
- DeviceStorageFile* aFile,
- RefCountedMtpServer* aMtpServer);
-
- StorageArray::index_type FindStorage(MtpStorageID aStorageID);
- MtpStorageID FindStorageIDFor(const nsACString& aPath, nsCSubstring& aRemainder);
- void MtpWatcherNotify(DbEntry* aEntry, const char* aEventType);
-
- // We need a mutex to protext mDb and mStorage. The MTP server runs on a
- // dedicated thread, and it updates/accesses mDb. When files are updated
- // through DeviceStorage, we need to update/access mDb and mStorage as well
- // (from a non-MTP server thread).
- mozilla::Mutex mMutex;
- ProtectedDbArray mDb;
- StorageArray mStorage;
-
- bool mBeginSendObjectCalled;
-};
-
-END_MTP_NAMESPACE
-
-#endif // mozilla_system_mozmtpdatabase_h__
diff --git a/dom/system/gonk/MozMtpServer.cpp b/dom/system/gonk/MozMtpServer.cpp
deleted file mode 100644
index c26b6368b..000000000
--- a/dom/system/gonk/MozMtpServer.cpp
+++ /dev/null
@@ -1,263 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "MozMtpServer.h"
-#include "MozMtpDatabase.h"
-
-#include <fcntl.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <errno.h>
-#include <stdio.h>
-#include <unistd.h>
-
-#include <cutils/properties.h>
-#include <private/android_filesystem_config.h>
-
-#include "base/message_loop.h"
-#include "DeviceStorage.h"
-#include "mozilla/LazyIdleThread.h"
-#include "mozilla/Scoped.h"
-#include "mozilla/Services.h"
-#include "mozilla/StaticPtr.h"
-#include "nsIObserver.h"
-#include "nsIObserverService.h"
-#include "nsISupportsImpl.h"
-#include "nsThreadUtils.h"
-#include "nsXULAppAPI.h"
-
-#include "Volume.h"
-
-#define DEFAULT_THREAD_TIMEOUT_MS 30000
-
-using namespace android;
-using namespace mozilla;
-BEGIN_MTP_NAMESPACE
-
-static const char* kMtpWatcherUpdate = "mtp-watcher-update";
-
-class MtpWatcherUpdateRunnable final : public Runnable
-{
-public:
- MtpWatcherUpdateRunnable(MozMtpDatabase* aMozMtpDatabase,
- RefCountedMtpServer* aMtpServer,
- DeviceStorageFile* aFile,
- const nsACString& aEventType)
- : mMozMtpDatabase(aMozMtpDatabase),
- mMtpServer(aMtpServer),
- mFile(aFile),
- mEventType(aEventType)
- {}
-
- NS_IMETHOD Run() override
- {
- // Runs on the MtpWatcherUpdate->mIOThread
- MOZ_ASSERT(!NS_IsMainThread());
-
- mMozMtpDatabase->MtpWatcherUpdate(mMtpServer, mFile, mEventType);
- return NS_OK;
- }
-
-private:
- RefPtr<MozMtpDatabase> mMozMtpDatabase;
- RefPtr<RefCountedMtpServer> mMtpServer;
- RefPtr<DeviceStorageFile> mFile;
- nsCString mEventType;
-};
-
-// The MtpWatcherUpdate class listens for mtp-watcher-update events
-// and tells the MtpServer about changes made in device storage.
-class MtpWatcherUpdate final : public nsIObserver
-{
-public:
- NS_DECL_THREADSAFE_ISUPPORTS
-
- MtpWatcherUpdate(MozMtpServer* aMozMtpServer)
- : mMozMtpServer(aMozMtpServer)
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- mIOThread = new LazyIdleThread(
- DEFAULT_THREAD_TIMEOUT_MS,
- NS_LITERAL_CSTRING("MtpWatcherUpdate"));
-
- nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
- obs->AddObserver(this, kMtpWatcherUpdate, false);
- }
-
- NS_IMETHOD
- Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData)
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- if (strcmp(aTopic, kMtpWatcherUpdate)) {
- // We're only interested in mtp-watcher-update events
- return NS_OK;
- }
-
- NS_ConvertUTF16toUTF8 eventType(aData);
- if (!eventType.EqualsLiteral("modified") && !eventType.EqualsLiteral("deleted")) {
- // Bug 1074604: Needn't handle "created" event, once file operation
- // finished, it would trigger "modified" event.
- return NS_OK;
- }
-
- DeviceStorageFile* file = static_cast<DeviceStorageFile*>(aSubject);
- file->Dump(kMtpWatcherUpdate);
- MTP_LOG("%s: file %s %s", kMtpWatcherUpdate,
- NS_LossyConvertUTF16toASCII(file->mPath).get(),
- eventType.get());
-
- RefPtr<MozMtpDatabase> mozMtpDatabase = mMozMtpServer->GetMozMtpDatabase();
- RefPtr<RefCountedMtpServer> mtpServer = mMozMtpServer->GetMtpServer();
-
- // We're not supposed to perform I/O on the main thread, so punt the
- // notification (which will write to /dev/mtp_usb) to an I/O Thread.
-
- RefPtr<MtpWatcherUpdateRunnable> r =
- new MtpWatcherUpdateRunnable(mozMtpDatabase, mtpServer, file, eventType);
- mIOThread->Dispatch(r, NS_DISPATCH_NORMAL);
-
- return NS_OK;
- }
-
-protected:
- ~MtpWatcherUpdate()
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
- obs->RemoveObserver(this, kMtpWatcherUpdate);
- }
-
-private:
- RefPtr<MozMtpServer> mMozMtpServer;
- nsCOMPtr<nsIThread> mIOThread;
-};
-NS_IMPL_ISUPPORTS(MtpWatcherUpdate, nsIObserver)
-static StaticRefPtr<MtpWatcherUpdate> sMtpWatcherUpdate;
-
-class AllocMtpWatcherUpdateRunnable final : public Runnable
-{
-public:
- AllocMtpWatcherUpdateRunnable(MozMtpServer* aMozMtpServer)
- : mMozMtpServer(aMozMtpServer)
- {}
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- sMtpWatcherUpdate = new MtpWatcherUpdate(mMozMtpServer);
- return NS_OK;
- }
-private:
- RefPtr<MozMtpServer> mMozMtpServer;
-};
-
-class FreeMtpWatcherUpdateRunnable final : public Runnable
-{
-public:
- FreeMtpWatcherUpdateRunnable(MozMtpServer* aMozMtpServer)
- : mMozMtpServer(aMozMtpServer)
- {}
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- sMtpWatcherUpdate = nullptr;
- return NS_OK;
- }
-private:
- RefPtr<MozMtpServer> mMozMtpServer;
-};
-
-class MtpServerRunnable : public Runnable
-{
-public:
- MtpServerRunnable(int aMtpUsbFd, MozMtpServer* aMozMtpServer)
- : mMozMtpServer(aMozMtpServer),
- mMtpUsbFd(aMtpUsbFd)
- {
- }
-
- nsresult Run()
- {
- RefPtr<RefCountedMtpServer> server = mMozMtpServer->GetMtpServer();
-
- DebugOnly<nsresult> rv =
- NS_DispatchToMainThread(new AllocMtpWatcherUpdateRunnable(mMozMtpServer));
- MOZ_ASSERT(NS_SUCCEEDED(rv));
-
- MTP_LOG("MozMtpServer started");
- server->run();
- MTP_LOG("MozMtpServer finished");
-
- // server->run will have closed the file descriptor.
- mMtpUsbFd.forget();
-
- rv = NS_DispatchToMainThread(new FreeMtpWatcherUpdateRunnable(mMozMtpServer));
- MOZ_ASSERT(NS_SUCCEEDED(rv));
-
- return NS_OK;
- }
-
-private:
- RefPtr<MozMtpServer> mMozMtpServer;
- ScopedClose mMtpUsbFd; // We want to hold this open while the server runs
-};
-
-already_AddRefed<RefCountedMtpServer>
-MozMtpServer::GetMtpServer()
-{
- RefPtr<RefCountedMtpServer> server = mMtpServer;
- return server.forget();
-}
-
-already_AddRefed<MozMtpDatabase>
-MozMtpServer::GetMozMtpDatabase()
-{
- RefPtr<MozMtpDatabase> db = mMozMtpDatabase;
- return db.forget();
-}
-
-bool
-MozMtpServer::Init()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- const char *mtpUsbFilename = "/dev/mtp_usb";
- mMtpUsbFd = open(mtpUsbFilename, O_RDWR);
- if (mMtpUsbFd.get() < 0) {
- MTP_ERR("open of '%s' failed((%s))", mtpUsbFilename, strerror(errno));
- return false;
- }
- MTP_LOG("Opened '%s' fd %d", mtpUsbFilename, mMtpUsbFd.get());
-
- mMozMtpDatabase = new MozMtpDatabase();
- mMtpServer = new RefCountedMtpServer(mMtpUsbFd.get(), // fd
- mMozMtpDatabase.get(), // MtpDatabase
- false, // ptp?
- AID_MEDIA_RW, // file group
- 0664, // file permissions
- 0775); // dir permissions
- return true;
-}
-
-void
-MozMtpServer::Run()
-{
- nsresult rv = NS_NewNamedThread("MtpServer", getter_AddRefs(mServerThread));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
- MOZ_ASSERT(mServerThread);
- mServerThread->Dispatch(new MtpServerRunnable(mMtpUsbFd.forget(), this), NS_DISPATCH_NORMAL);
-}
-
-END_MTP_NAMESPACE
diff --git a/dom/system/gonk/MozMtpServer.h b/dom/system/gonk/MozMtpServer.h
deleted file mode 100644
index 4989c25ef..000000000
--- a/dom/system/gonk/MozMtpServer.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_system_mozmtpserver_h__
-#define mozilla_system_mozmtpserver_h__
-
-#include "MozMtpCommon.h"
-#include "MozMtpDatabase.h"
-
-#include "mozilla/FileUtils.h"
-
-#include "nsCOMPtr.h"
-#include "nsIThread.h"
-
-BEGIN_MTP_NAMESPACE
-using namespace android;
-
-class RefCountedMtpServer : public MtpServer
-{
-public:
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(RefCountedMtpServer)
-
- RefCountedMtpServer(int aFd, MtpDatabase* aDatabase, bool aPtp,
- int aFileGroup, int aFilePerm, int aDirectoryPerm)
- : MtpServer(aFd, aDatabase, aPtp, aFileGroup, aFilePerm, aDirectoryPerm)
- {
- }
-
-protected:
- virtual ~RefCountedMtpServer() {}
-};
-
-class MozMtpServer
-{
-public:
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(MozMtpServer)
-
- bool Init();
- void Run();
-
- already_AddRefed<RefCountedMtpServer> GetMtpServer();
- already_AddRefed<MozMtpDatabase> GetMozMtpDatabase();
-
-protected:
- virtual ~MozMtpServer() {}
-
-private:
- RefPtr<RefCountedMtpServer> mMtpServer;
- RefPtr<MozMtpDatabase> mMozMtpDatabase;
- nsCOMPtr<nsIThread> mServerThread;
- ScopedClose mMtpUsbFd;
-};
-
-END_MTP_NAMESPACE
-
-#endif // mozilla_system_mozmtpserver_h__
-
-
diff --git a/dom/system/gonk/MozMtpStorage.cpp b/dom/system/gonk/MozMtpStorage.cpp
deleted file mode 100644
index 9c358a132..000000000
--- a/dom/system/gonk/MozMtpStorage.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "MozMtpStorage.h"
-#include "MozMtpDatabase.h"
-#include "MozMtpServer.h"
-
-#include "base/message_loop.h"
-#include "nsXULAppAPI.h"
-
-BEGIN_MTP_NAMESPACE
-using namespace android;
-
-MozMtpStorage::MozMtpStorage(Volume* aVolume, MozMtpServer* aMozMtpServer)
- : mMozMtpServer(aMozMtpServer),
- mVolume(aVolume)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- // The MtpStorageID has the physical volume in the top 16 bits, and the
- // logical volumein the lower 16 bits. We treat each volume as a separate
- // phsyical storage;
- mStorageID = mVolume->Id() << 16 | 1;
-
- MTP_LOG("Storage constructed for Volume %s mStorageID 0x%08x",
- aVolume->NameStr(), mStorageID);
-
- Volume::RegisterVolumeObserver(this, "MozMtpStorage");
-
- // Get things in sync
- Notify(mVolume);
-}
-
-MozMtpStorage::~MozMtpStorage()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- MTP_LOG("Storage destructed for Volume %s mStorageID 0x%08x",
- mVolume->NameStr(), mStorageID);
-
- Volume::UnregisterVolumeObserver(this, "MozMtpStorage");
- if (mMtpStorage) {
- StorageUnavailable();
- }
-}
-
-// virtual
-void
-MozMtpStorage::Notify(Volume* const& aVolume)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- if (aVolume != mVolume) {
- // Not our volume
- return;
- }
- Volume::STATE volState = aVolume->State();
-
- MTP_LOG("Volume %s mStorageID 0x%08x state changed to %s SharingEnabled: %d",
- aVolume->NameStr(), mStorageID, aVolume->StateStr(),
- aVolume->IsSharingEnabled());
-
- // vol->IsSharingEnabled really only applies to UMS volumes. We assume that
- // that as long as MTP is enabled, then all volumes will be shared. The UI
- // currently doesn't give us anything more granular than on/off.
-
- if (mMtpStorage) {
- if (volState != nsIVolume::STATE_MOUNTED) {
- // The volume is no longer accessible. We need to remove this storage
- // from the MTP server
- StorageUnavailable();
- }
- } else {
- if (volState == nsIVolume::STATE_MOUNTED) {
- // The volume is accessible. Tell the MTP server.
- StorageAvailable();
- }
- }
-}
-
-void
-MozMtpStorage::StorageAvailable()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- nsCString mountPoint = mVolume->MountPoint();
-
- MTP_LOG("Adding Volume %s mStorageID 0x%08x mountPoint %s to MozMtpDatabase",
- mVolume->NameStr(), mStorageID, mountPoint.get());
-
- RefPtr<MozMtpDatabase> db = mMozMtpServer->GetMozMtpDatabase();
- db->AddStorage(mStorageID, mountPoint.get(), mVolume->NameStr());
-
- MOZ_ASSERT(!mMtpStorage);
-
- //TODO: Figure out what to do about maxFileSize.
-
- mMtpStorage.reset(new MtpStorage(mStorageID, // id
- mountPoint.get(), // filePath
- mVolume->NameStr(), // description
- 1024uLL * 1024uLL, // reserveSpace
- mVolume->IsHotSwappable(), // removable
- 2uLL * 1024uLL * 1024uLL * 1024uLL)); // maxFileSize
- RefPtr<RefCountedMtpServer> server = mMozMtpServer->GetMtpServer();
-
- MTP_LOG("Adding Volume %s mStorageID 0x%08x mountPoint %s to MtpServer",
- mVolume->NameStr(), mStorageID, mountPoint.get());
- server->addStorage(mMtpStorage.get());
-}
-
-void
-MozMtpStorage::StorageUnavailable()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(mMtpStorage);
-
- MTP_LOG("Removing mStorageID 0x%08x from MtpServer", mStorageID);
-
- RefPtr<RefCountedMtpServer> server = mMozMtpServer->GetMtpServer();
- server->removeStorage(mMtpStorage.get());
-
- MTP_LOG("Removing mStorageID 0x%08x from MozMtpDatabse", mStorageID);
-
- RefPtr<MozMtpDatabase> db = mMozMtpServer->GetMozMtpDatabase();
- db->RemoveStorage(mStorageID);
-
- mMtpStorage = nullptr;
-}
-
-END_MTP_NAMESPACE
-
-
diff --git a/dom/system/gonk/MozMtpStorage.h b/dom/system/gonk/MozMtpStorage.h
deleted file mode 100644
index 18d1e04ac..000000000
--- a/dom/system/gonk/MozMtpStorage.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_system_mozmtpstorage_h__
-#define mozilla_system_mozmtpstorage_h__
-
-#include "MozMtpCommon.h"
-
-#include "mozilla/UniquePtr.h"
-
-#include "Volume.h"
-
-BEGIN_MTP_NAMESPACE
-using namespace android;
-
-class MozMtpServer;
-
-class MozMtpStorage : public Volume::EventObserver
-{
-public:
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(MozMtpStorage)
-
- MozMtpStorage(Volume* aVolume, MozMtpServer* aMozMtpServer);
-
- typedef nsTArray<RefPtr<MozMtpStorage> > Array;
-
-private:
- virtual ~MozMtpStorage();
- virtual void Notify(Volume* const& aEvent);
-
- void StorageAvailable();
- void StorageUnavailable();
-
- RefPtr<MozMtpServer> mMozMtpServer;
- UniquePtr<MtpStorage> mMtpStorage;
- RefPtr<Volume> mVolume;
- MtpStorageID mStorageID;
-};
-
-END_MTP_NAMESPACE
-
-#endif // mozilla_system_mozmtpstorage_h__
-
-
diff --git a/dom/system/gonk/NetIdManager.cpp b/dom/system/gonk/NetIdManager.cpp
deleted file mode 100644
index 510ec8b22..000000000
--- a/dom/system/gonk/NetIdManager.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "NetIdManager.h"
-
-NetIdManager::NetIdManager()
- : mNextNetId(MIN_NET_ID)
-{
-}
-
-int NetIdManager::getNextNetId()
-{
- // Modified from
- // http://androidxref.com/5.0.0_r2/xref/frameworks/base/services/
- // core/java/com/android/server/ConnectivityService.java#764
-
- int netId = mNextNetId;
- if (++mNextNetId > MAX_NET_ID) {
- mNextNetId = MIN_NET_ID;
- }
-
- return netId;
-}
-
-void NetIdManager::acquire(const nsString& aInterfaceName,
- NetIdInfo* aNetIdInfo)
-{
- // Lookup or create one.
- if (!mInterfaceToNetIdHash.Get(aInterfaceName, aNetIdInfo)) {
- aNetIdInfo->mNetId = getNextNetId();
- aNetIdInfo->mRefCnt = 1;
- } else {
- aNetIdInfo->mRefCnt++;
- }
-
- // Update hash and return.
- mInterfaceToNetIdHash.Put(aInterfaceName, *aNetIdInfo);
-
- return;
-}
-
-bool NetIdManager::lookup(const nsString& aInterfaceName,
- NetIdInfo* aNetIdInfo)
-{
- return mInterfaceToNetIdHash.Get(aInterfaceName, aNetIdInfo);
-}
-
-bool NetIdManager::release(const nsString& aInterfaceName,
- NetIdInfo* aNetIdInfo)
-{
- if (!mInterfaceToNetIdHash.Get(aInterfaceName, aNetIdInfo)) {
- return false; // No such key.
- }
-
- aNetIdInfo->mRefCnt--;
-
- // Update the hash if still be referenced.
- if (aNetIdInfo->mRefCnt > 0) {
- mInterfaceToNetIdHash.Put(aInterfaceName, *aNetIdInfo);
- return true;
- }
-
- // No longer be referenced. Remove the entry.
- mInterfaceToNetIdHash.Remove(aInterfaceName);
-
- return true;
-} \ No newline at end of file
diff --git a/dom/system/gonk/NetIdManager.h b/dom/system/gonk/NetIdManager.h
deleted file mode 100644
index e35d0ecd2..000000000
--- a/dom/system/gonk/NetIdManager.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 NetIdManager_h
-#define NetIdManager_h
-
-#include "nsString.h"
-#include "nsDataHashtable.h"
-
-// NetId is a logical network identifier defined by netd.
-// A network is typically a physical one (i.e. PhysicalNetwork.cpp)
-// for netd but it could be a virtual network as well.
-// We currently use physical network only and use one-to-one
-// network-interface mapping.
-
-class NetIdManager {
-public:
- // keep in sync with system/netd/NetworkController.cpp
- enum {
- MIN_NET_ID = 100,
- MAX_NET_ID = 65535,
- };
-
- // We need to count the number of references since different
- // application like data and mms may use the same interface.
- struct NetIdInfo {
- int mNetId;
- int mRefCnt;
- };
-
-public:
- NetIdManager();
-
- bool lookup(const nsString& aInterfaceName, NetIdInfo* aNetIdInfo);
- void acquire(const nsString& aInterfaceName, NetIdInfo* aNetIdInfo);
- bool release(const nsString& aInterfaceName, NetIdInfo* aNetIdInfo);
-
-private:
- int getNextNetId();
- int mNextNetId;
- nsDataHashtable<nsStringHashKey, NetIdInfo> mInterfaceToNetIdHash;
-};
-
-#endif \ No newline at end of file
diff --git a/dom/system/gonk/NetworkInterfaceListService.js b/dom/system/gonk/NetworkInterfaceListService.js
deleted file mode 100644
index 62fe046aa..000000000
--- a/dom/system/gonk/NetworkInterfaceListService.js
+++ /dev/null
@@ -1,110 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-const NETWORKLISTSERVICE_CONTRACTID =
- "@mozilla.org/network/interface-list-service;1";
-const NETWORKLISTSERVICE_CID =
- Components.ID("{3780be6e-7012-4e53-ade6-15212fb88a0d}");
-
-XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
- "@mozilla.org/childprocessmessagemanager;1",
- "nsISyncMessageSender");
-
-function NetworkInterfaceListService () {
-}
-
-NetworkInterfaceListService.prototype = {
- classID: NETWORKLISTSERVICE_CID,
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterfaceListService]),
-
- getDataInterfaceList: function(aConditions) {
- return new NetworkInterfaceList(
- cpmm.sendSyncMessage(
- 'NetworkInterfaceList:ListInterface',
- {
- excludeSupl: (aConditions &
- Ci.nsINetworkInterfaceListService.
- LIST_NOT_INCLUDE_SUPL_INTERFACES) != 0,
- excludeMms: (aConditions &
- Ci.nsINetworkInterfaceListService.
- LIST_NOT_INCLUDE_MMS_INTERFACES) != 0,
- excludeIms: (aConditions &
- Ci.nsINetworkInterfaceListService.
- LIST_NOT_INCLUDE_IMS_INTERFACES) != 0,
- excludeDun: (aConditions &
- Ci.nsINetworkInterfaceListService.
- LIST_NOT_INCLUDE_DUN_INTERFACES) != 0,
- excludeFota: (aConditions &
- Ci.nsINetworkInterfaceListService.
- LIST_NOT_INCLUDE_FOTA_INTERFACES) != 0
- }
- )[0]);
- }
-};
-
-function FakeNetworkInfo(aAttributes) {
- this.state = aAttributes.state;
- this.type = aAttributes.type;
- this.name = aAttributes.name;
- this.ips = aAttributes.ips;
- this.prefixLengths = aAttributes.prefixLengths;
- this.gateways = aAttributes.gateways;
- this.dnses = aAttributes.dnses;
-}
-FakeNetworkInfo.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInfo]),
-
- getAddresses: function (ips, prefixLengths) {
- ips.value = this.ips.slice();
- prefixLengths.value = this.prefixLengths.slice();
-
- return this.ips.length;
- },
-
- getGateways: function (count) {
- if (count) {
- count.value = this.gateways.length;
- }
- return this.gateways.slice();
- },
-
- getDnses: function (count) {
- if (count) {
- count.value = this.dnses.length;
- }
- return this.dnses.slice();
- }
-};
-
-function NetworkInterfaceList (aInterfaceLiterals) {
- this._interfaces = [];
- for (let entry of aInterfaceLiterals) {
- this._interfaces.push(new FakeNetworkInfo(entry));
- }
-}
-
-NetworkInterfaceList.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterfaceList]),
-
- getNumberOfInterface: function() {
- return this._interfaces.length;
- },
-
- getInterfaceInfo: function(index) {
- if (!this._interfaces) {
- return null;
- }
- return this._interfaces[index];
- }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NetworkInterfaceListService]);
-
diff --git a/dom/system/gonk/NetworkInterfaceListService.manifest b/dom/system/gonk/NetworkInterfaceListService.manifest
deleted file mode 100644
index a827e778f..000000000
--- a/dom/system/gonk/NetworkInterfaceListService.manifest
+++ /dev/null
@@ -1,17 +0,0 @@
-# Copyright 2012 Mozilla Foundation and Mozilla contributors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# NetworkInterfaceListService.js
-component {3780be6e-7012-4e53-ade6-15212fb88a0d} NetworkInterfaceListService.js
-contract @mozilla.org/network/interface-list-service;1 {3780be6e-7012-4e53-ade6-15212fb88a0d}
diff --git a/dom/system/gonk/NetworkManager.js b/dom/system/gonk/NetworkManager.js
deleted file mode 100644
index 9d7a5683e..000000000
--- a/dom/system/gonk/NetworkManager.js
+++ /dev/null
@@ -1,1219 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/FileUtils.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-Cu.import("resource://gre/modules/Promise.jsm");
-
-const NETWORKMANAGER_CONTRACTID = "@mozilla.org/network/manager;1";
-const NETWORKMANAGER_CID =
- Components.ID("{1ba9346b-53b5-4660-9dc6-58f0b258d0a6}");
-
-const DEFAULT_PREFERRED_NETWORK_TYPE = Ci.nsINetworkInterface.NETWORK_TYPE_ETHERNET;
-
-XPCOMUtils.defineLazyGetter(this, "ppmm", function() {
- return Cc["@mozilla.org/parentprocessmessagemanager;1"]
- .getService(Ci.nsIMessageBroadcaster);
-});
-
-XPCOMUtils.defineLazyServiceGetter(this, "gDNSService",
- "@mozilla.org/network/dns-service;1",
- "nsIDNSService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkService",
- "@mozilla.org/network/service;1",
- "nsINetworkService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gTetheringService",
- "@mozilla.org/tethering/service;1",
- "nsITetheringService");
-
-const TOPIC_INTERFACE_REGISTERED = "network-interface-registered";
-const TOPIC_INTERFACE_UNREGISTERED = "network-interface-unregistered";
-const TOPIC_ACTIVE_CHANGED = "network-active-changed";
-const TOPIC_PREF_CHANGED = "nsPref:changed";
-const TOPIC_XPCOM_SHUTDOWN = "xpcom-shutdown";
-const TOPIC_CONNECTION_STATE_CHANGED = "network-connection-state-changed";
-const PREF_MANAGE_OFFLINE_STATUS = "network.gonk.manage-offline-status";
-const PREF_NETWORK_DEBUG_ENABLED = "network.debugging.enabled";
-
-const IPV4_ADDRESS_ANY = "0.0.0.0";
-const IPV6_ADDRESS_ANY = "::0";
-
-const IPV4_MAX_PREFIX_LENGTH = 32;
-const IPV6_MAX_PREFIX_LENGTH = 128;
-
-// Connection Type for Network Information API
-const CONNECTION_TYPE_CELLULAR = 0;
-const CONNECTION_TYPE_BLUETOOTH = 1;
-const CONNECTION_TYPE_ETHERNET = 2;
-const CONNECTION_TYPE_WIFI = 3;
-const CONNECTION_TYPE_OTHER = 4;
-const CONNECTION_TYPE_NONE = 5;
-
-const MANUAL_PROXY_CONFIGURATION = 1;
-
-var debug;
-function updateDebug() {
- let debugPref = false; // set default value here.
- try {
- debugPref = debugPref || Services.prefs.getBoolPref(PREF_NETWORK_DEBUG_ENABLED);
- } catch (e) {}
-
- if (debugPref) {
- debug = function(s) {
- dump("-*- NetworkManager: " + s + "\n");
- };
- } else {
- debug = function(s) {};
- }
-}
-updateDebug();
-
-function defineLazyRegExp(obj, name, pattern) {
- obj.__defineGetter__(name, function() {
- delete obj[name];
- return obj[name] = new RegExp(pattern);
- });
-}
-
-function ExtraNetworkInfo(aNetwork) {
- let ips = {};
- let prefixLengths = {};
- aNetwork.info.getAddresses(ips, prefixLengths);
-
- this.state = aNetwork.info.state;
- this.type = aNetwork.info.type;
- this.name = aNetwork.info.name;
- this.ips = ips.value;
- this.prefixLengths = prefixLengths.value;
- this.gateways = aNetwork.info.getGateways();
- this.dnses = aNetwork.info.getDnses();
- this.httpProxyHost = aNetwork.httpProxyHost;
- this.httpProxyPort = aNetwork.httpProxyPort;
- this.mtu = aNetwork.mtu;
-}
-ExtraNetworkInfo.prototype = {
- getAddresses: function(aIps, aPrefixLengths) {
- aIps.value = this.ips.slice();
- aPrefixLengths.value = this.prefixLengths.slice();
-
- return this.ips.length;
- },
-
- getGateways: function(aCount) {
- if (aCount) {
- aCount.value = this.gateways.length;
- }
-
- return this.gateways.slice();
- },
-
- getDnses: function(aCount) {
- if (aCount) {
- aCount.value = this.dnses.length;
- }
-
- return this.dnses.slice();
- }
-};
-
-function NetworkInterfaceLinks()
-{
- this.resetLinks();
-}
-NetworkInterfaceLinks.prototype = {
- linkRoutes: null,
- gateways: null,
- interfaceName: null,
- extraRoutes: null,
-
- setLinks: function(linkRoutes, gateways, interfaceName) {
- this.linkRoutes = linkRoutes;
- this.gateways = gateways;
- this.interfaceName = interfaceName;
- },
-
- resetLinks: function() {
- this.linkRoutes = [];
- this.gateways = [];
- this.interfaceName = "";
- this.extraRoutes = [];
- },
-
- compareGateways: function(gateways) {
- if (this.gateways.length != gateways.length) {
- return false;
- }
-
- for (let i = 0; i < this.gateways.length; i++) {
- if (this.gateways[i] != gateways[i]) {
- return false;
- }
- }
-
- return true;
- }
-};
-
-/**
- * This component watches for network interfaces changing state and then
- * adjusts routes etc. accordingly.
- */
-function NetworkManager() {
- this.networkInterfaces = {};
- this.networkInterfaceLinks = {};
-
- try {
- this._manageOfflineStatus =
- Services.prefs.getBoolPref(PREF_MANAGE_OFFLINE_STATUS);
- } catch(ex) {
- // Ignore.
- }
- Services.prefs.addObserver(PREF_MANAGE_OFFLINE_STATUS, this, false);
- Services.prefs.addObserver(PREF_NETWORK_DEBUG_ENABLED, this, false);
- Services.obs.addObserver(this, TOPIC_XPCOM_SHUTDOWN, false);
-
- this.setAndConfigureActive();
-
- ppmm.addMessageListener('NetworkInterfaceList:ListInterface', this);
-
- // Used in resolveHostname().
- defineLazyRegExp(this, "REGEXP_IPV4", "^\\d{1,3}(?:\\.\\d{1,3}){3}$");
- defineLazyRegExp(this, "REGEXP_IPV6", "^[\\da-fA-F]{4}(?::[\\da-fA-F]{4}){7}$");
-}
-NetworkManager.prototype = {
- classID: NETWORKMANAGER_CID,
- classInfo: XPCOMUtils.generateCI({classID: NETWORKMANAGER_CID,
- contractID: NETWORKMANAGER_CONTRACTID,
- classDescription: "Network Manager",
- interfaces: [Ci.nsINetworkManager]}),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkManager,
- Ci.nsISupportsWeakReference,
- Ci.nsIObserver,
- Ci.nsISettingsServiceCallback]),
-
- // nsIObserver
-
- observe: function(subject, topic, data) {
- switch (topic) {
- case TOPIC_PREF_CHANGED:
- if (data === PREF_NETWORK_DEBUG_ENABLED) {
- updateDebug();
- } else if (data === PREF_MANAGE_OFFLINE_STATUS) {
- this._manageOfflineStatus =
- Services.prefs.getBoolPref(PREF_MANAGE_OFFLINE_STATUS);
- debug(PREF_MANAGE_OFFLINE_STATUS + " has changed to " + this._manageOfflineStatus);
- }
- break;
- case TOPIC_XPCOM_SHUTDOWN:
- Services.obs.removeObserver(this, TOPIC_XPCOM_SHUTDOWN);
- Services.prefs.removeObserver(PREF_MANAGE_OFFLINE_STATUS, this);
- Services.prefs.removeObserver(PREF_NETWORK_DEBUG_ENABLED, this);
- break;
- }
- },
-
- receiveMessage: function(aMsg) {
- switch (aMsg.name) {
- case "NetworkInterfaceList:ListInterface": {
- let excludeMms = aMsg.json.excludeMms;
- let excludeSupl = aMsg.json.excludeSupl;
- let excludeIms = aMsg.json.excludeIms;
- let excludeDun = aMsg.json.excludeDun;
- let excludeFota = aMsg.json.excludeFota;
- let interfaces = [];
-
- for (let key in this.networkInterfaces) {
- let network = this.networkInterfaces[key];
- let i = network.info;
- if ((i.type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS && excludeMms) ||
- (i.type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_SUPL && excludeSupl) ||
- (i.type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_IMS && excludeIms) ||
- (i.type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN && excludeDun) ||
- (i.type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_FOTA && excludeFota)) {
- continue;
- }
-
- let ips = {};
- let prefixLengths = {};
- i.getAddresses(ips, prefixLengths);
-
- interfaces.push({
- state: i.state,
- type: i.type,
- name: i.name,
- ips: ips.value,
- prefixLengths: prefixLengths.value,
- gateways: i.getGateways(),
- dnses: i.getDnses()
- });
- }
- return interfaces;
- }
- }
- },
-
- getNetworkId: function(aNetworkInfo) {
- let id = "device";
- try {
- if (aNetworkInfo instanceof Ci.nsIRilNetworkInfo) {
- let rilInfo = aNetworkInfo.QueryInterface(Ci.nsIRilNetworkInfo);
- id = "ril" + rilInfo.serviceId;
- }
- } catch (e) {}
-
- return id + "-" + aNetworkInfo.type;
- },
-
- // nsINetworkManager
-
- registerNetworkInterface: function(network) {
- if (!(network instanceof Ci.nsINetworkInterface)) {
- throw Components.Exception("Argument must be nsINetworkInterface.",
- Cr.NS_ERROR_INVALID_ARG);
- }
- let networkId = this.getNetworkId(network.info);
- if (networkId in this.networkInterfaces) {
- throw Components.Exception("Network with that type already registered!",
- Cr.NS_ERROR_INVALID_ARG);
- }
- this.networkInterfaces[networkId] = network;
- this.networkInterfaceLinks[networkId] = new NetworkInterfaceLinks();
-
- Services.obs.notifyObservers(network.info, TOPIC_INTERFACE_REGISTERED, null);
- debug("Network '" + networkId + "' registered.");
- },
-
- _addSubnetRoutes: function(network) {
- let ips = {};
- let prefixLengths = {};
- let length = network.getAddresses(ips, prefixLengths);
- let promises = [];
-
- for (let i = 0; i < length; i++) {
- debug('Adding subnet routes: ' + ips.value[i] + '/' + prefixLengths.value[i]);
- promises.push(
- gNetworkService.modifyRoute(Ci.nsINetworkService.MODIFY_ROUTE_ADD,
- network.name, ips.value[i], prefixLengths.value[i])
- .catch(aError => {
- debug("_addSubnetRoutes error: " + aError);
- }));
- }
-
- return Promise.all(promises);
- },
-
- updateNetworkInterface: function(network) {
- if (!(network instanceof Ci.nsINetworkInterface)) {
- throw Components.Exception("Argument must be nsINetworkInterface.",
- Cr.NS_ERROR_INVALID_ARG);
- }
- let networkId = this.getNetworkId(network.info);
- if (!(networkId in this.networkInterfaces)) {
- throw Components.Exception("No network with that type registered.",
- Cr.NS_ERROR_INVALID_ARG);
- }
- debug("Network " + network.info.type + "/" + network.info.name +
- " changed state to " + network.info.state);
-
- // Keep a copy of network in case it is modified while we are updating.
- let extNetworkInfo = new ExtraNetworkInfo(network);
-
- // Note that since Lollipop we need to allocate and initialize
- // something through netd, so we add createNetwork/destroyNetwork
- // to deal with that explicitly.
-
- switch (extNetworkInfo.state) {
- case Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED:
-
- this._createNetwork(extNetworkInfo.name)
- // Remove pre-created default route and let setAndConfigureActive()
- // to set default route only on preferred network
- .then(() => this._removeDefaultRoute(extNetworkInfo))
- // Set DNS server as early as possible to prevent from
- // premature domain name lookup.
- .then(() => this._setDNS(extNetworkInfo))
- .then(() => {
- // Add host route for data calls
- if (!this.isNetworkTypeMobile(extNetworkInfo.type)) {
- return;
- }
-
- let currentInterfaceLinks = this.networkInterfaceLinks[networkId];
- let newLinkRoutes = extNetworkInfo.getDnses().concat(
- extNetworkInfo.httpProxyHost);
- // If gateways have changed, remove all old routes first.
- return this._handleGateways(networkId, extNetworkInfo.getGateways())
- .then(() => this._updateRoutes(currentInterfaceLinks.linkRoutes,
- newLinkRoutes,
- extNetworkInfo.getGateways(),
- extNetworkInfo.name))
- .then(() => currentInterfaceLinks.setLinks(newLinkRoutes,
- extNetworkInfo.getGateways(),
- extNetworkInfo.name));
- })
- .then(() => {
- if (extNetworkInfo.type !=
- Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN) {
- return;
- }
- // Dun type is a special case where we add the default route to a
- // secondary table.
- return this.setSecondaryDefaultRoute(extNetworkInfo);
- })
- .then(() => this._addSubnetRoutes(extNetworkInfo))
- .then(() => {
- if (extNetworkInfo.mtu <= 0) {
- return;
- }
-
- return this._setMtu(extNetworkInfo);
- })
- .then(() => this.setAndConfigureActive())
- .then(() => {
- // Update data connection when Wifi connected/disconnected
- if (extNetworkInfo.type ==
- Ci.nsINetworkInfo.NETWORK_TYPE_WIFI && this.mRil) {
- for (let i = 0; i < this.mRil.numRadioInterfaces; i++) {
- this.mRil.getRadioInterface(i).updateRILNetworkInterface();
- }
- }
-
- // Probing the public network accessibility after routing table is ready
- CaptivePortalDetectionHelper
- .notify(CaptivePortalDetectionHelper.EVENT_CONNECT,
- this.activeNetworkInfo);
- })
- .then(() => {
- // Notify outer modules like MmsService to start the transaction after
- // the configuration of the network interface is done.
- Services.obs.notifyObservers(network.info,
- TOPIC_CONNECTION_STATE_CHANGED,
- this.convertConnectionType(network.info));
- })
- .catch(aError => {
- debug("updateNetworkInterface error: " + aError);
- });
- break;
- case Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED:
- Promise.resolve()
- .then(() => {
- if (!this.isNetworkTypeMobile(extNetworkInfo.type)) {
- return;
- }
- // Remove host route for data calls
- return this._cleanupAllHostRoutes(networkId);
- })
- .then(() => {
- if (extNetworkInfo.type !=
- Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN) {
- return;
- }
- // Remove secondary default route for dun.
- return this.removeSecondaryDefaultRoute(extNetworkInfo);
- })
- .then(() => {
- if (extNetworkInfo.type == Ci.nsINetworkInfo.NETWORK_TYPE_WIFI ||
- extNetworkInfo.type == Ci.nsINetworkInfo.NETWORK_TYPE_ETHERNET) {
- // Remove routing table in /proc/net/route
- return this._resetRoutingTable(extNetworkInfo.name);
- }
- if (extNetworkInfo.type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE) {
- return this._removeDefaultRoute(extNetworkInfo)
- }
- })
- .then(() => {
- // Clear http proxy on active network.
- if (this.activeNetworkInfo &&
- extNetworkInfo.type == this.activeNetworkInfo.type) {
- this.clearNetworkProxy();
- }
-
- // Abort ongoing captive portal detection on the wifi interface
- CaptivePortalDetectionHelper
- .notify(CaptivePortalDetectionHelper.EVENT_DISCONNECT, extNetworkInfo);
- })
- .then(() => this.setAndConfigureActive())
- .then(() => {
- // Update data connection when Wifi connected/disconnected
- if (extNetworkInfo.type ==
- Ci.nsINetworkInfo.NETWORK_TYPE_WIFI && this.mRil) {
- for (let i = 0; i < this.mRil.numRadioInterfaces; i++) {
- this.mRil.getRadioInterface(i).updateRILNetworkInterface();
- }
- }
- })
- .then(() => this._destroyNetwork(extNetworkInfo.name))
- .then(() => {
- // Notify outer modules like MmsService to start the transaction after
- // the configuration of the network interface is done.
- Services.obs.notifyObservers(network.info,
- TOPIC_CONNECTION_STATE_CHANGED,
- this.convertConnectionType(network.info));
- })
- .catch(aError => {
- debug("updateNetworkInterface error: " + aError);
- });
- break;
- }
- },
-
- unregisterNetworkInterface: function(network) {
- if (!(network instanceof Ci.nsINetworkInterface)) {
- throw Components.Exception("Argument must be nsINetworkInterface.",
- Cr.NS_ERROR_INVALID_ARG);
- }
- let networkId = this.getNetworkId(network.info);
- if (!(networkId in this.networkInterfaces)) {
- throw Components.Exception("No network with that type registered.",
- Cr.NS_ERROR_INVALID_ARG);
- }
-
- // This is for in case a network gets unregistered without being
- // DISCONNECTED.
- if (this.isNetworkTypeMobile(network.info.type)) {
- this._cleanupAllHostRoutes(networkId);
- }
-
- delete this.networkInterfaces[networkId];
-
- Services.obs.notifyObservers(network.info, TOPIC_INTERFACE_UNREGISTERED, null);
- debug("Network '" + networkId + "' unregistered.");
- },
-
- _manageOfflineStatus: true,
-
- networkInterfaces: null,
-
- networkInterfaceLinks: null,
-
- _networkTypePriorityList: [Ci.nsINetworkInterface.NETWORK_TYPE_ETHERNET,
- Ci.nsINetworkInterface.NETWORK_TYPE_WIFI,
- Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE],
- get networkTypePriorityList() {
- return this._networkTypePriorityList;
- },
- set networkTypePriorityList(val) {
- if (val.length != this._networkTypePriorityList.length) {
- throw "Priority list length should equal to " +
- this._networkTypePriorityList.length;
- }
-
- // Check if types in new priority list are valid and also make sure there
- // are no duplicate types.
- let list = [Ci.nsINetworkInterface.NETWORK_TYPE_ETHERNET,
- Ci.nsINetworkInterface.NETWORK_TYPE_WIFI,
- Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE];
- while (list.length) {
- let type = list.shift();
- if (val.indexOf(type) == -1) {
- throw "There is missing network type";
- }
- }
-
- this._networkTypePriorityList = val;
- },
-
- getPriority: function(type) {
- if (this._networkTypePriorityList.indexOf(type) == -1) {
- // 0 indicates the lowest priority.
- return 0;
- }
-
- return this._networkTypePriorityList.length -
- this._networkTypePriorityList.indexOf(type);
- },
-
- get allNetworkInfo() {
- let allNetworkInfo = {};
-
- for (let networkId in this.networkInterfaces) {
- if (this.networkInterfaces.hasOwnProperty(networkId)) {
- allNetworkInfo[networkId] = this.networkInterfaces[networkId].info;
- }
- }
-
- return allNetworkInfo;
- },
-
- _preferredNetworkType: DEFAULT_PREFERRED_NETWORK_TYPE,
- get preferredNetworkType() {
- return this._preferredNetworkType;
- },
- set preferredNetworkType(val) {
- if ([Ci.nsINetworkInterface.NETWORK_TYPE_WIFI,
- Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE,
- Ci.nsINetworkInterface.NETWORK_TYPE_ETHERNET].indexOf(val) == -1) {
- throw "Invalid network type";
- }
- this._preferredNetworkType = val;
- },
-
- _activeNetwork: null,
-
- get activeNetworkInfo() {
- return this._activeNetwork && this._activeNetwork.info;
- },
-
- _overriddenActive: null,
-
- overrideActive: function(network) {
- if ([Ci.nsINetworkInterface.NETWORK_TYPE_WIFI,
- Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE,
- Ci.nsINetworkInterface.NETWORK_TYPE_ETHERNET].indexOf(val) == -1) {
- throw "Invalid network type";
- }
-
- this._overriddenActive = network;
- this.setAndConfigureActive();
- },
-
- _updateRoutes: function(oldLinks, newLinks, gateways, interfaceName) {
- // Returns items that are in base but not in target.
- function getDifference(base, target) {
- return base.filter(function(i) { return target.indexOf(i) < 0; });
- }
-
- let addedLinks = getDifference(newLinks, oldLinks);
- let removedLinks = getDifference(oldLinks, newLinks);
-
- if (addedLinks.length === 0 && removedLinks.length === 0) {
- return Promise.resolve();
- }
-
- return this._setHostRoutes(false, removedLinks, interfaceName, gateways)
- .then(this._setHostRoutes(true, addedLinks, interfaceName, gateways));
- },
-
- _setHostRoutes: function(doAdd, ipAddresses, networkName, gateways) {
- let getMaxPrefixLength = (aIp) => {
- return aIp.match(this.REGEXP_IPV4) ? IPV4_MAX_PREFIX_LENGTH : IPV6_MAX_PREFIX_LENGTH;
- }
-
- let promises = [];
-
- ipAddresses.forEach((aIpAddress) => {
- let gateway = this.selectGateway(gateways, aIpAddress);
- if (gateway) {
- promises.push((doAdd)
- ? gNetworkService.modifyRoute(Ci.nsINetworkService.MODIFY_ROUTE_ADD,
- networkName, aIpAddress,
- getMaxPrefixLength(aIpAddress), gateway)
- : gNetworkService.modifyRoute(Ci.nsINetworkService.MODIFY_ROUTE_REMOVE,
- networkName, aIpAddress,
- getMaxPrefixLength(aIpAddress), gateway));
- }
- });
-
- return Promise.all(promises);
- },
-
- isValidatedNetwork: function(aNetworkInfo) {
- let isValid = false;
- try {
- isValid = (this.getNetworkId(aNetworkInfo) in this.networkInterfaces);
- } catch (e) {
- debug("Invalid network interface: " + e);
- }
-
- return isValid;
- },
-
- addHostRoute: function(aNetworkInfo, aHost) {
- if (!this.isValidatedNetwork(aNetworkInfo)) {
- return Promise.reject("Invalid network info.");
- }
-
- return this.resolveHostname(aNetworkInfo, aHost)
- .then((ipAddresses) => {
- let promises = [];
- let networkId = this.getNetworkId(aNetworkInfo);
-
- ipAddresses.forEach((aIpAddress) => {
- let promise =
- this._setHostRoutes(true, [aIpAddress], aNetworkInfo.name, aNetworkInfo.getGateways())
- .then(() => this.networkInterfaceLinks[networkId].extraRoutes.push(aIpAddress));
-
- promises.push(promise);
- });
-
- return Promise.all(promises);
- });
- },
-
- removeHostRoute: function(aNetworkInfo, aHost) {
- if (!this.isValidatedNetwork(aNetworkInfo)) {
- return Promise.reject("Invalid network info.");
- }
-
- return this.resolveHostname(aNetworkInfo, aHost)
- .then((ipAddresses) => {
- let promises = [];
- let networkId = this.getNetworkId(aNetworkInfo);
-
- ipAddresses.forEach((aIpAddress) => {
- let found = this.networkInterfaceLinks[networkId].extraRoutes.indexOf(aIpAddress);
- if (found < 0) {
- return; // continue
- }
-
- let promise =
- this._setHostRoutes(false, [aIpAddress], aNetworkInfo.name, aNetworkInfo.getGateways())
- .then(() => {
- this.networkInterfaceLinks[networkId].extraRoutes.splice(found, 1);
- }, () => {
- // We should remove it even if the operation failed.
- this.networkInterfaceLinks[networkId].extraRoutes.splice(found, 1);
- });
- promises.push(promise);
- });
-
- return Promise.all(promises);
- });
- },
-
- isNetworkTypeSecondaryMobile: function(type) {
- return (type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS ||
- type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_SUPL ||
- type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_IMS ||
- type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN ||
- type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_FOTA);
- },
-
- isNetworkTypeMobile: function(type) {
- return (type == Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE ||
- this.isNetworkTypeSecondaryMobile(type));
- },
-
- _handleGateways: function(networkId, gateways) {
- let currentNetworkLinks = this.networkInterfaceLinks[networkId];
- if (currentNetworkLinks.gateways.length == 0 ||
- currentNetworkLinks.compareGateways(gateways)) {
- return Promise.resolve();
- }
-
- let currentExtraRoutes = currentNetworkLinks.extraRoutes;
- return this._cleanupAllHostRoutes(networkId)
- .then(() => {
- // If gateways have changed, re-add extra host routes with new gateways.
- if (currentExtraRoutes.length > 0) {
- this._setHostRoutes(true,
- currentExtraRoutes,
- currentNetworkLinks.interfaceName,
- gateways)
- .then(() => {
- currentNetworkLinks.extraRoutes = currentExtraRoutes;
- });
- }
- });
- },
-
- _cleanupAllHostRoutes: function(networkId) {
- let currentNetworkLinks = this.networkInterfaceLinks[networkId];
- let hostRoutes = currentNetworkLinks.linkRoutes.concat(
- currentNetworkLinks.extraRoutes);
-
- if (hostRoutes.length === 0) {
- return Promise.resolve();
- }
-
- return this._setHostRoutes(false,
- hostRoutes,
- currentNetworkLinks.interfaceName,
- currentNetworkLinks.gateways)
- .catch((aError) => {
- debug("Error (" + aError + ") on _cleanupAllHostRoutes, keep proceeding.");
- })
- .then(() => currentNetworkLinks.resetLinks());
- },
-
- selectGateway: function(gateways, host) {
- for (let i = 0; i < gateways.length; i++) {
- let gateway = gateways[i];
- if (gateway.match(this.REGEXP_IPV4) && host.match(this.REGEXP_IPV4) ||
- gateway.indexOf(":") != -1 && host.indexOf(":") != -1) {
- return gateway;
- }
- }
- return null;
- },
-
- _setSecondaryRoute: function(aDoAdd, aInterfaceName, aRoute) {
- return new Promise((aResolve, aReject) => {
- if (aDoAdd) {
- gNetworkService.addSecondaryRoute(aInterfaceName, aRoute,
- (aSuccess) => {
- if (!aSuccess) {
- aReject("addSecondaryRoute failed");
- return;
- }
- aResolve();
- });
- } else {
- gNetworkService.removeSecondaryRoute(aInterfaceName, aRoute,
- (aSuccess) => {
- if (!aSuccess) {
- debug("removeSecondaryRoute failed")
- }
- // Always resolve.
- aResolve();
- });
- }
- });
- },
-
- setSecondaryDefaultRoute: function(network) {
- let gateways = network.getGateways();
- let promises = [];
-
- for (let i = 0; i < gateways.length; i++) {
- let isIPv6 = (gateways[i].indexOf(":") != -1) ? true : false;
- // First, we need to add a host route to the gateway in the secondary
- // routing table to make the gateway reachable. Host route takes the max
- // prefix and gateway address 'any'.
- let hostRoute = {
- ip: gateways[i],
- prefix: isIPv6 ? IPV6_MAX_PREFIX_LENGTH : IPV4_MAX_PREFIX_LENGTH,
- gateway: isIPv6 ? IPV6_ADDRESS_ANY : IPV4_ADDRESS_ANY
- };
- // Now we can add the default route through gateway. Default route takes the
- // min prefix and destination ip 'any'.
- let defaultRoute = {
- ip: isIPv6 ? IPV6_ADDRESS_ANY : IPV4_ADDRESS_ANY,
- prefix: 0,
- gateway: gateways[i]
- };
-
- let promise = this._setSecondaryRoute(true, network.name, hostRoute)
- .then(() => this._setSecondaryRoute(true, network.name, defaultRoute));
-
- promises.push(promise);
- }
-
- return Promise.all(promises);
- },
-
- removeSecondaryDefaultRoute: function(network) {
- let gateways = network.getGateways();
- let promises = [];
-
- for (let i = 0; i < gateways.length; i++) {
- let isIPv6 = (gateways[i].indexOf(":") != -1) ? true : false;
- // Remove both default route and host route.
- let defaultRoute = {
- ip: isIPv6 ? IPV6_ADDRESS_ANY : IPV4_ADDRESS_ANY,
- prefix: 0,
- gateway: gateways[i]
- };
- let hostRoute = {
- ip: gateways[i],
- prefix: isIPv6 ? IPV6_MAX_PREFIX_LENGTH : IPV4_MAX_PREFIX_LENGTH,
- gateway: isIPv6 ? IPV6_ADDRESS_ANY : IPV4_ADDRESS_ANY
- };
-
- let promise = this._setSecondaryRoute(false, network.name, defaultRoute)
- .then(() => this._setSecondaryRoute(false, network.name, hostRoute));
-
- promises.push(promise);
- }
-
- return Promise.all(promises);
- },
-
- /**
- * Determine the active interface and configure it.
- */
- setAndConfigureActive: function() {
- debug("Evaluating whether active network needs to be changed.");
- let oldActive = this._activeNetwork;
-
- if (this._overriddenActive) {
- debug("We have an override for the active network: " +
- this._overriddenActive.info.name);
- // The override was just set, so reconfigure the network.
- if (this._activeNetwork != this._overriddenActive) {
- this._activeNetwork = this._overriddenActive;
- this._setDefaultRouteAndProxy(this._activeNetwork, oldActive);
- Services.obs.notifyObservers(this.activeNetworkInfo,
- TOPIC_ACTIVE_CHANGED, null);
- }
- return;
- }
-
- // The active network is already our preferred type.
- if (this.activeNetworkInfo &&
- this.activeNetworkInfo.state == Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED &&
- this.activeNetworkInfo.type == this._preferredNetworkType) {
- debug("Active network is already our preferred type.");
- return this._setDefaultRouteAndProxy(this._activeNetwork, oldActive);
- }
-
- // Find a suitable network interface to activate.
- this._activeNetwork = null;
- let anyConnected = false;
-
- for (let key in this.networkInterfaces) {
- let network = this.networkInterfaces[key];
- if (network.info.state != Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- continue;
- }
- anyConnected = true;
-
- // Set active only for default connections.
- if (network.info.type != Ci.nsINetworkInfo.NETWORK_TYPE_WIFI &&
- network.info.type != Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE &&
- network.info.type != Ci.nsINetworkInfo.NETWORK_TYPE_ETHERNET) {
- continue;
- }
-
- if (network.info.type == this.preferredNetworkType) {
- this._activeNetwork = network;
- debug("Found our preferred type of network: " + network.info.name);
- break;
- }
-
- // Initialize the active network with the first connected network.
- if (!this._activeNetwork) {
- this._activeNetwork = network;
- continue;
- }
-
- // Compare the prioriy between two network types. If found incoming
- // network with higher priority, replace the active network.
- if (this.getPriority(this._activeNetwork.type) < this.getPriority(network.type)) {
- this._activeNetwork = network;
- }
- }
-
- return Promise.resolve()
- .then(() => {
- if (!this._activeNetwork) {
- return Promise.resolve();
- }
-
- return this._setDefaultRouteAndProxy(this._activeNetwork, oldActive);
- })
- .then(() => {
- if (this._activeNetwork != oldActive) {
- Services.obs.notifyObservers(this.activeNetworkInfo,
- TOPIC_ACTIVE_CHANGED, null);
- }
-
- if (this._manageOfflineStatus) {
- Services.io.offline = !anyConnected &&
- (gTetheringService.state ===
- Ci.nsITetheringService.TETHERING_STATE_INACTIVE);
- }
- });
- },
-
- resolveHostname: function(aNetworkInfo, aHostname) {
- // Sanity check for null, undefined and empty string... etc.
- if (!aHostname) {
- return Promise.reject(new Error("hostname is empty: " + aHostname));
- }
-
- if (aHostname.match(this.REGEXP_IPV4) ||
- aHostname.match(this.REGEXP_IPV6)) {
- return Promise.resolve([aHostname]);
- }
-
- // Wrap gDNSService.asyncResolveExtended to a promise, which
- // resolves with an array of ip addresses or rejects with
- // the reason otherwise.
- let hostResolveWrapper = aNetId => {
- return new Promise((aResolve, aReject) => {
- // Callback for gDNSService.asyncResolveExtended.
- let onLookupComplete = (aRequest, aRecord, aStatus) => {
- if (!Components.isSuccessCode(aStatus)) {
- aReject(new Error("Failed to resolve '" + aHostname +
- "', with status: " + aStatus));
- return;
- }
-
- let retval = [];
- while (aRecord.hasMore()) {
- retval.push(aRecord.getNextAddrAsString());
- }
-
- if (!retval.length) {
- aReject(new Error("No valid address after DNS lookup!"));
- return;
- }
-
- debug("hostname is resolved: " + aHostname);
- debug("Addresses: " + JSON.stringify(retval));
-
- aResolve(retval);
- };
-
- debug('Calling gDNSService.asyncResolveExtended: ' + aNetId + ', ' + aHostname);
- gDNSService.asyncResolveExtended(aHostname,
- 0,
- aNetId,
- onLookupComplete,
- Services.tm.mainThread);
- });
- };
-
- // TODO: |getNetId| will be implemented as a sync call in nsINetworkManager
- // once Bug 1141903 is landed.
- return gNetworkService.getNetId(aNetworkInfo.name)
- .then(aNetId => hostResolveWrapper(aNetId));
- },
-
- convertConnectionType: function(aNetworkInfo) {
- // If there is internal interface change (e.g., MOBILE_MMS, MOBILE_SUPL),
- // the function will return null so that it won't trigger type change event
- // in NetworkInformation API.
- if (aNetworkInfo.type != Ci.nsINetworkInterface.NETWORK_TYPE_WIFI &&
- aNetworkInfo.type != Ci.nsINetworkInterface.NETWORK_TYPE_MOBILE &&
- aNetworkInfo.type != Ci.nsINetworkInterface.NETWORK_TYPE_ETHERNET) {
- return null;
- }
-
- if (aNetworkInfo.state == Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED) {
- return CONNECTION_TYPE_NONE;
- }
-
- switch (aNetworkInfo.type) {
- case Ci.nsINetworkInfo.NETWORK_TYPE_WIFI:
- return CONNECTION_TYPE_WIFI;
- case Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE:
- return CONNECTION_TYPE_CELLULAR;
- case Ci.nsINetworkInterface.NETWORK_TYPE_ETHERNET:
- return CONNECTION_TYPE_ETHERNET;
- }
- },
-
- _setDNS: function(aNetworkInfo) {
- return new Promise((aResolve, aReject) => {
- let dnses = aNetworkInfo.getDnses();
- let gateways = aNetworkInfo.getGateways();
- gNetworkService.setDNS(aNetworkInfo.name, dnses.length, dnses,
- gateways.length, gateways, (aError) => {
- if (aError) {
- aReject("setDNS failed");
- return;
- }
- aResolve();
- });
- });
- },
-
- _setMtu: function(aNetworkInfo) {
- return new Promise((aResolve, aReject) => {
- gNetworkService.setMtu(aNetworkInfo.name, aNetworkInfo.mtu, (aSuccess) => {
- if (!aSuccess) {
- debug("setMtu failed");
- }
- // Always resolve.
- aResolve();
- });
- });
- },
-
- _createNetwork: function(aInterfaceName) {
- return new Promise((aResolve, aReject) => {
- gNetworkService.createNetwork(aInterfaceName, (aSuccess) => {
- if (!aSuccess) {
- aReject("createNetwork failed");
- return;
- }
- aResolve();
- });
- });
- },
-
- _destroyNetwork: function(aInterfaceName) {
- return new Promise((aResolve, aReject) => {
- gNetworkService.destroyNetwork(aInterfaceName, (aSuccess) => {
- if (!aSuccess) {
- debug("destroyNetwork failed")
- }
- // Always resolve.
- aResolve();
- });
- });
- },
-
- _resetRoutingTable: function(aInterfaceName) {
- return new Promise((aResolve, aReject) => {
- gNetworkService.resetRoutingTable(aInterfaceName, (aSuccess) => {
- if (!aSuccess) {
- debug("resetRoutingTable failed");
- }
- // Always resolve.
- aResolve();
- });
- });
- },
-
- _removeDefaultRoute: function(aNetworkInfo) {
- return new Promise((aResolve, aReject) => {
- let gateways = aNetworkInfo.getGateways();
- gNetworkService.removeDefaultRoute(aNetworkInfo.name, gateways.length,
- gateways, (aSuccess) => {
- if (!aSuccess) {
- debug("removeDefaultRoute failed");
- }
- // Always resolve.
- aResolve();
- });
- });
- },
-
- _setDefaultRouteAndProxy: function(aNetwork, aOldNetwork) {
- if (aOldNetwork) {
- return this._removeDefaultRoute(aOldNetwork.info)
- .then(() => this._setDefaultRouteAndProxy(aNetwork, null));
- }
-
- return new Promise((aResolve, aReject) => {
- let networkInfo = aNetwork.info;
- let gateways = networkInfo.getGateways();
-
- gNetworkService.setDefaultRoute(networkInfo.name, gateways.length, gateways,
- (aSuccess) => {
- if (!aSuccess) {
- gNetworkService.destroyNetwork(networkInfo.name, function() {
- aReject("setDefaultRoute failed");
- });
- return;
- }
- this.setNetworkProxy(aNetwork);
- aResolve();
- });
- });
- },
-
- setNetworkProxy: function(aNetwork) {
- try {
- if (!aNetwork.httpProxyHost || aNetwork.httpProxyHost === "") {
- // Sets direct connection to internet.
- this.clearNetworkProxy();
-
- debug("No proxy support for " + aNetwork.info.name + " network interface.");
- return;
- }
-
- debug("Going to set proxy settings for " + aNetwork.info.name + " network interface.");
- // Sets manual proxy configuration.
- Services.prefs.setIntPref("network.proxy.type", MANUAL_PROXY_CONFIGURATION);
-
- // Do not use this proxy server for all protocols.
- Services.prefs.setBoolPref("network.proxy.share_proxy_settings", false);
- Services.prefs.setCharPref("network.proxy.http", aNetwork.httpProxyHost);
- Services.prefs.setCharPref("network.proxy.ssl", aNetwork.httpProxyHost);
- let port = aNetwork.httpProxyPort === 0 ? 8080 : aNetwork.httpProxyPort;
- Services.prefs.setIntPref("network.proxy.http_port", port);
- Services.prefs.setIntPref("network.proxy.ssl_port", port);
- } catch(ex) {
- debug("Exception " + ex + ". Unable to set proxy setting for " +
- aNetwork.info.name + " network interface.");
- }
- },
-
- clearNetworkProxy: function() {
- debug("Going to clear all network proxy.");
-
- Services.prefs.clearUserPref("network.proxy.type");
- Services.prefs.clearUserPref("network.proxy.share_proxy_settings");
- Services.prefs.clearUserPref("network.proxy.http");
- Services.prefs.clearUserPref("network.proxy.http_port");
- Services.prefs.clearUserPref("network.proxy.ssl");
- Services.prefs.clearUserPref("network.proxy.ssl_port");
- },
-};
-
-var CaptivePortalDetectionHelper = (function() {
-
- const EVENT_CONNECT = "Connect";
- const EVENT_DISCONNECT = "Disconnect";
- let _ongoingInterface = null;
- let _available = ("nsICaptivePortalDetector" in Ci);
- let getService = function() {
- return Cc['@mozilla.org/toolkit/captive-detector;1']
- .getService(Ci.nsICaptivePortalDetector);
- };
-
- let _performDetection = function(interfaceName, callback) {
- let capService = getService();
- let capCallback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsICaptivePortalCallback]),
- prepare: function() {
- capService.finishPreparation(interfaceName);
- },
- complete: function(success) {
- _ongoingInterface = null;
- callback(success);
- }
- };
-
- // Abort any unfinished captive portal detection.
- if (_ongoingInterface != null) {
- capService.abort(_ongoingInterface);
- _ongoingInterface = null;
- }
- try {
- capService.checkCaptivePortal(interfaceName, capCallback);
- _ongoingInterface = interfaceName;
- } catch (e) {
- debug('Fail to detect captive portal due to: ' + e.message);
- }
- };
-
- let _abort = function(interfaceName) {
- if (_ongoingInterface !== interfaceName) {
- return;
- }
-
- let capService = getService();
- capService.abort(_ongoingInterface);
- _ongoingInterface = null;
- };
-
- return {
- EVENT_CONNECT: EVENT_CONNECT,
- EVENT_DISCONNECT: EVENT_DISCONNECT,
- notify: function(eventType, network) {
- switch (eventType) {
- case EVENT_CONNECT:
- // perform captive portal detection on wifi interface
- if (_available && network &&
- network.type == Ci.nsINetworkInfo.NETWORK_TYPE_WIFI) {
- _performDetection(network.name, function() {
- // TODO: bug 837600
- // We can disconnect wifi in here if user abort the login procedure.
- });
- }
-
- break;
- case EVENT_DISCONNECT:
- if (_available &&
- network.type == Ci.nsINetworkInfo.NETWORK_TYPE_WIFI) {
- _abort(network.name);
- }
- break;
- }
- }
- };
-}());
-
-XPCOMUtils.defineLazyGetter(NetworkManager.prototype, "mRil", function() {
- try {
- return Cc["@mozilla.org/ril;1"].getService(Ci.nsIRadioInterfaceLayer);
- } catch (e) {}
-
- return null;
-});
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NetworkManager]);
diff --git a/dom/system/gonk/NetworkManager.manifest b/dom/system/gonk/NetworkManager.manifest
deleted file mode 100644
index 995fa6559..000000000
--- a/dom/system/gonk/NetworkManager.manifest
+++ /dev/null
@@ -1,3 +0,0 @@
-# NetworkManager.js
-component {1ba9346b-53b5-4660-9dc6-58f0b258d0a6} NetworkManager.js
-contract @mozilla.org/network/manager;1 {1ba9346b-53b5-4660-9dc6-58f0b258d0a6}
diff --git a/dom/system/gonk/NetworkService.js b/dom/system/gonk/NetworkService.js
deleted file mode 100644
index 7147f40c7..000000000
--- a/dom/system/gonk/NetworkService.js
+++ /dev/null
@@ -1,862 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/NetUtil.jsm");
-Cu.import("resource://gre/modules/FileUtils.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-
-const NETWORKSERVICE_CONTRACTID = "@mozilla.org/network/service;1";
-const NETWORKSERVICE_CID = Components.ID("{48c13741-aec9-4a86-8962-432011708261}");
-
-const TOPIC_PREF_CHANGED = "nsPref:changed";
-const TOPIC_XPCOM_SHUTDOWN = "xpcom-shutdown";
-const PREF_NETWORK_DEBUG_ENABLED = "network.debugging.enabled";
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkWorker",
- "@mozilla.org/network/worker;1",
- "nsINetworkWorker");
-
-// 1xx - Requested action is proceeding
-const NETD_COMMAND_PROCEEDING = 100;
-// 2xx - Requested action has been successfully completed
-const NETD_COMMAND_OKAY = 200;
-// 4xx - The command is accepted but the requested action didn't
-// take place.
-const NETD_COMMAND_FAIL = 400;
-// 5xx - The command syntax or parameters error
-const NETD_COMMAND_ERROR = 500;
-// 6xx - Unsolicited broadcasts
-const NETD_COMMAND_UNSOLICITED = 600;
-
-const WIFI_CTRL_INTERFACE = "wl0.1";
-
-var debug;
-function updateDebug() {
- let debugPref = false; // set default value here.
- try {
- debugPref = debugPref || Services.prefs.getBoolPref(PREF_NETWORK_DEBUG_ENABLED);
- } catch (e) {}
-
- if (debugPref) {
- debug = function(s) {
- dump("-*- NetworkService: " + s + "\n");
- };
- } else {
- debug = function(s) {};
- }
-}
-updateDebug();
-
-function netdResponseType(aCode) {
- return Math.floor(aCode / 100) * 100;
-}
-
-function isError(aCode) {
- let type = netdResponseType(aCode);
- return (type !== NETD_COMMAND_PROCEEDING && type !== NETD_COMMAND_OKAY);
-}
-
-function Task(aId, aParams, aSetupFunction) {
- this.id = aId;
- this.params = aParams;
- this.setupFunction = aSetupFunction;
-}
-
-function NetworkWorkerRequestQueue(aNetworkService) {
- this.networkService = aNetworkService;
- this.tasks = [];
-}
-NetworkWorkerRequestQueue.prototype = {
- runQueue: function() {
- if (this.tasks.length === 0) {
- return;
- }
-
- let task = this.tasks[0];
- debug("run task id: " + task.id);
-
- if (typeof task.setupFunction === 'function') {
- // If setupFunction returns false, skip sending to Network Worker but call
- // handleWorkerMessage() directly with task id, as if the response was
- // returned from Network Worker.
- if (!task.setupFunction()) {
- this.networkService.handleWorkerMessage({id: task.id});
- return;
- }
- }
-
- gNetworkWorker.postMessage(task.params);
- },
-
- enqueue: function(aId, aParams, aSetupFunction) {
- debug("enqueue id: " + aId);
- this.tasks.push(new Task(aId, aParams, aSetupFunction));
-
- if (this.tasks.length === 1) {
- this.runQueue();
- }
- },
-
- dequeue: function(aId) {
- debug("dequeue id: " + aId);
-
- if (!this.tasks.length || this.tasks[0].id != aId) {
- debug("Id " + aId + " is not on top of the queue");
- return;
- }
-
- this.tasks.shift();
- if (this.tasks.length > 0) {
- // Run queue on the next tick.
- Services.tm.currentThread.dispatch(() => {
- this.runQueue();
- }, Ci.nsIThread.DISPATCH_NORMAL);
- }
- }
-};
-
-
-/**
- * This component watches for network interfaces changing state and then
- * adjusts routes etc. accordingly.
- */
-function NetworkService() {
- debug("Starting NetworkService.");
-
- let self = this;
-
- if (gNetworkWorker) {
- let networkListener = {
- onEvent: function(aEvent) {
- self.handleWorkerMessage(aEvent);
- }
- };
- gNetworkWorker.start(networkListener);
- }
- // Callbacks to invoke when a reply arrives from the net_worker.
- this.controlCallbacks = Object.create(null);
-
- this.addedRoutes = new Map();
- this.netWorkerRequestQueue = new NetworkWorkerRequestQueue(this);
- this.shutdown = false;
-
- Services.prefs.addObserver(PREF_NETWORK_DEBUG_ENABLED, this, false);
- Services.obs.addObserver(this, TOPIC_XPCOM_SHUTDOWN, false);
-}
-
-NetworkService.prototype = {
- classID: NETWORKSERVICE_CID,
- classInfo: XPCOMUtils.generateCI({classID: NETWORKSERVICE_CID,
- contractID: NETWORKSERVICE_CONTRACTID,
- classDescription: "Network Service",
- interfaces: [Ci.nsINetworkService]}),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkService,
- Ci.nsIObserver]),
-
- addedRoutes: null,
-
- shutdown: false,
-
- // nsIObserver
-
- observe: function(aSubject, aTopic, aData) {
- switch (aTopic) {
- case TOPIC_PREF_CHANGED:
- if (aData === PREF_NETWORK_DEBUG_ENABLED) {
- updateDebug();
- }
- break;
- case TOPIC_XPCOM_SHUTDOWN:
- debug("NetworkService shutdown");
- this.shutdown = true;
- if (gNetworkWorker) {
- gNetworkWorker.shutdown();
- gNetworkWorker = null;
- }
-
- Services.obs.removeObserver(this, TOPIC_XPCOM_SHUTDOWN);
- Services.prefs.removeObserver(PREF_NETWORK_DEBUG_ENABLED, this);
- break;
- }
- },
-
- // Helpers
-
- idgen: 0,
- controlMessage: function(aParams, aCallback, aSetupFunction) {
- if (this.shutdown) {
- return;
- }
-
- let id = this.idgen++;
- aParams.id = id;
- if (aCallback) {
- this.controlCallbacks[id] = aCallback;
- }
-
- // For now, we use aSetupFunction to determine if this command needs to be
- // queued or not.
- if (aSetupFunction) {
- this.netWorkerRequestQueue.enqueue(id, aParams, aSetupFunction);
- return;
- }
-
- if (gNetworkWorker) {
- gNetworkWorker.postMessage(aParams);
- }
- },
-
- handleWorkerMessage: function(aResponse) {
- debug("NetworkManager received message from worker: " + JSON.stringify(aResponse));
- let id = aResponse.id;
- if (aResponse.broadcast === true) {
- Services.obs.notifyObservers(null, aResponse.topic, aResponse.reason);
- return;
- }
- let callback = this.controlCallbacks[id];
- if (callback) {
- callback.call(this, aResponse);
- delete this.controlCallbacks[id];
- }
-
- this.netWorkerRequestQueue.dequeue(id);
- },
-
- // nsINetworkService
-
- getNetworkInterfaceStats: function(aInterfaceName, aCallback) {
- debug("getNetworkInterfaceStats for " + aInterfaceName);
-
- let file = new FileUtils.File("/proc/net/dev");
- if (!file) {
- aCallback.networkStatsAvailable(false, 0, 0, Date.now());
- return;
- }
-
- NetUtil.asyncFetch({
- uri: NetUtil.newURI(file),
- loadUsingSystemPrincipal: true
- }, function(inputStream, status) {
- let rxBytes = 0,
- txBytes = 0,
- now = Date.now();
-
- if (Components.isSuccessCode(status)) {
- // Find record for corresponding interface.
- let statExpr = /(\S+): +(\d+) +\d+ +\d+ +\d+ +\d+ +\d+ +\d+ +\d+ +(\d+) +\d+ +\d+ +\d+ +\d+ +\d+ +\d+ +\d+/;
- let data =
- NetUtil.readInputStreamToString(inputStream, inputStream.available())
- .split("\n");
- for (let i = 2; i < data.length; i++) {
- let parseResult = statExpr.exec(data[i]);
- if (parseResult && parseResult[1] === aInterfaceName) {
- rxBytes = parseInt(parseResult[2], 10);
- txBytes = parseInt(parseResult[3], 10);
- break;
- }
- }
- }
-
- // netd always return success even interface doesn't exist.
- aCallback.networkStatsAvailable(true, rxBytes, txBytes, now);
- });
- },
-
- setNetworkTetheringAlarm(aEnable, aInterface) {
- // Method called when enabling disabling tethering, it checks if there is
- // some alarm active and move from interfaceAlarm to globalAlarm because
- // interfaceAlarm doens't work in tethering scenario due to forwarding.
- debug("setNetworkTetheringAlarm for tethering" + aEnable);
-
- let filename = aEnable ? "/proc/net/xt_quota/" + aInterface + "Alert" :
- "/proc/net/xt_quota/globalAlert";
-
- let file = new FileUtils.File(filename);
- if (!file) {
- return;
- }
-
- NetUtil.asyncFetch({
- uri: NetUtil.newURI(file),
- loadUsingSystemPrincipal: true
- }, (inputStream, status) => {
- if (Components.isSuccessCode(status)) {
- let data = NetUtil.readInputStreamToString(inputStream, inputStream.available())
- .split("\n");
- if (data) {
- let threshold = parseInt(data[0], 10);
-
- this._setNetworkTetheringAlarm(aEnable, aInterface, threshold);
- }
- }
- });
- },
-
- _setNetworkTetheringAlarm(aEnable, aInterface, aThreshold, aCallback) {
- debug("_setNetworkTetheringAlarm for tethering" + aEnable);
-
- let cmd = aEnable ? "setTetheringAlarm" : "removeTetheringAlarm";
-
- let params = {
- cmd: cmd,
- ifname: aInterface,
- threshold: aThreshold,
- };
-
- this.controlMessage(params, function(aData) {
- let code = aData.resultCode;
- let reason = aData.resultReason;
- let enableString = aEnable ? "Enable" : "Disable";
- debug(enableString + " tethering Alarm result: Code " + code + " reason " + reason);
- if (aCallback) {
- aCallback.networkUsageAlarmResult(null);
- }
- });
- },
-
- setNetworkInterfaceAlarm: function(aInterfaceName, aThreshold, aCallback) {
- if (!aInterfaceName) {
- aCallback.networkUsageAlarmResult(-1);
- return;
- }
-
- let self = this;
- this._disableNetworkInterfaceAlarm(aInterfaceName, function(aResult) {
- if (aThreshold < 0) {
- if (!isError(aResult.resultCode)) {
- aCallback.networkUsageAlarmResult(null);
- return;
- }
- aCallback.networkUsageAlarmResult(aResult.reason);
- return
- }
-
- // Check if tethering is enabled
- let params = {
- cmd: "getTetheringStatus"
- };
-
- self.controlMessage(params, function(aResult) {
- if (isError(aResult.resultCode)) {
- aCallback.networkUsageAlarmResult(aResult.reason);
- return;
- }
-
- if (aResult.resultReason.indexOf('started') == -1) {
- // Tethering disabled, set interfaceAlarm
- self._setNetworkInterfaceAlarm(aInterfaceName, aThreshold, aCallback);
- return;
- }
-
- // Tethering enabled, set globalAlarm
- self._setNetworkTetheringAlarm(true, aInterfaceName, aThreshold, aCallback);
- });
- });
- },
-
- _setNetworkInterfaceAlarm: function(aInterfaceName, aThreshold, aCallback) {
- debug("setNetworkInterfaceAlarm for " + aInterfaceName + " at " + aThreshold + "bytes");
-
- let params = {
- cmd: "setNetworkInterfaceAlarm",
- ifname: aInterfaceName,
- threshold: aThreshold
- };
-
- params.report = true;
-
- this.controlMessage(params, function(aResult) {
- if (!isError(aResult.resultCode)) {
- aCallback.networkUsageAlarmResult(null);
- return;
- }
-
- this._enableNetworkInterfaceAlarm(aInterfaceName, aThreshold, aCallback);
- });
- },
-
- _enableNetworkInterfaceAlarm: function(aInterfaceName, aThreshold, aCallback) {
- debug("enableNetworkInterfaceAlarm for " + aInterfaceName + " at " + aThreshold + "bytes");
-
- let params = {
- cmd: "enableNetworkInterfaceAlarm",
- ifname: aInterfaceName,
- threshold: aThreshold
- };
-
- params.report = true;
-
- this.controlMessage(params, function(aResult) {
- if (!isError(aResult.resultCode)) {
- aCallback.networkUsageAlarmResult(null);
- return;
- }
- aCallback.networkUsageAlarmResult(aResult.reason);
- });
- },
-
- _disableNetworkInterfaceAlarm: function(aInterfaceName, aCallback) {
- debug("disableNetworkInterfaceAlarm for " + aInterfaceName);
-
- let params = {
- cmd: "disableNetworkInterfaceAlarm",
- ifname: aInterfaceName,
- };
-
- params.report = true;
-
- this.controlMessage(params, function(aResult) {
- aCallback(aResult);
- });
- },
-
- setWifiOperationMode: function(aInterfaceName, aMode, aCallback) {
- debug("setWifiOperationMode on " + aInterfaceName + " to " + aMode);
-
- let params = {
- cmd: "setWifiOperationMode",
- ifname: aInterfaceName,
- mode: aMode
- };
-
- params.report = true;
-
- this.controlMessage(params, function(aResult) {
- if (isError(aResult.resultCode)) {
- aCallback.wifiOperationModeResult("netd command error");
- } else {
- aCallback.wifiOperationModeResult(null);
- }
- });
- },
-
- resetRoutingTable: function(aInterfaceName, aCallback) {
- let options = {
- cmd: "removeNetworkRoute",
- ifname: aInterfaceName
- };
-
- this.controlMessage(options, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- setDNS: function(aInterfaceName, aDnsesCount, aDnses, aGatewaysCount,
- aGateways, aCallback) {
- debug("Going to set DNS to " + aInterfaceName);
- let options = {
- cmd: "setDNS",
- ifname: aInterfaceName,
- domain: "mozilla." + aInterfaceName + ".domain",
- dnses: aDnses,
- gateways: aGateways
- };
- this.controlMessage(options, function(aResult) {
- aCallback.setDnsResult(aResult.success ? null : aResult.reason);
- });
- },
-
- setDefaultRoute: function(aInterfaceName, aCount, aGateways, aCallback) {
- debug("Going to change default route to " + aInterfaceName);
- let options = {
- cmd: "setDefaultRoute",
- ifname: aInterfaceName,
- gateways: aGateways
- };
- this.controlMessage(options, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- removeDefaultRoute: function(aInterfaceName, aCount, aGateways, aCallback) {
- debug("Remove default route for " + aInterfaceName);
- let options = {
- cmd: "removeDefaultRoute",
- ifname: aInterfaceName,
- gateways: aGateways
- };
- this.controlMessage(options, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- _routeToString: function(aInterfaceName, aHost, aPrefixLength, aGateway) {
- return aHost + "-" + aPrefixLength + "-" + aGateway + "-" + aInterfaceName;
- },
-
- modifyRoute: function(aAction, aInterfaceName, aHost, aPrefixLength, aGateway) {
- let command;
-
- switch (aAction) {
- case Ci.nsINetworkService.MODIFY_ROUTE_ADD:
- command = 'addHostRoute';
- break;
- case Ci.nsINetworkService.MODIFY_ROUTE_REMOVE:
- command = 'removeHostRoute';
- break;
- default:
- debug('Unknown action: ' + aAction);
- return Promise.reject();
- }
-
- let route = this._routeToString(aInterfaceName, aHost, aPrefixLength, aGateway);
- let setupFunc = () => {
- let count = this.addedRoutes.get(route);
- debug(command + ": " + route + " -> " + count);
-
- // Return false if there is no need to send the command to network worker.
- if ((aAction == Ci.nsINetworkService.MODIFY_ROUTE_ADD && count) ||
- (aAction == Ci.nsINetworkService.MODIFY_ROUTE_REMOVE &&
- (!count || count > 1))) {
- return false;
- }
-
- return true;
- };
-
- debug(command + " " + aHost + " on " + aInterfaceName);
- let options = {
- cmd: command,
- ifname: aInterfaceName,
- gateway: aGateway,
- prefixLength: aPrefixLength,
- ip: aHost
- };
-
- return new Promise((aResolve, aReject) => {
- this.controlMessage(options, (aData) => {
- let count = this.addedRoutes.get(route);
-
- // Remove route from addedRoutes on success or failure.
- if (aAction == Ci.nsINetworkService.MODIFY_ROUTE_REMOVE) {
- if (count > 1) {
- this.addedRoutes.set(route, count - 1);
- } else {
- this.addedRoutes.delete(route);
- }
- }
-
- if (aData.error) {
- aReject(aData.reason);
- return;
- }
-
- if (aAction == Ci.nsINetworkService.MODIFY_ROUTE_ADD) {
- this.addedRoutes.set(route, count ? count + 1 : 1);
- }
-
- aResolve();
- }, setupFunc);
- });
- },
-
- addSecondaryRoute: function(aInterfaceName, aRoute, aCallback) {
- debug("Going to add route to secondary table on " + aInterfaceName);
- let options = {
- cmd: "addSecondaryRoute",
- ifname: aInterfaceName,
- ip: aRoute.ip,
- prefix: aRoute.prefix,
- gateway: aRoute.gateway
- };
- this.controlMessage(options, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- removeSecondaryRoute: function(aInterfaceName, aRoute, aCallback) {
- debug("Going to remove route from secondary table on " + aInterfaceName);
- let options = {
- cmd: "removeSecondaryRoute",
- ifname: aInterfaceName,
- ip: aRoute.ip,
- prefix: aRoute.prefix,
- gateway: aRoute.gateway
- };
- this.controlMessage(options, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- // Enable/Disable DHCP server.
- setDhcpServer: function(aEnabled, aConfig, aCallback) {
- if (null === aConfig) {
- aConfig = {};
- }
-
- aConfig.cmd = "setDhcpServer";
- aConfig.enabled = aEnabled;
-
- this.controlMessage(aConfig, function(aResponse) {
- if (!aResponse.success) {
- aCallback.dhcpServerResult('Set DHCP server error');
- return;
- }
- aCallback.dhcpServerResult(null);
- });
- },
-
- // Enable/disable WiFi tethering by sending commands to netd.
- setWifiTethering: function(aEnable, aConfig, aCallback) {
- // config should've already contained:
- // .ifname
- // .internalIfname
- // .externalIfname
- aConfig.wifictrlinterfacename = WIFI_CTRL_INTERFACE;
- aConfig.cmd = "setWifiTethering";
-
- // The callback function in controlMessage may not be fired immediately.
- this.controlMessage(aConfig, (aData) => {
- let code = aData.resultCode;
- let reason = aData.resultReason;
- let enable = aData.enable;
- let enableString = aEnable ? "Enable" : "Disable";
-
- debug(enableString + " Wifi tethering result: Code " + code + " reason " + reason);
-
- this.setNetworkTetheringAlarm(aEnable, aConfig.externalIfname);
-
- if (isError(code)) {
- aCallback.wifiTetheringEnabledChange("netd command error");
- } else {
- aCallback.wifiTetheringEnabledChange(null);
- }
- });
- },
-
- // Enable/disable USB tethering by sending commands to netd.
- setUSBTethering: function(aEnable, aConfig, aCallback) {
- aConfig.cmd = "setUSBTethering";
- // The callback function in controlMessage may not be fired immediately.
- this.controlMessage(aConfig, (aData) => {
- let code = aData.resultCode;
- let reason = aData.resultReason;
- let enable = aData.enable;
- let enableString = aEnable ? "Enable" : "Disable";
-
- debug(enableString + " USB tethering result: Code " + code + " reason " + reason);
-
- this.setNetworkTetheringAlarm(aEnable, aConfig.externalIfname);
-
- if (isError(code)) {
- aCallback.usbTetheringEnabledChange("netd command error");
- } else {
- aCallback.usbTetheringEnabledChange(null);
- }
- });
- },
-
- // Switch usb function by modifying property of persist.sys.usb.config.
- enableUsbRndis: function(aEnable, aCallback) {
- debug("enableUsbRndis: " + aEnable);
-
- let params = {
- cmd: "enableUsbRndis",
- enable: aEnable
- };
- // Ask net work to report the result when this value is set to true.
- if (aCallback) {
- params.report = true;
- } else {
- params.report = false;
- }
-
- // The callback function in controlMessage may not be fired immediately.
- //this._usbTetheringAction = TETHERING_STATE_ONGOING;
- this.controlMessage(params, function(aData) {
- aCallback.enableUsbRndisResult(aData.result, aData.enable);
- });
- },
-
- updateUpStream: function(aPrevious, aCurrent, aCallback) {
- let params = {
- cmd: "updateUpStream",
- preInternalIfname: aPrevious.internalIfname,
- preExternalIfname: aPrevious.externalIfname,
- curInternalIfname: aCurrent.internalIfname,
- curExternalIfname: aCurrent.externalIfname
- };
-
- this.controlMessage(params, function(aData) {
- let code = aData.resultCode;
- let reason = aData.resultReason;
- debug("updateUpStream result: Code " + code + " reason " + reason);
- aCallback.updateUpStreamResult(!isError(code), aData.curExternalIfname);
- });
- },
-
- getInterfaces: function(callback) {
- let params = {
- cmd: "getInterfaces",
- isAsync: true
- };
-
- this.controlMessage(params, function(data) {
- debug("getInterfaces result: " + JSON.stringify(data));
- let success = !isError(data.resultCode);
- callback.getInterfacesResult(success, data.interfaceList);
- });
- },
-
- getInterfaceConfig: function(ifname, callback) {
- let params = {
- cmd: "getInterfaceConfig",
- ifname: ifname,
- isAsync: true
- };
-
- this.controlMessage(params, function(data) {
- debug("getInterfaceConfig result: " + JSON.stringify(data));
- let success = !isError(data.resultCode);
- let result = { ip: data.ipAddr,
- prefix: data.prefixLength,
- link: data.flag,
- mac: data.macAddr };
- callback.getInterfaceConfigResult(success, result);
- });
- },
-
- setInterfaceConfig: function(config, callback) {
- config.cmd = "setInterfaceConfig";
- config.isAsync = true;
-
- this.controlMessage(config, function(data) {
- debug("setInterfaceConfig result: " + JSON.stringify(data));
- let success = !isError(data.resultCode);
- callback.setInterfaceConfigResult(success);
- });
- },
-
- configureInterface: function(aConfig, aCallback) {
- let params = {
- cmd: "configureInterface",
- ifname: aConfig.ifname,
- ipaddr: aConfig.ipaddr,
- mask: aConfig.mask,
- gateway_long: aConfig.gateway,
- dns1_long: aConfig.dns1,
- dns2_long: aConfig.dns2,
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- dhcpRequest: function(aInterfaceName, aCallback) {
- let params = {
- cmd: "dhcpRequest",
- ifname: aInterfaceName
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.dhcpRequestResult(!aResult.error, aResult.error ? null : aResult);
- });
- },
-
- stopDhcp: function(aInterfaceName, aCallback) {
- let params = {
- cmd: "stopDhcp",
- ifname: aInterfaceName
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- enableInterface: function(aInterfaceName, aCallback) {
- let params = {
- cmd: "enableInterface",
- ifname: aInterfaceName
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- disableInterface: function(aInterfaceName, aCallback) {
- let params = {
- cmd: "disableInterface",
- ifname: aInterfaceName
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- resetConnections: function(aInterfaceName, aCallback) {
- let params = {
- cmd: "resetConnections",
- ifname: aInterfaceName
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- createNetwork: function(aInterfaceName, aCallback) {
- let params = {
- cmd: "createNetwork",
- ifname: aInterfaceName
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- destroyNetwork: function(aInterfaceName, aCallback) {
- let params = {
- cmd: "destroyNetwork",
- ifname: aInterfaceName
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- },
-
- getNetId: function(aInterfaceName) {
- let params = {
- cmd: "getNetId",
- ifname: aInterfaceName
- };
-
- return new Promise((aResolve, aReject) => {
- this.controlMessage(params, result => {
- if (result.error) {
- aReject(result.reason);
- return;
- }
- aResolve(result.netId);
- });
- });
- },
-
- setMtu: function (aInterfaceName, aMtu, aCallback) {
- debug("Set MTU on " + aInterfaceName + ": " + aMtu);
-
- let params = {
- cmd: "setMtu",
- ifname: aInterfaceName,
- mtu: aMtu
- };
-
- this.controlMessage(params, function(aResult) {
- aCallback.nativeCommandResult(!aResult.error);
- });
- }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NetworkService]);
diff --git a/dom/system/gonk/NetworkService.manifest b/dom/system/gonk/NetworkService.manifest
deleted file mode 100644
index caf8f2554..000000000
--- a/dom/system/gonk/NetworkService.manifest
+++ /dev/null
@@ -1,3 +0,0 @@
-# NetworkService.js
-component {48c13741-aec9-4a86-8962-432011708261} NetworkService.js
-contract @mozilla.org/network/service;1 {48c13741-aec9-4a86-8962-432011708261}
diff --git a/dom/system/gonk/NetworkUtils.cpp b/dom/system/gonk/NetworkUtils.cpp
deleted file mode 100644
index d661368b8..000000000
--- a/dom/system/gonk/NetworkUtils.cpp
+++ /dev/null
@@ -1,2973 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "NetworkUtils.h"
-
-#include "mozilla/Sprintf.h"
-#include "SystemProperty.h"
-
-#include <android/log.h>
-#include <limits>
-#include "mozilla/dom/network/NetUtils.h"
-#include "mozilla/fallible.h"
-#include "base/task.h"
-
-#include <errno.h>
-#include <string.h>
-#include <sys/types.h> // struct addrinfo
-#include <sys/socket.h> // getaddrinfo(), freeaddrinfo()
-#include <netdb.h>
-#include <arpa/inet.h> // inet_ntop()
-
-#define _DEBUG 0
-
-#define WARN(args...) __android_log_print(ANDROID_LOG_WARN, "NetworkUtils", ## args)
-#define ERROR(args...) __android_log_print(ANDROID_LOG_ERROR, "NetworkUtils", ## args)
-
-#if _DEBUG
-#define NU_DBG(args...) __android_log_print(ANDROID_LOG_DEBUG, "NetworkUtils" , ## args)
-#else
-#define NU_DBG(args...)
-#endif
-
-using namespace mozilla::dom;
-using namespace mozilla::ipc;
-using mozilla::system::Property;
-
-static const char* PERSIST_SYS_USB_CONFIG_PROPERTY = "persist.sys.usb.config";
-static const char* SYS_USB_CONFIG_PROPERTY = "sys.usb.config";
-static const char* SYS_USB_STATE_PROPERTY = "sys.usb.state";
-
-static const char* USB_FUNCTION_RNDIS = "rndis";
-static const char* USB_FUNCTION_ADB = "adb";
-
-// Use this command to continue the function chain.
-static const char* DUMMY_COMMAND = "tether status";
-
-// IPV6 Tethering is not supported in AOSP, use the property to
-// identify vendor specific support in IPV6. We can remove this flag
-// once upstream Android support IPV6 in tethering.
-static const char* IPV6_TETHERING = "ro.tethering.ipv6";
-
-// Retry 20 times (2 seconds) for usb state transition.
-static const uint32_t USB_FUNCTION_RETRY_TIMES = 20;
-// Check "sys.usb.state" every 100ms.
-static const uint32_t USB_FUNCTION_RETRY_INTERVAL = 100;
-
-// 1xx - Requested action is proceeding
-static const uint32_t NETD_COMMAND_PROCEEDING = 100;
-// 2xx - Requested action has been successfully completed
-static const uint32_t NETD_COMMAND_OKAY = 200;
-// 4xx - The command is accepted but the requested action didn't
-// take place.
-static const uint32_t NETD_COMMAND_FAIL = 400;
-// 5xx - The command syntax or parameters error
-static const uint32_t NETD_COMMAND_ERROR = 500;
-// 6xx - Unsolicited broadcasts
-static const uint32_t NETD_COMMAND_UNSOLICITED = 600;
-
-// Broadcast messages
-static const uint32_t NETD_COMMAND_INTERFACE_CHANGE = 600;
-static const uint32_t NETD_COMMAND_BANDWIDTH_CONTROLLER = 601;
-
-static const char* INTERFACE_DELIMIT = ",";
-static const char* USB_CONFIG_DELIMIT = ",";
-static const char* NETD_MESSAGE_DELIMIT = " ";
-
-static const uint32_t BUF_SIZE = 1024;
-
-static const int32_t SUCCESS = 0;
-
-static uint32_t SDK_VERSION;
-static uint32_t SUPPORT_IPV6_TETHERING;
-
-struct IFProperties {
- char gateway[Property::VALUE_MAX_LENGTH];
- char dns1[Property::VALUE_MAX_LENGTH];
- char dns2[Property::VALUE_MAX_LENGTH];
-};
-
-struct CurrentCommand {
- CommandChain* chain;
- CommandCallback callback;
- char command[MAX_COMMAND_SIZE];
-};
-
-typedef Tuple3<NetdCommand*, CommandChain*, CommandCallback> QueueData;
-
-#define GET_CURRENT_NETD_COMMAND (gCommandQueue.IsEmpty() ? nullptr : gCommandQueue[0].a)
-#define GET_CURRENT_CHAIN (gCommandQueue.IsEmpty() ? nullptr : gCommandQueue[0].b)
-#define GET_CURRENT_CALLBACK (gCommandQueue.IsEmpty() ? nullptr : gCommandQueue[0].c)
-#define GET_CURRENT_COMMAND (gCommandQueue.IsEmpty() ? nullptr : gCommandQueue[0].a->mData)
-
-// A macro for native function call return value check.
-// For native function call, non-zero return value means failure.
-#define RETURN_IF_FAILED(rv) do { \
- if (SUCCESS != rv) { \
- return rv; \
- } \
-} while (0);
-
-#define WARN_IF_FAILED(rv) do { \
- if (SUCCESS != rv) { \
- WARN("Error (%d) occurred in %s (%s:%d)", rv, __PRETTY_FUNCTION__, __FILE__, __LINE__); \
- } \
-} while (0);
-
-static NetworkUtils* gNetworkUtils;
-static nsTArray<QueueData> gCommandQueue;
-static CurrentCommand gCurrentCommand;
-static bool gPending = false;
-static nsTArray<nsCString> gReason;
-static NetworkParams *gWifiTetheringParms = 0;
-
-static nsTArray<CommandChain*> gCommandChainQueue;
-
-const CommandFunc NetworkUtils::sWifiEnableChain[] = {
- NetworkUtils::clearWifiTetherParms,
- NetworkUtils::wifiFirmwareReload,
- NetworkUtils::startAccessPointDriver,
- NetworkUtils::setAccessPoint,
- NetworkUtils::startSoftAP,
- NetworkUtils::setConfig,
- NetworkUtils::tetherInterface,
- NetworkUtils::addInterfaceToLocalNetwork,
- NetworkUtils::addRouteToLocalNetwork,
- NetworkUtils::setIpForwardingEnabled,
- NetworkUtils::tetheringStatus,
- NetworkUtils::startTethering,
- NetworkUtils::setDnsForwarders,
- NetworkUtils::enableNat,
- NetworkUtils::wifiTetheringSuccess
-};
-
-const CommandFunc NetworkUtils::sWifiDisableChain[] = {
- NetworkUtils::clearWifiTetherParms,
- NetworkUtils::stopSoftAP,
- NetworkUtils::stopAccessPointDriver,
- NetworkUtils::wifiFirmwareReload,
- NetworkUtils::untetherInterface,
- NetworkUtils::removeInterfaceFromLocalNetwork,
- NetworkUtils::preTetherInterfaceList,
- NetworkUtils::postTetherInterfaceList,
- NetworkUtils::disableNat,
- NetworkUtils::setIpForwardingEnabled,
- NetworkUtils::stopTethering,
- NetworkUtils::wifiTetheringSuccess
-};
-
-const CommandFunc NetworkUtils::sWifiFailChain[] = {
- NetworkUtils::clearWifiTetherParms,
- NetworkUtils::stopSoftAP,
- NetworkUtils::setIpForwardingEnabled,
- NetworkUtils::stopTethering
-};
-
-const CommandFunc NetworkUtils::sWifiRetryChain[] = {
- NetworkUtils::clearWifiTetherParms,
- NetworkUtils::stopSoftAP,
- NetworkUtils::stopTethering,
-
- // sWifiEnableChain:
- NetworkUtils::wifiFirmwareReload,
- NetworkUtils::startAccessPointDriver,
- NetworkUtils::setAccessPoint,
- NetworkUtils::startSoftAP,
- NetworkUtils::setConfig,
- NetworkUtils::tetherInterface,
- NetworkUtils::addInterfaceToLocalNetwork,
- NetworkUtils::addRouteToLocalNetwork,
- NetworkUtils::setIpForwardingEnabled,
- NetworkUtils::tetheringStatus,
- NetworkUtils::startTethering,
- NetworkUtils::setDnsForwarders,
- NetworkUtils::enableNat,
- NetworkUtils::wifiTetheringSuccess
-};
-
-const CommandFunc NetworkUtils::sWifiOperationModeChain[] = {
- NetworkUtils::wifiFirmwareReload,
- NetworkUtils::wifiOperationModeSuccess
-};
-
-const CommandFunc NetworkUtils::sUSBEnableChain[] = {
- NetworkUtils::setConfig,
- NetworkUtils::enableNat,
- NetworkUtils::setIpForwardingEnabled,
- NetworkUtils::tetherInterface,
- NetworkUtils::addInterfaceToLocalNetwork,
- NetworkUtils::addRouteToLocalNetwork,
- NetworkUtils::tetheringStatus,
- NetworkUtils::startTethering,
- NetworkUtils::setDnsForwarders,
- NetworkUtils::addUpstreamInterface,
- NetworkUtils::usbTetheringSuccess
-};
-
-const CommandFunc NetworkUtils::sUSBDisableChain[] = {
- NetworkUtils::untetherInterface,
- NetworkUtils::removeInterfaceFromLocalNetwork,
- NetworkUtils::preTetherInterfaceList,
- NetworkUtils::postTetherInterfaceList,
- NetworkUtils::removeUpstreamInterface,
- NetworkUtils::disableNat,
- NetworkUtils::setIpForwardingEnabled,
- NetworkUtils::stopTethering,
- NetworkUtils::usbTetheringSuccess
-};
-
-const CommandFunc NetworkUtils::sUSBFailChain[] = {
- NetworkUtils::stopSoftAP,
- NetworkUtils::setIpForwardingEnabled,
- NetworkUtils::stopTethering
-};
-
-const CommandFunc NetworkUtils::sUpdateUpStreamChain[] = {
- NetworkUtils::cleanUpStream,
- NetworkUtils::removeUpstreamInterface,
- NetworkUtils::createUpStream,
- NetworkUtils::addUpstreamInterface,
- NetworkUtils::updateUpStreamSuccess
-};
-
-const CommandFunc NetworkUtils::sStartDhcpServerChain[] = {
- NetworkUtils::setConfig,
- NetworkUtils::startTethering,
- NetworkUtils::setDhcpServerSuccess
-};
-
-const CommandFunc NetworkUtils::sStopDhcpServerChain[] = {
- NetworkUtils::stopTethering,
- NetworkUtils::setDhcpServerSuccess
-};
-
-const CommandFunc NetworkUtils::sNetworkInterfaceEnableAlarmChain[] = {
- NetworkUtils::enableAlarm,
- NetworkUtils::setQuota,
- NetworkUtils::setAlarm,
- NetworkUtils::networkInterfaceAlarmSuccess
-};
-
-const CommandFunc NetworkUtils::sNetworkInterfaceDisableAlarmChain[] = {
- NetworkUtils::removeQuota,
- NetworkUtils::disableAlarm,
- NetworkUtils::networkInterfaceAlarmSuccess
-};
-
-const CommandFunc NetworkUtils::sNetworkInterfaceSetAlarmChain[] = {
- NetworkUtils::setAlarm,
- NetworkUtils::networkInterfaceAlarmSuccess
-};
-
-const CommandFunc NetworkUtils::sGetInterfacesChain[] = {
- NetworkUtils::getInterfaceList,
- NetworkUtils::getInterfacesSuccess
-};
-
-const CommandFunc NetworkUtils::sGetInterfaceConfigChain[] = {
- NetworkUtils::getConfig,
- NetworkUtils::getInterfaceConfigSuccess
-};
-
-const CommandFunc NetworkUtils::sSetInterfaceConfigChain[] = {
- NetworkUtils::setConfig,
- NetworkUtils::setInterfaceConfigSuccess
-};
-
-const CommandFunc NetworkUtils::sTetheringInterfaceSetAlarmChain[] = {
- NetworkUtils::setGlobalAlarm,
- NetworkUtils::removeAlarm,
- NetworkUtils::networkInterfaceAlarmSuccess
-};
-
-const CommandFunc NetworkUtils::sTetheringInterfaceRemoveAlarmChain[] = {
- NetworkUtils::removeGlobalAlarm,
- NetworkUtils::setAlarm,
- NetworkUtils::networkInterfaceAlarmSuccess
-};
-
-const CommandFunc NetworkUtils::sTetheringGetStatusChain[] = {
- NetworkUtils::tetheringStatus,
- NetworkUtils::defaultAsyncSuccessHandler
-};
-
-/**
- * Helper function to get the mask from given prefix length.
- */
-static uint32_t makeMask(const uint32_t prefixLength)
-{
- uint32_t mask = 0;
- for (uint32_t i = 0; i < prefixLength; ++i) {
- mask |= (0x80000000 >> i);
- }
- return ntohl(mask);
-}
-
-/**
- * Helper function to get the network part of an ip from prefix.
- * param ip must be in network byte order.
- */
-static char* getNetworkAddr(const uint32_t ip, const uint32_t prefix)
-{
- uint32_t mask = 0, subnet = 0;
-
- mask = ~mask << (32 - prefix);
- mask = htonl(mask);
- subnet = ip & mask;
-
- struct in_addr addr;
- addr.s_addr = subnet;
-
- return inet_ntoa(addr);
-}
-
-/**
- * Helper function to split string by seperator, store split result as an nsTArray.
- */
-static void split(char* str, const char* sep, nsTArray<nsCString>& result)
-{
- char *s = strtok(str, sep);
- while (s != nullptr) {
- result.AppendElement(s);
- s = strtok(nullptr, sep);
- }
-}
-
-static void split(char* str, const char* sep, nsTArray<nsString>& result)
-{
- char *s = strtok(str, sep);
- while (s != nullptr) {
- result.AppendElement(NS_ConvertUTF8toUTF16(s));
- s = strtok(nullptr, sep);
- }
-}
-
-/**
- * Helper function that implement join function.
- */
-static void join(nsTArray<nsCString>& array,
- const char* sep,
- const uint32_t maxlen,
- char* result)
-{
-#define CHECK_LENGTH(len, add, max) len += add; \
- if (len > max - 1) \
- return; \
-
- uint32_t len = 0;
- uint32_t seplen = strlen(sep);
-
- if (array.Length() > 0) {
- CHECK_LENGTH(len, strlen(array[0].get()), maxlen)
- strcpy(result, array[0].get());
-
- for (uint32_t i = 1; i < array.Length(); i++) {
- CHECK_LENGTH(len, seplen, maxlen)
- strcat(result, sep);
-
- CHECK_LENGTH(len, strlen(array[i].get()), maxlen)
- strcat(result, array[i].get());
- }
- }
-
-#undef CHECK_LEN
-}
-
-static void convertUTF8toUTF16(nsTArray<nsCString>& narrow,
- nsTArray<nsString>& wide,
- uint32_t length)
-{
- for (uint32_t i = 0; i < length; i++) {
- wide.AppendElement(NS_ConvertUTF8toUTF16(narrow[i].get()));
- }
-}
-
-/**
- * Helper function to get network interface properties from the system property table.
- */
-static void getIFProperties(const char* ifname, IFProperties& prop)
-{
- char key[Property::KEY_MAX_LENGTH];
- snprintf(key, Property::KEY_MAX_LENGTH - 1, "net.%s.gw", ifname);
- Property::Get(key, prop.gateway, "");
- snprintf(key, Property::KEY_MAX_LENGTH - 1, "net.%s.dns1", ifname);
- Property::Get(key, prop.dns1, "");
- snprintf(key, Property::KEY_MAX_LENGTH - 1, "net.%s.dns2", ifname);
- Property::Get(key, prop.dns2, "");
-}
-
-static int getIpType(const char *aIp) {
- struct addrinfo hint, *ip_info = NULL;
-
- memset(&hint, 0, sizeof(hint));
- hint.ai_family = AF_UNSPEC;
- hint.ai_flags = AI_NUMERICHOST;
-
- if (getaddrinfo(aIp, NULL, &hint, &ip_info)) {
- return AF_UNSPEC;
- }
-
- int type = ip_info->ai_family;
- freeaddrinfo(ip_info);
-
- return type;
-}
-
-static void postMessage(NetworkResultOptions& aResult)
-{
- MOZ_ASSERT(gNetworkUtils);
- MOZ_ASSERT(gNetworkUtils->getMessageCallback());
-
- if (*(gNetworkUtils->getMessageCallback()))
- (*(gNetworkUtils->getMessageCallback()))(aResult);
-}
-
-static void postMessage(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- MOZ_ASSERT(gNetworkUtils);
- MOZ_ASSERT(gNetworkUtils->getMessageCallback());
-
- aResult.mId = aOptions.mId;
-
- if (*(gNetworkUtils->getMessageCallback()))
- (*(gNetworkUtils->getMessageCallback()))(aResult);
-}
-
-void NetworkUtils::runNextQueuedCommandChain()
-{
- if (gCommandChainQueue.IsEmpty()) {
- NU_DBG("No command chain left in the queue. Done!");
- return;
- }
- NU_DBG("Process the queued command chain.");
- CommandChain* nextChain = gCommandChainQueue[0];
- NetworkResultOptions newResult;
- next(nextChain, false, newResult);
-}
-
-void NetworkUtils::next(CommandChain* aChain, bool aError, NetworkResultOptions& aResult)
-{
- if (aError) {
- ErrorCallback onError = aChain->getErrorCallback();
- if(onError) {
- aResult.mError = true;
- (*onError)(aChain->getParams(), aResult);
- }
- delete aChain;
- gCommandChainQueue.RemoveElementAt(0);
- runNextQueuedCommandChain();
- return;
- }
- CommandFunc f = aChain->getNextCommand();
- if (!f) {
- delete aChain;
- gCommandChainQueue.RemoveElementAt(0);
- runNextQueuedCommandChain();
- return;
- }
-
- (*f)(aChain, next, aResult);
-}
-
-CommandResult::CommandResult(int32_t aResultCode)
- : mIsPending(false)
-{
- // This is usually not a netd command. We treat the return code
- // typical linux convention, which uses 0 to indicate success.
- mResult.mError = (aResultCode == SUCCESS ? false : true);
- mResult.mResultCode = aResultCode;
- if (aResultCode != SUCCESS) {
- // The returned value is sometimes negative, make sure we pass a positive
- // error number to strerror.
- enum { STRERROR_R_BUF_SIZE = 1024, };
- char strerrorBuf[STRERROR_R_BUF_SIZE];
- strerror_r(abs(aResultCode), strerrorBuf, STRERROR_R_BUF_SIZE);
- mResult.mReason = NS_ConvertUTF8toUTF16(strerrorBuf);
- }
-}
-
-CommandResult::CommandResult(const mozilla::dom::NetworkResultOptions& aResult)
- : mResult(aResult)
- , mIsPending(false)
-{
-}
-
-CommandResult::CommandResult(const Pending&)
- : mIsPending(true)
-{
-}
-
-bool CommandResult::isPending() const
-{
- return mIsPending;
-}
-
-/**
- * Send command to netd.
- */
-void NetworkUtils::nextNetdCommand()
-{
- if (gCommandQueue.IsEmpty() || gPending) {
- return;
- }
-
- gCurrentCommand.chain = GET_CURRENT_CHAIN;
- gCurrentCommand.callback = GET_CURRENT_CALLBACK;
- snprintf(gCurrentCommand.command, MAX_COMMAND_SIZE - 1, "%s", GET_CURRENT_COMMAND);
-
- NU_DBG("Sending \'%s\' command to netd.", gCurrentCommand.command);
- SendNetdCommand(GET_CURRENT_NETD_COMMAND);
-
- gCommandQueue.RemoveElementAt(0);
- gPending = true;
-}
-
-/**
- * Composite NetdCommand sent to netd
- *
- * @param aCommand Command sent to netd to execute.
- * @param aChain Store command chain data, ex. command parameter.
- * @param aCallback Callback function to be executed when the result of
- * this command is returned from netd.
- */
-void NetworkUtils::doCommand(const char* aCommand, CommandChain* aChain, CommandCallback aCallback)
-{
- NU_DBG("Preparing to send \'%s\' command...", aCommand);
-
- NetdCommand* netdCommand = new NetdCommand();
-
- // Android JB version adds sequence number to netd command.
- if (SDK_VERSION >= 16) {
- snprintf((char*)netdCommand->mData, MAX_COMMAND_SIZE - 1, "0 %s", aCommand);
- } else {
- snprintf((char*)netdCommand->mData, MAX_COMMAND_SIZE - 1, "%s", aCommand);
- }
- netdCommand->mSize = strlen((char*)netdCommand->mData) + 1;
-
- gCommandQueue.AppendElement(QueueData(netdCommand, aChain, aCallback));
-
- nextNetdCommand();
-}
-
-/*
- * Netd command function
- */
-#define GET_CHAR(prop) NS_ConvertUTF16toUTF8(aChain->getParams().prop).get()
-#define GET_FIELD(prop) aChain->getParams().prop
-
-void NetworkUtils::wifiFirmwareReload(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "softap fwreload %s %s", GET_CHAR(mIfname), GET_CHAR(mMode));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::startAccessPointDriver(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- // Skip the command for sdk version >= 16.
- if (SDK_VERSION >= 16) {
- aResult.mResultCode = 0;
- aResult.mResultReason = NS_ConvertUTF8toUTF16("");
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "softap start %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::stopAccessPointDriver(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- // Skip the command for sdk version >= 16.
- if (SDK_VERSION >= 16) {
- aResult.mResultCode = 0;
- aResult.mResultReason = NS_ConvertUTF8toUTF16("");
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "softap stop %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-/**
- * Command format for sdk version < 16
- * Arguments:
- * argv[2] - wlan interface
- * argv[3] - SSID
- * argv[4] - Security
- * argv[5] - Key
- * argv[6] - Channel
- * argv[7] - Preamble
- * argv[8] - Max SCB
- *
- * Command format for sdk version >= 16
- * Arguments:
- * argv[2] - wlan interface
- * argv[3] - SSID
- * argv[4] - Security
- * argv[5] - Key
- *
- * Command format for sdk version >= 18
- * Arguments:
- * argv[2] - wlan interface
- * argv[3] - SSID
- * argv[4] - Broadcast/Hidden
- * argv[5] - Channel
- * argv[6] - Security
- * argv[7] - Key
- */
-void NetworkUtils::setAccessPoint(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- nsCString ssid(GET_CHAR(mSsid));
- nsCString key(GET_CHAR(mKey));
-
- escapeQuote(ssid);
- escapeQuote(key);
-
- if (SDK_VERSION >= 19) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "softap set %s \"%s\" broadcast 6 %s \"%s\"",
- GET_CHAR(mIfname),
- ssid.get(),
- GET_CHAR(mSecurity),
- key.get());
- } else if (SDK_VERSION >= 16) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "softap set %s \"%s\" %s \"%s\"",
- GET_CHAR(mIfname),
- ssid.get(),
- GET_CHAR(mSecurity),
- key.get());
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "softap set %s %s \"%s\" %s \"%s\" 6 0 8",
- GET_CHAR(mIfname),
- GET_CHAR(mWifictrlinterfacename),
- ssid.get(),
- GET_CHAR(mSecurity),
- key.get());
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::cleanUpStream(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "nat disable %s %s 0", GET_CHAR(mPreInternalIfname), GET_CHAR(mPreExternalIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::createUpStream(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "nat enable %s %s 0", GET_CHAR(mCurInternalIfname), GET_CHAR(mCurExternalIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::startSoftAP(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- const char* command= "softap startap";
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::stopSoftAP(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- const char* command= "softap stopap";
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::clearWifiTetherParms(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- delete gWifiTetheringParms;
- gWifiTetheringParms = 0;
- next(aChain, false, aResult);
-}
-
-void NetworkUtils::enableAlarm(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- const char* command= "bandwidth enable";
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::disableAlarm(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- const char* command= "bandwidth disable";
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::setQuota(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth setiquota %s % " PRId64, GET_CHAR(mIfname), INT64_MAX);
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::removeQuota(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth removeiquota %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::setAlarm(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth setinterfacealert %s %lld",
- GET_CHAR(mIfname), GET_FIELD(mThreshold));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::removeAlarm(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth removeinterfacealert %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::setGlobalAlarm(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
-
- snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth setglobalalert %lld", GET_FIELD(mThreshold));
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::removeGlobalAlarm(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
-
- snprintf(command, MAX_COMMAND_SIZE - 1, "bandwidth removeglobalalert");
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::tetherInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface add %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::addInterfaceToLocalNetwork(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- // Skip the command for sdk version < 20.
- if (SDK_VERSION < 20) {
- aResult.mResultCode = 0;
- aResult.mResultReason = NS_ConvertUTF8toUTF16("");
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "network interface add local %s",
- GET_CHAR(mInternalIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::addRouteToLocalNetwork(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- // Skip the command for sdk version < 20.
- if (SDK_VERSION < 20) {
- aResult.mResultCode = 0;
- aResult.mResultReason = NS_ConvertUTF8toUTF16("");
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- uint32_t prefix = atoi(GET_CHAR(mPrefix));
- uint32_t ip = inet_addr(GET_CHAR(mIp));
- char* networkAddr = getNetworkAddr(ip, prefix);
-
- snprintf(command, MAX_COMMAND_SIZE - 1, "network route add local %s %s/%s",
- GET_CHAR(mInternalIfname), networkAddr, GET_CHAR(mPrefix));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::preTetherInterfaceList(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- if (SDK_VERSION >= 16) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface list");
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface list 0");
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::postTetherInterfaceList(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- // Send the dummy command to continue the function chain.
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "%s", DUMMY_COMMAND);
-
- char buf[BUF_SIZE];
- NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
-
- size_t length = reason.Length() + 1 < BUF_SIZE ? reason.Length() + 1 : BUF_SIZE;
- memcpy(buf, reason.get(), length);
- split(buf, INTERFACE_DELIMIT, GET_FIELD(mInterfaceList));
-
- doCommand(command, aChain, aCallback);
-}
-
-bool isCommandChainIPv6(CommandChain* aChain, const char *externalInterface) {
- // Check by gateway address
- if (getIpType(GET_CHAR(mGateway)) == AF_INET6) {
- return true;
- }
-
- uint32_t length = GET_FIELD(mGateways).Length();
- for (uint32_t i = 0; i < length; i++) {
- NS_ConvertUTF16toUTF8 autoGateway(GET_FIELD(mGateways)[i]);
- if(getIpType(autoGateway.get()) == AF_INET6) {
- return true;
- }
- }
-
- // Check by external inteface address
- FILE *file = fopen("/proc/net/if_inet6", "r");
- if (!file) {
- return false;
- }
-
- bool isIPv6 = false;
- char interface[32];
- while(fscanf(file, "%*s %*s %*s %*s %*s %32s", interface)) {
- if (strcmp(interface, externalInterface) == 0) {
- isIPv6 = true;
- break;
- }
- }
-
- fclose(file);
- return isIPv6;
-}
-
-void NetworkUtils::addUpstreamInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- nsCString interface(GET_CHAR(mExternalIfname));
- if (!interface.get()[0]) {
- interface = GET_CHAR(mCurExternalIfname);
- }
-
- if (SUPPORT_IPV6_TETHERING == 0 || !isCommandChainIPv6(aChain, interface.get())) {
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface add_upstream %s",
- interface.get());
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::removeUpstreamInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- nsCString interface(GET_CHAR(mExternalIfname));
- if (!interface.get()[0]) {
- interface = GET_CHAR(mPreExternalIfname);
- }
-
- if (SUPPORT_IPV6_TETHERING == 0 || !isCommandChainIPv6(aChain, interface.get())) {
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface remove_upstream %s",
- interface.get());
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::setIpForwardingEnabled(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
-
- if (GET_FIELD(mEnable)) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "ipfwd enable");
- } else {
- // Don't disable ip forwarding because others interface still need it.
- // Send the dummy command to continue the function chain.
- if (GET_FIELD(mInterfaceList).Length() > 1) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "%s", DUMMY_COMMAND);
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "ipfwd disable");
- }
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::tetheringStatus(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- const char* command= "tether status";
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::stopTethering(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
-
- // Don't stop tethering because others interface still need it.
- // Send the dummy to continue the function chain.
- if (GET_FIELD(mInterfaceList).Length() > 1) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "%s", DUMMY_COMMAND);
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether stop");
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::startTethering(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
-
- // We don't need to start tethering again.
- // Send the dummy command to continue the function chain.
- if (aResult.mResultReason.Find("started") != kNotFound) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "%s", DUMMY_COMMAND);
- } else {
- // If usbStartIp/usbEndIp is not valid, don't append them since
- // the trailing white spaces will be parsed to extra empty args
- // See: http://androidxref.com/4.3_r2.1/xref/system/core/libsysutils/src/FrameworkListener.cpp#78
- if (!GET_FIELD(mUsbStartIp).IsEmpty() && !GET_FIELD(mUsbEndIp).IsEmpty()) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether start %s %s %s %s",
- GET_CHAR(mWifiStartIp), GET_CHAR(mWifiEndIp),
- GET_CHAR(mUsbStartIp), GET_CHAR(mUsbEndIp));
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether start %s %s",
- GET_CHAR(mWifiStartIp), GET_CHAR(mWifiEndIp));
- }
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::untetherInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether interface remove %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::removeInterfaceFromLocalNetwork(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- // Skip the command for sdk version < 20.
- if (SDK_VERSION < 20) {
- aResult.mResultCode = 0;
- aResult.mResultReason = NS_ConvertUTF8toUTF16("");
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "network interface remove local %s",
- GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::setDnsForwarders(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
-
- if (SDK_VERSION >= 20) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether dns set %d %s %s",
- GET_FIELD(mNetId), GET_CHAR(mDns1), GET_CHAR(mDns2));
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "tether dns set %s %s",
- GET_CHAR(mDns1), GET_CHAR(mDns2));
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::enableNat(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
-
- if (!GET_FIELD(mIp).IsEmpty() && !GET_FIELD(mPrefix).IsEmpty()) {
- uint32_t prefix = atoi(GET_CHAR(mPrefix));
- uint32_t ip = inet_addr(GET_CHAR(mIp));
- char* networkAddr = getNetworkAddr(ip, prefix);
-
- // address/prefix will only take effect when secondary routing table exists.
- snprintf(command, MAX_COMMAND_SIZE - 1, "nat enable %s %s 1 %s/%s",
- GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname), networkAddr,
- GET_CHAR(mPrefix));
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "nat enable %s %s 0",
- GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::disableNat(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
-
- if (!GET_FIELD(mIp).IsEmpty() && !GET_FIELD(mPrefix).IsEmpty()) {
- uint32_t prefix = atoi(GET_CHAR(mPrefix));
- uint32_t ip = inet_addr(GET_CHAR(mIp));
- char* networkAddr = getNetworkAddr(ip, prefix);
-
- snprintf(command, MAX_COMMAND_SIZE - 1, "nat disable %s %s 1 %s/%s",
- GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname), networkAddr,
- GET_CHAR(mPrefix));
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "nat disable %s %s 0",
- GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::setDefaultInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "resolver setdefaultif %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::removeDefaultRoute(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- if (GET_FIELD(mLoopIndex) >= GET_FIELD(mGateways).Length()) {
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- nsTArray<nsString>& gateways = GET_FIELD(mGateways);
- NS_ConvertUTF16toUTF8 autoGateway(gateways[GET_FIELD(mLoopIndex)]);
-
- int type = getIpType(autoGateway.get());
- snprintf(command, MAX_COMMAND_SIZE - 1, "network route remove %d %s %s/0 %s",
- GET_FIELD(mNetId), GET_CHAR(mIfname),
- type == AF_INET6 ? "::" : "0.0.0.0", autoGateway.get());
-
- struct MyCallback {
- static void callback(CommandCallback::CallbackType aOriginalCallback,
- CommandChain* aChain,
- bool aError,
- mozilla::dom::NetworkResultOptions& aResult)
- {
- NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
- NU_DBG("removeDefaultRoute's reason: %s", reason.get());
- if (aError && !reason.EqualsASCII("removeRoute() failed (No such process)")) {
- return aOriginalCallback(aChain, aError, aResult);
- }
-
- GET_FIELD(mLoopIndex)++;
- return removeDefaultRoute(aChain, aOriginalCallback, aResult);
- }
- };
-
- CommandCallback wrappedCallback(MyCallback::callback, aCallback);
- doCommand(command, aChain, wrappedCallback);
-}
-
-void NetworkUtils::setInterfaceDns(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- int written;
-
- if (SDK_VERSION >= 20) {
- written = SprintfLiteral(command, "resolver setnetdns %d %s",
- GET_FIELD(mNetId), GET_CHAR(mDomain));
- } else {
- written = SprintfLiteral(command, "resolver setifdns %s %s",
- GET_CHAR(mIfname), GET_CHAR(mDomain));
- }
-
- nsTArray<nsString>& dnses = GET_FIELD(mDnses);
- uint32_t length = dnses.Length();
-
- for (uint32_t i = 0; i < length; i++) {
- NS_ConvertUTF16toUTF8 autoDns(dnses[i]);
-
- int ret = snprintf(command + written, sizeof(command) - written, " %s", autoDns.get());
- if (ret <= 1) {
- command[written] = '\0';
- continue;
- }
-
- if (((size_t)ret + written) >= sizeof(command)) {
- command[written] = '\0';
- break;
- }
-
- written += ret;
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::getInterfaceList(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "interface list");
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::getConfig(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "interface getcfg %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::setConfig(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- if (SDK_VERSION >= 16) {
- snprintf(command, MAX_COMMAND_SIZE - 1, "interface setcfg %s %s %s %s",
- GET_CHAR(mIfname),
- GET_CHAR(mIp),
- GET_CHAR(mPrefix),
- GET_CHAR(mLink));
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1, "interface setcfg %s %s %s [%s]",
- GET_CHAR(mIfname),
- GET_CHAR(mIp),
- GET_CHAR(mPrefix),
- GET_CHAR(mLink));
- }
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::clearAddrForInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "interface clearaddrs %s", GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::createNetwork(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "network create %d", GET_FIELD(mNetId));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::destroyNetwork(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "network destroy %d", GET_FIELD(mNetId));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::addInterfaceToNetwork(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "network interface add %d %s",
- GET_FIELD(mNetId), GET_CHAR(mIfname));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::addRouteToInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- struct MyCallback {
- static void callback(CommandCallback::CallbackType aOriginalCallback,
- CommandChain* aChain,
- bool aError,
- mozilla::dom::NetworkResultOptions& aResult)
- {
- NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
- NU_DBG("addRouteToInterface's reason: %s", reason.get());
- if (aError && reason.EqualsASCII("addRoute() failed (File exists)")) {
- NU_DBG("Ignore \"File exists\" error when adding host route.");
- return aOriginalCallback(aChain, false, aResult);
- }
- aOriginalCallback(aChain, aError, aResult);
- }
- };
-
- CommandCallback wrappedCallback(MyCallback::callback, aCallback);
- modifyRouteOnInterface(aChain, wrappedCallback, aResult, true);
-}
-
-void NetworkUtils::removeRouteFromInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- modifyRouteOnInterface(aChain, aCallback, aResult, false);
-}
-
-void NetworkUtils::modifyRouteOnInterface(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult,
- bool aDoAdd)
-{
- char command[MAX_COMMAND_SIZE];
-
- // AOSP adds host route to its interface table but it doesn't work for
- // B2G because we cannot set fwmark per application. So, we add
- // all host routes to legacy_system table except scope link route.
-
- nsCString ipOrSubnetIp = NS_ConvertUTF16toUTF8(GET_FIELD(mIp));
- nsCString gatewayOrEmpty;
- const char* legacyOrEmpty = "legacy 0 "; // Add to legacy by default.
- if (GET_FIELD(mGateway).IsEmpty()) {
- ipOrSubnetIp = getSubnetIp(ipOrSubnetIp, GET_FIELD(mPrefixLength));
- legacyOrEmpty = ""; // Add to interface table for scope link route.
- } else {
- gatewayOrEmpty = nsCString(" ") + NS_ConvertUTF16toUTF8(GET_FIELD(mGateway));
- }
-
- const char* action = aDoAdd ? "add" : "remove";
-
- snprintf(command, MAX_COMMAND_SIZE - 1, "network route %s%s %d %s %s/%d%s",
- legacyOrEmpty, action,
- GET_FIELD(mNetId), GET_CHAR(mIfname), ipOrSubnetIp.get(),
- GET_FIELD(mPrefixLength), gatewayOrEmpty.get());
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::addDefaultRouteToNetwork(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- if (GET_FIELD(mLoopIndex) >= GET_FIELD(mGateways).Length()) {
- aCallback(aChain, false, aResult);
- return;
- }
-
- char command[MAX_COMMAND_SIZE];
- nsTArray<nsString>& gateways = GET_FIELD(mGateways);
- NS_ConvertUTF16toUTF8 autoGateway(gateways[GET_FIELD(mLoopIndex)]);
-
- int type = getIpType(autoGateway.get());
- snprintf(command, MAX_COMMAND_SIZE - 1, "network route add %d %s %s/0 %s",
- GET_FIELD(mNetId), GET_CHAR(mIfname),
- type == AF_INET6 ? "::" : "0.0.0.0", autoGateway.get());
-
- struct MyCallback {
- static void callback(CommandCallback::CallbackType aOriginalCallback,
- CommandChain* aChain,
- bool aError,
- mozilla::dom::NetworkResultOptions& aResult)
- {
- NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
- NU_DBG("addDefaultRouteToNetwork's reason: %s", reason.get());
- if (aError && !reason.EqualsASCII("addRoute() failed (File exists)")) {
- return aOriginalCallback(aChain, aError, aResult);
- }
-
- GET_FIELD(mLoopIndex)++;
- return addDefaultRouteToNetwork(aChain, aOriginalCallback, aResult);
- }
- };
-
- CommandCallback wrappedCallback(MyCallback::callback, aCallback);
- doCommand(command, aChain, wrappedCallback);
-}
-
-void NetworkUtils::setDefaultNetwork(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "network default set %d", GET_FIELD(mNetId));
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::addRouteToSecondaryTable(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult) {
-
- char command[MAX_COMMAND_SIZE];
-
- if (SDK_VERSION >= 20) {
- snprintf(command, MAX_COMMAND_SIZE - 1,
- "network route add %d %s %s/%s %s",
- GET_FIELD(mNetId),
- GET_CHAR(mIfname),
- GET_CHAR(mIp),
- GET_CHAR(mPrefix),
- GET_CHAR(mGateway));
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1,
- "interface route add %s secondary %s %s %s",
- GET_CHAR(mIfname),
- GET_CHAR(mIp),
- GET_CHAR(mPrefix),
- GET_CHAR(mGateway));
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::removeRouteFromSecondaryTable(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult) {
- char command[MAX_COMMAND_SIZE];
-
- if (SDK_VERSION >= 20) {
- snprintf(command, MAX_COMMAND_SIZE - 1,
- "network route remove %d %s %s/%s %s",
- GET_FIELD(mNetId),
- GET_CHAR(mIfname),
- GET_CHAR(mIp),
- GET_CHAR(mPrefix),
- GET_CHAR(mGateway));
- } else {
- snprintf(command, MAX_COMMAND_SIZE - 1,
- "interface route remove %s secondary %s %s %s",
- GET_CHAR(mIfname),
- GET_CHAR(mIp),
- GET_CHAR(mPrefix),
- GET_CHAR(mGateway));
- }
-
- doCommand(command, aChain, aCallback);
-}
-
-void NetworkUtils::setIpv6Enabled(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult,
- bool aEnabled)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "interface ipv6 %s %s",
- GET_CHAR(mIfname), aEnabled ? "enable" : "disable");
-
- struct MyCallback {
- static void callback(CommandCallback::CallbackType aOriginalCallback,
- CommandChain* aChain,
- bool aError,
- mozilla::dom::NetworkResultOptions& aResult)
- {
- aOriginalCallback(aChain, false, aResult);
- }
- };
-
- CommandCallback wrappedCallback(MyCallback::callback, aCallback);
- doCommand(command, aChain, wrappedCallback);
-}
-
-void NetworkUtils::enableIpv6(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- setIpv6Enabled(aChain, aCallback, aResult, true);
-}
-
-void NetworkUtils::disableIpv6(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- setIpv6Enabled(aChain, aCallback, aResult, false);
-}
-
-void NetworkUtils::setMtu(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char command[MAX_COMMAND_SIZE];
- snprintf(command, MAX_COMMAND_SIZE - 1, "interface setmtu %s %ld",
- GET_CHAR(mIfname), GET_FIELD(mMtu));
-
- doCommand(command, aChain, aCallback);
-}
-
-#undef GET_CHAR
-#undef GET_FIELD
-
-/*
- * Netd command success/fail function
- */
-#define ASSIGN_FIELD(prop) aResult.prop = aChain->getParams().prop;
-#define ASSIGN_FIELD_VALUE(prop, value) aResult.prop = value;
-
-template<size_t N>
-void NetworkUtils::runChain(const NetworkParams& aParams,
- const CommandFunc (&aCmds)[N],
- ErrorCallback aError)
-{
- CommandChain* chain = new CommandChain(aParams, aCmds, N, aError);
- gCommandChainQueue.AppendElement(chain);
-
- if (gCommandChainQueue.Length() > 1) {
- NU_DBG("%d command chains are queued. Wait!", gCommandChainQueue.Length());
- return;
- }
-
- NetworkResultOptions result;
- NetworkUtils::next(gCommandChainQueue[0], false, result);
-}
-
-// Called to clean up the command chain and process the queued command chain if any.
-void NetworkUtils::finalizeSuccess(CommandChain* aChain,
- NetworkResultOptions& aResult)
-{
- next(aChain, false, aResult);
-}
-
-void NetworkUtils::wifiTetheringFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- // Notify the main thread.
- postMessage(aOptions, aResult);
-
- // If one of the stages fails, we try roll back to ensure
- // we don't leave the network systems in limbo.
- ASSIGN_FIELD_VALUE(mEnable, false)
- runChain(aOptions, sWifiFailChain, nullptr);
-}
-
-void NetworkUtils::wifiTetheringSuccess(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- ASSIGN_FIELD(mEnable)
-
- if (aChain->getParams().mEnable) {
- MOZ_ASSERT(!gWifiTetheringParms);
- gWifiTetheringParms = new NetworkParams(aChain->getParams());
- }
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::usbTetheringFail(NetworkParams& aOptions,
- NetworkResultOptions& aResult)
-{
- // Notify the main thread.
- postMessage(aOptions, aResult);
- // Try to roll back to ensure
- // we don't leave the network systems in limbo.
- // This parameter is used to disable ipforwarding.
- {
- aOptions.mEnable = false;
- runChain(aOptions, sUSBFailChain, nullptr);
- }
-
- // Disable usb rndis function.
- {
- NetworkParams options;
- options.mEnable = false;
- options.mReport = false;
- gNetworkUtils->enableUsbRndis(options);
- }
-}
-
-void NetworkUtils::usbTetheringSuccess(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- ASSIGN_FIELD(mEnable)
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::networkInterfaceAlarmFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::networkInterfaceAlarmSuccess(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- // TODO : error is not used , and it is conflict with boolean type error.
- // params.error = parseFloat(params.resultReason);
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::updateUpStreamFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::updateUpStreamSuccess(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- ASSIGN_FIELD(mCurExternalIfname)
- ASSIGN_FIELD(mCurInternalIfname)
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::setDhcpServerFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- aResult.mSuccess = false;
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::setDhcpServerSuccess(CommandChain* aChain, CommandCallback aCallback, NetworkResultOptions& aResult)
-{
- aResult.mSuccess = true;
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::wifiOperationModeFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::wifiOperationModeSuccess(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::setDnsFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::defaultAsyncSuccessHandler(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- NU_DBG("defaultAsyncSuccessHandler");
- aResult.mRet = true;
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::defaultAsyncFailureHandler(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- aResult.mRet = false;
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::getInterfacesFail(NetworkParams& aOptions, NetworkResultOptions& aResult)
-{
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::getInterfacesSuccess(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char buf[BUF_SIZE];
- NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
- memcpy(buf, reason.get(), strlen(reason.get()));
-
- nsTArray<nsCString> result;
- split(buf, INTERFACE_DELIMIT, result);
-
- nsTArray<nsString> interfaceList;
- uint32_t length = result.Length();
- convertUTF8toUTF16(result, interfaceList, length);
-
- aResult.mInterfaceList.Construct();
- for (uint32_t i = 0; i < length; i++) {
- aResult.mInterfaceList.Value().AppendElement(interfaceList[i], fallible_t());
- }
-
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::getInterfaceConfigFail(NetworkParams& aOptions,
- NetworkResultOptions& aResult)
-{
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::getInterfaceConfigSuccess(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- char buf[BUF_SIZE];
- NS_ConvertUTF16toUTF8 reason(aResult.mResultReason);
- memcpy(buf, reason.get(), strlen(reason.get()));
-
- nsTArray<nsCString> result;
- split(buf, NETD_MESSAGE_DELIMIT, result);
-
- ASSIGN_FIELD_VALUE(mMacAddr, NS_ConvertUTF8toUTF16(result[0]))
- ASSIGN_FIELD_VALUE(mIpAddr, NS_ConvertUTF8toUTF16(result[1]))
- ASSIGN_FIELD_VALUE(mPrefixLength, atol(result[2].get()))
-
- if (result[3].Find("up")) {
- ASSIGN_FIELD_VALUE(mFlag, NS_ConvertUTF8toUTF16("up"))
- } else {
- ASSIGN_FIELD_VALUE(mFlag, NS_ConvertUTF8toUTF16("down"))
- }
-
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-void NetworkUtils::setInterfaceConfigFail(NetworkParams& aOptions,
- NetworkResultOptions& aResult)
-{
- postMessage(aOptions, aResult);
-}
-
-void NetworkUtils::setInterfaceConfigSuccess(CommandChain* aChain,
- CommandCallback aCallback,
- NetworkResultOptions& aResult)
-{
- postMessage(aChain->getParams(), aResult);
- finalizeSuccess(aChain, aResult);
-}
-
-#undef ASSIGN_FIELD
-#undef ASSIGN_FIELD_VALUE
-
-NetworkUtils::NetworkUtils(MessageCallback aCallback)
- : mMessageCallback(aCallback)
-{
- mNetUtils = new NetUtils();
-
- char value[Property::VALUE_MAX_LENGTH];
- Property::Get("ro.build.version.sdk", value, nullptr);
- SDK_VERSION = atoi(value);
-
- Property::Get(IPV6_TETHERING, value, "0");
- SUPPORT_IPV6_TETHERING = atoi(value);
-
- gNetworkUtils = this;
-}
-
-NetworkUtils::~NetworkUtils()
-{
-}
-
-#define GET_CHAR(prop) NS_ConvertUTF16toUTF8(aOptions.prop).get()
-#define GET_FIELD(prop) aOptions.prop
-
-// Hoist this type definition to global to avoid template
-// instantiation error on gcc 4.4 used by ICS emulator.
-typedef CommandResult (NetworkUtils::*CommandHandler)(NetworkParams&);
-struct CommandHandlerEntry
-{
- const char* mCommandName;
- CommandHandler mCommandHandler;
-};
-
-void NetworkUtils::ExecuteCommand(NetworkParams aOptions)
-{
- const static CommandHandlerEntry
- COMMAND_HANDLER_TABLE[] = {
-
- // For command 'testCommand', BUILD_ENTRY(testCommand) will generate
- // {"testCommand", NetworkUtils::testCommand}
- #define BUILD_ENTRY(c) {#c, &NetworkUtils::c}
-
- BUILD_ENTRY(removeNetworkRoute),
- BUILD_ENTRY(setDNS),
- BUILD_ENTRY(setDefaultRoute),
- BUILD_ENTRY(removeDefaultRoute),
- BUILD_ENTRY(addHostRoute),
- BUILD_ENTRY(removeHostRoute),
- BUILD_ENTRY(addSecondaryRoute),
- BUILD_ENTRY(removeSecondaryRoute),
- BUILD_ENTRY(setNetworkInterfaceAlarm),
- BUILD_ENTRY(enableNetworkInterfaceAlarm),
- BUILD_ENTRY(disableNetworkInterfaceAlarm),
- BUILD_ENTRY(setTetheringAlarm),
- BUILD_ENTRY(removeTetheringAlarm),
- BUILD_ENTRY(getTetheringStatus),
- BUILD_ENTRY(setWifiOperationMode),
- BUILD_ENTRY(setDhcpServer),
- BUILD_ENTRY(setWifiTethering),
- BUILD_ENTRY(setUSBTethering),
- BUILD_ENTRY(enableUsbRndis),
- BUILD_ENTRY(updateUpStream),
- BUILD_ENTRY(configureInterface),
- BUILD_ENTRY(dhcpRequest),
- BUILD_ENTRY(stopDhcp),
- BUILD_ENTRY(enableInterface),
- BUILD_ENTRY(disableInterface),
- BUILD_ENTRY(resetConnections),
- BUILD_ENTRY(createNetwork),
- BUILD_ENTRY(destroyNetwork),
- BUILD_ENTRY(getNetId),
- BUILD_ENTRY(getInterfaces),
- BUILD_ENTRY(getInterfaceConfig),
- BUILD_ENTRY(setInterfaceConfig),
- BUILD_ENTRY(setMtu),
-
- #undef BUILD_ENTRY
- };
-
- // Loop until we find the command name which matches aOptions.mCmd.
- CommandHandler handler = nullptr;
- for (size_t i = 0; i < mozilla::ArrayLength(COMMAND_HANDLER_TABLE); i++) {
- if (aOptions.mCmd.EqualsASCII(COMMAND_HANDLER_TABLE[i].mCommandName)) {
- handler = COMMAND_HANDLER_TABLE[i].mCommandHandler;
- break;
- }
- }
-
- if (!handler) {
- // Command not found in COMMAND_HANDLER_TABLE.
- WARN("unknown message: %s", NS_ConvertUTF16toUTF8(aOptions.mCmd).get());
- return;
- }
-
- // The handler would return one of the following 3 values
- // to be wrapped to CommandResult:
- //
- // 1) |int32_t| for mostly synchronous native function calls.
- // 2) |NetworkResultOptions| to populate additional results. (e.g. dhcpRequest)
- // 3) |CommandResult::Pending| to indicate the result is not
- // obtained yet.
- //
- // If the handler returns "Pending", the handler should take the
- // responsibility for posting result to main thread.
- CommandResult commandResult = (this->*handler)(aOptions);
- if (!commandResult.isPending()) {
- postMessage(aOptions, commandResult.mResult);
- }
-}
-
-/**
- * Handle received data from netd.
- */
-void NetworkUtils::onNetdMessage(NetdCommand* aCommand)
-{
- char* data = (char*)aCommand->mData;
-
- // get code & reason.
- char* result = strtok(data, NETD_MESSAGE_DELIMIT);
-
- if (!result) {
- nextNetdCommand();
- return;
- }
- uint32_t code = atoi(result);
-
- if (!isBroadcastMessage(code) && SDK_VERSION >= 16) {
- strtok(nullptr, NETD_MESSAGE_DELIMIT);
- }
-
- char* reason = strtok(nullptr, "\0");
-
- if (isBroadcastMessage(code)) {
- NU_DBG("Receiving broadcast message from netd.");
- NU_DBG(" ==> Code: %d Reason: %s", code, reason);
- sendBroadcastMessage(code, reason);
-
- if (code == NETD_COMMAND_INTERFACE_CHANGE) {
- if (gWifiTetheringParms) {
- char linkdownReason[MAX_COMMAND_SIZE];
- snprintf(linkdownReason, MAX_COMMAND_SIZE - 1,
- "Iface linkstate %s down",
- NS_ConvertUTF16toUTF8(gWifiTetheringParms->mIfname).get());
-
- if (!strcmp(reason, linkdownReason)) {
- NU_DBG("Wifi link down, restarting tethering.");
- runChain(*gWifiTetheringParms, sWifiRetryChain, wifiTetheringFail);
- }
- }
- }
-
- nextNetdCommand();
- return;
- }
-
- // Set pending to false before we handle next command.
- NU_DBG("Receiving \"%s\" command response from netd.", gCurrentCommand.command);
- NU_DBG(" ==> Code: %d Reason: %s", code, reason);
-
- gReason.AppendElement(nsCString(reason));
-
- // 1xx response code regards as command is proceeding, we need to wait for
- // final response code such as 2xx, 4xx and 5xx before sending next command.
- if (isProceeding(code)) {
- return;
- }
-
- if (isComplete(code)) {
- gPending = false;
- }
-
- {
- char buf[BUF_SIZE];
- join(gReason, INTERFACE_DELIMIT, BUF_SIZE, buf);
-
- NetworkResultOptions result;
- result.mResultCode = code;
- result.mResultReason = NS_ConvertUTF8toUTF16(buf);
- (gCurrentCommand.callback)(gCurrentCommand.chain, isError(code), result);
- gReason.Clear();
- }
-
- // Handling pending commands if any.
- if (isComplete(code)) {
- nextNetdCommand();
- }
-}
-
-/**
- * Start/Stop DHCP server.
- */
-CommandResult NetworkUtils::setDhcpServer(NetworkParams& aOptions)
-{
- if (aOptions.mEnabled) {
- aOptions.mWifiStartIp = aOptions.mStartIp;
- aOptions.mWifiEndIp = aOptions.mEndIp;
- aOptions.mIp = aOptions.mServerIp;
- aOptions.mPrefix = aOptions.mMaskLength;
- aOptions.mLink = NS_ConvertUTF8toUTF16("up");
-
- runChain(aOptions, sStartDhcpServerChain, setDhcpServerFail);
- } else {
- runChain(aOptions, sStopDhcpServerChain, setDhcpServerFail);
- }
- return CommandResult::Pending();
-}
-
-/**
- * Set DNS servers for given network interface.
- */
-CommandResult NetworkUtils::setDNS(NetworkParams& aOptions)
-{
- uint32_t length = aOptions.mDnses.Length();
-
- if (length > 0) {
- for (uint32_t i = 0; i < length; i++) {
- NS_ConvertUTF16toUTF8 autoDns(aOptions.mDnses[i]);
-
- char dns_prop_key[Property::VALUE_MAX_LENGTH];
- SprintfLiteral(dns_prop_key, "net.dns%d", i+1);
- Property::Set(dns_prop_key, autoDns.get());
- }
- } else {
- // Set dnses from system properties.
- IFProperties interfaceProperties;
- getIFProperties(GET_CHAR(mIfname), interfaceProperties);
-
- Property::Set("net.dns1", interfaceProperties.dns1);
- Property::Set("net.dns2", interfaceProperties.dns2);
- }
-
- // Bump the DNS change property.
- char dnschange[Property::VALUE_MAX_LENGTH];
- Property::Get("net.dnschange", dnschange, "0");
-
- char num[Property::VALUE_MAX_LENGTH];
- snprintf(num, Property::VALUE_MAX_LENGTH - 1, "%d", atoi(dnschange) + 1);
- Property::Set("net.dnschange", num);
-
- // DNS needs to be set through netd since JellyBean (4.3).
- if (SDK_VERSION >= 20) {
- // Lollipop.
- static CommandFunc COMMAND_CHAIN[] = {
- setInterfaceDns,
- addDefaultRouteToNetwork,
- defaultAsyncSuccessHandler
- };
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(aOptions.mIfname, &netIdInfo)) {
- return -1;
- }
- aOptions.mNetId = netIdInfo.mNetId;
- runChain(aOptions, COMMAND_CHAIN, setDnsFail);
- return CommandResult::Pending();
- }
- if (SDK_VERSION >= 18) {
- // JB, KK.
- static CommandFunc COMMAND_CHAIN[] = {
- #if ANDROID_VERSION == 18
- // Since we don't use per-interface DNS lookup feature on JB,
- // we need to set the default DNS interface whenever setting the
- // DNS name server.
- setDefaultInterface,
- #endif
- setInterfaceDns,
- defaultAsyncSuccessHandler
- };
- runChain(aOptions, COMMAND_CHAIN, setDnsFail);
- return CommandResult::Pending();
- }
-
- return SUCCESS;
-}
-
-CommandResult NetworkUtils::configureInterface(NetworkParams& aOptions)
-{
- NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
- return mNetUtils->do_ifc_configure(
- autoIfname.get(),
- aOptions.mIpaddr,
- aOptions.mMask,
- aOptions.mGateway_long,
- aOptions.mDns1_long,
- aOptions.mDns2_long
- );
-}
-
-CommandResult NetworkUtils::stopDhcp(NetworkParams& aOptions)
-{
- return mNetUtils->do_dhcp_stop(GET_CHAR(mIfname));
-}
-
-CommandResult NetworkUtils::dhcpRequest(NetworkParams& aOptions) {
- mozilla::dom::NetworkResultOptions result;
-
- NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
- char ipaddr[Property::VALUE_MAX_LENGTH];
- char gateway[Property::VALUE_MAX_LENGTH];
- uint32_t prefixLength;
- char dns1[Property::VALUE_MAX_LENGTH];
- char dns2[Property::VALUE_MAX_LENGTH];
- char server[Property::VALUE_MAX_LENGTH];
- uint32_t lease;
- char vendorinfo[Property::VALUE_MAX_LENGTH];
- int32_t ret = mNetUtils->do_dhcp_do_request(autoIfname.get(),
- ipaddr,
- gateway,
- &prefixLength,
- dns1,
- dns2,
- server,
- &lease,
- vendorinfo);
-
- RETURN_IF_FAILED(ret);
-
- result.mIpaddr_str = NS_ConvertUTF8toUTF16(ipaddr);
- result.mGateway_str = NS_ConvertUTF8toUTF16(gateway);
- result.mDns1_str = NS_ConvertUTF8toUTF16(dns1);
- result.mDns2_str = NS_ConvertUTF8toUTF16(dns2);
- result.mServer_str = NS_ConvertUTF8toUTF16(server);
- result.mVendor_str = NS_ConvertUTF8toUTF16(vendorinfo);
- result.mLease = lease;
- result.mPrefixLength = prefixLength;
- result.mMask = makeMask(prefixLength);
-
- uint32_t inet4; // only support IPv4 for now.
-
-#define INET_PTON(var, field) \
- PR_BEGIN_MACRO \
- inet_pton(AF_INET, var, &inet4); \
- result.field = inet4; \
- PR_END_MACRO
-
- INET_PTON(ipaddr, mIpaddr);
- INET_PTON(gateway, mGateway);
-
- if (dns1[0] != '\0') {
- INET_PTON(dns1, mDns1);
- }
-
- if (dns2[0] != '\0') {
- INET_PTON(dns2, mDns2);
- }
-
- INET_PTON(server, mServer);
-
- char inet_str[64];
- if (inet_ntop(AF_INET, &result.mMask, inet_str, sizeof(inet_str))) {
- result.mMask_str = NS_ConvertUTF8toUTF16(inet_str);
- }
-
- return result;
-}
-
-CommandResult NetworkUtils::enableInterface(NetworkParams& aOptions) {
- return mNetUtils->do_ifc_enable(
- NS_ConvertUTF16toUTF8(aOptions.mIfname).get());
-}
-
-CommandResult NetworkUtils::disableInterface(NetworkParams& aOptions) {
- return mNetUtils->do_ifc_disable(
- NS_ConvertUTF16toUTF8(aOptions.mIfname).get());
-}
-
-CommandResult NetworkUtils::resetConnections(NetworkParams& aOptions) {
- NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
- return mNetUtils->do_ifc_reset_connections(
- NS_ConvertUTF16toUTF8(aOptions.mIfname).get(),
- RESET_ALL_ADDRESSES);
-}
-
-/**
- * Set default route and DNS servers for given network interface.
- */
-CommandResult NetworkUtils::setDefaultRoute(NetworkParams& aOptions)
-{
- if (SDK_VERSION < 20) {
- return setDefaultRouteLegacy(aOptions);
- }
-
- static CommandFunc COMMAND_CHAIN[] = {
- addDefaultRouteToNetwork,
- setDefaultNetwork,
- defaultAsyncSuccessHandler,
- };
-
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
- ERROR("No such interface");
- return -1;
- }
-
- aOptions.mNetId = netIdInfo.mNetId;
- aOptions.mLoopIndex = 0;
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
-
- return CommandResult::Pending();
-}
-
-/**
- * Set default route and DNS servers for given network interface by obsoleted libnetutils.
- */
-CommandResult NetworkUtils::setDefaultRouteLegacy(NetworkParams& aOptions)
-{
- NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
-
- uint32_t length = aOptions.mGateways.Length();
- if (length > 0) {
- for (uint32_t i = 0; i < length; i++) {
- NS_ConvertUTF16toUTF8 autoGateway(aOptions.mGateways[i]);
-
- int type = getIpType(autoGateway.get());
- if (type != AF_INET && type != AF_INET6) {
- continue;
- }
-
- if (type == AF_INET6) {
- RETURN_IF_FAILED(mNetUtils->do_ifc_add_route(autoIfname.get(), "::", 0, autoGateway.get()));
- } else { /* type == AF_INET */
- RETURN_IF_FAILED(mNetUtils->do_ifc_set_default_route(autoIfname.get(), inet_addr(autoGateway.get())));
- }
- }
- } else {
- // Set default froute from system properties.
- char key[Property::KEY_MAX_LENGTH];
- char gateway[Property::KEY_MAX_LENGTH];
-
- snprintf(key, sizeof key - 1, "net.%s.gw", autoIfname.get());
- Property::Get(key, gateway, "");
-
- int type = getIpType(gateway);
- if (type != AF_INET && type != AF_INET6) {
- return EAFNOSUPPORT;
- }
-
- if (type == AF_INET6) {
- RETURN_IF_FAILED(mNetUtils->do_ifc_add_route(autoIfname.get(), "::", 0, gateway));
- } else { /* type == AF_INET */
- RETURN_IF_FAILED(mNetUtils->do_ifc_set_default_route(autoIfname.get(), inet_addr(gateway)));
- }
- }
-
- // Set the default DNS interface.
- if (SDK_VERSION >= 18) {
- // For JB, KK only.
- static CommandFunc COMMAND_CHAIN[] = {
- setDefaultInterface,
- defaultAsyncSuccessHandler
- };
- runChain(aOptions, COMMAND_CHAIN, setDnsFail);
- return CommandResult::Pending();
- }
-
- return SUCCESS;
-}
-
-/**
- * Remove default route for given network interface.
- */
-CommandResult NetworkUtils::removeDefaultRoute(NetworkParams& aOptions)
-{
- NU_DBG("Calling NetworkUtils::removeDefaultRoute");
-
- if (SDK_VERSION < 20) {
- return removeDefaultRouteLegacy(aOptions);
- }
-
- static CommandFunc COMMAND_CHAIN[] = {
- removeDefaultRoute,
- defaultAsyncSuccessHandler,
- };
-
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
- ERROR("No such interface: %s", GET_CHAR(mIfname));
- return -1;
- }
-
- NU_DBG("Obtained netid %d for interface %s", netIdInfo.mNetId, GET_CHAR(mIfname));
-
- aOptions.mNetId = netIdInfo.mNetId;
- aOptions.mLoopIndex = 0;
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
-
- return CommandResult::Pending();
-}
-
-/**
- * Remove default route for given network interface by obsoleted libnetutils.
- */
-CommandResult NetworkUtils::removeDefaultRouteLegacy(NetworkParams& aOptions)
-{
- // Legacy libnetutils calls before Lollipop.
- uint32_t length = aOptions.mGateways.Length();
- for (uint32_t i = 0; i < length; i++) {
- NS_ConvertUTF16toUTF8 autoGateway(aOptions.mGateways[i]);
-
- int type = getIpType(autoGateway.get());
- if (type != AF_INET && type != AF_INET6) {
- return EAFNOSUPPORT;
- }
-
- WARN_IF_FAILED(mNetUtils->do_ifc_remove_route(GET_CHAR(mIfname),
- type == AF_INET ? "0.0.0.0" : "::",
- 0, autoGateway.get()));
- }
-
- return SUCCESS;
-}
-
-/**
- * Add host route for given network interface.
- */
-CommandResult NetworkUtils::addHostRoute(NetworkParams& aOptions)
-{
- if (SDK_VERSION < 20) {
- return addHostRouteLegacy(aOptions);
- }
-
- static CommandFunc COMMAND_CHAIN[] = {
- addRouteToInterface,
- defaultAsyncSuccessHandler,
- };
-
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
- ERROR("No such interface: %s", GET_CHAR(mIfname));
- return -1;
- }
-
- NU_DBG("Obtained netid %d for interface %s", netIdInfo.mNetId, GET_CHAR(mIfname));
-
- aOptions.mNetId = netIdInfo.mNetId;
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
-
- return CommandResult::Pending();
-}
-
-/**
- * Add host route for given network interface.
- */
-CommandResult NetworkUtils::addHostRouteLegacy(NetworkParams& aOptions)
-{
- if (aOptions.mGateway.IsEmpty()) {
- ERROR("addHostRouteLegacy does not support empty gateway.");
- return EINVAL;
- }
-
- NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
- NS_ConvertUTF16toUTF8 autoHostname(aOptions.mIp);
- NS_ConvertUTF16toUTF8 autoGateway(aOptions.mGateway);
- int type, prefix;
-
- type = getIpType(autoHostname.get());
- if (type != AF_INET && type != AF_INET6) {
- return EAFNOSUPPORT;
- }
-
- if (type != getIpType(autoGateway.get())) {
- return EINVAL;
- }
-
- prefix = type == AF_INET ? 32 : 128;
- return mNetUtils->do_ifc_add_route(autoIfname.get(), autoHostname.get(),
- prefix, autoGateway.get());
-}
-
-/**
- * Remove host route for given network interface.
- */
-CommandResult NetworkUtils::removeHostRoute(NetworkParams& aOptions)
-{
- if (SDK_VERSION < 20) {
- return removeHostRouteLegacy(aOptions);
- }
-
- static CommandFunc COMMAND_CHAIN[] = {
- removeRouteFromInterface,
- defaultAsyncSuccessHandler,
- };
-
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
- ERROR("No such interface: %s", GET_CHAR(mIfname));
- return -1;
- }
-
- NU_DBG("Obtained netid %d for interface %s", netIdInfo.mNetId, GET_CHAR(mIfname));
-
- aOptions.mNetId = netIdInfo.mNetId;
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
-
- return CommandResult::Pending();
-}
-
-/**
- * Remove host route for given network interface.
- */
-CommandResult NetworkUtils::removeHostRouteLegacy(NetworkParams& aOptions)
-{
- NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
- NS_ConvertUTF16toUTF8 autoHostname(aOptions.mIp);
- NS_ConvertUTF16toUTF8 autoGateway(aOptions.mGateway);
- int type, prefix;
-
- type = getIpType(autoHostname.get());
- if (type != AF_INET && type != AF_INET6) {
- return EAFNOSUPPORT;
- }
-
- if (type != getIpType(autoGateway.get())) {
- return EINVAL;
- }
-
- prefix = type == AF_INET ? 32 : 128;
- return mNetUtils->do_ifc_remove_route(autoIfname.get(), autoHostname.get(),
- prefix, autoGateway.get());
-}
-
-CommandResult NetworkUtils::removeNetworkRoute(NetworkParams& aOptions)
-{
- if (SDK_VERSION < 20) {
- return removeNetworkRouteLegacy(aOptions);
- }
-
- static CommandFunc COMMAND_CHAIN[] = {
- clearAddrForInterface,
- defaultAsyncSuccessHandler,
- };
-
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
- ERROR("interface %s is not present in any network", GET_CHAR(mIfname));
- return -1;
- }
-
- NU_DBG("Obtained netid %d for interface %s", netIdInfo.mNetId, GET_CHAR(mIfname));
-
- aOptions.mNetId = netIdInfo.mNetId;
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
-
- return CommandResult::Pending();
-}
-
-nsCString NetworkUtils::getSubnetIp(const nsCString& aIp, int aPrefixLength)
-{
- int type = getIpType(aIp.get());
-
- if (AF_INET6 == type) {
- struct in6_addr in6;
- if (inet_pton(AF_INET6, aIp.get(), &in6) != 1) {
- return nsCString();
- }
-
- uint32_t p, i, p1, mask;
- p = aPrefixLength;
- i = 0;
- while (i < 4) {
- p1 = p > 32 ? 32 : p;
- p -= p1;
- mask = p1 ? ~0x0 << (32 - p1) : 0;
- in6.s6_addr32[i++] &= htonl(mask);
- }
-
- char subnetStr[INET6_ADDRSTRLEN];
- if (!inet_ntop(AF_INET6, &in6, subnetStr, sizeof subnetStr)) {
- return nsCString();
- }
-
- return nsCString(subnetStr);
- }
-
- if (AF_INET == type) {
- uint32_t ip = inet_addr(aIp.get());
- uint32_t netmask = makeMask(aPrefixLength);
- uint32_t subnet = ip & netmask;
- struct in_addr addr;
- addr.s_addr = subnet;
- return nsCString(inet_ntoa(addr));
- }
-
- return nsCString();
-}
-
-CommandResult NetworkUtils::removeNetworkRouteLegacy(NetworkParams& aOptions)
-{
- NS_ConvertUTF16toUTF8 autoIfname(aOptions.mIfname);
- NS_ConvertUTF16toUTF8 autoIp(aOptions.mIp);
-
- int type = getIpType(autoIp.get());
- if (type != AF_INET && type != AF_INET6) {
- return EAFNOSUPPORT;
- }
-
- uint32_t prefixLength = GET_FIELD(mPrefixLength);
-
- if (type == AF_INET6) {
- // Calculate subnet.
- struct in6_addr in6;
- if (inet_pton(AF_INET6, autoIp.get(), &in6) != 1) {
- return EINVAL;
- }
-
- uint32_t p, i, p1, mask;
- p = prefixLength;
- i = 0;
- while (i < 4) {
- p1 = p > 32 ? 32 : p;
- p -= p1;
- mask = p1 ? ~0x0 << (32 - p1) : 0;
- in6.s6_addr32[i++] &= htonl(mask);
- }
-
- char subnetStr[INET6_ADDRSTRLEN];
- if (!inet_ntop(AF_INET6, &in6, subnetStr, sizeof subnetStr)) {
- return EINVAL;
- }
-
- // Remove default route.
- WARN_IF_FAILED(mNetUtils->do_ifc_remove_route(autoIfname.get(), "::", 0, NULL));
-
- // Remove subnet route.
- RETURN_IF_FAILED(mNetUtils->do_ifc_remove_route(autoIfname.get(), subnetStr, prefixLength, NULL));
- return SUCCESS;
- }
-
- /* type == AF_INET */
- uint32_t ip = inet_addr(autoIp.get());
- uint32_t netmask = makeMask(prefixLength);
- uint32_t subnet = ip & netmask;
- const char* gateway = "0.0.0.0";
- struct in_addr addr;
- addr.s_addr = subnet;
- const char* dst = inet_ntoa(addr);
-
- RETURN_IF_FAILED(mNetUtils->do_ifc_remove_default_route(autoIfname.get()));
- RETURN_IF_FAILED(mNetUtils->do_ifc_remove_route(autoIfname.get(), dst, prefixLength, gateway));
- return SUCCESS;
-}
-
-CommandResult NetworkUtils::addSecondaryRoute(NetworkParams& aOptions)
-{
- static CommandFunc COMMAND_CHAIN[] = {
- addRouteToSecondaryTable,
- defaultAsyncSuccessHandler
- };
-
- if (SDK_VERSION >= 20) {
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(aOptions.mIfname, &netIdInfo)) {
- return -1;
- }
- aOptions.mNetId = netIdInfo.mNetId;
- }
-
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::removeSecondaryRoute(NetworkParams& aOptions)
-{
- static CommandFunc COMMAND_CHAIN[] = {
- removeRouteFromSecondaryTable,
- defaultAsyncSuccessHandler
- };
-
- if (SDK_VERSION >= 20) {
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(aOptions.mIfname, &netIdInfo)) {
- return -1;
- }
- aOptions.mNetId = netIdInfo.mNetId;
- }
-
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::setNetworkInterfaceAlarm(NetworkParams& aOptions)
-{
- NU_DBG("setNetworkInterfaceAlarms: %s", GET_CHAR(mIfname));
- runChain(aOptions, sNetworkInterfaceSetAlarmChain, networkInterfaceAlarmFail);
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::enableNetworkInterfaceAlarm(NetworkParams& aOptions)
-{
- NU_DBG("enableNetworkInterfaceAlarm: %s", GET_CHAR(mIfname));
- runChain(aOptions, sNetworkInterfaceEnableAlarmChain, networkInterfaceAlarmFail);
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::disableNetworkInterfaceAlarm(NetworkParams& aOptions)
-{
- NU_DBG("disableNetworkInterfaceAlarms: %s", GET_CHAR(mIfname));
- runChain(aOptions, sNetworkInterfaceDisableAlarmChain, networkInterfaceAlarmFail);
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::setTetheringAlarm(NetworkParams& aOptions)
-{
- NU_DBG("setTetheringAlarm");
- runChain(aOptions, sTetheringInterfaceSetAlarmChain, networkInterfaceAlarmFail);
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::removeTetheringAlarm(NetworkParams& aOptions)
-{
- NU_DBG("removeTetheringAlarm");
- runChain(aOptions, sTetheringInterfaceRemoveAlarmChain, networkInterfaceAlarmFail);
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::getTetheringStatus(NetworkParams& aOptions)
-{
- NU_DBG("getTetheringStatus");
- runChain(aOptions, sTetheringGetStatusChain, networkInterfaceAlarmFail);
- return CommandResult::Pending();
-}
-
-/**
- * handling main thread's reload Wifi firmware request
- */
-CommandResult NetworkUtils::setWifiOperationMode(NetworkParams& aOptions)
-{
- NU_DBG("setWifiOperationMode: %s %s", GET_CHAR(mIfname), GET_CHAR(mMode));
- runChain(aOptions, sWifiOperationModeChain, wifiOperationModeFail);
- return CommandResult::Pending();
-}
-
-/**
- * handling main thread's enable/disable WiFi Tethering request
- */
-CommandResult NetworkUtils::setWifiTethering(NetworkParams& aOptions)
-{
- bool enable = aOptions.mEnable;
- IFProperties interfaceProperties;
- getIFProperties(GET_CHAR(mExternalIfname), interfaceProperties);
-
- if (strcmp(interfaceProperties.dns1, "")) {
- int type = getIpType(interfaceProperties.dns1);
- if (type != AF_INET6) {
- aOptions.mDns1 = NS_ConvertUTF8toUTF16(interfaceProperties.dns1);
- }
- }
- if (strcmp(interfaceProperties.dns2, "")) {
- int type = getIpType(interfaceProperties.dns2);
- if (type != AF_INET6) {
- aOptions.mDns2 = NS_ConvertUTF8toUTF16(interfaceProperties.dns2);
- }
- }
- dumpParams(aOptions, "WIFI");
-
- if (SDK_VERSION >= 20) {
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(aOptions.mExternalIfname, &netIdInfo)) {
- ERROR("No such interface: %s", GET_CHAR(mExternalIfname));
- return -1;
- }
- aOptions.mNetId = netIdInfo.mNetId;
- }
-
- if (enable) {
- NU_DBG("Starting Wifi Tethering on %s <-> %s",
- GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
- runChain(aOptions, sWifiEnableChain, wifiTetheringFail);
- } else {
- NU_DBG("Stopping Wifi Tethering on %s <-> %s",
- GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
- runChain(aOptions, sWifiDisableChain, wifiTetheringFail);
- }
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::setUSBTethering(NetworkParams& aOptions)
-{
- bool enable = aOptions.mEnable;
- IFProperties interfaceProperties;
- getIFProperties(GET_CHAR(mExternalIfname), interfaceProperties);
-
- if (strcmp(interfaceProperties.dns1, "")) {
- int type = getIpType(interfaceProperties.dns1);
- if (type != AF_INET6) {
- aOptions.mDns1 = NS_ConvertUTF8toUTF16(interfaceProperties.dns1);
- }
- }
- if (strcmp(interfaceProperties.dns2, "")) {
- int type = getIpType(interfaceProperties.dns2);
- if (type != AF_INET6) {
- aOptions.mDns2 = NS_ConvertUTF8toUTF16(interfaceProperties.dns2);
- }
- }
- dumpParams(aOptions, "USB");
-
- if (SDK_VERSION >= 20) {
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.lookup(aOptions.mExternalIfname, &netIdInfo)) {
- ERROR("No such interface: %s", GET_CHAR(mExternalIfname));
- return -1;
- }
- aOptions.mNetId = netIdInfo.mNetId;
- }
-
- if (enable) {
- NU_DBG("Starting USB Tethering on %s <-> %s",
- GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
- runChain(aOptions, sUSBEnableChain, usbTetheringFail);
- } else {
- NU_DBG("Stopping USB Tethering on %s <-> %s",
- GET_CHAR(mInternalIfname), GET_CHAR(mExternalIfname));
- runChain(aOptions, sUSBDisableChain, usbTetheringFail);
- }
- return CommandResult::Pending();
-}
-
-void NetworkUtils::escapeQuote(nsCString& aString)
-{
- aString.ReplaceSubstring("\\", "\\\\");
- aString.ReplaceSubstring("\"", "\\\"");
-}
-
-CommandResult NetworkUtils::checkUsbRndisState(NetworkParams& aOptions)
-{
- static uint32_t retry = 0;
-
- char currentState[Property::VALUE_MAX_LENGTH];
- Property::Get(SYS_USB_STATE_PROPERTY, currentState, nullptr);
-
- nsTArray<nsCString> stateFuncs;
- split(currentState, USB_CONFIG_DELIMIT, stateFuncs);
- bool rndisPresent = stateFuncs.Contains(nsCString(USB_FUNCTION_RNDIS));
-
- if (aOptions.mEnable == rndisPresent) {
- NetworkResultOptions result;
- result.mEnable = aOptions.mEnable;
- result.mResult = true;
- retry = 0;
- return result;
- }
- if (retry < USB_FUNCTION_RETRY_TIMES) {
- retry++;
- usleep(USB_FUNCTION_RETRY_INTERVAL * 1000);
- return checkUsbRndisState(aOptions);
- }
-
- NetworkResultOptions result;
- result.mResult = false;
- retry = 0;
- return result;
-}
-
-/**
- * Modify usb function's property to turn on USB RNDIS function
- */
-CommandResult NetworkUtils::enableUsbRndis(NetworkParams& aOptions)
-{
- bool report = aOptions.mReport;
-
- // For some reason, rndis doesn't play well with diag,modem,nmea.
- // So when turning rndis on, we set sys.usb.config to either "rndis"
- // or "rndis,adb". When turning rndis off, we go back to
- // persist.sys.usb.config.
- //
- // On the otoro/unagi, persist.sys.usb.config should be one of:
- //
- // diag,modem,nmea,mass_storage
- // diag,modem,nmea,mass_storage,adb
- //
- // When rndis is enabled, sys.usb.config should be one of:
- //
- // rdnis
- // rndis,adb
- //
- // and when rndis is disabled, it should revert to persist.sys.usb.config
-
- char currentConfig[Property::VALUE_MAX_LENGTH];
- Property::Get(SYS_USB_CONFIG_PROPERTY, currentConfig, nullptr);
-
- nsTArray<nsCString> configFuncs;
- split(currentConfig, USB_CONFIG_DELIMIT, configFuncs);
-
- char persistConfig[Property::VALUE_MAX_LENGTH];
- Property::Get(PERSIST_SYS_USB_CONFIG_PROPERTY, persistConfig, nullptr);
-
- nsTArray<nsCString> persistFuncs;
- split(persistConfig, USB_CONFIG_DELIMIT, persistFuncs);
-
- if (aOptions.mEnable) {
- configFuncs.Clear();
- configFuncs.AppendElement(nsCString(USB_FUNCTION_RNDIS));
- if (persistFuncs.Contains(nsCString(USB_FUNCTION_ADB))) {
- configFuncs.AppendElement(nsCString(USB_FUNCTION_ADB));
- }
- } else {
- // We're turning rndis off, revert back to the persist setting.
- // adb will already be correct there, so we don't need to do any
- // further adjustments.
- configFuncs = persistFuncs;
- }
-
- char newConfig[Property::VALUE_MAX_LENGTH] = "";
- Property::Get(SYS_USB_CONFIG_PROPERTY, currentConfig, nullptr);
- join(configFuncs, USB_CONFIG_DELIMIT, Property::VALUE_MAX_LENGTH, newConfig);
- if (strcmp(currentConfig, newConfig)) {
- Property::Set(SYS_USB_CONFIG_PROPERTY, newConfig);
- }
-
- // Trigger the timer to check usb state and report the result to NetworkManager.
- if (report) {
- usleep(USB_FUNCTION_RETRY_INTERVAL * 1000);
- return checkUsbRndisState(aOptions);
- }
- return SUCCESS;
-}
-
-/**
- * handling upstream interface change event.
- */
-CommandResult NetworkUtils::updateUpStream(NetworkParams& aOptions)
-{
- runChain(aOptions, sUpdateUpStreamChain, updateUpStreamFail);
- return CommandResult::Pending();
-}
-
-/**
- * handling upstream interface change event.
- */
-CommandResult NetworkUtils::createNetwork(NetworkParams& aOptions)
-{
- if (SDK_VERSION < 20) {
- return SUCCESS;
- }
-
- static CommandFunc COMMAND_CHAIN[] = {
- createNetwork,
- enableIpv6,
- addInterfaceToNetwork,
- defaultAsyncSuccessHandler,
- };
-
- NetIdManager::NetIdInfo netIdInfo;
- mNetIdManager.acquire(GET_FIELD(mIfname), &netIdInfo);
- if (netIdInfo.mRefCnt > 1) {
- // Already created. Just return.
- NU_DBG("Interface %s (%d) has been created.", GET_CHAR(mIfname),
- netIdInfo.mNetId);
- return SUCCESS;
- }
-
- NU_DBG("Request netd to create a network with netid %d", netIdInfo.mNetId);
- // Newly created netid. Ask netd to create network.
- aOptions.mNetId = netIdInfo.mNetId;
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
-
- return CommandResult::Pending();
-}
-
-/**
- * handling upstream interface change event.
- */
-CommandResult NetworkUtils::destroyNetwork(NetworkParams& aOptions)
-{
- if (SDK_VERSION < 20) {
- return SUCCESS;
- }
-
- static CommandFunc COMMAND_CHAIN[] = {
- disableIpv6,
- destroyNetwork,
- defaultAsyncSuccessHandler,
- };
-
- NetIdManager::NetIdInfo netIdInfo;
- if (!mNetIdManager.release(GET_FIELD(mIfname), &netIdInfo)) {
- ERROR("No existing netid for %s", GET_CHAR(mIfname));
- return -1;
- }
-
- if (netIdInfo.mRefCnt > 0) {
- // Still be referenced. Just return.
- NU_DBG("Someone is still using this interface.");
- return SUCCESS;
- }
-
- NU_DBG("Interface %s (%d) is no longer used. Tell netd to destroy.",
- GET_CHAR(mIfname), netIdInfo.mNetId);
-
- aOptions.mNetId = netIdInfo.mNetId;
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
- return CommandResult::Pending();
-}
-
-/**
- * Query the netId associated with the given network interface name.
- */
-CommandResult NetworkUtils::getNetId(NetworkParams& aOptions)
-{
- NetworkResultOptions result;
-
- if (SDK_VERSION < 20) {
- // For pre-Lollipop, use the interface name as the fallback.
- result.mNetId = GET_FIELD(mIfname);
- return result;
- }
-
- NetIdManager::NetIdInfo netIdInfo;
- if (-1 == mNetIdManager.lookup(GET_FIELD(mIfname), &netIdInfo)) {
- return ESRCH;
- }
- result.mNetId.AppendInt(netIdInfo.mNetId, 10);
- return result;
-}
-
-/**
- * Get existing network interfaces.
- */
-CommandResult NetworkUtils::getInterfaces(NetworkParams& aOptions)
-{
- runChain(aOptions, sGetInterfacesChain, getInterfacesFail);
- return CommandResult::Pending();
-}
-
-/**
- * Get network config of a specified interface.
- */
-CommandResult NetworkUtils::getInterfaceConfig(NetworkParams& aOptions)
-{
- runChain(aOptions, sGetInterfaceConfigChain, getInterfaceConfigFail);
- return CommandResult::Pending();
-}
-
-/**
- * Set network config for a specified interface.
- */
-CommandResult NetworkUtils::setInterfaceConfig(NetworkParams& aOptions)
-{
- runChain(aOptions, sSetInterfaceConfigChain, setInterfaceConfigFail);
- return CommandResult::Pending();
-}
-
-CommandResult NetworkUtils::setMtu(NetworkParams& aOptions)
-{
- // Setting/getting mtu is supported since Kitkat.
- if (SDK_VERSION < 19) {
- ERROR("setMtu is not supported in current SDK_VERSION.");
- return -1;
- }
-
- static CommandFunc COMMAND_CHAIN[] = {
- setMtu,
- defaultAsyncSuccessHandler,
- };
-
- runChain(aOptions, COMMAND_CHAIN, defaultAsyncFailureHandler);
- return CommandResult::Pending();
-}
-
-void NetworkUtils::sendBroadcastMessage(uint32_t code, char* reason)
-{
- NetworkResultOptions result;
- switch(code) {
- case NETD_COMMAND_INTERFACE_CHANGE:
- result.mTopic = NS_ConvertUTF8toUTF16("netd-interface-change");
- break;
- case NETD_COMMAND_BANDWIDTH_CONTROLLER:
- result.mTopic = NS_ConvertUTF8toUTF16("netd-bandwidth-control");
- break;
- default:
- return;
- }
-
- result.mBroadcast = true;
- result.mReason = NS_ConvertUTF8toUTF16(reason);
- postMessage(result);
-}
-
-inline uint32_t NetworkUtils::netdResponseType(uint32_t code)
-{
- return (code / 100) * 100;
-}
-
-inline bool NetworkUtils::isBroadcastMessage(uint32_t code)
-{
- uint32_t type = netdResponseType(code);
- return type == NETD_COMMAND_UNSOLICITED;
-}
-
-inline bool NetworkUtils::isError(uint32_t code)
-{
- uint32_t type = netdResponseType(code);
- return type != NETD_COMMAND_PROCEEDING && type != NETD_COMMAND_OKAY;
-}
-
-inline bool NetworkUtils::isComplete(uint32_t code)
-{
- uint32_t type = netdResponseType(code);
- return type != NETD_COMMAND_PROCEEDING;
-}
-
-inline bool NetworkUtils::isProceeding(uint32_t code)
-{
- uint32_t type = netdResponseType(code);
- return type == NETD_COMMAND_PROCEEDING;
-}
-
-void NetworkUtils::dumpParams(NetworkParams& aOptions, const char* aType)
-{
-#ifdef _DEBUG
- NU_DBG("Dump params:");
- NU_DBG(" ifname: %s", GET_CHAR(mIfname));
- NU_DBG(" ip: %s", GET_CHAR(mIp));
- NU_DBG(" link: %s", GET_CHAR(mLink));
- NU_DBG(" prefix: %s", GET_CHAR(mPrefix));
- NU_DBG(" wifiStartIp: %s", GET_CHAR(mWifiStartIp));
- NU_DBG(" wifiEndIp: %s", GET_CHAR(mWifiEndIp));
- NU_DBG(" usbStartIp: %s", GET_CHAR(mUsbStartIp));
- NU_DBG(" usbEndIp: %s", GET_CHAR(mUsbEndIp));
- NU_DBG(" dnsserver1: %s", GET_CHAR(mDns1));
- NU_DBG(" dnsserver2: %s", GET_CHAR(mDns2));
- NU_DBG(" internalIfname: %s", GET_CHAR(mInternalIfname));
- NU_DBG(" externalIfname: %s", GET_CHAR(mExternalIfname));
- if (!strcmp(aType, "WIFI")) {
- NU_DBG(" wifictrlinterfacename: %s", GET_CHAR(mWifictrlinterfacename));
- NU_DBG(" ssid: %s", GET_CHAR(mSsid));
- NU_DBG(" security: %s", GET_CHAR(mSecurity));
- NU_DBG(" key: %s", GET_CHAR(mKey));
- }
-#endif
-}
-
-#undef GET_CHAR
-#undef GET_FIELD
diff --git a/dom/system/gonk/NetworkUtils.h b/dom/system/gonk/NetworkUtils.h
deleted file mode 100644
index d1af35f09..000000000
--- a/dom/system/gonk/NetworkUtils.h
+++ /dev/null
@@ -1,498 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 NetworkUtils_h
-#define NetworkUtils_h
-
-#include "nsAutoPtr.h"
-#include "nsString.h"
-#include "mozilla/dom/NetworkOptionsBinding.h"
-#include "mozilla/dom/network/NetUtils.h"
-#include "mozilla/ipc/Netd.h"
-#include "nsTArray.h"
-#include "NetIdManager.h"
-
-class NetworkParams;
-class CommandChain;
-
-class CommandCallback {
-public:
- typedef void (*CallbackType)(CommandChain*, bool,
- mozilla::dom::NetworkResultOptions& aResult);
-
- typedef void (*CallbackWrapperType)(CallbackType aOriginalCallback,
- CommandChain*, bool,
- mozilla::dom::NetworkResultOptions& aResult);
-
- CommandCallback()
- : mCallback(nullptr)
- , mCallbackWrapper(nullptr)
- {
- }
-
- CommandCallback(CallbackType aCallback)
- : mCallback(aCallback)
- , mCallbackWrapper(nullptr)
- {
- }
-
- CommandCallback(CallbackWrapperType aCallbackWrapper,
- CommandCallback aOriginalCallback)
- : mCallback(aOriginalCallback.mCallback)
- , mCallbackWrapper(aCallbackWrapper)
- {
- }
-
- void operator()(CommandChain* aChain, bool aError,
- mozilla::dom::NetworkResultOptions& aResult)
- {
- if (mCallbackWrapper) {
- return mCallbackWrapper(mCallback, aChain, aError, aResult);
- }
- if (mCallback) {
- return mCallback(aChain, aError, aResult);
- }
- }
-
-private:
- CallbackType mCallback;
- CallbackWrapperType mCallbackWrapper;
-};
-
-typedef void (*CommandFunc)(CommandChain*, CommandCallback,
- mozilla::dom::NetworkResultOptions& aResult);
-typedef void (*MessageCallback)(mozilla::dom::NetworkResultOptions& aResult);
-typedef void (*ErrorCallback)(NetworkParams& aOptions,
- mozilla::dom::NetworkResultOptions& aResult);
-
-class NetworkParams
-{
-public:
- NetworkParams() {
- }
-
- NetworkParams(const mozilla::dom::NetworkCommandOptions& aOther) {
-
-#define COPY_SEQUENCE_FIELD(prop, type) \
- if (aOther.prop.WasPassed()) { \
- mozilla::dom::Sequence<type > const & currentValue = aOther.prop.InternalValue(); \
- uint32_t length = currentValue.Length(); \
- for (uint32_t idx = 0; idx < length; idx++) { \
- prop.AppendElement(currentValue[idx]); \
- } \
- }
-
-#define COPY_OPT_STRING_FIELD(prop, defaultValue) \
- if (aOther.prop.WasPassed()) { \
- if (aOther.prop.Value().EqualsLiteral("null")) { \
- prop = defaultValue; \
- } else { \
- prop = aOther.prop.Value(); \
- } \
- } else { \
- prop = defaultValue; \
- }
-
-#define COPY_OPT_FIELD(prop, defaultValue) \
- if (aOther.prop.WasPassed()) { \
- prop = aOther.prop.Value(); \
- } else { \
- prop = defaultValue; \
- }
-
-#define COPY_FIELD(prop) prop = aOther.prop;
-
- COPY_FIELD(mId)
- COPY_FIELD(mCmd)
- COPY_OPT_STRING_FIELD(mDomain, EmptyString())
- COPY_OPT_STRING_FIELD(mGateway, EmptyString())
- COPY_SEQUENCE_FIELD(mGateways, nsString)
- COPY_OPT_STRING_FIELD(mIfname, EmptyString())
- COPY_OPT_STRING_FIELD(mIp, EmptyString())
- COPY_OPT_FIELD(mPrefixLength, 0)
- COPY_OPT_STRING_FIELD(mMode, EmptyString())
- COPY_OPT_FIELD(mReport, false)
- COPY_OPT_FIELD(mEnabled, false)
- COPY_OPT_STRING_FIELD(mWifictrlinterfacename, EmptyString())
- COPY_OPT_STRING_FIELD(mInternalIfname, EmptyString())
- COPY_OPT_STRING_FIELD(mExternalIfname, EmptyString())
- COPY_OPT_FIELD(mEnable, false)
- COPY_OPT_STRING_FIELD(mSsid, EmptyString())
- COPY_OPT_STRING_FIELD(mSecurity, EmptyString())
- COPY_OPT_STRING_FIELD(mKey, EmptyString())
- COPY_OPT_STRING_FIELD(mPrefix, EmptyString())
- COPY_OPT_STRING_FIELD(mLink, EmptyString())
- COPY_SEQUENCE_FIELD(mInterfaceList, nsString)
- COPY_OPT_STRING_FIELD(mWifiStartIp, EmptyString())
- COPY_OPT_STRING_FIELD(mWifiEndIp, EmptyString())
- COPY_OPT_STRING_FIELD(mUsbStartIp, EmptyString())
- COPY_OPT_STRING_FIELD(mUsbEndIp, EmptyString())
- COPY_OPT_STRING_FIELD(mDns1, EmptyString())
- COPY_OPT_STRING_FIELD(mDns2, EmptyString())
- COPY_SEQUENCE_FIELD(mDnses, nsString)
- COPY_OPT_STRING_FIELD(mStartIp, EmptyString())
- COPY_OPT_STRING_FIELD(mEndIp, EmptyString())
- COPY_OPT_STRING_FIELD(mServerIp, EmptyString())
- COPY_OPT_STRING_FIELD(mMaskLength, EmptyString())
- COPY_OPT_STRING_FIELD(mPreInternalIfname, EmptyString())
- COPY_OPT_STRING_FIELD(mPreExternalIfname, EmptyString())
- COPY_OPT_STRING_FIELD(mCurInternalIfname, EmptyString())
- COPY_OPT_STRING_FIELD(mCurExternalIfname, EmptyString())
- COPY_OPT_FIELD(mThreshold, -1)
- COPY_OPT_FIELD(mIpaddr, 0)
- COPY_OPT_FIELD(mMask, 0)
- COPY_OPT_FIELD(mGateway_long, 0)
- COPY_OPT_FIELD(mDns1_long, 0)
- COPY_OPT_FIELD(mDns2_long, 0)
- COPY_OPT_FIELD(mMtu, 0)
-
- mLoopIndex = 0;
-
-#undef COPY_SEQUENCE_FIELD
-#undef COPY_OPT_STRING_FIELD
-#undef COPY_OPT_FIELD
-#undef COPY_FIELD
- }
-
- // Followings attributes are 1-to-1 mapping to NetworkCommandOptions.
- int32_t mId;
- nsString mCmd;
- nsString mDomain;
- nsString mGateway;
- nsTArray<nsString> mGateways;
- nsString mIfname;
- nsString mIp;
- uint32_t mPrefixLength;
- nsString mMode;
- bool mReport;
- bool mEnabled;
- nsString mWifictrlinterfacename;
- nsString mInternalIfname;
- nsString mExternalIfname;
- bool mEnable;
- nsString mSsid;
- nsString mSecurity;
- nsString mKey;
- nsString mPrefix;
- nsString mLink;
- nsTArray<nsString> mInterfaceList;
- nsString mWifiStartIp;
- nsString mWifiEndIp;
- nsString mUsbStartIp;
- nsString mUsbEndIp;
- nsString mDns1;
- nsString mDns2;
- nsTArray<nsString> mDnses;
- nsString mStartIp;
- nsString mEndIp;
- nsString mServerIp;
- nsString mMaskLength;
- nsString mPreInternalIfname;
- nsString mPreExternalIfname;
- nsString mCurInternalIfname;
- nsString mCurExternalIfname;
- long long mThreshold;
- long mIpaddr;
- long mMask;
- long mGateway_long;
- long mDns1_long;
- long mDns2_long;
- long mMtu;
-
- // Auxiliary information required to carry accros command chain.
- int mNetId; // A locally defined id per interface.
- uint32_t mLoopIndex; // Loop index for adding/removing multiple gateways.
-};
-
-// CommandChain store the necessary information to execute command one by one.
-// Including :
-// 1. Command parameters.
-// 2. Command list.
-// 3. Error callback function.
-// 4. Index of current execution command.
-class CommandChain final
-{
-public:
- CommandChain(const NetworkParams& aParams,
- const CommandFunc aCmds[],
- uint32_t aLength,
- ErrorCallback aError)
- : mIndex(-1)
- , mParams(aParams)
- , mCommands(aCmds)
- , mLength(aLength)
- , mError(aError) {
- }
-
- NetworkParams&
- getParams()
- {
- return mParams;
- };
-
- CommandFunc
- getNextCommand()
- {
- mIndex++;
- return mIndex < mLength ? mCommands[mIndex] : nullptr;
- };
-
- ErrorCallback
- getErrorCallback() const
- {
- return mError;
- };
-
-private:
- uint32_t mIndex;
- NetworkParams mParams;
- const CommandFunc* mCommands;
- uint32_t mLength;
- ErrorCallback mError;
-};
-
-// A helper class to easily construct a resolved
-// or a pending result for command execution.
-class CommandResult
-{
-public:
- struct Pending {};
-
-public:
- CommandResult(int32_t aResultCode);
- CommandResult(const mozilla::dom::NetworkResultOptions& aResult);
- CommandResult(const Pending&);
- bool isPending() const;
-
- mozilla::dom::NetworkResultOptions mResult;
-
-private:
- bool mIsPending;
-};
-
-class NetworkUtils final
-{
-public:
- NetworkUtils(MessageCallback aCallback);
- ~NetworkUtils();
-
- void ExecuteCommand(NetworkParams aOptions);
- void onNetdMessage(mozilla::ipc::NetdCommand* aCommand);
-
- MessageCallback getMessageCallback() { return mMessageCallback; }
-
-private:
- /**
- * Commands supported by NetworkUtils.
- */
- CommandResult configureInterface(NetworkParams& aOptions);
- CommandResult dhcpRequest(NetworkParams& aOptions);
- CommandResult stopDhcp(NetworkParams& aOptions);
- CommandResult enableInterface(NetworkParams& aOptions);
- CommandResult disableInterface(NetworkParams& aOptions);
- CommandResult resetConnections(NetworkParams& aOptions);
- CommandResult setDefaultRoute(NetworkParams& aOptions);
- CommandResult addHostRoute(NetworkParams& aOptions);
- CommandResult removeDefaultRoute(NetworkParams& aOptions);
- CommandResult removeHostRoute(NetworkParams& aOptions);
- CommandResult removeNetworkRoute(NetworkParams& aOptions);
- CommandResult setDNS(NetworkParams& aOptions);
- CommandResult addSecondaryRoute(NetworkParams& aOptions);
- CommandResult removeSecondaryRoute(NetworkParams& aOptions);
- CommandResult setNetworkInterfaceAlarm(NetworkParams& aOptions);
- CommandResult enableNetworkInterfaceAlarm(NetworkParams& aOptions);
- CommandResult disableNetworkInterfaceAlarm(NetworkParams& aOptions);
- CommandResult setTetheringAlarm(NetworkParams& aOptions);
- CommandResult removeTetheringAlarm(NetworkParams& aOptions);
- CommandResult getTetheringStatus(NetworkParams& aOptions);
- CommandResult setWifiOperationMode(NetworkParams& aOptions);
- CommandResult setDhcpServer(NetworkParams& aOptions);
- CommandResult setWifiTethering(NetworkParams& aOptions);
- CommandResult setUSBTethering(NetworkParams& aOptions);
- CommandResult enableUsbRndis(NetworkParams& aOptions);
- CommandResult updateUpStream(NetworkParams& aOptions);
- CommandResult createNetwork(NetworkParams& aOptions);
- CommandResult destroyNetwork(NetworkParams& aOptions);
- CommandResult getNetId(NetworkParams& aOptions);
- CommandResult setMtu(NetworkParams& aOptions);
- CommandResult getInterfaces(NetworkParams& aOptions);
- CommandResult getInterfaceConfig(NetworkParams& aOptions);
- CommandResult setInterfaceConfig(NetworkParams& aOptions);
-
- CommandResult addHostRouteLegacy(NetworkParams& aOptions);
- CommandResult removeHostRouteLegacy(NetworkParams& aOptions);
- CommandResult setDefaultRouteLegacy(NetworkParams& aOptions);
- CommandResult removeDefaultRouteLegacy(NetworkParams& aOptions);
- CommandResult removeNetworkRouteLegacy(NetworkParams& aOptions);
-
-
- /**
- * function pointer array holds all netd commands should be executed
- * in sequence to accomplish a given command by other module.
- */
- static const CommandFunc sWifiEnableChain[];
- static const CommandFunc sWifiDisableChain[];
- static const CommandFunc sWifiFailChain[];
- static const CommandFunc sWifiRetryChain[];
- static const CommandFunc sWifiOperationModeChain[];
- static const CommandFunc sUSBEnableChain[];
- static const CommandFunc sUSBDisableChain[];
- static const CommandFunc sUSBFailChain[];
- static const CommandFunc sUpdateUpStreamChain[];
- static const CommandFunc sStartDhcpServerChain[];
- static const CommandFunc sStopDhcpServerChain[];
- static const CommandFunc sNetworkInterfaceEnableAlarmChain[];
- static const CommandFunc sNetworkInterfaceDisableAlarmChain[];
- static const CommandFunc sNetworkInterfaceSetAlarmChain[];
- static const CommandFunc sTetheringInterfaceSetAlarmChain[];
- static const CommandFunc sTetheringInterfaceRemoveAlarmChain[];
- static const CommandFunc sTetheringGetStatusChain[];
- static const CommandFunc sGetInterfacesChain[];
- static const CommandFunc sGetInterfaceConfigChain[];
- static const CommandFunc sSetInterfaceConfigChain[];
-
- /**
- * Individual netd command stored in command chain.
- */
-#define PARAMS CommandChain* aChain, CommandCallback aCallback, \
- mozilla::dom::NetworkResultOptions& aResult
- static void wifiFirmwareReload(PARAMS);
- static void startAccessPointDriver(PARAMS);
- static void stopAccessPointDriver(PARAMS);
- static void setAccessPoint(PARAMS);
- static void cleanUpStream(PARAMS);
- static void createUpStream(PARAMS);
- static void startSoftAP(PARAMS);
- static void stopSoftAP(PARAMS);
- static void clearWifiTetherParms(PARAMS);
- static void enableAlarm(PARAMS);
- static void disableAlarm(PARAMS);
- static void setQuota(PARAMS);
- static void removeQuota(PARAMS);
- static void setAlarm(PARAMS);
- static void removeAlarm(PARAMS);
- static void setGlobalAlarm(PARAMS);
- static void removeGlobalAlarm(PARAMS);
- static void tetherInterface(PARAMS);
- static void addInterfaceToLocalNetwork(PARAMS);
- static void addRouteToLocalNetwork(PARAMS);
- static void preTetherInterfaceList(PARAMS);
- static void postTetherInterfaceList(PARAMS);
- static void addUpstreamInterface(PARAMS);
- static void removeUpstreamInterface(PARAMS);
- static void setIpForwardingEnabled(PARAMS);
- static void tetheringStatus(PARAMS);
- static void stopTethering(PARAMS);
- static void startTethering(PARAMS);
- static void untetherInterface(PARAMS);
- static void removeInterfaceFromLocalNetwork(PARAMS);
- static void setDnsForwarders(PARAMS);
- static void enableNat(PARAMS);
- static void disableNat(PARAMS);
- static void setDefaultInterface(PARAMS);
- static void setInterfaceDns(PARAMS);
- static void getInterfaceList(PARAMS);
- static void getConfig(PARAMS);
- static void setConfig(PARAMS);
- static void wifiTetheringSuccess(PARAMS);
- static void usbTetheringSuccess(PARAMS);
- static void networkInterfaceAlarmSuccess(PARAMS);
- static void updateUpStreamSuccess(PARAMS);
- static void setDhcpServerSuccess(PARAMS);
- static void wifiOperationModeSuccess(PARAMS);
- static void clearAddrForInterface(PARAMS);
- static void createNetwork(PARAMS);
- static void destroyNetwork(PARAMS);
- static void addInterfaceToNetwork(PARAMS);
- static void addDefaultRouteToNetwork(PARAMS);
- static void setDefaultNetwork(PARAMS);
- static void removeDefaultRoute(PARAMS);
- static void removeNetworkRouteSuccess(PARAMS);
- static void removeNetworkRoute(PARAMS);
- static void addRouteToInterface(PARAMS);
- static void removeRouteFromInterface(PARAMS);
- static void modifyRouteOnInterface(PARAMS, bool aDoAdd);
- static void enableIpv6(PARAMS);
- static void disableIpv6(PARAMS);
- static void setMtu(PARAMS);
- static void setIpv6Enabled(PARAMS, bool aEnabled);
- static void addRouteToSecondaryTable(PARAMS);
- static void removeRouteFromSecondaryTable(PARAMS);
- static void defaultAsyncSuccessHandler(PARAMS);
- static void getInterfacesSuccess(PARAMS);
- static void getInterfaceConfigSuccess(PARAMS);
- static void setInterfaceConfigSuccess(PARAMS);
-
-#undef PARAMS
-
- /**
- * Error callback function executed when a command is fail.
- */
-#define PARAMS NetworkParams& aOptions, \
- mozilla::dom::NetworkResultOptions& aResult
- static void wifiTetheringFail(PARAMS);
- static void wifiOperationModeFail(PARAMS);
- static void usbTetheringFail(PARAMS);
- static void updateUpStreamFail(PARAMS);
- static void setDhcpServerFail(PARAMS);
- static void networkInterfaceAlarmFail(PARAMS);
- static void setDnsFail(PARAMS);
- static void defaultAsyncFailureHandler(PARAMS);
- static void getInterfacesFail(PARAMS);
- static void getInterfaceConfigFail(PARAMS);
- static void setInterfaceConfigFail(PARAMS);
-
-#undef PARAMS
-
- /**
- * Command chain processing functions.
- */
- static void next(CommandChain* aChain, bool aError,
- mozilla::dom::NetworkResultOptions& aResult);
- static void nextNetdCommand();
- static void doCommand(const char* aCommand, CommandChain* aChain, CommandCallback aCallback);
-
- /**
- * Notify broadcast message to main thread.
- */
- void sendBroadcastMessage(uint32_t code, char* reason);
-
- /**
- * Utility functions.
- */
- CommandResult checkUsbRndisState(NetworkParams& aOptions);
- void dumpParams(NetworkParams& aOptions, const char* aType);
-
- static void escapeQuote(nsCString& aString);
- inline uint32_t netdResponseType(uint32_t code);
- inline bool isBroadcastMessage(uint32_t code);
- inline bool isError(uint32_t code);
- inline bool isComplete(uint32_t code);
- inline bool isProceeding(uint32_t code);
- void Shutdown();
- static void runNextQueuedCommandChain();
- static void finalizeSuccess(CommandChain* aChain,
- mozilla::dom::NetworkResultOptions& aResult);
-
- template<size_t N>
- static void runChain(const NetworkParams& aParams,
- const CommandFunc (&aCmds)[N],
- ErrorCallback aError);
-
- static nsCString getSubnetIp(const nsCString& aIp, int aPrefixLength);
-
- /**
- * Callback function to send netd result to main thread.
- */
- MessageCallback mMessageCallback;
-
- /*
- * Utility class to access libnetutils.
- */
- nsAutoPtr<NetUtils> mNetUtils;
-
- NetIdManager mNetIdManager;
-};
-
-#endif
diff --git a/dom/system/gonk/NetworkWorker.cpp b/dom/system/gonk/NetworkWorker.cpp
deleted file mode 100644
index caf07f375..000000000
--- a/dom/system/gonk/NetworkWorker.cpp
+++ /dev/null
@@ -1,271 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "NetworkWorker.h"
-#include "NetworkUtils.h"
-#include <nsThreadUtils.h>
-#include "mozilla/ModuleUtils.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "nsAutoPtr.h"
-#include "nsXULAppAPI.h"
-
-#define NS_NETWORKWORKER_CID \
- { 0x6df093e1, 0x8127, 0x4fa7, {0x90, 0x13, 0xa3, 0xaa, 0xa7, 0x79, 0xbb, 0xdd} }
-
-using namespace mozilla;
-using namespace mozilla::dom;
-using namespace mozilla::ipc;
-
-namespace mozilla {
-
-nsCOMPtr<nsIThread> gWorkerThread;
-
-// The singleton network worker, to be used on the main thread.
-StaticRefPtr<NetworkWorker> gNetworkWorker;
-
-// The singleton networkutils class, that can be used on any thread.
-static nsAutoPtr<NetworkUtils> gNetworkUtils;
-
-// Runnable used dispatch command result on the main thread.
-class NetworkResultDispatcher : public Runnable
-{
-public:
- NetworkResultDispatcher(const NetworkResultOptions& aResult)
- : mResult(aResult)
- {
- MOZ_ASSERT(!NS_IsMainThread());
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- if (gNetworkWorker) {
- gNetworkWorker->DispatchNetworkResult(mResult);
- }
- return NS_OK;
- }
-private:
- NetworkResultOptions mResult;
-};
-
-// Runnable used dispatch netd command on the worker thread.
-class NetworkCommandDispatcher : public Runnable
-{
-public:
- NetworkCommandDispatcher(const NetworkParams& aParams)
- : mParams(aParams)
- {
- MOZ_ASSERT(NS_IsMainThread());
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(!NS_IsMainThread());
-
- if (gNetworkUtils) {
- gNetworkUtils->ExecuteCommand(mParams);
- }
- return NS_OK;
- }
-private:
- NetworkParams mParams;
-};
-
-// Runnable used dispatch netd result on the worker thread.
-class NetdEventRunnable : public Runnable
-{
-public:
- NetdEventRunnable(NetdCommand* aCommand)
- : mCommand(aCommand)
- {
- MOZ_ASSERT(!NS_IsMainThread());
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(!NS_IsMainThread());
-
- if (gNetworkUtils) {
- gNetworkUtils->onNetdMessage(mCommand);
- }
- return NS_OK;
- }
-
-private:
- nsAutoPtr<NetdCommand> mCommand;
-};
-
-class NetdMessageConsumer : public NetdConsumer
-{
-public:
- NetdMessageConsumer()
- {
- MOZ_ASSERT(NS_IsMainThread());
- }
-
- void MessageReceived(NetdCommand* aCommand)
- {
- MOZ_ASSERT(!NS_IsMainThread());
-
- nsCOMPtr<nsIRunnable> runnable = new NetdEventRunnable(aCommand);
- if (gWorkerThread) {
- gWorkerThread->Dispatch(runnable, nsIEventTarget::DISPATCH_NORMAL);
- }
- }
-};
-
-NS_IMPL_ISUPPORTS(NetworkWorker, nsINetworkWorker)
-
-NetworkWorker::NetworkWorker()
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!gNetworkWorker);
-}
-
-NetworkWorker::~NetworkWorker()
-{
- MOZ_ASSERT(!gNetworkWorker);
- MOZ_ASSERT(!mListener);
-}
-
-already_AddRefed<NetworkWorker>
-NetworkWorker::FactoryCreate()
-{
- if (!XRE_IsParentProcess()) {
- return nullptr;
- }
-
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!gNetworkWorker) {
- gNetworkWorker = new NetworkWorker();
- ClearOnShutdown(&gNetworkWorker);
-
- gNetworkUtils = new NetworkUtils(NetworkWorker::NotifyResult);
- ClearOnShutdown(&gNetworkUtils);
- }
-
- RefPtr<NetworkWorker> worker = gNetworkWorker.get();
- return worker.forget();
-}
-
-NS_IMETHODIMP
-NetworkWorker::Start(nsINetworkEventListener* aListener)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(aListener);
-
- if (mListener) {
- return NS_OK;
- }
-
- nsresult rv;
-
- rv = NS_NewNamedThread("NetworkWorker", getter_AddRefs(gWorkerThread));
- if (NS_FAILED(rv)) {
- NS_WARNING("Can't create network control thread");
- return NS_ERROR_FAILURE;
- }
-
- StartNetd(new NetdMessageConsumer());
- mListener = aListener;
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-NetworkWorker::Shutdown()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!mListener) {
- return NS_OK;
- }
-
- StopNetd();
-
- gWorkerThread->Shutdown();
- gWorkerThread = nullptr;
-
- mListener = nullptr;
- return NS_OK;
-}
-
-// Receive command from main thread (NetworkService.js).
-NS_IMETHODIMP
-NetworkWorker::PostMessage(JS::Handle<JS::Value> aOptions, JSContext* aCx)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- NetworkCommandOptions options;
- if (!options.Init(aCx, aOptions)) {
- NS_WARNING("Bad dictionary passed to NetworkWorker::SendCommand");
- return NS_ERROR_FAILURE;
- }
-
- // Dispatch the command to the control thread.
- NetworkParams NetworkParams(options);
- nsCOMPtr<nsIRunnable> runnable = new NetworkCommandDispatcher(NetworkParams);
- if (gWorkerThread) {
- gWorkerThread->Dispatch(runnable, nsIEventTarget::DISPATCH_NORMAL);
- }
- return NS_OK;
-}
-
-void
-NetworkWorker::DispatchNetworkResult(const NetworkResultOptions& aOptions)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- mozilla::AutoSafeJSContext cx;
- JS::RootedValue val(cx);
-
- if (!ToJSValue(cx, aOptions, &val)) {
- return;
- }
-
- // Call the listener with a JS value.
- if (mListener) {
- mListener->OnEvent(val);
- }
-}
-
-// Callback function from network worker thread to update result on main thread.
-void
-NetworkWorker::NotifyResult(NetworkResultOptions& aResult)
-{
- MOZ_ASSERT(!NS_IsMainThread());
-
- nsCOMPtr<nsIRunnable> runnable = new NetworkResultDispatcher(aResult);
- NS_DispatchToMainThread(runnable);
-}
-
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(NetworkWorker,
- NetworkWorker::FactoryCreate)
-
-NS_DEFINE_NAMED_CID(NS_NETWORKWORKER_CID);
-
-static const mozilla::Module::CIDEntry kNetworkWorkerCIDs[] = {
- { &kNS_NETWORKWORKER_CID, false, nullptr, NetworkWorkerConstructor },
- { nullptr }
-};
-
-static const mozilla::Module::ContractIDEntry kNetworkWorkerContracts[] = {
- { "@mozilla.org/network/worker;1", &kNS_NETWORKWORKER_CID },
- { nullptr }
-};
-
-static const mozilla::Module kNetworkWorkerModule = {
- mozilla::Module::kVersion,
- kNetworkWorkerCIDs,
- kNetworkWorkerContracts,
- nullptr
-};
-
-} // namespace mozilla
-
-NSMODULE_DEFN(NetworkWorkerModule) = &kNetworkWorkerModule;
diff --git a/dom/system/gonk/NetworkWorker.h b/dom/system/gonk/NetworkWorker.h
deleted file mode 100644
index f5c0a8fdd..000000000
--- a/dom/system/gonk/NetworkWorker.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 NetworkWorker_h
-#define NetworkWorker_h
-
-#include "mozilla/dom/NetworkOptionsBinding.h"
-#include "mozilla/ipc/Netd.h"
-#include "nsINetworkWorker.h"
-#include "nsCOMPtr.h"
-#include "nsThread.h"
-
-namespace mozilla {
-
-class NetworkWorker final : public nsINetworkWorker
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSINETWORKWORKER
-
- static already_AddRefed<NetworkWorker> FactoryCreate();
-
- void DispatchNetworkResult(const mozilla::dom::NetworkResultOptions& aOptions);
-
-private:
- NetworkWorker();
- ~NetworkWorker();
-
- static void NotifyResult(mozilla::dom::NetworkResultOptions& aResult);
-
- nsCOMPtr<nsINetworkEventListener> mListener;
-};
-
-} // namespace mozilla
-
-#endif // NetworkWorker_h
diff --git a/dom/system/gonk/OpenFileFinder.cpp b/dom/system/gonk/OpenFileFinder.cpp
deleted file mode 100644
index 388e813e1..000000000
--- a/dom/system/gonk/OpenFileFinder.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "OpenFileFinder.h"
-
-#include "mozilla/FileUtils.h"
-#include "nsPrintfCString.h"
-
-#include <sys/stat.h>
-#include <errno.h>
-
-#undef USE_DEBUG
-#define USE_DEBUG 0
-
-#undef LOG
-#undef LOGW
-#undef ERR
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "OpenFileFinder", ## args)
-#define LOGW(args...) __android_log_print(ANDROID_LOG_WARN, "OpenFileFinder", ## args)
-#define ERR(args...) __android_log_print(ANDROID_LOG_ERROR, "OpenFileFinder", ## args)
-
-#undef DBG
-#if USE_DEBUG
-#define DBG(args...) __android_log_print(ANDROID_LOG_DEBUG, "OpenFileFinder" , ## args)
-#else
-#define DBG(args...)
-#endif
-
-namespace mozilla {
-namespace system {
-
-OpenFileFinder::OpenFileFinder(const nsACString& aPath,
- bool aCheckIsB2gOrDescendant /* = true */)
- : mPath(aPath),
- mProcDir(nullptr),
- mFdDir(nullptr),
- mPid(0),
- mCheckIsB2gOrDescendant(aCheckIsB2gOrDescendant)
-{
- // We assume that we're running in the parent process
- mMyPid = getpid();
-}
-
-OpenFileFinder::~OpenFileFinder()
-{
- Close();
-}
-
-bool
-OpenFileFinder::First(OpenFileFinder::Info* aInfo)
-{
- Close();
-
- mProcDir = opendir("/proc");
- if (!mProcDir) {
- return false;
- }
- mState = NEXT_PID;
- return Next(aInfo);
-}
-
-bool
-OpenFileFinder::Next(OpenFileFinder::Info* aInfo)
-{
- // NOTE: This function calls readdir and readlink, neither of which should
- // block since we're using the proc filesystem, which is a purely
- // kernel in-memory filesystem and doesn't depend on external driver
- // behaviour.
- while (mState != DONE) {
- switch (mState) {
- case NEXT_PID: {
- struct dirent *pidEntry;
- pidEntry = readdir(mProcDir);
- if (!pidEntry) {
- mState = DONE;
- break;
- }
- char *endPtr;
- mPid = strtol(pidEntry->d_name, &endPtr, 10);
- if (mPid == 0 || *endPtr != '\0') {
- // Not a +ve number - ignore
- continue;
- }
- // We've found a /proc/PID directory. Scan open file descriptors.
- if (mFdDir) {
- closedir(mFdDir);
- }
- nsPrintfCString fdDirPath("/proc/%d/fd", mPid);
- mFdDir = opendir(fdDirPath.get());
- if (!mFdDir) {
- continue;
- }
- mState = CHECK_FDS;
- }
- // Fall through
- case CHECK_FDS: {
- struct dirent *fdEntry;
- while((fdEntry = readdir(mFdDir))) {
- if (!strcmp(fdEntry->d_name, ".") ||
- !strcmp(fdEntry->d_name, "..")) {
- continue;
- }
- nsPrintfCString fdSymLink("/proc/%d/fd/%s", mPid, fdEntry->d_name);
- nsCString resolvedPath;
- if (ReadSymLink(fdSymLink, resolvedPath) && PathMatches(resolvedPath)) {
- // We found an open file contained within the directory tree passed
- // into the constructor.
- FillInfo(aInfo, resolvedPath);
- // If sCheckIsB2gOrDescendant is set false, the caller cares about
- // all processes which have open files. If sCheckIsB2gOrDescendant
- // is set false, we only care about the b2g proccess or its descendants.
- if (!mCheckIsB2gOrDescendant || aInfo->mIsB2gOrDescendant) {
- return true;
- }
- LOG("Ignore process(%d), not a b2g process or its descendant.",
- aInfo->mPid);
- }
- }
- // We've checked all of the files for this pid, move onto the next one.
- mState = NEXT_PID;
- continue;
- }
- case DONE:
- default:
- mState = DONE; // covers the default case
- break;
- }
- }
- return false;
-}
-
-void
-OpenFileFinder::Close()
-{
- if (mFdDir) {
- closedir(mFdDir);
- }
- if (mProcDir) {
- closedir(mProcDir);
- }
-}
-
-void
-OpenFileFinder::FillInfo(OpenFileFinder::Info* aInfo, const nsACString& aPath)
-{
- aInfo->mFileName = aPath;
- aInfo->mPid = mPid;
- nsPrintfCString exePath("/proc/%d/exe", mPid);
- ReadSymLink(exePath, aInfo->mExe);
- aInfo->mComm.Truncate();
- aInfo->mAppName.Truncate();
- nsPrintfCString statPath("/proc/%d/stat", mPid);
- nsCString statString;
- statString.SetLength(200);
- char *stat = statString.BeginWriting();
- if (!stat) {
- return;
- }
- ReadSysFile(statPath.get(), stat, statString.Length());
- // The stat line includes the comm field, surrounded by parenthesis.
- // However, the contents of the comm field itself is arbitrary and
- // and can include ')', so we search for the rightmost ) as being
- // the end of the comm field.
- char *closeParen = strrchr(stat, ')');
- if (!closeParen) {
- return;
- }
- char *openParen = strchr(stat, '(');
- if (!openParen) {
- return;
- }
- if (openParen >= closeParen) {
- return;
- }
- nsDependentCSubstring comm(&openParen[1], closeParen - openParen - 1);
- aInfo->mComm = comm;
- // There is a single character field after the comm and then
- // the parent pid (the field we're interested in).
- // ) X ppid
- // 01234
- int ppid = atoi(&closeParen[4]);
-
- if (mPid == mMyPid) {
- // This is chrome process
- aInfo->mIsB2gOrDescendant = true;
- DBG("Chrome process has open file(s)");
- return;
- }
- // For the rest (non-chrome process), we recursively check the ppid to know
- // it is a descendant of b2g or not. See bug 931456.
- while (ppid != mMyPid && ppid != 1) {
- DBG("Process(%d) is not forked from b2g(%d) or Init(1), keep looking",
- ppid, mMyPid);
- nsPrintfCString ppStatPath("/proc/%d/stat", ppid);
- ReadSysFile(ppStatPath.get(), stat, statString.Length());
- closeParen = strrchr(stat, ')');
- if (!closeParen) {
- return;
- }
- ppid = atoi(&closeParen[4]);
- }
- if (ppid == 1) {
- // This is a not a b2g process.
- DBG("Non-b2g process has open file(s)");
- aInfo->mIsB2gOrDescendant = false;
- return;
- }
- if (ppid == mMyPid) {
- // This is a descendant of b2g.
- DBG("Child process of chrome process has open file(s)");
- aInfo->mIsB2gOrDescendant = true;
- }
-
- // This looks like a content process. The comm field will be the
- // app name.
- aInfo->mAppName = aInfo->mComm;
-}
-
-bool
-OpenFileFinder::ReadSymLink(const nsACString& aSymLink, nsACString& aOutPath)
-{
- aOutPath.Truncate();
- const char *symLink = aSymLink.BeginReading();
-
- // Verify that we actually have a symlink.
- struct stat st;
- if (lstat(symLink, &st)) {
- return false;
- }
- if ((st.st_mode & S_IFMT) != S_IFLNK) {
- return false;
- }
-
- // Contrary to the documentation st.st_size doesn't seem to be a reliable
- // indication of the length when reading from /proc, so we use a fixed
- // size buffer instead.
-
- char resolvedSymLink[PATH_MAX];
- ssize_t pathLength = readlink(symLink, resolvedSymLink,
- sizeof(resolvedSymLink) - 1);
- if (pathLength <= 0) {
- return false;
- }
- resolvedSymLink[pathLength] = '\0';
- aOutPath.Assign(resolvedSymLink);
- return true;
-}
-
-} // system
-} // mozilla
diff --git a/dom/system/gonk/OpenFileFinder.h b/dom/system/gonk/OpenFileFinder.h
deleted file mode 100644
index 24517965a..000000000
--- a/dom/system/gonk/OpenFileFinder.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_openfilefinder_h__
-#define mozilla_system_openfilefinder_h__
-
-#include "nsString.h"
-
-#include <dirent.h>
-
-namespace mozilla {
-namespace system {
-
-class OpenFileFinder
-{
-public:
- enum State
- {
- NEXT_PID,
- CHECK_FDS,
- DONE
- };
- class Info
- {
- public:
- nsCString mFileName; // name of the the open file
- nsCString mAppName; // App which has the file open (if it's a b2g app)
- pid_t mPid; // pid of the process which has the file open
- nsCString mComm; // comm associated with pid
- nsCString mExe; // executable name associated with pid
- bool mIsB2gOrDescendant; // this is b2g/its descendant or not
- };
-
- OpenFileFinder(const nsACString& aPath, bool aCheckIsB2gOrDescendant = true);
- ~OpenFileFinder();
-
- bool First(Info* aInfo); // Return the first open file
- bool Next(Info* aInfo); // Return the next open file
- void Close();
-
-private:
-
- void FillInfo(Info *aInfo, const nsACString& aPath);
- bool ReadSymLink(const nsACString& aSymLink, nsACString& aOutPath);
- bool PathMatches(const nsACString& aPath)
- {
- return Substring(aPath, 0, mPath.Length()).Equals(mPath);
- }
-
- State mState; // Keeps track of what we're doing.
- nsCString mPath; // Only report files contained within this directory tree
- DIR* mProcDir; // Used for scanning /proc
- DIR* mFdDir; // Used for scanning /proc/PID/fd
- int mPid; // PID currently being processed
- pid_t mMyPid; // PID of parent process, we assume we're running on it.
- bool mCheckIsB2gOrDescendant; // Do we care about non-b2g process?
-};
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_nsvolume_h__
diff --git a/dom/system/gonk/RILSystemMessenger.jsm b/dom/system/gonk/RILSystemMessenger.jsm
deleted file mode 100644
index 81373458c..000000000
--- a/dom/system/gonk/RILSystemMessenger.jsm
+++ /dev/null
@@ -1,338 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "RIL", function () {
- let obj = {};
- Cu.import("resource://gre/modules/ril_consts.js", obj);
- return obj;
-});
-
-/**
- * RILSystemMessenger
- */
-this.RILSystemMessenger = function() {};
-RILSystemMessenger.prototype = {
-
- /**
- * Hook of Broadcast function
- *
- * @param aType
- * The type of the message to be sent.
- * @param aMessage
- * The message object to be broadcasted.
- */
- broadcastMessage: function(aType, aMessage) {
- // Function stub to be replaced by the owner of this messenger.
- },
-
- /**
- * Hook of the function to create MozStkCommand message.
- * @param aStkProactiveCmd
- * nsIStkProactiveCmd instance.
- *
- * @return a JS object which complies the dictionary of MozStkCommand defined
- * in MozStkCommandEvent.webidl
- */
- createCommandMessage: function(aStkProactiveCmd) {
- // Function stub to be replaced by the owner of this messenger.
- },
-
- /**
- * Wrapper to send "telephony-new-call" system message.
- */
- notifyNewCall: function() {
- this.broadcastMessage("telephony-new-call", {});
- },
-
- /**
- * Wrapper to send "telephony-call-ended" system message.
- */
- notifyCallEnded: function(aServiceId, aNumber, aCdmaWaitingNumber, aEmergency,
- aDuration, aOutgoing, aHangUpLocal) {
- let data = {
- serviceId: aServiceId,
- number: aNumber,
- emergency: aEmergency,
- duration: aDuration,
- direction: aOutgoing ? "outgoing" : "incoming",
- hangUpLocal: aHangUpLocal
- };
-
- if (aCdmaWaitingNumber != null) {
- data.secondNumber = aCdmaWaitingNumber;
- }
-
- this.broadcastMessage("telephony-call-ended", data);
- },
-
- _convertSmsMessageClass: function(aMessageClass) {
- return RIL.GECKO_SMS_MESSAGE_CLASSES[aMessageClass] || null;
- },
-
- _convertSmsDelivery: function(aDelivery) {
- return ["received", "sending", "sent", "error"][aDelivery] || null;
- },
-
- _convertSmsDeliveryStatus: function(aDeliveryStatus) {
- return [
- RIL.GECKO_SMS_DELIVERY_STATUS_NOT_APPLICABLE,
- RIL.GECKO_SMS_DELIVERY_STATUS_SUCCESS,
- RIL.GECKO_SMS_DELIVERY_STATUS_PENDING,
- RIL.GECKO_SMS_DELIVERY_STATUS_ERROR
- ][aDeliveryStatus] || null;
- },
-
- /**
- * Wrapper to send 'sms-received', 'sms-delivery-success', 'sms-sent',
- * 'sms-failed', 'sms-delivery-error' system message.
- */
- notifySms: function(aNotificationType, aId, aThreadId, aIccId, aDelivery,
- aDeliveryStatus, aSender, aReceiver, aBody, aMessageClass,
- aTimestamp, aSentTimestamp, aDeliveryTimestamp, aRead) {
- let msgType = [
- "sms-received",
- "sms-sent",
- "sms-delivery-success",
- "sms-failed",
- "sms-delivery-error"
- ][aNotificationType];
-
- if (!msgType) {
- throw new Error("Invalid Notification Type: " + aNotificationType);
- }
-
- this.broadcastMessage(msgType, {
- iccId: aIccId,
- type: "sms",
- id: aId,
- threadId: aThreadId,
- delivery: this._convertSmsDelivery(aDelivery),
- deliveryStatus: this._convertSmsDeliveryStatus(aDeliveryStatus),
- sender: aSender,
- receiver: aReceiver,
- body: aBody,
- messageClass: this._convertSmsMessageClass(aMessageClass),
- timestamp: aTimestamp,
- sentTimestamp: aSentTimestamp,
- deliveryTimestamp: aDeliveryTimestamp,
- read: aRead
- });
- },
-
- _convertCbGsmGeographicalScope: function(aGeographicalScope) {
- return RIL.CB_GSM_GEOGRAPHICAL_SCOPE_NAMES[aGeographicalScope] || null;
- },
-
- _convertCbMessageClass: function(aMessageClass) {
- return RIL.GECKO_SMS_MESSAGE_CLASSES[aMessageClass] || null;
- },
-
- _convertCbEtwsWarningType: function(aWarningType) {
- return RIL.CB_ETWS_WARNING_TYPE_NAMES[aWarningType] || null;
- },
-
- /**
- * Wrapper to send 'cellbroadcast-received' system message.
- */
- notifyCbMessageReceived: function(aServiceId, aGsmGeographicalScope, aMessageCode,
- aMessageId, aLanguage, aBody, aMessageClass,
- aTimestamp, aCdmaServiceCategory, aHasEtwsInfo,
- aEtwsWarningType, aEtwsEmergencyUserAlert, aEtwsPopup) {
- // Align the same layout to MozCellBroadcastMessage
- let data = {
- serviceId: aServiceId,
- gsmGeographicalScope: this._convertCbGsmGeographicalScope(aGsmGeographicalScope),
- messageCode: aMessageCode,
- messageId: aMessageId,
- language: aLanguage,
- body: aBody,
- messageClass: this._convertCbMessageClass(aMessageClass),
- timestamp: aTimestamp,
- cdmaServiceCategory: null,
- etws: null
- };
-
- if (aHasEtwsInfo) {
- data.etws = {
- warningType: this._convertCbEtwsWarningType(aEtwsWarningType),
- emergencyUserAlert: aEtwsEmergencyUserAlert,
- popup: aEtwsPopup
- };
- }
-
- if (aCdmaServiceCategory !=
- Ci.nsICellBroadcastService.CDMA_SERVICE_CATEGORY_INVALID) {
- data.cdmaServiceCategory = aCdmaServiceCategory;
- }
-
- this.broadcastMessage("cellbroadcast-received", data);
- },
-
- /**
- * Wrapper to send 'ussd-received' system message.
- */
- notifyUssdReceived: function(aServiceId, aMessage, aSessionEnded) {
- this.broadcastMessage("ussd-received", {
- serviceId: aServiceId,
- message: aMessage,
- sessionEnded: aSessionEnded
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with Display Info.
- */
- notifyCdmaInfoRecDisplay: function(aServiceId, aDisplay) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- display: aDisplay
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with Called Party
- * Number Info.
- */
- notifyCdmaInfoRecCalledPartyNumber: function(aServiceId, aType, aPlan,
- aNumber, aPi, aSi) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- calledNumber: {
- type: aType,
- plan: aPlan,
- number: aNumber,
- pi: aPi,
- si: aSi
- }
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with Calling Party
- * Number Info.
- */
- notifyCdmaInfoRecCallingPartyNumber: function(aServiceId, aType, aPlan,
- aNumber, aPi, aSi) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- callingNumber: {
- type: aType,
- plan: aPlan,
- number: aNumber,
- pi: aPi,
- si: aSi
- }
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with Connected Party
- * Number Info.
- */
- notifyCdmaInfoRecConnectedPartyNumber: function(aServiceId, aType, aPlan,
- aNumber, aPi, aSi) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- connectedNumber: {
- type: aType,
- plan: aPlan,
- number: aNumber,
- pi: aPi,
- si: aSi
- }
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with Signal Info.
- */
- notifyCdmaInfoRecSignal: function(aServiceId, aType, aAlertPitch, aSignal) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- signal: {
- type: aType,
- alertPitch: aAlertPitch,
- signal: aSignal
- }
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with Redirecting
- * Number Info.
- */
- notifyCdmaInfoRecRedirectingNumber: function(aServiceId, aType, aPlan,
- aNumber, aPi, aSi, aReason) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- redirect: {
- type: aType,
- plan: aPlan,
- number: aNumber,
- pi: aPi,
- si: aSi,
- reason: aReason
- }
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with Line Control Info.
- */
- notifyCdmaInfoRecLineControl: function(aServiceId, aPolarityIncluded,
- aToggle, aReverse, aPowerDenial) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- lineControl: {
- polarityIncluded: aPolarityIncluded,
- toggle: aToggle,
- reverse: aReverse,
- powerDenial: aPowerDenial
- }
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with CLIR Info.
- */
- notifyCdmaInfoRecClir: function(aServiceId, aCause) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- clirCause: aCause
- });
- },
-
- /**
- * Wrapper to send 'cdma-info-rec-received' system message with Audio Control Info.
- */
- notifyCdmaInfoRecAudioControl: function(aServiceId, aUpLink, aDownLink) {
- this.broadcastMessage("cdma-info-rec-received", {
- clientId: aServiceId,
- audioControl: {
- upLink: aUpLink,
- downLink: aDownLink
- }
- });
- },
-
- /**
- * Wrapper to send 'icc-stkcommand' system message with Audio Control Info.
- */
- notifyStkProactiveCommand: function(aIccId, aCommand) {
- this.broadcastMessage("icc-stkcommand", {
- iccId: aIccId,
- command: this.createCommandMessage(aCommand)
- });
- }
-};
-
-this.EXPORTED_SYMBOLS = [
- 'RILSystemMessenger'
-];
diff --git a/dom/system/gonk/RILSystemMessengerHelper.js b/dom/system/gonk/RILSystemMessengerHelper.js
deleted file mode 100644
index 6ef263b66..000000000
--- a/dom/system/gonk/RILSystemMessengerHelper.js
+++ /dev/null
@@ -1,169 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-var RSM = {};
-Cu.import("resource://gre/modules/RILSystemMessenger.jsm", RSM);
-
-const RILSYSTEMMESSENGERHELPER_CONTRACTID =
- "@mozilla.org/ril/system-messenger-helper;1";
-const RILSYSTEMMESSENGERHELPER_CID =
- Components.ID("{19d9a4ea-580d-11e4-8f6c-37ababfaaea9}");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSystemMessenger",
- "@mozilla.org/system-message-internal;1",
- "nsISystemMessagesInternal");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gStkCmdFactory",
- "@mozilla.org/icc/stkcmdfactory;1",
- "nsIStkCmdFactory");
-
-var DEBUG = false;
-function debug(s) {
- dump("-@- RILSystemMessenger: " + s + "\n");
-};
-
-// Read debug setting from pref.
-try {
- let debugPref = Services.prefs.getBoolPref("ril.debugging.enabled");
- DEBUG = DEBUG || debugPref;
-} catch (e) {}
-
-/**
- * RILSystemMessengerHelper
- */
-function RILSystemMessengerHelper() {
- this.messenger = new RSM.RILSystemMessenger();
- this.messenger.broadcastMessage = (aType, aMessage) => {
- if (DEBUG) {
- debug("broadcastMessage: aType: " + aType +
- ", aMessage: "+ JSON.stringify(aMessage));
- }
-
- gSystemMessenger.broadcastMessage(aType, aMessage);
- };
-
- this.messenger.createCommandMessage = (aStkProactiveCmd) => {
- return gStkCmdFactory.createCommandMessage(aStkProactiveCmd);
- };
-}
-RILSystemMessengerHelper.prototype = {
-
- classID: RILSYSTEMMESSENGERHELPER_CID,
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITelephonyMessenger,
- Ci.nsISmsMessenger,
- Ci.nsICellbroadcastMessenger,
- Ci.nsIMobileConnectionMessenger,
- Ci.nsIIccMessenger]),
-
- /**
- * RILSystemMessenger instance.
- */
- messenger: null,
-
- /**
- * nsITelephonyMessenger API
- */
- notifyNewCall: function() {
- this.messenger.notifyNewCall();
- },
-
- notifyCallEnded: function(aServiceId, aNumber, aCdmaWaitingNumber, aEmergency,
- aDuration, aOutgoing, aHangUpLocal) {
- this.messenger.notifyCallEnded(aServiceId, aNumber, aCdmaWaitingNumber, aEmergency,
- aDuration, aOutgoing, aHangUpLocal);
- },
-
- notifyUssdReceived: function(aServiceId, aMessage, aSessionEnded) {
- this.messenger.notifyUssdReceived(aServiceId, aMessage, aSessionEnded);
- },
-
- /**
- * nsISmsMessenger API
- */
- notifySms: function(aNotificationType, aId, aThreadId, aIccId, aDelivery,
- aDeliveryStatus, aSender, aReceiver, aBody, aMessageClass,
- aTimestamp, aSentTimestamp, aDeliveryTimestamp, aRead) {
- this.messenger.notifySms(aNotificationType, aId, aThreadId, aIccId, aDelivery,
- aDeliveryStatus, aSender, aReceiver, aBody, aMessageClass,
- aTimestamp, aSentTimestamp, aDeliveryTimestamp, aRead);
- },
-
- /**
- * nsICellbroadcastMessenger API
- */
- notifyCbMessageReceived: function(aServiceId, aGsmGeographicalScope, aMessageCode,
- aMessageId, aLanguage, aBody, aMessageClass,
- aTimestamp, aCdmaServiceCategory, aHasEtwsInfo,
- aEtwsWarningType, aEtwsEmergencyUserAlert, aEtwsPopup) {
- this.messenger.notifyCbMessageReceived(aServiceId, aGsmGeographicalScope, aMessageCode,
- aMessageId, aLanguage, aBody, aMessageClass,
- aTimestamp, aCdmaServiceCategory, aHasEtwsInfo,
- aEtwsWarningType, aEtwsEmergencyUserAlert, aEtwsPopup);
- },
-
- /**
- * nsIMobileConnectionMessenger API
- */
- notifyCdmaInfoRecDisplay: function(aServiceId, aDisplay) {
- this.messenger.notifyCdmaInfoRecDisplay(aServiceId, aDisplay);
- },
-
- notifyCdmaInfoRecCalledPartyNumber: function(aServiceId, aType, aPlan,
- aNumber, aPi, aSi) {
- this.messenger.notifyCdmaInfoRecCalledPartyNumber(aServiceId, aType, aPlan,
- aNumber, aPi, aSi);
- },
-
- notifyCdmaInfoRecCallingPartyNumber: function(aServiceId, aType, aPlan,
- aNumber, aPi, aSi) {
- this.messenger.notifyCdmaInfoRecCallingPartyNumber(aServiceId, aType, aPlan,
- aNumber, aPi, aSi);
- },
-
- notifyCdmaInfoRecConnectedPartyNumber: function(aServiceId, aType, aPlan,
- aNumber, aPi, aSi) {
- this.messenger.notifyCdmaInfoRecConnectedPartyNumber(aServiceId, aType, aPlan,
- aNumber, aPi, aSi);
- },
-
- notifyCdmaInfoRecSignal: function(aServiceId, aType, aAlertPitch, aSignal) {
- this.messenger.notifyCdmaInfoRecSignal(aServiceId, aType, aAlertPitch, aSignal);
- },
-
- notifyCdmaInfoRecRedirectingNumber: function(aServiceId, aType, aPlan,
- aNumber, aPi, aSi, aReason) {
- this.messenger.notifyCdmaInfoRecRedirectingNumber(aServiceId, aType, aPlan,
- aNumber, aPi, aSi, aReason);
- },
-
- notifyCdmaInfoRecLineControl: function(aServiceId, aPolarityIncluded,
- aToggle, aReverse, aPowerDenial) {
- this.messenger.notifyCdmaInfoRecLineControl(aServiceId, aPolarityIncluded,
- aToggle, aReverse, aPowerDenial);
- },
-
- notifyCdmaInfoRecClir: function(aServiceId, aCause) {
- this.messenger.notifyCdmaInfoRecClir(aServiceId, aCause);
- },
-
- notifyCdmaInfoRecAudioControl: function(aServiceId, aUpLink, aDownLink) {
- this.messenger.notifyCdmaInfoRecAudioControl(aServiceId, aUpLink, aDownLink);
- },
-
- /**
- * nsIIccMessenger API
- */
- notifyStkProactiveCommand: function(aIccId, aCommand) {
- this.messenger.notifyStkProactiveCommand(aIccId, aCommand);
- }
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([RILSystemMessengerHelper]);
diff --git a/dom/system/gonk/RILSystemMessengerHelper.manifest b/dom/system/gonk/RILSystemMessengerHelper.manifest
deleted file mode 100644
index 7d1943702..000000000
--- a/dom/system/gonk/RILSystemMessengerHelper.manifest
+++ /dev/null
@@ -1,6 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-component {19d9a4ea-580d-11e4-8f6c-37ababfaaea9} RILSystemMessengerHelper.js
-contract @mozilla.org/ril/system-messenger-helper;1 {19d9a4ea-580d-11e4-8f6c-37ababfaaea9} \ No newline at end of file
diff --git a/dom/system/gonk/RadioInterfaceLayer.js b/dom/system/gonk/RadioInterfaceLayer.js
deleted file mode 100644
index f5885db5d..000000000
--- a/dom/system/gonk/RadioInterfaceLayer.js
+++ /dev/null
@@ -1,1324 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/Sntp.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/FileUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "RIL", function () {
- let obj = {};
- Cu.import("resource://gre/modules/ril_consts.js", obj);
- return obj;
-});
-
-// Ril quirk to always turn the radio off for the client without SIM card
-// except hw default client.
-var RILQUIRKS_RADIO_OFF_WO_CARD =
- libcutils.property_get("ro.moz.ril.radio_off_wo_card", "false") == "true";
-
-const RADIOINTERFACELAYER_CID =
- Components.ID("{2d831c8d-6017-435b-a80c-e5d422810cea}");
-const RADIOINTERFACE_CID =
- Components.ID("{6a7c91f0-a2b3-4193-8562-8969296c0b54}");
-
-const NS_XPCOM_SHUTDOWN_OBSERVER_ID = "xpcom-shutdown";
-const kNetworkConnStateChangedTopic = "network-connection-state-changed";
-const kMozSettingsChangedObserverTopic = "mozsettings-changed";
-const kSysMsgListenerReadyObserverTopic = "system-message-listener-ready";
-const kSysClockChangeObserverTopic = "system-clock-change";
-const kScreenStateChangedTopic = "screen-state-changed";
-
-const kSettingsClockAutoUpdateEnabled = "time.clock.automatic-update.enabled";
-const kSettingsClockAutoUpdateAvailable = "time.clock.automatic-update.available";
-const kSettingsTimezoneAutoUpdateEnabled = "time.timezone.automatic-update.enabled";
-const kSettingsTimezoneAutoUpdateAvailable = "time.timezone.automatic-update.available";
-
-const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID = "nsPref:changed";
-
-const kPrefRilNumRadioInterfaces = "ril.numRadioInterfaces";
-const kPrefRilDebuggingEnabled = "ril.debugging.enabled";
-
-const RADIO_POWER_OFF_TIMEOUT = 30000;
-const HW_DEFAULT_CLIENT_ID = 0;
-
-const NETWORK_TYPE_WIFI = Ci.nsINetworkInfo.NETWORK_TYPE_WIFI;
-const NETWORK_TYPE_MOBILE = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE;
-
-// set to true in ril_consts.js to see debug messages
-var DEBUG = RIL.DEBUG_RIL;
-
-function updateDebugFlag() {
- // Read debug setting from pref
- let debugPref;
- try {
- debugPref = Services.prefs.getBoolPref(kPrefRilDebuggingEnabled);
- } catch (e) {
- debugPref = false;
- }
- DEBUG = RIL.DEBUG_RIL || debugPref;
-}
-updateDebugFlag();
-
-function debug(s) {
- dump("-*- RadioInterfaceLayer: " + s + "\n");
-}
-
-XPCOMUtils.defineLazyServiceGetter(this, "gIccService",
- "@mozilla.org/icc/gonkiccservice;1",
- "nsIGonkIccService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileMessageService",
- "@mozilla.org/mobilemessage/mobilemessageservice;1",
- "nsIMobileMessageService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSmsService",
- "@mozilla.org/sms/gonksmsservice;1",
- "nsIGonkSmsService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "ppmm",
- "@mozilla.org/parentprocessmessagemanager;1",
- "nsIMessageBroadcaster");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
- "@mozilla.org/settingsService;1",
- "nsISettingsService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
- "@mozilla.org/network/manager;1",
- "nsINetworkManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gTimeService",
- "@mozilla.org/time/timeservice;1",
- "nsITimeService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSystemWorkerManager",
- "@mozilla.org/telephony/system-worker-manager;1",
- "nsISystemWorkerManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gTelephonyService",
- "@mozilla.org/telephony/telephonyservice;1",
- "nsIGonkTelephonyService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileConnectionService",
- "@mozilla.org/mobileconnection/mobileconnectionservice;1",
- "nsIGonkMobileConnectionService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gCellBroadcastService",
- "@mozilla.org/cellbroadcast/cellbroadcastservice;1",
- "nsIGonkCellBroadcastService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gDataCallManager",
- "@mozilla.org/datacall/manager;1",
- "nsIDataCallManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gDataCallInterfaceService",
- "@mozilla.org/datacall/interfaceservice;1",
- "nsIGonkDataCallInterfaceService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gStkCmdFactory",
- "@mozilla.org/icc/stkcmdfactory;1",
- "nsIStkCmdFactory");
-
-XPCOMUtils.defineLazyGetter(this, "gRadioEnabledController", function() {
- let _ril = null;
- let _pendingMessages = []; // For queueing "setRadioEnabled" message.
- let _isProcessingPending = false;
- let _timer = null;
- let _request = null;
- let _deactivatingDeferred = {};
- let _initializedCardState = {};
- let _allCardStateInitialized = !RILQUIRKS_RADIO_OFF_WO_CARD;
-
- return {
- init: function(ril) {
- _ril = ril;
- },
-
- receiveCardState: function(clientId) {
- if (_allCardStateInitialized) {
- return;
- }
-
- if (DEBUG) debug("RadioControl: receive cardState from " + clientId);
- _initializedCardState[clientId] = true;
- if (Object.keys(_initializedCardState).length == _ril.numRadioInterfaces) {
- _allCardStateInitialized = true;
- this._startProcessingPending();
- }
- },
-
- setRadioEnabled: function(clientId, data, callback) {
- if (DEBUG) debug("setRadioEnabled: " + clientId + ": " + JSON.stringify(data));
- let message = {
- clientId: clientId,
- data: data,
- callback: callback
- };
- _pendingMessages.push(message);
- this._startProcessingPending();
- },
-
- notifyRadioStateChanged: function(clientId, radioState) {
- gMobileConnectionService.notifyRadioStateChanged(clientId, radioState);
- },
-
- _startProcessingPending: function() {
- if (!_isProcessingPending) {
- if (DEBUG) debug("RadioControl: start dequeue");
- _isProcessingPending = true;
- this._processNextMessage();
- }
- },
-
- _processNextMessage: function() {
- if (_pendingMessages.length === 0 || !_allCardStateInitialized) {
- if (DEBUG) debug("RadioControl: stop dequeue");
- _isProcessingPending = false;
- return;
- }
-
- let msg = _pendingMessages.shift();
- this._handleMessage(msg);
- },
-
- _getNumCards: function() {
- let numCards = 0;
- for (let i = 0, N = _ril.numRadioInterfaces; i < N; ++i) {
- if (_ril.getRadioInterface(i).isCardPresent()) {
- numCards++;
- }
- }
- return numCards;
- },
-
- _isRadioAbleToEnableAtClient: function(clientId, numCards) {
- if (!RILQUIRKS_RADIO_OFF_WO_CARD) {
- return true;
- }
-
- // We could only turn on the radio for clientId if
- // 1. a SIM card is presented or
- // 2. it is the default clientId and there is no any SIM card at any client.
-
- if (_ril.getRadioInterface(clientId).isCardPresent()) {
- return true;
- }
-
- numCards = numCards == null ? this._getNumCards() : numCards;
- if (clientId === HW_DEFAULT_CLIENT_ID && numCards === 0) {
- return true;
- }
-
- return false;
- },
-
- _handleMessage: function(message) {
- if (DEBUG) debug("RadioControl: handleMessage: " + JSON.stringify(message));
- let clientId = message.clientId || 0;
- let connection =
- gMobileConnectionService.getItemByServiceId(clientId);
- let radioState = connection && connection.radioState;
-
- if (message.data.enabled) {
- if (this._isRadioAbleToEnableAtClient(clientId)) {
- this._setRadioEnabledInternal(message);
- } else {
- // Not really do it but respond success.
- message.callback(message.data);
- }
-
- this._processNextMessage();
- } else {
- _request = this._setRadioEnabledInternal.bind(this, message);
-
- // In 2G network, modem takes 35+ seconds to process deactivate data
- // call request if device has active voice call (please see bug 964974
- // for more details). Therefore we should hangup all active voice calls
- // first. And considering some DSDS architecture, toggling one radio may
- // toggle both, so we send hangUpAll to all clients.
- let hangUpCallback = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITelephonyCallback]),
- notifySuccess: function() {},
- notifyError: function() {}
- };
-
- gTelephonyService.enumerateCalls({
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITelephonyListener]),
- enumerateCallState: function(aInfo) {
- gTelephonyService.hangUpCall(aInfo.clientId, aInfo.callIndex,
- hangUpCallback);
- },
- enumerateCallStateComplete: function() {}
- });
-
- // In some DSDS architecture with only one modem, toggling one radio may
- // toggle both. Therefore, for safely turning off, we should first
- // explicitly deactivate all data calls from all clients.
- this._deactivateDataCalls().then(() => {
- if (DEBUG) debug("RadioControl: deactivation done");
- this._executeRequest();
- });
-
- this._createTimer();
- }
- },
-
- _setRadioEnabledInternal: function(message) {
- let clientId = message.clientId || 0;
- let enabled = message.data.enabled || false;
- let radioInterface = _ril.getRadioInterface(clientId);
-
- radioInterface.workerMessenger.send("setRadioEnabled", message.data,
- (function(response) {
- if (response.errorMsg) {
- // If request fails, set current radio state to unknown, since we will
- // handle it in |mobileConnectionService|.
- this.notifyRadioStateChanged(clientId,
- Ci.nsIMobileConnection.MOBILE_RADIO_STATE_UNKNOWN);
- }
- return message.callback(response);
- }).bind(this));
- },
-
- _deactivateDataCalls: function() {
- if (DEBUG) debug("RadioControl: deactivating data calls...");
- _deactivatingDeferred = {};
-
- let promise = Promise.resolve();
- for (let i = 0, N = _ril.numRadioInterfaces; i < N; ++i) {
- promise = promise.then(this._deactivateDataCallsForClient(i));
- }
-
- return promise;
- },
-
- _deactivateDataCallsForClient: function(clientId) {
- return function() {
- let deferred = _deactivatingDeferred[clientId] = Promise.defer();
- let dataCallHandler = gDataCallManager.getDataCallHandler(clientId);
-
- dataCallHandler.deactivateDataCalls(function() {
- deferred.resolve();
- });
-
- return deferred.promise;
- };
- },
-
- _createTimer: function() {
- if (!_timer) {
- _timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- }
- _timer.initWithCallback(this._executeRequest.bind(this),
- RADIO_POWER_OFF_TIMEOUT,
- Ci.nsITimer.TYPE_ONE_SHOT);
- },
-
- _cancelTimer: function() {
- if (_timer) {
- _timer.cancel();
- }
- },
-
- _executeRequest: function() {
- if (typeof _request === "function") {
- if (DEBUG) debug("RadioControl: executeRequest");
- this._cancelTimer();
- _request();
- _request = null;
- }
- this._processNextMessage();
- },
- };
-});
-
-// Initialize shared preference "ril.numRadioInterfaces" according to system
-// property.
-try {
- Services.prefs.setIntPref(kPrefRilNumRadioInterfaces, (function() {
- // When Gonk property "ro.moz.ril.numclients" is not set, return 1; if
- // explicitly set to any number larger-equal than 0, return num; else, return
- // 1 for compatibility.
- try {
- let numString = libcutils.property_get("ro.moz.ril.numclients", "1");
- let num = parseInt(numString, 10);
- if (num >= 0) {
- return num;
- }
- } catch (e) {}
-
- return 1;
- })());
-} catch (e) {}
-
-function DataCall(aAttributes) {
- for (let key in aAttributes) {
- if (key === "pdpType") {
- // Convert pdp type into constant int value.
- this[key] = RIL.RIL_DATACALL_PDP_TYPES.indexOf(aAttributes[key]);
- continue;
- }
-
- this[key] = aAttributes[key];
- }
-}
-DataCall.prototype = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDataCall]),
-
- failCause: Ci.nsIDataCallInterface.DATACALL_FAIL_NONE,
- suggestedRetryTime: -1,
- cid: -1,
- active: -1,
- pdpType: -1,
- ifname: null,
- addreses: null,
- dnses: null,
- gateways: null,
- pcscf: null,
- mtu: -1
-};
-
-function RadioInterfaceLayer() {
- let workerMessenger = new WorkerMessenger();
- workerMessenger.init();
- this.setWorkerDebugFlag = workerMessenger.setDebugFlag.bind(workerMessenger);
-
- let numIfaces = this.numRadioInterfaces;
- if (DEBUG) debug(numIfaces + " interfaces");
- this.radioInterfaces = [];
- for (let clientId = 0; clientId < numIfaces; clientId++) {
- this.radioInterfaces.push(new RadioInterface(clientId, workerMessenger));
- }
-
- Services.obs.addObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
- Services.prefs.addObserver(kPrefRilDebuggingEnabled, this, false);
-
- gRadioEnabledController.init(this);
-}
-RadioInterfaceLayer.prototype = {
-
- classID: RADIOINTERFACELAYER_CID,
- classInfo: XPCOMUtils.generateCI({classID: RADIOINTERFACELAYER_CID,
- classDescription: "RadioInterfaceLayer",
- interfaces: [Ci.nsIRadioInterfaceLayer]}),
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIRadioInterfaceLayer,
- Ci.nsIObserver]),
-
- /**
- * nsIObserver interface methods.
- */
-
- observe: function(subject, topic, data) {
- switch (topic) {
- case NS_XPCOM_SHUTDOWN_OBSERVER_ID:
- for (let radioInterface of this.radioInterfaces) {
- radioInterface.shutdown();
- }
- this.radioInterfaces = null;
- Services.obs.removeObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
- break;
-
- case NS_PREFBRANCH_PREFCHANGE_TOPIC_ID:
- if (data === kPrefRilDebuggingEnabled) {
- updateDebugFlag();
- this.setWorkerDebugFlag(DEBUG);
- }
- break;
- }
- },
-
- /**
- * nsIRadioInterfaceLayer interface methods.
- */
-
- getRadioInterface: function(clientId) {
- return this.radioInterfaces[clientId];
- },
-
- setMicrophoneMuted: function(muted) {
- for (let clientId = 0; clientId < this.numRadioInterfaces; clientId++) {
- let radioInterface = this.radioInterfaces[clientId];
- radioInterface.workerMessenger.send("setMute", { muted: muted });
- }
- }
-};
-
-XPCOMUtils.defineLazyGetter(RadioInterfaceLayer.prototype,
- "numRadioInterfaces", function() {
- try {
- return Services.prefs.getIntPref(kPrefRilNumRadioInterfaces);
- } catch(e) {}
-
- return 1;
-});
-
-function WorkerMessenger() {
- // Initial owning attributes.
- this.radioInterfaces = [];
- this.tokenCallbackMap = {};
-
- this.worker = new ChromeWorker("resource://gre/modules/ril_worker.js");
- this.worker.onerror = this.onerror.bind(this);
- this.worker.onmessage = this.onmessage.bind(this);
-}
-WorkerMessenger.prototype = {
- radioInterfaces: null,
- worker: null,
-
- // This gets incremented each time we send out a message.
- token: 1,
-
- // Maps tokens we send out with messages to the message callback.
- tokenCallbackMap: null,
-
- init: function() {
- let options = {
- debug: DEBUG,
- quirks: {
- callstateExtraUint32:
- libcutils.property_get("ro.moz.ril.callstate_extra_int", "false") === "true",
- requestUseDialEmergencyCall:
- libcutils.property_get("ro.moz.ril.dial_emergency_call", "false") === "true",
- simAppStateExtraFields:
- libcutils.property_get("ro.moz.ril.simstate_extra_field", "false") === "true",
- extraUint2ndCall:
- libcutils.property_get("ro.moz.ril.extra_int_2nd_call", "false") === "true",
- haveQueryIccLockRetryCount:
- libcutils.property_get("ro.moz.ril.query_icc_count", "false") === "true",
- sendStkProfileDownload:
- libcutils.property_get("ro.moz.ril.send_stk_profile_dl", "false") === "true",
- smscAddressFormat:
- libcutils.property_get("ro.moz.ril.smsc_address_format", "text"),
- dataRegistrationOnDemand:
- libcutils.property_get("ro.moz.ril.data_reg_on_demand", "false") === "true",
- subscriptionControl:
- libcutils.property_get("ro.moz.ril.subscription_control", "false") === "true",
- signalExtraInt:
- libcutils.property_get("ro.moz.ril.signal_extra_int", "false") === "true",
- availableNetworkExtraStr:
- libcutils.property_get("ro.moz.ril.avlbl_nw_extra_str", "false") === "true",
- }
- };
-
- this.send(null, "setInitialOptions", options);
- },
-
- setDebugFlag: function(aDebug) {
- let options = { debug: aDebug };
- this.send(null, "setDebugFlag", options);
- },
-
- debug: function(aClientId, aMessage) {
- // We use the same debug subject with RadioInterface's here.
- dump("-*- RadioInterface[" + aClientId + "]: " + aMessage + "\n");
- },
-
- onerror: function(event) {
- if (DEBUG) {
- this.debug("X", "Got an error: " + event.filename + ":" +
- event.lineno + ": " + event.message + "\n");
- }
- event.preventDefault();
- },
-
- /**
- * Process the incoming message from the RIL worker.
- */
- onmessage: function(event) {
- let message = event.data;
- let clientId = message.rilMessageClientId;
- if (clientId === null) {
- return;
- }
-
- if (DEBUG) {
- this.debug(clientId, "Received message from worker: " + JSON.stringify(message));
- }
-
- let token = message.rilMessageToken;
- if (token == null) {
- // That's an unsolicited message. Pass to RadioInterface directly.
- let radioInterface = this.radioInterfaces[clientId];
- radioInterface.handleUnsolicitedWorkerMessage(message);
- return;
- }
-
- let callback = this.tokenCallbackMap[message.rilMessageToken];
- if (!callback) {
- if (DEBUG) this.debug(clientId, "Ignore orphan token: " + message.rilMessageToken);
- return;
- }
-
- let keep = false;
- try {
- keep = callback(message);
- } catch(e) {
- if (DEBUG) this.debug(clientId, "callback throws an exception: " + e);
- }
-
- if (!keep) {
- delete this.tokenCallbackMap[message.rilMessageToken];
- }
- },
-
- registerClient: function(aClientId, aRadioInterface) {
- if (DEBUG) this.debug(aClientId, "Starting RIL Worker");
-
- // Keep a reference so that we can dispatch unsolicited messages to it.
- this.radioInterfaces[aClientId] = aRadioInterface;
-
- this.send(null, "registerClient", { clientId: aClientId });
- gSystemWorkerManager.registerRilWorker(aClientId, this.worker);
- },
-
- /**
- * Send arbitrary message to worker.
- *
- * @param rilMessageType
- * A text message type.
- * @param message [optional]
- * An optional message object to send.
- * @param callback [optional]
- * An optional callback function which is called when worker replies
- * with an message containing a "rilMessageToken" attribute of the
- * same value we passed. This callback function accepts only one
- * parameter -- the reply from worker. It also returns a boolean
- * value true to keep current token-callback mapping and wait for
- * another worker reply, or false to remove the mapping.
- */
- send: function(clientId, rilMessageType, message, callback) {
- message = message || {};
-
- message.rilMessageClientId = clientId;
- message.rilMessageToken = this.token;
- this.token++;
-
- if (callback) {
- // Only create the map if callback is provided. For sending a request
- // and intentionally leaving the callback undefined, that reply will
- // be dropped in |this.onmessage| because of that orphan token.
- //
- // For sending a request that never replied at all, we're fine with this
- // because no callback shall be passed and we leave nothing to be cleaned
- // up later.
- this.tokenCallbackMap[message.rilMessageToken] = callback;
- }
-
- message.rilMessageType = rilMessageType;
- this.worker.postMessage(message);
- }
-};
-
-function RadioInterface(aClientId, aWorkerMessenger) {
- this.clientId = aClientId;
- this.workerMessenger = {
- send: aWorkerMessenger.send.bind(aWorkerMessenger, aClientId)
- };
- aWorkerMessenger.registerClient(aClientId, this);
-
- this.operatorInfo = {};
-
- let lock = gSettingsService.createLock();
-
- // Read the "time.clock.automatic-update.enabled" setting to see if
- // we need to adjust the system clock time by NITZ or SNTP.
- lock.get(kSettingsClockAutoUpdateEnabled, this);
-
- // Read the "time.timezone.automatic-update.enabled" setting to see if
- // we need to adjust the system timezone by NITZ.
- lock.get(kSettingsTimezoneAutoUpdateEnabled, this);
-
- // Set "time.clock.automatic-update.available" to false when starting up.
- this.setClockAutoUpdateAvailable(false);
-
- // Set "time.timezone.automatic-update.available" to false when starting up.
- this.setTimezoneAutoUpdateAvailable(false);
-
- Services.obs.addObserver(this, kMozSettingsChangedObserverTopic, false);
- Services.obs.addObserver(this, kSysClockChangeObserverTopic, false);
- Services.obs.addObserver(this, kScreenStateChangedTopic, false);
-
- Services.obs.addObserver(this, kNetworkConnStateChangedTopic, false);
-
- this._sntp = new Sntp(this.setClockBySntp.bind(this),
- Services.prefs.getIntPref("network.sntp.maxRetryCount"),
- Services.prefs.getIntPref("network.sntp.refreshPeriod"),
- Services.prefs.getIntPref("network.sntp.timeout"),
- Services.prefs.getCharPref("network.sntp.pools").split(";"),
- Services.prefs.getIntPref("network.sntp.port"));
-}
-
-RadioInterface.prototype = {
-
- classID: RADIOINTERFACE_CID,
- classInfo: XPCOMUtils.generateCI({classID: RADIOINTERFACE_CID,
- classDescription: "RadioInterface",
- interfaces: [Ci.nsIRadioInterface]}),
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIRadioInterface,
- Ci.nsIObserver,
- Ci.nsISettingsServiceCallback]),
-
- // A private wrapped WorkerMessenger instance.
- workerMessenger: null,
-
- debug: function(s) {
- dump("-*- RadioInterface[" + this.clientId + "]: " + s + "\n");
- },
-
- shutdown: function() {
- Services.obs.removeObserver(this, kMozSettingsChangedObserverTopic);
- Services.obs.removeObserver(this, kSysClockChangeObserverTopic);
- Services.obs.removeObserver(this, kScreenStateChangedTopic);
- Services.obs.removeObserver(this, kNetworkConnStateChangedTopic);
- },
-
- isCardPresent: function() {
- let icc = gIccService.getIccByServiceId(this.clientId);
- let cardState = icc ? icc.cardState : Ci.nsIIcc.CARD_STATE_UNKNOWN;
- return cardState !== Ci.nsIIcc.CARD_STATE_UNDETECTED &&
- cardState !== Ci.nsIIcc.CARD_STATE_UNKNOWN;
- },
-
- handleUnsolicitedWorkerMessage: function(message) {
- switch (message.rilMessageType) {
- case "callRing":
- gTelephonyService.notifyCallRing();
- break;
- case "currentCalls":
- gTelephonyService.notifyCurrentCalls(this.clientId, message.calls);
- break;
- case "cdmaCallWaiting":
- gTelephonyService.notifyCdmaCallWaiting(this.clientId,
- message.waitingCall);
- break;
- case "suppSvcNotification":
- gTelephonyService.notifySupplementaryService(this.clientId,
- message.number,
- message.notification);
- break;
- case "ussdreceived":
- gTelephonyService.notifyUssdReceived(this.clientId, message.message,
- message.sessionEnded);
- break;
- case "datacalllistchanged":
- let dataCalls = message.datacalls.map(dataCall => new DataCall(dataCall));
- gDataCallInterfaceService.notifyDataCallListChanged(this.clientId,
- dataCalls.length,
- dataCalls);
- break;
- case "emergencyCbModeChange":
- gMobileConnectionService.notifyEmergencyCallbackModeChanged(this.clientId,
- message.active,
- message.timeoutMs);
- break;
- case "networkinfochanged":
- gMobileConnectionService.notifyNetworkInfoChanged(this.clientId,
- message);
- break;
- case "networkselectionmodechange":
- gMobileConnectionService.notifyNetworkSelectModeChanged(this.clientId,
- message.mode);
- break;
- case "voiceregistrationstatechange":
- gMobileConnectionService.notifyVoiceInfoChanged(this.clientId, message);
- break;
- case "dataregistrationstatechange":
- gMobileConnectionService.notifyDataInfoChanged(this.clientId, message);
- break;
- case "signalstrengthchange":
- gMobileConnectionService.notifySignalStrengthChanged(this.clientId,
- message);
- break;
- case "operatorchange":
- gMobileConnectionService.notifyOperatorChanged(this.clientId, message);
- break;
- case "otastatuschange":
- gMobileConnectionService.notifyOtaStatusChanged(this.clientId, message.status);
- break;
- case "deviceidentitieschange":
- gMobileConnectionService.notifyDeviceIdentitiesChanged(this.clientId,
- message.deviceIdentities.imei,
- message.deviceIdentities.imeisv,
- message.deviceIdentities.esn,
- message.deviceIdentities.meid);
- break;
- case "radiostatechange":
- // gRadioEnabledController should know the radio state for each client,
- // so notify gRadioEnabledController here.
- gRadioEnabledController.notifyRadioStateChanged(this.clientId,
- message.radioState);
- break;
- case "cardstatechange":
- gIccService.notifyCardStateChanged(this.clientId,
- message.cardState);
- gRadioEnabledController.receiveCardState(this.clientId);
- break;
- case "sms-received":
- this.handleSmsReceived(message);
- break;
- case "cellbroadcast-received":
- this.handleCellbroadcastMessageReceived(message);
- break;
- case "nitzTime":
- this.handleNitzTime(message);
- break;
- case "iccinfochange":
- gIccService.notifyIccInfoChanged(this.clientId,
- message.iccid ? message : null);
- break;
- case "iccimsi":
- gIccService.notifyImsiChanged(this.clientId, message.imsi);
- break;
- case "iccmbdn":
- this.handleIccMbdn(message);
- break;
- case "iccmwis":
- this.handleIccMwis(message.mwi);
- break;
- case "stkcommand":
- gIccService.notifyStkCommand(this.clientId,
- gStkCmdFactory.createCommand(message));
- break;
- case "stksessionend":
- gIccService.notifyStkSessionEnd(this.clientId);
- break;
- case "cdma-info-rec-received":
- this.handleCdmaInformationRecords(message.records);
- break;
- default:
- throw new Error("Don't know about this message type: " +
- message.rilMessageType);
- }
- },
-
- setDataRegistration: function(attach) {
- let deferred = Promise.defer();
- this.workerMessenger.send("setDataRegistration",
- {attach: attach},
- (function(response) {
- // Always resolve to proceed with the following steps.
- deferred.resolve(response.errorMsg ? response.errorMsg : null);
- }).bind(this));
-
- return deferred.promise;
- },
-
- /**
- * TODO: Bug 911713 - B2G NetworkManager: Move policy control logic to
- * NetworkManager
- */
- updateRILNetworkInterface: function() {
- let connHandler = gDataCallManager.getDataCallHandler(this.clientId);
- connHandler.updateRILNetworkInterface();
- },
-
- /**
- * handle received SMS.
- */
- handleSmsReceived: function(aMessage) {
- let header = aMessage.header;
- // Concatenation Info:
- // - segmentRef: a modulo 256 counter indicating the reference number for a
- // particular concatenated short message. '0' is a valid number.
- // - The concatenation info will not be available in |header| if
- // segmentSeq or segmentMaxSeq is 0.
- // See 3GPP TS 23.040, 9.2.3.24.1 Concatenated Short Messages.
- let segmentRef = (header && header.segmentRef !== undefined)
- ? header.segmentRef : 1;
- let segmentSeq = header && header.segmentSeq || 1;
- let segmentMaxSeq = header && header.segmentMaxSeq || 1;
- // Application Ports:
- // The port number ranges from 0 to 49151.
- // see 3GPP TS 23.040, 9.2.3.24.3/4 Application Port Addressing.
- let originatorPort = (header && header.originatorPort !== undefined)
- ? header.originatorPort
- : Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID;
- let destinationPort = (header && header.destinationPort !== undefined)
- ? header.destinationPort
- : Ci.nsIGonkSmsService.SMS_APPLICATION_PORT_INVALID;
- // MWI info:
- let mwiPresent = (aMessage.mwi)? true : false;
- let mwiDiscard = (mwiPresent)? aMessage.mwi.discard: false;
- let mwiMsgCount = (mwiPresent)? aMessage.mwi.msgCount: 0;
- let mwiActive = (mwiPresent)? aMessage.mwi.active: false;
- // CDMA related attributes:
- let cdmaMessageType = aMessage.messageType || 0;
- let cdmaTeleservice = aMessage.teleservice || 0;
- let cdmaServiceCategory = aMessage.serviceCategory || 0;
-
- gSmsService
- .notifyMessageReceived(this.clientId,
- aMessage.SMSC || null,
- aMessage.sentTimestamp,
- aMessage.sender,
- aMessage.pid,
- aMessage.encoding,
- RIL.GECKO_SMS_MESSAGE_CLASSES
- .indexOf(aMessage.messageClass),
- aMessage.language || null,
- segmentRef,
- segmentSeq,
- segmentMaxSeq,
- originatorPort,
- destinationPort,
- mwiPresent,
- mwiDiscard,
- mwiMsgCount,
- mwiActive,
- cdmaMessageType,
- cdmaTeleservice,
- cdmaServiceCategory,
- aMessage.body || null,
- aMessage.data || [],
- (aMessage.data) ? aMessage.data.length : 0);
- },
-
- /**
- * Set the setting value of "time.clock.automatic-update.available".
- */
- setClockAutoUpdateAvailable: function(value) {
- gSettingsService.createLock().set(kSettingsClockAutoUpdateAvailable, value, null);
- },
-
- /**
- * Set the setting value of "time.timezone.automatic-update.available".
- */
- setTimezoneAutoUpdateAvailable: function(value) {
- gSettingsService.createLock().set(kSettingsTimezoneAutoUpdateAvailable, value, null);
- },
-
- /**
- * Set the system clock by NITZ.
- */
- setClockByNitz: function(message) {
- // To set the system clock time. Note that there could be a time diff
- // between when the NITZ was received and when the time is actually set.
- gTimeService.set(
- message.networkTimeInMS + (Date.now() - message.receiveTimeInMS));
- },
-
- /**
- * Set the system time zone by NITZ.
- */
- setTimezoneByNitz: function(message) {
- // To set the sytem timezone. Note that we need to convert the time zone
- // value to a UTC repesentation string in the format of "UTC(+/-)hh:mm".
- // Ex, time zone -480 is "UTC+08:00"; time zone 630 is "UTC-10:30".
- //
- // We can unapply the DST correction if we want the raw time zone offset:
- // message.networkTimeZoneInMinutes -= message.networkDSTInMinutes;
- if (message.networkTimeZoneInMinutes != (new Date()).getTimezoneOffset()) {
- let absTimeZoneInMinutes = Math.abs(message.networkTimeZoneInMinutes);
- let timeZoneStr = "UTC";
- timeZoneStr += (message.networkTimeZoneInMinutes > 0 ? "-" : "+");
- timeZoneStr += ("0" + Math.floor(absTimeZoneInMinutes / 60)).slice(-2);
- timeZoneStr += ":";
- timeZoneStr += ("0" + absTimeZoneInMinutes % 60).slice(-2);
- gSettingsService.createLock().set("time.timezone", timeZoneStr, null);
- }
- },
-
- /**
- * Handle the NITZ message.
- */
- handleNitzTime: function(message) {
- // Got the NITZ info received from the ril_worker.
- this.setClockAutoUpdateAvailable(true);
- this.setTimezoneAutoUpdateAvailable(true);
-
- // Cache the latest NITZ message whenever receiving it.
- this._lastNitzMessage = message;
-
- // Set the received NITZ clock if the setting is enabled.
- if (this._clockAutoUpdateEnabled) {
- this.setClockByNitz(message);
- }
- // Set the received NITZ timezone if the setting is enabled.
- if (this._timezoneAutoUpdateEnabled) {
- this.setTimezoneByNitz(message);
- }
- },
-
- /**
- * Set the system clock by SNTP.
- */
- setClockBySntp: function(offset) {
- // Got the SNTP info.
- this.setClockAutoUpdateAvailable(true);
- if (!this._clockAutoUpdateEnabled) {
- return;
- }
- if (this._lastNitzMessage) {
- if (DEBUG) debug("SNTP: NITZ available, discard SNTP");
- return;
- }
- gTimeService.set(Date.now() + offset);
- },
-
- handleIccMbdn: function(message) {
- let service = Cc["@mozilla.org/voicemail/voicemailservice;1"]
- .getService(Ci.nsIGonkVoicemailService);
- service.notifyInfoChanged(this.clientId, message.number, message.alphaId);
- },
-
- handleIccMwis: function(mwi) {
- let service = Cc["@mozilla.org/voicemail/voicemailservice;1"]
- .getService(Ci.nsIGonkVoicemailService);
- // Note: returnNumber and returnMessage is not available from UICC.
- service.notifyStatusChanged(this.clientId, mwi.active, mwi.msgCount,
- null, null);
- },
-
- _convertCbGsmGeographicalScope: function(aGeographicalScope) {
- return (aGeographicalScope != null)
- ? aGeographicalScope
- : Ci.nsICellBroadcastService.GSM_GEOGRAPHICAL_SCOPE_INVALID;
- },
-
- _convertCbMessageClass: function(aMessageClass) {
- let index = RIL.GECKO_SMS_MESSAGE_CLASSES.indexOf(aMessageClass);
- return (index != -1)
- ? index
- : Ci.nsICellBroadcastService.GSM_MESSAGE_CLASS_NORMAL;
- },
-
- _convertCbEtwsWarningType: function(aWarningType) {
- return (aWarningType != null)
- ? aWarningType
- : Ci.nsICellBroadcastService.GSM_ETWS_WARNING_INVALID;
- },
-
- handleCellbroadcastMessageReceived: function(aMessage) {
- let etwsInfo = aMessage.etws;
- let hasEtwsInfo = etwsInfo != null;
- let serviceCategory = (aMessage.serviceCategory)
- ? aMessage.serviceCategory
- : Ci.nsICellBroadcastService.CDMA_SERVICE_CATEGORY_INVALID;
-
- gCellBroadcastService
- .notifyMessageReceived(this.clientId,
- this._convertCbGsmGeographicalScope(aMessage.geographicalScope),
- aMessage.messageCode,
- aMessage.messageId,
- aMessage.language,
- aMessage.fullBody,
- this._convertCbMessageClass(aMessage.messageClass),
- Date.now(),
- serviceCategory,
- hasEtwsInfo,
- (hasEtwsInfo)
- ? this._convertCbEtwsWarningType(etwsInfo.warningType)
- : Ci.nsICellBroadcastService.GSM_ETWS_WARNING_INVALID,
- hasEtwsInfo ? etwsInfo.emergencyUserAlert : false,
- hasEtwsInfo ? etwsInfo.popup : false);
- },
-
- handleCdmaInformationRecords: function(aRecords) {
- if (DEBUG) this.debug("cdma-info-rec-received: " + JSON.stringify(aRecords));
-
- let clientId = this.clientId;
-
- aRecords.forEach(function(aRecord) {
- if (aRecord.display) {
- gMobileConnectionService
- .notifyCdmaInfoRecDisplay(clientId, aRecord.display);
- return;
- }
-
- if (aRecord.calledNumber) {
- gMobileConnectionService
- .notifyCdmaInfoRecCalledPartyNumber(clientId,
- aRecord.calledNumber.type,
- aRecord.calledNumber.plan,
- aRecord.calledNumber.number,
- aRecord.calledNumber.pi,
- aRecord.calledNumber.si);
- return;
- }
-
- if (aRecord.callingNumber) {
- gMobileConnectionService
- .notifyCdmaInfoRecCallingPartyNumber(clientId,
- aRecord.callingNumber.type,
- aRecord.callingNumber.plan,
- aRecord.callingNumber.number,
- aRecord.callingNumber.pi,
- aRecord.callingNumber.si);
- return;
- }
-
- if (aRecord.connectedNumber) {
- gMobileConnectionService
- .notifyCdmaInfoRecConnectedPartyNumber(clientId,
- aRecord.connectedNumber.type,
- aRecord.connectedNumber.plan,
- aRecord.connectedNumber.number,
- aRecord.connectedNumber.pi,
- aRecord.connectedNumber.si);
- return;
- }
-
- if (aRecord.signal) {
- gMobileConnectionService
- .notifyCdmaInfoRecSignal(clientId,
- aRecord.signal.type,
- aRecord.signal.alertPitch,
- aRecord.signal.signal);
- return;
- }
-
- if (aRecord.redirect) {
- gMobileConnectionService
- .notifyCdmaInfoRecRedirectingNumber(clientId,
- aRecord.redirect.type,
- aRecord.redirect.plan,
- aRecord.redirect.number,
- aRecord.redirect.pi,
- aRecord.redirect.si,
- aRecord.redirect.reason);
- return;
- }
-
- if (aRecord.lineControl) {
- gMobileConnectionService
- .notifyCdmaInfoRecLineControl(clientId,
- aRecord.lineControl.polarityIncluded,
- aRecord.lineControl.toggle,
- aRecord.lineControl.reverse,
- aRecord.lineControl.powerDenial);
- return;
- }
-
- if (aRecord.clirCause) {
- gMobileConnectionService
- .notifyCdmaInfoRecClir(clientId,
- aRecord.clirCause);
- return;
- }
-
- if (aRecord.audioControl) {
- gMobileConnectionService
- .notifyCdmaInfoRecAudioControl(clientId,
- aRecord.audioControl.upLink,
- aRecord.audioControl.downLink);
- return;
- }
- });
- },
-
- // nsIObserver
-
- observe: function(subject, topic, data) {
- switch (topic) {
- case kMozSettingsChangedObserverTopic:
- if ("wrappedJSObject" in subject) {
- subject = subject.wrappedJSObject;
- }
- this.handleSettingsChange(subject.key, subject.value, subject.isInternalChange);
- break;
- case kSysClockChangeObserverTopic:
- let offset = parseInt(data, 10);
- if (this._lastNitzMessage) {
- this._lastNitzMessage.receiveTimeInMS += offset;
- }
- this._sntp.updateOffset(offset);
- break;
- case kNetworkConnStateChangedTopic:
- let networkInfo = subject.QueryInterface(Ci.nsINetworkInfo);
- if (networkInfo.state != Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- return;
- }
-
- // SNTP can only update when we have mobile or Wifi connections.
- if (networkInfo.type != NETWORK_TYPE_WIFI &&
- networkInfo.type != NETWORK_TYPE_MOBILE) {
- return;
- }
-
- // If the network comes from RIL, make sure the RIL service is matched.
- if (subject instanceof Ci.nsIRilNetworkInfo) {
- networkInfo = subject.QueryInterface(Ci.nsIRilNetworkInfo);
- if (networkInfo.serviceId != this.clientId) {
- return;
- }
- }
-
- // SNTP won't update unless the SNTP is already expired.
- if (this._sntp.isExpired()) {
- this._sntp.request();
- }
- break;
- case kScreenStateChangedTopic:
- this.workerMessenger.send("setScreenState", { on: (data === "on") });
- break;
- }
- },
-
- // Flag to determine whether to update system clock automatically. It
- // corresponds to the "time.clock.automatic-update.enabled" setting.
- _clockAutoUpdateEnabled: null,
-
- // Flag to determine whether to update system timezone automatically. It
- // corresponds to the "time.clock.automatic-update.enabled" setting.
- _timezoneAutoUpdateEnabled: null,
-
- // Remember the last NITZ message so that we can set the time based on
- // the network immediately when users enable network-based time.
- _lastNitzMessage: null,
-
- // Object that handles SNTP.
- _sntp: null,
-
- // Cell Broadcast settings values.
- _cellBroadcastSearchList: null,
-
- handleSettingsChange: function(aName, aResult, aIsInternalSetting) {
- // Don't allow any content processes to modify the setting
- // "time.clock.automatic-update.available" except for the chrome process.
- if (aName === kSettingsClockAutoUpdateAvailable &&
- !aIsInternalSetting) {
- let isClockAutoUpdateAvailable = this._lastNitzMessage !== null ||
- this._sntp.isAvailable();
- if (aResult !== isClockAutoUpdateAvailable) {
- if (DEBUG) {
- debug("Content processes cannot modify 'time.clock.automatic-update.available'. Restore!");
- }
- // Restore the setting to the current value.
- this.setClockAutoUpdateAvailable(isClockAutoUpdateAvailable);
- }
- }
-
- // Don't allow any content processes to modify the setting
- // "time.timezone.automatic-update.available" except for the chrome
- // process.
- if (aName === kSettingsTimezoneAutoUpdateAvailable &&
- !aIsInternalSetting) {
- let isTimezoneAutoUpdateAvailable = this._lastNitzMessage !== null;
- if (aResult !== isTimezoneAutoUpdateAvailable) {
- if (DEBUG) {
- this.debug("Content processes cannot modify 'time.timezone.automatic-update.available'. Restore!");
- }
- // Restore the setting to the current value.
- this.setTimezoneAutoUpdateAvailable(isTimezoneAutoUpdateAvailable);
- }
- }
-
- this.handle(aName, aResult);
- },
-
- // nsISettingsServiceCallback
- handle: function(aName, aResult) {
- switch(aName) {
- case kSettingsClockAutoUpdateEnabled:
- this._clockAutoUpdateEnabled = aResult;
- if (!this._clockAutoUpdateEnabled) {
- break;
- }
-
- // Set the latest cached NITZ time if it's available.
- if (this._lastNitzMessage) {
- this.setClockByNitz(this._lastNitzMessage);
- } else if (gNetworkManager.activeNetworkInfo &&
- gNetworkManager.activeNetworkInfo.state ==
- Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- // Set the latest cached SNTP time if it's available.
- if (!this._sntp.isExpired()) {
- this.setClockBySntp(this._sntp.getOffset());
- } else {
- // Or refresh the SNTP.
- this._sntp.request();
- }
- } else {
- // Set a sane minimum time.
- let buildTime = libcutils.property_get("ro.build.date.utc", "0") * 1000;
- let file = FileUtils.File("/system/b2g/b2g");
- if (file.lastModifiedTime > buildTime) {
- buildTime = file.lastModifiedTime;
- }
- if (buildTime > Date.now()) {
- gTimeService.set(buildTime);
- }
- }
- break;
- case kSettingsTimezoneAutoUpdateEnabled:
- this._timezoneAutoUpdateEnabled = aResult;
-
- if (this._timezoneAutoUpdateEnabled) {
- // Apply the latest cached NITZ for timezone if it's available.
- if (this._timezoneAutoUpdateEnabled && this._lastNitzMessage) {
- this.setTimezoneByNitz(this._lastNitzMessage);
- }
- }
- break;
- }
- },
-
- handleError: function(aErrorMessage) {
- if (DEBUG) {
- this.debug("There was an error while reading RIL settings.");
- }
- },
-
- // nsIRadioInterface
-
- // TODO: Bug 928861 - B2G NetworkManager: Provide a more generic function
- // for connecting
- setupDataCallByType: function(networkType) {
- let connHandler = gDataCallManager.getDataCallHandler(this.clientId);
- connHandler.setupDataCallByType(networkType);
- },
-
- // TODO: Bug 928861 - B2G NetworkManager: Provide a more generic function
- // for connecting
- deactivateDataCallByType: function(networkType) {
- let connHandler = gDataCallManager.getDataCallHandler(this.clientId);
- connHandler.deactivateDataCallByType(networkType);
- },
-
- // TODO: Bug 904514 - [meta] NetworkManager enhancement
- getDataCallStateByType: function(networkType) {
- let connHandler = gDataCallManager.getDataCallHandler(this.clientId);
- return connHandler.getDataCallStateByType(networkType);
- },
-
- sendWorkerMessage: function(rilMessageType, message, callback) {
- // Special handler for setRadioEnabled.
- if (rilMessageType === "setRadioEnabled") {
- // Forward it to gRadioEnabledController.
- gRadioEnabledController.setRadioEnabled(this.clientId, message,
- callback.handleResponse);
- return;
- }
-
- if (callback) {
- this.workerMessenger.send(rilMessageType, message, function(response) {
- return callback.handleResponse(response);
- });
- } else {
- this.workerMessenger.send(rilMessageType, message);
- }
- },
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([RadioInterfaceLayer]);
diff --git a/dom/system/gonk/RadioInterfaceLayer.manifest b/dom/system/gonk/RadioInterfaceLayer.manifest
deleted file mode 100644
index 3c7c3b808..000000000
--- a/dom/system/gonk/RadioInterfaceLayer.manifest
+++ /dev/null
@@ -1,18 +0,0 @@
-# Copyright 2012 Mozilla Foundation and Mozilla contributors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# RadioInterfaceLayer.js
-component {2d831c8d-6017-435b-a80c-e5d422810cea} RadioInterfaceLayer.js
-contract @mozilla.org/ril;1 {2d831c8d-6017-435b-a80c-e5d422810cea}
-category profile-after-change RadioInterfaceLayer @mozilla.org/ril;1
diff --git a/dom/system/gonk/SystemProperty.cpp b/dom/system/gonk/SystemProperty.cpp
deleted file mode 100644
index 1f874ce90..000000000
--- a/dom/system/gonk/SystemProperty.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/* -*- 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 "SystemProperty.h"
-
-#include <dlfcn.h>
-#include <string.h>
-
-#include "nsDebug.h"
-#include "prinit.h"
-
-namespace mozilla {
-namespace system {
-
-namespace {
-
-typedef int (*PropertyGet)(const char*, char*, const char*);
-typedef int (*PropertySet)(const char*, const char*);
-
-static void *sLibcUtils;
-static PRCallOnceType sInitLibcUtils;
-
-static int
-FakePropertyGet(const char* key, char* value, const char* default_value)
-{
- if(!default_value) {
- value[0] = '\0';
- return 0;
- }
-
- int len = strlen(default_value);
- if (len >= Property::VALUE_MAX_LENGTH) {
- len = Property::VALUE_MAX_LENGTH - 1;
- }
- memcpy(value, default_value, len);
- value[len] = '\0';
-
- return len;
-}
-
-static int
-FakePropertySet(const char* key, const char* value)
-{
- return 0;
-}
-
-static PRStatus
-InitLibcUtils()
-{
- sLibcUtils = dlopen("/system/lib/libcutils.so", RTLD_LAZY);
- // We will fallback to the fake getter/setter when sLibcUtils is not valid.
- return PR_SUCCESS;
-}
-
-static void*
-GetLibcUtils()
-{
- PR_CallOnce(&sInitLibcUtils, InitLibcUtils);
- return sLibcUtils;
-}
-
-} // anonymous namespace
-
-/*static*/ int
-Property::Get(const char* key, char* value, const char* default_value)
-{
- void *libcutils = GetLibcUtils();
- if (libcutils) {
- PropertyGet getter = (PropertyGet) dlsym(libcutils, "property_get");
- if (getter) {
- return getter(key, value, default_value);
- }
- NS_WARNING("Failed to get property_get() from libcutils!");
- }
- NS_WARNING("Fallback to the FakePropertyGet()");
- return FakePropertyGet(key, value, default_value);
-}
-
-/*static*/ int
-Property::Set(const char* key, const char* value)
-{
- void *libcutils = GetLibcUtils();
- if (libcutils) {
- PropertySet setter = (PropertySet) dlsym(libcutils, "property_set");
- if (setter) {
- return setter(key, value);
- }
- NS_WARNING("Failed to get property_set() from libcutils!");
- }
- NS_WARNING("Fallback to the FakePropertySet()");
- return FakePropertySet(key, value);
-}
-
-} // namespace system
-} // namespace mozilla
diff --git a/dom/system/gonk/SystemProperty.h b/dom/system/gonk/SystemProperty.h
deleted file mode 100644
index 2b5ceae8b..000000000
--- a/dom/system/gonk/SystemProperty.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* -*- 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_system_Property_h
-#define mozilla_system_Property_h
-
-namespace mozilla {
-namespace system {
-
-/**
-* Abstraction of property_get/property_get in libcutils from AOSP.
-*/
-class Property
-{
-public:
- // Constants defined in system_properties.h from AOSP.
- enum {
- KEY_MAX_LENGTH = 32,
- VALUE_MAX_LENGTH = 92
- };
-
- static int
- Get(const char* key, char* value, const char* default_value);
-
- static int
- Set(const char* key, const char* value);
-
-private:
- Property() {}
- virtual ~Property() {}
-};
-
-} // namespace system
-} // namespace mozilla
-
- #endif // mozilla_system_Property_h
diff --git a/dom/system/gonk/SystemWorkerManager.cpp b/dom/system/gonk/SystemWorkerManager.cpp
deleted file mode 100644
index ee3fc8de3..000000000
--- a/dom/system/gonk/SystemWorkerManager.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* vim: set ts=2 et sw=2 tw=80: */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "SystemWorkerManager.h"
-
-#include "nsINetworkService.h"
-#include "nsIWifi.h"
-#include "nsIWorkerHolder.h"
-#include "nsIXPConnect.h"
-
-#include "jsfriendapi.h"
-#include "mozilla/dom/workers/Workers.h"
-#include "AutoMounter.h"
-#include "TimeZoneSettingObserver.h"
-#include "AudioManager.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "mozilla/ipc/KeyStore.h"
-#include "nsIObserverService.h"
-#include "nsServiceManagerUtils.h"
-#include "nsThreadUtils.h"
-#include "WifiWorker.h"
-#include "mozilla/Services.h"
-
-USING_WORKERS_NAMESPACE
-
-using namespace mozilla::dom::gonk;
-using namespace mozilla::ipc;
-using namespace mozilla::system;
-
-namespace {
-
-NS_DEFINE_CID(kWifiWorkerCID, NS_WIFIWORKER_CID);
-
-// Doesn't carry a reference, we're owned by services.
-SystemWorkerManager *gInstance = nullptr;
-
-} // namespace
-
-SystemWorkerManager::SystemWorkerManager()
- : mShutdown(false)
-{
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
- NS_ASSERTION(!gInstance, "There should only be one instance!");
-}
-
-SystemWorkerManager::~SystemWorkerManager()
-{
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
- NS_ASSERTION(!gInstance || gInstance == this,
- "There should only be one instance!");
- gInstance = nullptr;
-}
-
-nsresult
-SystemWorkerManager::Init()
-{
- if (!XRE_IsParentProcess()) {
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- NS_ASSERTION(NS_IsMainThread(), "We can only initialize on the main thread");
- NS_ASSERTION(!mShutdown, "Already shutdown!");
-
- nsresult rv = InitWifi();
- if (NS_FAILED(rv)) {
- NS_WARNING("Failed to initialize WiFi Networking!");
- return rv;
- }
-
- InitKeyStore();
-
- InitAutoMounter();
- InitializeTimeZoneSettingObserver();
- nsCOMPtr<nsIAudioManager> audioManager =
- do_GetService(NS_AUDIOMANAGER_CONTRACTID);
-
- nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
- if (!obs) {
- NS_WARNING("Failed to get observer service!");
- return NS_ERROR_FAILURE;
- }
-
- rv = obs->AddObserver(this, WORKERS_SHUTDOWN_TOPIC, false);
- if (NS_FAILED(rv)) {
- NS_WARNING("Failed to initialize worker shutdown event!");
- return rv;
- }
-
- return NS_OK;
-}
-
-void
-SystemWorkerManager::Shutdown()
-{
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
- mShutdown = true;
-
- ShutdownAutoMounter();
-
- nsCOMPtr<nsIWifi> wifi(do_QueryInterface(mWifiWorker));
- if (wifi) {
- wifi->Shutdown();
- wifi = nullptr;
- }
- mWifiWorker = nullptr;
-
- if (mKeyStore) {
- mKeyStore->Shutdown();
- mKeyStore = nullptr;
- }
-
- nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
- if (obs) {
- obs->RemoveObserver(this, WORKERS_SHUTDOWN_TOPIC);
- }
-}
-
-// static
-already_AddRefed<SystemWorkerManager>
-SystemWorkerManager::FactoryCreate()
-{
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
- RefPtr<SystemWorkerManager> instance(gInstance);
-
- if (!instance) {
- instance = new SystemWorkerManager();
- if (NS_FAILED(instance->Init())) {
- instance->Shutdown();
- return nullptr;
- }
-
- gInstance = instance;
- }
-
- return instance.forget();
-}
-
-// static
-nsIInterfaceRequestor*
-SystemWorkerManager::GetInterfaceRequestor()
-{
- return gInstance;
-}
-
-NS_IMETHODIMP
-SystemWorkerManager::GetInterface(const nsIID &aIID, void **aResult)
-{
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
-
- if (aIID.Equals(NS_GET_IID(nsIWifi))) {
- return CallQueryInterface(mWifiWorker,
- reinterpret_cast<nsIWifi**>(aResult));
- }
-
- NS_WARNING("Got nothing for the requested IID!");
- return NS_ERROR_NO_INTERFACE;
-}
-
-nsresult
-SystemWorkerManager::RegisterRilWorker(unsigned int aClientId,
- JS::Handle<JS::Value> aWorker,
- JSContext *aCx)
-{
- return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-nsresult
-SystemWorkerManager::InitWifi()
-{
- nsCOMPtr<nsIWorkerHolder> worker = do_CreateInstance(kWifiWorkerCID);
- NS_ENSURE_TRUE(worker, NS_ERROR_FAILURE);
-
- mWifiWorker = worker;
- return NS_OK;
-}
-
-nsresult
-SystemWorkerManager::InitKeyStore()
-{
- mKeyStore = new KeyStore();
- return NS_OK;
-}
-
-NS_IMPL_ISUPPORTS(SystemWorkerManager,
- nsIObserver,
- nsIInterfaceRequestor,
- nsISystemWorkerManager)
-
-NS_IMETHODIMP
-SystemWorkerManager::Observe(nsISupports *aSubject, const char *aTopic,
- const char16_t *aData)
-{
- if (!strcmp(aTopic, WORKERS_SHUTDOWN_TOPIC)) {
- Shutdown();
- }
-
- return NS_OK;
-}
diff --git a/dom/system/gonk/SystemWorkerManager.h b/dom/system/gonk/SystemWorkerManager.h
deleted file mode 100644
index 625cda261..000000000
--- a/dom/system/gonk/SystemWorkerManager.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* vim: set ts=2 et sw=2 tw=40: */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef mozilla_dom_system_b2g_systemworkermanager_h__
-#define mozilla_dom_system_b2g_systemworkermanager_h__
-
-#include "nsIInterfaceRequestor.h"
-#include "nsISystemWorkerManager.h"
-#include "nsIObserver.h"
-#include "nsCOMPtr.h"
-#include "nsXULAppAPI.h" // For XRE_GetProcessType
-
-class nsIWorkerHolder;
-
-namespace mozilla {
-
-namespace ipc {
- class KeyStore;
-}
-
-namespace dom {
-namespace gonk {
-
-class SystemWorkerManager final : public nsIObserver,
- public nsIInterfaceRequestor,
- public nsISystemWorkerManager
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIOBSERVER
- NS_DECL_NSIINTERFACEREQUESTOR
- NS_DECL_NSISYSTEMWORKERMANAGER
-
- nsresult Init();
- void Shutdown();
-
- static already_AddRefed<SystemWorkerManager>
- FactoryCreate();
-
- static nsIInterfaceRequestor*
- GetInterfaceRequestor();
-
-private:
- SystemWorkerManager();
- ~SystemWorkerManager();
-
- nsresult InitWifi();
- nsresult InitKeyStore();
-
- nsCOMPtr<nsIWorkerHolder> mWifiWorker;
-
- RefPtr<mozilla::ipc::KeyStore> mKeyStore;
-
- bool mShutdown;
-};
-
-}
-}
-}
-
-#endif // mozilla_dom_system_b2g_systemworkermanager_h__
diff --git a/dom/system/gonk/TetheringService.js b/dom/system/gonk/TetheringService.js
deleted file mode 100644
index c5c478180..000000000
--- a/dom/system/gonk/TetheringService.js
+++ /dev/null
@@ -1,891 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/FileUtils.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-
-const TETHERINGSERVICE_CONTRACTID = "@mozilla.org/tethering/service;1";
-const TETHERINGSERVICE_CID =
- Components.ID("{527a4121-ee5a-4651-be9c-f46f59cf7c01}");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
- "@mozilla.org/network/manager;1",
- "nsINetworkManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkService",
- "@mozilla.org/network/service;1",
- "nsINetworkService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
- "@mozilla.org/settingsService;1",
- "nsISettingsService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gMobileConnectionService",
- "@mozilla.org/mobileconnection/mobileconnectionservice;1",
- "nsIMobileConnectionService");
-
-XPCOMUtils.defineLazyGetter(this, "gRil", function() {
- try {
- return Cc["@mozilla.org/ril;1"].getService(Ci.nsIRadioInterfaceLayer);
- } catch (e) {}
-
- return null;
-});
-
-const TOPIC_MOZSETTINGS_CHANGED = "mozsettings-changed";
-const TOPIC_CONNECTION_STATE_CHANGED = "network-connection-state-changed";
-const TOPIC_PREF_CHANGED = "nsPref:changed";
-const TOPIC_XPCOM_SHUTDOWN = "xpcom-shutdown";
-const PREF_MANAGE_OFFLINE_STATUS = "network.gonk.manage-offline-status";
-const PREF_NETWORK_DEBUG_ENABLED = "network.debugging.enabled";
-
-const POSSIBLE_USB_INTERFACE_NAME = "rndis0,usb0";
-const DEFAULT_USB_INTERFACE_NAME = "rndis0";
-const DEFAULT_3G_INTERFACE_NAME = "rmnet0";
-const DEFAULT_WIFI_INTERFACE_NAME = "wlan0";
-
-// The kernel's proc entry for network lists.
-const KERNEL_NETWORK_ENTRY = "/sys/class/net";
-
-const TETHERING_TYPE_WIFI = "WiFi";
-const TETHERING_TYPE_USB = "USB";
-
-const WIFI_FIRMWARE_AP = "AP";
-const WIFI_FIRMWARE_STATION = "STA";
-const WIFI_SECURITY_TYPE_NONE = "open";
-const WIFI_SECURITY_TYPE_WPA_PSK = "wpa-psk";
-const WIFI_SECURITY_TYPE_WPA2_PSK = "wpa2-psk";
-const WIFI_CTRL_INTERFACE = "wl0.1";
-
-const NETWORK_INTERFACE_UP = "up";
-const NETWORK_INTERFACE_DOWN = "down";
-
-const TETHERING_STATE_ONGOING = "ongoing";
-const TETHERING_STATE_IDLE = "idle";
-const TETHERING_STATE_ACTIVE = "active";
-
-// Settings DB path for USB tethering.
-const SETTINGS_USB_ENABLED = "tethering.usb.enabled";
-const SETTINGS_USB_IP = "tethering.usb.ip";
-const SETTINGS_USB_PREFIX = "tethering.usb.prefix";
-const SETTINGS_USB_DHCPSERVER_STARTIP = "tethering.usb.dhcpserver.startip";
-const SETTINGS_USB_DHCPSERVER_ENDIP = "tethering.usb.dhcpserver.endip";
-const SETTINGS_USB_DNS1 = "tethering.usb.dns1";
-const SETTINGS_USB_DNS2 = "tethering.usb.dns2";
-
-// Settings DB path for WIFI tethering.
-const SETTINGS_WIFI_DHCPSERVER_STARTIP = "tethering.wifi.dhcpserver.startip";
-const SETTINGS_WIFI_DHCPSERVER_ENDIP = "tethering.wifi.dhcpserver.endip";
-
-// Settings DB patch for dun required setting.
-const SETTINGS_DUN_REQUIRED = "tethering.dun.required";
-
-// Default value for USB tethering.
-const DEFAULT_USB_IP = "192.168.0.1";
-const DEFAULT_USB_PREFIX = "24";
-const DEFAULT_USB_DHCPSERVER_STARTIP = "192.168.0.10";
-const DEFAULT_USB_DHCPSERVER_ENDIP = "192.168.0.30";
-
-const DEFAULT_DNS1 = "8.8.8.8";
-const DEFAULT_DNS2 = "8.8.4.4";
-
-const DEFAULT_WIFI_DHCPSERVER_STARTIP = "192.168.1.10";
-const DEFAULT_WIFI_DHCPSERVER_ENDIP = "192.168.1.30";
-
-const SETTINGS_DATA_DEFAULT_SERVICE_ID = "ril.data.defaultServiceId";
-const MOBILE_DUN_CONNECT_TIMEOUT = 30000;
-const MOBILE_DUN_RETRY_INTERVAL = 5000;
-const MOBILE_DUN_MAX_RETRIES = 5;
-
-var debug;
-function updateDebug() {
- let debugPref = false; // set default value here.
- try {
- debugPref = debugPref || Services.prefs.getBoolPref(PREF_NETWORK_DEBUG_ENABLED);
- } catch (e) {}
-
- if (debugPref) {
- debug = function(s) {
- dump("-*- TetheringService: " + s + "\n");
- };
- } else {
- debug = function(s) {};
- }
-}
-updateDebug();
-
-function TetheringService() {
- Services.obs.addObserver(this, TOPIC_XPCOM_SHUTDOWN, false);
- Services.obs.addObserver(this, TOPIC_MOZSETTINGS_CHANGED, false);
- Services.obs.addObserver(this, TOPIC_CONNECTION_STATE_CHANGED, false);
- Services.prefs.addObserver(PREF_NETWORK_DEBUG_ENABLED, this, false);
- Services.prefs.addObserver(PREF_MANAGE_OFFLINE_STATUS, this, false);
-
- try {
- this._manageOfflineStatus =
- Services.prefs.getBoolPref(PREF_MANAGE_OFFLINE_STATUS);
- } catch(ex) {
- // Ignore.
- }
-
- this._dataDefaultServiceId = 0;
-
- // Possible usb tethering interfaces for different gonk platform.
- this.possibleInterface = POSSIBLE_USB_INTERFACE_NAME.split(",");
-
- // Default values for internal and external interfaces.
- this._tetheringInterface = {};
- this._tetheringInterface[TETHERING_TYPE_USB] = {
- externalInterface: DEFAULT_3G_INTERFACE_NAME,
- internalInterface: DEFAULT_USB_INTERFACE_NAME
- };
- this._tetheringInterface[TETHERING_TYPE_WIFI] = {
- externalInterface: DEFAULT_3G_INTERFACE_NAME,
- internalInterface: DEFAULT_WIFI_INTERFACE_NAME
- };
-
- this.tetheringSettings = {};
- this.initTetheringSettings();
-
- let settingsLock = gSettingsService.createLock();
- // Read the default service id for data call.
- settingsLock.get(SETTINGS_DATA_DEFAULT_SERVICE_ID, this);
-
- // Read usb tethering data from settings DB.
- settingsLock.get(SETTINGS_USB_IP, this);
- settingsLock.get(SETTINGS_USB_PREFIX, this);
- settingsLock.get(SETTINGS_USB_DHCPSERVER_STARTIP, this);
- settingsLock.get(SETTINGS_USB_DHCPSERVER_ENDIP, this);
- settingsLock.get(SETTINGS_USB_DNS1, this);
- settingsLock.get(SETTINGS_USB_DNS2, this);
- settingsLock.get(SETTINGS_USB_ENABLED, this);
-
- // Read wifi tethering data from settings DB.
- settingsLock.get(SETTINGS_WIFI_DHCPSERVER_STARTIP, this);
- settingsLock.get(SETTINGS_WIFI_DHCPSERVER_ENDIP, this);
-
- this._usbTetheringSettingsToRead = [SETTINGS_USB_IP,
- SETTINGS_USB_PREFIX,
- SETTINGS_USB_DHCPSERVER_STARTIP,
- SETTINGS_USB_DHCPSERVER_ENDIP,
- SETTINGS_USB_DNS1,
- SETTINGS_USB_DNS2,
- SETTINGS_USB_ENABLED,
- SETTINGS_WIFI_DHCPSERVER_STARTIP,
- SETTINGS_WIFI_DHCPSERVER_ENDIP];
-
- this.wantConnectionEvent = null;
-
- this.dunConnectTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-
- this.dunRetryTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-
- this._pendingTetheringRequests = [];
-}
-TetheringService.prototype = {
- classID: TETHERINGSERVICE_CID,
- classInfo: XPCOMUtils.generateCI({classID: TETHERINGSERVICE_CID,
- contractID: TETHERINGSERVICE_CONTRACTID,
- classDescription: "Tethering Service",
- interfaces: [Ci.nsITetheringService]}),
- QueryInterface: XPCOMUtils.generateQI([Ci.nsITetheringService,
- Ci.nsISupportsWeakReference,
- Ci.nsIObserver,
- Ci.nsISettingsServiceCallback]),
-
- // Flag to record the default client id for data call.
- _dataDefaultServiceId: null,
-
- // Number of usb tehering requests to be processed.
- _usbTetheringRequestCount: 0,
-
- // Usb tethering state.
- _usbTetheringAction: TETHERING_STATE_IDLE,
-
- // Tethering settings.
- tetheringSettings: null,
-
- // Tethering settings need to be read from settings DB.
- _usbTetheringSettingsToRead: null,
-
- // Previous usb tethering enabled state.
- _oldUsbTetheringEnabledState: null,
-
- // External and internal interface name.
- _tetheringInterface: null,
-
- // Dun connection timer.
- dunConnectTimer: null,
-
- // Dun connection retry times.
- dunRetryTimes: 0,
-
- // Dun retry timer.
- dunRetryTimer: null,
-
- // Pending tethering request to handle after dun is connected.
- _pendingTetheringRequests: null,
-
- // Flag to indicate wether wifi tethering is being processed.
- _wifiTetheringRequestOngoing: false,
-
- // Arguments for pending wifi tethering request.
- _pendingWifiTetheringRequestArgs: null,
-
- // The state of tethering.
- state: Ci.nsITetheringService.TETHERING_STATE_INACTIVE,
-
- // Flag to check if we can modify the Services.io.offline.
- _manageOfflineStatus: true,
-
- // nsIObserver
-
- observe: function(aSubject, aTopic, aData) {
- let network;
-
- switch(aTopic) {
- case TOPIC_PREF_CHANGED:
- if (aData === PREF_NETWORK_DEBUG_ENABLED) {
- updateDebug();
- }
- break;
- case TOPIC_MOZSETTINGS_CHANGED:
- if ("wrappedJSObject" in aSubject) {
- aSubject = aSubject.wrappedJSObject;
- }
- this.handle(aSubject.key, aSubject.value);
- break;
- case TOPIC_CONNECTION_STATE_CHANGED:
- network = aSubject.QueryInterface(Ci.nsINetworkInfo);
- debug("Network " + network.type + "/" + network.name +
- " changed state to " + network.state);
- this.onConnectionChanged(network);
- break;
- case TOPIC_XPCOM_SHUTDOWN:
- Services.obs.removeObserver(this, TOPIC_XPCOM_SHUTDOWN);
- Services.obs.removeObserver(this, TOPIC_MOZSETTINGS_CHANGED);
- Services.obs.removeObserver(this, TOPIC_CONNECTION_STATE_CHANGED);
- Services.prefs.removeObserver(PREF_NETWORK_DEBUG_ENABLED, this);
- Services.prefs.removeObserver(PREF_MANAGE_OFFLINE_STATUS, this);
-
- this.dunConnectTimer.cancel();
- this.dunRetryTimer.cancel();
- break;
- case PREF_MANAGE_OFFLINE_STATUS:
- try {
- this._manageOfflineStatus =
- Services.prefs.getBoolPref(PREF_MANAGE_OFFLINE_STATUS);
- } catch(ex) {
- // Ignore.
- }
- break;
- }
- },
-
- // nsISettingsServiceCallback
-
- handle: function(aName, aResult) {
- switch(aName) {
- case SETTINGS_DATA_DEFAULT_SERVICE_ID:
- this._dataDefaultServiceId = aResult || 0;
- debug("'_dataDefaultServiceId' is now " + this._dataDefaultServiceId);
- break;
- case SETTINGS_USB_ENABLED:
- this._oldUsbTetheringEnabledState = this.tetheringSettings[SETTINGS_USB_ENABLED];
- case SETTINGS_USB_IP:
- case SETTINGS_USB_PREFIX:
- case SETTINGS_USB_DHCPSERVER_STARTIP:
- case SETTINGS_USB_DHCPSERVER_ENDIP:
- case SETTINGS_USB_DNS1:
- case SETTINGS_USB_DNS2:
- case SETTINGS_WIFI_DHCPSERVER_STARTIP:
- case SETTINGS_WIFI_DHCPSERVER_ENDIP:
- if (aResult !== null) {
- this.tetheringSettings[aName] = aResult;
- }
- debug("'" + aName + "'" + " is now " + this.tetheringSettings[aName]);
- let index = this._usbTetheringSettingsToRead.indexOf(aName);
-
- if (index != -1) {
- this._usbTetheringSettingsToRead.splice(index, 1);
- }
-
- if (this._usbTetheringSettingsToRead.length) {
- debug("We haven't read completely the usb Tethering data from settings db.");
- break;
- }
-
- if (this._oldUsbTetheringEnabledState === this.tetheringSettings[SETTINGS_USB_ENABLED]) {
- debug("No changes for SETTINGS_USB_ENABLED flag. Nothing to do.");
- this.handlePendingWifiTetheringRequest();
- break;
- }
-
- this._usbTetheringRequestCount++;
- if (this._usbTetheringRequestCount === 1) {
- if (this._wifiTetheringRequestOngoing) {
- debug('USB tethering request is blocked by ongoing wifi tethering request.');
- } else {
- this.handleLastUsbTetheringRequest();
- }
- }
- break;
- };
- },
-
- handleError: function(aErrorMessage) {
- debug("There was an error while reading Tethering settings.");
- this.tetheringSettings = {};
- this.tetheringSettings[SETTINGS_USB_ENABLED] = false;
- },
-
- initTetheringSettings: function() {
- this.tetheringSettings[SETTINGS_USB_ENABLED] = false;
- this.tetheringSettings[SETTINGS_USB_IP] = DEFAULT_USB_IP;
- this.tetheringSettings[SETTINGS_USB_PREFIX] = DEFAULT_USB_PREFIX;
- this.tetheringSettings[SETTINGS_USB_DHCPSERVER_STARTIP] = DEFAULT_USB_DHCPSERVER_STARTIP;
- this.tetheringSettings[SETTINGS_USB_DHCPSERVER_ENDIP] = DEFAULT_USB_DHCPSERVER_ENDIP;
- this.tetheringSettings[SETTINGS_USB_DNS1] = DEFAULT_DNS1;
- this.tetheringSettings[SETTINGS_USB_DNS2] = DEFAULT_DNS2;
-
- this.tetheringSettings[SETTINGS_WIFI_DHCPSERVER_STARTIP] = DEFAULT_WIFI_DHCPSERVER_STARTIP;
- this.tetheringSettings[SETTINGS_WIFI_DHCPSERVER_ENDIP] = DEFAULT_WIFI_DHCPSERVER_ENDIP;
-
- this.tetheringSettings[SETTINGS_DUN_REQUIRED] =
- libcutils.property_get("ro.tethering.dun_required") === "1";
- },
-
- getNetworkInfo: function(aType, aServiceId) {
- for (let networkId in gNetworkManager.allNetworkInfo) {
- let networkInfo = gNetworkManager.allNetworkInfo[networkId];
- if (networkInfo.type == aType) {
- try {
- if (networkInfo instanceof Ci.nsIRilNetworkInfo) {
- let rilNetwork = networkInfo.QueryInterface(Ci.nsIRilNetworkInfo);
- if (rilNetwork.serviceId != aServiceId) {
- continue;
- }
- }
- } catch (e) {}
- return networkInfo;
- }
- }
- return null;
- },
-
- handleLastUsbTetheringRequest: function() {
- debug('handleLastUsbTetheringRequest... ' + this._usbTetheringRequestCount);
-
- if (this._usbTetheringRequestCount === 0) {
- if (this.wantConnectionEvent) {
- if (this.tetheringSettings[SETTINGS_USB_ENABLED]) {
- this.wantConnectionEvent.call(this);
- }
- this.wantConnectionEvent = null;
- }
- this.handlePendingWifiTetheringRequest();
- return;
- }
-
- // Cancel the accumlated count to 1 since we only care about the
- // last state.
- this._usbTetheringRequestCount = 1;
- this.handleUSBTetheringToggle(this.tetheringSettings[SETTINGS_USB_ENABLED]);
- this.wantConnectionEvent = null;
- },
-
- handlePendingWifiTetheringRequest: function() {
- if (this._pendingWifiTetheringRequestArgs) {
- this.setWifiTethering.apply(this, this._pendingWifiTetheringRequestArgs);
- this._pendingWifiTetheringRequestArgs = null;
- }
- },
-
- /**
- * Callback when dun connection fails to connect within timeout.
- */
- onDunConnectTimerTimeout: function() {
- while (this._pendingTetheringRequests.length > 0) {
- debug("onDunConnectTimerTimeout: callback without network info.");
- let callback = this._pendingTetheringRequests.shift();
- if (typeof callback === 'function') {
- callback();
- }
- }
- },
-
- setupDunConnection: function() {
- this.dunRetryTimer.cancel();
- let connection =
- gMobileConnectionService.getItemByServiceId(this._dataDefaultServiceId);
- let data = connection && connection.data;
- if (data && data.state === "registered") {
- let ril = gRil.getRadioInterface(this._dataDefaultServiceId);
-
- this.dunRetryTimes = 0;
- ril.setupDataCallByType(Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN);
- this.dunConnectTimer.cancel();
- this.dunConnectTimer.
- initWithCallback(this.onDunConnectTimerTimeout.bind(this),
- MOBILE_DUN_CONNECT_TIMEOUT, Ci.nsITimer.TYPE_ONE_SHOT);
- return;
- }
-
- if (this.dunRetryTimes++ >= this.MOBILE_DUN_MAX_RETRIES) {
- debug("setupDunConnection: max retries reached.");
- this.dunRetryTimes = 0;
- // same as dun connect timeout.
- this.onDunConnectTimerTimeout();
- return;
- }
-
- debug("Data not ready, retry dun after " + MOBILE_DUN_RETRY_INTERVAL + " ms.");
- this.dunRetryTimer.
- initWithCallback(this.setupDunConnection.bind(this),
- MOBILE_DUN_RETRY_INTERVAL, Ci.nsITimer.TYPE_ONE_SHOT);
- },
-
- _dunActiveUsers: 0,
- handleDunConnection: function(aEnable, aCallback) {
- debug("handleDunConnection: " + aEnable);
- let dun = this.getNetworkInfo(
- Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN, this._dataDefaultServiceId);
-
- if (!aEnable) {
- this._dunActiveUsers--;
- if (this._dunActiveUsers > 0) {
- debug("Dun still needed by others, do not disconnect.")
- return;
- }
-
- this.dunRetryTimes = 0;
- this.dunRetryTimer.cancel();
- this.dunConnectTimer.cancel();
- this._pendingTetheringRequests = [];
-
- if (dun && (dun.state == Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED)) {
- gRil.getRadioInterface(this._dataDefaultServiceId)
- .deactivateDataCallByType(Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN);
- }
- return;
- }
-
- this._dunActiveUsers++;
- if (!dun || (dun.state != Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED)) {
- debug("DUN data call inactive, setup dun data call!")
- this._pendingTetheringRequests.push(aCallback);
- this.dunRetryTimes = 0;
- this.setupDunConnection();
-
- return;
- }
-
- this._tetheringInterface[TETHERING_TYPE_USB].externalInterface = dun.name;
- aCallback(dun);
- },
-
- handleUSBTetheringToggle: function(aEnable) {
- debug("handleUSBTetheringToggle: " + aEnable);
- if (aEnable &&
- (this._usbTetheringAction === TETHERING_STATE_ONGOING ||
- this._usbTetheringAction === TETHERING_STATE_ACTIVE)) {
- debug("Usb tethering already connecting/connected.");
- this._usbTetheringRequestCount = 0;
- this.handlePendingWifiTetheringRequest();
- return;
- }
-
- if (!aEnable &&
- this._usbTetheringAction === TETHERING_STATE_IDLE) {
- debug("Usb tethering already disconnected.");
- this._usbTetheringRequestCount = 0;
- this.handlePendingWifiTetheringRequest();
- return;
- }
-
- if (!aEnable) {
- this.tetheringSettings[SETTINGS_USB_ENABLED] = false;
- gNetworkService.enableUsbRndis(false, this.enableUsbRndisResult.bind(this));
- return;
- }
-
- this.tetheringSettings[SETTINGS_USB_ENABLED] = true;
- this._usbTetheringAction = TETHERING_STATE_ONGOING;
-
- if (this.tetheringSettings[SETTINGS_DUN_REQUIRED]) {
- this.handleDunConnection(true, (aNetworkInfo) => {
- if (!aNetworkInfo){
- this.usbTetheringResultReport(aEnable, "Dun connection failed");
- return;
- }
- this._tetheringInterface[TETHERING_TYPE_USB].externalInterface =
- aNetworkInfo.name;
- gNetworkService.enableUsbRndis(true, this.enableUsbRndisResult.bind(this));
- });
- return;
- }
-
- if (gNetworkManager.activeNetworkInfo) {
- this._tetheringInterface[TETHERING_TYPE_USB].externalInterface =
- gNetworkManager.activeNetworkInfo.name;
- } else {
- let mobile = this.getNetworkInfo(
- Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE, this._dataDefaultServiceId);
- if (mobile && mobile.name) {
- this._tetheringInterface[TETHERING_TYPE_USB].externalInterface = mobile.name;
- }
- }
- gNetworkService.enableUsbRndis(true, this.enableUsbRndisResult.bind(this));
- },
-
- getUSBTetheringParameters: function(aEnable, aTetheringInterface) {
- let interfaceIp = this.tetheringSettings[SETTINGS_USB_IP];
- let prefix = this.tetheringSettings[SETTINGS_USB_PREFIX];
- let wifiDhcpStartIp = this.tetheringSettings[SETTINGS_WIFI_DHCPSERVER_STARTIP];
- let wifiDhcpEndIp = this.tetheringSettings[SETTINGS_WIFI_DHCPSERVER_ENDIP];
- let usbDhcpStartIp = this.tetheringSettings[SETTINGS_USB_DHCPSERVER_STARTIP];
- let usbDhcpEndIp = this.tetheringSettings[SETTINGS_USB_DHCPSERVER_ENDIP];
- let dns1 = this.tetheringSettings[SETTINGS_USB_DNS1];
- let dns2 = this.tetheringSettings[SETTINGS_USB_DNS2];
- let internalInterface = aTetheringInterface.internalInterface;
- let externalInterface = aTetheringInterface.externalInterface;
-
- // Using the default values here until application support these settings.
- if (interfaceIp == "" || prefix == "" ||
- wifiDhcpStartIp == "" || wifiDhcpEndIp == "" ||
- usbDhcpStartIp == "" || usbDhcpEndIp == "") {
- debug("Invalid subnet information.");
- return null;
- }
-
- return {
- ifname: internalInterface,
- ip: interfaceIp,
- prefix: prefix,
- wifiStartIp: wifiDhcpStartIp,
- wifiEndIp: wifiDhcpEndIp,
- usbStartIp: usbDhcpStartIp,
- usbEndIp: usbDhcpEndIp,
- dns1: dns1,
- dns2: dns2,
- internalIfname: internalInterface,
- externalIfname: externalInterface,
- enable: aEnable,
- link: aEnable ? NETWORK_INTERFACE_UP : NETWORK_INTERFACE_DOWN
- };
- },
-
- notifyError: function(aResetSettings, aCallback, aMsg) {
- if (aResetSettings) {
- let settingsLock = gSettingsService.createLock();
- // Disable wifi tethering with a useful error message for the user.
- settingsLock.set("tethering.wifi.enabled", false, null, aMsg);
- }
-
- debug("setWifiTethering: " + (aMsg ? aMsg : "success"));
-
- if (aCallback) {
- // Callback asynchronously to avoid netsted toggling.
- Services.tm.currentThread.dispatch(() => {
- aCallback.wifiTetheringEnabledChange(aMsg);
- }, Ci.nsIThread.DISPATCH_NORMAL);
- }
- },
-
- enableWifiTethering: function(aEnable, aConfig, aCallback) {
- // Fill in config's required fields.
- aConfig.ifname = this._tetheringInterface[TETHERING_TYPE_WIFI].internalInterface;
- aConfig.internalIfname = this._tetheringInterface[TETHERING_TYPE_WIFI].internalInterface;
- aConfig.externalIfname = this._tetheringInterface[TETHERING_TYPE_WIFI].externalInterface;
-
- this._wifiTetheringRequestOngoing = true;
- gNetworkService.setWifiTethering(aEnable, aConfig, (aError) => {
- // Change the tethering state to WIFI if there is no error.
- if (aEnable && !aError) {
- this.state = Ci.nsITetheringService.TETHERING_STATE_WIFI;
- } else {
- // If wifi thethering is disable, or any error happens,
- // then consider the following statements.
-
- // Check whether the state is USB now or not. If no then just change
- // it to INACTIVE, if yes then just keep it.
- // It means that don't let the disable or error of WIFI affect
- // the original active state.
- if (this.state != Ci.nsITetheringService.TETHERING_STATE_USB) {
- this.state = Ci.nsITetheringService.TETHERING_STATE_INACTIVE;
- }
-
- // Disconnect dun on error or when wifi tethering is disabled.
- if (this.tetheringSettings[SETTINGS_DUN_REQUIRED]) {
- this.handleDunConnection(false);
- }
- }
-
- if (this._manageOfflineStatus) {
- Services.io.offline = !this.isAnyConnected() &&
- (this.state ===
- Ci.nsITetheringService.TETHERING_STATE_INACTIVE);
- }
-
- let resetSettings = aError;
- debug('gNetworkService.setWifiTethering finished');
- this.notifyError(resetSettings, aCallback, aError);
- this._wifiTetheringRequestOngoing = false;
- if (this._usbTetheringRequestCount > 0) {
- debug('Perform pending USB tethering requests.');
- this.handleLastUsbTetheringRequest();
- }
- });
- },
-
- // Enable/disable WiFi tethering by sending commands to netd.
- setWifiTethering: function(aEnable, aInterfaceName, aConfig, aCallback) {
- debug("setWifiTethering: " + aEnable);
- if (!aInterfaceName) {
- this.notifyError(true, aCallback, "invalid network interface name");
- return;
- }
-
- if (!aConfig) {
- this.notifyError(true, aCallback, "invalid configuration");
- return;
- }
-
- if (this._usbTetheringRequestCount > 0) {
- // If there's still pending usb tethering request, save
- // the request params and redo |setWifiTethering| on
- // usb tethering task complete.
- debug('USB tethering request is being processed. Queue this wifi tethering request.');
- this._pendingWifiTetheringRequestArgs = Array.prototype.slice.call(arguments);
- debug('Pending args: ' + JSON.stringify(this._pendingWifiTetheringRequestArgs));
- return;
- }
-
- // Re-check again, test cases set this property later.
- this.tetheringSettings[SETTINGS_DUN_REQUIRED] =
- libcutils.property_get("ro.tethering.dun_required") === "1";
-
- if (!aEnable) {
- this.enableWifiTethering(false, aConfig, aCallback);
- return;
- }
-
- this._tetheringInterface[TETHERING_TYPE_WIFI].internalInterface =
- aInterfaceName;
-
- if (this.tetheringSettings[SETTINGS_DUN_REQUIRED]) {
- this.handleDunConnection(true, (aNetworkInfo) => {
- if (!aNetworkInfo) {
- this.notifyError(true, aCallback, "Dun connection failed");
- return;
- }
- this._tetheringInterface[TETHERING_TYPE_WIFI].externalInterface =
- aNetworkInfo.name;
- this.enableWifiTethering(true, aConfig, aCallback);
- });
- return;
- }
-
- let mobile = this.getNetworkInfo(
- Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE, this._dataDefaultServiceId);
- // Update the real interface name
- if (mobile && mobile.name) {
- this._tetheringInterface[TETHERING_TYPE_WIFI].externalInterface = mobile.name;
- }
-
- this.enableWifiTethering(true, aConfig, aCallback);
- },
-
- // Enable/disable USB tethering by sending commands to netd.
- setUSBTethering: function(aEnable, aTetheringInterface, aCallback) {
- let params = this.getUSBTetheringParameters(aEnable, aTetheringInterface);
-
- if (params === null) {
- gNetworkService.enableUsbRndis(false, function() {
- this.usbTetheringResultReport(aEnable, "Invalid parameters");
- });
- return;
- }
-
- gNetworkService.setUSBTethering(aEnable, params, aCallback);
- },
-
- getUsbInterface: function() {
- // Find the rndis interface.
- for (let i = 0; i < this.possibleInterface.length; i++) {
- try {
- let file = new FileUtils.File(KERNEL_NETWORK_ENTRY + "/" +
- this.possibleInterface[i]);
- if (file.exists()) {
- return this.possibleInterface[i];
- }
- } catch (e) {
- debug("Not " + this.possibleInterface[i] + " interface.");
- }
- }
- debug("Can't find rndis interface in possible lists.");
- return DEFAULT_USB_INTERFACE_NAME;
- },
-
- enableUsbRndisResult: function(aSuccess, aEnable) {
- if (aSuccess) {
- // If enable is false, don't find usb interface cause it is already down,
- // just use the internal interface in settings.
- if (aEnable) {
- this._tetheringInterface[TETHERING_TYPE_USB].internalInterface =
- this.getUsbInterface();
- }
- this.setUSBTethering(aEnable,
- this._tetheringInterface[TETHERING_TYPE_USB],
- this.usbTetheringResultReport.bind(this, aEnable));
- } else {
- this.usbTetheringResultReport(aEnable, "enableUsbRndisResult failure");
- throw new Error("failed to set USB Function to adb");
- }
- },
-
- usbTetheringResultReport: function(aEnable, aError) {
- this._usbTetheringRequestCount--;
-
- let settingsLock = gSettingsService.createLock();
-
- debug('usbTetheringResultReport callback. enable: ' + aEnable +
- ', error: ' + aError);
-
- // Disable tethering settings when fail to enable it.
- if (aError) {
- this.tetheringSettings[SETTINGS_USB_ENABLED] = false;
- settingsLock.set("tethering.usb.enabled", false, null);
- // Skip others request when we found an error.
- this._usbTetheringRequestCount = 0;
- this._usbTetheringAction = TETHERING_STATE_IDLE;
- // If the thethering state is WIFI now, then just keep it,
- // if not, just change the state to INACTIVE.
- // It means that don't let the error of USB affect the original active state.
- if (this.state != Ci.nsITetheringService.TETHERING_STATE_WIFI) {
- this.state = Ci.nsITetheringService.TETHERING_STATE_INACTIVE;
- }
- if (this.tetheringSettings[SETTINGS_DUN_REQUIRED]) {
- this.handleDunConnection(false);
- }
- } else {
- if (aEnable) {
- this._usbTetheringAction = TETHERING_STATE_ACTIVE;
- this.state = Ci.nsITetheringService.TETHERING_STATE_USB;
- } else {
- this._usbTetheringAction = TETHERING_STATE_IDLE;
- // If the state is now WIFI, don't let the disable of USB affect it.
- if (this.state != Ci.nsITetheringService.TETHERING_STATE_WIFI) {
- this.state = Ci.nsITetheringService.TETHERING_STATE_INACTIVE;
- }
- if (this.tetheringSettings[SETTINGS_DUN_REQUIRED]) {
- this.handleDunConnection(false);
- }
- }
-
- if (this._manageOfflineStatus) {
- Services.io.offline = !this.isAnyConnected() &&
- (this.state ===
- Ci.nsITetheringService.TETHERING_STATE_INACTIVE);
- }
-
- this.handleLastUsbTetheringRequest();
- }
- },
-
- onConnectionChangedReport: function(aSuccess, aExternalIfname) {
- debug("onConnectionChangedReport result: success " + aSuccess);
-
- if (aSuccess) {
- // Update the external interface.
- this._tetheringInterface[TETHERING_TYPE_USB].externalInterface =
- aExternalIfname;
- debug("Change the interface name to " + aExternalIfname);
- }
- },
-
- onConnectionChanged: function(aNetworkInfo) {
- if (aNetworkInfo.state != Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- debug("We are only interested in CONNECTED event");
- return;
- }
-
- if (this.tetheringSettings[SETTINGS_DUN_REQUIRED] &&
- aNetworkInfo.type === Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN) {
- this.dunConnectTimer.cancel();
- debug("DUN data call connected, process callbacks.");
- while (this._pendingTetheringRequests.length > 0) {
- let callback = this._pendingTetheringRequests.shift();
- if (typeof callback === 'function') {
- callback(aNetworkInfo);
- }
- }
- return;
- }
-
- if (!this.tetheringSettings[SETTINGS_USB_ENABLED]) {
- debug("Usb tethering settings is not enabled");
- return;
- }
-
- if (this.tetheringSettings[SETTINGS_DUN_REQUIRED] &&
- aNetworkInfo.type === Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN &&
- this._tetheringInterface[TETHERING_TYPE_USB].externalInterface ===
- aNetworkInfo.name) {
- debug("Dun required and dun interface is the same");
- return;
- }
-
- if (this._tetheringInterface[TETHERING_TYPE_USB].externalInterface ===
- gNetworkManager.activeNetworkInfo.name) {
- debug("The active interface is the same");
- return;
- }
-
- let previous = {
- internalIfname: this._tetheringInterface[TETHERING_TYPE_USB].internalInterface,
- externalIfname: this._tetheringInterface[TETHERING_TYPE_USB].externalInterface
- };
-
- let current = {
- internalIfname: this._tetheringInterface[TETHERING_TYPE_USB].internalInterface,
- externalIfname: aNetworkInfo.name
- };
-
- let callback = (() => {
- // Update external network interface.
- debug("Update upstream interface to " + aNetworkInfo.name);
- gNetworkService.updateUpStream(previous, current,
- this.onConnectionChangedReport.bind(this));
- });
-
- if (this._usbTetheringAction === TETHERING_STATE_ONGOING) {
- debug("Postpone the event and handle it when state is idle.");
- this.wantConnectionEvent = callback;
- return;
- }
- this.wantConnectionEvent = null;
-
- callback.call(this);
- },
-
- isAnyConnected: function() {
- let allNetworkInfo = gNetworkManager.allNetworkInfo;
- for (let networkId in allNetworkInfo) {
- if (allNetworkInfo.hasOwnProperty(networkId) &&
- allNetworkInfo[networkId].state === Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- return true;
- }
- }
- return false;
- },
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([TetheringService]);
diff --git a/dom/system/gonk/TetheringService.manifest b/dom/system/gonk/TetheringService.manifest
deleted file mode 100644
index b8f18dec1..000000000
--- a/dom/system/gonk/TetheringService.manifest
+++ /dev/null
@@ -1,4 +0,0 @@
-# TetheringService.js
-component {527a4121-ee5a-4651-be9c-f46f59cf7c01} TetheringService.js
-contract @mozilla.org/tethering/service;1 {527a4121-ee5a-4651-be9c-f46f59cf7c01}
-category profile-after-change TetheringService @mozilla.org/tethering/service;1
diff --git a/dom/system/gonk/TimeZoneSettingObserver.cpp b/dom/system/gonk/TimeZoneSettingObserver.cpp
deleted file mode 100644
index 512f79908..000000000
--- a/dom/system/gonk/TimeZoneSettingObserver.cpp
+++ /dev/null
@@ -1,239 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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/message_loop.h"
-#include "jsapi.h"
-#include "mozilla/dom/ScriptSettings.h"
-#include "mozilla/Attributes.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/Hal.h"
-#include "mozilla/Services.h"
-#include "mozilla/StaticPtr.h"
-#include "nsCOMPtr.h"
-#include "nsDebug.h"
-#include "nsIObserver.h"
-#include "nsIObserverService.h"
-#include "nsISettingsService.h"
-#include "nsJSUtils.h"
-#include "nsServiceManagerUtils.h"
-#include "nsString.h"
-#include "TimeZoneSettingObserver.h"
-#include "xpcpublic.h"
-#include "nsContentUtils.h"
-#include "nsPrintfCString.h"
-#include "mozilla/dom/BindingUtils.h"
-#include "mozilla/dom/SettingChangeNotificationBinding.h"
-
-#undef LOG
-#undef ERR
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Time Zone Setting" , ## args)
-#define ERR(args...) __android_log_print(ANDROID_LOG_ERROR, "Time Zone Setting" , ## args)
-
-#define TIME_TIMEZONE "time.timezone"
-#define MOZSETTINGS_CHANGED "mozsettings-changed"
-
-using namespace mozilla;
-using namespace mozilla::dom;
-
-namespace {
-
-class TimeZoneSettingObserver : public nsIObserver
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIOBSERVER
-
- TimeZoneSettingObserver();
- static nsresult SetTimeZone(const JS::Value &aValue, JSContext *aContext);
-
-protected:
- virtual ~TimeZoneSettingObserver();
-};
-
-class TimeZoneSettingCb final : public nsISettingsServiceCallback
-{
-public:
- NS_DECL_ISUPPORTS
-
- TimeZoneSettingCb() {}
-
- NS_IMETHOD Handle(const nsAString &aName, JS::Handle<JS::Value> aResult) {
-
- JSContext *cx = nsContentUtils::GetCurrentJSContext();
- NS_ENSURE_TRUE(cx, NS_OK);
-
- // If we don't have time.timezone value in the settings, we need
- // to initialize the settings based on the current system timezone
- // to make settings consistent with system. This usually happens
- // at the very first boot. After that, settings must have a value.
- if (aResult.isNull()) {
- // Get the current system time zone offset. Note that we need to
- // convert the value to a UTC representation in the format of
- // "UTC{+,-}hh:mm", so that the Gaia end can know how to interpret.
- // E.g., -480 is "UTC+08:00"; 630 is "UTC-10:30".
- int32_t timeZoneOffset = hal::GetTimezoneOffset();
- nsPrintfCString curTimeZone("UTC%+03d:%02d",
- -timeZoneOffset / 60,
- abs(timeZoneOffset) % 60);
-
- // Convert it to a JS string.
- NS_ConvertUTF8toUTF16 utf16Str(curTimeZone);
-
- JS::Rooted<JSString*> jsStr(cx, JS_NewUCStringCopyN(cx,
- utf16Str.get(),
- utf16Str.Length()));
- if (!jsStr) {
- return NS_ERROR_OUT_OF_MEMORY;
- }
-
- // Set the settings based on the current system timezone.
- nsCOMPtr<nsISettingsServiceLock> lock;
- nsCOMPtr<nsISettingsService> settingsService =
- do_GetService("@mozilla.org/settingsService;1");
- if (!settingsService) {
- ERR("Failed to get settingsLock service!");
- return NS_OK;
- }
- settingsService->CreateLock(nullptr, getter_AddRefs(lock));
- JS::Rooted<JS::Value> value(cx, JS::StringValue(jsStr));
- lock->Set(TIME_TIMEZONE, value, nullptr, nullptr);
- return NS_OK;
- }
-
- // Set the system timezone based on the current settings.
- if (aResult.isString()) {
- return TimeZoneSettingObserver::SetTimeZone(aResult, cx);
- }
-
- return NS_OK;
- }
-
- NS_IMETHOD HandleError(const nsAString &aName) {
- ERR("TimeZoneSettingCb::HandleError: %s\n", NS_LossyConvertUTF16toASCII(aName).get());
- return NS_OK;
- }
-
-protected:
- ~TimeZoneSettingCb() {}
-};
-
-NS_IMPL_ISUPPORTS(TimeZoneSettingCb, nsISettingsServiceCallback)
-
-TimeZoneSettingObserver::TimeZoneSettingObserver()
-{
- // Setup an observer to watch changes to the setting.
- nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
- if (!observerService) {
- ERR("GetObserverService failed");
- return;
- }
- nsresult rv;
- rv = observerService->AddObserver(this, MOZSETTINGS_CHANGED, false);
- if (NS_FAILED(rv)) {
- ERR("AddObserver failed");
- return;
- }
-
- // Read the 'time.timezone' setting in order to start with a known
- // value at boot time. The handle() will be called after reading.
- nsCOMPtr<nsISettingsServiceLock> lock;
- nsCOMPtr<nsISettingsService> settingsService =
- do_GetService("@mozilla.org/settingsService;1");
- if (!settingsService) {
- ERR("Failed to get settingsLock service!");
- return;
- }
- settingsService->CreateLock(nullptr, getter_AddRefs(lock));
- nsCOMPtr<nsISettingsServiceCallback> callback = new TimeZoneSettingCb();
- lock->Get(TIME_TIMEZONE, callback);
-}
-
-nsresult TimeZoneSettingObserver::SetTimeZone(const JS::Value &aValue, JSContext *aContext)
-{
- // Convert the JS value to a nsCString type.
- // The value should be a JS string like "America/Chicago" or "UTC-05:00".
- nsAutoJSString valueStr;
- if (!valueStr.init(aContext, aValue.toString())) {
- ERR("Failed to convert JS value to nsCString");
- return NS_ERROR_FAILURE;
- }
- NS_ConvertUTF16toUTF8 newTimezone(valueStr);
-
- // Hal expects opposite sign from general notations,
- // so we need to flip it.
- if (newTimezone.Find(NS_LITERAL_CSTRING("UTC+")) == 0) {
- if (!newTimezone.SetCharAt('-', 3)) {
- return NS_ERROR_FAILURE;
- }
- } else if (newTimezone.Find(NS_LITERAL_CSTRING("UTC-")) == 0) {
- if (!newTimezone.SetCharAt('+', 3)) {
- return NS_ERROR_FAILURE;
- }
- }
-
- // Set the timezone only when the system timezone is not identical.
- nsCString curTimezone = hal::GetTimezone();
- if (!curTimezone.Equals(newTimezone)) {
- hal::SetTimezone(newTimezone);
- }
-
- return NS_OK;
-}
-
-TimeZoneSettingObserver::~TimeZoneSettingObserver()
-{
- nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
- if (observerService) {
- observerService->RemoveObserver(this, MOZSETTINGS_CHANGED);
- }
-}
-
-NS_IMPL_ISUPPORTS(TimeZoneSettingObserver, nsIObserver)
-
-NS_IMETHODIMP
-TimeZoneSettingObserver::Observe(nsISupports *aSubject,
- const char *aTopic,
- const char16_t *aData)
-{
- if (strcmp(aTopic, MOZSETTINGS_CHANGED) != 0) {
- return NS_OK;
- }
-
- // Note that this function gets called for any and all settings changes,
- // so we need to carefully check if we have the one we're interested in.
- //
- // The string that we're interested in will be a JSON string that looks like:
- // {"key":"time.timezone","value":"America/Chicago"} or
- // {"key":"time.timezone","value":"UTC-05:00"}
-
- AutoSafeJSContext cx;
- RootedDictionary<SettingChangeNotification> setting(cx);
- if (!WrappedJSToDictionary(cx, aSubject, setting)) {
- return NS_OK;
- }
- if (!setting.mKey.EqualsASCII(TIME_TIMEZONE)) {
- return NS_OK;
- }
- if (!setting.mValue.isString()) {
- return NS_OK;
- }
-
- // Set the system timezone.
- return SetTimeZone(setting.mValue, cx);
-}
-
-} // namespace
-
-static mozilla::StaticRefPtr<TimeZoneSettingObserver> sTimeZoneSettingObserver;
-namespace mozilla {
-namespace system {
-void
-InitializeTimeZoneSettingObserver()
-{
- sTimeZoneSettingObserver = new TimeZoneSettingObserver();
- ClearOnShutdown(&sTimeZoneSettingObserver);
-}
-
-} // namespace system
-} // namespace mozilla
diff --git a/dom/system/gonk/TimeZoneSettingObserver.h b/dom/system/gonk/TimeZoneSettingObserver.h
deleted file mode 100644
index 08b7cebb3..000000000
--- a/dom/system/gonk/TimeZoneSettingObserver.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_timesetting_h__
-#define mozilla_system_timesetting_h__
-
-namespace mozilla {
-namespace system {
-
-// Initialize TimeZoneSettingObserver which observes the time zone change
-// event from settings service. When receiving the event, it modifies the
-// system time zone.
-void InitializeTimeZoneSettingObserver();
-
-} // namespace system
-} // namespace mozilla
-
-#endif // mozilla_system_timesetting_h__
-
diff --git a/dom/system/gonk/Volume.cpp b/dom/system/gonk/Volume.cpp
deleted file mode 100644
index f90c7b693..000000000
--- a/dom/system/gonk/Volume.cpp
+++ /dev/null
@@ -1,596 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "Volume.h"
-#include "VolumeCommand.h"
-#include "VolumeManager.h"
-#include "VolumeManagerLog.h"
-#include "nsIVolume.h"
-#include "nsXULAppAPI.h"
-
-#include <vold/ResponseCode.h>
-
-namespace mozilla {
-namespace system {
-
-#if DEBUG_VOLUME_OBSERVER
-void
-VolumeObserverList::Broadcast(Volume* const& aVolume)
-{
- uint32_t size = mObservers.Length();
- for (uint32_t i = 0; i < size; ++i) {
- LOG("VolumeObserverList::Broadcast to [%u] %p volume '%s'",
- i, mObservers[i], aVolume->NameStr());
- mObservers[i]->Notify(aVolume);
- }
-}
-#endif
-
-VolumeObserverList Volume::sEventObserverList;
-
-// We have a feature where volumes can be locked when mounted. This
-// is used to prevent a volume from being shared with the PC while
-// it is actively being used (say for storing an update image)
-//
-// We use WakeLocks (a poor choice of name, but it does what we want)
-// from the PowerManagerService to determine when we're locked.
-// In particular we'll create a wakelock called volume-NAME-GENERATION
-// (where NAME is the volume name, and GENERATION is its generation
-// number), and if this wakelock is locked, then we'll prevent a volume
-// from being shared.
-//
-// Implementation Details:
-//
-// Since the AutoMounter can only control when something gets mounted
-// and not when it gets unmounted (for example: a user pulls the SDCard)
-// and because Volume and nsVolume data structures are maintained on
-// separate threads, we have the potential for some race conditions.
-// We eliminate the race conditions by introducing the concept of a
-// generation number. Every time a volume transitions to the Mounted
-// state, it gets assigned a new generation number. Whenever the state
-// of a Volume changes, we send the updated state and current generation
-// number to the main thread where it gets updated in the nsVolume.
-//
-// Since WakeLocks can only be queried from the main-thread, the
-// nsVolumeService looks for WakeLock status changes, and forwards
-// the results to the IOThread.
-//
-// If the Volume (IOThread) receives a volume update where the generation
-// number mismatches, then the update is simply ignored.
-//
-// When a Volume (IOThread) initially becomes mounted, we assume it to
-// be locked until we get our first update from nsVolume (MainThread).
-static int32_t sMountGeneration = 0;
-
-static uint32_t sNextId = 1;
-
-// We don't get media inserted/removed events at startup. So we
-// assume it's present, and we'll be told that it's missing.
-Volume::Volume(const nsCSubstring& aName)
- : mMediaPresent(true),
- mState(nsIVolume::STATE_INIT),
- mName(aName),
- mMountGeneration(-1),
- mMountLocked(true), // Needs to agree with nsVolume::nsVolume
- mSharingEnabled(false),
- mFormatRequested(false),
- mMountRequested(false),
- mUnmountRequested(false),
- mCanBeShared(true),
- mIsSharing(false),
- mIsFormatting(false),
- mIsUnmounting(false),
- mIsRemovable(false),
- mIsHotSwappable(false),
- mId(sNextId++)
-{
- DBG("Volume %s: created", NameStr());
-}
-
-void
-Volume::Dump(const char* aLabel) const
-{
- LOG("%s: Volume: %s (%d) is %s and %s @ %s gen %d locked %d",
- aLabel,
- NameStr(),
- Id(),
- StateStr(),
- MediaPresent() ? "inserted" : "missing",
- MountPoint().get(),
- MountGeneration(),
- (int)IsMountLocked());
- LOG("%s: Sharing %s Mounting %s Formating %s Unmounting %s",
- aLabel,
- CanBeShared() ? (IsSharingEnabled() ? (IsSharing() ? "en-y" : "en-n")
- : "dis")
- : "x",
- IsMountRequested() ? "req" : "n",
- IsFormatRequested() ? (IsFormatting() ? "req-y" : "req-n")
- : (IsFormatting() ? "y" : "n"),
- IsUnmountRequested() ? (IsUnmounting() ? "req-y" : "req-n")
- : (IsUnmounting() ? "y" : "n"));
-}
-
-void
-Volume::ResolveAndSetMountPoint(const nsCSubstring& aMountPoint)
-{
- nsCString mountPoint(aMountPoint);
- char realPathBuf[PATH_MAX];
-
- // Call realpath so that we wind up with a path which is compatible with
- // functions like nsVolumeService::GetVolumeByPath.
-
- if (realpath(mountPoint.get(), realPathBuf) < 0) {
- // The path we were handed doesn't exist. Warn about it, but use it
- // anyways assuming that the user knows what they're doing.
-
- ERR("ResolveAndSetMountPoint: realpath on '%s' failed: %d",
- mountPoint.get(), errno);
- mMountPoint = mountPoint;
- } else {
- mMountPoint = realPathBuf;
- }
- DBG("Volume %s: Setting mountpoint to '%s'", NameStr(), mMountPoint.get());
-}
-
-void Volume::SetFakeVolume(const nsACString& aMountPoint)
-{
- this->mMountLocked = false;
- this->mCanBeShared = false;
- ResolveAndSetMountPoint(aMountPoint);
- SetState(nsIVolume::STATE_MOUNTED);
-}
-
-void
-Volume::SetIsSharing(bool aIsSharing)
-{
- if (aIsSharing == mIsSharing) {
- return;
- }
- mIsSharing = aIsSharing;
- LOG("Volume %s: IsSharing set to %d state %s",
- NameStr(), (int)mIsSharing, StateStr(mState));
- sEventObserverList.Broadcast(this);
-}
-
-void
-Volume::SetIsFormatting(bool aIsFormatting)
-{
- if (aIsFormatting == mIsFormatting) {
- return;
- }
- mIsFormatting = aIsFormatting;
- LOG("Volume %s: IsFormatting set to %d state %s",
- NameStr(), (int)mIsFormatting, StateStr(mState));
- if (mIsFormatting) {
- sEventObserverList.Broadcast(this);
- }
-}
-
-void
-Volume::SetIsUnmounting(bool aIsUnmounting)
-{
- if (aIsUnmounting == mIsUnmounting) {
- return;
- }
- mIsUnmounting = aIsUnmounting;
- LOG("Volume %s: IsUnmounting set to %d state %s",
- NameStr(), (int)mIsUnmounting, StateStr(mState));
- sEventObserverList.Broadcast(this);
-}
-
-void
-Volume::SetIsRemovable(bool aIsRemovable)
-{
- if (aIsRemovable == mIsRemovable) {
- return;
- }
- mIsRemovable = aIsRemovable;
- if (!mIsRemovable) {
- mIsHotSwappable = false;
- }
- LOG("Volume %s: IsRemovable set to %d state %s",
- NameStr(), (int)mIsRemovable, StateStr(mState));
- sEventObserverList.Broadcast(this);
-}
-
-void
-Volume::SetIsHotSwappable(bool aIsHotSwappable)
-{
- if (aIsHotSwappable == mIsHotSwappable) {
- return;
- }
- mIsHotSwappable = aIsHotSwappable;
- if (mIsHotSwappable) {
- mIsRemovable = true;
- }
- LOG("Volume %s: IsHotSwappable set to %d state %s",
- NameStr(), (int)mIsHotSwappable, StateStr(mState));
- sEventObserverList.Broadcast(this);
-}
-
-bool
-Volume::BoolConfigValue(const nsCString& aConfigValue, bool& aBoolValue)
-{
- if (aConfigValue.EqualsLiteral("1") ||
- aConfigValue.LowerCaseEqualsLiteral("true")) {
- aBoolValue = true;
- return true;
- }
- if (aConfigValue.EqualsLiteral("0") ||
- aConfigValue.LowerCaseEqualsLiteral("false")) {
- aBoolValue = false;
- return true;
- }
- return false;
-}
-
-void
-Volume::SetConfig(const nsCString& aConfigName, const nsCString& aConfigValue)
-{
- if (aConfigName.LowerCaseEqualsLiteral("removable")) {
- bool value = false;
- if (BoolConfigValue(aConfigValue, value)) {
- SetIsRemovable(value);
- } else {
- ERR("Volume %s: invalid value '%s' for configuration '%s'",
- NameStr(), aConfigValue.get(), aConfigName.get());
- }
- return;
- }
- if (aConfigName.LowerCaseEqualsLiteral("hotswappable")) {
- bool value = false;
- if (BoolConfigValue(aConfigValue, value)) {
- SetIsHotSwappable(value);
- } else {
- ERR("Volume %s: invalid value '%s' for configuration '%s'",
- NameStr(), aConfigValue.get(), aConfigName.get());
- }
- return;
- }
- ERR("Volume %s: invalid config '%s'", NameStr(), aConfigName.get());
-}
-
-void
-Volume::SetMediaPresent(bool aMediaPresent)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- // mMediaPresent is slightly redunant to the state, however
- // when media is removed (while Idle), we get the following:
- // 631 Volume sdcard /mnt/sdcard disk removed (179:0)
- // 605 Volume sdcard /mnt/sdcard state changed from 1 (Idle-Unmounted) to 0 (No-Media)
- //
- // And on media insertion, we get:
- // 630 Volume sdcard /mnt/sdcard disk inserted (179:0)
- // 605 Volume sdcard /mnt/sdcard state changed from 0 (No-Media) to 2 (Pending)
- // 605 Volume sdcard /mnt/sdcard state changed from 2 (Pending) to 1 (Idle-Unmounted)
- //
- // On media removal while the media is mounted:
- // 632 Volume sdcard /mnt/sdcard bad removal (179:1)
- // 605 Volume sdcard /mnt/sdcard state changed from 4 (Mounted) to 5 (Unmounting)
- // 605 Volume sdcard /mnt/sdcard state changed from 5 (Unmounting) to 1 (Idle-Unmounted)
- // 631 Volume sdcard /mnt/sdcard disk removed (179:0)
- // 605 Volume sdcard /mnt/sdcard state changed from 1 (Idle-Unmounted) to 0 (No-Media)
- //
- // When sharing with a PC, it goes Mounted -> Idle -> Shared
- // When unsharing with a PC, it goes Shared -> Idle -> Mounted
- //
- // The AutoMounter needs to know whether the media is present or not when
- // processing the Idle state.
-
- if (mMediaPresent == aMediaPresent) {
- return;
- }
-
- LOG("Volume: %s media %s", NameStr(), aMediaPresent ? "inserted" : "removed");
- mMediaPresent = aMediaPresent;
- sEventObserverList.Broadcast(this);
-}
-
-void
-Volume::SetSharingEnabled(bool aSharingEnabled)
-{
- mSharingEnabled = aSharingEnabled;
-
- LOG("SetSharingMode for volume %s to %d canBeShared = %d",
- NameStr(), (int)mSharingEnabled, (int)mCanBeShared);
- sEventObserverList.Broadcast(this);
-}
-
-void
-Volume::SetFormatRequested(bool aFormatRequested)
-{
- mFormatRequested = aFormatRequested;
-
- LOG("SetFormatRequested for volume %s to %d CanBeFormatted = %d",
- NameStr(), (int)mFormatRequested, (int)CanBeFormatted());
-}
-
-void
-Volume::SetMountRequested(bool aMountRequested)
-{
- mMountRequested = aMountRequested;
-
- LOG("SetMountRequested for volume %s to %d CanBeMounted = %d",
- NameStr(), (int)mMountRequested, (int)CanBeMounted());
-}
-
-void
-Volume::SetUnmountRequested(bool aUnmountRequested)
-{
- mUnmountRequested = aUnmountRequested;
-
- LOG("SetUnmountRequested for volume %s to %d CanBeMounted = %d",
- NameStr(), (int)mUnmountRequested, (int)CanBeMounted());
-}
-
-void
-Volume::SetState(Volume::STATE aNewState)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- if (aNewState == mState) {
- return;
- }
- if (aNewState == nsIVolume::STATE_MOUNTED) {
- mMountGeneration = ++sMountGeneration;
- LOG("Volume %s (%u): changing state from %s to %s @ '%s' (%d observers) "
- "mountGeneration = %d, locked = %d",
- NameStr(), mId, StateStr(mState),
- StateStr(aNewState), mMountPoint.get(), sEventObserverList.Length(),
- mMountGeneration, (int)mMountLocked);
- } else {
- LOG("Volume %s (%u): changing state from %s to %s (%d observers)",
- NameStr(), mId, StateStr(mState),
- StateStr(aNewState), sEventObserverList.Length());
- }
-
- switch (aNewState) {
- case nsIVolume::STATE_NOMEDIA:
- // Cover the startup case where we don't get insertion/removal events
- mMediaPresent = false;
- mIsSharing = false;
- mUnmountRequested = false;
- mMountRequested = false;
- mIsUnmounting = false;
- break;
-
- case nsIVolume::STATE_MOUNTED:
- case nsIVolume::STATE_MOUNT_FAIL:
- mMountRequested = false;
- mIsFormatting = false;
- mIsSharing = false;
- mIsUnmounting = false;
- break;
-
- case nsIVolume::STATE_FORMATTING:
- mFormatRequested = false;
- mIsFormatting = true;
- mIsSharing = false;
- mIsUnmounting = false;
- break;
-
- case nsIVolume::STATE_SHARED:
- case nsIVolume::STATE_SHAREDMNT:
- // Covers startup cases. Normally, mIsSharing would be set to true
- // when we issue the command to initiate the sharing process, but
- // it's conceivable that a volume could already be in a shared state
- // when b2g starts.
- mIsSharing = true;
- mIsUnmounting = false;
- mIsFormatting = false;
- break;
-
- case nsIVolume::STATE_UNMOUNTING:
- mIsUnmounting = true;
- mIsFormatting = false;
- mIsSharing = false;
- break;
-
- case nsIVolume::STATE_IDLE: // Fall through
- case nsIVolume::STATE_CHECKMNT: // Fall through
- default:
- break;
- }
- mState = aNewState;
- sEventObserverList.Broadcast(this);
-}
-
-void
-Volume::SetMountPoint(const nsCSubstring& aMountPoint)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- if (mMountPoint.Equals(aMountPoint)) {
- return;
- }
- ResolveAndSetMountPoint(aMountPoint);
-}
-
-void
-Volume::StartMount(VolumeResponseCallback* aCallback)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- StartCommand(new VolumeActionCommand(this, "mount", "", aCallback));
-}
-
-void
-Volume::StartUnmount(VolumeResponseCallback* aCallback)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- StartCommand(new VolumeActionCommand(this, "unmount", "force", aCallback));
-}
-
-void
-Volume::StartFormat(VolumeResponseCallback* aCallback)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- StartCommand(new VolumeActionCommand(this, "format", "", aCallback));
-}
-
-void
-Volume::StartShare(VolumeResponseCallback* aCallback)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- StartCommand(new VolumeActionCommand(this, "share", "ums", aCallback));
-}
-
-void
-Volume::StartUnshare(VolumeResponseCallback* aCallback)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- StartCommand(new VolumeActionCommand(this, "unshare", "ums", aCallback));
-}
-
-void
-Volume::StartCommand(VolumeCommand* aCommand)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- VolumeManager::PostCommand(aCommand);
-}
-
-//static
-void
-Volume::RegisterVolumeObserver(Volume::EventObserver* aObserver, const char* aName)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- sEventObserverList.AddObserver(aObserver);
-
- DBG("Added Volume Observer '%s' @%p, length = %u",
- aName, aObserver, sEventObserverList.Length());
-
- // Send an initial event to the observer (for each volume)
- size_t numVolumes = VolumeManager::NumVolumes();
- for (size_t volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = VolumeManager::GetVolume(volIndex);
- aObserver->Notify(vol);
- }
-}
-
-//static
-void
-Volume::UnregisterVolumeObserver(Volume::EventObserver* aObserver, const char* aName)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- sEventObserverList.RemoveObserver(aObserver);
-
- DBG("Removed Volume Observer '%s' @%p, length = %u",
- aName, aObserver, sEventObserverList.Length());
-}
-
-//static
-void
-Volume::UpdateMountLock(const nsACString& aVolumeName,
- const int32_t& aMountGeneration,
- const bool& aMountLocked)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- RefPtr<Volume> vol = VolumeManager::FindVolumeByName(aVolumeName);
- if (!vol || (vol->mMountGeneration != aMountGeneration)) {
- return;
- }
- if (vol->mMountLocked != aMountLocked) {
- vol->mMountLocked = aMountLocked;
- DBG("Volume::UpdateMountLock for '%s' to %d\n", vol->NameStr(), (int)aMountLocked);
- sEventObserverList.Broadcast(vol);
- }
-}
-
-void
-Volume::HandleVoldResponse(int aResponseCode, nsCWhitespaceTokenizer& aTokenizer)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- // The volume name will have already been parsed, and the tokenizer will point
- // to the token after the volume name
- switch (aResponseCode) {
- case ::ResponseCode::VolumeListResult: {
- // Each line will look something like:
- //
- // sdcard /mnt/sdcard 1
- //
- nsDependentCSubstring mntPoint(aTokenizer.nextToken());
- SetMountPoint(mntPoint);
- nsresult errCode;
- nsCString state(aTokenizer.nextToken());
- if (state.EqualsLiteral("X")) {
- // Special state for creating fake volumes which can't be shared.
- mCanBeShared = false;
- SetState(nsIVolume::STATE_MOUNTED);
- } else {
- SetState((STATE)state.ToInteger(&errCode));
- }
- break;
- }
-
- case ::ResponseCode::VolumeStateChange: {
- // Format of the line looks something like:
- //
- // Volume sdcard /mnt/sdcard state changed from 7 (Shared-Unmounted) to 1 (Idle-Unmounted)
- //
- // So we parse out the state after the string " to "
- while (aTokenizer.hasMoreTokens()) {
- nsAutoCString token(aTokenizer.nextToken());
- if (token.EqualsLiteral("to")) {
- nsresult errCode;
- token = aTokenizer.nextToken();
- STATE newState = (STATE)(token.ToInteger(&errCode));
- if (newState == nsIVolume::STATE_MOUNTED) {
- // We set the state to STATE_CHECKMNT here, and the once the
- // AutoMounter detects that the volume is actually accessible
- // then the AutoMounter will set the volume as STATE_MOUNTED.
- SetState(nsIVolume::STATE_CHECKMNT);
- } else {
- if (State() == nsIVolume::STATE_CHECKING && newState == nsIVolume::STATE_IDLE) {
- LOG("Mount of volume '%s' failed", NameStr());
- SetState(nsIVolume::STATE_MOUNT_FAIL);
- } else {
- SetState(newState);
- }
- }
- break;
- }
- }
- break;
- }
-
- case ::ResponseCode::VolumeDiskInserted:
- SetMediaPresent(true);
- break;
-
- case ::ResponseCode::VolumeDiskRemoved: // fall-thru
- case ::ResponseCode::VolumeBadRemoval:
- SetMediaPresent(false);
- break;
-
- default:
- LOG("Volume: %s unrecognized reponse code (ignored)", NameStr());
- break;
- }
-}
-
-} // namespace system
-} // namespace mozilla
diff --git a/dom/system/gonk/Volume.h b/dom/system/gonk/Volume.h
deleted file mode 100644
index 821292a9a..000000000
--- a/dom/system/gonk/Volume.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_volume_h__
-#define mozilla_system_volume_h__
-
-#include "VolumeCommand.h"
-#include "nsIVolume.h"
-#include "nsString.h"
-#include "mozilla/Observer.h"
-#include "nsISupportsImpl.h"
-#include "nsWhitespaceTokenizer.h"
-
-namespace mozilla {
-namespace system {
-
-/***************************************************************************
-*
-* There is an instance of the Volume class for each volume reported
-* from vold.
-*
-* Each volume originates from the /system/etv/vold.fstab file.
-*
-***************************************************************************/
-
-class Volume;
-
-#define DEBUG_VOLUME_OBSERVER 0
-
-#if DEBUG_VOLUME_OBSERVER
-class VolumeObserverList : public mozilla::ObserverList<Volume*>
-{
-public:
- void Broadcast(Volume* const& aVolume);
-};
-#else
-typedef mozilla::ObserverList<Volume*> VolumeObserverList;
-#endif
-
-class Volume final
-{
-public:
- NS_INLINE_DECL_REFCOUNTING(Volume)
-
- Volume(const nsCSubstring& aVolumeName);
-
- typedef long STATE; // States are now defined in nsIVolume.idl
-
- static const char* StateStr(STATE aState) { return NS_VolumeStateStr(aState); }
- const char* StateStr() const { return StateStr(mState); }
- STATE State() const { return mState; }
-
- const nsCString& Name() const { return mName; }
- const char* NameStr() const { return mName.get(); }
-
- void Dump(const char* aLabel) const;
-
- // The mount point is the name of the directory where the volume is mounted.
- // (i.e. path that leads to the files stored on the volume).
- const nsCString& MountPoint() const { return mMountPoint; }
-
- uint32_t Id() const { return mId; }
-
- int32_t MountGeneration() const { return mMountGeneration; }
- bool IsMountLocked() const { return mMountLocked; }
- bool MediaPresent() const { return mMediaPresent; }
- bool CanBeShared() const { return mCanBeShared; }
- bool CanBeFormatted() const { return CanBeShared(); }
- bool CanBeMounted() const { return CanBeShared(); }
- bool IsSharingEnabled() const { return mCanBeShared && mSharingEnabled; }
- bool IsFormatRequested() const { return CanBeFormatted() && mFormatRequested; }
- bool IsMountRequested() const { return CanBeMounted() && mMountRequested; }
- bool IsUnmountRequested() const { return CanBeMounted() && mUnmountRequested; }
- bool IsSharing() const { return mIsSharing; }
- bool IsFormatting() const { return mIsFormatting; }
- bool IsUnmounting() const { return mIsUnmounting; }
- bool IsRemovable() const { return mIsRemovable; }
- bool IsHotSwappable() const { return mIsHotSwappable; }
-
- void SetFakeVolume(const nsACString& aMountPoint);
-
- void SetSharingEnabled(bool aSharingEnabled);
- void SetFormatRequested(bool aFormatRequested);
- void SetMountRequested(bool aMountRequested);
- void SetUnmountRequested(bool aUnmountRequested);
-
- typedef mozilla::Observer<Volume *> EventObserver;
-
- // NOTE: that observers must live in the IOThread.
- static void RegisterVolumeObserver(EventObserver* aObserver, const char* aName);
- static void UnregisterVolumeObserver(EventObserver* aObserver, const char* aName);
-
-protected:
- ~Volume() {}
-
-private:
- friend class AutoMounter; // Calls StartXxx
- friend class nsVolume; // Calls UpdateMountLock
- friend class VolumeManager; // Calls HandleVoldResponse
- friend class VolumeListCallback; // Calls SetMountPoint, SetState
-
- // The StartXxx functions will queue up a command to the VolumeManager.
- // You can queue up as many commands as you like, and aCallback will
- // be called as each one completes.
- void StartMount(VolumeResponseCallback* aCallback);
- void StartUnmount(VolumeResponseCallback* aCallback);
- void StartFormat(VolumeResponseCallback* aCallback);
- void StartShare(VolumeResponseCallback* aCallback);
- void StartUnshare(VolumeResponseCallback* aCallback);
-
- void SetIsSharing(bool aIsSharing);
- void SetIsFormatting(bool aIsFormatting);
- void SetIsUnmounting(bool aIsUnmounting);
- void SetIsRemovable(bool aIsRemovable);
- void SetIsHotSwappable(bool aIsHotSwappable);
- void SetState(STATE aNewState);
- void SetMediaPresent(bool aMediaPresent);
- void SetMountPoint(const nsCSubstring& aMountPoint);
- void StartCommand(VolumeCommand* aCommand);
-
- void ResolveAndSetMountPoint(const nsCSubstring& aMountPoint);
-
- bool BoolConfigValue(const nsCString& aConfigValue, bool& aBoolValue);
- void SetConfig(const nsCString& aConfigName, const nsCString& aConfigValue);
-
- void HandleVoldResponse(int aResponseCode, nsCWhitespaceTokenizer& aTokenizer);
-
- static void UpdateMountLock(const nsACString& aVolumeName,
- const int32_t& aMountGeneration,
- const bool& aMountLocked);
-
- bool mMediaPresent;
- STATE mState;
- const nsCString mName;
- nsCString mMountPoint;
- int32_t mMountGeneration;
- bool mMountLocked;
- bool mSharingEnabled;
- bool mFormatRequested;
- bool mMountRequested;
- bool mUnmountRequested;
- bool mCanBeShared;
- bool mIsSharing;
- bool mIsFormatting;
- bool mIsUnmounting;
- bool mIsRemovable;
- bool mIsHotSwappable;
- uint32_t mId; // Unique ID (used by MTP)
-
- static VolumeObserverList sEventObserverList;
-};
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_volumemanager_h__
diff --git a/dom/system/gonk/VolumeCommand.cpp b/dom/system/gonk/VolumeCommand.cpp
deleted file mode 100644
index 8095956a7..000000000
--- a/dom/system/gonk/VolumeCommand.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsString.h"
-#include "nsWhitespaceTokenizer.h"
-
-#include "Volume.h"
-#include "VolumeCommand.h"
-#include "VolumeManager.h"
-#include "VolumeManagerLog.h"
-
-namespace mozilla {
-namespace system {
-
-/***************************************************************************
-*
-* The VolumeActionCommand class is used to send commands which apply
-* to a particular volume.
-*
-* The following commands would fit into this category:
-*
-* volume mount <volname>
-* volume unmount <volname> [force]
-* volume format <volname>
-* volume share <volname> <method>
-* volume unshare <volname> <method>
-* volume shared <volname> <method>
-*
-* A typical response looks like:
-*
-* # vdc volume unshare sdcard ums
-* 605 Volume sdcard /mnt/sdcard state changed from 7 (Shared-Unmounted) to 1 (Idle-Unmounted)
-* 200 volume operation succeeded
-*
-* Note that the 600 series of responses are considered unsolicited and
-* are dealt with directly by the VolumeManager. This command will only
-* see the terminating response code (200 in the example above).
-*
-***************************************************************************/
-
-VolumeActionCommand::VolumeActionCommand(Volume* aVolume,
- const char* aAction,
- const char* aExtraArgs,
- VolumeResponseCallback* aCallback)
- : VolumeCommand(aCallback),
- mVolume(aVolume)
-{
- nsAutoCString cmd;
-
- cmd = "volume ";
- cmd += aAction;
- cmd += " ";
- cmd += aVolume->Name().get();
-
- // vold doesn't like trailing white space, so only add it if we really need to.
- if (aExtraArgs && (*aExtraArgs != '\0')) {
- cmd += " ";
- cmd += aExtraArgs;
- }
- SetCmd(cmd);
-}
-
-/***************************************************************************
-*
-* The VolumeListCommand class is used to send the "volume list" command to
-* vold.
-*
-* A typical response looks like:
-*
-* # vdc volume list
-* 110 sdcard /mnt/sdcard 4
-* 110 sdcard1 /mnt/sdcard/external_sd 4
-* 200 Volumes listed.
-*
-***************************************************************************/
-
-VolumeListCommand::VolumeListCommand(VolumeResponseCallback* aCallback)
- : VolumeCommand(NS_LITERAL_CSTRING("volume list"), aCallback)
-{
-}
-
-} // system
-} // mozilla
-
diff --git a/dom/system/gonk/VolumeCommand.h b/dom/system/gonk/VolumeCommand.h
deleted file mode 100644
index 022965b5e..000000000
--- a/dom/system/gonk/VolumeCommand.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_volumecommand_h__
-#define mozilla_system_volumecommand_h__
-
-#include "nsString.h"
-#include "nsISupportsImpl.h"
-#include "mozilla/RefPtr.h"
-#include <algorithm>
-#include <vold/ResponseCode.h>
-
-namespace mozilla {
-namespace system {
-
-class Volume;
-class VolumeCommand;
-
-/***************************************************************************
-*
-* The VolumeResponseCallback class is an abstract base class. The ResponseReceived
-* method will be called for each response received.
-*
-* Depending on the command, there may be multiple responses for the
-* command. Done() will return true if this is the last response.
-*
-* The responses from vold are all of the form:
-*
-* <ResponseCode> <String>
-*
-* Valid Response codes can be found in the vold/ResponseCode.h header.
-*
-***************************************************************************/
-
-class VolumeResponseCallback
-{
-protected:
- virtual ~VolumeResponseCallback() {}
-
-public:
- NS_INLINE_DECL_REFCOUNTING(VolumeResponseCallback)
- VolumeResponseCallback()
- : mResponseCode(0), mPending(false) {}
-
- bool Done() const
- {
- // Response codes from the 200, 400, and 500 series all indicated that
- // the command has completed.
-
- return (mResponseCode >= ::ResponseCode::CommandOkay)
- && (mResponseCode < ::ResponseCode::UnsolicitedInformational);
- }
-
- bool WasSuccessful() const
- {
- return mResponseCode == ::ResponseCode::CommandOkay;
- }
-
- bool IsPending() const { return mPending; }
- int ResponseCode() const { return mResponseCode; }
- const nsCString &ResponseStr() const { return mResponseStr; }
-
-protected:
- virtual void ResponseReceived(const VolumeCommand* aCommand) = 0;
-
-private:
- friend class VolumeCommand; // Calls HandleResponse and SetPending
-
- void HandleResponse(const VolumeCommand* aCommand,
- int aResponseCode,
- nsACString& aResponseStr)
- {
- mResponseCode = aResponseCode;
-#if ANDROID_VERSION >= 17
- // There's a sequence number here that we don't care about
- // We expect it to be 0. See VolumeCommand::SetCmd
- mResponseStr = Substring(aResponseStr, 2);
-#else
- mResponseStr = aResponseStr;
-#endif
- if (mResponseCode >= ::ResponseCode::CommandOkay) {
- // This is a final response.
- mPending = false;
- }
- ResponseReceived(aCommand);
- }
-
- void SetPending(bool aPending) { mPending = aPending; }
-
- int mResponseCode; // The response code parsed from vold
- nsCString mResponseStr; // The rest of the line.
- bool mPending; // Waiting for response?
-};
-
-/***************************************************************************
-*
-* The VolumeCommand class is an abstract base class used to encapsulate
-* volume commands send to vold.
-*
-* See VolumeManager.h for a list of the volume commands.
-*
-* Commands sent to vold need an explicit null character so we add one
-* to the command to ensure that it's included in the length.
-*
-* All of these commands are asynchronous in nature, and the
-* ResponseReceived callback will be called when a response is available.
-*
-***************************************************************************/
-
-class VolumeCommand
-{
-protected:
- virtual ~VolumeCommand() {}
-
-public:
- NS_INLINE_DECL_REFCOUNTING(VolumeCommand)
-
- VolumeCommand(VolumeResponseCallback* aCallback)
- : mBytesConsumed(0),
- mCallback(aCallback)
- {
- SetCmd(NS_LITERAL_CSTRING(""));
- }
-
- VolumeCommand(const nsACString& aCommand, VolumeResponseCallback* aCallback)
- : mBytesConsumed(0),
- mCallback(aCallback)
- {
- SetCmd(aCommand);
- }
-
- void SetCmd(const nsACString& aCommand)
- {
- mCmd.Truncate();
-#if ANDROID_VERSION >= 17
- // JB requires a sequence number at the beginning of messages.
- // It doesn't matter what we use, so we use 0.
- mCmd = "0 ";
-#endif
- mCmd.Append(aCommand);
- // Add a null character. We want this to be included in the length since
- // vold uses it to determine the end of the command.
- mCmd.Append('\0');
- }
-
- const char* CmdStr() const { return mCmd.get(); }
- const char* Data() const { return mCmd.Data() + mBytesConsumed; }
- size_t BytesConsumed() const { return mBytesConsumed; }
-
- size_t BytesRemaining() const
- {
- return mCmd.Length() - std::min(mCmd.Length(), mBytesConsumed);
- }
-
- void ConsumeBytes(size_t aNumBytes)
- {
- mBytesConsumed += std::min(BytesRemaining(), aNumBytes);
- }
-
-private:
- friend class VolumeManager; // Calls SetPending & HandleResponse
-
- void SetPending(bool aPending)
- {
- if (mCallback) {
- mCallback->SetPending(aPending);
- }
- }
-
- void HandleResponse(int aResponseCode, nsACString& aResponseStr)
- {
- if (mCallback) {
- mCallback->HandleResponse(this, aResponseCode, aResponseStr);
- }
- }
-
- nsCString mCmd; // Command being sent
- size_t mBytesConsumed; // How many bytes have been sent
-
- // Called when a response to the command is received.
- RefPtr<VolumeResponseCallback> mCallback;
-};
-
-class VolumeActionCommand : public VolumeCommand
-{
-public:
- VolumeActionCommand(Volume* aVolume, const char* aAction,
- const char* aExtraArgs, VolumeResponseCallback* aCallback);
-
-private:
- RefPtr<Volume> mVolume;
-};
-
-class VolumeListCommand : public VolumeCommand
-{
-public:
- VolumeListCommand(VolumeResponseCallback* aCallback);
-};
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_volumecommand_h__
diff --git a/dom/system/gonk/VolumeManager.cpp b/dom/system/gonk/VolumeManager.cpp
deleted file mode 100644
index ddfa7af09..000000000
--- a/dom/system/gonk/VolumeManager.cpp
+++ /dev/null
@@ -1,591 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "VolumeManager.h"
-
-#include "Volume.h"
-#include "VolumeCommand.h"
-#include "VolumeManagerLog.h"
-#include "VolumeServiceTest.h"
-
-#include "nsWhitespaceTokenizer.h"
-#include "nsXULAppAPI.h"
-
-#include "base/message_loop.h"
-#include "base/task.h"
-#include "mozilla/Scoped.h"
-#include "mozilla/StaticPtr.h"
-
-#include <android/log.h>
-#include <cutils/sockets.h>
-#include <fcntl.h>
-#include <sys/socket.h>
-
-namespace mozilla {
-namespace system {
-
-static StaticRefPtr<VolumeManager> sVolumeManager;
-
-VolumeManager::STATE VolumeManager::mState = VolumeManager::UNINITIALIZED;
-VolumeManager::StateObserverList VolumeManager::mStateObserverList;
-
-/***************************************************************************/
-
-VolumeManager::VolumeManager()
- : LineWatcher('\0', kRcvBufSize),
- mSocket(-1),
- mCommandPending(false)
-{
- DBG("VolumeManager constructor called");
-}
-
-VolumeManager::~VolumeManager()
-{
-}
-
-//static
-void
-VolumeManager::Dump(const char* aLabel)
-{
- if (!sVolumeManager) {
- LOG("%s: sVolumeManager == null", aLabel);
- return;
- }
-
- VolumeArray::size_type numVolumes = NumVolumes();
- VolumeArray::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = GetVolume(volIndex);
- vol->Dump(aLabel);
- }
-}
-
-//static
-size_t
-VolumeManager::NumVolumes()
-{
- if (!sVolumeManager) {
- return 0;
- }
- return sVolumeManager->mVolumeArray.Length();
-}
-
-//static
-already_AddRefed<Volume>
-VolumeManager::GetVolume(size_t aIndex)
-{
- MOZ_ASSERT(aIndex < NumVolumes());
- RefPtr<Volume> vol = sVolumeManager->mVolumeArray[aIndex];
- return vol.forget();
-}
-
-//static
-VolumeManager::STATE
-VolumeManager::State()
-{
- return mState;
-}
-
-//static
-const char *
-VolumeManager::StateStr(VolumeManager::STATE aState)
-{
- switch (aState) {
- case UNINITIALIZED: return "Uninitialized";
- case STARTING: return "Starting";
- case VOLUMES_READY: return "Volumes Ready";
- }
- return "???";
-}
-
-
-//static
-void
-VolumeManager::SetState(STATE aNewState)
-{
- if (mState != aNewState) {
- LOG("changing state from '%s' to '%s'",
- StateStr(mState), StateStr(aNewState));
- mState = aNewState;
- mStateObserverList.Broadcast(StateChangedEvent());
- }
-}
-
-//static
-void
-VolumeManager::RegisterStateObserver(StateObserver* aObserver)
-{
- mStateObserverList.AddObserver(aObserver);
-}
-
-//static
-void VolumeManager::UnregisterStateObserver(StateObserver* aObserver)
-{
- mStateObserverList.RemoveObserver(aObserver);
-}
-
-//static
-already_AddRefed<Volume>
-VolumeManager::FindVolumeByName(const nsCSubstring& aName)
-{
- if (!sVolumeManager) {
- return nullptr;
- }
- VolumeArray::size_type numVolumes = NumVolumes();
- VolumeArray::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = GetVolume(volIndex);
- if (vol->Name().Equals(aName)) {
- return vol.forget();
- }
- }
- return nullptr;
-}
-
-//static
-already_AddRefed<Volume>
-VolumeManager::FindAddVolumeByName(const nsCSubstring& aName)
-{
- RefPtr<Volume> vol = FindVolumeByName(aName);
- if (vol) {
- return vol.forget();
- }
- // No volume found, create and add a new one.
- vol = new Volume(aName);
- sVolumeManager->mVolumeArray.AppendElement(vol);
- return vol.forget();
-}
-
-//static
-bool
-VolumeManager::RemoveVolumeByName(const nsCSubstring& aName)
-{
- if (!sVolumeManager) {
- return false;
- }
- VolumeArray::size_type numVolumes = NumVolumes();
- VolumeArray::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = GetVolume(volIndex);
- if (vol->Name().Equals(aName)) {
- sVolumeManager->mVolumeArray.RemoveElementAt(volIndex);
- return true;
- }
- }
- // No volume found. Return false to indicate this.
- return false;
-}
-
-
-//static
-void VolumeManager::InitConfig()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- // This function uses /system/etc/volume.cfg to add additional volumes
- // to the Volume Manager.
- //
- // This is useful on devices like the Nexus 4, which have no physical sd card
- // or dedicated partition.
- //
- // The format of the volume.cfg file is as follows:
- // create volume-name mount-point
- // configure volume-name preference preference-value
- // Blank lines and lines starting with the hash character "#" will be ignored.
-
- ScopedCloseFile fp;
- int n = 0;
- char line[255];
- const char *filename = "/system/etc/volume.cfg";
- if (!(fp = fopen(filename, "r"))) {
- LOG("Unable to open volume configuration file '%s' - ignoring", filename);
- return;
- }
- while(fgets(line, sizeof(line), fp)) {
- n++;
-
- if (line[0] == '#')
- continue;
-
- nsCString commandline(line);
- nsCWhitespaceTokenizer tokenizer(commandline);
- if (!tokenizer.hasMoreTokens()) {
- // Blank line - ignore
- continue;
- }
-
- nsCString command(tokenizer.nextToken());
- if (command.EqualsLiteral("create")) {
- if (!tokenizer.hasMoreTokens()) {
- ERR("No vol_name in %s line %d", filename, n);
- continue;
- }
- nsCString volName(tokenizer.nextToken());
- if (!tokenizer.hasMoreTokens()) {
- ERR("No mount point for volume '%s'. %s line %d",
- volName.get(), filename, n);
- continue;
- }
- nsCString mountPoint(tokenizer.nextToken());
- RefPtr<Volume> vol = FindAddVolumeByName(volName);
- vol->SetFakeVolume(mountPoint);
- continue;
- }
- if (command.EqualsLiteral("configure")) {
- if (!tokenizer.hasMoreTokens()) {
- ERR("No vol_name in %s line %d", filename, n);
- continue;
- }
- nsCString volName(tokenizer.nextToken());
- if (!tokenizer.hasMoreTokens()) {
- ERR("No configuration name specified for volume '%s'. %s line %d",
- volName.get(), filename, n);
- continue;
- }
- nsCString configName(tokenizer.nextToken());
- if (!tokenizer.hasMoreTokens()) {
- ERR("No value for configuration name '%s'. %s line %d",
- configName.get(), filename, n);
- continue;
- }
- nsCString configValue(tokenizer.nextToken());
- RefPtr<Volume> vol = FindVolumeByName(volName);
- if (vol) {
- vol->SetConfig(configName, configValue);
- } else {
- ERR("Invalid volume name '%s'.", volName.get());
- }
- continue;
- }
- if (command.EqualsLiteral("ignore")) {
- // This command is useful to remove volumes which are being tracked by
- // vold, but for which we have no interest.
- if (!tokenizer.hasMoreTokens()) {
- ERR("No vol_name in %s line %d", filename, n);
- continue;
- }
- nsCString volName(tokenizer.nextToken());
- RemoveVolumeByName(volName);
- continue;
- }
- ERR("Unrecognized command: '%s'", command.get());
- }
-}
-
-void
-VolumeManager::DefaultConfig()
-{
-
- VolumeManager::VolumeArray::size_type numVolumes = VolumeManager::NumVolumes();
- if (numVolumes == 0) {
- return;
- }
- if (numVolumes == 1) {
- // This is to cover early shipping phones like the Buri,
- // which had no internal storage, and only external sdcard.
- //
- // Phones line the nexus-4 which only have an internal
- // storage area will need to have a volume.cfg file with
- // removable set to false.
- RefPtr<Volume> vol = VolumeManager::GetVolume(0);
- vol->SetIsRemovable(true);
- vol->SetIsHotSwappable(true);
- return;
- }
- VolumeManager::VolumeArray::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = VolumeManager::GetVolume(volIndex);
- if (!vol->Name().EqualsLiteral("sdcard")) {
- vol->SetIsRemovable(true);
- vol->SetIsHotSwappable(true);
- }
- }
-}
-
-class VolumeListCallback : public VolumeResponseCallback
-{
- virtual void ResponseReceived(const VolumeCommand* aCommand)
- {
- switch (ResponseCode()) {
- case ::ResponseCode::VolumeListResult: {
- // Each line will look something like:
- //
- // sdcard /mnt/sdcard 1
- //
- // So for each volume that we get back, we update any volumes that
- // we have of the same name, or add new ones if they don't exist.
- nsCWhitespaceTokenizer tokenizer(ResponseStr());
- nsDependentCSubstring volName(tokenizer.nextToken());
- RefPtr<Volume> vol = VolumeManager::FindAddVolumeByName(volName);
- vol->HandleVoldResponse(ResponseCode(), tokenizer);
- break;
- }
-
- case ::ResponseCode::CommandOkay: {
- // We've received the list of volumes. Now read the Volume.cfg
- // file to perform customizations, and then tell everybody
- // that we're ready for business.
- VolumeManager::DefaultConfig();
- VolumeManager::InitConfig();
- VolumeManager::Dump("READY");
- VolumeManager::SetState(VolumeManager::VOLUMES_READY);
- break;
- }
- }
- }
-};
-
-bool
-VolumeManager::OpenSocket()
-{
- SetState(STARTING);
- if ((mSocket.rwget() = socket_local_client("vold",
- ANDROID_SOCKET_NAMESPACE_RESERVED,
- SOCK_STREAM)) < 0) {
- ERR("Error connecting to vold: (%s) - will retry", strerror(errno));
- return false;
- }
- // add FD_CLOEXEC flag
- int flags = fcntl(mSocket.get(), F_GETFD);
- if (flags == -1) {
- return false;
- }
- flags |= FD_CLOEXEC;
- if (fcntl(mSocket.get(), F_SETFD, flags) == -1) {
- return false;
- }
- // set non-blocking
- if (fcntl(mSocket.get(), F_SETFL, O_NONBLOCK) == -1) {
- return false;
- }
- if (!MessageLoopForIO::current()->
- WatchFileDescriptor(mSocket.get(),
- true,
- MessageLoopForIO::WATCH_READ,
- &mReadWatcher,
- this)) {
- return false;
- }
-
- LOG("Connected to vold");
- PostCommand(new VolumeListCommand(new VolumeListCallback));
- return true;
-}
-
-//static
-void
-VolumeManager::PostCommand(VolumeCommand* aCommand)
-{
- if (!sVolumeManager) {
- ERR("VolumeManager not initialized. Dropping command '%s'", aCommand->Data());
- return;
- }
- aCommand->SetPending(true);
-
- DBG("Sending command '%s'", aCommand->Data());
- // vold can only process one command at a time, so add our command
- // to the end of the command queue.
- sVolumeManager->mCommands.push(aCommand);
- if (!sVolumeManager->mCommandPending) {
- // There aren't any commands currently being processed, so go
- // ahead and kick this one off.
- sVolumeManager->mCommandPending = true;
- sVolumeManager->WriteCommandData();
- }
-}
-
-/***************************************************************************
-* The WriteCommandData initiates sending of a command to vold. Since
-* we're running on the IOThread and not allowed to block, WriteCommandData
-* will write as much data as it can, and if not all of the data can be
-* written then it will setup a file descriptor watcher and
-* OnFileCanWriteWithoutBlocking will call WriteCommandData to write out
-* more of the command data.
-*/
-void
-VolumeManager::WriteCommandData()
-{
- if (mCommands.size() == 0) {
- return;
- }
-
- VolumeCommand* cmd = mCommands.front();
- if (cmd->BytesRemaining() == 0) {
- // All bytes have been written. We're waiting for a response.
- return;
- }
- // There are more bytes left to write. Try to write them all.
- ssize_t bytesWritten = write(mSocket.get(), cmd->Data(), cmd->BytesRemaining());
- if (bytesWritten < 0) {
- ERR("Failed to write %d bytes to vold socket", cmd->BytesRemaining());
- Restart();
- return;
- }
- DBG("Wrote %d bytes (of %d)", bytesWritten, cmd->BytesRemaining());
- cmd->ConsumeBytes(bytesWritten);
- if (cmd->BytesRemaining() == 0) {
- return;
- }
- // We were unable to write all of the command bytes. Setup a watcher
- // so we'll get called again when we can write without blocking.
- if (!MessageLoopForIO::current()->
- WatchFileDescriptor(mSocket.get(),
- false, // one-shot
- MessageLoopForIO::WATCH_WRITE,
- &mWriteWatcher,
- this)) {
- ERR("Failed to setup write watcher for vold socket");
- Restart();
- }
-}
-
-void
-VolumeManager::OnLineRead(int aFd, nsDependentCSubstring& aMessage)
-{
- MOZ_ASSERT(aFd == mSocket.get());
- char* endPtr;
- int responseCode = strtol(aMessage.Data(), &endPtr, 10);
- if (*endPtr == ' ') {
- endPtr++;
- }
-
- // Now fish out the rest of the line after the response code
- nsDependentCString responseLine(endPtr, aMessage.Length() - (endPtr - aMessage.Data()));
- DBG("Rcvd: %d '%s'", responseCode, responseLine.Data());
-
- if (responseCode >= ::ResponseCode::UnsolicitedInformational) {
- // These are unsolicited broadcasts. We intercept these and process
- // them ourselves
- HandleBroadcast(responseCode, responseLine);
- } else {
- // Everything else is considered to be part of the command response.
- if (mCommands.size() > 0) {
- VolumeCommand* cmd = mCommands.front();
- cmd->HandleResponse(responseCode, responseLine);
- if (responseCode >= ::ResponseCode::CommandOkay) {
- // That's a terminating response. We can remove the command.
- mCommands.pop();
- mCommandPending = false;
- // Start the next command, if there is one.
- WriteCommandData();
- }
- } else {
- ERR("Response with no command");
- }
- }
-}
-
-void
-VolumeManager::OnFileCanWriteWithoutBlocking(int aFd)
-{
- MOZ_ASSERT(aFd == mSocket.get());
- WriteCommandData();
-}
-
-void
-VolumeManager::HandleBroadcast(int aResponseCode, nsCString& aResponseLine)
-{
- // Format of the line is something like:
- //
- // Volume sdcard /mnt/sdcard state changed from 7 (Shared-Unmounted) to 1 (Idle-Unmounted)
- //
- // So we parse out the volume name and the state after the string " to "
- nsCWhitespaceTokenizer tokenizer(aResponseLine);
- tokenizer.nextToken(); // The word "Volume"
- nsDependentCSubstring volName(tokenizer.nextToken());
-
- RefPtr<Volume> vol = FindVolumeByName(volName);
- if (!vol) {
- return;
- }
- vol->HandleVoldResponse(aResponseCode, tokenizer);
-}
-
-void
-VolumeManager::Restart()
-{
- mReadWatcher.StopWatchingFileDescriptor();
- mWriteWatcher.StopWatchingFileDescriptor();
-
- while (!mCommands.empty()) {
- mCommands.pop();
- }
- mCommandPending = false;
- mSocket.dispose();
- Start();
-}
-
-//static
-void
-VolumeManager::Start()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- if (!sVolumeManager) {
- return;
- }
- SetState(STARTING);
- if (!sVolumeManager->OpenSocket()) {
- // Socket open failed, try again in a second.
- MessageLoopForIO::current()->
- PostDelayedTask(NewRunnableFunction(VolumeManager::Start),
- 1000);
- }
-}
-
-void
-VolumeManager::OnError()
-{
- Restart();
-}
-
-/***************************************************************************/
-
-static void
-InitVolumeManagerIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(!sVolumeManager);
-
- sVolumeManager = new VolumeManager();
- VolumeManager::Start();
-
- InitVolumeServiceTestIOThread();
-}
-
-static void
-ShutdownVolumeManagerIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- sVolumeManager = nullptr;
-}
-
-/**************************************************************************
-*
-* Public API
-*
-* Since the VolumeManager runs in IO Thread context, we need to switch
-* to IOThread context before we can do anything.
-*
-**************************************************************************/
-
-void
-InitVolumeManager()
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(InitVolumeManagerIOThread));
-}
-
-void
-ShutdownVolumeManager()
-{
- ShutdownVolumeServiceTest();
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(ShutdownVolumeManagerIOThread));
-}
-
-} // system
-} // mozilla
diff --git a/dom/system/gonk/VolumeManager.h b/dom/system/gonk/VolumeManager.h
deleted file mode 100644
index 7c0503389..000000000
--- a/dom/system/gonk/VolumeManager.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_volumemanager_h__
-#define mozilla_system_volumemanager_h__
-
-#include <vector>
-#include <queue>
-
-#include "base/message_loop.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/Observer.h"
-#include "nsISupportsImpl.h"
-#include "nsString.h"
-#include "nsTArray.h"
-
-#include "Volume.h"
-#include "VolumeCommand.h"
-
-namespace mozilla {
-namespace system {
-
-/***************************************************************************
-*
-* All of the public API mentioned in this file (unless otherwise
-* mentioned) must run from the IOThread.
-*
-***************************************************************************/
-
-/***************************************************************************
-*
-* The VolumeManager class is a front-end for android's vold service.
-*
-* Vold uses a unix socket interface and accepts null-terminated string
-* commands. The following commands were determined by examining the vold
-* source code:
-*
-* volume list
-* volume mount <volname>
-* volume unmount <volname> [force]
-* volume debug [on|off]
-* volume format <volname>
-* volume share <volname> <method>
-* volume unshare <volname> <method>
-* volume shared <volname> <method>
-*
-* <volname> is the name of the volume as used in /system/etc/vold.fstab
-* <method> is ums
-*
-* dump
-*
-* share status <method> (Determines if a particular sharing method is available)
-* (GB only - not available in ICS)
-*
-* storage users (??? always crashes vold ???)
-*
-* asec list
-* asec ...lots more...
-*
-* obb list
-* obb ...lots more...
-*
-* xwarp enable
-* xwarp disable
-* xwarp status
-*
-* There is also a command line tool called vdc, which can be used to send
-* the above commands to vold.
-*
-* Currently, only the volume list, share/unshare, and mount/unmount
-* commands are being used.
-*
-***************************************************************************/
-
-class VolumeManager final : public MessageLoopForIO::LineWatcher
-{
- virtual ~VolumeManager();
-
-public:
- NS_INLINE_DECL_REFCOUNTING(VolumeManager)
-
- typedef nsTArray<RefPtr<Volume>> VolumeArray;
-
- VolumeManager();
-
- //-----------------------------------------------------------------------
- //
- // State related methods.
- //
- // The VolumeManager starts off in the STARTING state. Once a connection
- // is established with vold, it asks for a list of volumes, and once the
- // volume list has been received, then the VolumeManager enters the
- // VOLUMES_READY state.
- //
- // If vold crashes, then the VolumeManager will once again enter the
- // STARTING state and try to reestablish a connection with vold.
-
- enum STATE
- {
- UNINITIALIZED,
- STARTING,
- VOLUMES_READY
- };
-
- static STATE State();
- static const char* StateStr(STATE aState);
- static const char* StateStr() { return StateStr(State()); }
-
- class StateChangedEvent
- {
- public:
- StateChangedEvent() {}
- };
-
- typedef mozilla::Observer<StateChangedEvent> StateObserver;
- typedef mozilla::ObserverList<StateChangedEvent> StateObserverList;
-
- static void RegisterStateObserver(StateObserver* aObserver);
- static void UnregisterStateObserver(StateObserver* aObserver);
-
- //-----------------------------------------------------------------------
-
- static void Start();
- static void Dump(const char* aLabel);
-
- static VolumeArray::size_type NumVolumes();
- static already_AddRefed<Volume> GetVolume(VolumeArray::index_type aIndex);
- static already_AddRefed<Volume> FindVolumeByName(const nsCSubstring& aName);
- static already_AddRefed<Volume> FindAddVolumeByName(const nsCSubstring& aName);
- static bool RemoveVolumeByName(const nsCSubstring& aName);
- static void InitConfig();
-
- static void PostCommand(VolumeCommand* aCommand);
-
-protected:
-
- virtual void OnLineRead(int aFd, nsDependentCSubstring& aMessage);
- virtual void OnFileCanWriteWithoutBlocking(int aFd);
- virtual void OnError();
-
- static void DefaultConfig();
-
-private:
- bool OpenSocket();
-
- friend class VolumeListCallback; // Calls SetState
-
- static void SetState(STATE aNewState);
-
- void Restart();
- void WriteCommandData();
- void HandleBroadcast(int aResponseCode, nsCString& aResponseLine);
-
- typedef std::queue<RefPtr<VolumeCommand> > CommandQueue;
-
- static STATE mState;
- static StateObserverList mStateObserverList;
-
- static const int kRcvBufSize = 1024;
- ScopedClose mSocket;
- VolumeArray mVolumeArray;
- CommandQueue mCommands;
- bool mCommandPending;
- MessageLoopForIO::FileDescriptorWatcher mReadWatcher;
- MessageLoopForIO::FileDescriptorWatcher mWriteWatcher;
- RefPtr<VolumeResponseCallback> mBroadcastCallback;
-};
-
-/***************************************************************************
-*
-* The initialization/shutdown functions do not need to be called from
-* the IOThread context.
-*
-***************************************************************************/
-
-/**
- * Initialize the Volume Manager. On initialization, the VolumeManager will
- * attempt to connect with vold and collect the list of volumes that vold
- * knows about.
- */
-void InitVolumeManager();
-
-/**
- * Shuts down the Volume Manager.
- */
-void ShutdownVolumeManager();
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_volumemanager_h__
diff --git a/dom/system/gonk/VolumeManagerLog.h b/dom/system/gonk/VolumeManagerLog.h
deleted file mode 100644
index 793f4889c..000000000
--- a/dom/system/gonk/VolumeManagerLog.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_volumemanagerlog_h__
-#define mozilla_system_volumemanagerlog_h__
-
-#undef USE_DEBUG
-#define USE_DEBUG 0
-
-#if !defined(VOLUME_MANAGER_LOG_TAG)
-#define VOLUME_MANAGER_LOG_TAG "VolumeManager"
-#endif
-
-#undef LOG
-#undef ERR
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, VOLUME_MANAGER_LOG_TAG, ## args)
-#define ERR(args...) __android_log_print(ANDROID_LOG_ERROR, VOLUME_MANAGER_LOG_TAG, ## args)
-
-#undef DBG
-#if USE_DEBUG
-#define DBG(args...) __android_log_print(ANDROID_LOG_DEBUG, VOLUME_MANAGER_LOG_TAG, ## args)
-#else
-#define DBG(args...)
-#endif
-
-#endif // mozilla_system_volumemanagerlog_h__
diff --git a/dom/system/gonk/VolumeServiceIOThread.cpp b/dom/system/gonk/VolumeServiceIOThread.cpp
deleted file mode 100644
index 7eda843c0..000000000
--- a/dom/system/gonk/VolumeServiceIOThread.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "VolumeServiceIOThread.h"
-#include "base/message_loop.h"
-#include "nsVolumeService.h"
-#include "nsXULAppAPI.h"
-#include "Volume.h"
-#include "VolumeManager.h"
-
-namespace mozilla {
-namespace system {
-
-VolumeServiceIOThread::VolumeServiceIOThread(nsVolumeService* aVolumeService)
- : mVolumeService(aVolumeService)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- VolumeManager::RegisterStateObserver(this);
- Volume::RegisterVolumeObserver(this, "VolumeServiceIOThread");
- UpdateAllVolumes();
-}
-
-VolumeServiceIOThread::~VolumeServiceIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- Volume::UnregisterVolumeObserver(this, "VolumeServiceIOThread");
- VolumeManager::UnregisterStateObserver(this);
-}
-
-void
-VolumeServiceIOThread::Notify(Volume* const & aVolume)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- if (VolumeManager::State() != VolumeManager::VOLUMES_READY) {
- return;
- }
- mVolumeService->UpdateVolumeIOThread(aVolume);
-}
-
-void
-VolumeServiceIOThread::Notify(const VolumeManager::StateChangedEvent& aEvent)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- UpdateAllVolumes();
-}
-
-void
-VolumeServiceIOThread::UpdateAllVolumes()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- if (VolumeManager::State() != VolumeManager::VOLUMES_READY) {
- return;
- }
- VolumeManager::VolumeArray::size_type numVolumes = VolumeManager::NumVolumes();
- VolumeManager::VolumeArray::index_type volIndex;
-
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<Volume> vol = VolumeManager::GetVolume(volIndex);
- mVolumeService->UpdateVolumeIOThread(vol);
- }
-}
-
-static StaticRefPtr<VolumeServiceIOThread> sVolumeServiceIOThread;
-
-void
-InitVolumeServiceIOThread(nsVolumeService* const & aVolumeService)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- sVolumeServiceIOThread = new VolumeServiceIOThread(aVolumeService);
-}
-
-void
-ShutdownVolumeServiceIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- sVolumeServiceIOThread = nullptr;
-}
-
-} // system
-} // mozilla
diff --git a/dom/system/gonk/VolumeServiceIOThread.h b/dom/system/gonk/VolumeServiceIOThread.h
deleted file mode 100644
index 0c2a6a62f..000000000
--- a/dom/system/gonk/VolumeServiceIOThread.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_volumeserviceiothread_h__
-#define mozilla_system_volumeserviceiothread_h__
-
-#include "Volume.h"
-#include "VolumeManager.h"
-#include "mozilla/RefPtr.h"
-
-namespace mozilla {
-namespace system {
-
-class nsVolumeService;
-
-/***************************************************************************
-* The nsVolumeServiceIOThread is a companion class to the nsVolumeService
-* class, but whose methods are called from IOThread.
-*/
-class VolumeServiceIOThread : public VolumeManager::StateObserver,
- public Volume::EventObserver
-{
- ~VolumeServiceIOThread();
-
-public:
- NS_INLINE_DECL_REFCOUNTING(VolumeServiceIOThread)
-
- VolumeServiceIOThread(nsVolumeService* aVolumeService);
-
-private:
- void UpdateAllVolumes();
-
- virtual void Notify(const VolumeManager::StateChangedEvent& aEvent);
- virtual void Notify(Volume* const & aVolume);
-
- RefPtr<nsVolumeService> mVolumeService;
-};
-
-void InitVolumeServiceIOThread(nsVolumeService* const & aVolumeService);
-void ShutdownVolumeServiceIOThread();
-void FormatVolume(const nsCString& aVolume);
-void MountVolume(const nsCString& aVolume);
-void UnmountVolume(const nsCString& aVolume);
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_volumeserviceiothread_h__
diff --git a/dom/system/gonk/VolumeServiceTest.cpp b/dom/system/gonk/VolumeServiceTest.cpp
deleted file mode 100644
index 4082e3889..000000000
--- a/dom/system/gonk/VolumeServiceTest.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "VolumeServiceTest.h"
-
-#include "base/message_loop.h"
-#include "nsCOMPtr.h"
-#include "nsIObserver.h"
-#include "nsIObserverService.h"
-#include "nsServiceManagerUtils.h"
-#include "nsThreadUtils.h"
-#include "nsIVolume.h"
-#include "nsIVolumeService.h"
-#include "nsIVolumeStat.h"
-#include "nsXULAppAPI.h"
-
-#include "mozilla/Services.h"
-
-#undef VOLUME_MANAGER_LOG_TAG
-#define VOLUME_MANAGER_LOG_TAG "VolumeServiceTest"
-#include "VolumeManagerLog.h"
-
-using namespace mozilla::services;
-
-namespace mozilla {
-namespace system {
-
-#define TEST_NSVOLUME_OBSERVER 0
-
-#if TEST_NSVOLUME_OBSERVER
-
-/***************************************************************************
-* A test class to verify that the Observer stuff is working properly.
-*/
-class VolumeTestObserver : public nsIObserver
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIOBSERVER
-
- VolumeTestObserver()
- {
- nsCOMPtr<nsIObserverService> obs = GetObserverService();
- if (!obs) {
- return;
- }
- obs->AddObserver(this, NS_VOLUME_STATE_CHANGED, false);
- }
- ~VolumeTestObserver()
- {
- nsCOMPtr<nsIObserverService> obs = GetObserverService();
- if (!obs) {
- return;
- }
- obs->RemoveObserver(this, NS_VOLUME_STATE_CHANGED);
- }
-
- void LogVolume(nsIVolume* vol)
- {
- nsString volName;
- nsString mountPoint;
- int32_t volState;
-
- vol->GetName(volName);
- vol->GetMountPoint(mountPoint);
- vol->GetState(&volState);
-
- LOG(" Volume: %s MountPoint: %s State: %s",
- NS_LossyConvertUTF16toASCII(volName).get(),
- NS_LossyConvertUTF16toASCII(mountPoint).get(),
- NS_VolumeStateStr(volState));
-
- nsCOMPtr<nsIVolumeStat> stat;
- nsresult rv = vol->GetStats(getter_AddRefs(stat));
- if (NS_SUCCEEDED(rv)) {
- int64_t totalBytes;
- int64_t freeBytes;
-
- stat->GetTotalBytes(&totalBytes);
- stat->GetFreeBytes(&freeBytes);
-
- LOG(" Total Space: %llu Mb Free Bytes: %llu Mb",
- totalBytes / (1024LL * 1024LL), freeBytes / (1024LL * 1024LL));
- }
- else {
- LOG(" Unable to retrieve stats");
- }
- }
-};
-static nsCOMPtr<VolumeTestObserver> sTestObserver;
-
-NS_IMPL_ISUPPORTS(VolumeTestObserver, nsIObserver)
-
-NS_IMETHODIMP
-VolumeTestObserver::Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData)
-{
- LOG("TestObserver: topic: %s", aTopic);
-
- if (strcmp(aTopic, NS_VOLUME_STATE_CHANGED) != 0) {
- return NS_OK;
- }
- nsCOMPtr<nsIVolume> vol = do_QueryInterface(aSubject);
- if (vol) {
- LogVolume(vol);
- }
-
- // Since this observe method was called then we know that the service
- // has been initialized so we can do the VolumeService tests.
-
- nsCOMPtr<nsIVolumeService> vs = do_GetService(NS_VOLUMESERVICE_CONTRACTID);
- if (!vs) {
- ERR("do_GetService('%s') failed", NS_VOLUMESERVICE_CONTRACTID);
- return NS_ERROR_FAILURE;
- }
-
- nsresult rv = vs->GetVolumeByName(NS_LITERAL_STRING("sdcard"), getter_AddRefs(vol));
- if (NS_SUCCEEDED(rv)) {
- LOG("GetVolumeByName( 'sdcard' ) succeeded (expected)");
- LogVolume(vol);
- } else {
- ERR("GetVolumeByName( 'sdcard' ) failed (unexpected)");
- }
-
- rv = vs->GetVolumeByName(NS_LITERAL_STRING("foo"), getter_AddRefs(vol));
- if (NS_SUCCEEDED(rv)) {
- ERR("GetVolumeByName( 'foo' ) succeeded (unexpected)");
- } else {
- LOG("GetVolumeByName( 'foo' ) failed (expected)");
- }
-
- rv = vs->GetVolumeByPath(NS_LITERAL_STRING("/mnt/sdcard"), getter_AddRefs(vol));
- if (NS_SUCCEEDED(rv)) {
- LOG("GetVolumeByPath( '/mnt/sdcard' ) succeeded (expected)");
- LogVolume(vol);
- } else {
- ERR("GetVolumeByPath( '/mnt/sdcard' ) failed (unexpected");
- }
-
- rv = vs->GetVolumeByPath(NS_LITERAL_STRING("/mnt/sdcard/foo"), getter_AddRefs(vol));
- if (NS_SUCCEEDED(rv)) {
- LOG("GetVolumeByPath( '/mnt/sdcard/foo' ) succeeded (expected)");
- LogVolume(vol);
- } else {
- LOG("GetVolumeByPath( '/mnt/sdcard/foo' ) failed (unexpected)");
- }
-
- rv = vs->GetVolumeByPath(NS_LITERAL_STRING("/mnt/sdcardfoo"), getter_AddRefs(vol));
- if (NS_SUCCEEDED(rv)) {
- ERR("GetVolumeByPath( '/mnt/sdcardfoo' ) succeeded (unexpected)");
- } else {
- LOG("GetVolumeByPath( '/mnt/sdcardfoo' ) failed (expected)");
- }
-
- return NS_OK;
-}
-
-class InitVolumeServiceTestIO : public Runnable
-{
-public:
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- DBG("InitVolumeServiceTest called");
- nsCOMPtr<nsIVolumeService> vs = do_GetService(NS_VOLUMESERVICE_CONTRACTID);
- if (!vs) {
- ERR("do_GetService('%s') failed", NS_VOLUMESERVICE_CONTRACTID);
- return NS_ERROR_FAILURE;
- }
- sTestObserver = new VolumeTestObserver();
-
- return NS_OK;
- }
-};
-#endif // TEST_NSVOLUME_OBSERVER
-
-void
-InitVolumeServiceTestIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
-#if TEST_NSVOLUME_OBSERVER
- // Now that the volume manager is initialized we can go
- // ahead and do our test (on main thread).
- NS_DispatchToMainThread(new InitVolumeServiceTestIO());
-#endif
-}
-
-void
-ShutdownVolumeServiceTest()
-{
-#if TEST_NSVOLUME_OBSERVER
- DBG("ShutdownVolumeServiceTestIOThread called");
- sTestObserver = nullptr;
-#endif
-}
-
-} // system
-} // mozilla
diff --git a/dom/system/gonk/VolumeServiceTest.h b/dom/system/gonk/VolumeServiceTest.h
deleted file mode 100644
index 71a92bf6c..000000000
--- a/dom/system/gonk/VolumeServiceTest.h
+++ /dev/null
@@ -1,19 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_volumeservicetest_h__
-#define mozilla_system_volumeservicetest_h__
-
-
-namespace mozilla {
-namespace system {
-
-void InitVolumeServiceTestIOThread();
-void ShutdownVolumeServiceTest();
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_volumeservicetest_h__
-
diff --git a/dom/system/gonk/android_audio/AudioSystem.h b/dom/system/gonk/android_audio/AudioSystem.h
deleted file mode 100644
index d5841eaaa..000000000
--- a/dom/system/gonk/android_audio/AudioSystem.h
+++ /dev/null
@@ -1,1134 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_AUDIOSYSTEM_H_
-#define ANDROID_AUDIOSYSTEM_H_
-
-#pragma GCC visibility push(default)
-
-#include <utils/RefBase.h>
-#include <utils/threads.h>
-#include "IAudioFlinger.h"
-
-#ifndef VANILLA_ANDROID
-/* request to open a direct output with get_output() (by opposition to
- * sharing an output with other AudioTracks)
- */
-typedef enum {
- AUDIO_POLICY_OUTPUT_FLAG_INDIRECT = 0x0,
- AUDIO_POLICY_OUTPUT_FLAG_DIRECT = 0x1
-} audio_policy_output_flags_t;
-
-/* device categories used for audio_policy->set_force_use() */
-typedef enum {
- AUDIO_POLICY_FORCE_NONE,
- AUDIO_POLICY_FORCE_SPEAKER,
- AUDIO_POLICY_FORCE_HEADPHONES,
- AUDIO_POLICY_FORCE_BT_SCO,
- AUDIO_POLICY_FORCE_BT_A2DP,
- AUDIO_POLICY_FORCE_WIRED_ACCESSORY,
- AUDIO_POLICY_FORCE_BT_CAR_DOCK,
- AUDIO_POLICY_FORCE_BT_DESK_DOCK,
- AUDIO_POLICY_FORCE_ANALOG_DOCK,
- AUDIO_POLICY_FORCE_DIGITAL_DOCK,
- AUDIO_POLICY_FORCE_NO_BT_A2DP,
- AUDIO_POLICY_FORCE_CFG_CNT,
- AUDIO_POLICY_FORCE_CFG_MAX = AUDIO_POLICY_FORCE_CFG_CNT - 1,
-
- AUDIO_POLICY_FORCE_DEFAULT = AUDIO_POLICY_FORCE_NONE,
-} audio_policy_forced_cfg_t;
-
-/* usages used for audio_policy->set_force_use() */
-typedef enum {
- AUDIO_POLICY_FORCE_FOR_COMMUNICATION,
- AUDIO_POLICY_FORCE_FOR_MEDIA,
- AUDIO_POLICY_FORCE_FOR_RECORD,
- AUDIO_POLICY_FORCE_FOR_DOCK,
-
- AUDIO_POLICY_FORCE_USE_CNT,
- AUDIO_POLICY_FORCE_USE_MAX = AUDIO_POLICY_FORCE_USE_CNT - 1,
-} audio_policy_force_use_t;
-
-typedef enum {
- AUDIO_STREAM_DEFAULT = -1,
- AUDIO_STREAM_VOICE_CALL = 0,
- AUDIO_STREAM_SYSTEM = 1,
- AUDIO_STREAM_RING = 2,
- AUDIO_STREAM_MUSIC = 3,
- AUDIO_STREAM_ALARM = 4,
- AUDIO_STREAM_NOTIFICATION = 5,
- AUDIO_STREAM_BLUETOOTH_SCO = 6,
- AUDIO_STREAM_ENFORCED_AUDIBLE = 7, /* Sounds that cannot be muted by user and must be routed to speaker */
- AUDIO_STREAM_DTMF = 8,
- AUDIO_STREAM_TTS = 9,
-#if ANDROID_VERSION < 19
- AUDIO_STREAM_FM = 10,
-#endif
-
- AUDIO_STREAM_CNT,
- AUDIO_STREAM_MAX = AUDIO_STREAM_CNT - 1,
-} audio_stream_type_t;
-
-/* PCM sub formats */
-typedef enum {
- AUDIO_FORMAT_PCM_SUB_16_BIT = 0x1, /* DO NOT CHANGE - PCM signed 16 bits */
- AUDIO_FORMAT_PCM_SUB_8_BIT = 0x2, /* DO NOT CHANGE - PCM unsigned 8 bits */
- AUDIO_FORMAT_PCM_SUB_32_BIT = 0x3, /* PCM signed .31 fixed point */
- AUDIO_FORMAT_PCM_SUB_8_24_BIT = 0x4, /* PCM signed 7.24 fixed point */
-} audio_format_pcm_sub_fmt_t;
-
-/* Audio format consists in a main format field (upper 8 bits) and a sub format
- * field (lower 24 bits).
- *
- * The main format indicates the main codec type. The sub format field
- * indicates options and parameters for each format. The sub format is mainly
- * used for record to indicate for instance the requested bitrate or profile.
- * It can also be used for certain formats to give informations not present in
- * the encoded audio stream (e.g. octet alignement for AMR).
- */
-typedef enum {
- AUDIO_FORMAT_INVALID = 0xFFFFFFFFUL,
- AUDIO_FORMAT_DEFAULT = 0,
- AUDIO_FORMAT_PCM = 0x00000000UL, /* DO NOT CHANGE */
- AUDIO_FORMAT_MP3 = 0x01000000UL,
- AUDIO_FORMAT_AMR_NB = 0x02000000UL,
- AUDIO_FORMAT_AMR_WB = 0x03000000UL,
- AUDIO_FORMAT_AAC = 0x04000000UL,
- AUDIO_FORMAT_HE_AAC_V1 = 0x05000000UL,
- AUDIO_FORMAT_HE_AAC_V2 = 0x06000000UL,
- AUDIO_FORMAT_VORBIS = 0x07000000UL,
- AUDIO_FORMAT_MAIN_MASK = 0xFF000000UL,
- AUDIO_FORMAT_SUB_MASK = 0x00FFFFFFUL,
-
- /* Aliases */
- AUDIO_FORMAT_PCM_16_BIT = (AUDIO_FORMAT_PCM |
- AUDIO_FORMAT_PCM_SUB_16_BIT),
- AUDIO_FORMAT_PCM_8_BIT = (AUDIO_FORMAT_PCM |
- AUDIO_FORMAT_PCM_SUB_8_BIT),
- AUDIO_FORMAT_PCM_32_BIT = (AUDIO_FORMAT_PCM |
- AUDIO_FORMAT_PCM_SUB_32_BIT),
- AUDIO_FORMAT_PCM_8_24_BIT = (AUDIO_FORMAT_PCM |
- AUDIO_FORMAT_PCM_SUB_8_24_BIT),
-} audio_format_t;
-
-typedef enum {
- /* output channels */
- AUDIO_CHANNEL_OUT_FRONT_LEFT = 0x1,
- AUDIO_CHANNEL_OUT_FRONT_RIGHT = 0x2,
- AUDIO_CHANNEL_OUT_FRONT_CENTER = 0x4,
- AUDIO_CHANNEL_OUT_LOW_FREQUENCY = 0x8,
- AUDIO_CHANNEL_OUT_BACK_LEFT = 0x10,
- AUDIO_CHANNEL_OUT_BACK_RIGHT = 0x20,
- AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x40,
- AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x80,
- AUDIO_CHANNEL_OUT_BACK_CENTER = 0x100,
- AUDIO_CHANNEL_OUT_SIDE_LEFT = 0x200,
- AUDIO_CHANNEL_OUT_SIDE_RIGHT = 0x400,
- AUDIO_CHANNEL_OUT_TOP_CENTER = 0x800,
- AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT = 0x1000,
- AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER = 0x2000,
- AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT = 0x4000,
- AUDIO_CHANNEL_OUT_TOP_BACK_LEFT = 0x8000,
- AUDIO_CHANNEL_OUT_TOP_BACK_CENTER = 0x10000,
- AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT = 0x20000,
-
- AUDIO_CHANNEL_OUT_MONO = AUDIO_CHANNEL_OUT_FRONT_LEFT,
- AUDIO_CHANNEL_OUT_STEREO = (AUDIO_CHANNEL_OUT_FRONT_LEFT |
- AUDIO_CHANNEL_OUT_FRONT_RIGHT),
- AUDIO_CHANNEL_OUT_QUAD = (AUDIO_CHANNEL_OUT_FRONT_LEFT |
- AUDIO_CHANNEL_OUT_FRONT_RIGHT |
- AUDIO_CHANNEL_OUT_BACK_LEFT |
- AUDIO_CHANNEL_OUT_BACK_RIGHT),
- AUDIO_CHANNEL_OUT_SURROUND = (AUDIO_CHANNEL_OUT_FRONT_LEFT |
- AUDIO_CHANNEL_OUT_FRONT_RIGHT |
- AUDIO_CHANNEL_OUT_FRONT_CENTER |
- AUDIO_CHANNEL_OUT_BACK_CENTER),
- AUDIO_CHANNEL_OUT_5POINT1 = (AUDIO_CHANNEL_OUT_FRONT_LEFT |
- AUDIO_CHANNEL_OUT_FRONT_RIGHT |
- AUDIO_CHANNEL_OUT_FRONT_CENTER |
- AUDIO_CHANNEL_OUT_LOW_FREQUENCY |
- AUDIO_CHANNEL_OUT_BACK_LEFT |
- AUDIO_CHANNEL_OUT_BACK_RIGHT),
- // matches the correct AudioFormat.CHANNEL_OUT_7POINT1_SURROUND definition for 7.1
- AUDIO_CHANNEL_OUT_7POINT1 = (AUDIO_CHANNEL_OUT_FRONT_LEFT |
- AUDIO_CHANNEL_OUT_FRONT_RIGHT |
- AUDIO_CHANNEL_OUT_FRONT_CENTER |
- AUDIO_CHANNEL_OUT_LOW_FREQUENCY |
- AUDIO_CHANNEL_OUT_BACK_LEFT |
- AUDIO_CHANNEL_OUT_BACK_RIGHT |
- AUDIO_CHANNEL_OUT_SIDE_LEFT |
- AUDIO_CHANNEL_OUT_SIDE_RIGHT),
- AUDIO_CHANNEL_OUT_ALL = (AUDIO_CHANNEL_OUT_FRONT_LEFT |
- AUDIO_CHANNEL_OUT_FRONT_RIGHT |
- AUDIO_CHANNEL_OUT_FRONT_CENTER |
- AUDIO_CHANNEL_OUT_LOW_FREQUENCY |
- AUDIO_CHANNEL_OUT_BACK_LEFT |
- AUDIO_CHANNEL_OUT_BACK_RIGHT |
- AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER |
- AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER |
- AUDIO_CHANNEL_OUT_BACK_CENTER|
- AUDIO_CHANNEL_OUT_SIDE_LEFT|
- AUDIO_CHANNEL_OUT_SIDE_RIGHT|
- AUDIO_CHANNEL_OUT_TOP_CENTER|
- AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT|
- AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER|
- AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT|
- AUDIO_CHANNEL_OUT_TOP_BACK_LEFT|
- AUDIO_CHANNEL_OUT_TOP_BACK_CENTER|
- AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT),
-
- /* input channels */
- AUDIO_CHANNEL_IN_LEFT = 0x4,
- AUDIO_CHANNEL_IN_RIGHT = 0x8,
- AUDIO_CHANNEL_IN_FRONT = 0x10,
- AUDIO_CHANNEL_IN_BACK = 0x20,
- AUDIO_CHANNEL_IN_LEFT_PROCESSED = 0x40,
- AUDIO_CHANNEL_IN_RIGHT_PROCESSED = 0x80,
- AUDIO_CHANNEL_IN_FRONT_PROCESSED = 0x100,
- AUDIO_CHANNEL_IN_BACK_PROCESSED = 0x200,
- AUDIO_CHANNEL_IN_PRESSURE = 0x400,
- AUDIO_CHANNEL_IN_X_AXIS = 0x800,
- AUDIO_CHANNEL_IN_Y_AXIS = 0x1000,
- AUDIO_CHANNEL_IN_Z_AXIS = 0x2000,
- AUDIO_CHANNEL_IN_VOICE_UPLINK = 0x4000,
- AUDIO_CHANNEL_IN_VOICE_DNLINK = 0x8000,
-
- AUDIO_CHANNEL_IN_MONO = AUDIO_CHANNEL_IN_FRONT,
- AUDIO_CHANNEL_IN_STEREO = (AUDIO_CHANNEL_IN_LEFT | AUDIO_CHANNEL_IN_RIGHT),
- AUDIO_CHANNEL_IN_ALL = (AUDIO_CHANNEL_IN_LEFT |
- AUDIO_CHANNEL_IN_RIGHT |
- AUDIO_CHANNEL_IN_FRONT |
- AUDIO_CHANNEL_IN_BACK|
- AUDIO_CHANNEL_IN_LEFT_PROCESSED |
- AUDIO_CHANNEL_IN_RIGHT_PROCESSED |
- AUDIO_CHANNEL_IN_FRONT_PROCESSED |
- AUDIO_CHANNEL_IN_BACK_PROCESSED|
- AUDIO_CHANNEL_IN_PRESSURE |
- AUDIO_CHANNEL_IN_X_AXIS |
- AUDIO_CHANNEL_IN_Y_AXIS |
- AUDIO_CHANNEL_IN_Z_AXIS |
- AUDIO_CHANNEL_IN_VOICE_UPLINK |
- AUDIO_CHANNEL_IN_VOICE_DNLINK),
-} audio_channels_t;
-
-#if ANDROID_VERSION >= 17
-typedef enum {
- AUDIO_MODE_INVALID = -2,
- AUDIO_MODE_CURRENT = -1,
- AUDIO_MODE_NORMAL = 0,
- AUDIO_MODE_RINGTONE = 1,
- AUDIO_MODE_IN_CALL = 2,
- AUDIO_MODE_IN_COMMUNICATION = 3,
-
- AUDIO_MODE_CNT,
- AUDIO_MODE_MAX = AUDIO_MODE_CNT - 1,
-} audio_mode_t;
-#endif
-#endif
-
-#if ANDROID_VERSION < 17
-typedef enum {
- AUDIO_DEVICE_NONE = 0x0,
- /* output devices */
- AUDIO_DEVICE_OUT_EARPIECE = 0x1,
- AUDIO_DEVICE_OUT_SPEAKER = 0x2,
- AUDIO_DEVICE_OUT_WIRED_HEADSET = 0x4,
- AUDIO_DEVICE_OUT_WIRED_HEADPHONE = 0x8,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO = 0x10,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP = 0x80,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200,
- AUDIO_DEVICE_OUT_AUX_DIGITAL = 0x400,
- AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET = 0x800,
- AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET = 0x1000,
- AUDIO_DEVICE_OUT_FM = 0x2000,
- AUDIO_DEVICE_OUT_ANC_HEADSET = 0x4000,
- AUDIO_DEVICE_OUT_ANC_HEADPHONE = 0x8000,
- AUDIO_DEVICE_OUT_FM_TX = 0x10000,
- AUDIO_DEVICE_OUT_DIRECTOUTPUT = 0x20000,
- AUDIO_DEVICE_OUT_PROXY = 0x40000,
- AUDIO_DEVICE_OUT_DEFAULT = 0x80000,
- AUDIO_DEVICE_OUT_ALL = (AUDIO_DEVICE_OUT_EARPIECE |
- AUDIO_DEVICE_OUT_SPEAKER |
- AUDIO_DEVICE_OUT_WIRED_HEADSET |
- AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER |
- AUDIO_DEVICE_OUT_AUX_DIGITAL |
- AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET |
- AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET |
- AUDIO_DEVICE_OUT_FM |
- AUDIO_DEVICE_OUT_ANC_HEADSET |
- AUDIO_DEVICE_OUT_ANC_HEADPHONE |
- AUDIO_DEVICE_OUT_FM_TX |
- AUDIO_DEVICE_OUT_DIRECTOUTPUT |
- AUDIO_DEVICE_OUT_PROXY |
- AUDIO_DEVICE_OUT_DEFAULT),
- AUDIO_DEVICE_OUT_ALL_A2DP = (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
- AUDIO_DEVICE_OUT_ALL_SCO = (AUDIO_DEVICE_OUT_BLUETOOTH_SCO |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
- /* input devices */
- AUDIO_DEVICE_IN_COMMUNICATION = 0x100000,
- AUDIO_DEVICE_IN_AMBIENT = 0x200000,
- AUDIO_DEVICE_IN_BUILTIN_MIC = 0x400000,
- AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET = 0x800000,
- AUDIO_DEVICE_IN_WIRED_HEADSET = 0x1000000,
- AUDIO_DEVICE_IN_AUX_DIGITAL = 0x2000000,
- AUDIO_DEVICE_IN_VOICE_CALL = 0x4000000,
- AUDIO_DEVICE_IN_BACK_MIC = 0x8000000,
- AUDIO_DEVICE_IN_ANC_HEADSET = 0x10000000,
- AUDIO_DEVICE_IN_FM_RX = 0x20000000,
- AUDIO_DEVICE_IN_FM_RX_A2DP = 0x40000000,
- AUDIO_DEVICE_IN_DEFAULT = 0x80000000,
-
- AUDIO_DEVICE_IN_ALL = (AUDIO_DEVICE_IN_COMMUNICATION |
- AUDIO_DEVICE_IN_AMBIENT |
- AUDIO_DEVICE_IN_BUILTIN_MIC |
- AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_IN_WIRED_HEADSET |
- AUDIO_DEVICE_IN_AUX_DIGITAL |
- AUDIO_DEVICE_IN_VOICE_CALL |
- AUDIO_DEVICE_IN_BACK_MIC |
- AUDIO_DEVICE_IN_ANC_HEADSET |
- AUDIO_DEVICE_IN_FM_RX |
- AUDIO_DEVICE_IN_FM_RX_A2DP |
- AUDIO_DEVICE_IN_DEFAULT),
- AUDIO_DEVICE_IN_ALL_SCO = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
-} audio_devices_t;
-#elif ANDROID_VERSION < 21
-enum {
- AUDIO_DEVICE_NONE = 0x0,
- /* reserved bits */
- AUDIO_DEVICE_BIT_IN = 0x80000000,
- AUDIO_DEVICE_BIT_DEFAULT = 0x40000000,
- /* output devices */
- AUDIO_DEVICE_OUT_EARPIECE = 0x1,
- AUDIO_DEVICE_OUT_SPEAKER = 0x2,
- AUDIO_DEVICE_OUT_WIRED_HEADSET = 0x4,
- AUDIO_DEVICE_OUT_WIRED_HEADPHONE = 0x8,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO = 0x10,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP = 0x80,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200,
- AUDIO_DEVICE_OUT_AUX_DIGITAL = 0x400,
- AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET = 0x800,
- AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET = 0x1000,
- AUDIO_DEVICE_OUT_USB_ACCESSORY = 0x2000,
- AUDIO_DEVICE_OUT_USB_DEVICE = 0x4000,
- AUDIO_DEVICE_OUT_REMOTE_SUBMIX = 0x8000,
- AUDIO_DEVICE_OUT_ANC_HEADSET = 0x10000,
- AUDIO_DEVICE_OUT_ANC_HEADPHONE = 0x20000,
- AUDIO_DEVICE_OUT_PROXY = 0x40000,
- AUDIO_DEVICE_OUT_FM = 0x80000,
- AUDIO_DEVICE_OUT_FM_TX = 0x100000,
- AUDIO_DEVICE_OUT_DEFAULT = AUDIO_DEVICE_BIT_DEFAULT,
- AUDIO_DEVICE_OUT_ALL = (AUDIO_DEVICE_OUT_EARPIECE |
- AUDIO_DEVICE_OUT_SPEAKER |
- AUDIO_DEVICE_OUT_WIRED_HEADSET |
- AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER |
- AUDIO_DEVICE_OUT_AUX_DIGITAL |
- AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET |
- AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET |
- AUDIO_DEVICE_OUT_USB_ACCESSORY |
- AUDIO_DEVICE_OUT_USB_DEVICE |
- AUDIO_DEVICE_OUT_REMOTE_SUBMIX |
- AUDIO_DEVICE_OUT_ANC_HEADSET |
- AUDIO_DEVICE_OUT_ANC_HEADPHONE |
- AUDIO_DEVICE_OUT_PROXY |
- AUDIO_DEVICE_OUT_FM |
- AUDIO_DEVICE_OUT_FM_TX |
- AUDIO_DEVICE_OUT_DEFAULT),
- AUDIO_DEVICE_OUT_ALL_A2DP = (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
- AUDIO_DEVICE_OUT_ALL_SCO = (AUDIO_DEVICE_OUT_BLUETOOTH_SCO |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
- AUDIO_DEVICE_OUT_ALL_USB = (AUDIO_DEVICE_OUT_USB_ACCESSORY |
- AUDIO_DEVICE_OUT_USB_DEVICE),
-
- /* input devices */
- AUDIO_DEVICE_IN_COMMUNICATION = AUDIO_DEVICE_BIT_IN | 0x1,
- AUDIO_DEVICE_IN_AMBIENT = AUDIO_DEVICE_BIT_IN | 0x2,
- AUDIO_DEVICE_IN_BUILTIN_MIC = AUDIO_DEVICE_BIT_IN | 0x4,
- AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET = AUDIO_DEVICE_BIT_IN | 0x8,
- AUDIO_DEVICE_IN_WIRED_HEADSET = AUDIO_DEVICE_BIT_IN | 0x10,
- AUDIO_DEVICE_IN_AUX_DIGITAL = AUDIO_DEVICE_BIT_IN | 0x20,
- AUDIO_DEVICE_IN_VOICE_CALL = AUDIO_DEVICE_BIT_IN | 0x40,
- AUDIO_DEVICE_IN_BACK_MIC = AUDIO_DEVICE_BIT_IN | 0x80,
- AUDIO_DEVICE_IN_REMOTE_SUBMIX = AUDIO_DEVICE_BIT_IN | 0x100,
- AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET = AUDIO_DEVICE_BIT_IN | 0x200,
- AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET = AUDIO_DEVICE_BIT_IN | 0x400,
- AUDIO_DEVICE_IN_USB_ACCESSORY = AUDIO_DEVICE_BIT_IN | 0x800,
- AUDIO_DEVICE_IN_USB_DEVICE = AUDIO_DEVICE_BIT_IN | 0x1000,
- AUDIO_DEVICE_IN_ANC_HEADSET = AUDIO_DEVICE_BIT_IN | 0x2000,
- AUDIO_DEVICE_IN_PROXY = AUDIO_DEVICE_BIT_IN | 0x4000,
- AUDIO_DEVICE_IN_FM_RX = AUDIO_DEVICE_BIT_IN | 0x8000,
- AUDIO_DEVICE_IN_FM_RX_A2DP = AUDIO_DEVICE_BIT_IN | 0x10000,
- AUDIO_DEVICE_IN_DEFAULT = AUDIO_DEVICE_BIT_IN | AUDIO_DEVICE_BIT_DEFAULT,
-
- AUDIO_DEVICE_IN_ALL = (AUDIO_DEVICE_IN_COMMUNICATION |
- AUDIO_DEVICE_IN_AMBIENT |
- AUDIO_DEVICE_IN_BUILTIN_MIC |
- AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_IN_WIRED_HEADSET |
- AUDIO_DEVICE_IN_AUX_DIGITAL |
- AUDIO_DEVICE_IN_VOICE_CALL |
- AUDIO_DEVICE_IN_BACK_MIC |
- AUDIO_DEVICE_IN_REMOTE_SUBMIX |
- AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET |
- AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET |
- AUDIO_DEVICE_IN_USB_ACCESSORY |
- AUDIO_DEVICE_IN_USB_DEVICE |
- AUDIO_DEVICE_IN_ANC_HEADSET |
- AUDIO_DEVICE_IN_FM_RX |
- AUDIO_DEVICE_IN_FM_RX_A2DP |
- AUDIO_DEVICE_IN_PROXY |
- AUDIO_DEVICE_IN_DEFAULT),
- AUDIO_DEVICE_IN_ALL_SCO = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
-};
-
-typedef uint32_t audio_devices_t;
-#else
-enum {
- AUDIO_DEVICE_NONE = 0x0,
- /* reserved bits */
- AUDIO_DEVICE_BIT_IN = 0x80000000,
- AUDIO_DEVICE_BIT_DEFAULT = 0x40000000,
- /* output devices */
- AUDIO_DEVICE_OUT_EARPIECE = 0x1,
- AUDIO_DEVICE_OUT_SPEAKER = 0x2,
- AUDIO_DEVICE_OUT_WIRED_HEADSET = 0x4,
- AUDIO_DEVICE_OUT_WIRED_HEADPHONE = 0x8,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO = 0x10,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20,
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP = 0x80,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100,
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200,
- AUDIO_DEVICE_OUT_AUX_DIGITAL = 0x400,
- AUDIO_DEVICE_OUT_HDMI = AUDIO_DEVICE_OUT_AUX_DIGITAL,
- /* uses an analog connection (multiplexed over the USB connector pins for instance) */
- AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET = 0x800,
- AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET = 0x1000,
- /* USB accessory mode: your Android device is a USB device and the dock is a USB host */
- AUDIO_DEVICE_OUT_USB_ACCESSORY = 0x2000,
- /* USB host mode: your Android device is a USB host and the dock is a USB device */
- AUDIO_DEVICE_OUT_USB_DEVICE = 0x4000,
- AUDIO_DEVICE_OUT_REMOTE_SUBMIX = 0x8000,
- /* Telephony voice TX path */
- AUDIO_DEVICE_OUT_TELEPHONY_TX = 0x10000,
- /* Analog jack with line impedance detected */
- AUDIO_DEVICE_OUT_LINE = 0x20000,
- /* HDMI Audio Return Channel */
- AUDIO_DEVICE_OUT_HDMI_ARC = 0x40000,
- /* S/PDIF out */
- AUDIO_DEVICE_OUT_SPDIF = 0x80000,
- /* FM transmitter out */
- AUDIO_DEVICE_OUT_FM = 0x100000,
- /* Line out for av devices */
- AUDIO_DEVICE_OUT_AUX_LINE = 0x200000,
- /* limited-output speaker device for acoustic safety */
- AUDIO_DEVICE_OUT_SPEAKER_SAFE = 0x400000,
- AUDIO_DEVICE_OUT_DEFAULT = AUDIO_DEVICE_BIT_DEFAULT,
- AUDIO_DEVICE_OUT_ALL = (AUDIO_DEVICE_OUT_EARPIECE |
- AUDIO_DEVICE_OUT_SPEAKER |
- AUDIO_DEVICE_OUT_WIRED_HEADSET |
- AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER |
- AUDIO_DEVICE_OUT_AUX_DIGITAL |
- AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET |
- AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET |
- AUDIO_DEVICE_OUT_USB_ACCESSORY |
- AUDIO_DEVICE_OUT_USB_DEVICE |
- AUDIO_DEVICE_OUT_REMOTE_SUBMIX |
- AUDIO_DEVICE_OUT_TELEPHONY_TX |
- AUDIO_DEVICE_OUT_LINE |
- AUDIO_DEVICE_OUT_HDMI_ARC |
- AUDIO_DEVICE_OUT_SPDIF |
- AUDIO_DEVICE_OUT_FM |
- AUDIO_DEVICE_OUT_AUX_LINE |
- AUDIO_DEVICE_OUT_SPEAKER_SAFE |
- AUDIO_DEVICE_OUT_DEFAULT),
- AUDIO_DEVICE_OUT_ALL_A2DP = (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
- AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
- AUDIO_DEVICE_OUT_ALL_SCO = (AUDIO_DEVICE_OUT_BLUETOOTH_SCO |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
- AUDIO_DEVICE_OUT_ALL_USB = (AUDIO_DEVICE_OUT_USB_ACCESSORY |
- AUDIO_DEVICE_OUT_USB_DEVICE),
- /* input devices */
- AUDIO_DEVICE_IN_COMMUNICATION = AUDIO_DEVICE_BIT_IN | 0x1,
- AUDIO_DEVICE_IN_AMBIENT = AUDIO_DEVICE_BIT_IN | 0x2,
- AUDIO_DEVICE_IN_BUILTIN_MIC = AUDIO_DEVICE_BIT_IN | 0x4,
- AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET = AUDIO_DEVICE_BIT_IN | 0x8,
- AUDIO_DEVICE_IN_WIRED_HEADSET = AUDIO_DEVICE_BIT_IN | 0x10,
- AUDIO_DEVICE_IN_AUX_DIGITAL = AUDIO_DEVICE_BIT_IN | 0x20,
- AUDIO_DEVICE_IN_HDMI = AUDIO_DEVICE_IN_AUX_DIGITAL,
- /* Telephony voice RX path */
- AUDIO_DEVICE_IN_VOICE_CALL = AUDIO_DEVICE_BIT_IN | 0x40,
- AUDIO_DEVICE_IN_BACK_MIC = AUDIO_DEVICE_BIT_IN | 0x80,
- AUDIO_DEVICE_IN_REMOTE_SUBMIX = AUDIO_DEVICE_BIT_IN | 0x100,
- AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET = AUDIO_DEVICE_BIT_IN | 0x200,
- AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET = AUDIO_DEVICE_BIT_IN | 0x400,
- AUDIO_DEVICE_IN_USB_ACCESSORY = AUDIO_DEVICE_BIT_IN | 0x800,
- AUDIO_DEVICE_IN_USB_DEVICE = AUDIO_DEVICE_BIT_IN | 0x1000,
- /* FM tuner input */
- AUDIO_DEVICE_IN_FM_TUNER = AUDIO_DEVICE_BIT_IN | 0x2000,
- /* TV tuner input */
- AUDIO_DEVICE_IN_TV_TUNER = AUDIO_DEVICE_BIT_IN | 0x4000,
- /* Analog jack with line impedance detected */
- AUDIO_DEVICE_IN_LINE = AUDIO_DEVICE_BIT_IN | 0x8000,
- /* S/PDIF in */
- AUDIO_DEVICE_IN_SPDIF = AUDIO_DEVICE_BIT_IN | 0x10000,
- AUDIO_DEVICE_IN_BLUETOOTH_A2DP = AUDIO_DEVICE_BIT_IN | 0x20000,
- AUDIO_DEVICE_IN_LOOPBACK = AUDIO_DEVICE_BIT_IN | 0x40000,
- AUDIO_DEVICE_IN_DEFAULT = AUDIO_DEVICE_BIT_IN | AUDIO_DEVICE_BIT_DEFAULT,
- AUDIO_DEVICE_IN_ALL = (AUDIO_DEVICE_IN_COMMUNICATION |
- AUDIO_DEVICE_IN_AMBIENT |
- AUDIO_DEVICE_IN_BUILTIN_MIC |
- AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET |
- AUDIO_DEVICE_IN_WIRED_HEADSET |
- AUDIO_DEVICE_IN_AUX_DIGITAL |
- AUDIO_DEVICE_IN_VOICE_CALL |
- AUDIO_DEVICE_IN_BACK_MIC |
- AUDIO_DEVICE_IN_REMOTE_SUBMIX |
- AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET |
- AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET |
- AUDIO_DEVICE_IN_USB_ACCESSORY |
- AUDIO_DEVICE_IN_USB_DEVICE |
- AUDIO_DEVICE_IN_FM_TUNER |
- AUDIO_DEVICE_IN_TV_TUNER |
- AUDIO_DEVICE_IN_LINE |
- AUDIO_DEVICE_IN_SPDIF |
- AUDIO_DEVICE_IN_BLUETOOTH_A2DP |
- AUDIO_DEVICE_IN_LOOPBACK |
- AUDIO_DEVICE_IN_DEFAULT),
- AUDIO_DEVICE_IN_ALL_SCO = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET,
- AUDIO_DEVICE_IN_ALL_USB = (AUDIO_DEVICE_IN_USB_ACCESSORY |
- AUDIO_DEVICE_IN_USB_DEVICE),
-};
-
-typedef uint32_t audio_devices_t;
-#endif
-
-static inline bool audio_is_output_device(uint32_t device)
-{
-#if ANDROID_VERSION < 17
- if ((__builtin_popcount(device) == 1) && ((device & ~AUDIO_DEVICE_OUT_ALL) == 0))
- return true;
- else
- return false;
-#else
- if (((device & AUDIO_DEVICE_BIT_IN) == 0) &&
- (__builtin_popcount(device) == 1) && ((device & ~AUDIO_DEVICE_OUT_ALL) == 0))
- return true;
- else
- return false;
-#endif
-}
-
-/* device connection states used for audio_policy->set_device_connection_state()
- * */
-typedef enum {
- AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
- AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
-
- AUDIO_POLICY_DEVICE_STATE_CNT,
- AUDIO_POLICY_DEVICE_STATE_MAX = AUDIO_POLICY_DEVICE_STATE_CNT - 1,
-} audio_policy_dev_state_t;
-
-namespace android {
-
-typedef void (*audio_error_callback)(status_t err);
-typedef int audio_io_handle_t;
-
-class IAudioPolicyService;
-class String8;
-
-class AudioSystem
-{
-public:
-
- enum stream_type {
- DEFAULT =-1,
- VOICE_CALL = 0,
- SYSTEM = 1,
- RING = 2,
- MUSIC = 3,
- ALARM = 4,
- NOTIFICATION = 5,
- BLUETOOTH_SCO = 6,
- ENFORCED_AUDIBLE = 7, // Sounds that cannot be muted by user and must be routed to speaker
- DTMF = 8,
- TTS = 9,
- FM = 10,
- NUM_STREAM_TYPES
- };
-
- // Audio sub formats (see AudioSystem::audio_format).
- enum pcm_sub_format {
- PCM_SUB_16_BIT = 0x1, // must be 1 for backward compatibility
- PCM_SUB_8_BIT = 0x2, // must be 2 for backward compatibility
- };
-
- // MP3 sub format field definition : can use 11 LSBs in the same way as MP3 frame header to specify
- // bit rate, stereo mode, version...
- enum mp3_sub_format {
- //TODO
- };
-
- // AMR NB/WB sub format field definition: specify frame block interleaving, bandwidth efficient or octet aligned,
- // encoding mode for recording...
- enum amr_sub_format {
- //TODO
- };
-
- // AAC sub format field definition: specify profile or bitrate for recording...
- enum aac_sub_format {
- //TODO
- };
-
- // VORBIS sub format field definition: specify quality for recording...
- enum vorbis_sub_format {
- //TODO
- };
-
- // Audio format consists in a main format field (upper 8 bits) and a sub format field (lower 24 bits).
- // The main format indicates the main codec type. The sub format field indicates options and parameters
- // for each format. The sub format is mainly used for record to indicate for instance the requested bitrate
- // or profile. It can also be used for certain formats to give informations not present in the encoded
- // audio stream (e.g. octet alignement for AMR).
- enum audio_format {
- INVALID_FORMAT = -1,
- FORMAT_DEFAULT = 0,
- PCM = 0x00000000, // must be 0 for backward compatibility
- MP3 = 0x01000000,
- AMR_NB = 0x02000000,
- AMR_WB = 0x03000000,
- AAC = 0x04000000,
- HE_AAC_V1 = 0x05000000,
- HE_AAC_V2 = 0x06000000,
- VORBIS = 0x07000000,
- EVRC = 0x08000000,
- QCELP = 0x09000000,
- VOIP_PCM_INPUT = 0x0A000000,
- MAIN_FORMAT_MASK = 0xFF000000,
- SUB_FORMAT_MASK = 0x00FFFFFF,
- // Aliases
- PCM_16_BIT = (PCM|PCM_SUB_16_BIT),
- PCM_8_BIT = (PCM|PCM_SUB_8_BIT)
- };
-
-
- // Channel mask definitions must be kept in sync with JAVA values in /media/java/android/media/AudioFormat.java
- enum audio_channels {
- // output channels
- CHANNEL_OUT_FRONT_LEFT = 0x4,
- CHANNEL_OUT_FRONT_RIGHT = 0x8,
- CHANNEL_OUT_FRONT_CENTER = 0x10,
- CHANNEL_OUT_LOW_FREQUENCY = 0x20,
- CHANNEL_OUT_BACK_LEFT = 0x40,
- CHANNEL_OUT_BACK_RIGHT = 0x80,
- CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x100,
- CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x200,
- CHANNEL_OUT_BACK_CENTER = 0x400,
- CHANNEL_OUT_MONO = CHANNEL_OUT_FRONT_LEFT,
- CHANNEL_OUT_STEREO = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT),
- CHANNEL_OUT_QUAD = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
- CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT),
- CHANNEL_OUT_SURROUND = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
- CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_BACK_CENTER),
- CHANNEL_OUT_5POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
- CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT),
- CHANNEL_OUT_7POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
- CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
- CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER),
- CHANNEL_OUT_ALL = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
- CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
- CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER | CHANNEL_OUT_BACK_CENTER),
-
- // input channels
- CHANNEL_IN_LEFT = 0x4,
- CHANNEL_IN_RIGHT = 0x8,
- CHANNEL_IN_FRONT = 0x10,
- CHANNEL_IN_BACK = 0x20,
- CHANNEL_IN_LEFT_PROCESSED = 0x40,
- CHANNEL_IN_RIGHT_PROCESSED = 0x80,
- CHANNEL_IN_FRONT_PROCESSED = 0x100,
- CHANNEL_IN_BACK_PROCESSED = 0x200,
- CHANNEL_IN_PRESSURE = 0x400,
- CHANNEL_IN_X_AXIS = 0x800,
- CHANNEL_IN_Y_AXIS = 0x1000,
- CHANNEL_IN_Z_AXIS = 0x2000,
- CHANNEL_IN_VOICE_UPLINK = 0x4000,
- CHANNEL_IN_VOICE_DNLINK = 0x8000,
- CHANNEL_IN_MONO = CHANNEL_IN_FRONT,
- CHANNEL_IN_STEREO = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT),
- CHANNEL_IN_ALL = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT | CHANNEL_IN_FRONT | CHANNEL_IN_BACK|
- CHANNEL_IN_LEFT_PROCESSED | CHANNEL_IN_RIGHT_PROCESSED | CHANNEL_IN_FRONT_PROCESSED | CHANNEL_IN_BACK_PROCESSED|
- CHANNEL_IN_PRESSURE | CHANNEL_IN_X_AXIS | CHANNEL_IN_Y_AXIS | CHANNEL_IN_Z_AXIS |
- CHANNEL_IN_VOICE_UPLINK | CHANNEL_IN_VOICE_DNLINK)
- };
-
- enum audio_mode {
- MODE_INVALID = -2,
- MODE_CURRENT = -1,
- MODE_NORMAL = 0,
- MODE_RINGTONE,
- MODE_IN_CALL,
- MODE_IN_COMMUNICATION,
- NUM_MODES // not a valid entry, denotes end-of-list
- };
-
- enum audio_in_acoustics {
- AGC_ENABLE = 0x0001,
- AGC_DISABLE = 0,
- NS_ENABLE = 0x0002,
- NS_DISABLE = 0,
- TX_IIR_ENABLE = 0x0004,
- TX_DISABLE = 0
- };
-
- // special audio session values
- enum audio_sessions {
- SESSION_OUTPUT_STAGE = -1, // session for effects attached to a particular output stream
- // (value must be less than 0)
- SESSION_OUTPUT_MIX = 0, // session for effects applied to output mix. These effects can
- // be moved by audio policy manager to another output stream
- // (value must be 0)
- };
-
- /* These are static methods to control the system-wide AudioFlinger
- * only privileged processes can have access to them
- */
-
- // mute/unmute microphone
- static status_t muteMicrophone(bool state);
- static status_t isMicrophoneMuted(bool *state);
-
- // set/get master volume
- static status_t setMasterVolume(float value);
- static status_t getMasterVolume(float* volume);
- // mute/unmute audio outputs
- static status_t setMasterMute(bool mute);
- static status_t getMasterMute(bool* mute);
-
- // set/get stream volume on specified output
- static status_t setStreamVolume(int stream, float value, int output);
- static status_t getStreamVolume(int stream, float* volume, int output);
-
- // mute/unmute stream
- static status_t setStreamMute(int stream, bool mute);
- static status_t getStreamMute(int stream, bool* mute);
-
- // set audio mode in audio hardware (see AudioSystem::audio_mode)
- static status_t setMode(int mode);
-
- // returns true in *state if tracks are active on the specified stream
- static status_t isStreamActive(int stream, bool *state);
-
- // set/get audio hardware parameters. The function accepts a list of parameters
- // key value pairs in the form: key1=value1;key2=value2;...
- // Some keys are reserved for standard parameters (See AudioParameter class).
- static status_t setParameters(audio_io_handle_t ioHandle, const String8& keyValuePairs);
- static String8 getParameters(audio_io_handle_t ioHandle, const String8& keys);
-
- static void setErrorCallback(audio_error_callback cb);
-
- // helper function to obtain AudioFlinger service handle
- static const sp<IAudioFlinger>& get_audio_flinger();
-
- static float linearToLog(int volume);
- static int logToLinear(float volume);
-
- static status_t getOutputSamplingRate(int* samplingRate, int stream = DEFAULT);
- static status_t getOutputFrameCount(int* frameCount, int stream = DEFAULT);
- static status_t getOutputLatency(uint32_t* latency, int stream = DEFAULT);
-
- static bool routedToA2dpOutput(int streamType);
-
- static status_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
- size_t* buffSize);
-
- static status_t setVoiceVolume(float volume);
-
- // return the number of audio frames written by AudioFlinger to audio HAL and
- // audio dsp to DAC since the output on which the specificed stream is playing
- // has exited standby.
- // returned status (from utils/Errors.h) can be:
- // - NO_ERROR: successful operation, halFrames and dspFrames point to valid data
- // - INVALID_OPERATION: Not supported on current hardware platform
- // - BAD_VALUE: invalid parameter
- // NOTE: this feature is not supported on all hardware platforms and it is
- // necessary to check returned status before using the returned values.
- static status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int stream = DEFAULT);
-
- static unsigned int getInputFramesLost(audio_io_handle_t ioHandle);
-
- static int newAudioSessionId();
- //
- // AudioPolicyService interface
- //
-
- enum audio_devices {
- // output devices
- DEVICE_OUT_EARPIECE = 0x1,
- DEVICE_OUT_SPEAKER = 0x2,
- DEVICE_OUT_WIRED_HEADSET = 0x4,
- DEVICE_OUT_WIRED_HEADPHONE = 0x8,
- DEVICE_OUT_BLUETOOTH_SCO = 0x10,
- DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20,
- DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40,
- DEVICE_OUT_BLUETOOTH_A2DP = 0x80,
- DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100,
- DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200,
- DEVICE_OUT_AUX_DIGITAL = 0x400,
- DEVICE_OUT_DEFAULT = 0x8000,
- DEVICE_OUT_ALL = (DEVICE_OUT_EARPIECE | DEVICE_OUT_SPEAKER | DEVICE_OUT_WIRED_HEADSET |
- DEVICE_OUT_WIRED_HEADPHONE | DEVICE_OUT_BLUETOOTH_SCO | DEVICE_OUT_BLUETOOTH_SCO_HEADSET |
- DEVICE_OUT_BLUETOOTH_SCO_CARKIT | DEVICE_OUT_BLUETOOTH_A2DP | DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
- DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER | DEVICE_OUT_AUX_DIGITAL | DEVICE_OUT_DEFAULT),
- DEVICE_OUT_ALL_A2DP = (DEVICE_OUT_BLUETOOTH_A2DP | DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
- DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
-
- // input devices
- DEVICE_IN_COMMUNICATION = 0x10000,
- DEVICE_IN_AMBIENT = 0x20000,
- DEVICE_IN_BUILTIN_MIC = 0x40000,
- DEVICE_IN_BLUETOOTH_SCO_HEADSET = 0x80000,
- DEVICE_IN_WIRED_HEADSET = 0x100000,
- DEVICE_IN_AUX_DIGITAL = 0x200000,
- DEVICE_IN_VOICE_CALL = 0x400000,
- DEVICE_IN_BACK_MIC = 0x800000,
- DEVICE_IN_DEFAULT = 0x80000000,
-
- DEVICE_IN_ALL = (DEVICE_IN_COMMUNICATION | DEVICE_IN_AMBIENT | DEVICE_IN_BUILTIN_MIC |
- DEVICE_IN_BLUETOOTH_SCO_HEADSET | DEVICE_IN_WIRED_HEADSET | DEVICE_IN_AUX_DIGITAL |
- DEVICE_IN_VOICE_CALL | DEVICE_IN_BACK_MIC | DEVICE_IN_DEFAULT)
- };
-
- // device connection states used for setDeviceConnectionState()
- enum device_connection_state {
- DEVICE_STATE_UNAVAILABLE,
- DEVICE_STATE_AVAILABLE,
- NUM_DEVICE_STATES
- };
-
- // request to open a direct output with getOutput() (by opposition to sharing an output with other AudioTracks)
- enum output_flags {
- OUTPUT_FLAG_INDIRECT = 0x0,
- OUTPUT_FLAG_DIRECT = 0x1
- };
-
- // device categories used for setForceUse()
- enum forced_config {
- FORCE_NONE,
- FORCE_SPEAKER,
- FORCE_HEADPHONES,
- FORCE_BT_SCO,
- FORCE_BT_A2DP,
- FORCE_WIRED_ACCESSORY,
- FORCE_BT_CAR_DOCK,
- FORCE_BT_DESK_DOCK,
- FORCE_ANALOG_DOCK,
- FORCE_DIGITAL_DOCK,
- FORCE_NO_BT_A2DP,
- NUM_FORCE_CONFIG,
- FORCE_DEFAULT = FORCE_NONE
- };
-
- // usages used for setForceUse()
- enum force_use {
- FOR_COMMUNICATION,
- FOR_MEDIA,
- FOR_RECORD,
- FOR_DOCK,
- NUM_FORCE_USE
- };
-
- // types of io configuration change events received with ioConfigChanged()
- enum io_config_event {
- OUTPUT_OPENED,
- OUTPUT_CLOSED,
- OUTPUT_CONFIG_CHANGED,
- INPUT_OPENED,
- INPUT_CLOSED,
- INPUT_CONFIG_CHANGED,
- STREAM_CONFIG_CHANGED,
- NUM_CONFIG_EVENTS
- };
-
- // audio output descritor used to cache output configurations in client process to avoid frequent calls
- // through IAudioFlinger
- class OutputDescriptor {
- public:
- OutputDescriptor()
- : samplingRate(0), format(0), channels(0), frameCount(0), latency(0) {}
-
- uint32_t samplingRate;
- int32_t format;
- int32_t channels;
- size_t frameCount;
- uint32_t latency;
- };
-
- //
- // IAudioPolicyService interface (see AudioPolicyInterface for method descriptions)
- //
- static status_t setDeviceConnectionState(audio_devices device, device_connection_state state, const char *device_address);
- static device_connection_state getDeviceConnectionState(audio_devices device, const char *device_address);
- static status_t setPhoneState(int state);
-#if ANDROID_VERSION >= 17
- static status_t setPhoneState(audio_mode_t state);
-#endif
- static status_t setRingerMode(uint32_t mode, uint32_t mask);
-#ifdef VANILLA_ANDROID
- static status_t setForceUse(force_use usage, forced_config config);
- static forced_config getForceUse(force_use usage);
- static audio_io_handle_t getOutput(stream_type stream,
- uint32_t samplingRate = 0,
- uint32_t format = FORMAT_DEFAULT,
- uint32_t channels = CHANNEL_OUT_STEREO,
- output_flags flags = OUTPUT_FLAG_INDIRECT);
- static status_t setDeviceConnectionState(audio_devices_t device, audio_policy_dev_state_t state, const char *device_address);
- static status_t setFmVolume(float volume);
- static audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, const char *device_address);
-#else
- static status_t setForceUse(force_use usage, forced_config config) __attribute__((weak));
- static forced_config getForceUse(force_use usage) __attribute__((weak));
- static audio_io_handle_t getOutput(stream_type stream,
- uint32_t samplingRate = 0,
- uint32_t format = FORMAT_DEFAULT,
- uint32_t channels = CHANNEL_OUT_STEREO,
- output_flags flags = OUTPUT_FLAG_INDIRECT) __attribute__((weak));
-
- static status_t setForceUse(audio_policy_force_use_t usage, audio_policy_forced_cfg_t config) __attribute__((weak));
- static audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage) __attribute__((weak));
- static audio_io_handle_t getOutput(audio_stream_type_t stream,
- uint32_t samplingRate = 0,
- uint32_t format = AUDIO_FORMAT_DEFAULT,
- uint32_t channels = AUDIO_CHANNEL_OUT_STEREO,
- audio_policy_output_flags_t flags = AUDIO_POLICY_OUTPUT_FLAG_INDIRECT) __attribute__((weak));
- static status_t setDeviceConnectionState(audio_devices_t device, audio_policy_dev_state_t state, const char *device_address) __attribute__((weak));
- static status_t setFmVolume(float volume) __attribute__((weak));
- static audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device, const char *device_address) __attribute__((weak));
-
-#endif
- static status_t startOutput(audio_io_handle_t output,
- AudioSystem::stream_type stream,
- int session = 0);
- static status_t stopOutput(audio_io_handle_t output,
- AudioSystem::stream_type stream,
- int session = 0);
- static void releaseOutput(audio_io_handle_t output);
- static audio_io_handle_t getInput(int inputSource,
- uint32_t samplingRate = 0,
- uint32_t format = FORMAT_DEFAULT,
- uint32_t channels = CHANNEL_IN_MONO,
- audio_in_acoustics acoustics = (audio_in_acoustics)0);
- static status_t startInput(audio_io_handle_t input);
- static status_t stopInput(audio_io_handle_t input);
- static void releaseInput(audio_io_handle_t input);
- static status_t initStreamVolume(stream_type stream,
- int indexMin,
- int indexMax);
- static status_t initStreamVolume(audio_stream_type_t stream,
- int indexMin,
- int indexMax);
- static status_t setStreamVolumeIndex(stream_type stream, int index);
- static status_t setStreamVolumeIndex(audio_stream_type_t stream, int index);
-#if ANDROID_VERSION >= 17
- static status_t setStreamVolumeIndex(audio_stream_type_t stream,
- int index,
- audio_devices_t device);
- static status_t getStreamVolumeIndex(audio_stream_type_t stream,
- int *index,
- audio_devices_t device);
-#endif
- static status_t getStreamVolumeIndex(stream_type stream, int *index);
- static status_t getStreamVolumeIndex(audio_stream_type_t stream, int *index);
-
- static uint32_t getStrategyForStream(stream_type stream);
-#if ANDROID_VERSION >= 17
- static audio_devices_t getDevicesForStream(audio_stream_type_t stream);
-#endif
-
- static audio_io_handle_t getOutputForEffect(effect_descriptor_t *desc);
- static status_t registerEffect(effect_descriptor_t *desc,
- audio_io_handle_t output,
- uint32_t strategy,
- int session,
- int id);
- static status_t unregisterEffect(int id);
-
- static const sp<IAudioPolicyService>& get_audio_policy_service();
-
- // ----------------------------------------------------------------------------
-
- static uint32_t popCount(uint32_t u);
- static bool isOutputDevice(audio_devices device);
- static bool isInputDevice(audio_devices device);
- static bool isA2dpDevice(audio_devices device);
- static bool isBluetoothScoDevice(audio_devices device);
- static bool isSeperatedStream(stream_type stream);
- static bool isLowVisibility(stream_type stream);
- static bool isOutputChannel(uint32_t channel);
- static bool isInputChannel(uint32_t channel);
- static bool isValidFormat(uint32_t format);
- static bool isLinearPCM(uint32_t format);
- static bool isModeInCall();
-
-#if ANDROID_VERSION >= 21
- class AudioPortCallback : public RefBase
- {
- public:
-
- AudioPortCallback() {}
- virtual ~AudioPortCallback() {}
-
- virtual void onAudioPortListUpdate() = 0;
- virtual void onAudioPatchListUpdate() = 0;
- virtual void onServiceDied() = 0;
-
- };
-
- static void setAudioPortCallback(sp<AudioPortCallback> callBack);
-#endif
-
-private:
-
- class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient
- {
- public:
- AudioFlingerClient() {
- }
-
- // DeathRecipient
- virtual void binderDied(const wp<IBinder>& who);
-
- // IAudioFlingerClient
-
- // indicate a change in the configuration of an output or input: keeps the cached
- // values for output/input parameters upto date in client process
- virtual void ioConfigChanged(int event, int ioHandle, void *param2);
- };
-
- class AudioPolicyServiceClient: public IBinder::DeathRecipient
- {
- public:
- AudioPolicyServiceClient() {
- }
-
- // DeathRecipient
- virtual void binderDied(const wp<IBinder>& who);
- };
-
- static sp<AudioFlingerClient> gAudioFlingerClient;
- static sp<AudioPolicyServiceClient> gAudioPolicyServiceClient;
- friend class AudioFlingerClient;
- friend class AudioPolicyServiceClient;
-
- static Mutex gLock;
- static sp<IAudioFlinger> gAudioFlinger;
- static audio_error_callback gAudioErrorCallback;
-
- static size_t gInBuffSize;
- // previous parameters for recording buffer size queries
- static uint32_t gPrevInSamplingRate;
- static int gPrevInFormat;
- static int gPrevInChannelCount;
-
- static sp<IAudioPolicyService> gAudioPolicyService;
-
- // mapping between stream types and outputs
- static DefaultKeyedVector<int, audio_io_handle_t> gStreamOutputMap;
- // list of output descritor containing cached parameters (sampling rate, framecount, channel count...)
- static DefaultKeyedVector<audio_io_handle_t, OutputDescriptor *> gOutputs;
-};
-
-class AudioParameter {
-
-public:
- AudioParameter() {}
- AudioParameter(const String8& keyValuePairs);
- virtual ~AudioParameter();
-
- // reserved parameter keys for changing standard parameters with setParameters() function.
- // Using these keys is mandatory for AudioFlinger to properly monitor audio output/input
- // configuration changes and act accordingly.
- // keyRouting: to change audio routing, value is an int in AudioSystem::audio_devices
- // keySamplingRate: to change sampling rate routing, value is an int
- // keyFormat: to change audio format, value is an int in AudioSystem::audio_format
- // keyChannels: to change audio channel configuration, value is an int in AudioSystem::audio_channels
- // keyFrameCount: to change audio output frame count, value is an int
- // keyInputSource: to change audio input source, value is an int in audio_source
- // (defined in media/mediarecorder.h)
- static const char *keyRouting;
- static const char *keySamplingRate;
- static const char *keyFormat;
- static const char *keyChannels;
- static const char *keyFrameCount;
- static const char *keyInputSource;
-
- String8 toString();
-
- status_t add(const String8& key, const String8& value);
- status_t addInt(const String8& key, const int value);
- status_t addFloat(const String8& key, const float value);
-
- status_t remove(const String8& key);
-
- status_t get(const String8& key, String8& value);
- status_t getInt(const String8& key, int& value);
- status_t getFloat(const String8& key, float& value);
- status_t getAt(size_t index, String8& key, String8& value);
-
- size_t size() { return mParameters.size(); }
-
-private:
- String8 mKeyValuePairs;
- KeyedVector <String8, String8> mParameters;
-};
-
-}; // namespace android
-
-#pragma GCC visibility pop
-
-#endif /*ANDROID_AUDIOSYSTEM_H_*/
diff --git a/dom/system/gonk/android_audio/AudioTrack.h b/dom/system/gonk/android_audio/AudioTrack.h
deleted file mode 100644
index 6f8c6bb28..000000000
--- a/dom/system/gonk/android_audio/AudioTrack.h
+++ /dev/null
@@ -1,489 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_AUDIOTRACK_H
-#define ANDROID_AUDIOTRACK_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include "IAudioFlinger.h"
-#include "IAudioTrack.h"
-#include "AudioSystem.h"
-
-#include <utils/RefBase.h>
-#include <utils/Errors.h>
-#include <binder/IInterface.h>
-#include <binder/IMemory.h>
-#include <utils/threads.h>
-
-
-namespace android {
-
-// ----------------------------------------------------------------------------
-
-class audio_track_cblk_t;
-
-// ----------------------------------------------------------------------------
-
-class AudioTrack
-{
-public:
- enum channel_index {
- MONO = 0,
- LEFT = 0,
- RIGHT = 1
- };
-
- /* Events used by AudioTrack callback function (audio_track_cblk_t).
- */
- enum event_type {
- EVENT_MORE_DATA = 0, // Request to write more data to PCM buffer.
- EVENT_UNDERRUN = 1, // PCM buffer underrun occured.
- EVENT_LOOP_END = 2, // Sample loop end was reached; playback restarted from loop start if loop count was not 0.
- EVENT_MARKER = 3, // Playback head is at the specified marker position (See setMarkerPosition()).
- EVENT_NEW_POS = 4, // Playback head is at a new position (See setPositionUpdatePeriod()).
- EVENT_BUFFER_END = 5 // Playback head is at the end of the buffer.
- };
-
- /* Create Buffer on the stack and pass it to obtainBuffer()
- * and releaseBuffer().
- */
-
- class Buffer
- {
- public:
- enum {
- MUTE = 0x00000001
- };
- uint32_t flags;
- int channelCount;
- int format;
- size_t frameCount;
- size_t size;
- union {
- void* raw;
- short* i16;
- int8_t* i8;
- };
- };
-
-
- /* As a convenience, if a callback is supplied, a handler thread
- * is automatically created with the appropriate priority. This thread
- * invokes the callback when a new buffer becomes availlable or an underrun condition occurs.
- * Parameters:
- *
- * event: type of event notified (see enum AudioTrack::event_type).
- * user: Pointer to context for use by the callback receiver.
- * info: Pointer to optional parameter according to event type:
- * - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
- * more bytes than indicated by 'size' field and update 'size' if less bytes are
- * written.
- * - EVENT_UNDERRUN: unused.
- * - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
- * - EVENT_MARKER: pointer to an uin32_t containing the marker position in frames.
- * - EVENT_NEW_POS: pointer to an uin32_t containing the new position in frames.
- * - EVENT_BUFFER_END: unused.
- */
-
- typedef void (*callback_t)(int event, void* user, void *info);
-
- /* Returns the minimum frame count required for the successful creation of
- * an AudioTrack object.
- * Returned status (from utils/Errors.h) can be:
- * - NO_ERROR: successful operation
- * - NO_INIT: audio server or audio hardware not initialized
- */
-
- static status_t getMinFrameCount(int* frameCount,
- int streamType =-1,
- uint32_t sampleRate = 0);
-
- /* Constructs an uninitialized AudioTrack. No connection with
- * AudioFlinger takes place.
- */
- AudioTrack();
-
- /* Creates an audio track and registers it with AudioFlinger.
- * Once created, the track needs to be started before it can be used.
- * Unspecified values are set to the audio hardware's current
- * values.
- *
- * Parameters:
- *
- * streamType: Select the type of audio stream this track is attached to
- * (e.g. AudioSystem::MUSIC).
- * sampleRate: Track sampling rate in Hz.
- * format: Audio format (e.g AudioSystem::PCM_16_BIT for signed
- * 16 bits per sample).
- * channels: Channel mask: see AudioSystem::audio_channels.
- * frameCount: Total size of track PCM buffer in frames. This defines the
- * latency of the track.
- * flags: Reserved for future use.
- * cbf: Callback function. If not null, this function is called periodically
- * to request new PCM data.
- * notificationFrames: The callback function is called each time notificationFrames PCM
- * frames have been comsumed from track input buffer.
- * user Context for use by the callback receiver.
- */
-
- AudioTrack( int streamType,
- uint32_t sampleRate = 0,
- int format = 0,
- int channels = 0,
- int frameCount = 0,
- uint32_t flags = 0,
- callback_t cbf = 0,
- void* user = 0,
- int notificationFrames = 0,
- int sessionId = 0);
-
- /* Creates an audio track and registers it with AudioFlinger. With this constructor,
- * The PCM data to be rendered by AudioTrack is passed in a shared memory buffer
- * identified by the argument sharedBuffer. This prototype is for static buffer playback.
- * PCM data must be present into memory before the AudioTrack is started.
- * The Write() and Flush() methods are not supported in this case.
- * It is recommented to pass a callback function to be notified of playback end by an
- * EVENT_UNDERRUN event.
- */
-
- AudioTrack( int streamType,
- uint32_t sampleRate = 0,
- int format = 0,
- int channels = 0,
- const sp<IMemory>& sharedBuffer = 0,
- uint32_t flags = 0,
- callback_t cbf = 0,
- void* user = 0,
- int notificationFrames = 0,
- int sessionId = 0);
-
- /* Terminates the AudioTrack and unregisters it from AudioFlinger.
- * Also destroys all resources assotiated with the AudioTrack.
- */
- ~AudioTrack();
-
-
- /* Initialize an uninitialized AudioTrack.
- * Returned status (from utils/Errors.h) can be:
- * - NO_ERROR: successful intialization
- * - INVALID_OPERATION: AudioTrack is already intitialized
- * - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
- * - NO_INIT: audio server or audio hardware not initialized
- * */
- status_t set(int streamType =-1,
- uint32_t sampleRate = 0,
- int format = 0,
- int channels = 0,
- int frameCount = 0,
- uint32_t flags = 0,
- callback_t cbf = 0,
- void* user = 0,
- int notificationFrames = 0,
- const sp<IMemory>& sharedBuffer = 0,
- bool threadCanCallJava = false,
- int sessionId = 0);
-
-
- /* Result of constructing the AudioTrack. This must be checked
- * before using any AudioTrack API (except for set()), using
- * an uninitialized AudioTrack produces undefined results.
- * See set() method above for possible return codes.
- */
- status_t initCheck() const;
-
- /* Returns this track's latency in milliseconds.
- * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
- * and audio hardware driver.
- */
- uint32_t latency() const;
-
- /* getters, see constructor */
-
- int streamType() const;
- int format() const;
- int channelCount() const;
- uint32_t frameCount() const;
- int frameSize() const;
- sp<IMemory>& sharedBuffer();
-
-
- /* After it's created the track is not active. Call start() to
- * make it active. If set, the callback will start being called.
- */
- void start();
-
- /* Stop a track. If set, the callback will cease being called and
- * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
- * and will fill up buffers until the pool is exhausted.
- */
- void stop();
- bool stopped() const;
-
- /* flush a stopped track. All pending buffers are discarded.
- * This function has no effect if the track is not stoped.
- */
- void flush();
-
- /* Pause a track. If set, the callback will cease being called and
- * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
- * and will fill up buffers until the pool is exhausted.
- */
- void pause();
-
- /* mute or unmutes this track.
- * While mutted, the callback, if set, is still called.
- */
- void mute(bool);
- bool muted() const;
-
-
- /* set volume for this track, mostly used for games' sound effects
- * left and right volumes. Levels must be <= 1.0.
- */
- status_t setVolume(float left, float right);
- void getVolume(float* left, float* right);
-
- /* set the send level for this track. An auxiliary effect should be attached
- * to the track with attachEffect(). Level must be <= 1.0.
- */
- status_t setAuxEffectSendLevel(float level);
- void getAuxEffectSendLevel(float* level);
-
- /* set sample rate for this track, mostly used for games' sound effects
- */
- status_t setSampleRate(int sampleRate);
- uint32_t getSampleRate();
-
- /* Enables looping and sets the start and end points of looping.
- *
- * Parameters:
- *
- * loopStart: loop start expressed as the number of PCM frames played since AudioTrack start.
- * loopEnd: loop end expressed as the number of PCM frames played since AudioTrack start.
- * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any pending or
- * active loop. loopCount = -1 means infinite looping.
- *
- * For proper operation the following condition must be respected:
- * (loopEnd-loopStart) <= framecount()
- */
- status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
- status_t getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount);
-
-
- /* Sets marker position. When playback reaches the number of frames specified, a callback with event
- * type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker notification
- * callback.
- * If the AudioTrack has been opened with no callback function associated, the operation will fail.
- *
- * Parameters:
- *
- * marker: marker position expressed in frames.
- *
- * Returned status (from utils/Errors.h) can be:
- * - NO_ERROR: successful operation
- * - INVALID_OPERATION: the AudioTrack has no callback installed.
- */
- status_t setMarkerPosition(uint32_t marker);
- status_t getMarkerPosition(uint32_t *marker);
-
-
- /* Sets position update period. Every time the number of frames specified has been played,
- * a callback with event type EVENT_NEW_POS is called.
- * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
- * callback.
- * If the AudioTrack has been opened with no callback function associated, the operation will fail.
- *
- * Parameters:
- *
- * updatePeriod: position update notification period expressed in frames.
- *
- * Returned status (from utils/Errors.h) can be:
- * - NO_ERROR: successful operation
- * - INVALID_OPERATION: the AudioTrack has no callback installed.
- */
- status_t setPositionUpdatePeriod(uint32_t updatePeriod);
- status_t getPositionUpdatePeriod(uint32_t *updatePeriod);
-
-
- /* Sets playback head position within AudioTrack buffer. The new position is specified
- * in number of frames.
- * This method must be called with the AudioTrack in paused or stopped state.
- * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames.
- * Therefore using this method makes sense only when playing a "static" audio buffer
- * as opposed to streaming.
- * The getPosition() method on the other hand returns the total number of frames played since
- * playback start.
- *
- * Parameters:
- *
- * position: New playback head position within AudioTrack buffer.
- *
- * Returned status (from utils/Errors.h) can be:
- * - NO_ERROR: successful operation
- * - INVALID_OPERATION: the AudioTrack is not stopped.
- * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer
- */
- status_t setPosition(uint32_t position);
- status_t getPosition(uint32_t *position);
-
- /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
- * rewriting the buffer before restarting playback after a stop.
- * This method must be called with the AudioTrack in paused or stopped state.
- *
- * Returned status (from utils/Errors.h) can be:
- * - NO_ERROR: successful operation
- * - INVALID_OPERATION: the AudioTrack is not stopped.
- */
- status_t reload();
-
- /* returns a handle on the audio output used by this AudioTrack.
- *
- * Parameters:
- * none.
- *
- * Returned value:
- * handle on audio hardware output
- */
- audio_io_handle_t getOutput();
-
- /* returns the unique ID associated to this track.
- *
- * Parameters:
- * none.
- *
- * Returned value:
- * AudioTrack ID.
- */
- int getSessionId();
-
-
- /* Attach track auxiliary output to specified effect. Used effectId = 0
- * to detach track from effect.
- *
- * Parameters:
- *
- * effectId: effectId obtained from AudioEffect::id().
- *
- * Returned status (from utils/Errors.h) can be:
- * - NO_ERROR: successful operation
- * - INVALID_OPERATION: the effect is not an auxiliary effect.
- * - BAD_VALUE: The specified effect ID is invalid
- */
- status_t attachAuxEffect(int effectId);
-
- /* obtains a buffer of "frameCount" frames. The buffer must be
- * filled entirely. If the track is stopped, obtainBuffer() returns
- * STOPPED instead of NO_ERROR as long as there are buffers availlable,
- * at which point NO_MORE_BUFFERS is returned.
- * Buffers will be returned until the pool (buffercount())
- * is exhausted, at which point obtainBuffer() will either block
- * or return WOULD_BLOCK depending on the value of the "blocking"
- * parameter.
- */
-
- enum {
- NO_MORE_BUFFERS = 0x80000001,
- STOPPED = 1
- };
-
- status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
- void releaseBuffer(Buffer* audioBuffer);
-
-
- /* As a convenience we provide a write() interface to the audio buffer.
- * This is implemented on top of lockBuffer/unlockBuffer. For best
- * performance
- *
- */
- ssize_t write(const void* buffer, size_t size);
-
- /*
- * Dumps the state of an audio track.
- */
- status_t dump(int fd, const Vector<String16>& args) const;
-
-private:
- /* copying audio tracks is not allowed */
- AudioTrack(const AudioTrack& other);
- AudioTrack& operator = (const AudioTrack& other);
-
- /* a small internal class to handle the callback */
- class AudioTrackThread : public Thread
- {
- public:
- AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
- private:
- friend class AudioTrack;
- virtual bool threadLoop();
- virtual status_t readyToRun();
- virtual void onFirstRef();
- AudioTrack& mReceiver;
- Mutex mLock;
- };
-
- bool processAudioBuffer(const sp<AudioTrackThread>& thread);
- status_t createTrack(int streamType,
- uint32_t sampleRate,
- int format,
- int channelCount,
- int frameCount,
- uint32_t flags,
- const sp<IMemory>& sharedBuffer,
- audio_io_handle_t output,
- bool enforceFrameCount);
-
- sp<IAudioTrack> mAudioTrack;
- sp<IMemory> mCblkMemory;
- sp<AudioTrackThread> mAudioTrackThread;
-
- float mVolume[2];
- float mSendLevel;
- uint32_t mFrameCount;
-
- audio_track_cblk_t* mCblk;
- uint8_t mStreamType;
- uint8_t mFormat;
- uint8_t mChannelCount;
- uint8_t mMuted;
- uint32_t mChannels;
- status_t mStatus;
- uint32_t mLatency;
-
- volatile int32_t mActive;
-
- callback_t mCbf;
- void* mUserData;
- uint32_t mNotificationFramesReq; // requested number of frames between each notification callback
- uint32_t mNotificationFramesAct; // actual number of frames between each notification callback
- sp<IMemory> mSharedBuffer;
- int mLoopCount;
- uint32_t mRemainingFrames;
- uint32_t mMarkerPosition;
- bool mMarkerReached;
- uint32_t mNewPosition;
- uint32_t mUpdatePeriod;
- uint32_t mFlags;
- int mSessionId;
- int mAuxEffectId;
- uint32_t mPadding[8];
-};
-
-
-}; // namespace android
-
-#endif // ANDROID_AUDIOTRACK_H
diff --git a/dom/system/gonk/android_audio/EffectApi.h b/dom/system/gonk/android_audio/EffectApi.h
deleted file mode 100644
index 729545d0c..000000000
--- a/dom/system/gonk/android_audio/EffectApi.h
+++ /dev/null
@@ -1,798 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_EFFECTAPI_H_
-#define ANDROID_EFFECTAPI_H_
-
-#include <errno.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#if __cplusplus
-extern "C" {
-#endif
-
-/////////////////////////////////////////////////
-// Effect control interface
-/////////////////////////////////////////////////
-
-// The effect control interface is exposed by each effect engine implementation. It consists of
-// a set of functions controlling the configuration, activation and process of the engine.
-// The functions are grouped in a structure of type effect_interface_s:
-// struct effect_interface_s {
-// effect_process_t process;
-// effect_command_t command;
-// };
-
-
-// effect_interface_t: Effect control interface handle.
-// The effect_interface_t serves two purposes regarding the implementation of the effect engine:
-// - 1 it is the address of a pointer to an effect_interface_s structure where the functions
-// of the effect control API for a particular effect are located.
-// - 2 it is the address of the context of a particular effect instance.
-// A typical implementation in the effect library would define a structure as follows:
-// struct effect_module_s {
-// const struct effect_interface_s *itfe;
-// effect_config_t config;
-// effect_context_t context;
-// }
-// The implementation of EffectCreate() function would then allocate a structure of this
-// type and return its address as effect_interface_t
-typedef struct effect_interface_s **effect_interface_t;
-
-
-// Effect API version 1.0
-#define EFFECT_API_VERSION 0x0100 // Format 0xMMmm MM: Major version, mm: minor version
-
-// Maximum length of character strings in structures defines by this API.
-#define EFFECT_STRING_LEN_MAX 64
-
-//
-//--- Effect descriptor structure effect_descriptor_t
-//
-
-// Unique effect ID (can be generated from the following site:
-// http://www.itu.int/ITU-T/asn1/uuid.html)
-// This format is used for both "type" and "uuid" fields of the effect descriptor structure.
-// - When used for effect type and the engine is implementing and effect corresponding to a standard
-// OpenSL ES interface, this ID must be the one defined in OpenSLES_IID.h for that interface.
-// - When used as uuid, it should be a unique UUID for this particular implementation.
-typedef struct effect_uuid_s {
- uint32_t timeLow;
- uint16_t timeMid;
- uint16_t timeHiAndVersion;
- uint16_t clockSeq;
- uint8_t node[6];
-} effect_uuid_t;
-
-// NULL UUID definition (matches SL_IID_NULL_)
-#define EFFECT_UUID_INITIALIZER { 0xec7178ec, 0xe5e1, 0x4432, 0xa3f4, \
- { 0x46, 0x57, 0xe6, 0x79, 0x52, 0x10 } }
-static const effect_uuid_t EFFECT_UUID_NULL_ = EFFECT_UUID_INITIALIZER;
-const effect_uuid_t * const EFFECT_UUID_NULL = &EFFECT_UUID_NULL_;
-const char * const EFFECT_UUID_NULL_STR = "ec7178ec-e5e1-4432-a3f4-4657e6795210";
-
-// The effect descriptor contains necessary information to facilitate the enumeration of the effect
-// engines present in a library.
-typedef struct effect_descriptor_s {
- effect_uuid_t type; // UUID of to the OpenSL ES interface implemented by this effect
- effect_uuid_t uuid; // UUID for this particular implementation
- uint16_t apiVersion; // Version of the effect API implemented: matches EFFECT_API_VERSION
- uint32_t flags; // effect engine capabilities/requirements flags (see below)
- uint16_t cpuLoad; // CPU load indication (see below)
- uint16_t memoryUsage; // Data Memory usage (see below)
- char name[EFFECT_STRING_LEN_MAX]; // human readable effect name
- char implementor[EFFECT_STRING_LEN_MAX]; // human readable effect implementor name
-} effect_descriptor_t;
-
-// CPU load and memory usage indication: each effect implementation must provide an indication of
-// its CPU and memory usage for the audio effect framework to limit the number of effects
-// instantiated at a given time on a given platform.
-// The CPU load is expressed in 0.1 MIPS units as estimated on an ARM9E core (ARMv5TE) with 0 WS.
-// The memory usage is expressed in KB and includes only dynamically allocated memory
-
-// Definitions for flags field of effect descriptor.
-// +---------------------------+-----------+-----------------------------------
-// | description | bits | values
-// +---------------------------+-----------+-----------------------------------
-// | connection mode | 0..1 | 0 insert: after track process
-// | | | 1 auxiliary: connect to track auxiliary
-// | | | output and use send level
-// | | | 2 replace: replaces track process function;
-// | | | must implement SRC, volume and mono to stereo.
-// | | | 3 reserved
-// +---------------------------+-----------+-----------------------------------
-// | insertion preference | 2..4 | 0 none
-// | | | 1 first of the chain
-// | | | 2 last of the chain
-// | | | 3 exclusive (only effect in the insert chain)
-// | | | 4..7 reserved
-// +---------------------------+-----------+-----------------------------------
-// | Volume management | 5..6 | 0 none
-// | | | 1 implements volume control
-// | | | 2 requires volume indication
-// | | | 3 reserved
-// +---------------------------+-----------+-----------------------------------
-// | Device indication | 7..8 | 0 none
-// | | | 1 requires device updates
-// | | | 2..3 reserved
-// +---------------------------+-----------+-----------------------------------
-// | Sample input mode | 9..10 | 0 direct: process() function or EFFECT_CMD_CONFIGURE
-// | | | command must specify a buffer descriptor
-// | | | 1 provider: process() function uses the
-// | | | bufferProvider indicated by the
-// | | | EFFECT_CMD_CONFIGURE command to request input.
-// | | | buffers.
-// | | | 2 both: both input modes are supported
-// | | | 3 reserved
-// +---------------------------+-----------+-----------------------------------
-// | Sample output mode | 11..12 | 0 direct: process() function or EFFECT_CMD_CONFIGURE
-// | | | command must specify a buffer descriptor
-// | | | 1 provider: process() function uses the
-// | | | bufferProvider indicated by the
-// | | | EFFECT_CMD_CONFIGURE command to request output
-// | | | buffers.
-// | | | 2 both: both output modes are supported
-// | | | 3 reserved
-// +---------------------------+-----------+-----------------------------------
-// | Hardware acceleration | 13..15 | 0 No hardware acceleration
-// | | | 1 non tunneled hw acceleration: the process() function
-// | | | reads the samples, send them to HW accelerated
-// | | | effect processor, reads back the processed samples
-// | | | and returns them to the output buffer.
-// | | | 2 tunneled hw acceleration: the process() function is
-// | | | transparent. The effect interface is only used to
-// | | | control the effect engine. This mode is relevant for
-// | | | global effects actually applied by the audio
-// | | | hardware on the output stream.
-// +---------------------------+-----------+-----------------------------------
-// | Audio Mode indication | 16..17 | 0 none
-// | | | 1 requires audio mode updates
-// | | | 2..3 reserved
-// +---------------------------+-----------+-----------------------------------
-
-// Insert mode
-#define EFFECT_FLAG_TYPE_MASK 0x00000003
-#define EFFECT_FLAG_TYPE_INSERT 0x00000000
-#define EFFECT_FLAG_TYPE_AUXILIARY 0x00000001
-#define EFFECT_FLAG_TYPE_REPLACE 0x00000002
-
-// Insert preference
-#define EFFECT_FLAG_INSERT_MASK 0x0000001C
-#define EFFECT_FLAG_INSERT_ANY 0x00000000
-#define EFFECT_FLAG_INSERT_FIRST 0x00000004
-#define EFFECT_FLAG_INSERT_LAST 0x00000008
-#define EFFECT_FLAG_INSERT_EXCLUSIVE 0x0000000C
-
-
-// Volume control
-#define EFFECT_FLAG_VOLUME_MASK 0x00000060
-#define EFFECT_FLAG_VOLUME_CTRL 0x00000020
-#define EFFECT_FLAG_VOLUME_IND 0x00000040
-#define EFFECT_FLAG_VOLUME_NONE 0x00000000
-
-// Device indication
-#define EFFECT_FLAG_DEVICE_MASK 0x00000180
-#define EFFECT_FLAG_DEVICE_IND 0x00000080
-#define EFFECT_FLAG_DEVICE_NONE 0x00000000
-
-// Sample input modes
-#define EFFECT_FLAG_INPUT_MASK 0x00000600
-#define EFFECT_FLAG_INPUT_DIRECT 0x00000000
-#define EFFECT_FLAG_INPUT_PROVIDER 0x00000200
-#define EFFECT_FLAG_INPUT_BOTH 0x00000400
-
-// Sample output modes
-#define EFFECT_FLAG_OUTPUT_MASK 0x00001800
-#define EFFECT_FLAG_OUTPUT_DIRECT 0x00000000
-#define EFFECT_FLAG_OUTPUT_PROVIDER 0x00000800
-#define EFFECT_FLAG_OUTPUT_BOTH 0x00001000
-
-// Hardware acceleration mode
-#define EFFECT_FLAG_HW_ACC_MASK 0x00006000
-#define EFFECT_FLAG_HW_ACC_SIMPLE 0x00002000
-#define EFFECT_FLAG_HW_ACC_TUNNEL 0x00004000
-
-// Audio mode indication
-#define EFFECT_FLAG_AUDIO_MODE_MASK 0x00018000
-#define EFFECT_FLAG_AUDIO_MODE_IND 0x00008000
-#define EFFECT_FLAG_AUDIO_MODE_NONE 0x00000000
-
-// Forward definition of type audio_buffer_t
-typedef struct audio_buffer_s audio_buffer_t;
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// Function: process
-//
-// Description: Effect process function. Takes input samples as specified
-// (count and location) in input buffer descriptor and output processed
-// samples as specified in output buffer descriptor. If the buffer descriptor
-// is not specified the function must use either the buffer or the
-// buffer provider function installed by the EFFECT_CMD_CONFIGURE command.
-// The effect framework will call the process() function after the EFFECT_CMD_ENABLE
-// command is received and until the EFFECT_CMD_DISABLE is received. When the engine
-// receives the EFFECT_CMD_DISABLE command it should turn off the effect gracefully
-// and when done indicate that it is OK to stop calling the process() function by
-// returning the -ENODATA status.
-//
-// NOTE: the process() function implementation should be "real-time safe" that is
-// it should not perform blocking calls: malloc/free, sleep, read/write/open/close,
-// pthread_cond_wait/pthread_mutex_lock...
-//
-// Input:
-// effect_interface_t: handle to the effect interface this function
-// is called on.
-// inBuffer: buffer descriptor indicating where to read samples to process.
-// If NULL, use the configuration passed by EFFECT_CMD_CONFIGURE command.
-//
-// inBuffer: buffer descriptor indicating where to write processed samples.
-// If NULL, use the configuration passed by EFFECT_CMD_CONFIGURE command.
-//
-// Output:
-// returned value: 0 successful operation
-// -ENODATA the engine has finished the disable phase and the framework
-// can stop calling process()
-// -EINVAL invalid interface handle or
-// invalid input/output buffer description
-////////////////////////////////////////////////////////////////////////////////
-typedef int32_t (*effect_process_t)(effect_interface_t self,
- audio_buffer_t *inBuffer,
- audio_buffer_t *outBuffer);
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// Function: command
-//
-// Description: Send a command and receive a response to/from effect engine.
-//
-// Input:
-// effect_interface_t: handle to the effect interface this function
-// is called on.
-// cmdCode: command code: the command can be a standardized command defined in
-// effect_command_e (see below) or a proprietary command.
-// cmdSize: size of command in bytes
-// pCmdData: pointer to command data
-// pReplyData: pointer to reply data
-//
-// Input/Output:
-// replySize: maximum size of reply data as input
-// actual size of reply data as output
-//
-// Output:
-// returned value: 0 successful operation
-// -EINVAL invalid interface handle or
-// invalid command/reply size or format according to command code
-// The return code should be restricted to indicate problems related to the this
-// API specification. Status related to the execution of a particular command should be
-// indicated as part of the reply field.
-//
-// *pReplyData updated with command response
-//
-////////////////////////////////////////////////////////////////////////////////
-typedef int32_t (*effect_command_t)(effect_interface_t self,
- uint32_t cmdCode,
- uint32_t cmdSize,
- void *pCmdData,
- uint32_t *replySize,
- void *pReplyData);
-
-
-// Effect control interface definition
-struct effect_interface_s {
- effect_process_t process;
- effect_command_t command;
-};
-
-
-//
-//--- Standardized command codes for command() function
-//
-enum effect_command_e {
- EFFECT_CMD_INIT, // initialize effect engine
- EFFECT_CMD_CONFIGURE, // configure effect engine (see effect_config_t)
- EFFECT_CMD_RESET, // reset effect engine
- EFFECT_CMD_ENABLE, // enable effect process
- EFFECT_CMD_DISABLE, // disable effect process
- EFFECT_CMD_SET_PARAM, // set parameter immediately (see effect_param_t)
- EFFECT_CMD_SET_PARAM_DEFERRED, // set parameter deferred
- EFFECT_CMD_SET_PARAM_COMMIT, // commit previous set parameter deferred
- EFFECT_CMD_GET_PARAM, // get parameter
- EFFECT_CMD_SET_DEVICE, // set audio device (see audio_device_e)
- EFFECT_CMD_SET_VOLUME, // set volume
- EFFECT_CMD_SET_AUDIO_MODE, // set the audio mode (normal, ring, ...)
- EFFECT_CMD_FIRST_PROPRIETARY = 0x10000 // first proprietary command code
-};
-
-//==================================================================================================
-// command: EFFECT_CMD_INIT
-//--------------------------------------------------------------------------------------------------
-// description:
-// Initialize effect engine: All configurations return to default
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: 0
-// data: N/A
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: sizeof(int)
-// data: status
-//==================================================================================================
-// command: EFFECT_CMD_CONFIGURE
-//--------------------------------------------------------------------------------------------------
-// description:
-// Apply new audio parameters configurations for input and output buffers
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: sizeof(effect_config_t)
-// data: effect_config_t
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: sizeof(int)
-// data: status
-//==================================================================================================
-// command: EFFECT_CMD_RESET
-//--------------------------------------------------------------------------------------------------
-// description:
-// Reset the effect engine. Keep configuration but resets state and buffer content
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: 0
-// data: N/A
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: 0
-// data: N/A
-//==================================================================================================
-// command: EFFECT_CMD_ENABLE
-//--------------------------------------------------------------------------------------------------
-// description:
-// Enable the process. Called by the framework before the first call to process()
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: 0
-// data: N/A
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: sizeof(int)
-// data: status
-//==================================================================================================
-// command: EFFECT_CMD_DISABLE
-//--------------------------------------------------------------------------------------------------
-// description:
-// Disable the process. Called by the framework after the last call to process()
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: 0
-// data: N/A
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: sizeof(int)
-// data: status
-//==================================================================================================
-// command: EFFECT_CMD_SET_PARAM
-//--------------------------------------------------------------------------------------------------
-// description:
-// Set a parameter and apply it immediately
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: sizeof(effect_param_t) + size of param and value
-// data: effect_param_t + param + value. See effect_param_t definition below for value offset
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: sizeof(int)
-// data: status
-//==================================================================================================
-// command: EFFECT_CMD_SET_PARAM_DEFERRED
-//--------------------------------------------------------------------------------------------------
-// description:
-// Set a parameter but apply it only when receiving EFFECT_CMD_SET_PARAM_COMMIT command
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: sizeof(effect_param_t) + size of param and value
-// data: effect_param_t + param + value. See effect_param_t definition below for value offset
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: 0
-// data: N/A
-//==================================================================================================
-// command: EFFECT_CMD_SET_PARAM_COMMIT
-//--------------------------------------------------------------------------------------------------
-// description:
-// Apply all previously received EFFECT_CMD_SET_PARAM_DEFERRED commands
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: 0
-// data: N/A
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: sizeof(int)
-// data: status
-//==================================================================================================
-// command: EFFECT_CMD_GET_PARAM
-//--------------------------------------------------------------------------------------------------
-// description:
-// Get a parameter value
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: sizeof(effect_param_t) + size of param
-// data: effect_param_t + param
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: sizeof(effect_param_t) + size of param and value
-// data: effect_param_t + param + value. See effect_param_t definition below for value offset
-//==================================================================================================
-// command: EFFECT_CMD_SET_DEVICE
-//--------------------------------------------------------------------------------------------------
-// description:
-// Set the rendering device the audio output path is connected to. See audio_device_e for device
-// values.
-// The effect implementation must set EFFECT_FLAG_DEVICE_IND flag in its descriptor to receive this
-// command when the device changes
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: sizeof(uint32_t)
-// data: audio_device_e
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: 0
-// data: N/A
-//==================================================================================================
-// command: EFFECT_CMD_SET_VOLUME
-//--------------------------------------------------------------------------------------------------
-// description:
-// Set and get volume. Used by audio framework to delegate volume control to effect engine.
-// The effect implementation must set EFFECT_FLAG_VOLUME_IND or EFFECT_FLAG_VOLUME_CTRL flag in
-// its descriptor to receive this command before every call to process() function
-// If EFFECT_FLAG_VOLUME_CTRL flag is set in the effect descriptor, the effect engine must return
-// the volume that should be applied before the effect is processed. The overall volume (the volume
-// actually applied by the effect engine multiplied by the returned value) should match the value
-// indicated in the command.
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: n * sizeof(uint32_t)
-// data: volume for each channel defined in effect_config_t for output buffer expressed in
-// 8.24 fixed point format
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: n * sizeof(uint32_t) / 0
-// data: - if EFFECT_FLAG_VOLUME_CTRL is set in effect descriptor:
-// volume for each channel defined in effect_config_t for output buffer expressed in
-// 8.24 fixed point format
-// - if EFFECT_FLAG_VOLUME_CTRL is not set in effect descriptor:
-// N/A
-// It is legal to receive a null pointer as pReplyData in which case the effect framework has
-// delegated volume control to another effect
-//==================================================================================================
-// command: EFFECT_CMD_SET_AUDIO_MODE
-//--------------------------------------------------------------------------------------------------
-// description:
-// Set the audio mode. The effect implementation must set EFFECT_FLAG_AUDIO_MODE_IND flag in its
-// descriptor to receive this command when the audio mode changes.
-//--------------------------------------------------------------------------------------------------
-// command format:
-// size: sizeof(uint32_t)
-// data: audio_mode_e
-//--------------------------------------------------------------------------------------------------
-// reply format:
-// size: 0
-// data: N/A
-//==================================================================================================
-// command: EFFECT_CMD_FIRST_PROPRIETARY
-//--------------------------------------------------------------------------------------------------
-// description:
-// All proprietary effect commands must use command codes above this value. The size and format of
-// command and response fields is free in this case
-//==================================================================================================
-
-
-// Audio buffer descriptor used by process(), bufferProvider() functions and buffer_config_t
-// structure. Multi-channel audio is always interleaved. The channel order is from LSB to MSB with
-// regard to the channel mask definition in audio_channels_e e.g :
-// Stereo: left, right
-// 5 point 1: front left, front right, front center, low frequency, back left, back right
-// The buffer size is expressed in frame count, a frame being composed of samples for all
-// channels at a given time. Frame size for unspecified format (AUDIO_FORMAT_OTHER) is 8 bit by
-// definition
-struct audio_buffer_s {
- size_t frameCount; // number of frames in buffer
- union {
- void* raw; // raw pointer to start of buffer
- int32_t* s32; // pointer to signed 32 bit data at start of buffer
- int16_t* s16; // pointer to signed 16 bit data at start of buffer
- uint8_t* u8; // pointer to unsigned 8 bit data at start of buffer
- };
-};
-
-// The buffer_provider_s structure contains functions that can be used
-// by the effect engine process() function to query and release input
-// or output audio buffer.
-// The getBuffer() function is called to retrieve a buffer where data
-// should read from or written to by process() function.
-// The releaseBuffer() function MUST be called when the buffer retrieved
-// with getBuffer() is not needed anymore.
-// The process function should use the buffer provider mechanism to retrieve
-// input or output buffer if the inBuffer or outBuffer passed as argument is NULL
-// and the buffer configuration (buffer_config_t) given by the EFFECT_CMD_CONFIGURE
-// command did not specify an audio buffer.
-
-typedef int32_t (* buffer_function_t)(void *cookie, audio_buffer_t *buffer);
-
-typedef struct buffer_provider_s {
- buffer_function_t getBuffer; // retrieve next buffer
- buffer_function_t releaseBuffer; // release used buffer
- void *cookie; // for use by client of buffer provider functions
-} buffer_provider_t;
-
-
-// The buffer_config_s structure specifies the input or output audio format
-// to be used by the effect engine. It is part of the effect_config_t
-// structure that defines both input and output buffer configurations and is
-// passed by the EFFECT_CMD_CONFIGURE command.
-typedef struct buffer_config_s {
- audio_buffer_t buffer; // buffer for use by process() function if not passed explicitly
- uint32_t samplingRate; // sampling rate
- uint32_t channels; // channel mask (see audio_channels_e)
- buffer_provider_t bufferProvider; // buffer provider
- uint8_t format; // Audio format (see audio_format_e)
- uint8_t accessMode; // read/write or accumulate in buffer (effect_buffer_access_e)
- uint16_t mask; // indicates which of the above fields is valid
-} buffer_config_t;
-
-// Sample format
-enum audio_format_e {
- SAMPLE_FORMAT_PCM_S15, // PCM signed 16 bits
- SAMPLE_FORMAT_PCM_U8, // PCM unsigned 8 bits
- SAMPLE_FORMAT_PCM_S7_24, // PCM signed 7.24 fixed point representation
- SAMPLE_FORMAT_OTHER // other format (e.g. compressed)
-};
-
-// Channel mask
-enum audio_channels_e {
- CHANNEL_FRONT_LEFT = 0x1, // front left channel
- CHANNEL_FRONT_RIGHT = 0x2, // front right channel
- CHANNEL_FRONT_CENTER = 0x4, // front center channel
- CHANNEL_LOW_FREQUENCY = 0x8, // low frequency channel
- CHANNEL_BACK_LEFT = 0x10, // back left channel
- CHANNEL_BACK_RIGHT = 0x20, // back right channel
- CHANNEL_FRONT_LEFT_OF_CENTER = 0x40, // front left of center channel
- CHANNEL_FRONT_RIGHT_OF_CENTER = 0x80, // front right of center channel
- CHANNEL_BACK_CENTER = 0x100, // back center channel
- CHANNEL_MONO = CHANNEL_FRONT_LEFT,
- CHANNEL_STEREO = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT),
- CHANNEL_QUAD = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT |
- CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT),
- CHANNEL_SURROUND = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT |
- CHANNEL_FRONT_CENTER | CHANNEL_BACK_CENTER),
- CHANNEL_5POINT1 = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT |
- CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT),
- CHANNEL_7POINT1 = (CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT |
- CHANNEL_FRONT_CENTER | CHANNEL_LOW_FREQUENCY | CHANNEL_BACK_LEFT | CHANNEL_BACK_RIGHT |
- CHANNEL_FRONT_LEFT_OF_CENTER | CHANNEL_FRONT_RIGHT_OF_CENTER),
-};
-
-// Render device
-enum audio_device_e {
- DEVICE_EARPIECE = 0x1, // earpiece
- DEVICE_SPEAKER = 0x2, // speaker
- DEVICE_WIRED_HEADSET = 0x4, // wired headset, with microphone
- DEVICE_WIRED_HEADPHONE = 0x8, // wired headphone, without microphone
- DEVICE_BLUETOOTH_SCO = 0x10, // generic bluetooth SCO
- DEVICE_BLUETOOTH_SCO_HEADSET = 0x20, // bluetooth SCO headset
- DEVICE_BLUETOOTH_SCO_CARKIT = 0x40, // bluetooth SCO car kit
- DEVICE_BLUETOOTH_A2DP = 0x80, // generic bluetooth A2DP
- DEVICE_BLUETOOTH_A2DP_HEADPHONES = 0x100, // bluetooth A2DP headphones
- DEVICE_BLUETOOTH_A2DP_SPEAKER = 0x200, // bluetooth A2DP speakers
- DEVICE_AUX_DIGITAL = 0x400, // digital output
- DEVICE_EXTERNAL_SPEAKER = 0x800 // external speaker (stereo and High quality)
-};
-
-#if ANDROID_VERSION < 17
-// Audio mode
-enum audio_mode_e {
- AUDIO_MODE_NORMAL, // device idle
- AUDIO_MODE_RINGTONE, // device ringing
- AUDIO_MODE_IN_CALL // audio call connected (VoIP or telephony)
-};
-#endif
-
-// Values for "accessMode" field of buffer_config_t:
-// overwrite, read only, accumulate (read/modify/write)
-enum effect_buffer_access_e {
- EFFECT_BUFFER_ACCESS_WRITE,
- EFFECT_BUFFER_ACCESS_READ,
- EFFECT_BUFFER_ACCESS_ACCUMULATE
-
-};
-
-// Values for bit field "mask" in buffer_config_t. If a bit is set, the corresponding field
-// in buffer_config_t must be taken into account when executing the EFFECT_CMD_CONFIGURE command
-#define EFFECT_CONFIG_BUFFER 0x0001 // buffer field must be taken into account
-#define EFFECT_CONFIG_SMP_RATE 0x0002 // samplingRate field must be taken into account
-#define EFFECT_CONFIG_CHANNELS 0x0004 // channels field must be taken into account
-#define EFFECT_CONFIG_FORMAT 0x0008 // format field must be taken into account
-#define EFFECT_CONFIG_ACC_MODE 0x0010 // accessMode field must be taken into account
-#define EFFECT_CONFIG_PROVIDER 0x0020 // bufferProvider field must be taken into account
-#define EFFECT_CONFIG_ALL (EFFECT_CONFIG_BUFFER | EFFECT_CONFIG_SMP_RATE | \
- EFFECT_CONFIG_CHANNELS | EFFECT_CONFIG_FORMAT | \
- EFFECT_CONFIG_ACC_MODE | EFFECT_CONFIG_PROVIDER)
-
-
-// effect_config_s structure describes the format of the pCmdData argument of EFFECT_CMD_CONFIGURE
-// command to configure audio parameters and buffers for effect engine input and output.
-typedef struct effect_config_s {
- buffer_config_t inputCfg;
- buffer_config_t outputCfg;;
-} effect_config_t;
-
-
-// effect_param_s structure describes the format of the pCmdData argument of EFFECT_CMD_SET_PARAM
-// command and pCmdData and pReplyData of EFFECT_CMD_GET_PARAM command.
-// psize and vsize represent the actual size of parameter and value.
-//
-// NOTE: the start of value field inside the data field is always on a 32 bit boundary:
-//
-// +-----------+
-// | status | sizeof(int)
-// +-----------+
-// | psize | sizeof(int)
-// +-----------+
-// | vsize | sizeof(int)
-// +-----------+
-// | | | |
-// ~ parameter ~ > psize |
-// | | | > ((psize - 1)/sizeof(int) + 1) * sizeof(int)
-// +-----------+ |
-// | padding | |
-// +-----------+
-// | | |
-// ~ value ~ > vsize
-// | | |
-// +-----------+
-
-typedef struct effect_param_s {
- int32_t status; // Transaction status (unused for command, used for reply)
- uint32_t psize; // Parameter size
- uint32_t vsize; // Value size
- char data[]; // Start of Parameter + Value data
-} effect_param_t;
-
-
-/////////////////////////////////////////////////
-// Effect library interface
-/////////////////////////////////////////////////
-
-// An effect library is required to implement and expose the following functions
-// to enable effect enumeration and instantiation. The name of these functions must be as
-// specified here as the effect framework will get the function address with dlsym():
-//
-// - effect_QueryNumberEffects_t EffectQueryNumberEffects;
-// - effect_QueryEffect_t EffectQueryEffect;
-// - effect_CreateEffect_t EffectCreate;
-// - effect_ReleaseEffect_t EffectRelease;
-
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// Function: EffectQueryNumberEffects
-//
-// Description: Returns the number of different effects exposed by the
-// library. Each effect must have a unique effect uuid (see
-// effect_descriptor_t). This function together with EffectQueryEffect()
-// is used to enumerate all effects present in the library.
-//
-// Input/Output:
-// pNumEffects: address where the number of effects should be returned.
-//
-// Output:
-// returned value: 0 successful operation.
-// -ENODEV library failed to initialize
-// -EINVAL invalid pNumEffects
-// *pNumEffects: updated with number of effects in library
-//
-////////////////////////////////////////////////////////////////////////////////
-typedef int32_t (*effect_QueryNumberEffects_t)(uint32_t *pNumEffects);
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// Function: EffectQueryEffect
-//
-// Description: Returns the descriptor of the effect engine which index is
-// given as first argument.
-// See effect_descriptor_t for details on effect descriptors.
-// This function together with EffectQueryNumberEffects() is used to enumerate all
-// effects present in the library. The enumeration sequence is:
-// EffectQueryNumberEffects(&num_effects);
-// for (i = 0; i < num_effects; i++)
-// EffectQueryEffect(i,...);
-//
-// Input/Output:
-// index: index of the effect
-// pDescriptor: address where to return the effect descriptor.
-//
-// Output:
-// returned value: 0 successful operation.
-// -ENODEV library failed to initialize
-// -EINVAL invalid pDescriptor or index
-// -ENOSYS effect list has changed since last execution of
-// EffectQueryNumberEffects()
-// -ENOENT no more effect available
-// *pDescriptor: updated with the effect descriptor.
-//
-////////////////////////////////////////////////////////////////////////////////
-typedef int32_t (*effect_QueryEffect_t)(uint32_t index,
- effect_descriptor_t *pDescriptor);
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// Function: EffectCreate
-//
-// Description: Creates an effect engine of the specified type and returns an
-// effect control interface on this engine. The function will allocate the
-// resources for an instance of the requested effect engine and return
-// a handle on the effect control interface.
-//
-// Input:
-// uuid: pointer to the effect uuid.
-// sessionId: audio session to which this effect instance will be attached. All effects
-// created with the same session ID are connected in series and process the same signal
-// stream. Knowing that two effects are part of the same effect chain can help the
-// library implement some kind of optimizations.
-// ioId: identifies the output or input stream this effect is directed to at audio HAL.
-// For future use especially with tunneled HW accelerated effects
-//
-// Input/Output:
-// pInterface: address where to return the effect interface.
-//
-// Output:
-// returned value: 0 successful operation.
-// -ENODEV library failed to initialize
-// -EINVAL invalid pEffectUuid or pInterface
-// -ENOENT no effect with this uuid found
-// *pInterface: updated with the effect interface handle.
-//
-////////////////////////////////////////////////////////////////////////////////
-typedef int32_t (*effect_CreateEffect_t)(effect_uuid_t *uuid,
- int32_t sessionId,
- int32_t ioId,
- effect_interface_t *pInterface);
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// Function: EffectRelease
-//
-// Description: Releases the effect engine whose handle is given as argument.
-// All resources allocated to this particular instance of the effect are
-// released.
-//
-// Input:
-// interface: handle on the effect interface to be released.
-//
-// Output:
-// returned value: 0 successful operation.
-// -ENODEV library failed to initialize
-// -EINVAL invalid interface handle
-//
-////////////////////////////////////////////////////////////////////////////////
-typedef int32_t (*effect_ReleaseEffect_t)(effect_interface_t interface);
-
-
-#if __cplusplus
-} // extern "C"
-#endif
-
-
-#endif /*ANDROID_EFFECTAPI_H_*/
diff --git a/dom/system/gonk/android_audio/IAudioFlinger.h b/dom/system/gonk/android_audio/IAudioFlinger.h
deleted file mode 100644
index b10d3ab93..000000000
--- a/dom/system/gonk/android_audio/IAudioFlinger.h
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_IAUDIOFLINGER_H
-#define ANDROID_IAUDIOFLINGER_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <utils/RefBase.h>
-#include <utils/Errors.h>
-#include <binder/IInterface.h>
-#include "IAudioTrack.h"
-#include "IAudioRecord.h"
-#include "IAudioFlingerClient.h"
-#include "EffectApi.h"
-#include "IEffect.h"
-#include "IEffectClient.h"
-#include <utils/String8.h>
-
-namespace android {
-
-// ----------------------------------------------------------------------------
-
-class IAudioFlinger : public IInterface
-{
-public:
- DECLARE_META_INTERFACE(AudioFlinger);
-
- /* create an audio track and registers it with AudioFlinger.
- * return null if the track cannot be created.
- */
- virtual sp<IAudioTrack> createTrack(
- pid_t pid,
- int streamType,
- uint32_t sampleRate,
- int format,
- int channelCount,
- int frameCount,
- uint32_t flags,
- const sp<IMemory>& sharedBuffer,
- int output,
- int *sessionId,
- status_t *status) = 0;
-
- virtual sp<IAudioRecord> openRecord(
- pid_t pid,
- int input,
- uint32_t sampleRate,
- int format,
- int channelCount,
- int frameCount,
- uint32_t flags,
- int *sessionId,
- status_t *status) = 0;
-
- /* query the audio hardware state. This state never changes,
- * and therefore can be cached.
- */
- virtual uint32_t sampleRate(int output) const = 0;
- virtual int channelCount(int output) const = 0;
- virtual int format(int output) const = 0;
- virtual size_t frameCount(int output) const = 0;
- virtual uint32_t latency(int output) const = 0;
-
- /* set/get the audio hardware state. This will probably be used by
- * the preference panel, mostly.
- */
- virtual status_t setMasterVolume(float value) = 0;
- virtual status_t setMasterMute(bool muted) = 0;
-
- virtual float masterVolume() const = 0;
- virtual bool masterMute() const = 0;
-
- /* set/get stream type state. This will probably be used by
- * the preference panel, mostly.
- */
- virtual status_t setStreamVolume(int stream, float value, int output) = 0;
- virtual status_t setStreamMute(int stream, bool muted) = 0;
-
- virtual float streamVolume(int stream, int output) const = 0;
- virtual bool streamMute(int stream) const = 0;
-
- // set audio mode
- virtual status_t setMode(int mode) = 0;
-
- // mic mute/state
- virtual status_t setMicMute(bool state) = 0;
- virtual bool getMicMute() const = 0;
-
- // is any track active on this stream?
- virtual bool isStreamActive(int stream) const = 0;
-
- virtual status_t setParameters(int ioHandle, const String8& keyValuePairs) = 0;
- virtual String8 getParameters(int ioHandle, const String8& keys) = 0;
-
- // register a current process for audio output change notifications
- virtual void registerClient(const sp<IAudioFlingerClient>& client) = 0;
-
- // retrieve the audio recording buffer size
- virtual size_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount) = 0;
-
- virtual int openOutput(uint32_t *pDevices,
- uint32_t *pSamplingRate,
- uint32_t *pFormat,
- uint32_t *pChannels,
- uint32_t *pLatencyMs,
- uint32_t flags) = 0;
- virtual int openDuplicateOutput(int output1, int output2) = 0;
- virtual status_t closeOutput(int output) = 0;
- virtual status_t suspendOutput(int output) = 0;
- virtual status_t restoreOutput(int output) = 0;
-
- virtual int openInput(uint32_t *pDevices,
- uint32_t *pSamplingRate,
- uint32_t *pFormat,
- uint32_t *pChannels,
- uint32_t acoustics) = 0;
- virtual status_t closeInput(int input) = 0;
-
- virtual status_t setStreamOutput(uint32_t stream, int output) = 0;
-
- virtual status_t setVoiceVolume(float volume) = 0;
-
- virtual status_t getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames, int output) = 0;
-
- virtual unsigned int getInputFramesLost(int ioHandle) = 0;
-
- virtual int newAudioSessionId() = 0;
-
- virtual status_t loadEffectLibrary(const char *libPath, int *handle) = 0;
-
- virtual status_t unloadEffectLibrary(int handle) = 0;
-
- virtual status_t queryNumberEffects(uint32_t *numEffects) = 0;
-
- virtual status_t queryEffect(uint32_t index, effect_descriptor_t *pDescriptor) = 0;
-
- virtual status_t getEffectDescriptor(effect_uuid_t *pEffectUUID, effect_descriptor_t *pDescriptor) = 0;
-
- virtual sp<IEffect> createEffect(pid_t pid,
- effect_descriptor_t *pDesc,
- const sp<IEffectClient>& client,
- int32_t priority,
- int output,
- int sessionId,
- status_t *status,
- int *id,
- int *enabled) = 0;
-
- virtual status_t moveEffects(int session, int srcOutput, int dstOutput) = 0;
-};
-
-
-// ----------------------------------------------------------------------------
-
-class BnAudioFlinger : public BnInterface<IAudioFlinger>
-{
-public:
- virtual status_t onTransact( uint32_t code,
- const Parcel& data,
- Parcel* reply,
- uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------------
-
-}; // namespace android
-
-#endif // ANDROID_IAUDIOFLINGER_H
diff --git a/dom/system/gonk/android_audio/IAudioFlingerClient.h b/dom/system/gonk/android_audio/IAudioFlingerClient.h
deleted file mode 100644
index aa0cdcff1..000000000
--- a/dom/system/gonk/android_audio/IAudioFlingerClient.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_IAUDIOFLINGERCLIENT_H
-#define ANDROID_IAUDIOFLINGERCLIENT_H
-
-
-#include <utils/RefBase.h>
-#include <binder/IInterface.h>
-#include <utils/KeyedVector.h>
-
-namespace android {
-
-// ----------------------------------------------------------------------------
-
-class IAudioFlingerClient : public IInterface
-{
-public:
- DECLARE_META_INTERFACE(AudioFlingerClient);
-
- // Notifies a change of audio input/output configuration.
- virtual void ioConfigChanged(int event, int ioHandle, void *param2) = 0;
-
-};
-
-
-// ----------------------------------------------------------------------------
-
-class BnAudioFlingerClient : public BnInterface<IAudioFlingerClient>
-{
-public:
- virtual status_t onTransact( uint32_t code,
- const Parcel& data,
- Parcel* reply,
- uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------------
-
-}; // namespace android
-
-#endif // ANDROID_IAUDIOFLINGERCLIENT_H
diff --git a/dom/system/gonk/android_audio/IAudioRecord.h b/dom/system/gonk/android_audio/IAudioRecord.h
deleted file mode 100644
index 46735def2..000000000
--- a/dom/system/gonk/android_audio/IAudioRecord.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef IAUDIORECORD_H_
-#define IAUDIORECORD_H_
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/RefBase.h>
-#include <utils/Errors.h>
-#include <binder/IInterface.h>
-#include <binder/IMemory.h>
-
-
-namespace android {
-
-// ----------------------------------------------------------------------------
-
-class IAudioRecord : public IInterface
-{
-public:
- DECLARE_META_INTERFACE(AudioRecord);
-
- /* After it's created the track is not active. Call start() to
- * make it active. If set, the callback will start being called.
- */
- virtual status_t start() = 0;
-
- /* Stop a track. If set, the callback will cease being called and
- * obtainBuffer will return an error. Buffers that are already released
- * will be processed, unless flush() is called.
- */
- virtual void stop() = 0;
-
- /* get this tracks control block */
- virtual sp<IMemory> getCblk() const = 0;
-};
-
-// ----------------------------------------------------------------------------
-
-class BnAudioRecord : public BnInterface<IAudioRecord>
-{
-public:
- virtual status_t onTransact( uint32_t code,
- const Parcel& data,
- Parcel* reply,
- uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------------
-
-}; // namespace android
-
-#endif /*IAUDIORECORD_H_*/
diff --git a/dom/system/gonk/android_audio/IAudioTrack.h b/dom/system/gonk/android_audio/IAudioTrack.h
deleted file mode 100644
index 47d530be5..000000000
--- a/dom/system/gonk/android_audio/IAudioTrack.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_IAUDIOTRACK_H
-#define ANDROID_IAUDIOTRACK_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/RefBase.h>
-#include <utils/Errors.h>
-#include <binder/IInterface.h>
-#include <binder/IMemory.h>
-
-
-namespace android {
-
-// ----------------------------------------------------------------------------
-
-class IAudioTrack : public IInterface
-{
-public:
- DECLARE_META_INTERFACE(AudioTrack);
-
- /* After it's created the track is not active. Call start() to
- * make it active. If set, the callback will start being called.
- */
- virtual status_t start() = 0;
-
- /* Stop a track. If set, the callback will cease being called and
- * obtainBuffer will return an error. Buffers that are already released
- * will be processed, unless flush() is called.
- */
- virtual void stop() = 0;
-
- /* flush a stopped track. All pending buffers are discarded.
- * This function has no effect if the track is not stoped.
- */
- virtual void flush() = 0;
-
- /* mute or unmutes this track.
- * While mutted, the callback, if set, is still called.
- */
- virtual void mute(bool) = 0;
-
- /* Pause a track. If set, the callback will cease being called and
- * obtainBuffer will return an error. Buffers that are already released
- * will be processed, unless flush() is called.
- */
- virtual void pause() = 0;
-
- /* Attach track auxiliary output to specified effect. Use effectId = 0
- * to detach track from effect.
- */
- virtual status_t attachAuxEffect(int effectId) = 0;
-
- /* get this tracks control block */
- virtual sp<IMemory> getCblk() const = 0;
-};
-
-// ----------------------------------------------------------------------------
-
-class BnAudioTrack : public BnInterface<IAudioTrack>
-{
-public:
- virtual status_t onTransact( uint32_t code,
- const Parcel& data,
- Parcel* reply,
- uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------------
-
-}; // namespace android
-
-#endif // ANDROID_IAUDIOTRACK_H
diff --git a/dom/system/gonk/android_audio/IEffect.h b/dom/system/gonk/android_audio/IEffect.h
deleted file mode 100644
index ff04869e0..000000000
--- a/dom/system/gonk/android_audio/IEffect.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_IEFFECT_H
-#define ANDROID_IEFFECT_H
-
-#include <utils/RefBase.h>
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-#include <binder/IMemory.h>
-
-namespace android {
-
-class IEffect: public IInterface
-{
-public:
- DECLARE_META_INTERFACE(Effect);
-
- virtual status_t enable() = 0;
-
- virtual status_t disable() = 0;
-
- virtual status_t command(uint32_t cmdCode,
- uint32_t cmdSize,
- void *pCmdData,
- uint32_t *pReplySize,
- void *pReplyData) = 0;
-
- virtual void disconnect() = 0;
-
- virtual sp<IMemory> getCblk() const = 0;
-};
-
-// ----------------------------------------------------------------------------
-
-class BnEffect: public BnInterface<IEffect>
-{
-public:
- virtual status_t onTransact( uint32_t code,
- const Parcel& data,
- Parcel* reply,
- uint32_t flags = 0);
-};
-
-}; // namespace android
-
-#endif // ANDROID_IEFFECT_H
diff --git a/dom/system/gonk/android_audio/IEffectClient.h b/dom/system/gonk/android_audio/IEffectClient.h
deleted file mode 100644
index 2f78c98f1..000000000
--- a/dom/system/gonk/android_audio/IEffectClient.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_IEFFECTCLIENT_H
-#define ANDROID_IEFFECTCLIENT_H
-
-#include <utils/RefBase.h>
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-#include <binder/IMemory.h>
-
-namespace android {
-
-class IEffectClient: public IInterface
-{
-public:
- DECLARE_META_INTERFACE(EffectClient);
-
- virtual void controlStatusChanged(bool controlGranted) = 0;
- virtual void enableStatusChanged(bool enabled) = 0;
- virtual void commandExecuted(uint32_t cmdCode,
- uint32_t cmdSize,
- void *pCmdData,
- uint32_t replySize,
- void *pReplyData) = 0;
-};
-
-// ----------------------------------------------------------------------------
-
-class BnEffectClient: public BnInterface<IEffectClient>
-{
-public:
- virtual status_t onTransact( uint32_t code,
- const Parcel& data,
- Parcel* reply,
- uint32_t flags = 0);
-};
-
-}; // namespace android
-
-#endif // ANDROID_IEFFECTCLIENT_H
diff --git a/dom/system/gonk/moz.build b/dom/system/gonk/moz.build
deleted file mode 100644
index 229baaab4..000000000
--- a/dom/system/gonk/moz.build
+++ /dev/null
@@ -1,107 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# Copyright 2013 Mozilla Foundation and Mozilla contributors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-XPIDL_SOURCES += [
- 'nsIAudioManager.idl',
- 'nsINetworkInterface.idl',
- 'nsINetworkInterfaceListService.idl',
- 'nsINetworkManager.idl',
- 'nsINetworkService.idl',
- 'nsINetworkWorker.idl',
- 'nsISystemWorkerManager.idl',
- 'nsITetheringService.idl',
- 'nsIVolume.idl',
- 'nsIVolumeMountLock.idl',
- 'nsIVolumeService.idl',
- 'nsIVolumeStat.idl',
- 'nsIWorkerHolder.idl',
-]
-
-XPIDL_MODULE = 'dom_system_gonk'
-
-EXPORTS += [
- 'GeolocationUtil.h',
- 'GonkGPSGeolocationProvider.h',
- 'nsVolume.h',
- 'nsVolumeService.h',
- 'SystemProperty.h',
-]
-UNIFIED_SOURCES += [
- 'AudioChannelManager.cpp',
- 'AudioManager.cpp',
- 'AutoMounter.cpp',
- 'AutoMounterSetting.cpp',
- 'GeolocationUtil.cpp',
- 'GonkGPSGeolocationProvider.cpp',
- 'MozMtpDatabase.cpp',
- 'MozMtpServer.cpp',
- 'MozMtpStorage.cpp',
- 'NetIdManager.cpp',
- 'NetworkUtils.cpp',
- 'NetworkWorker.cpp',
- 'nsVolume.cpp',
- 'nsVolumeMountLock.cpp',
- 'nsVolumeService.cpp',
- 'nsVolumeStat.cpp',
- 'OpenFileFinder.cpp',
- 'SystemProperty.cpp',
- 'SystemWorkerManager.cpp',
- 'TimeZoneSettingObserver.cpp',
- 'Volume.cpp',
- 'VolumeCommand.cpp',
- 'VolumeManager.cpp',
- 'VolumeServiceIOThread.cpp',
- 'VolumeServiceTest.cpp',
-]
-
-if CONFIG['ANDROID_VERSION'] >= '17':
- LOCAL_INCLUDES += ['%' + '%s/frameworks/av/media/mtp' % CONFIG['ANDROID_SOURCE']]
-else:
- LOCAL_INCLUDES += ['%' + '%s/frameworks/base/media/mtp' % CONFIG['ANDROID_SOURCE']]
-
-if CONFIG['ENABLE_TESTS']:
- XPCSHELL_TESTS_MANIFESTS += ['tests/xpcshell.ini']
-
-EXTRA_COMPONENTS += [
- 'NetworkInterfaceListService.js',
- 'NetworkInterfaceListService.manifest',
- 'NetworkManager.js',
- 'NetworkManager.manifest',
- 'NetworkService.js',
- 'NetworkService.manifest',
- 'TetheringService.js',
- 'TetheringService.manifest',
-]
-EXTRA_JS_MODULES += [
- 'systemlibs.js',
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-DEFINES['HAVE_ANDROID_OS'] = True
-
-LOCAL_INCLUDES += [
- '/dom/base',
- '/dom/bluetooth/common',
- '/dom/geolocation',
- '/dom/wifi',
-]
-
-FINAL_LIBRARY = 'xul'
-
-FINAL_TARGET_FILES.modules.workers += [
- 'worker_buf.js',
-]
diff --git a/dom/system/gonk/mozstumbler/MozStumbler.cpp b/dom/system/gonk/mozstumbler/MozStumbler.cpp
deleted file mode 100644
index 61e09e705..000000000
--- a/dom/system/gonk/mozstumbler/MozStumbler.cpp
+++ /dev/null
@@ -1,426 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "MozStumbler.h"
-#include "nsDataHashtable.h"
-#include "nsGeoPosition.h"
-#include "nsNetCID.h"
-#include "nsPrintfCString.h"
-#include "StumblerLogging.h"
-#include "WriteStumbleOnThread.h"
-#include "../GeolocationUtil.h"
-
-#include "nsIInterfaceRequestor.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsIMobileConnectionInfo.h"
-#include "nsIMobileConnectionService.h"
-#include "nsIMobileCellInfo.h"
-#include "nsIMobileNetworkInfo.h"
-#include "nsINetworkInterface.h"
-#include "nsIRadioInterfaceLayer.h"
-
-using namespace mozilla;
-using namespace mozilla::dom;
-
-
-NS_IMPL_ISUPPORTS(StumblerInfo, nsICellInfoListCallback, nsIWifiScanResultsReady)
-
-class RequestCellInfoEvent : public Runnable {
-public:
- RequestCellInfoEvent(StumblerInfo *callback)
- : mRequestCallback(callback)
- {}
-
- NS_IMETHOD Run() override {
- MOZ_ASSERT(NS_IsMainThread());
- // Get Cell Info
- nsCOMPtr<nsIMobileConnectionService> service =
- do_GetService(NS_MOBILE_CONNECTION_SERVICE_CONTRACTID);
-
- if (!service) {
- STUMBLER_ERR("Stumbler-can not get nsIMobileConnectionService \n");
- return NS_OK;
- }
- nsCOMPtr<nsIMobileConnection> connection;
- uint32_t numberOfRilServices = 1, cellInfoNum = 0;
-
- service->GetNumItems(&numberOfRilServices);
- for (uint32_t rilNum = 0; rilNum < numberOfRilServices; rilNum++) {
- service->GetItemByServiceId(rilNum /* Client Id */, getter_AddRefs(connection));
- if (!connection) {
- STUMBLER_ERR("Stumbler-can not get nsIMobileConnection by ServiceId %d \n", rilNum);
- } else {
- cellInfoNum++;
- connection->GetCellInfoList(mRequestCallback);
- }
- }
- mRequestCallback->SetCellInfoResponsesExpected(cellInfoNum);
-
- // Get Wifi AP Info
- nsCOMPtr<nsIInterfaceRequestor> ir = do_GetService("@mozilla.org/telephony/system-worker-manager;1");
- nsCOMPtr<nsIWifi> wifi = do_GetInterface(ir);
- if (!wifi) {
- mRequestCallback->SetWifiInfoResponseReceived();
- STUMBLER_ERR("Stumbler-can not get nsIWifi interface\n");
- return NS_OK;
- }
- wifi->GetWifiScanResults(mRequestCallback);
- return NS_OK;
- }
-private:
- RefPtr<StumblerInfo> mRequestCallback;
-};
-
-void
-MozStumble(nsGeoPosition* position)
-{
- if (WriteStumbleOnThread::IsFileWaitingForUpload()) {
- nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
- MOZ_ASSERT(target);
- // Knowing that file is waiting to upload, and no collection will take place,
- // just trigger the thread with an empty string.
- nsCOMPtr<nsIRunnable> event = new WriteStumbleOnThread(EmptyCString());
- target->Dispatch(event, NS_DISPATCH_NORMAL);
- return;
- }
-
- nsCOMPtr<nsIDOMGeoPositionCoords> coords;
- position->GetCoords(getter_AddRefs(coords));
- if (!coords) {
- return;
- }
-
- double latitude, longitude;
- coords->GetLatitude(&latitude);
- coords->GetLongitude(&longitude);
-
- const double kMinChangeInMeters = 30;
- static int64_t lastTime_ms = 0;
- static double sLastLat = 0;
- static double sLastLon = 0;
- double delta = -1.0;
- int64_t timediff = (PR_Now() / PR_USEC_PER_MSEC) - lastTime_ms;
-
- if (0 != sLastLon || 0 != sLastLat) {
- delta = CalculateDeltaInMeter(latitude, longitude, sLastLat, sLastLon);
- }
- STUMBLER_DBG("Stumbler-Location. [%f , %f] time_diff:%lld, delta : %f\n",
- longitude, latitude, timediff, delta);
-
- // Consecutive GPS locations must be 30 meters and 3 seconds apart
- if (lastTime_ms == 0 || ((timediff >= STUMBLE_INTERVAL_MS) && (delta > kMinChangeInMeters))){
- lastTime_ms = (PR_Now() / PR_USEC_PER_MSEC);
- sLastLat = latitude;
- sLastLon = longitude;
- RefPtr<StumblerInfo> requestCallback = new StumblerInfo(position);
- RefPtr<RequestCellInfoEvent> runnable = new RequestCellInfoEvent(requestCallback);
- NS_DispatchToMainThread(runnable);
- } else {
- STUMBLER_DBG("Stumbler-GPS locations less than 30 meters and 3 seconds. Ignore!\n");
- }
-}
-
-void
-StumblerInfo::SetWifiInfoResponseReceived()
-{
- mIsWifiInfoResponseReceived = true;
-
- if (mIsWifiInfoResponseReceived && mCellInfoResponsesReceived == mCellInfoResponsesExpected) {
- STUMBLER_DBG("Call DumpStumblerInfo from SetWifiInfoResponseReceived\n");
- DumpStumblerInfo();
- }
-}
-
-void
-StumblerInfo::SetCellInfoResponsesExpected(uint8_t count)
-{
- mCellInfoResponsesExpected = count;
- STUMBLER_DBG("SetCellInfoNum (%d)\n", count);
-
- if (mIsWifiInfoResponseReceived && mCellInfoResponsesReceived == mCellInfoResponsesExpected) {
- STUMBLER_DBG("Call DumpStumblerInfo from SetCellInfoResponsesExpected\n");
- DumpStumblerInfo();
- }
-}
-
-
-#define TEXT_LAT NS_LITERAL_CSTRING("latitude")
-#define TEXT_LON NS_LITERAL_CSTRING("longitude")
-#define TEXT_ACC NS_LITERAL_CSTRING("accuracy")
-#define TEXT_ALT NS_LITERAL_CSTRING("altitude")
-#define TEXT_ALTACC NS_LITERAL_CSTRING("altitudeAccuracy")
-#define TEXT_HEAD NS_LITERAL_CSTRING("heading")
-#define TEXT_SPD NS_LITERAL_CSTRING("speed")
-
-nsresult
-StumblerInfo::LocationInfoToString(nsACString& aLocDesc)
-{
- nsCOMPtr<nsIDOMGeoPositionCoords> coords;
- mPosition->GetCoords(getter_AddRefs(coords));
- if (!coords) {
- return NS_ERROR_FAILURE;
- }
-
- nsDataHashtable<nsCStringHashKey, double> info;
-
- double val;
- coords->GetLatitude(&val);
- info.Put(TEXT_LAT, val);
- coords->GetLongitude(&val);
- info.Put(TEXT_LON, val);
- coords->GetAccuracy(&val);
- info.Put(TEXT_ACC, val);
- coords->GetAltitude(&val);
- info.Put(TEXT_ALT, val);
- coords->GetAltitudeAccuracy(&val);
- info.Put(TEXT_ALTACC, val);
- coords->GetHeading(&val);
- info.Put(TEXT_HEAD, val);
- coords->GetSpeed(&val);
- info.Put(TEXT_SPD, val);
-
- for (auto it = info.Iter(); !it.Done(); it.Next()) {
- const nsACString& key = it.Key();
- val = it.UserData();
- if (!IsNaN(val)) {
- aLocDesc += nsPrintfCString("\"%s\":%f,", key.BeginReading(), val);
- }
- }
-
- aLocDesc += nsPrintfCString("\"timestamp\":%lld,", PR_Now() / PR_USEC_PER_MSEC).get();
- return NS_OK;
-}
-
-#define TEXT_RADIOTYPE NS_LITERAL_CSTRING("radioType")
-#define TEXT_MCC NS_LITERAL_CSTRING("mobileCountryCode")
-#define TEXT_MNC NS_LITERAL_CSTRING("mobileNetworkCode")
-#define TEXT_LAC NS_LITERAL_CSTRING("locationAreaCode")
-#define TEXT_CID NS_LITERAL_CSTRING("cellId")
-#define TEXT_PSC NS_LITERAL_CSTRING("psc")
-#define TEXT_STRENGTH_ASU NS_LITERAL_CSTRING("asu")
-#define TEXT_STRENGTH_DBM NS_LITERAL_CSTRING("signalStrength")
-#define TEXT_REGISTERED NS_LITERAL_CSTRING("serving")
-#define TEXT_TIMEING_ADVANCE NS_LITERAL_CSTRING("timingAdvance")
-
-template <class T> void
-ExtractCommonNonCDMACellInfoItems(nsCOMPtr<T>& cell, nsDataHashtable<nsCStringHashKey, int32_t>& info)
-{
- int32_t mcc, mnc, cid, sig;
-
- cell->GetMcc(&mcc);
- cell->GetMnc(&mnc);
- cell->GetCid(&cid);
- cell->GetSignalStrength(&sig);
-
- info.Put(TEXT_MCC, mcc);
- info.Put(TEXT_MNC, mnc);
- info.Put(TEXT_CID, cid);
- info.Put(TEXT_STRENGTH_ASU, sig);
-}
-
-void
-StumblerInfo::CellNetworkInfoToString(nsACString& aCellDesc)
-{
- aCellDesc += "\"cellTowers\": [";
-
- for (uint32_t idx = 0; idx < mCellInfo.Length() ; idx++) {
- const char* radioType = 0;
- int32_t type;
- mCellInfo[idx]->GetType(&type);
- bool registered;
- mCellInfo[idx]->GetRegistered(&registered);
- if (idx) {
- aCellDesc += ",{";
- } else {
- aCellDesc += "{";
- }
-
- STUMBLER_DBG("type=%d\n", type);
-
- nsDataHashtable<nsCStringHashKey, int32_t> info;
- info.Put(TEXT_REGISTERED, registered);
-
- if(type == nsICellInfo::CELL_INFO_TYPE_GSM) {
- radioType = "gsm";
- nsCOMPtr<nsIGsmCellInfo> gsmCellInfo = do_QueryInterface(mCellInfo[idx]);
- ExtractCommonNonCDMACellInfoItems(gsmCellInfo, info);
- int32_t lac;
- gsmCellInfo->GetLac(&lac);
- info.Put(TEXT_LAC, lac);
- } else if (type == nsICellInfo::CELL_INFO_TYPE_WCDMA) {
- radioType = "wcdma";
- nsCOMPtr<nsIWcdmaCellInfo> wcdmaCellInfo = do_QueryInterface(mCellInfo[idx]);
- ExtractCommonNonCDMACellInfoItems(wcdmaCellInfo, info);
- int32_t lac, psc;
- wcdmaCellInfo->GetLac(&lac);
- wcdmaCellInfo->GetPsc(&psc);
- info.Put(TEXT_LAC, lac);
- info.Put(TEXT_PSC, psc);
- } else if (type == nsICellInfo::CELL_INFO_TYPE_CDMA) {
- radioType = "cdma";
- nsCOMPtr<nsICdmaCellInfo> cdmaCellInfo = do_QueryInterface(mCellInfo[idx]);
- int32_t mnc, lac, cid, sig;
- cdmaCellInfo->GetSystemId(&mnc);
- cdmaCellInfo->GetNetworkId(&lac);
- cdmaCellInfo->GetBaseStationId(&cid);
- info.Put(TEXT_MNC, mnc);
- info.Put(TEXT_LAC, lac);
- info.Put(TEXT_CID, cid);
-
- cdmaCellInfo->GetEvdoDbm(&sig);
- if (sig < 0 || sig == nsICellInfo::UNKNOWN_VALUE) {
- cdmaCellInfo->GetCdmaDbm(&sig);
- }
- if (sig > -1 && sig != nsICellInfo::UNKNOWN_VALUE) {
- sig *= -1;
- info.Put(TEXT_STRENGTH_DBM, sig);
- }
- } else if (type == nsICellInfo::CELL_INFO_TYPE_LTE) {
- radioType = "lte";
- nsCOMPtr<nsILteCellInfo> lteCellInfo = do_QueryInterface(mCellInfo[idx]);
- ExtractCommonNonCDMACellInfoItems(lteCellInfo, info);
- int32_t lac, timingAdvance, pcid, rsrp;
- lteCellInfo->GetTac(&lac);
- lteCellInfo->GetTimingAdvance(&timingAdvance);
- lteCellInfo->GetPcid(&pcid);
- lteCellInfo->GetRsrp(&rsrp);
- info.Put(TEXT_LAC, lac);
- info.Put(TEXT_TIMEING_ADVANCE, timingAdvance);
- info.Put(TEXT_PSC, pcid);
- if (rsrp != nsICellInfo::UNKNOWN_VALUE) {
- info.Put(TEXT_STRENGTH_DBM, rsrp * -1);
- }
- }
-
- aCellDesc += nsPrintfCString("\"%s\":\"%s\"", TEXT_RADIOTYPE.get(), radioType);
- for (auto it = info.Iter(); !it.Done(); it.Next()) {
- const nsACString& key = it.Key();
- int32_t value = it.UserData();
- if (value != nsICellInfo::UNKNOWN_VALUE) {
- aCellDesc += nsPrintfCString(",\"%s\":%d", key.BeginReading(), value);
- }
- }
-
- aCellDesc += "}";
- }
- aCellDesc += "]";
-}
-
-void
-StumblerInfo::DumpStumblerInfo()
-{
- if (!mIsWifiInfoResponseReceived || mCellInfoResponsesReceived != mCellInfoResponsesExpected) {
- STUMBLER_DBG("CellInfoReceived=%d (Expected=%d), WifiInfoResponseReceived=%d\n",
- mCellInfoResponsesReceived, mCellInfoResponsesExpected, mIsWifiInfoResponseReceived);
- return;
- }
- mIsWifiInfoResponseReceived = false;
- mCellInfoResponsesReceived = 0;
-
- nsAutoCString desc;
- nsresult rv = LocationInfoToString(desc);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("LocationInfoToString failed, skip this dump");
- return;
- }
-
- CellNetworkInfoToString(desc);
- desc += mWifiDesc;
-
- STUMBLER_DBG("dispatch write event to thread\n");
- nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
- MOZ_ASSERT(target);
-
- nsCOMPtr<nsIRunnable> event = new WriteStumbleOnThread(desc);
- target->Dispatch(event, NS_DISPATCH_NORMAL);
-}
-
-NS_IMETHODIMP
-StumblerInfo::NotifyGetCellInfoList(uint32_t count, nsICellInfo** aCellInfos)
-{
- MOZ_ASSERT(NS_IsMainThread());
- STUMBLER_DBG("There are %d cellinfo in the result\n", count);
-
- for (uint32_t i = 0; i < count; i++) {
- mCellInfo.AppendElement(aCellInfos[i]);
- }
- mCellInfoResponsesReceived++;
- DumpStumblerInfo();
- return NS_OK;
-}
-
-NS_IMETHODIMP StumblerInfo::NotifyGetCellInfoListFailed(const nsAString& error)
-{
- MOZ_ASSERT(NS_IsMainThread());
- mCellInfoResponsesReceived++;
- STUMBLER_ERR("NotifyGetCellInfoListFailedm CellInfoReadyNum=%d, mCellInfoResponsesExpected=%d, mIsWifiInfoResponseReceived=%d",
- mCellInfoResponsesReceived, mCellInfoResponsesExpected, mIsWifiInfoResponseReceived);
- DumpStumblerInfo();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-StumblerInfo::Onready(uint32_t count, nsIWifiScanResult** results)
-{
- MOZ_ASSERT(NS_IsMainThread());
- STUMBLER_DBG("There are %d wifiAPinfo in the result\n",count);
-
- mWifiDesc += ",\"wifiAccessPoints\": [";
- bool firstItem = true;
- for (uint32_t i = 0 ; i < count ; i++) {
- nsString ssid;
- results[i]->GetSsid(ssid);
- if (ssid.IsEmpty()) {
- STUMBLER_DBG("no ssid, skip this AP\n");
- continue;
- }
-
- if (ssid.Length() >= 6) {
- if (StringEndsWith(ssid, NS_LITERAL_STRING("_nomap"))) {
- STUMBLER_DBG("end with _nomap. skip this AP(ssid :%s)\n", ssid.get());
- continue;
- }
- }
-
- if (firstItem) {
- mWifiDesc += "{";
- firstItem = false;
- } else {
- mWifiDesc += ",{";
- }
-
- // mac address
- nsString bssid;
- results[i]->GetBssid(bssid);
- // 00:00:00:00:00:00 --> 000000000000
- bssid.StripChars(":");
- mWifiDesc += "\"macAddress\":\"";
- mWifiDesc += NS_ConvertUTF16toUTF8(bssid);
-
- uint32_t signal;
- results[i]->GetSignalStrength(&signal);
- mWifiDesc += "\",\"signalStrength\":";
- mWifiDesc.AppendInt(signal);
-
- mWifiDesc += "}";
- }
- mWifiDesc += "]";
-
- mIsWifiInfoResponseReceived = true;
- DumpStumblerInfo();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-StumblerInfo::Onfailure()
-{
- MOZ_ASSERT(NS_IsMainThread());
- STUMBLER_ERR("GetWifiScanResults Onfailure\n");
- mIsWifiInfoResponseReceived = true;
- DumpStumblerInfo();
- return NS_OK;
-}
-
diff --git a/dom/system/gonk/mozstumbler/MozStumbler.h b/dom/system/gonk/mozstumbler/MozStumbler.h
deleted file mode 100644
index 41ee4e5e1..000000000
--- a/dom/system/gonk/mozstumbler/MozStumbler.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_system_mozstumbler_h__
-#define mozilla_system_mozstumbler_h__
-
-#include "nsIDOMEventTarget.h"
-#include "nsICellInfo.h"
-#include "nsIWifi.h"
-
-#define STUMBLE_INTERVAL_MS 3000
-
-class nsGeoPosition;
-
-void MozStumble(nsGeoPosition* position);
-
-class StumblerInfo final : public nsICellInfoListCallback,
- public nsIWifiScanResultsReady
-{
-public:
- NS_DECL_THREADSAFE_ISUPPORTS
- NS_DECL_NSICELLINFOLISTCALLBACK
- NS_DECL_NSIWIFISCANRESULTSREADY
-
- explicit StumblerInfo(nsGeoPosition* position)
- : mPosition(position), mCellInfoResponsesExpected(0), mCellInfoResponsesReceived(0), mIsWifiInfoResponseReceived(0)
- {}
- void SetWifiInfoResponseReceived();
- void SetCellInfoResponsesExpected(uint8_t count);
-
-private:
- ~StumblerInfo() {}
- void DumpStumblerInfo();
- nsresult LocationInfoToString(nsACString& aLocDesc);
- void CellNetworkInfoToString(nsACString& aCellDesc);
- nsTArray<RefPtr<nsICellInfo>> mCellInfo;
- nsCString mWifiDesc;
- RefPtr<nsGeoPosition> mPosition;
- int mCellInfoResponsesExpected;
- int mCellInfoResponsesReceived;
- bool mIsWifiInfoResponseReceived;
-};
-#endif // mozilla_system_mozstumbler_h__
-
diff --git a/dom/system/gonk/mozstumbler/StumblerLogging.cpp b/dom/system/gonk/mozstumbler/StumblerLogging.cpp
deleted file mode 100644
index acf23b3b1..000000000
--- a/dom/system/gonk/mozstumbler/StumblerLogging.cpp
+++ /dev/null
@@ -1,13 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "StumblerLogging.h"
-
-mozilla::LogModule* GetLog()
-{
- static mozilla::LazyLogModule log("mozstumbler");
- return log;
-}
diff --git a/dom/system/gonk/mozstumbler/StumblerLogging.h b/dom/system/gonk/mozstumbler/StumblerLogging.h
deleted file mode 100644
index 038f44f8f..000000000
--- a/dom/system/gonk/mozstumbler/StumblerLogging.h
+++ /dev/null
@@ -1,18 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef STUMBLERLOGGING_H
-#define STUMBLERLOGGING_H
-
-#include "mozilla/Logging.h"
-
-mozilla::LogModule* GetLog();
-
-#define STUMBLER_DBG(arg, ...) MOZ_LOG(GetLog(), mozilla::LogLevel::Debug, ("STUMBLER - %s: " arg, __func__, ##__VA_ARGS__))
-#define STUMBLER_LOG(arg, ...) MOZ_LOG(GetLog(), mozilla::LogLevel::Info, ("STUMBLER - %s: " arg, __func__, ##__VA_ARGS__))
-#define STUMBLER_ERR(arg, ...) MOZ_LOG(GetLog(), mozilla::LogLevel::Error, ("STUMBLER -%s: " arg, __func__, ##__VA_ARGS__))
-
-#endif
diff --git a/dom/system/gonk/mozstumbler/UploadStumbleRunnable.cpp b/dom/system/gonk/mozstumbler/UploadStumbleRunnable.cpp
deleted file mode 100644
index d97aa9712..000000000
--- a/dom/system/gonk/mozstumbler/UploadStumbleRunnable.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "UploadStumbleRunnable.h"
-#include "StumblerLogging.h"
-#include "mozilla/dom/Event.h"
-#include "nsIInputStream.h"
-#include "nsIScriptSecurityManager.h"
-#include "nsIURLFormatter.h"
-#include "nsIXMLHttpRequest.h"
-#include "nsNetUtil.h"
-#include "nsVariant.h"
-
-UploadStumbleRunnable::UploadStumbleRunnable(nsIInputStream* aUploadData)
-: mUploadInputStream(aUploadData)
-{
-}
-
-NS_IMETHODIMP
-UploadStumbleRunnable::Run()
-{
- MOZ_ASSERT(NS_IsMainThread());
- nsresult rv = Upload();
- if (NS_FAILED(rv)) {
- WriteStumbleOnThread::UploadEnded(false);
- }
- return NS_OK;
-}
-
-nsresult
-UploadStumbleRunnable::Upload()
-{
- nsresult rv;
- RefPtr<nsVariant> variant = new nsVariant();
-
- rv = variant->SetAsISupports(mUploadInputStream);
- NS_ENSURE_SUCCESS(rv, rv);
-
- nsCOMPtr<nsIXMLHttpRequest> xhr = do_CreateInstance(NS_XMLHTTPREQUEST_CONTRACTID, &rv);
- NS_ENSURE_SUCCESS(rv, rv);
-
- nsCOMPtr<nsIScriptSecurityManager> secman =
- do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
- NS_ENSURE_SUCCESS(rv, rv);
-
- nsCOMPtr<nsIPrincipal> systemPrincipal;
- rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
- NS_ENSURE_SUCCESS(rv, rv);
-
- rv = xhr->Init(systemPrincipal, nullptr, nullptr, nullptr);
- NS_ENSURE_SUCCESS(rv, rv);
-
- nsCOMPtr<nsIURLFormatter> formatter =
- do_CreateInstance("@mozilla.org/toolkit/URLFormatterService;1", &rv);
- NS_ENSURE_SUCCESS(rv, rv);
- nsString url;
- rv = formatter->FormatURLPref(NS_LITERAL_STRING("geo.stumbler.url"), url);
- NS_ENSURE_SUCCESS(rv, rv);
-
- rv = xhr->Open(NS_LITERAL_CSTRING("POST"), NS_ConvertUTF16toUTF8(url), false, EmptyString(), EmptyString());
- NS_ENSURE_SUCCESS(rv, rv);
-
- xhr->SetRequestHeader(NS_LITERAL_CSTRING("Content-Type"), NS_LITERAL_CSTRING("gzip"));
- xhr->SetMozBackgroundRequest(true);
- // 60s timeout
- xhr->SetTimeout(60 * 1000);
-
- nsCOMPtr<EventTarget> target(do_QueryInterface(xhr));
- RefPtr<nsIDOMEventListener> listener = new UploadEventListener(xhr);
-
- const char* const sEventStrings[] = {
- // nsIXMLHttpRequestEventTarget event types
- "abort",
- "error",
- "load",
- "timeout"
- };
-
- for (uint32_t index = 0; index < MOZ_ARRAY_LENGTH(sEventStrings); index++) {
- nsAutoString eventType = NS_ConvertASCIItoUTF16(sEventStrings[index]);
- rv = target->AddEventListener(eventType, listener, false);
- NS_ENSURE_SUCCESS(rv, rv);
- }
-
- rv = xhr->Send(variant);
- NS_ENSURE_SUCCESS(rv, rv);
-
- return NS_OK;
-}
-
-NS_IMPL_ISUPPORTS(UploadEventListener, nsIDOMEventListener)
-
-UploadEventListener::UploadEventListener(nsIXMLHttpRequest* aXHR)
-: mXHR(aXHR)
-{
-}
-
-NS_IMETHODIMP
-UploadEventListener::HandleEvent(nsIDOMEvent* aEvent)
-{
- nsString type;
- if (NS_FAILED(aEvent->GetType(type))) {
- STUMBLER_ERR("Failed to get event type");
- WriteStumbleOnThread::UploadEnded(false);
- return NS_ERROR_FAILURE;
- }
-
- if (type.EqualsLiteral("load")) {
- STUMBLER_DBG("Got load Event\n");
- } else if (type.EqualsLiteral("error") && mXHR) {
- STUMBLER_ERR("Upload Error");
- } else {
- STUMBLER_DBG("Receive %s Event", NS_ConvertUTF16toUTF8(type).get());
- }
-
- uint32_t statusCode = 0;
- bool doDelete = false;
- if (!mXHR) {
- return NS_OK;
- }
- nsresult rv = mXHR->GetStatus(&statusCode);
- if (NS_SUCCEEDED(rv)) {
- STUMBLER_DBG("statuscode %d \n", statusCode);
- }
-
- if (200 == statusCode || 400 == statusCode) {
- doDelete = true;
- }
-
- WriteStumbleOnThread::UploadEnded(doDelete);
- nsCOMPtr<EventTarget> target(do_QueryInterface(mXHR));
-
- const char* const sEventStrings[] = {
- // nsIXMLHttpRequestEventTarget event types
- "abort",
- "error",
- "load",
- "timeout"
- };
-
- for (uint32_t index = 0; index < MOZ_ARRAY_LENGTH(sEventStrings); index++) {
- nsAutoString eventType = NS_ConvertASCIItoUTF16(sEventStrings[index]);
- rv = target->RemoveEventListener(eventType, this, false);
- }
-
- mXHR = nullptr;
- return NS_OK;
-}
diff --git a/dom/system/gonk/mozstumbler/UploadStumbleRunnable.h b/dom/system/gonk/mozstumbler/UploadStumbleRunnable.h
deleted file mode 100644
index 462665a86..000000000
--- a/dom/system/gonk/mozstumbler/UploadStumbleRunnable.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-
-#ifndef UPLOADSTUMBLERUNNABLE_H
-#define UPLOADSTUMBLERUNNABLE_H
-
-#include "nsIDOMEventListener.h"
-
-class nsIXMLHttpRequest;
-class nsIInputStream;
-
-/*
- This runnable is managed by WriteStumbleOnThread only, see that class
- for how this is scheduled.
- */
-class UploadStumbleRunnable final : public Runnable
-{
-public:
- explicit UploadStumbleRunnable(nsIInputStream* aUploadInputStream);
-
- NS_IMETHOD Run() override;
-private:
- virtual ~UploadStumbleRunnable() {}
- nsCOMPtr<nsIInputStream> mUploadInputStream;
- nsresult Upload();
-};
-
-
-class UploadEventListener : public nsIDOMEventListener
-{
-public:
- UploadEventListener(nsIXMLHttpRequest* aXHR);
-
- NS_DECL_ISUPPORTS
- NS_DECL_NSIDOMEVENTLISTENER
-
-protected:
- virtual ~UploadEventListener() {}
- nsCOMPtr<nsIXMLHttpRequest> mXHR;
-};
-
-#endif
diff --git a/dom/system/gonk/mozstumbler/WriteStumbleOnThread.cpp b/dom/system/gonk/mozstumbler/WriteStumbleOnThread.cpp
deleted file mode 100644
index e58e771c4..000000000
--- a/dom/system/gonk/mozstumbler/WriteStumbleOnThread.cpp
+++ /dev/null
@@ -1,321 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "WriteStumbleOnThread.h"
-#include "StumblerLogging.h"
-#include "UploadStumbleRunnable.h"
-#include "nsDumpUtils.h"
-#include "nsGZFileWriter.h"
-#include "nsIFileStreams.h"
-#include "nsIInputStream.h"
-#include "nsPrintfCString.h"
-
-#define MAXFILESIZE_KB (15 * 1024)
-#define ONEDAY_IN_MSEC (24 * 60 * 60 * 1000)
-#define MAX_UPLOAD_ATTEMPTS 20
-
-mozilla::Atomic<bool> WriteStumbleOnThread::sIsFileWaitingForUpload(false);
-mozilla::Atomic<bool> WriteStumbleOnThread::sIsAlreadyRunning(false);
-WriteStumbleOnThread::UploadFreqGuard WriteStumbleOnThread::sUploadFreqGuard = {0};
-
-#define FILENAME_INPROGRESS NS_LITERAL_CSTRING("stumbles.json.gz")
-#define FILENAME_COMPLETED NS_LITERAL_CSTRING("stumbles.done.json.gz")
-#define OUTPUT_DIR NS_LITERAL_CSTRING("mozstumbler")
-
-class DeleteRunnable : public Runnable
-{
- public:
- DeleteRunnable() {}
-
- NS_IMETHOD
- Run() override
- {
- nsCOMPtr<nsIFile> tmpFile;
- nsresult rv = nsDumpUtils::OpenTempFile(FILENAME_COMPLETED,
- getter_AddRefs(tmpFile),
- OUTPUT_DIR,
- nsDumpUtils::CREATE);
- if (NS_SUCCEEDED(rv)) {
- tmpFile->Remove(true);
- }
- // critically, this sets this flag to false so writing can happen again
- WriteStumbleOnThread::sIsAlreadyRunning = false;
- WriteStumbleOnThread::sIsFileWaitingForUpload = false;
- return NS_OK;
- }
-
- private:
- ~DeleteRunnable() {}
-};
-
-bool
-WriteStumbleOnThread::IsFileWaitingForUpload()
-{
- return sIsFileWaitingForUpload;
-}
-
-void
-WriteStumbleOnThread::UploadEnded(bool deleteUploadFile)
-{
- if (!deleteUploadFile) {
- sIsAlreadyRunning = false;
- return;
- }
-
- nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
- MOZ_ASSERT(target);
- nsCOMPtr<nsIRunnable> event = new DeleteRunnable();
- target->Dispatch(event, NS_DISPATCH_NORMAL);
-}
-
-void
-WriteStumbleOnThread::WriteJSON(Partition aPart)
-{
- MOZ_ASSERT(!NS_IsMainThread());
-
- nsCOMPtr<nsIFile> tmpFile;
- nsresult rv;
- rv = nsDumpUtils::OpenTempFile(FILENAME_INPROGRESS, getter_AddRefs(tmpFile),
- OUTPUT_DIR, nsDumpUtils::CREATE);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("Open a file for stumble failed");
- return;
- }
-
- RefPtr<nsGZFileWriter> gzWriter = new nsGZFileWriter(nsGZFileWriter::Append);
- rv = gzWriter->Init(tmpFile);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("gzWriter init failed");
- return;
- }
-
- /*
- The json format is like below.
- {items:[
- {item},
- {item},
- {item}
- ]}
- */
-
- // Need to add "]}" after the last item
- if (aPart == Partition::End) {
- rv = gzWriter->Write("]}");
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("gzWriter Write failed");
- }
-
- rv = gzWriter->Finish();
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("ostream finish failed");
- }
-
- nsCOMPtr<nsIFile> targetFile;
- nsresult rv = nsDumpUtils::OpenTempFile(FILENAME_COMPLETED, getter_AddRefs(targetFile),
- OUTPUT_DIR, nsDumpUtils::CREATE);
- nsAutoString targetFilename;
- rv = targetFile->GetLeafName(targetFilename);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("Get Filename failed");
- return;
- }
- rv = targetFile->Remove(true);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("Remove File failed");
- return;
- }
- // Rename tmpfile
- rv = tmpFile->MoveTo(/* directory */ nullptr, targetFilename);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("Rename File failed");
- return;
- }
- return;
- }
-
- // Need to add "{items:[" before the first item
- if (aPart == Partition::Begining) {
- rv = gzWriter->Write("{\"items\":[{");
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("ostream write begining failed");
- }
- } else if (aPart == Partition::Middle) {
- rv = gzWriter->Write(",{");
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("ostream write middle failed");
- }
- }
- rv = gzWriter->Write(mDesc.get());
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("ostream write mDesc failed");
- }
- // one item is ended with '}' (e.g. {item})
- rv = gzWriter->Write("}");
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("ostream write end failed");
- }
-
- rv = gzWriter->Finish();
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("ostream finish failed");
- }
-
- // check if it is the end of this file
- int64_t fileSize = 0;
- rv = tmpFile->GetFileSize(&fileSize);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("GetFileSize failed");
- return;
- }
- if (fileSize >= MAXFILESIZE_KB) {
- WriteJSON(Partition::End);
- return;
- }
-}
-
-WriteStumbleOnThread::Partition
-WriteStumbleOnThread::GetWritePosition()
-{
- MOZ_ASSERT(!NS_IsMainThread());
-
- nsCOMPtr<nsIFile> tmpFile;
- nsresult rv = nsDumpUtils::OpenTempFile(FILENAME_INPROGRESS, getter_AddRefs(tmpFile),
- OUTPUT_DIR, nsDumpUtils::CREATE);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("Open a file for stumble failed");
- return Partition::Unknown;
- }
-
- int64_t fileSize = 0;
- rv = tmpFile->GetFileSize(&fileSize);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("GetFileSize failed");
- return Partition::Unknown;
- }
-
- if (fileSize == 0) {
- return Partition::Begining;
- } else if (fileSize >= MAXFILESIZE_KB) {
- return Partition::End;
- } else {
- return Partition::Middle;
- }
-}
-
-NS_IMETHODIMP
-WriteStumbleOnThread::Run()
-{
- MOZ_ASSERT(!NS_IsMainThread());
-
- bool b = sIsAlreadyRunning.exchange(true);
- if (b) {
- return NS_OK;
- }
-
- UploadFileStatus status = GetUploadFileStatus();
-
- if (UploadFileStatus::NoFile != status) {
- if (UploadFileStatus::ExistsAndReadyToUpload == status) {
- sIsFileWaitingForUpload = true;
- Upload();
- return NS_OK;
- }
- } else {
- Partition partition = GetWritePosition();
- if (partition == Partition::Unknown) {
- STUMBLER_ERR("GetWritePosition failed, skip once");
- } else {
- WriteJSON(partition);
- }
- }
-
- sIsFileWaitingForUpload = false;
- sIsAlreadyRunning = false;
- return NS_OK;
-}
-
-
-/*
- If the upload file exists, then check if it is one day old.
- • if it is a day old -> ExistsAndReadyToUpload
- • if it is less than the current day old -> Exists
- • otherwise -> NoFile
-
- The Exists case means that the upload and the stumbling is rate limited
- per-day to the size of the one file.
- */
-WriteStumbleOnThread::UploadFileStatus
-WriteStumbleOnThread::GetUploadFileStatus()
-{
- nsCOMPtr<nsIFile> tmpFile;
- nsresult rv = nsDumpUtils::OpenTempFile(FILENAME_COMPLETED, getter_AddRefs(tmpFile),
- OUTPUT_DIR, nsDumpUtils::CREATE);
- int64_t fileSize;
- rv = tmpFile->GetFileSize(&fileSize);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("GetFileSize failed");
- return UploadFileStatus::NoFile;
- }
- if (fileSize <= 0) {
- tmpFile->Remove(true);
- return UploadFileStatus::NoFile;
- }
-
- PRTime lastModifiedTime;
- tmpFile->GetLastModifiedTime(&lastModifiedTime);
- if ((PR_Now() / PR_USEC_PER_MSEC) - lastModifiedTime >= ONEDAY_IN_MSEC) {
- return UploadFileStatus::ExistsAndReadyToUpload;
- }
- return UploadFileStatus::Exists;
-}
-
-void
-WriteStumbleOnThread::Upload()
-{
- MOZ_ASSERT(!NS_IsMainThread());
-
- time_t seconds = time(0);
- int day = seconds / (60 * 60 * 24);
-
- if (sUploadFreqGuard.daySinceEpoch < day) {
- sUploadFreqGuard.daySinceEpoch = day;
- sUploadFreqGuard.attempts = 0;
- }
-
- sUploadFreqGuard.attempts++;
- if (sUploadFreqGuard.attempts > MAX_UPLOAD_ATTEMPTS) {
- STUMBLER_ERR("Too many upload attempts today");
- sIsAlreadyRunning = false;
- return;
- }
-
- nsCOMPtr<nsIFile> tmpFile;
- nsresult rv = nsDumpUtils::OpenTempFile(FILENAME_COMPLETED, getter_AddRefs(tmpFile),
- OUTPUT_DIR, nsDumpUtils::CREATE);
- int64_t fileSize;
- rv = tmpFile->GetFileSize(&fileSize);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- STUMBLER_ERR("GetFileSize failed");
- sIsAlreadyRunning = false;
- return;
- }
-
- if (fileSize <= 0) {
- sIsAlreadyRunning = false;
- return;
- }
-
- // prepare json into nsIInputStream
- nsCOMPtr<nsIInputStream> inStream;
- rv = NS_NewLocalFileInputStream(getter_AddRefs(inStream), tmpFile);
- if (NS_FAILED(rv)) {
- sIsAlreadyRunning = false;
- return;
- }
-
- RefPtr<nsIRunnable> uploader = new UploadStumbleRunnable(inStream);
- NS_DispatchToMainThread(uploader);
-}
diff --git a/dom/system/gonk/mozstumbler/WriteStumbleOnThread.h b/dom/system/gonk/mozstumbler/WriteStumbleOnThread.h
deleted file mode 100644
index 104cf9bdd..000000000
--- a/dom/system/gonk/mozstumbler/WriteStumbleOnThread.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef WriteStumbleOnThread_H
-#define WriteStumbleOnThread_H
-
-#include "mozilla/Atomics.h"
-
-class DeleteRunnable;
-
-/*
- This class is the entry point to stumbling, in that it
- receives the location+cell+wifi string and writes it
- to disk, or instead, it calls UploadStumbleRunnable
- to upload the data.
-
- Writes will happen until the file is a max size, then stop.
- Uploads will happen only when the file is one day old.
- The purpose of these decisions is to have very simple rate-limiting
- on the writes, as well as the uploads.
-
- There is only one file active; it is either being used for writing,
- or for uploading. If the file is ready for uploading, no further
- writes will take place until this file has been uploaded.
- This can mean writing might not take place for days until the uploaded
- file is processed. This is correct by-design.
-
- A notable limitation is that the upload is triggered by a location event,
- this is used as an arbitrary and simple trigger. In future, there are
- better events that can be used, such as detecting network activity.
-
- This thread is guarded so that only one instance is active (see the
- mozilla::Atomics used for this).
- */
-class WriteStumbleOnThread : public mozilla::Runnable
-{
-public:
- explicit WriteStumbleOnThread(const nsCString& aDesc)
- : mDesc(aDesc)
- {}
-
- NS_IMETHOD Run() override;
-
- static void UploadEnded(bool deleteUploadFile);
-
- // Used externally to determine if cell+wifi scans should happen
- // (returns false for that case).
- static bool IsFileWaitingForUpload();
-
-private:
- friend class DeleteRunnable;
-
- enum class Partition {
- Begining,
- Middle,
- End,
- Unknown
- };
-
- enum class UploadFileStatus {
- NoFile, Exists, ExistsAndReadyToUpload
- };
-
- ~WriteStumbleOnThread() {}
-
- Partition GetWritePosition();
- UploadFileStatus GetUploadFileStatus();
- void WriteJSON(Partition aPart);
- void Upload();
-
- nsCString mDesc;
-
- // Only run one instance of this
- static mozilla::Atomic<bool> sIsAlreadyRunning;
-
- static mozilla::Atomic<bool> sIsFileWaitingForUpload;
-
- // Limit the upload attempts per day. If the device is rebooted
- // this resets the allowed attempts, which is acceptable.
- struct UploadFreqGuard {
- int attempts;
- int daySinceEpoch;
- };
- static UploadFreqGuard sUploadFreqGuard;
-
-};
-
-#endif
diff --git a/dom/system/gonk/nsIAudioManager.idl b/dom/system/gonk/nsIAudioManager.idl
deleted file mode 100644
index c2eb62b21..000000000
--- a/dom/system/gonk/nsIAudioManager.idl
+++ /dev/null
@@ -1,58 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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, builtinclass, uuid(df31c280-1ef1-11e5-867f-0800200c9a66)]
-interface nsIAudioManager : nsISupports
-{
- /**
- * Microphone muted?
- */
- attribute boolean microphoneMuted;
-
- /**
- * Set the phone's audio mode.
- */
- const long PHONE_STATE_INVALID = -2;
- const long PHONE_STATE_CURRENT = -1;
- const long PHONE_STATE_NORMAL = 0;
- const long PHONE_STATE_RINGTONE = 1;
- const long PHONE_STATE_IN_CALL = 2;
- const long PHONE_STATE_IN_COMMUNICATION = 3;
-
- attribute long phoneState;
-
- /**
- * Configure a particular device ("force") to be used for one of the uses
- * (communication, media playback, etc.)
- */
- const long FORCE_NONE = 0; // the default
- const long FORCE_SPEAKER = 1;
- const long FORCE_HEADPHONES = 2;
- const long FORCE_BT_SCO = 3;
- const long FORCE_BT_A2DP = 4;
- const long FORCE_WIRED_ACCESSORY = 5;
- const long FORCE_BT_CAR_DOCK = 6;
- const long FORCE_BT_DESK_DOCK = 7;
- const long FORCE_ANALOG_DOCK = 8;
- const long FORCE_DIGITAL_DOCK = 9;
- const long FORCE_NO_BT_A2DP = 10;
- const long USE_COMMUNICATION = 0;
- const long USE_MEDIA = 1;
- const long USE_RECORD = 2;
- const long USE_DOCK = 3;
-
- void setForceForUse(in long usage, in long force);
- long getForceForUse(in long usage);
-
- /**
- * These functions would be used when we enable the new volume control API
- * (mozAudioChannelManager). The range of volume index is from 0 to N.
- * More details on : https://gist.github.com/evanxd/41d8e2d91c5201a42bfa
- */
- void setAudioChannelVolume(in unsigned long channel, in unsigned long index);
- unsigned long getAudioChannelVolume(in unsigned long channel);
- unsigned long getMaxAudioChannelVolume(in unsigned long channel);
-};
diff --git a/dom/system/gonk/nsIDataCallInterfaceService.idl b/dom/system/gonk/nsIDataCallInterfaceService.idl
deleted file mode 100644
index c387879fa..000000000
--- a/dom/system/gonk/nsIDataCallInterfaceService.idl
+++ /dev/null
@@ -1,268 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(6b66446a-7000-438f-8e1b-b56b4cbf4fa9)]
-interface nsIDataCall : nsISupports
-{
- /**
- * Data call fail cause. One of the nsIDataCallInterface.DATACALL_FAIL_*
- * values.
- */
- readonly attribute long failCause;
-
- /**
- * If failCause != nsIDataCallInterface.DATACALL_FAIL_NONE, this field
- * indicates the suggested retry back-off timer. The unit is milliseconds.
- */
- readonly attribute long suggestedRetryTime;
-
- /**
- * Context ID, uniquely identifies this call.
- */
- readonly attribute long cid;
-
- /**
- * Data call network state. One of the nsIDataCallInterface.DATACALL_STATE_*
- * values.
- */
- readonly attribute long active;
-
- /**
- * Data call connection type. One of the
- * nsIDataCallInterface.DATACALL_PDP_TYPE_* values.
- */
- readonly attribute long pdpType;
-
- /**
- * The network interface name.
- */
- readonly attribute DOMString ifname;
-
- /**
- * A space-delimited list of addresses with optional "/" prefix length.
- */
- readonly attribute DOMString addresses;
-
- /**
- * A space-delimited list of DNS server addresses.
- */
- readonly attribute DOMString dnses;
-
- /**
- * A space-delimited list of default gateway addresses.
- */
- readonly attribute DOMString gateways;
-
- /**
- * A space-delimited list of Proxy Call State Control Function addresses for
- * IMS client.
- */
- readonly attribute DOMString pcscf;
-
- /**
- * MTU received from network, -1 if not set or invalid.
- */
- readonly attribute long mtu;
-};
-
-[scriptable, uuid(e119c54b-9354-4ad6-a1ee-18608bde9320)]
-interface nsIDataCallInterfaceListener : nsISupports
-{
- /**
- * Notify data call interface listeners about unsolicited data call state
- * changes.
- */
- void notifyDataCallListChanged(in uint32_t count,
- [array, size_is(count)] in nsIDataCall
- dataCalls);
-};
-
-[scriptable, uuid(db0b640a-3b3a-4f48-84dc-256e176876c2)]
-interface nsIDataCallCallback : nsISupports
-{
- /**
- * Called when setupDataCall() returns succesfully.
- */
- void notifySetupDataCallSuccess(in nsIDataCall dataCall);
-
- /**
- * Called when getDataCallList() returns succesfully.
- */
- void notifyGetDataCallListSuccess(in uint32_t count,
- [array, size_is(count)] in nsIDataCall
- dataCalls);
- /**
- * Called when request returns succesfully.
- */
- void notifySuccess();
-
- /**
- * Called when request returns error.
- */
- void notifyError(in AString errorMsg);
-};
-
-[scriptable, uuid(ec219021-8623-4b9f-aba5-4db58c60684f)]
-interface nsIDataCallInterface : nsISupports
-{
- /**
- * Data fail causes, defined in TS 24.008.
- */
- const long DATACALL_FAIL_NONE = 0;
- const long DATACALL_FAIL_OPERATOR_BARRED = 0x08;
- const long DATACALL_FAIL_INSUFFICIENT_RESOURCES = 0x1A;
- const long DATACALL_FAIL_MISSING_UKNOWN_APN = 0x1B;
- const long DATACALL_FAIL_UNKNOWN_PDP_ADDRESS_TYPE = 0x1C;
- const long DATACALL_FAIL_USER_AUTHENTICATION = 0x1D;
- const long DATACALL_FAIL_ACTIVATION_REJECT_GGSN = 0x1E;
- const long DATACALL_FAIL_ACTIVATION_REJECT_UNSPECIFIED = 0x1F;
- const long DATACALL_FAIL_SERVICE_OPTION_NOT_SUPPORTED = 0x20;
- const long DATACALL_FAIL_SERVICE_OPTION_NOT_SUBSCRIBED = 0x21;
- const long DATACALL_FAIL_SERVICE_OPTION_OUT_OF_ORDER = 0x22;
- const long DATACALL_FAIL_NSAPI_IN_USE = 0x23;
- const long DATACALL_FAIL_ONLY_IPV4_ALLOWED = 0x32;
- const long DATACALL_FAIL_ONLY_IPV6_ALLOWED = 0x33;
- const long DATACALL_FAIL_ONLY_SINGLE_BEARER_ALLOWED = 0x34;
- const long DATACALL_FAIL_PROTOCOL_ERRORS = 0x6F;
- /* Not mentioned in the specification */
- const long DATACALL_FAIL_VOICE_REGISTRATION_FAIL = -1;
- const long DATACALL_FAIL_DATA_REGISTRATION_FAIL = -2;
- const long DATACALL_FAIL_SIGNAL_LOST = -3;
- const long DATACALL_FAIL_PREF_RADIO_TECH_CHANGED = -4;
- const long DATACALL_FAIL_RADIO_POWER_OFF = -5;
- const long DATACALL_FAIL_TETHERED_CALL_ACTIVE = -6;
- const long DATACALL_FAIL_ERROR_UNSPECIFIED = 0xFFFF;
-
- /**
- * Data call network state.
- */
- const long DATACALL_STATE_INACTIVE = 0;
- const long DATACALL_STATE_ACTIVE_DOWN = 1;
- const long DATACALL_STATE_ACTIVE_UP = 2;
-
- /**
- * Data call authentication type. Must match the values in ril_consts
- * RIL_DATACALL_AUTH_TO_GECKO array.
- */
- const long DATACALL_AUTH_NONE = 0;
- const long DATACALL_AUTH_PAP = 1;
- const long DATACALL_AUTH_CHAP = 2;
- const long DATACALL_AUTH_PAP_OR_CHAP = 3;
-
- /**
- * Data call protocol type. Must match the values in ril_consts
- * RIL_DATACALL_PDP_TYPES array.
- */
- const long DATACALL_PDP_TYPE_IPV4 = 0;
- const long DATACALL_PDP_TYPE_IPV4V6 = 1;
- const long DATACALL_PDP_TYPE_IPV6 = 2;
-
- /**
- * Reason for deactivating data call.
- */
- const long DATACALL_DEACTIVATE_NO_REASON = 0;
- const long DATACALL_DEACTIVATE_RADIO_SHUTDOWN = 1;
-
- /**
- * Setup data call.
- *
- * @param apn
- * Apn to connect to.
- * @param username
- * Username for apn.
- * @param password
- * Password for apn.
- * @param authType
- * Authentication type. One of the DATACALL_AUTH_* values.
- * @param pdpType
- * Connection type. One of the DATACALL_PDP_TYPE_* values.
- * @param nsIDataCallCallback
- * Called when request is finished.
- *
- * If successful, the notifySetupDataCallSuccess() will be called with the
- * new nsIDataCall.
- *
- * Otherwise, the notifyError() will be called, and the error will be either
- * 'RadioNotAvailable', 'OpNotAllowedBeforeRegToNw',
- * 'OpNotAllowedDuringVoiceCall', 'RequestNotSupported' or 'GenericFailure'.
- */
- void setupDataCall(in AString apn, in AString username,
- in AString password, in long authType,
- in long pdpType,
- in nsIDataCallCallback callback);
-
- /**
- * Deactivate data call.
- *
- * @param cid
- * Context id.
- * @param reason
- * Disconnect Reason. One of the DATACALL_DEACTIVATE_* values.
- * @param nsIDataCallCallback
- * Called when request is finished.
- *
- * If successful, the notifySuccess() will be called.
- *
- * Otherwise, the notifyError() will be called, and the error will be either
- * 'RadioNotAvailable' or 'GenericFailure'.
- */
- void deactivateDataCall(in long cid,
- in long reason,
- in nsIDataCallCallback callback);
-
- /**
- * Get current data call list.
- *
- * @param nsIDataCallCallback
- * Called when request is finished.
- *
- * If successful, the notifyGetDataCallListSuccess() will be called with the
- * list of nsIDataCall(s).
- *
- * Otherwise, the notifyError() will be called, and the error will be either
- * 'RadioNotAvailable' or 'GenericFailure'.
- */
- void getDataCallList(in nsIDataCallCallback callback);
-
- /**
- * Set data registration state.
- *
- * @param attach
- * whether to attach data registration or not.
- * @param nsIDataCallCallback
- * Called when request is finished.
- *
- * If successful, the notifySuccess() will be called.
- *
- * Otherwise, the notifyError() will be called, and the error will be either
- * 'RadioNotAvailable', 'SubscriptionNotAvailable' or 'GenericFailure'.
- */
- void setDataRegistration(in boolean attach,
- in nsIDataCallCallback callback);
-
- /**
- * Register to receive unsolicited events from this nsIDataCallInterface.
- */
- void registerListener(in nsIDataCallInterfaceListener listener);
-
- /**
- * Unregister to stop receiving unsolicited events from this
- * nsIDataCallInterface.
- */
- void unregisterListener(in nsIDataCallInterfaceListener listener);
-};
-
-[scriptable, uuid(64700406-7429-4743-a6ae-f82e9877fd0d)]
-interface nsIDataCallInterfaceService : nsISupports
-{
- /**
- * Get the corresponding data call interface.
- *
- * @param clientId
- * clientId of the data call interface to get.
- */
- nsIDataCallInterface getDataCallInterface(in long clientId);
-}; \ No newline at end of file
diff --git a/dom/system/gonk/nsIDataCallManager.idl b/dom/system/gonk/nsIDataCallManager.idl
deleted file mode 100644
index de8477801..000000000
--- a/dom/system/gonk/nsIDataCallManager.idl
+++ /dev/null
@@ -1,81 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-#include "nsINetworkInterface.idl"
-
-[scriptable, uuid(b8bcd6aa-5b06-4362-a68c-317878429e51)]
-interface nsIRilNetworkInfo : nsINetworkInfo
-{
- readonly attribute unsigned long serviceId;
- readonly attribute DOMString iccId;
-
- /* The following attributes are for MMS proxy settings. */
- readonly attribute DOMString mmsc; // Empty string if not set.
- readonly attribute DOMString mmsProxy; // Empty string if not set.
- readonly attribute long mmsPort; // -1 if not set.
-
- /**
- * Get the list of pcscf addresses, could be IPv4 or IPv6.
- *
- * @param count
- * The length of the list of pcscf addresses.
- *
- * @returns the list of pcscf addresses.
- */
- void getPcscf([optional] out unsigned long count,
- [array, size_is(count), retval] out wstring pcscf);
-};
-
-[scriptable, function, uuid(cb2f0f5b-67f4-4c14-93e8-01e66b630464)]
-interface nsIDeactivateDataCallsCallback : nsISupports
-{
- /**
- * Callback function used to notify when all data calls are disconnected.
- */
- void notifyDataCallsDisconnected();
-};
-
-[scriptable, uuid(e3feec20-36b4-47de-a7a5-e32a65f20186)]
-interface nsIDataCallHandler : nsISupports
-{
- /**
- * PDP APIs
- *
- * @param networkType
- * Mobile network type, that is,
- * nsINetworkInterface.NETWORK_TYPE_MOBILE or one of the
- * nsINetworkInterface.NETWORK_TYPE_MOBILE_* values.
- */
- void setupDataCallByType(in long networkType);
- void deactivateDataCallByType(in long networkType);
- long getDataCallStateByType(in long networkType);
-
- /**
- * Deactivate all data calls.
- *
- * @param callback
- * Callback to notify when all data calls are disconnected.
- */
- void deactivateDataCalls(in nsIDeactivateDataCallsCallback callback);
-
- /**
- * Called to reconsider data call state.
- */
- void updateRILNetworkInterface();
-};
-
-[scriptable, uuid(2c46e37d-88dc-4d25-bb37-e1c0d3e9cb5f)]
-interface nsIDataCallManager : nsISupports
-{
- readonly attribute long dataDefaultServiceId;
-
- /**
- * Get the corresponding data call handler.
- *
- * @param clientId
- * clientId of the data call handler to get.
- */
- nsIDataCallHandler getDataCallHandler(in unsigned long clientId);
-}; \ No newline at end of file
diff --git a/dom/system/gonk/nsIGonkDataCallInterfaceService.idl b/dom/system/gonk/nsIGonkDataCallInterfaceService.idl
deleted file mode 100644
index 240ca6bab..000000000
--- a/dom/system/gonk/nsIGonkDataCallInterfaceService.idl
+++ /dev/null
@@ -1,18 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsIDataCallInterfaceService.idl"
-
-[scriptable, uuid(f008d00c-e2b8-49b2-8f88-19111577938e)]
-interface nsIGonkDataCallInterfaceService : nsIDataCallInterfaceService
-{
- /**
- * Called by RadioInterface or lower layer to notify about data call list
- * changes.
- */
- void notifyDataCallListChanged(in unsigned long clientId,
- in uint32_t count,
- [array, size_is(count)] in nsIDataCall
- dataCalls);
-}; \ No newline at end of file
diff --git a/dom/system/gonk/nsINetworkInterface.idl b/dom/system/gonk/nsINetworkInterface.idl
deleted file mode 100644
index bd40e751a..000000000
--- a/dom/system/gonk/nsINetworkInterface.idl
+++ /dev/null
@@ -1,108 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(4816a559-5620-4cb5-8433-ff0b25e6622f)]
-interface nsINetworkInfo : nsISupports
-{
- const long NETWORK_STATE_UNKNOWN = -1;
- const long NETWORK_STATE_CONNECTING = 0;
- const long NETWORK_STATE_CONNECTED = 1;
- const long NETWORK_STATE_DISCONNECTING = 2;
- const long NETWORK_STATE_DISCONNECTED = 3;
- const long NETWORK_STATE_ENABLED = 4;
- const long NETWORK_STATE_DISABLED = 5;
-
- /**
- * Current network state, one of the NETWORK_STATE_* constants.
- *
- * When this changes, network interface implementations notify with
- * updateNetworkInterface() API.
- */
- readonly attribute long state;
-
- const long NETWORK_TYPE_UNKNOWN = -1;
- const long NETWORK_TYPE_WIFI = 0;
- const long NETWORK_TYPE_MOBILE = 1;
- const long NETWORK_TYPE_MOBILE_MMS = 2;
- const long NETWORK_TYPE_MOBILE_SUPL = 3;
- const long NETWORK_TYPE_WIFI_P2P = 4;
- const long NETWORK_TYPE_MOBILE_IMS = 5;
- const long NETWORK_TYPE_MOBILE_DUN = 6;
- const long NETWORK_TYPE_MOBILE_FOTA = 7;
- const long NETWORK_TYPE_ETHERNET = 8;
-
- /**
- * Network type. One of the NETWORK_TYPE_* constants.
- */
- readonly attribute long type;
-
- /**
- * Interface name of the network interface this network info belongs to.
- */
- readonly attribute DOMString name;
-
- /**
- * Get the list of ip addresses and prefix lengths, ip address could be IPv4
- * or IPv6, typically 1 IPv4 or 1 IPv6 or one of each.
- *
- * @param ips
- * The list of ip addresses retrieved.
- * @param prefixLengths
- * The list of prefix lengths retrieved.
- *
- * @returns the length of the lists.
- */
- void getAddresses([array, size_is(count)] out wstring ips,
- [array, size_is(count)] out unsigned long prefixLengths,
- [retval] out unsigned long count);
-
- /**
- * Get the list of gateways, could be IPv4 or IPv6, typically 1 IPv4 or 1
- * IPv6 or one of each.
- *
- * @param count
- * The length of the list of gateways
- *
- * @returns the list of gateways.
- */
- void getGateways([optional] out unsigned long count,
- [array, size_is(count), retval] out wstring gateways);
-
- /**
- * Get the list of dnses, could be IPv4 or IPv6.
- *
- * @param count
- * The length of the list of dnses.
- *
- * @returns the list of dnses.
- */
- void getDnses([optional] out unsigned long count,
- [array, size_is(count), retval] out wstring dnses);
-};
-
-[scriptable, uuid(8b1345fa-b34c-41b3-8d21-09f961bf8887)]
-interface nsINetworkInterface : nsISupports
-{
- /**
- * The network information about this network interface.
- */
- readonly attribute nsINetworkInfo info;
-
- /**
- * The host name of the http proxy server.
- */
- readonly attribute DOMString httpProxyHost;
-
- /*
- * The port number of the http proxy server.
- */
- readonly attribute long httpProxyPort;
-
- /*
- * The Maximun Transmit Unit for this network interface, -1 if not set.
- */
- readonly attribute long mtu;
-};
diff --git a/dom/system/gonk/nsINetworkInterfaceListService.idl b/dom/system/gonk/nsINetworkInterfaceListService.idl
deleted file mode 100644
index 0c224842e..000000000
--- a/dom/system/gonk/nsINetworkInterfaceListService.idl
+++ /dev/null
@@ -1,40 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-
-interface nsINetworkInfo;
-
-[scriptable, uuid(55779d32-1e28-4f43-af87-09d04bc3cce9)]
-interface nsINetworkInterfaceList : nsISupports
-{
- /**
- * Number of the network interfaces that is available.
- */
- long getNumberOfInterface();
-
- /**
- * Get the i-th interface info info from the list.
- * @param interfaceIndex index of interface, from 0 to number of interface - 1.
- */
- nsINetworkInfo getInterfaceInfo(in long interfaceIndex);
-};
-
-[scriptable, uuid(21d7fc8b-28c4-4a4f-a15e-1f9defbc2cec)]
-interface nsINetworkInterfaceListService : nsISupports
-{
- const long LIST_NOT_INCLUDE_MMS_INTERFACES = (1 << 0);
- const long LIST_NOT_INCLUDE_SUPL_INTERFACES = (1 << 1);
- const long LIST_NOT_INCLUDE_IMS_INTERFACES = (1 << 2);
- const long LIST_NOT_INCLUDE_DUN_INTERFACES = (1 << 3);
- const long LIST_NOT_INCLUDE_FOTA_INTERFACES = (1 << 4);
-
- /**
- * Obtain a list of network interfaces that satisfy the specified condition.
- * @param condition flags that specify the interfaces to be returned. This
- * can be OR combination of LIST_* flags, or zero to make all available
- * interfaces returned.
- */
- nsINetworkInterfaceList getDataInterfaceList(in long condition);
-};
diff --git a/dom/system/gonk/nsINetworkManager.idl b/dom/system/gonk/nsINetworkManager.idl
deleted file mode 100644
index 0da123796..000000000
--- a/dom/system/gonk/nsINetworkManager.idl
+++ /dev/null
@@ -1,135 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-
-interface nsINetworkInfo;
-interface nsINetworkInterface;
-
-/**
- * Manage network interfaces.
- */
-[scriptable, uuid(1ba9346b-53b5-4660-9dc6-58f0b258d0a6)]
-interface nsINetworkManager : nsISupports
-{
- /**
- * Register the given network interface with the network manager.
- *
- * Consumers will be notified with the 'network-interface-registered'
- * observer notification.
- *
- * Throws if there's already an interface registered with the same network id.
- *
- * @param network
- * Network interface to register.
- */
- void registerNetworkInterface(in nsINetworkInterface network);
-
- /**
- * Update the routes and DNSes according the state of the given network.
- *
- * Consumers will be notified with the 'network-connection-state-changed'
- * observer notification.
- *
- * Throws an exception if the specified network interface object isn't
- * registered.
- *
- * @param network
- * Network interface to update.
- */
- void updateNetworkInterface(in nsINetworkInterface network);
-
- /**
- * Unregister the given network interface from the network manager.
- *
- * Consumers will be notified with the 'network-interface-unregistered'
- * observer notification.
- *
- * Throws an exception if the specified network interface object isn't
- * registered.
- *
- * @param network
- * Network interface to unregister.
- */
- void unregisterNetworkInterface(in nsINetworkInterface network);
-
- /**
- * Object containing all known network information, keyed by their
- * network id. Network id is composed of a sub-id + '-' + network
- * type. For mobile network types, sub-id is 'ril' + service id; for
- * non-mobile network types, sub-id is always 'device'.
- */
- readonly attribute jsval allNetworkInfo;
-
- /**
- * Priority list of network types. An array of
- * nsINetworkInterface::NETWORK_TYPE_* constants.
- *
- * The piror position of the type indicates the higher priority. The priority
- * is used to determine route when there are multiple connected networks.
- */
- attribute jsval networkTypePriorityList;
-
- /**
- * The preferred network type. One of the
- * nsINetworkInterface::NETWORK_TYPE_* constants.
- *
- * This attribute is used for setting default route to favor
- * interfaces with given type. This can be overriden by calling
- * overrideDefaultRoute().
- */
- attribute long preferredNetworkType;
-
- /**
- * The network information of the network interface handling all network
- * traffic.
- *
- * When this changes, the 'network-active-changed' observer
- * notification is dispatched.
- */
- readonly attribute nsINetworkInfo activeNetworkInfo;
-
- /**
- * Override the default behaviour for preferredNetworkType and route
- * all network traffic through the the specified interface.
- *
- * Consumers can observe changes to the active network by subscribing to
- * the 'network-active-changed' observer notification.
- *
- * @param network
- * Network to route all network traffic to. If this is null,
- * a previous override is canceled.
- */
- long overrideActive(in nsINetworkInterface network);
-
- /**
- * Add host route to the specified network into routing table.
- *
- * @param network
- * The network information for the host to be routed to.
- * @param host
- * The host to be added.
- * The host will be resolved in advance if it's not an ip-address.
- *
- * @return a Promise
- * resolved if added; rejected, otherwise.
- */
- jsval addHostRoute(in nsINetworkInfo network,
- in DOMString host);
-
- /**
- * Remove host route to the specified network from routing table.
- *
- * @param network
- * The network information for the routing to be removed from.
- * @param host
- * The host routed to the network.
- * The host will be resolved in advance if it's not an ip-address.
- *
- * @return a Promise
- * resolved if removed; rejected, otherwise.
- */
- jsval removeHostRoute(in nsINetworkInfo network,
- in DOMString host);
-};
diff --git a/dom/system/gonk/nsINetworkService.idl b/dom/system/gonk/nsINetworkService.idl
deleted file mode 100644
index 50a468494..000000000
--- a/dom/system/gonk/nsINetworkService.idl
+++ /dev/null
@@ -1,619 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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, function, uuid(91824160-fb25-11e1-a21f-0800200c9a66)]
-interface nsIWifiTetheringCallback : nsISupports
-{
- /**
- * Callback function used to report status to WifiManager.
- *
- * @param error
- * An error message if the operation wasn't successful,
- * or `null` if it was.
- */
- void wifiTetheringEnabledChange(in jsval error);
-};
-
-[scriptable, function, uuid(9c128e68-5e4b-4626-bb88-84ec54cce5d8)]
-interface nsINetworkStatsCallback : nsISupports
-{
- void networkStatsAvailable(in boolean success,
- in unsigned long rxBytes,
- in unsigned long txBytes,
- in unsigned long long timestamp);
-};
-
-[scriptable, function, uuid(0706bfa2-ac2d-11e2-9a8d-7b6d988d4767)]
-interface nsINetworkUsageAlarmCallback : nsISupports
-{
- void networkUsageAlarmResult(in jsval error);
-};
-
-[scriptable, function, uuid(9ede8720-f8bc-11e2-b778-0800200c9a66)]
-interface nsIWifiOperationModeCallback : nsISupports
-{
- /**
- * Callback function used to report result to WifiManager.
- *
- * @param error
- * An error message if the operation wasn't successful,
- * or `null` if it was.
- */
- void wifiOperationModeResult(in jsval error);
-};
-
-[scriptable, function, uuid(097878b0-19fc-11e3-8ffd-0800200c9a66)]
-interface nsISetDhcpServerCallback : nsISupports
-{
- /**
- * Callback function used to report the DHCP server set result
- *
- * @param error
- * An error message if the operation wasn't successful,
- * or `null` if it was.
- */
- void dhcpServerResult(in jsval error);
-};
-
-[scriptable, function, uuid(32407c50-46c7-11e3-8f96-0800200c9a66)]
-interface nsIUsbTetheringCallback : nsISupports
-{
- /**
- * Callback function used to report status of enabling usb tethering.
- *
- * @param error
- * An error message if the operation wasn't successful,
- * or `null` if it was.
- */
- void usbTetheringEnabledChange(in jsval error);
-};
-
-[scriptable, function, uuid(055fd560-46ad-11e3-8f96-0800200c9a66)]
-interface nsIEnableUsbRndisCallback : nsISupports
-{
- /**
- * Callback function used to report the status of enabling/disabling usb rndis.
- *
- * @param success
- * Boolean to indicate the operation is successful or not.
- * @param enable
- * Boolean to indicate if we are enabling or disabling usb rndis.
- */
- void enableUsbRndisResult(in boolean success, in boolean enable);
-};
-
-[scriptable, function, uuid(4f08cc30-46ad-11e3-8f96-0800200c9a66)]
-interface nsIUpdateUpStreamCallback : nsISupports
-{
- /**
- * Callback function used to report the result of updating upstream.
- *
- * @param success
- * Boolean to indicate the operation is successful or not.
- * @param externalIfname
- * The external interface name.
- */
- void updateUpStreamResult(in boolean success, in DOMString externalIfname);
-};
-
-[scriptable, function, uuid(eedca6c0-1310-11e4-9191-0800200c9a66)]
-interface nsISetDnsCallback : nsISupports
-{
- /**
- * Callback function used to report the result of setting DNS server.
- *
- * @param error
- * An error message if the operation wasn't successful,
- * or `null` if it was.
- */
- void setDnsResult(in jsval error);
-};
-
-[scriptable, function, uuid(5d0e1a60-1187-11e4-9191-0800200c9a66)]
-interface nsINativeCommandCallback : nsISupports
-{
- /**
- * Callback function used to report the result of a network native command.
- *
- * @param success
- * Boolean to indicate the operation is successful or not.
- */
- void nativeCommandResult(in boolean success);
-};
-
-[scriptable, function, uuid(694abb80-1187-11e4-9191-0800200c9a66)]
-interface nsIDhcpRequestCallback : nsISupports
-{
- /**
- * Callback function used to report the result of DHCP client request.
- *
- * @param success
- * Boolean to indicate the operation is successful or not.
- *
- * @param dhcpInfo
- * An object to represent the successful DHCP request:
- *
- * - gateway_str: string
- * - dns1_str: string
- * - dns2_str: string
- * - mask_str: string
- * - server_str: string
- * - vendor_str: string
- * - lease: long
- * - mask: long
- * - ipaddr: long
- * - gateway: long
- * - dns1: long
- * - dns2: long
- * - server: long
- */
- void dhcpRequestResult(in boolean success, in jsval dhcpInfo);
-};
-
-[scriptable, function, uuid(88e3ee22-f1b3-4fa0-8a5d-793fb827c42c)]
-interface nsIGetInterfacesCallback : nsISupports
-{
- /**
- * Callback function used to return the list of existing network interfaces.
- *
- * @param success
- * Boolean to indicate the operation is successful or not.
- * @param interfaceList
- * An array of interface name.
- */
- void getInterfacesResult(in boolean success, in jsval interfaceList);
-};
-
-[scriptable, function, uuid(064e02a3-d2c0-42c5-a293-1efa84056100)]
-interface nsIGetInterfaceConfigCallback : nsISupports
-{
- /**
- * Callback function used to return the network config of a given interface.
- *
- * @param success
- * Boolean to indicate the operation is successful or not.
- * @param result
- * .ip: Ip address.
- * .prefix: mask length.
- * .link: network link properties.
- * .mac: mac address.
- */
- void getInterfaceConfigResult(in boolean success, in jsval result);
-};
-
-[scriptable, function, uuid(b370f360-6ba8-4517-a4f9-31e8f004ee91)]
-interface nsISetInterfaceConfigCallback : nsISupports
-{
- /**
- * Callback function used to set network config for a specified interface.
- *
- * @param success
- * Boolean to indicate the operation is successful or not.
- */
- void setInterfaceConfigResult(in boolean success);
-};
-
-/**
- * Provide network services.
- */
-[scriptable, uuid(e16fe98f-9f63-48fe-82ba-8d1a1b7c6a57)]
-interface nsINetworkService : nsISupports
-{
- const long MODIFY_ROUTE_ADD = 0;
- const long MODIFY_ROUTE_REMOVE = 1;
-
- /**
- * Enable or disable Wifi Tethering
- *
- * @param enabled
- * Boolean that indicates whether tethering should be enabled (true) or disabled (false).
- * @param config
- * The Wifi Tethering configuration from settings db.
- * @param callback
- * Callback function used to report status to WifiManager.
- */
- void setWifiTethering(in boolean enabled,
- in jsval config,
- in nsIWifiTetheringCallback callback);
-
- /**
- * Enable or disable DHCP server
- *
- * @param enabled
- * Boolean that indicates enabling or disabling DHCP server.
- *
- * @param config
- * Config used to enable the DHCP server. It contains
- * .startIp start of the ip lease range (string)
- * .endIp end of the ip lease range (string)
- * .serverIp ip of the DHCP server (string)
- * .maskLength the length of the subnet mask
- * .ifname the interface name
- *
- * As for disabling the DHCP server, put this value |null|.
- *
- * @param callback
- * Callback function used to report status.
- */
- void setDhcpServer(in boolean enabled,
- in jsval config,
- in nsISetDhcpServerCallback callback);
-
-
- /**
- * Retrieve network interface stats.
- *
- * @param networkName
- * Select the Network interface to request estats.
- *
- * @param callback
- * Callback to notify result and provide stats, connectionType
- * and the date when stats are retrieved
- */
- void getNetworkInterfaceStats(in DOMString networkName, in nsINetworkStatsCallback callback);
-
- /**
- * Set Alarm of usage per interface
- *
- * @param networkName
- * Select the Network interface to set an alarm.
- *
- * @param threshold
- * Amount of data that will trigger the alarm.
- *
- * @param callback
- * Callback to notify the result.
- *
- * @return false if there is no interface registered for the networkType param.
- */
- boolean setNetworkInterfaceAlarm(in DOMString networkName,
- in long long threshold,
- in nsINetworkUsageAlarmCallback callback);
-
- /**
- * Reload Wifi firmware to specific operation mode.
- *
- * @param interfaceName
- * Wifi Network interface name.
- *
- * @param mode
- * AP - Access pointer mode.
- * P2P - Peer to peer connection mode.
- * STA - Station mode.
- *
- * @param callback
- * Callback to notify Wifi firmware reload result.
- */
- void setWifiOperationMode(in DOMString interfaceName,
- in DOMString mode,
- in nsIWifiOperationModeCallback callback);
-
- /**
- * Set USB tethering.
- *
- * @param enabled
- * Boolean to indicate we are going to enable or disable usb tethering.
- * @param config
- * The usb tethering configuration.
- * @param callback
- * Callback function used to report the result enabling/disabling usb tethering.
- */
- void setUSBTethering(in boolean enabled,
- in jsval config,
- in nsIUsbTetheringCallback callback);
-
- /**
- * Reset routing table.
- *
- * @param interfaceName
- * The name of the network interface we want to remove from the routing
- * table.
- *
- * @param callback
- * Callback to notify the result of resetting routing table.
- */
- void resetRoutingTable(in DOMString interfaceName,
- in nsINativeCommandCallback callback);
-
- /**
- * Set DNS.
- *
- * @param interfaceName
- * The network interface name of the DNS we want to set.
- * @param dnsesCount
- * Number of elements in dnses.
- * @param dnses
- * Dnses to set.
- * @param gatewaysCount
- * Number of elements in gateways.
- * @param gateways
- * Gateways for the dnses, the most suitable, usually the one with the
- * same address family, will be selected for each dns.
- *
- * @param callback
- * Callback to notify the result of setting DNS server.
- */
- void setDNS(in DOMString interfaceName,
- in unsigned long dnsesCount,
- [array, size_is(dnsesCount)] in wstring dnses,
- in unsigned long gatewaysCount,
- [array, size_is(gatewaysCount)] in wstring gateways,
- in nsISetDnsCallback callback);
-
- /**
- * Set default route.
- *
- * @param interfaceName
- * The network interface name of the default route we want to set.
- * @param count
- * Number of elements in gateways.
- * @param gateways
- * Default gateways for setting default route.
- *
- * @param callback
- * Callback to notify the result of setting default route.
- */
- void setDefaultRoute(in DOMString interfaceName,
- in unsigned long count,
- [array, size_is(count)] in wstring gateways,
- in nsINativeCommandCallback callback);
-
- /**
- * Remove default route.
- *
- * @param interfaceName
- * The network interface name of the default route we want to remove.
- * @param count
- * Number of elements in gateways.
- * @param gatways
- * Default gateways for removing default route.
- *
- * @param callback
- * Callback to notify the result of removing default route.
- */
- void removeDefaultRoute(in DOMString interfaceName,
- in unsigned long count,
- [array, size_is(count)] in wstring gateways,
- in nsINativeCommandCallback callback);
-
- /**
- * Modify route.
- *
- * @param action
- * nsINetworkService.MODIFY_ROUTE_ADD to add route and
- * nsINetworkService.MODIFY_ROUTE_REMOVE to remove.
- * @param interfaceName
- * Network interface name for the output of the host route.
- * @param host
- * Host ip we want to remove route for.
- * @param prefixLength
- * The prefix length of the route we'd like to modify.
- * @param [optional] gateway
- * Gateway ip for the output of the host route.
- *
- * @return A deferred promise that resolves on success or rejects with a
- * specified reason otherwise.
- */
- jsval modifyRoute(in long action,
- in DOMString interfaceName,
- in DOMString host,
- in long prefixLength,
- [optional] in DOMString gateway);
-
- /**
- * Add route to secondary routing table.
- *
- * @param interfaceName
- * The network interface for this route.
- * @param route
- * The route info should have the following fields:
- * .ip: destination ip address
- * .prefix: destination prefix
- * .gateway: gateway ip address
- */
- void addSecondaryRoute(in DOMString interfaceName, in jsval route,
- in nsINativeCommandCallback callback);
-
- /**
- * Remove route from secondary routing table.
- *
- * @param interfaceName
- * The network interface for the route we want to remove.
- * @param route
- * The route info should have the following fields:
- * .ip: destination ip address
- * .prefix: destination prefix
- * .gateway: gateway ip address
- */
- void removeSecondaryRoute(in DOMString interfaceName, in jsval route,
- in nsINativeCommandCallback callback);
-
- /**
- * Enable or disable usb rndis.
- *
- * @param enable
- * Boolean to indicate we want enable or disable usb rndis.
- * @param callback
- * Callback function to report the result.
- */
- void enableUsbRndis(in boolean enable,
- in nsIEnableUsbRndisCallback callback);
-
- /**
- * Update upstream.
- *
- * @param previous
- * The previous internal and external interface.
- * @param current
- * The current internal and external interface.
- * @param callback
- * Callback function to report the result.
- */
- void updateUpStream(in jsval previous,
- in jsval current,
- in nsIUpdateUpStreamCallback callback);
-
- /*
- * Obtain interfaces list.
- *
- * @param callback
- * Callback function to return the result.
- */
- void getInterfaces(in nsIGetInterfacesCallback callback);
-
- /**
- * Get config of a network interface.
- *
- * @param ifname
- * Target interface.
- * @param callback
- * Callback function to report the result.
- */
- void getInterfaceConfig(in DOMString ifname, in nsIGetInterfaceConfigCallback callback);
-
- /**
- * Set config for a network interface.
- *
- * @param config
- * .ifname: Target interface.
- * .ip: Ip address.
- * .prefix: mask length.
- * .link: network link properties.
- * @param callback
- * Callback function to report the result.
- */
- void setInterfaceConfig(in jsval config, in nsISetInterfaceConfigCallback callback);
-
- /**
- * Configure a network interface.
- *
- * @param config
- * An object containing the detail that we want to configure the interface:
- *
- * - ifname: string
- * - ipaddr: long
- * - mask: long
- * - gateway: long
- * - dns1: long
- * - dns2: long
- *
- * @param callback
- * Callback to notify the result of configurating network interface.
- */
- void configureInterface(in jsval config,
- in nsINativeCommandCallback callback);
-
- /**
- * Issue a DHCP client request.
- *
- * @param networkInterface
- * The network interface which we wnat to do the DHCP request on.
- *
- * @param callback
- * Callback to notify the result of the DHCP request.
- */
- void dhcpRequest(in DOMString interfaceName,
- in nsIDhcpRequestCallback callback);
-
- /**
- * Stop Dhcp daemon.
- *
- * @param ifname
- * Target interface.
- *
- * @param callback
- * Callback to notify the result of stopping dhcp request.
- */
- void stopDhcp(in DOMString ifname,
- in nsINativeCommandCallback callback);
-
- /**
- * Enable a network interface.
- *
- * @param networkInterface
- * The network interface name which we want to enable.
- *
- * @param callback
- * Callback to notify the result of disabling network interface.
- */
- void enableInterface(in DOMString interfaceName,
- in nsINativeCommandCallback callback);
-
- /**
- * Disable a network interface.
- *
- * @param networkInterface
- * The network interface name which we want to disable.
- *
- * @param callback
- * Callback to notify the result of disabling network interface.
- */
- void disableInterface(in DOMString interfaceName,
- in nsINativeCommandCallback callback);
-
- /**
- * Reset all connections on a specified network interface.
- *
- * @param interfaceName
- * The network interface name which we want to reset.
- *
- * @param callback
- * Callback to notify the result of resetting connections.
- */
- void resetConnections(in DOMString interfaceName,
- in nsINativeCommandCallback callback);
-
- /**
- * Create network (required to call prior to any networking operation).
- *
- * @param interfaceName
- * The network interface name which we want to create network for.
- *
- * @param callback
- * Callback to notify the result of creating network.
- */
- void createNetwork(in DOMString interfaceName,
- in nsINativeCommandCallback callback);
-
- /**
- * Destroy network.
- *
- * @param interfaceName
- * The network interface name of the network we want to destroy.
- *
- * @param callback
- * Callback to notify the result of destroying network.
- */
- void destroyNetwork(in DOMString interfaceName,
- in nsINativeCommandCallback callback);
-
- /**
- * Query the netId associated with given network interface name.
- *
- * @param interfaceName
- * The network interface name which we want to query.
- *
- * @return A deferred promise that resolves with a string to indicate.
- * the queried netId on success and rejects if the interface name
- * is invalid.
- *
- */
- jsval getNetId(in DOMString interfaceName);
-
- /**
- * Set maximum transmission unit on a network interface.
- *
- * @param interfaceName
- * The name of the network interface that we want to set mtu.
- * @param mtu
- * Size of maximum tranmission unit.
- *
- * @param callback
- * Callback to notify the result of setting mtu.
- */
- void setMtu(in DOMString interfaceName, in long mtu,
- in nsINativeCommandCallback callback);
-};
diff --git a/dom/system/gonk/nsINetworkWorker.idl b/dom/system/gonk/nsINetworkWorker.idl
deleted file mode 100644
index 8fe19be69..000000000
--- a/dom/system/gonk/nsINetworkWorker.idl
+++ /dev/null
@@ -1,18 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(98e31d3b-6cad-4cab-b4b3-4afff566ea65)]
-interface nsINetworkEventListener : nsISupports {
- void onEvent(in jsval result);
-};
-
-[scriptable, uuid(f9d9c694-0aac-4f9a-98ac-7788f954239a)]
-interface nsINetworkWorker : nsISupports {
- void start(in nsINetworkEventListener listener);
- void shutdown();
- [implicit_jscontext]
- void postMessage(in jsval options);
-};
diff --git a/dom/system/gonk/nsIRadioInterfaceLayer.idl b/dom/system/gonk/nsIRadioInterfaceLayer.idl
deleted file mode 100644
index 168fe3894..000000000
--- a/dom/system/gonk/nsIRadioInterfaceLayer.idl
+++ /dev/null
@@ -1,53 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-
-interface nsIIccInfo;
-interface nsIMobileConnectionInfo;
-interface nsIMobileMessageCallback;
-
-[scriptable, function, uuid(3bc96351-53b0-47a1-a888-c74c64b60f25)]
-interface nsIRilSendWorkerMessageCallback : nsISupports
-{
- boolean handleResponse(in jsval response);
-};
-
-[scriptable, uuid(1a3ef88a-e4d1-11e4-8512-176220f2b32b)]
-interface nsIRadioInterface : nsISupports
-{
- /**
- * PDP APIs
- *
- * @param networkType
- * Mobile network type, that is, nsINetworkInterface.NETWORK_TYPE_MOBILE
- * or one of the nsINetworkInterface.NETWORK_TYPE_MOBILE_* values.
- */
- void setupDataCallByType(in long networkType);
- void deactivateDataCallByType(in long networkType);
- long getDataCallStateByType(in long networkType);
-
- void updateRILNetworkInterface();
-
- void sendWorkerMessage(in DOMString type,
- [optional] in jsval message,
- [optional] in nsIRilSendWorkerMessageCallback callback);
-};
-
-%{C++
-#define NS_RADIOINTERFACELAYER_CID \
- { 0x2d831c8d, 0x6017, 0x435b, \
- { 0xa8, 0x0c, 0xe5, 0xd4, 0x22, 0x81, 0x0c, 0xea } }
-#define NS_RADIOINTERFACELAYER_CONTRACTID "@mozilla.org/ril;1"
-%}
-
-[scriptable, uuid(09730e0d-75bb-4f21-8540-062a2eadc8ff)]
-interface nsIRadioInterfaceLayer : nsISupports
-{
- readonly attribute unsigned long numRadioInterfaces;
-
- nsIRadioInterface getRadioInterface(in unsigned long clientId);
-
- void setMicrophoneMuted(in boolean muted);
-};
diff --git a/dom/system/gonk/nsISystemWorkerManager.idl b/dom/system/gonk/nsISystemWorkerManager.idl
deleted file mode 100644
index a77e253e4..000000000
--- a/dom/system/gonk/nsISystemWorkerManager.idl
+++ /dev/null
@@ -1,16 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-
-/**
- * Information about networks that is exposed to network manager API consumers.
- */
-[scriptable, builtinclass, uuid(4984b669-0ee0-4809-ae96-3358a325a6b0)]
-interface nsISystemWorkerManager : nsISupports
-{
- [implicit_jscontext]
- void registerRilWorker(in unsigned long aClientId,
- in jsval aWorker);
-};
diff --git a/dom/system/gonk/nsITetheringService.idl b/dom/system/gonk/nsITetheringService.idl
deleted file mode 100644
index 530ab0069..000000000
--- a/dom/system/gonk/nsITetheringService.idl
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-
-interface nsINetworkInterface;
-interface nsIWifiTetheringCallback;
-
-[scriptable, uuid(779de2d3-6d29-4ee6-b069-6251839f757a)]
-interface nsITetheringService : nsISupports
-{
- const long TETHERING_STATE_INACTIVE = 0;
- const long TETHERING_STATE_WIFI = 1;
- const long TETHERING_STATE_USB = 2;
-
- /**
- * Current tethering state. One of the TETHERING_STATE_* constants.
- */
- readonly attribute long state;
-
- /**
- * Enable or disable Wifi Tethering.
- *
- * @param enabled
- * Boolean that indicates whether tethering should be enabled (true) or
- * disabled (false).
- * @param interfaceName
- * The Wifi network interface name for internal interface.
- * @param config
- * The Wifi Tethering configuration from settings db.
- * @param callback
- * Callback function used to report status to WifiManager.
- */
- void setWifiTethering(in boolean enabled,
- in DOMString interfaceName,
- in jsval config,
- in nsIWifiTetheringCallback callback);
-}; \ No newline at end of file
diff --git a/dom/system/gonk/nsIVolume.idl b/dom/system/gonk/nsIVolume.idl
deleted file mode 100644
index 60785f0a4..000000000
--- a/dom/system/gonk/nsIVolume.idl
+++ /dev/null
@@ -1,114 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-#include "nsIVolumeStat.idl"
-
-[scriptable, uuid(EE752CB8-8FD7-11E4-A602-70221D5D46B0)]
-interface nsIVolume : nsISupports
-{
- // These MUST match the states from android's system/vold/Volume.h header
- // Note: Changes made to the STATE_xxx names should also be reflected in the
- // NS_VolumeStateStr function found in Volume.cpp
- const long STATE_INIT = -1;
- const long STATE_NOMEDIA = 0;
- const long STATE_IDLE = 1;
- const long STATE_PENDING = 2;
- const long STATE_CHECKING = 3;
- const long STATE_MOUNTED = 4;
- const long STATE_UNMOUNTING = 5;
- const long STATE_FORMATTING = 6;
- const long STATE_SHARED = 7;
- const long STATE_SHAREDMNT = 8;
- const long STATE_CHECKMNT = 100;
- const long STATE_MOUNT_FAIL = 101;
-
- // The name of the volume. Often there is only one volume, called sdcard.
- // But some phones support multiple volumes.
- readonly attribute DOMString name;
-
- // The mount point is the path on the system where the volume is mounted
- // and is only valid when state == STATE_MOUNTED.
- readonly attribute DOMString mountPoint;
-
- // Reflects the current state of the volume, using STATE_xxx constants
- // from above.
- readonly attribute long state;
-
- // mountGeneration is a unique number which is used distinguish between
- // periods of time that a volume is in the mounted state. Each time a
- // volume transitions to the mounted state, the mountGeneration will
- // be different from the last time it transitioned to the mounted state.
- readonly attribute long mountGeneration;
-
- // While a volume is mounted, it can be locked, preventing it from being
- // shared with the PC. To lock a volume, acquire an MozWakeLock
- // using the name of this attribute. Note that mountLockName changes
- // every time the mountGeneration changes, so you'll need to reacquire
- // the wakelock every time the volume becomes mounted.
- readonly attribute DOMString mountLockName;
-
- // Determines if a mountlock is currently being held against this volume.
- readonly attribute boolean isMountLocked;
-
- // Determines if media is actually present or not. Note, that when an sdcard
- // is ejected, it may go through several tranistory states before finally
- // arriving at STATE_NOMEDIA. So isMediaPresent may be false even when the
- // current state isn't STATE_NOMEDIA.
- readonly attribute boolean isMediaPresent;
-
- // Determines if the volume is currently being shared. This covers off
- // more than just state == STATE_SHARED. isSharing will return true from the
- // time that the volume leaves the mounted state, until it gets back to
- // mounted, nomedia, or formatting states. This attribute is to allow
- // device storage to suppress unwanted 'unavailable' status when
- // transitioning from mounted to sharing and back again.
- readonly attribute boolean isSharing;
-
- // Determines if the volume is currently formatting. This sets true once
- // mFormatRequest == true and mState == STATE_MOUNTED, and sets false
- // once the volume has been formatted and mounted again.
- readonly attribute boolean isFormatting;
-
- readonly attribute boolean isUnmounting;
-
- nsIVolumeStat getStats();
-
- // Formats the volume in IO thread, if the volume is ready to be formatted.
- // Automounter will unmount it, format it and then mount it again.
- void format();
-
- // Mounts the volume in IO thread, if the volume is already unmounted.
- // Automounter will mount it. Otherwise Automounter will skip this.
- void mount();
-
- // Unmounts the volume in IO thread, if the volume is already mounted.
- // Automounter will unmount it. Otherwise Automounter will skip this.
- void unmount();
-
- // Whether this is a fake volume.
- readonly attribute boolean isFake;
-
- // Whether this is a removable volume
- readonly attribute boolean isRemovable;
-
- // Whether this is a hot-swappable volume
- readonly attribute boolean isHotSwappable;
-
-};
-
-%{C++
-// For use with the ObserverService
-#define NS_VOLUME_STATE_CHANGED "volume-state-changed"
-#define NS_VOLUME_REMOVED "volume-removed"
-
-namespace mozilla {
-namespace system {
-
-// Convert a state into a loggable/printable string.
-const char* NS_VolumeStateStr(int32_t aState);
-
-} // system
-} // mozilla
-%}
diff --git a/dom/system/gonk/nsIVolumeMountLock.idl b/dom/system/gonk/nsIVolumeMountLock.idl
deleted file mode 100644
index 0a9a1a5c2..000000000
--- a/dom/system/gonk/nsIVolumeMountLock.idl
+++ /dev/null
@@ -1,12 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(44449f34-5ca1-4aff-bce6-22c79263de24)]
-interface nsIVolumeMountLock : nsISupports
-{
- void unlock();
-};
-
diff --git a/dom/system/gonk/nsIVolumeService.idl b/dom/system/gonk/nsIVolumeService.idl
deleted file mode 100644
index d3752e201..000000000
--- a/dom/system/gonk/nsIVolumeService.idl
+++ /dev/null
@@ -1,36 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-#include "nsIVolume.idl"
-#include "nsIVolumeMountLock.idl"
-
-interface nsIArray;
-
-[scriptable, uuid(cfbf9880-cba5-11e4-8830-0800200c9a66)]
-interface nsIVolumeService : nsISupports
-{
- nsIVolume getVolumeByName(in DOMString volName);
- nsIVolume getVolumeByPath(in DOMString path);
- nsIVolume createOrGetVolumeByPath(in DOMString path);
-
- nsIVolumeMountLock createMountLock(in DOMString volName);
-
- nsIArray getVolumeNames();
-
- void Dump(in DOMString label);
-
- /* for test case only to simulate sdcard insertion/removal */
- void createFakeVolume(in DOMString name, in DOMString path);
- void SetFakeVolumeState(in DOMString name, in long state);
-
- /* for test case only to test removal of storage area */
- void removeFakeVolume(in DOMString name);
-};
-
-%{C++
-#define NS_VOLUMESERVICE_CID \
- {0x7c179fb7, 0x67a0, 0x43a3, {0x93, 0x37, 0x29, 0x4e, 0x03, 0x60, 0xb8, 0x58}}
-#define NS_VOLUMESERVICE_CONTRACTID "@mozilla.org/telephony/volume-service;1"
-%}
diff --git a/dom/system/gonk/nsIVolumeStat.idl b/dom/system/gonk/nsIVolumeStat.idl
deleted file mode 100644
index 1d725689d..000000000
--- a/dom/system/gonk/nsIVolumeStat.idl
+++ /dev/null
@@ -1,12 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(b4c050d0-c57a-11e1-9b21-0800200c9a66)]
-interface nsIVolumeStat : nsISupports
-{
- readonly attribute long long totalBytes;
- readonly attribute long long freeBytes;
-};
diff --git a/dom/system/gonk/nsIWorkerHolder.idl b/dom/system/gonk/nsIWorkerHolder.idl
deleted file mode 100644
index e5cc82c9e..000000000
--- a/dom/system/gonk/nsIWorkerHolder.idl
+++ /dev/null
@@ -1,11 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(c04f3102-1ce8-4d57-9c27-8aece9c2740a)]
-interface nsIWorkerHolder : nsISupports
-{
- readonly attribute jsval worker;
-};
diff --git a/dom/system/gonk/nsVolume.cpp b/dom/system/gonk/nsVolume.cpp
deleted file mode 100644
index 77a1628e4..000000000
--- a/dom/system/gonk/nsVolume.cpp
+++ /dev/null
@@ -1,467 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsVolume.h"
-
-#include "base/message_loop.h"
-#include "base/task.h"
-#include "nsIPowerManagerService.h"
-#include "nsISupportsUtils.h"
-#include "nsIVolume.h"
-#include "nsServiceManagerUtils.h"
-#include "nsThreadUtils.h"
-#include "nsVolumeStat.h"
-#include "nsXULAppAPI.h"
-#include "Volume.h"
-#include "AutoMounter.h"
-#include "VolumeManager.h"
-
-#undef VOLUME_MANAGER_LOG_TAG
-#define VOLUME_MANAGER_LOG_TAG "nsVolume"
-#include "VolumeManagerLog.h"
-
-namespace mozilla {
-namespace system {
-
-const char *
-NS_VolumeStateStr(int32_t aState)
-{
- switch (aState) {
- case nsIVolume::STATE_INIT: return "Init";
- case nsIVolume::STATE_NOMEDIA: return "NoMedia";
- case nsIVolume::STATE_IDLE: return "Idle";
- case nsIVolume::STATE_PENDING: return "Pending";
- case nsIVolume::STATE_CHECKING: return "Checking";
- case nsIVolume::STATE_MOUNTED: return "Mounted";
- case nsIVolume::STATE_UNMOUNTING: return "Unmounting";
- case nsIVolume::STATE_FORMATTING: return "Formatting";
- case nsIVolume::STATE_SHARED: return "Shared";
- case nsIVolume::STATE_SHAREDMNT: return "Shared-Mounted";
- case nsIVolume::STATE_CHECKMNT: return "Check-Mounted";
- case nsIVolume::STATE_MOUNT_FAIL: return "Mount-Fail";
- }
- return "???";
-}
-
-// While nsVolumes can only be used on the main thread, in the
-// UpdateVolumeRunnable constructor (which is called from IOThread) we
-// allocate an nsVolume which is then passed to MainThread. Since we
-// have a situation where we allocate on one thread and free on another
-// we use a thread safe AddRef implementation.
-NS_IMPL_ISUPPORTS(nsVolume, nsIVolume)
-
-nsVolume::nsVolume(const Volume* aVolume)
- : mName(NS_ConvertUTF8toUTF16(aVolume->Name())),
- mMountPoint(NS_ConvertUTF8toUTF16(aVolume->MountPoint())),
- mState(aVolume->State()),
- mMountGeneration(aVolume->MountGeneration()),
- mMountLocked(aVolume->IsMountLocked()),
- mIsFake(!aVolume->CanBeShared()),
- mIsMediaPresent(aVolume->MediaPresent()),
- mIsSharing(aVolume->IsSharing()),
- mIsFormatting(aVolume->IsFormatting()),
- mIsUnmounting(aVolume->IsUnmounting()),
- mIsRemovable(aVolume->IsRemovable()),
- mIsHotSwappable(aVolume->IsHotSwappable())
-{
-}
-
-nsVolume::nsVolume(const nsVolume* aVolume)
- : mName(aVolume->mName),
- mMountPoint(aVolume->mMountPoint),
- mState(aVolume->mState),
- mMountGeneration(aVolume->mMountGeneration),
- mMountLocked(aVolume->mMountLocked),
- mIsFake(aVolume->mIsFake),
- mIsMediaPresent(aVolume->mIsMediaPresent),
- mIsSharing(aVolume->mIsSharing),
- mIsFormatting(aVolume->mIsFormatting),
- mIsUnmounting(aVolume->mIsUnmounting),
- mIsRemovable(aVolume->mIsRemovable),
- mIsHotSwappable(aVolume->mIsHotSwappable)
-{
-}
-
-void nsVolume::Dump(const char* aLabel) const
-{
- LOG("%s: Volume: %s is %s and %s @ %s gen %d locked %d",
- aLabel,
- NameStr().get(),
- StateStr(),
- IsMediaPresent() ? "inserted" : "missing",
- MountPointStr().get(),
- MountGeneration(),
- (int)IsMountLocked());
- LOG("%s: IsSharing %s IsFormating %s IsUnmounting %s",
- aLabel,
- (IsSharing() ? "y" : "n"),
- (IsFormatting() ? "y" : "n"),
- (IsUnmounting() ? "y" : "n"));
-}
-
-bool nsVolume::Equals(nsIVolume* aVolume)
-{
- nsString volName;
- aVolume->GetName(volName);
- if (!mName.Equals(volName)) {
- return false;
- }
-
- nsString volMountPoint;
- aVolume->GetMountPoint(volMountPoint);
- if (!mMountPoint.Equals(volMountPoint)) {
- return false;
- }
-
- int32_t volState;
- aVolume->GetState(&volState);
- if (mState != volState){
- return false;
- }
-
- int32_t volMountGeneration;
- aVolume->GetMountGeneration(&volMountGeneration);
- if (mMountGeneration != volMountGeneration) {
- return false;
- }
-
- bool volIsMountLocked;
- aVolume->GetIsMountLocked(&volIsMountLocked);
- if (mMountLocked != volIsMountLocked) {
- return false;
- }
-
- bool isFake;
- aVolume->GetIsFake(&isFake);
- if (mIsFake != isFake) {
- return false;
- }
-
- bool isSharing;
- aVolume->GetIsSharing(&isSharing);
- if (mIsSharing != isSharing) {
- return false;
- }
-
- bool isFormatting;
- aVolume->GetIsFormatting(&isFormatting);
- if (mIsFormatting != isFormatting) {
- return false;
- }
-
- bool isUnmounting;
- aVolume->GetIsUnmounting(&isUnmounting);
- if (mIsUnmounting != isUnmounting) {
- return false;
- }
-
- bool isRemovable;
- aVolume->GetIsRemovable(&isRemovable);
- if (mIsRemovable != isRemovable) {
- return false;
- }
-
- bool isHotSwappable;
- aVolume->GetIsHotSwappable(&isHotSwappable);
- if (mIsHotSwappable != isHotSwappable) {
- return false;
- }
-
- return true;
-}
-
-NS_IMETHODIMP nsVolume::GetIsMediaPresent(bool* aIsMediaPresent)
-{
- *aIsMediaPresent = mIsMediaPresent;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetIsMountLocked(bool* aIsMountLocked)
-{
- *aIsMountLocked = mMountLocked;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetIsSharing(bool* aIsSharing)
-{
- *aIsSharing = mIsSharing;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetIsFormatting(bool* aIsFormatting)
-{
- *aIsFormatting = mIsFormatting;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetIsUnmounting(bool* aIsUnmounting)
-{
- *aIsUnmounting = mIsUnmounting;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetName(nsAString& aName)
-{
- aName = mName;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetMountGeneration(int32_t* aMountGeneration)
-{
- *aMountGeneration = mMountGeneration;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetMountLockName(nsAString& aMountLockName)
-{
- aMountLockName = NS_LITERAL_STRING("volume-") + Name();
- aMountLockName.AppendPrintf("-%d", mMountGeneration);
-
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetMountPoint(nsAString& aMountPoint)
-{
- aMountPoint = mMountPoint;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetState(int32_t* aState)
-{
- *aState = mState;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetStats(nsIVolumeStat **aResult)
-{
- if (mState != STATE_MOUNTED) {
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- NS_IF_ADDREF(*aResult = new nsVolumeStat(mMountPoint));
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetIsFake(bool *aIsFake)
-{
- *aIsFake = mIsFake;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetIsRemovable(bool *aIsRemovable)
-{
- *aIsRemovable = mIsRemovable;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::GetIsHotSwappable(bool *aIsHotSwappable)
-{
- *aIsHotSwappable = mIsHotSwappable;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolume::Format()
-{
- MOZ_ASSERT(XRE_IsParentProcess());
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(FormatVolumeIOThread, NameStr()));
-
- return NS_OK;
-}
-
-/* static */
-void nsVolume::FormatVolumeIOThread(const nsCString& aVolume)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
-
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- if (VolumeManager::State() != VolumeManager::VOLUMES_READY) {
- return;
- }
-
- AutoMounterFormatVolume(aVolume);
-}
-
-NS_IMETHODIMP nsVolume::Mount()
-{
- MOZ_ASSERT(XRE_IsParentProcess());
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(MountVolumeIOThread, NameStr()));
-
- return NS_OK;
-}
-
-/* static */
-void nsVolume::MountVolumeIOThread(const nsCString& aVolume)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
-
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- if (VolumeManager::State() != VolumeManager::VOLUMES_READY) {
- return;
- }
-
- AutoMounterMountVolume(aVolume);
-}
-
-NS_IMETHODIMP nsVolume::Unmount()
-{
- MOZ_ASSERT(XRE_IsParentProcess());
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(UnmountVolumeIOThread, NameStr()));
-
- return NS_OK;
-}
-
-/* static */
-void nsVolume::UnmountVolumeIOThread(const nsCString& aVolume)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
-
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- if (VolumeManager::State() != VolumeManager::VOLUMES_READY) {
- return;
- }
-
- AutoMounterUnmountVolume(aVolume);
-}
-
-void
-nsVolume::LogState() const
-{
- if (mState == nsIVolume::STATE_MOUNTED) {
- LOG("nsVolume: %s state %s @ '%s' gen %d locked %d fake %d "
- "media %d sharing %d formatting %d unmounting %d removable %d hotswappable %d",
- NameStr().get(), StateStr(), MountPointStr().get(),
- MountGeneration(), (int)IsMountLocked(), (int)IsFake(),
- (int)IsMediaPresent(), (int)IsSharing(),
- (int)IsFormatting(), (int)IsUnmounting(),
- (int)IsRemovable(), (int)IsHotSwappable());
- return;
- }
-
- LOG("nsVolume: %s state %s", NameStr().get(), StateStr());
-}
-
-void nsVolume::UpdateMountLock(nsVolume* aOldVolume)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- bool oldMountLocked = aOldVolume ? aOldVolume->mMountLocked : false;
- if (mState != nsIVolume::STATE_MOUNTED) {
- // Since we're not in the mounted state, we need to
- // forgot whatever mount generation we may have had.
- mMountGeneration = -1;
- mMountLocked = oldMountLocked;
- return;
- }
-
- int32_t oldMountGeneration = aOldVolume ? aOldVolume->mMountGeneration : -1;
- if (mMountGeneration == oldMountGeneration) {
- // No change in mount generation, nothing else to do
- mMountLocked = oldMountLocked;
- return;
- }
-
- if (!XRE_IsParentProcess()) {
- // Child processes just track the state, not maintain it.
- return;
- }
-
- // Notify the Volume on IOThread whether the volume is locked or not.
- nsCOMPtr<nsIPowerManagerService> pmService =
- do_GetService(POWERMANAGERSERVICE_CONTRACTID);
- if (!pmService) {
- return;
- }
- nsString mountLockName;
- GetMountLockName(mountLockName);
- nsString mountLockState;
- pmService->GetWakeLockState(mountLockName, mountLockState);
- UpdateMountLock(mountLockState);
-}
-
-void
-nsVolume::UpdateMountLock(const nsAString& aMountLockState)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(NS_IsMainThread());
-
- // There are 3 states, unlocked, locked-background, and locked-foreground
- // I figured it was easier to use negtive logic and compare for unlocked.
- UpdateMountLock(!aMountLockState.EqualsLiteral("unlocked"));
-}
-
-void
-nsVolume::UpdateMountLock(bool aMountLocked)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(NS_IsMainThread());
-
- if (aMountLocked == mMountLocked) {
- return;
- }
- // The locked/unlocked state changed. Tell IOThread about it.
- mMountLocked = aMountLocked;
- LogState();
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(Volume::UpdateMountLock,
- NS_LossyConvertUTF16toASCII(Name()),
- MountGeneration(), aMountLocked));
-}
-
-void
-nsVolume::SetIsFake(bool aIsFake)
-{
- mIsFake = aIsFake;
- if (mIsFake) {
- // The media is always present for fake volumes.
- mIsMediaPresent = true;
- MOZ_ASSERT(!mIsSharing);
- }
-}
-
-void
-nsVolume::SetIsRemovable(bool aIsRemovable)
-{
- mIsRemovable = aIsRemovable;
- if (!mIsRemovable) {
- mIsHotSwappable = false;
- }
-}
-
-void
-nsVolume::SetIsHotSwappable(bool aIsHotSwappable)
-{
- mIsHotSwappable = aIsHotSwappable;
- if (mIsHotSwappable) {
- mIsRemovable = true;
- }
-}
-
-void
-nsVolume::SetState(int32_t aState)
-{
- static int32_t sMountGeneration = 0;
-
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(IsFake());
-
- if (aState == mState) {
- return;
- }
-
- if (aState == nsIVolume::STATE_MOUNTED) {
- mMountGeneration = ++sMountGeneration;
- }
-
- mState = aState;
-}
-
-} // system
-} // mozilla
diff --git a/dom/system/gonk/nsVolume.h b/dom/system/gonk/nsVolume.h
deleted file mode 100644
index 88be425f6..000000000
--- a/dom/system/gonk/nsVolume.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_nsvolume_h__
-#define mozilla_system_nsvolume_h__
-
-#include "nsCOMPtr.h"
-#include "nsIVolume.h"
-#include "nsString.h"
-#include "nsTArray.h"
-
-namespace mozilla {
-namespace system {
-
-class Volume;
-
-class nsVolume : public nsIVolume
-{
-public:
- NS_DECL_THREADSAFE_ISUPPORTS
- NS_DECL_NSIVOLUME
-
- // This constructor is used by the UpdateVolumeRunnable constructor
- nsVolume(const Volume* aVolume);
-
- // This constructor is used by nsVolumeService::SetFakeVolumeState
- nsVolume(const nsVolume* aVolume);
-
- // This constructor is used by ContentChild::RecvFileSystemUpdate which is
- // used to update the volume cache maintained in the child process.
- nsVolume(const nsAString& aName, const nsAString& aMountPoint,
- const int32_t& aState, const int32_t& aMountGeneration,
- const bool& aIsMediaPresent, const bool& aIsSharing,
- const bool& aIsFormatting, const bool& aIsFake,
- const bool& aIsUnmounting, const bool& aIsRemovable,
- const bool& aIsHotSwappable)
- : mName(aName),
- mMountPoint(aMountPoint),
- mState(aState),
- mMountGeneration(aMountGeneration),
- mMountLocked(false),
- mIsFake(aIsFake),
- mIsMediaPresent(aIsMediaPresent),
- mIsSharing(aIsSharing),
- mIsFormatting(aIsFormatting),
- mIsUnmounting(aIsUnmounting),
- mIsRemovable(aIsRemovable),
- mIsHotSwappable(aIsHotSwappable)
- {
- }
-
- bool Equals(nsIVolume* aVolume);
- void UpdateMountLock(nsVolume* aOldVolume);
-
- void LogState() const;
-
- const nsString& Name() const { return mName; }
- nsCString NameStr() const { return NS_LossyConvertUTF16toASCII(mName); }
-
- void Dump(const char* aLabel) const;
-
- int32_t MountGeneration() const { return mMountGeneration; }
- bool IsMountLocked() const { return mMountLocked; }
-
- const nsString& MountPoint() const { return mMountPoint; }
- nsCString MountPointStr() const { return NS_LossyConvertUTF16toASCII(mMountPoint); }
-
- int32_t State() const { return mState; }
- const char* StateStr() const { return NS_VolumeStateStr(mState); }
-
- bool IsFake() const { return mIsFake; }
- bool IsMediaPresent() const { return mIsMediaPresent; }
- bool IsSharing() const { return mIsSharing; }
- bool IsFormatting() const { return mIsFormatting; }
- bool IsUnmounting() const { return mIsUnmounting; }
- bool IsRemovable() const { return mIsRemovable; }
- bool IsHotSwappable() const { return mIsHotSwappable; }
-
- typedef nsTArray<RefPtr<nsVolume> > Array;
-
-private:
- virtual ~nsVolume() {} // MozExternalRefCountType complains if this is non-virtual
-
- friend class nsVolumeService; // Calls the following XxxMountLock functions
- void UpdateMountLock(const nsAString& aMountLockState);
- void UpdateMountLock(bool aMountLocked);
-
- void SetIsFake(bool aIsFake);
- void SetIsRemovable(bool aIsRemovable);
- void SetIsHotSwappable(bool aIsHotSwappble);
- void SetState(int32_t aState);
- static void FormatVolumeIOThread(const nsCString& aVolume);
- static void MountVolumeIOThread(const nsCString& aVolume);
- static void UnmountVolumeIOThread(const nsCString& aVolume);
-
- nsString mName;
- nsString mMountPoint;
- int32_t mState;
- int32_t mMountGeneration;
- bool mMountLocked;
- bool mIsFake;
- bool mIsMediaPresent;
- bool mIsSharing;
- bool mIsFormatting;
- bool mIsUnmounting;
- bool mIsRemovable;
- bool mIsHotSwappable;
-};
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_nsvolume_h__
diff --git a/dom/system/gonk/nsVolumeMountLock.cpp b/dom/system/gonk/nsVolumeMountLock.cpp
deleted file mode 100644
index 288c0f689..000000000
--- a/dom/system/gonk/nsVolumeMountLock.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsVolumeMountLock.h"
-
-#include "mozilla/dom/ContentChild.h"
-#include "mozilla/Services.h"
-
-#include "nsIObserverService.h"
-#include "nsIPowerManagerService.h"
-#include "nsIVolume.h"
-#include "nsIVolumeService.h"
-#include "nsString.h"
-#include "nsXULAppAPI.h"
-
-#undef VOLUME_MANAGER_LOG_TAG
-#define VOLUME_MANAGER_LOG_TAG "nsVolumeMountLock"
-#include "VolumeManagerLog.h"
-#include "nsServiceManagerUtils.h"
-#include "mozilla/dom/power/PowerManagerService.h"
-
-using namespace mozilla::dom;
-using namespace mozilla::services;
-
-namespace mozilla {
-namespace system {
-
-NS_IMPL_ISUPPORTS(nsVolumeMountLock, nsIVolumeMountLock,
- nsIObserver, nsISupportsWeakReference)
-
-// static
-already_AddRefed<nsVolumeMountLock>
-nsVolumeMountLock::Create(const nsAString& aVolumeName)
-{
- DBG("nsVolumeMountLock::Create called");
-
- RefPtr<nsVolumeMountLock> mountLock = new nsVolumeMountLock(aVolumeName);
- nsresult rv = mountLock->Init();
- NS_ENSURE_SUCCESS(rv, nullptr);
-
- return mountLock.forget();
-}
-
-nsVolumeMountLock::nsVolumeMountLock(const nsAString& aVolumeName)
- : mVolumeName(aVolumeName),
- mVolumeGeneration(-1),
- mUnlocked(false)
-{
-}
-
-//virtual
-nsVolumeMountLock::~nsVolumeMountLock()
-{
- Unlock();
-}
-
-nsresult nsVolumeMountLock::Init()
-{
- LOG("nsVolumeMountLock created for '%s'",
- NS_LossyConvertUTF16toASCII(mVolumeName).get());
-
- // Add ourselves as an Observer. It's important that we use a weak
- // reference here. If we used a strong reference, then that reference
- // would prevent this object from being destructed.
- nsCOMPtr<nsIObserverService> obs = GetObserverService();
- obs->AddObserver(this, NS_VOLUME_STATE_CHANGED, true /*weak*/);
-
- // Get the initial mountGeneration and grab a lock.
- nsCOMPtr<nsIVolumeService> vs = do_GetService(NS_VOLUMESERVICE_CONTRACTID);
- NS_ENSURE_TRUE(vs, NS_ERROR_FAILURE);
-
- nsCOMPtr<nsIVolume> vol;
- nsresult rv = vs->GetVolumeByName(mVolumeName, getter_AddRefs(vol));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
- rv = vol->GetMountGeneration(&mVolumeGeneration);
- NS_ENSURE_SUCCESS(rv, rv);
-
- return Lock(vol);
-}
-
-NS_IMETHODIMP nsVolumeMountLock::Unlock()
-{
- LOG("nsVolumeMountLock released for '%s'",
- NS_LossyConvertUTF16toASCII(mVolumeName).get());
-
- mUnlocked = true;
- mWakeLock = nullptr;
-
- // While we don't really need to remove weak observers, we do so anyways
- // since it will reduce the number of times Observe gets called.
- nsCOMPtr<nsIObserverService> obs = GetObserverService();
- obs->RemoveObserver(this, NS_VOLUME_STATE_CHANGED);
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolumeMountLock::Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData)
-{
- if (strcmp(aTopic, NS_VOLUME_STATE_CHANGED) != 0) {
- return NS_OK;
- }
- if (mUnlocked) {
- // We're not locked anymore, so we don't need to look at the notifications.
- return NS_OK;
- }
-
- nsCOMPtr<nsIVolume> vol = do_QueryInterface(aSubject);
- if (!vol) {
- return NS_OK;
- }
- nsString volName;
- vol->GetName(volName);
- if (!volName.Equals(mVolumeName)) {
- return NS_OK;
- }
- int32_t state;
- nsresult rv = vol->GetState(&state);
- NS_ENSURE_SUCCESS(rv, rv);
-
- if (state != nsIVolume::STATE_MOUNTED) {
- mWakeLock = nullptr;
- mVolumeGeneration = -1;
- return NS_OK;
- }
-
- int32_t mountGeneration;
- rv = vol->GetMountGeneration(&mountGeneration);
- NS_ENSURE_SUCCESS(rv, rv);
-
- DBG("nsVolumeMountLock::Observe mountGeneration = %d mVolumeGeneration = %d",
- mountGeneration, mVolumeGeneration);
-
- if (mVolumeGeneration == mountGeneration) {
- return NS_OK;
- }
-
- // The generation changed, which means that any wakelock we may have
- // been holding is now invalid. Grab a new wakelock for the new generation
- // number.
-
- mWakeLock = nullptr;
- mVolumeGeneration = mountGeneration;
-
- return Lock(vol);
-}
-
-nsresult
-nsVolumeMountLock::Lock(nsIVolume* aVolume)
-{
- RefPtr<power::PowerManagerService> pmService =
- power::PowerManagerService::GetInstance();
- NS_ENSURE_TRUE(pmService, NS_ERROR_FAILURE);
-
- nsString mountLockName;
- aVolume->GetMountLockName(mountLockName);
-
- ErrorResult err;
- mWakeLock = pmService->NewWakeLock(mountLockName, nullptr, err);
- if (err.Failed()) {
- return err.StealNSResult();
- }
-
- LOG("nsVolumeMountLock acquired for '%s' gen %d",
- NS_LossyConvertUTF16toASCII(mVolumeName).get(), mVolumeGeneration);
- return NS_OK;
-}
-
-} // namespace system
-} // namespace mozilla
diff --git a/dom/system/gonk/nsVolumeMountLock.h b/dom/system/gonk/nsVolumeMountLock.h
deleted file mode 100644
index caf5b2ad5..000000000
--- a/dom/system/gonk/nsVolumeMountLock.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_nsvolumemountlock_h__
-#define mozilla_system_nsvolumemountlock_h__
-
-#include "nsIVolumeMountLock.h"
-
-#include "mozilla/dom/WakeLock.h"
-#include "nsIObserver.h"
-#include "nsString.h"
-#include "nsTArray.h"
-#include "nsWeakReference.h"
-
-class nsIVolume;
-
-namespace mozilla {
-namespace system {
-
-/* The VolumeMountLock is designed so that it can be used in the Child or
- * Parent process. While the VolumeMountLock object exists, then the
- * VolumeManager/AutoMounter will prevent a mounted volume from being
- * shared with the PC.
- */
-
-class nsVolumeMountLock final : public nsIVolumeMountLock,
- public nsIObserver,
- public nsSupportsWeakReference
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIOBSERVER
- NS_DECL_NSIVOLUMEMOUNTLOCK
-
- static already_AddRefed<nsVolumeMountLock> Create(const nsAString& volumeName);
-
- const nsString& VolumeName() const { return mVolumeName; }
-
-private:
- nsVolumeMountLock(const nsAString& aVolumeName);
- ~nsVolumeMountLock();
-
- nsresult Init();
- nsresult Lock(nsIVolume* aVolume);
-
- RefPtr<dom::WakeLock> mWakeLock;
- nsString mVolumeName;
- int32_t mVolumeGeneration;
- bool mUnlocked;
-};
-
-} // namespace system
-} // namespace mozilla
-
-#endif // mozilla_system_nsvolumemountlock_h__
diff --git a/dom/system/gonk/nsVolumeService.cpp b/dom/system/gonk/nsVolumeService.cpp
deleted file mode 100644
index 48d95c26a..000000000
--- a/dom/system/gonk/nsVolumeService.cpp
+++ /dev/null
@@ -1,553 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsVolumeService.h"
-
-#include "Volume.h"
-#include "VolumeManager.h"
-#include "VolumeServiceIOThread.h"
-
-#include "nsCOMPtr.h"
-#include "nsDependentSubstring.h"
-#include "nsIDOMWakeLockListener.h"
-#include "nsIMutableArray.h"
-#include "nsIObserver.h"
-#include "nsIObserverService.h"
-#include "nsIPowerManagerService.h"
-#include "nsISupportsPrimitives.h"
-#include "nsISupportsUtils.h"
-#include "nsIVolume.h"
-#include "nsIVolumeService.h"
-#include "nsLocalFile.h"
-#include "nsServiceManagerUtils.h"
-#include "nsString.h"
-#include "nsTArray.h"
-#include "nsThreadUtils.h"
-#include "nsVolumeMountLock.h"
-#include "nsXULAppAPI.h"
-#include "mozilla/dom/ContentChild.h"
-#include "mozilla/Services.h"
-#include "base/task.h"
-
-#undef VOLUME_MANAGER_LOG_TAG
-#define VOLUME_MANAGER_LOG_TAG "nsVolumeService"
-#include "VolumeManagerLog.h"
-
-#include <stdlib.h>
-
-using namespace mozilla::dom;
-using namespace mozilla::services;
-
-namespace mozilla {
-namespace system {
-
-NS_IMPL_ISUPPORTS(nsVolumeService,
- nsIVolumeService,
- nsIDOMMozWakeLockListener)
-
-StaticRefPtr<nsVolumeService> nsVolumeService::sSingleton;
-
-// static
-already_AddRefed<nsVolumeService>
-nsVolumeService::GetSingleton()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!sSingleton) {
- sSingleton = new nsVolumeService();
- }
- RefPtr<nsVolumeService> volumeService = sSingleton.get();
- return volumeService.forget();
-}
-
-// static
-void
-nsVolumeService::Shutdown()
-{
- if (!sSingleton) {
- return;
- }
- if (!XRE_IsParentProcess()) {
- sSingleton = nullptr;
- return;
- }
-
- nsCOMPtr<nsIPowerManagerService> pmService =
- do_GetService(POWERMANAGERSERVICE_CONTRACTID);
- if (pmService) {
- pmService->RemoveWakeLockListener(sSingleton.get());
- }
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(ShutdownVolumeServiceIOThread));
-
- sSingleton = nullptr;
-}
-
-nsVolumeService::nsVolumeService()
- : mArrayMonitor("nsVolumeServiceArray"),
- mGotVolumesFromParent(false)
-{
- sSingleton = this;
-
- if (!XRE_IsParentProcess()) {
- // VolumeServiceIOThread and the WakeLock listener should only run in the
- // parent, so we return early.
- return;
- }
-
- // Startup the IOThread side of things. The actual volume changes
- // are captured by the IOThread and forwarded to main thread.
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(InitVolumeServiceIOThread, this));
-
- nsCOMPtr<nsIPowerManagerService> pmService =
- do_GetService(POWERMANAGERSERVICE_CONTRACTID);
- if (!pmService) {
- return;
- }
- pmService->AddWakeLockListener(this);
-}
-
-nsVolumeService::~nsVolumeService()
-{
-}
-
-// Callback for nsIDOMMozWakeLockListener
-NS_IMETHODIMP
-nsVolumeService::Callback(const nsAString& aTopic, const nsAString& aState)
-{
- CheckMountLock(aTopic, aState);
- return NS_OK;
-}
-
-void nsVolumeService::DumpNoLock(const char* aLabel)
-{
- mArrayMonitor.AssertCurrentThreadOwns();
-
- nsVolume::Array::size_type numVolumes = mVolumeArray.Length();
-
- if (numVolumes == 0) {
- LOG("%s: No Volumes!", aLabel);
- return;
- }
- nsVolume::Array::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<nsVolume> vol = mVolumeArray[volIndex];
- vol->Dump(aLabel);
- }
-}
-
-NS_IMETHODIMP
-nsVolumeService::Dump(const nsAString& aLabel)
-{
- MonitorAutoLock autoLock(mArrayMonitor);
- DumpNoLock(NS_LossyConvertUTF16toASCII(aLabel).get());
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolumeService::GetVolumeByName(const nsAString& aVolName, nsIVolume **aResult)
-{
- MonitorAutoLock autoLock(mArrayMonitor);
-
- RefPtr<nsVolume> vol = FindVolumeByName(aVolName);
- if (!vol) {
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- vol.forget(aResult);
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsVolumeService::GetVolumeByPath(const nsAString& aPath, nsIVolume **aResult)
-{
- NS_ConvertUTF16toUTF8 utf8Path(aPath);
- char realPathBuf[PATH_MAX];
-
- while (realpath(utf8Path.get(), realPathBuf) < 0) {
- if (errno != ENOENT) {
- ERR("GetVolumeByPath: realpath on '%s' failed: %d", utf8Path.get(), errno);
- return NSRESULT_FOR_ERRNO();
- }
- // The pathname we were passed doesn't exist, so we try stripping off trailing
- // components until we get a successful call to realpath, or until we run out
- // of components (if we finally get to /something then we also stop).
- int32_t slashIndex = utf8Path.RFindChar('/');
- if ((slashIndex == kNotFound) || (slashIndex == 0)) {
- errno = ENOENT;
- ERR("GetVolumeByPath: realpath on '%s' failed.", utf8Path.get());
- return NSRESULT_FOR_ERRNO();
- }
- utf8Path.Assign(Substring(utf8Path, 0, slashIndex));
- }
-
- // The volume mount point is always a directory. Something like /mnt/sdcard
- // Once we have a full qualified pathname with symlinks removed (which is
- // what realpath does), we basically check if aPath starts with the mount
- // point, but we don't want to have /mnt/sdcard match /mnt/sdcardfoo but we
- // do want it to match /mnt/sdcard/foo
- // So we add a trailing slash to the mount point and the pathname passed in
- // prior to doing the comparison.
-
- strlcat(realPathBuf, "/", sizeof(realPathBuf));
-
- MonitorAutoLock autoLock(mArrayMonitor);
-
- nsVolume::Array::size_type numVolumes = mVolumeArray.Length();
- nsVolume::Array::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<nsVolume> vol = mVolumeArray[volIndex];
- NS_ConvertUTF16toUTF8 volMountPointSlash(vol->MountPoint());
- volMountPointSlash.Append('/');
- nsDependentCSubstring testStr(realPathBuf, volMountPointSlash.Length());
- if (volMountPointSlash.Equals(testStr)) {
- vol.forget(aResult);
- return NS_OK;
- }
- }
- return NS_ERROR_FILE_NOT_FOUND;
-}
-
-NS_IMETHODIMP
-nsVolumeService::CreateOrGetVolumeByPath(const nsAString& aPath, nsIVolume** aResult)
-{
- nsresult rv = GetVolumeByPath(aPath, aResult);
- if (rv == NS_OK) {
- return NS_OK;
- }
-
- // In order to support queries by the updater, we will fabricate a volume
- // from the pathname, so that the caller can determine the volume size.
- nsCOMPtr<nsIVolume> vol = new nsVolume(NS_LITERAL_STRING("fake"),
- aPath, nsIVolume::STATE_MOUNTED,
- -1 /* generation */,
- true /* isMediaPresent*/,
- false /* isSharing */,
- false /* isFormatting */,
- true /* isFake */,
- false /* isUnmounting */,
- false /* isRemovable */,
- false /* isHotSwappable*/);
- vol.forget(aResult);
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsVolumeService::GetVolumeNames(nsIArray** aVolNames)
-{
- NS_ENSURE_ARG_POINTER(aVolNames);
- MonitorAutoLock autoLock(mArrayMonitor);
-
- *aVolNames = nullptr;
-
- nsresult rv;
- nsCOMPtr<nsIMutableArray> volNames =
- do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
- NS_ENSURE_SUCCESS(rv, rv);
-
- nsVolume::Array::size_type numVolumes = mVolumeArray.Length();
- nsVolume::Array::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<nsVolume> vol = mVolumeArray[volIndex];
- nsCOMPtr<nsISupportsString> isupportsString =
- do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv);
- NS_ENSURE_SUCCESS(rv, rv);
-
- rv = isupportsString->SetData(vol->Name());
- NS_ENSURE_SUCCESS(rv, rv);
-
- rv = volNames->AppendElement(isupportsString, false);
- NS_ENSURE_SUCCESS(rv, rv);
- }
-
- volNames.forget(aVolNames);
- return NS_OK;
-}
-
-void
-nsVolumeService::GetVolumesForIPC(nsTArray<VolumeInfo>* aResult)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(NS_IsMainThread());
-
- MonitorAutoLock autoLock(mArrayMonitor);
-
- nsVolume::Array::size_type numVolumes = mVolumeArray.Length();
- nsVolume::Array::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<nsVolume> vol = mVolumeArray[volIndex];
- VolumeInfo* volInfo = aResult->AppendElement();
-
- volInfo->name() = vol->mName;
- volInfo->mountPoint() = vol->mMountPoint;
- volInfo->volState() = vol->mState;
- volInfo->mountGeneration() = vol->mMountGeneration;
- volInfo->isMediaPresent() = vol->mIsMediaPresent;
- volInfo->isSharing() = vol->mIsSharing;
- volInfo->isFormatting() = vol->mIsFormatting;
- volInfo->isFake() = vol->mIsFake;
- volInfo->isUnmounting() = vol->mIsUnmounting;
- volInfo->isRemovable() = vol->mIsRemovable;
- volInfo->isHotSwappable() = vol->mIsHotSwappable;
- }
-}
-
-void
-nsVolumeService::RecvVolumesFromParent(const nsTArray<VolumeInfo>& aVolumes)
-{
- if (XRE_IsParentProcess()) {
- // We are the parent. Therefore our volumes are already correct.
- return;
- }
- if (mGotVolumesFromParent) {
- // We've already done this, no need to do it again.
- return;
- }
-
- for (uint32_t i = 0; i < aVolumes.Length(); i++) {
- const VolumeInfo& volInfo(aVolumes[i]);
- RefPtr<nsVolume> vol = new nsVolume(volInfo.name(),
- volInfo.mountPoint(),
- volInfo.volState(),
- volInfo.mountGeneration(),
- volInfo.isMediaPresent(),
- volInfo.isSharing(),
- volInfo.isFormatting(),
- volInfo.isFake(),
- volInfo.isUnmounting(),
- volInfo.isRemovable(),
- volInfo.isHotSwappable());
- UpdateVolume(vol, false);
- }
-}
-
-NS_IMETHODIMP
-nsVolumeService::CreateMountLock(const nsAString& aVolumeName, nsIVolumeMountLock **aResult)
-{
- nsCOMPtr<nsIVolumeMountLock> mountLock = nsVolumeMountLock::Create(aVolumeName);
- if (!mountLock) {
- return NS_ERROR_NOT_AVAILABLE;
- }
- mountLock.forget(aResult);
- return NS_OK;
-}
-
-void
-nsVolumeService::CheckMountLock(const nsAString& aMountLockName,
- const nsAString& aMountLockState)
-{
- MOZ_ASSERT(XRE_IsParentProcess());
- MOZ_ASSERT(NS_IsMainThread());
-
- RefPtr<nsVolume> vol = FindVolumeByMountLockName(aMountLockName);
- if (vol) {
- vol->UpdateMountLock(aMountLockState);
- }
-}
-
-already_AddRefed<nsVolume>
-nsVolumeService::FindVolumeByMountLockName(const nsAString& aMountLockName)
-{
- MonitorAutoLock autoLock(mArrayMonitor);
-
- nsVolume::Array::size_type numVolumes = mVolumeArray.Length();
- nsVolume::Array::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<nsVolume> vol = mVolumeArray[volIndex];
- nsString mountLockName;
- vol->GetMountLockName(mountLockName);
- if (mountLockName.Equals(aMountLockName)) {
- return vol.forget();
- }
- }
- return nullptr;
-}
-
-already_AddRefed<nsVolume>
-nsVolumeService::FindVolumeByName(const nsAString& aName, nsVolume::Array::index_type* aIndex)
-{
- mArrayMonitor.AssertCurrentThreadOwns();
-
- nsVolume::Array::size_type numVolumes = mVolumeArray.Length();
- nsVolume::Array::index_type volIndex;
- for (volIndex = 0; volIndex < numVolumes; volIndex++) {
- RefPtr<nsVolume> vol = mVolumeArray[volIndex];
- if (vol->Name().Equals(aName)) {
- if (aIndex) {
- *aIndex = volIndex;
- }
- return vol.forget();
- }
- }
- return nullptr;
-}
-
-void
-nsVolumeService::UpdateVolume(nsVolume* aVolume, bool aNotifyObservers)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- {
- MonitorAutoLock autoLock(mArrayMonitor);
- nsVolume::Array::index_type volIndex;
- RefPtr<nsVolume> vol = FindVolumeByName(aVolume->Name(), &volIndex);
- if (!vol) {
- mVolumeArray.AppendElement(aVolume);
- } else if (vol->Equals(aVolume) || (!vol->IsFake() && aVolume->IsFake())) {
- // Ignore if nothing changed or if a fake tries to override a real volume.
- return;
- } else {
- mVolumeArray.ReplaceElementAt(volIndex, aVolume);
- }
- aVolume->UpdateMountLock(vol);
- }
-
- if (!aNotifyObservers) {
- return;
- }
-
- nsCOMPtr<nsIObserverService> obs = GetObserverService();
- if (!obs) {
- return;
- }
- NS_ConvertUTF8toUTF16 stateStr(aVolume->StateStr());
- obs->NotifyObservers(aVolume, NS_VOLUME_STATE_CHANGED, stateStr.get());
-}
-
-NS_IMETHODIMP
-nsVolumeService::CreateFakeVolume(const nsAString& name, const nsAString& path)
-{
- if (XRE_IsParentProcess()) {
- RefPtr<nsVolume> vol = new nsVolume(name, path, nsIVolume::STATE_INIT,
- -1 /* mountGeneration */,
- true /* isMediaPresent */,
- false /* isSharing */,
- false /* isFormatting */,
- true /* isFake */,
- false /* isUnmounting */,
- false /* isRemovable */,
- false /* isHotSwappable */);
- vol->SetState(nsIVolume::STATE_MOUNTED);
- vol->LogState();
- UpdateVolume(vol.get());
- return NS_OK;
- }
-
- ContentChild::GetSingleton()->SendCreateFakeVolume(nsString(name), nsString(path));
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsVolumeService::SetFakeVolumeState(const nsAString& name, int32_t state)
-{
- if (XRE_IsParentProcess()) {
- RefPtr<nsVolume> vol;
- {
- MonitorAutoLock autoLock(mArrayMonitor);
- vol = FindVolumeByName(name);
- }
- if (!vol || !vol->IsFake()) {
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- // Clone the existing volume so we can replace it
- RefPtr<nsVolume> volume = new nsVolume(vol);
- volume->SetState(state);
- volume->LogState();
- UpdateVolume(volume.get());
- return NS_OK;
- }
-
- ContentChild::GetSingleton()->SendSetFakeVolumeState(nsString(name), state);
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsVolumeService::RemoveFakeVolume(const nsAString& name)
-{
- if (XRE_IsParentProcess()) {
- SetFakeVolumeState(name, nsIVolume::STATE_NOMEDIA);
- RemoveVolumeByName(name);
- return NS_OK;
- }
-
- ContentChild::GetSingleton()->SendRemoveFakeVolume(nsString(name));
- return NS_OK;
-}
-
-void
-nsVolumeService::RemoveVolumeByName(const nsAString& aName)
-{
- {
- MonitorAutoLock autoLock(mArrayMonitor);
- nsVolume::Array::index_type volIndex;
- RefPtr<nsVolume> vol = FindVolumeByName(aName, &volIndex);
- if (!vol) {
- return;
- }
- mVolumeArray.RemoveElementAt(volIndex);
- }
-
- if (XRE_IsParentProcess()) {
- nsCOMPtr<nsIObserverService> obs = GetObserverService();
- if (!obs) {
- return;
- }
- obs->NotifyObservers(nullptr, NS_VOLUME_REMOVED, nsString(aName).get());
- }
-}
-
-/***************************************************************************
-* The UpdateVolumeRunnable creates an nsVolume and updates the main thread
-* data structure while running on the main thread.
-*/
-class UpdateVolumeRunnable : public Runnable
-{
-public:
- UpdateVolumeRunnable(nsVolumeService* aVolumeService, const Volume* aVolume)
- : mVolumeService(aVolumeService),
- mVolume(new nsVolume(aVolume))
- {
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
- DBG("UpdateVolumeRunnable::Run '%s' state %s gen %d locked %d "
- "media %d sharing %d formatting %d unmounting %d removable %d hotswappable %d",
- mVolume->NameStr().get(), mVolume->StateStr(),
- mVolume->MountGeneration(), (int)mVolume->IsMountLocked(),
- (int)mVolume->IsMediaPresent(), mVolume->IsSharing(),
- mVolume->IsFormatting(), mVolume->IsUnmounting(),
- (int)mVolume->IsRemovable(), (int)mVolume->IsHotSwappable());
-
- mVolumeService->UpdateVolume(mVolume);
- mVolumeService = nullptr;
- mVolume = nullptr;
- return NS_OK;
- }
-
-private:
- RefPtr<nsVolumeService> mVolumeService;
- RefPtr<nsVolume> mVolume;
-};
-
-void
-nsVolumeService::UpdateVolumeIOThread(const Volume* aVolume)
-{
- DBG("UpdateVolumeIOThread: Volume '%s' state %s mount '%s' gen %d locked %d "
- "media %d sharing %d formatting %d unmounting %d removable %d hotswappable %d",
- aVolume->NameStr(), aVolume->StateStr(), aVolume->MountPoint().get(),
- aVolume->MountGeneration(), (int)aVolume->IsMountLocked(),
- (int)aVolume->MediaPresent(), (int)aVolume->IsSharing(),
- (int)aVolume->IsFormatting(), (int)aVolume->IsUnmounting(),
- (int)aVolume->IsRemovable(), (int)aVolume->IsHotSwappable());
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- NS_DispatchToMainThread(new UpdateVolumeRunnable(this, aVolume));
-}
-
-} // namespace system
-} // namespace mozilla
diff --git a/dom/system/gonk/nsVolumeService.h b/dom/system/gonk/nsVolumeService.h
deleted file mode 100644
index 9bddc0b8f..000000000
--- a/dom/system/gonk/nsVolumeService.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_nsvolumeservice_h__
-#define mozilla_system_nsvolumeservice_h__
-
-#include "mozilla/Monitor.h"
-#include "mozilla/RefPtr.h"
-#include "mozilla/StaticPtr.h"
-#include "nsCOMPtr.h"
-#include "nsIDOMWakeLockListener.h"
-#include "nsIVolume.h"
-#include "nsIVolumeService.h"
-#include "nsVolume.h"
-
-namespace mozilla {
-
-namespace dom {
-class VolumeInfo;
-} // dom
-
-namespace system {
-
-class Volume;
-
-/***************************************************************************
-* The nsVolumeData class encapsulates the data that is updated/maintained
-* on the main thread in order to support the nsIVolume and nsIVolumeService
-* classes.
-*/
-
-class nsVolumeService final : public nsIVolumeService,
- public nsIDOMMozWakeLockListener
-{
-public:
- NS_DECL_THREADSAFE_ISUPPORTS
- NS_DECL_NSIVOLUMESERVICE
- NS_DECL_NSIDOMMOZWAKELOCKLISTENER
-
- nsVolumeService();
-
- static already_AddRefed<nsVolumeService> GetSingleton();
- //static nsVolumeService* GetSingleton();
- static void Shutdown();
-
- void DumpNoLock(const char* aLabel);
-
- // To use this function, you have to create a new volume and pass it in.
- void UpdateVolume(nsVolume* aVolume, bool aNotifyObservers = true);
- void UpdateVolumeIOThread(const Volume* aVolume);
-
- void RecvVolumesFromParent(const nsTArray<dom::VolumeInfo>& aVolumes);
- void GetVolumesForIPC(nsTArray<dom::VolumeInfo>* aResult);
-
- void RemoveVolumeByName(const nsAString& aName);
-
-private:
- ~nsVolumeService();
-
- void CheckMountLock(const nsAString& aMountLockName,
- const nsAString& aMountLockState);
- already_AddRefed<nsVolume> FindVolumeByMountLockName(const nsAString& aMountLockName);
-
- already_AddRefed<nsVolume> FindVolumeByName(const nsAString& aName,
- nsVolume::Array::index_type* aIndex = nullptr);
-
- Monitor mArrayMonitor;
- nsVolume::Array mVolumeArray;
-
- static StaticRefPtr<nsVolumeService> sSingleton;
- bool mGotVolumesFromParent;
-};
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_nsvolumeservice_h__
diff --git a/dom/system/gonk/nsVolumeStat.cpp b/dom/system/gonk/nsVolumeStat.cpp
deleted file mode 100644
index 11976237f..000000000
--- a/dom/system/gonk/nsVolumeStat.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsVolumeStat.h"
-#include "nsString.h"
-
-namespace mozilla {
-namespace system {
-
-NS_IMPL_ISUPPORTS(nsVolumeStat, nsIVolumeStat)
-
-nsVolumeStat::nsVolumeStat(const nsAString& aPath)
-{
- if (statfs(NS_ConvertUTF16toUTF8(aPath).get(), &mStat) != 0) {
- memset(&mStat, 0, sizeof(mStat));
- }
-}
-
-NS_IMETHODIMP nsVolumeStat::GetTotalBytes(int64_t* aTotalBytes)
-{
- *aTotalBytes = mStat.f_blocks * mStat.f_bsize;
- return NS_OK;
-}
-
-NS_IMETHODIMP nsVolumeStat::GetFreeBytes(int64_t* aFreeBytes)
-{
- *aFreeBytes = mStat.f_bfree * mStat.f_bsize;
- return NS_OK;
-}
-
-} // system
-} // mozilla
diff --git a/dom/system/gonk/nsVolumeStat.h b/dom/system/gonk/nsVolumeStat.h
deleted file mode 100644
index 2ca03ed46..000000000
--- a/dom/system/gonk/nsVolumeStat.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_nsvolumestat_h__
-#define mozilla_system_nsvolumestat_h__
-
-#include "nsIVolumeStat.h"
-#include "nsString.h"
-#include <sys/statfs.h>
-
-namespace mozilla {
-namespace system {
-
-class nsVolumeStat final : public nsIVolumeStat
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIVOLUMESTAT
-
- nsVolumeStat(const nsAString& aPath);
-
-protected:
- ~nsVolumeStat() {}
-
-private:
- struct statfs mStat;
-};
-
-} // system
-} // mozilla
-
-#endif // mozilla_system_nsvolumestat_h__
diff --git a/dom/system/gonk/ril_consts.js b/dom/system/gonk/ril_consts.js
deleted file mode 100644
index af5b9d8e1..000000000
--- a/dom/system/gonk/ril_consts.js
+++ /dev/null
@@ -1,3338 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// Set to true to debug all RIL layers
-this.DEBUG_ALL = false;
-
-// Set individually to debug specific layers
-this.DEBUG_WORKER = false || DEBUG_ALL;
-this.DEBUG_CONTENT_HELPER = false || DEBUG_ALL;
-this.DEBUG_RIL = false || DEBUG_ALL;
-
-this.REQUEST_GET_SIM_STATUS = 1;
-this.REQUEST_ENTER_SIM_PIN = 2;
-this.REQUEST_ENTER_SIM_PUK = 3;
-this.REQUEST_ENTER_SIM_PIN2 = 4;
-this.REQUEST_ENTER_SIM_PUK2 = 5;
-this.REQUEST_CHANGE_SIM_PIN = 6;
-this.REQUEST_CHANGE_SIM_PIN2 = 7;
-this.REQUEST_ENTER_NETWORK_DEPERSONALIZATION_CODE = 8;
-this.REQUEST_GET_CURRENT_CALLS = 9;
-this.REQUEST_DIAL = 10;
-this.REQUEST_GET_IMSI = 11;
-this.REQUEST_HANGUP = 12;
-this.REQUEST_HANGUP_WAITING_OR_BACKGROUND = 13;
-this.REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND = 14;
-this.REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE = 15;
-this.REQUEST_CONFERENCE = 16;
-this.REQUEST_UDUB = 17;
-this.REQUEST_LAST_CALL_FAIL_CAUSE = 18;
-this.REQUEST_SIGNAL_STRENGTH = 19;
-this.REQUEST_VOICE_REGISTRATION_STATE = 20;
-this.REQUEST_DATA_REGISTRATION_STATE = 21;
-this.REQUEST_OPERATOR = 22;
-this.REQUEST_RADIO_POWER = 23;
-this.REQUEST_DTMF = 24;
-this.REQUEST_SEND_SMS = 25;
-this.REQUEST_SEND_SMS_EXPECT_MORE = 26;
-this.REQUEST_SETUP_DATA_CALL = 27;
-this.REQUEST_SIM_IO = 28;
-this.REQUEST_SEND_USSD = 29;
-this.REQUEST_CANCEL_USSD = 30;
-this.REQUEST_GET_CLIR = 31;
-this.REQUEST_SET_CLIR = 32;
-this.REQUEST_QUERY_CALL_FORWARD_STATUS = 33;
-this.REQUEST_SET_CALL_FORWARD = 34;
-this.REQUEST_QUERY_CALL_WAITING = 35;
-this.REQUEST_SET_CALL_WAITING = 36;
-this.REQUEST_SMS_ACKNOWLEDGE = 37;
-this.REQUEST_GET_IMEI = 38;
-this.REQUEST_GET_IMEISV = 39;
-this.REQUEST_ANSWER = 40;
-this.REQUEST_DEACTIVATE_DATA_CALL = 41;
-this.REQUEST_QUERY_FACILITY_LOCK = 42;
-this.REQUEST_SET_FACILITY_LOCK = 43;
-this.REQUEST_CHANGE_BARRING_PASSWORD = 44;
-this.REQUEST_QUERY_NETWORK_SELECTION_MODE = 45;
-this.REQUEST_SET_NETWORK_SELECTION_AUTOMATIC = 46;
-this.REQUEST_SET_NETWORK_SELECTION_MANUAL = 47;
-this.REQUEST_QUERY_AVAILABLE_NETWORKS = 48;
-this.REQUEST_DTMF_START = 49;
-this.REQUEST_DTMF_STOP = 50;
-this.REQUEST_BASEBAND_VERSION = 51;
-this.REQUEST_SEPARATE_CONNECTION = 52;
-this.REQUEST_SET_MUTE = 53;
-this.REQUEST_GET_MUTE = 54;
-this.REQUEST_QUERY_CLIP = 55;
-this.REQUEST_LAST_DATA_CALL_FAIL_CAUSE = 56;
-this.REQUEST_DATA_CALL_LIST = 57;
-this.REQUEST_RESET_RADIO = 58;
-this.REQUEST_OEM_HOOK_RAW = 59;
-this.REQUEST_OEM_HOOK_STRINGS = 60;
-this.REQUEST_SCREEN_STATE = 61;
-this.REQUEST_SET_SUPP_SVC_NOTIFICATION = 62;
-this.REQUEST_WRITE_SMS_TO_SIM = 63;
-this.REQUEST_DELETE_SMS_ON_SIM = 64;
-this.REQUEST_SET_BAND_MODE = 65;
-this.REQUEST_QUERY_AVAILABLE_BAND_MODE = 66;
-this.REQUEST_STK_GET_PROFILE = 67;
-this.REQUEST_STK_SET_PROFILE = 68;
-this.REQUEST_STK_SEND_ENVELOPE_COMMAND = 69;
-this.REQUEST_STK_SEND_TERMINAL_RESPONSE = 70;
-this.REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM = 71;
-this.REQUEST_EXPLICIT_CALL_TRANSFER = 72;
-this.REQUEST_SET_PREFERRED_NETWORK_TYPE = 73;
-this.REQUEST_GET_PREFERRED_NETWORK_TYPE = 74;
-this.REQUEST_GET_NEIGHBORING_CELL_IDS = 75;
-this.REQUEST_SET_LOCATION_UPDATES = 76;
-this.REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE = 77;
-this.REQUEST_CDMA_SET_ROAMING_PREFERENCE = 78;
-this.REQUEST_CDMA_QUERY_ROAMING_PREFERENCE = 79;
-this.REQUEST_SET_TTY_MODE = 80;
-this.REQUEST_QUERY_TTY_MODE = 81;
-this.REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE = 82;
-this.REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE = 83;
-this.REQUEST_CDMA_FLASH = 84;
-this.REQUEST_CDMA_BURST_DTMF = 85;
-this.REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY = 86;
-this.REQUEST_CDMA_SEND_SMS = 87;
-this.REQUEST_CDMA_SMS_ACKNOWLEDGE = 88;
-this.REQUEST_GSM_GET_BROADCAST_SMS_CONFIG = 89;
-this.REQUEST_GSM_SET_BROADCAST_SMS_CONFIG = 90;
-this.REQUEST_GSM_SMS_BROADCAST_ACTIVATION = 91;
-this.REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG = 92;
-this.REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG = 93;
-this.REQUEST_CDMA_SMS_BROADCAST_ACTIVATION = 94;
-this.REQUEST_CDMA_SUBSCRIPTION = 95;
-this.REQUEST_CDMA_WRITE_SMS_TO_RUIM = 96;
-this.REQUEST_CDMA_DELETE_SMS_ON_RUIM = 97;
-this.REQUEST_DEVICE_IDENTITY = 98;
-this.REQUEST_EXIT_EMERGENCY_CALLBACK_MODE = 99;
-this.REQUEST_GET_SMSC_ADDRESS = 100;
-this.REQUEST_SET_SMSC_ADDRESS = 101;
-this.REQUEST_REPORT_SMS_MEMORY_STATUS = 102;
-this.REQUEST_REPORT_STK_SERVICE_IS_RUNNING = 103;
-this.REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE = 104;
-this.REQUEST_ISIM_AUTHENTICATION = 105;
-this.REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU = 106;
-this.REQUEST_STK_SEND_ENVELOPE_WITH_STATUS = 107;
-this.REQUEST_VOICE_RADIO_TECH = 108;
-this.REQUEST_GET_CELL_INFO_LIST = 109;
-this.REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE = 110;
-this.REQUEST_SET_INITIAL_ATTACH_APN = 111;
-this.REQUEST_IMS_REGISTRATION_STATE = 112;
-this.REQUEST_IMS_SEND_SMS = 113;
-this.REQUEST_SIM_TRANSMIT_APDU_BASIC = 114;
-this.REQUEST_SIM_OPEN_CHANNEL = 115;
-this.REQUEST_SIM_CLOSE_CHANNEL = 116;
-this.REQUEST_SIM_TRANSMIT_APDU_CHANNEL = 117;
-this.REQUEST_NV_READ_ITEM = 118;
-this.REQUEST_NV_WRITE_ITEM = 119;
-this.REQUEST_NV_WRITE_CDMA_PRL = 120;
-this.REQUEST_NV_RESET_CONFIG = 121;
-this.REQUEST_SET_UICC_SUBSCRIPTION = 122;
-this.REQUEST_ALLOW_DATA = 123;
-this.REQUEST_GET_HARDWARE_CONFIG = 124;
-this.REQUEST_SIM_AUTHENTICATION = 125;
-this.REQUEST_GET_DC_RT_INFO = 126;
-this.REQUEST_SET_DC_RT_INFO_RATE = 127;
-this.REQUEST_SET_DATA_PROFILE = 128;
-this.REQUEST_SHUTDOWN = 129;
-
-// CAF specific parcel type. It should be synced with latest version. But CAF
-// doesn't have l version for b2g yet, so we set REQUEST_SET_DATA_SUBSCRIPTION
-// to a value that won't get conflict with known AOSP parcel.
-this.REQUEST_SET_DATA_SUBSCRIPTION = 130;
-
-// Mozilla specific parcel type.
-this.REQUEST_GET_UNLOCK_RETRY_COUNT = 150;
-
-// Fugu specific parcel types.
-this.RIL_REQUEST_GPRS_ATTACH = 5018;
-this.RIL_REQUEST_GPRS_DETACH = 5019;
-
-// Galaxy S2 specific parcel type.
-this.REQUEST_DIAL_EMERGENCY_CALL = 10016;
-
-this.RESPONSE_TYPE_SOLICITED = 0;
-this.RESPONSE_TYPE_UNSOLICITED = 1;
-
-this.UNSOLICITED_RESPONSE_BASE = 1000;
-this.UNSOLICITED_RESPONSE_RADIO_STATE_CHANGED = 1000;
-this.UNSOLICITED_RESPONSE_CALL_STATE_CHANGED = 1001;
-this.UNSOLICITED_RESPONSE_VOICE_NETWORK_STATE_CHANGED = 1002;
-this.UNSOLICITED_RESPONSE_NEW_SMS = 1003;
-this.UNSOLICITED_RESPONSE_NEW_SMS_STATUS_REPORT = 1004;
-this.UNSOLICITED_RESPONSE_NEW_SMS_ON_SIM = 1005;
-this.UNSOLICITED_ON_USSD = 1006;
-this.UNSOLICITED_ON_USSD_REQUEST = 1007;
-this.UNSOLICITED_NITZ_TIME_RECEIVED = 1008;
-this.UNSOLICITED_SIGNAL_STRENGTH = 1009;
-this.UNSOLICITED_DATA_CALL_LIST_CHANGED = 1010;
-this.UNSOLICITED_SUPP_SVC_NOTIFICATION = 1011;
-this.UNSOLICITED_STK_SESSION_END = 1012;
-this.UNSOLICITED_STK_PROACTIVE_COMMAND = 1013;
-this.UNSOLICITED_STK_EVENT_NOTIFY = 1014;
-this.UNSOLICITED_STK_CALL_SETUP = 1015;
-this.UNSOLICITED_SIM_SMS_STORAGE_FULL = 1016;
-this.UNSOLICITED_SIM_REFRESH = 1017;
-this.UNSOLICITED_CALL_RING = 1018;
-this.UNSOLICITED_RESPONSE_SIM_STATUS_CHANGED = 1019;
-this.UNSOLICITED_RESPONSE_CDMA_NEW_SMS = 1020;
-this.UNSOLICITED_RESPONSE_NEW_BROADCAST_SMS = 1021;
-this.UNSOLICITED_CDMA_RUIM_SMS_STORAGE_FULL = 1022;
-this.UNSOLICITED_RESTRICTED_STATE_CHANGED = 1023;
-this.UNSOLICITED_ENTER_EMERGENCY_CALLBACK_MODE = 1024;
-this.UNSOLICITED_CDMA_CALL_WAITING = 1025;
-this.UNSOLICITED_CDMA_OTA_PROVISION_STATUS = 1026;
-this.UNSOLICITED_CDMA_INFO_REC = 1027;
-this.UNSOLICITED_OEM_HOOK_RAW = 1028;
-this.UNSOLICITED_RINGBACK_TONE = 1029;
-this.UNSOLICITED_RESEND_INCALL_MUTE = 1030;
-this.UNSOLICITED_CDMA_SUBSCRIPTION_SOURCE_CHANGED = 1031;
-this.UNSOLICITED_CDMA_PRL_CHANGED = 1032;
-this.UNSOLICITED_EXIT_EMERGENCY_CALLBACK_MODE = 1033;
-this.UNSOLICITED_RIL_CONNECTED = 1034;
-this.UNSOLICITED_VOICE_RADIO_TECH_CHANGED = 1035;
-this.UNSOLICITED_CELL_INFO_LIST = 1036;
-this.UNSOLICITED_RESPONSE_IMS_NETWORK_STATE_CHANGED = 1037;
-this.UNSOLICITED_UICC_SUBSCRIPTION_STATUS_CHANGED = 1038;
-this.UNSOLICITED_SRVCC_STATE_NOTIFY = 1039;
-this.UNSOLICITED_HARDWARE_CONFIG_CHANGED = 1040;
-this.UNSOLICITED_DC_RT_INFO_CHANGED = 1041;
-
-this.ERROR_SUCCESS = 0;
-this.ERROR_RADIO_NOT_AVAILABLE = 1;
-this.ERROR_GENERIC_FAILURE = 2;
-this.ERROR_PASSWORD_INCORRECT = 3;
-this.ERROR_SIM_PIN2 = 4;
-this.ERROR_SIM_PUK2 = 5;
-this.ERROR_REQUEST_NOT_SUPPORTED = 6;
-this.ERROR_CANCELLED = 7;
-this.ERROR_OP_NOT_ALLOWED_DURING_VOICE_CALL = 8;
-this.ERROR_OP_NOT_ALLOWED_BEFORE_REG_TO_NW = 9;
-this.ERROR_SMS_SEND_FAIL_RETRY = 10;
-this.ERROR_SIM_ABSENT = 11;
-this.ERROR_SUBSCRIPTION_NOT_AVAILABLE = 12;
-this.ERROR_MODE_NOT_SUPPORTED = 13;
-this.ERROR_FDN_CHECK_FAILURE = 14;
-this.ERROR_ILLEGAL_SIM_OR_ME = 15;
-this.ERROR_MISSING_RESOURCE = 16;
-this.ERROR_NO_SUCH_ELEMENT = 17;
-
-this.GECKO_ERROR_RADIO_NOT_AVAILABLE = "RadioNotAvailable";
-this.GECKO_ERROR_GENERIC_FAILURE = "GenericFailure";
-this.GECKO_ERROR_PASSWORD_INCORRECT = "IncorrectPassword";
-this.GECKO_ERROR_SIM_PIN2 = "SimPin2";
-this.GECKO_ERROR_SIM_PUK2 = "SimPuk2";
-this.GECKO_ERROR_REQUEST_NOT_SUPPORTED = "RequestNotSupported";
-this.GECKO_ERROR_CANCELLED = "Cancelled";
-this.GECKO_ERROR_OP_NOT_ALLOWED_DURING_VOICE_CALL = "OpNotAllowedDuringVoiceCall";
-this.GECKO_ERROR_OP_NOT_ALLOWED_BEFORE_REG_TO_NW = "OpNotAllowedBeforeRegToNw";
-this.GECKO_ERROR_SMS_SEND_FAIL_RETRY = "SmsSendFailRetry";
-this.GECKO_ERROR_SIM_ABSENT = "SimAbsent";
-this.GECKO_ERROR_SUBSCRIPTION_NOT_AVAILABLE = "SubscriptionNotAvailable";
-this.GECKO_ERROR_MODE_NOT_SUPPORTED = "ModeNotSupported";
-this.GECKO_ERROR_FDN_CHECK_FAILURE = "FdnCheckFailure";
-this.GECKO_ERROR_ILLEGAL_SIM_OR_ME = "IllegalSIMorME";
-this.GECKO_ERROR_MISSING_RESOURCE = "MissingResource";
-this.GECKO_ERROR_NO_SUCH_ELEMENT = "NoSuchElement";
-this.GECKO_ERROR_INVALID_PARAMETER = "InvalidParameter";
-this.GECKO_ERROR_UNSPECIFIED_ERROR = "UnspecifiedError";
-
-this.RIL_ERROR_TO_GECKO_ERROR = {};
-RIL_ERROR_TO_GECKO_ERROR[ERROR_RADIO_NOT_AVAILABLE] = GECKO_ERROR_RADIO_NOT_AVAILABLE;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_GENERIC_FAILURE] = GECKO_ERROR_GENERIC_FAILURE;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_PASSWORD_INCORRECT] = GECKO_ERROR_PASSWORD_INCORRECT;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_SIM_PIN2] = GECKO_ERROR_SIM_PIN2;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_SIM_PUK2] = GECKO_ERROR_SIM_PUK2;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_REQUEST_NOT_SUPPORTED] = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_CANCELLED] = GECKO_ERROR_CANCELLED;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_OP_NOT_ALLOWED_DURING_VOICE_CALL] = GECKO_ERROR_OP_NOT_ALLOWED_DURING_VOICE_CALL;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_OP_NOT_ALLOWED_BEFORE_REG_TO_NW] = GECKO_ERROR_OP_NOT_ALLOWED_BEFORE_REG_TO_NW;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_SMS_SEND_FAIL_RETRY] = GECKO_ERROR_SMS_SEND_FAIL_RETRY;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_SIM_ABSENT] = GECKO_ERROR_SIM_ABSENT;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_SUBSCRIPTION_NOT_AVAILABLE] = GECKO_ERROR_SUBSCRIPTION_NOT_AVAILABLE;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_MODE_NOT_SUPPORTED] = GECKO_ERROR_MODE_NOT_SUPPORTED;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_FDN_CHECK_FAILURE] = GECKO_ERROR_FDN_CHECK_FAILURE;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_ILLEGAL_SIM_OR_ME] = GECKO_ERROR_ILLEGAL_SIM_OR_ME;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_MISSING_RESOURCE] = GECKO_ERROR_MISSING_RESOURCE;
-RIL_ERROR_TO_GECKO_ERROR[ERROR_NO_SUCH_ELEMENT] = GECKO_ERROR_NO_SUCH_ELEMENT;
-
-// 3GPP 23.040 clause 9.2.3.6 TP-Message-Reference(TP-MR):
-// The number of times the MS automatically repeats the SMS-SUBMIT shall be in
-// the range 1 to 3 but the precise number is an implementation matter.
-this.SMS_RETRY_MAX = 3;
-
-this.RADIO_STATE_OFF = 0;
-this.RADIO_STATE_UNAVAILABLE = 1;
-this.RADIO_STATE_ON = 10; // since RIL v7
-
-this.CARD_STATE_ABSENT = 0;
-this.CARD_STATE_PRESENT = 1;
-this.CARD_STATE_ERROR = 2;
-
-this.CARD_PERSOSUBSTATE_UNKNOWN = 0;
-this.CARD_PERSOSUBSTATE_IN_PROGRESS = 1;
-this.CARD_PERSOSUBSTATE_READY = 2;
-this.CARD_PERSOSUBSTATE_SIM_NETWORK = 3;
-this.CARD_PERSOSUBSTATE_SIM_NETWORK_SUBSET = 4;
-this.CARD_PERSOSUBSTATE_SIM_CORPORATE = 5;
-this.CARD_PERSOSUBSTATE_SIM_SERVICE_PROVIDER = 6;
-this.CARD_PERSOSUBSTATE_SIM_SIM = 7;
-this.CARD_PERSOSUBSTATE_SIM_NETWORK_PUK = 8;
-this.CARD_PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK = 9;
-this.CARD_PERSOSUBSTATE_SIM_CORPORATE_PUK = 10;
-this.CARD_PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK = 11;
-this.CARD_PERSOSUBSTATE_SIM_SIM_PUK = 12;
-this.CARD_PERSOSUBSTATE_RUIM_NETWORK1 = 13;
-this.CARD_PERSOSUBSTATE_RUIM_NETWORK2 = 14;
-this.CARD_PERSOSUBSTATE_RUIM_HRPD = 15;
-this.CARD_PERSOSUBSTATE_RUIM_CORPORATE = 16;
-this.CARD_PERSOSUBSTATE_RUIM_SERVICE_PROVIDER = 17;
-this.CARD_PERSOSUBSTATE_RUIM_RUIM = 18;
-this.CARD_PERSOSUBSTATE_RUIM_NETWORK1_PUK = 19;
-this.CARD_PERSOSUBSTATE_RUIM_NETWORK2_PUK = 20;
-this.CARD_PERSOSUBSTATE_RUIM_HRPD_PUK = 21;
-this.CARD_PERSOSUBSTATE_RUIM_CORPORATE_PUK = 22;
-this.CARD_PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK = 23;
-this.CARD_PERSOSUBSTATE_RUIM_RUIM_PUK = 24;
-
-this.CARD_APPSTATE_ILLEGAL = -1;
-this.CARD_APPSTATE_UNKNOWN = 0;
-this.CARD_APPSTATE_DETECTED = 1;
-this.CARD_APPSTATE_PIN = 2; // If PIN1 or UPin is required.
-this.CARD_APPSTATE_PUK = 3; // If PUK1 or Puk for UPin is required.
-this.CARD_APPSTATE_SUBSCRIPTION_PERSO = 4; // perso_substate should be looked
- // at when app_state is assigned
- // to this value.
-this.CARD_APPSTATE_READY = 5;
-
-this.CARD_PINSTATE_UNKNOWN = 0;
-this.CARD_PINSTATE_ENABLED_NOT_VERIFIED = 1;
-this.CARD_PINSTATE_ENABLED_VERIFIED = 2;
-this.CARD_PINSTATE_DISABLED = 3;
-this.CARD_PINSTATE_ENABLED_BLOCKED = 4;
-this.CARD_PINSTATE_ENABLED_PERM_BLOCKED = 5;
-
-this.CARD_APPTYPE_UNKNOWN = 0;
-this.CARD_APPTYPE_SIM = 1;
-this.CARD_APPTYPE_USIM = 2;
-this.CARD_APPTYPE_RUIM = 3;
-this.CARD_APPTYPE_CSIM = 4;
-this.CARD_APPTYPE_ISIM = 5;
-
-this.CARD_MAX_APPS = 8;
-
-this.GECKO_CARD_TYPE = [
- null,
- "sim",
- "usim",
- "ruim",
- "csim",
- "isim"
-];
-
-
-// Used for QUERY_AVAILABLE_NETWORKS status.
-this.QAN_STATE_UNKNOWN = "unknown";
-this.QAN_STATE_AVAILABLE = "available";
-this.QAN_STATE_CURRENT = "current";
-this.QAN_STATE_FORBIDDEN = "forbidden";
-
-// Must be in sync with MobileNetworkState of MozMobileNetworkInfo.webidl
-this.GECKO_QAN_STATE_UNKNOWN = null;
-this.GECKO_QAN_STATE_AVAILABLE = "available";
-this.GECKO_QAN_STATE_CONNECTED = "connected";
-this.GECKO_QAN_STATE_FORBIDDEN = "forbidden";
-
-this.RIL_QAN_STATE_TO_GECKO_STATE = {};
-this.RIL_QAN_STATE_TO_GECKO_STATE[this.QAN_STATE_UNKNOWN] = this.GECKO_QAN_STATE_UNKNOWN;
-this.RIL_QAN_STATE_TO_GECKO_STATE[this.QAN_STATE_AVAILABLE] = this.GECKO_QAN_STATE_AVAILABLE;
-this.RIL_QAN_STATE_TO_GECKO_STATE[this.QAN_STATE_CURRENT] = this.GECKO_QAN_STATE_CONNECTED;
-this.RIL_QAN_STATE_TO_GECKO_STATE[this.QAN_STATE_FORBIDDEN] = this.GECKO_QAN_STATE_FORBIDDEN;
-
-this.NETWORK_SELECTION_MODE_AUTOMATIC = 0;
-this.NETWORK_SELECTION_MODE_MANUAL = 1;
-
-this.NETWORK_INFO_VOICE_REGISTRATION_STATE = "voiceRegistrationState";
-this.NETWORK_INFO_DATA_REGISTRATION_STATE = "dataRegistrationState";
-this.NETWORK_INFO_OPERATOR = "operator";
-this.NETWORK_INFO_NETWORK_SELECTION_MODE = "networkSelectionMode";
-this.NETWORK_INFO_SIGNAL = "signal";
-this.NETWORK_INFO_MESSAGE_TYPES = [
- NETWORK_INFO_VOICE_REGISTRATION_STATE,
- NETWORK_INFO_DATA_REGISTRATION_STATE,
- NETWORK_INFO_OPERATOR,
- NETWORK_INFO_NETWORK_SELECTION_MODE,
- NETWORK_INFO_SIGNAL
-];
-
-this.GECKO_PREFERRED_NETWORK_TYPE_WCDMA_GSM = "wcdma/gsm";
-this.GECKO_PREFERRED_NETWORK_TYPE_GSM_ONLY = "gsm";
-this.GECKO_PREFERRED_NETWORK_TYPE_WCDMA_ONLY = "wcdma";
-this.GECKO_PREFERRED_NETWORK_TYPE_WCDMA_GSM_AUTO = "wcdma/gsm-auto";
-this.GECKO_PREFERRED_NETWORK_TYPE_CDMA_EVDO = "cdma/evdo";
-this.GECKO_PREFERRED_NETWORK_TYPE_CDMA_ONLY = "cdma";
-this.GECKO_PREFERRED_NETWORK_TYPE_EVDO_ONLY = "evdo";
-this.GECKO_PREFERRED_NETWORK_TYPE_WCDMA_GSM_CDMA_EVDO = "wcdma/gsm/cdma/evdo";
-this.GECKO_PREFERRED_NETWORK_TYPE_LTE_CDMA_EVDO = "lte/cdma/evdo";
-this.GECKO_PREFERRED_NETWORK_TYPE_LTE_WCDMA_GSM = "lte/wcdma/gsm";
-this.GECKO_PREFERRED_NETWORK_TYPE_LTE_WCDMA = "lte/wcdma";
-this.GECKO_PREFERRED_NETWORK_TYPE_LTE_WCDMA_GSM_CDMA_EVDO = "lte/wcdma/gsm/cdma/evdo";
-this.GECKO_PREFERRED_NETWORK_TYPE_LTE_ONLY = "lte";
-this.RIL_PREFERRED_NETWORK_TYPE_TO_GECKO = [
- GECKO_PREFERRED_NETWORK_TYPE_WCDMA_GSM,
- GECKO_PREFERRED_NETWORK_TYPE_GSM_ONLY,
- GECKO_PREFERRED_NETWORK_TYPE_WCDMA_ONLY,
- GECKO_PREFERRED_NETWORK_TYPE_WCDMA_GSM_AUTO,
- GECKO_PREFERRED_NETWORK_TYPE_CDMA_EVDO,
- GECKO_PREFERRED_NETWORK_TYPE_CDMA_ONLY,
- GECKO_PREFERRED_NETWORK_TYPE_EVDO_ONLY,
- GECKO_PREFERRED_NETWORK_TYPE_WCDMA_GSM_CDMA_EVDO,
- GECKO_PREFERRED_NETWORK_TYPE_LTE_CDMA_EVDO,
- GECKO_PREFERRED_NETWORK_TYPE_LTE_WCDMA_GSM,
- GECKO_PREFERRED_NETWORK_TYPE_LTE_WCDMA_GSM_CDMA_EVDO,
- GECKO_PREFERRED_NETWORK_TYPE_LTE_ONLY,
- GECKO_PREFERRED_NETWORK_TYPE_LTE_WCDMA
-];
-
-this.GECKO_SUPPORTED_NETWORK_TYPES_DEFAULT = "gsm,wcdma";
-// Index-item pair must be in sync with nsIMobileConnection.MOBILE_NETWORK_TYPE_*
-this.GECKO_SUPPORTED_NETWORK_TYPES = [
- "gsm",
- "wcdma",
- "cdma",
- "evdo",
- "lte"
-];
-
-// Network registration states. See TS 27.007 7.2
-this.NETWORK_CREG_STATE_NOT_SEARCHING = 0;
-this.NETWORK_CREG_STATE_REGISTERED_HOME = 1;
-this.NETWORK_CREG_STATE_SEARCHING = 2;
-this.NETWORK_CREG_STATE_DENIED = 3;
-this.NETWORK_CREG_STATE_UNKNOWN = 4;
-this.NETWORK_CREG_STATE_REGISTERED_ROAMING = 5;
-this.NETWORK_CREG_STATE_NOT_SEARCHING_EMERGENCY_CALLS = 10;
-this.NETWORK_CREG_STATE_SEARCHING_EMERGENCY_CALLS = 12;
-this.NETWORK_CREG_STATE_DENIED_EMERGENCY_CALLS = 13;
-this.NETWORK_CREG_STATE_UNKNOWN_EMERGENCY_CALLS = 14;
-
-this.NETWORK_CREG_TECH_UNKNOWN = 0;
-this.NETWORK_CREG_TECH_GPRS = 1;
-this.NETWORK_CREG_TECH_EDGE = 2;
-this.NETWORK_CREG_TECH_UMTS = 3;
-this.NETWORK_CREG_TECH_IS95A = 4;
-this.NETWORK_CREG_TECH_IS95B = 5;
-this.NETWORK_CREG_TECH_1XRTT = 6;
-this.NETWORK_CREG_TECH_EVDO0 = 7;
-this.NETWORK_CREG_TECH_EVDOA = 8;
-this.NETWORK_CREG_TECH_HSDPA = 9;
-this.NETWORK_CREG_TECH_HSUPA = 10;
-this.NETWORK_CREG_TECH_HSPA = 11;
-this.NETWORK_CREG_TECH_EVDOB = 12;
-this.NETWORK_CREG_TECH_EHRPD = 13;
-this.NETWORK_CREG_TECH_LTE = 14;
-this.NETWORK_CREG_TECH_HSPAP = 15;
-this.NETWORK_CREG_TECH_GSM = 16;
-this.NETWORK_CREG_TECH_DCHSPAP_1 = 18; // Some devices reports as 18
-this.NETWORK_CREG_TECH_DCHSPAP_2 = 19; // Some others report it as 19
-
-this.CELL_INFO_TYPE_GSM = 1;
-this.CELL_INFO_TYPE_CDMA = 2;
-this.CELL_INFO_TYPE_LTE = 3;
-this.CELL_INFO_TYPE_WCDMA = 4;
-
-this.CALL_STATE_UNKNOWN = -1;
-this.CALL_STATE_ACTIVE = 0;
-this.CALL_STATE_HOLDING = 1;
-this.CALL_STATE_DIALING = 2;
-this.CALL_STATE_ALERTING = 3;
-this.CALL_STATE_INCOMING = 4;
-this.CALL_STATE_WAITING = 5;
-
-this.TOA_INTERNATIONAL = 0x91;
-this.TOA_UNKNOWN = 0x81;
-
-this.CALL_PRESENTATION_ALLOWED = 0;
-this.CALL_PRESENTATION_RESTRICTED = 1;
-this.CALL_PRESENTATION_UNKNOWN = 2;
-this.CALL_PRESENTATION_PAYPHONE = 3;
-
-// Call forwarding actions, see TS 27.007 7.11 "mode"
-this.CALL_FORWARD_ACTION_QUERY_STATUS = 2;
-
-// ICC commands, see TS 27.007 +CRSM commands
-this.ICC_COMMAND_SEEK = 0xa2;
-this.ICC_COMMAND_READ_BINARY = 0xb0;
-this.ICC_COMMAND_READ_RECORD = 0xb2;
-this.ICC_COMMAND_GET_RESPONSE = 0xc0;
-this.ICC_COMMAND_UPDATE_BINARY = 0xd6;
-this.ICC_COMMAND_UPDATE_RECORD = 0xdc;
-
-// ICC constants, GSM SIM file ids from TS 51.011
-this.ICC_EF_ICCID = 0x2fe2;
-this.ICC_EF_IMG = 0x4f20;
-this.ICC_EF_PBR = 0x4f30;
-this.ICC_EF_PLMNsel = 0x6f30; // PLMN for SIM
-this.ICC_EF_SST = 0x6f38;
-this.ICC_EF_UST = 0x6f38; // For USIM
-this.ICC_EF_ADN = 0x6f3a;
-this.ICC_EF_FDN = 0x6f3b;
-this.ICC_EF_SMS = 0x6f3c;
-this.ICC_EF_GID1 = 0x6f3e;
-this.ICC_EF_MSISDN = 0x6f40;
-this.ICC_EF_CBMI = 0x6f45;
-this.ICC_EF_SPN = 0x6f46;
-this.ICC_EF_CBMID = 0x6f48;
-this.ICC_EF_SDN = 0x6f49;
-this.ICC_EF_EXT1 = 0x6f4a;
-this.ICC_EF_EXT2 = 0x6f4b;
-this.ICC_EF_EXT3 = 0x6f4c;
-this.ICC_EF_CBMIR = 0x6f50;
-this.ICC_EF_AD = 0x6fad;
-this.ICC_EF_PHASE = 0x6fae;
-this.ICC_EF_PNN = 0x6fc5;
-this.ICC_EF_OPL = 0x6fc6;
-this.ICC_EF_MBDN = 0x6fc7;
-this.ICC_EF_EXT6 = 0x6fc8; // Ext record for EF[MBDN]
-this.ICC_EF_MBI = 0x6fc9;
-this.ICC_EF_MWIS = 0x6fca;
-this.ICC_EF_CFIS = 0x6fcb;
-this.ICC_EF_SPDI = 0x6fcd;
-
-// CPHS files to be supported
-this.ICC_EF_CPHS_INFO = 0x6f16; // CPHS Information
-this.ICC_EF_CPHS_MBN = 0x6f17; // Mailbox Numbers
-
-// CSIM files
-this.ICC_EF_CSIM_IMSI_M = 0x6f22;
-this.ICC_EF_CSIM_CDMAHOME = 0x6f28;
-this.ICC_EF_CSIM_CST = 0x6f32; // CDMA Service table
-this.ICC_EF_CSIM_SPN = 0x6f41;
-
-this.ICC_PHASE_1 = 0x00;
-this.ICC_PHASE_2 = 0x02;
-this.ICC_PHASE_2_PROFILE_DOWNLOAD_REQUIRED = 0x03;
-
-// Types of files TS 11.11 9.3
-this.TYPE_RFU = 0;
-this.TYPE_MF = 1;
-this.TYPE_DF = 2;
-this.TYPE_EF = 4;
-
-this.RESPONSE_DATA_FILE_SIZE = 2;
-this.RESPONSE_DATA_FILE_ID_1 = 4;
-this.RESPONSE_DATA_FILE_ID_2 = 5;
-this.RESPONSE_DATA_FILE_TYPE = 6;
-this.RESPONSE_DATA_RFU_3 = 7;
-this.RESPONSE_DATA_ACCESS_CONDITION_1 = 8;
-this.RESPONSE_DATA_ACCESS_CONDITION_2 = 9;
-this.RESPONSE_DATA_ACCESS_CONDITION_3 = 10;
-this.RESPONSE_DATA_FILE_STATUS = 11;
-this.RESPONSE_DATA_LENGTH = 12;
-this.RESPONSE_DATA_STRUCTURE = 13;
-this.RESPONSE_DATA_RECORD_LENGTH = 14;
-
-// Structure of files TS 11.11 9.3
-this.EF_STRUCTURE_TRANSPARENT = 0;
-this.EF_STRUCTURE_LINEAR_FIXED = 1;
-this.EF_STRUCTURE_CYCLIC = 3;
-
-// TS 102.221 11.1.1.4.3 Table 11.5: File descriptor byte.
-this.UICC_EF_STRUCTURE = {};
-this.UICC_EF_STRUCTURE[this.EF_STRUCTURE_TRANSPARENT]= 1;
-this.UICC_EF_STRUCTURE[this.EF_STRUCTURE_LINEAR_FIXED]= 2;
-this.UICC_EF_STRUCTURE[this.EF_STRUCTURE_CYCLIC]= 6;
-
-// Status code of EFsms
-// see 3GPP TS 51.011 clause 10.5.3
-this.EFSMS_STATUS_FREE = 0x00;
-this.EFSMS_STATUS_READ = 0x01;
-this.EFSMS_STATUS_TO_BE_READ = 0x03;
-this.EFSMS_STATUS_TO_BE_SENT = 0x07;
-
-// Total size of ADN footer(the size of Alpha identifier excluded).
-// See TS 151.011 clause 10.5.1 EF_ADN.
-this.ADN_FOOTER_SIZE_BYTES = 14;
-// Maximum size of BCD numbers in ADN.
-// See TS 151.011 clause 10.5.1 EF_ADN, 'Length of BCD number/SSC contents'.
-this.ADN_MAX_BCD_NUMBER_BYTES = 11;
-// Maximum digits of the Dialling Number in ADN.
-// See TS 151.011 clause 10.5.1 EF_ADN, 'Dialling Number'.
-this.ADN_MAX_NUMBER_DIGITS = 20;
-// Maximum size of BCD numbers in EXT.
-// See TS 151.011 clause 10.5.10 EF_EXT1, 'Extension data'.
-this.EXT_MAX_BCD_NUMBER_BYTES = 10;
-// Maximum digits of the Dialling Number in EXT.
-// See TS 151.011 clause 10.5.10 EF_EXT1, 'Extension data'.
-this.EXT_MAX_NUMBER_DIGITS = 20;
-
-// READ_RECORD mode, TS 102.221
-this.READ_RECORD_ABSOLUTE_MODE = 4;
-
-// TS 102.221 Table 11.2, return FCP template
-this.GET_RESPONSE_FCP_TEMPLATE = 4;
-
-// GET_RESPONSE mandatory response size for EF, see TS 51.011 clause 9,
-// 'Response data in case of an EF.'
-this.GET_RESPONSE_EF_SIZE_BYTES = 15;
-
-// EF path
-this.EF_PATH_MF_SIM = "3f00";
-this.EF_PATH_DF_PHONEBOOK = "5f3a";
-this.EF_PATH_GRAPHICS = "5f50";
-this.EF_PATH_DF_TELECOM = "7f10";
-this.EF_PATH_DF_GSM = "7f20";
-this.EF_PATH_DF_CDMA = "7f25";
-this.EF_PATH_ADF_USIM = "7fff";
-
-// Status code of sw1 for ICC I/O,
-// see GSM11.11 and TS 51.011 clause 9.4, and ISO 7816-4
-this.ICC_STATUS_NORMAL_ENDING = 0x90;
-this.ICC_STATUS_NORMAL_ENDING_WITH_EXTRA = 0x91;
-this.ICC_STATUS_SAT_BUSY = 0x93;
-this.ICC_STATUS_WITH_SIM_DATA = 0x9e;
-this.ICC_STATUS_WITH_RESPONSE_DATA = 0x9f;
-this.ICC_STATUS_ERROR_WRONG_LENGTH = 0x67;
-this.ICC_STATUS_ERROR_COMMAND_NOT_ALLOWED = 0x69;
-this.ICC_STATUS_ERROR_WRONG_PARAMETERS = 0x6a;
-
-// ICC call barring facility.
-// TS 27.007, clause 7.4, +CLCK
-this.ICC_CB_FACILITY_SIM = "SC";
-this.ICC_CB_FACILITY_FDN = "FD";
-this.ICC_CB_FACILITY_BAOC = "AO";
-this.ICC_CB_FACILITY_BAOIC = "OI";
-this.ICC_CB_FACILITY_BAOICxH = "OX";
-this.ICC_CB_FACILITY_BAIC = "AI";
-this.ICC_CB_FACILITY_BAICr = "IR";
-this.ICC_CB_FACILITY_BA_ALL = "AB";
-this.ICC_CB_FACILITY_BA_MO = "AG";
-this.ICC_CB_FACILITY_BA_MT = "AC";
-
-// ICC service class
-// TS 27.007, clause 7.4, +CLCK
-this.ICC_SERVICE_CLASS_NONE = 0; // no user input
-this.ICC_SERVICE_CLASS_VOICE = (1 << 0);
-this.ICC_SERVICE_CLASS_DATA = (1 << 1);
-this.ICC_SERVICE_CLASS_FAX = (1 << 2);
-this.ICC_SERVICE_CLASS_SMS = (1 << 3);
-this.ICC_SERVICE_CLASS_DATA_SYNC = (1 << 4);
-this.ICC_SERVICE_CLASS_DATA_ASYNC = (1 << 5);
-this.ICC_SERVICE_CLASS_PACKET = (1 << 6);
-this.ICC_SERVICE_CLASS_PAD = (1 << 7);
-this.ICC_SERVICE_CLASS_MAX = (1 << 7); // Max ICC_SERVICE_CLASS value
-
-// ICC lock-selection codes
-// TS 27.007, clause 8.65, +CPINR
-this.ICC_SEL_CODE_SIM_PIN = "SIM PIN";
-this.ICC_SEL_CODE_SIM_PUK = "SIM PUK";
-this.ICC_SEL_CODE_PH_SIM_PIN = "PH-SIM PIN";
-this.ICC_SEL_CODE_PH_FSIM_PIN = "PH-FSIM PIN";
-this.ICC_SEL_CODE_PH_FSIM_PUK = "PH-FSIM PUK";
-this.ICC_SEL_CODE_SIM_PIN2 = "SIM PIN2";
-this.ICC_SEL_CODE_SIM_PUK2 = "SIM PUK2";
-this.ICC_SEL_CODE_PH_NET_PIN = "PH-NET PIN";
-this.ICC_SEL_CODE_PH_NET_PUK = "PH-NET PUK";
-this.ICC_SEL_CODE_PH_NETSUB_PIN = "PH-NETSUB PIN";
-this.ICC_SEL_CODE_PH_NETSUB_PUK = "PH-NETSUB PUK";
-this.ICC_SEL_CODE_PH_SP_PIN = "PH-SP PIN";
-this.ICC_SEL_CODE_PH_SP_PUK = "PH-SP PUK";
-this.ICC_SEL_CODE_PH_CORP_PIN = "PH-CORP PIN";
-this.ICC_SEL_CODE_PH_CORP_PUK = "PH-CORP PUK";
-// TODO: Bug 1116072: identify the mapping between RIL_PERSOSUBSTATE_SIM_SIM @
-// ril.h and TS 27.007, clause 8.65 for GECKO_CARDLOCK_PCK.
-
-this.ICC_USIM_TYPE1_TAG = 0xa8;
-this.ICC_USIM_TYPE2_TAG = 0xa9;
-this.ICC_USIM_TYPE3_TAG = 0xaa;
-this.ICC_USIM_EFADN_TAG = 0xc0;
-this.ICC_USIM_EFIAP_TAG = 0xc1;
-this.ICC_USIM_EFEXT1_TAG = 0xc2;
-this.ICC_USIM_EFSNE_TAG = 0xc3;
-this.ICC_USIM_EFANR_TAG = 0xc4;
-this.ICC_USIM_EFPBC_TAG = 0xc5;
-this.ICC_USIM_EFGRP_TAG = 0xc6;
-this.ICC_USIM_EFAAS_TAG = 0xc7;
-this.ICC_USIM_EFGSD_TAG = 0xc8;
-this.ICC_USIM_EFUID_TAG = 0xc9;
-this.ICC_USIM_EFEMAIL_TAG = 0xca;
-this.ICC_USIM_EFCCP1_TAG = 0xcb;
-
-// ICC image coding scheme
-// TS 31.102, sub-clause 4.6.1.1
-this.ICC_IMG_CODING_SCHEME_BASIC = 0x11;
-this.ICC_IMG_CODING_SCHEME_COLOR = 0x21;
-this.ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY = 0x22;
-
-// Must be in sync with enum IccImageCodingScheme in MozStkCommandEvent.webidl.
-this.GECKO_IMG_CODING_SCHEME_BASIC = "basic";
-this.GECKO_IMG_CODING_SCHEME_COLOR = "color";
-this.GECKO_IMG_CODING_SCHEME_COLOR_TRANSPARENCY = "color-transparency";
-
-this.ICC_IMG_CODING_SCHEME_TO_GECKO = {};
-ICC_IMG_CODING_SCHEME_TO_GECKO[ICC_IMG_CODING_SCHEME_BASIC] = GECKO_IMG_CODING_SCHEME_BASIC;
-ICC_IMG_CODING_SCHEME_TO_GECKO[ICC_IMG_CODING_SCHEME_COLOR] = GECKO_IMG_CODING_SCHEME_COLOR;
-ICC_IMG_CODING_SCHEME_TO_GECKO[ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY] = GECKO_IMG_CODING_SCHEME_COLOR_TRANSPARENCY;
-
-// ICC image header size per coding scheme
-// TS 31.102, Annex B
-this.ICC_IMG_HEADER_SIZE_BASIC = 2;
-this.ICC_IMG_HEADER_SIZE_COLOR = 6;
-
-this.ICC_CLUT_ENTRY_SIZE = 3;
-
-this.USIM_PBR_ANR = "anr";
-this.USIM_PBR_ANR0 = "anr0";
-this.USIM_PBR_EMAIL = "email";
-
-// Current supported fields. Adding more fields to read will increasing I/O
-// time dramatically, do check the performance is acceptable when you add
-// more fields.
-this.USIM_PBR_FIELDS = [USIM_PBR_EMAIL, USIM_PBR_ANR0];
-
-this.USIM_TAG_NAME = {};
-this.USIM_TAG_NAME[ICC_USIM_EFADN_TAG] = "adn";
-this.USIM_TAG_NAME[ICC_USIM_EFIAP_TAG] ="iap";
-this.USIM_TAG_NAME[ICC_USIM_EFEXT1_TAG] = "ext1";
-this.USIM_TAG_NAME[ICC_USIM_EFSNE_TAG] = "sne";
-this.USIM_TAG_NAME[ICC_USIM_EFANR_TAG] = "anr";
-this.USIM_TAG_NAME[ICC_USIM_EFPBC_TAG] = "pbc";
-this.USIM_TAG_NAME[ICC_USIM_EFGRP_TAG] = "grp";
-this.USIM_TAG_NAME[ICC_USIM_EFAAS_TAG] = "aas";
-this.USIM_TAG_NAME[ICC_USIM_EFGSD_TAG] = "gsd";
-this.USIM_TAG_NAME[ICC_USIM_EFUID_TAG] = "uid";
-this.USIM_TAG_NAME[ICC_USIM_EFEMAIL_TAG] = "email";
-this.USIM_TAG_NAME[ICC_USIM_EFCCP1_TAG] = "ccp1";
-
-// Error message for ICC contact.
-this.CONTACT_ERR_REQUEST_NOT_SUPPORTED = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
-this.CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED = "ContactTypeNotSupported";
-this.CONTACT_ERR_FIELD_NOT_SUPPORTED = "FieldNotSupported";
-this.CONTACT_ERR_NO_FREE_RECORD_FOUND = "NoFreeRecordFound";
-this.CONTACT_ERR_CANNOT_ACCESS_PHONEBOOK = "CannotAccessPhoneBook";
-
-// CDMA IMSI_M's byte const.
-// 3GPP2 C.S0065 Sec. 5.2.2
-this.CSIM_IMSI_M_MIN2_BYTE = 1;
-this.CSIM_IMSI_M_MIN1_BYTE = 3;
-this.CSIM_IMSI_M_MNC_BYTE = 6;
-this.CSIM_IMSI_M_PROGRAMMED_BYTE = 7;
-this.CSIM_IMSI_M_MCC_BYTE = 8;
-
-/**
- * Tags for Ber Tlv.
- * See 3GPP TS 101 220 clause 7.2 - Assigned TLV tag values.
- */
-this.BER_UNKNOWN_TAG = 0x00;
-this.BER_FCP_TEMPLATE_TAG = 0x62;
-this.BER_FCP_FILE_SIZE_DATA_TAG = 0x80;
-this.BER_FCP_FILE_SIZE_TOTAL_TAG = 0x81;
-this.BER_FCP_FILE_DESCRIPTOR_TAG = 0x82;
-this.BER_FCP_FILE_IDENTIFIER_TAG = 0x83;
-this.BER_FCP_DF_NAME_TAG = 0x84; // AID.
-this.BER_FCP_PROPRIETARY_PRIMITIVE_TAG = 0x85;
-this.BER_FCP_SFI_SUPPORT_TAG = 0x88;
-this.BER_FCP_LIFE_CYCLE_STATUS_TAG = 0x8a;
-this.BER_FCP_SA_REFERENCE_FORMAT_TAG = 0x8b; // Security Attribute - Reference Format.
-this.BER_FCP_SA_COMPACT_FORMAT_TAG = 0x8c; // Security Attribute - Compact Format.
-this.BER_FCP_SAT_EXPANDED_FORMAT_TAG = 0xab; // Security Attribute Template - Expanded Format.
-this.BER_FCP_PROPRIETARY_TEMPLATE_TAG = 0xa5;
-this.BER_FCP_PIN_STATUS_DATA_OBJECTS_TAG = 0xc6;
-this.BER_PROACTIVE_COMMAND_TAG = 0xd0;
-this.BER_SMS_PP_DOWNLOAD_TAG = 0xd1;
-this.BER_MENU_SELECTION_TAG = 0xd3;
-this.BER_EVENT_DOWNLOAD_TAG = 0xd6;
-this.BER_TIMER_EXPIRATION_TAG = 0xd7;
-
-// Flags in Comprehension TLV.
-this.COMPREHENSIONTLV_FLAG_CR = 0x80; // Comprehension required.
-
-// Tags for Comprehension TLV.
-this.COMPREHENSIONTLV_TAG_COMMAND_DETAILS = 0x01;
-this.COMPREHENSIONTLV_TAG_DEVICE_ID = 0x02;
-this.COMPREHENSIONTLV_TAG_RESULT = 0x03;
-this.COMPREHENSIONTLV_TAG_DURATION = 0x04;
-this.COMPREHENSIONTLV_TAG_ALPHA_ID = 0x05;
-this.COMPREHENSIONTLV_TAG_ADDRESS = 0x06;
-this.COMPREHENSIONTLV_TAG_SUBADDRESS = 0x08;
-this.COMPREHENSIONTLV_TAG_SMS_TPDU = 0x0b;
-this.COMPREHENSIONTLV_TAG_TEXT_STRING = 0x0d;
-this.COMPREHENSIONTLV_TAG_TONE = 0x0e;
-this.COMPREHENSIONTLV_TAG_ITEM = 0x0f;
-this.COMPREHENSIONTLV_TAG_ITEM_ID = 0x10;
-this.COMPREHENSIONTLV_TAG_RESPONSE_LENGTH = 0x11;
-this.COMPREHENSIONTLV_TAG_FILE_LIST = 0x12;
-this.COMPREHENSIONTLV_TAG_LOCATION_INFO = 0x13;
-this.COMPREHENSIONTLV_TAG_IMEI = 0x14;
-this.COMPREHENSIONTLV_TAG_HELP_REQUEST = 0x15;
-this.COMPREHENSIONTLV_TAG_NMR = 0x16;
-this.COMPREHENSIONTLV_TAG_DEFAULT_TEXT = 0x17;
-this.COMPREHENSIONTLV_TAG_NEXT_ACTION_IND = 0x18;
-this.COMPREHENSIONTLV_TAG_CAUSE = 0x1a;
-this.COMPREHENSIONTLV_TAG_LOCATION_STATUS = 0x1b;
-this.COMPREHENSIONTLV_TAG_TRANSACTION_ID = 0x1c;
-this.COMPREHENSIONTLV_TAG_EVENT_LIST = 0x19;
-this.COMPREHENSIONTLV_TAG_ICON_ID = 0x1e;
-this.COMPREHENSIONTLV_TAG_ICON_ID_LIST = 0x1f;
-this.COMPREHENSIONTLV_TAG_TIMER_IDENTIFIER = 0x24;
-this.COMPREHENSIONTLV_TAG_TIMER_VALUE = 0x25;
-this.COMPREHENSIONTLV_TAG_DATE_TIME_ZONE = 0x26;
-this.COMPREHENSIONTLV_TAG_IMMEDIATE_RESPONSE = 0x2b;
-this.COMPREHENSIONTLV_TAG_LANGUAGE = 0x2d;
-this.COMPREHENSIONTLV_TAG_URL = 0x31;
-this.COMPREHENSIONTLV_TAG_BROWSER_TERMINATION_CAUSE = 0x34;
-this.COMPREHENSIONTLV_TAG_ACCESS_TECH = 0x3f;
-this.COMPREHENSIONTLV_TAG_SERVICE_RECORD = 0x41;
-this.COMPREHENSIONTLV_TAG_IMEISV = 0x62;
-this.COMPREHENSIONTLV_TAG_BATTERY_STATE = 0x63;
-this.COMPREHENSIONTLV_TAG_NETWORK_SEARCH_MODE = 0x65;
-this.COMPREHENSIONTLV_TAG_MEID = 0x6d;
-this.COMPREHENSIONTLV_TAG_BROADCAST_NETWORK_INFO = 0x7a;
-
-// Tags for Service Provider Display Information TLV
-this.SPDI_TAG_SPDI = 0xa3;
-this.SPDI_TAG_PLMN_LIST = 0x80;
-
-// MM INFORMATION message content IEIs
-// See 3GPP TS 24.008 table 9.2.18
-this.PNN_IEI_FULL_NETWORK_NAME = 0x43;
-this.PNN_IEI_SHORT_NETWORK_NAME = 0x45;
-
-// Device identifiers, see TS 11.14, clause 12.7
-this.STK_DEVICE_ID_KEYPAD = 0x01;
-this.STK_DEVICE_ID_DISPLAY = 0x02;
-this.STK_DEVICE_ID_EARPIECE = 0x03;
-this.STK_DEVICE_ID_SIM = 0x81;
-this.STK_DEVICE_ID_ME = 0x82;
-this.STK_DEVICE_ID_NETWORK = 0x83;
-
-// STK Proactive commands.
-this.STK_CMD_REFRESH = 0x01;
-this.STK_CMD_MORE_TIME = 0x02;
-this.STK_CMD_POLL_INTERVAL = 0x03;
-this.STK_CMD_POLL_OFF = 0x04;
-this.STK_CMD_SET_UP_EVENT_LIST = 0x05;
-this.STK_CMD_SET_UP_CALL = 0x10;
-this.STK_CMD_SEND_SS = 0x11;
-this.STK_CMD_SEND_USSD = 0x12;
-this.STK_CMD_SEND_SMS = 0x13;
-this.STK_CMD_SEND_DTMF = 0x14;
-this.STK_CMD_LAUNCH_BROWSER = 0x15;
-this.STK_CMD_PLAY_TONE = 0x20;
-this.STK_CMD_DISPLAY_TEXT = 0x21;
-this.STK_CMD_GET_INKEY = 0x22;
-this.STK_CMD_GET_INPUT = 0x23;
-this.STK_CMD_SELECT_ITEM = 0x24;
-this.STK_CMD_SET_UP_MENU = 0x25;
-this.STK_CMD_PROVIDE_LOCAL_INFO = 0x26;
-this.STK_CMD_TIMER_MANAGEMENT = 0x27;
-this.STK_CMD_SET_UP_IDLE_MODE_TEXT = 0x28;
-this.STK_CMD_OPEN_CHANNEL = 0x40;
-this.STK_CMD_CLOSE_CHANNEL = 0x41;
-this.STK_CMD_RECEIVE_DATA = 0x42;
-this.STK_CMD_SEND_DATA = 0x43;
-
-// STK Result code.
-// TS 11.14, clause 12.12
-
-// Results '0X' and '1X' indicate that the command has been performed.
-
-// Command performed successfully.
-this.STK_RESULT_OK = 0x00;
-
-// Command performed with partial comprehension.
-this.STK_RESULT_PRFRMD_WITH_PARTIAL_COMPREHENSION = 0x01;
-
-// Command performed, with missing information.
-this.STK_RESULT_PRFRMD_WITH_MISSING_INFO = 0x02;
-
-// REFRESH performed with additional EFs read.
-this.STK_RESULT_PRFRMD_WITH_ADDITIONAL_EFS_READ = 0x03;
-
-// Command performed successfully, but requested icon could not be
-// displayed.
-this.STK_RESULT_PRFRMD_ICON_NOT_DISPLAYED = 0x04;
-
-// Command performed, but modified by call control by NAA.
-this.STK_RESULT_PRFRMD_MODIFIED_BY_NAA = 0x05;
-
-// Command performed successfully, limited service.
-this.STK_RESULT_PRFRMD_LIMITED_SERVICE = 0x06;
-
-// Command performed with modification.
-this.STK_RESULT_PRFRMD_WITH_MODIFICATION = 0x07;
-
-// REFRESH performed but indicated NAA was not active.
-this.STK_RESULT_PRFRMD_NAA_NOT_ACTIVE = 0x08;
-
-// Command performed successfully; tone not played.
-this.STK_RESULT_PRFRMD_TONE_NOT_PLAYED = 0x09;
-
-// Proactive UICC session terminated by the user.
-this.STK_RESULT_UICC_SESSION_TERM_BY_USER = 0x10;
-
-// Backward move in the proactive UICC session requested by the user.
-this.STK_RESULT_BACKWARD_MOVE_BY_USER = 0x11;
-
-// No response from user.
-this.STK_RESULT_NO_RESPONSE_FROM_USER = 0x12;
-
-// Help information required by the user.
-this.STK_RESULT_HELP_INFO_REQUIRED = 0x13;
-
-// USSD or SS transaction terminated by the user.
-this.STK_RESULT_USSD_SS_SESSION_TERM_BY_USER = 0x14;
-
-// Results '2X' indicate to the UICC that it may be worth re-trying the
-// command at a later opportunity.
-
-// Terminal currently unable to process command.
-this.STK_RESULT_TERMINAL_CRNTLY_UNABLE_TO_PROCESS = 0x20;
-
-// Network currently unable to process command.
-this.STK_RESULT_NETWORK_CRNTLY_UNABLE_TO_PROCESS = 0x21;
-
-// User did not accept the proactive command.
-this.STK_RESULT_USER_NOT_ACCEPT = 0x22;
-
-// User cleared down call before connection or network release.
-this.STK_RESULT_USER_CLEAR_DOWN_CALL = 0x23;
-
-// Action in contradiction with the current timer state.
-this.STK_RESULT_CONTRADICTION_WITH_TIMER = 0x24;
-
-// Interaction with call control by NAA; temporary problem.
-this.STK_RESULT_NAA_CALL_CONTROL_TEMPORARY = 0x25;
-
-// Launch browser generic error code.
-this.STK_RESULT_LAUNCH_BROWSER_ERROR = 0x26;
-
-// MMS temporary problem.
-this.STK_RESULT_MMS_TEMPORARY = 0x27;
-
-// Results '3X' indicate that it is not worth the UICC re-trying with an
-// identical command; as it will only get the same response. However, the
-// decision to retry lies with the application.
-
-// Command beyond terminal's capabilities.
-this.STK_RESULT_BEYOND_TERMINAL_CAPABILITY = 0x30;
-
-// Command type not understood by terminal.
-this.STK_RESULT_CMD_TYPE_NOT_UNDERSTOOD = 0x31;
-
-// Command data not understood by terminal.
-this.STK_RESULT_CMD_DATA_NOT_UNDERSTOOD = 0x32;
-
-// Command number not known by terminal.
-this.STK_RESULT_CMD_NUM_NOT_KNOWN = 0x33;
-
-// SS Return Error.
-this.STK_RESULT_SS_RETURN_ERROR = 0x34;
-
-// SMS RP-ERROR.
-this.STK_RESULT_SMS_RP_ERROR = 0x35;
-
-// Error, required values are missing.
-this.STK_RESULT_REQUIRED_VALUES_MISSING = 0x36;
-
-// USSD Return Error.
-this.STK_RESULT_USSD_RETURN_ERROR = 0x37;
-
-// MultipleCard commands error.
-this.STK_RESULT_MULTI_CARDS_CMD_ERROR = 0x38;
-
-// Interaction with call control by USIM or MO short message control by
-// USIM; permanent problem.
-this.STK_RESULT_USIM_CALL_CONTROL_PERMANENT = 0x39;
-
-// Bearer Independent Protocol error.
-this.STK_RESULT_BIP_ERROR = 0x3a;
-
-// Access Technology unable to process command.
-this.STK_RESULT_ACCESS_TECH_UNABLE_TO_PROCESS = 0x3b;
-
-// Frames error.
-this.STK_RESULT_FRAMES_ERROR = 0x3c;
-
-// MMS Error.
-this.STK_RESULT_MMS_ERROR = 0x3d;
-
-// STK presentation types, TS 11.14, clause 12.6, Command Qualifier: Select Item
-this.STK_PRESENTATION_TYPE_NOT_SPECIFIED = 0x00; // Bit 1 is 0.
-this.STK_PRESENTATION_TYPE_DATA_VALUES = 0x01; // Bit 1 is 1, bit 2 is 0.
-this.STK_PRESENTATION_TYPE_NAVIGATION_OPTIONS = 0x03; // Bit 1 is 1, bit 2 is 1.
-
-// STK Coding Scheme.
-this.STK_TEXT_CODING_GSM_7BIT_PACKED = 0x00;
-this.STK_TEXT_CODING_GSM_8BIT = 0x04;
-this.STK_TEXT_CODING_UCS2 = 0x08;
-
-// STK Event List.
-this.STK_EVENT_TYPE_MT_CALL = 0x00;
-this.STK_EVENT_TYPE_CALL_CONNECTED = 0x01;
-this.STK_EVENT_TYPE_CALL_DISCONNECTED = 0x02;
-this.STK_EVENT_TYPE_LOCATION_STATUS = 0x03;
-this.STK_EVENT_TYPE_USER_ACTIVITY = 0x04;
-this.STK_EVENT_TYPE_IDLE_SCREEN_AVAILABLE = 0x05;
-this.STK_EVENT_TYPE_CARD_READER_STATUS = 0x06;
-this.STK_EVENT_TYPE_LANGUAGE_SELECTION = 0x07;
-this.STK_EVENT_TYPE_BROWSER_TERMINATION = 0x08;
-this.STK_EVENT_TYPE_DATA_AVAILABLE = 0x09;
-this.STK_EVENT_TYPE_CHANNEL_STATUS = 0x0a;
-this.STK_EVENT_TYPE_SINGLE_ACCESS_TECHNOLOGY_CHANGED = 0x0b;
-this.STK_EVENT_TYPE_DISPLAY_PARAMETER_CHANGED = 0x0c;
-this.STK_EVENT_TYPE_LOCAL_CONNECTION = 0x0d;
-this.STK_EVENT_TYPE_NETWORK_SEARCH_MODE_CHANGED = 0x0e;
-this.STK_EVENT_TYPE_BROWSING_STATUS = 0x0f;
-
-// STK Service state of Location Status.
-this.STK_SERVICE_STATE_NORMAL = 0x00;
-this.STK_SERVICE_STATE_LIMITED = 0x01;
-this.STK_SERVICE_STATE_UNAVAILABLE = 0x02;
-
-// Refresh mode.
-this.STK_REFRESH_NAA_INIT_AND_FULL_FILE_CHANGE = 0x00;
-this.STK_REFRESH_FILE_CHANGE = 0x01;
-this.STK_REFRESH_NAA_INIT_AND_FILE_CHANGE = 0x02;
-this.STK_REFRESH_NAA_INIT = 0x03;
-this.STK_REFRESH_UICC_RESET = 0x04;
-
-// Tone type.
-this.STK_TONE_TYPE_DIAL_TONE = 0x01;
-this.STK_TONE_TYPE_CALLED_SUBSCRIBER_BUSY = 0x02;
-this.STK_TONE_TYPE_CONGESTION = 0x03;
-this.STK_TONE_TYPE_RADIO_PATH_ACK = 0x04;
-this.STK_TONE_TYPE_RADIO_PATH_NOT_AVAILABLE = 0x05;
-this.STK_TONE_TYPE_ERROR = 0x06;
-this.STK_TONE_TYPE_CALL_WAITING_TONE = 0x07;
-this.STK_TONE_TYPE_RINGING_TONE = 0x08;
-this.STK_TONE_TYPE_GENERAL_BEEP = 0x10;
-this.STK_TONE_TYPE_POSITIVE_ACK_TONE = 0x11;
-this.STK_TONE_TYPE_NEGATIVE_ACK_TONE = 0x12;
-
-// Time unit.
-this.STK_TIME_UNIT_MINUTE = 0x00;
-this.STK_TIME_UNIT_SECOND = 0x01;
-this.STK_TIME_UNIT_TENTH_SECOND = 0x02;
-
-// Local Information type.
-this.STK_LOCAL_INFO_NNA = 0x00;
-this.STK_LOCAL_INFO_IMEI = 0x01;
-this.STK_LOCAL_INFO_NMR_FOR_NNA = 0x02;
-this.STK_LOCAL_INFO_DATE_TIME_ZONE = 0x03;
-this.STK_LOCAL_INFO_LANGUAGE = 0x04;
-this.STK_LOCAL_INFO_ACCESS_TECH = 0x06;
-this.STK_LOCAL_INFO_ESN = 0x07;
-this.STK_LOCAL_INFO_IMEISV = 0x08;
-this.STK_LOCAL_INFO_SEARCH_MODE = 0x09;
-this.STK_LOCAL_INFO_CHARGE_STATE = 0x0A;
-this.STK_LOCAL_INFO_MEID = 0x0B;
-this.STK_LOCAL_INFO_BROADCAST_NETWORK_INFO = 0x0D;
-this.STK_LOCAL_INFO_MULTIPLE_ACCESS_TECH = 0x0E;
-this.STK_LOCAL_INFO_INFO_FOR_MULTIPLE_ACCESS_TECH = 0x0F;
-this.STK_LOCAL_INFO_NMR_FOR_MULTIPLE_ACCESS_TECH = 0x10;
-
-// Timer Management.
-this.STK_TIMER_START = 0x00;
-this.STK_TIMER_DEACTIVATE = 0x01;
-this.STK_TMIER_GET_CURRENT_VALUE = 0x02;
-
-// Browser Launch Mode.
-this.STK_BROWSER_MODE_LAUNCH_IF_NOT_ALREADY_LAUNCHED = 0x00;
-this.STK_BROWSER_MODE_USING_EXISTING_BROWSER = 0x02;
-this.STK_BROWSER_MODE_USING_NEW_BROWSER = 0x03;
-
-// Browser Termination Cause.
-this.STK_BROWSER_TERMINATION_CAUSE_USER = 0x00;
-this.STK_BROWSER_TERMINATION_CAUSE_ERROR = 0x01;
-
-// Next Action Indicator.
-this.STK_NEXT_ACTION_NULL = 0x00;
-this.STK_NEXT_ACTION_END_PROACTIVE_SESSION = 0x81;
-
-/**
- * Supported Terminal Facilities.
- *
- * value = 1, supported.
- * 0, not supported.
- */
-this.STK_TERMINAL_SUPPORT_PROFILE_DOWNLOAD = 1;
-this.STK_TERMINAL_SUPPORT_SMS_PP_DOWNLOAD = 1;
-this.STK_TERMINAL_SUPPORT_CELL_BROADCAST_DATA_DOWNLOAD = 0;
-this.STK_TERMINAL_SUPPORT_MENU_SELECTION = 1;
-this.STK_TERMINAL_SUPPORT_SIM_DATA_DOWNLOAD_ERROR = 0;
-this.STK_TERMINAL_SUPPORT_TIMER_EXPIRATION = 1;
-this.STK_TERMINAL_SUPPORT_USSD_IN_CALL_CONTROL = 0;
-this.STK_TERMINAL_SUPPORT_CALL_CONTROL_IN_REDIAL = 0;
-
-this.STK_TERMINAL_SUPPORT_COMMAND_RESULT = 1;
-this.STK_TERMINAL_SUPPORT_CALL_CONTROL = 1;
-this.STK_TERMINAL_SUPPORT_CALL_ID_INCLUDED = 0;
-this.STK_TERMINAL_SUPPORT_MO_SMS_CONTROL = 0;
-this.STK_TERMINAL_SUPPORT_ALPHA_ID_INDICATION = 0;
-this.STK_TERMINAL_SUPPORT_UCS2_ENTRY = 1;
-this.STK_TERMINAL_SUPPORT_UCS2_DISPLAY = 1;
-this.STK_TERMINAL_SUPPORT_EXTENSION_TEXT = 1;
-
-this.STK_TERMINAL_SUPPORT_PROACTIVE_DISPLAY_TEXT = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_GET_INKEY = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_GET_INPUT = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_MORE_TIME = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_PLAY_TONE = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_POLL_INTERVAL = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_POLL_OFF = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_REFRESH = 1;
-
-this.STK_TERMINAL_SUPPORT_PROACTIVE_SELECT_ITEM = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_SEND_SMS = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_SEND_SS = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_SEND_USSD = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_SET_UP_CALL = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_SET_UP_MENU = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_NMR = 0;
-
-this.STK_TERMINAL_SUPPORT_PROACTIVE_SET_UP_EVENT_LIST = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_MT_CALL = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_CALL_CONNECTED = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_CALL_DISCONNECTED = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_LOCATION_STATUS = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_USER_ACTIVITY = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_IDLE_SCREEN_AVAILABLE = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_CARD_READER_STATUS = 0;
-
-this.STK_TERMINAL_SUPPORT_EVENT_LANGUAGE_SELECTION = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_BROWSER_TERMINATION = 1;
-this.STK_TERMINAL_SUPPORT_EVENT_DATA_AVAILABLE = 0;
-this.STK_TERMINAL_SUPPORT_EVENT_CHANNEL_STATUS = 0;
-
-this.STK_TERMINAL_SUPPORT_PROACTIVE_TIMER_START_STOP = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_TIMER_GET_CURRENT = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_DATE = 1;
-this.STK_TERMINAL_SUPPORT_GET_INKEY = 1;
-this.STK_TERMINAL_SUPPORT_SET_UP_IDLE_MODE_TEXT = 1;
-this.STK_TERMINAL_SUPPORT_RUN_AT_COMMAND = 0;
-this.STK_TERMINAL_SUPPORT_SET_UP_CALL = 1;
-this.STK_TERMINAL_SUPPORT_CALL_CONTROL_BY_NNA = 0;
-
-this.STK_TERMINAL_SUPPORT_DISPLAY_TEXT = 1;
-this.STK_TERMINAL_SUPPORT_SEND_DTMF_COMMAND = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_NMR = 0;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_LANGUAGE = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_TIME_ADVANCE = 0;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LANGUAGE_NOTIFICATION = 0;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LAUNCH_BROWSER = 1;
-this.STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_ACCESS_TECH = 0;
-
-this.STK_TERMINAL_SUPPORT_BIP_COMMAND_OPEN_CHANNEL = 1;
-this.STK_TERMINAL_SUPPORT_BIP_COMMAND_CLOSE_CHANNEL = 1;
-this.STK_TERMINAL_SUPPORT_BIP_COMMAND_RECEIVE_DATA = 1;
-this.STK_TERMINAL_SUPPORT_BIP_COMMAND_SEND_DATA = 1;
-this.STK_TERMINAL_SUPPORT_BIP_COMMAND_GET_CHANNEL_STATUS = 0;
-
-/**
- * SAT profile
- *
- * @see ETSI TS 101.267, section 5.2.
- */
-this.STK_TERMINAL_PROFILE_DOWNLOAD =
- (STK_TERMINAL_SUPPORT_PROFILE_DOWNLOAD << 0) |
- (STK_TERMINAL_SUPPORT_SMS_PP_DOWNLOAD << 1) |
- (STK_TERMINAL_SUPPORT_CELL_BROADCAST_DATA_DOWNLOAD << 2) |
- (STK_TERMINAL_SUPPORT_MENU_SELECTION << 3) |
- (STK_TERMINAL_SUPPORT_SIM_DATA_DOWNLOAD_ERROR << 4) |
- (STK_TERMINAL_SUPPORT_TIMER_EXPIRATION << 5) |
- (STK_TERMINAL_SUPPORT_USSD_IN_CALL_CONTROL << 6) |
- (STK_TERMINAL_SUPPORT_CALL_CONTROL_IN_REDIAL << 7);
-
-this.STK_TERMINAL_PROFILE_OTHER =
- (STK_TERMINAL_SUPPORT_COMMAND_RESULT << 0) |
- (STK_TERMINAL_SUPPORT_CALL_CONTROL << 1) |
- (STK_TERMINAL_SUPPORT_CALL_ID_INCLUDED << 2) |
- (STK_TERMINAL_SUPPORT_MO_SMS_CONTROL << 3) |
- (STK_TERMINAL_SUPPORT_ALPHA_ID_INDICATION << 4) |
- (STK_TERMINAL_SUPPORT_UCS2_ENTRY << 5) |
- (STK_TERMINAL_SUPPORT_UCS2_DISPLAY << 6) |
- (STK_TERMINAL_SUPPORT_EXTENSION_TEXT << 7);
-
-this.STK_TERMINAL_PROFILE_PROACTIVE_1 =
- (STK_TERMINAL_SUPPORT_PROACTIVE_DISPLAY_TEXT << 0) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_GET_INKEY << 1) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_GET_INPUT << 2) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_MORE_TIME << 3) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_PLAY_TONE << 4) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_POLL_INTERVAL << 5) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_POLL_OFF << 6) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_REFRESH << 7);
-
-this.STK_TERMINAL_PROFILE_PROACTIVE_2 =
- (STK_TERMINAL_SUPPORT_PROACTIVE_SELECT_ITEM << 0) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_SEND_SMS << 1) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_SEND_SS << 2) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_SEND_USSD << 3) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_SET_UP_CALL << 4) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_SET_UP_MENU << 5) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO << 6) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_NMR << 7);
-
-this.STK_TERMINAL_PROFILE_EVENT =
- (STK_TERMINAL_SUPPORT_PROACTIVE_SET_UP_EVENT_LIST << 0) |
- (STK_TERMINAL_SUPPORT_EVENT_MT_CALL << 1) |
- (STK_TERMINAL_SUPPORT_EVENT_CALL_CONNECTED << 2) |
- (STK_TERMINAL_SUPPORT_EVENT_CALL_DISCONNECTED << 3) |
- (STK_TERMINAL_SUPPORT_EVENT_LOCATION_STATUS << 4) |
- (STK_TERMINAL_SUPPORT_EVENT_USER_ACTIVITY << 5) |
- (STK_TERMINAL_SUPPORT_EVENT_IDLE_SCREEN_AVAILABLE << 6) |
- (STK_TERMINAL_SUPPORT_EVENT_CARD_READER_STATUS << 7);
-
-this.STK_TERMINAL_PROFILE_EVENT_EXT =
- (STK_TERMINAL_SUPPORT_EVENT_LANGUAGE_SELECTION << 0) |
- (STK_TERMINAL_SUPPORT_EVENT_BROWSER_TERMINATION << 1) |
- (STK_TERMINAL_SUPPORT_EVENT_DATA_AVAILABLE << 2) |
- (STK_TERMINAL_SUPPORT_EVENT_CHANNEL_STATUS << 3);
-
-this.STK_TERMINAL_PROFILE_PROACTIVE_3 =
- (STK_TERMINAL_SUPPORT_PROACTIVE_TIMER_START_STOP << 0) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_TIMER_GET_CURRENT << 1) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_DATE << 2) |
- (STK_TERMINAL_SUPPORT_GET_INKEY << 3) |
- (STK_TERMINAL_SUPPORT_SET_UP_IDLE_MODE_TEXT << 4) |
- (STK_TERMINAL_SUPPORT_RUN_AT_COMMAND << 5) |
- (STK_TERMINAL_SUPPORT_SET_UP_CALL << 6) |
- (STK_TERMINAL_SUPPORT_CALL_CONTROL_BY_NNA << 7);
-
-this.STK_TERMINAL_PROFILE_PROACTIVE_4 =
- (STK_TERMINAL_SUPPORT_DISPLAY_TEXT << 0) |
- (STK_TERMINAL_SUPPORT_SEND_DTMF_COMMAND << 1) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_NMR << 2) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_LANGUAGE << 3) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_TIME_ADVANCE << 4) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LANGUAGE_NOTIFICATION << 5) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LAUNCH_BROWSER << 6) |
- (STK_TERMINAL_SUPPORT_PROACTIVE_LOCAL_INFO_ACCESS_TECH << 7);
-
-this.STK_TERMINAL_PROFILE_BIP_COMMAND =
- (STK_TERMINAL_SUPPORT_BIP_COMMAND_OPEN_CHANNEL << 0) |
- (STK_TERMINAL_SUPPORT_BIP_COMMAND_CLOSE_CHANNEL << 1) |
- (STK_TERMINAL_SUPPORT_BIP_COMMAND_RECEIVE_DATA << 2) |
- (STK_TERMINAL_SUPPORT_BIP_COMMAND_SEND_DATA << 3) |
- (STK_TERMINAL_SUPPORT_BIP_COMMAND_GET_CHANNEL_STATUS << 4);
-
-this.STK_SUPPORTED_TERMINAL_PROFILE = [
- STK_TERMINAL_PROFILE_DOWNLOAD,
- STK_TERMINAL_PROFILE_OTHER,
- STK_TERMINAL_PROFILE_PROACTIVE_1,
- STK_TERMINAL_PROFILE_PROACTIVE_2,
- STK_TERMINAL_PROFILE_EVENT,
- STK_TERMINAL_PROFILE_EVENT_EXT, // Event extension
- 0x00, // Multiple card proactive commands
- STK_TERMINAL_PROFILE_PROACTIVE_3,
- STK_TERMINAL_PROFILE_PROACTIVE_4,
- 0x00, // Softkey support
- 0x00, // Softkey information
- STK_TERMINAL_PROFILE_BIP_COMMAND,
- 0x00, // BIP supported bearers
- 0x00, // Screen height
- 0x00, // Screen width
- 0x00, // 16, Screen effects
- 0x00, // 17, BIP supported transport interface
- 0x00, // 18, RFU
- 0x00, // 19, RFU
- 0x00, // 20, RFU
-];
-
-/**
- * ICC Services Table.
- *
- * @see 3GPP TS 51.011 10.3.7 (SIM) and 3GPP TS 31.102 4.2.8 (USIM).
- */
-this.GECKO_ICC_SERVICES = {
- // @see 3GPP TS 51.011 10.3.7 (SIM).
- sim: {
- ADN: 2,
- FDN: 3,
- PLMNSEL: 7,
- MSISDN: 9,
- EXT1: 10,
- EXT2: 11,
- CBMI: 14,
- GID1: 15,
- SPN: 17,
- SDN: 18,
- EXT3: 19,
- DATA_DOWNLOAD_SMS_CB: 25,
- DATA_DOWNLOAD_SMS_PP: 26,
- CBMIR: 30,
- BDN: 31,
- IMG: 39,
- PNN: 51,
- OPL: 52,
- MDN: 53,
- MWIS: 54,
- SPDI: 56
- },
- // @see 3GPP TS 31.102 4.2.8 (USIM).
- usim: {
- FDN: 2,
- EXT2: 3,
- SDN: 4,
- EXT3: 5,
- BDN: 6,
- CBMI: 15,
- CBMIR: 16,
- GID1: 17,
- SPN: 19,
- MSISDN: 21,
- IMG: 22,
- DATA_DOWNLOAD_SMS_PP: 28,
- DATA_DOWNLOAD_SMS_CB: 29,
- PNN: 45,
- OPL: 46,
- MDN: 47,
- MWIS: 48,
- SPDI: 51
- },
- // @see 3GPP2 C.S0023-D 3.4.18 (RUIM).
- ruim: {
- FDN: 3,
- ENHANCED_PHONEBOOK: 6,
- EXT1: 10,
- EXT2: 11,
- SPN: 17,
- SDN: 18,
- EXT3: 19,
- },
- // @see B.3.1.1 CPHS Information in CPHS Phase 2:
- // Indicates which of the CPHS 'optional' data-fields are present in the SIM card:
- // EF_CPHS_CSP, EF_CPHS_SST, EF_CPHS_MBN, EF_CPHS_ONSF, EF_CPHS_INFO_NUM
- // Note: Mandatory EFs are: (B.3.1 Enhanced SIM Requirements)
- // EF_CPHS_CFF, EF_CPHS_VMI, EF_CPHS_ONS, EF_CPHS_INFO
- cphs: {
- CSP: 1,
- SST: 2,
- MBN: 3,
- ONSF: 4,
- INFO_NUM: 5
- }
-};
-
-/**
- * Cell Broadcast constants
- */
-
-this.CB_FORMAT_GSM = 0;
-this.CB_FORMAT_ETWS = 1;
-this.CB_FORMAT_CMAS = 2;
-this.CB_FORMAT_UMTS = 3;
-
-// CBS Data Coding Scheme: Language groups
-// see 3GPP TS 23.038 section 5
-this.CB_DCS_LANG_GROUP_1 = [
- "de", "en", "it", "fr", "es", "nl", "sv", "da", "pt", "fi",
- "no", "el", "tr", "hu", "pl", null
-];
-this.CB_DCS_LANG_GROUP_2 = [
- "cs", "he", "ar", "ru", "is", null, null, null, null, null,
- null, null, null, null, null, null
-];
-
-// See 3GPP TS 23.041 v11.2.0 section 9.4.1.2.2
-this.CB_NON_MMI_SETTABLE_RANGES = [
- /*0x1000 - 0x107F*/4096, 4224, /*0x1080 - 0x10FF*/4224, 4352,
- /*0x1112 - 0x1112*/4370, 4371, /*0x111F - 0x111F*/4383, 4384,
- /*0xF000 - 0xFFFE*/61440, 65535, /*0xFFFF - 0xFFFF*/65535, 65536
-];
-
-// User Data max length in septets
-this.CB_MAX_CONTENT_7BIT = 93;
-// User Data max length in octets
-this.CB_MAX_CONTENT_8BIT = 82;
-// User Data max length in chars
-this.CB_MAX_CONTENT_UCS2 = 41;
-
-// See 3GPP TS 23.041 v11.6.0 senction 9.3.19
-this.CB_MSG_PAGE_INFO_SIZE = 82;
-
-this.CB_MESSAGE_SIZE_ETWS = 56;
-this.CB_MESSAGE_SIZE_GSM = 88;
-this.CB_MESSAGE_SIZE_UMTS_MIN = 90;
-this.CB_MESSAGE_SIZE_UMTS_MAX = 1252;
-
-
-
-// GSM Cell Broadcast Geographical Scope
-// See 3GPP TS 23.041 clause 9.4.1.2.1
-this.CB_GSM_GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE = 0;
-this.CB_GSM_GEOGRAPHICAL_SCOPE_PLMN_WIDE = 1;
-this.CB_GSM_GEOGRAPHICAL_SCOPE_LOCATION_AREA_WIDE = 2;
-this.CB_GSM_GEOGRAPHICAL_SCOPE_CELL_WIDE = 3;
-
-// GSM Cell Broadcast Geographical Scope
-// See 3GPP TS 23.041 clause 9.4.1.2.1
-this.CB_GSM_GEOGRAPHICAL_SCOPE_NAMES = [
- "cell-immediate",
- "plmn",
- "location-area",
- "cell"
-];
-
-// GSM Cell Broadcast Message Identifiers
-// see 3GPP TS 23.041 clause 9.4.1.2.2
-this.CB_GSM_MESSAGEID_ETWS_BEGIN = 0x1100;
-this.CB_GSM_MESSAGEID_ETWS_END = 0x1107;
-
-// ETWS Warning-Type
-// see 3GPP TS 23.041 clause 9.3.24
-this.CB_ETWS_WARNING_TYPE_NAMES = [
- "earthquake",
- "tsunami",
- "earthquake-tsunami",
- "test",
- "other"
-];
-
-// UMTS Message Type
-// see 3GPP TS 25.324 section 11.1
-this.CB_UMTS_MESSAGE_TYPE_CBS = 1;
-this.CB_UMTS_MESSAGE_TYPE_SCHEDULE = 2;
-this.CB_UMTS_MESSAGE_TYPE_CBS41 = 3;
-
-/**
- * Number plan identification defined in
- * |Table 10.5.118: Called party BCD number| of 3GPP TS 24.008.
- */
-this.CALLED_PARTY_BCD_NPI_UNKNOWN = 0;
-this.CALLED_PARTY_BCD_NPI_ISDN = 1;
-this.CALLED_PARTY_BCD_NPI_DATA = 3;
-this.CALLED_PARTY_BCD_NPI_TELEX = 4;
-this.CALLED_PARTY_BCD_NPI_NATIONAL = 8;
-this.CALLED_PARTY_BCD_NPI_PRIVATE = 9;
-
-/**
- * Array of number plan identification values which can be used to map an
- * enumeration to the corresponding value. The indices should be consistent
- * with nsISmsService::NUMBER_PLAN_IDENTIFICATION_* constants.
- */
-this.CALLED_PARTY_BCD_NPI = [
- CALLED_PARTY_BCD_NPI_UNKNOWN,
- CALLED_PARTY_BCD_NPI_ISDN,
- CALLED_PARTY_BCD_NPI_DATA,
- CALLED_PARTY_BCD_NPI_TELEX,
- CALLED_PARTY_BCD_NPI_NATIONAL,
- CALLED_PARTY_BCD_NPI_PRIVATE
-];
-
-/**
- * GSM PDU constants
- */
-
-// PDU TYPE-OF-ADDRESS
-this.PDU_TOA_UNKNOWN = 0x80; // Unknown. This is used when the user or
- // network has no a priori information
- // about the numbering plan.
-this.PDU_TOA_ISDN = 0x81; // ISDN/Telephone numbering
-this.PDU_TOA_DATA_NUM = 0x83; // Data numbering plan
-this.PDU_TOA_TELEX_NUM = 0x84; // Telex numbering plan
-this.PDU_TOA_NATIONAL_NUM = 0x88; // National numbering plan
-this.PDU_TOA_PRIVATE_NUM = 0x89; // Private numbering plan
-this.PDU_TOA_ERMES_NUM = 0x8A; // Ermes numbering plan
-this.PDU_TOA_INTERNATIONAL = 0x90; // International number
-this.PDU_TOA_NATIONAL = 0xA0; // National number. Prefix or escape digits
- // shall not be included
-this.PDU_TOA_NETWORK_SPEC = 0xB0; // Network specific number This is used to
- // indicate administration/service number
- // specific to the serving network
-this.PDU_TOA_SUBSCRIBER = 0xC0; // Subscriber number. This is used when a
- // specific short number representation is
- // stored in one or more SCs as part of a
- // higher layer application
-this.PDU_TOA_ALPHANUMERIC = 0xD0; // Alphanumeric, (coded according to GSM TS
- // 03.38 7-bit default alphabet)
-this.PDU_TOA_ABBREVIATED = 0xE0; // Abbreviated number
-
-/**
- * First octet of the SMS-DELIVER PDU
- *
- * RP: 0 Reply Path parameter is not set in this PDU
- * 1 Reply Path parameter is set in this PDU
- *
- * UDHI: 0 The UD field contains only the short message
- * 1 The beginning of the UD field contains a header in addition of
- * the short message
- *
- * SRI: (is only set by the SMSC)
- * 0 A status report will not be returned to the SME
- * 1 A status report will be returned to the SME
- *
- * MMS: (is only set by the SMSC)
- * 0 More messages are waiting for the MS in the SMSC
- * 1 No more messages are waiting for the MS in the SMSC
- *
- * MTI: bit1 bit0 Message type
- * 0 0 SMS-DELIVER (SMSC ==> MS)
- * 0 0 SMS-DELIVER REPORT (MS ==> SMSC, is generated
- * automatically by the M20, after receiving a
- * SMS-DELIVER)
- * 0 1 SMS-SUBMIT (MS ==> SMSC)
- * 0 1 SMS-SUBMIT REPORT (SMSC ==> MS)
- * 1 0 SMS-STATUS REPORT (SMSC ==> MS)
- * 1 0 SMS-COMMAND (MS ==> SMSC)
- * 1 1 Reserved
- */
-this.PDU_RP = 0x80; // Reply path. Parameter indicating that
- // reply path exists.
-this.PDU_UDHI = 0x40; // User data header indicator. This bit is
- // set to 1 if the User Data field starts
- // with a header
-this.PDU_SRI_SRR = 0x20; // Status report indication (SMS-DELIVER)
- // or request (SMS-SUBMIT)
-this.PDU_VPF_ABSOLUTE = 0x18;// Validity period aboslute format
- // (SMS-SUBMIT only)
-this.PDU_VPF_RELATIVE = 0x10;// Validity period relative format
- // (SMS-SUBMIT only)
-this.PDU_VPF_ENHANCED = 0x8; // Validity period enhance format
- // (SMS-SUBMIT only)
-this.PDU_MMS_RD = 0x04;// More messages to send. (SMS-DELIVER only) or
- // Reject duplicates (SMS-SUBMIT only)
-
-// MTI - Message Type Indicator
-this.PDU_MTI_SMS_RESERVED = 0x03;
-this.PDU_MTI_SMS_STATUS_REPORT = 0x02;
-this.PDU_MTI_SMS_COMMAND = 0x02;
-this.PDU_MTI_SMS_SUBMIT = 0x01;
-this.PDU_MTI_SMS_DELIVER = 0x00;
-
-// PI - Parameter Indicator
-this.PDU_PI_EXTENSION = 0x80;
-this.PDU_PI_USER_DATA_LENGTH = 0x04;
-this.PDU_PI_DATA_CODING_SCHEME = 0x02;
-this.PDU_PI_PROTOCOL_IDENTIFIER = 0x01;
-this.PDU_PI_RESERVED = 0x78;
-
-// FCS - Failure Cause
-// 0...127 see 3GPP TS 24.011 clause E.2
-// 128...255 see 3GPP TS 23.040 clause 9.2.3.22
-// others see 3GPP TS 27.005 clause 3.2.5
-this.PDU_FCS_OK = 0x00;
-this.PDU_FCS_PROTOCOL_ERROR = 0x6F;
-this.PDU_FCS_MEMORY_CAPACITY_EXCEEDED = 0XD3;
-this.PDU_FCS_USAT_BUSY = 0XD4;
-this.PDU_FCS_USIM_DATA_DOWNLOAD_ERROR = 0xD5;
-this.PDU_FCS_RESERVED = 0xE0;
-this.PDU_FCS_UNSPECIFIED = 0xFF;
-// Special internal value that means we should not acknowledge an
-// incoming text right away, but need to wait for other components
-// (e.g. storage) to complete. This can be any value, so long it
-// doesn't conflict with the PDU_FCS_* constants above.
-this.MOZ_FCS_WAIT_FOR_EXPLICIT_ACK = 0x0F;
-
-// ST - Status
-// Bit 7..0 = 000xxxxx, short message transaction completed
-this.PDU_ST_0_RECEIVED = 0x00;
-this.PDU_ST_0_FORWARDED_NO_CONFIRM = 0x01;
-this.PDU_ST_0_REPLACED_BY_SC = 0x02;
-this.PDU_ST_0_RESERVED_BEGIN = 0x03;
-this.PDU_ST_0_SC_SPECIFIC_BEGIN = 0x10;
-this.PDU_ST_0_SC_SPECIFIC_END = 0x1F;
-// Bit 7..0 = 001xxxxx, temporary error, SC still trying to transfer SM
-this.PDU_ST_1_CONGESTION = 0x20;
-this.PDU_ST_1_SME_BUSY = 0x21;
-this.PDU_ST_1_SME_NO_RESPONSE = 0x22;
-this.PDU_ST_1_SERVICE_REJECTED = 0x23;
-this.PDU_ST_1_QOS_UNAVAILABLE = 0x24;
-this.PDU_ST_1_SME_ERROR = 0x25;
-this.PDU_ST_1_RESERVED_BEGIN = 0x26;
-this.PDU_ST_1_SC_SPECIFIC_BEGIN = 0x30;
-this.PDU_ST_1_SC_SPECIFIC_END = 0x3F;
-// Bit 7..0 = 010xxxxx, permanent error, SC is not making any more transfer
-// attempts
-this.PDU_ST_2_RPC_ERROR = 0x40;
-this.PDU_ST_2_DEST_INCOMPATIBLE = 0x41;
-this.PDU_ST_2_CONNECTION_REJECTED = 0x42;
-this.PDU_ST_2_NOT_OBTAINABLE = 0x43;
-this.PDU_ST_2_QOS_UNAVAILABLE = 0x44;
-this.PDU_ST_2_INTERWORKING_UNAVALIABLE = 0x45;
-this.PDU_ST_2_VALIDITY_EXPIRED = 0x46;
-this.PDU_ST_2_DELETED_BY_SME = 0x47;
-this.PDU_ST_2_DELETED_BY_SC = 0x48;
-this.PDU_ST_2_SM_MISSING = 0x49;
-this.PDU_ST_2_RESERVED_BEGIN = 0x4A;
-this.PDU_ST_2_SC_SPECIFIC_BEGIN = 0x50;
-this.PDU_ST_2_SC_SPECIFIC_END = 0x5F;
-// Bit 7..0 = 011xxxxx, temporary error, SC is not making any more transfer
-// attempts
-this.PDU_ST_3_CONGESTION = 0x60;
-this.PDU_ST_3_SME_BUSY = 0x61;
-this.PDU_ST_3_SME_NO_RESPONSE = 0x62;
-this.PDU_ST_3_SERVICE_REJECTED = 0x63;
-this.PDU_ST_3_QOS_UNAVAILABLE = 0x64;
-this.PDU_ST_3_SME_ERROR = 0x65;
-this.PDU_ST_3_RESERVED_BEGIN = 0x66;
-this.PDU_ST_3_SC_SPECIFIC_BEGIN = 0x70;
-this.PDU_ST_3_SC_SPECIFIC_END = 0x7F;
-
-this.GECKO_SMS_DELIVERY_STATUS_NOT_APPLICABLE = "not-applicable";
-this.GECKO_SMS_DELIVERY_STATUS_SUCCESS = "success";
-this.GECKO_SMS_DELIVERY_STATUS_PENDING = "pending";
-this.GECKO_SMS_DELIVERY_STATUS_ERROR = "error";
-
-// User Data max length in septets
-this.PDU_MAX_USER_DATA_7BIT = 160;
-// User Data max length in octets
-this.PDU_MAX_USER_DATA_8BIT = 140;
-// User Data max length in chars
-this.PDU_MAX_USER_DATA_UCS2 = 70;
-
-// PID - Protocol Indicator
-this.PDU_PID_DEFAULT = 0x00;
-this.PDU_PID_TELEMATIC_INTERWORKING = 0x20;
-this.PDU_PID_SHORT_MESSAGE_TYPE_0 = 0x40;
-this.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_1 = 0x41;
-this.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_2 = 0x42;
-this.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_3 = 0x43;
-this.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_4 = 0x44;
-this.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_5 = 0x45;
-this.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_6 = 0x46;
-this.PDU_PID_REPLACE_SHORT_MESSAGE_TYPE_7 = 0x47;
-this.PDU_PID_ENHANDED_MESSAGE_SERVICE = 0x5E;
-this.PDU_PID_RETURN_CALL_MESSAGE = 0x5F;
-this.PDU_PID_ANSI_136_R_DATA = 0x7C;
-this.PDU_PID_ME_DATA_DOWNLOAD = 0x7D;
-this.PDU_PID_ME_DEPERSONALIZATION = 0x7E;
-this.PDU_PID_USIM_DATA_DOWNLOAD = 0x7F;
-
-// DCS - Data Coding Scheme
-this.PDU_DCS_MSG_CODING_7BITS_ALPHABET = 0x00;
-this.PDU_DCS_MSG_CODING_8BITS_ALPHABET = 0x04;
-this.PDU_DCS_MSG_CODING_16BITS_ALPHABET = 0x08;
-this.PDU_DCS_MSG_CLASS_0 = 0x00;
-this.PDU_DCS_MSG_CLASS_1 = 0x01;
-this.PDU_DCS_MSG_CLASS_2 = 0x02;
-this.PDU_DCS_MSG_CLASS_3 = 0x03;
-this.PDU_DCS_MSG_CLASS_USER_1 = 0x04;
-this.PDU_DCS_MSG_CLASS_USER_2 = 0x05;
-this.PDU_DCS_MSG_CLASS_NORMAL = 0x06;
-this.PDU_DCS_CODING_GROUP_BITS = 0xF0;
-this.PDU_DCS_MSG_CLASS_BITS = 0x03;
-this.PDU_DCS_MWI_ACTIVE_BITS = 0x08;
-this.PDU_DCS_MWI_ACTIVE_VALUE = 0x08;
-this.PDU_DCS_MWI_TYPE_BITS = 0x03;
-this.PDU_DCS_MWI_TYPE_VOICEMAIL = 0x00;
-this.PDU_DCS_MWI_TYPE_FAX = 0x01;
-this.PDU_DCS_MWI_TYPE_EMAIL = 0x02;
-this.PDU_DCS_MWI_TYPE_OTHER = 0x03;
-
-// Set as Array instead of Object for reversed-mapping with Array.indexOf().
-this.GECKO_SMS_MESSAGE_CLASSES = [];
-GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_0] = "class-0";
-GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_1] = "class-1";
-GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_2] = "class-2";
-GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_3] = "class-3";
-GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_USER_1] = "user-1";
-GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_USER_2] = "user-2";
-GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL] = "normal";
-
-// Because service center timestamp omit the century. Yay.
-this.PDU_TIMESTAMP_YEAR_OFFSET = 2000;
-
-// See 9.2.3.24 TP‑User Data (TP‑UD)
-this.PDU_IEI_CONCATENATED_SHORT_MESSAGES_8BIT = 0x00;
-this.PDU_IEI_SPECIAL_SMS_MESSAGE_INDICATION = 0x01;
-this.PDU_IEI_APPLICATION_PORT_ADDRESSING_SCHEME_8BIT = 0x04;
-this.PDU_IEI_APPLICATION_PORT_ADDRESSING_SCHEME_16BIT = 0x05;
-this.PDU_IEI_SMSC_CONTROL_PARAMS = 0x06;
-this.PDU_IEI_UDH_SOURCE_INDICATOR = 0x07;
-this.PDU_IEI_CONCATENATED_SHORT_MESSAGES_16BIT = 0x08;
-this.PDU_IEI_WIRELESS_CONTROL_MESSAGE_PROTOCOL = 0x09;
-this.PDU_IEI_TEXT_FORMATING = 0x0A;
-this.PDU_IEI_PREDEFINED_SOUND = 0x0B;
-this.PDU_IEI_USER_DATA_SOUND = 0x0C;
-this.PDU_IEI_PREDEFINED_ANIMATION = 0x0D;
-this.PDU_IEI_LARGE_ANIMATION = 0x0E;
-this.PDU_IEI_SMALL_ANIMATION = 0x0F;
-this.PDU_IEI_LARGE_PICTURE = 0x10;
-this.PDU_IEI_SMALL_PICTURE = 0x11;
-this.PDU_IEI_VARIABLE_PICTURE = 0x12;
-this.PDU_IEI_USER_PROMPT_INDICATOR = 0x13;
-this.PDU_IEI_EXTENDED_OBJECT = 0x14;
-this.PDU_IEI_REUSED_EXTENDED_OBJECT = 0x15;
-this.PDU_IEI_COMPRESS_CONTROL = 0x16;
-this.PDU_IEI_OBJECT_DISTRIBUTION_INDICATOR = 0x17;
-this.PDU_IEI_STANDARD_WVG_OBJECT = 0x18;
-this.PDU_IEI_CHARACTER_SIZE_WVG_OBJECT = 0x19;
-this.PDU_IEI_EXTENDED_OBJECT_DATA_REQUEST_COMMAND = 0x1A;
-this.PDU_IEI_RFC822_EMAIL_HEADER = 0x20;
-this.PDU_IEI_HYPERLINK_FORMAT_ELEMENT = 0x21;
-this.PDU_IEI_REPLY_ADDRESS_ELEMENT = 0x22;
-this.PDU_IEI_ENHANCED_VOICE_MAIL_INFORMATION = 0x23;
-this.PDU_IEI_NATIONAL_LANGUAGE_SINGLE_SHIFT = 0x24;
-this.PDU_IEI_NATIONAL_LANGUAGE_LOCKING_SHIFT = 0x25;
-
-// Application Port Addressing, see 3GPP TS 23.040 9.2.3.24.3
-this.PDU_APA_RESERVED_8BIT_PORTS = 240;
-this.PDU_APA_VALID_16BIT_PORTS = 49152;
-
-// 7bit alphabet escape character. The encoded value of this code point is left
-// undefined in official spec. Its code value is internally assigned to \uffff,
-// <noncharacter-FFFF> in Unicode basic multilingual plane.
-this.PDU_NL_EXTENDED_ESCAPE = 0x1B;
-
-// <SP>, <LF>, <CR> are only defined in locking shift tables.
-this.PDU_NL_SPACE = 0x20;
-this.PDU_NL_LINE_FEED = 0x0A;
-this.PDU_NL_CARRIAGE_RETURN = 0x0D;
-
-// 7bit alphabet page break character, only defined in single shift tables.
-// The encoded value of this code point is left undefined in official spec, but
-// the code point itself maybe be used for example in compressed CBS messages.
-// Its code value is internally assigned to \u000c, ASCII form feed, or new page.
-this.PDU_NL_PAGE_BREAK = 0x0A;
-// 7bit alphabet reserved control character, only defined in single shift
-// tables. The encoded value of this code point is left undefined in official
-// spec. Its code value is internally assigned to \ufffe, <noncharacter-FFFE>
-// in Unicode basic multilingual plane.
-this.PDU_NL_RESERVED_CONTROL = 0x0D;
-
-this.PDU_NL_IDENTIFIER_DEFAULT = 0;
-this.PDU_NL_IDENTIFIER_TURKISH = 1;
-this.PDU_NL_IDENTIFIER_SPANISH = 2;
-this.PDU_NL_IDENTIFIER_PORTUGUESE = 3;
-this.PDU_NL_IDENTIFIER_BENGALI = 4;
-this.PDU_NL_IDENTIFIER_GUJARATI = 5;
-this.PDU_NL_IDENTIFIER_HINDI = 6;
-this.PDU_NL_IDENTIFIER_KANNADA = 7;
-this.PDU_NL_IDENTIFIER_MALAYALAM = 8;
-this.PDU_NL_IDENTIFIER_ORIYA = 9;
-this.PDU_NL_IDENTIFIER_PUNJABI = 10;
-this.PDU_NL_IDENTIFIER_TAMIL = 11;
-this.PDU_NL_IDENTIFIER_TELUGU = 12;
-this.PDU_NL_IDENTIFIER_URDU = 13;
-
-// The mapping of mcc and their extra GSM national language locking / single
-// shift table tuples to enable. The default GSM alphabet and extension table
-// are always enabled and need not to be list here.
-//
-// The content should be updated when a relevant national regulatory body
-// requests. See 'NOTE 2' of 6.2.1.2.5 in 3GPP TS 23.038:
-// "
-// Encoding of a message using the national locking shift mechanism is not
-// intended to be implemented until a formal request is issued by the
-// relevant national regulatory body. This is because a receiving entity
-// not supporting the relevant locking-shift decoding will present different
-// characters from the ones intended by the sending entity.
-// "
-this.PDU_MCC_NL_TABLE_TUPLES_MAPPING = {
- // Configuration for Turkey.
- //
- // The Turkish single shift table contains 7 extra characters
- // (Ğ, İ, Ş, ç, ğ, ı, ş) than the GSM default alphabet extension table. Since
- // all the 7 characters are also included in Turkish locking shift table, it's
- // not necessary to enable Turkish single shift table. Using GSM default
- // alphabet extension table instead saves 3 octets when these extension table
- // characters present in a message.
- 286: [[PDU_NL_IDENTIFIER_TURKISH, PDU_NL_IDENTIFIER_DEFAULT]]
-};
-
-/*
- * 3GPP TS 23.038 - 6.2.1 GSM 7 bit Default Alphabet
- */
-this.PDU_NL_GSM_DEFAULT_ALPHABET =
- // 01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....
- "@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5"
- // 0.....12.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\uffff\u00c6\u00e6\u00df\u00c9"
- // 012.34.....56789ABCDEF
- + " !\"#\u00a4%&'()*+,-./"
- // 0123456789ABCDEF
- + "0123456789:;<=>?"
- // 0.....123456789ABCDEF
- + "\u00a1ABCDEFGHIJKLMNO"
- // 0123456789AB.....C.....D.....E.....F.....
- + "PQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc\u00a7"
- // 0.....123456789ABCDEF
- + "\u00bfabcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0";
-
-// National Language Locking Shift Tables, see 3GPP TS 23.038
-this.PDU_NL_LOCKING_SHIFT_TABLES = [
- /**
- * National Language Identifier: 0x00
- * 6.2.1 GSM 7 bit Default Alphabet
- */
- PDU_NL_GSM_DEFAULT_ALPHABET,
-
- /**
- * National Language Identifier: 0x01
- * A.3.1 Turkish National Language Locking Shift Table
- */
- // 01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....
- "@\u00a3$\u00a5\u20ac\u00e9\u00f9\u0131\u00f2\u00c7\n\u011e\u011f\r\u00c5\u00e5"
- // 0.....12.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\uffff\u015e\u015f\u00df\u00c9"
- // 012.34.....56789ABCDEF
- + " !\"#\u00a4%&'()*+,-./"
- // 0123456789ABCDEF
- + "0123456789:;<=>?"
- // 0.....123456789ABCDEF
- + "\u0130ABCDEFGHIJKLMNO"
- // 0123456789AB.....C.....D.....E.....F.....
- + "PQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc\u00a7"
- // 0.....123456789ABCDEF
- + "\u00e7abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0",
-
- /**
- * National Language Identifier: 0x02
- * A.3.2 Void
- * Fallback to GSM Default Alphabet
- */
- PDU_NL_GSM_DEFAULT_ALPHABET,
-
- /**
- * National Language Identifier: 0x03
- * A.3.3 Portuguese National Language Locking Shift Table
- */
- // 01.....23.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....
- "@\u00a3$\u00a5\u00ea\u00e9\u00fa\u00ed\u00f3\u00e7\n\u00d4\u00f4\r\u00c1\u00e1"
- // 0.....12.....3.....4.....5.....67.8.....9.....AB.....C.....D.....E.....F.....
- + "\u0394_\u00aa\u00c7\u00c0\u221e^\\\u20ac\u00d3|\uffff\u00c2\u00e2\u00ca\u00c9"
- // 012.34.....56789ABCDEF
- + " !\"#\u00ba%&'()*+,-./"
- // 0123456789ABCDEF
- + "0123456789:;<=>?"
- // 0.....123456789ABCDEF
- + "\u00cdABCDEFGHIJKLMNO"
- // 0123456789AB.....C.....D.....E.....F.....
- + "PQRSTUVWXYZ\u00c3\u00d5\u00da\u00dc\u00a7"
- // 0123456789ABCDEF
- + "~abcdefghijklmno"
- // 0123456789AB.....C.....DE.....F.....
- + "pqrstuvwxyz\u00e3\u00f5`\u00fc\u00e0",
-
- /**
- * National Language Identifier: 0x04
- * A.3.4 Bengali National Language Locking Shift Table
- */
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.EF.....
- "\u0981\u0982\u0983\u0985\u0986\u0987\u0988\u0989\u098a\u098b\n\u098c \r \u098f"
- // 0.....123.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0990 \u0993\u0994\u0995\u0996\u0997\u0998\u0999\u099a\uffff\u099b\u099c\u099d\u099e"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u099f\u09a0\u09a1\u09a2\u09a3\u09a4)(\u09a5\u09a6,\u09a7.\u09a8"
- // 0123456789ABCD.....E.....F
- + "0123456789:; \u09aa\u09ab?"
- // 0.....1.....2.....3.....4.....56.....789A.....B.....C.....D.....E.....F.....
- + "\u09ac\u09ad\u09ae\u09af\u09b0 \u09b2 \u09b6\u09b7\u09b8\u09b9\u09bc\u09bd"
- // 0.....1.....2.....3.....4.....5.....6.....789.....A.....BCD.....E.....F.....
- + "\u09be\u09bf\u09c0\u09c1\u09c2\u09c3\u09c4 \u09c7\u09c8 \u09cb\u09cc\u09cd"
- // 0.....123456789ABCDEF
- + "\u09ceabcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u09d7\u09dc\u09dd\u09f0\u09f1",
-
- /**
- * National Language Identifier: 0x05
- * A.3.5 Gujarati National Language Locking Shift Table
- */
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.EF.....
- "\u0a81\u0a82\u0a83\u0a85\u0a86\u0a87\u0a88\u0a89\u0a8a\u0a8b\n\u0a8c\u0a8d\r \u0a8f"
- // 0.....1.....23.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0a90\u0a91 \u0a93\u0a94\u0a95\u0a96\u0a97\u0a98\u0a99\u0a9a\uffff\u0a9b\u0a9c\u0a9d\u0a9e"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u0a9f\u0aa0\u0aa1\u0aa2\u0aa3\u0aa4)(\u0aa5\u0aa6,\u0aa7.\u0aa8"
- // 0123456789ABCD.....E.....F
- + "0123456789:; \u0aaa\u0aab?"
- // 0.....1.....2.....3.....4.....56.....7.....89.....A.....B.....C.....D.....E.....F.....
- + "\u0aac\u0aad\u0aae\u0aaf\u0ab0 \u0ab2\u0ab3 \u0ab5\u0ab6\u0ab7\u0ab8\u0ab9\u0abc\u0abd"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....B.....CD.....E.....F.....
- + "\u0abe\u0abf\u0ac0\u0ac1\u0ac2\u0ac3\u0ac4\u0ac5 \u0ac7\u0ac8\u0ac9 \u0acb\u0acc\u0acd"
- // 0.....123456789ABCDEF
- + "\u0ad0abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0ae0\u0ae1\u0ae2\u0ae3\u0af1",
-
- /**
- * National Language Identifier: 0x06
- * A.3.6 Hindi National Language Locking Shift Table
- */
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....
- "\u0901\u0902\u0903\u0905\u0906\u0907\u0908\u0909\u090a\u090b\n\u090c\u090d\r\u090e\u090f"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0910\u0911\u0912\u0913\u0914\u0915\u0916\u0917\u0918\u0919\u091a\uffff\u091b\u091c\u091d\u091e"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u091f\u0920\u0921\u0922\u0923\u0924)(\u0925\u0926,\u0927.\u0928"
- // 0123456789ABC.....D.....E.....F
- + "0123456789:;\u0929\u092a\u092b?"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u092c\u092d\u092e\u092f\u0930\u0931\u0932\u0933\u0934\u0935\u0936\u0937\u0938\u0939\u093c\u093d"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u093e\u093f\u0940\u0941\u0942\u0943\u0944\u0945\u0946\u0947\u0948\u0949\u094a\u094b\u094c\u094d"
- // 0.....123456789ABCDEF
- + "\u0950abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0972\u097b\u097c\u097e\u097f",
-
- /**
- * National Language Identifier: 0x07
- * A.3.7 Kannada National Language Locking Shift Table
- */
- // 01.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....
- " \u0c82\u0c83\u0c85\u0c86\u0c87\u0c88\u0c89\u0c8a\u0c8b\n\u0c8c \r\u0c8e\u0c8f"
- // 0.....12.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0c90 \u0c92\u0c93\u0c94\u0c95\u0c96\u0c97\u0c98\u0c99\u0c9a\uffff\u0c9b\u0c9c\u0c9d\u0c9e"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u0c9f\u0ca0\u0ca1\u0ca2\u0ca3\u0ca4)(\u0ca5\u0ca6,\u0ca7.\u0ca8"
- // 0123456789ABCD.....E.....F
- + "0123456789:; \u0caa\u0cab?"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....B.....C.....D.....E.....F.....
- + "\u0cac\u0cad\u0cae\u0caf\u0cb0\u0cb1\u0cb2\u0cb3 \u0cb5\u0cb6\u0cb7\u0cb8\u0cb9\u0cbc\u0cbd"
- // 0.....1.....2.....3.....4.....5.....6.....78.....9.....A.....BC.....D.....E.....F.....
- + "\u0cbe\u0cbf\u0cc0\u0cc1\u0cc2\u0cc3\u0cc4 \u0cc6\u0cc7\u0cc8 \u0cca\u0ccb\u0ccc\u0ccd"
- // 0.....123456789ABCDEF
- + "\u0cd5abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0cd6\u0ce0\u0ce1\u0ce2\u0ce3",
-
- /**
- * National Language Identifier: 0x08
- * A.3.8 Malayalam National Language Locking Shift Table
- */
- // 01.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....
- " \u0d02\u0d03\u0d05\u0d06\u0d07\u0d08\u0d09\u0d0a\u0d0b\n\u0d0c \r\u0d0e\u0d0f"
- // 0.....12.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0d10 \u0d12\u0d13\u0d14\u0d15\u0d16\u0d17\u0d18\u0d19\u0d1a\uffff\u0d1b\u0d1c\u0d1d\u0d1e"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u0d1f\u0d20\u0d21\u0d22\u0d23\u0d24)(\u0d25\u0d26,\u0d27.\u0d28"
- // 0123456789ABCD.....E.....F
- + "0123456789:; \u0d2a\u0d2b?"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....EF.....
- + "\u0d2c\u0d2d\u0d2e\u0d2f\u0d30\u0d31\u0d32\u0d33\u0d34\u0d35\u0d36\u0d37\u0d38\u0d39 \u0d3d"
- // 0.....1.....2.....3.....4.....5.....6.....78.....9.....A.....BC.....D.....E.....F.....
- + "\u0d3e\u0d3f\u0d40\u0d41\u0d42\u0d43\u0d44 \u0d46\u0d47\u0d48 \u0d4a\u0d4b\u0d4c\u0d4d"
- // 0.....123456789ABCDEF
- + "\u0d57abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0d60\u0d61\u0d62\u0d63\u0d79",
-
- /**
- * National Language Identifier: 0x09
- * A.3.9 Oriya National Language Locking Shift Table
- */
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.EF.....
- "\u0b01\u0b02\u0b03\u0b05\u0b06\u0b07\u0b08\u0b09\u0b0a\u0b0b\n\u0b0c \r \u0b0f"
- // 0.....123.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0b10 \u0b13\u0b14\u0b15\u0b16\u0b17\u0b18\u0b19\u0b1a\uffff\u0b1b\u0b1c\u0b1d\u0b1e"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u0b1f\u0b20\u0b21\u0b22\u0b23\u0b24)(\u0b25\u0b26,\u0b27.\u0b28"
- // 0123456789ABCD.....E.....F
- + "0123456789:; \u0b2a\u0b2b?"
- // 0.....1.....2.....3.....4.....56.....7.....89.....A.....B.....C.....D.....E.....F.....
- + "\u0b2c\u0b2d\u0b2e\u0b2f\u0b30 \u0b32\u0b33 \u0b35\u0b36\u0b37\u0b38\u0b39\u0b3c\u0b3d"
- // 0.....1.....2.....3.....4.....5.....6.....789.....A.....BCD.....E.....F.....
- + "\u0b3e\u0b3f\u0b40\u0b41\u0b42\u0b43\u0b44 \u0b47\u0b48 \u0b4b\u0b4c\u0b4d"
- // 0.....123456789ABCDEF
- + "\u0b56abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0b57\u0b60\u0b61\u0b62\u0b63",
-
- /**
- * National Language Identifier: 0x0A
- * A.3.10 Punjabi National Language Locking Shift Table
- */
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9A.BCD.EF.....
- "\u0a01\u0a02\u0a03\u0a05\u0a06\u0a07\u0a08\u0a09\u0a0a \n \r \u0a0f"
- // 0.....123.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0a10 \u0a13\u0a14\u0a15\u0a16\u0a17\u0a18\u0a19\u0a1a\uffff\u0a1b\u0a1c\u0a1d\u0a1e"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u0a1f\u0a20\u0a21\u0a22\u0a23\u0a24)(\u0a25\u0a26,\u0a27.\u0a28"
- // 0123456789ABCD.....E.....F
- + "0123456789:; \u0a2a\u0a2b?"
- // 0.....1.....2.....3.....4.....56.....7.....89.....A.....BC.....D.....E.....F
- + "\u0a2c\u0a2d\u0a2e\u0a2f\u0a30 \u0a32\u0a33 \u0a35\u0a36 \u0a38\u0a39\u0a3c "
- // 0.....1.....2.....3.....4.....56789.....A.....BCD.....E.....F.....
- + "\u0a3e\u0a3f\u0a40\u0a41\u0a42 \u0a47\u0a48 \u0a4b\u0a4c\u0a4d"
- // 0.....123456789ABCDEF
- + "\u0a51abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0a70\u0a71\u0a72\u0a73\u0a74",
-
- /**
- * National Language Identifier: 0x0B
- * A.3.11 Tamil National Language Locking Shift Table
- */
- // 01.....2.....3.....4.....5.....6.....7.....8.....9A.BCD.E.....F.....
- " \u0b82\u0b83\u0b85\u0b86\u0b87\u0b88\u0b89\u0b8a \n \r\u0b8e\u0b8f"
- // 0.....12.....3.....4.....5.....6789.....A.....B.....CD.....EF.....
- + "\u0b90 \u0b92\u0b93\u0b94\u0b95 \u0b99\u0b9a\uffff \u0b9c \u0b9e"
- // 012.....3456.....7.....89ABCDEF.....
- + " !\u0b9f \u0ba3\u0ba4)( , .\u0ba8"
- // 0123456789ABC.....D.....EF
- + "0123456789:;\u0ba9\u0baa ?"
- // 012.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....EF
- + " \u0bae\u0baf\u0bb0\u0bb1\u0bb2\u0bb3\u0bb4\u0bb5\u0bb6\u0bb7\u0bb8\u0bb9 "
- // 0.....1.....2.....3.....4.....5678.....9.....A.....BC.....D.....E.....F.....
- + "\u0bbe\u0bbf\u0bc0\u0bc1\u0bc2 \u0bc6\u0bc7\u0bc8 \u0bca\u0bcb\u0bcc\u0bcd"
- // 0.....123456789ABCDEF
- + "\u0bd0abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0bd7\u0bf0\u0bf1\u0bf2\u0bf9",
-
- /**
- * National Language Identifier: 0x0C
- * A.3.12 Telugu National Language Locking Shift Table
- */
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....CD.E.....F.....
- "\u0c01\u0c02\u0c03\u0c05\u0c06\u0c07\u0c08\u0c09\u0c0a\u0c0b\n\u0c0c \r\u0c0e\u0c0f"
- // 0.....12.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0c10 \u0c12\u0c13\u0c14\u0c15\u0c16\u0c17\u0c18\u0c19\u0c1a\uffff\u0c1b\u0c1c\u0c1d\u0c1e"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u0c1f\u0c20\u0c21\u0c22\u0c23\u0c24)(\u0c25\u0c26,\u0c27.\u0c28"
- // 0123456789ABCD.....E.....F
- + "0123456789:; \u0c2a\u0c2b?"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89.....A.....B.....C.....D.....EF.....
- + "\u0c2c\u0c2d\u0c2e\u0c2f\u0c30\u0c31\u0c32\u0c33 \u0c35\u0c36\u0c37\u0c38\u0c39 \u0c3d"
- // 0.....1.....2.....3.....4.....5.....6.....78.....9.....A.....BC.....D.....E.....F.....
- + "\u0c3e\u0c3f\u0c40\u0c41\u0c42\u0c43\u0c44 \u0c46\u0c47\u0c48 \u0c4a\u0c4b\u0c4c\u0c4d"
- // 0.....123456789ABCDEF
- + "\u0c55abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0c56\u0c60\u0c61\u0c62\u0c63",
-
- /**
- * National Language Identifier: 0x0D
- * A.3.13 Urdu National Language Locking Shift Table
- */
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.B.....C.....D.E.....F.....
- "\u0627\u0622\u0628\u067b\u0680\u067e\u06a6\u062a\u06c2\u067f\n\u0679\u067d\r\u067a\u067c"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u062b\u062c\u0681\u0684\u0683\u0685\u0686\u0687\u062d\u062e\u062f\uffff\u068c\u0688\u0689\u068a"
- // 012.....3.....4.....5.....6.....7.....89A.....B.....CD.....EF.....
- + " !\u068f\u068d\u0630\u0631\u0691\u0693)(\u0699\u0632,\u0696.\u0698"
- // 0123456789ABC.....D.....E.....F
- + "0123456789:;\u069a\u0633\u0634?"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u0635\u0636\u0637\u0638\u0639\u0641\u0642\u06a9\u06aa\u06ab\u06af\u06b3\u06b1\u0644\u0645\u0646"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....C.....D.....E.....F.....
- + "\u06ba\u06bb\u06bc\u0648\u06c4\u06d5\u06c1\u06be\u0621\u06cc\u06d0\u06d2\u064d\u0650\u064f\u0657"
- // 0.....123456789ABCDEF
- + "\u0654abcdefghijklmno"
- // 0123456789AB.....C.....D.....E.....F.....
- + "pqrstuvwxyz\u0655\u0651\u0653\u0656\u0670"
-];
-
-// National Language Single Shift Tables, see 3GPP TS 23.038
-this.PDU_NL_SINGLE_SHIFT_TABLES = [
- /**
- * National Language Identifier: 0x00
- * 6.2.1.1 GSM 7 bit default alphabet extension table
- */
- // 0123456789A.....BCD.....EF
- " \u000c \ufffe "
- // 0123456789AB.....CDEF
- + " ^ \uffff "
- // 0123456789ABCDEF.
- + " {} \\"
- // 0123456789ABCDEF
- + " [~] "
- // 0123456789ABCDEF
- + "| "
- // 0123456789ABCDEF
- + " "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x01
- * A.2.1 Turkish National Language Single Shift Table
- */
- // 0123456789A.....BCD.....EF
- " \u000c \ufffe "
- // 0123456789AB.....CDEF
- + " ^ \uffff "
- // 0123456789ABCDEF.
- + " {} \\"
- // 0123456789ABCDEF
- + " [~] "
- // 01234567.....89.....ABCDEF
- + "| \u011e \u0130 "
- // 0123.....456789ABCDEF
- + " \u015e "
- // 0123.....45.....67.....89.....ABCDEF
- + " \u00e7 \u20ac \u011f \u0131 "
- // 0123.....456789ABCDEF
- + " \u015f ",
-
- /**
- * National Language Identifier: 0x02
- * A.2.2 Spanish National Language Single Shift Table
- */
- // 0123456789.....A.....BCD.....EF
- " \u00e7\u000c \ufffe "
- // 0123456789AB.....CDEF
- + " ^ \uffff "
- // 0123456789ABCDEF.
- + " {} \\"
- // 0123456789ABCDEF
- + " [~] "
- // 01.....23456789.....ABCDEF.....
- + "|\u00c1 \u00cd \u00d3"
- // 012345.....6789ABCDEF
- + " \u00da "
- // 01.....2345.....6789.....ABCDEF.....
- + " \u00e1 \u20ac \u00ed \u00f3"
- // 012345.....6789ABCDEF
- + " \u00fa ",
-
- /**
- * National Language Identifier: 0x03
- * A.2.3 Portuguese National Language Single Shift Table
- */
- // 012345.....6789.....A.....B.....C.....D.....E.....F.....
- " \u00ea \u00e7\u000c\u00d4\u00f4\ufffe\u00c1\u00e1"
- // 012.....3.....45.....6.....7.....8.....9.....AB.....CDEF.....
- + " \u03a6\u0393^\u03a9\u03a0\u03a8\u03a3\u0398 \uffff \u00ca"
- // 0123456789ABCDEF.
- + " {} \\"
- // 0123456789ABCDEF
- + " [~] "
- // 01.....23456789.....ABCDEF.....
- + "|\u00c0 \u00cd \u00d3"
- // 012345.....6789AB.....C.....DEF
- + " \u00da \u00c3\u00d5 "
- // 01.....2345.....6789.....ABCDEF.....
- + " \u00c2 \u20ac \u00ed \u00f3"
- // 012345.....6789AB.....C.....DEF.....
- + " \u00fa \u00e3\u00f5 \u00e2",
-
- /**
- * National Language Identifier: 0x04
- * A.2.4 Bengali National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u09e6\u09e7\uffff\u09e8\u09e9\u09ea\u09eb"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....E.....F.
- + "\u09ec\u09ed\u09ee\u09ef\u09df\u09e0\u09e1\u09e2{}\u09e3\u09f2\u09f3\u09f4\u09f5\\"
- // 0.....1.....2.....3.....4.....56789ABCDEF
- + "\u09f6\u09f7\u09f8\u09f9\u09fa [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x05
- * A.2.5 Gujarati National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u0964\u0965\uffff\u0ae6\u0ae7\u0ae8\u0ae9"
- // 0.....1.....2.....3.....4.....5.....6789ABCDEF.
- + "\u0aea\u0aeb\u0aec\u0aed\u0aee\u0aef {} \\"
- // 0123456789ABCDEF
- + " [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x06
- * A.2.6 Hindi National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u0964\u0965\uffff\u0966\u0967\u0968\u0969"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....E.....F.
- + "\u096a\u096b\u096c\u096d\u096e\u096f\u0951\u0952{}\u0953\u0954\u0958\u0959\u095a\\"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....BCDEF
- + "\u095b\u095c\u095d\u095e\u095f\u0960\u0961\u0962\u0963\u0970\u0971 [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x07
- * A.2.7 Kannada National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u0964\u0965\uffff\u0ce6\u0ce7\u0ce8\u0ce9"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....BCDEF.
- + "\u0cea\u0ceb\u0cec\u0ced\u0cee\u0cef\u0cde\u0cf1{}\u0cf2 \\"
- // 0123456789ABCDEF
- + " [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x08
- * A.2.8 Malayalam National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u0964\u0965\uffff\u0d66\u0d67\u0d68\u0d69"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....E.....F.
- + "\u0d6a\u0d6b\u0d6c\u0d6d\u0d6e\u0d6f\u0d70\u0d71{}\u0d72\u0d73\u0d74\u0d75\u0d7a\\"
- // 0.....1.....2.....3.....4.....56789ABCDEF
- + "\u0d7b\u0d7c\u0d7d\u0d7e\u0d7f [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x09
- * A.2.9 Oriya National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u0964\u0965\uffff\u0b66\u0b67\u0b68\u0b69"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....DEF.
- + "\u0b6a\u0b6b\u0b6c\u0b6d\u0b6e\u0b6f\u0b5c\u0b5d{}\u0b5f\u0b70\u0b71 \\"
- // 0123456789ABCDEF
- + " [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x0A
- * A.2.10 Punjabi National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u0964\u0965\uffff\u0a66\u0a67\u0a68\u0a69"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....EF.
- + "\u0a6a\u0a6b\u0a6c\u0a6d\u0a6e\u0a6f\u0a59\u0a5a{}\u0a5b\u0a5c\u0a5e\u0a75 \\"
- // 0123456789ABCDEF
- + " [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x0B
- * A.2.11 Tamil National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u0964\u0965\uffff\u0be6\u0be7\u0be8\u0be9"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....E.....F.
- + "\u0bea\u0beb\u0bec\u0bed\u0bee\u0bef\u0bf3\u0bf4{}\u0bf5\u0bf6\u0bf7\u0bf8\u0bfa\\"
- // 0123456789ABCDEF
- + " [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x0C
- * A.2.12 Telugu National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789AB.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#* \uffff\u0c66\u0c67\u0c68\u0c69"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....E.....F.
- + "\u0c6a\u0c6b\u0c6c\u0c6d\u0c6e\u0c6f\u0c58\u0c59{}\u0c78\u0c79\u0c7a\u0c7b\u0c7c\\"
- // 0.....1.....2.....3456789ABCDEF
- + "\u0c7d\u0c7e\u0c7f [~] "
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " ",
-
- /**
- * National Language Identifier: 0x0D
- * A.2.13 Urdu National Language Single Shift Table
- */
- // 01.....23.....4.....5.6.....789A.....BCD.....EF
- "@\u00a3$\u00a5\u00bf\"\u00a4%&'\u000c*+\ufffe-/"
- // 0123.....45.....6789.....A.....B.....C.....D.....E.....F.....
- + "<=>\u00a1^\u00a1_#*\u0600\u0601\uffff\u06f0\u06f1\u06f2\u06f3"
- // 0.....1.....2.....3.....4.....5.....6.....7.....89A.....B.....C.....D.....E.....F.
- + "\u06f4\u06f5\u06f6\u06f7\u06f8\u06f9\u060c\u060d{}\u060e\u060f\u0610\u0611\u0612\\"
- // 0.....1.....2.....3.....4.....5.....6.....7.....8.....9.....A.....B.....CDEF.....
- + "\u0613\u0614\u061b\u061f\u0640\u0652\u0658\u066b\u066c\u0672\u0673\u06cd[~]\u06d4"
- // 0123456789ABCDEF
- + "|ABCDEFGHIJKLMNO"
- // 0123456789ABCDEF
- + "PQRSTUVWXYZ "
- // 012345.....6789ABCDEF
- + " \u20ac "
- // 0123456789ABCDEF
- + " "
-];
-
-// Special SMS Message Indication constants
-this.PDU_MWI_STORE_TYPE_BIT = 0x80;
-this.PDU_MWI_STORE_TYPE_DISCARD = 0x00;
-this.PDU_MWI_STORE_TYPE_STORE = 0x80;
-
-this.GSM_SMS_STRICT_7BIT_CHARMAP = {
-//"\u0024": "\u0024", // "$" => "$", already in default alphabet
-//"\u00a5": "\u00a5", // "¥" => "¥", already in default alphabet
- "\u00c0": "\u0041", // "À" => "A"
- "\u00c1": "\u0041", // "Á" => "A"
- "\u00c2": "\u0041", // "Â" => "A"
- "\u00c3": "\u0041", // "Ã" => "A"
-//"\u00c4": "\u00c4", // "Ä" => "Ä", already in default alphabet
-//"\u00c5": "\u00c5", // "Å" => "Å", already in default alphabet
-//"\u00c6": "\u00c6", // "Æ" => "Æ", already in default alphabet
-//"\u00c7": "\u00c7", // "Ç" => "Ç", already in default alphabet
- "\u00c8": "\u0045", // "È" => "E"
-//"\u00c9": "\u00c9", // "É" => "É", already in default alphabet
- "\u00ca": "\u0045", // "Ê" => "E"
- "\u00cb": "\u0045", // "Ë" => "E"
- "\u00cc": "\u0049", // "Ì" => "I"
- "\u00cd": "\u0049", // "Í" => "I"
- "\u00ce": "\u0049", // "Î" => "I"
- "\u00cf": "\u0049", // "Ï" => "I"
-//"\u00d1": "\u00d1", // "Ñ" => "Ñ", already in default alphabet
- "\u00d2": "\u004f", // "Ò" => "O"
- "\u00d3": "\u004f", // "Ó" => "O"
- "\u00d4": "\u004f", // "Ô" => "O"
- "\u00d5": "\u004f", // "Õ" => "O"
-//"\u00d6": "\u00d6", // "Ö" => "Ö", already in default alphabet
- "\u00d9": "\u0055", // "Ù" => "U"
- "\u00da": "\u0055", // "Ú" => "U"
- "\u00db": "\u0055", // "Û" => "U"
-//"\u00dc": "\u00dc", // "Ü" => "Ü", already in default alphabet
-//"\u00df": "\u00df", // "ß" => "ß", already in default alphabet
-//"\u00e0": "\u00e0", // "à" => "à", already in default alphabet
- "\u00e1": "\u0061", // "á" => "a"
- "\u00e2": "\u0061", // "â" => "a"
- "\u00e3": "\u0061", // "ã" => "a"
-//"\u00e4": "\u00e4", // "ä" => "ä", already in default alphabet
-//"\u00e5": "\u00e5", // "å" => "å", already in default alphabet
-//"\u00e6": "\u00e6", // "æ" => "æ", already in default alphabet
- "\u00e7": "\u00c7", // "ç" => "Ç"
-//"\u00e8": "\u00e8", // "è" => "è", already in default alphabet
-//"\u00e9": "\u00e9", // "é" => "é", already in default alphabet
- "\u00ea": "\u0065", // "ê" => "e"
- "\u00eb": "\u0065", // "ë" => "e"
-//"\u00ec": "\u00ec", // "ì" => "ì", already in default alphabet
- "\u00ed": "\u0069", // "í" => "i"
- "\u00ee": "\u0069", // "î" => "i"
- "\u00ef": "\u0069", // "ï" => "i"
-//"\u00f1": "\u00f1", // "ñ" => "ñ", already in default alphabet
-//"\u00f2": "\u00f2", // "ò" => "ò", already in default alphabet
- "\u00f3": "\u006f", // "ó" => "o"
- "\u00f4": "\u006f", // "ô" => "o"
- "\u00f5": "\u006f", // "õ" => "o"
-//"\u00f6": "\u00f6", // "ö" => "ö", already in default alphabet
-//"\u00f8": "\u00f8", // "ø" => "ø", already in default alphabet
-//"\u00f9": "\u00f9", // "ù" => "ù", already in default alphabet
- "\u00fa": "\u0075", // "ú" => "u"
- "\u00fb": "\u0075", // "û" => "u"
-//"\u00fc": "\u00fc", // "ü" => "ü", already in default alphabet
- "\u00fe": "\u0074", // "þ" => "t"
- "\u0100": "\u0041", // "Ā" => "A"
- "\u0101": "\u0061", // "ā" => "a"
- "\u0106": "\u0043", // "Ć" => "C"
- "\u0107": "\u0063", // "ć" => "c"
- "\u010c": "\u0043", // "Č" => "C"
- "\u010d": "\u0063", // "č" => "c"
- "\u010f": "\u0064", // "ď" => "d"
- "\u0110": "\u0044", // "Đ" => "D"
- "\u0111": "\u0064", // "đ" => "d"
- "\u0112": "\u0045", // "Ē" => "E"
- "\u0113": "\u0065", // "ē" => "e"
- "\u0118": "\u0045", // "Ę" => "E"
- "\u0119": "\u0065", // "ę" => "e"
- "\u0128": "\u0049", // "Ĩ" => "I"
- "\u0129": "\u0069", // "ĩ" => "i"
- "\u012a": "\u0049", // "Ī" => "I"
- "\u012b": "\u0069", // "ī" => "i"
- "\u012e": "\u0049", // "Į" => "I"
- "\u012f": "\u0069", // "į" => "i"
- "\u0141": "\u004c", // "Ł" => "L"
- "\u0142": "\u006c", // "ł" => "l"
- "\u0143": "\u004e", // "Ń" => "N"
- "\u0144": "\u006e", // "ń" => "n"
- "\u0147": "\u004e", // "Ň" => "N"
- "\u0148": "\u006e", // "ň" => "n"
- "\u014c": "\u004f", // "Ō" => "O"
- "\u014d": "\u006f", // "ō" => "o"
- "\u0152": "\u004f", // "Œ" => "O"
- "\u0153": "\u006f", // "œ" => "o"
- "\u0158": "\u0052", // "Ř" => "R"
- "\u0159": "\u0072", // "ř" => "r"
- "\u0160": "\u0053", // "Š" => "S"
- "\u0161": "\u0073", // "š" => "s"
- "\u0165": "\u0074", // "ť" => "t"
- "\u0168": "\u0055", // "Ū" => "U"
- "\u0169": "\u0075", // "ū" => "u"
- "\u016a": "\u0055", // "Ū" => "U"
- "\u016b": "\u0075", // "ū" => "u"
- "\u0178": "\u0059", // "Ÿ" => "Y"
- "\u0179": "\u005a", // "Ź" => "Z"
- "\u017a": "\u007a", // "ź" => "z"
- "\u017b": "\u005a", // "Ż" => "Z"
- "\u017c": "\u007a", // "ż" => "z"
- "\u017d": "\u005a", // "Ž" => "Z"
- "\u017e": "\u007a", // "ž" => "z"
- "\u025b": "\u0045", // "ɛ" => "E"
-//"\u0398": "\u0398", // "Θ" => "Θ", already in default alphabet
- "\u1e7c": "\u0056", // "Ṽ" => "V"
- "\u1e7d": "\u0076", // "ṽ" => "v"
- "\u1ebc": "\u0045", // "Ẽ" => "E"
- "\u1ebd": "\u0065", // "ẽ" => "e"
- "\u1ef8": "\u0059", // "Ỹ" => "Y"
- "\u1ef9": "\u0079", // "ỹ" => "y"
- "\u20a4": "\u00a3", // "₤" => "£"
-//"\u20ac": "\u20ac", // "€" => "€", already in default alphabet
-};
-
-this.RADIOTECH_FAMILY_3GPP = 1; // GSM, WCDMA, LTE
-this.RADIOTECH_FAMILY_3GPP2 = 2; // CDMA, EVDO
-
-this.DATACALL_RADIOTECHNOLOGY_CDMA = 0;
-this.DATACALL_RADIOTECHNOLOGY_GSM = 1;
-
-this.DATACALL_AUTH_NONE = 0;
-this.DATACALL_AUTH_PAP = 1;
-this.DATACALL_AUTH_CHAP = 2;
-this.DATACALL_AUTH_PAP_OR_CHAP = 3;
-
-this.GECKO_DATACALL_AUTH_NONE = "none";
-this.GECKO_DATACALL_AUTH_PAP = "pap";
-this.GECKO_DATACALL_AUTH_CHAP = "chap";
-this.GECKO_DATACALL_AUTH_PAP_OR_CHAP = "papOrChap";
-this.GECKO_DATACALL_AUTH_DEFAULT = GECKO_DATACALL_AUTH_PAP_OR_CHAP;
-this.RIL_DATACALL_AUTH_TO_GECKO = [
- GECKO_DATACALL_AUTH_NONE, // DATACALL_AUTH_NONE
- GECKO_DATACALL_AUTH_PAP, // DATACALL_AUTH_PAP
- GECKO_DATACALL_AUTH_CHAP, // DATACALL_AUTH_CHAP
- GECKO_DATACALL_AUTH_PAP_OR_CHAP // DATACALL_AUTH_PAP_OR_CHAP
-];
-
-this.GECKO_DATACALL_PDP_TYPE_IP = "IP";
-this.GECKO_DATACALL_PDP_TYPE_IPV4V6 = "IPV4V6";
-this.GECKO_DATACALL_PDP_TYPE_IPV6 = "IPV6";
-this.GECKO_DATACALL_PDP_TYPE_DEFAULT = GECKO_DATACALL_PDP_TYPE_IP;
-this.RIL_DATACALL_PDP_TYPES = [
- GECKO_DATACALL_PDP_TYPE_IP,
- GECKO_DATACALL_PDP_TYPE_IPV4V6,
- GECKO_DATACALL_PDP_TYPE_IPV6,
-];
-
-this.DATACALL_PROFILE_DEFAULT = 0;
-this.DATACALL_PROFILE_TETHERED = 1;
-this.DATACALL_PROFILE_OEM_BASE = 1000;
-
-this.DATACALL_DEACTIVATE_NO_REASON = 0;
-this.DATACALL_DEACTIVATE_RADIO_SHUTDOWN = 1;
-
-this.DATACALL_ACTIVE_UNKNOWN = -1;
-this.DATACALL_INACTIVE = 0;
-this.DATACALL_ACTIVE_DOWN = 1;
-this.DATACALL_ACTIVE_UP = 2;
-
-this.DATACALL_FAIL_NONE = 0;
-this.DATACALL_FAIL_OPERATOR_BARRED = 0x08;
-this.DATACALL_FAIL_INSUFFICIENT_RESOURCES = 0x1A;
-this.DATACALL_FAIL_MISSING_UKNOWN_APN = 0x1B;
-this.DATACALL_FAIL_UNKNOWN_PDP_ADDRESS_TYPE = 0x1C;
-this.DATACALL_FAIL_USER_AUTHENTICATION = 0x1D;
-this.DATACALL_FAIL_ACTIVATION_REJECT_GGSN = 0x1E;
-this.DATACALL_FAIL_ACTIVATION_REJECT_UNSPECIFIED = 0x1F;
-this.DATACALL_FAIL_SERVICE_OPTION_NOT_SUPPORTED = 0x20;
-this.DATACALL_FAIL_SERVICE_OPTION_NOT_SUBSCRIBED = 0x21;
-this.DATACALL_FAIL_SERVICE_OPTION_OUT_OF_ORDER = 0x22;
-this.DATACALL_FAIL_NSAPI_IN_USE = 0x23;
-this.DATACALL_FAIL_ONLY_IPV4_ALLOWED = 0x32;
-this.DATACALL_FAIL_ONLY_IPV6_ALLOWED = 0x33;
-this.DATACALL_FAIL_ONLY_SINGLE_BEARER_ALLOWED = 0x34;
-this.DATACALL_FAIL_PROTOCOL_ERRORS = 0x6F;
-this.DATACALL_FAIL_VOICE_REGISTRATION_FAIL = -1;
-this.DATACALL_FAIL_DATA_REGISTRATION_FAIL = -2;
-this.DATACALL_FAIL_SIGNAL_LOST = -3;
-this.DATACALL_FAIL_PREF_RADIO_TECH_CHANGED = -4;
-this.DATACALL_FAIL_RADIO_POWER_OFF = -5;
-this.DATACALL_FAIL_TETHERED_CALL_ACTIVE = -6;
-this.DATACALL_FAIL_ERROR_UNSPECIFIED = 0xffff;
-
-// Keep consistent with nsINetworkManager.NETWORK_STATE_*.
-this.GECKO_NETWORK_STATE_UNKNOWN = -1;
-this.GECKO_NETWORK_STATE_CONNECTING = 0;
-this.GECKO_NETWORK_STATE_CONNECTED = 1;
-this.GECKO_NETWORK_STATE_DISCONNECTING = 2;
-this.GECKO_NETWORK_STATE_DISCONNECTED = 3;
-
-// 3GPP 24.008 Annex H.
-this.CALL_FAIL_UNOBTAINABLE_NUMBER = 1;
-this.CALL_FAIL_NO_ROUTE_TO_DESTINATION = 3;
-this.CALL_FAIL_CHANNEL_UNACCEPTABLE = 6;
-this.CALL_FAIL_OPERATOR_DETERMINED_BARRING = 8;
-this.CALL_FAIL_NORMAL = 16;
-this.CALL_FAIL_BUSY = 17;
-this.CALL_FAIL_NO_USER_RESPONDING = 18;
-this.CALL_FAIL_USER_ALERTING = 19;
-this.CALL_FAIL_CALL_REJECTED = 21;
-this.CALL_FAIL_NUMBER_CHANGED = 22;
-this.CALL_FAIL_CALL_REJECTED_DESTINATION_FEATURE = 24;
-this.CALL_FAIL_CALL_PRE_EMPTION = 25;
-this.CALL_FAIL_DEST_OUT_OF_ORDER = 27;
-this.CALL_FAIL_INVALID_FORMAT = 28;
-this.CALL_FAIL_FACILITY_REJECTED = 29;
-this.CALL_FAIL_RESPONSE_TO_STATUS_ENQUIRY = 30;
-this.CALL_FAIL_NORMAL_UNSPECIFIED = 31;
-this.CALL_FAIL_CONGESTION = 34;
-this.CALL_FAIL_NETWORK_OUT_OF_ORDER = 38;
-this.CALL_FAIL_NETWORK_TEMP_FAILURE = 41;
-this.CALL_FAIL_SWITCHING_EQUIP_CONGESTION = 42;
-this.CALL_FAIL_ACCESS_INFO_DISCARDED = 43;
-this.CALL_FAIL_REQUESTED_CHANNEL_NOT_AVAILABLE = 44;
-this.CALL_FAIL_RESOURCE_UNAVAILABLE = 47;
-this.CALL_FAIL_QOS_UNAVAILABLE = 49;
-this.CALL_FAIL_REQUESTED_FACILITY_NOT_SUBSCRIBED = 50;
-this.CALL_FAIL_INCOMING_CALLS_BARRED_WITHIN_CUG = 55;
-this.CALL_FAIL_BEARER_CAPABILITY_NOT_AUTHORIZED = 57;
-this.CALL_FAIL_BEARER_CAPABILITY_NOT_AVAILABLE = 58;
-this.CALL_FAIL_SERVICE_NOT_AVAILABLE = 63;
-this.CALL_FAIL_BEARER_NOT_IMPLEMENTED = 65;
-this.CALL_FAIL_ACM_LIMIT_EXCEEDED = 68;
-this.CALL_FAIL_REQUESTED_FACILITY_NOT_IMPLEMENTED = 69;
-this.CALL_FAIL_UNRESTRICTED_BEARER_NOT_AVAILABLE = 70;
-this.CALL_FAIL_SERVICE_NOT_IMPLEMENTED = 79;
-this.CALL_FAIL_INVALID_TRANSACTION_ID = 81;
-this.CALL_FAIL_USER_NOT_CUG_MEMBER = 87;
-this.CALL_FAIL_INCOMPATIBLE_DESTINATION = 88;
-this.CALL_FAIL_INVALID_TRANSIT_NETWORK_SELECTION = 91;
-this.CALL_FAIL_SEMANTICALLY_INCORRECT_MESSAGE = 95;
-this.CALL_FAIL_INVALID_MANDATORY_INFO = 96;
-this.CALL_FAIL_MESSAGE_TYPE_NOT_IMPLEMENTED = 97;
-this.CALL_FAIL_MESSAGE_TYPE_INCOMPATIBLE_PROTOCOL_STATE = 98;
-this.CALL_FAIL_INFO_ELEMENT_NOT_IMPLEMENTED = 99;
-this.CALL_FAIL_CONDITIONAL_IE_ERROR = 100;
-this.CALL_FAIL_MESSAGE_INCOMPABITLE_PROTOCOL_STATE = 101;
-this.CALL_FAIL_RECOVERY_ON_TIMER_EXPIRY = 102;
-this.CALL_FAIL_PROTOCOL_ERROR = 111;
-this.CALL_FAIL_INTERWORKING = 127;
-// AOSP ril.h
-this.CALL_FAIL_CALL_BARRED = 240;
-this.CALL_FAIL_FDN_BLOCKED = 241;
-this.CALL_FAIL_IMSI_UNKNOWN_IN_VLR = 242;
-this.CALL_FAIL_IMEI_NOT_ACCEPTED = 243;
-this.CALL_FAIL_DIAL_MODIFIED_TO_USSD = 244; // STK Call Control
-this.CALL_FAIL_DIAL_MODIFIED_TO_SS = 245;
-this.CALL_FAIL_DIAL_MODIFIED_TO_DIAL = 246;
-this.CALL_FAIL_CDMA_LOCKED_UNTIL_POWER_CYCLE = 1000;
-this.CALL_FAIL_CDMA_DROP = 1001;
-this.CALL_FAIL_CDMA_INTERCEPT = 1002;
-this.CALL_FAIL_CDMA_REORDER = 1003;
-this.CALL_FAIL_CDMA_SO_REJECT = 1004;
-this.CALL_FAIL_CDMA_RETRY_ORDER = 1005;
-this.CALL_FAIL_CDMA_ACCESS_FAILURE = 1006;
-this.CALL_FAIL_CDMA_PREEMPTED = 1007;
-this.CALL_FAIL_CDMA_NOT_EMERGENCY = 1008; // For non-emergency number dialed
- // during emergency callback mode
-this.CALL_FAIL_CDMA_ACCESS_BLOCKED = 1009;
-this.CALL_FAIL_ERROR_UNSPECIFIED = 0xffff;
-
-// See nsIMobileConnection::MOBILE_RADIO_STATE_*
-this.GECKO_RADIOSTATE_UNKNOWN = -1;
-this.GECKO_RADIOSTATE_ENABLED = 0;
-this.GECKO_RADIOSTATE_DISABLED = 1;
-
-// Only used in ril_worker.js
-this.GECKO_CARDSTATE_UNINITIALIZED = 4294967294; // UINT32_MAX - 1
-// See nsIIcc::CARD_STATE_*
-this.GECKO_CARDSTATE_UNDETECTED = 4294967295; // UINT32_MAX
-this.GECKO_CARDSTATE_UNKNOWN = 0;
-this.GECKO_CARDSTATE_READY = 1;
-this.GECKO_CARDSTATE_PIN_REQUIRED = 2;
-this.GECKO_CARDSTATE_PUK_REQUIRED = 3;
-this.GECKO_CARDSTATE_PERMANENT_BLOCKED = 4;
-this.GECKO_CARDSTATE_PERSONALIZATION_IN_PROGRESS = 5;
-this.GECKO_CARDSTATE_PERSONALIZATION_READY = 6;
-this.GECKO_CARDSTATE_NETWORK_LOCKED = 7;
-this.GECKO_CARDSTATE_NETWORK_SUBSET_LOCKED = 8;
-this.GECKO_CARDSTATE_CORPORATE_LOCKED = 9;
-this.GECKO_CARDSTATE_SERVICE_PROVIDER_LOCKED = 10;
-this.GECKO_CARDSTATE_SIM_LOCKED = 11;
-this.GECKO_CARDSTATE_NETWORK_PUK_REQUIRED = 12;
-this.GECKO_CARDSTATE_NETWORK_SUBSET_PUK_REQUIRED = 13;
-this.GECKO_CARDSTATE_CORPORATE_PUK_REQUIRED = 14;
-this.GECKO_CARDSTATE_SERVICE_PROVIDER_PUK_REQUIRED = 15;
-this.GECKO_CARDSTATE_SIM_PUK_REQUIRED = 16;
-this.GECKO_CARDSTATE_NETWORK1_LOCKED = 17;
-this.GECKO_CARDSTATE_NETWORK2_LOCKED = 18;
-this.GECKO_CARDSTATE_HRPD_NETWORK_LOCKED = 19;
-this.GECKO_CARDSTATE_RUIM_CORPORATE_LOCKED = 20;
-this.GECKO_CARDSTATE_RUIM_SERVICE_PROVIDER_LOCKED = 21;
-this.GECKO_CARDSTATE_RUIM_LOCKED = 22;
-this.GECKO_CARDSTATE_NETWORK1_PUK_REQUIRED = 23;
-this.GECKO_CARDSTATE_NETWORK2_PUK_REQUIRED = 24;
-this.GECKO_CARDSTATE_HRPD_NETWORK_PUK_REQUIRED = 25;
-this.GECKO_CARDSTATE_RUIM_CORPORATE_PUK_REQUIRED = 26;
-this.GECKO_CARDSTATE_RUIM_SERVICE_PROVIDER_PUK_REQUIRED = 27;
-this.GECKO_CARDSTATE_RUIM_PUK_REQUIRED = 28;
-this.GECKO_CARDSTATE_ILLEGAL = 29;
-
-// See nsIIcc::CARD_LOCK_TYPE_*
-this.GECKO_CARDLOCK_PIN = 0;
-this.GECKO_CARDLOCK_PIN2 = 1;
-this.GECKO_CARDLOCK_PUK = 2;
-this.GECKO_CARDLOCK_PUK2 = 3;
-this.GECKO_CARDLOCK_NCK = 4;
-this.GECKO_CARDLOCK_NSCK = 5;
-this.GECKO_CARDLOCK_NCK1 = 6;
-this.GECKO_CARDLOCK_NCK2 = 7;
-this.GECKO_CARDLOCK_HNCK = 8;
-this.GECKO_CARDLOCK_CCK = 9;
-this.GECKO_CARDLOCK_SPCK = 10;
-this.GECKO_CARDLOCK_PCK = 11;
-this.GECKO_CARDLOCK_RCCK = 12;
-this.GECKO_CARDLOCK_RSPCK = 13;
-this.GECKO_CARDLOCK_NCK_PUK = 14;
-this.GECKO_CARDLOCK_NSCK_PUK = 15;
-this.GECKO_CARDLOCK_NCK1_PUK = 16;
-this.GECKO_CARDLOCK_NCK2_PUK = 17;
-this.GECKO_CARDLOCK_HNCK_PUK = 18;
-this.GECKO_CARDLOCK_CCK_PUK = 19;
-this.GECKO_CARDLOCK_SPCK_PUK = 20;
-this.GECKO_CARDLOCK_PCK_PUK = 21;
-this.GECKO_CARDLOCK_RCCK_PUK = 22;
-this.GECKO_CARDLOCK_RSPCK_PUK = 23;
-this.GECKO_CARDLOCK_FDN = 24;
-
-this.GECKO_CARDLOCK_TO_FACILITY = {};
-GECKO_CARDLOCK_TO_FACILITY[GECKO_CARDLOCK_PIN] = ICC_CB_FACILITY_SIM;
-GECKO_CARDLOCK_TO_FACILITY[GECKO_CARDLOCK_FDN] = ICC_CB_FACILITY_FDN;
-
-this.GECKO_CARDLOCK_TO_SEL_CODE = {};
-GECKO_CARDLOCK_TO_SEL_CODE[GECKO_CARDLOCK_PIN] = ICC_SEL_CODE_SIM_PIN;
-GECKO_CARDLOCK_TO_SEL_CODE[GECKO_CARDLOCK_PIN2] = ICC_SEL_CODE_SIM_PIN2;
-GECKO_CARDLOCK_TO_SEL_CODE[GECKO_CARDLOCK_PUK] = ICC_SEL_CODE_SIM_PUK;
-GECKO_CARDLOCK_TO_SEL_CODE[GECKO_CARDLOCK_PUK2] = ICC_SEL_CODE_SIM_PUK2;
-GECKO_CARDLOCK_TO_SEL_CODE[GECKO_CARDLOCK_NCK] = ICC_SEL_CODE_PH_NET_PIN;
-GECKO_CARDLOCK_TO_SEL_CODE[GECKO_CARDLOCK_NSCK] = ICC_SEL_CODE_PH_NETSUB_PIN;
-GECKO_CARDLOCK_TO_SEL_CODE[GECKO_CARDLOCK_CCK] = ICC_SEL_CODE_PH_CORP_PIN;
-GECKO_CARDLOCK_TO_SEL_CODE[GECKO_CARDLOCK_SPCK] = ICC_SEL_CODE_PH_SP_PIN;
-// TODO: Bug 1116072: identify the mapping between RIL_PERSOSUBSTATE_SIM_SIM @
-// ril.h and TS 27.007, clause 8.65 for GECKO_CARDLOCK_PCK.
-
-// See nsIIcc::CARD_CONTACT_TYPE_*
-this.GECKO_CARDCONTACT_TYPE_ADN = 0;
-this.GECKO_CARDCONTACT_TYPE_FDN = 1;
-this.GECKO_CARDCONTACT_TYPE_SDN = 2;
-
-// See nsIIcc::CARD_MVNO_TYPE_*
-this.GECKO_CARDMVNO_TYPE_IMSI = 0;
-this.GECKO_CARDMVNO_TYPE_SPN = 1;
-this.GECKO_CARDMVNO_TYPE_GID = 2;
-
-// See nsIIcc::CARD_SERVICE_*
-this.GECKO_CARDSERVICE_FDN = 0;
-
-// See ril.h RIL_PersoSubstate
-this.PERSONSUBSTATE = {};
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_UNKNOWN] = GECKO_CARDSTATE_UNKNOWN;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_IN_PROGRESS] = GECKO_CARDSTATE_PERSONALIZATION_IN_PROGRESS;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_READY] = GECKO_CARDSTATE_PERSONALIZATION_READY;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_NETWORK] = GECKO_CARDSTATE_NETWORK_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_NETWORK_SUBSET] = GECKO_CARDSTATE_NETWORK_SUBSET_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_CORPORATE] = GECKO_CARDSTATE_CORPORATE_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_SERVICE_PROVIDER] = GECKO_CARDSTATE_SERVICE_PROVIDER_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_SIM] = GECKO_CARDSTATE_SIM_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_NETWORK_PUK] = GECKO_CARDSTATE_NETWORK_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK] = GECKO_CARDSTATE_NETWORK_SUBSET_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_CORPORATE_PUK] = GECKO_CARDSTATE_CORPORATE_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK] = GECKO_CARDSTATE_SERVICE_PROVIDER_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_SIM_SIM_PUK] = GECKO_CARDSTATE_SIM_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_NETWORK1] = GECKO_CARDSTATE_NETWORK1_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_NETWORK2] = GECKO_CARDSTATE_NETWORK2_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_HRPD] = GECKO_CARDSTATE_HRPD_NETWORK_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_CORPORATE] = GECKO_CARDSTATE_RUIM_CORPORATE_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_SERVICE_PROVIDER] = GECKO_CARDSTATE_RUIM_SERVICE_PROVIDER_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_RUIM] = GECKO_CARDSTATE_RUIM_LOCKED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_NETWORK1_PUK] = GECKO_CARDSTATE_NETWORK1_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_NETWORK2_PUK] = GECKO_CARDSTATE_NETWORK2_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_HRPD_PUK] = GECKO_CARDSTATE_HRPD_NETWORK_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_CORPORATE_PUK] = GECKO_CARDSTATE_RUIM_CORPORATE_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK] = GECKO_CARDSTATE_RUIM_SERVICE_PROVIDER_PUK_REQUIRED;
-PERSONSUBSTATE[CARD_PERSOSUBSTATE_RUIM_RUIM_PUK] = GECKO_CARDSTATE_RUIM_PUK_REQUIRED;
-
-// See nsIMobileConnection::NETWORK_SELECTION_MODE_*
-this.GECKO_NETWORK_SELECTION_UNKNOWN = -1;
-this.GECKO_NETWORK_SELECTION_AUTOMATIC = 0;
-this.GECKO_NETWORK_SELECTION_MANUAL = 1;
-
-this.GECKO_MOBILE_CONNECTION_STATE_UNKNOWN = null;
-this.GECKO_MOBILE_CONNECTION_STATE_NOTSEARCHING = "notSearching";
-this.GECKO_MOBILE_CONNECTION_STATE_SEARCHING = "searching";
-this.GECKO_MOBILE_CONNECTION_STATE_REGISTERED = "registered";
-this.GECKO_MOBILE_CONNECTION_STATE_DENIED = "denied";
-
-this.NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE = {};
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_NOT_SEARCHING] = GECKO_MOBILE_CONNECTION_STATE_NOTSEARCHING;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_REGISTERED_HOME] = GECKO_MOBILE_CONNECTION_STATE_REGISTERED;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_SEARCHING] = GECKO_MOBILE_CONNECTION_STATE_SEARCHING;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_DENIED] = GECKO_MOBILE_CONNECTION_STATE_DENIED;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_UNKNOWN] = GECKO_MOBILE_CONNECTION_STATE_UNKNOWN;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_REGISTERED_ROAMING] = GECKO_MOBILE_CONNECTION_STATE_REGISTERED;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_NOT_SEARCHING_EMERGENCY_CALLS] = GECKO_MOBILE_CONNECTION_STATE_NOTSEARCHING;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_SEARCHING_EMERGENCY_CALLS] = GECKO_MOBILE_CONNECTION_STATE_SEARCHING;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_DENIED_EMERGENCY_CALLS] = GECKO_MOBILE_CONNECTION_STATE_DENIED;
-NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[NETWORK_CREG_STATE_UNKNOWN_EMERGENCY_CALLS] = GECKO_MOBILE_CONNECTION_STATE_UNKNOWN;
-
-
-// Should match enum TelephonyCallDisconnectedReason defined in TelephonyCall.webidl
-this.GECKO_CALL_ERROR_BAD_NUMBER = "BadNumberError";
-this.GECKO_CALL_ERROR_NO_ROUTE_TO_DESTINATION = "NoRouteToDestinationError";
-this.GECKO_CALL_ERROR_CHANNEL_UNACCEPTABLE = "ChannelUnacceptableError";
-this.GECKO_CALL_ERROR_OPERATOR_DETERMINED_BARRING = "OperatorDeterminedBarringError";
-this.GECKO_CALL_ERROR_NORMAL_CALL_CLEARING = "NormalCallClearingError";
-this.GECKO_CALL_ERROR_BUSY = "BusyError";
-this.GECKO_CALL_ERROR_NO_USER_RESPONDING = "NoUserRespondingError";
-this.GECKO_CALL_ERROR_USER_ALERTING = "UserAlertingNoAnswerError";
-this.GECKO_CALL_ERROR_REJECTED = "CallRejectedError";
-this.GECKO_CALL_ERROR_NUMBER_CHANGED = "NumberChangedError";
-this.GECKO_CALL_ERROR_REJECTED_DETINATION_FEATURE = "CallRejectedDestinationFeatureError";
-this.GECKO_CALL_ERROR_PRE_EMPTION = "PreEmptionError";
-this.GECKO_CALL_ERROR_DEST_OUT_OF_ORDER = "DestinationOutOfOrderError";
-this.GECKO_CALL_ERROR_INVALID_NUMBER_FORMAT = "InvalidNumberFormatError";
-this.GECKO_CALL_ERROR_FACILITY_REJECTED = "FacilityRejectedError";
-this.GECKO_CALL_ERROR_RESPONSE_TO_STATUS_ENQUIRY = "ResponseToStatusEnquiryError";
-this.GECKO_CALL_ERROR_CONGESTION = "CongestionError";
-this.GECKO_CALL_ERROR_NETWORK_OUT_OF_ORDER = "NetworkOutOfOrderError";
-this.GECKO_CALL_ERROR_NETWORK_TEMP_FAILURE = "NetworkTempFailureError";
-this.GECKO_CALL_ERROR_SWITCHING_EQUIP_CONGESTION = "SwitchingEquipCongestionError";
-this.GECKO_CALL_ERROR_ACCESS_INFO_DISCARDED = "AccessInfoDiscardedError";
-this.GECKO_CALL_ERROR_REQUESTED_CHANNEL_NOT_AVAILABLE = "RequestedChannelNotAvailableError";
-this.GECKO_CALL_ERROR_RESOURCE_UNAVAILABLE = "ResourceUnavailableError";
-this.GECKO_CALL_ERROR_QOS_UNAVAILABLE = "QosUnavailableError";
-this.GECKO_CALL_ERROR_REQUESTED_FACILITY_NOT_SUBSCRIBED = "RequestedFacilityNotSubscribedError";
-this.GECKO_CALL_ERROR_INCOMING_CALLS_BARRED_WITHIN_CUG = "IncomingCallsBarredWithinCugError";
-this.GECKO_CALL_ERROR_BEARER_CAPABILITY_NOT_AUTHORIZED = "BearerCapabilityNotAuthorizedError";
-this.GECKO_CALL_ERROR_BEARER_CAPABILITY_NOT_AVAILABLE = "BearerCapabilityNotAvailableError";
-this.GECKO_CALL_ERROR_BEARER_NOT_IMPLEMENTED = "BearerNotImplementedError";
-this.GECKO_CALL_ERROR_SERVICE_NOT_AVAILABLE = "ServiceNotAvailableError";
-this.GECKO_CALL_ERROR_INCOMING_CALL_EXCEEDED = "IncomingCallExceededError";
-this.GECKO_CALL_ERROR_REQUESTED_FACILITY_NOT_IMPLEMENTED = "RequestedFacilityNotImplementedError";
-this.GECKO_CALL_ERROR_UNRESTRICTED_BEARER_NOT_AVAILABLE = "UnrestrictedBearerNotAvailableError";
-this.GECKO_CALL_ERROR_SERVICE_NOT_IMPLEMENTED = "ServiceNotImplementedError";
-this.GECKO_CALL_ERROR_INVALID_TRANSACTION_ID = "InvalidTransactionIdError";
-this.GECKO_CALL_ERROR_USER_NOT_CUG_MEMBER = "NotCugMemberError";
-this.GECKO_CALL_ERROR_INCOMPATIBLE_DESTINATION = "IncompatibleDestinationError";
-this.GECKO_CALL_ERROR_INVALID_TRANSIT_NETWORK_SELECTION = "InvalidTransitNetworkSelectionError";
-this.GECKO_CALL_ERROR_SEMANTICALLY_INCORRECT_MESSAGE = "SemanticallyIncorrectMessageError";
-this.GECKO_CALL_ERROR_INVALID_MANDATORY_INFO = "InvalidMandatoryInfoError";
-this.GECKO_CALL_ERROR_MESSAGE_TYPE_NOT_IMPLEMENTED = "MessageTypeNotImplementedError";
-this.GECKO_CALL_ERROR_MESSAGE_TYPE_INCOMPATIBLE_PROTOCOL_STATE = "MessageTypeIncompatibleProtocolStateError";
-this.GECKO_CALL_ERROR_INFO_ELEMENT_NOT_IMPLEMENTED = "InfoElementNotImplementedError";
-this.GECKO_CALL_ERROR_CONDITIONAL_IE = "ConditionalIeError";
-this.GECKO_CALL_ERROR_MESSAGE_INCOMPATIBLE_PROTOCOL_STATE = "MessageIncompatibleProtocolStateError";
-this.GECKO_CALL_ERROR_RECOVERY_ON_TIMER_EXPIRY = "RecoveryOnTimerExpiryError";
-this.GECKO_CALL_ERROR_PROTOCOL = "ProtocolError";
-this.GECKO_CALL_ERROR_INTERWORKING = "InterworkingError";
-this.GECKO_CALL_ERROR_BARRED = "BarredError";
-this.GECKO_CALL_ERROR_FDN_BLOCKED = "FDNBlockedError";
-this.GECKO_CALL_ERROR_SUBSCRIBER_UNKNOWN = "SubscriberUnknownError";
-this.GECKO_CALL_ERROR_DEVICE_NOT_ACCEPTED = "DeviceNotAcceptedError";
-this.GECKO_CALL_ERROR_MODIFIED_TO_DIAL_FAILED = "ModifiedDialError";
-this.GECKO_CALL_ERROR_CDMA_LOCKED_UNTIL_POWER_CYCLE = "CdmaLockedUntilPowerCycleError";
-this.GECKO_CALL_ERROR_CDMA_DROP = "CdmaDropError";
-this.GECKO_CALL_ERROR_CDMA_INTERCEPT = "CdmaInterceptError";
-this.GECKO_CALL_ERROR_CDMA_REORDER = "CdmaReorderError";
-this.GECKO_CALL_ERROR_CDMA_SO_REJECT = "CdmaSoRejectError";
-this.GECKO_CALL_ERROR_CDMA_RETRY_ORDER = "CdmaRetryOrderError";
-this.GECKO_CALL_ERROR_CDMA_ACCESS_FAILURE = "CdmaAcessError";
-this.GECKO_CALL_ERROR_CDMA_PREEMPTED = "CdmaPreemptedError";
-this.GECKO_CALL_ERROR_CDMA_NOT_EMERGENCY = "CdmaNotEmergencyError";
-this.GECKO_CALL_ERROR_CDMA_ACCESS_BLOCKED = "CdmaAccessBlockedError";
-this.GECKO_CALL_ERROR_UNSPECIFIED = "UnspecifiedError";
-
-this.RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR = {};
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_UNOBTAINABLE_NUMBER] = GECKO_CALL_ERROR_BAD_NUMBER;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_NO_ROUTE_TO_DESTINATION] = GECKO_CALL_ERROR_NO_ROUTE_TO_DESTINATION;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CHANNEL_UNACCEPTABLE] = GECKO_CALL_ERROR_CHANNEL_UNACCEPTABLE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_OPERATOR_DETERMINED_BARRING] = GECKO_CALL_ERROR_OPERATOR_DETERMINED_BARRING;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_NORMAL] = GECKO_CALL_ERROR_NORMAL_CALL_CLEARING;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_BUSY] = GECKO_CALL_ERROR_BUSY;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_NO_USER_RESPONDING] = GECKO_CALL_ERROR_NO_USER_RESPONDING;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_USER_ALERTING] = GECKO_CALL_ERROR_USER_ALERTING;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CALL_REJECTED] = GECKO_CALL_ERROR_REJECTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_NUMBER_CHANGED] = GECKO_CALL_ERROR_NUMBER_CHANGED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CALL_REJECTED_DESTINATION_FEATURE] = GECKO_CALL_ERROR_REJECTED_DETINATION_FEATURE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CALL_PRE_EMPTION] = GECKO_CALL_ERROR_PRE_EMPTION;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_DEST_OUT_OF_ORDER] = GECKO_CALL_ERROR_DEST_OUT_OF_ORDER;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_INVALID_FORMAT] = GECKO_CALL_ERROR_INVALID_NUMBER_FORMAT;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_FACILITY_REJECTED] = GECKO_CALL_ERROR_FACILITY_REJECTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_RESPONSE_TO_STATUS_ENQUIRY] = GECKO_CALL_ERROR_RESPONSE_TO_STATUS_ENQUIRY;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_NORMAL_UNSPECIFIED] = GECKO_CALL_ERROR_NORMAL_CALL_CLEARING;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CONGESTION] = GECKO_CALL_ERROR_CONGESTION;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_NETWORK_OUT_OF_ORDER] = GECKO_CALL_ERROR_NETWORK_OUT_OF_ORDER;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_NETWORK_TEMP_FAILURE] = GECKO_CALL_ERROR_NETWORK_TEMP_FAILURE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_SWITCHING_EQUIP_CONGESTION] = GECKO_CALL_ERROR_SWITCHING_EQUIP_CONGESTION;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_ACCESS_INFO_DISCARDED] = GECKO_CALL_ERROR_ACCESS_INFO_DISCARDED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_REQUESTED_CHANNEL_NOT_AVAILABLE] = GECKO_CALL_ERROR_REQUESTED_CHANNEL_NOT_AVAILABLE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_RESOURCE_UNAVAILABLE] = GECKO_CALL_ERROR_RESOURCE_UNAVAILABLE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_QOS_UNAVAILABLE] = GECKO_CALL_ERROR_QOS_UNAVAILABLE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_REQUESTED_FACILITY_NOT_SUBSCRIBED] = GECKO_CALL_ERROR_REQUESTED_FACILITY_NOT_SUBSCRIBED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_INCOMING_CALLS_BARRED_WITHIN_CUG] = GECKO_CALL_ERROR_INCOMING_CALLS_BARRED_WITHIN_CUG;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_BEARER_CAPABILITY_NOT_AUTHORIZED] = GECKO_CALL_ERROR_BEARER_CAPABILITY_NOT_AUTHORIZED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_BEARER_CAPABILITY_NOT_AVAILABLE] = GECKO_CALL_ERROR_BEARER_CAPABILITY_NOT_AVAILABLE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_SERVICE_NOT_AVAILABLE] = GECKO_CALL_ERROR_SERVICE_NOT_AVAILABLE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_BEARER_NOT_IMPLEMENTED] = GECKO_CALL_ERROR_BEARER_NOT_IMPLEMENTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_ACM_LIMIT_EXCEEDED] = GECKO_CALL_ERROR_INCOMING_CALL_EXCEEDED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_REQUESTED_FACILITY_NOT_IMPLEMENTED] = GECKO_CALL_ERROR_REQUESTED_FACILITY_NOT_IMPLEMENTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_UNRESTRICTED_BEARER_NOT_AVAILABLE] = GECKO_CALL_ERROR_UNRESTRICTED_BEARER_NOT_AVAILABLE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_SERVICE_NOT_IMPLEMENTED] = GECKO_CALL_ERROR_SERVICE_NOT_IMPLEMENTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_INVALID_TRANSACTION_ID] = GECKO_CALL_ERROR_INVALID_TRANSACTION_ID;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_USER_NOT_CUG_MEMBER] = GECKO_CALL_ERROR_USER_NOT_CUG_MEMBER;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_INCOMPATIBLE_DESTINATION] = GECKO_CALL_ERROR_INCOMPATIBLE_DESTINATION;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_INVALID_TRANSIT_NETWORK_SELECTION] = GECKO_CALL_ERROR_INVALID_TRANSIT_NETWORK_SELECTION;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_SEMANTICALLY_INCORRECT_MESSAGE] = GECKO_CALL_ERROR_SEMANTICALLY_INCORRECT_MESSAGE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_INVALID_MANDATORY_INFO] = GECKO_CALL_ERROR_INVALID_MANDATORY_INFO;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_MESSAGE_TYPE_NOT_IMPLEMENTED] = GECKO_CALL_ERROR_MESSAGE_TYPE_NOT_IMPLEMENTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_MESSAGE_TYPE_INCOMPATIBLE_PROTOCOL_STATE] = GECKO_CALL_ERROR_MESSAGE_TYPE_INCOMPATIBLE_PROTOCOL_STATE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_INFO_ELEMENT_NOT_IMPLEMENTED] = GECKO_CALL_ERROR_INFO_ELEMENT_NOT_IMPLEMENTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CONDITIONAL_IE_ERROR] = GECKO_CALL_ERROR_CONDITIONAL_IE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_MESSAGE_INCOMPABITLE_PROTOCOL_STATE] = GECKO_CALL_ERROR_MESSAGE_INCOMPATIBLE_PROTOCOL_STATE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_RECOVERY_ON_TIMER_EXPIRY] = GECKO_CALL_ERROR_RECOVERY_ON_TIMER_EXPIRY;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_PROTOCOL_ERROR] = GECKO_CALL_ERROR_PROTOCOL;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_INTERWORKING] = GECKO_CALL_ERROR_INTERWORKING;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CALL_BARRED] = GECKO_CALL_ERROR_BARRED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_FDN_BLOCKED] = GECKO_CALL_ERROR_FDN_BLOCKED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_IMSI_UNKNOWN_IN_VLR] = GECKO_CALL_ERROR_SUBSCRIBER_UNKNOWN;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_IMEI_NOT_ACCEPTED] = GECKO_CALL_ERROR_DEVICE_NOT_ACCEPTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_DIAL_MODIFIED_TO_USSD] = GECKO_CALL_ERROR_MODIFIED_TO_DIAL_FAILED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_DIAL_MODIFIED_TO_SS] = GECKO_CALL_ERROR_MODIFIED_TO_DIAL_FAILED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_DIAL_MODIFIED_TO_DIAL] = GECKO_CALL_ERROR_MODIFIED_TO_DIAL_FAILED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_LOCKED_UNTIL_POWER_CYCLE] = GECKO_CALL_ERROR_CDMA_LOCKED_UNTIL_POWER_CYCLE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_DROP] = GECKO_CALL_ERROR_CDMA_DROP;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_INTERCEPT] = GECKO_CALL_ERROR_CDMA_INTERCEPT;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_REORDER] = GECKO_CALL_ERROR_CDMA_REORDER;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_SO_REJECT] = GECKO_CALL_ERROR_CDMA_SO_REJECT;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_RETRY_ORDER] = GECKO_CALL_ERROR_CDMA_RETRY_ORDER;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_ACCESS_FAILURE] = GECKO_CALL_ERROR_CDMA_ACCESS_FAILURE;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_PREEMPTED] = GECKO_CALL_ERROR_CDMA_PREEMPTED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_NOT_EMERGENCY] = GECKO_CALL_ERROR_CDMA_NOT_EMERGENCY;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_CDMA_ACCESS_BLOCKED] = GECKO_CALL_ERROR_CDMA_ACCESS_BLOCKED;
-RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_ERROR_UNSPECIFIED] = GECKO_CALL_ERROR_UNSPECIFIED;
-
-this.GECKO_DATACALL_ERROR_OPERATOR_BARRED = "OperatorBarredError";
-this.GECKO_DATACALL_ERROR_INSUFFICIENT_RESOURCES = "InsufficientResourcesError";
-this.GECKO_DATACALL_ERROR_MISSING_UKNOWN_APN = "MissingUnknownAPNError";
-this.GECKO_DATACALL_ERROR_UNKNOWN_PDP_ADDRESS_TYPE = "UnknownPDPAddressTypeError";
-this.GECKO_DATACALL_ERROR_USER_AUTHENTICATION = "UserAuthenticationError";
-this.GECKO_DATACALL_ERROR_ACTIVATION_REJECT_GGSN = "ActivationRejectGGSNError";
-this.GECKO_DATACALL_ERROR_ACTIVATION_REJECT_UNSPECIFIED = "ActivationRejectUnspecifiedError";
-this.GECKO_DATACALL_ERROR_SERVICE_OPTION_NOT_SUPPORTED = "ServiceOptionNotSupportedError";
-this.GECKO_DATACALL_ERROR_SERVICE_OPTION_NOT_SUBSCRIBED = "ServiceOptionNotSubscribedError";
-this.GECKO_DATACALL_ERROR_SERVICE_OPTION_OUT_OF_ORDER = "ServiceOptionOutOfOrderError";
-this.GECKO_DATACALL_ERROR_NSAPI_IN_USE = "NSAPIInUseError";
-this.GECKO_DATACALL_ERROR_ONLY_IPV4_ALLOWED = "OnlyIPv4Error";
-this.GECKO_DATACALL_ERROR_ONLY_IPV6_ALLOWED = "OnlyIPv6Error";
-this.GECKO_DATACALL_ERROR_ONLY_SINGLE_BEARER_ALLOWED = "OnlySingleBearerAllowedError";
-this.GECKO_DATACALL_ERROR_PROTOCOL_ERRORS = "ProtocolErrorsError";
-this.GECKO_DATACALL_ERROR_VOICE_REGISTRATION_FAIL = "VoiceRegistrationFailError";
-this.GECKO_DATACALL_ERROR_DATA_REGISTRATION_FAIL = "DataRegistrationFailError";
-this.GECKO_DATACALL_ERROR_SIGNAL_LOST = "SignalLostError";
-this.GECKO_DATACALL_ERROR_PREF_RADIO_TECH_CHANGED = "PrefRadioTechChangedError";
-this.GECKO_DATACALL_ERROR_RADIO_POWER_OFF = "RadioPowerOffError";
-this.GECKO_DATACALL_ERROR_TETHERED_CALL_ACTIVE = "TetheredCallActiveError";
-this.GECKO_DATACALL_ERROR_UNSPECIFIED = "UnspecifiedError";
-
-this.RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR = {};
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_OPERATOR_BARRED] = GECKO_DATACALL_ERROR_OPERATOR_BARRED;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_INSUFFICIENT_RESOURCES] = GECKO_DATACALL_ERROR_INSUFFICIENT_RESOURCES;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_MISSING_UKNOWN_APN] = GECKO_DATACALL_ERROR_MISSING_UKNOWN_APN;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_UNKNOWN_PDP_ADDRESS_TYPE] = GECKO_DATACALL_ERROR_UNKNOWN_PDP_ADDRESS_TYPE;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_USER_AUTHENTICATION] = GECKO_DATACALL_ERROR_USER_AUTHENTICATION;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_ACTIVATION_REJECT_GGSN] = GECKO_DATACALL_ERROR_ACTIVATION_REJECT_GGSN;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_ACTIVATION_REJECT_UNSPECIFIED] = GECKO_DATACALL_ERROR_ACTIVATION_REJECT_UNSPECIFIED;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_SERVICE_OPTION_NOT_SUPPORTED] = GECKO_DATACALL_ERROR_SERVICE_OPTION_NOT_SUPPORTED;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_SERVICE_OPTION_NOT_SUBSCRIBED] = GECKO_DATACALL_ERROR_SERVICE_OPTION_NOT_SUBSCRIBED;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_SERVICE_OPTION_OUT_OF_ORDER] = GECKO_DATACALL_ERROR_SERVICE_OPTION_OUT_OF_ORDER;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_NSAPI_IN_USE] = GECKO_DATACALL_ERROR_NSAPI_IN_USE;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_ONLY_IPV4_ALLOWED] = GECKO_DATACALL_ERROR_ONLY_IPV4_ALLOWED;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_ONLY_IPV6_ALLOWED] = GECKO_DATACALL_ERROR_ONLY_IPV6_ALLOWED;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_ONLY_SINGLE_BEARER_ALLOWED] = GECKO_DATACALL_ERROR_ONLY_SINGLE_BEARER_ALLOWED;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_PROTOCOL_ERRORS] = GECKO_DATACALL_ERROR_PROTOCOL_ERRORS;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_VOICE_REGISTRATION_FAIL] = GECKO_DATACALL_ERROR_VOICE_REGISTRATION_FAIL;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_DATA_REGISTRATION_FAIL] = GECKO_DATACALL_ERROR_DATA_REGISTRATION_FAIL;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_SIGNAL_LOST] = GECKO_DATACALL_ERROR_SIGNAL_LOST;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_PREF_RADIO_TECH_CHANGED] = GECKO_DATACALL_ERROR_PREF_RADIO_TECH_CHANGED;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_RADIO_POWER_OFF] = GECKO_DATACALL_ERROR_RADIO_POWER_OFF;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_TETHERED_CALL_ACTIVE] = GECKO_DATACALL_ERROR_TETHERED_CALL_ACTIVE;
-RIL_DATACALL_FAILCAUSE_TO_GECKO_DATACALL_ERROR[DATACALL_FAIL_ERROR_UNSPECIFIED] = GECKO_DATACALL_ERROR_UNSPECIFIED;
-
-this.GECKO_RADIO_TECH = [
- null,
- "gprs",
- "edge",
- "umts",
- "is95a",
- "is95b",
- "1xrtt",
- "evdo0",
- "evdoa",
- "hsdpa",
- "hsupa",
- "hspa",
- "evdob",
- "ehrpd",
- "lte",
- "hspa+",
- "gsm",
- null,
- "hspa+", // DC-HSPA+
- "hspa+"
-];
-
-this.GECKO_VOICEMAIL_MESSAGE_COUNT_UNKNOWN = -1;
-
-// Call forwarding action. Must be in sync with nsIMobileConnectionService interface
-this.CALL_FORWARD_ACTION_DISABLE = 0;
-this.CALL_FORWARD_ACTION_ENABLE = 1;
-this.CALL_FORWARD_ACTION_QUERY_STATUS = 2;
-this.CALL_FORWARD_ACTION_REGISTRATION = 3;
-this.CALL_FORWARD_ACTION_ERASURE = 4;
-
-// Call forwarding reason. Must be in sync with nsIMobileConnectionService interface
-this.CALL_FORWARD_REASON_UNCONDITIONAL = 0;
-this.CALL_FORWARD_REASON_MOBILE_BUSY = 1;
-this.CALL_FORWARD_REASON_NO_REPLY = 2;
-this.CALL_FORWARD_REASON_NOT_REACHABLE = 3;
-this.CALL_FORWARD_REASON_ALL_CALL_FORWARDING = 4;
-this.CALL_FORWARD_REASON_ALL_CONDITIONAL_CALL_FORWARDING = 5;
-
-// Call barring program. Must be in sync with nsIMobileConnectionService interface
-this.CALL_BARRING_PROGRAM_ALL_OUTGOING = 0;
-this.CALL_BARRING_PROGRAM_OUTGOING_INTERNATIONAL = 1;
-this.CALL_BARRING_PROGRAM_OUTGOING_INTERNATIONAL_EXCEPT_HOME = 2;
-this.CALL_BARRING_PROGRAM_ALL_INCOMING = 3;
-this.CALL_BARRING_PROGRAM_INCOMING_ROAMING = 4;
-this.CALL_BARRING_PROGRAM_ALL_SERVICE = 5;
-this.CALL_BARRING_PROGRAM_OUTGOING_SERVICE = 6;
-this.CALL_BARRING_PROGRAM_INCOMING_SERVICE = 7;
-
-this.CALL_BARRING_PROGRAM_TO_FACILITY = {};
-CALL_BARRING_PROGRAM_TO_FACILITY[CALL_BARRING_PROGRAM_ALL_OUTGOING] = ICC_CB_FACILITY_BAOC;
-CALL_BARRING_PROGRAM_TO_FACILITY[CALL_BARRING_PROGRAM_OUTGOING_INTERNATIONAL] = ICC_CB_FACILITY_BAOIC;
-CALL_BARRING_PROGRAM_TO_FACILITY[CALL_BARRING_PROGRAM_OUTGOING_INTERNATIONAL_EXCEPT_HOME] = ICC_CB_FACILITY_BAOICxH;
-CALL_BARRING_PROGRAM_TO_FACILITY[CALL_BARRING_PROGRAM_ALL_INCOMING] = ICC_CB_FACILITY_BAIC;
-CALL_BARRING_PROGRAM_TO_FACILITY[CALL_BARRING_PROGRAM_INCOMING_ROAMING] = ICC_CB_FACILITY_BAICr;
-CALL_BARRING_PROGRAM_TO_FACILITY[CALL_BARRING_PROGRAM_ALL_SERVICE] = ICC_CB_FACILITY_BA_ALL;
-CALL_BARRING_PROGRAM_TO_FACILITY[CALL_BARRING_PROGRAM_OUTGOING_SERVICE] = ICC_CB_FACILITY_BA_MO;
-CALL_BARRING_PROGRAM_TO_FACILITY[CALL_BARRING_PROGRAM_INCOMING_SERVICE] = ICC_CB_FACILITY_BA_MT;
-
-/**
- * CDMA PDU constants
- */
-
-// SMS Message Type, as defined in 3GPP2 C.S0015-A v2.0, Table 3.4-1
-this.PDU_CDMA_MSG_TYPE_P2P = 0x00; // Point-to-Point
-this.PDU_CDMA_MSG_TYPE_BROADCAST = 0x01; // Broadcast
-this.PDU_CDMA_MSG_TYPE_ACK = 0x02; // Acknowledge
-
-// SMS Teleservice Identitifier, as defined in 3GPP2 N.S0005, Table 175
-this.PDU_CDMA_MSG_TELESERIVCIE_ID_SMS = 0x1002; // SMS
-this.PDU_CDMA_MSG_TELESERIVCIE_ID_WAP = 0x1004; // WAP
-this.PDU_CDMA_MSG_TELESERIVCIE_ID_WEMT = 0x1005; // Wireless Enhanced Messaging Teleservice
- // required for fragmented SMS
-
-// SMS Service Category, as defined in 3GPP2 C.R1001-D, Table 9.3.1-1
-this.PDU_CDMA_MSG_CATEGORY_UNSPEC = 0x00; // Unknown/Unspecified
-
-// Address Information, Digit Mode, as defined in 3GPP2 C.S0015-A v2.0, sec 3.4.3.3
-this.PDU_CDMA_MSG_ADDR_DIGIT_MODE_DTMF = 0x00; // Digit Mode : DTMF
-this.PDU_CDMA_MSG_ADDR_DIGIT_MODE_ASCII = 0x01; // Digit Mode : 8-bit ASCII with MSB = 0
-
-// Address Information, Number Mode, as defined in 3GPP2 C.S0015-A v2.0, sec 3.4.3.3
-this.PDU_CDMA_MSG_ADDR_NUMBER_MODE_ANSI = 0x00; // Number Mode : ANSI T1.607-2000(R2004)
-this.PDU_CDMA_MSG_ADDR_NUMBER_MODE_ASCII = 0x01; // Number Mode : Data network address format
-
-// Address Information, Number Type, as defined in 3GPP2 C.S0015-A v2.0, Table 3.4.3.3-1
-this.PDU_CDMA_MSG_ADDR_NUMBER_TYPE_UNKNOWN = 0x00; // Number Type : Unknown
-this.PDU_CDMA_MSG_ADDR_NUMBER_TYPE_INTERNATIONAL = 0x01; // Number Type : Internaltional number(+XXXXX)
-this.PDU_CDMA_MSG_ADDR_NUMBER_TYPE_NATIONAL = 0x02; // Number Type : National number
-
-// Address Information, Number Plan, as defined in 3GPP2 C.S0005-D v2.0, Table 2.7.1.3.2.4-3
-this.PDU_CDMA_MSG_ADDR_NUMBER_PLAN_UNKNOWN = 0x00; // Number Plan : Unknown
-this.PDU_CDMA_MSG_ADDR_NUMBER_PLAN_ISDN = 0x01; // Number Plan : ISDN/Telephony numbering plan
-
-// SMS Encoding, as defined in 3GPP2 C.R1001-D, Table 9.1-1
-this.PDU_CDMA_MSG_CODING_OCTET = 0x00; // octet(8-bit), Not tested
-this.PDU_CDMA_MSG_CODING_IS_91 = 0x01; // IS-91 Extended Protocol Message(variable), Not tested
-this.PDU_CDMA_MSG_CODING_7BITS_ASCII = 0x02; // 7-bit ASCII(7-bit)
-this.PDU_CDMA_MSG_CODING_IA5 = 0x03; // IA5(7-bit), Not tested
-this.PDU_CDMA_MSG_CODING_UNICODE = 0x04; // Unicode(16-bit)
-this.PDU_CDMA_MSG_CODING_SHIFT_JIS = 0x05; // Shift-6 JIS(8/16-bit variable), Not supported
-this.PDU_CDMA_MSG_CODING_KOREAN = 0x06; // Korean(8/16-bit variable), Not supported
-this.PDU_CDMA_MSG_CODING_LATIN_HEBREW = 0x07; // Latin/ Hebrew(8-bit), ISO/IEC 8859-8, Not supported
-this.PDU_CDMA_MSG_CODING_LATIN = 0x08; // Latin(8-bit), ISO/IEC 8859-1, Not tested
-this.PDU_CDMA_MSG_CODING_7BITS_GSM = 0x09; // GSM 7-bit default alphabet(7-bit), Not tested
-this.PDU_CDMA_MSG_CODING_GSM_DCS = 0x0A; // GSM Data-Coding-Scheme, Not supported
-
-// SMS Message Type, as defined in 3GPP2 C.S0015-A v2.0, Table 4.5.1-1
-this.PDU_CDMA_MSG_TYPE_DELIVER = 0x01; // Deliver
-this.PDU_CDMA_MSG_TYPE_SUBMIT = 0x02; // Submit
-this.PDU_CDMA_MSG_TYPE_DELIVER_ACK = 0x04; // Delivery Acknowledgment
-
-// SMS User Data Subparameters, as defined in 3GPP2 C.S0015-A v2.0, Table 4.5-1
-this.PDU_CDMA_MSG_USERDATA_MSG_ID = 0x00; // Message Identifier
-this.PDU_CDMA_MSG_USERDATA_BODY = 0x01; // User Data Body
-this.PDU_CDMA_MSG_USERDATA_TIMESTAMP = 0x03; // Message Center Time Stamp
-this.PDU_CDMA_MSG_USERDATA_REPLY_OPTION = 0x0A; // Reply Option
-this.PDU_CDMA_LANGUAGE_INDICATOR = 0x0D; // Language Indicator
-this.PDU_CDMA_MSG_USERDATA_CALLBACK_NUMBER = 0x0E; // Callback Number
-this.PDU_CDMA_MSG_USER_DATA_MSG_STATUS = 0x14; // Message Status
-
-// CDMA Language Indicator: Language groups
-// see 3GPP2 C.R1001-F table 9.2-1
-this.CB_CDMA_LANG_GROUP = [
- null, "en", "fr", "es", "ja", "ko", "zh", "he"
-];
-
-// IS-91 Message Type, as defined in TIA/EIA/IS-91-A, Table 9
-this.PDU_CDMA_MSG_CODING_IS_91_TYPE_VOICEMAIL_STATUS = 0x82;
-this.PDU_CDMA_MSG_CODING_IS_91_TYPE_SMS_FULL = 0x83;
-this.PDU_CDMA_MSG_CODING_IS_91_TYPE_CLI = 0x84;
-this.PDU_CDMA_MSG_CODING_IS_91_TYPE_SMS = 0x85;
-
-// Information Record Type, reference from ril.h
-this.PDU_CDMA_INFO_REC_TYPE_DISPLAY = 0;
-this.PDU_CDMA_INFO_REC_TYPE_CALLED_PARTY_NUMBER = 1;
-this.PDU_CDMA_INFO_REC_TYPE_CALLING_PARTY_NUMBER = 2;
-this.PDU_CDMA_INFO_REC_TYPE_CONNECTED_NUMBER =3;
-this.PDU_CDMA_INFO_REC_TYPE_SIGNAL = 4;
-this.PDU_CDMA_INFO_REC_TYPE_REDIRECTING_NUMBER = 5;
-this.PDU_CDMA_INFO_REC_TYPE_LINE_CONTROL = 6;
-this.PDU_CDMA_INFO_REC_TYPE_EXTENDED_DISPLAY = 7;
-this.PDU_CDMA_INFO_REC_TYPE_T53_CLIR = 8;
-this.PDU_CDMA_INFO_REC_TYPE_T53_RELEASE = 9;
-this.PDU_CDMA_INFO_REC_TYPE_T53_AUDIO_CONTROL = 10;
-
-// Display type of extended display of information record,
-// as defined in C.S0005-F v1.0, Table 3.7.5.16-2
-this.INFO_REC_EXTENDED_DISPLAY_BLANK = 0x80;
-this.INFO_REC_EXTENDED_DISPLAY_SKIP = 0x81;
-this.INFO_REC_EXTENDED_DISPLAY_CONTINATION = 0x82;
-this.INFO_REC_EXTENDED_DISPLAY_CALLED_ADDRESS = 0x83;
-this.INFO_REC_EXTENDED_DISPLAY_CAUSE = 0x84;
-this.INFO_REC_EXTENDED_DISPLAY_PROGRESS_INDICATOR = 0x85;
-this.INFO_REC_EXTENDED_DISPLAY_NOTIFICATION_INDICATOR = 0x86;
-this.INFO_REC_EXTENDED_DISPLAY_PROMPT = 0x87;
-this.INFO_REC_EXTENDED_DISPLAY_ACCUMULATED_DIGITS = 0x88;
-this.INFO_REC_EXTENDED_DISPLAY_STATUS = 0x89;
-this.INFO_REC_EXTENDED_DISPLAY_INBAND = 0x8A;
-this.INFO_REC_EXTENDED_DISPLAY_CALLING_ADDRESS = 0x8B;
-this.INFO_REC_EXTENDED_DISPLAY_REASON = 0x8C;
-this.INFO_REC_EXTENDED_DISPLAY_CALLING_PARTY_NAME = 0x8D;
-this.INFO_REC_EXTENDED_DISPLAY_CALLED_PARTY_NAME = 0x8E;
-this.INFO_REC_EXTENDED_DISPLAY_ORIGINAL_CALLED_NAME = 0x8F;
-this.INFO_REC_EXTENDED_DISPLAY_REDIRECT_NAME = 0x90;
-this.INFO_REC_EXTENDED_DISPLAY_CONNECTED_NAME = 0x91;
-this.INFO_REC_EXTENDED_DISPLAY_ORIGINATING_RESTRICTIONS = 0x92;
-this.INFO_REC_EXTENDED_DISPLAY_DATE_TIME_OF_DAY = 0x93;
-this.INFO_REC_EXTENDED_DISPLAY_CALL_APPEARANCE_ID = 0x94;
-this.INFO_REC_EXTENDED_DISPLAY_FEATURE_ADDRESS = 0x95;
-this.INFO_REC_EXTENDED_DISPLAY_REDIRECTION_NAME = 0x96;
-this.INFO_REC_EXTENDED_DISPLAY_REDIRECTION_NUMBER = 0x97;
-this.INFO_REC_EXTENDED_DISPLAY_REDIRECTING_NUMBER = 0x98;
-this.INFO_REC_EXTENDED_DISPLAY_ORIGINAL_CALLED_NUMBER = 0x99;
-this.INFO_REC_EXTENDED_DISPLAY_CONNECTED_NUMBER = 0x9A;
-this.INFO_REC_EXTENDED_DISPLAY_TEXT = 0x9B;
-
-/**
- * The table for MCC/MNC which the length of MNC is 3.
- *
- * This table is built from below links.
- * - http://www.itu.int/pub/T-SP-E.212B-2013
- * - http://en.wikipedia.org/wiki/Mobile_Network_Code
- */
-this.PLMN_HAVING_3DIGITS_MNC = {
- // Puerto Rico.
- "330":
- ["110", // América Móvil
- "120" // PR Wireless
- ],
- // Trinidad and Tobago.
- "374":
- ["130", // Digicel Trinidad and Tobago Ltd.
- "140" // LaqTel Ltd.
- ],
- // India.
- "405":
- ["000", // Shyam Telelink Ltd.
- "005", // Reliance, Delhi
- "006", // Reliance, Gujarat
- "007", // Reliance, Haryana
- "009", // Reliance, J&K
- "010", // Reliance, Karnataka
- "011", // Reliance, Kerala
- "012", // Reliance, Andhra Pradesh
- "013", // Reliance, Maharashtr
- "014", // Reliance, Madhya Pradesh
- "018", // Reliance, Punjab
- "020", // Reliance, Tamilnadu
- "021", // Reliance, UP (East)
- "022", // Reliance, UP (West)
- "025", // TATA DOCOMO, Andhra Pradesh
- "026", // TATA DOCOMO, Assam
- "027", // TATA DOCOMO, Bihar
- "028", // TATA DOCOMO, Chennai
- "029", // TATA DOCOMO, Delhi
- "030", // TATA DOCOMO, Gujarat
- "031", // TATA DOCOMO, Haryana
- "032", // TATA DOCOMO, Himachal Pradesh
- "033", // Reliance, Bihar
- "034", // TATA DOCOMO, Kamataka
- "035", // TATA DOCOMO, Kerala
- "036", // TATA DOCOMO, Kolkata
- "037", // TATA DOCOMO, Maharashtra
- "038", // TATA DOCOMO, Madhya Pradesh
- "039", // TATA DOCOMO, Mumbai
- "040", // Reliance, Chennai
- "041", // TATA DOCOMO, Orissa
- "042", // TATA DOCOMO, Punjab
- "043", // TATA DOCOMO, Rajasthan
- "044", // TATA DOCOMO, Tamilnadu
- "045", // TATA DOCOMO, UP (East)
- "046", // TATA DOCOMO, UP (West)
- "047", // TATA DOCOMO, West Bengal
- "750", // Vodafone IN, J&K
- "751", // Vodafone IN, Assam
- "752", // Vodafone IN, Bihar
- "753", // Vodafone IN, Orissa
- "754", // Vodafone IN, Himachal Pradesh
- "755", // Vodafone IN, North East
- "756", // Vodafone IN, Madhya Pradesh & Chhattisgarh
- "799", // Idea, MUMBAI
- "800", // Aircell, Delhi
- "801", // Aircell, Andhra Pradesh
- "802", // Aircell, Gujarat
- "803", // Aircell, Kamataka
- "804", // Aircell, Maharashtra
- "805", // Aircell, Mumbai
- "806", // Aircell, Rajasthan
- "807", // Aircell, Haryana
- "808", // Aircell, Madhya Pradesh
- "809", // Aircell, Kerala
- "810", // Aircell, Uttar Pradesh (East)
- "811", // Aircell, Uttar Pradesh (West)
- "812", // Aircell, Punjab
- "818", // Uninor, Uttar Pradesh (West)
- "819", // Uninor, Andhra Pradesh
- "820", // Uninor, Karnataka
- "821", // Uninor, Kerala
- "822", // Uninor, Kolkata
- "824", // Videocon, Assam
- "827", // Videocon, Gujarat
- "834", // Videocon, Madhya Pradesh
- "840", // Jio, West Bengal
- "844", // Uninor, Delhi & NCR
- "845", // IDEA, Assam
- "846", // IDEA, Jammu & Kashmir
- "847", // IDEA, Karnataka
- "848", // IDEA, Kolkata
- "849", // IDEA, North East
- "850", // IDEA, Orissa
- "851", // IDEA, Punjab
- "852", // IDEA, Tamil Nadu
- "853", // IDEA, West Bengal
- "854", // Jio, Andra Pradesh
- "855", // Jio, Assam
- "856", // Jio, Bihar
- "857", // Jio, Gujarat
- "858", // Jio, Haryana
- "859", // Jio, Himachal Pradesh
- "860", // Jio, Jammu Kashmir
- "861", // Jio, Karnataka
- "862", // Jio, Kerala
- "863", // Jio, Madhyya Pradesh
- "864", // Jio, Maharashtra
- "865", // Jio, North East
- "866", // Jio, Orissa
- "867", // Jio, Punjab
- "868", // Jio, Rajasthan
- "869", // Jio, Tamil Nadu Chennai
- "870", // Jio, Uttar Pradesh West
- "871", // Jio, Uttar Pradesh East
- "872", // Jio, Delhi
- "873", // Jio, Kolkatta
- "874", // Jio, Mumbai
- "875", // Uninor, Assam
- "880", // Uninor, West Bengal
- "881", // S Tel, Assam
- "908", // IDEA, Andhra Pradesh
- "909", // IDEA, Delhi
- "910", // IDEA, Haryana
- "911", // Etisalat, Maharashtra
- "912", // Etisalat, Andhra Pradesh
- "913", // Etisalat, Delhi & NCR
- "914", // Etisalat, Gujarat
- "917", // Etisalat, Kerala
- "927", // Uninor, Gujarat
- "929" // Uninor, Maharashtra
- ],
- // Malaysia.
- "502":
- ["150", // Tune Talk Sdn Bhd
- "151", // Baraka Telecom Sdn Bhd (MVNE)
- "152", // YTL Communications Sdn Bhd
- "156" // Altel Communications Sdn Bhd
- ],
- // Brazil.
- "724":
- ["055" // Sercomtel
- ]
-};
-
-/**
- * The table for MCC which the length of MNC is 3
- *
- * This table is built from below links.
- * - http://www.itu.int/pub/T-SP-E.212B-2013
- * - http://en.wikipedia.org/wiki/Mobile_Network_Code
- */
-this.MCC_TABLE_FOR_MNC_LENGTH_IS_3 = [
- "302", // Canada
- "310", // United States of America
- "311", // United States of America
- "312", // United States of America
- "313", // United States of America
- "316", // United States of America
- "330", // Puerto Rico
- "334", // Mexico
- "338", // Jamaica
- "342", // Barbados
- "344", // Antigua and Barbuda
- "346", // Cayman Islands
- "348", // British Virgin Islands
- "350", // Bermuda
- "352", // Grenada
- "354", // Montserrat
- "356", // Saint Kitts and Nevis
- "358", // Saint Lucia
- "360", // Saint Vincent and the Grenadines
- "365", // Anguilla
- "366", // Dominica
- "376", // Turks and Caicos Islands
- "708", // Honduras
- "722", // Argentina
- "732", // Colombia
- "750" // Falkland Islands (Malvinas)
-];
-
-// Supplementary service notifications, code2, as defined in 3GPP 27.007 7.17
-this.SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD = 2;
-this.SUPP_SVC_NOTIFICATION_CODE2_RETRIEVED = 3;
-
-this.GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD = "RemoteHeld";
-this.GECKO_SUPP_SVC_NOTIFICATION_REMOTE_RESUMED = "RemoteResumed";
-
-this.GECKO_SUPP_SVC_NOTIFICATION_FROM_CODE2 = {};
-GECKO_SUPP_SVC_NOTIFICATION_FROM_CODE2[SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD] = GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD;
-GECKO_SUPP_SVC_NOTIFICATION_FROM_CODE2[SUPP_SVC_NOTIFICATION_CODE2_RETRIEVED] = GECKO_SUPP_SVC_NOTIFICATION_REMOTE_RESUMED;
-
-/**
- * The status for an Over-the-Air Service Provisioning / Over-the-Air
- * Parameter Administration (OTASP/OTAPA) session.
- *
- * @see 3GPP2 C.S0016
- */
-this.GECKO_OTA_STATUS_SPL_UNLOCKED = "spl_unlocked";
-this.GECKO_OTA_STATUS_SPC_RETRIES_EXCEEDED = "spc_retries_exceeded";
-this.GECKO_OTA_STATUS_A_KEY_EXCHANGED = "a_key_exchanged";
-this.GECKO_OTA_STATUS_SSD_UPDATED = "ssd_updated";
-this.GECKO_OTA_STATUS_NAM_DOWNLOADED = "nam_downloaded";
-this.GECKO_OTA_STATUS_MDN_DOWNLOADED = "mdn_downloaded";
-this.GECKO_OTA_STATUS_IMSI_DOWNLOADED = "imsi_downloaded";
-this.GECKO_OTA_STATUS_PRL_DOWNLOADED = "prl_downloaded";
-this.GECKO_OTA_STATUS_COMMITTED = "committed";
-this.GECKO_OTA_STATUS_OTAPA_STARTED = "otapa_started";
-this.GECKO_OTA_STATUS_OTAPA_STOPPED = "otapa_stopped";
-this.GECKO_OTA_STATUS_OTAPA_ABORTED = "otapa_aborted";
-this.CDMA_OTA_PROVISION_STATUS_TO_GECKO = [
- GECKO_OTA_STATUS_SPL_UNLOCKED,
- GECKO_OTA_STATUS_SPC_RETRIES_EXCEEDED,
- GECKO_OTA_STATUS_A_KEY_EXCHANGED,
- GECKO_OTA_STATUS_SSD_UPDATED,
- GECKO_OTA_STATUS_NAM_DOWNLOADED,
- GECKO_OTA_STATUS_MDN_DOWNLOADED,
- GECKO_OTA_STATUS_IMSI_DOWNLOADED,
- GECKO_OTA_STATUS_PRL_DOWNLOADED,
- GECKO_OTA_STATUS_COMMITTED,
- GECKO_OTA_STATUS_OTAPA_STARTED,
- GECKO_OTA_STATUS_OTAPA_STOPPED,
- GECKO_OTA_STATUS_OTAPA_ABORTED
-];
-
-// Allow this file to be imported via Components.utils.import().
-this.EXPORTED_SYMBOLS = Object.keys(this);
diff --git a/dom/system/gonk/ril_worker.js b/dom/system/gonk/ril_worker.js
deleted file mode 100644
index 0608a5be3..000000000
--- a/dom/system/gonk/ril_worker.js
+++ /dev/null
@@ -1,15206 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * This file implements the RIL worker thread. It communicates with
- * the main thread to provide a high-level API to the phone's RIL
- * stack, and with the RIL IPC thread to communicate with the RIL
- * device itself. These communication channels use message events as
- * known from Web Workers:
- *
- * - postMessage()/"message" events for main thread communication
- *
- * - postRILMessage()/"RILMessageEvent" events for RIL IPC thread
- * communication.
- *
- * The two main objects in this file represent individual parts of this
- * communication chain:
- *
- * - RILMessageEvent -> Buf -> RIL -> postMessage() -> nsIRadioInterfaceLayer
- * - nsIRadioInterfaceLayer -> postMessage() -> RIL -> Buf -> postRILMessage()
- *
- * Note: The code below is purposely lean on abstractions to be as lean in
- * terms of object allocations. As a result, it may look more like C than
- * JavaScript, and that's intended.
- */
-
-/* global BufObject */
-/* global TelephonyRequestQueue */
-
-"use strict";
-
-importScripts("ril_consts.js");
-importScripts("resource://gre/modules/workers/require.js");
-importScripts("ril_worker_buf_object.js");
-importScripts("ril_worker_telephony_request_queue.js");
-
-// set to true in ril_consts.js to see debug messages
-var DEBUG = DEBUG_WORKER;
-var GLOBAL = this;
-
-if (!this.debug) {
- // Debugging stub that goes nowhere.
- this.debug = function debug(message) {
- dump("RIL Worker: " + message + "\n");
- };
-}
-
-// Timeout value for emergency callback mode.
-const EMERGENCY_CB_MODE_TIMEOUT_MS = 300000; // 5 mins = 300000 ms.
-
-const ICC_MAX_LINEAR_FIXED_RECORDS = 0xfe;
-
-const GET_CURRENT_CALLS_RETRY_MAX = 3;
-
-var RILQUIRKS_CALLSTATE_EXTRA_UINT32;
-var RILQUIRKS_REQUEST_USE_DIAL_EMERGENCY_CALL;
-var RILQUIRKS_SIM_APP_STATE_EXTRA_FIELDS;
-var RILQUIRKS_SIGNAL_EXTRA_INT32;
-var RILQUIRKS_AVAILABLE_NETWORKS_EXTRA_STRING;
-// Needed for call-waiting on Peak device
-var RILQUIRKS_EXTRA_UINT32_2ND_CALL;
-// On the emulator we support querying the number of lock retries
-var RILQUIRKS_HAVE_QUERY_ICC_LOCK_RETRY_COUNT;
-// Ril quirk to Send STK Profile Download
-var RILQUIRKS_SEND_STK_PROFILE_DOWNLOAD;
-// Ril quirk to attach data registration on demand.
-var RILQUIRKS_DATA_REGISTRATION_ON_DEMAND;
-// Ril quirk to control the uicc/data subscription.
-var RILQUIRKS_SUBSCRIPTION_CONTROL;
-// Ril quirk to describe the SMSC address format.
-var RILQUIRKS_SMSC_ADDRESS_FORMAT;
-
-/**
- * The RIL state machine.
- *
- * This object communicates with rild via parcels and with the main thread
- * via post messages. It maintains state about the radio, ICC, calls, etc.
- * and acts upon state changes accordingly.
- */
-function RilObject(aContext) {
- this.context = aContext;
-
- this.telephonyRequestQueue = new TelephonyRequestQueue(this);
- this.currentConferenceState = CALL_STATE_UNKNOWN;
- this._pendingSentSmsMap = {};
- this.pendingNetworkType = {};
- this._receivedSmsCbPagesMap = {};
- this._getCurrentCallsRetryCount = 0;
-}
-RilObject.prototype = {
- context: null,
-
- /**
- * RIL version.
- */
- version: null,
-
- /**
- * Call state of current conference group.
- */
- currentConferenceState: null,
-
- /**
- * Outgoing messages waiting for SMS-STATUS-REPORT.
- */
- _pendingSentSmsMap: null,
-
- /**
- * Marker object.
- */
- pendingNetworkType: null,
-
- /**
- * Global Cell Broadcast switch.
- */
- cellBroadcastDisabled: false,
-
- /**
- * Parsed Cell Broadcast search lists.
- * cellBroadcastConfigs.MMI should be preserved over rild reset.
- */
- cellBroadcastConfigs: null,
- mergedCellBroadcastConfig: null,
-
- _receivedSmsCbPagesMap: null,
-
- initRILState: function() {
- /**
- * One of the RADIO_STATE_* constants.
- */
- this.radioState = GECKO_RADIOSTATE_UNKNOWN;
-
- /**
- * True if we are on a CDMA phone.
- */
- this._isCdma = false;
-
- /**
- * True if we are in emergency callback mode.
- */
- this._isInEmergencyCbMode = false;
-
- /**
- * Set when radio is ready but radio tech is unknown. That is, we are
- * waiting for REQUEST_VOICE_RADIO_TECH
- */
- this._waitingRadioTech = false;
-
- /**
- * Card state
- */
- this.cardState = GECKO_CARDSTATE_UNINITIALIZED;
-
- /**
- * Device Identities including IMEI, IMEISV, ESN and MEID.
- */
- this.deviceIdentities = null;
-
- /**
- * ICC information that is not exposed to Gaia.
- */
- this.iccInfoPrivate = {};
-
- /**
- * ICC information, such as MSISDN, MCC, MNC, SPN...etc.
- */
- this.iccInfo = {};
-
- /**
- * CDMA specific information. ex. CDMA Network ID, CDMA System ID... etc.
- */
- this.cdmaHome = null;
-
- /**
- * Application identification for apps in ICC.
- */
- this.aid = null;
-
- /**
- * Application type for apps in ICC.
- */
- this.appType = null;
-
- this.networkSelectionMode = GECKO_NETWORK_SELECTION_UNKNOWN;
-
- this.voiceRegistrationState = {};
- this.dataRegistrationState = {};
-
- /**
- * List of strings identifying the network operator.
- */
- this.operator = null;
-
- /**
- * String containing the baseband version.
- */
- this.basebandVersion = null;
-
- // Clean up currentCalls: rild might have restarted.
- this.sendChromeMessage({
- rilMessageType: "currentCalls",
- calls: {}
- });
-
- // Don't clean up this._pendingSentSmsMap
- // because on rild restart: we may continue with the pending segments.
-
- /**
- * Whether or not the multiple requests in requestNetworkInfo() are currently
- * being processed
- */
- this._processingNetworkInfo = false;
-
- /**
- * Multiple requestNetworkInfo() in a row before finishing the first
- * request, hence we need to fire requestNetworkInfo() again after
- * gathering all necessary stuffs. This is to make sure that ril_worker
- * gets precise network information.
- */
- this._needRepollNetworkInfo = false;
-
- /**
- * Pending messages to be send in batch from requestNetworkInfo()
- */
- this._pendingNetworkInfo = {rilMessageType: "networkinfochanged"};
-
- /**
- * Cell Broadcast Search Lists.
- */
- let cbmmi = this.cellBroadcastConfigs && this.cellBroadcastConfigs.MMI;
- this.cellBroadcastConfigs = {
- MMI: cbmmi || null
- };
- this.mergedCellBroadcastConfig = null;
-
- /**
- * True when the request to report SMS Memory Status is pending.
- */
- this.pendingToReportSmsMemoryStatus = false;
- this.smsStorageAvailable = true;
- },
-
- /**
- * Parse an integer from a string, falling back to a default value
- * if the the provided value is not a string or does not contain a valid
- * number.
- *
- * @param string
- * String to be parsed.
- * @param defaultValue [optional]
- * Default value to be used.
- * @param radix [optional]
- * A number that represents the numeral system to be used. Default 10.
- */
- parseInt: function(string, defaultValue, radix) {
- let number = parseInt(string, radix || 10);
- if (!isNaN(number)) {
- return number;
- }
- if (defaultValue === undefined) {
- defaultValue = null;
- }
- return defaultValue;
- },
-
-
- /**
- * Outgoing requests to the RIL. These can be triggered from the
- * main thread via messages that look like this:
- *
- * {rilMessageType: "methodName",
- * extra: "parameters",
- * go: "here"}
- *
- * So if one of the following methods takes arguments, it takes only one,
- * an object, which then contains all of the parameters as attributes.
- * The "@param" documentation is to be interpreted accordingly.
- */
-
- /**
- * Retrieve the ICC's status.
- */
- getICCStatus: function() {
- this.context.Buf.simpleRequest(REQUEST_GET_SIM_STATUS);
- },
-
- /**
- * Helper function for unlocking ICC locks.
- */
- iccUnlockCardLock: function(options) {
- switch (options.lockType) {
- case GECKO_CARDLOCK_PIN:
- this.enterICCPIN(options);
- break;
- case GECKO_CARDLOCK_PIN2:
- this.enterICCPIN2(options);
- break;
- case GECKO_CARDLOCK_PUK:
- this.enterICCPUK(options);
- break;
- case GECKO_CARDLOCK_PUK2:
- this.enterICCPUK2(options);
- break;
- case GECKO_CARDLOCK_NCK:
- case GECKO_CARDLOCK_NSCK:
- case GECKO_CARDLOCK_NCK1:
- case GECKO_CARDLOCK_NCK2:
- case GECKO_CARDLOCK_HNCK:
- case GECKO_CARDLOCK_CCK:
- case GECKO_CARDLOCK_SPCK:
- case GECKO_CARDLOCK_PCK:
- case GECKO_CARDLOCK_RCCK:
- case GECKO_CARDLOCK_RSPCK:
- case GECKO_CARDLOCK_NCK_PUK:
- case GECKO_CARDLOCK_NSCK_PUK:
- case GECKO_CARDLOCK_NCK1_PUK:
- case GECKO_CARDLOCK_NCK2_PUK:
- case GECKO_CARDLOCK_HNCK_PUK:
- case GECKO_CARDLOCK_CCK_PUK:
- case GECKO_CARDLOCK_SPCK_PUK:
- case GECKO_CARDLOCK_PCK_PUK:
- case GECKO_CARDLOCK_RCCK_PUK: // Fall through.
- case GECKO_CARDLOCK_RSPCK_PUK:
- this.enterDepersonalization(options);
- break;
- default:
- options.errorMsg = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
- this.sendChromeMessage(options);
- }
- },
-
- /**
- * Enter a PIN to unlock the ICC.
- *
- * @param password
- * String containing the PIN.
- * @param [optional] aid
- * AID value.
- */
- enterICCPIN: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_ENTER_SIM_PIN, options);
- Buf.writeInt32(2);
- Buf.writeString(options.password);
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Enter a PIN2 to unlock the ICC.
- *
- * @param password
- * String containing the PIN2.
- * @param [optional] aid
- * AID value.
- */
- enterICCPIN2: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_ENTER_SIM_PIN2, options);
- Buf.writeInt32(2);
- Buf.writeString(options.password);
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Requests a network personalization be deactivated.
- *
- * @param personlization
- * One of CARD_PERSOSUBSTATE_*
- * @param password
- * String containing the password.
- */
- enterDepersonalization: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_ENTER_NETWORK_DEPERSONALIZATION_CODE, options);
- Buf.writeInt32(1);
- Buf.writeString(options.password);
- Buf.sendParcel();
- },
-
- /**
- * Change the current ICC PIN number.
- *
- * @param password
- * String containing the old PIN value
- * @param newPassword
- * String containing the new PIN value
- * @param [optional] aid
- * AID value.
- */
- changeICCPIN: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_CHANGE_SIM_PIN, options);
- Buf.writeInt32(3);
- Buf.writeString(options.password);
- Buf.writeString(options.newPassword);
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Change the current ICC PIN2 number.
- *
- * @param password
- * String containing the old PIN2 value
- * @param newPassword
- * String containing the new PIN2 value
- * @param [optional] aid
- * AID value.
- */
- changeICCPIN2: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_CHANGE_SIM_PIN2, options);
- Buf.writeInt32(3);
- Buf.writeString(options.password);
- Buf.writeString(options.newPassword);
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Supplies ICC PUK and a new PIN to unlock the ICC.
- *
- * @param password
- * String containing the PUK value.
- * @param newPassword
- * String containing the new PIN value.
- * @param [optional] aid
- * AID value.
- */
- enterICCPUK: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_ENTER_SIM_PUK, options);
- Buf.writeInt32(3);
- Buf.writeString(options.password);
- Buf.writeString(options.newPin);
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Supplies ICC PUK2 and a new PIN2 to unlock the ICC.
- *
- * @param password
- * String containing the PUK2 value.
- * @param newPassword
- * String containing the new PIN2 value.
- * @param [optional] aid
- * AID value.
- */
- enterICCPUK2: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_ENTER_SIM_PUK2, options);
- Buf.writeInt32(3);
- Buf.writeString(options.password);
- Buf.writeString(options.newPin);
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Helper function for changing ICC locks.
- */
- iccChangeCardLockPassword: function(options) {
- switch (options.lockType) {
- case GECKO_CARDLOCK_PIN:
- this.changeICCPIN(options);
- break;
- case GECKO_CARDLOCK_PIN2:
- this.changeICCPIN2(options);
- break;
- default:
- options.errorMsg = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
- this.sendChromeMessage(options);
- }
- },
-
- /**
- * Helper function for setting the state of ICC locks.
- */
- iccSetCardLockEnabled: function(options) {
- switch (options.lockType) {
- case GECKO_CARDLOCK_PIN: // Fall through.
- case GECKO_CARDLOCK_FDN:
- options.facility = GECKO_CARDLOCK_TO_FACILITY[options.lockType];
- break;
- default:
- options.errorMsg = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
- this.sendChromeMessage(options);
- return;
- }
-
- options.serviceClass = ICC_SERVICE_CLASS_VOICE |
- ICC_SERVICE_CLASS_DATA |
- ICC_SERVICE_CLASS_FAX;
- this.setICCFacilityLock(options);
- },
-
- /**
- * Helper function for fetching the state of ICC locks.
- */
- iccGetCardLockEnabled: function(options) {
- switch (options.lockType) {
- case GECKO_CARDLOCK_PIN: // Fall through.
- case GECKO_CARDLOCK_FDN:
- options.facility = GECKO_CARDLOCK_TO_FACILITY[options.lockType];
- break;
- default:
- options.errorMsg = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
- this.sendChromeMessage(options);
- return;
- }
-
- options.password = ""; // For query no need to provide pin.
- options.serviceClass = ICC_SERVICE_CLASS_VOICE |
- ICC_SERVICE_CLASS_DATA |
- ICC_SERVICE_CLASS_FAX;
- this.queryICCFacilityLock(options);
- },
-
- /**
- * Helper function for fetching the number of unlock retries of ICC locks.
- *
- * We only query the retry count when we're on the emulator. The phones do
- * not support the request id and their rild doesn't return an error.
- */
- iccGetCardLockRetryCount: function(options) {
- if (!RILQUIRKS_HAVE_QUERY_ICC_LOCK_RETRY_COUNT) {
- // Only the emulator supports this request.
- options.errorMsg = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
- this.sendChromeMessage(options);
- return;
- }
-
- switch (options.lockType) {
- case GECKO_CARDLOCK_PIN:
- case GECKO_CARDLOCK_PIN2:
- case GECKO_CARDLOCK_PUK:
- case GECKO_CARDLOCK_PUK2:
- case GECKO_CARDLOCK_NCK:
- case GECKO_CARDLOCK_NSCK:
- case GECKO_CARDLOCK_CCK: // Fall through.
- case GECKO_CARDLOCK_SPCK:
- // TODO: Bug 1116072: identify the mapping between RIL_PERSOSUBSTATE_SIM_SIM
- // @ ril.h and TS 27.007, clause 8.65 for GECKO_CARDLOCK_SPCK.
- options.selCode = GECKO_CARDLOCK_TO_SEL_CODE[options.lockType];
- break;
- default:
- options.errorMsg = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
- this.sendChromeMessage(options);
- return;
- }
-
- this.queryICCLockRetryCount(options);
- },
-
- /**
- * Query ICC lock retry count.
- *
- * @param selCode
- * One of ICC_SEL_CODE_*.
- * @param serviceClass
- * One of ICC_SERVICE_CLASS_*.
- */
- queryICCLockRetryCount: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_GET_UNLOCK_RETRY_COUNT, options);
- Buf.writeInt32(1);
- Buf.writeString(options.selCode);
- Buf.sendParcel();
- },
-
- /**
- * Query ICC facility lock.
- *
- * @param facility
- * One of ICC_CB_FACILITY_*.
- * @param password
- * Password for the facility, or "" if not required.
- * @param serviceClass
- * One of ICC_SERVICE_CLASS_*.
- * @param [optional] aid
- * AID value.
- */
- queryICCFacilityLock: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_QUERY_FACILITY_LOCK, options);
- Buf.writeInt32(4);
- Buf.writeString(options.facility);
- Buf.writeString(options.password);
- Buf.writeString(options.serviceClass.toString());
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Set ICC facility lock.
- *
- * @param facility
- * One of ICC_CB_FACILITY_*.
- * @param enabled
- * true to enable, false to disable.
- * @param password
- * Password for the facility, or "" if not required.
- * @param serviceClass
- * One of ICC_SERVICE_CLASS_*.
- * @param [optional] aid
- * AID value.
- */
- setICCFacilityLock: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_FACILITY_LOCK, options);
- Buf.writeInt32(5);
- Buf.writeString(options.facility);
- Buf.writeString(options.enabled ? "1" : "0");
- Buf.writeString(options.password);
- Buf.writeString(options.serviceClass.toString());
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Request an ICC I/O operation.
- *
- * See TS 27.007 "restricted SIM" operation, "AT Command +CRSM".
- * The sequence is in the same order as how libril reads this parcel,
- * see the struct RIL_SIM_IO_v5 or RIL_SIM_IO_v6 defined in ril.h
- *
- * @param command
- * The I/O command, one of the ICC_COMMAND_* constants.
- * @param fileId
- * The file to operate on, one of the ICC_EF_* constants.
- * @param pathId
- * String type, check the 'pathid' parameter from TS 27.007 +CRSM.
- * @param p1, p2, p3
- * Arbitrary integer parameters for the command.
- * @param [optional] dataWriter
- * The function for writing string parameter for the ICC_COMMAND_UPDATE_RECORD.
- * @param [optional] pin2
- * String containing the PIN2.
- * @param [optional] aid
- * AID value.
- */
- iccIO: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SIM_IO, options);
- Buf.writeInt32(options.command);
- Buf.writeInt32(options.fileId);
- Buf.writeString(options.pathId);
- Buf.writeInt32(options.p1);
- Buf.writeInt32(options.p2);
- Buf.writeInt32(options.p3);
-
- // Write data.
- if (options.command == ICC_COMMAND_UPDATE_RECORD &&
- options.dataWriter) {
- options.dataWriter(options.p3);
- } else {
- Buf.writeString(null);
- }
-
- // Write pin2.
- if (options.command == ICC_COMMAND_UPDATE_RECORD &&
- options.pin2) {
- Buf.writeString(options.pin2);
- } else {
- Buf.writeString(null);
- }
-
- Buf.writeString(options.aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Get IMSI.
- *
- * @param [optional] aid
- * AID value.
- */
- getIMSI: function(aid) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_GET_IMSI);
- Buf.writeInt32(1);
- Buf.writeString(aid || this.aid);
- Buf.sendParcel();
- },
-
- /**
- * Retrieve ICC's GID1 field.
- */
- getGID1: function(options) {
- options.gid1 = this.iccInfoPrivate.gid1;
- this.sendChromeMessage(options);
- },
-
- /**
- * Read UICC Phonebook contacts.
- *
- * @param contactType
- * One of GECKO_CARDCONTACT_TYPE_*.
- * @param requestId
- * Request id from RadioInterfaceLayer.
- */
- readICCContacts: function(options) {
- if (!this.appType) {
- options.errorMsg = CONTACT_ERR_REQUEST_NOT_SUPPORTED;
- this.sendChromeMessage(options);
- return;
- }
-
- this.context.ICCContactHelper.readICCContacts(
- this.appType,
- options.contactType,
- function onsuccess(contacts) {
- for (let i = 0; i < contacts.length; i++) {
- let contact = contacts[i];
- let pbrIndex = contact.pbrIndex || 0;
- let recordIndex = pbrIndex * ICC_MAX_LINEAR_FIXED_RECORDS + contact.recordId;
- contact.contactId = this.iccInfo.iccid + recordIndex;
- }
- // Reuse 'options' to get 'requestId' and 'contactType'.
- options.contacts = contacts;
- this.sendChromeMessage(options);
- }.bind(this),
- function onerror(errorMsg) {
- options.errorMsg = errorMsg;
- this.sendChromeMessage(options);
- }.bind(this));
- },
-
- /**
- * Update UICC Phonebook.
- *
- * @param contactType One of GECKO_CARDCONTACT_TYPE_*.
- * @param contact The contact will be updated.
- * @param pin2 PIN2 is required for updating FDN.
- * @param requestId Request id from RadioInterfaceLayer.
- */
- updateICCContact: function(options) {
- let onsuccess = function onsuccess(updatedContact) {
- let recordIndex =
- updatedContact.pbrIndex * ICC_MAX_LINEAR_FIXED_RECORDS + updatedContact.recordId;
- updatedContact.contactId = this.iccInfo.iccid + recordIndex;
- options.contact = updatedContact;
- // Reuse 'options' to get 'requestId' and 'contactType'.
- this.sendChromeMessage(options);
- }.bind(this);
-
- let onerror = function onerror(errorMsg) {
- options.errorMsg = errorMsg;
- this.sendChromeMessage(options);
- }.bind(this);
-
- if (!this.appType || !options.contact) {
- onerror(CONTACT_ERR_REQUEST_NOT_SUPPORTED );
- return;
- }
-
- let contact = options.contact;
- let iccid = this.iccInfo.iccid;
- let isValidRecordId = false;
- if (typeof contact.contactId === "string" &&
- contact.contactId.startsWith(iccid)) {
- let recordIndex = contact.contactId.substring(iccid.length);
- contact.pbrIndex = Math.floor(recordIndex / ICC_MAX_LINEAR_FIXED_RECORDS);
- contact.recordId = recordIndex % ICC_MAX_LINEAR_FIXED_RECORDS;
- isValidRecordId = contact.recordId > 0 && contact.recordId < 0xff;
- }
-
- if (DEBUG) {
- this.context.debug("Update ICC Contact " + JSON.stringify(contact));
- }
-
- let ICCContactHelper = this.context.ICCContactHelper;
- // If contact has 'recordId' property, updates corresponding record.
- // If not, inserts the contact into a free record.
- if (isValidRecordId) {
- ICCContactHelper.updateICCContact(
- this.appType, options.contactType, contact, options.pin2, onsuccess, onerror);
- } else {
- ICCContactHelper.addICCContact(
- this.appType, options.contactType, contact, options.pin2, onsuccess, onerror);
- }
- },
-
- /**
- * Check if operator name needs to be overriden by current voiceRegistrationState
- * , EFOPL and EFPNN. See 3GPP TS 31.102 clause 4.2.58 EFPNN and 4.2.59 EFOPL
- * for detail.
- *
- * @return true if operator name is overridden, false otherwise.
- */
- overrideICCNetworkName: function() {
- if (!this.operator) {
- return false;
- }
-
- // We won't get network name using PNN and OPL if voice registration isn't
- // ready.
- if (!this.voiceRegistrationState.cell ||
- this.voiceRegistrationState.cell.gsmLocationAreaCode == -1) {
- return false;
- }
-
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- let networkName = ICCUtilsHelper.getNetworkNameFromICC(
- this.operator.mcc,
- this.operator.mnc,
- this.voiceRegistrationState.cell.gsmLocationAreaCode);
-
- if (!networkName) {
- return false;
- }
-
- if (DEBUG) {
- this.context.debug("Operator names will be overriden: " +
- "longName = " + networkName.fullName + ", " +
- "shortName = " + networkName.shortName);
- }
-
- this.operator.longName = networkName.fullName;
- this.operator.shortName = networkName.shortName;
-
- this._sendNetworkInfoMessage(NETWORK_INFO_OPERATOR, this.operator);
- return true;
- },
-
- /**
- * Request the phone's radio to be enabled or disabled.
- *
- * @param enabled
- * Boolean indicating the desired state.
- */
- setRadioEnabled: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_RADIO_POWER, options);
- Buf.writeInt32(1);
- Buf.writeInt32(options.enabled ? 1 : 0);
- Buf.sendParcel();
- },
-
- /**
- * Query call waiting status.
- *
- */
- queryCallWaiting: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_QUERY_CALL_WAITING, options);
- Buf.writeInt32(1);
- // As per 3GPP TS 24.083, section 1.6 UE doesn't need to send service
- // class parameter in call waiting interrogation to network.
- Buf.writeInt32(ICC_SERVICE_CLASS_NONE);
- Buf.sendParcel();
- },
-
- /**
- * Set call waiting status.
- *
- * @param enabled
- * Boolean indicating the desired waiting status.
- * @param serviceClass
- * One of ICC_SERVICE_CLASS_* constants.
- */
- setCallWaiting: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_CALL_WAITING, options);
- Buf.writeInt32(2);
- Buf.writeInt32(options.enabled ? 1 : 0);
- Buf.writeInt32(options.serviceClass);
- Buf.sendParcel();
- },
-
- /**
- * Queries current CLIP status.
- */
- queryCLIP: function(options) {
- this.context.Buf.simpleRequest(REQUEST_QUERY_CLIP, options);
- },
-
- /**
- * Queries current CLIR status.
- *
- */
- getCLIR: function(options) {
- this.context.Buf.simpleRequest(REQUEST_GET_CLIR, options);
- },
-
- /**
- * Enables or disables the presentation of the calling line identity (CLI) to
- * the called party when originating a call.
- *
- * @param options.clirMode
- * One of the CLIR_* constants.
- */
- setCLIR: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_CLIR, options);
- Buf.writeInt32(1);
- Buf.writeInt32(options.clirMode);
- Buf.sendParcel();
- },
-
- /**
- * Set screen state.
- *
- * @param on
- * Boolean indicating whether the screen should be on or off.
- */
- setScreenState: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SCREEN_STATE);
- Buf.writeInt32(1);
- Buf.writeInt32(options.on ? 1 : 0);
- Buf.sendParcel();
- },
-
- getVoiceRegistrationState: function() {
- this.context.Buf.simpleRequest(REQUEST_VOICE_REGISTRATION_STATE);
- },
-
- getVoiceRadioTechnology: function() {
- this.context.Buf.simpleRequest(REQUEST_VOICE_RADIO_TECH);
- },
-
- getDataRegistrationState: function() {
- this.context.Buf.simpleRequest(REQUEST_DATA_REGISTRATION_STATE);
- },
-
- getOperator: function() {
- this.context.Buf.simpleRequest(REQUEST_OPERATOR);
- },
-
- /**
- * Set the preferred network type.
- *
- * @param options An object contains a valid value of
- * RIL_PREFERRED_NETWORK_TYPE_TO_GECKO as its `type` attribute.
- */
- setPreferredNetworkType: function(options) {
- let networkType = options.type;
- if (networkType < 0 || networkType >= RIL_PREFERRED_NETWORK_TYPE_TO_GECKO.length) {
- options.errorMsg = GECKO_ERROR_INVALID_PARAMETER;
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_PREFERRED_NETWORK_TYPE, options);
- Buf.writeInt32(1);
- Buf.writeInt32(networkType);
- Buf.sendParcel();
- },
-
- /**
- * Get the preferred network type.
- */
- getPreferredNetworkType: function(options) {
- this.context.Buf.simpleRequest(REQUEST_GET_PREFERRED_NETWORK_TYPE, options);
- },
-
- /**
- * Request neighboring cell ids in GSM network.
- */
- getNeighboringCellIds: function(options) {
- this.context.Buf.simpleRequest(REQUEST_GET_NEIGHBORING_CELL_IDS, options);
- },
-
- /**
- * Request all of the current cell information known to the radio.
- */
- getCellInfoList: function(options) {
- this.context.Buf.simpleRequest(REQUEST_GET_CELL_INFO_LIST, options);
- },
-
- /**
- * Request various states about the network.
- */
- requestNetworkInfo: function() {
- if (this._processingNetworkInfo) {
- if (DEBUG) {
- this.context.debug("Network info requested, but we're already " +
- "requesting network info.");
- }
- this._needRepollNetworkInfo = true;
- return;
- }
-
- if (DEBUG) this.context.debug("Requesting network info");
-
- this._processingNetworkInfo = true;
- this.getVoiceRegistrationState();
- this.getDataRegistrationState(); //TODO only GSM
- this.getOperator();
- this.getNetworkSelectionMode();
- this.getSignalStrength();
- },
-
- /**
- * Get the available networks
- */
- getAvailableNetworks: function(options) {
- if (DEBUG) this.context.debug("Getting available networks");
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_QUERY_AVAILABLE_NETWORKS, options);
- Buf.sendParcel();
- },
-
- /**
- * Request the radio's network selection mode
- */
- getNetworkSelectionMode: function() {
- if (DEBUG) this.context.debug("Getting network selection mode");
- this.context.Buf.simpleRequest(REQUEST_QUERY_NETWORK_SELECTION_MODE);
- },
-
- /**
- * Tell the radio to automatically choose a voice/data network
- */
- selectNetworkAuto: function(options) {
- if (DEBUG) this.context.debug("Setting automatic network selection");
- this.context.Buf.simpleRequest(REQUEST_SET_NETWORK_SELECTION_AUTOMATIC, options);
- },
-
- /**
- * Set the roaming preference mode
- */
- setRoamingPreference: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_CDMA_SET_ROAMING_PREFERENCE, options);
- Buf.writeInt32(1);
- Buf.writeInt32(options.mode);
- Buf.sendParcel();
- },
-
- /**
- * Get the roaming preference mode
- */
- queryRoamingPreference: function(options) {
- this.context.Buf.simpleRequest(REQUEST_CDMA_QUERY_ROAMING_PREFERENCE, options);
- },
-
- /**
- * Set the voice privacy mode
- */
- setVoicePrivacyMode: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE, options);
- Buf.writeInt32(1);
- Buf.writeInt32(options.enabled ? 1 : 0);
- Buf.sendParcel();
- },
-
- /**
- * Get the voice privacy mode
- */
- queryVoicePrivacyMode: function(options) {
- this.context.Buf.simpleRequest(REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE, options);
- },
-
- /**
- * Open Logical UICC channel (aid) for Secure Element access
- */
- iccOpenChannel: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SIM_OPEN_CHANNEL, options);
- Buf.writeString(options.aid);
- Buf.sendParcel();
- },
-
- /**
- * Exchange APDU data on an open Logical UICC channel
- */
- iccExchangeAPDU: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SIM_TRANSMIT_APDU_CHANNEL, options);
- Buf.writeInt32(options.channel);
- Buf.writeInt32(options.apdu.cla);
- Buf.writeInt32(options.apdu.command);
- Buf.writeInt32(options.apdu.p1);
- Buf.writeInt32(options.apdu.p2);
- Buf.writeInt32(options.apdu.p3);
- Buf.writeString(options.apdu.data);
- Buf.sendParcel();
- },
-
- /**
- * Close Logical UICC channel
- */
- iccCloseChannel: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SIM_CLOSE_CHANNEL, options);
- Buf.writeInt32(1);
- Buf.writeInt32(options.channel);
- Buf.sendParcel();
- },
-
- /**
- * Get UICC service state
- */
- getIccServiceState: function(options) {
- switch (options.service) {
- case GECKO_CARDSERVICE_FDN:
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- options.result = ICCUtilsHelper.isICCServiceAvailable("FDN");
- break;
- default:
- options.errorMsg = GECKO_ERROR_REQUEST_NOT_SUPPORTED;
- break;
- }
- this.sendChromeMessage(options);
- },
-
- /**
- * Enable/Disable UICC subscription
- */
- setUiccSubscription: function(options) {
- if (DEBUG) {
- this.context.debug("setUiccSubscription: " + JSON.stringify(options));
- }
-
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_UICC_SUBSCRIPTION, options);
- Buf.writeInt32(this.context.clientId);
- Buf.writeInt32(options.appIndex);
- Buf.writeInt32(this.context.clientId);
- Buf.writeInt32(options.enabled ? 1 : 0);
- Buf.sendParcel();
- },
-
- /**
- * Tell the radio to choose a specific voice/data network
- */
- selectNetwork: function(options) {
- if (DEBUG) {
- this.context.debug("Setting manual network selection: " +
- options.mcc + ", " + options.mnc);
- }
-
- let numeric = (options.mcc && options.mnc) ? options.mcc + options.mnc : null;
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_NETWORK_SELECTION_MANUAL, options);
- Buf.writeString(numeric);
- Buf.sendParcel();
- },
-
- /**
- * Get the signal strength.
- */
- getSignalStrength: function() {
- this.context.Buf.simpleRequest(REQUEST_SIGNAL_STRENGTH);
- },
-
- getDeviceIdentity: function() {
- this.deviceIdentities || this.context.Buf.simpleRequest(REQUEST_DEVICE_IDENTITY);
- },
-
- getBasebandVersion: function() {
- this.context.Buf.simpleRequest(REQUEST_BASEBAND_VERSION);
- },
-
- sendExitEmergencyCbModeRequest: function(options) {
- this.context.Buf.simpleRequest(REQUEST_EXIT_EMERGENCY_CALLBACK_MODE, options);
- },
-
- getCdmaSubscription: function() {
- this.context.Buf.simpleRequest(REQUEST_CDMA_SUBSCRIPTION);
- },
-
- exitEmergencyCbMode: function(options) {
- // The function could be called by an API from RadioInterfaceLayer or by
- // ril_worker itself. From ril_worker, we won't pass the parameter
- // 'options'. In this case, it is marked as internal.
- if (!options) {
- options = {internal: true};
- }
- this._cancelEmergencyCbModeTimeout();
- this.sendExitEmergencyCbModeRequest(options);
- },
-
- /**
- * Dial a non-emergency number.
- *
- * @param isEmergency
- * Whether the number is an emergency number.
- * @param number
- * String containing the number to dial.
- * @param clirMode
- * Integer for showing/hidding the caller Id to the called party.
- * @param uusInfo
- * Integer doing something XXX TODO
- */
- dial: function(options) {
- if (options.isEmergency) {
- options.request = RILQUIRKS_REQUEST_USE_DIAL_EMERGENCY_CALL ?
- REQUEST_DIAL_EMERGENCY_CALL : REQUEST_DIAL;
-
- } else {
- options.request = REQUEST_DIAL;
-
- // Exit emergency callback mode when user dial a non-emergency call.
- if (this._isInEmergencyCbMode) {
- this.exitEmergencyCbMode();
- }
- }
-
- this.telephonyRequestQueue.push(options.request, () => {
- let Buf = this.context.Buf;
- Buf.newParcel(options.request, options);
- Buf.writeString(options.number);
- Buf.writeInt32(options.clirMode || 0);
- Buf.writeInt32(options.uusInfo || 0);
- // TODO Why do we need this extra 0? It was put it in to make this
- // match the format of the binary message.
- Buf.writeInt32(0);
- Buf.sendParcel();
- });
- },
-
- /**
- * CDMA flash.
- *
- * @param featureStr (optional)
- * Dialing number when the command is used for three-way-calling
- */
- cdmaFlash: function(options) {
- let Buf = this.context.Buf;
- options.request = REQUEST_CDMA_FLASH;
- Buf.newParcel(options.request, options);
- Buf.writeString(options.featureStr || "");
- Buf.sendParcel();
- },
-
- /**
- * Hang up the phone.
- *
- * @param callIndex
- * Call index (1-based) as reported by REQUEST_GET_CURRENT_CALLS.
- */
- hangUpCall: function(options) {
- this.telephonyRequestQueue.push(REQUEST_HANGUP, () => {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_HANGUP, options);
- Buf.writeInt32(1);
- Buf.writeInt32(options.callIndex);
- Buf.sendParcel();
- });
- },
-
- hangUpForeground: function(options) {
- this.telephonyRequestQueue.push(REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND, () => {
- this.context.Buf.simpleRequest(REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND,
- options);
- });
- },
-
- hangUpBackground: function(options) {
- this.telephonyRequestQueue.push(REQUEST_HANGUP_WAITING_OR_BACKGROUND, () => {
- this.context.Buf.simpleRequest(REQUEST_HANGUP_WAITING_OR_BACKGROUND,
- options);
- });
- },
-
- switchActiveCall: function(options) {
- this.telephonyRequestQueue.push(REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE, () => {
- this.context.Buf.simpleRequest(REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE,
- options);
- });
- },
-
- udub: function(options) {
- this.telephonyRequestQueue.push(REQUEST_UDUB, () => {
- this.context.Buf.simpleRequest(REQUEST_UDUB, options);
- });
- },
-
- answerCall: function(options) {
- this.telephonyRequestQueue.push(REQUEST_ANSWER, () => {
- this.context.Buf.simpleRequest(REQUEST_ANSWER, options);
- });
- },
-
- conferenceCall: function(options) {
- this.telephonyRequestQueue.push(REQUEST_CONFERENCE, () => {
- this.context.Buf.simpleRequest(REQUEST_CONFERENCE, options);
- });
- },
-
- separateCall: function(options) {
- this.telephonyRequestQueue.push(REQUEST_SEPARATE_CONNECTION, () => {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SEPARATE_CONNECTION, options);
- Buf.writeInt32(1);
- Buf.writeInt32(options.callIndex);
- Buf.sendParcel();
- });
- },
-
- /**
- * Get current calls.
- */
- getCurrentCalls: function(options) {
- this.telephonyRequestQueue.push(REQUEST_GET_CURRENT_CALLS, () => {
- this.context.Buf.simpleRequest(REQUEST_GET_CURRENT_CALLS, options);
- });
- },
-
- /**
- * Mute or unmute the radio.
- *
- * @param mute
- * Boolean to indicate whether to mute or unmute the radio.
- */
- setMute: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_MUTE);
- Buf.writeInt32(1);
- Buf.writeInt32(options.muted ? 1 : 0);
- Buf.sendParcel();
- },
-
- /**
- * Send an SMS.
- *
- * The `options` parameter object should contain the following attributes:
- *
- * @param number
- * String containing the recipient number.
- * @param body
- * String containing the message text.
- * @param envelopeId
- * Numeric value identifying the sms request.
- */
- sendSMS: function(options) {
- options.langIndex = options.langIndex || PDU_NL_IDENTIFIER_DEFAULT;
- options.langShiftIndex = options.langShiftIndex || PDU_NL_IDENTIFIER_DEFAULT;
-
- if (!options.segmentSeq) {
- // Fist segment to send
- options.segmentSeq = 1;
- options.body = options.segments[0].body;
- options.encodedBodyLength = options.segments[0].encodedBodyLength;
- }
-
- let Buf = this.context.Buf;
- if (this._isCdma) {
- Buf.newParcel(REQUEST_CDMA_SEND_SMS, options);
- this.context.CdmaPDUHelper.writeMessage(options);
- } else {
- Buf.newParcel(REQUEST_SEND_SMS, options);
- Buf.writeInt32(2);
- Buf.writeString(options.SMSC);
- this.context.GsmPDUHelper.writeMessage(options);
- }
- Buf.sendParcel();
- },
-
- /**
- * Acknowledge the receipt and handling of an SMS.
- *
- * @param success
- * Boolean indicating whether the message was successfuly handled.
- * @param cause
- * SMS_* constant indicating the reason for unsuccessful handling.
- */
- acknowledgeGsmSms: function(success, cause) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SMS_ACKNOWLEDGE);
- Buf.writeInt32(2);
- Buf.writeInt32(success ? 1 : 0);
- Buf.writeInt32(cause);
- Buf.sendParcel();
- },
-
- /**
- * Acknowledge the receipt and handling of an SMS.
- *
- * @param success
- * Boolean indicating whether the message was successfuly handled.
- */
- ackSMS: function(options) {
- if (options.result == PDU_FCS_RESERVED) {
- return;
- }
- if (this._isCdma) {
- this.acknowledgeCdmaSms(options.result == PDU_FCS_OK, options.result);
- } else {
- this.acknowledgeGsmSms(options.result == PDU_FCS_OK, options.result);
- }
- },
-
- /**
- * Acknowledge the receipt and handling of a CDMA SMS.
- *
- * @param success
- * Boolean indicating whether the message was successfuly handled.
- * @param cause
- * SMS_* constant indicating the reason for unsuccessful handling.
- */
- acknowledgeCdmaSms: function(success, cause) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_CDMA_SMS_ACKNOWLEDGE);
- Buf.writeInt32(success ? 0 : 1);
- Buf.writeInt32(cause);
- Buf.sendParcel();
- },
-
- /**
- * Update received MWI into EF_MWIS.
- */
- updateMwis: function(options) {
- if (this.context.ICCUtilsHelper.isICCServiceAvailable("MWIS")) {
- this.context.SimRecordHelper.updateMWIS(options.mwi);
- }
- },
-
- /**
- * Report SMS storage status to modem.
- */
- _updateSmsMemoryStatus: function() {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_REPORT_SMS_MEMORY_STATUS);
- Buf.writeInt32(1);
- Buf.writeInt32(this.smsStorageAvailable ? 1 : 0);
- Buf.sendParcel();
- },
-
- reportSmsMemoryStatus: function(options) {
- this.pendingToReportSmsMemoryStatus = true;
- this.smsStorageAvailable = options.isAvailable;
- this._updateSmsMemoryStatus();
- },
-
- setCellBroadcastDisabled: function(options) {
- this.cellBroadcastDisabled = options.disabled;
-
- // If |this.mergedCellBroadcastConfig| is null, either we haven't finished
- // reading required SIM files, or no any channel is ever configured. In
- // the former case, we'll call |this.updateCellBroadcastConfig()| later
- // with correct configs; in the latter case, we don't bother resetting CB
- // to disabled again.
- if (this.mergedCellBroadcastConfig) {
- this.updateCellBroadcastConfig();
- }
- },
-
- setCellBroadcastSearchList: function(options) {
- let getSearchListStr = function(aSearchList) {
- if (typeof aSearchList === "string" || aSearchList instanceof String) {
- return aSearchList;
- }
-
- // TODO: Set search list for CDMA/GSM individually. Bug 990926
- let prop = this._isCdma ? "cdma" : "gsm";
-
- return aSearchList && aSearchList[prop];
- }.bind(this);
-
- try {
- let str = getSearchListStr(options.searchList);
- this.cellBroadcastConfigs.MMI = this._convertCellBroadcastSearchList(str);
- } catch (e) {
- if (DEBUG) {
- this.context.debug("Invalid Cell Broadcast search list: " + e);
- }
- options.errorMsg = GECKO_ERROR_UNSPECIFIED_ERROR;
- }
-
- this.sendChromeMessage(options);
- if (options.errorMsg) {
- return;
- }
-
- this._mergeAllCellBroadcastConfigs();
- },
-
- updateCellBroadcastConfig: function() {
- let activate = !this.cellBroadcastDisabled &&
- (this.mergedCellBroadcastConfig != null) &&
- (this.mergedCellBroadcastConfig.length > 0);
- if (activate) {
- this.setSmsBroadcastConfig(this.mergedCellBroadcastConfig);
- } else {
- // It's unnecessary to set config first if we're deactivating.
- this.setSmsBroadcastActivation(false);
- }
- },
-
- setGsmSmsBroadcastConfig: function(config) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_GSM_SET_BROADCAST_SMS_CONFIG);
-
- let numConfigs = config ? config.length / 2 : 0;
- Buf.writeInt32(numConfigs);
- for (let i = 0; i < config.length;) {
- // convert [from, to) to [from, to - 1]
- Buf.writeInt32(config[i++]);
- Buf.writeInt32(config[i++] - 1);
- Buf.writeInt32(0x00);
- Buf.writeInt32(0xFF);
- Buf.writeInt32(1);
- }
-
- Buf.sendParcel();
- },
-
- /**
- * Send CDMA SMS broadcast config.
- *
- * @see 3GPP2 C.R1001 Sec. 9.2 and 9.3
- */
- setCdmaSmsBroadcastConfig: function(config) {
- let Buf = this.context.Buf;
- // |config| is an array of half-closed range: [[from, to), [from, to), ...].
- // It will be further decomposed, ex: [1, 4) => 1, 2, 3.
- Buf.newParcel(REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG);
-
- let numConfigs = 0;
- for (let i = 0; i < config.length; i += 2) {
- numConfigs += (config[i+1] - config[i]);
- }
-
- Buf.writeInt32(numConfigs);
- for (let i = 0; i < config.length;) {
- let begin = config[i++];
- let end = config[i++];
-
- for (let j = begin; j < end; ++j) {
- Buf.writeInt32(j);
- Buf.writeInt32(0); // Language Indicator: Unknown or unspecified.
- Buf.writeInt32(1);
- }
- }
-
- Buf.sendParcel();
- },
-
- setSmsBroadcastConfig: function(config) {
- if (this._isCdma) {
- this.setCdmaSmsBroadcastConfig(config);
- } else {
- this.setGsmSmsBroadcastConfig(config);
- }
- },
-
- setSmsBroadcastActivation: function(activate) {
- let parcelType = this._isCdma ? REQUEST_CDMA_SMS_BROADCAST_ACTIVATION :
- REQUEST_GSM_SMS_BROADCAST_ACTIVATION;
- let Buf = this.context.Buf;
- Buf.newParcel(parcelType);
- Buf.writeInt32(1);
- // See hardware/ril/include/telephony/ril.h, 0 - Activate, 1 - Turn off.
- Buf.writeInt32(activate ? 0 : 1);
- Buf.sendParcel();
- },
-
- /**
- * Start a DTMF Tone.
- *
- * @param dtmfChar
- * DTMF signal to send, 0-9, *, +
- */
- startTone: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_DTMF_START, options);
- Buf.writeString(options.dtmfChar);
- Buf.sendParcel();
- },
-
- stopTone: function() {
- this.context.Buf.simpleRequest(REQUEST_DTMF_STOP);
- },
-
- /**
- * Send a DTMF tone.
- *
- * @param dtmfChar
- * DTMF signal to send, 0-9, *, +
- */
- sendTone: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_DTMF);
- Buf.writeString(options.dtmfChar);
- Buf.sendParcel();
- },
-
- /**
- * Get the Short Message Service Center address.
- */
- getSmscAddress: function(options) {
- this.context.Buf.simpleRequest(REQUEST_GET_SMSC_ADDRESS, options);
- },
-
- /**
- * Set the Short Message Service Center address.
- *
- * @param smscAddress
- * Number part of the SMSC address.
- * @param typeOfNumber
- * Type of number in integer, as defined in
- * |Table 10.5.118: Called party BCD number| of 3GPP TS 24.008.
- * @param numberPlanIdentification
- * The index of number plan identification value in
- * CALLED_PARTY_BCD_NPI array.
- */
- setSmscAddress: function(options) {
- let ton = options.typeOfNumber;
- let npi = CALLED_PARTY_BCD_NPI[options.numberPlanIdentification];
-
- // If any of the mandatory arguments is not available, return an error
- // immediately.
- if (ton === undefined || npi === undefined || !options.smscAddress) {
- options.errorMsg = GECKO_ERROR_INVALID_PARAMETER;
- this.sendChromeMessage(options);
- return;
- }
-
- // Remove all illegal characters in the number string for user-input fault
- // tolerance.
- let numStart = options.smscAddress[0] === "+" ? 1 : 0;
- let number = options.smscAddress.substring(0, numStart) +
- options.smscAddress.substring(numStart)
- .replace(/[^0-9*#abc]/ig, "");
-
- // If the filtered number is an empty string, return an error immediately.
- if (number.length === 0) {
- options.errorMsg = GECKO_ERROR_INVALID_PARAMETER;
- this.sendChromeMessage(options);
- return;
- }
-
- // Init parcel.
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_SMSC_ADDRESS, options);
-
- // +---+-----------+---------------+
- // | 1 | TON | NPI |
- // +---+-----------+---------------+
- let tosca = (0x1 << 7) + (ton << 4) + npi;
- if (RILQUIRKS_SMSC_ADDRESS_FORMAT === "pdu") {
- let pduHelper = this.context.GsmPDUHelper;
-
- // Remove the preceding '+', and covert the special BCD digits defined in
- // |Called party BCD number| of 3GPP TS 24.008 to corresponding
- // hexadecimal values (refer the following table).
- //
- // +=========+=======+=====+
- // | value | digit | hex |
- // +========================
- // | 1 0 1 0 | * | 0xA |
- // | 1 0 1 1 | # | 0xB |
- // | 1 1 0 0 | a | 0xC |
- // | 1 1 0 1 | b | 0xD |
- // | 1 1 1 0 | c | 0xE |
- // +=========+=======+=====+
- //
- // The replace order is reversed intentionally, because if the digits are
- // replaced in ascending order, "#" will be converted to "b" and then be
- // converted again to "d", which generates incorrect result.
- let pureNumber = number.substring(numStart)
- .replace(/c/ig, "e")
- .replace(/b/ig, "d")
- .replace(/a/ig, "c")
- .replace(/\#/g, "b")
- .replace(/\*/g, "a");
-
- // address length and string length
- let length = Math.ceil(pureNumber.length / 2) + 1; // +1 octet for TOA
- let strlen = length * 2 + 2; // +2 semi-octets for length octet
-
- Buf.writeInt32(strlen);
- pduHelper.writeHexOctet(length);
- pduHelper.writeHexOctet(tosca);
- pduHelper.writeSwappedNibbleBCD(pureNumber);
- Buf.writeStringDelimiter(strlen);
- } else /* RILQUIRKS_SMSC_ADDRESS_FORMAT === "text" */ {
- let sca;
- sca = '"' + number + '"' + ',' + tosca;
- Buf.writeString(sca);
- }
-
- Buf.sendParcel();
- },
-
- /**
- * Setup a data call.
- *
- * @param radioTech
- * Integer to indicate radio technology.
- * DATACALL_RADIOTECHNOLOGY_CDMA => CDMA.
- * DATACALL_RADIOTECHNOLOGY_GSM => GSM.
- * @param apn
- * String containing the name of the APN to connect to.
- * @param user
- * String containing the username for the APN.
- * @param passwd
- * String containing the password for the APN.
- * @param chappap
- * Integer containing CHAP/PAP auth type.
- * DATACALL_AUTH_NONE => PAP and CHAP is never performed.
- * DATACALL_AUTH_PAP => PAP may be performed.
- * DATACALL_AUTH_CHAP => CHAP may be performed.
- * DATACALL_AUTH_PAP_OR_CHAP => PAP / CHAP may be performed.
- * @param pdptype
- * String containing PDP type to request. ("IP", "IPV6", ...)
- */
- setupDataCall: function(options) {
- // From ./hardware/ril/include/telephony/ril.h:
- // ((const char **)data)[0] Radio technology to use: 0-CDMA, 1-GSM/UMTS, 2...
- // for values above 2 this is RIL_RadioTechnology + 2.
- //
- // From frameworks/base/telephony/java/com/android/internal/telephony/DataConnection.java:
- // if the mRilVersion < 6, radio technology must be GSM/UMTS or CDMA.
- // Otherwise, it must be + 2
- //
- // See also bug 901232 and 867873
- let radioTech = options.radioTech + 2;
- let Buf = this.context.Buf;
- let token = Buf.newParcel(REQUEST_SETUP_DATA_CALL, options);
- Buf.writeInt32(7);
- Buf.writeString(radioTech.toString());
- Buf.writeString(DATACALL_PROFILE_DEFAULT.toString());
- Buf.writeString(options.apn);
- Buf.writeString(options.user);
- Buf.writeString(options.passwd);
- Buf.writeString(options.chappap.toString());
- Buf.writeString(options.pdptype);
- Buf.sendParcel();
- return token;
- },
-
- /**
- * Deactivate a data call.
- *
- * @param cid
- * String containing CID.
- * @param reason
- * One of DATACALL_DEACTIVATE_* constants.
- */
- deactivateDataCall: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_DEACTIVATE_DATA_CALL, options);
- Buf.writeInt32(2);
- Buf.writeString(options.cid.toString());
- Buf.writeString(options.reason !== undefined ?
- options.reason.toString() :
- DATACALL_DEACTIVATE_NO_REASON.toString());
- Buf.sendParcel();
- },
-
- /**
- * Get a list of data calls.
- */
- getDataCallList: function(options) {
- this.context.Buf.simpleRequest(REQUEST_DATA_CALL_LIST, options);
- },
-
- _attachDataRegistration: false,
- /**
- * Manually attach/detach data registration.
- *
- * @param attach
- * Boolean value indicating attach or detach.
- */
- setDataRegistration: function(options) {
- this._attachDataRegistration = options.attach;
-
- if (RILQUIRKS_DATA_REGISTRATION_ON_DEMAND) {
- let request = options.attach ? RIL_REQUEST_GPRS_ATTACH :
- RIL_REQUEST_GPRS_DETACH;
- this.context.Buf.simpleRequest(request, options);
- return;
- } else if (RILQUIRKS_SUBSCRIPTION_CONTROL && options.attach) {
- this.context.Buf.simpleRequest(REQUEST_SET_DATA_SUBSCRIPTION, options);
- return;
- }
-
- // We don't really send a request to rild, so instantly reply success to
- // RadioInterfaceLayer.
- this.sendChromeMessage(options);
- },
-
- /**
- * Get failure casue code for the most recently failed PDP context.
- */
- getFailCause: function(options) {
- this.context.Buf.simpleRequest(REQUEST_LAST_CALL_FAIL_CAUSE, options);
- },
-
- /**
- * Send USSD.
- *
- * @param ussd
- * String containing the USSD code.
- */
- sendUSSD: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SEND_USSD, options);
- Buf.writeString(options.ussd);
- Buf.sendParcel();
- },
-
- /**
- * Cancel pending USSD.
- */
- cancelUSSD: function(options) {
- this.context.Buf.simpleRequest(REQUEST_CANCEL_USSD, options);
- },
-
- /**
- * Queries current call forward rules.
- *
- * @param reason
- * One of CALL_FORWARD_REASON_* constants.
- * @param serviceClass
- * One of ICC_SERVICE_CLASS_* constants.
- * @param number
- * Phone number of forwarding address.
- */
- queryCallForwardStatus: function(options) {
- let Buf = this.context.Buf;
- let number = options.number || "";
- Buf.newParcel(REQUEST_QUERY_CALL_FORWARD_STATUS, options);
- Buf.writeInt32(CALL_FORWARD_ACTION_QUERY_STATUS);
- Buf.writeInt32(options.reason);
- Buf.writeInt32(options.serviceClass || ICC_SERVICE_CLASS_NONE);
- Buf.writeInt32(this._toaFromString(number));
- Buf.writeString(number);
- Buf.writeInt32(0);
- Buf.sendParcel();
- },
-
- /**
- * Configures call forward rule.
- *
- * @param action
- * One of CALL_FORWARD_ACTION_* constants.
- * @param reason
- * One of CALL_FORWARD_REASON_* constants.
- * @param serviceClass
- * One of ICC_SERVICE_CLASS_* constants.
- * @param number
- * Phone number of forwarding address.
- * @param timeSeconds
- * Time in seconds to wait beforec all is forwarded.
- */
- setCallForward: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_SET_CALL_FORWARD, options);
- Buf.writeInt32(options.action);
- Buf.writeInt32(options.reason);
- Buf.writeInt32(options.serviceClass);
- Buf.writeInt32(this._toaFromString(options.number));
- Buf.writeString(options.number);
- Buf.writeInt32(options.timeSeconds);
- Buf.sendParcel();
- },
-
- /**
- * Queries current call barring rules.
- *
- * @param program
- * One of CALL_BARRING_PROGRAM_* constants.
- * @param serviceClass
- * One of ICC_SERVICE_CLASS_* constants.
- */
- queryCallBarringStatus: function(options) {
- options.facility = CALL_BARRING_PROGRAM_TO_FACILITY[options.program];
- options.password = ""; // For query no need to provide it.
-
- // For some operators, querying specific serviceClass doesn't work. We use
- // serviceClass 0 instead, and then process the response to extract the
- // answer for queryServiceClass.
- options.queryServiceClass = options.serviceClass;
- options.serviceClass = 0;
-
- this.queryICCFacilityLock(options);
- },
-
- /**
- * Configures call barring rule.
- *
- * @param program
- * One of CALL_BARRING_PROGRAM_* constants.
- * @param enabled
- * Enable or disable the call barring.
- * @param password
- * Barring password.
- * @param serviceClass
- * One of ICC_SERVICE_CLASS_* constants.
- */
- setCallBarring: function(options) {
- options.facility = CALL_BARRING_PROGRAM_TO_FACILITY[options.program];
- this.setICCFacilityLock(options);
- },
-
- /**
- * Change call barring facility password.
- *
- * @param pin
- * Old password.
- * @param newPin
- * New password.
- */
- changeCallBarringPassword: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_CHANGE_BARRING_PASSWORD, options);
- Buf.writeInt32(3);
- // Set facility to ICC_CB_FACILITY_BA_ALL by following TS.22.030 clause
- // 6.5.4 and Table B.1.
- Buf.writeString(ICC_CB_FACILITY_BA_ALL);
- Buf.writeString(options.pin);
- Buf.writeString(options.newPin);
- Buf.sendParcel();
- },
-
- /**
- * Handle STK CALL_SET_UP request.
- *
- * @param hasConfirmed
- * Does use have confirmed the call requested from ICC?
- */
- stkHandleCallSetup: function(options) {
- let Buf = this.context.Buf;
- Buf.newParcel(REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM);
- Buf.writeInt32(1);
- Buf.writeInt32(options.hasConfirmed ? 1 : 0);
- Buf.sendParcel();
- },
-
- /**
- * Send STK Profile Download.
- *
- * @param profile Profile supported by ME.
- */
- sendStkTerminalProfile: function(profile) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- Buf.newParcel(REQUEST_STK_SET_PROFILE);
- Buf.writeInt32(profile.length * 2);
- for (let i = 0; i < profile.length; i++) {
- GsmPDUHelper.writeHexOctet(profile[i]);
- }
- Buf.writeInt32(0);
- Buf.sendParcel();
- },
-
- /**
- * Send STK terminal response.
- *
- * @param command
- * @param deviceIdentities
- * @param resultCode
- * @param [optional] additionalInformation
- * @param [optional] itemIdentifier
- * @param [optional] input
- * @param [optional] isYesNo
- * @param [optional] hasConfirmed
- * @param [optional] localInfo
- * @param [optional] timer
- */
- sendStkTerminalResponse: function(response) {
- if (response.hasConfirmed !== undefined) {
- this.stkHandleCallSetup(response);
- return;
- }
-
- let Buf = this.context.Buf;
- let ComprehensionTlvHelper = this.context.ComprehensionTlvHelper;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let command = response.command;
- Buf.newParcel(REQUEST_STK_SEND_TERMINAL_RESPONSE);
-
- // 1st mark for Parcel size
- Buf.startCalOutgoingSize(function(size) {
- // Parcel size is in string length, which costs 2 uint8 per char.
- Buf.writeInt32(size / 2);
- });
-
- // Command Details
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_COMMAND_DETAILS |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(3);
- if (command) {
- GsmPDUHelper.writeHexOctet(command.commandNumber);
- GsmPDUHelper.writeHexOctet(command.typeOfCommand);
- GsmPDUHelper.writeHexOctet(command.commandQualifier);
- } else {
- GsmPDUHelper.writeHexOctet(0x00);
- GsmPDUHelper.writeHexOctet(0x00);
- GsmPDUHelper.writeHexOctet(0x00);
- }
-
- // Device Identifier
- // According to TS102.223/TS31.111 section 6.8 Structure of
- // TERMINAL RESPONSE, "For all SIMPLE-TLV objects with Min=N,
- // the ME should set the CR(comprehension required) flag to
- // comprehension not required.(CR=0)"
- // Since DEVICE_IDENTITIES and DURATION TLVs have Min=N,
- // the CR flag is not set.
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_DEVICE_ID);
- GsmPDUHelper.writeHexOctet(2);
- GsmPDUHelper.writeHexOctet(STK_DEVICE_ID_ME);
- GsmPDUHelper.writeHexOctet(STK_DEVICE_ID_SIM);
-
- // Result
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_RESULT |
- COMPREHENSIONTLV_FLAG_CR);
- if ("additionalInformation" in response) {
- // In |12.12 Result| TS 11.14, the length of additional information is
- // varied and all possible values are addressed in 12.12.1-11 of TS 11.14
- // and 8.12.1-13 in TS 31.111.
- // However,
- // 1. Only SEND SS requires info with more than 1 octet.
- // 2. In rild design, SEND SS is expected to be handled by modem and
- // UNSOLICITED_STK_EVENT_NOTIFY will be sent to application layer to
- // indicate appropriate messages to users. TR is not required in this
- // case.
- // Hence, we simplify the structure of |additionalInformation| to a
- // numeric value instead of a octet array.
- GsmPDUHelper.writeHexOctet(2);
- GsmPDUHelper.writeHexOctet(response.resultCode);
- GsmPDUHelper.writeHexOctet(response.additionalInformation);
- } else {
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(response.resultCode);
- }
-
- // Item Identifier
- if (response.itemIdentifier != null) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_ITEM_ID |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(response.itemIdentifier);
- }
-
- // No need to process Text data if user requests help information.
- if (response.resultCode != STK_RESULT_HELP_INFO_REQUIRED) {
- let text;
- let coding = command.options.isUCS2 ?
- STK_TEXT_CODING_UCS2 :
- (command.options.isPacked ?
- STK_TEXT_CODING_GSM_7BIT_PACKED :
- STK_TEXT_CODING_GSM_8BIT);
- if (response.isYesNo !== undefined) {
- // Tag: GET_INKEY
- // When the ME issues a successful TERMINAL RESPONSE for a GET INKEY
- // ("Yes/No") command with command qualifier set to "Yes/No", it shall
- // supply the value '01' when the answer is "positive" and the value
- // '00' when the answer is "negative" in the Text string data object.
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_TEXT_STRING |
- COMPREHENSIONTLV_FLAG_CR);
- // Length: 2
- GsmPDUHelper.writeHexOctet(2);
- // Value: Coding, Yes/No.
- GsmPDUHelper.writeHexOctet(coding);
- GsmPDUHelper.writeHexOctet(response.isYesNo ? 0x01 : 0x00);
- } else {
- if (response.input !== undefined) {
- ComprehensionTlvHelper.writeTextStringTlv(response.input, coding);
- }
- }
- }
-
- // Duration
- if (response.resultCode === STK_RESULT_NO_RESPONSE_FROM_USER) {
- // In TS102 223, 6.4.2 GET INKEY, "if the UICC requests a variable timeout,
- // the terminal shall wait until either the user enters a single character
- // or the timeout expires. The timer starts when the text is displayed on
- // the screen and stops when the TERMINAL RESPONSE is sent. The terminal
- // shall pass the total display text duration (command execution duration)
- // to the UICC using the TERMINAL RESPONSE. The time unit of the response
- // is identical to the time unit of the requested variable timeout."
- let duration = command && command.options && command.options.duration;
- if (duration) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_DURATION);
- GsmPDUHelper.writeHexOctet(2);
- GsmPDUHelper.writeHexOctet(duration.timeUnit);
- GsmPDUHelper.writeHexOctet(duration.timeInterval);
- }
- }
-
- // Local Information
- if (response.localInfo) {
- let localInfo = response.localInfo;
-
- // Location Infomation
- if (localInfo.locationInfo) {
- ComprehensionTlvHelper.writeLocationInfoTlv(localInfo.locationInfo);
- }
-
- // IMEI
- if (localInfo.imei != null) {
- let imei = localInfo.imei;
- if (imei.length == 15) {
- imei = imei + "0";
- }
-
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_IMEI);
- GsmPDUHelper.writeHexOctet(8);
- for (let i = 0; i < imei.length / 2; i++) {
- GsmPDUHelper.writeHexOctet(parseInt(imei.substr(i * 2, 2), 16));
- }
- }
-
- // Date and Time Zone
- if (localInfo.date != null) {
- ComprehensionTlvHelper.writeDateTimeZoneTlv(localInfo.date);
- }
-
- // Language
- if (localInfo.language) {
- ComprehensionTlvHelper.writeLanguageTlv(localInfo.language);
- }
- }
-
- // Timer
- if (response.timer) {
- let timer = response.timer;
-
- if (timer.timerId) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_TIMER_IDENTIFIER);
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(timer.timerId);
- }
-
- if (timer.timerValue) {
- ComprehensionTlvHelper.writeTimerValueTlv(timer.timerValue, false);
- }
- }
-
- // Calculate and write Parcel size to 1st mark
- Buf.stopCalOutgoingSize();
-
- Buf.writeInt32(0);
- Buf.sendParcel();
- },
-
- /**
- * Send STK Envelope(Menu Selection) command.
- *
- * @param itemIdentifier
- * @param helpRequested
- */
- sendStkMenuSelection: function(command) {
- command.tag = BER_MENU_SELECTION_TAG;
- command.deviceId = {
- sourceId :STK_DEVICE_ID_KEYPAD,
- destinationId: STK_DEVICE_ID_SIM
- };
- this.sendICCEnvelopeCommand(command);
- },
-
- /**
- * Send STK Envelope(Timer Expiration) command.
- *
- * @param timer
- */
- sendStkTimerExpiration: function(command) {
- command.tag = BER_TIMER_EXPIRATION_TAG;
- command.deviceId = {
- sourceId: STK_DEVICE_ID_ME,
- destinationId: STK_DEVICE_ID_SIM
- };
- command.timerId = command.timer.timerId;
- command.timerValue = command.timer.timerValue;
- this.sendICCEnvelopeCommand(command);
- },
-
- /**
- * Send STK Envelope(Event Download) command.
- * @param event
- */
- sendStkEventDownload: function(command) {
- command.tag = BER_EVENT_DOWNLOAD_TAG;
- command.eventList = command.event.eventType;
- switch (command.eventList) {
- case STK_EVENT_TYPE_LOCATION_STATUS:
- command.deviceId = {
- sourceId :STK_DEVICE_ID_ME,
- destinationId: STK_DEVICE_ID_SIM
- };
- command.locationStatus = command.event.locationStatus;
- // Location info should only be provided when locationStatus is normal.
- if (command.locationStatus == STK_SERVICE_STATE_NORMAL) {
- command.locationInfo = command.event.locationInfo;
- }
- break;
- case STK_EVENT_TYPE_MT_CALL:
- command.deviceId = {
- sourceId: STK_DEVICE_ID_NETWORK,
- destinationId: STK_DEVICE_ID_SIM
- };
- command.transactionId = 0;
- command.address = command.event.number;
- break;
- case STK_EVENT_TYPE_CALL_DISCONNECTED:
- command.cause = command.event.error;
- // Fall through.
- case STK_EVENT_TYPE_CALL_CONNECTED:
- command.deviceId = {
- sourceId: (command.event.isIssuedByRemote ?
- STK_DEVICE_ID_NETWORK : STK_DEVICE_ID_ME),
- destinationId: STK_DEVICE_ID_SIM
- };
- command.transactionId = 0;
- break;
- case STK_EVENT_TYPE_USER_ACTIVITY:
- command.deviceId = {
- sourceId: STK_DEVICE_ID_ME,
- destinationId: STK_DEVICE_ID_SIM
- };
- break;
- case STK_EVENT_TYPE_IDLE_SCREEN_AVAILABLE:
- command.deviceId = {
- sourceId: STK_DEVICE_ID_DISPLAY,
- destinationId: STK_DEVICE_ID_SIM
- };
- break;
- case STK_EVENT_TYPE_LANGUAGE_SELECTION:
- command.deviceId = {
- sourceId: STK_DEVICE_ID_ME,
- destinationId: STK_DEVICE_ID_SIM
- };
- command.language = command.event.language;
- break;
- case STK_EVENT_TYPE_BROWSER_TERMINATION:
- command.deviceId = {
- sourceId: STK_DEVICE_ID_ME,
- destinationId: STK_DEVICE_ID_SIM
- };
- command.terminationCause = command.event.terminationCause;
- break;
- }
- this.sendICCEnvelopeCommand(command);
- },
-
- /**
- * Send REQUEST_STK_SEND_ENVELOPE_COMMAND to ICC.
- *
- * @param tag
- * @patam deviceId
- * @param [optioanl] itemIdentifier
- * @param [optional] helpRequested
- * @param [optional] eventList
- * @param [optional] locationStatus
- * @param [optional] locationInfo
- * @param [optional] address
- * @param [optional] transactionId
- * @param [optional] cause
- * @param [optional] timerId
- * @param [optional] timerValue
- * @param [optional] terminationCause
- */
- sendICCEnvelopeCommand: function(options) {
- if (DEBUG) {
- this.context.debug("Stk Envelope " + JSON.stringify(options));
- }
-
- let Buf = this.context.Buf;
- let ComprehensionTlvHelper = this.context.ComprehensionTlvHelper;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- Buf.newParcel(REQUEST_STK_SEND_ENVELOPE_COMMAND);
-
- // 1st mark for Parcel size
- Buf.startCalOutgoingSize(function(size) {
- // Parcel size is in string length, which costs 2 uint8 per char.
- Buf.writeInt32(size / 2);
- });
-
- // Write a BER-TLV
- GsmPDUHelper.writeHexOctet(options.tag);
- // 2nd mark for BER length
- Buf.startCalOutgoingSize(function(size) {
- // BER length is in number of hexOctets, which costs 4 uint8 per hexOctet.
- GsmPDUHelper.writeHexOctet(size / 4);
- });
-
- // Event List
- if (options.eventList != null) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_EVENT_LIST |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(options.eventList);
- }
-
- // Device Identifies
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_DEVICE_ID |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(2);
- GsmPDUHelper.writeHexOctet(options.deviceId.sourceId);
- GsmPDUHelper.writeHexOctet(options.deviceId.destinationId);
-
- // Item Identifier
- if (options.itemIdentifier != null) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_ITEM_ID |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(options.itemIdentifier);
- }
-
- // Help Request
- if (options.helpRequested) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_HELP_REQUEST |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(0);
- // Help Request doesn't have value
- }
-
- // Location Status
- if (options.locationStatus != null) {
- let len = options.locationStatus.length;
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_LOCATION_STATUS |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(options.locationStatus);
- }
-
- // Location Info
- if (options.locationInfo) {
- ComprehensionTlvHelper.writeLocationInfoTlv(options.locationInfo);
- }
-
- // Transaction Id
- if (options.transactionId != null) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_TRANSACTION_ID |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(options.transactionId);
- }
-
- // Address
- if (options.address) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_ADDRESS |
- COMPREHENSIONTLV_FLAG_CR);
- let addressLength = options.address[0] == '+' ? options.address.length - 1
- : options.address.length;
- ComprehensionTlvHelper.writeLength(
- Math.ceil(addressLength / 2) + 1 // address BCD + TON
- );
- this.context.ICCPDUHelper.writeDiallingNumber(options.address);
- }
-
- // Cause of disconnection.
- if (options.cause != null) {
- ComprehensionTlvHelper.writeCauseTlv(options.cause);
- }
-
- // Timer Identifier
- if (options.timerId != null) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_TIMER_IDENTIFIER |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(options.timerId);
- }
-
- // Timer Value
- if (options.timerValue != null) {
- ComprehensionTlvHelper.writeTimerValueTlv(options.timerValue, true);
- }
-
- // Language
- if (options.language) {
- ComprehensionTlvHelper.writeLanguageTlv(options.language);
- }
-
- // Browser Termination
- if (options.terminationCause != null) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_BROWSER_TERMINATION_CAUSE |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(1);
- GsmPDUHelper.writeHexOctet(options.terminationCause);
- }
-
- // Calculate and write BER length to 2nd mark
- Buf.stopCalOutgoingSize();
-
- // Calculate and write Parcel size to 1st mark
- Buf.stopCalOutgoingSize();
-
- Buf.writeInt32(0);
- Buf.sendParcel();
- },
-
- /**
- * Report STK Service is running.
- */
- reportStkServiceIsRunning: function() {
- this.context.Buf.simpleRequest(REQUEST_REPORT_STK_SERVICE_IS_RUNNING);
- },
-
- /**
- * Process ICC status.
- */
- _processICCStatus: function(iccStatus) {
- // If |_waitingRadioTech| is true, we should not get app information because
- // the |_isCdma| flag is not ready yet. Otherwise we may use wrong index to
- // get app information, especially for the case that icc card has both cdma
- // and gsm subscription.
- if (this._waitingRadioTech) {
- return;
- }
-
- // When |iccStatus.cardState| is not CARD_STATE_PRESENT, set cardState to
- // undetected.
- if (iccStatus.cardState !== CARD_STATE_PRESENT) {
- if (this.cardState !== GECKO_CARDSTATE_UNDETECTED) {
- this.operator = null;
- // We should send |cardstatechange| before |iccinfochange|, otherwise we
- // may lost cardstatechange event when icc card becomes undetected.
- this.cardState = GECKO_CARDSTATE_UNDETECTED;
- this.sendChromeMessage({rilMessageType: "cardstatechange",
- cardState: this.cardState});
-
- this.iccInfo = {iccType: null};
- this.context.ICCUtilsHelper.handleICCInfoChange();
- }
- return;
- }
-
- if (RILQUIRKS_SUBSCRIPTION_CONTROL) {
- // All appIndex is -1 means the subscription is not activated yet.
- // Note that we don't support "ims" for now, so we don't take it into
- // account.
- let neetToActivate = iccStatus.cdmaSubscriptionAppIndex === -1 &&
- iccStatus.gsmUmtsSubscriptionAppIndex === -1;
- if (neetToActivate &&
- // Note: setUiccSubscription works abnormally when RADIO is OFF,
- // which causes SMS function broken in Flame.
- // See bug 1008557 for detailed info.
- this.radioState === GECKO_RADIOSTATE_ENABLED) {
- for (let i = 0; i < iccStatus.apps.length; i++) {
- this.setUiccSubscription({appIndex: i, enabled: true});
- }
- }
- }
-
- let newCardState;
- let index = this._isCdma ? iccStatus.cdmaSubscriptionAppIndex
- : iccStatus.gsmUmtsSubscriptionAppIndex;
- let app = iccStatus.apps[index];
- if (app) {
- // fetchICCRecords will need to read aid, so read aid here.
- this.aid = app.aid;
- this.appType = app.app_type;
- this.iccInfo.iccType = GECKO_CARD_TYPE[this.appType];
-
- switch (app.app_state) {
- case CARD_APPSTATE_ILLEGAL:
- newCardState = GECKO_CARDSTATE_ILLEGAL;
- break;
- case CARD_APPSTATE_PIN:
- newCardState = GECKO_CARDSTATE_PIN_REQUIRED;
- break;
- case CARD_APPSTATE_PUK:
- newCardState = GECKO_CARDSTATE_PUK_REQUIRED;
- break;
- case CARD_APPSTATE_SUBSCRIPTION_PERSO:
- newCardState = PERSONSUBSTATE[app.perso_substate];
- break;
- case CARD_APPSTATE_READY:
- newCardState = GECKO_CARDSTATE_READY;
- break;
- case CARD_APPSTATE_UNKNOWN:
- case CARD_APPSTATE_DETECTED:
- // Fall through.
- default:
- newCardState = GECKO_CARDSTATE_UNKNOWN;
- }
-
- let pin1State = app.pin1_replaced ? iccStatus.universalPINState :
- app.pin1;
- if (pin1State === CARD_PINSTATE_ENABLED_PERM_BLOCKED) {
- newCardState = GECKO_CARDSTATE_PERMANENT_BLOCKED;
- }
- } else {
- // Having incorrect app information, set card state to unknown.
- newCardState = GECKO_CARDSTATE_UNKNOWN;
- }
-
- let ICCRecordHelper = this.context.ICCRecordHelper;
- // Try to get iccId only when cardState left GECKO_CARDSTATE_UNDETECTED.
- if (iccStatus.cardState === CARD_STATE_PRESENT &&
- (this.cardState === GECKO_CARDSTATE_UNINITIALIZED ||
- this.cardState === GECKO_CARDSTATE_UNDETECTED)) {
- ICCRecordHelper.readICCID();
- }
-
- if (this.cardState == newCardState) {
- return;
- }
-
- // This was moved down from CARD_APPSTATE_READY
- this.requestNetworkInfo();
- if (newCardState == GECKO_CARDSTATE_READY) {
- // For type SIM, we need to check EF_phase first.
- // Other types of ICC we can send Terminal_Profile immediately.
- if (this.appType == CARD_APPTYPE_SIM) {
- this.context.SimRecordHelper.readSimPhase();
- } else if (RILQUIRKS_SEND_STK_PROFILE_DOWNLOAD) {
- this.sendStkTerminalProfile(STK_SUPPORTED_TERMINAL_PROFILE);
- }
-
- ICCRecordHelper.fetchICCRecords();
- }
-
- this.cardState = newCardState;
- this.sendChromeMessage({rilMessageType: "cardstatechange",
- cardState: this.cardState});
- },
-
- /**
- * Helper for processing responses of functions such as enterICC* and changeICC*.
- */
- _processEnterAndChangeICCResponses: function(length, options) {
- options.retryCount = length ? this.context.Buf.readInt32List()[0] : -1;
- this.sendChromeMessage(options);
- },
-
- // We combine all of the NETWORK_INFO_MESSAGE_TYPES into one "networkinfochange"
- // message to the RadioInterfaceLayer, so we can avoid sending multiple
- // VoiceInfoChanged events for both operator / voice_data_registration
- //
- // State management here is a little tricky. We need to know both:
- // 1. Whether or not a response was received for each of the
- // NETWORK_INFO_MESSAGE_TYPES
- // 2. The outbound message that corresponds with that response -- but this
- // only happens when internal state changes (i.e. it isn't guaranteed)
- //
- // To collect this state, each message response function first calls
- // _receivedNetworkInfo, to mark the response as received. When the
- // final response is received, a call to _sendPendingNetworkInfo is placed
- // on the next tick of the worker thread.
- //
- // Since the original call to _receivedNetworkInfo happens at the top
- // of the response handler, this gives the final handler a chance to
- // queue up it's "changed" message by calling _sendNetworkInfoMessage if/when
- // the internal state has actually changed.
- _sendNetworkInfoMessage: function(type, message) {
- if (!this._processingNetworkInfo) {
- // We only combine these messages in the case of the combined request
- // in requestNetworkInfo()
- this.sendChromeMessage(message);
- return;
- }
-
- if (DEBUG) {
- this.context.debug("Queuing " + type + " network info message: " +
- JSON.stringify(message));
- }
- this._pendingNetworkInfo[type] = message;
- },
-
- _receivedNetworkInfo: function(type) {
- if (DEBUG) this.context.debug("Received " + type + " network info.");
- if (!this._processingNetworkInfo) {
- return;
- }
-
- let pending = this._pendingNetworkInfo;
-
- // We still need to track states for events that aren't fired.
- if (!(type in pending)) {
- pending[type] = this.pendingNetworkType;
- }
-
- // Pending network info is ready to be sent when no more messages
- // are waiting for responses, but the combined payload hasn't been sent.
- for (let i = 0; i < NETWORK_INFO_MESSAGE_TYPES.length; i++) {
- let msgType = NETWORK_INFO_MESSAGE_TYPES[i];
- if (!(msgType in pending)) {
- if (DEBUG) {
- this.context.debug("Still missing some more network info, not " +
- "notifying main thread.");
- }
- return;
- }
- }
-
- // Do a pass to clean up the processed messages that didn't create
- // a response message, so we don't have unused keys in the outbound
- // networkinfochanged message.
- for (let key in pending) {
- if (pending[key] == this.pendingNetworkType) {
- delete pending[key];
- }
- }
-
- if (DEBUG) {
- this.context.debug("All pending network info has been received: " +
- JSON.stringify(pending));
- }
-
- // Send the message on the next tick of the worker's loop, so we give the
- // last message a chance to call _sendNetworkInfoMessage first.
- setTimeout(this._sendPendingNetworkInfo.bind(this), 0);
- },
-
- _sendPendingNetworkInfo: function() {
- this.sendChromeMessage(this._pendingNetworkInfo);
-
- this._processingNetworkInfo = false;
- for (let i = 0; i < NETWORK_INFO_MESSAGE_TYPES.length; i++) {
- delete this._pendingNetworkInfo[NETWORK_INFO_MESSAGE_TYPES[i]];
- }
-
- if (this._needRepollNetworkInfo) {
- this._needRepollNetworkInfo = false;
- this.requestNetworkInfo();
- }
- },
-
- /**
- * Normalize the signal strength in dBm to the signal level from 0 to 100.
- *
- * @param signal
- * The signal strength in dBm to normalize.
- * @param min
- * The signal strength in dBm maps to level 0.
- * @param max
- * The signal strength in dBm maps to level 100.
- *
- * @return level
- * The signal level from 0 to 100.
- */
- _processSignalLevel: function(signal, min, max) {
- if (signal <= min) {
- return 0;
- }
-
- if (signal >= max) {
- return 100;
- }
-
- return Math.floor((signal - min) * 100 / (max - min));
- },
-
- /**
- * Process LTE signal strength to the signal info object.
- *
- * @param signal
- * The signal object reported from RIL/modem.
- *
- * @return The object of signal strength info.
- * Or null if invalid signal input.
- *
- * TODO: Bug 982013: reconsider the format of signal strength APIs for
- * GSM/CDMA/LTE to expose details, such as rsrp and rsnnr,
- * individually.
- */
- _processLteSignal: function(signal) {
- let info = {
- voice: {
- signalStrength: null,
- relSignalStrength: null
- },
- data: {
- signalStrength: null,
- relSignalStrength: null
- }
- };
-
- // Referring to AOSP, use lteRSRP for signalStrength in dBm.
- let signalStrength = (signal.lteRSRP === undefined || signal.lteRSRP === 0x7FFFFFFF) ?
- null : signal.lteRSRP;
- info.voice.signalStrength = info.data.signalStrength = signalStrength;
-
- // Referring to AOSP, first determine signalLevel based on RSRP and RSSNR,
- // then on lteSignalStrength if RSRP and RSSNR are invalid.
- let rsrpLevel = -1;
- let rssnrLevel = -1;
- if (signal.lteRSRP !== undefined &&
- signal.lteRSRP !== 0x7FFFFFFF &&
- signal.lteRSRP >= 44 &&
- signal.lteRSRP <= 140) {
- rsrpLevel = this._processSignalLevel(signal.lteRSRP * -1, -115, -85);
- }
-
- if (signal.lteRSSNR !== undefined &&
- signal.lteRSSNR !== 0x7FFFFFFF &&
- signal.lteRSSNR >= -200 &&
- signal.lteRSSNR <= 300) {
- rssnrLevel = this._processSignalLevel(signal.lteRSSNR, -30, 130);
- }
-
- if (rsrpLevel !== -1 && rssnrLevel !== -1) {
- info.voice.relSignalStrength = info.data.relSignalStrength =
- Math.min(rsrpLevel, rssnrLevel);
- return info;
- }
-
- let level = Math.max(rsrpLevel, rssnrLevel);
- if (level !== -1) {
- info.voice.relSignalStrength = info.data.relSignalStrength = level;
- return info;
- }
-
- // Valid values are 0-63 as defined in TS 27.007 clause 8.69.
- if (signal.lteSignalStrength !== undefined &&
- signal.lteSignalStrength >= 0 &&
- signal.lteSignalStrength <= 63) {
- level = this._processSignalLevel(signal.lteSignalStrength, 0, 12);
- info.voice.relSignalStrength = info.data.relSignalStrength = level;
- return info;
- }
-
- return null;
- },
-
- _processSignalStrength: function(signal) {
- let info = {
- voice: {
- signalStrength: null,
- relSignalStrength: null
- },
- data: {
- signalStrength: null,
- relSignalStrength: null
- }
- };
-
- // During startup, |radioTech| is not yet defined, so we need to
- // check it separately.
- if (("radioTech" in this.voiceRegistrationState) &&
- !this._isGsmTechGroup(this.voiceRegistrationState.radioTech)) {
- // CDMA RSSI.
- // Valid values are positive integers. This value is the actual RSSI value
- // multiplied by -1. Example: If the actual RSSI is -75, then this
- // response value will be 75.
- if (signal.cdmaDBM && signal.cdmaDBM > 0) {
- let signalStrength = -1 * signal.cdmaDBM;
- info.voice.signalStrength = signalStrength;
-
- // -105 and -70 are referred to AOSP's implementation. These values are
- // not constants and can be customized based on different requirement.
- let signalLevel = this._processSignalLevel(signalStrength, -105, -70);
- info.voice.relSignalStrength = signalLevel;
- }
-
- // EVDO RSSI.
- // Valid values are positive integers. This value is the actual RSSI value
- // multiplied by -1. Example: If the actual RSSI is -75, then this
- // response value will be 75.
- if (signal.evdoDBM && signal.evdoDBM > 0) {
- let signalStrength = -1 * signal.evdoDBM;
- info.data.signalStrength = signalStrength;
-
- // -105 and -70 are referred to AOSP's implementation. These values are
- // not constants and can be customized based on different requirement.
- let signalLevel = this._processSignalLevel(signalStrength, -105, -70);
- info.data.relSignalStrength = signalLevel;
- }
- } else {
- // Check LTE level first, and check GSM/UMTS level next if LTE one is not
- // valid.
- let lteInfo = this._processLteSignal(signal);
- if (lteInfo) {
- info = lteInfo;
- } else {
- // GSM signal strength.
- // Valid values are 0-31 as defined in TS 27.007 8.5.
- // 0 : -113 dBm or less
- // 1 : -111 dBm
- // 2...30: -109...-53 dBm
- // 31 : -51 dBm
- if (signal.gsmSignalStrength &&
- signal.gsmSignalStrength >= 0 &&
- signal.gsmSignalStrength <= 31) {
- let signalStrength = -113 + 2 * signal.gsmSignalStrength;
- info.voice.signalStrength = info.data.signalStrength = signalStrength;
-
- // -115 and -85 are referred to AOSP's implementation. These values are
- // not constants and can be customized based on different requirement.
- let signalLevel = this._processSignalLevel(signalStrength, -110, -85);
- info.voice.relSignalStrength = info.data.relSignalStrength = signalLevel;
- }
- }
- }
-
- info.rilMessageType = "signalstrengthchange";
- this._sendNetworkInfoMessage(NETWORK_INFO_SIGNAL, info);
- },
-
- /**
- * Process the network registration flags.
- *
- * @return true if the state changed, false otherwise.
- */
- _processCREG: function(curState, newState) {
- let changed = false;
-
- let regState = this.parseInt(newState[0], NETWORK_CREG_STATE_UNKNOWN);
- if (curState.regState === undefined || curState.regState !== regState) {
- changed = true;
- curState.regState = regState;
-
- curState.state = NETWORK_CREG_TO_GECKO_MOBILE_CONNECTION_STATE[regState];
- curState.connected = regState == NETWORK_CREG_STATE_REGISTERED_HOME ||
- regState == NETWORK_CREG_STATE_REGISTERED_ROAMING;
- curState.roaming = regState == NETWORK_CREG_STATE_REGISTERED_ROAMING;
- curState.emergencyCallsOnly = !curState.connected;
- }
-
- if (!curState.cell) {
- curState.cell = {};
- }
-
- // From TS 23.003, 0000 and 0xfffe are indicated that no valid LAI exists
- // in MS. So we still need to report the '0000' as well.
- let lac = this.parseInt(newState[1], -1, 16);
- if (curState.cell.gsmLocationAreaCode === undefined ||
- curState.cell.gsmLocationAreaCode !== lac) {
- curState.cell.gsmLocationAreaCode = lac;
- changed = true;
- }
-
- let cid = this.parseInt(newState[2], -1, 16);
- if (curState.cell.gsmCellId === undefined ||
- curState.cell.gsmCellId !== cid) {
- curState.cell.gsmCellId = cid;
- changed = true;
- }
-
- let radioTech = (newState[3] === undefined ?
- NETWORK_CREG_TECH_UNKNOWN :
- this.parseInt(newState[3], NETWORK_CREG_TECH_UNKNOWN));
- if (curState.radioTech === undefined || curState.radioTech !== radioTech) {
- changed = true;
- curState.radioTech = radioTech;
- curState.type = GECKO_RADIO_TECH[radioTech] || null;
- }
- return changed;
- },
-
- _processVoiceRegistrationState: function(state) {
- let rs = this.voiceRegistrationState;
- let stateChanged = this._processCREG(rs, state);
- if (stateChanged && rs.connected) {
- this.getSmscAddress();
- }
-
- let cell = rs.cell;
- if (this._isCdma) {
- // Some variables below are not used. Comment them instead of removing to
- // keep the information about state[x].
- let cdmaBaseStationId = this.parseInt(state[4], -1);
- let cdmaBaseStationLatitude = this.parseInt(state[5], -2147483648);
- let cdmaBaseStationLongitude = this.parseInt(state[6], -2147483648);
- // let cssIndicator = this.parseInt(state[7]);
- let cdmaSystemId = this.parseInt(state[8], -1);
- let cdmaNetworkId = this.parseInt(state[9], -1);
- // let roamingIndicator = this.parseInt(state[10]);
- // let systemIsInPRL = this.parseInt(state[11]);
- // let defaultRoamingIndicator = this.parseInt(state[12]);
- // let reasonForDenial = this.parseInt(state[13]);
-
- if (cell.cdmaBaseStationId !== cdmaBaseStationId ||
- cell.cdmaBaseStationLatitude !== cdmaBaseStationLatitude ||
- cell.cdmaBaseStationLongitude !== cdmaBaseStationLongitude ||
- cell.cdmaSystemId !== cdmaSystemId ||
- cell.cdmaNetworkId !== cdmaNetworkId) {
- stateChanged = true;
- cell.cdmaBaseStationId = cdmaBaseStationId;
- cell.cdmaBaseStationLatitude = cdmaBaseStationLatitude;
- cell.cdmaBaseStationLongitude = cdmaBaseStationLongitude;
- cell.cdmaSystemId = cdmaSystemId;
- cell.cdmaNetworkId = cdmaNetworkId;
- }
- }
-
- if (stateChanged) {
- rs.rilMessageType = "voiceregistrationstatechange";
- this._sendNetworkInfoMessage(NETWORK_INFO_VOICE_REGISTRATION_STATE, rs);
- }
- },
-
- _processDataRegistrationState: function(state) {
- let rs = this.dataRegistrationState;
- let stateChanged = this._processCREG(rs, state);
- if (stateChanged) {
- rs.rilMessageType = "dataregistrationstatechange";
- this._sendNetworkInfoMessage(NETWORK_INFO_DATA_REGISTRATION_STATE, rs);
- }
- },
-
- _processOperator: function(operatorData) {
- if (operatorData.length < 3) {
- if (DEBUG) {
- this.context.debug("Expected at least 3 strings for operator.");
- }
- }
-
- if (!this.operator) {
- this.operator = {
- rilMessageType: "operatorchange",
- longName: null,
- shortName: null
- };
- }
-
- let [longName, shortName, networkTuple] = operatorData;
- let thisTuple = (this.operator.mcc || "") + (this.operator.mnc || "");
-
- if (this.operator.longName !== longName ||
- this.operator.shortName !== shortName ||
- thisTuple !== networkTuple) {
-
- this.operator.mcc = null;
- this.operator.mnc = null;
-
- if (networkTuple) {
- try {
- this._processNetworkTuple(networkTuple, this.operator);
- } catch (e) {
- if (DEBUG) this.context.debug("Error processing operator tuple: " + e);
- }
- } else {
- // According to ril.h, the operator fields will be NULL when the operator
- // is not currently registered. We can avoid trying to parse the numeric
- // tuple in that case.
- if (DEBUG) {
- this.context.debug("Operator is currently unregistered");
- }
- }
-
- this.operator.longName = longName;
- this.operator.shortName = shortName;
-
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- if (ICCUtilsHelper.updateDisplayCondition()) {
- ICCUtilsHelper.handleICCInfoChange();
- }
-
- // NETWORK_INFO_OPERATOR message will be sent out by overrideICCNetworkName
- // itself if operator name is overridden after checking, or we have to
- // do it by ourself.
- if (!this.overrideICCNetworkName()) {
- this._sendNetworkInfoMessage(NETWORK_INFO_OPERATOR, this.operator);
- }
- }
- },
-
- _processSuppSvcNotification: function(info) {
- if (DEBUG) {
- this.context.debug("handle supp svc notification: " + JSON.stringify(info));
- }
-
- if (info.notificationType !== 1) {
- // We haven't supported MO intermediate result code, i.e.
- // info.notificationType === 0, which refers to code1 defined in 3GPP
- // 27.007 7.17. We only support partial MT unsolicited result code,
- // referring to code2, for now.
- return;
- }
-
- let notification = null;
-
- switch (info.code) {
- case SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD:
- case SUPP_SVC_NOTIFICATION_CODE2_RETRIEVED:
- notification = GECKO_SUPP_SVC_NOTIFICATION_FROM_CODE2[info.code];
- break;
- default:
- // Notification type not supported.
- return;
- }
-
- let message = {rilMessageType: "suppSvcNotification",
- number: info.number, // could be empty.
- notification: notification};
- this.sendChromeMessage(message);
- },
-
- _cancelEmergencyCbModeTimeout: function() {
- if (this._exitEmergencyCbModeTimeoutID) {
- clearTimeout(this._exitEmergencyCbModeTimeoutID);
- this._exitEmergencyCbModeTimeoutID = null;
- }
- },
-
- _handleChangedEmergencyCbMode: function(active) {
- this._isInEmergencyCbMode = active;
-
- // Clear the existed timeout event.
- this._cancelEmergencyCbModeTimeout();
-
- // Start a new timeout event when entering the mode.
- if (active) {
- this._exitEmergencyCbModeTimeoutID = setTimeout(
- this.exitEmergencyCbMode.bind(this), EMERGENCY_CB_MODE_TIMEOUT_MS);
- }
-
- let message = {rilMessageType: "emergencyCbModeChange",
- active: active,
- timeoutMs: EMERGENCY_CB_MODE_TIMEOUT_MS};
- this.sendChromeMessage(message);
- },
-
- _updateNetworkSelectionMode: function(mode) {
- if (this.networkSelectionMode === mode) {
- return;
- }
-
- let options = {
- rilMessageType: "networkselectionmodechange",
- mode: mode
- };
- this.networkSelectionMode = mode;
- this._sendNetworkInfoMessage(NETWORK_INFO_NETWORK_SELECTION_MODE, options);
- },
-
- _processNetworks: function() {
- let strings = this.context.Buf.readStringList();
- let networks = [];
-
- for (let i = 0; i < strings.length;
- i += RILQUIRKS_AVAILABLE_NETWORKS_EXTRA_STRING ? 5 : 4) {
- let network = {
- longName: strings[i],
- shortName: strings[i + 1],
- mcc: null,
- mnc: null,
- state: null
- };
-
- let networkTuple = strings[i + 2];
- try {
- this._processNetworkTuple(networkTuple, network);
- } catch (e) {
- if (DEBUG) this.context.debug("Error processing operator tuple: " + e);
- }
-
- let state = strings[i + 3];
- network.state = RIL_QAN_STATE_TO_GECKO_STATE[state];
-
- networks.push(network);
- }
- return networks;
- },
-
- /**
- * The "numeric" portion of the operator info is a tuple
- * containing MCC (country code) and MNC (network code).
- * AFAICT, MCC should always be 3 digits, making the remaining
- * portion the MNC.
- */
- _processNetworkTuple: function(networkTuple, network) {
- let tupleLen = networkTuple.length;
-
- if (tupleLen == 5 || tupleLen == 6) {
- network.mcc = networkTuple.substr(0, 3);
- network.mnc = networkTuple.substr(3);
- } else {
- network.mcc = null;
- network.mnc = null;
-
- throw new Error("Invalid network tuple (should be 5 or 6 digits): " + networkTuple);
- }
- },
-
- /**
- * Check if GSM radio access technology group.
- */
- _isGsmTechGroup: function(radioTech) {
- if (!radioTech) {
- return true;
- }
-
- switch(radioTech) {
- case NETWORK_CREG_TECH_GPRS:
- case NETWORK_CREG_TECH_EDGE:
- case NETWORK_CREG_TECH_UMTS:
- case NETWORK_CREG_TECH_HSDPA:
- case NETWORK_CREG_TECH_HSUPA:
- case NETWORK_CREG_TECH_HSPA:
- case NETWORK_CREG_TECH_LTE:
- case NETWORK_CREG_TECH_HSPAP:
- case NETWORK_CREG_TECH_GSM:
- case NETWORK_CREG_TECH_DCHSPAP_1:
- case NETWORK_CREG_TECH_DCHSPAP_2:
- return true;
- }
-
- return false;
- },
-
- /**
- * Process radio technology change.
- */
- _processRadioTech: function(radioTech) {
- let isCdma = !this._isGsmTechGroup(radioTech);
- this.radioTech = radioTech;
-
- if (DEBUG) {
- this.context.debug("Radio tech is set to: " + GECKO_RADIO_TECH[radioTech] +
- ", it is a " + (isCdma?"cdma":"gsm") + " technology");
- }
-
- // We should request SIM information when
- // 1. Radio state has been changed, so we are waiting for radioTech or
- // 2. isCdma is different from this._isCdma.
- if (this._waitingRadioTech || isCdma != this._isCdma) {
- this._isCdma = isCdma;
- this._waitingRadioTech = false;
- this.getICCStatus();
- }
- },
-
- /**
- * Helper for returning the TOA for the given dial string.
- */
- _toaFromString: function(number) {
- let toa = TOA_UNKNOWN;
- if (number && number.length > 0 && number[0] == '+') {
- toa = TOA_INTERNATIONAL;
- }
- return toa;
- },
-
- /**
- * @param message A decoded SMS-DELIVER message.
- *
- * @see 3GPP TS 31.111 section 7.1.1
- */
- dataDownloadViaSMSPP: function(message) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let options = {
- pid: message.pid,
- dcs: message.dcs,
- encoding: message.encoding,
- };
- Buf.newParcel(REQUEST_STK_SEND_ENVELOPE_WITH_STATUS, options);
-
- Buf.seekIncoming(-1 * (Buf.getCurrentParcelSize() - Buf.getReadAvailable()
- - 2 * Buf.UINT32_SIZE)); // Skip response_type & request_type.
- let messageStringLength = Buf.readInt32(); // In semi-octets
- let smscLength = GsmPDUHelper.readHexOctet(); // In octets, inclusive of TOA
- let tpduLength = (messageStringLength / 2) - (smscLength + 1); // In octets
-
- // Device identities: 4 bytes
- // Address: 0 or (2 + smscLength)
- // SMS TPDU: (2 or 3) + tpduLength
- let berLen = 4 +
- (smscLength ? (2 + smscLength) : 0) +
- (tpduLength <= 127 ? 2 : 3) + tpduLength; // In octets
-
- let parcelLength = (berLen <= 127 ? 2 : 3) + berLen; // In octets
- Buf.writeInt32(parcelLength * 2); // In semi-octets
-
- // Write a BER-TLV
- GsmPDUHelper.writeHexOctet(BER_SMS_PP_DOWNLOAD_TAG);
- if (berLen > 127) {
- GsmPDUHelper.writeHexOctet(0x81);
- }
- GsmPDUHelper.writeHexOctet(berLen);
-
- // Device Identifies-TLV
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_DEVICE_ID |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(0x02);
- GsmPDUHelper.writeHexOctet(STK_DEVICE_ID_NETWORK);
- GsmPDUHelper.writeHexOctet(STK_DEVICE_ID_SIM);
-
- // Address-TLV
- if (smscLength) {
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_ADDRESS);
- GsmPDUHelper.writeHexOctet(smscLength);
- Buf.copyIncomingToOutgoing(Buf.PDU_HEX_OCTET_SIZE * smscLength);
- }
-
- // SMS TPDU-TLV
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_SMS_TPDU |
- COMPREHENSIONTLV_FLAG_CR);
- if (tpduLength > 127) {
- GsmPDUHelper.writeHexOctet(0x81);
- }
- GsmPDUHelper.writeHexOctet(tpduLength);
- Buf.copyIncomingToOutgoing(Buf.PDU_HEX_OCTET_SIZE * tpduLength);
-
- // Write 2 string delimitors for the total string length must be even.
- Buf.writeStringDelimiter(0);
-
- Buf.sendParcel();
- },
-
- /**
- * @param success A boolean value indicating the result of previous
- * SMS-DELIVER message handling.
- * @param responsePduLen ICC IO response PDU length in octets.
- * @param options An object that contains four attributes: `pid`, `dcs`,
- * `encoding` and `responsePduLen`.
- *
- * @see 3GPP TS 23.040 section 9.2.2.1a
- */
- acknowledgeIncomingGsmSmsWithPDU: function(success, responsePduLen, options) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- Buf.newParcel(REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU);
-
- // Two strings.
- Buf.writeInt32(2);
-
- // String 1: Success
- Buf.writeString(success ? "1" : "0");
-
- // String 2: RP-ACK/RP-ERROR PDU
- Buf.writeInt32(2 * (responsePduLen + (success ? 5 : 6))); // In semi-octet
- // 1. TP-MTI & TP-UDHI
- GsmPDUHelper.writeHexOctet(PDU_MTI_SMS_DELIVER);
- if (!success) {
- // 2. TP-FCS
- GsmPDUHelper.writeHexOctet(PDU_FCS_USIM_DATA_DOWNLOAD_ERROR);
- }
- // 3. TP-PI
- GsmPDUHelper.writeHexOctet(PDU_PI_USER_DATA_LENGTH |
- PDU_PI_DATA_CODING_SCHEME |
- PDU_PI_PROTOCOL_IDENTIFIER);
- // 4. TP-PID
- GsmPDUHelper.writeHexOctet(options.pid);
- // 5. TP-DCS
- GsmPDUHelper.writeHexOctet(options.dcs);
- // 6. TP-UDL
- if (options.encoding == PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
- GsmPDUHelper.writeHexOctet(Math.floor(responsePduLen * 8 / 7));
- } else {
- GsmPDUHelper.writeHexOctet(responsePduLen);
- }
- // TP-UD
- Buf.copyIncomingToOutgoing(Buf.PDU_HEX_OCTET_SIZE * responsePduLen);
- // Write 2 string delimitors for the total string length must be even.
- Buf.writeStringDelimiter(0);
-
- Buf.sendParcel();
- },
-
- /**
- * @param message A decoded SMS-DELIVER message.
- */
- writeSmsToSIM: function(message) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- Buf.newParcel(REQUEST_WRITE_SMS_TO_SIM);
-
- // Write EFsms Status
- Buf.writeInt32(EFSMS_STATUS_FREE);
-
- Buf.seekIncoming(-1 * (Buf.getCurrentParcelSize() - Buf.getReadAvailable()
- - 2 * Buf.UINT32_SIZE)); // Skip response_type & request_type.
- let messageStringLength = Buf.readInt32(); // In semi-octets
- let smscLength = GsmPDUHelper.readHexOctet(); // In octets, inclusive of TOA
- let pduLength = (messageStringLength / 2) - (smscLength + 1); // In octets
-
- // 1. Write PDU first.
- if (smscLength > 0) {
- Buf.seekIncoming(smscLength * Buf.PDU_HEX_OCTET_SIZE);
- }
- // Write EFsms PDU string length
- Buf.writeInt32(2 * pduLength); // In semi-octets
- if (pduLength) {
- Buf.copyIncomingToOutgoing(Buf.PDU_HEX_OCTET_SIZE * pduLength);
- }
- // Write 2 string delimitors for the total string length must be even.
- Buf.writeStringDelimiter(0);
-
- // 2. Write SMSC
- // Write EFsms SMSC string length
- Buf.writeInt32(2 * (smscLength + 1)); // Plus smscLength itself, in semi-octets
- // Write smscLength
- GsmPDUHelper.writeHexOctet(smscLength);
- // Write TOA & SMSC Address
- if (smscLength) {
- Buf.seekIncoming(-1 * (Buf.getCurrentParcelSize() - Buf.getReadAvailable()
- - 2 * Buf.UINT32_SIZE // Skip response_type, request_type.
- - 2 * Buf.PDU_HEX_OCTET_SIZE)); // Skip messageStringLength & smscLength.
- Buf.copyIncomingToOutgoing(Buf.PDU_HEX_OCTET_SIZE * smscLength);
- }
- // Write 2 string delimitors for the total string length must be even.
- Buf.writeStringDelimiter(0);
-
- Buf.sendParcel();
- },
-
- /**
- * Helper to delegate the received sms segment to RadioInterface to process.
- *
- * @param message
- * Received sms message.
- *
- * @return MOZ_FCS_WAIT_FOR_EXPLICIT_ACK
- */
- _processSmsMultipart: function(message) {
- message.rilMessageType = "sms-received";
-
- this.sendChromeMessage(message);
-
- return MOZ_FCS_WAIT_FOR_EXPLICIT_ACK;
- },
-
- /**
- * Helper for processing SMS-STATUS-REPORT PDUs.
- *
- * @param length
- * Length of SMS string in the incoming parcel.
- *
- * @return A failure cause defined in 3GPP 23.040 clause 9.2.3.22.
- */
- _processSmsStatusReport: function(length) {
- let [message, result] = this.context.GsmPDUHelper.processReceivedSms(length);
- if (!message) {
- if (DEBUG) this.context.debug("invalid SMS-STATUS-REPORT");
- return PDU_FCS_UNSPECIFIED;
- }
-
- let options = this._pendingSentSmsMap[message.messageRef];
- if (!options) {
- if (DEBUG) this.context.debug("no pending SMS-SUBMIT message");
- return PDU_FCS_OK;
- }
-
- let status = message.status;
-
- // 3GPP TS 23.040 9.2.3.15 `The MS shall interpret any reserved values as
- // "Service Rejected"(01100011) but shall store them exactly as received.`
- if ((status >= 0x80)
- || ((status >= PDU_ST_0_RESERVED_BEGIN)
- && (status < PDU_ST_0_SC_SPECIFIC_BEGIN))
- || ((status >= PDU_ST_1_RESERVED_BEGIN)
- && (status < PDU_ST_1_SC_SPECIFIC_BEGIN))
- || ((status >= PDU_ST_2_RESERVED_BEGIN)
- && (status < PDU_ST_2_SC_SPECIFIC_BEGIN))
- || ((status >= PDU_ST_3_RESERVED_BEGIN)
- && (status < PDU_ST_3_SC_SPECIFIC_BEGIN))
- ) {
- status = PDU_ST_3_SERVICE_REJECTED;
- }
-
- // Pending. Waiting for next status report.
- if ((status >>> 5) == 0x01) {
- if (DEBUG) this.context.debug("SMS-STATUS-REPORT: delivery still pending");
- return PDU_FCS_OK;
- }
-
- delete this._pendingSentSmsMap[message.messageRef];
-
- let deliveryStatus = ((status >>> 5) === 0x00)
- ? GECKO_SMS_DELIVERY_STATUS_SUCCESS
- : GECKO_SMS_DELIVERY_STATUS_ERROR;
- this.sendChromeMessage({
- rilMessageType: options.rilMessageType,
- rilMessageToken: options.rilMessageToken,
- deliveryStatus: deliveryStatus
- });
-
- return PDU_FCS_OK;
- },
-
- /**
- * Helper for processing CDMA SMS Delivery Acknowledgment Message
- *
- * @param message
- * decoded SMS Delivery ACK message from CdmaPDUHelper.
- *
- * @return A failure cause defined in 3GPP 23.040 clause 9.2.3.22.
- */
- _processCdmaSmsStatusReport: function(message) {
- let options = this._pendingSentSmsMap[message.msgId];
- if (!options) {
- if (DEBUG) this.context.debug("no pending SMS-SUBMIT message");
- return PDU_FCS_OK;
- }
-
- if (message.errorClass === 2) {
- if (DEBUG) {
- this.context.debug("SMS-STATUS-REPORT: delivery still pending, " +
- "msgStatus: " + message.msgStatus);
- }
- return PDU_FCS_OK;
- }
-
- delete this._pendingSentSmsMap[message.msgId];
-
- if (message.errorClass === -1 && message.body) {
- // Process as normal incoming SMS, if errorClass is invalid
- // but message body is available.
- return this._processSmsMultipart(message);
- }
-
- let deliveryStatus = (message.errorClass === 0)
- ? GECKO_SMS_DELIVERY_STATUS_SUCCESS
- : GECKO_SMS_DELIVERY_STATUS_ERROR;
- this.sendChromeMessage({
- rilMessageType: options.rilMessageType,
- rilMessageToken: options.rilMessageToken,
- deliveryStatus: deliveryStatus
- });
-
- return PDU_FCS_OK;
- },
-
- /**
- * Helper for processing CDMA SMS WAP Push Message
- *
- * @param message
- * decoded WAP message from CdmaPDUHelper.
- *
- * @return A failure cause defined in 3GPP 23.040 clause 9.2.3.22.
- */
- _processCdmaSmsWapPush: function(message) {
- if (!message.data) {
- if (DEBUG) this.context.debug("no data inside WAP Push message.");
- return PDU_FCS_OK;
- }
-
- // See 6.5. MAPPING OF WDP TO CDMA SMS in WAP-295-WDP.
- //
- // Field | Length (bits)
- // -----------------------------------------
- // MSG_TYPE | 8
- // TOTAL_SEGMENTS | 8
- // SEGMENT_NUMBER | 8
- // DATAGRAM | (NUM_FIELDS - 3) * 8
- let index = 0;
- if (message.data[index++] !== 0) {
- if (DEBUG) this.context.debug("Ignore a WAP Message which is not WDP.");
- return PDU_FCS_OK;
- }
-
- // 1. Originator Address in SMS-TL + Message_Id in SMS-TS are used to identify a unique WDP datagram.
- // 2. TOTAL_SEGMENTS, SEGMENT_NUMBER are used to verify that a complete
- // datagram has been received and is ready to be passed to a higher layer.
- message.header = {
- segmentRef: message.msgId,
- segmentMaxSeq: message.data[index++],
- segmentSeq: message.data[index++] + 1 // It's zero-based in CDMA WAP Push.
- };
-
- if (message.header.segmentSeq > message.header.segmentMaxSeq) {
- if (DEBUG) this.context.debug("Wrong WDP segment info.");
- return PDU_FCS_OK;
- }
-
- // Ports are only specified in 1st segment.
- if (message.header.segmentSeq == 1) {
- message.header.originatorPort = message.data[index++] << 8;
- message.header.originatorPort |= message.data[index++];
- message.header.destinationPort = message.data[index++] << 8;
- message.header.destinationPort |= message.data[index++];
- }
-
- message.data = message.data.subarray(index);
-
- return this._processSmsMultipart(message);
- },
-
- /**
- * Helper for processing sent multipart SMS.
- */
- _processSentSmsSegment: function(options) {
- // Setup attributes for sending next segment
- let next = options.segmentSeq;
- options.body = options.segments[next].body;
- options.encodedBodyLength = options.segments[next].encodedBodyLength;
- options.segmentSeq = next + 1;
-
- this.sendSMS(options);
- },
-
- /**
- * Helper for processing result of send SMS.
- *
- * @param length
- * Length of SMS string in the incoming parcel.
- * @param options
- * Sms information.
- */
- _processSmsSendResult: function(length, options) {
- if (options.errorMsg) {
- if (DEBUG) {
- this.context.debug("_processSmsSendResult: errorMsg = " +
- options.errorMsg);
- }
-
- this.sendChromeMessage({
- rilMessageType: options.rilMessageType,
- rilMessageToken: options.rilMessageToken,
- errorMsg: options.errorMsg,
- });
- return;
- }
-
- let Buf = this.context.Buf;
- options.messageRef = Buf.readInt32();
- options.ackPDU = Buf.readString();
- options.errorCode = Buf.readInt32();
-
- if ((options.segmentMaxSeq > 1)
- && (options.segmentSeq < options.segmentMaxSeq)) {
- // Not last segment
- this._processSentSmsSegment(options);
- } else {
- // Last segment sent with success.
- if (options.requestStatusReport) {
- if (DEBUG) {
- this.context.debug("waiting SMS-STATUS-REPORT for messageRef " +
- options.messageRef);
- }
- this._pendingSentSmsMap[options.messageRef] = options;
- }
-
- this.sendChromeMessage({
- rilMessageType: options.rilMessageType,
- rilMessageToken: options.rilMessageToken,
- });
- }
- },
-
- _processReceivedSmsCbPage: function(original) {
- if (original.numPages <= 1) {
- if (original.body) {
- original.fullBody = original.body;
- delete original.body;
- } else if (original.data) {
- original.fullData = original.data;
- delete original.data;
- }
- return original;
- }
-
- // Hash = <serial>:<mcc>:<mnc>:<lac>:<cid>
- let hash = original.serial + ":" + this.iccInfo.mcc + ":"
- + this.iccInfo.mnc + ":";
- switch (original.geographicalScope) {
- case CB_GSM_GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE:
- case CB_GSM_GEOGRAPHICAL_SCOPE_CELL_WIDE:
- hash += this.voiceRegistrationState.cell.gsmLocationAreaCode + ":"
- + this.voiceRegistrationState.cell.gsmCellId;
- break;
- case CB_GSM_GEOGRAPHICAL_SCOPE_LOCATION_AREA_WIDE:
- hash += this.voiceRegistrationState.cell.gsmLocationAreaCode + ":";
- break;
- default:
- hash += ":";
- break;
- }
-
- let index = original.pageIndex;
-
- let options = this._receivedSmsCbPagesMap[hash];
- if (!options) {
- options = original;
- this._receivedSmsCbPagesMap[hash] = options;
-
- options.receivedPages = 0;
- options.pages = [];
- } else if (options.pages[index]) {
- // Duplicated page?
- if (DEBUG) {
- this.context.debug("Got duplicated page no." + index +
- " of a multipage SMSCB: " + JSON.stringify(original));
- }
- return null;
- }
-
- if (options.encoding == PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
- options.pages[index] = original.data;
- delete original.data;
- } else {
- options.pages[index] = original.body;
- delete original.body;
- }
- options.receivedPages++;
- if (options.receivedPages < options.numPages) {
- if (DEBUG) {
- this.context.debug("Got page no." + index + " of a multipage SMSCB: " +
- JSON.stringify(options));
- }
- return null;
- }
-
- // Remove from map
- delete this._receivedSmsCbPagesMap[hash];
-
- // Rebuild full body
- if (options.encoding == PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
- // Uint8Array doesn't have `concat`, so we have to merge all pages by hand.
- let fullDataLen = 0;
- for (let i = 1; i <= options.numPages; i++) {
- fullDataLen += options.pages[i].length;
- }
-
- options.fullData = new Uint8Array(fullDataLen);
- for (let d= 0, i = 1; i <= options.numPages; i++) {
- let data = options.pages[i];
- for (let j = 0; j < data.length; j++) {
- options.fullData[d++] = data[j];
- }
- }
- } else {
- options.fullBody = options.pages.join("");
- }
-
- if (DEBUG) {
- this.context.debug("Got full multipage SMSCB: " + JSON.stringify(options));
- }
-
- return options;
- },
-
- _mergeCellBroadcastConfigs: function(list, from, to) {
- if (!list) {
- return [from, to];
- }
-
- for (let i = 0, f1, t1; i < list.length;) {
- f1 = list[i++];
- t1 = list[i++];
- if (to == f1) {
- // ...[from]...[to|f1]...(t1)
- list[i - 2] = from;
- return list;
- }
-
- if (to < f1) {
- // ...[from]...(to)...[f1] or ...[from]...(to)[f1]
- if (i > 2) {
- // Not the first range pair, merge three arrays.
- return list.slice(0, i - 2).concat([from, to]).concat(list.slice(i - 2));
- } else {
- return [from, to].concat(list);
- }
- }
-
- if (from > t1) {
- // ...[f1]...(t1)[from] or ...[f1]...(t1)...[from]
- continue;
- }
-
- // Have overlap or merge-able adjacency with [f1]...(t1). Replace it
- // with [min(from, f1)]...(max(to, t1)).
-
- let changed = false;
- if (from < f1) {
- // [from]...[f1]...(t1) or [from][f1]...(t1)
- // Save minimum from value.
- list[i - 2] = from;
- changed = true;
- }
-
- if (to <= t1) {
- // [from]...[to](t1) or [from]...(to|t1)
- // Can't have further merge-able adjacency. Return.
- return list;
- }
-
- // Try merging possible next adjacent range.
- let j = i;
- for (let f2, t2; j < list.length;) {
- f2 = list[j++];
- t2 = list[j++];
- if (to > t2) {
- // [from]...[f2]...[t2]...(to) or [from]...[f2]...[t2](to)
- // Merge next adjacent range again.
- continue;
- }
-
- if (to < t2) {
- if (to < f2) {
- // [from]...(to)[f2] or [from]...(to)...[f2]
- // Roll back and give up.
- j -= 2;
- } else if (to < t2) {
- // [from]...[to|f2]...(t2), or [from]...[f2]...[to](t2)
- // Merge to [from]...(t2) and give up.
- to = t2;
- }
- }
-
- break;
- }
-
- // Save maximum to value.
- list[i - 1] = to;
-
- if (j != i) {
- // Remove merged adjacent ranges.
- let ret = list.slice(0, i);
- if (j < list.length) {
- ret = ret.concat(list.slice(j));
- }
- return ret;
- }
-
- return list;
- }
-
- // Append to the end.
- list.push(from);
- list.push(to);
-
- return list;
- },
-
- _isCellBroadcastConfigReady: function() {
- if (!("MMI" in this.cellBroadcastConfigs)) {
- return false;
- }
-
- // CBMI should be ready in GSM.
- if (!this._isCdma &&
- (!("CBMI" in this.cellBroadcastConfigs) ||
- !("CBMID" in this.cellBroadcastConfigs) ||
- !("CBMIR" in this.cellBroadcastConfigs))) {
- return false;
- }
-
- return true;
- },
-
- /**
- * Merge all members of cellBroadcastConfigs into mergedCellBroadcastConfig.
- */
- _mergeAllCellBroadcastConfigs: function() {
- if (!this._isCellBroadcastConfigReady()) {
- if (DEBUG) {
- this.context.debug("cell broadcast configs not ready, waiting ...");
- }
- return;
- }
-
- // Prepare cell broadcast config. CBMI* are only used in GSM.
- let usedCellBroadcastConfigs = {MMI: this.cellBroadcastConfigs.MMI};
- if (!this._isCdma) {
- usedCellBroadcastConfigs.CBMI = this.cellBroadcastConfigs.CBMI;
- usedCellBroadcastConfigs.CBMID = this.cellBroadcastConfigs.CBMID;
- usedCellBroadcastConfigs.CBMIR = this.cellBroadcastConfigs.CBMIR;
- }
-
- if (DEBUG) {
- this.context.debug("Cell Broadcast search lists: " +
- JSON.stringify(usedCellBroadcastConfigs));
- }
-
- let list = null;
- for (let key in usedCellBroadcastConfigs) {
- let ll = usedCellBroadcastConfigs[key];
- if (ll == null) {
- continue;
- }
-
- for (let i = 0; i < ll.length; i += 2) {
- list = this._mergeCellBroadcastConfigs(list, ll[i], ll[i + 1]);
- }
- }
-
- if (DEBUG) {
- this.context.debug("Cell Broadcast search lists(merged): " +
- JSON.stringify(list));
- }
- this.mergedCellBroadcastConfig = list;
- this.updateCellBroadcastConfig();
- },
-
- /**
- * Check whether search list from settings is settable by MMI, that is,
- * whether the range is bounded in any entries of CB_NON_MMI_SETTABLE_RANGES.
- */
- _checkCellBroadcastMMISettable: function(from, to) {
- if ((to <= from) || (from >= 65536) || (from < 0)) {
- return false;
- }
-
- if (!this._isCdma) {
- // GSM not settable ranges.
- for (let i = 0, f, t; i < CB_NON_MMI_SETTABLE_RANGES.length;) {
- f = CB_NON_MMI_SETTABLE_RANGES[i++];
- t = CB_NON_MMI_SETTABLE_RANGES[i++];
- if ((from < t) && (to > f)) {
- // Have overlap.
- return false;
- }
- }
- }
-
- return true;
- },
-
- /**
- * Convert Cell Broadcast settings string into search list.
- */
- _convertCellBroadcastSearchList: function(searchListStr) {
- let parts = searchListStr && searchListStr.split(",");
- if (!parts) {
- return null;
- }
-
- let list = null;
- let result, from, to;
- for (let range of parts) {
- // Match "12" or "12-34". The result will be ["12", "12", null] or
- // ["12-34", "12", "34"].
- result = range.match(/^(\d+)(?:-(\d+))?$/);
- if (!result) {
- throw "Invalid format";
- }
-
- from = parseInt(result[1], 10);
- to = (result[2]) ? parseInt(result[2], 10) + 1 : from + 1;
- if (!this._checkCellBroadcastMMISettable(from, to)) {
- throw "Invalid range";
- }
-
- if (list == null) {
- list = [];
- }
- list.push(from);
- list.push(to);
- }
-
- return list;
- },
-
- /**
- * Handle incoming messages from the main UI thread.
- *
- * @param message
- * Object containing the message. Messages are supposed
- */
- handleChromeMessage: function(message) {
- if (DEBUG) {
- this.context.debug("Received chrome message " + JSON.stringify(message));
- }
- let method = this[message.rilMessageType];
- if (typeof method != "function") {
- if (DEBUG) {
- this.context.debug("Don't know what to do with message " +
- JSON.stringify(message));
- }
- return;
- }
- method.call(this, message);
- },
-
- /**
- * Process STK Proactive Command.
- */
- processStkProactiveCommand: function() {
- let Buf = this.context.Buf;
- let length = Buf.readInt32();
- let berTlv;
- try {
- berTlv = this.context.BerTlvHelper.decode(length / 2);
- } catch (e) {
- if (DEBUG) this.context.debug("processStkProactiveCommand : " + e);
- this.sendStkTerminalResponse({
- resultCode: STK_RESULT_CMD_DATA_NOT_UNDERSTOOD});
- return;
- }
-
- Buf.readStringDelimiter(length);
-
- let ctlvs = berTlv.value;
- let ctlv = this.context.StkProactiveCmdHelper.searchForTag(
- COMPREHENSIONTLV_TAG_COMMAND_DETAILS, ctlvs);
- if (!ctlv) {
- this.sendStkTerminalResponse({
- resultCode: STK_RESULT_CMD_DATA_NOT_UNDERSTOOD});
- throw new Error("Can't find COMMAND_DETAILS ComprehensionTlv");
- }
-
- let cmdDetails = ctlv.value;
- if (DEBUG) {
- this.context.debug("commandNumber = " + cmdDetails.commandNumber +
- " typeOfCommand = " + cmdDetails.typeOfCommand.toString(16) +
- " commandQualifier = " + cmdDetails.commandQualifier);
- }
-
- // STK_CMD_MORE_TIME need not to propagate event to chrome.
- if (cmdDetails.typeOfCommand == STK_CMD_MORE_TIME) {
- this.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_OK});
- return;
- }
-
- this.context.StkCommandParamsFactory.createParam(cmdDetails,
- ctlvs,
- (aResult) => {
- cmdDetails.options = aResult;
- cmdDetails.rilMessageType = "stkcommand";
- this.sendChromeMessage(cmdDetails);
- });
- },
-
- sendDefaultResponse: function(options) {
- if (!options.rilMessageType) {
- return;
- }
-
- this.sendChromeMessage(options);
- },
-
- /**
- * Send messages to the main thread.
- */
- sendChromeMessage: function(message) {
- message.rilMessageClientId = this.context.clientId;
- postMessage(message);
- },
-
- /**
- * Handle incoming requests from the RIL. We find the method that
- * corresponds to the request type. Incidentally, the request type
- * _is_ the method name, so that's easy.
- */
-
- handleParcel: function(request_type, length, options) {
- let method = this[request_type];
- if (typeof method == "function") {
- if (DEBUG) this.context.debug("Handling parcel as " + method.name);
- method.call(this, length, options);
- }
-
- if (this.telephonyRequestQueue.isValidRequest(request_type)) {
- this.telephonyRequestQueue.pop(request_type);
- }
- }
-};
-
-RilObject.prototype[REQUEST_GET_SIM_STATUS] = function REQUEST_GET_SIM_STATUS(length, options) {
- if (options.errorMsg) {
- return;
- }
-
- let iccStatus = {};
- let Buf = this.context.Buf;
- iccStatus.cardState = Buf.readInt32(); // CARD_STATE_*
- iccStatus.universalPINState = Buf.readInt32(); // CARD_PINSTATE_*
- iccStatus.gsmUmtsSubscriptionAppIndex = Buf.readInt32();
- iccStatus.cdmaSubscriptionAppIndex = Buf.readInt32();
- iccStatus.imsSubscriptionAppIndex = Buf.readInt32();
-
- let apps_length = Buf.readInt32();
- if (apps_length > CARD_MAX_APPS) {
- apps_length = CARD_MAX_APPS;
- }
-
- iccStatus.apps = [];
- for (let i = 0 ; i < apps_length ; i++) {
- iccStatus.apps.push({
- app_type: Buf.readInt32(), // CARD_APPTYPE_*
- app_state: Buf.readInt32(), // CARD_APPSTATE_*
- perso_substate: Buf.readInt32(), // CARD_PERSOSUBSTATE_*
- aid: Buf.readString(),
- app_label: Buf.readString(),
- pin1_replaced: Buf.readInt32(),
- pin1: Buf.readInt32(),
- pin2: Buf.readInt32()
- });
- if (RILQUIRKS_SIM_APP_STATE_EXTRA_FIELDS) {
- Buf.readInt32();
- Buf.readInt32();
- Buf.readInt32();
- Buf.readInt32();
- }
- }
-
- if (DEBUG) this.context.debug("iccStatus: " + JSON.stringify(iccStatus));
- this._processICCStatus(iccStatus);
-};
-RilObject.prototype[REQUEST_ENTER_SIM_PIN] = function REQUEST_ENTER_SIM_PIN(length, options) {
- this._processEnterAndChangeICCResponses(length, options);
-};
-RilObject.prototype[REQUEST_ENTER_SIM_PUK] = function REQUEST_ENTER_SIM_PUK(length, options) {
- this._processEnterAndChangeICCResponses(length, options);
-};
-RilObject.prototype[REQUEST_ENTER_SIM_PIN2] = function REQUEST_ENTER_SIM_PIN2(length, options) {
- this._processEnterAndChangeICCResponses(length, options);
-};
-RilObject.prototype[REQUEST_ENTER_SIM_PUK2] = function REQUEST_ENTER_SIM_PUK(length, options) {
- this._processEnterAndChangeICCResponses(length, options);
-};
-RilObject.prototype[REQUEST_CHANGE_SIM_PIN] = function REQUEST_CHANGE_SIM_PIN(length, options) {
- this._processEnterAndChangeICCResponses(length, options);
-};
-RilObject.prototype[REQUEST_CHANGE_SIM_PIN2] = function REQUEST_CHANGE_SIM_PIN2(length, options) {
- this._processEnterAndChangeICCResponses(length, options);
-};
-RilObject.prototype[REQUEST_ENTER_NETWORK_DEPERSONALIZATION_CODE] =
- function REQUEST_ENTER_NETWORK_DEPERSONALIZATION_CODE(length, options) {
- this._processEnterAndChangeICCResponses(length, options);
-};
-RilObject.prototype[REQUEST_GET_CURRENT_CALLS] = function REQUEST_GET_CURRENT_CALLS(length, options) {
- // Retry getCurrentCalls several times when error occurs.
- if (options.errorMsg) {
- if (this._getCurrentCallsRetryCount < GET_CURRENT_CALLS_RETRY_MAX) {
- this._getCurrentCallsRetryCount++;
- this.getCurrentCalls(options);
- } else {
- this.sendDefaultResponse(options);
- }
- return;
- }
-
- this._getCurrentCallsRetryCount = 0;
-
- let Buf = this.context.Buf;
- let calls_length = 0;
- // The RIL won't even send us the length integer if there are no active calls.
- // So only read this integer if the parcel actually has it.
- if (length) {
- calls_length = Buf.readInt32();
- }
-
- let calls = {};
- for (let i = 0; i < calls_length; i++) {
- let call = {};
-
- // Extra uint32 field to get correct callIndex and rest of call data for
- // call waiting feature.
- if (RILQUIRKS_EXTRA_UINT32_2ND_CALL && i > 0) {
- Buf.readInt32();
- }
-
- call.state = Buf.readInt32(); // CALL_STATE_*
- call.callIndex = Buf.readInt32(); // GSM index (1-based)
- call.toa = Buf.readInt32();
- call.isMpty = Boolean(Buf.readInt32());
- call.isMT = Boolean(Buf.readInt32());
- call.als = Buf.readInt32();
- call.isVoice = Boolean(Buf.readInt32());
- call.isVoicePrivacy = Boolean(Buf.readInt32());
- if (RILQUIRKS_CALLSTATE_EXTRA_UINT32) {
- Buf.readInt32();
- }
- call.number = Buf.readString();
- call.numberPresentation = Buf.readInt32(); // CALL_PRESENTATION_*
- call.name = Buf.readString();
- call.namePresentation = Buf.readInt32();
-
- call.uusInfo = null;
- let uusInfoPresent = Buf.readInt32();
- if (uusInfoPresent == 1) {
- call.uusInfo = {
- type: Buf.readInt32(),
- dcs: Buf.readInt32(),
- userData: null //XXX TODO byte array?!?
- };
- }
-
- if (call.isVoice) {
- calls[call.callIndex] = call;
- }
- }
-
- options.calls = calls;
- options.rilMessageType = options.rilMessageType || "currentCalls";
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_DIAL] = function REQUEST_DIAL(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_DIAL_EMERGENCY_CALL] = function REQUEST_DIAL_EMERGENCY_CALL(length, options) {
- RilObject.prototype[REQUEST_DIAL].call(this, length, options);
-};
-RilObject.prototype[REQUEST_GET_IMSI] = function REQUEST_GET_IMSI(length, options) {
- if (options.errorMsg) {
- return;
- }
-
- this.iccInfoPrivate.imsi = this.context.Buf.readString();
- if (DEBUG) {
- this.context.debug("IMSI: " + this.iccInfoPrivate.imsi);
- }
-
- options.rilMessageType = "iccimsi";
- options.imsi = this.iccInfoPrivate.imsi;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_HANGUP] = function REQUEST_HANGUP(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_HANGUP_WAITING_OR_BACKGROUND] = function REQUEST_HANGUP_WAITING_OR_BACKGROUND(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND] = function REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE] = function REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_CONFERENCE] = function REQUEST_CONFERENCE(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_UDUB] = function REQUEST_UDUB(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_LAST_CALL_FAIL_CAUSE] = function REQUEST_LAST_CALL_FAIL_CAUSE(length, options) {
- // Treat it as CALL_FAIL_ERROR_UNSPECIFIED if the request failed.
- let failCause = CALL_FAIL_ERROR_UNSPECIFIED;
-
- if (!options.errorMsg) {
- let Buf = this.context.Buf;
- let num = length ? Buf.readInt32() : 0;
-
- if (num) {
- let causeNum = Buf.readInt32();
- failCause = RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[causeNum] || failCause;
- }
- if (DEBUG) this.context.debug("Last call fail cause: " + failCause);
- }
-
- options.failCause = failCause;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SIGNAL_STRENGTH] = function REQUEST_SIGNAL_STRENGTH(length, options) {
- this._receivedNetworkInfo(NETWORK_INFO_SIGNAL);
-
- if (options.errorMsg) {
- return;
- }
-
- let Buf = this.context.Buf;
- let signal = {};
-
- signal.gsmSignalStrength = Buf.readInt32();
- signal.gsmBitErrorRate = Buf.readInt32();
- if (RILQUIRKS_SIGNAL_EXTRA_INT32) {
- Buf.readInt32();
- }
- signal.cdmaDBM = Buf.readInt32();
- signal.cdmaECIO = Buf.readInt32();
- signal.evdoDBM = Buf.readInt32();
- signal.evdoECIO = Buf.readInt32();
- signal.evdoSNR = Buf.readInt32();
-
- signal.lteSignalStrength = Buf.readInt32();
- signal.lteRSRP = Buf.readInt32();
- signal.lteRSRQ = Buf.readInt32();
- signal.lteRSSNR = Buf.readInt32();
- signal.lteCQI = Buf.readInt32();
-
- if (DEBUG) this.context.debug("signal strength: " + JSON.stringify(signal));
-
- this._processSignalStrength(signal);
-};
-RilObject.prototype[REQUEST_VOICE_REGISTRATION_STATE] = function REQUEST_VOICE_REGISTRATION_STATE(length, options) {
- this._receivedNetworkInfo(NETWORK_INFO_VOICE_REGISTRATION_STATE);
-
- if (options.errorMsg) {
- return;
- }
-
- let state = this.context.Buf.readStringList();
- if (DEBUG) this.context.debug("voice registration state: " + state);
-
- this._processVoiceRegistrationState(state);
-};
-RilObject.prototype[REQUEST_DATA_REGISTRATION_STATE] = function REQUEST_DATA_REGISTRATION_STATE(length, options) {
- this._receivedNetworkInfo(NETWORK_INFO_DATA_REGISTRATION_STATE);
-
- if (options.errorMsg) {
- return;
- }
-
- let state = this.context.Buf.readStringList();
- this._processDataRegistrationState(state);
-};
-RilObject.prototype[REQUEST_OPERATOR] = function REQUEST_OPERATOR(length, options) {
- this._receivedNetworkInfo(NETWORK_INFO_OPERATOR);
-
- if (options.errorMsg) {
- return;
- }
-
- let operatorData = this.context.Buf.readStringList();
- if (DEBUG) this.context.debug("Operator: " + operatorData);
- this._processOperator(operatorData);
-};
-RilObject.prototype[REQUEST_RADIO_POWER] = function REQUEST_RADIO_POWER(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_DTMF] = null;
-RilObject.prototype[REQUEST_SEND_SMS] = function REQUEST_SEND_SMS(length, options) {
- this._processSmsSendResult(length, options);
-};
-RilObject.prototype[REQUEST_SEND_SMS_EXPECT_MORE] = null;
-
-RilObject.prototype[REQUEST_SETUP_DATA_CALL] = function REQUEST_SETUP_DATA_CALL(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- let version = Buf.readInt32();
- // Skip number of data calls.
- Buf.readInt32();
-
- this.readDataCall(options, version);
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SIM_IO] = function REQUEST_SIM_IO(length, options) {
- if (options.errorMsg) {
- if (options.onerror) {
- options.onerror(options.errorMsg);
- }
- return;
- }
-
- let Buf = this.context.Buf;
- options.sw1 = Buf.readInt32();
- options.sw2 = Buf.readInt32();
-
- // See 3GPP TS 11.11, clause 9.4.1 for operation success results.
- if (options.sw1 !== ICC_STATUS_NORMAL_ENDING &&
- options.sw1 !== ICC_STATUS_NORMAL_ENDING_WITH_EXTRA &&
- options.sw1 !== ICC_STATUS_WITH_SIM_DATA &&
- options.sw1 !== ICC_STATUS_WITH_RESPONSE_DATA) {
- if (DEBUG) {
- this.context.debug("ICC I/O Error EF id = 0x" + options.fileId.toString(16) +
- ", command = 0x" + options.command.toString(16) +
- ", sw1 = 0x" + options.sw1.toString(16) +
- ", sw2 = 0x" + options.sw2.toString(16));
- }
- if (options.onerror) {
- // We can get fail cause from sw1/sw2 (See TS 11.11 clause 9.4.1 and
- // ISO 7816-4 clause 6). But currently no one needs this information,
- // so simply reports "GenericFailure" for now.
- options.onerror(GECKO_ERROR_GENERIC_FAILURE);
- }
- return;
- }
- this.context.ICCIOHelper.processICCIO(options);
-};
-RilObject.prototype[REQUEST_SEND_USSD] = function REQUEST_SEND_USSD(length, options) {
- if (DEBUG) {
- this.context.debug("REQUEST_SEND_USSD " + JSON.stringify(options));
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_CANCEL_USSD] = function REQUEST_CANCEL_USSD(length, options) {
- if (DEBUG) {
- this.context.debug("REQUEST_CANCEL_USSD" + JSON.stringify(options));
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_GET_CLIR] = function REQUEST_GET_CLIR(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- let bufLength = Buf.readInt32();
- if (!bufLength || bufLength < 2) {
- options.errorMsg = GECKO_ERROR_GENERIC_FAILURE;
- this.sendChromeMessage(options);
- return;
- }
-
- options.n = Buf.readInt32(); // Will be TS 27.007 +CLIR parameter 'n'.
- options.m = Buf.readInt32(); // Will be TS 27.007 +CLIR parameter 'm'.
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SET_CLIR] = function REQUEST_SET_CLIR(length, options) {
- if (options.rilMessageType == null) {
- // The request was made by ril_worker itself automatically. Don't report.
- return;
- }
-
- this.sendChromeMessage(options);
-};
-
-RilObject.prototype[REQUEST_QUERY_CALL_FORWARD_STATUS] =
- function REQUEST_QUERY_CALL_FORWARD_STATUS(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- let rulesLength = 0;
- if (length) {
- rulesLength = Buf.readInt32();
- }
- if (!rulesLength) {
- options.errorMsg = GECKO_ERROR_GENERIC_FAILURE;
- this.sendChromeMessage(options);
- return;
- }
- let rules = new Array(rulesLength);
- for (let i = 0; i < rulesLength; i++) {
- let rule = {};
- rule.active = Buf.readInt32() == 1; // CALL_FORWARD_STATUS_*
- rule.reason = Buf.readInt32(); // CALL_FORWARD_REASON_*
- rule.serviceClass = Buf.readInt32();
- rule.toa = Buf.readInt32();
- rule.number = Buf.readString();
- rule.timeSeconds = Buf.readInt32();
- rules[i] = rule;
- }
- options.rules = rules;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SET_CALL_FORWARD] =
- function REQUEST_SET_CALL_FORWARD(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_QUERY_CALL_WAITING] =
- function REQUEST_QUERY_CALL_WAITING(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- let results = Buf.readInt32List();
- let enabled = (results[0] === 1);
- options.serviceClass = enabled ? results[1] : ICC_SERVICE_CLASS_NONE;
- this.sendChromeMessage(options);
-};
-
-RilObject.prototype[REQUEST_SET_CALL_WAITING] = function REQUEST_SET_CALL_WAITING(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SMS_ACKNOWLEDGE] = null;
-RilObject.prototype[REQUEST_GET_IMEI] = null;
-RilObject.prototype[REQUEST_GET_IMEISV] = null;
-RilObject.prototype[REQUEST_ANSWER] = function REQUEST_ANSWER(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_DEACTIVATE_DATA_CALL] = function REQUEST_DEACTIVATE_DATA_CALL(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_QUERY_FACILITY_LOCK] = function REQUEST_QUERY_FACILITY_LOCK(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- if (!length) {
- options.errorMsg = GECKO_ERROR_GENERIC_FAILURE;
- this.sendChromeMessage(options);
- return;
- }
-
- // Buf.readInt32List()[0] for Call Barring is a bit vector of services.
- options.serviceClass = this.context.Buf.readInt32List()[0];
- if (options.queryServiceClass) {
- options.enabled = (options.serviceClass & options.queryServiceClass) ? true : false;
- options.serviceClass = options.queryServiceClass;
- } else {
- options.enabled = options.serviceClass ? true : false;
- }
-
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SET_FACILITY_LOCK] = function REQUEST_SET_FACILITY_LOCK(length, options) {
- options.retryCount = length ? this.context.Buf.readInt32List()[0] : -1;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_CHANGE_BARRING_PASSWORD] =
- function REQUEST_CHANGE_BARRING_PASSWORD(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_QUERY_NETWORK_SELECTION_MODE] = function REQUEST_QUERY_NETWORK_SELECTION_MODE(length, options) {
- this._receivedNetworkInfo(NETWORK_INFO_NETWORK_SELECTION_MODE);
-
- if (options.errorMsg) {
- return;
- }
-
- let mode = this.context.Buf.readInt32List();
- let selectionMode;
-
- switch (mode[0]) {
- case NETWORK_SELECTION_MODE_AUTOMATIC:
- selectionMode = GECKO_NETWORK_SELECTION_AUTOMATIC;
- break;
- case NETWORK_SELECTION_MODE_MANUAL:
- selectionMode = GECKO_NETWORK_SELECTION_MANUAL;
- break;
- default:
- selectionMode = GECKO_NETWORK_SELECTION_UNKNOWN;
- break;
- }
-
- this._updateNetworkSelectionMode(selectionMode);
-};
-RilObject.prototype[REQUEST_SET_NETWORK_SELECTION_AUTOMATIC] = function REQUEST_SET_NETWORK_SELECTION_AUTOMATIC(length, options) {
- if (!options.errorMsg) {
- this._updateNetworkSelectionMode(GECKO_NETWORK_SELECTION_AUTOMATIC);
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SET_NETWORK_SELECTION_MANUAL] = function REQUEST_SET_NETWORK_SELECTION_MANUAL(length, options) {
- if (!options.errorMsg) {
- this._updateNetworkSelectionMode(GECKO_NETWORK_SELECTION_MANUAL);
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_QUERY_AVAILABLE_NETWORKS] = function REQUEST_QUERY_AVAILABLE_NETWORKS(length, options) {
- if (!options.errorMsg) {
- options.networks = this._processNetworks();
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_DTMF_START] = function REQUEST_DTMF_START(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_DTMF_STOP] = null;
-RilObject.prototype[REQUEST_BASEBAND_VERSION] = function REQUEST_BASEBAND_VERSION(length, options) {
- if (options.errorMsg) {
- return;
- }
-
- this.basebandVersion = this.context.Buf.readString();
- if (DEBUG) this.context.debug("Baseband version: " + this.basebandVersion);
-};
-RilObject.prototype[REQUEST_SEPARATE_CONNECTION] = function REQUEST_SEPARATE_CONNECTION(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_SET_MUTE] = null;
-RilObject.prototype[REQUEST_GET_MUTE] = null;
-RilObject.prototype[REQUEST_QUERY_CLIP] = function REQUEST_QUERY_CLIP(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- let bufLength = Buf.readInt32();
- if (!bufLength) {
- options.errorMsg = GECKO_ERROR_GENERIC_FAILURE;
- this.sendChromeMessage(options);
- return;
- }
-
- options.provisioned = Buf.readInt32();
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_LAST_DATA_CALL_FAIL_CAUSE] = null;
-
-/**
- * V6:
- * # addresses - A space-delimited list of addresses with optional "/" prefix
- * length.
- * # dnses - A space-delimited list of DNS server addresses.
- * # gateways - A space-delimited list of default gateway addresses.
- *
- * V10:
- * # pcscf - A space-delimited list of Proxy Call State Control Function
- * addresses.
- */
-
-RilObject.prototype.readDataCall = function(options, version) {
- if (!options) {
- options = {};
- }
- let Buf = this.context.Buf;
- options.failCause = Buf.readInt32(); // DATACALL_FAIL_*
- options.suggestedRetryTime = Buf.readInt32();
- options.cid = Buf.readInt32().toString();
- options.active = Buf.readInt32(); // DATACALL_ACTIVE_*
- options.type = Buf.readString();
- options.ifname = Buf.readString();
- options.addresses = Buf.readString();
- options.dnses = Buf.readString();
- options.gateways = Buf.readString();
-
- if (version >= 10) {
- options.pcscf = Buf.readString();
- }
-
- if (version >= 11) {
- let mtu = Buf.readInt32();
- options.mtu = (mtu > 0) ? mtu : -1 ;
- }
-
- return options;
-};
-
-RilObject.prototype[REQUEST_DATA_CALL_LIST] = function REQUEST_DATA_CALL_LIST(length, options) {
- if (options.errorMsg) {
- if (options.rilMessageType) {
- this.sendChromeMessage(options);
- }
- return;
- }
-
- if (!options.rilMessageType) {
- // This is an unsolicited data call list changed.
- options.rilMessageType = "datacalllistchanged";
- }
-
- if (!length) {
- options.datacalls = [];
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- let version = Buf.readInt32();
- let num = Buf.readInt32();
- let datacalls = [];
- for (let i = 0; i < num; i++) {
- let datacall;
- datacall = this.readDataCall({}, version);
- datacalls.push(datacall);
- }
-
- options.datacalls = datacalls;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_RESET_RADIO] = null;
-RilObject.prototype[REQUEST_OEM_HOOK_RAW] = null;
-RilObject.prototype[REQUEST_OEM_HOOK_STRINGS] = null;
-RilObject.prototype[REQUEST_SCREEN_STATE] = null;
-RilObject.prototype[REQUEST_SET_SUPP_SVC_NOTIFICATION] = null;
-RilObject.prototype[REQUEST_WRITE_SMS_TO_SIM] = function REQUEST_WRITE_SMS_TO_SIM(length, options) {
- if (options.errorMsg) {
- // `The MS shall return a "protocol error, unspecified" error message if
- // the short message cannot be stored in the (U)SIM, and there is other
- // message storage available at the MS` ~ 3GPP TS 23.038 section 4. Here
- // we assume we always have indexed db as another storage.
- this.acknowledgeGsmSms(false, PDU_FCS_PROTOCOL_ERROR);
- } else {
- this.acknowledgeGsmSms(true, PDU_FCS_OK);
- }
-};
-RilObject.prototype[REQUEST_DELETE_SMS_ON_SIM] = null;
-RilObject.prototype[REQUEST_SET_BAND_MODE] = null;
-RilObject.prototype[REQUEST_QUERY_AVAILABLE_BAND_MODE] = null;
-RilObject.prototype[REQUEST_STK_GET_PROFILE] = null;
-RilObject.prototype[REQUEST_STK_SET_PROFILE] = null;
-RilObject.prototype[REQUEST_STK_SEND_ENVELOPE_COMMAND] = null;
-RilObject.prototype[REQUEST_STK_SEND_TERMINAL_RESPONSE] = null;
-RilObject.prototype[REQUEST_STK_HANDLE_CALL_SETUP_REQUESTED_FROM_SIM] = null;
-RilObject.prototype[REQUEST_EXPLICIT_CALL_TRANSFER] = null;
-RilObject.prototype[REQUEST_SET_PREFERRED_NETWORK_TYPE] = function REQUEST_SET_PREFERRED_NETWORK_TYPE(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_GET_PREFERRED_NETWORK_TYPE] = function REQUEST_GET_PREFERRED_NETWORK_TYPE(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- options.type = this.context.Buf.readInt32List()[0];
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_GET_NEIGHBORING_CELL_IDS] = function REQUEST_GET_NEIGHBORING_CELL_IDS(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let radioTech = this.voiceRegistrationState.radioTech;
- if (radioTech == undefined || radioTech == NETWORK_CREG_TECH_UNKNOWN) {
- options.errorMsg = "RadioTechUnavailable";
- this.sendChromeMessage(options);
- return;
- }
- if (!this._isGsmTechGroup(radioTech) || radioTech == NETWORK_CREG_TECH_LTE) {
- options.errorMsg = "UnsupportedRadioTech";
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- let neighboringCellIds = [];
- let num = Buf.readInt32();
-
- for (let i = 0; i < num; i++) {
- let cellId = {};
- cellId.networkType = GECKO_RADIO_TECH[radioTech];
- cellId.signalStrength = Buf.readInt32();
-
- let cid = Buf.readString();
- // pad cid string with leading "0"
- let length = cid.length;
- if (length > 8) {
- continue;
- }
- if (length < 8) {
- for (let j = 0; j < (8-length); j++) {
- cid = "0" + cid;
- }
- }
-
- switch (radioTech) {
- case NETWORK_CREG_TECH_GPRS:
- case NETWORK_CREG_TECH_EDGE:
- case NETWORK_CREG_TECH_GSM:
- cellId.gsmCellId = this.parseInt(cid.substring(4), -1, 16);
- cellId.gsmLocationAreaCode = this.parseInt(cid.substring(0, 4), -1, 16);
- break;
- case NETWORK_CREG_TECH_UMTS:
- case NETWORK_CREG_TECH_HSDPA:
- case NETWORK_CREG_TECH_HSUPA:
- case NETWORK_CREG_TECH_HSPA:
- case NETWORK_CREG_TECH_HSPAP:
- case NETWORK_CREG_TECH_DCHSPAP_1:
- case NETWORK_CREG_TECH_DCHSPAP_2:
- cellId.wcdmaPsc = this.parseInt(cid, -1, 16);
- break;
- }
-
- neighboringCellIds.push(cellId);
- }
-
- options.result = neighboringCellIds;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_GET_CELL_INFO_LIST] = function REQUEST_GET_CELL_INFO_LIST(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- let cellInfoList = [];
- let num = Buf.readInt32();
- for (let i = 0; i < num; i++) {
- let cellInfo = {};
- cellInfo.type = Buf.readInt32();
- cellInfo.registered = Buf.readInt32() ? true : false;
- cellInfo.timestampType = Buf.readInt32();
- cellInfo.timestamp = Buf.readInt64();
-
- switch(cellInfo.type) {
- case CELL_INFO_TYPE_GSM:
- case CELL_INFO_TYPE_WCDMA:
- cellInfo.mcc = Buf.readInt32();
- cellInfo.mnc = Buf.readInt32();
- cellInfo.lac = Buf.readInt32();
- cellInfo.cid = Buf.readInt32();
- if (cellInfo.type == CELL_INFO_TYPE_WCDMA) {
- cellInfo.psc = Buf.readInt32();
- }
- cellInfo.signalStrength = Buf.readInt32();
- cellInfo.bitErrorRate = Buf.readInt32();
- break;
- case CELL_INFO_TYPE_CDMA:
- cellInfo.networkId = Buf.readInt32();
- cellInfo.systemId = Buf.readInt32();
- cellInfo.basestationId = Buf.readInt32();
- cellInfo.longitude = Buf.readInt32();
- cellInfo.latitude = Buf.readInt32();
- cellInfo.cdmaDbm = Buf.readInt32();
- cellInfo.cdmaEcio = Buf.readInt32();
- cellInfo.evdoDbm = Buf.readInt32();
- cellInfo.evdoEcio = Buf.readInt32();
- cellInfo.evdoSnr = Buf.readInt32();
- break;
- case CELL_INFO_TYPE_LTE:
- cellInfo.mcc = Buf.readInt32();
- cellInfo.mnc = Buf.readInt32();
- cellInfo.cid = Buf.readInt32();
- cellInfo.pcid = Buf.readInt32();
- cellInfo.tac = Buf.readInt32();
- cellInfo.signalStrength = Buf.readInt32();
- cellInfo.rsrp = Buf.readInt32();
- cellInfo.rsrq = Buf.readInt32();
- cellInfo.rssnr = Buf.readInt32();
- cellInfo.cqi = Buf.readInt32();
- break;
- }
- cellInfoList.push(cellInfo);
- }
- options.result = cellInfoList;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SET_LOCATION_UPDATES] = null;
-RilObject.prototype[REQUEST_CDMA_SET_SUBSCRIPTION_SOURCE] = null;
-RilObject.prototype[REQUEST_CDMA_SET_ROAMING_PREFERENCE] = function REQUEST_CDMA_SET_ROAMING_PREFERENCE(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_CDMA_QUERY_ROAMING_PREFERENCE] = function REQUEST_CDMA_QUERY_ROAMING_PREFERENCE(length, options) {
- if (!options.errorMsg) {
- options.mode = this.context.Buf.readInt32List()[0];
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SET_TTY_MODE] = null;
-RilObject.prototype[REQUEST_QUERY_TTY_MODE] = null;
-RilObject.prototype[REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE] = function REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE] = function REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let enabled = this.context.Buf.readInt32List();
- options.enabled = enabled[0] ? true : false;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_CDMA_FLASH] = function REQUEST_CDMA_FLASH(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_CDMA_BURST_DTMF] = null;
-RilObject.prototype[REQUEST_CDMA_VALIDATE_AND_WRITE_AKEY] = null;
-RilObject.prototype[REQUEST_CDMA_SEND_SMS] = function REQUEST_CDMA_SEND_SMS(length, options) {
- this._processSmsSendResult(length, options);
-};
-RilObject.prototype[REQUEST_CDMA_SMS_ACKNOWLEDGE] = null;
-RilObject.prototype[REQUEST_GSM_GET_BROADCAST_SMS_CONFIG] = null;
-RilObject.prototype[REQUEST_GSM_SET_BROADCAST_SMS_CONFIG] = function REQUEST_GSM_SET_BROADCAST_SMS_CONFIG(length, options) {
- if (options.errorMsg) {
- return;
- }
- this.setSmsBroadcastActivation(true);
-};
-RilObject.prototype[REQUEST_GSM_SMS_BROADCAST_ACTIVATION] = null;
-RilObject.prototype[REQUEST_CDMA_GET_BROADCAST_SMS_CONFIG] = null;
-RilObject.prototype[REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG] = function REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG(length, options) {
- if (options.errorMsg) {
- return;
- }
- this.setSmsBroadcastActivation(true);
-};
-RilObject.prototype[REQUEST_CDMA_SMS_BROADCAST_ACTIVATION] = null;
-RilObject.prototype[REQUEST_CDMA_SUBSCRIPTION] = function REQUEST_CDMA_SUBSCRIPTION(length, options) {
- if (options.errorMsg) {
- return;
- }
-
- let result = this.context.Buf.readStringList();
-
- this.iccInfo.mdn = result[0];
- // The result[1] is Home SID. (Already be handled in readCDMAHome())
- // The result[2] is Home NID. (Already be handled in readCDMAHome())
- // The result[3] is MIN.
- this.iccInfo.prlVersion = parseInt(result[4], 10);
-
- this.context.ICCUtilsHelper.handleICCInfoChange();
-};
-RilObject.prototype[REQUEST_CDMA_WRITE_SMS_TO_RUIM] = null;
-RilObject.prototype[REQUEST_CDMA_DELETE_SMS_ON_RUIM] = null;
-RilObject.prototype[REQUEST_DEVICE_IDENTITY] = function REQUEST_DEVICE_IDENTITY(length, options) {
- if (options.errorMsg) {
- this.context.debug("Failed to get device identities:" + options.errorMsg);
- return;
- }
-
- let result = this.context.Buf.readStringList();
- this.deviceIdentities = {
- imei: result[0] || null,
- imeisv: result[1] || null,
- esn: result[2] || null,
- meid: result[3] || null,
- };
-
- this.sendChromeMessage({
- rilMessageType: "deviceidentitieschange",
- deviceIdentities: this.deviceIdentities
- });
-};
-RilObject.prototype[REQUEST_EXIT_EMERGENCY_CALLBACK_MODE] = function REQUEST_EXIT_EMERGENCY_CALLBACK_MODE(length, options) {
- if (options.internal) {
- return;
- }
-
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_GET_SMSC_ADDRESS] = function REQUEST_GET_SMSC_ADDRESS(length, options) {
- if (!options.rilMessageType || options.rilMessageType !== "getSmscAddress") {
- return;
- }
-
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let tosca = TOA_UNKNOWN;
- let smsc = "";
- let Buf = this.context.Buf;
- if (RILQUIRKS_SMSC_ADDRESS_FORMAT === "pdu") {
- let pduHelper = this.context.GsmPDUHelper;
- let strlen = Buf.readInt32();
- let length = pduHelper.readHexOctet();
-
- // As defined in |8.2.5.2 Destination address element| of 3GPP TS 24.011,
- // the value of length field can not exceed 11. Since the content might be
- // filled with 12 'F' when SMSC is cleared, we don't parse the TOA and
- // address fields if reported length exceeds 11 here. Instead, keep the
- // default value (TOA_UNKNOWN with an empty address) in this case.
- const MAX_LENGTH = 11
- if (length <= MAX_LENGTH) {
- tosca = pduHelper.readHexOctet();
-
- // Read and covert the decimal values back to special BCD digits defined in
- // |Called party BCD number| of 3GPP TS 24.008 (refer the following table).
- //
- // +=========+=======+=====+
- // | value | digit | hex |
- // +========================
- // | 1 0 1 0 | * | 0xA |
- // | 1 0 1 1 | # | 0xB |
- // | 1 1 0 0 | a | 0xC |
- // | 1 1 0 1 | b | 0xD |
- // | 1 1 1 0 | c | 0xE |
- // +=========+=======+=====+
- smsc = pduHelper.readSwappedNibbleBcdString(length - 1, true)
- .replace(/a/ig, "*")
- .replace(/b/ig, "#")
- .replace(/c/ig, "a")
- .replace(/d/ig, "b")
- .replace(/e/ig, "c");
-
- Buf.readStringDelimiter(strlen);
- }
- } else /* RILQUIRKS_SMSC_ADDRESS_FORMAT === "text" */ {
- let text = Buf.readString();
- let segments = text.split(",", 2);
- // Parse TOA only if it presents since some devices might omit the TOA
- // segment in the reported SMSC address. If TOA does not present, keep the
- // default value TOA_UNKNOWN.
- if (segments.length === 2) {
- tosca = this.parseInt(segments[1], TOA_UNKNOWN, 10);
- }
-
- smsc = segments[0].replace(/\"/g, "");
- }
-
- // Convert the NPI value to the corresponding index of CALLED_PARTY_BCD_NPI
- // array. If the value does not present in the array, use
- // CALLED_PARTY_BCD_NPI_ISDN.
- let npi = CALLED_PARTY_BCD_NPI.indexOf(tosca & 0xf);
- if (npi === -1) {
- npi = CALLED_PARTY_BCD_NPI.indexOf(CALLED_PARTY_BCD_NPI_ISDN);
- }
-
- // Extract TON.
- let ton = (tosca & 0x70) >> 4;
-
- // Ensure + sign if TON is international, and vice versa.
- const TON_INTERNATIONAL = (TOA_INTERNATIONAL & 0x70) >> 4;
- if (ton === TON_INTERNATIONAL && smsc.charAt(0) !== "+") {
- smsc = "+" + smsc;
- } else if (smsc.charAt(0) === "+" && ton !== TON_INTERNATIONAL) {
- if (DEBUG) {
- this.context.debug("SMSC address number begins with '+' while the TON is not international. Change TON to international.");
- }
- ton = TON_INTERNATIONAL;
- }
-
- options.smscAddress = smsc;
- options.typeOfNumber = ton;
- options.numberPlanIdentification = npi;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SET_SMSC_ADDRESS] = function REQUEST_SET_SMSC_ADDRESS(length, options) {
- if (!options.rilMessageType || options.rilMessageType !== "setSmscAddress") {
- return;
- }
-
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_REPORT_SMS_MEMORY_STATUS] = function REQUEST_REPORT_SMS_MEMORY_STATUS(length, options) {
- this.pendingToReportSmsMemoryStatus = !!options.errorMsg;
-};
-RilObject.prototype[REQUEST_REPORT_STK_SERVICE_IS_RUNNING] = null;
-RilObject.prototype[REQUEST_CDMA_GET_SUBSCRIPTION_SOURCE] = null;
-RilObject.prototype[REQUEST_ISIM_AUTHENTICATION] = null;
-RilObject.prototype[REQUEST_ACKNOWLEDGE_INCOMING_GSM_SMS_WITH_PDU] = null;
-RilObject.prototype[REQUEST_STK_SEND_ENVELOPE_WITH_STATUS] = function REQUEST_STK_SEND_ENVELOPE_WITH_STATUS(length, options) {
- if (options.errorMsg) {
- this.acknowledgeGsmSms(false, PDU_FCS_UNSPECIFIED);
- return;
- }
-
- let Buf = this.context.Buf;
- let sw1 = Buf.readInt32();
- let sw2 = Buf.readInt32();
- if ((sw1 == ICC_STATUS_SAT_BUSY) && (sw2 === 0x00)) {
- this.acknowledgeGsmSms(false, PDU_FCS_USAT_BUSY);
- return;
- }
-
- let success = ((sw1 == ICC_STATUS_NORMAL_ENDING) && (sw2 === 0x00))
- || (sw1 == ICC_STATUS_NORMAL_ENDING_WITH_EXTRA);
-
- let messageStringLength = Buf.readInt32(); // In semi-octets
- let responsePduLen = messageStringLength / 2; // In octets
- if (!responsePduLen) {
- this.acknowledgeGsmSms(success, success ? PDU_FCS_OK
- : PDU_FCS_USIM_DATA_DOWNLOAD_ERROR);
- return;
- }
-
- this.acknowledgeIncomingGsmSmsWithPDU(success, responsePduLen, options);
-};
-RilObject.prototype[REQUEST_VOICE_RADIO_TECH] = function REQUEST_VOICE_RADIO_TECH(length, options) {
- if (options.errorMsg) {
- if (DEBUG) {
- this.context.debug("Error when getting voice radio tech: " +
- options.errorMsg);
- }
- return;
- }
- let radioTech = this.context.Buf.readInt32List();
- this._processRadioTech(radioTech[0]);
-};
-RilObject.prototype[REQUEST_SET_UNSOL_CELL_INFO_LIST_RATE] = null;
-RilObject.prototype[REQUEST_SET_INITIAL_ATTACH_APN] = null;
-RilObject.prototype[REQUEST_IMS_REGISTRATION_STATE] = null;
-RilObject.prototype[REQUEST_IMS_SEND_SMS] = null;
-RilObject.prototype[REQUEST_SIM_TRANSMIT_APDU_BASIC] = null;
-RilObject.prototype[REQUEST_SIM_OPEN_CHANNEL] = function REQUEST_SIM_OPEN_CHANNEL(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- options.channel = this.context.Buf.readInt32List()[0];
- // onwards may optionally contain the select response for the open channel
- // command with one byte per integer.
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_SIM_CLOSE_CHANNEL] = function REQUEST_SIM_CLOSE_CHANNEL(length, options) {
- this.sendDefaultResponse(options);
-};
-RilObject.prototype[REQUEST_SIM_TRANSMIT_APDU_CHANNEL] = function REQUEST_SIM_TRANSMIT_APDU_CHANNEL(length, options) {
- if (options.errorMsg) {
- this.sendChromeMessage(options);
- return;
- }
-
- let Buf = this.context.Buf;
- options.sw1 = Buf.readInt32();
- options.sw2 = Buf.readInt32();
- options.simResponse = Buf.readString();
- if (DEBUG) {
- this.context.debug("Setting return values for RIL[REQUEST_SIM_TRANSMIT_APDU_CHANNEL]: [" +
- options.sw1 + "," +
- options.sw2 + ", " +
- options.simResponse + "]");
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_NV_READ_ITEM] = null;
-RilObject.prototype[REQUEST_NV_WRITE_ITEM] = null;
-RilObject.prototype[REQUEST_NV_WRITE_CDMA_PRL] = null;
-RilObject.prototype[REQUEST_NV_RESET_CONFIG] = null;
-RilObject.prototype[REQUEST_SET_UICC_SUBSCRIPTION] = function REQUEST_SET_UICC_SUBSCRIPTION(length, options) {
- // Resend data subscription after uicc subscription.
- if (this._attachDataRegistration) {
- this.setDataRegistration({attach: true});
- }
-};
-RilObject.prototype[REQUEST_ALLOW_DATA] = null;
-RilObject.prototype[REQUEST_GET_HARDWARE_CONFIG] = null;
-RilObject.prototype[REQUEST_SIM_AUTHENTICATION] = null;
-RilObject.prototype[REQUEST_GET_DC_RT_INFO] = null;
-RilObject.prototype[REQUEST_SET_DC_RT_INFO_RATE] = null;
-RilObject.prototype[REQUEST_SET_DATA_PROFILE] = null;
-RilObject.prototype[REQUEST_SHUTDOWN] = null;
-RilObject.prototype[REQUEST_SET_DATA_SUBSCRIPTION] = function REQUEST_SET_DATA_SUBSCRIPTION(length, options) {
- if (!options.rilMessageType) {
- // The request was made by ril_worker itself. Don't report.
- return;
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[REQUEST_GET_UNLOCK_RETRY_COUNT] = function REQUEST_GET_UNLOCK_RETRY_COUNT(length, options) {
- options.retryCount = length ? this.context.Buf.readInt32List()[0] : -1;
- this.sendChromeMessage(options);
-};
-RilObject.prototype[RIL_REQUEST_GPRS_ATTACH] = function RIL_REQUEST_GPRS_ATTACH(length, options) {
- if (!options.rilMessageType) {
- // The request was made by ril_worker itself. Don't report.
- return;
- }
- this.sendChromeMessage(options);
-};
-RilObject.prototype[RIL_REQUEST_GPRS_DETACH] = function RIL_REQUEST_GPRS_DETACH(length, options) {
- this.sendChromeMessage(options);
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_RADIO_STATE_CHANGED] = function UNSOLICITED_RESPONSE_RADIO_STATE_CHANGED() {
- let radioState = this.context.Buf.readInt32();
- let newState;
- switch (radioState) {
- case RADIO_STATE_UNAVAILABLE:
- newState = GECKO_RADIOSTATE_UNKNOWN;
- break;
- case RADIO_STATE_OFF:
- newState = GECKO_RADIOSTATE_DISABLED;
- break;
- default:
- newState = GECKO_RADIOSTATE_ENABLED;
- }
-
- if (DEBUG) {
- this.context.debug("Radio state changed from '" + this.radioState +
- "' to '" + newState + "'");
- }
- if (this.radioState == newState) {
- return;
- }
-
- if (radioState !== RADIO_STATE_UNAVAILABLE) {
- // Retrieve device identities once radio is available.
- this.getDeviceIdentity();
- }
-
- if (radioState == RADIO_STATE_ON) {
- // This value is defined in RIL v7, we will retrieve radio tech by another
- // request. We leave _isCdma untouched, and it will be set once we get the
- // radio technology.
- this._waitingRadioTech = true;
- this.getVoiceRadioTechnology();
- }
-
- if ((this.radioState == GECKO_RADIOSTATE_UNKNOWN ||
- this.radioState == GECKO_RADIOSTATE_DISABLED) &&
- newState == GECKO_RADIOSTATE_ENABLED) {
- // The radio became available, let's get its info.
- this.getBasebandVersion();
- this.updateCellBroadcastConfig();
- if ((RILQUIRKS_DATA_REGISTRATION_ON_DEMAND ||
- RILQUIRKS_SUBSCRIPTION_CONTROL) &&
- this._attachDataRegistration) {
- this.setDataRegistration({attach: true});
- }
-
- if (this.pendingToReportSmsMemoryStatus) {
- this._updateSmsMemoryStatus();
- }
- }
-
- this.radioState = newState;
- this.sendChromeMessage({
- rilMessageType: "radiostatechange",
- radioState: newState
- });
-
- // If the radio is up and on, so let's query the card state.
- // On older RILs only if the card is actually ready, though.
- // If _waitingRadioTech is set, we don't need to get icc status now.
- if (radioState == RADIO_STATE_UNAVAILABLE ||
- radioState == RADIO_STATE_OFF ||
- this._waitingRadioTech) {
- return;
- }
- this.getICCStatus();
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_CALL_STATE_CHANGED] = function UNSOLICITED_RESPONSE_CALL_STATE_CHANGED() {
- this.getCurrentCalls();
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_VOICE_NETWORK_STATE_CHANGED] = function UNSOLICITED_RESPONSE_VOICE_NETWORK_STATE_CHANGED() {
- if (DEBUG) {
- this.context.debug("Network state changed, re-requesting phone state and " +
- "ICC status");
- }
- this.getICCStatus();
- this.requestNetworkInfo();
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_NEW_SMS] = function UNSOLICITED_RESPONSE_NEW_SMS(length) {
- let [message, result] = this.context.GsmPDUHelper.processReceivedSms(length);
-
- if (message) {
- result = this._processSmsMultipart(message);
- }
-
- if (result == PDU_FCS_RESERVED || result == MOZ_FCS_WAIT_FOR_EXPLICIT_ACK) {
- return;
- }
-
- // Not reserved FCS values, send ACK now.
- this.acknowledgeGsmSms(result == PDU_FCS_OK, result);
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_NEW_SMS_STATUS_REPORT] = function UNSOLICITED_RESPONSE_NEW_SMS_STATUS_REPORT(length) {
- let result = this._processSmsStatusReport(length);
- this.acknowledgeGsmSms(result == PDU_FCS_OK, result);
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_NEW_SMS_ON_SIM] = function UNSOLICITED_RESPONSE_NEW_SMS_ON_SIM(length) {
- let recordNumber = this.context.Buf.readInt32List()[0];
-
- this.context.SimRecordHelper.readSMS(
- recordNumber,
- function onsuccess(message) {
- if (message && message.simStatus === 3) { //New Unread SMS
- this._processSmsMultipart(message);
- }
- }.bind(this),
- function onerror(errorMsg) {
- if (DEBUG) {
- this.context.debug("Failed to Read NEW SMS on SIM #" + recordNumber +
- ", errorMsg: " + errorMsg);
- }
- });
-};
-RilObject.prototype[UNSOLICITED_ON_USSD] = function UNSOLICITED_ON_USSD() {
- let [typeCode, message] = this.context.Buf.readStringList();
- if (DEBUG) {
- this.context.debug("On USSD. Type Code: " + typeCode + " Message: " + message);
- }
-
- this.sendChromeMessage({rilMessageType: "ussdreceived",
- message: message,
- // Per ril.h the USSD session is assumed to persist if
- // the type code is "1", otherwise the current session
- // (if any) is assumed to have terminated.
- sessionEnded: typeCode !== "1"});
-};
-RilObject.prototype[UNSOLICITED_ON_USSD_REQUEST] = null;
-RilObject.prototype[UNSOLICITED_NITZ_TIME_RECEIVED] = function UNSOLICITED_NITZ_TIME_RECEIVED() {
- let dateString = this.context.Buf.readString();
-
- // The data contained in the NITZ message is
- // in the form "yy/mm/dd,hh:mm:ss(+/-)tz,dt"
- // for example: 12/02/16,03:36:08-20,00,310410
- // See also bug 714352 - Listen for NITZ updates from rild.
-
- if (DEBUG) this.context.debug("DateTimeZone string " + dateString);
-
- let now = Date.now();
-
- let year = parseInt(dateString.substr(0, 2), 10);
- let month = parseInt(dateString.substr(3, 2), 10);
- let day = parseInt(dateString.substr(6, 2), 10);
- let hours = parseInt(dateString.substr(9, 2), 10);
- let minutes = parseInt(dateString.substr(12, 2), 10);
- let seconds = parseInt(dateString.substr(15, 2), 10);
- // Note that |tz| is in 15-min units.
- let tz = parseInt(dateString.substr(17, 3), 10);
- // Note that |dst| is in 1-hour units and is already applied in |tz|.
- let dst = parseInt(dateString.substr(21, 2), 10);
-
- let timeInMS = Date.UTC(year + PDU_TIMESTAMP_YEAR_OFFSET, month - 1, day,
- hours, minutes, seconds);
-
- if (isNaN(timeInMS)) {
- if (DEBUG) this.context.debug("NITZ failed to convert date");
- return;
- }
-
- this.sendChromeMessage({rilMessageType: "nitzTime",
- networkTimeInMS: timeInMS,
- networkTimeZoneInMinutes: -(tz * 15),
- networkDSTInMinutes: -(dst * 60),
- receiveTimeInMS: now});
-};
-
-RilObject.prototype[UNSOLICITED_SIGNAL_STRENGTH] = function UNSOLICITED_SIGNAL_STRENGTH(length) {
- this[REQUEST_SIGNAL_STRENGTH](length, {});
-};
-RilObject.prototype[UNSOLICITED_DATA_CALL_LIST_CHANGED] = function UNSOLICITED_DATA_CALL_LIST_CHANGED(length) {
- this[REQUEST_DATA_CALL_LIST](length, {});
-};
-RilObject.prototype[UNSOLICITED_SUPP_SVC_NOTIFICATION] = function UNSOLICITED_SUPP_SVC_NOTIFICATION(length) {
- let Buf = this.context.Buf;
- let info = {};
- info.notificationType = Buf.readInt32();
- info.code = Buf.readInt32();
- info.index = Buf.readInt32();
- info.type = Buf.readInt32();
- info.number = Buf.readString();
-
- this._processSuppSvcNotification(info);
-};
-
-RilObject.prototype[UNSOLICITED_STK_SESSION_END] = function UNSOLICITED_STK_SESSION_END() {
- this.sendChromeMessage({rilMessageType: "stksessionend"});
-};
-RilObject.prototype[UNSOLICITED_STK_PROACTIVE_COMMAND] = function UNSOLICITED_STK_PROACTIVE_COMMAND() {
- this.processStkProactiveCommand();
-};
-RilObject.prototype[UNSOLICITED_STK_EVENT_NOTIFY] = function UNSOLICITED_STK_EVENT_NOTIFY() {
- this.processStkProactiveCommand();
-};
-RilObject.prototype[UNSOLICITED_STK_CALL_SETUP] = null;
-RilObject.prototype[UNSOLICITED_SIM_SMS_STORAGE_FULL] = null;
-RilObject.prototype[UNSOLICITED_SIM_REFRESH] = null;
-RilObject.prototype[UNSOLICITED_CALL_RING] = function UNSOLICITED_CALL_RING() {
- let Buf = this.context.Buf;
- let info = {rilMessageType: "callRing"};
- let isCDMA = false; //XXX TODO hard-code this for now
- if (isCDMA) {
- info.isPresent = Buf.readInt32();
- info.signalType = Buf.readInt32();
- info.alertPitch = Buf.readInt32();
- info.signal = Buf.readInt32();
- }
- // At this point we don't know much other than the fact there's an incoming
- // call, but that's enough to bring up the Phone app already. We'll know
- // details once we get a call state changed notification and can then
- // dispatch DOM events etc.
- this.sendChromeMessage(info);
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_SIM_STATUS_CHANGED] = function UNSOLICITED_RESPONSE_SIM_STATUS_CHANGED() {
- this.getICCStatus();
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_CDMA_NEW_SMS] = function UNSOLICITED_RESPONSE_CDMA_NEW_SMS(length) {
- let [message, result] = this.context.CdmaPDUHelper.processReceivedSms(length);
-
- if (message) {
- if (message.teleservice === PDU_CDMA_MSG_TELESERIVCIE_ID_WAP) {
- result = this._processCdmaSmsWapPush(message);
- } else if (message.subMsgType === PDU_CDMA_MSG_TYPE_DELIVER_ACK) {
- result = this._processCdmaSmsStatusReport(message);
- } else {
- result = this._processSmsMultipart(message);
- }
- }
-
- if (result == PDU_FCS_RESERVED || result == MOZ_FCS_WAIT_FOR_EXPLICIT_ACK) {
- return;
- }
-
- // Not reserved FCS values, send ACK now.
- this.acknowledgeCdmaSms(result == PDU_FCS_OK, result);
-};
-RilObject.prototype[UNSOLICITED_RESPONSE_NEW_BROADCAST_SMS] = function UNSOLICITED_RESPONSE_NEW_BROADCAST_SMS(length) {
- let message;
- try {
- message =
- this.context.GsmPDUHelper.readCbMessage(this.context.Buf.readInt32());
-
- // "Data-Download" message is expected to be handled by the modem.
- // Ignore it here to prevent any garbage messages to be displayed.
- // See 9.4.1.2.2 Message Identifier of TS 32.041 for the range of
- // Message-identifier of the Data-Download CB messages.
- if (message.messageId >= 0x1000 && message.messageId <= 0x10FF) {
- if (DEBUG) {
- this.context.debug("Ignore a Data-Download message, messageId: " +
- message.messageId);
- }
- return;
- }
- } catch (e) {
- if (DEBUG) {
- this.context.debug("Failed to parse Cell Broadcast message: " + e);
- }
- return;
- }
-
- message = this._processReceivedSmsCbPage(message);
- if (!message) {
- return;
- }
-
- // Bug 1235697, failed to deactivate CBS in some modem.
- // Workaround it according to the settings.
- // Note: ETWS/CMAS/PWS can be received even disabled.
- // It will be displayed according to the setting in application layer.
- if (this.cellBroadcastDisabled && (
- !(message.messageId >= 0x1100 && message.messageId <= 0x1107) && // ETWS
- !(message.messageId >= 0x1112 && message.messageId <= 0x112F) && // CMAS
- !(message.messageId >= 0x1130 && message.messageId <= 0x18FF) // PWS
- )) {
- if (DEBUG) {
- this.context.debug("Ignore a CB message when disabled, messageId: " +
- message.messageId);
- }
- return;
- }
-
- message.rilMessageType = "cellbroadcast-received";
- this.sendChromeMessage(message);
-};
-RilObject.prototype[UNSOLICITED_CDMA_RUIM_SMS_STORAGE_FULL] = null;
-RilObject.prototype[UNSOLICITED_RESTRICTED_STATE_CHANGED] = null;
-RilObject.prototype[UNSOLICITED_ENTER_EMERGENCY_CALLBACK_MODE] = function UNSOLICITED_ENTER_EMERGENCY_CALLBACK_MODE() {
- this._handleChangedEmergencyCbMode(true);
-};
-RilObject.prototype[UNSOLICITED_CDMA_CALL_WAITING] = function UNSOLICITED_CDMA_CALL_WAITING(length) {
- let Buf = this.context.Buf;
- let call = {};
- call.number = Buf.readString();
- call.numberPresentation = Buf.readInt32();
- call.name = Buf.readString();
- call.namePresentation = Buf.readInt32();
- call.isPresent = Buf.readInt32();
- call.signalType = Buf.readInt32();
- call.alertPitch = Buf.readInt32();
- call.signal = Buf.readInt32();
- this.sendChromeMessage({rilMessageType: "cdmaCallWaiting",
- waitingCall: call});
-};
-RilObject.prototype[UNSOLICITED_CDMA_OTA_PROVISION_STATUS] = function UNSOLICITED_CDMA_OTA_PROVISION_STATUS() {
- let status =
- CDMA_OTA_PROVISION_STATUS_TO_GECKO[this.context.Buf.readInt32List()[0]];
- if (!status) {
- return;
- }
- this.sendChromeMessage({rilMessageType: "otastatuschange",
- status: status});
-};
-RilObject.prototype[UNSOLICITED_CDMA_INFO_REC] = function UNSOLICITED_CDMA_INFO_REC(length) {
- this.sendChromeMessage({
- rilMessageType: "cdma-info-rec-received",
- records: this.context.CdmaPDUHelper.decodeInformationRecord()
- });
-};
-RilObject.prototype[UNSOLICITED_OEM_HOOK_RAW] = null;
-RilObject.prototype[UNSOLICITED_RINGBACK_TONE] = null;
-RilObject.prototype[UNSOLICITED_RESEND_INCALL_MUTE] = null;
-RilObject.prototype[UNSOLICITED_CDMA_SUBSCRIPTION_SOURCE_CHANGED] = null;
-RilObject.prototype[UNSOLICITED_CDMA_PRL_CHANGED] = function UNSOLICITED_CDMA_PRL_CHANGED(length) {
- let version = this.context.Buf.readInt32List()[0];
- if (version !== this.iccInfo.prlVersion) {
- this.iccInfo.prlVersion = version;
- this.context.ICCUtilsHelper.handleICCInfoChange();
- }
-};
-RilObject.prototype[UNSOLICITED_EXIT_EMERGENCY_CALLBACK_MODE] = function UNSOLICITED_EXIT_EMERGENCY_CALLBACK_MODE() {
- this._handleChangedEmergencyCbMode(false);
-};
-RilObject.prototype[UNSOLICITED_RIL_CONNECTED] = function UNSOLICITED_RIL_CONNECTED(length) {
- // Prevent response id collision between UNSOLICITED_RIL_CONNECTED and
- // UNSOLICITED_VOICE_RADIO_TECH_CHANGED for Akami on gingerbread branch.
- if (!length) {
- return;
- }
-
- this.version = this.context.Buf.readInt32List()[0];
- if (DEBUG) {
- this.context.debug("Detected RIL version " + this.version);
- }
-
- this.initRILState();
- // rild might have restarted, ensure data call list.
- this.getDataCallList();
- // Always ensure that we are not in emergency callback mode when init.
- this.exitEmergencyCbMode();
- // Reset radio in the case that b2g restart (or crash).
- this.setRadioEnabled({enabled: false});
-};
-RilObject.prototype[UNSOLICITED_VOICE_RADIO_TECH_CHANGED] = function UNSOLICITED_VOICE_RADIO_TECH_CHANGED(length) {
- // This unsolicited response will be sent when the technology of a multi-tech
- // modem is changed, ex. switch between gsm and cdma.
- // TODO: We may need to do more on updating data when switching between gsm
- // and cdma mode, e.g. IMEI, ESN, iccInfo, iccType ... etc.
- // See Bug 866038.
- this._processRadioTech(this.context.Buf.readInt32List()[0]);
-};
-RilObject.prototype[UNSOLICITED_CELL_INFO_LIST] = null;
-RilObject.prototype[UNSOLICITED_RESPONSE_IMS_NETWORK_STATE_CHANGED] = null;
-RilObject.prototype[UNSOLICITED_UICC_SUBSCRIPTION_STATUS_CHANGED] = null;
-RilObject.prototype[UNSOLICITED_SRVCC_STATE_NOTIFY] = null;
-RilObject.prototype[UNSOLICITED_HARDWARE_CONFIG_CHANGED] = null;
-RilObject.prototype[UNSOLICITED_DC_RT_INFO_CHANGED] = null;
-
-/**
- * This object exposes the functionality to parse and serialize PDU strings
- *
- * A PDU is a string containing a series of hexadecimally encoded octets
- * or nibble-swapped binary-coded decimals (BCDs). It contains not only the
- * message text but information about the sender, the SMS service center,
- * timestamp, etc.
- */
-function GsmPDUHelperObject(aContext) {
- this.context = aContext;
-}
-GsmPDUHelperObject.prototype = {
- context: null,
-
- /**
- * Read one character (2 bytes) from a RIL string and decode as hex.
- *
- * @return the nibble as a number.
- */
- readHexNibble: function() {
- let nibble = this.context.Buf.readUint16();
- if (nibble >= 48 && nibble <= 57) {
- nibble -= 48; // ASCII '0'..'9'
- } else if (nibble >= 65 && nibble <= 70) {
- nibble -= 55; // ASCII 'A'..'F'
- } else if (nibble >= 97 && nibble <= 102) {
- nibble -= 87; // ASCII 'a'..'f'
- } else {
- throw "Found invalid nibble during PDU parsing: " +
- String.fromCharCode(nibble);
- }
- return nibble;
- },
-
- /**
- * Encode a nibble as one hex character in a RIL string (2 bytes).
- *
- * @param nibble
- * The nibble to encode (represented as a number)
- */
- writeHexNibble: function(nibble) {
- nibble &= 0x0f;
- if (nibble < 10) {
- nibble += 48; // ASCII '0'
- } else {
- nibble += 55; // ASCII 'A'
- }
- this.context.Buf.writeUint16(nibble);
- },
-
- /**
- * Read a hex-encoded octet (two nibbles).
- *
- * @return the octet as a number.
- */
- readHexOctet: function() {
- return (this.readHexNibble() << 4) | this.readHexNibble();
- },
-
- /**
- * Write an octet as two hex-encoded nibbles.
- *
- * @param octet
- * The octet (represented as a number) to encode.
- */
- writeHexOctet: function(octet) {
- this.writeHexNibble(octet >> 4);
- this.writeHexNibble(octet);
- },
-
- /**
- * Read an array of hex-encoded octets.
- */
- readHexOctetArray: function(length) {
- let array = new Uint8Array(length);
- for (let i = 0; i < length; i++) {
- array[i] = this.readHexOctet();
- }
- return array;
- },
-
- /**
- * Helper to write data into a temporary buffer for easier length encoding when
- * the number of octets for the length encoding is varied.
- *
- * @param writeFunction
- * Function of how the data to be written into temporary buffer.
- *
- * @return array of written octets.
- **/
- writeWithBuffer: function(writeFunction) {
- let buf = [];
- let writeHexOctet = this.writeHexOctet;
- this.writeHexOctet = function(octet) {
- buf.push(octet);
- }
-
- try {
- writeFunction();
- } catch (e) {
- if (DEBUG) {
- debug("Error when writeWithBuffer: " + e);
- }
- buf = [];
- } finally {
- this.writeHexOctet = writeHexOctet;
- }
-
- return buf;
- },
-
- /**
- * Convert an octet (number) to a BCD number.
- *
- * Any nibbles that are not in the BCD range count as 0.
- *
- * @param octet
- * The octet (a number, as returned by getOctet())
- *
- * @return the corresponding BCD number.
- */
- octetToBCD: function(octet) {
- return ((octet & 0xf0) <= 0x90) * ((octet >> 4) & 0x0f) +
- ((octet & 0x0f) <= 0x09) * (octet & 0x0f) * 10;
- },
-
- /**
- * Convert a BCD number to an octet (number)
- *
- * Only take two digits with absolute value.
- *
- * @param bcd
- *
- * @return the corresponding octet.
- */
- BCDToOctet: function(bcd) {
- bcd = Math.abs(bcd);
- return ((bcd % 10) << 4) + (Math.floor(bcd / 10) % 10);
- },
-
- /**
- * Convert a semi-octet (number) to a GSM BCD char, or return empty
- * string if invalid semiOctet and suppressException is set to true.
- *
- * @param semiOctet
- * Nibble to be converted to.
- * @param suppressException [optional]
- * Suppress exception if invalid semiOctet and suppressException is set
- * to true.
- *
- * @return GSM BCD char, or empty string.
- */
- bcdChars: "0123456789",
- semiOctetToBcdChar: function(semiOctet, suppressException) {
- if (semiOctet >= this.bcdChars.length) {
- if (suppressException) {
- return "";
- } else {
- throw new RangeError();
- }
- }
-
- return this.bcdChars.charAt(semiOctet);
- },
-
- /**
- * Convert a semi-octet (number) to a GSM extended BCD char, or return empty
- * string if invalid semiOctet and suppressException is set to true.
- *
- * @param semiOctet
- * Nibble to be converted to.
- * @param suppressException [optional]
- * Suppress exception if invalid semiOctet and suppressException is set
- * to true.
- *
- * @return GSM extended BCD char, or empty string.
- */
- extendedBcdChars: "0123456789*#,;",
- semiOctetToExtendedBcdChar: function(semiOctet, suppressException) {
- if (semiOctet >= this.extendedBcdChars.length) {
- if (suppressException) {
- return "";
- } else {
- throw new RangeError();
- }
- }
-
- return this.extendedBcdChars.charAt(semiOctet);
- },
-
- /**
- * Convert string to a GSM extended BCD string
- */
- stringToExtendedBcd: function(string) {
- return string.replace(/[^0-9*#,]/g, "")
- .replace(/\*/g, "a")
- .replace(/\#/g, "b")
- .replace(/\,/g, "c");
- },
-
- /**
- * Read a *swapped nibble* binary coded decimal (BCD)
- *
- * @param pairs
- * Number of nibble *pairs* to read.
- *
- * @return the decimal as a number.
- */
- readSwappedNibbleBcdNum: function(pairs) {
- let number = 0;
- for (let i = 0; i < pairs; i++) {
- let octet = this.readHexOctet();
- // Ignore 'ff' octets as they're often used as filler.
- if (octet == 0xff) {
- continue;
- }
- // If the first nibble is an "F" , only the second nibble is to be taken
- // into account.
- if ((octet & 0xf0) == 0xf0) {
- number *= 10;
- number += octet & 0x0f;
- continue;
- }
- number *= 100;
- number += this.octetToBCD(octet);
- }
- return number;
- },
-
- /**
- * Read a *swapped nibble* binary coded decimal (BCD) string
- *
- * @param pairs
- * Number of nibble *pairs* to read.
- * @param suppressException [optional]
- * Suppress exception if invalid semiOctet and suppressException is set
- * to true.
- *
- * @return The BCD string.
- */
- readSwappedNibbleBcdString: function(pairs, suppressException) {
- let str = "";
- for (let i = 0; i < pairs; i++) {
- let nibbleH = this.readHexNibble();
- let nibbleL = this.readHexNibble();
- if (nibbleL == 0x0F) {
- break;
- }
-
- str += this.semiOctetToBcdChar(nibbleL, suppressException);
- if (nibbleH != 0x0F) {
- str += this.semiOctetToBcdChar(nibbleH, suppressException);
- }
- }
-
- return str;
- },
-
- /**
- * Read a *swapped nibble* extended binary coded decimal (BCD) string
- *
- * @param pairs
- * Number of nibble *pairs* to read.
- * @param suppressException [optional]
- * Suppress exception if invalid semiOctet and suppressException is set
- * to true.
- *
- * @return The BCD string.
- */
- readSwappedNibbleExtendedBcdString: function(pairs, suppressException) {
- let str = "";
- for (let i = 0; i < pairs; i++) {
- let nibbleH = this.readHexNibble();
- let nibbleL = this.readHexNibble();
- if (nibbleL == 0x0F) {
- break;
- }
-
- str += this.semiOctetToExtendedBcdChar(nibbleL, suppressException);
- if (nibbleH != 0x0F) {
- str += this.semiOctetToExtendedBcdChar(nibbleH, suppressException);
- }
- }
-
- return str;
- },
-
- /**
- * Write numerical data as swapped nibble BCD.
- *
- * @param data
- * Data to write (as a string or a number)
- */
- writeSwappedNibbleBCD: function(data) {
- data = data.toString();
- if (data.length % 2) {
- data += "F";
- }
- let Buf = this.context.Buf;
- for (let i = 0; i < data.length; i += 2) {
- Buf.writeUint16(data.charCodeAt(i + 1));
- Buf.writeUint16(data.charCodeAt(i));
- }
- },
-
- /**
- * Write numerical data as swapped nibble BCD.
- * If the number of digit of data is even, add '0' at the beginning.
- *
- * @param data
- * Data to write (as a string or a number)
- */
- writeSwappedNibbleBCDNum: function(data) {
- data = data.toString();
- if (data.length % 2) {
- data = "0" + data;
- }
- let Buf = this.context.Buf;
- for (let i = 0; i < data.length; i += 2) {
- Buf.writeUint16(data.charCodeAt(i + 1));
- Buf.writeUint16(data.charCodeAt(i));
- }
- },
-
- /**
- * Read user data, convert to septets, look up relevant characters in a
- * 7-bit alphabet, and construct string.
- *
- * @param length
- * Number of septets to read (*not* octets)
- * @param paddingBits
- * Number of padding bits in the first byte of user data.
- * @param langIndex
- * Table index used for normal 7-bit encoded character lookup.
- * @param langShiftIndex
- * Table index used for escaped 7-bit encoded character lookup.
- *
- * @return a string.
- */
- readSeptetsToString: function(length, paddingBits, langIndex, langShiftIndex) {
- let ret = "";
- let byteLength = Math.ceil((length * 7 + paddingBits) / 8);
-
- /**
- * |<- last byte in header ->|
- * |<- incompleteBits ->|<- last header septet->|
- * +===7===|===6===|===5===|===4===|===3===|===2===|===1===|===0===|
- *
- * |<- 1st byte in user data ->|
- * |<- data septet 1 ->|<-paddingBits->|
- * +===7===|===6===|===5===|===4===|===3===|===2===|===1===|===0===|
- *
- * |<- 2nd byte in user data ->|
- * |<- data spetet 2 ->|<-ds1->|
- * +===7===|===6===|===5===|===4===|===3===|===2===|===1===|===0===|
- */
- let data = 0;
- let dataBits = 0;
- if (paddingBits) {
- data = this.readHexOctet() >> paddingBits;
- dataBits = 8 - paddingBits;
- --byteLength;
- }
-
- let escapeFound = false;
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[langIndex];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[langShiftIndex];
- do {
- // Read as much as fits in 32bit word
- let bytesToRead = Math.min(byteLength, dataBits ? 3 : 4);
- for (let i = 0; i < bytesToRead; i++) {
- data |= this.readHexOctet() << dataBits;
- dataBits += 8;
- --byteLength;
- }
-
- // Consume available full septets
- for (; dataBits >= 7; dataBits -= 7) {
- let septet = data & 0x7F;
- data >>>= 7;
-
- if (escapeFound) {
- escapeFound = false;
- if (septet == PDU_NL_EXTENDED_ESCAPE) {
- // According to 3GPP TS 23.038, section 6.2.1.1, NOTE 1, "On
- // receipt of this code, a receiving entity shall display a space
- // until another extensiion table is defined."
- ret += " ";
- } else if (septet == PDU_NL_RESERVED_CONTROL) {
- // According to 3GPP TS 23.038 B.2, "This code represents a control
- // character and therefore must not be used for language specific
- // characters."
- ret += " ";
- } else {
- ret += langShiftTable[septet];
- }
- } else if (septet == PDU_NL_EXTENDED_ESCAPE) {
- escapeFound = true;
-
- // <escape> is not an effective character
- --length;
- } else {
- ret += langTable[septet];
- }
- }
- } while (byteLength);
-
- if (ret.length != length) {
- /**
- * If num of effective characters does not equal to the length of read
- * string, cut the tail off. This happens when the last octet of user
- * data has following layout:
- *
- * |<- penultimate octet in user data ->|
- * |<- data septet N ->|<- dsN-1 ->|
- * +===7===|===6===|===5===|===4===|===3===|===2===|===1===|===0===|
- *
- * |<- last octet in user data ->|
- * |<- fill bits ->|<-dsN->|
- * +===7===|===6===|===5===|===4===|===3===|===2===|===1===|===0===|
- *
- * The fill bits in the last octet may happen to form a full septet and
- * be appended at the end of result string.
- */
- ret = ret.slice(0, length);
- }
- return ret;
- },
-
- writeStringAsSeptets: function(message, paddingBits, langIndex, langShiftIndex) {
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[langIndex];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[langShiftIndex];
-
- let dataBits = paddingBits;
- let data = 0;
- for (let i = 0; i < message.length; i++) {
- let c = message.charAt(i);
- let septet = langTable.indexOf(c);
- if (septet == PDU_NL_EXTENDED_ESCAPE) {
- continue;
- }
-
- if (septet >= 0) {
- data |= septet << dataBits;
- dataBits += 7;
- } else {
- septet = langShiftTable.indexOf(c);
- if (septet == -1) {
- throw new Error("'" + c + "' is not in 7 bit alphabet "
- + langIndex + ":" + langShiftIndex + "!");
- }
-
- if (septet == PDU_NL_RESERVED_CONTROL) {
- continue;
- }
-
- data |= PDU_NL_EXTENDED_ESCAPE << dataBits;
- dataBits += 7;
- data |= septet << dataBits;
- dataBits += 7;
- }
-
- for (; dataBits >= 8; dataBits -= 8) {
- this.writeHexOctet(data & 0xFF);
- data >>>= 8;
- }
- }
-
- if (dataBits !== 0) {
- this.writeHexOctet(data & 0xFF);
- }
- },
-
- writeStringAs8BitUnpacked: function(text) {
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
-
- let len = text ? text.length : 0;
- for (let i = 0; i < len; i++) {
- let c = text.charAt(i);
- let octet = langTable.indexOf(c);
-
- if (octet == -1) {
- octet = langShiftTable.indexOf(c);
- if (octet == -1) {
- // Fallback to ASCII space.
- octet = langTable.indexOf(' ');
- } else {
- this.writeHexOctet(PDU_NL_EXTENDED_ESCAPE);
- }
- }
- this.writeHexOctet(octet);
- }
- },
-
- /**
- * Read user data and decode as a UCS2 string.
- *
- * @param numOctets
- * Number of octets to be read as UCS2 string.
- *
- * @return a string.
- */
- readUCS2String: function(numOctets) {
- let str = "";
- let length = numOctets / 2;
- for (let i = 0; i < length; ++i) {
- let code = (this.readHexOctet() << 8) | this.readHexOctet();
- str += String.fromCharCode(code);
- }
-
- if (DEBUG) this.context.debug("Read UCS2 string: " + str);
-
- return str;
- },
-
- /**
- * Write user data as a UCS2 string.
- *
- * @param message
- * Message string to encode as UCS2 in hex-encoded octets.
- */
- writeUCS2String: function(message) {
- for (let i = 0; i < message.length; ++i) {
- let code = message.charCodeAt(i);
- this.writeHexOctet((code >> 8) & 0xFF);
- this.writeHexOctet(code & 0xFF);
- }
- },
-
- /**
- * Read 1 + UDHL octets and construct user data header.
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.040 9.2.3.24
- */
- readUserDataHeader: function(msg) {
- /**
- * A header object with properties contained in received message.
- * The properties set include:
- *
- * length: totoal length of the header, default 0.
- * langIndex: used locking shift table index, default
- * PDU_NL_IDENTIFIER_DEFAULT.
- * langShiftIndex: used locking shift table index, default
- * PDU_NL_IDENTIFIER_DEFAULT.
- *
- */
- let header = {
- length: 0,
- langIndex: PDU_NL_IDENTIFIER_DEFAULT,
- langShiftIndex: PDU_NL_IDENTIFIER_DEFAULT
- };
-
- header.length = this.readHexOctet();
- if (DEBUG) this.context.debug("Read UDH length: " + header.length);
-
- let dataAvailable = header.length;
- while (dataAvailable >= 2) {
- let id = this.readHexOctet();
- let length = this.readHexOctet();
- if (DEBUG) this.context.debug("Read UDH id: " + id + ", length: " + length);
-
- dataAvailable -= 2;
-
- switch (id) {
- case PDU_IEI_CONCATENATED_SHORT_MESSAGES_8BIT: {
- let ref = this.readHexOctet();
- let max = this.readHexOctet();
- let seq = this.readHexOctet();
- dataAvailable -= 3;
- if (max && seq && (seq <= max)) {
- header.segmentRef = ref;
- header.segmentMaxSeq = max;
- header.segmentSeq = seq;
- }
- break;
- }
- case PDU_IEI_APPLICATION_PORT_ADDRESSING_SCHEME_8BIT: {
- let dstp = this.readHexOctet();
- let orip = this.readHexOctet();
- dataAvailable -= 2;
- if ((dstp < PDU_APA_RESERVED_8BIT_PORTS)
- || (orip < PDU_APA_RESERVED_8BIT_PORTS)) {
- // 3GPP TS 23.040 clause 9.2.3.24.3: "A receiving entity shall
- // ignore any information element where the value of the
- // Information-Element-Data is Reserved or not supported"
- break;
- }
- header.destinationPort = dstp;
- header.originatorPort = orip;
- break;
- }
- case PDU_IEI_APPLICATION_PORT_ADDRESSING_SCHEME_16BIT: {
- let dstp = (this.readHexOctet() << 8) | this.readHexOctet();
- let orip = (this.readHexOctet() << 8) | this.readHexOctet();
- dataAvailable -= 4;
- if ((dstp >= PDU_APA_VALID_16BIT_PORTS) ||
- (orip >= PDU_APA_VALID_16BIT_PORTS)) {
- // 3GPP TS 23.040 clause 9.2.3.24.4: "A receiving entity shall
- // ignore any information element where the value of the
- // Information-Element-Data is Reserved or not supported"
- // Bug 1130292, some carriers set originatorPort to reserved port
- // numbers for wap push. We rise this as a warning in debug message
- // instead of ingoring this IEI to allow user to receive Wap Push
- // under these carriers.
- this.context.debug("Warning: Invalid port numbers [dstp, orip]: " +
- JSON.stringify([dstp, orip]));
- }
- header.destinationPort = dstp;
- header.originatorPort = orip;
- break;
- }
- case PDU_IEI_CONCATENATED_SHORT_MESSAGES_16BIT: {
- let ref = (this.readHexOctet() << 8) | this.readHexOctet();
- let max = this.readHexOctet();
- let seq = this.readHexOctet();
- dataAvailable -= 4;
- if (max && seq && (seq <= max)) {
- header.segmentRef = ref;
- header.segmentMaxSeq = max;
- header.segmentSeq = seq;
- }
- break;
- }
- case PDU_IEI_NATIONAL_LANGUAGE_SINGLE_SHIFT:
- let langShiftIndex = this.readHexOctet();
- --dataAvailable;
- if (langShiftIndex < PDU_NL_SINGLE_SHIFT_TABLES.length) {
- header.langShiftIndex = langShiftIndex;
- }
- break;
- case PDU_IEI_NATIONAL_LANGUAGE_LOCKING_SHIFT:
- let langIndex = this.readHexOctet();
- --dataAvailable;
- if (langIndex < PDU_NL_LOCKING_SHIFT_TABLES.length) {
- header.langIndex = langIndex;
- }
- break;
- case PDU_IEI_SPECIAL_SMS_MESSAGE_INDICATION:
- let msgInd = this.readHexOctet() & 0xFF;
- let msgCount = this.readHexOctet();
- dataAvailable -= 2;
-
-
- /*
- * TS 23.040 V6.8.1 Sec 9.2.3.24.2
- * bits 1 0 : basic message indication type
- * bits 4 3 2 : extended message indication type
- * bits 6 5 : Profile id
- * bit 7 : storage type
- */
- let storeType = msgInd & PDU_MWI_STORE_TYPE_BIT;
- let mwi = msg.mwi;
- if (!mwi) {
- mwi = msg.mwi = {};
- }
-
- if (storeType == PDU_MWI_STORE_TYPE_STORE) {
- // Store message because TP_UDH indicates so, note this may override
- // the setting in DCS, but that is expected
- mwi.discard = false;
- } else if (mwi.discard === undefined) {
- // storeType == PDU_MWI_STORE_TYPE_DISCARD
- // only override mwi.discard here if it hasn't already been set
- mwi.discard = true;
- }
-
- mwi.msgCount = msgCount & 0xFF;
- mwi.active = mwi.msgCount > 0;
-
- if (DEBUG) {
- this.context.debug("MWI in TP_UDH received: " + JSON.stringify(mwi));
- }
-
- break;
- default:
- if (DEBUG) {
- this.context.debug("readUserDataHeader: unsupported IEI(" + id +
- "), " + length + " bytes.");
- }
-
- // Read out unsupported data
- if (length) {
- let octets;
- if (DEBUG) octets = new Uint8Array(length);
-
- for (let i = 0; i < length; i++) {
- let octet = this.readHexOctet();
- if (DEBUG) octets[i] = octet;
- }
- dataAvailable -= length;
-
- if (DEBUG) {
- this.context.debug("readUserDataHeader: " + Array.slice(octets));
- }
- }
- break;
- }
- }
-
- if (dataAvailable !== 0) {
- throw new Error("Illegal user data header found!");
- }
-
- msg.header = header;
- },
-
- /**
- * Write out user data header.
- *
- * @param options
- * Options containing information for user data header write-out. The
- * `userDataHeaderLength` property must be correctly pre-calculated.
- */
- writeUserDataHeader: function(options) {
- this.writeHexOctet(options.userDataHeaderLength);
-
- if (options.segmentMaxSeq > 1) {
- if (options.segmentRef16Bit) {
- this.writeHexOctet(PDU_IEI_CONCATENATED_SHORT_MESSAGES_16BIT);
- this.writeHexOctet(4);
- this.writeHexOctet((options.segmentRef >> 8) & 0xFF);
- } else {
- this.writeHexOctet(PDU_IEI_CONCATENATED_SHORT_MESSAGES_8BIT);
- this.writeHexOctet(3);
- }
- this.writeHexOctet(options.segmentRef & 0xFF);
- this.writeHexOctet(options.segmentMaxSeq & 0xFF);
- this.writeHexOctet(options.segmentSeq & 0xFF);
- }
-
- if (options.dcs == PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
- if (options.langIndex != PDU_NL_IDENTIFIER_DEFAULT) {
- this.writeHexOctet(PDU_IEI_NATIONAL_LANGUAGE_LOCKING_SHIFT);
- this.writeHexOctet(1);
- this.writeHexOctet(options.langIndex);
- }
-
- if (options.langShiftIndex != PDU_NL_IDENTIFIER_DEFAULT) {
- this.writeHexOctet(PDU_IEI_NATIONAL_LANGUAGE_SINGLE_SHIFT);
- this.writeHexOctet(1);
- this.writeHexOctet(options.langShiftIndex);
- }
- }
- },
-
- /**
- * Read SM-TL Address.
- *
- * @param len
- * Length of useful semi-octets within the Address-Value field. For
- * example, the lenth of "12345" should be 5, and 4 for "1234".
- *
- * @see 3GPP TS 23.040 9.1.2.5
- */
- readAddress: function(len) {
- // Address Length
- if (!len || (len < 0)) {
- if (DEBUG) {
- this.context.debug("PDU error: invalid sender address length: " + len);
- }
- return null;
- }
- if (len % 2 == 1) {
- len += 1;
- }
- if (DEBUG) this.context.debug("PDU: Going to read address: " + len);
-
- // Type-of-Address
- let toa = this.readHexOctet();
- let addr = "";
-
- if ((toa & 0xF0) == PDU_TOA_ALPHANUMERIC) {
- addr = this.readSeptetsToString(Math.floor(len * 4 / 7), 0,
- PDU_NL_IDENTIFIER_DEFAULT , PDU_NL_IDENTIFIER_DEFAULT );
- return addr;
- }
- addr = this.readSwappedNibbleExtendedBcdString(len / 2);
- if (addr.length <= 0) {
- if (DEBUG) this.context.debug("PDU error: no number provided");
- return null;
- }
- if ((toa & 0xF0) == (PDU_TOA_INTERNATIONAL)) {
- addr = '+' + addr;
- }
-
- return addr;
- },
-
- /**
- * Read TP-Protocol-Indicator(TP-PID).
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.040 9.2.3.9
- */
- readProtocolIndicator: function(msg) {
- // `The MS shall interpret reserved, obsolete, or unsupported values as the
- // value 00000000 but shall store them exactly as received.`
- msg.pid = this.readHexOctet();
-
- msg.epid = msg.pid;
- switch (msg.epid & 0xC0) {
- case 0x40:
- // Bit 7..0 = 01xxxxxx
- switch (msg.epid) {
- case PDU_PID_SHORT_MESSAGE_TYPE_0:
- case PDU_PID_ANSI_136_R_DATA:
- case PDU_PID_USIM_DATA_DOWNLOAD:
- return;
- }
- break;
- }
-
- msg.epid = PDU_PID_DEFAULT;
- },
-
- /**
- * Read TP-Data-Coding-Scheme(TP-DCS)
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.040 9.2.3.10, 3GPP TS 23.038 4.
- */
- readDataCodingScheme: function(msg) {
- let dcs = this.readHexOctet();
- if (DEBUG) this.context.debug("PDU: read SMS dcs: " + dcs);
-
- // No message class by default.
- let messageClass = PDU_DCS_MSG_CLASS_NORMAL;
- // 7 bit is the default fallback encoding.
- let encoding = PDU_DCS_MSG_CODING_7BITS_ALPHABET;
- switch (dcs & PDU_DCS_CODING_GROUP_BITS) {
- case 0x40: // bits 7..4 = 01xx
- case 0x50:
- case 0x60:
- case 0x70:
- // Bit 5..0 are coded exactly the same as Group 00xx
- case 0x00: // bits 7..4 = 00xx
- case 0x10:
- case 0x20:
- case 0x30:
- if (dcs & 0x10) {
- messageClass = dcs & PDU_DCS_MSG_CLASS_BITS;
- }
- switch (dcs & 0x0C) {
- case 0x4:
- encoding = PDU_DCS_MSG_CODING_8BITS_ALPHABET;
- break;
- case 0x8:
- encoding = PDU_DCS_MSG_CODING_16BITS_ALPHABET;
- break;
- }
- break;
-
- case 0xE0: // bits 7..4 = 1110
- encoding = PDU_DCS_MSG_CODING_16BITS_ALPHABET;
- // Bit 3..0 are coded exactly the same as Message Waiting Indication
- // Group 1101.
- // Fall through.
- case 0xC0: // bits 7..4 = 1100
- case 0xD0: // bits 7..4 = 1101
- // Indiciates voicemail indicator set or clear
- let active = (dcs & PDU_DCS_MWI_ACTIVE_BITS) == PDU_DCS_MWI_ACTIVE_VALUE;
-
- // If TP-UDH is present, these values will be overwritten
- switch (dcs & PDU_DCS_MWI_TYPE_BITS) {
- case PDU_DCS_MWI_TYPE_VOICEMAIL:
- let mwi = msg.mwi;
- if (!mwi) {
- mwi = msg.mwi = {};
- }
-
- mwi.active = active;
- mwi.discard = (dcs & PDU_DCS_CODING_GROUP_BITS) == 0xC0;
- mwi.msgCount = active ? GECKO_VOICEMAIL_MESSAGE_COUNT_UNKNOWN : 0;
-
- if (DEBUG) {
- this.context.debug("MWI in DCS received for voicemail: " +
- JSON.stringify(mwi));
- }
- break;
- case PDU_DCS_MWI_TYPE_FAX:
- if (DEBUG) this.context.debug("MWI in DCS received for fax");
- break;
- case PDU_DCS_MWI_TYPE_EMAIL:
- if (DEBUG) this.context.debug("MWI in DCS received for email");
- break;
- default:
- if (DEBUG) this.context.debug("MWI in DCS received for \"other\"");
- break;
- }
- break;
-
- case 0xF0: // bits 7..4 = 1111
- if (dcs & 0x04) {
- encoding = PDU_DCS_MSG_CODING_8BITS_ALPHABET;
- }
- messageClass = dcs & PDU_DCS_MSG_CLASS_BITS;
- break;
-
- default:
- // Falling back to default encoding.
- break;
- }
-
- msg.dcs = dcs;
- msg.encoding = encoding;
- msg.messageClass = GECKO_SMS_MESSAGE_CLASSES[messageClass];
-
- if (DEBUG) this.context.debug("PDU: message encoding is " + encoding + " bit.");
- },
-
- /**
- * Read GSM TP-Service-Centre-Time-Stamp(TP-SCTS).
- *
- * @see 3GPP TS 23.040 9.2.3.11
- */
- readTimestamp: function() {
- let year = this.readSwappedNibbleBcdNum(1) + PDU_TIMESTAMP_YEAR_OFFSET;
- let month = this.readSwappedNibbleBcdNum(1) - 1;
- let day = this.readSwappedNibbleBcdNum(1);
- let hour = this.readSwappedNibbleBcdNum(1);
- let minute = this.readSwappedNibbleBcdNum(1);
- let second = this.readSwappedNibbleBcdNum(1);
- let timestamp = Date.UTC(year, month, day, hour, minute, second);
-
- // If the most significant bit of the least significant nibble is 1,
- // the timezone offset is negative (fourth bit from the right => 0x08):
- // localtime = UTC + tzOffset
- // therefore
- // UTC = localtime - tzOffset
- let tzOctet = this.readHexOctet();
- let tzOffset = this.octetToBCD(tzOctet & ~0x08) * 15 * 60 * 1000;
- tzOffset = (tzOctet & 0x08) ? -tzOffset : tzOffset;
- timestamp -= tzOffset;
-
- return timestamp;
- },
-
- /**
- * Write GSM TP-Service-Centre-Time-Stamp(TP-SCTS).
- *
- * @see 3GPP TS 23.040 9.2.3.11
- */
- writeTimestamp: function(date) {
- this.writeSwappedNibbleBCDNum(date.getFullYear() - PDU_TIMESTAMP_YEAR_OFFSET);
-
- // The value returned by getMonth() is an integer between 0 and 11.
- // 0 is corresponds to January, 1 to February, and so on.
- this.writeSwappedNibbleBCDNum(date.getMonth() + 1);
- this.writeSwappedNibbleBCDNum(date.getDate());
- this.writeSwappedNibbleBCDNum(date.getHours());
- this.writeSwappedNibbleBCDNum(date.getMinutes());
- this.writeSwappedNibbleBCDNum(date.getSeconds());
-
- // the value returned by getTimezoneOffset() is the difference,
- // in minutes, between UTC and local time.
- // For example, if your time zone is UTC+10 (Australian Eastern Standard Time),
- // -600 will be returned.
- // In TS 23.040 9.2.3.11, the Time Zone field of TP-SCTS indicates
- // the different between the local time and GMT.
- // And expressed in quarters of an hours. (so need to divid by 15)
- let zone = date.getTimezoneOffset() / 15;
- let octet = this.BCDToOctet(zone);
-
- // the bit3 of the Time Zone field represents the algebraic sign.
- // (0: positive, 1: negative).
- // For example, if the time zone is -0800 GMT,
- // 480 will be returned by getTimezoneOffset().
- // In this case, need to mark sign bit as 1. => 0x08
- if (zone > 0) {
- octet = octet | 0x08;
- }
- this.writeHexOctet(octet);
- },
-
- /**
- * User data can be 7 bit (default alphabet) data, 8 bit data, or 16 bit
- * (UCS2) data.
- *
- * @param msg
- * message object for output.
- * @param length
- * length of user data to read in octets.
- */
- readUserData: function(msg, length) {
- if (DEBUG) {
- this.context.debug("Reading " + length + " bytes of user data.");
- }
-
- let paddingBits = 0;
- if (msg.udhi) {
- this.readUserDataHeader(msg);
-
- if (msg.encoding == PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
- let headerBits = (msg.header.length + 1) * 8;
- let headerSeptets = Math.ceil(headerBits / 7);
-
- length -= headerSeptets;
- paddingBits = headerSeptets * 7 - headerBits;
- } else {
- length -= (msg.header.length + 1);
- }
- }
-
- if (DEBUG) {
- this.context.debug("After header, " + length + " septets left of user data");
- }
-
- msg.body = null;
- msg.data = null;
-
- if (length <= 0) {
- // No data to read.
- return;
- }
-
- switch (msg.encoding) {
- case PDU_DCS_MSG_CODING_7BITS_ALPHABET:
- // 7 bit encoding allows 140 octets, which means 160 characters
- // ((140x8) / 7 = 160 chars)
- if (length > PDU_MAX_USER_DATA_7BIT) {
- if (DEBUG) {
- this.context.debug("PDU error: user data is too long: " + length);
- }
- break;
- }
-
- let langIndex = msg.udhi ? msg.header.langIndex : PDU_NL_IDENTIFIER_DEFAULT;
- let langShiftIndex = msg.udhi ? msg.header.langShiftIndex : PDU_NL_IDENTIFIER_DEFAULT;
- msg.body = this.readSeptetsToString(length, paddingBits, langIndex,
- langShiftIndex);
- break;
- case PDU_DCS_MSG_CODING_8BITS_ALPHABET:
- msg.data = this.readHexOctetArray(length);
- break;
- case PDU_DCS_MSG_CODING_16BITS_ALPHABET:
- msg.body = this.readUCS2String(length);
- break;
- }
- },
-
- /**
- * Read extra parameters if TP-PI is set.
- *
- * @param msg
- * message object for output.
- */
- readExtraParams: function(msg) {
- // Because each PDU octet is converted to two UCS2 char2, we should always
- // get even messageStringLength in this#_processReceivedSms(). So, we'll
- // always need two delimitors at the end.
- if (this.context.Buf.getReadAvailable() <= 4) {
- return;
- }
-
- // TP-Parameter-Indicator
- let pi;
- do {
- // `The most significant bit in octet 1 and any other TP-PI octets which
- // may be added later is reserved as an extension bit which when set to a
- // 1 shall indicate that another TP-PI octet follows immediately
- // afterwards.` ~ 3GPP TS 23.040 9.2.3.27
- pi = this.readHexOctet();
- } while (pi & PDU_PI_EXTENSION);
-
- // `If the TP-UDL bit is set to "1" but the TP-DCS bit is set to "0" then
- // the receiving entity shall for TP-DCS assume a value of 0x00, i.e. the
- // 7bit default alphabet.` ~ 3GPP 23.040 9.2.3.27
- msg.dcs = 0;
- msg.encoding = PDU_DCS_MSG_CODING_7BITS_ALPHABET;
-
- // TP-Protocol-Identifier
- if (pi & PDU_PI_PROTOCOL_IDENTIFIER) {
- this.readProtocolIndicator(msg);
- }
- // TP-Data-Coding-Scheme
- if (pi & PDU_PI_DATA_CODING_SCHEME) {
- this.readDataCodingScheme(msg);
- }
- // TP-User-Data-Length
- if (pi & PDU_PI_USER_DATA_LENGTH) {
- let userDataLength = this.readHexOctet();
- this.readUserData(msg, userDataLength);
- }
- },
-
- /**
- * Read and decode a PDU-encoded message from the stream.
- *
- * TODO: add some basic sanity checks like:
- * - do we have the minimum number of chars available
- */
- readMessage: function() {
- // An empty message object. This gets filled below and then returned.
- let msg = {
- // D:DELIVER, DR:DELIVER-REPORT, S:SUBMIT, SR:SUBMIT-REPORT,
- // ST:STATUS-REPORT, C:COMMAND
- // M:Mandatory, O:Optional, X:Unavailable
- // D DR S SR ST C
- SMSC: null, // M M M M M M
- mti: null, // M M M M M M
- udhi: null, // M M O M M M
- sender: null, // M X X X X X
- recipient: null, // X X M X M M
- pid: null, // M O M O O M
- epid: null, // M O M O O M
- dcs: null, // M O M O O X
- mwi: null, // O O O O O O
- replace: false, // O O O O O O
- header: null, // M M O M M M
- body: null, // M O M O O O
- data: null, // M O M O O O
- sentTimestamp: null, // M X X X X X
- status: null, // X X X X M X
- scts: null, // X X X M M X
- dt: null, // X X X X M X
- };
-
- // SMSC info
- let smscLength = this.readHexOctet();
- if (smscLength > 0) {
- let smscTypeOfAddress = this.readHexOctet();
- // Subtract the type-of-address octet we just read from the length.
- msg.SMSC = this.readSwappedNibbleExtendedBcdString(smscLength - 1);
- if ((smscTypeOfAddress >> 4) == (PDU_TOA_INTERNATIONAL >> 4)) {
- msg.SMSC = '+' + msg.SMSC;
- }
- }
-
- // First octet of this SMS-DELIVER or SMS-SUBMIT message
- let firstOctet = this.readHexOctet();
- // Message Type Indicator
- msg.mti = firstOctet & 0x03;
- // User data header indicator
- msg.udhi = firstOctet & PDU_UDHI;
-
- switch (msg.mti) {
- case PDU_MTI_SMS_RESERVED:
- // `If an MS receives a TPDU with a "Reserved" value in the TP-MTI it
- // shall process the message as if it were an "SMS-DELIVER" but store
- // the message exactly as received.` ~ 3GPP TS 23.040 9.2.3.1
- case PDU_MTI_SMS_DELIVER:
- return this.readDeliverMessage(msg);
- case PDU_MTI_SMS_STATUS_REPORT:
- return this.readStatusReportMessage(msg);
- default:
- return null;
- }
- },
-
- /**
- * Helper for processing received SMS parcel data.
- *
- * @param length
- * Length of SMS string in the incoming parcel.
- *
- * @return Message parsed or null for invalid message.
- */
- processReceivedSms: function(length) {
- if (!length) {
- if (DEBUG) this.context.debug("Received empty SMS!");
- return [null, PDU_FCS_UNSPECIFIED];
- }
-
- let Buf = this.context.Buf;
-
- // An SMS is a string, but we won't read it as such, so let's read the
- // string length and then defer to PDU parsing helper.
- let messageStringLength = Buf.readInt32();
- if (DEBUG) this.context.debug("Got new SMS, length " + messageStringLength);
- let message = this.readMessage();
- if (DEBUG) this.context.debug("Got new SMS: " + JSON.stringify(message));
-
- // Read string delimiters. See Buf.readString().
- Buf.readStringDelimiter(length);
-
- // Determine result
- if (!message) {
- return [null, PDU_FCS_UNSPECIFIED];
- }
-
- if (message.epid == PDU_PID_SHORT_MESSAGE_TYPE_0) {
- // `A short message type 0 indicates that the ME must acknowledge receipt
- // of the short message but shall discard its contents.` ~ 3GPP TS 23.040
- // 9.2.3.9
- return [null, PDU_FCS_OK];
- }
-
- if (message.messageClass == GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_2]) {
- let RIL = this.context.RIL;
- switch (message.epid) {
- case PDU_PID_ANSI_136_R_DATA:
- case PDU_PID_USIM_DATA_DOWNLOAD:
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- if (ICCUtilsHelper.isICCServiceAvailable("DATA_DOWNLOAD_SMS_PP")) {
- // `If the service "data download via SMS Point-to-Point" is
- // allocated and activated in the (U)SIM Service Table, ... then the
- // ME shall pass the message transparently to the UICC using the
- // ENVELOPE (SMS-PP DOWNLOAD).` ~ 3GPP TS 31.111 7.1.1.1
- RIL.dataDownloadViaSMSPP(message);
-
- // `the ME shall not display the message, or alert the user of a
- // short message waiting.` ~ 3GPP TS 31.111 7.1.1.1
- return [null, PDU_FCS_RESERVED];
- }
-
- // If the service "data download via SMS-PP" is not available in the
- // (U)SIM Service Table, ..., then the ME shall store the message in
- // EFsms in accordance with TS 31.102` ~ 3GPP TS 31.111 7.1.1.1
-
- // Fall through.
- default:
- RIL.writeSmsToSIM(message);
- break;
- }
- }
-
- // TODO: Bug 739143: B2G SMS: Support SMS Storage Full event
- if ((message.messageClass != GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_0]) && !true) {
- // `When a mobile terminated message is class 0..., the MS shall display
- // the message immediately and send a ACK to the SC ..., irrespective of
- // whether there is memory available in the (U)SIM or ME.` ~ 3GPP 23.038
- // clause 4.
-
- if (message.messageClass == GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_2]) {
- // `If all the short message storage at the MS is already in use, the
- // MS shall return "memory capacity exceeded".` ~ 3GPP 23.038 clause 4.
- return [null, PDU_FCS_MEMORY_CAPACITY_EXCEEDED];
- }
-
- return [null, PDU_FCS_UNSPECIFIED];
- }
-
- return [message, PDU_FCS_OK];
- },
-
- /**
- * Read and decode a SMS-DELIVER PDU.
- *
- * @param msg
- * message object for output.
- */
- readDeliverMessage: function(msg) {
- // - Sender Address info -
- let senderAddressLength = this.readHexOctet();
- msg.sender = this.readAddress(senderAddressLength);
- // - TP-Protocolo-Identifier -
- this.readProtocolIndicator(msg);
- // - TP-Data-Coding-Scheme -
- this.readDataCodingScheme(msg);
- // - TP-Service-Center-Time-Stamp -
- msg.sentTimestamp = this.readTimestamp();
- // - TP-User-Data-Length -
- let userDataLength = this.readHexOctet();
-
- // - TP-User-Data -
- if (userDataLength > 0) {
- this.readUserData(msg, userDataLength);
- }
-
- return msg;
- },
-
- /**
- * Read and decode a SMS-STATUS-REPORT PDU.
- *
- * @param msg
- * message object for output.
- */
- readStatusReportMessage: function(msg) {
- // TP-Message-Reference
- msg.messageRef = this.readHexOctet();
- // TP-Recipient-Address
- let recipientAddressLength = this.readHexOctet();
- msg.recipient = this.readAddress(recipientAddressLength);
- // TP-Service-Centre-Time-Stamp
- msg.scts = this.readTimestamp();
- // TP-Discharge-Time
- msg.dt = this.readTimestamp();
- // TP-Status
- msg.status = this.readHexOctet();
-
- this.readExtraParams(msg);
-
- return msg;
- },
-
- /**
- * Serialize a SMS-SUBMIT PDU message and write it to the output stream.
- *
- * This method expects that a data coding scheme has been chosen already
- * and that the length of the user data payload in that encoding is known,
- * too. Both go hand in hand together anyway.
- *
- * @param address
- * String containing the address (number) of the SMS receiver
- * @param userData
- * String containing the message to be sent as user data
- * @param dcs
- * Data coding scheme. One of the PDU_DCS_MSG_CODING_*BITS_ALPHABET
- * constants.
- * @param userDataHeaderLength
- * Length of embedded user data header, in bytes. The whole header
- * size will be userDataHeaderLength + 1; 0 for no header.
- * @param encodedBodyLength
- * Length of the user data when encoded with the given DCS. For UCS2,
- * in bytes; for 7-bit, in septets.
- * @param langIndex
- * Table index used for normal 7-bit encoded character lookup.
- * @param langShiftIndex
- * Table index used for escaped 7-bit encoded character lookup.
- * @param requestStatusReport
- * Request status report.
- */
- writeMessage: function(options) {
- if (DEBUG) {
- this.context.debug("writeMessage: " + JSON.stringify(options));
- }
- let Buf = this.context.Buf;
- let address = options.number;
- let body = options.body;
- let dcs = options.dcs;
- let userDataHeaderLength = options.userDataHeaderLength;
- let encodedBodyLength = options.encodedBodyLength;
- let langIndex = options.langIndex;
- let langShiftIndex = options.langShiftIndex;
-
- // SMS-SUBMIT Format:
- //
- // PDU Type - 1 octet
- // Message Reference - 1 octet
- // DA - Destination Address - 2 to 12 octets
- // PID - Protocol Identifier - 1 octet
- // DCS - Data Coding Scheme - 1 octet
- // VP - Validity Period - 0, 1 or 7 octets
- // UDL - User Data Length - 1 octet
- // UD - User Data - 140 octets
-
- let addressFormat = PDU_TOA_ISDN; // 81
- if (address[0] == '+') {
- addressFormat = PDU_TOA_INTERNATIONAL | PDU_TOA_ISDN; // 91
- address = address.substring(1);
- }
- //TODO validity is unsupported for now
- let validity = 0;
-
- let headerOctets = (userDataHeaderLength ? userDataHeaderLength + 1 : 0);
- let paddingBits;
- let userDataLengthInSeptets;
- let userDataLengthInOctets;
- if (dcs == PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
- let headerSeptets = Math.ceil(headerOctets * 8 / 7);
- userDataLengthInSeptets = headerSeptets + encodedBodyLength;
- userDataLengthInOctets = Math.ceil(userDataLengthInSeptets * 7 / 8);
- paddingBits = headerSeptets * 7 - headerOctets * 8;
- } else {
- userDataLengthInOctets = headerOctets + encodedBodyLength;
- paddingBits = 0;
- }
-
- let pduOctetLength = 4 + // PDU Type, Message Ref, address length + format
- Math.ceil(address.length / 2) +
- 3 + // PID, DCS, UDL
- userDataLengthInOctets;
- if (validity) {
- //TODO: add more to pduOctetLength
- }
-
- // Start the string. Since octets are represented in hex, we will need
- // twice as many characters as octets.
- Buf.writeInt32(pduOctetLength * 2);
-
- // - PDU-TYPE-
-
- // +--------+----------+---------+---------+--------+---------+
- // | RP (1) | UDHI (1) | SRR (1) | VPF (2) | RD (1) | MTI (2) |
- // +--------+----------+---------+---------+--------+---------+
- // RP: 0 Reply path parameter is not set
- // 1 Reply path parameter is set
- // UDHI: 0 The UD Field contains only the short message
- // 1 The beginning of the UD field contains a header in addition
- // of the short message
- // SRR: 0 A status report is not requested
- // 1 A status report is requested
- // VPF: bit4 bit3
- // 0 0 VP field is not present
- // 0 1 Reserved
- // 1 0 VP field present an integer represented (relative)
- // 1 1 VP field present a semi-octet represented (absolute)
- // RD: Instruct the SMSC to accept(0) or reject(1) an SMS-SUBMIT
- // for a short message still held in the SMSC which has the same
- // MR and DA as a previously submitted short message from the
- // same OA
- // MTI: bit1 bit0 Message Type
- // 0 0 SMS-DELIVER (SMSC ==> MS)
- // 0 1 SMS-SUBMIT (MS ==> SMSC)
-
- // PDU type. MTI is set to SMS-SUBMIT
- let firstOctet = PDU_MTI_SMS_SUBMIT;
-
- // Status-Report-Request
- if (options.requestStatusReport) {
- firstOctet |= PDU_SRI_SRR;
- }
-
- // Validity period
- if (validity) {
- //TODO: not supported yet, OR with one of PDU_VPF_*
- }
- // User data header indicator
- if (headerOctets) {
- firstOctet |= PDU_UDHI;
- }
- this.writeHexOctet(firstOctet);
-
- // Message reference 00
- this.writeHexOctet(0x00);
-
- // - Destination Address -
- this.writeHexOctet(address.length);
- this.writeHexOctet(addressFormat);
- this.writeSwappedNibbleBCD(address);
-
- // - Protocol Identifier -
- this.writeHexOctet(0x00);
-
- // - Data coding scheme -
- // For now it assumes bits 7..4 = 1111 except for the 16 bits use case
- this.writeHexOctet(dcs);
-
- // - Validity Period -
- if (validity) {
- this.writeHexOctet(validity);
- }
-
- // - User Data -
- if (dcs == PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
- this.writeHexOctet(userDataLengthInSeptets);
- } else {
- this.writeHexOctet(userDataLengthInOctets);
- }
-
- if (headerOctets) {
- this.writeUserDataHeader(options);
- }
-
- switch (dcs) {
- case PDU_DCS_MSG_CODING_7BITS_ALPHABET:
- this.writeStringAsSeptets(body, paddingBits, langIndex, langShiftIndex);
- break;
- case PDU_DCS_MSG_CODING_8BITS_ALPHABET:
- // Unsupported.
- break;
- case PDU_DCS_MSG_CODING_16BITS_ALPHABET:
- this.writeUCS2String(body);
- break;
- }
-
- // End of the string. The string length is always even by definition, so
- // we write two \0 delimiters.
- Buf.writeUint16(0);
- Buf.writeUint16(0);
- },
-
- /**
- * Read GSM CBS message serial number.
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.041 section 9.4.1.2.1
- */
- readCbSerialNumber: function(msg) {
- let Buf = this.context.Buf;
- msg.serial = Buf.readUint8() << 8 | Buf.readUint8();
- msg.geographicalScope = (msg.serial >>> 14) & 0x03;
- msg.messageCode = (msg.serial >>> 4) & 0x03FF;
- msg.updateNumber = msg.serial & 0x0F;
- },
-
- /**
- * Read GSM CBS message message identifier.
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.041 section 9.4.1.2.2
- */
- readCbMessageIdentifier: function(msg) {
- let Buf = this.context.Buf;
- msg.messageId = Buf.readUint8() << 8 | Buf.readUint8();
- },
-
- /**
- * Read ETWS information from message identifier and serial Number
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.041 section 9.4.1.2.1 & 9.4.1.2.2
- */
- readCbEtwsInfo: function(msg) {
- if ((msg.format != CB_FORMAT_ETWS)
- && (msg.messageId >= CB_GSM_MESSAGEID_ETWS_BEGIN)
- && (msg.messageId <= CB_GSM_MESSAGEID_ETWS_END)) {
- // `In the case of transmitting CBS message for ETWS, a part of
- // Message Code can be used to command mobile terminals to activate
- // emergency user alert and message popup in order to alert the users.`
- msg.etws = {
- emergencyUserAlert: msg.messageCode & 0x0200 ? true : false,
- popup: msg.messageCode & 0x0100 ? true : false
- };
-
- let warningType = msg.messageId - CB_GSM_MESSAGEID_ETWS_BEGIN;
- if (warningType < CB_ETWS_WARNING_TYPE_NAMES.length) {
- msg.etws.warningType = warningType;
- }
- }
- },
-
- /**
- * Read CBS Data Coding Scheme.
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.038 section 5.
- */
- readCbDataCodingScheme: function(msg) {
- let dcs = this.context.Buf.readUint8();
- if (DEBUG) this.context.debug("PDU: read CBS dcs: " + dcs);
-
- let language = null, hasLanguageIndicator = false;
- // `Any reserved codings shall be assumed to be the GSM 7bit default
- // alphabet.`
- let encoding = PDU_DCS_MSG_CODING_7BITS_ALPHABET;
- let messageClass = PDU_DCS_MSG_CLASS_NORMAL;
-
- switch (dcs & PDU_DCS_CODING_GROUP_BITS) {
- case 0x00: // 0000
- language = CB_DCS_LANG_GROUP_1[dcs & 0x0F];
- break;
-
- case 0x10: // 0001
- switch (dcs & 0x0F) {
- case 0x00:
- hasLanguageIndicator = true;
- break;
- case 0x01:
- encoding = PDU_DCS_MSG_CODING_16BITS_ALPHABET;
- hasLanguageIndicator = true;
- break;
- }
- break;
-
- case 0x20: // 0010
- language = CB_DCS_LANG_GROUP_2[dcs & 0x0F];
- break;
-
- case 0x40: // 01xx
- case 0x50:
- //case 0x60: Text Compression, not supported
- //case 0x70: Text Compression, not supported
- case 0x90: // 1001
- encoding = (dcs & 0x0C);
- if (encoding == 0x0C) {
- encoding = PDU_DCS_MSG_CODING_7BITS_ALPHABET;
- }
- messageClass = (dcs & PDU_DCS_MSG_CLASS_BITS);
- break;
-
- case 0xF0:
- encoding = (dcs & 0x04) ? PDU_DCS_MSG_CODING_8BITS_ALPHABET
- : PDU_DCS_MSG_CODING_7BITS_ALPHABET;
- switch(dcs & PDU_DCS_MSG_CLASS_BITS) {
- case 0x01: messageClass = PDU_DCS_MSG_CLASS_USER_1; break;
- case 0x02: messageClass = PDU_DCS_MSG_CLASS_USER_2; break;
- case 0x03: messageClass = PDU_DCS_MSG_CLASS_3; break;
- }
- break;
-
- case 0x30: // 0011 (Reserved)
- case 0x80: // 1000 (Reserved)
- case 0xA0: // 1010..1100 (Reserved)
- case 0xB0:
- case 0xC0:
- break;
-
- default:
- throw new Error("Unsupported CBS data coding scheme: " + dcs);
- }
-
- msg.dcs = dcs;
- msg.encoding = encoding;
- msg.language = language;
- msg.messageClass = GECKO_SMS_MESSAGE_CLASSES[messageClass];
- msg.hasLanguageIndicator = hasLanguageIndicator;
- },
-
- /**
- * Read GSM CBS message page parameter.
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.041 section 9.4.1.2.4
- */
- readCbPageParameter: function(msg) {
- let octet = this.context.Buf.readUint8();
- msg.pageIndex = (octet >>> 4) & 0x0F;
- msg.numPages = octet & 0x0F;
- if (!msg.pageIndex || !msg.numPages) {
- // `If a mobile receives the code 0000 in either the first field or the
- // second field then it shall treat the CBS message exactly the same as a
- // CBS message with page parameter 0001 0001 (i.e. a single page message).`
- msg.pageIndex = msg.numPages = 1;
- }
- },
-
- /**
- * Read ETWS Primary Notification message warning type.
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.041 section 9.3.24
- */
- readCbWarningType: function(msg) {
- let Buf = this.context.Buf;
- let word = Buf.readUint8() << 8 | Buf.readUint8();
- msg.etws = {
- warningType: (word >>> 9) & 0x7F,
- popup: word & 0x80 ? true : false,
- emergencyUserAlert: word & 0x100 ? true : false
- };
- },
-
- /**
- * Read GSM CB Data
- *
- * This parameter is a copy of the 'CBS-Message-Information-Page' as sent
- * from the CBC to the BSC.
- *
- * @see 3GPP TS 23.041 section 9.4.1.2.5
- */
- readGsmCbData: function(msg, length) {
- let Buf = this.context.Buf;
- let bufAdapter = {
- context: this.context,
- readHexOctet: function() {
- return Buf.readUint8();
- }
- };
-
- msg.body = null;
- msg.data = null;
- switch (msg.encoding) {
- case PDU_DCS_MSG_CODING_7BITS_ALPHABET:
- msg.body = this.readSeptetsToString.call(bufAdapter,
- Math.floor(length * 8 / 7), 0,
- PDU_NL_IDENTIFIER_DEFAULT,
- PDU_NL_IDENTIFIER_DEFAULT);
- if (msg.hasLanguageIndicator) {
- msg.language = msg.body.substring(0, 2);
- msg.body = msg.body.substring(3);
- }
- break;
-
- case PDU_DCS_MSG_CODING_8BITS_ALPHABET:
- msg.data = Buf.readUint8Array(length);
- break;
-
- case PDU_DCS_MSG_CODING_16BITS_ALPHABET:
- if (msg.hasLanguageIndicator) {
- msg.language = this.readSeptetsToString.call(bufAdapter, 2, 0,
- PDU_NL_IDENTIFIER_DEFAULT,
- PDU_NL_IDENTIFIER_DEFAULT);
- length -= 2;
- }
- msg.body = this.readUCS2String.call(bufAdapter, length);
- break;
- }
-
- if (msg.data || !msg.body) {
- return;
- }
-
- // According to 9.3.19 CBS-Message-Information-Page in TS 23.041:
- // "
- // This parameter is of a fixed length of 82 octets and carries up to and
- // including 82 octets of user information. Where the user information is
- // less than 82 octets, the remaining octets must be filled with padding.
- // "
- // According to 6.2.1.1 GSM 7 bit Default Alphabet and 6.2.3 UCS2 in
- // TS 23.038, the padding character is <CR>.
- for (let i = msg.body.length - 1; i >= 0; i--) {
- if (msg.body.charAt(i) !== '\r') {
- msg.body = msg.body.substring(0, i + 1);
- break;
- }
- }
- },
-
- /**
- * Read UMTS CB Data
- *
- * Octet Number(s) Parameter
- * 1 Number-of-Pages
- * 2 - 83 CBS-Message-Information-Page 1
- * 84 CBS-Message-Information-Length 1
- * ...
- * CBS-Message-Information-Page n
- * CBS-Message-Information-Length n
- *
- * @see 3GPP TS 23.041 section 9.4.2.2.5
- */
- readUmtsCbData: function(msg) {
- let Buf = this.context.Buf;
- let numOfPages = Buf.readUint8();
- if (numOfPages < 0 || numOfPages > 15) {
- throw new Error("Invalid numOfPages: " + numOfPages);
- }
-
- let bufAdapter = {
- context: this.context,
- readHexOctet: function() {
- return Buf.readUint8();
- }
- };
-
- let removePaddingCharactors = function (text) {
- for (let i = text.length - 1; i >= 0; i--) {
- if (text.charAt(i) !== '\r') {
- return text.substring(0, i + 1);
- }
- }
- return text;
- };
-
- let totalLength = 0, length, pageLengths = [];
- for (let i = 0; i < numOfPages; i++) {
- Buf.seekIncoming(CB_MSG_PAGE_INFO_SIZE);
- length = Buf.readUint8();
- totalLength += length;
- pageLengths.push(length);
- }
-
- // Seek back to beginning of CB Data.
- Buf.seekIncoming(-numOfPages * (CB_MSG_PAGE_INFO_SIZE + 1));
-
- switch (msg.encoding) {
- case PDU_DCS_MSG_CODING_7BITS_ALPHABET: {
- let body;
- msg.body = "";
- for (let i = 0; i < numOfPages; i++) {
- body = this.readSeptetsToString.call(bufAdapter,
- Math.floor(pageLengths[i] * 8 / 7),
- 0,
- PDU_NL_IDENTIFIER_DEFAULT,
- PDU_NL_IDENTIFIER_DEFAULT);
- if (msg.hasLanguageIndicator) {
- if (!msg.language) {
- msg.language = body.substring(0, 2);
- }
- body = body.substring(3);
- }
-
- msg.body += removePaddingCharactors(body);
-
- // Skip padding octets
- Buf.seekIncoming(CB_MSG_PAGE_INFO_SIZE - pageLengths[i]);
- // Read the octet of CBS-Message-Information-Length
- Buf.readUint8();
- }
-
- break;
- }
-
- case PDU_DCS_MSG_CODING_8BITS_ALPHABET: {
- msg.data = new Uint8Array(totalLength);
- for (let i = 0, j = 0; i < numOfPages; i++) {
- for (let pageLength = pageLengths[i]; pageLength > 0; pageLength--) {
- msg.data[j++] = Buf.readUint8();
- }
-
- // Skip padding octets
- Buf.seekIncoming(CB_MSG_PAGE_INFO_SIZE - pageLengths[i]);
- // Read the octet of CBS-Message-Information-Length
- Buf.readUint8();
- }
-
- break;
- }
-
- case PDU_DCS_MSG_CODING_16BITS_ALPHABET: {
- msg.body = "";
- for (let i = 0; i < numOfPages; i++) {
- let pageLength = pageLengths[i];
- if (msg.hasLanguageIndicator) {
- if (!msg.language) {
- msg.language = this.readSeptetsToString.call(bufAdapter,
- 2,
- 0,
- PDU_NL_IDENTIFIER_DEFAULT,
- PDU_NL_IDENTIFIER_DEFAULT);
- } else {
- Buf.readUint16();
- }
-
- pageLength -= 2;
- }
-
- msg.body += removePaddingCharactors(
- this.readUCS2String.call(bufAdapter, pageLength));
-
- // Skip padding octets
- Buf.seekIncoming(CB_MSG_PAGE_INFO_SIZE - pageLengths[i]);
- // Read the octet of CBS-Message-Information-Length
- Buf.readUint8();
- }
-
- break;
- }
- }
- },
-
- /**
- * Read Cell GSM/ETWS/UMTS Broadcast Message.
- *
- * @param pduLength
- * total length of the incoming PDU in octets.
- */
- readCbMessage: function(pduLength) {
- // Validity GSM ETWS UMTS
- let msg = {
- // Internally used in ril_worker:
- serial: null, // O O O
- updateNumber: null, // O O O
- format: null, // O O O
- dcs: 0x0F, // O X O
- encoding: PDU_DCS_MSG_CODING_7BITS_ALPHABET, // O X O
- hasLanguageIndicator: false, // O X O
- data: null, // O X O
- body: null, // O X O
- pageIndex: 1, // O X X
- numPages: 1, // O X X
-
- // DOM attributes:
- geographicalScope: null, // O O O
- messageCode: null, // O O O
- messageId: null, // O O O
- language: null, // O X O
- fullBody: null, // O X O
- fullData: null, // O X O
- messageClass: GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL], // O x O
- etws: null // ? O ?
- /*{
- warningType: null, // X O X
- popup: false, // X O X
- emergencyUserAlert: false, // X O X
- }*/
- };
-
- if (pduLength <= CB_MESSAGE_SIZE_ETWS) {
- msg.format = CB_FORMAT_ETWS;
- return this.readEtwsCbMessage(msg);
- }
-
- if (pduLength <= CB_MESSAGE_SIZE_GSM) {
- msg.format = CB_FORMAT_GSM;
- return this.readGsmCbMessage(msg, pduLength);
- }
-
- if (pduLength >= CB_MESSAGE_SIZE_UMTS_MIN &&
- pduLength <= CB_MESSAGE_SIZE_UMTS_MAX) {
- msg.format = CB_FORMAT_UMTS;
- return this.readUmtsCbMessage(msg);
- }
-
- throw new Error("Invalid PDU Length: " + pduLength);
- },
-
- /**
- * Read UMTS CBS Message.
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.041 section 9.4.2
- * @see 3GPP TS 25.324 section 10.2
- */
- readUmtsCbMessage: function(msg) {
- let Buf = this.context.Buf;
- let type = Buf.readUint8();
- if (type != CB_UMTS_MESSAGE_TYPE_CBS) {
- throw new Error("Unsupported UMTS Cell Broadcast message type: " + type);
- }
-
- this.readCbMessageIdentifier(msg);
- this.readCbSerialNumber(msg);
- this.readCbEtwsInfo(msg);
- this.readCbDataCodingScheme(msg);
- this.readUmtsCbData(msg);
-
- return msg;
- },
-
- /**
- * Read GSM Cell Broadcast Message.
- *
- * @param msg
- * message object for output.
- * @param pduLength
- * total length of the incomint PDU in octets.
- *
- * @see 3GPP TS 23.041 clause 9.4.1.2
- */
- readGsmCbMessage: function(msg, pduLength) {
- this.readCbSerialNumber(msg);
- this.readCbMessageIdentifier(msg);
- this.readCbEtwsInfo(msg);
- this.readCbDataCodingScheme(msg);
- this.readCbPageParameter(msg);
-
- // GSM CB message header takes 6 octets.
- this.readGsmCbData(msg, pduLength - 6);
-
- return msg;
- },
-
- /**
- * Read ETWS Primary Notification Message.
- *
- * @param msg
- * message object for output.
- *
- * @see 3GPP TS 23.041 clause 9.4.1.3
- */
- readEtwsCbMessage: function(msg) {
- this.readCbSerialNumber(msg);
- this.readCbMessageIdentifier(msg);
- this.readCbWarningType(msg);
-
- // Octet 7..56 is Warning Security Information. However, according to
- // section 9.4.1.3.6, `The UE shall ignore this parameter.` So we just skip
- // processing it here.
-
- return msg;
- },
-
- /**
- * Read network name.
- *
- * @param len Length of the information element.
- * @return
- * {
- * networkName: network name.
- * shouldIncludeCi: Should Country's initials included in text string.
- * }
- * @see TS 24.008 clause 10.5.3.5a.
- */
- readNetworkName: function(len) {
- // According to TS 24.008 Sec. 10.5.3.5a, the first octet is:
- // bit 8: must be 1.
- // bit 5-7: Text encoding.
- // 000 - GSM default alphabet.
- // 001 - UCS2 (16 bit).
- // else - reserved.
- // bit 4: MS should add the letters for Country's Initials and a space
- // to the text string if this bit is true.
- // bit 1-3: number of spare bits in last octet.
-
- let codingInfo = this.readHexOctet();
- if (!(codingInfo & 0x80)) {
- return null;
- }
-
- let textEncoding = (codingInfo & 0x70) >> 4;
- let shouldIncludeCountryInitials = !!(codingInfo & 0x08);
- let spareBits = codingInfo & 0x07;
- let resultString;
-
- switch (textEncoding) {
- case 0:
- // GSM Default alphabet.
- resultString = this.readSeptetsToString(
- Math.floor(((len - 1) * 8 - spareBits) / 7), 0,
- PDU_NL_IDENTIFIER_DEFAULT,
- PDU_NL_IDENTIFIER_DEFAULT);
- break;
- case 1:
- // UCS2 encoded.
- resultString = this.context.ICCPDUHelper.readAlphaIdentifier(len - 1);
- break;
- default:
- // Not an available text coding.
- return null;
- }
-
- // TODO - Bug 820286: According to shouldIncludeCountryInitials, add
- // country initials to the resulting string.
- return resultString;
- }
-};
-
-/**
- * Provide buffer with bitwise read/write function so make encoding/decoding easier.
- */
-function BitBufferHelperObject(/* unused */aContext) {
- this.readBuffer = [];
- this.writeBuffer = [];
-}
-BitBufferHelperObject.prototype = {
- readCache: 0,
- readCacheSize: 0,
- readBuffer: null,
- readIndex: 0,
- writeCache: 0,
- writeCacheSize: 0,
- writeBuffer: null,
-
- // Max length is 32 because we use integer as read/write cache.
- // All read/write functions are implemented based on bitwise operation.
- readBits: function(length) {
- if (length <= 0 || length > 32) {
- return null;
- }
-
- if (length > this.readCacheSize) {
- let bytesToRead = Math.ceil((length - this.readCacheSize) / 8);
- for(let i = 0; i < bytesToRead; i++) {
- this.readCache = (this.readCache << 8) | (this.readBuffer[this.readIndex++] & 0xFF);
- this.readCacheSize += 8;
- }
- }
-
- let bitOffset = (this.readCacheSize - length),
- resultMask = (1 << length) - 1,
- result = 0;
-
- result = (this.readCache >> bitOffset) & resultMask;
- this.readCacheSize -= length;
-
- return result;
- },
-
- backwardReadPilot: function(length) {
- if (length <= 0) {
- return;
- }
-
- // Zero-based position.
- let bitIndexToRead = this.readIndex * 8 - this.readCacheSize - length;
-
- if (bitIndexToRead < 0) {
- return;
- }
-
- // Update readIndex, readCache, readCacheSize accordingly.
- let readBits = bitIndexToRead % 8;
- this.readIndex = Math.floor(bitIndexToRead / 8) + ((readBits) ? 1 : 0);
- this.readCache = (readBits) ? this.readBuffer[this.readIndex - 1] : 0;
- this.readCacheSize = (readBits) ? (8 - readBits) : 0;
- },
-
- writeBits: function(value, length) {
- if (length <= 0 || length > 32) {
- return;
- }
-
- let totalLength = length + this.writeCacheSize;
-
- // 8-byte cache not full
- if (totalLength < 8) {
- let valueMask = (1 << length) - 1;
- this.writeCache = (this.writeCache << length) | (value & valueMask);
- this.writeCacheSize += length;
- return;
- }
-
- // Deal with unaligned part
- if (this.writeCacheSize) {
- let mergeLength = 8 - this.writeCacheSize,
- valueMask = (1 << mergeLength) - 1;
-
- this.writeCache = (this.writeCache << mergeLength) | ((value >> (length - mergeLength)) & valueMask);
- this.writeBuffer.push(this.writeCache & 0xFF);
- length -= mergeLength;
- }
-
- // Aligned part, just copy
- while (length >= 8) {
- length -= 8;
- this.writeBuffer.push((value >> length) & 0xFF);
- }
-
- // Rest part is saved into cache
- this.writeCacheSize = length;
- this.writeCache = value & ((1 << length) - 1);
-
- return;
- },
-
- // Drop what still in read cache and goto next 8-byte alignment.
- // There might be a better naming.
- nextOctetAlign: function() {
- this.readCache = 0;
- this.readCacheSize = 0;
- },
-
- // Flush current write cache to Buf with padding 0s.
- // There might be a better naming.
- flushWithPadding: function() {
- if (this.writeCacheSize) {
- this.writeBuffer.push(this.writeCache << (8 - this.writeCacheSize));
- }
- this.writeCache = 0;
- this.writeCacheSize = 0;
- },
-
- startWrite: function(dataBuffer) {
- this.writeBuffer = dataBuffer;
- this.writeCache = 0;
- this.writeCacheSize = 0;
- },
-
- startRead: function(dataBuffer) {
- this.readBuffer = dataBuffer;
- this.readCache = 0;
- this.readCacheSize = 0;
- this.readIndex = 0;
- },
-
- getWriteBufferSize: function() {
- return this.writeBuffer.length;
- },
-
- overwriteWriteBuffer: function(position, data) {
- let writeLength = data.length;
- if (writeLength + position >= this.writeBuffer.length) {
- writeLength = this.writeBuffer.length - position;
- }
- for (let i = 0; i < writeLength; i++) {
- this.writeBuffer[i + position] = data[i];
- }
- }
-};
-
-/**
- * Helper for CDMA PDU
- *
- * Currently, some function are shared with GsmPDUHelper, they should be
- * moved from GsmPDUHelper to a common object shared among GsmPDUHelper and
- * CdmaPDUHelper.
- */
-function CdmaPDUHelperObject(aContext) {
- this.context = aContext;
-}
-CdmaPDUHelperObject.prototype = {
- context: null,
-
- // 1..........C
- // Only "1234567890*#" is defined in C.S0005-D v2.0
- dtmfChars: ".1234567890*#...",
-
- /**
- * Entry point for SMS encoding, the options object is made compatible
- * with existing writeMessage() of GsmPDUHelper, but less key is used.
- *
- * Current used key in options:
- * @param number
- * String containing the address (number) of the SMS receiver
- * @param body
- * String containing the message to be sent, segmented part
- * @param dcs
- * Data coding scheme. One of the PDU_DCS_MSG_CODING_*BITS_ALPHABET
- * constants.
- * @param encodedBodyLength
- * Length of the user data when encoded with the given DCS. For UCS2,
- * in bytes; for 7-bit, in septets.
- * @param requestStatusReport
- * Request status report.
- * @param segmentRef
- * Reference number of concatenated SMS message
- * @param segmentMaxSeq
- * Total number of concatenated SMS message
- * @param segmentSeq
- * Sequence number of concatenated SMS message
- */
- writeMessage: function(options) {
- if (DEBUG) {
- this.context.debug("cdma_writeMessage: " + JSON.stringify(options));
- }
-
- // Get encoding
- options.encoding = this.gsmDcsToCdmaEncoding(options.dcs);
-
- // Common Header
- if (options.segmentMaxSeq > 1) {
- this.writeInt(PDU_CDMA_MSG_TELESERIVCIE_ID_WEMT);
- } else {
- this.writeInt(PDU_CDMA_MSG_TELESERIVCIE_ID_SMS);
- }
-
- this.writeInt(0);
- this.writeInt(PDU_CDMA_MSG_CATEGORY_UNSPEC);
-
- // Just fill out address info in byte, rild will encap them for us
- let addrInfo = this.encodeAddr(options.number);
- this.writeByte(addrInfo.digitMode);
- this.writeByte(addrInfo.numberMode);
- this.writeByte(addrInfo.numberType);
- this.writeByte(addrInfo.numberPlan);
- this.writeByte(addrInfo.address.length);
- for (let i = 0; i < addrInfo.address.length; i++) {
- this.writeByte(addrInfo.address[i]);
- }
-
- // Subaddress, not supported
- this.writeByte(0); // Subaddress : Type
- this.writeByte(0); // Subaddress : Odd
- this.writeByte(0); // Subaddress : length
-
- // User Data
- let encodeResult = this.encodeUserData(options);
- this.writeByte(encodeResult.length);
- for (let i = 0; i < encodeResult.length; i++) {
- this.writeByte(encodeResult[i]);
- }
-
- encodeResult = null;
- },
-
- /**
- * Data writters
- */
- writeInt: function(value) {
- this.context.Buf.writeInt32(value);
- },
-
- writeByte: function(value) {
- this.context.Buf.writeInt32(value & 0xFF);
- },
-
- /**
- * Transform GSM DCS to CDMA encoding.
- */
- gsmDcsToCdmaEncoding: function(encoding) {
- switch (encoding) {
- case PDU_DCS_MSG_CODING_7BITS_ALPHABET:
- return PDU_CDMA_MSG_CODING_7BITS_ASCII;
- case PDU_DCS_MSG_CODING_8BITS_ALPHABET:
- return PDU_CDMA_MSG_CODING_OCTET;
- case PDU_DCS_MSG_CODING_16BITS_ALPHABET:
- return PDU_CDMA_MSG_CODING_UNICODE;
- }
- throw new Error("gsmDcsToCdmaEncoding(): Invalid GSM SMS DCS value: " + encoding);
- },
-
- /**
- * Encode address into CDMA address format, as a byte array.
- *
- * @see 3GGP2 C.S0015-B 2.0, 3.4.3.3 Address Parameters
- *
- * @param address
- * String of address to be encoded
- */
- encodeAddr: function(address) {
- let result = {};
-
- result.numberType = PDU_CDMA_MSG_ADDR_NUMBER_TYPE_UNKNOWN;
- result.numberPlan = PDU_CDMA_MSG_ADDR_NUMBER_TYPE_UNKNOWN;
-
- if (address[0] === '+') {
- address = address.substring(1);
- }
-
- // Try encode with DTMF first
- result.digitMode = PDU_CDMA_MSG_ADDR_DIGIT_MODE_DTMF;
- result.numberMode = PDU_CDMA_MSG_ADDR_NUMBER_MODE_ANSI;
-
- result.address = [];
- for (let i = 0; i < address.length; i++) {
- let addrDigit = this.dtmfChars.indexOf(address.charAt(i));
- if (addrDigit < 0) {
- result.digitMode = PDU_CDMA_MSG_ADDR_DIGIT_MODE_ASCII;
- result.numberMode = PDU_CDMA_MSG_ADDR_NUMBER_MODE_ASCII;
- result.address = [];
- break;
- }
- result.address.push(addrDigit);
- }
-
- // Address can't be encoded with DTMF, then use 7-bit ASCII
- if (result.digitMode !== PDU_CDMA_MSG_ADDR_DIGIT_MODE_DTMF) {
- if (address.indexOf("@") !== -1) {
- result.numberType = PDU_CDMA_MSG_ADDR_NUMBER_TYPE_NATIONAL;
- }
-
- for (let i = 0; i < address.length; i++) {
- result.address.push(address.charCodeAt(i) & 0x7F);
- }
- }
-
- return result;
- },
-
- /**
- * Encode SMS contents in options into CDMA userData field.
- * Corresponding and required subparameters will be added automatically.
- *
- * @see 3GGP2 C.S0015-B 2.0, 3.4.3.7 Bearer Data
- * 4.5 Bearer Data Parameters
- *
- * Current used key in options:
- * @param body
- * String containing the message to be sent, segmented part
- * @param encoding
- * Encoding method of CDMA, can be transformed from GSM DCS by function
- * cdmaPduHelp.gsmDcsToCdmaEncoding()
- * @param encodedBodyLength
- * Length of the user data when encoded with the given DCS. For UCS2,
- * in bytes; for 7-bit, in septets.
- * @param requestStatusReport
- * Request status report.
- * @param segmentRef
- * Reference number of concatenated SMS message
- * @param segmentMaxSeq
- * Total number of concatenated SMS message
- * @param segmentSeq
- * Sequence number of concatenated SMS message
- */
- encodeUserData: function(options) {
- let userDataBuffer = [];
- this.context.BitBufferHelper.startWrite(userDataBuffer);
-
- // Message Identifier
- this.encodeUserDataMsgId(options);
-
- // User Data
- this.encodeUserDataMsg(options);
-
- // Reply Option
- this.encodeUserDataReplyOption(options);
-
- return userDataBuffer;
- },
-
- /**
- * User data subparameter encoder : Message Identifier
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.1 Message Identifier
- */
- encodeUserDataMsgId: function(options) {
- let BitBufferHelper = this.context.BitBufferHelper;
- BitBufferHelper.writeBits(PDU_CDMA_MSG_USERDATA_MSG_ID, 8);
- BitBufferHelper.writeBits(3, 8);
- BitBufferHelper.writeBits(PDU_CDMA_MSG_TYPE_SUBMIT, 4);
- BitBufferHelper.writeBits(1, 16); // TODO: How to get message ID?
- if (options.segmentMaxSeq > 1) {
- BitBufferHelper.writeBits(1, 1);
- } else {
- BitBufferHelper.writeBits(0, 1);
- }
-
- BitBufferHelper.flushWithPadding();
- },
-
- /**
- * User data subparameter encoder : User Data
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.2 User Data
- */
- encodeUserDataMsg: function(options) {
- let BitBufferHelper = this.context.BitBufferHelper;
- BitBufferHelper.writeBits(PDU_CDMA_MSG_USERDATA_BODY, 8);
- // Reserve space for length
- BitBufferHelper.writeBits(0, 8);
- let lengthPosition = BitBufferHelper.getWriteBufferSize();
-
- BitBufferHelper.writeBits(options.encoding, 5);
-
- // Add user data header for message segement
- let msgBody = options.body,
- msgBodySize = (options.encoding === PDU_CDMA_MSG_CODING_7BITS_ASCII ?
- options.encodedBodyLength :
- msgBody.length);
- if (options.segmentMaxSeq > 1) {
- if (options.encoding === PDU_CDMA_MSG_CODING_7BITS_ASCII) {
- BitBufferHelper.writeBits(msgBodySize + 7, 8); // Required length for user data header, in septet(7-bit)
-
- BitBufferHelper.writeBits(5, 8); // total header length 5 bytes
- BitBufferHelper.writeBits(PDU_IEI_CONCATENATED_SHORT_MESSAGES_8BIT, 8); // header id 0
- BitBufferHelper.writeBits(3, 8); // length of element for id 0 is 3
- BitBufferHelper.writeBits(options.segmentRef & 0xFF, 8); // Segement reference
- BitBufferHelper.writeBits(options.segmentMaxSeq & 0xFF, 8); // Max segment
- BitBufferHelper.writeBits(options.segmentSeq & 0xFF, 8); // Current segment
- BitBufferHelper.writeBits(0, 1); // Padding to make header data septet(7-bit) aligned
- } else {
- if (options.encoding === PDU_CDMA_MSG_CODING_UNICODE) {
- BitBufferHelper.writeBits(msgBodySize + 3, 8); // Required length for user data header, in 16-bit
- } else {
- BitBufferHelper.writeBits(msgBodySize + 6, 8); // Required length for user data header, in octet(8-bit)
- }
-
- BitBufferHelper.writeBits(5, 8); // total header length 5 bytes
- BitBufferHelper.writeBits(PDU_IEI_CONCATENATED_SHORT_MESSAGES_8BIT, 8); // header id 0
- BitBufferHelper.writeBits(3, 8); // length of element for id 0 is 3
- BitBufferHelper.writeBits(options.segmentRef & 0xFF, 8); // Segement reference
- BitBufferHelper.writeBits(options.segmentMaxSeq & 0xFF, 8); // Max segment
- BitBufferHelper.writeBits(options.segmentSeq & 0xFF, 8); // Current segment
- }
- } else {
- BitBufferHelper.writeBits(msgBodySize, 8);
- }
-
- // Encode message based on encoding method
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- for (let i = 0; i < msgBody.length; i++) {
- switch (options.encoding) {
- case PDU_CDMA_MSG_CODING_OCTET: {
- let msgDigit = msgBody.charCodeAt(i);
- BitBufferHelper.writeBits(msgDigit, 8);
- break;
- }
- case PDU_CDMA_MSG_CODING_7BITS_ASCII: {
- let msgDigit = msgBody.charCodeAt(i),
- msgDigitChar = msgBody.charAt(i);
-
- if (msgDigit >= 32) {
- BitBufferHelper.writeBits(msgDigit, 7);
- } else {
- msgDigit = langTable.indexOf(msgDigitChar);
-
- if (msgDigit === PDU_NL_EXTENDED_ESCAPE) {
- break;
- }
- if (msgDigit >= 0) {
- BitBufferHelper.writeBits(msgDigit, 7);
- } else {
- msgDigit = langShiftTable.indexOf(msgDigitChar);
- if (msgDigit == -1) {
- throw new Error("'" + msgDigitChar + "' is not in 7 bit alphabet "
- + langIndex + ":" + langShiftIndex + "!");
- }
-
- if (msgDigit === PDU_NL_RESERVED_CONTROL) {
- break;
- }
-
- BitBufferHelper.writeBits(PDU_NL_EXTENDED_ESCAPE, 7);
- BitBufferHelper.writeBits(msgDigit, 7);
- }
- }
- break;
- }
- case PDU_CDMA_MSG_CODING_UNICODE: {
- let msgDigit = msgBody.charCodeAt(i);
- BitBufferHelper.writeBits(msgDigit, 16);
- break;
- }
- }
- }
- BitBufferHelper.flushWithPadding();
-
- // Fill length
- let currentPosition = BitBufferHelper.getWriteBufferSize();
- BitBufferHelper.overwriteWriteBuffer(lengthPosition - 1, [currentPosition - lengthPosition]);
- },
-
- /**
- * User data subparameter encoder : Reply Option
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.11 Reply Option
- */
- encodeUserDataReplyOption: function(options) {
- if (options.requestStatusReport) {
- let BitBufferHelper = this.context.BitBufferHelper;
- BitBufferHelper.writeBits(PDU_CDMA_MSG_USERDATA_REPLY_OPTION, 8);
- BitBufferHelper.writeBits(1, 8);
- BitBufferHelper.writeBits(0, 1); // USER_ACK_REQ
- BitBufferHelper.writeBits(1, 1); // DAK_REQ
- BitBufferHelper.flushWithPadding();
- }
- },
-
- /**
- * Entry point for SMS decoding, the returned object is made compatible
- * with existing readMessage() of GsmPDUHelper
- */
- readMessage: function() {
- let message = {};
-
- // Teleservice Identifier
- message.teleservice = this.readInt();
-
- // Message Type
- let isServicePresent = this.readByte();
- if (isServicePresent) {
- message.messageType = PDU_CDMA_MSG_TYPE_BROADCAST;
- } else {
- if (message.teleservice) {
- message.messageType = PDU_CDMA_MSG_TYPE_P2P;
- } else {
- message.messageType = PDU_CDMA_MSG_TYPE_ACK;
- }
- }
-
- // Service Category
- message.service = this.readInt();
-
- // Originated Address
- let addrInfo = {};
- addrInfo.digitMode = (this.readInt() & 0x01);
- addrInfo.numberMode = (this.readInt() & 0x01);
- addrInfo.numberType = (this.readInt() & 0x01);
- addrInfo.numberPlan = (this.readInt() & 0x01);
- addrInfo.addrLength = this.readByte();
- addrInfo.address = [];
- for (let i = 0; i < addrInfo.addrLength; i++) {
- addrInfo.address.push(this.readByte());
- }
- message.sender = this.decodeAddr(addrInfo);
-
- // Originated Subaddress
- addrInfo.Type = (this.readInt() & 0x07);
- addrInfo.Odd = (this.readByte() & 0x01);
- addrInfo.addrLength = this.readByte();
- for (let i = 0; i < addrInfo.addrLength; i++) {
- let addrDigit = this.readByte();
- message.sender += String.fromCharCode(addrDigit);
- }
-
- // Bearer Data
- this.decodeUserData(message);
-
- // Bearer Data Sub-Parameter: User Data
- let userData = message[PDU_CDMA_MSG_USERDATA_BODY];
- [message.header, message.body, message.encoding, message.data] =
- (userData) ? [userData.header, userData.body, userData.encoding, userData.data]
- : [null, null, null, null];
-
- // Bearer Data Sub-Parameter: Message Status
- // Success Delivery (0) if both Message Status and User Data are absent.
- // Message Status absent (-1) if only User Data is available.
- let msgStatus = message[PDU_CDMA_MSG_USER_DATA_MSG_STATUS];
- [message.errorClass, message.msgStatus] =
- (msgStatus) ? [msgStatus.errorClass, msgStatus.msgStatus]
- : ((message.body) ? [-1, -1] : [0, 0]);
-
- // Transform message to GSM msg
- let msg = {
- SMSC: "",
- mti: 0,
- udhi: 0,
- sender: message.sender,
- recipient: null,
- pid: PDU_PID_DEFAULT,
- epid: PDU_PID_DEFAULT,
- dcs: 0,
- mwi: null,
- replace: false,
- header: message.header,
- body: message.body,
- data: message.data,
- sentTimestamp: message[PDU_CDMA_MSG_USERDATA_TIMESTAMP],
- language: message[PDU_CDMA_LANGUAGE_INDICATOR],
- status: null,
- scts: null,
- dt: null,
- encoding: message.encoding,
- messageClass: GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- messageType: message.messageType,
- serviceCategory: message.service,
- subMsgType: message[PDU_CDMA_MSG_USERDATA_MSG_ID].msgType,
- msgId: message[PDU_CDMA_MSG_USERDATA_MSG_ID].msgId,
- errorClass: message.errorClass,
- msgStatus: message.msgStatus,
- teleservice: message.teleservice
- };
-
- return msg;
- },
-
- /**
- * Helper for processing received SMS parcel data.
- *
- * @param length
- * Length of SMS string in the incoming parcel.
- *
- * @return Message parsed or null for invalid message.
- */
- processReceivedSms: function(length) {
- if (!length) {
- if (DEBUG) this.context.debug("Received empty SMS!");
- return [null, PDU_FCS_UNSPECIFIED];
- }
-
- let message = this.readMessage();
- if (DEBUG) this.context.debug("Got new SMS: " + JSON.stringify(message));
-
- // Determine result
- if (!message) {
- return [null, PDU_FCS_UNSPECIFIED];
- }
-
- return [message, PDU_FCS_OK];
- },
-
- /**
- * Data readers
- */
- readInt: function() {
- return this.context.Buf.readInt32();
- },
-
- readByte: function() {
- return (this.context.Buf.readInt32() & 0xFF);
- },
-
- /**
- * Decode CDMA address data into address string
- *
- * @see 3GGP2 C.S0015-B 2.0, 3.4.3.3 Address Parameters
- *
- * Required key in addrInfo
- * @param addrLength
- * Length of address
- * @param digitMode
- * Address encoding method
- * @param address
- * Array of encoded address data
- */
- decodeAddr: function(addrInfo) {
- let result = "";
- for (let i = 0; i < addrInfo.addrLength; i++) {
- if (addrInfo.digitMode === PDU_CDMA_MSG_ADDR_DIGIT_MODE_DTMF) {
- result += this.dtmfChars.charAt(addrInfo.address[i]);
- } else {
- result += String.fromCharCode(addrInfo.address[i]);
- }
- }
- return result;
- },
-
- /**
- * Read userData in parcel buffer and decode into message object.
- * Each subparameter will be stored in corresponding key.
- *
- * @see 3GGP2 C.S0015-B 2.0, 3.4.3.7 Bearer Data
- * 4.5 Bearer Data Parameters
- */
- decodeUserData: function(message) {
- let userDataLength = this.readInt();
-
- while (userDataLength > 0) {
- let id = this.readByte(),
- length = this.readByte(),
- userDataBuffer = [];
-
- for (let i = 0; i < length; i++) {
- userDataBuffer.push(this.readByte());
- }
-
- this.context.BitBufferHelper.startRead(userDataBuffer);
-
- switch (id) {
- case PDU_CDMA_MSG_USERDATA_MSG_ID:
- message[id] = this.decodeUserDataMsgId();
- break;
- case PDU_CDMA_MSG_USERDATA_BODY:
- message[id] = this.decodeUserDataMsg(message[PDU_CDMA_MSG_USERDATA_MSG_ID].userHeader);
- break;
- case PDU_CDMA_MSG_USERDATA_TIMESTAMP:
- message[id] = this.decodeUserDataTimestamp();
- break;
- case PDU_CDMA_MSG_USERDATA_REPLY_OPTION:
- message[id] = this.decodeUserDataReplyOption();
- break;
- case PDU_CDMA_LANGUAGE_INDICATOR:
- message[id] = this.decodeLanguageIndicator();
- break;
- case PDU_CDMA_MSG_USERDATA_CALLBACK_NUMBER:
- message[id] = this.decodeUserDataCallbackNumber();
- break;
- case PDU_CDMA_MSG_USER_DATA_MSG_STATUS:
- message[id] = this.decodeUserDataMsgStatus();
- break;
- }
-
- userDataLength -= (length + 2);
- userDataBuffer = [];
- }
- },
-
- /**
- * User data subparameter decoder: Message Identifier
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.1 Message Identifier
- */
- decodeUserDataMsgId: function() {
- let result = {};
- let BitBufferHelper = this.context.BitBufferHelper;
- result.msgType = BitBufferHelper.readBits(4);
- result.msgId = BitBufferHelper.readBits(16);
- result.userHeader = BitBufferHelper.readBits(1);
-
- return result;
- },
-
- /**
- * Decode user data header, we only care about segment information
- * on CDMA.
- *
- * This function is mostly copied from gsmPduHelper.readUserDataHeader() but
- * change the read function, because CDMA user header decoding is't byte-wise
- * aligned.
- */
- decodeUserDataHeader: function(encoding) {
- let BitBufferHelper = this.context.BitBufferHelper;
- let header = {},
- headerSize = BitBufferHelper.readBits(8),
- userDataHeaderSize = headerSize + 1,
- headerPaddingBits = 0;
-
- // Calculate header size
- if (encoding === PDU_DCS_MSG_CODING_7BITS_ALPHABET) {
- // Length is in 7-bit
- header.length = Math.ceil(userDataHeaderSize * 8 / 7);
- // Calulate padding length
- headerPaddingBits = (header.length * 7) - (userDataHeaderSize * 8);
- } else if (encoding === PDU_DCS_MSG_CODING_8BITS_ALPHABET) {
- header.length = userDataHeaderSize;
- } else {
- header.length = userDataHeaderSize / 2;
- }
-
- while (headerSize) {
- let identifier = BitBufferHelper.readBits(8),
- length = BitBufferHelper.readBits(8);
-
- headerSize -= (2 + length);
-
- switch (identifier) {
- case PDU_IEI_CONCATENATED_SHORT_MESSAGES_8BIT: {
- let ref = BitBufferHelper.readBits(8),
- max = BitBufferHelper.readBits(8),
- seq = BitBufferHelper.readBits(8);
- if (max && seq && (seq <= max)) {
- header.segmentRef = ref;
- header.segmentMaxSeq = max;
- header.segmentSeq = seq;
- }
- break;
- }
- case PDU_IEI_APPLICATION_PORT_ADDRESSING_SCHEME_8BIT: {
- let dstp = BitBufferHelper.readBits(8),
- orip = BitBufferHelper.readBits(8);
- if ((dstp < PDU_APA_RESERVED_8BIT_PORTS)
- || (orip < PDU_APA_RESERVED_8BIT_PORTS)) {
- // 3GPP TS 23.040 clause 9.2.3.24.3: "A receiving entity shall
- // ignore any information element where the value of the
- // Information-Element-Data is Reserved or not supported"
- break;
- }
- header.destinationPort = dstp;
- header.originatorPort = orip;
- break;
- }
- case PDU_IEI_APPLICATION_PORT_ADDRESSING_SCHEME_16BIT: {
- let dstp = (BitBufferHelper.readBits(8) << 8) | BitBufferHelper.readBits(8),
- orip = (BitBufferHelper.readBits(8) << 8) | BitBufferHelper.readBits(8);
- // 3GPP TS 23.040 clause 9.2.3.24.4: "A receiving entity shall
- // ignore any information element where the value of the
- // Information-Element-Data is Reserved or not supported"
- if ((dstp < PDU_APA_VALID_16BIT_PORTS)
- && (orip < PDU_APA_VALID_16BIT_PORTS)) {
- header.destinationPort = dstp;
- header.originatorPort = orip;
- }
- break;
- }
- case PDU_IEI_CONCATENATED_SHORT_MESSAGES_16BIT: {
- let ref = (BitBufferHelper.readBits(8) << 8) | BitBufferHelper.readBits(8),
- max = BitBufferHelper.readBits(8),
- seq = BitBufferHelper.readBits(8);
- if (max && seq && (seq <= max)) {
- header.segmentRef = ref;
- header.segmentMaxSeq = max;
- header.segmentSeq = seq;
- }
- break;
- }
- case PDU_IEI_NATIONAL_LANGUAGE_SINGLE_SHIFT: {
- let langShiftIndex = BitBufferHelper.readBits(8);
- if (langShiftIndex < PDU_NL_SINGLE_SHIFT_TABLES.length) {
- header.langShiftIndex = langShiftIndex;
- }
- break;
- }
- case PDU_IEI_NATIONAL_LANGUAGE_LOCKING_SHIFT: {
- let langIndex = BitBufferHelper.readBits(8);
- if (langIndex < PDU_NL_LOCKING_SHIFT_TABLES.length) {
- header.langIndex = langIndex;
- }
- break;
- }
- case PDU_IEI_SPECIAL_SMS_MESSAGE_INDICATION: {
- let msgInd = BitBufferHelper.readBits(8) & 0xFF,
- msgCount = BitBufferHelper.readBits(8);
- /*
- * TS 23.040 V6.8.1 Sec 9.2.3.24.2
- * bits 1 0 : basic message indication type
- * bits 4 3 2 : extended message indication type
- * bits 6 5 : Profile id
- * bit 7 : storage type
- */
- let storeType = msgInd & PDU_MWI_STORE_TYPE_BIT;
- header.mwi = {};
- mwi = header.mwi;
-
- if (storeType == PDU_MWI_STORE_TYPE_STORE) {
- // Store message because TP_UDH indicates so, note this may override
- // the setting in DCS, but that is expected
- mwi.discard = false;
- } else if (mwi.discard === undefined) {
- // storeType == PDU_MWI_STORE_TYPE_DISCARD
- // only override mwi.discard here if it hasn't already been set
- mwi.discard = true;
- }
-
- mwi.msgCount = msgCount & 0xFF;
- mwi.active = mwi.msgCount > 0;
-
- if (DEBUG) {
- this.context.debug("MWI in TP_UDH received: " + JSON.stringify(mwi));
- }
- break;
- }
- default:
- // Drop unsupported id
- for (let i = 0; i < length; i++) {
- BitBufferHelper.readBits(8);
- }
- }
- }
-
- // Consume padding bits
- if (headerPaddingBits) {
- BitBufferHelper.readBits(headerPaddingBits);
- }
-
- return header;
- },
-
- getCdmaMsgEncoding: function(encoding) {
- // Determine encoding method
- switch (encoding) {
- case PDU_CDMA_MSG_CODING_7BITS_ASCII:
- case PDU_CDMA_MSG_CODING_IA5:
- case PDU_CDMA_MSG_CODING_7BITS_GSM:
- return PDU_DCS_MSG_CODING_7BITS_ALPHABET;
- case PDU_CDMA_MSG_CODING_OCTET:
- case PDU_CDMA_MSG_CODING_IS_91:
- case PDU_CDMA_MSG_CODING_LATIN_HEBREW:
- case PDU_CDMA_MSG_CODING_LATIN:
- return PDU_DCS_MSG_CODING_8BITS_ALPHABET;
- case PDU_CDMA_MSG_CODING_UNICODE:
- case PDU_CDMA_MSG_CODING_SHIFT_JIS:
- case PDU_CDMA_MSG_CODING_KOREAN:
- return PDU_DCS_MSG_CODING_16BITS_ALPHABET;
- }
- return null;
- },
-
- decodeCdmaPDUMsg: function(encoding, msgType, msgBodySize) {
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- let BitBufferHelper = this.context.BitBufferHelper;
- let result = "";
- let msgDigit;
- switch (encoding) {
- case PDU_CDMA_MSG_CODING_OCTET: // TODO : Require Test
- while(msgBodySize > 0) {
- msgDigit = String.fromCharCode(BitBufferHelper.readBits(8));
- result += msgDigit;
- msgBodySize--;
- }
- break;
- case PDU_CDMA_MSG_CODING_IS_91: // TODO : Require Test
- // Referenced from android code
- switch (msgType) {
- case PDU_CDMA_MSG_CODING_IS_91_TYPE_SMS:
- case PDU_CDMA_MSG_CODING_IS_91_TYPE_SMS_FULL:
- case PDU_CDMA_MSG_CODING_IS_91_TYPE_VOICEMAIL_STATUS:
- while(msgBodySize > 0) {
- msgDigit = String.fromCharCode(BitBufferHelper.readBits(6) + 0x20);
- result += msgDigit;
- msgBodySize--;
- }
- break;
- case PDU_CDMA_MSG_CODING_IS_91_TYPE_CLI:
- let addrInfo = {};
- addrInfo.digitMode = PDU_CDMA_MSG_ADDR_DIGIT_MODE_DTMF;
- addrInfo.numberMode = PDU_CDMA_MSG_ADDR_NUMBER_MODE_ANSI;
- addrInfo.numberType = PDU_CDMA_MSG_ADDR_NUMBER_TYPE_UNKNOWN;
- addrInfo.numberPlan = PDU_CDMA_MSG_ADDR_NUMBER_PLAN_UNKNOWN;
- addrInfo.addrLength = msgBodySize;
- addrInfo.address = [];
- for (let i = 0; i < addrInfo.addrLength; i++) {
- addrInfo.address.push(BitBufferHelper.readBits(4));
- }
- result = this.decodeAddr(addrInfo);
- break;
- }
- // Fall through.
- case PDU_CDMA_MSG_CODING_7BITS_ASCII:
- case PDU_CDMA_MSG_CODING_IA5: // TODO : Require Test
- while(msgBodySize > 0) {
- msgDigit = BitBufferHelper.readBits(7);
- if (msgDigit >= 32) {
- msgDigit = String.fromCharCode(msgDigit);
- } else {
- if (msgDigit !== PDU_NL_EXTENDED_ESCAPE) {
- msgDigit = langTable[msgDigit];
- } else {
- msgDigit = BitBufferHelper.readBits(7);
- msgBodySize--;
- msgDigit = langShiftTable[msgDigit];
- }
- }
- result += msgDigit;
- msgBodySize--;
- }
- break;
- case PDU_CDMA_MSG_CODING_UNICODE:
- while(msgBodySize > 0) {
- msgDigit = String.fromCharCode(BitBufferHelper.readBits(16));
- result += msgDigit;
- msgBodySize--;
- }
- break;
- case PDU_CDMA_MSG_CODING_7BITS_GSM: // TODO : Require Test
- while(msgBodySize > 0) {
- msgDigit = BitBufferHelper.readBits(7);
- if (msgDigit !== PDU_NL_EXTENDED_ESCAPE) {
- msgDigit = langTable[msgDigit];
- } else {
- msgDigit = BitBufferHelper.readBits(7);
- msgBodySize--;
- msgDigit = langShiftTable[msgDigit];
- }
- result += msgDigit;
- msgBodySize--;
- }
- break;
- case PDU_CDMA_MSG_CODING_LATIN: // TODO : Require Test
- // Reference : http://en.wikipedia.org/wiki/ISO/IEC_8859-1
- while(msgBodySize > 0) {
- msgDigit = String.fromCharCode(BitBufferHelper.readBits(8));
- result += msgDigit;
- msgBodySize--;
- }
- break;
- case PDU_CDMA_MSG_CODING_LATIN_HEBREW: // TODO : Require Test
- // Reference : http://en.wikipedia.org/wiki/ISO/IEC_8859-8
- while(msgBodySize > 0) {
- msgDigit = BitBufferHelper.readBits(8);
- if (msgDigit === 0xDF) {
- msgDigit = String.fromCharCode(0x2017);
- } else if (msgDigit === 0xFD) {
- msgDigit = String.fromCharCode(0x200E);
- } else if (msgDigit === 0xFE) {
- msgDigit = String.fromCharCode(0x200F);
- } else if (msgDigit >= 0xE0 && msgDigit <= 0xFA) {
- msgDigit = String.fromCharCode(0x4F0 + msgDigit);
- } else {
- msgDigit = String.fromCharCode(msgDigit);
- }
- result += msgDigit;
- msgBodySize--;
- }
- break;
- case PDU_CDMA_MSG_CODING_SHIFT_JIS:
- // Reference : http://msdn.microsoft.com/en-US/goglobal/cc305152.aspx
- // http://demo.icu-project.org/icu-bin/convexp?conv=Shift_JIS
- let shift_jis_message = [];
-
- while (msgBodySize > 0) {
- shift_jis_message.push(BitBufferHelper.readBits(8));
- msgBodySize--;
- }
-
- let decoder = new TextDecoder("shift_jis");
- result = decoder.decode(new Uint8Array(shift_jis_message));
- break;
- case PDU_CDMA_MSG_CODING_KOREAN:
- case PDU_CDMA_MSG_CODING_GSM_DCS:
- // Fall through.
- default:
- break;
- }
- return result;
- },
-
- /**
- * User data subparameter decoder : User Data
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.2 User Data
- */
- decodeUserDataMsg: function(hasUserHeader) {
- let BitBufferHelper = this.context.BitBufferHelper;
- let result = {},
- encoding = BitBufferHelper.readBits(5),
- msgType;
-
- if (encoding === PDU_CDMA_MSG_CODING_IS_91) {
- msgType = BitBufferHelper.readBits(8);
- }
- result.encoding = this.getCdmaMsgEncoding(encoding);
-
- let msgBodySize = BitBufferHelper.readBits(8);
-
- // For segmented SMS, a user header is included before sms content
- if (hasUserHeader) {
- result.header = this.decodeUserDataHeader(result.encoding);
- // header size is included in body size, they are decoded
- msgBodySize -= result.header.length;
- }
-
- // Store original payload if enconding is OCTET for further handling of WAP Push, etc.
- if (encoding === PDU_CDMA_MSG_CODING_OCTET && msgBodySize > 0) {
- result.data = new Uint8Array(msgBodySize);
- for (let i = 0; i < msgBodySize; i++) {
- result.data[i] = BitBufferHelper.readBits(8);
- }
- BitBufferHelper.backwardReadPilot(8 * msgBodySize);
- }
-
- // Decode sms content
- result.body = this.decodeCdmaPDUMsg(encoding, msgType, msgBodySize);
-
- return result;
- },
-
- decodeBcd: function(value) {
- return ((value >> 4) & 0xF) * 10 + (value & 0x0F);
- },
-
- /**
- * User data subparameter decoder : Time Stamp
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.4 Message Center Time Stamp
- */
- decodeUserDataTimestamp: function() {
- let BitBufferHelper = this.context.BitBufferHelper;
- let year = this.decodeBcd(BitBufferHelper.readBits(8)),
- month = this.decodeBcd(BitBufferHelper.readBits(8)) - 1,
- date = this.decodeBcd(BitBufferHelper.readBits(8)),
- hour = this.decodeBcd(BitBufferHelper.readBits(8)),
- min = this.decodeBcd(BitBufferHelper.readBits(8)),
- sec = this.decodeBcd(BitBufferHelper.readBits(8));
-
- if (year >= 96 && year <= 99) {
- year += 1900;
- } else {
- year += 2000;
- }
-
- let result = (new Date(year, month, date, hour, min, sec, 0)).valueOf();
-
- return result;
- },
-
- /**
- * User data subparameter decoder : Reply Option
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.11 Reply Option
- */
- decodeUserDataReplyOption: function() {
- let replyAction = this.context.BitBufferHelper.readBits(4),
- result = { userAck: (replyAction & 0x8) ? true : false,
- deliverAck: (replyAction & 0x4) ? true : false,
- readAck: (replyAction & 0x2) ? true : false,
- report: (replyAction & 0x1) ? true : false
- };
-
- return result;
- },
-
- /**
- * User data subparameter decoder : Language Indicator
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.14 Language Indicator
- */
- decodeLanguageIndicator: function() {
- let language = this.context.BitBufferHelper.readBits(8);
- let result = CB_CDMA_LANG_GROUP[language];
- return result;
- },
-
- /**
- * User data subparameter decoder : Call-Back Number
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.15 Call-Back Number
- */
- decodeUserDataCallbackNumber: function() {
- let BitBufferHelper = this.context.BitBufferHelper;
- let digitMode = BitBufferHelper.readBits(1);
- if (digitMode) {
- let numberType = BitBufferHelper.readBits(3),
- numberPlan = BitBufferHelper.readBits(4);
- }
- let numberFields = BitBufferHelper.readBits(8),
- result = "";
- for (let i = 0; i < numberFields; i++) {
- if (digitMode === PDU_CDMA_MSG_ADDR_DIGIT_MODE_DTMF) {
- let addrDigit = BitBufferHelper.readBits(4);
- result += this.dtmfChars.charAt(addrDigit);
- } else {
- let addrDigit = BitBufferHelper.readBits(8);
- result += String.fromCharCode(addrDigit);
- }
- }
-
- return result;
- },
-
- /**
- * User data subparameter decoder : Message Status
- *
- * @see 3GGP2 C.S0015-B 2.0, 4.5.21 Message Status
- */
- decodeUserDataMsgStatus: function() {
- let BitBufferHelper = this.context.BitBufferHelper;
- let result = {
- errorClass: BitBufferHelper.readBits(2),
- msgStatus: BitBufferHelper.readBits(6)
- };
-
- return result;
- },
-
- /**
- * Decode information record parcel.
- */
- decodeInformationRecord: function() {
- let Buf = this.context.Buf;
- let records = [];
- let numOfRecords = Buf.readInt32();
-
- let type;
- let record;
- for (let i = 0; i < numOfRecords; i++) {
- record = {};
- type = Buf.readInt32();
-
- switch (type) {
- /*
- * Every type is encaped by ril, except extended display
- */
- case PDU_CDMA_INFO_REC_TYPE_DISPLAY:
- case PDU_CDMA_INFO_REC_TYPE_EXTENDED_DISPLAY:
- record.display = Buf.readString();
- break;
- case PDU_CDMA_INFO_REC_TYPE_CALLED_PARTY_NUMBER:
- record.calledNumber = {};
- record.calledNumber.number = Buf.readString();
- record.calledNumber.type = Buf.readInt32();
- record.calledNumber.plan = Buf.readInt32();
- record.calledNumber.pi = Buf.readInt32();
- record.calledNumber.si = Buf.readInt32();
- break;
- case PDU_CDMA_INFO_REC_TYPE_CALLING_PARTY_NUMBER:
- record.callingNumber = {};
- record.callingNumber.number = Buf.readString();
- record.callingNumber.type = Buf.readInt32();
- record.callingNumber.plan = Buf.readInt32();
- record.callingNumber.pi = Buf.readInt32();
- record.callingNumber.si = Buf.readInt32();
- break;
- case PDU_CDMA_INFO_REC_TYPE_CONNECTED_NUMBER:
- record.connectedNumber = {};
- record.connectedNumber.number = Buf.readString();
- record.connectedNumber.type = Buf.readInt32();
- record.connectedNumber.plan = Buf.readInt32();
- record.connectedNumber.pi = Buf.readInt32();
- record.connectedNumber.si = Buf.readInt32();
- break;
- case PDU_CDMA_INFO_REC_TYPE_SIGNAL:
- record.signal = {};
- if (!Buf.readInt32()) { // Non-zero if signal is present.
- Buf.seekIncoming(3 * Buf.UINT32_SIZE);
- continue;
- }
- record.signal.type = Buf.readInt32();
- record.signal.alertPitch = Buf.readInt32();
- record.signal.signal = Buf.readInt32();
- break;
- case PDU_CDMA_INFO_REC_TYPE_REDIRECTING_NUMBER:
- record.redirect = {};
- record.redirect.number = Buf.readString();
- record.redirect.type = Buf.readInt32();
- record.redirect.plan = Buf.readInt32();
- record.redirect.pi = Buf.readInt32();
- record.redirect.si = Buf.readInt32();
- record.redirect.reason = Buf.readInt32();
- break;
- case PDU_CDMA_INFO_REC_TYPE_LINE_CONTROL:
- record.lineControl = {};
- record.lineControl.polarityIncluded = Buf.readInt32();
- record.lineControl.toggle = Buf.readInt32();
- record.lineControl.reverse = Buf.readInt32();
- record.lineControl.powerDenial = Buf.readInt32();
- break;
- case PDU_CDMA_INFO_REC_TYPE_T53_CLIR:
- record.clirCause = Buf.readInt32();
- break;
- case PDU_CDMA_INFO_REC_TYPE_T53_AUDIO_CONTROL:
- record.audioControl = {};
- record.audioControl.upLink = Buf.readInt32();
- record.audioControl.downLink = Buf.readInt32();
- break;
- case PDU_CDMA_INFO_REC_TYPE_T53_RELEASE:
- // Fall through
- default:
- throw new Error("UNSOLICITED_CDMA_INFO_REC(), Unsupported information record type " + type + "\n");
- }
-
- records.push(record);
- }
-
- return records;
- }
-};
-
-/**
- * Helper for processing ICC PDUs.
- */
-function ICCPDUHelperObject(aContext) {
- this.context = aContext;
-}
-ICCPDUHelperObject.prototype = {
- context: null,
-
- /**
- * Read GSM 8-bit unpacked octets,
- * which are default 7-bit alphabets with bit 8 set to 0.
- *
- * @param numOctets
- * Number of octets to be read.
- */
- read8BitUnpackedToString: function(numOctets) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let ret = "";
- let escapeFound = false;
- let i;
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
-
- for(i = 0; i < numOctets; i++) {
- let octet = GsmPDUHelper.readHexOctet();
- if (octet == 0xff) {
- i++;
- break;
- }
-
- if (escapeFound) {
- escapeFound = false;
- if (octet == PDU_NL_EXTENDED_ESCAPE) {
- // According to 3GPP TS 23.038, section 6.2.1.1, NOTE 1, "On
- // receipt of this code, a receiving entity shall display a space
- // until another extensiion table is defined."
- ret += " ";
- } else if (octet == PDU_NL_RESERVED_CONTROL) {
- // According to 3GPP TS 23.038 B.2, "This code represents a control
- // character and therefore must not be used for language specific
- // characters."
- ret += " ";
- } else {
- ret += langShiftTable[octet];
- }
- } else if (octet == PDU_NL_EXTENDED_ESCAPE) {
- escapeFound = true;
- } else {
- ret += langTable[octet];
- }
- }
-
- let Buf = this.context.Buf;
- Buf.seekIncoming((numOctets - i) * Buf.PDU_HEX_OCTET_SIZE);
- return ret;
- },
-
- /**
- * Write GSM 8-bit unpacked octets.
- *
- * @param numOctets Number of total octets to be writen, including trailing
- * 0xff.
- * @param str String to be written. Could be null.
- *
- * @return The string has been written into Buf. "" if str is null.
- */
- writeStringTo8BitUnpacked: function(numOctets, str) {
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- // If the character is GSM extended alphabet, two octets will be written.
- // So we need to keep track of number of octets to be written.
- let i, j;
- let len = str ? str.length : 0;
- for (i = 0, j = 0; i < len && j < numOctets; i++) {
- let c = str.charAt(i);
- let octet = langTable.indexOf(c);
-
- if (octet == -1) {
- // Make sure we still have enough space to write two octets.
- if (j + 2 > numOctets) {
- break;
- }
-
- octet = langShiftTable.indexOf(c);
- if (octet == -1) {
- // Fallback to ASCII space.
- octet = langTable.indexOf(' ');
- } else {
- GsmPDUHelper.writeHexOctet(PDU_NL_EXTENDED_ESCAPE);
- j++;
- }
- }
- GsmPDUHelper.writeHexOctet(octet);
- j++;
- }
-
- // trailing 0xff
- while (j++ < numOctets) {
- GsmPDUHelper.writeHexOctet(0xff);
- }
-
- return (str) ? str.substring(0, i) : "";
- },
-
- /**
- * Write UCS2 String on UICC.
- * The default choose 0x81 or 0x82 encode, otherwise use 0x80 encode.
- *
- * @see TS 102.221, Annex A.
- * @param numOctets
- * Total number of octets to be written. This includes the length of
- * alphaId and the length of trailing unused octets(0xff).
- * @param str
- * String to be written.
- *
- * @return The string has been written into Buf.
- */
- writeICCUCS2String: function(numOctets, str) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let scheme = 0x80;
- let basePointer;
-
- if (str.length > 2) {
- let min = 0xFFFF;
- let max = 0;
- for (let i = 0; i < str.length; i++) {
- let code = str.charCodeAt(i);
- // filter out GSM Default Alphabet character
- if (code & 0xFF80) {
- if (min > code) {
- min = code;
- }
- if (max < code) {
- max = code;
- }
- }
- }
-
- // 0x81 and 0x82 only support 'half-page', i.e., 128 characters.
- if ((max - min) >= 0 && (max - min) < 128) {
- // 0x81 base pointer is 0hhh hhhh h000 0000, and bit 16 is set to zero,
- // therefore it can't compute 0x8000~0xFFFF.
- // Since 0x81 only support 128 characters,
- // either XX00~XX7f(bit 8 are 0) or XX80~XXff(bit 8 are 1)
- if (((min & 0x7f80) == (max & 0x7f80)) &&
- ((max & 0x8000) == 0)) {
- scheme = 0x81;
- basePointer = min & 0x7f80;
- } else {
- scheme = 0x82;
- basePointer = min;
- }
- }
- }
-
- switch (scheme) {
- /**
- * +------+---------+---------+---------+---------+------+------+
- * | 0x80 | Ch1_msb | Ch1_lsb | Ch2_msb | Ch2_lsb | 0xff | 0xff |
- * +------+---------+---------+---------+---------+------+------+
- */
- case 0x80: {
- // 0x80 support UCS2 0000~ffff
- GsmPDUHelper.writeHexOctet(0x80);
- numOctets--;
- // Now the str is UCS2 string, each character will take 2 octets.
- if (str.length * 2 > numOctets) {
- str = str.substring(0, Math.floor(numOctets / 2));
- }
- GsmPDUHelper.writeUCS2String(str);
-
- // trailing 0xff
- for (let i = str.length * 2; i < numOctets; i++) {
- GsmPDUHelper.writeHexOctet(0xff);
- }
- return str;
- }
- /**
- * +------+-----+--------------+-----+-----+-----+--------+------+
- * | 0x81 | len | base_pointer | Ch1 | Ch2 | ... | Ch_len | 0xff |
- * +------+-----+--------------+-----+-----+-----+--------+------+
- *
- * len: The length of characters.
- * base_pointer: 0hhh hhhh h000 0000
- * Ch_n: bit 8 = 0
- * GSM default alphabets
- * bit 8 = 1
- * UCS2 character whose char code is (Ch_n - base_pointer) | 0x80
- *
- */
- case 0x81: {
- GsmPDUHelper.writeHexOctet(0x81);
-
- if (str.length > (numOctets - 3)) {
- str = str.substring(0, numOctets - 3);
- }
-
- GsmPDUHelper.writeHexOctet(str.length);
- GsmPDUHelper.writeHexOctet((basePointer >> 7) & 0xff);
- numOctets -= 3;
- break;
- }
- /* +------+-----+------------------+------------------+-----+-----+-----+--------+
- * | 0x82 | len | base_pointer_msb | base_pointer_lsb | Ch1 | Ch2 | ... | Ch_len |
- * +------+-----+------------------+------------------+-----+-----+-----+--------+
- *
- * len: The length of characters.
- * base_pointer_msb, base_pointer_lsn: base_pointer
- * Ch_n: bit 8 = 0
- * GSM default alphabets
- * bit 8 = 1
- * UCS2 character whose char code is (Ch_n - base_pointer) | 0x80
- */
- case 0x82: {
- GsmPDUHelper.writeHexOctet(0x82);
-
- if (str.length > (numOctets - 4)) {
- str = str.substring(0, numOctets - 4);
- }
-
- GsmPDUHelper.writeHexOctet(str.length);
- GsmPDUHelper.writeHexOctet((basePointer >> 8) & 0xff);
- GsmPDUHelper.writeHexOctet(basePointer & 0xff);
- numOctets -= 4;
- break;
- }
- }
-
- if (scheme == 0x81 || scheme == 0x82) {
- for (let i = 0; i < str.length; i++) {
- let code = str.charCodeAt(i);
-
- // bit 8 = 0,
- // GSM default alphabets
- if (code >> 8 == 0) {
- GsmPDUHelper.writeHexOctet(code & 0x7F);
- } else {
- // bit 8 = 1,
- // UCS2 character whose char code is (code - basePointer) | 0x80
- GsmPDUHelper.writeHexOctet((code - basePointer) | 0x80);
- }
- }
-
- // trailing 0xff
- for (let i = 0; i < numOctets - str.length; i++) {
- GsmPDUHelper.writeHexOctet(0xff);
- }
- }
- return str;
- },
-
- /**
- * Read UCS2 String on UICC.
- *
- * @see TS 101.221, Annex A.
- * @param scheme
- * Coding scheme for UCS2 on UICC. One of 0x80, 0x81 or 0x82.
- * @param numOctets
- * Number of octets to be read as UCS2 string.
- */
- readICCUCS2String: function(scheme, numOctets) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let str = "";
- switch (scheme) {
- /**
- * +------+---------+---------+---------+---------+------+------+
- * | 0x80 | Ch1_msb | Ch1_lsb | Ch2_msb | Ch2_lsb | 0xff | 0xff |
- * +------+---------+---------+---------+---------+------+------+
- */
- case 0x80:
- let isOdd = numOctets % 2;
- let i;
- for (i = 0; i < numOctets - isOdd; i += 2) {
- let code = (GsmPDUHelper.readHexOctet() << 8) | GsmPDUHelper.readHexOctet();
- if (code == 0xffff) {
- i += 2;
- break;
- }
- str += String.fromCharCode(code);
- }
-
- // Skip trailing 0xff
- Buf.seekIncoming((numOctets - i) * Buf.PDU_HEX_OCTET_SIZE);
- break;
- case 0x81: // Fall through
- case 0x82:
- /**
- * +------+-----+--------+-----+-----+-----+--------+------+
- * | 0x81 | len | offset | Ch1 | Ch2 | ... | Ch_len | 0xff |
- * +------+-----+--------+-----+-----+-----+--------+------+
- *
- * len : The length of characters.
- * offset : 0hhh hhhh h000 0000
- * Ch_n: bit 8 = 0
- * GSM default alphabets
- * bit 8 = 1
- * UCS2 character whose char code is (Ch_n & 0x7f) + offset
- *
- * +------+-----+------------+------------+-----+-----+-----+--------+
- * | 0x82 | len | offset_msb | offset_lsb | Ch1 | Ch2 | ... | Ch_len |
- * +------+-----+------------+------------+-----+-----+-----+--------+
- *
- * len : The length of characters.
- * offset_msb, offset_lsn: offset
- * Ch_n: bit 8 = 0
- * GSM default alphabets
- * bit 8 = 1
- * UCS2 character whose char code is (Ch_n & 0x7f) + offset
- */
- let len = GsmPDUHelper.readHexOctet();
- let offset, headerLen;
- if (scheme == 0x81) {
- offset = GsmPDUHelper.readHexOctet() << 7;
- headerLen = 2;
- } else {
- offset = (GsmPDUHelper.readHexOctet() << 8) | GsmPDUHelper.readHexOctet();
- headerLen = 3;
- }
-
- for (let i = 0; i < len; i++) {
- let ch = GsmPDUHelper.readHexOctet();
- if (ch & 0x80) {
- // UCS2
- str += String.fromCharCode((ch & 0x7f) + offset);
- } else {
- // GSM 8bit
- let count = 0, gotUCS2 = 0;
- while ((i + count + 1 < len)) {
- count++;
- if (GsmPDUHelper.readHexOctet() & 0x80) {
- gotUCS2 = 1;
- break;
- }
- }
- // Unread.
- // +1 for the GSM alphabet indexed at i,
- Buf.seekIncoming(-1 * (count + 1) * Buf.PDU_HEX_OCTET_SIZE);
- str += this.read8BitUnpackedToString(count + 1 - gotUCS2);
- i += count - gotUCS2;
- }
- }
-
- // Skipping trailing 0xff
- Buf.seekIncoming((numOctets - len - headerLen) * Buf.PDU_HEX_OCTET_SIZE);
- break;
- }
- return str;
- },
-
- /**
- * Read Alpha Id and Dialling number from TS TS 151.011 clause 10.5.1
- *
- * @param recordSize The size of linear fixed record.
- */
- readAlphaIdDiallingNumber: function(recordSize) {
- let Buf = this.context.Buf;
- let length = Buf.readInt32();
-
- let alphaLen = recordSize - ADN_FOOTER_SIZE_BYTES;
- let alphaId = this.readAlphaIdentifier(alphaLen);
-
- let number = this.readNumberWithLength();
-
- // Skip unused octet, CCP
- Buf.seekIncoming(Buf.PDU_HEX_OCTET_SIZE);
-
- let extRecordNumber = this.context.GsmPDUHelper.readHexOctet();
- Buf.readStringDelimiter(length);
-
- let contact = null;
- if (alphaId || number) {
- contact = {alphaId: alphaId,
- number: number,
- extRecordNumber: extRecordNumber};
- }
-
- return contact;
- },
-
- /**
- * Write Alpha Identifier and Dialling number from TS 151.011 clause 10.5.1
- *
- * @param recordSize The size of linear fixed record.
- * @param alphaId Alpha Identifier to be written.
- * @param number Dialling Number to be written.
- * @param extRecordNumber The record identifier of the EXT.
- *
- * @return An object contains the alphaId and number
- * that have been written into Buf.
- */
- writeAlphaIdDiallingNumber: function(recordSize, alphaId, number, extRecordNumber) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- // Write String length
- let strLen = recordSize * 2;
- Buf.writeInt32(strLen);
-
- let alphaLen = recordSize - ADN_FOOTER_SIZE_BYTES;
- let writtenAlphaId = this.writeAlphaIdentifier(alphaLen, alphaId);
- let writtenNumber = this.writeNumberWithLength(number);
-
- // Write unused CCP octet 0xff.
- GsmPDUHelper.writeHexOctet(0xff);
- GsmPDUHelper.writeHexOctet((extRecordNumber != null) ? extRecordNumber : 0xff);
-
- Buf.writeStringDelimiter(strLen);
-
- return {alphaId: writtenAlphaId,
- number: writtenNumber};
- },
-
- /**
- * Read Alpha Identifier.
- *
- * @see TS 131.102
- *
- * @param numOctets
- * Number of octets to be read.
- *
- * It uses either
- * 1. SMS default 7-bit alphabet with bit 8 set to 0.
- * 2. UCS2 string.
- *
- * Unused bytes should be set to 0xff.
- */
- readAlphaIdentifier: function(numOctets) {
- if (numOctets === 0) {
- return "";
- }
-
- let temp;
- // Read the 1st octet to determine the encoding.
- if ((temp = this.context.GsmPDUHelper.readHexOctet()) == 0x80 ||
- temp == 0x81 ||
- temp == 0x82) {
- numOctets--;
- return this.readICCUCS2String(temp, numOctets);
- } else {
- let Buf = this.context.Buf;
- Buf.seekIncoming(-1 * Buf.PDU_HEX_OCTET_SIZE);
- return this.read8BitUnpackedToString(numOctets);
- }
- },
-
- /**
- * Write Alpha Identifier.
- *
- * @param numOctets
- * Total number of octets to be written. This includes the length of
- * alphaId and the length of trailing unused octets(0xff).
- * @param alphaId
- * Alpha Identifier to be written.
- *
- * @return The Alpha Identifier has been written into Buf.
- *
- * Unused octets will be written as 0xff.
- */
- writeAlphaIdentifier: function(numOctets, alphaId) {
- if (numOctets === 0) {
- return "";
- }
-
- // If alphaId is empty or it's of GSM 8 bit.
- if (!alphaId || this.context.ICCUtilsHelper.isGsm8BitAlphabet(alphaId)) {
- return this.writeStringTo8BitUnpacked(numOctets, alphaId);
- } else {
- return this.writeICCUCS2String(numOctets, alphaId);
- }
- },
-
- /**
- * Read Dialling number.
- *
- * @see TS 131.102
- *
- * @param len
- * The Length of BCD number.
- *
- * From TS 131.102, in EF_ADN, EF_FDN, the field 'Length of BCD number'
- * means the total bytes should be allocated to store the TON/NPI and
- * the dialing number.
- * For example, if the dialing number is 1234567890,
- * and the TON/NPI is 0x81,
- * The field 'Length of BCD number' should be 06, which is
- * 1 byte to store the TON/NPI, 0x81
- * 5 bytes to store the BCD number 2143658709.
- *
- * Here the definition of the length is different from SMS spec,
- * TS 23.040 9.1.2.5, which the length means
- * "number of useful semi-octets within the Address-Value field".
- */
- readDiallingNumber: function(len) {
- if (DEBUG) this.context.debug("PDU: Going to read Dialling number: " + len);
- if (len === 0) {
- return "";
- }
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- // TOA = TON + NPI
- let toa = GsmPDUHelper.readHexOctet();
-
- let number = GsmPDUHelper.readSwappedNibbleExtendedBcdString(len - 1);
- if (number.length <= 0) {
- if (DEBUG) this.context.debug("No number provided");
- return "";
- }
- if ((toa >> 4) == (PDU_TOA_INTERNATIONAL >> 4)) {
- number = '+' + number;
- }
- return number;
- },
-
- /**
- * Write Dialling Number.
- *
- * @param number The Dialling number
- */
- writeDiallingNumber: function(number) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let toa = PDU_TOA_ISDN; // 81
- if (number[0] == '+') {
- toa = PDU_TOA_INTERNATIONAL | PDU_TOA_ISDN; // 91
- number = number.substring(1);
- }
- GsmPDUHelper.writeHexOctet(toa);
- GsmPDUHelper.writeSwappedNibbleBCD(number);
- },
-
- readNumberWithLength: function() {
- let Buf = this.context.Buf;
- let number = "";
- let numLen = this.context.GsmPDUHelper.readHexOctet();
- if (numLen != 0xff) {
- if (numLen > ADN_MAX_BCD_NUMBER_BYTES) {
- if (DEBUG) {
- this.context.debug(
- "Error: invalid length of BCD number/SSC contents - " + numLen);
- }
- Buf.seekIncoming(ADN_MAX_BCD_NUMBER_BYTES * Buf.PDU_HEX_OCTET_SIZE);
- return number;
- }
-
- number = this.readDiallingNumber(numLen);
- Buf.seekIncoming((ADN_MAX_BCD_NUMBER_BYTES - numLen) * Buf.PDU_HEX_OCTET_SIZE);
- } else {
- Buf.seekIncoming(ADN_MAX_BCD_NUMBER_BYTES * Buf.PDU_HEX_OCTET_SIZE);
- }
-
- return number;
- },
-
- /**
- * Write Number with Length
- *
- * @param number The value to be written.
- *
- * @return The number has been written into Buf.
- */
- writeNumberWithLength: function(number) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- if (number) {
- let numStart = number[0] == "+" ? 1 : 0;
- let writtenNumber = number.substring(0, numStart) +
- number.substring(numStart)
- .replace(/[^0-9*#,]/g, "");
- let numDigits = writtenNumber.length - numStart;
-
- if (numDigits > ADN_MAX_NUMBER_DIGITS) {
- writtenNumber = writtenNumber.substring(0, ADN_MAX_NUMBER_DIGITS + numStart);
- numDigits = writtenNumber.length - numStart;
- }
-
- // +1 for TON/NPI
- let numLen = Math.ceil(numDigits / 2) + 1;
- GsmPDUHelper.writeHexOctet(numLen);
- this.writeDiallingNumber(writtenNumber.replace(/\*/g, "a")
- .replace(/\#/g, "b")
- .replace(/\,/g, "c"));
- // Write trailing 0xff of Dialling Number.
- for (let i = 0; i < ADN_MAX_BCD_NUMBER_BYTES - numLen; i++) {
- GsmPDUHelper.writeHexOctet(0xff);
- }
- return writtenNumber;
- } else {
- // +1 for numLen
- for (let i = 0; i < ADN_MAX_BCD_NUMBER_BYTES + 1; i++) {
- GsmPDUHelper.writeHexOctet(0xff);
- }
- return "";
- }
- }
-};
-
-function StkCommandParamsFactoryObject(aContext) {
- this.context = aContext;
-}
-StkCommandParamsFactoryObject.prototype = {
- context: null,
-
- createParam: function(cmdDetails, ctlvs, onComplete) {
- let method = this[cmdDetails.typeOfCommand];
- if (typeof method != "function") {
- if (DEBUG) {
- this.context.debug("Unknown proactive command " +
- cmdDetails.typeOfCommand.toString(16));
- }
- return;
- }
- method.call(this, cmdDetails, ctlvs, onComplete);
- },
-
- loadIcons: function(iconIdCtlvs, callback) {
- if (!iconIdCtlvs ||
- !this.context.ICCUtilsHelper.isICCServiceAvailable("IMG")) {
- callback(null);
- return;
- }
-
- let onerror = (function() {
- callback(null);
- }).bind(this);
-
- let onsuccess = (function(aIcons) {
- callback(aIcons);
- }).bind(this);
-
- this.context.IconLoader.loadIcons(iconIdCtlvs.map(aCtlv => aCtlv.value.identifier),
- onsuccess,
- onerror);
- },
-
- appendIconIfNecessary: function(iconIdCtlvs, result, onComplete) {
- this.loadIcons(iconIdCtlvs, (aIcons) => {
- if (aIcons) {
- result.icons = aIcons[0];
- result.iconSelfExplanatory =
- iconIdCtlvs[0].value.qualifier == 0 ? true : false;
- }
-
- onComplete(result);
- });
- },
-
- /**
- * Construct a param for Refresh.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processRefresh: function(cmdDetails, ctlvs, onComplete) {
- let refreshType = cmdDetails.commandQualifier;
- switch (refreshType) {
- case STK_REFRESH_FILE_CHANGE:
- case STK_REFRESH_NAA_INIT_AND_FILE_CHANGE:
- let ctlv = this.context.StkProactiveCmdHelper.searchForTag(
- COMPREHENSIONTLV_TAG_FILE_LIST, ctlvs);
- if (ctlv) {
- let list = ctlv.value.fileList;
- if (DEBUG) {
- this.context.debug("Refresh, list = " + list);
- }
- this.context.ICCRecordHelper.fetchICCRecords();
- }
- break;
- }
-
- onComplete(null);
- },
-
- /**
- * Construct a param for Poll Interval.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processPollInterval: function(cmdDetails, ctlvs, onComplete) {
- // Duration is mandatory.
- let ctlv = this.context.StkProactiveCmdHelper.searchForTag(
- COMPREHENSIONTLV_TAG_DURATION, ctlvs);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Poll Interval: Required value missing : Duration");
- }
-
- onComplete(ctlv.value);
- },
-
- /**
- * Construct a param for Poll Off.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processPollOff: function(cmdDetails, ctlvs, onComplete) {
- onComplete(null);
- },
-
- /**
- * Construct a param for Set Up Event list.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processSetUpEventList: function(cmdDetails, ctlvs, onComplete) {
- // Event list is mandatory.
- let ctlv = this.context.StkProactiveCmdHelper.searchForTag(
- COMPREHENSIONTLV_TAG_EVENT_LIST, ctlvs);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Event List: Required value missing : Event List");
- }
-
- onComplete(ctlv.value || { eventList: null });
- },
-
- /**
- * Construct a param for Setup Menu.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processSetupMenu: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let menu = {
- // Help information available.
- isHelpAvailable: !!(cmdDetails.commandQualifier & 0x80)
- };
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_ALPHA_ID,
- COMPREHENSIONTLV_TAG_ITEM,
- COMPREHENSIONTLV_TAG_ITEM_ID,
- COMPREHENSIONTLV_TAG_NEXT_ACTION_IND,
- COMPREHENSIONTLV_TAG_ICON_ID,
- COMPREHENSIONTLV_TAG_ICON_ID_LIST
- ]);
-
- // Alpha identifier is optional.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- if (ctlv) {
- menu.title = ctlv.value.identifier;
- }
-
- // Item data object for item 1 is mandatory.
- let menuCtlvs = selectedCtlvs[COMPREHENSIONTLV_TAG_ITEM];
- if (!menuCtlvs) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Menu: Required value missing : items");
- }
- menu.items = menuCtlvs.map(aCtlv => aCtlv.value);
-
- // Item identifier is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ITEM_ID);
- if (ctlv) {
- menu.defaultItem = ctlv.value.identifier - 1;
- }
-
- // Items next action indicator is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_NEXT_ACTION_IND);
- if (ctlv) {
- menu.nextActionList = ctlv.value;
- }
-
- // Icon identifier is optional.
- let iconIdCtlvs = null;
- let menuIconCtlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ICON_ID);
- if (menuIconCtlv) {
- iconIdCtlvs = [menuIconCtlv];
- }
-
- // Item icon identifier list is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ICON_ID_LIST);
- if (ctlv) {
- if (!iconIdCtlvs) {
- iconIdCtlvs = [];
- };
- let iconIdList = ctlv.value;
- iconIdCtlvs = iconIdCtlvs.concat(iconIdList.identifiers.map((aId) => {
- return {
- value: { qualifier: iconIdList.qualifier, identifier: aId }
- };
- }));
- }
-
- this.loadIcons(iconIdCtlvs, (aIcons) => {
- if (aIcons) {
- if (menuIconCtlv) {
- menu.iconSelfExplanatory =
- (iconIdCtlvs.shift().value.qualifier == 0) ? true: false;
- menu.icons = aIcons.shift();
- }
-
- for (let i = 0; i < aIcons.length; i++) {
- menu.items[i].icons = aIcons[i];
- menu.items[i].iconSelfExplanatory =
- (iconIdCtlvs[i].value.qualifier == 0) ? true: false;
- }
- }
-
- onComplete(menu);
- });
- },
-
- /**
- * Construct a param for Select Item.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processSelectItem: function(cmdDetails, ctlvs, onComplete) {
- this.processSetupMenu(cmdDetails, ctlvs, (menu) => {
- // The 1st bit and 2nd bit determines the presentation type.
- menu.presentationType = cmdDetails.commandQualifier & 0x03;
- onComplete(menu);
- });
- },
-
- /**
- * Construct a param for Display Text.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processDisplayText: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let textMsg = {
- isHighPriority: !!(cmdDetails.commandQualifier & 0x01),
- userClear: !!(cmdDetails.commandQualifier & 0x80)
- };
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_TEXT_STRING,
- COMPREHENSIONTLV_TAG_IMMEDIATE_RESPONSE,
- COMPREHENSIONTLV_TAG_DURATION,
- COMPREHENSIONTLV_TAG_ICON_ID
- ]);
-
- // Text string is mandatory.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_TEXT_STRING);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Display Text: Required value missing : Text String");
- }
- textMsg.text = ctlv.value.textString;
-
- // Immediate response is optional.
- textMsg.responseNeeded =
- !!(selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_IMMEDIATE_RESPONSE));
-
- // Duration is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_DURATION);
- if (ctlv) {
- textMsg.duration = ctlv.value;
- }
-
- // Icon identifier is optional.
- this.appendIconIfNecessary(selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null,
- textMsg,
- onComplete);
- },
-
- /**
- * Construct a param for Setup Idle Mode Text.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processSetUpIdleModeText: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let textMsg = {};
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_TEXT_STRING,
- COMPREHENSIONTLV_TAG_ICON_ID
- ]);
-
- // Text string is mandatory.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_TEXT_STRING);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Set Up Idle Text: Required value missing : Text String");
- }
- textMsg.text = ctlv.value.textString;
-
- // Icon identifier is optional.
- this.appendIconIfNecessary(selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null,
- textMsg,
- onComplete);
- },
-
- /**
- * Construct a param for Get Inkey.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processGetInkey: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let input = {
- minLength: 1,
- maxLength: 1,
- isAlphabet: !!(cmdDetails.commandQualifier & 0x01),
- isUCS2: !!(cmdDetails.commandQualifier & 0x02),
- // Character sets defined in bit 1 and bit 2 are disable and
- // the YES/NO reponse is required.
- isYesNoRequested: !!(cmdDetails.commandQualifier & 0x04),
- // Help information available.
- isHelpAvailable: !!(cmdDetails.commandQualifier & 0x80)
- };
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_TEXT_STRING,
- COMPREHENSIONTLV_TAG_DURATION,
- COMPREHENSIONTLV_TAG_ICON_ID
- ]);
-
- // Text string is mandatory.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_TEXT_STRING);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Get InKey: Required value missing : Text String");
- }
- input.text = ctlv.value.textString;
-
- // Duration is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_DURATION);
- if (ctlv) {
- input.duration = ctlv.value;
- }
-
- // Icon identifier is optional.
- this.appendIconIfNecessary(selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null,
- input,
- onComplete);
- },
-
- /**
- * Construct a param for Get Input.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processGetInput: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let input = {
- isAlphabet: !!(cmdDetails.commandQualifier & 0x01),
- isUCS2: !!(cmdDetails.commandQualifier & 0x02),
- // User input shall not be revealed
- hideInput: !!(cmdDetails.commandQualifier & 0x04),
- // User input in SMS packed format
- isPacked: !!(cmdDetails.commandQualifier & 0x08),
- // Help information available.
- isHelpAvailable: !!(cmdDetails.commandQualifier & 0x80)
- };
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_TEXT_STRING,
- COMPREHENSIONTLV_TAG_RESPONSE_LENGTH,
- COMPREHENSIONTLV_TAG_DEFAULT_TEXT,
- COMPREHENSIONTLV_TAG_ICON_ID
- ]);
-
- // Text string is mandatory.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_TEXT_STRING);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Get Input: Required value missing : Text String");
- }
- input.text = ctlv.value.textString;
-
- // Response length is mandatory.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_RESPONSE_LENGTH);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Get Input: Required value missing : Response Length");
- }
- input.minLength = ctlv.value.minLength;
- input.maxLength = ctlv.value.maxLength;
-
- // Default text is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_DEFAULT_TEXT);
- if (ctlv) {
- input.defaultText = ctlv.value.textString;
- }
-
- // Icon identifier is optional.
- this.appendIconIfNecessary(selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null,
- input,
- onComplete);
- },
-
- /**
- * Construct a param for SendSS/SMS/USSD/DTMF.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processEventNotify: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let textMsg = {};
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_ALPHA_ID,
- COMPREHENSIONTLV_TAG_ICON_ID
- ]);
-
- // Alpha identifier is optional.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- if (ctlv) {
- textMsg.text = ctlv.value.identifier;
- }
-
- // According to section 6.4.10 of |ETSI TS 102 223|:
- //
- // - if the alpha identifier is provided by the UICC and is a null data
- // object (i.e. length = '00' and no value part), this is an indication
- // that the terminal should not give any information to the user on the
- // fact that the terminal is sending a short message;
- //
- // - if the alpha identifier is not provided by the UICC, the terminal may
- // give information to the user concerning what is happening.
- //
- // ICCPDUHelper reads alpha id as an empty string if the length is zero,
- // hence we'll notify the caller when it's not an empty string.
- if (textMsg.text !== "") {
- // Icon identifier is optional.
- this.appendIconIfNecessary(selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null,
- textMsg,
- onComplete);
- }
- },
-
- /**
- * Construct a param for Setup Call.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processSetupCall: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let call = {};
- let confirmMessage = {};
- let callMessage = {};
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_ADDRESS,
- COMPREHENSIONTLV_TAG_ALPHA_ID,
- COMPREHENSIONTLV_TAG_ICON_ID,
- COMPREHENSIONTLV_TAG_DURATION
- ]);
-
- // Address is mandatory.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ADDRESS);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Set Up Call: Required value missing : Address");
- }
- call.address = ctlv.value.number;
-
- // Alpha identifier (user confirmation phase) is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- if (ctlv) {
- confirmMessage.text = ctlv.value.identifier;
- call.confirmMessage = confirmMessage;
- }
-
- // Alpha identifier (call set up phase) is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- if (ctlv) {
- callMessage.text = ctlv.value.identifier;
- call.callMessage = callMessage;
- }
-
- // Duration is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_DURATION);
- if (ctlv) {
- call.duration = ctlv.value;
- }
-
- // Icon identifier is optional.
- let iconIdCtlvs = selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null;
- this.loadIcons(iconIdCtlvs, (aIcons) => {
- if (aIcons) {
- confirmMessage.icons = aIcons[0];
- confirmMessage.iconSelfExplanatory =
- (iconIdCtlvs[0].value.qualifier == 0) ? true: false;
- call.confirmMessage = confirmMessage;
-
- if (aIcons.length > 1) {
- callMessage.icons = aIcons[1];
- callMessage.iconSelfExplanatory =
- (iconIdCtlvs[1].value.qualifier == 0) ? true: false;
- call.callMessage = callMessage;
- }
- }
-
- onComplete(call);
- });
- },
-
- /**
- * Construct a param for Launch Browser.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processLaunchBrowser: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let browser = {
- mode: cmdDetails.commandQualifier & 0x03
- };
- let confirmMessage = {};
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_URL,
- COMPREHENSIONTLV_TAG_ALPHA_ID,
- COMPREHENSIONTLV_TAG_ICON_ID
- ]);
-
- // URL is mandatory.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_URL);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Launch Browser: Required value missing : URL");
- }
- browser.url = ctlv.value.url;
-
- // Alpha identifier is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- if (ctlv) {
- confirmMessage.text = ctlv.value.identifier;
- browser.confirmMessage = confirmMessage;
- }
-
- // Icon identifier is optional.
- let iconIdCtlvs = selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null;
- this.loadIcons(iconIdCtlvs, (aIcons) => {
- if (aIcons) {
- confirmMessage.icons = aIcons[0];
- confirmMessage.iconSelfExplanatory =
- (iconIdCtlvs[0].value.qualifier == 0) ? true: false;
- browser.confirmMessage = confirmMessage;
- }
-
- onComplete(browser);
- });
- },
-
- /**
- * Construct a param for Play Tone.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processPlayTone: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let playTone = {
- // The vibrate is only defined in TS 102.223.
- isVibrate: !!(cmdDetails.commandQualifier & 0x01)
- };
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_ALPHA_ID,
- COMPREHENSIONTLV_TAG_TONE,
- COMPREHENSIONTLV_TAG_DURATION,
- COMPREHENSIONTLV_TAG_ICON_ID
- ]);
-
- // Alpha identifier is optional.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- if (ctlv) {
- playTone.text = ctlv.value.identifier;
- }
-
- // Tone is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_TONE);
- if (ctlv) {
- playTone.tone = ctlv.value.tone;
- }
-
- // Duration is optional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_DURATION);
- if (ctlv) {
- playTone.duration = ctlv.value;
- }
-
- // Icon identifier is optional.
- this.appendIconIfNecessary(selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null,
- playTone,
- onComplete);
- },
-
- /**
- * Construct a param for Provide Local Information.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processProvideLocalInfo: function(cmdDetails, ctlvs, onComplete) {
- let provideLocalInfo = {
- localInfoType: cmdDetails.commandQualifier
- };
-
- onComplete(provideLocalInfo);
- },
-
- /**
- * Construct a param for Timer Management.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processTimerManagement: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let timer = {
- timerAction: cmdDetails.commandQualifier
- };
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_TIMER_IDENTIFIER,
- COMPREHENSIONTLV_TAG_TIMER_VALUE
- ]);
-
- // Timer identifier is mandatory.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_TIMER_IDENTIFIER);
- if (!ctlv) {
- this.context.RIL.sendStkTerminalResponse({
- command: cmdDetails,
- resultCode: STK_RESULT_REQUIRED_VALUES_MISSING});
- throw new Error("Stk Timer Management: Required value missing : Timer Identifier");
- }
- timer.timerId = ctlv.value.timerId;
-
- // Timer value is conditional.
- ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_TIMER_VALUE);
- if (ctlv) {
- timer.timerValue = ctlv.value.timerValue;
- }
-
- onComplete(timer);
- },
-
- /**
- * Construct a param for BIP commands.
- *
- * @param cmdDetails
- * The value object of CommandDetails TLV.
- * @param ctlvs
- * The all TLVs in this proactive command.
- * @param onComplete
- * Callback to be called when complete.
- */
- processBipMessage: function(cmdDetails, ctlvs, onComplete) {
- let StkProactiveCmdHelper = this.context.StkProactiveCmdHelper;
- let bipMsg = {};
-
- let selectedCtlvs = StkProactiveCmdHelper.searchForSelectedTags(ctlvs, [
- COMPREHENSIONTLV_TAG_ALPHA_ID,
- COMPREHENSIONTLV_TAG_ICON_ID
- ]);
-
- // Alpha identifier is optional.
- let ctlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- if (ctlv) {
- bipMsg.text = ctlv.value.identifier;
- }
-
- // Icon identifier is optional.
- this.appendIconIfNecessary(selectedCtlvs[COMPREHENSIONTLV_TAG_ICON_ID] || null,
- bipMsg,
- onComplete);
- }
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_REFRESH] = function STK_CMD_REFRESH(cmdDetails, ctlvs, onComplete) {
- return this.processRefresh(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_POLL_INTERVAL] = function STK_CMD_POLL_INTERVAL(cmdDetails, ctlvs, onComplete) {
- return this.processPollInterval(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_POLL_OFF] = function STK_CMD_POLL_OFF(cmdDetails, ctlvs, onComplete) {
- return this.processPollOff(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_PROVIDE_LOCAL_INFO] = function STK_CMD_PROVIDE_LOCAL_INFO(cmdDetails, ctlvs, onComplete) {
- return this.processProvideLocalInfo(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SET_UP_EVENT_LIST] = function STK_CMD_SET_UP_EVENT_LIST(cmdDetails, ctlvs, onComplete) {
- return this.processSetUpEventList(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SET_UP_MENU] = function STK_CMD_SET_UP_MENU(cmdDetails, ctlvs, onComplete) {
- return this.processSetupMenu(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SELECT_ITEM] = function STK_CMD_SELECT_ITEM(cmdDetails, ctlvs, onComplete) {
- return this.processSelectItem(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_DISPLAY_TEXT] = function STK_CMD_DISPLAY_TEXT(cmdDetails, ctlvs, onComplete) {
- return this.processDisplayText(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SET_UP_IDLE_MODE_TEXT] = function STK_CMD_SET_UP_IDLE_MODE_TEXT(cmdDetails, ctlvs, onComplete) {
- return this.processSetUpIdleModeText(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_GET_INKEY] = function STK_CMD_GET_INKEY(cmdDetails, ctlvs, onComplete) {
- return this.processGetInkey(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_GET_INPUT] = function STK_CMD_GET_INPUT(cmdDetails, ctlvs, onComplete) {
- return this.processGetInput(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SEND_SS] = function STK_CMD_SEND_SS(cmdDetails, ctlvs, onComplete) {
- return this.processEventNotify(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SEND_USSD] = function STK_CMD_SEND_USSD(cmdDetails, ctlvs, onComplete) {
- return this.processEventNotify(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SEND_SMS] = function STK_CMD_SEND_SMS(cmdDetails, ctlvs, onComplete) {
- return this.processEventNotify(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SEND_DTMF] = function STK_CMD_SEND_DTMF(cmdDetails, ctlvs, onComplete) {
- return this.processEventNotify(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SET_UP_CALL] = function STK_CMD_SET_UP_CALL(cmdDetails, ctlvs, onComplete) {
- return this.processSetupCall(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_LAUNCH_BROWSER] = function STK_CMD_LAUNCH_BROWSER(cmdDetails, ctlvs, onComplete) {
- return this.processLaunchBrowser(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_PLAY_TONE] = function STK_CMD_PLAY_TONE(cmdDetails, ctlvs, onComplete) {
- return this.processPlayTone(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_TIMER_MANAGEMENT] = function STK_CMD_TIMER_MANAGEMENT(cmdDetails, ctlvs, onComplete) {
- return this.processTimerManagement(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_OPEN_CHANNEL] = function STK_CMD_OPEN_CHANNEL(cmdDetails, ctlvs, onComplete) {
- return this.processBipMessage(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_CLOSE_CHANNEL] = function STK_CMD_CLOSE_CHANNEL(cmdDetails, ctlvs, onComplete) {
- return this.processBipMessage(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_RECEIVE_DATA] = function STK_CMD_RECEIVE_DATA(cmdDetails, ctlvs, onComplete) {
- return this.processBipMessage(cmdDetails, ctlvs, onComplete);
-};
-StkCommandParamsFactoryObject.prototype[STK_CMD_SEND_DATA] = function STK_CMD_SEND_DATA(cmdDetails, ctlvs, onComplete) {
- return this.processBipMessage(cmdDetails, ctlvs, onComplete);
-};
-
-function StkProactiveCmdHelperObject(aContext) {
- this.context = aContext;
-}
-StkProactiveCmdHelperObject.prototype = {
- context: null,
-
- retrieve: function(tag, length) {
- let method = this[tag];
- if (typeof method != "function") {
- if (DEBUG) {
- this.context.debug("Unknown comprehension tag " + tag.toString(16));
- }
- let Buf = this.context.Buf;
- Buf.seekIncoming(length * Buf.PDU_HEX_OCTET_SIZE);
- return null;
- }
- return method.call(this, length);
- },
-
- /**
- * Command Details.
- *
- * | Byte | Description | Length |
- * | 1 | Command details Tag | 1 |
- * | 2 | Length = 03 | 1 |
- * | 3 | Command number | 1 |
- * | 4 | Type of Command | 1 |
- * | 5 | Command Qualifier | 1 |
- */
- retrieveCommandDetails: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let cmdDetails = {
- commandNumber: GsmPDUHelper.readHexOctet(),
- typeOfCommand: GsmPDUHelper.readHexOctet(),
- commandQualifier: GsmPDUHelper.readHexOctet()
- };
- return cmdDetails;
- },
-
- /**
- * Device Identities.
- *
- * | Byte | Description | Length |
- * | 1 | Device Identity Tag | 1 |
- * | 2 | Length = 02 | 1 |
- * | 3 | Source device Identity | 1 |
- * | 4 | Destination device Id | 1 |
- */
- retrieveDeviceId: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let deviceId = {
- sourceId: GsmPDUHelper.readHexOctet(),
- destinationId: GsmPDUHelper.readHexOctet()
- };
- return deviceId;
- },
-
- /**
- * Alpha Identifier.
- *
- * | Byte | Description | Length |
- * | 1 | Alpha Identifier Tag | 1 |
- * | 2 ~ (Y-1)+2 | Length (X) | Y |
- * | (Y-1)+3 ~ | Alpha identfier | X |
- * | (Y-1)+X+2 | | |
- */
- retrieveAlphaId: function(length) {
- let alphaId = {
- identifier: this.context.ICCPDUHelper.readAlphaIdentifier(length)
- };
- return alphaId;
- },
-
- /**
- * Duration.
- *
- * | Byte | Description | Length |
- * | 1 | Response Length Tag | 1 |
- * | 2 | Lenth = 02 | 1 |
- * | 3 | Time unit | 1 |
- * | 4 | Time interval | 1 |
- */
- retrieveDuration: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let duration = {
- timeUnit: GsmPDUHelper.readHexOctet(),
- timeInterval: GsmPDUHelper.readHexOctet(),
- };
- return duration;
- },
-
- /**
- * Address.
- *
- * | Byte | Description | Length |
- * | 1 | Alpha Identifier Tag | 1 |
- * | 2 ~ (Y-1)+2 | Length (X) | Y |
- * | (Y-1)+3 | TON and NPI | 1 |
- * | (Y-1)+4 ~ | Dialling number | X |
- * | (Y-1)+X+2 | | |
- */
- retrieveAddress: function(length) {
- let address = {
- number : this.context.ICCPDUHelper.readDiallingNumber(length)
- };
- return address;
- },
-
- /**
- * Text String.
- *
- * | Byte | Description | Length |
- * | 1 | Text String Tag | 1 |
- * | 2 ~ (Y-1)+2 | Length (X) | Y |
- * | (Y-1)+3 | Data coding scheme | 1 |
- * | (Y-1)+4~ | Text String | X |
- * | (Y-1)+X+2 | | |
- */
- retrieveTextString: function(length) {
- if (!length) {
- // null string.
- return {textString: null};
- }
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let text = {
- codingScheme: GsmPDUHelper.readHexOctet()
- };
-
- length--; // -1 for the codingScheme.
- switch (text.codingScheme & 0x0c) {
- case STK_TEXT_CODING_GSM_7BIT_PACKED:
- text.textString =
- GsmPDUHelper.readSeptetsToString(Math.floor(length * 8 / 7), 0, 0, 0);
- break;
- case STK_TEXT_CODING_GSM_8BIT:
- text.textString =
- this.context.ICCPDUHelper.read8BitUnpackedToString(length);
- break;
- case STK_TEXT_CODING_UCS2:
- text.textString = GsmPDUHelper.readUCS2String(length);
- break;
- }
- return text;
- },
-
- /**
- * Tone.
- *
- * | Byte | Description | Length |
- * | 1 | Tone Tag | 1 |
- * | 2 | Lenth = 01 | 1 |
- * | 3 | Tone | 1 |
- */
- retrieveTone: function(length) {
- let tone = {
- tone: this.context.GsmPDUHelper.readHexOctet(),
- };
- return tone;
- },
-
- /**
- * Item.
- *
- * | Byte | Description | Length |
- * | 1 | Item Tag | 1 |
- * | 2 ~ (Y-1)+2 | Length (X) | Y |
- * | (Y-1)+3 | Identifier of item | 1 |
- * | (Y-1)+4 ~ | Text string of item | X |
- * | (Y-1)+X+2 | | |
- */
- retrieveItem: function(length) {
- // TS 102.223 ,clause 6.6.7 SET-UP MENU
- // If the "Item data object for item 1" is a null data object
- // (i.e. length = '00' and no value part), this is an indication to the ME
- // to remove the existing menu from the menu system in the ME.
- if (!length) {
- return null;
- }
- let item = {
- identifier: this.context.GsmPDUHelper.readHexOctet(),
- text: this.context.ICCPDUHelper.readAlphaIdentifier(length - 1)
- };
- return item;
- },
-
- /**
- * Item Identifier.
- *
- * | Byte | Description | Length |
- * | 1 | Item Identifier Tag | 1 |
- * | 2 | Lenth = 01 | 1 |
- * | 3 | Identifier of Item chosen | 1 |
- */
- retrieveItemId: function(length) {
- let itemId = {
- identifier: this.context.GsmPDUHelper.readHexOctet()
- };
- return itemId;
- },
-
- /**
- * Response Length.
- *
- * | Byte | Description | Length |
- * | 1 | Response Length Tag | 1 |
- * | 2 | Lenth = 02 | 1 |
- * | 3 | Minimum length of response | 1 |
- * | 4 | Maximum length of response | 1 |
- */
- retrieveResponseLength: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let rspLength = {
- minLength : GsmPDUHelper.readHexOctet(),
- maxLength : GsmPDUHelper.readHexOctet()
- };
- return rspLength;
- },
-
- /**
- * File List.
- *
- * | Byte | Description | Length |
- * | 1 | File List Tag | 1 |
- * | 2 ~ (Y-1)+2 | Length (X) | Y |
- * | (Y-1)+3 | Number of files | 1 |
- * | (Y-1)+4 ~ | Files | X |
- * | (Y-1)+X+2 | | |
- */
- retrieveFileList: function(length) {
- let num = this.context.GsmPDUHelper.readHexOctet();
- let fileList = "";
- length--; // -1 for the num octet.
- for (let i = 0; i < 2 * length; i++) {
- // Didn't use readHexOctet here,
- // otherwise 0x00 will be "0", not "00"
- fileList += String.fromCharCode(this.context.Buf.readUint16());
- }
- return {
- fileList: fileList
- };
- },
-
- /**
- * Default Text.
- *
- * Same as Text String.
- */
- retrieveDefaultText: function(length) {
- return this.retrieveTextString(length);
- },
-
- /**
- * Event List.
- */
- retrieveEventList: function(length) {
- if (!length) {
- // null means an indication to ME to remove the existing list of events
- // in ME.
- return null;
- }
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let eventList = [];
- for (let i = 0; i < length; i++) {
- eventList.push(GsmPDUHelper.readHexOctet());
- }
- return {
- eventList: eventList
- };
- },
-
- /**
- * Icon Id.
- *
- * | Byte | Description | Length |
- * | 1 | Icon Identifier Tag | 1 |
- * | 2 | Length = 02 | 1 |
- * | 3 | Icon qualifier | 1 |
- * | 4 | Icon identifier | 1 |
- */
- retrieveIconId: function(length) {
- if (!length) {
- return null;
- }
-
- let iconId = {
- qualifier: this.context.GsmPDUHelper.readHexOctet(),
- identifier: this.context.GsmPDUHelper.readHexOctet()
- };
- return iconId;
- },
-
- /**
- * Icon Id List.
- *
- * | Byte | Description | Length |
- * | 1 | Icon Identifier Tag | 1 |
- * | 2 | Length = X | 1 |
- * | 3 | Icon qualifier | 1 |
- * | 4~ | Icon identifier | X-1 |
- * | 4+X-2 | | |
- */
- retrieveIconIdList: function(length) {
- if (!length) {
- return null;
- }
-
- let iconIdList = {
- qualifier: this.context.GsmPDUHelper.readHexOctet(),
- identifiers: []
- };
- for (let i = 0; i < length - 1; i++) {
- iconIdList.identifiers.push(this.context.GsmPDUHelper.readHexOctet());
- }
- return iconIdList;
- },
-
- /**
- * Timer Identifier.
- *
- * | Byte | Description | Length |
- * | 1 | Timer Identifier Tag | 1 |
- * | 2 | Length = 01 | 1 |
- * | 3 | Timer Identifier | 1 |
- */
- retrieveTimerId: function(length) {
- let id = {
- timerId: this.context.GsmPDUHelper.readHexOctet()
- };
- return id;
- },
-
- /**
- * Timer Value.
- *
- * | Byte | Description | Length |
- * | 1 | Timer Value Tag | 1 |
- * | 2 | Length = 03 | 1 |
- * | 3 | Hour | 1 |
- * | 4 | Minute | 1 |
- * | 5 | Second | 1 |
- */
- retrieveTimerValue: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let value = {
- timerValue: (GsmPDUHelper.readSwappedNibbleBcdNum(1) * 60 * 60) +
- (GsmPDUHelper.readSwappedNibbleBcdNum(1) * 60) +
- (GsmPDUHelper.readSwappedNibbleBcdNum(1))
- };
- return value;
- },
-
- /**
- * Immediate Response.
- *
- * | Byte | Description | Length |
- * | 1 | Immediate Response Tag | 1 |
- * | 2 | Length = 00 | 1 |
- */
- retrieveImmediaResponse: function(length) {
- return {};
- },
-
- /**
- * URL
- *
- * | Byte | Description | Length |
- * | 1 | URL Tag | 1 |
- * | 2 ~ (Y+1) | Length(X) | Y |
- * | (Y+2) ~ | URL | X |
- * | (Y+1+X) | | |
- */
- retrieveUrl: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let s = "";
- for (let i = 0; i < length; i++) {
- s += String.fromCharCode(GsmPDUHelper.readHexOctet());
- }
- return {url: s};
- },
-
- /**
- * Next Action Indicator List.
- *
- * | Byte | Description | Length |
- * | 1 | Next Action tag | 1 |
- * | 1 | Length(X) | 1 |
- * | 3~ | Next Action List | X |
- * | 3+X-1 | | |
- */
- retrieveNextActionList: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let nextActionList = [];
- for (let i = 0; i < length; i++) {
- nextActionList.push(GsmPDUHelper.readHexOctet());
- }
- return nextActionList;
- },
-
- searchForTag: function(tag, ctlvs) {
- for (let ctlv of ctlvs) {
- if ((ctlv.tag & ~COMPREHENSIONTLV_FLAG_CR) == tag) {
- return ctlv;
- }
- }
- return null;
- },
-
- searchForSelectedTags: function(ctlvs, tags) {
- let ret = {
- // Handy utility to de-queue the 1st ctlv of the specified tag.
- retrieve: function(aTag) {
- return (this[aTag]) ? this[aTag].shift() : null;
- }
- };
-
- ctlvs.forEach((aCtlv) => {
- tags.forEach((aTag) => {
- if ((aCtlv.tag & ~COMPREHENSIONTLV_FLAG_CR) == aTag) {
- if (!ret[aTag]) {
- ret[aTag] = [];
- }
- ret[aTag].push(aCtlv);
- }
- });
- });
-
- return ret;
- },
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_COMMAND_DETAILS] = function COMPREHENSIONTLV_TAG_COMMAND_DETAILS(length) {
- return this.retrieveCommandDetails(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_DEVICE_ID] = function COMPREHENSIONTLV_TAG_DEVICE_ID(length) {
- return this.retrieveDeviceId(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_ALPHA_ID] = function COMPREHENSIONTLV_TAG_ALPHA_ID(length) {
- return this.retrieveAlphaId(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_DURATION] = function COMPREHENSIONTLV_TAG_DURATION(length) {
- return this.retrieveDuration(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_ADDRESS] = function COMPREHENSIONTLV_TAG_ADDRESS(length) {
- return this.retrieveAddress(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_TEXT_STRING] = function COMPREHENSIONTLV_TAG_TEXT_STRING(length) {
- return this.retrieveTextString(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_TONE] = function COMPREHENSIONTLV_TAG_TONE(length) {
- return this.retrieveTone(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_ITEM] = function COMPREHENSIONTLV_TAG_ITEM(length) {
- return this.retrieveItem(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_ITEM_ID] = function COMPREHENSIONTLV_TAG_ITEM_ID(length) {
- return this.retrieveItemId(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_RESPONSE_LENGTH] = function COMPREHENSIONTLV_TAG_RESPONSE_LENGTH(length) {
- return this.retrieveResponseLength(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_FILE_LIST] = function COMPREHENSIONTLV_TAG_FILE_LIST(length) {
- return this.retrieveFileList(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_DEFAULT_TEXT] = function COMPREHENSIONTLV_TAG_DEFAULT_TEXT(length) {
- return this.retrieveDefaultText(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_EVENT_LIST] = function COMPREHENSIONTLV_TAG_EVENT_LIST(length) {
- return this.retrieveEventList(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_ICON_ID] = function COMPREHENSIONTLV_TAG_ICON_ID(length) {
- return this.retrieveIconId(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_ICON_ID_LIST] = function COMPREHENSIONTLV_TAG_ICON_ID_LIST(length) {
- return this.retrieveIconIdList(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_TIMER_IDENTIFIER] = function COMPREHENSIONTLV_TAG_TIMER_IDENTIFIER(length) {
- return this.retrieveTimerId(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_TIMER_VALUE] = function COMPREHENSIONTLV_TAG_TIMER_VALUE(length) {
- return this.retrieveTimerValue(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_IMMEDIATE_RESPONSE] = function COMPREHENSIONTLV_TAG_IMMEDIATE_RESPONSE(length) {
- return this.retrieveImmediaResponse(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_URL] = function COMPREHENSIONTLV_TAG_URL(length) {
- return this.retrieveUrl(length);
-};
-StkProactiveCmdHelperObject.prototype[COMPREHENSIONTLV_TAG_NEXT_ACTION_IND] = function COMPREHENSIONTLV_TAG_NEXT_ACTION_IND(length) {
- return this.retrieveNextActionList(length);
-};
-
-function ComprehensionTlvHelperObject(aContext) {
- this.context = aContext;
-}
-ComprehensionTlvHelperObject.prototype = {
- context: null,
-
- /**
- * Decode raw data to a Comprehension-TLV.
- */
- decode: function() {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let hlen = 0; // For header(tag field + length field) length.
- let temp = GsmPDUHelper.readHexOctet();
- hlen++;
-
- // TS 101.220, clause 7.1.1
- let tag, cr;
- switch (temp) {
- // TS 101.220, clause 7.1.1
- case 0x0: // Not used.
- case 0xff: // Not used.
- case 0x80: // Reserved for future use.
- throw new Error("Invalid octet when parsing Comprehension TLV :" + temp);
- case 0x7f: // Tag is three byte format.
- // TS 101.220 clause 7.1.1.2.
- // | Byte 1 | Byte 2 | Byte 3 |
- // | | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | |
- // | 0x7f |CR | Tag Value |
- tag = (GsmPDUHelper.readHexOctet() << 8) | GsmPDUHelper.readHexOctet();
- hlen += 2;
- cr = (tag & 0x8000) !== 0;
- tag &= ~0x8000;
- break;
- default: // Tag is single byte format.
- tag = temp;
- // TS 101.220 clause 7.1.1.1.
- // | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
- // |CR | Tag Value |
- cr = (tag & 0x80) !== 0;
- tag &= ~0x80;
- }
-
- // TS 101.220 clause 7.1.2, Length Encoding.
- // Length | Byte 1 | Byte 2 | Byte 3 | Byte 4 |
- // 0 - 127 | 00 - 7f | N/A | N/A | N/A |
- // 128-255 | 81 | 80 - ff| N/A | N/A |
- // 256-65535| 82 | 0100 - ffff | N/A |
- // 65536- | 83 | 010000 - ffffff |
- // 16777215
- //
- // Length errors: TS 11.14, clause 6.10.6
-
- let length; // Data length.
- temp = GsmPDUHelper.readHexOctet();
- hlen++;
- if (temp < 0x80) {
- length = temp;
- } else if (temp == 0x81) {
- length = GsmPDUHelper.readHexOctet();
- hlen++;
- if (length < 0x80) {
- throw new Error("Invalid length in Comprehension TLV :" + length);
- }
- } else if (temp == 0x82) {
- length = (GsmPDUHelper.readHexOctet() << 8) | GsmPDUHelper.readHexOctet();
- hlen += 2;
- if (lenth < 0x0100) {
- throw new Error("Invalid length in 3-byte Comprehension TLV :" + length);
- }
- } else if (temp == 0x83) {
- length = (GsmPDUHelper.readHexOctet() << 16) |
- (GsmPDUHelper.readHexOctet() << 8) |
- GsmPDUHelper.readHexOctet();
- hlen += 3;
- if (length < 0x010000) {
- throw new Error("Invalid length in 4-byte Comprehension TLV :" + length);
- }
- } else {
- throw new Error("Invalid octet in Comprehension TLV :" + temp);
- }
-
- let ctlv = {
- tag: tag,
- length: length,
- value: this.context.StkProactiveCmdHelper.retrieve(tag, length),
- cr: cr,
- hlen: hlen
- };
- return ctlv;
- },
-
- decodeChunks: function(length) {
- let chunks = [];
- let index = 0;
- while (index < length) {
- let tlv = this.decode();
- chunks.push(tlv);
- index += tlv.length;
- index += tlv.hlen;
- }
- return chunks;
- },
-
- /**
- * Write Location Info Comprehension TLV.
- *
- * @param loc location Information.
- */
- writeLocationInfoTlv: function(loc) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_LOCATION_INFO |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(loc.gsmCellId > 0xffff ? 9 : 7);
- // From TS 11.14, clause 12.19
- // "The mobile country code (MCC), the mobile network code (MNC),
- // the location area code (LAC) and the cell ID are
- // coded as in TS 04.08."
- // And from TS 04.08 and TS 24.008,
- // the format is as follows:
- //
- // MCC = MCC_digit_1 + MCC_digit_2 + MCC_digit_3
- //
- // 8 7 6 5 4 3 2 1
- // +-------------+-------------+
- // | MCC digit 2 | MCC digit 1 | octet 2
- // | MNC digit 3 | MCC digit 3 | octet 3
- // | MNC digit 2 | MNC digit 1 | octet 4
- // +-------------+-------------+
- //
- // Also in TS 24.008
- // "However a network operator may decide to
- // use only two digits in the MNC in the LAI over the
- // radio interface. In this case, bits 5 to 8 of octet 3
- // shall be coded as '1111'".
-
- // MCC & MNC, 3 octets
- let mcc = loc.mcc, mnc;
- if (loc.mnc.length == 2) {
- mnc = "F" + loc.mnc;
- } else {
- mnc = loc.mnc[2] + loc.mnc[0] + loc.mnc[1];
- }
- GsmPDUHelper.writeSwappedNibbleBCD(mcc + mnc);
-
- // LAC, 2 octets
- GsmPDUHelper.writeHexOctet((loc.gsmLocationAreaCode >> 8) & 0xff);
- GsmPDUHelper.writeHexOctet(loc.gsmLocationAreaCode & 0xff);
-
- // Cell Id
- if (loc.gsmCellId > 0xffff) {
- // UMTS/WCDMA, gsmCellId is 28 bits.
- GsmPDUHelper.writeHexOctet((loc.gsmCellId >> 24) & 0xff);
- GsmPDUHelper.writeHexOctet((loc.gsmCellId >> 16) & 0xff);
- GsmPDUHelper.writeHexOctet((loc.gsmCellId >> 8) & 0xff);
- GsmPDUHelper.writeHexOctet(loc.gsmCellId & 0xff);
- } else {
- // GSM, gsmCellId is 16 bits.
- GsmPDUHelper.writeHexOctet((loc.gsmCellId >> 8) & 0xff);
- GsmPDUHelper.writeHexOctet(loc.gsmCellId & 0xff);
- }
- },
-
- /**
- * Given a geckoError string, this function translates it into cause value
- * and write the value into buffer.
- *
- * @param geckoError Error string that is passed to gecko.
- */
- writeCauseTlv: function(geckoError) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let cause = -1;
- for (let errorNo in RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR) {
- if (geckoError == RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[errorNo]) {
- cause = errorNo;
- break;
- }
- }
-
- // Causes specified in 10.5.4.11 of TS 04.08 are less than 128.
- // we can ignore causes > 127 since Cause TLV is optional in
- // STK_EVENT_TYPE_CALL_DISCONNECTED.
- if (cause > 127) {
- return;
- }
-
- cause = (cause == -1) ? ERROR_SUCCESS : cause;
-
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_CAUSE |
- COMPREHENSIONTLV_FLAG_CR);
- GsmPDUHelper.writeHexOctet(2); // For single cause value.
-
- // TS 04.08, clause 10.5.4.11:
- // Code Standard : Standard defined for GSM PLMNS
- // Location: User
- GsmPDUHelper.writeHexOctet(0x60);
-
- // TS 04.08, clause 10.5.4.11: ext bit = 1 + 7 bits for cause.
- // +-----------------+----------------------------------+
- // | Ext = 1 (1 bit) | Cause (7 bits) |
- // +-----------------+----------------------------------+
- GsmPDUHelper.writeHexOctet(0x80 | cause);
- },
-
- writeDateTimeZoneTlv: function(date) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_DATE_TIME_ZONE);
- GsmPDUHelper.writeHexOctet(7);
- GsmPDUHelper.writeTimestamp(date);
- },
-
- writeLanguageTlv: function(language) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_LANGUAGE);
- GsmPDUHelper.writeHexOctet(2);
-
- // ISO 639-1, Alpha-2 code
- // TS 123.038, clause 6.2.1, GSM 7 bit Default Alphabet
- GsmPDUHelper.writeHexOctet(
- PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT].indexOf(language[0]));
- GsmPDUHelper.writeHexOctet(
- PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT].indexOf(language[1]));
- },
-
- /**
- * Write Timer Value Comprehension TLV.
- *
- * @param seconds length of time during of the timer.
- * @param cr Comprehension Required or not
- */
- writeTimerValueTlv: function(seconds, cr) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_TIMER_VALUE |
- (cr ? COMPREHENSIONTLV_FLAG_CR : 0));
- GsmPDUHelper.writeHexOctet(3);
-
- // TS 102.223, clause 8.38
- // +----------------+------------------+-------------------+
- // | hours (1 byte) | minutes (1 btye) | seconds (1 byte) |
- // +----------------+------------------+-------------------+
- GsmPDUHelper.writeSwappedNibbleBCDNum(Math.floor(seconds / 60 / 60));
- GsmPDUHelper.writeSwappedNibbleBCDNum(Math.floor(seconds / 60) % 60);
- GsmPDUHelper.writeSwappedNibbleBCDNum(Math.floor(seconds) % 60);
- },
-
- writeTextStringTlv: function(text, coding) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let buf = GsmPDUHelper.writeWithBuffer(() => {
- // Write Coding.
- GsmPDUHelper.writeHexOctet(coding);
-
- // Write Text String.
- switch (coding) {
- case STK_TEXT_CODING_UCS2:
- GsmPDUHelper.writeUCS2String(text);
- break;
- case STK_TEXT_CODING_GSM_7BIT_PACKED:
- GsmPDUHelper.writeStringAsSeptets(text, 0, 0, 0);
- break;
- case STK_TEXT_CODING_GSM_8BIT:
- GsmPDUHelper.writeStringAs8BitUnpacked(text);
- break;
- }
- });
-
- let length = buf.length;
- if (length) {
- // Write Tag.
- GsmPDUHelper.writeHexOctet(COMPREHENSIONTLV_TAG_TEXT_STRING |
- COMPREHENSIONTLV_FLAG_CR);
- // Write Length.
- this.writeLength(length);
- // Write Value.
- for (let i = 0; i < length; i++) {
- GsmPDUHelper.writeHexOctet(buf[i]);
- }
- }
- },
-
- getSizeOfLengthOctets: function(length) {
- if (length >= 0x10000) {
- return 4; // 0x83, len_1, len_2, len_3
- } else if (length >= 0x100) {
- return 3; // 0x82, len_1, len_2
- } else if (length >= 0x80) {
- return 2; // 0x81, len
- } else {
- return 1; // len
- }
- },
-
- writeLength: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- // TS 101.220 clause 7.1.2, Length Encoding.
- // Length | Byte 1 | Byte 2 | Byte 3 | Byte 4 |
- // 0 - 127 | 00 - 7f | N/A | N/A | N/A |
- // 128-255 | 81 | 80 - ff| N/A | N/A |
- // 256-65535| 82 | 0100 - ffff | N/A |
- // 65536- | 83 | 010000 - ffffff |
- // 16777215
- if (length < 0x80) {
- GsmPDUHelper.writeHexOctet(length);
- } else if (0x80 <= length && length < 0x100) {
- GsmPDUHelper.writeHexOctet(0x81);
- GsmPDUHelper.writeHexOctet(length);
- } else if (0x100 <= length && length < 0x10000) {
- GsmPDUHelper.writeHexOctet(0x82);
- GsmPDUHelper.writeHexOctet((length >> 8) & 0xff);
- GsmPDUHelper.writeHexOctet(length & 0xff);
- } else if (0x10000 <= length && length < 0x1000000) {
- GsmPDUHelper.writeHexOctet(0x83);
- GsmPDUHelper.writeHexOctet((length >> 16) & 0xff);
- GsmPDUHelper.writeHexOctet((length >> 8) & 0xff);
- GsmPDUHelper.writeHexOctet(length & 0xff);
- } else {
- throw new Error("Invalid length value :" + length);
- }
- },
-};
-
-function BerTlvHelperObject(aContext) {
- this.context = aContext;
-}
-BerTlvHelperObject.prototype = {
- context: null,
-
- /**
- * Decode Ber TLV.
- *
- * @param dataLen
- * The length of data in bytes.
- */
- decode: function(dataLen) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let hlen = 0;
- let tag = GsmPDUHelper.readHexOctet();
- hlen++;
-
- // The length is coded onto 1 or 2 bytes.
- // Length | Byte 1 | Byte 2
- // 0 - 127 | length ('00' to '7f') | N/A
- // 128 - 255 | '81' | length ('80' to 'ff')
- let length;
- let temp = GsmPDUHelper.readHexOctet();
- hlen++;
- if (temp < 0x80) {
- length = temp;
- } else if (temp === 0x81) {
- length = GsmPDUHelper.readHexOctet();
- hlen++;
- if (length < 0x80) {
- throw new Error("Invalid length " + length);
- }
- } else {
- throw new Error("Invalid length octet " + temp);
- }
-
- // Header + body length check.
- if (dataLen - hlen !== length) {
- throw new Error("Unexpected BerTlvHelper value length!!");
- }
-
- let method = this[tag];
- if (typeof method != "function") {
- throw new Error("Unknown Ber tag 0x" + tag.toString(16));
- }
-
- let value = method.call(this, length);
-
- return {
- tag: tag,
- length: length,
- value: value
- };
- },
-
- /**
- * Process the value part for FCP template TLV.
- *
- * @param length
- * The length of data in bytes.
- */
- processFcpTemplate: function(length) {
- let tlvs = this.decodeChunks(length);
- return tlvs;
- },
-
- /**
- * Process the value part for proactive command TLV.
- *
- * @param length
- * The length of data in bytes.
- */
- processProactiveCommand: function(length) {
- let ctlvs = this.context.ComprehensionTlvHelper.decodeChunks(length);
- return ctlvs;
- },
-
- /**
- * Decode raw data to a Ber-TLV.
- */
- decodeInnerTlv: function() {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let tag = GsmPDUHelper.readHexOctet();
- let length = GsmPDUHelper.readHexOctet();
- return {
- tag: tag,
- length: length,
- value: this.retrieve(tag, length)
- };
- },
-
- decodeChunks: function(length) {
- let chunks = [];
- let index = 0;
- while (index < length) {
- let tlv = this.decodeInnerTlv();
- if (tlv.value) {
- chunks.push(tlv);
- }
- index += tlv.length;
- // tag + length fields consume 2 bytes.
- index += 2;
- }
- return chunks;
- },
-
- retrieve: function(tag, length) {
- let method = this[tag];
- if (typeof method != "function") {
- if (DEBUG) {
- this.context.debug("Unknown Ber tag : 0x" + tag.toString(16));
- }
- let Buf = this.context.Buf;
- Buf.seekIncoming(length * Buf.PDU_HEX_OCTET_SIZE);
- return null;
- }
- return method.call(this, length);
- },
-
- /**
- * File Size Data.
- *
- * | Byte | Description | Length |
- * | 1 | Tag | 1 |
- * | 2 | Length | 1 |
- * | 3 to X+24 | Number of allocated data bytes in the file | X |
- * | | , excluding structural information | |
- */
- retrieveFileSizeData: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let fileSizeData = 0;
- for (let i = 0; i < length; i++) {
- fileSizeData = fileSizeData << 8;
- fileSizeData += GsmPDUHelper.readHexOctet();
- }
-
- return {fileSizeData: fileSizeData};
- },
-
- /**
- * File Descriptor.
- *
- * | Byte | Description | Length |
- * | 1 | Tag | 1 |
- * | 2 | Length | 1 |
- * | 3 | File descriptor byte | 1 |
- * | 4 | Data coding byte | 1 |
- * | 5 ~ 6 | Record length | 2 |
- * | 7 | Number of records | 1 |
- */
- retrieveFileDescriptor: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let fileDescriptorByte = GsmPDUHelper.readHexOctet();
- let dataCodingByte = GsmPDUHelper.readHexOctet();
- // See TS 102 221 Table 11.5, we only care the least 3 bits for the
- // structure of file.
- let fileStructure = fileDescriptorByte & 0x07;
-
- let fileDescriptor = {
- fileStructure: fileStructure
- };
- // byte 5 ~ 7 are mandatory for linear fixed and cyclic files, otherwise
- // they are not applicable.
- if (fileStructure === UICC_EF_STRUCTURE[EF_STRUCTURE_LINEAR_FIXED] ||
- fileStructure === UICC_EF_STRUCTURE[EF_STRUCTURE_CYCLIC]) {
- fileDescriptor.recordLength = (GsmPDUHelper.readHexOctet() << 8) +
- GsmPDUHelper.readHexOctet();
- fileDescriptor.numOfRecords = GsmPDUHelper.readHexOctet();
- }
-
- return fileDescriptor;
- },
-
- /**
- * File identifier.
- *
- * | Byte | Description | Length |
- * | 1 | Tag | 1 |
- * | 2 | Length | 1 |
- * | 3 ~ 4 | File identifier | 2 |
- */
- retrieveFileIdentifier: function(length) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- return {fileId : (GsmPDUHelper.readHexOctet() << 8) +
- GsmPDUHelper.readHexOctet()};
- },
-
- searchForNextTag: function(tag, iter) {
- for (let tlv of iter) {
- if (tlv.tag === tag) {
- return tlv;
- }
- }
- return null;
- }
-};
-BerTlvHelperObject.prototype[BER_FCP_TEMPLATE_TAG] = function BER_FCP_TEMPLATE_TAG(length) {
- return this.processFcpTemplate(length);
-};
-BerTlvHelperObject.prototype[BER_PROACTIVE_COMMAND_TAG] = function BER_PROACTIVE_COMMAND_TAG(length) {
- return this.processProactiveCommand(length);
-};
-BerTlvHelperObject.prototype[BER_FCP_FILE_SIZE_DATA_TAG] = function BER_FCP_FILE_SIZE_DATA_TAG(length) {
- return this.retrieveFileSizeData(length);
-};
-BerTlvHelperObject.prototype[BER_FCP_FILE_DESCRIPTOR_TAG] = function BER_FCP_FILE_DESCRIPTOR_TAG(length) {
- return this.retrieveFileDescriptor(length);
-};
-BerTlvHelperObject.prototype[BER_FCP_FILE_IDENTIFIER_TAG] = function BER_FCP_FILE_IDENTIFIER_TAG(length) {
- return this.retrieveFileIdentifier(length);
-};
-
-/**
- * ICC Helper for getting EF path.
- */
-function ICCFileHelperObject(aContext) {
- this.context = aContext;
-}
-ICCFileHelperObject.prototype = {
- context: null,
-
- /**
- * This function handles only EFs that are common to RUIM, SIM, USIM
- * and other types of ICC cards.
- */
- getCommonEFPath: function(fileId) {
- switch (fileId) {
- case ICC_EF_ICCID:
- return EF_PATH_MF_SIM;
- case ICC_EF_ADN:
- case ICC_EF_SDN: // Fall through.
- return EF_PATH_MF_SIM + EF_PATH_DF_TELECOM;
- case ICC_EF_PBR:
- return EF_PATH_MF_SIM + EF_PATH_DF_TELECOM + EF_PATH_DF_PHONEBOOK;
- case ICC_EF_IMG:
- return EF_PATH_MF_SIM + EF_PATH_DF_TELECOM + EF_PATH_GRAPHICS;
- }
- return null;
- },
-
- /**
- * This function handles EFs for SIM.
- */
- getSimEFPath: function(fileId) {
- switch (fileId) {
- case ICC_EF_FDN:
- case ICC_EF_MSISDN:
- case ICC_EF_SMS:
- case ICC_EF_EXT1:
- case ICC_EF_EXT2:
- case ICC_EF_EXT3:
- return EF_PATH_MF_SIM + EF_PATH_DF_TELECOM;
- case ICC_EF_AD:
- case ICC_EF_MBDN:
- case ICC_EF_MWIS:
- case ICC_EF_PLMNsel:
- case ICC_EF_SPN:
- case ICC_EF_SPDI:
- case ICC_EF_SST:
- case ICC_EF_PHASE:
- case ICC_EF_CBMI:
- case ICC_EF_CBMID:
- case ICC_EF_CBMIR:
- case ICC_EF_OPL:
- case ICC_EF_PNN:
- case ICC_EF_GID1:
- case ICC_EF_CPHS_INFO:
- case ICC_EF_CPHS_MBN:
- return EF_PATH_MF_SIM + EF_PATH_DF_GSM;
- default:
- return null;
- }
- },
-
- /**
- * This function handles EFs for USIM.
- */
- getUSimEFPath: function(fileId) {
- switch (fileId) {
- case ICC_EF_AD:
- case ICC_EF_FDN:
- case ICC_EF_MBDN:
- case ICC_EF_MWIS:
- case ICC_EF_UST:
- case ICC_EF_MSISDN:
- case ICC_EF_SPN:
- case ICC_EF_SPDI:
- case ICC_EF_CBMI:
- case ICC_EF_CBMID:
- case ICC_EF_CBMIR:
- case ICC_EF_OPL:
- case ICC_EF_PNN:
- case ICC_EF_SMS:
- case ICC_EF_GID1:
- // CPHS spec was provided in 1997 based on SIM requirement, there is no
- // detailed info about how these ICC_EF_CPHS_XXX are allocated in USIM.
- // What we can do now is to follow what has been done in AOSP to have file
- // path equal to MF_SIM/DF_GSM.
- case ICC_EF_CPHS_INFO:
- case ICC_EF_CPHS_MBN:
- return EF_PATH_MF_SIM + EF_PATH_ADF_USIM;
- default:
- // The file ids in USIM phone book entries are decided by the
- // card manufacturer. So if we don't match any of the cases
- // above and if its a USIM return the phone book path.
- return EF_PATH_MF_SIM + EF_PATH_DF_TELECOM + EF_PATH_DF_PHONEBOOK;
- }
- },
-
- /**
- * This function handles EFs for RUIM
- */
- getRuimEFPath: function(fileId) {
- switch(fileId) {
- case ICC_EF_CSIM_IMSI_M:
- case ICC_EF_CSIM_CDMAHOME:
- case ICC_EF_CSIM_CST:
- case ICC_EF_CSIM_SPN:
- return EF_PATH_MF_SIM + EF_PATH_DF_CDMA;
- case ICC_EF_FDN:
- case ICC_EF_EXT1:
- case ICC_EF_EXT2:
- case ICC_EF_EXT3:
- return EF_PATH_MF_SIM + EF_PATH_DF_TELECOM;
- default:
- return null;
- }
- },
-
- /**
- * Helper function for getting the pathId for the specific ICC record
- * depeding on which type of ICC card we are using.
- *
- * @param fileId
- * File id.
- * @return The pathId or null in case of an error or invalid input.
- */
- getEFPath: function(fileId) {
- let path = this.getCommonEFPath(fileId);
- if (path) {
- return path;
- }
-
- switch (this.context.RIL.appType) {
- case CARD_APPTYPE_SIM:
- return this.getSimEFPath(fileId);
- case CARD_APPTYPE_USIM:
- return this.getUSimEFPath(fileId);
- case CARD_APPTYPE_RUIM:
- return this.getRuimEFPath(fileId);
- default:
- return null;
- }
- }
-};
-
-/**
- * Helper for ICC IO functionalities.
- */
-function ICCIOHelperObject(aContext) {
- this.context = aContext;
-}
-ICCIOHelperObject.prototype = {
- context: null,
-
- /**
- * Load EF with type 'Linear Fixed'.
- *
- * @param fileId
- * The file to operate on, one of the ICC_EF_* constants.
- * @param recordNumber [optional]
- * The number of the record shall be loaded.
- * @param recordSize [optional]
- * The size of the record.
- * @param callback [optional]
- * The callback function shall be called when the record(s) is read.
- * @param onerror [optional]
- * The callback function shall be called when failure.
- */
- loadLinearFixedEF: function(options) {
- let cb;
- let readRecord = (function(options) {
- options.command = ICC_COMMAND_READ_RECORD;
- options.p1 = options.recordNumber || 1; // Record number
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = options.recordSize;
- options.callback = cb || options.callback;
- this.context.RIL.iccIO(options);
- }).bind(this);
-
- options.structure = EF_STRUCTURE_LINEAR_FIXED;
- options.pathId = this.context.ICCFileHelper.getEFPath(options.fileId);
- if (options.recordSize) {
- readRecord(options);
- return;
- }
-
- cb = options.callback;
- options.callback = readRecord;
- this.getResponse(options);
- },
-
- /**
- * Load next record from current record Id.
- */
- loadNextRecord: function(options) {
- options.p1++;
- this.context.RIL.iccIO(options);
- },
-
- /**
- * Update EF with type 'Linear Fixed'.
- *
- * @param fileId
- * The file to operate on, one of the ICC_EF_* constants.
- * @param recordNumber
- * The number of the record shall be updated.
- * @param dataWriter [optional]
- * The function for writing string parameter for the ICC_COMMAND_UPDATE_RECORD.
- * @param pin2 [optional]
- * PIN2 is required when updating ICC_EF_FDN.
- * @param callback [optional]
- * The callback function shall be called when the record is updated.
- * @param onerror [optional]
- * The callback function shall be called when failure.
- */
- updateLinearFixedEF: function(options) {
- if (!options.fileId || !options.recordNumber) {
- throw new Error("Unexpected fileId " + options.fileId +
- " or recordNumber " + options.recordNumber);
- }
-
- options.structure = EF_STRUCTURE_LINEAR_FIXED;
- options.pathId = this.context.ICCFileHelper.getEFPath(options.fileId);
- let cb = options.callback;
- options.callback = function callback(options) {
- options.callback = cb;
- options.command = ICC_COMMAND_UPDATE_RECORD;
- options.p1 = options.recordNumber;
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = options.recordSize;
- this.context.RIL.iccIO(options);
- }.bind(this);
- this.getResponse(options);
- },
-
- /**
- * Load EF with type 'Transparent'.
- *
- * @param fileId
- * The file to operate on, one of the ICC_EF_* constants.
- * @param callback [optional]
- * The callback function shall be called when the record(s) is read.
- * @param onerror [optional]
- * The callback function shall be called when failure.
- */
- loadTransparentEF: function(options) {
- options.structure = EF_STRUCTURE_TRANSPARENT;
- let cb = options.callback;
- options.callback = function callback(options) {
- options.callback = cb;
- options.command = ICC_COMMAND_READ_BINARY;
- options.p2 = 0x00;
- options.p3 = options.fileSize;
- this.context.RIL.iccIO(options);
- }.bind(this);
- this.getResponse(options);
- },
-
- /**
- * Use ICC_COMMAND_GET_RESPONSE to query the EF.
- *
- * @param fileId
- * The file to operate on, one of the ICC_EF_* constants.
- */
- getResponse: function(options) {
- options.command = ICC_COMMAND_GET_RESPONSE;
- options.pathId = options.pathId ||
- this.context.ICCFileHelper.getEFPath(options.fileId);
- if (!options.pathId) {
- throw new Error("Unknown pathId for " + options.fileId.toString(16));
- }
- options.p1 = 0; // For GET_RESPONSE, p1 = 0
- switch (this.context.RIL.appType) {
- case CARD_APPTYPE_USIM:
- options.p2 = GET_RESPONSE_FCP_TEMPLATE;
- options.p3 = 0x00;
- break;
- // For RUIM, CSIM and ISIM, cf bug 955946: keep the old behavior
- case CARD_APPTYPE_RUIM:
- case CARD_APPTYPE_CSIM:
- case CARD_APPTYPE_ISIM:
- // For SIM, this is what we want
- case CARD_APPTYPE_SIM:
- default:
- options.p2 = 0x00;
- options.p3 = GET_RESPONSE_EF_SIZE_BYTES;
- break;
- }
- this.context.RIL.iccIO(options);
- },
-
- /**
- * Process ICC I/O response.
- */
- processICCIO: function(options) {
- let func = this[options.command];
- func.call(this, options);
- },
-
- /**
- * Process a ICC_COMMAND_GET_RESPONSE type command for REQUEST_SIM_IO.
- */
- processICCIOGetResponse: function(options) {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
-
- let peek = this.context.GsmPDUHelper.readHexOctet();
- Buf.seekIncoming(-1 * Buf.PDU_HEX_OCTET_SIZE);
- if (peek === BER_FCP_TEMPLATE_TAG) {
- this.processUSimGetResponse(options, strLen / 2);
- } else {
- this.processSimGetResponse(options);
- }
- Buf.readStringDelimiter(strLen);
-
- if (options.callback) {
- options.callback(options);
- }
- },
-
- /**
- * Helper function for processing USIM get response.
- */
- processUSimGetResponse: function(options, octetLen) {
- let BerTlvHelper = this.context.BerTlvHelper;
-
- let berTlv = BerTlvHelper.decode(octetLen);
- // See TS 102 221 Table 11.4 for the content order of getResponse.
- let iter = berTlv.value.values();
- let tlv = BerTlvHelper.searchForNextTag(BER_FCP_FILE_DESCRIPTOR_TAG,
- iter);
- if (!tlv ||
- (tlv.value.fileStructure !== UICC_EF_STRUCTURE[options.structure])) {
- throw new Error("Expected EF structure " +
- UICC_EF_STRUCTURE[options.structure] +
- " but read " + tlv.value.fileStructure);
- }
-
- if (tlv.value.fileStructure === UICC_EF_STRUCTURE[EF_STRUCTURE_LINEAR_FIXED] ||
- tlv.value.fileStructure === UICC_EF_STRUCTURE[EF_STRUCTURE_CYCLIC]) {
- options.recordSize = tlv.value.recordLength;
- options.totalRecords = tlv.value.numOfRecords;
- }
-
- tlv = BerTlvHelper.searchForNextTag(BER_FCP_FILE_IDENTIFIER_TAG, iter);
- if (!tlv || (tlv.value.fileId !== options.fileId)) {
- throw new Error("Expected file ID " + options.fileId.toString(16) +
- " but read " + fileId.toString(16));
- }
-
- tlv = BerTlvHelper.searchForNextTag(BER_FCP_FILE_SIZE_DATA_TAG, iter);
- if (!tlv) {
- throw new Error("Unexpected file size data");
- }
- options.fileSize = tlv.value.fileSizeData;
- },
-
- /**
- * Helper function for processing SIM get response.
- */
- processSimGetResponse: function(options) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- // The format is from TS 51.011, clause 9.2.1
-
- // Skip RFU, data[0] data[1].
- Buf.seekIncoming(2 * Buf.PDU_HEX_OCTET_SIZE);
-
- // File size, data[2], data[3]
- options.fileSize = (GsmPDUHelper.readHexOctet() << 8) |
- GsmPDUHelper.readHexOctet();
-
- // 2 bytes File id. data[4], data[5]
- let fileId = (GsmPDUHelper.readHexOctet() << 8) |
- GsmPDUHelper.readHexOctet();
- if (fileId != options.fileId) {
- throw new Error("Expected file ID " + options.fileId.toString(16) +
- " but read " + fileId.toString(16));
- }
-
- // Type of file, data[6]
- let fileType = GsmPDUHelper.readHexOctet();
- if (fileType != TYPE_EF) {
- throw new Error("Unexpected file type " + fileType);
- }
-
- // Skip 1 byte RFU, data[7],
- // 3 bytes Access conditions, data[8] data[9] data[10],
- // 1 byte File status, data[11],
- // 1 byte Length of the following data, data[12].
- Buf.seekIncoming(((RESPONSE_DATA_STRUCTURE - RESPONSE_DATA_FILE_TYPE - 1) *
- Buf.PDU_HEX_OCTET_SIZE));
-
- // Read Structure of EF, data[13]
- let efStructure = GsmPDUHelper.readHexOctet();
- if (efStructure != options.structure) {
- throw new Error("Expected EF structure " + options.structure +
- " but read " + efStructure);
- }
-
- // Length of a record, data[14].
- // Only available for LINEAR_FIXED and CYCLIC.
- if (efStructure == EF_STRUCTURE_LINEAR_FIXED ||
- efStructure == EF_STRUCTURE_CYCLIC) {
- options.recordSize = GsmPDUHelper.readHexOctet();
- options.totalRecords = options.fileSize / options.recordSize;
- } else {
- Buf.seekIncoming(1 * Buf.PDU_HEX_OCTET_SIZE);
- }
- },
-
- /**
- * Process a ICC_COMMAND_READ_RECORD type command for REQUEST_SIM_IO.
- */
- processICCIOReadRecord: function(options) {
- if (options.callback) {
- options.callback(options);
- }
- },
-
- /**
- * Process a ICC_COMMAND_READ_BINARY type command for REQUEST_SIM_IO.
- */
- processICCIOReadBinary: function(options) {
- if (options.callback) {
- options.callback(options);
- }
- },
-
- /**
- * Process a ICC_COMMAND_UPDATE_RECORD type command for REQUEST_SIM_IO.
- */
- processICCIOUpdateRecord: function(options) {
- if (options.callback) {
- options.callback(options);
- }
- },
-};
-ICCIOHelperObject.prototype[ICC_COMMAND_SEEK] = null;
-ICCIOHelperObject.prototype[ICC_COMMAND_READ_BINARY] = function ICC_COMMAND_READ_BINARY(options) {
- this.processICCIOReadBinary(options);
-};
-ICCIOHelperObject.prototype[ICC_COMMAND_READ_RECORD] = function ICC_COMMAND_READ_RECORD(options) {
- this.processICCIOReadRecord(options);
-};
-ICCIOHelperObject.prototype[ICC_COMMAND_GET_RESPONSE] = function ICC_COMMAND_GET_RESPONSE(options) {
- this.processICCIOGetResponse(options);
-};
-ICCIOHelperObject.prototype[ICC_COMMAND_UPDATE_BINARY] = null;
-ICCIOHelperObject.prototype[ICC_COMMAND_UPDATE_RECORD] = function ICC_COMMAND_UPDATE_RECORD(options) {
- this.processICCIOUpdateRecord(options);
-};
-
-/**
- * Helper for ICC records.
- */
-function ICCRecordHelperObject(aContext) {
- this.context = aContext;
- // Cache the possible free record id for all files, use fileId as key.
- this._freeRecordIds = {};
-}
-ICCRecordHelperObject.prototype = {
- context: null,
-
- /**
- * Fetch ICC records.
- */
- fetchICCRecords: function() {
- switch (this.context.RIL.appType) {
- case CARD_APPTYPE_SIM:
- case CARD_APPTYPE_USIM:
- this.context.SimRecordHelper.fetchSimRecords();
- break;
- case CARD_APPTYPE_RUIM:
- this.context.RuimRecordHelper.fetchRuimRecords();
- break;
- }
- },
-
- /**
- * Read the ICCID.
- */
- readICCID: function() {
- function callback() {
- let Buf = this.context.Buf;
- let RIL = this.context.RIL;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let strLen = Buf.readInt32();
- let octetLen = strLen / 2;
- RIL.iccInfo.iccid =
- GsmPDUHelper.readSwappedNibbleBcdString(octetLen, true);
- // Consumes the remaining buffer if any.
- let unReadBuffer = this.context.Buf.getReadAvailable() -
- this.context.Buf.PDU_HEX_OCTET_SIZE;
- if (unReadBuffer > 0) {
- this.context.Buf.seekIncoming(unReadBuffer);
- }
- Buf.readStringDelimiter(strLen);
-
- if (DEBUG) this.context.debug("ICCID: " + RIL.iccInfo.iccid);
- if (RIL.iccInfo.iccid) {
- this.context.ICCUtilsHelper.handleICCInfoChange();
- RIL.reportStkServiceIsRunning();
- }
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_ICCID,
- callback: callback.bind(this)
- });
- },
-
- /**
- * Read ICC ADN like EF, i.e. EF_ADN, EF_FDN.
- *
- * @param fileId EF id of the ADN, FDN or SDN.
- * @param extFileId EF id of the EXT.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readADNLike: function(fileId, extFileId, onsuccess, onerror) {
- let ICCIOHelper = this.context.ICCIOHelper;
-
- function callback(options) {
- let loadNextContactRecord = () => {
- if (options.p1 < options.totalRecords) {
- ICCIOHelper.loadNextRecord(options);
- return;
- }
- if (DEBUG) {
- for (let i = 0; i < contacts.length; i++) {
- this.context.debug("contact [" + i + "] " +
- JSON.stringify(contacts[i]));
- }
- }
- if (onsuccess) {
- onsuccess(contacts);
- }
- };
-
- let contact =
- this.context.ICCPDUHelper.readAlphaIdDiallingNumber(options.recordSize);
- if (contact) {
- let record = {
- recordId: options.p1,
- alphaId: contact.alphaId,
- number: contact.number
- };
- contacts.push(record);
-
- if (extFileId && contact.extRecordNumber != 0xff) {
- this.readExtension(extFileId, contact.extRecordNumber, (number) => {
- if (number) {
- record.number += number;
- }
- loadNextContactRecord();
- }, () => loadNextContactRecord());
- return;
- }
- }
- loadNextContactRecord();
- }
-
- let contacts = [];
- ICCIOHelper.loadLinearFixedEF({fileId: fileId,
- callback: callback.bind(this),
- onerror: onerror});
- },
-
- /**
- * Update ICC ADN like EFs, like EF_ADN, EF_FDN.
- *
- * @param fileId EF id of the ADN or FDN.
- * @param extRecordNumber The record identifier of the EXT.
- * @param contact The contact will be updated. (Shall have recordId property)
- * @param pin2 PIN2 is required when updating ICC_EF_FDN.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateADNLike: function(fileId, extRecordNumber, contact, pin2, onsuccess, onerror) {
- let updatedContact;
- function dataWriter(recordSize) {
- updatedContact = this.context.ICCPDUHelper.writeAlphaIdDiallingNumber(recordSize,
- contact.alphaId,
- contact.number,
- extRecordNumber);
- }
-
- function callback(options) {
- if (onsuccess) {
- onsuccess(updatedContact);
- }
- }
-
- if (!contact || !contact.recordId) {
- if (onerror) onerror(GECKO_ERROR_INVALID_PARAMETER);
- return;
- }
-
- this.context.ICCIOHelper.updateLinearFixedEF({
- fileId: fileId,
- recordNumber: contact.recordId,
- dataWriter: dataWriter.bind(this),
- pin2: pin2,
- callback: callback.bind(this),
- onerror: onerror
- });
- },
-
- /**
- * Read USIM/RUIM Phonebook.
- *
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readPBR: function(onsuccess, onerror) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let ICCIOHelper = this.context.ICCIOHelper;
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- let RIL = this.context.RIL;
-
- function callback(options) {
- let strLen = Buf.readInt32();
- let octetLen = strLen / 2, readLen = 0;
-
- let pbrTlvs = [];
- while (readLen < octetLen) {
- let tag = GsmPDUHelper.readHexOctet();
- if (tag == 0xff) {
- readLen++;
- Buf.seekIncoming((octetLen - readLen) * Buf.PDU_HEX_OCTET_SIZE);
- break;
- }
-
- let tlvLen = GsmPDUHelper.readHexOctet();
- let tlvs = ICCUtilsHelper.decodeSimTlvs(tlvLen);
- pbrTlvs.push({tag: tag,
- length: tlvLen,
- value: tlvs});
-
- readLen += tlvLen + 2; // +2 for tag and tlvLen
- }
- Buf.readStringDelimiter(strLen);
-
- if (pbrTlvs.length > 0) {
- let pbr = ICCUtilsHelper.parsePbrTlvs(pbrTlvs);
- // EF_ADN is mandatory if and only if DF_PHONEBOOK is present.
- if (!pbr.adn) {
- if (onerror) onerror("Cannot access ADN.");
- return;
- }
- pbrs.push(pbr);
- }
-
- if (options.p1 < options.totalRecords) {
- ICCIOHelper.loadNextRecord(options);
- } else {
- if (onsuccess) {
- RIL.iccInfoPrivate.pbrs = pbrs;
- onsuccess(pbrs);
- }
- }
- }
-
- if (RIL.iccInfoPrivate.pbrs) {
- onsuccess(RIL.iccInfoPrivate.pbrs);
- return;
- }
-
- let pbrs = [];
- ICCIOHelper.loadLinearFixedEF({fileId : ICC_EF_PBR,
- callback: callback.bind(this),
- onerror: onerror});
- },
-
- /**
- * Cache EF_IAP record size.
- */
- _iapRecordSize: null,
-
- /**
- * Read ICC EF_IAP. (Index Administration Phonebook)
- *
- * @see TS 131.102, clause 4.4.2.2
- *
- * @param fileId EF id of the IAP.
- * @param recordNumber The number of the record shall be loaded.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readIAP: function(fileId, recordNumber, onsuccess, onerror) {
- function callback(options) {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
- let octetLen = strLen / 2;
- this._iapRecordSize = options.recordSize;
-
- let iap = this.context.GsmPDUHelper.readHexOctetArray(octetLen);
- Buf.readStringDelimiter(strLen);
-
- if (onsuccess) {
- onsuccess(iap);
- }
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- recordSize: this._iapRecordSize,
- callback: callback.bind(this),
- onerror: onerror
- });
- },
-
- /**
- * Update USIM/RUIM Phonebook EF_IAP.
- *
- * @see TS 131.102, clause 4.4.2.13
- *
- * @param fileId EF id of the IAP.
- * @param recordNumber The identifier of the record shall be updated.
- * @param iap The IAP value to be written.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateIAP: function(fileId, recordNumber, iap, onsuccess, onerror) {
- let dataWriter = function dataWriter(recordSize) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- // Write String length
- let strLen = recordSize * 2;
- Buf.writeInt32(strLen);
-
- for (let i = 0; i < iap.length; i++) {
- GsmPDUHelper.writeHexOctet(iap[i]);
- }
-
- Buf.writeStringDelimiter(strLen);
- }.bind(this);
-
- this.context.ICCIOHelper.updateLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- dataWriter: dataWriter,
- callback: onsuccess,
- onerror: onerror
- });
- },
-
- /**
- * Cache EF_Email record size.
- */
- _emailRecordSize: null,
-
- /**
- * Read USIM/RUIM Phonebook EF_EMAIL.
- *
- * @see TS 131.102, clause 4.4.2.13
- *
- * @param fileId EF id of the EMAIL.
- * @param fileType The type of the EMAIL, one of the ICC_USIM_TYPE* constants.
- * @param recordNumber The number of the record shall be loaded.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readEmail: function(fileId, fileType, recordNumber, onsuccess, onerror) {
- function callback(options) {
- let Buf = this.context.Buf;
- let ICCPDUHelper = this.context.ICCPDUHelper;
-
- let strLen = Buf.readInt32();
- let octetLen = strLen / 2;
- let email = null;
- this._emailRecordSize = options.recordSize;
-
- // Read contact's email
- //
- // | Byte | Description | Length | M/O
- // | 1 ~ X | E-mail Address | X | M
- // | X+1 | ADN file SFI | 1 | C
- // | X+2 | ADN file Record Identifier | 1 | C
- // Note: The fields marked as C above are mandatort if the file
- // is not type 1 (as specified in EF_PBR)
- if (fileType == ICC_USIM_TYPE1_TAG) {
- email = ICCPDUHelper.read8BitUnpackedToString(octetLen);
- } else {
- email = ICCPDUHelper.read8BitUnpackedToString(octetLen - 2);
-
- // Consumes the remaining buffer
- Buf.seekIncoming(2 * Buf.PDU_HEX_OCTET_SIZE); // For ADN SFI and Record Identifier
- }
-
- Buf.readStringDelimiter(strLen);
-
- if (onsuccess) {
- onsuccess(email);
- }
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- recordSize: this._emailRecordSize,
- callback: callback.bind(this),
- onerror: onerror
- });
- },
-
- /**
- * Update USIM/RUIM Phonebook EF_EMAIL.
- *
- * @see TS 131.102, clause 4.4.2.13
- *
- * @param pbr Phonebook Reference File.
- * @param recordNumber The identifier of the record shall be updated.
- * @param email The value to be written.
- * @param adnRecordId The record Id of ADN, only needed if the fileType of Email is TYPE2.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateEmail: function(pbr, recordNumber, email, adnRecordId, onsuccess, onerror) {
- let fileId = pbr[USIM_PBR_EMAIL].fileId;
- let fileType = pbr[USIM_PBR_EMAIL].fileType;
- let writtenEmail;
- let dataWriter = function dataWriter(recordSize) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let ICCPDUHelper = this.context.ICCPDUHelper;
-
- // Write String length
- let strLen = recordSize * 2;
- Buf.writeInt32(strLen);
-
- if (fileType == ICC_USIM_TYPE1_TAG) {
- writtenEmail = ICCPDUHelper.writeStringTo8BitUnpacked(recordSize, email);
- } else {
- writtenEmail = ICCPDUHelper.writeStringTo8BitUnpacked(recordSize - 2, email);
- GsmPDUHelper.writeHexOctet(pbr.adn.sfi || 0xff);
- GsmPDUHelper.writeHexOctet(adnRecordId);
- }
-
- Buf.writeStringDelimiter(strLen);
- }.bind(this);
-
- let callback = (options) => {
- if (onsuccess) {
- onsuccess(writtenEmail);
- }
- }
-
- this.context.ICCIOHelper.updateLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- dataWriter: dataWriter,
- callback: callback,
- onerror: onerror
- });
- },
-
- /**
- * Cache EF_ANR record size.
- */
- _anrRecordSize: null,
-
- /**
- * Read USIM/RUIM Phonebook EF_ANR.
- *
- * @see TS 131.102, clause 4.4.2.9
- *
- * @param fileId EF id of the ANR.
- * @param fileType One of the ICC_USIM_TYPE* constants.
- * @param recordNumber The number of the record shall be loaded.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readANR: function(fileId, fileType, recordNumber, onsuccess, onerror) {
- function callback(options) {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
- let number = null;
- this._anrRecordSize = options.recordSize;
-
- // Skip EF_AAS Record ID.
- Buf.seekIncoming(1 * Buf.PDU_HEX_OCTET_SIZE);
-
- number = this.context.ICCPDUHelper.readNumberWithLength();
-
- // Skip 2 unused octets, CCP and EXT1.
- Buf.seekIncoming(2 * Buf.PDU_HEX_OCTET_SIZE);
-
- // For Type 2 there are two extra octets.
- if (fileType == ICC_USIM_TYPE2_TAG) {
- // Skip 2 unused octets, ADN SFI and Record Identifier.
- Buf.seekIncoming(2 * Buf.PDU_HEX_OCTET_SIZE);
- }
-
- Buf.readStringDelimiter(strLen);
-
- if (onsuccess) {
- onsuccess(number);
- }
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- recordSize: this._anrRecordSize,
- callback: callback.bind(this),
- onerror: onerror
- });
- },
-
- /**
- * Update USIM/RUIM Phonebook EF_ANR.
- *
- * @see TS 131.102, clause 4.4.2.9
- *
- * @param pbr Phonebook Reference File.
- * @param recordNumber The identifier of the record shall be updated.
- * @param number The value to be written.
- * @param adnRecordId The record Id of ADN, only needed if the fileType of Email is TYPE2.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateANR: function(pbr, recordNumber, number, adnRecordId, onsuccess, onerror) {
- let fileId = pbr[USIM_PBR_ANR0].fileId;
- let fileType = pbr[USIM_PBR_ANR0].fileType;
- let writtenNumber;
- let dataWriter = function dataWriter(recordSize) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- // Write String length
- let strLen = recordSize * 2;
- Buf.writeInt32(strLen);
-
- // EF_AAS record Id. Unused for now.
- GsmPDUHelper.writeHexOctet(0xff);
-
- writtenNumber = this.context.ICCPDUHelper.writeNumberWithLength(number);
-
- // Write unused octets 0xff, CCP and EXT1.
- GsmPDUHelper.writeHexOctet(0xff);
- GsmPDUHelper.writeHexOctet(0xff);
-
- // For Type 2 there are two extra octets.
- if (fileType == ICC_USIM_TYPE2_TAG) {
- GsmPDUHelper.writeHexOctet(pbr.adn.sfi || 0xff);
- GsmPDUHelper.writeHexOctet(adnRecordId);
- }
-
- Buf.writeStringDelimiter(strLen);
- }.bind(this);
-
- let callback = (options) => {
- if (onsuccess) {
- onsuccess(writtenNumber);
- }
- }
-
- this.context.ICCIOHelper.updateLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- dataWriter: dataWriter,
- callback: callback,
- onerror: onerror
- });
- },
-
- /**
- * Cache the possible free record id for all files.
- */
- _freeRecordIds: null,
-
- /**
- * Find free record id.
- *
- * @param fileId EF id.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- findFreeRecordId: function(fileId, onsuccess, onerror) {
- let ICCIOHelper = this.context.ICCIOHelper;
-
- function callback(options) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let strLen = Buf.readInt32();
- let octetLen = strLen / 2;
- let readLen = 0;
-
- while (readLen < octetLen) {
- let octet = GsmPDUHelper.readHexOctet();
- readLen++;
- if (octet != 0xff) {
- break;
- }
- }
-
- let nextRecord = (options.p1 % options.totalRecords) + 1;
-
- if (readLen == octetLen) {
- // Find free record, assume next record is probably free.
- this._freeRecordIds[fileId] = nextRecord;
- if (onsuccess) {
- onsuccess(options.p1);
- }
- return;
- } else {
- Buf.seekIncoming((octetLen - readLen) * Buf.PDU_HEX_OCTET_SIZE);
- }
-
- Buf.readStringDelimiter(strLen);
-
- if (nextRecord !== recordNumber) {
- options.p1 = nextRecord;
- this.context.RIL.iccIO(options);
- } else {
- // No free record found.
- delete this._freeRecordIds[fileId];
- if (DEBUG) {
- this.context.debug(CONTACT_ERR_NO_FREE_RECORD_FOUND);
- }
- onerror(CONTACT_ERR_NO_FREE_RECORD_FOUND);
- }
- }
-
- // Start searching free records from the possible one.
- let recordNumber = this._freeRecordIds[fileId] || 1;
- ICCIOHelper.loadLinearFixedEF({fileId: fileId,
- recordNumber: recordNumber,
- callback: callback.bind(this),
- onerror: onerror});
- },
-
- /**
- * Read Extension Number from TS 151.011 clause 10.5.10, TS 31.102, clause 4.4.2.4
- *
- * @param fileId EF Extension id
- * @param recordNumber The number of the record shall be loaded.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readExtension: function(fileId, recordNumber, onsuccess, onerror) {
- let callback = (options) => {
- let Buf = this.context.Buf;
- let length = Buf.readInt32();
- let recordType = this.context.GsmPDUHelper.readHexOctet();
- let number = "";
-
- // TS 31.102, clause 4.4.2.4 EFEXT1
- // Case 1, Extension1 record is additional data
- if (recordType & 0x02) {
- let numLen = this.context.GsmPDUHelper.readHexOctet();
- if (numLen != 0xff) {
- if (numLen > EXT_MAX_BCD_NUMBER_BYTES) {
- if (DEBUG) {
- this.context.debug(
- "Error: invalid length of BCD number/SSC contents - " + numLen);
- }
- // +1 to skip Identifier
- Buf.seekIncoming((EXT_MAX_BCD_NUMBER_BYTES + 1) * Buf.PDU_HEX_OCTET_SIZE);
- Buf.readStringDelimiter(length);
- onerror();
- return;
- }
-
- number = this.context.GsmPDUHelper.readSwappedNibbleExtendedBcdString(numLen);
- if (DEBUG) this.context.debug("Contact Extension Number: "+ number);
- Buf.seekIncoming((EXT_MAX_BCD_NUMBER_BYTES - numLen) * Buf.PDU_HEX_OCTET_SIZE);
- } else {
- Buf.seekIncoming(EXT_MAX_BCD_NUMBER_BYTES * Buf.PDU_HEX_OCTET_SIZE);
- }
- } else {
- // Don't support Case 2, Extension1 record is Called Party Subaddress.
- // +1 skip numLen
- Buf.seekIncoming((EXT_MAX_BCD_NUMBER_BYTES + 1) * Buf.PDU_HEX_OCTET_SIZE);
- }
-
- // Skip Identifier
- Buf.seekIncoming(Buf.PDU_HEX_OCTET_SIZE);
- Buf.readStringDelimiter(length);
- onsuccess(number);
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- callback: callback,
- onerror: onerror
- });
- },
-
- /**
- * Update Extension.
- *
- * @param fileId EF id of the EXT.
- * @param recordNumber The number of the record shall be updated.
- * @param number Dialling Number to be written.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateExtension: function(fileId, recordNumber, number, onsuccess, onerror) {
- let dataWriter = (recordSize) => {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- // Write String length
- let strLen = recordSize * 2;
- let Buf = this.context.Buf;
- Buf.writeInt32(strLen);
-
- // We don't support extension chain.
- if (number.length > EXT_MAX_NUMBER_DIGITS) {
- number = number.substring(0, EXT_MAX_NUMBER_DIGITS);
- }
-
- let numLen = Math.ceil(number.length / 2);
- // Write Extension record
- GsmPDUHelper.writeHexOctet(0x02);
- GsmPDUHelper.writeHexOctet(numLen);
- GsmPDUHelper.writeSwappedNibbleBCD(number);
- // Write trailing 0xff of Extension data.
- for (let i = 0; i < EXT_MAX_BCD_NUMBER_BYTES - numLen; i++) {
- GsmPDUHelper.writeHexOctet(0xff);
- }
- // Write trailing 0xff for Identifier.
- GsmPDUHelper.writeHexOctet(0xff);
- Buf.writeStringDelimiter(strLen);
- };
-
- this.context.ICCIOHelper.updateLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- dataWriter: dataWriter,
- callback: onsuccess,
- onerror: onerror
- });
- },
-
- /**
- * Clean an EF record.
- *
- * @param fileId EF id.
- * @param recordNumber The number of the record shall be updated.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- cleanEFRecord: function(fileId, recordNumber, onsuccess, onerror) {
- let dataWriter = (recordSize) => {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let Buf = this.context.Buf;
- // Write String length
- let strLen = recordSize * 2;
-
- Buf.writeInt32(strLen);
- // Write record to 0xff
- for (let i = 0; i < recordSize; i++) {
- GsmPDUHelper.writeHexOctet(0xff);
- }
- Buf.writeStringDelimiter(strLen);
- }
-
- this.context.ICCIOHelper.updateLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- dataWriter: dataWriter,
- callback: onsuccess,
- onerror: onerror
- });
- },
-
- /**
- * Get ADNLike extension record number.
- *
- * @param fileId EF id of the ADN or FDN.
- * @param recordNumber EF record id of the ADN or FDN.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- getADNLikeExtensionRecordNumber: function(fileId, recordNumber, onsuccess, onerror) {
- let callback = (options) => {
- let Buf = this.context.Buf;
- let length = Buf.readInt32();
-
- // Skip alphaLen, numLen, BCD Number, CCP octets.
- Buf.seekIncoming((options.recordSize -1) * Buf.PDU_HEX_OCTET_SIZE);
-
- let extRecordNumber = this.context.GsmPDUHelper.readHexOctet();
- Buf.readStringDelimiter(length);
-
- onsuccess(extRecordNumber);
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: fileId,
- recordNumber: recordNumber,
- callback: callback,
- onerror: onerror
- });
- },
-};
-
-/**
- * Helper for (U)SIM Records.
- */
-function SimRecordHelperObject(aContext) {
- this.context = aContext;
-}
-SimRecordHelperObject.prototype = {
- context: null,
-
- /**
- * Fetch (U)SIM records.
- */
- fetchSimRecords: function() {
- this.context.RIL.getIMSI();
- this.readAD();
- // CPHS was widely introduced in Europe during GSM(2G) era to provide easier
- // access to carrier's core service like voicemail, call forwarding, manual
- // PLMN selection, and etc.
- // Addition EF like EF_CPHS_MBN, EF_CPHS_CPHS_CFF, EF_CPHS_VWI, etc are
- // introduced to support these feature.
- // In USIM, the replancement of these EFs are provided. (EF_MBDN, EF_MWIS, ...)
- // However, some carriers in Europe still rely on these EFs.
- this.readCphsInfo(() => this.readSST(),
- (aErrorMsg) => {
- this.context.debug("Failed to read CPHS_INFO: " + aErrorMsg);
- this.readSST();
- });
- },
-
- /**
- * Read EF_phase.
- * This EF is only available in SIM.
- */
- readSimPhase: function() {
- function callback() {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let phase = GsmPDUHelper.readHexOctet();
- // If EF_phase is coded '03' or greater, an ME supporting STK shall
- // perform the PROFILE DOWNLOAD procedure.
- if (RILQUIRKS_SEND_STK_PROFILE_DOWNLOAD &&
- phase >= ICC_PHASE_2_PROFILE_DOWNLOAD_REQUIRED) {
- this.context.RIL.sendStkTerminalProfile(STK_SUPPORTED_TERMINAL_PROFILE);
- }
-
- Buf.readStringDelimiter(strLen);
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_PHASE,
- callback: callback.bind(this)
- });
- },
-
- /**
- * Read the MSISDN from the (U)SIM.
- */
- readMSISDN: function() {
- function callback(options) {
- let RIL = this.context.RIL;
-
- let contact =
- this.context.ICCPDUHelper.readAlphaIdDiallingNumber(options.recordSize);
- if (!contact ||
- (RIL.iccInfo.msisdn !== undefined &&
- RIL.iccInfo.msisdn === contact.number)) {
- return;
- }
- RIL.iccInfo.msisdn = contact.number;
- if (DEBUG) this.context.debug("MSISDN: " + RIL.iccInfo.msisdn);
- this.context.ICCUtilsHelper.handleICCInfoChange();
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: ICC_EF_MSISDN,
- callback: callback.bind(this)
- });
- },
-
- /**
- * Read the AD (Administrative Data) from the (U)SIM.
- */
- readAD: function() {
- function callback() {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
- // Each octet is encoded into two chars.
- let octetLen = strLen / 2;
- let ad = this.context.GsmPDUHelper.readHexOctetArray(octetLen);
- Buf.readStringDelimiter(strLen);
-
- if (DEBUG) {
- let str = "";
- for (let i = 0; i < ad.length; i++) {
- str += ad[i] + ", ";
- }
- this.context.debug("AD: " + str);
- }
-
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- let RIL = this.context.RIL;
- // TS 31.102, clause 4.2.18 EFAD
- let mncLength = 0;
- if (ad && ad[3]) {
- mncLength = ad[3] & 0x0f;
- if (mncLength != 0x02 && mncLength != 0x03) {
- mncLength = 0;
- }
- }
- // The 4th byte of the response is the length of MNC.
- let mccMnc = ICCUtilsHelper.parseMccMncFromImsi(RIL.iccInfoPrivate.imsi,
- mncLength);
- if (mccMnc) {
- RIL.iccInfo.mcc = mccMnc.mcc;
- RIL.iccInfo.mnc = mccMnc.mnc;
- ICCUtilsHelper.handleICCInfoChange();
- }
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_AD,
- callback: callback.bind(this)
- });
- },
-
- /**
- * Read the SPN (Service Provider Name) from the (U)SIM.
- */
- readSPN: function() {
- function callback() {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
- // Each octet is encoded into two chars.
- let octetLen = strLen / 2;
- let spnDisplayCondition = this.context.GsmPDUHelper.readHexOctet();
- // Minus 1 because the first octet is used to store display condition.
- let spn = this.context.ICCPDUHelper.readAlphaIdentifier(octetLen - 1);
- Buf.readStringDelimiter(strLen);
-
- if (DEBUG) {
- this.context.debug("SPN: spn = " + spn +
- ", spnDisplayCondition = " + spnDisplayCondition);
- }
-
- let RIL = this.context.RIL;
- RIL.iccInfoPrivate.spnDisplayCondition = spnDisplayCondition;
- RIL.iccInfo.spn = spn;
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- ICCUtilsHelper.updateDisplayCondition();
- ICCUtilsHelper.handleICCInfoChange();
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_SPN,
- callback: callback.bind(this)
- });
- },
-
- readIMG: function(recordNumber, onsuccess, onerror) {
- function callback(options) {
- let RIL = this.context.RIL;
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let strLen = Buf.readInt32();
- // Each octet is encoded into two chars.
- let octetLen = strLen / 2;
-
- let numInstances = GsmPDUHelper.readHexOctet();
-
- // Data length is defined as 9n+1 or 9n+2. See TS 31.102, sub-clause
- // 4.6.1.1. However, it's likely to have padding appended so we have a
- // rather loose check.
- if (octetLen < (9 * numInstances + 1)) {
- Buf.seekIncoming((octetLen - 1) * Buf.PDU_HEX_OCTET_SIZE);
- Buf.readStringDelimiter(strLen);
- if (onerror) {
- onerror();
- }
- return;
- }
-
- let imgDescriptors = [];
- for (let i = 0; i < numInstances; i++) {
- imgDescriptors[i] = {
- width: GsmPDUHelper.readHexOctet(),
- height: GsmPDUHelper.readHexOctet(),
- codingScheme: GsmPDUHelper.readHexOctet(),
- fileId: (GsmPDUHelper.readHexOctet() << 8) |
- GsmPDUHelper.readHexOctet(),
- offset: (GsmPDUHelper.readHexOctet() << 8) |
- GsmPDUHelper.readHexOctet(),
- dataLen: (GsmPDUHelper.readHexOctet() << 8) |
- GsmPDUHelper.readHexOctet()
- };
- }
- Buf.seekIncoming((octetLen - 9 * numInstances - 1) * Buf.PDU_HEX_OCTET_SIZE);
- Buf.readStringDelimiter(strLen);
-
- let instances = [];
- let currentInstance = 0;
- let readNextInstance = (function(img) {
- instances[currentInstance] = img;
- currentInstance++;
-
- if (currentInstance < numInstances) {
- let imgDescriptor = imgDescriptors[currentInstance];
- this.readIIDF(imgDescriptor.fileId,
- imgDescriptor.offset,
- imgDescriptor.dataLen,
- imgDescriptor.codingScheme,
- readNextInstance,
- onerror);
- } else {
- if (onsuccess) {
- onsuccess(instances);
- }
- }
- }).bind(this);
-
- this.readIIDF(imgDescriptors[0].fileId,
- imgDescriptors[0].offset,
- imgDescriptors[0].dataLen,
- imgDescriptors[0].codingScheme,
- readNextInstance,
- onerror);
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: ICC_EF_IMG,
- recordNumber: recordNumber,
- callback: callback.bind(this),
- onerror: onerror
- });
- },
-
- readIIDF: function(fileId, offset, dataLen, codingScheme, onsuccess, onerror) {
- // Valid fileId is '4FXX', see TS 31.102, clause 4.6.1.2.
- if ((fileId >> 8) != 0x4F) {
- if (onerror) {
- onerror();
- }
- return;
- }
-
- function callback() {
- let Buf = this.context.Buf;
- let RIL = this.context.RIL;
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let strLen = Buf.readInt32();
- // Each octet is encoded into two chars.
- let octetLen = strLen / 2;
-
- if (octetLen < offset + dataLen) {
- // Data length is not enough. See TS 31.102, clause 4.6.1.1, the
- // paragraph "Bytes 8 and 9: Length of Image Instance Data."
- Buf.seekIncoming(octetLen * Buf.PDU_HEX_OCTET_SIZE);
- Buf.readStringDelimiter(strLen);
- if (onerror) {
- onerror();
- }
- return;
- }
-
- Buf.seekIncoming(offset * Buf.PDU_HEX_OCTET_SIZE);
-
- let rawData = {
- width: GsmPDUHelper.readHexOctet(),
- height: GsmPDUHelper.readHexOctet(),
- codingScheme: codingScheme
- };
-
- switch (codingScheme) {
- case ICC_IMG_CODING_SCHEME_BASIC:
- rawData.body = GsmPDUHelper.readHexOctetArray(
- dataLen - ICC_IMG_HEADER_SIZE_BASIC);
- Buf.seekIncoming((octetLen - offset - dataLen) * Buf.PDU_HEX_OCTET_SIZE);
- break;
-
- case ICC_IMG_CODING_SCHEME_COLOR:
- case ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY:
- rawData.bitsPerImgPoint = GsmPDUHelper.readHexOctet();
- let num = GsmPDUHelper.readHexOctet();
- // The value 0 shall be interpreted as 256. See TS 31.102, Annex B.2.
- rawData.numOfClutEntries = (num === 0) ? 0x100 : num;
- rawData.clutOffset = (GsmPDUHelper.readHexOctet() << 8) |
- GsmPDUHelper.readHexOctet();
- rawData.body = GsmPDUHelper.readHexOctetArray(
- dataLen - ICC_IMG_HEADER_SIZE_COLOR);
-
- Buf.seekIncoming((rawData.clutOffset - offset - dataLen) *
- Buf.PDU_HEX_OCTET_SIZE);
- let clut = GsmPDUHelper.readHexOctetArray(rawData.numOfClutEntries *
- ICC_CLUT_ENTRY_SIZE);
-
- rawData.clut = clut;
- }
-
- Buf.readStringDelimiter(strLen);
-
- if (onsuccess) {
- onsuccess(rawData);
- }
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: fileId,
- pathId: this.context.ICCFileHelper.getEFPath(ICC_EF_IMG),
- callback: callback.bind(this),
- onerror: onerror
- });
- },
-
- /**
- * Read the (U)SIM Service Table from the (U)SIM.
- */
- readSST: function() {
- function callback() {
- let Buf = this.context.Buf;
- let RIL = this.context.RIL;
-
- let strLen = Buf.readInt32();
- // Each octet is encoded into two chars.
- let octetLen = strLen / 2;
- let sst = this.context.GsmPDUHelper.readHexOctetArray(octetLen);
- Buf.readStringDelimiter(strLen);
- RIL.iccInfoPrivate.sst = sst;
- if (DEBUG) {
- let str = "";
- for (let i = 0; i < sst.length; i++) {
- str += sst[i] + ", ";
- }
- this.context.debug("SST: " + str);
- }
-
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- if (ICCUtilsHelper.isICCServiceAvailable("MSISDN")) {
- if (DEBUG) this.context.debug("MSISDN: MSISDN is available");
- this.readMSISDN();
- } else {
- if (DEBUG) this.context.debug("MSISDN: MSISDN service is not available");
- }
-
- // Fetch SPN and PLMN list, if some of them are available.
- if (ICCUtilsHelper.isICCServiceAvailable("SPN")) {
- if (DEBUG) this.context.debug("SPN: SPN is available");
- this.readSPN();
- } else {
- if (DEBUG) this.context.debug("SPN: SPN service is not available");
- }
-
- if (ICCUtilsHelper.isICCServiceAvailable("MDN")) {
- if (DEBUG) this.context.debug("MDN: MDN available.");
- this.readMBDN();
- } else {
- if (DEBUG) this.context.debug("MDN: MDN service is not available");
-
- if (ICCUtilsHelper.isCphsServiceAvailable("MBN")) {
- // read CPHS_MBN in advance if MBDN is not available.
- this.readCphsMBN();
- } else {
- if (DEBUG) this.context.debug("CPHS_MBN: CPHS_MBN service is not available");
- }
- }
-
- if (ICCUtilsHelper.isICCServiceAvailable("MWIS")) {
- if (DEBUG) this.context.debug("MWIS: MWIS is available");
- this.readMWIS();
- } else {
- if (DEBUG) this.context.debug("MWIS: MWIS is not available");
- }
-
- if (ICCUtilsHelper.isICCServiceAvailable("SPDI")) {
- if (DEBUG) this.context.debug("SPDI: SPDI available.");
- this.readSPDI();
- } else {
- if (DEBUG) this.context.debug("SPDI: SPDI service is not available");
- }
-
- if (ICCUtilsHelper.isICCServiceAvailable("PNN")) {
- if (DEBUG) this.context.debug("PNN: PNN is available");
- this.readPNN();
- } else {
- if (DEBUG) this.context.debug("PNN: PNN is not available");
- }
-
- if (ICCUtilsHelper.isICCServiceAvailable("OPL")) {
- if (DEBUG) this.context.debug("OPL: OPL is available");
- this.readOPL();
- } else {
- if (DEBUG) this.context.debug("OPL: OPL is not available");
- }
-
- if (ICCUtilsHelper.isICCServiceAvailable("GID1")) {
- if (DEBUG) this.context.debug("GID1: GID1 is available");
- this.readGID1();
- } else {
- if (DEBUG) this.context.debug("GID1: GID1 is not available");
- }
-
- if (ICCUtilsHelper.isICCServiceAvailable("CBMI")) {
- this.readCBMI();
- } else {
- RIL.cellBroadcastConfigs.CBMI = null;
- }
- if (ICCUtilsHelper.isICCServiceAvailable("DATA_DOWNLOAD_SMS_CB")) {
- this.readCBMID();
- } else {
- RIL.cellBroadcastConfigs.CBMID = null;
- }
- if (ICCUtilsHelper.isICCServiceAvailable("CBMIR")) {
- this.readCBMIR();
- } else {
- RIL.cellBroadcastConfigs.CBMIR = null;
- }
- RIL._mergeAllCellBroadcastConfigs();
- }
-
- // ICC_EF_UST has the same value with ICC_EF_SST.
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_SST,
- callback: callback.bind(this)
- });
- },
-
- /**
- * Read (U)SIM MBDN. (Mailbox Dialling Number)
- *
- * @see TS 131.102, clause 4.2.60
- */
- readMBDN: function() {
- function callback(options) {
- let RIL = this.context.RIL;
- let contact =
- this.context.ICCPDUHelper.readAlphaIdDiallingNumber(options.recordSize);
- if ((!contact ||
- ((!contact.alphaId || contact.alphaId == "") &&
- (!contact.number || contact.number == ""))) &&
- this.context.ICCUtilsHelper.isCphsServiceAvailable("MBN")) {
- // read CPHS_MBN in advance if MBDN is invalid or empty.
- this.readCphsMBN();
- return;
- }
-
- if (!contact ||
- (RIL.iccInfoPrivate.mbdn !== undefined &&
- RIL.iccInfoPrivate.mbdn === contact.number)) {
- return;
- }
- RIL.iccInfoPrivate.mbdn = contact.number;
- if (DEBUG) {
- this.context.debug("MBDN, alphaId=" + contact.alphaId +
- " number=" + contact.number);
- }
- contact.rilMessageType = "iccmbdn";
- RIL.sendChromeMessage(contact);
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: ICC_EF_MBDN,
- callback: callback.bind(this)
- });
- },
-
- /**
- * Read ICC MWIS. (Message Waiting Indication Status)
- *
- * @see TS 31.102, clause 4.2.63 for USIM and TS 51.011, clause 10.3.45 for SIM.
- */
- readMWIS: function() {
- function callback(options) {
- let Buf = this.context.Buf;
- let RIL = this.context.RIL;
-
- let strLen = Buf.readInt32();
- // Each octet is encoded into two chars.
- let octetLen = strLen / 2;
- let mwis = this.context.GsmPDUHelper.readHexOctetArray(octetLen);
- Buf.readStringDelimiter(strLen);
- if (!mwis) {
- return;
- }
- RIL.iccInfoPrivate.mwis = mwis; //Keep raw MWIS for updateMWIS()
-
- let mwi = {};
- // b8 b7 B6 b5 b4 b3 b2 b1 4.2.63, TS 31.102 version 11.6.0
- // | | | | | | | |__ Voicemail
- // | | | | | | |_____ Fax
- // | | | | | |________ Electronic Mail
- // | | | | |___________ Other
- // | | | |______________ Videomail
- // |__|__|_________________ RFU
- mwi.active = ((mwis[0] & 0x01) != 0);
-
- if (mwi.active) {
- // In TS 23.040 msgCount is in the range from 0 to 255.
- // The value 255 shall be taken to mean 255 or greater.
- //
- // However, There is no definition about 0 when MWI is active.
- //
- // Normally, when mwi is active, the msgCount must be larger than 0.
- // Refer to other reference phone,
- // 0 is usually treated as UNKNOWN for storing 2nd level MWI status (DCS).
- mwi.msgCount = (mwis[1] === 0) ? GECKO_VOICEMAIL_MESSAGE_COUNT_UNKNOWN
- : mwis[1];
- } else {
- mwi.msgCount = 0;
- }
-
- RIL.sendChromeMessage({ rilMessageType: "iccmwis",
- mwi: mwi });
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: ICC_EF_MWIS,
- recordNumber: 1, // Get 1st Subscriber Profile.
- callback: callback.bind(this)
- });
- },
-
- /**
- * Update ICC MWIS. (Message Waiting Indication Status)
- *
- * @see TS 31.102, clause 4.2.63 for USIM and TS 51.011, clause 10.3.45 for SIM.
- */
- updateMWIS: function(mwi) {
- let RIL = this.context.RIL;
- if (!RIL.iccInfoPrivate.mwis) {
- return;
- }
-
- function dataWriter(recordSize) {
- let mwis = RIL.iccInfoPrivate.mwis;
-
- let msgCount =
- (mwi.msgCount === GECKO_VOICEMAIL_MESSAGE_COUNT_UNKNOWN) ? 0 : mwi.msgCount;
-
- [mwis[0], mwis[1]] = (mwi.active) ? [(mwis[0] | 0x01), msgCount]
- : [(mwis[0] & 0xFE), 0];
-
- let strLen = recordSize * 2;
- let Buf = this.context.Buf;
- Buf.writeInt32(strLen);
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
- for (let i = 0; i < mwis.length; i++) {
- GsmPDUHelper.writeHexOctet(mwis[i]);
- }
-
- Buf.writeStringDelimiter(strLen);
- }
-
- this.context.ICCIOHelper.updateLinearFixedEF({
- fileId: ICC_EF_MWIS,
- recordNumber: 1, // Update 1st Subscriber Profile.
- dataWriter: dataWriter.bind(this)
- });
- },
-
- /**
- * Read the SPDI (Service Provider Display Information) from the (U)SIM.
- *
- * See TS 131.102 section 4.2.66 for USIM and TS 51.011 section 10.3.50
- * for SIM.
- */
- readSPDI: function() {
- function callback() {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
- let octetLen = strLen / 2;
- let readLen = 0;
- let endLoop = false;
-
- let RIL = this.context.RIL;
- RIL.iccInfoPrivate.SPDI = null;
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
- while ((readLen < octetLen) && !endLoop) {
- let tlvTag = GsmPDUHelper.readHexOctet();
- let tlvLen = GsmPDUHelper.readHexOctet();
- readLen += 2; // For tag and length fields.
- switch (tlvTag) {
- case SPDI_TAG_SPDI:
- // The value part itself is a TLV.
- continue;
- case SPDI_TAG_PLMN_LIST:
- // This PLMN list is what we want.
- RIL.iccInfoPrivate.SPDI = this.readPLMNEntries(tlvLen / 3);
- readLen += tlvLen;
- endLoop = true;
- break;
- default:
- // We don't care about its content if its tag is not SPDI nor
- // PLMN_LIST.
- endLoop = true;
- break;
- }
- }
-
- // Consume unread octets.
- Buf.seekIncoming((octetLen - readLen) * Buf.PDU_HEX_OCTET_SIZE);
- Buf.readStringDelimiter(strLen);
-
- if (DEBUG) {
- this.context.debug("SPDI: " + JSON.stringify(RIL.iccInfoPrivate.SPDI));
- }
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- if (ICCUtilsHelper.updateDisplayCondition()) {
- ICCUtilsHelper.handleICCInfoChange();
- }
- }
-
- // PLMN List is Servive 51 in USIM, EF_SPDI
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_SPDI,
- callback: callback.bind(this)
- });
- },
-
- _readCbmiHelper: function(which) {
- let RIL = this.context.RIL;
-
- function callback() {
- let Buf = this.context.Buf;
- let strLength = Buf.readInt32();
-
- // Each Message Identifier takes two octets and each octet is encoded
- // into two chars.
- let numIds = strLength / 4, list = null;
- if (numIds) {
- list = [];
- let GsmPDUHelper = this.context.GsmPDUHelper;
- for (let i = 0, id; i < numIds; i++) {
- id = GsmPDUHelper.readHexOctet() << 8 | GsmPDUHelper.readHexOctet();
- // `Unused entries shall be set to 'FF FF'.`
- if (id != 0xFFFF) {
- list.push(id);
- list.push(id + 1);
- }
- }
- }
- if (DEBUG) {
- this.context.debug(which + ": " + JSON.stringify(list));
- }
-
- Buf.readStringDelimiter(strLength);
-
- RIL.cellBroadcastConfigs[which] = list;
- RIL._mergeAllCellBroadcastConfigs();
- }
-
- function onerror() {
- RIL.cellBroadcastConfigs[which] = null;
- RIL._mergeAllCellBroadcastConfigs();
- }
-
- let fileId = GLOBAL["ICC_EF_" + which];
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: fileId,
- callback: callback.bind(this),
- onerror: onerror.bind(this)
- });
- },
-
- /**
- * Read EFcbmi (Cell Broadcast Message Identifier selection)
- *
- * @see 3GPP TS 31.102 v110.02.0 section 4.2.14 EFcbmi
- * @see 3GPP TS 51.011 v5.0.0 section 10.3.13 EFcbmi
- */
- readCBMI: function() {
- this._readCbmiHelper("CBMI");
- },
-
- /**
- * Read EFcbmid (Cell Broadcast Message Identifier for Data Download)
- *
- * @see 3GPP TS 31.102 v110.02.0 section 4.2.20 EFcbmid
- * @see 3GPP TS 51.011 v5.0.0 section 10.3.26 EFcbmid
- */
- readCBMID: function() {
- this._readCbmiHelper("CBMID");
- },
-
- /**
- * Read EFcbmir (Cell Broadcast Message Identifier Range selection)
- *
- * @see 3GPP TS 31.102 v110.02.0 section 4.2.22 EFcbmir
- * @see 3GPP TS 51.011 v5.0.0 section 10.3.28 EFcbmir
- */
- readCBMIR: function() {
- let RIL = this.context.RIL;
-
- function callback() {
- let Buf = this.context.Buf;
- let strLength = Buf.readInt32();
-
- // Each Message Identifier range takes four octets and each octet is
- // encoded into two chars.
- let numIds = strLength / 8, list = null;
- if (numIds) {
- list = [];
- let GsmPDUHelper = this.context.GsmPDUHelper;
- for (let i = 0, from, to; i < numIds; i++) {
- // `Bytes one and two of each range identifier equal the lower value
- // of a cell broadcast range, bytes three and four equal the upper
- // value of a cell broadcast range.`
- from = GsmPDUHelper.readHexOctet() << 8 | GsmPDUHelper.readHexOctet();
- to = GsmPDUHelper.readHexOctet() << 8 | GsmPDUHelper.readHexOctet();
- // `Unused entries shall be set to 'FF FF'.`
- if ((from != 0xFFFF) && (to != 0xFFFF)) {
- list.push(from);
- list.push(to + 1);
- }
- }
- }
- if (DEBUG) {
- this.context.debug("CBMIR: " + JSON.stringify(list));
- }
-
- Buf.readStringDelimiter(strLength);
-
- RIL.cellBroadcastConfigs.CBMIR = list;
- RIL._mergeAllCellBroadcastConfigs();
- }
-
- function onerror() {
- RIL.cellBroadcastConfigs.CBMIR = null;
- RIL._mergeAllCellBroadcastConfigs();
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_CBMIR,
- callback: callback.bind(this),
- onerror: onerror.bind(this)
- });
- },
-
- /**
- * Read OPL (Operator PLMN List) from (U)SIM.
- *
- * See 3GPP TS 31.102 Sec. 4.2.59 for USIM
- * 3GPP TS 51.011 Sec. 10.3.42 for SIM.
- */
- readOPL: function() {
- let ICCIOHelper = this.context.ICCIOHelper;
- let opl = [];
- function callback(options) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let strLen = Buf.readInt32();
- // The first 7 bytes are LAI (for UMTS) and the format of LAI is defined
- // in 3GPP TS 23.003, Sec 4.1
- // +-------------+---------+
- // | Octet 1 - 3 | MCC/MNC |
- // +-------------+---------+
- // | Octet 4 - 7 | LAC |
- // +-------------+---------+
- let mccMnc = [GsmPDUHelper.readHexOctet(),
- GsmPDUHelper.readHexOctet(),
- GsmPDUHelper.readHexOctet()];
- if (mccMnc[0] != 0xFF || mccMnc[1] != 0xFF || mccMnc[2] != 0xFF) {
- let oplElement = {};
- let semiOctets = [];
- for (let i = 0; i < mccMnc.length; i++) {
- semiOctets.push((mccMnc[i] & 0xf0) >> 4);
- semiOctets.push(mccMnc[i] & 0x0f);
- }
- let reformat = [semiOctets[1], semiOctets[0], semiOctets[3],
- semiOctets[5], semiOctets[4], semiOctets[2]];
- let buf = "";
- for (let i = 0; i < reformat.length; i++) {
- if (reformat[i] != 0xF) {
- buf += GsmPDUHelper.semiOctetToExtendedBcdChar(reformat[i]);
- }
- if (i === 2) {
- // 0-2: MCC
- oplElement.mcc = buf;
- buf = "";
- } else if (i === 5) {
- // 3-5: MNC
- oplElement.mnc = buf;
- }
- }
- // LAC/TAC
- oplElement.lacTacStart =
- (GsmPDUHelper.readHexOctet() << 8) | GsmPDUHelper.readHexOctet();
- oplElement.lacTacEnd =
- (GsmPDUHelper.readHexOctet() << 8) | GsmPDUHelper.readHexOctet();
- // PLMN Network Name Record Identifier
- oplElement.pnnRecordId = GsmPDUHelper.readHexOctet();
- if (DEBUG) {
- this.context.debug("OPL: [" + (opl.length + 1) + "]: " +
- JSON.stringify(oplElement));
- }
- opl.push(oplElement);
- } else {
- Buf.seekIncoming(5 * Buf.PDU_HEX_OCTET_SIZE);
- }
- Buf.readStringDelimiter(strLen);
-
- let RIL = this.context.RIL;
- if (options.p1 < options.totalRecords) {
- ICCIOHelper.loadNextRecord(options);
- } else {
- RIL.iccInfoPrivate.OPL = opl;
- RIL.overrideICCNetworkName();
- }
- }
-
- ICCIOHelper.loadLinearFixedEF({fileId: ICC_EF_OPL,
- callback: callback.bind(this)});
- },
-
- /**
- * Read PNN (PLMN Network Name) from (U)SIM.
- *
- * See 3GPP TS 31.102 Sec. 4.2.58 for USIM
- * 3GPP TS 51.011 Sec. 10.3.41 for SIM.
- */
- readPNN: function() {
- let ICCIOHelper = this.context.ICCIOHelper;
- function callback(options) {
- let pnnElement;
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
- let octetLen = strLen / 2;
- let readLen = 0;
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
- while (readLen < octetLen) {
- let tlvTag = GsmPDUHelper.readHexOctet();
-
- if (tlvTag == 0xFF) {
- // Unused byte
- readLen++;
- Buf.seekIncoming((octetLen - readLen) * Buf.PDU_HEX_OCTET_SIZE);
- break;
- }
-
- // Needs this check to avoid initializing twice.
- pnnElement = pnnElement || {};
-
- let tlvLen = GsmPDUHelper.readHexOctet();
-
- switch (tlvTag) {
- case PNN_IEI_FULL_NETWORK_NAME:
- pnnElement.fullName = GsmPDUHelper.readNetworkName(tlvLen);
- break;
- case PNN_IEI_SHORT_NETWORK_NAME:
- pnnElement.shortName = GsmPDUHelper.readNetworkName(tlvLen);
- break;
- default:
- Buf.seekIncoming(tlvLen * Buf.PDU_HEX_OCTET_SIZE);
- break;
- }
-
- readLen += (tlvLen + 2); // +2 for tlvTag and tlvLen
- }
- Buf.readStringDelimiter(strLen);
-
- pnn.push(pnnElement);
-
- let RIL = this.context.RIL;
- if (options.p1 < options.totalRecords) {
- ICCIOHelper.loadNextRecord(options);
- } else {
- if (DEBUG) {
- for (let i = 0; i < pnn.length; i++) {
- this.context.debug("PNN: [" + i + "]: " + JSON.stringify(pnn[i]));
- }
- }
- RIL.iccInfoPrivate.PNN = pnn;
- RIL.overrideICCNetworkName();
- }
- }
-
- let pnn = [];
- ICCIOHelper.loadLinearFixedEF({fileId: ICC_EF_PNN,
- callback: callback.bind(this)});
- },
-
- /**
- * Read the list of PLMN (Public Land Mobile Network) entries
- * We cannot directly rely on readSwappedNibbleBcdToString(),
- * since it will no correctly handle some corner-cases that are
- * not a problem in our case (0xFF 0xFF 0xFF).
- *
- * @param length The number of PLMN records.
- * @return An array of string corresponding to the PLMNs.
- */
- readPLMNEntries: function(length) {
- let plmnList = [];
- // Each PLMN entry has 3 bytes.
- if (DEBUG) {
- this.context.debug("PLMN entries length = " + length);
- }
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let index = 0;
- while (index < length) {
- // Unused entries will be 0xFFFFFF, according to EF_SPDI
- // specs (TS 131 102, section 4.2.66)
- try {
- let plmn = [GsmPDUHelper.readHexOctet(),
- GsmPDUHelper.readHexOctet(),
- GsmPDUHelper.readHexOctet()];
- if (DEBUG) {
- this.context.debug("Reading PLMN entry: [" + index + "]: '" + plmn + "'");
- }
- if (plmn[0] != 0xFF &&
- plmn[1] != 0xFF &&
- plmn[2] != 0xFF) {
- let semiOctets = [];
- for (let idx = 0; idx < plmn.length; idx++) {
- semiOctets.push((plmn[idx] & 0xF0) >> 4);
- semiOctets.push(plmn[idx] & 0x0F);
- }
-
- // According to TS 24.301, 9.9.3.12, the semi octets is arranged
- // in format:
- // Byte 1: MCC[2] | MCC[1]
- // Byte 2: MNC[3] | MCC[3]
- // Byte 3: MNC[2] | MNC[1]
- // Therefore, we need to rearrange them.
- let reformat = [semiOctets[1], semiOctets[0], semiOctets[3],
- semiOctets[5], semiOctets[4], semiOctets[2]];
- let buf = "";
- let plmnEntry = {};
- for (let i = 0; i < reformat.length; i++) {
- if (reformat[i] != 0xF) {
- buf += GsmPDUHelper.semiOctetToExtendedBcdChar(reformat[i]);
- }
- if (i === 2) {
- // 0-2: MCC
- plmnEntry.mcc = buf;
- buf = "";
- } else if (i === 5) {
- // 3-5: MNC
- plmnEntry.mnc = buf;
- }
- }
- if (DEBUG) {
- this.context.debug("PLMN = " + plmnEntry.mcc + ", " + plmnEntry.mnc);
- }
- plmnList.push(plmnEntry);
- }
- } catch (e) {
- if (DEBUG) {
- this.context.debug("PLMN entry " + index + " is invalid.");
- }
- break;
- }
- index ++;
- }
- return plmnList;
- },
-
- /**
- * Read the SMS from the ICC.
- *
- * @param recordNumber The number of the record shall be loaded.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readSMS: function(recordNumber, onsuccess, onerror) {
- function callback(options) {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
-
- // TS 51.011, 10.5.3 EF_SMS
- // b3 b2 b1
- // 0 0 1 message received by MS from network; message read
- // 0 1 1 message received by MS from network; message to be read
- // 1 1 1 MS originating message; message to be sent
- // 1 0 1 MS originating message; message sent to the network:
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let status = GsmPDUHelper.readHexOctet();
-
- let message = GsmPDUHelper.readMessage();
- message.simStatus = status;
-
- // Consumes the remaining buffer
- Buf.seekIncoming(Buf.getReadAvailable() - Buf.PDU_HEX_OCTET_SIZE);
-
- Buf.readStringDelimiter(strLen);
-
- if (message) {
- onsuccess(message);
- } else {
- onerror("Failed to decode SMS on SIM #" + recordNumber);
- }
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: ICC_EF_SMS,
- recordNumber: recordNumber,
- callback: callback.bind(this),
- onerror: onerror
- });
- },
-
- readGID1: function() {
- function callback() {
- let Buf = this.context.Buf;
- let RIL = this.context.RIL;
-
- RIL.iccInfoPrivate.gid1 = Buf.readString();
- if (DEBUG) {
- this.context.debug("GID1: " + RIL.iccInfoPrivate.gid1);
- }
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_GID1,
- callback: callback.bind(this)
- });
- },
-
- /**
- * Read CPHS Phase & Service Table from CPHS Info.
- *
- * @See B.3.1.1 CPHS Information in CPHS Phase 2.
- *
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readCphsInfo: function(onsuccess, onerror) {
- function callback() {
- try {
- let Buf = this.context.Buf;
- let RIL = this.context.RIL;
-
- let strLen = Buf.readInt32();
- // Each octet is encoded into two chars.
- let octetLen = strLen / 2;
- let cphsInfo = this.context.GsmPDUHelper.readHexOctetArray(octetLen);
- Buf.readStringDelimiter(strLen);
- if (DEBUG) {
- let str = "";
- for (let i = 0; i < cphsInfo.length; i++) {
- str += cphsInfo[i] + ", ";
- }
- this.context.debug("CPHS INFO: " + str);
- }
-
- /**
- * CPHS INFORMATION
- *
- * Byte 1: CPHS Phase
- * 01 phase 1
- * 02 phase 2
- * etc.
- *
- * Byte 2: CPHS Service Table
- * +----+----+----+----+----+----+----+----+
- * | b8 | b7 | b6 | b5 | b4 | b3 | b2 | b1 |
- * +----+----+----+----+----+----+----+----+
- * | ONSF | MBN | SST | CSP |
- * | Phase 2 | ALL | Phase 1 | All |
- * +----+----+----+----+----+----+----+----+
- *
- * Byte 3: CPHS Service Table continued
- * +----+----+----+----+----+----+----+----+
- * | b8 | b7 | b6 | b5 | b4 | b3 | b2 | b1 |
- * +----+----+----+----+----+----+----+----+
- * | RFU | RFU | RFU | INFO_NUM|
- * | | | | Phase 2 |
- * +----+----+----+----+----+----+----+----+
- */
- let cphsPhase = cphsInfo[0];
- if (cphsPhase == 1) {
- // Clear 'Phase 2 only' services.
- cphsInfo[1] &= 0x3F;
- // We don't know whether Byte 3 is available in CPHS phase 1 or not.
- // Add boundary check before accessing it.
- if (cphsInfo.length > 2) {
- cphsInfo[2] = 0x00;
- }
- } else if (cphsPhase == 2) {
- // Clear 'Phase 1 only' services.
- cphsInfo[1] &= 0xF3;
- } else {
- throw new Error("Unknown CPHS phase: " + cphsPhase);
- }
-
- RIL.iccInfoPrivate.cphsSt = cphsInfo.subarray(1);
- onsuccess();
- } catch(e) {
- onerror(e.toString());
- }
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_CPHS_INFO,
- callback: callback.bind(this),
- onerror: onerror
- });
- },
-
- /**
- * Read CPHS MBN. (Mailbox Numbers)
- *
- * @See B.4.2.2 Voice Message Retrieval and Indicator Clearing
- */
- readCphsMBN: function() {
- function callback(options) {
- let RIL = this.context.RIL;
- let contact =
- this.context.ICCPDUHelper.readAlphaIdDiallingNumber(options.recordSize);
- if (!contact ||
- (RIL.iccInfoPrivate.mbdn !== undefined &&
- RIL.iccInfoPrivate.mbdn === contact.number)) {
- return;
- }
- RIL.iccInfoPrivate.mbdn = contact.number;
- if (DEBUG) {
- this.context.debug("CPHS_MDN, alphaId=" + contact.alphaId +
- " number=" + contact.number);
- }
- contact.rilMessageType = "iccmbdn";
- RIL.sendChromeMessage(contact);
- }
-
- this.context.ICCIOHelper.loadLinearFixedEF({
- fileId: ICC_EF_CPHS_MBN,
- callback: callback.bind(this)
- });
- }
-};
-
-function RuimRecordHelperObject(aContext) {
- this.context = aContext;
-}
-RuimRecordHelperObject.prototype = {
- context: null,
-
- fetchRuimRecords: function() {
- this.getIMSI_M();
- this.readCST();
- this.readCDMAHome();
- this.context.RIL.getCdmaSubscription();
- },
-
- /**
- * Get IMSI_M from CSIM/RUIM.
- * See 3GPP2 C.S0065 Sec. 5.2.2
- */
- getIMSI_M: function() {
- function callback() {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
- let encodedImsi = this.context.GsmPDUHelper.readHexOctetArray(strLen / 2);
- Buf.readStringDelimiter(strLen);
-
- if ((encodedImsi[CSIM_IMSI_M_PROGRAMMED_BYTE] & 0x80)) { // IMSI_M programmed
- let RIL = this.context.RIL;
- RIL.iccInfoPrivate.imsi = this.decodeIMSI(encodedImsi);
- RIL.sendChromeMessage({rilMessageType: "iccimsi",
- imsi: RIL.iccInfoPrivate.imsi});
-
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- let mccMnc = ICCUtilsHelper.parseMccMncFromImsi(RIL.iccInfoPrivate.imsi);
- if (mccMnc) {
- RIL.iccInfo.mcc = mccMnc.mcc;
- RIL.iccInfo.mnc = mccMnc.mnc;
- ICCUtilsHelper.handleICCInfoChange();
- }
- }
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_CSIM_IMSI_M,
- callback: callback.bind(this)
- });
- },
-
- /**
- * Decode IMSI from IMSI_M
- * See 3GPP2 C.S0005 Sec. 2.3.1
- * +---+---------+------------+---+--------+---------+---+---------+--------+
- * |RFU| MCC | programmed |RFU| MNC | MIN1 |RFU| MIN2 | CLASS |
- * +---+---------+------------+---+--------+---------+---+---------+--------+
- * | 6 | 10 bits | 8 bits | 1 | 7 bits | 24 bits | 6 | 10 bits | 8 bits |
- * +---+---------+------------+---+--------+---------+---+---------+--------+
- */
- decodeIMSI: function(encodedImsi) {
- // MCC: 10 bits, 3 digits
- let encodedMCC = ((encodedImsi[CSIM_IMSI_M_MCC_BYTE + 1] & 0x03) << 8) +
- (encodedImsi[CSIM_IMSI_M_MCC_BYTE] & 0xff);
- let mcc = this.decodeIMSIValue(encodedMCC, 3);
-
- // MNC: 7 bits, 2 digits
- let encodedMNC = encodedImsi[CSIM_IMSI_M_MNC_BYTE] & 0x7f;
- let mnc = this.decodeIMSIValue(encodedMNC, 2);
-
- // MIN2: 10 bits, 3 digits
- let encodedMIN2 = ((encodedImsi[CSIM_IMSI_M_MIN2_BYTE + 1] & 0x03) << 8) +
- (encodedImsi[CSIM_IMSI_M_MIN2_BYTE] & 0xff);
- let min2 = this.decodeIMSIValue(encodedMIN2, 3);
-
- // MIN1: 10+4+10 bits, 3+1+3 digits
- let encodedMIN1First3 = ((encodedImsi[CSIM_IMSI_M_MIN1_BYTE + 2] & 0xff) << 2) +
- ((encodedImsi[CSIM_IMSI_M_MIN1_BYTE + 1] & 0xc0) >> 6);
- let min1First3 = this.decodeIMSIValue(encodedMIN1First3, 3);
-
- let encodedFourthDigit = (encodedImsi[CSIM_IMSI_M_MIN1_BYTE + 1] & 0x3c) >> 2;
- if (encodedFourthDigit > 9) {
- encodedFourthDigit = 0;
- }
- let fourthDigit = encodedFourthDigit.toString();
-
- let encodedMIN1Last3 = ((encodedImsi[CSIM_IMSI_M_MIN1_BYTE + 1] & 0x03) << 8) +
- (encodedImsi[CSIM_IMSI_M_MIN1_BYTE] & 0xff);
- let min1Last3 = this.decodeIMSIValue(encodedMIN1Last3, 3);
-
- return mcc + mnc + min2 + min1First3 + fourthDigit + min1Last3;
- },
-
- /**
- * Decode IMSI Helper function
- * See 3GPP2 C.S0005 section 2.3.1.1
- */
- decodeIMSIValue: function(encoded, length) {
- let offset = length === 3 ? 111 : 11;
- let value = encoded + offset;
-
- for (let base = 10, temp = value, i = 0; i < length; i++) {
- if (temp % 10 === 0) {
- value -= base;
- }
- temp = Math.floor(value / base);
- base = base * 10;
- }
-
- let s = value.toString();
- while (s.length < length) {
- s = "0" + s;
- }
-
- return s;
- },
-
- /**
- * Read CDMAHOME for CSIM.
- * See 3GPP2 C.S0023 Sec. 3.4.8.
- */
- readCDMAHome: function() {
- let ICCIOHelper = this.context.ICCIOHelper;
-
- function callback(options) {
- let Buf = this.context.Buf;
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let strLen = Buf.readInt32();
- let tempOctet = GsmPDUHelper.readHexOctet();
- cdmaHomeSystemId.push(((GsmPDUHelper.readHexOctet() & 0x7f) << 8) | tempOctet);
- tempOctet = GsmPDUHelper.readHexOctet();
- cdmaHomeNetworkId.push(((GsmPDUHelper.readHexOctet() & 0xff) << 8) | tempOctet);
-
- // Consuming the last octet: band class.
- Buf.seekIncoming(Buf.PDU_HEX_OCTET_SIZE);
-
- Buf.readStringDelimiter(strLen);
- if (options.p1 < options.totalRecords) {
- ICCIOHelper.loadNextRecord(options);
- } else {
- if (DEBUG) {
- this.context.debug("CDMAHome system id: " +
- JSON.stringify(cdmaHomeSystemId));
- this.context.debug("CDMAHome network id: " +
- JSON.stringify(cdmaHomeNetworkId));
- }
- this.context.RIL.cdmaHome = {
- systemId: cdmaHomeSystemId,
- networkId: cdmaHomeNetworkId
- };
- }
- }
-
- let cdmaHomeSystemId = [], cdmaHomeNetworkId = [];
- ICCIOHelper.loadLinearFixedEF({fileId: ICC_EF_CSIM_CDMAHOME,
- callback: callback.bind(this)});
- },
-
- /**
- * Read CDMA Service Table.
- * See 3GPP2 C.S0023 Sec. 3.4.18
- */
- readCST: function() {
- function callback() {
- let Buf = this.context.Buf;
- let RIL = this.context.RIL;
-
- let strLen = Buf.readInt32();
- // Each octet is encoded into two chars.
- RIL.iccInfoPrivate.cst =
- this.context.GsmPDUHelper.readHexOctetArray(strLen / 2);
- Buf.readStringDelimiter(strLen);
-
- if (DEBUG) {
- let str = "";
- for (let i = 0; i < RIL.iccInfoPrivate.cst.length; i++) {
- str += RIL.iccInfoPrivate.cst[i] + ", ";
- }
- this.context.debug("CST: " + str);
- }
-
- if (this.context.ICCUtilsHelper.isICCServiceAvailable("SPN")) {
- if (DEBUG) this.context.debug("SPN: SPN is available");
- this.readSPN();
- }
- }
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_CSIM_CST,
- callback: callback.bind(this)
- });
- },
-
- readSPN: function() {
- function callback() {
- let Buf = this.context.Buf;
- let strLen = Buf.readInt32();
- let octetLen = strLen / 2;
-
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let displayCondition = GsmPDUHelper.readHexOctet();
- let codingScheme = GsmPDUHelper.readHexOctet();
- // Skip one octet: language indicator.
- Buf.seekIncoming(Buf.PDU_HEX_OCTET_SIZE);
- let readLen = 3;
-
- // SPN String ends up with 0xff.
- let userDataBuffer = [];
-
- while (readLen < octetLen) {
- let octet = GsmPDUHelper.readHexOctet();
- readLen++;
- if (octet == 0xff) {
- break;
- }
- userDataBuffer.push(octet);
- }
-
- this.context.BitBufferHelper.startRead(userDataBuffer);
-
- let CdmaPDUHelper = this.context.CdmaPDUHelper;
- let msgLen;
- switch (CdmaPDUHelper.getCdmaMsgEncoding(codingScheme)) {
- case PDU_DCS_MSG_CODING_7BITS_ALPHABET:
- msgLen = Math.floor(userDataBuffer.length * 8 / 7);
- break;
- case PDU_DCS_MSG_CODING_8BITS_ALPHABET:
- msgLen = userDataBuffer.length;
- break;
- case PDU_DCS_MSG_CODING_16BITS_ALPHABET:
- msgLen = Math.floor(userDataBuffer.length / 2);
- break;
- }
-
- let RIL = this.context.RIL;
- RIL.iccInfo.spn = CdmaPDUHelper.decodeCdmaPDUMsg(codingScheme, null, msgLen);
- if (DEBUG) {
- this.context.debug("CDMA SPN: " + RIL.iccInfo.spn +
- ", Display condition: " + displayCondition);
- }
- RIL.iccInfoPrivate.spnDisplayCondition = displayCondition;
- Buf.seekIncoming((octetLen - readLen) * Buf.PDU_HEX_OCTET_SIZE);
- Buf.readStringDelimiter(strLen);
- }
-
- this.context.ICCIOHelper.loadTransparentEF({
- fileId: ICC_EF_CSIM_SPN,
- callback: callback.bind(this)
- });
- }
-};
-
-/**
- * Helper functions for ICC utilities.
- */
-function ICCUtilsHelperObject(aContext) {
- this.context = aContext;
-}
-ICCUtilsHelperObject.prototype = {
- context: null,
-
- /**
- * Get network names by using EF_OPL and EF_PNN
- *
- * @See 3GPP TS 31.102 sec. 4.2.58 and sec. 4.2.59 for USIM,
- * 3GPP TS 51.011 sec. 10.3.41 and sec. 10.3.42 for SIM.
- *
- * @param mcc The mobile country code of the network.
- * @param mnc The mobile network code of the network.
- * @param lac The location area code of the network.
- */
- getNetworkNameFromICC: function(mcc, mnc, lac) {
- let RIL = this.context.RIL;
- let iccInfoPriv = RIL.iccInfoPrivate;
- let iccInfo = RIL.iccInfo;
- let pnnEntry;
-
- if (!mcc || !mnc || lac == null || lac < 0) {
- return null;
- }
-
- // We won't get network name if there is no PNN file.
- if (!iccInfoPriv.PNN) {
- return null;
- }
-
- if (!this.isICCServiceAvailable("OPL")) {
- // When OPL is not present:
- // According to 3GPP TS 31.102 Sec. 4.2.58 and 3GPP TS 51.011 Sec. 10.3.41,
- // If EF_OPL is not present, the first record in this EF is used for the
- // default network name when registered to the HPLMN.
- // If we haven't get pnnEntry assigned, we should try to assign default
- // value to it.
- if (mcc == iccInfo.mcc && mnc == iccInfo.mnc) {
- pnnEntry = iccInfoPriv.PNN[0];
- }
- } else {
- let GsmPDUHelper = this.context.GsmPDUHelper;
- let wildChar = GsmPDUHelper.extendedBcdChars.charAt(0x0d);
- // According to 3GPP TS 31.102 Sec. 4.2.59 and 3GPP TS 51.011 Sec. 10.3.42,
- // the ME shall use this EF_OPL in association with the EF_PNN in place
- // of any network name stored within the ME's internal list and any network
- // name received when registered to the PLMN.
- let length = iccInfoPriv.OPL ? iccInfoPriv.OPL.length : 0;
- for (let i = 0; i < length; i++) {
- let unmatch = false;
- let opl = iccInfoPriv.OPL[i];
- // Try to match the MCC/MNC. Besides, A BCD value of 'D' in any of the
- // MCC and/or MNC digits shall be used to indicate a "wild" value for
- // that corresponding MCC/MNC digit.
- if (opl.mcc.indexOf(wildChar) !== -1) {
- for (let j = 0; j < opl.mcc.length; j++) {
- if (opl.mcc[j] !== wildChar && opl.mcc[j] !== mcc[j]) {
- unmatch = true;
- break;
- }
- }
- if (unmatch) {
- continue;
- }
- } else {
- if (mcc !== opl.mcc) {
- continue;
- }
- }
-
- if (mnc.length !== opl.mnc.length) {
- continue;
- }
-
- if (opl.mnc.indexOf(wildChar) !== -1) {
- for (let j = 0; j < opl.mnc.length; j++) {
- if (opl.mnc[j] !== wildChar && opl.mnc[j] !== mnc[j]) {
- unmatch = true;
- break;
- }
- }
- if (unmatch) {
- continue;
- }
- } else {
- if (mnc !== opl.mnc) {
- continue;
- }
- }
-
- // Try to match the location area code. If current local area code is
- // covered by lac range that specified in the OPL entry, use the PNN
- // that specified in the OPL entry.
- if ((opl.lacTacStart === 0x0 && opl.lacTacEnd == 0xFFFE) ||
- (opl.lacTacStart <= lac && opl.lacTacEnd >= lac)) {
- if (opl.pnnRecordId === 0) {
- // See 3GPP TS 31.102 Sec. 4.2.59 and 3GPP TS 51.011 Sec. 10.3.42,
- // A value of '00' indicates that the name is to be taken from other
- // sources.
- return null;
- }
- pnnEntry = iccInfoPriv.PNN[opl.pnnRecordId - 1];
- break;
- }
- }
- }
-
- if (!pnnEntry) {
- return null;
- }
-
- // Return a new object to avoid global variable, PNN, be modified by accident.
- return { fullName: pnnEntry.fullName || "",
- shortName: pnnEntry.shortName || "" };
- },
-
- /**
- * This will compute the spnDisplay field of the network.
- * See TS 22.101 Annex A and TS 51.011 10.3.11 for details.
- *
- * @return True if some of iccInfo is changed in by this function.
- */
- updateDisplayCondition: function() {
- let RIL = this.context.RIL;
-
- // If EFspn isn't existed in SIM or it haven't been read yet, we should
- // just set isDisplayNetworkNameRequired = true and
- // isDisplaySpnRequired = false
- let iccInfo = RIL.iccInfo;
- let iccInfoPriv = RIL.iccInfoPrivate;
- let displayCondition = iccInfoPriv.spnDisplayCondition;
- let origIsDisplayNetworkNameRequired = iccInfo.isDisplayNetworkNameRequired;
- let origIsDisplaySPNRequired = iccInfo.isDisplaySpnRequired;
-
- if (displayCondition === undefined) {
- iccInfo.isDisplayNetworkNameRequired = true;
- iccInfo.isDisplaySpnRequired = false;
- } else if (RIL._isCdma) {
- // CDMA family display rule.
- let cdmaHome = RIL.cdmaHome;
- let cell = RIL.voiceRegistrationState.cell;
- let sid = cell && cell.cdmaSystemId;
- let nid = cell && cell.cdmaNetworkId;
-
- iccInfo.isDisplayNetworkNameRequired = false;
-
- // If display condition is 0x0, we don't even need to check network id
- // or system id.
- if (displayCondition === 0x0) {
- iccInfo.isDisplaySpnRequired = false;
- } else {
- // CDMA SPN Display condition dosen't specify whenever network name is
- // reqired.
- if (!cdmaHome ||
- !cdmaHome.systemId ||
- cdmaHome.systemId.length === 0 ||
- cdmaHome.systemId.length != cdmaHome.networkId.length ||
- !sid || !nid) {
- // CDMA Home haven't been ready, or we haven't got the system id and
- // network id of the network we register to, assuming we are in home
- // network.
- iccInfo.isDisplaySpnRequired = true;
- } else {
- // Determine if we are registered in the home service area.
- // System ID and Network ID are described in 3GPP2 C.S0005 Sec. 2.6.5.2.
- let inHomeArea = false;
- for (let i = 0; i < cdmaHome.systemId.length; i++) {
- let homeSid = cdmaHome.systemId[i],
- homeNid = cdmaHome.networkId[i];
- if (homeSid === 0 || homeNid === 0 // Reserved system id/network id
- || homeSid != sid) {
- continue;
- }
- // According to 3GPP2 C.S0005 Sec. 2.6.5.2, NID number 65535 means
- // all networks in the system should be considered as home.
- if (homeNid == 65535 || homeNid == nid) {
- inHomeArea = true;
- break;
- }
- }
- iccInfo.isDisplaySpnRequired = inHomeArea;
- }
- }
- } else {
- // GSM family display rule.
- let operatorMnc = RIL.operator ? RIL.operator.mnc : -1;
- let operatorMcc = RIL.operator ? RIL.operator.mcc : -1;
-
- // First detect if we are on HPLMN or one of the PLMN
- // specified by the SIM card.
- let isOnMatchingPlmn = false;
-
- // If the current network is the one defined as mcc/mnc
- // in SIM card, it's okay.
- if (iccInfo.mcc == operatorMcc && iccInfo.mnc == operatorMnc) {
- isOnMatchingPlmn = true;
- }
-
- // Test to see if operator's mcc/mnc match mcc/mnc of PLMN.
- if (!isOnMatchingPlmn && iccInfoPriv.SPDI) {
- let iccSpdi = iccInfoPriv.SPDI; // PLMN list
- for (let plmn in iccSpdi) {
- let plmnMcc = iccSpdi[plmn].mcc;
- let plmnMnc = iccSpdi[plmn].mnc;
- isOnMatchingPlmn = (plmnMcc == operatorMcc) && (plmnMnc == operatorMnc);
- if (isOnMatchingPlmn) {
- break;
- }
- }
- }
-
- // See 3GPP TS 22.101 A.4 Service Provider Name indication, and TS 31.102
- // clause 4.2.12 EF_SPN for detail.
- if (isOnMatchingPlmn) {
- // The first bit of display condition tells us if we should display
- // registered PLMN.
- if (DEBUG) {
- this.context.debug("PLMN is HPLMN or PLMN " + "is in PLMN list");
- }
-
- // TS 31.102 Sec. 4.2.66 and TS 51.011 Sec. 10.3.50
- // EF_SPDI contains a list of PLMNs in which the Service Provider Name
- // shall be displayed.
- iccInfo.isDisplaySpnRequired = true;
- iccInfo.isDisplayNetworkNameRequired = (displayCondition & 0x01) !== 0;
- } else {
- // The second bit of display condition tells us if we should display
- // registered PLMN.
- if (DEBUG) {
- this.context.debug("PLMN isn't HPLMN and PLMN isn't in PLMN list");
- }
-
- iccInfo.isDisplayNetworkNameRequired = true;
- iccInfo.isDisplaySpnRequired = (displayCondition & 0x02) === 0;
- }
- }
-
- if (DEBUG) {
- this.context.debug("isDisplayNetworkNameRequired = " +
- iccInfo.isDisplayNetworkNameRequired);
- this.context.debug("isDisplaySpnRequired = " + iccInfo.isDisplaySpnRequired);
- }
-
- return ((origIsDisplayNetworkNameRequired !== iccInfo.isDisplayNetworkNameRequired) ||
- (origIsDisplaySPNRequired !== iccInfo.isDisplaySpnRequired));
- },
-
- decodeSimTlvs: function(tlvsLen) {
- let GsmPDUHelper = this.context.GsmPDUHelper;
-
- let index = 0;
- let tlvs = [];
- while (index < tlvsLen) {
- let simTlv = {
- tag : GsmPDUHelper.readHexOctet(),
- length : GsmPDUHelper.readHexOctet(),
- };
- simTlv.value = GsmPDUHelper.readHexOctetArray(simTlv.length);
- tlvs.push(simTlv);
- index += simTlv.length + 2; // The length of 'tag' and 'length' field.
- }
- return tlvs;
- },
-
- /**
- * Parse those TLVs and convert it to an object.
- */
- parsePbrTlvs: function(pbrTlvs) {
- let pbr = {};
- for (let i = 0; i < pbrTlvs.length; i++) {
- let pbrTlv = pbrTlvs[i];
- let anrIndex = 0;
- for (let j = 0; j < pbrTlv.value.length; j++) {
- let tlv = pbrTlv.value[j];
- let tagName = USIM_TAG_NAME[tlv.tag];
-
- // ANR could have multiple files. We save it as anr0, anr1,...etc.
- if (tlv.tag == ICC_USIM_EFANR_TAG) {
- tagName += anrIndex;
- anrIndex++;
- }
- pbr[tagName] = tlv;
- pbr[tagName].fileType = pbrTlv.tag;
- pbr[tagName].fileId = (tlv.value[0] << 8) | tlv.value[1];
- pbr[tagName].sfi = tlv.value[2];
-
- // For Type 2, the order of files is in the same order in IAP.
- if (pbrTlv.tag == ICC_USIM_TYPE2_TAG) {
- pbr[tagName].indexInIAP = j;
- }
- }
- }
-
- return pbr;
- },
-
- /**
- * Update the ICC information to RadioInterfaceLayer.
- */
- handleICCInfoChange: function() {
- let RIL = this.context.RIL;
- RIL.iccInfo.rilMessageType = "iccinfochange";
- RIL.sendChromeMessage(RIL.iccInfo);
- },
-
- /**
- * Get whether specificed (U)SIM service is available.
- *
- * @param geckoService
- * Service name like "ADN", "BDN", etc.
- *
- * @return true if the service is enabled, false otherwise.
- */
- isICCServiceAvailable: function(geckoService) {
- let RIL = this.context.RIL;
- let serviceTable = RIL._isCdma ? RIL.iccInfoPrivate.cst:
- RIL.iccInfoPrivate.sst;
- let index, bitmask;
- if (RIL.appType == CARD_APPTYPE_SIM || RIL.appType == CARD_APPTYPE_RUIM) {
- /**
- * Service id is valid in 1..N, and 2 bits are used to code each service.
- *
- * +----+-- --+----+----+
- * | b8 | ... | b2 | b1 |
- * +----+-- --+----+----+
- *
- * b1 = 0, service not allocated.
- * 1, service allocated.
- * b2 = 0, service not activated.
- * 1, service activated.
- *
- * @see 3GPP TS 51.011 10.3.7.
- */
- let simService;
- if (RIL.appType == CARD_APPTYPE_SIM) {
- simService = GECKO_ICC_SERVICES.sim[geckoService];
- } else {
- simService = GECKO_ICC_SERVICES.ruim[geckoService];
- }
- if (!simService) {
- return false;
- }
- simService -= 1;
- index = Math.floor(simService / 4);
- bitmask = 2 << ((simService % 4) << 1);
- } else if (RIL.appType == CARD_APPTYPE_USIM) {
- /**
- * Service id is valid in 1..N, and 1 bit is used to code each service.
- *
- * +----+-- --+----+----+
- * | b8 | ... | b2 | b1 |
- * +----+-- --+----+----+
- *
- * b1 = 0, service not avaiable.
- * 1, service available.
- *
- * @see 3GPP TS 31.102 4.2.8.
- */
- let usimService = GECKO_ICC_SERVICES.usim[geckoService];
- if (!usimService) {
- return false;
- }
- usimService -= 1;
- index = Math.floor(usimService / 8);
- bitmask = 1 << ((usimService % 8) << 0);
- }
-
- return (serviceTable !== null) &&
- (index < serviceTable.length) &&
- ((serviceTable[index] & bitmask) !== 0);
- },
-
- /**
- * Get whether specificed CPHS service is available.
- *
- * @param geckoService
- * Service name like "MDN", etc.
- *
- * @return true if the service is enabled, false otherwise.
- */
- isCphsServiceAvailable: function(geckoService) {
- let RIL = this.context.RIL;
- let serviceTable = RIL.iccInfoPrivate.cphsSt;
-
- if (!(serviceTable instanceof Uint8Array)) {
- return false;
- }
-
- /**
- * Service id is valid in 1..N, and 2 bits are used to code each service.
- *
- * +----+-- --+----+----+
- * | b8 | ... | b2 | b1 |
- * +----+-- --+----+----+
- *
- * b1 = 0, service not allocated.
- * 1, service allocated.
- * b2 = 0, service not activated.
- * 1, service activated.
- *
- * @See B.3.1.1 CPHS Information in CPHS Phase 2.
- */
- let cphsService = GECKO_ICC_SERVICES.cphs[geckoService];
-
- if (!cphsService) {
- return false;
- }
- cphsService -= 1;
- let index = Math.floor(cphsService / 4);
- let bitmask = 2 << ((cphsService % 4) << 1);
-
- return (index < serviceTable.length) &&
- ((serviceTable[index] & bitmask) !== 0);
- },
-
- /**
- * Check if the string is of GSM default 7-bit coded alphabets with bit 8
- * set to 0.
- *
- * @param str String to be checked.
- */
- isGsm8BitAlphabet: function(str) {
- if (!str) {
- return false;
- }
-
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
-
- for (let i = 0; i < str.length; i++) {
- let c = str.charAt(i);
- let octet = langTable.indexOf(c);
- if (octet == -1) {
- octet = langShiftTable.indexOf(c);
- if (octet == -1) {
- return false;
- }
- }
- }
-
- return true;
- },
-
- /**
- * Parse MCC/MNC from IMSI. If there is no available value for the length of
- * mnc, it will use the data in MCC table to parse.
- *
- * @param imsi
- * The imsi of icc.
- * @param mncLength [optional]
- * The length of mnc.
- * Zero indicates we haven't got a valid mnc length.
- *
- * @return An object contains the parsing result of mcc and mnc.
- * Or null if any error occurred.
- */
- parseMccMncFromImsi: function(imsi, mncLength) {
- if (!imsi) {
- return null;
- }
-
- // MCC is the first 3 digits of IMSI.
- let mcc = imsi.substr(0,3);
- if (!mncLength) {
- // Check the MCC/MNC table for MNC length = 3 first for the case we don't
- // have the 4th byte data from EF_AD.
- if (PLMN_HAVING_3DIGITS_MNC[mcc] &&
- PLMN_HAVING_3DIGITS_MNC[mcc].indexOf(imsi.substr(3, 3)) !== -1) {
- mncLength = 3;
- } else {
- // Check the MCC table to decide the length of MNC.
- let index = MCC_TABLE_FOR_MNC_LENGTH_IS_3.indexOf(mcc);
- mncLength = (index !== -1) ? 3 : 2;
- }
- }
- let mnc = imsi.substr(3, mncLength);
- if (DEBUG) {
- this.context.debug("IMSI: " + imsi + " MCC: " + mcc + " MNC: " + mnc);
- }
-
- return { mcc: mcc, mnc: mnc};
- },
-};
-
-/**
- * Helper for ICC Contacts.
- */
-function ICCContactHelperObject(aContext) {
- this.context = aContext;
-}
-ICCContactHelperObject.prototype = {
- context: null,
-
- /**
- * Helper function to check DF_PHONEBOOK.
- */
- hasDfPhoneBook: function(appType) {
- switch (appType) {
- case CARD_APPTYPE_SIM:
- return false;
- case CARD_APPTYPE_USIM:
- return true;
- case CARD_APPTYPE_RUIM:
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
- return ICCUtilsHelper.isICCServiceAvailable("ENHANCED_PHONEBOOK");
- default:
- return false;
- }
- },
-
- /**
- * Helper function to read ICC contacts.
- *
- * @param appType One of CARD_APPTYPE_*.
- * @param contactType One of GECKO_CARDCONTACT_TYPE_*.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readICCContacts: function(appType, contactType, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
-
- switch (contactType) {
- case GECKO_CARDCONTACT_TYPE_ADN:
- if (!this.hasDfPhoneBook(appType)) {
- ICCRecordHelper.readADNLike(ICC_EF_ADN,
- (ICCUtilsHelper.isICCServiceAvailable("EXT1")) ? ICC_EF_EXT1 : null,
- onsuccess, onerror);
- } else {
- this.readUSimContacts(onsuccess, onerror);
- }
- break;
- case GECKO_CARDCONTACT_TYPE_FDN:
- if (!ICCUtilsHelper.isICCServiceAvailable("FDN")) {
- onerror(CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED);
- break;
- }
- ICCRecordHelper.readADNLike(ICC_EF_FDN,
- (ICCUtilsHelper.isICCServiceAvailable("EXT2")) ? ICC_EF_EXT2 : null,
- onsuccess, onerror);
- break;
- case GECKO_CARDCONTACT_TYPE_SDN:
- if (!ICCUtilsHelper.isICCServiceAvailable("SDN")) {
- onerror(CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED);
- break;
- }
-
- ICCRecordHelper.readADNLike(ICC_EF_SDN,
- (ICCUtilsHelper.isICCServiceAvailable("EXT3")) ? ICC_EF_EXT3 : null,
- onsuccess, onerror);
- break;
- default:
- if (DEBUG) {
- this.context.debug("Unsupported contactType :" + contactType);
- }
- onerror(CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED);
- break;
- }
- },
-
- /**
- * Helper function to find free contact record.
- *
- * @param appType One of CARD_APPTYPE_*.
- * @param contactType One of GECKO_CARDCONTACT_TYPE_*.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- findFreeICCContact: function(appType, contactType, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
-
- switch (contactType) {
- case GECKO_CARDCONTACT_TYPE_ADN:
- if (!this.hasDfPhoneBook(appType)) {
- ICCRecordHelper.findFreeRecordId(ICC_EF_ADN, onsuccess.bind(null, 0), onerror);
- } else {
- let gotPbrCb = function gotPbrCb(pbrs) {
- this.findUSimFreeADNRecordId(pbrs, onsuccess, onerror);
- }.bind(this);
-
- ICCRecordHelper.readPBR(gotPbrCb, onerror);
- }
- break;
- case GECKO_CARDCONTACT_TYPE_FDN:
- ICCRecordHelper.findFreeRecordId(ICC_EF_FDN, onsuccess.bind(null, 0), onerror);
- break;
- default:
- if (DEBUG) {
- this.context.debug("Unsupported contactType :" + contactType);
- }
- onerror(CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED);
- break;
- }
- },
-
- /**
- * Cache the pbr index of the possible free record.
- */
- _freePbrIndex: 0,
-
- /**
- * Find free ADN record id in USIM.
- *
- * @param pbrs All Phonebook Reference Files read.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- findUSimFreeADNRecordId: function(pbrs, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
-
- function callback(pbrIndex, recordId) {
- // Assume other free records are probably in the same phonebook set.
- this._freePbrIndex = pbrIndex;
- onsuccess(pbrIndex, recordId);
- }
-
- let nextPbrIndex = -1;
- (function findFreeRecordId(pbrIndex) {
- if (nextPbrIndex === this._freePbrIndex) {
- // No free record found, reset the pbr index of free record.
- this._freePbrIndex = 0;
- if (DEBUG) {
- this.context.debug(CONTACT_ERR_NO_FREE_RECORD_FOUND);
- }
- onerror(CONTACT_ERR_NO_FREE_RECORD_FOUND);
- return;
- }
-
- let pbr = pbrs[pbrIndex];
- nextPbrIndex = (pbrIndex + 1) % pbrs.length;
- ICCRecordHelper.findFreeRecordId(
- pbr.adn.fileId,
- callback.bind(this, pbrIndex),
- findFreeRecordId.bind(this, nextPbrIndex));
- }).call(this, this._freePbrIndex);
- },
-
- /**
- * Helper function to add a new ICC contact.
- *
- * @param appType One of CARD_APPTYPE_*.
- * @param contactType One of GECKO_CARDCONTACT_TYPE_*.
- * @param contact The contact will be added.
- * @param pin2 PIN2 is required for FDN.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- addICCContact: function(appType, contactType, contact, pin2, onsuccess, onerror) {
- let foundFreeCb = (function foundFreeCb(pbrIndex, recordId) {
- contact.pbrIndex = pbrIndex;
- contact.recordId = recordId;
- this.updateICCContact(appType, contactType, contact, pin2, onsuccess, onerror);
- }).bind(this);
-
- // Find free record first.
- this.findFreeICCContact(appType, contactType, foundFreeCb, onerror);
- },
-
- /**
- * Helper function to update ICC contact.
- *
- * @param appType One of CARD_APPTYPE_*.
- * @param contactType One of GECKO_CARDCONTACT_TYPE_*.
- * @param contact The contact will be updated.
- * @param pin2 PIN2 is required for FDN.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateICCContact: function(appType, contactType, contact, pin2, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
- let ICCUtilsHelper = this.context.ICCUtilsHelper;
-
- let updateContactCb = (updatedContact) => {
- updatedContact.pbrIndex = contact.pbrIndex;
- updatedContact.recordId = contact.recordId;
- onsuccess(updatedContact);
- }
-
- switch (contactType) {
- case GECKO_CARDCONTACT_TYPE_ADN:
- if (!this.hasDfPhoneBook(appType)) {
- if (ICCUtilsHelper.isICCServiceAvailable("EXT1")) {
- this.updateADNLikeWithExtension(ICC_EF_ADN, ICC_EF_EXT1,
- contact, null,
- updateContactCb, onerror);
- } else {
- ICCRecordHelper.updateADNLike(ICC_EF_ADN, 0xff,
- contact, null,
- updateContactCb, onerror);
- }
- } else {
- this.updateUSimContact(contact, updateContactCb, onerror);
- }
- break;
- case GECKO_CARDCONTACT_TYPE_FDN:
- if (!pin2) {
- onerror(GECKO_ERROR_SIM_PIN2);
- return;
- }
- if (!ICCUtilsHelper.isICCServiceAvailable("FDN")) {
- onerror(CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED);
- break;
- }
- if (ICCUtilsHelper.isICCServiceAvailable("EXT2")) {
- this.updateADNLikeWithExtension(ICC_EF_FDN, ICC_EF_EXT2,
- contact, pin2,
- updateContactCb, onerror);
- } else {
- ICCRecordHelper.updateADNLike(ICC_EF_FDN,
- 0xff,
- contact, pin2,
- updateContactCb, onerror);
- }
- break;
- default:
- if (DEBUG) {
- this.context.debug("Unsupported contactType :" + contactType);
- }
- onerror(CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED);
- break;
- }
- },
-
- /**
- * Read contacts from USIM.
- *
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readUSimContacts: function(onsuccess, onerror) {
- let gotPbrCb = function gotPbrCb(pbrs) {
- this.readAllPhonebookSets(pbrs, onsuccess, onerror);
- }.bind(this);
-
- this.context.ICCRecordHelper.readPBR(gotPbrCb, onerror);
- },
-
- /**
- * Read all Phonebook sets.
- *
- * @param pbrs All Phonebook Reference Files read.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readAllPhonebookSets: function(pbrs, onsuccess, onerror) {
- let allContacts = [], pbrIndex = 0;
- let readPhonebook = function(contacts) {
- if (contacts) {
- allContacts = allContacts.concat(contacts);
- }
-
- let cLen = contacts ? contacts.length : 0;
- for (let i = 0; i < cLen; i++) {
- contacts[i].pbrIndex = pbrIndex;
- }
-
- pbrIndex++;
- if (pbrIndex >= pbrs.length) {
- if (onsuccess) {
- onsuccess(allContacts);
- }
- return;
- }
-
- this.readPhonebookSet(pbrs[pbrIndex], readPhonebook, onerror);
- }.bind(this);
-
- this.readPhonebookSet(pbrs[pbrIndex], readPhonebook, onerror);
- },
-
- /**
- * Read from Phonebook Reference File.
- *
- * @param pbr Phonebook Reference File to be read.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readPhonebookSet: function(pbr, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
- let gotAdnCb = function gotAdnCb(contacts) {
- this.readSupportedPBRFields(pbr, contacts, onsuccess, onerror);
- }.bind(this);
-
- ICCRecordHelper.readADNLike(pbr.adn.fileId,
- (pbr.ext1) ? pbr.ext1.fileId : null, gotAdnCb, onerror);
- },
-
- /**
- * Read supported Phonebook fields.
- *
- * @param pbr Phone Book Reference file.
- * @param contacts Contacts stored on ICC.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readSupportedPBRFields: function(pbr, contacts, onsuccess, onerror) {
- let fieldIndex = 0;
- (function readField() {
- let field = USIM_PBR_FIELDS[fieldIndex];
- fieldIndex += 1;
- if (!field) {
- if (onsuccess) {
- onsuccess(contacts);
- }
- return;
- }
-
- this.readPhonebookField(pbr, contacts, field, readField.bind(this), onerror);
- }).call(this);
- },
-
- /**
- * Read Phonebook field.
- *
- * @param pbr The phonebook reference file.
- * @param contacts Contacts stored on ICC.
- * @param field Phonebook field to be retrieved.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readPhonebookField: function(pbr, contacts, field, onsuccess, onerror) {
- if (!pbr[field]) {
- if (onsuccess) {
- onsuccess(contacts);
- }
- return;
- }
-
- (function doReadContactField(n) {
- if (n >= contacts.length) {
- // All contact's fields are read.
- if (onsuccess) {
- onsuccess(contacts);
- }
- return;
- }
-
- // get n-th contact's field.
- this.readContactField(pbr, contacts[n], field,
- doReadContactField.bind(this, n + 1), onerror);
- }).call(this, 0);
- },
-
- /**
- * Read contact's field from USIM.
- *
- * @param pbr The phonebook reference file.
- * @param contact The contact needs to get field.
- * @param field Phonebook field to be retrieved.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- readContactField: function(pbr, contact, field, onsuccess, onerror) {
- let gotRecordIdCb = function gotRecordIdCb(recordId) {
- if (recordId == 0xff) {
- if (onsuccess) {
- onsuccess();
- }
- return;
- }
-
- let fileId = pbr[field].fileId;
- let fileType = pbr[field].fileType;
- let gotFieldCb = function gotFieldCb(value) {
- if (value) {
- // Move anr0 anr1,.. into anr[].
- if (field.startsWith(USIM_PBR_ANR)) {
- if (!contact[USIM_PBR_ANR]) {
- contact[USIM_PBR_ANR] = [];
- }
- contact[USIM_PBR_ANR].push(value);
- } else {
- contact[field] = value;
- }
- }
-
- if (onsuccess) {
- onsuccess();
- }
- }.bind(this);
-
- let ICCRecordHelper = this.context.ICCRecordHelper;
- // Detect EF to be read, for anr, it could have anr0, anr1,...
- let ef = field.startsWith(USIM_PBR_ANR) ? USIM_PBR_ANR : field;
- switch (ef) {
- case USIM_PBR_EMAIL:
- ICCRecordHelper.readEmail(fileId, fileType, recordId, gotFieldCb, onerror);
- break;
- case USIM_PBR_ANR:
- ICCRecordHelper.readANR(fileId, fileType, recordId, gotFieldCb, onerror);
- break;
- default:
- if (DEBUG) {
- this.context.debug("Unsupported field :" + field);
- }
- onerror(CONTACT_ERR_FIELD_NOT_SUPPORTED);
- break;
- }
- }.bind(this);
-
- this.getContactFieldRecordId(pbr, contact, field, gotRecordIdCb, onerror);
- },
-
- /**
- * Get the recordId.
- *
- * If the fileType of field is ICC_USIM_TYPE1_TAG, use corresponding ADN recordId.
- * otherwise get the recordId from IAP.
- *
- * @see TS 131.102, clause 4.4.2.2
- *
- * @param pbr The phonebook reference file.
- * @param contact The contact will be updated.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- getContactFieldRecordId: function(pbr, contact, field, onsuccess, onerror) {
- if (pbr[field].fileType == ICC_USIM_TYPE1_TAG) {
- // If the file type is ICC_USIM_TYPE1_TAG, use corresponding ADN recordId.
- if (onsuccess) {
- onsuccess(contact.recordId);
- }
- } else if (pbr[field].fileType == ICC_USIM_TYPE2_TAG) {
- // If the file type is ICC_USIM_TYPE2_TAG, the recordId shall be got from IAP.
- let gotIapCb = function gotIapCb(iap) {
- let indexInIAP = pbr[field].indexInIAP;
- let recordId = iap[indexInIAP];
-
- if (onsuccess) {
- onsuccess(recordId);
- }
- }.bind(this);
-
- this.context.ICCRecordHelper.readIAP(pbr.iap.fileId, contact.recordId,
- gotIapCb, onerror);
- } else {
- if (DEBUG) {
- this.context.debug("USIM PBR files in Type 3 format are not supported.");
- }
- onerror(CONTACT_ERR_REQUEST_NOT_SUPPORTED);
- }
- },
-
- /**
- * Update USIM contact.
- *
- * @param contact The contact will be updated.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateUSimContact: function(contact, onsuccess, onerror) {
- let gotPbrCb = function gotPbrCb(pbrs) {
- let pbr = pbrs[contact.pbrIndex];
- if (!pbr) {
- if (DEBUG) {
- this.context.debug(CONTACT_ERR_CANNOT_ACCESS_PHONEBOOK);
- }
- onerror(CONTACT_ERR_CANNOT_ACCESS_PHONEBOOK);
- return;
- }
- this.updatePhonebookSet(pbr, contact, onsuccess, onerror);
- }.bind(this);
-
- this.context.ICCRecordHelper.readPBR(gotPbrCb, onerror);
- },
-
- /**
- * Update fields in Phonebook Reference File.
- *
- * @param pbr Phonebook Reference File to be read.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updatePhonebookSet: function(pbr, contact, onsuccess, onerror) {
- let updateAdnCb = function(updatedContact) {
- this.updateSupportedPBRFields(pbr, contact, (updatedContactField) => {
- onsuccess(Object.assign(updatedContact, updatedContactField));
- }, onerror);
- }.bind(this);
-
- if (pbr.ext1) {
- this.updateADNLikeWithExtension(pbr.adn.fileId, pbr.ext1.fileId,
- contact, null, updateAdnCb, onerror);
- } else {
- this.context.ICCRecordHelper.updateADNLike(pbr.adn.fileId, 0xff, contact,
- null, updateAdnCb, onerror);
- }
- },
-
- /**
- * Update supported Phonebook fields.
- *
- * @param pbr Phone Book Reference file.
- * @param contact Contact to be updated.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateSupportedPBRFields: function(pbr, contact, onsuccess, onerror) {
- let fieldIndex = 0;
- let contactField = {};
-
- (function updateField() {
- let field = USIM_PBR_FIELDS[fieldIndex];
- fieldIndex += 1;
-
- if (!field) {
- if (onsuccess) {
- onsuccess(contactField);
- }
- return;
- }
-
- // Check if PBR has this field.
- if (!pbr[field]) {
- updateField.call(this);
- return;
- }
-
- this.updateContactField(pbr, contact, field, (fieldEntry) => {
- contactField = Object.assign(contactField, fieldEntry);
- updateField.call(this);
- }, (errorMsg) => {
- // Bug 1194149, there are some sim cards without sufficient
- // Type 2 USIM contact fields record. We allow user continue
- // importing contacts.
- if (errorMsg === CONTACT_ERR_NO_FREE_RECORD_FOUND) {
- updateField.call(this);
- return;
- }
- onerror(errorMsg);
- });
- }).call(this);
- },
-
- /**
- * Update contact's field from USIM.
- *
- * @param pbr The phonebook reference file.
- * @param contact The contact needs to be updated.
- * @param field Phonebook field to be updated.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateContactField: function(pbr, contact, field, onsuccess, onerror) {
- if (pbr[field].fileType === ICC_USIM_TYPE1_TAG) {
- this.updateContactFieldType1(pbr, contact, field, onsuccess, onerror);
- } else if (pbr[field].fileType === ICC_USIM_TYPE2_TAG) {
- this.updateContactFieldType2(pbr, contact, field, onsuccess, onerror);
- } else {
- if (DEBUG) {
- this.context.debug("USIM PBR files in Type 3 format are not supported.");
- }
- onerror(CONTACT_ERR_REQUEST_NOT_SUPPORTED);
- }
- },
-
- /**
- * Update Type 1 USIM contact fields.
- *
- * @param pbr The phonebook reference file.
- * @param contact The contact needs to be updated.
- * @param field Phonebook field to be updated.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateContactFieldType1: function(pbr, contact, field, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
-
- if (field === USIM_PBR_EMAIL) {
- ICCRecordHelper.updateEmail(pbr, contact.recordId, contact.email, null,
- (updatedEmail) => {
- onsuccess({email: updatedEmail});
- }, onerror);
- } else if (field === USIM_PBR_ANR0) {
- let anr = Array.isArray(contact.anr) ? contact.anr[0] : null;
- ICCRecordHelper.updateANR(pbr, contact.recordId, anr, null,
- (updatedANR) => {
- // ANR could have multiple files. If we support more than one anr,
- // we will save it as anr0, anr1,...etc.
- onsuccess((updatedANR) ? {anr: [updatedANR]} : null);
- }, onerror);
- } else {
- if (DEBUG) {
- this.context.debug("Unsupported field :" + field);
- }
- onerror(CONTACT_ERR_FIELD_NOT_SUPPORTED);
- }
- },
-
- /**
- * Update Type 2 USIM contact fields.
- *
- * @param pbr The phonebook reference file.
- * @param contact The contact needs to be updated.
- * @param field Phonebook field to be updated.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateContactFieldType2: function(pbr, contact, field, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
-
- // Case 1 : EF_IAP[adnRecordId] doesn't have a value(0xff)
- // Find a free recordId for EF_field
- // Update field with that free recordId.
- // Update IAP.
- //
- // Case 2: EF_IAP[adnRecordId] has a value
- // update EF_field[iap[field.indexInIAP]]
-
- let gotIapCb = function gotIapCb(iap) {
- let recordId = iap[pbr[field].indexInIAP];
- if (recordId === 0xff) {
- // If the value in IAP[index] is 0xff, which means the contact stored on
- // the SIM doesn't have the additional attribute (email or anr).
- // So if the contact to be updated doesn't have the attribute either,
- // we don't have to update it.
- if ((field === USIM_PBR_EMAIL && contact.email) ||
- (field === USIM_PBR_ANR0 &&
- (Array.isArray(contact.anr) && contact.anr[0]))) {
- // Case 1.
- this.addContactFieldType2(pbr, contact, field, onsuccess, onerror);
- } else {
- if (onsuccess) {
- onsuccess();
- }
- }
- return;
- }
-
- // Case 2.
- if (field === USIM_PBR_EMAIL) {
- ICCRecordHelper.updateEmail(pbr, recordId, contact.email, contact.recordId,
- (updatedEmail) => {
- onsuccess({email: updatedEmail});
- }, onerror);
- } else if (field === USIM_PBR_ANR0) {
- let anr = Array.isArray(contact.anr) ? contact.anr[0] : null;
- ICCRecordHelper.updateANR(pbr, recordId, anr, contact.recordId,
- (updatedANR) => {
- // ANR could have multiple files. If we support more than one anr,
- // we will save it as anr0, anr1,...etc.
- onsuccess((updatedANR) ? {anr: [updatedANR]} : null);
- }, onerror);
- } else {
- if (DEBUG) {
- this.context.debug("Unsupported field :" + field);
- }
- onerror(CONTACT_ERR_FIELD_NOT_SUPPORTED);
- }
-
- }.bind(this);
-
- ICCRecordHelper.readIAP(pbr.iap.fileId, contact.recordId, gotIapCb, onerror);
- },
-
- /**
- * Add Type 2 USIM contact fields.
- *
- * @param pbr The phonebook reference file.
- * @param contact The contact needs to be updated.
- * @param field Phonebook field to be updated.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- addContactFieldType2: function(pbr, contact, field, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
- let successCb = function successCb(recordId) {
-
- let updateCb = function updateCb(contactField) {
- this.updateContactFieldIndexInIAP(pbr, contact.recordId, field, recordId, () => {
- onsuccess(contactField);
- }, onerror);
- }.bind(this);
-
- if (field === USIM_PBR_EMAIL) {
- ICCRecordHelper.updateEmail(pbr, recordId, contact.email, contact.recordId,
- (updatedEmail) => {
- updateCb({email: updatedEmail});
- }, onerror);
- } else if (field === USIM_PBR_ANR0) {
- ICCRecordHelper.updateANR(pbr, recordId, contact.anr[0], contact.recordId,
- (updatedANR) => {
- // ANR could have multiple files. If we support more than one anr,
- // we will save it as anr0, anr1,...etc.
- updateCb((updatedANR) ? {anr: [updatedANR]} : null);
- }, onerror);
- }
- }.bind(this);
-
- let errorCb = function errorCb(errorMsg) {
- if (DEBUG) {
- this.context.debug(errorMsg + " USIM field " + field);
- }
- onerror(errorMsg);
- }.bind(this);
-
- ICCRecordHelper.findFreeRecordId(pbr[field].fileId, successCb, errorCb);
- },
-
- /**
- * Update IAP value.
- *
- * @param pbr The phonebook reference file.
- * @param recordNumber The record identifier of EF_IAP.
- * @param field Phonebook field.
- * @param value The value of 'field' in IAP.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- *
- */
- updateContactFieldIndexInIAP: function(pbr, recordNumber, field, value, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
-
- let gotIAPCb = function gotIAPCb(iap) {
- iap[pbr[field].indexInIAP] = value;
- ICCRecordHelper.updateIAP(pbr.iap.fileId, recordNumber, iap, onsuccess, onerror);
- }.bind(this);
- ICCRecordHelper.readIAP(pbr.iap.fileId, recordNumber, gotIAPCb, onerror);
- },
-
- /**
- * Update ICC ADN like EFs with Extension, like EF_ADN, EF_FDN.
- *
- * @param fileId EF id of the ADN or FDN.
- * @param extFileId EF id of the EXT.
- * @param contact The contact will be updated. (Shall have recordId property)
- * @param pin2 PIN2 is required when updating ICC_EF_FDN.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- updateADNLikeWithExtension: function(fileId, extFileId, contact, pin2, onsuccess, onerror) {
- let ICCRecordHelper = this.context.ICCRecordHelper;
- let extNumber;
-
- if (contact.number) {
- let numStart = contact.number[0] == "+" ? 1 : 0;
- let number = contact.number.substring(0, numStart) +
- this.context.GsmPDUHelper.stringToExtendedBcd(
- contact.number.substring(numStart));
- extNumber = number.substr(numStart + ADN_MAX_NUMBER_DIGITS,
- EXT_MAX_NUMBER_DIGITS);
- }
-
- ICCRecordHelper.getADNLikeExtensionRecordNumber(fileId, contact.recordId,
- (extRecordNumber) => {
- let updateADNLike = (extRecordNumber) => {
- ICCRecordHelper.updateADNLike(fileId, extRecordNumber, contact,
- pin2, (updatedContact) => {
- if (extNumber && extRecordNumber != 0xff) {
- updatedContact.number = updatedContact.number.concat(extNumber);
- }
- onsuccess(updatedContact);
- }, onerror);
- };
-
- let updateExtension = (extRecordNumber) => {
- ICCRecordHelper.updateExtension(extFileId, extRecordNumber, extNumber,
- () => updateADNLike(extRecordNumber),
- () => updateADNLike(0xff));
- };
-
- if (extNumber) {
- if (extRecordNumber != 0xff) {
- updateExtension(extRecordNumber);
- return;
- }
-
- ICCRecordHelper.findFreeRecordId(extFileId,
- (extRecordNumber) => updateExtension(extRecordNumber),
- (errorMsg) => {
- if (DEBUG) {
- this.context.debug("Couldn't find free extension record Id for " + extFileId + ": " + errorMsg);
- }
- updateADNLike(0xff);
- });
- return;
- }
-
- if (extRecordNumber != 0xff) {
- ICCRecordHelper.cleanEFRecord(extFileId, extRecordNumber,
- () => updateADNLike(0xff), onerror);
- return;
- }
-
- updateADNLike(0xff);
- }, onerror);
- },
-};
-
-function IconLoaderObject(aContext) {
- this.context = aContext;
-}
-IconLoaderObject.prototype = {
- context: null,
-
- /**
- * Load icons.
- *
- * @param recordNumbers Array of the record identifiers of EF_IMG.
- * @param onsuccess Callback to be called when success.
- * @param onerror Callback to be called when error.
- */
- loadIcons: function(recordNumbers, onsuccess, onerror) {
- if (!recordNumbers || !recordNumbers.length) {
- if (onerror) {
- onerror();
- }
- return;
- }
-
- this._start({
- recordNumbers: recordNumbers,
- onsuccess: onsuccess,
- onerror: onerror});
- },
-
- _start: function(options) {
- let callback = (function(icons) {
- if (!options.icons) {
- options.icons = [];
- }
- for (let i = 0; i < icons.length; i++) {
- icons[i] = this._parseRawData(icons[i]);
- }
- options.icons[options.currentRecordIndex] = icons;
- options.currentRecordIndex++;
-
- let recordNumbers = options.recordNumbers;
- if (options.currentRecordIndex < recordNumbers.length) {
- let recordNumber = recordNumbers[options.currentRecordIndex];
- this.context.SimRecordHelper.readIMG(recordNumber,
- callback,
- options.onerror);
- } else {
- if (options.onsuccess) {
- options.onsuccess(options.icons);
- }
- }
- }).bind(this);
-
- options.currentRecordIndex = 0;
- this.context.SimRecordHelper.readIMG(options.recordNumbers[0],
- callback,
- options.onerror);
- },
-
- _parseRawData: function(rawData) {
- let codingScheme = rawData.codingScheme;
-
- switch (codingScheme) {
- case ICC_IMG_CODING_SCHEME_BASIC:
- return this._decodeBasicImage(rawData.width, rawData.height, rawData.body);
-
- case ICC_IMG_CODING_SCHEME_COLOR:
- case ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY:
- return this._decodeColorImage(codingScheme,
- rawData.width, rawData.height,
- rawData.bitsPerImgPoint,
- rawData.numOfClutEntries,
- rawData.clut, rawData.body);
- }
-
- return null;
- },
-
- _decodeBasicImage: function(width, height, body) {
- let numOfPixels = width * height;
- let pixelIndex = 0;
- let currentByteIndex = 0;
- let currentByte = 0x00;
-
- const BLACK = 0x000000FF;
- const WHITE = 0xFFFFFFFF;
-
- let pixels = [];
- while (pixelIndex < numOfPixels) {
- // Reassign data and index for every byte (8 bits).
- if (pixelIndex % 8 == 0) {
- currentByte = body[currentByteIndex++];
- }
- let bit = (currentByte >> (7 - (pixelIndex % 8))) & 0x01;
- pixels[pixelIndex++] = bit ? WHITE : BLACK;
- }
-
- return {pixels: pixels,
- codingScheme: GECKO_IMG_CODING_SCHEME_BASIC,
- width: width,
- height: height};
- },
-
- _decodeColorImage: function(codingScheme, width, height, bitsPerImgPoint,
- numOfClutEntries, clut, body) {
- let mask = 0xff >> (8 - bitsPerImgPoint);
- let bitsStartOffset = 8 - bitsPerImgPoint;
- let bitIndex = bitsStartOffset;
- let numOfPixels = width * height;
- let pixelIndex = 0;
- let currentByteIndex = 0;
- let currentByte = body[currentByteIndex++];
-
- let pixels = [];
- while (pixelIndex < numOfPixels) {
- // Reassign data and index for every byte (8 bits).
- if (bitIndex < 0) {
- currentByte = body[currentByteIndex++];
- bitIndex = bitsStartOffset;
- }
- let clutEntry = ((currentByte >> bitIndex) & mask);
- let clutIndex = clutEntry * ICC_CLUT_ENTRY_SIZE;
- let alpha = codingScheme == ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY &&
- clutEntry == numOfClutEntries - 1;
- pixels[pixelIndex++] = alpha ? 0x00
- : (clut[clutIndex] << 24 |
- clut[clutIndex + 1] << 16 |
- clut[clutIndex + 2] << 8 |
- 0xFF) >>> 0;
- bitIndex -= bitsPerImgPoint;
- }
-
- return {pixels: pixels,
- codingScheme: ICC_IMG_CODING_SCHEME_TO_GECKO[codingScheme],
- width: width,
- height: height};
- },
-};
-
-/**
- * Global stuff.
- */
-
-function Context(aClientId) {
- this.clientId = aClientId;
-
- this.Buf = new BufObject(this);
- this.RIL = new RilObject(this);
- this.RIL.initRILState();
-}
-Context.prototype = {
- clientId: null,
- Buf: null,
- RIL: null,
-
- debug: function(aMessage) {
- GLOBAL.debug("[" + this.clientId + "] " + aMessage);
- }
-};
-
-(function() {
- let lazySymbols = [
- "BerTlvHelper", "BitBufferHelper", "CdmaPDUHelper",
- "ComprehensionTlvHelper", "GsmPDUHelper", "ICCContactHelper",
- "ICCFileHelper", "ICCIOHelper", "ICCPDUHelper", "ICCRecordHelper",
- "ICCUtilsHelper", "RuimRecordHelper", "SimRecordHelper",
- "StkCommandParamsFactory", "StkProactiveCmdHelper", "IconLoader",
- ];
-
- for (let i = 0; i < lazySymbols.length; i++) {
- let symbol = lazySymbols[i];
- Object.defineProperty(Context.prototype, symbol, {
- get: function() {
- let real = new GLOBAL[symbol + "Object"](this);
- Object.defineProperty(this, symbol, {
- value: real,
- enumerable: true
- });
- return real;
- },
- configurable: true,
- enumerable: true
- });
- }
-})();
-
-var ContextPool = {
- _contexts: [],
-
- handleRilMessage: function(aClientId, aUint8Array) {
- let context = this._contexts[aClientId];
- context.Buf.processIncoming(aUint8Array);
- },
-
- handleChromeMessage: function(aMessage) {
- let clientId = aMessage.rilMessageClientId;
- if (clientId != null) {
- let context = this._contexts[clientId];
- context.RIL.handleChromeMessage(aMessage);
- return;
- }
-
- if (DEBUG) debug("Received global chrome message " + JSON.stringify(aMessage));
- let method = this[aMessage.rilMessageType];
- if (typeof method != "function") {
- if (DEBUG) {
- debug("Don't know what to do");
- }
- return;
- }
- method.call(this, aMessage);
- },
-
- setInitialOptions: function(aOptions) {
- DEBUG = DEBUG_WORKER || aOptions.debug;
-
- let quirks = aOptions.quirks;
- RILQUIRKS_CALLSTATE_EXTRA_UINT32 = quirks.callstateExtraUint32;
- RILQUIRKS_REQUEST_USE_DIAL_EMERGENCY_CALL = quirks.requestUseDialEmergencyCall;
- RILQUIRKS_SIM_APP_STATE_EXTRA_FIELDS = quirks.simAppStateExtraFields;
- RILQUIRKS_EXTRA_UINT32_2ND_CALL = quirks.extraUint2ndCall;
- RILQUIRKS_HAVE_QUERY_ICC_LOCK_RETRY_COUNT = quirks.haveQueryIccLockRetryCount;
- RILQUIRKS_SEND_STK_PROFILE_DOWNLOAD = quirks.sendStkProfileDownload;
- RILQUIRKS_DATA_REGISTRATION_ON_DEMAND = quirks.dataRegistrationOnDemand;
- RILQUIRKS_SUBSCRIPTION_CONTROL = quirks.subscriptionControl;
- RILQUIRKS_SIGNAL_EXTRA_INT32 = quirks.signalExtraInt;
- RILQUIRKS_AVAILABLE_NETWORKS_EXTRA_STRING = quirks.availableNetworkExtraStr;
- RILQUIRKS_SMSC_ADDRESS_FORMAT = quirks.smscAddressFormat;
- },
-
- setDebugFlag: function(aOptions) {
- DEBUG = DEBUG_WORKER || aOptions.debug;
- },
-
- registerClient: function(aOptions) {
- let clientId = aOptions.clientId;
- this._contexts[clientId] = new Context(clientId);
- },
-};
-
-function onRILMessage(aClientId, aUint8Array) {
- ContextPool.handleRilMessage(aClientId, aUint8Array);
-}
-
-onmessage = function onmessage(event) {
- ContextPool.handleChromeMessage(event.data);
-};
-
-onerror = function onerror(event) {
- if (DEBUG) debug("onerror" + event.message + "\n");
-};
diff --git a/dom/system/gonk/ril_worker_buf_object.js b/dom/system/gonk/ril_worker_buf_object.js
deleted file mode 100644
index 70018c5b2..000000000
--- a/dom/system/gonk/ril_worker_buf_object.js
+++ /dev/null
@@ -1,168 +0,0 @@
-/* global require */
-/* global DEBUG, DEBUG_WORKER */
-/* global RESPONSE_TYPE_SOLICITED */
-/* global RESPONSE_TYPE_UNSOLICITED */
-
-"use strict";
-
-/**
- * This is a specialized worker buffer for the Parcel protocol.
- *
- * NOTE: To prevent including/importing twice, this file should be included
- * in a file which already includes 'ril_consts.js' and 'require.js'.
- */
-(function(exports) {
-
- // Set to true in ril_consts.js to see debug messages
- let DEBUG = DEBUG_WORKER;
- // Need to inherit it.
- let Buf = require("resource://gre/modules/workers/worker_buf.js").Buf;
-
- let BufObject = function(aContext) {
- this.context = aContext;
- // This gets incremented each time we send out a parcel.
- this.mToken = 1;
- // Maps tokens we send out with requests to the request type, so that
- // when we get a response parcel back, we know what request it was for.
- this.mTokenRequestMap = new Map();
- // This is because the underlying 'Buf' is still using the 'init' pattern, so
- // this derived one needs to invoke it.
- // Using 'apply' style to mark it's a parent method calling explicitly.
- Buf._init.apply(this);
-
- // Remapping the request type to different values based on RIL version.
- // We only have to do this for SUBSCRIPTION right now, so I just make it
- // simple. A generic logic or structure could be discussed if we have more
- // use cases, especially the cases from different partners.
- this._requestMap = {};
- // RIL version 8.
- // For the CAF's proprietary parcels. Please see
- // https://www.codeaurora.org/cgit/quic/la/platform/hardware/ril/tree/include/telephony/ril.h?h=b2g_jb_3.2
- let map = {};
- map[REQUEST_SET_UICC_SUBSCRIPTION] = 114;
- map[REQUEST_SET_DATA_SUBSCRIPTION] = 115;
- this._requestMap[8] = map;
- // RIL version 9.
- // For the CAF's proprietary parcels. Please see
- // https://www.codeaurora.org/cgit/quic/la/platform/hardware/ril/tree/include/telephony/ril.h?h=b2g_kk_3.5
- map = {};
- map[REQUEST_SET_UICC_SUBSCRIPTION] = 115;
- map[REQUEST_SET_DATA_SUBSCRIPTION] = 116;
- this._requestMap[9] = map;
- };
-
- /**
- * "inherit" the basic worker buffer.
- */
- BufObject.prototype = Object.create(Buf);
-
- /**
- * Process one parcel.
- */
- BufObject.prototype.processParcel = function() {
- let responseType = this.readInt32();
-
- let requestType, options;
- if (responseType == RESPONSE_TYPE_SOLICITED) {
- let token = this.readInt32();
- let error = this.readInt32();
-
- options = this.mTokenRequestMap.get(token);
- if (!options) {
- if (DEBUG) {
- this.context.debug("Suspicious uninvited request found: " +
- token + ". Ignored!");
- }
- return;
- }
-
- this.mTokenRequestMap.delete(token);
- requestType = options.rilRequestType;
-
- if (error !== ERROR_SUCCESS) {
- options.errorMsg = RIL_ERROR_TO_GECKO_ERROR[error] ||
- GECKO_ERROR_UNSPECIFIED_ERROR;
- }
- if (DEBUG) {
- this.context.debug("Solicited response for request type " + requestType +
- ", token " + token + ", error " + error);
- }
- } else if (responseType == RESPONSE_TYPE_UNSOLICITED) {
- requestType = this.readInt32();
- if (DEBUG) {
- this.context.debug("Unsolicited response for request type " + requestType);
- }
- } else {
- if (DEBUG) {
- this.context.debug("Unknown response type: " + responseType);
- }
- return;
- }
-
- this.context.RIL.handleParcel(requestType, this.readAvailable, options);
- };
-
- /**
- * Start a new outgoing parcel.
- *
- * @param type
- * Integer specifying the request type.
- * @param options [optional]
- * Object containing information about the request, e.g. the
- * original main thread message object that led to the RIL request.
- */
- BufObject.prototype.newParcel = function(type, options) {
- if (DEBUG) {
- this.context.debug("New outgoing parcel of type " + type);
- }
-
- // We're going to leave room for the parcel size at the beginning.
- this.outgoingIndex = this.PARCEL_SIZE_SIZE;
- this.writeInt32(this._reMapRequestType(type));
- this.writeInt32(this.mToken);
-
- if (!options) {
- options = {};
- }
- options.rilRequestType = type;
- this.mTokenRequestMap.set(this.mToken, options);
- this.mToken++;
- return this.mToken;
- };
-
- BufObject.prototype.simpleRequest = function(type, options) {
- this.newParcel(type, options);
- this.sendParcel();
- };
-
- BufObject.prototype.onSendParcel = function(parcel) {
- self.postRILMessage(this.context.clientId, parcel);
- };
-
- /**
- * Remapping the request type to different values based on RIL version.
- * We only have to do this for SUBSCRIPTION right now, so I just make it
- * simple. A generic logic or structure could be discussed if we have more
- * use cases, especially the cases from different partners.
- */
- BufObject.prototype._reMapRequestType = function(type) {
- for (let version in this._requestMap) {
- if (this.context.RIL.version <= version) {
- let newType = this._requestMap[version][type];
- if (newType) {
- if (DEBUG) {
- this.context.debug("Remap request type to " + newType);
- }
- return newType;
- }
- }
- }
- return type;
- };
-
- // Before we make sure to form it as a module would not add extra
- // overhead of module loading, we need to define it in this way
- // rather than 'module.exports' it as a module component.
- exports.BufObject = BufObject;
-})(self); // in worker self is the global
-
diff --git a/dom/system/gonk/ril_worker_telephony_request_queue.js b/dom/system/gonk/ril_worker_telephony_request_queue.js
deleted file mode 100644
index 4dba7a42f..000000000
--- a/dom/system/gonk/ril_worker_telephony_request_queue.js
+++ /dev/null
@@ -1,157 +0,0 @@
-/* global DEBUG, DEBUG_WORKER */
-/* global REQUEST_GET_CURRENT_CALLS */
-/* global REQUEST_ANSWER, REQUEST_CONFERENCE, REQUEST_DIAL */
-/* global REQUEST_DIAL_EMERGENCY_CALL, REQUEST_HANGUP */
-/* global REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND */
-/* global REQUEST_HANGUP_WAITING_OR_BACKGROUND */
-/* global REQUEST_SEPARATE_CONNECTION */
-/* global REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE, REQUEST_UDUB */
-
-"use strict";
-
-(function(exports) {
-
- const TELEPHONY_REQUESTS = [
- REQUEST_GET_CURRENT_CALLS,
- REQUEST_ANSWER,
- REQUEST_CONFERENCE,
- REQUEST_DIAL,
- REQUEST_DIAL_EMERGENCY_CALL,
- REQUEST_HANGUP,
- REQUEST_HANGUP_FOREGROUND_RESUME_BACKGROUND,
- REQUEST_HANGUP_WAITING_OR_BACKGROUND,
- REQUEST_SEPARATE_CONNECTION,
- REQUEST_SWITCH_WAITING_OR_HOLDING_AND_ACTIVE,
- REQUEST_UDUB
- ];
-
- // Set to true in ril_consts.js to see debug messages
- let DEBUG = DEBUG_WORKER;
-
- /**
- * Queue entry; only used in the queue.
- */
- let TelephonyRequestEntry = function(request, callback) {
- this.request = request;
- this.callback = callback;
- };
-
- let TelephonyRequestQueue = function(ril) {
- this.ril = ril;
- this.currentQueue = null; // Point to the current running queue.
-
- this.queryQueue = [];
- this.controlQueue = [];
- };
-
- TelephonyRequestQueue.prototype._getQueue = function(request) {
- return (request === REQUEST_GET_CURRENT_CALLS) ? this.queryQueue
- : this.controlQueue;
- };
-
- TelephonyRequestQueue.prototype._getAnotherQueue = function(queue) {
- return (this.queryQueue === queue) ? this.controlQueue : this.queryQueue;
- };
-
- TelephonyRequestQueue.prototype._find = function(queue, request) {
- for (let i = 0; i < queue.length; ++i) {
- if (queue[i].request === request) {
- return i;
- }
- }
- return -1;
- };
-
- TelephonyRequestQueue.prototype._startQueue = function(queue) {
- if (queue.length === 0) {
- return;
- }
-
- // We only need to keep one entry for queryQueue.
- if (queue === this.queryQueue) {
- queue.splice(1, queue.length - 1);
- }
-
- this.currentQueue = queue;
- for (let entry of queue) {
- this._executeEntry(entry);
- }
- };
-
- TelephonyRequestQueue.prototype._executeEntry = function(entry) {
- if (DEBUG) {
- this.debug("execute " + this._getRequestName(entry.request));
- }
- entry.callback();
- };
-
- TelephonyRequestQueue.prototype._getRequestName = function(request) {
- let method = this.ril[request];
- return (typeof method === 'function') ? method.name : "";
- };
-
- TelephonyRequestQueue.prototype.debug = function(msg) {
- this.ril.context.debug("[TeleQ] " + msg);
- };
-
- TelephonyRequestQueue.prototype.isValidRequest = function(request) {
- return TELEPHONY_REQUESTS.indexOf(request) !== -1;
- };
-
- TelephonyRequestQueue.prototype.push = function(request, callback) {
- if (!this.isValidRequest(request)) {
- if (DEBUG) {
- this.debug("Error: " + this._getRequestName(request) +
- " is not a telephony request");
- }
- return;
- }
-
- if (DEBUG) {
- this.debug("push " + this._getRequestName(request));
- }
- let entry = new TelephonyRequestEntry(request, callback);
- let queue = this._getQueue(request);
- queue.push(entry);
-
- // Try to run the request.
- if (this.currentQueue === queue) {
- this._executeEntry(entry);
- } else if (!this.currentQueue) {
- this._startQueue(queue);
- }
- };
-
- TelephonyRequestQueue.prototype.pop = function(request) {
- if (!this.isValidRequest(request)) {
- if (DEBUG) {
- this.debug("Error: " + this._getRequestName(request) +
- " is not a telephony request");
- }
- return;
- }
-
- if (DEBUG) {
- this.debug("pop " + this._getRequestName(request));
- }
- let queue = this._getQueue(request);
- let index = this._find(queue, request);
- if (index === -1) {
- throw new Error("Cannot find the request in telephonyRequestQueue.");
- } else {
- queue.splice(index, 1);
- }
-
- if (queue.length === 0) {
- this.currentQueue = null;
- this._startQueue(this._getAnotherQueue(queue));
- }
- };
-
-
- // Before we make sure to form it as a module would not add extra
- // overhead of module loading, we need to define it in this way
- // rather than 'module.exports' it as a module component.
- exports.TelephonyRequestQueue = TelephonyRequestQueue;
-})(self); // in worker self is the global
-
diff --git a/dom/system/gonk/systemlibs.js b/dom/system/gonk/systemlibs.js
deleted file mode 100644
index a27b30e20..000000000
--- a/dom/system/gonk/systemlibs.js
+++ /dev/null
@@ -1,201 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-if (!this.ctypes) {
- // We're likely being loaded as a JSM.
- this.EXPORTED_SYMBOLS = [ "libcutils", "netHelpers" ];
- Components.utils.import("resource://gre/modules/ctypes.jsm");
-}
-
-const SYSTEM_PROPERTY_KEY_MAX = 32;
-const SYSTEM_PROPERTY_VALUE_MAX = 92;
-
-// We leave this as 'undefined' instead of setting it to 'false'. That
-// way a file that includes us can have it defined already without us
-// overriding the value here.
-var DEBUG;
-
-/**
- * Expose some system-level functions.
- */
-this.libcutils = (function() {
- let lib;
- try {
- lib = ctypes.open("libcutils.so");
- } catch(ex) {
- // Return a fallback option in case libcutils.so isn't present (e.g.
- // when building Firefox with MOZ_B2G_RIL.
- if (DEBUG) {
- dump("Could not load libcutils.so. Using fake propdb.\n");
- }
- let fake_propdb = Object.create(null);
- return {
- property_get: function(key, defaultValue) {
- if (key in fake_propdb) {
- return fake_propdb[key];
- }
- return defaultValue === undefined ? null : defaultValue;
- },
- property_set: function(key, value) {
- fake_propdb[key] = value;
- }
- };
- }
-
- let c_property_get = lib.declare("property_get", ctypes.default_abi,
- ctypes.int, // return value: length
- ctypes.char.ptr, // key
- ctypes.char.ptr, // value
- ctypes.char.ptr); // default
- let c_property_set = lib.declare("property_set", ctypes.default_abi,
- ctypes.int, // return value: success
- ctypes.char.ptr, // key
- ctypes.char.ptr); // value
- let c_value_buf = ctypes.char.array(SYSTEM_PROPERTY_VALUE_MAX)();
-
- return {
-
- /**
- * Get a system property.
- *
- * @param key
- * Name of the property
- * @param defaultValue [optional]
- * Default value to return if the property isn't set (default: null)
- */
- property_get: function(key, defaultValue) {
- if (defaultValue === undefined) {
- defaultValue = null;
- }
- c_property_get(key, c_value_buf, defaultValue);
- return c_value_buf.readString();
- },
-
- /**
- * Set a system property
- *
- * @param key
- * Name of the property
- * @param value
- * Value to set the property to.
- */
- property_set: function(key, value) {
- let rv = c_property_set(key, value);
- if (rv) {
- throw Error('libcutils.property_set("' + key + '", "' + value +
- '") failed with error ' + rv);
- }
- }
-
- };
-})();
-
-/**
- * Helpers for conversions.
- */
-this.netHelpers = {
-
- /**
- * Swap byte orders for 32-bit value
- */
- swap32: function(n) {
- return (((n >> 24) & 0xFF) << 0) |
- (((n >> 16) & 0xFF) << 8) |
- (((n >> 8) & 0xFF) << 16) |
- (((n >> 0) & 0xFF) << 24);
- },
-
- /**
- * Convert network byte order to host byte order
- * Note: Assume that the system is little endian
- */
- ntohl: function(n) {
- return this.swap32(n);
- },
-
- /**
- * Convert host byte order to network byte order
- * Note: Assume that the system is little endian
- */
- htonl: function(n) {
- return this.swap32(n);
- },
-
- /**
- * Convert integer representation of an IP address to the string
- * representation.
- *
- * @param ip
- * IP address in number format.
- */
- ipToString: function(ip) {
- return ((ip >> 0) & 0xFF) + "." +
- ((ip >> 8) & 0xFF) + "." +
- ((ip >> 16) & 0xFF) + "." +
- ((ip >> 24) & 0xFF);
- },
-
- /**
- * Convert string representation of an IP address to the integer
- * representation (network byte order).
- *
- * @param string
- * String containing the IP address.
- */
- stringToIP: function(string) {
- if (!string) {
- return null;
- }
- let ip = 0;
- let start, end = -1;
- for (let i = 0; i < 4; i++) {
- start = end + 1;
- end = string.indexOf(".", start);
- if (end == -1) {
- end = string.length;
- }
- let num = parseInt(string.slice(start, end), 10);
- if (isNaN(num)) {
- return null;
- }
- ip |= num << (i * 8);
- }
- return ip;
- },
-
- /**
- * Make a subnet mask.
- */
- makeMask: function(len) {
- let mask = 0;
- for (let i = 0; i < len; ++i) {
- mask |= (0x80000000 >> i);
- }
- return this.ntohl(mask);
- },
-
- /**
- * Get Mask length from given mask address
- */
- getMaskLength: function(mask) {
- let len = 0;
- let netmask = this.ntohl(mask);
- while (netmask & 0x80000000) {
- len++;
- netmask = netmask << 1;
- }
- return len;
- }
-};
diff --git a/dom/system/gonk/tests/header_helpers.js b/dom/system/gonk/tests/header_helpers.js
deleted file mode 100644
index 8d1144f75..000000000
--- a/dom/system/gonk/tests/header_helpers.js
+++ /dev/null
@@ -1,217 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-"use strict";
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-
-var subscriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
- .getService(Ci.mozIJSSubScriptLoader);
-
-/**
- * Start a new RIL worker.
- *
- * @param custom_ns
- * Namespace with symbols to be injected into the new worker
- * namespace.
- *
- * @return an object that represents the worker's namespace.
- *
- * @note that this does not start an actual worker thread. The worker
- * is executed on the main thread, within a separate namespace object.
- */
-function newWorker(custom_ns) {
- let worker_ns = {
- importScripts: function() {
- Array.slice(arguments).forEach(function(script) {
- if (!script.startsWith("resource:")) {
- script = "resource://gre/modules/" + script;
- }
- subscriptLoader.loadSubScript(script, this);
- }, this);
- },
-
- postRILMessage: function(message) {
- },
-
- postMessage: function(message) {
- },
-
- // Define these variables inside the worker scope so ES5 strict mode
- // doesn't flip out.
- onmessage: undefined,
- onerror: undefined,
-
- DEBUG: true
- };
- // The 'self' variable in a worker points to the worker's own namespace.
- worker_ns.self = worker_ns;
-
- // Copy the custom definitions over.
- for (let key in custom_ns) {
- worker_ns[key] = custom_ns[key];
- }
-
- // fake require() for toolkit/components/workerloader/require.js
- let require = (function() {
- return function require(script) {
- worker_ns.module = {};
- worker_ns.importScripts(script);
- return worker_ns;
- }
- })();
-
- Object.freeze(require);
- Object.defineProperty(worker_ns, "require", {
- value: require,
- enumerable: true,
- configurable: false
- });
-
- // Load the RIL worker itself.
- worker_ns.importScripts("ril_worker.js");
-
- // Register at least one client.
- worker_ns.ContextPool.registerClient({ clientId: 0 });
-
- return worker_ns;
-}
-
-/**
- * Create a buffered RIL worker.
- *
- * @return A worker object that stores sending octets in a internal buffer.
- */
-function newUint8Worker() {
- let worker = newWorker();
- let index = 0; // index for read
- let buf = [];
-
- let context = worker.ContextPool._contexts[0];
- context.Buf.writeUint8 = function(value) {
- buf.push(value);
- };
-
- context.Buf.readUint8 = function() {
- return buf[index++];
- };
-
- context.Buf.seekIncoming = function(offset) {
- index += offset;
- };
-
- context.Buf.getReadAvailable = function() {
- return buf.length - index;
- };
-
- worker.debug = do_print;
-
- return worker;
-}
-
-/**
- * Create a worker that keeps posted chrome message.
- */
-function newInterceptWorker() {
- let postedMessage;
- let worker = newWorker({
- postRILMessage: function(data) {
- },
- postMessage: function(message) {
- postedMessage = message;
- }
- });
- return {
- get postedMessage() {
- return postedMessage;
- },
- get worker() {
- return worker;
- }
- };
-}
-
-/**
- * Create a parcel suitable for postRILMessage().
- *
- * @param fakeParcelSize
- * Value to be written to parcel size field for testing
- * incorrect/incomplete parcel reading. Replaced with correct
- * one determined length of data if negative.
- * @param response
- * Response code of the incoming parcel.
- * @param request
- * Request code of the incoming parcel.
- * @param data
- * Extra data to be appended.
- *
- * @return an Uint8Array carrying all parcel data.
- */
-function newIncomingParcel(fakeParcelSize, response, request, data) {
- const UINT32_SIZE = 4;
- const PARCEL_SIZE_SIZE = 4;
-
- let realParcelSize = data.length + 2 * UINT32_SIZE;
- let buffer = new ArrayBuffer(realParcelSize + PARCEL_SIZE_SIZE);
- let bytes = new Uint8Array(buffer);
-
- let writeIndex = 0;
- function writeUint8(value) {
- bytes[writeIndex] = value;
- ++writeIndex;
- }
-
- function writeInt32(value) {
- writeUint8(value & 0xff);
- writeUint8((value >> 8) & 0xff);
- writeUint8((value >> 16) & 0xff);
- writeUint8((value >> 24) & 0xff);
- }
-
- function writeParcelSize(value) {
- writeUint8((value >> 24) & 0xff);
- writeUint8((value >> 16) & 0xff);
- writeUint8((value >> 8) & 0xff);
- writeUint8(value & 0xff);
- }
-
- if (fakeParcelSize < 0) {
- fakeParcelSize = realParcelSize;
- }
- writeParcelSize(fakeParcelSize);
-
- writeInt32(response);
- writeInt32(request);
-
- // write parcel data
- for (let ii = 0; ii < data.length; ++ii) {
- writeUint8(data[ii]);
- }
-
- return bytes;
-}
-
-/**
- * Create a parcel buffer which represents the hex string.
- *
- * @param hexString
- * The HEX string to be converted.
- *
- * @return an Uint8Array carrying all parcel data.
- */
-function hexStringToParcelByteArrayData(hexString) {
- let length = Math.ceil((hexString.length / 2));
- let bytes = new Uint8Array(4 + length);
-
- bytes[0] = length & 0xFF;
- bytes[1] = (length >> 8) & 0xFF;
- bytes[2] = (length >> 16) & 0xFF;
- bytes[3] = (length >> 24) & 0xFF;
-
- for (let i = 0; i < length; i ++) {
- bytes[i + 4] = Number.parseInt(hexString.substr(i * 2, 2), 16);
- }
-
- return bytes;
-}
diff --git a/dom/system/gonk/tests/marionette/head.js b/dom/system/gonk/tests/marionette/head.js
deleted file mode 100644
index 5a6ee1272..000000000
--- a/dom/system/gonk/tests/marionette/head.js
+++ /dev/null
@@ -1,345 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_CONTEXT = "chrome";
-
-const SETTINGS_KEY_DATA_ENABLED = "ril.data.enabled";
-const SETTINGS_KEY_DATA_APN_SETTINGS = "ril.data.apnSettings";
-const SETTINGS_KEY_WIFI_ENABLED = "wifi.enabled";
-
-const TOPIC_CONNECTION_STATE_CHANGED = "network-connection-state-changed";
-const TOPIC_NETWORK_ACTIVE_CHANGED = "network-active-changed";
-
-const NETWORK_STATE_UNKNOWN = Ci.nsINetworkInfo.NETWORK_STATE_UNKNOWN;
-const NETWORK_STATE_CONNECTING = Ci.nsINetworkInfo.NETWORK_STATE_CONNECTING;
-const NETWORK_STATE_CONNECTED = Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED;
-const NETWORK_STATE_DISCONNECTING = Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTING;
-const NETWORK_STATE_DISCONNECTED = Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED;
-
-const NETWORK_TYPE_MOBILE = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE;
-const NETWORK_TYPE_MOBILE_MMS = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS;
-const NETWORK_TYPE_MOBILE_SUPL = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_SUPL;
-const NETWORK_TYPE_MOBILE_IMS = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_IMS;
-const NETWORK_TYPE_MOBILE_DUN = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_DUN;
-const NETWORK_TYPE_MOBILE_FOTA = Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_FOTA;
-
-const networkTypes = [
- NETWORK_TYPE_MOBILE,
- NETWORK_TYPE_MOBILE_MMS,
- NETWORK_TYPE_MOBILE_SUPL,
- NETWORK_TYPE_MOBILE_IMS,
- NETWORK_TYPE_MOBILE_DUN,
- NETWORK_TYPE_MOBILE_FOTA
-];
-
-var Promise = Cu.import("resource://gre/modules/Promise.jsm").Promise;
-
-var ril = Cc["@mozilla.org/ril;1"].getService(Ci.nsIRadioInterfaceLayer);
-ok(ril, "ril.constructor is " + ril.constructor);
-
-var radioInterface = ril.getRadioInterface(0);
-ok(radioInterface, "radioInterface.constructor is " + radioInterface.constrctor);
-
-var _pendingEmulatorShellCmdCount = 0;
-var _pendingEmulatorCmdCount = 0;
-
-/**
- * Send emulator shell command with safe guard.
- *
- * We should only call |finish()| after all emulator shell command transactions
- * end, so here comes with the pending counter. Resolve when the emulator
- * shell gives response. Never reject.
- *
- * Fulfill params:
- * result -- an array of emulator shell response lines.
- *
- * @param aCommands
- * A string array commands to be passed to emulator through adb shell.
- *
- * @return A deferred promise.
- */
-function runEmulatorShellCmdSafe(aCommands) {
- return new Promise(function(aResolve, aReject) {
- ++_pendingEmulatorShellCmdCount;
- runEmulatorShell(aCommands, function(aResult) {
- --_pendingEmulatorShellCmdCount;
-
- log("Emulator shell response: " + JSON.stringify(aResult));
- aResolve(aResult);
- });
- });
-}
-
-/**
- * Send emulator command with safe guard.
- *
- * We should only call |finish()| after all emulator command transactions
- * end, so here comes with the pending counter. Resolve when the emulator
- * gives positive response, and reject otherwise.
- *
- * Fulfill params:
- * result -- an array of emulator response lines.
- * Reject params:
- * result -- an array of emulator response lines.
- *
- * @param aCommand
- * A string command to be passed to emulator through its telnet console.
- *
- * @return A deferred promise.
- */
-function runEmulatorCmdSafe(aCommand) {
- log(aCommand);
- return new Promise(function(aResolve, aReject) {
- ++_pendingEmulatorCmdCount;
- runEmulatorCmd(aCommand, function(aResult) {
- --_pendingEmulatorCmdCount;
-
- log("Emulator console response: " + JSON.stringify(aResult));
- if (Array.isArray(aResult) &&
- aResult[aResult.length - 1] === "OK") {
- aResolve(aResult);
- } else {
- aReject(aResult);
- }
- });
- });
-}
-
-/**
- * Get mozSettings value specified by @aKey.
- *
- * Resolve if that mozSettings value is retrieved successfully, reject
- * otherwise.
- *
- * Fulfill params: The corresponding mozSettings value of the key.
- * Reject params: (none)
- *
- * @param aKey
- * A string.
- * @param aAllowError [optional]
- * A boolean value. If set to true, an error response won't be treated
- * as test failure. Default: false.
- *
- * @return A deferred promise.
- */
-function getSettings(aKey, aAllowError) {
- let request = window.navigator.mozSettings.createLock().get(aKey);
- return request.then(function resolve(aValue) {
- log("getSettings(" + aKey + ") - success");
- return aValue[aKey];
- }, function reject(aError) {
- ok(aAllowError, "getSettings(" + aKey + ") - error");
- });
-}
-
-/**
- * Set mozSettings values.
- *
- * Resolve if that mozSettings value is set successfully, reject otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aKey
- * A string key.
- * @param aValue
- * An object value.
- * @param aAllowError [optional]
- * A boolean value. If set to true, an error response won't be treated
- * as test failure. Default: false.
- *
- * @return A deferred promise.
- */
-function setSettings(aKey, aValue, aAllowError) {
- let settings = {};
- settings[aKey] = aValue;
- let lock = window.navigator.mozSettings.createLock();
- let request = lock.set(settings);
- let deferred = Promise.defer();
- lock.onsettingstransactionsuccess = function () {
- log("setSettings(" + JSON.stringify(settings) + ") - success");
- deferred.resolve();
- };
- lock.onsettingstransactionfailure = function () {
- ok(aAllowError, "setSettings(" + JSON.stringify(settings) + ") - error");
- // We resolve even though we've thrown an error, since the ok()
- // will do that.
- deferred.resolve();
- };
- return deferred.promise;
-}
-
-/**
- * Wait for observer event.
- *
- * Resolve if that topic event occurs. Never reject.
- *
- * Fulfill params: the subject passed.
- *
- * @param aTopic
- * A string topic name.
- *
- * @return A deferred promise.
- */
-function waitForObserverEvent(aTopic) {
- let obs = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
- let deferred = Promise.defer();
-
- obs.addObserver(function observer(subject, topic, data) {
- if (topic === aTopic) {
- obs.removeObserver(observer, aTopic);
- deferred.resolve(subject);
- }
- }, aTopic, false);
-
- return deferred.promise;
-}
-
-/**
- * Wait for one named event.
- *
- * Resolve if that named event occurs. Never reject.
- *
- * Fulfill params: the DOMEvent passed.
- *
- * @param aEventTarget
- * An EventTarget object.
- * @param aEventName
- * A string event name.
- * @param aMatchFun [optional]
- * A matching function returns true or false to filter the event.
- *
- * @return A deferred promise.
- */
-function waitForTargetEvent(aEventTarget, aEventName, aMatchFun) {
- return new Promise(function(aResolve, aReject) {
- aEventTarget.addEventListener(aEventName, function onevent(aEvent) {
- if (!aMatchFun || aMatchFun(aEvent)) {
- aEventTarget.removeEventListener(aEventName, onevent);
- ok(true, "Event '" + aEventName + "' got.");
- aResolve(aEvent);
- }
- });
- });
-}
-
-/**
- * Set the default data connection enabling state, wait for
- * "network-connection-state-changed" event and verify state.
- *
- * Fulfill params: instance of nsIRilNetworkInfo of the network connected.
- *
- * @param aEnabled
- * A boolean state.
- *
- * @return A deferred promise.
- */
-function setDataEnabledAndWait(aEnabled) {
- let promises = [];
- promises.push(waitForObserverEvent(TOPIC_CONNECTION_STATE_CHANGED)
- .then(function(aSubject) {
- ok(aSubject instanceof Ci.nsIRilNetworkInfo,
- "subject should be an instance of nsIRilNetworkInfo");
- is(aSubject.type, NETWORK_TYPE_MOBILE,
- "subject.type should be " + NETWORK_TYPE_MOBILE);
- is(aSubject.state,
- aEnabled ? Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED
- : Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED,
- "subject.state should be " + aEnabled ? "CONNECTED" : "DISCONNECTED");
-
- return aSubject;
- }));
- promises.push(setSettings(SETTINGS_KEY_DATA_ENABLED, aEnabled));
-
- return Promise.all(promises).then(aValues => aValues[0]);
-}
-
-/**
- * Setup a certain type of data connection, wait for
- * "network-connection-state-changed" event and verify state.
- *
- * Fulfill params: instance of nsIRilNetworkInfo of the network connected.
- *
- * @param aNetworkType
- * The mobile network type to setup.
- *
- * @return A deferred promise.
- */
-function setupDataCallAndWait(aNetworkType) {
- log("setupDataCallAndWait: " + aNetworkType);
-
- let promises = [];
- promises.push(waitForObserverEvent(TOPIC_CONNECTION_STATE_CHANGED)
- .then(function(aSubject) {
- ok(aSubject instanceof Ci.nsIRilNetworkInfo,
- "subject should be an instance of nsIRilNetworkInfo");
- is(aSubject.type, aNetworkType,
- "subject.type should be " + aNetworkType);
- is(aSubject.state, Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED,
- "subject.state should be CONNECTED");
-
- return aSubject;
- }));
- promises.push(radioInterface.setupDataCallByType(aNetworkType));
-
- return Promise.all(promises).then(aValues => aValues[0]);
-}
-
-/**
- * Deactivate a certain type of data connection, wait for
- * "network-connection-state-changed" event and verify state.
- *
- * Fulfill params: (none)
- *
- * @param aNetworkType
- * The mobile network type to deactivate.
- *
- * @return A deferred promise.
- */
-function deactivateDataCallAndWait(aNetworkType) {
- log("deactivateDataCallAndWait: " + aNetworkType);
-
- let promises = [];
- promises.push(waitForObserverEvent(TOPIC_CONNECTION_STATE_CHANGED)
- .then(function(aSubject) {
- ok(aSubject instanceof Ci.nsIRilNetworkInfo,
- "subject should be an instance of nsIRilNetworkInfo");
- is(aSubject.type, aNetworkType,
- "subject.type should be " + aNetworkType);
- is(aSubject.state, Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED,
- "subject.state should be DISCONNECTED");
- }));
- promises.push(radioInterface.deactivateDataCallByType(aNetworkType));
-
- return Promise.all(promises);
-}
-
-/**
- * Wait for pending emulator transactions and call |finish()|.
- */
-function cleanUp() {
- // Use ok here so that we have at least one test run.
- ok(true, ":: CLEANING UP ::");
-
- waitFor(finish, function() {
- return _pendingEmulatorShellCmdCount === 0 &&
- _pendingEmulatorCmdCount === 0;
- });
-}
-
-/**
- * Basic test routine helper.
- *
- * This helper does nothing but clean-ups.
- *
- * @param aTestCaseMain
- * A function that takes no parameter.
- */
-function startTestBase(aTestCaseMain) {
- Promise.resolve()
- .then(aTestCaseMain)
- .then(cleanUp, function(aException) {
- ok(false, "promise rejects during test: " + aException);
- cleanUp();
- });
-}
diff --git a/dom/system/gonk/tests/marionette/manifest.ini b/dom/system/gonk/tests/marionette/manifest.ini
deleted file mode 100644
index 528fe3baf..000000000
--- a/dom/system/gonk/tests/marionette/manifest.ini
+++ /dev/null
@@ -1,19 +0,0 @@
-[DEFAULT]
-run-if = buildapp == 'b2g'
-
-[test_geolocation.js]
-skip-if = true # Bug 808783
-[test_fakevolume.js]
-[test_ril_code_quality.py]
-[test_screen_state.js]
-[test_dsds_numRadioInterfaces.js]
-[test_data_connection.js]
-[test_network_active_changed.js]
-[test_multiple_data_connection.js]
-[test_data_connection_proxy.js]
-[test_network_interface_list_service.js]
-[test_all_network_info.js]
-[test_network_interface_mtu.js]
-skip-if = android_version < '19'
-[test_timezone_changes.js]
-skip-if = android_version < '19'
diff --git a/dom/system/gonk/tests/marionette/ril_jshint/README.md b/dom/system/gonk/tests/marionette/ril_jshint/README.md
deleted file mode 100644
index a63967d63..000000000
--- a/dom/system/gonk/tests/marionette/ril_jshint/README.md
+++ /dev/null
@@ -1,9 +0,0 @@
-Test RIL Code Quality
-=====================
-
-For more information, please refer to
-
-* Bug 880643 - B2G RIL: Add a code quality test on try server for RIL javascript code in gecko
-* Slide: https://speakerdeck.com/aknow/improve-code-quality-of-ril-code-by-jshint
-* Document: https://hackpad.com/Code-Quality-Test-For-RIL-Javascript-Code-In-Gecko-cz5j7YIGiw8
-
diff --git a/dom/system/gonk/tests/marionette/ril_jshint/jshint.js b/dom/system/gonk/tests/marionette/ril_jshint/jshint.js
deleted file mode 100644
index ec5263a5b..000000000
--- a/dom/system/gonk/tests/marionette/ril_jshint/jshint.js
+++ /dev/null
@@ -1,11096 +0,0 @@
-//2.1.3
-var JSHINT;
-(function () {
-var require;
-require=(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
-// shim for using process in browser
-
-var process = module.exports = {};
-
-process.nextTick = (function () {
- var canSetImmediate = typeof window !== 'undefined'
- && window.setImmediate;
- var canPost = typeof window !== 'undefined'
- && window.postMessage && window.addEventListener
- ;
-
- if (canSetImmediate) {
- return function (f) { return window.setImmediate(f) };
- }
-
- if (canPost) {
- var queue = [];
- window.addEventListener('message', function (ev) {
- if (ev.source === window && ev.data === 'process-tick') {
- ev.stopPropagation();
- if (queue.length > 0) {
- var fn = queue.shift();
- fn();
- }
- }
- }, true);
-
- return function nextTick(fn) {
- queue.push(fn);
- window.postMessage('process-tick', '*');
- };
- }
-
- return function nextTick(fn) {
- setTimeout(fn, 0);
- };
-})();
-
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-}
-
-// TODO(shtylman)
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-
-},{}],2:[function(require,module,exports){
-(function(process){if (!process.EventEmitter) process.EventEmitter = function () {};
-
-var EventEmitter = exports.EventEmitter = process.EventEmitter;
-var isArray = typeof Array.isArray === 'function'
- ? Array.isArray
- : function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]'
- }
-;
-function indexOf (xs, x) {
- if (xs.indexOf) return xs.indexOf(x);
- for (var i = 0; i < xs.length; i++) {
- if (x === xs[i]) return i;
- }
- return -1;
-}
-
-// By default EventEmitters will print a warning if more than
-// 10 listeners are added to it. This is a useful default which
-// helps finding memory leaks.
-//
-// Obviously not all Emitters should be limited to 10. This function allows
-// that to be increased. Set to zero for unlimited.
-var defaultMaxListeners = 10;
-EventEmitter.prototype.setMaxListeners = function(n) {
- if (!this._events) this._events = {};
- this._events.maxListeners = n;
-};
-
-
-EventEmitter.prototype.emit = function(type) {
- // If there is no 'error' event listener then throw.
- if (type === 'error') {
- if (!this._events || !this._events.error ||
- (isArray(this._events.error) && !this._events.error.length))
- {
- if (arguments[1] instanceof Error) {
- throw arguments[1]; // Unhandled 'error' event
- } else {
- throw new Error("Uncaught, unspecified 'error' event.");
- }
- return false;
- }
- }
-
- if (!this._events) return false;
- var handler = this._events[type];
- if (!handler) return false;
-
- if (typeof handler == 'function') {
- switch (arguments.length) {
- // fast cases
- case 1:
- handler.call(this);
- break;
- case 2:
- handler.call(this, arguments[1]);
- break;
- case 3:
- handler.call(this, arguments[1], arguments[2]);
- break;
- // slower
- default:
- var args = Array.prototype.slice.call(arguments, 1);
- handler.apply(this, args);
- }
- return true;
-
- } else if (isArray(handler)) {
- var args = Array.prototype.slice.call(arguments, 1);
-
- var listeners = handler.slice();
- for (var i = 0, l = listeners.length; i < l; i++) {
- listeners[i].apply(this, args);
- }
- return true;
-
- } else {
- return false;
- }
-};
-
-// EventEmitter is defined in src/node_events.cc
-// EventEmitter.prototype.emit() is also defined there.
-EventEmitter.prototype.addListener = function(type, listener) {
- if ('function' !== typeof listener) {
- throw new Error('addListener only takes instances of Function');
- }
-
- if (!this._events) this._events = {};
-
- // To avoid recursion in the case that type == "newListeners"! Before
- // adding it to the listeners, first emit "newListeners".
- this.emit('newListener', type, listener);
-
- if (!this._events[type]) {
- // Optimize the case of one listener. Don't need the extra array object.
- this._events[type] = listener;
- } else if (isArray(this._events[type])) {
-
- // Check for listener leak
- if (!this._events[type].warned) {
- var m;
- if (this._events.maxListeners !== undefined) {
- m = this._events.maxListeners;
- } else {
- m = defaultMaxListeners;
- }
-
- if (m && m > 0 && this._events[type].length > m) {
- this._events[type].warned = true;
- console.error('(node) warning: possible EventEmitter memory ' +
- 'leak detected. %d listeners added. ' +
- 'Use emitter.setMaxListeners() to increase limit.',
- this._events[type].length);
- console.trace();
- }
- }
-
- // If we've already got an array, just append.
- this._events[type].push(listener);
- } else {
- // Adding the second element, need to change to array.
- this._events[type] = [this._events[type], listener];
- }
-
- return this;
-};
-
-EventEmitter.prototype.on = EventEmitter.prototype.addListener;
-
-EventEmitter.prototype.once = function(type, listener) {
- var self = this;
- self.on(type, function g() {
- self.removeListener(type, g);
- listener.apply(this, arguments);
- });
-
- return this;
-};
-
-EventEmitter.prototype.removeListener = function(type, listener) {
- if ('function' !== typeof listener) {
- throw new Error('removeListener only takes instances of Function');
- }
-
- // does not use listeners(), so no side effect of creating _events[type]
- if (!this._events || !this._events[type]) return this;
-
- var list = this._events[type];
-
- if (isArray(list)) {
- var i = indexOf(list, listener);
- if (i < 0) return this;
- list.splice(i, 1);
- if (list.length == 0)
- delete this._events[type];
- } else if (this._events[type] === listener) {
- delete this._events[type];
- }
-
- return this;
-};
-
-EventEmitter.prototype.removeAllListeners = function(type) {
- if (arguments.length === 0) {
- this._events = {};
- return this;
- }
-
- // does not use listeners(), so no side effect of creating _events[type]
- if (type && this._events && this._events[type]) this._events[type] = null;
- return this;
-};
-
-EventEmitter.prototype.listeners = function(type) {
- if (!this._events) this._events = {};
- if (!this._events[type]) this._events[type] = [];
- if (!isArray(this._events[type])) {
- this._events[type] = [this._events[type]];
- }
- return this._events[type];
-};
-
-})(require("__browserify_process"))
-},{"__browserify_process":1}],3:[function(require,module,exports){
-(function(){// jshint -W001
-
-"use strict";
-
-// Identifiers provided by the ECMAScript standard.
-
-exports.reservedVars = {
- arguments : false,
- NaN : false
-};
-
-exports.ecmaIdentifiers = {
- Array : false,
- Boolean : false,
- Date : false,
- decodeURI : false,
- decodeURIComponent : false,
- encodeURI : false,
- encodeURIComponent : false,
- Error : false,
- "eval" : false,
- EvalError : false,
- Function : false,
- hasOwnProperty : false,
- isFinite : false,
- isNaN : false,
- JSON : false,
- Math : false,
- Map : false,
- Number : false,
- Object : false,
- parseInt : false,
- parseFloat : false,
- RangeError : false,
- ReferenceError : false,
- RegExp : false,
- Set : false,
- String : false,
- SyntaxError : false,
- TypeError : false,
- URIError : false,
- WeakMap : false
-};
-
-// Global variables commonly provided by a web browser environment.
-
-exports.browser = {
- ArrayBuffer : false,
- ArrayBufferView : false,
- Audio : false,
- Blob : false,
- addEventListener : false,
- applicationCache : false,
- atob : false,
- blur : false,
- btoa : false,
- clearInterval : false,
- clearTimeout : false,
- close : false,
- closed : false,
- DataView : false,
- DOMParser : false,
- defaultStatus : false,
- document : false,
- Element : false,
- ElementTimeControl : false,
- event : false,
- FileReader : false,
- Float32Array : false,
- Float64Array : false,
- FormData : false,
- focus : false,
- frames : false,
- getComputedStyle : false,
- HTMLElement : false,
- HTMLAnchorElement : false,
- HTMLBaseElement : false,
- HTMLBlockquoteElement: false,
- HTMLBodyElement : false,
- HTMLBRElement : false,
- HTMLButtonElement : false,
- HTMLCanvasElement : false,
- HTMLDirectoryElement : false,
- HTMLDivElement : false,
- HTMLDListElement : false,
- HTMLFieldSetElement : false,
- HTMLFontElement : false,
- HTMLFormElement : false,
- HTMLFrameElement : false,
- HTMLFrameSetElement : false,
- HTMLHeadElement : false,
- HTMLHeadingElement : false,
- HTMLHRElement : false,
- HTMLHtmlElement : false,
- HTMLIFrameElement : false,
- HTMLImageElement : false,
- HTMLInputElement : false,
- HTMLIsIndexElement : false,
- HTMLLabelElement : false,
- HTMLLayerElement : false,
- HTMLLegendElement : false,
- HTMLLIElement : false,
- HTMLLinkElement : false,
- HTMLMapElement : false,
- HTMLMenuElement : false,
- HTMLMetaElement : false,
- HTMLModElement : false,
- HTMLObjectElement : false,
- HTMLOListElement : false,
- HTMLOptGroupElement : false,
- HTMLOptionElement : false,
- HTMLParagraphElement : false,
- HTMLParamElement : false,
- HTMLPreElement : false,
- HTMLQuoteElement : false,
- HTMLScriptElement : false,
- HTMLSelectElement : false,
- HTMLStyleElement : false,
- HTMLTableCaptionElement: false,
- HTMLTableCellElement : false,
- HTMLTableColElement : false,
- HTMLTableElement : false,
- HTMLTableRowElement : false,
- HTMLTableSectionElement: false,
- HTMLTextAreaElement : false,
- HTMLTitleElement : false,
- HTMLUListElement : false,
- HTMLVideoElement : false,
- history : false,
- Int16Array : false,
- Int32Array : false,
- Int8Array : false,
- Image : false,
- length : false,
- localStorage : false,
- location : false,
- MessageChannel : false,
- MessageEvent : false,
- MessagePort : false,
- moveBy : false,
- moveTo : false,
- MutationObserver : false,
- name : false,
- Node : false,
- NodeFilter : false,
- navigator : false,
- onbeforeunload : true,
- onblur : true,
- onerror : true,
- onfocus : true,
- onload : true,
- onresize : true,
- onunload : true,
- open : false,
- openDatabase : false,
- opener : false,
- Option : false,
- parent : false,
- print : false,
- removeEventListener : false,
- resizeBy : false,
- resizeTo : false,
- screen : false,
- scroll : false,
- scrollBy : false,
- scrollTo : false,
- sessionStorage : false,
- setInterval : false,
- setTimeout : false,
- SharedWorker : false,
- status : false,
- SVGAElement : false,
- SVGAltGlyphDefElement: false,
- SVGAltGlyphElement : false,
- SVGAltGlyphItemElement: false,
- SVGAngle : false,
- SVGAnimateColorElement: false,
- SVGAnimateElement : false,
- SVGAnimateMotionElement: false,
- SVGAnimateTransformElement: false,
- SVGAnimatedAngle : false,
- SVGAnimatedBoolean : false,
- SVGAnimatedEnumeration: false,
- SVGAnimatedInteger : false,
- SVGAnimatedLength : false,
- SVGAnimatedLengthList: false,
- SVGAnimatedNumber : false,
- SVGAnimatedNumberList: false,
- SVGAnimatedPathData : false,
- SVGAnimatedPoints : false,
- SVGAnimatedPreserveAspectRatio: false,
- SVGAnimatedRect : false,
- SVGAnimatedString : false,
- SVGAnimatedTransformList: false,
- SVGAnimationElement : false,
- SVGCSSRule : false,
- SVGCircleElement : false,
- SVGClipPathElement : false,
- SVGColor : false,
- SVGColorProfileElement: false,
- SVGColorProfileRule : false,
- SVGComponentTransferFunctionElement: false,
- SVGCursorElement : false,
- SVGDefsElement : false,
- SVGDescElement : false,
- SVGDocument : false,
- SVGElement : false,
- SVGElementInstance : false,
- SVGElementInstanceList: false,
- SVGEllipseElement : false,
- SVGExternalResourcesRequired: false,
- SVGFEBlendElement : false,
- SVGFEColorMatrixElement: false,
- SVGFEComponentTransferElement: false,
- SVGFECompositeElement: false,
- SVGFEConvolveMatrixElement: false,
- SVGFEDiffuseLightingElement: false,
- SVGFEDisplacementMapElement: false,
- SVGFEDistantLightElement: false,
- SVGFEDropShadowElement: false,
- SVGFEFloodElement : false,
- SVGFEFuncAElement : false,
- SVGFEFuncBElement : false,
- SVGFEFuncGElement : false,
- SVGFEFuncRElement : false,
- SVGFEGaussianBlurElement: false,
- SVGFEImageElement : false,
- SVGFEMergeElement : false,
- SVGFEMergeNodeElement: false,
- SVGFEMorphologyElement: false,
- SVGFEOffsetElement : false,
- SVGFEPointLightElement: false,
- SVGFESpecularLightingElement: false,
- SVGFESpotLightElement: false,
- SVGFETileElement : false,
- SVGFETurbulenceElement: false,
- SVGFilterElement : false,
- SVGFilterPrimitiveStandardAttributes: false,
- SVGFitToViewBox : false,
- SVGFontElement : false,
- SVGFontFaceElement : false,
- SVGFontFaceFormatElement: false,
- SVGFontFaceNameElement: false,
- SVGFontFaceSrcElement: false,
- SVGFontFaceUriElement: false,
- SVGForeignObjectElement: false,
- SVGGElement : false,
- SVGGlyphElement : false,
- SVGGlyphRefElement : false,
- SVGGradientElement : false,
- SVGHKernElement : false,
- SVGICCColor : false,
- SVGImageElement : false,
- SVGLangSpace : false,
- SVGLength : false,
- SVGLengthList : false,
- SVGLineElement : false,
- SVGLinearGradientElement: false,
- SVGLocatable : false,
- SVGMPathElement : false,
- SVGMarkerElement : false,
- SVGMaskElement : false,
- SVGMatrix : false,
- SVGMetadataElement : false,
- SVGMissingGlyphElement: false,
- SVGNumber : false,
- SVGNumberList : false,
- SVGPaint : false,
- SVGPathElement : false,
- SVGPathSeg : false,
- SVGPathSegArcAbs : false,
- SVGPathSegArcRel : false,
- SVGPathSegClosePath : false,
- SVGPathSegCurvetoCubicAbs: false,
- SVGPathSegCurvetoCubicRel: false,
- SVGPathSegCurvetoCubicSmoothAbs: false,
- SVGPathSegCurvetoCubicSmoothRel: false,
- SVGPathSegCurvetoQuadraticAbs: false,
- SVGPathSegCurvetoQuadraticRel: false,
- SVGPathSegCurvetoQuadraticSmoothAbs: false,
- SVGPathSegCurvetoQuadraticSmoothRel: false,
- SVGPathSegLinetoAbs : false,
- SVGPathSegLinetoHorizontalAbs: false,
- SVGPathSegLinetoHorizontalRel: false,
- SVGPathSegLinetoRel : false,
- SVGPathSegLinetoVerticalAbs: false,
- SVGPathSegLinetoVerticalRel: false,
- SVGPathSegList : false,
- SVGPathSegMovetoAbs : false,
- SVGPathSegMovetoRel : false,
- SVGPatternElement : false,
- SVGPoint : false,
- SVGPointList : false,
- SVGPolygonElement : false,
- SVGPolylineElement : false,
- SVGPreserveAspectRatio: false,
- SVGRadialGradientElement: false,
- SVGRect : false,
- SVGRectElement : false,
- SVGRenderingIntent : false,
- SVGSVGElement : false,
- SVGScriptElement : false,
- SVGSetElement : false,
- SVGStopElement : false,
- SVGStringList : false,
- SVGStylable : false,
- SVGStyleElement : false,
- SVGSwitchElement : false,
- SVGSymbolElement : false,
- SVGTRefElement : false,
- SVGTSpanElement : false,
- SVGTests : false,
- SVGTextContentElement: false,
- SVGTextElement : false,
- SVGTextPathElement : false,
- SVGTextPositioningElement: false,
- SVGTitleElement : false,
- SVGTransform : false,
- SVGTransformList : false,
- SVGTransformable : false,
- SVGURIReference : false,
- SVGUnitTypes : false,
- SVGUseElement : false,
- SVGVKernElement : false,
- SVGViewElement : false,
- SVGViewSpec : false,
- SVGZoomAndPan : false,
- TimeEvent : false,
- top : false,
- Uint16Array : false,
- Uint32Array : false,
- Uint8Array : false,
- Uint8ClampedArray : false,
- WebSocket : false,
- window : false,
- Worker : false,
- XMLHttpRequest : false,
- XMLSerializer : false,
- XPathEvaluator : false,
- XPathException : false,
- XPathExpression : false,
- XPathNSResolver : false,
- XPathResult : false
-};
-
-exports.devel = {
- alert : false,
- confirm: false,
- console: false,
- Debug : false,
- opera : false,
- prompt : false
-};
-
-exports.worker = {
- importScripts: true,
- postMessage : true,
- self : true
-};
-
-// Widely adopted global names that are not part of ECMAScript standard
-exports.nonstandard = {
- escape : false,
- unescape: false
-};
-
-// Globals provided by popular JavaScript environments.
-
-exports.couch = {
- "require" : false,
- respond : false,
- getRow : false,
- emit : false,
- send : false,
- start : false,
- sum : false,
- log : false,
- exports : false,
- module : false,
- provides : false
-};
-
-exports.node = {
- __filename : false,
- __dirname : false,
- Buffer : false,
- DataView : false,
- console : false,
- exports : true, // In Node it is ok to exports = module.exports = foo();
- GLOBAL : false,
- global : false,
- module : false,
- process : false,
- require : false,
- setTimeout : false,
- clearTimeout : false,
- setInterval : false,
- clearInterval : false,
- setImmediate : false, // v0.9.1+
- clearImmediate: false // v0.9.1+
-};
-
-exports.phantom = {
- phantom : true,
- require : true,
- WebPage : true
-};
-
-exports.rhino = {
- defineClass : false,
- deserialize : false,
- gc : false,
- help : false,
- importPackage: false,
- "java" : false,
- load : false,
- loadClass : false,
- print : false,
- quit : false,
- readFile : false,
- readUrl : false,
- runCommand : false,
- seal : false,
- serialize : false,
- spawn : false,
- sync : false,
- toint32 : false,
- version : false
-};
-
-exports.wsh = {
- ActiveXObject : true,
- Enumerator : true,
- GetObject : true,
- ScriptEngine : true,
- ScriptEngineBuildVersion : true,
- ScriptEngineMajorVersion : true,
- ScriptEngineMinorVersion : true,
- VBArray : true,
- WSH : true,
- WScript : true,
- XDomainRequest : true
-};
-
-// Globals provided by popular JavaScript libraries.
-
-exports.dojo = {
- dojo : false,
- dijit : false,
- dojox : false,
- define : false,
- "require": false
-};
-
-exports.jquery = {
- "$" : false,
- jQuery : false
-};
-
-exports.mootools = {
- "$" : false,
- "$$" : false,
- Asset : false,
- Browser : false,
- Chain : false,
- Class : false,
- Color : false,
- Cookie : false,
- Core : false,
- Document : false,
- DomReady : false,
- DOMEvent : false,
- DOMReady : false,
- Drag : false,
- Element : false,
- Elements : false,
- Event : false,
- Events : false,
- Fx : false,
- Group : false,
- Hash : false,
- HtmlTable : false,
- Iframe : false,
- IframeShim : false,
- InputValidator: false,
- instanceOf : false,
- Keyboard : false,
- Locale : false,
- Mask : false,
- MooTools : false,
- Native : false,
- Options : false,
- OverText : false,
- Request : false,
- Scroller : false,
- Slick : false,
- Slider : false,
- Sortables : false,
- Spinner : false,
- Swiff : false,
- Tips : false,
- Type : false,
- typeOf : false,
- URI : false,
- Window : false
-};
-
-exports.prototypejs = {
- "$" : false,
- "$$" : false,
- "$A" : false,
- "$F" : false,
- "$H" : false,
- "$R" : false,
- "$break" : false,
- "$continue" : false,
- "$w" : false,
- Abstract : false,
- Ajax : false,
- Class : false,
- Enumerable : false,
- Element : false,
- Event : false,
- Field : false,
- Form : false,
- Hash : false,
- Insertion : false,
- ObjectRange : false,
- PeriodicalExecuter: false,
- Position : false,
- Prototype : false,
- Selector : false,
- Template : false,
- Toggle : false,
- Try : false,
- Autocompleter : false,
- Builder : false,
- Control : false,
- Draggable : false,
- Draggables : false,
- Droppables : false,
- Effect : false,
- Sortable : false,
- SortableObserver : false,
- Sound : false,
- Scriptaculous : false
-};
-
-exports.yui = {
- YUI : false,
- Y : false,
- YUI_config: false
-};
-
-
-})()
-},{}],4:[function(require,module,exports){
-"use strict";
-
-var state = {
- syntax: {},
-
- reset: function () {
- this.tokens = {
- prev: null,
- next: null,
- curr: null
- };
-
- this.option = {};
- this.ignored = {};
- this.directive = {};
- this.jsonMode = false;
- this.jsonWarnings = [];
- this.lines = [];
- this.tab = "";
- this.cache = {}; // Node.JS doesn't have Map. Sniff.
- }
-};
-
-exports.state = state;
-
-},{}],5:[function(require,module,exports){
-(function(){"use strict";
-
-exports.register = function (linter) {
- // Check for properties named __proto__. This special property was
- // deprecated and then re-introduced for ES6.
-
- linter.on("Identifier", function style_scanProto(data) {
- if (linter.getOption("proto")) {
- return;
- }
-
- if (data.name === "__proto__") {
- linter.warn("W103", {
- line: data.line,
- char: data.char,
- data: [ data.name ]
- });
- }
- });
-
- // Check for properties named __iterator__. This is a special property
- // available only in browsers with JavaScript 1.7 implementation.
-
- linter.on("Identifier", function style_scanIterator(data) {
- if (linter.getOption("iterator")) {
- return;
- }
-
- if (data.name === "__iterator__") {
- linter.warn("W104", {
- line: data.line,
- char: data.char,
- data: [ data.name ]
- });
- }
- });
-
- // Check for dangling underscores.
-
- linter.on("Identifier", function style_scanDangling(data) {
- if (!linter.getOption("nomen")) {
- return;
- }
-
- // Underscore.js
- if (data.name === "_") {
- return;
- }
-
- // In Node, __dirname and __filename should be ignored.
- if (linter.getOption("node")) {
- if (/^(__dirname|__filename)$/.test(data.name) && !data.isProperty) {
- return;
- }
- }
-
- if (/^(_+.*|.*_+)$/.test(data.name)) {
- linter.warn("W105", {
- line: data.line,
- char: data.from,
- data: [ "dangling '_'", data.name ]
- });
- }
- });
-
- // Check that all identifiers are using camelCase notation.
- // Exceptions: names like MY_VAR and _myVar.
-
- linter.on("Identifier", function style_scanCamelCase(data) {
- if (!linter.getOption("camelcase")) {
- return;
- }
-
- if (data.name.replace(/^_+/, "").indexOf("_") > -1 && !data.name.match(/^[A-Z0-9_]*$/)) {
- linter.warn("W106", {
- line: data.line,
- char: data.from,
- data: [ data.name ]
- });
- }
- });
-
- // Enforce consistency in style of quoting.
-
- linter.on("String", function style_scanQuotes(data) {
- var quotmark = linter.getOption("quotmark");
- var code;
-
- if (!quotmark) {
- return;
- }
-
- // If quotmark is set to 'single' warn about all double-quotes.
-
- if (quotmark === "single" && data.quote !== "'") {
- code = "W109";
- }
-
- // If quotmark is set to 'double' warn about all single-quotes.
-
- if (quotmark === "double" && data.quote !== "\"") {
- code = "W108";
- }
-
- // If quotmark is set to true, remember the first quotation style
- // and then warn about all others.
-
- if (quotmark === true) {
- if (!linter.getCache("quotmark")) {
- linter.setCache("quotmark", data.quote);
- }
-
- if (linter.getCache("quotmark") !== data.quote) {
- code = "W110";
- }
- }
-
- if (code) {
- linter.warn(code, {
- line: data.line,
- char: data.char,
- });
- }
- });
-
- linter.on("Number", function style_scanNumbers(data) {
- if (data.value.charAt(0) === ".") {
- // Warn about a leading decimal point.
- linter.warn("W008", {
- line: data.line,
- char: data.char,
- data: [ data.value ]
- });
- }
-
- if (data.value.substr(data.value.length - 1) === ".") {
- // Warn about a trailing decimal point.
- linter.warn("W047", {
- line: data.line,
- char: data.char,
- data: [ data.value ]
- });
- }
-
- if (/^00+/.test(data.value)) {
- // Multiple leading zeroes.
- linter.warn("W046", {
- line: data.line,
- char: data.char,
- data: [ data.value ]
- });
- }
- });
-
- // Warn about script URLs.
-
- linter.on("String", function style_scanJavaScriptURLs(data) {
- var re = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i;
-
- if (linter.getOption("scripturl")) {
- return;
- }
-
- if (re.test(data.value)) {
- linter.warn("W107", {
- line: data.line,
- char: data.char
- });
- }
- });
-};
-})()
-},{}],6:[function(require,module,exports){
-/*
- * Regular expressions. Some of these are stupidly long.
- */
-
-/*jshint maxlen:1000 */
-
-"use string";
-
-// Unsafe comment or string (ax)
-exports.unsafeString =
- /@cc|<\/?|script|\]\s*\]|<\s*!|&lt/i;
-
-// Unsafe characters that are silently deleted by one or more browsers (cx)
-exports.unsafeChars =
- /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/;
-
-// Characters in strings that need escaping (nx and nxg)
-exports.needEsc =
- /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/;
-
-exports.needEscGlobal =
- /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
-
-// Star slash (lx)
-exports.starSlash = /\*\//;
-
-// Identifier (ix)
-exports.identifier = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/;
-
-// JavaScript URL (jx)
-exports.javascriptURL = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i;
-
-// Catches /* falls through */ comments (ft)
-//exports.fallsThrough = /^\s*\/\*\s*falls?\sthrough\s*\*\/\s*$/;
-exports.fallsThrough = /^\s*\/\/\s*Falls?\sthrough.*\s*$/;
-
-},{}],7:[function(require,module,exports){
-(function(global){/*global window, global*/
-var util = require("util")
-var assert = require("assert")
-
-var slice = Array.prototype.slice
-var console
-var times = {}
-
-if (typeof global !== "undefined" && global.console) {
- console = global.console
-} else if (typeof window !== "undefined" && window.console) {
- console = window.console
-} else {
- console = window.console = {}
-}
-
-var functions = [
- [log, "log"]
- , [info, "info"]
- , [warn, "warn"]
- , [error, "error"]
- , [time, "time"]
- , [timeEnd, "timeEnd"]
- , [trace, "trace"]
- , [dir, "dir"]
- , [assert, "assert"]
-]
-
-for (var i = 0; i < functions.length; i++) {
- var tuple = functions[i]
- var f = tuple[0]
- var name = tuple[1]
-
- if (!console[name]) {
- console[name] = f
- }
-}
-
-module.exports = console
-
-function log() {}
-
-function info() {
- console.log.apply(console, arguments)
-}
-
-function warn() {
- console.log.apply(console, arguments)
-}
-
-function error() {
- console.warn.apply(console, arguments)
-}
-
-function time(label) {
- times[label] = Date.now()
-}
-
-function timeEnd(label) {
- var time = times[label]
- if (!time) {
- throw new Error("No such label: " + label)
- }
-
- var duration = Date.now() - time
- console.log(label + ": " + duration + "ms")
-}
-
-function trace() {
- var err = new Error()
- err.name = "Trace"
- err.message = util.format.apply(null, arguments)
- console.error(err.stack)
-}
-
-function dir(object) {
- console.log(util.inspect(object) + "\n")
-}
-
-function assert(expression) {
- if (!expression) {
- var arr = slice.call(arguments, 1)
- assert.ok(false, util.format.apply(null, arr))
- }
-}
-
-})(window)
-},{"util":8,"assert":9}],10:[function(require,module,exports){
-(function(){/*
- * Lexical analysis and token construction.
- */
-
-"use strict";
-
-var _ = require("underscore");
-var events = require("events");
-var reg = require("./reg.js");
-var state = require("./state.js").state;
-
-// Some of these token types are from JavaScript Parser API
-// while others are specific to JSHint parser.
-// JS Parser API: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
-
-var Token = {
- Identifier: 1,
- Punctuator: 2,
- NumericLiteral: 3,
- StringLiteral: 4,
- Comment: 5,
- Keyword: 6,
- NullLiteral: 7,
- BooleanLiteral: 8,
- RegExp: 9
-};
-
-// This is auto generated from the unicode tables.
-// The tables are at:
-// http://www.fileformat.info/info/unicode/category/Lu/list.htm
-// http://www.fileformat.info/info/unicode/category/Ll/list.htm
-// http://www.fileformat.info/info/unicode/category/Lt/list.htm
-// http://www.fileformat.info/info/unicode/category/Lm/list.htm
-// http://www.fileformat.info/info/unicode/category/Lo/list.htm
-// http://www.fileformat.info/info/unicode/category/Nl/list.htm
-
-var unicodeLetterTable = [
- 170, 170, 181, 181, 186, 186, 192, 214,
- 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750,
- 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908,
- 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366,
- 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610,
- 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775,
- 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957,
- 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069,
- 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2308, 2361,
- 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431,
- 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482,
- 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529,
- 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608,
- 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654,
- 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736,
- 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785,
- 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867,
- 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929,
- 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970,
- 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001,
- 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123,
- 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212,
- 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261,
- 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344,
- 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455,
- 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526,
- 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716,
- 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743,
- 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760,
- 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805,
- 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138,
- 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198,
- 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4304, 4346,
- 4348, 4348, 4352, 4680, 4682, 4685, 4688, 4694, 4696, 4696,
- 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789,
- 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880,
- 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740,
- 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900,
- 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000,
- 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312,
- 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516,
- 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823,
- 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7104, 7141,
- 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409,
- 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013,
- 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061,
- 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140,
- 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188,
- 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455,
- 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486,
- 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521,
- 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358,
- 11360, 11492, 11499, 11502, 11520, 11557, 11568, 11621,
- 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694,
- 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726,
- 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295,
- 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438,
- 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589,
- 12593, 12686, 12704, 12730, 12784, 12799, 13312, 13312,
- 19893, 19893, 19968, 19968, 40907, 40907, 40960, 42124,
- 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539,
- 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783,
- 42786, 42888, 42891, 42894, 42896, 42897, 42912, 42921,
- 43002, 43009, 43011, 43013, 43015, 43018, 43020, 43042,
- 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259,
- 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442,
- 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595,
- 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697,
- 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714,
- 43739, 43741, 43777, 43782, 43785, 43790, 43793, 43798,
- 43808, 43814, 43816, 43822, 43968, 44002, 44032, 44032,
- 55203, 55203, 55216, 55238, 55243, 55291, 63744, 64045,
- 64048, 64109, 64112, 64217, 64256, 64262, 64275, 64279,
- 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316,
- 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433,
- 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019,
- 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370,
- 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495,
- 65498, 65500, 65536, 65547, 65549, 65574, 65576, 65594,
- 65596, 65597, 65599, 65613, 65616, 65629, 65664, 65786,
- 65856, 65908, 66176, 66204, 66208, 66256, 66304, 66334,
- 66352, 66378, 66432, 66461, 66464, 66499, 66504, 66511,
- 66513, 66517, 66560, 66717, 67584, 67589, 67592, 67592,
- 67594, 67637, 67639, 67640, 67644, 67644, 67647, 67669,
- 67840, 67861, 67872, 67897, 68096, 68096, 68112, 68115,
- 68117, 68119, 68121, 68147, 68192, 68220, 68352, 68405,
- 68416, 68437, 68448, 68466, 68608, 68680, 69635, 69687,
- 69763, 69807, 73728, 74606, 74752, 74850, 77824, 78894,
- 92160, 92728, 110592, 110593, 119808, 119892, 119894, 119964,
- 119966, 119967, 119970, 119970, 119973, 119974, 119977, 119980,
- 119982, 119993, 119995, 119995, 119997, 120003, 120005, 120069,
- 120071, 120074, 120077, 120084, 120086, 120092, 120094, 120121,
- 120123, 120126, 120128, 120132, 120134, 120134, 120138, 120144,
- 120146, 120485, 120488, 120512, 120514, 120538, 120540, 120570,
- 120572, 120596, 120598, 120628, 120630, 120654, 120656, 120686,
- 120688, 120712, 120714, 120744, 120746, 120770, 120772, 120779,
- 131072, 131072, 173782, 173782, 173824, 173824, 177972, 177972,
- 177984, 177984, 178205, 178205, 194560, 195101
-];
-
-var identifierStartTable = [];
-
-for (var i = 0; i < 128; i++) {
- identifierStartTable[i] =
- i === 36 || // $
- i >= 65 && i <= 90 || // A-Z
- i === 95 || // _
- i >= 97 && i <= 122; // a-z
-}
-
-var identifierPartTable = [];
-
-for (var i = 0; i < 128; i++) {
- identifierPartTable[i] =
- identifierStartTable[i] || // $, _, A-Z, a-z
- i >= 48 && i <= 57; // 0-9
-}
-
-// Object that handles postponed lexing verifications that checks the parsed
-// environment state.
-
-function asyncTrigger() {
- var _checks = [];
-
- return {
- push: function (fn) {
- _checks.push(fn);
- },
-
- check: function () {
- for (var check in _checks) {
- _checks[check]();
- }
-
- _checks.splice(0, _checks.length);
- }
- };
-}
-
-/*
- * Lexer for JSHint.
- *
- * This object does a char-by-char scan of the provided source code
- * and produces a sequence of tokens.
- *
- * var lex = new Lexer("var i = 0;");
- * lex.start();
- * lex.token(); // returns the next token
- *
- * You have to use the token() method to move the lexer forward
- * but you don't have to use its return value to get tokens. In addition
- * to token() method returning the next token, the Lexer object also
- * emits events.
- *
- * lex.on("Identifier", function (data) {
- * if (data.name.indexOf("_") >= 0) {
- * // Produce a warning.
- * }
- * });
- *
- * Note that the token() method returns tokens in a JSLint-compatible
- * format while the event emitter uses a slightly modified version of
- * Mozilla's JavaScript Parser API. Eventually, we will move away from
- * JSLint format.
- */
-function Lexer(source) {
- var lines = source;
-
- if (typeof lines === "string") {
- lines = lines
- .replace(/\r\n/g, "\n")
- .replace(/\r/g, "\n")
- .split("\n");
- }
-
- // If the first line is a shebang (#!), make it a blank and move on.
- // Shebangs are used by Node scripts.
-
- if (lines[0] && lines[0].substr(0, 2) === "#!") {
- lines[0] = "";
- }
-
- this.emitter = new events.EventEmitter();
- this.source = source;
- this.lines = lines;
- this.prereg = true;
-
- this.line = 0;
- this.char = 1;
- this.from = 1;
- this.input = "";
-
- for (var i = 0; i < state.option.indent; i += 1) {
- state.tab += " ";
- }
-}
-
-Lexer.prototype = {
- _lines: [],
-
- get lines() {
- this._lines = state.lines;
- return this._lines;
- },
-
- set lines(val) {
- this._lines = val;
- state.lines = this._lines;
- },
-
- /*
- * Return the next i character without actually moving the
- * char pointer.
- */
- peek: function (i) {
- return this.input.charAt(i || 0);
- },
-
- /*
- * Move the char pointer forward i times.
- */
- skip: function (i) {
- i = i || 1;
- this.char += i;
- this.input = this.input.slice(i);
- },
-
- /*
- * Subscribe to a token event. The API for this method is similar
- * Underscore.js i.e. you can subscribe to multiple events with
- * one call:
- *
- * lex.on("Identifier Number", function (data) {
- * // ...
- * });
- */
- on: function (names, listener) {
- names.split(" ").forEach(function (name) {
- this.emitter.on(name, listener);
- }.bind(this));
- },
-
- /*
- * Trigger a token event. All arguments will be passed to each
- * listener.
- */
- trigger: function () {
- this.emitter.emit.apply(this.emitter, Array.prototype.slice.call(arguments));
- },
-
- /*
- * Postpone a token event. the checking condition is set as
- * last parameter, and the trigger function is called in a
- * stored callback. To be later called using the check() function
- * by the parser. This avoids parser's peek() to give the lexer
- * a false context.
- */
- triggerAsync: function (type, args, checks, fn) {
- checks.push(function () {
- if (fn()) {
- this.trigger(type, args);
- }
- }.bind(this));
- },
-
- /*
- * Extract a punctuator out of the next sequence of characters
- * or return 'null' if its not possible.
- *
- * This method's implementation was heavily influenced by the
- * scanPunctuator function in the Esprima parser's source code.
- */
- scanPunctuator: function () {
- var ch1 = this.peek();
- var ch2, ch3, ch4;
-
- switch (ch1) {
- // Most common single-character punctuators
- case ".":
- if ((/^[0-9]$/).test(this.peek(1))) {
- return null;
- }
- if (this.peek(1) === "." && this.peek(2) === ".") {
- return {
- type: Token.Punctuator,
- value: "..."
- };
- }
- /* falls through */
- case "(":
- case ")":
- case ";":
- case ",":
- case "{":
- case "}":
- case "[":
- case "]":
- case ":":
- case "~":
- case "?":
- return {
- type: Token.Punctuator,
- value: ch1
- };
-
- // A pound sign (for Node shebangs)
- case "#":
- return {
- type: Token.Punctuator,
- value: ch1
- };
-
- // We're at the end of input
- case "":
- return null;
- }
-
- // Peek more characters
-
- ch2 = this.peek(1);
- ch3 = this.peek(2);
- ch4 = this.peek(3);
-
- // 4-character punctuator: >>>=
-
- if (ch1 === ">" && ch2 === ">" && ch3 === ">" && ch4 === "=") {
- return {
- type: Token.Punctuator,
- value: ">>>="
- };
- }
-
- // 3-character punctuators: === !== >>> <<= >>=
-
- if (ch1 === "=" && ch2 === "=" && ch3 === "=") {
- return {
- type: Token.Punctuator,
- value: "==="
- };
- }
-
- if (ch1 === "!" && ch2 === "=" && ch3 === "=") {
- return {
- type: Token.Punctuator,
- value: "!=="
- };
- }
-
- if (ch1 === ">" && ch2 === ">" && ch3 === ">") {
- return {
- type: Token.Punctuator,
- value: ">>>"
- };
- }
-
- if (ch1 === "<" && ch2 === "<" && ch3 === "=") {
- return {
- type: Token.Punctuator,
- value: "<<="
- };
- }
-
- if (ch1 === ">" && ch2 === ">" && ch3 === "=") {
- return {
- type: Token.Punctuator,
- value: ">>="
- };
- }
-
- // Fat arrow punctuator
- if (ch1 === "=" && ch2 === ">") {
- return {
- type: Token.Punctuator,
- value: ch1 + ch2
- };
- }
-
- // 2-character punctuators: <= >= == != ++ -- << >> && ||
- // += -= *= %= &= |= ^= (but not /=, see below)
- if (ch1 === ch2 && ("+-<>&|".indexOf(ch1) >= 0)) {
- return {
- type: Token.Punctuator,
- value: ch1 + ch2
- };
- }
-
- if ("<>=!+-*%&|^".indexOf(ch1) >= 0) {
- if (ch2 === "=") {
- return {
- type: Token.Punctuator,
- value: ch1 + ch2
- };
- }
-
- return {
- type: Token.Punctuator,
- value: ch1
- };
- }
-
- // Special case: /=. We need to make sure that this is an
- // operator and not a regular expression.
-
- if (ch1 === "/") {
- if (ch2 === "=" && /\/=(?!(\S*\/[gim]?))/.test(this.input)) {
- // /= is not a part of a regular expression, return it as a
- // punctuator.
- return {
- type: Token.Punctuator,
- value: "/="
- };
- }
-
- return {
- type: Token.Punctuator,
- value: "/"
- };
- }
-
- return null;
- },
-
- /*
- * Extract a comment out of the next sequence of characters and/or
- * lines or return 'null' if its not possible. Since comments can
- * span across multiple lines this method has to move the char
- * pointer.
- *
- * In addition to normal JavaScript comments (// and /*) this method
- * also recognizes JSHint- and JSLint-specific comments such as
- * /*jshint, /*jslint, /*globals and so on.
- */
- scanComments: function () {
- var ch1 = this.peek();
- var ch2 = this.peek(1);
- var rest = this.input.substr(2);
- var startLine = this.line;
- var startChar = this.char;
-
- // Create a comment token object and make sure it
- // has all the data JSHint needs to work with special
- // comments.
-
- function commentToken(label, body, opt) {
- var special = ["jshint", "jslint", "members", "member", "globals", "global", "exported"];
- var isSpecial = false;
- var value = label + body;
- var commentType = "plain";
- opt = opt || {};
-
- if (opt.isMultiline) {
- value += "*/";
- }
-
- special.forEach(function (str) {
- if (isSpecial) {
- return;
- }
-
- // Don't recognize any special comments other than jshint for single-line
- // comments. This introduced many problems with legit comments.
- if (label === "//" && str !== "jshint") {
- return;
- }
-
- if (body.substr(0, str.length) === str) {
- isSpecial = true;
- label = label + str;
- body = body.substr(str.length);
- }
-
- if (!isSpecial && body.charAt(0) === " " && body.substr(1, str.length) === str) {
- isSpecial = true;
- label = label + " " + str;
- body = body.substr(str.length + 1);
- }
-
- if (!isSpecial) {
- return;
- }
-
- switch (str) {
- case "member":
- commentType = "members";
- break;
- case "global":
- commentType = "globals";
- break;
- default:
- commentType = str;
- }
- });
-
- return {
- type: Token.Comment,
- commentType: commentType,
- value: value,
- body: body,
- isSpecial: isSpecial,
- isMultiline: opt.isMultiline || false,
- isMalformed: opt.isMalformed || false
- };
- }
-
- // End of unbegun comment. Raise an error and skip that input.
- if (ch1 === "*" && ch2 === "/") {
- this.trigger("error", {
- code: "E018",
- line: startLine,
- character: startChar
- });
-
- this.skip(2);
- return null;
- }
-
- // Comments must start either with // or /*
- if (ch1 !== "/" || (ch2 !== "*" && ch2 !== "/")) {
- return null;
- }
-
- // One-line comment
- if (ch2 === "/") {
- this.skip(this.input.length); // Skip to the EOL.
- return commentToken("//", rest);
- }
-
- var body = "";
-
- /* Multi-line comment */
- if (ch2 === "*") {
- this.skip(2);
-
- while (this.peek() !== "*" || this.peek(1) !== "/") {
- if (this.peek() === "") { // End of Line
- body += "\n";
-
- // If we hit EOF and our comment is still unclosed,
- // trigger an error and end the comment implicitly.
- if (!this.nextLine()) {
- this.trigger("error", {
- code: "E017",
- line: startLine,
- character: startChar
- });
-
- return commentToken("/*", body, {
- isMultiline: true,
- isMalformed: true
- });
- }
- } else {
- body += this.peek();
- this.skip();
- }
- }
-
- this.skip(2);
- return commentToken("/*", body, { isMultiline: true });
- }
- },
-
- /*
- * Extract a keyword out of the next sequence of characters or
- * return 'null' if its not possible.
- */
- scanKeyword: function () {
- var result = /^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input);
- var keywords = [
- "if", "in", "do", "var", "for", "new",
- "try", "let", "this", "else", "case",
- "void", "with", "enum", "while", "break",
- "catch", "throw", "const", "yield", "class",
- "super", "return", "typeof", "delete",
- "switch", "export", "import", "default",
- "finally", "extends", "function", "continue",
- "debugger", "instanceof"
- ];
-
- if (result && keywords.indexOf(result[0]) >= 0) {
- return {
- type: Token.Keyword,
- value: result[0]
- };
- }
-
- return null;
- },
-
- /*
- * Extract a JavaScript identifier out of the next sequence of
- * characters or return 'null' if its not possible. In addition,
- * to Identifier this method can also produce BooleanLiteral
- * (true/false) and NullLiteral (null).
- */
- scanIdentifier: function () {
- var id = "";
- var index = 0;
- var type, char;
-
- // Detects any character in the Unicode categories "Uppercase
- // letter (Lu)", "Lowercase letter (Ll)", "Titlecase letter
- // (Lt)", "Modifier letter (Lm)", "Other letter (Lo)", or
- // "Letter number (Nl)".
- //
- // Both approach and unicodeLetterTable were borrowed from
- // Google's Traceur.
-
- function isUnicodeLetter(code) {
- for (var i = 0; i < unicodeLetterTable.length;) {
- if (code < unicodeLetterTable[i++]) {
- return false;
- }
-
- if (code <= unicodeLetterTable[i++]) {
- return true;
- }
- }
-
- return false;
- }
-
- function isHexDigit(str) {
- return (/^[0-9a-fA-F]$/).test(str);
- }
-
- var readUnicodeEscapeSequence = function () {
- /*jshint validthis:true */
- index += 1;
-
- if (this.peek(index) !== "u") {
- return null;
- }
-
- var ch1 = this.peek(index + 1);
- var ch2 = this.peek(index + 2);
- var ch3 = this.peek(index + 3);
- var ch4 = this.peek(index + 4);
- var code;
-
- if (isHexDigit(ch1) && isHexDigit(ch2) && isHexDigit(ch3) && isHexDigit(ch4)) {
- code = parseInt(ch1 + ch2 + ch3 + ch4, 16);
-
- if (isUnicodeLetter(code)) {
- index += 5;
- return "\\u" + ch1 + ch2 + ch3 + ch4;
- }
-
- return null;
- }
-
- return null;
- }.bind(this);
-
- var getIdentifierStart = function () {
- /*jshint validthis:true */
- var chr = this.peek(index);
- var code = chr.charCodeAt(0);
-
- if (code === 92) {
- return readUnicodeEscapeSequence();
- }
-
- if (code < 128) {
- if (identifierStartTable[code]) {
- index += 1;
- return chr;
- }
-
- return null;
- }
-
- if (isUnicodeLetter(code)) {
- index += 1;
- return chr;
- }
-
- return null;
- }.bind(this);
-
- var getIdentifierPart = function () {
- /*jshint validthis:true */
- var chr = this.peek(index);
- var code = chr.charCodeAt(0);
-
- if (code === 92) {
- return readUnicodeEscapeSequence();
- }
-
- if (code < 128) {
- if (identifierPartTable[code]) {
- index += 1;
- return chr;
- }
-
- return null;
- }
-
- if (isUnicodeLetter(code)) {
- index += 1;
- return chr;
- }
-
- return null;
- }.bind(this);
-
- char = getIdentifierStart();
- if (char === null) {
- return null;
- }
-
- id = char;
- for (;;) {
- char = getIdentifierPart();
-
- if (char === null) {
- break;
- }
-
- id += char;
- }
-
- switch (id) {
- case "true":
- case "false":
- type = Token.BooleanLiteral;
- break;
- case "null":
- type = Token.NullLiteral;
- break;
- default:
- type = Token.Identifier;
- }
-
- return {
- type: type,
- value: id
- };
- },
-
- /*
- * Extract a numeric literal out of the next sequence of
- * characters or return 'null' if its not possible. This method
- * supports all numeric literals described in section 7.8.3
- * of the EcmaScript 5 specification.
- *
- * This method's implementation was heavily influenced by the
- * scanNumericLiteral function in the Esprima parser's source code.
- */
- scanNumericLiteral: function () {
- var index = 0;
- var value = "";
- var length = this.input.length;
- var char = this.peek(index);
- var bad;
-
- function isDecimalDigit(str) {
- return (/^[0-9]$/).test(str);
- }
-
- function isOctalDigit(str) {
- return (/^[0-7]$/).test(str);
- }
-
- function isHexDigit(str) {
- return (/^[0-9a-fA-F]$/).test(str);
- }
-
- function isIdentifierStart(ch) {
- return (ch === "$") || (ch === "_") || (ch === "\\") ||
- (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z");
- }
-
- // Numbers must start either with a decimal digit or a point.
-
- if (char !== "." && !isDecimalDigit(char)) {
- return null;
- }
-
- if (char !== ".") {
- value = this.peek(index);
- index += 1;
- char = this.peek(index);
-
- if (value === "0") {
- // Base-16 numbers.
- if (char === "x" || char === "X") {
- index += 1;
- value += char;
-
- while (index < length) {
- char = this.peek(index);
- if (!isHexDigit(char)) {
- break;
- }
- value += char;
- index += 1;
- }
-
- if (value.length <= 2) { // 0x
- return {
- type: Token.NumericLiteral,
- value: value,
- isMalformed: true
- };
- }
-
- if (index < length) {
- char = this.peek(index);
- if (isIdentifierStart(char)) {
- return null;
- }
- }
-
- return {
- type: Token.NumericLiteral,
- value: value,
- base: 16,
- isMalformed: false
- };
- }
-
- // Base-8 numbers.
- if (isOctalDigit(char)) {
- index += 1;
- value += char;
- bad = false;
-
- while (index < length) {
- char = this.peek(index);
-
- // Numbers like '019' (note the 9) are not valid octals
- // but we still parse them and mark as malformed.
-
- if (isDecimalDigit(char)) {
- bad = true;
- } else if (!isOctalDigit(char)) {
- break;
- }
- value += char;
- index += 1;
- }
-
- if (index < length) {
- char = this.peek(index);
- if (isIdentifierStart(char)) {
- return null;
- }
- }
-
- return {
- type: Token.NumericLiteral,
- value: value,
- base: 8,
- isMalformed: false
- };
- }
-
- // Decimal numbers that start with '0' such as '09' are illegal
- // but we still parse them and return as malformed.
-
- if (isDecimalDigit(char)) {
- index += 1;
- value += char;
- }
- }
-
- while (index < length) {
- char = this.peek(index);
- if (!isDecimalDigit(char)) {
- break;
- }
- value += char;
- index += 1;
- }
- }
-
- // Decimal digits.
-
- if (char === ".") {
- value += char;
- index += 1;
-
- while (index < length) {
- char = this.peek(index);
- if (!isDecimalDigit(char)) {
- break;
- }
- value += char;
- index += 1;
- }
- }
-
- // Exponent part.
-
- if (char === "e" || char === "E") {
- value += char;
- index += 1;
- char = this.peek(index);
-
- if (char === "+" || char === "-") {
- value += this.peek(index);
- index += 1;
- }
-
- char = this.peek(index);
- if (isDecimalDigit(char)) {
- value += char;
- index += 1;
-
- while (index < length) {
- char = this.peek(index);
- if (!isDecimalDigit(char)) {
- break;
- }
- value += char;
- index += 1;
- }
- } else {
- return null;
- }
- }
-
- if (index < length) {
- char = this.peek(index);
- if (isIdentifierStart(char)) {
- return null;
- }
- }
-
- return {
- type: Token.NumericLiteral,
- value: value,
- base: 10,
- isMalformed: !isFinite(value)
- };
- },
-
- /*
- * Extract a string out of the next sequence of characters and/or
- * lines or return 'null' if its not possible. Since strings can
- * span across multiple lines this method has to move the char
- * pointer.
- *
- * This method recognizes pseudo-multiline JavaScript strings:
- *
- * var str = "hello\
- * world";
- */
- scanStringLiteral: function (checks) {
- /*jshint loopfunc:true */
- var quote = this.peek();
-
- // String must start with a quote.
- if (quote !== "\"" && quote !== "'") {
- return null;
- }
-
- // In JSON strings must always use double quotes.
- this.triggerAsync("warning", {
- code: "W108",
- line: this.line,
- character: this.char // +1?
- }, checks, function () { return state.jsonMode && quote !== "\""; });
-
- var value = "";
- var startLine = this.line;
- var startChar = this.char;
- var allowNewLine = false;
-
- this.skip();
-
- while (this.peek() !== quote) {
- while (this.peek() === "") { // End Of Line
-
- // If an EOL is not preceded by a backslash, show a warning
- // and proceed like it was a legit multi-line string where
- // author simply forgot to escape the newline symbol.
- //
- // Another approach is to implicitly close a string on EOL
- // but it generates too many false positives.
-
- if (!allowNewLine) {
- this.trigger("warning", {
- code: "W112",
- line: this.line,
- character: this.char
- });
- } else {
- allowNewLine = false;
-
- // Otherwise show a warning if multistr option was not set.
- // For JSON, show warning no matter what.
-
- this.triggerAsync("warning", {
- code: "W043",
- line: this.line,
- character: this.char
- }, checks, function () { return !state.option.multistr; });
-
- this.triggerAsync("warning", {
- code: "W042",
- line: this.line,
- character: this.char
- }, checks, function () { return state.jsonMode && state.option.multistr; });
- }
-
- // If we get an EOF inside of an unclosed string, show an
- // error and implicitly close it at the EOF point.
-
- if (!this.nextLine()) {
- this.trigger("error", {
- code: "E029",
- line: startLine,
- character: startChar
- });
-
- return {
- type: Token.StringLiteral,
- value: value,
- isUnclosed: true,
- quote: quote
- };
- }
- }
-
- allowNewLine = false;
- var char = this.peek();
- var jump = 1; // A length of a jump, after we're done
- // parsing this character.
-
- if (char < " ") {
- // Warn about a control character in a string.
- this.trigger("warning", {
- code: "W113",
- line: this.line,
- character: this.char,
- data: [ "<non-printable>" ]
- });
- }
-
- // Special treatment for some escaped characters.
-
- if (char === "\\") {
- this.skip();
- char = this.peek();
-
- switch (char) {
- case "'":
- this.triggerAsync("warning", {
- code: "W114",
- line: this.line,
- character: this.char,
- data: [ "\\'" ]
- }, checks, function () {return state.jsonMode; });
- break;
- case "b":
- char = "\b";
- break;
- case "f":
- char = "\f";
- break;
- case "n":
- char = "\n";
- break;
- case "r":
- char = "\r";
- break;
- case "t":
- char = "\t";
- break;
- case "0":
- char = "\0";
-
- // Octal literals fail in strict mode.
- // Check if the number is between 00 and 07.
- var n = parseInt(this.peek(1), 10);
- this.triggerAsync("warning", {
- code: "W115",
- line: this.line,
- character: this.char
- }, checks,
- function () { return n >= 0 && n <= 7 && state.directive["use strict"]; });
- break;
- case "u":
- char = String.fromCharCode(parseInt(this.input.substr(1, 4), 16));
- jump = 5;
- break;
- case "v":
- this.triggerAsync("warning", {
- code: "W114",
- line: this.line,
- character: this.char,
- data: [ "\\v" ]
- }, checks, function () { return state.jsonMode; });
-
- char = "\v";
- break;
- case "x":
- var x = parseInt(this.input.substr(1, 2), 16);
-
- this.triggerAsync("warning", {
- code: "W114",
- line: this.line,
- character: this.char,
- data: [ "\\x-" ]
- }, checks, function () { return state.jsonMode; });
-
- char = String.fromCharCode(x);
- jump = 3;
- break;
- case "\\":
- case "\"":
- case "/":
- break;
- case "":
- allowNewLine = true;
- char = "";
- break;
- case "!":
- if (value.slice(value.length - 2) === "<") {
- break;
- }
-
- /*falls through */
- default:
- // Weird escaping.
- this.trigger("warning", {
- code: "W044",
- line: this.line,
- character: this.char
- });
- }
- }
-
- value += char;
- this.skip(jump);
- }
-
- this.skip();
- return {
- type: Token.StringLiteral,
- value: value,
- isUnclosed: false,
- quote: quote
- };
- },
-
- /*
- * Extract a regular expression out of the next sequence of
- * characters and/or lines or return 'null' if its not possible.
- *
- * This method is platform dependent: it accepts almost any
- * regular expression values but then tries to compile and run
- * them using system's RegExp object. This means that there are
- * rare edge cases where one JavaScript engine complains about
- * your regular expression while others don't.
- */
- scanRegExp: function () {
- var index = 0;
- var length = this.input.length;
- var char = this.peek();
- var value = char;
- var body = "";
- var flags = [];
- var malformed = false;
- var isCharSet = false;
- var terminated;
-
- var scanUnexpectedChars = function () {
- // Unexpected control character
- if (char < " ") {
- malformed = true;
- this.trigger("warning", {
- code: "W048",
- line: this.line,
- character: this.char
- });
- }
-
- // Unexpected escaped character
- if (char === "<") {
- malformed = true;
- this.trigger("warning", {
- code: "W049",
- line: this.line,
- character: this.char,
- data: [ char ]
- });
- }
- }.bind(this);
-
- // Regular expressions must start with '/'
- if (!this.prereg || char !== "/") {
- return null;
- }
-
- index += 1;
- terminated = false;
-
- // Try to get everything in between slashes. A couple of
- // cases aside (see scanUnexpectedChars) we don't really
- // care whether the resulting expression is valid or not.
- // We will check that later using the RegExp object.
-
- while (index < length) {
- char = this.peek(index);
- value += char;
- body += char;
-
- if (isCharSet) {
- if (char === "]") {
- if (this.peek(index - 1) !== "\\" || this.peek(index - 2) === "\\") {
- isCharSet = false;
- }
- }
-
- if (char === "\\") {
- index += 1;
- char = this.peek(index);
- body += char;
- value += char;
-
- scanUnexpectedChars();
- }
-
- index += 1;
- continue;
- }
-
- if (char === "\\") {
- index += 1;
- char = this.peek(index);
- body += char;
- value += char;
-
- scanUnexpectedChars();
-
- if (char === "/") {
- index += 1;
- continue;
- }
-
- if (char === "[") {
- index += 1;
- continue;
- }
- }
-
- if (char === "[") {
- isCharSet = true;
- index += 1;
- continue;
- }
-
- if (char === "/") {
- body = body.substr(0, body.length - 1);
- terminated = true;
- index += 1;
- break;
- }
-
- index += 1;
- }
-
- // A regular expression that was never closed is an
- // error from which we cannot recover.
-
- if (!terminated) {
- this.trigger("error", {
- code: "E015",
- line: this.line,
- character: this.from
- });
-
- return void this.trigger("fatal", {
- line: this.line,
- from: this.from
- });
- }
-
- // Parse flags (if any).
-
- while (index < length) {
- char = this.peek(index);
- if (!/[gim]/.test(char)) {
- break;
- }
- flags.push(char);
- value += char;
- index += 1;
- }
-
- // Check regular expression for correctness.
-
- try {
- new RegExp(body, flags.join(""));
- } catch (err) {
- malformed = true;
- this.trigger("error", {
- code: "E016",
- line: this.line,
- character: this.char,
- data: [ err.message ] // Platform dependent!
- });
- }
-
- return {
- type: Token.RegExp,
- value: value,
- flags: flags,
- isMalformed: malformed
- };
- },
-
- /*
- * Scan for any occurence of mixed tabs and spaces. If smarttabs option
- * is on, ignore tabs followed by spaces.
- *
- * Tabs followed by one space followed by a block comment are allowed.
- */
- scanMixedSpacesAndTabs: function () {
- var at, match;
-
- if (state.option.smarttabs) {
- // Negative look-behind for "//"
- match = this.input.match(/(\/\/|^\s?\*)? \t/);
- at = match && !match[1] ? 0 : -1;
- } else {
- at = this.input.search(/ \t|\t [^\*]/);
- }
-
- return at;
- },
-
- /*
- * Scan for characters that get silently deleted by one or more browsers.
- */
- scanUnsafeChars: function () {
- return this.input.search(reg.unsafeChars);
- },
-
- /*
- * Produce the next raw token or return 'null' if no tokens can be matched.
- * This method skips over all space characters.
- */
- next: function (checks) {
- this.from = this.char;
-
- // Move to the next non-space character.
- var start;
- if (/\s/.test(this.peek())) {
- start = this.char;
-
- while (/\s/.test(this.peek())) {
- this.from += 1;
- this.skip();
- }
-
- if (this.peek() === "") { // EOL
- if (!/^\s*$/.test(this.lines[this.line - 1]) && state.option.trailing) {
- this.trigger("warning", { code: "W102", line: this.line, character: start });
- }
- }
- }
-
- // Methods that work with multi-line structures and move the
- // character pointer.
-
- var match = this.scanComments() ||
- this.scanStringLiteral(checks);
-
- if (match) {
- return match;
- }
-
- // Methods that don't move the character pointer.
-
- match =
- this.scanRegExp() ||
- this.scanPunctuator() ||
- this.scanKeyword() ||
- this.scanIdentifier() ||
- this.scanNumericLiteral();
-
- if (match) {
- this.skip(match.value.length);
- return match;
- }
-
- // No token could be matched, give up.
-
- return null;
- },
-
- /*
- * Switch to the next line and reset all char pointers. Once
- * switched, this method also checks for mixed spaces and tabs
- * and other minor warnings.
- */
- nextLine: function () {
- var char;
-
- if (this.line >= this.lines.length) {
- return false;
- }
-
- this.input = this.lines[this.line];
- this.line += 1;
- this.char = 1;
- this.from = 1;
-
- char = this.scanMixedSpacesAndTabs();
- if (char >= 0) {
- this.trigger("warning", { code: "W099", line: this.line, character: char + 1 });
- }
-
- this.input = this.input.replace(/\t/g, state.tab);
- char = this.scanUnsafeChars();
-
- if (char >= 0) {
- this.trigger("warning", { code: "W100", line: this.line, character: char });
- }
-
- // If there is a limit on line length, warn when lines get too
- // long.
-
- if (state.option.maxlen && state.option.maxlen < this.input.length) {
- this.trigger("warning", { code: "W101", line: this.line, character: this.input.length });
- }
-
- return true;
- },
-
- /*
- * This is simply a synonym for nextLine() method with a friendlier
- * public name.
- */
- start: function () {
- this.nextLine();
- },
-
- /*
- * Produce the next token. This function is called by advance() to get
- * the next token. It retuns a token in a JSLint-compatible format.
- */
- token: function () {
- /*jshint loopfunc:true */
- var checks = asyncTrigger();
- var token;
-
-
- function isReserved(token, isProperty) {
- if (!token.reserved) {
- return false;
- }
-
- if (token.meta && token.meta.isFutureReservedWord) {
- // ES3 FutureReservedWord in an ES5 environment.
- if (state.option.inES5(true) && !token.meta.es5) {
- return false;
- }
-
- // Some ES5 FutureReservedWord identifiers are active only
- // within a strict mode environment.
- if (token.meta.strictOnly) {
- if (!state.option.strict && !state.directive["use strict"]) {
- return false;
- }
- }
-
- if (isProperty) {
- return false;
- }
- }
-
- return true;
- }
-
- // Produce a token object.
- var create = function (type, value, isProperty) {
- /*jshint validthis:true */
- var obj;
-
- if (type !== "(endline)" && type !== "(end)") {
- this.prereg = false;
- }
-
- if (type === "(punctuator)") {
- switch (value) {
- case ".":
- case ")":
- case "~":
- case "#":
- case "]":
- this.prereg = false;
- break;
- default:
- this.prereg = true;
- }
-
- obj = Object.create(state.syntax[value] || state.syntax["(error)"]);
- }
-
- if (type === "(identifier)") {
- if (value === "return" || value === "case" || value === "typeof") {
- this.prereg = true;
- }
-
- if (_.has(state.syntax, value)) {
- obj = Object.create(state.syntax[value] || state.syntax["(error)"]);
-
- // If this can't be a reserved keyword, reset the object.
- if (!isReserved(obj, isProperty && type === "(identifier)")) {
- obj = null;
- }
- }
- }
-
- if (!obj) {
- obj = Object.create(state.syntax[type]);
- }
-
- obj.identifier = (type === "(identifier)");
- obj.type = obj.type || type;
- obj.value = value;
- obj.line = this.line;
- obj.character = this.char;
- obj.from = this.from;
-
- if (isProperty && obj.identifier) {
- obj.isProperty = isProperty;
- }
-
- obj.check = checks.check;
-
- return obj;
- }.bind(this);
-
- for (;;) {
- if (!this.input.length) {
- return create(this.nextLine() ? "(endline)" : "(end)", "");
- }
-
- token = this.next(checks);
-
- if (!token) {
- if (this.input.length) {
- // Unexpected character.
- this.trigger("error", {
- code: "E024",
- line: this.line,
- character: this.char,
- data: [ this.peek() ]
- });
-
- this.input = "";
- }
-
- continue;
- }
-
- switch (token.type) {
- case Token.StringLiteral:
- this.triggerAsync("String", {
- line: this.line,
- char: this.char,
- from: this.from,
- value: token.value,
- quote: token.quote
- }, checks, function () { return true; });
-
- return create("(string)", token.value);
- case Token.Identifier:
- this.trigger("Identifier", {
- line: this.line,
- char: this.char,
- from: this.form,
- name: token.value,
- isProperty: state.tokens.curr.id === "."
- });
-
- /* falls through */
- case Token.Keyword:
- case Token.NullLiteral:
- case Token.BooleanLiteral:
- return create("(identifier)", token.value, state.tokens.curr.id === ".");
-
- case Token.NumericLiteral:
- if (token.isMalformed) {
- this.trigger("warning", {
- code: "W045",
- line: this.line,
- character: this.char,
- data: [ token.value ]
- });
- }
-
- this.triggerAsync("warning", {
- code: "W114",
- line: this.line,
- character: this.char,
- data: [ "0x-" ]
- }, checks, function () { return token.base === 16 && state.jsonMode; });
-
- this.triggerAsync("warning", {
- code: "W115",
- line: this.line,
- character: this.char
- }, checks, function () {
- return state.directive["use strict"] && token.base === 8;
- });
-
- this.trigger("Number", {
- line: this.line,
- char: this.char,
- from: this.from,
- value: token.value,
- base: token.base,
- isMalformed: token.malformed
- });
-
- return create("(number)", token.value);
-
- case Token.RegExp:
- return create("(regexp)", token.value);
-
- case Token.Comment:
- state.tokens.curr.comment = true;
-
- if (token.isSpecial) {
- return {
- value: token.value,
- body: token.body,
- type: token.commentType,
- isSpecial: token.isSpecial,
- line: this.line,
- character: this.char,
- from: this.from
- };
- }
-
- break;
-
- case "":
- break;
-
- default:
- return create("(punctuator)", token.value);
- }
- }
- }
-};
-
-exports.Lexer = Lexer;
-
-})()
-},{"events":2,"./reg.js":6,"./state.js":4,"underscore":11}],"jshint":[function(require,module,exports){
-module.exports=require('E/GbHF');
-},{}],"E/GbHF":[function(require,module,exports){
-(function(){/*!
- * JSHint, by JSHint Community.
- *
- * This file (and this file only) is licensed under the same slightly modified
- * MIT license that JSLint is. It stops evil-doers everywhere:
- *
- * Copyright (c) 2002 Douglas Crockford (www.JSLint.com)
- *
- * 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 shall be used for Good, not Evil.
- *
- * 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.
- *
- */
-
-/*jshint quotmark:double */
-/*global console:true */
-/*exported console */
-
-var _ = require("underscore");
-var events = require("events");
-var vars = require("../shared/vars.js");
-var messages = require("../shared/messages.js");
-var Lexer = require("./lex.js").Lexer;
-var reg = require("./reg.js");
-var state = require("./state.js").state;
-var style = require("./style.js");
-
-// We need this module here because environments such as IE and Rhino
-// don't necessarilly expose the 'console' API and browserify uses
-// it to log things. It's a sad state of affair, really.
-var console = require("console-browserify");
-
-// We build the application inside a function so that we produce only a singleton
-// variable. That function will be invoked immediately, and its return value is
-// the JSHINT function itself.
-
-var JSHINT = (function () {
- "use strict";
-
- var anonname, // The guessed name for anonymous functions.
- api, // Extension API
-
- // These are operators that should not be used with the ! operator.
- bang = {
- "<" : true,
- "<=" : true,
- "==" : true,
- "===": true,
- "!==": true,
- "!=" : true,
- ">" : true,
- ">=" : true,
- "+" : true,
- "-" : true,
- "*" : true,
- "/" : true,
- "%" : true
- },
-
- // These are the JSHint boolean options.
- boolOptions = {
- asi : true, // if automatic semicolon insertion should be tolerated
- bitwise : true, // if bitwise operators should not be allowed
- boss : true, // if advanced usage of assignments should be allowed
- browser : true, // if the standard browser globals should be predefined
- camelcase : true, // if identifiers should be required in camel case
- couch : true, // if CouchDB globals should be predefined
- curly : true, // if curly braces around all blocks should be required
- debug : true, // if debugger statements should be allowed
- devel : true, // if logging globals should be predefined (console, alert, etc.)
- dojo : true, // if Dojo Toolkit globals should be predefined
- eqeqeq : true, // if === should be required
- eqnull : true, // if == null comparisons should be tolerated
- es3 : true, // if ES3 syntax should be allowed
- es5 : true, // if ES5 syntax should be allowed (is now set per default)
- esnext : true, // if es.next specific syntax should be allowed
- moz : true, // if mozilla specific syntax should be allowed
- evil : true, // if eval should be allowed
- expr : true, // if ExpressionStatement should be allowed as Programs
- forin : true, // if for in statements must filter
- funcscope : true, // if only function scope should be used for scope tests
- gcl : true, // if JSHint should be compatible with Google Closure Linter
- globalstrict: true, // if global "use strict"; should be allowed (also enables 'strict')
- immed : true, // if immediate invocations must be wrapped in parens
- iterator : true, // if the `__iterator__` property should be allowed
- jquery : true, // if jQuery globals should be predefined
- lastsemic : true, // if semicolons may be ommitted for the trailing
- // statements inside of a one-line blocks.
- laxbreak : true, // if line breaks should not be checked
- laxcomma : true, // if line breaks should not be checked around commas
- loopfunc : true, // if functions should be allowed to be defined within
- // loops
- mootools : true, // if MooTools globals should be predefined
- multistr : true, // allow multiline strings
- newcap : true, // if constructor names must be capitalized
- noarg : true, // if arguments.caller and arguments.callee should be
- // disallowed
- node : true, // if the Node.js environment globals should be
- // predefined
- noempty : true, // if empty blocks should be disallowed
- nonew : true, // if using `new` for side-effects should be disallowed
- nonstandard : true, // if non-standard (but widely adopted) globals should
- // be predefined
- nomen : true, // if names should be checked
- onevar : true, // if only one var statement per function should be
- // allowed
- passfail : true, // if the scan should stop on first error
- phantom : true, // if PhantomJS symbols should be allowed
- plusplus : true, // if increment/decrement should not be allowed
- proto : true, // if the `__proto__` property should be allowed
- prototypejs : true, // if Prototype and Scriptaculous globals should be
- // predefined
- rhino : true, // if the Rhino environment globals should be predefined
- undef : true, // if variables should be declared before used
- scripturl : true, // if script-targeted URLs should be tolerated
- shadow : true, // if variable shadowing should be tolerated
- smarttabs : true, // if smarttabs should be tolerated
- // (http://www.emacswiki.org/emacs/SmartTabs)
- strict : true, // require the "use strict"; pragma
- sub : true, // if all forms of subscript notation are tolerated
- supernew : true, // if `new function () { ... };` and `new Object;`
- // should be tolerated
- trailing : true, // if trailing whitespace rules apply
- validthis : true, // if 'this' inside a non-constructor function is valid.
- // This is a function scoped option only.
- withstmt : true, // if with statements should be allowed
- white : true, // if strict whitespace rules apply
- worker : true, // if Web Worker script symbols should be allowed
- wsh : true, // if the Windows Scripting Host environment globals
- // should be predefined
- yui : true, // YUI variables should be predefined
-
- // Obsolete options
- onecase : true, // if one case switch statements should be allowed
- regexp : true, // if the . should not be allowed in regexp literals
- regexdash : true // if unescaped first/last dash (-) inside brackets
- // should be tolerated
- },
-
- // These are the JSHint options that can take any value
- // (we use this object to detect invalid options)
- valOptions = {
- maxlen : false,
- indent : false,
- maxerr : false,
- predef : false,
- quotmark : false, //'single'|'double'|true
- scope : false,
- maxstatements: false, // {int} max statements per function
- maxdepth : false, // {int} max nested block depth per function
- maxparams : false, // {int} max params per function
- maxcomplexity: false, // {int} max cyclomatic complexity per function
- unused : true, // warn if variables are unused. Available options:
- // false - don't check for unused variables
- // true - "vars" + check last function param
- // "vars" - skip checking unused function params
- // "strict" - "vars" + check all function params
- latedef : false // warn if the variable is used before its definition
- // false - don't emit any warnings
- // true - warn if any variable is used before its definition
- // "nofunc" - warn for any variable but function declarations
- },
-
- // These are JSHint boolean options which are shared with JSLint
- // where the definition in JSHint is opposite JSLint
- invertedOptions = {
- bitwise : true,
- forin : true,
- newcap : true,
- nomen : true,
- plusplus: true,
- regexp : true,
- undef : true,
- white : true,
-
- // Inverted and renamed, use JSHint name here
- eqeqeq : true,
- onevar : true,
- strict : true
- },
-
- // These are JSHint boolean options which are shared with JSLint
- // where the name has been changed but the effect is unchanged
- renamedOptions = {
- eqeq : "eqeqeq",
- vars : "onevar",
- windows: "wsh",
- sloppy : "strict"
- },
-
- declared, // Globals that were declared using /*global ... */ syntax.
- exported, // Variables that are used outside of the current file.
-
- functionicity = [
- "closure", "exception", "global", "label",
- "outer", "unused", "var"
- ],
-
- funct, // The current function
- functions, // All of the functions
-
- global, // The global scope
- implied, // Implied globals
- inblock,
- indent,
- lookahead,
- lex,
- member,
- membersOnly,
- noreach,
- predefined, // Global variables defined by option
-
- scope, // The current scope
- stack,
- unuseds,
- urls,
- warnings,
-
- extraModules = [],
- emitter = new events.EventEmitter();
-
- function checkOption(name, t) {
- name = name.trim();
-
- if (/^[+-]W\d{3}$/g.test(name)) {
- return true;
- }
-
- if (valOptions[name] === undefined && boolOptions[name] === undefined) {
- if (t.type !== "jslint") {
- error("E001", t, name);
- return false;
- }
- }
-
- return true;
- }
-
- function isString(obj) {
- return Object.prototype.toString.call(obj) === "[object String]";
- }
-
- function isIdentifier(tkn, value) {
- if (!tkn)
- return false;
-
- if (!tkn.identifier || tkn.value !== value)
- return false;
-
- return true;
- }
-
- function isReserved(token) {
- if (!token.reserved) {
- return false;
- }
-
- if (token.meta && token.meta.isFutureReservedWord) {
- // ES3 FutureReservedWord in an ES5 environment.
- if (state.option.inES5(true) && !token.meta.es5) {
- return false;
- }
-
- // Some ES5 FutureReservedWord identifiers are active only
- // within a strict mode environment.
- if (token.meta.strictOnly) {
- if (!state.option.strict && !state.directive["use strict"]) {
- return false;
- }
- }
-
- if (token.isProperty) {
- return false;
- }
- }
-
- return true;
- }
-
- function supplant(str, data) {
- return str.replace(/\{([^{}]*)\}/g, function (a, b) {
- var r = data[b];
- return typeof r === "string" || typeof r === "number" ? r : a;
- });
- }
-
- function combine(t, o) {
- var n;
- for (n in o) {
- if (_.has(o, n) && !_.has(JSHINT.blacklist, n)) {
- t[n] = o[n];
- }
- }
- }
-
- function updatePredefined() {
- Object.keys(JSHINT.blacklist).forEach(function (key) {
- delete predefined[key];
- });
- }
-
- function assume() {
- if (state.option.es5) {
- warning("I003");
- }
- if (state.option.couch) {
- combine(predefined, vars.couch);
- }
-
- if (state.option.rhino) {
- combine(predefined, vars.rhino);
- }
-
- if (state.option.phantom) {
- combine(predefined, vars.phantom);
- }
-
- if (state.option.prototypejs) {
- combine(predefined, vars.prototypejs);
- }
-
- if (state.option.node) {
- combine(predefined, vars.node);
- }
-
- if (state.option.devel) {
- combine(predefined, vars.devel);
- }
-
- if (state.option.dojo) {
- combine(predefined, vars.dojo);
- }
-
- if (state.option.browser) {
- combine(predefined, vars.browser);
- }
-
- if (state.option.nonstandard) {
- combine(predefined, vars.nonstandard);
- }
-
- if (state.option.jquery) {
- combine(predefined, vars.jquery);
- }
-
- if (state.option.mootools) {
- combine(predefined, vars.mootools);
- }
-
- if (state.option.worker) {
- combine(predefined, vars.worker);
- }
-
- if (state.option.wsh) {
- combine(predefined, vars.wsh);
- }
-
- if (state.option.globalstrict && state.option.strict !== false) {
- state.option.strict = true;
- }
-
- if (state.option.yui) {
- combine(predefined, vars.yui);
- }
-
- // Let's assume that chronologically ES3 < ES5 < ES6/ESNext < Moz
-
- state.option.inMoz = function (strict) {
- if (strict) {
- return state.option.moz && !state.option.esnext;
- }
- return state.option.moz;
- };
-
- state.option.inESNext = function (strict) {
- if (strict) {
- return !state.option.moz && state.option.esnext;
- }
- return state.option.moz || state.option.esnext;
- };
-
- state.option.inES5 = function (/* strict */) {
- return !state.option.es3;
- };
-
- state.option.inES3 = function (strict) {
- if (strict) {
- return !state.option.moz && !state.option.esnext && state.option.es3;
- }
- return state.option.es3;
- };
- }
-
- // Produce an error warning.
- function quit(code, line, chr) {
- var percentage = Math.floor((line / state.lines.length) * 100);
- var message = messages.errors[code].desc;
-
- throw {
- name: "JSHintError",
- line: line,
- character: chr,
- message: message + " (" + percentage + "% scanned).",
- raw: message
- };
- }
-
- function isundef(scope, code, token, a) {
- return JSHINT.undefs.push([scope, code, token, a]);
- }
-
- function warning(code, t, a, b, c, d) {
- var ch, l, w, msg;
-
- if (/^W\d{3}$/.test(code)) {
- if (state.ignored[code])
- return;
-
- msg = messages.warnings[code];
- } else if (/E\d{3}/.test(code)) {
- msg = messages.errors[code];
- } else if (/I\d{3}/.test(code)) {
- msg = messages.info[code];
- }
-
- t = t || state.tokens.next;
- if (t.id === "(end)") { // `~
- t = state.tokens.curr;
- }
-
- l = t.line || 0;
- ch = t.from || 0;
-
- w = {
- id: "(error)",
- raw: msg.desc,
- code: msg.code,
- evidence: state.lines[l - 1] || "",
- line: l,
- character: ch,
- scope: JSHINT.scope,
- a: a,
- b: b,
- c: c,
- d: d
- };
-
- w.reason = supplant(msg.desc, w);
- JSHINT.errors.push(w);
-
- if (state.option.passfail) {
- quit("E042", l, ch);
- }
-
- warnings += 1;
- if (warnings >= state.option.maxerr) {
- quit("E043", l, ch);
- }
-
- return w;
- }
-
- function warningAt(m, l, ch, a, b, c, d) {
- return warning(m, {
- line: l,
- from: ch
- }, a, b, c, d);
- }
-
- function error(m, t, a, b, c, d) {
- warning(m, t, a, b, c, d);
- }
-
- function errorAt(m, l, ch, a, b, c, d) {
- return error(m, {
- line: l,
- from: ch
- }, a, b, c, d);
- }
-
- // Tracking of "internal" scripts, like eval containing a static string
- function addInternalSrc(elem, src) {
- var i;
- i = {
- id: "(internal)",
- elem: elem,
- value: src
- };
- JSHINT.internals.push(i);
- return i;
- }
-
- function addlabel(t, type, tkn, islet) {
- // Define t in the current function in the current scope.
- if (type === "exception") {
- if (_.has(funct["(context)"], t)) {
- if (funct[t] !== true && !state.option.node) {
- warning("W002", state.tokens.next, t);
- }
- }
- }
-
- if (_.has(funct, t) && !funct["(global)"]) {
- if (funct[t] === true) {
- if (state.option.latedef) {
- if ((state.option.latedef === true && _.contains([funct[t], type], "unction")) ||
- !_.contains([funct[t], type], "unction")) {
- warning("W003", state.tokens.next, t);
- }
- }
- } else {
- if (!state.option.shadow && type !== "exception" ||
- (funct["(blockscope)"].getlabel(t))) {
- warning("W004", state.tokens.next, t);
- }
- }
- }
-
- // a double definition of a let variable in same block throws a TypeError
- //if (funct["(blockscope)"] && funct["(blockscope)"].current.has(t)) {
- // error("E044", state.tokens.next, t);
- //}
-
- // if the identifier is from a let, adds it only to the current blockscope
- if (islet) {
- funct["(blockscope)"].current.add(t, type, state.tokens.curr);
- } else {
-
- funct[t] = type;
-
- if (tkn) {
- funct["(tokens)"][t] = tkn;
- }
-
- if (funct["(global)"]) {
- global[t] = funct;
- if (_.has(implied, t)) {
- if (state.option.latedef) {
- if ((state.option.latedef === true && _.contains([funct[t], type], "unction")) ||
- !_.contains([funct[t], type], "unction")) {
- warning("W003", state.tokens.next, t);
- }
- }
-
- delete implied[t];
- }
- } else {
- scope[t] = funct;
- }
- }
- }
-
- function doOption() {
- var nt = state.tokens.next;
- var body = nt.body.split(",").map(function (s) { return s.trim(); });
- var predef = {};
-
- if (nt.type === "globals") {
- body.forEach(function (g) {
- g = g.split(":");
- var key = g[0];
- var val = g[1];
-
- if (key.charAt(0) === "-") {
- key = key.slice(1);
- val = false;
-
- JSHINT.blacklist[key] = key;
- updatePredefined();
- } else {
- predef[key] = (val === "true");
- }
- });
-
- combine(predefined, predef);
-
- for (var key in predef) {
- if (_.has(predef, key)) {
- declared[key] = nt;
- }
- }
- }
-
- if (nt.type === "exported") {
- body.forEach(function (e) {
- exported[e] = true;
- });
- }
-
- if (nt.type === "members") {
- membersOnly = membersOnly || {};
-
- body.forEach(function (m) {
- var ch1 = m.charAt(0);
- var ch2 = m.charAt(m.length - 1);
-
- if (ch1 === ch2 && (ch1 === "\"" || ch1 === "'")) {
- m = m
- .substr(1, m.length - 2)
- .replace("\\b", "\b")
- .replace("\\t", "\t")
- .replace("\\n", "\n")
- .replace("\\v", "\v")
- .replace("\\f", "\f")
- .replace("\\r", "\r")
- .replace("\\\\", "\\")
- .replace("\\\"", "\"");
- }
-
- membersOnly[m] = false;
- });
- }
-
- var numvals = [
- "maxstatements",
- "maxparams",
- "maxdepth",
- "maxcomplexity",
- "maxerr",
- "maxlen",
- "indent"
- ];
-
- if (nt.type === "jshint" || nt.type === "jslint") {
- body.forEach(function (g) {
- g = g.split(":");
- var key = (g[0] || "").trim();
- var val = (g[1] || "").trim();
-
- if (!checkOption(key, nt)) {
- return;
- }
-
- if (numvals.indexOf(key) >= 0) {
-
- // GH988 - numeric options can be disabled by setting them to `false`
- if (val !== "false") {
- val = +val;
-
- if (typeof val !== "number" || !isFinite(val) || val <= 0 || Math.floor(val) !== val) {
- error("E032", nt, g[1].trim());
- return;
- }
-
- if (key === "indent") {
- state.option["(explicitIndent)"] = true;
- }
- state.option[key] = val;
- } else {
- if (key === "indent") {
- state.option["(explicitIndent)"] = false;
- } else {
- state.option[key] = false;
- }
- }
-
- return;
- }
-
- if (key === "validthis") {
- // `validthis` is valid only within a function scope.
- if (funct["(global)"]) {
- error("E009");
- } else {
- if (val === "true" || val === "false") {
- state.option.validthis = (val === "true");
- } else {
- error("E002", nt);
- }
- }
- return;
- }
-
- if (key === "quotmark") {
- switch (val) {
- case "true":
- case "false":
- state.option.quotmark = (val === "true");
- break;
- case "double":
- case "single":
- state.option.quotmark = val;
- break;
- default:
- error("E002", nt);
- }
- return;
- }
-
- if (key === "unused") {
- switch (val) {
- case "true":
- state.option.unused = true;
- break;
- case "false":
- state.option.unused = false;
- break;
- case "vars":
- case "strict":
- state.option.unused = val;
- break;
- default:
- error("E002", nt);
- }
- return;
- }
-
- if (key === "latedef") {
- switch (val) {
- case "true":
- state.option.latedef = true;
- break;
- case "false":
- state.option.latedef = false;
- break;
- case "nofunc":
- state.option.latedef = "nofunc";
- break;
- default:
- error("E002", nt);
- }
- return;
- }
-
- var match = /^([+-])(W\d{3})$/g.exec(key);
- if (match) {
- // ignore for -W..., unignore for +W...
- state.ignored[match[2]] = (match[1] === "-");
- return;
- }
-
- var tn;
- if (val === "true" || val === "false") {
- if (nt.type === "jslint") {
- tn = renamedOptions[key] || key;
- state.option[tn] = (val === "true");
-
- if (invertedOptions[tn] !== undefined) {
- state.option[tn] = !state.option[tn];
- }
- } else {
- state.option[key] = (val === "true");
- }
-
- if (key === "newcap") {
- state.option["(explicitNewcap)"] = true;
- }
- return;
- }
-
- error("E002", nt);
- });
-
- assume();
- }
- }
-
- // We need a peek function. If it has an argument, it peeks that much farther
- // ahead. It is used to distinguish
- // for ( var i in ...
- // from
- // for ( var i = ...
-
- function peek(p) {
- var i = p || 0, j = 0, t;
-
- while (j <= i) {
- t = lookahead[j];
- if (!t) {
- t = lookahead[j] = lex.token();
- }
- j += 1;
- }
- return t;
- }
-
- // Produce the next token. It looks for programming errors.
-
- function advance(id, t) {
- switch (state.tokens.curr.id) {
- case "(number)":
- if (state.tokens.next.id === ".") {
- warning("W005", state.tokens.curr);
- }
- break;
- case "-":
- if (state.tokens.next.id === "-" || state.tokens.next.id === "--") {
- warning("W006");
- }
- break;
- case "+":
- if (state.tokens.next.id === "+" || state.tokens.next.id === "++") {
- warning("W007");
- }
- break;
- }
-
- if (state.tokens.curr.type === "(string)" || state.tokens.curr.identifier) {
- anonname = state.tokens.curr.value;
- }
-
- if (id && state.tokens.next.id !== id) {
- if (t) {
- if (state.tokens.next.id === "(end)") {
- error("E019", t, t.id);
- } else {
- error("E020", state.tokens.next, id, t.id, t.line, state.tokens.next.value);
- }
- } else if (state.tokens.next.type !== "(identifier)" || state.tokens.next.value !== id) {
- warning("W116", state.tokens.next, id, state.tokens.next.value);
- }
- }
-
- state.tokens.prev = state.tokens.curr;
- state.tokens.curr = state.tokens.next;
- for (;;) {
- state.tokens.next = lookahead.shift() || lex.token();
-
- if (!state.tokens.next) { // No more tokens left, give up
- quit("E041", state.tokens.curr.line);
- }
-
- if (state.tokens.next.id === "(end)" || state.tokens.next.id === "(error)") {
- return;
- }
-
- if (state.tokens.next.check) {
- state.tokens.next.check();
- }
-
- if (state.tokens.next.isSpecial) {
- doOption();
- } else {
- if (state.tokens.next.id !== "(endline)") {
- break;
- }
- }
- }
- }
-
- // This is the heart of JSHINT, the Pratt parser. In addition to parsing, it
- // is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is
- // like .nud except that it is only used on the first token of a statement.
- // Having .fud makes it much easier to define statement-oriented languages like
- // JavaScript. I retained Pratt's nomenclature.
-
- // .nud Null denotation
- // .fud First null denotation
- // .led Left denotation
- // lbp Left binding power
- // rbp Right binding power
-
- // They are elements of the parsing method called Top Down Operator Precedence.
-
- function expression(rbp, initial) {
- var left, isArray = false, isObject = false, isLetExpr = false;
-
- // if current expression is a let expression
- if (!initial && state.tokens.next.value === "let" && peek(0).value === "(") {
- if (!state.option.inMoz(true)) {
- warning("W118", state.tokens.next, "let expressions");
- }
- isLetExpr = true;
- // create a new block scope we use only for the current expression
- funct["(blockscope)"].stack();
- advance("let");
- advance("(");
- state.syntax["let"].fud.call(state.syntax["let"].fud, false);
- advance(")");
- }
-
- if (state.tokens.next.id === "(end)")
- error("E006", state.tokens.curr);
-
- advance();
-
- if (initial) {
- anonname = "anonymous";
- funct["(verb)"] = state.tokens.curr.value;
- }
-
- if (initial === true && state.tokens.curr.fud) {
- left = state.tokens.curr.fud();
- } else {
- if (state.tokens.curr.nud) {
- left = state.tokens.curr.nud();
- } else {
- error("E030", state.tokens.curr, state.tokens.curr.id);
- }
-
- var end_of_expr = state.tokens.next.identifier &&
- !state.tokens.curr.led &&
- state.tokens.curr.line !== state.tokens.next.line;
- while (rbp < state.tokens.next.lbp && !end_of_expr) {
- isArray = state.tokens.curr.value === "Array";
- isObject = state.tokens.curr.value === "Object";
-
- // #527, new Foo.Array(), Foo.Array(), new Foo.Object(), Foo.Object()
- // Line breaks in IfStatement heads exist to satisfy the checkJSHint
- // "Line too long." error.
- if (left && (left.value || (left.first && left.first.value))) {
- // If the left.value is not "new", or the left.first.value is a "."
- // then safely assume that this is not "new Array()" and possibly
- // not "new Object()"...
- if (left.value !== "new" ||
- (left.first && left.first.value && left.first.value === ".")) {
- isArray = false;
- // ...In the case of Object, if the left.value and state.tokens.curr.value
- // are not equal, then safely assume that this not "new Object()"
- if (left.value !== state.tokens.curr.value) {
- isObject = false;
- }
- }
- }
-
- advance();
-
- if (isArray && state.tokens.curr.id === "(" && state.tokens.next.id === ")") {
- warning("W009", state.tokens.curr);
- }
-
- if (isObject && state.tokens.curr.id === "(" && state.tokens.next.id === ")") {
- warning("W010", state.tokens.curr);
- }
-
- if (left && state.tokens.curr.led) {
- left = state.tokens.curr.led(left);
- } else {
- error("E033", state.tokens.curr, state.tokens.curr.id);
- }
- }
- }
- if (isLetExpr) {
- funct["(blockscope)"].unstack();
- }
- return left;
- }
-
-
-// Functions for conformance of style.
-
- function adjacent(left, right) {
- left = left || state.tokens.curr;
- right = right || state.tokens.next;
- if (state.option.white) {
- if (left.character !== right.from && left.line === right.line) {
- left.from += (left.character - left.from);
- warning("W011", left, left.value);
- }
- }
- }
-
- function nobreak(left, right) {
- left = left || state.tokens.curr;
- right = right || state.tokens.next;
- if (state.option.white && (left.character !== right.from || left.line !== right.line)) {
- warning("W012", right, right.value);
- }
- }
-
- function nospace(left, right) {
- left = left || state.tokens.curr;
- right = right || state.tokens.next;
- if (state.option.white && !left.comment) {
- if (left.line === right.line) {
- adjacent(left, right);
- }
- }
- }
-
- function nonadjacent(left, right) {
- if (state.option.white) {
- left = left || state.tokens.curr;
- right = right || state.tokens.next;
-
- if (left.value === ";" && right.value === ";") {
- return;
- }
-
- if (left.line === right.line && left.character === right.from) {
- left.from += (left.character - left.from);
- warning("W013", left, left.value);
- }
- }
- }
-
- function nobreaknonadjacent(left, right) {
- left = left || state.tokens.curr;
- right = right || state.tokens.next;
- if (!state.option.laxbreak && left.line !== right.line) {
- warning("W014", right, right.id);
- } else if (state.option.white) {
- left = left || state.tokens.curr;
- right = right || state.tokens.next;
- if (left.character === right.from) {
- left.from += (left.character - left.from);
- warning("W013", left, left.value);
- }
- }
- }
-
- function indentation(bias) {
- if (!state.option.white && !state.option["(explicitIndent)"]) {
- return;
- }
-
- if (state.tokens.next.id === "(end)") {
- return;
- }
-
- var i = indent + (bias || 0);
- if (state.tokens.next.from !== i) {
- warning("W015", state.tokens.next, state.tokens.next.value, i, state.tokens.next.from);
- }
- }
-
- function nolinebreak(t) {
- t = t || state.tokens.curr;
- if (t.line !== state.tokens.next.line) {
- warning("E022", t, t.value);
- }
- }
-
-
- function comma(opts) {
- opts = opts || {};
-
- if (!opts.peek) {
- if (state.tokens.curr.line !== state.tokens.next.line) {
- if (!state.option.laxcomma) {
- if (comma.first) {
- warning("I001");
- comma.first = false;
- }
- warning("W014", state.tokens.curr, state.tokens.next.value);
- }
- } else if (!state.tokens.curr.comment &&
- state.tokens.curr.character !== state.tokens.next.from && state.option.white) {
- state.tokens.curr.from += (state.tokens.curr.character - state.tokens.curr.from);
- warning("W011", state.tokens.curr, state.tokens.curr.value);
- }
-
- advance(",");
- }
-
- // TODO: This is a temporary solution to fight against false-positives in
- // arrays and objects with trailing commas (see GH-363). The best solution
- // would be to extract all whitespace rules out of parser.
-
- if (state.tokens.next.value !== "]" && state.tokens.next.value !== "}") {
- nonadjacent(state.tokens.curr, state.tokens.next);
- }
-
- if (state.tokens.next.identifier && !(opts.property && state.option.inES5())) {
- // Keywords that cannot follow a comma operator.
- switch (state.tokens.next.value) {
- case "break":
- case "case":
- case "catch":
- case "continue":
- case "default":
- case "do":
- case "else":
- case "finally":
- case "for":
- case "if":
- case "in":
- case "instanceof":
- case "return":
- case "yield":
- case "switch":
- case "throw":
- case "try":
- case "var":
- case "let":
- case "while":
- case "with":
- error("E024", state.tokens.next, state.tokens.next.value);
- return false;
- }
- }
-
- if (state.tokens.next.type === "(punctuator)") {
- switch (state.tokens.next.value) {
- case "}":
- case "]":
- case ",":
- if (opts.allowTrailing) {
- return true;
- }
-
- /* falls through */
- case ")":
- error("E024", state.tokens.next, state.tokens.next.value);
- return false;
- }
- }
- return true;
- }
-
- // Functional constructors for making the symbols that will be inherited by
- // tokens.
-
- function symbol(s, p) {
- var x = state.syntax[s];
- if (!x || typeof x !== "object") {
- state.syntax[s] = x = {
- id: s,
- lbp: p,
- value: s
- };
- }
- return x;
- }
-
- function delim(s) {
- return symbol(s, 0);
- }
-
- function stmt(s, f) {
- var x = delim(s);
- x.identifier = x.reserved = true;
- x.fud = f;
- return x;
- }
-
- function blockstmt(s, f) {
- var x = stmt(s, f);
- x.block = true;
- return x;
- }
-
- function reserveName(x) {
- var c = x.id.charAt(0);
- if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z")) {
- x.identifier = x.reserved = true;
- }
- return x;
- }
-
- function prefix(s, f) {
- var x = symbol(s, 150);
- reserveName(x);
- x.nud = (typeof f === "function") ? f : function () {
- this.right = expression(150);
- this.arity = "unary";
- if (this.id === "++" || this.id === "--") {
- if (state.option.plusplus) {
- warning("W016", this, this.id);
- } else if ((!this.right.identifier || isReserved(this.right)) &&
- this.right.id !== "." && this.right.id !== "[") {
- warning("W017", this);
- }
- }
- return this;
- };
- return x;
- }
-
- function type(s, f) {
- var x = delim(s);
- x.type = s;
- x.nud = f;
- return x;
- }
-
- function reserve(name, func) {
- var x = type(name, func);
- x.identifier = true;
- x.reserved = true;
- return x;
- }
-
- function FutureReservedWord(name, meta) {
- var x = type(name, (meta && meta.nud) || function () {
- return this;
- });
-
- meta = meta || {};
- meta.isFutureReservedWord = true;
-
- x.value = name;
- x.identifier = true;
- x.reserved = true;
- x.meta = meta;
-
- return x;
- }
-
- function reservevar(s, v) {
- return reserve(s, function () {
- if (typeof v === "function") {
- v(this);
- }
- return this;
- });
- }
-
- function infix(s, f, p, w) {
- var x = symbol(s, p);
- reserveName(x);
- x.led = function (left) {
- if (!w) {
- nobreaknonadjacent(state.tokens.prev, state.tokens.curr);
- nonadjacent(state.tokens.curr, state.tokens.next);
- }
- if (s === "in" && left.id === "!") {
- warning("W018", left, "!");
- }
- if (typeof f === "function") {
- return f(left, this);
- } else {
- this.left = left;
- this.right = expression(p);
- return this;
- }
- };
- return x;
- }
-
-
- function application(s) {
- var x = symbol(s, 42);
-
- x.led = function (left) {
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.curr, "arrow function syntax (=>)");
- }
-
- nobreaknonadjacent(state.tokens.prev, state.tokens.curr);
- nonadjacent(state.tokens.curr, state.tokens.next);
-
- this.left = left;
- this.right = doFunction(undefined, undefined, false, left);
- return this;
- };
- return x;
- }
-
- function relation(s, f) {
- var x = symbol(s, 100);
-
- x.led = function (left) {
- nobreaknonadjacent(state.tokens.prev, state.tokens.curr);
- nonadjacent(state.tokens.curr, state.tokens.next);
- var right = expression(100);
-
- if (isIdentifier(left, "NaN") || isIdentifier(right, "NaN")) {
- warning("W019", this);
- } else if (f) {
- f.apply(this, [left, right]);
- }
-
- if (!left || !right) {
- quit("E041", state.tokens.curr.line);
- }
-
- if (left.id === "!") {
- warning("W018", left, "!");
- }
-
- if (right.id === "!") {
- warning("W018", right, "!");
- }
-
- this.left = left;
- this.right = right;
- return this;
- };
- return x;
- }
-
- function isPoorRelation(node) {
- return node &&
- ((node.type === "(number)" && +node.value === 0) ||
- (node.type === "(string)" && node.value === "") ||
- (node.type === "null" && !state.option.eqnull) ||
- node.type === "true" ||
- node.type === "false" ||
- node.type === "undefined");
- }
-
- function assignop(s) {
- symbol(s, 20).exps = true;
-
- return infix(s, function (left, that) {
- that.left = left;
-
- if (left) {
- if (predefined[left.value] === false &&
- scope[left.value]["(global)"] === true) {
- warning("W020", left);
- } else if (left["function"]) {
- warning("W021", left, left.value);
- }
-
- if (funct[left.value] === "const") {
- error("E013", left, left.value);
- }
-
- if (left.id === ".") {
- if (!left.left) {
- warning("E031", that);
- } else if (left.left.value === "arguments" && !state.directive["use strict"]) {
- warning("E031", that);
- }
-
- that.right = expression(19);
- return that;
- } else if (left.id === "[") {
- if (state.tokens.curr.left.first) {
- state.tokens.curr.left.first.forEach(function (t) {
- if (funct[t.value] === "const") {
- error("E013", t, t.value);
- }
- });
- } else if (!left.left) {
- warning("E031", that);
- } else if (left.left.value === "arguments" && !state.directive["use strict"]) {
- warning("E031", that);
- }
- that.right = expression(19);
- return that;
- } else if (left.identifier && !isReserved(left)) {
- if (funct[left.value] === "exception") {
- warning("W022", left);
- }
- that.right = expression(19);
- return that;
- }
-
- if (left === state.syntax["function"]) {
- warning("W023", state.tokens.curr);
- }
- }
-
- error("E031", that);
- }, 20);
- }
-
-
- function bitwise(s, f, p) {
- var x = symbol(s, p);
- reserveName(x);
- x.led = (typeof f === "function") ? f : function (left) {
- if (state.option.bitwise) {
- warning("W016", this, this.id);
- }
- this.left = left;
- this.right = expression(p);
- return this;
- };
- return x;
- }
-
-
- function bitwiseassignop(s) {
- symbol(s, 20).exps = true;
- return infix(s, function (left, that) {
- if (state.option.bitwise) {
- warning("W016", that, that.id);
- }
- nonadjacent(state.tokens.prev, state.tokens.curr);
- nonadjacent(state.tokens.curr, state.tokens.next);
- if (left) {
- if (left.id === "." || left.id === "[" ||
- (left.identifier && !isReserved(left))) {
- expression(19);
- return that;
- }
- if (left === state.syntax["function"]) {
- warning("W023", state.tokens.curr);
- }
- return that;
- }
- error("E031", that);
- }, 20);
- }
-
-
- function suffix(s) {
- var x = symbol(s, 150);
-
- x.led = function (left) {
- if (state.option.plusplus) {
- warning("W016", this, this.id);
- } else if ((!left.identifier || isReserved(left)) && left.id !== "." && left.id !== "[") {
- warning("W017", this);
- }
-
- this.left = left;
- return this;
- };
- return x;
- }
-
- // fnparam means that this identifier is being defined as a function
- // argument (see identifier())
- // prop means that this identifier is that of an object property
-
- function optionalidentifier(fnparam, prop) {
- if (!state.tokens.next.identifier) {
- return;
- }
-
- advance();
-
- var curr = state.tokens.curr;
- var meta = curr.meta || {};
- var val = state.tokens.curr.value;
-
- if (!isReserved(curr)) {
- return val;
- }
-
- if (prop) {
- if (state.option.inES5() || meta.isFutureReservedWord) {
- return val;
- }
- }
-
- if (fnparam && val === "undefined") {
- return val;
- }
-
- // Display an info message about reserved words as properties
- // and ES5 but do it only once.
- if (prop && !api.getCache("displayed:I002")) {
- api.setCache("displayed:I002", true);
- warning("I002");
- }
-
- warning("W024", state.tokens.curr, state.tokens.curr.id);
- return val;
- }
-
- // fnparam means that this identifier is being defined as a function
- // argument
- // prop means that this identifier is that of an object property
- function identifier(fnparam, prop) {
- var i = optionalidentifier(fnparam, prop);
- if (i) {
- return i;
- }
- if (state.tokens.curr.id === "function" && state.tokens.next.id === "(") {
- warning("W025");
- } else {
- error("E030", state.tokens.next, state.tokens.next.value);
- }
- }
-
-
- function reachable(s) {
- var i = 0, t;
- if (state.tokens.next.id !== ";" || noreach) {
- return;
- }
- for (;;) {
- t = peek(i);
- if (t.reach) {
- return;
- }
- if (t.id !== "(endline)") {
- if (t.id === "function") {
- if (!state.option.latedef) {
- break;
- }
-
- warning("W026", t);
- break;
- }
-
- warning("W027", t, t.value, s);
- break;
- }
- i += 1;
- }
- }
-
-
- function statement(noindent) {
- var values;
- var i = indent, r, s = scope, t = state.tokens.next;
-
- if (t.id === ";") {
- advance(";");
- return;
- }
-
- // Is this a labelled statement?
- var res = isReserved(t);
-
- // We're being more tolerant here: if someone uses
- // a FutureReservedWord as a label, we warn but proceed
- // anyway.
-
- if (res && t.meta && t.meta.isFutureReservedWord && peek().id === ":") {
- warning("W024", t, t.id);
- res = false;
- }
-
- // detect a destructuring assignment
- if (_.has(["[", "{"], t.value)) {
- if (lookupBlockType().isDestAssign) {
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.curr, "destructuring expression");
- }
- values = destructuringExpression();
- values.forEach(function (tok) {
- isundef(funct, "W117", tok.token, tok.id);
- });
- advance("=");
- destructuringExpressionMatch(values, expression(5, true));
- advance(";");
- return;
- }
- }
- if (t.identifier && !res && peek().id === ":") {
- advance();
- advance(":");
- scope = Object.create(s);
- addlabel(t.value, "label");
-
- if (!state.tokens.next.labelled && state.tokens.next.value !== "{") {
- warning("W028", state.tokens.next, t.value, state.tokens.next.value);
- }
-
- state.tokens.next.label = t.value;
- t = state.tokens.next;
- }
-
- // Is it a lonely block?
-
- if (t.id === "{") {
- // Is it a switch case block?
- //
- // switch (foo) {
- // case bar: { <= here.
- // ...
- // }
- // }
- var iscase = (funct["(verb)"] === "case" && state.tokens.curr.value === ":");
- block(true, true, false, false, iscase);
- return;
- }
-
- // Parse the statement.
-
- if (!noindent) {
- indentation();
- }
- r = expression(0, true);
-
- // Look for the final semicolon.
-
- if (!t.block) {
- if (!state.option.expr && (!r || !r.exps)) {
- warning("W030", state.tokens.curr);
- } else if (state.option.nonew && r && r.left && r.id === "(" && r.left.id === "new") {
- warning("W031", t);
- }
-
- if (state.tokens.next.id !== ";") {
- if (!state.option.asi) {
- // If this is the last statement in a block that ends on
- // the same line *and* option lastsemic is on, ignore the warning.
- // Otherwise, complain about missing semicolon.
- if (!state.option.lastsemic || state.tokens.next.id !== "}" ||
- state.tokens.next.line !== state.tokens.curr.line) {
- warningAt("W033", state.tokens.curr.line, state.tokens.curr.character);
- }
- }
- } else {
- adjacent(state.tokens.curr, state.tokens.next);
- advance(";");
- nonadjacent(state.tokens.curr, state.tokens.next);
- }
- }
-
- // Restore the indentation.
-
- indent = i;
- scope = s;
- return r;
- }
-
-
- function statements(startLine) {
- var a = [], p;
-
- while (!state.tokens.next.reach && state.tokens.next.id !== "(end)") {
- if (state.tokens.next.id === ";") {
- p = peek();
-
- if (!p || (p.id !== "(" && p.id !== "[")) {
- warning("W032");
- }
-
- advance(";");
- } else {
- a.push(statement(startLine === state.tokens.next.line));
- }
- }
- return a;
- }
-
-
- /*
- * read all directives
- * recognizes a simple form of asi, but always
- * warns, if it is used
- */
- function directives() {
- var i, p, pn;
-
- for (;;) {
- if (state.tokens.next.id === "(string)") {
- p = peek(0);
- if (p.id === "(endline)") {
- i = 1;
- do {
- pn = peek(i);
- i = i + 1;
- } while (pn.id === "(endline)");
-
- if (pn.id !== ";") {
- if (pn.id !== "(string)" && pn.id !== "(number)" &&
- pn.id !== "(regexp)" && pn.identifier !== true &&
- pn.id !== "}") {
- break;
- }
- warning("W033", state.tokens.next);
- } else {
- p = pn;
- }
- } else if (p.id === "}") {
- // Directive with no other statements, warn about missing semicolon
- warning("W033", p);
- } else if (p.id !== ";") {
- break;
- }
-
- indentation();
- advance();
- if (state.directive[state.tokens.curr.value]) {
- warning("W034", state.tokens.curr, state.tokens.curr.value);
- }
-
- if (state.tokens.curr.value === "use strict") {
- if (!state.option["(explicitNewcap)"])
- state.option.newcap = true;
- state.option.undef = true;
- }
-
- // there's no directive negation, so always set to true
- state.directive[state.tokens.curr.value] = true;
-
- if (p.id === ";") {
- advance(";");
- }
- continue;
- }
- break;
- }
- }
-
-
- /*
- * Parses a single block. A block is a sequence of statements wrapped in
- * braces.
- *
- * ordinary - true for everything but function bodies and try blocks.
- * stmt - true if block can be a single statement (e.g. in if/for/while).
- * isfunc - true if block is a function body
- * isfatarrow -
- * iscase - true if block is a switch case block
- */
- function block(ordinary, stmt, isfunc, isfatarrow, iscase) {
- var a,
- b = inblock,
- old_indent = indent,
- m,
- s = scope,
- t,
- line,
- d;
-
- inblock = ordinary;
-
- if (!ordinary || !state.option.funcscope)
- scope = Object.create(scope);
-
- nonadjacent(state.tokens.curr, state.tokens.next);
- t = state.tokens.next;
-
- var metrics = funct["(metrics)"];
- metrics.nestedBlockDepth += 1;
- metrics.verifyMaxNestedBlockDepthPerFunction();
-
- if (state.tokens.next.id === "{") {
- advance("{");
-
- // create a new block scope
- funct["(blockscope)"].stack();
-
- line = state.tokens.curr.line;
- if (state.tokens.next.id !== "}") {
- indent += state.option.indent;
- while (!ordinary && state.tokens.next.from > indent) {
- indent += state.option.indent;
- }
-
- if (isfunc) {
- m = {};
- for (d in state.directive) {
- if (_.has(state.directive, d)) {
- m[d] = state.directive[d];
- }
- }
- directives();
-
- if (state.option.strict && funct["(context)"]["(global)"]) {
- if (!m["use strict"] && !state.directive["use strict"]) {
- warning("E007");
- }
- }
- }
-
- a = statements(line);
-
- metrics.statementCount += a.length;
-
- if (isfunc) {
- state.directive = m;
- }
-
- indent -= state.option.indent;
- if (line !== state.tokens.next.line) {
- indentation();
- }
- } else if (line !== state.tokens.next.line) {
- indentation();
- }
- advance("}", t);
-
- funct["(blockscope)"].unstack();
-
- indent = old_indent;
- } else if (!ordinary) {
- if (isfunc) {
- m = {};
- if (stmt && !isfatarrow && !state.option.inMoz(true)) {
- error("W118", state.tokens.curr, "function closure expressions");
- }
-
- if (!stmt) {
- for (d in state.directive) {
- if (_.has(state.directive, d)) {
- m[d] = state.directive[d];
- }
- }
- }
- expression(5);
-
- if (state.option.strict && funct["(context)"]["(global)"]) {
- if (!m["use strict"] && !state.directive["use strict"]) {
- warning("E007");
- }
- }
- } else {
- error("E021", state.tokens.next, "{", state.tokens.next.value);
- }
- } else {
-
- // check to avoid let declaration not within a block
- funct["(nolet)"] = true;
-
- if (!stmt || state.option.curly) {
- warning("W116", state.tokens.next, "{", state.tokens.next.value);
- }
-
- noreach = true;
- indent += state.option.indent;
- // test indentation only if statement is in new line
- a = [statement(state.tokens.next.line === state.tokens.curr.line)];
- indent -= state.option.indent;
- noreach = false;
-
- delete funct["(nolet)"];
- }
- // If it is a "break" in switch case, don't clear and let it propagate out.
- if (!(iscase && funct["(verb)"] === "break")) funct["(verb)"] = null;
-
- if (!ordinary || !state.option.funcscope) scope = s;
- inblock = b;
- if (ordinary && state.option.noempty && (!a || a.length === 0)) {
- warning("W035");
- }
- metrics.nestedBlockDepth -= 1;
- return a;
- }
-
-
- function countMember(m) {
- if (membersOnly && typeof membersOnly[m] !== "boolean") {
- warning("W036", state.tokens.curr, m);
- }
- if (typeof member[m] === "number") {
- member[m] += 1;
- } else {
- member[m] = 1;
- }
- }
-
-
- function note_implied(tkn) {
- var name = tkn.value, line = tkn.line, a = implied[name];
- if (typeof a === "function") {
- a = false;
- }
-
- if (!a) {
- a = [line];
- implied[name] = a;
- } else if (a[a.length - 1] !== line) {
- a.push(line);
- }
- }
-
-
- // Build the syntax table by declaring the syntactic elements of the language.
-
- type("(number)", function () {
- return this;
- });
-
- type("(string)", function () {
- return this;
- });
-
- state.syntax["(identifier)"] = {
- type: "(identifier)",
- lbp: 0,
- identifier: true,
- nud: function () {
- var v = this.value,
- s = scope[v],
- f;
-
- if (typeof s === "function") {
- // Protection against accidental inheritance.
- s = undefined;
- } else if (typeof s === "boolean") {
- f = funct;
- funct = functions[0];
- addlabel(v, "var");
- s = funct;
- funct = f;
- }
- var block;
- if (_.has(funct, "(blockscope)")) {
- block = funct["(blockscope)"].getlabel(v);
- }
-
- // The name is in scope and defined in the current function.
- if (funct === s || block) {
- // Change 'unused' to 'var', and reject labels.
- // the name is in a block scope
- switch (block ? block[v]["(type)"] : funct[v]) {
- case "unused":
- if (block) block[v]["(type)"] = "var";
- else funct[v] = "var";
- break;
- case "unction":
- if (block) block[v]["(type)"] = "function";
- else funct[v] = "function";
- this["function"] = true;
- break;
- case "function":
- this["function"] = true;
- break;
- case "label":
- warning("W037", state.tokens.curr, v);
- break;
- }
- } else if (funct["(global)"]) {
- // The name is not defined in the function. If we are in the global
- // scope, then we have an undefined variable.
- //
- // Operators typeof and delete do not raise runtime errors even if
- // the base object of a reference is null so no need to display warning
- // if we're inside of typeof or delete.
-
- if (typeof predefined[v] !== "boolean") {
- // Attempting to subscript a null reference will throw an
- // error, even within the typeof and delete operators
- if (!(anonname === "typeof" || anonname === "delete") ||
- (state.tokens.next && (state.tokens.next.value === "." ||
- state.tokens.next.value === "["))) {
-
- // if we're in a list comprehension, variables are declared
- // locally and used before being defined. So we check
- // the presence of the given variable in the comp array
- // before declaring it undefined.
-
- if (!funct["(comparray)"].check(v)) {
- isundef(funct, "W117", state.tokens.curr, v);
- }
- }
- }
-
- note_implied(state.tokens.curr);
- } else {
- // If the name is already defined in the current
- // function, but not as outer, then there is a scope error.
-
- switch (funct[v]) {
- case "closure":
- case "function":
- case "var":
- case "unused":
- warning("W038", state.tokens.curr, v);
- break;
- case "label":
- warning("W037", state.tokens.curr, v);
- break;
- case "outer":
- case "global":
- break;
- default:
- // If the name is defined in an outer function, make an outer entry,
- // and if it was unused, make it var.
- if (s === true) {
- funct[v] = true;
- } else if (s === null) {
- warning("W039", state.tokens.curr, v);
- note_implied(state.tokens.curr);
- } else if (typeof s !== "object") {
- // Operators typeof and delete do not raise runtime errors even
- // if the base object of a reference is null so no need to
- //
- // display warning if we're inside of typeof or delete.
- // Attempting to subscript a null reference will throw an
- // error, even within the typeof and delete operators
- if (!(anonname === "typeof" || anonname === "delete") ||
- (state.tokens.next &&
- (state.tokens.next.value === "." || state.tokens.next.value === "["))) {
-
- isundef(funct, "W117", state.tokens.curr, v);
- }
- funct[v] = true;
- note_implied(state.tokens.curr);
- } else {
- switch (s[v]) {
- case "function":
- case "unction":
- this["function"] = true;
- s[v] = "closure";
- funct[v] = s["(global)"] ? "global" : "outer";
- break;
- case "var":
- case "unused":
- s[v] = "closure";
- funct[v] = s["(global)"] ? "global" : "outer";
- break;
- case "closure":
- funct[v] = s["(global)"] ? "global" : "outer";
- break;
- case "label":
- warning("W037", state.tokens.curr, v);
- }
- }
- }
- }
- return this;
- },
- led: function () {
- error("E033", state.tokens.next, state.tokens.next.value);
- }
- };
-
- type("(regexp)", function () {
- return this;
- });
-
- // ECMAScript parser
-
- delim("(endline)");
- delim("(begin)");
- delim("(end)").reach = true;
- delim("(error)").reach = true;
- delim("}").reach = true;
- delim(")");
- delim("]");
- delim("\"").reach = true;
- delim("'").reach = true;
- delim(";");
- delim(":").reach = true;
- delim("#");
-
- reserve("else");
- reserve("case").reach = true;
- reserve("catch");
- reserve("default").reach = true;
- reserve("finally");
- reservevar("arguments", function (x) {
- if (state.directive["use strict"] && funct["(global)"]) {
- warning("E008", x);
- }
- });
- reservevar("eval");
- reservevar("false");
- reservevar("Infinity");
- reservevar("null");
- reservevar("this", function (x) {
- if (state.directive["use strict"] && !state.option.validthis && ((funct["(statement)"] &&
- funct["(name)"].charAt(0) > "Z") || funct["(global)"])) {
- warning("W040", x);
- }
- });
- reservevar("true");
- reservevar("undefined");
-
- assignop("=", "assign", 20);
- assignop("+=", "assignadd", 20);
- assignop("-=", "assignsub", 20);
- assignop("*=", "assignmult", 20);
- assignop("/=", "assigndiv", 20).nud = function () {
- error("E014");
- };
- assignop("%=", "assignmod", 20);
-
- bitwiseassignop("&=", "assignbitand", 20);
- bitwiseassignop("|=", "assignbitor", 20);
- bitwiseassignop("^=", "assignbitxor", 20);
- bitwiseassignop("<<=", "assignshiftleft", 20);
- bitwiseassignop(">>=", "assignshiftright", 20);
- bitwiseassignop(">>>=", "assignshiftrightunsigned", 20);
- infix(",", function (left, that) {
- var expr;
- that.exprs = [left];
- if (!comma({peek: true})) {
- return that;
- }
- while (true) {
- if (!(expr = expression(5))) {
- break;
- }
- that.exprs.push(expr);
- if (state.tokens.next.value !== "," || !comma()) {
- break;
- }
- }
- return that;
- }, 5, true);
- infix("?", function (left, that) {
- that.left = left;
- that.right = expression(10);
- advance(":");
- that["else"] = expression(10);
- return that;
- }, 30);
-
- infix("||", "or", 40);
- infix("&&", "and", 50);
- bitwise("|", "bitor", 70);
- bitwise("^", "bitxor", 80);
- bitwise("&", "bitand", 90);
- relation("==", function (left, right) {
- var eqnull = state.option.eqnull && (left.value === "null" || right.value === "null");
-
- if (!eqnull && state.option.eqeqeq)
- warning("W116", this, "===", "==");
- else if (isPoorRelation(left))
- warning("W041", this, "===", left.value);
- else if (isPoorRelation(right))
- warning("W041", this, "===", right.value);
-
- return this;
- });
- relation("===");
- relation("!=", function (left, right) {
- var eqnull = state.option.eqnull &&
- (left.value === "null" || right.value === "null");
-
- if (!eqnull && state.option.eqeqeq) {
- warning("W116", this, "!==", "!=");
- } else if (isPoorRelation(left)) {
- warning("W041", this, "!==", left.value);
- } else if (isPoorRelation(right)) {
- warning("W041", this, "!==", right.value);
- }
- return this;
- });
- relation("!==");
- relation("<");
- relation(">");
- relation("<=");
- relation(">=");
- bitwise("<<", "shiftleft", 120);
- bitwise(">>", "shiftright", 120);
- bitwise(">>>", "shiftrightunsigned", 120);
- infix("in", "in", 120);
- infix("instanceof", "instanceof", 120);
- infix("+", function (left, that) {
- var right = expression(130);
- if (left && right && left.id === "(string)" && right.id === "(string)") {
- left.value += right.value;
- left.character = right.character;
- if (!state.option.scripturl && reg.javascriptURL.test(left.value)) {
- warning("W050", left);
- }
- return left;
- }
- that.left = left;
- that.right = right;
- return that;
- }, 130);
- prefix("+", "num");
- prefix("+++", function () {
- warning("W007");
- this.right = expression(150);
- this.arity = "unary";
- return this;
- });
- infix("+++", function (left) {
- warning("W007");
- this.left = left;
- this.right = expression(130);
- return this;
- }, 130);
- infix("-", "sub", 130);
- prefix("-", "neg");
- prefix("---", function () {
- warning("W006");
- this.right = expression(150);
- this.arity = "unary";
- return this;
- });
- infix("---", function (left) {
- warning("W006");
- this.left = left;
- this.right = expression(130);
- return this;
- }, 130);
- infix("*", "mult", 140);
- infix("/", "div", 140);
- infix("%", "mod", 140);
-
- suffix("++", "postinc");
- prefix("++", "preinc");
- state.syntax["++"].exps = true;
-
- suffix("--", "postdec");
- prefix("--", "predec");
- state.syntax["--"].exps = true;
- prefix("delete", function () {
- var p = expression(5);
- if (!p || (p.id !== "." && p.id !== "[")) {
- warning("W051");
- }
- this.first = p;
- return this;
- }).exps = true;
-
- prefix("~", function () {
- if (state.option.bitwise) {
- warning("W052", this, "~");
- }
- expression(150);
- return this;
- });
-
- prefix("...", function () {
- if (!state.option.inESNext()) {
- warning("W104", this, "spread/rest operator");
- }
- if (!state.tokens.next.identifier) {
- error("E030", state.tokens.next, state.tokens.next.value);
- }
- expression(150);
- return this;
- });
-
- prefix("!", function () {
- this.right = expression(150);
- this.arity = "unary";
-
- if (!this.right) { // '!' followed by nothing? Give up.
- quit("E041", this.line || 0);
- }
-
- if (bang[this.right.id] === true) {
- warning("W018", this, "!");
- }
- return this;
- });
-
- prefix("typeof", "typeof");
- prefix("new", function () {
- var c = expression(155), i;
- if (c && c.id !== "function") {
- if (c.identifier) {
- c["new"] = true;
- switch (c.value) {
- case "Number":
- case "String":
- case "Boolean":
- case "Math":
- case "JSON":
- warning("W053", state.tokens.prev, c.value);
- break;
- case "Function":
- if (!state.option.evil) {
- warning("W054");
- }
- break;
- case "Date":
- case "RegExp":
- break;
- default:
- if (c.id !== "function") {
- i = c.value.substr(0, 1);
- if (state.option.newcap && (i < "A" || i > "Z") && !_.has(global, c.value)) {
- warning("W055", state.tokens.curr);
- }
- }
- }
- } else {
- if (c.id !== "." && c.id !== "[" && c.id !== "(") {
- warning("W056", state.tokens.curr);
- }
- }
- } else {
- if (!state.option.supernew)
- warning("W057", this);
- }
- adjacent(state.tokens.curr, state.tokens.next);
- if (state.tokens.next.id !== "(" && !state.option.supernew) {
- warning("W058", state.tokens.curr, state.tokens.curr.value);
- }
- this.first = c;
- return this;
- });
- state.syntax["new"].exps = true;
-
- prefix("void").exps = true;
-
- infix(".", function (left, that) {
- adjacent(state.tokens.prev, state.tokens.curr);
- nobreak();
- var m = identifier(false, true);
-
- if (typeof m === "string") {
- countMember(m);
- }
-
- that.left = left;
- that.right = m;
-
- if (m && m === "hasOwnProperty" && state.tokens.next.value === "=") {
- warning("W001");
- }
-
- if (left && left.value === "arguments" && (m === "callee" || m === "caller")) {
- if (state.option.noarg)
- warning("W059", left, m);
- else if (state.directive["use strict"])
- error("E008");
- } else if (!state.option.evil && left && left.value === "document" &&
- (m === "write" || m === "writeln")) {
- warning("W060", left);
- }
-
- if (!state.option.evil && (m === "eval" || m === "execScript")) {
- warning("W061");
- }
-
- return that;
- }, 160, true);
-
- infix("(", function (left, that) {
- if (state.tokens.prev.id !== "}" && state.tokens.prev.id !== ")") {
- nobreak(state.tokens.prev, state.tokens.curr);
- }
-
- nospace();
- if (state.option.immed && left && !left.immed && left.id === "function") {
- warning("W062");
- }
-
- var n = 0;
- var p = [];
-
- if (left) {
- if (left.type === "(identifier)") {
- if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) {
- if ("Number String Boolean Date Object".indexOf(left.value) === -1) {
- if (left.value === "Math") {
- warning("W063", left);
- } else if (state.option.newcap) {
- warning("W064", left);
- }
- }
- }
- }
- }
-
- if (state.tokens.next.id !== ")") {
- for (;;) {
- p[p.length] = expression(10);
- n += 1;
- if (state.tokens.next.id !== ",") {
- break;
- }
- comma();
- }
- }
-
- advance(")");
- nospace(state.tokens.prev, state.tokens.curr);
-
- if (typeof left === "object") {
- if (left.value === "parseInt" && n === 1) {
- warning("W065", state.tokens.curr);
- }
- if (!state.option.evil) {
- if (left.value === "eval" || left.value === "Function" ||
- left.value === "execScript") {
- warning("W061", left);
-
- if (p[0] && [0].id === "(string)") {
- addInternalSrc(left, p[0].value);
- }
- } else if (p[0] && p[0].id === "(string)" &&
- (left.value === "setTimeout" ||
- left.value === "setInterval")) {
- warning("W066", left);
- addInternalSrc(left, p[0].value);
-
- // window.setTimeout/setInterval
- } else if (p[0] && p[0].id === "(string)" &&
- left.value === "." &&
- left.left.value === "window" &&
- (left.right === "setTimeout" ||
- left.right === "setInterval")) {
- warning("W066", left);
- addInternalSrc(left, p[0].value);
- }
- }
- if (!left.identifier && left.id !== "." && left.id !== "[" &&
- left.id !== "(" && left.id !== "&&" && left.id !== "||" &&
- left.id !== "?") {
- warning("W067", left);
- }
- }
-
- that.left = left;
- return that;
- }, 155, true).exps = true;
-
- prefix("(", function () {
- nospace();
- var bracket, brackets = [];
- var pn, pn1, i = 0;
-
- do {
- pn = peek(i);
- i += 1;
- pn1 = peek(i);
- i += 1;
- } while (pn.value !== ")" && pn1.value !== "=>" && pn1.value !== ";" && pn1.type !== "(end)");
-
- if (state.tokens.next.id === "function") {
- state.tokens.next.immed = true;
- }
-
- var exprs = [];
-
- if (state.tokens.next.id !== ")") {
- for (;;) {
- if (pn1.value === "=>" && state.tokens.next.value === "{") {
- bracket = state.tokens.next;
- bracket.left = destructuringExpression();
- brackets.push(bracket);
- for (var t in bracket.left) {
- exprs.push(bracket.left[t].token);
- }
- } else {
- exprs.push(expression(5));
- }
- if (state.tokens.next.id !== ",") {
- break;
- }
- comma();
- }
- }
-
- advance(")", this);
- nospace(state.tokens.prev, state.tokens.curr);
- if (state.option.immed && exprs[0] && exprs[0].id === "function") {
- if (state.tokens.next.id !== "(" &&
- (state.tokens.next.id !== "." || (peek().value !== "call" && peek().value !== "apply"))) {
- warning("W068", this);
- }
- }
-
- if (state.tokens.next.value === "=>") {
- return exprs;
- }
- if (!exprs.length) {
- return;
- }
- exprs[exprs.length - 1].paren = true;
- if (exprs.length > 1) {
- return Object.create(state.syntax[","], { exprs: { value: exprs } });
- }
- return exprs[0];
- });
-
- application("=>");
-
- infix("[", function (left, that) {
- nobreak(state.tokens.prev, state.tokens.curr);
- nospace();
- var e = expression(5), s;
- if (e && e.type === "(string)") {
- if (!state.option.evil && (e.value === "eval" || e.value === "execScript")) {
- warning("W061", that);
- }
-
- countMember(e.value);
- if (!state.option.sub && reg.identifier.test(e.value)) {
- s = state.syntax[e.value];
- if (!s || !isReserved(s)) {
- warning("W069", state.tokens.prev, e.value);
- }
- }
- }
- advance("]", that);
-
- if (e && e.value === "hasOwnProperty" && state.tokens.next.value === "=") {
- warning("W001");
- }
-
- nospace(state.tokens.prev, state.tokens.curr);
- that.left = left;
- that.right = e;
- return that;
- }, 160, true);
-
- function comprehensiveArrayExpression() {
- var res = {};
- res.exps = true;
- funct["(comparray)"].stack();
-
- res.right = expression(5);
- advance("for");
- if (state.tokens.next.value === "each") {
- advance("each");
- if (!state.option.inMoz(true)) {
- warning("W118", state.tokens.curr, "for each");
- }
- }
- advance("(");
- funct["(comparray)"].setState("define");
- res.left = expression(5);
- advance(")");
- if (state.tokens.next.value === "if") {
- advance("if");
- advance("(");
- funct["(comparray)"].setState("filter");
- res.filter = expression(5);
- advance(")");
- }
- advance("]");
- funct["(comparray)"].unstack();
- return res;
- }
-
- prefix("[", function () {
- var blocktype = lookupBlockType(true);
- if (blocktype.isCompArray) {
- if (!state.option.inMoz(true)) {
- warning("W118", state.tokens.curr, "array comprehension");
- }
- return comprehensiveArrayExpression();
- } else if (blocktype.isDestAssign && !state.option.inESNext()) {
- warning("W104", state.tokens.curr, "destructuring assignment");
- }
- var b = state.tokens.curr.line !== state.tokens.next.line;
- this.first = [];
- if (b) {
- indent += state.option.indent;
- if (state.tokens.next.from === indent + state.option.indent) {
- indent += state.option.indent;
- }
- }
- while (state.tokens.next.id !== "(end)") {
- while (state.tokens.next.id === ",") {
- if (!state.option.inES5())
- warning("W070");
- advance(",");
- }
- if (state.tokens.next.id === "]") {
- break;
- }
- if (b && state.tokens.curr.line !== state.tokens.next.line) {
- indentation();
- }
- this.first.push(expression(10));
- if (state.tokens.next.id === ",") {
- comma({ allowTrailing: true });
- if (state.tokens.next.id === "]" && !state.option.inES5(true)) {
- warning("W070", state.tokens.curr);
- break;
- }
- } else {
- break;
- }
- }
- if (b) {
- indent -= state.option.indent;
- indentation();
- }
- advance("]", this);
- return this;
- }, 160);
-
-
- function property_name() {
- var id = optionalidentifier(false, true);
-
- if (!id) {
- if (state.tokens.next.id === "(string)") {
- id = state.tokens.next.value;
- advance();
- } else if (state.tokens.next.id === "(number)") {
- id = state.tokens.next.value.toString();
- advance();
- }
- }
-
- if (id === "hasOwnProperty") {
- warning("W001");
- }
-
- return id;
- }
-
-
- function functionparams(parsed) {
- var curr, next;
- var params = [];
- var ident;
- var tokens = [];
- var t;
-
- if (parsed) {
- if (parsed instanceof Array) {
- for (var i in parsed) {
- curr = parsed[i];
- if (_.contains(["{", "["], curr.id)) {
- for (t in curr.left) {
- t = tokens[t];
- if (t.id) {
- params.push(t.id);
- addlabel(t.id, "unused", t.token);
- }
- }
- } else if (curr.value === "...") {
- if (!state.option.inESNext()) {
- warning("W104", curr, "spread/rest operator");
- }
- continue;
- } else {
- addlabel(curr.value, "unused", curr);
- }
- }
- return params;
- } else {
- if (parsed.identifier === true) {
- addlabel(parsed.value, "unused", parsed);
- return [parsed];
- }
- }
- }
-
- next = state.tokens.next;
-
- advance("(");
- nospace();
-
- if (state.tokens.next.id === ")") {
- advance(")");
- return;
- }
-
- for (;;) {
- if (_.contains(["{", "["], state.tokens.next.id)) {
- tokens = destructuringExpression();
- for (t in tokens) {
- t = tokens[t];
- if (t.id) {
- params.push(t.id);
- addlabel(t.id, "unused", t.token);
- }
- }
- } else if (state.tokens.next.value === "...") {
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.next, "spread/rest operator");
- }
- advance("...");
- nospace();
- ident = identifier(true);
- params.push(ident);
- addlabel(ident, "unused", state.tokens.curr);
- } else {
- ident = identifier(true);
- params.push(ident);
- addlabel(ident, "unused", state.tokens.curr);
- }
- if (state.tokens.next.id === ",") {
- comma();
- } else {
- advance(")", next);
- nospace(state.tokens.prev, state.tokens.curr);
- return params;
- }
- }
- }
-
-
- function doFunction(name, statement, generator, fatarrowparams) {
- var f;
- var oldOption = state.option;
- var oldIgnored = state.ignored;
- var oldScope = scope;
-
- state.option = Object.create(state.option);
- state.ignored = Object.create(state.ignored);
- scope = Object.create(scope);
-
- funct = {
- "(name)" : name || "\"" + anonname + "\"",
- "(line)" : state.tokens.next.line,
- "(character)" : state.tokens.next.character,
- "(context)" : funct,
- "(breakage)" : 0,
- "(loopage)" : 0,
- "(metrics)" : createMetrics(state.tokens.next),
- "(scope)" : scope,
- "(statement)" : statement,
- "(tokens)" : {},
- "(blockscope)": funct["(blockscope)"],
- "(comparray)" : funct["(comparray)"]
- };
-
- if (generator) {
- funct["(generator)"] = true;
- }
-
- f = funct;
- state.tokens.curr.funct = funct;
-
- functions.push(funct);
-
- if (name) {
- addlabel(name, "function");
- }
-
- funct["(params)"] = functionparams(fatarrowparams);
-
- funct["(metrics)"].verifyMaxParametersPerFunction(funct["(params)"]);
-
- block(false, true, true, fatarrowparams ? true:false);
-
- if (generator && funct["(generator)"] !== "yielded") {
- error("E047", state.tokens.curr);
- }
-
- funct["(metrics)"].verifyMaxStatementsPerFunction();
- funct["(metrics)"].verifyMaxComplexityPerFunction();
- funct["(unusedOption)"] = state.option.unused;
-
- scope = oldScope;
- state.option = oldOption;
- state.ignored = oldIgnored;
- funct["(last)"] = state.tokens.curr.line;
- funct["(lastcharacter)"] = state.tokens.curr.character;
- funct = funct["(context)"];
-
- return f;
- }
-
- function createMetrics(functionStartToken) {
- return {
- statementCount: 0,
- nestedBlockDepth: -1,
- ComplexityCount: 1,
- verifyMaxStatementsPerFunction: function () {
- if (state.option.maxstatements &&
- this.statementCount > state.option.maxstatements) {
- warning("W071", functionStartToken, this.statementCount);
- }
- },
-
- verifyMaxParametersPerFunction: function (params) {
- params = params || [];
-
- if (state.option.maxparams && params.length > state.option.maxparams) {
- warning("W072", functionStartToken, params.length);
- }
- },
-
- verifyMaxNestedBlockDepthPerFunction: function () {
- if (state.option.maxdepth &&
- this.nestedBlockDepth > 0 &&
- this.nestedBlockDepth === state.option.maxdepth + 1) {
- warning("W073", null, this.nestedBlockDepth);
- }
- },
-
- verifyMaxComplexityPerFunction: function () {
- var max = state.option.maxcomplexity;
- var cc = this.ComplexityCount;
- if (max && cc > max) {
- warning("W074", functionStartToken, cc);
- }
- }
- };
- }
-
- function increaseComplexityCount() {
- funct["(metrics)"].ComplexityCount += 1;
- }
-
- // Parse assignments that were found instead of conditionals.
- // For example: if (a = 1) { ... }
-
- function checkCondAssignment(expr) {
- var id = expr.id;
- if (id === ",") {
- expr = expr.exprs[expr.exprs.length - 1];
- id = expr.id;
- }
- switch (id) {
- case "=":
- case "+=":
- case "-=":
- case "*=":
- case "%=":
- case "&=":
- case "|=":
- case "^=":
- case "/=":
- if (!expr.paren && !state.option.boss) {
- warning("W084");
- }
- }
- }
-
-
- (function (x) {
- x.nud = function (isclassdef) {
- var b, f, i, p, t, g;
- var props = {}; // All properties, including accessors
- var tag = "";
-
- function saveProperty(name, tkn) {
- if (props[name] && _.has(props, name))
- warning("W075", state.tokens.next, i);
- else
- props[name] = {};
-
- props[name].basic = true;
- props[name].basictkn = tkn;
- }
-
- function saveSetter(name, tkn) {
- if (props[name] && _.has(props, name)) {
- if (props[name].basic || props[name].setter)
- warning("W075", state.tokens.next, i);
- } else {
- props[name] = {};
- }
-
- props[name].setter = true;
- props[name].setterToken = tkn;
- }
-
- function saveGetter(name) {
- if (props[name] && _.has(props, name)) {
- if (props[name].basic || props[name].getter)
- warning("W075", state.tokens.next, i);
- } else {
- props[name] = {};
- }
-
- props[name].getter = true;
- props[name].getterToken = state.tokens.curr;
- }
-
- b = state.tokens.curr.line !== state.tokens.next.line;
- if (b) {
- indent += state.option.indent;
- if (state.tokens.next.from === indent + state.option.indent) {
- indent += state.option.indent;
- }
- }
-
- for (;;) {
- if (state.tokens.next.id === "}") {
- break;
- }
-
- if (b) {
- indentation();
- }
-
- if (isclassdef && state.tokens.next.value === "static") {
- advance("static");
- tag = "static ";
- }
-
- if (state.tokens.next.value === "get" && peek().id !== ":") {
- advance("get");
-
- if (!state.option.inES5(!isclassdef)) {
- error("E034");
- }
-
- i = property_name();
- if (!i) {
- error("E035");
- }
-
- // It is a Syntax Error if PropName of MethodDefinition is
- // "constructor" and SpecialMethod of MethodDefinition is true.
- if (isclassdef && i === "constructor") {
- error("E049", state.tokens.next, "class getter method", i);
- }
-
- saveGetter(tag + i);
- t = state.tokens.next;
- adjacent(state.tokens.curr, state.tokens.next);
- f = doFunction();
- p = f["(params)"];
-
- if (p) {
- warning("W076", t, p[0], i);
- }
-
- adjacent(state.tokens.curr, state.tokens.next);
- } else if (state.tokens.next.value === "set" && peek().id !== ":") {
- advance("set");
-
- if (!state.option.inES5(!isclassdef)) {
- error("E034");
- }
-
- i = property_name();
- if (!i) {
- error("E035");
- }
-
- // It is a Syntax Error if PropName of MethodDefinition is
- // "constructor" and SpecialMethod of MethodDefinition is true.
- if (isclassdef && i === "constructor") {
- error("E049", state.tokens.next, "class setter method", i);
- }
-
- saveSetter(tag + i, state.tokens.next);
- t = state.tokens.next;
- adjacent(state.tokens.curr, state.tokens.next);
- f = doFunction();
- p = f["(params)"];
-
- if (!p || p.length !== 1) {
- warning("W077", t, i);
- }
- } else {
- g = false;
- if (state.tokens.next.value === "*" && state.tokens.next.type === "(punctuator)") {
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.next, "generator functions");
- }
- advance("*");
- g = true;
- }
- i = property_name();
- saveProperty(tag + i, state.tokens.next);
-
- if (typeof i !== "string") {
- break;
- }
-
- if (state.tokens.next.value === "(") {
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.curr, "concise methods");
- }
- doFunction(i, undefined, g);
- } else if (!isclassdef) {
- advance(":");
- nonadjacent(state.tokens.curr, state.tokens.next);
- expression(10);
- }
- }
- // It is a Syntax Error if PropName of MethodDefinition is "prototype".
- if (isclassdef && i === "prototype") {
- error("E049", state.tokens.next, "class method", i);
- }
-
- countMember(i);
- if (isclassdef) {
- tag = "";
- continue;
- }
- if (state.tokens.next.id === ",") {
- comma({ allowTrailing: true, property: true });
- if (state.tokens.next.id === ",") {
- warning("W070", state.tokens.curr);
- } else if (state.tokens.next.id === "}" && !state.option.inES5(true)) {
- warning("W070", state.tokens.curr);
- }
- } else {
- break;
- }
- }
- if (b) {
- indent -= state.option.indent;
- indentation();
- }
- advance("}", this);
-
- // Check for lonely setters if in the ES5 mode.
- if (state.option.inES5()) {
- for (var name in props) {
- if (_.has(props, name) && props[name].setter && !props[name].getter) {
- warning("W078", props[name].setterToken);
- }
- }
- }
- return this;
- };
- x.fud = function () {
- error("E036", state.tokens.curr);
- };
- }(delim("{")));
-
- function destructuringExpression() {
- var id, ids;
- var identifiers = [];
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.curr, "destructuring expression");
- }
- var nextInnerDE = function () {
- var ident;
- if (_.contains(["[", "{"], state.tokens.next.value)) {
- ids = destructuringExpression();
- for (var id in ids) {
- id = ids[id];
- identifiers.push({ id: id.id, token: id.token });
- }
- } else if (state.tokens.next.value === ",") {
- identifiers.push({ id: null, token: state.tokens.curr });
- } else {
- ident = identifier();
- if (ident)
- identifiers.push({ id: ident, token: state.tokens.curr });
- }
- };
- if (state.tokens.next.value === "[") {
- advance("[");
- nextInnerDE();
- while (state.tokens.next.value !== "]") {
- advance(",");
- nextInnerDE();
- }
- advance("]");
- } else if (state.tokens.next.value === "{") {
- advance("{");
- id = identifier();
- if (state.tokens.next.value === ":") {
- advance(":");
- nextInnerDE();
- } else {
- identifiers.push({ id: id, token: state.tokens.curr });
- }
- while (state.tokens.next.value !== "}") {
- advance(",");
- id = identifier();
- if (state.tokens.next.value === ":") {
- advance(":");
- nextInnerDE();
- } else {
- identifiers.push({ id: id, token: state.tokens.curr });
- }
- }
- advance("}");
- }
- return identifiers;
- }
- function destructuringExpressionMatch(tokens, value) {
- if (value.first) {
- _.zip(tokens, value.first).forEach(function (val) {
- var token = val[0];
- var value = val[1];
- if (token && value) {
- token.first = value;
- } else if (token && token.first && !value) {
- warning("W080", token.first, token.first.value);
- } /* else {
- XXX value is discarded: wouldn't it need a warning ?
- } */
- });
- }
- }
-
- var conststatement = stmt("const", function (prefix) {
- var tokens, value;
- // state variable to know if it is a lone identifier, or a destructuring statement.
- var lone;
-
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.curr, "const");
- }
-
- this.first = [];
- for (;;) {
- var names = [];
- nonadjacent(state.tokens.curr, state.tokens.next);
- if (_.contains(["{", "["], state.tokens.next.value)) {
- tokens = destructuringExpression();
- lone = false;
- } else {
- tokens = [ { id: identifier(), token: state.tokens.curr } ];
- lone = true;
- }
- for (var t in tokens) {
- t = tokens[t];
- if (funct[t.id] === "const") {
- warning("E011", null, t.id);
- }
- if (funct["(global)"] && predefined[t.id] === false) {
- warning("W079", t.token, t.id);
- }
- if (t.id) {
- addlabel(t.id, "const");
- names.push(t.token);
- }
- }
- if (prefix) {
- break;
- }
-
- this.first = this.first.concat(names);
-
- if (state.tokens.next.id !== "=") {
- warning("E012", state.tokens.curr, state.tokens.curr.value);
- }
-
- if (state.tokens.next.id === "=") {
- nonadjacent(state.tokens.curr, state.tokens.next);
- advance("=");
- nonadjacent(state.tokens.curr, state.tokens.next);
- if (state.tokens.next.id === "undefined") {
- warning("W080", state.tokens.prev, state.tokens.prev.value);
- }
- if (peek(0).id === "=" && state.tokens.next.identifier) {
- error("E037", state.tokens.next, state.tokens.next.value);
- }
- value = expression(5);
- if (lone) {
- tokens[0].first = value;
- } else {
- destructuringExpressionMatch(names, value);
- }
- }
-
- if (state.tokens.next.id !== ",") {
- break;
- }
- comma();
- }
- return this;
- });
- conststatement.exps = true;
- var varstatement = stmt("var", function (prefix) {
- // JavaScript does not have block scope. It only has function scope. So,
- // declaring a variable in a block can have unexpected consequences.
- var tokens, lone, value;
-
- if (funct["(onevar)"] && state.option.onevar) {
- warning("W081");
- } else if (!funct["(global)"]) {
- funct["(onevar)"] = true;
- }
-
- this.first = [];
- for (;;) {
- var names = [];
- nonadjacent(state.tokens.curr, state.tokens.next);
- if (_.contains(["{", "["], state.tokens.next.value)) {
- tokens = destructuringExpression();
- lone = false;
- } else {
- tokens = [ { id: identifier(), token: state.tokens.curr } ];
- lone = true;
- }
- for (var t in tokens) {
- t = tokens[t];
- if (state.option.inESNext() && funct[t.id] === "const") {
- warning("E011", null, t.id);
- }
- if (funct["(global)"] && predefined[t.id] === false) {
- warning("W079", t.token, t.id);
- }
- if (t.id) {
- addlabel(t.id, "unused", t.token);
- names.push(t.token);
- }
- }
- if (prefix) {
- break;
- }
-
- this.first = this.first.concat(names);
-
- if (state.tokens.next.id === "=") {
- nonadjacent(state.tokens.curr, state.tokens.next);
- advance("=");
- nonadjacent(state.tokens.curr, state.tokens.next);
- if (state.tokens.next.id === "undefined") {
- warning("W080", state.tokens.prev, state.tokens.prev.value);
- }
- if (peek(0).id === "=" && state.tokens.next.identifier) {
- error("E038", state.tokens.next, state.tokens.next.value);
- }
- value = expression(5);
- if (lone) {
- tokens[0].first = value;
- } else {
- destructuringExpressionMatch(names, value);
- }
- }
-
- if (state.tokens.next.id !== ",") {
- break;
- }
- comma();
- }
- return this;
- });
- varstatement.exps = true;
- var letstatement = stmt("let", function (prefix) {
- var tokens, lone, value, letblock;
-
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.curr, "let");
- }
-
- if (state.tokens.next.value === "(") {
- if (!state.option.inMoz(true)) {
- warning("W118", state.tokens.next, "let block");
- }
- advance("(");
- funct["(blockscope)"].stack();
- letblock = true;
- } else if (funct["(nolet)"]) {
- error("E048", state.tokens.curr);
- }
-
- if (funct["(onevar)"] && state.option.onevar) {
- warning("W081");
- } else if (!funct["(global)"]) {
- funct["(onevar)"] = true;
- }
-
- this.first = [];
- for (;;) {
- var names = [];
- nonadjacent(state.tokens.curr, state.tokens.next);
- if (_.contains(["{", "["], state.tokens.next.value)) {
- tokens = destructuringExpression();
- lone = false;
- } else {
- tokens = [ { id: identifier(), token: state.tokens.curr.value } ];
- lone = true;
- }
- for (var t in tokens) {
- t = tokens[t];
- if (state.option.inESNext() && funct[t.id] === "const") {
- warning("E011", null, t.id);
- }
- if (funct["(global)"] && predefined[t.id] === false) {
- warning("W079", t.token, t.id);
- }
- if (t.id && !funct["(nolet)"]) {
- addlabel(t.id, "unused", t.token, true);
- names.push(t.token);
- }
- }
- if (prefix) {
- break;
- }
-
- this.first = this.first.concat(names);
-
- if (state.tokens.next.id === "=") {
- nonadjacent(state.tokens.curr, state.tokens.next);
- advance("=");
- nonadjacent(state.tokens.curr, state.tokens.next);
- if (state.tokens.next.id === "undefined") {
- warning("W080", state.tokens.prev, state.tokens.prev.value);
- }
- if (peek(0).id === "=" && state.tokens.next.identifier) {
- error("E037", state.tokens.next, state.tokens.next.value);
- }
- value = expression(5);
- if (lone) {
- tokens[0].first = value;
- } else {
- destructuringExpressionMatch(names, value);
- }
- }
-
- if (state.tokens.next.id !== ",") {
- break;
- }
- comma();
- }
- if (letblock) {
- advance(")");
- block(true, true);
- this.block = true;
- funct["(blockscope)"].unstack();
- }
-
- return this;
- });
- letstatement.exps = true;
-
- blockstmt("class", function () {
- return classdef.call(this, true);
- });
-
- function classdef(stmt) {
- /*jshint validthis:true */
- if (!state.option.inESNext()) {
- warning("W104", state.tokens.curr, "class");
- }
- if (stmt) {
- // BindingIdentifier
- this.name = identifier();
- addlabel(this.name, "unused", state.tokens.curr);
- } else if (state.tokens.next.identifier && state.tokens.next.value !== "extends") {
- // BindingIdentifier(opt)
- this.name = identifier();
- }
- classtail(this);
- return this;
- }
-
- function classtail(c) {
- var strictness = state.directive["use strict"];
-
- // ClassHeritage(opt)
- if (state.tokens.next.value === "extends") {
- advance("extends");
- c.heritage = expression(10);
- }
-
- // A ClassBody is always strict code.
- state.directive["use strict"] = true;
- advance("{");
- // ClassBody(opt)
- c.body = state.syntax["{"].nud(true);
- state.directive["use strict"] = strictness;
- }
-
- blockstmt("function", function () {
- var generator = false;
- if (state.tokens.next.value === "*") {
- advance("*");
- if (state.option.inESNext(true)) {
- generator = true;
- } else {
- warning("W119", state.tokens.curr, "function*");
- }
- }
- if (inblock) {
- warning("W082", state.tokens.curr);
-
- }
- var i = identifier();
- if (funct[i] === "const") {
- warning("E011", null, i);
- }
- adjacent(state.tokens.curr, state.tokens.next);
- addlabel(i, "unction", state.tokens.curr);
-
- doFunction(i, { statement: true }, generator);
- if (state.tokens.next.id === "(" && state.tokens.next.line === state.tokens.curr.line) {
- error("E039");
- }
- return this;
- });
-
- prefix("function", function () {
- var generator = false;
- if (state.tokens.next.value === "*") {
- if (!state.option.inESNext()) {
- warning("W119", state.tokens.curr, "function*");
- }
- advance("*");
- generator = true;
- }
- var i = optionalidentifier();
- if (i || state.option.gcl) {
- adjacent(state.tokens.curr, state.tokens.next);
- } else {
- nonadjacent(state.tokens.curr, state.tokens.next);
- }
- doFunction(i, undefined, generator);
- if (!state.option.loopfunc && funct["(loopage)"]) {
- warning("W083");
- }
- return this;
- });
-
- blockstmt("if", function () {
- var t = state.tokens.next;
- increaseComplexityCount();
- state.condition = true;
- advance("(");
- nonadjacent(this, t);
- nospace();
- checkCondAssignment(expression(0));
- advance(")", t);
- state.condition = false;
- nospace(state.tokens.prev, state.tokens.curr);
- block(true, true);
- if (state.tokens.next.id === "else") {
- nonadjacent(state.tokens.curr, state.tokens.next);
- advance("else");
- if (state.tokens.next.id === "if" || state.tokens.next.id === "switch") {
- statement(true);
- } else {
- block(true, true);
- }
- }
- return this;
- });
-
- blockstmt("try", function () {
- var b;
-
- function doCatch() {
- var oldScope = scope;
- var e;
-
- advance("catch");
- nonadjacent(state.tokens.curr, state.tokens.next);
- advance("(");
-
- scope = Object.create(oldScope);
-
- e = state.tokens.next.value;
- if (state.tokens.next.type !== "(identifier)") {
- e = null;
- warning("E030", state.tokens.next, e);
- }
-
- advance();
-
- funct = {
- "(name)" : "(catch)",
- "(line)" : state.tokens.next.line,
- "(character)": state.tokens.next.character,
- "(context)" : funct,
- "(breakage)" : funct["(breakage)"],
- "(loopage)" : funct["(loopage)"],
- "(scope)" : scope,
- "(statement)": false,
- "(metrics)" : createMetrics(state.tokens.next),
- "(catch)" : true,
- "(tokens)" : {},
- "(blockscope)": funct["(blockscope)"],
- "(comparray)": funct["(comparray)"]
- };
-
- if (e) {
- addlabel(e, "exception");
- }
-
- if (state.tokens.next.value === "if") {
- if (!state.option.inMoz(true)) {
- warning("W118", state.tokens.curr, "catch filter");
- }
- advance("if");
- expression(0);
- }
-
- advance(")");
-
- state.tokens.curr.funct = funct;
- functions.push(funct);
-
- block(false);
-
- scope = oldScope;
-
- funct["(last)"] = state.tokens.curr.line;
- funct["(lastcharacter)"] = state.tokens.curr.character;
- funct = funct["(context)"];
- }
-
- block(false);
-
- while (state.tokens.next.id === "catch") {
- increaseComplexityCount();
- if (b && (!state.option.inMoz(true))) {
- warning("W118", state.tokens.next, "multiple catch blocks");
- }
- doCatch();
- b = true;
- }
-
- if (state.tokens.next.id === "finally") {
- advance("finally");
- block(false);
- return;
- }
-
- if (!b) {
- error("E021", state.tokens.next, "catch", state.tokens.next.value);
- }
-
- return this;
- });
-
- blockstmt("while", function () {
- var t = state.tokens.next;
- funct["(breakage)"] += 1;
- funct["(loopage)"] += 1;
- increaseComplexityCount();
- advance("(");
- nonadjacent(this, t);
- nospace();
- checkCondAssignment(expression(0));
- advance(")", t);
- nospace(state.tokens.prev, state.tokens.curr);
- block(true, true);
- funct["(breakage)"] -= 1;
- funct["(loopage)"] -= 1;
- return this;
- }).labelled = true;
-
- blockstmt("with", function () {
- var t = state.tokens.next;
- if (state.directive["use strict"]) {
- error("E010", state.tokens.curr);
- } else if (!state.option.withstmt) {
- warning("W085", state.tokens.curr);
- }
-
- advance("(");
- nonadjacent(this, t);
- nospace();
- expression(0);
- advance(")", t);
- nospace(state.tokens.prev, state.tokens.curr);
- block(true, true);
-
- return this;
- });
-
- blockstmt("switch", function () {
- var t = state.tokens.next,
- g = false;
- funct["(breakage)"] += 1;
- advance("(");
- nonadjacent(this, t);
- nospace();
- checkCondAssignment(expression(0));
- advance(")", t);
- nospace(state.tokens.prev, state.tokens.curr);
- nonadjacent(state.tokens.curr, state.tokens.next);
- t = state.tokens.next;
- advance("{");
- nonadjacent(state.tokens.curr, state.tokens.next);
- indent += state.option.indent;
- this.cases = [];
-
- for (;;) {
- switch (state.tokens.next.id) {
- case "case":
- switch (funct["(verb)"]) {
- case "yield":
- case "break":
- case "case":
- case "continue":
- case "return":
- case "switch":
- case "throw":
- break;
- default:
- // You can tell JSHint that you don't use break intentionally by
- // adding a comment /* falls through */ on a line just before
- // the next `case`.
- if (!reg.fallsThrough.test(state.lines[state.tokens.next.line - 2])) {
- warning("W086", state.tokens.curr, "case");
- }
- }
- indentation(-state.option.indent);
- advance("case");
- this.cases.push(expression(20));
- increaseComplexityCount();
- g = true;
- advance(":");
- funct["(verb)"] = "case";
- break;
- case "default":
- switch (funct["(verb)"]) {
- case "yield":
- case "break":
- case "continue":
- case "return":
- case "throw":
- break;
- default:
- // Do not display a warning if 'default' is the first statement or if
- // there is a special /* falls through */ comment.
- if (this.cases.length) {
- if (!reg.fallsThrough.test(state.lines[state.tokens.next.line - 2])) {
- warning("W086", state.tokens.curr, "default");
- }
- }
- }
- indentation(-state.option.indent);
- advance("default");
- g = true;
- advance(":");
- break;
- case "}":
- indent -= state.option.indent;
- indentation();
- advance("}", t);
- funct["(breakage)"] -= 1;
- funct["(verb)"] = undefined;
- return;
- case "(end)":
- error("E023", state.tokens.next, "}");
- return;
- default:
- if (g) {
- switch (state.tokens.curr.id) {
- case ",":
- error("E040");
- return;
- case ":":
- g = false;
- statements();
- break;
- default:
- error("E025", state.tokens.curr);
- return;
- }
- } else {
- if (state.tokens.curr.id === ":") {
- advance(":");
- error("E024", state.tokens.curr, ":");
- statements();
- } else {
- error("E021", state.tokens.next, "case", state.tokens.next.value);
- return;
- }
- }
- }
- }
- }).labelled = true;
-
- stmt("debugger", function () {
- if (!state.option.debug) {
- warning("W087");
- }
- return this;
- }).exps = true;
-
- (function () {
- var x = stmt("do", function () {
- funct["(breakage)"] += 1;
- funct["(loopage)"] += 1;
- increaseComplexityCount();
-
- this.first = block(true, true);
- advance("while");
- var t = state.tokens.next;
- nonadjacent(state.tokens.curr, t);
- advance("(");
- nospace();
- checkCondAssignment(expression(0));
- advance(")", t);
- nospace(state.tokens.prev, state.tokens.curr);
- funct["(breakage)"] -= 1;
- funct["(loopage)"] -= 1;
- return this;
- });
- x.labelled = true;
- x.exps = true;
- }());
-
- blockstmt("for", function () {
- var s, t = state.tokens.next;
- var letscope = false;
- var foreachtok = null;
-
- if (t.value === "each") {
- foreachtok = t;
- advance("each");
- if (!state.option.inMoz(true)) {
- warning("W118", state.tokens.curr, "for each");
- }
- }
-
- funct["(breakage)"] += 1;
- funct["(loopage)"] += 1;
- increaseComplexityCount();
- advance("(");
- nonadjacent(this, t);
- nospace();
-
- // what kind of for(…) statement it is? for(…of…)? for(…in…)? for(…;…;…)?
- var nextop; // contains the token of the "in" or "of" operator
- var i = 0;
- var inof = ["in", "of"];
- do {
- nextop = peek(i);
- ++i;
- } while (!_.contains(inof, nextop.value) && nextop.value !== ";" &&
- nextop.type !== "(end)");
-
- // if we're in a for (… in|of …) statement
- if (_.contains(inof, nextop.value)) {
- if (!state.option.inESNext() && nextop.value === "of") {
- error("W104", nextop, "for of");
- }
- if (state.tokens.next.id === "var") {
- advance("var");
- state.syntax["var"].fud.call(state.syntax["var"].fud, true);
- } else if (state.tokens.next.id === "let") {
- advance("let");
- // create a new block scope
- letscope = true;
- funct["(blockscope)"].stack();
- state.syntax["let"].fud.call(state.syntax["let"].fud, true);
- } else {
- switch (funct[state.tokens.next.value]) {
- case "unused":
- funct[state.tokens.next.value] = "var";
- break;
- case "var":
- break;
- default:
- if (!funct["(blockscope)"].getlabel(state.tokens.next.value))
- warning("W088", state.tokens.next, state.tokens.next.value);
- }
- advance();
- }
- advance(nextop.value);
- expression(20);
- advance(")", t);
- s = block(true, true);
- if (state.option.forin && s && (s.length > 1 || typeof s[0] !== "object" ||
- s[0].value !== "if")) {
- warning("W089", this);
- }
- funct["(breakage)"] -= 1;
- funct["(loopage)"] -= 1;
- } else {
- if (foreachtok) {
- error("E045", foreachtok);
- }
- if (state.tokens.next.id !== ";") {
- if (state.tokens.next.id === "var") {
- advance("var");
- state.syntax["var"].fud.call(state.syntax["var"].fud);
- } else if (state.tokens.next.id === "let") {
- advance("let");
- // create a new block scope
- letscope = true;
- funct["(blockscope)"].stack();
- state.syntax["let"].fud.call(state.syntax["let"].fud);
- } else {
- for (;;) {
- expression(0, "for");
- if (state.tokens.next.id !== ",") {
- break;
- }
- comma();
- }
- }
- }
- nolinebreak(state.tokens.curr);
- advance(";");
- if (state.tokens.next.id !== ";") {
- checkCondAssignment(expression(0));
- }
- nolinebreak(state.tokens.curr);
- advance(";");
- if (state.tokens.next.id === ";") {
- error("E021", state.tokens.next, ")", ";");
- }
- if (state.tokens.next.id !== ")") {
- for (;;) {
- expression(0, "for");
- if (state.tokens.next.id !== ",") {
- break;
- }
- comma();
- }
- }
- advance(")", t);
- nospace(state.tokens.prev, state.tokens.curr);
- block(true, true);
- funct["(breakage)"] -= 1;
- funct["(loopage)"] -= 1;
-
- }
- // unstack loop blockscope
- if (letscope) {
- funct["(blockscope)"].unstack();
- }
- return this;
- }).labelled = true;
-
-
- stmt("break", function () {
- var v = state.tokens.next.value;
-
- if (funct["(breakage)"] === 0)
- warning("W052", state.tokens.next, this.value);
-
- if (!state.option.asi)
- nolinebreak(this);
-
- if (state.tokens.next.id !== ";") {
- if (state.tokens.curr.line === state.tokens.next.line) {
- if (funct[v] !== "label") {
- warning("W090", state.tokens.next, v);
- } else if (scope[v] !== funct) {
- warning("W091", state.tokens.next, v);
- }
- this.first = state.tokens.next;
- advance();
- }
- }
- reachable("break");
- return this;
- }).exps = true;
-
-
- stmt("continue", function () {
- var v = state.tokens.next.value;
-
- if (funct["(breakage)"] === 0)
- warning("W052", state.tokens.next, this.value);
-
- if (!state.option.asi)
- nolinebreak(this);
-
- if (state.tokens.next.id !== ";") {
- if (state.tokens.curr.line === state.tokens.next.line) {
- if (funct[v] !== "label") {
- warning("W090", state.tokens.next, v);
- } else if (scope[v] !== funct) {
- warning("W091", state.tokens.next, v);
- }
- this.first = state.tokens.next;
- advance();
- }
- } else if (!funct["(loopage)"]) {
- warning("W052", state.tokens.next, this.value);
- }
- reachable("continue");
- return this;
- }).exps = true;
-
-
- stmt("return", function () {
- if (this.line === state.tokens.next.line) {
- if (state.tokens.next.id === "(regexp)")
- warning("W092");
-
- if (state.tokens.next.id !== ";" && !state.tokens.next.reach) {
- nonadjacent(state.tokens.curr, state.tokens.next);
- this.first = expression(0);
-
- if (this.first &&
- this.first.type === "(punctuator)" && this.first.value === "=" && !state.option.boss) {
- warningAt("W093", this.first.line, this.first.character);
- }
- }
- } else {
- if (state.tokens.next.type === "(punctuator)" &&
- ["[", "{", "+", "-"].indexOf(state.tokens.next.value) > -1) {
- nolinebreak(this); // always warn (Line breaking error)
- }
- }
- reachable("return");
- return this;
- }).exps = true;
-
- stmt("yield", function () {
- if (state.option.inESNext(true) && funct["(generator)"] !== true) {
- error("E046", state.tokens.curr, "yield");
- } else if (!state.option.inESNext()) {
- warning("W104", state.tokens.curr, "yield");
- }
- funct["(generator)"] = "yielded";
- if (this.line === state.tokens.next.line) {
- if (state.tokens.next.id === "(regexp)")
- warning("W092");
-
- if (state.tokens.next.id !== ";" && !state.tokens.next.reach) {
- nonadjacent(state.tokens.curr, state.tokens.next);
- this.first = expression(0);
-
- if (this.first.type === "(punctuator)" && this.first.value === "=" && !state.option.boss) {
- warningAt("W093", this.first.line, this.first.character);
- }
- }
- } else if (!state.option.asi) {
- nolinebreak(this); // always warn (Line breaking error)
- }
- return this;
- }).exps = true;
-
-
- stmt("throw", function () {
- nolinebreak(this);
- nonadjacent(state.tokens.curr, state.tokens.next);
- this.first = expression(20);
- reachable("throw");
- return this;
- }).exps = true;
-
- // Future Reserved Words
-
- FutureReservedWord("abstract");
- FutureReservedWord("boolean");
- FutureReservedWord("byte");
- FutureReservedWord("char");
- FutureReservedWord("class", { es5: true, nud: classdef });
- FutureReservedWord("double");
- FutureReservedWord("enum", { es5: true });
- FutureReservedWord("export", { es5: true });
- FutureReservedWord("extends", { es5: true });
- FutureReservedWord("final");
- FutureReservedWord("float");
- FutureReservedWord("goto");
- FutureReservedWord("implements", { es5: true, strictOnly: true });
- FutureReservedWord("import", { es5: true });
- FutureReservedWord("int");
- FutureReservedWord("interface", { es5: true, strictOnly: true });
- FutureReservedWord("long");
- FutureReservedWord("native");
- FutureReservedWord("package", { es5: true, strictOnly: true });
- FutureReservedWord("private", { es5: true, strictOnly: true });
- FutureReservedWord("protected", { es5: true, strictOnly: true });
- FutureReservedWord("public", { es5: true, strictOnly: true });
- FutureReservedWord("short");
- FutureReservedWord("static", { es5: true, strictOnly: true });
- FutureReservedWord("super", { es5: true });
- FutureReservedWord("synchronized");
- FutureReservedWord("throws");
- FutureReservedWord("transient");
- FutureReservedWord("volatile");
-
- // this function is used to determine wether a squarebracket or a curlybracket
- // expression is a comprehension array, destructuring assignment or a json value.
-
- var lookupBlockType = function () {
- var pn, pn1;
- var i = 0;
- var bracketStack = 0;
- var ret = {};
- if (_.contains(["[", "{"], state.tokens.curr.value))
- bracketStack += 1;
- if (_.contains(["[", "{"], state.tokens.next.value))
- bracketStack += 1;
- if (_.contains(["]", "}"], state.tokens.next.value))
- bracketStack -= 1;
- do {
- pn = peek(i);
- pn1 = peek(i + 1);
- i = i + 1;
- if (_.contains(["[", "{"], pn.value)) {
- bracketStack += 1;
- } else if (_.contains(["]", "}"], pn.value)) {
- bracketStack -= 1;
- }
- if (pn.identifier && pn.value === "for" && bracketStack === 1) {
- ret.isCompArray = true;
- ret.notJson = true;
- break;
- }
- if (_.contains(["}", "]"], pn.value) && pn1.value === "=") {
- ret.isDestAssign = true;
- ret.notJson = true;
- break;
- }
- if (pn.value === ";") {
- ret.isBlock = true;
- ret.notJson = true;
- }
- } while (bracketStack > 0 && pn.id !== "(end)" && i < 15);
- return ret;
- };
-
- // Check whether this function has been reached for a destructuring assign with undeclared values
- function destructuringAssignOrJsonValue() {
- // lookup for the assignment (esnext only)
- // if it has semicolons, it is a block, so go parse it as a block
- // or it's not a block, but there are assignments, check for undeclared variables
-
- var block = lookupBlockType();
- if (block.notJson) {
- if (!state.option.inESNext() && block.isDestAssign) {
- warning("W104", state.tokens.curr, "destructuring assignment");
- }
- statements();
- // otherwise parse json value
- } else {
- state.option.laxbreak = true;
- state.jsonMode = true;
- jsonValue();
- }
- }
-
- // array comprehension parsing function
- // parses and defines the three states of the list comprehension in order
- // to avoid defining global variables, but keeping them to the list comprehension scope
- // only. The order of the states are as follows:
- // * "use" which will be the returned iterative part of the list comprehension
- // * "define" which will define the variables local to the list comprehension
- // * "filter" which will help filter out values
-
- var arrayComprehension = function () {
- var CompArray = function () {
- this.mode = "use";
- this.variables = [];
- };
- var _carrays = [];
- var _current;
- function declare(v) {
- var l = _current.variables.filter(function (elt) {
- // if it has, change its undef state
- if (elt.value === v) {
- elt.undef = false;
- return v;
- }
- }).length;
- return l !== 0;
- }
- function use(v) {
- var l = _current.variables.filter(function (elt) {
- // and if it has been defined
- if (elt.value === v && !elt.undef) {
- if (elt.unused === true) {
- elt.unused = false;
- }
- return v;
- }
- }).length;
- // otherwise we warn about it
- return (l === 0);
- }
- return {stack: function () {
- _current = new CompArray();
- _carrays.push(_current);
- },
- unstack: function () {
- _current.variables.filter(function (v) {
- if (v.unused)
- warning("W098", v.token, v.value);
- if (v.undef)
- isundef(v.funct, "W117", v.token, v.value);
- });
- _carrays.splice(_carrays[_carrays.length - 1], 1);
- _current = _carrays[_carrays.length - 1];
- },
- setState: function (s) {
- if (_.contains(["use", "define", "filter"], s))
- _current.mode = s;
- },
- check: function (v) {
- // When we are in "use" state of the list comp, we enqueue that var
- if (_current && _current.mode === "use") {
- _current.variables.push({funct: funct,
- token: state.tokens.curr,
- value: v,
- undef: true,
- unused: false});
- return true;
- // When we are in "define" state of the list comp,
- } else if (_current && _current.mode === "define") {
- // check if the variable has been used previously
- if (!declare(v)) {
- _current.variables.push({funct: funct,
- token: state.tokens.curr,
- value: v,
- undef: false,
- unused: true});
- }
- return true;
- // When we are in "filter" state,
- } else if (_current && _current.mode === "filter") {
- // we check whether current variable has been declared
- if (use(v)) {
- // if not we warn about it
- isundef(funct, "W117", state.tokens.curr, v);
- }
- return true;
- }
- return false;
- }
- };
- };
-
-
- // Parse JSON
-
- function jsonValue() {
-
- function jsonObject() {
- var o = {}, t = state.tokens.next;
- advance("{");
- if (state.tokens.next.id !== "}") {
- for (;;) {
- if (state.tokens.next.id === "(end)") {
- error("E026", state.tokens.next, t.line);
- } else if (state.tokens.next.id === "}") {
- warning("W094", state.tokens.curr);
- break;
- } else if (state.tokens.next.id === ",") {
- error("E028", state.tokens.next);
- } else if (state.tokens.next.id !== "(string)") {
- warning("W095", state.tokens.next, state.tokens.next.value);
- }
- if (o[state.tokens.next.value] === true) {
- warning("W075", state.tokens.next, state.tokens.next.value);
- } else if ((state.tokens.next.value === "__proto__" &&
- !state.option.proto) || (state.tokens.next.value === "__iterator__" &&
- !state.option.iterator)) {
- warning("W096", state.tokens.next, state.tokens.next.value);
- } else {
- o[state.tokens.next.value] = true;
- }
- advance();
- advance(":");
- jsonValue();
- if (state.tokens.next.id !== ",") {
- break;
- }
- advance(",");
- }
- }
- advance("}");
- }
-
- function jsonArray() {
- var t = state.tokens.next;
- advance("[");
- if (state.tokens.next.id !== "]") {
- for (;;) {
- if (state.tokens.next.id === "(end)") {
- error("E027", state.tokens.next, t.line);
- } else if (state.tokens.next.id === "]") {
- warning("W094", state.tokens.curr);
- break;
- } else if (state.tokens.next.id === ",") {
- error("E028", state.tokens.next);
- }
- jsonValue();
- if (state.tokens.next.id !== ",") {
- break;
- }
- advance(",");
- }
- }
- advance("]");
- }
-
- switch (state.tokens.next.id) {
- case "{":
- jsonObject();
- break;
- case "[":
- jsonArray();
- break;
- case "true":
- case "false":
- case "null":
- case "(number)":
- case "(string)":
- advance();
- break;
- case "-":
- advance("-");
- if (state.tokens.curr.character !== state.tokens.next.from) {
- warning("W011", state.tokens.curr);
- }
- adjacent(state.tokens.curr, state.tokens.next);
- advance("(number)");
- break;
- default:
- error("E003", state.tokens.next);
- }
- }
-
- var blockScope = function () {
- var _current = {};
- var _variables = [_current];
-
- function _checkBlockLabels() {
- for (var t in _current) {
- if (_current[t]["(type)"] === "unused") {
- if (state.option.unused) {
- var tkn = _current[t]["(token)"];
- var line = tkn.line;
- var chr = tkn.character;
- warningAt("W098", line, chr, t);
- }
- }
- }
- }
-
- return {
- stack: function () {
- _current = {};
- _variables.push(_current);
- },
-
- unstack: function () {
- _checkBlockLabels();
- _variables.splice(_variables.length - 1, 1);
- _current = _.last(_variables);
- },
-
- getlabel: function (l) {
- for (var i = _variables.length - 1 ; i >= 0; --i) {
- if (_.has(_variables[i], l)) {
- return _variables[i];
- }
- }
- },
-
- current: {
- has: function (t) {
- return _.has(_current, t);
- },
- add: function (t, type, tok) {
- _current[t] = { "(type)" : type,
- "(token)": tok };
- }
- }
- };
- };
-
- // The actual JSHINT function itself.
- var itself = function (s, o, g) {
- var a, i, k, x;
- var optionKeys;
- var newOptionObj = {};
- var newIgnoredObj = {};
-
- state.reset();
-
- if (o && o.scope) {
- JSHINT.scope = o.scope;
- } else {
- JSHINT.errors = [];
- JSHINT.undefs = [];
- JSHINT.internals = [];
- JSHINT.blacklist = {};
- JSHINT.scope = "(main)";
- }
-
- predefined = Object.create(null);
- combine(predefined, vars.ecmaIdentifiers);
- combine(predefined, vars.reservedVars);
-
- combine(predefined, g || {});
-
- declared = Object.create(null);
- exported = Object.create(null);
-
- if (o) {
- a = o.predef;
- if (a) {
- if (!Array.isArray(a) && typeof a === "object") {
- a = Object.keys(a);
- }
-
- a.forEach(function (item) {
- var slice, prop;
-
- if (item[0] === "-") {
- slice = item.slice(1);
- JSHINT.blacklist[slice] = slice;
- } else {
- prop = Object.getOwnPropertyDescriptor(o.predef, item);
- predefined[item] = prop ? prop.value : false;
- }
- });
- }
-
- optionKeys = Object.keys(o);
- for (x = 0; x < optionKeys.length; x++) {
- if (/^-W\d{3}$/g.test(optionKeys[x])) {
- newIgnoredObj[optionKeys[x].slice(1)] = true;
- } else {
- newOptionObj[optionKeys[x]] = o[optionKeys[x]];
-
- if (optionKeys[x] === "newcap" && o[optionKeys[x]] === false)
- newOptionObj["(explicitNewcap)"] = true;
-
- if (optionKeys[x] === "indent")
- newOptionObj["(explicitIndent)"] = o[optionKeys[x]] === false ? false : true;
- }
- }
- }
-
- state.option = newOptionObj;
- state.ignored = newIgnoredObj;
-
- state.option.indent = state.option.indent || 4;
- state.option.maxerr = state.option.maxerr || 50;
-
- indent = 1;
- global = Object.create(predefined);
- scope = global;
- funct = {
- "(global)": true,
- "(name)": "(global)",
- "(scope)": scope,
- "(breakage)": 0,
- "(loopage)": 0,
- "(tokens)": {},
- "(metrics)": createMetrics(state.tokens.next),
- "(blockscope)": blockScope(),
- "(comparray)": arrayComprehension()
- };
- functions = [funct];
- urls = [];
- stack = null;
- member = {};
- membersOnly = null;
- implied = {};
- inblock = false;
- lookahead = [];
- warnings = 0;
- unuseds = [];
-
- if (!isString(s) && !Array.isArray(s)) {
- errorAt("E004", 0);
- return false;
- }
-
- api = {
- get isJSON() {
- return state.jsonMode;
- },
-
- getOption: function (name) {
- return state.option[name] || null;
- },
-
- getCache: function (name) {
- return state.cache[name];
- },
-
- setCache: function (name, value) {
- state.cache[name] = value;
- },
-
- warn: function (code, data) {
- warningAt.apply(null, [ code, data.line, data.char ].concat(data.data));
- },
-
- on: function (names, listener) {
- names.split(" ").forEach(function (name) {
- emitter.on(name, listener);
- }.bind(this));
- }
- };
-
- emitter.removeAllListeners();
- (extraModules || []).forEach(function (func) {
- func(api);
- });
-
- state.tokens.prev = state.tokens.curr = state.tokens.next = state.syntax["(begin)"];
-
- lex = new Lexer(s);
-
- lex.on("warning", function (ev) {
- warningAt.apply(null, [ ev.code, ev.line, ev.character].concat(ev.data));
- });
-
- lex.on("error", function (ev) {
- errorAt.apply(null, [ ev.code, ev.line, ev.character ].concat(ev.data));
- });
-
- lex.on("fatal", function (ev) {
- quit("E041", ev.line, ev.from);
- });
-
- lex.on("Identifier", function (ev) {
- emitter.emit("Identifier", ev);
- });
-
- lex.on("String", function (ev) {
- emitter.emit("String", ev);
- });
-
- lex.on("Number", function (ev) {
- emitter.emit("Number", ev);
- });
-
- lex.start();
-
- // Check options
- for (var name in o) {
- if (_.has(o, name)) {
- checkOption(name, state.tokens.curr);
- }
- }
-
- assume();
-
- // combine the passed globals after we've assumed all our options
- combine(predefined, g || {});
-
- //reset values
- comma.first = true;
-
- try {
- advance();
- switch (state.tokens.next.id) {
- case "{":
- case "[":
- destructuringAssignOrJsonValue();
- break;
- default:
- directives();
-
- if (state.directive["use strict"]) {
- if (!state.option.globalstrict && !state.option.node) {
- warning("W097", state.tokens.prev);
- }
- }
-
- statements();
- }
- advance((state.tokens.next && state.tokens.next.value !== ".") ? "(end)" : undefined);
- funct["(blockscope)"].unstack();
-
- var markDefined = function (name, context) {
- do {
- if (typeof context[name] === "string") {
- // JSHINT marks unused variables as 'unused' and
- // unused function declaration as 'unction'. This
- // code changes such instances back 'var' and
- // 'closure' so that the code in JSHINT.data()
- // doesn't think they're unused.
-
- if (context[name] === "unused")
- context[name] = "var";
- else if (context[name] === "unction")
- context[name] = "closure";
-
- return true;
- }
-
- context = context["(context)"];
- } while (context);
-
- return false;
- };
-
- var clearImplied = function (name, line) {
- if (!implied[name])
- return;
-
- var newImplied = [];
- for (var i = 0; i < implied[name].length; i += 1) {
- if (implied[name][i] !== line)
- newImplied.push(implied[name][i]);
- }
-
- if (newImplied.length === 0)
- delete implied[name];
- else
- implied[name] = newImplied;
- };
-
- var warnUnused = function (name, tkn, type, unused_opt) {
- var line = tkn.line;
- var chr = tkn.character;
-
- if (unused_opt === undefined) {
- unused_opt = state.option.unused;
- }
-
- if (unused_opt === true) {
- unused_opt = "last-param";
- }
-
- var warnable_types = {
- "vars": ["var"],
- "last-param": ["var", "param"],
- "strict": ["var", "param", "last-param"]
- };
-
- if (unused_opt) {
- if (warnable_types[unused_opt] && warnable_types[unused_opt].indexOf(type) !== -1) {
- warningAt("W098", line, chr, name);
- }
- }
-
- unuseds.push({
- name: name,
- line: line,
- character: chr
- });
- };
-
- var checkUnused = function (func, key) {
- var type = func[key];
- var tkn = func["(tokens)"][key];
-
- if (key.charAt(0) === "(")
- return;
-
- if (type !== "unused" && type !== "unction")
- return;
-
- // Params are checked separately from other variables.
- if (func["(params)"] && func["(params)"].indexOf(key) !== -1)
- return;
-
- // Variable is in global scope and defined as exported.
- if (func["(global)"] && _.has(exported, key)) {
- return;
- }
-
- warnUnused(key, tkn, "var");
- };
-
- // Check queued 'x is not defined' instances to see if they're still undefined.
- for (i = 0; i < JSHINT.undefs.length; i += 1) {
- k = JSHINT.undefs[i].slice(0);
-
- if (markDefined(k[2].value, k[0])) {
- clearImplied(k[2].value, k[2].line);
- } else if (state.option.undef) {
- warning.apply(warning, k.slice(1));
- }
- }
-
- functions.forEach(function (func) {
- if (func["(unusedOption)"] === false) {
- return;
- }
-
- for (var key in func) {
- if (_.has(func, key)) {
- checkUnused(func, key);
- }
- }
-
- if (!func["(params)"])
- return;
-
- var params = func["(params)"].slice();
- var param = params.pop();
- var type, unused_opt;
-
- while (param) {
- type = func[param];
- unused_opt = func["(unusedOption)"] || state.option.unused;
- unused_opt = unused_opt === true ? "last-param" : unused_opt;
-
- // 'undefined' is a special case for (function (window, undefined) { ... })();
- // patterns.
-
- if (param === "undefined")
- return;
-
- if (type === "unused" || type === "unction") {
- warnUnused(param, func["(tokens)"][param], "param", func["(unusedOption)"]);
- } else if (unused_opt === "last-param") {
- return;
- }
-
- param = params.pop();
- }
- });
-
- for (var key in declared) {
- if (_.has(declared, key) && !_.has(global, key)) {
- warnUnused(key, declared[key], "var");
- }
- }
-
- } catch (err) {
- if (err && err.name === "JSHintError") {
- var nt = state.tokens.next || {};
- JSHINT.errors.push({
- scope : "(main)",
- raw : err.raw,
- reason : err.message,
- line : err.line || nt.line,
- character : err.character || nt.from
- }, null);
- } else {
- throw err;
- }
- }
-
- // Loop over the listed "internals", and check them as well.
-
- if (JSHINT.scope === "(main)") {
- o = o || {};
-
- for (i = 0; i < JSHINT.internals.length; i += 1) {
- k = JSHINT.internals[i];
- o.scope = k.elem;
- itself(k.value, o, g);
- }
- }
-
- return JSHINT.errors.length === 0;
- };
-
- // Modules.
- itself.addModule = function (func) {
- extraModules.push(func);
- };
-
- itself.addModule(style.register);
-
- // Data summary.
- itself.data = function () {
- var data = {
- functions: [],
- options: state.option
- };
- var implieds = [];
- var members = [];
- var fu, f, i, j, n, globals;
-
- if (itself.errors.length) {
- data.errors = itself.errors;
- }
-
- if (state.jsonMode) {
- data.json = true;
- }
-
- for (n in implied) {
- if (_.has(implied, n)) {
- implieds.push({
- name: n,
- line: implied[n]
- });
- }
- }
-
- if (implieds.length > 0) {
- data.implieds = implieds;
- }
-
- if (urls.length > 0) {
- data.urls = urls;
- }
-
- globals = Object.keys(scope);
- if (globals.length > 0) {
- data.globals = globals;
- }
-
- for (i = 1; i < functions.length; i += 1) {
- f = functions[i];
- fu = {};
-
- for (j = 0; j < functionicity.length; j += 1) {
- fu[functionicity[j]] = [];
- }
-
- for (j = 0; j < functionicity.length; j += 1) {
- if (fu[functionicity[j]].length === 0) {
- delete fu[functionicity[j]];
- }
- }
-
- fu.name = f["(name)"];
- fu.param = f["(params)"];
- fu.line = f["(line)"];
- fu.character = f["(character)"];
- fu.last = f["(last)"];
- fu.lastcharacter = f["(lastcharacter)"];
- data.functions.push(fu);
- }
-
- if (unuseds.length > 0) {
- data.unused = unuseds;
- }
-
- members = [];
- for (n in member) {
- if (typeof member[n] === "number") {
- data.member = member;
- break;
- }
- }
-
- return data;
- };
-
- itself.jshint = itself;
-
- return itself;
-}());
-
-// Make JSHINT a Node module, if possible.
-if (typeof exports === "object" && exports) {
- exports.JSHINT = JSHINT;
-}
-
-})()
-},{"events":2,"../shared/vars.js":3,"./lex.js":10,"./reg.js":6,"./state.js":4,"../shared/messages.js":12,"./style.js":5,"console-browserify":7,"underscore":11}],12:[function(require,module,exports){
-(function(){"use strict";
-
-var _ = require("underscore");
-
-var errors = {
- // JSHint options
- E001: "Bad option: '{a}'.",
- E002: "Bad option value.",
-
- // JSHint input
- E003: "Expected a JSON value.",
- E004: "Input is neither a string nor an array of strings.",
- E005: "Input is empty.",
- E006: "Unexpected early end of program.",
-
- // Strict mode
- E007: "Missing \"use strict\" statement.",
- E008: "Strict violation.",
- E009: "Option 'validthis' can't be used in a global scope.",
- E010: "'with' is not allowed in strict mode.",
-
- // Constants
- E011: "const '{a}' has already been declared.",
- E012: "const '{a}' is initialized to 'undefined'.",
- E013: "Attempting to override '{a}' which is a constant.",
-
- // Regular expressions
- E014: "A regular expression literal can be confused with '/='.",
- E015: "Unclosed regular expression.",
- E016: "Invalid regular expression.",
-
- // Tokens
- E017: "Unclosed comment.",
- E018: "Unbegun comment.",
- E019: "Unmatched '{a}'.",
- E020: "Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.",
- E021: "Expected '{a}' and instead saw '{b}'.",
- E022: "Line breaking error '{a}'.",
- E023: "Missing '{a}'.",
- E024: "Unexpected '{a}'.",
- E025: "Missing ':' on a case clause.",
- E026: "Missing '}' to match '{' from line {a}.",
- E027: "Missing ']' to match '[' form line {a}.",
- E028: "Illegal comma.",
- E029: "Unclosed string.",
-
- // Everything else
- E030: "Expected an identifier and instead saw '{a}'.",
- E031: "Bad assignment.", // FIXME: Rephrase
- E032: "Expected a small integer or 'false' and instead saw '{a}'.",
- E033: "Expected an operator and instead saw '{a}'.",
- E034: "get/set are ES5 features.",
- E035: "Missing property name.",
- E036: "Expected to see a statement and instead saw a block.",
- E037: "Constant {a} was not declared correctly.",
- E038: "Variable {a} was not declared correctly.",
- E039: "Function declarations are not invocable. Wrap the whole function invocation in parens.",
- E040: "Each value should have its own case label.",
- E041: "Unrecoverable syntax error.",
- E042: "Stopping.",
- E043: "Too many errors.",
- E044: "'{a}' is already defined and can't be redefined.",
- E045: "Invalid for each loop.",
- E046: "A yield statement shall be within a generator function (with syntax: `function*`)",
- E047: "A generator function shall contain a yield statement.",
- E048: "Let declaration not directly within block.",
- E049: "A {a} cannot be named '{b}'."
-};
-
-var warnings = {
- W001: "'hasOwnProperty' is a really bad name.",
- W002: "Value of '{a}' may be overwritten in IE.",
- W003: "'{a}' was used before it was defined.",
- W004: "'{a}' is already defined.",
- W005: "A dot following a number can be confused with a decimal point.",
- W006: "Confusing minuses.",
- W007: "Confusing pluses.",
- W008: "A leading decimal point can be confused with a dot: '{a}'.",
- W009: "The array literal notation [] is preferrable.",
- W010: "The object literal notation {} is preferrable.",
- W011: "Unexpected space after '{a}'.",
- W012: "Unexpected space before '{a}'.",
- W013: "Missing space after '{a}'.",
- W014: "Bad line breaking before '{a}'.",
- W015: "Expected '{a}' to have an indentation at {b} instead at {c}.",
- W016: "Unexpected use of '{a}'.",
- W017: "Bad operand.",
- W018: "Confusing use of '{a}'.",
- W019: "Use the isNaN function to compare with NaN.",
- W020: "Read only.",
- W021: "'{a}' is a function.",
- W022: "Do not assign to the exception parameter.",
- W023: "Expected an identifier in an assignment and instead saw a function invocation.",
- W024: "Expected an identifier and instead saw '{a}' (a reserved word).",
- W025: "Missing name in function declaration.",
- W026: "Inner functions should be listed at the top of the outer function.",
- W027: "Unreachable '{a}' after '{b}'.",
- W028: "Label '{a}' on {b} statement.",
- W030: "Expected an assignment or function call and instead saw an expression.",
- W031: "Do not use 'new' for side effects.",
- W032: "Unnecessary semicolon.",
- W033: "Missing semicolon.",
- W034: "Unnecessary directive \"{a}\".",
- W035: "Empty block.",
- W036: "Unexpected /*member '{a}'.",
- W037: "'{a}' is a statement label.",
- W038: "'{a}' used out of scope.",
- W039: "'{a}' is not allowed.",
- W040: "Possible strict violation.",
- W041: "Use '{a}' to compare with '{b}'.",
- W042: "Avoid EOL escaping.",
- W043: "Bad escaping of EOL. Use option multistr if needed.",
- W044: "Bad or unnecessary escaping.",
- W045: "Bad number '{a}'.",
- W046: "Don't use extra leading zeros '{a}'.",
- W047: "A trailing decimal point can be confused with a dot: '{a}'.",
- W048: "Unexpected control character in regular expression.",
- W049: "Unexpected escaped character '{a}' in regular expression.",
- W050: "JavaScript URL.",
- W051: "Variables should not be deleted.",
- W052: "Unexpected '{a}'.",
- W053: "Do not use {a} as a constructor.",
- W054: "The Function constructor is a form of eval.",
- W055: "A constructor name should start with an uppercase letter.",
- W056: "Bad constructor.",
- W057: "Weird construction. Is 'new' unnecessary?",
- W058: "Missing '()' invoking a constructor.",
- W059: "Avoid arguments.{a}.",
- W060: "document.write can be a form of eval.",
- W061: "eval can be harmful.",
- W062: "Wrap an immediate function invocation in parens " +
- "to assist the reader in understanding that the expression " +
- "is the result of a function, and not the function itself.",
- W063: "Math is not a function.",
- W064: "Missing 'new' prefix when invoking a constructor.",
- W065: "Missing radix parameter.",
- W066: "Implied eval. Consider passing a function instead of a string.",
- W067: "Bad invocation.",
- W068: "Wrapping non-IIFE function literals in parens is unnecessary.",
- W069: "['{a}'] is better written in dot notation.",
- W070: "Extra comma. (it breaks older versions of IE)",
- W071: "This function has too many statements. ({a})",
- W072: "This function has too many parameters. ({a})",
- W073: "Blocks are nested too deeply. ({a})",
- W074: "This function's cyclomatic complexity is too high. ({a})",
- W075: "Duplicate key '{a}'.",
- W076: "Unexpected parameter '{a}' in get {b} function.",
- W077: "Expected a single parameter in set {a} function.",
- W078: "Setter is defined without getter.",
- W079: "Redefinition of '{a}'.",
- W080: "It's not necessary to initialize '{a}' to 'undefined'.",
- W081: "Too many var statements.",
- W082: "Function declarations should not be placed in blocks. " +
- "Use a function expression or move the statement to the top of " +
- "the outer function.",
- W083: "Don't make functions within a loop.",
- W084: "Expected a conditional expression and instead saw an assignment.",
- W085: "Don't use 'with'.",
- W086: "Expected a 'break' statement before '{a}'.",
- W087: "Forgotten 'debugger' statement?",
- W088: "Creating global 'for' variable. Should be 'for (var {a} ...'.",
- W089: "The body of a for in should be wrapped in an if statement to filter " +
- "unwanted properties from the prototype.",
- W090: "'{a}' is not a statement label.",
- W091: "'{a}' is out of scope.",
- W092: "Wrap the /regexp/ literal in parens to disambiguate the slash operator.",
- W093: "Did you mean to return a conditional instead of an assignment?",
- W094: "Unexpected comma.",
- W095: "Expected a string and instead saw {a}.",
- W096: "The '{a}' key may produce unexpected results.",
- W097: "Use the function form of \"use strict\".",
- W098: "'{a}' is defined but never used.",
- W099: "Mixed spaces and tabs.",
- W100: "This character may get silently deleted by one or more browsers.",
- W101: "Line is too long.",
- W102: "Trailing whitespace.",
- W103: "The '{a}' property is deprecated.",
- W104: "'{a}' is only available in JavaScript 1.7.",
- W105: "Unexpected {a} in '{b}'.",
- W106: "Identifier '{a}' is not in camel case.",
- W107: "Script URL.",
- W108: "Strings must use doublequote.",
- W109: "Strings must use singlequote.",
- W110: "Mixed double and single quotes.",
- W112: "Unclosed string.",
- W113: "Control character in string: {a}.",
- W114: "Avoid {a}.",
- W115: "Octal literals are not allowed in strict mode.",
- W116: "Expected '{a}' and instead saw '{b}'.",
- W117: "'{a}' is not defined.",
- W118: "'{a}' is only available in Mozilla JavaScript extensions (use moz option).",
- W119: "'{a}' is only available in ES6 (use esnext option)."
-};
-
-var info = {
- I001: "Comma warnings can be turned off with 'laxcomma'.",
- I002: "Reserved words as properties can be used under the 'es5' option.",
- I003: "ES5 option is now set per default"
-};
-
-exports.errors = {};
-exports.warnings = {};
-exports.info = {};
-
-_.each(errors, function (desc, code) {
- exports.errors[code] = { code: code, desc: desc };
-});
-
-_.each(warnings, function (desc, code) {
- exports.warnings[code] = { code: code, desc: desc };
-});
-
-_.each(info, function (desc, code) {
- exports.info[code] = { code: code, desc: desc };
-});
-
-})()
-},{"underscore":11}],8:[function(require,module,exports){
-var events = require('events');
-
-exports.isArray = isArray;
-exports.isDate = function(obj){return Object.prototype.toString.call(obj) === '[object Date]'};
-exports.isRegExp = function(obj){return Object.prototype.toString.call(obj) === '[object RegExp]'};
-
-
-exports.print = function () {};
-exports.puts = function () {};
-exports.debug = function() {};
-
-exports.inspect = function(obj, showHidden, depth, colors) {
- var seen = [];
-
- var stylize = function(str, styleType) {
- // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
- var styles =
- { 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39] };
-
- var style =
- { 'special': 'cyan',
- 'number': 'blue',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red' }[styleType];
-
- if (style) {
- return '\033[' + styles[style][0] + 'm' + str +
- '\033[' + styles[style][1] + 'm';
- } else {
- return str;
- }
- };
- if (! colors) {
- stylize = function(str, styleType) { return str; };
- }
-
- function format(value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (value && typeof value.inspect === 'function' &&
- // Filter out the util module, it's inspect function is special
- value !== exports &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- return value.inspect(recurseTimes);
- }
-
- // Primitive types cannot have properties
- switch (typeof value) {
- case 'undefined':
- return stylize('undefined', 'undefined');
-
- case 'string':
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return stylize(simple, 'string');
-
- case 'number':
- return stylize('' + value, 'number');
-
- case 'boolean':
- return stylize('' + value, 'boolean');
- }
- // For some reason typeof null is "object", so special case here.
- if (value === null) {
- return stylize('null', 'null');
- }
-
- // Look up the keys of the object.
- var visible_keys = Object_keys(value);
- var keys = showHidden ? Object_getOwnPropertyNames(value) : visible_keys;
-
- // Functions without properties can be shortcutted.
- if (typeof value === 'function' && keys.length === 0) {
- if (isRegExp(value)) {
- return stylize('' + value, 'regexp');
- } else {
- var name = value.name ? ': ' + value.name : '';
- return stylize('[Function' + name + ']', 'special');
- }
- }
-
- // Dates without properties can be shortcutted
- if (isDate(value) && keys.length === 0) {
- return stylize(value.toUTCString(), 'date');
- }
-
- var base, type, braces;
- // Determine the object type
- if (isArray(value)) {
- type = 'Array';
- braces = ['[', ']'];
- } else {
- type = 'Object';
- braces = ['{', '}'];
- }
-
- // Make functions say that they are functions
- if (typeof value === 'function') {
- var n = value.name ? ': ' + value.name : '';
- base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';
- } else {
- base = '';
- }
-
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + value.toUTCString();
- }
-
- if (keys.length === 0) {
- return braces[0] + base + braces[1];
- }
-
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return stylize('' + value, 'regexp');
- } else {
- return stylize('[Object]', 'special');
- }
- }
-
- seen.push(value);
-
- var output = keys.map(function(key) {
- var name, str;
- if (value.__lookupGetter__) {
- if (value.__lookupGetter__(key)) {
- if (value.__lookupSetter__(key)) {
- str = stylize('[Getter/Setter]', 'special');
- } else {
- str = stylize('[Getter]', 'special');
- }
- } else {
- if (value.__lookupSetter__(key)) {
- str = stylize('[Setter]', 'special');
- }
- }
- }
- if (visible_keys.indexOf(key) < 0) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (seen.indexOf(value[key]) < 0) {
- if (recurseTimes === null) {
- str = format(value[key]);
- } else {
- str = format(value[key], recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (isArray(value)) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = stylize('[Circular]', 'special');
- }
- }
- if (typeof name === 'undefined') {
- if (type === 'Array' && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = stylize(name, 'string');
- }
- }
-
- return name + ': ' + str;
- });
-
- seen.pop();
-
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.length + 1;
- }, 0);
-
- if (length > 50) {
- output = braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
-
- } else {
- output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
- }
-
- return output;
- }
- return format(obj, (typeof depth === 'undefined' ? 2 : depth));
-};
-
-
-function isArray(ar) {
- return ar instanceof Array ||
- Array.isArray(ar) ||
- (ar && ar !== Object.prototype && isArray(ar.__proto__));
-}
-
-
-function isRegExp(re) {
- return re instanceof RegExp ||
- (typeof re === 'object' && Object.prototype.toString.call(re) === '[object RegExp]');
-}
-
-
-function isDate(d) {
- if (d instanceof Date) return true;
- if (typeof d !== 'object') return false;
- var properties = Date.prototype && Object_getOwnPropertyNames(Date.prototype);
- var proto = d.__proto__ && Object_getOwnPropertyNames(d.__proto__);
- return JSON.stringify(proto) === JSON.stringify(properties);
-}
-
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}
-
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
-
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-}
-
-exports.log = function (msg) {};
-
-exports.pump = null;
-
-var Object_keys = Object.keys || function (obj) {
- var res = [];
- for (var key in obj) res.push(key);
- return res;
-};
-
-var Object_getOwnPropertyNames = Object.getOwnPropertyNames || function (obj) {
- var res = [];
- for (var key in obj) {
- if (Object.hasOwnProperty.call(obj, key)) res.push(key);
- }
- return res;
-};
-
-var Object_create = Object.create || function (prototype, properties) {
- // from es5-shim
- var object;
- if (prototype === null) {
- object = { '__proto__' : null };
- }
- else {
- if (typeof prototype !== 'object') {
- throw new TypeError(
- 'typeof prototype[' + (typeof prototype) + '] != \'object\''
- );
- }
- var Type = function () {};
- Type.prototype = prototype;
- object = new Type();
- object.__proto__ = prototype;
- }
- if (typeof properties !== 'undefined' && Object.defineProperties) {
- Object.defineProperties(object, properties);
- }
- return object;
-};
-
-exports.inherits = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object_create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (typeof f !== 'string') {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(exports.inspect(arguments[i]));
- }
- return objects.join(' ');
- }
-
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j': return JSON.stringify(args[i++]);
- default:
- return x;
- }
- });
- for(var x = args[i]; i < len; x = args[++i]){
- if (x === null || typeof x !== 'object') {
- str += ' ' + x;
- } else {
- str += ' ' + exports.inspect(x);
- }
- }
- return str;
-};
-
-},{"events":2}],9:[function(require,module,exports){
-(function(){// UTILITY
-var util = require('util');
-var Buffer = require("buffer").Buffer;
-var pSlice = Array.prototype.slice;
-
-function objectKeys(object) {
- if (Object.keys) return Object.keys(object);
- var result = [];
- for (var name in object) {
- if (Object.prototype.hasOwnProperty.call(object, name)) {
- result.push(name);
- }
- }
- return result;
-}
-
-// 1. The assert module provides functions that throw
-// AssertionError's when particular conditions are not met. The
-// assert module must conform to the following interface.
-
-var assert = module.exports = ok;
-
-// 2. The AssertionError is defined in assert.
-// new assert.AssertionError({ message: message,
-// actual: actual,
-// expected: expected })
-
-assert.AssertionError = function AssertionError(options) {
- this.name = 'AssertionError';
- this.message = options.message;
- this.actual = options.actual;
- this.expected = options.expected;
- this.operator = options.operator;
- var stackStartFunction = options.stackStartFunction || fail;
-
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, stackStartFunction);
- }
-};
-util.inherits(assert.AssertionError, Error);
-
-function replacer(key, value) {
- if (value === undefined) {
- return '' + value;
- }
- if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) {
- return value.toString();
- }
- if (typeof value === 'function' || value instanceof RegExp) {
- return value.toString();
- }
- return value;
-}
-
-function truncate(s, n) {
- if (typeof s == 'string') {
- return s.length < n ? s : s.slice(0, n);
- } else {
- return s;
- }
-}
-
-assert.AssertionError.prototype.toString = function() {
- if (this.message) {
- return [this.name + ':', this.message].join(' ');
- } else {
- return [
- this.name + ':',
- truncate(JSON.stringify(this.actual, replacer), 128),
- this.operator,
- truncate(JSON.stringify(this.expected, replacer), 128)
- ].join(' ');
- }
-};
-
-// assert.AssertionError instanceof Error
-
-assert.AssertionError.__proto__ = Error.prototype;
-
-// At present only the three keys mentioned above are used and
-// understood by the spec. Implementations or sub modules can pass
-// other keys to the AssertionError's constructor - they will be
-// ignored.
-
-// 3. All of the following functions must throw an AssertionError
-// when a corresponding condition is not met, with a message that
-// may be undefined if not provided. All assertion methods provide
-// both the actual and expected values to the assertion error for
-// display purposes.
-
-function fail(actual, expected, message, operator, stackStartFunction) {
- throw new assert.AssertionError({
- message: message,
- actual: actual,
- expected: expected,
- operator: operator,
- stackStartFunction: stackStartFunction
- });
-}
-
-// EXTENSION! allows for well behaved errors defined elsewhere.
-assert.fail = fail;
-
-// 4. Pure assertion tests whether a value is truthy, as determined
-// by !!guard.
-// assert.ok(guard, message_opt);
-// This statement is equivalent to assert.equal(true, guard,
-// message_opt);. To test strictly for the value true, use
-// assert.strictEqual(true, guard, message_opt);.
-
-function ok(value, message) {
- if (!!!value) fail(value, true, message, '==', assert.ok);
-}
-assert.ok = ok;
-
-// 5. The equality assertion tests shallow, coercive equality with
-// ==.
-// assert.equal(actual, expected, message_opt);
-
-assert.equal = function equal(actual, expected, message) {
- if (actual != expected) fail(actual, expected, message, '==', assert.equal);
-};
-
-// 6. The non-equality assertion tests for whether two objects are not equal
-// with != assert.notEqual(actual, expected, message_opt);
-
-assert.notEqual = function notEqual(actual, expected, message) {
- if (actual == expected) {
- fail(actual, expected, message, '!=', assert.notEqual);
- }
-};
-
-// 7. The equivalence assertion tests a deep equality relation.
-// assert.deepEqual(actual, expected, message_opt);
-
-assert.deepEqual = function deepEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected)) {
- fail(actual, expected, message, 'deepEqual', assert.deepEqual);
- }
-};
-
-function _deepEqual(actual, expected) {
- // 7.1. All identical values are equivalent, as determined by ===.
- if (actual === expected) {
- return true;
-
- } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
- if (actual.length != expected.length) return false;
-
- for (var i = 0; i < actual.length; i++) {
- if (actual[i] !== expected[i]) return false;
- }
-
- return true;
-
- // 7.2. If the expected value is a Date object, the actual value is
- // equivalent if it is also a Date object that refers to the same time.
- } else if (actual instanceof Date && expected instanceof Date) {
- return actual.getTime() === expected.getTime();
-
- // 7.3. Other pairs that do not both pass typeof value == 'object',
- // equivalence is determined by ==.
- } else if (typeof actual != 'object' && typeof expected != 'object') {
- return actual == expected;
-
- // 7.4. For all other Object pairs, including Array objects, equivalence is
- // determined by having the same number of owned properties (as verified
- // with Object.prototype.hasOwnProperty.call), the same set of keys
- // (although not necessarily the same order), equivalent values for every
- // corresponding key, and an identical 'prototype' property. Note: this
- // accounts for both named and indexed properties on Arrays.
- } else {
- return objEquiv(actual, expected);
- }
-}
-
-function isUndefinedOrNull(value) {
- return value === null || value === undefined;
-}
-
-function isArguments(object) {
- return Object.prototype.toString.call(object) == '[object Arguments]';
-}
-
-function objEquiv(a, b) {
- if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
- return false;
- // an identical 'prototype' property.
- if (a.prototype !== b.prototype) return false;
- //~~~I've managed to break Object.keys through screwy arguments passing.
- // Converting to array solves the problem.
- if (isArguments(a)) {
- if (!isArguments(b)) {
- return false;
- }
- a = pSlice.call(a);
- b = pSlice.call(b);
- return _deepEqual(a, b);
- }
- try {
- var ka = objectKeys(a),
- kb = objectKeys(b),
- key, i;
- } catch (e) {//happens when one is a string literal and the other isn't
- return false;
- }
- // having the same number of owned properties (keys incorporates
- // hasOwnProperty)
- if (ka.length != kb.length)
- return false;
- //the same set of keys (although not necessarily the same order),
- ka.sort();
- kb.sort();
- //~~~cheap key test
- for (i = ka.length - 1; i >= 0; i--) {
- if (ka[i] != kb[i])
- return false;
- }
- //equivalent values for every corresponding key, and
- //~~~possibly expensive deep test
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!_deepEqual(a[key], b[key])) return false;
- }
- return true;
-}
-
-// 8. The non-equivalence assertion tests for any deep inequality.
-// assert.notDeepEqual(actual, expected, message_opt);
-
-assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
- if (_deepEqual(actual, expected)) {
- fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
- }
-};
-
-// 9. The strict equality assertion tests strict equality, as determined by ===.
-// assert.strictEqual(actual, expected, message_opt);
-
-assert.strictEqual = function strictEqual(actual, expected, message) {
- if (actual !== expected) {
- fail(actual, expected, message, '===', assert.strictEqual);
- }
-};
-
-// 10. The strict non-equality assertion tests for strict inequality, as
-// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
-
-assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
- if (actual === expected) {
- fail(actual, expected, message, '!==', assert.notStrictEqual);
- }
-};
-
-function expectedException(actual, expected) {
- if (!actual || !expected) {
- return false;
- }
-
- if (expected instanceof RegExp) {
- return expected.test(actual);
- } else if (actual instanceof expected) {
- return true;
- } else if (expected.call({}, actual) === true) {
- return true;
- }
-
- return false;
-}
-
-function _throws(shouldThrow, block, expected, message) {
- var actual;
-
- if (typeof expected === 'string') {
- message = expected;
- expected = null;
- }
-
- try {
- block();
- } catch (e) {
- actual = e;
- }
-
- message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
- (message ? ' ' + message : '.');
-
- if (shouldThrow && !actual) {
- fail('Missing expected exception' + message);
- }
-
- if (!shouldThrow && expectedException(actual, expected)) {
- fail('Got unwanted exception' + message);
- }
-
- if ((shouldThrow && actual && expected &&
- !expectedException(actual, expected)) || (!shouldThrow && actual)) {
- throw actual;
- }
-}
-
-// 11. Expected to throw an error:
-// assert.throws(block, Error_opt, message_opt);
-
-assert.throws = function(block, /*optional*/error, /*optional*/message) {
- _throws.apply(this, [true].concat(pSlice.call(arguments)));
-};
-
-// EXTENSION! This is annoying to write outside this module.
-assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
- _throws.apply(this, [false].concat(pSlice.call(arguments)));
-};
-
-assert.ifError = function(err) { if (err) {throw err;}};
-
-})()
-},{"util":8,"buffer":13}],11:[function(require,module,exports){
-(function(){// Underscore.js 1.4.4
-// http://underscorejs.org
-// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
-// Underscore may be freely distributed under the MIT license.
-
-(function() {
-
- // Baseline setup
- // --------------
-
- // Establish the root object, `window` in the browser, or `global` on the server.
- var root = this;
-
- // Save the previous value of the `_` variable.
- var previousUnderscore = root._;
-
- // Establish the object that gets returned to break out of a loop iteration.
- var breaker = {};
-
- // Save bytes in the minified (but not gzipped) version:
- var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
-
- // Create quick reference variables for speed access to core prototypes.
- var push = ArrayProto.push,
- slice = ArrayProto.slice,
- concat = ArrayProto.concat,
- toString = ObjProto.toString,
- hasOwnProperty = ObjProto.hasOwnProperty;
-
- // All **ECMAScript 5** native function implementations that we hope to use
- // are declared here.
- var
- nativeForEach = ArrayProto.forEach,
- nativeMap = ArrayProto.map,
- nativeReduce = ArrayProto.reduce,
- nativeReduceRight = ArrayProto.reduceRight,
- nativeFilter = ArrayProto.filter,
- nativeEvery = ArrayProto.every,
- nativeSome = ArrayProto.some,
- nativeIndexOf = ArrayProto.indexOf,
- nativeLastIndexOf = ArrayProto.lastIndexOf,
- nativeIsArray = Array.isArray,
- nativeKeys = Object.keys,
- nativeBind = FuncProto.bind;
-
- // Create a safe reference to the Underscore object for use below.
- var _ = function(obj) {
- if (obj instanceof _) return obj;
- if (!(this instanceof _)) return new _(obj);
- this._wrapped = obj;
- };
-
- // Export the Underscore object for **Node.js**, with
- // backwards-compatibility for the old `require()` API. If we're in
- // the browser, add `_` as a global object via a string identifier,
- // for Closure Compiler "advanced" mode.
- if (typeof exports !== 'undefined') {
- if (typeof module !== 'undefined' && module.exports) {
- exports = module.exports = _;
- }
- exports._ = _;
- } else {
- root._ = _;
- }
-
- // Current version.
- _.VERSION = '1.4.4';
-
- // Collection Functions
- // --------------------
-
- // The cornerstone, an `each` implementation, aka `forEach`.
- // Handles objects with the built-in `forEach`, arrays, and raw objects.
- // Delegates to **ECMAScript 5**'s native `forEach` if available.
- var each = _.each = _.forEach = function(obj, iterator, context) {
- if (obj == null) return;
- if (nativeForEach && obj.forEach === nativeForEach) {
- obj.forEach(iterator, context);
- } else if (obj.length === +obj.length) {
- for (var i = 0, l = obj.length; i < l; i++) {
- if (iterator.call(context, obj[i], i, obj) === breaker) return;
- }
- } else {
- for (var key in obj) {
- if (_.has(obj, key)) {
- if (iterator.call(context, obj[key], key, obj) === breaker) return;
- }
- }
- }
- };
-
- // Return the results of applying the iterator to each element.
- // Delegates to **ECMAScript 5**'s native `map` if available.
- _.map = _.collect = function(obj, iterator, context) {
- var results = [];
- if (obj == null) return results;
- if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
- each(obj, function(value, index, list) {
- results[results.length] = iterator.call(context, value, index, list);
- });
- return results;
- };
-
- var reduceError = 'Reduce of empty array with no initial value';
-
- // **Reduce** builds up a single result from a list of values, aka `inject`,
- // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
- _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
- var initial = arguments.length > 2;
- if (obj == null) obj = [];
- if (nativeReduce && obj.reduce === nativeReduce) {
- if (context) iterator = _.bind(iterator, context);
- return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
- }
- each(obj, function(value, index, list) {
- if (!initial) {
- memo = value;
- initial = true;
- } else {
- memo = iterator.call(context, memo, value, index, list);
- }
- });
- if (!initial) throw new TypeError(reduceError);
- return memo;
- };
-
- // The right-associative version of reduce, also known as `foldr`.
- // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
- _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
- var initial = arguments.length > 2;
- if (obj == null) obj = [];
- if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
- if (context) iterator = _.bind(iterator, context);
- return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
- }
- var length = obj.length;
- if (length !== +length) {
- var keys = _.keys(obj);
- length = keys.length;
- }
- each(obj, function(value, index, list) {
- index = keys ? keys[--length] : --length;
- if (!initial) {
- memo = obj[index];
- initial = true;
- } else {
- memo = iterator.call(context, memo, obj[index], index, list);
- }
- });
- if (!initial) throw new TypeError(reduceError);
- return memo;
- };
-
- // Return the first value which passes a truth test. Aliased as `detect`.
- _.find = _.detect = function(obj, iterator, context) {
- var result;
- any(obj, function(value, index, list) {
- if (iterator.call(context, value, index, list)) {
- result = value;
- return true;
- }
- });
- return result;
- };
-
- // Return all the elements that pass a truth test.
- // Delegates to **ECMAScript 5**'s native `filter` if available.
- // Aliased as `select`.
- _.filter = _.select = function(obj, iterator, context) {
- var results = [];
- if (obj == null) return results;
- if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
- each(obj, function(value, index, list) {
- if (iterator.call(context, value, index, list)) results[results.length] = value;
- });
- return results;
- };
-
- // Return all the elements for which a truth test fails.
- _.reject = function(obj, iterator, context) {
- return _.filter(obj, function(value, index, list) {
- return !iterator.call(context, value, index, list);
- }, context);
- };
-
- // Determine whether all of the elements match a truth test.
- // Delegates to **ECMAScript 5**'s native `every` if available.
- // Aliased as `all`.
- _.every = _.all = function(obj, iterator, context) {
- iterator || (iterator = _.identity);
- var result = true;
- if (obj == null) return result;
- if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
- each(obj, function(value, index, list) {
- if (!(result = result && iterator.call(context, value, index, list))) return breaker;
- });
- return !!result;
- };
-
- // Determine if at least one element in the object matches a truth test.
- // Delegates to **ECMAScript 5**'s native `some` if available.
- // Aliased as `any`.
- var any = _.some = _.any = function(obj, iterator, context) {
- iterator || (iterator = _.identity);
- var result = false;
- if (obj == null) return result;
- if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
- each(obj, function(value, index, list) {
- if (result || (result = iterator.call(context, value, index, list))) return breaker;
- });
- return !!result;
- };
-
- // Determine if the array or object contains a given value (using `===`).
- // Aliased as `include`.
- _.contains = _.include = function(obj, target) {
- if (obj == null) return false;
- if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
- return any(obj, function(value) {
- return value === target;
- });
- };
-
- // Invoke a method (with arguments) on every item in a collection.
- _.invoke = function(obj, method) {
- var args = slice.call(arguments, 2);
- var isFunc = _.isFunction(method);
- return _.map(obj, function(value) {
- return (isFunc ? method : value[method]).apply(value, args);
- });
- };
-
- // Convenience version of a common use case of `map`: fetching a property.
- _.pluck = function(obj, key) {
- return _.map(obj, function(value){ return value[key]; });
- };
-
- // Convenience version of a common use case of `filter`: selecting only objects
- // containing specific `key:value` pairs.
- _.where = function(obj, attrs, first) {
- if (_.isEmpty(attrs)) return first ? null : [];
- return _[first ? 'find' : 'filter'](obj, function(value) {
- for (var key in attrs) {
- if (attrs[key] !== value[key]) return false;
- }
- return true;
- });
- };
-
- // Convenience version of a common use case of `find`: getting the first object
- // containing specific `key:value` pairs.
- _.findWhere = function(obj, attrs) {
- return _.where(obj, attrs, true);
- };
-
- // Return the maximum element or (element-based computation).
- // Can't optimize arrays of integers longer than 65,535 elements.
- // See: https://bugs.webkit.org/show_bug.cgi?id=80797
- _.max = function(obj, iterator, context) {
- if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
- return Math.max.apply(Math, obj);
- }
- if (!iterator && _.isEmpty(obj)) return -Infinity;
- var result = {computed : -Infinity, value: -Infinity};
- each(obj, function(value, index, list) {
- var computed = iterator ? iterator.call(context, value, index, list) : value;
- computed >= result.computed && (result = {value : value, computed : computed});
- });
- return result.value;
- };
-
- // Return the minimum element (or element-based computation).
- _.min = function(obj, iterator, context) {
- if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
- return Math.min.apply(Math, obj);
- }
- if (!iterator && _.isEmpty(obj)) return Infinity;
- var result = {computed : Infinity, value: Infinity};
- each(obj, function(value, index, list) {
- var computed = iterator ? iterator.call(context, value, index, list) : value;
- computed < result.computed && (result = {value : value, computed : computed});
- });
- return result.value;
- };
-
- // Shuffle an array.
- _.shuffle = function(obj) {
- var rand;
- var index = 0;
- var shuffled = [];
- each(obj, function(value) {
- rand = _.random(index++);
- shuffled[index - 1] = shuffled[rand];
- shuffled[rand] = value;
- });
- return shuffled;
- };
-
- // An internal function to generate lookup iterators.
- var lookupIterator = function(value) {
- return _.isFunction(value) ? value : function(obj){ return obj[value]; };
- };
-
- // Sort the object's values by a criterion produced by an iterator.
- _.sortBy = function(obj, value, context) {
- var iterator = lookupIterator(value);
- return _.pluck(_.map(obj, function(value, index, list) {
- return {
- value : value,
- index : index,
- criteria : iterator.call(context, value, index, list)
- };
- }).sort(function(left, right) {
- var a = left.criteria;
- var b = right.criteria;
- if (a !== b) {
- if (a > b || a === void 0) return 1;
- if (a < b || b === void 0) return -1;
- }
- return left.index < right.index ? -1 : 1;
- }), 'value');
- };
-
- // An internal function used for aggregate "group by" operations.
- var group = function(obj, value, context, behavior) {
- var result = {};
- var iterator = lookupIterator(value || _.identity);
- each(obj, function(value, index) {
- var key = iterator.call(context, value, index, obj);
- behavior(result, key, value);
- });
- return result;
- };
-
- // Groups the object's values by a criterion. Pass either a string attribute
- // to group by, or a function that returns the criterion.
- _.groupBy = function(obj, value, context) {
- return group(obj, value, context, function(result, key, value) {
- (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
- });
- };
-
- // Counts instances of an object that group by a certain criterion. Pass
- // either a string attribute to count by, or a function that returns the
- // criterion.
- _.countBy = function(obj, value, context) {
- return group(obj, value, context, function(result, key) {
- if (!_.has(result, key)) result[key] = 0;
- result[key]++;
- });
- };
-
- // Use a comparator function to figure out the smallest index at which
- // an object should be inserted so as to maintain order. Uses binary search.
- _.sortedIndex = function(array, obj, iterator, context) {
- iterator = iterator == null ? _.identity : lookupIterator(iterator);
- var value = iterator.call(context, obj);
- var low = 0, high = array.length;
- while (low < high) {
- var mid = (low + high) >>> 1;
- iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
- }
- return low;
- };
-
- // Safely convert anything iterable into a real, live array.
- _.toArray = function(obj) {
- if (!obj) return [];
- if (_.isArray(obj)) return slice.call(obj);
- if (obj.length === +obj.length) return _.map(obj, _.identity);
- return _.values(obj);
- };
-
- // Return the number of elements in an object.
- _.size = function(obj) {
- if (obj == null) return 0;
- return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
- };
-
- // Array Functions
- // ---------------
-
- // Get the first element of an array. Passing **n** will return the first N
- // values in the array. Aliased as `head` and `take`. The **guard** check
- // allows it to work with `_.map`.
- _.first = _.head = _.take = function(array, n, guard) {
- if (array == null) return void 0;
- return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
- };
-
- // Returns everything but the last entry of the array. Especially useful on
- // the arguments object. Passing **n** will return all the values in
- // the array, excluding the last N. The **guard** check allows it to work with
- // `_.map`.
- _.initial = function(array, n, guard) {
- return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
- };
-
- // Get the last element of an array. Passing **n** will return the last N
- // values in the array. The **guard** check allows it to work with `_.map`.
- _.last = function(array, n, guard) {
- if (array == null) return void 0;
- if ((n != null) && !guard) {
- return slice.call(array, Math.max(array.length - n, 0));
- } else {
- return array[array.length - 1];
- }
- };
-
- // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
- // Especially useful on the arguments object. Passing an **n** will return
- // the rest N values in the array. The **guard**
- // check allows it to work with `_.map`.
- _.rest = _.tail = _.drop = function(array, n, guard) {
- return slice.call(array, (n == null) || guard ? 1 : n);
- };
-
- // Trim out all falsy values from an array.
- _.compact = function(array) {
- return _.filter(array, _.identity);
- };
-
- // Internal implementation of a recursive `flatten` function.
- var flatten = function(input, shallow, output) {
- each(input, function(value) {
- if (_.isArray(value)) {
- shallow ? push.apply(output, value) : flatten(value, shallow, output);
- } else {
- output.push(value);
- }
- });
- return output;
- };
-
- // Return a completely flattened version of an array.
- _.flatten = function(array, shallow) {
- return flatten(array, shallow, []);
- };
-
- // Return a version of the array that does not contain the specified value(s).
- _.without = function(array) {
- return _.difference(array, slice.call(arguments, 1));
- };
-
- // Produce a duplicate-free version of the array. If the array has already
- // been sorted, you have the option of using a faster algorithm.
- // Aliased as `unique`.
- _.uniq = _.unique = function(array, isSorted, iterator, context) {
- if (_.isFunction(isSorted)) {
- context = iterator;
- iterator = isSorted;
- isSorted = false;
- }
- var initial = iterator ? _.map(array, iterator, context) : array;
- var results = [];
- var seen = [];
- each(initial, function(value, index) {
- if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
- seen.push(value);
- results.push(array[index]);
- }
- });
- return results;
- };
-
- // Produce an array that contains the union: each distinct element from all of
- // the passed-in arrays.
- _.union = function() {
- return _.uniq(concat.apply(ArrayProto, arguments));
- };
-
- // Produce an array that contains every item shared between all the
- // passed-in arrays.
- _.intersection = function(array) {
- var rest = slice.call(arguments, 1);
- return _.filter(_.uniq(array), function(item) {
- return _.every(rest, function(other) {
- return _.indexOf(other, item) >= 0;
- });
- });
- };
-
- // Take the difference between one array and a number of other arrays.
- // Only the elements present in just the first array will remain.
- _.difference = function(array) {
- var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
- return _.filter(array, function(value){ return !_.contains(rest, value); });
- };
-
- // Zip together multiple lists into a single array -- elements that share
- // an index go together.
- _.zip = function() {
- var args = slice.call(arguments);
- var length = _.max(_.pluck(args, 'length'));
- var results = new Array(length);
- for (var i = 0; i < length; i++) {
- results[i] = _.pluck(args, "" + i);
- }
- return results;
- };
-
- // Converts lists into objects. Pass either a single array of `[key, value]`
- // pairs, or two parallel arrays of the same length -- one of keys, and one of
- // the corresponding values.
- _.object = function(list, values) {
- if (list == null) return {};
- var result = {};
- for (var i = 0, l = list.length; i < l; i++) {
- if (values) {
- result[list[i]] = values[i];
- } else {
- result[list[i][0]] = list[i][1];
- }
- }
- return result;
- };
-
- // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
- // we need this function. Return the position of the first occurrence of an
- // item in an array, or -1 if the item is not included in the array.
- // Delegates to **ECMAScript 5**'s native `indexOf` if available.
- // If the array is large and already in sort order, pass `true`
- // for **isSorted** to use binary search.
- _.indexOf = function(array, item, isSorted) {
- if (array == null) return -1;
- var i = 0, l = array.length;
- if (isSorted) {
- if (typeof isSorted == 'number') {
- i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
- } else {
- i = _.sortedIndex(array, item);
- return array[i] === item ? i : -1;
- }
- }
- if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
- for (; i < l; i++) if (array[i] === item) return i;
- return -1;
- };
-
- // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
- _.lastIndexOf = function(array, item, from) {
- if (array == null) return -1;
- var hasIndex = from != null;
- if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
- return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
- }
- var i = (hasIndex ? from : array.length);
- while (i--) if (array[i] === item) return i;
- return -1;
- };
-
- // Generate an integer Array containing an arithmetic progression. A port of
- // the native Python `range()` function. See
- // [the Python documentation](http://docs.python.org/library/functions.html#range).
- _.range = function(start, stop, step) {
- if (arguments.length <= 1) {
- stop = start || 0;
- start = 0;
- }
- step = arguments[2] || 1;
-
- var len = Math.max(Math.ceil((stop - start) / step), 0);
- var idx = 0;
- var range = new Array(len);
-
- while(idx < len) {
- range[idx++] = start;
- start += step;
- }
-
- return range;
- };
-
- // Function (ahem) Functions
- // ------------------
-
- // Create a function bound to a given object (assigning `this`, and arguments,
- // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
- // available.
- _.bind = function(func, context) {
- if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
- var args = slice.call(arguments, 2);
- return function() {
- return func.apply(context, args.concat(slice.call(arguments)));
- };
- };
-
- // Partially apply a function by creating a version that has had some of its
- // arguments pre-filled, without changing its dynamic `this` context.
- _.partial = function(func) {
- var args = slice.call(arguments, 1);
- return function() {
- return func.apply(this, args.concat(slice.call(arguments)));
- };
- };
-
- // Bind all of an object's methods to that object. Useful for ensuring that
- // all callbacks defined on an object belong to it.
- _.bindAll = function(obj) {
- var funcs = slice.call(arguments, 1);
- if (funcs.length === 0) funcs = _.functions(obj);
- each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
- return obj;
- };
-
- // Memoize an expensive function by storing its results.
- _.memoize = function(func, hasher) {
- var memo = {};
- hasher || (hasher = _.identity);
- return function() {
- var key = hasher.apply(this, arguments);
- return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
- };
- };
-
- // Delays a function for the given number of milliseconds, and then calls
- // it with the arguments supplied.
- _.delay = function(func, wait) {
- var args = slice.call(arguments, 2);
- return setTimeout(function(){ return func.apply(null, args); }, wait);
- };
-
- // Defers a function, scheduling it to run after the current call stack has
- // cleared.
- _.defer = function(func) {
- return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
- };
-
- // Returns a function, that, when invoked, will only be triggered at most once
- // during a given window of time.
- _.throttle = function(func, wait) {
- var context, args, timeout, result;
- var previous = 0;
- var later = function() {
- previous = new Date;
- timeout = null;
- result = func.apply(context, args);
- };
- return function() {
- var now = new Date;
- var remaining = wait - (now - previous);
- context = this;
- args = arguments;
- if (remaining <= 0) {
- clearTimeout(timeout);
- timeout = null;
- previous = now;
- result = func.apply(context, args);
- } else if (!timeout) {
- timeout = setTimeout(later, remaining);
- }
- return result;
- };
- };
-
- // Returns a function, that, as long as it continues to be invoked, will not
- // be triggered. The function will be called after it stops being called for
- // N milliseconds. If `immediate` is passed, trigger the function on the
- // leading edge, instead of the trailing.
- _.debounce = function(func, wait, immediate) {
- var timeout, result;
- return function() {
- var context = this, args = arguments;
- var later = function() {
- timeout = null;
- if (!immediate) result = func.apply(context, args);
- };
- var callNow = immediate && !timeout;
- clearTimeout(timeout);
- timeout = setTimeout(later, wait);
- if (callNow) result = func.apply(context, args);
- return result;
- };
- };
-
- // Returns a function that will be executed at most one time, no matter how
- // often you call it. Useful for lazy initialization.
- _.once = function(func) {
- var ran = false, memo;
- return function() {
- if (ran) return memo;
- ran = true;
- memo = func.apply(this, arguments);
- func = null;
- return memo;
- };
- };
-
- // Returns the first function passed as an argument to the second,
- // allowing you to adjust arguments, run code before and after, and
- // conditionally execute the original function.
- _.wrap = function(func, wrapper) {
- return function() {
- var args = [func];
- push.apply(args, arguments);
- return wrapper.apply(this, args);
- };
- };
-
- // Returns a function that is the composition of a list of functions, each
- // consuming the return value of the function that follows.
- _.compose = function() {
- var funcs = arguments;
- return function() {
- var args = arguments;
- for (var i = funcs.length - 1; i >= 0; i--) {
- args = [funcs[i].apply(this, args)];
- }
- return args[0];
- };
- };
-
- // Returns a function that will only be executed after being called N times.
- _.after = function(times, func) {
- if (times <= 0) return func();
- return function() {
- if (--times < 1) {
- return func.apply(this, arguments);
- }
- };
- };
-
- // Object Functions
- // ----------------
-
- // Retrieve the names of an object's properties.
- // Delegates to **ECMAScript 5**'s native `Object.keys`
- _.keys = nativeKeys || function(obj) {
- if (obj !== Object(obj)) throw new TypeError('Invalid object');
- var keys = [];
- for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
- return keys;
- };
-
- // Retrieve the values of an object's properties.
- _.values = function(obj) {
- var values = [];
- for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
- return values;
- };
-
- // Convert an object into a list of `[key, value]` pairs.
- _.pairs = function(obj) {
- var pairs = [];
- for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
- return pairs;
- };
-
- // Invert the keys and values of an object. The values must be serializable.
- _.invert = function(obj) {
- var result = {};
- for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
- return result;
- };
-
- // Return a sorted list of the function names available on the object.
- // Aliased as `methods`
- _.functions = _.methods = function(obj) {
- var names = [];
- for (var key in obj) {
- if (_.isFunction(obj[key])) names.push(key);
- }
- return names.sort();
- };
-
- // Extend a given object with all the properties in passed-in object(s).
- _.extend = function(obj) {
- each(slice.call(arguments, 1), function(source) {
- if (source) {
- for (var prop in source) {
- obj[prop] = source[prop];
- }
- }
- });
- return obj;
- };
-
- // Return a copy of the object only containing the whitelisted properties.
- _.pick = function(obj) {
- var copy = {};
- var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
- each(keys, function(key) {
- if (key in obj) copy[key] = obj[key];
- });
- return copy;
- };
-
- // Return a copy of the object without the blacklisted properties.
- _.omit = function(obj) {
- var copy = {};
- var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
- for (var key in obj) {
- if (!_.contains(keys, key)) copy[key] = obj[key];
- }
- return copy;
- };
-
- // Fill in a given object with default properties.
- _.defaults = function(obj) {
- each(slice.call(arguments, 1), function(source) {
- if (source) {
- for (var prop in source) {
- if (obj[prop] == null) obj[prop] = source[prop];
- }
- }
- });
- return obj;
- };
-
- // Create a (shallow-cloned) duplicate of an object.
- _.clone = function(obj) {
- if (!_.isObject(obj)) return obj;
- return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
- };
-
- // Invokes interceptor with the obj, and then returns obj.
- // The primary purpose of this method is to "tap into" a method chain, in
- // order to perform operations on intermediate results within the chain.
- _.tap = function(obj, interceptor) {
- interceptor(obj);
- return obj;
- };
-
- // Internal recursive comparison function for `isEqual`.
- var eq = function(a, b, aStack, bStack) {
- // Identical objects are equal. `0 === -0`, but they aren't identical.
- // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
- if (a === b) return a !== 0 || 1 / a == 1 / b;
- // A strict comparison is necessary because `null == undefined`.
- if (a == null || b == null) return a === b;
- // Unwrap any wrapped objects.
- if (a instanceof _) a = a._wrapped;
- if (b instanceof _) b = b._wrapped;
- // Compare `[[Class]]` names.
- var className = toString.call(a);
- if (className != toString.call(b)) return false;
- switch (className) {
- // Strings, numbers, dates, and booleans are compared by value.
- case '[object String]':
- // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
- // equivalent to `new String("5")`.
- return a == String(b);
- case '[object Number]':
- // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
- // other numeric values.
- return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
- case '[object Date]':
- case '[object Boolean]':
- // Coerce dates and booleans to numeric primitive values. Dates are compared by their
- // millisecond representations. Note that invalid dates with millisecond representations
- // of `NaN` are not equivalent.
- return +a == +b;
- // RegExps are compared by their source patterns and flags.
- case '[object RegExp]':
- return a.source == b.source &&
- a.global == b.global &&
- a.multiline == b.multiline &&
- a.ignoreCase == b.ignoreCase;
- }
- if (typeof a != 'object' || typeof b != 'object') return false;
- // Assume equality for cyclic structures. The algorithm for detecting cyclic
- // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
- var length = aStack.length;
- while (length--) {
- // Linear search. Performance is inversely proportional to the number of
- // unique nested structures.
- if (aStack[length] == a) return bStack[length] == b;
- }
- // Add the first object to the stack of traversed objects.
- aStack.push(a);
- bStack.push(b);
- var size = 0, result = true;
- // Recursively compare objects and arrays.
- if (className == '[object Array]') {
- // Compare array lengths to determine if a deep comparison is necessary.
- size = a.length;
- result = size == b.length;
- if (result) {
- // Deep compare the contents, ignoring non-numeric properties.
- while (size--) {
- if (!(result = eq(a[size], b[size], aStack, bStack))) break;
- }
- }
- } else {
- // Objects with different constructors are not equivalent, but `Object`s
- // from different frames are.
- var aCtor = a.constructor, bCtor = b.constructor;
- if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
- _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
- return false;
- }
- // Deep compare objects.
- for (var key in a) {
- if (_.has(a, key)) {
- // Count the expected number of properties.
- size++;
- // Deep compare each member.
- if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
- }
- }
- // Ensure that both objects contain the same number of properties.
- if (result) {
- for (key in b) {
- if (_.has(b, key) && !(size--)) break;
- }
- result = !size;
- }
- }
- // Remove the first object from the stack of traversed objects.
- aStack.pop();
- bStack.pop();
- return result;
- };
-
- // Perform a deep comparison to check if two objects are equal.
- _.isEqual = function(a, b) {
- return eq(a, b, [], []);
- };
-
- // Is a given array, string, or object empty?
- // An "empty" object has no enumerable own-properties.
- _.isEmpty = function(obj) {
- if (obj == null) return true;
- if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
- for (var key in obj) if (_.has(obj, key)) return false;
- return true;
- };
-
- // Is a given value a DOM element?
- _.isElement = function(obj) {
- return !!(obj && obj.nodeType === 1);
- };
-
- // Is a given value an array?
- // Delegates to ECMA5's native Array.isArray
- _.isArray = nativeIsArray || function(obj) {
- return toString.call(obj) == '[object Array]';
- };
-
- // Is a given variable an object?
- _.isObject = function(obj) {
- return obj === Object(obj);
- };
-
- // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
- each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
- _['is' + name] = function(obj) {
- return toString.call(obj) == '[object ' + name + ']';
- };
- });
-
- // Define a fallback version of the method in browsers (ahem, IE), where
- // there isn't any inspectable "Arguments" type.
- if (!_.isArguments(arguments)) {
- _.isArguments = function(obj) {
- return !!(obj && _.has(obj, 'callee'));
- };
- }
-
- // Optimize `isFunction` if appropriate.
- if (typeof (/./) !== 'function') {
- _.isFunction = function(obj) {
- return typeof obj === 'function';
- };
- }
-
- // Is a given object a finite number?
- _.isFinite = function(obj) {
- return isFinite(obj) && !isNaN(parseFloat(obj));
- };
-
- // Is the given value `NaN`? (NaN is the only number which does not equal itself).
- _.isNaN = function(obj) {
- return _.isNumber(obj) && obj != +obj;
- };
-
- // Is a given value a boolean?
- _.isBoolean = function(obj) {
- return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
- };
-
- // Is a given value equal to null?
- _.isNull = function(obj) {
- return obj === null;
- };
-
- // Is a given variable undefined?
- _.isUndefined = function(obj) {
- return obj === void 0;
- };
-
- // Shortcut function for checking if an object has a given property directly
- // on itself (in other words, not on a prototype).
- _.has = function(obj, key) {
- return hasOwnProperty.call(obj, key);
- };
-
- // Utility Functions
- // -----------------
-
- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
- // previous owner. Returns a reference to the Underscore object.
- _.noConflict = function() {
- root._ = previousUnderscore;
- return this;
- };
-
- // Keep the identity function around for default iterators.
- _.identity = function(value) {
- return value;
- };
-
- // Run a function **n** times.
- _.times = function(n, iterator, context) {
- var accum = Array(n);
- for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
- return accum;
- };
-
- // Return a random integer between min and max (inclusive).
- _.random = function(min, max) {
- if (max == null) {
- max = min;
- min = 0;
- }
- return min + Math.floor(Math.random() * (max - min + 1));
- };
-
- // List of HTML entities for escaping.
- var entityMap = {
- escape: {
- '&': '&amp;',
- '<': '&lt;',
- '>': '&gt;',
- '"': '&quot;',
- "'": '&#x27;',
- '/': '&#x2F;'
- }
- };
- entityMap.unescape = _.invert(entityMap.escape);
-
- // Regexes containing the keys and values listed immediately above.
- var entityRegexes = {
- escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
- unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
- };
-
- // Functions for escaping and unescaping strings to/from HTML interpolation.
- _.each(['escape', 'unescape'], function(method) {
- _[method] = function(string) {
- if (string == null) return '';
- return ('' + string).replace(entityRegexes[method], function(match) {
- return entityMap[method][match];
- });
- };
- });
-
- // If the value of the named property is a function then invoke it;
- // otherwise, return it.
- _.result = function(object, property) {
- if (object == null) return null;
- var value = object[property];
- return _.isFunction(value) ? value.call(object) : value;
- };
-
- // Add your own custom functions to the Underscore object.
- _.mixin = function(obj) {
- each(_.functions(obj), function(name){
- var func = _[name] = obj[name];
- _.prototype[name] = function() {
- var args = [this._wrapped];
- push.apply(args, arguments);
- return result.call(this, func.apply(_, args));
- };
- });
- };
-
- // Generate a unique integer id (unique within the entire client session).
- // Useful for temporary DOM ids.
- var idCounter = 0;
- _.uniqueId = function(prefix) {
- var id = ++idCounter + '';
- return prefix ? prefix + id : id;
- };
-
- // By default, Underscore uses ERB-style template delimiters, change the
- // following template settings to use alternative delimiters.
- _.templateSettings = {
- evaluate : /<%([\s\S]+?)%>/g,
- interpolate : /<%=([\s\S]+?)%>/g,
- escape : /<%-([\s\S]+?)%>/g
- };
-
- // When customizing `templateSettings`, if you don't want to define an
- // interpolation, evaluation or escaping regex, we need one that is
- // guaranteed not to match.
- var noMatch = /(.)^/;
-
- // Certain characters need to be escaped so that they can be put into a
- // string literal.
- var escapes = {
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\t': 't',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- };
-
- var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
-
- // JavaScript micro-templating, similar to John Resig's implementation.
- // Underscore templating handles arbitrary delimiters, preserves whitespace,
- // and correctly escapes quotes within interpolated code.
- _.template = function(text, data, settings) {
- var render;
- settings = _.defaults({}, settings, _.templateSettings);
-
- // Combine delimiters into one regular expression via alternation.
- var matcher = new RegExp([
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$', 'g');
-
- // Compile the template source, escaping string literals appropriately.
- var index = 0;
- var source = "__p+='";
- text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
- source += text.slice(index, offset)
- .replace(escaper, function(match) { return '\\' + escapes[match]; });
-
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
- }
- if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
- }
- if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='";
- }
- index = offset + match.length;
- return match;
- });
- source += "';\n";
-
- // If a variable is not specified, place data values in local scope.
- if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
-
- source = "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source + "return __p;\n";
-
- try {
- render = new Function(settings.variable || 'obj', '_', source);
- } catch (e) {
- e.source = source;
- throw e;
- }
-
- if (data) return render(data, _);
- var template = function(data) {
- return render.call(this, data, _);
- };
-
- // Provide the compiled function source as a convenience for precompilation.
- template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
-
- return template;
- };
-
- // Add a "chain" function, which will delegate to the wrapper.
- _.chain = function(obj) {
- return _(obj).chain();
- };
-
- // OOP
- // ---------------
- // If Underscore is called as a function, it returns a wrapped object that
- // can be used OO-style. This wrapper holds altered versions of all the
- // underscore functions. Wrapped objects may be chained.
-
- // Helper function to continue chaining intermediate results.
- var result = function(obj) {
- return this._chain ? _(obj).chain() : obj;
- };
-
- // Add all of the Underscore functions to the wrapper object.
- _.mixin(_);
-
- // Add all mutator Array functions to the wrapper.
- each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
- var method = ArrayProto[name];
- _.prototype[name] = function() {
- var obj = this._wrapped;
- method.apply(obj, arguments);
- if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
- return result.call(this, obj);
- };
- });
-
- // Add all accessor Array functions to the wrapper.
- each(['concat', 'join', 'slice'], function(name) {
- var method = ArrayProto[name];
- _.prototype[name] = function() {
- return result.call(this, method.apply(this._wrapped, arguments));
- };
- });
-
- _.extend(_.prototype, {
-
- // Start chaining a wrapped Underscore object.
- chain: function() {
- this._chain = true;
- return this;
- },
-
- // Extracts the result from a wrapped and chained object.
- value: function() {
- return this._wrapped;
- }
-
- });
-
-}).call(this);
-
-})()
-},{}],14:[function(require,module,exports){
-exports.readIEEE754 = function(buffer, offset, isBE, mLen, nBytes) {
- var e, m,
- eLen = nBytes * 8 - mLen - 1,
- eMax = (1 << eLen) - 1,
- eBias = eMax >> 1,
- nBits = -7,
- i = isBE ? 0 : (nBytes - 1),
- d = isBE ? 1 : -1,
- s = buffer[offset + i];
-
- i += d;
-
- e = s & ((1 << (-nBits)) - 1);
- s >>= (-nBits);
- nBits += eLen;
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
-
- m = e & ((1 << (-nBits)) - 1);
- e >>= (-nBits);
- nBits += mLen;
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
-
- if (e === 0) {
- e = 1 - eBias;
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity);
- } else {
- m = m + Math.pow(2, mLen);
- e = e - eBias;
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
-};
-
-exports.writeIEEE754 = function(buffer, value, offset, isBE, mLen, nBytes) {
- var e, m, c,
- eLen = nBytes * 8 - mLen - 1,
- eMax = (1 << eLen) - 1,
- eBias = eMax >> 1,
- rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
- i = isBE ? (nBytes - 1) : 0,
- d = isBE ? -1 : 1,
- s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
-
- value = Math.abs(value);
-
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0;
- e = eMax;
- } else {
- e = Math.floor(Math.log(value) / Math.LN2);
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--;
- c *= 2;
- }
- if (e + eBias >= 1) {
- value += rt / c;
- } else {
- value += rt * Math.pow(2, 1 - eBias);
- }
- if (value * c >= 2) {
- e++;
- c /= 2;
- }
-
- if (e + eBias >= eMax) {
- m = 0;
- e = eMax;
- } else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen);
- e = e + eBias;
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
- e = 0;
- }
- }
-
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8);
-
- e = (e << mLen) | m;
- eLen += mLen;
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8);
-
- buffer[offset + i - d] |= s * 128;
-};
-
-},{}],13:[function(require,module,exports){
-(function(){function SlowBuffer (size) {
- this.length = size;
-};
-
-var assert = require('assert');
-
-exports.INSPECT_MAX_BYTES = 50;
-
-
-function toHex(n) {
- if (n < 16) return '0' + n.toString(16);
- return n.toString(16);
-}
-
-function utf8ToBytes(str) {
- var byteArray = [];
- for (var i = 0; i < str.length; i++)
- if (str.charCodeAt(i) <= 0x7F)
- byteArray.push(str.charCodeAt(i));
- else {
- var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
- for (var j = 0; j < h.length; j++)
- byteArray.push(parseInt(h[j], 16));
- }
-
- return byteArray;
-}
-
-function asciiToBytes(str) {
- var byteArray = []
- for (var i = 0; i < str.length; i++ )
- // Node's code seems to be doing this and not & 0x7F..
- byteArray.push( str.charCodeAt(i) & 0xFF );
-
- return byteArray;
-}
-
-function base64ToBytes(str) {
- return require("base64-js").toByteArray(str);
-}
-
-SlowBuffer.byteLength = function (str, encoding) {
- switch (encoding || "utf8") {
- case 'hex':
- return str.length / 2;
-
- case 'utf8':
- case 'utf-8':
- return utf8ToBytes(str).length;
-
- case 'ascii':
- case 'binary':
- return str.length;
-
- case 'base64':
- return base64ToBytes(str).length;
-
- default:
- throw new Error('Unknown encoding');
- }
-};
-
-function blitBuffer(src, dst, offset, length) {
- var pos, i = 0;
- while (i < length) {
- if ((i+offset >= dst.length) || (i >= src.length))
- break;
-
- dst[i + offset] = src[i];
- i++;
- }
- return i;
-}
-
-SlowBuffer.prototype.utf8Write = function (string, offset, length) {
- var bytes, pos;
- return SlowBuffer._charsWritten = blitBuffer(utf8ToBytes(string), this, offset, length);
-};
-
-SlowBuffer.prototype.asciiWrite = function (string, offset, length) {
- var bytes, pos;
- return SlowBuffer._charsWritten = blitBuffer(asciiToBytes(string), this, offset, length);
-};
-
-SlowBuffer.prototype.binaryWrite = SlowBuffer.prototype.asciiWrite;
-
-SlowBuffer.prototype.base64Write = function (string, offset, length) {
- var bytes, pos;
- return SlowBuffer._charsWritten = blitBuffer(base64ToBytes(string), this, offset, length);
-};
-
-SlowBuffer.prototype.base64Slice = function (start, end) {
- var bytes = Array.prototype.slice.apply(this, arguments)
- return require("base64-js").fromByteArray(bytes);
-}
-
-function decodeUtf8Char(str) {
- try {
- return decodeURIComponent(str);
- } catch (err) {
- return String.fromCharCode(0xFFFD); // UTF 8 invalid char
- }
-}
-
-SlowBuffer.prototype.utf8Slice = function () {
- var bytes = Array.prototype.slice.apply(this, arguments);
- var res = "";
- var tmp = "";
- var i = 0;
- while (i < bytes.length) {
- if (bytes[i] <= 0x7F) {
- res += decodeUtf8Char(tmp) + String.fromCharCode(bytes[i]);
- tmp = "";
- } else
- tmp += "%" + bytes[i].toString(16);
-
- i++;
- }
-
- return res + decodeUtf8Char(tmp);
-}
-
-SlowBuffer.prototype.asciiSlice = function () {
- var bytes = Array.prototype.slice.apply(this, arguments);
- var ret = "";
- for (var i = 0; i < bytes.length; i++)
- ret += String.fromCharCode(bytes[i]);
- return ret;
-}
-
-SlowBuffer.prototype.binarySlice = SlowBuffer.prototype.asciiSlice;
-
-SlowBuffer.prototype.inspect = function() {
- var out = [],
- len = this.length;
- for (var i = 0; i < len; i++) {
- out[i] = toHex(this[i]);
- if (i == exports.INSPECT_MAX_BYTES) {
- out[i + 1] = '...';
- break;
- }
- }
- return '<SlowBuffer ' + out.join(' ') + '>';
-};
-
-
-SlowBuffer.prototype.hexSlice = function(start, end) {
- var len = this.length;
-
- if (!start || start < 0) start = 0;
- if (!end || end < 0 || end > len) end = len;
-
- var out = '';
- for (var i = start; i < end; i++) {
- out += toHex(this[i]);
- }
- return out;
-};
-
-
-SlowBuffer.prototype.toString = function(encoding, start, end) {
- encoding = String(encoding || 'utf8').toLowerCase();
- start = +start || 0;
- if (typeof end == 'undefined') end = this.length;
-
- // Fastpath empty strings
- if (+end == start) {
- return '';
- }
-
- switch (encoding) {
- case 'hex':
- return this.hexSlice(start, end);
-
- case 'utf8':
- case 'utf-8':
- return this.utf8Slice(start, end);
-
- case 'ascii':
- return this.asciiSlice(start, end);
-
- case 'binary':
- return this.binarySlice(start, end);
-
- case 'base64':
- return this.base64Slice(start, end);
-
- case 'ucs2':
- case 'ucs-2':
- return this.ucs2Slice(start, end);
-
- default:
- throw new Error('Unknown encoding');
- }
-};
-
-
-SlowBuffer.prototype.hexWrite = function(string, offset, length) {
- offset = +offset || 0;
- var remaining = this.length - offset;
- if (!length) {
- length = remaining;
- } else {
- length = +length;
- if (length > remaining) {
- length = remaining;
- }
- }
-
- // must be an even number of digits
- var strLen = string.length;
- if (strLen % 2) {
- throw new Error('Invalid hex string');
- }
- if (length > strLen / 2) {
- length = strLen / 2;
- }
- for (var i = 0; i < length; i++) {
- var byte = parseInt(string.substr(i * 2, 2), 16);
- if (isNaN(byte)) throw new Error('Invalid hex string');
- this[offset + i] = byte;
- }
- SlowBuffer._charsWritten = i * 2;
- return i;
-};
-
-
-SlowBuffer.prototype.write = function(string, offset, length, encoding) {
- // Support both (string, offset, length, encoding)
- // and the legacy (string, encoding, offset, length)
- if (isFinite(offset)) {
- if (!isFinite(length)) {
- encoding = length;
- length = undefined;
- }
- } else { // legacy
- var swap = encoding;
- encoding = offset;
- offset = length;
- length = swap;
- }
-
- offset = +offset || 0;
- var remaining = this.length - offset;
- if (!length) {
- length = remaining;
- } else {
- length = +length;
- if (length > remaining) {
- length = remaining;
- }
- }
- encoding = String(encoding || 'utf8').toLowerCase();
-
- switch (encoding) {
- case 'hex':
- return this.hexWrite(string, offset, length);
-
- case 'utf8':
- case 'utf-8':
- return this.utf8Write(string, offset, length);
-
- case 'ascii':
- return this.asciiWrite(string, offset, length);
-
- case 'binary':
- return this.binaryWrite(string, offset, length);
-
- case 'base64':
- return this.base64Write(string, offset, length);
-
- case 'ucs2':
- case 'ucs-2':
- return this.ucs2Write(string, offset, length);
-
- default:
- throw new Error('Unknown encoding');
- }
-};
-
-
-// slice(start, end)
-SlowBuffer.prototype.slice = function(start, end) {
- if (end === undefined) end = this.length;
-
- if (end > this.length) {
- throw new Error('oob');
- }
- if (start > end) {
- throw new Error('oob');
- }
-
- return new Buffer(this, end - start, +start);
-};
-
-SlowBuffer.prototype.copy = function(target, targetstart, sourcestart, sourceend) {
- var temp = [];
- for (var i=sourcestart; i<sourceend; i++) {
- assert.ok(typeof this[i] !== 'undefined', "copying undefined buffer bytes!");
- temp.push(this[i]);
- }
-
- for (var i=targetstart; i<targetstart+temp.length; i++) {
- target[i] = temp[i-targetstart];
- }
-};
-
-SlowBuffer.prototype.fill = function(value, start, end) {
- if (end > this.length) {
- throw new Error('oob');
- }
- if (start > end) {
- throw new Error('oob');
- }
-
- for (var i = start; i < end; i++) {
- this[i] = value;
- }
-}
-
-function coerce(length) {
- // Coerce length to a number (possibly NaN), round up
- // in case it's fractional (e.g. 123.456) then do a
- // double negate to coerce a NaN to 0. Easy, right?
- length = ~~Math.ceil(+length);
- return length < 0 ? 0 : length;
-}
-
-
-// Buffer
-
-function Buffer(subject, encoding, offset) {
- if (!(this instanceof Buffer)) {
- return new Buffer(subject, encoding, offset);
- }
-
- var type;
-
- // Are we slicing?
- if (typeof offset === 'number') {
- this.length = coerce(encoding);
- this.parent = subject;
- this.offset = offset;
- } else {
- // Find the length
- switch (type = typeof subject) {
- case 'number':
- this.length = coerce(subject);
- break;
-
- case 'string':
- this.length = Buffer.byteLength(subject, encoding);
- break;
-
- case 'object': // Assume object is an array
- this.length = coerce(subject.length);
- break;
-
- default:
- throw new Error('First argument needs to be a number, ' +
- 'array or string.');
- }
-
- if (this.length > Buffer.poolSize) {
- // Big buffer, just alloc one.
- this.parent = new SlowBuffer(this.length);
- this.offset = 0;
-
- } else {
- // Small buffer.
- if (!pool || pool.length - pool.used < this.length) allocPool();
- this.parent = pool;
- this.offset = pool.used;
- pool.used += this.length;
- }
-
- // Treat array-ish objects as a byte array.
- if (isArrayIsh(subject)) {
- for (var i = 0; i < this.length; i++) {
- if (subject instanceof Buffer) {
- this.parent[i + this.offset] = subject.readUInt8(i);
- }
- else {
- this.parent[i + this.offset] = subject[i];
- }
- }
- } else if (type == 'string') {
- // We are a string
- this.length = this.write(subject, 0, encoding);
- }
- }
-
-}
-
-function isArrayIsh(subject) {
- return Array.isArray(subject) || Buffer.isBuffer(subject) ||
- subject && typeof subject === 'object' &&
- typeof subject.length === 'number';
-}
-
-exports.SlowBuffer = SlowBuffer;
-exports.Buffer = Buffer;
-
-Buffer.poolSize = 8 * 1024;
-var pool;
-
-function allocPool() {
- pool = new SlowBuffer(Buffer.poolSize);
- pool.used = 0;
-}
-
-
-// Static methods
-Buffer.isBuffer = function isBuffer(b) {
- return b instanceof Buffer || b instanceof SlowBuffer;
-};
-
-Buffer.concat = function (list, totalLength) {
- if (!Array.isArray(list)) {
- throw new Error("Usage: Buffer.concat(list, [totalLength])\n \
- list should be an Array.");
- }
-
- if (list.length === 0) {
- return new Buffer(0);
- } else if (list.length === 1) {
- return list[0];
- }
-
- if (typeof totalLength !== 'number') {
- totalLength = 0;
- for (var i = 0; i < list.length; i++) {
- var buf = list[i];
- totalLength += buf.length;
- }
- }
-
- var buffer = new Buffer(totalLength);
- var pos = 0;
- for (var i = 0; i < list.length; i++) {
- var buf = list[i];
- buf.copy(buffer, pos);
- pos += buf.length;
- }
- return buffer;
-};
-
-// Inspect
-Buffer.prototype.inspect = function inspect() {
- var out = [],
- len = this.length;
-
- for (var i = 0; i < len; i++) {
- out[i] = toHex(this.parent[i + this.offset]);
- if (i == exports.INSPECT_MAX_BYTES) {
- out[i + 1] = '...';
- break;
- }
- }
-
- return '<Buffer ' + out.join(' ') + '>';
-};
-
-
-Buffer.prototype.get = function get(i) {
- if (i < 0 || i >= this.length) throw new Error('oob');
- return this.parent[this.offset + i];
-};
-
-
-Buffer.prototype.set = function set(i, v) {
- if (i < 0 || i >= this.length) throw new Error('oob');
- return this.parent[this.offset + i] = v;
-};
-
-
-// write(string, offset = 0, length = buffer.length-offset, encoding = 'utf8')
-Buffer.prototype.write = function(string, offset, length, encoding) {
- // Support both (string, offset, length, encoding)
- // and the legacy (string, encoding, offset, length)
- if (isFinite(offset)) {
- if (!isFinite(length)) {
- encoding = length;
- length = undefined;
- }
- } else { // legacy
- var swap = encoding;
- encoding = offset;
- offset = length;
- length = swap;
- }
-
- offset = +offset || 0;
- var remaining = this.length - offset;
- if (!length) {
- length = remaining;
- } else {
- length = +length;
- if (length > remaining) {
- length = remaining;
- }
- }
- encoding = String(encoding || 'utf8').toLowerCase();
-
- var ret;
- switch (encoding) {
- case 'hex':
- ret = this.parent.hexWrite(string, this.offset + offset, length);
- break;
-
- case 'utf8':
- case 'utf-8':
- ret = this.parent.utf8Write(string, this.offset + offset, length);
- break;
-
- case 'ascii':
- ret = this.parent.asciiWrite(string, this.offset + offset, length);
- break;
-
- case 'binary':
- ret = this.parent.binaryWrite(string, this.offset + offset, length);
- break;
-
- case 'base64':
- // Warning: maxLength not taken into account in base64Write
- ret = this.parent.base64Write(string, this.offset + offset, length);
- break;
-
- case 'ucs2':
- case 'ucs-2':
- ret = this.parent.ucs2Write(string, this.offset + offset, length);
- break;
-
- default:
- throw new Error('Unknown encoding');
- }
-
- Buffer._charsWritten = SlowBuffer._charsWritten;
-
- return ret;
-};
-
-
-// toString(encoding, start=0, end=buffer.length)
-Buffer.prototype.toString = function(encoding, start, end) {
- encoding = String(encoding || 'utf8').toLowerCase();
-
- if (typeof start == 'undefined' || start < 0) {
- start = 0;
- } else if (start > this.length) {
- start = this.length;
- }
-
- if (typeof end == 'undefined' || end > this.length) {
- end = this.length;
- } else if (end < 0) {
- end = 0;
- }
-
- start = start + this.offset;
- end = end + this.offset;
-
- switch (encoding) {
- case 'hex':
- return this.parent.hexSlice(start, end);
-
- case 'utf8':
- case 'utf-8':
- return this.parent.utf8Slice(start, end);
-
- case 'ascii':
- return this.parent.asciiSlice(start, end);
-
- case 'binary':
- return this.parent.binarySlice(start, end);
-
- case 'base64':
- return this.parent.base64Slice(start, end);
-
- case 'ucs2':
- case 'ucs-2':
- return this.parent.ucs2Slice(start, end);
-
- default:
- throw new Error('Unknown encoding');
- }
-};
-
-
-// byteLength
-Buffer.byteLength = SlowBuffer.byteLength;
-
-
-// fill(value, start=0, end=buffer.length)
-Buffer.prototype.fill = function fill(value, start, end) {
- value || (value = 0);
- start || (start = 0);
- end || (end = this.length);
-
- if (typeof value === 'string') {
- value = value.charCodeAt(0);
- }
- if (!(typeof value === 'number') || isNaN(value)) {
- throw new Error('value is not a number');
- }
-
- if (end < start) throw new Error('end < start');
-
- // Fill 0 bytes; we're done
- if (end === start) return 0;
- if (this.length == 0) return 0;
-
- if (start < 0 || start >= this.length) {
- throw new Error('start out of bounds');
- }
-
- if (end < 0 || end > this.length) {
- throw new Error('end out of bounds');
- }
-
- return this.parent.fill(value,
- start + this.offset,
- end + this.offset);
-};
-
-
-// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
-Buffer.prototype.copy = function(target, target_start, start, end) {
- var source = this;
- start || (start = 0);
- end || (end = this.length);
- target_start || (target_start = 0);
-
- if (end < start) throw new Error('sourceEnd < sourceStart');
-
- // Copy 0 bytes; we're done
- if (end === start) return 0;
- if (target.length == 0 || source.length == 0) return 0;
-
- if (target_start < 0 || target_start >= target.length) {
- throw new Error('targetStart out of bounds');
- }
-
- if (start < 0 || start >= source.length) {
- throw new Error('sourceStart out of bounds');
- }
-
- if (end < 0 || end > source.length) {
- throw new Error('sourceEnd out of bounds');
- }
-
- // Are we oob?
- if (end > this.length) {
- end = this.length;
- }
-
- if (target.length - target_start < end - start) {
- end = target.length - target_start + start;
- }
-
- return this.parent.copy(target.parent,
- target_start + target.offset,
- start + this.offset,
- end + this.offset);
-};
-
-
-// slice(start, end)
-Buffer.prototype.slice = function(start, end) {
- if (end === undefined) end = this.length;
- if (end > this.length) throw new Error('oob');
- if (start > end) throw new Error('oob');
-
- return new Buffer(this.parent, end - start, +start + this.offset);
-};
-
-
-// Legacy methods for backwards compatibility.
-
-Buffer.prototype.utf8Slice = function(start, end) {
- return this.toString('utf8', start, end);
-};
-
-Buffer.prototype.binarySlice = function(start, end) {
- return this.toString('binary', start, end);
-};
-
-Buffer.prototype.asciiSlice = function(start, end) {
- return this.toString('ascii', start, end);
-};
-
-Buffer.prototype.utf8Write = function(string, offset) {
- return this.write(string, offset, 'utf8');
-};
-
-Buffer.prototype.binaryWrite = function(string, offset) {
- return this.write(string, offset, 'binary');
-};
-
-Buffer.prototype.asciiWrite = function(string, offset) {
- return this.write(string, offset, 'ascii');
-};
-
-Buffer.prototype.readUInt8 = function(offset, noAssert) {
- var buffer = this;
-
- if (!noAssert) {
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset < buffer.length,
- 'Trying to read beyond buffer length');
- }
-
- if (offset >= buffer.length) return;
-
- return buffer.parent[buffer.offset + offset];
-};
-
-function readUInt16(buffer, offset, isBigEndian, noAssert) {
- var val = 0;
-
-
- if (!noAssert) {
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 1 < buffer.length,
- 'Trying to read beyond buffer length');
- }
-
- if (offset >= buffer.length) return 0;
-
- if (isBigEndian) {
- val = buffer.parent[buffer.offset + offset] << 8;
- if (offset + 1 < buffer.length) {
- val |= buffer.parent[buffer.offset + offset + 1];
- }
- } else {
- val = buffer.parent[buffer.offset + offset];
- if (offset + 1 < buffer.length) {
- val |= buffer.parent[buffer.offset + offset + 1] << 8;
- }
- }
-
- return val;
-}
-
-Buffer.prototype.readUInt16LE = function(offset, noAssert) {
- return readUInt16(this, offset, false, noAssert);
-};
-
-Buffer.prototype.readUInt16BE = function(offset, noAssert) {
- return readUInt16(this, offset, true, noAssert);
-};
-
-function readUInt32(buffer, offset, isBigEndian, noAssert) {
- var val = 0;
-
- if (!noAssert) {
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 3 < buffer.length,
- 'Trying to read beyond buffer length');
- }
-
- if (offset >= buffer.length) return 0;
-
- if (isBigEndian) {
- if (offset + 1 < buffer.length)
- val = buffer.parent[buffer.offset + offset + 1] << 16;
- if (offset + 2 < buffer.length)
- val |= buffer.parent[buffer.offset + offset + 2] << 8;
- if (offset + 3 < buffer.length)
- val |= buffer.parent[buffer.offset + offset + 3];
- val = val + (buffer.parent[buffer.offset + offset] << 24 >>> 0);
- } else {
- if (offset + 2 < buffer.length)
- val = buffer.parent[buffer.offset + offset + 2] << 16;
- if (offset + 1 < buffer.length)
- val |= buffer.parent[buffer.offset + offset + 1] << 8;
- val |= buffer.parent[buffer.offset + offset];
- if (offset + 3 < buffer.length)
- val = val + (buffer.parent[buffer.offset + offset + 3] << 24 >>> 0);
- }
-
- return val;
-}
-
-Buffer.prototype.readUInt32LE = function(offset, noAssert) {
- return readUInt32(this, offset, false, noAssert);
-};
-
-Buffer.prototype.readUInt32BE = function(offset, noAssert) {
- return readUInt32(this, offset, true, noAssert);
-};
-
-
-/*
- * Signed integer types, yay team! A reminder on how two's complement actually
- * works. The first bit is the signed bit, i.e. tells us whether or not the
- * number should be positive or negative. If the two's complement value is
- * positive, then we're done, as it's equivalent to the unsigned representation.
- *
- * Now if the number is positive, you're pretty much done, you can just leverage
- * the unsigned translations and return those. Unfortunately, negative numbers
- * aren't quite that straightforward.
- *
- * At first glance, one might be inclined to use the traditional formula to
- * translate binary numbers between the positive and negative values in two's
- * complement. (Though it doesn't quite work for the most negative value)
- * Mainly:
- * - invert all the bits
- * - add one to the result
- *
- * Of course, this doesn't quite work in Javascript. Take for example the value
- * of -128. This could be represented in 16 bits (big-endian) as 0xff80. But of
- * course, Javascript will do the following:
- *
- * > ~0xff80
- * -65409
- *
- * Whoh there, Javascript, that's not quite right. But wait, according to
- * Javascript that's perfectly correct. When Javascript ends up seeing the
- * constant 0xff80, it has no notion that it is actually a signed number. It
- * assumes that we've input the unsigned value 0xff80. Thus, when it does the
- * binary negation, it casts it into a signed value, (positive 0xff80). Then
- * when you perform binary negation on that, it turns it into a negative number.
- *
- * Instead, we're going to have to use the following general formula, that works
- * in a rather Javascript friendly way. I'm glad we don't support this kind of
- * weird numbering scheme in the kernel.
- *
- * (BIT-MAX - (unsigned)val + 1) * -1
- *
- * The astute observer, may think that this doesn't make sense for 8-bit numbers
- * (really it isn't necessary for them). However, when you get 16-bit numbers,
- * you do. Let's go back to our prior example and see how this will look:
- *
- * (0xffff - 0xff80 + 1) * -1
- * (0x007f + 1) * -1
- * (0x0080) * -1
- */
-Buffer.prototype.readInt8 = function(offset, noAssert) {
- var buffer = this;
- var neg;
-
- if (!noAssert) {
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset < buffer.length,
- 'Trying to read beyond buffer length');
- }
-
- if (offset >= buffer.length) return;
-
- neg = buffer.parent[buffer.offset + offset] & 0x80;
- if (!neg) {
- return (buffer.parent[buffer.offset + offset]);
- }
-
- return ((0xff - buffer.parent[buffer.offset + offset] + 1) * -1);
-};
-
-function readInt16(buffer, offset, isBigEndian, noAssert) {
- var neg, val;
-
- if (!noAssert) {
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 1 < buffer.length,
- 'Trying to read beyond buffer length');
- }
-
- val = readUInt16(buffer, offset, isBigEndian, noAssert);
- neg = val & 0x8000;
- if (!neg) {
- return val;
- }
-
- return (0xffff - val + 1) * -1;
-}
-
-Buffer.prototype.readInt16LE = function(offset, noAssert) {
- return readInt16(this, offset, false, noAssert);
-};
-
-Buffer.prototype.readInt16BE = function(offset, noAssert) {
- return readInt16(this, offset, true, noAssert);
-};
-
-function readInt32(buffer, offset, isBigEndian, noAssert) {
- var neg, val;
-
- if (!noAssert) {
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 3 < buffer.length,
- 'Trying to read beyond buffer length');
- }
-
- val = readUInt32(buffer, offset, isBigEndian, noAssert);
- neg = val & 0x80000000;
- if (!neg) {
- return (val);
- }
-
- return (0xffffffff - val + 1) * -1;
-}
-
-Buffer.prototype.readInt32LE = function(offset, noAssert) {
- return readInt32(this, offset, false, noAssert);
-};
-
-Buffer.prototype.readInt32BE = function(offset, noAssert) {
- return readInt32(this, offset, true, noAssert);
-};
-
-function readFloat(buffer, offset, isBigEndian, noAssert) {
- if (!noAssert) {
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset + 3 < buffer.length,
- 'Trying to read beyond buffer length');
- }
-
- return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
- 23, 4);
-}
-
-Buffer.prototype.readFloatLE = function(offset, noAssert) {
- return readFloat(this, offset, false, noAssert);
-};
-
-Buffer.prototype.readFloatBE = function(offset, noAssert) {
- return readFloat(this, offset, true, noAssert);
-};
-
-function readDouble(buffer, offset, isBigEndian, noAssert) {
- if (!noAssert) {
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset + 7 < buffer.length,
- 'Trying to read beyond buffer length');
- }
-
- return require('./buffer_ieee754').readIEEE754(buffer, offset, isBigEndian,
- 52, 8);
-}
-
-Buffer.prototype.readDoubleLE = function(offset, noAssert) {
- return readDouble(this, offset, false, noAssert);
-};
-
-Buffer.prototype.readDoubleBE = function(offset, noAssert) {
- return readDouble(this, offset, true, noAssert);
-};
-
-
-/*
- * We have to make sure that the value is a valid integer. This means that it is
- * non-negative. It has no fractional component and that it does not exceed the
- * maximum allowed value.
- *
- * value The number to check for validity
- *
- * max The maximum value
- */
-function verifuint(value, max) {
- assert.ok(typeof (value) == 'number',
- 'cannot write a non-number as a number');
-
- assert.ok(value >= 0,
- 'specified a negative value for writing an unsigned value');
-
- assert.ok(value <= max, 'value is larger than maximum value for type');
-
- assert.ok(Math.floor(value) === value, 'value has a fractional component');
-}
-
-Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
- var buffer = this;
-
- if (!noAssert) {
- assert.ok(value !== undefined && value !== null,
- 'missing value');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset < buffer.length,
- 'trying to write beyond buffer length');
-
- verifuint(value, 0xff);
- }
-
- if (offset < buffer.length) {
- buffer.parent[buffer.offset + offset] = value;
- }
-};
-
-function writeUInt16(buffer, value, offset, isBigEndian, noAssert) {
- if (!noAssert) {
- assert.ok(value !== undefined && value !== null,
- 'missing value');
-
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 1 < buffer.length,
- 'trying to write beyond buffer length');
-
- verifuint(value, 0xffff);
- }
-
- for (var i = 0; i < Math.min(buffer.length - offset, 2); i++) {
- buffer.parent[buffer.offset + offset + i] =
- (value & (0xff << (8 * (isBigEndian ? 1 - i : i)))) >>>
- (isBigEndian ? 1 - i : i) * 8;
- }
-
-}
-
-Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
- writeUInt16(this, value, offset, false, noAssert);
-};
-
-Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
- writeUInt16(this, value, offset, true, noAssert);
-};
-
-function writeUInt32(buffer, value, offset, isBigEndian, noAssert) {
- if (!noAssert) {
- assert.ok(value !== undefined && value !== null,
- 'missing value');
-
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 3 < buffer.length,
- 'trying to write beyond buffer length');
-
- verifuint(value, 0xffffffff);
- }
-
- for (var i = 0; i < Math.min(buffer.length - offset, 4); i++) {
- buffer.parent[buffer.offset + offset + i] =
- (value >>> (isBigEndian ? 3 - i : i) * 8) & 0xff;
- }
-}
-
-Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
- writeUInt32(this, value, offset, false, noAssert);
-};
-
-Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
- writeUInt32(this, value, offset, true, noAssert);
-};
-
-
-/*
- * We now move onto our friends in the signed number category. Unlike unsigned
- * numbers, we're going to have to worry a bit more about how we put values into
- * arrays. Since we are only worrying about signed 32-bit values, we're in
- * slightly better shape. Unfortunately, we really can't do our favorite binary
- * & in this system. It really seems to do the wrong thing. For example:
- *
- * > -32 & 0xff
- * 224
- *
- * What's happening above is really: 0xe0 & 0xff = 0xe0. However, the results of
- * this aren't treated as a signed number. Ultimately a bad thing.
- *
- * What we're going to want to do is basically create the unsigned equivalent of
- * our representation and pass that off to the wuint* functions. To do that
- * we're going to do the following:
- *
- * - if the value is positive
- * we can pass it directly off to the equivalent wuint
- * - if the value is negative
- * we do the following computation:
- * mb + val + 1, where
- * mb is the maximum unsigned value in that byte size
- * val is the Javascript negative integer
- *
- *
- * As a concrete value, take -128. In signed 16 bits this would be 0xff80. If
- * you do out the computations:
- *
- * 0xffff - 128 + 1
- * 0xffff - 127
- * 0xff80
- *
- * You can then encode this value as the signed version. This is really rather
- * hacky, but it should work and get the job done which is our goal here.
- */
-
-/*
- * A series of checks to make sure we actually have a signed 32-bit number
- */
-function verifsint(value, max, min) {
- assert.ok(typeof (value) == 'number',
- 'cannot write a non-number as a number');
-
- assert.ok(value <= max, 'value larger than maximum allowed value');
-
- assert.ok(value >= min, 'value smaller than minimum allowed value');
-
- assert.ok(Math.floor(value) === value, 'value has a fractional component');
-}
-
-function verifIEEE754(value, max, min) {
- assert.ok(typeof (value) == 'number',
- 'cannot write a non-number as a number');
-
- assert.ok(value <= max, 'value larger than maximum allowed value');
-
- assert.ok(value >= min, 'value smaller than minimum allowed value');
-}
-
-Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
- var buffer = this;
-
- if (!noAssert) {
- assert.ok(value !== undefined && value !== null,
- 'missing value');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset < buffer.length,
- 'Trying to write beyond buffer length');
-
- verifsint(value, 0x7f, -0x80);
- }
-
- if (value >= 0) {
- buffer.writeUInt8(value, offset, noAssert);
- } else {
- buffer.writeUInt8(0xff + value + 1, offset, noAssert);
- }
-};
-
-function writeInt16(buffer, value, offset, isBigEndian, noAssert) {
- if (!noAssert) {
- assert.ok(value !== undefined && value !== null,
- 'missing value');
-
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 1 < buffer.length,
- 'Trying to write beyond buffer length');
-
- verifsint(value, 0x7fff, -0x8000);
- }
-
- if (value >= 0) {
- writeUInt16(buffer, value, offset, isBigEndian, noAssert);
- } else {
- writeUInt16(buffer, 0xffff + value + 1, offset, isBigEndian, noAssert);
- }
-}
-
-Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
- writeInt16(this, value, offset, false, noAssert);
-};
-
-Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
- writeInt16(this, value, offset, true, noAssert);
-};
-
-function writeInt32(buffer, value, offset, isBigEndian, noAssert) {
- if (!noAssert) {
- assert.ok(value !== undefined && value !== null,
- 'missing value');
-
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 3 < buffer.length,
- 'Trying to write beyond buffer length');
-
- verifsint(value, 0x7fffffff, -0x80000000);
- }
-
- if (value >= 0) {
- writeUInt32(buffer, value, offset, isBigEndian, noAssert);
- } else {
- writeUInt32(buffer, 0xffffffff + value + 1, offset, isBigEndian, noAssert);
- }
-}
-
-Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
- writeInt32(this, value, offset, false, noAssert);
-};
-
-Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
- writeInt32(this, value, offset, true, noAssert);
-};
-
-function writeFloat(buffer, value, offset, isBigEndian, noAssert) {
- if (!noAssert) {
- assert.ok(value !== undefined && value !== null,
- 'missing value');
-
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 3 < buffer.length,
- 'Trying to write beyond buffer length');
-
- verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38);
- }
-
- require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
- 23, 4);
-}
-
-Buffer.prototype.writeFloatLE = function(value, offset, noAssert) {
- writeFloat(this, value, offset, false, noAssert);
-};
-
-Buffer.prototype.writeFloatBE = function(value, offset, noAssert) {
- writeFloat(this, value, offset, true, noAssert);
-};
-
-function writeDouble(buffer, value, offset, isBigEndian, noAssert) {
- if (!noAssert) {
- assert.ok(value !== undefined && value !== null,
- 'missing value');
-
- assert.ok(typeof (isBigEndian) === 'boolean',
- 'missing or invalid endian');
-
- assert.ok(offset !== undefined && offset !== null,
- 'missing offset');
-
- assert.ok(offset + 7 < buffer.length,
- 'Trying to write beyond buffer length');
-
- verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308);
- }
-
- require('./buffer_ieee754').writeIEEE754(buffer, value, offset, isBigEndian,
- 52, 8);
-}
-
-Buffer.prototype.writeDoubleLE = function(value, offset, noAssert) {
- writeDouble(this, value, offset, false, noAssert);
-};
-
-Buffer.prototype.writeDoubleBE = function(value, offset, noAssert) {
- writeDouble(this, value, offset, true, noAssert);
-};
-
-SlowBuffer.prototype.readUInt8 = Buffer.prototype.readUInt8;
-SlowBuffer.prototype.readUInt16LE = Buffer.prototype.readUInt16LE;
-SlowBuffer.prototype.readUInt16BE = Buffer.prototype.readUInt16BE;
-SlowBuffer.prototype.readUInt32LE = Buffer.prototype.readUInt32LE;
-SlowBuffer.prototype.readUInt32BE = Buffer.prototype.readUInt32BE;
-SlowBuffer.prototype.readInt8 = Buffer.prototype.readInt8;
-SlowBuffer.prototype.readInt16LE = Buffer.prototype.readInt16LE;
-SlowBuffer.prototype.readInt16BE = Buffer.prototype.readInt16BE;
-SlowBuffer.prototype.readInt32LE = Buffer.prototype.readInt32LE;
-SlowBuffer.prototype.readInt32BE = Buffer.prototype.readInt32BE;
-SlowBuffer.prototype.readFloatLE = Buffer.prototype.readFloatLE;
-SlowBuffer.prototype.readFloatBE = Buffer.prototype.readFloatBE;
-SlowBuffer.prototype.readDoubleLE = Buffer.prototype.readDoubleLE;
-SlowBuffer.prototype.readDoubleBE = Buffer.prototype.readDoubleBE;
-SlowBuffer.prototype.writeUInt8 = Buffer.prototype.writeUInt8;
-SlowBuffer.prototype.writeUInt16LE = Buffer.prototype.writeUInt16LE;
-SlowBuffer.prototype.writeUInt16BE = Buffer.prototype.writeUInt16BE;
-SlowBuffer.prototype.writeUInt32LE = Buffer.prototype.writeUInt32LE;
-SlowBuffer.prototype.writeUInt32BE = Buffer.prototype.writeUInt32BE;
-SlowBuffer.prototype.writeInt8 = Buffer.prototype.writeInt8;
-SlowBuffer.prototype.writeInt16LE = Buffer.prototype.writeInt16LE;
-SlowBuffer.prototype.writeInt16BE = Buffer.prototype.writeInt16BE;
-SlowBuffer.prototype.writeInt32LE = Buffer.prototype.writeInt32LE;
-SlowBuffer.prototype.writeInt32BE = Buffer.prototype.writeInt32BE;
-SlowBuffer.prototype.writeFloatLE = Buffer.prototype.writeFloatLE;
-SlowBuffer.prototype.writeFloatBE = Buffer.prototype.writeFloatBE;
-SlowBuffer.prototype.writeDoubleLE = Buffer.prototype.writeDoubleLE;
-SlowBuffer.prototype.writeDoubleBE = Buffer.prototype.writeDoubleBE;
-
-})()
-},{"assert":9,"./buffer_ieee754":14,"base64-js":15}],15:[function(require,module,exports){
-(function (exports) {
- 'use strict';
-
- var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
-
- function b64ToByteArray(b64) {
- var i, j, l, tmp, placeHolders, arr;
-
- if (b64.length % 4 > 0) {
- throw 'Invalid string. Length must be a multiple of 4';
- }
-
- // the number of equal signs (place holders)
- // if there are two placeholders, than the two characters before it
- // represent one byte
- // if there is only one, then the three characters before it represent 2 bytes
- // this is just a cheap hack to not do indexOf twice
- placeHolders = b64.indexOf('=');
- placeHolders = placeHolders > 0 ? b64.length - placeHolders : 0;
-
- // base64 is 4/3 + up to two characters of the original data
- arr = [];//new Uint8Array(b64.length * 3 / 4 - placeHolders);
-
- // if there are placeholders, only get up to the last complete 4 chars
- l = placeHolders > 0 ? b64.length - 4 : b64.length;
-
- for (i = 0, j = 0; i < l; i += 4, j += 3) {
- tmp = (lookup.indexOf(b64[i]) << 18) | (lookup.indexOf(b64[i + 1]) << 12) | (lookup.indexOf(b64[i + 2]) << 6) | lookup.indexOf(b64[i + 3]);
- arr.push((tmp & 0xFF0000) >> 16);
- arr.push((tmp & 0xFF00) >> 8);
- arr.push(tmp & 0xFF);
- }
-
- if (placeHolders === 2) {
- tmp = (lookup.indexOf(b64[i]) << 2) | (lookup.indexOf(b64[i + 1]) >> 4);
- arr.push(tmp & 0xFF);
- } else if (placeHolders === 1) {
- tmp = (lookup.indexOf(b64[i]) << 10) | (lookup.indexOf(b64[i + 1]) << 4) | (lookup.indexOf(b64[i + 2]) >> 2);
- arr.push((tmp >> 8) & 0xFF);
- arr.push(tmp & 0xFF);
- }
-
- return arr;
- }
-
- function uint8ToBase64(uint8) {
- var i,
- extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
- output = "",
- temp, length;
-
- function tripletToBase64 (num) {
- return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
- };
-
- // go through the array every three bytes, we'll deal with trailing stuff later
- for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
- temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
- output += tripletToBase64(temp);
- }
-
- // pad the end with zeros, but make sure to not forget the extra bytes
- switch (extraBytes) {
- case 1:
- temp = uint8[uint8.length - 1];
- output += lookup[temp >> 2];
- output += lookup[(temp << 4) & 0x3F];
- output += '==';
- break;
- case 2:
- temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
- output += lookup[temp >> 10];
- output += lookup[(temp >> 4) & 0x3F];
- output += lookup[(temp << 2) & 0x3F];
- output += '=';
- break;
- }
-
- return output;
- }
-
- module.exports.toByteArray = b64ToByteArray;
- module.exports.fromByteArray = uint8ToBase64;
-}());
-
-},{}]},{},["E/GbHF"])
-;
-JSHINT = require('jshint').JSHINT;
-}());
diff --git a/dom/system/gonk/tests/marionette/ril_jshint/jshintrc b/dom/system/gonk/tests/marionette/ril_jshint/jshintrc
deleted file mode 100644
index 437fe1a6f..000000000
--- a/dom/system/gonk/tests/marionette/ril_jshint/jshintrc
+++ /dev/null
@@ -1,118 +0,0 @@
-{
- // JSHint Default Configuration File (as on JSHint website)
- // See http://jshint.com/docs/ for more details
-
- // Modify for RIL usage.
-
- "maxerr" : 10000, // {int} Maximum error before stopping
-
- // Enforcing
- "bitwise" : false, // true: Prohibit bitwise operators (&, |, ^, etc.)
- "camelcase" : false, // true: Identifiers must be in camelCase
- "curly" : false, // true: Require {} for every new block or scope
- "eqeqeq" : false, // true: Require triple equals (===) for comparison
- "forin" : false, // true: Require filtering for..in loops with obj.hasOwnProperty()
- "immed" : false, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());`
- //"indent" : 2, // {int} Number of spaces to use for indentation
- "latedef" : false, // true: Require variables/functions to be defined before being used
- "newcap" : false, // true: Require capitalization of all constructor functions e.g. `new F()`
- "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee`
- "noempty" : false, // true: Prohibit use of empty blocks
- "nonew" : false, // true: Prohibit use of constructors for side-effects (without assignment)
- "plusplus" : false, // true: Prohibit use of `++` & `--`
- "quotmark" : false, // Quotation mark consistency:
- // false : do nothing (default)
- // true : ensure whatever is used is consistent
- // "single" : require single quotes
- // "double" : require double quotes
- "undef" : false, // true: Require all non-global variables to be declared (prevents global leaks)
- "unused" : false, // true: Require all defined variables be used
- "strict" : false, // true: Requires all functions run in ES5 Strict Mode
- "trailing" : false, // true: Prohibit trailing whitespaces
- "maxparams" : false, // {int} Max number of formal params allowed per function
- "maxdepth" : false, // {int} Max depth of nested blocks (within functions)
- "maxstatements" : false, // {int} Max number statements per function
- "maxcomplexity" : false, // {int} Max cyclomatic complexity per function
- "maxlen" : false, // {int} Max number of characters per line
-
- // Relaxing
- "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons)
- "boss" : false, // true: Tolerate assignments where comparisons would be expected
- "debug" : false, // true: Allow debugger statements e.g. browser breakpoints.
- "eqnull" : true, // true: Tolerate use of `== null`
- "es5" : false, // true: Allow ES5 syntax (ex: getters and setters)
- "esnext" : false, // true: Allow ES.next (ES6) syntax (ex: `const`)
- "moz" : true, // true: Allow Mozilla specific syntax (extends and overrides esnext features)
- // (ex: `for each`, multiple try/catch, function expression…)
- "evil" : false, // true: Tolerate use of `eval` and `new Function()`
- "expr" : false, // true: Tolerate `ExpressionStatement` as Programs
- "funcscope" : false, // true: Tolerate defining variables inside control statements"
- "globalstrict" : true, // true: Allow global "use strict" (also enables 'strict')
- "iterator" : false, // true: Tolerate using the `__iterator__` property
- "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block
- "laxbreak" : true, // true: Tolerate possibly unsafe line breakings
- "laxcomma" : false, // true: Tolerate comma-first style coding
- "loopfunc" : false, // true: Tolerate functions being defined in loops
- "multistr" : false, // true: Tolerate multi-line strings
- "proto" : true, // true: Tolerate using the `__proto__` property
- "scripturl" : false, // true: Tolerate script-targeted URLs
- "smarttabs" : false, // true: Tolerate mixed tabs/spaces when used for alignment
- "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;`
- "sub" : false, // true: Tolerate using `[]` notation when it can still be expressed in dot notation
- "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;`
- "validthis" : true, // true: Tolerate using this in a non-constructor function
-
- // Environments
- "browser" : false, // Web Browser (window, document, etc)
- "couch" : false, // CouchDB
- "devel" : true, // Development/debugging (alert, confirm, etc)
- "dojo" : false, // Dojo Toolkit
- "jquery" : false, // jQuery
- "mootools" : false, // MooTools
- "node" : false, // Node.js
- "nonstandard" : false, // Widely adopted globals (escape, unescape, etc)
- "prototypejs" : false, // Prototype and Scriptaculous
- "rhino" : false, // Rhino
- "worker" : true, // Web Workers
- "wsh" : false, // Windows Scripting Host
- "yui" : false, // Yahoo User Interface
-
- // Legacy
- "nomen" : false, // true: Prohibit dangling `_` in variables
- "onevar" : false, // true: Allow only one `var` statement per function
- "passfail" : false, // true: Stop on first error
- "white" : false, // true: Check against strict whitespace and indentation rules
-
- // Custom Globals
- "predef" : [ ], // additional predefined global variables
-
- "globals": {
- "ChromeWorker": false,
- "Components": false,
- "DOMRequestIpcHelper": false,
- "ObjectWrapper": false,
- "PhoneNumberUtils": false,
- "RILNetworkInterface": false,
- "Services": false,
- "Uint8Array": false,
- "WAP": false,
- "XPCOMUtils": false,
- "cpmm": false,
- "dump": false,
- "gAudioManager": false,
- "gMessageManager": false,
- "gMobileMessageDatabaseService": false,
- "gMobileMessageService": false,
- "gNetworkManager": false,
- "gPowerManagerService": false,
- "gSettingsService": false,
- "gSmsService": false,
- "gSystemMessenger": false,
- "gSystemWorkerManager": false,
- "gTimeService": false,
- "gUUIDGenerator": false,
- "ppmm": true,
-
- "__end_guardian_for_easy_sorting__": false
- }
-}
diff --git a/dom/system/gonk/tests/marionette/test_all_network_info.js b/dom/system/gonk/tests/marionette/test_all_network_info.js
deleted file mode 100644
index 5225ab6d6..000000000
--- a/dom/system/gonk/tests/marionette/test_all_network_info.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-var networkManager =
- Cc["@mozilla.org/network/manager;1"].getService(Ci.nsINetworkManager);
-ok(networkManager,
- "networkManager.constructor is " + networkManager.constructor);
-
-var wifiManager = window.navigator.mozWifiManager;
-ok(wifiManager, "wifiManager.constructor is " + wifiManager.constructor);
-
-function setEmulatorAPN() {
- let apn = [
- [{"carrier":"T-Mobile US",
- "apn":"epc.tmobile.com",
- "mmsc":"http://mms.msg.eng.t-mobile.com/mms/wapenc",
- "types":["default","supl","mms","ims","dun", "fota"]}]
- ];
-
- return setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, apn);
-}
-
-function ensureWifiEnabled(aEnabled) {
- if (wifiManager.enabled === aEnabled) {
- log('Already ' + (aEnabled ? 'enabled' : 'disabled'));
- return Promise.resolve();
- }
- return requestWifiEnabled(aEnabled);
-}
-
-function requestWifiEnabled(aEnabled) {
- let promises = [];
-
- promises.push(waitForTargetEvent(wifiManager, aEnabled ? 'enabled' : 'disabled',
- function() {
- return wifiManager.enabled === aEnabled ? true : false;
- }));
- promises.push(setSettings(SETTINGS_KEY_WIFI_ENABLED, aEnabled));
-
- return Promise.all(promises);
-}
-
-// Test initial State
-function verifyInitialState() {
- log("= verifyInitialState =");
-
- // Data and wifi should be off before starting any test.
- return getSettings(SETTINGS_KEY_DATA_ENABLED)
- .then(value => {
- is(value, false, "Data must be off");
- })
- .then(() => ensureWifiEnabled(false));
-}
-
-function testAllNetworkInfo(aAnyConnected) {
- log("= testAllNetworkInfo = " + aAnyConnected);
-
- let allNetworkInfo = networkManager.allNetworkInfo;
- ok(allNetworkInfo, "NetworkManager.allNetworkInfo");
-
- let count = Object.keys(allNetworkInfo).length;
- ok(count > 0, "NetworkManager.allNetworkInfo count");
-
- let connected = false;
- for (let networkId in allNetworkInfo) {
- if (allNetworkInfo.hasOwnProperty(networkId)) {
- let networkInfo = allNetworkInfo[networkId];
- if (networkInfo.state == Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- connected = true;
- break;
- }
- }
- }
-
- is(aAnyConnected, connected, "NetworkManager.allNetworkInfo any connected");
-}
-
-// Start test
-startTestBase(function() {
-
- let origApnSettings, origWifiEnabled;
- return Promise.resolve()
- .then(() => {
- origWifiEnabled = wifiManager.enabled;
- })
- .then(() => verifyInitialState())
- .then(() => getSettings(SETTINGS_KEY_DATA_APN_SETTINGS))
- .then(value => {
- origApnSettings = value;
- })
- .then(() => setEmulatorAPN())
- .then(() => setDataEnabledAndWait(true))
- .then(() => testAllNetworkInfo(true))
- .then(() => setDataEnabledAndWait(false))
- .then(() => testAllNetworkInfo(false))
- // Restore original apn settings and wifi state.
- .then(() => {
- if (origApnSettings) {
- return setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, origApnSettings);
- }
- })
- .then(() => ensureWifiEnabled(origWifiEnabled));
-});
diff --git a/dom/system/gonk/tests/marionette/test_data_connection.js b/dom/system/gonk/tests/marionette/test_data_connection.js
deleted file mode 100644
index 5a53b1e5f..000000000
--- a/dom/system/gonk/tests/marionette/test_data_connection.js
+++ /dev/null
@@ -1,70 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-function setEmulatorAPN() {
- let apn = [
- [{"carrier":"T-Mobile US",
- "apn":"epc.tmobile.com",
- "mmsc":"http://mms.msg.eng.t-mobile.com/mms/wapenc",
- "types":["default","supl","mms","ims","dun", "fota"]}]
- ];
-
- return setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, apn);
-}
-
-// Test initial State
-function testInitialState() {
- log("= testInitialState =");
-
- // Data should be off before starting any test.
- return getSettings(SETTINGS_KEY_DATA_ENABLED)
- .then(value => {
- is(value, false, "Data must be off");
- });
-}
-
-// Test default data Connection
-function testDefaultDataConnection() {
- log("= testDefaultDataConnection =");
-
- // Enable default data
- return setDataEnabledAndWait(true)
- // Disable default data
- .then(() => setDataEnabledAndWait(false));
-}
-
-// Test non default data connection
-function testNonDefaultDataConnection() {
- log("= testNonDefaultDataConnection =");
-
- function doTestNonDefaultDataConnection(type) {
- log("doTestNonDefaultDataConnection: " + type);
-
- return setupDataCallAndWait(type)
- .then(() => deactivateDataCallAndWait(type));
- }
-
- let currentApn;
- return getSettings(SETTINGS_KEY_DATA_APN_SETTINGS)
- .then(value => {
- currentApn = value;
- })
- .then(setEmulatorAPN)
- .then(() => doTestNonDefaultDataConnection(NETWORK_TYPE_MOBILE_MMS))
- .then(() => doTestNonDefaultDataConnection(NETWORK_TYPE_MOBILE_SUPL))
- .then(() => doTestNonDefaultDataConnection(NETWORK_TYPE_MOBILE_IMS))
- .then(() => doTestNonDefaultDataConnection(NETWORK_TYPE_MOBILE_DUN))
- .then(() => doTestNonDefaultDataConnection(NETWORK_TYPE_MOBILE_FOTA))
- // Restore APN settings
- .then(() => setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, currentApn));
-}
-
-// Start test
-startTestBase(function() {
- return testInitialState()
- .then(() => testDefaultDataConnection())
- .then(() => testNonDefaultDataConnection());
-});
diff --git a/dom/system/gonk/tests/marionette/test_data_connection_proxy.js b/dom/system/gonk/tests/marionette/test_data_connection_proxy.js
deleted file mode 100644
index a99187538..000000000
--- a/dom/system/gonk/tests/marionette/test_data_connection_proxy.js
+++ /dev/null
@@ -1,99 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-const HTTP_PROXY = "10.0.2.200";
-const HTTP_PROXY_PORT = "8080";
-const MANUAL_PROXY_CONFIGURATION = 1;
-
-// Test initial State
-function verifyInitialState() {
- log("= verifyInitialState =");
-
- // Data should be off before starting any test.
- return getSettings(SETTINGS_KEY_DATA_ENABLED)
- .then(value => {
- is(value, false, "Data must be off");
- });
-}
-
-function setTestApn() {
- let apn = [
- [ {"carrier": "T-Mobile US",
- "apn": "epc.tmobile.com",
- "proxy": HTTP_PROXY,
- "port": HTTP_PROXY_PORT,
- "mmsc": "http://mms.msg.eng.t-mobile.com/mms/wapenc",
- "types": ["default","supl","mms"]} ]
- ];
-
- return setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, apn);
-}
-
-function waitForHttpProxyVerified(aShouldBeSet) {
- let TIME_OUT_VALUE = 20000;
-
- return new Promise(function(aResolve, aReject) {
- try {
- waitFor(aResolve, () => {
- let proxyType = SpecialPowers.getIntPref("network.proxy.type");
- let httpProxy = SpecialPowers.getCharPref("network.proxy.http");
- let sslProxy = SpecialPowers.getCharPref("network.proxy.ssl");
- let httpProxyPort = SpecialPowers.getIntPref("network.proxy.http_port");
- let sslProxyPort = SpecialPowers.getIntPref("network.proxy.ssl_port");
-
- if ((aShouldBeSet &&
- proxyType == MANUAL_PROXY_CONFIGURATION &&
- httpProxy == HTTP_PROXY &&
- sslProxy == HTTP_PROXY &&
- httpProxyPort == HTTP_PROXY_PORT &&
- sslProxyPort == HTTP_PROXY_PORT) ||
- (!aShouldBeSet && proxyType != MANUAL_PROXY_CONFIGURATION &&
- !httpProxy && !sslProxy && !httpProxyPort && !sslProxyPort)) {
- return true;
- }
-
- return false;
- }, TIME_OUT_VALUE);
- } catch(aError) {
- // Timed out.
- aReject(aError);
- }
- });
-}
-
-function testDefaultDataHttpProxy() {
- log("= testDefaultDataHttpProxy =");
-
- return setDataEnabledAndWait(true)
- .then(() => waitForHttpProxyVerified(true))
- .then(() => setDataEnabledAndWait(false))
- .then(() => waitForHttpProxyVerified(false));
-}
-
-function testNonDefaultDataHttpProxy(aType) {
- log("= testNonDefaultDataHttpProxy - " + aType + " =");
-
- return setupDataCallAndWait(aType)
- // Http proxy should not be set for non-default data connections.
- .then(() => waitForHttpProxyVerified(false))
- .then(() => deactivateDataCallAndWait(aType));
-}
-
-// Start test
-startTestBase(function() {
- let origApnSettings;
- return verifyInitialState()
- .then(() => getSettings(SETTINGS_KEY_DATA_APN_SETTINGS))
- .then(value => {
- origApnSettings = value;
- })
- .then(() => setTestApn())
- .then(() => testDefaultDataHttpProxy())
- .then(() => testNonDefaultDataHttpProxy(NETWORK_TYPE_MOBILE_MMS))
- .then(() => testNonDefaultDataHttpProxy(NETWORK_TYPE_MOBILE_SUPL))
- // Restore APN settings
- .then(() => setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, origApnSettings));
-});
diff --git a/dom/system/gonk/tests/marionette/test_dsds_numRadioInterfaces.js b/dom/system/gonk/tests/marionette/test_dsds_numRadioInterfaces.js
deleted file mode 100644
index e178b8b65..000000000
--- a/dom/system/gonk/tests/marionette/test_dsds_numRadioInterfaces.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_CONTEXT = "chrome";
-
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-
-const NS_RIL_CONTRACTID = "@mozilla.org/ril;1";
-
-const PROP_RO_MOZ_RIL_NUMCLIENTS = "ro.moz.ril.numclients";
-
-const PREF_RIL_NUM_RADIO_INTERFACES = "ril.numRadioInterfaces";
-
-ok(libcutils, "libcutils is available");
-
-var propNum = (function() {
- try {
- let numString = libcutils.property_get(PROP_RO_MOZ_RIL_NUMCLIENTS, "1");
- let num = parseInt(numString, 10);
- if (num >= 0) {
- return num;
- }
- } catch (e) {}
-})();
-
-log("Retrieved '" + PROP_RO_MOZ_RIL_NUMCLIENTS + "' = " + propNum);
-ok(propNum, PROP_RO_MOZ_RIL_NUMCLIENTS);
-
-var prefNum = Services.prefs.getIntPref(PREF_RIL_NUM_RADIO_INTERFACES);
-log("Retrieved '" + PREF_RIL_NUM_RADIO_INTERFACES + "' = " + prefNum);
-
-var ril = Cc[NS_RIL_CONTRACTID].getService(Ci.nsIRadioInterfaceLayer);
-ok(ril, "ril.constructor is " + ril.constructor);
-
-var ifaceNum = ril.numRadioInterfaces;
-log("Retrieved 'nsIRadioInterfaceLayer.numRadioInterfaces' = " + ifaceNum);
-
-is(propNum, prefNum);
-is(propNum, ifaceNum);
-
-finish();
diff --git a/dom/system/gonk/tests/marionette/test_fakevolume.js b/dom/system/gonk/tests/marionette/test_fakevolume.js
deleted file mode 100644
index 173f9ac11..000000000
--- a/dom/system/gonk/tests/marionette/test_fakevolume.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 10000;
-
-var Cc = SpecialPowers.Cc;
-var Ci = SpecialPowers.Ci;
-
-var volumeService = Cc["@mozilla.org/telephony/volume-service;1"].getService(Ci.nsIVolumeService);
-ok(volumeService, "Should have volume service");
-
-var volName = "fake";
-var mountPoint = "/data/fake/storage";
-volumeService.createFakeVolume(volName, mountPoint);
-
-var vol = volumeService.getVolumeByName(volName);
-ok(vol, "volume shouldn't be null");
-
-is(volName, vol.name, "name");
-is(mountPoint, vol.mountPoint, "moutnPoint");
-is(Ci.nsIVolume.STATE_MOUNTED, vol.state, "state");
-
-ok(vol.mountGeneration > 0, "mount generation should not be zero");
-
-finish();
diff --git a/dom/system/gonk/tests/marionette/test_geolocation.js b/dom/system/gonk/tests/marionette/test_geolocation.js
deleted file mode 100644
index 201c8b3e3..000000000
--- a/dom/system/gonk/tests/marionette/test_geolocation.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 10000;
-
-var geolocation = window.navigator.geolocation;
-ok(geolocation);
-
-var sample = [];
-var result = [];
-var wpid;
-
-/**
- * Grant special power to get the geolocation
- */
-SpecialPowers.addPermission("geolocation", true, document);
-
-/**
- * Disable wifi geolocation provider
- */
-wifiUri = SpecialPowers.getCharPref("geo.wifi.uri");
-SpecialPowers.setCharPref("geo.wifi.uri", "http://mochi.test:8888/tests/dom/tests/mochitest/geolocation/network_geolocation.sjs?action=stop-responding");
-
-/**
- * Helper that compares the geolocation against the web API.
- */
-function verifyLocation() {
-
- log("Sample:" + sample.join(','));
- log("Result:" + result.join(','));
-
- for (i in sample) {
- is(sample.pop(), result.pop());
- }
-
- window.setTimeout(cleanup, 0);
-}
-
-/**
- * Test story begins here.
- */
-function setup() {
- log("Providing initial setup: set geographic position watcher.");
-
-
- wpid = geolocation.watchPosition(function(position) {
- log("Position changes: (" + position.coords.latitude + "/" + position.coords.longitude + ")");
- result.push(""+position.coords.latitude + "/" + position.coords.longitude);
- });
-
- lat = 0;
- lon = 0;
-
- cmd = "geo fix " + lon + " " + lat;
- sample.push(lat+"/"+lon);
-
- runEmulatorCmd(cmd, function(result) {
- window.setTimeout(movePosition_1, 0);
- });
-}
-
-function movePosition_1() {
- log("Geolocation changes. Move to Position 1.");
-
- lat = 25;
- lon = 121.56499833333334;
-
- cmd = "geo fix " + lon + " " + lat;
- sample.push(lat+"/"+lon);
-
- runEmulatorCmd(cmd, function(result) {
- window.setTimeout(movePosition_2, 0);
- });
-}
-
-function movePosition_2() {
- log("Geolocation changes to a negative longitude. Move to Position 2.");
-
- lat = 37.393;
- lon = -122.08199833333335;
-
- cmd = "geo fix " + lon + " " + lat;
- sample.push(lat+"/"+lon);
-
- runEmulatorCmd(cmd, function(result) {
- window.setTimeout(movePosition_3, 0);
- });
-}
-
-function movePosition_3() {
- log("Geolocation changes with WatchPosition. Move to Position 3.");
-
- lat = -22;
- lon = -43;
-
- cmd = "geo fix " + lon + " " + lat;
- sample.push(lat+"/"+lon);
-
- geolocation.getCurrentPosition(function(position) {
- log("getCurrentPosition: Expected location: ("+lat+"/"+lon+"); Current location: (" + position.coords.latitude + "/" + position.coords.longitude + ")");
- is(lat, position.coords.latitude);
- is(lon, position.coords.longitude);
- });
-
- runEmulatorCmd(cmd, function(result) {
- window.setTimeout(verifyLocation, 0);
- });
-}
-
-function cleanup() {
- geolocation.clearWatch(wpid);
- SpecialPowers.removePermission("geolocation", document);
- SpecialPowers.setCharPref("geo.wifi.uri", wifiUri);
- finish();
-}
-
-setup();
diff --git a/dom/system/gonk/tests/marionette/test_multiple_data_connection.js b/dom/system/gonk/tests/marionette/test_multiple_data_connection.js
deleted file mode 100644
index 24abd4451..000000000
--- a/dom/system/gonk/tests/marionette/test_multiple_data_connection.js
+++ /dev/null
@@ -1,89 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-// Must sync with hardware/ril/reference-ril/reference-ril.c
-const MAX_DATA_CONTEXTS = 4;
-
-function setEmulatorAPN() {
- // Use different apn for each network type.
- let apn = [[ { "carrier":"T-Mobile US",
- "apn":"epc1.tmobile.com",
- "types":["default"] },
- { "carrier":"T-Mobile US",
- "apn":"epc2.tmobile.com",
- "mmsc":"http://mms.msg.eng.t-mobile.com/mms/wapenc",
- "types":["mms"] },
- { "carrier":"T-Mobile US",
- "apn":"epc3.tmobile.com",
- "types":["supl"] },
- { "carrier":"T-Mobile US",
- "apn":"epc4.tmobile.com",
- "types":["ims"] },
- { "carrier":"T-Mobile US",
- "apn":"epc5.tmobile.com",
- "types":["dun"] },
- { "carrier":"T-Mobile US",
- "apn":"epc6.tmobile.com",
- "types":["fota"] }]];
-
- return setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, apn);
-}
-
-// Test initial State
-function testInitialState() {
- log("= testInitialState =");
-
- // Data should be off before starting any test.
- return getSettings(SETTINGS_KEY_DATA_ENABLED)
- .then(value => {
- is(value, false, "Data must be off");
- });
-}
-
-function testSetupConcurrentDataCalls() {
- log("= testSetupConcurrentDataCalls =");
-
- let promise = Promise.resolve();
- // Skip default mobile type.
- for (let i = 1; i < MAX_DATA_CONTEXTS; i++) {
- let type = networkTypes[i];
- promise = promise.then(() => setupDataCallAndWait(type));
- }
- return promise;
-}
-
-function testDeactivateConcurrentDataCalls() {
- log("= testDeactivateConcurrentDataCalls =");
-
- let promise = Promise.resolve();
- // Skip default mobile type.
- for (let i = 1; i < MAX_DATA_CONTEXTS; i++) {
- let type = networkTypes[i];
- promise = promise.then(() => deactivateDataCallAndWait(type));
- }
- return promise;
-}
-
-// Start test
-startTestBase(function() {
-
- let origApnSettings;
- return testInitialState()
- .then(() => getSettings(SETTINGS_KEY_DATA_APN_SETTINGS))
- .then(value => {
- origApnSettings = value;
- })
- .then(() => setEmulatorAPN())
- .then(() => setDataEnabledAndWait(true))
- .then(() => testSetupConcurrentDataCalls())
- .then(() => testDeactivateConcurrentDataCalls())
- .then(() => setDataEnabledAndWait(false))
- .then(() => {
- if (origApnSettings) {
- return setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, origApnSettings);
- }
- });
-});
diff --git a/dom/system/gonk/tests/marionette/test_network_active_changed.js b/dom/system/gonk/tests/marionette/test_network_active_changed.js
deleted file mode 100644
index 5886f37ed..000000000
--- a/dom/system/gonk/tests/marionette/test_network_active_changed.js
+++ /dev/null
@@ -1,52 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-var networkManager =
- Cc["@mozilla.org/network/manager;1"].getService(Ci.nsINetworkManager);
-ok(networkManager,
- "networkManager.constructor is " + networkManager.constructor);
-
-function testInitialState() {
- return getSettings(SETTINGS_KEY_DATA_ENABLED)
- .then((enabled) => {
- is(enabled, false, "data should be off by default");
- is(networkManager.activeNetworkInfo, null,
- "networkManager.activeNetworkInfo should be null by default");
- });
-}
-
-function testActiveNetworkChangedBySwitchingDataCall(aDataCallEnabled) {
- log("Test active network by switching dataCallEnabled to " + aDataCallEnabled);
-
- let promises = [];
- promises.push(waitForObserverEvent(TOPIC_NETWORK_ACTIVE_CHANGED));
- promises.push(setSettings(SETTINGS_KEY_DATA_ENABLED, aDataCallEnabled));
-
- return Promise.all(promises).then(function(results) {
- let subject = results[0];
-
- if (aDataCallEnabled) {
- ok(subject instanceof Ci.nsINetworkInfo,
- "subject should be an instance of nsINetworkInfo");
- ok(subject instanceof Ci.nsIRilNetworkInfo,
- "subject should be an instance of nsIRilNetworkInfo");
- is(subject.type, NETWORK_TYPE_MOBILE,
- "subject.type should be NETWORK_TYPE_MOBILE");
- }
-
- is(subject, networkManager.activeNetworkInfo,
- "subject should be equal with networkManager.activeNetworkInfo");
- });
-}
-
-// Start test
-startTestBase(function() {
- return testInitialState()
- // Test active network changed by enabling data call.
- .then(() => testActiveNetworkChangedBySwitchingDataCall(true))
- // Test active network changed by disabling data call.
- .then(() => testActiveNetworkChangedBySwitchingDataCall(false));
-});
diff --git a/dom/system/gonk/tests/marionette/test_network_interface_list_service.js b/dom/system/gonk/tests/marionette/test_network_interface_list_service.js
deleted file mode 100644
index 549940fa5..000000000
--- a/dom/system/gonk/tests/marionette/test_network_interface_list_service.js
+++ /dev/null
@@ -1,95 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-function getNetworkInfo(aType) {
- let networkListService =
- Cc["@mozilla.org/network/interface-list-service;1"].
- getService(Ci.nsINetworkInterfaceListService);
- // Get all available interfaces
- let networkList = networkListService.getDataInterfaceList(0);
-
- // Try to get nsINetworkInterface for aType.
- let numberOfInterface = networkList.getNumberOfInterface();
- for (let i = 0; i < numberOfInterface; i++) {
- let info = networkList.getInterfaceInfo(i);
- if (info.type === aType) {
- return info;
- }
- }
-
- return null;
-}
-
-// Test getDataInterfaceList by enabling/disabling mobile data.
-function testGetDataInterfaceList(aMobileDataEnabled) {
- log("Test getDataInterfaceList with mobile data " +
- aMobileDataEnabled ? "enabled" : "disabled");
-
- return setDataEnabledAndWait(aMobileDataEnabled)
- .then(() => getNetworkInfo(NETWORK_TYPE_MOBILE))
- .then((networkInfo) => {
- if (!networkInfo) {
- ok(false, "Should get an valid nsINetworkInfo for mobile");
- return;
- }
-
- ok(networkInfo instanceof Ci.nsINetworkInfo,
- "networkInfo should be an instance of nsINetworkInfo");
-
- let ipAddresses = {};
- let prefixs = {};
- let numOfGateways = {};
- let numOfDnses = {};
- let numOfIpAddresses = networkInfo.getAddresses(ipAddresses, prefixs);
- let gateways = networkInfo.getGateways(numOfGateways);
- let dnses = networkInfo.getDnses(numOfDnses);
-
- if (aMobileDataEnabled) {
- // Mobile data is enabled.
- is(networkInfo.state, NETWORK_STATE_CONNECTED, "check state");
- ok(numOfIpAddresses > 0, "check number of ipAddresses");
- ok(ipAddresses.value.length > 0, "check ipAddresses.length");
- ok(prefixs.value.length > 0, "check prefixs.length");
- ok(numOfGateways.value > 0, "check number of gateways");
- ok(prefixs.value.length > 0, "check prefixs.length");
- ok(gateways.length > 0, "check gateways.length");
- ok(numOfDnses.value > 0, "check number of dnses");
- ok(dnses.length > 0, "check dnses.length");
- } else {
- // Mobile data is disabled.
- is(networkInfo.state, NETWORK_STATE_DISCONNECTED, "check state");
- is(numOfIpAddresses, 0, "check number of ipAddresses");
- is(ipAddresses.value.length, 0, "check ipAddresses.length");
- is(prefixs.value.length, 0, "check prefixs.length");
- is(numOfGateways.value, 0, "check number of gateways");
- is(prefixs.value.length, 0, "check prefixs.length");
- is(gateways.length, 0, "check gateways.length");
- is(numOfDnses.value, 0, "check number of dnses");
- is(dnses.length, 0, "check dnses.length");
- }
- });
-}
-
-// Start test
-startTestBase(function() {
- return Promise.resolve()
- // Test initial State
- .then(() => {
- log("Test initial state");
-
- // Data should be off before starting any test.
- return getSettings(SETTINGS_KEY_DATA_ENABLED)
- .then(value => {
- is(value, false, "Mobile data must be off");
- });
- })
-
- // Test getDataInterfaceList with mobile data enabled.
- .then(() => testGetDataInterfaceList(true))
-
- // Test getDataInterfaceList with mobile data disabled.
- .then(() => testGetDataInterfaceList(false));
-});
diff --git a/dom/system/gonk/tests/marionette/test_network_interface_mtu.js b/dom/system/gonk/tests/marionette/test_network_interface_mtu.js
deleted file mode 100644
index 679efe2ed..000000000
--- a/dom/system/gonk/tests/marionette/test_network_interface_mtu.js
+++ /dev/null
@@ -1,100 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = "head.js";
-
-const TEST_MTU1 = "1410";
-const TEST_MTU2 = "1440";
-
-function setEmulatorAPN() {
- let apn = [
- [ { "carrier":"T-Mobile US",
- "apn":"epc1.tmobile.com",
- "types":["default"],
- "mtu": TEST_MTU1 },
- { "carrier":"T-Mobile US",
- "apn":"epc2.tmobile.com",
- "mmsc":"http://mms.msg.eng.t-mobile.com/mms/wapenc",
- "types":["supl","mms","ims","dun", "fota"],
- "mtu": TEST_MTU2 } ]
- ];
-
- return setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, apn);
-}
-
-function verifyInitialState() {
- // Data should be off before starting any test.
- return getSettings(SETTINGS_KEY_DATA_ENABLED)
- .then(value => {
- is(value, false, "Data must be off");
- });
-}
-
-function verifyMtu(aInterfaceName, aMtu) {
- return runEmulatorShellCmdSafe(['ip', 'link', 'show', 'dev', aInterfaceName])
- .then(aLines => {
- // Sample output:
- //
- // 4: rmnet0: <BROADCAST,MULTICAST> mtu 1410 qdisc pfifo_fast state DOWN mode DEFAULT qlen 1000
- // link/ether 52:54:00:12:34:58 brd ff:ff:ff:ff:ff:ff
- //
- let mtu;
- aLines.some(function (aLine) {
- let tokens = aLine.trim().split(/\s+/);
- let mtuIndex = tokens.indexOf('mtu');
- if (mtuIndex < 0 || mtuIndex + 1 >= tokens.length) {
- return false;
- }
-
- mtu = tokens[mtuIndex + 1];
- return true;
- });
-
- is(mtu, aMtu, aInterfaceName + "'s mtu.");
- });
-}
-
-function testDefaultDataCallMtu() {
- log("= testDefaultDataCallMtu =");
-
- return setDataEnabledAndWait(true)
- .then(aNetworkInfo => verifyMtu(aNetworkInfo.name, TEST_MTU1))
- .then(() => setDataEnabledAndWait(false));
-}
-
-function testNonDefaultDataCallMtu() {
- log("= testNonDefaultDataCallMtu =");
-
- function doTestNonDefaultDataCallMtu(aType) {
- log("doTestNonDefaultDataCallMtu: " + aType);
-
- return setupDataCallAndWait(aType)
- .then(aNetworkInfo => verifyMtu(aNetworkInfo.name, TEST_MTU2))
- .then(() => deactivateDataCallAndWait(aType));
- }
-
- return doTestNonDefaultDataCallMtu(NETWORK_TYPE_MOBILE_MMS)
- .then(() => doTestNonDefaultDataCallMtu(NETWORK_TYPE_MOBILE_SUPL))
- .then(() => doTestNonDefaultDataCallMtu(NETWORK_TYPE_MOBILE_IMS))
- .then(() => doTestNonDefaultDataCallMtu(NETWORK_TYPE_MOBILE_DUN))
- .then(() => doTestNonDefaultDataCallMtu(NETWORK_TYPE_MOBILE_FOTA));
-}
-
-// Start test
-startTestBase(function() {
- let origApnSettings;
- return verifyInitialState()
- .then(() => getSettings(SETTINGS_KEY_DATA_APN_SETTINGS))
- .then(value => {
- origApnSettings = value;
- })
- .then(() => setEmulatorAPN())
- .then(() => testDefaultDataCallMtu())
- .then(() => testNonDefaultDataCallMtu())
- .then(() => {
- if (origApnSettings) {
- return setSettings(SETTINGS_KEY_DATA_APN_SETTINGS, origApnSettings);
- }
- });
-});
diff --git a/dom/system/gonk/tests/marionette/test_ril_code_quality.py b/dom/system/gonk/tests/marionette/test_ril_code_quality.py
deleted file mode 100644
index d741d8a2e..000000000
--- a/dom/system/gonk/tests/marionette/test_ril_code_quality.py
+++ /dev/null
@@ -1,371 +0,0 @@
-"""
-The test performs the static code analysis check by JSHint.
-
-Target js files:
-- RadioInterfaceLayer.js
-- ril_worker.js
-- ril_consts.js
-
-If the js file contains the line of 'importScript()' (Ex: ril_worker.js), the
-test will perform a special merge step before excuting JSHint.
-
-Ex: Script A
---------------------------------
-importScripts('Script B')
-...
---------------------------------
-
-We merge these two scripts into one by the following way.
-
---------------------------------
-[Script B (ex: ril_consts.js)]
-(function(){ [Script A (ex: ril_worker.js)]
-})();
---------------------------------
-
-Script A (ril_worker.js) runs global strict mode.
-Script B (ril_consts.js) not.
-
-The above merge way ensures the correct scope of 'strict mode.'
-"""
-
-import bisect
-import inspect
-import os
-import os.path
-import re
-import unicodedata
-
-from marionette_harness import MarionetteTestCase
-
-
-class StringUtility:
-
- """A collection of some string utilities."""
-
- @staticmethod
- def find_match_lines(lines, pattern):
- """Return a list of lines that contains given pattern."""
- return [line for line in lines if pattern in line]
-
- @staticmethod
- def remove_non_ascii(data):
- """Remove non ascii characters in data and return it as new string."""
- if type(data).__name__ == 'unicode':
- data = unicodedata.normalize(
- 'NFKD', data).encode('ascii', 'ignore')
- return data
-
- @staticmethod
- def auto_close(lines):
- """Ensure every line ends with '\n'."""
- if lines and not lines[-1].endswith('\n'):
- lines[-1] += '\n'
- return lines
-
- @staticmethod
- def auto_wrap_strict_mode(lines):
- """Wrap by function scope if lines contain 'use strict'."""
- if StringUtility.find_match_lines(lines, 'use strict'):
- lines[0] = '(function(){' + lines[0]
- lines.append('})();\n')
- return lines
-
- @staticmethod
- def get_imported_list(lines):
- """Get a list of imported items."""
- return [item
- for line in StringUtility.find_match_lines(lines, 'importScripts')
- for item in StringUtility._get_imported_list_from_line(line)]
-
- @staticmethod
- def _get_imported_list_from_line(line):
- """Extract all items from 'importScripts(...)'.
-
- importScripts("ril_consts.js", "systemlibs.js")
- => ['ril_consts', 'systemlibs.js']
-
- """
- pattern = re.compile(r'\s*importScripts\((.*)\)')
- m = pattern.match(line)
- if not m:
- raise Exception('Parse importScripts error.')
- return [name.translate(None, '\' "') for name in m.group(1).split(',')]
-
-
-class ResourceUriFileReader:
-
- """Handle the process of reading the source code from system."""
-
- URI_PREFIX = 'resource://gre/'
- URI_PATH = {
- 'RadioInterfaceLayer.js': 'components/RadioInterfaceLayer.js',
- 'ril_worker.js': 'modules/ril_worker.js',
- 'ril_consts.js': 'modules/ril_consts.js',
- 'systemlibs.js': 'modules/systemlibs.js',
- 'worker_buf.js': 'modules/workers/worker_buf.js',
- }
-
- CODE_OPEN_CHANNEL_BY_URI = '''
- var Cc = Components.classes;
- var Ci = Components.interfaces;
- var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
- var secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager);
- global.uri = '%(uri)s';
- global.channel = ios.newChannel2(global.uri,
- null,
- null,
- null, // aLoadingNode
- secMan.getSystemPrincipal(),
- null, // aTriggeringPrincipal
- Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
- Ci.nsIContentPolicy.TYPE_OTHER);
- '''
-
- CODE_GET_SPEC = '''
- return global.channel.URI.spec;
- '''
-
- CODE_READ_CONTENT = '''
- var Cc = Components.classes;
- var Ci = Components.interfaces;
-
- var zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(Ci.nsIZipReader);
- var inputStream = Cc["@mozilla.org/scriptableinputstream;1"].createInstance(Ci.nsIScriptableInputStream);
-
- var jaruri = global.channel.URI.QueryInterface(Ci.nsIJARURI);
- var file = jaruri.JARFile.QueryInterface(Ci.nsIFileURL).file;
- var entry = jaruri.JAREntry;
- zipReader.open(file);
- inputStream.init(zipReader.getInputStream(entry));
- var content = inputStream.read(inputStream.available());
- inputStream.close();
- zipReader.close();
- return content;
- '''
-
- @classmethod
- def get_uri(cls, filename):
- """Convert filename to URI in system."""
- if filename.startswith(cls.URI_PREFIX):
- return filename
- else:
- return cls.URI_PREFIX + cls.URI_PATH[filename]
-
- def __init__(self, marionette):
- self.runjs = lambda x: marionette.execute_script(x,
- new_sandbox=False,
- sandbox='system')
-
- def read_file(self, filename):
- """Read file and return the contents as string."""
- content = self._read_uri(self.get_uri(filename))
- content = content.replace('"use strict";', '')
- return StringUtility.remove_non_ascii(content)
-
- def _read_uri(self, uri):
- """Read URI in system and return the contents as string."""
- # Open the uri as a channel.
- self.runjs(self.CODE_OPEN_CHANNEL_BY_URI % {'uri': uri})
-
- # Make sure spec is a jar uri, and not recursive.
- # Ex: 'jar:file:///system/b2g/omni.ja!/modules/ril_worker.js'
- #
- # For simplicity, we don't handle other special cases in this test.
- # If B2G build system changes in the future, such as put the jar in
- # another jar, the test case will fail.
- spec = self.runjs(self.CODE_GET_SPEC)
- if (not spec.startswith('jar:file://')) or (spec.count('jar:') != 1):
- raise Exception('URI resolve error')
-
- # Read the content from channel.
- content = self.runjs(self.CODE_READ_CONTENT)
- return content
-
-
-class JSHintEngine:
-
- """Invoke jshint script on system."""
-
- CODE_INIT_JSHINT = '''
- %(script)s;
- global.JSHINT = JSHINT;
- global.options = JSON.parse(%(config_string)s);
- global.globals = global.options.globals;
- delete global.options.globals;
- '''
-
- CODE_RUN_JSHINT = '''
- global.script = %(code)s;
- return global.JSHINT(global.script, global.options, global.globals);
- '''
-
- CODE_GET_JSHINT_ERROR = '''
- return global.JSHINT.errors;
- '''
-
- def __init__(self, marionette, script, config):
- # Remove single line comment in config.
- config = '\n'.join([line.partition('//')[0]
- for line in config.splitlines()])
-
- # Set global (JSHINT, options, global) in js environment.
- self.runjs = lambda x: marionette.execute_script(x,
- new_sandbox=False,
- sandbox='system')
- self.runjs(self.CODE_INIT_JSHINT %
- {'script': script, 'config_string': repr(config)})
-
- def run(self, code, filename=''):
- """Excute JShint check for the given code."""
- check_pass = self.runjs(self.CODE_RUN_JSHINT % {'code': repr(code)})
- errors = self.runjs(self.CODE_GET_JSHINT_ERROR)
- return check_pass, self._get_error_messages(errors, filename)
-
- def _get_error_messages(self, errors, filename=''):
- """
- Convert an error object to a list of readable string.
-
- [{"a": null, "c": null, "code": "W033", "d": null, "character": 6,
- "evidence": "var a", "raw": "Missing semicolon.",
- "reason": "Missing semicolon.", "b": null, "scope": "(main)", "line": 1,
- "id": "(error)"}]
- => line 1, col 6, Missing semicolon.
-
- """
- LINE, COL, REASON = u'line', u'character', u'reason'
- return ["%s: line %s, col %s, %s" %
- (filename, error[LINE], error[COL], error[REASON])
- for error in errors if error]
-
-
-class Linter:
-
- """Handle the linting related process."""
-
- def __init__(self, code_reader, jshint, reporter=None):
- """Set the linter with code_reader, jshint engine, and reporter.
-
- Should have following functionality.
- - code_reader.read_file(filename)
- - jshint.run(code, filename)
- - reporter([...])
-
- """
- self.code_reader = code_reader
- self.jshint = jshint
- if reporter is None:
- self.reporter = lambda x: '\n'.join(x)
- else:
- self.reporter = reporter
-
- def lint_file(self, filename):
- """Lint the file and return (pass, error_message)."""
- # Get code contents.
- code = self.code_reader.read_file(filename)
- lines = code.splitlines()
- import_list = StringUtility.get_imported_list(lines)
- if not import_list:
- check_pass, error_message = self.jshint.run(code, filename)
- else:
- newlines, info = self._merge_multiple_codes(filename, import_list)
- # Each line of |newlines| contains '\n'.
- check_pass, error_message = self.jshint.run(''.join(newlines))
- error_message = self._convert_merged_result(error_message, info)
- # Only keep errors for this file.
- error_message = [line for line in error_message
- if line.startswith(filename)]
- check_pass = (len(error_message) == 0)
- return check_pass, self.reporter(error_message)
-
- def _merge_multiple_codes(self, filename, import_list):
- """Merge multiple codes from filename and import_list."""
- dirname, filename = os.path.split(filename)
- dst_line = 1
- dst_results = []
- info = []
-
- # Put the imported script first, and then the original script.
- for f in import_list + [filename]:
- filepath = os.path.join(dirname, f)
-
- # Maintain a mapping table.
- # New line number after merge => original file and line number.
- info.append((dst_line, filepath, 1))
- try:
- code = self.code_reader.read_file(filepath)
- lines = code.splitlines(True) # Keep '\n'.
- src_results = StringUtility.auto_wrap_strict_mode(
- StringUtility.auto_close(lines))
- dst_results.extend(src_results)
- dst_line += len(src_results)
- except:
- info.pop()
- return dst_results, info
-
- def _convert_merged_result(self, error_lines, line_info):
- pattern = re.compile(r'(.*): line (\d+),(.*)')
- start_line = [info[0] for info in line_info]
- new_result_lines = []
- for line in error_lines:
- m = pattern.match(line)
- if not m:
- continue
-
- line_number, remain = int(m.group(2)), m.group(3)
-
- # [1, 2, 7, 8]
- # ^ for 7, pos = 3
- # ^ for 6, pos = 2
- pos = bisect.bisect_right(start_line, line_number)
- dst_line, name, src_line = line_info[pos - 1]
- real_line_number = line_number - dst_line + src_line
- new_result_lines.append(
- "%s: line %s,%s" % (name, real_line_number, remain))
- return new_result_lines
-
-
-class TestRILCodeQuality(MarionetteTestCase):
-
- JSHINT_PATH = 'ril_jshint/jshint.js'
- JSHINTRC_PATH = 'ril_jshint/jshintrc'
-
- def _read_local_file(self, filepath):
- """Read file content from local (folder of this test case)."""
- test_dir = os.path.dirname(inspect.getfile(TestRILCodeQuality))
- return open(os.path.join(test_dir, filepath)).read()
-
- def _get_extended_error_message(self, error_message):
- return '\n'.join(['See errors below and more information in Bug 880643',
- '\n'.join(error_message),
- 'See errors above and more information in Bug 880643'])
-
- def _check(self, filename):
- check_pass, error_message = self.linter.lint_file(filename)
- self.assertTrue(check_pass, error_message)
-
- def setUp(self):
- MarionetteTestCase.setUp(self)
- self.linter = Linter(
- ResourceUriFileReader(self.marionette),
- JSHintEngine(self.marionette,
- self._read_local_file(self.JSHINT_PATH),
- self._read_local_file(self.JSHINTRC_PATH)),
- self._get_extended_error_message)
-
- def tearDown(self):
- MarionetteTestCase.tearDown(self)
-
- def test_RadioInterfaceLayer(self):
- self._check('RadioInterfaceLayer.js')
-
- # Bug 936504. Disable the test for 'ril_worker.js'. It sometimes runs very
- # slow and causes the timeout fail on try server.
- #def test_ril_worker(self):
- # self._check('ril_worker.js')
-
- def test_ril_consts(self):
- self._check('ril_consts.js')
-
- def test_worker_buf(self):
- self._check('worker_buf.js')
diff --git a/dom/system/gonk/tests/marionette/test_screen_state.js b/dom/system/gonk/tests/marionette/test_screen_state.js
deleted file mode 100644
index 2281412d5..000000000
--- a/dom/system/gonk/tests/marionette/test_screen_state.js
+++ /dev/null
@@ -1,47 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 10000;
-
-var Services = SpecialPowers.Services;
-
-function testScreenState(on, expected, msg) {
- // send event to RadioInterface
- Services.obs.notifyObservers(null, 'screen-state-changed', on);
- // maybe rild/qemu needs some time to process the event
- window.setTimeout(function() {
- runEmulatorCmd('gsm report creg', function(result) {
- is(result.pop(), 'OK', '\'gsm report creg\' successful');
- ok(result.indexOf(expected) !== -1, msg);
- runNextTest();
- })}, 1000);
-}
-
-function testScreenStateDisabled() {
- testScreenState('off', '+CREG: 1', 'screen is disabled');
-}
-
-function testScreenStateEnabled() {
- testScreenState('on', '+CREG: 2', 'screen is enabled');
-}
-
-var tests = [
- testScreenStateDisabled,
- testScreenStateEnabled
-];
-
-function runNextTest() {
- let test = tests.shift();
- if (!test) {
- cleanUp();
- return;
- }
-
- test();
-}
-
-function cleanUp() {
- finish();
-}
-
-runNextTest();
diff --git a/dom/system/gonk/tests/marionette/test_timezone_changes.js b/dom/system/gonk/tests/marionette/test_timezone_changes.js
deleted file mode 100644
index 11dbaec5a..000000000
--- a/dom/system/gonk/tests/marionette/test_timezone_changes.js
+++ /dev/null
@@ -1,135 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-function init() {
- let promises = [];
-
- /*
- * The initial timezone of the emulator could be anywhere, depends the host
- * machine. Ensure resetting it to UTC before testing.
- */
- promises.push(runEmulatorCmdSafe('gsm timezone 0'));
- promises.push(new Promise((aResolve, aReject) => {
- waitFor(aResolve, () => {
- return new Date().getTimezoneOffset() === 0;
- });
- }));
-
- return Promise.all(promises);
-}
-
-function paddingZeros(aNumber, aLength) {
- let str = '' + aNumber;
- while (str.length < aLength) {
- str = '0' + str;
- }
-
- return str;
-}
-
-function verifyDate(aTestDate, aUTCOffsetDate) {
- // Verify basic properties.
- is(aUTCOffsetDate.getUTCFullYear(), aTestDate.getFullYear(), 'year');
- is(aUTCOffsetDate.getUTCMonth(), aTestDate.getMonth(), 'month');
- is(aUTCOffsetDate.getUTCDate(), aTestDate.getDate(), 'date');
- is(aUTCOffsetDate.getUTCHours(), aTestDate.getHours(), 'hours');
- is(aUTCOffsetDate.getUTCMinutes(), aTestDate.getMinutes(), 'minutes');
- is(aUTCOffsetDate.getUTCMilliseconds(), aTestDate.getMilliseconds(), 'milliseconds');
-
- // Ensure toLocaleString also uses correct timezone.
- // It uses ICU's timezone instead of the offset calculated from gecko prtime.
- let expectedDateString =
- paddingZeros(aUTCOffsetDate.getUTCMonth() + 1, 2) + '/' +
- paddingZeros(aUTCOffsetDate.getUTCDate(), 2);
- let dateString = aTestDate.toLocaleString('en-US', {
- month: '2-digit',
- day: '2-digit',
- });
- let expectedTimeString =
- paddingZeros(aUTCOffsetDate.getUTCHours(), 2) + ':' +
- paddingZeros(aUTCOffsetDate.getUTCMinutes(), 2);
- let timeString = aTestDate.toLocaleString('en-US', {
- hour12: false,
- hour: '2-digit',
- minute: '2-digit'
- });
-
- is(expectedDateString, dateString, 'dateString');
- is(expectedTimeString, timeString, 'timeString');
-}
-
-function waitForTimezoneUpdate(aTzOffset,
- aTestDateInMillis = 86400000, // Use 'UTC 00:00:00, 2nd of Jan, 1970' by default.
- aTransTzOffset, aTransTestDateInMillis) {
- return new Promise(function(aResolve, aReject) {
- window.addEventListener('moztimechange', function onevent(aEvent) {
- // Since there could be multiple duplicate moztimechange event, wait until
- // timezone is actually changed to expected value before removing the
- // listener.
- let testDate = new Date(aTestDateInMillis);
- if (testDate.getTimezoneOffset() === aTzOffset) {
- window.removeEventListener('moztimechange', onevent);
-
- // The UTC time of offsetDate is the same as the expected local time of
- // testDate. We'll use it to verify the values.
- let offsetDate = new Date(aTestDateInMillis - aTzOffset * 60 * 1000);
- verifyDate(testDate, offsetDate);
-
- // Verify transition time if given.
- if (aTransTzOffset !== undefined) {
- testDate = new Date(aTransTestDateInMillis);
- is(testDate.getTimezoneOffset(), aTransTzOffset);
-
- // Verify transition date.
- offsetDate = new Date(aTransTestDateInMillis - aTransTzOffset * 60 * 1000);
- verifyDate(testDate, offsetDate);
- }
-
- aResolve(aEvent);
- }
- });
- });
-}
-
-function testChangeNitzTimezone(aTzDiff) {
- let promises = [];
-
- // aTzOffset should be the expected value for getTimezoneOffset().
- // Note that getTimezoneOffset() is not so straightforward,
- // it values (UTC - localtime), so UTC+08:00 returns -480.
- promises.push(waitForTimezoneUpdate(-aTzDiff * 15));
- promises.push(runEmulatorCmdSafe('gsm timezone ' + aTzDiff));
-
- return Promise.all(promises);
-}
-
-function testChangeOlsonTimezone(aOlsonTz, aTzOffset, aTestDateInMillis,
- aTransTzOffset, aTransTestDateInMillis) {
- let promises = [];
-
- promises.push(waitForTimezoneUpdate(aTzOffset, aTestDateInMillis,
- aTransTzOffset, aTransTestDateInMillis));
- promises.push(setSettings('time.timezone', aOlsonTz));
-
- return Promise.all(promises);
-}
-
-// Start test
-startTestBase(function() {
- return init()
- .then(() => testChangeNitzTimezone(36)) // UTC+09:00
- .then(() => testChangeOlsonTimezone('America/New_York',
- 300, 1446357600000, // 2015/11/01 02:00 UTC-04:00 => 01:00 UTC-05:00 (EST)
- 240, 1425798000000)) // 2015/03/08 02:00 UTC-05:00 => 03:00 UTC-04:00 (EDT)
- .then(() => testChangeNitzTimezone(-22)) // UTC-05:30
- .then(() => testChangeNitzTimezone(51)) // UTC+12:45
- .then(() => testChangeOlsonTimezone('Australia/Adelaide',
- -570, 1428165000000, // 2015/04/05 03:00 UTC+10:30 => 02:00 UTC+09:30 (ACST)
- -630, 1443889800000)) // 2015/10/04 02:00 UTC+09:30 => 03:00 UTC+10:30 (ACDT)
- .then(() => testChangeNitzTimezone(-38)) // UTC-09:30
- .then(() => testChangeNitzTimezone(0)) // UTC
- .then(() => runEmulatorCmdSafe('gsm timezone auto'));
-});
diff --git a/dom/system/gonk/tests/test_ril_system_messenger.js b/dom/system/gonk/tests/test_ril_system_messenger.js
deleted file mode 100644
index a588d0ddb..000000000
--- a/dom/system/gonk/tests/test_ril_system_messenger.js
+++ /dev/null
@@ -1,1187 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-var RIL = {};
-Cu.import("resource://gre/modules/ril_consts.js", RIL);
-
-XPCOMUtils.defineLazyServiceGetter(this, "gStkCmdFactory",
- "@mozilla.org/icc/stkcmdfactory;1",
- "nsIStkCmdFactory");
-
-/**
- * Name space for RILSystemMessenger.jsm. Only initialized after first call to
- * newRILSystemMessenger.
- */
-var RSM;
-
-var gReceivedMsgType = null;
-var gReceivedMessage = null;
-
-/**
- * Create a new RILSystemMessenger instance.
- *
- * @return a RILSystemMessenger instance.
- */
-function newRILSystemMessenger() {
- if (!RSM) {
- RSM = Cu.import("resource://gre/modules/RILSystemMessenger.jsm", {});
- equal(typeof RSM.RILSystemMessenger, "function", "RSM.RILSystemMessenger");
- }
-
- let rsm = new RSM.RILSystemMessenger();
- rsm.broadcastMessage = (aType, aMessage) => {
- gReceivedMsgType = aType;
- gReceivedMessage = aMessage;
- };
-
- rsm.createCommandMessage = (aStkProactiveCmd) => {
- return gStkCmdFactory.createCommandMessage(aStkProactiveCmd);
- };
-
- return rsm;
-}
-
-function equal_received_system_message(aType, aMessage) {
- equal(aType, gReceivedMsgType);
- deepEqual(aMessage, gReceivedMessage);
- gReceivedMsgType = null;
- gReceivedMessage = null;
-}
-
-/**
- * Verify that each nsIXxxMessenger could be retrieved.
- */
-function run_test() {
- let telephonyMessenger = Cc["@mozilla.org/ril/system-messenger-helper;1"]
- .getService(Ci.nsITelephonyMessenger);
-
- let smsMessenger = Cc["@mozilla.org/ril/system-messenger-helper;1"]
- .getService(Ci.nsISmsMessenger);
-
- let cellbroadcastMessenger = Cc["@mozilla.org/ril/system-messenger-helper;1"]
- .getService(Ci.nsICellbroadcastMessenger);
-
- let mobileConnectionMessenger = Cc["@mozilla.org/ril/system-messenger-helper;1"]
- .getService(Ci.nsIMobileConnectionMessenger);
-
- let iccMessenger = Cc["@mozilla.org/ril/system-messenger-helper;1"]
- .getService(Ci.nsIIccMessenger);
-
- ok(telephonyMessenger !== null, "Get TelephonyMessenger.");
- ok(smsMessenger != null, "Get SmsMessenger.");
- ok(cellbroadcastMessenger != null, "Get CellbroadcastMessenger.");
- ok(mobileConnectionMessenger != null, "Get MobileConnectionMessenger.");
- ok(iccMessenger != null, "Get IccMessenger.");
-
- run_next_test();
-}
-
-/**
- * Verify RILSystemMessenger.notifyNewCall()
- */
-add_test(function test_telephony_messenger_notify_new_call() {
- let messenger = newRILSystemMessenger();
-
- messenger.notifyNewCall();
- equal_received_system_message("telephony-new-call", {});
-
- run_next_test();
-});
-
-/**
- * Verify RILSystemMessenger.notifyCallEnded()
- */
-add_test(function test_telephony_messenger_notify_call_ended() {
- let messenger = newRILSystemMessenger();
-
- messenger.notifyCallEnded(1,
- "+0987654321",
- null,
- true,
- 500,
- false,
- true);
-
- equal_received_system_message("telephony-call-ended", {
- serviceId: 1,
- number: "+0987654321",
- emergency: true,
- duration: 500,
- direction: "incoming",
- hangUpLocal: true
- });
-
- // Verify 'optional' parameter of secondNumber.
- messenger.notifyCallEnded(1,
- "+0987654321",
- "+1234567890",
- true,
- 500,
- true,
- false);
-
- equal_received_system_message("telephony-call-ended", {
- serviceId: 1,
- number: "+0987654321",
- emergency: true,
- duration: 500,
- direction: "outgoing",
- hangUpLocal: false,
- secondNumber: "+1234567890"
- });
-
- run_next_test();
-});
-
-/**
- * Verify RILSystemMessenger.notifySms()
- */
-add_test(function test_sms_messenger_notify_sms() {
- let messenger = newRILSystemMessenger();
- let timestamp = Date.now();
- let sentTimestamp = timestamp + 100;
- let deliveryTimestamp = sentTimestamp + 100;
-
- // Verify 'sms-received' system message.
- messenger.notifySms(Ci.nsISmsMessenger.NOTIFICATION_TYPE_RECEIVED,
- 1,
- 2,
- "99887766554433221100",
- Ci.nsISmsService.DELIVERY_TYPE_RECEIVED,
- Ci.nsISmsService.DELIVERY_STATUS_TYPE_SUCCESS,
- "+0987654321",
- null,
- "Incoming message",
- Ci.nsISmsService.MESSAGE_CLASS_TYPE_CLASS_2,
- timestamp,
- sentTimestamp,
- 0,
- false);
-
- equal_received_system_message("sms-received", {
- iccId: "99887766554433221100",
- type: "sms",
- id: 1,
- threadId: 2,
- delivery: "received",
- deliveryStatus: "success",
- sender: "+0987654321",
- receiver: null,
- body: "Incoming message",
- messageClass: "class-2",
- timestamp: timestamp,
- sentTimestamp: sentTimestamp,
- deliveryTimestamp: 0,
- read: false
- });
-
- // Verify 'sms-sent' system message.
- messenger.notifySms(Ci.nsISmsMessenger.NOTIFICATION_TYPE_SENT,
- 3,
- 4,
- "99887766554433221100",
- Ci.nsISmsService.DELIVERY_TYPE_SENT,
- Ci.nsISmsService.DELIVERY_STATUS_TYPE_PENDING,
- null,
- "+0987654321",
- "Outgoing message",
- Ci.nsISmsService.MESSAGE_CLASS_TYPE_NORMAL,
- timestamp,
- 0,
- 0,
- true);
-
- equal_received_system_message("sms-sent", {
- iccId: "99887766554433221100",
- type: "sms",
- id: 3,
- threadId: 4,
- delivery: "sent",
- deliveryStatus: "pending",
- sender: null,
- receiver: "+0987654321",
- body: "Outgoing message",
- messageClass: "normal",
- timestamp: timestamp,
- sentTimestamp: 0,
- deliveryTimestamp: 0,
- read: true
- });
-
- // Verify 'sms-delivery-success' system message.
- messenger.notifySms(Ci.nsISmsMessenger.NOTIFICATION_TYPE_DELIVERY_SUCCESS,
- 5,
- 6,
- "99887766554433221100",
- Ci.nsISmsService.DELIVERY_TYPE_SENT,
- Ci.nsISmsService.DELIVERY_STATUS_TYPE_SUCCESS,
- null,
- "+0987654321",
- "Outgoing message",
- Ci.nsISmsService.MESSAGE_CLASS_TYPE_NORMAL,
- timestamp,
- 0,
- deliveryTimestamp,
- true);
-
- equal_received_system_message("sms-delivery-success", {
- iccId: "99887766554433221100",
- type: "sms",
- id: 5,
- threadId: 6,
- delivery: "sent",
- deliveryStatus: "success",
- sender: null,
- receiver: "+0987654321",
- body: "Outgoing message",
- messageClass: "normal",
- timestamp: timestamp,
- sentTimestamp: 0,
- deliveryTimestamp: deliveryTimestamp,
- read: true
- });
-
- // Verify 'sms-failed' system message.
- messenger.notifySms(Ci.nsISmsMessenger.NOTIFICATION_TYPE_SENT_FAILED,
- 7,
- 8,
- "99887766554433221100",
- Ci.nsISmsService.DELIVERY_TYPE_ERROR,
- Ci.nsISmsService.DELIVERY_STATUS_TYPE_ERROR,
- null,
- "+0987654321",
- "Outgoing message",
- Ci.nsISmsService.MESSAGE_CLASS_TYPE_NORMAL,
- timestamp,
- 0,
- 0,
- true);
-
- equal_received_system_message("sms-failed", {
- iccId: "99887766554433221100",
- type: "sms",
- id: 7,
- threadId: 8,
- delivery: "error",
- deliveryStatus: "error",
- sender: null,
- receiver: "+0987654321",
- body: "Outgoing message",
- messageClass: "normal",
- timestamp: timestamp,
- sentTimestamp: 0,
- deliveryTimestamp: 0,
- read: true
- });
-
- // Verify 'sms-delivery-error' system message.
- messenger.notifySms(Ci.nsISmsMessenger.NOTIFICATION_TYPE_DELIVERY_ERROR,
- 9,
- 10,
- "99887766554433221100",
- Ci.nsISmsService.DELIVERY_TYPE_SENT,
- Ci.nsISmsService.DELIVERY_STATUS_TYPE_ERROR,
- null,
- "+0987654321",
- "Outgoing message",
- Ci.nsISmsService.MESSAGE_CLASS_TYPE_NORMAL,
- timestamp,
- 0,
- 0,
- true);
-
- equal_received_system_message("sms-delivery-error", {
- iccId: "99887766554433221100",
- type: "sms",
- id: 9,
- threadId: 10,
- delivery: "sent",
- deliveryStatus: "error",
- sender: null,
- receiver: "+0987654321",
- body: "Outgoing message",
- messageClass: "normal",
- timestamp: timestamp,
- sentTimestamp: 0,
- deliveryTimestamp: 0,
- read: true
- });
-
- // Verify the protection of invalid nsISmsMessenger.NOTIFICATION_TYPEs.
- try {
- messenger.notifySms(5,
- 1,
- 2,
- "99887766554433221100",
- Ci.nsISmsService.DELIVERY_TYPE_RECEIVED,
- Ci.nsISmsService.DELIVERY_STATUS_TYPE_SUCCESS,
- "+0987654321",
- null,
- "Incoming message",
- Ci.nsISmsService.MESSAGE_CLASS_TYPE_NORMAL,
- timestamp,
- sentTimestamp,
- 0,
- false);
- ok(false, "Failed to verify the protection of invalid nsISmsMessenger.NOTIFICATION_TYPE!");
- } catch (e) {}
-
- run_next_test();
-});
-
-/**
- * Verify RILSystemMessenger.notifyCbMessageReceived()
- */
-add_test(function test_cellbroadcast_messenger_notify_cb_message_received() {
- let messenger = newRILSystemMessenger();
- let timestamp = Date.now();
-
- // Verify ETWS
- messenger.notifyCbMessageReceived(0,
- Ci.nsICellBroadcastService.GSM_GEOGRAPHICAL_SCOPE_CELL_IMMEDIATE,
- 256,
- 4352,
- null,
- null,
- Ci.nsICellBroadcastService.GSM_MESSAGE_CLASS_NORMAL,
- timestamp,
- Ci.nsICellBroadcastService.CDMA_SERVICE_CATEGORY_INVALID,
- true,
- Ci.nsICellBroadcastService.GSM_ETWS_WARNING_EARTHQUAKE,
- false,
- true);
- equal_received_system_message("cellbroadcast-received", {
- serviceId: 0,
- gsmGeographicalScope: "cell-immediate",
- messageCode: 256,
- messageId: 4352,
- language: null,
- body: null,
- messageClass: "normal",
- timestamp: timestamp,
- cdmaServiceCategory: null,
- etws: {
- warningType: "earthquake",
- emergencyUserAlert: false,
- popup: true
- }
- });
-
- // Verify Normal CB Message
- messenger.notifyCbMessageReceived(1,
- Ci.nsICellBroadcastService.GSM_GEOGRAPHICAL_SCOPE_PLMN,
- 0,
- 50,
- "en",
- "The quick brown fox jumps over the lazy dog",
- Ci.nsICellBroadcastService.GSM_MESSAGE_CLASS_NORMAL,
- timestamp,
- Ci.nsICellBroadcastService.CDMA_SERVICE_CATEGORY_INVALID,
- false,
- Ci.nsICellBroadcastService.GSM_ETWS_WARNING_INVALID,
- false,
- false);
- equal_received_system_message("cellbroadcast-received", {
- serviceId: 1,
- gsmGeographicalScope: "plmn",
- messageCode: 0,
- messageId: 50,
- language: "en",
- body: "The quick brown fox jumps over the lazy dog",
- messageClass: "normal",
- timestamp: timestamp,
- cdmaServiceCategory: null,
- etws: null
- });
-
- // Verify CB Message with ETWS Info
- messenger.notifyCbMessageReceived(0,
- Ci.nsICellBroadcastService.GSM_GEOGRAPHICAL_SCOPE_LOCATION_AREA,
- 0,
- 4354,
- "en",
- "Earthquake & Tsunami Warning!",
- Ci.nsICellBroadcastService.GSM_MESSAGE_CLASS_0,
- timestamp,
- Ci.nsICellBroadcastService.CDMA_SERVICE_CATEGORY_INVALID,
- true,
- Ci.nsICellBroadcastService.GSM_ETWS_WARNING_EARTHQUAKE_TSUNAMI,
- true,
- false);
- equal_received_system_message("cellbroadcast-received", {
- serviceId: 0,
- gsmGeographicalScope: "location-area",
- messageCode: 0,
- messageId: 4354,
- language: "en",
- body: "Earthquake & Tsunami Warning!",
- messageClass: "class-0",
- timestamp: timestamp,
- cdmaServiceCategory: null,
- etws: {
- warningType: "earthquake-tsunami",
- emergencyUserAlert: true,
- popup: false
- }
- });
-
- // Verify CDMA CB Message
- messenger.notifyCbMessageReceived(0,
- Ci.nsICellBroadcastService.GSM_GEOGRAPHICAL_SCOPE_INVALID,
- 0,
- 0,
- null,
- "CDMA CB Message",
- Ci.nsICellBroadcastService.GSM_MESSAGE_CLASS_NORMAL,
- timestamp,
- 512,
- false,
- Ci.nsICellBroadcastService.GSM_ETWS_WARNING_INVALID,
- false,
- false);
- equal_received_system_message("cellbroadcast-received", {
- serviceId: 0,
- gsmGeographicalScope: null,
- messageCode: 0,
- messageId: 0,
- language: null,
- body: "CDMA CB Message",
- messageClass: "normal",
- timestamp: timestamp,
- cdmaServiceCategory: 512,
- etws: null
- });
-
- run_next_test();
-});
-
-/**
- * Verify RILSystemMessenger.notifyUssdReceived()
- */
-add_test(function test_mobileconnection_notify_ussd_received() {
- let messenger = newRILSystemMessenger();
-
- messenger.notifyUssdReceived(0, "USSD Message", false);
-
- equal_received_system_message("ussd-received", {
- serviceId: 0,
- message: "USSD Message",
- sessionEnded: false
- });
-
- messenger.notifyUssdReceived(1, "USSD Message", true);
-
- equal_received_system_message("ussd-received", {
- serviceId: 1,
- message: "USSD Message",
- sessionEnded: true
- });
-
- run_next_test();
-});
-
-/**
- * Verify RILSystemMessenger.notifyCdmaInfoRecXXX()
- */
-add_test(function test_mobileconnection_notify_cdma_info() {
- let messenger = newRILSystemMessenger();
-
- messenger.notifyCdmaInfoRecDisplay(0, "CDMA Display Info");
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 0,
- display: "CDMA Display Info"
- });
-
- messenger.notifyCdmaInfoRecCalledPartyNumber(1, 1, 2, "+0987654321", 3, 4);
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 1,
- calledNumber: {
- type: 1,
- plan: 2,
- number: "+0987654321",
- pi: 3,
- si: 4
- }
- });
-
- messenger.notifyCdmaInfoRecCallingPartyNumber(0, 5, 6, "+1234567890", 7, 8);
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 0,
- callingNumber: {
- type: 5,
- plan: 6,
- number: "+1234567890",
- pi: 7,
- si: 8
- }
- });
-
- messenger.notifyCdmaInfoRecConnectedPartyNumber(1, 4, 3, "+56473839201", 2, 1);
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 1,
- connectedNumber: {
- type: 4,
- plan: 3,
- number: "+56473839201",
- pi: 2,
- si: 1
- }
- });
-
- messenger.notifyCdmaInfoRecSignal(0, 1, 2, 3);
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 0,
- signal: {
- type: 1,
- alertPitch: 2,
- signal: 3
- }
- });
-
- messenger.notifyCdmaInfoRecRedirectingNumber(1, 8, 7, "+1029384756", 6, 5, 4);
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 1,
- redirect: {
- type: 8,
- plan: 7,
- number: "+1029384756",
- pi: 6,
- si: 5,
- reason: 4
- }
- });
-
- messenger.notifyCdmaInfoRecLineControl(0, 1, 0, 1, 255);
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 0,
- lineControl: {
- polarityIncluded: 1,
- toggle: 0,
- reverse: 1,
- powerDenial: 255
- }
- });
-
- messenger.notifyCdmaInfoRecClir(1, 256);
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 1,
- clirCause: 256
- });
-
- messenger.notifyCdmaInfoRecAudioControl(0, 255, -1);
-
- equal_received_system_message("cdma-info-rec-received", {
- clientId: 0,
- audioControl: {
- upLink: 255,
- downLink: -1
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Error Handling of StkProactiveCmdFactory.createCommand()
- */
-add_test(function test_icc_stk_cmd_factory_create_command_error() {
- let messenger = newRILSystemMessenger();
-
- // Verify the protection of invalid typeOfCommand.
- try {
- gStkCmdFactory.createCommand({
- commandNumber: 0,
- typeOfCommand: RIL.STK_CMD_MORE_TIME, // Invalid TypeOfCommand
- commandQualifier: 0x00
- });
-
- ok(false, "Failed to verify the protection of createCommand()!");
- } catch (e) {
- ok(e.message.indexOf("Unknown Command Type") !== -1,
- "Invalid typeOfCommand!");
- }
-
- run_next_test();
-});
-
-/**
- * Verify Error Handling of StkProactiveCmdFactory.createCommandMessage()
- */
-add_test(function test_icc_stk_cmd_factory_create_system_msg_invalid_cmd_type() {
- let messenger = newRILSystemMessenger();
- let iccId = "99887766554433221100";
-
- // Verify the protection of invalid typeOfCommand.
- try {
- gStkCmdFactory.createCommandMessage({
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIStkProactiveCmd]),
-
- // nsIStkProactiveCmd
- commandNumber: 0,
- typeOfCommand: RIL.STK_CMD_MORE_TIME, // Invalid TypeOfCommand
- commandQualifier: 0
- });
-
- ok(false, "Failed to identify invalid typeOfCommand!");
- } catch (e) {
- ok(e.message.indexOf("Unknown Command Type") !== -1,
- "Invalid typeOfCommand!");
- }
-
- run_next_test();
-});
-
-/**
- * Verify Error Handling of StkProactiveCmdFactory.createCommandMessage()
- */
-add_test(function test_icc_stk_cmd_factory_create_system_msg_incorrect_cmd_type() {
- let messenger = newRILSystemMessenger();
- let iccId = "99887766554433221100";
-
- // Verify the protection of invalid typeOfCommand.
- try {
- gStkCmdFactory.createCommandMessage({
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIStkProactiveCmd,
- Ci.nsIStkProvideLocalInfoCmd]),
-
- // nsIStkProactiveCmd
- commandNumber: 0,
- typeOfCommand: RIL.STK_CMD_POLL_INTERVAL, // Incorrect typeOfCommand
- commandQualifier: 0,
- // nsIStkProvideLocalInfoCmd
- localInfoType: 0x00,
- });
-
- ok(false, "Failed to identify incorrect typeOfCommand!");
- } catch (e) {
- ok(e.message.indexOf("Failed to convert command into concrete class: ") !== -1);
- }
-
- run_next_test();
-});
-
-/**
- * Verify RILSystemMessenger.notifyStkProactiveCommand()
- */
-add_test(function test_icc_notify_stk_proactive_command() {
- let messenger = newRILSystemMessenger();
- let iccId = "99887766554433221100";
- let WHT = 0xFFFFFFFF;
- let BLK = 0x000000FF;
- let RED = 0xFF0000FF;
- let GRN = 0x00FF00FF;
- let BLU = 0x0000FFFF;
- let TSP = 0;
- // Basic Image, see Anex B.1 in TS 31.102.
- let basicIcon = {
- width: 8,
- height: 8,
- codingScheme: "basic",
- pixels: [WHT, WHT, WHT, WHT, WHT, WHT, WHT, WHT,
- BLK, BLK, BLK, BLK, BLK, BLK, WHT, WHT,
- WHT, BLK, WHT, BLK, BLK, WHT, BLK, WHT,
- WHT, BLK, BLK, WHT, WHT, BLK, BLK, WHT,
- WHT, BLK, BLK, WHT, WHT, BLK, BLK, WHT,
- WHT, BLK, WHT, BLK, BLK, WHT, BLK, WHT,
- WHT, WHT, BLK, BLK, BLK, BLK, WHT, WHT,
- WHT, WHT, WHT, WHT, WHT, WHT, WHT, WHT]
- };
- // Color Image, see Anex B.2 in TS 31.102.
- let colorIcon = {
- width: 8,
- height: 8,
- codingScheme: "color",
- pixels: [BLU, BLU, BLU, BLU, BLU, BLU, BLU, BLU,
- BLU, RED, RED, RED, RED, RED, RED, BLU,
- BLU, RED, GRN, GRN, GRN, RED, RED, BLU,
- BLU, RED, RED, GRN, GRN, RED, RED, BLU,
- BLU, RED, RED, GRN, GRN, RED, RED, BLU,
- BLU, RED, RED, GRN, GRN, GRN, RED, BLU,
- BLU, RED, RED, RED, RED, RED, RED, BLU,
- BLU, BLU, BLU, BLU, BLU, BLU, BLU, BLU]
- };
- // Color Image with Transparency, see Anex B.2 in TS 31.102.
- let colorTransparencyIcon = {
- width: 8,
- height: 8,
- codingScheme: "color-transparency",
- pixels: [TSP, TSP, TSP, TSP, TSP, TSP, TSP, TSP,
- TSP, RED, RED, RED, RED, RED, RED, TSP,
- TSP, RED, GRN, GRN, GRN, RED, RED, TSP,
- TSP, RED, RED, GRN, GRN, RED, RED, TSP,
- TSP, RED, RED, GRN, GRN, RED, RED, TSP,
- TSP, RED, RED, GRN, GRN, GRN, RED, TSP,
- TSP, RED, RED, RED, RED, RED, RED, TSP,
- TSP, TSP, TSP, TSP, TSP, TSP, TSP, TSP]
- };
-
- let cmdCount = 0;
-
- // Test Messages:
- let messages = [
- // STK_CMD_REFRESH
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_REFRESH,
- commandQualifier: 0x04 // UICC Reset
- },
- // STK_CMD_POLL_INTERVAL
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_POLL_INTERVAL,
- commandQualifier: 0x00, // RFU
- options: {
- timeUnit: RIL.STK_TIME_UNIT_TENTH_SECOND,
- timeInterval: 0x05
- }
- },
- // STK_CMD_POLL_OFF
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_POLL_OFF,
- commandQualifier: 0x00, // RFU
- },
- // STK_CMD_PROVIDE_LOCAL_INFO
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_PROVIDE_LOCAL_INFO,
- commandQualifier: 0x01, // IMEI of the terminal
- options: {
- localInfoType: 0x01 // IMEI of the terminal
- }
- },
- // STK_CMD_SET_UP_EVENT_LIST with eventList
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SET_UP_EVENT_LIST,
- commandQualifier: 0x00, // RFU
- options: {
- eventList: [ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
- 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
- 0x18, 0x19, 0x1A, 0x1B, 0x1C ]
- }
- },
- // STK_CMD_SET_UP_EVENT_LIST without eventList
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SET_UP_EVENT_LIST,
- commandQualifier: 0x00, // RFU
- options: {
- eventList: null
- }
- },
- // STK_CMD_SET_UP_MENU with mandatory properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SET_UP_MENU,
- commandQualifier: 0x80, // bit 8: 1 = help information available
- options: {
- title: "Toolkit Menu 1",
- items: [
- { identifier: 0x01, text: "Menu Item 1" },
- { identifier: 0x02, text: "Menu Item 2" },
- { identifier: 0x03, text: "Menu Item 3" }
- ],
- isHelpAvailable: true
- }
- },
- // STK_CMD_SET_UP_MENU with optional properties including:
- // iconInfo for this menu, iconInfo for each item and nextActionList.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SET_UP_MENU,
- commandQualifier: 0x00, // bit 8: 0 = help information is not available
- options: {
- title: "Toolkit Menu 2",
- items: [
- { identifier: 0x01,
- text: "Menu Item 1",
- iconSelfExplanatory: true,
- icons: [basicIcon]
- },
- { identifier: 0x02,
- text: "Menu Item 2",
- iconSelfExplanatory: false,
- icons: [basicIcon, colorIcon]
- },
- { identifier: 0x03,
- text: "Menu Item 3",
- iconSelfExplanatory: true,
- icons: [basicIcon, colorIcon, colorTransparencyIcon]
- },
- ],
- nextActionList: [
- RIL.STK_NEXT_ACTION_END_PROACTIVE_SESSION,
- RIL.STK_NEXT_ACTION_NULL,
- RIL.STK_NEXT_ACTION_NULL,
- RIL.STK_NEXT_ACTION_NULL
- ],
- iconSelfExplanatory: false,
- icons: [basicIcon, colorIcon, colorTransparencyIcon],
- isHelpAvailable: false
- }
- },
- // STK_CMD_SELECT_ITEM with mandatory properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SELECT_ITEM,
- commandQualifier: RIL.STK_PRESENTATION_TYPE_NOT_SPECIFIED,
- options: {
- title: null,
- items: [
- { identifier: 0x01, text: "Menu Item 1" },
- { identifier: 0x02, text: "Menu Item 2" },
- { identifier: 0x03, text: "Menu Item 3" }
- ],
- presentationType: RIL.STK_PRESENTATION_TYPE_NOT_SPECIFIED,
- isHelpAvailable: false
- }
- },
- // STK_CMD_SELECT_ITEM with optional properties including:
- // title, iconInfo for this menu, iconInfo for each item and nextActionList.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SELECT_ITEM,
- commandQualifier: RIL.STK_PRESENTATION_TYPE_NAVIGATION_OPTIONS,
- options: {
- title: "Selected Toolkit Menu",
- items: [
- { identifier: 0x01,
- text: "Menu Item 1",
- iconSelfExplanatory: true,
- icons: [basicIcon]
- },
- { identifier: 0x02,
- text: "Menu Item 2",
- iconSelfExplanatory: false,
- icons: [basicIcon, colorIcon]
- },
- { identifier: 0x03,
- text: "Menu Item 3",
- iconSelfExplanatory: true,
- icons: [basicIcon, colorIcon, colorTransparencyIcon]
- },
- ],
- nextActionList: [
- RIL.STK_NEXT_ACTION_END_PROACTIVE_SESSION,
- RIL.STK_NEXT_ACTION_NULL,
- RIL.STK_NEXT_ACTION_NULL,
- RIL.STK_NEXT_ACTION_NULL
- ],
- defaultItem: 0x02,
- iconSelfExplanatory: false,
- icons: [basicIcon, colorIcon, colorTransparencyIcon],
- presentationType: RIL.STK_PRESENTATION_TYPE_NAVIGATION_OPTIONS,
- isHelpAvailable: false
- }
- },
- // STK_CMD_DISPLAY_TEXT with mandatory properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_DISPLAY_TEXT,
- commandQualifier: 0x01, // bit 1: High Priority
- options: {
- text: "Display Text 1",
- isHighPriority: true,
- userClear: false,
- responseNeeded: false
- }
- },
- // STK_CMD_DISPLAY_TEXT with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_DISPLAY_TEXT,
- commandQualifier: 0x80, // bit 8: User Clear
- options: {
- text: "Display Text 2",
- isHighPriority: false,
- userClear: true,
- responseNeeded: true,
- duration: {
- timeUnit: RIL.STK_TIME_UNIT_TENTH_SECOND,
- timeInterval: 0x05
- },
- iconSelfExplanatory: true,
- icons: [basicIcon]
- }
- },
- // STK_CMD_SET_UP_IDLE_MODE_TEXT
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SET_UP_IDLE_MODE_TEXT,
- commandQualifier: 0x00, // RFU
- options: {
- text: "Setup Idle Mode Text"
- }
- },
- // STK_CMD_SEND_SS
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SEND_SS,
- commandQualifier: 0x00, // RFU
- options: {
- text: "Send SS",
- iconSelfExplanatory: true,
- icons: [colorIcon]
- }
- },
- // STK_CMD_SEND_USSD
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SEND_USSD,
- commandQualifier: 0x00, // RFU
- options: {
- text: "Send USSD"
- }
- },
- // STK_CMD_SEND_SMS
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SEND_SMS,
- commandQualifier: 0x00, // RFU
- options: {
- text: "Send SMS",
- iconSelfExplanatory: false,
- icons: [colorTransparencyIcon]
- }
- },
- // STK_CMD_SEND_DTMF
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SEND_DTMF,
- commandQualifier: 0x00, // RFU
- options: {
- text: "Send DTMF",
- iconSelfExplanatory: true,
- icons: [basicIcon]
- }
- },
- // STK_CMD_GET_INKEY
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_GET_INKEY,
- commandQualifier: 0x84, // bit 3: isYesNoRequested, bit 8: isHelpAvailable
- options: {
- text: "Get Input Key",
- minLength: 1,
- maxLength: 1,
- duration: {
- timeUnit: RIL.STK_TIME_UNIT_SECOND,
- timeInterval: 0x0A
- },
- isAlphabet: false,
- isUCS2: false,
- isYesNoRequested: true,
- isHelpAvailable: true,
- defaultText: null,
- iconSelfExplanatory: false,
- icons: [colorIcon]
- }
- },
- // STK_CMD_GET_INPUT
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_GET_INPUT,
- commandQualifier: 0x0F, // bit 1-4: isAlphabet, isUCS2, hideInput, isPacked
- options: {
- text: "Get Input Text",
- minLength: 1,
- maxLength: 255,
- defaultText: "Default Input Text",
- isAlphabet: true,
- isUCS2: true,
- hideInput: true,
- isPacked: true,
- isHelpAvailable: false,
- defaultText: null,
- iconSelfExplanatory: true,
- icons: [basicIcon]
- }
- },
- // STK_CMD_SET_UP_CALL with mandatory properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SET_UP_CALL,
- commandQualifier: 0x00, // RFU
- options: {
- address: "+0987654321"
- }
- },
- // STK_CMD_SET_UP_CALL with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SET_UP_CALL,
- commandQualifier: 0x00, // RFU
- options: {
- address: "+0987654321",
- confirmMessage: {
- text: "Confirm Message",
- iconSelfExplanatory: false,
- icons: [colorIcon]
- },
- callMessage: {
- text: "Call Message",
- iconSelfExplanatory: true,
- icons: [basicIcon]
- },
- duration: {
- timeUnit: RIL.STK_TIME_UNIT_SECOND,
- timeInterval: 0x0A
- }
- }
- },
- // STK_CMD_LAUNCH_BROWSER with mandatory properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_LAUNCH_BROWSER,
- commandQualifier: RIL.STK_BROWSER_MODE_USING_NEW_BROWSER,
- options: {
- url: "http://www.mozilla.org",
- mode: RIL.STK_BROWSER_MODE_USING_NEW_BROWSER
- }
- },
- // STK_CMD_LAUNCH_BROWSER with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_LAUNCH_BROWSER,
- commandQualifier: RIL.STK_BROWSER_MODE_USING_NEW_BROWSER,
- options: {
- url: "http://www.mozilla.org",
- mode: RIL.STK_BROWSER_MODE_USING_NEW_BROWSER,
- confirmMessage: {
- text: "Confirm Message for Launch Browser",
- iconSelfExplanatory: false,
- icons: [colorTransparencyIcon]
- }
- }
- },
- // STK_CMD_PLAY_TONE with mandatory properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_PLAY_TONE,
- commandQualifier: 0x01, // isVibrate
- options: {
- text: null,
- isVibrate: true
- }
- },
- // STK_CMD_PLAY_TONE with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_PLAY_TONE,
- commandQualifier: 0x00, // isVibrate = false
- options: {
- text: "Play Tone",
- tone: RIL.STK_TONE_TYPE_CONGESTION,
- isVibrate: false,
- duration: {
- timeUnit: RIL.STK_TIME_UNIT_SECOND,
- timeInterval: 0x0A
- },
- iconSelfExplanatory: true,
- icons: [basicIcon]
- }
- },
- // STK_CMD_TIMER_MANAGEMENT with mandatory properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_TIMER_MANAGEMENT,
- commandQualifier: RIL.STK_TIMER_DEACTIVATE,
- options: {
- timerId: 0x08,
- timerAction: RIL.STK_TIMER_DEACTIVATE
- }
- },
- // STK_CMD_TIMER_MANAGEMENT with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_TIMER_MANAGEMENT,
- commandQualifier: RIL.STK_TIMER_START,
- options: {
- timerId: 0x01,
- timerValue: (12 * 60 * 60) + (30 * 60) + (30), // 12:30:30
- timerAction: RIL.STK_TIMER_START
- }
- },
- // STK_CMD_OPEN_CHANNEL with mandatory properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_OPEN_CHANNEL,
- commandQualifier: 0x00, //RFU
- options: {
- text: null,
- }
- },
- // STK_CMD_OPEN_CHANNEL with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_OPEN_CHANNEL,
- commandQualifier: 0x00, //RFU
- options: {
- text: "Open Channel",
- iconSelfExplanatory: false,
- icons: [colorIcon]
- }
- },
- // STK_CMD_CLOSE_CHANNEL with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_CLOSE_CHANNEL,
- commandQualifier: 0x00, //RFU
- options: {
- text: "Close Channel",
- iconSelfExplanatory: true,
- icons: [colorTransparencyIcon]
- }
- },
- // STK_CMD_SEND_DATA with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_SEND_DATA,
- commandQualifier: 0x00, //RFU
- options: {
- text: null,
- iconSelfExplanatory: false,
- icons: [basicIcon]
- }
- },
- // STK_CMD_RECEIVE_DATA with optional properties.
- {
- commandNumber: ++cmdCount,
- typeOfCommand: RIL.STK_CMD_RECEIVE_DATA,
- commandQualifier: 0x00, //RFU
- options: {
- text: "Receive Data"
- }
- },
- null // Termination condition to run_next_test()
- ];
-
- messages.forEach(function(aMessage) {
- if (!aMessage) {
- run_next_test();
- return;
- }
-
- messenger.notifyStkProactiveCommand(iccId,
- gStkCmdFactory.createCommand(aMessage));
-
- equal_received_system_message("icc-stkcommand", {
- iccId: iccId,
- command: aMessage
- });
- });
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_barring_password.js b/dom/system/gonk/tests/test_ril_worker_barring_password.js
deleted file mode 100644
index fcd3e4405..000000000
--- a/dom/system/gonk/tests/test_ril_worker_barring_password.js
+++ /dev/null
@@ -1,61 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-const PIN = "0000";
-const NEW_PIN = "1234";
-
-add_test(function test_change_call_barring_password() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
-
- function do_test(facility, pin, newPin) {
- buf.sendParcel = function fakeSendParcel () {
- // Request Type.
- equal(this.readInt32(), REQUEST_CHANGE_BARRING_PASSWORD);
-
- // Token : we don't care.
- this.readInt32();
-
- let parcel = this.readStringList();
- equal(parcel.length, 3);
- equal(parcel[0], facility);
- equal(parcel[1], pin);
- equal(parcel[2], newPin);
- };
-
- let options = {facility: facility, pin: pin, newPin: newPin};
- context.RIL.changeCallBarringPassword(options);
- }
-
- do_test(ICC_CB_FACILITY_BA_ALL, PIN, NEW_PIN);
-
- run_next_test();
-});
-
-add_test(function test_check_change_call_barring_password_result() {
- let barringPasswordOptions;
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
-
- let context = worker.ContextPool._contexts[0];
- context.RIL.changeCallBarringPassword =
- function fakeChangeCallBarringPassword(options) {
- barringPasswordOptions = options;
- context.RIL[REQUEST_CHANGE_BARRING_PASSWORD](0, {});
- };
-
- context.RIL.changeCallBarringPassword({pin: PIN, newPin: NEW_PIN});
-
- let postedMessage = workerHelper.postedMessage;
- equal(barringPasswordOptions.pin, PIN);
- equal(barringPasswordOptions.newPin, NEW_PIN);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_buf.js b/dom/system/gonk/tests/test_ril_worker_buf.js
deleted file mode 100644
index 30054a881..000000000
--- a/dom/system/gonk/tests/test_ril_worker_buf.js
+++ /dev/null
@@ -1,187 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Add test function with specified parcel and request handler.
- *
- * @param parcel
- * Incoming parcel to be tested.
- * @param handler
- * Handler to be invoked as RIL request handler.
- */
-function add_test_incoming_parcel(parcel, handler) {
- add_test(function test_incoming_parcel() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // do nothing
- },
- postMessage: function(message) {
- // do nothing
- }
- });
-
- if (!parcel) {
- parcel = newIncomingParcel(-1,
- worker.RESPONSE_TYPE_UNSOLICITED,
- worker.REQUEST_VOICE_REGISTRATION_STATE,
- [0, 0, 0, 0]);
- }
-
- let context = worker.ContextPool._contexts[0];
- // supports only requests less or equal than UINT8_MAX(255).
- let buf = context.Buf;
- let request = parcel[buf.PARCEL_SIZE_SIZE + buf.UINT32_SIZE];
- context.RIL[request] = function ril_request_handler() {
- handler.apply(this, arguments);
- };
-
- worker.onRILMessage(0, parcel);
-
- // end of incoming parcel's trip, let's do next test.
- run_next_test();
- });
-}
-
-// Test normal parcel handling.
-add_test_incoming_parcel(null,
- function test_normal_parcel_handling() {
- let self = this;
- try {
- // reads exactly the same size, should not throw anything.
- self.context.Buf.readInt32();
- } catch (e) {
- ok(false, "Got exception: " + e);
- }
- }
-);
-
-// Test parcel under read.
-add_test_incoming_parcel(null,
- function test_parcel_under_read() {
- let self = this;
- try {
- // reads less than parcel size, should not throw.
- self.context.Buf.readUint16();
- } catch (e) {
- ok(false, "Got exception: " + e);
- }
- }
-);
-
-// Test parcel over read.
-add_test_incoming_parcel(null,
- function test_parcel_over_read() {
- let buf = this.context.Buf;
-
- // read all data available
- while (buf.readAvailable > 0) {
- buf.readUint8();
- }
-
- throws(function over_read_handler() {
- // reads more than parcel size, should throw an error.
- buf.readUint8();
- },"Trying to read data beyond the parcel end!");
- }
-);
-
-// Test Bug 814761: buffer overwritten
-add_test(function test_incoming_parcel_buffer_overwritten() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // do nothing
- },
- postMessage: function(message) {
- // do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- // A convenient alias.
- let buf = context.Buf;
-
- // Allocate an array of specified size and set each of its elements to value.
- function calloc(length, value) {
- let array = new Array(length);
- for (let i = 0; i < length; i++) {
- array[i] = value;
- }
- return array;
- }
-
- // Do nothing in handleParcel().
- let request = worker.REQUEST_VOICE_REGISTRATION_STATE;
- context.RIL[request] = null;
-
- // Prepare two parcels, whose sizes are both smaller than the incoming buffer
- // size but larger when combined, to trigger the bug.
- let pA_dataLength = buf.incomingBufferLength / 2;
- let pA = newIncomingParcel(-1,
- worker.RESPONSE_TYPE_UNSOLICITED,
- request,
- calloc(pA_dataLength, 1));
- let pA_parcelSize = pA.length - buf.PARCEL_SIZE_SIZE;
-
- let pB_dataLength = buf.incomingBufferLength * 3 / 4;
- let pB = newIncomingParcel(-1,
- worker.RESPONSE_TYPE_UNSOLICITED,
- request,
- calloc(pB_dataLength, 1));
- let pB_parcelSize = pB.length - buf.PARCEL_SIZE_SIZE;
-
- // First, send an incomplete pA and verifies related data pointer:
- let p1 = pA.subarray(0, pA.length - 1);
- worker.onRILMessage(0, p1);
- // The parcel should not have been processed.
- equal(buf.readAvailable, 0);
- // buf.currentParcelSize should have been set because incoming data has more
- // than 4 octets.
- equal(buf.currentParcelSize, pA_parcelSize);
- // buf.readIncoming should contains remaining unconsumed octets count.
- equal(buf.readIncoming, p1.length - buf.PARCEL_SIZE_SIZE);
- // buf.incomingWriteIndex should be ready to accept the last octet.
- equal(buf.incomingWriteIndex, p1.length);
-
- // Second, send the last octet of pA and whole pB. The Buf should now expand
- // to cover both pA & pB.
- let p2 = new Uint8Array(1 + pB.length);
- p2.set(pA.subarray(pA.length - 1), 0);
- p2.set(pB, 1);
- worker.onRILMessage(0, p2);
- // The parcels should have been both consumed.
- equal(buf.readAvailable, 0);
- // No parcel data remains.
- equal(buf.currentParcelSize, 0);
- // No parcel data remains.
- equal(buf.readIncoming, 0);
- // The Buf should now expand to cover both pA & pB.
- equal(buf.incomingWriteIndex, pA.length + pB.length);
-
- // end of incoming parcel's trip, let's do next test.
- run_next_test();
-});
-
-// Test Buf.readUint8Array.
-add_test_incoming_parcel(null,
- function test_buf_readUint8Array() {
- let buf = this.context.Buf;
-
- let u8array = buf.readUint8Array(1);
- equal(u8array instanceof Uint8Array, true);
- equal(u8array.length, 1);
- equal(buf.readAvailable, 3);
-
- u8array = buf.readUint8Array(2);
- equal(u8array.length, 2);
- equal(buf.readAvailable, 1);
-
- throws(function over_read_handler() {
- // reads more than parcel size, should throw an error.
- u8array = buf.readUint8Array(2);
- }, "Trying to read data beyond the parcel end!");
- }
-);
diff --git a/dom/system/gonk/tests/test_ril_worker_cdma_info_rec.js b/dom/system/gonk/tests/test_ril_worker_cdma_info_rec.js
deleted file mode 100644
index 335c0c403..000000000
--- a/dom/system/gonk/tests/test_ril_worker_cdma_info_rec.js
+++ /dev/null
@@ -1,234 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Helper function.
- */
-function newWorkerWithParcel(parcelBuf) {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let index = 0; // index for read
- let buf = parcelBuf;
-
- let context = worker.ContextPool._contexts[0];
- context.Buf.readUint8 = function() {
- return buf[index++];
- };
-
- context.Buf.readUint16 = function() {
- return buf[index++];
- };
-
- context.Buf.readInt32 = function() {
- return buf[index++];
- };
-
- context.Buf.seekIncoming = function(offset) {
- index += offset / context.Buf.UINT32_SIZE;
- };
-
- return worker;
-}
-
-// Test CDMA information record decoder.
-
-/**
- * Verify decoder for type DISPLAY
- */
-add_test(function test_display() {
- let worker = newWorkerWithParcel([
- 0x01, // one inforemation record
- 0x00, // type: display
- 0x09, // length: 9
- 0x54, 0x65, 0x73, 0x74, 0x20, 0x49, 0x6E, 0x66,
- 0x6F, 0x00]);
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records[0].display, "Test Info");
-
- run_next_test();
-});
-
-/**
- * Verify decoder for type EXTENDED DISPLAY
- */
-add_test(function test_extended_display() {
- let worker = newWorkerWithParcel([
- 0x01, // one inforemation record
- 0x07, // type: extended display
- 0x12, // length: 18
- 0x54, 0x65, 0x73, 0x74, 0x20, 0x45, 0x78, 0x74,
- 0x65, 0x6E, 0x64, 0x65, 0x64, 0x20, 0x49, 0x6E,
- 0x66, 0x6F, 0x00, 0x00]);
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records[0].display, "Test Extended Info");
-
- run_next_test();
-});
-
-/**
- * Verify decoder for mixed type
- */
-add_test(function test_mixed() {
- let worker = newWorkerWithParcel([
- 0x02, // two inforemation record
- 0x00, // type: display
- 0x0B, // length: 11
- 0x54, 0x65, 0x73, 0x74, 0x20, 0x49, 0x6E, 0x66,
- 0x6F, 0x20, 0x31, 0x00,
- 0x07, // type: extended display
- 0x0B, // length: 11
- 0x54, 0x65, 0x73, 0x74, 0x20, 0x49, 0x6E, 0x66,
- 0x6F, 0x20, 0x32, 0x00]);
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records[0].display, "Test Info 1");
- equal(records[1].display, "Test Info 2");
-
- run_next_test();
-});
-
-/**
- * Verify decoder for multiple types
- */
-add_test(function test_multiple() {
- let worker = newWorkerWithParcel([
- 0x02, // two inforemation record
- 0x00, // type: display
- 0x0B, // length: 11
- 0x54, 0x65, 0x73, 0x74, 0x20, 0x49, 0x6E, 0x66,
- 0x6F, 0x20, 0x31, 0x00,
- 0x00, // type: display
- 0x0B, // length: 11
- 0x54, 0x65, 0x73, 0x74, 0x20, 0x49, 0x6E, 0x66,
- 0x6F, 0x20, 0x32, 0x00]);
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records[0].display, "Test Info 1");
- equal(records[1].display, "Test Info 2");
-
- run_next_test();
-});
-
-/**
- * Verify decoder for Signal Type
- */
-add_test(function test_signal() {
- let worker = newWorkerWithParcel([
- 0x01, // one inforemation record
- 0x04, // type: signal
- 0x01, // isPresent: non-zero
- 0x00, // signalType: Tone signal (00)
- 0x01, // alertPitch: High pitch
- 0x03]); // signal: Abbreviated intercept (000011)
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records[0].signal.type, 0x00);
- equal(records[0].signal.alertPitch, 0x01);
- equal(records[0].signal.signal, 0x03);
-
- run_next_test();
-});
-
-/**
- * Verify decoder for Signal Type for Not Presented
- */
-add_test(function test_signal_not_present() {
- let worker = newWorkerWithParcel([
- 0x01, // one inforemation record
- 0x04, // type: signal
- 0x00, // isPresent: zero
- 0x00, // signalType: Tone signal (00)
- 0x01, // alertPitch: High pitch
- 0x03]); // signal: Abbreviated intercept (000011)
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records.length, 0);
-
- run_next_test();
-});
-
-/**
- * Verify decoder for Line Control
- */
-add_test(function test_line_control() {
- let worker = newWorkerWithParcel([
- 0x01, // one inforemation record
- 0x06, // type: line control
- 0x01, // polarity included
- 0x00, // not toggled
- 0x01, // reversed
- 0xFF]); // Power denial timeout: 255 * 5 ms
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records[0].lineControl.polarityIncluded, 1);
- equal(records[0].lineControl.toggle, 0);
- equal(records[0].lineControl.reverse, 1);
- equal(records[0].lineControl.powerDenial, 255);
-
- run_next_test();
-});
-
-/**
- * Verify decoder for CLIR Cause
- */
-add_test(function test_clir() {
- let worker = newWorkerWithParcel([
- 0x01, // one inforemation record
- 0x08, // type: clir
- 0x01]); // cause: Rejected by user
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records[0].clirCause, 1);
-
- run_next_test();
-});
-
-/**
- * Verify decoder for Audio Control
- */
-add_test(function test_clir() {
- let worker = newWorkerWithParcel([
- 0x01, // one inforemation record
- 0x0A, // type: audio control
- 0x01, // uplink
- 0xFF]); // downlink
- let context = worker.ContextPool._contexts[0];
- let helper = context.CdmaPDUHelper;
- let records = helper.decodeInformationRecord();
-
- equal(records[0].audioControl.upLink, 1);
- equal(records[0].audioControl.downLink, 255);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_cellbroadcast_config.js b/dom/system/gonk/tests/test_ril_worker_cellbroadcast_config.js
deleted file mode 100644
index d5645a3cf..000000000
--- a/dom/system/gonk/tests/test_ril_worker_cellbroadcast_config.js
+++ /dev/null
@@ -1,470 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_ril_worker_cellbroadcast_activate() {
- let worker = newWorker({
- postRILMessage: function(id, parcel) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
- let context = worker.ContextPool._contexts[0];
-
- let parcelTypes = [];
- let org_newParcel = context.Buf.newParcel;
- context.Buf.newParcel = function(type, options) {
- parcelTypes.push(type);
- org_newParcel.apply(this, arguments);
- };
-
- function setup(isCdma) {
- context.RIL._isCdma = isCdma;
- context.RIL.cellBroadcastDisabled = false;
- context.RIL.mergedCellBroadcastConfig = [1, 2, 4, 7]; // 1, 4-6
- parcelTypes = [];
- }
-
- function test(isCdma, expectedRequest) {
- setup(isCdma);
- context.RIL.setCellBroadcastDisabled({disabled: true});
- // Makesure that request parcel is sent out.
- notEqual(parcelTypes.indexOf(expectedRequest), -1);
- equal(context.RIL.cellBroadcastDisabled, true);
- }
-
- test(false, REQUEST_GSM_SMS_BROADCAST_ACTIVATION);
- test(true, REQUEST_CDMA_SMS_BROADCAST_ACTIVATION);
-
- run_next_test();
-});
-
-add_test(function test_ril_worker_cellbroadcast_config() {
- let currentParcel;
- let worker = newWorker({
- postRILMessage: function(id, parcel) {
- currentParcel = parcel;
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
- let context = worker.ContextPool._contexts[0];
-
- function U32ArrayFromParcelArray(pa) {
- do_print(pa);
- let out = [];
- for (let i = 0; i < pa.length; i += 4) {
- let data = pa[i] + (pa[i+1] << 8) + (pa[i+2] << 16) + (pa[i+3] << 24);
- out.push(data);
- }
- return out;
- }
-
- function test(isCdma, configs, expected) {
- let parcelType = isCdma ? REQUEST_CDMA_SET_BROADCAST_SMS_CONFIG
- : REQUEST_GSM_SET_BROADCAST_SMS_CONFIG;
-
- let found = false;
- worker.postRILMessage = function(id, parcel) {
- let u32Parcel = U32ArrayFromParcelArray(Array.slice(parcel));
- if (u32Parcel[1] != parcelType) {
- return;
- }
-
- found = true;
- // Check parcel. Data start from 4th word (32bit)
- equal(u32Parcel.slice(3).toString(), expected);
- };
-
- context.RIL._isCdma = isCdma;
- context.RIL.setSmsBroadcastConfig(configs);
-
- // Makesure that request parcel is sent out.
- ok(found);
- }
-
- // (GSM) RIL writes the following data to outgoing parcel:
- // nums [(from, to, 0, 0xFF, 1), ... ]
- test(false,
- [1, 2, 4, 7] /* 1, 4-6 */,
- ["2", "1,1,0,255,1", "4,6,0,255,1"].join());
-
- // (CDMA) RIL writes the following data to outgoing parcel:
- // nums [(id, 0, 1), ... ]
- test(true,
- [1, 2, 4, 7] /* 1, 4-6 */,
- ["4", "1,0,1", "4,0,1", "5,0,1", "6,0,1"].join());
-
- run_next_test();
-});
-
-add_test(function test_ril_worker_cellbroadcast_merge_config() {
- let worker = newWorker({
- postRILMessage: function(id, parcel) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
- let context = worker.ContextPool._contexts[0];
-
- function test(isCdma, configs, expected) {
- context.RIL._isCdma = isCdma;
- context.RIL.cellBroadcastConfigs = configs;
- context.RIL._mergeAllCellBroadcastConfigs();
- equal(context.RIL.mergedCellBroadcastConfig.toString(), expected);
- }
-
- let configs = {
- MMI: [1, 2, 4, 7], // 1, 4-6
- CBMI: [6, 9], // 6-8
- CBMID: [8, 11], // 8-10
- CBMIR: [10, 13] // 10-12
- };
-
- test(false, configs, "1,2,4,13");
- test(true, configs, "1,2,4,7");
-
- run_next_test();
-});
-
-add_test(function test_ril_worker_cellbroadcast_set_search_list() {
- let worker = newWorker({
- postRILMessage: function(id, parcel) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
-
- function test(aIsCdma, aSearchList, aExpected) {
- context.RIL._isCdma = aIsCdma;
-
- let options = { searchList: aSearchList };
- context.RIL.setCellBroadcastSearchList(options);
- // Enforce the MMI result to string for comparison.
- equal("" + context.RIL.cellBroadcastConfigs.MMI, aExpected);
- do_check_eq(options.errorMsg, undefined);
- }
-
- let searchListStr = "1,2,3,4";
- let searchList = { gsm: "1,2,3,4", cdma: "5,6,7,8" };
-
- test(false, searchListStr, "1,2,2,3,3,4,4,5");
- test(true, searchListStr, "1,2,2,3,3,4,4,5");
- test(false, searchList, "1,2,2,3,3,4,4,5");
- test(true, searchList, "5,6,6,7,7,8,8,9");
- test(false, null, "null");
- test(true, null, "null");
-
- run_next_test();
-});
-
-add_test(function test_ril_worker_mergeCellBroadcastConfigs() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
-
- function test(olist, from, to, expected) {
- let result = ril._mergeCellBroadcastConfigs(olist, from, to);
- equal(JSON.stringify(expected), JSON.stringify(result));
- }
-
- test(null, 0, 1, [0, 1]);
-
- test([10, 13], 7, 8, [ 7, 8, 10, 13]);
- test([10, 13], 7, 9, [ 7, 9, 10, 13]);
- test([10, 13], 7, 10, [ 7, 13]);
- test([10, 13], 7, 11, [ 7, 13]);
- test([10, 13], 7, 12, [ 7, 13]);
- test([10, 13], 7, 13, [ 7, 13]);
- test([10, 13], 7, 14, [ 7, 14]);
- test([10, 13], 7, 15, [ 7, 15]);
- test([10, 13], 7, 16, [ 7, 16]);
- test([10, 13], 8, 9, [ 8, 9, 10, 13]);
- test([10, 13], 8, 10, [ 8, 13]);
- test([10, 13], 8, 11, [ 8, 13]);
- test([10, 13], 8, 12, [ 8, 13]);
- test([10, 13], 8, 13, [ 8, 13]);
- test([10, 13], 8, 14, [ 8, 14]);
- test([10, 13], 8, 15, [ 8, 15]);
- test([10, 13], 8, 16, [ 8, 16]);
- test([10, 13], 9, 10, [ 9, 13]);
- test([10, 13], 9, 11, [ 9, 13]);
- test([10, 13], 9, 12, [ 9, 13]);
- test([10, 13], 9, 13, [ 9, 13]);
- test([10, 13], 9, 14, [ 9, 14]);
- test([10, 13], 9, 15, [ 9, 15]);
- test([10, 13], 9, 16, [ 9, 16]);
- test([10, 13], 10, 11, [10, 13]);
- test([10, 13], 10, 12, [10, 13]);
- test([10, 13], 10, 13, [10, 13]);
- test([10, 13], 10, 14, [10, 14]);
- test([10, 13], 10, 15, [10, 15]);
- test([10, 13], 10, 16, [10, 16]);
- test([10, 13], 11, 12, [10, 13]);
- test([10, 13], 11, 13, [10, 13]);
- test([10, 13], 11, 14, [10, 14]);
- test([10, 13], 11, 15, [10, 15]);
- test([10, 13], 11, 16, [10, 16]);
- test([10, 13], 12, 13, [10, 13]);
- test([10, 13], 12, 14, [10, 14]);
- test([10, 13], 12, 15, [10, 15]);
- test([10, 13], 12, 16, [10, 16]);
- test([10, 13], 13, 14, [10, 14]);
- test([10, 13], 13, 15, [10, 15]);
- test([10, 13], 13, 16, [10, 16]);
- test([10, 13], 14, 15, [10, 13, 14, 15]);
- test([10, 13], 14, 16, [10, 13, 14, 16]);
- test([10, 13], 15, 16, [10, 13, 15, 16]);
-
- test([10, 13, 14, 17], 7, 8, [ 7, 8, 10, 13, 14, 17]);
- test([10, 13, 14, 17], 7, 9, [ 7, 9, 10, 13, 14, 17]);
- test([10, 13, 14, 17], 7, 10, [ 7, 13, 14, 17]);
- test([10, 13, 14, 17], 7, 11, [ 7, 13, 14, 17]);
- test([10, 13, 14, 17], 7, 12, [ 7, 13, 14, 17]);
- test([10, 13, 14, 17], 7, 13, [ 7, 13, 14, 17]);
- test([10, 13, 14, 17], 7, 14, [ 7, 17]);
- test([10, 13, 14, 17], 7, 15, [ 7, 17]);
- test([10, 13, 14, 17], 7, 16, [ 7, 17]);
- test([10, 13, 14, 17], 7, 17, [ 7, 17]);
- test([10, 13, 14, 17], 7, 18, [ 7, 18]);
- test([10, 13, 14, 17], 7, 19, [ 7, 19]);
- test([10, 13, 14, 17], 8, 9, [ 8, 9, 10, 13, 14, 17]);
- test([10, 13, 14, 17], 8, 10, [ 8, 13, 14, 17]);
- test([10, 13, 14, 17], 8, 11, [ 8, 13, 14, 17]);
- test([10, 13, 14, 17], 8, 12, [ 8, 13, 14, 17]);
- test([10, 13, 14, 17], 8, 13, [ 8, 13, 14, 17]);
- test([10, 13, 14, 17], 8, 14, [ 8, 17]);
- test([10, 13, 14, 17], 8, 15, [ 8, 17]);
- test([10, 13, 14, 17], 8, 16, [ 8, 17]);
- test([10, 13, 14, 17], 8, 17, [ 8, 17]);
- test([10, 13, 14, 17], 8, 18, [ 8, 18]);
- test([10, 13, 14, 17], 8, 19, [ 8, 19]);
- test([10, 13, 14, 17], 9, 10, [ 9, 13, 14, 17]);
- test([10, 13, 14, 17], 9, 11, [ 9, 13, 14, 17]);
- test([10, 13, 14, 17], 9, 12, [ 9, 13, 14, 17]);
- test([10, 13, 14, 17], 9, 13, [ 9, 13, 14, 17]);
- test([10, 13, 14, 17], 9, 14, [ 9, 17]);
- test([10, 13, 14, 17], 9, 15, [ 9, 17]);
- test([10, 13, 14, 17], 9, 16, [ 9, 17]);
- test([10, 13, 14, 17], 9, 17, [ 9, 17]);
- test([10, 13, 14, 17], 9, 18, [ 9, 18]);
- test([10, 13, 14, 17], 9, 19, [ 9, 19]);
- test([10, 13, 14, 17], 10, 11, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 10, 12, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 10, 13, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 10, 14, [10, 17]);
- test([10, 13, 14, 17], 10, 15, [10, 17]);
- test([10, 13, 14, 17], 10, 16, [10, 17]);
- test([10, 13, 14, 17], 10, 17, [10, 17]);
- test([10, 13, 14, 17], 10, 18, [10, 18]);
- test([10, 13, 14, 17], 10, 19, [10, 19]);
- test([10, 13, 14, 17], 11, 12, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 11, 13, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 11, 14, [10, 17]);
- test([10, 13, 14, 17], 11, 15, [10, 17]);
- test([10, 13, 14, 17], 11, 16, [10, 17]);
- test([10, 13, 14, 17], 11, 17, [10, 17]);
- test([10, 13, 14, 17], 11, 18, [10, 18]);
- test([10, 13, 14, 17], 11, 19, [10, 19]);
- test([10, 13, 14, 17], 12, 13, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 12, 14, [10, 17]);
- test([10, 13, 14, 17], 12, 15, [10, 17]);
- test([10, 13, 14, 17], 12, 16, [10, 17]);
- test([10, 13, 14, 17], 12, 17, [10, 17]);
- test([10, 13, 14, 17], 12, 18, [10, 18]);
- test([10, 13, 14, 17], 12, 19, [10, 19]);
- test([10, 13, 14, 17], 13, 14, [10, 17]);
- test([10, 13, 14, 17], 13, 15, [10, 17]);
- test([10, 13, 14, 17], 13, 16, [10, 17]);
- test([10, 13, 14, 17], 13, 17, [10, 17]);
- test([10, 13, 14, 17], 13, 18, [10, 18]);
- test([10, 13, 14, 17], 13, 19, [10, 19]);
- test([10, 13, 14, 17], 14, 15, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 14, 16, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 14, 17, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 14, 18, [10, 13, 14, 18]);
- test([10, 13, 14, 17], 14, 19, [10, 13, 14, 19]);
- test([10, 13, 14, 17], 15, 16, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 15, 17, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 15, 18, [10, 13, 14, 18]);
- test([10, 13, 14, 17], 15, 19, [10, 13, 14, 19]);
- test([10, 13, 14, 17], 16, 17, [10, 13, 14, 17]);
- test([10, 13, 14, 17], 16, 18, [10, 13, 14, 18]);
- test([10, 13, 14, 17], 16, 19, [10, 13, 14, 19]);
- test([10, 13, 14, 17], 17, 18, [10, 13, 14, 18]);
- test([10, 13, 14, 17], 17, 19, [10, 13, 14, 19]);
- test([10, 13, 14, 17], 18, 19, [10, 13, 14, 17, 18, 19]);
-
- test([10, 13, 16, 19], 7, 14, [ 7, 14, 16, 19]);
- test([10, 13, 16, 19], 7, 15, [ 7, 15, 16, 19]);
- test([10, 13, 16, 19], 7, 16, [ 7, 19]);
- test([10, 13, 16, 19], 8, 14, [ 8, 14, 16, 19]);
- test([10, 13, 16, 19], 8, 15, [ 8, 15, 16, 19]);
- test([10, 13, 16, 19], 8, 16, [ 8, 19]);
- test([10, 13, 16, 19], 9, 14, [ 9, 14, 16, 19]);
- test([10, 13, 16, 19], 9, 15, [ 9, 15, 16, 19]);
- test([10, 13, 16, 19], 9, 16, [ 9, 19]);
- test([10, 13, 16, 19], 10, 14, [10, 14, 16, 19]);
- test([10, 13, 16, 19], 10, 15, [10, 15, 16, 19]);
- test([10, 13, 16, 19], 10, 16, [10, 19]);
- test([10, 13, 16, 19], 11, 14, [10, 14, 16, 19]);
- test([10, 13, 16, 19], 11, 15, [10, 15, 16, 19]);
- test([10, 13, 16, 19], 11, 16, [10, 19]);
- test([10, 13, 16, 19], 12, 14, [10, 14, 16, 19]);
- test([10, 13, 16, 19], 12, 15, [10, 15, 16, 19]);
- test([10, 13, 16, 19], 12, 16, [10, 19]);
- test([10, 13, 16, 19], 13, 14, [10, 14, 16, 19]);
- test([10, 13, 16, 19], 13, 15, [10, 15, 16, 19]);
- test([10, 13, 16, 19], 13, 16, [10, 19]);
- test([10, 13, 16, 19], 14, 15, [10, 13, 14, 15, 16, 19]);
- test([10, 13, 16, 19], 14, 16, [10, 13, 14, 19]);
- test([10, 13, 16, 19], 15, 16, [10, 13, 15, 19]);
-
- run_next_test();
-});
-
-add_test(function test_ril_consts_cellbroadcast_misc() {
- // Must be 16 for indexing.
- equal(CB_DCS_LANG_GROUP_1.length, 16);
- equal(CB_DCS_LANG_GROUP_2.length, 16);
-
- // Array length must be even.
- equal(CB_NON_MMI_SETTABLE_RANGES.length & 0x01, 0);
- for (let i = 0; i < CB_NON_MMI_SETTABLE_RANGES.length;) {
- let from = CB_NON_MMI_SETTABLE_RANGES[i++];
- let to = CB_NON_MMI_SETTABLE_RANGES[i++];
- equal(from < to, true);
- }
-
- run_next_test();
-});
-
-add_test(function test_ril_worker_checkCellBroadcastMMISettable() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
-
- function test(from, to, expected) {
- equal(expected, ril._checkCellBroadcastMMISettable(from, to));
- }
-
- test(-2, -1, false);
- test(-1, 0, false);
- test(0, 1, true);
- test(1, 1, false);
- test(2, 1, false);
- test(65536, 65537, false);
-
- // We have both [4096, 4224), [4224, 4352), so it's actually [4096, 4352),
- // and [61440, 65536), [65535, 65536), so it's actually [61440, 65536).
- for (let i = 0; i < CB_NON_MMI_SETTABLE_RANGES.length;) {
- let from = CB_NON_MMI_SETTABLE_RANGES[i++];
- let to = CB_NON_MMI_SETTABLE_RANGES[i++];
- if ((from != 4224) && (from != 65535)) {
- test(from - 1, from, true);
- }
- test(from - 1, from + 1, false);
- test(from - 1, to, false);
- test(from - 1, to + 1, false);
- test(from, from + 1, false);
- test(from, to, false);
- test(from, to + 1, false);
- if ((from + 1) < to) {
- test(from + 1, to, false);
- test(from + 1, to + 1, false);
- }
- if ((to != 4224) && (to < 65535)) {
- test(to, to + 1, true);
- test(to + 1, to + 2, true);
- }
- }
-
- run_next_test();
-});
-
-add_test(function test_ril_worker_CellBroadcastDisabled() {
- let count = 0;
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- if (message.rilMessageType == "cellbroadcast-received") {
- ok(true, "cellbroadcast-received: " + JSON.stringify(message));
- count++;
- }
- }
- });
-
- function buildPdu(aMessageId) {
- return "C002" + aMessageId + "011154741914AFA7C76B9058" +
- "FEBEBB41E6371EA4AEB7E173D0DB5E96" +
- "83E8E832881DD6E741E4F7B9D168341A" +
- "8D46A3D168341A8D46A3D168341A8D46" +
- "A3D168341A8D46A3D168341A8D46A3D1" +
- "68341A8D46A3D100";
- }
-
- worker.ContextPool._contexts[0].RIL.cellBroadcastDisabled = true;
-
- let networkAlertIds = [
- "1100", "1107", // ETWS
- "1112", "112F", // CMAS
- "1130", "18FF", // PWS
- ];
- networkAlertIds.forEach(aMessageId => {
- worker.onRILMessage(
- 0,
- newIncomingParcel(
- -1,
- RESPONSE_TYPE_UNSOLICITED,
- UNSOLICITED_RESPONSE_NEW_BROADCAST_SMS,
- hexStringToParcelByteArrayData(buildPdu(aMessageId))));
- });
- equal(count, networkAlertIds.length, "Alerts shall not be ignored.");
-
- count = 0;
- let normalMsgIds = [ "0000", "03E7", "1108", "1901" ];
- normalMsgIds.forEach(aMessageId => {
- worker.onRILMessage(
- 0,
- newIncomingParcel(
- -1,
- RESPONSE_TYPE_UNSOLICITED,
- UNSOLICITED_RESPONSE_NEW_BROADCAST_SMS,
- hexStringToParcelByteArrayData(buildPdu(aMessageId))));
- });
- equal(count, 0, "Normal messages shall be ignored.");
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_cellbroadcast_gsm.js b/dom/system/gonk/tests/test_ril_worker_cellbroadcast_gsm.js
deleted file mode 100644
index b08b64135..000000000
--- a/dom/system/gonk/tests/test_ril_worker_cellbroadcast_gsm.js
+++ /dev/null
@@ -1,230 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_ril_worker_GsmPDUHelper_readCbDataCodingScheme() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- function test_dcs(dcs, encoding, language, hasLanguageIndicator, messageClass) {
- context.Buf.readUint8 = function() {
- return dcs;
- };
-
- let msg = {};
- context.GsmPDUHelper.readCbDataCodingScheme(msg);
-
- equal(msg.dcs, dcs);
- equal(msg.encoding, encoding);
- equal(msg.language, language);
- equal(msg.hasLanguageIndicator, hasLanguageIndicator);
- equal(msg.messageClass, messageClass);
- }
-
- function test_dcs_throws(dcs) {
- context.Buf.readUint8 = function() {
- return dcs;
- };
-
- throws(function() {
- context.GsmPDUHelper.readCbDataCodingScheme({});
- }, "Unsupported CBS data coding scheme: " + dcs);
- }
-
- // Group 0000
- for (let i = 0; i < 16; i++) {
- test_dcs(i, PDU_DCS_MSG_CODING_7BITS_ALPHABET, CB_DCS_LANG_GROUP_1[i],
- false, GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- }
-
- // Group 0001
- // 0000 GSM 7 bit default alphabet; message preceded by language indication.
- test_dcs(0x10, PDU_DCS_MSG_CODING_7BITS_ALPHABET, null, true,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- // 0001 UCS2; message preceded by language indication.
- test_dcs(0x11, PDU_DCS_MSG_CODING_16BITS_ALPHABET, null, true,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
-
- // Group 0010
- // 0000..0100
- for (let i = 0; i < 5; i++) {
- test_dcs(0x20 + i, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- CB_DCS_LANG_GROUP_2[i], false,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- }
- // 0101..1111 Reserved
- for (let i = 5; i < 16; i++) {
- test_dcs(0x20 + i, PDU_DCS_MSG_CODING_7BITS_ALPHABET, null, false,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- }
-
- // Group 0100, 0101, 1001
- for (let group of [0x40, 0x50, 0x90]) {
- for (let i = 0; i < 16; i++) {
- let encoding = i & 0x0C;
- if (encoding == 0x0C) {
- encoding = PDU_DCS_MSG_CODING_7BITS_ALPHABET;
- }
- let messageClass = GECKO_SMS_MESSAGE_CLASSES[i & PDU_DCS_MSG_CLASS_BITS];
- test_dcs(group + i, encoding, null, false, messageClass);
- }
- }
-
- // Group 1111
- for (let i = 0; i < 16; i ++) {
- let encoding = i & 0x04 ? PDU_DCS_MSG_CODING_8BITS_ALPHABET
- : PDU_DCS_MSG_CODING_7BITS_ALPHABET;
- let messageClass;
- switch(i & PDU_DCS_MSG_CLASS_BITS) {
- case 0x01: messageClass = PDU_DCS_MSG_CLASS_USER_1; break;
- case 0x02: messageClass = PDU_DCS_MSG_CLASS_USER_2; break;
- case 0x03: messageClass = PDU_DCS_MSG_CLASS_3; break;
- default: messageClass = PDU_DCS_MSG_CLASS_NORMAL; break;
- }
- test_dcs(0xF0 + i, encoding, null, false,
- GECKO_SMS_MESSAGE_CLASSES[messageClass]);
- }
-
- // Group 0011, 1000, 1010, 1011, 1100
- // 0000..1111 Reserved
- for (let group of [0x30, 0x80, 0xA0, 0xB0, 0xC0]) {
- for (let i = 0; i < 16; i++) {
- test_dcs(group + i, PDU_DCS_MSG_CODING_7BITS_ALPHABET, null, false,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- }
- }
-
- // Group 0110, 0111, 1101, 1110
- // TODO: unsupported
- for (let group of [0x60, 0x70, 0xD0, 0xE0]) {
- for (let i = 0; i < 16; i++) {
- test_dcs_throws(group + i);
- }
- }
-
- run_next_test();
-});
-
-add_test(function test_ril_worker_GsmPDUHelper_readGsmCbData() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- function test_data(options, expected) {
- let readIndex = 0;
- context.Buf.readUint8 = function() {
- return options[3][readIndex++];
- };
- context.Buf.readUint8Array = function(length) {
- let array = new Uint8Array(length);
- for (let i = 0; i < length; i++) {
- array[i] = this.readUint8();
- }
- return array;
- };
-
- let msg = {
- encoding: options[0],
- language: options[1],
- hasLanguageIndicator: options[2]
- };
- context.GsmPDUHelper.readGsmCbData(msg, options[3].length);
-
- equal(msg.body, expected[0]);
- equal(msg.data == null, expected[1] == null);
- if (expected[1] != null) {
- equal(msg.data.length, expected[1].length);
- for (let i = 0; i < expected[1].length; i++) {
- equal(msg.data[i], expected[1][i]);
- }
- }
- equal(msg.language, expected[2]);
- }
-
- // We're testing Cell Broadcast message body with all zeros octet stream. As
- // shown in 3GPP TS 23.038, septet 0x00 will be decoded as '@' when both
- // langTableIndex and langShiftTableIndex equal to
- // PDU_DCS_MSG_CODING_7BITS_ALPHABET.
-
- // PDU_DCS_MSG_CODING_7BITS_ALPHABET
- test_data([PDU_DCS_MSG_CODING_7BITS_ALPHABET, null, false,
- [0]],
- ["@", null, null]);
- test_data([PDU_DCS_MSG_CODING_7BITS_ALPHABET, null, true,
- [0, 0, 0, 0]],
- ["@", null, "@@"]);
- test_data([PDU_DCS_MSG_CODING_7BITS_ALPHABET, "@@", false,
- [0]],
- ["@", null, "@@"]);
-
- // PDU_DCS_MSG_CODING_8BITS_ALPHABET
- test_data([PDU_DCS_MSG_CODING_8BITS_ALPHABET, null, false,
- [0]],
- [null, [0], null]);
-
- // PDU_DCS_MSG_CODING_16BITS_ALPHABET
- test_data([PDU_DCS_MSG_CODING_16BITS_ALPHABET, null, false,
- [0x00, 0x40]],
- ["@", null, null]);
- test_data([PDU_DCS_MSG_CODING_16BITS_ALPHABET, null, true,
- [0x00, 0x00, 0x00, 0x40]],
- ["@", null, "@@"]);
- test_data([PDU_DCS_MSG_CODING_16BITS_ALPHABET, "@@", false,
- [0x00, 0x40]],
- ["@", null, "@@"]);
-
- run_next_test();
-});
-
-add_test(function test_ril_worker_Sim_Download_Message() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- ok(message.rilMessageType !== "cellbroadcast-received",
- "Data-Download message shall be ignored.");
- }
- });
-
- function buildPdu(aMessageId) {
- return "C002" + aMessageId + "011154741914AFA7C76B9058" +
- "FEBEBB41E6371EA4AEB7E173D0DB5E96" +
- "83E8E832881DD6E741E4F7B9D168341A" +
- "8D46A3D168341A8D46A3D168341A8D46" +
- "A3D168341A8D46A3D168341A8D46A3D1" +
- "68341A8D46A3D100";
- }
-
- ["1000", "107F", "1080", "10FF"].forEach(aMessageId => {
- worker.onRILMessage(
- 0,
- newIncomingParcel(
- -1,
- RESPONSE_TYPE_UNSOLICITED,
- UNSOLICITED_RESPONSE_NEW_BROADCAST_SMS,
- hexStringToParcelByteArrayData(buildPdu(aMessageId))));
- });
-
- ok(true, "All Data-Download Messages are ingored.");
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_cellbroadcast_umts.js b/dom/system/gonk/tests/test_ril_worker_cellbroadcast_umts.js
deleted file mode 100644
index 0380c4122..000000000
--- a/dom/system/gonk/tests/test_ril_worker_cellbroadcast_umts.js
+++ /dev/null
@@ -1,105 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-function buildHexStr(aNum, aNumSemiOctets) {
- let str = aNum.toString(16);
- while (str.length < aNumSemiOctets) {
- str = "0" + str;
- }
- return str;
-}
-
-/**
- * Verify GsmPDUHelper#readUmtsCbMessage with numOfPages from 1 to 15.
- */
-add_test(function test_GsmPDUHelper_readUmtsCbMessage_MultiParts() {
- let CB_UMTS_MESSAGE_PAGE_SIZE = 82;
- let CB_MAX_CONTENT_PER_PAGE_7BIT = 93;
- let workerHelper = newInterceptWorker(),
- worker = workerHelper.worker,
- context = worker.ContextPool._contexts[0],
- GsmPDUHelper = context.GsmPDUHelper;
-
- function test_MultiParts(aNumOfPages) {
- let pdu = buildHexStr(CB_UMTS_MESSAGE_TYPE_CBS, 2) // msg_type
- + buildHexStr(0, 4) // skip msg_id
- + buildHexStr(0, 4) // skip SN
- + buildHexStr(0, 2) // skip dcs
- + buildHexStr(aNumOfPages, 2); // set num_of_pages
- for (let i = 1; i <= aNumOfPages; i++) {
- pdu = pdu + buildHexStr(0, CB_UMTS_MESSAGE_PAGE_SIZE * 2)
- + buildHexStr(CB_UMTS_MESSAGE_PAGE_SIZE, 2); // msg_info_length
- }
-
- worker.onRILMessage(0, newIncomingParcel(-1,
- RESPONSE_TYPE_UNSOLICITED,
- UNSOLICITED_RESPONSE_NEW_BROADCAST_SMS,
- hexStringToParcelByteArrayData(pdu)));
-
- let postedMessage = workerHelper.postedMessage;
- equal("cellbroadcast-received", postedMessage.rilMessageType);
- equal(postedMessage.fullBody.length,
- aNumOfPages * CB_MAX_CONTENT_PER_PAGE_7BIT);
- }
-
- [1, 5, 15].forEach(function(i) {
- test_MultiParts(i);
- });
-
- run_next_test();
-});
-
-/**
- * Verify GsmPDUHelper#readUmtsCbMessage with 8bit encoded.
- */
-add_test(function test_GsmPDUHelper_readUmtsCbMessage_Binary() {
- let CB_UMTS_MESSAGE_PAGE_SIZE = 82;
- let CB_MAX_CONTENT_PER_PAGE_7BIT = 93;
- let TEXT_BINARY = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
- + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
- + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
- + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
- + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
- + "FFFF";
- let workerHelper = newInterceptWorker(),
- worker = workerHelper.worker,
- context = worker.ContextPool._contexts[0],
- GsmPDUHelper = context.GsmPDUHelper;
-
- function test_MultiPartsBinary(aNumOfPages) {
- let pdu = buildHexStr(CB_UMTS_MESSAGE_TYPE_CBS, 2) // msg_type
- + buildHexStr(0, 4) // skip msg_id
- + buildHexStr(0, 4) // skip SN
- + buildHexStr(68, 2) // set DCS to 8bit data
- + buildHexStr(aNumOfPages, 2); // set num_of_pages
- for (let i = 1; i <= aNumOfPages; i++) {
- pdu = pdu + TEXT_BINARY
- + buildHexStr(CB_UMTS_MESSAGE_PAGE_SIZE, 2); // msg_info_length
- }
-
- worker.onRILMessage(0, newIncomingParcel(-1,
- RESPONSE_TYPE_UNSOLICITED,
- UNSOLICITED_RESPONSE_NEW_BROADCAST_SMS,
- hexStringToParcelByteArrayData(pdu)));
-
- let postedMessage = workerHelper.postedMessage;
- equal("cellbroadcast-received", postedMessage.rilMessageType);
- equal(postedMessage.fullData.length,
- aNumOfPages * CB_UMTS_MESSAGE_PAGE_SIZE);
- for (let i = 0; i < postedMessage.fullData.length; i++) {
- equal(postedMessage.fullData[i], 255);
- }
- }
-
- [1, 5, 15].forEach(function(i) {
- test_MultiPartsBinary(i);
- });
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_cf.js b/dom/system/gonk/tests/test_ril_worker_cf.js
deleted file mode 100644
index b8db716b7..000000000
--- a/dom/system/gonk/tests/test_ril_worker_cf.js
+++ /dev/null
@@ -1,126 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-function toaFromString(number) {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
- let context = worker.ContextPool._contexts[0];
- return context.RIL._toaFromString(number);
-}
-
-add_test(function test_toaFromString_empty() {
- let retval = toaFromString("");
-
- equal(retval, TOA_UNKNOWN);
-
- run_next_test();
-});
-
-add_test(function test_toaFromString_undefined() {
- let retval = toaFromString();
-
- equal(retval, TOA_UNKNOWN);
-
- run_next_test();
-});
-
-add_test(function test_toaFromString_unknown() {
- let retval = toaFromString("666222333");
-
- equal(retval, TOA_UNKNOWN);
-
- run_next_test();
-});
-
-add_test(function test_toaFromString_international() {
- let retval = toaFromString("+34666222333");
-
- equal(retval, TOA_INTERNATIONAL);
-
- run_next_test();
-});
-
-add_test(function test_setCallForward_unconditional() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL.setCallForward = function fakeSetCallForward(options) {
- context.RIL[REQUEST_SET_CALL_FORWARD](0, {});
- };
-
- context.RIL.setCallForward({
- action: CALL_FORWARD_ACTION_REGISTRATION,
- reason: CALL_FORWARD_REASON_UNCONDITIONAL,
- serviceClass: ICC_SERVICE_CLASS_VOICE,
- number: "666222333",
- timeSeconds: 10
- });
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
-
- run_next_test();
-});
-
-add_test(function test_queryCallForwardStatus_unconditional() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL.setCallForward = function fakeSetCallForward(options) {
- context.RIL[REQUEST_SET_CALL_FORWARD](0, {});
- };
-
- context.Buf.readInt32 = function fakeReadUint32() {
- return context.Buf.int32Array.pop();
- };
-
- context.Buf.readString = function fakeReadString() {
- return "+34666222333";
- };
-
- context.RIL.queryCallForwardStatus = function fakeQueryCallForward(options) {
- context.Buf.int32Array = [
- 0, // rules.timeSeconds
- 145, // rules.toa
- 49, // rules.serviceClass
- CALL_FORWARD_REASON_UNCONDITIONAL, // rules.reason
- 1, // rules.active
- 1 // rulesLength
- ];
- context.RIL[REQUEST_QUERY_CALL_FORWARD_STATUS](1, {});
- };
-
- context.RIL.queryCallForwardStatus({
- action: CALL_FORWARD_ACTION_QUERY_STATUS,
- reason: CALL_FORWARD_REASON_UNCONDITIONAL,
- serviceClass: ICC_SERVICE_CLASS_VOICE,
- number: "666222333",
- timeSeconds: 10
- });
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
- ok(Array.isArray(postedMessage.rules));
- do_print(postedMessage.rules.length);
- equal(postedMessage.rules.length, 1);
- ok(postedMessage.rules[0].active);
- equal(postedMessage.rules[0].reason, CALL_FORWARD_REASON_UNCONDITIONAL);
- equal(postedMessage.rules[0].number, "+34666222333");
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_clip.js b/dom/system/gonk/tests/test_ril_worker_clip.js
deleted file mode 100644
index d1ce5f617..000000000
--- a/dom/system/gonk/tests/test_ril_worker_clip.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_queryCLIP_provisioned() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.readInt32 = function fakeReadUint32() {
- return context.Buf.int32Array.pop();
- };
-
- context.RIL.queryCLIP = function fakeQueryCLIP(options) {
- context.Buf.int32Array = [
- 1, // CLIP provisioned.
- 1 // Length.
- ];
- context.RIL[REQUEST_QUERY_CLIP](1, {});
- };
-
- context.RIL.queryCLIP({});
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
- equal(postedMessage.provisioned, 1);
- run_next_test();
-});
-
-add_test(function test_getCLIP_error_generic_failure_invalid_length() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.readInt32 = function fakeReadUint32() {
- return context.Buf.int32Array.pop();
- };
-
- context.RIL.queryCLIP = function fakeQueryCLIP(options) {
- context.Buf.int32Array = [
- 1, // CLIP provisioned.
- 0 // Length.
- ];
- context.RIL[REQUEST_QUERY_CLIP](1, {});
- };
-
- context.RIL.queryCLIP({});
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, GECKO_ERROR_GENERIC_FAILURE);
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_clir.js b/dom/system/gonk/tests/test_ril_worker_clir.js
deleted file mode 100644
index 5882a3c4c..000000000
--- a/dom/system/gonk/tests/test_ril_worker_clir.js
+++ /dev/null
@@ -1,122 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-// Calling line identification restriction constants.
-
-// Uses subscription default value.
-const CLIR_DEFAULT = 0;
-// Restricts CLI presentation.
-const CLIR_INVOCATION = 1;
-// Allows CLI presentation.
-const CLIR_SUPPRESSION = 2;
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_setCLIR_success() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL.setCLIR = function fakeSetCLIR(options) {
- context.RIL[REQUEST_SET_CLIR](0, {
- rilMessageType: "setCLIR"
- });
- };
-
- context.RIL.setCLIR({
- clirMode: CLIR_DEFAULT
- });
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
-
- run_next_test();
-});
-
-add_test(function test_setCLIR_generic_failure() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL.setCLIR = function fakeSetCLIR(options) {
- context.RIL[REQUEST_SET_CLIR](0, {
- rilMessageType: "setCLIR",
- errorMsg: GECKO_ERROR_GENERIC_FAILURE
- });
- };
-
- context.RIL.setCLIR({
- clirMode: CLIR_DEFAULT
- });
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, GECKO_ERROR_GENERIC_FAILURE);
-
- run_next_test();
-});
-
-add_test(function test_getCLIR_n0_m1() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.readInt32 = function fakeReadUint32() {
- return context.Buf.int32Array.pop();
- };
-
- context.RIL.getCLIR = function fakeGetCLIR(options) {
- context.Buf.int32Array = [
- 1, // Presentation indicator is used according to the subscription
- // of the CLIR service.
- 0, // CLIR provisioned in permanent mode.
- 2 // Length.
- ];
- context.RIL[REQUEST_GET_CLIR](1, {
- rilMessageType: "setCLIR"
- });
- };
-
- context.RIL.getCLIR({});
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
- equal(postedMessage.n, 0);
- equal(postedMessage.m, 1);
- run_next_test();
-});
-
-add_test(function test_getCLIR_error_generic_failure_invalid_length() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.readInt32 = function fakeReadUint32() {
- return context.Buf.int32Array.pop();
- };
-
- context.RIL.getCLIR = function fakeGetCLIR(options) {
- context.Buf.int32Array = [
- 1, // Presentation indicator is used according to the subscription
- // of the CLIR service.
- 0, // CLIR provisioned in permanent mode.
- 0 // Length (invalid one).
- ];
- context.RIL[REQUEST_GET_CLIR](1, {
- rilMessageType: "setCLIR"
- });
- };
-
- context.RIL.getCLIR({});
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, GECKO_ERROR_GENERIC_FAILURE);
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_cw.js b/dom/system/gonk/tests/test_ril_worker_cw.js
deleted file mode 100644
index efa8b5c21..000000000
--- a/dom/system/gonk/tests/test_ril_worker_cw.js
+++ /dev/null
@@ -1,104 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_setCallWaiting_success() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL.setCallWaiting = function fakeSetCallWaiting(options) {
- context.RIL[REQUEST_SET_CALL_WAITING](0, {});
- };
-
- context.RIL.setCallWaiting({
- enabled: true
- });
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
-
- run_next_test();
-});
-
-add_test(function test_setCallWaiting_generic_failure() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL.setCallWaiting = function fakeSetCallWaiting(options) {
- context.RIL[REQUEST_SET_CALL_WAITING](0, {
- errorMsg: GECKO_ERROR_GENERIC_FAILURE
- });
- };
-
- context.RIL.setCallWaiting({
- enabled: true
- });
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, GECKO_ERROR_GENERIC_FAILURE);
-
- run_next_test();
-});
-
-add_test(function test_queryCallWaiting_success_enabled_true() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.readInt32 = function fakeReadUint32() {
- return context.Buf.int32Array.pop();
- };
-
- context.RIL.queryCallWaiting = function fakeQueryCallWaiting(options) {
- context.Buf.int32Array = [
- 1, // serviceClass
- 1, // enabled
- 2 // length
- ];
- context.RIL[REQUEST_QUERY_CALL_WAITING](1, {});
- };
-
- context.RIL.queryCallWaiting({});
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
- equal(postedMessage.serviceClass, 1);
- run_next_test();
-});
-
-add_test(function test_queryCallWaiting_success_enabled_false() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.readInt32 = function fakeReadUint32() {
- return context.Buf.int32Array.pop();
- };
-
- context.RIL.queryCallWaiting = function fakeQueryCallWaiting(options) {
- context.Buf.int32Array = [
- 1, // serviceClass
- 0, // enabled
- 2 // length
- ];
- context.RIL[REQUEST_QUERY_CALL_WAITING](1, {});
- };
-
- context.RIL.queryCallWaiting({});
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
- equal(postedMessage.serviceClass, ICC_SERVICE_CLASS_NONE);
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_ecm.js b/dom/system/gonk/tests/test_ril_worker_ecm.js
deleted file mode 100644
index d10cba9ec..000000000
--- a/dom/system/gonk/tests/test_ril_worker_ecm.js
+++ /dev/null
@@ -1,168 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-var timeoutCallback = null;
-var timeoutDelayMs = 0;
-const TIMER_ID = 1234;
-const TIMEOUT_VALUE = 300000; // 5 mins.
-
-// No window in xpcshell-test. Create our own timer mechanism.
-
-function setTimeout(callback, timeoutMs) {
- timeoutCallback = callback;
- timeoutDelayMs = timeoutMs;
- equal(timeoutMs, TIMEOUT_VALUE);
- return TIMER_ID;
-}
-
-function clearTimeout(timeoutId) {
- equal(timeoutId, TIMER_ID);
- timeoutCallback = null;
-}
-
-function fireTimeout() {
- notEqual(timeoutCallback, null);
- if (timeoutCallback) {
- timeoutCallback();
- timeoutCallback = null;
- }
-}
-
-add_test(function test_enter_emergencyCbMode() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- // Do it twice. Should always send the event.
- for (let i = 0; i < 2; ++i) {
- context.RIL[UNSOLICITED_ENTER_EMERGENCY_CALLBACK_MODE]();
- let postedMessage = workerHelper.postedMessage;
-
- // Should store the mode.
- equal(context.RIL._isInEmergencyCbMode, true);
-
- // Should notify change.
- equal(postedMessage.rilMessageType, "emergencyCbModeChange");
- equal(postedMessage.active, true);
- equal(postedMessage.timeoutMs, TIMEOUT_VALUE);
-
- // Should start timer.
- equal(context.RIL._exitEmergencyCbModeTimeoutID, TIMER_ID);
- }
-
- run_next_test();
-});
-
-add_test(function test_exit_emergencyCbMode() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL[UNSOLICITED_ENTER_EMERGENCY_CALLBACK_MODE]();
- context.RIL[UNSOLICITED_EXIT_EMERGENCY_CALLBACK_MODE]();
- let postedMessage = workerHelper.postedMessage;
-
- // Should store the mode.
- equal(context.RIL._isInEmergencyCbMode, false);
-
- // Should notify change.
- equal(postedMessage.rilMessageType, "emergencyCbModeChange");
- equal(postedMessage.active, false);
-
- // Should clear timer.
- equal(context.RIL._exitEmergencyCbModeTimeoutID, null);
-
- run_next_test();
-});
-
-add_test(function test_request_exit_emergencyCbMode_when_timeout() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL[UNSOLICITED_ENTER_EMERGENCY_CALLBACK_MODE]();
- equal(context.RIL._isInEmergencyCbMode, true);
- equal(context.RIL._exitEmergencyCbModeTimeoutID, TIMER_ID);
-
- let parcelTypes = [];
- context.Buf.newParcel = function(type, options) {
- parcelTypes.push(type);
- };
-
- // Timeout.
- fireTimeout();
-
- // Should clear timeout event.
- equal(context.RIL._exitEmergencyCbModeTimeoutID, null);
-
- // Check indeed sent out REQUEST_EXIT_EMERGENCY_CALLBACK_MODE.
- notEqual(parcelTypes.indexOf(REQUEST_EXIT_EMERGENCY_CALLBACK_MODE), -1);
-
- run_next_test();
-});
-
-add_test(function test_request_exit_emergencyCbMode_when_dial() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL[UNSOLICITED_ENTER_EMERGENCY_CALLBACK_MODE]();
- equal(context.RIL._isInEmergencyCbMode, true);
- equal(context.RIL._exitEmergencyCbModeTimeoutID, TIMER_ID);
-
- let parcelTypes = [];
- context.Buf.newParcel = function(type, options) {
- parcelTypes.push(type);
- };
-
- // Dial non-emergency call.
- context.RIL.dial({number: "0912345678",
- isEmergency: false,
- isDialEmergency: false});
-
- // Should clear timeout event.
- equal(context.RIL._exitEmergencyCbModeTimeoutID, null);
-
- // Check indeed sent out REQUEST_EXIT_EMERGENCY_CALLBACK_MODE.
- notEqual(parcelTypes.indexOf(REQUEST_EXIT_EMERGENCY_CALLBACK_MODE), -1);
-
- run_next_test();
-});
-
-add_test(function test_request_exit_emergencyCbMode_explicitly() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL[UNSOLICITED_ENTER_EMERGENCY_CALLBACK_MODE]();
- equal(context.RIL._isInEmergencyCbMode, true);
- equal(context.RIL._exitEmergencyCbModeTimeoutID, TIMER_ID);
-
- let parcelTypes = [];
- context.Buf.newParcel = function(type, options) {
- parcelTypes.push(type);
- };
-
- context.RIL.handleChromeMessage({rilMessageType: "exitEmergencyCbMode"});
- context.RIL[REQUEST_EXIT_EMERGENCY_CALLBACK_MODE](1, {
- rilMessageType: "exitEmergencyCbMode"
- });
- let postedMessage = workerHelper.postedMessage;
-
- // Should clear timeout event.
- equal(context.RIL._exitEmergencyCbModeTimeoutID, null);
-
- // Check indeed sent out REQUEST_EXIT_EMERGENCY_CALLBACK_MODE.
- notEqual(parcelTypes.indexOf(REQUEST_EXIT_EMERGENCY_CALLBACK_MODE), -1);
-
- // Send back the response.
- equal(postedMessage.rilMessageType, "exitEmergencyCbMode");
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_BerTlvHelper.js b/dom/system/gonk/tests/test_ril_worker_icc_BerTlvHelper.js
deleted file mode 100644
index 89fcd874d..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_BerTlvHelper.js
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-// Test ICC_COMMAND_GET_RESPONSE with FCP template format.
-/**
- * Verify transparent structure with FCP template format.
- */
-add_test(function test_fcp_template_for_transparent_structure() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let berHelper = context.BerTlvHelper;
-
- let tag_test = [
- 0x62,
- 0x22,
- 0x82, 0x02, 0x41, 0x21,
- 0x83, 0x02, 0x2F, 0xE2,
- 0xA5, 0x09, 0xC1, 0x04, 0x40, 0x0F, 0xF5, 0x55, 0x92, 0x01, 0x00,
- 0x8A, 0x01, 0x05,
- 0x8B, 0x03, 0x2F, 0x06, 0x0B,
- 0x80, 0x02, 0x00, 0x0A,
- 0x88, 0x01, 0x10];
-
- for (let i = 0; i < tag_test.length; i++) {
- pduHelper.writeHexOctet(tag_test[i]);
- }
-
- let berTlv = berHelper.decode(tag_test.length);
- let iter = berTlv.value.values();
- let tlv = berHelper.searchForNextTag(BER_FCP_FILE_DESCRIPTOR_TAG, iter);
- equal(tlv.value.fileStructure, UICC_EF_STRUCTURE[EF_STRUCTURE_TRANSPARENT]);
-
- tlv = berHelper.searchForNextTag(BER_FCP_FILE_IDENTIFIER_TAG, iter);
- equal(tlv.value.fileId, 0x2FE2);
-
- tlv = berHelper.searchForNextTag(BER_FCP_FILE_SIZE_DATA_TAG, iter);
- equal(tlv.value.fileSizeData, 0x0A);
-
- run_next_test();
-});
-
-/**
- * Verify linear fixed structure with FCP template format.
- */
-add_test(function test_fcp_template_for_linear_fixed_structure() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let berHelper = context.BerTlvHelper;
-
- let tag_test = [
- 0x62,
- 0x1E,
- 0x82, 0x05, 0x42, 0x21, 0x00, 0x1A, 0x01,
- 0x83, 0x02, 0x6F, 0x40,
- 0xA5, 0x03, 0x92, 0x01, 0x00,
- 0x8A, 0x01, 0x07,
- 0x8B, 0x03, 0x6F, 0x06, 0x02,
- 0x80, 0x02, 0x00, 0x1A,
- 0x88, 0x00];
-
- for (let i = 0; i < tag_test.length; i++) {
- pduHelper.writeHexOctet(tag_test[i]);
- }
-
- let berTlv = berHelper.decode(tag_test.length);
- let iter = berTlv.value.values();
- let tlv = berHelper.searchForNextTag(BER_FCP_FILE_DESCRIPTOR_TAG, iter);
- equal(tlv.value.fileStructure, UICC_EF_STRUCTURE[EF_STRUCTURE_LINEAR_FIXED]);
- equal(tlv.value.recordLength, 0x1A);
- equal(tlv.value.numOfRecords, 0x01);
-
- tlv = berHelper.searchForNextTag(BER_FCP_FILE_IDENTIFIER_TAG, iter);
- equal(tlv.value.fileId, 0x6F40);
-
- tlv = berHelper.searchForNextTag(BER_FCP_FILE_SIZE_DATA_TAG, iter);
- equal(tlv.value.fileSizeData, 0x1A);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_CardLock.js b/dom/system/gonk/tests/test_ril_worker_icc_CardLock.js
deleted file mode 100644
index dc7eb93b9..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_CardLock.js
+++ /dev/null
@@ -1,282 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify RIL.iccGetCardLockEnabled
- */
-add_test(function test_icc_get_card_lock_enabled() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let ril = context.RIL;
- ril.aid = "123456789";
-
- function do_test(aLock) {
- const serviceClass = ICC_SERVICE_CLASS_VOICE |
- ICC_SERVICE_CLASS_DATA |
- ICC_SERVICE_CLASS_FAX;
-
- buf.sendParcel = function fakeSendParcel() {
- // Request Type.
- equal(this.readInt32(), REQUEST_QUERY_FACILITY_LOCK)
-
- // Token : we don't care.
- this.readInt32();
-
- // Data
- let parcel = this.readStringList();
- equal(parcel.length, 4);
- equal(parcel[0], GECKO_CARDLOCK_TO_FACILITY[aLock]);
- equal(parcel[1], "");
- equal(parcel[2], serviceClass.toString());
- equal(parcel[3], ril.aid);
- };
-
- ril.iccGetCardLockEnabled({lockType: aLock});
- }
-
- do_test(GECKO_CARDLOCK_PIN)
- do_test(GECKO_CARDLOCK_FDN)
-
- run_next_test();
-});
-
-add_test(function test_path_id_for_spid_and_spn() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }});
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let ICCFileHelper = context.ICCFileHelper;
-
- // Test SIM
- RIL.appType = CARD_APPTYPE_SIM;
- equal(ICCFileHelper.getEFPath(ICC_EF_SPDI),
- EF_PATH_MF_SIM + EF_PATH_DF_GSM);
- equal(ICCFileHelper.getEFPath(ICC_EF_SPN),
- EF_PATH_MF_SIM + EF_PATH_DF_GSM);
-
- // Test USIM
- RIL.appType = CARD_APPTYPE_USIM;
- equal(ICCFileHelper.getEFPath(ICC_EF_SPDI),
- EF_PATH_MF_SIM + EF_PATH_ADF_USIM);
- equal(ICCFileHelper.getEFPath(ICC_EF_SPDI),
- EF_PATH_MF_SIM + EF_PATH_ADF_USIM);
- run_next_test();
-});
-
-/**
- * Verify RIL.iccSetCardLockEnabled
- */
-add_test(function test_icc_set_card_lock_enabled() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let ril = context.RIL;
- ril.aid = "123456789";
-
- function do_test(aLock, aPassword, aEnabled) {
- const serviceClass = ICC_SERVICE_CLASS_VOICE |
- ICC_SERVICE_CLASS_DATA |
- ICC_SERVICE_CLASS_FAX;
-
- buf.sendParcel = function fakeSendParcel() {
- // Request Type.
- equal(this.readInt32(), REQUEST_SET_FACILITY_LOCK);
-
- // Token : we don't care
- this.readInt32();
-
- // Data
- let parcel = this.readStringList();
- equal(parcel.length, 5);
- equal(parcel[0], GECKO_CARDLOCK_TO_FACILITY[aLock]);
- equal(parcel[1], aEnabled ? "1" : "0");
- equal(parcel[2], aPassword);
- equal(parcel[3], serviceClass.toString());
- equal(parcel[4], ril.aid);
- };
-
- ril.iccSetCardLockEnabled({
- lockType: aLock,
- enabled: aEnabled,
- password: aPassword});
- }
-
- do_test(GECKO_CARDLOCK_PIN, "1234", true);
- do_test(GECKO_CARDLOCK_PIN, "1234", false);
- do_test(GECKO_CARDLOCK_FDN, "4321", true);
- do_test(GECKO_CARDLOCK_FDN, "4321", false);
-
- run_next_test();
-});
-
-/**
- * Verify RIL.iccChangeCardLockPassword
- */
-add_test(function test_icc_change_card_lock_password() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let ril = context.RIL;
-
-
- function do_test(aLock, aPassword, aNewPassword) {
- let GECKO_CARDLOCK_TO_REQUEST = {};
- GECKO_CARDLOCK_TO_REQUEST[GECKO_CARDLOCK_PIN] = REQUEST_CHANGE_SIM_PIN;
- GECKO_CARDLOCK_TO_REQUEST[GECKO_CARDLOCK_PIN2] = REQUEST_CHANGE_SIM_PIN2;
-
- buf.sendParcel = function fakeSendParcel() {
- // Request Type.
- equal(this.readInt32(), GECKO_CARDLOCK_TO_REQUEST[aLock]);
-
- // Token : we don't care
- this.readInt32();
-
- // Data
- let parcel = this.readStringList();
- equal(parcel.length, 3);
- equal(parcel[0], aPassword);
- equal(parcel[1], aNewPassword);
- equal(parcel[2], ril.aid);
- };
-
- ril.iccChangeCardLockPassword({
- lockType: aLock,
- password: aPassword,
- newPassword: aNewPassword});
- }
-
- do_test(GECKO_CARDLOCK_PIN, "1234", "4321");
- do_test(GECKO_CARDLOCK_PIN2, "1234", "4321");
-
- run_next_test();
-});
-
-/**
- * Verify RIL.iccUnlockCardLock - PIN
- */
-add_test(function test_icc_unlock_card_lock_pin() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let buf = context.Buf;
- ril.aid = "123456789";
-
- function do_test(aLock, aPassword) {
- let GECKO_CARDLOCK_TO_REQUEST = {};
- GECKO_CARDLOCK_TO_REQUEST[GECKO_CARDLOCK_PIN] = REQUEST_ENTER_SIM_PIN;
- GECKO_CARDLOCK_TO_REQUEST[GECKO_CARDLOCK_PIN2] = REQUEST_ENTER_SIM_PIN2;
-
- buf.sendParcel = function fakeSendParcel() {
- // Request Type.
- equal(this.readInt32(), GECKO_CARDLOCK_TO_REQUEST[aLock]);
-
- // Token : we don't care
- this.readInt32();
-
- // Data
- let parcel = this.readStringList();
- equal(parcel.length, 2);
- equal(parcel[0], aPassword);
- equal(parcel[1], ril.aid);
- };
-
- ril.iccUnlockCardLock({
- lockType: aLock,
- password: aPassword
- });
- }
-
- do_test(GECKO_CARDLOCK_PIN, "1234");
- do_test(GECKO_CARDLOCK_PIN2, "1234");
-
- run_next_test();
-});
-
-/**
- * Verify RIL.iccUnlockCardLock - PUK
- */
-add_test(function test_icc_unlock_card_lock_puk() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let buf = context.Buf;
- ril.aid = "123456789";
-
- function do_test(aLock, aPassword, aNewPin) {
- let GECKO_CARDLOCK_TO_REQUEST = {};
- GECKO_CARDLOCK_TO_REQUEST[GECKO_CARDLOCK_PUK] = REQUEST_ENTER_SIM_PUK;
- GECKO_CARDLOCK_TO_REQUEST[GECKO_CARDLOCK_PUK2] = REQUEST_ENTER_SIM_PUK2;
-
- buf.sendParcel = function fakeSendParcel() {
- // Request Type.
- equal(this.readInt32(), GECKO_CARDLOCK_TO_REQUEST[aLock]);
-
- // Token : we don't care
- this.readInt32();
-
- // Data
- let parcel = this.readStringList();
- equal(parcel.length, 3);
- equal(parcel[0], aPassword);
- equal(parcel[1], aNewPin);
- equal(parcel[2], ril.aid);
- };
-
- ril.iccUnlockCardLock({
- lockType: aLock,
- password: aPassword,
- newPin: aNewPin
- });
- }
-
- do_test(GECKO_CARDLOCK_PUK, "12345678", "1234");
- do_test(GECKO_CARDLOCK_PUK2, "12345678", "1234");
-
- run_next_test();
-});
-
-/**
- * Verify RIL.iccUnlockCardLock - Depersonalization
- */
-add_test(function test_icc_unlock_card_lock_depersonalization() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let buf = context.Buf;
-
- function do_test(aPassword) {
- buf.sendParcel = function fakeSendParcel() {
- // Request Type.
- equal(this.readInt32(), REQUEST_ENTER_NETWORK_DEPERSONALIZATION_CODE);
-
- // Token : we don't care
- this.readInt32();
-
- // Data
- let parcel = this.readStringList();
- equal(parcel.length, 1);
- equal(parcel[0], aPassword);
- };
-
- ril.iccUnlockCardLock({
- lockType: GECKO_CARDLOCK_NCK,
- password: aPassword
- });
- }
-
- do_test("12345678");
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_CardState.js b/dom/system/gonk/tests/test_ril_worker_icc_CardState.js
deleted file mode 100644
index 788df5073..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_CardState.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_personalization_state() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
-
- context.ICCRecordHelper.readICCID = function fakeReadICCID() {};
-
- function testPersonalization(isCdma, cardPersoState, geckoCardState) {
- let iccStatus = {
- cardState: CARD_STATE_PRESENT,
- gsmUmtsSubscriptionAppIndex: (!isCdma) ? 0 : -1,
- cdmaSubscriptionAppIndex: (isCdma) ? 0 : -1,
- apps: [
- {
- app_state: CARD_APPSTATE_SUBSCRIPTION_PERSO,
- perso_substate: cardPersoState
- }],
- };
-
- ril._isCdma = isCdma;
- ril._processICCStatus(iccStatus);
- equal(ril.cardState, geckoCardState);
- }
-
- // Test GSM personalization state.
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_NETWORK,
- Ci.nsIIcc.CARD_STATE_NETWORK_LOCKED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_NETWORK_SUBSET,
- Ci.nsIIcc.CARD_STATE_NETWORK_SUBSET_LOCKED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_CORPORATE,
- Ci.nsIIcc.CARD_STATE_CORPORATE_LOCKED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_SERVICE_PROVIDER,
- Ci.nsIIcc.CARD_STATE_SERVICE_PROVIDER_LOCKED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_SIM,
- Ci.nsIIcc.CARD_STATE_SIM_LOCKED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_NETWORK_PUK,
- Ci.nsIIcc.CARD_STATE_NETWORK_PUK_REQUIRED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_NETWORK_SUBSET_PUK,
- Ci.nsIIcc.CARD_STATE_NETWORK_SUBSET_PUK_REQUIRED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_CORPORATE_PUK,
- Ci.nsIIcc.CARD_STATE_CORPORATE_PUK_REQUIRED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_SERVICE_PROVIDER_PUK,
- Ci.nsIIcc.CARD_STATE_SERVICE_PROVIDER_PUK_REQUIRED);
- testPersonalization(false, CARD_PERSOSUBSTATE_SIM_SIM_PUK,
- Ci.nsIIcc.CARD_STATE_SIM_PUK_REQUIRED);
-
- testPersonalization(false, CARD_PERSOSUBSTATE_UNKNOWN,
- Ci.nsIIcc.CARD_STATE_UNKNOWN);
- testPersonalization(false, CARD_PERSOSUBSTATE_IN_PROGRESS,
- Ci.nsIIcc.CARD_STATE_PERSONALIZATION_IN_PROGRESS);
- testPersonalization(false, CARD_PERSOSUBSTATE_READY,
- Ci.nsIIcc.CARD_STATE_PERSONALIZATION_READY);
-
- // Test CDMA personalization state.
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_NETWORK1,
- Ci.nsIIcc.CARD_STATE_NETWORK1_LOCKED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_NETWORK2,
- Ci.nsIIcc.CARD_STATE_NETWORK2_LOCKED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_HRPD,
- Ci.nsIIcc.CARD_STATE_HRPD_NETWORK_LOCKED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_CORPORATE,
- Ci.nsIIcc.CARD_STATE_RUIM_CORPORATE_LOCKED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_SERVICE_PROVIDER,
- Ci.nsIIcc.CARD_STATE_RUIM_SERVICE_PROVIDER_LOCKED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_RUIM,
- Ci.nsIIcc.CARD_STATE_RUIM_LOCKED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_NETWORK1_PUK,
- Ci.nsIIcc.CARD_STATE_NETWORK1_PUK_REQUIRED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_NETWORK2_PUK,
- Ci.nsIIcc.CARD_STATE_NETWORK2_PUK_REQUIRED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_HRPD_PUK,
- Ci.nsIIcc.CARD_STATE_HRPD_NETWORK_PUK_REQUIRED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_CORPORATE_PUK,
- Ci.nsIIcc.CARD_STATE_RUIM_CORPORATE_PUK_REQUIRED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_SERVICE_PROVIDER_PUK,
- Ci.nsIIcc.CARD_STATE_RUIM_SERVICE_PROVIDER_PUK_REQUIRED);
- testPersonalization(true, CARD_PERSOSUBSTATE_RUIM_RUIM_PUK,
- Ci.nsIIcc.CARD_STATE_RUIM_PUK_REQUIRED);
-
- testPersonalization(true, CARD_PERSOSUBSTATE_UNKNOWN,
- Ci.nsIIcc.CARD_STATE_UNKNOWN);
- testPersonalization(true, CARD_PERSOSUBSTATE_IN_PROGRESS,
- Ci.nsIIcc.CARD_STATE_PERSONALIZATION_IN_PROGRESS);
- testPersonalization(true, CARD_PERSOSUBSTATE_READY,
- Ci.nsIIcc.CARD_STATE_PERSONALIZATION_READY);
-
- run_next_test();
-});
-
-/**
- * Verify SIM app_state in _processICCStatus
- */
-add_test(function test_card_app_state() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
-
- context.ICCRecordHelper.readICCID = function fakeReadICCID() {};
-
- function testCardAppState(cardAppState, geckoCardState) {
- let iccStatus = {
- cardState: CARD_STATE_PRESENT,
- gsmUmtsSubscriptionAppIndex: 0,
- apps: [
- {
- app_state: cardAppState
- }],
- };
-
- ril._processICCStatus(iccStatus);
- equal(ril.cardState, geckoCardState);
- }
-
- testCardAppState(CARD_APPSTATE_ILLEGAL,
- Ci.nsIIcc.CARD_STATE_ILLEGAL);
- testCardAppState(CARD_APPSTATE_PIN,
- Ci.nsIIcc.CARD_STATE_PIN_REQUIRED);
- testCardAppState(CARD_APPSTATE_PUK,
- Ci.nsIIcc.CARD_STATE_PUK_REQUIRED);
- testCardAppState(CARD_APPSTATE_READY,
- Ci.nsIIcc.CARD_STATE_READY);
- testCardAppState(CARD_APPSTATE_UNKNOWN,
- Ci.nsIIcc.CARD_STATE_UNKNOWN);
- testCardAppState(CARD_APPSTATE_DETECTED,
- Ci.nsIIcc.CARD_STATE_UNKNOWN);
-
- run_next_test();
-});
-
-/**
- * Verify permanent blocked for ICC.
- */
-add_test(function test_icc_permanent_blocked() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
-
- context.ICCRecordHelper.readICCID = function fakeReadICCID() {};
-
- function testPermanentBlocked(pin1_replaced, universalPINState, pin1) {
- let iccStatus = {
- cardState: CARD_STATE_PRESENT,
- gsmUmtsSubscriptionAppIndex: 0,
- universalPINState: universalPINState,
- apps: [
- {
- pin1_replaced: pin1_replaced,
- pin1: pin1
- }]
- };
-
- ril._processICCStatus(iccStatus);
- equal(ril.cardState, Ci.nsIIcc.CARD_STATE_PERMANENT_BLOCKED);
- }
-
- testPermanentBlocked(1,
- CARD_PINSTATE_ENABLED_PERM_BLOCKED,
- CARD_PINSTATE_UNKNOWN);
- testPermanentBlocked(1,
- CARD_PINSTATE_ENABLED_PERM_BLOCKED,
- CARD_PINSTATE_ENABLED_PERM_BLOCKED);
- testPermanentBlocked(0,
- CARD_PINSTATE_UNKNOWN,
- CARD_PINSTATE_ENABLED_PERM_BLOCKED);
-
- run_next_test();
-});
-
-/**
- * Verify ICC without app index.
- */
-add_test(function test_icc_without_app_index() {
- const ICCID = "123456789";
-
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
-
- let iccStatus = {
- cardState: CARD_STATE_PRESENT,
- gsmUmtsSubscriptionAppIndex: -1,
- universalPINState: CARD_PINSTATE_DISABLED,
- apps: [
- {
- app_state: CARD_APPSTATE_READY
- }]
- };
-
- context.ICCRecordHelper.readICCID = function fakeReadICCID() {
- ril.iccInfo.iccid = ICCID;
- };
-
- ril._processICCStatus(iccStatus);
-
- // Should read icc id event if the app index is -1.
- equal(ril.iccInfo.iccid, ICCID);
- // cardState is "unknown" if the app index is -1.
- equal(ril.cardState, GECKO_CARDSTATE_UNKNOWN);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_GsmPDUHelper.js b/dom/system/gonk/tests/test_ril_worker_icc_GsmPDUHelper.js
deleted file mode 100644
index 0d074da79..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_GsmPDUHelper.js
+++ /dev/null
@@ -1,79 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify GsmPDUHelper.writeTimestamp
- */
-add_test(function test_write_timestamp() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
-
- // current date
- let dateInput = new Date();
- let dateOutput = new Date();
- helper.writeTimestamp(dateInput);
- dateOutput.setTime(helper.readTimestamp());
-
- equal(dateInput.getFullYear(), dateOutput.getFullYear());
- equal(dateInput.getMonth(), dateOutput.getMonth());
- equal(dateInput.getDate(), dateOutput.getDate());
- equal(dateInput.getHours(), dateOutput.getHours());
- equal(dateInput.getMinutes(), dateOutput.getMinutes());
- equal(dateInput.getSeconds(), dateOutput.getSeconds());
- equal(dateInput.getTimezoneOffset(), dateOutput.getTimezoneOffset());
-
- // 2034-01-23 12:34:56 -0800 GMT
- let time = Date.UTC(2034, 1, 23, 12, 34, 56);
- time = time - (8 * 60 * 60 * 1000);
- dateInput.setTime(time);
- helper.writeTimestamp(dateInput);
- dateOutput.setTime(helper.readTimestamp());
-
- equal(dateInput.getFullYear(), dateOutput.getFullYear());
- equal(dateInput.getMonth(), dateOutput.getMonth());
- equal(dateInput.getDate(), dateOutput.getDate());
- equal(dateInput.getHours(), dateOutput.getHours());
- equal(dateInput.getMinutes(), dateOutput.getMinutes());
- equal(dateInput.getSeconds(), dateOutput.getSeconds());
- equal(dateInput.getTimezoneOffset(), dateOutput.getTimezoneOffset());
-
- run_next_test();
-});
-
-/**
- * Verify GsmPDUHelper.octectToBCD and GsmPDUHelper.BCDToOctet
- */
-add_test(function test_octect_BCD() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
-
- // 23
- let number = 23;
- let octet = helper.BCDToOctet(number);
- equal(helper.octetToBCD(octet), number);
-
- // 56
- number = 56;
- octet = helper.BCDToOctet(number);
- equal(helper.octetToBCD(octet), number);
-
- // 0x23
- octet = 0x23;
- number = helper.octetToBCD(octet);
- equal(helper.BCDToOctet(number), octet);
-
- // 0x56
- octet = 0x56;
- number = helper.octetToBCD(octet);
- equal(helper.BCDToOctet(number), octet);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_ICCContactHelper.js b/dom/system/gonk/tests/test_ril_worker_icc_ICCContactHelper.js
deleted file mode 100644
index 29b83b76a..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_ICCContactHelper.js
+++ /dev/null
@@ -1,1042 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Test error message returned in onerror for readICCContacts.
- */
-add_test(function test_error_message_read_icc_contact () {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
-
- function do_test(options, expectedErrorMsg) {
- ril.sendChromeMessage = function(message) {
- equal(message.errorMsg, expectedErrorMsg);
- }
- ril.readICCContacts(options);
- }
-
- // Error 1, didn't specify correct contactType.
- do_test({}, CONTACT_ERR_REQUEST_NOT_SUPPORTED);
-
- // Error 2, specifying a non-supported contactType.
- ril.appType = CARD_APPTYPE_USIM;
- do_test({contactType: "foo"}, CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED);
-
- // Error 3, suppose we update the supported PBR fields in USIM_PBR_FIELDS,
- // but forget to add implemenetations for it.
- USIM_PBR_FIELDS.push("pbc");
- do_test({contactType: GECKO_CARDCONTACT_TYPE_ADN},
- CONTACT_ERR_FIELD_NOT_SUPPORTED);
-
- run_next_test();
-});
-
-/**
- * Test error message returned in onerror for updateICCContact.
- */
-add_test(function test_error_message_update_icc_contact() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
-
- const ICCID = "123456789";
- ril.iccInfo.iccid = ICCID;
-
- function do_test(options, expectedErrorMsg) {
- ril.sendChromeMessage = function(message) {
- equal(message.errorMsg, expectedErrorMsg);
- }
- ril.updateICCContact(options);
- }
-
- // Error 1, didn't specify correct contactType.
- do_test({}, CONTACT_ERR_REQUEST_NOT_SUPPORTED);
-
- // Error 2, specifying a correct contactType, but without providing 'contact'.
- do_test({contactType: GECKO_CARDCONTACT_TYPE_ADN},
- CONTACT_ERR_REQUEST_NOT_SUPPORTED);
-
- // Error 3, specifying a non-supported contactType.
- ril.appType = CARD_APPTYPE_USIM;
- do_test({contactType: GECKO_CARDCONTACT_TYPE_SDN, contact: {}},
- CONTACT_ERR_CONTACT_TYPE_NOT_SUPPORTED);
-
- // Error 4, without supplying pin2.
- do_test({contactType: GECKO_CARDCONTACT_TYPE_FDN,
- contact: {contactId: ICCID + "1"}},
- GECKO_ERROR_SIM_PIN2);
-
- // Error 5, No free record found in EF_ADN.
- let record = context.ICCRecordHelper;
- record.readPBR = function(onsuccess, onerror) {
- onsuccess([{adn: {fileId: 0x4f3a}}]);
- };
-
- let io = context.ICCIOHelper;
- io.loadLinearFixedEF = function(options) {
- options.totalRecords = 1;
- options.p1 = 1;
- options.callback(options);
- };
-
- do_test({contactType: GECKO_CARDCONTACT_TYPE_ADN, contact: {}},
- CONTACT_ERR_NO_FREE_RECORD_FOUND);
-
- // Error 6, ICC IO Error.
- io.loadLinearFixedEF = function(options) {
- ril[REQUEST_SIM_IO](0, {
- errorMsg: GECKO_ERROR_GENERIC_FAILURE
- });
- };
- do_test({contactType: GECKO_CARDCONTACT_TYPE_ADN,
- contact: {contactId: ICCID + "1"}},
- GECKO_ERROR_GENERIC_FAILURE);
-
- // Error 7, suppose we update the supported PBR fields in USIM_PBR_FIELDS,
- // but forget to add implemenetations for it.
- USIM_PBR_FIELDS.push("pbc");
- do_test({contactType: GECKO_CARDCONTACT_TYPE_ADN,
- contact: {contactId: ICCID + "1"}},
- CONTACT_ERR_FIELD_NOT_SUPPORTED);
-
- // Error 8, EF_PBR doesn't exist.
- record.readPBR = function(onsuccess, onerror) {
- onsuccess([]);
- };
-
- do_test({contactType: GECKO_CARDCONTACT_TYPE_ADN,
- contact: {contactId: ICCID + "1"}},
- CONTACT_ERR_CANNOT_ACCESS_PHONEBOOK);
-
- run_next_test();
-});
-
-/**
- * Verify ICCContactHelper.readICCContacts
- */
-add_test(function test_read_icc_contacts() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.ICCRecordHelper;
- let contactHelper = context.ICCContactHelper;
- let ril = context.RIL;
- let test_data = [
- //Record 1.
- {
- comment: "Test read SIM adn contact",
- rawData: {
- simType: CARD_APPTYPE_SIM,
- contactType: GECKO_CARDCONTACT_TYPE_ADN,
- adnLike: [{recordId: 1, alphaId: "name", number: "111111"}],
- },
- expectedContact: [{
- recordId: 1,
- alphaId: "name",
- number: "111111"
- }],
- },
- //Record 2.
- {
- comment: "Test read SIM fdn contact",
- rawData: {
- simType: CARD_APPTYPE_SIM,
- contactType: GECKO_CARDCONTACT_TYPE_FDN,
- adnLike: [{recordId: 1, alphaId: "name", number: "111111"}],
- },
- expectedContact: [{
- recordId: 1,
- alphaId: "name",
- number: "111111"
- }],
- },
- //Record 3.
- {
- comment: "Test read USIM adn contact",
- rawData: {
- simType: CARD_APPTYPE_USIM,
- contactType: GECKO_CARDCONTACT_TYPE_ADN,
- pbrs: [{adn:{fileId: 0x6f3a}, email: {}, anr0: {}}],
- adnLike: [{recordId: 1, alphaId: "name", number: "111111"}],
- email: "hello@mail.com",
- anr: "123456",
- },
- expectedContact: [{
- pbrIndex: 0,
- recordId: 1,
- alphaId: "name",
- number: "111111",
- email: "hello@mail.com",
- anr: ["123456"]
- }],
- },
- //Record 4.
- {
- comment: "Test read USIM adn contacts",
- rawData: {
- simType: CARD_APPTYPE_USIM,
- contactType: GECKO_CARDCONTACT_TYPE_ADN,
- pbrs: [{adn:{fileId: 0x6f3a}, email: {}, anr0: {}},
- {adn:{fileId: 0x6f3b}, email: {}, anr0: {}}],
- adnLike: [{recordId: 1, alphaId: "name1", number: "111111"},
- {recordId: 2, alphaId: "name2", number: "222222"}],
- email: "hello@mail.com",
- anr: "123456",
- },
- expectedContact: [
- {
- pbrIndex: 0,
- recordId: 1,
- alphaId: "name1",
- number: "111111",
- email: "hello@mail.com",
- anr: ["123456"]
- }, {
- pbrIndex: 0,
- recordId: 2,
- alphaId: "name2",
- number: "222222",
- email: "hello@mail.com",
- anr: ["123456"]
- }, {
- pbrIndex: 1,
- recordId: 1,
- alphaId: "name1",
- number: "111111",
- email: "hello@mail.com",
- anr: ["123456"]
- }, {
- pbrIndex: 1,
- recordId: 2,
- alphaId: "name2",
- number: "222222",
- email: "hello@mail.com",
- anr: ["123456"]
- }
- ],
- },
- //Record 5.
- {
- comment: "Test read USIM fdn contact",
- rawData: {
- simType: CARD_APPTYPE_USIM,
- contactType: GECKO_CARDCONTACT_TYPE_FDN,
- adnLike: [{recordId: 1, alphaId: "name", number: "111111"}],
- },
- expectedContact: [{
- recordId: 1,
- alphaId: "name",
- number: "111111"
- }],
- },
- //Record 6.
- {
- comment: "Test read RUIM adn contact",
- rawData: {
- simType: CARD_APPTYPE_RUIM,
- contactType: GECKO_CARDCONTACT_TYPE_ADN,
- adnLike: [{recordId: 1, alphaId: "name", number: "111111"}],
- },
- expectedContact: [{
- recordId: 1,
- alphaId: "name",
- number: "111111"
- }],
- },
- //Record 7.
- {
- comment: "Test read RUIM fdn contact",
- rawData: {
- simType: CARD_APPTYPE_RUIM,
- contactType: GECKO_CARDCONTACT_TYPE_FDN,
- adnLike: [{recordId: 1, alphaId: "name", number: "111111"}],
- },
- expectedContact: [{
- recordId: 1,
- alphaId: "name",
- number: "111111"
- }],
- },
- //Record 8.
- {
- comment: "Test read RUIM adn contact with enhanced phone book",
- rawData: {
- simType: CARD_APPTYPE_RUIM,
- contactType: GECKO_CARDCONTACT_TYPE_ADN,
- pbrs: [{adn:{fileId: 0x6f3a}, email: {}, anr0: {}}],
- adnLike: [{recordId: 1, alphaId: "name", number: "111111"}],
- email: "hello@mail.com",
- anr: "123456",
- enhancedPhoneBook: true,
- },
- expectedContact: [{
- pbrIndex: 0,
- recordId: 1,
- alphaId: "name",
- number: "111111",
- email: "hello@mail.com",
- anr: ["123456"]
- }],
- },
- //Record 9.
- {
- comment: "Test read RUIM adn contacts with enhanced phone book",
- rawData: {
- simType: CARD_APPTYPE_RUIM,
- contactType: GECKO_CARDCONTACT_TYPE_ADN,
- pbrs: [{adn:{fileId: 0x6f3a}, email: {}, anr0: {}},
- {adn:{fileId: 0x6f3b}, email: {}, anr0: {}}],
- adnLike: [{recordId: 1, alphaId: "name1", number: "111111"},
- {recordId: 2, alphaId: "name2", number: "222222"}],
- email: "hello@mail.com",
- anr: "123456",
- enhancedPhoneBook: true,
- },
- expectedContact: [
- {
- pbrIndex: 0,
- recordId: 1,
- alphaId: "name1",
- number: "111111",
- email: "hello@mail.com",
- anr: ["123456"]
- }, {
- pbrIndex: 0,
- recordId: 2,
- alphaId: "name2",
- number: "222222",
- email: "hello@mail.com",
- anr: ["123456"]
- }, {
- pbrIndex: 1,
- recordId: 1,
- alphaId: "name1",
- number: "111111",
- email: "hello@mail.com",
- anr: ["123456"]
- }, {
- pbrIndex: 1,
- recordId: 2,
- alphaId: "name2",
- number: "222222",
- email: "hello@mail.com",
- anr: ["123456"]
- }
- ],
- },
- ];
-
- function do_test(aTestData, aExpectedContact) {
- ril.appType = aTestData.simType;
- ril._isCdma = (aTestData.simType === CARD_APPTYPE_RUIM);
- ril.iccInfoPrivate.cst = (aTestData.enhancedPhoneBook) ?
- [0x20, 0x0C, 0x0, 0x0, 0x0]:
- [0x20, 0x00, 0x0, 0x0, 0x0];
-
- ril.iccInfoPrivate.sst = (aTestData.simType === CARD_APPTYPE_SIM)?
- [0x20, 0x0, 0x0, 0x0, 0x0]:
- [0x2, 0x0, 0x0, 0x0, 0x0];
-
- // Override some functions to test.
- contactHelper.getContactFieldRecordId = function(pbr, contact, field, onsuccess, onerror) {
- onsuccess(1);
- };
-
- record.readPBR = function readPBR(onsuccess, onerror) {
- onsuccess(JSON.parse(JSON.stringify(aTestData.pbrs)));
- };
-
- record.readADNLike = function readADNLike(fileId, extFileId, onsuccess, onerror) {
- onsuccess(JSON.parse(JSON.stringify(aTestData.adnLike)));
- };
-
- record.readEmail = function readEmail(fileId, fileType, recordNumber, onsuccess, onerror) {
- onsuccess(aTestData.email);
- };
-
- record.readANR = function readANR(fileId, fileType, recordNumber, onsuccess, onerror) {
- onsuccess(aTestData.anr);
- };
-
- let onsuccess = function onsuccess(contacts) {
- for (let i = 0; i < contacts.length; i++) {
- do_print("check contacts[" + i + "]:" + JSON.stringify(contacts[i]));
- deepEqual(contacts[i], aExpectedContact[i]);
- }
- };
-
- let onerror = function onerror(errorMsg) {
- do_print("readICCContacts failed: " + errorMsg);
- ok(false);
- };
-
- contactHelper.readICCContacts(aTestData.simType, aTestData.contactType, onsuccess, onerror);
- }
-
- for (let i = 0; i < test_data.length; i++) {
- do_print(test_data[i].comment);
- do_test(test_data[i].rawData, test_data[i].expectedContact);
- }
-
- run_next_test();
-});
-
-/**
- * Verify ICCContactHelper.updateICCContact with appType is CARD_APPTYPE_USIM.
- */
-add_test(function test_update_icc_contact() {
- const ADN_RECORD_ID = 100;
- const ADN_SFI = 1;
- const IAP_FILE_ID = 0x4f17;
- const EMAIL_FILE_ID = 0x4f50;
- const EMAIL_RECORD_ID = 20;
- const ANR0_FILE_ID = 0x4f11;
- const ANR0_RECORD_ID = 30;
- const EXT_RECORD_ID = 0x01;
-
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let recordHelper = context.ICCRecordHelper;
- let contactHelper = context.ICCContactHelper;
- let ril = context.RIL;
-
- function do_test(aSimType, aContactType, aContact, aPin2, aFileType, aHaveIapIndex, aEnhancedPhoneBook) {
- ril.appType = aSimType;
- ril._isCdma = (aSimType === CARD_APPTYPE_RUIM);
- ril.iccInfoPrivate.cst = (aEnhancedPhoneBook) ? [0x20, 0x0C, 0x28, 0x0, 0x20]
- : [0x20, 0x0, 0x28, 0x0, 0x20];
- ril.iccInfoPrivate.sst = (aSimType === CARD_APPTYPE_SIM)?
- [0x20, 0x0, 0x28, 0x0, 0x20]:
- [0x16, 0x0, 0x0, 0x0, 0x0];
-
- recordHelper.readPBR = function(onsuccess, onerror) {
- if (aFileType === ICC_USIM_TYPE1_TAG) {
- onsuccess([{
- adn: {fileId: ICC_EF_ADN},
- email: {fileId: EMAIL_FILE_ID,
- fileType: ICC_USIM_TYPE1_TAG},
- anr0: {fileId: ANR0_FILE_ID,
- fileType: ICC_USIM_TYPE1_TAG},
- ext1: {fileId: ICC_EF_EXT1}
-
- }]);
- } else if (aFileType === ICC_USIM_TYPE2_TAG) {
- onsuccess([{
- adn: {fileId: ICC_EF_ADN,
- sfi: ADN_SFI},
- iap: {fileId: IAP_FILE_ID},
- email: {fileId: EMAIL_FILE_ID,
- fileType: ICC_USIM_TYPE2_TAG,
- indexInIAP: 0},
- anr0: {fileId: ANR0_FILE_ID,
- fileType: ICC_USIM_TYPE2_TAG,
- indexInIAP: 1},
- ext1: {fileId: ICC_EF_EXT1}
- }]);
- }
- };
-
- recordHelper.updateADNLike = function(fileId, extRecordNumber, contact, pin2, onsuccess, onerror) {
- if (aContactType === GECKO_CARDCONTACT_TYPE_FDN) {
- equal(fileId, ICC_EF_FDN);
- } else if (aContactType === GECKO_CARDCONTACT_TYPE_ADN) {
- equal(fileId, ICC_EF_ADN);
- }
-
- if (aContact.number.length > ADN_MAX_NUMBER_DIGITS) {
- equal(extRecordNumber, EXT_RECORD_ID);
- } else {
- equal(extRecordNumber, 0xff);
- }
-
- equal(pin2, aPin2);
- equal(contact.alphaId, aContact.alphaId);
- equal(contact.number, aContact.number);
- onsuccess({alphaId: contact.alphaId,
- number: contact.number.substring(0, ADN_MAX_NUMBER_DIGITS)});
- };
-
- recordHelper.getADNLikeExtensionRecordNumber = function(fileId, recordNumber, onsuccess, onerror) {
- onsuccess(EXT_RECORD_ID);
- };
-
- recordHelper.updateExtension = function(fileId, recordNumber, number, onsuccess, onerror) {
- onsuccess();
- };
-
- recordHelper.findFreeRecordId = function(fileId, onsuccess, onerror) {
- onsuccess(EXT_RECORD_ID);
- };
-
- recordHelper.cleanEFRecord = function(fileId, recordNumber, onsuccess, onerror) {
- onsuccess();
- }
-
- recordHelper.readIAP = function(fileId, recordNumber, onsuccess, onerror) {
- equal(fileId, IAP_FILE_ID);
- equal(recordNumber, ADN_RECORD_ID);
- onsuccess((aHaveIapIndex) ? [EMAIL_RECORD_ID, ANR0_RECORD_ID]
- : [0xff, 0xff]);
- };
-
- recordHelper.updateIAP = function(fileId, recordNumber, iap, onsuccess, onerror) {
- equal(fileId, IAP_FILE_ID);
- equal(recordNumber, ADN_RECORD_ID);
- onsuccess();
- };
-
- recordHelper.updateEmail = function(pbr, recordNumber, email, adnRecordId, onsuccess, onerror) {
- equal(pbr.email.fileId, EMAIL_FILE_ID);
- if (pbr.email.fileType === ICC_USIM_TYPE1_TAG) {
- equal(recordNumber, ADN_RECORD_ID);
- } else if (pbr.email.fileType === ICC_USIM_TYPE2_TAG) {
- equal(recordNumber, EMAIL_RECORD_ID);
- }
- equal(email, aContact.email);
- onsuccess(email);
- };
-
- recordHelper.updateANR = function(pbr, recordNumber, number, adnRecordId, onsuccess, onerror) {
- equal(pbr.anr0.fileId, ANR0_FILE_ID);
- if (pbr.anr0.fileType === ICC_USIM_TYPE1_TAG) {
- equal(recordNumber, ADN_RECORD_ID);
- } else if (pbr.anr0.fileType === ICC_USIM_TYPE2_TAG) {
- equal(recordNumber, ANR0_RECORD_ID);
- }
- if (Array.isArray(aContact.anr)) {
- equal(number, aContact.anr[0]);
- }
- onsuccess(number);
- };
-
- recordHelper.findFreeRecordId = function(fileId, onsuccess, onerror) {
- let recordId = 0;
- if (fileId === EMAIL_FILE_ID) {
- recordId = EMAIL_RECORD_ID;
- } else if (fileId === ANR0_FILE_ID) {
- recordId = ANR0_RECORD_ID;
- }
- onsuccess(recordId);
- };
-
- let isSuccess = false;
- let onsuccess = function onsuccess(updatedContact) {
- equal(ADN_RECORD_ID, updatedContact.recordId);
- equal(aContact.alphaId, updatedContact.alphaId);
- equal(aContact.number.substring(0, ADN_MAX_NUMBER_DIGITS + EXT_MAX_NUMBER_DIGITS),
- updatedContact.number);
- if ((aSimType == CARD_APPTYPE_USIM || aSimType == CARD_APPTYPE_RUIM) &&
- (aFileType == ICC_USIM_TYPE1_TAG || aFileType == ICC_USIM_TYPE2_TAG)) {
- if (aContact.hasOwnProperty('email')) {
- equal(aContact.email, updatedContact.email);
- }
-
- if (aContact.hasOwnProperty('anr')) {
- equal(aContact.anr[0], updatedContact.anr[0]);
- }
- } else {
- equal(updatedContact.email, null);
- equal(updatedContact.anr, null);
- }
-
- do_print("updateICCContact success");
- isSuccess = true;
- };
-
- let onerror = function onerror(errorMsg) {
- do_print("updateICCContact failed: " + errorMsg);
- };
-
- contactHelper.updateICCContact(aSimType, aContactType, aContact, aPin2, onsuccess, onerror);
- ok(isSuccess);
- }
-
- let contacts = [
- {
- pbrIndex: 0,
- recordId: ADN_RECORD_ID,
- alphaId: "test",
- number: "123456",
- email: "test@mail.com",
- anr: ["+654321"]
- },
- // a contact without email and anr.
- {
- pbrIndex: 0,
- recordId: ADN_RECORD_ID,
- alphaId: "test2",
- number: "123456",
- },
- // a contact with email but no anr.
- {
- pbrIndex: 0,
- recordId: ADN_RECORD_ID,
- alphaId: "test3",
- number: "123456",
- email: "test@mail.com"
- },
- // a contact with anr but no email.
- {
- pbrIndex: 0,
- recordId: ADN_RECORD_ID,
- alphaId: "test4",
- number: "123456",
- anr: ["+654321"]
- },
- // a contact number over 20 digits.
- {
- pbrIndex: 0,
- recordId: ADN_RECORD_ID,
- alphaId: "test4",
- number: "0123456789012345678901234567890123456789",
- anr: ["+654321"]
- },
- // a contact number over 40 digits.
- {
- pbrIndex: 0,
- recordId: ADN_RECORD_ID,
- alphaId: "test5",
- number: "01234567890123456789012345678901234567890123456789",
- anr: ["+654321"]
- }];
-
- for (let i = 0; i < contacts.length; i++) {
- let contact = contacts[i];
- // SIM
- do_print("Test update SIM adn contacts");
- do_test(CARD_APPTYPE_SIM, GECKO_CARDCONTACT_TYPE_ADN, contact);
-
- do_print("Test update SIM fdn contacts");
- do_test(CARD_APPTYPE_SIM, GECKO_CARDCONTACT_TYPE_FDN, contact, "1234");
-
- // USIM
- do_print("Test update USIM adn contacts");
- do_test(CARD_APPTYPE_USIM, GECKO_CARDCONTACT_TYPE_ADN, contact, null,
- ICC_USIM_TYPE1_TAG);
- do_test(CARD_APPTYPE_USIM, GECKO_CARDCONTACT_TYPE_ADN, contact, null,
- ICC_USIM_TYPE2_TAG, true);
- do_test(CARD_APPTYPE_USIM, GECKO_CARDCONTACT_TYPE_ADN, contact, null,
- ICC_USIM_TYPE2_TAG, false);
-
- do_print("Test update USIM fdn contacts");
- do_test(CARD_APPTYPE_USIM, GECKO_CARDCONTACT_TYPE_FDN, contact, "1234");
-
- // RUIM
- do_print("Test update RUIM adn contacts");
- do_test(CARD_APPTYPE_RUIM, GECKO_CARDCONTACT_TYPE_ADN, contact);
-
- do_print("Test update RUIM fdn contacts");
- do_test(CARD_APPTYPE_RUIM, GECKO_CARDCONTACT_TYPE_FDN, contact, "1234");
-
- // RUIM with enhanced phone book
- do_print("Test update RUIM adn contacts with enhanced phone book");
- do_test(CARD_APPTYPE_RUIM, GECKO_CARDCONTACT_TYPE_ADN, contact, null,
- ICC_USIM_TYPE1_TAG, null,true);
- do_test(CARD_APPTYPE_RUIM, GECKO_CARDCONTACT_TYPE_ADN, contact, null,
- ICC_USIM_TYPE2_TAG, true, true);
- do_test(CARD_APPTYPE_RUIM, GECKO_CARDCONTACT_TYPE_ADN, contact, null,
- ICC_USIM_TYPE2_TAG, false, true);
-
- do_print("Test update RUIM fdn contacts with enhanced phone book");
- do_test(CARD_APPTYPE_RUIM, GECKO_CARDCONTACT_TYPE_FDN, contact, "1234",
- null, true);
- }
-
- run_next_test();
-});
-
-/**
- * Verify ICCContactHelper.updateICCContact with appType is CARD_APPTYPE_USIM and
- * insufficient space to store Type 2 USIM contact fields.
- */
-add_test(function test_update_icc_contact_full_email_and_anr_field() {
- const ADN_RECORD_ID = 100;
- const ADN_SFI = 1;
- const IAP_FILE_ID = 0x4f17;
- const EMAIL_FILE_ID = 0x4f50;
- const EMAIL_RECORD_ID = 20;
- const ANR0_FILE_ID = 0x4f11;
- const ANR0_RECORD_ID = 30;
-
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let recordHelper = context.ICCRecordHelper;
- let contactHelper = context.ICCContactHelper;
- let ril = context.RIL;
-
- function do_test(aSimType, aContactType, aContact, aPin2) {
- ril.appType = CARD_APPTYPE_USIM;
- ril.iccInfoPrivate.sst = [0x2, 0x0, 0x0, 0x0, 0x0];
-
- recordHelper.readPBR = function(onsuccess, onerror) {
- onsuccess([{
- adn: {fileId: ICC_EF_ADN,
- sfi: ADN_SFI},
- iap: {fileId: IAP_FILE_ID},
- email: {fileId: EMAIL_FILE_ID,
- fileType: ICC_USIM_TYPE2_TAG,
- indexInIAP: 0},
- anr0: {fileId: ANR0_FILE_ID,
- fileType: ICC_USIM_TYPE2_TAG,
- indexInIAP: 1}
- }]);
- };
-
- recordHelper.updateADNLike = function(fileId, extRecordNumber, contact, pin2, onsuccess, onerror) {
- if (aContactType === GECKO_CARDCONTACT_TYPE_ADN) {
- equal(fileId, ICC_EF_ADN);
- }
- equal(pin2, aPin2);
- equal(contact.alphaId, aContact.alphaId);
- equal(contact.number, aContact.number);
- onsuccess({alphaId: contact.alphaId,
- number: contact.number});
- };
-
- recordHelper.readIAP = function(fileId, recordNumber, onsuccess, onerror) {
- equal(fileId, IAP_FILE_ID);
- equal(recordNumber, ADN_RECORD_ID);
- onsuccess([0xff, 0xff]);
- };
-
- recordHelper.updateIAP = function(fileId, recordNumber, iap, onsuccess, onerror) {
- equal(fileId, IAP_FILE_ID);
- equal(recordNumber, ADN_RECORD_ID);
- onsuccess();
- };
-
- recordHelper.findFreeRecordId = function(fileId, onsuccess, onerror) {
- let recordId = 0;
- // emulate email and anr don't have free record.
- if (fileId === EMAIL_FILE_ID || fileId === ANR0_FILE_ID) {
- onerror(CONTACT_ERR_NO_FREE_RECORD_FOUND);
- } else {
- onsuccess(recordId);
- }
- };
-
- let isSuccess = false;
- let onsuccess = function onsuccess(updatedContact) {
- equal(ADN_RECORD_ID, updatedContact.recordId);
- equal(aContact.alphaId, updatedContact.alphaId);
- equal(updatedContact.email, null);
- equal(updatedContact.anr, null);
-
- do_print("updateICCContact success");
- isSuccess = true;
- };
-
- let onerror = function onerror(errorMsg) {
- do_print("updateICCContact failed: " + errorMsg);
- };
-
- contactHelper.updateICCContact(aSimType, aContactType, aContact, aPin2, onsuccess, onerror);
- ok(isSuccess);
- }
-
- let contact = {
- pbrIndex: 0,
- recordId: ADN_RECORD_ID,
- alphaId: "test",
- number: "123456",
- email: "test@mail.com",
- anr: ["+654321"]
- };
-
- // USIM
- do_print("Test update USIM adn contacts");
- do_test(CARD_APPTYPE_USIM, GECKO_CARDCONTACT_TYPE_ADN, contact, null);
-
- run_next_test();
-});
-
-/**
- * Verify updateICCContact with removal of anr and email with File Type 1.
- */
-add_test(function test_update_icc_contact_with_remove_type1_attr() {
- const ADN_RECORD_ID = 100;
- const IAP_FILE_ID = 0x4f17;
- const EMAIL_FILE_ID = 0x4f50;
- const EMAIL_RECORD_ID = 20;
- const ANR0_FILE_ID = 0x4f11;
- const ANR0_RECORD_ID = 30;
-
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let recordHelper = context.ICCRecordHelper;
- let contactHelper = context.ICCContactHelper;
-
- recordHelper.updateADNLike = function(fileId, extRecordNumber, contact, pin2, onsuccess, onerror) {
- onsuccess({alphaId: contact.alphaId,
- number: contact.number});
- };
-
- let contact = {
- pbrIndex: 0,
- recordId: ADN_RECORD_ID,
- alphaId: "test2",
- number: "123456",
- };
-
- recordHelper.readIAP = function(fileId, recordNumber, onsuccess, onerror) {
- onsuccess([EMAIL_RECORD_ID, ANR0_RECORD_ID]);
- };
-
- recordHelper.updateEmail = function(pbr, recordNumber, email, adnRecordId, onsuccess, onerror) {
- ok(email == null);
- onsuccess(email);
- };
-
- recordHelper.updateANR = function(pbr, recordNumber, number, adnRecordId, onsuccess, onerror) {
- ok(number == null);
- onsuccess(number);
- };
-
- function do_test(type) {
- recordHelper.readPBR = function(onsuccess, onerror) {
- if (type == ICC_USIM_TYPE1_TAG) {
- onsuccess([{
- adn: {fileId: ICC_EF_ADN},
- email: {fileId: EMAIL_FILE_ID,
- fileType: ICC_USIM_TYPE1_TAG},
- anr0: {fileId: ANR0_FILE_ID,
- fileType: ICC_USIM_TYPE1_TAG}}]);
- } else {
- onsuccess([{
- adn: {fileId: ICC_EF_ADN},
- iap: {fileId: IAP_FILE_ID},
- email: {fileId: EMAIL_FILE_ID,
- fileType: ICC_USIM_TYPE2_TAG,
- indexInIAP: 0},
- anr0: {fileId: ANR0_FILE_ID,
- fileType: ICC_USIM_TYPE2_TAG,
- indexInIAP: 1}}]);
- }
- };
-
- let successCb = function(updatedContact) {
- equal(updatedContact.email, null);
- equal(updatedContact.anr, null);
- ok(true);
- };
-
- let errorCb = function(errorMsg) {
- do_print(errorMsg);
- ok(false);
- };
-
- contactHelper.updateICCContact(CARD_APPTYPE_USIM,
- GECKO_CARDCONTACT_TYPE_ADN,
- contact, null, successCb, errorCb);
- }
-
- do_test(ICC_USIM_TYPE1_TAG);
- do_test(ICC_USIM_TYPE2_TAG);
-
- run_next_test();
-});
-
-/**
- * Verify ICCContactHelper.findFreeICCContact in SIM
- */
-add_test(function test_find_free_icc_contact_sim() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let recordHelper = context.ICCRecordHelper;
- let contactHelper = context.ICCContactHelper;
- // Correct record Id starts with 1, so put a null element at index 0.
- let records = [null];
- const MAX_RECORDS = 3;
- const PBR_INDEX = 0;
-
- recordHelper.findFreeRecordId = function(fileId, onsuccess, onerror) {
- if (records.length > MAX_RECORDS) {
- onerror("No free record found.");
- return;
- }
-
- onsuccess(records.length);
- };
-
- let successCb = function(pbrIndex, recordId) {
- equal(pbrIndex, PBR_INDEX);
- records[recordId] = {};
- };
-
- let errorCb = function(errorMsg) {
- do_print(errorMsg);
- ok(false);
- };
-
- for (let i = 0; i < MAX_RECORDS; i++) {
- contactHelper.findFreeICCContact(CARD_APPTYPE_SIM,
- GECKO_CARDCONTACT_TYPE_ADN,
- successCb, errorCb);
- }
- // The 1st element, records[0], is null.
- equal(records.length - 1, MAX_RECORDS);
-
- // Now the EF is full, so finding a free one should result failure.
- successCb = function(pbrIndex, recordId) {
- ok(false);
- };
-
- errorCb = function(errorMsg) {
- ok(errorMsg === "No free record found.");
- };
- contactHelper.findFreeICCContact(CARD_APPTYPE_SIM, GECKO_CARDCONTACT_TYPE_ADN,
- successCb, errorCb);
-
- run_next_test();
-});
-
-/**
- * Verify ICCContactHelper.findFreeICCContact in USIM
- */
-add_test(function test_find_free_icc_contact_usim() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let recordHelper = context.ICCRecordHelper;
- let contactHelper = context.ICCContactHelper;
- const ADN1_FILE_ID = 0x6f3a;
- const ADN2_FILE_ID = 0x6f3b;
- const MAX_RECORDS = 3;
-
- // The adn in the first phonebook set has already two records, which means
- // only 1 free record remained.
- let pbrs = [{adn: {fileId: ADN1_FILE_ID, records: [null, {}, {}]}},
- {adn: {fileId: ADN2_FILE_ID, records: [null]}}];
-
- recordHelper.readPBR = function readPBR(onsuccess, onerror) {
- onsuccess(pbrs);
- };
-
- recordHelper.findFreeRecordId = function(fileId, onsuccess, onerror) {
- let pbr = (fileId == ADN1_FILE_ID ? pbrs[0]: pbrs[1]);
- if (pbr.adn.records.length > MAX_RECORDS) {
- onerror("No free record found.");
- return;
- }
-
- onsuccess(pbr.adn.records.length);
- };
-
- let successCb = function(pbrIndex, recordId) {
- equal(pbrIndex, 0);
- pbrs[pbrIndex].adn.records[recordId] = {};
- };
-
- let errorCb = function(errorMsg) {
- ok(false);
- };
-
- contactHelper.findFreeICCContact(CARD_APPTYPE_USIM,
- GECKO_CARDCONTACT_TYPE_ADN,
- successCb, errorCb);
-
- // Now the EF_ADN in the 1st phonebook set is full, so the next free contact
- // will come from the 2nd phonebook set.
- successCb = function(pbrIndex, recordId) {
- equal(pbrIndex, 1);
- equal(recordId, 1);
- }
- contactHelper.findFreeICCContact(CARD_APPTYPE_USIM,
- GECKO_CARDCONTACT_TYPE_ADN,
- successCb, errorCb);
-
- run_next_test();
-});
-
-/**
- * Verify ICCContactHelper.updateADNLikeWithExtension
- */
-add_test(function test_update_adn_like_with_extension() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let record = context.ICCRecordHelper;
- let contactHelper = context.ICCContactHelper;
- ril.appType = CARD_APPTYPE_SIM;
- // Correct record Id starts from 1, so put a null element at index 0.
- // ext_records contains data at index 1, and it only has 1 free record at index 2.
- let notFree = 0x01;
- let ext_records = [null, notFree, null];
-
- function do_test(contact, extRecordNumber, expectedExtRecordNumber, expectedNumber, expectedCleanEFRecord) {
- // Override some functions to test.
- record.getADNLikeExtensionRecordNumber = function(fileId, recordNumber, onsuccess, onerror) {
- onsuccess(extRecordNumber);
- }
-
- record.updateADNLike = function(fileId, extRecordNumber, contact, pin2, onsuccess, onerror) {
- equal(extRecordNumber, expectedExtRecordNumber);
- onsuccess({alphaId: contact.alphaId,
- number: contact.number.substring(0, ADN_MAX_NUMBER_DIGITS)});
- }
-
- record.updateExtension = function(fileId, recordNumber, number, onsuccess, onerror) {
- if (recordNumber > ext_records.length) {
- onerror("updateExtension failed.");
- return;
- }
- ext_records[recordNumber] = number;
- onsuccess();
- }
-
- record.findFreeRecordId = function(fileId, onsuccess, onerror) {
- for (let i = 1; i < ext_records.length; i++) {
- if (!ext_records[i]) {
- onsuccess(i);
- return;
- }
- }
-
- onerror("No free record found.");
- }
-
- let isCleanEFRecord = false;
- record.cleanEFRecord = function(fileId, recordNumber, onsuccess, onerror) {
- if (recordNumber > ext_records.length) {
- onerror("cleanEFRecord failed.");
- return;
- }
- ext_records[recordNumber] = null;
- isCleanEFRecord = true;
- onsuccess();
- }
-
- let successCb = function successCb(updatedContact) {
- equal(updatedContact.number, expectedNumber);
- };
-
- let errorCb = function errorCb(errorMsg) {
- do_print("updateADNLikeWithExtension failed, msg = " + errorMsg);
- ok(false);
- };
-
- contactHelper.updateADNLikeWithExtension(ICC_EF_ADN, ICC_EF_EXT1, contact, null, successCb, errorCb);
-
- if (expectedCleanEFRecord) {
- ok(isCleanEFRecord);
- }
- }
-
- // Update extension record with previous extension record number.
- do_test({recordId: 1, alphaId: "test", number: "001122334455667788991234"}, 0x01, 0x01, "001122334455667788991234");
- // Update extension record and find a free record.
- do_test({recordId: 1, alphaId: "test", number: "001122334455667788995678"}, 0xff, 0x02, "001122334455667788995678");
- // Update extension record with no free extension record.
- do_test({recordId: 1, alphaId: "test", number: "001122334455667788994321"}, 0xff, 0xff, "00112233445566778899");
- // Update extension record with clean previous extension record.
- do_test({recordId: 1, alphaId: "test", number: "00112233445566778899"}, 0x01, 0xff, "00112233445566778899", true);
- // Update extension record with no extension record and previous extension record.
- do_test({recordId: 1, alphaId: "test", number: "00112233445566778899"}, 0xff, 0xff, "00112233445566778899");
-
- run_next_test();
-}); \ No newline at end of file
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_ICCIOHelper.js b/dom/system/gonk/tests/test_ril_worker_icc_ICCIOHelper.js
deleted file mode 100644
index e690b1206..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_ICCIOHelper.js
+++ /dev/null
@@ -1,173 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify ICCIOHelper.loadLinearFixedEF with recordSize.
- */
-add_test(function test_load_linear_fixed_ef() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let io = context.ICCIOHelper;
-
- io.getResponse = function fakeGetResponse(options) {
- // When recordSize is provided, loadLinearFixedEF should call iccIO directly.
- ok(false);
- run_next_test();
- };
-
- ril.iccIO = function fakeIccIO(options) {
- ok(true);
- run_next_test();
- };
-
- io.loadLinearFixedEF({recordSize: 0x20});
-});
-
-/**
- * Verify ICCIOHelper.loadLinearFixedEF without recordSize.
- */
-add_test(function test_load_linear_fixed_ef() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let io = context.ICCIOHelper;
-
- io.getResponse = function fakeGetResponse(options) {
- ok(true);
- run_next_test();
- };
-
- ril.iccIO = function fakeIccIO(options) {
- // When recordSize is not provided, loadLinearFixedEF should call getResponse.
- ok(false);
- run_next_test();
- };
-
- io.loadLinearFixedEF({});
-});
-
-/**
- * Verify ICC IO Error.
- */
-add_test(function test_process_icc_io_error() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
-
- function do_test(sw1, sw2, expectedErrorMsg) {
- let called = false;
- function errorCb(errorMsg) {
- called = true;
- equal(errorMsg, expectedErrorMsg);
- }
-
- // Write sw1 and sw2 to buffer.
- buf.writeInt32(sw1);
- buf.writeInt32(sw2);
-
- context.RIL[REQUEST_SIM_IO](0, {fileId: 0xffff,
- command: 0xff,
- onerror: errorCb});
-
- // onerror callback should be triggered.
- ok(called);
- }
-
- let TEST_DATA = [
- // [sw1, sw2, expectError]
- [ICC_STATUS_ERROR_COMMAND_NOT_ALLOWED, 0xff, GECKO_ERROR_GENERIC_FAILURE],
- [ICC_STATUS_ERROR_WRONG_PARAMETERS, 0xff, GECKO_ERROR_GENERIC_FAILURE],
- ];
-
- for (let i = 0; i < TEST_DATA.length; i++) {
- do_test.apply(null, TEST_DATA[i]);
- }
-
- run_next_test();
-});
-
-/**
- * Verify ICCIOHelper.processICCIOGetResponse for EF_TYPE_TRANSPARENT.
- */
-add_test(function test_icc_io_get_response_for_transparent_structure() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let iccioHelper = context.ICCIOHelper;
- let pduHelper = context.GsmPDUHelper;
-
- let responseArray = [
- // SIM response.
- [0x00, 0x00, 0x00, 0x0A, 0x2F, 0xE2, 0x04, 0x00, 0x0A, 0xA0, 0xAA, 0x00,
- 0x02, 0x00, 0x00],
- // USIM response.
- [0x62, 0x22, 0x82, 0x02, 0x41, 0x21, 0x83, 0x02, 0x2F, 0xE2, 0xA5, 0x09,
- 0xC1, 0x04, 0x40, 0x0F, 0xF5, 0x55, 0x92, 0x01, 0x00, 0x8A, 0x01, 0x05,
- 0x8B, 0x03, 0x2F, 0x06, 0x0B, 0x80, 0x02, 0x00, 0x0A, 0x88, 0x01, 0x10]
- ];
-
- for (let i = 0; i < responseArray.length; i++) {
- let strLen = responseArray[i].length * 2;
- buf.writeInt32(strLen);
- for (let j = 0; j < responseArray[i].length; j++) {
- pduHelper.writeHexOctet(responseArray[i][j]);
- }
- buf.writeStringDelimiter(strLen);
-
- let options = {fileId: ICC_EF_ICCID,
- structure: EF_STRUCTURE_TRANSPARENT};
- iccioHelper.processICCIOGetResponse(options);
-
- equal(options.fileSize, 0x0A);
- }
-
- run_next_test();
-});
-
-/**
- * Verify ICCIOHelper.processICCIOGetResponse for EF_TYPE_LINEAR_FIXED.
- */
-add_test(function test_icc_io_get_response_for_linear_fixed_structure() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let iccioHelper = context.ICCIOHelper;
- let pduHelper = context.GsmPDUHelper;
-
- let responseArray = [
- // SIM response.
- [0x00, 0x00, 0x00, 0x1A, 0x6F, 0x40, 0x04, 0x00, 0x11, 0xA0, 0xAA, 0x00,
- 0x02, 0x01, 0x1A],
- // USIM response.
- [0x62, 0x1E, 0x82, 0x05, 0x42, 0x21, 0x00, 0x1A, 0x01, 0x83, 0x02, 0x6F,
- 0x40, 0xA5, 0x03, 0x92, 0x01, 0x00, 0x8A, 0x01, 0x07, 0x8B, 0x03, 0x6F,
- 0x06, 0x02, 0x80, 0x02, 0x00, 0x1A, 0x88, 0x00]
- ];
-
- for (let i = 0; i < responseArray.length; i++) {
- let strLen = responseArray[i].length * 2;
- buf.writeInt32(strLen);
- for (let j = 0; j < responseArray[i].length; j++) {
- pduHelper.writeHexOctet(responseArray[i][j]);
- }
- buf.writeStringDelimiter(strLen);
-
- let options = {fileId: ICC_EF_MSISDN,
- structure: EF_STRUCTURE_LINEAR_FIXED};
- iccioHelper.processICCIOGetResponse(options);
-
- equal(options.fileSize, 0x1A);
- equal(options.recordSize, 0x1A);
- equal(options.totalRecords, 0x01);
- }
-
- run_next_test();
-});
-
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_ICCPDUHelper.js b/dom/system/gonk/tests/test_ril_worker_icc_ICCPDUHelper.js
deleted file mode 100644
index 91495b1b7..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_ICCPDUHelper.js
+++ /dev/null
@@ -1,652 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify ICCPDUHelper#readICCUCS2String()
- */
-add_test(function test_read_icc_ucs2_string() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
-
- // 0x80
- let text = "TEST";
- helper.writeUCS2String(text);
- // Also write two unused octets.
- let ffLen = 2;
- for (let i = 0; i < ffLen; i++) {
- helper.writeHexOctet(0xff);
- }
- equal(iccHelper.readICCUCS2String(0x80, (2 * text.length) + ffLen), text);
-
- // 0x81
- let array = [0x08, 0xd2, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0xca,
- 0xff, 0xff];
- let len = array.length;
- for (let i = 0; i < len; i++) {
- helper.writeHexOctet(array[i]);
- }
- equal(iccHelper.readICCUCS2String(0x81, len), "Mozilla\u694a");
-
- // 0x82
- let array2 = [0x08, 0x69, 0x00, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61,
- 0xca, 0xff, 0xff];
- let len2 = array2.length;
- for (let i = 0; i < len2; i++) {
- helper.writeHexOctet(array2[i]);
- }
- equal(iccHelper.readICCUCS2String(0x82, len2), "Mozilla\u694a");
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper#writeICCUCS2String()
- */
-add_test(function test_write_icc_ucs2_string() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- let alphaLen = 18;
- let test_data = [
- {
- encode: 0x80,
- // string only contain one character.
- data: "\u82b3"
- }, {
- encode: 0x80,
- // 2 UCS2 character not located in the same half-page.
- data: "Fire \u82b3\u8233"
- }, {
- encode: 0x80,
- // 2 UCS2 character not located in the same half-page.
- data: "\u694a\u704a"
- }, {
- encode: 0x81,
- // 2 UCS2 character within same half-page.
- data: "Fire \u6901\u697f"
- }, {
- encode: 0x81,
- // 2 UCS2 character within same half-page.
- data: "Fire \u6980\u69ff"
- }, {
- encode: 0x82,
- // 2 UCS2 character within same half-page, but bit 8 is different.
- data: "Fire \u0514\u0593"
- }, {
- encode: 0x82,
- // 2 UCS2 character over 0x81 can encode range.
- data: "Fire \u8000\u8001"
- }, {
- encode: 0x82,
- // 2 UCS2 character over 0x81 can encode range.
- data: "Fire \ufffd\ufffe"
- }];
-
- for (let i = 0; i < test_data.length; i++) {
- let test = test_data[i];
- let writtenStr = iccHelper.writeICCUCS2String(alphaLen, test.data);
- equal(writtenStr, test.data);
- equal(helper.readHexOctet(), test.encode);
- equal(iccHelper.readICCUCS2String(test.encode, alphaLen - 1), test.data);
- }
-
- // This string use 0x80 encoded and the maximum capacity is 17 octets.
- // Each alphabet takes 2 octets, thus the first 8 alphabets can be written.
- let str = "Mozilla \u82b3\u8233 On Fire";
- let writtenStr = iccHelper.writeICCUCS2String(alphaLen, str);
- equal(writtenStr, str.substring(0, 8));
- equal(helper.readHexOctet(), 0x80);
- equal(iccHelper.readICCUCS2String(0x80, alphaLen - 1), str.substring(0, 8));
-
- // This string use 0x81 encoded and the maximum capacity is 15 octets.
- // Each alphabet takes 1 octets, thus the first 15 alphabets can be written.
- str = "Mozilla \u6901\u697f On Fire";
- writtenStr = iccHelper.writeICCUCS2String(alphaLen, str);
- equal(writtenStr, str.substring(0, 15));
- equal(helper.readHexOctet(), 0x81);
- equal(iccHelper.readICCUCS2String(0x81, alphaLen - 1), str.substring(0, 15));
-
- // This string use 0x82 encoded and the maximum capacity is 14 octets.
- // Each alphabet takes 1 octets, thus the first 14 alphabets can be written.
- str = "Mozilla \u0514\u0593 On Fire";
- writtenStr = iccHelper.writeICCUCS2String(alphaLen, str);
- equal(writtenStr, str.substring(0, 14));
- equal(helper.readHexOctet(), 0x82);
- equal(iccHelper.readICCUCS2String(0x82, alphaLen - 1), str.substring(0, 14));
-
- run_next_test();
-});
-/**
- * Verify ICCPDUHelper#readDiallingNumber
- */
-add_test(function test_read_dialling_number() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- let str = "123456789";
-
- helper.readHexOctet = function() {
- return 0x81;
- };
-
- helper.readSwappedNibbleExtendedBcdString = function(len) {
- return str.substring(0, len);
- };
-
- for (let i = 0; i < str.length; i++) {
- equal(str.substring(0, i - 1), // -1 for the TON
- iccHelper.readDiallingNumber(i));
- }
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper#read8BitUnpackedToString
- */
-add_test(function test_read_8bit_unpacked_to_string() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
-
- // Test 1: Read GSM alphabets.
- // Write alphabets before ESCAPE.
- for (let i = 0; i < PDU_NL_EXTENDED_ESCAPE; i++) {
- helper.writeHexOctet(i);
- }
-
- // Write two ESCAPEs to make it become ' '.
- helper.writeHexOctet(PDU_NL_EXTENDED_ESCAPE);
- helper.writeHexOctet(PDU_NL_EXTENDED_ESCAPE);
-
- for (let i = PDU_NL_EXTENDED_ESCAPE + 1; i < langTable.length; i++) {
- helper.writeHexOctet(i);
- }
-
- // Also write two unused fields.
- let ffLen = 2;
- for (let i = 0; i < ffLen; i++) {
- helper.writeHexOctet(0xff);
- }
-
- equal(iccHelper.read8BitUnpackedToString(PDU_NL_EXTENDED_ESCAPE),
- langTable.substring(0, PDU_NL_EXTENDED_ESCAPE));
- equal(iccHelper.read8BitUnpackedToString(2), " ");
- equal(iccHelper.read8BitUnpackedToString(langTable.length -
- PDU_NL_EXTENDED_ESCAPE - 1 + ffLen),
- langTable.substring(PDU_NL_EXTENDED_ESCAPE + 1));
-
- // Test 2: Read GSM extended alphabets.
- for (let i = 0; i < langShiftTable.length; i++) {
- helper.writeHexOctet(PDU_NL_EXTENDED_ESCAPE);
- helper.writeHexOctet(i);
- }
-
- // Read string before RESERVED_CONTROL.
- equal(iccHelper.read8BitUnpackedToString(PDU_NL_RESERVED_CONTROL * 2),
- langShiftTable.substring(0, PDU_NL_RESERVED_CONTROL));
- // ESCAPE + RESERVED_CONTROL will become ' '.
- equal(iccHelper.read8BitUnpackedToString(2), " ");
- // Read string between RESERVED_CONTROL and EXTENDED_ESCAPE.
- equal(iccHelper.read8BitUnpackedToString(
- (PDU_NL_EXTENDED_ESCAPE - PDU_NL_RESERVED_CONTROL - 1) * 2),
- langShiftTable.substring(PDU_NL_RESERVED_CONTROL + 1,
- PDU_NL_EXTENDED_ESCAPE));
- // ESCAPE + ESCAPE will become ' '.
- equal(iccHelper.read8BitUnpackedToString(2), " ");
- // Read remaining string.
- equal(iccHelper.read8BitUnpackedToString(
- (langShiftTable.length - PDU_NL_EXTENDED_ESCAPE - 1) * 2),
- langShiftTable.substring(PDU_NL_EXTENDED_ESCAPE + 1));
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper#writeStringTo8BitUnpacked.
- *
- * Test writing GSM 8 bit alphabets.
- */
-add_test(function test_write_string_to_8bit_unpacked() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- // Length of trailing 0xff.
- let ffLen = 2;
- let str;
-
- // Test 1, write GSM alphabets.
- let writtenStr = iccHelper.writeStringTo8BitUnpacked(langTable.length + ffLen, langTable);
- equal(writtenStr, langTable);
-
- for (let i = 0; i < langTable.length; i++) {
- equal(helper.readHexOctet(), i);
- }
-
- for (let i = 0; i < ffLen; i++) {
- equal(helper.readHexOctet(), 0xff);
- }
-
- // Test 2, write GSM extended alphabets.
- str = "\u000c\u20ac";
- writtenStr = iccHelper.writeStringTo8BitUnpacked(4, str);
- equal(writtenStr, str);
- equal(iccHelper.read8BitUnpackedToString(4), str);
-
- // Test 3, write GSM and GSM extended alphabets.
- // \u000c, \u20ac are from gsm extended alphabets.
- // \u00a3 is from gsm alphabet.
- str = "\u000c\u20ac\u00a3";
-
- // 2 octets * 2 = 4 octets for 2 gsm extended alphabets,
- // 1 octet for 1 gsm alphabet,
- // 2 octes for trailing 0xff.
- // "Totally 7 octets are to be written."
- writtenStr = iccHelper.writeStringTo8BitUnpacked(7, str);
- equal(writtenStr, str);
- equal(iccHelper.read8BitUnpackedToString(7), str);
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper#writeStringTo8BitUnpacked with maximum octets written.
- */
-add_test(function test_write_string_to_8bit_unpacked_with_max_octets_written() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
-
- // The maximum of the number of octets that can be written is 3.
- // Only 3 characters shall be written even the length of the string is 4.
- let writtenStr = iccHelper.writeStringTo8BitUnpacked(3, langTable.substring(0, 4));
- equal(writtenStr, langTable.substring(0, 3));
- helper.writeHexOctet(0xff); // dummy octet.
- for (let i = 0; i < 3; i++) {
- equal(helper.readHexOctet(), i);
- }
- ok(helper.readHexOctet() != 4);
-
- // \u000c is GSM extended alphabet, 2 octets.
- // \u00a3 is GSM alphabet, 1 octet.
- let str = "\u000c\u00a3";
- writtenStr = iccHelper.writeStringTo8BitUnpacked(3, str);
- equal(writtenStr, str.substring(0, 2));
- equal(iccHelper.read8BitUnpackedToString(3), str);
-
- str = "\u00a3\u000c";
- writtenStr = iccHelper.writeStringTo8BitUnpacked(3, str);
- equal(writtenStr, str.substring(0, 2));
- equal(iccHelper.read8BitUnpackedToString(3), str);
-
- // 2 GSM extended alphabets cost 4 octets, but maximum is 3, so only the 1st
- // alphabet can be written.
- str = "\u000c\u000c";
- writtenStr = iccHelper.writeStringTo8BitUnpacked(3, str);
- helper.writeHexOctet(0xff); // dummy octet.
- equal(writtenStr, str.substring(0, 1));
- equal(iccHelper.read8BitUnpackedToString(4), str.substring(0, 1));
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper.readAlphaIdentifier
- */
-add_test(function test_read_alpha_identifier() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
-
- // UCS2: 0x80
- let text = "TEST";
- helper.writeHexOctet(0x80);
- helper.writeUCS2String(text);
- // Also write two unused octets.
- let ffLen = 2;
- for (let i = 0; i < ffLen; i++) {
- helper.writeHexOctet(0xff);
- }
- equal(iccHelper.readAlphaIdentifier(1 + (2 * text.length) + ffLen), text);
-
- // UCS2: 0x81
- let array = [0x81, 0x08, 0xd2, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0xca, 0xff, 0xff];
- for (let i = 0; i < array.length; i++) {
- helper.writeHexOctet(array[i]);
- }
- equal(iccHelper.readAlphaIdentifier(array.length), "Mozilla\u694a");
-
- // UCS2: 0x82
- let array2 = [0x82, 0x08, 0x69, 0x00, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0xca, 0xff, 0xff];
- for (let i = 0; i < array2.length; i++) {
- helper.writeHexOctet(array2[i]);
- }
- equal(iccHelper.readAlphaIdentifier(array2.length), "Mozilla\u694a");
-
- // GSM 8 Bit Unpacked
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- for (let i = 0; i < PDU_NL_EXTENDED_ESCAPE; i++) {
- helper.writeHexOctet(i);
- }
- equal(iccHelper.readAlphaIdentifier(PDU_NL_EXTENDED_ESCAPE),
- langTable.substring(0, PDU_NL_EXTENDED_ESCAPE));
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper.writeAlphaIdentifier
- */
-add_test(function test_write_alpha_identifier() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- // Length of trailing 0xff.
- let ffLen = 2;
-
- // Removal
- let writenAlphaId = iccHelper.writeAlphaIdentifier(10, null);
- equal(writenAlphaId, "");
- equal(iccHelper.readAlphaIdentifier(10), "");
-
- // GSM 8 bit
- let str = "Mozilla";
- writenAlphaId = iccHelper.writeAlphaIdentifier(str.length + ffLen, str);
- equal(writenAlphaId , str);
- equal(iccHelper.readAlphaIdentifier(str.length + ffLen), str);
-
- // UCS2
- str = "Mozilla\u8000";
- writenAlphaId = iccHelper.writeAlphaIdentifier(str.length * 2 + ffLen, str);
- equal(writenAlphaId , str);
- // * 2 for each character will be encoded to UCS2 alphabets.
- equal(iccHelper.readAlphaIdentifier(str.length * 2 + ffLen), str);
-
- // Test with maximum octets written.
- // 1 coding scheme (0x80) and 1 UCS2 character, total 3 octets.
- str = "\u694a";
- writenAlphaId = iccHelper.writeAlphaIdentifier(3, str);
- equal(writenAlphaId , str);
- equal(iccHelper.readAlphaIdentifier(3), str);
-
- // 1 coding scheme (0x80) and 2 UCS2 characters, total 5 octets.
- // numOctets is limited to 4, so only 1 UCS2 character can be written.
- str = "\u694a\u69ca";
- writenAlphaId = iccHelper.writeAlphaIdentifier(4, str);
- helper.writeHexOctet(0xff); // dummy octet.
- equal(writenAlphaId , str.substring(0, 1));
- equal(iccHelper.readAlphaIdentifier(5), str.substring(0, 1));
-
- // Write 0 octet.
- writenAlphaId = iccHelper.writeAlphaIdentifier(0, "1");
- helper.writeHexOctet(0xff); // dummy octet.
- equal(writenAlphaId, "");
- equal(iccHelper.readAlphaIdentifier(1), "");
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper.readAlphaIdDiallingNumber
- */
-add_test(function test_read_alpha_id_dialling_number() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- let buf = context.Buf;
- const recordSize = 32;
-
- function testReadAlphaIdDiallingNumber(contact) {
- iccHelper.readAlphaIdentifier = function() {
- return contact.alphaId;
- };
-
- iccHelper.readNumberWithLength = function() {
- return contact.number;
- };
-
- let strLen = recordSize * 2;
- buf.writeInt32(strLen); // fake length
- helper.writeHexOctet(0xff); // fake CCP
- helper.writeHexOctet(0xff); // fake EXT1
- buf.writeStringDelimiter(strLen);
-
- let contactR = iccHelper.readAlphaIdDiallingNumber(recordSize);
- if (contact.alphaId == "" && contact.number == "") {
- equal(contactR, null);
- } else {
- equal(contactR.alphaId, contact.alphaId);
- equal(contactR.number, contact.number);
- }
- }
-
- testReadAlphaIdDiallingNumber({alphaId: "AlphaId", number: "0987654321"});
- testReadAlphaIdDiallingNumber({alphaId: "", number: ""});
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper.writeAlphaIdDiallingNumber
- */
-add_test(function test_write_alpha_id_dialling_number() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.ICCPDUHelper;
- const recordSize = 32;
-
- // Write a normal contact.
- let contactW = {
- alphaId: "Mozilla",
- number: "1234567890"
- };
-
- let writtenContact = helper.writeAlphaIdDiallingNumber(recordSize,
- contactW.alphaId,
- contactW.number, 0xff);
-
- let contactR = helper.readAlphaIdDiallingNumber(recordSize);
- equal(writtenContact.alphaId, contactR.alphaId);
- equal(writtenContact.number, contactR.number);
- equal(0xff, contactR.extRecordNumber);
-
- // Write a contact with alphaId encoded in UCS2 and number has '+'.
- let contactUCS2 = {
- alphaId: "火狐",
- number: "+1234567890"
- };
-
- writtenContact = helper.writeAlphaIdDiallingNumber(recordSize,
- contactUCS2.alphaId,
- contactUCS2.number, 0xff);
- contactR = helper.readAlphaIdDiallingNumber(recordSize);
- equal(writtenContact.alphaId, contactR.alphaId);
- equal(writtenContact.number, contactR.number);
- equal(0xff, contactR.extRecordNumber);
-
- // Write a null contact (Removal).
- writtenContact = helper.writeAlphaIdDiallingNumber(recordSize);
- contactR = helper.readAlphaIdDiallingNumber(recordSize);
- equal(contactR, null);
- equal(writtenContact.alphaId, "");
- equal(writtenContact.number, "");
-
- // Write a longer alphaId/dialling number
- // Dialling Number : Maximum 20 digits(10 octets).
- // Alpha Identifier: 32(recordSize) - 14 (10 octets for Dialling Number, 1
- // octet for TON/NPI, 1 for number length octet, and 2 for
- // Ext) = Maximum 18 octets.
- let longContact = {
- alphaId: "AAAAAAAAABBBBBBBBBCCCCCCCCC",
- number: "123456789012345678901234567890",
- };
-
- writtenContact = helper.writeAlphaIdDiallingNumber(recordSize,
- longContact.alphaId,
- longContact.number, 0xff);
- contactR = helper.readAlphaIdDiallingNumber(recordSize);
- equal(writtenContact.alphaId, contactR.alphaId);
- equal(writtenContact.number, contactR.number);
- equal(0xff, contactR.extRecordNumber);
-
- // Add '+' to number and test again.
- longContact.number = "+123456789012345678901234567890";
- writtenContact = helper.writeAlphaIdDiallingNumber(recordSize,
- longContact.alphaId,
- longContact.number, 0xff);
- contactR = helper.readAlphaIdDiallingNumber(recordSize);
- equal(writtenContact.alphaId, contactR.alphaId);
- equal(writtenContact.number, contactR.number);
- equal(0xff, contactR.extRecordNumber);
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper.writeDiallingNumber
- */
-add_test(function test_write_dialling_number() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.ICCPDUHelper;
-
- // with +
- let number = "+123456";
- let len = 4;
- helper.writeDiallingNumber(number);
- equal(helper.readDiallingNumber(len), number);
-
- // without +
- number = "987654";
- len = 4;
- helper.writeDiallingNumber(number);
- equal(helper.readDiallingNumber(len), number);
-
- number = "9876543";
- len = 5;
- helper.writeDiallingNumber(number);
- equal(helper.readDiallingNumber(len), number);
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper.readNumberWithLength
- */
-add_test(function test_read_number_with_length() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
-
- let numbers = [
- {
- number: "123456789",
- expectedNumber: "123456789"
- },
- {
- number: "",
- expectedNumber: ""
- },
- // Invalid length of BCD number/SSC contents
- {
- number: "12345678901234567890123",
- expectedNumber: ""
- },
- ];
-
- // To avoid obtaining wrong buffer content.
- context.Buf.seekIncoming = function(offset) {
- };
-
- function do_test(aNumber, aExpectedNumber) {
- iccHelper.readDiallingNumber = function(numLen) {
- return aNumber.substring(0, numLen);
- };
-
- if (aNumber) {
- helper.writeHexOctet(aNumber.length + 1);
- } else {
- helper.writeHexOctet(0xff);
- }
-
- equal(iccHelper.readNumberWithLength(), aExpectedNumber);
- }
-
- for (let i = 0; i < numbers.length; i++) {
- do_test(numbers[i].number, numbers[i].expectedNumber);
- }
-
- run_next_test();
-});
-
-/**
- * Verify ICCPDUHelper.writeNumberWithLength
- */
-add_test(function test_write_number_with_length() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
-
- function test(number, expectedNumber) {
- expectedNumber = expectedNumber || number;
- let writeNumber = iccHelper.writeNumberWithLength(number);
- equal(writeNumber, expectedNumber);
- let numLen = helper.readHexOctet();
- equal(expectedNumber, iccHelper.readDiallingNumber(numLen));
- for (let i = 0; i < (ADN_MAX_BCD_NUMBER_BYTES - numLen); i++) {
- equal(0xff, helper.readHexOctet());
- }
- }
-
- // without +
- test("123456789");
-
- // with +
- test("+987654321");
-
- // extended BCD coding
- test("1*2#3,4*5#6,");
-
- // with + and extended BCD coding
- test("+1*2#3,4*5#6,");
-
- // non-supported characters should not be written.
- test("(1)23-456+789", "123456789");
-
- test("++(01)2*3-4#5,6+7(8)9*0#1,", "+012*34#5,6789*0#1,");
-
- // over maximum 20 digits should be truncated.
- test("012345678901234567890123456789", "01234567890123456789");
-
- // null
- iccHelper.writeNumberWithLength(null);
- for (let i = 0; i < (ADN_MAX_BCD_NUMBER_BYTES + 1); i++) {
- equal(0xff, helper.readHexOctet());
- }
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_ICCRecordHelper.js b/dom/system/gonk/tests/test_ril_worker_icc_ICCRecordHelper.js
deleted file mode 100644
index 00c55873d..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_ICCRecordHelper.js
+++ /dev/null
@@ -1,1080 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify ICCRecordHelper.readPBR
- */
-add_test(function test_read_pbr() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let record = context.ICCRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- let pbr_1 = [
- 0xa8, 0x05, 0xc0, 0x03, 0x4f, 0x3a, 0x01
- ];
-
- // Write data size
- buf.writeInt32(pbr_1.length * 2);
-
- // Write pbr
- for (let i = 0; i < pbr_1.length; i++) {
- helper.writeHexOctet(pbr_1[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(pbr_1.length * 2);
-
- options.totalRecords = 2;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- io.loadNextRecord = function fakeLoadNextRecord(options) {
- let pbr_2 = [
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
- ];
-
- options.p1++;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let successCb = function successCb(pbrs) {
- equal(pbrs[0].adn.fileId, 0x4f3a);
- equal(pbrs.length, 1);
- };
-
- let errorCb = function errorCb(errorMsg) {
- do_print("Reading EF_PBR failed, msg = " + errorMsg);
- ok(false);
- };
-
- record.readPBR(successCb, errorCb);
-
- // Check cache pbrs when 2nd call
- let ifLoadEF = false;
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- ifLoadEF = true;
- }
- record.readPBR(successCb, errorCb);
- ok(!ifLoadEF);
-
- run_next_test();
-});
-
-/**
- * Verify ICCRecordHelper.readEmail
- */
-add_test(function test_read_email() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let record = context.ICCRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
- let recordSize;
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- let email_1 = [
- 0x65, 0x6D, 0x61, 0x69, 0x6C,
- 0x00, 0x6D, 0x6F, 0x7A, 0x69,
- 0x6C, 0x6C, 0x61, 0x2E, 0x63,
- 0x6F, 0x6D, 0x02, 0x23];
-
- // Write data size
- buf.writeInt32(email_1.length * 2);
-
- // Write email
- for (let i = 0; i < email_1.length; i++) {
- helper.writeHexOctet(email_1[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(email_1.length * 2);
-
- recordSize = email_1.length;
- options.recordSize = recordSize;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- function doTestReadEmail(type, expectedResult) {
- let fileId = 0x6a75;
- let recordNumber = 1;
-
- // fileId and recordNumber are dummy arguments.
- record.readEmail(fileId, type, recordNumber, function(email) {
- equal(email, expectedResult);
- });
- };
-
- doTestReadEmail(ICC_USIM_TYPE1_TAG, "email@mozilla.com$#");
- doTestReadEmail(ICC_USIM_TYPE2_TAG, "email@mozilla.com");
- equal(record._emailRecordSize, recordSize);
-
- run_next_test();
-});
-
-/**
- * Verify ICCRecordHelper.updateEmail
- */
-add_test(function test_update_email() {
- const recordSize = 0x20;
- const recordNumber = 1;
- const fileId = 0x4f50;
- const NUM_TESTS = 2;
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- let ril = context.RIL;
- ril.appType = CARD_APPTYPE_USIM;
- let recordHelper = context.ICCRecordHelper;
- let buf = context.Buf;
- let ioHelper = context.ICCIOHelper;
- let pbr = {email: {fileId: fileId, fileType: ICC_USIM_TYPE1_TAG},
- adn: {sfi: 1}};
- let count = 0;
-
- // Override.
- ioHelper.updateLinearFixedEF = function(options) {
- options.pathId = context.ICCFileHelper.getEFPath(options.fileId);
- options.command = ICC_COMMAND_UPDATE_RECORD;
- options.p1 = options.recordNumber;
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = recordSize;
- ril.iccIO(options);
- };
-
- function do_test(pbr, expectedEmail, expectedAdnRecordId) {
- buf.sendParcel = function() {
- count++;
-
- // Request Type.
- equal(this.readInt32(), REQUEST_SIM_IO);
-
- // Token : we don't care
- this.readInt32();
-
- // command.
- equal(this.readInt32(), ICC_COMMAND_UPDATE_RECORD);
-
- // fileId.
- equal(this.readInt32(), fileId);
-
- // pathId.
- equal(this.readString(),
- EF_PATH_MF_SIM + EF_PATH_DF_TELECOM + EF_PATH_DF_PHONEBOOK);
-
- // p1.
- equal(this.readInt32(), recordNumber);
-
- // p2.
- equal(this.readInt32(), READ_RECORD_ABSOLUTE_MODE);
-
- // p3.
- equal(this.readInt32(), recordSize);
-
- // data.
- let strLen = this.readInt32();
- let email;
- if (pbr.email.fileType === ICC_USIM_TYPE1_TAG) {
- email = iccHelper.read8BitUnpackedToString(recordSize);
- } else {
- email = iccHelper.read8BitUnpackedToString(recordSize - 2);
- equal(pduHelper.readHexOctet(), pbr.adn.sfi);
- equal(pduHelper.readHexOctet(), expectedAdnRecordId);
- }
- this.readStringDelimiter(strLen);
- equal(email, expectedEmail);
-
- // pin2.
- equal(this.readString(), null);
-
- // AID. Ignore because it's from modem.
- this.readInt32();
-
- if (count == NUM_TESTS) {
- run_next_test();
- }
- };
- recordHelper.updateEmail(pbr, recordNumber, expectedEmail, expectedAdnRecordId);
- }
-
- do_test(pbr, "test@mail.com");
- pbr.email.fileType = ICC_USIM_TYPE2_TAG;
- do_test(pbr, "test@mail.com", 1);
-});
-
-/**
- * Verify ICCRecordHelper.readANR
- */
-add_test(function test_read_anr() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let record = context.ICCRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
- let recordSize;
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- let anr_1 = [
- 0x01, 0x05, 0x81, 0x10, 0x32,
- 0x54, 0xF6, 0xFF, 0xFF];
-
- // Write data size
- buf.writeInt32(anr_1.length * 2);
-
- // Write anr
- for (let i = 0; i < anr_1.length; i++) {
- helper.writeHexOctet(anr_1[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(anr_1.length * 2);
-
- recordSize = anr_1.length;
- options.recordSize = recordSize;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- function doTestReadAnr(fileType, expectedResult) {
- let fileId = 0x4f11;
- let recordNumber = 1;
-
- // fileId and recordNumber are dummy arguments.
- record.readANR(fileId, fileType, recordNumber, function(anr) {
- equal(anr, expectedResult);
- });
- };
-
- doTestReadAnr(ICC_USIM_TYPE1_TAG, "0123456");
- equal(record._anrRecordSize, recordSize);
-
- run_next_test();
-});
-
-/**
- * Verify ICCRecordHelper.updateANR
- */
-add_test(function test_update_anr() {
- const recordSize = 0x20;
- const recordNumber = 1;
- const fileId = 0x4f11;
- const NUM_TESTS = 2;
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
- let ril = context.RIL;
- ril.appType = CARD_APPTYPE_USIM;
- let recordHelper = context.ICCRecordHelper;
- let buf = context.Buf;
- let ioHelper = context.ICCIOHelper;
- let pbr = {anr0: {fileId: fileId, fileType: ICC_USIM_TYPE1_TAG},
- adn: {sfi: 1}};
- let count = 0;
-
- // Override.
- ioHelper.updateLinearFixedEF = function(options) {
- options.pathId = context.ICCFileHelper.getEFPath(options.fileId);
- options.command = ICC_COMMAND_UPDATE_RECORD;
- options.p1 = options.recordNumber;
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = recordSize;
- ril.iccIO(options);
- };
-
- function do_test(pbr, expectedANR, expectedAdnRecordId) {
- buf.sendParcel = function() {
- count++;
-
- // Request Type.
- equal(this.readInt32(), REQUEST_SIM_IO);
-
- // Token : we don't care
- this.readInt32();
-
- // command.
- equal(this.readInt32(), ICC_COMMAND_UPDATE_RECORD);
-
- // fileId.
- equal(this.readInt32(), fileId);
-
- // pathId.
- equal(this.readString(),
- EF_PATH_MF_SIM + EF_PATH_DF_TELECOM + EF_PATH_DF_PHONEBOOK);
-
- // p1.
- equal(this.readInt32(), recordNumber);
-
- // p2.
- equal(this.readInt32(), READ_RECORD_ABSOLUTE_MODE);
-
- // p3.
- equal(this.readInt32(), recordSize);
-
- // data.
- let strLen = this.readInt32();
- // EF_AAS, ignore.
- pduHelper.readHexOctet();
- equal(iccHelper.readNumberWithLength(), expectedANR);
- // EF_CCP, ignore.
- pduHelper.readHexOctet();
- // EF_EXT1, ignore.
- pduHelper.readHexOctet();
- if (pbr.anr0.fileType === ICC_USIM_TYPE2_TAG) {
- equal(pduHelper.readHexOctet(), pbr.adn.sfi);
- equal(pduHelper.readHexOctet(), expectedAdnRecordId);
- }
- this.readStringDelimiter(strLen);
-
- // pin2.
- equal(this.readString(), null);
-
- // AID. Ignore because it's from modem.
- this.readInt32();
-
- if (count == NUM_TESTS) {
- run_next_test();
- }
- };
- recordHelper.updateANR(pbr, recordNumber, expectedANR, expectedAdnRecordId);
- }
-
- do_test(pbr, "+123456789");
- pbr.anr0.fileType = ICC_USIM_TYPE2_TAG;
- do_test(pbr, "123456789", 1);
-});
-
-/**
- * Verify ICCRecordHelper.readIAP
- */
-add_test(function test_read_iap() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let record = context.ICCRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
- let recordSize;
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- let iap_1 = [0x01, 0x02];
-
- // Write data size/
- buf.writeInt32(iap_1.length * 2);
-
- // Write iap.
- for (let i = 0; i < iap_1.length; i++) {
- helper.writeHexOctet(iap_1[i]);
- }
-
- // Write string delimiter.
- buf.writeStringDelimiter(iap_1.length * 2);
-
- recordSize = iap_1.length;
- options.recordSize = recordSize;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- function doTestReadIAP(expectedIAP) {
- const fileId = 0x4f17;
- const recordNumber = 1;
-
- let successCb = function successCb(iap) {
- for (let i = 0; i < iap.length; i++) {
- equal(expectedIAP[i], iap[i]);
- }
- run_next_test();
- }.bind(this);
-
- let errorCb = function errorCb(errorMsg) {
- do_print(errorMsg);
- ok(false);
- run_next_test();
- }.bind(this);
-
- record.readIAP(fileId, recordNumber, successCb, errorCb);
- };
-
- doTestReadIAP([1, 2]);
-});
-
-/**
- * Verify ICCRecordHelper.updateIAP
- */
-add_test(function test_update_iap() {
- const recordSize = 2;
- const recordNumber = 1;
- const fileId = 0x4f17;
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let ril = context.RIL;
- ril.appType = CARD_APPTYPE_USIM;
- let recordHelper = context.ICCRecordHelper;
- let buf = context.Buf;
- let ioHelper = context.ICCIOHelper;
- let count = 0;
-
- // Override.
- ioHelper.updateLinearFixedEF = function(options) {
- options.pathId = context.ICCFileHelper.getEFPath(options.fileId);
- options.command = ICC_COMMAND_UPDATE_RECORD;
- options.p1 = options.recordNumber;
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = recordSize;
- ril.iccIO(options);
- };
-
- function do_test(expectedIAP) {
- buf.sendParcel = function() {
- // Request Type.
- equal(this.readInt32(), REQUEST_SIM_IO);
-
- // Token : we don't care
- this.readInt32();
-
- // command.
- equal(this.readInt32(), ICC_COMMAND_UPDATE_RECORD);
-
- // fileId.
- equal(this.readInt32(), fileId);
-
- // pathId.
- equal(this.readString(),
- EF_PATH_MF_SIM + EF_PATH_DF_TELECOM + EF_PATH_DF_PHONEBOOK);
-
- // p1.
- equal(this.readInt32(), recordNumber);
-
- // p2.
- equal(this.readInt32(), READ_RECORD_ABSOLUTE_MODE);
-
- // p3.
- equal(this.readInt32(), recordSize);
-
- // data.
- let strLen = this.readInt32();
- for (let i = 0; i < recordSize; i++) {
- equal(expectedIAP[i], pduHelper.readHexOctet());
- }
- this.readStringDelimiter(strLen);
-
- // pin2.
- equal(this.readString(), null);
-
- // AID. Ignore because it's from modem.
- this.readInt32();
-
- run_next_test();
- };
- recordHelper.updateIAP(fileId, recordNumber, expectedIAP);
- }
-
- do_test([1, 2]);
-});
-
-/**
- * Verify ICCRecordHelper.readADNLike.
- */
-add_test(function test_read_adn_like() {
- const RECORD_SIZE = 0x20;
-
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let record = context.ICCRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
- let ril = context.RIL;
-
- function do_test(extFileId, rawEF, expectedExtRecordNumber, expectedNumber) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(rawEF.length * 2);
-
- // Write adn
- for (let i = 0; i < rawEF.length; i += 2) {
- helper.writeHexOctet(parseInt(rawEF.substr(i, 2), 16));
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(rawEF.length * 2);
-
- options.p1 = 1;
- options.recordSize = RECORD_SIZE;
- options.totalRecords = 1;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- record.readExtension = function(fileId, recordNumber, onsuccess, onerror) {
- onsuccess("1234");
- }
-
- let successCb = function successCb(contacts) {
- ok(contacts[0].number == expectedNumber);
- };
-
- let errorCb = function errorCb(errorMsg) {
- do_print("Reading ADNLike failed, msg = " + errorMsg);
- ok(false);
- };
-
- record.readADNLike(ICC_EF_ADN, extFileId, successCb, errorCb);
- }
-
- ril.appType = CARD_APPTYPE_SIM;
- // Valid extension
- do_test(ICC_EF_EXT1,"436f6e74616374303031ffffffffffffffff0b8199887766554433221100ff01",
- 0x01,"998877665544332211001234");
- // Empty extension
- do_test(ICC_EF_EXT1,"436f6e74616374303031ffffffffffffffff0b8199887766554433221100ffff",
- 0xff, "99887766554433221100");
- // Unsupport extension
- do_test(null,"436f6e74616374303031ffffffffffffffff0b8199887766554433221100ffff",
- 0xff, "99887766554433221100");
- // Empty dialling number contact
- do_test(null,"436f6e74616374303031ffffffffffffffffffffffffffffffffffffffffffff",
- 0xff, "");
-
- run_next_test();
-});
-
-/**
- * Verify ICCRecordHelper.updateADNLike.
- */
-add_test(function test_update_adn_like() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let record = context.ICCRecordHelper;
- let io = context.ICCIOHelper;
- let pdu = context.ICCPDUHelper;
- let buf = context.Buf;
-
- ril.appType = CARD_APPTYPE_SIM;
- const recordSize = 0x20;
- let fileId;
-
- // Override.
- io.updateLinearFixedEF = function(options) {
- options.pathId = context.ICCFileHelper.getEFPath(options.fileId);
- options.command = ICC_COMMAND_UPDATE_RECORD;
- options.p1 = options.recordNumber;
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = recordSize;
- ril.iccIO(options);
- };
-
- buf.sendParcel = function() {
- // Request Type.
- equal(this.readInt32(), REQUEST_SIM_IO);
-
- // Token : we don't care
- this.readInt32();
-
- // command.
- equal(this.readInt32(), ICC_COMMAND_UPDATE_RECORD);
-
- // fileId.
- equal(this.readInt32(), fileId);
-
- // pathId.
- equal(this.readString(), EF_PATH_MF_SIM + EF_PATH_DF_TELECOM);
-
- // p1.
- equal(this.readInt32(), 1);
-
- // p2.
- equal(this.readInt32(), READ_RECORD_ABSOLUTE_MODE);
-
- // p3.
- equal(this.readInt32(), 0x20);
-
- // data.
- let contact = pdu.readAlphaIdDiallingNumber(0x20);
- equal(contact.alphaId, "test");
- equal(contact.number, "123456");
- equal(contact.extRecordNumber, "0xff");
-
- // pin2.
- if (fileId == ICC_EF_ADN) {
- equal(this.readString(), null);
- } else {
- equal(this.readString(), "1111");
- }
-
- // AID. Ignore because it's from modem.
- this.readInt32();
-
- if (fileId == ICC_EF_FDN) {
- run_next_test();
- }
- };
-
- fileId = ICC_EF_ADN;
- record.updateADNLike(fileId, 0xff,
- {recordId: 1, alphaId: "test", number: "123456"});
-
- fileId = ICC_EF_FDN;
- record.updateADNLike(fileId, 0xff,
- {recordId: 1, alphaId: "test", number: "123456"},
- "1111");
-});
-
-/**
- * Verify ICCRecordHelper.findFreeRecordId.
- */
-add_test(function test_find_free_record_id() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let recordHelper = context.ICCRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
- let ril = context.RIL;
-
- function writeRecord(record) {
- // Write data size
- buf.writeInt32(record.length * 2);
-
- for (let i = 0; i < record.length; i++) {
- pduHelper.writeHexOctet(record[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(record.length * 2);
- }
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Some random data.
- let record = [0x12, 0x34, 0x56, 0x78, 0x90];
- options.p1 = 1;
- options.totalRecords = 2;
- writeRecord(record);
- if (options.callback) {
- options.callback(options);
- }
- };
-
- ril.iccIO = function fakeIccIO(options) {
- // Unused bytes.
- let record = [0xff, 0xff, 0xff, 0xff, 0xff];
- writeRecord(record);
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let fileId = 0x0000; // Dummy.
- recordHelper.findFreeRecordId(
- fileId,
- function(recordId) {
- equal(recordId, 2);
- run_next_test();
- }.bind(this),
- function(errorMsg) {
- do_print(errorMsg);
- ok(false);
- run_next_test();
- }.bind(this));
-});
-
-/**
- * Verify ICCRecordHelper.fetchICCRecords.
- */
-add_test(function test_fetch_icc_recodes() {
- let worker = newWorker();
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let iccRecord = context.ICCRecordHelper;
- let simRecord = context.SimRecordHelper;
- let ruimRecord = context.RuimRecordHelper;
- let fetchTag = 0x00;
-
- simRecord.fetchSimRecords = function() {
- fetchTag = 0x01;
- };
-
- ruimRecord.fetchRuimRecords = function() {
- fetchTag = 0x02;
- };
-
- RIL.appType = CARD_APPTYPE_SIM;
- iccRecord.fetchICCRecords();
- equal(fetchTag, 0x01);
-
- RIL.appType = CARD_APPTYPE_RUIM;
- iccRecord.fetchICCRecords();
- equal(fetchTag, 0x02);
-
- RIL.appType = CARD_APPTYPE_USIM;
- iccRecord.fetchICCRecords();
- equal(fetchTag, 0x01);
-
- run_next_test();
-});
-
-/**
- * Verify reading EF_ICCID.
- */
-add_test(function test_handling_iccid() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.ICCRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- ril.reportStkServiceIsRunning = function fakeReportStkServiceIsRunning() {
- };
-
- function do_test(rawICCID, expectedICCID) {
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(rawICCID.length);
-
- // Write data
- for (let i = 0; i < rawICCID.length; i += 2) {
- helper.writeHexOctet(parseInt(rawICCID.substr(i, 2), 16));
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(rawICCID.length);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- record.readICCID();
-
- equal(ril.iccInfo.iccid, expectedICCID);
- }
-
- // Invalid value 0xE at high nibbile + low nibbile contains 0xF.
- do_test("9868002E90909F001519", "89860020909");
- // Invalid value 0xD at low nibbile.
- do_test("986800D2909090001519", "8986002090909005191");
- // Invalid value 0xC at low nibbile.
- do_test("986800C2909090001519", "8986002090909005191");
- // Invalid value 0xB at low nibbile.
- do_test("986800B2909090001519", "8986002090909005191");
- // Invalid value 0xA at low nibbile.
- do_test("986800A2909090001519", "8986002090909005191");
- // Valid ICCID.
- do_test("98101430121181157002", "89014103211118510720");
-
- run_next_test();
-});
-
-/**
- * Verify ICCRecordHelper.readExtension
- */
-add_test(function test_read_extension() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let record = context.ICCRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- function do_test(rawExtension, expectedExtensionNumber) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(rawExtension.length * 2);
-
- // Write ext
- for (let i = 0; i < rawExtension.length; i += 2) {
- helper.writeHexOctet(parseInt(rawExtension.substr(i, 2), 16));
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(rawExtension.length);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let successCb = function successCb(number) {
- do_print("extension number:" + number);
- equal(number, expectedExtensionNumber);
- };
-
- let errorCb = function errorCb() {
- ok(expectedExtensionNumber == null);
- };
-
- record.readExtension(0x6f4a, 1, successCb, errorCb);
- }
-
- // Test unsupported record type 0x01
- do_test("010a10325476981032547698ff", "");
- // Test invalid length 0xc1
- do_test("020c10325476981032547698ff", null);
- // Test extension chain which we don't support
- do_test("020a1032547698103254769802", "01234567890123456789");
- // Test valid Extension
- do_test("020a10325476981032547698ff", "01234567890123456789");
- // Test valid Extension
- do_test("0209103254769810325476ffff", "012345678901234567");
- // Test empty Extension
- do_test("02ffffffffffffffffffffffff", "");
-
- run_next_test();
-});
-
-/**
- * Verify ICCRecordHelper.updateExtension
- */
-add_test(function test_update_extension() {
- const RECORD_SIZE = 13;
- const RECORD_NUMBER = 1;
-
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let ril = context.RIL;
- let recordHelper = context.ICCRecordHelper;
- let buf = context.Buf;
- let ioHelper = context.ICCIOHelper;
-
- // Override.
- ioHelper.updateLinearFixedEF = function(options) {
- options.pathId = context.ICCFileHelper.getEFPath(options.fileId);
- options.command = ICC_COMMAND_UPDATE_RECORD;
- options.p1 = options.recordNumber;
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = RECORD_SIZE;
- ril.iccIO(options);
- };
-
- function do_test(fileId, number, expectedNumber) {
- buf.sendParcel = function() {
- // Request Type.
- equal(this.readInt32(), REQUEST_SIM_IO);
-
- // Token : we don't care
- this.readInt32();
-
- // command.
- equal(this.readInt32(), ICC_COMMAND_UPDATE_RECORD);
-
- // fileId.
- equal(this.readInt32(), fileId);
-
- // pathId.
- if (ril.appType == CARD_APPTYPE_SIM || ril.appType == CARD_APPTYPE_RUIM) {
- equal(this.readString(),
- EF_PATH_MF_SIM + EF_PATH_DF_TELECOM);
- } else{
- equal(this.readString(),
- EF_PATH_MF_SIM + EF_PATH_DF_TELECOM + EF_PATH_DF_PHONEBOOK);
- }
-
- // p1.
- equal(this.readInt32(), RECORD_NUMBER);
-
- // p2.
- equal(this.readInt32(), READ_RECORD_ABSOLUTE_MODE);
-
- // p3.
- equal(this.readInt32(), RECORD_SIZE);
-
- // data.
- let strLen = this.readInt32();
- // Extension record
- let recordType = pduHelper.readHexOctet();
-
- equal(recordType, 0x02);
- equal(pduHelper.readHexOctet(), 10);
- equal(
- pduHelper.readSwappedNibbleExtendedBcdString(EXT_MAX_NUMBER_DIGITS - 1),
- expectedNumber);
-
- this.readStringDelimiter(strLen);
-
- // pin2.
- equal(this.readString(), null);
-
- // AID. Ignore because it's from modem.
- this.readInt32();
- };
-
- recordHelper.updateExtension(fileId, RECORD_NUMBER, number);
- }
-
- ril.appType = CARD_APPTYPE_SIM;
- do_test(ICC_EF_EXT1, "01234567890123456789", "01234567890123456789");
- // We don't support extension chain.
- do_test(ICC_EF_EXT1, "012345678901234567891234", "01234567890123456789");
-
- ril.appType = CARD_APPTYPE_USIM;
- do_test(ICC_EF_EXT1, "01234567890123456789", "01234567890123456789");
-
- ril.appType = CARD_APPTYPE_RUIM;
- do_test(ICC_EF_EXT1, "01234567890123456789", "01234567890123456789");
-
- run_next_test();
-});
-
-/**
- * Verify ICCRecordHelper.cleanEFRecord
- */
-add_test(function test_clean_ef_record() {
- const RECORD_SIZE = 13;
- const RECORD_NUMBER = 1;
-
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let ril = context.RIL;
- let recordHelper = context.ICCRecordHelper;
- let buf = context.Buf;
- let ioHelper = context.ICCIOHelper;
-
- // Override.
- ioHelper.updateLinearFixedEF = function(options) {
- options.pathId = context.ICCFileHelper.getEFPath(options.fileId);
- options.command = ICC_COMMAND_UPDATE_RECORD;
- options.p1 = options.recordNumber;
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = RECORD_SIZE;
- ril.iccIO(options);
- };
-
- function do_test(fileId) {
- buf.sendParcel = function() {
- // Request Type.
- equal(this.readInt32(), REQUEST_SIM_IO);
-
- // Token : we don't care
- this.readInt32();
-
- // command.
- equal(this.readInt32(), ICC_COMMAND_UPDATE_RECORD);
-
- // fileId.
- equal(this.readInt32(), fileId);
-
- // pathId.
- if (ril.appType == CARD_APPTYPE_SIM || ril.appType == CARD_APPTYPE_RUIM) {
- equal(this.readString(),
- EF_PATH_MF_SIM + EF_PATH_DF_TELECOM);
- } else{
- equal(this.readString(),
- EF_PATH_MF_SIM + EF_PATH_DF_TELECOM + EF_PATH_DF_PHONEBOOK);
- }
-
- // p1.
- equal(this.readInt32(), RECORD_NUMBER);
-
- // p2.
- equal(this.readInt32(), READ_RECORD_ABSOLUTE_MODE);
-
- // p3.
- equal(this.readInt32(), RECORD_SIZE);
-
- // data.
- let strLen = this.readInt32();
- // Extension record
- for (let i = 0; i < RECORD_SIZE; i++) {
- equal(pduHelper.readHexOctet(), 0xff);
- }
-
- this.readStringDelimiter(strLen);
-
- // pin2.
- equal(this.readString(), null);
-
- // AID. Ignore because it's from modem.
- this.readInt32();
- };
-
- recordHelper.cleanEFRecord(fileId, RECORD_NUMBER);
- }
-
- ril.appType = CARD_APPTYPE_SIM;
- do_test(ICC_EF_EXT1);
-
- run_next_test();
-});
-
-/**
- * Verify ICCRecordHelper.getADNLikeExtensionRecordNumber
- */
-add_test(function test_get_adn_like_extension_record_number() {
- const RECORD_SIZE = 0x20;
-
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let record = context.ICCRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- function do_test(rawEF, expectedRecordNumber) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(rawEF.length * 2);
-
- // Write ext
- for (let i = 0; i < rawEF.length; i += 2) {
- helper.writeHexOctet(parseInt(rawEF.substr(i, 2), 16));
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(rawEF.length);
- options.recordSize = RECORD_SIZE;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let isSuccess = false;
- let successCb = function successCb(number) {
- equal(number, expectedRecordNumber);
- isSuccess = true;
- };
-
- let errorCb = function errorCb(errorMsg) {
- do_print("Reading ADNLike failed, msg = " + errorMsg);
- ok(false);
- };
-
- record.getADNLikeExtensionRecordNumber(ICC_EF_ADN, 1, successCb, errorCb);
- ok(isSuccess);
- }
-
- // Valid Extension, Alpha Id(Encoded with GSM 8 bit): "Contact001",
- // Dialling Number: 99887766554433221100, Ext1: 0x01
- do_test("436f6e74616374303031ffffffffffffffff0b8199887766554433221100ff01", 0x01);
- // Empty Extension, Alpha Id(Encoded with GSM 8 bit): "Contact001", Ext1: 0xff
- do_test("436f6e74616374303031ffffffffffffffffffffffffffffffffffffffffffff", 0xff);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_ICCUtilsHelper.js b/dom/system/gonk/tests/test_ril_worker_icc_ICCUtilsHelper.js
deleted file mode 100644
index b23d0b598..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_ICCUtilsHelper.js
+++ /dev/null
@@ -1,326 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify ICCUtilsHelper.isICCServiceAvailable.
- */
-add_test(function test_is_icc_service_available() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ICCUtilsHelper = context.ICCUtilsHelper;
- let RIL = context.RIL;
-
- function test_table(sst, geckoService, simEnabled, usimEnabled) {
- RIL.iccInfoPrivate.sst = sst;
- RIL.appType = CARD_APPTYPE_SIM;
- equal(ICCUtilsHelper.isICCServiceAvailable(geckoService), simEnabled);
- RIL.appType = CARD_APPTYPE_USIM;
- equal(ICCUtilsHelper.isICCServiceAvailable(geckoService), usimEnabled);
- }
-
- test_table([0x08], "ADN", true, false);
- test_table([0x08], "FDN", false, false);
- test_table([0x08], "SDN", false, true);
-
- run_next_test();
-});
-
-/**
- * Verify ICCUtilsHelper.isGsm8BitAlphabet
- */
-add_test(function test_is_gsm_8bit_alphabet() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ICCUtilsHelper = context.ICCUtilsHelper;
- const langTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- const langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
-
- equal(ICCUtilsHelper.isGsm8BitAlphabet(langTable), true);
- equal(ICCUtilsHelper.isGsm8BitAlphabet(langShiftTable), true);
- equal(ICCUtilsHelper.isGsm8BitAlphabet("\uaaaa"), false);
-
- run_next_test();
-});
-
-/**
- * Verify ICCUtilsHelper.parsePbrTlvs
- */
-add_test(function test_parse_pbr_tlvs() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
-
- let pbrTlvs = [
- {tag: ICC_USIM_TYPE1_TAG,
- length: 0x0F,
- value: [{tag: ICC_USIM_EFADN_TAG,
- length: 0x03,
- value: [0x4F, 0x3A, 0x02]},
- {tag: ICC_USIM_EFIAP_TAG,
- length: 0x03,
- value: [0x4F, 0x25, 0x01]},
- {tag: ICC_USIM_EFPBC_TAG,
- length: 0x03,
- value: [0x4F, 0x09, 0x04]}]
- },
- {tag: ICC_USIM_TYPE2_TAG,
- length: 0x05,
- value: [{tag: ICC_USIM_EFEMAIL_TAG,
- length: 0x03,
- value: [0x4F, 0x50, 0x0B]},
- {tag: ICC_USIM_EFANR_TAG,
- length: 0x03,
- value: [0x4F, 0x11, 0x02]},
- {tag: ICC_USIM_EFANR_TAG,
- length: 0x03,
- value: [0x4F, 0x12, 0x03]}]
- },
- {tag: ICC_USIM_TYPE3_TAG,
- length: 0x0A,
- value: [{tag: ICC_USIM_EFCCP1_TAG,
- length: 0x03,
- value: [0x4F, 0x3D, 0x0A]},
- {tag: ICC_USIM_EFEXT1_TAG,
- length: 0x03,
- value: [0x4F, 0x4A, 0x03]}]
- },
- ];
-
- let pbr = context.ICCUtilsHelper.parsePbrTlvs(pbrTlvs);
- equal(pbr.adn.fileId, 0x4F3a);
- equal(pbr.iap.fileId, 0x4F25);
- equal(pbr.pbc.fileId, 0x4F09);
- equal(pbr.email.fileId, 0x4F50);
- equal(pbr.anr0.fileId, 0x4f11);
- equal(pbr.anr1.fileId, 0x4f12);
- equal(pbr.ccp1.fileId, 0x4F3D);
- equal(pbr.ext1.fileId, 0x4F4A);
-
- run_next_test();
-});
-
-/**
- * Verify MCC and MNC parsing
- */
-add_test(function test_mcc_mnc_parsing() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.ICCUtilsHelper;
-
- function do_test(imsi, mncLength, expectedMcc, expectedMnc) {
- let result = helper.parseMccMncFromImsi(imsi, mncLength);
-
- if (!imsi) {
- equal(result, null);
- return;
- }
-
- equal(result.mcc, expectedMcc);
- equal(result.mnc, expectedMnc);
- }
-
- // Test the imsi is null.
- do_test(null, null, null, null);
-
- // Test MCC is Taiwan
- do_test("466923202422409", 0x02, "466", "92");
- do_test("466923202422409", 0x03, "466", "923");
- do_test("466923202422409", null, "466", "92");
-
- // Test MCC is US
- do_test("310260542718417", 0x02, "310", "26");
- do_test("310260542718417", 0x03, "310", "260");
- do_test("310260542718417", null, "310", "260");
-
- run_next_test();
-});
-
-add_test(function test_get_network_name_from_icc() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let ICCUtilsHelper = context.ICCUtilsHelper;
-
- function testGetNetworkNameFromICC(operatorData, expectedResult) {
- let result = ICCUtilsHelper.getNetworkNameFromICC(operatorData.mcc,
- operatorData.mnc,
- operatorData.lac);
-
- if (expectedResult == null) {
- equal(result, expectedResult);
- } else {
- equal(result.fullName, expectedResult.longName);
- equal(result.shortName, expectedResult.shortName);
- }
- }
-
- // Before EF_OPL and EF_PNN have been loaded.
- testGetNetworkNameFromICC({mcc: "123", mnc: "456", lac: 0x1000}, null);
- testGetNetworkNameFromICC({mcc: "321", mnc: "654", lac: 0x2000}, null);
-
- // Set HPLMN
- RIL.iccInfo.mcc = "123";
- RIL.iccInfo.mnc = "456";
-
- RIL.voiceRegistrationState = {
- cell: {
- gsmLocationAreaCode: 0x1000
- }
- };
- RIL.operator = {};
-
- // Set EF_PNN
- RIL.iccInfoPrivate = {
- PNN: [
- {"fullName": "PNN1Long", "shortName": "PNN1Short"},
- {"fullName": "PNN2Long", "shortName": "PNN2Short"},
- {"fullName": "PNN3Long", "shortName": "PNN3Short"},
- {"fullName": "PNN4Long", "shortName": "PNN4Short"},
- {"fullName": "PNN5Long", "shortName": "PNN5Short"},
- {"fullName": "PNN6Long", "shortName": "PNN6Short"},
- {"fullName": "PNN7Long", "shortName": "PNN7Short"},
- {"fullName": "PNN8Long", "shortName": "PNN8Short"}
- ]
- };
-
- // EF_OPL isn't available
- ICCUtilsHelper.isICCServiceAvailable = function fakeIsICCServiceAvailable(service) {
- return false;
- };
-
- // EF_OPL isn't available and current isn't in HPLMN,
- testGetNetworkNameFromICC({mcc: "321", mnc: "654", lac: 0x1000}, null);
-
- // EF_OPL isn't available and current is in HPLMN,
- // the first record of PNN should be returned.
- testGetNetworkNameFromICC({mcc: "123", mnc: "456", lac: 0x1000},
- {longName: "PNN1Long", shortName: "PNN1Short"});
-
- // EF_OPL is available
- ICCUtilsHelper.isICCServiceAvailable = function fakeIsICCServiceAvailable(service) {
- return service === "OPL";
- };
-
- // Set EF_OPL
- RIL.iccInfoPrivate.OPL = [
- {
- "mcc": "123",
- "mnc": "456",
- "lacTacStart": 0,
- "lacTacEnd": 0xFFFE,
- "pnnRecordId": 4
- },
- {
- "mcc": "321",
- "mnc": "654",
- "lacTacStart": 0,
- "lacTacEnd": 0x0010,
- "pnnRecordId": 3
- },
- {
- "mcc": "321",
- "mnc": "654",
- "lacTacStart": 0x0100,
- "lacTacEnd": 0x1010,
- "pnnRecordId": 2
- },
- {
- "mcc": ";;;",
- "mnc": "01",
- "lacTacStart": 0,
- "lacTacEnd": 0xFFFE,
- "pnnRecordId": 5
- },
- {
- "mcc": "00;",
- "mnc": "02",
- "lacTacStart": 0,
- "lacTacEnd": 0xFFFE,
- "pnnRecordId": 6
- },
- {
- "mcc": "001",
- "mnc": ";;",
- "lacTacStart": 0,
- "lacTacEnd": 0xFFFE,
- "pnnRecordId": 7
- },
- {
- "mcc": "002",
- "mnc": "0;",
- "lacTacStart": 0,
- "lacTacEnd": 0xFFFE,
- "pnnRecordId": 8
- }
- ];
-
- // Both EF_PNN and EF_OPL are presented, and current PLMN is HPLMN,
- testGetNetworkNameFromICC({mcc: "123", mnc: "456", lac: 0x1000},
- {longName: "PNN4Long", shortName: "PNN4Short"});
-
- // Current PLMN is not HPLMN, and according to LAC, we should get
- // the second PNN record.
- testGetNetworkNameFromICC({mcc: "321", mnc: "654", lac: 0x1000},
- {longName: "PNN2Long", shortName: "PNN2Short"});
-
- // Current PLMN is not HPLMN, and according to LAC, we should get
- // the thrid PNN record.
- testGetNetworkNameFromICC({mcc: "321", mnc: "654", lac: 0x0001},
- {longName: "PNN3Long", shortName: "PNN3Short"});
-
- // Current PLMN is not HPLMN, and according to LAC, we should get
- // the 5th PNN record after wild char (ie: ';') handling.
- testGetNetworkNameFromICC({mcc: "001", mnc: "01", lac: 0x0001},
- {longName: "PNN5Long", shortName: "PNN5Short"});
-
- // Current PLMN is not HPLMN, and according to LAC, we should get
- // the 6th PNN record after wild char (ie: ';') handling.
- testGetNetworkNameFromICC({mcc: "001", mnc: "02", lac: 0x0001},
- {longName: "PNN6Long", shortName: "PNN6Short"});
-
- // Current PLMN is not HPLMN, and according to LAC, we should get
- // the 7th PNN record after wild char (ie: ';') handling.
- testGetNetworkNameFromICC({mcc: "001", mnc: "03", lac: 0x0001},
- {longName: "PNN7Long", shortName: "PNN7Short"});
-
- // Current PLMN is not HPLMN, and according to LAC, we should get
- // the 8th PNN record after wild char (ie: ';') handling.
- testGetNetworkNameFromICC({mcc: "002", mnc: "03", lac: 0x0001},
- {longName: "PNN8Long", shortName: "PNN8Short"});
-
- run_next_test();
-});
-
-/**
- * Verify ICCUtilsHelper.isCphsServiceAvailable.
- */
-add_test(function test_is_cphs_service_available() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ICCUtilsHelper = context.ICCUtilsHelper;
- let RIL = context.RIL;
- RIL.iccInfoPrivate.cphsSt = new Uint8Array(2);
-
- function test_table(cphsSt, geckoService) {
- RIL.iccInfoPrivate.cphsSt.set(cphsSt);
-
- for (let service in GECKO_ICC_SERVICES.cphs) {
- equal(ICCUtilsHelper.isCphsServiceAvailable(service),
- geckoService == service);
- }
- }
-
- test_table([0x03, 0x00], "CSP");
- test_table([0x0C, 0x00], "SST");
- test_table([0x30, 0x00], "MBN");
- test_table([0xC0, 0x00], "ONSF");
- test_table([0x00, 0x03], "INFO_NUM");
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_IconLoader.js b/dom/system/gonk/tests/test_ril_worker_icc_IconLoader.js
deleted file mode 100644
index 8bcd26ffe..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_IconLoader.js
+++ /dev/null
@@ -1,771 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify IconLoader.loadIcons with recordNumbers array length being 1.
- * Query images of one record at a time.
- */
-add_test(function test_load_icon_basic() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let iconLoader = context.IconLoader;
- let simRecordHelper = context.SimRecordHelper;
-
- let test_data = [
- {rawData: [
- {codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- width: 0x10,
- height: 0x10,
- body: [0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00,
- 0x00, 0x9d, 0xe9, 0xa1, 0x2d, 0xa1, 0x2d, 0xa1, 0x2b,
- 0xa1, 0x2b, 0x9d, 0xe9, 0x00, 0x00, 0xff, 0xff, 0xff,
- 0xff, 0x00, 0x00, 0xff, 0xff]}],
- expected: [
- {width: 0x10,
- height: 0x10,
- pixels: [/* 1st byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 2nd byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 3rd byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 4th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 5th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 6th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 7th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 8th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 9th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 10th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 11th byte of body: 0x9d */
- 0xffffffff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 12th byte of body: 0xe9 */
- 0xffffffff, 0xffffffff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 13th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 14th byte of body: 0x2d */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 15th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 16th byte of body: 0x2d */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 17th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 18th byte of body: 0x2b */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0xffffffff, 0xffffffff,
- /* 19th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 20th byte of body: 0x2b */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0xffffffff, 0xffffffff,
- /* 21th byte of body: 0x9d */
- 0xffffffff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 22th byte of body: 0xe9 */
- 0xffffffff, 0xffffffff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 23th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 24th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 25th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 26th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 27th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 28th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 29th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 30th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 31th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 32th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff]}]},
- {rawData: [
- {codingScheme: ICC_IMG_CODING_SCHEME_COLOR,
- width: 0x10,
- height: 0x10,
- bitsPerImgPoint: 0x04,
- numOfClutEntries: 0x10,
- body: [0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xaa, 0xaa,
- 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
- 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xcf, 0xfc, 0xcc, 0xfc, 0xcc,
- 0xcf, 0xcf, 0xfc, 0xcf, 0xcf, 0xff, 0xfc, 0xff, 0xcf,
- 0xcc, 0xfc, 0xcf, 0xcf, 0xff, 0xfc, 0xff, 0xcf, 0xcc,
- 0xfc, 0xcf, 0xcf, 0xff, 0xfc, 0xff, 0xcf, 0xcf, 0xcc,
- 0xcf, 0xcf, 0xff, 0xfc, 0xff, 0xcf, 0xcf, 0xcc, 0xcf,
- 0xfc, 0xcc, 0xfc, 0xcc, 0xcf, 0xcf, 0xfc, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xaa, 0xaa, 0xaa,
- 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
- 0xaa, 0xaa, 0xaa, 0xaa, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99,
- 0x99, 0x99],
- clut: [0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00,
- 0x80, 0x80, 0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80,
- 0x00, 0x80, 0x80, 0xc0, 0xc0, 0xc0, 0x80, 0x80, 0x80,
- 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0x00,
- 0x00, 0x00, 0xff, 0xff, 0x00, 0xff, 0x00, 0xff, 0xff,
- 0xff, 0xff, 0xff]}],
- expected: [
- {width: 0x10,
- height: 0x10,
- pixels: [0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0xffffffff, 0xffffffff,
- 0x0000ffff, 0x0000ffff, 0xffffffff, 0x0000ffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0x0000ffff, 0xffffffff,
- 0xffffffff, 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff,
- 0xffffffff, 0x0000ffff, 0x0000ffff, 0xffffffff, 0x0000ffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x0000ffff,
- 0xffffffff, 0xffffffff, 0x0000ffff, 0xffffffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0x0000ffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff, 0x0000ffff,
- 0xffffffff, 0x0000ffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x0000ffff, 0xffffffff, 0xffffffff, 0x0000ffff,
- 0xffffffff, 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0xffffffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff]}]},
- {rawData: [
- {codingScheme: ICC_IMG_CODING_SCHEME_COLOR,
- width: 0x03,
- height: 0x03,
- bitsPerImgPoint: 0x05,
- numOfClutEntries: 0x20,
- body: [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88],
- clut: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
- 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11,
- 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
- 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
- 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c,
- 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
- 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
- 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
- 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,
- 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
- 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f]},
- {codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- width: 0x10,
- height: 0x10,
- body: [0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00,
- 0x00, 0x9d, 0xe9, 0xa1, 0x2d, 0xa1, 0x2d, 0xa1, 0x2b,
- 0xa1, 0x2b, 0x9d, 0xe9, 0x00, 0x00, 0xff, 0xff, 0xff,
- 0xff, 0x00, 0x00, 0xff, 0xff]}],
- expected: [
- {width: 0x03,
- height: 0x03,
- pixels: [0x000102ff, 0x060708ff, 0x0c0d0eff, 0x121314ff, 0x18191aff,
- 0x1e1f20ff, 0x242526ff, 0x2a2b2cff, 0x333435ff]},
- {width: 0x10,
- height: 0x10,
- pixels: [/* 1st byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 2nd byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 3rd byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 4th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 5th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 6th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 7th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 8th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 9th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 10th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 11th byte of body: 0x9d */
- 0xffffffff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 12th byte of body: 0xe9 */
- 0xffffffff, 0xffffffff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 13th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 14th byte of body: 0x2d */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 15th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 16th byte of body: 0x2d */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 17th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 18th byte of body: 0x2b */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0xffffffff, 0xffffffff,
- /* 19th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 20th byte of body: 0x2b */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0xffffffff, 0xffffffff,
- /* 21th byte of body: 0x9d */
- 0xffffffff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 22th byte of body: 0xe9 */
- 0xffffffff, 0xffffffff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 23th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 24th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 25th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 26th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 27th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 28th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 29th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 30th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 31th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 32th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff]}]},
- {rawData: [
- {codingScheme: ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY,
- width: 0x04,
- height: 0x04,
- bitsPerImgPoint: 0x04,
- numOfClutEntries: 0x10,
- body: [0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88],
- clut: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
- 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11,
- 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
- 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
- 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c,
- 0x2d, 0x2e, 0x2f]}],
- expected: [
- {width: 0x04,
- height: 0x04,
- pixels: [0x00000000, 0x00000000, 0x2a2b2cff, 0x2a2b2cff, 0x272829ff,
- 0x272829ff, 0x242526ff, 0x242526ff, 0x212223ff, 0x212223ff,
- 0x1e1f20ff, 0x1e1f20ff, 0x1b1c1dff, 0x1b1c1dff, 0x18191aff,
- 0x18191aff]}]}];
-
- function do_test(test_data, expected) {
- simRecordHelper.readIMG = function fakeReadIMG(recordNumber, onsuccess, onerror) {
- onsuccess(test_data);
- };
-
- let onsuccess = function(icons) {
- // Query one record at a time.
- equal(icons.length, 1);
- equal(icons[0].length, expected.length);
- for (let i = 0; i < icons[0].length; i++) {
- // Read the i_th image of the record.
- let icon = icons[0][i];
- let exp = expected[i];
- equal(icon.width, exp.width);
- equal(icon.height, exp.height);
- equal(icon.pixels.length, exp.pixels.length);
- for (let j = 0; j < icon.pixels.length; j++) {
- equal(icon.pixels[j], exp.pixels[j]);
- }
- }
- };
-
- iconLoader.loadIcons([0], onsuccess);
- }
-
- for (let i = 0; i < test_data.length; i++) {
- do_test(test_data[i].rawData, test_data[i].expected);
- }
-
- run_next_test();
-});
-
-/**
- * Verify IconLoader.loadIcons.
- */
-add_test(function test_load_icons() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let iconLoader = context.IconLoader;
- let simRecordHelper = context.SimRecordHelper;
-
- let test_data = {
- rawData: [
- // Record 1.
- [{codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- width: 0x10,
- height: 0x10,
- body: [0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00,
- 0x00, 0x9d, 0xe9, 0xa1, 0x2d, 0xa1, 0x2d, 0xa1, 0x2b,
- 0xa1, 0x2b, 0x9d, 0xe9, 0x00, 0x00, 0xff, 0xff, 0xff,
- 0xff, 0x00, 0x00, 0xff, 0xff]}],
- // Record 2.
- [{codingScheme: ICC_IMG_CODING_SCHEME_COLOR,
- width: 0x10,
- height: 0x10,
- bitsPerImgPoint: 0x04,
- numOfClutEntries: 0x10,
- body: [0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xaa, 0xaa,
- 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
- 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xcf, 0xfc, 0xcc, 0xfc, 0xcc,
- 0xcf, 0xcf, 0xfc, 0xcf, 0xcf, 0xff, 0xfc, 0xff, 0xcf,
- 0xcc, 0xfc, 0xcf, 0xcf, 0xff, 0xfc, 0xff, 0xcf, 0xcc,
- 0xfc, 0xcf, 0xcf, 0xff, 0xfc, 0xff, 0xcf, 0xcf, 0xcc,
- 0xcf, 0xcf, 0xff, 0xfc, 0xff, 0xcf, 0xcf, 0xcc, 0xcf,
- 0xfc, 0xcc, 0xfc, 0xcc, 0xcf, 0xcf, 0xfc, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xaa, 0xaa, 0xaa,
- 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
- 0xaa, 0xaa, 0xaa, 0xaa, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99,
- 0x99, 0x99],
- clut: [0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00,
- 0x80, 0x80, 0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80,
- 0x00, 0x80, 0x80, 0xc0, 0xc0, 0xc0, 0x80, 0x80, 0x80,
- 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0x00,
- 0x00, 0x00, 0xff, 0xff, 0x00, 0xff, 0x00, 0xff, 0xff,
- 0xff, 0xff, 0xff]}],
- // Record 3.
- [{codingScheme: ICC_IMG_CODING_SCHEME_COLOR,
- width: 0x03,
- height: 0x03,
- bitsPerImgPoint: 0x05,
- numOfClutEntries: 0x20,
- body: [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88],
- clut: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
- 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11,
- 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
- 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
- 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c,
- 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
- 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
- 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
- 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50,
- 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
- 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f]},
- {codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- width: 0x10,
- height: 0x10,
- body: [0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00,
- 0x00, 0x9d, 0xe9, 0xa1, 0x2d, 0xa1, 0x2d, 0xa1, 0x2b,
- 0xa1, 0x2b, 0x9d, 0xe9, 0x00, 0x00, 0xff, 0xff, 0xff,
- 0xff, 0x00, 0x00, 0xff, 0xff]}],
- // Record 4.
- [{codingScheme: ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY,
- width: 0x04,
- height: 0x04,
- bitsPerImgPoint: 0x04,
- numOfClutEntries: 0x10,
- body: [0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88],
- clut: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
- 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11,
- 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a,
- 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
- 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c,
- 0x2d, 0x2e, 0x2f]}]],
- expected: [
- // Record 1.
- [{width: 0x10,
- height: 0x10,
- pixels: [/* 1st byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 2nd byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 3rd byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 4th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 5th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 6th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 7th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 8th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 9th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 10th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 11th byte of body: 0x9d */
- 0xffffffff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 12th byte of body: 0xe9 */
- 0xffffffff, 0xffffffff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 13th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 14th byte of body: 0x2d */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 15th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 16th byte of body: 0x2d */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 17th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 18th byte of body: 0x2b */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0xffffffff, 0xffffffff,
- /* 19th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 20th byte of body: 0x2b */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0xffffffff, 0xffffffff,
- /* 21th byte of body: 0x9d */
- 0xffffffff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 22th byte of body: 0xe9 */
- 0xffffffff, 0xffffffff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 23th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 24th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 25th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 26th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 27th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 28th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 29th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 30th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 31th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 32th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff]}],
- // Record 2.
- [{width: 0x10,
- height: 0x10,
- pixels: [0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0xffffffff, 0xffffffff,
- 0x0000ffff, 0x0000ffff, 0xffffffff, 0x0000ffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0x0000ffff, 0xffffffff,
- 0xffffffff, 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff,
- 0xffffffff, 0x0000ffff, 0x0000ffff, 0xffffffff, 0x0000ffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x0000ffff,
- 0xffffffff, 0xffffffff, 0x0000ffff, 0xffffffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0x0000ffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff, 0x0000ffff,
- 0xffffffff, 0x0000ffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x0000ffff, 0xffffffff, 0xffffffff, 0x0000ffff,
- 0xffffffff, 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0x0000ffff, 0x0000ffff,
- 0x0000ffff, 0xffffffff, 0x0000ffff, 0xffffffff, 0xffffffff,
- 0x0000ffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff,
- 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0x00ff00ff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0000ff,
- 0xff0000ff]}],
- // Record 3.
- [{width: 0x03,
- height: 0x03,
- pixels: [0x000102ff, 0x060708ff, 0x0c0d0eff, 0x121314ff, 0x18191aff,
- 0x1e1f20ff, 0x242526ff, 0x2a2b2cff, 0x333435ff]},
- {width: 0x10,
- height: 0x10,
- pixels: [/* 1st byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 2nd byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 3rd byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 4th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 5th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 6th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 7th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 8th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 9th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 10th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 11th byte of body: 0x9d */
- 0xffffffff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 12th byte of body: 0xe9 */
- 0xffffffff, 0xffffffff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 13th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 14th byte of body: 0x2d */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 15th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 16th byte of body: 0x2d */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 17th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 18th byte of body: 0x2b */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0xffffffff, 0xffffffff,
- /* 19th byte of body: 0xa1 */
- 0xffffffff, 0x000000ff, 0xffffffff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 20th byte of body: 0x2b */
- 0x000000ff, 0x000000ff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0xffffffff, 0xffffffff,
- /* 21th byte of body: 0x9d */
- 0xffffffff, 0x000000ff, 0x000000ff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0x000000ff, 0xffffffff,
- /* 22th byte of body: 0xe9 */
- 0xffffffff, 0xffffffff, 0xffffffff, 0x000000ff, 0xffffffff,
- 0x000000ff, 0x000000ff, 0xffffffff,
- /* 23th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 24th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 25th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 26th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 27th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 28th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 29th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 30th byte of body: 0x00 */
- 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff,
- 0x000000ff, 0x000000ff, 0x000000ff,
- /* 31th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff,
- /* 32th byte of body: 0xff */
- 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
- 0xffffffff, 0xffffffff, 0xffffffff]}],
- // Record 4.
- [{width: 0x04,
- height: 0x04,
- pixels: [0x00000000, 0x00000000, 0x2a2b2cff, 0x2a2b2cff, 0x272829ff,
- 0x272829ff, 0x242526ff, 0x242526ff, 0x212223ff, 0x212223ff,
- 0x1e1f20ff, 0x1e1f20ff, 0x1b1c1dff, 0x1b1c1dff, 0x18191aff,
- 0x18191aff]}]]};
-
- function do_test() {
- simRecordHelper.readIMG = function fakeReadIMG(recordNumber, onsuccess, onerror) {
- onsuccess(test_data.rawData[recordNumber]);
- };
-
- let onsuccess = function(icons) {
- equal(icons.length, test_data.expected.length);
- for (let i = 0; i < icons.length; i++) {
- for (let j = 0; j < icons[i].length; j++) {
- // Read the j_th image from the i_th record.
- let icon = icons[i][j];
- let expected = test_data.expected[i][j];
- equal(icon.width, expected.width);
- equal(icon.height, expected.height);
- equal(icon.pixels.length, expected.pixels.length);
- for (let k = 0; k < icon.pixels.length; k++) {
- equal(icon.pixels[k], expected.pixels[k]);
- }
- }
- }
- };
-
- let recordNumbers = [0, 1, 2, 3];
- iconLoader.loadIcons(recordNumbers, onsuccess);
- }
-
- do_test();
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_icc_SimRecordHelper.js b/dom/system/gonk/tests/test_ril_worker_icc_SimRecordHelper.js
deleted file mode 100644
index 6500cc663..000000000
--- a/dom/system/gonk/tests/test_ril_worker_icc_SimRecordHelper.js
+++ /dev/null
@@ -1,1648 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify reading EF_AD and parsing MCC/MNC
- */
-add_test(function test_reading_ad_and_parsing_mcc_mnc() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- function do_test(mncLengthInEf, imsi, expectedMcc, expectedMnc) {
- ril.iccInfoPrivate.imsi = imsi;
-
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- let ad = [0x00, 0x00, 0x00];
- if (typeof mncLengthInEf === 'number') {
- ad.push(mncLengthInEf);
- }
-
- // Write data size
- buf.writeInt32(ad.length * 2);
-
- // Write data
- for (let i = 0; i < ad.length; i++) {
- helper.writeHexOctet(ad[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(ad.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- record.readAD();
-
- equal(ril.iccInfo.mcc, expectedMcc);
- equal(ril.iccInfo.mnc, expectedMnc);
- }
-
- do_test(undefined, "466923202422409", "466", "92" );
- do_test(0x00, "466923202422409", "466", "92" );
- do_test(0x01, "466923202422409", "466", "92" );
- do_test(0x02, "466923202422409", "466", "92" );
- do_test(0x03, "466923202422409", "466", "923");
- do_test(0x04, "466923202422409", "466", "92" );
- do_test(0xff, "466923202422409", "466", "92" );
-
- do_test(undefined, "310260542718417", "310", "260");
- do_test(0x00, "310260542718417", "310", "260");
- do_test(0x01, "310260542718417", "310", "260");
- do_test(0x02, "310260542718417", "310", "26" );
- do_test(0x03, "310260542718417", "310", "260");
- do_test(0x04, "310260542718417", "310", "260");
- do_test(0xff, "310260542718417", "310", "260");
-
- run_next_test();
-});
-
-add_test(function test_reading_optional_efs() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let gsmPdu = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- function buildSST(supportedEf) {
- let sst = [];
- let len = supportedEf.length;
- for (let i = 0; i < len; i++) {
- let index, bitmask, iccService;
- if (ril.appType === CARD_APPTYPE_SIM) {
- iccService = GECKO_ICC_SERVICES.sim[supportedEf[i]];
- iccService -= 1;
- index = Math.floor(iccService / 4);
- bitmask = 2 << ((iccService % 4) << 1);
- } else if (ril.appType === CARD_APPTYPE_USIM){
- iccService = GECKO_ICC_SERVICES.usim[supportedEf[i]];
- iccService -= 1;
- index = Math.floor(iccService / 8);
- bitmask = 1 << ((iccService % 8) << 0);
- }
-
- if (sst) {
- sst[index] |= bitmask;
- }
- }
- return sst;
- }
-
- ril.updateCellBroadcastConfig = function fakeUpdateCellBroadcastConfig() {
- // Ignore updateCellBroadcastConfig after reading SST
- };
-
- function do_test(sst, supportedEf) {
- // Clone supportedEf to local array for testing
- let testEf = supportedEf.slice(0);
-
- record.readMSISDN = function fakeReadMSISDN() {
- testEf.splice(testEf.indexOf("MSISDN"), 1);
- };
-
- record.readMBDN = function fakeReadMBDN() {
- testEf.splice(testEf.indexOf("MDN"), 1);
- };
-
- record.readMWIS = function fakeReadMWIS() {
- testEf.splice(testEf.indexOf("MWIS"), 1);
- };
-
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(sst.length * 2);
-
- // Write data
- for (let i = 0; i < sst.length; i++) {
- gsmPdu.writeHexOctet(sst[i] || 0);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(sst.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
-
- if (testEf.length !== 0) {
- do_print("Un-handled EF: " + JSON.stringify(testEf));
- ok(false);
- }
- };
-
- record.readSST();
- }
-
- // TODO: Add all necessary optional EFs eventually
- let supportedEf = ["MSISDN", "MDN", "MWIS"];
- ril.appType = CARD_APPTYPE_SIM;
- do_test(buildSST(supportedEf), supportedEf);
- ril.appType = CARD_APPTYPE_USIM;
- do_test(buildSST(supportedEf), supportedEf);
-
- run_next_test();
-});
-
-/**
- * Verify fetchSimRecords.
- */
-add_test(function test_fetch_sim_records() {
- let worker = newWorker();
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let iccRecord = context.ICCRecordHelper;
- let simRecord = context.SimRecordHelper;
-
- function testFetchSimRecordes(expectCalled, expectCphsSuccess) {
- let ifCalled = [];
-
- RIL.getIMSI = function() {
- ifCalled.push("getIMSI");
- };
-
- simRecord.readAD = function() {
- ifCalled.push("readAD");
- };
-
- simRecord.readCphsInfo = function(onsuccess, onerror) {
- ifCalled.push("readCphsInfo");
- if (expectCphsSuccess) {
- onsuccess();
- } else {
- onerror();
- }
- };
-
- simRecord.readSST = function() {
- ifCalled.push("readSST");
- };
-
- simRecord.fetchSimRecords();
-
- for (let i = 0; i < expectCalled.length; i++ ) {
- if (ifCalled[i] != expectCalled[i]) {
- do_print(expectCalled[i] + " is not called.");
- ok(false);
- }
- }
- }
-
- let expectCalled = ["getIMSI", "readAD", "readCphsInfo", "readSST"];
- testFetchSimRecordes(expectCalled, true);
- testFetchSimRecordes(expectCalled, false);
-
- run_next_test();
-});
-
-/**
- * Verify SimRecordHelper.readMWIS
- */
-add_test(function test_read_mwis() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let recordHelper = context.SimRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
- let mwisData;
- let postedMessage;
-
- worker.postMessage = function fakePostMessage(message) {
- postedMessage = message;
- };
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- if (mwisData) {
- // Write data size
- buf.writeInt32(mwisData.length * 2);
-
- // Write MWIS
- for (let i = 0; i < mwisData.length; i++) {
- helper.writeHexOctet(mwisData[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(mwisData.length * 2);
-
- options.recordSize = mwisData.length;
- if (options.callback) {
- options.callback(options);
- }
- } else {
- do_print("mwisData[] is not set.");
- }
- };
-
- function buildMwisData(isActive, msgCount) {
- if (msgCount < 0 || msgCount === GECKO_VOICEMAIL_MESSAGE_COUNT_UNKNOWN) {
- msgCount = 0;
- } else if (msgCount > 255) {
- msgCount = 255;
- }
-
- mwisData = [ (isActive) ? 0x01 : 0x00,
- msgCount,
- 0xFF, 0xFF, 0xFF ];
- }
-
- function do_test(isActive, msgCount) {
- buildMwisData(isActive, msgCount);
- recordHelper.readMWIS();
-
- equal("iccmwis", postedMessage.rilMessageType);
- equal(isActive, postedMessage.mwi.active);
- equal((isActive) ? msgCount : 0, postedMessage.mwi.msgCount);
- }
-
- do_test(true, GECKO_VOICEMAIL_MESSAGE_COUNT_UNKNOWN);
- do_test(true, 1);
- do_test(true, 255);
-
- do_test(false, 0);
- do_test(false, 255); // Test the corner case when mwi is disable with incorrect msgCount.
-
- run_next_test();
-});
-
-/**
- * Verify SimRecordHelper.updateMWIS
- */
-add_test(function test_update_mwis() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let ril = context.RIL;
- ril.appType = CARD_APPTYPE_USIM;
- ril.iccInfoPrivate.mwis = [0x00, 0x00, 0x00, 0x00, 0x00];
- let recordHelper = context.SimRecordHelper;
- let buf = context.Buf;
- let ioHelper = context.ICCIOHelper;
- let recordSize = ril.iccInfoPrivate.mwis.length;
- let recordNum = 1;
-
- ioHelper.updateLinearFixedEF = function(options) {
- options.pathId = context.ICCFileHelper.getEFPath(options.fileId);
- options.command = ICC_COMMAND_UPDATE_RECORD;
- options.p1 = options.recordNumber;
- options.p2 = READ_RECORD_ABSOLUTE_MODE;
- options.p3 = recordSize;
- ril.iccIO(options);
- };
-
- function do_test(isActive, count) {
- let mwis = ril.iccInfoPrivate.mwis;
- let isUpdated = false;
-
- function buildMwisData() {
- let result = mwis.slice(0);
- result[0] = isActive? (mwis[0] | 0x01) : (mwis[0] & 0xFE);
- result[1] = (count === GECKO_VOICEMAIL_MESSAGE_COUNT_UNKNOWN) ? 0 : count;
-
- return result;
- }
-
- buf.sendParcel = function() {
- isUpdated = true;
-
- // Request Type.
- equal(this.readInt32(), REQUEST_SIM_IO);
-
- // Token : we don't care
- this.readInt32();
-
- // command.
- equal(this.readInt32(), ICC_COMMAND_UPDATE_RECORD);
-
- // fileId.
- equal(this.readInt32(), ICC_EF_MWIS);
-
- // pathId.
- equal(this.readString(),
- EF_PATH_MF_SIM + ((ril.appType === CARD_APPTYPE_USIM) ? EF_PATH_ADF_USIM : EF_PATH_DF_GSM));
-
- // p1.
- equal(this.readInt32(), recordNum);
-
- // p2.
- equal(this.readInt32(), READ_RECORD_ABSOLUTE_MODE);
-
- // p3.
- equal(this.readInt32(), recordSize);
-
- // data.
- let strLen = this.readInt32();
- equal(recordSize * 2, strLen);
- let expectedMwis = buildMwisData();
- for (let i = 0; i < recordSize; i++) {
- equal(expectedMwis[i], pduHelper.readHexOctet());
- }
- this.readStringDelimiter(strLen);
-
- // pin2.
- equal(this.readString(), null);
-
- // AID. Ignore because it's from modem.
- this.readInt32();
- };
-
- ok(!isUpdated);
-
- recordHelper.updateMWIS({ active: isActive,
- msgCount: count });
-
- ok((ril.iccInfoPrivate.mwis) ? isUpdated : !isUpdated);
- }
-
- do_test(true, GECKO_VOICEMAIL_MESSAGE_COUNT_UNKNOWN);
- do_test(true, 1);
- do_test(true, 255);
-
- do_test(false, 0);
-
- // Test if Path ID is correct for SIM.
- ril.appType = CARD_APPTYPE_SIM;
- do_test(false, 0);
-
- // Test if loadLinearFixedEF() is not invoked in updateMWIS() when
- // EF_MWIS is not loaded/available.
- delete ril.iccInfoPrivate.mwis;
- do_test(false, 0);
-
- run_next_test();
-});
-
-/**
- * Verify the call flow of receiving Class 2 SMS stored in SIM:
- * 1. UNSOLICITED_RESPONSE_NEW_SMS_ON_SIM.
- * 2. SimRecordHelper.readSMS().
- * 3. sendChromeMessage() with rilMessageType == "sms-received".
- */
-add_test(function test_read_new_sms_on_sim() {
- // Instead of reusing newUint8Worker defined in this file,
- // we define our own worker to fake the methods in WorkerBuffer dynamically.
- function newSmsOnSimWorkerHelper() {
- let _postedMessage;
- let _worker = newWorker({
- postRILMessage: function(data) {
- },
- postMessage: function(message) {
- _postedMessage = message;
- }
- });
-
- _worker.debug = do_print;
-
- return {
- get postedMessage() {
- return _postedMessage;
- },
- get worker() {
- return _worker;
- },
- fakeWokerBuffer: function() {
- let context = _worker.ContextPool._contexts[0];
- let index = 0; // index for read
- let buf = [];
- context.Buf.writeUint8 = function(value) {
- buf.push(value);
- };
- context.Buf.readUint8 = function() {
- return buf[index++];
- };
- context.Buf.seekIncoming = function(offset) {
- index += offset;
- };
- context.Buf.getReadAvailable = function() {
- return buf.length - index;
- };
- }
- };
- }
-
- let workerHelper = newSmsOnSimWorkerHelper();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.ICCIOHelper.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // SimStatus: Unread, SMSC:+0123456789, Sender: +9876543210, Text: How are you?
- let SimSmsPduHex = "0306911032547698040A9189674523010000208062917314080CC8F71D14969741F977FD07"
- // In 4.2.25 EF_SMS Short Messages of 3GPP TS 31.102:
- // 1. Record length == 176 bytes.
- // 2. Any bytes in the record following the TPDU shall be filled with 'FF'.
- + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
- + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
- + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
- + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
-
- workerHelper.fakeWokerBuffer();
-
- context.Buf.writeString(SimSmsPduHex);
-
- options.recordSize = 176; // Record length is fixed to 176 bytes.
- if (options.callback) {
- options.callback(options);
- }
- };
-
- function newSmsOnSimParcel() {
- let data = new Uint8Array(4 + 4); // Int32List with 1 element.
- let offset = 0;
-
- function writeInt(value) {
- data[offset++] = value & 0xFF;
- data[offset++] = (value >> 8) & 0xFF;
- data[offset++] = (value >> 16) & 0xFF;
- data[offset++] = (value >> 24) & 0xFF;
- }
-
- writeInt(1); // Length of Int32List
- writeInt(1); // RecordNum = 1.
-
- return newIncomingParcel(-1,
- RESPONSE_TYPE_UNSOLICITED,
- UNSOLICITED_RESPONSE_NEW_SMS_ON_SIM,
- data);
- }
-
- function do_test() {
- worker.onRILMessage(0, newSmsOnSimParcel());
-
- let postedMessage = workerHelper.postedMessage;
-
- equal("sms-received", postedMessage.rilMessageType);
- equal("+0123456789", postedMessage.SMSC);
- equal("+9876543210", postedMessage.sender);
- equal("How are you?", postedMessage.body);
- }
-
- do_test();
-
- run_next_test();
-});
-
-/**
- * Verify the result of updateDisplayCondition after reading EF_SPDI | EF_SPN.
- */
-add_test(function test_update_display_condition() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- function do_test_spdi() {
- // No EF_SPN, but having EF_SPDI.
- // It implies "ril.iccInfoPrivate.spnDisplayCondition = undefined;".
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // PLMN lists are : 234-136 and 466-92.
- let spdi = [0xA3, 0x0B, 0x80, 0x09, 0x32, 0x64, 0x31, 0x64, 0x26, 0x9F,
- 0xFF, 0xFF, 0xFF];
-
- // Write data size.
- buf.writeInt32(spdi.length * 2);
-
- // Write data.
- for (let i = 0; i < spdi.length; i++) {
- helper.writeHexOctet(spdi[i]);
- }
-
- // Write string delimiter.
- buf.writeStringDelimiter(spdi.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- record.readSPDI();
-
- equal(ril.iccInfo.isDisplayNetworkNameRequired, true);
- equal(ril.iccInfo.isDisplaySpnRequired, false);
- }
-
- function do_test_spn(displayCondition,
- expectedPlmnNameDisplay,
- expectedSpnDisplay) {
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // "Android" as Service Provider Name.
- let spn = [0x41, 0x6E, 0x64, 0x72, 0x6F, 0x69, 0x64];
- if (typeof displayCondition === 'number') {
- spn.unshift(displayCondition);
- }
-
- // Write data size.
- buf.writeInt32(spn.length * 2);
-
- // Write data.
- for (let i = 0; i < spn.length; i++) {
- helper.writeHexOctet(spn[i]);
- }
-
- // Write string delimiter.
- buf.writeStringDelimiter(spn.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- record.readSPN();
-
- equal(ril.iccInfo.isDisplayNetworkNameRequired, expectedPlmnNameDisplay);
- equal(ril.iccInfo.isDisplaySpnRequired, expectedSpnDisplay);
- }
-
- // Create empty operator object.
- ril.operator = {};
- // Setup SIM MCC-MNC to 310-260 as home network.
- ril.iccInfo.mcc = 310;
- ril.iccInfo.mnc = 260;
-
- do_test_spdi();
-
- // No network.
- do_test_spn(0x00, true, true);
- do_test_spn(0x01, true, true);
- do_test_spn(0x02, true, false);
- do_test_spn(0x03, true, false);
-
- // Home network.
- ril.operator.mcc = 310;
- ril.operator.mnc = 260;
- do_test_spn(0x00, false, true);
- do_test_spn(0x01, true, true);
- do_test_spn(0x02, false, true);
- do_test_spn(0x03, true, true);
-
- // Not HPLMN but in PLMN list.
- ril.iccInfoPrivate.SPDI = [{"mcc":"234","mnc":"136"},{"mcc":"466","mnc":"92"}];
- ril.operator.mcc = 466;
- ril.operator.mnc = 92;
- do_test_spn(0x00, false, true);
- do_test_spn(0x01, true, true);
- do_test_spn(0x02, false, true);
- do_test_spn(0x03, true, true);
- ril.iccInfoPrivate.SPDI = null; // reset SPDI to null;
-
- // Non-Home network.
- ril.operator.mcc = 466;
- ril.operator.mnc = 01;
- do_test_spn(0x00, true, true);
- do_test_spn(0x01, true, true);
- do_test_spn(0x02, true, false);
- do_test_spn(0x03, true, false);
-
- run_next_test();
-});
-
-/**
- * Verify reading EF_IMG and EF_IIDF with ICC_IMG_CODING_SCHEME_BASIC
- */
-add_test(function test_reading_img_basic() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- let test_data = [
- {img: [0x01, 0x05, 0x05, 0x11, 0x4f, 0x00, 0x00, 0x00, 0x00, 0x06],
- iidf: [
- [/* Header */
- 0x05, 0x05,
- /* Image body */
- 0x11, 0x33, 0x55, 0xfe]],
- expected: [
- {width: 0x05,
- height: 0x05,
- codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- body: [0x11, 0x33, 0x55, 0xfe]}]},
- {img: [0x01, 0x05, 0x05, 0x11, 0x4f, 0x00, 0x00, 0x00, 0x00, 0x06,
- /* Padding */
- 0xff, 0xff],
- iidf: [
- [/* Header */
- 0x05, 0x05,
- /* Image body */
- 0x11, 0x33, 0x55, 0xfe]],
- expected: [
- {width: 0x05,
- height: 0x05,
- codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- body: [0x11, 0x33, 0x55, 0xfe]}]},
- {img: [0x02, 0x10, 0x01, 0x11, 0x4f, 0x04, 0x00, 0x05, 0x00, 0x04, 0x10,
- 0x01, 0x11, 0x4f, 0x05, 0x00, 0x05, 0x00, 0x04],
- iidf: [
- [/* Data offset */
- 0xff, 0xff, 0xff, 0xff, 0xff,
- /* Header */
- 0x10, 0x01,
- /* Image body */
- 0x11, 0x99,
- /* Trailing data */
- 0xff, 0xff, 0xff],
- [/* Data offset */
- 0xff, 0xff, 0xff, 0xff, 0xff,
- /* Header */
- 0x10, 0x01,
- /* Image body */
- 0x99, 0x11]],
- expected: [
- {width: 0x10,
- height: 0x01,
- codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- body: [0x11, 0x99]},
- {width: 0x10,
- height: 0x01,
- codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- body: [0x99, 0x11]}]},
- {img: [0x01, 0x28, 0x20, 0x11, 0x4f, 0xac, 0x00, 0x0b, 0x00, 0xa2],
- iidf: [
- [/* Data offset */
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- /* Header */
- 0x28, 0x20,
- /* Image body */
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
- 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
- 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
- 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36,
- 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41,
- 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c,
- 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
- 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x00, 0x01, 0x02,
- 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
- 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
- 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
- 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e,
- 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
- 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f]],
- expected: [
- {width: 0x28,
- height: 0x20,
- codingScheme: ICC_IMG_CODING_SCHEME_BASIC,
- body: [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
- 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13,
- 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
- 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
- 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31,
- 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
- 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
- 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
- 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
- 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 0x00, 0x01, 0x02, 0x03,
- 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
- 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
- 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21,
- 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
- 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
- 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f]}]}];
-
- function do_test(img, iidf, expected) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(img.length * 2);
-
- // Write data
- for (let i = 0; i < img.length; i++) {
- helper.writeHexOctet(img[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(img.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let instanceIndex = 0;
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(iidf[instanceIndex].length * 2);
-
- // Write data
- for (let i = 0; i < iidf[instanceIndex].length; i++) {
- helper.writeHexOctet(iidf[instanceIndex][i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(iidf[instanceIndex].length * 2);
-
- instanceIndex++;
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let onsuccess = function(icons) {
- equal(icons.length, expected.length);
- for (let i = 0; i < icons.length; i++) {
- let icon = icons[i];
- let exp = expected[i];
- equal(icon.width, exp.width);
- equal(icon.height, exp.height);
- equal(icon.codingScheme, exp.codingScheme);
-
- equal(icon.body.length, exp.body.length);
- for (let j = 0; j < icon.body.length; j++) {
- equal(icon.body[j], exp.body[j]);
- }
- }
- };
- record.readIMG(0, onsuccess);
- }
-
- for (let i = 0; i< test_data.length; i++) {
- do_test(test_data[i].img, test_data[i].iidf, test_data[i].expected);
- }
- run_next_test();
-});
-
-/**
- * Verify reading EF_IMG and EF_IIDF with the case data length is not enough
- */
-add_test(function test_reading_img_length_error() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- let test_data = [
- {/* Offset length not enough, should be 4. */
- img: [0x01, 0x05, 0x05, 0x11, 0x4f, 0x00, 0x00, 0x04, 0x00, 0x06],
- iidf: [0xff, 0xff, 0xff, // Offset.
- 0x05, 0x05, 0x11, 0x22, 0x33, 0xfe]},
- {/* iidf data length not enough, should be 6. */
- img: [0x01, 0x05, 0x05, 0x11, 0x4f, 0x00, 0x00, 0x00, 0x00, 0x06],
- iidf: [0x05, 0x05, 0x11, 0x22, 0x33]}];
-
- function do_test(img, iidf) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(img.length * 2);
-
- // Write data
- for (let i = 0; i < img.length; i++) {
- helper.writeHexOctet(img[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(img.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(iidf.length * 2);
-
- // Write data
- for (let i = 0; i < iidf.length; i++) {
- helper.writeHexOctet(iidf[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(iidf.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let onsuccess = function() {
- do_print("onsuccess shouldn't be called.");
- ok(false);
- };
-
- let onerror = function() {
- do_print("onerror called as expected.");
- ok(true);
- };
-
- record.readIMG(0, onsuccess, onerror);
- }
-
- for (let i = 0; i < test_data.length; i++) {
- do_test(test_data[i].img, test_data[i].iidf);
- }
- run_next_test();
-});
-
-/**
- * Verify reading EF_IMG and EF_IIDF with an invalid fileId
- */
-add_test(function test_reading_img_invalid_fileId() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- // Test invalid fileId: 0x5f00.
- let img_test = [0x01, 0x05, 0x05, 0x11, 0x5f, 0x00, 0x00, 0x00, 0x00, 0x06];
- let iidf_test = [0x05, 0x05, 0x11, 0x22, 0x33, 0xfe];
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(img_test.length * 2);
-
- // Write data
- for (let i = 0; i < img_test.length; i++) {
- helper.writeHexOctet(img_test[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(img_test.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(iidf_test.length * 2);
-
- // Write data
- for (let i = 0; i < iidf_test.length; i++) {
- helper.writeHexOctet(iidf_test[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(iidf_test.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let onsuccess = function() {
- do_print("onsuccess shouldn't be called.");
- ok(false);
- };
-
- let onerror = function() {
- do_print("onerror called as expected.");
- ok(true);
- };
-
- record.readIMG(0, onsuccess, onerror);
-
- run_next_test();
-});
-
-/**
- * Verify reading EF_IMG with a wrong record length
- */
-add_test(function test_reading_img_wrong_record_length() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- let test_data = [
- [0x01, 0x05, 0x05, 0x11, 0x4f, 0x00, 0x00, 0x00],
- [0x02, 0x05, 0x05, 0x11, 0x4f, 0x00, 0x00, 0x00, 0x00, 0x06]];
-
- function do_test(img) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(img.length * 2);
-
- // Write data
- for (let i = 0; i < img.length; i++) {
- helper.writeHexOctet(img[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(img.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let onsuccess = function() {
- do_print("onsuccess shouldn't be called.");
- ok(false);
- };
-
- let onerror = function() {
- do_print("onerror called as expected.");
- ok(true);
- };
-
- record.readIMG(0, onsuccess, onerror);
- }
-
- for (let i = 0; i < test_data.length; i++) {
- do_test(test_data[i]);
- }
- run_next_test();
-});
-
-/**
- * Verify reading EF_IMG and EF_IIDF with ICC_IMG_CODING_SCHEME_COLOR
- */
-add_test(function test_reading_img_color() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- let test_data = [
- {img: [0x01, 0x05, 0x05, 0x21, 0x4f, 0x11, 0x00, 0x00, 0x00, 0x13],
- iidf: [
- [/* Header */
- 0x05, 0x05, 0x03, 0x08, 0x00, 0x13,
- /* Image body */
- 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0,
- 0xb0, 0xc0, 0xd0,
- /* Clut entries */
- 0x00, 0x01, 0x02,
- 0x10, 0x11, 0x12,
- 0x20, 0x21, 0x22,
- 0x30, 0x31, 0x32,
- 0x40, 0x41, 0x42,
- 0x50, 0x51, 0x52,
- 0x60, 0x61, 0x62,
- 0x70, 0x71, 0x72]],
- expected: [
- {width: 0x05,
- height: 0x05,
- codingScheme: ICC_IMG_CODING_SCHEME_COLOR,
- bitsPerImgPoint: 0x03,
- numOfClutEntries: 0x08,
- body: [0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0,
- 0xc0, 0xd0],
- clut: [0x00, 0x01, 0x02,
- 0x10, 0x11, 0x12,
- 0x20, 0x21, 0x22,
- 0x30, 0x31, 0x32,
- 0x40, 0x41, 0x42,
- 0x50, 0x51, 0x52,
- 0x60, 0x61, 0x62,
- 0x70, 0x71, 0x72]}]},
- {img: [0x02, 0x01, 0x06, 0x21, 0x4f, 0x33, 0x00, 0x02, 0x00, 0x08, 0x01,
- 0x06, 0x21, 0x4f, 0x44, 0x00, 0x02, 0x00, 0x08],
- iidf: [
- [/* Data offset */
- 0xff, 0xff,
- /* Header */
- 0x01, 0x06, 0x02, 0x04, 0x00, 0x0d,
- /* Image body */
- 0x40, 0x50,
- /* Clut offset */
- 0xaa, 0xbb, 0xcc,
- /* Clut entries */
- 0x01, 0x03, 0x05,
- 0x21, 0x23, 0x25,
- 0x41, 0x43, 0x45,
- 0x61, 0x63, 0x65],
- [/* Data offset */
- 0xff, 0xff,
- /* Header */
- 0x01, 0x06, 0x02, 0x04, 0x00, 0x0d,
- /* Image body */
- 0x4f, 0x5f,
- /* Clut offset */
- 0xaa, 0xbb, 0xcc,
- /* Clut entries */
- 0x11, 0x13, 0x15,
- 0x21, 0x23, 0x25,
- 0x41, 0x43, 0x45,
- 0x61, 0x63, 0x65]],
- expected: [
- {width: 0x01,
- height: 0x06,
- codingScheme: ICC_IMG_CODING_SCHEME_COLOR,
- bitsPerImgPoint: 0x02,
- numOfClutEntries: 0x04,
- body: [0x40, 0x50],
- clut: [0x01, 0x03, 0x05,
- 0x21, 0x23, 0x25,
- 0x41, 0x43, 0x45,
- 0x61, 0x63, 0x65]},
- {width: 0x01,
- height: 0x06,
- codingScheme: ICC_IMG_CODING_SCHEME_COLOR,
- bitsPerImgPoint: 0x02,
- numOfClutEntries: 0x04,
- body: [0x4f, 0x5f],
- clut: [0x11, 0x13, 0x15,
- 0x21, 0x23, 0x25,
- 0x41, 0x43, 0x45,
- 0x61, 0x63, 0x65]}]}];
-
- function do_test(img, iidf, expected) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(img.length * 2);
-
- // Write data
- for (let i = 0; i < img.length; i++) {
- helper.writeHexOctet(img[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(img.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let instanceIndex = 0;
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(iidf[instanceIndex].length * 2);
-
- // Write data
- for (let i = 0; i < iidf[instanceIndex].length; i++) {
- helper.writeHexOctet(iidf[instanceIndex][i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(iidf[instanceIndex].length * 2);
-
- instanceIndex++;
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let onsuccess = function(icons) {
- equal(icons.length, expected.length);
- for (let i = 0; i < icons.length; i++) {
- let icon = icons[i];
- let exp = expected[i];
- equal(icon.width, exp.width);
- equal(icon.height, exp.height);
- equal(icon.codingScheme, exp.codingScheme);
-
- equal(icon.body.length, exp.body.length);
- for (let j = 0; j < icon.body.length; j++) {
- equal(icon.body[j], exp.body[j]);
- }
-
- equal(icon.clut.length, exp.clut.length);
- for (let j = 0; j < icon.clut.length; j++) {
- equal(icon.clut[j], exp.clut[j]);
- }
- }
- };
-
- record.readIMG(0, onsuccess);
- }
-
- for (let i = 0; i< test_data.length; i++) {
- do_test(test_data[i].img, test_data[i].iidf, test_data[i].expected);
- }
- run_next_test();
-});
-
-/**
- * Verify reading EF_IMG and EF_IIDF with
- * ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY
- */
-add_test(function test_reading_img_color() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let helper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- let test_data = [
- {img: [0x01, 0x05, 0x05, 0x22, 0x4f, 0x11, 0x00, 0x00, 0x00, 0x13],
- iidf: [
- [/* Header */
- 0x05, 0x05, 0x03, 0x08, 0x00, 0x13,
- /* Image body */
- 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0,
- 0xb0, 0xc0, 0xd0,
- /* Clut entries */
- 0x00, 0x01, 0x02,
- 0x10, 0x11, 0x12,
- 0x20, 0x21, 0x22,
- 0x30, 0x31, 0x32,
- 0x40, 0x41, 0x42,
- 0x50, 0x51, 0x52,
- 0x60, 0x61, 0x62,
- 0x70, 0x71, 0x72]],
- expected: [
- {width: 0x05,
- height: 0x05,
- codingScheme: ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY,
- bitsPerImgPoint: 0x03,
- numOfClutEntries: 0x08,
- body: [0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90,
- 0xa0, 0xb0, 0xc0, 0xd0],
- clut: [0x00, 0x01, 0x02,
- 0x10, 0x11, 0x12,
- 0x20, 0x21, 0x22,
- 0x30, 0x31, 0x32,
- 0x40, 0x41, 0x42,
- 0x50, 0x51, 0x52,
- 0x60, 0x61, 0x62,
- 0x70, 0x71, 0x72]}]},
- {img: [0x02, 0x01, 0x06, 0x22, 0x4f, 0x33, 0x00, 0x02, 0x00, 0x08, 0x01,
- 0x06, 0x22, 0x4f, 0x33, 0x00, 0x02, 0x00, 0x08],
- iidf: [
- [/* Data offset */
- 0xff, 0xff,
- /* Header */
- 0x01, 0x06, 0x02, 0x04, 0x00, 0x0d,
- /* Image body */
- 0x40, 0x50,
- /* Clut offset */
- 0x0a, 0x0b, 0x0c,
- /* Clut entries */
- 0x01, 0x03, 0x05,
- 0x21, 0x23, 0x25,
- 0x41, 0x43, 0x45,
- 0x61, 0x63, 0x65],
- [/* Data offset */
- 0xff, 0xff,
- /* Header */
- 0x01, 0x06, 0x02, 0x04, 0x00, 0x0d,
- /* Image body */
- 0x4f, 0x5f,
- /* Clut offset */
- 0x0a, 0x0b, 0x0c,
- /* Clut entries */
- 0x11, 0x13, 0x15,
- 0x21, 0x23, 0x25,
- 0x41, 0x43, 0x45,
- 0x61, 0x63, 0x65]],
- expected: [
- {width: 0x01,
- height: 0x06,
- codingScheme: ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY,
- bitsPerImgPoint: 0x02,
- numOfClutEntries: 0x04,
- body: [0x40, 0x50],
- clut: [0x01, 0x03, 0x05,
- 0x21, 0x23, 0x25,
- 0x41, 0x43, 0x45,
- 0x61, 0x63, 0x65]},
- {width: 0x01,
- height: 0x06,
- codingScheme: ICC_IMG_CODING_SCHEME_COLOR_TRANSPARENCY,
- bitsPerImgPoint: 0x02,
- numOfClutEntries: 0x04,
- body: [0x4f, 0x5f],
- clut: [0x11, 0x13, 0x15,
- 0x21, 0x23, 0x25,
- 0x41, 0x43, 0x45,
- 0x61, 0x63, 0x65]}]}];
-
- function do_test(img, iidf, expected) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size
- buf.writeInt32(img.length * 2);
-
- // Write data
- for (let i = 0; i < img.length; i++) {
- helper.writeHexOctet(img[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(img.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let instanceIndex = 0;
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(iidf[instanceIndex].length * 2);
-
- // Write data
- for (let i = 0; i < iidf[instanceIndex].length; i++) {
- helper.writeHexOctet(iidf[instanceIndex][i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(iidf[instanceIndex].length * 2);
-
- instanceIndex++;
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- let onsuccess = function(icons) {
- equal(icons.length, expected.length);
- for (let i = 0; i < icons.length; i++) {
- let icon = icons[i];
- let exp = expected[i];
- equal(icon.width, exp.width);
- equal(icon.height, exp.height);
- equal(icon.codingScheme, exp.codingScheme);
-
- equal(icon.body.length, exp.body.length);
- for (let j = 0; j < icon.body.length; j++) {
- equal(icon.body[j], exp.body[j]);
- }
-
- equal(icon.clut.length, exp.clut.length);
- for (let j = 0; j < icon.clut.length; j++) {
- equal(icon.clut[j], exp.clut[j]);
- }
- }
- };
-
- record.readIMG(0, onsuccess);
- }
-
- for (let i = 0; i< test_data.length; i++) {
- do_test(test_data[i].img, test_data[i].iidf, test_data[i].expected);
- }
- run_next_test();
-});
-
-/**
- * Verify SimRecordHelper.readCphsInfo
- */
-add_test(function test_read_cphs_info() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let pduHelper = context.GsmPDUHelper;
- let recordHelper = context.SimRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
- let cphsPDU = new Uint8Array(3);
-
- io.loadTransparentEF = function(options) {
- if (cphsPDU) {
- // Write data size
- buf.writeInt32(cphsPDU.length * 2);
-
- // Write CPHS INFO
- for (let i = 0; i < cphsPDU.length; i++) {
- pduHelper.writeHexOctet(cphsPDU[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(cphsPDU.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- } else {
- do_print("cphsPDU[] is not set.");
- }
- };
-
- function do_test(cphsInfo, cphsSt) {
- let onsuccess = false;
- let onerror = false;
-
- delete RIL.iccInfoPrivate.cphsSt;
- cphsPDU.set(cphsInfo);
- recordHelper.readCphsInfo(() => { onsuccess = true; },
- () => { onerror = true; });
-
- ok((cphsSt) ? onsuccess : onerror);
- ok(!((cphsSt) ? onerror : onsuccess));
- if (cphsSt) {
- equal(RIL.iccInfoPrivate.cphsSt.length, cphsSt.length);
- for (let i = 0; i < cphsSt.length; i++) {
- equal(RIL.iccInfoPrivate.cphsSt[i], cphsSt[i]);
- }
- } else {
- equal(RIL.iccInfoPrivate.cphsSt, cphsSt);
- }
- }
-
- do_test([
- 0x01, // Phase 1
- 0xFF, // All available & activated
- 0x03 // All available & activated
- ],
- [
- 0x3F, // All services except ONSF(bit 8-7) are available and activated.
- 0x00 // INFO_NUM shall not be available & activated.
- ]);
-
- do_test([
- 0x02, // Phase 2
- 0xFF, // All available & activated
- 0x03 // All available & activated
- ],
- [
- 0xF3, // All services except ONSF are available and activated.
- 0x03 // INFO_NUM shall not be available & activated.
- ]);
-
- do_test([
- 0x03, // Phase 3
- 0xFF, // All available & activated
- 0x03 // All available & activated
- ],
- undefined); // RIL.iccInfoPrivate.cphsSt shall be remained as 'undefined'.
-
- run_next_test();
-});
-
-/**
- * Verify SimRecordHelper.readMBDN/SimRecordHelper.readCphsMBN
- */
-add_test(function test_read_voicemail_number() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let pduHelper = context.GsmPDUHelper;
- let recordHelper = context.SimRecordHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
- let postedMessage;
-
- worker.postMessage = function(message) {
- postedMessage = message;
- };
-
- io.loadLinearFixedEF = function(options) {
- let mbnData = [
- 0x56, 0x6F, 0x69, 0x63, 0x65, 0x6D, 0x61, 0x69,
- 0x6C, 0xFF, // Alpha Identifier: Voicemail
- 0x03, // Length of BCD number: 3
- 0x80, // TOA: Unknown
- 0x11, 0xF1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, // Dialing Number: 111
- 0xFF, // Capability/Configuration Record Identifier
- 0xFF // Extension Record Identifier
- ];
-
- // Write data size
- buf.writeInt32(mbnData.length * 2);
-
- // Write MBN
- for (let i = 0; i < mbnData.length; i++) {
- pduHelper.writeHexOctet(mbnData[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(mbnData.length * 2);
-
- options.recordSize = mbnData.length;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- function do_test(funcName, msgCount) {
- postedMessage = null;
- delete RIL.iccInfoPrivate.mbdn;
- recordHelper[funcName]();
-
- equal("iccmbdn", postedMessage.rilMessageType);
- equal("Voicemail", postedMessage.alphaId);
- equal("111", postedMessage.number);
- }
-
- do_test("readMBDN");
- do_test("readCphsMBN");
-
- run_next_test();
-});
-
-/**
- * Verify the recovery from SimRecordHelper.readCphsMBN() if MBDN is not valid
- * or is empty after SimRecordHelper.readMBDN().
- */
-add_test(function test_read_mbdn_recovered_from_cphs_mbn() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let pduHelper = context.GsmPDUHelper;
- let recordHelper = context.SimRecordHelper;
- let iccUtilsHelper = context.ICCUtilsHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- io.loadLinearFixedEF = function(options) {
- let mbnData = [
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
- 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
- ];
-
- // Write data size
- buf.writeInt32(mbnData.length * 2);
-
- // Write MBN
- for (let i = 0; i < mbnData.length; i++) {
- pduHelper.writeHexOctet(mbnData[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(mbnData.length * 2);
-
- options.recordSize = mbnData.length;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- iccUtilsHelper.isCphsServiceAvailable = function(geckoService) {
- return geckoService == "MBN";
- };
-
- let isRecovered = false;
- recordHelper.readCphsMBN = function(onComplete) {
- isRecovered = true;
- };
-
- recordHelper.readMBDN();
-
- equal(RIL.iccInfoPrivate.mbdn, undefined);
- ok(isRecovered);
-
- run_next_test();
-});
-
-/**
- * Verify reading EF_PNN with different coding scheme.
- */
-add_test(function test_pnn_with_different_coding_scheme() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let pduHelper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- let test_data = [{
- // Cell Broadcast data coding scheme - "Test1"
- pnn: [0x43, 0x06, 0x85, 0xD4, 0xF2, 0x9C, 0x1E, 0x03],
- expectedResult: "Test1"
- },{
- // UCS2 with 0x80 - "Test1"
- pnn: [0x43, 0x0C, 0x90, 0x80, 0x00, 0x54, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x31],
- expectedResult: "Test1"
- },{
- // UCS2 with 0x81 - "Mozilla\u694a"
- pnn: [0x43, 0x0E, 0x90, 0x81, 0x08, 0xd2, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0xca, 0xff, 0xff],
- expectedResult: "Mozilla\u694a"
- },{
- // UCS2 with 0x82 - "Mozilla\u694a"
- pnn: [0x43, 0x0F, 0x90, 0x82, 0x08, 0x69, 0x00, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0xca, 0xff, 0xff],
- expectedResult: "Mozilla\u694a"
- }];
-
- function do_test_pnn(pnn, expectedResult) {
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- // Write data size.
- buf.writeInt32(pnn.length * 2);
-
- // Write data.
- for (let i = 0; i < pnn.length; i++) {
- pduHelper.writeHexOctet(pnn[i]);
- }
-
- // Write string delimiter.
- buf.writeStringDelimiter(pnn.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- record.readPNN();
-
- equal(ril.iccInfoPrivate.PNN[0].fullName, expectedResult);
- // Reset PNN info for next test
- ril.iccInfoPrivate.PNN = null;
- }
-
- ril.appType = CARD_APPTYPE_SIM;
- for (let i = 0; i < test_data.length; i++) {
- do_test_pnn(test_data[i].pnn, test_data[i].expectedResult);
- }
-
- run_next_test();
-});
-
-/**
- * Verify reading EF_PNN with different content.
- */
-add_test(function test_pnn_with_different_content() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let record = context.SimRecordHelper;
- let pduHelper = context.GsmPDUHelper;
- let ril = context.RIL;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- let test_data = [{
- // [0]: {"fullName":"Test1","shortName":"Test1"}
- pnn: [0x43, 0x06, 0x85, 0xD4, 0xF2, 0x9C, 0x1E, 0x03,
- 0x45, 0x06, 0x85, 0xD4, 0xF2, 0x9C, 0x1E, 0x03],
- expectedResult: {"fullName": "Test1","shortName": "Test1"}
- },{
- // [1]: {"fullName":"Test2"}
- pnn: [0x43, 0x06, 0x85, 0xD4, 0xF2, 0x9C, 0x2E, 0x03],
- expectedResult: {"fullName": "Test2"}
- },{
- // [2]: undefined
- pnn: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
- },{
- // [3]: {"fullName": "Test4"}
- pnn: [0x43, 0x06, 0x85, 0xD4, 0xF2, 0x9C, 0x4E, 0x03],
- expectedResult: {"fullName": "Test4"}
- },{
- // [4]: undefined
- pnn: [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF],
- }];
-
- function do_test_pnn() {
- ril.iccIO = function fakeIccIO(options) {
- let index = options.p1 - 1;
- let pnn = test_data[index].pnn;
-
- // Write data size.
- buf.writeInt32(pnn.length * 2);
-
- // Write data.
- for (let i = 0; i < pnn.length; i++) {
- pduHelper.writeHexOctet(pnn[i]);
- }
-
- // Write string delimiter.
- buf.writeStringDelimiter(pnn.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- options.p1 = 1;
- options.totalRecords = test_data.length;
-
- ril.iccIO(options);
- };
-
- record.readPNN();
-
- equal(test_data.length, ril.iccInfoPrivate.PNN.length);
- for (let i = 0; i < test_data.length; i++) {
- if (test_data[i].expectedResult) {
- equal(test_data[i].expectedResult.fullName,
- ril.iccInfoPrivate.PNN[i].fullName);
- equal(test_data[i].expectedResult.shortName,
- ril.iccInfoPrivate.PNN[i].shortName);
- } else {
- equal(test_data[i].expectedResult, ril.iccInfoPrivate.PNN[i]);
- }
- }
- }
-
- ril.appType = CARD_APPTYPE_SIM;
- do_test_pnn();
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_ruim.js b/dom/system/gonk/tests/test_ril_worker_ruim.js
deleted file mode 100644
index 0ddc10f29..000000000
--- a/dom/system/gonk/tests/test_ril_worker_ruim.js
+++ /dev/null
@@ -1,328 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify RUIM Service.
- */
-add_test(function test_is_ruim_service_available() {
- let worker = newWorker();
- let context = worker.ContextPool._contexts[0];
- context.RIL._isCdma = true;
- context.RIL.appType = CARD_APPTYPE_RUIM;
-
- function test_table(cst, geckoService, enabled) {
- context.RIL.iccInfoPrivate.cst = cst;
- equal(context.ICCUtilsHelper.isICCServiceAvailable(geckoService),
- enabled);
- }
-
- test_table([0x0, 0x0, 0x0, 0x0, 0x03], "SPN", true);
- test_table([0x0, 0x0, 0x0, 0x03, 0x0], "SPN", false);
- test_table([0x0, 0x0C, 0x0, 0x0, 0x0], "ENHANCED_PHONEBOOK", true);
- test_table([0x0, 0x0, 0x0, 0x0, 0x0], "ENHANCED_PHONEBOOK", false);
-
- run_next_test();
-});
-
-/**
- * Verify EF_PATH for RUIM file.
- */
-add_test(function test_ruim_file_path_id() {
- let worker = newWorker();
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let ICCFileHelper = context.ICCFileHelper;
-
- RIL.appType = CARD_APPTYPE_RUIM;
- equal(ICCFileHelper.getEFPath(ICC_EF_CSIM_CST),
- EF_PATH_MF_SIM + EF_PATH_DF_CDMA);
-
- run_next_test();
-});
-
-add_test(function test_fetch_ruim_recodes() {
- let worker = newWorker();
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let ruimHelper = context.RuimRecordHelper;
-
- function testFetchRuimRecordes(expectCalled) {
- let ifCalled = [];
-
- ruimHelper.getIMSI_M = function() {
- ifCalled.push("getIMSI_M");
- };
-
- ruimHelper.readCST = function() {
- ifCalled.push("readCST");
- };
-
- ruimHelper.readCDMAHome = function() {
- ifCalled.push("readCDMAHome");
- };
-
- RIL.getCdmaSubscription = function() {
- ifCalled.push("getCdmaSubscription");
- };
-
- ruimHelper.fetchRuimRecords();
-
- for (let i = 0; i < expectCalled.length; i++ ) {
- if (ifCalled[i] != expectCalled[i]) {
- do_print(expectCalled[i] + " is not called.");
- ok(false);
- }
- }
- }
-
- let expectCalled = ["getIMSI_M", "readCST", "readCDMAHome",
- "getCdmaSubscription"];
- testFetchRuimRecordes(expectCalled);
-
- run_next_test();
-});
-
-/**
- * Verify RuimRecordHelper.decodeIMSIValue
- */
-add_test(function test_decode_imsi_value() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
-
- function testDecodeImsiValue(encoded, length, expect) {
- let decoded = context.RuimRecordHelper.decodeIMSIValue(encoded, length);
-
- equal(expect, decoded);
- }
-
- testDecodeImsiValue( 99, 2, "00");
- testDecodeImsiValue( 90, 2, "01");
- testDecodeImsiValue( 19, 2, "20");
- testDecodeImsiValue( 23, 2, "34");
- testDecodeImsiValue(999, 3, "000");
- testDecodeImsiValue(990, 3, "001");
- testDecodeImsiValue(909, 3, "010");
- testDecodeImsiValue( 99, 3, "100");
- testDecodeImsiValue(901, 3, "012");
- testDecodeImsiValue( 19, 3, "120");
- testDecodeImsiValue( 91, 3, "102");
- testDecodeImsiValue(199, 3, "200");
- testDecodeImsiValue(123, 3, "234");
- testDecodeImsiValue(578, 3, "689");
-
- run_next_test();
-});
-
-/**
- * Verify RuimRecordHelper.getIMSI_M
- */
-add_test(function test_get_imsi_m() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- function testDecodeImsi(encodedImsi, expectedImsi) {
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(encodedImsi.length * 2);
-
- // Write imsi
- for (let i = 0; i < encodedImsi.length; i++) {
- helper.writeHexOctet(encodedImsi[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(encodedImsi.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- context.RuimRecordHelper.getIMSI_M();
- let imsi = context.RIL.iccInfoPrivate.imsi;
-
- equal(expectedImsi, imsi)
- }
-
- let imsi_1 = "466050081062861";
- testDecodeImsi([0x0, 0xe5, 0x03, 0xee, 0xca, 0x17, 0x5e, 0x80, 0x63, 0x01], imsi_1);
-
- let imsi_2 = "460038351175976";
- testDecodeImsi([0x0, 0xd4, 0x02, 0x61, 0x97, 0x01, 0x5c, 0x80, 0x67, 0x01], imsi_2);
-
- run_next_test();
-});
-
-/**
- * Verify RuimRecordHelper.readCDMAHome
- */
-add_test(function test_read_cdmahome() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- io.loadLinearFixedEF = function fakeLoadLinearFixedEF(options) {
- let cdmaHome = [0xc1, 0x34, 0xff, 0xff, 0x00];
-
- // Write data size
- buf.writeInt32(cdmaHome.length * 2);
-
- // Write cdma home file.
- for (let i = 0; i < cdmaHome.length; i++) {
- helper.writeHexOctet(cdmaHome[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(cdmaHome.length * 2);
-
- // We just have 1 test record.
-
- options.totalRecords = 1;
- if (options.callback) {
- options.callback(options);
- }
- };
-
- function testCdmaHome(expectedSystemIds, expectedNetworkIds) {
- context.RuimRecordHelper.readCDMAHome();
- let cdmaHome = context.RIL.cdmaHome;
- for (let i = 0; i < expectedSystemIds.length; i++) {
- equal(cdmaHome.systemId[i], expectedSystemIds[i]);
- equal(cdmaHome.networkId[i], expectedNetworkIds[i]);
- }
- equal(cdmaHome.systemId.length, expectedSystemIds.length);
- equal(cdmaHome.networkId.length, expectedNetworkIds.length);
- }
-
- testCdmaHome([13505], [65535]);
-
- run_next_test();
-});
-
-/**
- * Verify reading CDMA EF_SPN
- */
-add_test(function test_read_cdmaspn() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let buf = context.Buf;
- let io = context.ICCIOHelper;
-
- function testReadSpn(file, expectedSpn, expectedDisplayCondition) {
- io.loadTransparentEF = function fakeLoadTransparentEF(options) {
- // Write data size
- buf.writeInt32(file.length * 2);
-
- // Write file.
- for (let i = 0; i < file.length; i++) {
- helper.writeHexOctet(file[i]);
- }
-
- // Write string delimiter
- buf.writeStringDelimiter(file.length * 2);
-
- if (options.callback) {
- options.callback(options);
- }
- };
-
- context.RuimRecordHelper.readSPN();
- equal(context.RIL.iccInfo.spn, expectedSpn);
- equal(context.RIL.iccInfoPrivate.spnDisplayCondition,
- expectedDisplayCondition);
- }
-
- testReadSpn([0x01, 0x04, 0x06, 0x4e, 0x9e, 0x59, 0x2a, 0x96,
- 0xfb, 0x4f, 0xe1, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
- 0xff, 0xff, 0xff],
- String.fromCharCode(0x4e9e) +
- String.fromCharCode(0x592a) +
- String.fromCharCode(0x96fb) +
- String.fromCharCode(0x4fe1),
- 0x1);
-
- // Test when there's no tailing 0xff in spn string.
- testReadSpn([0x01, 0x04, 0x06, 0x4e, 0x9e, 0x59, 0x2a, 0x96,
- 0xfb, 0x4f, 0xe1],
- String.fromCharCode(0x4e9e) +
- String.fromCharCode(0x592a) +
- String.fromCharCode(0x96fb) +
- String.fromCharCode(0x4fe1),
- 0x1);
-
- run_next_test();
-});
-
-/**
- * Verify display condition for CDMA.
- */
-add_test(function test_cdma_spn_display_condition() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
- let context = worker.ContextPool._contexts[0];
- let RIL = context.RIL;
- let ICCUtilsHelper = context.ICCUtilsHelper;
-
- // Set cdma.
- RIL._isCdma = true;
-
- // Test updateDisplayCondition runs before any of SIM file is ready.
- equal(ICCUtilsHelper.updateDisplayCondition(), true);
- equal(RIL.iccInfo.isDisplayNetworkNameRequired, true);
- equal(RIL.iccInfo.isDisplaySpnRequired, false);
-
- // Test with value.
- function testDisplayCondition(ruimDisplayCondition,
- homeSystemIds, homeNetworkIds,
- currentSystemId, currentNetworkId,
- expectUpdateDisplayCondition,
- expectIsDisplaySPNRequired) {
- RIL.iccInfoPrivate.spnDisplayCondition = ruimDisplayCondition;
- RIL.cdmaHome = {
- systemId: homeSystemIds,
- networkId: homeNetworkIds
- };
- RIL.voiceRegistrationState.cell = {
- cdmaSystemId: currentSystemId,
- cdmaNetworkId: currentNetworkId
- };
-
- equal(ICCUtilsHelper.updateDisplayCondition(), expectUpdateDisplayCondition);
- equal(RIL.iccInfo.isDisplayNetworkNameRequired, false);
- equal(RIL.iccInfo.isDisplaySpnRequired, expectIsDisplaySPNRequired);
- };
-
- // SPN is not required when ruimDisplayCondition is false.
- testDisplayCondition(0x0, [123], [345], 123, 345, true, false);
-
- // System id and network id are all match.
- testDisplayCondition(0x1, [123], [345], 123, 345, true, true);
-
- // Network is 65535, we should only need to match system id.
- testDisplayCondition(0x1, [123], [65535], 123, 345, false, true);
-
- // Not match.
- testDisplayCondition(0x1, [123], [456], 123, 345, true, false);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_sms.js b/dom/system/gonk/tests/test_ril_worker_sms.js
deleted file mode 100644
index 7c1b972a7..000000000
--- a/dom/system/gonk/tests/test_ril_worker_sms.js
+++ /dev/null
@@ -1,273 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "gSmsSegmentHelper", function() {
- let ns = {};
- Cu.import("resource://gre/modules/SmsSegmentHelper.jsm", ns);
- return ns.SmsSegmentHelper;
-});
-
-const ESCAPE = "\uffff";
-const RESCTL = "\ufffe";
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify receiving SMS-DELIVERY messages
- */
-
-function hexToNibble(nibble) {
- nibble &= 0x0f;
- if (nibble < 10) {
- nibble += 48; // ASCII '0'
- } else {
- nibble += 55; // ASCII 'A'
- }
- return nibble;
-}
-
-function pduToParcelData(pdu) {
- let dataLength = 4 + pdu.length * 4 + 4;
- let data = new Uint8Array(dataLength);
- let offset = 0;
-
- // String length
- data[offset++] = pdu.length & 0xFF;
- data[offset++] = (pdu.length >> 8) & 0xFF;
- data[offset++] = (pdu.length >> 16) & 0xFF;
- data[offset++] = (pdu.length >> 24) & 0xFF;
-
- // PDU data
- for (let i = 0; i < pdu.length; i++) {
- let hi = (pdu[i] >>> 4) & 0x0F;
- let lo = pdu[i] & 0x0F;
-
- data[offset++] = hexToNibble(hi);
- data[offset++] = 0;
- data[offset++] = hexToNibble(lo);
- data[offset++] = 0;
- }
-
- // String delimitor
- data[offset++] = 0;
- data[offset++] = 0;
- data[offset++] = 0;
- data[offset++] = 0;
-
- return data;
-}
-
-function compose7bitPdu(lst, sst, data, septets) {
- if ((lst == 0) && (sst == 0)) {
- return [0x00, // SMSC
- PDU_MTI_SMS_DELIVER, // firstOctet
- 1, 0x00, 0, // senderAddress
- 0x00, // protocolIdentifier
- PDU_DCS_MSG_CODING_7BITS_ALPHABET, // dataCodingScheme
- 0, 0, 0, 0, 0, 0, 0, // y m d h m s tz
- septets] // userDataLength
- .concat(data);
- }
-
- return [0x00, // SMSC
- PDU_MTI_SMS_DELIVER | PDU_UDHI, // firstOctet
- 1, 0x00, 0, // senderAddress
- 0x00, // protocolIdentifier
- PDU_DCS_MSG_CODING_7BITS_ALPHABET, // dataCodingScheme
- 0, 0, 0, 0, 0, 0, 0, // y m d h m s tz
- 8 + septets, // userDataLength
- 6, // user data header length
- PDU_IEI_NATIONAL_LANGUAGE_LOCKING_SHIFT, 1, lst, // PDU_IEI_NATIONAL_LANGUAGE_LOCKING_SHIFT
- PDU_IEI_NATIONAL_LANGUAGE_SINGLE_SHIFT, 1, sst] // PDU_IEI_NATIONAL_LANGUAGE_SINGLE_SHIFT
- .concat(data);
-}
-
-function composeUcs2Pdu(rawBytes) {
- return [0x00, // SMSC
- PDU_MTI_SMS_DELIVER, // firstOctet
- 1, 0x00, 0, // senderAddress
- 0x00, // protocolIdentifier
- PDU_DCS_MSG_CODING_16BITS_ALPHABET, // dataCodingScheme
- 0, 0, 0, 0, 0, 0, 0, // y m d h m s tz
- rawBytes.length] // userDataLength
- .concat(rawBytes);
-}
-
-function newSmsParcel(pdu) {
- return newIncomingParcel(-1,
- RESPONSE_TYPE_UNSOLICITED,
- UNSOLICITED_RESPONSE_NEW_SMS,
- pduToParcelData(pdu));
-}
-
-function removeSpecialChar(str, needle) {
- for (let i = 0; i < needle.length; i++) {
- let pos;
- while ((pos = str.indexOf(needle[i])) >= 0) {
- str = str.substring(0, pos) + str.substring(pos + 1);
- }
- }
- return str;
-}
-
-function newWriteHexOctetAsUint8Worker() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- context.GsmPDUHelper.writeHexOctet = function(value) {
- context.Buf.writeUint8(value);
- };
-
- return worker;
-}
-
-function add_test_receiving_sms(expected, pdu) {
- add_test(function test_receiving_sms() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- do_print("fullBody: " + message.fullBody);
- equal(expected, message.fullBody)
- }
- });
-
- do_print("expect: " + expected);
- do_print("pdu: " + pdu);
- worker.onRILMessage(0, newSmsParcel(pdu));
-
- run_next_test();
- });
-}
-
-var test_receiving_7bit_alphabets__worker;
-function test_receiving_7bit_alphabets(lst, sst) {
- if (!test_receiving_7bit_alphabets__worker) {
- test_receiving_7bit_alphabets__worker = newWriteHexOctetAsUint8Worker();
- }
- let worker = test_receiving_7bit_alphabets__worker;
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let buf = context.Buf;
-
- function get7bitRawBytes(expected) {
- buf.outgoingIndex = 0;
- helper.writeStringAsSeptets(expected, 0, lst, sst);
-
- let subArray = buf.outgoingBytes.subarray(0, buf.outgoingIndex);
- return Array.slice(subArray);
- }
-
- let langTable = PDU_NL_LOCKING_SHIFT_TABLES[lst];
- let langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[sst];
-
- let text = removeSpecialChar(langTable + langShiftTable, ESCAPE + RESCTL);
- for (let i = 0; i < text.length;) {
- let len = Math.min(70, text.length - i);
- let expected = text.substring(i, i + len);
- let septets =
- gSmsSegmentHelper.countGsm7BitSeptets(expected, langTable, langShiftTable);
- let rawBytes = get7bitRawBytes(expected);
- let pdu = compose7bitPdu(lst, sst, rawBytes, septets);
- add_test_receiving_sms(expected, pdu);
-
- i += len;
- }
-}
-
-function test_receiving_ucs2_alphabets(text) {
- let worker = test_receiving_7bit_alphabets__worker;
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
-
- function getUCS2RawBytes(expected) {
- buf.outgoingIndex = 0;
- context.GsmPDUHelper.writeUCS2String(expected);
-
- let subArray = buf.outgoingBytes.subarray(0, buf.outgoingIndex);
- return Array.slice(subArray);
- }
-
- for (let i = 0; i < text.length;) {
- let len = Math.min(70, text.length - i);
- let expected = text.substring(i, i + len);
- let rawBytes = getUCS2RawBytes(expected);
- let pdu = composeUcs2Pdu(rawBytes);
- add_test_receiving_sms(expected, pdu);
-
- i += len;
- }
-}
-
-var ucs2str = "";
-for (let lst = 0; lst < PDU_NL_LOCKING_SHIFT_TABLES.length; lst++) {
- ucs2str += PDU_NL_LOCKING_SHIFT_TABLES[lst];
- for (let sst = 0; sst < PDU_NL_SINGLE_SHIFT_TABLES.length; sst++) {
- test_receiving_7bit_alphabets(lst, sst);
-
- if (lst == 0) {
- ucs2str += PDU_NL_SINGLE_SHIFT_TABLES[sst];
- }
- }
-}
-test_receiving_ucs2_alphabets(ucs2str);
-
-// Bug 820220: B2G SMS: wrong order and truncated content in multi-part messages
-add_test(function test_sendSMS_UCS2_without_langIndex_langShiftIndex_defined() {
- let worker = newWriteHexOctetAsUint8Worker();
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.sendParcel = function() {
- // Each sendParcel() call represents one outgoing segment of a multipart
- // SMS message. Here, we have the first segment send, so it's "Hello "
- // only.
- //
- // 4(parcel size) + 4(request type) + 4(token)
- // + 4(two messages) + 4(null SMSC) + 4(message string length)
- // + 1(first octet) + 1(message reference)
- // + 2(DA len, TOA) + 4(addr)
- // + 1(pid) + 1(dcs)
- // + 1(UDL) + 6(UDHL, type, len, ref, max, seq)
- // + 12(2 * strlen("Hello "))
- // + 4(two delimitors) = 57
- //
- // If we have additional 6(type, len, langIndex, type len, langShiftIndex)
- // octets here, then bug 809553 is not fixed.
- equal(this.outgoingIndex, 57);
-
- run_next_test();
- };
-
- context.RIL.sendSMS({
- number: "1",
- segmentMaxSeq: 2,
- fullBody: "Hello World!",
- dcs: PDU_DCS_MSG_CODING_16BITS_ALPHABET,
- segmentRef16Bit: false,
- userDataHeaderLength: 5,
- requestStatusReport: true,
- segments: [
- {
- body: "Hello ",
- encodedBodyLength: 12,
- }, {
- body: "World!",
- encodedBodyLength: 12,
- }
- ],
- });
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_sms_cdma.js b/dom/system/gonk/tests/test_ril_worker_sms_cdma.js
deleted file mode 100644
index 85d0b6e0c..000000000
--- a/dom/system/gonk/tests/test_ril_worker_sms_cdma.js
+++ /dev/null
@@ -1,298 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/*
- * Helper function to covert a HEX string to a byte array.
- *
- * @param hexString
- * A hexadecimal string of which the length is even.
- */
-function hexStringToBytes(hexString) {
- let bytes = [];
-
- let length = hexString.length;
-
- for (let i = 0; i < length; i += 2) {
- bytes.push(Number.parseInt(hexString.substr(i, 2), 16));
- }
-
- return bytes;
-}
-
-/*
- * Helper function to covert a byte array to a HEX string.
- *
- * @param bytes
- * Could be a regular byte array or Uint8Array.
- */
-function bytesToHexString(bytes) {
- let hexString = "";
- let hex;
-
- for (let i = 0; i < bytes.length; i++) {
- hex = bytes[i].toString(16).toUpperCase();
- if (hex.length === 1) {
- hexString += "0";
- }
- hexString += hex;
- }
-
- return hexString;
-}
-
-/*
- * Helper function to ecode Opaque UserData
- *
- * @param msg_type
- * PDU_CDMA_MSG_TYPE_SUBMIT or PDU_CDMA_MSG_TYPE_DELIVER
- * @param data
- * The byte array of opaque data to be encoded.
- */
-function encodeOpaqueUserData(bitBufferHelper, options) {
- let bearerDataBuffer = [];
- bitBufferHelper.startWrite(bearerDataBuffer);
-
- // Msg-Id
- bitBufferHelper.writeBits(PDU_CDMA_MSG_USERDATA_MSG_ID, 8);
- bitBufferHelper.writeBits(3, 8);
- bitBufferHelper.writeBits(options.msg_type, 4); // MSG_TYPE
- bitBufferHelper.writeBits(1, 16); // MSG_ID
- bitBufferHelper.flushWithPadding(); // HEADER_IND (1) + RESERVED (3)
-
- // User Data
- bitBufferHelper.writeBits(PDU_CDMA_MSG_USERDATA_BODY, 8);
- let dataLength = options.data.length;
- bitBufferHelper.writeBits(2 + dataLength, 8); // 2 bytes for MSG_ENCODING, NUM_FIELDS
- bitBufferHelper.writeBits(PDU_CDMA_MSG_CODING_OCTET, 5); //MSG_ENCODING
- // MSG_TYPE is omitted if MSG_ENCODING is CODING_OCTET
- bitBufferHelper.writeBits(dataLength, 8); // NUM_FIELDS
- for (let i = 0; i < dataLength; i++) { // CHARi
- bitBufferHelper.writeBits(options.data[i], 8);
- }
- bitBufferHelper.flushWithPadding(); // RESERVED (3 filling bits)
-
- return bearerDataBuffer;
-}
-
-function newSmsParcel(cdmaPduHelper, pdu) {
- return newIncomingParcel(-1,
- RESPONSE_TYPE_UNSOLICITED,
- UNSOLICITED_RESPONSE_CDMA_NEW_SMS,
- pduToParcelData(cdmaPduHelper, pdu));
-}
-
-/*
- * Helper function to encode PDU into Parcel.
- * See ril_cdma_sms.h for the structure definition of RIL_CDMA_SMS_Message
- *
- * @param teleservice
- * The Teleservice-Id of this PDU.
- * See PDU_CDMA_MSG_TELESERIVCIE_ID_XXX in ril_const.js.
- * @param address
- * The Orginating or Destinating address.
- * @param bearerData
- * The byte array of the encoded bearer data.
- */
-function pduToParcelData(cdmaPduHelper, pdu) {
-
- let addrInfo = cdmaPduHelper.encodeAddr(pdu.address);
- // Teleservice, isServicePresent, ServiceCategory,
- // addrInfo {digitMode, numberMode, numberType, numberPlan, address.length, address}
- // Sub Address
- // bearerData length, bearerData.
- let dataLength = 4 + 4 + 4
- + (5 + addrInfo.address.length) * 4
- + 3 * 4
- + 4 + pdu.bearerData.length * 4;
-
- let data = new Uint8Array(dataLength);
- let offset = 0;
-
- function writeInt(value) {
- data[offset++] = value & 0xFF;
- data[offset++] = (value >> 8) & 0xFF;
- data[offset++] = (value >> 16) & 0xFF;
- data[offset++] = (value >> 24) & 0xFF;
- }
-
- function writeByte(value) {
- data[offset++] = value & 0xFF;
- data[offset++] = 0;
- data[offset++] = 0;
- data[offset++] = 0;
- }
-
- // Teleservice
- writeInt(pdu.teleservice);
-
- // isServicePresent
- writeByte(0);
-
- // ServiceCategory
- writeInt(PDU_CDMA_MSG_CATEGORY_UNSPEC);
-
- // AddrInfo
- writeByte(addrInfo.digitMode);
- writeByte(addrInfo.numberMode);
- writeByte(addrInfo.numberType);
- writeByte(addrInfo.numberPlan);
- let addressLength = addrInfo.address.length;
- writeByte(addressLength);
- for (let i = 0; i < addressLength; i++) {
- writeByte(addrInfo.address[i]);
- }
-
- // Subaddress
- writeByte(0);
- writeByte(0);
- writeByte(0);
-
- // Bearer Data Length
- dataLength = pdu.bearerData.length;
- writeByte(dataLength);
-
- // Bearer Data
- for (let i = 0; i < dataLength; i++) {
- writeByte(pdu.bearerData[i]);
- }
-
- return data;
-}
-
-/**
- * Verify CDMA SMS Delivery ACK Message.
- */
-add_test(function test_processCdmaSmsStatusReport() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- function test_StatusReport(errorClass, msgStatus) {
- let msgId = 0;
- let sentSmsMap = context.RIL._pendingSentSmsMap;
-
- sentSmsMap[msgId] = {};
-
- let message = {
- SMSC: "",
- mti: 0,
- udhi: 0,
- sender: "0987654321",
- recipient: null,
- pid: PDU_PID_DEFAULT,
- epid: PDU_PID_DEFAULT,
- dcs: 0,
- mwi: null,
- replace: false,
- header: null,
- body: "Status: Sent, Dest: 0987654321",
- data: null,
- timestamp: new Date().valueOf(),
- language: null,
- status: null,
- scts: null,
- dt: null,
- encoding: PDU_CDMA_MSG_CODING_7BITS_ASCII,
- messageClass: GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- messageType: PDU_CDMA_MSG_TYPE_P2P,
- serviceCategory: 0,
- subMsgType: PDU_CDMA_MSG_TYPE_DELIVER_ACK,
- msgId: msgId,
- errorClass: errorClass,
- msgStatus: msgStatus
- };
-
- context.RIL._processCdmaSmsStatusReport(message);
-
- let postedMessage = workerHelper.postedMessage;
-
- // Check if pending token is removed.
- ok((errorClass === 2) ? !!sentSmsMap[msgId] : !sentSmsMap[msgId]);
-
- // Check the response message accordingly.
- if (errorClass === -1) {
- // Check if the report is treated as normal incoming SMS
- equal("sms-received", postedMessage.rilMessageType);
- } else if (errorClass === 2) {
- // Do nothing.
- } else {
- // Check Delivery Status
- if (errorClass === 0) {
- equal(postedMessage.deliveryStatus, GECKO_SMS_DELIVERY_STATUS_SUCCESS);
- } else {
- equal(postedMessage.deliveryStatus, GECKO_SMS_DELIVERY_STATUS_ERROR);
- }
- }
- }
-
- test_StatusReport(-1, -1); // Message Status Sub-parameter is absent.
- test_StatusReport(0, 0); // 00|000000: no error|Message accepted
- test_StatusReport(2, 4); // 10|000100: temporary condition|Network congestion
- test_StatusReport(3, 5); // 11|000101: permanent condition|Network error
-
- run_next_test();
-});
-
-/**
- * Verify WAP Push over CDMA SMS Message.
- */
-add_test(function test_processCdmaSmsWapPush() {
- let workerHelper = newInterceptWorker(),
- worker = workerHelper.worker,
- context = worker.ContextPool._contexts[0],
- bitBufferHelper = context.BitBufferHelper,
- cdmaPduHelper = context.CdmaPDUHelper;
-
- function test_CdmaSmsWapPdu(wdpData, reversed) {
- let orig_address = "0987654321",
- hexString,
- fullDataHexString = "";
-
- for (let i = 0; i < wdpData.length; i++) {
- let dataIndex = (reversed) ? (wdpData.length - i - 1) : i;
- hexString = "00"; // MSG_TYPE
- hexString += bytesToHexString([wdpData.length]); // TOTAL_SEG
- hexString += bytesToHexString([dataIndex]); // SEG_NUM (zero-based)
- if ((dataIndex === 0)) {
- hexString += "23F00B84"; // SOURCE_PORT, DEST_PORT for 1st segment
- }
- hexString += wdpData[dataIndex]; // WDP DATA
-
- do_print("hexString: " + hexString);
-
- fullDataHexString += wdpData[i];
-
- let pdu = {
- teleservice: PDU_CDMA_MSG_TELESERIVCIE_ID_WAP,
- address: orig_address,
- bearerData: encodeOpaqueUserData(bitBufferHelper,
- { msg_type: PDU_CDMA_MSG_TYPE_DELIVER,
- data: hexStringToBytes(hexString) })
- };
-
- worker.onRILMessage(0, newSmsParcel(cdmaPduHelper, pdu));
- }
-
- let postedMessage = workerHelper.postedMessage;
-
- do_print("fullDataHexString: " + fullDataHexString);
-
- equal("sms-received", postedMessage.rilMessageType);
- equal(PDU_CDMA_MSG_TELESERIVCIE_ID_WAP, postedMessage.teleservice);
- equal(orig_address, postedMessage.sender);
- equal(0x23F0, postedMessage.header.originatorPort);
- equal(0x0B84, postedMessage.header.destinationPort);
- equal(fullDataHexString, bytesToHexString(postedMessage.data));
- }
-
- // Verify Single WAP PDU
- test_CdmaSmsWapPdu(["000102030405060708090A0B0C0D0E0F"]);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_sms_cdmapduhelper.js b/dom/system/gonk/tests/test_ril_worker_sms_cdmapduhelper.js
deleted file mode 100644
index 276728f2f..000000000
--- a/dom/system/gonk/tests/test_ril_worker_sms_cdmapduhelper.js
+++ /dev/null
@@ -1,210 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify CdmaPDUHelper#encodeUserDataReplyOption.
- */
-add_test(function test_CdmaPDUHelper_encodeUserDataReplyOption() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
- let context = worker.ContextPool._contexts[0];
-
- let testDataBuffer = [];
- context.BitBufferHelper.startWrite(testDataBuffer);
-
- let helper = context.CdmaPDUHelper;
- helper.encodeUserDataReplyOption({requestStatusReport: true});
-
- let expectedDataBuffer = [PDU_CDMA_MSG_USERDATA_REPLY_OPTION, 0x01, 0x40];
-
- equal(testDataBuffer.length, expectedDataBuffer.length);
-
- for (let i = 0; i < expectedDataBuffer.length; i++) {
- equal(testDataBuffer[i], expectedDataBuffer[i]);
- }
-
- run_next_test();
-});
-
-/**
- * Verify CdmaPDUHelper#cdma_decodeUserDataMsgStatus.
- */
-add_test(function test_CdmaPDUHelper_decodeUserDataMsgStatus() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
- let context = worker.ContextPool._contexts[0];
-
- let helper = context.CdmaPDUHelper;
- function test_MsgStatus(octet) {
- let testDataBuffer = [octet];
- context.BitBufferHelper.startRead(testDataBuffer);
- let result = helper.decodeUserDataMsgStatus();
-
- equal(result.errorClass, octet >>> 6);
- equal(result.msgStatus, octet & 0x3F);
- }
-
- // 00|000000: no error|Message accepted
- test_MsgStatus(0x00);
-
- // 10|000100: temporary condition|Network congestion
- test_MsgStatus(0x84);
-
- // 11|000101: permanent condition|Network error
- test_MsgStatus(0xC5);
-
- run_next_test();
-});
-
-/**
- * Verify CdmaPDUHelper#decodeCdmaPDUMsg.
- * - encoding by shift-jis
- */
-add_test(function test_CdmaPDUHelper_decodeCdmaPDUMsg_Shift_jis() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
- let context = worker.ContextPool._contexts[0];
-
- let helper = context.CdmaPDUHelper;
- function test_decodePDUMsg(testDataBuffer, expected, encoding, msgType, msgBodySize) {
- context.BitBufferHelper.startRead(testDataBuffer);
- let result = helper.decodeCdmaPDUMsg(encoding, msgType, msgBodySize);
- equal(result, expected);
- }
-
- // Shift-JIS has 1 byte and 2 byte code for one character and has some types of characters:
- // Hiragana, Kanji, Katakana(fullwidth, halfwidth)...
- // This test is a combination of 1 byte and 2 byte code and types of characters.
-
- // test case 1
- let testDataBuffer1 = [0x82, 0x58, 0x33, 0x41, 0x61, 0x33, 0x82, 0x60,
- 0x82, 0x81, 0x33, 0xB1, 0xAF, 0x33, 0x83, 0x41,
- 0x83, 0x96, 0x33, 0x82, 0xA0, 0x33, 0x93, 0xFA,
- 0x33, 0x3A, 0x3C, 0x33, 0x81, 0x80, 0x81, 0x8E,
- 0x33, 0x31, 0x82, 0x51, 0x41, 0x61, 0x82, 0x51,
- 0x82, 0x60, 0x82, 0x81, 0x82, 0x51, 0xB1, 0xAF,
- 0x82, 0x51, 0x83, 0x41, 0x83, 0x96, 0x82, 0x51,
- 0x82, 0xA0, 0x82, 0x51, 0x93, 0xFA, 0x82, 0x51,
- 0x3A, 0x3C, 0x82, 0x51, 0x81, 0x80, 0x81, 0x8E,
- 0x82, 0x51];
-
- test_decodePDUMsg(
- testDataBuffer1,
- "\uFF19\u0033\u0041\u0061\u0033\uFF21\uFF41\u0033\uFF71\uFF6F\u0033\u30A2\u30F6\u0033\u3042\u0033\u65E5\u0033\u003A\u003C\u0033\u00F7\u2103\u0033\u0031\uFF12\u0041\u0061\uFF12\uFF21\uFF41\uFF12\uFF71\uFF6F\uFF12\u30A2\u30F6\uFF12\u3042\uFF12\u65E5\uFF12\u003A\u003C\uFF12\u00F7\u2103\uFF12",
- PDU_CDMA_MSG_CODING_SHIFT_JIS,
- undefined,
- testDataBuffer1.length
- );
-
- // test case 2
- let testDataBuffer2 = [0x31, 0x51, 0x63, 0x82, 0x58, 0x51, 0x63, 0x82,
- 0x60, 0x82, 0x81, 0x51, 0x63, 0xB1, 0xAF, 0x51,
- 0x63, 0x83, 0x41, 0x83, 0x96, 0x51, 0x63, 0x82,
- 0xA0, 0x51, 0x63, 0x93, 0xFA, 0x51, 0x63, 0x3A,
- 0x3C, 0x51, 0x63, 0x81, 0x80, 0x81, 0x8E, 0x51,
- 0x63, 0x31, 0x82, 0x70, 0x82, 0x85, 0x82, 0x58,
- 0x82, 0x70, 0x82, 0x85, 0x41, 0x61, 0x82, 0x70,
- 0x82, 0x85, 0xB1, 0xAF, 0x82, 0x70, 0x82, 0x85,
- 0x83, 0x41, 0x83, 0x96, 0x82, 0x70, 0x82, 0x85,
- 0x82, 0xA0, 0x82, 0x70, 0x82, 0x85, 0x93, 0xFA,
- 0x82, 0x70, 0x82, 0x85, 0x3A, 0x3C, 0x82, 0x70,
- 0x82, 0x85, 0x81, 0x80, 0x81, 0x8E, 0x82, 0x70,
- 0x82, 0x85];
-
- test_decodePDUMsg(
- testDataBuffer2,
- "\u0031\u0051\u0063\uFF19\u0051\u0063\uFF21\uFF41\u0051\u0063\uFF71\uFF6F\u0051\u0063\u30A2\u30F6\u0051\u0063\u3042\u0051\u0063\u65E5\u0051\u0063\u003A\u003C\u0051\u0063\u00F7\u2103\u0051\u0063\u0031\uFF31\uFF45\uFF19\uFF31\uFF45\u0041\u0061\uFF31\uFF45\uFF71\uFF6F\uFF31\uFF45\u30A2\u30F6\uFF31\uFF45\u3042\uFF31\uFF45\u65E5\uFF31\uFF45\u003A\u003C\uFF31\uFF45\u00F7\u2103\uFF31\uFF45",
- PDU_CDMA_MSG_CODING_SHIFT_JIS,
- undefined,
- testDataBuffer2.length
- );
-
- // test case 3
- let testDataBuffer3 = [0x31, 0xC2, 0xDF, 0x82, 0x58, 0xC2, 0xDF, 0x41,
- 0x61, 0xC2, 0xDF, 0x82, 0x60, 0x82, 0x81, 0xC2,
- 0xDF, 0x83, 0x41, 0x83, 0x96, 0xC2, 0xDF, 0x82,
- 0xA0, 0xC2, 0xDF, 0x93, 0xFA, 0xC2, 0xDF, 0x3A,
- 0x3C, 0xC2, 0xDF, 0x81, 0x80, 0x81, 0x8E, 0xC2,
- 0xDF, 0x31, 0x83, 0x51, 0x83, 0x87, 0x82, 0x58,
- 0x83, 0x51, 0x83, 0x87, 0x41, 0x61, 0x83, 0x51,
- 0x83, 0x87, 0x82, 0x60, 0x82, 0x81, 0x83, 0x51,
- 0x83, 0x87, 0xB1, 0xAF, 0x83, 0x51, 0x83, 0x87,
- 0x82, 0xA0, 0x83, 0x51, 0x83, 0x87, 0x93, 0xFA,
- 0x83, 0x51, 0x83, 0x87, 0x3A, 0x3C, 0x83, 0x51,
- 0x83, 0x87, 0x81, 0x80, 0x81, 0x8E, 0x83, 0x51,
- 0x83, 0x87];
-
- test_decodePDUMsg(
- testDataBuffer3,
- "\u0031\uFF82\uFF9F\uFF19\uFF82\uFF9F\u0041\u0061\uFF82\uFF9F\uFF21\uFF41\uFF82\uFF9F\u30A2\u30F6\uFF82\uFF9F\u3042\uFF82\uFF9F\u65E5\uFF82\uFF9F\u003A\u003C\uFF82\uFF9F\u00F7\u2103\uFF82\uFF9F\u0031\u30B2\u30E7\uFF19\u30B2\u30E7\u0041\u0061\u30B2\u30E7\uFF21\uFF41\u30B2\u30E7\uFF71\uFF6F\u30B2\u30E7\u3042\u30B2\u30E7\u65E5\u30B2\u30E7\u003A\u003C\u30B2\u30E7\u00F7\u2103\u30B2\u30E7",
- PDU_CDMA_MSG_CODING_SHIFT_JIS,
- undefined,
- testDataBuffer3.length
- );
-
- // test case 4
- let testDataBuffer4 = [0x31, 0x82, 0xB0, 0x82, 0x58, 0x82, 0xB0, 0x41,
- 0x61, 0x82, 0xB0, 0x82, 0x60, 0x82, 0x81, 0x82,
- 0xB0, 0xB1, 0xAF, 0x82, 0xB0, 0x83, 0x41, 0x83,
- 0x96, 0x82, 0xB0, 0x93, 0xFA, 0x82, 0xB0, 0x3A,
- 0x3C, 0x82, 0xB0, 0x81, 0x80, 0x81, 0x8E, 0x82,
- 0xB0, 0x31, 0x88, 0xA4, 0x82, 0x58, 0x88, 0xA4,
- 0x41, 0x61, 0x88, 0xA4, 0x82, 0x60, 0x82, 0x81,
- 0x88, 0xA4, 0xB1, 0xAF, 0x88, 0xA4, 0x83, 0x41,
- 0x83, 0x96, 0x88, 0xA4, 0x82, 0xA0, 0x88, 0xA4,
- 0x3A, 0x3C, 0x88, 0xA4, 0x81, 0x80, 0x81, 0x8E,
- 0x88, 0xA4];
-
- test_decodePDUMsg(
- testDataBuffer4,
- "\u0031\u3052\uFF19\u3052\u0041\u0061\u3052\uFF21\uFF41\u3052\uFF71\uFF6F\u3052\u30A2\u30F6\u3052\u65E5\u3052\u003A\u003C\u3052\u00F7\u2103\u3052\u0031\u611B\uFF19\u611B\u0041\u0061\u611B\uFF21\uFF41\u611B\uFF71\uFF6F\u611B\u30A2\u30F6\u611B\u3042\u611B\u003A\u003C\u611B\u00F7\u2103\u611B",
- PDU_CDMA_MSG_CODING_SHIFT_JIS,
- undefined,
- testDataBuffer4.length
- );
-
- // test case 5
- let testDataBuffer5 = [0x31, 0x40, 0x82, 0x58, 0x40, 0x41, 0x61, 0x40,
- 0x82, 0x60, 0x82, 0x81, 0x40, 0xB1, 0xAF, 0x40,
- 0x83, 0x41, 0x83, 0x96, 0x40, 0x82, 0xA0, 0x40,
- 0x93, 0xFA, 0x40, 0x81, 0x80, 0x81, 0x8E, 0x40,
- 0x31, 0x81, 0x9B, 0x82, 0x58, 0x81, 0x9B, 0x41,
- 0x61, 0x81, 0x9B, 0x82, 0x60, 0x82, 0x81, 0x81,
- 0x9B, 0xB1, 0xAF, 0x81, 0x9B, 0x83, 0x41, 0x83,
- 0x96, 0x81, 0x9B, 0x82, 0xA0, 0x81, 0x9B, 0x93,
- 0xFA, 0x81, 0x9B, 0x3A, 0x3C, 0x81, 0x9B];
-
- test_decodePDUMsg(
- testDataBuffer5,
- "\u0031\u0040\uFF19\u0040\u0041\u0061\u0040\uFF21\uFF41\u0040\uFF71\uFF6F\u0040\u30A2\u30F6\u0040\u3042\u0040\u65E5\u0040\u00F7\u2103\u0040\u0031\u25CB\uFF19\u25CB\u0041\u0061\u25CB\uFF21\uFF41\u25CB\uFF71\uFF6F\u25CB\u30A2\u30F6\u25CB\u3042\u25CB\u65E5\u25CB\u003A\u003C\u25CB",
- PDU_CDMA_MSG_CODING_SHIFT_JIS,
- undefined,
- testDataBuffer5.length
- );
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_sms_gsmpduhelper.js b/dom/system/gonk/tests/test_ril_worker_sms_gsmpduhelper.js
deleted file mode 100644
index f52c64cf8..000000000
--- a/dom/system/gonk/tests/test_ril_worker_sms_gsmpduhelper.js
+++ /dev/null
@@ -1,282 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify GsmPDUHelper#readDataCodingScheme.
- */
-add_test(function test_GsmPDUHelper_readDataCodingScheme() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- function test_dcs(dcs, encoding, messageClass, mwi) {
- helper.readHexOctet = function() {
- return dcs;
- }
-
- let msg = {};
- helper.readDataCodingScheme(msg);
-
- equal(msg.dcs, dcs);
- equal(msg.encoding, encoding);
- equal(msg.messageClass, messageClass);
- equal(msg.mwi == null, mwi == null);
- if (mwi != null) {
- equal(msg.mwi.active, mwi.active);
- equal(msg.mwi.discard, mwi.discard);
- equal(msg.mwi.msgCount, mwi.msgCount);
- }
- }
-
- // Group 00xx
- // Bit 3 and 2 indicate the character set being used.
- test_dcs(0x00, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- test_dcs(0x04, PDU_DCS_MSG_CODING_8BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- test_dcs(0x08, PDU_DCS_MSG_CODING_16BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- test_dcs(0x0C, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- // Bit 4, if set to 0, indicates that bits 1 to 0 are reserved and have no
- // message class meaning.
- test_dcs(0x01, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- test_dcs(0x02, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- test_dcs(0x03, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- // Bit 4, if set to 1, indicates that bits 1 to 0 have a message class meaning.
- test_dcs(0x10, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_0]);
- test_dcs(0x11, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_1]);
- test_dcs(0x12, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_2]);
- test_dcs(0x13, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_3]);
-
- // Group 01xx
- test_dcs(0x50, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_0]);
-
- // Group 1000..1011: reserved
- test_dcs(0x8F, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- test_dcs(0x9F, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- test_dcs(0xAF, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
- test_dcs(0xBF, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL]);
-
- // Group 1100: Message Waiting Indication Group: Discard Message
- // Bit 3 indicates Indication Sense:
- test_dcs(0xC0, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: false, discard: true, msgCount: 0});
- test_dcs(0xC8, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: true, discard: true, msgCount: -1});
- // Bit 2 is reserved, and set to 0:
- test_dcs(0xCC, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: true, discard: true, msgCount: -1});
-
- // Group 1101: Message Waiting Indication Group: Store Message
- // Bit 3 indicates Indication Sense:
- test_dcs(0xD0, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: false, discard: false, msgCount: 0});
- test_dcs(0xD8, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: true, discard: false, msgCount: -1});
- // Bit 2 is reserved, and set to 0:
- test_dcs(0xDC, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: true, discard: false, msgCount: -1});
-
- // Group 1110: Message Waiting Indication Group: Store Message, UCS2
- // Bit 3 indicates Indication Sense:
- test_dcs(0xE0, PDU_DCS_MSG_CODING_16BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: false, discard: false, msgCount: 0});
- test_dcs(0xE8, PDU_DCS_MSG_CODING_16BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: true, discard: false, msgCount: -1});
- // Bit 2 is reserved, and set to 0:
- test_dcs(0xEC, PDU_DCS_MSG_CODING_16BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_NORMAL],
- {active: true, discard: false, msgCount: -1});
-
- // Group 1111
- test_dcs(0xF0, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_0]);
- test_dcs(0xF1, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_1]);
- test_dcs(0xF2, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_2]);
- test_dcs(0xF3, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_3]);
- test_dcs(0xF4, PDU_DCS_MSG_CODING_8BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_0]);
- test_dcs(0xF5, PDU_DCS_MSG_CODING_8BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_1]);
- test_dcs(0xF6, PDU_DCS_MSG_CODING_8BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_2]);
- test_dcs(0xF7, PDU_DCS_MSG_CODING_8BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_3]);
- // Bit 3 is reserved and should be set to 0, but if it doesn't we should
- // ignore it.
- test_dcs(0xF8, PDU_DCS_MSG_CODING_7BITS_ALPHABET,
- GECKO_SMS_MESSAGE_CLASSES[PDU_DCS_MSG_CLASS_0]);
-
- run_next_test();
-});
-
-/**
- * Verify GsmPDUHelper#writeStringAsSeptets() padding bits handling.
- */
-add_test(function test_GsmPDUHelper_writeStringAsSeptets() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- helper.resetOctetWritten = function() {
- helper.octetsWritten = 0;
- };
- helper.writeHexOctet = function() {
- helper.octetsWritten++;
- };
-
- let base = "AAAAAAAA"; // Base string of 8 characters long
- for (let len = 0; len < 8; len++) {
- let str = base.substring(0, len);
-
- for (let paddingBits = 0; paddingBits < 8; paddingBits++) {
- do_print("Verifying GsmPDUHelper.writeStringAsSeptets("
- + str + ", " + paddingBits + ", <default>, <default>)");
- helper.resetOctetWritten();
- helper.writeStringAsSeptets(str, paddingBits, PDU_NL_IDENTIFIER_DEFAULT,
- PDU_NL_IDENTIFIER_DEFAULT);
- equal(Math.ceil(((len * 7) + paddingBits) / 8),
- helper.octetsWritten);
- }
- }
-
- run_next_test();
-});
-
-/**
- * Verify that encoding with Spanish locking shift table generates the same
- * septets as with GSM default alphabet table.
- *
- * Bug 1138841 - Incorrect Spanish national language locking shift table
- * definition.
- */
-add_test(function test_GsmPDUHelper_writeStringAsSeptets_spanish_fallback() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- let buf = [];
- helper.writeHexOctet = function(octet) {
- buf.push(octet);
- }
-
- // Simple message string which is covered by GSM default alphabet.
- let msg = "The quick brown fox jumps over the lazy dog";
-
- // Encoded with GSM default alphabet.
- helper.writeStringAsSeptets(msg, 0 /* paddingBits */,
- PDU_NL_IDENTIFIER_DEFAULT, PDU_NL_IDENTIFIER_DEFAULT);
- let octetsWithDefaultTable = buf;
- buf = [];
-
- // Encoded with Spanish locking shift table.
- helper.writeStringAsSeptets(msg, 0 /* paddingBits */,
- PDU_NL_IDENTIFIER_SPANISH, PDU_NL_IDENTIFIER_SPANISH);
-
- // The length and content should be equal to what encoded with GSM default
- // alphabet.
- equal(octetsWithDefaultTable.length, buf.length);
- for (let i = 0; i < buf.length; i++) {
- equal(octetsWithDefaultTable[i], buf[i]);
- }
-
- run_next_test();
-});
-
-/**
- * Verify GsmPDUHelper#readAddress
- */
-add_test(function test_GsmPDUHelper_readAddress() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- function test_address(addrHex, addrString) {
- let uint16Array = [];
- let ix = 0;
- for (let i = 0; i < addrHex.length; ++i) {
- uint16Array[i] = addrHex[i].charCodeAt();
- }
-
- context.Buf.readUint16 = function(){
- if(ix >= uint16Array.length) {
- do_throw("out of range in uint16Array");
- }
- return uint16Array[ix++];
- }
- let length = helper.readHexOctet();
- let parsedAddr = helper.readAddress(length);
- equal(parsedAddr, addrString);
- }
-
- // For AlphaNumeric
- test_address("04D01100", "_@");
- test_address("04D01000", "\u0394@");
-
- // Direct prepand
- test_address("0B914151245584F6", "+14154255486");
- test_address("0E914151245584B633", "+14154255486#33");
-
- // PDU_TOA_NATIONAL
- test_address("0BA14151245584F6", "14154255486");
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_sms_nl_tables.js b/dom/system/gonk/tests/test_ril_worker_sms_nl_tables.js
deleted file mode 100644
index 32bc5dc2a..000000000
--- a/dom/system/gonk/tests/test_ril_worker_sms_nl_tables.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-const ESCAPE = "\uffff";
-const RESCTL = "\ufffe";
-const LF = "\n";
-const CR = "\r";
-const SP = " ";
-const FF = "\u000c";
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify validity of the national language tables
- */
-add_test(function test_nl_locking_shift_tables_validity() {
- for (let lst = 0; lst < PDU_NL_LOCKING_SHIFT_TABLES.length; lst++) {
- do_print("Verifying PDU_NL_LOCKING_SHIFT_TABLES[" + lst + "]");
-
- let table = PDU_NL_LOCKING_SHIFT_TABLES[lst];
-
- // Make sure table length is 128, or it will break table lookup algorithm.
- equal(table.length, 128);
-
- // Make sure special values are preserved.
- equal(table[PDU_NL_EXTENDED_ESCAPE], ESCAPE);
- equal(table[PDU_NL_LINE_FEED], LF);
- equal(table[PDU_NL_CARRIAGE_RETURN], CR);
- equal(table[PDU_NL_SPACE], SP);
- }
-
- run_next_test();
-});
-
-add_test(function test_nl_single_shift_tables_validity() {
- for (let sst = 0; sst < PDU_NL_SINGLE_SHIFT_TABLES.length; sst++) {
- do_print("Verifying PDU_NL_SINGLE_SHIFT_TABLES[" + sst + "]");
-
- let table = PDU_NL_SINGLE_SHIFT_TABLES[sst];
-
- // Make sure table length is 128, or it will break table lookup algorithm.
- equal(table.length, 128);
-
- // Make sure special values are preserved.
- equal(table[PDU_NL_EXTENDED_ESCAPE], ESCAPE);
- equal(table[PDU_NL_PAGE_BREAK], FF);
- equal(table[PDU_NL_RESERVED_CONTROL], RESCTL);
- }
-
- run_next_test();
-});
-
-add_test(function test_gsm_sms_strict_7bit_charmap_validity() {
- let defaultTable = PDU_NL_LOCKING_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- let defaultShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[PDU_NL_IDENTIFIER_DEFAULT];
- for (let from in GSM_SMS_STRICT_7BIT_CHARMAP) {
- let to = GSM_SMS_STRICT_7BIT_CHARMAP[from];
- do_print("Verifying GSM_SMS_STRICT_7BIT_CHARMAP[\"\\u0x"
- + from.charCodeAt(0).toString(16) + "\"] => \"\\u"
- + to.charCodeAt(0).toString(16) + "\"");
-
- // Make sure "from" is not in default table
- equal(defaultTable.indexOf(from), -1);
- equal(defaultShiftTable.indexOf(from), -1);
- // Make sure "to" is in default table
- if ((defaultTable.indexOf(to) < 0)
- && (defaultShiftTable.indexOf(to) < 0)) {
- equal(false, true);
- }
- }
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_sms_segment_info.js b/dom/system/gonk/tests/test_ril_worker_sms_segment_info.js
deleted file mode 100644
index 2b29ac60e..000000000
--- a/dom/system/gonk/tests/test_ril_worker_sms_segment_info.js
+++ /dev/null
@@ -1,115 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-
-XPCOMUtils.defineLazyGetter(this, "gSmsSegmentHelper", function() {
- let ns = {};
- Cu.import("resource://gre/modules/SmsSegmentHelper.jsm", ns);
- return ns.SmsSegmentHelper;
-});
-
-const ESCAPE = "\uffff";
-const RESCTL = "\ufffe";
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Verify SmsSegmentHelper#countGsm7BitSeptets() and
- * GsmPDUHelper#writeStringAsSeptets() algorithm match each other.
- */
-add_test(function test_SmsSegmentHelper__countGsm7BitSeptets() {
- let worker = newWorker({
- postRILMessage: function(data) {
- // Do nothing
- },
- postMessage: function(message) {
- // Do nothing
- }
- });
-
- let context = worker.ContextPool._contexts[0];
- let helper = context.GsmPDUHelper;
- helper.resetOctetWritten = function() {
- helper.octetsWritten = 0;
- };
- helper.writeHexOctet = function() {
- helper.octetsWritten++;
- };
-
- function do_check_calc(str, expectedCalcLen, lst, sst, strict7BitEncoding, strToWrite) {
- equal(expectedCalcLen,
- gSmsSegmentHelper
- .countGsm7BitSeptets(str,
- PDU_NL_LOCKING_SHIFT_TABLES[lst],
- PDU_NL_SINGLE_SHIFT_TABLES[sst],
- strict7BitEncoding));
-
- helper.resetOctetWritten();
- strToWrite = strToWrite || str;
- helper.writeStringAsSeptets(strToWrite, 0, lst, sst);
- equal(Math.ceil(expectedCalcLen * 7 / 8), helper.octetsWritten);
- }
-
- // Test calculation encoded message length using both locking/single shift tables.
- for (let lst = 0; lst < PDU_NL_LOCKING_SHIFT_TABLES.length; lst++) {
- let langTable = PDU_NL_LOCKING_SHIFT_TABLES[lst];
-
- let str = langTable.substring(0, PDU_NL_EXTENDED_ESCAPE)
- + langTable.substring(PDU_NL_EXTENDED_ESCAPE + 1);
-
- for (let sst = 0; sst < PDU_NL_SINGLE_SHIFT_TABLES.length; sst++) {
- let langShiftTable = PDU_NL_SINGLE_SHIFT_TABLES[sst];
-
- // <escape>, <resctrl> should be ignored.
- do_check_calc(ESCAPE + RESCTL, 0, lst, sst);
-
- // Characters defined in locking shift table should be encoded directly.
- do_check_calc(str, str.length, lst, sst);
-
- let [str1, str2] = ["", ""];
- for (let i = 0; i < langShiftTable.length; i++) {
- if ((i == PDU_NL_EXTENDED_ESCAPE) || (i == PDU_NL_RESERVED_CONTROL)) {
- continue;
- }
-
- let c = langShiftTable[i];
- if (langTable.indexOf(c) >= 0) {
- str1 += c;
- } else {
- str2 += c;
- }
- }
-
- // Characters found in both locking/single shift tables should be
- // directly encoded.
- do_check_calc(str1, str1.length, lst, sst);
-
- // Characters found only in single shift tables should be encoded as
- // <escape><code>, therefore doubles its original length.
- do_check_calc(str2, str2.length * 2, lst, sst);
- }
- }
-
- // Bug 790192: support strict GSM SMS 7-Bit encoding
- let str = "", strToWrite = "", gsmLen = 0;
- for (let c in GSM_SMS_STRICT_7BIT_CHARMAP) {
- str += c;
- strToWrite += GSM_SMS_STRICT_7BIT_CHARMAP[c];
- if (PDU_NL_LOCKING_SHIFT_TABLES.indexOf(GSM_SMS_STRICT_7BIT_CHARMAP[c])) {
- gsmLen += 1;
- } else {
- gsmLen += 2;
- }
- }
- do_check_calc(str, gsmLen,
- PDU_NL_IDENTIFIER_DEFAULT, PDU_NL_IDENTIFIER_DEFAULT,
- true, strToWrite);
-
- run_next_test();
-});
-
diff --git a/dom/system/gonk/tests/test_ril_worker_smsc_address.js b/dom/system/gonk/tests/test_ril_worker_smsc_address.js
deleted file mode 100644
index c8c283b7c..000000000
--- a/dom/system/gonk/tests/test_ril_worker_smsc_address.js
+++ /dev/null
@@ -1,112 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-const SMSC_ATT = '+13123149810';
-const SMSC_ATT_TYPO = '+++1312@@@314$$$9,8,1,0';
-const SMSC_ATT_TEXT = '"+13123149810",145';
-const SMSC_ATT_TEXT_INCORRECT_TOA = '"+13123149810",129';
-const SMSC_ATT_PDU = '07913121139418F0';
-const SMSC_O2 = '+447802000332';
-const SMSC_O2_TEXT = '"+447802000332",145';
-const SMSC_O2_PDU = '0791448720003023';
-const SMSC_EMPTY = '';
-const SMSC_TON_UNKNOWN = '0407485455'
-const SMSC_TON_UNKNOWN_TEXT = '"0407485455",129';
-const SMSC_TON_UNKNOWN_TEXT_NO_TOA = '"0407485455"';
-const SMSC_TON_UNKNOWN_TEXT_INVALID_TOA = '"0407485455",abc';
-const SMSC_TON_UNKNOWN_PDU = '06814070844555';
-const SMSC_EMPTY_PDU = 'FFFFFFFFFFFFFFFFFFFFFFFF';
-const SMSC_EMPTY_TEXT = '';
-
-function run_test() {
- run_next_test();
-}
-
-function setSmsc(context, smsc, ton, npi, expected) {
- context.Buf.postRILMessage = function() {
- equal(this.readString(), expected);
- };
-
- context.RIL.setSmscAddress({
- smscAddress: smsc,
- typeOfNumber: ton,
- numberPlanIdentification: npi
- });
-}
-
-function getSmsc(worker, context, raw, smsc, ton, npi) {
- worker.postMessage = function(message) {
- equal(message.smscAddress, smsc);
- equal(message.typeOfNumber, ton);
- equal(message.numberPlanIdentification, npi);
- }
-
- context.Buf.writeString(raw);
- context.RIL[REQUEST_GET_SMSC_ADDRESS](0, { rilMessageType: "getSmscAddress"});
-}
-
-add_test(function test_setSmscAddress() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let parcelTypes = [];
- context.Buf.newParcel = (type, options) => parcelTypes.push(type);
-
- // Test text mode.
- worker.RILQUIRKS_SMSC_ADDRESS_FORMAT = "text";
-
- setSmsc(context, SMSC_ATT, 1, 1, SMSC_ATT_TEXT);
- equal(parcelTypes.pop(), REQUEST_SET_SMSC_ADDRESS);
-
- setSmsc(context, SMSC_O2, 1, 1, SMSC_O2_TEXT);
- equal(parcelTypes.pop(), REQUEST_SET_SMSC_ADDRESS);
-
- setSmsc(context, SMSC_ATT_TYPO, 1, 1, SMSC_ATT_TEXT);
- equal(parcelTypes.pop(), REQUEST_SET_SMSC_ADDRESS);
-
- setSmsc(context, SMSC_TON_UNKNOWN, 0, 1, SMSC_TON_UNKNOWN_TEXT);
- equal(parcelTypes.pop(), REQUEST_SET_SMSC_ADDRESS);
-
- // Test pdu mode.
- worker.RILQUIRKS_SMSC_ADDRESS_FORMAT = "pdu";
-
- setSmsc(context, SMSC_ATT, 1, 1, SMSC_ATT_PDU);
- equal(parcelTypes.pop(), REQUEST_SET_SMSC_ADDRESS);
-
- setSmsc(context, SMSC_O2, 1, 1, SMSC_O2_PDU);
- equal(parcelTypes.pop(), REQUEST_SET_SMSC_ADDRESS);
-
- setSmsc(context, SMSC_ATT_TYPO, 1, 1, SMSC_ATT_PDU);
- equal(parcelTypes.pop(), REQUEST_SET_SMSC_ADDRESS);
-
- setSmsc(context, SMSC_TON_UNKNOWN, 0, 1, SMSC_TON_UNKNOWN_PDU);
- equal(parcelTypes.pop(), REQUEST_SET_SMSC_ADDRESS);
-
- run_next_test();
-});
-
-add_test(function test_getSmscAddress() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
-
- // Test text mode.
- worker.RILQUIRKS_SMSC_ADDRESS_FORMAT = "text";
- getSmsc(worker, context, SMSC_ATT_TEXT, SMSC_ATT, 1, 1);
- getSmsc(worker, context, SMSC_ATT_TEXT_INCORRECT_TOA, SMSC_ATT, 1, 1);
- getSmsc(worker, context, SMSC_O2_TEXT, SMSC_O2, 1, 1);
- getSmsc(worker, context, SMSC_TON_UNKNOWN_TEXT, SMSC_TON_UNKNOWN, 0, 1);
- getSmsc(worker, context, SMSC_TON_UNKNOWN_TEXT_NO_TOA, SMSC_TON_UNKNOWN, 0, 1);
- getSmsc(worker, context, SMSC_TON_UNKNOWN_TEXT_INVALID_TOA, SMSC_TON_UNKNOWN,
- 0, 1);
- getSmsc(worker, context, SMSC_EMPTY_TEXT, SMSC_EMPTY, 0, 1);
-
- // Test pdu mode.
- worker.RILQUIRKS_SMSC_ADDRESS_FORMAT = "pdu";
- getSmsc(worker, context, SMSC_ATT_PDU, SMSC_ATT, 1, 1);
- getSmsc(worker, context, SMSC_O2_PDU, SMSC_O2, 1, 1);
- getSmsc(worker, context, SMSC_TON_UNKNOWN_PDU, SMSC_TON_UNKNOWN, 0, 1);
- getSmsc(worker, context, SMSC_EMPTY_PDU, SMSC_EMPTY, 0, 1);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_ssn.js b/dom/system/gonk/tests/test_ril_worker_ssn.js
deleted file mode 100644
index ea0a2a599..000000000
--- a/dom/system/gonk/tests/test_ril_worker_ssn.js
+++ /dev/null
@@ -1,104 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_notification() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- function Call(callIndex, number) {
- this.callIndex = callIndex;
- this.number = number;
- }
-
- Call.prototype = {
- // Should use CALL_STATE_ACTIVE.
- // Any new outgoing call (state = dialing or alerting) will be drop if there
- // is no pending outgoing call created before.
- state: CALL_STATE_ACTIVE,
- //callIndex: 0,
- toa: 0,
- isMpty: false,
- isMT: false,
- als: 0,
- isVoice: true,
- isVoicePrivacy: false,
- //number: null,
- numberPresentation: 0,
- name: null,
- namePresentation: 0,
- uusInfo: null
- };
-
- let oneCall = {
- 0: new Call(0, '00000')
- };
-
- let twoCalls = {
- 0: new Call(0, '00000'),
- 1: new Call(1, '11111')
- };
-
- function testNotification(calls, code, number, resultNotification) {
-
- let testInfo = {calls: calls, code: code, number: number,
- resultNotification: resultNotification};
- do_print('Test case info: ' + JSON.stringify(testInfo));
-
- // Set current calls.
- context.RIL.sendChromeMessage({
- rilMessageType: "currentCalls",
- calls: calls
- });
-
- let notificationInfo = {
- notificationType: 1, // MT
- code: code,
- index: 0,
- type: 0,
- number: number
- };
-
- context.RIL._processSuppSvcNotification(notificationInfo);
-
- let postedMessage = workerHelper.postedMessage;
- equal(postedMessage.rilMessageType, 'suppSvcNotification');
- equal(postedMessage.number, number);
- equal(postedMessage.notification, resultNotification);
-
- // Clear all existed calls.
- context.RIL.sendChromeMessage({
- rilMessageType: "currentCalls",
- calls: {}
- });
- }
-
- testNotification(oneCall, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, null,
- GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD);
-
- testNotification(oneCall, SUPP_SVC_NOTIFICATION_CODE2_RETRIEVED, null,
- GECKO_SUPP_SVC_NOTIFICATION_REMOTE_RESUMED);
-
- testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, null,
- GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD);
-
- testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_RETRIEVED, null,
- GECKO_SUPP_SVC_NOTIFICATION_REMOTE_RESUMED);
-
- testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, '00000',
- GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD);
-
- testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, '11111',
- GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD);
-
- testNotification(twoCalls, SUPP_SVC_NOTIFICATION_CODE2_PUT_ON_HOLD, '22222',
- GECKO_SUPP_SVC_NOTIFICATION_REMOTE_HELD);
-
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_stk.js b/dom/system/gonk/tests/test_ril_worker_stk.js
deleted file mode 100644
index 49b914e89..000000000
--- a/dom/system/gonk/tests/test_ril_worker_stk.js
+++ /dev/null
@@ -1,1698 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-/**
- * Helper function.
- */
-function newUint8SupportOutgoingIndexWorker() {
- let worker = newWorker();
- let index = 4; // index for read
- let buf = [0, 0, 0, 0]; // Preserved parcel size
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.writeUint8 = function(value) {
- if (context.Buf.outgoingIndex >= buf.length) {
- buf.push(value);
- } else {
- buf[context.Buf.outgoingIndex] = value;
- }
-
- context.Buf.outgoingIndex++;
- };
-
- context.Buf.readUint8 = function() {
- return buf[index++];
- };
-
- context.Buf.seekIncoming = function(offset) {
- index += offset;
- };
-
- worker.debug = do_print;
-
- return worker;
-}
-
-// Test RIL requests related to STK.
-/**
- * Verify if RIL.sendStkTerminalProfile be called.
- */
-add_test(function test_if_send_stk_terminal_profile() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let profileSend = false;
- context.RIL.sendStkTerminalProfile = function(data) {
- profileSend = true;
- };
-
- let iccStatus = {
- gsmUmtsSubscriptionAppIndex: 0,
- apps: [{
- app_state: CARD_APPSTATE_READY,
- app_type: CARD_APPTYPE_USIM
- }],
- };
- worker.RILQUIRKS_SEND_STK_PROFILE_DOWNLOAD = false;
-
- context.RIL._processICCStatus(iccStatus);
-
- equal(profileSend, false);
-
- run_next_test();
-});
-
-/**
- * Verify RIL.sendStkTerminalProfile
- */
-add_test(function test_send_stk_terminal_profile() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let ril = context.RIL;
- let buf = context.Buf;
-
- ril.sendStkTerminalProfile(STK_SUPPORTED_TERMINAL_PROFILE);
-
- buf.seekIncoming(8);
- let profile = buf.readString();
- for (let i = 0; i < STK_SUPPORTED_TERMINAL_PROFILE.length; i++) {
- equal(parseInt(profile.substring(2 * i, 2 * i + 2), 16),
- STK_SUPPORTED_TERMINAL_PROFILE[i]);
- }
-
- run_next_test();
-});
-
-/**
- * Verify STK terminal response
- */
-add_test(function test_stk_terminal_response() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_TERMINAL_RESPONSE);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 44 = 2 * (TLV_COMMAND_DETAILS_SIZE(5) +
- // TLV_DEVICE_ID_SIZE(4) +
- // TLV_RESULT_SIZE(3) +
- // TEXT LENGTH(10))
- equal(this.readInt32(), 44);
-
- // Command Details, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_COMMAND_DETAILS |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 3);
- equal(pduHelper.readHexOctet(), 0x01);
- equal(pduHelper.readHexOctet(), STK_CMD_PROVIDE_LOCAL_INFO);
- equal(pduHelper.readHexOctet(), STK_LOCAL_INFO_NNA);
-
- // Device Identifies, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Result
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_RESULT |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_RESULT_OK);
-
- // Text
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_TEXT_STRING |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 8);
- equal(pduHelper.readHexOctet(), STK_TEXT_CODING_GSM_7BIT_PACKED);
- equal(pduHelper.readSeptetsToString(7, 0, PDU_NL_IDENTIFIER_DEFAULT,
- PDU_NL_IDENTIFIER_DEFAULT), "Mozilla");
-
- run_next_test();
- };
-
- let response = {
- command: {
- commandNumber: 0x01,
- typeOfCommand: STK_CMD_PROVIDE_LOCAL_INFO,
- commandQualifier: STK_LOCAL_INFO_NNA,
- options: {
- isPacked: true
- }
- },
- input: "Mozilla",
- resultCode: STK_RESULT_OK
- };
- context.RIL.sendStkTerminalResponse(response);
-});
-
-/**
- * Verify STK terminal response : GET INPUT with empty string.
- *
- * @See |TERMINAL RESPONSE: GET INPUT 1.9.1A| of 27.22.4.3.1 GET INPUT (normal)
- * in TS 102 384.
- */
-add_test(function test_stk_terminal_response_get_input_empty_string() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_TERMINAL_RESPONSE);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 30 = 2 * (TLV_COMMAND_DETAILS_SIZE(5) +
- // TLV_DEVICE_ID_SIZE(4) +
- // TLV_RESULT_SIZE(3) +
- // TEXT LENGTH(3))
- equal(this.readInt32(), 30);
-
- // Command Details, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_COMMAND_DETAILS |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 3);
- equal(pduHelper.readHexOctet(), 0x01);
- equal(pduHelper.readHexOctet(), STK_CMD_GET_INPUT);
- equal(pduHelper.readHexOctet(), 0x00);
-
- // Device Identifies, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Result
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_RESULT |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_RESULT_OK);
-
- // Text
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_TEXT_STRING |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_TEXT_CODING_GSM_8BIT);
-
- run_next_test();
- };
-
- let response = {
- command: {
- commandNumber: 0x01,
- typeOfCommand: STK_CMD_GET_INPUT,
- commandQualifier: 0x00,
- options: {
- minLength: 0,
- maxLength: 1,
- defaultText: "<SEND>"
- }
- },
- input: "",
- resultCode: STK_RESULT_OK
- };
- context.RIL.sendStkTerminalResponse(response);
-});
-
-/**
- * Verify STK terminal response : GET INPUT with 160 unpacked characters.
- *
- * @See |TERMINAL RESPONSE: GET INPUT 1.8.1| of 27.22.4.3.1 GET INPUT (normal)
- * in TS 102 384.
- */
-add_test(function test_stk_terminal_response_get_input_160_unpacked_characters() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
- let iccPduHelper = context.ICCPDUHelper;
- let TEST_TEXT_STRING = "***1111111111###" +
- "***2222222222###" +
- "***3333333333###" +
- "***4444444444###" +
- "***5555555555###" +
- "***6666666666###" +
- "***7777777777###" +
- "***8888888888###" +
- "***9999999999###" +
- "***0000000000###";
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_TERMINAL_RESPONSE);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 352 = 2 * (TLV_COMMAND_DETAILS_SIZE(5) +
- // TLV_DEVICE_ID_SIZE(4) +
- // TLV_RESULT_SIZE(3) +
- // TEXT LENGTH(164))
- equal(this.readInt32(), 352);
-
- // Command Details, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_COMMAND_DETAILS |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 3);
- equal(pduHelper.readHexOctet(), 0x01);
- equal(pduHelper.readHexOctet(), STK_CMD_GET_INPUT);
- equal(pduHelper.readHexOctet(), 0x00);
-
- // Device Identifies, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Result
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_RESULT |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_RESULT_OK);
-
- // Text
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_TEXT_STRING |
- COMPREHENSIONTLV_FLAG_CR);
- // C-TLV Length Encoding: 161 = 0x81 0xA1
- equal(pduHelper.readHexOctet(), 0x81);
- equal(pduHelper.readHexOctet(), 0xA1);
- equal(pduHelper.readHexOctet(), STK_TEXT_CODING_GSM_8BIT);
- equal(iccPduHelper.read8BitUnpackedToString(160), TEST_TEXT_STRING);
-
- run_next_test();
- };
-
- let response = {
- command: {
- commandNumber: 0x01,
- typeOfCommand: STK_CMD_GET_INPUT,
- commandQualifier: 0x00,
- options: {
- minLength: 160,
- maxLength: 160,
- text: TEST_TEXT_STRING
- }
- },
- input: TEST_TEXT_STRING,
- resultCode: STK_RESULT_OK
- };
- context.RIL.sendStkTerminalResponse(response);
-});
-
-/**
- * Verify STK terminal response : GET_INKEY - NO_RESPONSE_FROM_USER with
- * duration provided.
- *
- * @See |27.22.4.2.8 GET INKEY (Variable Time out)| in TS 102 384.
- */
-add_test(function test_stk_terminal_response_get_inkey_no_response_from_user() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_TERMINAL_RESPONSE);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 32 = 2 * (TLV_COMMAND_DETAILS_SIZE(5) +
- // TLV_DEVICE_ID_SIZE(4) +
- // TLV_RESULT_SIZE(3) +
- // DURATION(4))
- equal(this.readInt32(), 32);
-
- // Command Details, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_COMMAND_DETAILS |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 3);
- equal(pduHelper.readHexOctet(), 0x01);
- equal(pduHelper.readHexOctet(), STK_CMD_GET_INKEY);
- equal(pduHelper.readHexOctet(), 0x00);
-
- // Device Identifies, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Result
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_RESULT |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_RESULT_NO_RESPONSE_FROM_USER);
-
- // Duration, Type-Length-Value(Time unit, Time interval)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DURATION);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_TIME_UNIT_SECOND);
- equal(pduHelper.readHexOctet(), 10);
-
- run_next_test();
- };
-
- let response = {
- command: {
- commandNumber: 0x01,
- typeOfCommand: STK_CMD_GET_INKEY,
- commandQualifier: 0x00,
- options: {
- duration: {
- timeUnit: STK_TIME_UNIT_SECOND,
- timeInterval: 10
- },
- text: 'Enter "+"'
- }
- },
- resultCode: STK_RESULT_NO_RESPONSE_FROM_USER
- };
- context.RIL.sendStkTerminalResponse(response);
-});
-
-/**
- * Verify STK terminal response : GET_INKEY - YES/NO request
- */
-add_test(function test_stk_terminal_response_get_inkey() {
- function do_test(isYesNo) {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_TERMINAL_RESPONSE);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 32 = 2 * (TLV_COMMAND_DETAILS_SIZE(5) +
- // TLV_DEVICE_ID_SIZE(4) +
- // TLV_RESULT_SIZE(3) +
- // TEXT LENGTH(4))
- equal(this.readInt32(), 32);
-
- // Command Details, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_COMMAND_DETAILS |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 3);
- equal(pduHelper.readHexOctet(), 0x01);
- equal(pduHelper.readHexOctet(), STK_CMD_GET_INKEY);
- equal(pduHelper.readHexOctet(), 0x04);
-
- // Device Identifies, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Result
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_RESULT |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_RESULT_OK);
-
- // Yes/No response
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_TEXT_STRING |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_TEXT_CODING_GSM_8BIT);
- equal(pduHelper.readHexOctet(), isYesNo ? 0x01 : 0x00);
- };
-
- let response = {
- command: {
- commandNumber: 0x01,
- typeOfCommand: STK_CMD_GET_INKEY,
- commandQualifier: 0x04,
- options: {
- isYesNoRequested: true
- }
- },
- isYesNo: isYesNo,
- resultCode: STK_RESULT_OK
- };
-
- context.RIL.sendStkTerminalResponse(response);
- };
-
- // Test "Yes" response
- do_test(true);
- // Test "No" response
- do_test(false);
-
- run_next_test();
-});
-
-/**
- * Verify STK terminal response with additional information.
- */
-add_test(function test_stk_terminal_response_with_additional_info() {
- function do_test(aInfo) {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_TERMINAL_RESPONSE);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Length 26 = 2 * (TLV_COMMAND_DETAILS_SIZE(5) +
- // TLV_DEVICE_ID_SIZE(4) +
- // TLV_RESULT_SIZE(4))
- equal(this.readInt32(), 26);
-
- // Command Details, Type-Length-Value(commandNumber, typeOfCommand, commandQualifier)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_COMMAND_DETAILS |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 3);
- equal(pduHelper.readHexOctet(), 0x01);
- equal(pduHelper.readHexOctet(), STK_CMD_DISPLAY_TEXT);
- equal(pduHelper.readHexOctet(), 0x01);
-
- // Device Identifies, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Result, Type-Length-Value(General result, Additional information on result)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_RESULT |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_RESULT_TERMINAL_CRNTLY_UNABLE_TO_PROCESS);
- equal(pduHelper.readHexOctet(), aInfo);
- };
-
- let response = {
- command: {
- commandNumber: 0x01,
- typeOfCommand: STK_CMD_DISPLAY_TEXT,
- commandQualifier: 0x01,
- options: {
- isHighPriority: true
- }
- },
- resultCode: STK_RESULT_TERMINAL_CRNTLY_UNABLE_TO_PROCESS,
- additionalInformation: aInfo
- };
-
- context.RIL.sendStkTerminalResponse(response);
- };
-
- do_test(0x01); // 'Screen is busy'
-
- run_next_test();
-});
-
-// Test ComprehensionTlvHelper
-
-/**
- * Verify ComprehensionTlvHelper.writeLocationInfoTlv
- */
-add_test(function test_write_location_info_tlv() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let tlvHelper = context.ComprehensionTlvHelper;
-
- // Test with 2-digit mnc, and gsmCellId obtained from UMTS network.
- let loc = {
- mcc: "466",
- mnc: "92",
- gsmLocationAreaCode : 10291,
- gsmCellId: 19072823
- };
- tlvHelper.writeLocationInfoTlv(loc);
-
- let tag = pduHelper.readHexOctet();
- equal(tag, COMPREHENSIONTLV_TAG_LOCATION_INFO |
- COMPREHENSIONTLV_FLAG_CR);
-
- let length = pduHelper.readHexOctet();
- equal(length, 9);
-
- let mcc_mnc = pduHelper.readSwappedNibbleBcdString(3);
- equal(mcc_mnc, "46692");
-
- let lac = (pduHelper.readHexOctet() << 8) | pduHelper.readHexOctet();
- equal(lac, 10291);
-
- let cellId = (pduHelper.readHexOctet() << 24) |
- (pduHelper.readHexOctet() << 16) |
- (pduHelper.readHexOctet() << 8) |
- (pduHelper.readHexOctet());
- equal(cellId, 19072823);
-
- // Test with 1-digit mnc, and gsmCellId obtained from GSM network.
- loc = {
- mcc: "466",
- mnc: "02",
- gsmLocationAreaCode : 10291,
- gsmCellId: 65534
- };
- tlvHelper.writeLocationInfoTlv(loc);
-
- tag = pduHelper.readHexOctet();
- equal(tag, COMPREHENSIONTLV_TAG_LOCATION_INFO |
- COMPREHENSIONTLV_FLAG_CR);
-
- length = pduHelper.readHexOctet();
- equal(length, 7);
-
- mcc_mnc = pduHelper.readSwappedNibbleBcdString(3);
- equal(mcc_mnc, "46602");
-
- lac = (pduHelper.readHexOctet() << 8) | pduHelper.readHexOctet();
- equal(lac, 10291);
-
- cellId = (pduHelper.readHexOctet() << 8) | (pduHelper.readHexOctet());
- equal(cellId, 65534);
-
- // Test with 3-digit mnc, and gsmCellId obtained from GSM network.
- loc = {
- mcc: "466",
- mnc: "222",
- gsmLocationAreaCode : 10291,
- gsmCellId: 65534
- };
- tlvHelper.writeLocationInfoTlv(loc);
-
- tag = pduHelper.readHexOctet();
- equal(tag, COMPREHENSIONTLV_TAG_LOCATION_INFO |
- COMPREHENSIONTLV_FLAG_CR);
-
- length = pduHelper.readHexOctet();
- equal(length, 7);
-
- mcc_mnc = pduHelper.readSwappedNibbleBcdString(3);
- equal(mcc_mnc, "466222");
-
- lac = (pduHelper.readHexOctet() << 8) | pduHelper.readHexOctet();
- equal(lac, 10291);
-
- cellId = (pduHelper.readHexOctet() << 8) | (pduHelper.readHexOctet());
- equal(cellId, 65534);
-
- run_next_test();
-});
-
-/**
- * Verify ComprehensionTlvHelper.writeErrorNumber
- */
-add_test(function test_write_disconnecting_cause() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let tlvHelper = context.ComprehensionTlvHelper;
-
- tlvHelper.writeCauseTlv(RIL_CALL_FAILCAUSE_TO_GECKO_CALL_ERROR[CALL_FAIL_BUSY]);
- let tag = pduHelper.readHexOctet();
- equal(tag, COMPREHENSIONTLV_TAG_CAUSE | COMPREHENSIONTLV_FLAG_CR);
- let len = pduHelper.readHexOctet();
- equal(len, 2); // We have one cause.
- let standard = pduHelper.readHexOctet();
- equal(standard, 0x60);
- let cause = pduHelper.readHexOctet();
- equal(cause, 0x80 | CALL_FAIL_BUSY);
-
- run_next_test();
-});
-
-/**
- * Verify ComprehensionTlvHelper.getSizeOfLengthOctets
- */
-add_test(function test_get_size_of_length_octets() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let tlvHelper = context.ComprehensionTlvHelper;
-
- let length = 0x70;
- equal(tlvHelper.getSizeOfLengthOctets(length), 1);
-
- length = 0x80;
- equal(tlvHelper.getSizeOfLengthOctets(length), 2);
-
- length = 0x180;
- equal(tlvHelper.getSizeOfLengthOctets(length), 3);
-
- length = 0x18000;
- equal(tlvHelper.getSizeOfLengthOctets(length), 4);
-
- run_next_test();
-});
-
-/**
- * Verify ComprehensionTlvHelper.writeLength
- */
-add_test(function test_write_length() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let tlvHelper = context.ComprehensionTlvHelper;
-
- let length = 0x70;
- tlvHelper.writeLength(length);
- equal(pduHelper.readHexOctet(), length);
-
- length = 0x80;
- tlvHelper.writeLength(length);
- equal(pduHelper.readHexOctet(), 0x81);
- equal(pduHelper.readHexOctet(), length);
-
- length = 0x180;
- tlvHelper.writeLength(length);
- equal(pduHelper.readHexOctet(), 0x82);
- equal(pduHelper.readHexOctet(), (length >> 8) & 0xff);
- equal(pduHelper.readHexOctet(), length & 0xff);
-
- length = 0x18000;
- tlvHelper.writeLength(length);
- equal(pduHelper.readHexOctet(), 0x83);
- equal(pduHelper.readHexOctet(), (length >> 16) & 0xff);
- equal(pduHelper.readHexOctet(), (length >> 8) & 0xff);
- equal(pduHelper.readHexOctet(), length & 0xff);
-
- run_next_test();
-});
-
-// Test Proactive commands.
-
-function test_stk_proactive_command(aOptions) {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let berHelper = context.BerTlvHelper;
- let stkHelper = context.StkProactiveCmdHelper;
- let stkFactory = context.StkCommandParamsFactory;
-
- let testPdu = aOptions.pdu;
- let testTypeOfCommand = aOptions.typeOfCommand;
- let testIcons = aOptions.icons;
- let testFunc = aOptions.testFunc;
-
- if (testIcons) {
- let ril = context.RIL;
- ril.iccInfoPrivate.sst = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x30]; //IMG: 39
- ril.appType = CARD_APPTYPE_SIM;
-
- // skip asynchornous process in IconLoader.loadIcons().
- let iconLoader = context.IconLoader;
- iconLoader.loadIcons = (recordNumbers, onsuccess, onerror) => {
- onsuccess(testIcons);
- };
- }
-
- for(let i = 0 ; i < testPdu.length; i++) {
- pduHelper.writeHexOctet(testPdu[i]);
- }
-
- let berTlv = berHelper.decode(testPdu.length);
- let ctlvs = berTlv.value;
- let ctlv = stkHelper.searchForTag(COMPREHENSIONTLV_TAG_COMMAND_DETAILS, ctlvs);
- let cmdDetails = ctlv.value;
- equal(cmdDetails.typeOfCommand, testTypeOfCommand);
-
- stkFactory.createParam(cmdDetails, ctlvs, (aResult) => {
- cmdDetails.options = aResult;
- testFunc(context, cmdDetails, ctlvs);
- });
-}
-
-/**
- * Verify Proactive command helper : searchForSelectedTags
- */
-add_test(function test_stk_proactive_command_search_for_selected_tags() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let berHelper = context.BerTlvHelper;
- let stkHelper = context.StkProactiveCmdHelper;
-
- let tag_test = [
- 0xD0,
- 0x3E,
- 0x85, 0x0A, 0x61, 0x6C, 0x70, 0x68, 0x61, 0x20, 0x69, 0x64, 0x20, 0x31,
- 0x85, 0x0A, 0x61, 0x6C, 0x70, 0x68, 0x61, 0x20, 0x69, 0x64, 0x20, 0x32,
- 0x85, 0x0A, 0x61, 0x6C, 0x70, 0x68, 0x61, 0x20, 0x69, 0x64, 0x20, 0x33,
- 0x85, 0x0A, 0x61, 0x6C, 0x70, 0x68, 0x61, 0x20, 0x69, 0x64, 0x20, 0x34,
- 0x85, 0x0A, 0x61, 0x6C, 0x70, 0x68, 0x61, 0x20, 0x69, 0x64, 0x20, 0x35,
- 0x85, 0x00];
-
- for (let i = 0; i < tag_test.length; i++) {
- pduHelper.writeHexOctet(tag_test[i]);
- }
-
- let berTlv = berHelper.decode(tag_test.length);
- let selectedCtlvs =
- stkHelper.searchForSelectedTags(berTlv.value, [COMPREHENSIONTLV_TAG_ALPHA_ID]);
- let tlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- equal(tlv.value.identifier, "alpha id 1");
-
- tlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- equal(tlv.value.identifier, "alpha id 2");
-
- tlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- equal(tlv.value.identifier, "alpha id 3");
-
- tlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- equal(tlv.value.identifier, "alpha id 4");
-
- tlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- equal(tlv.value.identifier, "alpha id 5");
-
- // emulate that the alpha identifier is provided and is a null data object,
- // which is converted to an empty string in ICCPDUHelper.
- tlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- strictEqual(tlv.value.identifier, "");
-
- // emulate that the alpha identifier is not provided
- tlv = selectedCtlvs.retrieve(COMPREHENSIONTLV_TAG_ALPHA_ID);
- strictEqual(tlv, undefined);
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Refresh
- */
-add_test(function test_stk_proactive_command_refresh() {
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x10,
- 0x81, 0x03, 0x01, 0x01, 0x01,
- 0x82, 0x02, 0x81, 0x82,
- 0x92, 0x05, 0x01, 0x3F, 0x00, 0x2F, 0xE2
- ],
- typeOfCommand: STK_CMD_REFRESH,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let stkHelper = context.StkProactiveCmdHelper;
- let ctlv = stkHelper.searchForTag(COMPREHENSIONTLV_TAG_FILE_LIST, ctlvs);
- equal(ctlv.value.fileList, "3F002FE2");
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Play Tone
- */
-add_test(function test_stk_proactive_command_play_tone() {
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x1F,
- 0x81, 0x03, 0x01, 0x20, 0x00,
- 0x82, 0x02, 0x81, 0x03,
- 0x85, 0x09, 0x44, 0x69, 0x61, 0x6C, 0x20, 0x54, 0x6F, 0x6E, 0x65,
- 0x8E, 0x01, 0x01,
- 0x84, 0x02, 0x01, 0x05,
- 0x9E, 0x02, 0x00, 0x01
- ],
- typeOfCommand: STK_CMD_PLAY_TONE,
- icons: [1],
- testFunc: (context, cmdDetails, ctlvs) => {
- let playTone = cmdDetails.options;
-
- equal(playTone.text, "Dial Tone");
- equal(playTone.tone, STK_TONE_TYPE_DIAL_TONE);
- equal(playTone.duration.timeUnit, STK_TIME_UNIT_SECOND);
- equal(playTone.duration.timeInterval, 5);
- equal(playTone.iconSelfExplanatory, true);
- equal(playTone.icons, 1);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Poll Interval
- */
-add_test(function test_stk_proactive_command_poll_interval() {
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x0D,
- 0x81, 0x03, 0x01, 0x03, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x84, 0x02, 0x01, 0x14
- ],
- typeOfCommand: STK_CMD_POLL_INTERVAL,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let interval = cmdDetails.options;
-
- equal(interval.timeUnit, STK_TIME_UNIT_SECOND);
- equal(interval.timeInterval, 0x14);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command: Display Text
- */
-add_test(function test_stk_proactive_command_display_text() {
- test_stk_proactive_command({
- pdu: [
- 0xd0,
- 0x2c,
- 0x81, 0x03, 0x01, 0x21, 0x80,
- 0x82, 0x02, 0x81, 0x02,
- 0x0d, 0x1d, 0x00, 0xd3, 0x30, 0x9b, 0xfc, 0x06, 0xc9, 0x5c, 0x30, 0x1a,
- 0xa8, 0xe8, 0x02, 0x59, 0xc3, 0xec, 0x34, 0xb9, 0xac, 0x07, 0xc9, 0x60,
- 0x2f, 0x58, 0xed, 0x15, 0x9b, 0xb9, 0x40,
- 0x9e, 0x02, 0x00, 0x01
- ],
- typeOfCommand: STK_CMD_DISPLAY_TEXT,
- icons: [1],
- testFunc: (context, cmdDetails, ctlvs) => {
- let textMsg = cmdDetails.options;
-
- equal(textMsg.text, "Saldo 2.04 E. Validez 20/05/13. ");
- equal(textMsg.iconSelfExplanatory, true);
- equal(textMsg.icons, 1);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command: Set Up Event List.
- */
-add_test(function test_stk_proactive_command_event_list() {
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x0F,
- 0x81, 0x03, 0x01, 0x05, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x99, 0x04, 0x00, 0x01, 0x02, 0x03
- ],
- typeOfCommand: STK_CMD_SET_UP_EVENT_LIST,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let event = cmdDetails.options;
-
- equal(Array.isArray(event.eventList), true);
-
- for (let i = 0; i < event.eventList.length; i++) {
- equal(event.eventList[i], i);
- }
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Get Input
- */
-add_test(function test_stk_proactive_command_get_input() {
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x22,
- 0x81, 0x03, 0x01, 0x23, 0x8F,
- 0x82, 0x02, 0x81, 0x82,
- 0x8D, 0x05, 0x04, 0x54, 0x65, 0x78, 0x74,
- 0x91, 0x02, 0x01, 0x10,
- 0x17, 0x08, 0x04, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74,
- 0x9E, 0x02, 0x00, 0x01
- ],
- typeOfCommand: STK_CMD_GET_INPUT,
- icons: [1],
- testFunc: (context, cmdDetails, ctlvs) => {
- let input = cmdDetails.options;
-
- equal(input.text, "Text");
- equal(input.isAlphabet, true);
- equal(input.isUCS2, true);
- equal(input.hideInput, true);
- equal(input.isPacked, true);
- equal(input.isHelpAvailable, true);
- equal(input.minLength, 0x01);
- equal(input.maxLength, 0x10);
- equal(input.defaultText, "Default");
- equal(input.iconSelfExplanatory, true);
- equal(input.icons, 1);
- }
- });
-
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x11,
- 0x81, 0x03, 0x01, 0x23, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x8D, 0x00,
- 0x91, 0x02, 0x01, 0x10,
- 0x17, 0x00
- ],
- typeOfCommand: STK_CMD_GET_INPUT,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let input = cmdDetails.options;
-
- equal(input.text, null);
- equal(input.minLength, 0x01);
- equal(input.maxLength, 0x10);
- equal(input.defaultText, null);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : More Time
- */
-add_test(function test_stk_proactive_command_more_time() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let berHelper = context.BerTlvHelper;
- let stkHelper = context.StkProactiveCmdHelper;
-
- let more_time_1 = [
- 0xD0,
- 0x09,
- 0x81, 0x03, 0x01, 0x02, 0x00,
- 0x82, 0x02, 0x81, 0x82];
-
- for(let i = 0 ; i < more_time_1.length; i++) {
- pduHelper.writeHexOctet(more_time_1[i]);
- }
-
- let berTlv = berHelper.decode(more_time_1.length);
- let ctlvs = berTlv.value;
- let tlv = stkHelper.searchForTag(COMPREHENSIONTLV_TAG_COMMAND_DETAILS, ctlvs);
- equal(tlv.value.commandNumber, 0x01);
- equal(tlv.value.typeOfCommand, STK_CMD_MORE_TIME);
- equal(tlv.value.commandQualifier, 0x00);
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Select Item
- */
-add_test(function test_stk_proactive_command_select_item() {
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x3D,
- 0x81, 0x03, 0x01, 0x24, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x85, 0x05, 0x54, 0x69, 0x74, 0x6C, 0x65,
- 0x8F, 0x07, 0x01, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x31,
- 0x8F, 0x07, 0x02, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x32,
- 0x8F, 0x07, 0x03, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x33,
- 0x18, 0x03, 0x10, 0x15, 0x20,
- 0x90, 0x01, 0x01,
- 0x9E, 0x02, 0x00, 0x01,
- 0x9F, 0x04, 0x00, 0x01, 0x02, 0x03
- ],
- typeOfCommand: STK_CMD_SELECT_ITEM,
- icons: [1, 1, 2, 3],
- testFunc: (context, cmdDetails, ctlvs) => {
- let menu = cmdDetails.options;
-
- equal(menu.title, "Title");
- equal(menu.iconSelfExplanatory, true);
- equal(menu.icons, 1);
- equal(menu.items[0].identifier, 1);
- equal(menu.items[0].text, "item 1");
- equal(menu.items[0].iconSelfExplanatory, true);
- equal(menu.items[0].icons, 1);
- equal(menu.items[1].identifier, 2);
- equal(menu.items[1].text, "item 2");
- equal(menu.items[1].iconSelfExplanatory, true);
- equal(menu.items[1].icons, 2);
- equal(menu.items[2].identifier, 3);
- equal(menu.items[2].text, "item 3");
- equal(menu.items[2].iconSelfExplanatory, true);
- equal(menu.items[2].icons, 3);
- equal(menu.nextActionList[0], STK_CMD_SET_UP_CALL);
- equal(menu.nextActionList[1], STK_CMD_LAUNCH_BROWSER);
- equal(menu.nextActionList[2], STK_CMD_PLAY_TONE);
- equal(menu.defaultItem, 0x00);
- }
- });
-
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x33,
- 0x81, 0x03, 0x01, 0x24, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x85, 0x05, 0x54, 0x69, 0x74, 0x6C, 0x65,
- 0x8F, 0x07, 0x01, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x31,
- 0x8F, 0x07, 0x02, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x32,
- 0x8F, 0x07, 0x03, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x33,
- 0x18, 0x03, 0x00, 0x15, 0x81,
- 0x90, 0x01, 0x03
- ],
- typeOfCommand: STK_CMD_SELECT_ITEM,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let menu = cmdDetails.options;
-
- equal(menu.title, "Title");
- equal(menu.items[0].identifier, 1);
- equal(menu.items[0].text, "item 1");
- equal(menu.items[1].identifier, 2);
- equal(menu.items[1].text, "item 2");
- equal(menu.items[2].identifier, 3);
- equal(menu.items[2].text, "item 3");
- equal(menu.nextActionList[0], STK_NEXT_ACTION_NULL);
- equal(menu.nextActionList[1], STK_CMD_LAUNCH_BROWSER);
- equal(menu.nextActionList[2], STK_NEXT_ACTION_END_PROACTIVE_SESSION);
- equal(menu.defaultItem, 0x02);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Set Up Menu
- */
-add_test(function test_stk_proactive_command_set_up_menu() {
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x3A,
- 0x81, 0x03, 0x01, 0x25, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x85, 0x05, 0x54, 0x69, 0x74, 0x6C, 0x65,
- 0x8F, 0x07, 0x01, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x31,
- 0x8F, 0x07, 0x02, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x32,
- 0x8F, 0x07, 0x03, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x33,
- 0x18, 0x03, 0x10, 0x15, 0x20,
- 0x9E, 0x02, 0x00, 0x01,
- 0x9F, 0x04, 0x00, 0x01, 0x02, 0x03
- ],
- typeOfCommand: STK_CMD_SET_UP_MENU,
- icons: [1, 1, 2, 3],
- testFunc: (context, cmdDetails, ctlvs) => {
- let menu = cmdDetails.options;
-
- equal(menu.title, "Title");
- equal(menu.iconSelfExplanatory, true);
- equal(menu.icons, 1);
- equal(menu.items[0].identifier, 1);
- equal(menu.items[0].text, "item 1");
- equal(menu.items[0].iconSelfExplanatory, true);
- equal(menu.items[0].icons, 1);
- equal(menu.items[1].identifier, 2);
- equal(menu.items[1].text, "item 2");
- equal(menu.items[1].iconSelfExplanatory, true);
- equal(menu.items[1].icons, 2);
- equal(menu.items[2].identifier, 3);
- equal(menu.items[2].text, "item 3");
- equal(menu.items[2].iconSelfExplanatory, true);
- equal(menu.items[2].icons, 3);
- equal(menu.nextActionList[0], STK_CMD_SET_UP_CALL);
- equal(menu.nextActionList[1], STK_CMD_LAUNCH_BROWSER);
- equal(menu.nextActionList[2], STK_CMD_PLAY_TONE);
- }
- });
-
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x30,
- 0x81, 0x03, 0x01, 0x25, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x85, 0x05, 0x54, 0x69, 0x74, 0x6C, 0x65,
- 0x8F, 0x07, 0x01, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x31,
- 0x8F, 0x07, 0x02, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x32,
- 0x8F, 0x07, 0x03, 0x69, 0x74, 0x65, 0x6D, 0x20, 0x33,
- 0x18, 0x03, 0x81, 0x00, 0x00
- ],
- typeOfCommand: STK_CMD_SET_UP_MENU,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let menu = cmdDetails.options;
-
- equal(menu.title, "Title");
- equal(menu.items[0].identifier, 1);
- equal(menu.items[0].text, "item 1");
- equal(menu.items[1].identifier, 2);
- equal(menu.items[1].text, "item 2");
- equal(menu.items[2].identifier, 3);
- equal(menu.items[2].text, "item 3");
- equal(menu.nextActionList[0], STK_NEXT_ACTION_END_PROACTIVE_SESSION);
- equal(menu.nextActionList[1], STK_NEXT_ACTION_NULL);
- equal(menu.nextActionList[2], STK_NEXT_ACTION_NULL);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Set Up Call
- */
-add_test(function test_stk_proactive_command_set_up_call() {
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x31,
- 0x81, 0x03, 0x01, 0x10, 0x04,
- 0x82, 0x02, 0x81, 0x82,
- 0x05, 0x0A, 0x44, 0x69, 0x73, 0x63, 0x6F, 0x6E, 0x6E, 0x65, 0x63, 0x74,
- 0x86, 0x09, 0x81, 0x10, 0x32, 0x04, 0x21, 0x43, 0x65, 0x1C, 0x2C,
- 0x05, 0x07, 0x4D, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
- 0x9E, 0x02, 0x00, 0x01,
- 0x9E, 0x02, 0x01, 0x02
- ],
- typeOfCommand: STK_CMD_SET_UP_CALL,
- icons: [1, 2],
- testFunc: (context, cmdDetails, ctlvs) => {
- let setupCall = cmdDetails.options;
-
- equal(setupCall.address, "012340123456,1,2");
- equal(setupCall.confirmMessage.text, "Disconnect");
- equal(setupCall.confirmMessage.iconSelfExplanatory, true);
- equal(setupCall.confirmMessage.icons, 1);
- equal(setupCall.callMessage.text, "Message");
- equal(setupCall.callMessage.iconSelfExplanatory, false);
- equal(setupCall.callMessage.icons, 2);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Timer Management
- */
-add_test(function test_stk_proactive_command_timer_management() {
- // Timer Management - Start
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x11,
- 0x81, 0x03, 0x01, 0x27, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0xA4, 0x01, 0x01,
- 0xA5, 0x03, 0x10, 0x20, 0x30
- ],
- typeOfCommand: STK_CMD_TIMER_MANAGEMENT,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- equal(cmdDetails.commandQualifier, STK_TIMER_START);
-
- let timer = cmdDetails.options;
-
- equal(timer.timerId, 0x01);
- equal(timer.timerValue, (0x01 * 60 * 60) + (0x02 * 60) + 0x03);
- }
- });
-
- // Timer Management - Deactivate
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x0C,
- 0x81, 0x03, 0x01, 0x27, 0x01,
- 0x82, 0x02, 0x81, 0x82,
- 0xA4, 0x01, 0x01
- ],
- typeOfCommand: STK_CMD_TIMER_MANAGEMENT,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- equal(cmdDetails.commandQualifier, STK_TIMER_DEACTIVATE);
-
- let timer = cmdDetails.options;
-
- equal(timer.timerId, 0x01);
- ok(timer.timerValue === undefined);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive Command : Provide Local Information
- */
-add_test(function test_stk_proactive_command_provide_local_information() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let berHelper = context.BerTlvHelper;
- let stkHelper = context.StkProactiveCmdHelper;
- let stkCmdHelper = context.StkCommandParamsFactory;
-
- // Verify IMEI
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x09,
- 0x81, 0x03, 0x01, 0x26, 0x01,
- 0x82, 0x02, 0x81, 0x82
- ],
- typeOfCommand: STK_CMD_PROVIDE_LOCAL_INFO,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- equal(cmdDetails.commandQualifier, STK_LOCAL_INFO_IMEI);
-
- let provideLocalInfo = cmdDetails.options;
- equal(provideLocalInfo.localInfoType, STK_LOCAL_INFO_IMEI);
- }
- });
-
- // Verify Date and Time Zone
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x09,
- 0x81, 0x03, 0x01, 0x26, 0x03,
- 0x82, 0x02, 0x81, 0x82
- ],
- typeOfCommand: STK_CMD_PROVIDE_LOCAL_INFO,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- equal(cmdDetails.commandQualifier, STK_LOCAL_INFO_DATE_TIME_ZONE);
-
- let provideLocalInfo = cmdDetails.options;
- equal(provideLocalInfo.localInfoType, STK_LOCAL_INFO_DATE_TIME_ZONE);
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Proactive command : BIP Messages
- */
-add_test(function test_stk_proactive_command_open_channel() {
- let worker = newUint8Worker();
- let context = worker.ContextPool._contexts[0];
- let pduHelper = context.GsmPDUHelper;
- let berHelper = context.BerTlvHelper;
- let stkHelper = context.StkProactiveCmdHelper;
- let stkCmdHelper = context.StkCommandParamsFactory;
-
- // Open Channel
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x0F,
- 0x81, 0x03, 0x01, 0x40, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x85, 0x04, 0x4F, 0x70, 0x65, 0x6E //alpha id: "Open"
- ],
- typeOfCommand: STK_CMD_OPEN_CHANNEL,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let bipMsg = cmdDetails.options;
-
- equal(bipMsg.text, "Open");
- }
- });
-
- // Close Channel
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x10,
- 0x81, 0x03, 0x01, 0x41, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x85, 0x05, 0x43, 0x6C, 0x6F, 0x73, 0x65 //alpha id: "Close"
- ],
- typeOfCommand: STK_CMD_CLOSE_CHANNEL,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let bipMsg = cmdDetails.options;
-
- equal(bipMsg.text, "Close");
- }
- });
-
- // Receive Data
- test_stk_proactive_command({
- pdu: [
- 0XD0,
- 0X12,
- 0x81, 0x03, 0x01, 0x42, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x85, 0x07, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65 //alpha id: "Receive"
- ],
- typeOfCommand: STK_CMD_RECEIVE_DATA,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let bipMsg = cmdDetails.options;
-
- equal(bipMsg.text, "Receive");
- }
- });
-
- // Send Data
- test_stk_proactive_command({
- pdu: [
- 0xD0,
- 0x0F,
- 0x81, 0x03, 0x01, 0x43, 0x00,
- 0x82, 0x02, 0x81, 0x82,
- 0x85, 0x04, 0x53, 0x65, 0x6E, 0x64 //alpha id: "Send"
- ],
- typeOfCommand: STK_CMD_SEND_DATA,
- icons: null,
- testFunc: (context, cmdDetails, ctlvs) => {
- let bipMsg = cmdDetails.options;
-
- equal(bipMsg.text, "Send");
- }
- });
-
- run_next_test();
-});
-
-/**
- * Verify Event Download Command : Location Status
- */
-add_test(function test_stk_event_download_location_status() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_ENVELOPE_COMMAND);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 42 = 2 * (2 + TLV_DEVICE_ID_SIZE(4) +
- // TLV_EVENT_LIST_SIZE(3) +
- // TLV_LOCATION_STATUS_SIZE(3) +
- // TLV_LOCATION_INFO_GSM_SIZE(9))
- equal(this.readInt32(), 42);
-
- // BER tag
- equal(pduHelper.readHexOctet(), BER_EVENT_DOWNLOAD_TAG);
-
- // BER length, 19 = TLV_DEVICE_ID_SIZE(4) +
- // TLV_EVENT_LIST_SIZE(3) +
- // TLV_LOCATION_STATUS_SIZE(3) +
- // TLV_LOCATION_INFO_GSM_SIZE(9)
- equal(pduHelper.readHexOctet(), 19);
-
- // Event List, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_EVENT_LIST |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_EVENT_TYPE_LOCATION_STATUS);
-
- // Device Identifies, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Location Status, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_LOCATION_STATUS |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_SERVICE_STATE_NORMAL);
-
- // Location Info, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_LOCATION_INFO |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 7);
-
- equal(pduHelper.readHexOctet(), 0x21); // MCC + MNC
- equal(pduHelper.readHexOctet(), 0x63);
- equal(pduHelper.readHexOctet(), 0x54);
- equal(pduHelper.readHexOctet(), 0); // LAC
- equal(pduHelper.readHexOctet(), 0);
- equal(pduHelper.readHexOctet(), 0); // Cell ID
- equal(pduHelper.readHexOctet(), 0);
-
- run_next_test();
- };
-
- let event = {
- eventType: STK_EVENT_TYPE_LOCATION_STATUS,
- locationStatus: STK_SERVICE_STATE_NORMAL,
- locationInfo: {
- mcc: "123",
- mnc: "456",
- gsmLocationAreaCode: 0,
- gsmCellId: 0
- }
- };
- context.RIL.sendStkEventDownload({
- event: event
- });
-});
-
-// Test Event Download commands.
-
-/**
- * Verify Event Download Command : Language Selection
- */
-add_test(function test_stk_event_download_language_selection() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
- let iccHelper = context.ICCPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_ENVELOPE_COMMAND);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 26 = 2 * (2 + TLV_DEVICE_ID_SIZE(4) +
- // TLV_EVENT_LIST_SIZE(3) +
- // TLV_LANGUAGE(4))
- equal(this.readInt32(), 26);
-
- // BER tag
- equal(pduHelper.readHexOctet(), BER_EVENT_DOWNLOAD_TAG);
-
- // BER length, 19 = TLV_DEVICE_ID_SIZE(4) +
- // TLV_EVENT_LIST_SIZE(3) +
- // TLV_LANGUAGE(4)
- equal(pduHelper.readHexOctet(), 11);
-
- // Event List, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_EVENT_LIST |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_EVENT_TYPE_LANGUAGE_SELECTION);
-
- // Device Identifies, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Language, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_LANGUAGE);
- equal(pduHelper.readHexOctet(), 2);
- equal(iccHelper.read8BitUnpackedToString(2), "zh");
-
- run_next_test();
- };
-
- let event = {
- eventType: STK_EVENT_TYPE_LANGUAGE_SELECTION,
- language: "zh"
- };
- context.RIL.sendStkEventDownload({
- event: event
- });
-});
-
-/**
- * Verify Event Download Command : User Activity
- */
-add_test(function test_stk_event_download_user_activity() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_ENVELOPE_COMMAND);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 18 = 2 * (2 + TLV_DEVICE_ID_SIZE(4) + TLV_EVENT_LIST_SIZE(3))
- equal(this.readInt32(), 18);
-
- // BER tag
- equal(pduHelper.readHexOctet(), BER_EVENT_DOWNLOAD_TAG);
-
- // BER length, 7 = TLV_DEVICE_ID_SIZE(4) + TLV_EVENT_LIST_SIZE(3)
- equal(pduHelper.readHexOctet(), 7);
-
- // Event List, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_EVENT_LIST |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_EVENT_TYPE_USER_ACTIVITY);
-
- // Device Identities, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- run_next_test();
- };
-
- let event = {
- eventType: STK_EVENT_TYPE_USER_ACTIVITY
- };
- context.RIL.sendStkEventDownload({
- event: event
- });
-});
-
-/**
- * Verify Event Download Command : Idle Screen Available
- */
-add_test(function test_stk_event_download_idle_screen_available() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_ENVELOPE_COMMAND);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 18 = 2 * (2 + TLV_DEVICE_ID_SIZE(4) + TLV_EVENT_LIST_SIZE(3))
- equal(this.readInt32(), 18);
-
- // BER tag
- equal(pduHelper.readHexOctet(), BER_EVENT_DOWNLOAD_TAG);
-
- // BER length, 7 = TLV_DEVICE_ID_SIZE(4) + TLV_EVENT_LIST_SIZE(3)
- equal(pduHelper.readHexOctet(), 7);
-
- // Event List, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_EVENT_LIST |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_EVENT_TYPE_IDLE_SCREEN_AVAILABLE);
-
- // Device Identities, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_DISPLAY);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- run_next_test();
- };
-
- let event = {
- eventType: STK_EVENT_TYPE_IDLE_SCREEN_AVAILABLE
- };
- context.RIL.sendStkEventDownload({
- event: event
- });
-});
-
-/**
- * Verify Event Downloaded Command :Browser Termination
- */
-add_test(function test_stk_event_download_browser_termination() {
- let worker = newUint8SupportOutgoingIndexWorker();
- let context = worker.ContextPool._contexts[0];
- let buf = context.Buf;
- let pduHelper = context.GsmPDUHelper;
-
- buf.sendParcel = function() {
- // Type
- equal(this.readInt32(), REQUEST_STK_SEND_ENVELOPE_COMMAND);
-
- // Token : we don't care
- this.readInt32();
-
- // Data Size, 24 = 2 * ( 2+TLV_DEVICE_ID(4)+TLV_EVENT_LIST_SIZE(3)
- // +TLV_BROWSER_TERMINATION_CAUSE(3) )
- equal(this.readInt32(), 24);
-
- // BER tag
- equal(pduHelper.readHexOctet(), BER_EVENT_DOWNLOAD_TAG);
-
- // BER length, 10 = TLV_DEVICE_ID(4)+TLV_EVENT_LIST_SIZE(3)
- // ++TLV_BROWSER_TERMINATION_CAUSE(3)
- equal(pduHelper.readHexOctet(), 10);
-
- // Event List, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_EVENT_LIST |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_EVENT_TYPE_BROWSER_TERMINATION);
-
- // Device Identities, Type-Length-Value(Source ID-Destination ID)
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_DEVICE_ID |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 2);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_ME);
- equal(pduHelper.readHexOctet(), STK_DEVICE_ID_SIM);
-
- // Browser Termination Case, Type-Length-Value
- equal(pduHelper.readHexOctet(), COMPREHENSIONTLV_TAG_BROWSER_TERMINATION_CAUSE |
- COMPREHENSIONTLV_FLAG_CR);
- equal(pduHelper.readHexOctet(), 1);
- equal(pduHelper.readHexOctet(), STK_BROWSER_TERMINATION_CAUSE_USER);
-
- run_next_test();
- };
-
- let event = {
- eventType: STK_EVENT_TYPE_BROWSER_TERMINATION,
- terminationCause: STK_BROWSER_TERMINATION_CAUSE_USER
- };
- context.RIL.sendStkEventDownload({
- event: event
- });
-});
diff --git a/dom/system/gonk/tests/test_ril_worker_voiceprivacy.js b/dom/system/gonk/tests/test_ril_worker_voiceprivacy.js
deleted file mode 100644
index 21829da22..000000000
--- a/dom/system/gonk/tests/test_ril_worker_voiceprivacy.js
+++ /dev/null
@@ -1,94 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-subscriptLoader.loadSubScript("resource://gre/modules/ril_consts.js", this);
-
-function run_test() {
- run_next_test();
-}
-
-add_test(function test_setVoicePrivacyMode_success() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL.setVoicePrivacyMode = function fakeSetVoicePrivacyMode(options) {
- context.RIL[REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE](0, {});
- };
-
- context.RIL.setVoicePrivacyMode({
- enabled: true
- });
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
-
- run_next_test();
-});
-
-add_test(function test_setVoicePrivacyMode_generic_failure() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.RIL.setVoicePrivacyMode = function fakeSetVoicePrivacyMode(options) {
- context.RIL[REQUEST_CDMA_SET_PREFERRED_VOICE_PRIVACY_MODE](0, {
- errorMsg: GECKO_ERROR_GENERIC_FAILURE
- });
- };
-
- context.RIL.setVoicePrivacyMode({
- enabled: true
- });
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, GECKO_ERROR_GENERIC_FAILURE);
-
- run_next_test();
-});
-
-add_test(function test_queryVoicePrivacyMode_success_enabled_true() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.readInt32List = function fakeReadUint32List() {
- return [1];
- };
-
- context.RIL.queryVoicePrivacyMode = function fakeQueryVoicePrivacyMode(options) {
- context.RIL[REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE](1, {});
- };
-
- context.RIL.queryVoicePrivacyMode();
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
- ok(postedMessage.enabled);
- run_next_test();
-});
-
-add_test(function test_queryVoicePrivacyMode_success_enabled_false() {
- let workerHelper = newInterceptWorker();
- let worker = workerHelper.worker;
- let context = worker.ContextPool._contexts[0];
-
- context.Buf.readInt32List = function fakeReadUint32List() {
- return [0];
- };
-
- context.RIL.queryVoicePrivacyMode = function fakeQueryVoicePrivacyMode(options) {
- context.RIL[REQUEST_CDMA_QUERY_PREFERRED_VOICE_PRIVACY_MODE](1, {});
- };
-
- context.RIL.queryVoicePrivacyMode();
-
- let postedMessage = workerHelper.postedMessage;
-
- equal(postedMessage.errorMsg, undefined);
- ok(!postedMessage.enabled);
- run_next_test();
-});
diff --git a/dom/system/gonk/tests/xpcshell.ini b/dom/system/gonk/tests/xpcshell.ini
deleted file mode 100644
index 1e8b798a3..000000000
--- a/dom/system/gonk/tests/xpcshell.ini
+++ /dev/null
@@ -1,43 +0,0 @@
-[DEFAULT]
-head = header_helpers.js
-tail =
-
-[test_ril_worker_buf.js]
-[test_ril_worker_icc_CardLock.js]
-[test_ril_worker_icc_CardState.js]
-[test_ril_worker_icc_BerTlvHelper.js]
-[test_ril_worker_icc_GsmPDUHelper.js]
-[test_ril_worker_icc_ICCContactHelper.js]
-[test_ril_worker_icc_ICCIOHelper.js]
-[test_ril_worker_icc_ICCPDUHelper.js]
-[test_ril_worker_icc_ICCRecordHelper.js]
-[test_ril_worker_icc_IconLoader.js]
-[test_ril_worker_icc_ICCUtilsHelper.js]
-[test_ril_worker_icc_SimRecordHelper.js]
-[test_ril_worker_sms.js]
-# Bug 916067 - B2G RIL: test_ril_worker_sms.js takes too long to finish
-skip-if = true
-[test_ril_worker_sms_cdma.js]
-[test_ril_worker_sms_cdmapduhelper.js]
-[test_ril_worker_sms_nl_tables.js]
-[test_ril_worker_sms_gsmpduhelper.js]
-[test_ril_worker_sms_segment_info.js]
-[test_ril_worker_smsc_address.js]
-[test_ril_worker_cf.js]
-[test_ril_worker_cellbroadcast_config.js]
-[test_ril_worker_cellbroadcast_gsm.js]
-[test_ril_worker_cellbroadcast_umts.js]
-[test_ril_worker_ruim.js]
-[test_ril_worker_cw.js]
-[test_ril_worker_clir.js]
-[test_ril_worker_clip.js]
-[test_ril_worker_ssn.js]
-[test_ril_worker_voiceprivacy.js]
-[test_ril_worker_ecm.js]
-[test_ril_worker_stk.js]
-requesttimeoutfactor = 4
-[test_ril_worker_barring_password.js]
-[test_ril_worker_cdma_info_rec.js]
-[test_ril_system_messenger.js]
-# header_helpers.js is not needed for test_ril_system_messenger.js
-head =
diff --git a/dom/system/gonk/worker_buf.js b/dom/system/gonk/worker_buf.js
deleted file mode 100644
index 7064eeac5..000000000
--- a/dom/system/gonk/worker_buf.js
+++ /dev/null
@@ -1,623 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 object contains helpers buffering incoming data & deconstructing it
- * into parcels as well as buffering outgoing data & constructing parcels.
- * For that it maintains two buffers and corresponding uint8 views, indexes.
- *
- * The incoming buffer is a circular buffer where we store incoming data.
- * As soon as a complete parcel is received, it is processed right away, so
- * the buffer only needs to be large enough to hold one parcel.
- *
- * The outgoing buffer is to prepare outgoing parcels. The index is reset
- * every time a parcel is sent.
- */
-
-var Buf = {
- INT32_MAX: 2147483647,
- UINT8_SIZE: 1,
- UINT16_SIZE: 2,
- UINT32_SIZE: 4,
- PARCEL_SIZE_SIZE: 4,
- PDU_HEX_OCTET_SIZE: 4,
-
- incomingBufferLength: 1024,
- incomingBuffer: null,
- incomingBytes: null,
- incomingWriteIndex: 0,
- incomingReadIndex: 0,
- readIncoming: 0,
- readAvailable: 0,
- currentParcelSize: 0,
-
- outgoingBufferLength: 1024,
- outgoingBuffer: null,
- outgoingBytes: null,
- outgoingIndex: 0,
- outgoingBufferCalSizeQueue: null,
-
- _init: function() {
- this.incomingBuffer = new ArrayBuffer(this.incomingBufferLength);
- this.outgoingBuffer = new ArrayBuffer(this.outgoingBufferLength);
-
- this.incomingBytes = new Uint8Array(this.incomingBuffer);
- this.outgoingBytes = new Uint8Array(this.outgoingBuffer);
-
- // Track where incoming data is read from and written to.
- this.incomingWriteIndex = 0;
- this.incomingReadIndex = 0;
-
- // Leave room for the parcel size for outgoing parcels.
- this.outgoingIndex = this.PARCEL_SIZE_SIZE;
-
- // How many bytes we've read for this parcel so far.
- this.readIncoming = 0;
-
- // How many bytes available as parcel data.
- this.readAvailable = 0;
-
- // Size of the incoming parcel. If this is zero, we're expecting a new
- // parcel.
- this.currentParcelSize = 0;
-
- // Queue for storing outgoing override points
- this.outgoingBufferCalSizeQueue = [];
- },
-
- /**
- * Mark current outgoingIndex as start point for calculation length of data
- * written to outgoingBuffer.
- * Mark can be nested for here uses queue to remember marks.
- *
- * @param writeFunction
- * Function to write data length into outgoingBuffer, this function is
- * also used to allocate buffer for data length.
- * Raw data size(in Uint8) is provided as parameter calling writeFunction.
- * If raw data size is not in proper unit for writing, user can adjust
- * the length value in writeFunction before writing.
- **/
- startCalOutgoingSize: function(writeFunction) {
- let sizeInfo = {index: this.outgoingIndex,
- write: writeFunction};
-
- // Allocate buffer for data lemgtj.
- writeFunction.call(0);
-
- // Get size of data length buffer for it is not counted into data size.
- sizeInfo.size = this.outgoingIndex - sizeInfo.index;
-
- // Enqueue size calculation information.
- this.outgoingBufferCalSizeQueue.push(sizeInfo);
- },
-
- /**
- * Calculate data length since last mark, and write it into mark position.
- **/
- stopCalOutgoingSize: function() {
- let sizeInfo = this.outgoingBufferCalSizeQueue.pop();
-
- // Remember current outgoingIndex.
- let currentOutgoingIndex = this.outgoingIndex;
- // Calculate data length, in uint8.
- let writeSize = this.outgoingIndex - sizeInfo.index - sizeInfo.size;
-
- // Write data length to mark, use same function for allocating buffer to make
- // sure there is no buffer overloading.
- this.outgoingIndex = sizeInfo.index;
- sizeInfo.write(writeSize);
-
- // Restore outgoingIndex.
- this.outgoingIndex = currentOutgoingIndex;
- },
-
- /**
- * Grow the incoming buffer.
- *
- * @param min_size
- * Minimum new size. The actual new size will be the the smallest
- * power of 2 that's larger than this number.
- */
- growIncomingBuffer: function(min_size) {
- if (DEBUG) {
- debug("Current buffer of " + this.incomingBufferLength +
- " can't handle incoming " + min_size + " bytes.");
- }
- let oldBytes = this.incomingBytes;
- this.incomingBufferLength =
- 2 << Math.floor(Math.log(min_size)/Math.log(2));
- if (DEBUG) debug("New incoming buffer size: " + this.incomingBufferLength);
- this.incomingBuffer = new ArrayBuffer(this.incomingBufferLength);
- this.incomingBytes = new Uint8Array(this.incomingBuffer);
- if (this.incomingReadIndex <= this.incomingWriteIndex) {
- // Read and write index are in natural order, so we can just copy
- // the old buffer over to the bigger one without having to worry
- // about the indexes.
- this.incomingBytes.set(oldBytes, 0);
- } else {
- // The write index has wrapped around but the read index hasn't yet.
- // Write whatever the read index has left to read until it would
- // circle around to the beginning of the new buffer, and the rest
- // behind that.
- let head = oldBytes.subarray(this.incomingReadIndex);
- let tail = oldBytes.subarray(0, this.incomingReadIndex);
- this.incomingBytes.set(head, 0);
- this.incomingBytes.set(tail, head.length);
- this.incomingReadIndex = 0;
- this.incomingWriteIndex += head.length;
- }
- if (DEBUG) {
- debug("New incoming buffer size is " + this.incomingBufferLength);
- }
- },
-
- /**
- * Grow the outgoing buffer.
- *
- * @param min_size
- * Minimum new size. The actual new size will be the the smallest
- * power of 2 that's larger than this number.
- */
- growOutgoingBuffer: function(min_size) {
- if (DEBUG) {
- debug("Current buffer of " + this.outgoingBufferLength +
- " is too small.");
- }
- let oldBytes = this.outgoingBytes;
- this.outgoingBufferLength =
- 2 << Math.floor(Math.log(min_size)/Math.log(2));
- this.outgoingBuffer = new ArrayBuffer(this.outgoingBufferLength);
- this.outgoingBytes = new Uint8Array(this.outgoingBuffer);
- this.outgoingBytes.set(oldBytes, 0);
- if (DEBUG) {
- debug("New outgoing buffer size is " + this.outgoingBufferLength);
- }
- },
-
- /**
- * Functions for reading data from the incoming buffer.
- *
- * These are all little endian, apart from readParcelSize();
- */
-
- /**
- * Ensure position specified is readable.
- *
- * @param index
- * Data position in incoming parcel, valid from 0 to
- * currentParcelSize.
- */
- ensureIncomingAvailable: function(index) {
- if (index >= this.currentParcelSize) {
- throw new Error("Trying to read data beyond the parcel end!");
- } else if (index < 0) {
- throw new Error("Trying to read data before the parcel begin!");
- }
- },
-
- /**
- * Seek in current incoming parcel.
- *
- * @param offset
- * Seek offset in relative to current position.
- */
- seekIncoming: function(offset) {
- // Translate to 0..currentParcelSize
- let cur = this.currentParcelSize - this.readAvailable;
-
- let newIndex = cur + offset;
- this.ensureIncomingAvailable(newIndex);
-
- // ... incomingReadIndex -->|
- // 0 new cur currentParcelSize
- // |================|=======|====================|
- // |<-- cur -->|<- readAvailable ->|
- // |<-- newIndex -->|<-- new readAvailable -->|
- this.readAvailable = this.currentParcelSize - newIndex;
-
- // Translate back:
- if (this.incomingReadIndex < cur) {
- // The incomingReadIndex is wrapped.
- newIndex += this.incomingBufferLength;
- }
- newIndex += (this.incomingReadIndex - cur);
- newIndex %= this.incomingBufferLength;
- this.incomingReadIndex = newIndex;
- },
-
- readUint8Unchecked: function() {
- let value = this.incomingBytes[this.incomingReadIndex];
- this.incomingReadIndex = (this.incomingReadIndex + 1) %
- this.incomingBufferLength;
- return value;
- },
-
- readUint8: function() {
- // Translate to 0..currentParcelSize
- let cur = this.currentParcelSize - this.readAvailable;
- this.ensureIncomingAvailable(cur);
-
- this.readAvailable--;
- return this.readUint8Unchecked();
- },
-
- readUint8Array: function(length) {
- // Translate to 0..currentParcelSize
- let last = this.currentParcelSize - this.readAvailable;
- last += (length - 1);
- this.ensureIncomingAvailable(last);
-
- let array = new Uint8Array(length);
- for (let i = 0; i < length; i++) {
- array[i] = this.readUint8Unchecked();
- }
-
- this.readAvailable -= length;
- return array;
- },
-
- readUint16: function() {
- return this.readUint8() | this.readUint8() << 8;
- },
-
- readInt32: function() {
- return this.readUint8() | this.readUint8() << 8 |
- this.readUint8() << 16 | this.readUint8() << 24;
- },
-
- readInt64: function() {
- // Avoid using bitwise operators as the operands of all bitwise operators
- // are converted to signed 32-bit integers.
- return this.readUint8() +
- this.readUint8() * Math.pow(2, 8) +
- this.readUint8() * Math.pow(2, 16) +
- this.readUint8() * Math.pow(2, 24) +
- this.readUint8() * Math.pow(2, 32) +
- this.readUint8() * Math.pow(2, 40) +
- this.readUint8() * Math.pow(2, 48) +
- this.readUint8() * Math.pow(2, 56);
- },
-
- readInt32List: function() {
- let length = this.readInt32();
- let ints = [];
- for (let i = 0; i < length; i++) {
- ints.push(this.readInt32());
- }
- return ints;
- },
-
- readString: function() {
- let string_len = this.readInt32();
- if (string_len < 0 || string_len >= this.INT32_MAX) {
- return null;
- }
- let s = "";
- for (let i = 0; i < string_len; i++) {
- s += String.fromCharCode(this.readUint16());
- }
- // Strings are \0\0 delimited, but that isn't part of the length. And
- // if the string length is even, the delimiter is two characters wide.
- // It's insane, I know.
- this.readStringDelimiter(string_len);
- return s;
- },
-
- readStringList: function() {
- let num_strings = this.readInt32();
- let strings = [];
- for (let i = 0; i < num_strings; i++) {
- strings.push(this.readString());
- }
- return strings;
- },
-
- readStringDelimiter: function(length) {
- let delimiter = this.readUint16();
- if (!(length & 1)) {
- delimiter |= this.readUint16();
- }
- if (DEBUG) {
- if (delimiter !== 0) {
- debug("Something's wrong, found string delimiter: " + delimiter);
- }
- }
- },
-
- readParcelSize: function() {
- return this.readUint8Unchecked() << 24 |
- this.readUint8Unchecked() << 16 |
- this.readUint8Unchecked() << 8 |
- this.readUint8Unchecked();
- },
-
- /**
- * Functions for writing data to the outgoing buffer.
- */
-
- /**
- * Ensure position specified is writable.
- *
- * @param index
- * Data position in outgoing parcel, valid from 0 to
- * outgoingBufferLength.
- */
- ensureOutgoingAvailable: function(index) {
- if (index >= this.outgoingBufferLength) {
- this.growOutgoingBuffer(index + 1);
- }
- },
-
- writeUint8: function(value) {
- this.ensureOutgoingAvailable(this.outgoingIndex);
-
- this.outgoingBytes[this.outgoingIndex] = value;
- this.outgoingIndex++;
- },
-
- writeUint16: function(value) {
- this.writeUint8(value & 0xff);
- this.writeUint8((value >> 8) & 0xff);
- },
-
- writeInt32: function(value) {
- this.writeUint8(value & 0xff);
- this.writeUint8((value >> 8) & 0xff);
- this.writeUint8((value >> 16) & 0xff);
- this.writeUint8((value >> 24) & 0xff);
- },
-
- writeString: function(value) {
- if (value == null) {
- this.writeInt32(-1);
- return;
- }
- this.writeInt32(value.length);
- for (let i = 0; i < value.length; i++) {
- this.writeUint16(value.charCodeAt(i));
- }
- // Strings are \0\0 delimited, but that isn't part of the length. And
- // if the string length is even, the delimiter is two characters wide.
- // It's insane, I know.
- this.writeStringDelimiter(value.length);
- },
-
- writeStringList: function(strings) {
- this.writeInt32(strings.length);
- for (let i = 0; i < strings.length; i++) {
- this.writeString(strings[i]);
- }
- },
-
- writeStringDelimiter: function(length) {
- this.writeUint16(0);
- if (!(length & 1)) {
- this.writeUint16(0);
- }
- },
-
- writeParcelSize: function(value) {
- /**
- * Parcel size will always be the first thing in the parcel byte
- * array, but the last thing written. Store the current index off
- * to a temporary to be reset after we write the size.
- */
- let currentIndex = this.outgoingIndex;
- this.outgoingIndex = 0;
- this.writeUint8((value >> 24) & 0xff);
- this.writeUint8((value >> 16) & 0xff);
- this.writeUint8((value >> 8) & 0xff);
- this.writeUint8(value & 0xff);
- this.outgoingIndex = currentIndex;
- },
-
- copyIncomingToOutgoing: function(length) {
- if (!length || (length < 0)) {
- return;
- }
-
- let translatedReadIndexEnd =
- this.currentParcelSize - this.readAvailable + length - 1;
- this.ensureIncomingAvailable(translatedReadIndexEnd);
-
- let translatedWriteIndexEnd = this.outgoingIndex + length - 1;
- this.ensureOutgoingAvailable(translatedWriteIndexEnd);
-
- let newIncomingReadIndex = this.incomingReadIndex + length;
- if (newIncomingReadIndex < this.incomingBufferLength) {
- // Reading won't cause wrapping, go ahead with builtin copy.
- this.outgoingBytes
- .set(this.incomingBytes.subarray(this.incomingReadIndex,
- newIncomingReadIndex),
- this.outgoingIndex);
- } else {
- // Not so lucky.
- newIncomingReadIndex %= this.incomingBufferLength;
- this.outgoingBytes
- .set(this.incomingBytes.subarray(this.incomingReadIndex,
- this.incomingBufferLength),
- this.outgoingIndex);
- if (newIncomingReadIndex) {
- let firstPartLength = this.incomingBufferLength - this.incomingReadIndex;
- this.outgoingBytes.set(this.incomingBytes.subarray(0, newIncomingReadIndex),
- this.outgoingIndex + firstPartLength);
- }
- }
-
- this.incomingReadIndex = newIncomingReadIndex;
- this.readAvailable -= length;
- this.outgoingIndex += length;
- },
-
- /**
- * Parcel management
- */
-
- /**
- * Write incoming data to the circular buffer.
- *
- * @param incoming
- * Uint8Array containing the incoming data.
- */
- writeToIncoming: function(incoming) {
- // We don't have to worry about the head catching the tail since
- // we process any backlog in parcels immediately, before writing
- // new data to the buffer. So the only edge case we need to handle
- // is when the incoming data is larger than the buffer size.
- let minMustAvailableSize = incoming.length + this.readIncoming;
- if (minMustAvailableSize > this.incomingBufferLength) {
- this.growIncomingBuffer(minMustAvailableSize);
- }
-
- // We can let the typed arrays do the copying if the incoming data won't
- // wrap around the edges of the circular buffer.
- let remaining = this.incomingBufferLength - this.incomingWriteIndex;
- if (remaining >= incoming.length) {
- this.incomingBytes.set(incoming, this.incomingWriteIndex);
- } else {
- // The incoming data would wrap around it.
- let head = incoming.subarray(0, remaining);
- let tail = incoming.subarray(remaining);
- this.incomingBytes.set(head, this.incomingWriteIndex);
- this.incomingBytes.set(tail, 0);
- }
- this.incomingWriteIndex = (this.incomingWriteIndex + incoming.length) %
- this.incomingBufferLength;
- },
-
- /**
- * Process incoming data.
- *
- * @param incoming
- * Uint8Array containing the incoming data.
- */
- processIncoming: function(incoming) {
- if (DEBUG) {
- debug("Received " + incoming.length + " bytes.");
- debug("Already read " + this.readIncoming);
- }
-
- this.writeToIncoming(incoming);
- this.readIncoming += incoming.length;
- while (true) {
- if (!this.currentParcelSize) {
- // We're expecting a new parcel.
- if (this.readIncoming < this.PARCEL_SIZE_SIZE) {
- // We don't know how big the next parcel is going to be, need more
- // data.
- if (DEBUG) debug("Next parcel size unknown, going to sleep.");
- return;
- }
- this.currentParcelSize = this.readParcelSize();
- if (DEBUG) {
- debug("New incoming parcel of size " + this.currentParcelSize);
- }
- // The size itself is not included in the size.
- this.readIncoming -= this.PARCEL_SIZE_SIZE;
- }
-
- if (this.readIncoming < this.currentParcelSize) {
- // We haven't read enough yet in order to be able to process a parcel.
- if (DEBUG) debug("Read " + this.readIncoming + ", but parcel size is "
- + this.currentParcelSize + ". Going to sleep.");
- return;
- }
-
- // Alright, we have enough data to process at least one whole parcel.
- // Let's do that.
- let expectedAfterIndex = (this.incomingReadIndex + this.currentParcelSize)
- % this.incomingBufferLength;
-
- if (DEBUG) {
- let parcel;
- if (expectedAfterIndex < this.incomingReadIndex) {
- let head = this.incomingBytes.subarray(this.incomingReadIndex);
- let tail = this.incomingBytes.subarray(0, expectedAfterIndex);
- parcel = Array.slice(head).concat(Array.slice(tail));
- } else {
- parcel = Array.slice(this.incomingBytes.subarray(
- this.incomingReadIndex, expectedAfterIndex));
- }
- debug("Parcel (size " + this.currentParcelSize + "): " + parcel);
- }
-
- if (DEBUG) debug("We have at least one complete parcel.");
- try {
- this.readAvailable = this.currentParcelSize;
- this.processParcel();
- } catch (ex) {
- if (DEBUG) debug("Parcel handling threw " + ex + "\n" + ex.stack);
- }
-
- // Ensure that the whole parcel was consumed.
- if (this.incomingReadIndex != expectedAfterIndex) {
- if (DEBUG) {
- debug("Parcel handler didn't consume whole parcel, " +
- Math.abs(expectedAfterIndex - this.incomingReadIndex) +
- " bytes left over");
- }
- this.incomingReadIndex = expectedAfterIndex;
- }
- this.readIncoming -= this.currentParcelSize;
- this.readAvailable = 0;
- this.currentParcelSize = 0;
- }
- },
-
- /**
- * Communicate with the IPC thread.
- */
- sendParcel: function() {
- // Compute the size of the parcel and write it to the front of the parcel
- // where we left room for it. Note that he parcel size does not include
- // the size itself.
- let parcelSize = this.outgoingIndex - this.PARCEL_SIZE_SIZE;
- this.writeParcelSize(parcelSize);
-
- // This assumes that postRILMessage will make a copy of the ArrayBufferView
- // right away!
- let parcel = this.outgoingBytes.subarray(0, this.outgoingIndex);
- if (DEBUG) debug("Outgoing parcel: " + Array.slice(parcel));
- this.onSendParcel(parcel);
- this.outgoingIndex = this.PARCEL_SIZE_SIZE;
- },
-
- getCurrentParcelSize: function() {
- return this.currentParcelSize;
- },
-
- getReadAvailable: function() {
- return this.readAvailable;
- }
-
- /**
- * Process one parcel.
- *
- * |processParcel| is an implementation provided incoming parcel processing
- * function invoked when we have received a complete parcel. Implementation
- * may call multiple read functions to extract data from the incoming buffer.
- */
- //processParcel: function() {
- // let something = this.readInt32();
- // ...
- //},
-
- /**
- * Write raw data out to underlying channel.
- *
- * |onSendParcel| is an implementation provided stream output function
- * invoked when we're really going to write something out. We assume the
- * data are completely copied to some output buffer in this call and may
- * be destroyed when it's done.
- *
- * @param parcel
- * An array of numeric octet data.
- */
- //onSendParcel: function(parcel) {
- // ...
- //}
-};
-
-module.exports = { Buf: Buf };
diff --git a/dom/system/moz.build b/dom/system/moz.build
index 3cff531b5..fc8cf533b 100644
--- a/dom/system/moz.build
+++ b/dom/system/moz.build
@@ -12,8 +12,6 @@ elif toolkit == 'cocoa':
DIRS += ['mac']
elif toolkit == 'android':
DIRS += ['android']
-elif toolkit == 'gonk':
- DIRS += ['gonk']
elif toolkit in ('gtk2', 'gtk3'):
DIRS += ['linux']
diff --git a/dom/tests/mochitest/bugs/test_resize_move_windows.html b/dom/tests/mochitest/bugs/test_resize_move_windows.html
index 0762e9231..f84b4fde8 100644
--- a/dom/tests/mochitest/bugs/test_resize_move_windows.html
+++ b/dom/tests/mochitest/bugs/test_resize_move_windows.html
@@ -312,7 +312,10 @@ function checkChangeIsEnabled(aWindow, aNext)
.then(aNext);
}
-SpecialPowers.pushPrefEnv({"set": [["dom.disable_window_move_resize", false]]}, function() {
+SpecialPowers.pushPrefEnv({
+ "set": [["dom.disable_window_move_resize", false],
+ ["security.data_uri.block_toplevel_data_uri_navigations", false],]},
+ function() {
SimpleTest.waitForFocus(function() {
if (screen.width <= 200 || screen.height <= 200) {
todo(false, "The screen needs to be bigger than 200px*200px to run this test.");
diff --git a/dom/tests/mochitest/general/test_interfaces.html b/dom/tests/mochitest/general/test_interfaces.html
index acbc12e07..98f3ffed0 100644
--- a/dom/tests/mochitest/general/test_interfaces.html
+++ b/dom/tests/mochitest/general/test_interfaces.html
@@ -63,7 +63,7 @@ var ecmaGlobals =
"Int32Array",
"Int8Array",
"InternalError",
- {name: "Intl", android: false},
+ "Intl",
"Iterator",
"JSON",
"Map",
@@ -751,9 +751,11 @@ var interfaceNamesInGlobalScope =
// IMPORTANT: Do not change this list without review from a DOM peer!
"PerformanceNavigation",
// IMPORTANT: Do not change this list without review from a DOM peer!
- {name: "PerformanceObserver", nightly: true},
+ "PerformanceNavigationTiming",
// IMPORTANT: Do not change this list without review from a DOM peer!
- {name: "PerformanceObserverEntryList", nightly: true},
+ "PerformanceObserver"
+// IMPORTANT: Do not change this list without review from a DOM peer!
+ "PerformanceObserverEntryList"
// IMPORTANT: Do not change this list without review from a DOM peer!
"PerformanceResourceTiming",
// IMPORTANT: Do not change this list without review from a DOM peer!
diff --git a/dom/tethering/TetheringManager.js b/dom/tethering/TetheringManager.js
deleted file mode 100644
index 1e3d3a0ea..000000000
--- a/dom/tethering/TetheringManager.js
+++ /dev/null
@@ -1,92 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
-
-XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
- "@mozilla.org/childprocessmessagemanager;1",
- "nsIMessageSender");
-
-const DEBUG = false;
-
-const TETHERING_TYPE_WIFI = "wifi";
-const TETHERING_TYPE_BLUETOOTH = "bt";
-const TETHERING_TYPE_USB = "usb";
-
-function TetheringManager() {
-}
-
-TetheringManager.prototype = {
- __proto__: DOMRequestIpcHelper.prototype,
-
- classDescription: "TetheringManager",
- classID: Components.ID("{bd8a831c-d8ec-4f00-8803-606e50781097}"),
- contractID: "@mozilla.org/dom/tetheringmanager;1",
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMGlobalPropertyInitializer,
- Ci.nsISupportsWeakReference,
- Ci.nsIObserver]),
-
- init: function(aWindow) {
- const messages = ["WifiManager:setWifiTethering:Return:OK",
- "WifiManager:setWifiTethering:Return:NO"];
- this.initDOMRequestHelper(aWindow, messages);
- },
-
- // TODO : aMessage format may be different after supporting bt/usb.
- // for now, use wifi format first.
- receiveMessage: function(aMessage) {
- let data = aMessage.data.data;
-
- let resolver = this.takePromiseResolver(data.resolverId);
- if (!resolver) {
- return;
- }
-
- switch (aMessage.name) {
- case "WifiManager:setWifiTethering:Return:OK":
- resolver.resolve(data);
- break;
- case "WifiManager:setWifiTethering:Return:NO":
- resolver.reject(data.reason);
- break;
- }
- },
-
- setTetheringEnabled: function setTetheringEnabled(aEnabled, aType, aConfig) {
- let self = this;
- switch (aType) {
- case TETHERING_TYPE_WIFI:
- return this.createPromiseWithId(function(aResolverId) {
- let data = { resolverId: aResolverId, enabled: aEnabled, config: aConfig };
- cpmm.sendAsyncMessage("WifiManager:setWifiTethering", { data: data});
- });
- case TETHERING_TYPE_BLUETOOTH:
- case TETHERING_TYPE_USB:
- default:
- debug("tethering type(" + aType + ") doesn't support");
- return this.createPromiseWithId(function(aResolverId) {
- self.takePromiseResolver(aResolverId).reject();
- });
- }
- },
-};
-
-this.NSGetFactory =
- XPCOMUtils.generateNSGetFactory([TetheringManager]);
-
-var debug;
-if (DEBUG) {
- debug = function (s) {
- dump("-*- TetheringManager component: " + s + "\n");
- };
-} else {
- debug = function (s) {};
-}
diff --git a/dom/tethering/TetheringManager.manifest b/dom/tethering/TetheringManager.manifest
deleted file mode 100644
index 6ef01c69d..000000000
--- a/dom/tethering/TetheringManager.manifest
+++ /dev/null
@@ -1,4 +0,0 @@
-#TetheringManager.js
-component {bd8a831c-d8ec-4f00-8803-606e50781097} TetheringManager.js
-contract @mozilla.org/tetheringmanager;1 {bd8a831c-d8ec-4f00-8803-606e50781097}
-
diff --git a/dom/tethering/moz.build b/dom/tethering/moz.build
deleted file mode 100644
index 4f68aca2d..000000000
--- a/dom/tethering/moz.build
+++ /dev/null
@@ -1,12 +0,0 @@
-# -*- 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/.
-
-EXTRA_COMPONENTS += [
- 'TetheringManager.js',
- 'TetheringManager.manifest',
-]
-
-FINAL_LIBRARY = 'xul'
diff --git a/dom/tethering/tests/marionette/head.js b/dom/tethering/tests/marionette/head.js
deleted file mode 100644
index c6b6abe26..000000000
--- a/dom/tethering/tests/marionette/head.js
+++ /dev/null
@@ -1,768 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-const TYPE_WIFI = "wifi";
-const TYPE_BLUETOOTH = "bt";
-const TYPE_USB = "usb";
-
-/**
- * General tethering setting.
- */
-const TETHERING_SETTING_IP = "192.168.1.1";
-const TETHERING_SETTNG_PREFIX = "24";
-const TETHERING_SETTING_START_IP = "192.168.1.10";
-const TETHERING_SETTING_END_IP = "192.168.1.30";
-const TETHERING_SETTING_DNS1 = "8.8.8.8";
-const TETHERING_SETTING_DNS2 = "8.8.4.4";
-
-const TETHERING_NETWORK_ADDR = "192.168.1.0/24";
-
-/**
- * Wifi tethering setting.
- */
-const TETHERING_SETTING_SSID = "FirefoxHotSpot";
-const TETHERING_SETTING_SECURITY = "open";
-const TETHERING_SETTING_KEY = "1234567890";
-
-const SETTINGS_RIL_DATA_ENABLED = 'ril.data.enabled';
-const SETTINGS_KEY_DATA_APN_SETTINGS = "ril.data.apnSettings";
-
-// Emulate Promise.jsm semantics.
-Promise.defer = function() { return new Deferred(); }
-function Deferred() {
- this.promise = new Promise(function(resolve, reject) {
- this.resolve = resolve;
- this.reject = reject;
- }.bind(this));
- Object.freeze(this);
-}
-
-var gTestSuite = (function() {
- let suite = {};
-
- let tetheringManager;
- let pendingEmulatorShellCount = 0;
-
- /**
- * A wrapper function of "is".
- *
- * Calls the marionette function "is" as well as throws an exception
- * if the givens values are not equal.
- *
- * @param value1
- * Any type of value to compare.
- *
- * @param value2
- * Any type of value to compare.
- *
- * @param message
- * Debug message for this check.
- *
- */
- function isOrThrow(value1, value2, message) {
- is(value1, value2, message);
- if (value1 !== value2) {
- throw message;
- }
- }
-
- /**
- * Send emulator shell command with safe guard.
- *
- * We should only call |finish()| after all emulator command transactions
- * end, so here comes with the pending counter. Resolve when the emulator
- * gives positive response, and reject otherwise.
- *
- * Fulfill params:
- * result -- an array of emulator response lines.
- * Reject params:
- * result -- an array of emulator response lines.
- *
- * @param aCommand
- * A string command to be passed to emulator through its telnet console.
- *
- * @return A deferred promise.
- */
- function runEmulatorShellSafe(aCommand) {
- let deferred = Promise.defer();
-
- ++pendingEmulatorShellCount;
- runEmulatorShell(aCommand, function(aResult) {
- --pendingEmulatorShellCount;
-
- ok(true, "Emulator shell response: " + JSON.stringify(aResult));
- if (Array.isArray(aResult)) {
- deferred.resolve(aResult);
- } else {
- deferred.reject(aResult);
- }
- });
-
- return deferred.promise;
- }
-
- /**
- * Wait for timeout.
- *
- * Resolve when the given duration elapsed. Never reject.
- *
- * Fulfill params: (none)
- *
- * @param aTimeoutMs
- * The duration after which the timeout event should occurs.
- *
- * @return A deferred promise.
- */
- function waitForTimeout(aTimeoutMs) {
- let deferred = Promise.defer();
-
- setTimeout(function() {
- deferred.resolve();
- }, aTimeoutMs);
-
- return deferred.promise;
- }
-
- /**
- * Get mozSettings value specified by @aKey.
- *
- * Resolve if that mozSettings value is retrieved successfully, reject
- * otherwise.
- *
- * Fulfill params:
- * The corresponding mozSettings value of the key.
- * Reject params: (none)
- *
- * @param aKey
- * A string.
- *
- * @return A deferred promise.
- */
- function getSettings(aKey) {
- let request = navigator.mozSettings.createLock().get(aKey);
-
- return wrapDomRequestAsPromise(request)
- .then(function resolve(aEvent) {
- ok(true, "getSettings(" + aKey + ") - success");
- return aEvent.target.result[aKey];
- }, function reject(aEvent) {
- ok(false, "getSettings(" + aKey + ") - error");
- throw aEvent.target.error;
- });
- }
-
- /**
- * Set mozSettings values.
- *
- * Resolve if that mozSettings value is set successfully, reject otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aSettings
- * An object of format |{key1: value1, key2: value2, ...}|.
- * @return A deferred promise.
- */
- function setSettings(aSettings) {
- let lock = window.navigator.mozSettings.createLock();
- let request = lock.set(aSettings);
- let deferred = Promise.defer();
- lock.onsettingstransactionsuccess = function () {
- ok(true, "setSettings(" + JSON.stringify(aSettings) + ")");
- deferred.resolve();
- };
- lock.onsettingstransactionfailure = function (aEvent) {
- ok(false, "setSettings(" + JSON.stringify(aSettings) + ")");
- deferred.reject();
- throw aEvent.target.error;
- };
- return deferred.promise;
- }
-
- /**
- * Set mozSettings value with only one key.
- *
- * Resolve if that mozSettings value is set successfully, reject otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aKey
- * A string key.
- * @param aValue
- * An object value.
- * @param aAllowError [optional]
- * A boolean value. If set to true, an error response won't be treated
- * as test failure. Default: false.
- *
- * @return A deferred promise.
- */
- function setSettings1(aKey, aValue, aAllowError) {
- let settings = {};
- settings[aKey] = aValue;
- return setSettings(settings, aAllowError);
- }
-
- /**
- * Convenient MozSettings getter for SETTINGS_KEY_DATA_APN_SETTINGS.
- */
- function getDataApnSettings(aAllowError) {
- return getSettings(SETTINGS_KEY_DATA_APN_SETTINGS, aAllowError);
- }
-
- /**
- * Convenient MozSettings setter for SETTINGS_KEY_DATA_APN_SETTINGS.
- */
- function setDataApnSettings(aApnSettings, aAllowError) {
- return setSettings1(SETTINGS_KEY_DATA_APN_SETTINGS, aApnSettings, aAllowError);
- }
-
- /**
- * Set 'ro.tethering.dun_required' system property to 1. Note that this is a
- * 'ro' property, it can only be set once.
- */
- function setTetheringDunRequired() {
- return runEmulatorShellSafe(['setprop', 'ro.tethering.dun_required', '1']);
- }
-
- /**
- * Wrap DOMRequest onsuccess/onerror events to Promise resolve/reject.
- *
- * Fulfill params: A DOMEvent.
- * Reject params: A DOMEvent.
- *
- * @param aRequest
- * A DOMRequest instance.
- *
- * @return A deferred promise.
- */
- function wrapDomRequestAsPromise(aRequest) {
- let deffered = Promise.defer();
-
- ok(aRequest instanceof DOMRequest,
- "aRequest is instanceof" + aRequest.constructor);
-
- aRequest.onsuccess = function(aEvent) {
- deffered.resolve(aEvent);
- };
- aRequest.onerror = function(aEvent) {
- deffered.reject(aEvent);
- };
-
- return deffered.promise;
- }
-
- /**
- * Wait for one named MozMobileConnection event.
- *
- * Resolve if that named event occurs. Never reject.
- *
- * Fulfill params: the DOMEvent passed.
- *
- * @param aEventName
- * A string event name.
- *
- * @return A deferred promise.
- */
- function waitForMobileConnectionEventOnce(aEventName, aServiceId) {
- aServiceId = aServiceId || 0;
-
- let deferred = Promise.defer();
- let mobileconnection = navigator.mozMobileConnections[aServiceId];
-
- mobileconnection.addEventListener(aEventName, function onevent(aEvent) {
- mobileconnection.removeEventListener(aEventName, onevent);
-
- ok(true, "Mobile connection event '" + aEventName + "' got.");
- deferred.resolve(aEvent);
- });
-
- return deferred.promise;
- }
-
- /**
- * Wait for RIL data being connected.
- *
- * This function will check |MozMobileConnection.data.connected| on
- * every 'datachange' event. Resolve when |MozMobileConnection.data.connected|
- * becomes the expected state. Never reject.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aConnected
- * Boolean that indicates the desired data state.
- *
- * @param aServiceId [optional]
- * A numeric DSDS service id. Default: 0.
- *
- * @return A deferred promise.
- */
- function waitForRilDataConnected(aConnected, aServiceId) {
- aServiceId = aServiceId || 0;
-
- return waitForMobileConnectionEventOnce('datachange', aServiceId)
- .then(function () {
- let mobileconnection = navigator.mozMobileConnections[aServiceId];
- if (mobileconnection.data.connected !== aConnected) {
- return waitForRilDataConnected(aConnected, aServiceId);
- }
- });
- }
-
- /**
- * Verify everything about routing when the wifi tethering is either on or off.
- *
- * We use two unix commands to verify the routing: 'netcfg' and 'ip route'.
- * For now the following two things will be checked:
- * 1) The default route interface should be 'rmnet0'.
- * 2) wlan0 is up and its ip is set to a private subnet.
- *
- * We also verify iptables output as netd's NatController will execute
- * $ iptables -t nat -A POSTROUTING -o rmnet0 -j MASQUERADE
- *
- * For tethering through dun, we use 'ip rule' to find the secondary routing
- * table and look for default route on that table.
- *
- * Resolve when the verification is successful and reject otherwise.
- *
- * Fulfill params: (none)
- * Reject params: String that indicates the reason of rejection.
- *
- * @return A deferred promise.
- */
- function verifyTetheringRouting(aEnabled, aIsDun) {
- let netcfgResult = {};
- let ipRouteResult = {};
- let ipSecondaryRouteResult = {};
-
- // Execute 'netcfg' and parse to |netcfgResult|, each key of which is the
- // interface name and value is { ip(string) }.
- function exeAndParseNetcfg() {
- return runEmulatorShellSafe(['netcfg'])
- .then(function (aLines) {
- // Sample output:
- //
- // lo UP 127.0.0.1/8 0x00000049 00:00:00:00:00:00
- // eth0 UP 10.0.2.15/24 0x00001043 52:54:00:12:34:56
- // rmnet1 DOWN 0.0.0.0/0 0x00001002 52:54:00:12:34:58
- // rmnet2 DOWN 0.0.0.0/0 0x00001002 52:54:00:12:34:59
- // rmnet3 DOWN 0.0.0.0/0 0x00001002 52:54:00:12:34:5a
- // wlan0 UP 192.168.1.1/24 0x00001043 52:54:00:12:34:5b
- // sit0 DOWN 0.0.0.0/0 0x00000080 00:00:00:00:00:00
- // rmnet0 UP 10.0.2.100/24 0x00001043 52:54:00:12:34:57
- //
- aLines.forEach(function (aLine) {
- let tokens = aLine.split(/\s+/);
- if (tokens.length < 5) {
- return;
- }
- let ifname = tokens[0];
- let ip = (tokens[2].split('/'))[0];
- netcfgResult[ifname] = { ip: ip };
- });
- });
- }
-
- // Execute 'ip route' and parse to |ipRouteResult|, each key of which is the
- // interface name and value is { src(string), default(boolean) }.
- function exeAndParseIpRoute() {
- return runEmulatorShellSafe(['ip', 'route'])
- .then(function (aLines) {
- // Sample output:
- //
- // 10.0.2.4 via 10.0.2.2 dev rmnet0
- // 10.0.2.3 via 10.0.2.2 dev rmnet0
- // 192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.1
- // 10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15
- // 10.0.2.0/24 dev rmnet0 proto kernel scope link src 10.0.2.100
- // default via 10.0.2.2 dev rmnet0
- // default via 10.0.2.2 dev eth0 metric 2
- //
-
- // Parse source ip for each interface.
- aLines.forEach(function (aLine) {
- let tokens = aLine.trim().split(/\s+/);
- let srcIndex = tokens.indexOf('src');
- if (srcIndex < 0 || srcIndex + 1 >= tokens.length) {
- return;
- }
- let ifname = tokens[2];
- let src = tokens[srcIndex + 1];
- ipRouteResult[ifname] = { src: src, default: false };
- });
-
- // Parse default interfaces.
- aLines.forEach(function (aLine) {
- let tokens = aLine.split(/\s+/);
- if (tokens.length < 2) {
- return;
- }
- if ('default' === tokens[0]) {
- let ifnameIndex = tokens.indexOf('dev');
- if (ifnameIndex < 0 || ifnameIndex + 1 >= tokens.length) {
- return;
- }
- let ifname = tokens[ifnameIndex + 1];
- if (ipRouteResult[ifname]) {
- ipRouteResult[ifname].default = true;
- }
- return;
- }
- });
-
- });
-
- }
-
- // Find MASQUERADE in POSTROUTING section. 'MASQUERADE' should be found
- // when tethering is enabled. 'MASQUERADE' shouldn't be found when tethering
- // is disabled.
- function verifyIptables() {
- return runEmulatorShellSafe(['iptables', '-t', 'nat', '-L', 'POSTROUTING'])
- .then(function(aLines) {
- // $ iptables -t nat -L POSTROUTING
- //
- // Sample output (tethering on):
- //
- // Chain POSTROUTING (policy ACCEPT)
- // target prot opt source destination
- // MASQUERADE all -- anywhere anywhere
- //
- let found = (function find_MASQUERADE() {
- // Skip first two lines.
- for (let i = 2; i < aLines.length; i++) {
- if (-1 !== aLines[i].indexOf('MASQUERADE')) {
- return true;
- }
- }
- return false;
- })();
-
- if ((aEnabled && !found) || (!aEnabled && found)) {
- throw 'MASQUERADE' + (found ? '' : ' not') + ' found while tethering is ' +
- (aEnabled ? 'enabled' : 'disabled');
- }
- });
- }
-
- // Execute 'ip rule show', there must be one rule for tethering network
- // address to lookup for a secondary routing table, return that table id.
- function verifyIpRule() {
- if (!aIsDun) {
- return;
- }
-
- return runEmulatorShellSafe(['ip', 'rule', 'show'])
- .then(function (aLines) {
- // Sample output:
- //
- // 0: from all lookup local
- // 32765: from 192.168.1.0/24 lookup 60
- // 32766: from all lookup main
- // 32767: from all lookup default
- //
- let tableId = (function findTableId() {
- for (let i = 0; i < aLines.length; i++) {
- let tokens = aLines[i].split(/\s+/);
- if (-1 != tokens.indexOf(TETHERING_NETWORK_ADDR)) {
- let lookupIndex = tokens.indexOf('lookup');
- if (lookupIndex < 0 || lookupIndex + 1 >= tokens.length) {
- return;
- }
- return tokens[lookupIndex + 1];
- }
- }
- return;
- })();
-
- if ((aEnabled && !tableId) || (!aEnabled && tableId)) {
- throw 'Secondary table' + (tableId ? '' : ' not') + ' found while tethering is ' +
- (aEnabled ? 'enabled' : 'disabled');
- }
-
- return tableId;
- });
- }
-
- // Given the table id, use 'ip rule show table <table id>' to find the
- // default route on that secondary routing table.
- function execAndParseSecondaryTable(aTableId) {
- if (!aIsDun || !aEnabled) {
- return;
- }
-
- return runEmulatorShellSafe(['ip', 'route', 'show', 'table', aTableId])
- .then(function (aLines) {
- // We only look for default route in secondary table.
- aLines.forEach(function (aLine) {
- let tokens = aLine.split(/\s+/);
- if (tokens.length < 2) {
- return;
- }
- if ('default' === tokens[0]) {
- let ifnameIndex = tokens.indexOf('dev');
- if (ifnameIndex < 0 || ifnameIndex + 1 >= tokens.length) {
- return;
- }
- let ifname = tokens[ifnameIndex + 1];
- ipSecondaryRouteResult[ifname] = { default: true };
- return;
- }
- });
- });
- }
-
- function verifyDefaultRouteAndIp(aExpectedWifiTetheringIp) {
- log(JSON.stringify(ipRouteResult));
- log(JSON.stringify(ipSecondaryRouteResult));
- log(JSON.stringify(netcfgResult));
-
- if (aEnabled) {
- isOrThrow(ipRouteResult['rmnet0'].src, netcfgResult['rmnet0'].ip, 'rmnet0.ip');
- isOrThrow(ipRouteResult['rmnet0'].default, true, 'rmnet0.default');
-
- isOrThrow(ipRouteResult['wlan0'].src, netcfgResult['wlan0'].ip, 'wlan0.ip');
- isOrThrow(ipRouteResult['wlan0'].src, aExpectedWifiTetheringIp, 'expected ip');
- isOrThrow(ipRouteResult['wlan0'].default, false, 'wlan0.default');
-
- if (aIsDun) {
- isOrThrow(ipRouteResult['rmnet1'].src, netcfgResult['rmnet1'].ip, 'rmnet1.ip');
- isOrThrow(ipRouteResult['rmnet1'].default, false, 'rmnet1.default');
- // Dun's network default route is set on secondary routing table.
- isOrThrow(ipSecondaryRouteResult['rmnet1'].default, true, 'secondary rmnet1.default');
- }
- }
- }
-
- return verifyIptables()
- .then(verifyIpRule)
- .then(tableId => execAndParseSecondaryTable(tableId))
- .then(exeAndParseNetcfg)
- .then(exeAndParseIpRoute)
- .then(() => verifyDefaultRouteAndIp(TETHERING_SETTING_IP));
- }
-
- /**
- * Request to enable/disable wifi tethering.
- *
- * Enable/disable wifi tethering by using setTetheringEnabled API
- * Resolve when the routing is verified to set up successfully in 20 seconds. The polling
- * period is 1 second.
- *
- * Fulfill params: (none)
- * Reject params: The error message.
- *
- * @param aEnabled
- * Boolean that indicates to enable or disable wifi tethering.
- * @param aIsDun
- * Boolean that indicates whether dun is required.
- *
- * @return A deferred promise.
- */
- function setWifiTetheringEnabled(aEnabled, aIsDun) {
- let RETRY_INTERVAL_MS = 1000;
- let retryCnt = 20;
-
- let config = {
- "ip" : TETHERING_SETTING_IP,
- "prefix" : TETHERING_SETTNG_PREFIX,
- "startIp" : TETHERING_SETTING_START_IP,
- "endIp" : TETHERING_SETTING_END_IP,
- "dns1" : TETHERING_SETTING_DNS1,
- "dns2" : TETHERING_SETTING_DNS2,
- "wifiConfig": {
- "ssid" : TETHERING_SETTING_SSID,
- "security" : TETHERING_SETTING_SECURITY
- }
- };
-
- return tetheringManager.setTetheringEnabled(aEnabled, TYPE_WIFI, config)
- .then(function waitForRoutingVerified() {
- return verifyTetheringRouting(aEnabled, aIsDun)
- .then(null, function onreject(aReason) {
-
- log('verifyTetheringRouting rejected due to ' + aReason +
- ' (' + retryCnt + ')');
-
- if (!retryCnt--) {
- throw aReason;
- }
-
- return waitForTimeout(RETRY_INTERVAL_MS).then(waitForRoutingVerified);
- });
- });
- }
-
- /**
- * Ensure wifi is enabled/disabled.
- *
- * Issue a wifi enable/disable request if wifi is not in the desired state;
- * return a resolved promise otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return a resolved promise or deferred promise.
- */
- function ensureWifiEnabled(aEnabled) {
- let wifiManager = window.navigator.mozWifiManager;
- if (wifiManager.enabled === aEnabled) {
- return Promise.resolve();
- }
- let request = wifiManager.setWifiEnabled(aEnabled);
- return wrapDomRequestAsPromise(request)
- }
-
- /**
- * Ensure tethering manager exists.
- *
- * Check navigator property |mozTetheringManager| to ensure we could access
- * tethering related function.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function ensureTetheringManager() {
- let deferred = Promise.defer();
-
- tetheringManager = window.navigator.mozTetheringManager;
-
- if (tetheringManager instanceof MozTetheringManager) {
- deferred.resolve();
- } else {
- log("navigator.mozTetheringManager is unavailable");
- deferred.reject();
- }
-
- return deferred.promise;
- }
-
- /**
- * Add required permissions for tethering. Never reject.
- *
- * The permissions required for wifi testing are 'wifi-manage' and 'settings-write'.
- * Never reject.
- *
- * Fulfill params: (none)
- *
- * @return A deferred promise.
- */
- function acquirePermission() {
- let deferred = Promise.defer();
-
- let permissions = [{ 'type': 'wifi-manage', 'allow': 1, 'context': window.document },
- { 'type': 'settings-write', 'allow': 1, 'context': window.document },
- { 'type': 'settings-read', 'allow': 1, 'context': window.document },
- { 'type': 'settings-api-write', 'allow': 1, 'context': window.document },
- { 'type': 'settings-api-read', 'allow': 1, 'context': window.document },
- { 'type': 'mobileconnection', 'allow': 1, 'context': window.document }];
-
- SpecialPowers.pushPermissions(permissions, function() {
- deferred.resolve();
- });
-
- return deferred.promise;
- }
-
- /**
- * Common test routine.
- *
- * Start a test with the given test case chain. The test environment will be
- * settled down before the test. After the test, all the affected things will
- * be restored.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aTestCaseChain
- * The test case entry point, which can be a function or a promise.
- *
- * @return A deferred promise.
- */
- suite.startTest = function(aTestCaseChain) {
- function setUp() {
- return ensureTetheringManager()
- .then(acquirePermission);
- }
-
- function tearDown() {
- waitFor(finish, function() {
- return pendingEmulatorShellCount === 0;
- });
- }
-
- return setUp()
- .then(aTestCaseChain)
- .then(function onresolve() {
- tearDown();
- }, function onreject(aReason) {
- ok(false, 'Promise rejects during test' + (aReason ? '(' + aReason + ')' : ''));
- tearDown();
- });
- };
-
- //---------------------------------------------------
- // Public test suite functions
- //---------------------------------------------------
- suite.ensureWifiEnabled = ensureWifiEnabled;
- suite.setWifiTetheringEnabled = setWifiTetheringEnabled;
- suite.getDataApnSettings = getDataApnSettings;
- suite.setDataApnSettings = setDataApnSettings;
- suite.setTetheringDunRequired = setTetheringDunRequired;
-
-
- /**
- * The common test routine for wifi tethering.
- *
- * Set 'ril.data.enabled' to true
- * before testing and restore it afterward. It will also verify 'ril.data.enabled'
- * and 'tethering.wifi.enabled' to be false in the beginning. Note that this routine
- * will NOT change the state of 'tethering.wifi.enabled' so the user should enable
- * than disable on his/her own. This routine will only check if tethering is turned
- * off after testing.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aTestCaseChain
- * The test case entry point, which can be a function or a promise.
- *
- * @return A deferred promise.
- */
- suite.startTetheringTest = function(aTestCaseChain) {
- let oriDataEnabled;
- function verifyInitialState() {
- return getSettings(SETTINGS_RIL_DATA_ENABLED)
- .then(enabled => initTetheringTestEnvironment(enabled));
- }
-
- function initTetheringTestEnvironment(aEnabled) {
- oriDataEnabled = aEnabled;
- if (aEnabled) {
- return Promise.resolve();
- } else {
- return Promise.all([waitForRilDataConnected(true),
- setSettings1(SETTINGS_RIL_DATA_ENABLED, true)]);
- }
- }
-
- function restoreToInitialState() {
- return setSettings1(SETTINGS_RIL_DATA_ENABLED, oriDataEnabled);
- }
-
- return suite.startTest(function() {
- return verifyInitialState()
- .then(aTestCaseChain)
- .then(restoreToInitialState, function onreject(aReason) {
- return restoreToInitialState()
- .then(() => { throw aReason; }); // Re-throw the orignal reject reason.
- });
- });
- };
-
- return suite;
-})();
diff --git a/dom/tethering/tests/marionette/manifest.ini b/dom/tethering/tests/marionette/manifest.ini
deleted file mode 100644
index 89065724f..000000000
--- a/dom/tethering/tests/marionette/manifest.ini
+++ /dev/null
@@ -1,7 +0,0 @@
-[DEFAULT]
-run-if = buildapp == 'b2g'
-
-[test_wifi_tethering_enabled.js]
-; The following test must be the last tethering test ran, as it sets the
-; 'ro.tethering.dun_required' property.
-[test_wifi_tethering_dun.js]
diff --git a/dom/tethering/tests/marionette/test_wifi_tethering_dun.js b/dom/tethering/tests/marionette/test_wifi_tethering_dun.js
deleted file mode 100644
index 3d93cf8d3..000000000
--- a/dom/tethering/tests/marionette/test_wifi_tethering_dun.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-gTestSuite.startTest(function() {
- let origApnSettings;
- return gTestSuite.getDataApnSettings()
- .then(value => {
- origApnSettings = value;
- })
- .then(() => {
- // Set dun apn settings.
- let apnSettings = [[ { "carrier": "T-Mobile US",
- "apn": "epc1.tmobile.com",
- "mmsc": "http://mms.msg.eng.t-mobile.com/mms/wapenc",
- "types": ["default","supl","mms"] },
- { "carrier": "T-Mobile US",
- "apn": "epc2.tmobile.com",
- "types": ["dun"] } ]];
- return gTestSuite.setDataApnSettings(apnSettings);
- })
- .then(() => gTestSuite.setTetheringDunRequired())
- .then(() => gTestSuite.startTetheringTest(function() {
- return gTestSuite.ensureWifiEnabled(false)
- .then(() => gTestSuite.setWifiTetheringEnabled(true, true))
- .then(() => gTestSuite.setWifiTetheringEnabled(false, true));
- }))
- // Restore apn settings.
- .then(() => {
- if (origApnSettings) {
- return gTestSuite.setDataApnSettings(origApnSettings);
- }
- });
-}); \ No newline at end of file
diff --git a/dom/tethering/tests/marionette/test_wifi_tethering_enabled.js b/dom/tethering/tests/marionette/test_wifi_tethering_enabled.js
deleted file mode 100644
index 936219ec5..000000000
--- a/dom/tethering/tests/marionette/test_wifi_tethering_enabled.js
+++ /dev/null
@@ -1,12 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-gTestSuite.startTetheringTest(function() {
- return gTestSuite.ensureWifiEnabled(false)
- .then(() => gTestSuite.setWifiTetheringEnabled(true))
- .then(() => gTestSuite.setWifiTetheringEnabled(false));
-});
diff --git a/dom/webidl/EventHandler.webidl b/dom/webidl/EventHandler.webidl
index e65a75787..1edc45ac9 100644
--- a/dom/webidl/EventHandler.webidl
+++ b/dom/webidl/EventHandler.webidl
@@ -33,6 +33,7 @@ interface GlobalEventHandlers {
// attribute OnErrorEventHandler onerror;
attribute EventHandler onfocus;
//(Not implemented)attribute EventHandler oncancel;
+ attribute EventHandler onauxclick;
attribute EventHandler oncanplay;
attribute EventHandler oncanplaythrough;
attribute EventHandler onchange;
@@ -128,14 +129,14 @@ interface GlobalEventHandlers {
attribute EventHandler onmozpointerlockerror;
// CSS-Animation and CSS-Transition handlers.
+ attribute EventHandler onanimationcancel;
attribute EventHandler onanimationend;
attribute EventHandler onanimationiteration;
attribute EventHandler onanimationstart;
+ attribute EventHandler ontransitioncancel;
attribute EventHandler ontransitionend;
- // We will ship transitionrun and transitionstart events
- // on Firefox 53. (For detail, see bug 1324985)
-// attribute EventHandler ontransitionrun;
-// attribute EventHandler ontransitionstart;
+ attribute EventHandler ontransitionrun;
+ attribute EventHandler ontransitionstart;
// CSS-Animation and CSS-Transition legacy handlers.
// This handler isn't standard.
diff --git a/dom/webidl/MozApplicationEvent.webidl b/dom/webidl/MozApplicationEvent.webidl
deleted file mode 100644
index e46fdca06..000000000
--- a/dom/webidl/MozApplicationEvent.webidl
+++ /dev/null
@@ -1,16 +0,0 @@
-/* -*- Mode: IDL; 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/.
- */
-
-[Constructor(DOMString type, optional MozApplicationEventInit eventInitDict), ChromeOnly]
-interface MozApplicationEvent : Event
-{
- readonly attribute DOMApplication? application;
-};
-
-dictionary MozApplicationEventInit : EventInit
-{
- DOMApplication? application = null;
-};
diff --git a/dom/webidl/MozNetworkStats.webidl b/dom/webidl/MozNetworkStats.webidl
deleted file mode 100644
index dc8635b87..000000000
--- a/dom/webidl/MozNetworkStats.webidl
+++ /dev/null
@@ -1,73 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Provide the detailed options for specifying different kinds of data filtering
- * in getSamples function.
- */
-dictionary NetworkStatsGetOptions
-{
- /**
- * App manifest URL is used to filter network stats by app, while service type
- * is used to filter stats by system service.
- * Note that, these two options cannot be specified at the same time for now;
- * others, an NS_ERROR_NOT_IMPLMENTED exception will be thrown.
- */
- DOMString? appManifestURL = null;
- DOMString serviceType = "";
- /**
- * If it is set as true, only the browsing traffic, which is generated from
- * the mozbrowser iframe element within an app, is returned in result.
- * If it is set as false or not set, the total traffic, which is generated
- * from both the mozapp and mozbrowser iframe elements, is returned.
- */
- boolean browsingTrafficOnly = false;
-};
-
-dictionary NetworkStatsAlarmOptions
-{
- Date startTime;
- Date data;
-};
-
-[JSImplementation="@mozilla.org/networkstats;1",
- ChromeOnly,
- Pref="dom.mozNetworkStats.enabled"]
-interface MozNetworkStats {
- /**
- * App manifest URL of an application for specifying the per-app stats of the
- * specified app.
- */
- readonly attribute DOMString appManifestURL;
-
- /**
- * True if this stats is the browsing traffic of an app (the traffic generated
- * by a mozbrowser iframe element).
- * Otherwise this stats represents the total traffic of an app.
- */
- readonly attribute boolean browsingTrafficOnly;
-
- /**
- * Service type is used to retrieve the corresponding "system-only" stats.
- * E.g., "Tethering", "OTA", etc.
- */
- readonly attribute DOMString serviceType;
-
- /**
- * Network the returned data belongs to.
- */
- readonly attribute MozNetworkStatsInterface network;
-
- /**
- * Stats for a network.
- */
- [Cached, Pure]
- readonly attribute sequence<MozNetworkStatsData> data;
-
- /**
- * Dates
- */
- readonly attribute object start;
- readonly attribute object end;
-};
diff --git a/dom/webidl/MozNetworkStatsAlarm.webidl b/dom/webidl/MozNetworkStatsAlarm.webidl
deleted file mode 100644
index e8bc01998..000000000
--- a/dom/webidl/MozNetworkStatsAlarm.webidl
+++ /dev/null
@@ -1,13 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-[JSImplementation="@mozilla.org/networkstatsalarm;1",
- ChromeOnly,
- Pref="dom.mozNetworkStats.enabled"]
-interface MozNetworkStatsAlarm {
- readonly attribute unsigned long alarmId;
- readonly attribute MozNetworkStatsInterface network;
- readonly attribute long long threshold;
- readonly attribute any data;
-};
diff --git a/dom/webidl/MozNetworkStatsData.webidl b/dom/webidl/MozNetworkStatsData.webidl
deleted file mode 100644
index 60d1e0d36..000000000
--- a/dom/webidl/MozNetworkStatsData.webidl
+++ /dev/null
@@ -1,12 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-[JSImplementation="@mozilla.org/networkStatsdata;1",
- ChromeOnly,
- Pref="dom.mozNetworkStats.enabled"]
-interface MozNetworkStatsData {
- readonly attribute unsigned long rxBytes; // Received bytes.
- readonly attribute unsigned long txBytes; // Sent bytes.
- readonly attribute Date date; // Date.
-};
diff --git a/dom/webidl/MozNetworkStatsInterface.webidl b/dom/webidl/MozNetworkStatsInterface.webidl
deleted file mode 100644
index 82acfad6b..000000000
--- a/dom/webidl/MozNetworkStatsInterface.webidl
+++ /dev/null
@@ -1,26 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-dictionary NetworkInterface {
- long type;
- DOMString id;
-};
-
-/**
- * Represents a data interface for which the manager is recording statistics.
- */
-[Constructor(optional NetworkInterface networkinterface),
- JSImplementation="@mozilla.org/networkstatsinterface;1",
- ChromeOnly,
- Pref="dom.mozNetworkStats.enabled"]
-interface MozNetworkStatsInterface {
- readonly attribute long type;
-
- /**
- * Id value is '0' for wifi or the iccid for mobile (SIM).
- */
- readonly attribute DOMString id;
-
- jsonifier;
-};
diff --git a/dom/webidl/MozNetworkStatsManager.webidl b/dom/webidl/MozNetworkStatsManager.webidl
deleted file mode 100644
index 2c0e374d7..000000000
--- a/dom/webidl/MozNetworkStatsManager.webidl
+++ /dev/null
@@ -1,96 +0,0 @@
-/* -*- Mode: IDL; 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/.
- */
-
-[NavigatorProperty="mozNetworkStats",
- JSImplementation="@mozilla.org/networkStatsManager;1",
- ChromeOnly,
- Pref="dom.mozNetworkStats.enabled"]
-interface MozNetworkStatsManager {
- /**
- * Constants for known interface types.
- */
- const long WIFI = 0;
- const long MOBILE = 1;
-
- /**
- * Find samples between two dates start and end, both included.
- *
- * If options is provided, per-app or per-system service usage will be
- * retrieved; otherwise the target will be overall system usage.
- *
- * If success, the request result will be an MozNetworkStats object.
- */
- DOMRequest getSamples(MozNetworkStatsInterface network,
- Date start,
- Date end,
- optional NetworkStatsGetOptions options);
-
- /**
- * Install an alarm on a network. The network must be in the return of
- * getAvailableNetworks() otherwise an "InvalidNetwork" exception will
- * be raised.
- *
- * When total data usage reaches threshold bytes, a "networkstats-alarm"
- * system message is sent to the application, where the optional parameter
- * |data| must be a cloneable object.
- *
- * If success, the |result| field of the DOMRequest keeps the alarm Id.
- */
- DOMRequest addAlarm(MozNetworkStatsInterface network,
- long long threshold,
- optional NetworkStatsAlarmOptions options);
-
- /**
- * Obtain all alarms for those networks returned by getAvailableNetworks().
- * If a network is provided, only retrieves the alarms for that network.
- * The network must be one of those returned by getAvailebleNetworks() or an
- * "InvalidNetwork" exception will be raised.
- *
- * Each alarm object has the same fields as that in the system message:
- * - alarmId
- * - network
- * - threshold
- * - data
- */
- DOMRequest getAllAlarms(optional MozNetworkStatsInterface network);
-
- /**
- * Remove all network alarms. If an |alarmId| is provided, then only that
- * alarm is removed.
- */
- DOMRequest removeAlarms(optional unsigned long alarmId = 0);
-
- /**
- * Remove all stats related with the provided network from DB.
- */
- DOMRequest clearStats(MozNetworkStatsInterface network);
-
- /**
- * Remove all stats in the database.
- */
- DOMRequest clearAllStats();
-
- /**
- * Return available networks that used to be saved in the database.
- */
- DOMRequest getAvailableNetworks(); // array of MozNetworkStatsInterface.
-
- /**
- * Return available service types that used to be saved in the database.
- */
- DOMRequest getAvailableServiceTypes(); // array of string.
-
- /**
- * Minimum time in milliseconds between samples stored in the database.
- */
- readonly attribute long sampleRate;
-
- /**
- * Time in milliseconds recorded by the API until present time. All samples
- * older than maxStorageAge from now are deleted.
- */
- readonly attribute long long maxStorageAge;
-};
diff --git a/dom/webidl/MozSpeakerManager.webidl b/dom/webidl/MozSpeakerManager.webidl
deleted file mode 100644
index 56ecf866f..000000000
--- a/dom/webidl/MozSpeakerManager.webidl
+++ /dev/null
@@ -1,18 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/.
- */
-
-/*
- * Allow application can control acoustic sound output through speaker.
- * Reference https://wiki.mozilla.org/WebAPI/SpeakerManager
- */
-[Constructor()]
-interface MozSpeakerManager : EventTarget {
- /* query the speaker status */
- readonly attribute boolean speakerforced;
- /* force device device's acoustic sound output through speaker */
- attribute boolean forcespeaker;
- /* this event will be fired when device's speaker forced status change */
- attribute EventHandler onspeakerforcedchange;
-};
diff --git a/dom/webidl/MozWifiCapabilities.webidl b/dom/webidl/MozWifiCapabilities.webidl
deleted file mode 100644
index 3acf5fd55..000000000
--- a/dom/webidl/MozWifiCapabilities.webidl
+++ /dev/null
@@ -1,46 +0,0 @@
-/* -*- Mode: IDL; 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/.
- */
-
-/*
- * The capabilities of Wifi. These are guaranteed not to change over the
- * lifetime of that particular instance.
- */
-enum WifiSecurityMethod {
- "OPEN",
- "WEP",
- "WPA-PSK",
- "WPA-EAP"
-};
-
-enum WifiWpaMethod {
- "SIM",
- "PEAP",
- "TTLS",
- "TLS"
-};
-
-enum WifiWpaPhase2Method {
- "MSCHAPV2",
- "GTC"
-};
-
-enum WifiWpaCertificate {
- "SERVER",
- "USER"
-};
-
-[JSImplementation="@mozilla.org/mozwificapabilities;1",
- Func="Navigator::HasWifiManagerSupport"]
-interface MozWifiCapabilities {
- [Constant, Cached] readonly attribute sequence<WifiSecurityMethod> security;
- [Constant, Cached] readonly attribute sequence<WifiWpaMethod> eapMethod;
- [Constant, Cached] readonly attribute sequence<WifiWpaPhase2Method> eapPhase2;
- [Constant, Cached] readonly attribute sequence<WifiWpaCertificate> certificate;
-
- jsonifier;
-};
-
diff --git a/dom/webidl/MozWifiConnectionInfoEvent.webidl b/dom/webidl/MozWifiConnectionInfoEvent.webidl
deleted file mode 100644
index cfba1aa3e..000000000
--- a/dom/webidl/MozWifiConnectionInfoEvent.webidl
+++ /dev/null
@@ -1,43 +0,0 @@
-/* -*- Mode: IDL; 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/.
- */
-
-[Constructor(DOMString type, optional MozWifiConnectionInfoEventInit eventInitDict)]
-interface MozWifiConnectionInfoEvent : Event
-{
- /**
- * Network object with an SSID field.
- */
- readonly attribute any network;
-
- /**
- * Strength of the signal to network, in dBm between -55 and -100 dBm.
- */
- readonly attribute short signalStrength;
-
- /**
- * Relative signal strength between 0 and 100.
- */
- readonly attribute short relSignalStrength;
-
- /**
- * Link speed in Mb/s.
- */
- readonly attribute long linkSpeed;
-
- /**
- * IP address in the dotted quad format.
- */
- readonly attribute DOMString? ipAddress;
-};
-
-dictionary MozWifiConnectionInfoEventInit : EventInit
-{
- any network = null;
- short signalStrength = 0;
- short relSignalStrength = 0;
- long linkSpeed = 0;
- DOMString ipAddress = "";
-};
diff --git a/dom/webidl/MozWifiManager.webidl b/dom/webidl/MozWifiManager.webidl
deleted file mode 100644
index dd5aa5932..000000000
--- a/dom/webidl/MozWifiManager.webidl
+++ /dev/null
@@ -1,347 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-enum WifiWPSMethod {
- "pbc",
- "pin",
- "cancel"
-};
-
-enum ConnectionStatus {
- "connecting",
- "authenticating",
- "associated",
- "connected",
- "disconnected",
- "wps-timedout",
- "wps-failed",
- "wps-overlapped",
- "connectingfailed"
-};
-
-dictionary WifiWPSInfo {
- WifiWPSMethod method;
- DOMString? pin;
- DOMString? bssid;
-};
-
-dictionary NetworkProperties {
- DOMString ssid;
- long mode;
- long frequency;
- sequence<DOMString>? security;
- sequence<DOMString>? capabilities;
- boolean known;
- boolean connected;
- boolean hidden;
- DOMString bssid;
- DOMString signalStrength;
- long relSignalStrength;
- DOMString psk;
- DOMString wep;
- DOMString wep_key0;
- DOMString wep_key1;
- DOMString wep_key2;
- DOMString wep_key3;
- long wep_tx_keyidx;
- long priority;
- long scan_ssid;
- DOMString keyManagement;
- DOMString identity;
- DOMString password;
- DOMString auth_alg;
- DOMString phase1;
- DOMString phase2;
- DOMString eap;
- DOMString pin;
- boolean dontConnect;
- DOMString serverCertificate;
- DOMString subjectMatch;
- DOMString userCertificate;
-};
-
-[Constructor(optional NetworkProperties properties),
- JSImplementation="@mozilla.org/mozwifinetwork;1",
- Func="Navigator::HasWifiManagerSupport"]
-interface MozWifiNetwork {
- readonly attribute DOMString ssid;
- readonly attribute long mode;
- readonly attribute long frequency;
- [Constant, Cached] readonly attribute sequence<DOMString>? security;
- [Constant, Cached] readonly attribute sequence<DOMString>? capabilities;
- readonly attribute boolean known;
- readonly attribute boolean connected;
- readonly attribute boolean hidden;
-
- attribute DOMString? bssid;
- attribute DOMString? signalStrength;
- attribute long? relSignalStrength;
- attribute DOMString? psk;
- attribute DOMString? wep;
- attribute DOMString? wep_key0;
- attribute DOMString? wep_key1;
- attribute DOMString? wep_key2;
- attribute DOMString? wep_key3;
- attribute long? wep_tx_keyidx;
- attribute long? priority;
- attribute long? scan_ssid;
- attribute DOMString? keyManagement;
- attribute DOMString? identity;
- attribute DOMString? password;
- attribute DOMString? auth_alg;
- attribute DOMString? phase1;
- attribute DOMString? phase2;
- attribute DOMString? eap;
- attribute DOMString? pin;
- attribute boolean? dontConnect;
- attribute DOMString? serverCertificate;
- attribute DOMString? subjectMatch;
- attribute DOMString? userCertificate;
-};
-
-[JSImplementation="@mozilla.org/mozwificonnection;1",
- ChromeOnly]
-interface MozWifiConnection {
- readonly attribute ConnectionStatus status;
- readonly attribute MozWifiNetwork? network;
-};
-
-[JSImplementation="@mozilla.org/mozwificonnectioninfo;1",
- ChromeOnly]
-interface MozWifiConnectionInfo {
- readonly attribute short signalStrength;
- readonly attribute short relSignalStrength;
- readonly attribute long linkSpeed;
- readonly attribute DOMString? ipAddress;
-};
-
-dictionary IPConfiguration {
- boolean enabled;
- DOMString ipaddr;
- DOMString proxy;
- short maskLength;
- DOMString gateway;
- DOMString dns1;
- DOMString dns2;
-};
-
-[JSImplementation="@mozilla.org/wifimanager;1",
- NavigatorProperty="mozWifiManager",
- Func="Navigator::HasWifiManagerSupport",
- UnsafeInPrerendering]
-interface MozWifiManager : EventTarget {
- /**
- * Turn on/off wifi functionality.
- * @param enable true for enable, false for disable.
- * onsuccess: Wifi enable/disable successfully, including no status change.
- * onerror: Wifi enable/disable failed or prohibited.
- */
- DOMRequest setWifiEnabled(boolean enabled);
-
- /**
- * Returns the list of currently available networks.
- * onsuccess: We have obtained the current list of networks. request.value
- * is an object whose property names are SSIDs and values are
- * network objects.
- * onerror: We were unable to obtain a list of property names.
- */
- DOMRequest getNetworks();
-
- /**
- * Returns the list of networks known to the system that will be
- * automatically connected to if they're in range.
- * onsuccess: request.value is an object whose property names are
- * SSIDs and values are network objects.
- * onerror: We were unable to obtain a list of known networks.
- */
- DOMRequest getKnownNetworks();
-
- /**
- * Takes one of the networks returned from getNetworks and tries to
- * connect to it.
- * @param network A network object with information about the network,
- * such as the SSID, key management desired, etc.
- * onsuccess: We have started attempting to associate with the network.
- * request.value is true.
- * onerror: We were unable to select the network. This most likely means a
- * configuration error.
- */
- DOMRequest associate(MozWifiNetwork network);
-
- /**
- * Given a network, removes it from the list of networks that we'll
- * automatically connect to. In order to re-connect to the network, it is
- * necessary to call associate on it.
- * @param network A network object with the SSID of the network to remove.
- * onsuccess: We have removed this network. If we were previously
- * connected to it, we have started reconnecting to the next
- * network in the list.
- * onerror: We were unable to remove the network.
- */
- DOMRequest forget(MozWifiNetwork network);
-
- /**
- * Wi-Fi Protected Setup functionality.
- * @param detail WPS detail which has 'method' and 'pin' field.
- * The possible method field values are:
- * - pbc: The Push Button Configuration.
- * - pin: The PIN configuration.
- * - cancel: Request to cancel WPS in progress.
- * If method field is 'pin', 'pin' field can exist and has
- * a PIN number.
- * If method field is 'pin', 'bssid' field can exist and has
- * a opposite BSSID.
- * onsuccess: We have successfully started/canceled wps.
- * onerror: We have failed to start/cancel wps.
- */
- DOMRequest wps(optional WifiWPSInfo detail);
-
- /**
- * Turn on/off wifi power saving mode.
- * @param enabled true or false.
- * onsuccess: We have successfully turn on/off wifi power saving mode.
- * onerror: We have failed to turn on/off wifi power saving mode.
- */
- DOMRequest setPowerSavingMode(boolean enabled);
-
- /**
- * Given a network, configure using static IP instead of running DHCP
- * @param network A network object with the SSID of the network to set static ip.
- * @param info info should have following field:
- * - enabled True to enable static IP, false to use DHCP
- * - ipaddr configured static IP address
- * - proxy configured proxy server address
- * - maskLength configured mask length
- * - gateway configured gateway address
- * - dns1 configured first DNS server address
- * - dns2 configured seconf DNS server address
- * onsuccess: We have successfully configure the static ip mode.
- * onerror: We have failed to configure the static ip mode.
- */
- DOMRequest setStaticIpMode(MozWifiNetwork network, optional IPConfiguration info);
-
- /**
- * Given a network, configure http proxy when using wifi.
- * @param network A network object with the SSID of the network to set http proxy.
- * @param info info should have following field:
- * - httpProxyHost ip address of http proxy.
- * - httpProxyPort port of http proxy, set 0 to use default port 8080.
- * set info to null to clear http proxy.
- * onsuccess: We have successfully configure http proxy.
- * onerror: We have failed to configure http proxy.
- */
- DOMRequest setHttpProxy(MozWifiNetwork network, any info);
-
- /**
- * Import a certificate file, only support CA certificate now.
- * @param certBlob A Blob object containing raw data of certificate to be imported.
- * Supported format: binary/base64 encoded DER certificates.
- * (.der/.crt/.cer/.pem)
- * Cause error if importing certificates already imported.
- * @param certPassword Password of certificate.
- * @param certNickname User assigned nickname for imported certificate.
- * Nickname must be unique, it causes error on redundant nickname.
- * onsuccess: We have successfully imported certificate. request.result is an
- * object, containing information of imported CA:
- * {
- * nickname: Nickname of imported CA, String.
- * usage: Supported usage of imported CA, Array of String,
- * includes: "ServerCert".
- * }
- * onerror: We have failed to import certificate.
- */
- DOMRequest importCert(Blob certBlob,
- DOMString certPassword,
- DOMString certNickname);
-
- /**
- * Get list of imported WIFI certificates.
- * onsuccess: We have successfully gotten imported certificate list.
- * request.result is an object using nickname as key, array of usage
- * string as value.
- * request.result[USAGE] = [CA_NICKNAME1, CA_NICKNAME2, ...]
- * USAGE string includes: "ServerCert".
- * onerror: We have failed to list certificate.
- */
- DOMRequest getImportedCerts();
-
- /**
- * Delete an imported certificate.
- * @param certNickname Nickname of imported to be deleted.
- * onsuccess: We have successfully deleted certificate.
- * onerror: We have failed to delete certificate.
- */
- DOMRequest deleteCert(DOMString certNickname);
-
- /**
- * Returns whether or not wifi is currently enabled.
- */
- readonly attribute boolean enabled;
-
- /**
- * Returns the MAC address of the wifi adapter.
- */
- readonly attribute DOMString macAddress;
-
- /**
- * An non-null object containing the following information:
- * - status ("disconnected", "connecting", "associated", "connected")
- * - network
- *
- * Note that the object returned is read only. Any changes required must
- * be done by calling other APIs.
- */
- readonly attribute MozWifiConnection connection;
-
- /**
- * A connectionInformation object with the same information found in an
- * MozWifiConnectionInfoEvent (but without the network).
- * If we are not currently connected to a network, this will be null.
- */
- readonly attribute MozWifiConnectionInfo? connectionInformation;
-
- /**
- * Capabilities of Wifi.
- */
- readonly attribute MozWifiCapabilities? capabilities;
-
- /**
- * State notification listeners. These all take an
- * MozWifiStatusChangeEvent with the new status and a network (which may be
- * null).
- *
- * The possible statuses are:
- * - connecting: Fires when we start the process of connecting to a
- * network.
- * - associated: Fires when we have connected to an access point but do
- * not yet have an IP address.
- * - connected: Fires once we are fully connected to an access point and
- * can access the internet.
- * - disconnected: Fires when we either fail to connect to an access
- * point (transition: associated -> disconnected) or
- * when we were connected to a network but have
- * disconnected for any reason (transition: connected ->
- * disconnected).
- */
- attribute EventHandler onstatuschange;
-
- /**
- * An event listener that is called with information about the signal
- * strength and link speed every 5 seconds.
- */
- attribute EventHandler onconnectioninfoupdate;
-
- /**
- * These two events fire when the wifi system is brought online or taken
- * offline.
- */
- attribute EventHandler onenabled;
- attribute EventHandler ondisabled;
-
- /**
- * An event listener that is called with information about the number
- * of wifi stations connected to wifi hotspot every 5 seconds.
- */
- attribute EventHandler onstationinfoupdate;
-};
diff --git a/dom/webidl/MozWifiP2pManager.webidl b/dom/webidl/MozWifiP2pManager.webidl
deleted file mode 100644
index 58ac1f7be..000000000
--- a/dom/webidl/MozWifiP2pManager.webidl
+++ /dev/null
@@ -1,147 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-enum WPSMethod {
- "pbc",
- "keypad",
- "display"
-};
-
-dictionary WPSInfo {
- WPSMethod method;
- DOMString pin;
-};
-
-[JSImplementation="@mozilla.org/wifip2pgroupowner;1",
- Func="Navigator::HasWifiManagerSupport"]
-interface MozWifiP2pGroupOwner {
- readonly attribute DOMString groupName;
- readonly attribute DOMString macAddress;
- readonly attribute DOMString ipAddress;
- readonly attribute DOMString passphrase;
- readonly attribute DOMString ssid;
- readonly attribute any wpsCapabilities;
- readonly attribute unsigned long freq;
- readonly attribute boolean isLocal;
-};
-
-[JSImplementation="@mozilla.org/wifip2pmanager;1",
- NavigatorProperty="mozWifiP2pManager",
- Func="Navigator::HasWifiManagerSupport"]
-interface MozWifiP2pManager : EventTarget
-{
- /**
- * Enable/Disable wifi direct scan.
- *
- * onsuccess: Succeeded in starting/stopping wifi direct scan.
- * onerror: Failed to start/stop wifi direct scan.
- *
- */
- DOMRequest setScanEnabled(boolean enabled);
-
- /**
- * Connect to a peer with given configuration.
- *
- * @param address The peer MAC address we are going to connect.
- * @param wpsMethod The WPS method we want to use.
- * @param goIntent Number from 0 ~ 15 to indicate how much we want to be
- * the group owner.
- *
- * onsuccess: Succeeded in issueing a 'connect' request. It doesn't mean we
- * have connected to the peer.
- *
- * onerror: Failed to issue a 'connect' request, probably due to an
- * invalid peer address, unsupported wps method or any
- * preliminary error.
- *
- **/
- DOMRequest connect(DOMString address, WPSMethod wpsMethod, optional byte goIntent);
-
- /**
- * Disconnect with a peer.
- *
- * @param address The mac address of the peer.
- *
- * onsuccess: Succeeded to issue a 'disconnect' request. It doesn't mean we
- * have disconnected with the peer.
- *
- * onerror: Failed to issue a 'disconnect' request, probably due to the
- * invalid peer address or any preliminary error.
- *
- */
- DOMRequest disconnect(DOMString address);
-
- /**
- * Get peer list
- *
- * onsuccess: Command success, req.result contains an array of peer objects.
- * onerror: Command failed.
- *
- * Peer object format:
- * .address MAC address of the peer (string)
- * .name the peer's device name (string)
- * .isGroupOwner if the peer is the group owner (boolean)
- * .wpsCapabilities array of the supported |WPSMethod|
- * .connectionStatus one of { "disconnected", "connecting", "connected", "disconnecting" }
- *
- */
- DOMRequest getPeerList();
-
- /**
- * Set pairing confirmation result.
- *
- * @param accepted Boolean to indicate whether we accepted the request or not.
- * @param pin The user input pin number if the wps method is keypad.
- *
- * onsuccess: Command succeeded.
- * onerror: Command failed.
- *
- */
- DOMRequest setPairingConfirmation(boolean accepted, optional DOMString pin);
-
- /**
- * Set device name.
- *
- * @param devieName The new device name we are going to set.
- *
- * onsuccess: Command succeeded.
- * onerror: Command failed.
- *
- */
- DOMRequest setDeviceName(DOMString deviceName);
-
- /**
- * Returns if Wifi Direct is enabled.
- *
- */
- readonly attribute boolean enabled;
-
- /**
- * The current group owner, null if none.
- */
- readonly attribute MozWifiP2pGroupOwner? groupOwner;
-
- /**
- * An event listener that is called whenever the Wifi Direct peer list is
- * updated. Use getPeerList() to get the up-to-date peer list.
- */
- attribute EventHandler onpeerinfoupdate;
-
- /**
- * An event listener that is called whenever Wifi Direct status changed.
- * The address of the changed peer will be stored in event.peerList.
- * See MozWifiP2pStatusChangeEvent.webidl.
- */
- attribute EventHandler onstatuschange;
-
- /**
- * An event listener that is called whenever Wifi Direct is enabled.
- */
- attribute EventHandler onenabled;
-
- /**
- * An event listener that is called whenever Wifi Direct is disabled.
- */
- attribute EventHandler ondisabled;
-};
diff --git a/dom/webidl/MozWifiP2pStatusChangeEvent.webidl b/dom/webidl/MozWifiP2pStatusChangeEvent.webidl
deleted file mode 100644
index be96e2786..000000000
--- a/dom/webidl/MozWifiP2pStatusChangeEvent.webidl
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- Mode: IDL; 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/.
- */
-
-[Constructor(DOMString type, optional MozWifiP2pStatusChangeEventInit eventInitDict),
- Func="Navigator::HasWifiManagerSupport"]
-interface MozWifiP2pStatusChangeEvent : Event
-{
- /**
- * The mac address of the peer whose status has just changed.
- */
- readonly attribute DOMString peerAddress;
-};
-
-dictionary MozWifiP2pStatusChangeEventInit : EventInit
-{
- DOMString peerAddress = "";
-};
diff --git a/dom/webidl/MozWifiStationInfoEvent.webidl b/dom/webidl/MozWifiStationInfoEvent.webidl
deleted file mode 100644
index ff3f5ac6a..000000000
--- a/dom/webidl/MozWifiStationInfoEvent.webidl
+++ /dev/null
@@ -1,19 +0,0 @@
-/* -*- Mode: IDL; 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/.
- */
-
-[Constructor(DOMString type, optional MozWifiStationInfoEventInit eventInitDict)]
-interface MozWifiStationInfoEvent : Event
-{
- /**
- * The number of wifi stations connected to wifi hotspot.
- */
- readonly attribute short station;
-};
-
-dictionary MozWifiStationInfoEventInit : EventInit
-{
- short station = 0;
-};
diff --git a/dom/webidl/MozWifiStatusChangeEvent.webidl b/dom/webidl/MozWifiStatusChangeEvent.webidl
deleted file mode 100644
index 20d16e4d9..000000000
--- a/dom/webidl/MozWifiStatusChangeEvent.webidl
+++ /dev/null
@@ -1,27 +0,0 @@
-/* -*- Mode: IDL; 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/.
- */
-
-[Constructor(DOMString type, optional MozWifiStatusChangeEventInit eventInitDict)]
-interface MozWifiStatusChangeEvent : Event
-{
- /**
- * Network object with a SSID field describing the network affected by
- * this change. This might be null.
- */
- readonly attribute any network;
-
- /**
- * String describing the current status of the wifi manager. See above for
- * the possible values.
- */
- readonly attribute DOMString? status;
-};
-
-dictionary MozWifiStatusChangeEventInit : EventInit
-{
- any network = null;
- DOMString status = "";
-};
diff --git a/dom/webidl/Performance.webidl b/dom/webidl/Performance.webidl
index eaede253c..0bd2677df 100644
--- a/dom/webidl/Performance.webidl
+++ b/dom/webidl/Performance.webidl
@@ -17,6 +17,9 @@ typedef sequence <PerformanceEntry> PerformanceEntryList;
interface Performance {
[DependsOn=DeviceState, Affects=Nothing]
DOMHighResTimeStamp now();
+
+ [Constant]
+ readonly attribute DOMHighResTimeStamp timeOrigin;
};
[Exposed=Window]
diff --git a/dom/webidl/PerformanceNavigationTiming.webidl b/dom/webidl/PerformanceNavigationTiming.webidl
new file mode 100644
index 000000000..fa3ecaec4
--- /dev/null
+++ b/dom/webidl/PerformanceNavigationTiming.webidl
@@ -0,0 +1,33 @@
+/* -*- Mode: IDL; 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/.
+ *
+ * The origin of this IDL file is
+ * https://www.w3.org/TR/navigation-timing-2/#sec-PerformanceNavigationTiming
+ *
+ * Copyright © 2016 W3C® (MIT, ERCIM, Keio, Beihang).
+ * W3C liability, trademark and document use rules apply.
+ */
+
+enum NavigationType {
+ "navigate",
+ "reload",
+ "back_forward",
+ "prerender"
+};
+
+interface PerformanceNavigationTiming : PerformanceResourceTiming {
+ readonly attribute DOMHighResTimeStamp unloadEventStart;
+ readonly attribute DOMHighResTimeStamp unloadEventEnd;
+ readonly attribute DOMHighResTimeStamp domInteractive;
+ readonly attribute DOMHighResTimeStamp domContentLoadedEventStart;
+ readonly attribute DOMHighResTimeStamp domContentLoadedEventEnd;
+ readonly attribute DOMHighResTimeStamp domComplete;
+ readonly attribute DOMHighResTimeStamp loadEventStart;
+ readonly attribute DOMHighResTimeStamp loadEventEnd;
+ readonly attribute NavigationType type;
+ readonly attribute unsigned short redirectCount;
+
+ jsonifier;
+};
diff --git a/dom/webidl/PerformanceObserver.webidl b/dom/webidl/PerformanceObserver.webidl
index a3a14cb1e..4cebecbeb 100644
--- a/dom/webidl/PerformanceObserver.webidl
+++ b/dom/webidl/PerformanceObserver.webidl
@@ -9,6 +9,7 @@
dictionary PerformanceObserverInit {
required sequence<DOMString> entryTypes;
+ boolean buffered = false;
};
callback PerformanceObserverCallback = void (PerformanceObserverEntryList entries, PerformanceObserver observer);
diff --git a/dom/webidl/PerformanceResourceTiming.webidl b/dom/webidl/PerformanceResourceTiming.webidl
index 021b84ae2..112228325 100644
--- a/dom/webidl/PerformanceResourceTiming.webidl
+++ b/dom/webidl/PerformanceResourceTiming.webidl
@@ -4,7 +4,7 @@
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The origin of this IDL file is
- * http://w3c-test.org/webperf/specs/ResourceTiming/#performanceresourcetiming
+ * https://w3c.github.io/resource-timing/#performanceresourcetiming
*
* Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
* liability, trademark and document use rules apply.
@@ -12,14 +12,10 @@
interface PerformanceResourceTiming : PerformanceEntry
{
- // A string with the name of that element that initiated the load.
- // If the initiator is a CSS resource, the initiatorType attribute must return
- // the string "css".
- // If the initiator is an XMLHttpRequest object, the initiatorType attribute
- // must return the string "xmlhttprequest".
readonly attribute DOMString initiatorType;
readonly attribute DOMString nextHopProtocol;
+ readonly attribute DOMHighResTimeStamp workerStart;
readonly attribute DOMHighResTimeStamp redirectStart;
readonly attribute DOMHighResTimeStamp redirectEnd;
readonly attribute DOMHighResTimeStamp fetchStart;
diff --git a/dom/webidl/PerformanceTiming.webidl b/dom/webidl/PerformanceTiming.webidl
index e14201440..4aa403a50 100644
--- a/dom/webidl/PerformanceTiming.webidl
+++ b/dom/webidl/PerformanceTiming.webidl
@@ -33,5 +33,11 @@ interface PerformanceTiming {
readonly attribute unsigned long long loadEventStart;
readonly attribute unsigned long long loadEventEnd;
+ // This is a Chrome proprietary extension and not part of the
+ // performance/navigation timing specification.
+ // Returns 0 if a non-blank paint has not happened.
+ [Pref="dom.performance.time_to_non_blank_paint.enabled"]
+ readonly attribute unsigned long long timeToNonBlankPaint;
+
jsonifier;
};
diff --git a/dom/webidl/Window.webidl b/dom/webidl/Window.webidl
index 36b1f0313..468f1cc8a 100644
--- a/dom/webidl/Window.webidl
+++ b/dom/webidl/Window.webidl
@@ -343,12 +343,6 @@ partial interface Window {
attribute EventHandler onuserproximity;
attribute EventHandler ondevicelight;
-#ifdef MOZ_B2G
- attribute EventHandler onmoztimechange;
- attribute EventHandler onmoznetworkupload;
- attribute EventHandler onmoznetworkdownload;
-#endif
-
void dump(DOMString str);
/**
@@ -385,7 +379,7 @@ Window implements TouchEventHandlers;
Window implements OnErrorEventHandlerForWindow;
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
// https://compat.spec.whatwg.org/#windoworientation-interface
partial interface Window {
[NeedsCallerType]
diff --git a/dom/webidl/moz.build b/dom/webidl/moz.build
index 8682aee97..4c2567a1c 100644
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -347,6 +347,7 @@ WEBIDL_FILES = [
'PerformanceMark.webidl',
'PerformanceMeasure.webidl',
'PerformanceNavigation.webidl',
+ 'PerformanceNavigationTiming.webidl',
'PerformanceObserver.webidl',
'PerformanceObserverEntryList.webidl',
'PerformanceResourceTiming.webidl',
@@ -676,22 +677,9 @@ if CONFIG['MOZ_SECUREELEMENT']:
'SecureElementManager.webidl',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- WEBIDL_FILES += [
- 'MozNetworkStats.webidl',
- 'MozNetworkStatsAlarm.webidl',
- 'MozNetworkStatsData.webidl',
- 'MozNetworkStatsInterface.webidl',
- 'MozNetworkStatsManager.webidl',
- 'MozSpeakerManager.webidl',
- 'MozWifiCapabilities.webidl',
- 'MozWifiManager.webidl',
- 'MozWifiP2pManager.webidl',
- ]
-else:
- WEBIDL_FILES += [
- 'InstallTrigger.webidl',
- ]
+WEBIDL_FILES += [
+ 'InstallTrigger.webidl',
+]
GENERATED_EVENTS_WEBIDL_FILES = [
'AnimationPlaybackEvent.webidl',
@@ -760,14 +748,6 @@ if CONFIG['MOZ_GAMEPAD']:
'GamepadEvent.webidl',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- GENERATED_EVENTS_WEBIDL_FILES += [
- 'MozWifiConnectionInfoEvent.webidl',
- 'MozWifiP2pStatusChangeEvent.webidl',
- 'MozWifiStationInfoEvent.webidl',
- 'MozWifiStatusChangeEvent.webidl',
- ]
-
if CONFIG['MOZ_BUILD_APP'] in ['xulrunner'] or CONFIG['MOZ_PHOENIX'] or CONFIG['MOZ_SUITE']:
WEBIDL_FILES += [
'BrowserFeedWriter.webidl',
@@ -778,14 +758,6 @@ if CONFIG['MOZ_PHOENIX'] or CONFIG['MOZ_FENNEC'] or CONFIG['MOZ_XULRUNNER']:
'External.webidl',
]
-if CONFIG['MOZ_B2G']:
- WEBIDL_FILES += [
- 'MozApplicationEvent.webidl'
- ]
- GENERATED_EVENTS_WEBIDL_FILES += [
- 'MozApplicationEvent.webidl'
- ]
-
if CONFIG['ACCESSIBILITY']:
WEBIDL_FILES += [
'AccessibleNode.webidl',
diff --git a/dom/wifi/DOMWifiManager.js b/dom/wifi/DOMWifiManager.js
deleted file mode 100644
index 8bedfc398..000000000
--- a/dom/wifi/DOMWifiManager.js
+++ /dev/null
@@ -1,543 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
-
-const DEBUG = false; // set to false to suppress debug messages
-
-const DOMWIFIMANAGER_CONTRACTID = "@mozilla.org/wifimanager;1";
-const DOMWIFIMANAGER_CID = Components.ID("{c9b5f09e-25d2-40ca-aef4-c4d13d93c706}");
-
-function MozWifiNetwork() {
-}
-
-MozWifiNetwork.prototype = {
-
- init: function(aWindow) {
- this._window = aWindow;
- },
-
- __init: function(obj) {
- for (let key in obj) {
- this[key] = obj[key];
- }
- },
-
- classID: Components.ID("{c01fd751-43c0-460a-8b64-abf652ec7220}"),
- contractID: "@mozilla.org/mozwifinetwork;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports,
- Ci.nsIDOMGlobalPropertyInitializer])
-};
-
-function MozWifiConnection(obj) {
- this.status = obj.status;
- this.network = obj.network;
-}
-
-MozWifiConnection.prototype = {
- classID: Components.ID("{23579da4-201b-4319-bd42-9b7f337343ac}"),
- contractID: "@mozilla.org/mozwificonnection;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports])
-};
-
-function MozWifiConnectionInfo(obj) {
- this.signalStrength = obj.signalStrength;
- this.relSignalStrength = obj.relSignalStrength;
- this.linkSpeed = obj.linkSpeed;
- this.ipAddress = obj.ipAddress;
-}
-
-MozWifiConnectionInfo.prototype = {
- classID: Components.ID("{83670352-6ed4-4c35-8de9-402296a1959c}"),
- contractID: "@mozilla.org/mozwificonnectioninfo;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports])
-}
-
-function MozWifiCapabilities(obj) {
- this.security = obj.security;
- this.eapMethod = obj.eapMethod;
- this.eapPhase2 = obj.eapPhase2;
- this.certificate = obj.certificate;
-}
-
-MozWifiCapabilities.prototype = {
- classID: Components.ID("08c88ece-8092-481b-863b-5515a52e411a"),
- contractID: "@mozilla.org/mozwificapabilities;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports])
-}
-
-function DOMWifiManager() {
- this.defineEventHandlerGetterSetter("onstatuschange");
- this.defineEventHandlerGetterSetter("onconnectioninfoupdate");
- this.defineEventHandlerGetterSetter("onenabled");
- this.defineEventHandlerGetterSetter("ondisabled");
- this.defineEventHandlerGetterSetter("onstationinfoupdate");
-}
-
-DOMWifiManager.prototype = {
- __proto__: DOMRequestIpcHelper.prototype,
- classDescription: "DOMWifiManager",
- classID: DOMWIFIMANAGER_CID,
- contractID: DOMWIFIMANAGER_CONTRACTID,
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMGlobalPropertyInitializer,
- Ci.nsISupportsWeakReference,
- Ci.nsIObserver]),
-
- // nsIDOMGlobalPropertyInitializer implementation
- init: function(aWindow) {
- // Maintain this state for synchronous APIs.
- this._currentNetwork = null;
- this._connectionStatus = "disconnected";
- this._enabled = false;
- this._lastConnectionInfo = null;
- this._capabilities = null;
- this._stationNumber = 0;
-
- const messages = ["WifiManager:getNetworks:Return:OK", "WifiManager:getNetworks:Return:NO",
- "WifiManager:getKnownNetworks:Return:OK", "WifiManager:getKnownNetworks:Return:NO",
- "WifiManager:associate:Return:OK", "WifiManager:associate:Return:NO",
- "WifiManager:forget:Return:OK", "WifiManager:forget:Return:NO",
- "WifiManager:wps:Return:OK", "WifiManager:wps:Return:NO",
- "WifiManager:setPowerSavingMode:Return:OK", "WifiManager:setPowerSavingMode:Return:NO",
- "WifiManager:setHttpProxy:Return:OK", "WifiManager:setHttpProxy:Return:NO",
- "WifiManager:setStaticIpMode:Return:OK", "WifiManager:setStaticIpMode:Return:NO",
- "WifiManager:importCert:Return:OK", "WifiManager:importCert:Return:NO",
- "WifiManager:getImportedCerts:Return:OK", "WifiManager:getImportedCerts:Return:NO",
- "WifiManager:deleteCert:Return:OK", "WifiManager:deleteCert:Return:NO",
- "WifiManager:setWifiEnabled:Return:OK", "WifiManager:setWifiEnabled:Return:NO",
- "WifiManager:wifiDown", "WifiManager:wifiUp",
- "WifiManager:onconnecting", "WifiManager:onassociate",
- "WifiManager:onconnect", "WifiManager:ondisconnect",
- "WifiManager:onwpstimeout", "WifiManager:onwpsfail",
- "WifiManager:onwpsoverlap", "WifiManager:connectioninfoupdate",
- "WifiManager:onauthenticating", "WifiManager:onconnectingfailed",
- "WifiManager:stationinfoupdate"];
- this.initDOMRequestHelper(aWindow, messages);
- this._mm = Cc["@mozilla.org/childprocessmessagemanager;1"].getService(Ci.nsISyncMessageSender);
-
- var state = this._mm.sendSyncMessage("WifiManager:getState")[0];
- if (state) {
- this._currentNetwork = this._convertWifiNetwork(state.network);
- this._lastConnectionInfo = this._convertConnectionInfo(state.connectionInfo);
- this._enabled = state.enabled;
- this._connectionStatus = state.status;
- this._macAddress = state.macAddress;
- this._capabilities = this._convertWifiCapabilities(state.capabilities);
- } else {
- this._currentNetwork = null;
- this._lastConnectionInfo = null;
- this._enabled = false;
- this._connectionStatus = "disconnected";
- this._macAddress = "";
- }
- },
-
- _convertWifiNetworkToJSON: function(aNetwork) {
- let json = {};
-
- for (let key in aNetwork) {
- // In WifiWorker.js there are lots of check using "key in network".
- // So if the value of any property of WifiNetwork is undefined, do not clone it.
- if (aNetwork[key] != undefined) {
- json[key] = aNetwork[key];
- }
- }
- return json;
- },
-
- _convertWifiNetwork: function(aNetwork) {
- let network = aNetwork ? new this._window.MozWifiNetwork(aNetwork) : null;
- return network;
- },
-
- _convertWifiNetworks: function(aNetworks) {
- let networks = new this._window.Array();
- for (let i in aNetworks) {
- networks.push(this._convertWifiNetwork(aNetworks[i]));
- }
- return networks;
- },
-
- _convertConnection: function(aConn) {
- let conn = aConn ? new MozWifiConnection(aConn) : null;
- return conn;
- },
-
- _convertConnectionInfo: function(aInfo) {
- let info = aInfo ? new MozWifiConnectionInfo(aInfo) : null;
- return info;
- },
-
- _convertWifiCapabilities: function(aCapabilities) {
- let capabilities = aCapabilities ?
- new MozWifiCapabilities(aCapabilities) : null;
- return capabilities;
- },
-
- _sendMessageForRequest: function(name, data, request) {
- let id = this.getRequestId(request);
- this._mm.sendAsyncMessage(name, { data: data, rid: id, mid: this._id });
- },
-
- receiveMessage: function(aMessage) {
- let msg = aMessage.json;
- if (msg.mid && msg.mid != this._id)
- return;
-
- let request;
- if (msg.rid) {
- request = this.takeRequest(msg.rid);
- if (!request) {
- return;
- }
- }
-
- switch (aMessage.name) {
- case "WifiManager:setWifiEnabled:Return:OK":
- Services.DOMRequest.fireSuccess(request, msg.data);
- break;
-
- case "WifiManager:setWifiEnabled:Return:NO":
- Services.DOMRequest.fireError(request, "Unable to enable/disable Wifi");
- break;
-
- case "WifiManager:getNetworks:Return:OK":
- Services.DOMRequest.fireSuccess(request, this._convertWifiNetworks(msg.data));
- break;
-
- case "WifiManager:getNetworks:Return:NO":
- Services.DOMRequest.fireError(request, "Unable to scan for networks");
- break;
-
- case "WifiManager:getKnownNetworks:Return:OK":
- Services.DOMRequest.fireSuccess(request, this._convertWifiNetworks(msg.data));
- break;
-
- case "WifiManager:getKnownNetworks:Return:NO":
- Services.DOMRequest.fireError(request, "Unable to get known networks");
- break;
-
- case "WifiManager:associate:Return:OK":
- Services.DOMRequest.fireSuccess(request, true);
- break;
-
- case "WifiManager:associate:Return:NO":
- Services.DOMRequest.fireError(request, "Unable to add the network");
- break;
-
- case "WifiManager:forget:Return:OK":
- Services.DOMRequest.fireSuccess(request, true);
- break;
-
- case "WifiManager:forget:Return:NO":
- Services.DOMRequest.fireError(request, msg.data);
- break;
-
- case "WifiManager:wps:Return:OK":
- Services.DOMRequest.fireSuccess(request, msg.data);
- break;
-
- case "WifiManager:wps:Return:NO":
- Services.DOMRequest.fireError(request, msg.data);
- break;
-
- case "WifiManager:setPowerSavingMode:Return:OK":
- Services.DOMRequest.fireSuccess(request, msg.data);
- break;
-
- case "WifiManager:setPowerSavingMode:Return:NO":
- Services.DOMRequest.fireError(request, msg.data);
- break;
-
- case "WifiManager:setHttpProxy:Return:OK":
- Services.DOMRequest.fireSuccess(request, msg.data);
- break;
-
- case "WifiManager:setHttpProxy:Return:NO":
- Services.DOMRequest.fireError(request, msg.data);
- break;
-
- case "WifiManager:setStaticIpMode:Return:OK":
- Services.DOMRequest.fireSuccess(request, msg.data);
- break;
-
- case "WifiManager:setStaticIpMode:Return:NO":
- Services.DOMRequest.fireError(request, msg.data);
- break;
-
- case "WifiManager:importCert:Return:OK":
- Services.DOMRequest.fireSuccess(request, Cu.cloneInto(msg.data, this._window));
- break;
-
- case "WifiManager:importCert:Return:NO":
- Services.DOMRequest.fireError(request, msg.data);
- break;
-
- case "WifiManager:getImportedCerts:Return:OK":
- Services.DOMRequest.fireSuccess(request, Cu.cloneInto(msg.data, this._window));
- break;
-
- case "WifiManager:getImportedCerts:Return:NO":
- Services.DOMRequest.fireError(request, msg.data);
- break;
-
- case "WifiManager:deleteCert:Return:OK":
- Services.DOMRequest.fireSuccess(request, msg.data);
- break;
-
- case "WifiManager:deleteCert:Return:NO":
- Services.DOMRequest.fireError(request, msg.data);
- break;
-
- case "WifiManager:wifiDown":
- this._enabled = false;
- this._currentNetwork = null;
- this._fireEnabledOrDisabled(false);
- break;
-
- case "WifiManager:wifiUp":
- this._enabled = true;
- this._macAddress = msg.macAddress;
- this._fireEnabledOrDisabled(true);
- break;
-
- case "WifiManager:onconnecting":
- this._currentNetwork = this._convertWifiNetwork(msg.network);
- this._connectionStatus = "connecting";
- this._fireStatusChangeEvent(msg.network);
- break;
-
- case "WifiManager:onassociate":
- this._currentNetwork = this._convertWifiNetwork(msg.network);
- this._connectionStatus = "associated";
- this._fireStatusChangeEvent(msg.network);
- break;
-
- case "WifiManager:onconnect":
- this._currentNetwork = this._convertWifiNetwork(msg.network);
- this._connectionStatus = "connected";
- this._fireStatusChangeEvent(msg.network);
- break;
-
- case "WifiManager:ondisconnect":
- this._currentNetwork = null;
- this._connectionStatus = "disconnected";
- this._lastConnectionInfo = null;
- this._fireStatusChangeEvent(msg.network);
- break;
-
- case "WifiManager:onwpstimeout":
- this._currentNetwork = null;
- this._connectionStatus = "wps-timedout";
- this._lastConnectionInfo = null;
- this._fireStatusChangeEvent(msg.network);
- break;
-
- case "WifiManager:onwpsfail":
- this._currentNetwork = null;
- this._connectionStatus = "wps-failed";
- this._lastConnectionInfo = null;
- this._fireStatusChangeEvent(msg.network);
- break;
-
- case "WifiManager:onwpsoverlap":
- this._currentNetwork = null;
- this._connectionStatus = "wps-overlapped";
- this._lastConnectionInfo = null;
- this._fireStatusChangeEvent(msg.network);
- break;
-
- case "WifiManager:connectioninfoupdate":
- this._lastConnectionInfo = this._convertConnectionInfo(msg);
- this._fireConnectionInfoUpdate(msg);
- break;
- case "WifiManager:onconnectingfailed":
- this._currentNetwork = null;
- this._connectionStatus = "connectingfailed";
- this._lastConnectionInfo = null;
- this._fireStatusChangeEvent(msg.network);
- break;
- case "WifiManager:onauthenticating":
- this._currentNetwork = this._convertWifiNetwork(msg.network);
- this._connectionStatus = "authenticating";
- this._fireStatusChangeEvent(msg.network);
- break;
- case "WifiManager:stationinfoupdate":
- this._stationNumber = msg.station;
- this._fireStationInfoUpdate(msg);
- break;
- }
- },
-
- _fireStatusChangeEvent: function StatusChangeEvent(aNetwork) {
- var event = new this._window.MozWifiStatusChangeEvent("statuschange",
- { network: this._convertWifiNetwork(aNetwork),
- status: this._connectionStatus
- });
- this.__DOM_IMPL__.dispatchEvent(event);
- },
-
- _fireConnectionInfoUpdate: function onConnectionInfoUpdate(info) {
- var evt = new this._window.MozWifiConnectionInfoEvent("connectioninfoupdate",
- { network: this._currentNetwork,
- signalStrength: info.signalStrength,
- relSignalStrength: info.relSignalStrength,
- linkSpeed: info.linkSpeed,
- ipAddress: info.ipAddress,
- });
- this.__DOM_IMPL__.dispatchEvent(evt);
- },
-
- _fireEnabledOrDisabled: function enabledDisabled(enabled) {
- var evt = new this._window.Event(enabled ? "enabled" : "disabled");
- this.__DOM_IMPL__.dispatchEvent(evt);
- },
-
- _fireStationInfoUpdate: function onStationInfoUpdate(info) {
- var evt = new this._window.MozWifiStationInfoEvent("stationinfoupdate",
- { station: this._stationNumber}
- );
- this.__DOM_IMPL__.dispatchEvent(evt);
- },
-
- setWifiEnabled: function setWifiEnabled(enabled) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:setWifiEnabled", enabled, request);
- return request;
- },
-
- getNetworks: function getNetworks() {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:getNetworks", null, request);
- return request;
- },
-
- getKnownNetworks: function getKnownNetworks() {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:getKnownNetworks", null, request);
- return request;
- },
-
- associate: function associate(network) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:associate",
- this._convertWifiNetworkToJSON(network), request);
- return request;
- },
-
- forget: function forget(network) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:forget",
- this._convertWifiNetworkToJSON(network), request);
- return request;
- },
-
- wps: function wps(detail) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:wps", detail, request);
- return request;
- },
-
- setPowerSavingMode: function setPowerSavingMode(enabled) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:setPowerSavingMode", enabled, request);
- return request;
- },
-
- setHttpProxy: function setHttpProxy(network, info) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:setHttpProxy",
- { network: this._convertWifiNetworkToJSON(network), info:info}, request);
- return request;
- },
-
- setStaticIpMode: function setStaticIpMode(network, info) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:setStaticIpMode",
- { network: this._convertWifiNetworkToJSON(network), info: info}, request);
- return request;
- },
-
- importCert: function nsIDOMWifiManager_importCert(certBlob, certPassword, certNickname) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:importCert",
- {
- certBlob: certBlob,
- certPassword: certPassword,
- certNickname: certNickname
- }, request);
- return request;
- },
-
- getImportedCerts: function nsIDOMWifiManager_getImportedCerts() {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:getImportedCerts", null, request);
- return request;
- },
-
- deleteCert: function nsIDOMWifiManager_deleteCert(certNickname) {
- var request = this.createRequest();
- this._sendMessageForRequest("WifiManager:deleteCert",
- {
- certNickname: certNickname
- }, request);
- return request;
- },
-
- get enabled() {
- return this._enabled;
- },
-
- get macAddress() {
- return this._macAddress;
- },
-
- get connection() {
- let _connection = this._convertConnection({ status: this._connectionStatus,
- network: this._currentNetwork,
- });
- return _connection;
- },
-
- get connectionInformation() {
- return this._lastConnectionInfo;
- },
-
- get capabilities() {
- return this._capabilities;
- },
-
- defineEventHandlerGetterSetter: function(name) {
- Object.defineProperty(this, name, {
- get: function() {
- return this.__DOM_IMPL__.getEventHandler(name);
- },
- set: function(handler) {
- this.__DOM_IMPL__.setEventHandler(name, handler);
- }
- });
- },
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([
- DOMWifiManager, MozWifiNetwork, MozWifiConnection, MozWifiCapabilities,
- MozWifiConnectionInfo
-]);
-
-var debug;
-if (DEBUG) {
- debug = function (s) {
- dump("-*- DOMWifiManager component: " + s + "\n");
- };
-} else {
- debug = function (s) {};
-}
diff --git a/dom/wifi/DOMWifiManager.manifest b/dom/wifi/DOMWifiManager.manifest
deleted file mode 100644
index 3ba83c1b2..000000000
--- a/dom/wifi/DOMWifiManager.manifest
+++ /dev/null
@@ -1,18 +0,0 @@
-# DOMWifiManager.js
-component {c9b5f09e-25d2-40ca-aef4-c4d13d93c706} DOMWifiManager.js
-contract @mozilla.org/wifimanager;1 {c9b5f09e-25d2-40ca-aef4-c4d13d93c706}
-
-component {c01fd751-43c0-460a-8b64-abf652ec7220} DOMWifiManager.js
-contract @mozilla.org/mozwifinetwork;1 {c01fd751-43c0-460a-8b64-abf652ec7220}
-
-component {23579da4-201b-4319-bd42-9b7f337343ac} DOMWifiManager.js
-contract @mozilla.org/mozwificonnection;1 {23579da4-201b-4319-bd42-9b7f337343ac}
-
-component {83670352-6ed4-4c35-8de9-402296a1959c} DOMWifiManager.js
-contract @mozilla.org/mozwificonnectioninfo;1 {83670352-6ed4-4c35-8de9-402296a1959c}
-
-component {ad5c5295-85fb-4460-8e0c-e130d3f029ab} DOMWifiManager.js
-contract @mozilla.org/mozwificertificateinfo;1 {ad5c5295-85fb-4460-8e0c-e130d3f029ab}
-
-component {08c88ece-8092-481b-863b-5515a52e411a} DOMWifiManager.js
-contract @mozilla.org/mozwificapabilities;1 {08c88ece-8092-481b-863b-5515a52e411a}
diff --git a/dom/wifi/DOMWifiP2pManager.js b/dom/wifi/DOMWifiP2pManager.js
deleted file mode 100644
index 3a5637521..000000000
--- a/dom/wifi/DOMWifiP2pManager.js
+++ /dev/null
@@ -1,328 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/DOMRequestHelper.jsm");
-
-const DEBUG = false;
-
-// interface MozWifiP2pGroupOwner implementation.
-
-function MozWifiP2pGroupOwner(aGo) {
- this.groupName = aGo.groupName;
- this.macAddress = aGo.macAddress;
- this.ipAddress = aGo.ipAddress;
- this.passphrase = aGo.passphrase;
- this.ssid = aGo.ssid;
- this.wpsCapabilities = aGo.wpsCapabilities;
- this.freq = aGo.freq;
- this.isLocal = aGo.isLocal;
-}
-
-MozWifiP2pGroupOwner.prototype = {
- classID: Components.ID("{a9b81450-349d-11e3-aa6e-0800200c9a66}"),
- contractID: "@mozilla.org/wifip2pgroupowner;1",
- QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports])
-};
-
-// interface MozWifiP2pManager implementation.
-
-const MOZ_WIFIP2PMANAGER_CONTRACTID = "@mozilla.org/wifip2pmanager;1";
-const MOZ_WIFIP2PMANAGER_CID = Components.ID("{8d9125a0-3498-11e3-aa6e-0800200c9a66}");
-
-function MozWifiP2pManager() {
- this.defineEventHandlerGetterSetter("onstatuschange");
- this.defineEventHandlerGetterSetter("onpeerinfoupdate");
- this.defineEventHandlerGetterSetter("onenabled");
- this.defineEventHandlerGetterSetter("ondisabled");
-
- this.currentPeer = null;
- this.enabled = false;
- this.groupOwner = null;
-}
-
-// For smaller, read-only APIs, we expose any property that doesn't begin with
-// an underscore.
-function exposeReadOnly(obj) {
- let exposedProps = {};
- for (let i in obj) {
- if (i[0] === "_") {
- continue;
- }
- exposedProps[i] = "r";
- }
-
- obj.__exposedProps__ = exposedProps;
- return obj;
-}
-
-function debug(msg) {
- if (DEBUG) {
- dump('-------------- MozWifiP2pManager: ' + msg);
- }
-}
-
-MozWifiP2pManager.prototype = {
- __proto__: DOMRequestIpcHelper.prototype,
-
- classID: MOZ_WIFIP2PMANAGER_CID,
- contractID: MOZ_WIFIP2PMANAGER_CONTRACTID,
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMGlobalPropertyInitializer,
- Ci.nsISupportsWeakReference,
- Ci.nsIObserver,
- Ci.nsISupports]),
-
- //
- // nsIDOMGlobalPropertyInitializer implementation.
- //
-
- init: function(aWindow) {
- const messages = ["WifiP2pManager:setScanEnabled:Return:OK",
- "WifiP2pManager:setScanEnabled:Return:NO",
- "WifiP2pManager:getPeerList:Return:OK",
- "WifiP2pManager:getPeerList:Return:NO",
- "WifiP2pManager:connect:Return:OK",
- "WifiP2pManager:connect:Return:NO",
- "WifiP2pManager:disconnect:Return:OK",
- "WifiP2pManager:disconnect:Return:NO",
- "WifiP2pManager:setPairingConfirmation:Return",
- "WifiP2pManager:setDeviceName:Return:OK",
- "WifiP2pManager:setDeviceName:Return:NO",
-
- "WifiP2pManager:p2pDown",
- "WifiP2pManager:p2pUp",
- "WifiP2pManager:onconnecting",
- "WifiP2pManager:onconnected",
- "WifiP2pManager:ondisconnected",
- "WifiP2pManager:ongroupnstop",
- "WifiP2pManager:onconnectingfailed",
- "WifiP2pManager:onwpstimeout",
- "WifiP2pManager:onwpsfail",
- "WifiP2pManager:onpeerinfoupdate",
- ];
-
- this.initDOMRequestHelper(aWindow, messages);
- this._mm = Cc["@mozilla.org/childprocessmessagemanager;1"].getService(Ci.nsISyncMessageSender);
-
- // Notify the internal a new DOM mananger is created.
- let state = this._mm.sendSyncMessage("WifiP2pManager:getState")[0];
- if (state) {
- debug('State: ' + JSON.stringify(state));
- this.enabled = state.enabled;
- this.currentPeer = state.currentPeer;
- if (state.groupOwner) {
- this.groupOwner = new MozWifiP2pGroupOwner(state.groupOwner);
- }
- } else {
- debug('Failed to get state');
- }
- },
-
- uninit: function() {
- },
-
- _sendMessageForRequest: function(name, data, request) {
- let id = this.getRequestId(request);
- this._mm.sendAsyncMessage(name, { data: data, rid: id, mid: this._id });
- },
-
- receiveMessage: function(aMessage) {
- let msg = aMessage.json;
- if (msg.mid && msg.mid !== this._id) {
- return;
- }
-
- let request;
- switch (aMessage.name) {
- case "WifiP2pManager:setScanEnabled:Return:OK":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireSuccess(request, exposeReadOnly(msg.data));
- break;
-
- case "WifiP2pManager:setScanEnabled:Return:NO":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireError(request, "Unable to enable/disable Wifi P2P peer discovery.");
- break;
-
- case "WifiP2pManager:getPeerList:Return:OK":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireSuccess(request, Cu.cloneInto(msg.data, this._window));
- break;
-
- case "WifiP2pManager:getPeerList:Return:NO":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireError(request, "Unable to disable Wifi P2P peer discovery.");
- break;
-
- case "WifiP2pManager:connect:Return:OK":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireSuccess(request, exposeReadOnly(msg.data));
- break;
-
- case "WifiP2pManager:connect:Return:NO":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireError(request, "Unable to connect to Wifi P2P peer.");
- break;
-
- case "WifiP2pManager:disconnect:Return:OK":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireSuccess(request, exposeReadOnly(msg.data));
- break;
-
- case "WifiP2pManager:disconnect:Return:NO":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireError(request, "Unable to disconnect to Wifi P2P peer.");
- break;
-
- case "WifiP2pManager:setDeviceName:Return:OK":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireSuccess(request, exposeReadOnly(msg.data));
- break;
-
- case "WifiP2pManager:setDeviceName:Return:NO":
- request = this.takeRequest(msg.rid);
- Services.DOMRequest.fireError(request, "Unable to set device name.");
- break;
-
- case "WifiP2pManager:p2pDown":
- this.enabled = false;
- this.currentPeer = null;
- this._fireEnabledOrDisabled(false);
- break;
-
- case "WifiP2pManager:p2pUp":
- this.enabled = true;
- this._fireEnabledOrDisabled(true);
- break;
-
- case "WifiP2pManager:onconnecting":
- debug('onconnecting with peer: ' + JSON.stringify(msg.peer));
- this.currentPeer = msg.peer;
- this._fireStatusChangeEvent(msg.peer.address);
- break;
-
- case "WifiP2pManager:onconnected":
- debug('onconnected with peer: ' + JSON.stringify(msg.peer));
- this.currentPeer = msg.peer;
- this.groupOwner = new MozWifiP2pGroupOwner(msg.groupOwner);
- this._fireStatusChangeEvent(msg.peer.address);
- break;
-
- case "WifiP2pManager:ondisconnected":
- debug('ondisconnected with peer: ' + JSON.stringify(msg.peer));
- this.currentPeer = null;
- this.groupOwner = null;
- this._fireStatusChangeEvent(msg.peer.address);
- break;
-
- case "WifiP2pManager:onconnectingfailed":
- this._fireStatusChangeEvent(null);
- break;
-
- case "WifiP2pManager:onwpstimeout":
- this._fireStatusChangeEvent(null);
- break;
-
- case "WifiP2pManager:onwpsfail":
- this._fireStatusChangeEvent(null);
- break;
-
- case "WifiP2pManager:onpeerinfoupdate":
- this._firePeerInfoUpdateEvent();
- break;
- }
- },
-
- _firePeerInfoUpdateEvent: function PeerInfoUpdate() {
- let evt = new this._window.Event("peerinfoupdate");
- this.__DOM_IMPL__.dispatchEvent(evt);
- },
-
- _fireStatusChangeEvent: function WifiP2pStatusChange(peerAddress) {
- let evt = new this._window.MozWifiP2pStatusChangeEvent("statuschange",
- { peerAddress: peerAddress });
- this.__DOM_IMPL__.dispatchEvent(evt);
- },
-
- _fireEnabledOrDisabled: function enabledDisabled(enabled) {
- let evt = new this._window.Event(enabled ? "enabled" : "disabled");
- this.__DOM_IMPL__.dispatchEvent(evt);
- },
-
- //
- // WifiP2pManager.webidl implementation.
- //
-
- enableScan: function () {
- let request = this.createRequest();
- this._sendMessageForRequest("WifiP2pManager:enableScan", null, request);
- return request;
- },
-
- disableScan: function () {
- let request = this.createRequest();
- this._sendMessageForRequest("WifiP2pManager:disableScan", null, request);
- return request;
- },
-
- setScanEnabled: function(enabled) {
- let request = this.createRequest();
- this._sendMessageForRequest("WifiP2pManager:setScanEnabled", enabled, request);
- return request;
- },
-
- connect: function (address, wpsMethod, goIntent) {
- let request = this.createRequest();
- let connectionInfo = { address: address, wpsMethod: wpsMethod, goIntent: goIntent };
- this._sendMessageForRequest("WifiP2pManager:connect", connectionInfo, request);
- return request;
- },
-
- disconnect: function (address) {
- let request = this.createRequest();
- this._sendMessageForRequest("WifiP2pManager:disconnect", address, request);
- return request;
- },
-
- getPeerList: function () {
- let request = this.createRequest();
- this._sendMessageForRequest("WifiP2pManager:getPeerList", null, request);
- return request;
- },
-
- setPairingConfirmation: function (accepted, pin) {
- let request = this.createRequest();
- let result = { accepted: accepted, pin: pin };
- this._sendMessageForRequest("WifiP2pManager:setPairingConfirmation", result, request);
- return request;
- },
-
- setDeviceName: function(newDeviceName) {
- let request = this.createRequest();
- this._sendMessageForRequest("WifiP2pManager:setDeviceName", newDeviceName, request);
- return request;
- },
-
- // Helpers.
- defineEventHandlerGetterSetter: function(event) {
- Object.defineProperty(this, event, {
- get: function() {
- return this.__DOM_IMPL__.getEventHandler(event);
- },
-
- set: function(handler) {
- this.__DOM_IMPL__.setEventHandler(event, handler);
- }
- });
- },
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([MozWifiP2pManager, MozWifiP2pGroupOwner]);
diff --git a/dom/wifi/DOMWifiP2pManager.manifest b/dom/wifi/DOMWifiP2pManager.manifest
deleted file mode 100644
index bc80efa48..000000000
--- a/dom/wifi/DOMWifiP2pManager.manifest
+++ /dev/null
@@ -1,6 +0,0 @@
-# DOMWifiP2pManager.js
-component {8d9125a0-3498-11e3-aa6e-0800200c9a66} DOMWifiP2pManager.js
-contract @mozilla.org/wifip2pmanager;1 {8d9125a0-3498-11e3-aa6e-0800200c9a66}
-
-component {a9b81450-349d-11e3-aa6e-0800200c9a66} DOMWifiP2pManager.js
-contract @mozilla.org/wifip2pgroupowner;1 {a9b81450-349d-11e3-aa6e-0800200c9a66} \ No newline at end of file
diff --git a/dom/wifi/StateMachine.jsm b/dom/wifi/StateMachine.jsm
deleted file mode 100644
index 94b876f82..000000000
--- a/dom/wifi/StateMachine.jsm
+++ /dev/null
@@ -1,205 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/Services.jsm");
-
-this.EXPORTED_SYMBOLS = ["StateMachine"];
-
-const DEBUG = false;
-
-this.StateMachine = function(aDebugTag) {
- function debug(aMsg) {
- dump('-------------- StateMachine:' + aDebugTag + ': ' + aMsg);
- }
-
- var sm = {};
-
- var _initialState;
- var _curState;
- var _prevState;
- var _paused;
- var _eventQueue = [];
- var _deferredEventQueue = [];
- var _defaultEventHandler;
-
- // Public interfaces.
-
- sm.setDefaultEventHandler = function(aDefaultEventHandler) {
- _defaultEventHandler = aDefaultEventHandler;
- };
-
- sm.start = function(aInitialState) {
- _initialState = aInitialState;
- sm.gotoState(_initialState);
- };
-
- sm.sendEvent = function (aEvent) {
- if (!_initialState) {
- if (DEBUG) {
- debug('StateMachine is not running. Call StateMachine.start() first.');
- }
- return;
- }
- _eventQueue.push(aEvent);
- asyncCall(handleFirstEvent);
- };
-
- sm.getPreviousState = function() {
- return _prevState;
- };
-
- sm.getCurrentState = function() {
- return _curState;
- };
-
- // State object maker.
- // @param aName string for this state's name.
- // @param aDelegate object:
- // .handleEvent: required.
- // .enter: called before entering this state (optional).
- // .exit: called before exiting this state (optional).
- sm.makeState = function (aName, aDelegate) {
- if (!aDelegate.handleEvent) {
- throw "handleEvent is a required delegate function.";
- }
- var nop = function() {};
- return {
- name: aName,
- enter: (aDelegate.enter || nop),
- exit: (aDelegate.exit || nop),
- handleEvent: aDelegate.handleEvent
- };
- };
-
- sm.deferEvent = function (aEvent) {
- // The definition of a 'deferred event' is:
- // We are not able to handle this event now but after receiving
- // certain event or entering a new state, we might be able to handle
- // it. For example, we couldn't handle CONNECT_EVENT in the
- // diconnecting state. But once we finish doing "disconnecting", we
- // could then handle CONNECT_EVENT!
- //
- // So, the deferred event may be handled in the following cases:
- // 1. Once we entered a new state.
- // 2. Once we handled a regular event.
- if (DEBUG) {
- debug('Deferring event: ' + JSON.stringify(aEvent));
- }
- _deferredEventQueue.push(aEvent);
- };
-
- // Goto the new state. If the current state is null, the exit
- // function won't be called.
- sm.gotoState = function (aNewState) {
- if (_curState) {
- if (DEBUG) {
- debug("exiting state: " + _curState.name);
- }
- _curState.exit();
- }
-
- _prevState = _curState;
- _curState = aNewState;
-
- if (DEBUG) {
- debug("entering state: " + _curState.name);
- }
- _curState.enter();
-
- // We are in the new state now. We got a chance to handle the
- // deferred events.
- handleDeferredEvents();
-
- sm.resume();
- };
-
- // No incoming event will be handled after you call pause().
- // (But they will be queued.)
- sm.pause = function() {
- _paused = true;
- };
-
- // Continue to handle incoming events.
- sm.resume = function() {
- _paused = false;
- asyncCall(handleFirstEvent);
- };
-
- //----------------------------------------------------------
- // Private stuff
- //----------------------------------------------------------
-
- function asyncCall(f) {
- Services.tm.currentThread.dispatch(f, Ci.nsIThread.DISPATCH_NORMAL);
- }
-
- function handleFirstEvent() {
- var hadDeferredEvents;
-
- if (0 === _eventQueue.length) {
- return;
- }
-
- if (_paused) {
- return; // The state machine is paused now.
- }
-
- hadDeferredEvents = _deferredEventQueue.length > 0;
-
- handleOneEvent(_eventQueue.shift()); // The handler may defer this event.
-
- // We've handled one event. If we had deferred events before, now is
- // a good chance to handle them.
- if (hadDeferredEvents) {
- handleDeferredEvents();
- }
-
- // Continue to handle the next regular event.
- handleFirstEvent();
- }
-
- function handleDeferredEvents() {
- if (_deferredEventQueue.length && DEBUG) {
- debug('Handle deferred events: ' + _deferredEventQueue.length);
- }
- for (let i = 0; i < _deferredEventQueue.length; i++) {
- handleOneEvent(_deferredEventQueue.shift());
- }
- }
-
- function handleOneEvent(aEvent)
- {
- if (DEBUG) {
- debug('Handling event: ' + JSON.stringify(aEvent));
- }
-
- var handled = _curState.handleEvent(aEvent);
-
- if (undefined === handled) {
- throw "handleEvent returns undefined: " + _curState.name;
- }
- if (!handled) {
- // Event is not handled in the current state. Try handleEventCommon().
- handled = (_defaultEventHandler ? _defaultEventHandler(aEvent) : handled);
- }
- if (undefined === handled) {
- throw "handleEventCommon returns undefined: " + _curState.name;
- }
- if (!handled) {
- if (DEBUG) {
- debug('!!!!!!!!! FIXME !!!!!!!!! Event not handled: ' + JSON.stringify(aEvent));
- }
- }
-
- return handled;
- }
-
- return sm;
-};
diff --git a/dom/wifi/WifiCertService.cpp b/dom/wifi/WifiCertService.cpp
deleted file mode 100644
index 85e0d2f5b..000000000
--- a/dom/wifi/WifiCertService.cpp
+++ /dev/null
@@ -1,536 +0,0 @@
-/* -*- 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 "WifiCertService.h"
-
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/EndianUtils.h"
-#include "mozilla/ModuleUtils.h"
-#include "mozilla/RefPtr.h"
-#include "mozilla/dom/File.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "cert.h"
-#include "certdb.h"
-#include "CryptoTask.h"
-#include "nsIDOMBlob.h"
-#include "nsIWifiService.h"
-#include "nsNetUtil.h"
-#include "nsIInputStream.h"
-#include "nsServiceManagerUtils.h"
-#include "nsXULAppAPI.h"
-#include "ScopedNSSTypes.h"
-
-#define NS_WIFICERTSERVICE_CID \
- { 0x83585afd, 0x0e11, 0x43aa, {0x83, 0x46, 0xf3, 0x4d, 0x97, 0x5e, 0x46, 0x77} }
-
-using namespace mozilla;
-using namespace mozilla::dom;
-
-namespace mozilla {
-
-// The singleton Wifi Cert service, to be used on the main thread.
-StaticRefPtr<WifiCertService> gWifiCertService;
-
-class ImportCertTask final: public CryptoTask
-{
-public:
- ImportCertTask(int32_t aId, Blob* aCertBlob,
- const nsAString& aCertPassword,
- const nsAString& aCertNickname)
- : mBlob(aCertBlob)
- , mPassword(aCertPassword)
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- mResult.mId = aId;
- mResult.mStatus = 0;
- mResult.mUsageFlag = 0;
- mResult.mNickname = aCertNickname;
- }
-
-private:
- virtual void ReleaseNSSResources() {}
-
- virtual nsresult CalculateResult() override
- {
- MOZ_ASSERT(!NS_IsMainThread());
-
- // read data from blob.
- nsCString blobBuf;
- nsresult rv = ReadBlob(blobBuf);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- char* buf;
- uint32_t size = blobBuf.GetMutableData(&buf);
- if (size == 0) {
- return NS_ERROR_OUT_OF_MEMORY;
- }
-
- // Try import as DER format first.
- rv = ImportDERBlob(buf, size);
- if (NS_SUCCEEDED(rv)) {
- return rv;
- }
-
- // Try import as PKCS#12 format.
- return ImportPKCS12Blob(buf, size, mPassword);
- }
-
- virtual void CallCallback(nsresult rv)
- {
- if (NS_FAILED(rv)) {
- mResult.mStatus = -1;
- }
- gWifiCertService->DispatchResult(mResult);
- }
-
- nsresult ImportDERBlob(char* buf, uint32_t size)
- {
- // Create certificate object.
- ScopedCERTCertificate cert(CERT_DecodeCertFromPackage(buf, size));
- if (!cert) {
- return MapSECStatus(SECFailure);
- }
-
- // Import certificate.
- return ImportCert(cert);
- }
-
- static SECItem*
- HandleNicknameCollision(SECItem* aOldNickname, PRBool* aCancel, void* aWincx)
- {
- const char* dummyName = "Imported User Cert";
- const size_t dummyNameLen = strlen(dummyName);
- SECItem* newNick = ::SECITEM_AllocItem(nullptr, nullptr, dummyNameLen + 1);
- if (!newNick) {
- return nullptr;
- }
-
- newNick->type = siAsciiString;
- // Dummy name, will be renamed later.
- memcpy(newNick->data, dummyName, dummyNameLen + 1);
- newNick->len = dummyNameLen;
-
- return newNick;
- }
-
- static SECStatus
- HandleNicknameUpdate(const CERTCertificate *aCert,
- const SECItem *default_nickname,
- SECItem **new_nickname,
- void *arg)
- {
- WifiCertServiceResultOptions *result = (WifiCertServiceResultOptions *)arg;
-
- nsCString userNickname;
- CopyUTF16toUTF8(result->mNickname, userNickname);
-
- nsCString fullNickname;
- if (aCert->isRoot && (aCert->nsCertType & NS_CERT_TYPE_SSL_CA)) {
- // Accept self-signed SSL CA as server certificate.
- fullNickname.AssignLiteral("WIFI_SERVERCERT_");
- fullNickname += userNickname;
- result->mUsageFlag |= nsIWifiCertService::WIFI_CERT_USAGE_FLAG_SERVER;
- } else if (aCert->nsCertType & NS_CERT_TYPE_SSL_CLIENT) {
- // User Certificate
- fullNickname.AssignLiteral("WIFI_USERCERT_");
- fullNickname += userNickname;
- result->mUsageFlag |= nsIWifiCertService::WIFI_CERT_USAGE_FLAG_USER;
- }
- char* nickname;
- uint32_t length = fullNickname.GetMutableData(&nickname);
-
- SECItem* newNick = ::SECITEM_AllocItem(nullptr, nullptr, length + 1);
- if (!newNick) {
- return SECFailure;
- }
-
- newNick->type = siAsciiString;
- memcpy(newNick->data, nickname, length + 1);
- newNick->len = length;
-
- *new_nickname = newNick;
- return SECSuccess;
- }
-
- nsresult ImportPKCS12Blob(char* buf, uint32_t size, const nsAString& aPassword)
- {
- nsString password(aPassword);
-
- // password is null-terminated wide-char string.
- // passwordItem is required to be big-endian form of password, stored in char
- // array, including the null-termination.
- uint32_t length = password.Length() + 1;
- ScopedSECItem passwordItem(
- ::SECITEM_AllocItem(nullptr, nullptr, length * sizeof(nsString::char_type)));
-
- if (!passwordItem) {
- return NS_ERROR_FAILURE;
- }
-
- mozilla::NativeEndian::copyAndSwapToBigEndian(passwordItem->data,
- password.BeginReading(),
- length);
- // Create a decoder.
- ScopedSEC_PKCS12DecoderContext p12dcx(SEC_PKCS12DecoderStart(
- passwordItem, nullptr, nullptr,
- nullptr, nullptr, nullptr, nullptr,
- nullptr));
-
- if (!p12dcx) {
- return NS_ERROR_FAILURE;
- }
-
- // Assign data to decorder.
- SECStatus srv = SEC_PKCS12DecoderUpdate(p12dcx,
- reinterpret_cast<unsigned char*>(buf),
- size);
- if (srv != SECSuccess) {
- return MapSECStatus(srv);
- }
-
- // Verify certificates.
- srv = SEC_PKCS12DecoderVerify(p12dcx);
- if (srv != SECSuccess) {
- return MapSECStatus(srv);
- }
-
- // Set certificate nickname and usage flag.
- srv = SEC_PKCS12DecoderRenameCertNicknames(p12dcx, HandleNicknameUpdate,
- &mResult);
-
- // Validate certificates.
- srv = SEC_PKCS12DecoderValidateBags(p12dcx, HandleNicknameCollision);
- if (srv != SECSuccess) {
- return MapSECStatus(srv);
- }
-
- // Initialize slot.
- ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
- if (!slot) {
- return NS_ERROR_FAILURE;
- }
- if (PK11_NeedLogin(slot) && PK11_NeedUserInit(slot)) {
- srv = PK11_InitPin(slot, "", "");
- if (srv != SECSuccess) {
- return MapSECStatus(srv);
- }
- }
-
- // Import cert and key.
- srv = SEC_PKCS12DecoderImportBags(p12dcx);
- if (srv != SECSuccess) {
- return MapSECStatus(srv);
- }
-
- // User certificate must be imported from PKCS#12.
- return (mResult.mUsageFlag & nsIWifiCertService::WIFI_CERT_USAGE_FLAG_USER)
- ? NS_OK : NS_ERROR_FAILURE;
- }
-
- nsresult ReadBlob(/*out*/ nsCString& aBuf)
- {
- NS_ENSURE_ARG_POINTER(mBlob);
-
- static const uint64_t MAX_FILE_SIZE = 16384;
-
- ErrorResult rv;
- uint64_t size = mBlob->GetSize(rv);
- if (NS_WARN_IF(rv.Failed())) {
- return rv.StealNSResult();
- }
-
- if (size > MAX_FILE_SIZE) {
- return NS_ERROR_FILE_TOO_BIG;
- }
-
- nsCOMPtr<nsIInputStream> inputStream;
- mBlob->GetInternalStream(getter_AddRefs(inputStream), rv);
- if (NS_WARN_IF(rv.Failed())) {
- return rv.StealNSResult();
- }
-
- rv = NS_ReadInputStreamToString(inputStream, aBuf, (uint32_t)size);
- if (NS_WARN_IF(rv.Failed())) {
- return rv.StealNSResult();
- }
-
- return NS_OK;
- }
-
- nsresult ImportCert(CERTCertificate* aCert)
- {
- nsCString userNickname, fullNickname;
-
- CopyUTF16toUTF8(mResult.mNickname, userNickname);
- // Determine certificate nickname by adding prefix according to its type.
- if (aCert->isRoot && (aCert->nsCertType & NS_CERT_TYPE_SSL_CA)) {
- // Accept self-signed SSL CA as server certificate.
- fullNickname.AssignLiteral("WIFI_SERVERCERT_");
- fullNickname += userNickname;
- mResult.mUsageFlag |= nsIWifiCertService::WIFI_CERT_USAGE_FLAG_SERVER;
- } else if (aCert->nsCertType & NS_CERT_TYPE_SSL_CLIENT) {
- // User Certificate
- fullNickname.AssignLiteral("WIFI_USERCERT_");
- fullNickname += userNickname;
- mResult.mUsageFlag |= nsIWifiCertService::WIFI_CERT_USAGE_FLAG_USER;
- } else {
- return NS_ERROR_ABORT;
- }
-
- char* nickname;
- uint32_t length;
- length = fullNickname.GetMutableData(&nickname);
- if (length == 0) {
- return NS_ERROR_UNEXPECTED;
- }
-
- // Import certificate, duplicated nickname will cause error.
- SECStatus srv = CERT_AddTempCertToPerm(aCert, nickname, nullptr);
- if (srv != SECSuccess) {
- return MapSECStatus(srv);
- }
-
- return NS_OK;
- }
-
- RefPtr<Blob> mBlob;
- nsString mPassword;
- WifiCertServiceResultOptions mResult;
-};
-
-class DeleteCertTask final: public CryptoTask
-{
-public:
- DeleteCertTask(int32_t aId, const nsAString& aCertNickname)
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- mResult.mId = aId;
- mResult.mStatus = 0;
- mResult.mUsageFlag = 0;
- mResult.mNickname = aCertNickname;
- }
-
-private:
- virtual void ReleaseNSSResources() {}
-
- virtual nsresult CalculateResult() override
- {
- MOZ_ASSERT(!NS_IsMainThread());
-
- nsCString userNickname;
- CopyUTF16toUTF8(mResult.mNickname, userNickname);
-
- // Delete server certificate.
- nsCString serverCertName("WIFI_SERVERCERT_", 16);
- serverCertName += userNickname;
- nsresult rv = deleteCert(serverCertName);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- // Delete user certificate and private key.
- nsCString userCertName("WIFI_USERCERT_", 14);
- userCertName += userNickname;
- rv = deleteCert(userCertName);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- return NS_OK;
- }
-
- nsresult deleteCert(const nsCString &aCertNickname)
- {
- ScopedCERTCertificate cert(
- CERT_FindCertByNickname(CERT_GetDefaultCertDB(), aCertNickname.get())
- );
- // Because we delete certificates in blind, so it's acceptable to delete
- // a non-exist certificate.
- if (!cert) {
- return NS_OK;
- }
-
- ScopedPK11SlotInfo slot(
- PK11_KeyForCertExists(cert, nullptr, nullptr)
- );
-
- SECStatus srv;
- if (slot) {
- // Delete private key along with certificate.
- srv = PK11_DeleteTokenCertAndKey(cert, nullptr);
- } else {
- srv = SEC_DeletePermCertificate(cert);
- }
-
- if (srv != SECSuccess) {
- return MapSECStatus(srv);
- }
-
- return NS_OK;
- }
-
- virtual void CallCallback(nsresult rv)
- {
- if (NS_FAILED(rv)) {
- mResult.mStatus = -1;
- }
- gWifiCertService->DispatchResult(mResult);
- }
-
- WifiCertServiceResultOptions mResult;
-};
-
-NS_IMPL_ISUPPORTS(WifiCertService, nsIWifiCertService)
-
-NS_IMETHODIMP
-WifiCertService::Start(nsIWifiEventListener* aListener)
-{
- MOZ_ASSERT(aListener);
-
- mListener = aListener;
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-WifiCertService::Shutdown()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- mListener = nullptr;
-
- return NS_OK;
-}
-
-void
-WifiCertService::DispatchResult(const WifiCertServiceResultOptions& aOptions)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- mozilla::AutoSafeJSContext cx;
- JS::RootedValue val(cx);
- nsCString dummyInterface;
-
- if (!ToJSValue(cx, aOptions, &val)) {
- return;
- }
-
- // Certll the listener with a JS value.
- mListener->OnCommand(val, dummyInterface);
-}
-
-WifiCertService::WifiCertService()
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!gWifiCertService);
-}
-
-WifiCertService::~WifiCertService()
-{
- MOZ_ASSERT(!gWifiCertService);
-
- nsNSSShutDownPreventionLock locker;
- if (isAlreadyShutDown()) {
- return;
- }
- shutdown(ShutdownCalledFrom::Object);
-}
-
-already_AddRefed<WifiCertService>
-WifiCertService::FactoryCreate()
-{
- if (!XRE_IsParentProcess()) {
- return nullptr;
- }
-
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!gWifiCertService) {
- gWifiCertService = new WifiCertService();
- ClearOnShutdown(&gWifiCertService);
- }
-
- RefPtr<WifiCertService> service = gWifiCertService.get();
- return service.forget();
-}
-
-NS_IMETHODIMP
-WifiCertService::ImportCert(int32_t aId, nsIDOMBlob* aCertBlob,
- const nsAString& aCertPassword,
- const nsAString& aCertNickname)
-{
- RefPtr<Blob> blob = static_cast<Blob*>(aCertBlob);
- RefPtr<CryptoTask> task = new ImportCertTask(aId, blob, aCertPassword,
- aCertNickname);
- return task->Dispatch("WifiImportCert");
-}
-
-NS_IMETHODIMP
-WifiCertService::DeleteCert(int32_t aId, const nsAString& aCertNickname)
-{
- RefPtr<CryptoTask> task = new DeleteCertTask(aId, aCertNickname);
- return task->Dispatch("WifiDeleteCert");
-}
-
-NS_IMETHODIMP
-WifiCertService::HasPrivateKey(const nsAString& aCertNickname, bool *aHasKey)
-{
- *aHasKey = false;
-
- nsNSSShutDownPreventionLock locker;
- if (isAlreadyShutDown()) {
- return NS_ERROR_NOT_AVAILABLE;
- }
-
- nsCString certNickname;
- CopyUTF16toUTF8(aCertNickname, certNickname);
-
- ScopedCERTCertificate cert(
- CERT_FindCertByNickname(CERT_GetDefaultCertDB(), certNickname.get())
- );
- if (!cert) {
- return NS_OK;
- }
-
- ScopedPK11SlotInfo slot(
- PK11_KeyForCertExists(cert, nullptr, nullptr)
- );
- if (slot) {
- *aHasKey = true;
- }
-
- return NS_OK;
-}
-
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(WifiCertService,
- WifiCertService::FactoryCreate)
-
-NS_DEFINE_NAMED_CID(NS_WIFICERTSERVICE_CID);
-
-static const mozilla::Module::CIDEntry kWifiCertServiceCIDs[] = {
- { &kNS_WIFICERTSERVICE_CID, false, nullptr, WifiCertServiceConstructor },
- { nullptr }
-};
-
-static const mozilla::Module::ContractIDEntry kWifiCertServiceContracts[] = {
- { "@mozilla.org/wifi/certservice;1", &kNS_WIFICERTSERVICE_CID },
- { nullptr }
-};
-
-static const mozilla::Module kWifiCertServiceModule = {
- mozilla::Module::kVersion,
- kWifiCertServiceCIDs,
- kWifiCertServiceContracts,
- nullptr
-};
-
-} // namespace mozilla
-
-NSMODULE_DEFN(WifiCertServiceModule) = &kWifiCertServiceModule;
diff --git a/dom/wifi/WifiCertService.h b/dom/wifi/WifiCertService.h
deleted file mode 100644
index f542bb0c8..000000000
--- a/dom/wifi/WifiCertService.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/* -*- 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 WifiCertService_h
-#define WifiCertService_h
-
-#include "nsIWifiCertService.h"
-#include "nsCOMPtr.h"
-#include "nsNSSShutDown.h"
-#include "nsThread.h"
-#include "mozilla/dom/WifiOptionsBinding.h"
-
-namespace mozilla {
-namespace dom {
-
-class WifiCertService final : public nsIWifiCertService,
- public nsNSSShutDownObject
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIWIFICERTSERVICE
-
- static already_AddRefed<WifiCertService>
- FactoryCreate();
- void DispatchResult(const mozilla::dom::WifiCertServiceResultOptions& aOptions);
-
-private:
- WifiCertService();
- ~WifiCertService();
- virtual void virtualDestroyNSSReference() {};
- nsCOMPtr<nsIWifiEventListener> mListener;
-};
-
-} // namespce dom
-} // namespace mozilla
-
-#endif // WifiCertService_h
diff --git a/dom/wifi/WifiCommand.jsm b/dom/wifi/WifiCommand.jsm
deleted file mode 100644
index 93b0f1a1e..000000000
--- a/dom/wifi/WifiCommand.jsm
+++ /dev/null
@@ -1,594 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = ["WifiCommand"];
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/systemlibs.js");
-
-const SUPP_PROP = "init.svc.wpa_supplicant";
-const WPA_SUPPLICANT = "wpa_supplicant";
-const DEBUG = false;
-
-this.WifiCommand = function(aControlMessage, aInterface, aSdkVersion) {
- function debug(msg) {
- if (DEBUG) {
- dump('-------------- WifiCommand: ' + msg);
- }
- }
-
- var command = {};
-
- //-------------------------------------------------
- // Utilities.
- //-------------------------------------------------
- command.getSdkVersion = function() {
- return aSdkVersion;
- };
-
- //-------------------------------------------------
- // General commands.
- //-------------------------------------------------
-
- command.loadDriver = function (callback) {
- voidControlMessage("load_driver", function(status) {
- callback(status);
- });
- };
-
- command.unloadDriver = function (callback) {
- voidControlMessage("unload_driver", function(status) {
- callback(status);
- });
- };
-
- command.startSupplicant = function (callback) {
- voidControlMessage("start_supplicant", callback);
- };
-
- command.killSupplicant = function (callback) {
- // It is interesting to note that this function does exactly what
- // wifi_stop_supplicant does. Unforunately, on the Galaxy S2, Samsung
- // changed that function in a way that means that it doesn't recognize
- // wpa_supplicant as already running. Therefore, we have to roll our own
- // version here.
- stopProcess(SUPP_PROP, WPA_SUPPLICANT, callback);
- };
-
- command.terminateSupplicant = function (callback) {
- doBooleanCommand("TERMINATE", "OK", callback);
- };
-
- command.stopSupplicant = function (callback) {
- voidControlMessage("stop_supplicant", callback);
- };
-
- command.listNetworks = function (callback) {
- doStringCommand("LIST_NETWORKS", callback);
- };
-
- command.addNetwork = function (callback) {
- doIntCommand("ADD_NETWORK", callback);
- };
-
- command.setNetworkVariable = function (netId, name, value, callback) {
- doBooleanCommand("SET_NETWORK " + netId + " " + name + " " +
- value, "OK", callback);
- };
-
- command.getNetworkVariable = function (netId, name, callback) {
- doStringCommand("GET_NETWORK " + netId + " " + name, callback);
- };
-
- command.removeNetwork = function (netId, callback) {
- doBooleanCommand("REMOVE_NETWORK " + netId, "OK", callback);
- };
-
- command.enableNetwork = function (netId, disableOthers, callback) {
- doBooleanCommand((disableOthers ? "SELECT_NETWORK " : "ENABLE_NETWORK ") +
- netId, "OK", callback);
- };
-
- command.disableNetwork = function (netId, callback) {
- doBooleanCommand("DISABLE_NETWORK " + netId, "OK", callback);
- };
-
- command.status = function (callback) {
- doStringCommand("STATUS", callback);
- };
-
- command.ping = function (callback) {
- doBooleanCommand("PING", "PONG", callback);
- };
-
- command.scanResults = function (callback) {
- doStringCommand("SCAN_RESULTS", callback);
- };
-
- command.disconnect = function (callback) {
- doBooleanCommand("DISCONNECT", "OK", callback);
- };
-
- command.reconnect = function (callback) {
- doBooleanCommand("RECONNECT", "OK", callback);
- };
-
- command.reassociate = function (callback) {
- doBooleanCommand("REASSOCIATE", "OK", callback);
- };
-
- command.setBackgroundScan = function (enable, callback) {
- doBooleanCommand("SET pno " + (enable ? "1" : "0"),
- "OK",
- function(ok) {
- callback(true, ok);
- });
- };
-
- command.doSetScanMode = function (setActive, callback) {
- doBooleanCommand(setActive ?
- "DRIVER SCAN-ACTIVE" :
- "DRIVER SCAN-PASSIVE", "OK", callback);
- };
-
- command.scan = function (callback) {
- doBooleanCommand("SCAN", "OK", callback);
- };
-
- command.setLogLevel = function (level, callback) {
- doBooleanCommand("LOG_LEVEL " + level, "OK", callback);
- };
-
- command.getLogLevel = function (callback) {
- doStringCommand("LOG_LEVEL", callback);
- };
-
- command.wpsPbc = function (callback, iface) {
- let cmd = 'WPS_PBC';
-
- // If the network interface is specified and we are based on JB,
- // append the argument 'interface=[iface]' to the supplicant command.
- //
- // Note: The argument "interface" is only required for wifi p2p on JB.
- // For other cases, the argument is useless and even leads error.
- // Check the evil work here:
- // http://androidxref.com/4.2.2_r1/xref/external/wpa_supplicant_8/wpa_supplicant/ctrl_iface_unix.c#172
- //
- if (iface && isJellybean()) {
- cmd += (' inferface=' + iface);
- }
-
- doBooleanCommand(cmd, "OK", callback);
- };
-
- command.wpsPin = function (detail, callback) {
- let cmd = 'WPS_PIN ';
-
- // See the comment above in wpsPbc().
- if (detail.iface && isJellybean()) {
- cmd += ('inferface=' + iface + ' ');
- }
-
- cmd += (detail.bssid === undefined ? "any" : detail.bssid);
- cmd += (detail.pin === undefined ? "" : (" " + detail.pin));
-
- doStringCommand(cmd, callback);
- };
-
- command.wpsCancel = function (callback) {
- doBooleanCommand("WPS_CANCEL", "OK", callback);
- };
-
- command.startDriver = function (callback) {
- doBooleanCommand("DRIVER START", "OK");
- };
-
- command.stopDriver = function (callback) {
- doBooleanCommand("DRIVER STOP", "OK");
- };
-
- command.startPacketFiltering = function (callback) {
- var commandChain = ["DRIVER RXFILTER-ADD 0",
- "DRIVER RXFILTER-ADD 1",
- "DRIVER RXFILTER-ADD 3",
- "DRIVER RXFILTER-START"];
-
- doBooleanCommandChain(commandChain, callback);
- };
-
- command.stopPacketFiltering = function (callback) {
- var commandChain = ["DRIVER RXFILTER-STOP",
- "DRIVER RXFILTER-REMOVE 3",
- "DRIVER RXFILTER-REMOVE 1",
- "DRIVER RXFILTER-REMOVE 0"];
-
- doBooleanCommandChain(commandChain, callback);
- };
-
- command.doGetRssi = function (cmd, callback) {
- doCommand(cmd, function(data) {
- var rssi = -200;
-
- if (!data.status) {
- // If we are associating, the reply is "OK".
- var reply = data.reply;
- if (reply !== "OK") {
- // Format is: <SSID> rssi XX". SSID can contain spaces.
- var offset = reply.lastIndexOf("rssi ");
- if (offset !== -1) {
- rssi = reply.substr(offset + 5) | 0;
- }
- }
- }
- callback(rssi);
- });
- };
-
- command.getRssi = function (callback) {
- command.doGetRssi("DRIVER RSSI", callback);
- };
-
- command.getRssiApprox = function (callback) {
- command.doGetRssi("DRIVER RSSI-APPROX", callback);
- };
-
- command.getLinkSpeed = function (callback) {
- doStringCommand("DRIVER LINKSPEED", function(reply) {
- if (reply) {
- reply = reply.split(" ")[1] | 0; // Format: LinkSpeed XX
- }
- callback(reply);
- });
- };
-
- let infoKeys = [{regexp: /RSSI=/i, prop: 'rssi'},
- {regexp: /LINKSPEED=/i, prop: 'linkspeed'}];
-
- command.getConnectionInfoICS = function (callback) {
- doStringCommand("SIGNAL_POLL", function(reply) {
- if (!reply) {
- callback(null);
- return;
- }
-
- // Find any values matching |infoKeys|. This gets executed frequently
- // enough that we want to avoid creating intermediate strings as much as
- // possible.
- let rval = {};
- for (let i = 0; i < infoKeys.length; i++) {
- let re = infoKeys[i].regexp;
- let iKeyStart = reply.search(re);
- if (iKeyStart !== -1) {
- let prop = infoKeys[i].prop;
- let iValueStart = reply.indexOf('=', iKeyStart) + 1;
- let iNewlineAfterValue = reply.indexOf('\n', iValueStart);
- let iValueEnd = iNewlineAfterValue !== -1
- ? iNewlineAfterValue
- : reply.length;
- rval[prop] = reply.substring(iValueStart, iValueEnd) | 0;
- }
- }
-
- callback(rval);
- });
- };
-
- command.getMacAddress = function (callback) {
- doStringCommand("DRIVER MACADDR", function(reply) {
- if (reply) {
- reply = reply.split(" ")[2]; // Format: Macaddr = XX.XX.XX.XX.XX.XX
- }
- callback(reply);
- });
- };
-
- command.connectToHostapd = function(callback) {
- voidControlMessage("connect_to_hostapd", callback);
- };
-
- command.closeHostapdConnection = function(callback) {
- voidControlMessage("close_hostapd_connection", callback);
- };
-
- command.hostapdCommand = function (callback, request) {
- var msg = { cmd: "hostapd_command",
- request: request,
- iface: aInterface };
-
- aControlMessage(msg, function(data) {
- callback(data.status ? null : data.reply);
- });
- };
-
- command.hostapdGetStations = function (callback) {
- var msg = { cmd: "hostapd_get_stations",
- iface: aInterface };
-
- aControlMessage(msg, function(data) {
- callback(data.status);
- });
- };
-
- command.setPowerModeICS = function (mode, callback) {
- doBooleanCommand("DRIVER POWERMODE " + (mode === "AUTO" ? 0 : 1), "OK", callback);
- };
-
- command.setPowerModeJB = function (mode, callback) {
- doBooleanCommand("SET ps " + (mode === "AUTO" ? 1 : 0), "OK", callback);
- };
-
- command.getPowerMode = function (callback) {
- doStringCommand("DRIVER GETPOWER", function(reply) {
- if (reply) {
- reply = (reply.split()[2]|0); // Format: powermode = XX
- }
- callback(reply);
- });
- };
-
- command.setNumAllowedChannels = function (numChannels, callback) {
- doBooleanCommand("DRIVER SCAN-CHANNELS " + numChannels, "OK", callback);
- };
-
- command.getNumAllowedChannels = function (callback) {
- doStringCommand("DRIVER SCAN-CHANNELS", function(reply) {
- if (reply) {
- reply = (reply.split()[2]|0); // Format: Scan-Channels = X
- }
- callback(reply);
- });
- };
-
- command.setBluetoothCoexistenceMode = function (mode, callback) {
- doBooleanCommand("DRIVER BTCOEXMODE " + mode, "OK", callback);
- };
-
- command.setBluetoothCoexistenceScanMode = function (mode, callback) {
- doBooleanCommand("DRIVER BTCOEXSCAN-" + (mode ? "START" : "STOP"),
- "OK", callback);
- };
-
- command.saveConfig = function (callback) {
- // Make sure we never write out a value for AP_SCAN other than 1.
- doBooleanCommand("AP_SCAN 1", "OK", function(ok) {
- doBooleanCommand("SAVE_CONFIG", "OK", callback);
- });
- };
-
- command.reloadConfig = function (callback) {
- doBooleanCommand("RECONFIGURE", "OK", callback);
- };
-
- command.setScanResultHandling = function (mode, callback) {
- doBooleanCommand("AP_SCAN " + mode, "OK", callback);
- };
-
- command.addToBlacklist = function (bssid, callback) {
- doBooleanCommand("BLACKLIST " + bssid, "OK", callback);
- };
-
- command.clearBlacklist = function (callback) {
- doBooleanCommand("BLACKLIST clear", "OK", callback);
- };
-
- command.setSuspendOptimizationsICS = function (enabled, callback) {
- doBooleanCommand("DRIVER SETSUSPENDOPT " + (enabled ? 0 : 1),
- "OK", callback);
- };
-
- command.setSuspendOptimizationsJB = function (enabled, callback) {
- doBooleanCommand("DRIVER SETSUSPENDMODE " + (enabled ? 1 : 0),
- "OK", callback);
- };
-
- command.connectToSupplicant = function(callback) {
- voidControlMessage("connect_to_supplicant", callback);
- };
-
- command.closeSupplicantConnection = function(callback) {
- voidControlMessage("close_supplicant_connection", callback);
- };
-
- command.getMacAddress = function(callback) {
- doStringCommand("DRIVER MACADDR", function(reply) {
- if (reply) {
- reply = reply.split(" ")[2]; // Format: Macaddr = XX.XX.XX.XX.XX.XX
- }
- callback(reply);
- });
- };
-
- command.setDeviceName = function(deviceName, callback) {
- doBooleanCommand("SET device_name " + deviceName, "OK", callback);
- };
-
- //-------------------------------------------------
- // P2P commands.
- //-------------------------------------------------
-
- command.p2pProvDiscovery = function(address, wpsMethod, callback) {
- var command = "P2P_PROV_DISC " + address + " " + wpsMethod;
- doBooleanCommand(command, "OK", callback);
- };
-
- command.p2pConnect = function(config, callback) {
- var command = "P2P_CONNECT " + config.address + " " + config.wpsMethodWithPin + " ";
- if (config.joinExistingGroup) {
- command += "join";
- } else {
- command += "go_intent=" + config.goIntent;
- }
-
- debug('P2P connect command: ' + command);
- doBooleanCommand(command, "OK", callback);
- };
-
- command.p2pGroupRemove = function(iface, callback) {
- debug("groupRemove()");
- doBooleanCommand("P2P_GROUP_REMOVE " + iface, "OK", callback);
- };
-
- command.p2pEnable = function(detail, callback) {
- var commandChain = ["SET device_name " + detail.deviceName,
- "SET device_type " + detail.deviceType,
- "SET config_methods " + detail.wpsMethods,
- "P2P_SET conc_pref sta",
- "P2P_FLUSH"];
-
- doBooleanCommandChain(commandChain, callback);
- };
-
- command.p2pDisable = function(callback) {
- doBooleanCommand("P2P_SET disabled 1", "OK", callback);
- };
-
- command.p2pEnableScan = function(timeout, callback) {
- doBooleanCommand("P2P_FIND " + timeout, "OK", callback);
- };
-
- command.p2pDisableScan = function(callback) {
- doBooleanCommand("P2P_STOP_FIND", "OK", callback);
- };
-
- command.p2pGetGroupCapab = function(address, callback) {
- command.p2pPeer(address, function(reply) {
- debug('p2p_peer reply: ' + reply);
- if (!reply) {
- callback(0);
- return;
- }
- var capab = /group_capab=0x([0-9a-fA-F]+)/.exec(reply)[1];
- if (!capab) {
- callback(0);
- } else {
- callback(parseInt(capab, 16));
- }
- });
- };
-
- command.p2pPeer = function(address, callback) {
- doStringCommand("P2P_PEER " + address, callback);
- };
-
- command.p2pGroupAdd = function(netId, callback) {
- doBooleanCommand("P2P_GROUP_ADD persistent=" + netId, callback);
- };
-
- command.p2pReinvoke = function(netId, address, callback) {
- doBooleanCommand("P2P_INVITE persistent=" + netId + " peer=" + address, "OK", callback);
- };
-
- //----------------------------------------------------------
- // Private stuff.
- //----------------------------------------------------------
-
- function voidControlMessage(cmd, callback) {
- aControlMessage({ cmd: cmd, iface: aInterface }, function (data) {
- callback(data.status);
- });
- }
-
- function doCommand(request, callback) {
- var msg = { cmd: "command",
- request: request,
- iface: aInterface };
-
- aControlMessage(msg, callback);
- }
-
- function doIntCommand(request, callback) {
- doCommand(request, function(data) {
- callback(data.status ? -1 : (data.reply|0));
- });
- }
-
- function doBooleanCommand(request, expected, callback) {
- doCommand(request, function(data) {
- callback(data.status ? false : (data.reply === expected));
- });
- }
-
- function doStringCommand(request, callback) {
- doCommand(request, function(data) {
- callback(data.status ? null : data.reply);
- });
- }
-
- function doBooleanCommandChain(commandChain, callback, i) {
- if (undefined === i) {
- i = 0;
- }
-
- doBooleanCommand(commandChain[i], "OK", function(ok) {
- if (!ok) {
- return callback(false);
- }
- i++;
- if (i === commandChain.length || !commandChain[i]) {
- // Reach the end or empty command.
- return callback(true);
- }
- doBooleanCommandChain(commandChain, callback, i);
- });
- }
-
- //--------------------------------------------------
- // Helper functions.
- //--------------------------------------------------
-
- function stopProcess(service, process, callback) {
- var count = 0;
- var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- function tick() {
- let result = libcutils.property_get(service);
- if (result === null) {
- callback();
- return;
- }
- if (result === "stopped" || ++count >= 5) {
- // Either we succeeded or ran out of time.
- timer = null;
- callback();
- return;
- }
-
- // Else it's still running, continue waiting.
- timer.initWithCallback(tick, 1000, Ci.nsITimer.TYPE_ONE_SHOT);
- }
-
- setProperty("ctl.stop", process, tick);
- }
-
- // Wrapper around libcutils.property_set that returns true if setting the
- // value was successful.
- // Note that the callback is not called asynchronously.
- function setProperty(key, value, callback) {
- let ok = true;
- try {
- libcutils.property_set(key, value);
- } catch(e) {
- ok = false;
- }
- callback(ok);
- }
-
- function isJellybean() {
- // According to http://developer.android.com/guide/topics/manifest/uses-sdk-element.html
- // ----------------------------------------------------
- // | Platform Version | API Level | VERSION_CODE |
- // ----------------------------------------------------
- // | Android 4.1, 4.1.1 | 16 | JELLY_BEAN_MR2 |
- // | Android 4.2, 4.2.2 | 17 | JELLY_BEAN_MR1 |
- // | Android 4.3 | 18 | JELLY_BEAN |
- // ----------------------------------------------------
- return aSdkVersion === 16 || aSdkVersion === 17 || aSdkVersion === 18;
- }
-
- return command;
-};
diff --git a/dom/wifi/WifiHotspotUtils.cpp b/dom/wifi/WifiHotspotUtils.cpp
deleted file mode 100644
index 5fdb9b76e..000000000
--- a/dom/wifi/WifiHotspotUtils.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/* -*- 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 "WifiHotspotUtils.h"
-#include <dlfcn.h>
-#include <errno.h>
-#include <string.h>
-#include <dirent.h>
-#include <stdlib.h>
-#include <cutils/properties.h>
-
-#include "prinit.h"
-#include "mozilla/Assertions.h"
-#include "mozilla/Sprintf.h"
-#include "nsDebug.h"
-#include "nsPrintfCString.h"
-
-static void* sWifiHotspotUtilsLib;
-static PRCallOnceType sInitWifiHotspotUtilsLib;
-// Socket pair used to exit from a blocking read.
-static struct wpa_ctrl* ctrl_conn;
-static const char *ctrl_iface_dir = "/data/misc/wifi/hostapd";
-static char *ctrl_ifname = nullptr;
-
-DEFINE_DLFUNC(wpa_ctrl_open, struct wpa_ctrl*, const char*)
-DEFINE_DLFUNC(wpa_ctrl_close, void, struct wpa_ctrl*)
-DEFINE_DLFUNC(wpa_ctrl_attach, int32_t, struct wpa_ctrl*)
-DEFINE_DLFUNC(wpa_ctrl_detach, int32_t, struct wpa_ctrl*)
-DEFINE_DLFUNC(wpa_ctrl_request, int32_t, struct wpa_ctrl*,
- const char*, size_t cmd_len, char *reply,
- size_t *reply_len, void (*msg_cb)(char *msg, size_t len))
-
-
-static PRStatus
-InitWifiHotspotUtilsLib()
-{
- sWifiHotspotUtilsLib = dlopen("/system/lib/libwpa_client.so", RTLD_LAZY);
- // We might fail to open the hardware lib. That's OK.
- return PR_SUCCESS;
-}
-
-static void*
-GetWifiHotspotLibHandle()
-{
- PR_CallOnce(&sInitWifiHotspotUtilsLib, InitWifiHotspotUtilsLib);
- return sWifiHotspotUtilsLib;
-}
-
-struct wpa_ctrl *
-WifiHotspotUtils::openConnection(const char *ifname)
-{
- if (!ifname) {
- return nullptr;
- }
-
- USE_DLFUNC(wpa_ctrl_open)
- ctrl_conn = wpa_ctrl_open(nsPrintfCString("%s/%s", ctrl_iface_dir, ifname).get());
- return ctrl_conn;
-}
-
-int32_t
-WifiHotspotUtils::sendCommand(struct wpa_ctrl *ctrl, const char *cmd,
- char *reply, size_t *reply_len)
-{
- int32_t ret;
-
- if (!ctrl_conn) {
- NS_WARNING(nsPrintfCString("Not connected to hostapd - \"%s\" command dropped.\n", cmd).get());
- return -1;
- }
-
- USE_DLFUNC(wpa_ctrl_request)
- ret = wpa_ctrl_request(ctrl, cmd, strlen(cmd), reply, reply_len, nullptr);
- if (ret == -2) {
- NS_WARNING(nsPrintfCString("'%s' command timed out.\n", cmd).get());
- return -2;
- } else if (ret < 0 || strncmp(reply, "FAIL", 4) == 0) {
- return -1;
- }
-
- // Make the reply printable.
- reply[*reply_len] = '\0';
- if (strncmp(cmd, "STA-FIRST", 9) == 0 ||
- strncmp(cmd, "STA-NEXT", 8) == 0) {
- char *pos = reply;
-
- while (*pos && *pos != '\n')
- pos++;
- *pos = '\0';
- }
-
- return 0;
-}
-
-
-// static
-void*
-WifiHotspotUtils::GetSharedLibrary()
-{
- void* wpaClientLib = GetWifiHotspotLibHandle();
- if (!wpaClientLib) {
- NS_WARNING("No /system/lib/libwpa_client.so");
- }
- return wpaClientLib;
-}
-
-int32_t WifiHotspotUtils::do_wifi_connect_to_hostapd()
-{
- struct dirent *dent;
-
- DIR *dir = opendir(ctrl_iface_dir);
- if (dir) {
- while ((dent = readdir(dir))) {
- if (strcmp(dent->d_name, ".") == 0 ||
- strcmp(dent->d_name, "..") == 0) {
- continue;
- }
- ctrl_ifname = strdup(dent->d_name);
- break;
- }
- closedir(dir);
- }
-
- ctrl_conn = openConnection(ctrl_ifname);
- if (!ctrl_conn) {
- NS_WARNING(nsPrintfCString("Unable to open connection to hostapd on \"%s\": %s",
- ctrl_ifname, strerror(errno)).get());
- return -1;
- }
-
- USE_DLFUNC(wpa_ctrl_attach)
- if (wpa_ctrl_attach(ctrl_conn) != 0) {
- USE_DLFUNC(wpa_ctrl_close)
- wpa_ctrl_close(ctrl_conn);
- ctrl_conn = nullptr;
- return -1;
- }
-
- return 0;
-}
-
-int32_t WifiHotspotUtils::do_wifi_close_hostapd_connection()
-{
- if (!ctrl_conn) {
- NS_WARNING("Invalid ctrl_conn.");
- return -1;
- }
-
- USE_DLFUNC(wpa_ctrl_detach)
- if (wpa_ctrl_detach(ctrl_conn) < 0) {
- NS_WARNING("Failed to detach wpa_ctrl.");
- }
-
- USE_DLFUNC(wpa_ctrl_close)
- wpa_ctrl_close(ctrl_conn);
- ctrl_conn = nullptr;
- return 0;
-}
-
-int32_t WifiHotspotUtils::do_wifi_hostapd_command(const char *command,
- char *reply,
- size_t *reply_len)
-{
- return sendCommand(ctrl_conn, command, reply, reply_len);
-}
-
-int32_t WifiHotspotUtils::do_wifi_hostapd_get_stations()
-{
- char addr[32], cmd[64];
- int stations = 0;
- size_t addrLen = sizeof(addr);
-
- if (sendCommand(ctrl_conn, "STA-FIRST", addr, &addrLen)) {
- return 0;
- }
- stations++;
-
- SprintfLiteral(cmd, "STA-NEXT %s", addr);
- while (sendCommand(ctrl_conn, cmd, addr, &addrLen) == 0) {
- stations++;
- SprintfLiteral(cmd, "STA-NEXT %s", addr);
- }
-
- return stations;
-}
diff --git a/dom/wifi/WifiHotspotUtils.h b/dom/wifi/WifiHotspotUtils.h
deleted file mode 100644
index 7afdec7da..000000000
--- a/dom/wifi/WifiHotspotUtils.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* -*- 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/. */
-
-/**
- * Abstraction on top of the network support from libnetutils that we
- * use to set up network connections.
- */
-
-#ifndef WifiHotspotUtils_h
-#define WifiHotspotUtils_h
-
-// Forward declaration.
-struct wpa_ctrl;
-
-class WifiHotspotUtils
-{
-public:
- static void* GetSharedLibrary();
-
- int32_t do_wifi_connect_to_hostapd();
- int32_t do_wifi_close_hostapd_connection();
- int32_t do_wifi_hostapd_command(const char *command,
- char *reply,
- size_t *reply_len);
- int32_t do_wifi_hostapd_get_stations();
-
-private:
- struct wpa_ctrl * openConnection(const char *ifname);
- int32_t sendCommand(struct wpa_ctrl *ctrl, const char *cmd,
- char *reply, size_t *reply_len);
-};
-
-// Defines a function type with the right arguments and return type.
-#define DEFINE_DLFUNC(name, ret, args...) typedef ret (*FUNC##name)(args);
-
-// Set up a dlsymed function ready to use.
-#define USE_DLFUNC(name) \
- FUNC##name name = (FUNC##name) dlsym(GetSharedLibrary(), #name); \
- if (!name) { \
- MOZ_CRASH("Symbol not found in shared library : " #name); \
- }
-
-#endif // WifiHotspotUtils_h
diff --git a/dom/wifi/WifiNetUtil.jsm b/dom/wifi/WifiNetUtil.jsm
deleted file mode 100644
index 2a1866515..000000000
--- a/dom/wifi/WifiNetUtil.jsm
+++ /dev/null
@@ -1,154 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkService",
- "@mozilla.org/network/service;1",
- "nsINetworkService");
-
-this.EXPORTED_SYMBOLS = ["WifiNetUtil"];
-
-const DHCP_PROP = "init.svc.dhcpcd";
-const DHCP = "dhcpcd";
-const DEBUG = false;
-
-this.WifiNetUtil = function(controlMessage) {
- function debug(msg) {
- if (DEBUG) {
- dump('-------------- NetUtil: ' + msg);
- }
- }
-
- var util = {};
-
- util.runDhcp = function (ifname, gen, callback) {
- util.stopDhcp(ifname, function() {
- gNetworkService.dhcpRequest(ifname, function(success, dhcpInfo) {
- util.runIpConfig(ifname, dhcpInfo, function(data) {
- callback(data, gen);
- });
- });
- });
- };
-
- util.stopDhcp = function (ifname, callback) {
- // This function does exactly what dhcp_stop does. Unforunately, if we call
- // this function twice before the previous callback is returned. We may block
- // our self waiting for the callback. It slows down the wifi startup procedure.
- // Therefore, we have to roll our own version here.
- let dhcpService = DHCP_PROP + "_" + ifname;
- let suffix = (ifname.substr(0, 3) === "p2p") ? "p2p" : ifname;
- let processName = DHCP + "_" + suffix;
-
- // The implementation of |dhcp_do_request| would wait until the
- // |result_prop_name| (e.g. dhcp.wlan0.result) to be non-null
- // or 30 second timeout. So we manually change the result property
- // to 'ko' to avoid timeout.
- //
- // http://androidxref.com/4.4.4_r1/xref/system/core/libnetutils/dhcp_utils.c#234
- setProperty('dhcp.' + suffix + '.result', 'ko', function() {
- stopProcess(dhcpService, processName, callback);
- });
- };
-
- util.startDhcpServer = function (config, callback) {
- gNetworkService.setDhcpServer(true, config, function (error) {
- callback(!error);
- });
- };
-
- util.stopDhcpServer = function (callback) {
- gNetworkService.setDhcpServer(false, null, function (error) {
- callback(!error);
- });
- };
-
- util.runIpConfig = function (name, data, callback) {
- if (!data) {
- debug("IP config failed to run");
- callback({ info: data });
- return;
- }
-
- setProperty("net." + name + ".dns1", ipToString(data.dns1),
- function(ok) {
- if (!ok) {
- debug("Unable to set net.<ifname>.dns1");
- return;
- }
- setProperty("net." + name + ".dns2", ipToString(data.dns2),
- function(ok) {
- if (!ok) {
- debug("Unable to set net.<ifname>.dns2");
- return;
- }
- setProperty("net." + name + ".gw", ipToString(data.gateway),
- function(ok) {
- if (!ok) {
- debug("Unable to set net.<ifname>.gw");
- return;
- }
- callback({ info: data });
- });
- });
- });
- };
-
- //--------------------------------------------------
- // Helper functions.
- //--------------------------------------------------
-
- function stopProcess(service, process, callback) {
- var count = 0;
- var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- function tick() {
- let result = libcutils.property_get(service);
- if (result === null) {
- callback();
- return;
- }
- if (result === "stopped" || ++count >= 5) {
- // Either we succeeded or ran out of time.
- timer = null;
- callback();
- return;
- }
-
- // Else it's still running, continue waiting.
- timer.initWithCallback(tick, 1000, Ci.nsITimer.TYPE_ONE_SHOT);
- }
-
- setProperty("ctl.stop", process, tick);
- }
-
- // Wrapper around libcutils.property_set that returns true if setting the
- // value was successful.
- // Note that the callback is not called asynchronously.
- function setProperty(key, value, callback) {
- let ok = true;
- try {
- libcutils.property_set(key, value);
- } catch(e) {
- ok = false;
- }
- callback(ok);
- }
-
- function ipToString(n) {
- return String((n >> 0) & 0xFF) + "." +
- ((n >> 8) & 0xFF) + "." +
- ((n >> 16) & 0xFF) + "." +
- ((n >> 24) & 0xFF);
- }
-
- return util;
-};
diff --git a/dom/wifi/WifiP2pManager.jsm b/dom/wifi/WifiP2pManager.jsm
deleted file mode 100644
index c1b687438..000000000
--- a/dom/wifi/WifiP2pManager.jsm
+++ /dev/null
@@ -1,1649 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/StateMachine.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSysMsgr",
- "@mozilla.org/system-message-internal;1",
- "nsISystemMessagesInternal");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
- "@mozilla.org/network/manager;1",
- "nsINetworkManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkService",
- "@mozilla.org/network/service;1",
- "nsINetworkService");
-
-this.EXPORTED_SYMBOLS = ["WifiP2pManager"];
-
-const EVENT_IGNORED = -1;
-const EVENT_UNKNOWN = -2;
-
-// Events from supplicant for p2p.
-const EVENT_P2P_DEVICE_FOUND = 0;
-const EVENT_P2P_DEVICE_LOST = 1;
-const EVENT_P2P_GROUP_STARTED = 2;
-const EVENT_P2P_GROUP_REMOVED = 3;
-const EVENT_P2P_PROV_DISC_PBC_REQ = 4;
-const EVENT_P2P_PROV_DISC_PBC_RESP = 5;
-const EVENT_P2P_PROV_DISC_SHOW_PIN = 6;
-const EVENT_P2P_PROV_DISC_ENTER_PIN = 7;
-const EVENT_P2P_GO_NEG_REQUEST = 8;
-const EVENT_P2P_GO_NEG_SUCCESS = 9;
-const EVENT_P2P_GO_NEG_FAILURE = 10;
-const EVENT_P2P_GROUP_FORMATION_SUCCESS = 11;
-const EVENT_P2P_GROUP_FORMATION_FAILURE = 12;
-const EVENT_P2P_FIND_STOPPED = 13;
-const EVENT_P2P_INVITATION_RESULT = 14;
-const EVENT_P2P_INVITATION_RECEIVED = 15;
-const EVENT_P2P_PROV_DISC_FAILURE = 16;
-
-// Events from supplicant but not p2p specific.
-const EVENT_AP_STA_DISCONNECTED = 100;
-const EVENT_AP_STA_CONNECTED = 101;
-
-// Events from DOM.
-const EVENT_P2P_SET_PAIRING_CONFIRMATION = 1000;
-const EVENT_P2P_CMD_CONNECT = 1001;
-const EVENT_P2P_CMD_DISCONNECT = 1002;
-const EVENT_P2P_CMD_ENABLE = 1003;
-const EVENT_P2P_CMD_DISABLE = 1004;
-const EVENT_P2P_CMD_ENABLE_SCAN = 1005;
-const EVENT_P2P_CMD_DISABLE_SCAN = 1006;
-const EVENT_P2P_CMD_BLOCK_SCAN = 1007;
-const EVENT_P2P_CMD_UNBLOCK_SCAN = 1008;
-
-// Internal events.
-const EVENT_TIMEOUT_PAIRING_CONFIRMATION = 10000;
-const EVENT_TIMEOUT_NEG_REQ = 10001;
-const EVENT_TIMEOUT_CONNECTING = 10002;
-const EVENT_P2P_ENABLE_SUCCESS = 10003;
-const EVENT_P2P_ENABLE_FAILED = 10004;
-const EVENT_P2P_DISABLE_SUCCESS = 10005;
-
-// WPS method string.
-const WPS_METHOD_PBC = "pbc";
-const WPS_METHOD_DISPLAY = "display";
-const WPS_METHOD_KEYPAD = "keypad";
-
-// Role string.
-const P2P_ROLE_GO = "GO";
-const P2P_ROLE_CLIENT = "client";
-
-// System message for pairing request.
-const PAIRING_REQUEST_SYS_MSG = "wifip2p-pairing-request";
-
-// Configuration.
-const P2P_INTERFACE_NAME = "p2p0";
-const DEFAULT_GO_INTENT = 15;
-const DEFAULT_P2P_DEVICE_NAME = "FirefoxPhone";
-const P2P_SCAN_TIMEOUT_SEC = 120;
-const DEFAULT_P2P_WPS_METHODS = "virtual_push_button physical_display keypad"; // For wpa_supplicant.
-const DEFAULT_P2P_DEVICE_TYPE = "10-0050F204-5"; // For wpa_supplicant.
-
-const GO_NETWORK_INTERFACE = {
- ip: "192.168.2.1",
- maskLength: 24,
- gateway: "192.168.2.1",
- dns1: "0.0.0.0",
- dns2: "0.0.0.0",
- dhcpServer: "192.168.2.1"
-};
-
-const GO_DHCP_SERVER_IP_RANGE = {
- startIp: "192.168.2.10",
- endIp: "192.168.2.30"
-};
-
-var gDebug = false;
-
-// Device Capability bitmap
-const DEVICE_CAPAB_SERVICE_DISCOVERY = 1;
-const DEVICE_CAPAB_CLIENT_DISCOVERABILITY = 1<<1;
-const DEVICE_CAPAB_CONCURRENT_OPER = 1<<2;
-const DEVICE_CAPAB_INFRA_MANAGED = 1<<3;
-const DEVICE_CAPAB_DEVICE_LIMIT = 1<<4;
-const DEVICE_CAPAB_INVITATION_PROCEDURE = 1<<5;
-
-// Group Capability bitmap
-const GROUP_CAPAB_GROUP_OWNER = 1;
-const GROUP_CAPAB_PERSISTENT_GROUP = 1<<1;
-const GROUP_CAPAB_GROUP_LIMIT = 1<<2;
-const GROUP_CAPAB_INTRA_BSS_DIST = 1<<3;
-const GROUP_CAPAB_CROSS_CONN = 1<<4;
-const GROUP_CAPAB_PERSISTENT_RECONN = 1<<5;
-const GROUP_CAPAB_GROUP_FORMATION = 1<<6;
-
-// Constants defined in wpa_supplicants.
-const DEV_PW_REGISTRAR_SPECIFIED = 5;
-const DEV_PW_USER_SPECIFIED = 1;
-const DEV_PW_PUSHBUTTON = 4;
-
-this.WifiP2pManager = function (aP2pCommand, aNetUtil) {
- function debug(aMsg) {
- if (gDebug) {
- dump('-------------- WifiP2pManager: ' + aMsg);
- }
- }
-
- let manager = {};
-
- let _stateMachine = P2pStateMachine(aP2pCommand, aNetUtil);
-
- // Set debug flag to true or false.
- //
- // @param aDebug Boolean to indicate enabling or disabling the debug flag.
- manager.setDebug = function(aDebug) {
- gDebug = aDebug;
- };
-
- // Set observer of observing internal state machine events.
- //
- // @param aObserver Used to notify WifiWorker what's happening
- // in the internal p2p state machine.
- manager.setObserver = function(aObserver) {
- _stateMachine.setObserver(aObserver);
- };
-
- // Handle wpa_supplicant events.
- //
- // @param aEventString string from wpa_supplicant.
- manager.handleEvent = function(aEventString) {
- let event = parseEventString(aEventString);
- if (EVENT_UNKNOWN === event.id || EVENT_IGNORED === event.id) {
- debug('Unknow or ignored event: ' + aEventString);
- return false;
- }
- return _stateMachine.sendEvent(event);
- };
-
- // Set the confirmation of pairing request.
- //
- // @param aResult Object of confirmation result which contains:
- // .accepted: user granted.
- // .pin: pin code which is displaying or input by user.
- // .wpsMethod: string of "pbc" or "display" or "keypad".
- manager.setPairingConfirmation = function(aResult) {
- let event = {
- id: EVENT_P2P_SET_PAIRING_CONFIRMATION,
- info: {
- accepted: aResult.accepted,
- pin: aResult.pin
- }
- };
- _stateMachine.sendEvent(event);
- };
-
- // Connect to a known peer.
- //
- // @param aAddress MAC address of the peer to connect.
- // @param aWpsMethod String of "pbc" or "display" or "keypad".
- // @param aGoIntent Number from 0 to 15.
- // @param aCallback Callback |true| on attempting to connect.
- // |false| on failed to connect.
- manager.connect = function(aAddress, aWpsMethod, aGoIntent, aCallback) {
- let event = {
- id: EVENT_P2P_CMD_CONNECT,
- info: {
- wpsMethod: aWpsMethod,
- address: aAddress,
- goIntent: aGoIntent,
- onDoConnect: aCallback
- }
- };
- _stateMachine.sendEvent(event);
- };
-
- // Disconnect with a known peer.
- //
- // @param aAddress The address the user desires to disconect.
- // @param aCallback Callback |true| on "attempting" to disconnect.
- // |false| on failed to disconnect.
- manager.disconnect = function(aAddress, aCallback) {
- let event = {
- id: EVENT_P2P_CMD_DISCONNECT,
- info: {
- address: aAddress,
- onDoDisconnect: aCallback
- }
- };
- _stateMachine.sendEvent(event);
- };
-
- // Enable/disable wifi p2p.
- //
- // @param aEnabled |true| to enable, |false| to disable.
- // @param aCallbacks object for callbacks:
- // .onEnabled
- // .onDisabled
- // .onSupplicantConnected
- manager.setEnabled = function(aEnabled, aCallbacks) {
- let event = {
- id: (aEnabled ? EVENT_P2P_CMD_ENABLE : EVENT_P2P_CMD_DISABLE),
- info: {
- onEnabled: aCallbacks.onEnabled,
- onDisabled: aCallbacks.onDisabled,
- onSupplicantConnected: aCallbacks.onSupplicantConnected
- }
- };
- _stateMachine.sendEvent(event);
- };
-
- // Enable/disable the wifi p2p scan.
- //
- // @param aEnabled |true| to enable scan, |false| to disable scan.
- // @param aCallback Callback |true| on success to enable/disable scan.
- // |false| on failed to enable/disable scan.
- manager.setScanEnabled = function(aEnabled, aCallback) {
- let event = {
- id: (aEnabled ? EVENT_P2P_CMD_ENABLE_SCAN : EVENT_P2P_CMD_DISABLE_SCAN),
- info: { callback: aCallback }
- };
- _stateMachine.sendEvent(event);
- };
-
- // Block wifi p2p scan.
- manager.blockScan = function() {
- _stateMachine.sendEvent({ id: EVENT_P2P_CMD_BLOCK_SCAN });
- };
-
- // Un-block and do the pending scan if any.
- manager.unblockScan = function() {
- _stateMachine.sendEvent({ id: EVENT_P2P_CMD_UNBLOCK_SCAN });
- };
-
- // Set the p2p device name.
- manager.setDeviceName = function(newDeivceName, callback) {
- aP2pCommand.setDeviceName(newDeivceName, callback);
- };
-
- // Parse wps_supplicant event string.
- //
- // @param aEventString The raw event string from wpa_supplicant.
- //
- // @return Object:
- // .id: a number to represent an event.
- // .info: the additional information carried by this event string.
- function parseEventString(aEventString) {
- if (isIgnoredEvent(aEventString)) {
- return { id: EVENT_IGNORED };
- }
-
- let match = RegExp("p2p_dev_addr=([0-9a-fA-F:]+) " +
- "pri_dev_type=([0-9a-zA-Z-]+) " +
- "name='(.*)' " +
- "config_methods=0x([0-9a-fA-F]+) " +
- "dev_capab=0x([0-9a-fA-F]+) " +
- "group_capab=0x([0-9a-fA-F]+) ").exec(aEventString + ' ');
-
- let tokens = aEventString.split(" ");
-
- let id = EVENT_UNKNOWN;
-
- // general info.
- let info = {};
-
- if (match) {
- info = {
- address: match[1] ? match[1] : null,
- type: match[2] ? match[2] : null,
- name: match[3] ? match[3] : null,
- wpsFlag: match[4] ? parseInt(match[4], 16) : null,
- devFlag: match[5] ? parseInt(match[5], 16) : null,
- groupFlag: match[6] ? parseInt(match[6], 16) : null
- };
- }
-
- if (0 === aEventString.indexOf("P2P-DEVICE-FOUND")) {
- id = EVENT_P2P_DEVICE_FOUND;
- info.wpsCapabilities = wpsFlagToCapabilities(info.wpsFlag);
- info.isGroupOwner = isPeerGroupOwner(info.groupFlag);
- } else if (0 === aEventString.indexOf("P2P-DEVICE-LOST")) {
- // e.g. "P2P-DEVICE-LOST p2p_dev_addr=5e:0a:5b:15:1f:80".
- id = EVENT_P2P_DEVICE_LOST;
- info.address = /p2p_dev_addr=([0-9a-f:]+)/.exec(aEventString)[1];
- } else if (0 === aEventString.indexOf("P2P-GROUP-STARTED")) {
- // e.g. "P2P-GROUP-STARTED wlan0-p2p-0 GO ssid="DIRECT-3F Testing
- // passphrase="12345678" go_dev_addr=02:40:61:c2:f3:b7 [PERSISTENT]".
-
- id = EVENT_P2P_GROUP_STARTED;
- let groupMatch = RegExp('ssid="(.*)" ' +
- 'freq=([0-9]*) ' +
- '(passphrase|psk)=([^ ]+) ' +
- 'go_dev_addr=([0-9a-f:]+)').exec(aEventString);
- info.ssid = groupMatch[1];
- info.freq = groupMatch[2];
- if ('passphrase' === groupMatch[3]) {
- let s = groupMatch[4]; // e.g. "G7jHkkz9".
- info.passphrase = s.substring(1, s.length-1); // Trim the double quote.
- } else { // psk
- info.psk = groupMatch[4];
- }
- info.goAddress = groupMatch[5];
- info.ifname = tokens[1];
- info.role = tokens[2];
- } else if (0 === aEventString.indexOf("P2P-GROUP-REMOVED")) {
- id = EVENT_P2P_GROUP_REMOVED;
- // e.g. "P2P-GROUP-REMOVED wlan0-p2p-0 GO".
- info.ifname = tokens[1];
- info.role = tokens[2];
- } else if (0 === aEventString.indexOf("P2P-PROV-DISC-PBC-REQ")) {
- id = EVENT_P2P_PROV_DISC_PBC_REQ;
- info.wpsMethod = WPS_METHOD_PBC;
- } else if (0 === aEventString.indexOf("P2P-PROV-DISC-PBC-RESP")) {
- id = EVENT_P2P_PROV_DISC_PBC_RESP;
- // The address is different from the general pattern.
- info.address = aEventString.split(" ")[1];
- info.wpsMethod = WPS_METHOD_PBC;
- } else if (0 === aEventString.indexOf("P2P-PROV-DISC-SHOW-PIN")) {
- id = EVENT_P2P_PROV_DISC_SHOW_PIN;
- // Obtain peer address and pin from tokens.
- info.address = tokens[1];
- info.pin = tokens[2];
- info.wpsMethod = WPS_METHOD_DISPLAY;
- } else if (0 === aEventString.indexOf("P2P-PROV-DISC-ENTER-PIN")) {
- id = EVENT_P2P_PROV_DISC_ENTER_PIN;
- // Obtain peer address from tokens.
- info.address = tokens[1];
- info.wpsMethod = WPS_METHOD_KEYPAD;
- } else if (0 === aEventString.indexOf("P2P-GO-NEG-REQUEST")) {
- id = EVENT_P2P_GO_NEG_REQUEST;
- info.address = tokens[1];
- switch (parseInt(tokens[2].split("=")[1], 10)) {
- case DEV_PW_REGISTRAR_SPECIFIED: // (5) Peer is display.
- info.wpsMethod = WPS_METHOD_KEYPAD;
- break;
- case DEV_PW_USER_SPECIFIED: // (1) Peer is keypad.
- info.wpsMethod = WPS_METHOD_DISPLAY;
- break;
- case DEV_PW_PUSHBUTTON: // (4) Peer is pbc.
- info.wpsMethod = WPS_METHOD_PBC;
- break;
- default:
- debug('Unknown wps method from event P2P-GO-NEG-REQUEST');
- break;
- }
- } else if (0 === aEventString.indexOf("P2P-GO-NEG-SUCCESS")) {
- id = EVENT_P2P_GO_NEG_SUCCESS;
- } else if (0 === aEventString.indexOf("P2P-GO-NEG-FAILURE")) {
- id = EVENT_P2P_GO_NEG_FAILURE;
- } else if (0 === aEventString.indexOf("P2P-GROUP-FORMATION-FAILURE")) {
- id = EVENT_P2P_GROUP_FORMATION_FAILURE;
- } else if (0 === aEventString.indexOf("P2P-GROUP-FORMATION-SUCCESS")) {
- id = EVENT_P2P_GROUP_FORMATION_SUCCESS;
- } else if (0 === aEventString.indexOf("P2P-FIND-STOPPED")) {
- id = EVENT_P2P_FIND_STOPPED;
- } else if (0 === aEventString.indexOf("P2P-INVITATION-RESULT")) {
- id = EVENT_P2P_INVITATION_RESULT;
- info.status = /status=([0-9]+)/.exec(aEventString)[1];
- } else if (0 === aEventString.indexOf("P2P-INVITATION-RECEIVED")) {
- // e.g. "P2P-INVITATION-RECEIVED sa=32:85:a9:da:e6:1f persistent=7".
- id = EVENT_P2P_INVITATION_RECEIVED;
- info.address = /sa=([0-9a-f:]+)/.exec(aEventString)[1];
- info.netId = /persistent=([0-9]+)/.exec(aEventString)[1];
- } else if (0 === aEventString.indexOf("P2P-PROV-DISC-FAILURE")) {
- id = EVENT_P2P_PROV_DISC_FAILURE;
- } else {
- // Not P2P event but we do receive it. Try to recognize it.
- if (0 === aEventString.indexOf("AP-STA-DISCONNECTED")) {
- id = EVENT_AP_STA_DISCONNECTED;
- info.address = tokens[1];
- } else if (0 === aEventString.indexOf("AP-STA-CONNECTED")) {
- id = EVENT_AP_STA_CONNECTED;
- info.address = tokens[1];
- } else {
- // Neither P2P event nor recognized supplicant event.
- debug('Unknwon event string: ' + aEventString);
- }
- }
-
- let event = {id: id, info: info};
- debug('Event parsing result: ' + aEventString + ": " + JSON.stringify(event));
-
- return event;
- }
-
- function isIgnoredEvent(aEventString) {
- const IGNORED_EVENTS = [
- "CTRL-EVENT-BSS-ADDED",
- "CTRL-EVENT-BSS-REMOVED",
- "CTRL-EVENT-SCAN-RESULTS",
- "CTRL-EVENT-STATE-CHANGE",
- "WPS-AP-AVAILABLE",
- "WPS-ENROLLEE-SEEN"
- ];
- for(let i = 0; i < IGNORED_EVENTS.length; i++) {
- if (0 === aEventString.indexOf(IGNORED_EVENTS[i])) {
- return true;
- }
- }
- return false;
- }
-
- function isPeerGroupOwner(aGroupFlag) {
- return (aGroupFlag & GROUP_CAPAB_GROUP_OWNER) !== 0;
- }
-
- // Convert flag to a wps capability array.
- //
- // @param aWpsFlag Number that represents the wps capabilities.
- // @return Array of WPS flag.
- function wpsFlagToCapabilities(aWpsFlag) {
- let wpsCapabilities = [];
- if (aWpsFlag & 0x8) {
- wpsCapabilities.push(WPS_METHOD_DISPLAY);
- }
- if (aWpsFlag & 0x80) {
- wpsCapabilities.push(WPS_METHOD_PBC);
- }
- if (aWpsFlag & 0x100) {
- wpsCapabilities.push(WPS_METHOD_KEYPAD);
- }
- return wpsCapabilities;
- }
-
- _stateMachine.start();
- return manager;
-};
-
-function P2pStateMachine(aP2pCommand, aNetUtil) {
- function debug(aMsg) {
- if (gDebug) {
- dump('-------------- WifiP2pStateMachine: ' + aMsg);
- }
- }
-
- let p2pSm = {}; // The state machine to return.
-
- let _sm = StateMachine('WIFIP2P'); // The general purpose state machine.
-
- // Information we need to keep track across states.
- let _observer;
-
- let _onEnabled;
- let _onDisabled;
- let _onSupplicantConnected;
- let _savedConfig = {}; // Configuration used to do P2P_CONNECT.
- let _groupInfo = {}; // The information of the group we have formed.
- let _removedGroupInfo = {}; // Used to store the group info we are going to remove.
-
- let _scanBlocked = false;
- let _scanPostponded = false;
-
- let _localDevice = {
- address: "",
- deviceName: DEFAULT_P2P_DEVICE_NAME + "_" + libcutils.property_get("ro.build.product"),
- wpsCapabilities: [WPS_METHOD_PBC, WPS_METHOD_KEYPAD, WPS_METHOD_DISPLAY]
- };
-
- let _p2pNetworkInterface = {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterface]),
-
- info: {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInfo]),
-
- state: Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED,
- type: Ci.nsINetworkInfo.NETWORK_TYPE_WIFI_P2P,
- name: P2P_INTERFACE_NAME,
- ips: [],
- prefixLengths: [],
- dnses: [],
- gateways: [],
-
- getAddresses: function (ips, prefixLengths) {
- ips.value = this.ips.slice();
- prefixLengths.value = this.prefixLengths.slice();
-
- return this.ips.length;
- },
-
- getGateways: function (count) {
- if (count) {
- count.value = this.gateways.length;
- }
- return this.gateways.slice();
- },
-
- getDnses: function (count) {
- if (count) {
- count.value = this.dnses.length;
- }
- return this.dnses.slice();
- }
- },
-
- httpProxyHost: null,
- httpProxyPort: null,
-
- // help
- registered: false
- };
-
- //---------------------------------------------------------
- // State machine APIs.
- //---------------------------------------------------------
-
- // Register the observer which is implemented in WifiP2pWorkerObserver.jsm.
- //
- // @param aObserver:
- // .onEnabled
- // .onDisbaled
- // .onPeerFound
- // .onPeerLost
- // .onConnecting
- // .onConnected
- // .onDisconnected
- // .onLocalDeviceChanged
- p2pSm.setObserver = function(aObserver) {
- _observer = aObserver;
- };
-
- p2pSm.start = function() {
- _sm.start(stateDisabled);
- };
-
- p2pSm.sendEvent = function(aEvent) {
- let willBeHandled = isInP2pManagedState(_sm.getCurrentState());
- _sm.sendEvent(aEvent);
- return willBeHandled;
- };
-
- // Initialize internal state machine _sm.
- _sm.setDefaultEventHandler(handleEventCommon);
-
- //----------------------------------------------------------
- // State definition.
- //----------------------------------------------------------
-
- // The initial state.
- var stateDisabled = _sm.makeState("DISABLED", {
- enter: function() {
- _onEnabled = null;
- _onSupplicantConnected = null;
- _savedConfig = null;
- _groupInfo = null;
- _removedGroupInfo = null;
- _scanBlocked = false;
- _scanPostponded = false;
-
- unregisterP2pNetworkInteface();
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_CMD_ENABLE:
- _onEnabled = aEvent.info.onEnabled;
- _onSupplicantConnected = aEvent.info.onSupplicantConnected;
- _sm.gotoState(stateEnabling);
- break;
-
- default:
- return false;
- } // End of switch.
- return true;
- }
- });
-
- // The state where we are trying to enable wifi p2p.
- var stateEnabling = _sm.makeState("ENABLING", {
- enter: function() {
-
- function onFailure()
- {
- _onEnabled(false);
- _observer.onDisabled();
- _sm.gotoState(stateDisabled);
- }
-
- function onSuccess()
- {
- _onEnabled(true);
- _observer.onEnabled();
- _sm.gotoState(stateInactive);
- }
-
- _sm.pause();
-
- // This function will only call back on success.
- function connectToSupplicantIfNeeded(callback) {
- if (aP2pCommand.getSdkVersion() >= 19) {
- // No need to connect to supplicant on KK. Call back directly.
- callback();
- return;
- }
- aP2pCommand.connectToSupplicant(function (status) {
- if (0 !== status) {
- debug('Failed to connect to p2p0');
- onFailure();
- return;
- }
- debug('wpa_supplicant p2p0 connected!');
- _onSupplicantConnected();
- callback();
- });
- }
-
- // Step 1: Connect to p2p0 if needed.
- connectToSupplicantIfNeeded(function callback () {
- let detail;
-
- // Step 2: Get MAC address.
- if (!_localDevice.address) {
- aP2pCommand.getMacAddress(function (address) {
- if (!address) {
- debug('Failed to get MAC address....');
- onFailure();
- return;
- }
- debug('Got mac address: ' + address);
- _localDevice.address = address;
- _observer.onLocalDeviceChanged(_localDevice);
- });
- }
-
- // Step 3: Enable p2p with the device name and wps methods.
- detail = { deviceName: _localDevice.deviceName,
- deviceType: libcutils.property_get("ro.moz.wifi.p2p_device_type") || DEFAULT_P2P_DEVICE_TYPE,
- wpsMethods: libcutils.property_get("ro.moz.wifi.p2p_wps_methods") || DEFAULT_P2P_WPS_METHODS };
-
- aP2pCommand.p2pEnable(detail, function (success) {
- if (!success) {
- debug('Failed to enable p2p');
- onFailure();
- return;
- }
-
- debug('P2P is enabled! Enabling net interface...');
-
- // Step 4: Enable p2p0 net interface. wpa_supplicant may have
- // already done it for us.
- gNetworkService.enableInterface(P2P_INTERFACE_NAME, function (success) {
- onSuccess();
- });
- });
- });
- },
-
- handleEvent: function(aEvent) {
- // We won't receive any event since all of them will be blocked.
- return true;
- }
- });
-
- // The state just after enabling wifi direct.
- var stateInactive = _sm.makeState("INACTIVE", {
- enter: function() {
- registerP2pNetworkInteface();
-
- if (_sm.getPreviousState() !== stateEnabling) {
- _observer.onDisconnected(_savedConfig);
- }
-
- _savedConfig = null; // Used to connect p2p peer.
- _groupInfo = null; // The information of the formed group.
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- // Receiving the following 3 states implies someone is trying to
- // connect to me.
- case EVENT_P2P_PROV_DISC_PBC_REQ:
- case EVENT_P2P_PROV_DISC_SHOW_PIN:
- case EVENT_P2P_PROV_DISC_ENTER_PIN:
- debug('Someone is trying to connect to me: ' + JSON.stringify(aEvent.info));
-
- _savedConfig = {
- name: aEvent.info.name,
- address: aEvent.info.address,
- wpsMethod: aEvent.info.wpsMethod,
- goIntent: DEFAULT_GO_INTENT,
- pin: aEvent.info.pin // EVENT_P2P_PROV_DISC_SHOW_PIN only.
- };
-
- _sm.gotoState(stateWaitingForConfirmation);
- break;
-
- // Connect to a peer.
- case EVENT_P2P_CMD_CONNECT:
- debug('Trying to connect to peer: ' + JSON.stringify(aEvent.info));
-
- _savedConfig = {
- address: aEvent.info.address,
- wpsMethod: aEvent.info.wpsMethod,
- goIntent: aEvent.info.goIntent
- };
-
- _sm.gotoState(stateProvisionDiscovery);
- aEvent.info.onDoConnect(true);
- break;
-
- case EVENT_P2P_INVITATION_RECEIVED:
- _savedConfig = {
- address: aEvent.info.address,
- wpsMethod: WPS_METHOD_PBC,
- goIntent: DEFAULT_GO_INTENT,
- netId: aEvent.info.netId
- };
- _sm.gotoState(stateWaitingForInvitationConfirmation);
- break;
-
- case EVENT_P2P_GROUP_STARTED:
- // Most likely the peer just reinvoked a peristen group and succeeeded.
-
- _savedConfig = { address: aEvent.info.goAddress };
-
- _sm.pause();
- handleGroupStarted(aEvent.info, function (success) {
- _sm.resume();
- });
- break;
-
- case EVENT_AP_STA_DISCONNECTED:
- // We will hit this case when we used to be a group owner and
- // requested to remove the group we owned.
- break;
-
- default:
- return false;
- } // End of switch.
- return true;
- },
- });
-
- // Waiting for user's confirmation.
- var stateWaitingForConfirmation = _sm.makeState("WAITING_FOR_CONFIRMATION", {
- timeoutTimer: null,
-
- enter: function() {
- gSysMsgr.broadcastMessage(PAIRING_REQUEST_SYS_MSG, _savedConfig);
- this.timeoutTimer = initTimeoutTimer(30000, EVENT_TIMEOUT_PAIRING_CONFIRMATION);
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_SET_PAIRING_CONFIRMATION:
- if (!aEvent.info.accepted) {
- debug('User rejected this request');
- _sm.gotoState(stateInactive); // Reset to inactive state.
- break;
- }
-
- debug('User accepted this request');
-
- // The only information we may have to grab from user.
- _savedConfig.pin = aEvent.info.pin;
-
- // The case that user requested to form a group ealier on.
- // Just go to connecting state and do p2p_connect.
- if (_sm.getPreviousState() === stateProvisionDiscovery) {
- _sm.gotoState(stateConnecting);
- break;
- }
-
- // Otherwise, wait for EVENT_P2P_GO_NEG_REQUEST.
- _sm.gotoState(stateWaitingForNegReq);
- break;
-
- case EVENT_TIMEOUT_PAIRING_CONFIRMATION:
- debug('Confirmation timeout!');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_P2P_GO_NEG_REQUEST:
- _sm.deferEvent(aEvent);
- break;
-
- default:
- return false;
- } // End of switch.
-
- return true;
- },
-
- exit: function() {
- this.timeoutTimer.cancel();
- this.timeoutTimer = null;
- }
- });
-
- var stateWaitingForNegReq = _sm.makeState("WAITING_FOR_NEG_REQ", {
- timeoutTimer: null,
-
- enter: function() {
- debug('Wait for EVENT_P2P_GO_NEG_REQUEST');
- this.timeoutTimer = initTimeoutTimer(30000, EVENT_TIMEOUT_NEG_REQ);
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_GO_NEG_REQUEST:
- if (aEvent.info.wpsMethod !== _savedConfig.wpsMethod) {
- debug('Unmatched wps method: ' + aEvent.info.wpsMethod + ", " + _savedConfig.wpsMetho);
- }
- _sm.gotoState(stateConnecting);
- break;
-
- case EVENT_TIMEOUT_NEG_REQ:
- debug("Waiting for NEG-REQ timeout");
- _sm.gotoState(stateInactive);
- break;
-
- default:
- return false;
- } // End of switch.
- return true;
- },
-
- exit: function() {
- this.timeoutTimer.cancel();
- this.timeoutTimer = null;
- }
- });
-
- // Waiting for user's confirmation for invitation.
- var stateWaitingForInvitationConfirmation = _sm.makeState("WAITING_FOR_INV_CONFIRMATION", {
- timeoutTimer: null,
-
- enter: function() {
- gSysMsgr.broadcastMessage(PAIRING_REQUEST_SYS_MSG, _savedConfig);
- this.timeoutTimer = initTimeoutTimer(30000, EVENT_TIMEOUT_PAIRING_CONFIRMATION);
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_SET_PAIRING_CONFIRMATION:
- if (!aEvent.info.accepted) {
- debug('User rejected this request');
- _sm.gotoState(stateInactive); // Reset to inactive state.
- break;
- }
-
- debug('User accepted this request');
- _sm.pause();
- aP2pCommand.p2pGetGroupCapab(_savedConfig.address, function (gc) {
- let isPeeGroupOwner = gc & GROUP_CAPAB_GROUP_OWNER;
- _sm.gotoState(isPeeGroupOwner ? stateGroupAdding : stateReinvoking);
- });
-
- break;
-
- case EVENT_TIMEOUT_PAIRING_CONFIRMATION:
- debug('Confirmation timeout!');
- _sm.gotoState(stateInactive);
- break;
-
- default:
- return false;
- } // End of switch.
-
- return true;
- },
-
- exit: function() {
- this.timeoutTimer.cancel();
- this.timeoutTimer = null;
- }
- });
-
- var stateGroupAdding = _sm.makeState("GROUP_ADDING", {
- timeoutTimer: null,
-
- enter: function() {
- let self = this;
-
- _observer.onConnecting(_savedConfig);
-
- _sm.pause();
- aP2pCommand.p2pGroupAdd(_savedConfig.netId, function (success) {
- if (!success) {
- _sm.gotoState(stateInactive);
- return;
- }
- // Waiting for EVENT_P2P_GROUP_STARTED.
- self.timeoutTimer = initTimeoutTimer(60000, EVENT_TIMEOUT_CONNECTING);
- _sm.resume();
- });
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_GROUP_STARTED:
- _sm.pause();
- handleGroupStarted(aEvent.info, function (success) {
- _sm.resume();
- });
- break;
-
- case EVENT_P2P_GO_NEG_FAILURE:
- debug('Negotiation failure. Go back to inactive state');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_TIMEOUT_CONNECTING:
- debug('Connecting timeout! Go back to inactive state');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_P2P_GROUP_FORMATION_SUCCESS:
- case EVENT_P2P_GO_NEG_SUCCESS:
- break;
-
- case EVENT_P2P_GROUP_FORMATION_FAILURE:
- debug('Group formation failure');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_P2P_GROUP_REMOVED:
- debug('Received P2P-GROUP-REMOVED due to previous failed handleGroupdStarted()');
- _removedGroupInfo = {
- role: aEvent.info.role,
- ifname: aEvent.info.ifname
- };
- _sm.gotoState(stateDisconnecting);
- break;
-
- default:
- return false;
- } // End of switch.
-
- return true;
- },
-
- exit: function() {
- this.timeoutTimer.cancel();
- this.timeoutTimer = null;
- }
- });
-
- var stateReinvoking = _sm.makeState("REINVOKING", {
- timeoutTimer: null,
-
- enter: function() {
- let self = this;
-
- _observer.onConnecting(_savedConfig);
- _sm.pause();
- aP2pCommand.p2pReinvoke(_savedConfig.netId, _savedConfig.address, function(success) {
- if (!success) {
- _sm.gotoState(stateInactive);
- return;
- }
- // Waiting for EVENT_P2P_GROUP_STARTED.
- self.timeoutTimer = initTimeoutTimer(60000, EVENT_TIMEOUT_CONNECTING);
- _sm.resume();
- });
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_GROUP_STARTED:
- _sm.pause();
- handleGroupStarted(aEvent.info, function(success) {
- _sm.resume();
- });
- break;
-
- case EVENT_P2P_GO_NEG_FAILURE:
- debug('Negotiation failure. Go back to inactive state');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_TIMEOUT_CONNECTING:
- debug('Connecting timeout! Go back to inactive state');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_P2P_GROUP_FORMATION_SUCCESS:
- case EVENT_P2P_GO_NEG_SUCCESS:
- break;
-
- case EVENT_P2P_GROUP_FORMATION_FAILURE:
- debug('Group formation failure');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_P2P_GROUP_REMOVED:
- debug('Received P2P-GROUP-REMOVED due to previous failed handleGroupdStarted()');
- _removedGroupInfo = {
- role: aEvent.info.role,
- ifname: aEvent.info.ifname
- };
- _sm.gotoState(stateDisconnecting);
- break;
-
- default:
- return false;
- } // End of switch.
-
- return true;
- },
-
- exit: function() {
- this.timeoutTimer.cancel();
- }
- });
-
- var stateProvisionDiscovery = _sm.makeState("PROVISION_DISCOVERY", {
- enter: function() {
- function onDiscoveryCommandSent(success) {
- if (!success) {
- _sm.gotoState(stateInactive);
- debug('Failed to send p2p_prov_disc. Go back to inactive state.');
- return;
- }
-
- debug('p2p_prov_disc has been sent.');
-
- _sm.resume();
- // Waiting for EVENT_P2P_PROV_DISC_PBC_RESP or
- // EVENT_P2P_PROV_DISC_SHOW_PIN or
- // EVENT_P2P_PROV_DISC_ENTER_PIN.
- }
-
- _sm.pause();
- aP2pCommand.p2pProvDiscovery(_savedConfig.address,
- toPeerWpsMethod(_savedConfig.wpsMethod),
- onDiscoveryCommandSent);
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_PROV_DISC_PBC_RESP:
- _sm.gotoState(stateConnecting); // No need for local user grant.
- break;
- case EVENT_P2P_PROV_DISC_SHOW_PIN:
- case EVENT_P2P_PROV_DISC_ENTER_PIN:
- if (aEvent.info.wpsMethod !== _savedConfig.wpsMethod) {
- debug('Unmatched wps method: ' + aEvent.info.wpsMethod + ":" + _savedConfig.wpsMethod);
- }
- if (EVENT_P2P_PROV_DISC_SHOW_PIN === aEvent.id) {
- _savedConfig.pin = aEvent.info.pin;
- }
- _sm.gotoState(stateWaitingForConfirmation);
- break;
-
- case EVENT_P2P_PROV_DISC_FAILURE:
- _sm.gotoState(stateInactive);
- break;
-
- default:
- return false;
- } // End of switch.
- return true;
- }
- });
-
- // We are going to connect to the peer.
- // |_savedConfig| is supposed to have been filled properly.
- var stateConnecting = _sm.makeState("CONNECTING", {
- timeoutTimer: null,
-
- enter: function() {
- let self = this;
-
- if (null === _savedConfig.goIntent) {
- _savedConfig.goIntent = DEFAULT_GO_INTENT;
- }
-
- _observer.onConnecting(_savedConfig);
-
- let wpsMethodWithPin;
- if (WPS_METHOD_KEYPAD === _savedConfig.wpsMethod ||
- WPS_METHOD_DISPLAY === _savedConfig.wpsMethod) {
- // e.g. '12345678 display or '12345678 keypad'.
- wpsMethodWithPin = (_savedConfig.pin + ' ' + _savedConfig.wpsMethod);
- } else {
- // e.g. 'pbc'.
- wpsMethodWithPin = _savedConfig.wpsMethod;
- }
-
- _sm.pause();
-
- aP2pCommand.p2pGetGroupCapab(_savedConfig.address, function(gc) {
- debug('group capabilities of ' + _savedConfig.address + ': ' + gc);
-
- let isPeerGroupOwner = gc & GROUP_CAPAB_GROUP_OWNER;
- let config = { address: _savedConfig.address,
- wpsMethodWithPin: wpsMethodWithPin,
- goIntent: _savedConfig.goIntent,
- joinExistingGroup: isPeerGroupOwner };
-
- aP2pCommand.p2pConnect(config, function (success) {
- if (!success) {
- debug('Failed to send p2p_connect');
- _sm.gotoState(stateInactive);
- return;
- }
- debug('Waiting for EVENT_P2P_GROUP_STARTED.');
- self.timeoutTimer = initTimeoutTimer(60000, EVENT_TIMEOUT_CONNECTING);
- _sm.resume();
- });
- });
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_GROUP_STARTED:
- _sm.pause();
- handleGroupStarted(aEvent.info, function (success) {
- _sm.resume();
- });
- break;
-
- case EVENT_P2P_GO_NEG_FAILURE:
- debug('Negotiation failure. Go back to inactive state');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_TIMEOUT_CONNECTING:
- debug('Connecting timeout! Go back to inactive state');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_P2P_GROUP_FORMATION_SUCCESS:
- case EVENT_P2P_GO_NEG_SUCCESS:
- break;
-
- case EVENT_P2P_GROUP_FORMATION_FAILURE:
- debug('Group formation failure');
- _sm.gotoState(stateInactive);
- break;
-
- case EVENT_P2P_GROUP_REMOVED:
- debug('Received P2P-GROUP-REMOVED due to previous failed ' +
- 'handleGroupdStarted()');
- _removedGroupInfo = {
- role: aEvent.info.role,
- ifname: aEvent.info.ifname
- };
- _sm.gotoState(stateDisconnecting);
- break;
-
- default:
- return false;
- } // End of switch.
-
- return true;
- },
-
- exit: function() {
- this.timeoutTimer.cancel();
- }
- });
-
- var stateConnected = _sm.makeState("CONNECTED", {
- groupOwner: null,
-
- enter: function() {
- this.groupOwner = {
- macAddress: _groupInfo.goAddress,
- ipAddress: _groupInfo.networkInterface.info.gateways[0],
- passphrase: _groupInfo.passphrase,
- ssid: _groupInfo.ssid,
- freq: _groupInfo.freq,
- isLocal: _groupInfo.isGroupOwner
- };
-
- if (!_groupInfo.isGroupOwner) {
- _observer.onConnected(this.groupOwner, _savedConfig);
- } else {
- // If I am a group owner, notify onConnected until EVENT_AP_STA_CONNECTED
- // is received.
- }
-
- _removedGroupInfo = null;
- },
-
- handleEvent: function(aEvent) {
- switch (aEvent.id) {
- case EVENT_AP_STA_CONNECTED:
- if (_groupInfo.isGroupOwner) {
- _observer.onConnected(this.groupOwner, _savedConfig);
- }
- break;
-
- case EVENT_P2P_GROUP_REMOVED:
- _removedGroupInfo = {
- role: aEvent.info.role,
- ifname: aEvent.info.ifname
- };
- _sm.gotoState(stateDisconnecting);
- break;
-
- case EVENT_AP_STA_DISCONNECTED:
- debug('Client disconnected: ' + aEvent.info.address);
-
- // Now we suppose it's the only client. Remove my group.
- _sm.pause();
- aP2pCommand.p2pGroupRemove(_groupInfo.ifname, function (success) {
- debug('Requested to remove p2p group. Wait for EVENT_P2P_GROUP_REMOVED.');
- _sm.resume();
- });
- break;
-
- case EVENT_P2P_CMD_DISCONNECT:
- // Since we only support single connection, we can ignore
- // the given peer address.
- _sm.pause();
- aP2pCommand.p2pGroupRemove(_groupInfo.ifname, function(success) {
- aEvent.info.onDoDisconnect(true);
- _sm.resume();
- });
-
- debug('Sent disconnect command. Wait for EVENT_P2P_GROUP_REMOVED.');
- break;
-
- case EVENT_P2P_PROV_DISC_PBC_REQ:
- case EVENT_P2P_PROV_DISC_SHOW_PIN:
- case EVENT_P2P_PROV_DISC_ENTER_PIN:
- debug('Someone is trying to connect to me: ' + JSON.stringify(aEvent.info));
-
- _savedConfig = {
- name: aEvent.info.name,
- address: aEvent.info.address,
- wpsMethod: aEvent.info.wpsMethod,
- pin: aEvent.info.pin
- };
-
- _sm.gotoState(stateWaitingForJoiningConfirmation);
- break;
-
- default:
- return false;
- } // end of switch
- return true;
- }
- });
-
- var stateWaitingForJoiningConfirmation = _sm.makeState("WAITING_FOR_JOINING_CONFIRMATION", {
- timeoutTimer: null,
-
- enter: function() {
- gSysMsgr.broadcastMessage(PAIRING_REQUEST_SYS_MSG, _savedConfig);
- this.timeoutTimer = initTimeoutTimer(30000, EVENT_TIMEOUT_PAIRING_CONFIRMATION);
- },
-
- handleEvent: function (aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_SET_PAIRING_CONFIRMATION:
- if (!aEvent.info.accepted) {
- debug('User rejected invitation!');
- _sm.gotoState(stateConnected);
- break;
- }
-
- let onWpsCommandSent = function(success) {
- _observer.onConnecting(_savedConfig);
- _sm.gotoState(stateConnected);
- };
-
- _sm.pause();
- if (WPS_METHOD_PBC === _savedConfig.wpsMethod) {
- aP2pCommand.wpsPbc(onWpsCommandSent, _groupInfo.ifname);
- } else {
- let detail = { pin: _savedConfig.pin, iface: _groupInfo.ifname };
- aP2pCommand.wpsPin(detail, onWpsCommandSent);
- }
- break;
-
- case EVENT_TIMEOUT_PAIRING_CONFIRMATION:
- debug('WAITING_FOR_JOINING_CONFIRMATION timeout!');
- _sm.gotoState(stateConnected);
- break;
-
- default:
- return false;
- } // End of switch.
- return true;
- },
-
- exit: function() {
- this.timeoutTimer.cancel();
- this.timeoutTimer = null;
- }
- });
-
- var stateDisconnecting = _sm.makeState("DISCONNECTING", {
- enter: function() {
- _sm.pause();
- handleGroupRemoved(_removedGroupInfo, function (success) {
- if (!success) {
- debug('Failed to handle group removed event. What can I do?');
- }
- _sm.gotoState(stateInactive);
- });
- },
-
- handleEvent: function(aEvent) {
- return false; // We will not receive any event in this state.
- }
- });
-
- var stateDisabling = _sm.makeState("DISABLING", {
- enter: function() {
- _sm.pause();
- aNetUtil.stopDhcpServer(function (success) { // Stopping DHCP server is harmless.
- debug('Stop DHCP server result: ' + success);
- aP2pCommand.p2pDisable(function(success) {
- debug('P2P function disabled');
- closeSupplicantConnectionIfNeeded(function() {
- debug('Supplicant connection closed');
- gNetworkService.disableInterface(P2P_INTERFACE_NAME, function (success){
- debug('Disabled interface: ' + P2P_INTERFACE_NAME);
- _onDisabled(true);
- _observer.onDisabled();
- _sm.gotoState(stateDisabled);
- });
- });
- });
- });
-
- function closeSupplicantConnectionIfNeeded(callback) {
- // No need to connect to supplicant on KK. Call back directly.
- if (aP2pCommand.getSdkVersion() >= 19) {
- callback();
- return;
- }
- aP2pCommand.closeSupplicantConnection(callback);
- }
- },
-
- handleEvent: function(aEvent) {
- return false; // We will not receive any event in this state.
- }
- });
-
- //----------------------------------------------------------
- // Helper functions.
- //----------------------------------------------------------
-
- // Handle 'P2P_GROUP_STARTED' event. Note that this function
- // will also do the state transitioning and error handling.
- //
- // @param aInfo Information carried by "P2P_GROUP_STARTED" event:
- // .role: P2P_ROLE_GO or P2P_ROLE_CLIENT
- // .ssid:
- // .freq:
- // .passphrase: Used to connect to GO for legacy device.
- // .goAddress:
- // .ifname: e.g. p2p-p2p0
- //
- // @param aCallback Callback function.
- function handleGroupStarted(aInfo, aCallback) {
- debug('handleGroupStarted: ' + JSON.stringify(aInfo));
-
- function onSuccess()
- {
- _sm.gotoState(stateConnected);
- aCallback(true);
- }
-
- function onFailure()
- {
- debug('Failed to handleGroupdStarted(). Remove the group...');
- aP2pCommand.p2pGroupRemove(aInfo.ifname, function (success) {
- aCallback(false);
-
- if (success) {
- return; // Stay in current state and wait for EVENT_P2P_GROUP_REMOVED.
- }
-
- debug('p2pGroupRemove command error!');
- _sm.gotoState(stateInactive);
- });
- }
-
- // Save this group information.
- _groupInfo = aInfo;
- _groupInfo.isGroupOwner = (P2P_ROLE_GO === aInfo.role);
-
- if (_groupInfo.isGroupOwner) {
- debug('Group owner. Start DHCP server');
- let dhcpServerConfig = { ifname: aInfo.ifname,
- startIp: GO_DHCP_SERVER_IP_RANGE.startIp,
- endIp: GO_DHCP_SERVER_IP_RANGE.endIp,
- serverIp: GO_NETWORK_INTERFACE.ip,
- maskLength: GO_NETWORK_INTERFACE.maskLength };
-
- aNetUtil.startDhcpServer(dhcpServerConfig, function (success) {
- if (!success) {
- debug('Failed to start DHCP server');
- onFailure();
- return;
- }
-
- // Update p2p network interface.
- _p2pNetworkInterface.info.state = Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED;
- _p2pNetworkInterface.info.ips = [GO_NETWORK_INTERFACE.ip];
- _p2pNetworkInterface.info.prefixLengths = [GO_NETWORK_INTERFACE.maskLength];
- _p2pNetworkInterface.info.gateways = [GO_NETWORK_INTERFACE.ip];
- handleP2pNetworkInterfaceStateChanged();
-
- _groupInfo.networkInterface = _p2pNetworkInterface;
-
- debug('Everything is done. Happy p2p GO~');
- onSuccess();
- });
-
- return;
- }
-
- // We are the client.
-
- debug("Client. Request IP from DHCP server on interface: " + _groupInfo.ifname);
-
- aNetUtil.runDhcp(aInfo.ifname, 0, function(dhcpData) {
- if(!dhcpData || !dhcpData.info) {
- debug('Failed to run DHCP client');
- onFailure();
- return;
- }
-
- // Save network interface.
- debug("DHCP request success: " + JSON.stringify(dhcpData.info));
-
- // Update p2p network interface.
- let maskLength =
- netHelpers.getMaskLength(netHelpers.stringToIP(dhcpData.info.mask_str));
- if (!maskLength) {
- maskLength = 32; // max prefix for IPv4.
- }
- _p2pNetworkInterface.info.state = Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED;
- _p2pNetworkInterface.info.ips = [dhcpData.info.ipaddr_str];
- _p2pNetworkInterface.info.prefixLengths = [maskLength];
- if (typeof dhcpData.info.dns1_str == "string" &&
- dhcpData.info.dns1_str.length) {
- _p2pNetworkInterface.info.dnses.push(dhcpData.info.dns1_str);
- }
- if (typeof dhcpData.info.dns2_str == "string" &&
- dhcpData.info.dns2_str.length) {
- _p2pNetworkInterface.info.dnses.push(dhcpData.info.dns2_str);
- }
- _p2pNetworkInterface.info.gateways = [dhcpData.info.gateway_str];
- handleP2pNetworkInterfaceStateChanged();
-
- _groupInfo.networkInterface = _p2pNetworkInterface;
-
- debug('Happy p2p client~');
- onSuccess();
- });
- }
-
- function resetP2pNetworkInterface() {
- _p2pNetworkInterface.info.state = Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED;
- _p2pNetworkInterface.info.ips = [];
- _p2pNetworkInterface.info.prefixLengths = [];
- _p2pNetworkInterface.info.dnses = [];
- _p2pNetworkInterface.info.gateways = [];
- }
-
- function registerP2pNetworkInteface() {
- if (!_p2pNetworkInterface.registered) {
- resetP2pNetworkInterface();
- gNetworkManager.registerNetworkInterface(_p2pNetworkInterface);
- _p2pNetworkInterface.registered = true;
- }
- }
-
- function unregisterP2pNetworkInteface() {
- if (_p2pNetworkInterface.registered) {
- resetP2pNetworkInterface();
- gNetworkManager.unregisterNetworkInterface(_p2pNetworkInterface);
- _p2pNetworkInterface.registered = false;
- }
- }
-
- function handleP2pNetworkInterfaceStateChanged() {
- gNetworkManager.updateNetworkInterface(_p2pNetworkInterface);
- }
-
- // Handle 'P2P_GROUP_STARTED' event.
- //
- // @param aInfo information carried by "P2P_GROUP_REMOVED" event:
- // .ifname
- // .role: "GO" or "client".
- //
- // @param aCallback Callback function.
- function handleGroupRemoved(aInfo, aCallback) {
- if (!_groupInfo) {
- debug('No group info. Why?');
- aCallback(true);
- return;
- }
- if (_groupInfo.ifname !== aInfo.ifname ||
- _groupInfo.role !== aInfo.role) {
- debug('Unmatched group info: ' + JSON.stringify(_groupInfo) +
- ' v.s. ' + JSON.stringify(aInfo));
- }
-
- // Update p2p network interface.
- _p2pNetworkInterface.info.state = Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED;
- handleP2pNetworkInterfaceStateChanged();
-
- if (P2P_ROLE_GO === aInfo.role) {
- aNetUtil.stopDhcpServer(function(success) {
- debug('Stop DHCP server result: ' + success);
- aCallback(true);
- });
- } else {
- aNetUtil.stopDhcp(aInfo.ifname, function() {
- aCallback(true);
- });
- }
- }
-
- // Non state-specific event handler.
- function handleEventCommon(aEvent) {
- switch (aEvent.id) {
- case EVENT_P2P_DEVICE_FOUND:
- _observer.onPeerFound(aEvent.info);
- break;
-
- case EVENT_P2P_DEVICE_LOST:
- _observer.onPeerLost(aEvent.info);
- break;
-
- case EVENT_P2P_CMD_DISABLE:
- _onDisabled = aEvent.info.onDisabled;
- _sm.gotoState(stateDisabling);
- break;
-
- case EVENT_P2P_CMD_ENABLE_SCAN:
- if (_scanBlocked) {
- _scanPostponded = true;
- aEvent.info.callback(true);
- break;
- }
- aP2pCommand.p2pEnableScan(P2P_SCAN_TIMEOUT_SEC, aEvent.info.callback);
- break;
-
- case EVENT_P2P_CMD_DISABLE_SCAN:
- aP2pCommand.p2pDisableScan(aEvent.info.callback);
- break;
-
- case EVENT_P2P_FIND_STOPPED:
- break;
-
- case EVENT_P2P_CMD_BLOCK_SCAN:
- _scanBlocked = true;
- aP2pCommand.p2pDisableScan(function(success) {});
- break;
-
- case EVENT_P2P_CMD_UNBLOCK_SCAN:
- _scanBlocked = false;
- if (_scanPostponded) {
- aP2pCommand.p2pEnableScan(P2P_SCAN_TIMEOUT_SEC, function(success) {});
- }
- break;
-
- case EVENT_P2P_CMD_CONNECT:
- case EVENT_P2P_CMD_DISCONNECT:
- debug("The current state couldn't handle connect/disconnect request. Ignore it.");
- break;
-
- default:
- return false;
- } // End of switch.
- return true;
- }
-
- function isInP2pManagedState(aState) {
- let p2pManagedStates = [stateWaitingForConfirmation,
- stateWaitingForNegReq,
- stateProvisionDiscovery,
- stateWaitingForInvitationConfirmation,
- stateGroupAdding,
- stateReinvoking,
- stateConnecting,
- stateConnected,
- stateDisconnecting];
-
- for (let i = 0; i < p2pManagedStates.length; i++) {
- if (aState === p2pManagedStates[i]) {
- return true;
- }
- }
-
- return false;
- }
-
- function initTimeoutTimer(aTimeoutMs, aTimeoutEvent) {
- let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- function onTimerFired() {
- _sm.sendEvent({ id: aTimeoutEvent });
- timer = null;
- }
- timer.initWithCallback(onTimerFired.bind(this), aTimeoutMs,
- Ci.nsITimer.TYPE_ONE_SHOT);
- return timer;
- }
-
- // Converts local WPS method to peer WPS method.
- function toPeerWpsMethod(aLocalWpsMethod) {
- switch (aLocalWpsMethod) {
- case WPS_METHOD_DISPLAY:
- return WPS_METHOD_KEYPAD;
- case WPS_METHOD_KEYPAD:
- return WPS_METHOD_DISPLAY;
- case WPS_METHOD_PBC:
- return WPS_METHOD_PBC;
- default:
- return WPS_METHOD_PBC; // Use "push button" as the default method.
- }
- }
-
- return p2pSm;
-}
-
-this.WifiP2pManager.INTERFACE_NAME = P2P_INTERFACE_NAME;
diff --git a/dom/wifi/WifiP2pWorkerObserver.jsm b/dom/wifi/WifiP2pWorkerObserver.jsm
deleted file mode 100644
index d04e8db5e..000000000
--- a/dom/wifi/WifiP2pWorkerObserver.jsm
+++ /dev/null
@@ -1,319 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-const CONNECTION_STATUS_DISCONNECTED = "disconnected";
-const CONNECTION_STATUS_CONNECTING = "connecting";
-const CONNECTION_STATUS_CONNECTED = "connected";
-const CONNECTION_STATUS_DISCONNECTING = "disconnecting";
-
-const DEBUG = false;
-
-this.EXPORTED_SYMBOLS = ["WifiP2pWorkerObserver"];
-
-// WifiP2pWorkerObserver resides in WifiWorker to handle DOM message
-// by either 1) returning internally maintained information or
-// 2) delegating to aDomMsgResponder. It is also responsible
-// for observing events from WifiP2pManager and dispatch to DOM.
-//
-// @param aDomMsgResponder handles DOM messages, including
-// - setScanEnabled
-// - connect
-// - disconnect
-// - setPairingConfirmation
-// The instance is actually WifiP2pManager.
-this.WifiP2pWorkerObserver = function(aDomMsgResponder) {
- function debug(aMsg) {
- if (DEBUG) {
- dump('-------------- WifiP2pWorkerObserver: ' + aMsg);
- }
- }
-
- // Private member variables.
- let _localDevice;
- let _peerList = {}; // List of P2pDevice.
- let _domManagers = [];
- let _enabled = false;
- let _groupOwner = null;
- let _currentPeer = null;
-
- // Constructor of P2pDevice. It will be exposed to DOM.
- //
- // @param aPeer object representing a P2P device:
- // .name: string for the device name.
- // .address: Mac address.
- // .isGroupOwner: boolean to indicate if this device is the group owner.
- // .wpsCapabilities: array of string of {"pbc", "display", "keypad"}.
- function P2pDevice(aPeer) {
- this.address = aPeer.address;
- this.name = (aPeer.name ? aPeer.name : aPeer.address);
- this.isGroupOwner = aPeer.isGroupOwner;
- this.wpsCapabilities = aPeer.wpsCapabilities;
- this.connectionStatus = CONNECTION_STATUS_DISCONNECTED;
-
- // Since this object will be exposed to web, defined the exposed
- // properties here.
- this.__exposedProps__ = {
- address: "r",
- name: "r",
- isGroupOwner: "r",
- wpsCapabilities: "r",
- connectionStatus: "r"
- };
- }
-
- // Constructor of P2pGroupOwner.
- //
- // @param aGroupOwner:
- // .macAddress
- // .ipAddress
- // .passphrase
- // .ssid
- // .freq
- // .isLocal
- function P2pGroupOwner(aGroupOwner) {
- this.macAddress = aGroupOwner.macAddress; // The identifier to get further information.
- this.ipAddress = aGroupOwner.ipAddress;
- this.passphrase = aGroupOwner.passphrase;
- this.ssid = aGroupOwner.ssid; // e.g. DIRECT-xy.
- this.freq = aGroupOwner.freq;
- this.isLocal = aGroupOwner.isLocal;
-
- let detail = _peerList[aGroupOwner.macAddress];
- if (detail) {
- this.name = detail.name;
- this.wpsCapabilities = detail.wpsCapabilities;
- } else if (_localDevice.address === this.macAddress) {
- this.name = _localDevice.name;
- this.wpsCapabilities = _localDevice.wpsCapabilities;
- } else {
- debug("We don't know this group owner: " + aGroupOwner.macAddress);
- this.name = aGroupOwner.macAddress;
- this.wpsCapabilities = [];
- }
- }
-
- function fireEvent(aMessage, aData) {
- debug('domManager: ' + JSON.stringify(_domManagers));
- _domManagers.forEach(function(manager) {
- // Note: We should never have a dead message manager here because we
- // observe our child message managers shutting down below.
- manager.sendAsyncMessage("WifiP2pManager:" + aMessage, aData);
- });
- }
-
- function addDomManager(aMsg) {
- if (-1 === _domManagers.indexOf(aMsg.manager)) {
- _domManagers.push(aMsg.manager);
- }
- }
-
- function returnMessage(aMessage, aSuccess, aData, aMsg) {
- let rMsg = aMessage + ":Return:" + (aSuccess ? "OK" : "NO");
- aMsg.manager.sendAsyncMessage(rMsg,
- { data: aData, rid: aMsg.rid, mid: aMsg.mid });
- }
-
- function handlePeerListUpdated() {
- fireEvent("onpeerinfoupdate", {});
- }
-
- // Return a literal object as the constructed object.
- return {
- onLocalDeviceChanged: function(aDevice) {
- _localDevice = aDevice;
- debug('Local device updated to: ' + JSON.stringify(_localDevice));
- },
-
- onEnabled: function() {
- _peerList = [];
- _enabled = true;
- fireEvent("p2pUp", {});
- },
-
- onDisbaled: function() {
- _enabled = false;
- fireEvent("p2pDown", {});
- },
-
- onPeerFound: function(aPeer) {
- let newFoundPeer = new P2pDevice(aPeer);
- let origianlPeer = _peerList[aPeer.address];
- _peerList[aPeer.address] = newFoundPeer;
- if (origianlPeer) {
- newFoundPeer.connectionStatus = origianlPeer.connectionStatus;
- }
- handlePeerListUpdated();
- },
-
- onPeerLost: function(aPeer) {
- let lostPeer = _peerList[aPeer.address];
- if (!lostPeer) {
- debug('Unknown peer lost: ' + aPeer.address);
- return;
- }
- delete _peerList[aPeer.address];
- handlePeerListUpdated();
- },
-
- onConnecting: function(aPeer) {
- let peer = _peerList[aPeer.address];
- if (!peer) {
- debug('Unknown peer connecting: ' + aPeer.address);
- peer = new P2pDevice(aPeer);
- _peerList[aPeer.address] = peer;
- handlePeerListUpdated();
- }
- peer.connectionStatus = CONNECTION_STATUS_CONNECTING;
-
- fireEvent('onconnecting', { peer: peer });
- },
-
- onConnected: function(aGroupOwner, aPeer) {
- let go = new P2pGroupOwner(aGroupOwner);
- let peer = _peerList[aPeer.address];
- if (!peer) {
- debug('Unknown peer connected: ' + aPeer.address);
- peer = new P2pDevice(aPeer);
- _peerList[aPeer.address] = peer;
- handlePeerListUpdated();
- }
- peer.connectionStatus = CONNECTION_STATUS_CONNECTED;
- peer.isGroupOwner = (aPeer.address === aGroupOwner.address);
-
- _groupOwner = go;
- _currentPeer = peer;
-
- fireEvent('onconnected', { groupOwner: go, peer: peer });
- },
-
- onDisconnected: function(aPeer) {
- let peer = _peerList[aPeer.address];
- if (!peer) {
- debug('Unknown peer disconnected: ' + aPeer.address);
- return;
- }
-
- peer.connectionStatus = CONNECTION_STATUS_DISCONNECTED;
-
- _groupOwner = null;
- _currentPeer = null;
-
- fireEvent('ondisconnected', { peer: peer });
- },
-
- getObservedDOMMessages: function() {
- return [
- "WifiP2pManager:getState",
- "WifiP2pManager:getPeerList",
- "WifiP2pManager:setScanEnabled",
- "WifiP2pManager:connect",
- "WifiP2pManager:disconnect",
- "WifiP2pManager:setPairingConfirmation",
- "WifiP2pManager:setDeviceName"
- ];
- },
-
- onDOMMessage: function(aMessage) {
- let msg = aMessage.data || {};
- msg.manager = aMessage.target;
-
- if ("child-process-shutdown" === aMessage.name) {
- let i;
- if (-1 !== (i = _domManagers.indexOf(msg.manager))) {
- _domManagers.splice(i, 1);
- }
- return;
- }
-
- if (!aMessage.target.assertPermission("wifi-manage")) {
- return;
- }
-
- switch (aMessage.name) {
- case "WifiP2pManager:getState": // A new DOM manager is created.
- addDomManager(msg);
- return { // Synchronous call. Simply return it.
- enabled: _enabled,
- groupOwner: _groupOwner,
- currentPeer: _currentPeer
- };
-
- case "WifiP2pManager:setScanEnabled":
- {
- let enabled = msg.data;
-
- aDomMsgResponder.setScanEnabled(enabled, function(success) {
- returnMessage(aMessage.name, success, (success ? true : "ERROR"), msg);
- });
- }
- break;
-
- case "WifiP2pManager:getPeerList":
- {
- // Convert the object to an array.
- let peerArray = [];
- for (let key in _peerList) {
- if (_peerList.hasOwnProperty(key)) {
- peerArray.push(_peerList[key]);
- }
- }
-
- returnMessage(aMessage.name, true, peerArray, msg);
- }
- break;
-
- case "WifiP2pManager:connect":
- {
- let peer = msg.data;
-
- let onDoConnect = function(success) {
- returnMessage(aMessage.name, success, (success ? true : "ERROR"), msg);
- };
-
- aDomMsgResponder.connect(peer.address, peer.wpsMethod,
- peer.goIntent, onDoConnect);
- }
- break;
-
- case "WifiP2pManager:disconnect":
- {
- let address = msg.data;
-
- aDomMsgResponder.disconnect(address, function(success) {
- returnMessage(aMessage.name, success, (success ? true : "ERROR"), msg);
- });
- }
- break;
-
- case "WifiP2pManager:setPairingConfirmation":
- {
- let result = msg.data;
- aDomMsgResponder.setPairingConfirmation(result);
- returnMessage(aMessage.name, true, true, msg);
- }
- break;
-
- case "WifiP2pManager:setDeviceName":
- {
- let newDeviceName = msg.data;
- aDomMsgResponder.setDeviceName(newDeviceName, function(success) {
- returnMessage(aMessage.name, success, (success ? true : "ERROR"), msg);
- });
- }
- break;
-
- default:
- if (0 === aMessage.name.indexOf("WifiP2pManager:")) {
- debug("DOM WifiP2pManager message not handled: " + aMessage.name);
- }
- } // End of switch.
- }
- };
-};
diff --git a/dom/wifi/WifiProxyService.cpp b/dom/wifi/WifiProxyService.cpp
deleted file mode 100644
index 0ff5097af..000000000
--- a/dom/wifi/WifiProxyService.cpp
+++ /dev/null
@@ -1,357 +0,0 @@
-/* -*- 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 "WifiProxyService.h"
-#include "nsServiceManagerUtils.h"
-#include "mozilla/ModuleUtils.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/dom/ToJSValue.h"
-#include "nsXULAppAPI.h"
-#include "WifiUtils.h"
-
-#ifdef MOZ_TASK_TRACER
-#include "GeckoTaskTracer.h"
-using namespace mozilla::tasktracer;
-#endif
-
-#define NS_WIFIPROXYSERVICE_CID \
- { 0xc6c9be7e, 0x744f, 0x4222, {0xb2, 0x03, 0xcd, 0x55, 0xdf, 0xc8, 0xbc, 0x12} }
-
-using namespace mozilla;
-using namespace mozilla::dom;
-
-namespace mozilla {
-
-// The singleton Wifi service, to be used on the main thread.
-static StaticRefPtr<WifiProxyService> gWifiProxyService;
-
-// The singleton supplicant class, that can be used on any thread.
-static UniquePtr<WpaSupplicant> gWpaSupplicant;
-
-// Runnable used dispatch the WaitForEvent result on the main thread.
-class WifiEventDispatcher : public Runnable
-{
-public:
- WifiEventDispatcher(const nsAString& aEvent, const nsACString& aInterface)
- : mEvent(aEvent)
- , mInterface(aInterface)
- {
- MOZ_ASSERT(!NS_IsMainThread());
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
- gWifiProxyService->DispatchWifiEvent(mEvent, mInterface);
- return NS_OK;
- }
-
-private:
- nsString mEvent;
- nsCString mInterface;
-};
-
-// Runnable used to call WaitForEvent on the event thread.
-class EventRunnable : public Runnable
-{
-public:
- EventRunnable(const nsACString& aInterface)
- : mInterface(aInterface)
- {
- MOZ_ASSERT(NS_IsMainThread());
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(!NS_IsMainThread());
- nsAutoString event;
- gWpaSupplicant->WaitForEvent(event, mInterface);
- if (!event.IsEmpty()) {
-#ifdef MOZ_TASK_TRACER
- // Make wifi initialization events to be the source events of TaskTracer,
- // and originate the rest correlation tasks from here.
- AutoSourceEvent taskTracerEvent(SourceEventType::Wifi);
- AddLabel("%s %s", mInterface.get(), NS_ConvertUTF16toUTF8(event).get());
-#endif
- nsCOMPtr<nsIRunnable> runnable = new WifiEventDispatcher(event, mInterface);
- NS_DispatchToMainThread(runnable);
- }
- return NS_OK;
- }
-
-private:
- nsCString mInterface;
-};
-
-// Runnable used dispatch the Command result on the main thread.
-class WifiResultDispatcher : public Runnable
-{
-public:
- WifiResultDispatcher(WifiResultOptions& aResult, const nsACString& aInterface)
- : mResult(aResult)
- , mInterface(aInterface)
- {
- MOZ_ASSERT(!NS_IsMainThread());
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
- gWifiProxyService->DispatchWifiResult(mResult, mInterface);
- return NS_OK;
- }
-
-private:
- WifiResultOptions mResult;
- nsCString mInterface;
-};
-
-// Runnable used to call SendCommand on the control thread.
-class ControlRunnable : public Runnable
-{
-public:
- ControlRunnable(CommandOptions aOptions, const nsACString& aInterface)
- : mOptions(aOptions)
- , mInterface(aInterface)
- {
- MOZ_ASSERT(NS_IsMainThread());
- }
-
- NS_IMETHOD Run() override
- {
- WifiResultOptions result;
- if (gWpaSupplicant->ExecuteCommand(mOptions, result, mInterface)) {
- nsCOMPtr<nsIRunnable> runnable = new WifiResultDispatcher(result, mInterface);
- NS_DispatchToMainThread(runnable);
- }
- return NS_OK;
- }
-private:
- CommandOptions mOptions;
- nsCString mInterface;
-};
-
-NS_IMPL_ISUPPORTS(WifiProxyService, nsIWifiProxyService)
-
-WifiProxyService::WifiProxyService()
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!gWifiProxyService);
-}
-
-WifiProxyService::~WifiProxyService()
-{
- MOZ_ASSERT(!gWifiProxyService);
-}
-
-already_AddRefed<WifiProxyService>
-WifiProxyService::FactoryCreate()
-{
- if (!XRE_IsParentProcess()) {
- return nullptr;
- }
-
- MOZ_ASSERT(NS_IsMainThread());
-
- if (!gWifiProxyService) {
- gWifiProxyService = new WifiProxyService();
- ClearOnShutdown(&gWifiProxyService);
-
- gWpaSupplicant = MakeUnique<WpaSupplicant>();
- ClearOnShutdown(&gWpaSupplicant);
- }
-
- RefPtr<WifiProxyService> service = gWifiProxyService.get();
- return service.forget();
-}
-
-NS_IMETHODIMP
-WifiProxyService::Start(nsIWifiEventListener* aListener,
- const char ** aInterfaces,
- uint32_t aNumOfInterfaces)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(aListener);
-
-#if ANDROID_VERSION >= 19
- // KK changes the way mux'ing/demux'ing different supplicant interfaces
- // (e.g. wlan0/p2p0) from multi-sockets to single socket embedded with
- // prefixed interface name (e.g. IFNAME=wlan0 xxxxxx). Therefore, we use
- // the first given interface as the global interface for KK.
- aNumOfInterfaces = 1;
-#endif
-
- nsresult rv;
-
- // Since EventRunnable runs in the manner of blocking, we have to
- // spin a thread for each interface.
- // (See the WpaSupplicant::WaitForEvent)
- mEventThreadList.SetLength(aNumOfInterfaces);
- for (uint32_t i = 0; i < aNumOfInterfaces; i++) {
- mEventThreadList[i].mInterface = aInterfaces[i];
- rv = NS_NewThread(getter_AddRefs(mEventThreadList[i].mThread));
- if (NS_FAILED(rv)) {
- NS_WARNING("Can't create wifi event thread");
- Shutdown();
- return NS_ERROR_FAILURE;
- }
- }
-
- rv = NS_NewThread(getter_AddRefs(mControlThread));
- if (NS_FAILED(rv)) {
- NS_WARNING("Can't create wifi control thread");
- Shutdown();
- return NS_ERROR_FAILURE;
- }
-
- mListener = aListener;
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-WifiProxyService::Shutdown()
-{
- MOZ_ASSERT(NS_IsMainThread());
- for (size_t i = 0; i < mEventThreadList.Length(); i++) {
- if (mEventThreadList[i].mThread) {
- mEventThreadList[i].mThread->Shutdown();
- mEventThreadList[i].mThread = nullptr;
- }
- }
-
- mEventThreadList.Clear();
-
- if (mControlThread) {
- mControlThread->Shutdown();
- mControlThread = nullptr;
- }
-
- mListener = nullptr;
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-WifiProxyService::SendCommand(JS::Handle<JS::Value> aOptions,
- const nsACString& aInterface,
- JSContext* aCx)
-{
- MOZ_ASSERT(NS_IsMainThread());
- WifiCommandOptions options;
-
- if (!options.Init(aCx, aOptions)) {
- NS_WARNING("Bad dictionary passed to WifiProxyService::SendCommand");
- return NS_ERROR_FAILURE;
- }
-
- if (!mControlThread) {
- return NS_ERROR_FAILURE;
- }
-
- // Dispatch the command to the control thread.
- CommandOptions commandOptions(options);
- nsCOMPtr<nsIRunnable> runnable = new ControlRunnable(commandOptions, aInterface);
- mControlThread->Dispatch(runnable, nsIEventTarget::DISPATCH_NORMAL);
- return NS_OK;
-}
-
-NS_IMETHODIMP
-WifiProxyService::WaitForEvent(const nsACString& aInterface)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
-#if ANDROID_VERSION >= 19
- // We will only have one global interface for KK.
- if (!mEventThreadList.IsEmpty()) {
- nsCOMPtr<nsIRunnable> runnable = new EventRunnable(aInterface);
- mEventThreadList[0].mThread->Dispatch(runnable, nsIEventTarget::DISPATCH_NORMAL);
- return NS_OK;
- }
-#else
- // Dispatch to the event thread which has the given interface name
- for (size_t i = 0; i < mEventThreadList.Length(); i++) {
- if (mEventThreadList[i].mInterface.Equals(aInterface)) {
- nsCOMPtr<nsIRunnable> runnable = new EventRunnable(aInterface);
- mEventThreadList[i].mThread->Dispatch(runnable, nsIEventTarget::DISPATCH_NORMAL);
- return NS_OK;
- }
- }
-#endif
-
- return NS_ERROR_FAILURE;
-}
-
-void
-WifiProxyService::DispatchWifiResult(const WifiResultOptions& aOptions, const nsACString& aInterface)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- mozilla::AutoSafeJSContext cx;
- JS::Rooted<JS::Value> val(cx);
-
- if (!ToJSValue(cx, aOptions, &val)) {
- return;
- }
-
- if (mListener) {
- // Call the listener with a JS value.
- mListener->OnCommand(val, aInterface);
- }
-}
-
-void
-WifiProxyService::DispatchWifiEvent(const nsAString& aEvent, const nsACString& aInterface)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
-#if ANDROID_VERSION < 19
- mListener->OnWaitEvent(aEvent, aInterface);
-#else
- // The interface might be embedded in the event string such as
- // "IFNAME=wlan0 CTRL-EVENT-BSS-ADDED 65 3c:94:d5:7c:11:8b".
- // Parse the interface name from the event string and use p2p0
- // as the default interface if "IFNAME" is not found.
- nsAutoString event;
- nsAutoString embeddedInterface(NS_LITERAL_STRING("p2p0"));
- if (StringBeginsWith(aEvent, NS_LITERAL_STRING("IFNAME"))) {
- int32_t ifnameFrom = aEvent.FindChar('=') + 1;
- int32_t ifnameTo = aEvent.FindChar(' ') - 1;
- embeddedInterface = Substring(aEvent, ifnameFrom, ifnameTo - ifnameFrom + 1);
- event = Substring(aEvent, aEvent.FindChar(' ') + 1);
- }
- else {
- event = aEvent;
- }
- mListener->OnWaitEvent(event, NS_ConvertUTF16toUTF8(embeddedInterface));
-#endif
-}
-
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(WifiProxyService,
- WifiProxyService::FactoryCreate)
-
-NS_DEFINE_NAMED_CID(NS_WIFIPROXYSERVICE_CID);
-
-static const mozilla::Module::CIDEntry kWifiProxyServiceCIDs[] = {
- { &kNS_WIFIPROXYSERVICE_CID, false, nullptr, WifiProxyServiceConstructor },
- { nullptr }
-};
-
-static const mozilla::Module::ContractIDEntry kWifiProxyServiceContracts[] = {
- { "@mozilla.org/wifi/service;1", &kNS_WIFIPROXYSERVICE_CID },
- { nullptr }
-};
-
-static const mozilla::Module kWifiProxyServiceModule = {
- mozilla::Module::kVersion,
- kWifiProxyServiceCIDs,
- kWifiProxyServiceContracts,
- nullptr
-};
-
-} // namespace mozilla
-
-NSMODULE_DEFN(WifiProxyServiceModule) = &kWifiProxyServiceModule;
diff --git a/dom/wifi/WifiProxyService.h b/dom/wifi/WifiProxyService.h
deleted file mode 100644
index 406be47de..000000000
--- a/dom/wifi/WifiProxyService.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* -*- 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 WifiProxyService_h
-#define WifiProxyService_h
-
-#include "nsIWifiService.h"
-#include "nsCOMPtr.h"
-#include "nsThread.h"
-#include "mozilla/dom/WifiOptionsBinding.h"
-#include "nsTArray.h"
-
-namespace mozilla {
-
-class WifiProxyService final : public nsIWifiProxyService
-{
-private:
- struct EventThreadListEntry
- {
- nsCOMPtr<nsIThread> mThread;
- nsCString mInterface;
- };
-
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIWIFIPROXYSERVICE
-
- static already_AddRefed<WifiProxyService>
- FactoryCreate();
-
- void DispatchWifiEvent(const nsAString& aEvent, const nsACString& aInterface);
- void DispatchWifiResult(const mozilla::dom::WifiResultOptions& aOptions,
- const nsACString& aInterface);
-
-private:
- WifiProxyService();
- ~WifiProxyService();
-
- nsTArray<EventThreadListEntry> mEventThreadList;
- nsCOMPtr<nsIThread> mControlThread;
- nsCOMPtr<nsIWifiEventListener> mListener;
-};
-
-} // namespace mozilla
-
-#endif // WifiProxyService_h
diff --git a/dom/wifi/WifiUtils.cpp b/dom/wifi/WifiUtils.cpp
deleted file mode 100644
index 2526c9ea4..000000000
--- a/dom/wifi/WifiUtils.cpp
+++ /dev/null
@@ -1,521 +0,0 @@
-/* -*- 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 "WifiUtils.h"
-#include <dlfcn.h>
-#include <errno.h>
-#include <cutils/properties.h>
-#include "prinit.h"
-#include "mozilla/Sprintf.h"
-#include "js/CharacterEncoding.h"
-
-using namespace mozilla::dom;
-
-#define BUFFER_SIZE 4096
-#define COMMAND_SIZE 256
-
-// Intentionally not trying to dlclose() this handle. That's playing
-// Russian roulette with security bugs.
-static void* sWifiLib;
-static PRCallOnceType sInitWifiLib;
-
-static PRStatus
-InitWifiLib()
-{
- sWifiLib = dlopen("/system/lib/libhardware_legacy.so", RTLD_LAZY);
- // We might fail to open the hardware lib. That's OK.
- return PR_SUCCESS;
-}
-
-static void*
-GetSharedLibrary()
-{
- PR_CallOnce(&sInitWifiLib, InitWifiLib);
- return sWifiLib;
-}
-
-static bool
-GetWifiP2pSupported()
-{
- char propP2pSupported[PROPERTY_VALUE_MAX];
- property_get("ro.moz.wifi.p2p_supported", propP2pSupported, "0");
- return (0 == strcmp(propP2pSupported, "1"));
-}
-
-static int
-hex2num(char c)
-{
- if (c >= '0' && c <= '9')
- return c - '0';
- if (c >= 'a' && c <= 'f')
- return c - 'a' + 10;
- if (c >= 'A' && c <= 'F')
- return c - 'A' + 10;
- return -1;
-}
-
-static int
-hex2byte(const char* hex)
-{
- int a, b;
- a = hex2num(*hex++);
- if (a < 0)
- return -1;
- b = hex2num(*hex++);
- if (b < 0)
- return -1;
- return (a << 4) | b;
-}
-
-// This function is equivalent to printf_decode() at src/utils/common.c in
-// the supplicant.
-
-static uint32_t
-convertToBytes(char* buf, uint32_t maxlen, const char* str)
-{
- const char *pos = str;
- uint32_t len = 0;
- int val;
-
- while (*pos) {
- if (len == maxlen)
- break;
- switch (*pos) {
- case '\\':
- pos++;
- switch (*pos) {
- case '\\':
- buf[len++] = '\\';
- pos++;
- break;
- case '"':
- buf[len++] = '"';
- pos++;
- break;
- case 'n':
- buf[len++] = '\n';
- pos++;
- break;
- case 'r':
- buf[len++] = '\r';
- pos++;
- break;
- case 't':
- buf[len++] = '\t';
- pos++;
- break;
- case 'e':
- buf[len++] = '\e';
- pos++;
- break;
- case 'x':
- pos++;
- val = hex2byte(pos);
- if (val < 0) {
- val = hex2num(*pos);
- if (val < 0)
- break;
- buf[len++] = val;
- pos++;
- } else {
- buf[len++] = val;
- pos += 2;
- }
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- val = *pos++ - '0';
- if (*pos >= '0' && *pos <= '7')
- val = val * 8 + (*pos++ - '0');
- if (*pos >= '0' && *pos <= '7')
- val = val * 8 + (*pos++ - '0');
- buf[len++] = val;
- break;
- default:
- break;
- }
- break;
- default:
- buf[len++] = *pos++;
- break;
- }
- }
- return len;
-}
-
-// This is the same algorithm as in InflateUTF8StringToBuffer with Copy and
-// while ignoring invalids.
-// https://mxr.mozilla.org/mozilla-central/source/js/src/vm/CharacterEncoding.cpp#231
-
-static const uint32_t REPLACE_UTF8 = 0xFFFD;
-
-static void
-LossyConvertUTF8toUTF16(const char* aInput, uint32_t aLength, nsAString& aOut)
-{
- JS::UTF8Chars src(aInput, aLength);
-
- char16_t dst[aLength]; // Allocating for worst case.
-
- // Count how many char16_t characters are needed in the inflated string.
- // |i| is the index into |src|, and |j| is the the index into |dst|.
- size_t srclen = src.length();
- uint32_t j = 0;
- for (uint32_t i = 0; i < srclen; i++, j++) {
- uint32_t v = uint32_t(src[i]);
- if (v == uint32_t('\0') && i < srclen - 1) {
- // If the leading byte is '\0' and it's not the last byte,
- // just ignore it to prevent from being truncated. This could
- // be caused by |convertToBytes| (e.g. \x00 would be converted to '\0')
- j--;
- continue;
- }
- if (!(v & 0x80)) {
- // ASCII code unit. Simple copy.
- dst[j] = char16_t(v);
- } else {
- // Non-ASCII code unit. Determine its length in bytes (n).
- uint32_t n = 1;
- while (v & (0x80 >> n))
- n++;
-
- #define INVALID(report, arg, n2) \
- do { \
- n = n2; \
- goto invalidMultiByteCodeUnit; \
- } while (0)
-
- // Check the leading byte.
- if (n < 2 || n > 4)
- INVALID(ReportInvalidCharacter, i, 1);
-
- // Check that |src| is large enough to hold an n-byte code unit.
- if (i + n > srclen)
- INVALID(ReportBufferTooSmall, /* dummy = */ 0, 1);
-
- // Check the second byte. From Unicode Standard v6.2, Table 3-7
- // Well-Formed UTF-8 Byte Sequences.
- if ((v == 0xE0 && ((uint8_t)src[i + 1] & 0xE0) != 0xA0) || // E0 A0~BF
- (v == 0xED && ((uint8_t)src[i + 1] & 0xE0) != 0x80) || // ED 80~9F
- (v == 0xF0 && ((uint8_t)src[i + 1] & 0xF0) == 0x80) || // F0 90~BF
- (v == 0xF4 && ((uint8_t)src[i + 1] & 0xF0) != 0x80)) // F4 80~8F
- {
- INVALID(ReportInvalidCharacter, i, 1);
- }
-
- // Check the continuation bytes.
- for (uint32_t m = 1; m < n; m++)
- if ((src[i + m] & 0xC0) != 0x80)
- INVALID(ReportInvalidCharacter, i, m);
-
- // Determine the code unit's length in char16_t units and act accordingly.
- v = JS::Utf8ToOneUcs4Char((uint8_t *)&src[i], n);
- if (v < 0x10000) {
- // The n-byte UTF8 code unit will fit in a single char16_t.
- dst[j] = char16_t(v);
- } else {
- v -= 0x10000;
- if (v <= 0xFFFFF) {
- // The n-byte UTF8 code unit will fit in two char16_t units.
- dst[j] = char16_t((v >> 10) + 0xD800);
- j++;
- dst[j] = char16_t((v & 0x3FF) + 0xDC00);
- } else {
- // The n-byte UTF8 code unit won't fit in two char16_t units.
- INVALID(ReportTooBigCharacter, v, 1);
- }
- }
-
- invalidMultiByteCodeUnit:
- // Move i to the last byte of the multi-byte code unit; the loop
- // header will do the final i++ to move to the start of the next
- // code unit.
- i += n - 1;
- }
- }
-
- dst[j] = 0;
- aOut = dst;
-}
-
-// Helper to check we have loaded the hardware shared library.
-#define CHECK_HWLIB(ret) \
- void* hwLib = GetSharedLibrary(); \
- if (!hwLib) { \
- NS_WARNING("No /system/lib/libhardware_legacy.so"); \
- return ret; \
- }
-
-#define DEFAULT_IMPL(name, ret, args...) \
- DEFINE_DLFUNC(name, ret, args...) \
- ret do_##name(args) { \
- USE_DLFUNC(name) \
- return name(args); \
- }
-
-// ICS implementation.
-class ICSWpaSupplicantImpl : public WpaSupplicantImpl
-{
-public:
- DEFAULT_IMPL(wifi_load_driver, int32_t, )
- DEFAULT_IMPL(wifi_unload_driver, int32_t, )
-
- DEFINE_DLFUNC(wifi_wait_for_event, int32_t, char*, size_t)
- int32_t do_wifi_wait_for_event(const char *iface, char *buf, size_t len) {
- USE_DLFUNC(wifi_wait_for_event)
- return wifi_wait_for_event(buf, len);
- }
-
- DEFINE_DLFUNC(wifi_command, int32_t, const char*, char*, size_t*)
- int32_t do_wifi_command(const char* iface, const char* cmd, char* buf, size_t* len) {
- USE_DLFUNC(wifi_command)
- return wifi_command(cmd, buf, len);
- }
-
- DEFINE_DLFUNC(wifi_start_supplicant, int32_t, )
- int32_t do_wifi_start_supplicant(int32_t) {
- USE_DLFUNC(wifi_start_supplicant)
- return wifi_start_supplicant();
- }
-
- DEFINE_DLFUNC(wifi_stop_supplicant, int32_t)
- int32_t do_wifi_stop_supplicant(int32_t) {
- USE_DLFUNC(wifi_stop_supplicant)
- return wifi_stop_supplicant();
- }
-
- DEFINE_DLFUNC(wifi_connect_to_supplicant, int32_t, )
- int32_t do_wifi_connect_to_supplicant(const char* iface) {
- USE_DLFUNC(wifi_connect_to_supplicant)
- return wifi_connect_to_supplicant();
- }
-
- DEFINE_DLFUNC(wifi_close_supplicant_connection, void, )
- void do_wifi_close_supplicant_connection(const char* iface) {
- USE_DLFUNC(wifi_close_supplicant_connection)
- return wifi_close_supplicant_connection();
- }
-};
-
-// JB implementation.
-// We only redefine the methods that have a different signature than on ICS.
-class JBWpaSupplicantImpl : public ICSWpaSupplicantImpl
-{
-public:
- DEFINE_DLFUNC(wifi_wait_for_event, int32_t, const char*, char*, size_t)
- int32_t do_wifi_wait_for_event(const char* iface, char* buf, size_t len) {
- USE_DLFUNC(wifi_wait_for_event)
- return wifi_wait_for_event(iface, buf, len);
- }
-
- DEFINE_DLFUNC(wifi_command, int32_t, const char*, const char*, char*, size_t*)
- int32_t do_wifi_command(const char* iface, const char* cmd, char* buf, size_t* len) {
- USE_DLFUNC(wifi_command)
- return wifi_command(iface, cmd, buf, len);
- }
-
- DEFINE_DLFUNC(wifi_start_supplicant, int32_t, int32_t)
- int32_t do_wifi_start_supplicant(int32_t arg) {
- USE_DLFUNC(wifi_start_supplicant)
- return wifi_start_supplicant(arg);
- }
-
- DEFINE_DLFUNC(wifi_stop_supplicant, int32_t, int32_t)
- int32_t do_wifi_stop_supplicant(int32_t arg) {
- USE_DLFUNC(wifi_stop_supplicant)
- return wifi_stop_supplicant(arg);
- }
-
- DEFINE_DLFUNC(wifi_connect_to_supplicant, int32_t, const char*)
- int32_t do_wifi_connect_to_supplicant(const char* iface) {
- USE_DLFUNC(wifi_connect_to_supplicant)
- return wifi_connect_to_supplicant(iface);
- }
-
- DEFINE_DLFUNC(wifi_close_supplicant_connection, void, const char*)
- void do_wifi_close_supplicant_connection(const char* iface) {
- USE_DLFUNC(wifi_close_supplicant_connection)
- wifi_close_supplicant_connection(iface);
- }
-};
-
-// KK implementation.
-// We only redefine the methods that have a different signature than on ICS.
-class KKWpaSupplicantImpl : public ICSWpaSupplicantImpl
-{
-public:
- DEFINE_DLFUNC(wifi_start_supplicant, int32_t, int32_t)
- int32_t do_wifi_start_supplicant(int32_t arg) {
- USE_DLFUNC(wifi_start_supplicant)
- return wifi_start_supplicant(arg);
- }
-
- DEFINE_DLFUNC(wifi_stop_supplicant, int32_t, int32_t)
- int32_t do_wifi_stop_supplicant(int32_t arg) {
- USE_DLFUNC(wifi_stop_supplicant)
- return wifi_stop_supplicant(arg);
- }
-
- DEFINE_DLFUNC(wifi_command, int32_t, const char*, char*, size_t*)
- int32_t do_wifi_command(const char* iface, const char* cmd, char* buf, size_t* len) {
- char command[COMMAND_SIZE];
- if (!strcmp(iface, "p2p0")) {
- // Commands for p2p0 interface don't need prefix
- SprintfLiteral(command, "%s", cmd);
- }
- else {
- SprintfLiteral(command, "IFNAME=%s %s", iface, cmd);
- }
- USE_DLFUNC(wifi_command)
- return wifi_command(command, buf, len);
- }
-};
-
-// Concrete class to use to access the wpa supplicant.
-WpaSupplicant::WpaSupplicant()
-{
- char propVersion[PROPERTY_VALUE_MAX];
- property_get("ro.build.version.sdk", propVersion, "0");
- mSdkVersion = strtol(propVersion, nullptr, 10);
-
- if (mSdkVersion < 16) {
- mImpl = MakeUnique<ICSWpaSupplicantImpl>();
- } else if (mSdkVersion < 19) {
- mImpl = MakeUnique<JBWpaSupplicantImpl>();
- } else {
- mImpl = MakeUnique<KKWpaSupplicantImpl>();
- }
- mWifiHotspotUtils = MakeUnique<WifiHotspotUtils>();
-};
-
-void WpaSupplicant::WaitForEvent(nsAString& aEvent, const nsCString& aInterface)
-{
- CHECK_HWLIB()
-
- char buffer[BUFFER_SIZE];
- int32_t ret = mImpl->do_wifi_wait_for_event(aInterface.get(), buffer, BUFFER_SIZE);
- CheckBuffer(buffer, ret, aEvent);
-}
-
-#define GET_CHAR(prop) NS_ConvertUTF16toUTF8(aOptions.prop).get()
-
-/**
- * Make a subnet mask.
- */
-uint32_t WpaSupplicant::MakeMask(uint32_t len) {
- uint32_t mask = 0;
- for (uint32_t i = 0; i < len; ++i) {
- mask |= (0x80000000 >> i);
- }
- return ntohl(mask);
-}
-
-bool WpaSupplicant::ExecuteCommand(CommandOptions aOptions,
- WifiResultOptions& aResult,
- const nsCString& aInterface)
-{
- CHECK_HWLIB(false)
-
- if (!mWifiHotspotUtils->GetSharedLibrary()) {
- return false;
- }
-
- // Always correlate the opaque ids.
- aResult.mId = aOptions.mId;
-
- if (aOptions.mCmd.EqualsLiteral("command")) {
- size_t len = BUFFER_SIZE - 1;
- char buffer[BUFFER_SIZE];
- NS_ConvertUTF16toUTF8 request(aOptions.mRequest);
- aResult.mStatus = mImpl->do_wifi_command(aInterface.get(), request.get(), buffer, &len);
- nsString value;
- if (aResult.mStatus == 0) {
- if (buffer[len - 1] == '\n') { // remove trailing new lines.
- len--;
- }
- buffer[len] = '\0';
- CheckBuffer(buffer, len, value);
- }
- aResult.mReply = value;
- } else if (aOptions.mCmd.EqualsLiteral("close_supplicant_connection")) {
- mImpl->do_wifi_close_supplicant_connection(aInterface.get());
- } else if (aOptions.mCmd.EqualsLiteral("load_driver")) {
- aResult.mStatus = mImpl->do_wifi_load_driver();
- } else if (aOptions.mCmd.EqualsLiteral("unload_driver")) {
- aResult.mStatus = mImpl->do_wifi_unload_driver();
- } else if (aOptions.mCmd.EqualsLiteral("start_supplicant")) {
- aResult.mStatus = mImpl->do_wifi_start_supplicant(GetWifiP2pSupported() ? 1 : 0);
- } else if (aOptions.mCmd.EqualsLiteral("stop_supplicant")) {
- aResult.mStatus = mImpl->do_wifi_stop_supplicant(0);
- } else if (aOptions.mCmd.EqualsLiteral("connect_to_supplicant")) {
- aResult.mStatus = mImpl->do_wifi_connect_to_supplicant(aInterface.get());
- } else if (aOptions.mCmd.EqualsLiteral("hostapd_command")) {
- size_t len = BUFFER_SIZE - 1;
- char buffer[BUFFER_SIZE];
- NS_ConvertUTF16toUTF8 request(aOptions.mRequest);
- aResult.mStatus = mWifiHotspotUtils->do_wifi_hostapd_command(request.get(),
- buffer,
- &len);
- nsString value;
- if (aResult.mStatus == 0) {
- if (buffer[len - 1] == '\n') { // remove trailing new lines.
- len--;
- }
- buffer[len] = '\0';
- CheckBuffer(buffer, len, value);
- }
- aResult.mReply = value;
- } else if (aOptions.mCmd.EqualsLiteral("hostapd_get_stations")) {
- aResult.mStatus = mWifiHotspotUtils->do_wifi_hostapd_get_stations();
- } else if (aOptions.mCmd.EqualsLiteral("connect_to_hostapd")) {
- aResult.mStatus = mWifiHotspotUtils->do_wifi_connect_to_hostapd();
- } else if (aOptions.mCmd.EqualsLiteral("close_hostapd_connection")) {
- aResult.mStatus = mWifiHotspotUtils->do_wifi_close_hostapd_connection();
-
- } else {
- NS_WARNING("WpaSupplicant::ExecuteCommand : Unknown command");
- printf_stderr("WpaSupplicant::ExecuteCommand : Unknown command: %s",
- NS_ConvertUTF16toUTF8(aOptions.mCmd).get());
- return false;
- }
-
- return true;
-}
-
-// Checks the buffer and do the utf processing.
-void
-WpaSupplicant::CheckBuffer(char* buffer, int32_t length,
- nsAString& aEvent)
-{
- if (length <= 0 || length >= (BUFFER_SIZE - 1)) {
- NS_WARNING("WpaSupplicant::CheckBuffer: Invalid buffer length");
- return;
- }
-
- if (mSdkVersion < 18) {
- buffer[length] = 0;
- LossyConvertUTF8toUTF16(buffer, length, aEvent);
- return;
- }
-
- // After Android JB4.3, the SSIDs have been converted into printable form.
- // In most of cases, SSIDs do not use unprintable characters, but IEEE 802.11
- // standard does not limit the used character set, so anything could be used
- // in an SSID. Convert it to raw data form here.
- char bytesBuffer[BUFFER_SIZE];
- uint32_t bytes = convertToBytes(bytesBuffer, length, buffer);
- if (bytes <= 0 || bytes >= BUFFER_SIZE) {
- NS_WARNING("WpaSupplicant::CheckBuffer: Invalid bytesbuffer length");
- return;
- }
- bytesBuffer[bytes] = 0;
- LossyConvertUTF8toUTF16(bytesBuffer, bytes, aEvent);
-}
diff --git a/dom/wifi/WifiUtils.h b/dom/wifi/WifiUtils.h
deleted file mode 100644
index a83ba9c15..000000000
--- a/dom/wifi/WifiUtils.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/* -*- 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/. */
-
-/**
- * Abstraction on top of the wifi support from libhardware_legacy that we
- * use to talk to the wpa_supplicant.
- */
-
-#ifndef WifiUtils_h
-#define WifiUtils_h
-
-#include "nsString.h"
-#include "mozilla/dom/WifiOptionsBinding.h"
-#include "mozilla/UniquePtr.h"
-#include "WifiHotspotUtils.h"
-
-// Needed to add a copy constructor to WifiCommandOptions.
-struct CommandOptions
-{
-public:
- CommandOptions(const mozilla::dom::WifiCommandOptions& aOther) {
-
-#define COPY_OPT_FIELD(prop, defaultValue) \
- if (aOther.prop.WasPassed()) { \
- prop = aOther.prop.Value(); \
- } else { \
- prop = defaultValue; \
- }
-
-#define COPY_FIELD(prop) prop = aOther.prop;
- COPY_FIELD(mId)
- COPY_FIELD(mCmd)
- COPY_OPT_FIELD(mRequest, EmptyString())
-
-#undef COPY_OPT_FIELD
-#undef COPY_FIELD
- }
-
- // All the fields, not Optional<> anymore to get copy constructors.
- nsString mCmd;
- int32_t mId;
- nsString mRequest;
-};
-
-// Abstract class that exposes libhardware_legacy functions we need for
-// wifi management.
-// We use the ICS signatures here since they are likely more future-proof.
-class WpaSupplicantImpl
-{
-public:
- // Suppress warning from |UniquePtr|
- virtual ~WpaSupplicantImpl() {}
-
- virtual int32_t
- do_wifi_wait_for_event(const char *iface, char *buf, size_t len) = 0; // KK == ICS != JB
-
- virtual int32_t
- do_wifi_command(const char* iface, const char* cmd, char* buff, size_t* len) = 0; // KK == ICS != JB
-
- virtual int32_t
- do_wifi_load_driver() = 0;
-
- virtual int32_t
- do_wifi_unload_driver() = 0;
-
- virtual int32_t
- do_wifi_start_supplicant(int32_t) = 0; // ICS != JB == KK
-
- virtual int32_t
- do_wifi_stop_supplicant(int32_t) = 0; //ICS != JB == KK
-
- virtual int32_t
- do_wifi_connect_to_supplicant(const char* iface) = 0; // KK == ICS != JB
-
- virtual void
- do_wifi_close_supplicant_connection(const char* iface) = 0; // KK == ICS != JB
-};
-
-// Concrete class to use to access the wpa supplicant.
-class WpaSupplicant final
-{
-public:
- WpaSupplicant();
-
- // Use nsCString as the type of aInterface to guarantee it's
- // null-terminated so that we can pass it to c API without
- // conversion
- void WaitForEvent(nsAString& aEvent, const nsCString& aInterface);
- bool ExecuteCommand(CommandOptions aOptions,
- mozilla::dom::WifiResultOptions& result,
- const nsCString& aInterface);
-
-private:
- UniquePtr<WpaSupplicantImpl> mImpl;
- UniquePtr<WifiHotspotUtils> mWifiHotspotUtils;
-
- uint32_t mSdkVersion;
-
-protected:
- void CheckBuffer(char* buffer, int32_t length, nsAString& aEvent);
- uint32_t MakeMask(uint32_t len);
-};
-
-#endif // WifiUtils_h
diff --git a/dom/wifi/WifiWorker.h b/dom/wifi/WifiWorker.h
deleted file mode 100644
index 2cd89c3e7..000000000
--- a/dom/wifi/WifiWorker.h
+++ /dev/null
@@ -1,9 +0,0 @@
-/* -*- 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/. */
-
-#define NS_WIFIWORKER_CID \
-{ 0xA14E8977, 0xD259, 0x433A, \
- { 0xA8, 0x8D, 0x58, 0xDD, 0x44, 0x65, 0x7E, 0x5B } }
diff --git a/dom/wifi/WifiWorker.js b/dom/wifi/WifiWorker.js
deleted file mode 100644
index 243ba8b97..000000000
--- a/dom/wifi/WifiWorker.js
+++ /dev/null
@@ -1,3928 +0,0 @@
-/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
-/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-"use strict";
-
-const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/systemlibs.js");
-Cu.import("resource://gre/modules/FileUtils.jsm");
-Cu.import("resource://gre/modules/WifiCommand.jsm");
-Cu.import("resource://gre/modules/WifiNetUtil.jsm");
-Cu.import("resource://gre/modules/WifiP2pManager.jsm");
-Cu.import("resource://gre/modules/WifiP2pWorkerObserver.jsm");
-
-var DEBUG = false; // set to true to show debug messages.
-
-const WIFIWORKER_CONTRACTID = "@mozilla.org/wifi/worker;1";
-const WIFIWORKER_CID = Components.ID("{a14e8977-d259-433a-a88d-58dd44657e5b}");
-
-const WIFIWORKER_WORKER = "resource://gre/modules/wifi_worker.js";
-
-const kMozSettingsChangedObserverTopic = "mozsettings-changed";
-
-const MAX_RETRIES_ON_AUTHENTICATION_FAILURE = 2;
-const MAX_SUPPLICANT_LOOP_ITERATIONS = 4;
-const MAX_RETRIES_ON_DHCP_FAILURE = 2;
-
-// Settings DB path for wifi
-const SETTINGS_WIFI_ENABLED = "wifi.enabled";
-const SETTINGS_WIFI_DEBUG_ENABLED = "wifi.debugging.enabled";
-// Settings DB path for Wifi tethering.
-const SETTINGS_WIFI_TETHERING_ENABLED = "tethering.wifi.enabled";
-const SETTINGS_WIFI_SSID = "tethering.wifi.ssid";
-const SETTINGS_WIFI_SECURITY_TYPE = "tethering.wifi.security.type";
-const SETTINGS_WIFI_SECURITY_PASSWORD = "tethering.wifi.security.password";
-const SETTINGS_WIFI_IP = "tethering.wifi.ip";
-const SETTINGS_WIFI_PREFIX = "tethering.wifi.prefix";
-const SETTINGS_WIFI_DHCPSERVER_STARTIP = "tethering.wifi.dhcpserver.startip";
-const SETTINGS_WIFI_DHCPSERVER_ENDIP = "tethering.wifi.dhcpserver.endip";
-const SETTINGS_WIFI_DNS1 = "tethering.wifi.dns1";
-const SETTINGS_WIFI_DNS2 = "tethering.wifi.dns2";
-
-// Settings DB path for USB tethering.
-const SETTINGS_USB_DHCPSERVER_STARTIP = "tethering.usb.dhcpserver.startip";
-const SETTINGS_USB_DHCPSERVER_ENDIP = "tethering.usb.dhcpserver.endip";
-
-// Default value for WIFI tethering.
-const DEFAULT_WIFI_IP = "192.168.1.1";
-const DEFAULT_WIFI_PREFIX = "24";
-const DEFAULT_WIFI_DHCPSERVER_STARTIP = "192.168.1.10";
-const DEFAULT_WIFI_DHCPSERVER_ENDIP = "192.168.1.30";
-const DEFAULT_WIFI_SSID = "FirefoxHotspot";
-const DEFAULT_WIFI_SECURITY_TYPE = "open";
-const DEFAULT_WIFI_SECURITY_PASSWORD = "1234567890";
-const DEFAULT_DNS1 = "8.8.8.8";
-const DEFAULT_DNS2 = "8.8.4.4";
-
-// Default value for USB tethering.
-const DEFAULT_USB_DHCPSERVER_STARTIP = "192.168.0.10";
-const DEFAULT_USB_DHCPSERVER_ENDIP = "192.168.0.30";
-
-const WIFI_FIRMWARE_AP = "AP";
-const WIFI_FIRMWARE_STATION = "STA";
-const WIFI_SECURITY_TYPE_NONE = "open";
-const WIFI_SECURITY_TYPE_WPA_PSK = "wpa-psk";
-const WIFI_SECURITY_TYPE_WPA2_PSK = "wpa2-psk";
-
-const NETWORK_INTERFACE_UP = "up";
-const NETWORK_INTERFACE_DOWN = "down";
-
-const DEFAULT_WLAN_INTERFACE = "wlan0";
-
-const DRIVER_READY_WAIT = 2000;
-
-const SUPP_PROP = "init.svc.wpa_supplicant";
-const WPA_SUPPLICANT = "wpa_supplicant";
-const DHCP_PROP = "init.svc.dhcpcd";
-const DHCP = "dhcpcd";
-
-const MODE_ESS = 0;
-const MODE_IBSS = 1;
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkManager",
- "@mozilla.org/network/manager;1",
- "nsINetworkManager");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gNetworkService",
- "@mozilla.org/network/service;1",
- "nsINetworkService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gSettingsService",
- "@mozilla.org/settingsService;1",
- "nsISettingsService");
-
-XPCOMUtils.defineLazyServiceGetter(this, "gTetheringService",
- "@mozilla.org/tethering/service;1",
- "nsITetheringService");
-
-// A note about errors and error handling in this file:
-// The libraries that we use in this file are intended for C code. For
-// C code, it is natural to return -1 for errors and 0 for success.
-// Therefore, the code that interacts directly with the worker uses this
-// convention (note: command functions do get boolean results since the
-// command always succeeds and we do a string/boolean check for the
-// expected results).
-var WifiManager = (function() {
- var manager = {};
-
- function getStartupPrefs() {
- return {
- sdkVersion: parseInt(libcutils.property_get("ro.build.version.sdk"), 10),
- unloadDriverEnabled: libcutils.property_get("ro.moz.wifi.unloaddriver") === "1",
- schedScanRecovery: libcutils.property_get("ro.moz.wifi.sched_scan_recover") === "false" ? false : true,
- driverDelay: libcutils.property_get("ro.moz.wifi.driverDelay"),
- p2pSupported: libcutils.property_get("ro.moz.wifi.p2p_supported") === "1",
- eapSimSupported: libcutils.property_get("ro.moz.wifi.eapsim_supported") === "1",
- ibssSupported: libcutils.property_get("ro.moz.wifi.ibss_supported", "true") === "true",
- ifname: libcutils.property_get("wifi.interface")
- };
- }
-
- let {sdkVersion, unloadDriverEnabled, schedScanRecovery,
- driverDelay, p2pSupported, eapSimSupported, ibssSupported, ifname} = getStartupPrefs();
-
- let capabilities = {
- security: ["OPEN", "WEP", "WPA-PSK", "WPA-EAP"],
- eapMethod: ["PEAP", "TTLS", "TLS"],
- eapPhase2: ["MSCHAPV2"],
- certificate: ["SERVER"],
- mode: [MODE_ESS]
- };
- if (eapSimSupported) {
- capabilities.eapMethod.unshift("SIM");
- }
- if (ibssSupported) {
- capabilities.mode.push(MODE_IBSS);
- }
-
- let wifiListener = {
- onWaitEvent: function(event, iface) {
- if (manager.ifname === iface && handleEvent(event)) {
- waitForEvent(iface);
- } else if (p2pSupported) {
- // Please refer to
- // http://androidxref.com/4.4.2_r1/xref/frameworks/base/wifi/java/android/net/wifi/WifiMonitor.java#519
- // for interface event mux/demux rules. In short words, both
- // 'p2p0' and 'p2p-' should go to Wifi P2P state machine.
- if (WifiP2pManager.INTERFACE_NAME === iface || -1 !== iface.indexOf('p2p-')) {
- // If the connection is closed, wifi.c::wifi_wait_for_event()
- // will still return 'CTRL-EVENT-TERMINATING - connection closed'
- // rather than blocking. So when we see this special event string,
- // just return immediately.
- const TERMINATED_EVENT = 'CTRL-EVENT-TERMINATING - connection closed';
- if (-1 !== event.indexOf(TERMINATED_EVENT)) {
- return;
- }
- p2pManager.handleEvent(event);
- waitForEvent(iface);
- }
- }
- },
-
- onCommand: function(event, iface) {
- onmessageresult(event, iface);
- }
- }
-
- manager.ifname = ifname;
- manager.connectToSupplicant = false;
- // Emulator build runs to here.
- // The debug() should only be used after WifiManager.
- if (!ifname) {
- manager.ifname = DEFAULT_WLAN_INTERFACE;
- }
- manager.schedScanRecovery = schedScanRecovery;
- manager.driverDelay = driverDelay ? parseInt(driverDelay, 10) : DRIVER_READY_WAIT;
-
- // Regular Wifi stuff.
- var netUtil = WifiNetUtil(controlMessage);
- var wifiCommand = WifiCommand(controlMessage, manager.ifname, sdkVersion);
-
- // Wifi P2P stuff
- var p2pManager;
- if (p2pSupported) {
- let p2pCommand = WifiCommand(controlMessage, WifiP2pManager.INTERFACE_NAME, sdkVersion);
- p2pManager = WifiP2pManager(p2pCommand, netUtil);
- }
-
- let wifiService = Cc["@mozilla.org/wifi/service;1"];
- if (wifiService) {
- wifiService = wifiService.getService(Ci.nsIWifiProxyService);
- let interfaces = [manager.ifname];
- if (p2pSupported) {
- interfaces.push(WifiP2pManager.INTERFACE_NAME);
- }
- wifiService.start(wifiListener, interfaces, interfaces.length);
- } else {
- debug("No wifi service component available!");
- }
-
- // Callbacks to invoke when a reply arrives from the wifi service.
- var controlCallbacks = Object.create(null);
- var idgen = 0;
-
- function controlMessage(obj, callback) {
- var id = idgen++;
- obj.id = id;
- if (callback) {
- controlCallbacks[id] = callback;
- }
- wifiService.sendCommand(obj, obj.iface);
- }
-
- let onmessageresult = function(data, iface) {
- var id = data.id;
- var callback = controlCallbacks[id];
- if (callback) {
- callback(data);
- delete controlCallbacks[id];
- }
- }
-
- // Polling the status worker
- var recvErrors = 0;
-
- function waitForEvent(iface) {
- wifiService.waitForEvent(iface);
- }
-
- // Commands to the control worker.
-
- var driverLoaded = false;
-
- function loadDriver(callback) {
- if (driverLoaded) {
- callback(0);
- return;
- }
-
- wifiCommand.loadDriver(function (status) {
- driverLoaded = (status >= 0);
- callback(status)
- });
- }
-
- function unloadDriver(type, callback) {
- if (!unloadDriverEnabled) {
- // Unloading drivers is generally unnecessary and
- // can trigger bugs in some drivers.
- // On properly written drivers, bringing the interface
- // down powers down the interface.
- if (type === WIFI_FIRMWARE_STATION) {
- notify("supplicantlost", { success: true });
- }
- callback(0);
- return;
- }
-
- wifiCommand.unloadDriver(function(status) {
- driverLoaded = (status < 0);
- if (type === WIFI_FIRMWARE_STATION) {
- notify("supplicantlost", { success: true });
- }
- callback(status);
- });
- }
-
- // A note about background scanning:
- // Normally, background scanning shouldn't be necessary as wpa_supplicant
- // has the capability to automatically schedule its own scans at appropriate
- // intervals. However, with some drivers, this appears to get stuck after
- // three scans, so we enable the driver's background scanning to work around
- // that when we're not connected to any network. This ensures that we'll
- // automatically reconnect to networks if one falls out of range.
- var reEnableBackgroundScan = false;
-
- // NB: This is part of the internal API.
- manager.backgroundScanEnabled = false;
- function setBackgroundScan(enable, callback) {
- var doEnable = (enable === "ON");
- if (doEnable === manager.backgroundScanEnabled) {
- callback(false, true);
- return;
- }
-
- manager.backgroundScanEnabled = doEnable;
- wifiCommand.setBackgroundScan(manager.backgroundScanEnabled, callback);
- }
-
- var scanModeActive = false;
-
- function scan(forceActive, callback) {
- if (forceActive && !scanModeActive) {
- // Note: we ignore errors from doSetScanMode.
- wifiCommand.doSetScanMode(true, function(ignore) {
- setBackgroundScan("OFF", function(turned, ignore) {
- reEnableBackgroundScan = turned;
- manager.handlePreWifiScan();
- wifiCommand.scan(function(ok) {
- wifiCommand.doSetScanMode(false, function(ignore) {
- // The result of scanCommand is the result of the actual SCAN
- // request.
- callback(ok);
- });
- });
- });
- });
- return;
- }
- manager.handlePreWifiScan();
- wifiCommand.scan(callback);
- }
-
- var debugEnabled = false;
-
- function syncDebug() {
- if (debugEnabled !== DEBUG) {
- let wanted = DEBUG;
- wifiCommand.setLogLevel(wanted ? "DEBUG" : "INFO", function(ok) {
- if (ok)
- debugEnabled = wanted;
- });
- if (p2pSupported && p2pManager) {
- p2pManager.setDebug(DEBUG);
- }
- }
- }
-
- function getDebugEnabled(callback) {
- wifiCommand.getLogLevel(function(level) {
- if (level === null) {
- debug("Unable to get wpa_supplicant's log level");
- callback(false);
- return;
- }
-
- var lines = level.split("\n");
- for (let i = 0; i < lines.length; ++i) {
- let match = /Current level: (.*)/.exec(lines[i]);
- if (match) {
- debugEnabled = match[1].toLowerCase() === "debug";
- callback(true);
- return;
- }
- }
-
- // If we're here, we didn't get the current level.
- callback(false);
- });
- }
-
- function setScanMode(setActive, callback) {
- scanModeActive = setActive;
- wifiCommand.doSetScanMode(setActive, callback);
- }
-
- var httpProxyConfig = Object.create(null);
-
- /**
- * Given a network, configure http proxy when using wifi.
- * @param network A network object to update http proxy
- * @param info Info should have following field:
- * - httpProxyHost ip address of http proxy.
- * - httpProxyPort port of http proxy, set 0 to use default port 8080.
- * @param callback callback function.
- */
- function configureHttpProxy(network, info, callback) {
- if (!network)
- return;
-
- let networkKey = getNetworkKey(network);
-
- if (!info || info.httpProxyHost === "") {
- delete httpProxyConfig[networkKey];
- } else {
- httpProxyConfig[networkKey] = network;
- httpProxyConfig[networkKey].httpProxyHost = info.httpProxyHost;
- httpProxyConfig[networkKey].httpProxyPort = info.httpProxyPort;
- }
-
- callback(true);
- }
-
- function getHttpProxyNetwork(network) {
- if (!network)
- return null;
-
- let networkKey = getNetworkKey(network);
- return httpProxyConfig[networkKey];
- }
-
- function setHttpProxy(network) {
- if (!network)
- return;
-
- // If we got here, arg network must be the currentNetwork, so we just update
- // WifiNetworkInterface correspondingly and notify NetworkManager.
- WifiNetworkInterface.httpProxyHost = network.httpProxyHost;
- WifiNetworkInterface.httpProxyPort = network.httpProxyPort;
-
- if (WifiNetworkInterface.info.state ==
- Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED) {
- gNetworkManager.updateNetworkInterface(WifiNetworkInterface);
- }
- }
-
- var staticIpConfig = Object.create(null);
- function setStaticIpMode(network, info, callback) {
- let setNetworkKey = getNetworkKey(network);
- let curNetworkKey = null;
- let currentNetwork = Object.create(null);
- currentNetwork.netId = manager.connectionInfo.id;
-
- manager.getNetworkConfiguration(currentNetwork, function () {
- curNetworkKey = getNetworkKey(currentNetwork);
-
- // Add additional information to static ip configuration
- // It is used to compatiable with information dhcp callback.
- info.ipaddr = netHelpers.stringToIP(info.ipaddr_str);
- info.gateway = netHelpers.stringToIP(info.gateway_str);
- info.mask_str = netHelpers.ipToString(netHelpers.makeMask(info.maskLength));
-
- // Optional
- info.dns1 = netHelpers.stringToIP(info.dns1_str);
- info.dns2 = netHelpers.stringToIP(info.dns2_str);
- info.proxy = netHelpers.stringToIP(info.proxy_str);
-
- staticIpConfig[setNetworkKey] = info;
-
- // If the ssid of current connection is the same as configured ssid
- // It means we need update current connection to use static IP address.
- if (setNetworkKey == curNetworkKey) {
- // Use configureInterface directly doesn't work, the network interface
- // and routing table is changed but still cannot connect to network
- // so the workaround here is disable interface the enable again to
- // trigger network reconnect with static ip.
- gNetworkService.disableInterface(manager.ifname, function (ok) {
- gNetworkService.enableInterface(manager.ifname, function (ok) {
- callback(ok);
- });
- });
- return;
- }
-
- callback(true);
- });
- }
-
- var dhcpInfo = null;
-
- function runStaticIp(ifname, key) {
- debug("Run static ip");
-
- // Read static ip information from settings.
- let staticIpInfo;
-
- if (!(key in staticIpConfig))
- return;
-
- staticIpInfo = staticIpConfig[key];
-
- // Stop dhcpd when use static IP
- if (dhcpInfo != null) {
- netUtil.stopDhcp(manager.ifname, function() {});
- }
-
- // Set ip, mask length, gateway, dns to network interface
- gNetworkService.configureInterface( { ifname: ifname,
- ipaddr: staticIpInfo.ipaddr,
- mask: staticIpInfo.maskLength,
- gateway: staticIpInfo.gateway,
- dns1: staticIpInfo.dns1,
- dns2: staticIpInfo.dns2 }, function (data) {
- netUtil.runIpConfig(ifname, staticIpInfo, function(data) {
- dhcpInfo = data.info;
- notify("networkconnected", data);
- });
- });
- }
-
- var suppressEvents = false;
- function notify(eventName, eventObject) {
- if (suppressEvents)
- return;
- var handler = manager["on" + eventName];
- if (handler) {
- if (!eventObject)
- eventObject = ({});
- handler.call(eventObject);
- }
- }
-
- function notifyStateChange(fields) {
- // If we're already in the COMPLETED state, we might receive events from
- // the supplicant that tell us that we're re-authenticating or reminding
- // us that we're associated to a network. In those cases, we don't need to
- // do anything, so just ignore them.
- if (manager.state === "COMPLETED" &&
- fields.state !== "DISCONNECTED" &&
- fields.state !== "INTERFACE_DISABLED" &&
- fields.state !== "INACTIVE" &&
- fields.state !== "SCANNING") {
- return false;
- }
-
- // Stop background scanning if we're trying to connect to a network.
- if (manager.backgroundScanEnabled &&
- (fields.state === "ASSOCIATING" ||
- fields.state === "ASSOCIATED" ||
- fields.state === "FOUR_WAY_HANDSHAKE" ||
- fields.state === "GROUP_HANDSHAKE" ||
- fields.state === "COMPLETED")) {
- setBackgroundScan("OFF", function() {});
- }
-
- fields.prevState = manager.state;
- // Detect wpa_supplicant's loop iterations.
- manager.supplicantLoopDetection(fields.prevState, fields.state);
- notify("statechange", fields);
-
- // Don't update state when and after disabling.
- if (manager.state === "DISABLING" ||
- manager.state === "UNINITIALIZED") {
- return false;
- }
-
- manager.state = fields.state;
- return true;
- }
-
- function parseStatus(status) {
- if (status === null) {
- debug("Unable to get wpa supplicant's status");
- return;
- }
-
- var ssid;
- var bssid;
- var state;
- var ip_address;
- var id;
-
- var lines = status.split("\n");
- for (let i = 0; i < lines.length; ++i) {
- let [key, value] = lines[i].split("=");
- switch (key) {
- case "wpa_state":
- state = value;
- break;
- case "ssid":
- ssid = value;
- break;
- case "bssid":
- bssid = value;
- break;
- case "ip_address":
- ip_address = value;
- break;
- case "id":
- id = value;
- break;
- }
- }
-
- if (bssid && ssid) {
- manager.connectionInfo.bssid = bssid;
- manager.connectionInfo.ssid = ssid;
- manager.connectionInfo.id = id;
- }
-
- if (ip_address)
- dhcpInfo = { ip_address: ip_address };
-
- notifyStateChange({ state: state, fromStatus: true });
-
- // If we parse the status and the supplicant has already entered the
- // COMPLETED state, then we need to set up DHCP right away.
- if (state === "COMPLETED")
- onconnected();
- }
-
- // try to connect to the supplicant
- var connectTries = 0;
- var retryTimer = null;
- function connectCallback(ok) {
- if (ok === 0) {
- // Tell the event worker to start waiting for events.
- retryTimer = null;
- connectTries = 0;
- recvErrors = 0;
- manager.connectToSupplicant = true;
- didConnectSupplicant(function(){});
- return;
- }
- if (connectTries++ < 5) {
- // Try again in 1 seconds.
- if (!retryTimer)
- retryTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
-
- retryTimer.initWithCallback(function(timer) {
- wifiCommand.connectToSupplicant(connectCallback);
- }, 1000, Ci.nsITimer.TYPE_ONE_SHOT);
- return;
- }
-
- retryTimer = null;
- connectTries = 0;
- notify("supplicantlost", { success: false });
- }
-
- manager.connectionDropped = function(callback) {
- // Reset network interface when connection drop
- gNetworkService.configureInterface( { ifname: manager.ifname,
- ipaddr: 0,
- mask: 0,
- gateway: 0,
- dns1: 0,
- dns2: 0 }, function (data) {
- });
-
- // If we got disconnected, kill the DHCP client in preparation for
- // reconnection.
- gNetworkService.resetConnections(manager.ifname, function() {
- netUtil.stopDhcp(manager.ifname, function() {
- callback();
- });
- });
- }
-
- manager.start = function() {
- debug("detected SDK version " + sdkVersion);
- wifiCommand.connectToSupplicant(connectCallback);
- }
-
- let dhcpRequestGen = 0;
-
- function onconnected() {
- // For now we do our own DHCP. In the future, this should be handed
- // off to the Network Manager.
- let currentNetwork = Object.create(null);
- currentNetwork.netId = manager.connectionInfo.id;
-
- manager.getNetworkConfiguration(currentNetwork, function (){
- let key = getNetworkKey(currentNetwork);
- if (staticIpConfig &&
- (key in staticIpConfig) &&
- staticIpConfig[key].enabled) {
- debug("Run static ip");
- runStaticIp(manager.ifname, key);
- return;
- }
- netUtil.runDhcp(manager.ifname, dhcpRequestGen++, function(data, gen) {
- dhcpInfo = data.info;
- debug('dhcpRequestGen: ' + dhcpRequestGen + ', gen: ' + gen);
- if (!dhcpInfo) {
- if (gen + 1 < dhcpRequestGen) {
- debug('Do not bother younger DHCP request.');
- return;
- }
- if (++manager.dhcpFailuresCount >= MAX_RETRIES_ON_DHCP_FAILURE) {
- manager.dhcpFailuresCount = 0;
- notify("disconnected", {connectionInfo: manager.connectionInfo});
- return;
- }
- // NB: We have to call disconnect first. Otherwise, we only reauth with
- // the existing AP and don't retrigger DHCP.
- manager.disconnect(function() {
- manager.reassociate(function(){});
- });
- return;
- }
-
- manager.dhcpFailuresCount = 0;
- notify("networkconnected", data);
- });
- });
- }
-
- var supplicantStatesMap = (sdkVersion >= 15) ?
- ["DISCONNECTED", "INTERFACE_DISABLED", "INACTIVE", "SCANNING",
- "AUTHENTICATING", "ASSOCIATING", "ASSOCIATED", "FOUR_WAY_HANDSHAKE",
- "GROUP_HANDSHAKE", "COMPLETED"]
- :
- ["DISCONNECTED", "INACTIVE", "SCANNING", "ASSOCIATING",
- "ASSOCIATED", "FOUR_WAY_HANDSHAKE", "GROUP_HANDSHAKE",
- "COMPLETED", "DORMANT", "UNINITIALIZED"];
-
- var driverEventMap = { STOPPED: "driverstopped", STARTED: "driverstarted", HANGED: "driverhung" };
-
- manager.getNetworkId = function (ssid, callback) {
- manager.getConfiguredNetworks(function(networks) {
- if (!networks) {
- debug("Unable to get configured networks");
- return callback(null);
- }
- for (let net in networks) {
- let network = networks[net];
- // Trying to get netId from
- // 1. network matching SSID if SSID is provided.
- // 2. current network if no SSID is provided, it's not guaranteed that
- // current network matches requested SSID.
- if ((!ssid && network.status === "CURRENT") ||
- (ssid && network.ssid && ssid === dequote(network.ssid))) {
- return callback(net);
- }
- }
- callback(null);
- });
- }
-
- function handleWpaEapEvents(event) {
- if (event.indexOf("CTRL-EVENT-EAP-FAILURE") !== -1) {
- if (event.indexOf("EAP authentication failed") !== -1) {
- notify("passwordmaybeincorrect");
- if (manager.authenticationFailuresCount > MAX_RETRIES_ON_AUTHENTICATION_FAILURE) {
- manager.authenticationFailuresCount = 0;
- notify("disconnected", {connectionInfo: manager.connectionInfo});
- }
- }
- return true;
- }
- if (event.indexOf("CTRL-EVENT-EAP-TLS-CERT-ERROR") !== -1) {
- // Cert Error
- notify("passwordmaybeincorrect");
- if (manager.authenticationFailuresCount > MAX_RETRIES_ON_AUTHENTICATION_FAILURE) {
- manager.authenticationFailuresCount = 0;
- notify("disconnected", {connectionInfo: manager.connectionInfo});
- }
- return true;
- }
- if (event.indexOf("CTRL-EVENT-EAP-STARTED") !== -1) {
- notifyStateChange({ state: "AUTHENTICATING" });
- return true;
- }
- return true;
- }
-
- // Handle events sent to us by the event worker.
- function handleEvent(event) {
- debug("Event coming in: " + event);
- if (event.indexOf("CTRL-EVENT-") !== 0 && event.indexOf("WPS") !== 0) {
- // Handle connection fail exception on WEP-128, while password length
- // is not 5 nor 13 bytes.
- if (event.indexOf("Association request to the driver failed") !== -1) {
- notify("passwordmaybeincorrect");
- if (manager.authenticationFailuresCount > MAX_RETRIES_ON_AUTHENTICATION_FAILURE) {
- manager.authenticationFailuresCount = 0;
- notify("disconnected", {connectionInfo: manager.connectionInfo});
- }
- return true;
- }
-
- if (event.indexOf("WPA:") == 0 &&
- event.indexOf("pre-shared key may be incorrect") != -1) {
- notify("passwordmaybeincorrect");
- }
-
- // This is ugly, but we need to grab the SSID here. BSSID is not guaranteed
- // to be provided, so don't grab BSSID here.
- var match = /Trying to associate with.*SSID[ =]'(.*)'/.exec(event);
- if (match) {
- debug("Matched: " + match[1] + "\n");
- manager.connectionInfo.ssid = match[1];
- }
- return true;
- }
-
- var space = event.indexOf(" ");
- var eventData = event.substr(0, space + 1);
- if (eventData.indexOf("CTRL-EVENT-STATE-CHANGE") === 0) {
- // Parse the event data.
- var fields = {};
- var tokens = event.substr(space + 1).split(" ");
- for (var n = 0; n < tokens.length; ++n) {
- var kv = tokens[n].split("=");
- if (kv.length === 2)
- fields[kv[0]] = kv[1];
- }
- if (!("state" in fields))
- return true;
- fields.state = supplicantStatesMap[fields.state];
-
- // The BSSID field is only valid in the ASSOCIATING and ASSOCIATED
- // states, except when we "reauth", except this seems to depend on the
- // driver, so simply check to make sure that we don't have a null BSSID.
- if (fields.BSSID !== "00:00:00:00:00:00")
- manager.connectionInfo.bssid = fields.BSSID;
-
- if (notifyStateChange(fields) && fields.state === "COMPLETED") {
- onconnected();
- }
- return true;
- }
- if (eventData.indexOf("CTRL-EVENT-DRIVER-STATE") === 0) {
- var handlerName = driverEventMap[eventData];
- if (handlerName)
- notify(handlerName);
- return true;
- }
- if (eventData.indexOf("CTRL-EVENT-TERMINATING") === 0) {
- // As long the monitor socket is not closed and we haven't seen too many
- // recv errors yet, we will keep going for a bit longer.
- if (event.indexOf("connection closed") === -1 &&
- event.indexOf("recv error") !== -1 && ++recvErrors < 10)
- return true;
-
- notifyStateChange({ state: "DISCONNECTED", BSSID: null, id: -1 });
-
- // If the supplicant is terminated as commanded, the supplicant lost
- // notification will be sent after driver unloaded. In such case, the
- // manager state will be "DISABLING" or "UNINITIALIZED".
- // So if supplicant terminated with incorrect manager state, implying
- // unexpected condition, we should notify supplicant lost here.
- if (manager.state !== "DISABLING" && manager.state !== "UNINITIALIZED") {
- notify("supplicantlost", { success: true });
- }
-
- if (manager.stopSupplicantCallback) {
- cancelWaitForTerminateEventTimer();
- // It's possible that the terminating event triggered by timer comes
- // earlier than the event from wpa_supplicant. Since
- // stopSupplicantCallback contains async. callbacks, swap it to local
- // to prevent calling the callback twice.
- let stopSupplicantCallback = manager.stopSupplicantCallback.bind(manager);
- manager.stopSupplicantCallback = null;
- stopSupplicantCallback();
- stopSupplicantCallback = null;
- }
- return false;
- }
- if (eventData.indexOf("CTRL-EVENT-DISCONNECTED") === 0) {
- var token = event.split(" ")[1];
- var bssid = token.split("=")[1];
- if (manager.authenticationFailuresCount > MAX_RETRIES_ON_AUTHENTICATION_FAILURE) {
- manager.authenticationFailuresCount = 0;
- notify("disconnected", {connectionInfo: manager.connectionInfo});
- }
- manager.connectionInfo.bssid = null;
- manager.connectionInfo.ssid = null;
- manager.connectionInfo.id = -1;
- return true;
- }
- if (eventData.indexOf("CTRL-EVENT-CONNECTED") === 0) {
- // Format: CTRL-EVENT-CONNECTED - Connection to 00:1e:58:ec:d5:6d completed (reauth) [id=1 id_str=]
- var bssid = event.split(" ")[4];
-
- var keyword = "id=";
- var id = event.substr(event.indexOf(keyword) + keyword.length).split(" ")[0];
- // Read current BSSID here, it will always being provided.
- manager.connectionInfo.id = id;
- manager.connectionInfo.bssid = bssid;
- return true;
- }
- if (eventData.indexOf("CTRL-EVENT-SCAN-RESULTS") === 0) {
- debug("Notifying of scan results available");
- if (reEnableBackgroundScan) {
- reEnableBackgroundScan = false;
- setBackgroundScan("ON", function() {});
- }
- manager.handlePostWifiScan();
- notify("scanresultsavailable");
- return true;
- }
- if (eventData.indexOf("CTRL-EVENT-EAP") === 0) {
- return handleWpaEapEvents(event);
- }
- if (eventData.indexOf("CTRL-EVENT-ASSOC-REJECT") === 0) {
- debug("CTRL-EVENT-ASSOC-REJECT: network error");
- notify("passwordmaybeincorrect");
- if (manager.authenticationFailuresCount > MAX_RETRIES_ON_AUTHENTICATION_FAILURE) {
- manager.authenticationFailuresCount = 0;
- debug("CTRL-EVENT-ASSOC-REJECT: disconnect network");
- notify("disconnected", {connectionInfo: manager.connectionInfo});
- }
- return true;
- }
- if (eventData.indexOf("WPS-TIMEOUT") === 0) {
- notifyStateChange({ state: "WPS_TIMEOUT", BSSID: null, id: -1 });
- return true;
- }
- if (eventData.indexOf("WPS-FAIL") === 0) {
- notifyStateChange({ state: "WPS_FAIL", BSSID: null, id: -1 });
- return true;
- }
- if (eventData.indexOf("WPS-OVERLAP-DETECTED") === 0) {
- notifyStateChange({ state: "WPS_OVERLAP_DETECTED", BSSID: null, id: -1 });
- return true;
- }
- // Unknown event.
- return true;
- }
-
- function setPowerSavingMode(enabled) {
- let mode = enabled ? "AUTO" : "ACTIVE";
- // Some wifi drivers may not implement this command. Set power mode
- // even if suspend optimization command failed.
- manager.setSuspendOptimizations(enabled, function(ok) {
- manager.setPowerMode(mode, function() {});
- });
- }
-
- function didConnectSupplicant(callback) {
- waitForEvent(manager.ifname);
-
- // Load up the supplicant state.
- getDebugEnabled(function(ok) {
- syncDebug();
- });
- wifiCommand.status(function(status) {
- parseStatus(status);
- notify("supplicantconnection");
- callback();
- });
- // WPA supplicant already connected.
- manager.setPowerSavingMode(true);
- if (p2pSupported) {
- manager.enableP2p(function(success) {});
- }
- }
-
- function prepareForStartup(callback) {
- let status = libcutils.property_get(DHCP_PROP + "_" + manager.ifname);
- if (status !== "running") {
- tryStopSupplicant();
- return;
- }
- manager.connectionDropped(function() {
- tryStopSupplicant();
- });
-
- // Ignore any errors and kill any currently-running supplicants. On some
- // phones, stopSupplicant won't work for a supplicant that we didn't
- // start, so we hand-roll it here.
- function tryStopSupplicant () {
- let status = libcutils.property_get(SUPP_PROP);
- if (status !== "running") {
- callback();
- return;
- }
- suppressEvents = true;
- wifiCommand.killSupplicant(function() {
- gNetworkService.disableInterface(manager.ifname, function (ok) {
- suppressEvents = false;
- callback();
- });
- });
- }
- }
-
- // Initial state.
- manager.state = "UNINITIALIZED";
- manager.tetheringState = "UNINITIALIZED";
- manager.supplicantStarted = false;
- manager.connectionInfo = { ssid: null, bssid: null, id: -1 };
- manager.authenticationFailuresCount = 0;
- manager.loopDetectionCount = 0;
- manager.dhcpFailuresCount = 0;
- manager.stopSupplicantCallback = null;
-
- manager.__defineGetter__("enabled", function() {
- switch (manager.state) {
- case "UNINITIALIZED":
- case "INITIALIZING":
- case "DISABLING":
- return false;
- default:
- return true;
- }
- });
-
- var waitForTerminateEventTimer = null;
- function cancelWaitForTerminateEventTimer() {
- if (waitForTerminateEventTimer) {
- waitForTerminateEventTimer.cancel();
- waitForTerminateEventTimer = null;
- }
- };
- function createWaitForTerminateEventTimer(onTimeout) {
- if (waitForTerminateEventTimer) {
- return;
- }
- waitForTerminateEventTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- waitForTerminateEventTimer.initWithCallback(onTimeout,
- 4000,
- Ci.nsITimer.TYPE_ONE_SHOT);
- };
-
- var waitForDriverReadyTimer = null;
- function cancelWaitForDriverReadyTimer() {
- if (waitForDriverReadyTimer) {
- waitForDriverReadyTimer.cancel();
- waitForDriverReadyTimer = null;
- }
- };
- function createWaitForDriverReadyTimer(onTimeout) {
- waitForDriverReadyTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- waitForDriverReadyTimer.initWithCallback(onTimeout,
- manager.driverDelay,
- Ci.nsITimer.TYPE_ONE_SHOT);
- };
-
- // Public interface of the wifi service.
- manager.setWifiEnabled = function(enabled, callback) {
- if (enabled === manager.isWifiEnabled(manager.state)) {
- callback("no change");
- return;
- }
-
- if (enabled) {
- manager.state = "INITIALIZING";
- // Register as network interface.
- WifiNetworkInterface.info.name = manager.ifname;
- if (!WifiNetworkInterface.registered) {
- gNetworkManager.registerNetworkInterface(WifiNetworkInterface);
- WifiNetworkInterface.registered = true;
- }
- WifiNetworkInterface.info.state =
- Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED;
- WifiNetworkInterface.info.ips = [];
- WifiNetworkInterface.info.prefixLengths = [];
- WifiNetworkInterface.info.gateways = [];
- WifiNetworkInterface.info.dnses = [];
- gNetworkManager.updateNetworkInterface(WifiNetworkInterface);
-
- prepareForStartup(function() {
- loadDriver(function (status) {
- if (status < 0) {
- callback(status);
- manager.state = "UNINITIALIZED";
- return;
- }
- // This command is mandatory for Nexus 4. But some devices like
- // Galaxy S2 don't support it. Continue to start wpa_supplicant
- // even if we fail to set wifi operation mode to station.
- gNetworkService.setWifiOperationMode(manager.ifname,
- WIFI_FIRMWARE_STATION,
- function (status) {
-
- function startSupplicantInternal() {
- wifiCommand.startSupplicant(function (status) {
- if (status < 0) {
- unloadDriver(WIFI_FIRMWARE_STATION, function() {
- callback(status);
- });
- manager.state = "UNINITIALIZED";
- return;
- }
-
- manager.supplicantStarted = true;
- gNetworkService.enableInterface(manager.ifname, function (ok) {
- callback(ok ? 0 : -1);
- });
- });
- }
-
- function doStartSupplicant() {
- cancelWaitForDriverReadyTimer();
-
- if (!manager.connectToSupplicant) {
- startSupplicantInternal();
- return;
- }
- wifiCommand.closeSupplicantConnection(function () {
- manager.connectToSupplicant = false;
- // closeSupplicantConnection() will trigger onsupplicantlost
- // and set manager.state to "UNINITIALIZED", we have to
- // restore it here.
- manager.state = "INITIALIZING";
- startSupplicantInternal();
- });
- }
- // Driver startup on certain platforms takes longer than it takes for us
- // to return from loadDriver, so wait 2 seconds before starting
- // the supplicant to give it a chance to start.
- if (manager.driverDelay > 0) {
- createWaitForDriverReadyTimer(doStartSupplicant);
- } else {
- doStartSupplicant();
- }
- });
- });
- });
- } else {
- manager.state = "DISABLING";
- // Note these following calls ignore errors. If we fail to kill the
- // supplicant gracefully, then we need to continue telling it to die
- // until it does.
- let doDisableWifi = function() {
- manager.stopSupplicantCallback = (function () {
- wifiCommand.stopSupplicant(function (status) {
- wifiCommand.closeSupplicantConnection(function() {
- manager.connectToSupplicant = false;
- manager.state = "UNINITIALIZED";
- gNetworkService.disableInterface(manager.ifname, function (ok) {
- unloadDriver(WIFI_FIRMWARE_STATION, callback);
- });
- });
- });
- }).bind(this);
-
- let terminateEventCallback = (function() {
- handleEvent("CTRL-EVENT-TERMINATING");
- }).bind(this);
- createWaitForTerminateEventTimer(terminateEventCallback);
-
- // We are going to terminate the connection between wpa_supplicant.
- // Stop the polling timer immediately to prevent connection info update
- // command blocking in control thread until socket timeout.
- notify("stopconnectioninfotimer");
-
- wifiCommand.terminateSupplicant(function (ok) {
- manager.connectionDropped(function () {
- });
- });
- }
-
- if (p2pSupported) {
- p2pManager.setEnabled(false, { onDisabled: doDisableWifi });
- } else {
- doDisableWifi();
- }
- }
- }
-
- var wifiHotspotStatusTimer = null;
- function cancelWifiHotspotStatusTimer() {
- if (wifiHotspotStatusTimer) {
- wifiHotspotStatusTimer.cancel();
- wifiHotspotStatusTimer = null;
- }
- }
-
- function createWifiHotspotStatusTimer(onTimeout) {
- wifiHotspotStatusTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- wifiHotspotStatusTimer.init(onTimeout, 5000, Ci.nsITimer.TYPE_REPEATING_SLACK);
- }
-
- // Get wifi interface and load wifi driver when enable Ap mode.
- manager.setWifiApEnabled = function(enabled, configuration, callback) {
- if (enabled === manager.isWifiTetheringEnabled(manager.tetheringState)) {
- callback("no change");
- return;
- }
-
- if (enabled) {
- manager.tetheringState = "INITIALIZING";
- loadDriver(function (status) {
- if (status < 0) {
- callback();
- manager.tetheringState = "UNINITIALIZED";
- if (wifiHotspotStatusTimer) {
- cancelWifiHotspotStatusTimer();
- wifiCommand.closeHostapdConnection(function(result) {
- });
- }
- return;
- }
-
- function getWifiHotspotStatus() {
- wifiCommand.hostapdGetStations(function(result) {
- notify("stationinfoupdate", {station: result});
- });
- }
-
- function doStartWifiTethering() {
- cancelWaitForDriverReadyTimer();
- WifiNetworkInterface.info.name =
- libcutils.property_get("wifi.tethering.interface", manager.ifname);
- gTetheringService.setWifiTethering(enabled,
- WifiNetworkInterface.info.name,
- configuration, function(result) {
- if (result) {
- manager.tetheringState = "UNINITIALIZED";
- } else {
- manager.tetheringState = "COMPLETED";
- wifiCommand.connectToHostapd(function(result) {
- if (result) {
- return;
- }
- // Create a timer to track the connection status.
- createWifiHotspotStatusTimer(getWifiHotspotStatus);
- });
- }
- // Pop out current request.
- callback();
- // Should we fire a dom event if we fail to set wifi tethering ?
- debug("Enable Wifi tethering result: " + (result ? result : "successfully"));
- });
- }
-
- // Driver startup on certain platforms takes longer than it takes
- // for us to return from loadDriver, so wait 2 seconds before
- // turning on Wifi tethering.
- createWaitForDriverReadyTimer(doStartWifiTethering);
- });
- } else {
- cancelWifiHotspotStatusTimer();
- gTetheringService.setWifiTethering(enabled, WifiNetworkInterface,
- configuration, function(result) {
- // Should we fire a dom event if we fail to set wifi tethering ?
- debug("Disable Wifi tethering result: " + (result ? result : "successfully"));
- // Unload wifi driver even if we fail to control wifi tethering.
- unloadDriver(WIFI_FIRMWARE_AP, function(status) {
- if (status < 0) {
- debug("Fail to unload wifi driver");
- }
- manager.tetheringState = "UNINITIALIZED";
- callback();
- });
- });
- }
- }
-
- manager.disconnect = wifiCommand.disconnect;
- manager.reconnect = wifiCommand.reconnect;
- manager.reassociate = wifiCommand.reassociate;
-
- var networkConfigurationFields = [
- {name: "ssid", type: "string"},
- {name: "bssid", type: "string"},
- {name: "psk", type: "string"},
- {name: "wep_key0", type: "string"},
- {name: "wep_key1", type: "string"},
- {name: "wep_key2", type: "string"},
- {name: "wep_key3", type: "string"},
- {name: "wep_tx_keyidx", type: "integer"},
- {name: "priority", type: "integer"},
- {name: "key_mgmt", type: "string"},
- {name: "scan_ssid", type: "string"},
- {name: "disabled", type: "integer"},
- {name: "identity", type: "string"},
- {name: "password", type: "string"},
- {name: "auth_alg", type: "string"},
- {name: "phase1", type: "string"},
- {name: "phase2", type: "string"},
- {name: "eap", type: "string"},
- {name: "pin", type: "string"},
- {name: "pcsc", type: "string"},
- {name: "ca_cert", type: "string"},
- {name: "subject_match", type: "string"},
- {name: "client_cert", type: "string"},
- {name: "private_key", type: "stirng"},
- {name: "engine", type: "integer"},
- {name: "engine_id", type: "string"},
- {name: "key_id", type: "string"},
- {name: "frequency", type: "integer"},
- {name: "mode", type: "integer"}
- ];
- // These fields are only handled in IBSS (aka ad-hoc) mode
- var ibssNetworkConfigurationFields = [
- "frequency", "mode"
- ];
-
- manager.getNetworkConfiguration = function(config, callback) {
- var netId = config.netId;
- var done = 0;
- for (var n = 0; n < networkConfigurationFields.length; ++n) {
- let fieldName = networkConfigurationFields[n].name;
- let fieldType = networkConfigurationFields[n].type;
- wifiCommand.getNetworkVariable(netId, fieldName, function(value) {
- if (value !== null) {
- if (fieldType === "integer") {
- config[fieldName] = parseInt(value, 10);
- } else if ( fieldName == "ssid" && value[0] != '"' ) {
- // SET_NETWORK will set a quoted ssid to wpa_supplicant.
- // But if ssid contains non-ascii char, it will be converted into utf-8.
- // For example: "Test的wifi" --> 54657374e79a8477696669
- // When GET_NETWORK receive a un-quoted utf-8 ssid, it must be decoded and quoted.
- config[fieldName] = quote(decodeURIComponent(value.replace(/[0-9a-f]{2}/g, '%$&')));
- } else {
- // value is string type by default.
- config[fieldName] = value;
- }
- }
- if (++done == networkConfigurationFields.length)
- callback(config);
- });
- }
- }
- manager.setNetworkConfiguration = function(config, callback) {
- var netId = config.netId;
- var done = 0;
- var errors = 0;
-
- function hasValidProperty(name) {
- return ((name in config) &&
- config[name] != null &&
- (["password", "wep_key0", "psk"].indexOf(name) === -1 ||
- config[name] !== '*'));
- }
-
- function getModeFromConfig() {
- /* we use the mode from the config, or ESS as default */
- return hasValidProperty("mode") ? config["mode"] : MODE_ESS;
- }
-
- var mode = getModeFromConfig();
-
- function validForMode(name, mode) {
- /* all fields are valid for IBSS */
- return (mode == MODE_IBSS) ||
- /* IBSS fields are not valid for ESS */
- ((mode == MODE_ESS) && !(name in ibssNetworkConfigurationFields));
- }
-
- for (var n = 0; n < networkConfigurationFields.length; ++n) {
- let fieldName = networkConfigurationFields[n].name;
- if (!hasValidProperty(fieldName) || !validForMode(fieldName, mode)) {
- ++done;
- } else {
- wifiCommand.setNetworkVariable(netId, fieldName, config[fieldName], function(ok) {
- if (!ok)
- ++errors;
- if (++done == networkConfigurationFields.length)
- callback(errors == 0);
- });
- }
- }
- // If config didn't contain any of the fields we want, don't lose the error callback.
- if (done == networkConfigurationFields.length)
- callback(false);
- }
- manager.getConfiguredNetworks = function(callback) {
- wifiCommand.listNetworks(function (reply) {
- var networks = Object.create(null);
- var lines = reply ? reply.split("\n") : 0;
- if (lines.length <= 1) {
- // We need to make sure we call the callback even if there are no
- // configured networks.
- callback(networks);
- return;
- }
-
- var done = 0;
- var errors = 0;
- for (var n = 1; n < lines.length; ++n) {
- var result = lines[n].split("\t");
- var netId = parseInt(result[0], 10);
- var config = networks[netId] = { netId: netId };
- switch (result[3]) {
- case "[CURRENT]":
- config.status = "CURRENT";
- break;
- case "[DISABLED]":
- config.status = "DISABLED";
- break;
- default:
- config.status = "ENABLED";
- break;
- }
- manager.getNetworkConfiguration(config, function (ok) {
- if (!ok)
- ++errors;
- if (++done == lines.length - 1) {
- if (errors) {
- // If an error occured, delete the new netId.
- wifiCommand.removeNetwork(netId, function() {
- callback(null);
- });
- } else {
- callback(networks);
- }
- }
- });
- }
- });
- }
- manager.addNetwork = function(config, callback) {
- wifiCommand.addNetwork(function (netId) {
- config.netId = netId;
- manager.setNetworkConfiguration(config, function (ok) {
- if (!ok) {
- wifiCommand.removeNetwork(netId, function() { callback(false); });
- return;
- }
-
- callback(ok);
- });
- });
- }
- manager.updateNetwork = function(config, callback) {
- manager.setNetworkConfiguration(config, callback);
- }
- manager.removeNetwork = function(netId, callback) {
- wifiCommand.removeNetwork(netId, callback);
- }
-
- manager.saveConfig = function(callback) {
- wifiCommand.saveConfig(callback);
- }
- manager.enableNetwork = function(netId, disableOthers, callback) {
- if (p2pSupported) {
- // We have to stop wifi direct scan before associating to an AP.
- // Otherwise we will get a "REJECT" wpa supplicant event.
- p2pManager.setScanEnabled(false, function(success) {});
- }
- wifiCommand.enableNetwork(netId, disableOthers, callback);
- }
- manager.disableNetwork = function(netId, callback) {
- wifiCommand.disableNetwork(netId, callback);
- }
- manager.getMacAddress = wifiCommand.getMacAddress;
- manager.getScanResults = wifiCommand.scanResults;
- manager.setScanMode = function(mode, callback) {
- setScanMode(mode === "active", callback); // Use our own version.
- }
- manager.setBackgroundScan = setBackgroundScan; // Use our own version.
- manager.scan = scan; // Use our own version.
- manager.wpsPbc = wifiCommand.wpsPbc;
- manager.wpsPin = wifiCommand.wpsPin;
- manager.wpsCancel = wifiCommand.wpsCancel;
- manager.setPowerMode = (sdkVersion >= 16)
- ? wifiCommand.setPowerModeJB
- : wifiCommand.setPowerModeICS;
- manager.setPowerSavingMode = setPowerSavingMode;
- manager.getHttpProxyNetwork = getHttpProxyNetwork;
- manager.setHttpProxy = setHttpProxy;
- manager.configureHttpProxy = configureHttpProxy;
- manager.setSuspendOptimizations = (sdkVersion >= 16)
- ? wifiCommand.setSuspendOptimizationsJB
- : wifiCommand.setSuspendOptimizationsICS;
- manager.setStaticIpMode = setStaticIpMode;
- manager.getRssiApprox = wifiCommand.getRssiApprox;
- manager.getLinkSpeed = wifiCommand.getLinkSpeed;
- manager.getDhcpInfo = function() { return dhcpInfo; }
- manager.getConnectionInfo = (sdkVersion >= 15)
- ? wifiCommand.getConnectionInfoICS
- : wifiCommand.getConnectionInfoGB;
-
- manager.ensureSupplicantDetached = aCallback => {
- if (!manager.enabled) {
- aCallback();
- return;
- }
- wifiCommand.closeSupplicantConnection(aCallback);
- };
-
- manager.isHandShakeState = function(state) {
- switch (state) {
- case "AUTHENTICATING":
- case "ASSOCIATING":
- case "ASSOCIATED":
- case "FOUR_WAY_HANDSHAKE":
- case "GROUP_HANDSHAKE":
- return true;
- case "DORMANT":
- case "COMPLETED":
- case "DISCONNECTED":
- case "INTERFACE_DISABLED":
- case "INACTIVE":
- case "SCANNING":
- case "UNINITIALIZED":
- case "INVALID":
- case "CONNECTED":
- default:
- return false;
- }
- }
-
- manager.isWifiEnabled = function(state) {
- switch (state) {
- case "UNINITIALIZED":
- case "DISABLING":
- return false;
- default:
- return true;
- }
- }
-
- manager.isWifiTetheringEnabled = function(state) {
- switch (state) {
- case "UNINITIALIZED":
- return false;
- default:
- return true;
- }
- }
-
- manager.syncDebug = syncDebug;
- manager.stateOrdinal = function(state) {
- return supplicantStatesMap.indexOf(state);
- }
- manager.supplicantLoopDetection = function(prevState, state) {
- var isPrevStateInHandShake = manager.isHandShakeState(prevState);
- var isStateInHandShake = manager.isHandShakeState(state);
-
- if (isPrevStateInHandShake) {
- if (isStateInHandShake) {
- // Increase the count only if we are in the loop.
- if (manager.stateOrdinal(state) > manager.stateOrdinal(prevState)) {
- manager.loopDetectionCount++;
- }
- if (manager.loopDetectionCount > MAX_SUPPLICANT_LOOP_ITERATIONS) {
- notify("disconnected", {connectionInfo: manager.connectionInfo});
- manager.loopDetectionCount = 0;
- }
- }
- } else {
- // From others state to HandShake state. Reset the count.
- if (isStateInHandShake) {
- manager.loopDetectionCount = 0;
- }
- }
- }
-
- manager.handlePreWifiScan = function() {
- if (p2pSupported) {
- // Before doing regular wifi scan, we have to disable wifi direct
- // scan first. Otherwise we will never get the scan result.
- p2pManager.blockScan();
- }
- };
-
- manager.handlePostWifiScan = function() {
- if (p2pSupported) {
- // After regular wifi scanning, we should restore the restricted
- // wifi direct scan.
- p2pManager.unblockScan();
- }
- };
-
- //
- // Public APIs for P2P.
- //
-
- manager.p2pSupported = function() {
- return p2pSupported;
- };
-
- manager.getP2pManager = function() {
- return p2pManager;
- };
-
- manager.enableP2p = function(callback) {
- p2pManager.setEnabled(true, {
- onSupplicantConnected: function() {
- waitForEvent(WifiP2pManager.INTERFACE_NAME);
- },
-
- onEnabled: function(success) {
- callback(success);
- }
- });
- };
-
- manager.getCapabilities = function() {
- return capabilities;
- }
-
- // Cert Services
- let wifiCertService = Cc["@mozilla.org/wifi/certservice;1"];
- if (wifiCertService) {
- wifiCertService = wifiCertService.getService(Ci.nsIWifiCertService);
- wifiCertService.start(wifiListener);
- } else {
- debug("No wifi CA service component available");
- }
-
- manager.importCert = function(caInfo, callback) {
- var id = idgen++;
- if (callback) {
- controlCallbacks[id] = callback;
- }
-
- wifiCertService.importCert(id, caInfo.certBlob, caInfo.certPassword,
- caInfo.certNickname);
- }
-
- manager.deleteCert = function(caInfo, callback) {
- var id = idgen++;
- if (callback) {
- controlCallbacks[id] = callback;
- }
-
- wifiCertService.deleteCert(id, caInfo.certNickname);
- }
-
- manager.sdkVersion = function() {
- return sdkVersion;
- }
-
- return manager;
-})();
-
-// Get unique key for a network, now the key is created by escape(SSID)+Security.
-// So networks of same SSID but different security mode can be identified.
-function getNetworkKey(network)
-{
- var ssid = "",
- encryption = "OPEN";
-
- if ("security" in network) {
- // manager network object, represents an AP
- // object structure
- // {
- // .ssid : SSID of AP
- // .security[] : "WPA-PSK" for WPA-PSK
- // "WPA-EAP" for WPA-EAP
- // "WEP" for WEP
- // "" for OPEN
- // other keys
- // }
-
- var security = network.security;
- ssid = network.ssid;
-
- for (let j = 0; j < security.length; j++) {
- if (security[j] === "WPA-PSK") {
- encryption = "WPA-PSK";
- break;
- } else if (security[j] === "WPA-EAP") {
- encryption = "WPA-EAP";
- break;
- } else if (security[j] === "WEP") {
- encryption = "WEP";
- break;
- }
- }
- } else if ("key_mgmt" in network) {
- // configure network object, represents a network
- // object structure
- // {
- // .ssid : SSID of network, quoted
- // .key_mgmt : Encryption type
- // "WPA-PSK" for WPA-PSK
- // "WPA-EAP" for WPA-EAP
- // "NONE" for WEP/OPEN
- // .auth_alg : Encryption algorithm(WEP mode only)
- // "OPEN_SHARED" for WEP
- // other keys
- // }
- var key_mgmt = network.key_mgmt,
- auth_alg = network.auth_alg;
- ssid = dequote(network.ssid);
-
- if (key_mgmt == "WPA-PSK") {
- encryption = "WPA-PSK";
- } else if (key_mgmt.indexOf("WPA-EAP") != -1) {
- encryption = "WPA-EAP";
- } else if (key_mgmt == "NONE" && auth_alg === "OPEN SHARED") {
- encryption = "WEP";
- }
- }
-
- // ssid here must be dequoted, and it's safer to esacpe it.
- // encryption won't be empty and always be assigned one of the followings :
- // "OPEN"/"WEP"/"WPA-PSK"/"WPA-EAP".
- // So for a invalid network object, the returned key will be "OPEN".
- return escape(ssid) + encryption;
-}
-
-function getMode(flags) {
- if (/\[IBSS/.test(flags))
- return MODE_IBSS;
-
- return MODE_ESS;
-}
-
-function getKeyManagement(flags) {
- var types = [];
- if (!flags)
- return types;
-
- if (/\[WPA2?-PSK/.test(flags))
- types.push("WPA-PSK");
- if (/\[WPA2?-EAP/.test(flags))
- types.push("WPA-EAP");
- if (/\[WEP/.test(flags))
- types.push("WEP");
- return types;
-}
-
-function getCapabilities(flags) {
- var types = [];
- if (!flags)
- return types;
-
- if (/\[WPS/.test(flags))
- types.push("WPS");
- return types;
-}
-
-// These constants shamelessly ripped from WifiManager.java
-// strength is the value returned by scan_results. It is nominally in dB. We
-// transform it into a percentage for clients looking to simply show a
-// relative indication of the strength of a network.
-const MIN_RSSI = -100;
-const MAX_RSSI = -55;
-
-function calculateSignal(strength) {
- // Some wifi drivers represent their signal strengths as 8-bit integers, so
- // in order to avoid negative numbers, they add 256 to the actual values.
- // While we don't *know* that this is the case here, we make an educated
- // guess.
- if (strength > 0)
- strength -= 256;
-
- if (strength <= MIN_RSSI)
- return 0;
- if (strength >= MAX_RSSI)
- return 100;
- return Math.floor(((strength - MIN_RSSI) / (MAX_RSSI - MIN_RSSI)) * 100);
-}
-
-function Network(ssid, mode, frequency, security, password, capabilities) {
- this.ssid = ssid;
- this.mode = mode;
- this.frequency = frequency;
- this.security = security;
-
- if (typeof password !== "undefined")
- this.password = password;
- if (capabilities !== undefined)
- this.capabilities = capabilities;
- // TODO connected here as well?
-
- this.__exposedProps__ = Network.api;
-}
-
-Network.api = {
- ssid: "r",
- mode: "r",
- frequency: "r",
- security: "r",
- capabilities: "r",
- known: "r",
-
- password: "rw",
- keyManagement: "rw",
- psk: "rw",
- identity: "rw",
- wep: "rw",
- hidden: "rw",
- eap: "rw",
- pin: "rw",
- phase1: "rw",
- phase2: "rw",
- serverCertificate: "rw",
- userCertificate: "rw"
-};
-
-// Note: We never use ScanResult.prototype, so the fact that it's unrelated to
-// Network.prototype is OK.
-function ScanResult(ssid, bssid, frequency, flags, signal) {
- Network.call(this, ssid, getMode(flags), frequency,
- getKeyManagement(flags), undefined, getCapabilities(flags));
- this.bssid = bssid;
- this.signalStrength = signal;
- this.relSignalStrength = calculateSignal(Number(signal));
-
- this.__exposedProps__ = ScanResult.api;
-}
-
-// XXX This should probably live in the DOM-facing side, but it's hard to do
-// there, so we stick this here.
-ScanResult.api = {
- bssid: "r",
- signalStrength: "r",
- relSignalStrength: "r",
- connected: "r"
-};
-
-for (let i in Network.api) {
- ScanResult.api[i] = Network.api[i];
-}
-
-function quote(s) {
- return '"' + s + '"';
-}
-
-function dequote(s) {
- if (s[0] != '"' || s[s.length - 1] != '"')
- throw "Invalid argument, not a quoted string: " + s;
- return s.substr(1, s.length - 2);
-}
-
-function isWepHexKey(s) {
- if (s.length != 10 && s.length != 26 && s.length != 58)
- return false;
- return !/[^a-fA-F0-9]/.test(s);
-}
-
-
-var WifiNetworkInterface = {
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInterface]),
-
- registered: false,
-
- // nsINetworkInterface
-
- NETWORK_STATE_UNKNOWN: Ci.nsINetworkInfo.NETWORK_STATE_UNKNOWN,
- NETWORK_STATE_CONNECTING: Ci.nsINetworkInfo.CONNECTING,
- NETWORK_STATE_CONNECTED: Ci.nsINetworkInfo.CONNECTED,
- NETWORK_STATE_DISCONNECTING: Ci.nsINetworkInfo.DISCONNECTING,
- NETWORK_STATE_DISCONNECTED: Ci.nsINetworkInfo.DISCONNECTED,
-
- NETWORK_TYPE_WIFI: Ci.nsINetworkInfo.NETWORK_TYPE_WIFI,
- NETWORK_TYPE_MOBILE: Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE,
- NETWORK_TYPE_MOBILE_MMS: Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_MMS,
- NETWORK_TYPE_MOBILE_SUPL: Ci.nsINetworkInfo.NETWORK_TYPE_MOBILE_SUPL,
-
- info: {
- QueryInterface: XPCOMUtils.generateQI([Ci.nsINetworkInfo]),
-
- state: Ci.nsINetworkInfo.NETWORK_STATE_UNKNOWN,
-
- type: Ci.nsINetworkInfo.NETWORK_TYPE_WIFI,
-
- name: null,
-
- ips: [],
-
- prefixLengths: [],
-
- dnses: [],
-
- gateways: [],
-
- getAddresses: function (ips, prefixLengths) {
- ips.value = this.ips.slice();
- prefixLengths.value = this.prefixLengths.slice();
-
- return this.ips.length;
- },
-
- getGateways: function (count) {
- if (count) {
- count.value = this.gateways.length;
- }
- return this.gateways.slice();
- },
-
- getDnses: function (count) {
- if (count) {
- count.value = this.dnses.length;
- }
- return this.dnses.slice();
- }
- },
-
- httpProxyHost: null,
-
- httpProxyPort: null
-};
-
-function WifiScanResult() {}
-
-// TODO Make the difference between a DOM-based network object and our
-// networks objects much clearer.
-var netToDOM;
-var netFromDOM;
-
-function WifiWorker() {
- var self = this;
-
- this._mm = Cc["@mozilla.org/parentprocessmessagemanager;1"]
- .getService(Ci.nsIMessageListenerManager);
- const messages = ["WifiManager:getNetworks", "WifiManager:getKnownNetworks",
- "WifiManager:associate", "WifiManager:forget",
- "WifiManager:wps", "WifiManager:getState",
- "WifiManager:setPowerSavingMode",
- "WifiManager:setHttpProxy",
- "WifiManager:setStaticIpMode",
- "WifiManager:importCert",
- "WifiManager:getImportedCerts",
- "WifiManager:deleteCert",
- "WifiManager:setWifiEnabled",
- "WifiManager:setWifiTethering",
- "child-process-shutdown"];
-
- messages.forEach((function(msgName) {
- this._mm.addMessageListener(msgName, this);
- }).bind(this));
-
- Services.obs.addObserver(this, kMozSettingsChangedObserverTopic, false);
- Services.obs.addObserver(this, "xpcom-shutdown", false);
-
- this.wantScanResults = [];
-
- this._needToEnableNetworks = false;
- this._highestPriority = -1;
-
- // Networks is a map from SSID -> a scan result.
- this.networks = Object.create(null);
-
- // ConfiguredNetworks is a map from SSID -> our view of a network. It only
- // lists networks known to the wpa_supplicant. The SSID field (and other
- // fields) are quoted for ease of use with WifiManager commands.
- // Note that we don't have to worry about escaping embedded quotes since in
- // all cases, the supplicant will take the last quotation that we pass it as
- // the end of the string.
- this.configuredNetworks = Object.create(null);
- this._addingNetworks = Object.create(null);
-
- this.currentNetwork = null;
- this.ipAddress = "";
- this.macAddress = null;
-
- this._lastConnectionInfo = null;
- this._connectionInfoTimer = null;
- this._reconnectOnDisconnect = false;
-
- // Create p2pObserver and assign to p2pManager.
- if (WifiManager.p2pSupported()) {
- this._p2pObserver = WifiP2pWorkerObserver(WifiManager.getP2pManager());
- WifiManager.getP2pManager().setObserver(this._p2pObserver);
-
- // Add DOM message observerd by p2pObserver to the message listener as well.
- this._p2pObserver.getObservedDOMMessages().forEach((function(msgName) {
- this._mm.addMessageListener(msgName, this);
- }).bind(this));
- }
-
- // Users of instances of nsITimer should keep a reference to the timer until
- // it is no longer needed in order to assure the timer is fired.
- this._callbackTimer = null;
-
- // XXX On some phones (Otoro and Unagi) the wifi driver doesn't play nicely
- // with the automatic scans that wpa_supplicant does (it appears that the
- // driver forgets that it's returned scan results and then refuses to try to
- // rescan. In order to detect this case we start a timer when we enter the
- // SCANNING state and reset it whenever we either get scan results or leave
- // the SCANNING state. If the timer fires, we assume that we are stuck and
- // forceably try to unstick the supplican, also turning on background
- // scanning to avoid having to constantly poke the supplicant.
-
- // How long we wait is controlled by the SCAN_STUCK_WAIT constant.
- const SCAN_STUCK_WAIT = 12000;
- this._scanStuckTimer = null;
- this._turnOnBackgroundScan = false;
-
- function startScanStuckTimer() {
- if (WifiManager.schedScanRecovery) {
- self._scanStuckTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- self._scanStuckTimer.initWithCallback(scanIsStuck, SCAN_STUCK_WAIT,
- Ci.nsITimer.TYPE_ONE_SHOT);
- }
- }
-
- function scanIsStuck() {
- // Uh-oh, we've waited too long for scan results. Disconnect (which
- // guarantees that we leave the SCANNING state and tells wpa_supplicant to
- // wait for our next command) ensure that background scanning is on and
- // then try again.
- debug("Determined that scanning is stuck, turning on background scanning!");
- WifiManager.handlePostWifiScan();
- WifiManager.disconnect(function(ok) {});
- self._turnOnBackgroundScan = true;
- }
-
- // A list of requests to turn wifi on or off.
- this._stateRequests = [];
-
- // Given a connection status network, takes a network from
- // self.configuredNetworks and prepares it for the DOM.
- netToDOM = function(net) {
- if (!net) {
- return null;
- }
- var ssid = dequote(net.ssid);
- var mode = net.mode;
- var frequency = net.frequency;
- var security = (net.key_mgmt === "NONE" && net.wep_key0) ? ["WEP"] :
- (net.key_mgmt && net.key_mgmt !== "NONE") ? [net.key_mgmt.split(" ")[0]] :
- [];
- var password;
- if (("psk" in net && net.psk) ||
- ("password" in net && net.password) ||
- ("wep_key0" in net && net.wep_key0)) {
- password = "*";
- }
-
- var pub = new Network(ssid, mode, frequency, security, password);
- if (net.identity)
- pub.identity = dequote(net.identity);
- if ("netId" in net)
- pub.known = true;
- if (net.scan_ssid === 1)
- pub.hidden = true;
- if ("ca_cert" in net && net.ca_cert &&
- net.ca_cert.indexOf("keystore://WIFI_SERVERCERT_" === 0)) {
- pub.serverCertificate = net.ca_cert.substr(27);
- }
- if(net.subject_match) {
- pub.subjectMatch = net.subject_match;
- }
- if ("client_cert" in net && net.client_cert &&
- net.client_cert.indexOf("keystore://WIFI_USERCERT_" === 0)) {
- pub.userCertificate = net.client_cert.substr(25);
- }
- return pub;
- };
-
- netFromDOM = function(net, configured) {
- // Takes a network from the DOM and makes it suitable for insertion into
- // self.configuredNetworks (that is calling addNetwork will do the right
- // thing).
- // NB: Modifies net in place: safe since we don't share objects between
- // the dom and the chrome code.
-
- // Things that are useful for the UI but not to us.
- delete net.bssid;
- delete net.signalStrength;
- delete net.relSignalStrength;
- delete net.security;
- delete net.capabilities;
-
- if (!configured)
- configured = {};
-
- net.ssid = quote(net.ssid);
-
- let wep = false;
- if ("keyManagement" in net) {
- if (net.keyManagement === "WEP") {
- wep = true;
- net.keyManagement = "NONE";
- } else if (net.keyManagement === "WPA-EAP") {
- net.keyManagement += " IEEE8021X";
- }
-
- configured.key_mgmt = net.key_mgmt = net.keyManagement; // WPA2-PSK, WPA-PSK, etc.
- delete net.keyManagement;
- } else {
- configured.key_mgmt = net.key_mgmt = "NONE";
- }
-
- if (net.hidden) {
- configured.scan_ssid = net.scan_ssid = 1;
- delete net.hidden;
- }
-
- function checkAssign(name, checkStar) {
- if (name in net) {
- let value = net[name];
- if (!value || (checkStar && value === '*')) {
- if (name in configured)
- net[name] = configured[name];
- else
- delete net[name];
- } else {
- configured[name] = net[name] = quote(value);
- }
- }
- }
-
- checkAssign("psk", true);
- checkAssign("identity", false);
- checkAssign("password", true);
- if (wep && net.wep && net.wep != '*') {
- configured.wep_key0 = net.wep_key0 = isWepHexKey(net.wep) ? net.wep : quote(net.wep);
- configured.auth_alg = net.auth_alg = "OPEN SHARED";
- }
-
- function hasValidProperty(name) {
- return ((name in net) && net[name] != null);
- }
-
- if (hasValidProperty("eap")) {
- if (hasValidProperty("pin")) {
- net.pin = quote(net.pin);
- }
-
- if (hasValidProperty("phase1"))
- net.phase1 = quote(net.phase1);
-
- if (hasValidProperty("phase2")) {
- if (net.phase2 === "TLS") {
- net.phase2 = quote("autheap=" + net.phase2);
- } else { // PAP, MSCHAPV2, etc.
- net.phase2 = quote("auth=" + net.phase2);
- }
- }
-
- if (hasValidProperty("serverCertificate"))
- net.ca_cert = quote("keystore://WIFI_SERVERCERT_" + net.serverCertificate);
-
- if (hasValidProperty("subjectMatch"))
- net.subject_match = quote(net.subjectMatch);
-
- if (hasValidProperty("userCertificate")) {
- let userCertName = "WIFI_USERCERT_" + net.userCertificate;
- net.client_cert = quote("keystore://" + userCertName);
-
- let wifiCertService = Cc["@mozilla.org/wifi/certservice;1"].
- getService(Ci.nsIWifiCertService);
- if (wifiCertService.hasPrivateKey(userCertName)) {
- if (WifiManager.sdkVersion() >= 19) {
- // Use openssol engine instead of keystore protocol after Kitkat.
- net.engine = 1;
- net.engine_id = quote("keystore");
- net.key_id = quote("WIFI_USERKEY_" + net.userCertificate);
- } else {
- net.private_key = quote("keystore://WIFI_USERKEY_" + net.userCertificate);
- }
- }
- }
- }
-
- return net;
- };
-
- WifiManager.onsupplicantconnection = function() {
- debug("Connected to supplicant");
- // Give it a state other than UNINITIALIZED, INITIALIZING or DISABLING
- // defined in getter function of WifiManager.enabled. It implies that
- // we are ready to accept dom request from applications.
- WifiManager.state = "DISCONNECTED";
- self._reloadConfiguredNetworks(function(ok) {
- // Prime this.networks.
- if (!ok)
- return;
-
- // The select network command we used in associate() disables others networks.
- // Enable them here to make sure wpa_supplicant helps to connect to known
- // network automatically.
- self._enableAllNetworks();
- WifiManager.saveConfig(function() {})
- });
-
- // Notify everybody, even if they didn't ask us to come up.
- WifiManager.getMacAddress(function (mac) {
- self.macAddress = mac;
- debug("Got mac: " + mac);
- self._fireEvent("wifiUp", { macAddress: mac });
- self.requestDone();
- });
-
- if (WifiManager.state === "SCANNING")
- startScanStuckTimer();
- };
-
- WifiManager.onsupplicantlost = function() {
- WifiManager.supplicantStarted = false;
- WifiManager.state = "UNINITIALIZED";
- debug("Supplicant died!");
-
- // Notify everybody, even if they didn't ask us to come up.
- self._fireEvent("wifiDown", {});
- self.requestDone();
- };
-
- WifiManager.onpasswordmaybeincorrect = function() {
- WifiManager.authenticationFailuresCount++;
- };
-
- WifiManager.ondisconnected = function() {
- // We may fail to establish the connection, re-enable the
- // rest of our networks.
- if (self._needToEnableNetworks) {
- self._enableAllNetworks();
- self._needToEnableNetworks = false;
- }
-
- let connectionInfo = this.connectionInfo;
- WifiManager.getNetworkId(connectionInfo.ssid, function(netId) {
- // Trying to get netId from current network.
- if (!netId &&
- self.currentNetwork && self.currentNetwork.ssid &&
- dequote(self.currentNetwork.ssid) == connectionInfo.ssid &&
- typeof self.currentNetwork.netId !== "undefined") {
- netId = self.currentNetwork.netId;
- }
- if (netId) {
- WifiManager.disableNetwork(netId, function() {});
- }
- });
- self._fireEvent("onconnectingfailed", {network: netToDOM(self.currentNetwork)});
- }
-
- WifiManager.onstatechange = function() {
- debug("State change: " + this.prevState + " -> " + this.state);
-
- if (self._connectionInfoTimer &&
- this.state !== "CONNECTED" &&
- this.state !== "COMPLETED") {
- self._stopConnectionInfoTimer();
- }
-
- if (this.state !== "SCANNING" &&
- self._scanStuckTimer) {
- self._scanStuckTimer.cancel();
- self._scanStuckTimer = null;
- }
-
- switch (this.state) {
- case "DORMANT":
- // The dormant state is a bad state to be in since we won't
- // automatically connect. Try to knock us out of it. We only
- // hit this state when we've failed to run DHCP, so trying
- // again isn't the worst thing we can do. Eventually, we'll
- // need to detect if we're looping in this state and bail out.
- WifiManager.reconnect(function(){});
- break;
- case "ASSOCIATING":
- // id has not yet been filled in, so we can only report the ssid and
- // bssid. mode and frequency are simply made up.
- self.currentNetwork =
- { bssid: WifiManager.connectionInfo.bssid,
- ssid: quote(WifiManager.connectionInfo.ssid),
- mode: MODE_ESS,
- frequency: 0};
- WifiManager.getNetworkConfiguration(self.currentNetwork, function (){
- // Notify again because we get complete network information.
- self._fireEvent("onconnecting", { network: netToDOM(self.currentNetwork) });
- });
- break;
- case "ASSOCIATED":
- // set to full power mode when ready to do 4 way handsharke.
- WifiManager.setPowerSavingMode(false);
- if (!self.currentNetwork) {
- self.currentNetwork =
- { bssid: WifiManager.connectionInfo.bssid,
- ssid: quote(WifiManager.connectionInfo.ssid) };
- }
- self.currentNetwork.netId = this.id;
- WifiManager.getNetworkConfiguration(self.currentNetwork, function (){
- // Notify again because we get complete network information.
- self._fireEvent("onconnecting", { network: netToDOM(self.currentNetwork) });
- });
- break;
- case "COMPLETED":
- // Now that we've successfully completed the connection, re-enable the
- // rest of our networks.
- // XXX Need to do this eventually if the user entered an incorrect
- // password. For now, we require user interaction to break the loop and
- // select a better network!
- if (self._needToEnableNetworks) {
- self._enableAllNetworks();
- self._needToEnableNetworks = false;
- }
-
- var _oncompleted = function() {
- // The full authentication process is completed, reset the count.
- WifiManager.authenticationFailuresCount = 0;
- WifiManager.loopDetectionCount = 0;
- self._startConnectionInfoTimer();
- self._fireEvent("onassociate", { network: netToDOM(self.currentNetwork) });
- };
-
- // We get the ASSOCIATED event when we've associated but not connected, so
- // wait until the handshake is complete.
- if (this.fromStatus || !self.currentNetwork) {
- // In this case, we connected to an already-connected wpa_supplicant,
- // because of that we need to gather information about the current
- // network here.
- self.currentNetwork = { bssid: WifiManager.connectionInfo.bssid,
- ssid: quote(WifiManager.connectionInfo.ssid),
- netId: WifiManager.connectionInfo.id };
- WifiManager.getNetworkConfiguration(self.currentNetwork, _oncompleted);
- } else {
- _oncompleted();
- }
- break;
- case "CONNECTED":
- // wifi connection complete, turn on the power saving mode.
- WifiManager.setPowerSavingMode(true);
- // BSSID is read after connected, update it.
- self.currentNetwork.bssid = WifiManager.connectionInfo.bssid;
- break;
- case "DISCONNECTED":
- // wpa_supplicant may give us a "DISCONNECTED" event even if
- // we are already in "DISCONNECTED" state.
- if ((WifiNetworkInterface.info.state ===
- Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED) &&
- (this.prevState === "INITIALIZING" ||
- this.prevState === "DISCONNECTED" ||
- this.prevState === "INTERFACE_DISABLED" ||
- this.prevState === "INACTIVE" ||
- this.prevState === "UNINITIALIZED")) {
- // When in disconnected mode, need to turn on wifi power saving mode.
- WifiManager.setPowerSavingMode(true);
- return;
- }
-
- self._fireEvent("ondisconnect", {network: netToDOM(self.currentNetwork)});
-
- self.currentNetwork = null;
- self.ipAddress = "";
-
- if (self._turnOnBackgroundScan) {
- self._turnOnBackgroundScan = false;
- WifiManager.setBackgroundScan("ON", function(did_something, ok) {
- WifiManager.reassociate(function() {});
- });
- }
-
- WifiManager.connectionDropped(function() {
- // We've disconnected from a network because of a call to forgetNetwork.
- // Reconnect to the next available network (if any).
- if (self._reconnectOnDisconnect) {
- self._reconnectOnDisconnect = false;
- WifiManager.reconnect(function(){});
- }
- });
-
- WifiNetworkInterface.info.state =
- Ci.nsINetworkInfo.NETWORK_STATE_DISCONNECTED;
-
- // Update network infterface first then clear properties.
- gNetworkManager.updateNetworkInterface(WifiNetworkInterface);
- WifiNetworkInterface.info.ips = [];
- WifiNetworkInterface.info.prefixLengths = [];
- WifiNetworkInterface.info.gateways = [];
- WifiNetworkInterface.info.dnses = [];
-
-
- break;
- case "WPS_TIMEOUT":
- self._fireEvent("onwpstimeout", {});
- break;
- case "WPS_FAIL":
- self._fireEvent("onwpsfail", {});
- break;
- case "WPS_OVERLAP_DETECTED":
- self._fireEvent("onwpsoverlap", {});
- break;
- case "AUTHENTICATING":
- self._fireEvent("onauthenticating", {network: netToDOM(self.currentNetwork)});
- break;
- case "SCANNING":
- // If we're already scanning in the background, we don't need to worry
- // about getting stuck while scanning.
- if (!WifiManager.backgroundScanEnabled && WifiManager.enabled)
- startScanStuckTimer();
- break;
- }
- };
-
- WifiManager.onnetworkconnected = function() {
- if (!this.info || !this.info.ipaddr_str) {
- debug("Network information is invalid.");
- return;
- }
-
- let maskLength =
- netHelpers.getMaskLength(netHelpers.stringToIP(this.info.mask_str));
- if (!maskLength) {
- maskLength = 32; // max prefix for IPv4.
- }
-
- let netConnect = WifiManager.getHttpProxyNetwork(self.currentNetwork);
- if (netConnect) {
- WifiNetworkInterface.httpProxyHost = netConnect.httpProxyHost;
- WifiNetworkInterface.httpProxyPort = netConnect.httpProxyPort;
- }
-
- WifiNetworkInterface.info.state =
- Ci.nsINetworkInfo.NETWORK_STATE_CONNECTED;
- WifiNetworkInterface.info.ips = [this.info.ipaddr_str];
- WifiNetworkInterface.info.prefixLengths = [maskLength];
- WifiNetworkInterface.info.gateways = [this.info.gateway_str];
- if (typeof this.info.dns1_str == "string" &&
- this.info.dns1_str.length) {
- WifiNetworkInterface.info.dnses.push(this.info.dns1_str);
- }
- if (typeof this.info.dns2_str == "string" &&
- this.info.dns2_str.length) {
- WifiNetworkInterface.info.dnses.push(this.info.dns2_str);
- }
- gNetworkManager.updateNetworkInterface(WifiNetworkInterface);
-
- self.ipAddress = this.info.ipaddr_str;
-
- // We start the connection information timer when we associate, but
- // don't have our IP address until here. Make sure that we fire a new
- // connectionInformation event with the IP address the next time the
- // timer fires.
- self._lastConnectionInfo = null;
- self._fireEvent("onconnect", { network: netToDOM(self.currentNetwork) });
- };
-
- WifiManager.onscanresultsavailable = function() {
- if (self._scanStuckTimer) {
- // We got scan results! We must not be stuck for now, try again.
- self._scanStuckTimer.cancel();
- self._scanStuckTimer.initWithCallback(scanIsStuck, SCAN_STUCK_WAIT,
- Ci.nsITimer.TYPE_ONE_SHOT);
- }
-
- if (self.wantScanResults.length === 0) {
- debug("Scan results available, but we don't need them");
- return;
- }
-
- debug("Scan results are available! Asking for them.");
- WifiManager.getScanResults(function(r) {
- // Failure.
- if (!r) {
- self.wantScanResults.forEach(function(callback) { callback(null) });
- self.wantScanResults = [];
- return;
- }
-
- let capabilities = WifiManager.getCapabilities();
-
- // Now that we have scan results, there's no more need to continue
- // scanning. Ignore any errors from this command.
- WifiManager.setScanMode("inactive", function() {});
- let lines = r.split("\n");
- // NB: Skip the header line.
- self.networksArray = [];
- for (let i = 1; i < lines.length; ++i) {
- // bssid / frequency / signal level / flags / ssid
- var match = /([\S]+)\s+([\S]+)\s+([\S]+)\s+(\[[\S]+\])?\s(.*)/.exec(lines[i]);
-
- if (match && match[5]) {
- let ssid = match[5],
- bssid = match[1],
- frequency = match[2],
- signalLevel = match[3],
- flags = match[4];
-
- /* Skip networks with unknown or unsupported modes. */
- if (capabilities.mode.indexOf(getMode(flags)) == -1)
- continue;
-
- // If this is the first time that we've seen this SSID in the scan
- // results, add it to the list along with any other information.
- // Also, we use the highest signal strength that we see.
- let network = new ScanResult(ssid, bssid, frequency, flags, signalLevel);
-
- let networkKey = getNetworkKey(network);
- let eapIndex = -1;
- if (networkKey in self.configuredNetworks) {
- let known = self.configuredNetworks[networkKey];
- network.known = true;
-
- if ("identity" in known && known.identity)
- network.identity = dequote(known.identity);
-
- // Note: we don't hand out passwords here! The * marks that there
- // is a password that we're hiding.
- if (("psk" in known && known.psk) ||
- ("password" in known && known.password) ||
- ("wep_key0" in known && known.wep_key0)) {
- network.password = "*";
- }
- }
-
- self.networksArray.push(network);
- if (network.bssid === WifiManager.connectionInfo.bssid)
- network.connected = true;
-
- let signal = calculateSignal(Number(match[3]));
- if (signal > network.relSignalStrength)
- network.relSignalStrength = signal;
- } else if (!match) {
- debug("Match didn't find anything for: " + lines[i]);
- }
- }
-
- self.wantScanResults.forEach(function(callback) { callback(self.networksArray) });
- self.wantScanResults = [];
- });
- };
-
- WifiManager.onstationinfoupdate = function() {
- self._fireEvent("stationinfoupdate", { station: this.station });
- };
-
- WifiManager.onstopconnectioninfotimer = function() {
- self._stopConnectionInfoTimer();
- };
-
- // Read the 'wifi.enabled' setting in order to start with a known
- // value at boot time. The handle() will be called after reading.
- //
- // nsISettingsServiceCallback implementation.
- var initWifiEnabledCb = {
- handle: function handle(aName, aResult) {
- if (aName !== SETTINGS_WIFI_ENABLED)
- return;
- if (aResult === null)
- aResult = true;
- self.handleWifiEnabled(aResult);
- },
- handleError: function handleError(aErrorMessage) {
- debug("Error reading the 'wifi.enabled' setting. Default to wifi on.");
- self.handleWifiEnabled(true);
- }
- };
-
- var initWifiDebuggingEnabledCb = {
- handle: function handle(aName, aResult) {
- if (aName !== SETTINGS_WIFI_DEBUG_ENABLED)
- return;
- if (aResult === null)
- aResult = false;
- DEBUG = aResult;
- updateDebug();
- },
- handleError: function handleError(aErrorMessage) {
- debug("Error reading the 'wifi.debugging.enabled' setting. Default to debugging off.");
- DEBUG = false;
- updateDebug();
- }
- };
-
- this.initTetheringSettings();
-
- let lock = gSettingsService.createLock();
- lock.get(SETTINGS_WIFI_ENABLED, initWifiEnabledCb);
- lock.get(SETTINGS_WIFI_DEBUG_ENABLED, initWifiDebuggingEnabledCb);
-
- lock.get(SETTINGS_WIFI_SSID, this);
- lock.get(SETTINGS_WIFI_SECURITY_TYPE, this);
- lock.get(SETTINGS_WIFI_SECURITY_PASSWORD, this);
- lock.get(SETTINGS_WIFI_IP, this);
- lock.get(SETTINGS_WIFI_PREFIX, this);
- lock.get(SETTINGS_WIFI_DHCPSERVER_STARTIP, this);
- lock.get(SETTINGS_WIFI_DHCPSERVER_ENDIP, this);
- lock.get(SETTINGS_WIFI_DNS1, this);
- lock.get(SETTINGS_WIFI_DNS2, this);
- lock.get(SETTINGS_WIFI_TETHERING_ENABLED, this);
-
- lock.get(SETTINGS_USB_DHCPSERVER_STARTIP, this);
- lock.get(SETTINGS_USB_DHCPSERVER_ENDIP, this);
-
- this._wifiTetheringSettingsToRead = [SETTINGS_WIFI_SSID,
- SETTINGS_WIFI_SECURITY_TYPE,
- SETTINGS_WIFI_SECURITY_PASSWORD,
- SETTINGS_WIFI_IP,
- SETTINGS_WIFI_PREFIX,
- SETTINGS_WIFI_DHCPSERVER_STARTIP,
- SETTINGS_WIFI_DHCPSERVER_ENDIP,
- SETTINGS_WIFI_DNS1,
- SETTINGS_WIFI_DNS2,
- SETTINGS_WIFI_TETHERING_ENABLED,
- SETTINGS_USB_DHCPSERVER_STARTIP,
- SETTINGS_USB_DHCPSERVER_ENDIP];
-}
-
-function translateState(state) {
- switch (state) {
- case "INTERFACE_DISABLED":
- case "INACTIVE":
- case "SCANNING":
- case "DISCONNECTED":
- default:
- return "disconnected";
-
- case "AUTHENTICATING":
- case "ASSOCIATING":
- case "ASSOCIATED":
- case "FOUR_WAY_HANDSHAKE":
- case "GROUP_HANDSHAKE":
- return "connecting";
-
- case "COMPLETED":
- return WifiManager.getDhcpInfo() ? "connected" : "associated";
- }
-}
-
-WifiWorker.prototype = {
- classID: WIFIWORKER_CID,
- classInfo: XPCOMUtils.generateCI({classID: WIFIWORKER_CID,
- contractID: WIFIWORKER_CONTRACTID,
- classDescription: "WifiWorker",
- interfaces: [Ci.nsIWorkerHolder,
- Ci.nsIWifi,
- Ci.nsIObserver]}),
-
- QueryInterface: XPCOMUtils.generateQI([Ci.nsIWorkerHolder,
- Ci.nsIWifi,
- Ci.nsIObserver,
- Ci.nsISettingsServiceCallback]),
-
- disconnectedByWifi: false,
-
- disconnectedByWifiTethering: false,
-
- _wifiTetheringSettingsToRead: [],
-
- _oldWifiTetheringEnabledState: null,
-
- tetheringSettings: {},
-
- initTetheringSettings: function initTetheringSettings() {
- this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED] = null;
- this.tetheringSettings[SETTINGS_WIFI_SSID] = DEFAULT_WIFI_SSID;
- this.tetheringSettings[SETTINGS_WIFI_SECURITY_TYPE] = DEFAULT_WIFI_SECURITY_TYPE;
- this.tetheringSettings[SETTINGS_WIFI_SECURITY_PASSWORD] = DEFAULT_WIFI_SECURITY_PASSWORD;
- this.tetheringSettings[SETTINGS_WIFI_IP] = DEFAULT_WIFI_IP;
- this.tetheringSettings[SETTINGS_WIFI_PREFIX] = DEFAULT_WIFI_PREFIX;
- this.tetheringSettings[SETTINGS_WIFI_DHCPSERVER_STARTIP] = DEFAULT_WIFI_DHCPSERVER_STARTIP;
- this.tetheringSettings[SETTINGS_WIFI_DHCPSERVER_ENDIP] = DEFAULT_WIFI_DHCPSERVER_ENDIP;
- this.tetheringSettings[SETTINGS_WIFI_DNS1] = DEFAULT_DNS1;
- this.tetheringSettings[SETTINGS_WIFI_DNS2] = DEFAULT_DNS2;
-
- this.tetheringSettings[SETTINGS_USB_DHCPSERVER_STARTIP] = DEFAULT_USB_DHCPSERVER_STARTIP;
- this.tetheringSettings[SETTINGS_USB_DHCPSERVER_ENDIP] = DEFAULT_USB_DHCPSERVER_ENDIP;
- },
-
- // Internal methods.
- waitForScan: function(callback) {
- this.wantScanResults.push(callback);
- },
-
- // In order to select a specific network, we disable the rest of the
- // networks known to us. However, in general, we want the supplicant to
- // connect to which ever network it thinks is best, so when we select the
- // proper network (or fail to), we need to re-enable the rest.
- _enableAllNetworks: function() {
- for (let key in this.configuredNetworks) {
- let net = this.configuredNetworks[key];
- WifiManager.enableNetwork(net.netId, false, function(ok) {
- net.disabled = ok ? 1 : 0;
- });
- }
- },
-
- _startConnectionInfoTimer: function() {
- if (this._connectionInfoTimer)
- return;
-
- var self = this;
- function getConnectionInformation() {
- WifiManager.getConnectionInfo(function(connInfo) {
- // See comments in calculateSignal for information about this.
- if (!connInfo) {
- self._lastConnectionInfo = null;
- return;
- }
-
- let { rssi, linkspeed } = connInfo;
- if (rssi > 0)
- rssi -= 256;
- if (rssi <= MIN_RSSI)
- rssi = MIN_RSSI;
- else if (rssi >= MAX_RSSI)
- rssi = MAX_RSSI;
-
- let info = { signalStrength: rssi,
- relSignalStrength: calculateSignal(rssi),
- linkSpeed: linkspeed,
- ipAddress: self.ipAddress };
- let last = self._lastConnectionInfo;
-
- // Only fire the event if the link speed changed or the signal
- // strength changed by more than 10%.
- function tensPlace(percent) {
- return (percent / 10) | 0;
- }
-
- if (last && last.linkSpeed === info.linkSpeed &&
- last.ipAddress === info.ipAddress &&
- tensPlace(last.relSignalStrength) === tensPlace(info.relSignalStrength)) {
- return;
- }
-
- self._lastConnectionInfo = info;
- debug("Firing connectioninfoupdate: " + uneval(info));
- self._fireEvent("connectioninfoupdate", info);
- });
- }
-
- // Prime our _lastConnectionInfo immediately and fire the event at the
- // same time.
- getConnectionInformation();
-
- // Now, set up the timer for regular updates.
- this._connectionInfoTimer =
- Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- this._connectionInfoTimer.init(getConnectionInformation, 5000,
- Ci.nsITimer.TYPE_REPEATING_SLACK);
- },
-
- _stopConnectionInfoTimer: function() {
- if (!this._connectionInfoTimer)
- return;
-
- this._connectionInfoTimer.cancel();
- this._connectionInfoTimer = null;
- this._lastConnectionInfo = null;
- },
-
- _reloadConfiguredNetworks: function(callback) {
- WifiManager.getConfiguredNetworks((function(networks) {
- if (!networks) {
- debug("Unable to get configured networks");
- callback(false);
- return;
- }
-
- this._highestPriority = -1;
-
- // Convert between netId-based and ssid-based indexing.
- for (let net in networks) {
- let network = networks[net];
- delete networks[net];
-
- if (!network.ssid) {
- WifiManager.removeNetwork(network.netId, function() {});
- continue;
- }
-
- if (network.hasOwnProperty("priority") &&
- network.priority > this._highestPriority) {
- this._highestPriority = network.priority;
- }
-
- let networkKey = getNetworkKey(network);
- // Accept latest config of same network(same SSID and same security).
- if (networks[networkKey]) {
- WifiManager.removeNetwork(networks[networkKey].netId, function() {});
- }
- networks[networkKey] = network;
- }
-
- this.configuredNetworks = networks;
- callback(true);
- }).bind(this));
- },
-
- // Important side effect: calls WifiManager.saveConfig.
- _reprioritizeNetworks: function(callback) {
- // First, sort the networks in orer of their priority.
- var ordered = Object.getOwnPropertyNames(this.configuredNetworks);
- let self = this;
- ordered.sort(function(a, b) {
- var neta = self.configuredNetworks[a],
- netb = self.configuredNetworks[b];
-
- // Sort unsorted networks to the end of the list.
- if (isNaN(neta.priority))
- return isNaN(netb.priority) ? 0 : 1;
- if (isNaN(netb.priority))
- return -1;
- return netb.priority - neta.priority;
- });
-
- // Skip unsorted networks.
- let newPriority = 0, i;
- for (i = ordered.length - 1; i >= 0; --i) {
- if (!isNaN(this.configuredNetworks[ordered[i]].priority))
- break;
- }
-
- // No networks we care about?
- if (i < 0) {
- WifiManager.saveConfig(callback);
- return;
- }
-
- // Now assign priorities from 0 to length, starting with the smallest
- // priority and heading towards the highest (note the dependency between
- // total and i here).
- let done = 0, errors = 0, total = i + 1;
- for (; i >= 0; --i) {
- let network = this.configuredNetworks[ordered[i]];
- network.priority = newPriority++;
-
- // Note: networkUpdated declared below since it happens logically after
- // this loop.
- WifiManager.updateNetwork(network, networkUpdated);
- }
-
- function networkUpdated(ok) {
- if (!ok)
- ++errors;
- if (++done === total) {
- if (errors > 0) {
- callback(false);
- return;
- }
-
- WifiManager.saveConfig(function(ok) {
- if (!ok) {
- callback(false);
- return;
- }
-
- self._reloadConfiguredNetworks(function(ok) {
- callback(ok);
- });
- });
- }
- }
- },
-
- // nsIWifi
-
- _domManagers: [],
- _fireEvent: function(message, data) {
- this._domManagers.forEach(function(manager) {
- // Note: We should never have a dead message manager here because we
- // observe our child message managers shutting down, below.
- manager.sendAsyncMessage("WifiManager:" + message, data);
- });
- },
-
- _sendMessage: function(message, success, data, msg) {
- try {
- msg.manager.sendAsyncMessage(message + (success ? ":OK" : ":NO"),
- { data: data, rid: msg.rid, mid: msg.mid });
- } catch (e) {
- debug("sendAsyncMessage error : " + e);
- }
- this._splicePendingRequest(msg);
- },
-
- _domRequest: [],
-
- _splicePendingRequest: function(msg) {
- for (let i = 0; i < this._domRequest.length; i++) {
- if (this._domRequest[i].msg === msg) {
- this._domRequest.splice(i, 1);
- return;
- }
- }
- },
-
- _clearPendingRequest: function() {
- if (this._domRequest.length === 0) return;
- this._domRequest.forEach((function(req) {
- this._sendMessage(req.name + ":Return", false, "Wifi is disabled", req.msg);
- }).bind(this));
- },
-
- receiveMessage: function MessageManager_receiveMessage(aMessage) {
- let msg = aMessage.data || {};
- msg.manager = aMessage.target;
-
- if (WifiManager.p2pSupported()) {
- // If p2pObserver returns something truthy, return it!
- // Otherwise, continue to do the rest of tasks.
- var p2pRet = this._p2pObserver.onDOMMessage(aMessage);
- if (p2pRet) {
- return p2pRet;
- }
- }
-
- // Note: By the time we receive child-process-shutdown, the child process
- // has already forgotten its permissions so we do this before the
- // permissions check.
- if (aMessage.name === "child-process-shutdown") {
- let i;
- if ((i = this._domManagers.indexOf(msg.manager)) != -1) {
- this._domManagers.splice(i, 1);
- }
- for (i = this._domRequest.length - 1; i >= 0; i--) {
- if (this._domRequest[i].msg.manager === msg.manager) {
- this._domRequest.splice(i, 1);
- }
- }
- return;
- }
-
- if (!aMessage.target.assertPermission("wifi-manage")) {
- return;
- }
-
- // We are interested in DOMRequests only.
- if (aMessage.name != "WifiManager:getState") {
- this._domRequest.push({name: aMessage.name, msg:msg});
- }
-
- switch (aMessage.name) {
- case "WifiManager:setWifiEnabled":
- this.setWifiEnabled(msg);
- break;
- case "WifiManager:getNetworks":
- this.getNetworks(msg);
- break;
- case "WifiManager:getKnownNetworks":
- this.getKnownNetworks(msg);
- break;
- case "WifiManager:associate":
- this.associate(msg);
- break;
- case "WifiManager:forget":
- this.forget(msg);
- break;
- case "WifiManager:wps":
- this.wps(msg);
- break;
- case "WifiManager:setPowerSavingMode":
- this.setPowerSavingMode(msg);
- break;
- case "WifiManager:setHttpProxy":
- this.setHttpProxy(msg);
- break;
- case "WifiManager:setStaticIpMode":
- this.setStaticIpMode(msg);
- break;
- case "WifiManager:importCert":
- this.importCert(msg);
- break;
- case "WifiManager:getImportedCerts":
- this.getImportedCerts(msg);
- break;
- case "WifiManager:deleteCert":
- this.deleteCert(msg);
- break;
- case "WifiManager:setWifiTethering":
- this.setWifiTethering(msg);
- break;
- case "WifiManager:getState": {
- let i;
- if ((i = this._domManagers.indexOf(msg.manager)) === -1) {
- this._domManagers.push(msg.manager);
- }
-
- let net = this.currentNetwork ? netToDOM(this.currentNetwork) : null;
- return { network: net,
- connectionInfo: this._lastConnectionInfo,
- enabled: WifiManager.enabled,
- status: translateState(WifiManager.state),
- macAddress: this.macAddress,
- capabilities: WifiManager.getCapabilities()};
- }
- }
- },
-
- getNetworks: function(msg) {
- const message = "WifiManager:getNetworks:Return";
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- let sent = false;
- let callback = (function (networks) {
- if (sent)
- return;
- sent = true;
- this._sendMessage(message, networks !== null, networks, msg);
- }).bind(this);
- this.waitForScan(callback);
-
- WifiManager.scan(true, (function(ok) {
- // If the scan command succeeded, we're done.
- if (ok)
- return;
-
- // Avoid sending multiple responses.
- if (sent)
- return;
-
- // Otherwise, let the client know that it failed, it's responsible for
- // trying again in a few seconds.
- sent = true;
- this._sendMessage(message, false, "ScanFailed", msg);
- }).bind(this));
- },
-
- getWifiScanResults: function(callback) {
- var count = 0;
- var timer = null;
- var self = this;
-
- if (!WifiManager.enabled) {
- callback.onfailure();
- return;
- }
-
- self.waitForScan(waitForScanCallback);
- doScan();
- function doScan() {
- WifiManager.scan(true, (function (ok) {
- if (!ok) {
- if (!timer) {
- count = 0;
- timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- }
-
- if (count++ >= 3) {
- timer = null;
- self.wantScanResults.splice(self.wantScanResults.indexOf(waitForScanCallback), 1);
- callback.onfailure();
- return;
- }
-
- // Else it's still running, continue waiting.
- timer.initWithCallback(doScan, 10000, Ci.nsITimer.TYPE_ONE_SHOT);
- return;
- }
- }).bind(this));
- }
-
- function waitForScanCallback(networks) {
- if (networks === null) {
- callback.onfailure();
- return;
- }
-
- var wifiScanResults = new Array();
- var net;
- for (let net in networks) {
- let value = networks[net];
- wifiScanResults.push(transformResult(value));
- }
- callback.onready(wifiScanResults.length, wifiScanResults);
- }
-
- function transformResult(element) {
- var result = new WifiScanResult();
- result.connected = false;
- for (let id in element) {
- if (id === "__exposedProps__") {
- continue;
- }
- if (id === "security") {
- result[id] = 0;
- var security = element[id];
- for (let j = 0; j < security.length; j++) {
- if (security[j] === "WPA-PSK") {
- result[id] |= Ci.nsIWifiScanResult.WPA_PSK;
- } else if (security[j] === "WPA-EAP") {
- result[id] |= Ci.nsIWifiScanResult.WPA_EAP;
- } else if (security[j] === "WEP") {
- result[id] |= Ci.nsIWifiScanResult.WEP;
- } else {
- result[id] = 0;
- }
- }
- } else {
- result[id] = element[id];
- }
- }
- return result;
- }
- },
-
- getKnownNetworks: function(msg) {
- const message = "WifiManager:getKnownNetworks:Return";
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- this._reloadConfiguredNetworks((function(ok) {
- if (!ok) {
- this._sendMessage(message, false, "Failed", msg);
- return;
- }
-
- var networks = [];
- for (let networkKey in this.configuredNetworks) {
- networks.push(netToDOM(this.configuredNetworks[networkKey]));
- }
-
- this._sendMessage(message, true, networks, msg);
- }).bind(this));
- },
-
- _setWifiEnabledCallback: function(status) {
- if (status !== 0) {
- this.requestDone();
- return;
- }
-
- // If we're enabling ourselves, then wait until we've connected to the
- // supplicant to notify. If we're disabling, we take care of this in
- // supplicantlost.
- if (WifiManager.supplicantStarted)
- WifiManager.start();
- },
-
- /**
- * Compatibility flags for detecting if Gaia is controlling wifi by settings
- * or API, once API is called, gecko will no longer accept wifi enable
- * control from settings.
- * This is used to deal with compatibility issue while Gaia adopted to use
- * API but gecko doesn't remove the settings code in time.
- * TODO: Remove this flag in Bug 1050147
- */
- ignoreWifiEnabledFromSettings: false,
- setWifiEnabled: function(msg) {
- const message = "WifiManager:setWifiEnabled:Return";
- let self = this;
- let enabled = msg.data;
-
- self.ignoreWifiEnabledFromSettings = true;
- // No change.
- if (enabled === WifiManager.enabled) {
- this._sendMessage(message, true, true, msg);
- return;
- }
-
- // Can't enable wifi while hotspot mode is enabled.
- if (enabled && (this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED] ||
- WifiManager.isWifiTetheringEnabled(WifiManager.tetheringState))) {
- self._sendMessage(message, false, "Can't enable Wifi while hotspot mode is enabled", msg);
- return;
- }
-
- WifiManager.setWifiEnabled(enabled, function(ok) {
- if (ok === 0 || ok === "no change") {
- self._sendMessage(message, true, true, msg);
-
- // Reply error to pending requests.
- if (!enabled) {
- self._clearPendingRequest();
- } else {
- WifiManager.start();
- }
- } else {
- self._sendMessage(message, false, "Set wifi enabled failed", msg);
- }
- });
- },
-
- _setWifiEnabled: function(enabled, callback) {
- // Reply error to pending requests.
- if (!enabled) {
- this._clearPendingRequest();
- }
-
- WifiManager.setWifiEnabled(enabled, callback);
- },
-
- // requestDone() must be called to before callback complete(or error)
- // so next queue in the request quene can be executed.
- // TODO: Remove command queue in Bug 1050147
- queueRequest: function(data, callback) {
- if (!callback) {
- throw "Try to enqueue a request without callback";
- }
-
- let optimizeCommandList = ["setWifiEnabled", "setWifiApEnabled"];
- if (optimizeCommandList.indexOf(data.command) != -1) {
- this._stateRequests = this._stateRequests.filter(function(element) {
- return element.data.command !== data.command;
- });
- }
-
- this._stateRequests.push({
- data: data,
- callback: callback
- });
-
- this.nextRequest();
- },
-
- getWifiTetheringParameters: function getWifiTetheringParameters(enable) {
- if (this.useTetheringAPI) {
- return this.getWifiTetheringConfiguration(enable);
- } else {
- return this.getWifiTetheringParametersBySetting(enable);
- }
- },
-
- getWifiTetheringConfiguration: function getWifiTetheringConfiguration(enable) {
- let config = {};
- let params = this.tetheringConfig;
-
- let check = function(field, _default) {
- config[field] = field in params ? params[field] : _default;
- };
-
- check("ssid", DEFAULT_WIFI_SSID);
- check("security", DEFAULT_WIFI_SECURITY_TYPE);
- check("key", DEFAULT_WIFI_SECURITY_PASSWORD);
- check("ip", DEFAULT_WIFI_IP);
- check("prefix", DEFAULT_WIFI_PREFIX);
- check("wifiStartIp", DEFAULT_WIFI_DHCPSERVER_STARTIP);
- check("wifiEndIp", DEFAULT_WIFI_DHCPSERVER_ENDIP);
- check("usbStartIp", DEFAULT_USB_DHCPSERVER_STARTIP);
- check("usbEndIp", DEFAULT_USB_DHCPSERVER_ENDIP);
- check("dns1", DEFAULT_DNS1);
- check("dns2", DEFAULT_DNS2);
-
- config.enable = enable;
- config.mode = enable ? WIFI_FIRMWARE_AP : WIFI_FIRMWARE_STATION;
- config.link = enable ? NETWORK_INTERFACE_UP : NETWORK_INTERFACE_DOWN;
-
- // Check the format to prevent netd from crash.
- if (enable && (!config.ssid || config.ssid == "")) {
- debug("Invalid SSID value.");
- return null;
- }
-
- if (enable && (config.security != WIFI_SECURITY_TYPE_NONE && !config.key)) {
- debug("Invalid security password.");
- return null;
- }
-
- // Using the default values here until application supports these settings.
- if (config.ip == "" || config.prefix == "" ||
- config.wifiStartIp == "" || config.wifiEndIp == "" ||
- config.usbStartIp == "" || config.usbEndIp == "") {
- debug("Invalid subnet information.");
- return null;
- }
-
- return config;
- },
-
- getWifiTetheringParametersBySetting: function getWifiTetheringParametersBySetting(enable) {
- let ssid;
- let securityType;
- let securityId;
- let interfaceIp;
- let prefix;
- let wifiDhcpStartIp;
- let wifiDhcpEndIp;
- let usbDhcpStartIp;
- let usbDhcpEndIp;
- let dns1;
- let dns2;
-
- ssid = this.tetheringSettings[SETTINGS_WIFI_SSID];
- securityType = this.tetheringSettings[SETTINGS_WIFI_SECURITY_TYPE];
- securityId = this.tetheringSettings[SETTINGS_WIFI_SECURITY_PASSWORD];
- interfaceIp = this.tetheringSettings[SETTINGS_WIFI_IP];
- prefix = this.tetheringSettings[SETTINGS_WIFI_PREFIX];
- wifiDhcpStartIp = this.tetheringSettings[SETTINGS_WIFI_DHCPSERVER_STARTIP];
- wifiDhcpEndIp = this.tetheringSettings[SETTINGS_WIFI_DHCPSERVER_ENDIP];
- usbDhcpStartIp = this.tetheringSettings[SETTINGS_USB_DHCPSERVER_STARTIP];
- usbDhcpEndIp = this.tetheringSettings[SETTINGS_USB_DHCPSERVER_ENDIP];
- dns1 = this.tetheringSettings[SETTINGS_WIFI_DNS1];
- dns2 = this.tetheringSettings[SETTINGS_WIFI_DNS2];
-
- // Check the format to prevent netd from crash.
- if (!ssid || ssid == "") {
- debug("Invalid SSID value.");
- return null;
- }
- // Truncate ssid if its length of encoded to utf8 is longer than 32.
- while (unescape(encodeURIComponent(ssid)).length > 32)
- {
- ssid = ssid.substring(0, ssid.length-1);
- }
-
- if (securityType != WIFI_SECURITY_TYPE_NONE &&
- securityType != WIFI_SECURITY_TYPE_WPA_PSK &&
- securityType != WIFI_SECURITY_TYPE_WPA2_PSK) {
-
- debug("Invalid security type.");
- return null;
- }
- if (securityType != WIFI_SECURITY_TYPE_NONE && !securityId) {
- debug("Invalid security password.");
- return null;
- }
- // Using the default values here until application supports these settings.
- if (interfaceIp == "" || prefix == "" ||
- wifiDhcpStartIp == "" || wifiDhcpEndIp == "" ||
- usbDhcpStartIp == "" || usbDhcpEndIp == "") {
- debug("Invalid subnet information.");
- return null;
- }
-
- return {
- ssid: ssid,
- security: securityType,
- key: securityId,
- ip: interfaceIp,
- prefix: prefix,
- wifiStartIp: wifiDhcpStartIp,
- wifiEndIp: wifiDhcpEndIp,
- usbStartIp: usbDhcpStartIp,
- usbEndIp: usbDhcpEndIp,
- dns1: dns1,
- dns2: dns2,
- enable: enable,
- mode: enable ? WIFI_FIRMWARE_AP : WIFI_FIRMWARE_STATION,
- link: enable ? NETWORK_INTERFACE_UP : NETWORK_INTERFACE_DOWN
- };
- },
-
- setWifiApEnabled: function(enabled, callback) {
- let configuration = this.getWifiTetheringParameters(enabled);
-
- if (!configuration) {
- this.requestDone();
- debug("Invalid Wifi Tethering configuration.");
- return;
- }
-
- WifiManager.setWifiApEnabled(enabled, configuration, callback);
- },
-
- associate: function(msg) {
- const MAX_PRIORITY = 9999;
- const message = "WifiManager:associate:Return";
- let network = msg.data;
-
- let privnet = network;
- let dontConnect = privnet.dontConnect;
- delete privnet.dontConnect;
-
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- let self = this;
- function networkReady() {
- // saveConfig now before we disable most of the other networks.
- function selectAndConnect() {
- WifiManager.enableNetwork(privnet.netId, true, function (ok) {
- if (ok)
- self._needToEnableNetworks = true;
- if (WifiManager.state === "DISCONNECTED" ||
- WifiManager.state === "SCANNING") {
- WifiManager.reconnect(function (ok) {
- self._sendMessage(message, ok, ok, msg);
- });
- } else {
- self._sendMessage(message, ok, ok, msg);
- }
- });
- }
-
- var selectAndConnectOrReturn = dontConnect ?
- function() {
- self._sendMessage(message, true, "Wifi has been recorded", msg);
- } : selectAndConnect;
- if (self._highestPriority >= MAX_PRIORITY) {
- self._reprioritizeNetworks(selectAndConnectOrReturn);
- } else {
- WifiManager.saveConfig(selectAndConnectOrReturn);
- }
- }
-
- function connectToNetwork() {
- WifiManager.updateNetwork(privnet, (function(ok) {
- if (!ok) {
- self._sendMessage(message, false, "Network is misconfigured", msg);
- return;
- }
-
- networkReady();
- }));
- }
-
- let ssid = privnet.ssid;
- let networkKey = getNetworkKey(privnet);
- let configured;
-
- if (networkKey in this._addingNetworks) {
- this._sendMessage(message, false, "Racing associates");
- return;
- }
-
- if (networkKey in this.configuredNetworks)
- configured = this.configuredNetworks[networkKey];
-
- netFromDOM(privnet, configured);
-
- privnet.priority = ++this._highestPriority;
- if (configured) {
- privnet.netId = configured.netId;
- // Sync priority back to configured so if priority reaches MAX_PRIORITY,
- // it can be sorted correctly in _reprioritizeNetworks() because the
- // function sort network based on priority in configure list.
- configured.priority = privnet.priority;
-
- // When investigating Bug 1123680, we observed that gaia may unexpectedly
- // request to associate with incorrect password before successfully
- // forgetting the network. It would cause the network unable to connect
- // subsequently. Aside from preventing the racing forget/associate, we
- // also try to disable network prior to updating the network.
- WifiManager.getNetworkId(dequote(configured.ssid), function(netId) {
- if (netId) {
- WifiManager.disableNetwork(netId, function() {
- connectToNetwork();
- });
- }
- else {
- connectToNetwork();
- }
- });
- } else {
- // networkReady, above, calls saveConfig. We want to remember the new
- // network as being enabled, which isn't the default, so we explicitly
- // set it to being "enabled" before we add it and save the
- // configuration.
- privnet.disabled = 0;
- this._addingNetworks[networkKey] = privnet;
- WifiManager.addNetwork(privnet, (function(ok) {
- delete this._addingNetworks[networkKey];
-
- if (!ok) {
- this._sendMessage(message, false, "Network is misconfigured", msg);
- return;
- }
-
- this.configuredNetworks[networkKey] = privnet;
- networkReady();
- }).bind(this));
- }
- },
-
- forget: function(msg) {
- const message = "WifiManager:forget:Return";
- let network = msg.data;
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- this._reloadConfiguredNetworks((function(ok) {
- // Give it a chance to remove the network even if reload is failed.
- if (!ok) {
- debug("Warning !!! Failed to reload the configured networks");
- }
-
- let ssid = network.ssid;
- let networkKey = getNetworkKey(network);
- if (!(networkKey in this.configuredNetworks)) {
- this._sendMessage(message, false, "Trying to forget an unknown network", msg);
- return;
- }
-
- let self = this;
- let configured = this.configuredNetworks[networkKey];
- this._reconnectOnDisconnect = (this.currentNetwork &&
- (this.currentNetwork.ssid === ssid));
- WifiManager.removeNetwork(configured.netId, function(ok) {
- if (self._needToEnableNetworks) {
- self._enableAllNetworks();
- self._needToEnableNetworks = false;
- }
-
- if (!ok) {
- self._sendMessage(message, false, "Unable to remove the network", msg);
- self._reconnectOnDisconnect = false;
- return;
- }
-
- WifiManager.saveConfig(function() {
- self._reloadConfiguredNetworks(function() {
- self._sendMessage(message, true, true, msg);
- });
- });
- });
- }).bind(this));
- },
-
- wps: function(msg) {
- const message = "WifiManager:wps:Return";
- let self = this;
- let detail = msg.data;
-
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- if (detail.method === "pbc") {
- WifiManager.wpsPbc(function(ok) {
- if (ok)
- self._sendMessage(message, true, true, msg);
- else
- self._sendMessage(message, false, "WPS PBC failed", msg);
- });
- } else if (detail.method === "pin") {
- WifiManager.wpsPin(detail, function(pin) {
- if (pin)
- self._sendMessage(message, true, pin, msg);
- else
- self._sendMessage(message, false, "WPS PIN failed", msg);
- });
- } else if (detail.method === "cancel") {
- WifiManager.wpsCancel(function(ok) {
- if (ok)
- self._sendMessage(message, true, true, msg);
- else
- self._sendMessage(message, false, "WPS Cancel failed", msg);
- });
- } else {
- self._sendMessage(message, false, "Invalid WPS method=" + detail.method,
- msg);
- }
- },
-
- setPowerSavingMode: function(msg) {
- const message = "WifiManager:setPowerSavingMode:Return";
- let self = this;
- let enabled = msg.data;
- let mode = enabled ? "AUTO" : "ACTIVE";
-
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- // Some wifi drivers may not implement this command. Set power mode
- // even if suspend optimization command failed.
- WifiManager.setSuspendOptimizations(enabled, function(ok) {
- WifiManager.setPowerMode(mode, function(ok) {
- if (ok) {
- self._sendMessage(message, true, true, msg);
- } else {
- self._sendMessage(message, false, "Set power saving mode failed", msg);
- }
- });
- });
- },
-
- setHttpProxy: function(msg) {
- const message = "WifiManager:setHttpProxy:Return";
- let self = this;
- let network = msg.data.network;
- let info = msg.data.info;
-
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- WifiManager.configureHttpProxy(network, info, function(ok) {
- if (ok) {
- // If configured network is current connected network
- // need update http proxy immediately.
- let setNetworkKey = getNetworkKey(network);
- let curNetworkKey = self.currentNetwork ? getNetworkKey(self.currentNetwork) : null;
- if (setNetworkKey === curNetworkKey)
- WifiManager.setHttpProxy(network);
-
- self._sendMessage(message, true, true, msg);
- } else {
- self._sendMessage(message, false, "Set http proxy failed", msg);
- }
- });
- },
-
- setStaticIpMode: function(msg) {
- const message = "WifiManager:setStaticIpMode:Return";
- let self = this;
- let network = msg.data.network;
- let info = msg.data.info;
-
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- // To compatiable with DHCP returned info structure, do translation here
- info.ipaddr_str = info.ipaddr;
- info.proxy_str = info.proxy;
- info.gateway_str = info.gateway;
- info.dns1_str = info.dns1;
- info.dns2_str = info.dns2;
-
- WifiManager.setStaticIpMode(network, info, function(ok) {
- if (ok) {
- self._sendMessage(message, true, true, msg);
- } else {
- self._sendMessage(message, false, "Set static ip mode failed", msg);
- }
- });
- },
-
- importCert: function importCert(msg) {
- const message = "WifiManager:importCert:Return";
- let self = this;
-
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- WifiManager.importCert(msg.data, function(data) {
- if (data.status === 0) {
- let usageString = ["ServerCert", "UserCert"];
- let usageArray = [];
- for (let i = 0; i < usageString.length; i++) {
- if (data.usageFlag & (0x01 << i)) {
- usageArray.push(usageString[i]);
- }
- }
-
- self._sendMessage(message, true, {
- nickname: data.nickname,
- usage: usageArray
- }, msg);
- } else {
- self._sendMessage(message, false, "Import Cert failed", msg);
- }
- });
- },
-
- getImportedCerts: function getImportedCerts(msg) {
- const message = "WifiManager:getImportedCerts:Return";
- let self = this;
-
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- let certDB = Cc["@mozilla.org/security/x509certdb;1"]
- .getService(Ci.nsIX509CertDB);
- if (!certDB) {
- self._sendMessage(message, false, "Failed to query NSS DB service", msg);
- }
-
- let certList = certDB.getCerts();
- if (!certList) {
- self._sendMessage(message, false, "Failed to get certificate List", msg);
- }
-
- let certListEnum = certList.getEnumerator();
- if (!certListEnum) {
- self._sendMessage(message, false, "Failed to get certificate List enumerator", msg);
- }
- let importedCerts = {
- ServerCert: [],
- UserCert: [],
- };
- let UsageMapping = {
- SERVERCERT: "ServerCert",
- USERCERT: "UserCert",
- };
-
- while (certListEnum.hasMoreElements()) {
- let certInfo = certListEnum.getNext().QueryInterface(Ci.nsIX509Cert);
- let certNicknameInfo = /WIFI\_([A-Z]*)\_(.*)/.exec(certInfo.nickname);
- if (!certNicknameInfo) {
- continue;
- }
- importedCerts[UsageMapping[certNicknameInfo[1]]].push(certNicknameInfo[2]);
- }
-
- self._sendMessage(message, true, importedCerts, msg);
- },
-
- deleteCert: function deleteCert(msg) {
- const message = "WifiManager:deleteCert:Return";
- let self = this;
-
- if (!WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is disabled", msg);
- return;
- }
-
- WifiManager.deleteCert(msg.data, function(data) {
- self._sendMessage(message, data.status === 0, "Delete Cert failed", msg);
- });
- },
-
- // TODO : These two variables should be removed once GAIA uses tethering API.
- useTetheringAPI : false,
- tetheringConfig : {},
-
- setWifiTethering: function setWifiTethering(msg) {
- const message = "WifiManager:setWifiTethering:Return";
- let self = this;
- let enabled = msg.data.enabled;
-
- this.useTetheringAPI = true;
- this.tetheringConfig = msg.data.config;
-
- if (WifiManager.enabled) {
- this._sendMessage(message, false, "Wifi is enabled", msg);
- return;
- }
-
- this.setWifiApEnabled(enabled, function() {
- if ((enabled && WifiManager.tetheringState == "COMPLETED") ||
- (!enabled && WifiManager.tetheringState == "UNINITIALIZED")) {
- self._sendMessage(message, true, msg.data, msg);
- } else {
- msg.data.reason = enabled ?
- "Enable WIFI tethering faild" : "Disable WIFI tethering faild";
- self._sendMessage(message, false, msg.data, msg);
- }
- });
- },
-
- // This is a bit ugly, but works. In particular, this depends on the fact
- // that RadioManager never actually tries to get the worker from us.
- get worker() { throw "Not implemented"; },
-
- shutdown: function() {
- debug("shutting down ...");
- this.queueRequest({command: "setWifiEnabled", value: false}, function(data) {
- this._setWifiEnabled(false, this._setWifiEnabledCallback.bind(this));
- }.bind(this));
- },
-
- // TODO: Remove command queue in Bug 1050147.
- requestProcessing: false, // Hold while dequeue and execution a request.
- // Released upon the request is fully executed,
- // i.e, mostly after callback is done.
- requestDone: function requestDone() {
- this.requestProcessing = false;
- this.nextRequest();
- },
-
- nextRequest: function nextRequest() {
- // No request to process
- if (this._stateRequests.length === 0) {
- return;
- }
-
- // Handling request, wait for it.
- if (this.requestProcessing) {
- return;
- }
-
- // Hold processing lock
- this.requestProcessing = true;
-
- // Find next valid request
- let request = this._stateRequests.shift();
-
- request.callback(request.data);
- },
-
- notifyTetheringOn: function notifyTetheringOn() {
- // It's really sad that we don't have an API to notify the wifi
- // hotspot status. Toggle settings to let gaia know that wifi hotspot
- // is enabled.
- let self = this;
- this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED] = true;
- this._oldWifiTetheringEnabledState = true;
- gSettingsService.createLock().set(
- SETTINGS_WIFI_TETHERING_ENABLED,
- true,
- {
- handle: function(aName, aResult) {
- self.requestDone();
- },
- handleError: function(aErrorMessage) {
- self.requestDone();
- }
- });
- },
-
- notifyTetheringOff: function notifyTetheringOff() {
- // It's really sad that we don't have an API to notify the wifi
- // hotspot status. Toggle settings to let gaia know that wifi hotspot
- // is disabled.
- let self = this;
- this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED] = false;
- this._oldWifiTetheringEnabledState = false;
- gSettingsService.createLock().set(
- SETTINGS_WIFI_TETHERING_ENABLED,
- false,
- {
- handle: function(aName, aResult) {
- self.requestDone();
- },
- handleError: function(aErrorMessage) {
- self.requestDone();
- }
- });
- },
-
- handleWifiEnabled: function(enabled) {
- if (this.ignoreWifiEnabledFromSettings) {
- return;
- }
-
- // Make sure Wifi hotspot is idle before switching to Wifi mode.
- if (enabled) {
- this.queueRequest({command: "setWifiApEnabled", value: false}, function(data) {
- if (this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED] ||
- WifiManager.isWifiTetheringEnabled(WifiManager.tetheringState)) {
- this.disconnectedByWifi = true;
- this.setWifiApEnabled(false, this.notifyTetheringOff.bind(this));
- } else {
- this.requestDone();
- }
- }.bind(this));
- }
-
- this.queueRequest({command: "setWifiEnabled", value: enabled}, function(data) {
- this._setWifiEnabled(enabled, this._setWifiEnabledCallback.bind(this));
- }.bind(this));
-
- if (!enabled) {
- this.queueRequest({command: "setWifiApEnabled", value: true}, function(data) {
- if (this.disconnectedByWifi) {
- this.setWifiApEnabled(true, this.notifyTetheringOn.bind(this));
- } else {
- this.requestDone();
- }
- this.disconnectedByWifi = false;
- }.bind(this));
- }
- },
-
- handleWifiTetheringEnabled: function(enabled) {
- // Make sure Wifi is idle before switching to Wifi hotspot mode.
- if (enabled) {
- this.queueRequest({command: "setWifiEnabled", value: false}, function(data) {
- if (WifiManager.isWifiEnabled(WifiManager.state)) {
- this.disconnectedByWifiTethering = true;
- this._setWifiEnabled(false, this._setWifiEnabledCallback.bind(this));
- } else {
- this.requestDone();
- }
- }.bind(this));
- }
-
- this.queueRequest({command: "setWifiApEnabled", value: enabled}, function(data) {
- this.setWifiApEnabled(enabled, this.requestDone.bind(this));
- }.bind(this));
-
- if (!enabled) {
- this.queueRequest({command: "setWifiEnabled", value: true}, function(data) {
- if (this.disconnectedByWifiTethering) {
- this._setWifiEnabled(true, this._setWifiEnabledCallback.bind(this));
- } else {
- this.requestDone();
- }
- this.disconnectedByWifiTethering = false;
- }.bind(this));
- }
- },
-
- // nsIObserver implementation
- observe: function observe(subject, topic, data) {
- switch (topic) {
- case kMozSettingsChangedObserverTopic:
- // To avoid WifiWorker setting the wifi again, don't need to deal with
- // the "mozsettings-changed" event fired from internal setting.
- if ("wrappedJSObject" in subject) {
- subject = subject.wrappedJSObject;
- }
- if (subject.isInternalChange) {
- return;
- }
-
- this.handle(subject.key, subject.value);
- break;
-
- case "xpcom-shutdown":
- // Ensure the supplicant is detached from B2G to avoid XPCOM shutdown
- // blocks forever.
- WifiManager.ensureSupplicantDetached(() => {
- let wifiService = Cc["@mozilla.org/wifi/service;1"].getService(Ci.nsIWifiProxyService);
- wifiService.shutdown();
- let wifiCertService = Cc["@mozilla.org/wifi/certservice;1"].getService(Ci.nsIWifiCertService);
- wifiCertService.shutdown();
- });
- break;
- }
- },
-
- handle: function handle(aName, aResult) {
- switch(aName) {
- // TODO: Remove function call in Bug 1050147.
- case SETTINGS_WIFI_ENABLED:
- this.handleWifiEnabled(aResult)
- break;
- case SETTINGS_WIFI_DEBUG_ENABLED:
- if (aResult === null)
- aResult = false;
- DEBUG = aResult;
- updateDebug();
- break;
- case SETTINGS_WIFI_TETHERING_ENABLED:
- this._oldWifiTetheringEnabledState = this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED];
- // Fall through!
- case SETTINGS_WIFI_SSID:
- case SETTINGS_WIFI_SECURITY_TYPE:
- case SETTINGS_WIFI_SECURITY_PASSWORD:
- case SETTINGS_WIFI_IP:
- case SETTINGS_WIFI_PREFIX:
- case SETTINGS_WIFI_DHCPSERVER_STARTIP:
- case SETTINGS_WIFI_DHCPSERVER_ENDIP:
- case SETTINGS_WIFI_DNS1:
- case SETTINGS_WIFI_DNS2:
- case SETTINGS_USB_DHCPSERVER_STARTIP:
- case SETTINGS_USB_DHCPSERVER_ENDIP:
- // TODO: code related to wifi-tethering setting should be removed after GAIA
- // use tethering API
- if (this.useTetheringAPI) {
- break;
- }
-
- if (aResult !== null) {
- this.tetheringSettings[aName] = aResult;
- }
- debug("'" + aName + "'" + " is now " + this.tetheringSettings[aName]);
- let index = this._wifiTetheringSettingsToRead.indexOf(aName);
-
- if (index != -1) {
- this._wifiTetheringSettingsToRead.splice(index, 1);
- }
-
- if (this._wifiTetheringSettingsToRead.length) {
- debug("We haven't read completely the wifi Tethering data from settings db.");
- break;
- }
-
- if (this._oldWifiTetheringEnabledState === this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED]) {
- debug("No changes for SETTINGS_WIFI_TETHERING_ENABLED flag. Nothing to do.");
- break;
- }
-
- if (this._oldWifiTetheringEnabledState === null &&
- !this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED]) {
- debug("Do nothing when initial settings for SETTINGS_WIFI_TETHERING_ENABLED flag is false.");
- break;
- }
-
- this._oldWifiTetheringEnabledState = this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED];
- this.handleWifiTetheringEnabled(aResult)
- break;
- };
- },
-
- handleError: function handleError(aErrorMessage) {
- debug("There was an error while reading Tethering settings.");
- this.tetheringSettings = {};
- this.tetheringSettings[SETTINGS_WIFI_TETHERING_ENABLED] = false;
- },
-};
-
-this.NSGetFactory = XPCOMUtils.generateNSGetFactory([WifiWorker]);
-
-var debug;
-function updateDebug() {
- if (DEBUG) {
- debug = function (s) {
- dump("-*- WifiWorker component: " + s + "\n");
- };
- } else {
- debug = function (s) {};
- }
- WifiManager.syncDebug();
-}
-updateDebug();
diff --git a/dom/wifi/WifiWorker.manifest b/dom/wifi/WifiWorker.manifest
deleted file mode 100644
index e33d6401a..000000000
--- a/dom/wifi/WifiWorker.manifest
+++ /dev/null
@@ -1 +0,0 @@
-component {a14e8977-d259-433a-a88d-58dd44657e5b} WifiWorker.js
diff --git a/dom/wifi/moz.build b/dom/wifi/moz.build
deleted file mode 100644
index d769c649c..000000000
--- a/dom/wifi/moz.build
+++ /dev/null
@@ -1,41 +0,0 @@
-# -*- 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/.
-
-XPIDL_SOURCES += [
- 'nsIWifi.idl',
- 'nsIWifiCertService.idl',
- 'nsIWifiService.idl',
-]
-
-XPIDL_MODULE = 'dom_wifi'
-
-EXTRA_COMPONENTS += [
- 'DOMWifiManager.js',
- 'DOMWifiManager.manifest',
- 'DOMWifiP2pManager.js',
- 'DOMWifiP2pManager.manifest',
- 'WifiWorker.js',
- 'WifiWorker.manifest',
-]
-
-EXTRA_JS_MODULES += [
- 'StateMachine.jsm',
- 'WifiCommand.jsm',
- 'WifiNetUtil.jsm',
- 'WifiP2pManager.jsm',
- 'WifiP2pWorkerObserver.jsm',
-]
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- UNIFIED_SOURCES = [
- 'WifiCertService.cpp',
- 'WifiHotspotUtils.cpp',
- 'WifiProxyService.cpp',
- 'WifiUtils.cpp',
- ]
- DEFINES['CERT_AddTempCertToPerm'] = '__CERT_AddTempCertToPerm'
-
-FINAL_LIBRARY = 'xul'
diff --git a/dom/wifi/nsIWifi.idl b/dom/wifi/nsIWifi.idl
deleted file mode 100644
index 82ab9a75b..000000000
--- a/dom/wifi/nsIWifi.idl
+++ /dev/null
@@ -1,60 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-#include "nsIDOMDOMRequest.idl"
-#include "nsIDOMEvent.idl"
-
-interface nsIVariant;
-
-[scriptable, uuid(cf1ac02b-1f39-446e-815b-651ac78d2233)]
-interface nsIWifiScanResult : nsISupports {
- readonly attribute DOMString ssid;
- readonly attribute DOMString bssid;
-
- const int32_t WPA_PSK = 0x01;
- const int32_t WPA_EAP = 0x02;
- const int32_t WEP = 0x04;
- readonly attribute uint32_t capabilities;
-
- /**
- * Strength of the signal to network.
- */
- readonly attribute uint32_t signalStrength;
-
- readonly attribute uint32_t relSignalStrength;
- readonly attribute boolean connected;
-};
-
-[scriptable, uuid(a6931ebf-8493-4014-90e2-99f406999982)]
-interface nsIWifiScanResultsReady : nsISupports {
-
- /**
- * Callback with list of networks.
- */
- void onready(in uint32_t count, [array, size_is(count)] in nsIWifiScanResult results);
-
- /**
- * Callback if scanning for networks failed after 3 retry attempts.
- */
- void onfailure();
-};
-
-[scriptable, uuid(08dfefed-5c5d-4468-8c5d-2c65c24692d9)]
-interface nsIWifi : nsISupports
-{
- /**
- * Shutdown the wifi system.
- */
- void shutdown();
-
- /**
- * Returns the list of currently available networks as well as the list of
- * currently configured networks.
- *
- * On success a callback is notified with the list of networks.
- * On failure after 3 scan retry attempts a callback is notified of failure.
- */
- void getWifiScanResults(in nsIWifiScanResultsReady callback);
-};
diff --git a/dom/wifi/nsIWifiCertService.idl b/dom/wifi/nsIWifiCertService.idl
deleted file mode 100644
index fce2dd719..000000000
--- a/dom/wifi/nsIWifiCertService.idl
+++ /dev/null
@@ -1,54 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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"
-
-interface nsIDOMBlob;
-interface nsIWifiEventListener;
-
-[scriptable, uuid(5d0edcd3-c2f1-4946-aae5-06adcbdf0992)]
-interface nsIWifiCertService : nsISupports
-{
- const unsigned short WIFI_CERT_USAGE_FLAG_SERVER = 0x01;
- const unsigned short WIFI_CERT_USAGE_FLAG_USER = 0x02;
-
- void start(in nsIWifiEventListener listener);
- void shutdown();
-
- /**
- * Import a certificate file.
- *
- * @param id
- * Request ID.
- * @param certBlob
- * A Blob object containing raw data of certificate to be imported.
- * @param certPassword
- * Password of certificate.
- * @param certNickname
- * User assigned nickname for imported certificate.
- */
- void importCert(in long id,
- in nsIDOMBlob certBlob,
- in DOMString certPassword,
- in DOMString certNickname);
-
- /**
- * Delete an imported certificate file
- *
- * @param id
- * Request ID.
- * @param certNickname
- * Certificate nickname to delete.
- */
- void deleteCert(in long id,
- in DOMString certNickname);
-
- /**
- * Check if certificate has private key.
- *
- * @param certNickname
- * Certificate nickname to check for private key.
- */
- boolean hasPrivateKey(in DOMString certNickname);
-};
diff --git a/dom/wifi/nsIWifiService.idl b/dom/wifi/nsIWifiService.idl
deleted file mode 100644
index 0f320ddda..000000000
--- a/dom/wifi/nsIWifiService.idl
+++ /dev/null
@@ -1,22 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(4d4389e0-1547-11e3-8ffd-0800200c9a66)]
-interface nsIWifiEventListener : nsISupports {
- void onWaitEvent(in AString event, in ACString aInterface);
- void onCommand(in jsval result, in ACString aInterface);
-};
-
-[scriptable, uuid(5e2bd8c0-1547-11e3-8ffd-0800200c9a66)]
-interface nsIWifiProxyService : nsISupports {
- void start(in nsIWifiEventListener listener,
- [array, size_is(aNumOfInterface)] in string aInterfaces,
- in unsigned long aNumOfInterface);
- void shutdown();
- [implicit_jscontext]
- void sendCommand(in jsval parameters, in ACString aInterface);
- void waitForEvent(in ACString aInterface);
-};
diff --git a/dom/wifi/test/marionette/head.js b/dom/wifi/test/marionette/head.js
deleted file mode 100644
index f4a212b11..000000000
--- a/dom/wifi/test/marionette/head.js
+++ /dev/null
@@ -1,1486 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-// Emulate Promise.jsm semantics.
-Promise.defer = function() { return new Deferred(); }
-function Deferred() {
- this.promise = new Promise(function(resolve, reject) {
- this.resolve = resolve;
- this.reject = reject;
- }.bind(this));
- Object.freeze(this);
-}
-
-const STOCK_HOSTAPD_NAME = 'goldfish-hostapd';
-const HOSTAPD_CONFIG_PATH = '/data/misc/wifi/remote-hostapd/';
-
-const SETTINGS_RIL_DATA_ENABLED = 'ril.data.enabled';
-const SETTINGS_TETHERING_WIFI_ENABLED = 'tethering.wifi.enabled';
-const SETTINGS_TETHERING_WIFI_IP = 'tethering.wifi.ip';
-const SETTINGS_TETHERING_WIFI_SECURITY = 'tethering.wifi.security.type';
-
-const HOSTAPD_COMMON_CONFIG = {
- driver: 'test',
- ctrl_interface: '/data/misc/wifi/remote-hostapd',
- test_socket: 'DIR:/data/misc/wifi/sockets',
- hw_mode: 'b',
- channel: '2',
-};
-
-const HOSTAPD_CONFIG_LIST = [
- { ssid: 'ap0' },
-
- { ssid: 'ap1',
- wpa: 1,
- wpa_pairwise: 'TKIP CCMP',
- wpa_passphrase: '12345678'
- },
-
- { ssid: 'ap2',
- wpa: 2,
- rsn_pairwise: 'CCMP',
- wpa_passphrase: '12345678',
- },
-];
-
-var gTestSuite = (function() {
- let suite = {};
-
- // Private member variables of the returned object |suite|.
- let wifiManager;
- let wifiOrigEnabled;
- let pendingEmulatorShellCount = 0;
- let sdkVersion;
-
- /**
- * A wrapper function of "is".
- *
- * Calls the marionette function "is" as well as throws an exception
- * if the givens values are not equal.
- *
- * @param value1
- * Any type of value to compare.
- *
- * @param value2
- * Any type of value to compare.
- *
- * @param message
- * Debug message for this check.
- *
- */
- function isOrThrow(value1, value2, message) {
- is(value1, value2, message);
- if (value1 !== value2) {
- throw message;
- }
- }
-
- /**
- * Send emulator shell command with safe guard.
- *
- * We should only call |finish()| after all emulator command transactions
- * end, so here comes with the pending counter. Resolve when the emulator
- * gives positive response, and reject otherwise.
- *
- * Fulfill params:
- * result -- an array of emulator response lines.
- * Reject params:
- * result -- an array of emulator response lines.
- *
- * @param aCommand
- * A string command to be passed to emulator through its telnet console.
- *
- * @return A deferred promise.
- */
- function runEmulatorShellSafe(aCommand) {
- let deferred = Promise.defer();
-
- ++pendingEmulatorShellCount;
- runEmulatorShell(aCommand, function(aResult) {
- --pendingEmulatorShellCount;
-
- ok(true, "Emulator shell response: " + JSON.stringify(aResult));
- if (Array.isArray(aResult)) {
- deferred.resolve(aResult);
- } else {
- deferred.reject(aResult);
- }
- });
-
- return deferred.promise;
- }
-
- /**
- * Wait for one named MozWifiManager event.
- *
- * Resolve if that named event occurs. Never reject.
- *
- * Fulfill params: the DOMEvent passed.
- *
- * @param aEventName
- * A string event name.
- *
- * @return A deferred promise.
- */
- function waitForWifiManagerEventOnce(aEventName) {
- let deferred = Promise.defer();
-
- wifiManager.addEventListener(aEventName, function onevent(aEvent) {
- wifiManager.removeEventListener(aEventName, onevent);
-
- ok(true, "WifiManager event '" + aEventName + "' got.");
- deferred.resolve(aEvent);
- });
-
- return deferred.promise;
- }
-
- /**
- * Wait for one named MozMobileConnection event.
- *
- * Resolve if that named event occurs. Never reject.
- *
- * Fulfill params: the DOMEvent passed.
- *
- * @param aEventName
- * A string event name.
- *
- * @return A deferred promise.
- */
- function waitForMobileConnectionEventOnce(aEventName, aServiceId) {
- aServiceId = aServiceId || 0;
-
- let deferred = Promise.defer();
- let mobileconnection = navigator.mozMobileConnections[aServiceId];
-
- mobileconnection.addEventListener(aEventName, function onevent(aEvent) {
- mobileconnection.removeEventListener(aEventName, onevent);
-
- ok(true, "Mobile connection event '" + aEventName + "' got.");
- deferred.resolve(aEvent);
- });
-
- return deferred.promise;
- }
-
- /**
- * Get the detail of currently running processes containing the given name.
- *
- * Use shell command 'ps' to get the desired process's detail. Never reject.
- *
- * Fulfill params:
- * result -- an array of { pname, pid }
- *
- * @param aProcessName
- * The process to get the detail.
- *
- * @return A deferred promise.
- */
- function getProcessDetail(aProcessName) {
- return runEmulatorShellSafe(['ps'])
- .then(processes => {
- // Sample 'ps' output:
- //
- // USER PID PPID VSIZE RSS WCHAN PC NAME
- // root 1 0 284 204 c009e6c4 0000deb4 S /init
- // root 2 0 0 0 c0052c64 00000000 S kthreadd
- // root 3 2 0 0 c0044978 00000000 S ksoftirqd/0
- //
- let detail = [];
-
- processes.shift(); // Skip the first line.
- for (let i = 0; i < processes.length; i++) {
- let tokens = processes[i].split(/\s+/);
- let pname = tokens[tokens.length - 1];
- let pid = tokens[1];
- if (-1 !== pname.indexOf(aProcessName)) {
- detail.push({ pname: pname, pid: pid });
- }
- }
-
- return detail;
- });
- }
-
- /**
- * Add required permissions for wifi testing. Never reject.
- *
- * The permissions required for wifi testing are 'wifi-manage' and 'settings-write'.
- * Never reject.
- *
- * Fulfill params: (none)
- *
- * @return A deferred promise.
- */
- function addRequiredPermissions() {
- let deferred = Promise.defer();
-
- let permissions = [{ 'type': 'wifi-manage', 'allow': 1, 'context': window.document },
- { 'type': 'settings-write', 'allow': 1, 'context': window.document },
- { 'type': 'settings-read', 'allow': 1, 'context': window.document },
- { 'type': 'settings-api-write', 'allow': 1, 'context': window.document },
- { 'type': 'settings-api-read', 'allow': 1, 'context': window.document },
- { 'type': 'mobileconnection', 'allow': 1, 'context': window.document }];
-
- SpecialPowers.pushPermissions(permissions, function() {
- deferred.resolve();
- });
-
- return deferred.promise;
- }
-
- /**
- * Wrap DOMRequest onsuccess/onerror events to Promise resolve/reject.
- *
- * Fulfill params: A DOMEvent.
- * Reject params: A DOMEvent.
- *
- * @param aRequest
- * A DOMRequest instance.
- *
- * @return A deferred promise.
- */
- function wrapDomRequestAsPromise(aRequest) {
- let deferred = Promise.defer();
-
- ok(aRequest instanceof DOMRequest,
- "aRequest is instanceof " + aRequest.constructor);
-
- aRequest.addEventListener("success", function(aEvent) {
- deferred.resolve(aEvent);
- });
- aRequest.addEventListener("error", function(aEvent) {
- deferred.reject(aEvent);
- });
-
- return deferred.promise;
- }
-
- /**
- * Ensure wifi is enabled/disabled.
- *
- * Issue a wifi enable/disable request if wifi is not in the desired state;
- * return a resolved promise otherwise. Note that you cannot rely on this
- * function to test the correctness of enabling/disabling wifi.
- * (use requestWifiEnabled instead)
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return a resolved promise or deferred promise.
- */
- function ensureWifiEnabled(aEnabled, useAPI) {
- if (wifiManager.enabled === aEnabled) {
- log('Already ' + (aEnabled ? 'enabled' : 'disabled'));
- return Promise.resolve();
- }
- return requestWifiEnabled(aEnabled, useAPI);
- }
-
- /**
- * Issue a request to enable/disable wifi.
- *
- * This function will attempt to enable/disable wifi, by calling API or by
- * writing settings 'wifi.enabled' regardless of the wifi state, based on the
- * value of |userAPI| parameter.
- * Default is using settings.
- *
- * Note there's a limitation of co-existance of both method, per bug 930355,
- * that once enable/disable wifi by API, the settings method won't work until
- * reboot. So the test of wifi enable API should be executed last.
- * TODO: Remove settings method after enable/disable wifi by settings is
- * removed after bug 1050147.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function requestWifiEnabled(aEnabled, useAPI) {
- return Promise.all([
- waitForWifiManagerEventOnce(aEnabled ? 'enabled' : 'disabled'),
- useAPI ?
- wrapDomRequestAsPromise(wifiManager.setWifiEnabled(aEnabled)) :
- setSettings({ 'wifi.enabled': aEnabled }),
- ]);
- }
-
- /**
- * Wait for RIL data being connected.
- *
- * This function will check |MozMobileConnection.data.connected| on
- * every 'datachange' event. Resolve when |MozMobileConnection.data.connected|
- * becomes the expected state. Never reject.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aConnected
- * Boolean that indicates the desired data state.
- *
- * @param aServiceId [optional]
- * A numeric DSDS service id. Default: 0.
- *
- * @return A deferred promise.
- */
- function waitForRilDataConnected(aConnected, aServiceId) {
- aServiceId = aServiceId || 0;
- return waitForMobileConnectionEventOnce('datachange', aServiceId)
- .then(function () {
- let mobileconnection = navigator.mozMobileConnections[aServiceId];
- if (mobileconnection.data.connected !== aConnected) {
- return waitForRilDataConnected(aConnected, aServiceId);
- }
- });
- }
-
- /**
- * Request to enable/disable wifi tethering.
- *
- * Enable/disable wifi tethering by changing the settings value 'tethering.wifi.enabled'.
- * Resolve when the routing is verified to set up successfully in 20 seconds. The polling
- * period is 1 second.
- *
- * Fulfill params: (none)
- * Reject params: The error message.
- *
- * @param aEnabled
- * Boolean that indicates to enable or disable wifi tethering.
- *
- * @return A deferred promise.
- */
- function requestTetheringEnabled(aEnabled) {
- let RETRY_INTERVAL_MS = 1000;
- let retryCnt = 20;
-
- return setSettings1(SETTINGS_TETHERING_WIFI_ENABLED, aEnabled)
- .then(function waitForRoutingVerified() {
- return verifyTetheringRouting(aEnabled)
- .then(null, function onreject(aReason) {
-
- log('verifyTetheringRouting rejected due to ' + aReason +
- ' (' + retryCnt + ')');
-
- if (!retryCnt--) {
- throw aReason;
- }
-
- return waitForTimeout(RETRY_INTERVAL_MS).then(waitForRoutingVerified);
- });
- });
- }
-
- /**
- * Forget the given network.
- *
- * Resolve when we successfully forget the given network; reject when any error
- * occurs.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aNetwork
- * An object of MozWifiNetwork.
- *
- * @return A deferred promise.
- */
- function forgetNetwork(aNetwork) {
- let request = wifiManager.forget(aNetwork);
- return wrapDomRequestAsPromise(request)
- .then(event => event.target.result);
- }
-
- /**
- * Forget all known networks.
- *
- * Resolve when we successfully forget all the known network;
- * reject when any error occurs.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function forgetAllKnownNetworks() {
-
- function createForgetNetworkChain(aNetworks) {
- let chain = Promise.resolve();
-
- aNetworks.forEach(function (aNetwork) {
- chain = chain.then(() => forgetNetwork(aNetwork));
- });
-
- return chain;
- }
-
- return getKnownNetworks()
- .then(networks => createForgetNetworkChain(networks));
- }
-
- /**
- * Get all known networks.
- *
- * Resolve when we get all the known networks; reject when any error
- * occurs.
- *
- * Fulfill params: An array of MozWifiNetwork
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function getKnownNetworks() {
- let request = wifiManager.getKnownNetworks();
- return wrapDomRequestAsPromise(request)
- .then(event => event.target.result);
- }
-
- /**
- * Set the given network to static ip mode.
- *
- * Resolve when we set static ip mode successfully; reject when any error
- * occurs.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function setStaticIpMode(aNetwork, aConfig) {
- let request = wifiManager.setStaticIpMode(aNetwork, aConfig);
- return wrapDomRequestAsPromise(request)
- .then(event => event.target.result);
- }
-
- /**
- * Issue a request to scan all wifi available networks.
- *
- * Resolve when we get the scan result; reject when any error
- * occurs.
- *
- * Fulfill params: An array of MozWifiNetwork
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function requestWifiScan() {
- let request = wifiManager.getNetworks();
- return wrapDomRequestAsPromise(request)
- .then(event => event.target.result);
- }
-
- /**
- * Import a certificate with nickname and password.
- *
- * Resolve when we import certificate successfully; reject when any error
- * occurs.
- *
- * Fulfill params: An object of certificate information.
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function importCert(certBlob, password, nickname) {
- let request = wifiManager.importCert(certBlob, password, nickname);
- return wrapDomRequestAsPromise(request)
- .then(event => event.target.result);
- }
-
- /**
- * Delete certificate of nickname.
- *
- * Resolve when we delete certificate successfully; reject when any error
- * occurs.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function deleteCert(nickname) {
- let request = wifiManager.deleteCert(nickname);
- return wrapDomRequestAsPromise(request)
- .then(event => event.target.result);
- }
-
- /**
- * Get list of imported certificates.
- *
- * Resolve when we get certificate list successfully; reject when any error
- * occurs.
- *
- * Fulfill params: Nickname of imported certificate arranged by usage.
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function getImportedCerts() {
- let request = wifiManager.getImportedCerts();
- return wrapDomRequestAsPromise(request)
- .then(event => event.target.result);
- }
-
- /**
- * Request wifi scan and verify the scan result as well.
- *
- * Issue a wifi scan request and check if the result is expected.
- * Since the old APs may be cached and the newly added APs may be
- * still not scan-able, a couple of attempts are acceptable.
- * Resolve if we eventually get the expected scan result; reject otherwise.
- *
- * Fulfill params: The scan result, which is an array of MozWifiNetwork
- * Reject params: (none)
- *
- * @param aRetryCnt
- * The maxmimum number of attempts until we get the expected scan result.
- * @param aExpectedNetworks
- * An array of object, each of which contains at least the |ssid| property.
- *
- * @return A deferred promise.
- */
- function testWifiScanWithRetry(aRetryCnt, aExpectedNetworks) {
-
- // Check if every single ssid of each |aScanResult| exists in |aExpectedNetworks|
- // as well as the length of |aScanResult| equals to |aExpectedNetworks|.
- function isScanResultExpected(aScanResult) {
- if (aScanResult.length !== aExpectedNetworks.length) {
- return false;
- }
-
- for (let i = 0; i < aScanResult.length; i++) {
- if (-1 === getFirstIndexBySsid(aScanResult[i].ssid, aExpectedNetworks)) {
- return false;
- }
- }
- return true;
- }
-
- return requestWifiScan()
- .then(function (networks) {
- if (isScanResultExpected(networks, aExpectedNetworks)) {
- return networks;
- }
- if (aRetryCnt > 0) {
- return testWifiScanWithRetry(aRetryCnt - 1, aExpectedNetworks);
- }
- throw 'Unexpected scan result!';
- });
- }
-
- /**
- * Test wifi association.
- *
- * Associate with the given network object which is obtained by
- * MozWifiManager.getNetworks() (i.e. MozWifiNetwork).
- * Resolve when the 'connected' status change event is received.
- * Note that we might see other events like 'connecting'
- * before 'connected'. So we need to call |waitForWifiManagerEventOnce|
- * again whenever non 'connected' event is seen. Never reject.
- *
- * Fulfill params: (none)
- *
- * @param aNetwork
- * An object of MozWifiNetwork.
- *
- * @return A deferred promise.
- */
- function testAssociate(aNetwork) {
- setPasswordIfNeeded(aNetwork);
-
- let promises = [];
-
- // Register the event listerner to wait for 'connected' event first
- // to avoid racing issue.
- promises.push(waitForConnected(aNetwork));
-
- // Then we do the association.
- let request = wifiManager.associate(aNetwork);
- promises.push(wrapDomRequestAsPromise(request));
-
- return Promise.all(promises);
- }
-
- function waitForConnected(aExpectedNetwork) {
- return waitForWifiManagerEventOnce('statuschange')
- .then(function onstatuschange(event) {
- log("event.status: " + event.status);
- log("event.network.ssid: " + (event.network ? event.network.ssid : ''));
-
- if ("connected" === event.status &&
- event.network.ssid === aExpectedNetwork.ssid) {
- return; // Got expected 'connected' event from aNetwork.ssid.
- }
-
- log('Not expected "connected" statuschange event. Wait again!');
- return waitForConnected(aExpectedNetwork);
- });
- }
-
- /**
- * Set the password for associating the given network if needed.
- *
- * Set the password by looking up HOSTAPD_CONFIG_LIST. This function
- * will also set |keyManagement| properly.
- *
- * @param aNetwork
- * The MozWifiNetwork object.
- */
- function setPasswordIfNeeded(aNetwork) {
- let i = getFirstIndexBySsid(aNetwork.ssid, HOSTAPD_CONFIG_LIST);
- if (-1 === i) {
- log('unknown ssid: ' + aNetwork.ssid);
- return; // Unknown network. Assume insecure.
- }
-
- if (!aNetwork.security.length) {
- return; // No need to set password.
- }
-
- let security = aNetwork.security[0];
- if (/PSK$/.test(security)) {
- aNetwork.psk = HOSTAPD_CONFIG_LIST[i].wpa_passphrase;
- aNetwork.keyManagement = 'WPA-PSK';
- } else if (/WEP$/.test(security)) {
- aNetwork.wep = HOSTAPD_CONFIG_LIST[i].wpa_passphrase;
- aNetwork.keyManagement = 'WEP';
- }
- }
-
- /**
- * Set mozSettings values.
- *
- * Resolve if that mozSettings value is set successfully, reject otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aSettings
- * An object of format |{key1: value1, key2: value2, ...}|.
- * @param aAllowError [optional]
- * A boolean value. If set to true, an error response won't be treated
- * as test failure. Default: false.
- *
- * @return A deferred promise.
- */
- function setSettings(aSettings) {
- let lock = window.navigator.mozSettings.createLock();
- let request = lock.set(aSettings);
- let deferred = Promise.defer();
- lock.onsettingstransactionsuccess = function () {
- ok(true, "setSettings(" + JSON.stringify(aSettings) + ")");
- deferred.resolve();
- };
- lock.onsettingstransactionfailure = function (aEvent) {
- ok(false, "setSettings(" + JSON.stringify(aSettings) + ")");
- deferred.reject();
- throw aEvent.target.error;
- };
- return deferred.promise;
- }
-
- /**
- * Set mozSettings value with only one key.
- *
- * Resolve if that mozSettings value is set successfully, reject otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aKey
- * A string key.
- * @param aValue
- * An object value.
- * @param aAllowError [optional]
- * A boolean value. If set to true, an error response won't be treated
- * as test failure. Default: false.
- *
- * @return A deferred promise.
- */
- function setSettings1(aKey, aValue, aAllowError) {
- let settings = {};
- settings[aKey] = aValue;
- return setSettings(settings, aAllowError);
- }
-
- /**
- * Get mozSettings value specified by @aKey.
- *
- * Resolve if that mozSettings value is retrieved successfully, reject
- * otherwise.
- *
- * Fulfill params:
- * The corresponding mozSettings value of the key.
- * Reject params: (none)
- *
- * @param aKey
- * A string.
- * @param aAllowError [optional]
- * A boolean value. If set to true, an error response won't be treated
- * as test failure. Default: false.
- *
- * @return A deferred promise.
- */
- function getSettings(aKey, aAllowError) {
- let request =
- navigator.mozSettings.createLock().get(aKey);
- return wrapDomRequestAsPromise(request)
- .then(function resolve(aEvent) {
- ok(true, "getSettings(" + aKey + ") - success");
- return aEvent.target.result[aKey];
- }, function reject(aEvent) {
- ok(aAllowError, "getSettings(" + aKey + ") - error");
- });
- }
-
-
- /**
- * Start hostapd processes with given configuration list.
- *
- * For starting one hostapd, we need to generate a specific config file
- * then launch a hostapd process with the confg file path passed. The
- * config file is generated by two sources: one is the common
- * part (HOSTAPD_COMMON_CONFIG) and the other is from the given |aConfigList|.
- * Resolve when all the hostpads are requested to start. It is not guaranteed
- * that all the hostapds will be up and running successfully. Never reject.
- *
- * Fulfill params: (none)
- *
- * @param aConfigList
- * An array of config objects, each property in which will be
- * output to the confg file with the format: [key]=[value] in one line.
- * See http://hostap.epitest.fi/cgit/hostap/plain/hostapd/hostapd.conf
- * for more information.
- *
- * @return A deferred promise.
- */
- function startHostapds(aConfigList) {
-
- function createConfigFromCommon(aIndex) {
- // Create an copy of HOSTAPD_COMMON_CONFIG.
- let config = JSON.parse(JSON.stringify(HOSTAPD_COMMON_CONFIG));
-
- // Add user config.
- for (let key in aConfigList[aIndex]) {
- config[key] = aConfigList[aIndex][key];
- }
-
- // 'interface' is a required field but no need of being configurable
- // for a test case. So we initialize this field on our own.
- config.interface = 'AP-' + aIndex;
-
- return config;
- }
-
- function startOneHostapd(aIndex) {
- let configFileName = HOSTAPD_CONFIG_PATH + 'ap' + aIndex + '.conf';
- return writeHostapdConfFile(configFileName, createConfigFromCommon(aIndex))
- .then(() => runEmulatorShellSafe(['hostapd', '-B', configFileName]))
- .then(function (reply) {
- // It may fail at the first time due to the previous ungracefully terminated one.
- if (reply.length === 0) {
- // The hostapd starts successfully
- return;
- }
-
- if (reply[0].indexOf('bind(PF_UNIX): Address already in use') !== -1) {
- return startOneHostapd(aIndex);
- }
- });
- }
-
- return Promise.all(aConfigList.map(function(aConfig, aIndex) {
- return startOneHostapd(aIndex);
- }));
- }
-
- /**
- * Kill all the running hostapd processes.
- *
- * Use shell command 'kill -9' to kill all hostapds. Never reject.
- *
- * Fulfill params: (none)
- *
- * @return A deferred promise.
- */
- function killAllHostapd() {
- return getProcessDetail('hostapd')
- .then(function (runningHostapds) {
- let promises = runningHostapds.map(runningHostapd => {
- return runEmulatorShellSafe(['kill', '-9', runningHostapd.pid]);
- });
- return Promise.all(promises);
- });
- }
-
- /**
- * Write out the config file to the given path.
- *
- * For each key/value pair in |aConfig|,
- *
- * [key]=[value]
- *
- * will be output to one new line. Never reject.
- *
- * Fulfill params: (none)
- *
- * @param aFilePath
- * The file path that we desire the config file to be located.
- *
- * @param aConfig
- * The config object.
- *
- * @return A deferred promise.
- */
- function writeHostapdConfFile(aFilePath, aConfig) {
- let content = '';
- for (let key in aConfig) {
- if (aConfig.hasOwnProperty(key)) {
- content += (key + '=' + aConfig[key] + '\n');
- }
- }
- return writeFile(aFilePath, content);
- }
-
- /**
- * Write file to the given path filled with given content.
- *
- * For now it is implemented by shell command 'echo'. Also, if the
- * content contains whitespace, we need to quote the content to
- * avoid error. Never reject.
- *
- * Fulfill params: (none)
- *
- * @param aFilePath
- * The file path that we desire the file to be located.
- *
- * @param aContent
- * The content as string which should be written to the file.
- *
- * @return A deferred promise.
- */
- function writeFile(aFilePath, aContent) {
- const CONTENT_MAX_LENGTH = 900;
- var commands = [];
- for (var i = 0; i < aContent.length; i += CONTENT_MAX_LENGTH) {
- var content = aContent.substr(i, CONTENT_MAX_LENGTH);
- if (-1 === content.indexOf(' ')) {
- content = '"' + content + '"';
- }
- commands.push(['echo', '-n', content, i === 0 ? '>' : '>>', aFilePath]);
- }
-
- let chain = Promise.resolve();
- commands.forEach(function (command) {
- chain = chain.then(() => runEmulatorShellSafe(command));
- });
- return chain;
- }
-
- /**
- * Check if a init service is running or not.
- *
- * Check the android property 'init.svc.[aServiceName]' to determine if
- * a init service is running. Reject if the propery is neither 'running'
- * nor 'stopped'.
- *
- * Fulfill params:
- * result -- |true| if the init service is running; |false| otherwise.
- * Reject params: (none)
- *
- * @param aServiceName
- * The init service name.
- *
- * @return A deferred promise.
- */
- function isInitServiceRunning(aServiceName) {
- return runEmulatorShellSafe(['getprop', 'init.svc.' + aServiceName])
- .then(function (result) {
- if ('running' !== result[0] && 'stopped' !== result[0]) {
- throw 'Init service running state should be "running" or "stopped".';
- }
- return 'running' === result[0];
- });
- }
-
- /**
- * Wait for timeout.
- *
- * Resolve when the given duration elapsed. Never reject.
- *
- * Fulfill params: (none)
- *
- * @param aTimeoutMs
- * The duration after which the timeout event should occurs.
- *
- * @return A deferred promise.
- */
- function waitForTimeout(aTimeoutMs) {
- let deferred = Promise.defer();
-
- setTimeout(function() {
- deferred.resolve();
- }, aTimeoutMs);
-
- return deferred.promise;
- }
-
- /**
- * Start or stop an init service.
- *
- * Use shell command 'start'/'stop' to start/stop an init service.
- * The running state will also be checked after we start/stop the service.
- * Resolve if the service is successfully started/stopped; Reject otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aServiceName
- * The name of the service we want to start/stop.
- *
- * @param aStart
- * |true| for starting the init service. |false| for stopping.
- *
- * @return A deferred promise.
- */
- function startStopInitService(aServiceName, aStart) {
- let retryCnt = 5;
-
- return runEmulatorShellSafe([aStart ? 'start' : 'stop', aServiceName])
- .then(() => isInitServiceRunning(aServiceName))
- .then(function onIsServiceRunningResolved(aIsRunning) {
- if (aStart === aIsRunning) {
- return;
- }
-
- if (retryCnt-- > 0) {
- log('Failed to ' + (aStart ? 'start ' : 'stop ') + aServiceName +
- '. Retry: ' + retryCnt);
-
- return waitForTimeout(500)
- .then(() => isInitServiceRunning(aServiceName))
- .then(onIsServiceRunningResolved);
- }
-
- throw 'Failed to ' + (aStart ? 'start' : 'stop') + ' ' + aServiceName;
- });
- }
-
- /**
- * Start the stock hostapd.
- *
- * Since the stock hostapd is an init service, use |startStopInitService| to
- * start it. Note that we might fail to start the stock hostapd at the first time
- * for unknown reason so give it the second chance to start again.
- * Resolve when we are eventually successful to start the stock hostapd; Reject
- * otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function startStockHostapd() {
- return startStopInitService(STOCK_HOSTAPD_NAME, true)
- .then(null, function onreject() {
- log('Failed to restart goldfish-hostapd at the first time. Try again!');
- return startStopInitService((STOCK_HOSTAPD_NAME), true);
- });
- }
-
- /**
- * Stop the stock hostapd.
- *
- * Since the stock hostapd is an init service, use |startStopInitService| to
- * stop it.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function stopStockHostapd() {
- return startStopInitService(STOCK_HOSTAPD_NAME, false);
- }
-
- /**
- * Get the index of the first matching entry by |ssid|.
- *
- * Find the index of the first entry of |aArray| which property |ssid|
- * is same as |aSsid|.
- *
- * @param aSsid
- * The ssid that we want to match.
- * @param aArray
- * An array of objects, each of which should have the property |ssid|.
- *
- * @return The 0-based index of first matching entry if found; -1 otherwise.
- */
- function getFirstIndexBySsid(aSsid, aArray) {
- for (let i = 0; i < aArray.length; i++) {
- if (aArray[i].ssid === aSsid) {
- return i;
- }
- }
- return -1;
- }
-
- /**
- * Count the number of running process and verify if the count is expected.
- *
- * Return a promise that resolves when the process has expected number
- * of running instances and rejects otherwise.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aOrigWifiEnabled
- * Boolean which indicates wifi was originally enabled.
- *
- * @return A deferred promise.
- */
- function verifyNumOfProcesses(aProcessName, aExpectedNum) {
- return getProcessDetail(aProcessName)
- .then(function (detail) {
- if (detail.length === aExpectedNum) {
- return;
- }
- throw 'Unexpected number of running processes:' + aProcessName +
- ', expected: ' + aExpectedNum + ', actual: ' + detail.length;
- });
- }
-
- /**
- * Execute 'netcfg' shell and parse the result.
- *
- * Resolve when the executing is successful and reject otherwise.
- *
- * Fulfill params: Command result object, each key of which is the interface
- * name and value is { ip(string), prefix(string) }.
- * Reject params: String that indicates the reason of rejection.
- *
- * @return A deferred promise.
- */
- function exeAndParseNetcfg() {
- return runEmulatorShellSafe(['netcfg'])
- .then(function (aLines) {
- // Sample output:
- //
- // lo UP 127.0.0.1/8 0x00000049 00:00:00:00:00:00
- // eth0 UP 10.0.2.15/24 0x00001043 52:54:00:12:34:56
- // rmnet1 DOWN 0.0.0.0/0 0x00001002 52:54:00:12:34:58
- // rmnet2 DOWN 0.0.0.0/0 0x00001002 52:54:00:12:34:59
- // rmnet3 DOWN 0.0.0.0/0 0x00001002 52:54:00:12:34:5a
- // wlan0 UP 192.168.1.1/24 0x00001043 52:54:00:12:34:5b
- // sit0 DOWN 0.0.0.0/0 0x00000080 00:00:00:00:00:00
- // rmnet0 UP 10.0.2.100/24 0x00001043 52:54:00:12:34:57
- //
- let netcfgResult = {};
- aLines.forEach(function (aLine) {
- let tokens = aLine.split(/\s+/);
- if (tokens.length < 5) {
- return;
- }
- let ifname = tokens[0];
- let [ip, prefix] = tokens[2].split('/');
- netcfgResult[ifname] = { ip: ip, prefix: prefix };
- });
- log("netcfg result:" + JSON.stringify(netcfgResult));
-
- return netcfgResult;
- });
- }
-
- /**
- * Execute 'ip route' and parse the result.
- *
- * Resolve when the executing is successful and reject otherwise.
- *
- * Fulfill params: Command result object, each key of which is the interface
- * name and value is { src(string), gateway(string),
- * default(boolean) }.
- * Reject params: String that indicates the reason of rejection.
- *
- * @return A deferred promise.
- */
- function exeAndParseIpRoute() {
- return runEmulatorShellSafe(['ip', 'route'])
- .then(function (aLines) {
- // Sample output:
- //
- // 10.0.2.4 via 10.0.2.2 dev rmnet0
- // 10.0.2.3 via 10.0.2.2 dev rmnet0
- // 192.168.1.0/24 dev wlan0 proto kernel scope link src 192.168.1.1
- // 10.0.2.0/24 dev eth0 proto kernel scope link src 10.0.2.15
- // 10.0.2.0/24 dev rmnet0 proto kernel scope link src 10.0.2.100
- // default via 10.0.2.2 dev rmnet0
- // default via 10.0.2.2 dev eth0 metric 2
- //
-
- let ipRouteResult = {};
-
- // Parse source ip for each interface.
- aLines.forEach(function (aLine) {
- let tokens = aLine.trim().split(/\s+/);
- let srcIndex = tokens.indexOf('src');
- if (srcIndex < 0 || srcIndex + 1 >= tokens.length) {
- return;
- }
- let ifname = tokens[2];
- let src = tokens[srcIndex + 1];
- ipRouteResult[ifname] = { src: src, default: false, gateway: null };
- });
-
- // Parse default interfaces.
- aLines.forEach(function (aLine) {
- let tokens = aLine.split(/\s+/);
- if (tokens.length < 2) {
- return;
- }
- if ('default' === tokens[0]) {
- let ifnameIndex = tokens.indexOf('dev');
- if (ifnameIndex < 0 || ifnameIndex + 1 >= tokens.length) {
- return;
- }
- let ifname = tokens[ifnameIndex + 1];
- if (!ipRouteResult[ifname]) {
- return;
- }
- ipRouteResult[ifname].default = true;
- let gwIndex = tokens.indexOf('via');
- if (gwIndex < 0 || gwIndex + 1 >= tokens.length) {
- return;
- }
- ipRouteResult[ifname].gateway = tokens[gwIndex + 1];
- return;
- }
- });
- log("ip route result:" + JSON.stringify(ipRouteResult));
-
- return ipRouteResult;
- });
- }
-
- /**
- * Verify everything about routing when the wifi tethering is either on or off.
- *
- * We use two unix commands to verify the routing: 'netcfg' and 'ip route'.
- * For now the following two things will be checked:
- * 1) The default route interface should be 'rmnet0'.
- * 2) wlan0 is up and its ip is set to a private subnet.
- *
- * We also verify iptables output as netd's NatController will execute
- * $ iptables -t nat -A POSTROUTING -o rmnet0 -j MASQUERADE
- *
- * Resolve when the verification is successful and reject otherwise.
- *
- * Fulfill params: (none)
- * Reject params: String that indicates the reason of rejection.
- *
- * @return A deferred promise.
- */
- function verifyTetheringRouting(aEnabled) {
- let netcfgResult;
- let ipRouteResult;
-
- // Find MASQUERADE in POSTROUTING section. 'MASQUERADE' should be found
- // when tethering is enabled. 'MASQUERADE' shouldn't be found when tethering
- // is disabled.
- function verifyIptables() {
- let MASQUERADE_checkSection = 'POSTROUTING';
- if (sdkVersion > 15) {
- // Check 'natctrl_nat_POSTROUTING' section after ICS.
- MASQUERADE_checkSection = 'natctrl_nat_POSTROUTING';
- }
-
- return runEmulatorShellSafe(['iptables', '-t', 'nat', '-L', MASQUERADE_checkSection])
- .then(function(aLines) {
- // $ iptables -t nat -L POSTROUTING
- //
- // Sample output (tethering on):
- //
- // Chain POSTROUTING (policy ACCEPT)
- // target prot opt source destination
- // MASQUERADE all -- anywhere anywhere
- //
- let found = (function find_MASQUERADE() {
- // Skip first two lines.
- for (let i = 2; i < aLines.length; i++) {
- if (-1 !== aLines[i].indexOf('MASQUERADE')) {
- return true;
- }
- }
- return false;
- })();
-
- if ((aEnabled && !found) || (!aEnabled && found)) {
- throw 'MASQUERADE' + (found ? '' : ' not') + ' found while tethering is ' +
- (aEnabled ? 'enabled' : 'disabled');
- }
- });
- }
-
- function verifyDefaultRouteAndIp(aExpectedWifiTetheringIp) {
- if (aEnabled) {
- isOrThrow(ipRouteResult['rmnet0'].src, netcfgResult['rmnet0'].ip, 'rmnet0.ip');
- isOrThrow(ipRouteResult['rmnet0'].default, true, 'rmnet0.default');
-
- isOrThrow(ipRouteResult['wlan0'].src, netcfgResult['wlan0'].ip, 'wlan0.ip');
- isOrThrow(ipRouteResult['wlan0'].src, aExpectedWifiTetheringIp, 'expected ip');
- isOrThrow(ipRouteResult['wlan0'].default, false, 'wlan0.default');
- }
- }
-
- return verifyIptables()
- .then(exeAndParseNetcfg)
- .then((aResult) => { netcfgResult = aResult; })
- .then(exeAndParseIpRoute)
- .then((aResult) => { ipRouteResult = aResult; })
- .then(() => getSettings(SETTINGS_TETHERING_WIFI_IP))
- .then(ip => verifyDefaultRouteAndIp(ip));
- }
-
- /**
- * Clean up all the allocated resources and running services for the test.
- *
- * After the test no matter success or failure, we should
- * 1) Restore to the wifi original state (enabled or disabled)
- * 2) Wait until all pending emulator shell commands are done.
- *
- * |finsih| will be called in the end.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @return A deferred promise.
- */
- function cleanUp() {
- waitFor(function() {
- return ensureWifiEnabled(true)
- .then(forgetAllKnownNetworks)
- .then(() => ensureWifiEnabled(wifiOrigEnabled))
- .then(finish);
- }, function() {
- return pendingEmulatorShellCount === 0;
- });
- }
-
- /**
- * Init the test environment.
- *
- * Mainly add the required permissions and initialize the wifiManager
- * and the orignal state of wifi. Reject if failing to create
- * window.navigator.mozWifiManager; resolve if all is well.
- *
- * |finsih| will be called in the end.
- *
- * Fulfill params: (none)
- * Reject params: The reject reason.
- *
- * @return A deferred promise.
- */
- function initTestEnvironment() {
- return addRequiredPermissions()
- .then(function() {
- wifiManager = window.navigator.mozWifiManager;
- if (!wifiManager) {
- throw 'window.navigator.mozWifiManager is NULL';
- }
- wifiOrigEnabled = wifiManager.enabled;
- })
- .then(() => runEmulatorShellSafe(['getprop', 'ro.build.version.sdk']))
- .then(aLines => {
- sdkVersion = parseInt(aLines[0]);
- });
- }
-
- //---------------------------------------------------
- // Public test suite functions
- //---------------------------------------------------
- suite.getWifiManager = (() => wifiManager);
- suite.ensureWifiEnabled = ensureWifiEnabled;
- suite.requestWifiEnabled = requestWifiEnabled;
- suite.startHostapds = startHostapds;
- suite.getProcessDetail = getProcessDetail;
- suite.killAllHostapd = killAllHostapd;
- suite.wrapDomRequestAsPromise = wrapDomRequestAsPromise;
- suite.waitForWifiManagerEventOnce = waitForWifiManagerEventOnce;
- suite.verifyNumOfProcesses = verifyNumOfProcesses;
- suite.testWifiScanWithRetry = testWifiScanWithRetry;
- suite.getFirstIndexBySsid = getFirstIndexBySsid;
- suite.testAssociate = testAssociate;
- suite.getKnownNetworks = getKnownNetworks;
- suite.setStaticIpMode = setStaticIpMode;
- suite.requestWifiScan = requestWifiScan;
- suite.waitForConnected = waitForConnected;
- suite.forgetNetwork = forgetNetwork;
- suite.waitForTimeout = waitForTimeout;
- suite.waitForRilDataConnected = waitForRilDataConnected;
- suite.requestTetheringEnabled = requestTetheringEnabled;
- suite.importCert = importCert;
- suite.getImportedCerts = getImportedCerts;
- suite.deleteCert = deleteCert;
- suite.writeFile = writeFile;
- suite.exeAndParseNetcfg = exeAndParseNetcfg;
- suite.exeAndParseIpRoute = exeAndParseIpRoute;
-
- /**
- * Common test routine.
- *
- * Start a test with the given test case chain. The test environment will be
- * settled down before the test. After the test, all the affected things will
- * be restored.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aTestCaseChain
- * The test case entry point, which can be a function or a promise.
- *
- * @return A deferred promise.
- */
- suite.doTest = function(aTestCaseChain) {
- return initTestEnvironment()
- .then(aTestCaseChain)
- .then(function onresolve() {
- cleanUp();
- }, function onreject(aReason) {
- ok(false, 'Promise rejects during test' + (aReason ? '(' + aReason + ')' : ''));
- cleanUp();
- });
- };
-
- /**
- * Common test routine without the presence of stock hostapd.
- *
- * Same as doTest except stopping the stock hostapd before test
- * and restarting it after test.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aTestCaseChain
- * The test case entry point, which can be a function or a promise.
- *
- * @return A deferred promise.
- */
- suite.doTestWithoutStockAp = function(aTestCaseChain) {
- return suite.doTest(function() {
- return stopStockHostapd()
- .then(aTestCaseChain)
- .then(startStockHostapd);
- });
- };
-
- /**
- * The common test routine for wifi tethering.
- *
- * Similar as doTest except that it will set 'ril.data.enabled' to true
- * before testing and restore it afterward. It will also verify 'ril.data.enabled'
- * and 'tethering.wifi.enabled' to be false in the beginning. Note that this routine
- * will NOT change the state of 'tethering.wifi.enabled' so the user should enable
- * than disable on his/her own. This routine will only check if tethering is turned
- * off after testing.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aTestCaseChain
- * The test case entry point, which can be a function or a promise.
- *
- * @return A deferred promise.
- */
- suite.doTestTethering = function(aTestCaseChain) {
-
- function verifyInitialState() {
- return getSettings(SETTINGS_RIL_DATA_ENABLED)
- .then(enabled => isOrThrow(enabled, false, SETTINGS_RIL_DATA_ENABLED))
- .then(() => getSettings(SETTINGS_TETHERING_WIFI_ENABLED))
- .then(enabled => isOrThrow(enabled, false, SETTINGS_TETHERING_WIFI_ENABLED));
- }
-
- function initTetheringTestEnvironment() {
- // Enable ril data.
- return Promise.all([waitForRilDataConnected(true),
- setSettings1(SETTINGS_RIL_DATA_ENABLED, true)])
- .then(setSettings1(SETTINGS_TETHERING_WIFI_SECURITY, 'open'));
- }
-
- function restoreToInitialState() {
- return setSettings1(SETTINGS_RIL_DATA_ENABLED, false)
- .then(() => getSettings(SETTINGS_TETHERING_WIFI_ENABLED))
- .then(enabled => is(enabled, false, 'Tethering should be turned off.'));
- }
-
- return suite.doTest(function() {
- return verifyInitialState()
- .then(initTetheringTestEnvironment)
- // Since stock hostapd is not reliable after ICS, we just
- // turn off potential stock hostapd during testing to avoid
- // interference.
- .then(stopStockHostapd)
- .then(aTestCaseChain)
- .then(startStockHostapd)
- .then(restoreToInitialState, function onreject(aReason) {
- return restoreToInitialState()
- .then(() => { throw aReason; }); // Re-throw the orignal reject reason.
- });
- });
- };
-
- /**
- * Run test with imported certificate.
- *
- * Certificate will be imported and confirmed before running test, and be
- * deleted after running test.
- *
- * Fulfill params: (none)
- *
- * @param certBlob
- * Certificate content as Blob.
- * @param password
- * Password for importing certificate, only used for importing PKCS#12.
- * @param nickanem
- * Nickname for imported certificate.
- * @param usage
- * Expected usage of imported certificate.
- * @param aTestCaseChain
- * The test case entry point, which can be a function or a promise.
- *
- * @return A deferred promise.
- */
- suite.doTestWithCertificate = function(certBlob, password, nickname, usage, aTestCaseChain) {
- return suite.doTestWithoutStockAp(function() {
- return ensureWifiEnabled(true)
- // Import test certificate.
- .then(() => importCert(certBlob, password, nickname))
- .then(function(info) {
- // Check import result.
- is(info.nickname, nickname, "Imported nickname");
- for (let i = 0; i < usage.length; i++) {
- isnot(info.usage.indexOf(usage[i]), -1, "Usage " + usage[i]);
- }
- })
- // Get imported certificate list.
- .then(getImportedCerts)
- // Check if certificate exists in imported certificate list.
- .then(function(list) {
- for (let i = 0; i < usage.length; i++) {
- isnot(list[usage[i]].indexOf(nickname), -1,
- "Certificate \"" + nickname + "\" of usage " + usage[i] + " is imported");
- }
- })
- // Run test case.
- .then(aTestCaseChain)
- // Delete imported certificates.
- .then(() => deleteCert(nickname))
- // Check if certificate doesn't exist in imported certificate list.
- .then(getImportedCerts)
- .then(function(list) {
- for (let i = 0; i < usage.length; i++) {
- is(list[usage[i]].indexOf(nickname), -1, "Certificate is deleted");
- }
- })
- });
- };
-
- return suite;
-})();
diff --git a/dom/wifi/test/marionette/manifest.ini b/dom/wifi/test/marionette/manifest.ini
deleted file mode 100644
index 5d719e4b6..000000000
--- a/dom/wifi/test/marionette/manifest.ini
+++ /dev/null
@@ -1,22 +0,0 @@
-[DEFAULT]
-run-if = buildapp == 'b2g'
-
-[test_wifi_enable.js]
-[test_wifi_scan.js]
-[test_wifi_associate.js]
-[test_wifi_associate_wo_connect.js]
-[test_wifi_auto_connect.js]
-[test_wifi_static_ip.js]
-[test_wifi_tethering_wifi_disabled.js]
-[test_wifi_tethering_wifi_inactive.js]
-[test_wifi_tethering_wifi_active.js]
-[test_wifi_manage_server_certificate.js]
-[test_wifi_manage_user_certificate.js]
-[test_wifi_manage_pkcs12_certificate.js]
-[test_wifi_associate_WPA_EAP_PEAP.js]
-skip-if = android_version < '16' # EAP test not working before KK.
-[test_wifi_associate_WPA_EAP_TTLS.js]
-skip-if = android_version < '16'
-[test_wifi_associate_WPA_EAP_TLS.js]
-skip-if = android_version < '16'
-[test_wifi_enable_api.js]
diff --git a/dom/wifi/test/marionette/test_wifi_associate.js b/dom/wifi/test/marionette/test_wifi_associate.js
deleted file mode 100644
index 0c00c583b..000000000
--- a/dom/wifi/test/marionette/test_wifi_associate.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SCAN_RETRY_CNT = 5;
-
-/**
- * Convert the given MozWifiNetwork object array to testAssociate chain.
- *
- * @param aNetworks
- * An array of MozWifiNetwork which we want to convert.
- *
- * @return A promise chain which "then"s testAssociate accordingly.
- */
-function convertToTestAssociateChain(aNetworks) {
- let chain = Promise.resolve();
-
- aNetworks.forEach(function (aNetwork) {
- chain = chain.then(() => gTestSuite.testAssociate(aNetwork));
- });
-
- return chain;
-}
-
-gTestSuite.doTestWithoutStockAp(function() {
- return gTestSuite.ensureWifiEnabled(true)
- .then(() => gTestSuite.startHostapds(HOSTAPD_CONFIG_LIST))
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', HOSTAPD_CONFIG_LIST.length))
- .then(() => gTestSuite.testWifiScanWithRetry(SCAN_RETRY_CNT, HOSTAPD_CONFIG_LIST))
- .then(networks => convertToTestAssociateChain(networks))
- .then(gTestSuite.killAllHostapd)
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', 0));
-});
diff --git a/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_PEAP.js b/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_PEAP.js
deleted file mode 100644
index ce53da2d7..000000000
--- a/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_PEAP.js
+++ /dev/null
@@ -1,623 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SCAN_RETRY_CNT = 5;
-
-const EAP_USERNAME = 'username';
-const EAP_PASSWORD = 'password';
-
-const SERVER_EAP_USER_CONF = {
- path: HOSTAPD_CONFIG_PATH + 'hostapd.eap_user',
- content: '* PEAP,TTLS,TLS\n' +
- '"' + EAP_USERNAME + '" MSCHAPV2,TTLS-MSCHAPV2 "' + EAP_PASSWORD + '" [2]\n'
-};
-const CA_CERT = {
- path: HOSTAPD_CONFIG_PATH + 'ca.pem',
- content: '-----BEGIN CERTIFICATE-----\n' +
- 'MIIDsTCCApmgAwIBAgIJAKxTf+8X8qngMA0GCSqGSIb3DQEBCwUAMG4xCzAJBgNV\n' +
- 'BAYTAlRXMRMwEQYDVQQIDApTb21lLVN0YXRlMREwDwYDVQQKDAhjaHVja2xlZTER\n' +
- 'MA8GA1UEAwwIY2h1Y2tsZWUxJDAiBgkqhkiG9w0BCQEWFWNodWNrbGkwNzA2QGdt\n' +
- 'YWlsLmNvbTAgFw0xNDEyMjQxMTI4NTBaGA8yMjg4MTAwNzExMjg1MFowbjELMAkG\n' +
- 'A1UEBhMCVFcxEzARBgNVBAgMClNvbWUtU3RhdGUxETAPBgNVBAoMCGNodWNrbGVl\n' +
- 'MREwDwYDVQQDDAhjaHVja2xlZTEkMCIGCSqGSIb3DQEJARYVY2h1Y2tsaTA3MDZA\n' +
- 'Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo3c2yFxY\n' +
- 'o6gGg0I83jy00ME+MAfzCd+4ShL45ZLqysQP93jRBfPzU9ZuZ29ysVwgWIdqkZao\n' +
- 'XTuV/NAW2GMGd8W1jQJ3J81fjb9wvhlny3rrACwvUn1N1S1BnM+BAAiDLGxEmvAQ\n' +
- 'onp2aaa6HsHsYS8ONX+d2Qh4LEA4vupeSGAqJychCZv/l+aq/ErFZhFYB3CPUQEt\n' +
- 'cClO24ucsIYP95lA0zhscnmAj06qplFD4Bv6IVrdDqujy1zNwCQwsJq/8OQdaTN/\n' +
- 'h3y9pWvNKMBMM2niOUAjtuNpqsSK/lTS1WAT3PdtVECX9fYBi0Bg+HM92xs/6gt6\n' +
- 'kh9jPV8keXHvSwIDAQABo1AwTjAdBgNVHQ4EFgQU7hBqhuG04xeCzrQ3ngx18ZJ3\n' +
- 'lUswHwYDVR0jBBgwFoAU7hBqhuG04xeCzrQ3ngx18ZJ3lUswDAYDVR0TBAUwAwEB\n' +
- '/zANBgkqhkiG9w0BAQsFAAOCAQEAFYX2iy680GAnBTttk0gyX6gk+8pYr3D22k/G\n' +
- '6rvcjefzS7ELQPRKr6mfmwXq3mMf/4jiS2zI5zmXsestPYzHYxf2viQ6t7vr9XiJ\n' +
- '3WfFjNw4ERlRisAvg0aqqTNNQq5v2VME4sdFZagy217f73C7azwCHl0bqOLH05rl\n' +
- '8RubOxiHEj7ZybJqnRciK/bht4D+rZkwf4bBBmoloqH7xT0+rFQclpYXDGGjNUQB\n' +
- 'LcHLF10xcr7g3ZVVu82fe6+d85gIGOIMR9+TKhdw6gO3CNcnDAj6gxksghgtcxmh\n' +
- 'OzOggCn7nlIwImtsg2sZkpWB4lEi9hdv4lkNuyFjOL3bnuc+NA==\n' +
- '-----END CERTIFICATE-----\n'
-};
-
-const SERVER_CERT = {
- path: HOSTAPD_CONFIG_PATH + 'server.pem',
- content: '-----BEGIN CERTIFICATE-----\n' +
- 'MIID1DCCArygAwIBAgIBADANBgkqhkiG9w0BAQsFADBuMQswCQYDVQQGEwJUVzET\n' +
- 'MBEGA1UECAwKU29tZS1TdGF0ZTERMA8GA1UECgwIY2h1Y2tsZWUxETAPBgNVBAMM\n' +
- 'CGNodWNrbGVlMSQwIgYJKoZIhvcNAQkBFhVjaHVja2xpMDcwNkBnbWFpbC5jb20w\n' +
- 'IBcNMTQxMjI0MTEyOTQ5WhgPMjI4ODEwMDcxMTI5NDlaMG4xCzAJBgNVBAYTAlRX\n' +
- 'MRMwEQYDVQQIDApTb21lLVN0YXRlMREwDwYDVQQKDAhjaHVja2xlZTERMA8GA1UE\n' +
- 'AwwIY2h1Y2tsZWUxJDAiBgkqhkiG9w0BCQEWFWNodWNrbGkwNzA2QGdtYWlsLmNv\n' +
- 'bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMdhQmKilTJbWZRxTiSV\n' +
- 'rqIU+LYW1RKghx5o+0JpNRJVLuz5kBMaNskbbfUSNuHbEq0QA9BDKAZWIc4LSotk\n' +
- 'lCo8TbcO9CJvJPQGGjGdHcohWX5vy6BE/OVE46CUteMFyZF6F8R2fNUww08iR/u1\n' +
- 'YZebL5pWO1j43sPpAzEy6Tij2ACPt6EZcFaZG3SF2mVJWkCQnBqrojP65WUvZQqp\n' +
- 'seUhW2YAS8Nu0Yrohgxz6VYk+cNDuDZVGs6qWRStZzJfYrfc76DtkHof5B14M+xp\n' +
- 'XJaBLxN+whvnYkDTfinaCxnW1O7eXUltr87fLc5zmeBkgwaiaQuIdcfZm7vDUiz8\n' +
- 'vnUCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBH\n' +
- 'ZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFKK4f9/YavTHOfEiAB83Deac\n' +
- '6gT5MB8GA1UdIwQYMBaAFO4QaobhtOMXgs60N54MdfGSd5VLMA0GCSqGSIb3DQEB\n' +
- 'CwUAA4IBAQBWnO9o9KSJIqjoz5Nwll63ULOdcvgGdOeJIw1fcKQ817Rsp+TVcjcH\n' +
- 'IrIADsT/QZGXRO/l6p1750e2iFtJEo1hsRaxtA1wWn2I9HO3+av2spQhr3jpYGPf\n' +
- 'zpsMTp4RNYV7Q8+q1kZIz9PY4V1T0p6lveK8+fUj2hSLnxSj0QiGSJJtnEC3w4Rv\n' +
- 'C9T6oUwIeToULmi+8FXQFdEqwKRU98DPq3eLzN28ZxUgoPE1C8+42D2UW8uyp/Gm\n' +
- 'tGOa/k7nzkCdVqZI7lX7f0AjEvQgjtAMQ/k7Mhxx7TzW2HO+1YPMoKji6Z4WkNwt\n' +
- 'JEj9ZUBSNt8B26UksJMBDkcvSegF3a7o\n' +
- '-----END CERTIFICATE-----\n'
-};
-
-const SERVER_KEY = {
- path: HOSTAPD_CONFIG_PATH + 'server.key',
- content: '-----BEGIN RSA PRIVATE KEY-----\n' +
- 'MIIEpAIBAAKCAQEAx2FCYqKVMltZlHFOJJWuohT4thbVEqCHHmj7Qmk1ElUu7PmQ\n' +
- 'Exo2yRtt9RI24dsSrRAD0EMoBlYhzgtKi2SUKjxNtw70Im8k9AYaMZ0dyiFZfm/L\n' +
- 'oET85UTjoJS14wXJkXoXxHZ81TDDTyJH+7Vhl5svmlY7WPjew+kDMTLpOKPYAI+3\n' +
- 'oRlwVpkbdIXaZUlaQJCcGquiM/rlZS9lCqmx5SFbZgBLw27RiuiGDHPpViT5w0O4\n' +
- 'NlUazqpZFK1nMl9it9zvoO2Qeh/kHXgz7GlcloEvE37CG+diQNN+KdoLGdbU7t5d\n' +
- 'SW2vzt8tznOZ4GSDBqJpC4h1x9mbu8NSLPy+dQIDAQABAoIBAASG4Mr8hgaurEoC\n' +
- 'iJOsElr7vunjetMBcg/uskW/vcS8ymP3Bp5oafYG+WgnEbfvEW18f5mq7K24JuxW\n' +
- 'tUqU7ghHdjxByqk9fMlNmiqmNpbwSufkAeuRpWxPNBvhRH/zEbCL5R5A0nTEtqqF\n' +
- 'TL0aUSzwCRSoAJD0lZo9ICVt0n3GsDyM9rqQg/uZmh1qsRdwPsRuYORND9g48rKq\n' +
- '6WN9leskSxhhsYE2D9ocOFd9bNt8Zxejh9ppVSnG/KsIdt18iBzcabatgAQ046fb\n' +
- 'Z3vprcZJLg93Sg2gSuVqlSTs3M2W8VQnm22/EBMb1y0M48MSRCgnbPLG/CcCLLfF\n' +
- 'LwxCOgECgYEA/eYt67xyJ6JeAdxdwOZuT1WWGbFpLiG9+2OgiHumyRQ5969XMTWo\n' +
- 'fIhMKchDdjoy9RR236\/\/EFCs7UEyB7+a7ODRzNiK2zCD8Smjp+21fUPSthEeQesk\n' +
- 'eiMYICIu5Ay35x9sxIX+XOUVvRhPOGcD29GVeRnKh1inTHOz2dje8LkCgYEAyQeY\n' +
- 'STi9jjCEcHkM1E/UeDiLfHHepLXi8wS41JNRHl5Jacp7XB5djAjKu/jf367/VpFy\n' +
- 'GDDMetE7n8eWkrnAvovxOwZ000YDMtL1sUYSjL+XtBS5s6VY1p4qaSAY9nUUGrJh\n' +
- 'JvtvsuI7SKTtL+60vjBOH7zDnvOdBgAp0utLhZ0CgYEAuLzzqrPKB8afShFSchn4\n' +
- 'J2dpuLYahsNsXW7HDqeR2nsKFosRETAusLXnXPtnAq4kB6jlOarwFqnsuRCX24Vx\n' +
- 'r2uBm9/vYL7zMdUPTA+s30ErHuhjsKjsOKYyVqcooSwT32pBFNk+E89nutfmRG7I\n' +
- 'IvhjHuNCNqqtx/Xj5d1jkZkCgYBQicppC2Jl5OoqZVTOem0U/RJk+PnJ41TZJ7sk\n' +
- '7yBAmmWvDH\/\/l+rCf4M5a6vFYcbKV9rt9h711X2dtciNX/3oWQh8LUoAmrwNUJc+\n' +
- 'PmSQHvIYI3WCk2vUD+nN1B4sHxu+1lg11eYaNKiroeeknG2tBI1ICcgVlmQCU25u\n' +
- 'IfZPwQKBgQCdO6QHhPLtcHUDNFA6FQ1jKL1iEd7G0JLVRz4Xkpkn1Vrr5MD6JFDa\n' +
- '5ccabADyl0lpFqDIVJQIzLku2hOD2i9aBNCY0pL391HeOS7CkZX+TdOY1tquoBq5\n' +
- 'MnmixZjDCVd2VcrVyTA6ntOBoharKFW0rH1PqU+qu7dZF7CBPbAdEw==\n' +
- '-----END RSA PRIVATE KEY-----\n'
-};
-
-const WPA_EAP_AP_LIST = [
- {
- ssid: 'WPA-EAP-PEAP',
- ieee8021x: 1,
- eapol_version: 1,
- eap_server: 1,
- eapol_key_index_workaround: 0,
- eap_user_file: SERVER_EAP_USER_CONF.path,
- ca_cert: CA_CERT.path,
- server_cert: SERVER_CERT.path,
- private_key: SERVER_KEY.path,
- wpa: 3,
- wpa_key_mgmt: 'WPA-EAP'
- }
-];
-
-const CLIENT_PKCS12_CERT = {
- nickname: 'client',
- password: 'password',
- usage: ['UserCert', 'ServerCert'],
- content: [0x30, 0x82, 0x0E, 0x01, 0x02, 0x01, 0x03, 0x30,
- 0x82, 0x0D, 0xC7, 0x06, 0x09, 0x2A, 0x86, 0x48,
- 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x82,
- 0x0D, 0xB8, 0x04, 0x82, 0x0D, 0xB4, 0x30, 0x82,
- 0x0D, 0xB0, 0x30, 0x82, 0x08, 0x67, 0x06, 0x09,
- 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07,
- 0x06, 0xA0, 0x82, 0x08, 0x58, 0x30, 0x82, 0x08,
- 0x54, 0x02, 0x01, 0x00, 0x30, 0x82, 0x08, 0x4D,
- 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D,
- 0x01, 0x07, 0x01, 0x30, 0x1C, 0x06, 0x0A, 0x2A,
- 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01,
- 0x06, 0x30, 0x0E, 0x04, 0x08, 0x67, 0x7A, 0xF3,
- 0x61, 0xBE, 0xE0, 0x51, 0xC1, 0x02, 0x02, 0x08,
- 0x00, 0x80, 0x82, 0x08, 0x20, 0xFC, 0x6A, 0x79,
- 0xA1, 0x6C, 0xAF, 0xBE, 0xEE, 0x62, 0x45, 0x33,
- 0xB8, 0x48, 0xE1, 0x68, 0xA1, 0x15, 0x11, 0x4B,
- 0x95, 0xCB, 0x77, 0xC0, 0x5D, 0xA2, 0xCB, 0xDB,
- 0xD1, 0x83, 0x74, 0x60, 0xD7, 0xEC, 0x42, 0xA6,
- 0x3A, 0x23, 0xF7, 0x85, 0xEB, 0xC1, 0xFE, 0x6A,
- 0x57, 0x8E, 0xC1, 0x44, 0xF3, 0x1F, 0xFE, 0xB8,
- 0x2D, 0x8C, 0x4D, 0xC9, 0x5B, 0xAE, 0x21, 0x2E,
- 0x4C, 0x1A, 0xEB, 0x84, 0x09, 0xF3, 0x40, 0x92,
- 0x39, 0x7F, 0x56, 0x02, 0x46, 0x61, 0x16, 0xDE,
- 0x5C, 0x48, 0xB6, 0x0C, 0x1D, 0xD3, 0x5F, 0x10,
- 0x9A, 0x39, 0xB8, 0x66, 0x31, 0xFC, 0x39, 0x71,
- 0x87, 0x23, 0x46, 0x9D, 0xE8, 0x3C, 0x2B, 0xA1,
- 0x39, 0x8A, 0xD3, 0xFF, 0xD9, 0x43, 0xB6, 0x61,
- 0xC6, 0x67, 0x70, 0x40, 0xBD, 0xFE, 0xD3, 0xC1,
- 0x68, 0xF5, 0xF7, 0xC8, 0x89, 0xD8, 0x17, 0xC5,
- 0xE8, 0x3D, 0x29, 0xD5, 0x91, 0xDF, 0x1F, 0x56,
- 0x74, 0x5A, 0xC4, 0xA8, 0x14, 0xBA, 0xD4, 0xFA,
- 0x13, 0x49, 0x2A, 0x9F, 0x63, 0xF1, 0xB2, 0x45,
- 0xF1, 0xF0, 0x2A, 0xDD, 0x75, 0x66, 0x8A, 0xF7,
- 0xAB, 0x73, 0x86, 0x26, 0x9D, 0x1F, 0x07, 0xAD,
- 0xD3, 0xFE, 0xE0, 0xA3, 0xED, 0xA0, 0x96, 0x3E,
- 0x1E, 0x89, 0x86, 0x02, 0x4C, 0x28, 0xFD, 0x57,
- 0xA1, 0x67, 0x55, 0xF0, 0x82, 0x3B, 0x7F, 0xCC,
- 0x2A, 0x32, 0x01, 0x93, 0x1D, 0x8B, 0x66, 0x8A,
- 0x20, 0x52, 0x84, 0xDD, 0x2C, 0xFD, 0xEE, 0x72,
- 0xF3, 0x8C, 0x58, 0xB9, 0x99, 0xE5, 0xC1, 0x22,
- 0x63, 0x59, 0x00, 0xE2, 0x76, 0xC5, 0x3A, 0x17,
- 0x7F, 0x93, 0xE9, 0x67, 0x61, 0xAA, 0x10, 0xC3,
- 0xD9, 0xC8, 0x24, 0x46, 0x5B, 0xBE, 0x8C, 0x1F,
- 0x2D, 0x66, 0x48, 0xD2, 0x02, 0x11, 0xFB, 0x74,
- 0x14, 0x76, 0x76, 0x5A, 0x98, 0x54, 0x35, 0xA7,
- 0x85, 0x66, 0x20, 0x26, 0x8B, 0x13, 0x6F, 0x68,
- 0xE3, 0xC9, 0x58, 0x7D, 0x1C, 0x3E, 0x01, 0x8D,
- 0xF8, 0xD6, 0x7F, 0xCF, 0xA2, 0x07, 0xB7, 0x95,
- 0xFD, 0xF0, 0x02, 0x34, 0x32, 0x30, 0xE8, 0xD4,
- 0x57, 0x5E, 0x53, 0xFB, 0x54, 0xE2, 0x03, 0x32,
- 0xCC, 0x52, 0x2E, 0xD2, 0x35, 0xD9, 0x58, 0x85,
- 0x2D, 0xEC, 0x2D, 0x71, 0xD1, 0x8A, 0x29, 0xD0,
- 0xB0, 0x24, 0xBD, 0x24, 0xDC, 0x1A, 0x28, 0x3F,
- 0xA0, 0x12, 0x81, 0x15, 0x24, 0xC9, 0xB5, 0x4A,
- 0x23, 0xB6, 0xA3, 0x45, 0x50, 0x2D, 0x73, 0x99,
- 0x6B, 0x1C, 0xFB, 0xA4, 0x53, 0xD7, 0x5C, 0xF4,
- 0x6C, 0xB0, 0xE5, 0x74, 0xB3, 0x76, 0xF8, 0xB1,
- 0x0D, 0x59, 0x70, 0x9F, 0xCA, 0xDE, 0xF2, 0xAA,
- 0x4C, 0x7D, 0x11, 0x54, 0xC4, 0x19, 0x0F, 0x36,
- 0x4A, 0x62, 0xFF, 0x8B, 0x10, 0xCB, 0x93, 0x50,
- 0xDA, 0x79, 0x5E, 0x4E, 0x09, 0x1F, 0x22, 0xC8,
- 0x19, 0x85, 0xE9, 0xEE, 0xB7, 0x71, 0x65, 0xB9,
- 0x10, 0xD2, 0x0A, 0x73, 0x5B, 0xA6, 0xDA, 0x37,
- 0x46, 0x02, 0x00, 0x98, 0x9E, 0x20, 0x6C, 0x7D,
- 0xC7, 0x69, 0xBB, 0xC2, 0x00, 0x40, 0x9C, 0x57,
- 0x00, 0xC2, 0x36, 0x76, 0xE8, 0x2A, 0x8D, 0xAD,
- 0x62, 0x57, 0xC8, 0xD0, 0x9D, 0x66, 0x27, 0x5A,
- 0xD8, 0x0D, 0x35, 0x60, 0x28, 0x38, 0x62, 0x94,
- 0x78, 0x36, 0x25, 0x58, 0xFD, 0xF8, 0x66, 0x1F,
- 0x68, 0x04, 0x0F, 0xD8, 0x00, 0xDF, 0xA0, 0x6C,
- 0x25, 0x42, 0x9A, 0x4C, 0xEB, 0x80, 0x13, 0x51,
- 0x7D, 0x2D, 0xA8, 0x89, 0xD6, 0x1B, 0x67, 0x72,
- 0x01, 0xF3, 0x2D, 0x16, 0x77, 0xFE, 0x22, 0xBC,
- 0x8A, 0x45, 0x09, 0x1F, 0x9C, 0x2F, 0x2A, 0xA9,
- 0x61, 0x5B, 0x4A, 0xE6, 0x64, 0x2C, 0x62, 0x1A,
- 0x3A, 0x96, 0xE6, 0x0A, 0xAE, 0x05, 0x1A, 0xC8,
- 0xCB, 0xD6, 0x8F, 0x3A, 0x4B, 0xE0, 0x7F, 0x82,
- 0xB4, 0x98, 0xF1, 0x9D, 0xD7, 0x14, 0x76, 0x5E,
- 0x77, 0x85, 0x87, 0xEC, 0x13, 0xDA, 0xFD, 0xAF,
- 0xCB, 0xA3, 0x1C, 0x99, 0xC1, 0xFE, 0x17, 0x0C,
- 0x40, 0x4D, 0x3C, 0x8F, 0x70, 0x86, 0x63, 0x64,
- 0xB7, 0x75, 0xA8, 0x71, 0x36, 0xDC, 0x54, 0x10,
- 0x57, 0x0C, 0xA8, 0xF2, 0xA1, 0xBB, 0xED, 0x03,
- 0x41, 0x57, 0x34, 0x2C, 0x8F, 0x7C, 0xA0, 0x09,
- 0xF3, 0x9E, 0x41, 0xB7, 0xA8, 0xD4, 0x66, 0x0D,
- 0x0D, 0xC0, 0x6A, 0xFC, 0x6A, 0xA2, 0xAC, 0xE2,
- 0x60, 0x00, 0xE3, 0xF7, 0x75, 0x43, 0x23, 0xEB,
- 0xC8, 0x61, 0xFA, 0xB3, 0xB8, 0x28, 0xCE, 0xCA,
- 0xF4, 0x47, 0x7F, 0x30, 0x6D, 0x61, 0x89, 0x47,
- 0xA1, 0x4A, 0xFE, 0xD1, 0x21, 0x0B, 0x6D, 0xF4,
- 0x3F, 0x00, 0x86, 0x30, 0x8E, 0x33, 0x21, 0x6F,
- 0xDA, 0x15, 0xFD, 0x5F, 0xEC, 0x8E, 0xF1, 0x12,
- 0x3F, 0xC9, 0x83, 0x0C, 0xCA, 0x22, 0x01, 0xF1,
- 0x70, 0x5F, 0x1F, 0x66, 0xB5, 0xF8, 0x3E, 0x7A,
- 0x6F, 0xDE, 0xDB, 0xA7, 0x8D, 0x18, 0x9E, 0xBE,
- 0xDB, 0xAD, 0x3D, 0x66, 0x30, 0xC1, 0x6C, 0x0C,
- 0x87, 0xB4, 0x65, 0x75, 0xE0, 0x9D, 0xEA, 0x16,
- 0x0D, 0x07, 0x37, 0x33, 0xC5, 0xEC, 0x97, 0x93,
- 0x37, 0xEB, 0x8E, 0x65, 0x9C, 0x40, 0x63, 0x6C,
- 0x43, 0x60, 0xB0, 0x40, 0x4D, 0x85, 0xEF, 0xC2,
- 0x47, 0x5F, 0xE7, 0x6B, 0xCB, 0x40, 0xE8, 0xEA,
- 0xD8, 0xAB, 0xB1, 0x9A, 0x72, 0xDC, 0x4C, 0x14,
- 0xFA, 0x43, 0x61, 0x5F, 0xA6, 0x5C, 0x3A, 0x05,
- 0x17, 0x2E, 0x74, 0xF3, 0x5E, 0x45, 0xD9, 0x47,
- 0xAA, 0x59, 0xB6, 0x8F, 0x42, 0x66, 0x42, 0x29,
- 0x90, 0x95, 0x48, 0x46, 0x91, 0x88, 0x3C, 0x8C,
- 0xDE, 0xCC, 0xED, 0xB3, 0xAA, 0x62, 0xEA, 0xBC,
- 0xB4, 0x0C, 0x48, 0x4C, 0x53, 0x23, 0x5E, 0x24,
- 0x85, 0xBF, 0x92, 0xDA, 0x14, 0xDB, 0x1A, 0x3D,
- 0xEF, 0x30, 0xD9, 0x49, 0x64, 0x4D, 0xE5, 0x01,
- 0xFC, 0xA4, 0x4B, 0xD1, 0x9F, 0xDE, 0x96, 0x7F,
- 0x50, 0xBC, 0x4D, 0x38, 0x44, 0xE9, 0x23, 0x5F,
- 0x37, 0x57, 0x1A, 0xA6, 0x52, 0x5A, 0x0F, 0x4F,
- 0x87, 0x33, 0x4A, 0x7B, 0x66, 0xEE, 0x3D, 0x66,
- 0x0A, 0x63, 0x39, 0x1F, 0x23, 0x38, 0x35, 0x73,
- 0x60, 0x5E, 0x47, 0x20, 0x4F, 0xC0, 0xC8, 0x3C,
- 0x09, 0xF9, 0x29, 0x4F, 0x5E, 0x55, 0x69, 0xC4,
- 0x6B, 0xE8, 0xF8, 0x91, 0xC0, 0x22, 0x65, 0x15,
- 0x1E, 0xFB, 0xB9, 0x61, 0xCE, 0x45, 0xBE, 0x2B,
- 0xEE, 0xB9, 0x04, 0x2B, 0xFD, 0xAE, 0x61, 0x1C,
- 0x3D, 0x3D, 0x7C, 0xBF, 0xC1, 0xF7, 0x3C, 0x4E,
- 0x9E, 0x0E, 0x54, 0xC8, 0xAD, 0xA9, 0xDF, 0x43,
- 0x49, 0xB9, 0x41, 0x05, 0xE5, 0xF1, 0x49, 0xAA,
- 0x77, 0x6C, 0x34, 0x5B, 0x93, 0x24, 0x24, 0x23,
- 0x74, 0x68, 0x11, 0xCE, 0x15, 0x80, 0xA1, 0xA4,
- 0x1F, 0x8D, 0x81, 0xCD, 0xB2, 0x98, 0xCA, 0x14,
- 0x0B, 0x0C, 0x61, 0x50, 0x69, 0x72, 0xAE, 0xFA,
- 0x8B, 0xC0, 0x3F, 0x0D, 0xE7, 0xF2, 0x0F, 0xEB,
- 0xC1, 0x11, 0xB9, 0x10, 0x03, 0x6A, 0xF5, 0x97,
- 0x3C, 0x53, 0x2F, 0x67, 0x86, 0x09, 0x6A, 0xE3,
- 0x28, 0xC0, 0x78, 0xC8, 0xB4, 0x39, 0x8E, 0xD1,
- 0xCE, 0x25, 0xE8, 0x66, 0xF7, 0x09, 0x40, 0x7D,
- 0x81, 0xFB, 0xAF, 0xFA, 0x59, 0xC4, 0x9B, 0x2B,
- 0x83, 0x45, 0x5B, 0xA8, 0x66, 0x9E, 0x38, 0xC8,
- 0xFD, 0xAC, 0xF2, 0x2D, 0x21, 0xDE, 0x50, 0x4C,
- 0x03, 0xCB, 0x88, 0x42, 0xDD, 0x84, 0x09, 0x99,
- 0x8E, 0x8B, 0x40, 0x97, 0x1B, 0x14, 0x85, 0x37,
- 0x11, 0x01, 0xE0, 0x74, 0x6B, 0x33, 0x52, 0x8C,
- 0x68, 0x3A, 0x89, 0xB2, 0xAF, 0x35, 0xE6, 0x65,
- 0xC3, 0x58, 0x70, 0xD2, 0xE7, 0x1F, 0x1F, 0xF6,
- 0xE5, 0x0A, 0xB1, 0xFE, 0xD0, 0xC9, 0x51, 0x50,
- 0xE7, 0xFD, 0x58, 0xF5, 0xC4, 0x58, 0x65, 0x94,
- 0xD1, 0x57, 0x55, 0x5E, 0xD2, 0x27, 0x98, 0xAF,
- 0xE7, 0x55, 0x0B, 0x87, 0x50, 0x9B, 0xEF, 0xE8,
- 0x2B, 0xFC, 0xE7, 0x3B, 0x4E, 0xD7, 0xB7, 0x4D,
- 0xF4, 0xBC, 0xF4, 0x88, 0x63, 0xE4, 0x8A, 0x20,
- 0x4B, 0x22, 0xB0, 0xA0, 0x53, 0x7F, 0xA8, 0xC9,
- 0x0C, 0xF8, 0xD7, 0xBD, 0x46, 0x39, 0xA7, 0x7D,
- 0xDD, 0x10, 0x91, 0x50, 0x54, 0x06, 0x47, 0xF0,
- 0x3C, 0xAA, 0x43, 0x40, 0xF8, 0x54, 0xDD, 0x8A,
- 0xEA, 0x8A, 0x0B, 0xA5, 0x7F, 0xCD, 0x5E, 0xAA,
- 0x02, 0x2E, 0x1F, 0xC6, 0x50, 0x15, 0xF8, 0x0A,
- 0x0C, 0x1B, 0x3C, 0x55, 0x3A, 0xC3, 0x6F, 0x88,
- 0xD7, 0xBF, 0xB1, 0x02, 0xCC, 0xE0, 0x08, 0x29,
- 0x97, 0xD2, 0xAA, 0x23, 0xC4, 0x6D, 0xE3, 0xE3,
- 0x76, 0x39, 0x92, 0xC3, 0x2E, 0x7A, 0xE2, 0x98,
- 0xD1, 0xFC, 0xAE, 0xCC, 0x95, 0xD8, 0xB4, 0xDC,
- 0x92, 0xEA, 0x6A, 0x5F, 0xF2, 0x92, 0x17, 0x0B,
- 0x8D, 0xC3, 0xFA, 0x9C, 0x62, 0xCE, 0x44, 0x8D,
- 0xC3, 0x1E, 0xC3, 0xB2, 0xD5, 0x00, 0xCD, 0xB4,
- 0x9E, 0x2D, 0x7B, 0xF2, 0x98, 0xA3, 0x00, 0x8B,
- 0x81, 0x30, 0x77, 0x5B, 0x02, 0x99, 0xB1, 0xCD,
- 0xC3, 0x1D, 0x74, 0x74, 0xEF, 0x41, 0xCB, 0x69,
- 0x63, 0x8E, 0xA6, 0xD3, 0x2D, 0x3E, 0x1F, 0x1D,
- 0x12, 0x9E, 0xD9, 0x18, 0x67, 0x06, 0xAF, 0x37,
- 0x29, 0xAD, 0x65, 0xD8, 0xEB, 0x71, 0xC4, 0x7D,
- 0x94, 0x3D, 0xEA, 0xCC, 0xDF, 0x72, 0x41, 0x51,
- 0x3C, 0xA1, 0x66, 0x98, 0x32, 0x32, 0x40, 0x54,
- 0xB0, 0x2F, 0xEB, 0xCE, 0xDF, 0x4A, 0x64, 0xFB,
- 0x9A, 0x90, 0xDC, 0xF6, 0x6F, 0xA9, 0xD4, 0xCA,
- 0xCB, 0x91, 0xC4, 0xFE, 0xEE, 0x9C, 0x01, 0x50,
- 0x2E, 0xAC, 0xCC, 0x5F, 0x89, 0xD0, 0x91, 0xA3,
- 0xD9, 0xF9, 0x4B, 0x8D, 0xDE, 0x6C, 0x60, 0x21,
- 0x19, 0xB1, 0xD3, 0x4D, 0x75, 0x56, 0x6F, 0xB8,
- 0x25, 0xA4, 0x92, 0x4F, 0x12, 0xF5, 0x8F, 0xC1,
- 0x17, 0x4B, 0xB3, 0x34, 0x21, 0x22, 0xAC, 0x52,
- 0xD2, 0x64, 0xC9, 0x9A, 0x7D, 0xFC, 0xC0, 0x0A,
- 0x89, 0x34, 0xFF, 0x08, 0xD3, 0x04, 0xDC, 0xFE,
- 0x7C, 0xB3, 0xB8, 0xFD, 0x85, 0xDD, 0x79, 0x51,
- 0xA7, 0x89, 0xE8, 0xF1, 0x23, 0xB1, 0xDF, 0xD7,
- 0x1F, 0x7B, 0xB1, 0x5D, 0x42, 0xF9, 0x61, 0xF8,
- 0xDC, 0x81, 0x04, 0xF1, 0xCC, 0xFA, 0xD7, 0xED,
- 0xBF, 0x47, 0xAC, 0xBD, 0xE5, 0xFA, 0xAC, 0xB3,
- 0x1C, 0xD9, 0xA1, 0xB3, 0x60, 0xEE, 0x9C, 0x8A,
- 0x36, 0x57, 0xB4, 0x2F, 0xA1, 0xA2, 0xF3, 0xE2,
- 0x09, 0x9A, 0x6E, 0x43, 0x9B, 0xE5, 0x93, 0xB8,
- 0x3D, 0x9E, 0x9F, 0xC1, 0xC6, 0x0D, 0x02, 0xEB,
- 0x4D, 0x38, 0xE9, 0xB4, 0x9F, 0xEA, 0x33, 0x8C,
- 0x07, 0xD8, 0xB4, 0x71, 0xAD, 0xE5, 0x43, 0xB2,
- 0xCC, 0x55, 0x93, 0x6A, 0xDB, 0x1E, 0x80, 0xDB,
- 0xC2, 0xEA, 0x42, 0x8E, 0xFC, 0x86, 0x44, 0xC9,
- 0x8A, 0xC4, 0xF2, 0x46, 0xA7, 0x39, 0x50, 0x0D,
- 0x1A, 0xAA, 0x07, 0x04, 0xBE, 0xD4, 0xCE, 0x62,
- 0x4D, 0x0F, 0x91, 0x7D, 0x29, 0x88, 0x9C, 0x4C,
- 0xAF, 0xF7, 0xD8, 0x40, 0x93, 0x88, 0xC7, 0x20,
- 0xD2, 0x17, 0x2A, 0xC4, 0x92, 0x72, 0xD0, 0xC0,
- 0x4E, 0x56, 0x47, 0xB1, 0x27, 0x02, 0xE6, 0x61,
- 0x82, 0x5E, 0xC8, 0x2E, 0x90, 0xD2, 0x31, 0x22,
- 0xE2, 0xA9, 0x4A, 0x91, 0x45, 0x69, 0xB1, 0xA5,
- 0x0F, 0x66, 0x2C, 0x30, 0xAD, 0x7F, 0x1B, 0x0E,
- 0x22, 0x17, 0x60, 0x2E, 0x3D, 0x7F, 0x7F, 0x8C,
- 0x33, 0x51, 0xA0, 0x25, 0xDE, 0xFD, 0x75, 0xBC,
- 0xEF, 0xE6, 0xE7, 0x20, 0x04, 0x5A, 0xEC, 0x50,
- 0x21, 0x48, 0x56, 0x98, 0xE2, 0x33, 0x6D, 0x22,
- 0x5C, 0xC3, 0xFB, 0xFC, 0x6F, 0xB3, 0xA7, 0x8E,
- 0x6F, 0x67, 0x70, 0x9D, 0xDA, 0x02, 0x01, 0x59,
- 0x7B, 0x3D, 0x2B, 0x38, 0xCC, 0x0F, 0x44, 0x3D,
- 0xFB, 0x9A, 0xB3, 0x23, 0x15, 0x50, 0x6E, 0xBF,
- 0x8B, 0xA1, 0x94, 0x33, 0xE5, 0x7B, 0x88, 0x4E,
- 0xCB, 0x6D, 0x9F, 0xBF, 0xBC, 0x7A, 0xA8, 0x1E,
- 0x68, 0x25, 0xED, 0x8E, 0x53, 0x21, 0x72, 0xC5,
- 0x70, 0xB3, 0xE4, 0xA6, 0xA1, 0x5A, 0x2D, 0xC8,
- 0x43, 0x9D, 0x60, 0x77, 0x78, 0xE0, 0xC4, 0xAF,
- 0xC8, 0x29, 0xBA, 0xD0, 0x4D, 0x39, 0x83, 0x51,
- 0xA7, 0x10, 0x7F, 0x0C, 0x34, 0x0E, 0x6C, 0x75,
- 0x26, 0xD7, 0xD6, 0xC7, 0x32, 0x53, 0xAF, 0x4E,
- 0xBE, 0xF2, 0xC2, 0x0F, 0x99, 0x23, 0xB9, 0xE1,
- 0xC8, 0xB4, 0xBC, 0x5A, 0xC6, 0xCB, 0xEB, 0x4D,
- 0x28, 0x56, 0x72, 0xFE, 0x1B, 0x2C, 0x5D, 0xE3,
- 0xBC, 0xC7, 0xA3, 0xC0, 0x7D, 0x27, 0xF0, 0xD0,
- 0x4F, 0x3F, 0x1F, 0xF7, 0x87, 0x15, 0xF2, 0xEA,
- 0xD4, 0x03, 0x6D, 0x2F, 0xD4, 0x8E, 0x50, 0x4B,
- 0x05, 0xBF, 0xF7, 0x8C, 0x67, 0x5A, 0xDC, 0x4D,
- 0xCD, 0xCF, 0x9D, 0x02, 0xB6, 0xE7, 0xAE, 0x49,
- 0xD1, 0x7C, 0x00, 0xE7, 0x3B, 0xEA, 0xFB, 0x0D,
- 0x2A, 0x7B, 0x41, 0x33, 0x66, 0xD0, 0x29, 0x9F,
- 0xB3, 0x8A, 0x71, 0xB0, 0xE2, 0x76, 0xA9, 0xDB,
- 0xFD, 0x64, 0x04, 0x69, 0xDF, 0x89, 0x1F, 0x56,
- 0x86, 0x92, 0xD9, 0xD9, 0xB9, 0xF3, 0x4F, 0xAC,
- 0xAE, 0x61, 0x48, 0x20, 0xCE, 0x3C, 0x2B, 0x44,
- 0xAB, 0x42, 0xFA, 0xAB, 0x2E, 0x94, 0x82, 0xC8,
- 0xD9, 0x97, 0xCF, 0x27, 0xDF, 0xAC, 0xAC, 0xE7,
- 0xCA, 0xB2, 0x84, 0xAB, 0xF2, 0x5D, 0xDF, 0x56,
- 0x0C, 0x8C, 0x07, 0x3C, 0x3D, 0xA8, 0xDD, 0xBE,
- 0xFF, 0x4E, 0x28, 0x0D, 0xB2, 0x2D, 0xE6, 0x9D,
- 0x44, 0x21, 0xCB, 0xE7, 0x33, 0x63, 0x22, 0x8F,
- 0x4C, 0xFF, 0xB6, 0x1D, 0x9A, 0x71, 0x3F, 0xB1,
- 0x29, 0xAE, 0x3A, 0x35, 0xEE, 0x9C, 0x97, 0x68,
- 0xA7, 0x52, 0x66, 0x01, 0xD8, 0x9A, 0x5D, 0xF4,
- 0xB3, 0x2F, 0x5C, 0xD4, 0x0E, 0xF9, 0xCF, 0x07,
- 0xF6, 0x8C, 0xBA, 0xA6, 0x8D, 0x6B, 0xC6, 0x01,
- 0xC2, 0x69, 0xAE, 0x60, 0x08, 0x1A, 0x0E, 0x3F,
- 0xAE, 0x60, 0x29, 0xF3, 0x48, 0x0D, 0xE0, 0xD0,
- 0xAE, 0x52, 0x44, 0xE9, 0x7F, 0x1F, 0x92, 0x5F,
- 0x71, 0xAD, 0xEC, 0x6B, 0x47, 0x66, 0x92, 0x22,
- 0x27, 0xAE, 0x6E, 0x25, 0xCD, 0xF3, 0x5F, 0x55,
- 0x59, 0xBD, 0x73, 0xCE, 0x2B, 0x7E, 0x99, 0x44,
- 0x56, 0x70, 0xA3, 0xE7, 0x7A, 0x59, 0x75, 0xD8,
- 0x48, 0x0C, 0x39, 0x2B, 0xD7, 0x53, 0xC6, 0xAD,
- 0x4A, 0x6F, 0xB4, 0x14, 0x96, 0xDF, 0xF2, 0x4A,
- 0x0C, 0xA2, 0xD5, 0x29, 0x98, 0x7C, 0x42, 0x87,
- 0xD9, 0x1F, 0x97, 0x61, 0xD9, 0xBF, 0x99, 0x4F,
- 0x2C, 0x4C, 0x75, 0xAC, 0xB8, 0x06, 0x75, 0xD6,
- 0x87, 0x76, 0x7E, 0xE3, 0x23, 0x4B, 0xEA, 0x1A,
- 0x1A, 0xF4, 0xB7, 0x09, 0xAF, 0x53, 0xEB, 0xA6,
- 0x39, 0x10, 0xFE, 0xD4, 0xEB, 0x1B, 0xAE, 0x38,
- 0x31, 0x33, 0xBA, 0x68, 0xEE, 0xC7, 0x65, 0x76,
- 0xFB, 0x49, 0x77, 0xD4, 0x19, 0xC4, 0xE6, 0xA7,
- 0x05, 0xFE, 0x2A, 0xDA, 0x39, 0x99, 0x1A, 0x92,
- 0xD2, 0xF0, 0x61, 0x97, 0xF6, 0x06, 0x6C, 0x88,
- 0x7B, 0x6F, 0x60, 0xE6, 0x70, 0x08, 0xF0, 0xB4,
- 0x6B, 0x39, 0x6F, 0x05, 0x41, 0x81, 0xF9, 0xBE,
- 0x7A, 0x51, 0xC4, 0x75, 0xB0, 0x6A, 0x89, 0xA0,
- 0xA6, 0x9A, 0x5B, 0xEE, 0x7D, 0x78, 0x17, 0x5F,
- 0x9F, 0x3B, 0x7D, 0xDD, 0x8A, 0x9E, 0xAA, 0x1A,
- 0xDA, 0x49, 0x08, 0xE9, 0xFD, 0x91, 0xA6, 0xFA,
- 0xCE, 0xCF, 0x67, 0xDF, 0x0F, 0xC9, 0xD6, 0x38,
- 0xD9, 0xD5, 0xD1, 0xC0, 0x76, 0x59, 0x42, 0x53,
- 0xBF, 0x48, 0xE9, 0x11, 0x74, 0xC7, 0x11, 0xD8,
- 0xE7, 0x8E, 0xD3, 0xC8, 0x25, 0xA1, 0x26, 0x50,
- 0xBB, 0xB4, 0x35, 0xAF, 0xAF, 0x06, 0x23, 0x69,
- 0x3E, 0x30, 0xFD, 0x7B, 0x34, 0x83, 0x07, 0xD0,
- 0xF0, 0x0F, 0x6C, 0x9A, 0x13, 0x5D, 0xC2, 0x7B,
- 0xDF, 0x6F, 0xDD, 0x8E, 0xF4, 0x30, 0x82, 0x05,
- 0x41, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
- 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x82, 0x05, 0x32,
- 0x04, 0x82, 0x05, 0x2E, 0x30, 0x82, 0x05, 0x2A,
- 0x30, 0x82, 0x05, 0x26, 0x06, 0x0B, 0x2A, 0x86,
- 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01,
- 0x02, 0xA0, 0x82, 0x04, 0xEE, 0x30, 0x82, 0x04,
- 0xEA, 0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48,
- 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03, 0x30,
- 0x0E, 0x04, 0x08, 0x74, 0xC0, 0x84, 0x8F, 0xC7,
- 0x74, 0x5E, 0x21, 0x02, 0x02, 0x08, 0x00, 0x04,
- 0x82, 0x04, 0xC8, 0x1E, 0xF4, 0xE9, 0x07, 0x27,
- 0x9E, 0x5A, 0xC9, 0x39, 0x1D, 0x37, 0x2C, 0x06,
- 0x4B, 0x57, 0xEA, 0xC5, 0x42, 0x9A, 0x60, 0xD5,
- 0x42, 0xB2, 0x34, 0x2D, 0xD3, 0x88, 0x7C, 0x78,
- 0x87, 0xB6, 0xE9, 0x42, 0x44, 0x1F, 0x67, 0x32,
- 0x92, 0x54, 0x22, 0xDA, 0xB2, 0x43, 0xE7, 0x40,
- 0xBE, 0x1F, 0xAF, 0x3A, 0xCD, 0x2A, 0x9F, 0xD7,
- 0x44, 0x5B, 0x37, 0x69, 0x85, 0xDF, 0xEB, 0x2A,
- 0xB9, 0xE2, 0x92, 0x3B, 0xEA, 0xD5, 0x42, 0x53,
- 0x95, 0x4A, 0xB0, 0x1B, 0xA5, 0xEF, 0xA6, 0x0D,
- 0x29, 0xF4, 0x33, 0xFE, 0xD7, 0x49, 0x04, 0x1E,
- 0x8C, 0xAD, 0x63, 0x1E, 0x79, 0x63, 0x74, 0x0C,
- 0xE5, 0x5E, 0xA2, 0x2C, 0xBE, 0xB8, 0x90, 0xCE,
- 0x06, 0x25, 0xBF, 0xD1, 0x5A, 0x50, 0xCF, 0x3B,
- 0x52, 0xE2, 0xA7, 0xFF, 0x19, 0x02, 0xCF, 0xD0,
- 0x9B, 0xD9, 0xF7, 0x28, 0x07, 0x38, 0x1F, 0xF2,
- 0xAF, 0x44, 0x91, 0x3F, 0x0F, 0xB6, 0x6E, 0x8C,
- 0xC0, 0x32, 0x92, 0xC0, 0xCD, 0x25, 0x98, 0x67,
- 0xF1, 0x47, 0x52, 0x50, 0xF0, 0xA3, 0x7B, 0xE6,
- 0x74, 0xDC, 0x72, 0x28, 0xC8, 0xAB, 0xB3, 0x31,
- 0x7D, 0xA3, 0xF7, 0xC7, 0xD1, 0xE6, 0x99, 0xB4,
- 0xB6, 0x5A, 0x3A, 0x4D, 0x83, 0x4F, 0xB8, 0xB5,
- 0x86, 0xF8, 0x37, 0x7F, 0xA0, 0x16, 0x2F, 0x3C,
- 0x62, 0x7A, 0xD4, 0x3A, 0xEB, 0xC2, 0xE8, 0x03,
- 0x49, 0x17, 0x9E, 0xFB, 0xD7, 0xAF, 0x91, 0x32,
- 0xFD, 0xEA, 0x4F, 0x64, 0xC6, 0x6E, 0x02, 0xEA,
- 0xC4, 0xC8, 0x1F, 0x16, 0xC5, 0x4C, 0xFB, 0xC5,
- 0x42, 0xF5, 0x85, 0x05, 0x92, 0x59, 0x4B, 0x31,
- 0xE5, 0xE9, 0x69, 0xE7, 0x02, 0x98, 0x33, 0xBA,
- 0x4C, 0x17, 0x09, 0xEF, 0x89, 0x20, 0xFA, 0x83,
- 0x9F, 0xAE, 0x0E, 0x1B, 0x7D, 0x98, 0xB9, 0xF2,
- 0x3C, 0x0F, 0xB7, 0x1C, 0x72, 0xDF, 0x17, 0x84,
- 0x7F, 0x0A, 0xFD, 0x12, 0x3C, 0x6F, 0x68, 0x5D,
- 0x45, 0xEB, 0xB8, 0xD6, 0x24, 0x65, 0x42, 0x75,
- 0x5C, 0xC2, 0xF3, 0x3A, 0x6A, 0x4E, 0x51, 0x34,
- 0x1B, 0xB6, 0x81, 0xB2, 0x8A, 0xEF, 0x28, 0xA4,
- 0xC5, 0x88, 0x9A, 0x97, 0xE0, 0xEF, 0x31, 0x12,
- 0x01, 0x7E, 0x1B, 0x43, 0x0F, 0x27, 0x80, 0x87,
- 0x98, 0xC5, 0xD5, 0x83, 0xCB, 0x4B, 0xB7, 0x01,
- 0x79, 0x60, 0xA1, 0x1A, 0x03, 0x05, 0xC6, 0x36,
- 0x04, 0x31, 0x3C, 0x06, 0xDB, 0x08, 0xA8, 0xDA,
- 0x8E, 0x32, 0x19, 0x91, 0xF1, 0x0D, 0x61, 0x6F,
- 0xE4, 0xB2, 0x79, 0x8A, 0xDE, 0xF4, 0xF7, 0xFB,
- 0x2C, 0x23, 0x5B, 0xD9, 0x64, 0x2F, 0xB7, 0xB3,
- 0x8B, 0xCA, 0xB8, 0x8C, 0x1D, 0x3B, 0x49, 0x05,
- 0x38, 0xA1, 0xE5, 0x8C, 0x1A, 0xDC, 0xA5, 0x61,
- 0xFE, 0xF4, 0x2B, 0xDC, 0x77, 0x28, 0xF6, 0x19,
- 0xE7, 0xB7, 0x8F, 0x4D, 0x27, 0x2D, 0xED, 0x8A,
- 0x3F, 0x3D, 0xDC, 0x9F, 0xD1, 0x30, 0xFF, 0xD6,
- 0xC3, 0xBE, 0x41, 0x25, 0xE3, 0xA5, 0x9B, 0x73,
- 0xDF, 0x6A, 0xD9, 0xF9, 0x70, 0x84, 0x02, 0x4C,
- 0x35, 0xD4, 0x3E, 0x05, 0x76, 0x3A, 0xDC, 0x6D,
- 0x5A, 0x81, 0xB3, 0x94, 0xF7, 0x22, 0xF7, 0xDC,
- 0xC1, 0x43, 0x31, 0x57, 0x5B, 0x42, 0x9A, 0x0B,
- 0xF4, 0x95, 0x30, 0xA9, 0xBB, 0xD8, 0x06, 0xFB,
- 0x1D, 0x6F, 0x9B, 0xC3, 0xBB, 0xF3, 0xBF, 0xFB,
- 0xB4, 0x9F, 0x35, 0x64, 0x0A, 0x69, 0xB7, 0xD1,
- 0x3E, 0xCA, 0x78, 0x07, 0x04, 0x03, 0x79, 0xD4,
- 0xF3, 0xA8, 0xEC, 0x18, 0xDB, 0x03, 0x5E, 0x47,
- 0xD7, 0xD0, 0x56, 0x2C, 0x74, 0x94, 0x86, 0x04,
- 0x46, 0xB8, 0xD4, 0x35, 0x0A, 0x7B, 0xE6, 0x78,
- 0xC4, 0x43, 0x3C, 0x56, 0xCC, 0x37, 0x8B, 0xFD,
- 0xE8, 0xF4, 0x57, 0xEA, 0xAE, 0xCF, 0x36, 0x97,
- 0x12, 0xAC, 0x39, 0xCF, 0x7C, 0xEF, 0x22, 0x67,
- 0x01, 0xEC, 0xD8, 0x09, 0x49, 0x4E, 0xE3, 0x74,
- 0xDD, 0x39, 0xE1, 0x39, 0xD7, 0x0C, 0x5F, 0x1B,
- 0xCE, 0x69, 0xBC, 0x72, 0x44, 0x87, 0x64, 0x1C,
- 0x08, 0x05, 0x93, 0x69, 0x6D, 0x7F, 0x90, 0x0A,
- 0x2C, 0xCB, 0x8A, 0xBB, 0x7F, 0xE3, 0xE0, 0x80,
- 0x31, 0xD0, 0x0A, 0x3A, 0x95, 0xFF, 0xF7, 0xB4,
- 0x36, 0x38, 0x93, 0xE0, 0x0C, 0x11, 0x37, 0x12,
- 0x06, 0xF6, 0xAD, 0xE9, 0xB1, 0x7A, 0x00, 0xF5,
- 0xD2, 0x32, 0x6B, 0xD0, 0x27, 0xA5, 0x1B, 0x3D,
- 0xE8, 0xDB, 0xCC, 0xA9, 0x1F, 0x1F, 0xB1, 0x99,
- 0x3D, 0x7C, 0xB7, 0xCA, 0xDA, 0x27, 0x2C, 0x64,
- 0x1C, 0x49, 0xB6, 0x87, 0x44, 0x06, 0x94, 0x9D,
- 0xBC, 0x6B, 0x20, 0xA2, 0x68, 0x15, 0x1F, 0xE2,
- 0xF2, 0xAD, 0x6D, 0x23, 0x2E, 0x2B, 0x74, 0xE2,
- 0x5D, 0xE4, 0xB0, 0xC7, 0x84, 0xCB, 0x64, 0xBF,
- 0xE0, 0xA8, 0x18, 0x83, 0xB4, 0xC9, 0xD9, 0x73,
- 0xA8, 0xE6, 0xA9, 0x36, 0xD5, 0x63, 0x1E, 0x2C,
- 0x2A, 0x55, 0x09, 0x77, 0x5E, 0xB3, 0x4B, 0xEA,
- 0xB5, 0xD0, 0x14, 0x5F, 0xEB, 0x50, 0x7B, 0xAA,
- 0xEF, 0x94, 0xBA, 0x2B, 0xD7, 0x8A, 0x07, 0xF1,
- 0xF9, 0x5E, 0x12, 0x12, 0x21, 0x52, 0xE5, 0x0A,
- 0x3E, 0xC0, 0xBC, 0x5D, 0x4C, 0xE2, 0x12, 0x7C,
- 0x39, 0xF9, 0x16, 0x9D, 0xBD, 0x96, 0x83, 0x3B,
- 0x7F, 0x3D, 0x6A, 0xEC, 0xF1, 0x25, 0xD2, 0xB0,
- 0xB0, 0xEB, 0x20, 0x06, 0x07, 0xD6, 0xD9, 0x4C,
- 0x07, 0x9A, 0x82, 0xC1, 0xFC, 0xF7, 0x66, 0x15,
- 0xBD, 0x62, 0x65, 0xD8, 0x6C, 0xF6, 0x33, 0x7B,
- 0x5A, 0x28, 0xEC, 0x90, 0xA1, 0x26, 0x9F, 0xC3,
- 0x28, 0x4A, 0x64, 0x50, 0x5F, 0xCA, 0xE2, 0x6D,
- 0xB8, 0x0F, 0xE2, 0x94, 0xB5, 0x8E, 0x1F, 0x8A,
- 0x8F, 0x6B, 0xA6, 0x86, 0x1F, 0xEE, 0xDC, 0x24,
- 0xB4, 0xB8, 0x25, 0xEC, 0x28, 0x2D, 0xF9, 0xCB,
- 0x7D, 0x38, 0xFF, 0xC7, 0x74, 0x2E, 0xD3, 0x10,
- 0xEC, 0x03, 0x31, 0xEE, 0x83, 0xE7, 0xA4, 0xF7,
- 0xBA, 0x28, 0x21, 0xE0, 0x7F, 0xB4, 0xB7, 0xE1,
- 0x7A, 0xF9, 0x2B, 0xB0, 0x2C, 0x3B, 0x80, 0x5F,
- 0xE0, 0x5D, 0xB2, 0x7E, 0x59, 0xFF, 0x59, 0x07,
- 0x58, 0x42, 0x57, 0xEE, 0x44, 0xF1, 0xB1, 0xAD,
- 0xBA, 0xDE, 0xCB, 0x1D, 0x8A, 0x36, 0x67, 0xE8,
- 0x45, 0xFF, 0x07, 0x8D, 0xEE, 0xA4, 0x51, 0x9C,
- 0x4C, 0x83, 0x5D, 0x2E, 0x2F, 0xE1, 0x5B, 0x75,
- 0xE8, 0x29, 0xCD, 0x0B, 0x07, 0x62, 0xE0, 0xC3,
- 0x0D, 0x1D, 0xEA, 0xCF, 0xF0, 0x8A, 0x65, 0x27,
- 0x70, 0x42, 0x9F, 0x26, 0x00, 0x15, 0x70, 0xC5,
- 0x4A, 0xF6, 0x25, 0xD0, 0x40, 0x72, 0xE9, 0xC1,
- 0x73, 0xFD, 0x48, 0x94, 0xA3, 0x8D, 0x66, 0x63,
- 0x96, 0x4F, 0xF7, 0xEE, 0xFB, 0x4C, 0xC7, 0xB8,
- 0x6B, 0xE9, 0x90, 0xE1, 0x2A, 0x66, 0x80, 0x99,
- 0x3B, 0xB0, 0x1A, 0x6C, 0xF9, 0x0E, 0x72, 0xDA,
- 0x8E, 0x4F, 0x46, 0xC2, 0x6A, 0x4B, 0x7A, 0x16,
- 0xE5, 0x26, 0x0B, 0x5C, 0xD4, 0x47, 0x34, 0xE5,
- 0x37, 0xBE, 0x68, 0x6C, 0xDA, 0xD3, 0x9B, 0x6F,
- 0xAE, 0x51, 0x9C, 0x99, 0x0A, 0x5B, 0xF8, 0x37,
- 0xBC, 0xDE, 0xFC, 0x93, 0xC5, 0xE7, 0x0F, 0xEF,
- 0x0B, 0xA6, 0x07, 0xC2, 0xA6, 0xE6, 0xDA, 0x2D,
- 0x1B, 0x49, 0xC9, 0xDE, 0x6B, 0x27, 0xDC, 0x00,
- 0xEF, 0x23, 0x87, 0x0E, 0xEB, 0xD1, 0x48, 0x7D,
- 0xB4, 0xF2, 0x58, 0xC6, 0x3C, 0xE2, 0x89, 0xBA,
- 0xB0, 0x05, 0xAC, 0x94, 0x41, 0x9A, 0xA8, 0xFF,
- 0x3E, 0xBC, 0x3A, 0x52, 0x9C, 0xF9, 0x7F, 0x07,
- 0x8B, 0xB0, 0x2C, 0x71, 0x83, 0x7B, 0xCF, 0x2E,
- 0x7F, 0x7C, 0x96, 0x65, 0xD9, 0x08, 0x17, 0xEC,
- 0xFA, 0xDE, 0x4E, 0x40, 0x12, 0x26, 0x70, 0x71,
- 0x65, 0xA5, 0xDC, 0x98, 0x47, 0xA3, 0xFC, 0xE0,
- 0x9A, 0x16, 0xED, 0x45, 0x56, 0x72, 0x50, 0x05,
- 0x28, 0x2C, 0x99, 0xEC, 0x20, 0x2E, 0x40, 0xC0,
- 0x26, 0x69, 0xCD, 0x49, 0x45, 0x17, 0xA4, 0xA3,
- 0x42, 0x0D, 0x14, 0x65, 0x87, 0x33, 0x8C, 0x92,
- 0xC5, 0xC4, 0x61, 0xFD, 0xE8, 0x68, 0x56, 0x20,
- 0x57, 0xF5, 0x8E, 0x5F, 0xCF, 0x7E, 0x97, 0xF6,
- 0x49, 0x97, 0x0A, 0xFE, 0xD3, 0x60, 0x1A, 0x5B,
- 0x0C, 0x75, 0xDD, 0x8E, 0x31, 0x78, 0x29, 0xA6,
- 0xB1, 0x4D, 0xAA, 0xDF, 0x8A, 0xD1, 0xE6, 0x91,
- 0xE3, 0x32, 0x3F, 0xEC, 0x8A, 0x1F, 0x0E, 0x35,
- 0x07, 0x6E, 0x4B, 0x83, 0x3B, 0xE5, 0x67, 0x34,
- 0x1F, 0x0C, 0x81, 0xD8, 0xD5, 0x25, 0x68, 0xE5,
- 0x28, 0x1B, 0x5C, 0x81, 0x3E, 0xE3, 0x5C, 0xB4,
- 0xB6, 0xBD, 0x62, 0x6A, 0x70, 0x33, 0xC2, 0xC5,
- 0x75, 0x27, 0xF4, 0x30, 0xE1, 0x1D, 0xC1, 0x4C,
- 0xC5, 0x02, 0x12, 0x46, 0xAC, 0xEC, 0xF9, 0xE8,
- 0xE7, 0x58, 0x24, 0x11, 0xB1, 0xF3, 0xB7, 0x8C,
- 0x3C, 0xA4, 0x0A, 0x94, 0xA6, 0x7C, 0x68, 0x54,
- 0x5B, 0xB9, 0x4D, 0x57, 0x9C, 0xE7, 0x28, 0x09,
- 0x6B, 0x89, 0x26, 0x5D, 0xE7, 0x50, 0xA9, 0x95,
- 0x90, 0x91, 0x8E, 0x00, 0x59, 0xF8, 0x3A, 0x70,
- 0xAF, 0x48, 0x2E, 0xE8, 0xC4, 0x34, 0x8C, 0xF4,
- 0x5F, 0x7F, 0xCB, 0x07, 0xAA, 0xF0, 0xD9, 0xFB,
- 0x5C, 0x32, 0x90, 0x22, 0x1A, 0xD2, 0x1A, 0xCF,
- 0x92, 0x06, 0x02, 0xCF, 0x10, 0x18, 0x7B, 0x93,
- 0xCC, 0x07, 0x4A, 0x31, 0x25, 0x30, 0x23, 0x06,
- 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01,
- 0x09, 0x15, 0x31, 0x16, 0x04, 0x14, 0xD1, 0xDE,
- 0x23, 0x16, 0x9F, 0x6E, 0xF4, 0x42, 0x21, 0x23,
- 0xE1, 0x11, 0xAA, 0xC8, 0x7C, 0x60, 0x4A, 0x78,
- 0x9D, 0x24, 0x30, 0x31, 0x30, 0x21, 0x30, 0x09,
- 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05,
- 0x00, 0x04, 0x14, 0xD6, 0x4A, 0xBB, 0x75, 0xB1,
- 0xF9, 0x9E, 0xD3, 0x58, 0x6D, 0xD1, 0x74, 0x9F,
- 0x00, 0x8A, 0xF2, 0xC8, 0xAA, 0x52, 0x4D, 0x04,
- 0x08, 0x77, 0x46, 0xE7, 0xBA, 0x25, 0x4B, 0xDA,
- 0x41, 0x02, 0x02, 0x08, 0x00]
-};
-
-const WPA_EAP_CLIENT_LIST = [
- {
- ssid: 'WPA-EAP-PEAP',
- keyManagement: 'WPA-EAP',
- eap: 'PEAP',
- identity: EAP_USERNAME,
- password: EAP_PASSWORD,
- serverCertificate: CLIENT_PKCS12_CERT.nickname,
- phase2: 'MSCHAPV2'
- }
-];
-
-/**
- * Convert the given MozWifiNetwork object array to testAssociate chain.
- *
- * @param aNetworks
- * An array of MozWifiNetwork which we want to convert.
- *
- * @return A promise chain which "then"s testAssociate accordingly.
- */
-function convertToTestAssociateChain(aNetworks) {
- let chain = Promise.resolve();
-
- aNetworks.forEach(function (aNetwork) {
- network = new window.MozWifiNetwork(aNetwork);
- chain = chain.then(() => gTestSuite.testAssociate(network));
- });
-
- return chain;
-}
-
-gTestSuite.doTestWithCertificate(
- new Blob([new Uint8Array(CLIENT_PKCS12_CERT.content)]),
- CLIENT_PKCS12_CERT.password,
- CLIENT_PKCS12_CERT.nickname,
- CLIENT_PKCS12_CERT.usage,
- function() {
- return gTestSuite.ensureWifiEnabled(true)
- // Load required server files.
- .then(() => gTestSuite.writeFile(SERVER_EAP_USER_CONF.path, SERVER_EAP_USER_CONF.content))
- .then(() => gTestSuite.writeFile(CA_CERT.path, CA_CERT.content))
- .then(() => gTestSuite.writeFile(SERVER_CERT.path, SERVER_CERT.content))
- .then(() => gTestSuite.writeFile(SERVER_KEY.path, SERVER_KEY.content))
- // Start AP.
- .then(() => gTestSuite.startHostapds(WPA_EAP_AP_LIST))
- // Scan test.
- .then(() => gTestSuite.testWifiScanWithRetry(SCAN_RETRY_CNT, WPA_EAP_AP_LIST))
- // Associate test.
- .then(() => convertToTestAssociateChain(WPA_EAP_CLIENT_LIST))
- // Tear down.
- .then(gTestSuite.killAllHostapd)
-});
diff --git a/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_TLS.js b/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_TLS.js
deleted file mode 100644
index 35b942f8e..000000000
--- a/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_TLS.js
+++ /dev/null
@@ -1,622 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SCAN_RETRY_CNT = 5;
-
-const EAP_USERNAME = 'username';
-const EAP_PASSWORD = 'password';
-
-const SERVER_EAP_USER_CONF = {
- path: HOSTAPD_CONFIG_PATH + 'hostapd.eap_user',
- content: '* PEAP,TTLS,TLS\n' +
- '"' + EAP_USERNAME + '" MSCHAPV2,TTLS-MSCHAPV2 "' + EAP_PASSWORD + '" [2]\n'
-};
-const CA_CERT = {
- path: HOSTAPD_CONFIG_PATH + 'ca.pem',
- content: '-----BEGIN CERTIFICATE-----\n' +
- 'MIIDsTCCApmgAwIBAgIJAKxTf+8X8qngMA0GCSqGSIb3DQEBCwUAMG4xCzAJBgNV\n' +
- 'BAYTAlRXMRMwEQYDVQQIDApTb21lLVN0YXRlMREwDwYDVQQKDAhjaHVja2xlZTER\n' +
- 'MA8GA1UEAwwIY2h1Y2tsZWUxJDAiBgkqhkiG9w0BCQEWFWNodWNrbGkwNzA2QGdt\n' +
- 'YWlsLmNvbTAgFw0xNDEyMjQxMTI4NTBaGA8yMjg4MTAwNzExMjg1MFowbjELMAkG\n' +
- 'A1UEBhMCVFcxEzARBgNVBAgMClNvbWUtU3RhdGUxETAPBgNVBAoMCGNodWNrbGVl\n' +
- 'MREwDwYDVQQDDAhjaHVja2xlZTEkMCIGCSqGSIb3DQEJARYVY2h1Y2tsaTA3MDZA\n' +
- 'Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo3c2yFxY\n' +
- 'o6gGg0I83jy00ME+MAfzCd+4ShL45ZLqysQP93jRBfPzU9ZuZ29ysVwgWIdqkZao\n' +
- 'XTuV/NAW2GMGd8W1jQJ3J81fjb9wvhlny3rrACwvUn1N1S1BnM+BAAiDLGxEmvAQ\n' +
- 'onp2aaa6HsHsYS8ONX+d2Qh4LEA4vupeSGAqJychCZv/l+aq/ErFZhFYB3CPUQEt\n' +
- 'cClO24ucsIYP95lA0zhscnmAj06qplFD4Bv6IVrdDqujy1zNwCQwsJq/8OQdaTN/\n' +
- 'h3y9pWvNKMBMM2niOUAjtuNpqsSK/lTS1WAT3PdtVECX9fYBi0Bg+HM92xs/6gt6\n' +
- 'kh9jPV8keXHvSwIDAQABo1AwTjAdBgNVHQ4EFgQU7hBqhuG04xeCzrQ3ngx18ZJ3\n' +
- 'lUswHwYDVR0jBBgwFoAU7hBqhuG04xeCzrQ3ngx18ZJ3lUswDAYDVR0TBAUwAwEB\n' +
- '/zANBgkqhkiG9w0BAQsFAAOCAQEAFYX2iy680GAnBTttk0gyX6gk+8pYr3D22k/G\n' +
- '6rvcjefzS7ELQPRKr6mfmwXq3mMf/4jiS2zI5zmXsestPYzHYxf2viQ6t7vr9XiJ\n' +
- '3WfFjNw4ERlRisAvg0aqqTNNQq5v2VME4sdFZagy217f73C7azwCHl0bqOLH05rl\n' +
- '8RubOxiHEj7ZybJqnRciK/bht4D+rZkwf4bBBmoloqH7xT0+rFQclpYXDGGjNUQB\n' +
- 'LcHLF10xcr7g3ZVVu82fe6+d85gIGOIMR9+TKhdw6gO3CNcnDAj6gxksghgtcxmh\n' +
- 'OzOggCn7nlIwImtsg2sZkpWB4lEi9hdv4lkNuyFjOL3bnuc+NA==\n' +
- '-----END CERTIFICATE-----\n'
-};
-
-const SERVER_CERT = {
- path: HOSTAPD_CONFIG_PATH + 'server.pem',
- content: '-----BEGIN CERTIFICATE-----\n' +
- 'MIID1DCCArygAwIBAgIBADANBgkqhkiG9w0BAQsFADBuMQswCQYDVQQGEwJUVzET\n' +
- 'MBEGA1UECAwKU29tZS1TdGF0ZTERMA8GA1UECgwIY2h1Y2tsZWUxETAPBgNVBAMM\n' +
- 'CGNodWNrbGVlMSQwIgYJKoZIhvcNAQkBFhVjaHVja2xpMDcwNkBnbWFpbC5jb20w\n' +
- 'IBcNMTQxMjI0MTEyOTQ5WhgPMjI4ODEwMDcxMTI5NDlaMG4xCzAJBgNVBAYTAlRX\n' +
- 'MRMwEQYDVQQIDApTb21lLVN0YXRlMREwDwYDVQQKDAhjaHVja2xlZTERMA8GA1UE\n' +
- 'AwwIY2h1Y2tsZWUxJDAiBgkqhkiG9w0BCQEWFWNodWNrbGkwNzA2QGdtYWlsLmNv\n' +
- 'bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMdhQmKilTJbWZRxTiSV\n' +
- 'rqIU+LYW1RKghx5o+0JpNRJVLuz5kBMaNskbbfUSNuHbEq0QA9BDKAZWIc4LSotk\n' +
- 'lCo8TbcO9CJvJPQGGjGdHcohWX5vy6BE/OVE46CUteMFyZF6F8R2fNUww08iR/u1\n' +
- 'YZebL5pWO1j43sPpAzEy6Tij2ACPt6EZcFaZG3SF2mVJWkCQnBqrojP65WUvZQqp\n' +
- 'seUhW2YAS8Nu0Yrohgxz6VYk+cNDuDZVGs6qWRStZzJfYrfc76DtkHof5B14M+xp\n' +
- 'XJaBLxN+whvnYkDTfinaCxnW1O7eXUltr87fLc5zmeBkgwaiaQuIdcfZm7vDUiz8\n' +
- 'vnUCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBH\n' +
- 'ZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFKK4f9/YavTHOfEiAB83Deac\n' +
- '6gT5MB8GA1UdIwQYMBaAFO4QaobhtOMXgs60N54MdfGSd5VLMA0GCSqGSIb3DQEB\n' +
- 'CwUAA4IBAQBWnO9o9KSJIqjoz5Nwll63ULOdcvgGdOeJIw1fcKQ817Rsp+TVcjcH\n' +
- 'IrIADsT/QZGXRO/l6p1750e2iFtJEo1hsRaxtA1wWn2I9HO3+av2spQhr3jpYGPf\n' +
- 'zpsMTp4RNYV7Q8+q1kZIz9PY4V1T0p6lveK8+fUj2hSLnxSj0QiGSJJtnEC3w4Rv\n' +
- 'C9T6oUwIeToULmi+8FXQFdEqwKRU98DPq3eLzN28ZxUgoPE1C8+42D2UW8uyp/Gm\n' +
- 'tGOa/k7nzkCdVqZI7lX7f0AjEvQgjtAMQ/k7Mhxx7TzW2HO+1YPMoKji6Z4WkNwt\n' +
- 'JEj9ZUBSNt8B26UksJMBDkcvSegF3a7o\n' +
- '-----END CERTIFICATE-----\n'
-};
-
-const SERVER_KEY = {
- path: HOSTAPD_CONFIG_PATH + 'server.key',
- content: '-----BEGIN RSA PRIVATE KEY-----\n' +
- 'MIIEpAIBAAKCAQEAx2FCYqKVMltZlHFOJJWuohT4thbVEqCHHmj7Qmk1ElUu7PmQ\n' +
- 'Exo2yRtt9RI24dsSrRAD0EMoBlYhzgtKi2SUKjxNtw70Im8k9AYaMZ0dyiFZfm/L\n' +
- 'oET85UTjoJS14wXJkXoXxHZ81TDDTyJH+7Vhl5svmlY7WPjew+kDMTLpOKPYAI+3\n' +
- 'oRlwVpkbdIXaZUlaQJCcGquiM/rlZS9lCqmx5SFbZgBLw27RiuiGDHPpViT5w0O4\n' +
- 'NlUazqpZFK1nMl9it9zvoO2Qeh/kHXgz7GlcloEvE37CG+diQNN+KdoLGdbU7t5d\n' +
- 'SW2vzt8tznOZ4GSDBqJpC4h1x9mbu8NSLPy+dQIDAQABAoIBAASG4Mr8hgaurEoC\n' +
- 'iJOsElr7vunjetMBcg/uskW/vcS8ymP3Bp5oafYG+WgnEbfvEW18f5mq7K24JuxW\n' +
- 'tUqU7ghHdjxByqk9fMlNmiqmNpbwSufkAeuRpWxPNBvhRH/zEbCL5R5A0nTEtqqF\n' +
- 'TL0aUSzwCRSoAJD0lZo9ICVt0n3GsDyM9rqQg/uZmh1qsRdwPsRuYORND9g48rKq\n' +
- '6WN9leskSxhhsYE2D9ocOFd9bNt8Zxejh9ppVSnG/KsIdt18iBzcabatgAQ046fb\n' +
- 'Z3vprcZJLg93Sg2gSuVqlSTs3M2W8VQnm22/EBMb1y0M48MSRCgnbPLG/CcCLLfF\n' +
- 'LwxCOgECgYEA/eYt67xyJ6JeAdxdwOZuT1WWGbFpLiG9+2OgiHumyRQ5969XMTWo\n' +
- 'fIhMKchDdjoy9RR236\/\/EFCs7UEyB7+a7ODRzNiK2zCD8Smjp+21fUPSthEeQesk\n' +
- 'eiMYICIu5Ay35x9sxIX+XOUVvRhPOGcD29GVeRnKh1inTHOz2dje8LkCgYEAyQeY\n' +
- 'STi9jjCEcHkM1E/UeDiLfHHepLXi8wS41JNRHl5Jacp7XB5djAjKu/jf367/VpFy\n' +
- 'GDDMetE7n8eWkrnAvovxOwZ000YDMtL1sUYSjL+XtBS5s6VY1p4qaSAY9nUUGrJh\n' +
- 'JvtvsuI7SKTtL+60vjBOH7zDnvOdBgAp0utLhZ0CgYEAuLzzqrPKB8afShFSchn4\n' +
- 'J2dpuLYahsNsXW7HDqeR2nsKFosRETAusLXnXPtnAq4kB6jlOarwFqnsuRCX24Vx\n' +
- 'r2uBm9/vYL7zMdUPTA+s30ErHuhjsKjsOKYyVqcooSwT32pBFNk+E89nutfmRG7I\n' +
- 'IvhjHuNCNqqtx/Xj5d1jkZkCgYBQicppC2Jl5OoqZVTOem0U/RJk+PnJ41TZJ7sk\n' +
- '7yBAmmWvDH\/\/l+rCf4M5a6vFYcbKV9rt9h711X2dtciNX/3oWQh8LUoAmrwNUJc+\n' +
- 'PmSQHvIYI3WCk2vUD+nN1B4sHxu+1lg11eYaNKiroeeknG2tBI1ICcgVlmQCU25u\n' +
- 'IfZPwQKBgQCdO6QHhPLtcHUDNFA6FQ1jKL1iEd7G0JLVRz4Xkpkn1Vrr5MD6JFDa\n' +
- '5ccabADyl0lpFqDIVJQIzLku2hOD2i9aBNCY0pL391HeOS7CkZX+TdOY1tquoBq5\n' +
- 'MnmixZjDCVd2VcrVyTA6ntOBoharKFW0rH1PqU+qu7dZF7CBPbAdEw==\n' +
- '-----END RSA PRIVATE KEY-----\n'
-};
-
-const WPA_EAP_AP_LIST = [
- {
- ssid: 'WPA-EAP-TLS',
- ieee8021x: 1,
- eapol_version: 1,
- eap_server: 1,
- eapol_key_index_workaround: 0,
- eap_user_file: SERVER_EAP_USER_CONF.path,
- ca_cert: CA_CERT.path,
- server_cert: SERVER_CERT.path,
- private_key: SERVER_KEY.path,
- wpa: 2,
- wpa_key_mgmt: 'WPA-EAP'
- }
-];
-
-const CLIENT_PKCS12_CERT = {
- nickname: 'client',
- password: 'password',
- usage: ['UserCert', 'ServerCert'],
- content: [0x30, 0x82, 0x0E, 0x01, 0x02, 0x01, 0x03, 0x30,
- 0x82, 0x0D, 0xC7, 0x06, 0x09, 0x2A, 0x86, 0x48,
- 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x82,
- 0x0D, 0xB8, 0x04, 0x82, 0x0D, 0xB4, 0x30, 0x82,
- 0x0D, 0xB0, 0x30, 0x82, 0x08, 0x67, 0x06, 0x09,
- 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07,
- 0x06, 0xA0, 0x82, 0x08, 0x58, 0x30, 0x82, 0x08,
- 0x54, 0x02, 0x01, 0x00, 0x30, 0x82, 0x08, 0x4D,
- 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D,
- 0x01, 0x07, 0x01, 0x30, 0x1C, 0x06, 0x0A, 0x2A,
- 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01,
- 0x06, 0x30, 0x0E, 0x04, 0x08, 0x67, 0x7A, 0xF3,
- 0x61, 0xBE, 0xE0, 0x51, 0xC1, 0x02, 0x02, 0x08,
- 0x00, 0x80, 0x82, 0x08, 0x20, 0xFC, 0x6A, 0x79,
- 0xA1, 0x6C, 0xAF, 0xBE, 0xEE, 0x62, 0x45, 0x33,
- 0xB8, 0x48, 0xE1, 0x68, 0xA1, 0x15, 0x11, 0x4B,
- 0x95, 0xCB, 0x77, 0xC0, 0x5D, 0xA2, 0xCB, 0xDB,
- 0xD1, 0x83, 0x74, 0x60, 0xD7, 0xEC, 0x42, 0xA6,
- 0x3A, 0x23, 0xF7, 0x85, 0xEB, 0xC1, 0xFE, 0x6A,
- 0x57, 0x8E, 0xC1, 0x44, 0xF3, 0x1F, 0xFE, 0xB8,
- 0x2D, 0x8C, 0x4D, 0xC9, 0x5B, 0xAE, 0x21, 0x2E,
- 0x4C, 0x1A, 0xEB, 0x84, 0x09, 0xF3, 0x40, 0x92,
- 0x39, 0x7F, 0x56, 0x02, 0x46, 0x61, 0x16, 0xDE,
- 0x5C, 0x48, 0xB6, 0x0C, 0x1D, 0xD3, 0x5F, 0x10,
- 0x9A, 0x39, 0xB8, 0x66, 0x31, 0xFC, 0x39, 0x71,
- 0x87, 0x23, 0x46, 0x9D, 0xE8, 0x3C, 0x2B, 0xA1,
- 0x39, 0x8A, 0xD3, 0xFF, 0xD9, 0x43, 0xB6, 0x61,
- 0xC6, 0x67, 0x70, 0x40, 0xBD, 0xFE, 0xD3, 0xC1,
- 0x68, 0xF5, 0xF7, 0xC8, 0x89, 0xD8, 0x17, 0xC5,
- 0xE8, 0x3D, 0x29, 0xD5, 0x91, 0xDF, 0x1F, 0x56,
- 0x74, 0x5A, 0xC4, 0xA8, 0x14, 0xBA, 0xD4, 0xFA,
- 0x13, 0x49, 0x2A, 0x9F, 0x63, 0xF1, 0xB2, 0x45,
- 0xF1, 0xF0, 0x2A, 0xDD, 0x75, 0x66, 0x8A, 0xF7,
- 0xAB, 0x73, 0x86, 0x26, 0x9D, 0x1F, 0x07, 0xAD,
- 0xD3, 0xFE, 0xE0, 0xA3, 0xED, 0xA0, 0x96, 0x3E,
- 0x1E, 0x89, 0x86, 0x02, 0x4C, 0x28, 0xFD, 0x57,
- 0xA1, 0x67, 0x55, 0xF0, 0x82, 0x3B, 0x7F, 0xCC,
- 0x2A, 0x32, 0x01, 0x93, 0x1D, 0x8B, 0x66, 0x8A,
- 0x20, 0x52, 0x84, 0xDD, 0x2C, 0xFD, 0xEE, 0x72,
- 0xF3, 0x8C, 0x58, 0xB9, 0x99, 0xE5, 0xC1, 0x22,
- 0x63, 0x59, 0x00, 0xE2, 0x76, 0xC5, 0x3A, 0x17,
- 0x7F, 0x93, 0xE9, 0x67, 0x61, 0xAA, 0x10, 0xC3,
- 0xD9, 0xC8, 0x24, 0x46, 0x5B, 0xBE, 0x8C, 0x1F,
- 0x2D, 0x66, 0x48, 0xD2, 0x02, 0x11, 0xFB, 0x74,
- 0x14, 0x76, 0x76, 0x5A, 0x98, 0x54, 0x35, 0xA7,
- 0x85, 0x66, 0x20, 0x26, 0x8B, 0x13, 0x6F, 0x68,
- 0xE3, 0xC9, 0x58, 0x7D, 0x1C, 0x3E, 0x01, 0x8D,
- 0xF8, 0xD6, 0x7F, 0xCF, 0xA2, 0x07, 0xB7, 0x95,
- 0xFD, 0xF0, 0x02, 0x34, 0x32, 0x30, 0xE8, 0xD4,
- 0x57, 0x5E, 0x53, 0xFB, 0x54, 0xE2, 0x03, 0x32,
- 0xCC, 0x52, 0x2E, 0xD2, 0x35, 0xD9, 0x58, 0x85,
- 0x2D, 0xEC, 0x2D, 0x71, 0xD1, 0x8A, 0x29, 0xD0,
- 0xB0, 0x24, 0xBD, 0x24, 0xDC, 0x1A, 0x28, 0x3F,
- 0xA0, 0x12, 0x81, 0x15, 0x24, 0xC9, 0xB5, 0x4A,
- 0x23, 0xB6, 0xA3, 0x45, 0x50, 0x2D, 0x73, 0x99,
- 0x6B, 0x1C, 0xFB, 0xA4, 0x53, 0xD7, 0x5C, 0xF4,
- 0x6C, 0xB0, 0xE5, 0x74, 0xB3, 0x76, 0xF8, 0xB1,
- 0x0D, 0x59, 0x70, 0x9F, 0xCA, 0xDE, 0xF2, 0xAA,
- 0x4C, 0x7D, 0x11, 0x54, 0xC4, 0x19, 0x0F, 0x36,
- 0x4A, 0x62, 0xFF, 0x8B, 0x10, 0xCB, 0x93, 0x50,
- 0xDA, 0x79, 0x5E, 0x4E, 0x09, 0x1F, 0x22, 0xC8,
- 0x19, 0x85, 0xE9, 0xEE, 0xB7, 0x71, 0x65, 0xB9,
- 0x10, 0xD2, 0x0A, 0x73, 0x5B, 0xA6, 0xDA, 0x37,
- 0x46, 0x02, 0x00, 0x98, 0x9E, 0x20, 0x6C, 0x7D,
- 0xC7, 0x69, 0xBB, 0xC2, 0x00, 0x40, 0x9C, 0x57,
- 0x00, 0xC2, 0x36, 0x76, 0xE8, 0x2A, 0x8D, 0xAD,
- 0x62, 0x57, 0xC8, 0xD0, 0x9D, 0x66, 0x27, 0x5A,
- 0xD8, 0x0D, 0x35, 0x60, 0x28, 0x38, 0x62, 0x94,
- 0x78, 0x36, 0x25, 0x58, 0xFD, 0xF8, 0x66, 0x1F,
- 0x68, 0x04, 0x0F, 0xD8, 0x00, 0xDF, 0xA0, 0x6C,
- 0x25, 0x42, 0x9A, 0x4C, 0xEB, 0x80, 0x13, 0x51,
- 0x7D, 0x2D, 0xA8, 0x89, 0xD6, 0x1B, 0x67, 0x72,
- 0x01, 0xF3, 0x2D, 0x16, 0x77, 0xFE, 0x22, 0xBC,
- 0x8A, 0x45, 0x09, 0x1F, 0x9C, 0x2F, 0x2A, 0xA9,
- 0x61, 0x5B, 0x4A, 0xE6, 0x64, 0x2C, 0x62, 0x1A,
- 0x3A, 0x96, 0xE6, 0x0A, 0xAE, 0x05, 0x1A, 0xC8,
- 0xCB, 0xD6, 0x8F, 0x3A, 0x4B, 0xE0, 0x7F, 0x82,
- 0xB4, 0x98, 0xF1, 0x9D, 0xD7, 0x14, 0x76, 0x5E,
- 0x77, 0x85, 0x87, 0xEC, 0x13, 0xDA, 0xFD, 0xAF,
- 0xCB, 0xA3, 0x1C, 0x99, 0xC1, 0xFE, 0x17, 0x0C,
- 0x40, 0x4D, 0x3C, 0x8F, 0x70, 0x86, 0x63, 0x64,
- 0xB7, 0x75, 0xA8, 0x71, 0x36, 0xDC, 0x54, 0x10,
- 0x57, 0x0C, 0xA8, 0xF2, 0xA1, 0xBB, 0xED, 0x03,
- 0x41, 0x57, 0x34, 0x2C, 0x8F, 0x7C, 0xA0, 0x09,
- 0xF3, 0x9E, 0x41, 0xB7, 0xA8, 0xD4, 0x66, 0x0D,
- 0x0D, 0xC0, 0x6A, 0xFC, 0x6A, 0xA2, 0xAC, 0xE2,
- 0x60, 0x00, 0xE3, 0xF7, 0x75, 0x43, 0x23, 0xEB,
- 0xC8, 0x61, 0xFA, 0xB3, 0xB8, 0x28, 0xCE, 0xCA,
- 0xF4, 0x47, 0x7F, 0x30, 0x6D, 0x61, 0x89, 0x47,
- 0xA1, 0x4A, 0xFE, 0xD1, 0x21, 0x0B, 0x6D, 0xF4,
- 0x3F, 0x00, 0x86, 0x30, 0x8E, 0x33, 0x21, 0x6F,
- 0xDA, 0x15, 0xFD, 0x5F, 0xEC, 0x8E, 0xF1, 0x12,
- 0x3F, 0xC9, 0x83, 0x0C, 0xCA, 0x22, 0x01, 0xF1,
- 0x70, 0x5F, 0x1F, 0x66, 0xB5, 0xF8, 0x3E, 0x7A,
- 0x6F, 0xDE, 0xDB, 0xA7, 0x8D, 0x18, 0x9E, 0xBE,
- 0xDB, 0xAD, 0x3D, 0x66, 0x30, 0xC1, 0x6C, 0x0C,
- 0x87, 0xB4, 0x65, 0x75, 0xE0, 0x9D, 0xEA, 0x16,
- 0x0D, 0x07, 0x37, 0x33, 0xC5, 0xEC, 0x97, 0x93,
- 0x37, 0xEB, 0x8E, 0x65, 0x9C, 0x40, 0x63, 0x6C,
- 0x43, 0x60, 0xB0, 0x40, 0x4D, 0x85, 0xEF, 0xC2,
- 0x47, 0x5F, 0xE7, 0x6B, 0xCB, 0x40, 0xE8, 0xEA,
- 0xD8, 0xAB, 0xB1, 0x9A, 0x72, 0xDC, 0x4C, 0x14,
- 0xFA, 0x43, 0x61, 0x5F, 0xA6, 0x5C, 0x3A, 0x05,
- 0x17, 0x2E, 0x74, 0xF3, 0x5E, 0x45, 0xD9, 0x47,
- 0xAA, 0x59, 0xB6, 0x8F, 0x42, 0x66, 0x42, 0x29,
- 0x90, 0x95, 0x48, 0x46, 0x91, 0x88, 0x3C, 0x8C,
- 0xDE, 0xCC, 0xED, 0xB3, 0xAA, 0x62, 0xEA, 0xBC,
- 0xB4, 0x0C, 0x48, 0x4C, 0x53, 0x23, 0x5E, 0x24,
- 0x85, 0xBF, 0x92, 0xDA, 0x14, 0xDB, 0x1A, 0x3D,
- 0xEF, 0x30, 0xD9, 0x49, 0x64, 0x4D, 0xE5, 0x01,
- 0xFC, 0xA4, 0x4B, 0xD1, 0x9F, 0xDE, 0x96, 0x7F,
- 0x50, 0xBC, 0x4D, 0x38, 0x44, 0xE9, 0x23, 0x5F,
- 0x37, 0x57, 0x1A, 0xA6, 0x52, 0x5A, 0x0F, 0x4F,
- 0x87, 0x33, 0x4A, 0x7B, 0x66, 0xEE, 0x3D, 0x66,
- 0x0A, 0x63, 0x39, 0x1F, 0x23, 0x38, 0x35, 0x73,
- 0x60, 0x5E, 0x47, 0x20, 0x4F, 0xC0, 0xC8, 0x3C,
- 0x09, 0xF9, 0x29, 0x4F, 0x5E, 0x55, 0x69, 0xC4,
- 0x6B, 0xE8, 0xF8, 0x91, 0xC0, 0x22, 0x65, 0x15,
- 0x1E, 0xFB, 0xB9, 0x61, 0xCE, 0x45, 0xBE, 0x2B,
- 0xEE, 0xB9, 0x04, 0x2B, 0xFD, 0xAE, 0x61, 0x1C,
- 0x3D, 0x3D, 0x7C, 0xBF, 0xC1, 0xF7, 0x3C, 0x4E,
- 0x9E, 0x0E, 0x54, 0xC8, 0xAD, 0xA9, 0xDF, 0x43,
- 0x49, 0xB9, 0x41, 0x05, 0xE5, 0xF1, 0x49, 0xAA,
- 0x77, 0x6C, 0x34, 0x5B, 0x93, 0x24, 0x24, 0x23,
- 0x74, 0x68, 0x11, 0xCE, 0x15, 0x80, 0xA1, 0xA4,
- 0x1F, 0x8D, 0x81, 0xCD, 0xB2, 0x98, 0xCA, 0x14,
- 0x0B, 0x0C, 0x61, 0x50, 0x69, 0x72, 0xAE, 0xFA,
- 0x8B, 0xC0, 0x3F, 0x0D, 0xE7, 0xF2, 0x0F, 0xEB,
- 0xC1, 0x11, 0xB9, 0x10, 0x03, 0x6A, 0xF5, 0x97,
- 0x3C, 0x53, 0x2F, 0x67, 0x86, 0x09, 0x6A, 0xE3,
- 0x28, 0xC0, 0x78, 0xC8, 0xB4, 0x39, 0x8E, 0xD1,
- 0xCE, 0x25, 0xE8, 0x66, 0xF7, 0x09, 0x40, 0x7D,
- 0x81, 0xFB, 0xAF, 0xFA, 0x59, 0xC4, 0x9B, 0x2B,
- 0x83, 0x45, 0x5B, 0xA8, 0x66, 0x9E, 0x38, 0xC8,
- 0xFD, 0xAC, 0xF2, 0x2D, 0x21, 0xDE, 0x50, 0x4C,
- 0x03, 0xCB, 0x88, 0x42, 0xDD, 0x84, 0x09, 0x99,
- 0x8E, 0x8B, 0x40, 0x97, 0x1B, 0x14, 0x85, 0x37,
- 0x11, 0x01, 0xE0, 0x74, 0x6B, 0x33, 0x52, 0x8C,
- 0x68, 0x3A, 0x89, 0xB2, 0xAF, 0x35, 0xE6, 0x65,
- 0xC3, 0x58, 0x70, 0xD2, 0xE7, 0x1F, 0x1F, 0xF6,
- 0xE5, 0x0A, 0xB1, 0xFE, 0xD0, 0xC9, 0x51, 0x50,
- 0xE7, 0xFD, 0x58, 0xF5, 0xC4, 0x58, 0x65, 0x94,
- 0xD1, 0x57, 0x55, 0x5E, 0xD2, 0x27, 0x98, 0xAF,
- 0xE7, 0x55, 0x0B, 0x87, 0x50, 0x9B, 0xEF, 0xE8,
- 0x2B, 0xFC, 0xE7, 0x3B, 0x4E, 0xD7, 0xB7, 0x4D,
- 0xF4, 0xBC, 0xF4, 0x88, 0x63, 0xE4, 0x8A, 0x20,
- 0x4B, 0x22, 0xB0, 0xA0, 0x53, 0x7F, 0xA8, 0xC9,
- 0x0C, 0xF8, 0xD7, 0xBD, 0x46, 0x39, 0xA7, 0x7D,
- 0xDD, 0x10, 0x91, 0x50, 0x54, 0x06, 0x47, 0xF0,
- 0x3C, 0xAA, 0x43, 0x40, 0xF8, 0x54, 0xDD, 0x8A,
- 0xEA, 0x8A, 0x0B, 0xA5, 0x7F, 0xCD, 0x5E, 0xAA,
- 0x02, 0x2E, 0x1F, 0xC6, 0x50, 0x15, 0xF8, 0x0A,
- 0x0C, 0x1B, 0x3C, 0x55, 0x3A, 0xC3, 0x6F, 0x88,
- 0xD7, 0xBF, 0xB1, 0x02, 0xCC, 0xE0, 0x08, 0x29,
- 0x97, 0xD2, 0xAA, 0x23, 0xC4, 0x6D, 0xE3, 0xE3,
- 0x76, 0x39, 0x92, 0xC3, 0x2E, 0x7A, 0xE2, 0x98,
- 0xD1, 0xFC, 0xAE, 0xCC, 0x95, 0xD8, 0xB4, 0xDC,
- 0x92, 0xEA, 0x6A, 0x5F, 0xF2, 0x92, 0x17, 0x0B,
- 0x8D, 0xC3, 0xFA, 0x9C, 0x62, 0xCE, 0x44, 0x8D,
- 0xC3, 0x1E, 0xC3, 0xB2, 0xD5, 0x00, 0xCD, 0xB4,
- 0x9E, 0x2D, 0x7B, 0xF2, 0x98, 0xA3, 0x00, 0x8B,
- 0x81, 0x30, 0x77, 0x5B, 0x02, 0x99, 0xB1, 0xCD,
- 0xC3, 0x1D, 0x74, 0x74, 0xEF, 0x41, 0xCB, 0x69,
- 0x63, 0x8E, 0xA6, 0xD3, 0x2D, 0x3E, 0x1F, 0x1D,
- 0x12, 0x9E, 0xD9, 0x18, 0x67, 0x06, 0xAF, 0x37,
- 0x29, 0xAD, 0x65, 0xD8, 0xEB, 0x71, 0xC4, 0x7D,
- 0x94, 0x3D, 0xEA, 0xCC, 0xDF, 0x72, 0x41, 0x51,
- 0x3C, 0xA1, 0x66, 0x98, 0x32, 0x32, 0x40, 0x54,
- 0xB0, 0x2F, 0xEB, 0xCE, 0xDF, 0x4A, 0x64, 0xFB,
- 0x9A, 0x90, 0xDC, 0xF6, 0x6F, 0xA9, 0xD4, 0xCA,
- 0xCB, 0x91, 0xC4, 0xFE, 0xEE, 0x9C, 0x01, 0x50,
- 0x2E, 0xAC, 0xCC, 0x5F, 0x89, 0xD0, 0x91, 0xA3,
- 0xD9, 0xF9, 0x4B, 0x8D, 0xDE, 0x6C, 0x60, 0x21,
- 0x19, 0xB1, 0xD3, 0x4D, 0x75, 0x56, 0x6F, 0xB8,
- 0x25, 0xA4, 0x92, 0x4F, 0x12, 0xF5, 0x8F, 0xC1,
- 0x17, 0x4B, 0xB3, 0x34, 0x21, 0x22, 0xAC, 0x52,
- 0xD2, 0x64, 0xC9, 0x9A, 0x7D, 0xFC, 0xC0, 0x0A,
- 0x89, 0x34, 0xFF, 0x08, 0xD3, 0x04, 0xDC, 0xFE,
- 0x7C, 0xB3, 0xB8, 0xFD, 0x85, 0xDD, 0x79, 0x51,
- 0xA7, 0x89, 0xE8, 0xF1, 0x23, 0xB1, 0xDF, 0xD7,
- 0x1F, 0x7B, 0xB1, 0x5D, 0x42, 0xF9, 0x61, 0xF8,
- 0xDC, 0x81, 0x04, 0xF1, 0xCC, 0xFA, 0xD7, 0xED,
- 0xBF, 0x47, 0xAC, 0xBD, 0xE5, 0xFA, 0xAC, 0xB3,
- 0x1C, 0xD9, 0xA1, 0xB3, 0x60, 0xEE, 0x9C, 0x8A,
- 0x36, 0x57, 0xB4, 0x2F, 0xA1, 0xA2, 0xF3, 0xE2,
- 0x09, 0x9A, 0x6E, 0x43, 0x9B, 0xE5, 0x93, 0xB8,
- 0x3D, 0x9E, 0x9F, 0xC1, 0xC6, 0x0D, 0x02, 0xEB,
- 0x4D, 0x38, 0xE9, 0xB4, 0x9F, 0xEA, 0x33, 0x8C,
- 0x07, 0xD8, 0xB4, 0x71, 0xAD, 0xE5, 0x43, 0xB2,
- 0xCC, 0x55, 0x93, 0x6A, 0xDB, 0x1E, 0x80, 0xDB,
- 0xC2, 0xEA, 0x42, 0x8E, 0xFC, 0x86, 0x44, 0xC9,
- 0x8A, 0xC4, 0xF2, 0x46, 0xA7, 0x39, 0x50, 0x0D,
- 0x1A, 0xAA, 0x07, 0x04, 0xBE, 0xD4, 0xCE, 0x62,
- 0x4D, 0x0F, 0x91, 0x7D, 0x29, 0x88, 0x9C, 0x4C,
- 0xAF, 0xF7, 0xD8, 0x40, 0x93, 0x88, 0xC7, 0x20,
- 0xD2, 0x17, 0x2A, 0xC4, 0x92, 0x72, 0xD0, 0xC0,
- 0x4E, 0x56, 0x47, 0xB1, 0x27, 0x02, 0xE6, 0x61,
- 0x82, 0x5E, 0xC8, 0x2E, 0x90, 0xD2, 0x31, 0x22,
- 0xE2, 0xA9, 0x4A, 0x91, 0x45, 0x69, 0xB1, 0xA5,
- 0x0F, 0x66, 0x2C, 0x30, 0xAD, 0x7F, 0x1B, 0x0E,
- 0x22, 0x17, 0x60, 0x2E, 0x3D, 0x7F, 0x7F, 0x8C,
- 0x33, 0x51, 0xA0, 0x25, 0xDE, 0xFD, 0x75, 0xBC,
- 0xEF, 0xE6, 0xE7, 0x20, 0x04, 0x5A, 0xEC, 0x50,
- 0x21, 0x48, 0x56, 0x98, 0xE2, 0x33, 0x6D, 0x22,
- 0x5C, 0xC3, 0xFB, 0xFC, 0x6F, 0xB3, 0xA7, 0x8E,
- 0x6F, 0x67, 0x70, 0x9D, 0xDA, 0x02, 0x01, 0x59,
- 0x7B, 0x3D, 0x2B, 0x38, 0xCC, 0x0F, 0x44, 0x3D,
- 0xFB, 0x9A, 0xB3, 0x23, 0x15, 0x50, 0x6E, 0xBF,
- 0x8B, 0xA1, 0x94, 0x33, 0xE5, 0x7B, 0x88, 0x4E,
- 0xCB, 0x6D, 0x9F, 0xBF, 0xBC, 0x7A, 0xA8, 0x1E,
- 0x68, 0x25, 0xED, 0x8E, 0x53, 0x21, 0x72, 0xC5,
- 0x70, 0xB3, 0xE4, 0xA6, 0xA1, 0x5A, 0x2D, 0xC8,
- 0x43, 0x9D, 0x60, 0x77, 0x78, 0xE0, 0xC4, 0xAF,
- 0xC8, 0x29, 0xBA, 0xD0, 0x4D, 0x39, 0x83, 0x51,
- 0xA7, 0x10, 0x7F, 0x0C, 0x34, 0x0E, 0x6C, 0x75,
- 0x26, 0xD7, 0xD6, 0xC7, 0x32, 0x53, 0xAF, 0x4E,
- 0xBE, 0xF2, 0xC2, 0x0F, 0x99, 0x23, 0xB9, 0xE1,
- 0xC8, 0xB4, 0xBC, 0x5A, 0xC6, 0xCB, 0xEB, 0x4D,
- 0x28, 0x56, 0x72, 0xFE, 0x1B, 0x2C, 0x5D, 0xE3,
- 0xBC, 0xC7, 0xA3, 0xC0, 0x7D, 0x27, 0xF0, 0xD0,
- 0x4F, 0x3F, 0x1F, 0xF7, 0x87, 0x15, 0xF2, 0xEA,
- 0xD4, 0x03, 0x6D, 0x2F, 0xD4, 0x8E, 0x50, 0x4B,
- 0x05, 0xBF, 0xF7, 0x8C, 0x67, 0x5A, 0xDC, 0x4D,
- 0xCD, 0xCF, 0x9D, 0x02, 0xB6, 0xE7, 0xAE, 0x49,
- 0xD1, 0x7C, 0x00, 0xE7, 0x3B, 0xEA, 0xFB, 0x0D,
- 0x2A, 0x7B, 0x41, 0x33, 0x66, 0xD0, 0x29, 0x9F,
- 0xB3, 0x8A, 0x71, 0xB0, 0xE2, 0x76, 0xA9, 0xDB,
- 0xFD, 0x64, 0x04, 0x69, 0xDF, 0x89, 0x1F, 0x56,
- 0x86, 0x92, 0xD9, 0xD9, 0xB9, 0xF3, 0x4F, 0xAC,
- 0xAE, 0x61, 0x48, 0x20, 0xCE, 0x3C, 0x2B, 0x44,
- 0xAB, 0x42, 0xFA, 0xAB, 0x2E, 0x94, 0x82, 0xC8,
- 0xD9, 0x97, 0xCF, 0x27, 0xDF, 0xAC, 0xAC, 0xE7,
- 0xCA, 0xB2, 0x84, 0xAB, 0xF2, 0x5D, 0xDF, 0x56,
- 0x0C, 0x8C, 0x07, 0x3C, 0x3D, 0xA8, 0xDD, 0xBE,
- 0xFF, 0x4E, 0x28, 0x0D, 0xB2, 0x2D, 0xE6, 0x9D,
- 0x44, 0x21, 0xCB, 0xE7, 0x33, 0x63, 0x22, 0x8F,
- 0x4C, 0xFF, 0xB6, 0x1D, 0x9A, 0x71, 0x3F, 0xB1,
- 0x29, 0xAE, 0x3A, 0x35, 0xEE, 0x9C, 0x97, 0x68,
- 0xA7, 0x52, 0x66, 0x01, 0xD8, 0x9A, 0x5D, 0xF4,
- 0xB3, 0x2F, 0x5C, 0xD4, 0x0E, 0xF9, 0xCF, 0x07,
- 0xF6, 0x8C, 0xBA, 0xA6, 0x8D, 0x6B, 0xC6, 0x01,
- 0xC2, 0x69, 0xAE, 0x60, 0x08, 0x1A, 0x0E, 0x3F,
- 0xAE, 0x60, 0x29, 0xF3, 0x48, 0x0D, 0xE0, 0xD0,
- 0xAE, 0x52, 0x44, 0xE9, 0x7F, 0x1F, 0x92, 0x5F,
- 0x71, 0xAD, 0xEC, 0x6B, 0x47, 0x66, 0x92, 0x22,
- 0x27, 0xAE, 0x6E, 0x25, 0xCD, 0xF3, 0x5F, 0x55,
- 0x59, 0xBD, 0x73, 0xCE, 0x2B, 0x7E, 0x99, 0x44,
- 0x56, 0x70, 0xA3, 0xE7, 0x7A, 0x59, 0x75, 0xD8,
- 0x48, 0x0C, 0x39, 0x2B, 0xD7, 0x53, 0xC6, 0xAD,
- 0x4A, 0x6F, 0xB4, 0x14, 0x96, 0xDF, 0xF2, 0x4A,
- 0x0C, 0xA2, 0xD5, 0x29, 0x98, 0x7C, 0x42, 0x87,
- 0xD9, 0x1F, 0x97, 0x61, 0xD9, 0xBF, 0x99, 0x4F,
- 0x2C, 0x4C, 0x75, 0xAC, 0xB8, 0x06, 0x75, 0xD6,
- 0x87, 0x76, 0x7E, 0xE3, 0x23, 0x4B, 0xEA, 0x1A,
- 0x1A, 0xF4, 0xB7, 0x09, 0xAF, 0x53, 0xEB, 0xA6,
- 0x39, 0x10, 0xFE, 0xD4, 0xEB, 0x1B, 0xAE, 0x38,
- 0x31, 0x33, 0xBA, 0x68, 0xEE, 0xC7, 0x65, 0x76,
- 0xFB, 0x49, 0x77, 0xD4, 0x19, 0xC4, 0xE6, 0xA7,
- 0x05, 0xFE, 0x2A, 0xDA, 0x39, 0x99, 0x1A, 0x92,
- 0xD2, 0xF0, 0x61, 0x97, 0xF6, 0x06, 0x6C, 0x88,
- 0x7B, 0x6F, 0x60, 0xE6, 0x70, 0x08, 0xF0, 0xB4,
- 0x6B, 0x39, 0x6F, 0x05, 0x41, 0x81, 0xF9, 0xBE,
- 0x7A, 0x51, 0xC4, 0x75, 0xB0, 0x6A, 0x89, 0xA0,
- 0xA6, 0x9A, 0x5B, 0xEE, 0x7D, 0x78, 0x17, 0x5F,
- 0x9F, 0x3B, 0x7D, 0xDD, 0x8A, 0x9E, 0xAA, 0x1A,
- 0xDA, 0x49, 0x08, 0xE9, 0xFD, 0x91, 0xA6, 0xFA,
- 0xCE, 0xCF, 0x67, 0xDF, 0x0F, 0xC9, 0xD6, 0x38,
- 0xD9, 0xD5, 0xD1, 0xC0, 0x76, 0x59, 0x42, 0x53,
- 0xBF, 0x48, 0xE9, 0x11, 0x74, 0xC7, 0x11, 0xD8,
- 0xE7, 0x8E, 0xD3, 0xC8, 0x25, 0xA1, 0x26, 0x50,
- 0xBB, 0xB4, 0x35, 0xAF, 0xAF, 0x06, 0x23, 0x69,
- 0x3E, 0x30, 0xFD, 0x7B, 0x34, 0x83, 0x07, 0xD0,
- 0xF0, 0x0F, 0x6C, 0x9A, 0x13, 0x5D, 0xC2, 0x7B,
- 0xDF, 0x6F, 0xDD, 0x8E, 0xF4, 0x30, 0x82, 0x05,
- 0x41, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
- 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x82, 0x05, 0x32,
- 0x04, 0x82, 0x05, 0x2E, 0x30, 0x82, 0x05, 0x2A,
- 0x30, 0x82, 0x05, 0x26, 0x06, 0x0B, 0x2A, 0x86,
- 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01,
- 0x02, 0xA0, 0x82, 0x04, 0xEE, 0x30, 0x82, 0x04,
- 0xEA, 0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48,
- 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03, 0x30,
- 0x0E, 0x04, 0x08, 0x74, 0xC0, 0x84, 0x8F, 0xC7,
- 0x74, 0x5E, 0x21, 0x02, 0x02, 0x08, 0x00, 0x04,
- 0x82, 0x04, 0xC8, 0x1E, 0xF4, 0xE9, 0x07, 0x27,
- 0x9E, 0x5A, 0xC9, 0x39, 0x1D, 0x37, 0x2C, 0x06,
- 0x4B, 0x57, 0xEA, 0xC5, 0x42, 0x9A, 0x60, 0xD5,
- 0x42, 0xB2, 0x34, 0x2D, 0xD3, 0x88, 0x7C, 0x78,
- 0x87, 0xB6, 0xE9, 0x42, 0x44, 0x1F, 0x67, 0x32,
- 0x92, 0x54, 0x22, 0xDA, 0xB2, 0x43, 0xE7, 0x40,
- 0xBE, 0x1F, 0xAF, 0x3A, 0xCD, 0x2A, 0x9F, 0xD7,
- 0x44, 0x5B, 0x37, 0x69, 0x85, 0xDF, 0xEB, 0x2A,
- 0xB9, 0xE2, 0x92, 0x3B, 0xEA, 0xD5, 0x42, 0x53,
- 0x95, 0x4A, 0xB0, 0x1B, 0xA5, 0xEF, 0xA6, 0x0D,
- 0x29, 0xF4, 0x33, 0xFE, 0xD7, 0x49, 0x04, 0x1E,
- 0x8C, 0xAD, 0x63, 0x1E, 0x79, 0x63, 0x74, 0x0C,
- 0xE5, 0x5E, 0xA2, 0x2C, 0xBE, 0xB8, 0x90, 0xCE,
- 0x06, 0x25, 0xBF, 0xD1, 0x5A, 0x50, 0xCF, 0x3B,
- 0x52, 0xE2, 0xA7, 0xFF, 0x19, 0x02, 0xCF, 0xD0,
- 0x9B, 0xD9, 0xF7, 0x28, 0x07, 0x38, 0x1F, 0xF2,
- 0xAF, 0x44, 0x91, 0x3F, 0x0F, 0xB6, 0x6E, 0x8C,
- 0xC0, 0x32, 0x92, 0xC0, 0xCD, 0x25, 0x98, 0x67,
- 0xF1, 0x47, 0x52, 0x50, 0xF0, 0xA3, 0x7B, 0xE6,
- 0x74, 0xDC, 0x72, 0x28, 0xC8, 0xAB, 0xB3, 0x31,
- 0x7D, 0xA3, 0xF7, 0xC7, 0xD1, 0xE6, 0x99, 0xB4,
- 0xB6, 0x5A, 0x3A, 0x4D, 0x83, 0x4F, 0xB8, 0xB5,
- 0x86, 0xF8, 0x37, 0x7F, 0xA0, 0x16, 0x2F, 0x3C,
- 0x62, 0x7A, 0xD4, 0x3A, 0xEB, 0xC2, 0xE8, 0x03,
- 0x49, 0x17, 0x9E, 0xFB, 0xD7, 0xAF, 0x91, 0x32,
- 0xFD, 0xEA, 0x4F, 0x64, 0xC6, 0x6E, 0x02, 0xEA,
- 0xC4, 0xC8, 0x1F, 0x16, 0xC5, 0x4C, 0xFB, 0xC5,
- 0x42, 0xF5, 0x85, 0x05, 0x92, 0x59, 0x4B, 0x31,
- 0xE5, 0xE9, 0x69, 0xE7, 0x02, 0x98, 0x33, 0xBA,
- 0x4C, 0x17, 0x09, 0xEF, 0x89, 0x20, 0xFA, 0x83,
- 0x9F, 0xAE, 0x0E, 0x1B, 0x7D, 0x98, 0xB9, 0xF2,
- 0x3C, 0x0F, 0xB7, 0x1C, 0x72, 0xDF, 0x17, 0x84,
- 0x7F, 0x0A, 0xFD, 0x12, 0x3C, 0x6F, 0x68, 0x5D,
- 0x45, 0xEB, 0xB8, 0xD6, 0x24, 0x65, 0x42, 0x75,
- 0x5C, 0xC2, 0xF3, 0x3A, 0x6A, 0x4E, 0x51, 0x34,
- 0x1B, 0xB6, 0x81, 0xB2, 0x8A, 0xEF, 0x28, 0xA4,
- 0xC5, 0x88, 0x9A, 0x97, 0xE0, 0xEF, 0x31, 0x12,
- 0x01, 0x7E, 0x1B, 0x43, 0x0F, 0x27, 0x80, 0x87,
- 0x98, 0xC5, 0xD5, 0x83, 0xCB, 0x4B, 0xB7, 0x01,
- 0x79, 0x60, 0xA1, 0x1A, 0x03, 0x05, 0xC6, 0x36,
- 0x04, 0x31, 0x3C, 0x06, 0xDB, 0x08, 0xA8, 0xDA,
- 0x8E, 0x32, 0x19, 0x91, 0xF1, 0x0D, 0x61, 0x6F,
- 0xE4, 0xB2, 0x79, 0x8A, 0xDE, 0xF4, 0xF7, 0xFB,
- 0x2C, 0x23, 0x5B, 0xD9, 0x64, 0x2F, 0xB7, 0xB3,
- 0x8B, 0xCA, 0xB8, 0x8C, 0x1D, 0x3B, 0x49, 0x05,
- 0x38, 0xA1, 0xE5, 0x8C, 0x1A, 0xDC, 0xA5, 0x61,
- 0xFE, 0xF4, 0x2B, 0xDC, 0x77, 0x28, 0xF6, 0x19,
- 0xE7, 0xB7, 0x8F, 0x4D, 0x27, 0x2D, 0xED, 0x8A,
- 0x3F, 0x3D, 0xDC, 0x9F, 0xD1, 0x30, 0xFF, 0xD6,
- 0xC3, 0xBE, 0x41, 0x25, 0xE3, 0xA5, 0x9B, 0x73,
- 0xDF, 0x6A, 0xD9, 0xF9, 0x70, 0x84, 0x02, 0x4C,
- 0x35, 0xD4, 0x3E, 0x05, 0x76, 0x3A, 0xDC, 0x6D,
- 0x5A, 0x81, 0xB3, 0x94, 0xF7, 0x22, 0xF7, 0xDC,
- 0xC1, 0x43, 0x31, 0x57, 0x5B, 0x42, 0x9A, 0x0B,
- 0xF4, 0x95, 0x30, 0xA9, 0xBB, 0xD8, 0x06, 0xFB,
- 0x1D, 0x6F, 0x9B, 0xC3, 0xBB, 0xF3, 0xBF, 0xFB,
- 0xB4, 0x9F, 0x35, 0x64, 0x0A, 0x69, 0xB7, 0xD1,
- 0x3E, 0xCA, 0x78, 0x07, 0x04, 0x03, 0x79, 0xD4,
- 0xF3, 0xA8, 0xEC, 0x18, 0xDB, 0x03, 0x5E, 0x47,
- 0xD7, 0xD0, 0x56, 0x2C, 0x74, 0x94, 0x86, 0x04,
- 0x46, 0xB8, 0xD4, 0x35, 0x0A, 0x7B, 0xE6, 0x78,
- 0xC4, 0x43, 0x3C, 0x56, 0xCC, 0x37, 0x8B, 0xFD,
- 0xE8, 0xF4, 0x57, 0xEA, 0xAE, 0xCF, 0x36, 0x97,
- 0x12, 0xAC, 0x39, 0xCF, 0x7C, 0xEF, 0x22, 0x67,
- 0x01, 0xEC, 0xD8, 0x09, 0x49, 0x4E, 0xE3, 0x74,
- 0xDD, 0x39, 0xE1, 0x39, 0xD7, 0x0C, 0x5F, 0x1B,
- 0xCE, 0x69, 0xBC, 0x72, 0x44, 0x87, 0x64, 0x1C,
- 0x08, 0x05, 0x93, 0x69, 0x6D, 0x7F, 0x90, 0x0A,
- 0x2C, 0xCB, 0x8A, 0xBB, 0x7F, 0xE3, 0xE0, 0x80,
- 0x31, 0xD0, 0x0A, 0x3A, 0x95, 0xFF, 0xF7, 0xB4,
- 0x36, 0x38, 0x93, 0xE0, 0x0C, 0x11, 0x37, 0x12,
- 0x06, 0xF6, 0xAD, 0xE9, 0xB1, 0x7A, 0x00, 0xF5,
- 0xD2, 0x32, 0x6B, 0xD0, 0x27, 0xA5, 0x1B, 0x3D,
- 0xE8, 0xDB, 0xCC, 0xA9, 0x1F, 0x1F, 0xB1, 0x99,
- 0x3D, 0x7C, 0xB7, 0xCA, 0xDA, 0x27, 0x2C, 0x64,
- 0x1C, 0x49, 0xB6, 0x87, 0x44, 0x06, 0x94, 0x9D,
- 0xBC, 0x6B, 0x20, 0xA2, 0x68, 0x15, 0x1F, 0xE2,
- 0xF2, 0xAD, 0x6D, 0x23, 0x2E, 0x2B, 0x74, 0xE2,
- 0x5D, 0xE4, 0xB0, 0xC7, 0x84, 0xCB, 0x64, 0xBF,
- 0xE0, 0xA8, 0x18, 0x83, 0xB4, 0xC9, 0xD9, 0x73,
- 0xA8, 0xE6, 0xA9, 0x36, 0xD5, 0x63, 0x1E, 0x2C,
- 0x2A, 0x55, 0x09, 0x77, 0x5E, 0xB3, 0x4B, 0xEA,
- 0xB5, 0xD0, 0x14, 0x5F, 0xEB, 0x50, 0x7B, 0xAA,
- 0xEF, 0x94, 0xBA, 0x2B, 0xD7, 0x8A, 0x07, 0xF1,
- 0xF9, 0x5E, 0x12, 0x12, 0x21, 0x52, 0xE5, 0x0A,
- 0x3E, 0xC0, 0xBC, 0x5D, 0x4C, 0xE2, 0x12, 0x7C,
- 0x39, 0xF9, 0x16, 0x9D, 0xBD, 0x96, 0x83, 0x3B,
- 0x7F, 0x3D, 0x6A, 0xEC, 0xF1, 0x25, 0xD2, 0xB0,
- 0xB0, 0xEB, 0x20, 0x06, 0x07, 0xD6, 0xD9, 0x4C,
- 0x07, 0x9A, 0x82, 0xC1, 0xFC, 0xF7, 0x66, 0x15,
- 0xBD, 0x62, 0x65, 0xD8, 0x6C, 0xF6, 0x33, 0x7B,
- 0x5A, 0x28, 0xEC, 0x90, 0xA1, 0x26, 0x9F, 0xC3,
- 0x28, 0x4A, 0x64, 0x50, 0x5F, 0xCA, 0xE2, 0x6D,
- 0xB8, 0x0F, 0xE2, 0x94, 0xB5, 0x8E, 0x1F, 0x8A,
- 0x8F, 0x6B, 0xA6, 0x86, 0x1F, 0xEE, 0xDC, 0x24,
- 0xB4, 0xB8, 0x25, 0xEC, 0x28, 0x2D, 0xF9, 0xCB,
- 0x7D, 0x38, 0xFF, 0xC7, 0x74, 0x2E, 0xD3, 0x10,
- 0xEC, 0x03, 0x31, 0xEE, 0x83, 0xE7, 0xA4, 0xF7,
- 0xBA, 0x28, 0x21, 0xE0, 0x7F, 0xB4, 0xB7, 0xE1,
- 0x7A, 0xF9, 0x2B, 0xB0, 0x2C, 0x3B, 0x80, 0x5F,
- 0xE0, 0x5D, 0xB2, 0x7E, 0x59, 0xFF, 0x59, 0x07,
- 0x58, 0x42, 0x57, 0xEE, 0x44, 0xF1, 0xB1, 0xAD,
- 0xBA, 0xDE, 0xCB, 0x1D, 0x8A, 0x36, 0x67, 0xE8,
- 0x45, 0xFF, 0x07, 0x8D, 0xEE, 0xA4, 0x51, 0x9C,
- 0x4C, 0x83, 0x5D, 0x2E, 0x2F, 0xE1, 0x5B, 0x75,
- 0xE8, 0x29, 0xCD, 0x0B, 0x07, 0x62, 0xE0, 0xC3,
- 0x0D, 0x1D, 0xEA, 0xCF, 0xF0, 0x8A, 0x65, 0x27,
- 0x70, 0x42, 0x9F, 0x26, 0x00, 0x15, 0x70, 0xC5,
- 0x4A, 0xF6, 0x25, 0xD0, 0x40, 0x72, 0xE9, 0xC1,
- 0x73, 0xFD, 0x48, 0x94, 0xA3, 0x8D, 0x66, 0x63,
- 0x96, 0x4F, 0xF7, 0xEE, 0xFB, 0x4C, 0xC7, 0xB8,
- 0x6B, 0xE9, 0x90, 0xE1, 0x2A, 0x66, 0x80, 0x99,
- 0x3B, 0xB0, 0x1A, 0x6C, 0xF9, 0x0E, 0x72, 0xDA,
- 0x8E, 0x4F, 0x46, 0xC2, 0x6A, 0x4B, 0x7A, 0x16,
- 0xE5, 0x26, 0x0B, 0x5C, 0xD4, 0x47, 0x34, 0xE5,
- 0x37, 0xBE, 0x68, 0x6C, 0xDA, 0xD3, 0x9B, 0x6F,
- 0xAE, 0x51, 0x9C, 0x99, 0x0A, 0x5B, 0xF8, 0x37,
- 0xBC, 0xDE, 0xFC, 0x93, 0xC5, 0xE7, 0x0F, 0xEF,
- 0x0B, 0xA6, 0x07, 0xC2, 0xA6, 0xE6, 0xDA, 0x2D,
- 0x1B, 0x49, 0xC9, 0xDE, 0x6B, 0x27, 0xDC, 0x00,
- 0xEF, 0x23, 0x87, 0x0E, 0xEB, 0xD1, 0x48, 0x7D,
- 0xB4, 0xF2, 0x58, 0xC6, 0x3C, 0xE2, 0x89, 0xBA,
- 0xB0, 0x05, 0xAC, 0x94, 0x41, 0x9A, 0xA8, 0xFF,
- 0x3E, 0xBC, 0x3A, 0x52, 0x9C, 0xF9, 0x7F, 0x07,
- 0x8B, 0xB0, 0x2C, 0x71, 0x83, 0x7B, 0xCF, 0x2E,
- 0x7F, 0x7C, 0x96, 0x65, 0xD9, 0x08, 0x17, 0xEC,
- 0xFA, 0xDE, 0x4E, 0x40, 0x12, 0x26, 0x70, 0x71,
- 0x65, 0xA5, 0xDC, 0x98, 0x47, 0xA3, 0xFC, 0xE0,
- 0x9A, 0x16, 0xED, 0x45, 0x56, 0x72, 0x50, 0x05,
- 0x28, 0x2C, 0x99, 0xEC, 0x20, 0x2E, 0x40, 0xC0,
- 0x26, 0x69, 0xCD, 0x49, 0x45, 0x17, 0xA4, 0xA3,
- 0x42, 0x0D, 0x14, 0x65, 0x87, 0x33, 0x8C, 0x92,
- 0xC5, 0xC4, 0x61, 0xFD, 0xE8, 0x68, 0x56, 0x20,
- 0x57, 0xF5, 0x8E, 0x5F, 0xCF, 0x7E, 0x97, 0xF6,
- 0x49, 0x97, 0x0A, 0xFE, 0xD3, 0x60, 0x1A, 0x5B,
- 0x0C, 0x75, 0xDD, 0x8E, 0x31, 0x78, 0x29, 0xA6,
- 0xB1, 0x4D, 0xAA, 0xDF, 0x8A, 0xD1, 0xE6, 0x91,
- 0xE3, 0x32, 0x3F, 0xEC, 0x8A, 0x1F, 0x0E, 0x35,
- 0x07, 0x6E, 0x4B, 0x83, 0x3B, 0xE5, 0x67, 0x34,
- 0x1F, 0x0C, 0x81, 0xD8, 0xD5, 0x25, 0x68, 0xE5,
- 0x28, 0x1B, 0x5C, 0x81, 0x3E, 0xE3, 0x5C, 0xB4,
- 0xB6, 0xBD, 0x62, 0x6A, 0x70, 0x33, 0xC2, 0xC5,
- 0x75, 0x27, 0xF4, 0x30, 0xE1, 0x1D, 0xC1, 0x4C,
- 0xC5, 0x02, 0x12, 0x46, 0xAC, 0xEC, 0xF9, 0xE8,
- 0xE7, 0x58, 0x24, 0x11, 0xB1, 0xF3, 0xB7, 0x8C,
- 0x3C, 0xA4, 0x0A, 0x94, 0xA6, 0x7C, 0x68, 0x54,
- 0x5B, 0xB9, 0x4D, 0x57, 0x9C, 0xE7, 0x28, 0x09,
- 0x6B, 0x89, 0x26, 0x5D, 0xE7, 0x50, 0xA9, 0x95,
- 0x90, 0x91, 0x8E, 0x00, 0x59, 0xF8, 0x3A, 0x70,
- 0xAF, 0x48, 0x2E, 0xE8, 0xC4, 0x34, 0x8C, 0xF4,
- 0x5F, 0x7F, 0xCB, 0x07, 0xAA, 0xF0, 0xD9, 0xFB,
- 0x5C, 0x32, 0x90, 0x22, 0x1A, 0xD2, 0x1A, 0xCF,
- 0x92, 0x06, 0x02, 0xCF, 0x10, 0x18, 0x7B, 0x93,
- 0xCC, 0x07, 0x4A, 0x31, 0x25, 0x30, 0x23, 0x06,
- 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01,
- 0x09, 0x15, 0x31, 0x16, 0x04, 0x14, 0xD1, 0xDE,
- 0x23, 0x16, 0x9F, 0x6E, 0xF4, 0x42, 0x21, 0x23,
- 0xE1, 0x11, 0xAA, 0xC8, 0x7C, 0x60, 0x4A, 0x78,
- 0x9D, 0x24, 0x30, 0x31, 0x30, 0x21, 0x30, 0x09,
- 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05,
- 0x00, 0x04, 0x14, 0xD6, 0x4A, 0xBB, 0x75, 0xB1,
- 0xF9, 0x9E, 0xD3, 0x58, 0x6D, 0xD1, 0x74, 0x9F,
- 0x00, 0x8A, 0xF2, 0xC8, 0xAA, 0x52, 0x4D, 0x04,
- 0x08, 0x77, 0x46, 0xE7, 0xBA, 0x25, 0x4B, 0xDA,
- 0x41, 0x02, 0x02, 0x08, 0x00]
-};
-
-const WPA_EAP_CLIENT_LIST = [
- {
- ssid: 'WPA-EAP-TLS',
- keyManagement: 'WPA-EAP',
- eap: 'TLS',
- identity: EAP_USERNAME,
- serverCertificate: CLIENT_PKCS12_CERT.nickname,
- userCertificate: CLIENT_PKCS12_CERT.nickname
- }
-];
-
-/**
- * Convert the given MozWifiNetwork object array to testAssociate chain.
- *
- * @param aNetworks
- * An array of MozWifiNetwork which we want to convert.
- *
- * @return A promise chain which "then"s testAssociate accordingly.
- */
-function convertToTestAssociateChain(aNetworks) {
- let chain = Promise.resolve();
-
- aNetworks.forEach(function (aNetwork) {
- network = new window.MozWifiNetwork(aNetwork);
- chain = chain.then(() => gTestSuite.testAssociate(network));
- });
-
- return chain;
-}
-
-gTestSuite.doTestWithCertificate(
- new Blob([new Uint8Array(CLIENT_PKCS12_CERT.content)]),
- CLIENT_PKCS12_CERT.password,
- CLIENT_PKCS12_CERT.nickname,
- CLIENT_PKCS12_CERT.usage,
- function() {
- return gTestSuite.ensureWifiEnabled(true)
- // Load required server files.
- .then(() => gTestSuite.writeFile(SERVER_EAP_USER_CONF.path, SERVER_EAP_USER_CONF.content))
- .then(() => gTestSuite.writeFile(CA_CERT.path, CA_CERT.content))
- .then(() => gTestSuite.writeFile(SERVER_CERT.path, SERVER_CERT.content))
- .then(() => gTestSuite.writeFile(SERVER_KEY.path, SERVER_KEY.content))
- // Start AP.
- .then(() => gTestSuite.startHostapds(WPA_EAP_AP_LIST))
- // Scan test.
- .then(() => gTestSuite.testWifiScanWithRetry(SCAN_RETRY_CNT, WPA_EAP_AP_LIST))
- // Associate test.
- .then(() => convertToTestAssociateChain(WPA_EAP_CLIENT_LIST))
- // Tear down.
- .then(gTestSuite.killAllHostapd)
-});
diff --git a/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_TTLS.js b/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_TTLS.js
deleted file mode 100644
index 06e052909..000000000
--- a/dom/wifi/test/marionette/test_wifi_associate_WPA_EAP_TTLS.js
+++ /dev/null
@@ -1,623 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SCAN_RETRY_CNT = 5;
-
-const EAP_USERNAME = 'username';
-const EAP_PASSWORD = 'password';
-
-const SERVER_EAP_USER_CONF = {
- path: HOSTAPD_CONFIG_PATH + 'hostapd.eap_user',
- content: '* PEAP,TTLS,TLS\n' +
- '"' + EAP_USERNAME + '" MSCHAPV2,TTLS-MSCHAPV2 "' + EAP_PASSWORD + '" [2]\n'
-};
-const CA_CERT = {
- path: HOSTAPD_CONFIG_PATH + 'ca.pem',
- content: '-----BEGIN CERTIFICATE-----\n' +
- 'MIIDsTCCApmgAwIBAgIJAKxTf+8X8qngMA0GCSqGSIb3DQEBCwUAMG4xCzAJBgNV\n' +
- 'BAYTAlRXMRMwEQYDVQQIDApTb21lLVN0YXRlMREwDwYDVQQKDAhjaHVja2xlZTER\n' +
- 'MA8GA1UEAwwIY2h1Y2tsZWUxJDAiBgkqhkiG9w0BCQEWFWNodWNrbGkwNzA2QGdt\n' +
- 'YWlsLmNvbTAgFw0xNDEyMjQxMTI4NTBaGA8yMjg4MTAwNzExMjg1MFowbjELMAkG\n' +
- 'A1UEBhMCVFcxEzARBgNVBAgMClNvbWUtU3RhdGUxETAPBgNVBAoMCGNodWNrbGVl\n' +
- 'MREwDwYDVQQDDAhjaHVja2xlZTEkMCIGCSqGSIb3DQEJARYVY2h1Y2tsaTA3MDZA\n' +
- 'Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo3c2yFxY\n' +
- 'o6gGg0I83jy00ME+MAfzCd+4ShL45ZLqysQP93jRBfPzU9ZuZ29ysVwgWIdqkZao\n' +
- 'XTuV/NAW2GMGd8W1jQJ3J81fjb9wvhlny3rrACwvUn1N1S1BnM+BAAiDLGxEmvAQ\n' +
- 'onp2aaa6HsHsYS8ONX+d2Qh4LEA4vupeSGAqJychCZv/l+aq/ErFZhFYB3CPUQEt\n' +
- 'cClO24ucsIYP95lA0zhscnmAj06qplFD4Bv6IVrdDqujy1zNwCQwsJq/8OQdaTN/\n' +
- 'h3y9pWvNKMBMM2niOUAjtuNpqsSK/lTS1WAT3PdtVECX9fYBi0Bg+HM92xs/6gt6\n' +
- 'kh9jPV8keXHvSwIDAQABo1AwTjAdBgNVHQ4EFgQU7hBqhuG04xeCzrQ3ngx18ZJ3\n' +
- 'lUswHwYDVR0jBBgwFoAU7hBqhuG04xeCzrQ3ngx18ZJ3lUswDAYDVR0TBAUwAwEB\n' +
- '/zANBgkqhkiG9w0BAQsFAAOCAQEAFYX2iy680GAnBTttk0gyX6gk+8pYr3D22k/G\n' +
- '6rvcjefzS7ELQPRKr6mfmwXq3mMf/4jiS2zI5zmXsestPYzHYxf2viQ6t7vr9XiJ\n' +
- '3WfFjNw4ERlRisAvg0aqqTNNQq5v2VME4sdFZagy217f73C7azwCHl0bqOLH05rl\n' +
- '8RubOxiHEj7ZybJqnRciK/bht4D+rZkwf4bBBmoloqH7xT0+rFQclpYXDGGjNUQB\n' +
- 'LcHLF10xcr7g3ZVVu82fe6+d85gIGOIMR9+TKhdw6gO3CNcnDAj6gxksghgtcxmh\n' +
- 'OzOggCn7nlIwImtsg2sZkpWB4lEi9hdv4lkNuyFjOL3bnuc+NA==\n' +
- '-----END CERTIFICATE-----\n'
-};
-
-const SERVER_CERT = {
- path: HOSTAPD_CONFIG_PATH + 'server.pem',
- content: '-----BEGIN CERTIFICATE-----\n' +
- 'MIID1DCCArygAwIBAgIBADANBgkqhkiG9w0BAQsFADBuMQswCQYDVQQGEwJUVzET\n' +
- 'MBEGA1UECAwKU29tZS1TdGF0ZTERMA8GA1UECgwIY2h1Y2tsZWUxETAPBgNVBAMM\n' +
- 'CGNodWNrbGVlMSQwIgYJKoZIhvcNAQkBFhVjaHVja2xpMDcwNkBnbWFpbC5jb20w\n' +
- 'IBcNMTQxMjI0MTEyOTQ5WhgPMjI4ODEwMDcxMTI5NDlaMG4xCzAJBgNVBAYTAlRX\n' +
- 'MRMwEQYDVQQIDApTb21lLVN0YXRlMREwDwYDVQQKDAhjaHVja2xlZTERMA8GA1UE\n' +
- 'AwwIY2h1Y2tsZWUxJDAiBgkqhkiG9w0BCQEWFWNodWNrbGkwNzA2QGdtYWlsLmNv\n' +
- 'bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMdhQmKilTJbWZRxTiSV\n' +
- 'rqIU+LYW1RKghx5o+0JpNRJVLuz5kBMaNskbbfUSNuHbEq0QA9BDKAZWIc4LSotk\n' +
- 'lCo8TbcO9CJvJPQGGjGdHcohWX5vy6BE/OVE46CUteMFyZF6F8R2fNUww08iR/u1\n' +
- 'YZebL5pWO1j43sPpAzEy6Tij2ACPt6EZcFaZG3SF2mVJWkCQnBqrojP65WUvZQqp\n' +
- 'seUhW2YAS8Nu0Yrohgxz6VYk+cNDuDZVGs6qWRStZzJfYrfc76DtkHof5B14M+xp\n' +
- 'XJaBLxN+whvnYkDTfinaCxnW1O7eXUltr87fLc5zmeBkgwaiaQuIdcfZm7vDUiz8\n' +
- 'vnUCAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgBhvhCAQ0EHxYdT3BlblNTTCBH\n' +
- 'ZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFKK4f9/YavTHOfEiAB83Deac\n' +
- '6gT5MB8GA1UdIwQYMBaAFO4QaobhtOMXgs60N54MdfGSd5VLMA0GCSqGSIb3DQEB\n' +
- 'CwUAA4IBAQBWnO9o9KSJIqjoz5Nwll63ULOdcvgGdOeJIw1fcKQ817Rsp+TVcjcH\n' +
- 'IrIADsT/QZGXRO/l6p1750e2iFtJEo1hsRaxtA1wWn2I9HO3+av2spQhr3jpYGPf\n' +
- 'zpsMTp4RNYV7Q8+q1kZIz9PY4V1T0p6lveK8+fUj2hSLnxSj0QiGSJJtnEC3w4Rv\n' +
- 'C9T6oUwIeToULmi+8FXQFdEqwKRU98DPq3eLzN28ZxUgoPE1C8+42D2UW8uyp/Gm\n' +
- 'tGOa/k7nzkCdVqZI7lX7f0AjEvQgjtAMQ/k7Mhxx7TzW2HO+1YPMoKji6Z4WkNwt\n' +
- 'JEj9ZUBSNt8B26UksJMBDkcvSegF3a7o\n' +
- '-----END CERTIFICATE-----\n'
-};
-
-const SERVER_KEY = {
- path: HOSTAPD_CONFIG_PATH + 'server.key',
- content: '-----BEGIN RSA PRIVATE KEY-----\n' +
- 'MIIEpAIBAAKCAQEAx2FCYqKVMltZlHFOJJWuohT4thbVEqCHHmj7Qmk1ElUu7PmQ\n' +
- 'Exo2yRtt9RI24dsSrRAD0EMoBlYhzgtKi2SUKjxNtw70Im8k9AYaMZ0dyiFZfm/L\n' +
- 'oET85UTjoJS14wXJkXoXxHZ81TDDTyJH+7Vhl5svmlY7WPjew+kDMTLpOKPYAI+3\n' +
- 'oRlwVpkbdIXaZUlaQJCcGquiM/rlZS9lCqmx5SFbZgBLw27RiuiGDHPpViT5w0O4\n' +
- 'NlUazqpZFK1nMl9it9zvoO2Qeh/kHXgz7GlcloEvE37CG+diQNN+KdoLGdbU7t5d\n' +
- 'SW2vzt8tznOZ4GSDBqJpC4h1x9mbu8NSLPy+dQIDAQABAoIBAASG4Mr8hgaurEoC\n' +
- 'iJOsElr7vunjetMBcg/uskW/vcS8ymP3Bp5oafYG+WgnEbfvEW18f5mq7K24JuxW\n' +
- 'tUqU7ghHdjxByqk9fMlNmiqmNpbwSufkAeuRpWxPNBvhRH/zEbCL5R5A0nTEtqqF\n' +
- 'TL0aUSzwCRSoAJD0lZo9ICVt0n3GsDyM9rqQg/uZmh1qsRdwPsRuYORND9g48rKq\n' +
- '6WN9leskSxhhsYE2D9ocOFd9bNt8Zxejh9ppVSnG/KsIdt18iBzcabatgAQ046fb\n' +
- 'Z3vprcZJLg93Sg2gSuVqlSTs3M2W8VQnm22/EBMb1y0M48MSRCgnbPLG/CcCLLfF\n' +
- 'LwxCOgECgYEA/eYt67xyJ6JeAdxdwOZuT1WWGbFpLiG9+2OgiHumyRQ5969XMTWo\n' +
- 'fIhMKchDdjoy9RR236\/\/EFCs7UEyB7+a7ODRzNiK2zCD8Smjp+21fUPSthEeQesk\n' +
- 'eiMYICIu5Ay35x9sxIX+XOUVvRhPOGcD29GVeRnKh1inTHOz2dje8LkCgYEAyQeY\n' +
- 'STi9jjCEcHkM1E/UeDiLfHHepLXi8wS41JNRHl5Jacp7XB5djAjKu/jf367/VpFy\n' +
- 'GDDMetE7n8eWkrnAvovxOwZ000YDMtL1sUYSjL+XtBS5s6VY1p4qaSAY9nUUGrJh\n' +
- 'JvtvsuI7SKTtL+60vjBOH7zDnvOdBgAp0utLhZ0CgYEAuLzzqrPKB8afShFSchn4\n' +
- 'J2dpuLYahsNsXW7HDqeR2nsKFosRETAusLXnXPtnAq4kB6jlOarwFqnsuRCX24Vx\n' +
- 'r2uBm9/vYL7zMdUPTA+s30ErHuhjsKjsOKYyVqcooSwT32pBFNk+E89nutfmRG7I\n' +
- 'IvhjHuNCNqqtx/Xj5d1jkZkCgYBQicppC2Jl5OoqZVTOem0U/RJk+PnJ41TZJ7sk\n' +
- '7yBAmmWvDH\/\/l+rCf4M5a6vFYcbKV9rt9h711X2dtciNX/3oWQh8LUoAmrwNUJc+\n' +
- 'PmSQHvIYI3WCk2vUD+nN1B4sHxu+1lg11eYaNKiroeeknG2tBI1ICcgVlmQCU25u\n' +
- 'IfZPwQKBgQCdO6QHhPLtcHUDNFA6FQ1jKL1iEd7G0JLVRz4Xkpkn1Vrr5MD6JFDa\n' +
- '5ccabADyl0lpFqDIVJQIzLku2hOD2i9aBNCY0pL391HeOS7CkZX+TdOY1tquoBq5\n' +
- 'MnmixZjDCVd2VcrVyTA6ntOBoharKFW0rH1PqU+qu7dZF7CBPbAdEw==\n' +
- '-----END RSA PRIVATE KEY-----\n'
-};
-
-const WPA_EAP_AP_LIST = [
- {
- ssid: 'WPA-EAP-TTLS',
- ieee8021x: 1,
- eapol_version: 1,
- eap_server: 1,
- eapol_key_index_workaround: 0,
- eap_user_file: SERVER_EAP_USER_CONF.path,
- ca_cert: CA_CERT.path,
- server_cert: SERVER_CERT.path,
- private_key: SERVER_KEY.path,
- wpa: 3,
- wpa_key_mgmt: 'WPA-EAP'
- }
-];
-
-const CLIENT_PKCS12_CERT = {
- nickname: 'client',
- password: 'password',
- usage: ['UserCert', 'ServerCert'],
- content: [0x30, 0x82, 0x0E, 0x01, 0x02, 0x01, 0x03, 0x30,
- 0x82, 0x0D, 0xC7, 0x06, 0x09, 0x2A, 0x86, 0x48,
- 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x82,
- 0x0D, 0xB8, 0x04, 0x82, 0x0D, 0xB4, 0x30, 0x82,
- 0x0D, 0xB0, 0x30, 0x82, 0x08, 0x67, 0x06, 0x09,
- 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07,
- 0x06, 0xA0, 0x82, 0x08, 0x58, 0x30, 0x82, 0x08,
- 0x54, 0x02, 0x01, 0x00, 0x30, 0x82, 0x08, 0x4D,
- 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D,
- 0x01, 0x07, 0x01, 0x30, 0x1C, 0x06, 0x0A, 0x2A,
- 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01,
- 0x06, 0x30, 0x0E, 0x04, 0x08, 0x67, 0x7A, 0xF3,
- 0x61, 0xBE, 0xE0, 0x51, 0xC1, 0x02, 0x02, 0x08,
- 0x00, 0x80, 0x82, 0x08, 0x20, 0xFC, 0x6A, 0x79,
- 0xA1, 0x6C, 0xAF, 0xBE, 0xEE, 0x62, 0x45, 0x33,
- 0xB8, 0x48, 0xE1, 0x68, 0xA1, 0x15, 0x11, 0x4B,
- 0x95, 0xCB, 0x77, 0xC0, 0x5D, 0xA2, 0xCB, 0xDB,
- 0xD1, 0x83, 0x74, 0x60, 0xD7, 0xEC, 0x42, 0xA6,
- 0x3A, 0x23, 0xF7, 0x85, 0xEB, 0xC1, 0xFE, 0x6A,
- 0x57, 0x8E, 0xC1, 0x44, 0xF3, 0x1F, 0xFE, 0xB8,
- 0x2D, 0x8C, 0x4D, 0xC9, 0x5B, 0xAE, 0x21, 0x2E,
- 0x4C, 0x1A, 0xEB, 0x84, 0x09, 0xF3, 0x40, 0x92,
- 0x39, 0x7F, 0x56, 0x02, 0x46, 0x61, 0x16, 0xDE,
- 0x5C, 0x48, 0xB6, 0x0C, 0x1D, 0xD3, 0x5F, 0x10,
- 0x9A, 0x39, 0xB8, 0x66, 0x31, 0xFC, 0x39, 0x71,
- 0x87, 0x23, 0x46, 0x9D, 0xE8, 0x3C, 0x2B, 0xA1,
- 0x39, 0x8A, 0xD3, 0xFF, 0xD9, 0x43, 0xB6, 0x61,
- 0xC6, 0x67, 0x70, 0x40, 0xBD, 0xFE, 0xD3, 0xC1,
- 0x68, 0xF5, 0xF7, 0xC8, 0x89, 0xD8, 0x17, 0xC5,
- 0xE8, 0x3D, 0x29, 0xD5, 0x91, 0xDF, 0x1F, 0x56,
- 0x74, 0x5A, 0xC4, 0xA8, 0x14, 0xBA, 0xD4, 0xFA,
- 0x13, 0x49, 0x2A, 0x9F, 0x63, 0xF1, 0xB2, 0x45,
- 0xF1, 0xF0, 0x2A, 0xDD, 0x75, 0x66, 0x8A, 0xF7,
- 0xAB, 0x73, 0x86, 0x26, 0x9D, 0x1F, 0x07, 0xAD,
- 0xD3, 0xFE, 0xE0, 0xA3, 0xED, 0xA0, 0x96, 0x3E,
- 0x1E, 0x89, 0x86, 0x02, 0x4C, 0x28, 0xFD, 0x57,
- 0xA1, 0x67, 0x55, 0xF0, 0x82, 0x3B, 0x7F, 0xCC,
- 0x2A, 0x32, 0x01, 0x93, 0x1D, 0x8B, 0x66, 0x8A,
- 0x20, 0x52, 0x84, 0xDD, 0x2C, 0xFD, 0xEE, 0x72,
- 0xF3, 0x8C, 0x58, 0xB9, 0x99, 0xE5, 0xC1, 0x22,
- 0x63, 0x59, 0x00, 0xE2, 0x76, 0xC5, 0x3A, 0x17,
- 0x7F, 0x93, 0xE9, 0x67, 0x61, 0xAA, 0x10, 0xC3,
- 0xD9, 0xC8, 0x24, 0x46, 0x5B, 0xBE, 0x8C, 0x1F,
- 0x2D, 0x66, 0x48, 0xD2, 0x02, 0x11, 0xFB, 0x74,
- 0x14, 0x76, 0x76, 0x5A, 0x98, 0x54, 0x35, 0xA7,
- 0x85, 0x66, 0x20, 0x26, 0x8B, 0x13, 0x6F, 0x68,
- 0xE3, 0xC9, 0x58, 0x7D, 0x1C, 0x3E, 0x01, 0x8D,
- 0xF8, 0xD6, 0x7F, 0xCF, 0xA2, 0x07, 0xB7, 0x95,
- 0xFD, 0xF0, 0x02, 0x34, 0x32, 0x30, 0xE8, 0xD4,
- 0x57, 0x5E, 0x53, 0xFB, 0x54, 0xE2, 0x03, 0x32,
- 0xCC, 0x52, 0x2E, 0xD2, 0x35, 0xD9, 0x58, 0x85,
- 0x2D, 0xEC, 0x2D, 0x71, 0xD1, 0x8A, 0x29, 0xD0,
- 0xB0, 0x24, 0xBD, 0x24, 0xDC, 0x1A, 0x28, 0x3F,
- 0xA0, 0x12, 0x81, 0x15, 0x24, 0xC9, 0xB5, 0x4A,
- 0x23, 0xB6, 0xA3, 0x45, 0x50, 0x2D, 0x73, 0x99,
- 0x6B, 0x1C, 0xFB, 0xA4, 0x53, 0xD7, 0x5C, 0xF4,
- 0x6C, 0xB0, 0xE5, 0x74, 0xB3, 0x76, 0xF8, 0xB1,
- 0x0D, 0x59, 0x70, 0x9F, 0xCA, 0xDE, 0xF2, 0xAA,
- 0x4C, 0x7D, 0x11, 0x54, 0xC4, 0x19, 0x0F, 0x36,
- 0x4A, 0x62, 0xFF, 0x8B, 0x10, 0xCB, 0x93, 0x50,
- 0xDA, 0x79, 0x5E, 0x4E, 0x09, 0x1F, 0x22, 0xC8,
- 0x19, 0x85, 0xE9, 0xEE, 0xB7, 0x71, 0x65, 0xB9,
- 0x10, 0xD2, 0x0A, 0x73, 0x5B, 0xA6, 0xDA, 0x37,
- 0x46, 0x02, 0x00, 0x98, 0x9E, 0x20, 0x6C, 0x7D,
- 0xC7, 0x69, 0xBB, 0xC2, 0x00, 0x40, 0x9C, 0x57,
- 0x00, 0xC2, 0x36, 0x76, 0xE8, 0x2A, 0x8D, 0xAD,
- 0x62, 0x57, 0xC8, 0xD0, 0x9D, 0x66, 0x27, 0x5A,
- 0xD8, 0x0D, 0x35, 0x60, 0x28, 0x38, 0x62, 0x94,
- 0x78, 0x36, 0x25, 0x58, 0xFD, 0xF8, 0x66, 0x1F,
- 0x68, 0x04, 0x0F, 0xD8, 0x00, 0xDF, 0xA0, 0x6C,
- 0x25, 0x42, 0x9A, 0x4C, 0xEB, 0x80, 0x13, 0x51,
- 0x7D, 0x2D, 0xA8, 0x89, 0xD6, 0x1B, 0x67, 0x72,
- 0x01, 0xF3, 0x2D, 0x16, 0x77, 0xFE, 0x22, 0xBC,
- 0x8A, 0x45, 0x09, 0x1F, 0x9C, 0x2F, 0x2A, 0xA9,
- 0x61, 0x5B, 0x4A, 0xE6, 0x64, 0x2C, 0x62, 0x1A,
- 0x3A, 0x96, 0xE6, 0x0A, 0xAE, 0x05, 0x1A, 0xC8,
- 0xCB, 0xD6, 0x8F, 0x3A, 0x4B, 0xE0, 0x7F, 0x82,
- 0xB4, 0x98, 0xF1, 0x9D, 0xD7, 0x14, 0x76, 0x5E,
- 0x77, 0x85, 0x87, 0xEC, 0x13, 0xDA, 0xFD, 0xAF,
- 0xCB, 0xA3, 0x1C, 0x99, 0xC1, 0xFE, 0x17, 0x0C,
- 0x40, 0x4D, 0x3C, 0x8F, 0x70, 0x86, 0x63, 0x64,
- 0xB7, 0x75, 0xA8, 0x71, 0x36, 0xDC, 0x54, 0x10,
- 0x57, 0x0C, 0xA8, 0xF2, 0xA1, 0xBB, 0xED, 0x03,
- 0x41, 0x57, 0x34, 0x2C, 0x8F, 0x7C, 0xA0, 0x09,
- 0xF3, 0x9E, 0x41, 0xB7, 0xA8, 0xD4, 0x66, 0x0D,
- 0x0D, 0xC0, 0x6A, 0xFC, 0x6A, 0xA2, 0xAC, 0xE2,
- 0x60, 0x00, 0xE3, 0xF7, 0x75, 0x43, 0x23, 0xEB,
- 0xC8, 0x61, 0xFA, 0xB3, 0xB8, 0x28, 0xCE, 0xCA,
- 0xF4, 0x47, 0x7F, 0x30, 0x6D, 0x61, 0x89, 0x47,
- 0xA1, 0x4A, 0xFE, 0xD1, 0x21, 0x0B, 0x6D, 0xF4,
- 0x3F, 0x00, 0x86, 0x30, 0x8E, 0x33, 0x21, 0x6F,
- 0xDA, 0x15, 0xFD, 0x5F, 0xEC, 0x8E, 0xF1, 0x12,
- 0x3F, 0xC9, 0x83, 0x0C, 0xCA, 0x22, 0x01, 0xF1,
- 0x70, 0x5F, 0x1F, 0x66, 0xB5, 0xF8, 0x3E, 0x7A,
- 0x6F, 0xDE, 0xDB, 0xA7, 0x8D, 0x18, 0x9E, 0xBE,
- 0xDB, 0xAD, 0x3D, 0x66, 0x30, 0xC1, 0x6C, 0x0C,
- 0x87, 0xB4, 0x65, 0x75, 0xE0, 0x9D, 0xEA, 0x16,
- 0x0D, 0x07, 0x37, 0x33, 0xC5, 0xEC, 0x97, 0x93,
- 0x37, 0xEB, 0x8E, 0x65, 0x9C, 0x40, 0x63, 0x6C,
- 0x43, 0x60, 0xB0, 0x40, 0x4D, 0x85, 0xEF, 0xC2,
- 0x47, 0x5F, 0xE7, 0x6B, 0xCB, 0x40, 0xE8, 0xEA,
- 0xD8, 0xAB, 0xB1, 0x9A, 0x72, 0xDC, 0x4C, 0x14,
- 0xFA, 0x43, 0x61, 0x5F, 0xA6, 0x5C, 0x3A, 0x05,
- 0x17, 0x2E, 0x74, 0xF3, 0x5E, 0x45, 0xD9, 0x47,
- 0xAA, 0x59, 0xB6, 0x8F, 0x42, 0x66, 0x42, 0x29,
- 0x90, 0x95, 0x48, 0x46, 0x91, 0x88, 0x3C, 0x8C,
- 0xDE, 0xCC, 0xED, 0xB3, 0xAA, 0x62, 0xEA, 0xBC,
- 0xB4, 0x0C, 0x48, 0x4C, 0x53, 0x23, 0x5E, 0x24,
- 0x85, 0xBF, 0x92, 0xDA, 0x14, 0xDB, 0x1A, 0x3D,
- 0xEF, 0x30, 0xD9, 0x49, 0x64, 0x4D, 0xE5, 0x01,
- 0xFC, 0xA4, 0x4B, 0xD1, 0x9F, 0xDE, 0x96, 0x7F,
- 0x50, 0xBC, 0x4D, 0x38, 0x44, 0xE9, 0x23, 0x5F,
- 0x37, 0x57, 0x1A, 0xA6, 0x52, 0x5A, 0x0F, 0x4F,
- 0x87, 0x33, 0x4A, 0x7B, 0x66, 0xEE, 0x3D, 0x66,
- 0x0A, 0x63, 0x39, 0x1F, 0x23, 0x38, 0x35, 0x73,
- 0x60, 0x5E, 0x47, 0x20, 0x4F, 0xC0, 0xC8, 0x3C,
- 0x09, 0xF9, 0x29, 0x4F, 0x5E, 0x55, 0x69, 0xC4,
- 0x6B, 0xE8, 0xF8, 0x91, 0xC0, 0x22, 0x65, 0x15,
- 0x1E, 0xFB, 0xB9, 0x61, 0xCE, 0x45, 0xBE, 0x2B,
- 0xEE, 0xB9, 0x04, 0x2B, 0xFD, 0xAE, 0x61, 0x1C,
- 0x3D, 0x3D, 0x7C, 0xBF, 0xC1, 0xF7, 0x3C, 0x4E,
- 0x9E, 0x0E, 0x54, 0xC8, 0xAD, 0xA9, 0xDF, 0x43,
- 0x49, 0xB9, 0x41, 0x05, 0xE5, 0xF1, 0x49, 0xAA,
- 0x77, 0x6C, 0x34, 0x5B, 0x93, 0x24, 0x24, 0x23,
- 0x74, 0x68, 0x11, 0xCE, 0x15, 0x80, 0xA1, 0xA4,
- 0x1F, 0x8D, 0x81, 0xCD, 0xB2, 0x98, 0xCA, 0x14,
- 0x0B, 0x0C, 0x61, 0x50, 0x69, 0x72, 0xAE, 0xFA,
- 0x8B, 0xC0, 0x3F, 0x0D, 0xE7, 0xF2, 0x0F, 0xEB,
- 0xC1, 0x11, 0xB9, 0x10, 0x03, 0x6A, 0xF5, 0x97,
- 0x3C, 0x53, 0x2F, 0x67, 0x86, 0x09, 0x6A, 0xE3,
- 0x28, 0xC0, 0x78, 0xC8, 0xB4, 0x39, 0x8E, 0xD1,
- 0xCE, 0x25, 0xE8, 0x66, 0xF7, 0x09, 0x40, 0x7D,
- 0x81, 0xFB, 0xAF, 0xFA, 0x59, 0xC4, 0x9B, 0x2B,
- 0x83, 0x45, 0x5B, 0xA8, 0x66, 0x9E, 0x38, 0xC8,
- 0xFD, 0xAC, 0xF2, 0x2D, 0x21, 0xDE, 0x50, 0x4C,
- 0x03, 0xCB, 0x88, 0x42, 0xDD, 0x84, 0x09, 0x99,
- 0x8E, 0x8B, 0x40, 0x97, 0x1B, 0x14, 0x85, 0x37,
- 0x11, 0x01, 0xE0, 0x74, 0x6B, 0x33, 0x52, 0x8C,
- 0x68, 0x3A, 0x89, 0xB2, 0xAF, 0x35, 0xE6, 0x65,
- 0xC3, 0x58, 0x70, 0xD2, 0xE7, 0x1F, 0x1F, 0xF6,
- 0xE5, 0x0A, 0xB1, 0xFE, 0xD0, 0xC9, 0x51, 0x50,
- 0xE7, 0xFD, 0x58, 0xF5, 0xC4, 0x58, 0x65, 0x94,
- 0xD1, 0x57, 0x55, 0x5E, 0xD2, 0x27, 0x98, 0xAF,
- 0xE7, 0x55, 0x0B, 0x87, 0x50, 0x9B, 0xEF, 0xE8,
- 0x2B, 0xFC, 0xE7, 0x3B, 0x4E, 0xD7, 0xB7, 0x4D,
- 0xF4, 0xBC, 0xF4, 0x88, 0x63, 0xE4, 0x8A, 0x20,
- 0x4B, 0x22, 0xB0, 0xA0, 0x53, 0x7F, 0xA8, 0xC9,
- 0x0C, 0xF8, 0xD7, 0xBD, 0x46, 0x39, 0xA7, 0x7D,
- 0xDD, 0x10, 0x91, 0x50, 0x54, 0x06, 0x47, 0xF0,
- 0x3C, 0xAA, 0x43, 0x40, 0xF8, 0x54, 0xDD, 0x8A,
- 0xEA, 0x8A, 0x0B, 0xA5, 0x7F, 0xCD, 0x5E, 0xAA,
- 0x02, 0x2E, 0x1F, 0xC6, 0x50, 0x15, 0xF8, 0x0A,
- 0x0C, 0x1B, 0x3C, 0x55, 0x3A, 0xC3, 0x6F, 0x88,
- 0xD7, 0xBF, 0xB1, 0x02, 0xCC, 0xE0, 0x08, 0x29,
- 0x97, 0xD2, 0xAA, 0x23, 0xC4, 0x6D, 0xE3, 0xE3,
- 0x76, 0x39, 0x92, 0xC3, 0x2E, 0x7A, 0xE2, 0x98,
- 0xD1, 0xFC, 0xAE, 0xCC, 0x95, 0xD8, 0xB4, 0xDC,
- 0x92, 0xEA, 0x6A, 0x5F, 0xF2, 0x92, 0x17, 0x0B,
- 0x8D, 0xC3, 0xFA, 0x9C, 0x62, 0xCE, 0x44, 0x8D,
- 0xC3, 0x1E, 0xC3, 0xB2, 0xD5, 0x00, 0xCD, 0xB4,
- 0x9E, 0x2D, 0x7B, 0xF2, 0x98, 0xA3, 0x00, 0x8B,
- 0x81, 0x30, 0x77, 0x5B, 0x02, 0x99, 0xB1, 0xCD,
- 0xC3, 0x1D, 0x74, 0x74, 0xEF, 0x41, 0xCB, 0x69,
- 0x63, 0x8E, 0xA6, 0xD3, 0x2D, 0x3E, 0x1F, 0x1D,
- 0x12, 0x9E, 0xD9, 0x18, 0x67, 0x06, 0xAF, 0x37,
- 0x29, 0xAD, 0x65, 0xD8, 0xEB, 0x71, 0xC4, 0x7D,
- 0x94, 0x3D, 0xEA, 0xCC, 0xDF, 0x72, 0x41, 0x51,
- 0x3C, 0xA1, 0x66, 0x98, 0x32, 0x32, 0x40, 0x54,
- 0xB0, 0x2F, 0xEB, 0xCE, 0xDF, 0x4A, 0x64, 0xFB,
- 0x9A, 0x90, 0xDC, 0xF6, 0x6F, 0xA9, 0xD4, 0xCA,
- 0xCB, 0x91, 0xC4, 0xFE, 0xEE, 0x9C, 0x01, 0x50,
- 0x2E, 0xAC, 0xCC, 0x5F, 0x89, 0xD0, 0x91, 0xA3,
- 0xD9, 0xF9, 0x4B, 0x8D, 0xDE, 0x6C, 0x60, 0x21,
- 0x19, 0xB1, 0xD3, 0x4D, 0x75, 0x56, 0x6F, 0xB8,
- 0x25, 0xA4, 0x92, 0x4F, 0x12, 0xF5, 0x8F, 0xC1,
- 0x17, 0x4B, 0xB3, 0x34, 0x21, 0x22, 0xAC, 0x52,
- 0xD2, 0x64, 0xC9, 0x9A, 0x7D, 0xFC, 0xC0, 0x0A,
- 0x89, 0x34, 0xFF, 0x08, 0xD3, 0x04, 0xDC, 0xFE,
- 0x7C, 0xB3, 0xB8, 0xFD, 0x85, 0xDD, 0x79, 0x51,
- 0xA7, 0x89, 0xE8, 0xF1, 0x23, 0xB1, 0xDF, 0xD7,
- 0x1F, 0x7B, 0xB1, 0x5D, 0x42, 0xF9, 0x61, 0xF8,
- 0xDC, 0x81, 0x04, 0xF1, 0xCC, 0xFA, 0xD7, 0xED,
- 0xBF, 0x47, 0xAC, 0xBD, 0xE5, 0xFA, 0xAC, 0xB3,
- 0x1C, 0xD9, 0xA1, 0xB3, 0x60, 0xEE, 0x9C, 0x8A,
- 0x36, 0x57, 0xB4, 0x2F, 0xA1, 0xA2, 0xF3, 0xE2,
- 0x09, 0x9A, 0x6E, 0x43, 0x9B, 0xE5, 0x93, 0xB8,
- 0x3D, 0x9E, 0x9F, 0xC1, 0xC6, 0x0D, 0x02, 0xEB,
- 0x4D, 0x38, 0xE9, 0xB4, 0x9F, 0xEA, 0x33, 0x8C,
- 0x07, 0xD8, 0xB4, 0x71, 0xAD, 0xE5, 0x43, 0xB2,
- 0xCC, 0x55, 0x93, 0x6A, 0xDB, 0x1E, 0x80, 0xDB,
- 0xC2, 0xEA, 0x42, 0x8E, 0xFC, 0x86, 0x44, 0xC9,
- 0x8A, 0xC4, 0xF2, 0x46, 0xA7, 0x39, 0x50, 0x0D,
- 0x1A, 0xAA, 0x07, 0x04, 0xBE, 0xD4, 0xCE, 0x62,
- 0x4D, 0x0F, 0x91, 0x7D, 0x29, 0x88, 0x9C, 0x4C,
- 0xAF, 0xF7, 0xD8, 0x40, 0x93, 0x88, 0xC7, 0x20,
- 0xD2, 0x17, 0x2A, 0xC4, 0x92, 0x72, 0xD0, 0xC0,
- 0x4E, 0x56, 0x47, 0xB1, 0x27, 0x02, 0xE6, 0x61,
- 0x82, 0x5E, 0xC8, 0x2E, 0x90, 0xD2, 0x31, 0x22,
- 0xE2, 0xA9, 0x4A, 0x91, 0x45, 0x69, 0xB1, 0xA5,
- 0x0F, 0x66, 0x2C, 0x30, 0xAD, 0x7F, 0x1B, 0x0E,
- 0x22, 0x17, 0x60, 0x2E, 0x3D, 0x7F, 0x7F, 0x8C,
- 0x33, 0x51, 0xA0, 0x25, 0xDE, 0xFD, 0x75, 0xBC,
- 0xEF, 0xE6, 0xE7, 0x20, 0x04, 0x5A, 0xEC, 0x50,
- 0x21, 0x48, 0x56, 0x98, 0xE2, 0x33, 0x6D, 0x22,
- 0x5C, 0xC3, 0xFB, 0xFC, 0x6F, 0xB3, 0xA7, 0x8E,
- 0x6F, 0x67, 0x70, 0x9D, 0xDA, 0x02, 0x01, 0x59,
- 0x7B, 0x3D, 0x2B, 0x38, 0xCC, 0x0F, 0x44, 0x3D,
- 0xFB, 0x9A, 0xB3, 0x23, 0x15, 0x50, 0x6E, 0xBF,
- 0x8B, 0xA1, 0x94, 0x33, 0xE5, 0x7B, 0x88, 0x4E,
- 0xCB, 0x6D, 0x9F, 0xBF, 0xBC, 0x7A, 0xA8, 0x1E,
- 0x68, 0x25, 0xED, 0x8E, 0x53, 0x21, 0x72, 0xC5,
- 0x70, 0xB3, 0xE4, 0xA6, 0xA1, 0x5A, 0x2D, 0xC8,
- 0x43, 0x9D, 0x60, 0x77, 0x78, 0xE0, 0xC4, 0xAF,
- 0xC8, 0x29, 0xBA, 0xD0, 0x4D, 0x39, 0x83, 0x51,
- 0xA7, 0x10, 0x7F, 0x0C, 0x34, 0x0E, 0x6C, 0x75,
- 0x26, 0xD7, 0xD6, 0xC7, 0x32, 0x53, 0xAF, 0x4E,
- 0xBE, 0xF2, 0xC2, 0x0F, 0x99, 0x23, 0xB9, 0xE1,
- 0xC8, 0xB4, 0xBC, 0x5A, 0xC6, 0xCB, 0xEB, 0x4D,
- 0x28, 0x56, 0x72, 0xFE, 0x1B, 0x2C, 0x5D, 0xE3,
- 0xBC, 0xC7, 0xA3, 0xC0, 0x7D, 0x27, 0xF0, 0xD0,
- 0x4F, 0x3F, 0x1F, 0xF7, 0x87, 0x15, 0xF2, 0xEA,
- 0xD4, 0x03, 0x6D, 0x2F, 0xD4, 0x8E, 0x50, 0x4B,
- 0x05, 0xBF, 0xF7, 0x8C, 0x67, 0x5A, 0xDC, 0x4D,
- 0xCD, 0xCF, 0x9D, 0x02, 0xB6, 0xE7, 0xAE, 0x49,
- 0xD1, 0x7C, 0x00, 0xE7, 0x3B, 0xEA, 0xFB, 0x0D,
- 0x2A, 0x7B, 0x41, 0x33, 0x66, 0xD0, 0x29, 0x9F,
- 0xB3, 0x8A, 0x71, 0xB0, 0xE2, 0x76, 0xA9, 0xDB,
- 0xFD, 0x64, 0x04, 0x69, 0xDF, 0x89, 0x1F, 0x56,
- 0x86, 0x92, 0xD9, 0xD9, 0xB9, 0xF3, 0x4F, 0xAC,
- 0xAE, 0x61, 0x48, 0x20, 0xCE, 0x3C, 0x2B, 0x44,
- 0xAB, 0x42, 0xFA, 0xAB, 0x2E, 0x94, 0x82, 0xC8,
- 0xD9, 0x97, 0xCF, 0x27, 0xDF, 0xAC, 0xAC, 0xE7,
- 0xCA, 0xB2, 0x84, 0xAB, 0xF2, 0x5D, 0xDF, 0x56,
- 0x0C, 0x8C, 0x07, 0x3C, 0x3D, 0xA8, 0xDD, 0xBE,
- 0xFF, 0x4E, 0x28, 0x0D, 0xB2, 0x2D, 0xE6, 0x9D,
- 0x44, 0x21, 0xCB, 0xE7, 0x33, 0x63, 0x22, 0x8F,
- 0x4C, 0xFF, 0xB6, 0x1D, 0x9A, 0x71, 0x3F, 0xB1,
- 0x29, 0xAE, 0x3A, 0x35, 0xEE, 0x9C, 0x97, 0x68,
- 0xA7, 0x52, 0x66, 0x01, 0xD8, 0x9A, 0x5D, 0xF4,
- 0xB3, 0x2F, 0x5C, 0xD4, 0x0E, 0xF9, 0xCF, 0x07,
- 0xF6, 0x8C, 0xBA, 0xA6, 0x8D, 0x6B, 0xC6, 0x01,
- 0xC2, 0x69, 0xAE, 0x60, 0x08, 0x1A, 0x0E, 0x3F,
- 0xAE, 0x60, 0x29, 0xF3, 0x48, 0x0D, 0xE0, 0xD0,
- 0xAE, 0x52, 0x44, 0xE9, 0x7F, 0x1F, 0x92, 0x5F,
- 0x71, 0xAD, 0xEC, 0x6B, 0x47, 0x66, 0x92, 0x22,
- 0x27, 0xAE, 0x6E, 0x25, 0xCD, 0xF3, 0x5F, 0x55,
- 0x59, 0xBD, 0x73, 0xCE, 0x2B, 0x7E, 0x99, 0x44,
- 0x56, 0x70, 0xA3, 0xE7, 0x7A, 0x59, 0x75, 0xD8,
- 0x48, 0x0C, 0x39, 0x2B, 0xD7, 0x53, 0xC6, 0xAD,
- 0x4A, 0x6F, 0xB4, 0x14, 0x96, 0xDF, 0xF2, 0x4A,
- 0x0C, 0xA2, 0xD5, 0x29, 0x98, 0x7C, 0x42, 0x87,
- 0xD9, 0x1F, 0x97, 0x61, 0xD9, 0xBF, 0x99, 0x4F,
- 0x2C, 0x4C, 0x75, 0xAC, 0xB8, 0x06, 0x75, 0xD6,
- 0x87, 0x76, 0x7E, 0xE3, 0x23, 0x4B, 0xEA, 0x1A,
- 0x1A, 0xF4, 0xB7, 0x09, 0xAF, 0x53, 0xEB, 0xA6,
- 0x39, 0x10, 0xFE, 0xD4, 0xEB, 0x1B, 0xAE, 0x38,
- 0x31, 0x33, 0xBA, 0x68, 0xEE, 0xC7, 0x65, 0x76,
- 0xFB, 0x49, 0x77, 0xD4, 0x19, 0xC4, 0xE6, 0xA7,
- 0x05, 0xFE, 0x2A, 0xDA, 0x39, 0x99, 0x1A, 0x92,
- 0xD2, 0xF0, 0x61, 0x97, 0xF6, 0x06, 0x6C, 0x88,
- 0x7B, 0x6F, 0x60, 0xE6, 0x70, 0x08, 0xF0, 0xB4,
- 0x6B, 0x39, 0x6F, 0x05, 0x41, 0x81, 0xF9, 0xBE,
- 0x7A, 0x51, 0xC4, 0x75, 0xB0, 0x6A, 0x89, 0xA0,
- 0xA6, 0x9A, 0x5B, 0xEE, 0x7D, 0x78, 0x17, 0x5F,
- 0x9F, 0x3B, 0x7D, 0xDD, 0x8A, 0x9E, 0xAA, 0x1A,
- 0xDA, 0x49, 0x08, 0xE9, 0xFD, 0x91, 0xA6, 0xFA,
- 0xCE, 0xCF, 0x67, 0xDF, 0x0F, 0xC9, 0xD6, 0x38,
- 0xD9, 0xD5, 0xD1, 0xC0, 0x76, 0x59, 0x42, 0x53,
- 0xBF, 0x48, 0xE9, 0x11, 0x74, 0xC7, 0x11, 0xD8,
- 0xE7, 0x8E, 0xD3, 0xC8, 0x25, 0xA1, 0x26, 0x50,
- 0xBB, 0xB4, 0x35, 0xAF, 0xAF, 0x06, 0x23, 0x69,
- 0x3E, 0x30, 0xFD, 0x7B, 0x34, 0x83, 0x07, 0xD0,
- 0xF0, 0x0F, 0x6C, 0x9A, 0x13, 0x5D, 0xC2, 0x7B,
- 0xDF, 0x6F, 0xDD, 0x8E, 0xF4, 0x30, 0x82, 0x05,
- 0x41, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
- 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x82, 0x05, 0x32,
- 0x04, 0x82, 0x05, 0x2E, 0x30, 0x82, 0x05, 0x2A,
- 0x30, 0x82, 0x05, 0x26, 0x06, 0x0B, 0x2A, 0x86,
- 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01,
- 0x02, 0xA0, 0x82, 0x04, 0xEE, 0x30, 0x82, 0x04,
- 0xEA, 0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48,
- 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03, 0x30,
- 0x0E, 0x04, 0x08, 0x74, 0xC0, 0x84, 0x8F, 0xC7,
- 0x74, 0x5E, 0x21, 0x02, 0x02, 0x08, 0x00, 0x04,
- 0x82, 0x04, 0xC8, 0x1E, 0xF4, 0xE9, 0x07, 0x27,
- 0x9E, 0x5A, 0xC9, 0x39, 0x1D, 0x37, 0x2C, 0x06,
- 0x4B, 0x57, 0xEA, 0xC5, 0x42, 0x9A, 0x60, 0xD5,
- 0x42, 0xB2, 0x34, 0x2D, 0xD3, 0x88, 0x7C, 0x78,
- 0x87, 0xB6, 0xE9, 0x42, 0x44, 0x1F, 0x67, 0x32,
- 0x92, 0x54, 0x22, 0xDA, 0xB2, 0x43, 0xE7, 0x40,
- 0xBE, 0x1F, 0xAF, 0x3A, 0xCD, 0x2A, 0x9F, 0xD7,
- 0x44, 0x5B, 0x37, 0x69, 0x85, 0xDF, 0xEB, 0x2A,
- 0xB9, 0xE2, 0x92, 0x3B, 0xEA, 0xD5, 0x42, 0x53,
- 0x95, 0x4A, 0xB0, 0x1B, 0xA5, 0xEF, 0xA6, 0x0D,
- 0x29, 0xF4, 0x33, 0xFE, 0xD7, 0x49, 0x04, 0x1E,
- 0x8C, 0xAD, 0x63, 0x1E, 0x79, 0x63, 0x74, 0x0C,
- 0xE5, 0x5E, 0xA2, 0x2C, 0xBE, 0xB8, 0x90, 0xCE,
- 0x06, 0x25, 0xBF, 0xD1, 0x5A, 0x50, 0xCF, 0x3B,
- 0x52, 0xE2, 0xA7, 0xFF, 0x19, 0x02, 0xCF, 0xD0,
- 0x9B, 0xD9, 0xF7, 0x28, 0x07, 0x38, 0x1F, 0xF2,
- 0xAF, 0x44, 0x91, 0x3F, 0x0F, 0xB6, 0x6E, 0x8C,
- 0xC0, 0x32, 0x92, 0xC0, 0xCD, 0x25, 0x98, 0x67,
- 0xF1, 0x47, 0x52, 0x50, 0xF0, 0xA3, 0x7B, 0xE6,
- 0x74, 0xDC, 0x72, 0x28, 0xC8, 0xAB, 0xB3, 0x31,
- 0x7D, 0xA3, 0xF7, 0xC7, 0xD1, 0xE6, 0x99, 0xB4,
- 0xB6, 0x5A, 0x3A, 0x4D, 0x83, 0x4F, 0xB8, 0xB5,
- 0x86, 0xF8, 0x37, 0x7F, 0xA0, 0x16, 0x2F, 0x3C,
- 0x62, 0x7A, 0xD4, 0x3A, 0xEB, 0xC2, 0xE8, 0x03,
- 0x49, 0x17, 0x9E, 0xFB, 0xD7, 0xAF, 0x91, 0x32,
- 0xFD, 0xEA, 0x4F, 0x64, 0xC6, 0x6E, 0x02, 0xEA,
- 0xC4, 0xC8, 0x1F, 0x16, 0xC5, 0x4C, 0xFB, 0xC5,
- 0x42, 0xF5, 0x85, 0x05, 0x92, 0x59, 0x4B, 0x31,
- 0xE5, 0xE9, 0x69, 0xE7, 0x02, 0x98, 0x33, 0xBA,
- 0x4C, 0x17, 0x09, 0xEF, 0x89, 0x20, 0xFA, 0x83,
- 0x9F, 0xAE, 0x0E, 0x1B, 0x7D, 0x98, 0xB9, 0xF2,
- 0x3C, 0x0F, 0xB7, 0x1C, 0x72, 0xDF, 0x17, 0x84,
- 0x7F, 0x0A, 0xFD, 0x12, 0x3C, 0x6F, 0x68, 0x5D,
- 0x45, 0xEB, 0xB8, 0xD6, 0x24, 0x65, 0x42, 0x75,
- 0x5C, 0xC2, 0xF3, 0x3A, 0x6A, 0x4E, 0x51, 0x34,
- 0x1B, 0xB6, 0x81, 0xB2, 0x8A, 0xEF, 0x28, 0xA4,
- 0xC5, 0x88, 0x9A, 0x97, 0xE0, 0xEF, 0x31, 0x12,
- 0x01, 0x7E, 0x1B, 0x43, 0x0F, 0x27, 0x80, 0x87,
- 0x98, 0xC5, 0xD5, 0x83, 0xCB, 0x4B, 0xB7, 0x01,
- 0x79, 0x60, 0xA1, 0x1A, 0x03, 0x05, 0xC6, 0x36,
- 0x04, 0x31, 0x3C, 0x06, 0xDB, 0x08, 0xA8, 0xDA,
- 0x8E, 0x32, 0x19, 0x91, 0xF1, 0x0D, 0x61, 0x6F,
- 0xE4, 0xB2, 0x79, 0x8A, 0xDE, 0xF4, 0xF7, 0xFB,
- 0x2C, 0x23, 0x5B, 0xD9, 0x64, 0x2F, 0xB7, 0xB3,
- 0x8B, 0xCA, 0xB8, 0x8C, 0x1D, 0x3B, 0x49, 0x05,
- 0x38, 0xA1, 0xE5, 0x8C, 0x1A, 0xDC, 0xA5, 0x61,
- 0xFE, 0xF4, 0x2B, 0xDC, 0x77, 0x28, 0xF6, 0x19,
- 0xE7, 0xB7, 0x8F, 0x4D, 0x27, 0x2D, 0xED, 0x8A,
- 0x3F, 0x3D, 0xDC, 0x9F, 0xD1, 0x30, 0xFF, 0xD6,
- 0xC3, 0xBE, 0x41, 0x25, 0xE3, 0xA5, 0x9B, 0x73,
- 0xDF, 0x6A, 0xD9, 0xF9, 0x70, 0x84, 0x02, 0x4C,
- 0x35, 0xD4, 0x3E, 0x05, 0x76, 0x3A, 0xDC, 0x6D,
- 0x5A, 0x81, 0xB3, 0x94, 0xF7, 0x22, 0xF7, 0xDC,
- 0xC1, 0x43, 0x31, 0x57, 0x5B, 0x42, 0x9A, 0x0B,
- 0xF4, 0x95, 0x30, 0xA9, 0xBB, 0xD8, 0x06, 0xFB,
- 0x1D, 0x6F, 0x9B, 0xC3, 0xBB, 0xF3, 0xBF, 0xFB,
- 0xB4, 0x9F, 0x35, 0x64, 0x0A, 0x69, 0xB7, 0xD1,
- 0x3E, 0xCA, 0x78, 0x07, 0x04, 0x03, 0x79, 0xD4,
- 0xF3, 0xA8, 0xEC, 0x18, 0xDB, 0x03, 0x5E, 0x47,
- 0xD7, 0xD0, 0x56, 0x2C, 0x74, 0x94, 0x86, 0x04,
- 0x46, 0xB8, 0xD4, 0x35, 0x0A, 0x7B, 0xE6, 0x78,
- 0xC4, 0x43, 0x3C, 0x56, 0xCC, 0x37, 0x8B, 0xFD,
- 0xE8, 0xF4, 0x57, 0xEA, 0xAE, 0xCF, 0x36, 0x97,
- 0x12, 0xAC, 0x39, 0xCF, 0x7C, 0xEF, 0x22, 0x67,
- 0x01, 0xEC, 0xD8, 0x09, 0x49, 0x4E, 0xE3, 0x74,
- 0xDD, 0x39, 0xE1, 0x39, 0xD7, 0x0C, 0x5F, 0x1B,
- 0xCE, 0x69, 0xBC, 0x72, 0x44, 0x87, 0x64, 0x1C,
- 0x08, 0x05, 0x93, 0x69, 0x6D, 0x7F, 0x90, 0x0A,
- 0x2C, 0xCB, 0x8A, 0xBB, 0x7F, 0xE3, 0xE0, 0x80,
- 0x31, 0xD0, 0x0A, 0x3A, 0x95, 0xFF, 0xF7, 0xB4,
- 0x36, 0x38, 0x93, 0xE0, 0x0C, 0x11, 0x37, 0x12,
- 0x06, 0xF6, 0xAD, 0xE9, 0xB1, 0x7A, 0x00, 0xF5,
- 0xD2, 0x32, 0x6B, 0xD0, 0x27, 0xA5, 0x1B, 0x3D,
- 0xE8, 0xDB, 0xCC, 0xA9, 0x1F, 0x1F, 0xB1, 0x99,
- 0x3D, 0x7C, 0xB7, 0xCA, 0xDA, 0x27, 0x2C, 0x64,
- 0x1C, 0x49, 0xB6, 0x87, 0x44, 0x06, 0x94, 0x9D,
- 0xBC, 0x6B, 0x20, 0xA2, 0x68, 0x15, 0x1F, 0xE2,
- 0xF2, 0xAD, 0x6D, 0x23, 0x2E, 0x2B, 0x74, 0xE2,
- 0x5D, 0xE4, 0xB0, 0xC7, 0x84, 0xCB, 0x64, 0xBF,
- 0xE0, 0xA8, 0x18, 0x83, 0xB4, 0xC9, 0xD9, 0x73,
- 0xA8, 0xE6, 0xA9, 0x36, 0xD5, 0x63, 0x1E, 0x2C,
- 0x2A, 0x55, 0x09, 0x77, 0x5E, 0xB3, 0x4B, 0xEA,
- 0xB5, 0xD0, 0x14, 0x5F, 0xEB, 0x50, 0x7B, 0xAA,
- 0xEF, 0x94, 0xBA, 0x2B, 0xD7, 0x8A, 0x07, 0xF1,
- 0xF9, 0x5E, 0x12, 0x12, 0x21, 0x52, 0xE5, 0x0A,
- 0x3E, 0xC0, 0xBC, 0x5D, 0x4C, 0xE2, 0x12, 0x7C,
- 0x39, 0xF9, 0x16, 0x9D, 0xBD, 0x96, 0x83, 0x3B,
- 0x7F, 0x3D, 0x6A, 0xEC, 0xF1, 0x25, 0xD2, 0xB0,
- 0xB0, 0xEB, 0x20, 0x06, 0x07, 0xD6, 0xD9, 0x4C,
- 0x07, 0x9A, 0x82, 0xC1, 0xFC, 0xF7, 0x66, 0x15,
- 0xBD, 0x62, 0x65, 0xD8, 0x6C, 0xF6, 0x33, 0x7B,
- 0x5A, 0x28, 0xEC, 0x90, 0xA1, 0x26, 0x9F, 0xC3,
- 0x28, 0x4A, 0x64, 0x50, 0x5F, 0xCA, 0xE2, 0x6D,
- 0xB8, 0x0F, 0xE2, 0x94, 0xB5, 0x8E, 0x1F, 0x8A,
- 0x8F, 0x6B, 0xA6, 0x86, 0x1F, 0xEE, 0xDC, 0x24,
- 0xB4, 0xB8, 0x25, 0xEC, 0x28, 0x2D, 0xF9, 0xCB,
- 0x7D, 0x38, 0xFF, 0xC7, 0x74, 0x2E, 0xD3, 0x10,
- 0xEC, 0x03, 0x31, 0xEE, 0x83, 0xE7, 0xA4, 0xF7,
- 0xBA, 0x28, 0x21, 0xE0, 0x7F, 0xB4, 0xB7, 0xE1,
- 0x7A, 0xF9, 0x2B, 0xB0, 0x2C, 0x3B, 0x80, 0x5F,
- 0xE0, 0x5D, 0xB2, 0x7E, 0x59, 0xFF, 0x59, 0x07,
- 0x58, 0x42, 0x57, 0xEE, 0x44, 0xF1, 0xB1, 0xAD,
- 0xBA, 0xDE, 0xCB, 0x1D, 0x8A, 0x36, 0x67, 0xE8,
- 0x45, 0xFF, 0x07, 0x8D, 0xEE, 0xA4, 0x51, 0x9C,
- 0x4C, 0x83, 0x5D, 0x2E, 0x2F, 0xE1, 0x5B, 0x75,
- 0xE8, 0x29, 0xCD, 0x0B, 0x07, 0x62, 0xE0, 0xC3,
- 0x0D, 0x1D, 0xEA, 0xCF, 0xF0, 0x8A, 0x65, 0x27,
- 0x70, 0x42, 0x9F, 0x26, 0x00, 0x15, 0x70, 0xC5,
- 0x4A, 0xF6, 0x25, 0xD0, 0x40, 0x72, 0xE9, 0xC1,
- 0x73, 0xFD, 0x48, 0x94, 0xA3, 0x8D, 0x66, 0x63,
- 0x96, 0x4F, 0xF7, 0xEE, 0xFB, 0x4C, 0xC7, 0xB8,
- 0x6B, 0xE9, 0x90, 0xE1, 0x2A, 0x66, 0x80, 0x99,
- 0x3B, 0xB0, 0x1A, 0x6C, 0xF9, 0x0E, 0x72, 0xDA,
- 0x8E, 0x4F, 0x46, 0xC2, 0x6A, 0x4B, 0x7A, 0x16,
- 0xE5, 0x26, 0x0B, 0x5C, 0xD4, 0x47, 0x34, 0xE5,
- 0x37, 0xBE, 0x68, 0x6C, 0xDA, 0xD3, 0x9B, 0x6F,
- 0xAE, 0x51, 0x9C, 0x99, 0x0A, 0x5B, 0xF8, 0x37,
- 0xBC, 0xDE, 0xFC, 0x93, 0xC5, 0xE7, 0x0F, 0xEF,
- 0x0B, 0xA6, 0x07, 0xC2, 0xA6, 0xE6, 0xDA, 0x2D,
- 0x1B, 0x49, 0xC9, 0xDE, 0x6B, 0x27, 0xDC, 0x00,
- 0xEF, 0x23, 0x87, 0x0E, 0xEB, 0xD1, 0x48, 0x7D,
- 0xB4, 0xF2, 0x58, 0xC6, 0x3C, 0xE2, 0x89, 0xBA,
- 0xB0, 0x05, 0xAC, 0x94, 0x41, 0x9A, 0xA8, 0xFF,
- 0x3E, 0xBC, 0x3A, 0x52, 0x9C, 0xF9, 0x7F, 0x07,
- 0x8B, 0xB0, 0x2C, 0x71, 0x83, 0x7B, 0xCF, 0x2E,
- 0x7F, 0x7C, 0x96, 0x65, 0xD9, 0x08, 0x17, 0xEC,
- 0xFA, 0xDE, 0x4E, 0x40, 0x12, 0x26, 0x70, 0x71,
- 0x65, 0xA5, 0xDC, 0x98, 0x47, 0xA3, 0xFC, 0xE0,
- 0x9A, 0x16, 0xED, 0x45, 0x56, 0x72, 0x50, 0x05,
- 0x28, 0x2C, 0x99, 0xEC, 0x20, 0x2E, 0x40, 0xC0,
- 0x26, 0x69, 0xCD, 0x49, 0x45, 0x17, 0xA4, 0xA3,
- 0x42, 0x0D, 0x14, 0x65, 0x87, 0x33, 0x8C, 0x92,
- 0xC5, 0xC4, 0x61, 0xFD, 0xE8, 0x68, 0x56, 0x20,
- 0x57, 0xF5, 0x8E, 0x5F, 0xCF, 0x7E, 0x97, 0xF6,
- 0x49, 0x97, 0x0A, 0xFE, 0xD3, 0x60, 0x1A, 0x5B,
- 0x0C, 0x75, 0xDD, 0x8E, 0x31, 0x78, 0x29, 0xA6,
- 0xB1, 0x4D, 0xAA, 0xDF, 0x8A, 0xD1, 0xE6, 0x91,
- 0xE3, 0x32, 0x3F, 0xEC, 0x8A, 0x1F, 0x0E, 0x35,
- 0x07, 0x6E, 0x4B, 0x83, 0x3B, 0xE5, 0x67, 0x34,
- 0x1F, 0x0C, 0x81, 0xD8, 0xD5, 0x25, 0x68, 0xE5,
- 0x28, 0x1B, 0x5C, 0x81, 0x3E, 0xE3, 0x5C, 0xB4,
- 0xB6, 0xBD, 0x62, 0x6A, 0x70, 0x33, 0xC2, 0xC5,
- 0x75, 0x27, 0xF4, 0x30, 0xE1, 0x1D, 0xC1, 0x4C,
- 0xC5, 0x02, 0x12, 0x46, 0xAC, 0xEC, 0xF9, 0xE8,
- 0xE7, 0x58, 0x24, 0x11, 0xB1, 0xF3, 0xB7, 0x8C,
- 0x3C, 0xA4, 0x0A, 0x94, 0xA6, 0x7C, 0x68, 0x54,
- 0x5B, 0xB9, 0x4D, 0x57, 0x9C, 0xE7, 0x28, 0x09,
- 0x6B, 0x89, 0x26, 0x5D, 0xE7, 0x50, 0xA9, 0x95,
- 0x90, 0x91, 0x8E, 0x00, 0x59, 0xF8, 0x3A, 0x70,
- 0xAF, 0x48, 0x2E, 0xE8, 0xC4, 0x34, 0x8C, 0xF4,
- 0x5F, 0x7F, 0xCB, 0x07, 0xAA, 0xF0, 0xD9, 0xFB,
- 0x5C, 0x32, 0x90, 0x22, 0x1A, 0xD2, 0x1A, 0xCF,
- 0x92, 0x06, 0x02, 0xCF, 0x10, 0x18, 0x7B, 0x93,
- 0xCC, 0x07, 0x4A, 0x31, 0x25, 0x30, 0x23, 0x06,
- 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01,
- 0x09, 0x15, 0x31, 0x16, 0x04, 0x14, 0xD1, 0xDE,
- 0x23, 0x16, 0x9F, 0x6E, 0xF4, 0x42, 0x21, 0x23,
- 0xE1, 0x11, 0xAA, 0xC8, 0x7C, 0x60, 0x4A, 0x78,
- 0x9D, 0x24, 0x30, 0x31, 0x30, 0x21, 0x30, 0x09,
- 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05,
- 0x00, 0x04, 0x14, 0xD6, 0x4A, 0xBB, 0x75, 0xB1,
- 0xF9, 0x9E, 0xD3, 0x58, 0x6D, 0xD1, 0x74, 0x9F,
- 0x00, 0x8A, 0xF2, 0xC8, 0xAA, 0x52, 0x4D, 0x04,
- 0x08, 0x77, 0x46, 0xE7, 0xBA, 0x25, 0x4B, 0xDA,
- 0x41, 0x02, 0x02, 0x08, 0x00]
-};
-
-const WPA_EAP_CLIENT_LIST = [
- {
- ssid: 'WPA-EAP-TTLS',
- keyManagement: 'WPA-EAP',
- eap: 'TTLS',
- identity: EAP_USERNAME,
- password: EAP_PASSWORD,
- serverCertificate: CLIENT_PKCS12_CERT.nickname,
- phase2: 'MSCHAPV2'
- }
-];
-
-/**
- * Convert the given MozWifiNetwork object array to testAssociate chain.
- *
- * @param aNetworks
- * An array of MozWifiNetwork which we want to convert.
- *
- * @return A promise chain which "then"s testAssociate accordingly.
- */
-function convertToTestAssociateChain(aNetworks) {
- let chain = Promise.resolve();
-
- aNetworks.forEach(function (aNetwork) {
- network = new window.MozWifiNetwork(aNetwork);
- chain = chain.then(() => gTestSuite.testAssociate(network));
- });
-
- return chain;
-}
-
-gTestSuite.doTestWithCertificate(
- new Blob([new Uint8Array(CLIENT_PKCS12_CERT.content)]),
- CLIENT_PKCS12_CERT.password,
- CLIENT_PKCS12_CERT.nickname,
- CLIENT_PKCS12_CERT.usage,
- function() {
- return gTestSuite.ensureWifiEnabled(true)
- // Load required server files.
- .then(() => gTestSuite.writeFile(SERVER_EAP_USER_CONF.path, SERVER_EAP_USER_CONF.content))
- .then(() => gTestSuite.writeFile(CA_CERT.path, CA_CERT.content))
- .then(() => gTestSuite.writeFile(SERVER_CERT.path, SERVER_CERT.content))
- .then(() => gTestSuite.writeFile(SERVER_KEY.path, SERVER_KEY.content))
- // Start AP.
- .then(() => gTestSuite.startHostapds(WPA_EAP_AP_LIST))
- // Scan test.
- .then(() => gTestSuite.testWifiScanWithRetry(SCAN_RETRY_CNT, WPA_EAP_AP_LIST))
- // Associate test.
- .then(() => convertToTestAssociateChain(WPA_EAP_CLIENT_LIST))
- // Tear down.
- .then(gTestSuite.killAllHostapd)
-});
diff --git a/dom/wifi/test/marionette/test_wifi_associate_wo_connect.js b/dom/wifi/test/marionette/test_wifi_associate_wo_connect.js
deleted file mode 100644
index 3fba0b2c6..000000000
--- a/dom/wifi/test/marionette/test_wifi_associate_wo_connect.js
+++ /dev/null
@@ -1,55 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-/**
- * Associate with the given networks but don't connect to it.
- *
- * Issue a association-only request, which will not have us connect
- * to the network. Instead, the network config will be added as the
- * known networks. After calling the "associate" API, we will wait
- * a while to make sure the "connected" event is not received.
- *
- * Fulfill params: (none)
- * Reject params: (none)
- *
- * @param aNetwork
- * MozWifiNetwork object.
- *
- * @return A deferred promise.
- */
-function associateButDontConnect(aNetwork) {
- log('Associating with ' + aNetwork.ssid);
- aNetwork.dontConnect = true;
-
- let promises = [];
- promises.push(gTestSuite.waitForTimeout(10 * 1000)
- .then(() => { throw 'timeout'; }));
-
- promises.push(gTestSuite.testAssociate(aNetwork));
-
- return Promise.all(promises)
- .then(() => { throw 'unexpected state'; },
- function(aReason) {
- is(typeof aReason, 'string', 'typeof aReason');
- is(aReason, 'timeout', aReason);
- });
-}
-
-gTestSuite.doTest(function() {
- let firstNetwork;
- return gTestSuite.ensureWifiEnabled(true)
- .then(gTestSuite.requestWifiScan)
- .then(function(aNetworks) {
- firstNetwork = aNetworks[0];
- return associateButDontConnect(firstNetwork);
- })
- .then(gTestSuite.getKnownNetworks)
- .then(function(aKnownNetworks) {
- is(1, aKnownNetworks.length, 'There should be only one known network!');
- is(aKnownNetworks[0].ssid, firstNetwork.ssid,
- 'The only one known network should be ' + firstNetwork.ssid)
- });
-});
diff --git a/dom/wifi/test/marionette/test_wifi_auto_connect.js b/dom/wifi/test/marionette/test_wifi_auto_connect.js
deleted file mode 100644
index 7add9f03d..000000000
--- a/dom/wifi/test/marionette/test_wifi_auto_connect.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const TESTING_HOSTAPD = [{ ssid: 'ap0' }];
-
-gTestSuite.doTestWithoutStockAp(function() {
- let firstNetwork;
- return gTestSuite.ensureWifiEnabled(true)
- // Start custom hostapd for testing.
- .then(() => gTestSuite.startHostapds(TESTING_HOSTAPD))
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', TESTING_HOSTAPD.length))
-
- // Request the first scan.
- .then(gTestSuite.requestWifiScan)
- .then(function(networks) {
- firstNetwork = networks[0];
- return gTestSuite.testAssociate(firstNetwork);
- })
-
- // Note that due to Bug 1168285, we need to re-start testing hostapd
- // after wifi has been re-enabled.
-
- // Disable wifi and kill running hostapd.
- .then(() => gTestSuite.requestWifiEnabled(false))
- .then(gTestSuite.killAllHostapd)
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', 0))
-
- // Re-enable wifi.
- .then(() => gTestSuite.requestWifiEnabled(true))
-
- // Restart hostapd.
- .then(() => gTestSuite.startHostapds(TESTING_HOSTAPD))
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', TESTING_HOSTAPD.length))
-
- // Wait for connection automatically.
- .then(() => gTestSuite.waitForConnected(firstNetwork))
-
- // Kill running hostapd.
- .then(gTestSuite.killAllHostapd)
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', 0))
-});
diff --git a/dom/wifi/test/marionette/test_wifi_enable.js b/dom/wifi/test/marionette/test_wifi_enable.js
deleted file mode 100644
index 6a1bec7a2..000000000
--- a/dom/wifi/test/marionette/test_wifi_enable.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-gTestSuite.doTest(function() {
- return Promise.resolve()
- .then(() => gTestSuite.ensureWifiEnabled(false))
- .then(() => gTestSuite.requestWifiEnabled(true));
-}); \ No newline at end of file
diff --git a/dom/wifi/test/marionette/test_wifi_enable_api.js b/dom/wifi/test/marionette/test_wifi_enable_api.js
deleted file mode 100644
index 3728330a2..000000000
--- a/dom/wifi/test/marionette/test_wifi_enable_api.js
+++ /dev/null
@@ -1,13 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-gTestSuite.doTest(function() {
- return Promise.resolve()
- .then(() => gTestSuite.ensureWifiEnabled(false, true))
- .then(() => gTestSuite.requestWifiEnabled(true, true))
- .then(() => gTestSuite.requestWifiEnabled(false, true))
- .then(() => gTestSuite.ensureWifiEnabled(true, true));
-});
diff --git a/dom/wifi/test/marionette/test_wifi_manage_pkcs12_certificate.js b/dom/wifi/test/marionette/test_wifi_manage_pkcs12_certificate.js
deleted file mode 100644
index f85ef00c9..000000000
--- a/dom/wifi/test/marionette/test_wifi_manage_pkcs12_certificate.js
+++ /dev/null
@@ -1,338 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-// Binary form of test certificate.
-var testCertInfo = {
- nickname: 'Test Certificate',
- password: '12345678',
- usage: ['UserCert', 'ServerCert'],
- blob: [0x30, 0x82, 0x09, 0xF1, 0x02, 0x01, 0x03, 0x30,
- 0x82, 0x09, 0xB7, 0x06, 0x09, 0x2A, 0x86, 0x48,
- 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x82,
- 0x09, 0xA8, 0x04, 0x82, 0x09, 0xA4, 0x30, 0x82,
- 0x09, 0xA0, 0x30, 0x82, 0x06, 0x9F, 0x06, 0x09,
- 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07,
- 0x06, 0xA0, 0x82, 0x06, 0x90, 0x30, 0x82, 0x06,
- 0x8C, 0x02, 0x01, 0x00, 0x30, 0x82, 0x06, 0x85,
- 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D,
- 0x01, 0x07, 0x01, 0x30, 0x1C, 0x06, 0x0A, 0x2A,
- 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01,
- 0x06, 0x30, 0x0E, 0x04, 0x08, 0x13, 0xB5, 0x2F,
- 0x5A, 0xB9, 0x49, 0xE6, 0x0B, 0x02, 0x02, 0x08,
- 0x00, 0x80, 0x82, 0x06, 0x58, 0x35, 0x77, 0x6B,
- 0xBF, 0x5C, 0x06, 0x09, 0xD8, 0xF0, 0x36, 0x06,
- 0x69, 0x8D, 0xA2, 0x86, 0xCF, 0x6B, 0x73, 0x86,
- 0x14, 0xFA, 0x51, 0x9A, 0x87, 0x73, 0x29, 0x71,
- 0xC5, 0xB1, 0x4F, 0xFB, 0xEC, 0x64, 0x84, 0x20,
- 0xFC, 0x06, 0x4A, 0x93, 0x74, 0x01, 0xFB, 0xEB,
- 0x1F, 0xDC, 0xF8, 0xF7, 0xBB, 0xDC, 0x42, 0xA1,
- 0x4A, 0x71, 0xDE, 0x08, 0x33, 0x7A, 0xCA, 0xD3,
- 0xD8, 0x40, 0x24, 0x47, 0xAE, 0x41, 0x42, 0x8E,
- 0xC8, 0x4E, 0xBE, 0x8B, 0xB3, 0xE5, 0x77, 0xAC,
- 0xBD, 0x98, 0x0C, 0x0E, 0x53, 0xBE, 0x38, 0xB7,
- 0xEA, 0xD2, 0x29, 0x35, 0xD2, 0xC4, 0xF4, 0xC7,
- 0xD8, 0xB1, 0x73, 0x2A, 0x13, 0x11, 0x65, 0xF7,
- 0x0C, 0x8B, 0xC0, 0x43, 0xFB, 0x31, 0x6C, 0xD2,
- 0xE4, 0x43, 0x85, 0x51, 0x16, 0xBF, 0x35, 0xB5,
- 0x05, 0x6B, 0x86, 0x11, 0xEA, 0x78, 0x64, 0x9F,
- 0x42, 0x29, 0xB9, 0x79, 0xAF, 0xB0, 0x7C, 0xBF,
- 0xC0, 0x89, 0xAD, 0xC7, 0x37, 0xD2, 0x30, 0x8C,
- 0xDC, 0xF6, 0x77, 0x5E, 0x1F, 0x26, 0x28, 0x8F,
- 0xAC, 0x19, 0x6C, 0xA0, 0x15, 0xC7, 0x12, 0xA3,
- 0x0A, 0xD5, 0xC6, 0x15, 0x60, 0x58, 0x16, 0xB8,
- 0x30, 0x12, 0x3C, 0x78, 0x3C, 0x93, 0x23, 0xA1,
- 0x56, 0x75, 0x0B, 0x77, 0xAA, 0x0B, 0x0B, 0x2B,
- 0x91, 0xB6, 0x41, 0xAB, 0xF5, 0x09, 0x4C, 0x1E,
- 0x36, 0xC0, 0x88, 0xC3, 0x08, 0xF2, 0x65, 0xCB,
- 0x58, 0x8F, 0x94, 0xB4, 0xB4, 0x05, 0xCC, 0x44,
- 0x49, 0x73, 0x1B, 0x25, 0x6F, 0x5D, 0x83, 0xBD,
- 0xF0, 0x70, 0xD0, 0xE8, 0x0D, 0x18, 0x2E, 0x44,
- 0xD7, 0x89, 0x64, 0x6A, 0xED, 0x23, 0x30, 0xDF,
- 0xAD, 0x84, 0x3B, 0x74, 0x2C, 0x0D, 0x2B, 0x51,
- 0x84, 0xA2, 0xA4, 0x9E, 0x42, 0xC3, 0x81, 0x69,
- 0xFA, 0x56, 0x76, 0x9F, 0xD9, 0x02, 0x64, 0x04,
- 0xFE, 0xF0, 0xD9, 0x01, 0xBC, 0xE2, 0xC9, 0xDD,
- 0x88, 0xAC, 0xFA, 0x24, 0x7E, 0xB1, 0xF8, 0x39,
- 0x27, 0xA2, 0xEB, 0xE4, 0x53, 0xC1, 0xF3, 0xFE,
- 0x2D, 0x9A, 0x49, 0x73, 0xFF, 0x7C, 0x8E, 0x39,
- 0xF7, 0x15, 0x27, 0xB3, 0x47, 0x48, 0x92, 0x8C,
- 0x57, 0x60, 0x9C, 0x97, 0xBA, 0x80, 0xD2, 0x25,
- 0x80, 0x94, 0xCE, 0x2C, 0x0C, 0x00, 0x44, 0x8C,
- 0x8C, 0x37, 0x82, 0x5D, 0x5F, 0x62, 0x8B, 0x05,
- 0x6F, 0xB0, 0x07, 0x34, 0xF9, 0xC3, 0xA1, 0x34,
- 0x3D, 0xE4, 0x90, 0xB0, 0x03, 0x59, 0x97, 0x6E,
- 0xFB, 0xF2, 0x92, 0xE5, 0xB5, 0x30, 0x7C, 0x0D,
- 0x3B, 0x8F, 0x90, 0x8E, 0x04, 0x47, 0x01, 0x0E,
- 0x88, 0x50, 0x4A, 0x88, 0xA0, 0xFF, 0xB7, 0x9E,
- 0x2B, 0x2C, 0x98, 0xD0, 0x3E, 0x16, 0x35, 0x5B,
- 0xD5, 0xEA, 0x54, 0x86, 0xE0, 0xFB, 0x9F, 0x2F,
- 0x62, 0x89, 0x36, 0x36, 0x9D, 0x6E, 0x62, 0xCB,
- 0xC8, 0x6C, 0x62, 0x34, 0x8F, 0x66, 0x07, 0x62,
- 0xA7, 0x00, 0x90, 0x31, 0xFA, 0x5D, 0xDD, 0x12,
- 0x33, 0x69, 0xD0, 0x74, 0x0E, 0x0B, 0x42, 0x9A,
- 0xF3, 0x40, 0x7E, 0x3E, 0x48, 0x1D, 0xF2, 0x5C,
- 0x71, 0x0B, 0x78, 0x7E, 0xD5, 0x15, 0xA4, 0x16,
- 0x1E, 0xBD, 0x71, 0x18, 0x87, 0x3A, 0xC9, 0xE3,
- 0x45, 0xEE, 0x70, 0xA2, 0x4C, 0x50, 0xF5, 0x16,
- 0x5C, 0xF8, 0x76, 0xE6, 0x9F, 0x8D, 0x86, 0x41,
- 0x7E, 0xF8, 0x60, 0x3D, 0x75, 0x6D, 0x55, 0x96,
- 0x9E, 0x43, 0x48, 0x82, 0xF7, 0xB6, 0xAC, 0x98,
- 0x6F, 0x10, 0xAA, 0x20, 0x64, 0xD0, 0x7C, 0x25,
- 0x24, 0xF7, 0xD8, 0xA4, 0xCC, 0x2D, 0xBF, 0x85,
- 0x62, 0x6C, 0x4F, 0xFF, 0x9D, 0x71, 0x04, 0x98,
- 0x61, 0xB0, 0xBC, 0x31, 0xC1, 0xE9, 0xB8, 0x29,
- 0xA5, 0xEB, 0xD1, 0x1D, 0x65, 0x8E, 0xAE, 0x38,
- 0x55, 0x65, 0x22, 0xC7, 0xFD, 0x7E, 0xF2, 0x6A,
- 0xB6, 0xB1, 0x51, 0x37, 0x4B, 0x05, 0x8F, 0xA7,
- 0x2D, 0x3F, 0x5C, 0x04, 0x2B, 0xBA, 0x2C, 0x37,
- 0xCA, 0xDE, 0xD5, 0x3E, 0xA0, 0xA5, 0x86, 0x59,
- 0xA7, 0xD7, 0x38, 0x07, 0xFB, 0x79, 0xF6, 0x2D,
- 0xE1, 0xAA, 0x7C, 0xD1, 0x91, 0xBE, 0x39, 0xDF,
- 0x53, 0x3C, 0xD1, 0x44, 0x2C, 0xF9, 0x12, 0x7D,
- 0xB1, 0xCD, 0xF3, 0x35, 0x1F, 0x85, 0xA6, 0x64,
- 0x2F, 0xFD, 0x28, 0xF2, 0x85, 0xA8, 0xA7, 0x1F,
- 0x7F, 0xD9, 0x79, 0x30, 0x9B, 0xFC, 0x69, 0x3A,
- 0x9B, 0x1F, 0x55, 0x70, 0xC9, 0x60, 0x82, 0x3D,
- 0xE9, 0x5A, 0x37, 0x5F, 0x8C, 0xBD, 0x19, 0x5D,
- 0xCC, 0x1C, 0xBE, 0x26, 0x4A, 0xEA, 0x8B, 0x39,
- 0xCE, 0x0D, 0xBD, 0x63, 0x05, 0x98, 0x75, 0xAB,
- 0x08, 0x79, 0x90, 0xC7, 0x20, 0xFF, 0xE4, 0x0D,
- 0xB1, 0xA0, 0x92, 0x2B, 0x0C, 0x4B, 0x0C, 0xDC,
- 0xB9, 0x72, 0x2A, 0xA4, 0xCC, 0xA6, 0x32, 0xA3,
- 0x57, 0x82, 0xB4, 0xB9, 0x0F, 0x81, 0xC5, 0xD9,
- 0x7C, 0xB8, 0x0F, 0x7D, 0xEA, 0x5D, 0xD3, 0xC4,
- 0x2F, 0x31, 0x79, 0x11, 0xAD, 0x36, 0x56, 0x1F,
- 0xFA, 0xE3, 0xCE, 0xD2, 0x29, 0x23, 0xE8, 0x2C,
- 0xDF, 0x7D, 0x94, 0x28, 0x28, 0x9A, 0x0E, 0x64,
- 0xFC, 0x07, 0x11, 0x96, 0x06, 0x1A, 0x39, 0xCD,
- 0x04, 0x37, 0x37, 0xDB, 0xFE, 0x68, 0x37, 0xF5,
- 0x59, 0x54, 0xBC, 0xEF, 0xDB, 0x0C, 0x80, 0xCD,
- 0xD3, 0x46, 0xA8, 0xA2, 0xBE, 0xE0, 0x63, 0x80,
- 0xA1, 0x5F, 0x5D, 0xF1, 0xFB, 0x96, 0x8C, 0x06,
- 0x38, 0xB6, 0xCB, 0x70, 0xB0, 0xFB, 0xD3, 0x26,
- 0xB3, 0x8B, 0xC6, 0x85, 0x34, 0xB7, 0xAB, 0x5F,
- 0x7E, 0xC6, 0xAA, 0x79, 0x5B, 0x48, 0x11, 0x65,
- 0x9E, 0x2A, 0xCD, 0x6A, 0xF0, 0xB2, 0x93, 0xF5,
- 0x2B, 0x88, 0x45, 0xB7, 0xC9, 0xBE, 0x1A, 0x72,
- 0x60, 0x62, 0xA4, 0xA5, 0x3B, 0xC2, 0x1C, 0xC6,
- 0x21, 0x09, 0xA9, 0x40, 0xF6, 0x58, 0x2B, 0xE5,
- 0x70, 0xDC, 0xFC, 0x47, 0x3B, 0x08, 0xEE, 0xA9,
- 0x94, 0x26, 0x43, 0xFE, 0xA7, 0x75, 0xD6, 0x4E,
- 0x52, 0xF6, 0x46, 0xD1, 0x80, 0xEB, 0x3B, 0x8E,
- 0xBE, 0x54, 0x4F, 0xBD, 0x42, 0x0E, 0x41, 0xF9,
- 0x36, 0x7D, 0xB6, 0x7F, 0x99, 0x20, 0xC9, 0x63,
- 0xE7, 0x93, 0x02, 0x62, 0x59, 0x94, 0xCB, 0xC6,
- 0x62, 0xA9, 0x26, 0xE1, 0x1E, 0x03, 0x5A, 0x41,
- 0x2F, 0x43, 0x28, 0x75, 0xB7, 0x0C, 0x02, 0x9C,
- 0x1E, 0xE0, 0x40, 0xB3, 0xE2, 0x9A, 0xED, 0xC6,
- 0x20, 0x49, 0xEC, 0xDD, 0xC5, 0x64, 0x95, 0x83,
- 0x51, 0xAE, 0x46, 0x9D, 0x70, 0x17, 0xC6, 0x47,
- 0xD3, 0x82, 0xCC, 0x6A, 0x5D, 0x93, 0xB2, 0x85,
- 0x5B, 0x25, 0x05, 0xE7, 0x26, 0x2E, 0xD3, 0xDA,
- 0x1C, 0xD9, 0x06, 0xB6, 0x16, 0x69, 0x8C, 0x7F,
- 0xC8, 0xCF, 0x95, 0x18, 0xB5, 0x98, 0xC0, 0x42,
- 0x61, 0xDE, 0x77, 0x41, 0x3A, 0xF6, 0xE1, 0xB0,
- 0xE8, 0x64, 0x4A, 0xC2, 0x58, 0xBE, 0x27, 0xC6,
- 0x9B, 0x0D, 0x47, 0x1A, 0x09, 0x56, 0x7D, 0x2B,
- 0x19, 0x01, 0x88, 0xC7, 0xFB, 0x1E, 0xCF, 0x5E,
- 0xF6, 0xB0, 0x82, 0x87, 0xC0, 0xBE, 0xD6, 0xA5,
- 0xC3, 0xAC, 0x3A, 0x97, 0x88, 0x25, 0x81, 0xAA,
- 0x3A, 0xCE, 0x66, 0x88, 0x0F, 0xC3, 0x02, 0x50,
- 0x1C, 0xC3, 0x2B, 0xBC, 0x53, 0x52, 0xFE, 0xD2,
- 0x3F, 0x50, 0xC8, 0xB2, 0x19, 0x0A, 0x14, 0xB1,
- 0x73, 0x18, 0xB4, 0xDF, 0xBD, 0xED, 0x43, 0xC5,
- 0x91, 0xF4, 0x91, 0xBA, 0x7E, 0xB0, 0x7E, 0xA9,
- 0x43, 0x67, 0x06, 0xCF, 0x51, 0xC1, 0xBF, 0x63,
- 0x7E, 0x91, 0x76, 0xFF, 0x4F, 0x48, 0x91, 0xCF,
- 0xDF, 0x01, 0x4D, 0x7E, 0x81, 0x22, 0xFB, 0x79,
- 0xFC, 0x1D, 0xE3, 0xA7, 0x45, 0x16, 0xFB, 0xF2,
- 0x83, 0xC7, 0xAE, 0xC6, 0xC5, 0x81, 0xDB, 0xA2,
- 0x9F, 0x2F, 0xEA, 0xE6, 0x8E, 0x12, 0x8D, 0x43,
- 0x14, 0x26, 0x25, 0x0E, 0xB4, 0x18, 0xE8, 0x41,
- 0x84, 0xA3, 0x04, 0xDF, 0x97, 0xFF, 0xAA, 0x45,
- 0xEC, 0x18, 0xAA, 0xB1, 0xFC, 0xDC, 0xB9, 0xAB,
- 0xEE, 0xD1, 0xC4, 0x9E, 0x42, 0x3F, 0x5B, 0x8F,
- 0x9F, 0x22, 0xAF, 0xCC, 0x6F, 0xA0, 0x41, 0x41,
- 0xCB, 0xD3, 0xAC, 0x96, 0x20, 0xF1, 0x63, 0x56,
- 0x65, 0xCE, 0x83, 0xC6, 0x62, 0x04, 0x85, 0x16,
- 0x7F, 0x4E, 0xFB, 0xA0, 0x68, 0x11, 0x85, 0x5B,
- 0x51, 0xB6, 0x9F, 0xA2, 0xF5, 0xA1, 0xCF, 0x01,
- 0x9A, 0x80, 0x68, 0xC3, 0xE9, 0x7F, 0x9E, 0x2E,
- 0x83, 0x84, 0xDC, 0x3C, 0x35, 0xCF, 0x24, 0xBF,
- 0xF5, 0x00, 0x91, 0x45, 0x14, 0x65, 0xE0, 0xC5,
- 0x75, 0xDA, 0xEF, 0x14, 0xBD, 0xDB, 0x28, 0x8D,
- 0x30, 0x96, 0xC9, 0xFE, 0xA8, 0x49, 0x76, 0xC9,
- 0xED, 0x90, 0x4C, 0x2E, 0xF1, 0x14, 0x2C, 0xF7,
- 0x13, 0x7C, 0xF1, 0xCC, 0x67, 0xA5, 0x11, 0x55,
- 0xBD, 0x66, 0x13, 0x8A, 0x76, 0xF9, 0xAC, 0xC9,
- 0x51, 0x8A, 0xBB, 0x5D, 0x29, 0xEF, 0xF6, 0x37,
- 0xA0, 0x3E, 0x99, 0x77, 0x6B, 0xE5, 0xCD, 0x06,
- 0xAC, 0x57, 0x07, 0x37, 0x44, 0x3D, 0x5D, 0xD7,
- 0xB6, 0x5C, 0xCB, 0x77, 0xD0, 0x4C, 0x28, 0x9D,
- 0x12, 0x69, 0x5A, 0x68, 0xD1, 0x15, 0x30, 0xC4,
- 0x30, 0xD2, 0x20, 0xDF, 0xD5, 0x73, 0x9F, 0x83,
- 0xE9, 0x4C, 0x55, 0xF5, 0xAF, 0xAA, 0x37, 0xF8,
- 0x28, 0xB6, 0x3F, 0x99, 0x4B, 0x15, 0x1E, 0x40,
- 0xAB, 0x4F, 0x58, 0x3D, 0x3B, 0x81, 0x7D, 0x62,
- 0x28, 0x6E, 0x73, 0x58, 0x50, 0x36, 0x49, 0x01,
- 0xF7, 0x04, 0x3A, 0x23, 0x28, 0xDA, 0x15, 0xC5,
- 0xE3, 0xF6, 0x6F, 0xE1, 0x79, 0x07, 0xFB, 0xAA,
- 0xFF, 0x44, 0x48, 0x53, 0x9E, 0x7F, 0x8D, 0x89,
- 0x88, 0x1A, 0x9A, 0xF9, 0x47, 0x58, 0x20, 0xBB,
- 0x79, 0x4A, 0x2A, 0x14, 0x03, 0x9B, 0x65, 0x4C,
- 0x67, 0x02, 0x02, 0xFE, 0xEB, 0xCD, 0xCB, 0x84,
- 0xF5, 0xCE, 0x32, 0x59, 0xBC, 0xEA, 0xEC, 0xB1,
- 0x3C, 0x22, 0xCF, 0x9D, 0xB0, 0x34, 0x6D, 0xE6,
- 0x5A, 0x37, 0xC0, 0x22, 0xAA, 0xF3, 0xB5, 0x71,
- 0x90, 0x21, 0xE0, 0xB6, 0x19, 0xE9, 0xB3, 0x10,
- 0xCE, 0x5B, 0xF9, 0xD4, 0x25, 0x30, 0x7D, 0xF6,
- 0x7D, 0xB6, 0x16, 0xFC, 0x20, 0x3C, 0x2F, 0x96,
- 0xD5, 0x79, 0x90, 0x88, 0x24, 0x5D, 0x46, 0x64,
- 0x99, 0xC1, 0xF8, 0x7F, 0x96, 0xA7, 0xB5, 0xA9,
- 0x47, 0xA3, 0x14, 0xED, 0x93, 0xED, 0x30, 0x56,
- 0x58, 0xA5, 0xD4, 0x54, 0x2A, 0xF3, 0x89, 0x27,
- 0x7C, 0x55, 0x41, 0x11, 0x27, 0x9D, 0xF6, 0x4D,
- 0xA6, 0xB1, 0x00, 0xE0, 0xB0, 0xF6, 0x1E, 0xAB,
- 0x20, 0x1F, 0xAE, 0x8A, 0x82, 0xA7, 0x49, 0xFC,
- 0xBB, 0x66, 0xAC, 0x97, 0x95, 0x49, 0x29, 0xCB,
- 0x6F, 0xF4, 0xC1, 0xB7, 0x6B, 0xF9, 0x8C, 0x25,
- 0xC6, 0xF0, 0xB5, 0x81, 0xB0, 0xA2, 0x4D, 0xCC,
- 0x2E, 0xD0, 0x13, 0x5F, 0x96, 0x3F, 0xCD, 0xD0,
- 0x52, 0xD1, 0xFE, 0xF9, 0xC2, 0x7E, 0x9D, 0xAB,
- 0xCB, 0x95, 0x0F, 0x27, 0x01, 0x9E, 0x23, 0x6B,
- 0x19, 0xFF, 0x52, 0x55, 0x71, 0x0A, 0xD4, 0xBB,
- 0x43, 0x65, 0x29, 0x66, 0xBE, 0x2D, 0x6C, 0xE3,
- 0x2A, 0x7C, 0xB4, 0x02, 0x32, 0x59, 0x94, 0x80,
- 0x14, 0xE7, 0x62, 0xE4, 0xCE, 0xB0, 0xCA, 0xCA,
- 0x37, 0xD7, 0x0C, 0x68, 0x29, 0xE2, 0x92, 0xE1,
- 0xEB, 0x91, 0xE5, 0xA1, 0x0C, 0xFC, 0x55, 0xCB,
- 0x56, 0xB3, 0x96, 0xFB, 0x64, 0xD9, 0x53, 0x8E,
- 0x82, 0x2B, 0xDF, 0x7F, 0xCB, 0x2A, 0xF6, 0x3C,
- 0xA7, 0x89, 0x52, 0x13, 0x2C, 0x6A, 0x93, 0xA2,
- 0x74, 0xF5, 0x91, 0x00, 0x17, 0xAA, 0x74, 0x45,
- 0x63, 0x5A, 0xE5, 0xC3, 0x16, 0xFC, 0x0E, 0xF7,
- 0xF3, 0xA4, 0x55, 0x8A, 0xA2, 0x60, 0x24, 0x57,
- 0x25, 0x2C, 0x94, 0xE0, 0xF5, 0x32, 0x54, 0x4A,
- 0x2D, 0x63, 0x5F, 0xD8, 0x35, 0x96, 0xBD, 0xFE,
- 0x90, 0x33, 0x17, 0xF6, 0xB5, 0x81, 0x02, 0xFA,
- 0x5C, 0x94, 0x3A, 0xBE, 0x22, 0xB9, 0xFC, 0x3E,
- 0x09, 0xE4, 0x76, 0xD7, 0x03, 0x38, 0x38, 0xC2,
- 0xC2, 0x0D, 0x66, 0x3C, 0xD0, 0x91, 0x5C, 0xF4,
- 0x0E, 0xC2, 0xDE, 0x46, 0x90, 0x2E, 0xF5, 0x22,
- 0xA9, 0x3D, 0x15, 0x20, 0x5F, 0x17, 0x10, 0x5A,
- 0x54, 0x63, 0x93, 0x7B, 0xC3, 0x00, 0x3D, 0x42,
- 0x73, 0xF1, 0xAD, 0xC1, 0xDE, 0x76, 0x18, 0x9C,
- 0x68, 0x17, 0xBF, 0x3B, 0xE0, 0x30, 0x82, 0x02,
- 0xF9, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
- 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x82, 0x02, 0xEA,
- 0x04, 0x82, 0x02, 0xE6, 0x30, 0x82, 0x02, 0xE2,
- 0x30, 0x82, 0x02, 0xDE, 0x06, 0x0B, 0x2A, 0x86,
- 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x0A, 0x01,
- 0x02, 0xA0, 0x82, 0x02, 0xA6, 0x30, 0x82, 0x02,
- 0xA2, 0x30, 0x1C, 0x06, 0x0A, 0x2A, 0x86, 0x48,
- 0x86, 0xF7, 0x0D, 0x01, 0x0C, 0x01, 0x03, 0x30,
- 0x0E, 0x04, 0x08, 0x34, 0x37, 0x27, 0x5F, 0xE8,
- 0xD6, 0x00, 0x0D, 0x02, 0x02, 0x08, 0x00, 0x04,
- 0x82, 0x02, 0x80, 0xC0, 0xE6, 0xB1, 0x63, 0x73,
- 0xFC, 0xBF, 0x50, 0xFB, 0x54, 0xCF, 0x67, 0x16,
- 0xF8, 0x28, 0x48, 0x13, 0x7F, 0xF2, 0xBD, 0x66,
- 0x70, 0xC7, 0xF6, 0x01, 0xD0, 0x58, 0xF4, 0xA4,
- 0xD9, 0x45, 0xE2, 0x63, 0x92, 0x7F, 0x78, 0x2B,
- 0xB6, 0xDB, 0x16, 0x44, 0x1D, 0x11, 0xCB, 0xC3,
- 0x20, 0xA9, 0x8A, 0x96, 0x13, 0xB8, 0x6E, 0xF3,
- 0xDA, 0x46, 0x05, 0x2C, 0xF9, 0x67, 0xBB, 0x05,
- 0x88, 0xC0, 0xC8, 0x60, 0x09, 0xA3, 0x82, 0x27,
- 0x33, 0xEB, 0xEE, 0x43, 0x98, 0xE9, 0xE2, 0x24,
- 0xA8, 0x06, 0xD5, 0xFF, 0xF5, 0xC0, 0x79, 0x4B,
- 0x06, 0x40, 0xE6, 0x28, 0xC6, 0x6E, 0x4E, 0x03,
- 0xCC, 0x9B, 0xB6, 0xBD, 0xB6, 0x81, 0x88, 0x5C,
- 0x34, 0x6B, 0x8B, 0x15, 0x23, 0x75, 0x21, 0xAC,
- 0x79, 0xFD, 0xDB, 0x80, 0x1D, 0x20, 0x84, 0xF1,
- 0x47, 0xAF, 0x7B, 0x40, 0x6C, 0xD2, 0x64, 0x52,
- 0x11, 0x1B, 0x01, 0x1E, 0xB5, 0xA9, 0x4B, 0xC4,
- 0x51, 0x54, 0x40, 0xE2, 0xC8, 0xEB, 0x20, 0x48,
- 0x2D, 0x40, 0xF8, 0xC6, 0x58, 0x5A, 0xE3, 0x34,
- 0xD8, 0x79, 0x04, 0xD7, 0xD6, 0x07, 0xF2, 0x12,
- 0x66, 0xC8, 0x31, 0x37, 0x71, 0x60, 0xF4, 0x75,
- 0xDC, 0x60, 0x54, 0x19, 0x6A, 0x75, 0x56, 0xC5,
- 0xA9, 0x67, 0x4A, 0x03, 0x7A, 0xFD, 0x12, 0x59,
- 0x2B, 0x74, 0xE6, 0xA5, 0xE2, 0xF8, 0xBB, 0x1E,
- 0x76, 0x96, 0xD4, 0xD4, 0x3F, 0x8B, 0xAD, 0x90,
- 0xAF, 0x04, 0x41, 0xDB, 0xD8, 0xCC, 0x2D, 0x37,
- 0x06, 0x20, 0x9B, 0xE7, 0x98, 0x87, 0x12, 0xAC,
- 0x70, 0xC9, 0xF4, 0x1C, 0x28, 0xFB, 0x2C, 0x9E,
- 0x18, 0xE1, 0x6D, 0x79, 0x34, 0xBC, 0xAC, 0xCB,
- 0x75, 0x92, 0x7E, 0x8E, 0x7C, 0xA9, 0x0B, 0x86,
- 0x4A, 0x88, 0xFB, 0xE8, 0xBE, 0x6A, 0x32, 0xEF,
- 0x58, 0xCC, 0x4C, 0x89, 0x50, 0xEF, 0xDF, 0xE0,
- 0xDD, 0x35, 0x07, 0x8C, 0x01, 0x8B, 0x57, 0x38,
- 0xB5, 0x64, 0xBB, 0x0A, 0xC2, 0xD8, 0xAB, 0xC5,
- 0x45, 0xA6, 0x83, 0xBF, 0xA6, 0xA2, 0xCC, 0x06,
- 0x64, 0xBE, 0x84, 0x04, 0x55, 0x8E, 0xF4, 0x4C,
- 0xB5, 0xBC, 0xE5, 0x97, 0x2B, 0x3C, 0x42, 0x44,
- 0x91, 0x9B, 0xB2, 0x65, 0x70, 0x02, 0xC5, 0xB7,
- 0x71, 0xB3, 0xF0, 0xAA, 0x46, 0x4F, 0x42, 0x40,
- 0x53, 0x65, 0x89, 0xA5, 0x6C, 0xBC, 0xB5, 0x6C,
- 0x0C, 0x3B, 0x50, 0x46, 0x67, 0xFA, 0x14, 0x68,
- 0x01, 0xE7, 0xA6, 0xD4, 0xB5, 0xD0, 0x82, 0x44,
- 0x92, 0x2C, 0xE3, 0x43, 0x5D, 0x34, 0x7C, 0x04,
- 0xA3, 0x4D, 0x2F, 0x5A, 0x75, 0xE7, 0x0B, 0x64,
- 0xD0, 0xAE, 0x7F, 0xCB, 0xDD, 0x7D, 0x05, 0x88,
- 0x4C, 0x34, 0xBB, 0xF4, 0x00, 0xCE, 0x1C, 0x13,
- 0x4E, 0xA3, 0xE3, 0x60, 0x4B, 0x50, 0x4E, 0xE1,
- 0x26, 0x22, 0x51, 0xD4, 0x32, 0x60, 0xC6, 0x3E,
- 0x7D, 0x4A, 0x3E, 0x56, 0x78, 0xBD, 0x5F, 0x23,
- 0x7F, 0x0A, 0xA0, 0xC1, 0x1A, 0x60, 0xA2, 0x7C,
- 0x9E, 0x17, 0x6F, 0xD8, 0x73, 0x0F, 0x1A, 0x1F,
- 0x47, 0x58, 0x44, 0x20, 0x80, 0xC6, 0x5D, 0x6E,
- 0xEC, 0xFF, 0xCA, 0x65, 0xA1, 0xFB, 0xEE, 0xF2,
- 0x56, 0x1A, 0x16, 0x9E, 0x4D, 0xCA, 0x67, 0x81,
- 0x23, 0xDE, 0xBE, 0x5E, 0x31, 0x56, 0xF0, 0x34,
- 0xBA, 0x12, 0xFC, 0x07, 0x03, 0x96, 0xD2, 0x8E,
- 0xCE, 0xA6, 0xF6, 0x74, 0x07, 0x4F, 0x63, 0x40,
- 0x14, 0x0A, 0xD6, 0x45, 0xB4, 0xF1, 0x72, 0x87,
- 0x34, 0x89, 0x5C, 0x06, 0x1B, 0x8C, 0x0E, 0xA2,
- 0x84, 0x50, 0x12, 0xAD, 0x26, 0x5B, 0x4F, 0x6B,
- 0x23, 0x9D, 0x3C, 0xBB, 0x8A, 0xDA, 0x08, 0x4B,
- 0x93, 0x47, 0x02, 0x96, 0x76, 0xD4, 0x87, 0xE9,
- 0x4B, 0x69, 0x82, 0xD6, 0xCC, 0x69, 0x02, 0xC0,
- 0xA4, 0x75, 0x7A, 0x90, 0xFD, 0xF6, 0xD6, 0x9D,
- 0xE2, 0x4C, 0xB6, 0xFA, 0x61, 0xA5, 0x7C, 0x18,
- 0xEA, 0x84, 0xA1, 0x74, 0x85, 0x2E, 0xCA, 0xF9,
- 0x17, 0x29, 0xFF, 0x67, 0x70, 0xC9, 0x6F, 0xF1,
- 0x41, 0xEF, 0xA1, 0x59, 0x54, 0xA0, 0x99, 0x14,
- 0x48, 0x74, 0x5D, 0x14, 0x3E, 0x04, 0xCE, 0xF7,
- 0x16, 0x9F, 0x8A, 0x41, 0xF4, 0xAE, 0xB3, 0x10,
- 0xCE, 0x19, 0xC2, 0x83, 0x7B, 0xD0, 0x26, 0x1E,
- 0x75, 0x8A, 0x0A, 0x40, 0x4A, 0xB8, 0xE0, 0x5C,
- 0x13, 0x8B, 0xCC, 0x6F, 0xF3, 0x00, 0xB3, 0x64,
- 0x1B, 0x3C, 0x3D, 0x08, 0x3B, 0x9F, 0xD0, 0x9B,
- 0xE5, 0x72, 0x45, 0x96, 0x95, 0x4D, 0x66, 0xC7,
- 0x79, 0x5D, 0x3A, 0x1A, 0x94, 0x64, 0x94, 0x07,
- 0x1A, 0xE8, 0x7C, 0xD1, 0x1C, 0xB1, 0x7E, 0x32,
- 0x28, 0x1A, 0x90, 0x22, 0xD9, 0x86, 0x9B, 0x9C,
- 0x9B, 0x0C, 0x04, 0x31, 0x85, 0x10, 0x42, 0x50,
- 0x40, 0x11, 0x72, 0xAB, 0x94, 0x0C, 0xAF, 0xC3,
- 0x22, 0x1A, 0xC1, 0x31, 0x25, 0x30, 0x23, 0x06,
- 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01,
- 0x09, 0x15, 0x31, 0x16, 0x04, 0x14, 0xFD, 0x78,
- 0xA7, 0x70, 0x1F, 0x8A, 0xE9, 0x07, 0xB9, 0xCA,
- 0x3C, 0xD1, 0xE8, 0xDC, 0x68, 0xFF, 0x02, 0x61,
- 0x29, 0x97, 0x30, 0x31, 0x30, 0x21, 0x30, 0x09,
- 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05,
- 0x00, 0x04, 0x14, 0x22, 0x7E, 0x99, 0x10, 0xB3,
- 0x99, 0x79, 0xE7, 0x14, 0x7F, 0x91, 0x59, 0x24,
- 0x4F, 0x2F, 0xCF, 0xE8, 0x53, 0x1D, 0x0F, 0x04,
- 0x08, 0x30, 0x1E, 0x5C, 0xE4, 0x3C, 0x66, 0xDF,
- 0xB0, 0x02, 0x02, 0x08, 0x00]
-};
-
-gTestSuite.doTestWithCertificate(
- new Blob([new Uint8Array(testCertInfo.blob)]),
- testCertInfo.password,
- testCertInfo.nickname,
- testCertInfo.usage
-);
diff --git a/dom/wifi/test/marionette/test_wifi_manage_server_certificate.js b/dom/wifi/test/marionette/test_wifi_manage_server_certificate.js
deleted file mode 100644
index dfaf524b2..000000000
--- a/dom/wifi/test/marionette/test_wifi_manage_server_certificate.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-// Binary form of test certificate.
-var testCertInfo = {
- nickname: 'Test Certificate',
- password: '',
- usage: ['ServerCert'],
- blob: [0x30, 0x82, 0x02, 0xae, 0x30, 0x82, 0x02, 0x17,
- 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00,
- 0x92, 0x49, 0xe2, 0x62, 0x71, 0xf6, 0xc7, 0x92,
- 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
- 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30,
- 0x70, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55,
- 0x04, 0x06, 0x13, 0x02, 0x54, 0x57, 0x31, 0x0f,
- 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c,
- 0x06, 0x54, 0x61, 0x69, 0x70, 0x65, 0x69, 0x31,
- 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0a,
- 0x0c, 0x07, 0x4d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c,
- 0x61, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55,
- 0x04, 0x0b, 0x0c, 0x02, 0x51, 0x41, 0x31, 0x0e,
- 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c,
- 0x05, 0x47, 0x65, 0x72, 0x72, 0x79, 0x31, 0x21,
- 0x30, 0x1f, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
- 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16, 0x12, 0x67,
- 0x63, 0x68, 0x61, 0x6e, 0x67, 0x40, 0x6d, 0x6f,
- 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0x2e, 0x63, 0x6f,
- 0x6d, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x34, 0x30,
- 0x35, 0x32, 0x33, 0x30, 0x39, 0x34, 0x32, 0x33,
- 0x37, 0x5a, 0x17, 0x0d, 0x31, 0x37, 0x30, 0x35,
- 0x32, 0x32, 0x30, 0x39, 0x34, 0x32, 0x33, 0x37,
- 0x5a, 0x30, 0x70, 0x31, 0x0b, 0x30, 0x09, 0x06,
- 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x54, 0x57,
- 0x31, 0x0f, 0x30, 0x0d, 0x06, 0x03, 0x55, 0x04,
- 0x08, 0x0c, 0x06, 0x54, 0x61, 0x69, 0x70, 0x65,
- 0x69, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55,
- 0x04, 0x0a, 0x0c, 0x07, 0x4d, 0x6f, 0x7a, 0x69,
- 0x6c, 0x6c, 0x61, 0x31, 0x0b, 0x30, 0x09, 0x06,
- 0x03, 0x55, 0x04, 0x0b, 0x0c, 0x02, 0x51, 0x41,
- 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04,
- 0x03, 0x0c, 0x05, 0x47, 0x65, 0x72, 0x72, 0x79,
- 0x31, 0x21, 0x30, 0x1f, 0x06, 0x09, 0x2a, 0x86,
- 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01, 0x16,
- 0x12, 0x67, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x40,
- 0x6d, 0x6f, 0x7a, 0x69, 0x6c, 0x6c, 0x61, 0x2e,
- 0x63, 0x6f, 0x6d, 0x30, 0x81, 0x9f, 0x30, 0x0d,
- 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
- 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8d,
- 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00,
- 0xd3, 0xdb, 0x54, 0xcc, 0xca, 0x0b, 0xee, 0xf9,
- 0x8a, 0x37, 0x0d, 0x06, 0x8b, 0x20, 0x00, 0x4a,
- 0x55, 0x84, 0x90, 0x1a, 0xb7, 0x9c, 0x91, 0xb2,
- 0x38, 0x6b, 0x8b, 0x32, 0x7a, 0x89, 0x9e, 0x79,
- 0x71, 0x88, 0x43, 0x21, 0x94, 0x18, 0xa8, 0xfc,
- 0xe3, 0x7a, 0x8a, 0xb3, 0xa1, 0xf7, 0x23, 0xe7,
- 0x1a, 0xe3, 0xe7, 0x0d, 0xf1, 0x66, 0x21, 0x58,
- 0x21, 0x85, 0x5b, 0x35, 0xec, 0x68, 0xd2, 0xfd,
- 0x44, 0x76, 0x93, 0x05, 0xbb, 0x89, 0x7d, 0x92,
- 0xf9, 0xce, 0x75, 0xa3, 0xeb, 0x39, 0xc1, 0x7d,
- 0x7e, 0x50, 0xf9, 0xb8, 0x60, 0x61, 0xf7, 0x2f,
- 0x54, 0x39, 0xfe, 0x8a, 0x20, 0xb2, 0x0d, 0x48,
- 0x7f, 0x18, 0x0d, 0x02, 0xcc, 0x7b, 0x8e, 0x31,
- 0xe9, 0xbe, 0xfc, 0x96, 0x2e, 0x63, 0x6f, 0xfa,
- 0x4c, 0xc4, 0xcf, 0x8a, 0xe4, 0x13, 0x67, 0xf1,
- 0xec, 0x3e, 0xd8, 0x23, 0xa1, 0xbf, 0x67, 0x71,
- 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x50, 0x30,
- 0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e,
- 0x04, 0x16, 0x04, 0x14, 0x13, 0xe1, 0xac, 0xa4,
- 0x75, 0x3d, 0x2c, 0x5f, 0xe5, 0x41, 0x42, 0x90,
- 0x5a, 0x48, 0x5c, 0x46, 0xbc, 0x24, 0x8e, 0xa1,
- 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04,
- 0x18, 0x30, 0x16, 0x80, 0x14, 0x13, 0xe1, 0xac,
- 0xa4, 0x75, 0x3d, 0x2c, 0x5f, 0xe5, 0x41, 0x42,
- 0x90, 0x5a, 0x48, 0x5c, 0x46, 0xbc, 0x24, 0x8e,
- 0xa1, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13,
- 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30,
- 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7,
- 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x81,
- 0x81, 0x00, 0xaa, 0x6b, 0x62, 0x53, 0x74, 0x2a,
- 0x20, 0x76, 0xab, 0xd2, 0x60, 0x06, 0xfd, 0x88,
- 0xf5, 0x1c, 0x85, 0xe6, 0x57, 0xf1, 0xf0, 0x18,
- 0x97, 0x7c, 0x70, 0xb8, 0xb4, 0x7c, 0xcc, 0x58,
- 0x8d, 0xf4, 0x7c, 0xb6, 0x34, 0xcc, 0x15, 0x79,
- 0xaf, 0x75, 0xa9, 0x0b, 0xd1, 0xea, 0xf8, 0x85,
- 0x7c, 0xe8, 0x19, 0xe9, 0x13, 0x90, 0x84, 0x5f,
- 0x21, 0x94, 0x0a, 0x4d, 0x15, 0xef, 0xd1, 0x16,
- 0xd4, 0xba, 0x2c, 0x59, 0x1b, 0x83, 0x23, 0xf5,
- 0xa5, 0xcd, 0xbd, 0xda, 0x32, 0x73, 0x46, 0x49,
- 0x98, 0xf3, 0xfb, 0x50, 0x6e, 0x30, 0xd7, 0x3e,
- 0x31, 0xd6, 0xe8, 0x65, 0x2f, 0x5a, 0xf1, 0x0f,
- 0x7b, 0x0a, 0x21, 0x61, 0x8e, 0x45, 0x29, 0x4f,
- 0x7a, 0x04, 0xda, 0x29, 0xfc, 0x6f, 0xc5, 0x5e,
- 0xee, 0xe1, 0x0f, 0xd5, 0x4b, 0xb7, 0xc9, 0x6a,
- 0x8e, 0x7c, 0x19, 0xef, 0x6e, 0x64, 0x98, 0xfe,
- 0xe3, 0x35]
-};
-
-gTestSuite.doTestWithCertificate(
- new Blob([new Uint8Array(testCertInfo.blob)]),
- testCertInfo.password,
- testCertInfo.nickname,
- testCertInfo.usage
-);
diff --git a/dom/wifi/test/marionette/test_wifi_manage_user_certificate.js b/dom/wifi/test/marionette/test_wifi_manage_user_certificate.js
deleted file mode 100644
index 950ceae4e..000000000
--- a/dom/wifi/test/marionette/test_wifi_manage_user_certificate.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-// Binary form of test certificate.
-var testCertInfo = {
- nickname: 'Test Certificate',
- password: '',
- usage: ['UserCert'],
- blob: '-----BEGIN CERTIFICATE-----\n' +
- 'MIICTjCCAbegAwIBAgICNV4wDQYJKoZIhvcNAQEEBQAwgYUxCzAJBgNVBAYTAklU\n' +
- 'MRYwFAYDVQQKEw1aZXJvc2hlbGwubmV0MRAwDgYDVQQLEwdFeGFtcGxlMR0wGwYD\n' +
- 'VQQDExRaZXJvU2hlbGwgRXhhbXBsZSBDQTEtMCsGCSqGSIb3DQEJARYeRnVsdmlv\n' +
- 'LlJpY2NpYXJkaUB6ZXJvc2hlbGwubmV0MB4XDTEzMDMxMTAzMzg1MloXDTE0MDMx\n' +
- 'MTAzMzg1MlowIzEOMAwGA1UECxMFVXNlcnMxETAPBgNVBAMTCGNodWNrbGVlMIGf\n' +
- 'MA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDvVzFhQAVqAIHW5DlAhp4FEGEei7k7\n' +
- 'uVUeqkH7JAsww6zmDLg9yZlcZAc95N0lkz022gLXehH2M0R1FOR++nkqofzWfc7w\n' +
- 'n79ith+dU2GQMeKq7vPGDYXpgIkEKbYfzKj3fY3129MlTxJQt1UD/ejz38V8HKgw\n' +
- 'qKSuwo0NVeY66QIDAQABoy4wLDALBgNVHQ8EBAMCBLAwHQYDVR0lBBYwFAYIKwYB\n' +
- 'BQUHAwIGCCsGAQUFBwMEMA0GCSqGSIb3DQEBBAUAA4GBAJWgfX5vYSD7MGZk1rTF\n' +
- 'DSziWYGqpR+Moo3qQ+9qLG8m+XVM9hckWpY31A5sWAeCZCe1SSNLFbbgsaOyPZE2\n' +
- 'NqMyvs61Vszpc2mmWAYT6j2OU2tw8p5pcUZd6eIp7Gc3fLymiX/WoSmilZKmrGUZ\n' +
- 'Q15R+TCpclUsaNrUGjybgaw7\n' +
- '-----END CERTIFICATE-----'
-};
-
-gTestSuite.doTestWithCertificate(
- new Blob([testCertInfo.blob]),
- testCertInfo.password,
- testCertInfo.nickname,
- testCertInfo.usage
-);
diff --git a/dom/wifi/test/marionette/test_wifi_scan.js b/dom/wifi/test/marionette/test_wifi_scan.js
deleted file mode 100644
index 4bb7d1a3d..000000000
--- a/dom/wifi/test/marionette/test_wifi_scan.js
+++ /dev/null
@@ -1,43 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const SCAN_RETRY_CNT = 5;
-
-/**
- * Test scan with no AP present.
- *
- * The precondition is:
- * 1) Wifi is enabled.
- * 2) All the hostapds are turned off.
- *
- * @return deferred promise.
- */
-function testScanNoAp() {
- return gTestSuite.testWifiScanWithRetry(SCAN_RETRY_CNT, []);
-}
-
-/**
- * Test scan with APs present.
- *
- * The precondition is:
- * 1) Wifi is enabled.
- * 2) All the hostapds are turned off.
- *
- * @return deferred promise.
- */
-function testScanWithAps() {
- return gTestSuite.startHostapds(HOSTAPD_CONFIG_LIST)
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', HOSTAPD_CONFIG_LIST.length))
- .then(() => gTestSuite.testWifiScanWithRetry(SCAN_RETRY_CNT, HOSTAPD_CONFIG_LIST))
- .then(gTestSuite.killAllHostapd)
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', 0));
-}
-
-gTestSuite.doTestWithoutStockAp(function() {
- return gTestSuite.ensureWifiEnabled(true)
- .then(testScanNoAp)
- .then(testScanWithAps);
-});
diff --git a/dom/wifi/test/marionette/test_wifi_static_ip.js b/dom/wifi/test/marionette/test_wifi_static_ip.js
deleted file mode 100644
index 90436b6fe..000000000
--- a/dom/wifi/test/marionette/test_wifi_static_ip.js
+++ /dev/null
@@ -1,65 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const STATIC_IP_CONFIG = {
- enabled: true,
- ipaddr: "192.168.111.222",
- proxy: "",
- maskLength: 24,
- gateway: "192.168.111.1",
- dns1: "8.8.8.8",
- dns2: "8.8.4.4",
-};
-
-const TESTING_HOSTAPD = [{ ssid: 'ap0' }];
-
-function testAssociateWithStaticIp(aNetwork, aStaticIpConfig) {
- return gTestSuite.setStaticIpMode(aNetwork, aStaticIpConfig)
- .then(() => gTestSuite.testAssociate(aNetwork))
- // Check ip address and prefix.
- .then(() => gTestSuite.exeAndParseNetcfg())
- .then((aResult) => {
- is(aResult["wlan0"].ip, aStaticIpConfig.ipaddr, "Check ip address");
- is(aResult["wlan0"].prefix, aStaticIpConfig.maskLength, "Check prefix");
- })
- // Check routing.
- .then(() => gTestSuite.exeAndParseIpRoute())
- .then((aResult) => {
- is(aResult["wlan0"].src, aStaticIpConfig.ipaddr, "Check ip address");
- is(aResult["wlan0"].default, true, "Check default route");
- is(aResult["wlan0"].gateway, aStaticIpConfig.gateway, "Check gateway");
- });
-}
-
-function findDesireNetwork(aNetworks) {
- let i = gTestSuite.getFirstIndexBySsid(TESTING_HOSTAPD[0].ssid, aNetworks);
-
- if (-1 !== i) {
- return aNetworks[i];
- }
-
- return aNetworks[0];
-}
-
-// Start test.
-gTestSuite.doTestWithoutStockAp(function() {
- return gTestSuite.ensureWifiEnabled(true)
-
- // Start custom hostapd for testing.
- .then(() => gTestSuite.startHostapds(TESTING_HOSTAPD))
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd',
- TESTING_HOSTAPD.length))
-
- // Perform a wifi scan, and then run the static ip test
- .then(() => gTestSuite.requestWifiScan())
- .then((aNetworks) => findDesireNetwork(aNetworks))
- .then((aNetwork) => testAssociateWithStaticIp(aNetwork,
- STATIC_IP_CONFIG))
-
- // Kill running hostapd.
- .then(gTestSuite.killAllHostapd)
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', 0));
-});
diff --git a/dom/wifi/test/marionette/test_wifi_tethering_wifi_active.js b/dom/wifi/test/marionette/test_wifi_tethering_wifi_active.js
deleted file mode 100644
index af0df01a0..000000000
--- a/dom/wifi/test/marionette/test_wifi_tethering_wifi_active.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-const TESTING_HOSTAPD = [{ ssid: 'ap0' }];
-
-function connectToFirstNetwork() {
- let firstNetwork;
- return gTestSuite.requestWifiScan()
- .then(function (networks) {
- firstNetwork = networks[0];
- return gTestSuite.testAssociate(firstNetwork);
- })
- .then(() => firstNetwork);
-}
-
-gTestSuite.doTestTethering(function() {
- let firstNetwork;
-
- return gTestSuite.ensureWifiEnabled(true)
- // Start custom hostapd for testing.
- .then(() => gTestSuite.startHostapds(TESTING_HOSTAPD))
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', TESTING_HOSTAPD.length))
-
- // Connect to the testing AP and wait for data becoming disconnected.
- .then(function () {
- return Promise.all([
- // 1) Set up the event listener first:
- // RIL data should become disconnected after connecting to wifi.
- gTestSuite.waitForRilDataConnected(false),
-
- // 2) Connect to the first scanned network.
- connectToFirstNetwork()
- .then(aFirstNetwork => firstNetwork = aFirstNetwork)
- ]);
- })
- .then(function() {
- return Promise.all([
- // 1) Set up the event listeners first:
- // Wifi should be turned off and RIL data should be connected.
- gTestSuite.waitForWifiManagerEventOnce('disabled'),
- gTestSuite.waitForRilDataConnected(true),
-
- // 2) Start wifi tethering.
- gTestSuite.requestTetheringEnabled(true)
- ]);
- })
- .then(function() {
- return Promise.all([
- // 1) Set up the event listeners first:
- // Wifi should be enabled, RIL data should become disconnected and
- // we should connect to an wifi AP.
- gTestSuite.waitForWifiManagerEventOnce('enabled'),
-
- // Due to Bug 1168285, after re-enablin wifi, the remembered network
- // will not be connected automatically. Leave "auto connect test"
- // covered by test_wifi_auto_connect.js.
- //gTestSuite.waitForRilDataConnected(false),
- //gTestSuite.waitForConnected(firstNetwork),
-
- // 2) Stop wifi tethering.
- gTestSuite.requestTetheringEnabled(false)
- ]);
- })
- // Remove wlan0 from default route by disabling wifi. Otherwise,
- // it will cause the subsequent test cases loading page error.
- .then(() => gTestSuite.requestWifiEnabled(false))
-
- // Kill running hostapd.
- .then(gTestSuite.killAllHostapd)
- .then(() => gTestSuite.verifyNumOfProcesses('hostapd', 0));
-}); \ No newline at end of file
diff --git a/dom/wifi/test/marionette/test_wifi_tethering_wifi_disabled.js b/dom/wifi/test/marionette/test_wifi_tethering_wifi_disabled.js
deleted file mode 100644
index 860a91cf6..000000000
--- a/dom/wifi/test/marionette/test_wifi_tethering_wifi_disabled.js
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-gTestSuite.doTestTethering(function() {
- return gTestSuite.ensureWifiEnabled(false)
- .then(() => gTestSuite.requestTetheringEnabled(true))
- .then(() => gTestSuite.requestTetheringEnabled(false))
-});
diff --git a/dom/wifi/test/marionette/test_wifi_tethering_wifi_inactive.js b/dom/wifi/test/marionette/test_wifi_tethering_wifi_inactive.js
deleted file mode 100644
index 2de6ab667..000000000
--- a/dom/wifi/test/marionette/test_wifi_tethering_wifi_inactive.js
+++ /dev/null
@@ -1,21 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-MARIONETTE_TIMEOUT = 60000;
-MARIONETTE_HEAD_JS = 'head.js';
-
-gTestSuite.doTestTethering(function() {
- return gTestSuite.ensureWifiEnabled(true)
- .then(function() {
- return Promise.all([
- gTestSuite.waitForWifiManagerEventOnce('disabled'),
- gTestSuite.requestTetheringEnabled(true)
- ]);
- })
- .then(function() {
- return Promise.all([
- gTestSuite.waitForWifiManagerEventOnce('enabled'),
- gTestSuite.requestTetheringEnabled(false)
- ]);
- });
-});
diff --git a/dom/workers/ServiceWorkerEvents.cpp b/dom/workers/ServiceWorkerEvents.cpp
index 780b2f5f8..1f79e2c92 100644
--- a/dom/workers/ServiceWorkerEvents.cpp
+++ b/dom/workers/ServiceWorkerEvents.cpp
@@ -12,6 +12,7 @@
#include "nsINetworkInterceptController.h"
#include "nsIOutputStream.h"
#include "nsIScriptError.h"
+#include "nsITimedChannel.h"
#include "nsIUnicodeDecoder.h"
#include "nsIUnicodeEncoder.h"
#include "nsContentPolicyUtils.h"
@@ -108,6 +109,12 @@ NS_IMETHODIMP
CancelChannelRunnable::Run()
{
MOZ_ASSERT(NS_IsMainThread());
+
+ // TODO: When bug 1204254 is implemented, this time marker should be moved to
+ // the point where the body of the network request is complete.
+ mChannel->SetHandleFetchEventEnd(TimeStamp::Now());
+ mChannel->SaveTimeStampsToUnderlyingChannel();
+
mChannel->Cancel(mStatus);
mRegistration->MaybeScheduleUpdate();
return NS_OK;
@@ -230,6 +237,9 @@ public:
return NS_OK;
}
+ mChannel->SetHandleFetchEventEnd(TimeStamp::Now());
+ mChannel->SaveTimeStampsToUnderlyingChannel();
+
nsCOMPtr<nsIObserverService> obsService = services::GetObserverService();
if (obsService) {
obsService->NotifyObservers(underlyingChannel, "service-worker-synthesized-response", nullptr);
diff --git a/dom/workers/ServiceWorkerPrivate.cpp b/dom/workers/ServiceWorkerPrivate.cpp
index eaa548f95..24b2e11e6 100644
--- a/dom/workers/ServiceWorkerPrivate.cpp
+++ b/dom/workers/ServiceWorkerPrivate.cpp
@@ -13,6 +13,7 @@
#include "nsINetworkInterceptController.h"
#include "nsIPushErrorReporter.h"
#include "nsISupportsImpl.h"
+#include "nsITimedChannel.h"
#include "nsIUploadChannel2.h"
#include "nsNetUtil.h"
#include "nsProxyRelease.h"
@@ -1255,6 +1256,7 @@ class FetchEventRunnable : public ExtendableFunctionalEventWorkerRunnable
nsCString mMethod;
nsString mClientId;
bool mIsReload;
+ bool mMarkLaunchServiceWorkerEnd;
RequestCache mCacheMode;
RequestMode mRequestMode;
RequestRedirect mRequestRedirect;
@@ -1273,13 +1275,15 @@ public:
const nsACString& aScriptSpec,
nsMainThreadPtrHandle<ServiceWorkerRegistrationInfo>& aRegistration,
const nsAString& aDocumentId,
- bool aIsReload)
+ bool aIsReload,
+ bool aMarkLaunchServiceWorkerEnd)
: ExtendableFunctionalEventWorkerRunnable(
aWorkerPrivate, aKeepAliveToken, aRegistration)
, mInterceptedChannel(aChannel)
, mScriptSpec(aScriptSpec)
, mClientId(aDocumentId)
, mIsReload(aIsReload)
+ , mMarkLaunchServiceWorkerEnd(aMarkLaunchServiceWorkerEnd)
, mCacheMode(RequestCache::Default)
, mRequestMode(RequestMode::No_cors)
, mRequestRedirect(RequestRedirect::Follow)
@@ -1417,6 +1421,12 @@ public:
WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override
{
MOZ_ASSERT(aWorkerPrivate);
+
+ if (mMarkLaunchServiceWorkerEnd) {
+ mInterceptedChannel->SetLaunchServiceWorkerEnd(TimeStamp::Now());
+ }
+
+ mInterceptedChannel->SetDispatchFetchEventEnd(TimeStamp::Now());
return DispatchFetchEvent(aCx, aWorkerPrivate);
}
@@ -1445,6 +1455,10 @@ private:
NS_IMETHOD Run() override
{
AssertIsOnMainThread();
+
+ mChannel->SetHandleFetchEventEnd(TimeStamp::Now());
+ mChannel->SaveTimeStampsToUnderlyingChannel();
+
nsresult rv = mChannel->ResetInterception();
NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
"Failed to resume intercepted network request");
@@ -1520,6 +1534,8 @@ private:
event->PostInit(mInterceptedChannel, mRegistration, mScriptSpec);
event->SetTrusted(true);
+ mInterceptedChannel->SetHandleFetchEventStart(TimeStamp::Now());
+
RefPtr<EventTarget> target = do_QueryObject(aWorkerPrivate->GlobalScope());
nsresult rv2 = target->DispatchDOMEvent(nullptr, event, nullptr, nullptr);
if (NS_WARN_IF(NS_FAILED(rv2)) || !event->WaitToRespond()) {
@@ -1614,9 +1630,21 @@ ServiceWorkerPrivate::SendFetchEvent(nsIInterceptedChannel* aChannel,
nsCOMPtr<nsIRunnable> failRunnable =
NewRunnableMethod(aChannel, &nsIInterceptedChannel::ResetInterception);
- nsresult rv = SpawnWorkerIfNeeded(FetchEvent, failRunnable, aLoadGroup);
+ aChannel->SetLaunchServiceWorkerStart(TimeStamp::Now());
+ aChannel->SetDispatchFetchEventStart(TimeStamp::Now());
+
+ bool newWorkerCreated = false;
+ nsresult rv = SpawnWorkerIfNeeded(FetchEvent,
+ failRunnable,
+ &newWorkerCreated,
+ aLoadGroup);
+
NS_ENSURE_SUCCESS(rv, rv);
+ if (!newWorkerCreated) {
+ aChannel->SetLaunchServiceWorkerEnd(TimeStamp::Now());
+ }
+
nsMainThreadPtrHandle<nsIInterceptedChannel> handle(
new nsMainThreadPtrHolder<nsIInterceptedChannel>(aChannel, false));
@@ -1646,7 +1674,7 @@ ServiceWorkerPrivate::SendFetchEvent(nsIInterceptedChannel* aChannel,
RefPtr<FetchEventRunnable> r =
new FetchEventRunnable(mWorkerPrivate, token, handle,
mInfo->ScriptSpec(), regInfo,
- aDocumentId, aIsReload);
+ aDocumentId, aIsReload, newWorkerCreated);
rv = r->Init();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
@@ -1669,6 +1697,7 @@ ServiceWorkerPrivate::SendFetchEvent(nsIInterceptedChannel* aChannel,
nsresult
ServiceWorkerPrivate::SpawnWorkerIfNeeded(WakeUpReason aWhy,
nsIRunnable* aLoadFailedRunnable,
+ bool* aNewWorkerCreated,
nsILoadGroup* aLoadGroup)
{
AssertIsOnMainThread();
@@ -1679,6 +1708,12 @@ ServiceWorkerPrivate::SpawnWorkerIfNeeded(WakeUpReason aWhy,
// the overriden load group when intercepting a fetch.
MOZ_ASSERT_IF(aWhy == FetchEvent, aLoadGroup);
+ // Defaults to no new worker created, but if there is one, we'll set the value
+ // to true at the end of this function.
+ if (aNewWorkerCreated) {
+ *aNewWorkerCreated = false;
+ }
+
if (mWorkerPrivate) {
mWorkerPrivate->UpdateOverridenLoadGroup(aLoadGroup);
RenewKeepAliveToken(aWhy);
@@ -1762,6 +1797,10 @@ ServiceWorkerPrivate::SpawnWorkerIfNeeded(WakeUpReason aWhy,
RenewKeepAliveToken(aWhy);
+ if (aNewWorkerCreated) {
+ *aNewWorkerCreated = true;
+ }
+
return NS_OK;
}
diff --git a/dom/workers/ServiceWorkerPrivate.h b/dom/workers/ServiceWorkerPrivate.h
index 8d59ea1d0..911b07a11 100644
--- a/dom/workers/ServiceWorkerPrivate.h
+++ b/dom/workers/ServiceWorkerPrivate.h
@@ -189,6 +189,7 @@ private:
nsresult
SpawnWorkerIfNeeded(WakeUpReason aWhy,
nsIRunnable* aLoadFailedRunnable,
+ bool* aNewWorkerCreated = nullptr,
nsILoadGroup* aLoadGroup = nullptr);
~ServiceWorkerPrivate();
diff --git a/dom/workers/WorkerPrivate.cpp b/dom/workers/WorkerPrivate.cpp
index bd8a33032..8848e881a 100644
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -2419,8 +2419,6 @@ WorkerPrivateParent<Derived>::WorkerPrivateParent(
MOZ_ASSERT_IF(mIsChromeWorker, mIsSecureContext);
MOZ_ASSERT(IsDedicatedWorker());
- mNowBaseTimeStamp = aParent->NowBaseTimeStamp();
- mNowBaseTimeHighRes = aParent->NowBaseTime();
if (aParent->mParentFrozen) {
Freeze(nullptr);
@@ -2451,18 +2449,6 @@ WorkerPrivateParent<Derived>::WorkerPrivateParent(
.creationOptions().setSecureContext(true);
}
- if (IsDedicatedWorker() && mLoadInfo.mWindow &&
- mLoadInfo.mWindow->GetPerformance()) {
- mNowBaseTimeStamp = mLoadInfo.mWindow->GetPerformance()->GetDOMTiming()->
- GetNavigationStartTimeStamp();
- mNowBaseTimeHighRes =
- mLoadInfo.mWindow->GetPerformance()->GetDOMTiming()->
- GetNavigationStartHighRes();
- } else {
- mNowBaseTimeStamp = CreationTimeStamp();
- mNowBaseTimeHighRes = CreationTime();
- }
-
// Our parent can get suspended after it initiates the async creation
// of a new worker thread. In this case suspend the new worker as well.
if (mLoadInfo.mWindow && mLoadInfo.mWindow->IsSuspended()) {
diff --git a/dom/workers/WorkerPrivate.h b/dom/workers/WorkerPrivate.h
index 465c0f9a3..28283bed7 100644
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -216,8 +216,6 @@ private:
WorkerType mWorkerType;
TimeStamp mCreationTimeStamp;
DOMHighResTimeStamp mCreationTimeHighRes;
- TimeStamp mNowBaseTimeStamp;
- DOMHighResTimeStamp mNowBaseTimeHighRes;
protected:
// The worker is owned by its thread, which is represented here. This is set
@@ -579,14 +577,11 @@ public:
return mCreationTimeHighRes;
}
- TimeStamp NowBaseTimeStamp() const
+ DOMHighResTimeStamp TimeStampToDOMHighRes(const TimeStamp& aTimeStamp) const
{
- return mNowBaseTimeStamp;
- }
-
- DOMHighResTimeStamp NowBaseTime() const
- {
- return mNowBaseTimeHighRes;
+ MOZ_ASSERT(!aTimeStamp.IsNull());
+ TimeDuration duration = aTimeStamp - mCreationTimeStamp;
+ return duration.ToMilliseconds();
}
nsIPrincipal*
diff --git a/dom/workers/test/serviceworkers/chrome.ini b/dom/workers/test/serviceworkers/chrome.ini
index e064e7fd0..6d7dbebd0 100644
--- a/dom/workers/test/serviceworkers/chrome.ini
+++ b/dom/workers/test/serviceworkers/chrome.ini
@@ -3,6 +3,8 @@ skip-if = os == 'android'
support-files =
chrome_helpers.js
empty.js
+ fetch.js
+ hello.html
serviceworker.html
serviceworkerinfo_iframe.html
serviceworkermanager_iframe.html
@@ -10,6 +12,7 @@ support-files =
worker.js
worker2.js
+[test_devtools_serviceworker_interception.html]
[test_privateBrowsing.html]
[test_serviceworkerinfo.xul]
[test_serviceworkermanager.xul]
diff --git a/dom/workers/test/serviceworkers/test_devtools_serviceworker_interception.html b/dom/workers/test/serviceworkers/test_devtools_serviceworker_interception.html
new file mode 100644
index 000000000..d49ebb2c9
--- /dev/null
+++ b/dom/workers/test/serviceworkers/test_devtools_serviceworker_interception.html
@@ -0,0 +1,168 @@
+<!--
+ Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Bug 1168875 - test devtools serviceworker interception.</title>
+ <script type="application/javascript"
+ src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+ <link rel="stylesheet"
+ type="text/css"
+ href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+</head>
+<body>
+<p id="display"></p>
+<div id="content" style="display: none"></div>
+<pre id="test"></pre>
+<script class="testbody" type="text/javascript">
+
+// Constants
+const Ci = Components.interfaces;
+const workerScope = "http://mochi.test:8888/chrome/dom/workers/test/serviceworkers/";
+const workerURL = workerScope + "fetch.js";
+const contentPage = workerScope + "hello.html";
+
+function createTestWindow(aURL) {
+ var mainwindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebNavigation)
+ .QueryInterface(Ci.nsIDocShellTreeItem)
+ .rootTreeItem
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindow);
+ var win = mainwindow.OpenBrowserWindow(contentPage);
+
+ return new Promise(aResolve => {
+ win.addEventListener("DOMContentLoaded", function callback() {
+ if (win.content.location.href != aURL) {
+ win.gBrowser.loadURI(aURL);
+ return;
+ }
+
+ win.removeEventListener("DOMContentLoaded", callback);
+ aResolve(win.content);
+ });
+ });
+}
+
+function executeTest(aWindow) {
+ var registration;
+
+ return Promise.resolve()
+ // Should not be intercepted.
+ .then(_ => fetchAndCheckTimedChannel(aWindow, false, true, "hello.html"))
+
+ // Regist a service worker.
+ .then(_ => register(aWindow, workerURL, workerScope))
+ .then(r => registration = r)
+
+ // Should be intercpeted and synthesized.
+ .then(_ => fetchAndCheckTimedChannel(aWindow, true, false, "fake.html"))
+
+ // Should be intercepted but still fetch from network.
+ .then(_ => fetchAndCheckTimedChannel(aWindow, true, true,
+ "hello.html?ForBypassingHttpCache"))
+
+ // Tear down
+ .then(_ => registration.unregister());
+}
+
+function register(aWindow, aURL, aScope) {
+ return aWindow.navigator.serviceWorker.register(aURL, {scope: aScope})
+ .then(r => {
+ var worker = r.installing;
+ return new Promise(function(aResolve) {
+ worker.onstatechange = function() {
+ if (worker.state == "activated") {
+ aResolve(r);
+ }
+ }
+ });
+ });
+}
+
+function fetchAndCheckTimedChannel(aWindow, aIntercepted, aFetch, aURL) {
+ var resolveFunction;
+ var promise = new Promise(aResolve => resolveFunction = aResolve);
+
+ var topic = aFetch ? "http-on-examine-response"
+ : "service-worker-synthesized-response";
+
+ function observer(aSubject) {
+ var channel = aSubject.QueryInterface(Ci.nsIChannel);
+ ok(channel.URI.spec.endsWith(aURL));
+
+ var tc = aSubject.QueryInterface(Ci.nsITimedChannel);
+
+ // Check service worker related timings.
+ var serviceWorkerTimings = [{start: tc.launchServiceWorkerStartTime,
+ end: tc.launchServiceWorkerEndTime},
+ {start: tc.dispatchFetchEventStartTime,
+ end: tc.dispatchFetchEventEndTime},
+ {start: tc.handleFetchEventStartTime,
+ end: tc.handleFetchEventEndTime}];
+ if (aIntercepted) {
+ serviceWorkerTimings.reduce((aPreviousTimings, aCurrentTimings) => {
+ ok(aPreviousTimings.start <= aCurrentTimings.start,
+ "Start time order check.");
+ ok(aPreviousTimings.end <= aCurrentTimings.end,
+ "End time order check.");
+ ok(aCurrentTimings.start <= aCurrentTimings.end,
+ "Start time should be smaller than end time.");
+ return aCurrentTimings;
+ });
+ } else {
+ serviceWorkerTimings.forEach(aTimings => {
+ is(aTimings.start, 0);
+ is(aTimings.end, 0);
+ });
+ }
+
+ // Check network related timings.
+ var networkTimings = [tc.domainLookupStartTime,
+ tc.domainLookupEndTime,
+ tc.connectStartTime,
+ tc.connectEndTime,
+ tc.requestStartTime,
+ tc.responseStartTime,
+ tc.responseEndTime];
+ if (aFetch) {
+ networkTimings.reduce((aPreviousTiming, aCurrentTiming) => {
+ ok(aPreviousTiming <= aCurrentTiming);
+ return aCurrentTiming;
+ });
+ } else {
+ networkTimings.forEach(aTiming => is(aTiming, 0));
+ }
+
+ SpecialPowers.removeObserver(observer, topic);
+ resolveFunction();
+ }
+
+ SpecialPowers.addObserver(observer, topic, false);
+
+ // return promise;
+ return Promise.all([aWindow.fetch(aURL), promise]);
+}
+
+function runTest() {
+ return Promise.resolve()
+ .then(_ => createTestWindow(contentPage))
+ .then(w => executeTest(w))
+ .catch(e => ok(false, "Some test failed with error " + e))
+ .then(_ => SimpleTest.finish());
+}
+
+SimpleTest.waitForExplicitFinish();
+SpecialPowers.pushPrefEnv({"set": [
+ ["dom.serviceWorkers.exemptFromPerDomainMax", true],
+ ["dom.serviceWorkers.enabled", true],
+ ["dom.serviceWorkers.testing.enabled", true],
+]}, runTest);
+
+</script>
+</pre>
+</body>
+</html>
+
diff --git a/dom/workers/test/serviceworkers/test_serviceworker_interfaces.js b/dom/workers/test/serviceworkers/test_serviceworker_interfaces.js
index 9dbfcc099..b337b13ba 100644
--- a/dom/workers/test/serviceworkers/test_serviceworker_interfaces.js
+++ b/dom/workers/test/serviceworkers/test_serviceworker_interfaces.js
@@ -38,7 +38,7 @@ var ecmaGlobals =
"Int32Array",
"Int8Array",
"InternalError",
- {name: "Intl", android: false},
+ "Intl",
"Iterator",
"JSON",
"Map",
@@ -172,9 +172,9 @@ var interfaceNamesInGlobalScope =
// IMPORTANT: Do not change this list without review from a DOM peer!
"PerformanceMeasure",
// IMPORTANT: Do not change this list without review from a DOM peer!
- { name: "PerformanceObserver", nightly: true },
+ "PerformanceObserver",
// IMPORTANT: Do not change this list without review from a DOM peer!
- { name: "PerformanceObserverEntryList", nightly: true },
+ "PerformanceObserverEntryList",
// IMPORTANT: Do not change this list without review from a DOM peer!
"Request",
// IMPORTANT: Do not change this list without review from a DOM peer!
diff --git a/dom/workers/test/test_worker_interfaces.js b/dom/workers/test/test_worker_interfaces.js
index e0647682c..159278f9a 100644
--- a/dom/workers/test/test_worker_interfaces.js
+++ b/dom/workers/test/test_worker_interfaces.js
@@ -38,7 +38,7 @@ var ecmaGlobals =
"Int32Array",
"Int8Array",
"InternalError",
- {name: "Intl", android: false},
+ "Intl",
"Iterator",
"JSON",
"Map",
@@ -163,9 +163,9 @@ var interfaceNamesInGlobalScope =
// IMPORTANT: Do not change this list without review from a DOM peer!
"PerformanceMeasure",
// IMPORTANT: Do not change this list without review from a DOM peer!
- { name: "PerformanceObserver", nightly: true },
+ "PerformanceObserver",
// IMPORTANT: Do not change this list without review from a DOM peer!
- { name: "PerformanceObserverEntryList", nightly: true },
+ "PerformanceObserverEntryList",
// IMPORTANT: Do not change this list without review from a DOM peer!
"Request",
// IMPORTANT: Do not change this list without review from a DOM peer!
diff --git a/dom/xhr/tests/mochitest.ini b/dom/xhr/tests/mochitest.ini
index 35ba1e3db..a2a52787a 100644
--- a/dom/xhr/tests/mochitest.ini
+++ b/dom/xhr/tests/mochitest.ini
@@ -68,13 +68,11 @@ support-files =
[test_bug1300552.html]
[test_html_in_xhr.html]
[test_relativeLoad.html]
-skip-if = buildapp == 'b2g' # b2g(Failed to load script: relativeLoad_import.js) b2g-debug(Failed to load script: relativeLoad_import.js) b2g-desktop(Failed to load script: relativeLoad_import.js)
[test_sync_xhr_timer.xhtml]
skip-if = toolkit == 'android'
[test_sync_xhr_unload.html]
[test_temporaryFileBlob.html]
[test_worker_terminateSyncXHR.html]
-skip-if = buildapp == 'b2g'
[test_worker_xhr.html]
[test_worker_xhr2.html]
[test_worker_xhr_3rdparty.html]
@@ -82,7 +80,6 @@ skip-if = buildapp == 'b2g'
[test_worker_xhr_headers.html]
[test_worker_xhr_implicit_cancel.html]
[test_worker_xhr_parameters.html]
-skip-if = buildapp == 'b2g'
[test_worker_xhr_responseURL.html]
[test_worker_xhr_system.html]
[test_worker_xhr_timeout.html]
@@ -96,17 +93,13 @@ skip-if = toolkit == 'android'
[test_XHR_header.html]
[test_XHR_onuploadprogress.html]
[test_xhr_overridemimetype_throws_on_invalid_state.html]
-skip-if = buildapp == 'b2g' # Requires webgl support
[test_XHR_parameters.html]
-skip-if = buildapp == 'b2g' # b2g(86 total, 4 failing - testing mozAnon - got false, expected true) b2g-debug(86 total, 4 failing - testing mozAnon - got false, expected true) b2g-desktop(86 total, 4 failing - testing mozAnon - got false, expected true)
[test_xhr_progressevents.html]
skip-if = toolkit == 'android'
[test_xhr_send.html]
[test_xhr_send_readystate.html]
[test_XHR_system.html]
-skip-if = (buildapp == 'b2g' && (toolkit != 'gonk' || debug)) # b2g-debug(12 total, 2 failing - .mozSystem == true - got false, expected true + ) b2g-desktop(12 total, 2 failing - .mozSystem == true - got false, expected true + )
[test_XHR_timeout.html]
-skip-if = buildapp == 'b2g' || (android_version == '18' && debug) # b2g(flaky on B2G, bug 960743) b2g-debug(flaky on B2G, bug 960743) b2g-desktop(flaky on B2G, bug 960743)
support-files = test_XHR_timeout.js
[test_xhr_withCredentials.html]
[test_XHRDocURI.html]
diff --git a/dom/xslt/xpath/txXPCOMExtensionFunction.cpp b/dom/xslt/xpath/txXPCOMExtensionFunction.cpp
index 4913702aa..032161722 100644
--- a/dom/xslt/xpath/txXPCOMExtensionFunction.cpp
+++ b/dom/xslt/xpath/txXPCOMExtensionFunction.cpp
@@ -322,7 +322,7 @@ public:
void trace(JSTracer* trc) {
for (uint8_t i = 0; i < mCount; ++i) {
if (mArray[i].type == nsXPTType::T_JSVAL) {
- JS::UnsafeTraceRoot(trc, &mArray[i].val.j, "txParam value");
+ JS::UnsafeTraceRoot(trc, &mArray[i].val.j.asValueRef(), "txParam value");
}
}
}
diff --git a/editor/libeditor/tests/browser.ini b/editor/libeditor/tests/browser.ini
index 249f59aa8..bd234fc8d 100644
--- a/editor/libeditor/tests/browser.ini
+++ b/editor/libeditor/tests/browser.ini
@@ -1,6 +1,8 @@
[browser_bug527935.js]
skip-if = toolkit == 'android'
-support-files = bug527935.html
+support-files =
+ bug527935.html
+ bug527935_2.html
[browser_bug629172.js]
skip-if = toolkit == 'android'
support-files = bug629172.html
diff --git a/editor/libeditor/tests/bug527935.html b/editor/libeditor/tests/bug527935.html
index 4bfa1bac2..1731734d2 100644
--- a/editor/libeditor/tests/bug527935.html
+++ b/editor/libeditor/tests/bug527935.html
@@ -3,7 +3,7 @@
<body>
<div id="content">
<iframe id="formTarget" name="formTarget"></iframe>
- <form action="data:text/html," target="formTarget">
+ <form action="bug527935_2.html" target="formTarget">
<input name="test" id="initValue"><input type="submit">
</form>
</div>
diff --git a/editor/libeditor/tests/bug527935_2.html b/editor/libeditor/tests/bug527935_2.html
new file mode 100644
index 000000000..96af0721d
--- /dev/null
+++ b/editor/libeditor/tests/bug527935_2.html
@@ -0,0 +1 @@
+<html><body>dummy page</body></html>
diff --git a/editor/libeditor/tests/file_bug635636_2.html b/editor/libeditor/tests/file_bug635636_2.html
new file mode 100644
index 000000000..bf0c8101f
--- /dev/null
+++ b/editor/libeditor/tests/file_bug635636_2.html
@@ -0,0 +1 @@
+<html><body>2</body></html>
diff --git a/editor/libeditor/tests/file_bug966155.html b/editor/libeditor/tests/file_bug966155.html
new file mode 100644
index 000000000..04f55a918
--- /dev/null
+++ b/editor/libeditor/tests/file_bug966155.html
@@ -0,0 +1 @@
+<input><iframe onload="contentDocument.designMode = 'on';">
diff --git a/editor/libeditor/tests/file_bug966552.html b/editor/libeditor/tests/file_bug966552.html
new file mode 100644
index 000000000..5061c2e40
--- /dev/null
+++ b/editor/libeditor/tests/file_bug966552.html
@@ -0,0 +1 @@
+<body onload="document.designMode='on'">test</body>
diff --git a/editor/libeditor/tests/test_bug966155.html b/editor/libeditor/tests/test_bug966155.html
index 524b15d69..1e7ed67f3 100644
--- a/editor/libeditor/tests/test_bug966155.html
+++ b/editor/libeditor/tests/test_bug966155.html
@@ -18,13 +18,10 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=966155
<script class="testbody" type="text/javascript">
SimpleTest.waitForExplicitFinish();
-addLoadEvent(function() {
- var win = window.open("data:text/html,<input><iframe onload=\"contentDocument.designMode = 'on';\">", "", "test-966155");
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- runTest(win);
- }, false);
-});
+var win = window.open("file_bug966155.html", "", "test-966155");
+win.addEventListener("load", function() {
+ runTest(win);
+}, {once: true});
function runTest(win) {
SimpleTest.waitForFocus(function() {
@@ -38,14 +35,14 @@ function runTest(win) {
"test".split("").forEach(function(letter) {
synthesizeKey(letter, {}, win);
});
- is(iframeDoc.body.textContent, "test", "entered the text");
+ is(iframeDoc.body.textContent.trim(), "test", "entered the text");
// focus the input box
input.focus();
// press tab
synthesizeKey("VK_TAB", {}, win);
// Now press Ctrl+Backspace
synthesizeKey("VK_BACK_SPACE", {ctrlKey: true}, win);
- is(iframeDoc.body.textContent, "", "deleted the text");
+ is(iframeDoc.body.textContent.trim(), "", "deleted the text");
win.close();
SimpleTest.finish();
}, win);
diff --git a/editor/libeditor/tests/test_bug966552.html b/editor/libeditor/tests/test_bug966552.html
index 3d0ec5fe3..e18883aad 100644
--- a/editor/libeditor/tests/test_bug966552.html
+++ b/editor/libeditor/tests/test_bug966552.html
@@ -18,13 +18,10 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=966552
<script class="testbody" type="text/javascript">
SimpleTest.waitForExplicitFinish();
-addLoadEvent(function() {
- var win = window.open("data:text/html,<body onload=\"document.designMode='on'\">test</body>", "", "test-966552");
- win.addEventListener("load", function onLoad() {
- win.removeEventListener("load", onLoad);
- runTest(win);
- }, false);
-});
+var win = window.open("file_bug966552.html", "", "test-966552");
+win.addEventListener("load", function() {
+ runTest(win);
+}, {once: true});
function runTest(win) {
SimpleTest.waitForFocus(function() {
@@ -33,7 +30,7 @@ function runTest(win) {
doc.body.focus();
sel.collapse(doc.body.firstChild, 2);
synthesizeKey("VK_BACK_SPACE", {ctrlKey: true}, win);
- is(doc.body.textContent, "st");
+ is(doc.body.textContent.trim(), "st");
win.close();
SimpleTest.finish();
}, win);
diff --git a/embedding/browser/nsIWebBrowserChrome3.idl b/embedding/browser/nsIWebBrowserChrome3.idl
index a95cab911..d78a1d63b 100644
--- a/embedding/browser/nsIWebBrowserChrome3.idl
+++ b/embedding/browser/nsIWebBrowserChrome3.idl
@@ -8,6 +8,7 @@
interface nsIDocShell;
interface nsIInputStream;
+interface nsIPrincipal;
/**
* nsIWebBrowserChrome3 is an extension to nsIWebBrowserChrome2.
@@ -43,10 +44,13 @@ interface nsIWebBrowserChrome3 : nsIWebBrowserChrome2
* The URI being loaded.
* @param aReferrer
* The referrer of the load.
+ * @param aTriggeringPrincipal
+ * The principal that initiated the load of aURI.
*/
bool shouldLoadURI(in nsIDocShell aDocShell,
in nsIURI aURI,
- in nsIURI aReferrer);
+ in nsIURI aReferrer,
+ in nsIPrincipal aTriggeringPrincipal);
/**
* Attempts to load the currently loaded page into a fresh process to increase
@@ -57,5 +61,6 @@ interface nsIWebBrowserChrome3 : nsIWebBrowserChrome2
*/
bool reloadInFreshProcess(in nsIDocShell aDocShell,
in nsIURI aURI,
- in nsIURI aReferrer);
+ in nsIURI aReferrer,
+ in nsIPrincipal aTriggeringPrincipal);
};
diff --git a/embedding/browser/nsWebBrowser.cpp b/embedding/browser/nsWebBrowser.cpp
index 655aa1e43..c034fc03e 100644
--- a/embedding/browser/nsWebBrowser.cpp
+++ b/embedding/browser/nsWebBrowser.cpp
@@ -654,13 +654,14 @@ nsWebBrowser::LoadURIWithOptions(const char16_t* aURI, uint32_t aLoadFlags,
uint32_t aReferrerPolicy,
nsIInputStream* aPostDataStream,
nsIInputStream* aExtraHeaderStream,
- nsIURI* aBaseURI)
+ nsIURI* aBaseURI,
+ nsIPrincipal* aTriggeringPrincipal)
{
NS_ENSURE_STATE(mDocShell);
return mDocShellAsNav->LoadURIWithOptions(
aURI, aLoadFlags, aReferringURI, aReferrerPolicy, aPostDataStream,
- aExtraHeaderStream, aBaseURI);
+ aExtraHeaderStream, aBaseURI, aTriggeringPrincipal);
}
NS_IMETHODIMP
diff --git a/embedding/components/windowwatcher/nsWindowWatcher.cpp b/embedding/components/windowwatcher/nsWindowWatcher.cpp
index 07872410e..e0e8b4bef 100644
--- a/embedding/components/windowwatcher/nsWindowWatcher.cpp
+++ b/embedding/components/windowwatcher/nsWindowWatcher.cpp
@@ -494,13 +494,6 @@ nsWindowWatcher::CreateChromeWindow(const nsACString& aFeatures,
return NS_ERROR_UNEXPECTED;
}
- // B2G multi-screen support. mozDisplayId is returned from the
- // "display-changed" event, it is also platform-dependent.
-#ifdef MOZ_WIDGET_GONK
- int retval = WinHasOption(aFeatures, "mozDisplayId", 0, nullptr);
- windowCreator2->SetScreenId(retval);
-#endif
-
bool cancel = false;
nsCOMPtr<nsIWebBrowserChrome> newWindowChrome;
nsresult rv =
diff --git a/extensions/cookie/nsPermissionManager.cpp b/extensions/cookie/nsPermissionManager.cpp
index d3696dd94..c44830812 100644
--- a/extensions/cookie/nsPermissionManager.cpp
+++ b/extensions/cookie/nsPermissionManager.cpp
@@ -1666,18 +1666,6 @@ nsPermissionManager::AddInternal(nsIPrincipal* aPrincipal,
id = aID;
}
-#ifdef MOZ_B2G
- // When we do the initial addition of the permissions we don't want to
- // inherit session specific permissions from other tabs or apps
- // so we ignore them and set the permission to PROMPT_ACTION if it was
- // previously allowed or denied by the user.
- if (aIgnoreSessionPermissions &&
- aExpireType == nsIPermissionManager::EXPIRE_SESSION) {
- aPermission = nsIPermissionManager::PROMPT_ACTION;
- aExpireType = nsIPermissionManager::EXPIRE_NEVER;
- }
-#endif // MOZ_B2G
-
entry->GetPermissions().AppendElement(PermissionEntry(id, typeIndex, aPermission,
aExpireType, aExpireTime,
aModificationTime));
diff --git a/gfx/cairo/cairo/src/cairo-mutex-impl-private.h b/gfx/cairo/cairo/src/cairo-mutex-impl-private.h
index 25223f3ea..6c67f6ebb 100644
--- a/gfx/cairo/cairo/src/cairo-mutex-impl-private.h
+++ b/gfx/cairo/cairo/src/cairo-mutex-impl-private.h
@@ -36,6 +36,7 @@
* Carl D. Worth <cworth@cworth.org>
* Mathias Hasselmann <mathias.hasselmann@gmx.de>
* Behdad Esfahbod <behdad@behdad.org>
+ * Mark Straver <moonchild@palemoon.org>
*/
#ifndef CAIRO_MUTEX_IMPL_PRIVATE_H
@@ -178,24 +179,24 @@
#elif defined(_WIN32) /******************************************************/
#define WIN32_LEAN_AND_MEAN
-/* We require Windows 2000 features such as ETO_PDY */
-#if !defined(WINVER) || (WINVER < 0x0500)
-# define WINVER 0x0500
+/* We require Windows 7 features */
+#if !defined(WINVER) || (WINVER < 0x0601)
+# define WINVER 0x0601
#endif
-#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
-# define _WIN32_WINNT 0x0500
+#if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0601)
+# define _WIN32_WINNT 0x0601
#endif
# include <windows.h>
- typedef CRITICAL_SECTION cairo_mutex_impl_t;
+ typedef SRWLOCK cairo_mutex_impl_t;
# define CAIRO_MUTEX_IMPL_WIN32 1
-# define CAIRO_MUTEX_IMPL_LOCK(mutex) EnterCriticalSection (&(mutex))
-# define CAIRO_MUTEX_IMPL_UNLOCK(mutex) LeaveCriticalSection (&(mutex))
-# define CAIRO_MUTEX_IMPL_INIT(mutex) InitializeCriticalSection (&(mutex))
-# define CAIRO_MUTEX_IMPL_FINI(mutex) DeleteCriticalSection (&(mutex))
-# define CAIRO_MUTEX_IMPL_NIL_INITIALIZER { NULL, 0, 0, NULL, NULL, 0 }
+# define CAIRO_MUTEX_IMPL_LOCK(mutex) AcquireSRWLockExclusive (&(mutex))
+# define CAIRO_MUTEX_IMPL_UNLOCK(mutex) ReleaseSRWLockExclusive (&(mutex))
+# define CAIRO_MUTEX_IMPL_INIT(mutex) InitializeSRWLock (&(mutex))
+# define CAIRO_MUTEX_IMPL_FINI(mutex) CAIRO_MUTEX_IMPL_NOOP
+# define CAIRO_MUTEX_IMPL_NIL_INITIALIZER SRWLOCK_INIT
#elif defined __OS2__ /******************************************************/
diff --git a/gfx/gl/GLContextProviderEGL.cpp b/gfx/gl/GLContextProviderEGL.cpp
index ca972e0f3..086f35ad7 100644
--- a/gfx/gl/GLContextProviderEGL.cpp
+++ b/gfx/gl/GLContextProviderEGL.cpp
@@ -23,7 +23,7 @@
#ifdef ANDROID
#include <android/log.h>
- #define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
+ #define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Android" , ## args)
#endif
#define GLES2_LIB "libGLESv2.so"
diff --git a/gfx/gl/GLLibraryEGL.cpp b/gfx/gl/GLLibraryEGL.cpp
index 130bce119..22be44ed6 100644
--- a/gfx/gl/GLLibraryEGL.cpp
+++ b/gfx/gl/GLLibraryEGL.cpp
@@ -33,9 +33,6 @@ namespace gl {
StaticMutex GLLibraryEGL::sMutex;
GLLibraryEGL sEGLLibrary;
-#ifdef MOZ_B2G
-MOZ_THREAD_LOCAL(EGLContext) GLLibraryEGL::sCurrentContext;
-#endif
// should match the order of EGLExtensions, and be null-terminated.
static const char* sEGLExtensionNames[] = {
@@ -305,11 +302,6 @@ GLLibraryEGL::EnsureInitialized(bool forceAccel, nsACString* const out_failureId
mozilla::ScopedGfxFeatureReporter reporter("EGL");
-#ifdef MOZ_B2G
- if (!sCurrentContext.init())
- MOZ_CRASH("GFX: Tls init failed");
-#endif
-
#ifdef XP_WIN
if (!mEGLLibrary) {
// On Windows, the GLESv2, EGL and DXSDK libraries are shipped with libxul and
diff --git a/gfx/gl/GLLibraryEGL.h b/gfx/gl/GLLibraryEGL.h
index fa6ea748b..88fce067e 100644
--- a/gfx/gl/GLLibraryEGL.h
+++ b/gfx/gl/GLLibraryEGL.h
@@ -656,32 +656,12 @@ public:
static void AfterGLCall(const char* glFunction);
#endif
-#ifdef MOZ_B2G
- EGLContext CachedCurrentContext() {
- return sCurrentContext.get();
- }
- void UnsetCachedCurrentContext() {
- sCurrentContext.set(nullptr);
- }
- void SetCachedCurrentContext(EGLContext aCtx) {
- sCurrentContext.set(aCtx);
- }
- bool CachedCurrentContextMatches() {
- return sCurrentContext.get() == fGetCurrentContext();
- }
-
-private:
- static MOZ_THREAD_LOCAL(EGLContext) sCurrentContext;
-public:
-
-#else
EGLContext CachedCurrentContext() {
return nullptr;
}
void UnsetCachedCurrentContext() {}
void SetCachedCurrentContext(EGLContext aCtx) { }
bool CachedCurrentContextMatches() { return true; }
-#endif
private:
bool mInitialized;
diff --git a/gfx/layers/Compositor.cpp b/gfx/layers/Compositor.cpp
index ce7eb9008..b623b8de9 100644
--- a/gfx/layers/Compositor.cpp
+++ b/gfx/layers/Compositor.cpp
@@ -173,9 +173,7 @@ Compositor::DrawDiagnosticsInternal(DiagnosticFlags aFlags,
const gfx::Matrix4x4& aTransform,
uint32_t aFlashCounter)
{
-#ifdef MOZ_B2G
- int lWidth = 4;
-#elif defined(ANDROID)
+#if defined(ANDROID)
int lWidth = 10;
#else
int lWidth = 2;
diff --git a/gfx/layers/apz/src/APZCTreeManager.cpp b/gfx/layers/apz/src/APZCTreeManager.cpp
index 857ae5958..f54326360 100644
--- a/gfx/layers/apz/src/APZCTreeManager.cpp
+++ b/gfx/layers/apz/src/APZCTreeManager.cpp
@@ -1145,6 +1145,7 @@ APZCTreeManager::UpdateWheelTransaction(LayoutDeviceIntPoint aRefPoint,
case eMouseUp:
case eMouseDown:
case eMouseDoubleClick:
+ case eMouseAuxClick:
case eMouseClick:
case eContextMenu:
case eDrop:
diff --git a/gfx/layers/ipc/LayerTransactionChild.cpp b/gfx/layers/ipc/LayerTransactionChild.cpp
index 8b60d3b51..f07e2c27f 100644
--- a/gfx/layers/ipc/LayerTransactionChild.cpp
+++ b/gfx/layers/ipc/LayerTransactionChild.cpp
@@ -72,15 +72,6 @@ void
LayerTransactionChild::ActorDestroy(ActorDestroyReason why)
{
mDestroyed = true;
-#ifdef MOZ_B2G
- // Due to poor lifetime management of gralloc (and possibly shmems) we will
- // crash at some point in the future when we get destroyed due to abnormal
- // shutdown. Its better just to crash here. On desktop though, we have a chance
- // of recovering.
- if (why == AbnormalShutdown) {
- NS_RUNTIMEABORT("ActorDestroy by IPC channel failure at LayerTransactionChild");
- }
-#endif
}
} // namespace layers
diff --git a/gfx/skia/skia/src/core/SkMask.cpp b/gfx/skia/skia/src/core/SkMask.cpp
index 111508074..b40b94974 100644
--- a/gfx/skia/skia/src/core/SkMask.cpp
+++ b/gfx/skia/skia/src/core/SkMask.cpp
@@ -43,7 +43,12 @@ uint8_t* SkMask::AllocImage(size_t size) {
#ifdef TRACK_SKMASK_LIFETIME
SkDebugf("SkMask::AllocImage %d\n", gCounter++);
#endif
- return (uint8_t*)sk_malloc_throw(SkAlign4(size));
+ size_t aligned_size = std::numeric_limits<size_t>::max();
+ size_t adjustment = 3;
+ if (size + adjustment > size) {
+ aligned_size = (size + adjustment) & ~adjustment;
+ }
+ return static_cast<uint8_t*>(sk_malloc_throw(aligned_size));
}
/** We explicitly use this allocator for SkBimap pixels, so that we can
diff --git a/gfx/skia/skia/src/gpu/GrBufferAllocPool.cpp b/gfx/skia/skia/src/gpu/GrBufferAllocPool.cpp
index e3f30b0c1..993e1c59d 100644
--- a/gfx/skia/skia/src/gpu/GrBufferAllocPool.cpp
+++ b/gfx/skia/skia/src/gpu/GrBufferAllocPool.cpp
@@ -14,6 +14,7 @@
#include "GrResourceProvider.h"
#include "GrTypes.h"
+#include "SkSafeMath.h"
#include "SkTraceEvent.h"
#ifdef SK_DEBUG
@@ -335,7 +336,7 @@ void* GrVertexBufferAllocPool::makeSpace(size_t vertexSize,
SkASSERT(startVertex);
size_t offset = 0; // assign to suppress warning
- void* ptr = INHERITED::makeSpace(vertexSize * vertexCount,
+ void* ptr = INHERITED::makeSpace(SkSafeMath::Mul(vertexSize, vertexCount),
vertexSize,
buffer,
&offset);
@@ -360,7 +361,7 @@ void* GrIndexBufferAllocPool::makeSpace(int indexCount,
SkASSERT(startIndex);
size_t offset = 0; // assign to suppress warning
- void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t),
+ void* ptr = INHERITED::makeSpace(SkSafeMath::Mul(indexCount, sizeof(uint16_t)),
sizeof(uint16_t),
buffer,
&offset);
diff --git a/gfx/skia/skia/src/gpu/batches/GrAAHairLinePathRenderer.cpp b/gfx/skia/skia/src/gpu/batches/GrAAHairLinePathRenderer.cpp
index 9d73cf4f1..ec6c99c6e 100644
--- a/gfx/skia/skia/src/gpu/batches/GrAAHairLinePathRenderer.cpp
+++ b/gfx/skia/skia/src/gpu/batches/GrAAHairLinePathRenderer.cpp
@@ -828,6 +828,13 @@ void AAHairlineBatch::onPrepareDraws(Target* target) const {
int lineCount = lines.count() / 2;
int conicCount = conics.count() / 3;
+ int quadAndConicCount = conicCount + quadCount;
+
+ static constexpr int kMaxLines = SK_MaxS32 / kLineSegNumVertices;
+ static constexpr int kMaxQuadsAndConics = SK_MaxS32 / kQuadNumVertices;
+ if (lineCount > kMaxLines || quadAndConicCount > kMaxQuadsAndConics) {
+ return;
+ }
// do lines first
if (lineCount) {
@@ -899,7 +906,7 @@ void AAHairlineBatch::onPrepareDraws(Target* target) const {
ref_quads_index_buffer(target->resourceProvider()));
size_t vertexStride = sizeof(BezierVertex);
- int vertexCount = kQuadNumVertices * quadCount + kQuadNumVertices * conicCount;
+ int vertexCount = kQuadNumVertices * quadAndConicCount;
void *vertices = target->makeVertexSpace(vertexStride, vertexCount,
&vertexBuffer, &firstVertex);
diff --git a/gfx/tests/mochitest/test_acceleration.html b/gfx/tests/mochitest/test_acceleration.html
index 0475a9590..cb1fcd39b 100644
--- a/gfx/tests/mochitest/test_acceleration.html
+++ b/gfx/tests/mochitest/test_acceleration.html
@@ -98,7 +98,7 @@ switch(osName)
break;
default:
- if (xr.OS == "Android" && xr.widgetToolkit != "gonk") {
+ if (xr.OS == "Android") {
isnot(acceleratedWindows, 0, "Acceleration enabled on Android");
} else {
is(acceleratedWindows, 0, "Acceleration not supported on '" + osName + "'");
diff --git a/gfx/thebes/gfxAndroidPlatform.cpp b/gfx/thebes/gfxAndroidPlatform.cpp
index f587737b5..76427d88c 100644
--- a/gfx/thebes/gfxAndroidPlatform.cpp
+++ b/gfx/thebes/gfxAndroidPlatform.cpp
@@ -21,6 +21,7 @@
#include "nsIScreenManager.h"
#include "nsILocaleService.h"
#include "nsServiceManagerUtils.h"
+#include "nsUnicodeProperties.h"
#include "gfxPrefs.h"
#include "cairo.h"
#include "VsyncSource.h"
@@ -32,6 +33,7 @@
using namespace mozilla;
using namespace mozilla::dom;
using namespace mozilla::gfx;
+using namespace mozilla::unicode;
static FT_Library gPlatformFTLibrary = nullptr;
@@ -168,19 +170,17 @@ gfxAndroidPlatform::GetCommonFallbackFonts(uint32_t aCh, uint32_t aNextCh,
static const char kNotoSansCJKJP[] = "Noto Sans CJK JP";
static const char kNotoColorEmoji[] = "Noto Color Emoji";
- if (aNextCh == 0xfe0fu) {
- // if char is followed by VS16, try for a color emoji glyph
- aFontList.AppendElement(kNotoColorEmoji);
+ EmojiPresentation emoji = GetEmojiPresentation(aCh);
+ if (emoji != EmojiPresentation::TextOnly) {
+ if (aNextCh == kVariationSelector16 ||
+ (aNextCh != kVariationSelector15 &&
+ emoji == EmojiPresentation::EmojiDefault)) {
+ // if char is followed by VS16, try for a color emoji glyph
+ aFontList.AppendElement(kNotoColorEmoji);
+ }
}
- if (!IS_IN_BMP(aCh)) {
- uint32_t p = aCh >> 16;
- if (p == 1) { // try color emoji font, unless VS15 (text style) present
- if (aNextCh != 0xfe0fu && aNextCh != 0xfe0eu) {
- aFontList.AppendElement(kNotoColorEmoji);
- }
- }
- } else {
+ if (IS_IN_BMP(aCh)) {
// try language-specific "Droid Sans *" and "Noto Sans *" fonts for
// certain blocks, as most devices probably have these
uint8_t block = (aCh >> 8) & 0xff;
diff --git a/gfx/thebes/gfxFontConstants.h b/gfx/thebes/gfxFontConstants.h
index 5aa1eb0c7..3eae49ee1 100644
--- a/gfx/thebes/gfxFontConstants.h
+++ b/gfx/thebes/gfxFontConstants.h
@@ -222,13 +222,14 @@ enum {
#define NS_FONT_SUB_SUPER_SMALL_SIZE (20.0)
#define NS_FONT_SUB_SUPER_LARGE_SIZE (45.0)
-// pref lang id's for font prefs
+// pref lang ids for font prefs
enum eFontPrefLang {
#define FONT_PREF_LANG(enum_id_, str_, atom_id_) eFontPrefLang_ ## enum_id_
#include "gfxFontPrefLangList.h"
#undef FONT_PREF_LANG
, eFontPrefLang_CJKSet // special code for CJK set
+ , eFontPrefLang_Emoji // special code for emoji presentation
, eFontPrefLang_First = eFontPrefLang_Western
, eFontPrefLang_Last = eFontPrefLang_Others
, eFontPrefLang_Count = (eFontPrefLang_Last - eFontPrefLang_First + 1)
diff --git a/gfx/thebes/gfxFontFamilyList.h b/gfx/thebes/gfxFontFamilyList.h
index e240102e0..9d1a3cf49 100644
--- a/gfx/thebes/gfxFontFamilyList.h
+++ b/gfx/thebes/gfxFontFamilyList.h
@@ -38,6 +38,7 @@ enum FontFamilyType : uint32_t {
// special
eFamily_moz_variable,
eFamily_moz_fixed,
+ eFamily_moz_emoji,
eFamily_generic_first = eFamily_serif,
eFamily_generic_last = eFamily_fantasy,
diff --git a/gfx/thebes/gfxHarfBuzzShaper.cpp b/gfx/thebes/gfxHarfBuzzShaper.cpp
index 1f472f88d..4b9dbbc14 100644
--- a/gfx/thebes/gfxHarfBuzzShaper.cpp
+++ b/gfx/thebes/gfxHarfBuzzShaper.cpp
@@ -12,20 +12,14 @@
#include "mozilla/Sprintf.h"
#include "nsUnicodeProperties.h"
#include "nsUnicodeScriptCodes.h"
-#include "nsUnicodeNormalizer.h"
#include "harfbuzz/hb.h"
#include "harfbuzz/hb-ot.h"
-#if ENABLE_INTL_API // ICU is available: we'll use it for Unicode composition
- // and decomposition in preference to nsUnicodeNormalizer.
#include "unicode/unorm.h"
#include "unicode/utext.h"
-#define MOZ_HB_SHAPER_USE_ICU_NORMALIZATION 1
+
static const UNormalizer2 * sNormalizer = nullptr;
-#else
-#undef MOZ_HB_SHAPER_USE_ICU_NORMALIZATION
-#endif
#include <algorithm>
@@ -1091,8 +1085,6 @@ HBUnicodeCompose(hb_unicode_funcs_t *ufuncs,
hb_codepoint_t *ab,
void *user_data)
{
-#if MOZ_HB_SHAPER_USE_ICU_NORMALIZATION
-
if (sNormalizer) {
UChar32 ch = unorm2_composePair(sNormalizer, a, b);
if (ch >= 0) {
@@ -1101,14 +1093,6 @@ HBUnicodeCompose(hb_unicode_funcs_t *ufuncs,
}
}
-#else // no ICU available, use the old nsUnicodeNormalizer
-
- if (nsUnicodeNormalizer::Compose(a, b, ab)) {
- return true;
- }
-
-#endif
-
return false;
}
@@ -1129,8 +1113,6 @@ HBUnicodeDecompose(hb_unicode_funcs_t *ufuncs,
}
#endif
-#if MOZ_HB_SHAPER_USE_ICU_NORMALIZATION
-
if (!sNormalizer) {
return false;
}
@@ -1162,12 +1144,6 @@ HBUnicodeDecompose(hb_unicode_funcs_t *ufuncs,
utext_close(&text);
return *b != 0 || *a != ab;
-
-#else // no ICU available, use the old nsUnicodeNormalizer
-
- return nsUnicodeNormalizer::DecomposeNonRecursively(ab, a, b);
-
-#endif
}
static void
@@ -1250,11 +1226,9 @@ gfxHarfBuzzShaper::Initialize()
HBUnicodeDecompose,
nullptr, nullptr);
-#if MOZ_HB_SHAPER_USE_ICU_NORMALIZATION
UErrorCode error = U_ZERO_ERROR;
sNormalizer = unorm2_getNFCInstance(&error);
- NS_ASSERTION(U_SUCCESS(error), "failed to get ICU normalizer");
-#endif
+ MOZ_ASSERT(U_SUCCESS(error), "failed to get ICU normalizer");
}
gfxFontEntry *entry = mFont->GetFontEntry();
diff --git a/gfx/thebes/gfxPlatform.cpp b/gfx/thebes/gfxPlatform.cpp
index a468592fe..4db7bc29f 100644
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -2399,11 +2399,10 @@ gfxPlatform::GetTilesSupportInfo(mozilla::widget::InfoObject& aObj)
/*static*/ bool
gfxPlatform::AsyncPanZoomEnabled()
{
-#if !defined(MOZ_B2G) && !defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_WIDGET_UIKIT)
- // For XUL applications (everything but B2G on mobile and desktop, and
- // Firefox on Android) we only want to use APZ when E10S is enabled. If
- // we ever get input events off the main thread we can consider relaxing
- // this requirement.
+#if !defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_WIDGET_UIKIT)
+ // For XUL applications (everything but Firefox on Android) we only want
+ // to use APZ when E10S is enabled. If we ever get input events off the
+ // main thread we can consider relaxing this requirement.
if (!BrowserTabsRemoteAutostart()) {
return false;
}
diff --git a/gfx/thebes/gfxPlatformFontList.cpp b/gfx/thebes/gfxPlatformFontList.cpp
index 01394db14..e12f4e197 100644
--- a/gfx/thebes/gfxPlatformFontList.cpp
+++ b/gfx/thebes/gfxPlatformFontList.cpp
@@ -869,28 +869,54 @@ gfxPlatformFontList::ResolveGenericFontNames(
nsIAtom* langGroup = GetLangGroupForPrefLang(aPrefLang);
NS_ASSERTION(langGroup, "null lang group for pref lang");
+ gfxPlatformFontList::GetFontFamiliesFromGenericFamilies(genericFamilies,
+ langGroup,
+ aGenericFamilies);
+
+#if 0 // dump out generic mappings
+ printf("%s ===> ", prefFontName.get());
+ for (uint32_t k = 0; k < aGenericFamilies->Length(); k++) {
+ if (k > 0) printf(", ");
+ printf("%s", NS_ConvertUTF16toUTF8(aGenericFamilies[k]->Name()).get());
+ }
+ printf("\n");
+#endif
+}
+
+void
+gfxPlatformFontList::ResolveEmojiFontNames(
+ nsTArray<RefPtr<gfxFontFamily>>* aGenericFamilies)
+{
+ // emoji preference has no lang name
+ AutoTArray<nsString,4> genericFamilies;
+
+ nsAutoCString prefFontListName("font.name-list.emoji");
+ gfxFontUtils::AppendPrefsFontList(prefFontListName.get(), genericFamilies);
+
+ gfxPlatformFontList::GetFontFamiliesFromGenericFamilies(genericFamilies,
+ nullptr,
+ aGenericFamilies);
+}
+
+void
+gfxPlatformFontList::GetFontFamiliesFromGenericFamilies(
+ nsTArray<nsString>& aGenericNameFamilies,
+ nsIAtom* aLangGroup,
+ nsTArray<RefPtr<gfxFontFamily>>* aGenericFamilies)
+{
// lookup and add platform fonts uniquely
- for (const nsString& genericFamily : genericFamilies) {
+ for (const nsString& genericFamily : aGenericNameFamilies) {
gfxFontStyle style;
- style.language = langGroup;
+ style.language = aLangGroup;
style.systemFont = false;
AutoTArray<gfxFontFamily*,10> families;
- FindAndAddFamilies(genericFamily, &families, &style);
+ FindAndAddFamilies(genericFamily, &families, &style, 1.0);
for (gfxFontFamily* f : families) {
if (!aGenericFamilies->Contains(f)) {
aGenericFamilies->AppendElement(f);
}
}
}
-
-#if 0 // dump out generic mappings
- printf("%s ===> ", prefFontName.get());
- for (uint32_t k = 0; k < aGenericFamilies->Length(); k++) {
- if (k > 0) printf(", ");
- printf("%s", NS_ConvertUTF16toUTF8(aGenericFamilies[k]->Name()).get());
- }
- printf("\n");
-#endif
}
nsTArray<RefPtr<gfxFontFamily>>*
@@ -902,6 +928,17 @@ gfxPlatformFontList::GetPrefFontsLangGroup(mozilla::FontFamilyType aGenericType,
aGenericType = eFamily_monospace;
}
+ if (aGenericType == eFamily_moz_emoji) {
+ // Emoji font has no lang
+ PrefFontList* prefFonts = mEmojiPrefFont.get();
+ if (MOZ_UNLIKELY(!prefFonts)) {
+ prefFonts = new PrefFontList;
+ ResolveEmojiFontNames(prefFonts);
+ mEmojiPrefFont.reset(prefFonts);
+ }
+ return prefFonts;
+ }
+
PrefFontList* prefFonts =
mLangGroupPrefFonts[aPrefLang][aGenericType].get();
if (MOZ_UNLIKELY(!prefFonts)) {
@@ -1180,6 +1217,10 @@ gfxPlatformFontList::AppendPrefLang(eFontPrefLang aPrefLangs[], uint32_t& aLen,
mozilla::FontFamilyType
gfxPlatformFontList::GetDefaultGeneric(eFontPrefLang aLang)
{
+ if (aLang == eFontPrefLang_Emoji) {
+ return eFamily_moz_emoji;
+ }
+
// initialize lang group pref font defaults (i.e. serif/sans-serif)
if (MOZ_UNLIKELY(mDefaultGenericsLangGroup.IsEmpty())) {
mDefaultGenericsLangGroup.AppendElements(ArrayLength(gPrefLangNames));
diff --git a/gfx/thebes/gfxPlatformFontList.h b/gfx/thebes/gfxPlatformFontList.h
index c16994d8c..d77c12059 100644
--- a/gfx/thebes/gfxPlatformFontList.h
+++ b/gfx/thebes/gfxPlatformFontList.h
@@ -380,6 +380,15 @@ protected:
eFontPrefLang aPrefLang,
nsTArray<RefPtr<gfxFontFamily>>* aGenericFamilies);
+ void
+ ResolveEmojiFontNames(nsTArray<RefPtr<gfxFontFamily>>* aGenericFamilies);
+
+ void
+ GetFontFamiliesFromGenericFamilies(
+ nsTArray<nsString>& aGenericFamilies,
+ nsIAtom* aLangGroup,
+ nsTArray<RefPtr<gfxFontFamily>>* aFontFamilies);
+
virtual nsresult InitFontListForPlatform() = 0;
void ApplyWhitelist();
@@ -436,6 +445,8 @@ protected:
eFontPrefLang_First,
eFontPrefLang_Count> mLangGroupPrefFonts;
+ mozilla::UniquePtr<PrefFontList> mEmojiPrefFont;
+
// when system-wide font lookup fails for a character, cache it to skip future searches
gfxSparseBitSet mCodepointsWithNoFonts;
diff --git a/gfx/thebes/gfxPlatformGtk.cpp b/gfx/thebes/gfxPlatformGtk.cpp
index 1fb3bc4fd..be75332d6 100644
--- a/gfx/thebes/gfxPlatformGtk.cpp
+++ b/gfx/thebes/gfxPlatformGtk.cpp
@@ -240,9 +240,14 @@ gfxPlatformGtk::GetCommonFallbackFonts(uint32_t aCh, uint32_t aNextCh,
Script aRunScript,
nsTArray<const char*>& aFontList)
{
- if (aNextCh == 0xfe0fu) {
- // if char is followed by VS16, try for a color emoji glyph
- aFontList.AppendElement(kFontTwemojiMozilla);
+ EmojiPresentation emoji = GetEmojiPresentation(aCh);
+ if (emoji != EmojiPresentation::TextOnly) {
+ if (aNextCh == kVariationSelector16 ||
+ (aNextCh != kVariationSelector15 &&
+ emoji == EmojiPresentation::EmojiDefault)) {
+ // if char is followed by VS16, try for a color emoji glyph
+ aFontList.AppendElement(kFontTwemojiMozilla);
+ }
}
aFontList.AppendElement(kFontDejaVuSerif);
@@ -250,15 +255,6 @@ gfxPlatformGtk::GetCommonFallbackFonts(uint32_t aCh, uint32_t aNextCh,
aFontList.AppendElement(kFontDejaVuSans);
aFontList.AppendElement(kFontFreeSans);
- if (!IS_IN_BMP(aCh)) {
- uint32_t p = aCh >> 16;
- if (p == 1) { // try color emoji font, unless VS15 (text style) present
- if (aNextCh != 0xfe0fu && aNextCh != 0xfe0eu) {
- aFontList.AppendElement(kFontTwemojiMozilla);
- }
- }
- }
-
// add fonts for CJK ranges
// xxx - this isn't really correct, should use the same CJK font ordering
// as the pref font code
diff --git a/gfx/thebes/gfxPlatformMac.cpp b/gfx/thebes/gfxPlatformMac.cpp
index 3216f0f07..79684dd19 100644
--- a/gfx/thebes/gfxPlatformMac.cpp
+++ b/gfx/thebes/gfxPlatformMac.cpp
@@ -18,6 +18,7 @@
#include "nsTArray.h"
#include "mozilla/Preferences.h"
#include "mozilla/VsyncDispatcher.h"
+#include "nsUnicodeProperties.h"
#include "qcms.h"
#include "gfx2DGlue.h"
@@ -29,6 +30,7 @@
using namespace mozilla;
using namespace mozilla::gfx;
+using namespace mozilla::unicode;
// cribbed from CTFontManager.h
enum {
@@ -195,23 +197,24 @@ gfxPlatformMac::GetCommonFallbackFonts(uint32_t aCh, uint32_t aNextCh,
Script aRunScript,
nsTArray<const char*>& aFontList)
{
- if (aNextCh == 0xfe0f) {
- aFontList.AppendElement(kFontAppleColorEmoji);
+ EmojiPresentation emoji = GetEmojiPresentation(aCh);
+ if (emoji != EmojiPresentation::TextOnly) {
+ if (aNextCh == kVariationSelector16 ||
+ (aNextCh != kVariationSelector15 &&
+ emoji == EmojiPresentation::EmojiDefault)) {
+ // if char is followed by VS16, try for a color emoji glyph
+ aFontList.AppendElement(kFontAppleColorEmoji);
+ }
}
aFontList.AppendElement(kFontLucidaGrande);
if (!IS_IN_BMP(aCh)) {
uint32_t p = aCh >> 16;
- uint32_t b = aCh >> 8;
if (p == 1) {
- if (b >= 0x1f0 && b < 0x1f7) {
- aFontList.AppendElement(kFontAppleColorEmoji);
- } else {
- aFontList.AppendElement(kFontAppleSymbols);
- aFontList.AppendElement(kFontSTIXGeneral);
- aFontList.AppendElement(kFontGeneva);
- }
+ aFontList.AppendElement(kFontAppleSymbols);
+ aFontList.AppendElement(kFontSTIXGeneral);
+ aFontList.AppendElement(kFontGeneva);
} else if (p == 2) {
// OSX installations with MS Office may have these fonts
aFontList.AppendElement(kFontMingLiUExtB);
diff --git a/gfx/thebes/gfxTextRun.cpp b/gfx/thebes/gfxTextRun.cpp
index 6718eed01..1702cab66 100644
--- a/gfx/thebes/gfxTextRun.cpp
+++ b/gfx/thebes/gfxTextRun.cpp
@@ -2813,7 +2813,7 @@ gfxFontGroup::FindFontForChar(uint32_t aCh, uint32_t aPrevCh, uint32_t aNextCh,
return nullptr;
// 2. search pref fonts
- RefPtr<gfxFont> font = WhichPrefFontSupportsChar(aCh);
+ RefPtr<gfxFont> font = WhichPrefFontSupportsChar(aCh, aNextCh);
if (font) {
*aMatchType = gfxTextRange::kPrefsFallback;
return font.forget();
@@ -3081,15 +3081,25 @@ gfxFontGroup::ContainsUserFont(const gfxUserFontEntry* aUserFont)
}
already_AddRefed<gfxFont>
-gfxFontGroup::WhichPrefFontSupportsChar(uint32_t aCh)
+gfxFontGroup::WhichPrefFontSupportsChar(uint32_t aCh, uint32_t aNextCh)
{
RefPtr<gfxFont> font;
- // get the pref font list if it hasn't been set up already
- uint32_t unicodeRange = FindCharUnicodeRange(aCh);
+ eFontPrefLang charLang;
gfxPlatformFontList* pfl = gfxPlatformFontList::PlatformFontList();
- eFontPrefLang charLang = pfl->GetFontPrefLangFor(unicodeRange);
+ EmojiPresentation emoji = GetEmojiPresentation(aCh);
+ if ((emoji != EmojiPresentation::TextOnly &&
+ (aNextCh == kVariationSelector16 ||
+ (emoji == EmojiPresentation::EmojiDefault &&
+ aNextCh != kVariationSelector15)))) {
+ charLang = eFontPrefLang_Emoji;
+ } else {
+ // get the pref font list if it hasn't been set up already
+ uint32_t unicodeRange = FindCharUnicodeRange(aCh);
+ charLang = pfl->GetFontPrefLangFor(unicodeRange);
+ }
+
// if the last pref font was the first family in the pref list, no need to recheck through a list of families
if (mLastPrefFont && charLang == mLastPrefLang &&
mLastPrefFirstFont && mLastPrefFont->HasCharacter(aCh)) {
diff --git a/gfx/thebes/gfxTextRun.h b/gfx/thebes/gfxTextRun.h
index 0e44456ae..c3673785c 100644
--- a/gfx/thebes/gfxTextRun.h
+++ b/gfx/thebes/gfxTextRun.h
@@ -917,7 +917,8 @@ public:
protected:
// search through pref fonts for a character, return nullptr if no matching pref font
- already_AddRefed<gfxFont> WhichPrefFontSupportsChar(uint32_t aCh);
+ already_AddRefed<gfxFont> WhichPrefFontSupportsChar(uint32_t aCh,
+ uint32_t aNextCh);
already_AddRefed<gfxFont>
WhichSystemFontSupportsChar(uint32_t aCh, uint32_t aNextCh,
diff --git a/gfx/thebes/gfxWindowsPlatform.cpp b/gfx/thebes/gfxWindowsPlatform.cpp
index af4d932a9..c68f622c6 100755
--- a/gfx/thebes/gfxWindowsPlatform.cpp
+++ b/gfx/thebes/gfxWindowsPlatform.cpp
@@ -13,6 +13,7 @@
#include "gfxWindowsSurface.h"
#include "nsUnicharUtils.h"
+#include "nsUnicodeProperties.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
@@ -81,6 +82,7 @@ using namespace mozilla::gfx;
using namespace mozilla::layers;
using namespace mozilla::widget;
using namespace mozilla::image;
+using namespace mozilla::unicode;
IDWriteRenderingParams* GetDwriteRenderingParams(bool aGDI)
{
@@ -669,9 +671,15 @@ gfxWindowsPlatform::GetCommonFallbackFonts(uint32_t aCh, uint32_t aNextCh,
Script aRunScript,
nsTArray<const char*>& aFontList)
{
- if (aNextCh == 0xfe0fu) {
- aFontList.AppendElement(kFontSegoeUIEmoji);
- aFontList.AppendElement(kFontTwemojiMozilla);
+ EmojiPresentation emoji = GetEmojiPresentation(aCh);
+ if (emoji != EmojiPresentation::TextOnly) {
+ if (aNextCh == kVariationSelector16 ||
+ (aNextCh != kVariationSelector15 &&
+ emoji == EmojiPresentation::EmojiDefault)) {
+ // if char is followed by VS16, try for a color emoji glyph
+ // XXX: For Win8+ native, aFontList.AppendElement(kFontSegoeUIEmoji);
+ aFontList.AppendElement(kFontTwemojiMozilla);
+ }
}
// Arial is used as the default fallback for system fallback
@@ -680,17 +688,7 @@ gfxWindowsPlatform::GetCommonFallbackFonts(uint32_t aCh, uint32_t aNextCh,
if (!IS_IN_BMP(aCh)) {
uint32_t p = aCh >> 16;
if (p == 1) { // SMP plane
- if (aNextCh == 0xfe0eu) {
- aFontList.AppendElement(kFontSegoeUISymbol);
- aFontList.AppendElement(kFontSegoeUIEmoji);
- aFontList.AppendElement(kFontTwemojiMozilla);
- } else {
- if (aNextCh != 0xfe0fu) {
- aFontList.AppendElement(kFontSegoeUIEmoji);
- aFontList.AppendElement(kFontTwemojiMozilla);
- }
- aFontList.AppendElement(kFontSegoeUISymbol);
- }
+ aFontList.AppendElement(kFontSegoeUISymbol);
aFontList.AppendElement(kFontEbrima);
aFontList.AppendElement(kFontNirmalaUI);
aFontList.AppendElement(kFontCambriaMath);
diff --git a/gfx/thebes/moz.build b/gfx/thebes/moz.build
index 227b2b875..e253d7891 100644
--- a/gfx/thebes/moz.build
+++ b/gfx/thebes/moz.build
@@ -223,12 +223,10 @@ elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
'DeviceManagerDx.cpp',
]
-# We prefer to use ICU for normalization functions, but currently it is only
-# available if we're building with the Intl API enabled:
-if CONFIG['ENABLE_INTL_API']:
- USE_LIBS += [
- 'icu',
- ]
+# We use ICU for normalization functions
+USE_LIBS += [
+ 'icu',
+]
include('/ipc/chromium/chromium-config.mozbuild')
diff --git a/hal/Hal.cpp b/hal/Hal.cpp
index 44be2f510..8ac9e6847 100644
--- a/hal/Hal.cpp
+++ b/hal/Hal.cpp
@@ -89,8 +89,6 @@ AssertMainProcess()
MOZ_ASSERT(GeckoProcessType_Default == XRE_GetProcessType());
}
-#if !defined(MOZ_WIDGET_GONK)
-
bool
WindowIsActive(nsPIDOMWindowInner* aWindow)
{
@@ -100,8 +98,6 @@ WindowIsActive(nsPIDOMWindowInner* aWindow)
return !document->Hidden();
}
-#endif // !defined(MOZ_WIDGET_GONK)
-
StaticAutoPtr<WindowIdentifier::IDArrayType> gLastIDToVibrate;
void InitLastIDToVibrate()
@@ -123,7 +119,6 @@ Vibrate(const nsTArray<uint32_t>& pattern, const WindowIdentifier &id)
{
AssertMainThread();
-#if !defined(MOZ_WIDGET_GONK)
// Only active windows may start vibrations. If |id| hasn't gone
// through the IPC layer -- that is, if our caller is the outside
// world, not hal_proxy -- check whether the window is active. If
@@ -134,7 +129,6 @@ Vibrate(const nsTArray<uint32_t>& pattern, const WindowIdentifier &id)
HAL_LOG("Vibrate: Window is inactive, dropping vibrate.");
return;
}
-#endif // !defined(MOZ_WIDGET_GONK)
if (!InSandbox()) {
if (!gLastIDToVibrate) {
diff --git a/hal/gonk/GonkDiskSpaceWatcher.cpp b/hal/gonk/GonkDiskSpaceWatcher.cpp
deleted file mode 100644
index cdc48ef89..000000000
--- a/hal/gonk/GonkDiskSpaceWatcher.cpp
+++ /dev/null
@@ -1,324 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "Hal.h"
-#include <sys/syscall.h>
-#include <sys/vfs.h>
-#include <fcntl.h>
-#include <errno.h>
-#include "base/message_loop.h"
-#include "base/task.h"
-#include "DiskSpaceWatcher.h"
-#include "fanotify.h"
-#include "nsIObserverService.h"
-#include "nsIDiskSpaceWatcher.h"
-#include "nsThreadUtils.h"
-#include "nsXULAppAPI.h"
-#include "mozilla/ModuleUtils.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/Services.h"
-
-using namespace mozilla;
-
-namespace mozilla { namespace hal_impl { class GonkDiskSpaceWatcher; } }
-
-using namespace mozilla::hal_impl;
-
-namespace mozilla {
-namespace hal_impl {
-
-// NOTE: this should be unnecessary once we no longer support ICS.
-#ifndef __NR_fanotify_init
-#if defined(__ARM_EABI__)
-#define __NR_fanotify_init 367
-#define __NR_fanotify_mark 368
-#elif defined(__i386__)
-#define __NR_fanotify_init 338
-#define __NR_fanotify_mark 339
-#else
-#error "Unhandled architecture"
-#endif
-#endif
-
-// fanotify_init and fanotify_mark functions are syscalls.
-// The user space bits are not part of bionic so we add them here
-// as well as fanotify.h
-int fanotify_init (unsigned int flags, unsigned int event_f_flags)
-{
- return syscall(__NR_fanotify_init, flags, event_f_flags);
-}
-
-// Add, remove, or modify an fanotify mark on a filesystem object.
-int fanotify_mark (int fanotify_fd, unsigned int flags,
- uint64_t mask, int dfd, const char *pathname)
-{
-
- // On 32 bits platforms we have to convert the 64 bits mask into
- // two 32 bits ints.
- if (sizeof(void *) == 4) {
- union {
- uint64_t _64;
- uint32_t _32[2];
- } _mask;
- _mask._64 = mask;
- return syscall(__NR_fanotify_mark, fanotify_fd, flags,
- _mask._32[0], _mask._32[1], dfd, pathname);
- }
-
- return syscall(__NR_fanotify_mark, fanotify_fd, flags, mask, dfd, pathname);
-}
-
-class GonkDiskSpaceWatcher final : public MessageLoopForIO::Watcher
-{
-public:
- GonkDiskSpaceWatcher();
- ~GonkDiskSpaceWatcher() {};
-
- virtual void OnFileCanReadWithoutBlocking(int aFd);
-
- // We should never write to the fanotify fd.
- virtual void OnFileCanWriteWithoutBlocking(int aFd)
- {
- MOZ_CRASH("Must not write to fanotify fd");
- }
-
- void DoStart();
- void DoStop();
-
-private:
- void NotifyUpdate();
-
- uint64_t mLowThreshold;
- uint64_t mHighThreshold;
- TimeDuration mTimeout;
- TimeStamp mLastTimestamp;
- uint64_t mLastFreeSpace;
- uint32_t mSizeDelta;
-
- bool mIsDiskFull;
- uint64_t mFreeSpace;
-
- int mFd;
- MessageLoopForIO::FileDescriptorWatcher mReadWatcher;
-};
-
-static GonkDiskSpaceWatcher* gHalDiskSpaceWatcher = nullptr;
-
-#define WATCHER_PREF_LOW "disk_space_watcher.low_threshold"
-#define WATCHER_PREF_HIGH "disk_space_watcher.high_threshold"
-#define WATCHER_PREF_TIMEOUT "disk_space_watcher.timeout"
-#define WATCHER_PREF_SIZE_DELTA "disk_space_watcher.size_delta"
-
-static const char kWatchedPath[] = "/data";
-
-// Helper class to dispatch calls to xpcom on the main thread.
-class DiskSpaceNotifier : public Runnable
-{
-public:
- DiskSpaceNotifier(const bool aIsDiskFull, const uint64_t aFreeSpace) :
- mIsDiskFull(aIsDiskFull),
- mFreeSpace(aFreeSpace) {}
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
- DiskSpaceWatcher::UpdateState(mIsDiskFull, mFreeSpace);
- return NS_OK;
- }
-
-private:
- bool mIsDiskFull;
- uint64_t mFreeSpace;
-};
-
-// Helper runnable to delete the watcher on the main thread.
-class DiskSpaceCleaner : public Runnable
-{
-public:
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
- if (gHalDiskSpaceWatcher) {
- delete gHalDiskSpaceWatcher;
- gHalDiskSpaceWatcher = nullptr;
- }
- return NS_OK;
- }
-};
-
-GonkDiskSpaceWatcher::GonkDiskSpaceWatcher() :
- mLastFreeSpace(UINT64_MAX),
- mIsDiskFull(false),
- mFreeSpace(UINT64_MAX),
- mFd(-1)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(gHalDiskSpaceWatcher == nullptr);
-
- // Default values: 5MB for low threshold, 10MB for high threshold, and
- // a timeout of 5 seconds.
- mLowThreshold = Preferences::GetInt(WATCHER_PREF_LOW, 5) * 1024 * 1024;
- mHighThreshold = Preferences::GetInt(WATCHER_PREF_HIGH, 10) * 1024 * 1024;
- mTimeout = TimeDuration::FromSeconds(Preferences::GetInt(WATCHER_PREF_TIMEOUT, 5));
- mSizeDelta = Preferences::GetInt(WATCHER_PREF_SIZE_DELTA, 1) * 1024 * 1024;
-}
-
-void
-GonkDiskSpaceWatcher::DoStart()
-{
- NS_ASSERTION(XRE_GetIOMessageLoop() == MessageLoopForIO::current(),
- "Not on the correct message loop");
-
- mFd = fanotify_init(FAN_CLASS_NOTIF, FAN_CLOEXEC | O_LARGEFILE);
- if (mFd == -1) {
- if (errno == ENOSYS) {
- // Don't change these printf_stderr since we need these logs even
- // in opt builds.
- printf_stderr("Warning: No fanotify support in this device's kernel.\n");
-#if ANDROID_VERSION >= 19
- MOZ_CRASH("Fanotify support must be enabled in the kernel.");
-#endif
- } else {
- printf_stderr("Error calling fanotify_init()");
- }
- return;
- }
-
- if (fanotify_mark(mFd, FAN_MARK_ADD | FAN_MARK_MOUNT, FAN_CLOSE,
- 0, kWatchedPath) < 0) {
- NS_WARNING("Error calling fanotify_mark");
- close(mFd);
- mFd = -1;
- return;
- }
-
- if (!MessageLoopForIO::current()->WatchFileDescriptor(
- mFd, /* persistent = */ true,
- MessageLoopForIO::WATCH_READ,
- &mReadWatcher, gHalDiskSpaceWatcher)) {
- NS_WARNING("Unable to watch fanotify fd.");
- close(mFd);
- mFd = -1;
- }
-}
-
-void
-GonkDiskSpaceWatcher::DoStop()
-{
- NS_ASSERTION(XRE_GetIOMessageLoop() == MessageLoopForIO::current(),
- "Not on the correct message loop");
-
- if (mFd != -1) {
- mReadWatcher.StopWatchingFileDescriptor();
- fanotify_mark(mFd, FAN_MARK_FLUSH, 0, 0, kWatchedPath);
- close(mFd);
- mFd = -1;
- }
-
- // Dispatch the cleanup to the main thread.
- nsCOMPtr<nsIRunnable> runnable = new DiskSpaceCleaner();
- NS_DispatchToMainThread(runnable);
-}
-
-// We are called off the main thread, so we proxy first to the main thread
-// before calling the xpcom object.
-void
-GonkDiskSpaceWatcher::NotifyUpdate()
-{
- mLastTimestamp = TimeStamp::Now();
- mLastFreeSpace = mFreeSpace;
-
- nsCOMPtr<nsIRunnable> runnable =
- new DiskSpaceNotifier(mIsDiskFull, mFreeSpace);
- NS_DispatchToMainThread(runnable);
-}
-
-void
-GonkDiskSpaceWatcher::OnFileCanReadWithoutBlocking(int aFd)
-{
- struct fanotify_event_metadata* fem = nullptr;
- char buf[4096];
- struct statfs sfs;
- int32_t len, rc;
-
- do {
- len = read(aFd, buf, sizeof(buf));
- } while(len == -1 && errno == EINTR);
-
- // Bail out if the file is busy.
- if (len < 0 && errno == ETXTBSY) {
- return;
- }
-
- // We should get an exact multiple of fanotify_event_metadata
- if (len <= 0 || (len % FAN_EVENT_METADATA_LEN != 0)) {
- MOZ_CRASH("About to crash: fanotify_event_metadata read error.");
- }
-
- fem = reinterpret_cast<fanotify_event_metadata *>(buf);
-
- while (FAN_EVENT_OK(fem, len)) {
- rc = fstatfs(fem->fd, &sfs);
- if (rc < 0) {
- NS_WARNING("Unable to stat fan_notify fd");
- } else {
- bool firstRun = mFreeSpace == UINT64_MAX;
- mFreeSpace = sfs.f_bavail * sfs.f_bsize;
- // We change from full <-> free depending on the free space and the
- // low and high thresholds.
- // Once we are in 'full' mode we send updates for all size changes with
- // a minimum of time between messages or when we cross a size change
- // threshold.
- if (firstRun) {
- mIsDiskFull = mFreeSpace <= mLowThreshold;
- // Always notify the current state at first run.
- NotifyUpdate();
- } else if (!mIsDiskFull && (mFreeSpace <= mLowThreshold)) {
- mIsDiskFull = true;
- NotifyUpdate();
- } else if (mIsDiskFull && (mFreeSpace > mHighThreshold)) {
- mIsDiskFull = false;
- NotifyUpdate();
- } else if (mIsDiskFull) {
- if (mTimeout < TimeStamp::Now() - mLastTimestamp ||
- mSizeDelta < llabs(mFreeSpace - mLastFreeSpace)) {
- NotifyUpdate();
- }
- }
- }
- close(fem->fd);
- fem = FAN_EVENT_NEXT(fem, len);
- }
-}
-
-void
-StartDiskSpaceWatcher()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- // Bail out if called several times.
- if (gHalDiskSpaceWatcher != nullptr) {
- return;
- }
-
- gHalDiskSpaceWatcher = new GonkDiskSpaceWatcher();
-
- XRE_GetIOMessageLoop()->PostTask(
- NewNonOwningRunnableMethod(gHalDiskSpaceWatcher, &GonkDiskSpaceWatcher::DoStart));
-}
-
-void
-StopDiskSpaceWatcher()
-{
- MOZ_ASSERT(NS_IsMainThread());
- if (!gHalDiskSpaceWatcher) {
- return;
- }
-
- XRE_GetIOMessageLoop()->PostTask(
- NewNonOwningRunnableMethod(gHalDiskSpaceWatcher, &GonkDiskSpaceWatcher::DoStop));
-}
-
-} // namespace hal_impl
-} // namespace mozilla
diff --git a/hal/gonk/GonkHal.cpp b/hal/gonk/GonkHal.cpp
deleted file mode 100644
index 05d9295a2..000000000
--- a/hal/gonk/GonkHal.cpp
+++ /dev/null
@@ -1,2045 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=8 et ft=cpp : */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/android_alarm.h>
-#include <math.h>
-#include <regex.h>
-#include <sched.h>
-#include <stdio.h>
-#include <sys/klog.h>
-#include <sys/stat.h>
-#include <sys/syscall.h>
-#include <sys/resource.h>
-#include <time.h>
-#include <unistd.h>
-
-#include "mozilla/DebugOnly.h"
-
-#include "android/log.h"
-#include "cutils/properties.h"
-#include "hardware/hardware.h"
-#include "hardware/lights.h"
-#include "hardware_legacy/uevent.h"
-#include "hardware_legacy/vibrator.h"
-#include "hardware_legacy/power.h"
-#include "libdisplay/GonkDisplay.h"
-#include "utils/threads.h"
-
-#include "base/message_loop.h"
-#include "base/task.h"
-
-#include "Hal.h"
-#include "HalImpl.h"
-#include "HalLog.h"
-#include "mozilla/ArrayUtils.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/dom/battery/Constants.h"
-#include "mozilla/DebugOnly.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/Monitor.h"
-#include "mozilla/RefPtr.h"
-#include "mozilla/Services.h"
-#include "mozilla/StaticMutex.h"
-#include "mozilla/StaticPtr.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/UniquePtrExtensions.h"
-#include "nsAlgorithm.h"
-#include "nsPrintfCString.h"
-#include "nsIObserver.h"
-#include "nsIObserverService.h"
-#include "nsIRecoveryService.h"
-#include "nsIRunnable.h"
-#include "nsScreenManagerGonk.h"
-#include "nsThreadUtils.h"
-#include "nsThreadUtils.h"
-#include "nsIThread.h"
-#include "nsXULAppAPI.h"
-#include "OrientationObserver.h"
-#include "UeventPoller.h"
-#include "nsIWritablePropertyBag2.h"
-#include <algorithm>
-
-#define NsecPerMsec 1000000LL
-#define NsecPerSec 1000000000
-
-// The header linux/oom.h is not available in bionic libc. We
-// redefine some of its constants here.
-
-#ifndef OOM_DISABLE
-#define OOM_DISABLE (-17)
-#endif
-
-#ifndef OOM_ADJUST_MIN
-#define OOM_ADJUST_MIN (-16)
-#endif
-
-#ifndef OOM_ADJUST_MAX
-#define OOM_ADJUST_MAX 15
-#endif
-
-#ifndef OOM_SCORE_ADJ_MIN
-#define OOM_SCORE_ADJ_MIN (-1000)
-#endif
-
-#ifndef OOM_SCORE_ADJ_MAX
-#define OOM_SCORE_ADJ_MAX 1000
-#endif
-
-#ifndef BATTERY_CHARGING_ARGB
-#define BATTERY_CHARGING_ARGB 0x00FF0000
-#endif
-#ifndef BATTERY_FULL_ARGB
-#define BATTERY_FULL_ARGB 0x0000FF00
-#endif
-
-using namespace mozilla;
-using namespace mozilla::hal;
-using namespace mozilla::dom;
-
-namespace mozilla {
-namespace hal_impl {
-
-/**
- * These are defined by libhardware, specifically, hardware/libhardware/include/hardware/lights.h
- * in the gonk subsystem.
- * If these change and are exposed to JS, make sure nsIHal.idl is updated as well.
- */
-enum LightType {
- eHalLightID_Backlight = 0,
- eHalLightID_Keyboard = 1,
- eHalLightID_Buttons = 2,
- eHalLightID_Battery = 3,
- eHalLightID_Notifications = 4,
- eHalLightID_Attention = 5,
- eHalLightID_Bluetooth = 6,
- eHalLightID_Wifi = 7,
- eHalLightID_Count // This should stay at the end
-};
-enum LightMode {
- eHalLightMode_User = 0, // brightness is managed by user setting
- eHalLightMode_Sensor = 1, // brightness is managed by a light sensor
- eHalLightMode_Count
-};
-enum FlashMode {
- eHalLightFlash_None = 0,
- eHalLightFlash_Timed = 1, // timed flashing. Use flashOnMS and flashOffMS for timing
- eHalLightFlash_Hardware = 2, // hardware assisted flashing
- eHalLightFlash_Count
-};
-
-struct LightConfiguration {
- LightType light;
- LightMode mode;
- FlashMode flash;
- uint32_t flashOnMS;
- uint32_t flashOffMS;
- uint32_t color;
-};
-
-static light_device_t* sLights[eHalLightID_Count]; // will be initialized to nullptr
-
-static light_device_t*
-GetDevice(hw_module_t* module, char const* name)
-{
- int err;
- hw_device_t* device;
- err = module->methods->open(module, name, &device);
- if (err == 0) {
- return (light_device_t*)device;
- } else {
- return nullptr;
- }
-}
-
-static void
-InitLights()
-{
- // assume that if backlight is nullptr, nothing has been set yet
- // if this is not true, the initialization will occur everytime a light is read or set!
- if (!sLights[eHalLightID_Backlight]) {
- int err;
- hw_module_t* module;
-
- err = hw_get_module(LIGHTS_HARDWARE_MODULE_ID, (hw_module_t const**)&module);
- if (err == 0) {
- sLights[eHalLightID_Backlight]
- = GetDevice(module, LIGHT_ID_BACKLIGHT);
- sLights[eHalLightID_Keyboard]
- = GetDevice(module, LIGHT_ID_KEYBOARD);
- sLights[eHalLightID_Buttons]
- = GetDevice(module, LIGHT_ID_BUTTONS);
- sLights[eHalLightID_Battery]
- = GetDevice(module, LIGHT_ID_BATTERY);
- sLights[eHalLightID_Notifications]
- = GetDevice(module, LIGHT_ID_NOTIFICATIONS);
- sLights[eHalLightID_Attention]
- = GetDevice(module, LIGHT_ID_ATTENTION);
- sLights[eHalLightID_Bluetooth]
- = GetDevice(module, LIGHT_ID_BLUETOOTH);
- sLights[eHalLightID_Wifi]
- = GetDevice(module, LIGHT_ID_WIFI);
- }
- }
-}
-
-/**
- * The state last set for the lights until liblights supports
- * getting the light state.
- */
-static light_state_t sStoredLightState[eHalLightID_Count];
-
-/**
-* Set the value of a light to a particular color, with a specific flash pattern.
-* light specifices which light. See Hal.idl for the list of constants
-* mode specifies user set or based on ambient light sensor
-* flash specifies whether or how to flash the light
-* flashOnMS and flashOffMS specify the pattern for XXX flash mode
-* color specifies the color. If the light doesn't support color, the given color is
-* transformed into a brightness, or just an on/off if that is all the light is capable of.
-* returns true if successful and false if failed.
-*/
-static bool
-SetLight(LightType light, const LightConfiguration& aConfig)
-{
- light_state_t state;
-
- InitLights();
-
- if (light < 0 || light >= eHalLightID_Count ||
- sLights[light] == nullptr) {
- return false;
- }
-
- memset(&state, 0, sizeof(light_state_t));
- state.color = aConfig.color;
- state.flashMode = aConfig.flash;
- state.flashOnMS = aConfig.flashOnMS;
- state.flashOffMS = aConfig.flashOffMS;
- state.brightnessMode = aConfig.mode;
-
- sLights[light]->set_light(sLights[light], &state);
- sStoredLightState[light] = state;
- return true;
-}
-
-/**
-* GET the value of a light returning a particular color, with a specific flash pattern.
-* returns true if successful and false if failed.
-*/
-static bool
-GetLight(LightType light, LightConfiguration* aConfig)
-{
- light_state_t state;
-
- if (light < 0 || light >= eHalLightID_Count ||
- sLights[light] == nullptr) {
- return false;
- }
-
- memset(&state, 0, sizeof(light_state_t));
- state = sStoredLightState[light];
-
- aConfig->light = light;
- aConfig->color = state.color;
- aConfig->flash = FlashMode(state.flashMode);
- aConfig->flashOnMS = state.flashOnMS;
- aConfig->flashOffMS = state.flashOffMS;
- aConfig->mode = LightMode(state.brightnessMode);
-
- return true;
-}
-
-namespace {
-
-/**
- * This runnable runs for the lifetime of the program, once started. It's
- * responsible for "playing" vibration patterns.
- */
-class VibratorRunnable final
- : public nsIRunnable
- , public nsIObserver
-{
-public:
- VibratorRunnable()
- : mMonitor("VibratorRunnable")
- , mIndex(0)
- {
- nsCOMPtr<nsIObserverService> os = services::GetObserverService();
- if (!os) {
- NS_WARNING("Could not get observer service!");
- return;
- }
-
- os->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
- }
-
- NS_DECL_THREADSAFE_ISUPPORTS
- NS_DECL_NSIRUNNABLE
- NS_DECL_NSIOBSERVER
-
- // Run on the main thread, not the vibrator thread.
- void Vibrate(const nsTArray<uint32_t> &pattern);
- void CancelVibrate();
-
- static bool ShuttingDown() { return sShuttingDown; }
-
-protected:
- ~VibratorRunnable() {}
-
-private:
- Monitor mMonitor;
-
- // The currently-playing pattern.
- nsTArray<uint32_t> mPattern;
-
- // The index we're at in the currently-playing pattern. If mIndex >=
- // mPattern.Length(), then we're not currently playing anything.
- uint32_t mIndex;
-
- // Set to true in our shutdown observer. When this is true, we kill the
- // vibrator thread.
- static bool sShuttingDown;
-};
-
-NS_IMPL_ISUPPORTS(VibratorRunnable, nsIRunnable, nsIObserver);
-
-bool VibratorRunnable::sShuttingDown = false;
-
-static StaticRefPtr<VibratorRunnable> sVibratorRunnable;
-
-NS_IMETHODIMP
-VibratorRunnable::Run()
-{
- MonitorAutoLock lock(mMonitor);
-
- // We currently assume that mMonitor.Wait(X) waits for X milliseconds. But in
- // reality, the kernel might not switch to this thread for some time after the
- // wait expires. So there's potential for some inaccuracy here.
- //
- // This doesn't worry me too much. Note that we don't even start vibrating
- // immediately when VibratorRunnable::Vibrate is called -- we go through a
- // condvar onto another thread. Better just to be chill about small errors in
- // the timing here.
-
- while (!sShuttingDown) {
- if (mIndex < mPattern.Length()) {
- uint32_t duration = mPattern[mIndex];
- if (mIndex % 2 == 0) {
- vibrator_on(duration);
- }
- mIndex++;
- mMonitor.Wait(PR_MillisecondsToInterval(duration));
- }
- else {
- mMonitor.Wait();
- }
- }
- sVibratorRunnable = nullptr;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-VibratorRunnable::Observe(nsISupports *subject, const char *topic,
- const char16_t *data)
-{
- MOZ_ASSERT(strcmp(topic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0);
- MonitorAutoLock lock(mMonitor);
- sShuttingDown = true;
- mMonitor.Notify();
-
- return NS_OK;
-}
-
-void
-VibratorRunnable::Vibrate(const nsTArray<uint32_t> &pattern)
-{
- MonitorAutoLock lock(mMonitor);
- mPattern = pattern;
- mIndex = 0;
- mMonitor.Notify();
-}
-
-void
-VibratorRunnable::CancelVibrate()
-{
- MonitorAutoLock lock(mMonitor);
- mPattern.Clear();
- mPattern.AppendElement(0);
- mIndex = 0;
- mMonitor.Notify();
-}
-
-void
-EnsureVibratorThreadInitialized()
-{
- if (sVibratorRunnable) {
- return;
- }
-
- sVibratorRunnable = new VibratorRunnable();
- nsCOMPtr<nsIThread> thread;
- NS_NewThread(getter_AddRefs(thread), sVibratorRunnable);
-}
-
-} // namespace
-
-void
-Vibrate(const nsTArray<uint32_t> &pattern, const hal::WindowIdentifier &)
-{
- MOZ_ASSERT(NS_IsMainThread());
- if (VibratorRunnable::ShuttingDown()) {
- return;
- }
- EnsureVibratorThreadInitialized();
- sVibratorRunnable->Vibrate(pattern);
-}
-
-void
-CancelVibrate(const hal::WindowIdentifier &)
-{
- MOZ_ASSERT(NS_IsMainThread());
- if (VibratorRunnable::ShuttingDown()) {
- return;
- }
- EnsureVibratorThreadInitialized();
- sVibratorRunnable->CancelVibrate();
-}
-
-namespace {
-
-class BatteryUpdater : public Runnable {
-public:
- NS_IMETHOD Run() override
- {
- hal::BatteryInformation info;
- hal_impl::GetCurrentBatteryInformation(&info);
-
- // Control the battery indicator (led light) here using BatteryInformation
- // we just retrieved.
- uint32_t color = 0; // Format: 0x00rrggbb.
- if (info.charging() && (info.level() == 1)) {
- // Charging and battery full.
- color = BATTERY_FULL_ARGB;
- } else if (info.charging() && (info.level() < 1)) {
- // Charging but not full.
- color = BATTERY_CHARGING_ARGB;
- } // else turn off battery indicator.
-
- LightConfiguration aConfig;
- aConfig.light = eHalLightID_Battery;
- aConfig.mode = eHalLightMode_User;
- aConfig.flash = eHalLightFlash_None;
- aConfig.flashOnMS = aConfig.flashOffMS = 0;
- aConfig.color = color;
-
- SetLight(eHalLightID_Battery, aConfig);
-
- hal::NotifyBatteryChange(info);
-
- {
- // bug 975667
- // Gecko gonk hal is required to emit battery charging/level notification via nsIObserverService.
- // This is useful for XPCOM components that are not statically linked to Gecko and cannot call
- // hal::EnableBatteryNotifications
- nsCOMPtr<nsIObserverService> obsService = mozilla::services::GetObserverService();
- nsCOMPtr<nsIWritablePropertyBag2> propbag =
- do_CreateInstance("@mozilla.org/hash-property-bag;1");
- if (obsService && propbag) {
- propbag->SetPropertyAsBool(NS_LITERAL_STRING("charging"),
- info.charging());
- propbag->SetPropertyAsDouble(NS_LITERAL_STRING("level"),
- info.level());
-
- obsService->NotifyObservers(propbag, "gonkhal-battery-notifier", nullptr);
- }
- }
-
- return NS_OK;
- }
-};
-
-} // namespace
-
-class BatteryObserver final : public IUeventObserver
-{
-public:
- NS_INLINE_DECL_REFCOUNTING(BatteryObserver)
-
- BatteryObserver()
- :mUpdater(new BatteryUpdater())
- {
- }
-
- virtual void Notify(const NetlinkEvent &aEvent)
- {
- // this will run on IO thread
- NetlinkEvent *event = const_cast<NetlinkEvent*>(&aEvent);
- const char *subsystem = event->getSubsystem();
- // e.g. DEVPATH=/devices/platform/sec-battery/power_supply/battery
- const char *devpath = event->findParam("DEVPATH");
- if (strcmp(subsystem, "power_supply") == 0 &&
- strstr(devpath, "battery")) {
- // aEvent will be valid only in this method.
- NS_DispatchToMainThread(mUpdater);
- }
- }
-
-protected:
- ~BatteryObserver() {}
-
-private:
- RefPtr<BatteryUpdater> mUpdater;
-};
-
-// sBatteryObserver is owned by the IO thread. Only the IO thread may
-// create or destroy it.
-static StaticRefPtr<BatteryObserver> sBatteryObserver;
-
-static void
-RegisterBatteryObserverIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(!sBatteryObserver);
-
- sBatteryObserver = new BatteryObserver();
- RegisterUeventListener(sBatteryObserver);
-}
-
-void
-EnableBatteryNotifications()
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(RegisterBatteryObserverIOThread));
-}
-
-static void
-UnregisterBatteryObserverIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(sBatteryObserver);
-
- UnregisterUeventListener(sBatteryObserver);
- sBatteryObserver = nullptr;
-}
-
-void
-DisableBatteryNotifications()
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(UnregisterBatteryObserverIOThread));
-}
-
-static bool
-GetCurrentBatteryCharge(int* aCharge)
-{
- bool success = ReadSysFile("/sys/class/power_supply/battery/capacity",
- aCharge);
- if (!success) {
- return false;
- }
-
- #ifdef DEBUG
- if ((*aCharge < 0) || (*aCharge > 100)) {
- HAL_LOG("charge level contains unknown value: %d", *aCharge);
- }
- #endif
-
- return (*aCharge >= 0) && (*aCharge <= 100);
-}
-
-static bool
-GetCurrentBatteryCharging(int* aCharging)
-{
- static const DebugOnly<int> BATTERY_NOT_CHARGING = 0;
- static const int BATTERY_CHARGING_USB = 1;
- static const int BATTERY_CHARGING_AC = 2;
-
- // Generic device support
-
- int chargingSrc;
- bool success =
- ReadSysFile("/sys/class/power_supply/battery/charging_source", &chargingSrc);
-
- if (success) {
- #ifdef DEBUG
- if (chargingSrc != BATTERY_NOT_CHARGING &&
- chargingSrc != BATTERY_CHARGING_USB &&
- chargingSrc != BATTERY_CHARGING_AC) {
- HAL_LOG("charging_source contained unknown value: %d", chargingSrc);
- }
- #endif
-
- *aCharging = (chargingSrc == BATTERY_CHARGING_USB ||
- chargingSrc == BATTERY_CHARGING_AC);
- return true;
- }
-
- // Otoro device support
-
- char chargingSrcString[16];
-
- success = ReadSysFile("/sys/class/power_supply/battery/status",
- chargingSrcString, sizeof(chargingSrcString));
- if (success) {
- *aCharging = strcmp(chargingSrcString, "Charging") == 0 ||
- strcmp(chargingSrcString, "Full") == 0;
- return true;
- }
-
- return false;
-}
-
-void
-GetCurrentBatteryInformation(hal::BatteryInformation* aBatteryInfo)
-{
- int charge;
- static bool previousCharging = false;
- static double previousLevel = 0.0, remainingTime = 0.0;
- static struct timespec lastLevelChange;
- struct timespec now;
- double dtime, dlevel;
-
- if (GetCurrentBatteryCharge(&charge)) {
- aBatteryInfo->level() = (double)charge / 100.0;
- } else {
- aBatteryInfo->level() = dom::battery::kDefaultLevel;
- }
-
- int charging;
-
- if (GetCurrentBatteryCharging(&charging)) {
- aBatteryInfo->charging() = charging;
- } else {
- aBatteryInfo->charging() = true;
- }
-
- if (aBatteryInfo->charging() != previousCharging){
- aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
- memset(&lastLevelChange, 0, sizeof(struct timespec));
- remainingTime = 0.0;
- }
-
- if (aBatteryInfo->charging()) {
- if (aBatteryInfo->level() == 1.0) {
- aBatteryInfo->remainingTime() = dom::battery::kDefaultRemainingTime;
- } else if (aBatteryInfo->level() != previousLevel){
- if (lastLevelChange.tv_sec != 0) {
- clock_gettime(CLOCK_MONOTONIC, &now);
- dtime = now.tv_sec - lastLevelChange.tv_sec;
- dlevel = aBatteryInfo->level() - previousLevel;
-
- if (dlevel <= 0.0) {
- aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
- } else {
- remainingTime = (double) round(dtime / dlevel * (1.0 - aBatteryInfo->level()));
- aBatteryInfo->remainingTime() = remainingTime;
- }
-
- lastLevelChange = now;
- } else { // lastLevelChange.tv_sec == 0
- clock_gettime(CLOCK_MONOTONIC, &lastLevelChange);
- aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
- }
-
- } else {
- clock_gettime(CLOCK_MONOTONIC, &now);
- dtime = now.tv_sec - lastLevelChange.tv_sec;
- if (dtime < remainingTime) {
- aBatteryInfo->remainingTime() = round(remainingTime - dtime);
- } else {
- aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
- }
-
- }
-
- } else {
- if (aBatteryInfo->level() == 0.0) {
- aBatteryInfo->remainingTime() = dom::battery::kDefaultRemainingTime;
- } else if (aBatteryInfo->level() != previousLevel){
- if (lastLevelChange.tv_sec != 0) {
- clock_gettime(CLOCK_MONOTONIC, &now);
- dtime = now.tv_sec - lastLevelChange.tv_sec;
- dlevel = previousLevel - aBatteryInfo->level();
-
- if (dlevel <= 0.0) {
- aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
- } else {
- remainingTime = (double) round(dtime / dlevel * aBatteryInfo->level());
- aBatteryInfo->remainingTime() = remainingTime;
- }
-
- lastLevelChange = now;
- } else { // lastLevelChange.tv_sec == 0
- clock_gettime(CLOCK_MONOTONIC, &lastLevelChange);
- aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
- }
-
- } else {
- clock_gettime(CLOCK_MONOTONIC, &now);
- dtime = now.tv_sec - lastLevelChange.tv_sec;
- if (dtime < remainingTime) {
- aBatteryInfo->remainingTime() = round(remainingTime - dtime);
- } else {
- aBatteryInfo->remainingTime() = dom::battery::kUnknownRemainingTime;
- }
-
- }
- }
-
- previousCharging = aBatteryInfo->charging();
- previousLevel = aBatteryInfo->level();
-}
-
-namespace {
-
-// We can write to screenEnabledFilename to enable/disable the screen, but when
-// we read, we always get "mem"! So we have to keep track ourselves whether
-// the screen is on or not.
-bool sScreenEnabled = true;
-
-// We can read wakeLockFilename to find out whether the cpu wake lock
-// is already acquired, but reading and parsing it is a lot more work
-// than tracking it ourselves, and it won't be accurate anyway (kernel
-// internal wake locks aren't counted here.)
-bool sCpuSleepAllowed = true;
-
-// Some CPU wake locks may be acquired internally in HAL. We use a counter to
-// keep track of these needs. Note we have to hold |sInternalLockCpuMutex|
-// when reading or writing this variable to ensure thread-safe.
-int32_t sInternalLockCpuCount = 0;
-
-} // namespace
-
-bool
-GetScreenEnabled()
-{
- return sScreenEnabled;
-}
-
-void
-SetScreenEnabled(bool aEnabled)
-{
- GetGonkDisplay()->SetEnabled(aEnabled);
- sScreenEnabled = aEnabled;
-}
-
-bool
-GetKeyLightEnabled()
-{
- LightConfiguration config;
- bool ok = GetLight(eHalLightID_Buttons, &config);
- if (ok) {
- return (config.color != 0x00000000);
- }
- return false;
-}
-
-void
-SetKeyLightEnabled(bool aEnabled)
-{
- LightConfiguration config;
- config.mode = eHalLightMode_User;
- config.flash = eHalLightFlash_None;
- config.flashOnMS = config.flashOffMS = 0;
- config.color = 0x00000000;
-
- if (aEnabled) {
- // Convert the value in [0, 1] to an int between 0 and 255 and then convert
- // it to a color. Note that the high byte is FF, corresponding to the alpha
- // channel.
- double brightness = GetScreenBrightness();
- uint32_t val = static_cast<int>(round(brightness * 255.0));
- uint32_t color = (0xff<<24) + (val<<16) + (val<<8) + val;
-
- config.color = color;
- }
-
- SetLight(eHalLightID_Buttons, config);
- SetLight(eHalLightID_Keyboard, config);
-}
-
-double
-GetScreenBrightness()
-{
- LightConfiguration config;
- LightType light = eHalLightID_Backlight;
-
- bool ok = GetLight(light, &config);
- if (ok) {
- // backlight is brightness only, so using one of the RGB elements as value.
- int brightness = config.color & 0xFF;
- return brightness / 255.0;
- }
- // If GetLight fails, it's because the light doesn't exist. So return
- // a value corresponding to "off".
- return 0;
-}
-
-void
-SetScreenBrightness(double brightness)
-{
- // Don't use De Morgan's law to push the ! into this expression; we want to
- // catch NaN too.
- if (!(0 <= brightness && brightness <= 1)) {
- HAL_LOG("SetScreenBrightness: Dropping illegal brightness %f.", brightness);
- return;
- }
-
- // Convert the value in [0, 1] to an int between 0 and 255 and convert to a color
- // note that the high byte is FF, corresponding to the alpha channel.
- uint32_t val = static_cast<int>(round(brightness * 255.0));
- uint32_t color = (0xff<<24) + (val<<16) + (val<<8) + val;
-
- LightConfiguration config;
- config.mode = eHalLightMode_User;
- config.flash = eHalLightFlash_None;
- config.flashOnMS = config.flashOffMS = 0;
- config.color = color;
- SetLight(eHalLightID_Backlight, config);
- if (GetKeyLightEnabled()) {
- SetLight(eHalLightID_Buttons, config);
- SetLight(eHalLightID_Keyboard, config);
- }
-}
-
-static StaticMutex sInternalLockCpuMutex;
-
-static void
-UpdateCpuSleepState()
-{
- const char *wakeLockFilename = "/sys/power/wake_lock";
- const char *wakeUnlockFilename = "/sys/power/wake_unlock";
-
- sInternalLockCpuMutex.AssertCurrentThreadOwns();
- bool allowed = sCpuSleepAllowed && !sInternalLockCpuCount;
- WriteSysFile(allowed ? wakeUnlockFilename : wakeLockFilename, "gecko");
-}
-
-static void
-InternalLockCpu() {
- StaticMutexAutoLock lock(sInternalLockCpuMutex);
- ++sInternalLockCpuCount;
- UpdateCpuSleepState();
-}
-
-static void
-InternalUnlockCpu() {
- StaticMutexAutoLock lock(sInternalLockCpuMutex);
- --sInternalLockCpuCount;
- UpdateCpuSleepState();
-}
-
-bool
-GetCpuSleepAllowed()
-{
- return sCpuSleepAllowed;
-}
-
-void
-SetCpuSleepAllowed(bool aAllowed)
-{
- StaticMutexAutoLock lock(sInternalLockCpuMutex);
- sCpuSleepAllowed = aAllowed;
- UpdateCpuSleepState();
-}
-
-void
-AdjustSystemClock(int64_t aDeltaMilliseconds)
-{
- int fd;
- struct timespec now;
-
- if (aDeltaMilliseconds == 0) {
- return;
- }
-
- // Preventing context switch before setting system clock
- sched_yield();
- clock_gettime(CLOCK_REALTIME, &now);
- now.tv_sec += (time_t)(aDeltaMilliseconds / 1000LL);
- now.tv_nsec += (long)((aDeltaMilliseconds % 1000LL) * NsecPerMsec);
- if (now.tv_nsec >= NsecPerSec) {
- now.tv_sec += 1;
- now.tv_nsec -= NsecPerSec;
- }
-
- if (now.tv_nsec < 0) {
- now.tv_nsec += NsecPerSec;
- now.tv_sec -= 1;
- }
-
- do {
- fd = open("/dev/alarm", O_RDWR);
- } while (fd == -1 && errno == EINTR);
- ScopedClose autoClose(fd);
- if (fd < 0) {
- HAL_LOG("Failed to open /dev/alarm: %s", strerror(errno));
- return;
- }
-
- if (ioctl(fd, ANDROID_ALARM_SET_RTC, &now) < 0) {
- HAL_LOG("ANDROID_ALARM_SET_RTC failed: %s", strerror(errno));
- }
-
- hal::NotifySystemClockChange(aDeltaMilliseconds);
-}
-
-int32_t
-GetTimezoneOffset()
-{
- PRExplodedTime prTime;
- PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &prTime);
-
- // Daylight saving time (DST) will be taken into account.
- int32_t offset = prTime.tm_params.tp_gmt_offset;
- offset += prTime.tm_params.tp_dst_offset;
-
- // Returns the timezone offset relative to UTC in minutes.
- return -(offset / 60);
-}
-
-static int32_t sKernelTimezoneOffset = 0;
-
-static void
-UpdateKernelTimezone(int32_t timezoneOffset)
-{
- if (sKernelTimezoneOffset == timezoneOffset) {
- return;
- }
-
- // Tell the kernel about the new time zone as well, so that FAT filesystems
- // will get local timestamps rather than UTC timestamps.
- //
- // We assume that /init.rc has a sysclktz entry so that settimeofday has
- // already been called once before we call it (there is a side-effect in
- // the kernel the very first time settimeofday is called where it does some
- // special processing if you only set the timezone).
- struct timezone tz;
- memset(&tz, 0, sizeof(tz));
- tz.tz_minuteswest = timezoneOffset;
- settimeofday(nullptr, &tz);
- sKernelTimezoneOffset = timezoneOffset;
-}
-
-void
-SetTimezone(const nsCString& aTimezoneSpec)
-{
- if (aTimezoneSpec.Equals(GetTimezone())) {
- // Even though the timezone hasn't changed, we still need to tell the
- // kernel what the current timezone is. The timezone is persisted in
- // a property and doesn't change across reboots, but the kernel still
- // needs to be updated on every boot.
- UpdateKernelTimezone(GetTimezoneOffset());
- return;
- }
-
- int32_t oldTimezoneOffsetMinutes = GetTimezoneOffset();
- property_set("persist.sys.timezone", aTimezoneSpec.get());
- // This function is automatically called by the other time conversion
- // functions that depend on the timezone. To be safe, we call it manually.
- tzset();
- int32_t newTimezoneOffsetMinutes = GetTimezoneOffset();
- UpdateKernelTimezone(newTimezoneOffsetMinutes);
- hal::NotifySystemTimezoneChange(
- hal::SystemTimezoneChangeInformation(
- oldTimezoneOffsetMinutes, newTimezoneOffsetMinutes));
-}
-
-nsCString
-GetTimezone()
-{
- char timezone[32];
- property_get("persist.sys.timezone", timezone, "");
- return nsCString(timezone);
-}
-
-void
-EnableSystemClockChangeNotifications()
-{
-}
-
-void
-DisableSystemClockChangeNotifications()
-{
-}
-
-void
-EnableSystemTimezoneChangeNotifications()
-{
-}
-
-void
-DisableSystemTimezoneChangeNotifications()
-{
-}
-
-// Nothing to do here. Gonk widgetry always listens for screen
-// orientation changes.
-void
-EnableScreenConfigurationNotifications()
-{
-}
-
-void
-DisableScreenConfigurationNotifications()
-{
-}
-
-void
-GetCurrentScreenConfiguration(hal::ScreenConfiguration* aScreenConfiguration)
-{
- RefPtr<nsScreenGonk> screen = nsScreenManagerGonk::GetPrimaryScreen();
- *aScreenConfiguration = screen->GetConfiguration();
-}
-
-bool
-LockScreenOrientation(const dom::ScreenOrientationInternal& aOrientation)
-{
- return OrientationObserver::GetInstance()->LockScreenOrientation(aOrientation);
-}
-
-void
-UnlockScreenOrientation()
-{
- OrientationObserver::GetInstance()->UnlockScreenOrientation();
-}
-
-// This thread will wait for the alarm firing by a blocking IO.
-static pthread_t sAlarmFireWatcherThread;
-
-// If |sAlarmData| is non-null, it's owned by the alarm-watcher thread.
-struct AlarmData {
-public:
- AlarmData(int aFd) : mFd(aFd),
- mGeneration(sNextGeneration++),
- mShuttingDown(false) {}
- ScopedClose mFd;
- int mGeneration;
- bool mShuttingDown;
-
- static int sNextGeneration;
-
-};
-
-int AlarmData::sNextGeneration = 0;
-
-AlarmData* sAlarmData = nullptr;
-
-class AlarmFiredEvent : public Runnable {
-public:
- AlarmFiredEvent(int aGeneration) : mGeneration(aGeneration) {}
-
- NS_IMETHOD Run() override {
- // Guard against spurious notifications caused by an alarm firing
- // concurrently with it being disabled.
- if (sAlarmData && !sAlarmData->mShuttingDown &&
- mGeneration == sAlarmData->mGeneration) {
- hal::NotifyAlarmFired();
- }
- // The fired alarm event has been delivered to the observer (if needed);
- // we can now release a CPU wake lock.
- InternalUnlockCpu();
- return NS_OK;
- }
-
-private:
- int mGeneration;
-};
-
-// Runs on alarm-watcher thread.
-static void
-DestroyAlarmData(void* aData)
-{
- AlarmData* alarmData = static_cast<AlarmData*>(aData);
- delete alarmData;
-}
-
-// Runs on alarm-watcher thread.
-void ShutDownAlarm(int aSigno)
-{
- if (aSigno == SIGUSR1 && sAlarmData) {
- sAlarmData->mShuttingDown = true;
- }
- return;
-}
-
-static void*
-WaitForAlarm(void* aData)
-{
- pthread_cleanup_push(DestroyAlarmData, aData);
-
- AlarmData* alarmData = static_cast<AlarmData*>(aData);
-
- while (!alarmData->mShuttingDown) {
- int alarmTypeFlags = 0;
-
- // ALARM_WAIT apparently will block even if an alarm hasn't been
- // programmed, although this behavior doesn't seem to be
- // documented. We rely on that here to avoid spinning the CPU
- // while awaiting an alarm to be programmed.
- do {
- alarmTypeFlags = ioctl(alarmData->mFd, ANDROID_ALARM_WAIT);
- } while (alarmTypeFlags < 0 && errno == EINTR &&
- !alarmData->mShuttingDown);
-
- if (!alarmData->mShuttingDown && alarmTypeFlags >= 0 &&
- (alarmTypeFlags & ANDROID_ALARM_RTC_WAKEUP_MASK)) {
- // To make sure the observer can get the alarm firing notification
- // *on time* (the system won't sleep during the process in any way),
- // we need to acquire a CPU wake lock before firing the alarm event.
- InternalLockCpu();
- RefPtr<AlarmFiredEvent> event =
- new AlarmFiredEvent(alarmData->mGeneration);
- NS_DispatchToMainThread(event);
- }
- }
-
- pthread_cleanup_pop(1);
- return nullptr;
-}
-
-bool
-EnableAlarm()
-{
- MOZ_ASSERT(!sAlarmData);
-
- int alarmFd = open("/dev/alarm", O_RDWR);
- if (alarmFd < 0) {
- HAL_LOG("Failed to open alarm device: %s.", strerror(errno));
- return false;
- }
-
- UniquePtr<AlarmData> alarmData = MakeUnique<AlarmData>(alarmFd);
-
- struct sigaction actions;
- memset(&actions, 0, sizeof(actions));
- sigemptyset(&actions.sa_mask);
- actions.sa_flags = 0;
- actions.sa_handler = ShutDownAlarm;
- if (sigaction(SIGUSR1, &actions, nullptr)) {
- HAL_LOG("Failed to set SIGUSR1 signal for alarm-watcher thread.");
- return false;
- }
-
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
-
- int status = pthread_create(&sAlarmFireWatcherThread, &attr, WaitForAlarm,
- alarmData.get());
- if (status) {
- alarmData.reset();
- HAL_LOG("Failed to create alarm-watcher thread. Status: %d.", status);
- return false;
- }
-
- pthread_attr_destroy(&attr);
-
- // The thread owns this now. We only hold a pointer.
- sAlarmData = alarmData.release();
- return true;
-}
-
-void
-DisableAlarm()
-{
- MOZ_ASSERT(sAlarmData);
-
- // NB: this must happen-before the thread cancellation.
- sAlarmData = nullptr;
-
- // The cancel will interrupt the thread and destroy it, freeing the
- // data pointed at by sAlarmData.
- DebugOnly<int> err = pthread_kill(sAlarmFireWatcherThread, SIGUSR1);
- MOZ_ASSERT(!err);
-}
-
-bool
-SetAlarm(int32_t aSeconds, int32_t aNanoseconds)
-{
- if (!sAlarmData) {
- HAL_LOG("We should have enabled the alarm.");
- return false;
- }
-
- struct timespec ts;
- ts.tv_sec = aSeconds;
- ts.tv_nsec = aNanoseconds;
-
- // Currently we only support RTC wakeup alarm type.
- const int result = ioctl(sAlarmData->mFd,
- ANDROID_ALARM_SET(ANDROID_ALARM_RTC_WAKEUP), &ts);
-
- if (result < 0) {
- HAL_LOG("Unable to set alarm: %s.", strerror(errno));
- return false;
- }
-
- return true;
-}
-
-static int
-OomAdjOfOomScoreAdj(int aOomScoreAdj)
-{
- // Convert OOM adjustment from the domain of /proc/<pid>/oom_score_adj
- // to the domain of /proc/<pid>/oom_adj.
-
- int adj;
-
- if (aOomScoreAdj < 0) {
- adj = (OOM_DISABLE * aOomScoreAdj) / OOM_SCORE_ADJ_MIN;
- } else {
- adj = (OOM_ADJUST_MAX * aOomScoreAdj) / OOM_SCORE_ADJ_MAX;
- }
-
- return adj;
-}
-
-static void
-RoundOomScoreAdjUpWithLRU(int& aOomScoreAdj, uint32_t aLRU)
-{
- // We want to add minimum value to round OomScoreAdj up according to
- // the steps by aLRU.
- aOomScoreAdj +=
- ceil(((float)OOM_SCORE_ADJ_MAX / OOM_ADJUST_MAX) * aLRU);
-}
-
-#define OOM_LOG(level, args...) __android_log_print(level, "OomLogger", ##args)
-class OomVictimLogger final
- : public nsIObserver
-{
-public:
- OomVictimLogger()
- : mLastLineChecked(-1.0),
- mRegexes(nullptr)
- {
- // Enable timestamps in kernel's printk
- WriteSysFile("/sys/module/printk/parameters/time", "Y");
- }
-
- NS_DECL_ISUPPORTS
- NS_DECL_NSIOBSERVER
-
-protected:
- ~OomVictimLogger() {}
-
-private:
- double mLastLineChecked;
- UniqueFreePtr<regex_t> mRegexes;
-};
-NS_IMPL_ISUPPORTS(OomVictimLogger, nsIObserver);
-
-NS_IMETHODIMP
-OomVictimLogger::Observe(
- nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData)
-{
- nsDependentCString event_type(aTopic);
- if (!event_type.EqualsLiteral("ipc:content-shutdown")) {
- return NS_OK;
- }
-
- // OOM message finding regexes
- const char* const regexes_raw[] = {
- ".*select.*to kill.*",
- ".*send sigkill to.*",
- ".*lowmem_shrink.*",
- ".*[Oo]ut of [Mm]emory.*",
- ".*[Kk]ill [Pp]rocess.*",
- ".*[Kk]illed [Pp]rocess.*",
- ".*oom-killer.*",
- // The regexes below are for the output of dump_task from oom_kill.c
- // 1st - title 2nd - body lines (8 ints and a string)
- // oom_adj and oom_score_adj can be negative
- "\\[ pid \\] uid tgid total_vm rss cpu oom_adj oom_score_adj name",
- "\\[.*[0-9][0-9]*\\][ ]*[0-9][0-9]*[ ]*[0-9][0-9]*[ ]*[0-9][0-9]*[ ]*[0-9][0-9]*[ ]*[0-9][0-9]*[ ]*.[0-9][0-9]*[ ]*.[0-9][0-9]*.*"
- };
- const size_t regex_count = ArrayLength(regexes_raw);
-
- // Compile our regex just in time
- if (!mRegexes) {
- UniqueFreePtr<regex_t> regexes(
- static_cast<regex_t*>(malloc(sizeof(regex_t) * regex_count))
- );
- mRegexes.swap(regexes);
- for (size_t i = 0; i < regex_count; i++) {
- int compilation_err =
- regcomp(&(mRegexes.get()[i]), regexes_raw[i], REG_NOSUB);
- if (compilation_err) {
- OOM_LOG(ANDROID_LOG_ERROR, "Cannot compile regex \"%s\"\n", regexes_raw[i]);
- return NS_OK;
- }
- }
- }
-
-#ifndef KLOG_SIZE_BUFFER
- // Upstream bionic in commit
- // e249b059637b49a285ed9f58a2a18bfd054e5d95
- // deprecated the old klog defs.
- // Our current bionic does not hit this
- // change yet so handle the future change.
- // (ICS doesn't have KLOG_SIZE_BUFFER but
- // JB and onwards does.)
- #define KLOG_SIZE_BUFFER KLOG_WRITE
-#endif
- // Retreive kernel log
- int msg_buf_size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
- UniqueFreePtr<char> msg_buf(static_cast<char *>(malloc(msg_buf_size + 1)));
- int read_size = klogctl(KLOG_READ_ALL, msg_buf.get(), msg_buf_size);
-
- // Turn buffer into cstring
- read_size = read_size > msg_buf_size ? msg_buf_size : read_size;
- msg_buf.get()[read_size] = '\0';
-
- // Foreach line
- char* line_end;
- char* line_begin = msg_buf.get();
- for (; (line_end = strchr(line_begin, '\n')); line_begin = line_end + 1) {
- // make line into cstring
- *line_end = '\0';
-
- // Note: Kernel messages look like:
- // <5>[63648.286409] sd 35:0:0:0: Attached scsi generic sg1 type 0
- // 5 is the loging level
- // [*] is the time timestamp, seconds since boot
- // last comes the logged message
-
- // Since the logging level can be a string we must
- // skip it since scanf lacks wildcard matching
- char* timestamp_begin = strchr(line_begin, '[');
- char after_float;
- double lineTimestamp = -1;
- bool lineTimestampFound = false;
- if (timestamp_begin &&
- // Note: scanf treats a ' ' as [ ]*
- // Note: scanf treats [ %lf] as [ %lf thus we must check
- // for the closing bracket outselves.
- 2 == sscanf(timestamp_begin, "[ %lf%c", &lineTimestamp, &after_float) &&
- after_float == ']') {
- if (lineTimestamp <= mLastLineChecked) {
- continue;
- }
-
- lineTimestampFound = true;
- mLastLineChecked = lineTimestamp;
- }
-
- // Log interesting lines
- for (size_t i = 0; i < regex_count; i++) {
- int matching = !regexec(&(mRegexes.get()[i]), line_begin, 0, NULL, 0);
- if (matching) {
- // Log content of kernel message. We try to skip the ], but if for
- // some reason (most likely due to buffer overflow/wraparound), we
- // can't find the ] then we just log the entire line.
- char* endOfTimestamp = strchr(line_begin, ']');
- if (endOfTimestamp && endOfTimestamp[1] == ' ') {
- // skip the ] and the space that follows it
- line_begin = endOfTimestamp + 2;
- }
- if (!lineTimestampFound) {
- OOM_LOG(ANDROID_LOG_WARN, "following kill message may be a duplicate");
- }
- OOM_LOG(ANDROID_LOG_ERROR, "[Kill]: %s\n", line_begin);
- break;
- }
- }
- }
-
- return NS_OK;
-}
-
-/**
- * Wraps a particular ProcessPriority, giving us easy access to the prefs that
- * are relevant to it.
- *
- * Creating a PriorityClass also ensures that the control group is created.
- */
-class PriorityClass
-{
-public:
- /**
- * Create a PriorityClass for the given ProcessPriority. This implicitly
- * reads the relevant prefs and opens the cgroup.procs file of the relevant
- * control group caching its file descriptor for later use.
- */
- PriorityClass(ProcessPriority aPriority);
-
- /**
- * Closes the file descriptor for the cgroup.procs file of the associated
- * control group.
- */
- ~PriorityClass();
-
- PriorityClass(const PriorityClass& aOther);
- PriorityClass& operator=(const PriorityClass& aOther);
-
- ProcessPriority Priority()
- {
- return mPriority;
- }
-
- int32_t OomScoreAdj()
- {
- return clamped<int32_t>(mOomScoreAdj, OOM_SCORE_ADJ_MIN, OOM_SCORE_ADJ_MAX);
- }
-
- int32_t KillUnderKB()
- {
- return mKillUnderKB;
- }
-
- nsCString CGroup()
- {
- return mGroup;
- }
-
- /**
- * Adds a process to this priority class, this moves the process' PID into
- * the associated control group.
- *
- * @param aPid The PID of the process to be added.
- */
- void AddProcess(int aPid);
-
-private:
- ProcessPriority mPriority;
- int32_t mOomScoreAdj;
- int32_t mKillUnderKB;
- int mCpuCGroupProcsFd;
- int mMemCGroupProcsFd;
- nsCString mGroup;
-
- /**
- * Return a string that identifies where we can find the value of aPref
- * that's specific to mPriority. For example, we might return
- * "hal.processPriorityManager.gonk.FOREGROUND_HIGH.oomScoreAdjust".
- */
- nsCString PriorityPrefName(const char* aPref)
- {
- return nsPrintfCString("hal.processPriorityManager.gonk.%s.%s",
- ProcessPriorityToString(mPriority), aPref);
- }
-
- /**
- * Get the full path of the cgroup.procs file associated with the group.
- */
- nsCString CpuCGroupProcsFilename()
- {
- nsCString cgroupName = mGroup;
-
- /* If mGroup is empty, our cgroup.procs file is the root procs file,
- * located at /dev/cpuctl/cgroup.procs. Otherwise our procs file is
- * /dev/cpuctl/NAME/cgroup.procs. */
-
- if (!mGroup.IsEmpty()) {
- cgroupName.AppendLiteral("/");
- }
-
- return NS_LITERAL_CSTRING("/dev/cpuctl/") + cgroupName +
- NS_LITERAL_CSTRING("cgroup.procs");
- }
-
- nsCString MemCGroupProcsFilename()
- {
- nsCString cgroupName = mGroup;
-
- /* If mGroup is empty, our cgroup.procs file is the root procs file,
- * located at /sys/fs/cgroup/memory/cgroup.procs. Otherwise our procs
- * file is /sys/fs/cgroup/memory/NAME/cgroup.procs. */
-
- if (!mGroup.IsEmpty()) {
- cgroupName.AppendLiteral("/");
- }
-
- return NS_LITERAL_CSTRING("/sys/fs/cgroup/memory/") + cgroupName +
- NS_LITERAL_CSTRING("cgroup.procs");
- }
-
- int OpenCpuCGroupProcs()
- {
- return open(CpuCGroupProcsFilename().get(), O_WRONLY);
- }
-
- int OpenMemCGroupProcs()
- {
- return open(MemCGroupProcsFilename().get(), O_WRONLY);
- }
-};
-
-/**
- * Try to create the cgroup for the given PriorityClass, if it doesn't already
- * exist. This essentially implements mkdir -p; that is, we create parent
- * cgroups as necessary. The group parameters are also set according to
- * the corresponding preferences.
- *
- * @param aGroup The name of the group.
- * @return true if we successfully created the cgroup, or if it already
- * exists. Otherwise, return false.
- */
-static bool
-EnsureCpuCGroupExists(const nsACString &aGroup)
-{
- NS_NAMED_LITERAL_CSTRING(kDevCpuCtl, "/dev/cpuctl/");
- NS_NAMED_LITERAL_CSTRING(kSlash, "/");
-
- nsAutoCString groupName(aGroup);
- HAL_LOG("EnsureCpuCGroupExists for group '%s'", groupName.get());
-
- nsAutoCString prefPrefix("hal.processPriorityManager.gonk.cgroups.");
-
- /* If cgroup is not empty, append the cgroup name and a dot to obtain the
- * group specific preferences. */
- if (!aGroup.IsEmpty()) {
- prefPrefix += aGroup + NS_LITERAL_CSTRING(".");
- }
-
- nsAutoCString cpuSharesPref(prefPrefix + NS_LITERAL_CSTRING("cpu_shares"));
- int cpuShares = Preferences::GetInt(cpuSharesPref.get());
-
- nsAutoCString cpuNotifyOnMigratePref(prefPrefix
- + NS_LITERAL_CSTRING("cpu_notify_on_migrate"));
- int cpuNotifyOnMigrate = Preferences::GetInt(cpuNotifyOnMigratePref.get());
-
- // Create mCGroup and its parent directories, as necessary.
- nsCString cgroupIter = aGroup + kSlash;
-
- int32_t offset = 0;
- while ((offset = cgroupIter.FindChar('/', offset)) != -1) {
- nsAutoCString path = kDevCpuCtl + Substring(cgroupIter, 0, offset);
- int rv = mkdir(path.get(), 0744);
-
- if (rv == -1 && errno != EEXIST) {
- HAL_LOG("Could not create the %s control group.", path.get());
- return false;
- }
-
- offset++;
- }
- HAL_LOG("EnsureCpuCGroupExists created group '%s'", groupName.get());
-
- nsAutoCString pathPrefix(kDevCpuCtl + aGroup + kSlash);
- nsAutoCString cpuSharesPath(pathPrefix + NS_LITERAL_CSTRING("cpu.shares"));
- if (cpuShares && !WriteSysFile(cpuSharesPath.get(),
- nsPrintfCString("%d", cpuShares).get())) {
- HAL_LOG("Could not set the cpu share for group %s", cpuSharesPath.get());
- return false;
- }
-
- nsAutoCString notifyOnMigratePath(pathPrefix
- + NS_LITERAL_CSTRING("cpu.notify_on_migrate"));
- if (!WriteSysFile(notifyOnMigratePath.get(),
- nsPrintfCString("%d", cpuNotifyOnMigrate).get())) {
- HAL_LOG("Could not set the cpu migration notification flag for group %s",
- notifyOnMigratePath.get());
- return false;
- }
-
- return true;
-}
-
-static bool
-EnsureMemCGroupExists(const nsACString &aGroup)
-{
- NS_NAMED_LITERAL_CSTRING(kMemCtl, "/sys/fs/cgroup/memory/");
- NS_NAMED_LITERAL_CSTRING(kSlash, "/");
-
- nsAutoCString groupName(aGroup);
- HAL_LOG("EnsureMemCGroupExists for group '%s'", groupName.get());
-
- nsAutoCString prefPrefix("hal.processPriorityManager.gonk.cgroups.");
-
- /* If cgroup is not empty, append the cgroup name and a dot to obtain the
- * group specific preferences. */
- if (!aGroup.IsEmpty()) {
- prefPrefix += aGroup + NS_LITERAL_CSTRING(".");
- }
-
- nsAutoCString memSwappinessPref(prefPrefix + NS_LITERAL_CSTRING("memory_swappiness"));
- int memSwappiness = Preferences::GetInt(memSwappinessPref.get());
-
- // Create mCGroup and its parent directories, as necessary.
- nsCString cgroupIter = aGroup + kSlash;
-
- int32_t offset = 0;
- while ((offset = cgroupIter.FindChar('/', offset)) != -1) {
- nsAutoCString path = kMemCtl + Substring(cgroupIter, 0, offset);
- int rv = mkdir(path.get(), 0744);
-
- if (rv == -1 && errno != EEXIST) {
- HAL_LOG("Could not create the %s control group.", path.get());
- return false;
- }
-
- offset++;
- }
- HAL_LOG("EnsureMemCGroupExists created group '%s'", groupName.get());
-
- nsAutoCString pathPrefix(kMemCtl + aGroup + kSlash);
- nsAutoCString memSwappinessPath(pathPrefix + NS_LITERAL_CSTRING("memory.swappiness"));
- if (!WriteSysFile(memSwappinessPath.get(),
- nsPrintfCString("%d", memSwappiness).get())) {
- HAL_LOG("Could not set the memory.swappiness for group %s", memSwappinessPath.get());
- return false;
- }
- HAL_LOG("Set memory.swappiness for group %s to %d", memSwappinessPath.get(), memSwappiness);
-
- return true;
-}
-
-PriorityClass::PriorityClass(ProcessPriority aPriority)
- : mPriority(aPriority)
- , mOomScoreAdj(0)
- , mKillUnderKB(0)
- , mCpuCGroupProcsFd(-1)
- , mMemCGroupProcsFd(-1)
-{
- DebugOnly<nsresult> rv;
-
- rv = Preferences::GetInt(PriorityPrefName("OomScoreAdjust").get(),
- &mOomScoreAdj);
- MOZ_ASSERT(NS_SUCCEEDED(rv), "Missing oom_score_adj preference");
-
- rv = Preferences::GetInt(PriorityPrefName("KillUnderKB").get(),
- &mKillUnderKB);
-
- rv = Preferences::GetCString(PriorityPrefName("cgroup").get(), &mGroup);
- MOZ_ASSERT(NS_SUCCEEDED(rv), "Missing control group preference");
-
- if (EnsureCpuCGroupExists(mGroup)) {
- mCpuCGroupProcsFd = OpenCpuCGroupProcs();
- }
- if (EnsureMemCGroupExists(mGroup)) {
- mMemCGroupProcsFd = OpenMemCGroupProcs();
- }
-}
-
-PriorityClass::~PriorityClass()
-{
- if (mCpuCGroupProcsFd != -1) {
- close(mCpuCGroupProcsFd);
- }
- if (mMemCGroupProcsFd != -1) {
- close(mMemCGroupProcsFd);
- }
-}
-
-PriorityClass::PriorityClass(const PriorityClass& aOther)
- : mPriority(aOther.mPriority)
- , mOomScoreAdj(aOther.mOomScoreAdj)
- , mKillUnderKB(aOther.mKillUnderKB)
- , mGroup(aOther.mGroup)
-{
- mCpuCGroupProcsFd = OpenCpuCGroupProcs();
- mMemCGroupProcsFd = OpenMemCGroupProcs();
-}
-
-PriorityClass& PriorityClass::operator=(const PriorityClass& aOther)
-{
- mPriority = aOther.mPriority;
- mOomScoreAdj = aOther.mOomScoreAdj;
- mKillUnderKB = aOther.mKillUnderKB;
- mGroup = aOther.mGroup;
- mCpuCGroupProcsFd = OpenCpuCGroupProcs();
- mMemCGroupProcsFd = OpenMemCGroupProcs();
- return *this;
-}
-
-void PriorityClass::AddProcess(int aPid)
-{
- if (mCpuCGroupProcsFd >= 0) {
- nsPrintfCString str("%d", aPid);
-
- if (write(mCpuCGroupProcsFd, str.get(), strlen(str.get())) < 0) {
- HAL_ERR("Couldn't add PID %d to the %s cpu control group", aPid, mGroup.get());
- }
- }
- if (mMemCGroupProcsFd >= 0) {
- nsPrintfCString str("%d", aPid);
-
- if (write(mMemCGroupProcsFd, str.get(), strlen(str.get())) < 0) {
- HAL_ERR("Couldn't add PID %d to the %s memory control group", aPid, mGroup.get());
- }
- }
-}
-
-/**
- * Get the PriorityClass associated with the given ProcessPriority.
- *
- * If you pass an invalid ProcessPriority value, we return null.
- *
- * The pointers returned here are owned by GetPriorityClass (don't free them
- * yourself). They are guaranteed to stick around until shutdown.
- */
-PriorityClass*
-GetPriorityClass(ProcessPriority aPriority)
-{
- static StaticAutoPtr<nsTArray<PriorityClass>> priorityClasses;
-
- // Initialize priorityClasses if this is the first time we're running this
- // method.
- if (!priorityClasses) {
- priorityClasses = new nsTArray<PriorityClass>();
- ClearOnShutdown(&priorityClasses);
-
- for (int32_t i = 0; i < NUM_PROCESS_PRIORITY; i++) {
- priorityClasses->AppendElement(PriorityClass(ProcessPriority(i)));
- }
- }
-
- if (aPriority < 0 ||
- static_cast<uint32_t>(aPriority) >= priorityClasses->Length()) {
- return nullptr;
- }
-
- return &(*priorityClasses)[aPriority];
-}
-
-static void
-EnsureKernelLowMemKillerParamsSet()
-{
- static bool kernelLowMemKillerParamsSet;
- if (kernelLowMemKillerParamsSet) {
- return;
- }
- kernelLowMemKillerParamsSet = true;
-
- HAL_LOG("Setting kernel's low-mem killer parameters.");
-
- // Set /sys/module/lowmemorykiller/parameters/{adj,minfree,notify_trigger}
- // according to our prefs. These files let us tune when the kernel kills
- // processes when we're low on memory, and when it notifies us that we're
- // running low on available memory.
- //
- // adj and minfree are both comma-separated lists of integers. If adj="A,B"
- // and minfree="X,Y", then the kernel will kill processes with oom_adj
- // A or higher once we have fewer than X pages of memory free, and will kill
- // processes with oom_adj B or higher once we have fewer than Y pages of
- // memory free.
- //
- // notify_trigger is a single integer. If we set notify_trigger=Z, then
- // we'll get notified when there are fewer than Z pages of memory free. (See
- // GonkMemoryPressureMonitoring.cpp.)
-
- // Build the adj and minfree strings.
- nsAutoCString adjParams;
- nsAutoCString minfreeParams;
-
- DebugOnly<int32_t> lowerBoundOfNextOomScoreAdj = OOM_SCORE_ADJ_MIN - 1;
- DebugOnly<int32_t> lowerBoundOfNextKillUnderKB = 0;
- int32_t countOfLowmemorykillerParametersSets = 0;
-
- long page_size = sysconf(_SC_PAGESIZE);
-
- for (int i = NUM_PROCESS_PRIORITY - 1; i >= 0; i--) {
- // The system doesn't function correctly if we're missing these prefs, so
- // crash loudly.
-
- PriorityClass* pc = GetPriorityClass(static_cast<ProcessPriority>(i));
-
- int32_t oomScoreAdj = pc->OomScoreAdj();
- int32_t killUnderKB = pc->KillUnderKB();
-
- if (killUnderKB == 0) {
- // ProcessPriority values like PROCESS_PRIORITY_FOREGROUND_KEYBOARD,
- // which has only OomScoreAdjust but lacks KillUnderMB value, will not
- // create new LMK parameters.
- continue;
- }
-
- // The LMK in kernel silently malfunctions if we assign the parameters
- // in non-increasing order, so we add this assertion here. See bug 887192.
- MOZ_ASSERT(oomScoreAdj > lowerBoundOfNextOomScoreAdj);
- MOZ_ASSERT(killUnderKB > lowerBoundOfNextKillUnderKB);
-
- // The LMK in kernel only accept 6 sets of LMK parameters. See bug 914728.
- MOZ_ASSERT(countOfLowmemorykillerParametersSets < 6);
-
- // adj is in oom_adj units.
- adjParams.AppendPrintf("%d,", OomAdjOfOomScoreAdj(oomScoreAdj));
-
- // minfree is in pages.
- minfreeParams.AppendPrintf("%ld,", killUnderKB * 1024 / page_size);
-
- lowerBoundOfNextOomScoreAdj = oomScoreAdj;
- lowerBoundOfNextKillUnderKB = killUnderKB;
- countOfLowmemorykillerParametersSets++;
- }
-
- // Strip off trailing commas.
- adjParams.Cut(adjParams.Length() - 1, 1);
- minfreeParams.Cut(minfreeParams.Length() - 1, 1);
- if (!adjParams.IsEmpty() && !minfreeParams.IsEmpty()) {
- WriteSysFile("/sys/module/lowmemorykiller/parameters/adj", adjParams.get());
- WriteSysFile("/sys/module/lowmemorykiller/parameters/minfree",
- minfreeParams.get());
- }
-
- // Set the low-memory-notification threshold.
- int32_t lowMemNotifyThresholdKB;
- if (NS_SUCCEEDED(Preferences::GetInt(
- "hal.processPriorityManager.gonk.notifyLowMemUnderKB",
- &lowMemNotifyThresholdKB))) {
-
- // notify_trigger is in pages.
- WriteSysFile("/sys/module/lowmemorykiller/parameters/notify_trigger",
- nsPrintfCString("%ld", lowMemNotifyThresholdKB * 1024 / page_size).get());
- }
-
- // Ensure OOM events appear in logcat
- RefPtr<OomVictimLogger> oomLogger = new OomVictimLogger();
- nsCOMPtr<nsIObserverService> os = services::GetObserverService();
- if (os) {
- os->AddObserver(oomLogger, "ipc:content-shutdown", false);
- }
-}
-
-void
-SetProcessPriority(int aPid, ProcessPriority aPriority, uint32_t aLRU)
-{
- HAL_LOG("SetProcessPriority(pid=%d, priority=%d, LRU=%u)",
- aPid, aPriority, aLRU);
-
- // If this is the first time SetProcessPriority was called, set the kernel's
- // OOM parameters according to our prefs.
- //
- // We could/should do this on startup instead of waiting for the first
- // SetProcessPriorityCall. But in practice, the master process needs to set
- // its priority early in the game, so we can reasonably rely on
- // SetProcessPriority being called early in startup.
- EnsureKernelLowMemKillerParamsSet();
-
- PriorityClass* pc = GetPriorityClass(aPriority);
-
- int oomScoreAdj = pc->OomScoreAdj();
-
- RoundOomScoreAdjUpWithLRU(oomScoreAdj, aLRU);
-
- // We try the newer interface first, and fall back to the older interface
- // on failure.
- if (!WriteSysFile(nsPrintfCString("/proc/%d/oom_score_adj", aPid).get(),
- nsPrintfCString("%d", oomScoreAdj).get()))
- {
- WriteSysFile(nsPrintfCString("/proc/%d/oom_adj", aPid).get(),
- nsPrintfCString("%d", OomAdjOfOomScoreAdj(oomScoreAdj)).get());
- }
-
- HAL_LOG("Assigning pid %d to cgroup %s", aPid, pc->CGroup().get());
- pc->AddProcess(aPid);
-}
-
-static bool
-IsValidRealTimePriority(int aValue, int aSchedulePolicy)
-{
- return (aValue >= sched_get_priority_min(aSchedulePolicy)) &&
- (aValue <= sched_get_priority_max(aSchedulePolicy));
-}
-
-static void
-SetThreadNiceValue(pid_t aTid, ThreadPriority aThreadPriority, int aValue)
-{
- MOZ_ASSERT(aThreadPriority < NUM_THREAD_PRIORITY);
- MOZ_ASSERT(aThreadPriority >= 0);
-
- HAL_LOG("Setting thread %d to priority level %s; nice level %d",
- aTid, ThreadPriorityToString(aThreadPriority), aValue);
- int rv = setpriority(PRIO_PROCESS, aTid, aValue);
-
- if (rv) {
- HAL_LOG("Failed to set thread %d to priority level %s; error %s", aTid,
- ThreadPriorityToString(aThreadPriority), strerror(errno));
- }
-}
-
-static void
-SetRealTimeThreadPriority(pid_t aTid,
- ThreadPriority aThreadPriority,
- int aValue)
-{
- int policy = SCHED_FIFO;
-
- MOZ_ASSERT(aThreadPriority < NUM_THREAD_PRIORITY);
- MOZ_ASSERT(aThreadPriority >= 0);
- MOZ_ASSERT(IsValidRealTimePriority(aValue, policy), "Invalid real time priority");
-
- // Setting real time priorities requires using sched_setscheduler
- HAL_LOG("Setting thread %d to priority level %s; Real Time priority %d, "
- "Schedule FIFO", aTid, ThreadPriorityToString(aThreadPriority),
- aValue);
- sched_param schedParam;
- schedParam.sched_priority = aValue;
- int rv = sched_setscheduler(aTid, policy, &schedParam);
-
- if (rv) {
- HAL_LOG("Failed to set thread %d to real time priority level %s; error %s",
- aTid, ThreadPriorityToString(aThreadPriority), strerror(errno));
- }
-}
-
-/*
- * Used to store the nice value adjustments and real time priorities for the
- * various thread priority levels.
- */
-struct ThreadPriorityPrefs {
- bool initialized;
- struct {
- int nice;
- int realTime;
- } priorities[NUM_THREAD_PRIORITY];
-};
-
-/*
- * Reads the preferences for the various process priority levels and sets up
- * watchers so that if they're dynamically changed the change is reflected on
- * the appropriate variables.
- */
-void
-EnsureThreadPriorityPrefs(ThreadPriorityPrefs* prefs)
-{
- if (prefs->initialized) {
- return;
- }
-
- for (int i = THREAD_PRIORITY_COMPOSITOR; i < NUM_THREAD_PRIORITY; i++) {
- ThreadPriority priority = static_cast<ThreadPriority>(i);
-
- // Read the nice values
- const char* threadPriorityStr = ThreadPriorityToString(priority);
- nsPrintfCString niceStr("hal.gonk.%s.nice", threadPriorityStr);
- Preferences::AddIntVarCache(&prefs->priorities[i].nice, niceStr.get());
-
- // Read the real-time priorities
- nsPrintfCString realTimeStr("hal.gonk.%s.rt_priority", threadPriorityStr);
- Preferences::AddIntVarCache(&prefs->priorities[i].realTime,
- realTimeStr.get());
- }
-
- prefs->initialized = true;
-}
-
-static void
-DoSetThreadPriority(pid_t aTid, hal::ThreadPriority aThreadPriority)
-{
- // See bug 999115, we can only read preferences on the main thread otherwise
- // we create a race condition in HAL
- MOZ_ASSERT(NS_IsMainThread(), "Can only set thread priorities on main thread");
- MOZ_ASSERT(aThreadPriority >= 0);
-
- static ThreadPriorityPrefs prefs = { 0 };
- EnsureThreadPriorityPrefs(&prefs);
-
- switch (aThreadPriority) {
- case THREAD_PRIORITY_COMPOSITOR:
- break;
- default:
- HAL_ERR("Unrecognized thread priority %d; Doing nothing",
- aThreadPriority);
- return;
- }
-
- int realTimePriority = prefs.priorities[aThreadPriority].realTime;
-
- if (IsValidRealTimePriority(realTimePriority, SCHED_FIFO)) {
- SetRealTimeThreadPriority(aTid, aThreadPriority, realTimePriority);
- return;
- }
-
- SetThreadNiceValue(aTid, aThreadPriority,
- prefs.priorities[aThreadPriority].nice);
-}
-
-namespace {
-
-/**
- * This class sets the priority of threads given the kernel thread's id and a
- * value taken from hal::ThreadPriority.
- *
- * This runnable must always be dispatched to the main thread otherwise it will fail.
- * We have to run this from the main thread since preferences can only be read on
- * main thread.
- */
-class SetThreadPriorityRunnable : public Runnable
-{
-public:
- SetThreadPriorityRunnable(pid_t aThreadId, hal::ThreadPriority aThreadPriority)
- : mThreadId(aThreadId)
- , mThreadPriority(aThreadPriority)
- { }
-
- NS_IMETHOD Run() override
- {
- NS_ASSERTION(NS_IsMainThread(), "Can only set thread priorities on main thread");
- hal_impl::DoSetThreadPriority(mThreadId, mThreadPriority);
- return NS_OK;
- }
-
-private:
- pid_t mThreadId;
- hal::ThreadPriority mThreadPriority;
-};
-
-} // namespace
-
-void
-SetCurrentThreadPriority(ThreadPriority aThreadPriority)
-{
- pid_t threadId = gettid();
- hal_impl::SetThreadPriority(threadId, aThreadPriority);
-}
-
-void
-SetThreadPriority(PlatformThreadId aThreadId,
- ThreadPriority aThreadPriority)
-{
- switch (aThreadPriority) {
- case THREAD_PRIORITY_COMPOSITOR: {
- nsCOMPtr<nsIRunnable> runnable =
- new SetThreadPriorityRunnable(aThreadId, aThreadPriority);
- NS_DispatchToMainThread(runnable);
- break;
- }
- default:
- HAL_LOG("Unrecognized thread priority %d; Doing nothing",
- aThreadPriority);
- return;
- }
-}
-
-void
-FactoryReset(FactoryResetReason& aReason)
-{
- nsCOMPtr<nsIRecoveryService> recoveryService =
- do_GetService("@mozilla.org/recovery-service;1");
- if (!recoveryService) {
- NS_WARNING("Could not get recovery service!");
- return;
- }
-
- if (aReason == FactoryResetReason::Wipe) {
- recoveryService->FactoryReset("wipe");
- } else if (aReason == FactoryResetReason::Root) {
- recoveryService->FactoryReset("root");
- } else {
- recoveryService->FactoryReset("normal");
- }
-}
-
-} // hal_impl
-} // mozilla
diff --git a/hal/gonk/GonkSensor.cpp b/hal/gonk/GonkSensor.cpp
deleted file mode 100644
index 7bd2d3c9b..000000000
--- a/hal/gonk/GonkSensor.cpp
+++ /dev/null
@@ -1,861 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <pthread.h>
-#include <stdio.h>
-
-#include "mozilla/DebugOnly.h"
-#include "mozilla/Saturate.h"
-
-#include "base/basictypes.h"
-#include "base/thread.h"
-#include "base/task.h"
-
-#include "GonkSensorsInterface.h"
-#include "GonkSensorsPollInterface.h"
-#include "GonkSensorsRegistryInterface.h"
-#include "Hal.h"
-#include "HalLog.h"
-#include "HalSensor.h"
-#include "hardware/sensors.h"
-#include "nsThreadUtils.h"
-
-using namespace mozilla::hal;
-
-namespace mozilla {
-
-//
-// Internal implementation
-//
-
-// The value from SensorDevice.h (Android)
-#define DEFAULT_DEVICE_POLL_RATE 200000000 /*200ms*/
-// ProcessOrientation.cpp needs smaller poll rate to detect delay between
-// different orientation angles
-#define ACCELEROMETER_POLL_RATE 66667000 /*66.667ms*/
-
-// This is present in Android from API level 18 onwards, which is 4.3. We might
-// be building on something before 4.3, so use a local define for its value
-#define MOZ_SENSOR_TYPE_GAME_ROTATION_VECTOR 15
-
-double radToDeg(double a) {
- return a * (180.0 / M_PI);
-}
-
-static SensorType
-HardwareSensorToHalSensor(int type)
-{
- switch(type) {
- case SENSOR_TYPE_ORIENTATION:
- return SENSOR_ORIENTATION;
- case SENSOR_TYPE_ACCELEROMETER:
- return SENSOR_ACCELERATION;
- case SENSOR_TYPE_PROXIMITY:
- return SENSOR_PROXIMITY;
- case SENSOR_TYPE_LIGHT:
- return SENSOR_LIGHT;
- case SENSOR_TYPE_GYROSCOPE:
- return SENSOR_GYROSCOPE;
- case SENSOR_TYPE_LINEAR_ACCELERATION:
- return SENSOR_LINEAR_ACCELERATION;
- case SENSOR_TYPE_ROTATION_VECTOR:
- return SENSOR_ROTATION_VECTOR;
- case MOZ_SENSOR_TYPE_GAME_ROTATION_VECTOR:
- return SENSOR_GAME_ROTATION_VECTOR;
- default:
- return SENSOR_UNKNOWN;
- }
-}
-
-static SensorAccuracyType
-HardwareStatusToHalAccuracy(int status) {
- return static_cast<SensorAccuracyType>(status);
-}
-
-static int
-HalSensorToHardwareSensor(SensorType type)
-{
- switch(type) {
- case SENSOR_ORIENTATION:
- return SENSOR_TYPE_ORIENTATION;
- case SENSOR_ACCELERATION:
- return SENSOR_TYPE_ACCELEROMETER;
- case SENSOR_PROXIMITY:
- return SENSOR_TYPE_PROXIMITY;
- case SENSOR_LIGHT:
- return SENSOR_TYPE_LIGHT;
- case SENSOR_GYROSCOPE:
- return SENSOR_TYPE_GYROSCOPE;
- case SENSOR_LINEAR_ACCELERATION:
- return SENSOR_TYPE_LINEAR_ACCELERATION;
- case SENSOR_ROTATION_VECTOR:
- return SENSOR_TYPE_ROTATION_VECTOR;
- case SENSOR_GAME_ROTATION_VECTOR:
- return MOZ_SENSOR_TYPE_GAME_ROTATION_VECTOR;
- default:
- return -1;
- }
-}
-
-static int
-SensorseventStatus(const sensors_event_t& data)
-{
- int type = data.type;
- switch(type) {
- case SENSOR_ORIENTATION:
- return data.orientation.status;
- case SENSOR_LINEAR_ACCELERATION:
- case SENSOR_ACCELERATION:
- return data.acceleration.status;
- case SENSOR_GYROSCOPE:
- return data.gyro.status;
- }
-
- return SENSOR_STATUS_UNRELIABLE;
-}
-
-class SensorRunnable : public Runnable
-{
-public:
- SensorRunnable(const sensors_event_t& data, const sensor_t* sensors, ssize_t size)
- {
- mSensorData.sensor() = HardwareSensorToHalSensor(data.type);
- mSensorData.accuracy() = HardwareStatusToHalAccuracy(SensorseventStatus(data));
- mSensorData.timestamp() = data.timestamp;
- if (mSensorData.sensor() == SENSOR_GYROSCOPE) {
- // libhardware returns gyro as rad. convert.
- mSensorValues.AppendElement(radToDeg(data.data[0]));
- mSensorValues.AppendElement(radToDeg(data.data[1]));
- mSensorValues.AppendElement(radToDeg(data.data[2]));
- } else if (mSensorData.sensor() == SENSOR_PROXIMITY) {
- mSensorValues.AppendElement(data.data[0]);
- mSensorValues.AppendElement(0);
-
- // Determine the maxRange for this sensor.
- for (ssize_t i = 0; i < size; i++) {
- if (sensors[i].type == SENSOR_TYPE_PROXIMITY) {
- mSensorValues.AppendElement(sensors[i].maxRange);
- }
- }
- } else if (mSensorData.sensor() == SENSOR_LIGHT) {
- mSensorValues.AppendElement(data.data[0]);
- } else if (mSensorData.sensor() == SENSOR_ROTATION_VECTOR) {
- mSensorValues.AppendElement(data.data[0]);
- mSensorValues.AppendElement(data.data[1]);
- mSensorValues.AppendElement(data.data[2]);
- if (data.data[3] == 0.0) {
- // data.data[3] was optional in Android <= API level 18. It can be computed from 012,
- // but it's better to take the actual value if one is provided. The computation is
- // v = 1 - d[0]*d[0] - d[1]*d[1] - d[2]*d[2]
- // d[3] = v > 0 ? sqrt(v) : 0;
- // I'm assuming that it will be 0 if it's not passed in. (The values form a unit
- // quaternion, so the angle can be computed from the direction vector.)
- float sx = data.data[0], sy = data.data[1], sz = data.data[2];
- float v = 1.0f - sx*sx - sy*sy - sz*sz;
- mSensorValues.AppendElement(v > 0.0f ? sqrt(v) : 0.0f);
- } else {
- mSensorValues.AppendElement(data.data[3]);
- }
- } else if (mSensorData.sensor() == SENSOR_GAME_ROTATION_VECTOR) {
- mSensorValues.AppendElement(data.data[0]);
- mSensorValues.AppendElement(data.data[1]);
- mSensorValues.AppendElement(data.data[2]);
- mSensorValues.AppendElement(data.data[3]);
- } else {
- mSensorValues.AppendElement(data.data[0]);
- mSensorValues.AppendElement(data.data[1]);
- mSensorValues.AppendElement(data.data[2]);
- }
- mSensorData.values() = mSensorValues;
- }
-
- ~SensorRunnable() {}
-
- NS_IMETHOD Run() override
- {
- NotifySensorChange(mSensorData);
- return NS_OK;
- }
-
-private:
- SensorData mSensorData;
- AutoTArray<float, 4> mSensorValues;
-};
-
-namespace hal_impl {
-
-static DebugOnly<int> sSensorRefCount[NUM_SENSOR_TYPE];
-static base::Thread* sPollingThread;
-static sensors_poll_device_t* sSensorDevice;
-static sensors_module_t* sSensorModule;
-
-static void
-PollSensors()
-{
- const size_t numEventMax = 16;
- sensors_event_t buffer[numEventMax];
- const sensor_t* sensors;
- int size = sSensorModule->get_sensors_list(sSensorModule, &sensors);
-
- do {
- // didn't check sSensorDevice because already be done on creating pollingThread.
- int n = sSensorDevice->poll(sSensorDevice, buffer, numEventMax);
- if (n < 0) {
- HAL_ERR("Error polling for sensor data (err=%d)", n);
- break;
- }
-
- for (int i = 0; i < n; ++i) {
- // FIXME: bug 802004, add proper support for the magnetic field sensor.
- if (buffer[i].type == SENSOR_TYPE_MAGNETIC_FIELD)
- continue;
-
- // Bug 938035, transfer HAL data for orientation sensor to meet w3c spec
- // ex: HAL report alpha=90 means East but alpha=90 means West in w3c spec
- if (buffer[i].type == SENSOR_TYPE_ORIENTATION) {
- buffer[i].orientation.azimuth = 360 - buffer[i].orientation.azimuth;
- buffer[i].orientation.pitch = -buffer[i].orientation.pitch;
- buffer[i].orientation.roll = -buffer[i].orientation.roll;
- }
-
- if (HardwareSensorToHalSensor(buffer[i].type) == SENSOR_UNKNOWN) {
- // Emulator is broken and gives us events without types set
- int index;
- for (index = 0; index < size; index++) {
- if (sensors[index].handle == buffer[i].sensor) {
- break;
- }
- }
- if (index < size &&
- HardwareSensorToHalSensor(sensors[index].type) != SENSOR_UNKNOWN) {
- buffer[i].type = sensors[index].type;
- } else {
- HAL_LOG("Could not determine sensor type of event");
- continue;
- }
- }
-
- NS_DispatchToMainThread(new SensorRunnable(buffer[i], sensors, size));
- }
- } while (true);
-}
-
-static void
-SwitchSensor(bool aActivate, sensor_t aSensor, pthread_t aThreadId)
-{
- int index = HardwareSensorToHalSensor(aSensor.type);
-
- MOZ_ASSERT(sSensorRefCount[index] || aActivate);
-
- sSensorDevice->activate(sSensorDevice, aSensor.handle, aActivate);
-
- if (aActivate) {
- if (aSensor.type == SENSOR_TYPE_ACCELEROMETER) {
- sSensorDevice->setDelay(sSensorDevice, aSensor.handle,
- ACCELEROMETER_POLL_RATE);
- } else {
- sSensorDevice->setDelay(sSensorDevice, aSensor.handle,
- DEFAULT_DEVICE_POLL_RATE);
- }
- }
-
- if (aActivate) {
- sSensorRefCount[index]++;
- } else {
- sSensorRefCount[index]--;
- }
-}
-
-static void
-SetSensorState(SensorType aSensor, bool activate)
-{
- int type = HalSensorToHardwareSensor(aSensor);
- const sensor_t* sensors = nullptr;
-
- int size = sSensorModule->get_sensors_list(sSensorModule, &sensors);
- for (ssize_t i = 0; i < size; i++) {
- if (sensors[i].type == type) {
- SwitchSensor(activate, sensors[i], pthread_self());
- break;
- }
- }
-}
-
-static void
-EnableSensorNotificationsInternal(SensorType aSensor)
-{
- if (!sSensorModule) {
- hw_get_module(SENSORS_HARDWARE_MODULE_ID,
- (hw_module_t const**)&sSensorModule);
- if (!sSensorModule) {
- HAL_ERR("Can't get sensor HAL module\n");
- return;
- }
-
- sensors_open(&sSensorModule->common, &sSensorDevice);
- if (!sSensorDevice) {
- sSensorModule = nullptr;
- HAL_ERR("Can't get sensor poll device from module \n");
- return;
- }
-
- sensor_t const* sensors;
- int count = sSensorModule->get_sensors_list(sSensorModule, &sensors);
- for (size_t i=0 ; i<size_t(count) ; i++) {
- sSensorDevice->activate(sSensorDevice, sensors[i].handle, 0);
- }
- }
-
- if (!sPollingThread) {
- sPollingThread = new base::Thread("GonkSensors");
- MOZ_ASSERT(sPollingThread);
- // sPollingThread never terminates because poll may never return
- sPollingThread->Start();
- sPollingThread->message_loop()->PostTask(
- NewRunnableFunction(PollSensors));
- }
-
- SetSensorState(aSensor, true);
-}
-
-static void
-DisableSensorNotificationsInternal(SensorType aSensor)
-{
- if (!sSensorModule) {
- return;
- }
- SetSensorState(aSensor, false);
-}
-
-//
-// Daemon
-//
-
-typedef detail::SaturateOp<uint32_t> SaturateOpUint32;
-
-/**
- * The poll notification handler receives all events about sensors and
- * sensor events.
- */
-class SensorsPollNotificationHandler final
- : public GonkSensorsPollNotificationHandler
-{
-public:
- SensorsPollNotificationHandler(GonkSensorsPollInterface* aPollInterface)
- : mPollInterface(aPollInterface)
- {
- MOZ_ASSERT(mPollInterface);
-
- mPollInterface->SetNotificationHandler(this);
- }
-
- void EnableSensorsByType(SensorsType aType)
- {
- if (SaturateOpUint32(mClasses[aType].mActivated)++) {
- return;
- }
-
- SensorsDeliveryMode deliveryMode = DefaultSensorsDeliveryMode(aType);
-
- // Old ref-count for the sensor type was 0, so we
- // activate all sensors of the type.
- for (size_t i = 0; i < mSensors.Length(); ++i) {
- if (mSensors[i].mType == aType &&
- mSensors[i].mDeliveryMode == deliveryMode) {
- mPollInterface->EnableSensor(mSensors[i].mId, nullptr);
- mPollInterface->SetPeriod(mSensors[i].mId, DefaultSensorPeriod(aType),
- nullptr);
- }
- }
- }
-
- void DisableSensorsByType(SensorsType aType)
- {
- if (SaturateOpUint32(mClasses[aType].mActivated)-- != 1) {
- return;
- }
-
- SensorsDeliveryMode deliveryMode = DefaultSensorsDeliveryMode(aType);
-
- // Old ref-count for the sensor type was 1, so we
- // deactivate all sensors of the type.
- for (size_t i = 0; i < mSensors.Length(); ++i) {
- if (mSensors[i].mType == aType &&
- mSensors[i].mDeliveryMode == deliveryMode) {
- mPollInterface->DisableSensor(mSensors[i].mId, nullptr);
- }
- }
- }
-
- void ClearSensorClasses()
- {
- for (size_t i = 0; i < MOZ_ARRAY_LENGTH(mClasses); ++i) {
- mClasses[i] = SensorsSensorClass();
- }
- }
-
- void ClearSensors()
- {
- mSensors.Clear();
- }
-
- // Methods for SensorsPollNotificationHandler
- //
-
- void ErrorNotification(SensorsError aError) override
- {
- // XXX: Bug 1206056: Try to repair some of the errors or restart cleanly.
- }
-
- void SensorDetectedNotification(int32_t aId, SensorsType aType,
- float aRange, float aResolution,
- float aPower, int32_t aMinPeriod,
- int32_t aMaxPeriod,
- SensorsTriggerMode aTriggerMode,
- SensorsDeliveryMode aDeliveryMode) override
- {
- auto i = FindSensorIndexById(aId);
- if (i == -1) {
- // Add a new sensor...
- i = mSensors.Length();
- mSensors.AppendElement(SensorsSensor(aId, aType, aRange, aResolution,
- aPower, aMinPeriod, aMaxPeriod,
- aTriggerMode, aDeliveryMode));
- } else {
- // ...or update an existing one.
- mSensors[i] = SensorsSensor(aId, aType, aRange, aResolution, aPower,
- aMinPeriod, aMaxPeriod, aTriggerMode,
- aDeliveryMode);
- }
-
- mClasses[aType].UpdateFromSensor(mSensors[i]);
-
- if (mClasses[aType].mActivated &&
- mSensors[i].mDeliveryMode == DefaultSensorsDeliveryMode(aType)) {
- // The new sensor's type is enabled, so enable sensor.
- mPollInterface->EnableSensor(aId, nullptr);
- mPollInterface->SetPeriod(mSensors[i].mId, DefaultSensorPeriod(aType),
- nullptr);
- }
- }
-
- void SensorLostNotification(int32_t aId) override
- {
- auto i = FindSensorIndexById(aId);
- if (i != -1) {
- mSensors.RemoveElementAt(i);
- }
- }
-
- void EventNotification(int32_t aId, const SensorsEvent& aEvent) override
- {
- auto i = FindSensorIndexById(aId);
- if (i == -1) {
- HAL_ERR("Sensor %d not registered", aId);
- return;
- }
-
- SensorData sensorData;
- auto rv = CreateSensorData(aEvent, mClasses[mSensors[i].mType],
- sensorData);
- if (NS_FAILED(rv)) {
- return;
- }
-
- NotifySensorChange(sensorData);
- }
-
-private:
- ssize_t FindSensorIndexById(int32_t aId) const
- {
- for (size_t i = 0; i < mSensors.Length(); ++i) {
- if (mSensors[i].mId == aId) {
- return i;
- }
- }
- return -1;
- }
-
- uint64_t DefaultSensorPeriod(SensorsType aType) const
- {
- return aType == SENSORS_TYPE_ACCELEROMETER ? ACCELEROMETER_POLL_RATE
- : DEFAULT_DEVICE_POLL_RATE;
- }
-
- SensorsDeliveryMode DefaultSensorsDeliveryMode(SensorsType aType) const
- {
- if (aType == SENSORS_TYPE_PROXIMITY ||
- aType == SENSORS_TYPE_SIGNIFICANT_MOTION) {
- return SENSORS_DELIVERY_MODE_IMMEDIATE;
- }
- return SENSORS_DELIVERY_MODE_BEST_EFFORT;
- }
-
- SensorType HardwareSensorToHalSensor(SensorsType aType) const
- {
- // FIXME: bug 802004, add proper support for the magnetic-field sensor.
- switch (aType) {
- case SENSORS_TYPE_ORIENTATION:
- return SENSOR_ORIENTATION;
- case SENSORS_TYPE_ACCELEROMETER:
- return SENSOR_ACCELERATION;
- case SENSORS_TYPE_PROXIMITY:
- return SENSOR_PROXIMITY;
- case SENSORS_TYPE_LIGHT:
- return SENSOR_LIGHT;
- case SENSORS_TYPE_GYROSCOPE:
- return SENSOR_GYROSCOPE;
- case SENSORS_TYPE_LINEAR_ACCELERATION:
- return SENSOR_LINEAR_ACCELERATION;
- case SENSORS_TYPE_ROTATION_VECTOR:
- return SENSOR_ROTATION_VECTOR;
- case SENSORS_TYPE_GAME_ROTATION_VECTOR:
- return SENSOR_GAME_ROTATION_VECTOR;
- default:
- NS_NOTREACHED("Invalid sensors type");
- }
- return SENSOR_UNKNOWN;
- }
-
- SensorAccuracyType HardwareStatusToHalAccuracy(SensorsStatus aStatus) const
- {
- return static_cast<SensorAccuracyType>(aStatus - 1);
- }
-
- nsresult CreateSensorData(const SensorsEvent& aEvent,
- const SensorsSensorClass& aSensorClass,
- SensorData& aSensorData) const
- {
- AutoTArray<float, 4> sensorValues;
-
- auto sensor = HardwareSensorToHalSensor(aEvent.mType);
-
- if (sensor == SENSOR_UNKNOWN) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
-
- aSensorData.sensor() = sensor;
- aSensorData.accuracy() = HardwareStatusToHalAccuracy(aEvent.mStatus);
- aSensorData.timestamp() = aEvent.mTimestamp;
-
- if (aSensorData.sensor() == SENSOR_ORIENTATION) {
- // Bug 938035: transfer HAL data for orientation sensor to meet W3C spec
- // ex: HAL report alpha=90 means East but alpha=90 means West in W3C spec
- sensorValues.AppendElement(360.0 - radToDeg(aEvent.mData.mFloat[0]));
- sensorValues.AppendElement(-radToDeg(aEvent.mData.mFloat[1]));
- sensorValues.AppendElement(-radToDeg(aEvent.mData.mFloat[2]));
- } else if (aSensorData.sensor() == SENSOR_ACCELERATION) {
- sensorValues.AppendElement(aEvent.mData.mFloat[0]);
- sensorValues.AppendElement(aEvent.mData.mFloat[1]);
- sensorValues.AppendElement(aEvent.mData.mFloat[2]);
- } else if (aSensorData.sensor() == SENSOR_PROXIMITY) {
- sensorValues.AppendElement(aEvent.mData.mFloat[0]);
- sensorValues.AppendElement(aSensorClass.mMinValue);
- sensorValues.AppendElement(aSensorClass.mMaxValue);
- } else if (aSensorData.sensor() == SENSOR_LINEAR_ACCELERATION) {
- sensorValues.AppendElement(aEvent.mData.mFloat[0]);
- sensorValues.AppendElement(aEvent.mData.mFloat[1]);
- sensorValues.AppendElement(aEvent.mData.mFloat[2]);
- } else if (aSensorData.sensor() == SENSOR_GYROSCOPE) {
- sensorValues.AppendElement(radToDeg(aEvent.mData.mFloat[0]));
- sensorValues.AppendElement(radToDeg(aEvent.mData.mFloat[1]));
- sensorValues.AppendElement(radToDeg(aEvent.mData.mFloat[2]));
- } else if (aSensorData.sensor() == SENSOR_LIGHT) {
- sensorValues.AppendElement(aEvent.mData.mFloat[0]);
- } else if (aSensorData.sensor() == SENSOR_ROTATION_VECTOR) {
- sensorValues.AppendElement(aEvent.mData.mFloat[0]);
- sensorValues.AppendElement(aEvent.mData.mFloat[1]);
- sensorValues.AppendElement(aEvent.mData.mFloat[2]);
- sensorValues.AppendElement(aEvent.mData.mFloat[3]);
- } else if (aSensorData.sensor() == SENSOR_GAME_ROTATION_VECTOR) {
- sensorValues.AppendElement(aEvent.mData.mFloat[0]);
- sensorValues.AppendElement(aEvent.mData.mFloat[1]);
- sensorValues.AppendElement(aEvent.mData.mFloat[2]);
- sensorValues.AppendElement(aEvent.mData.mFloat[3]);
- }
-
- aSensorData.values() = sensorValues;
-
- return NS_OK;
- }
-
- GonkSensorsPollInterface* mPollInterface;
- nsTArray<SensorsSensor> mSensors;
- SensorsSensorClass mClasses[SENSORS_NUM_TYPES];
-};
-
-static StaticAutoPtr<SensorsPollNotificationHandler> sPollNotificationHandler;
-
-/**
- * This is the notifiaction handler for the Sensors interface. If the backend
- * crashes, we can restart it from here.
- */
-class SensorsNotificationHandler final : public GonkSensorsNotificationHandler
-{
-public:
- SensorsNotificationHandler(GonkSensorsInterface* aInterface)
- : mInterface(aInterface)
- {
- MOZ_ASSERT(mInterface);
-
- mInterface->SetNotificationHandler(this);
- }
-
- void BackendErrorNotification(bool aCrashed) override
- {
- // XXX: Bug 1206056: restart sensorsd
- }
-
-private:
- GonkSensorsInterface* mInterface;
-};
-
-static StaticAutoPtr<SensorsNotificationHandler> sNotificationHandler;
-
-/**
- * |SensorsRegisterModuleResultHandler| implements the result-handler
- * callback for registering the Poll service and activating the first
- * sensors. If an error occures during the process, the result handler
- * disconnects and closes the backend.
- */
-class SensorsRegisterModuleResultHandler final
- : public GonkSensorsRegistryResultHandler
-{
-public:
- SensorsRegisterModuleResultHandler(
- uint32_t* aSensorsTypeActivated,
- GonkSensorsInterface* aInterface)
- : mSensorsTypeActivated(aSensorsTypeActivated)
- , mInterface(aInterface)
- {
- MOZ_ASSERT(mSensorsTypeActivated);
- MOZ_ASSERT(mInterface);
- }
- void OnError(SensorsError aError) override
- {
- GonkSensorsRegistryResultHandler::OnError(aError); // print error message
- Disconnect(); // Registering failed, so close the connection completely
- }
- void RegisterModule(uint32_t aProtocolVersion) override
- {
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!sPollNotificationHandler);
-
- // Init, step 3: set notification handler for poll service and vice versa
- auto pollInterface = mInterface->GetSensorsPollInterface();
- if (!pollInterface) {
- Disconnect();
- return;
- }
- if (NS_FAILED(pollInterface->SetProtocolVersion(aProtocolVersion))) {
- Disconnect();
- return;
- }
-
- sPollNotificationHandler =
- new SensorsPollNotificationHandler(pollInterface);
-
- // Init, step 4: activate sensors
- for (int i = 0; i < SENSORS_NUM_TYPES; ++i) {
- while (mSensorsTypeActivated[i]) {
- sPollNotificationHandler->EnableSensorsByType(
- static_cast<SensorsType>(i));
- --mSensorsTypeActivated[i];
- }
- }
- }
-public:
- void Disconnect()
- {
- class DisconnectResultHandler final : public GonkSensorsResultHandler
- {
- public:
- void OnError(SensorsError aError)
- {
- GonkSensorsResultHandler::OnError(aError); // print error message
- sNotificationHandler = nullptr;
- }
- void Disconnect() override
- {
- sNotificationHandler = nullptr;
- }
- };
- mInterface->Disconnect(new DisconnectResultHandler());
- }
-private:
- uint32_t* mSensorsTypeActivated;
- GonkSensorsInterface* mInterface;
-};
-
-/**
- * |SensorsConnectResultHandler| implements the result-handler
- * callback for starting the Sensors backend.
- */
-class SensorsConnectResultHandler final : public GonkSensorsResultHandler
-{
-public:
- SensorsConnectResultHandler(
- uint32_t* aSensorsTypeActivated,
- GonkSensorsInterface* aInterface)
- : mSensorsTypeActivated(aSensorsTypeActivated)
- , mInterface(aInterface)
- {
- MOZ_ASSERT(mSensorsTypeActivated);
- MOZ_ASSERT(mInterface);
- }
- void OnError(SensorsError aError) override
- {
- GonkSensorsResultHandler::OnError(aError); // print error message
- sNotificationHandler = nullptr;
- }
- void Connect() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- // Init, step 2: register poll service
- auto registryInterface = mInterface->GetSensorsRegistryInterface();
- if (!registryInterface) {
- return;
- }
- registryInterface->RegisterModule(
- GonkSensorsPollModule::SERVICE_ID,
- new SensorsRegisterModuleResultHandler(mSensorsTypeActivated,
- mInterface));
- }
-private:
- uint32_t* mSensorsTypeActivated;
- GonkSensorsInterface* mInterface;
-};
-
-static uint32_t sSensorsTypeActivated[SENSORS_NUM_TYPES];
-
-static const SensorsType sSensorsType[] = {
- [SENSOR_ORIENTATION] = SENSORS_TYPE_ORIENTATION,
- [SENSOR_ACCELERATION] = SENSORS_TYPE_ACCELEROMETER,
- [SENSOR_PROXIMITY] = SENSORS_TYPE_PROXIMITY,
- [SENSOR_LINEAR_ACCELERATION] = SENSORS_TYPE_LINEAR_ACCELERATION,
- [SENSOR_GYROSCOPE] = SENSORS_TYPE_GYROSCOPE,
- [SENSOR_LIGHT] = SENSORS_TYPE_LIGHT,
- [SENSOR_ROTATION_VECTOR] = SENSORS_TYPE_ROTATION_VECTOR,
- [SENSOR_GAME_ROTATION_VECTOR] = SENSORS_TYPE_GAME_ROTATION_VECTOR
-};
-
-void
-EnableSensorNotificationsDaemon(SensorType aSensor)
-{
- if ((aSensor < 0) ||
- (aSensor > static_cast<ssize_t>(MOZ_ARRAY_LENGTH(sSensorsType)))) {
- HAL_ERR("Sensor type %d not known", aSensor);
- return; // Unsupported sensor type
- }
-
- auto interface = GonkSensorsInterface::GetInstance();
- if (!interface) {
- return;
- }
-
- if (sPollNotificationHandler) {
- // Everythings already up and running; enable sensor type.
- sPollNotificationHandler->EnableSensorsByType(sSensorsType[aSensor]);
- return;
- }
-
- ++SaturateOpUint32(sSensorsTypeActivated[sSensorsType[aSensor]]);
-
- if (sNotificationHandler) {
- // We are in the middle of a pending start up; nothing else to do.
- return;
- }
-
- // Start up
-
- MOZ_ASSERT(!sPollNotificationHandler);
- MOZ_ASSERT(!sNotificationHandler);
-
- sNotificationHandler = new SensorsNotificationHandler(interface);
-
- // Init, step 1: connect to Sensors backend
- interface->Connect(
- sNotificationHandler,
- new SensorsConnectResultHandler(sSensorsTypeActivated, interface));
-}
-
-void
-DisableSensorNotificationsDaemon(SensorType aSensor)
-{
- if ((aSensor < 0) ||
- (aSensor > static_cast<ssize_t>(MOZ_ARRAY_LENGTH(sSensorsType)))) {
- HAL_ERR("Sensor type %d not known", aSensor);
- return; // Unsupported sensor type
- }
-
- if (sPollNotificationHandler) {
- // Everthings up and running; disable sensors type
- sPollNotificationHandler->DisableSensorsByType(sSensorsType[aSensor]);
- return;
- }
-
- // We might be in the middle of a startup; decrement type's ref-counter.
- --SaturateOpUint32(sSensorsTypeActivated[sSensorsType[aSensor]]);
-
- // TODO: stop sensorsd if all sensors are disabled
-}
-
-//
-// Public interface
-//
-
-// TODO: Remove in-Gecko sensors code. Until all devices' base
-// images come with sensorsd installed, we have to support the
-// in-Gecko implementation as well. So we test for the existance
-// of the binary. If it's there, we use it. Otherwise we run the
-// old code.
-static bool
-HasDaemon()
-{
- static bool tested;
- static bool hasDaemon;
-
- if (MOZ_UNLIKELY(!tested)) {
- hasDaemon = !access("/system/bin/sensorsd", X_OK);
- tested = true;
- }
-
- return hasDaemon;
-}
-
-void
-EnableSensorNotifications(SensorType aSensor)
-{
- if (HasDaemon()) {
- EnableSensorNotificationsDaemon(aSensor);
- } else {
- EnableSensorNotificationsInternal(aSensor);
- }
-}
-
-void
-DisableSensorNotifications(SensorType aSensor)
-{
- if (HasDaemon()) {
- DisableSensorNotificationsDaemon(aSensor);
- } else {
- DisableSensorNotificationsInternal(aSensor);
- }
-}
-
-} // hal_impl
-} // mozilla
diff --git a/hal/gonk/GonkSensorsHelpers.cpp b/hal/gonk/GonkSensorsHelpers.cpp
deleted file mode 100644
index ccc940c7c..000000000
--- a/hal/gonk/GonkSensorsHelpers.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/* -*- 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 "GonkSensorsHelpers.h"
-
-namespace mozilla {
-namespace hal {
-
-//
-// Unpacking
-//
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, SensorsEvent& aOut)
-{
- nsresult rv = UnpackPDU(aPDU, aOut.mType);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(aPDU, aOut.mTimestamp);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(aPDU, aOut.mStatus);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- size_t i = 0;
-
- switch (aOut.mType) {
- case SENSORS_TYPE_MAGNETIC_FIELD_UNCALIBRATED:
- case SENSORS_TYPE_GYROSCOPE_UNCALIBRATED:
- /* 6 data values */
- rv = UnpackPDU(aPDU, aOut.mData.mFloat[i++]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- /* fall through */
- case SENSORS_TYPE_ROTATION_VECTOR:
- case SENSORS_TYPE_GAME_ROTATION_VECTOR:
- case SENSORS_TYPE_GEOMAGNETIC_ROTATION_VECTOR:
- /* 5 data values */
- rv = UnpackPDU(aPDU, aOut.mData.mFloat[i++]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(aPDU, aOut.mData.mFloat[i++]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- /* fall through */
- case SENSORS_TYPE_ACCELEROMETER:
- case SENSORS_TYPE_GEOMAGNETIC_FIELD:
- case SENSORS_TYPE_ORIENTATION:
- case SENSORS_TYPE_GYROSCOPE:
- case SENSORS_TYPE_GRAVITY:
- case SENSORS_TYPE_LINEAR_ACCELERATION:
- /* 3 data values */
- rv = UnpackPDU(aPDU, aOut.mData.mFloat[i++]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(aPDU, aOut.mData.mFloat[i++]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- /* fall through */
- case SENSORS_TYPE_LIGHT:
- case SENSORS_TYPE_PRESSURE:
- case SENSORS_TYPE_TEMPERATURE:
- case SENSORS_TYPE_PROXIMITY:
- case SENSORS_TYPE_RELATIVE_HUMIDITY:
- case SENSORS_TYPE_AMBIENT_TEMPERATURE:
- case SENSORS_TYPE_HEART_RATE:
- case SENSORS_TYPE_TILT_DETECTOR:
- case SENSORS_TYPE_WAKE_GESTURE:
- case SENSORS_TYPE_GLANCE_GESTURE:
- case SENSORS_TYPE_PICK_UP_GESTURE:
- case SENSORS_TYPE_WRIST_TILT_GESTURE:
- case SENSORS_TYPE_SIGNIFICANT_MOTION:
- case SENSORS_TYPE_STEP_DETECTED:
- /* 1 data value */
- rv = UnpackPDU(aPDU, aOut.mData.mFloat[i++]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- break;
- case SENSORS_TYPE_STEP_COUNTER:
- /* 1 data value */
- rv = UnpackPDU(aPDU, aOut.mData.mUint[0]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- break;
- default:
- if (MOZ_HAL_IPC_UNPACK_WARN_IF(true, SensorsEvent)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
- }
- rv = UnpackPDU(aPDU, aOut.mDeliveryMode);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
-}
-
-} // namespace hal
-} // namespace mozilla
diff --git a/hal/gonk/GonkSensorsHelpers.h b/hal/gonk/GonkSensorsHelpers.h
deleted file mode 100644
index 5218af53a..000000000
--- a/hal/gonk/GonkSensorsHelpers.h
+++ /dev/null
@@ -1,226 +0,0 @@
-/* -*- 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 hal_gonk_GonkSensorsHelpers_h
-#define hal_gonk_GonkSensorsHelpers_h
-
-#include <mozilla/ipc/DaemonSocketPDU.h>
-#include <mozilla/ipc/DaemonSocketPDUHelpers.h>
-#include "SensorsTypes.h"
-
-namespace mozilla {
-namespace hal {
-
-using mozilla::ipc::DaemonSocketPDU;
-using mozilla::ipc::DaemonSocketPDUHeader;
-using mozilla::ipc::DaemonSocketPDUHelpers::Convert;
-using mozilla::ipc::DaemonSocketPDUHelpers::PackPDU;
-using mozilla::ipc::DaemonSocketPDUHelpers::UnpackPDU;
-
-using namespace mozilla::ipc::DaemonSocketPDUHelpers;
-
-//
-// Conversion
-//
-// The functions below convert the input value to the output value's
-// type and perform extension tests on the validity of the result. On
-// success the output value will be returned in |aOut|. The functions
-// return NS_OK on success, or an XPCOM error code otherwise.
-//
-// See the documentation of the HAL IPC framework for more information
-// on conversion functions.
-//
-
-nsresult
-Convert(int32_t aIn, SensorsStatus& aOut)
-{
- static const uint8_t sStatus[] = {
- [0] = SENSORS_STATUS_NO_CONTACT, // '-1'
- [1] = SENSORS_STATUS_UNRELIABLE, // '0'
- [2] = SENSORS_STATUS_ACCURACY_LOW, // '1'
- [3] = SENSORS_STATUS_ACCURACY_MEDIUM, // '2'
- [4] = SENSORS_STATUS_ACCURACY_HIGH // '3'
- };
- static const int8_t sOffset = -1; // '-1' is the lower bound of the status
-
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(aIn < sOffset, int32_t, SensorsStatus) ||
- MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn >= (static_cast<ssize_t>(MOZ_ARRAY_LENGTH(sStatus)) + sOffset),
- int32_t, SensorsStatus)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<SensorsStatus>(sStatus[aIn - sOffset]);
- return NS_OK;
-}
-
-nsresult
-Convert(uint8_t aIn, SensorsDeliveryMode& aOut)
-{
- static const uint8_t sMode[] = {
- [0x00] = SENSORS_DELIVERY_MODE_BEST_EFFORT,
- [0x01] = SENSORS_DELIVERY_MODE_IMMEDIATE
- };
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn >= MOZ_ARRAY_LENGTH(sMode), uint8_t, SensorsDeliveryMode)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<SensorsDeliveryMode>(sMode[aIn]);
- return NS_OK;
-}
-
-nsresult
-Convert(uint8_t aIn, SensorsError& aOut)
-{
- static const uint8_t sError[] = {
- [0x00] = SENSORS_ERROR_NONE,
- [0x01] = SENSORS_ERROR_FAIL,
- [0x02] = SENSORS_ERROR_NOT_READY,
- [0x03] = SENSORS_ERROR_NOMEM,
- [0x04] = SENSORS_ERROR_BUSY,
- [0x05] = SENSORS_ERROR_DONE,
- [0x06] = SENSORS_ERROR_UNSUPPORTED,
- [0x07] = SENSORS_ERROR_PARM_INVALID
- };
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn >= MOZ_ARRAY_LENGTH(sError), uint8_t, SensorsError)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<SensorsError>(sError[aIn]);
- return NS_OK;
-}
-
-nsresult
-Convert(uint8_t aIn, SensorsTriggerMode& aOut)
-{
- static const uint8_t sMode[] = {
- [0x00] = SENSORS_TRIGGER_MODE_CONTINUOUS,
- [0x01] = SENSORS_TRIGGER_MODE_ON_CHANGE,
- [0x02] = SENSORS_TRIGGER_MODE_ONE_SHOT,
- [0x03] = SENSORS_TRIGGER_MODE_SPECIAL
- };
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn >= MOZ_ARRAY_LENGTH(sMode), uint8_t, SensorsTriggerMode)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<SensorsTriggerMode>(sMode[aIn]);
- return NS_OK;
-}
-
-nsresult
-Convert(uint32_t aIn, SensorsType& aOut)
-{
- static const uint8_t sType[] = {
- [0x00] = 0, // invalid, required by gcc
- [0x01] = SENSORS_TYPE_ACCELEROMETER,
- [0x02] = SENSORS_TYPE_GEOMAGNETIC_FIELD,
- [0x03] = SENSORS_TYPE_ORIENTATION,
- [0x04] = SENSORS_TYPE_GYROSCOPE,
- [0x05] = SENSORS_TYPE_LIGHT,
- [0x06] = SENSORS_TYPE_PRESSURE,
- [0x07] = SENSORS_TYPE_TEMPERATURE,
- [0x08] = SENSORS_TYPE_PROXIMITY,
- [0x09] = SENSORS_TYPE_GRAVITY,
- [0x0a] = SENSORS_TYPE_LINEAR_ACCELERATION,
- [0x0b] = SENSORS_TYPE_ROTATION_VECTOR,
- [0x0c] = SENSORS_TYPE_RELATIVE_HUMIDITY,
- [0x0d] = SENSORS_TYPE_AMBIENT_TEMPERATURE,
- [0x0e] = SENSORS_TYPE_MAGNETIC_FIELD_UNCALIBRATED,
- [0x0f] = SENSORS_TYPE_GAME_ROTATION_VECTOR,
- [0x10] = SENSORS_TYPE_GYROSCOPE_UNCALIBRATED,
- [0x11] = SENSORS_TYPE_SIGNIFICANT_MOTION,
- [0x12] = SENSORS_TYPE_STEP_DETECTED,
- [0x13] = SENSORS_TYPE_STEP_COUNTER,
- [0x14] = SENSORS_TYPE_GEOMAGNETIC_ROTATION_VECTOR,
- [0x15] = SENSORS_TYPE_HEART_RATE,
- [0x16] = SENSORS_TYPE_TILT_DETECTOR,
- [0x17] = SENSORS_TYPE_WAKE_GESTURE,
- [0x18] = SENSORS_TYPE_GLANCE_GESTURE,
- [0x19] = SENSORS_TYPE_PICK_UP_GESTURE,
- [0x1a] = SENSORS_TYPE_WRIST_TILT_GESTURE
- };
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- !aIn, uint32_t, SensorsType) ||
- MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn >= MOZ_ARRAY_LENGTH(sType), uint32_t, SensorsType)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<SensorsType>(sType[aIn]);
- return NS_OK;
-}
-
-nsresult
-Convert(nsresult aIn, SensorsError& aOut)
-{
- if (NS_SUCCEEDED(aIn)) {
- aOut = SENSORS_ERROR_NONE;
- } else if (aIn == NS_ERROR_OUT_OF_MEMORY) {
- aOut = SENSORS_ERROR_NOMEM;
- } else if (aIn == NS_ERROR_ILLEGAL_VALUE) {
- aOut = SENSORS_ERROR_PARM_INVALID;
- } else {
- aOut = SENSORS_ERROR_FAIL;
- }
- return NS_OK;
-}
-
-//
-// Packing
-//
-// Pack functions store a value in PDU. See the documentation of the
-// HAL IPC framework for more information.
-//
-// There are currently no sensor-specific pack functions necessary. If
-// you add one, put it below.
-//
-
-//
-// Unpacking
-//
-// Unpack function retrieve a value from a PDU. The functions return
-// NS_OK on success, or an XPCOM error code otherwise. On sucess, the
-// returned value is stored in the second argument |aOut|.
-//
-// See the documentation of the HAL IPC framework for more information
-// on unpack functions.
-//
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, SensorsDeliveryMode& aOut)
-{
- return UnpackPDU(aPDU, UnpackConversion<uint8_t, SensorsDeliveryMode>(aOut));
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, SensorsError& aOut)
-{
- return UnpackPDU(aPDU, UnpackConversion<uint8_t, SensorsError>(aOut));
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, SensorsEvent& aOut);
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, SensorsStatus& aOut)
-{
- return UnpackPDU(aPDU, UnpackConversion<int32_t, SensorsStatus>(aOut));
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, SensorsTriggerMode& aOut)
-{
- return UnpackPDU(aPDU, UnpackConversion<uint8_t, SensorsTriggerMode>(aOut));
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, SensorsType& aOut)
-{
- return UnpackPDU(aPDU, UnpackConversion<uint32_t, SensorsType>(aOut));
-}
-
-} // namespace hal
-} // namespace mozilla
-
-#endif // hal_gonk_GonkSensorsHelpers_h
diff --git a/hal/gonk/GonkSensorsInterface.cpp b/hal/gonk/GonkSensorsInterface.cpp
deleted file mode 100644
index 51e1ff50c..000000000
--- a/hal/gonk/GonkSensorsInterface.cpp
+++ /dev/null
@@ -1,494 +0,0 @@
-/* -*- 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 "GonkSensorsInterface.h"
-#include "GonkSensorsPollInterface.h"
-#include "GonkSensorsRegistryInterface.h"
-#include "HalLog.h"
-#include <mozilla/ipc/DaemonSocket.h>
-#include <mozilla/ipc/DaemonSocketConnector.h>
-#include <mozilla/ipc/ListenSocket.h>
-
-namespace mozilla {
-namespace hal {
-
-using namespace mozilla::ipc;
-
-//
-// GonkSensorsResultHandler
-//
-
-void
-GonkSensorsResultHandler::OnError(SensorsError aError)
-{
- HAL_ERR("Received error code %d", static_cast<int>(aError));
-}
-
-void
-GonkSensorsResultHandler::Connect()
-{ }
-
-void
-GonkSensorsResultHandler::Disconnect()
-{ }
-
-GonkSensorsResultHandler::~GonkSensorsResultHandler()
-{ }
-
-//
-// GonkSensorsNotificationHandler
-//
-
-void
-GonkSensorsNotificationHandler::BackendErrorNotification(bool aCrashed)
-{
- if (aCrashed) {
- HAL_ERR("Sensors backend crashed");
- } else {
- HAL_ERR("Error in sensors backend");
- }
-}
-
-GonkSensorsNotificationHandler::~GonkSensorsNotificationHandler()
-{ }
-
-//
-// GonkSensorsProtocol
-//
-
-class GonkSensorsProtocol final
- : public DaemonSocketIOConsumer
- , public GonkSensorsRegistryModule
- , public GonkSensorsPollModule
-{
-public:
- GonkSensorsProtocol();
-
- void SetConnection(DaemonSocket* aConnection);
-
- already_AddRefed<DaemonSocketResultHandler> FetchResultHandler(
- const DaemonSocketPDUHeader& aHeader);
-
- // Methods for |SensorsRegistryModule| and |SensorsPollModule|
- //
-
- nsresult Send(DaemonSocketPDU* aPDU,
- DaemonSocketResultHandler* aRes) override;
-
- // Methods for |DaemonSocketIOConsumer|
- //
-
- void Handle(DaemonSocketPDU& aPDU) override;
- void StoreResultHandler(const DaemonSocketPDU& aPDU) override;
-
-private:
- void HandleRegistrySvc(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes);
- void HandlePollSvc(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes);
-
- DaemonSocket* mConnection;
- nsTArray<RefPtr<DaemonSocketResultHandler>> mResultHandlerQ;
-};
-
-GonkSensorsProtocol::GonkSensorsProtocol()
-{ }
-
-void
-GonkSensorsProtocol::SetConnection(DaemonSocket* aConnection)
-{
- mConnection = aConnection;
-}
-
-already_AddRefed<DaemonSocketResultHandler>
-GonkSensorsProtocol::FetchResultHandler(const DaemonSocketPDUHeader& aHeader)
-{
- MOZ_ASSERT(!NS_IsMainThread());
-
- if (aHeader.mOpcode & 0x80) {
- return nullptr; // Ignore notifications
- }
-
- RefPtr<DaemonSocketResultHandler> res = mResultHandlerQ.ElementAt(0);
- mResultHandlerQ.RemoveElementAt(0);
-
- return res.forget();
-}
-
-void
-GonkSensorsProtocol::HandleRegistrySvc(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes)
-{
- GonkSensorsRegistryModule::HandleSvc(aHeader, aPDU, aRes);
-}
-
-void
-GonkSensorsProtocol::HandlePollSvc(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes)
-{
- GonkSensorsPollModule::HandleSvc(aHeader, aPDU, aRes);
-}
-
-// |SensorsRegistryModule|, |SensorsPollModule|
-
-nsresult
-GonkSensorsProtocol::Send(DaemonSocketPDU* aPDU,
- DaemonSocketResultHandler* aRes)
-{
- MOZ_ASSERT(mConnection);
- MOZ_ASSERT(aPDU);
-
- aPDU->SetConsumer(this);
- aPDU->SetResultHandler(aRes);
- aPDU->UpdateHeader();
-
- if (mConnection->GetConnectionStatus() == SOCKET_DISCONNECTED) {
- HAL_ERR("Sensors socket is disconnected");
- return NS_ERROR_FAILURE;
- }
-
- mConnection->SendSocketData(aPDU); // Forward PDU to data channel
-
- return NS_OK;
-}
-
-// |DaemonSocketIOConsumer|
-
-void
-GonkSensorsProtocol::Handle(DaemonSocketPDU& aPDU)
-{
- static void (GonkSensorsProtocol::* const HandleSvc[])(
- const DaemonSocketPDUHeader&, DaemonSocketPDU&,
- DaemonSocketResultHandler*) = {
- [GonkSensorsRegistryModule::SERVICE_ID] =
- &GonkSensorsProtocol::HandleRegistrySvc,
- [GonkSensorsPollModule::SERVICE_ID] =
- &GonkSensorsProtocol::HandlePollSvc
- };
-
- DaemonSocketPDUHeader header;
-
- if (NS_FAILED(UnpackPDU(aPDU, header))) {
- return;
- }
- if (!(header.mService < MOZ_ARRAY_LENGTH(HandleSvc)) ||
- !HandleSvc[header.mService]) {
- HAL_ERR("Sensors service %d unknown", header.mService);
- return;
- }
-
- RefPtr<DaemonSocketResultHandler> res = FetchResultHandler(header);
-
- (this->*(HandleSvc[header.mService]))(header, aPDU, res);
-}
-
-void
-GonkSensorsProtocol::StoreResultHandler(const DaemonSocketPDU& aPDU)
-{
- MOZ_ASSERT(!NS_IsMainThread());
-
- mResultHandlerQ.AppendElement(aPDU.GetResultHandler());
-}
-
-//
-// GonkSensorsInterface
-//
-
-GonkSensorsInterface*
-GonkSensorsInterface::GetInstance()
-{
- static GonkSensorsInterface* sGonkSensorsInterface;
-
- if (sGonkSensorsInterface) {
- return sGonkSensorsInterface;
- }
-
- sGonkSensorsInterface = new GonkSensorsInterface();
-
- return sGonkSensorsInterface;
-}
-
-void
-GonkSensorsInterface::SetNotificationHandler(
- GonkSensorsNotificationHandler* aNotificationHandler)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- mNotificationHandler = aNotificationHandler;
-}
-
-/*
- * The connect procedure consists of several steps.
- *
- * (1) Start listening for the command channel's socket connection: We
- * do this before anything else, so that we don't miss connection
- * requests from the Sensors daemon. This step will create a listen
- * socket.
- *
- * (2) Start the Sensors daemon: When the daemon starts up it will open
- * a socket connection to Gecko and thus create the data channel.
- * Gecko already opened the listen socket in step (1). Step (2) ends
- * with the creation of the data channel.
- *
- * (3) Signal success to the caller.
- *
- * If any step fails, we roll-back the procedure and signal an error to the
- * caller.
- */
-void
-GonkSensorsInterface::Connect(GonkSensorsNotificationHandler* aNotificationHandler,
- GonkSensorsResultHandler* aRes)
-{
-#define BASE_SOCKET_NAME "sensorsd"
- static unsigned long POSTFIX_LENGTH = 16;
-
- // If we could not cleanup properly before and an old
- // instance of the daemon is still running, we kill it
- // here.
- mozilla::hal::StopSystemService("sensorsd");
-
- mNotificationHandler = aNotificationHandler;
-
- mResultHandlerQ.AppendElement(aRes);
-
- if (!mProtocol) {
- mProtocol = MakeUnique<GonkSensorsProtocol>();
- }
-
- if (!mListenSocket) {
- mListenSocket = new ListenSocket(this, LISTEN_SOCKET);
- }
-
- // Init, step 1: Listen for data channel... */
-
- if (!mDataSocket) {
- mDataSocket = new DaemonSocket(mProtocol.get(), this, DATA_SOCKET);
- } else if (mDataSocket->GetConnectionStatus() == SOCKET_CONNECTED) {
- // Command channel should not be open; let's close it.
- mDataSocket->Close();
- }
-
- // The listen socket's name is generated with a random postfix. This
- // avoids naming collisions if we still have a listen socket from a
- // previously failed cleanup. It also makes it hard for malicious
- // external programs to capture the socket name or connect before
- // the daemon can do so. If no random postfix can be generated, we
- // simply use the base name as-is.
- nsresult rv = DaemonSocketConnector::CreateRandomAddressString(
- NS_LITERAL_CSTRING(BASE_SOCKET_NAME), POSTFIX_LENGTH, mListenSocketName);
- if (NS_FAILED(rv)) {
- mListenSocketName.AssignLiteral(BASE_SOCKET_NAME);
- }
-
- rv = mListenSocket->Listen(new DaemonSocketConnector(mListenSocketName),
- mDataSocket);
- if (NS_FAILED(rv)) {
- OnConnectError(DATA_SOCKET);
- return;
- }
-
- // The protocol implementation needs a data channel for
- // sending commands to the daemon. We set it here, because
- // this is the earliest time when it's available.
- mProtocol->SetConnection(mDataSocket);
-}
-
-/*
- * Disconnecting is inverse to connecting.
- *
- * (1) Close data socket: We close the data channel and the daemon will
- * will notice. Once we see the socket's disconnect, we continue with
- * the cleanup.
- *
- * (2) Close listen socket: The listen socket is not active any longer
- * and we simply close it.
- *
- * (3) Signal success to the caller.
- *
- * We don't have to stop the daemon explicitly. It will cleanup and quit
- * after it noticed the closing of the data channel
- *
- * Rolling back half-completed cleanups is not possible. In the case of
- * an error, we simply push forward and try to recover during the next
- * initialization.
- */
-void
-GonkSensorsInterface::Disconnect(GonkSensorsResultHandler* aRes)
-{
- mNotificationHandler = nullptr;
-
- // Cleanup, step 1: Close data channel
- mDataSocket->Close();
-
- mResultHandlerQ.AppendElement(aRes);
-}
-
-GonkSensorsRegistryInterface*
-GonkSensorsInterface::GetSensorsRegistryInterface()
-{
- if (mRegistryInterface) {
- return mRegistryInterface.get();
- }
-
- mRegistryInterface = MakeUnique<GonkSensorsRegistryInterface>(mProtocol.get());
-
- return mRegistryInterface.get();
-}
-
-GonkSensorsPollInterface*
-GonkSensorsInterface::GetSensorsPollInterface()
-{
- if (mPollInterface) {
- return mPollInterface.get();
- }
-
- mPollInterface = MakeUnique<GonkSensorsPollInterface>(mProtocol.get());
-
- return mPollInterface.get();
-}
-
-GonkSensorsInterface::GonkSensorsInterface()
- : mNotificationHandler(nullptr)
-{ }
-
-GonkSensorsInterface::~GonkSensorsInterface()
-{ }
-
-void
-GonkSensorsInterface::DispatchError(GonkSensorsResultHandler* aRes,
- SensorsError aError)
-{
- DaemonResultRunnable1<GonkSensorsResultHandler, void,
- SensorsError, SensorsError>::Dispatch(
- aRes, &GonkSensorsResultHandler::OnError,
- ConstantInitOp1<SensorsError>(aError));
-}
-
-void
-GonkSensorsInterface::DispatchError(
- GonkSensorsResultHandler* aRes, nsresult aRv)
-{
- SensorsError error;
-
- if (NS_FAILED(Convert(aRv, error))) {
- error = SENSORS_ERROR_FAIL;
- }
- DispatchError(aRes, error);
-}
-
-// |DaemonSocketConsumer|, |ListenSocketConsumer|
-
-void
-GonkSensorsInterface::OnConnectSuccess(int aIndex)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!mResultHandlerQ.IsEmpty());
-
- switch (aIndex) {
- case LISTEN_SOCKET: {
- // Init, step 2: Start Sensors daemon
- nsCString args("-a ");
- args.Append(mListenSocketName);
- mozilla::hal::StartSystemService("sensorsd", args.get());
- }
- break;
- case DATA_SOCKET:
- if (!mResultHandlerQ.IsEmpty()) {
- // Init, step 3: Signal success
- RefPtr<GonkSensorsResultHandler> res = mResultHandlerQ.ElementAt(0);
- mResultHandlerQ.RemoveElementAt(0);
- if (res) {
- res->Connect();
- }
- }
- break;
- }
-}
-
-void
-GonkSensorsInterface::OnConnectError(int aIndex)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!mResultHandlerQ.IsEmpty());
-
- switch (aIndex) {
- case DATA_SOCKET:
- // Stop daemon and close listen socket
- mozilla::hal::StopSystemService("sensorsd");
- mListenSocket->Close();
- // fall through
- case LISTEN_SOCKET:
- if (!mResultHandlerQ.IsEmpty()) {
- // Signal error to caller
- RefPtr<GonkSensorsResultHandler> res = mResultHandlerQ.ElementAt(0);
- mResultHandlerQ.RemoveElementAt(0);
- if (res) {
- DispatchError(res, SENSORS_ERROR_FAIL);
- }
- }
- break;
- }
-}
-
-/*
- * Disconnects can happend
- *
- * (a) during startup,
- * (b) during regular service, or
- * (c) during shutdown.
- *
- * For cases (a) and (c), |mResultHandlerQ| contains an element. For
- * case (b) |mResultHandlerQ| will be empty. This distinguishes a crash in
- * the daemon. The following procedure to recover from crashes consists of
- * several steps for case (b).
- *
- * (1) Close listen socket.
- * (2) Wait for all sockets to be disconnected and inform caller about
- * the crash.
- * (3) After all resources have been cleaned up, let the caller restart
- * the daemon.
- */
-void
-GonkSensorsInterface::OnDisconnect(int aIndex)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- switch (aIndex) {
- case DATA_SOCKET:
- // Cleanup, step 2 (Recovery, step 1): Close listen socket
- mListenSocket->Close();
- break;
- case LISTEN_SOCKET:
- // Cleanup, step 3: Signal success to caller
- if (!mResultHandlerQ.IsEmpty()) {
- RefPtr<GonkSensorsResultHandler> res = mResultHandlerQ.ElementAt(0);
- mResultHandlerQ.RemoveElementAt(0);
- if (res) {
- res->Disconnect();
- }
- }
- break;
- }
-
- /* For recovery make sure all sockets disconnected, in order to avoid
- * the remaining disconnects interfere with the restart procedure.
- */
- if (mNotificationHandler && mResultHandlerQ.IsEmpty()) {
- if (mListenSocket->GetConnectionStatus() == SOCKET_DISCONNECTED &&
- mDataSocket->GetConnectionStatus() == SOCKET_DISCONNECTED) {
- // Recovery, step 2: Notify the caller to prepare the restart procedure.
- mNotificationHandler->BackendErrorNotification(true);
- mNotificationHandler = nullptr;
- }
- }
-}
-
-} // namespace hal
-} // namespace mozilla
diff --git a/hal/gonk/GonkSensorsInterface.h b/hal/gonk/GonkSensorsInterface.h
deleted file mode 100644
index 6e356dc36..000000000
--- a/hal/gonk/GonkSensorsInterface.h
+++ /dev/null
@@ -1,191 +0,0 @@
-/* -*- 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/. */
-
-/*
- * The sensors interface gives you access to the low-level sensors code
- * in a platform-independent manner. The interfaces in this file allow
- * for starting an stopping the sensors driver. Specific functionality
- * is implemented in sub-interfaces.
- */
-
-#ifndef hal_gonk_GonkSensorsInterface_h
-#define hal_gonk_GonkSensorsInterface_h
-
-#include <mozilla/ipc/DaemonSocketConsumer.h>
-#include <mozilla/ipc/DaemonSocketMessageHandlers.h>
-#include <mozilla/ipc/ListenSocketConsumer.h>
-#include <mozilla/UniquePtr.h>
-#include "SensorsTypes.h"
-
-namespace mozilla {
-namespace ipc {
-
-class DaemonSocket;
-class ListenSocket;
-
-}
-}
-
-namespace mozilla {
-namespace hal {
-
-class GonkSensorsPollInterface;
-class GonkSensorsProtocol;
-class GonkSensorsRegistryInterface;
-
-/**
- * This class is the result-handler interface for the Sensors
- * interface. Methods always run on the main thread.
- */
-class GonkSensorsResultHandler
- : public mozilla::ipc::DaemonSocketResultHandler
-{
-public:
-
- /**
- * Called if a command failed.
- *
- * @param aError The error code.
- */
- virtual void OnError(SensorsError aError);
-
- /**
- * The callback method for |GonkSensorsInterface::Connect|.
- */
- virtual void Connect();
-
- /**
- * The callback method for |GonkSensorsInterface::Connect|.
- */
- virtual void Disconnect();
-
-protected:
- virtual ~GonkSensorsResultHandler();
-};
-
-/**
- * This is the notification-handler interface. Implement this classes
- * methods to handle event and notifications from the sensors daemon.
- * All methods run on the main thread.
- */
-class GonkSensorsNotificationHandler
-{
-public:
-
- /**
- * This notification is called when the backend code fails
- * unexpectedly. Save state in the high-level code and restart
- * the driver.
- *
- * @param aCrash True is the sensors driver crashed.
- */
- virtual void BackendErrorNotification(bool aCrashed);
-
-protected:
- virtual ~GonkSensorsNotificationHandler();
-};
-
-/**
- * This class implements the public interface to the Sensors functionality
- * and driver. Use |GonkSensorsInterface::GetInstance| to retrieve an instance.
- * All methods run on the main thread.
- */
-class GonkSensorsInterface final
- : public mozilla::ipc::DaemonSocketConsumer
- , public mozilla::ipc::ListenSocketConsumer
-{
-public:
- /**
- * Returns an instance of the Sensors backend. This code can return
- * |nullptr| if no Sensors backend is available.
- *
- * @return An instance of |GonkSensorsInterface|.
- */
- static GonkSensorsInterface* GetInstance();
-
- /**
- * This method sets the notification handler for sensor notifications. Call
- * this method immediately after retreiving an instance of the class, or you
- * won't be able able to receive notifications. You may not free the handler
- * class while the Sensors backend is connected.
- *
- * @param aNotificationHandler An instance of a notification handler.
- */
- void SetNotificationHandler(
- GonkSensorsNotificationHandler* aNotificationHandler);
-
- /**
- * This method starts the Sensors backend and establishes ad connection
- * with Gecko. This is a multi-step process and errors are signalled by
- * |GonkSensorsNotificationHandler::BackendErrorNotification|. If you see
- * this notification before the connection has been established, it's
- * certainly best to assume the Sensors backend to be not evailable.
- *
- * @param aRes The result handler.
- */
- void Connect(GonkSensorsNotificationHandler* aNotificationHandler,
- GonkSensorsResultHandler* aRes);
-
- /**
- * This method disconnects Gecko from the Sensors backend and frees
- * the backend's resources. This will invalidate all interfaces and
- * state. Don't use any sensors functionality without reconnecting
- * first.
- *
- * @param aRes The result handler.
- */
- void Disconnect(GonkSensorsResultHandler* aRes);
-
- /**
- * Returns the Registry interface for the connected Sensors backend.
- *
- * @return An instance of the Sensors Registry interface.
- */
- GonkSensorsRegistryInterface* GetSensorsRegistryInterface();
-
- /**
- * Returns the Poll interface for the connected Sensors backend.
- *
- * @return An instance of the Sensors Poll interface.
- */
- GonkSensorsPollInterface* GetSensorsPollInterface();
-
-private:
- enum Channel {
- LISTEN_SOCKET,
- DATA_SOCKET
- };
-
- GonkSensorsInterface();
- ~GonkSensorsInterface();
-
- void DispatchError(GonkSensorsResultHandler* aRes, SensorsError aError);
- void DispatchError(GonkSensorsResultHandler* aRes, nsresult aRv);
-
- // Methods for |DaemonSocketConsumer| and |ListenSocketConsumer|
- //
-
- void OnConnectSuccess(int aIndex) override;
- void OnConnectError(int aIndex) override;
- void OnDisconnect(int aIndex) override;
-
- nsCString mListenSocketName;
- RefPtr<mozilla::ipc::ListenSocket> mListenSocket;
- RefPtr<mozilla::ipc::DaemonSocket> mDataSocket;
- UniquePtr<GonkSensorsProtocol> mProtocol;
-
- nsTArray<RefPtr<GonkSensorsResultHandler> > mResultHandlerQ;
-
- GonkSensorsNotificationHandler* mNotificationHandler;
-
- UniquePtr<GonkSensorsRegistryInterface> mRegistryInterface;
- UniquePtr<GonkSensorsPollInterface> mPollInterface;
-};
-
-} // namespace hal
-} // namespace mozilla
-
-#endif // hal_gonk_GonkSensorsInterface_h
diff --git a/hal/gonk/GonkSensorsPollInterface.cpp b/hal/gonk/GonkSensorsPollInterface.cpp
deleted file mode 100644
index d4edc2e7a..000000000
--- a/hal/gonk/GonkSensorsPollInterface.cpp
+++ /dev/null
@@ -1,431 +0,0 @@
-/* -*- 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 "GonkSensorsPollInterface.h"
-#include "HalLog.h"
-#include <mozilla/UniquePtr.h>
-
-namespace mozilla {
-namespace hal {
-
-using namespace mozilla::ipc;
-
-//
-// GonkSensorsPollResultHandler
-//
-
-void
-GonkSensorsPollResultHandler::OnError(SensorsError aError)
-{
- HAL_ERR("Received error code %d", static_cast<int>(aError));
-}
-
-void
-GonkSensorsPollResultHandler::EnableSensor()
-{ }
-
-void
-GonkSensorsPollResultHandler::DisableSensor()
-{ }
-
-void
-GonkSensorsPollResultHandler::SetPeriod()
-{ }
-
-GonkSensorsPollResultHandler::~GonkSensorsPollResultHandler()
-{ }
-
-//
-// GonkSensorsPollNotificationHandler
-//
-
-void
-GonkSensorsPollNotificationHandler::ErrorNotification(SensorsError aError)
-{
- HAL_ERR("Received error code %d", static_cast<int>(aError));
-}
-
-void
-GonkSensorsPollNotificationHandler::SensorDetectedNotification(
- int32_t aId,
- SensorsType aType,
- float aRange,
- float aResolution,
- float aPower,
- int32_t aMinPeriod,
- int32_t aMaxPeriod,
- SensorsTriggerMode aTriggerMode,
- SensorsDeliveryMode aDeliveryMode)
-{ }
-
-void
-GonkSensorsPollNotificationHandler::SensorLostNotification(int32_t aId)
-{ }
-
-void
-GonkSensorsPollNotificationHandler::EventNotification(int32_t aId,
- const SensorsEvent& aEvent)
-{ }
-
-GonkSensorsPollNotificationHandler::~GonkSensorsPollNotificationHandler()
-{ }
-
-//
-// GonkSensorsPollModule
-//
-
-GonkSensorsPollModule::GonkSensorsPollModule()
- : mProtocolVersion(0)
-{ }
-
-GonkSensorsPollModule::~GonkSensorsPollModule()
-{ }
-
-nsresult
-GonkSensorsPollModule::SetProtocolVersion(unsigned long aProtocolVersion)
-{
- if ((aProtocolVersion < MIN_PROTOCOL_VERSION) ||
- (aProtocolVersion > MAX_PROTOCOL_VERSION)) {
- HAL_ERR("Sensors Poll protocol version %lu not supported",
- aProtocolVersion);
- return NS_ERROR_ILLEGAL_VALUE;
- }
- mProtocolVersion = aProtocolVersion;
- return NS_OK;
-}
-
-void
-GonkSensorsPollModule::HandleSvc(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes)
-{
- static void (GonkSensorsPollModule::* const HandleOp[])(
- const DaemonSocketPDUHeader&, DaemonSocketPDU&,
- DaemonSocketResultHandler*) = {
- [0] = &GonkSensorsPollModule::HandleRsp,
- [1] = &GonkSensorsPollModule::HandleNtf
- };
-
- MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
-
- // Negate twice to map bit to 0/1
- unsigned long isNtf = !!(aHeader.mOpcode & 0x80);
-
- (this->*(HandleOp[isNtf]))(aHeader, aPDU, aRes);
-}
-
-// Commands
-//
-
-nsresult
-GonkSensorsPollModule::EnableSensorCmd(int32_t aId, GonkSensorsPollResultHandler* aRes)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- UniquePtr<DaemonSocketPDU> pdu =
- MakeUnique<DaemonSocketPDU>(SERVICE_ID, OPCODE_ENABLE_SENSOR, 0);
-
- nsresult rv = PackPDU(aId, *pdu);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = Send(pdu.get(), aRes);
- if (NS_FAILED(rv)) {
- return rv;
- }
- Unused << pdu.release();
- return NS_OK;
-}
-
-nsresult
-GonkSensorsPollModule::DisableSensorCmd(int32_t aId, GonkSensorsPollResultHandler* aRes)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- UniquePtr<DaemonSocketPDU> pdu =
- MakeUnique<DaemonSocketPDU>(SERVICE_ID, OPCODE_DISABLE_SENSOR, 0);
-
- nsresult rv = PackPDU(aId, *pdu);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = Send(pdu.get(), aRes);
- if (NS_FAILED(rv)) {
- return rv;
- }
- Unused << pdu.release();
- return NS_OK;
-}
-
-nsresult
-GonkSensorsPollModule::SetPeriodCmd(int32_t aId, uint64_t aPeriod,
- GonkSensorsPollResultHandler* aRes)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- UniquePtr<DaemonSocketPDU> pdu =
- MakeUnique<DaemonSocketPDU>(SERVICE_ID, OPCODE_SET_PERIOD, 0);
-
- nsresult rv = PackPDU(aId, *pdu);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aPeriod, *pdu);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = Send(pdu.get(), aRes);
- if (NS_FAILED(rv)) {
- return rv;
- }
- Unused << pdu.release();
- return NS_OK;
-}
-
-// Responses
-//
-
-void
-GonkSensorsPollModule::ErrorRsp(
- const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU, GonkSensorsPollResultHandler* aRes)
-{
- ErrorRunnable::Dispatch(
- aRes, &GonkSensorsPollResultHandler::OnError, UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsPollModule::EnableSensorRsp(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- GonkSensorsPollResultHandler* aRes)
-{
- ResultRunnable::Dispatch(
- aRes, &GonkSensorsPollResultHandler::EnableSensor, UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsPollModule::DisableSensorRsp(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- GonkSensorsPollResultHandler* aRes)
-{
- ResultRunnable::Dispatch(
- aRes, &GonkSensorsPollResultHandler::DisableSensor, UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsPollModule::SetPeriodRsp(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- GonkSensorsPollResultHandler* aRes)
-{
- ResultRunnable::Dispatch(
- aRes, &GonkSensorsPollResultHandler::SetPeriod, UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsPollModule::HandleRsp(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes)
-{
- static void (GonkSensorsPollModule::* const sHandleRsp[])(
- const DaemonSocketPDUHeader&, DaemonSocketPDU&,
- GonkSensorsPollResultHandler*) = {
- [OPCODE_ERROR] = &GonkSensorsPollModule::ErrorRsp,
- [OPCODE_ENABLE_SENSOR] = &GonkSensorsPollModule::EnableSensorRsp,
- [OPCODE_DISABLE_SENSOR] = &GonkSensorsPollModule::DisableSensorRsp,
- [OPCODE_SET_PERIOD] = &GonkSensorsPollModule::SetPeriodRsp,
- };
-
- MOZ_ASSERT(!NS_IsMainThread()); // I/O thread
-
- if (!(aHeader.mOpcode < MOZ_ARRAY_LENGTH(sHandleRsp)) ||
- !sHandleRsp[aHeader.mOpcode]) {
- HAL_ERR("Sensors poll response opcode %d unknown", aHeader.mOpcode);
- return;
- }
-
- RefPtr<GonkSensorsPollResultHandler> res =
- static_cast<GonkSensorsPollResultHandler*>(aRes);
-
- if (!res) {
- return; // Return early if no result handler has been set for response
- }
-
- (this->*(sHandleRsp[aHeader.mOpcode]))(aHeader, aPDU, res);
-}
-
-// Notifications
-//
-
-// Returns the current notification handler to a notification runnable
-class GonkSensorsPollModule::NotificationHandlerWrapper final
-{
-public:
- typedef GonkSensorsPollNotificationHandler ObjectType;
-
- static ObjectType* GetInstance()
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- return sNotificationHandler;
- }
-
- static GonkSensorsPollNotificationHandler* sNotificationHandler;
-};
-
-GonkSensorsPollNotificationHandler*
- GonkSensorsPollModule::NotificationHandlerWrapper::sNotificationHandler;
-
-void
-GonkSensorsPollModule::ErrorNtf(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU)
-{
- ErrorNotification::Dispatch(
- &GonkSensorsPollNotificationHandler::ErrorNotification,
- UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsPollModule::SensorDetectedNtf(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU)
-{
- SensorDetectedNotification::Dispatch(
- &GonkSensorsPollNotificationHandler::SensorDetectedNotification,
- UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsPollModule::SensorLostNtf(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU)
-{
- SensorLostNotification::Dispatch(
- &GonkSensorsPollNotificationHandler::SensorLostNotification,
- UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsPollModule::EventNtf(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU)
-{
- EventNotification::Dispatch(
- &GonkSensorsPollNotificationHandler::EventNotification,
- UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsPollModule::HandleNtf(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes)
-{
- static void (GonkSensorsPollModule::* const sHandleNtf[])(
- const DaemonSocketPDUHeader&, DaemonSocketPDU&) = {
- [0] = &GonkSensorsPollModule::ErrorNtf,
- [1] = &GonkSensorsPollModule::SensorDetectedNtf,
- [2] = &GonkSensorsPollModule::SensorLostNtf,
- [3] = &GonkSensorsPollModule::EventNtf
- };
-
- MOZ_ASSERT(!NS_IsMainThread());
-
- uint8_t index = aHeader.mOpcode - 0x80;
-
- if (!(index < MOZ_ARRAY_LENGTH(sHandleNtf)) || !sHandleNtf[index]) {
- HAL_ERR("Sensors poll notification opcode %d unknown", aHeader.mOpcode);
- return;
- }
-
- (this->*(sHandleNtf[index]))(aHeader, aPDU);
-}
-
-//
-// GonkSensorsPollInterface
-//
-
-GonkSensorsPollInterface::GonkSensorsPollInterface(
- GonkSensorsPollModule* aModule)
- : mModule(aModule)
-{ }
-
-GonkSensorsPollInterface::~GonkSensorsPollInterface()
-{ }
-
-void
-GonkSensorsPollInterface::SetNotificationHandler(
- GonkSensorsPollNotificationHandler* aNotificationHandler)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- GonkSensorsPollModule::NotificationHandlerWrapper::sNotificationHandler =
- aNotificationHandler;
-}
-
-nsresult
-GonkSensorsPollInterface::SetProtocolVersion(unsigned long aProtocolVersion)
-{
- MOZ_ASSERT(mModule);
-
- return mModule->SetProtocolVersion(aProtocolVersion);
-}
-
-void
-GonkSensorsPollInterface::EnableSensor(int32_t aId,
- GonkSensorsPollResultHandler* aRes)
-{
- MOZ_ASSERT(mModule);
-
- nsresult rv = mModule->EnableSensorCmd(aId, aRes);
- if (NS_FAILED(rv)) {
- DispatchError(aRes, rv);
- }
-}
-
-void
-GonkSensorsPollInterface::DisableSensor(int32_t aId,
- GonkSensorsPollResultHandler* aRes)
-{
- MOZ_ASSERT(mModule);
-
- nsresult rv = mModule->DisableSensorCmd(aId, aRes);
- if (NS_FAILED(rv)) {
- DispatchError(aRes, rv);
- }
-}
-
-void
-GonkSensorsPollInterface::SetPeriod(int32_t aId, uint64_t aPeriod,
- GonkSensorsPollResultHandler* aRes)
-{
- MOZ_ASSERT(mModule);
-
- nsresult rv = mModule->SetPeriodCmd(aId, aPeriod, aRes);
- if (NS_FAILED(rv)) {
- DispatchError(aRes, rv);
- }
-}
-
-void
-GonkSensorsPollInterface::DispatchError(
- GonkSensorsPollResultHandler* aRes, SensorsError aError)
-{
- DaemonResultRunnable1<GonkSensorsPollResultHandler, void,
- SensorsError, SensorsError>::Dispatch(
- aRes, &GonkSensorsPollResultHandler::OnError,
- ConstantInitOp1<SensorsError>(aError));
-}
-
-void
-GonkSensorsPollInterface::DispatchError(
- GonkSensorsPollResultHandler* aRes, nsresult aRv)
-{
- SensorsError error;
-
- if (NS_FAILED(Convert(aRv, error))) {
- error = SENSORS_ERROR_FAIL;
- }
- DispatchError(aRes, error);
-}
-
-} // namespace hal
-} // namespace mozilla
diff --git a/hal/gonk/GonkSensorsPollInterface.h b/hal/gonk/GonkSensorsPollInterface.h
deleted file mode 100644
index 89381a9bd..000000000
--- a/hal/gonk/GonkSensorsPollInterface.h
+++ /dev/null
@@ -1,340 +0,0 @@
-/* -*- 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/. */
-
-/*
- * The poll interface gives yo access to the Sensors daemon's Poll service,
- * which handles sensors. The poll service will inform you when sensors are
- * detected or removed from the system. You can activate (or deactivate)
- * existing sensors and poll will deliver the sensors' events.
- *
- * All public methods and callback methods run on the main thread.
- */
-
-#ifndef hal_gonk_GonkSensorsPollInterface_h
-#define hal_gonk_GonkSensorsPollInterface_h
-
-#include <mozilla/ipc/DaemonRunnables.h>
-#include <mozilla/ipc/DaemonSocketMessageHandlers.h>
-#include "SensorsTypes.h"
-
-namespace mozilla {
-namespace ipc {
-
-class DaemonSocketPDU;
-class DaemonSocketPDUHeader;
-
-}
-}
-
-namespace mozilla {
-namespace hal {
-
-class SensorsInterface;
-
-using mozilla::ipc::DaemonSocketPDU;
-using mozilla::ipc::DaemonSocketPDUHeader;
-using mozilla::ipc::DaemonSocketResultHandler;
-
-/**
- * This class is the result-handler interface for the Sensors
- * Poll interface. Methods always run on the main thread.
- */
-class GonkSensorsPollResultHandler : public DaemonSocketResultHandler
-{
-public:
-
- /**
- * Called if a poll command failed.
- *
- * @param aError The error code.
- */
- virtual void OnError(SensorsError aError);
-
- /**
- * The callback method for |GonkSensorsPollInterface::EnableSensor|.
- */
- virtual void EnableSensor();
-
- /**
- * The callback method for |GonkSensorsPollInterface::DisableSensor|.
- */
- virtual void DisableSensor();
-
- /**
- * The callback method for |GonkSensorsPollInterface::SetPeriod|.
- */
- virtual void SetPeriod();
-
-protected:
- virtual ~GonkSensorsPollResultHandler();
-};
-
-/**
- * This is the notification-handler interface. Implement this classes
- * methods to handle event and notifications from the sensors daemon.
- */
-class GonkSensorsPollNotificationHandler
-{
-public:
-
- /**
- * The notification handler for errors. You'll receive this call if
- * there's been a critical error in the daemon. Either try to handle
- * the error, or restart the daemon.
- *
- * @param aError The error code.
- */
- virtual void ErrorNotification(SensorsError aError);
-
- /**
- * This methods gets call when a new sensor has been detected.
- *
- * @param aId The sensor's id.
- * @param aType The sensor's type.
- * @param aRange The sensor's maximum value.
- * @param aResolution The minimum difference between two consecutive values.
- * @param aPower The sensor's power consumption (in mA).
- * @param aMinPeriod The minimum time between two events (in ns).
- * @param aMaxPeriod The maximum time between two events (in ns).
- * @param aTriggerMode The sensor's mode for triggering events.
- * @param aDeliveryMode The sensor's urgency for event delivery.
- */
- virtual void SensorDetectedNotification(int32_t aId, SensorsType aType,
- float aRange, float aResolution,
- float aPower, int32_t aMinPeriod,
- int32_t aMaxPeriod,
- SensorsTriggerMode aTriggerMode,
- SensorsDeliveryMode aDeliveryMode);
-
- /**
- * This methods gets call when an existing sensor has been removed.
- *
- * @param aId The sensor's id.
- */
- virtual void SensorLostNotification(int32_t aId);
-
- /**
- * This is the callback methods for sensor events. Only activated sensors
- * generate events. All sensors are disabled by default. The actual data
- * of the event depends on the sensor type.
- *
- * @param aId The sensor's id.
- * @param aEvent The event's data.
- */
- virtual void EventNotification(int32_t aId, const SensorsEvent& aEvent);
-
-protected:
- virtual ~GonkSensorsPollNotificationHandler();
-};
-
-/**
- * This is the module class for the Sensors poll component. It handles PDU
- * packing and unpacking. Methods are either executed on the main thread or
- * the I/O thread.
- *
- * This is an internal class, use |GonkSensorsPollInterface| instead.
- */
-class GonkSensorsPollModule
-{
-public:
- class NotificationHandlerWrapper;
-
- enum {
- SERVICE_ID = 0x01
- };
-
- enum {
- OPCODE_ERROR = 0x00,
- OPCODE_ENABLE_SENSOR = 0x01,
- OPCODE_DISABLE_SENSOR = 0x02,
- OPCODE_SET_PERIOD = 0x03
- };
-
- enum {
- MIN_PROTOCOL_VERSION = 1,
- MAX_PROTOCOL_VERSION = 1
- };
-
- virtual nsresult Send(DaemonSocketPDU* aPDU,
- DaemonSocketResultHandler* aRes) = 0;
-
- nsresult SetProtocolVersion(unsigned long aProtocolVersion);
-
- //
- // Commands
- //
-
- nsresult EnableSensorCmd(int32_t aId,
- GonkSensorsPollResultHandler* aRes);
-
- nsresult DisableSensorCmd(int32_t aId,
- GonkSensorsPollResultHandler* aRes);
-
- nsresult SetPeriodCmd(int32_t aId, uint64_t aPeriod,
- GonkSensorsPollResultHandler* aRes);
-
-protected:
- GonkSensorsPollModule();
- virtual ~GonkSensorsPollModule();
-
- void HandleSvc(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes);
-
-private:
-
- //
- // Responses
- //
-
- typedef mozilla::ipc::DaemonResultRunnable0<
- GonkSensorsPollResultHandler, void>
- ResultRunnable;
-
- typedef mozilla::ipc::DaemonResultRunnable1<
- GonkSensorsPollResultHandler, void, SensorsError, SensorsError>
- ErrorRunnable;
-
- void ErrorRsp(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- GonkSensorsPollResultHandler* aRes);
-
- void EnableSensorRsp(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- GonkSensorsPollResultHandler* aRes);
-
- void DisableSensorRsp(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- GonkSensorsPollResultHandler* aRes);
-
- void SetPeriodRsp(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- GonkSensorsPollResultHandler* aRes);
-
- void HandleRsp(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes);
-
- //
- // Notifications
- //
-
- typedef mozilla::ipc::DaemonNotificationRunnable1<
- NotificationHandlerWrapper, void, SensorsError>
- ErrorNotification;
-
- typedef mozilla::ipc::DaemonNotificationRunnable9<
- NotificationHandlerWrapper, void, int32_t, SensorsType,
- float, float, float, int32_t, int32_t, SensorsTriggerMode,
- SensorsDeliveryMode>
- SensorDetectedNotification;
-
- typedef mozilla::ipc::DaemonNotificationRunnable1<
- NotificationHandlerWrapper, void, int32_t>
- SensorLostNotification;
-
- typedef mozilla::ipc::DaemonNotificationRunnable2<
- NotificationHandlerWrapper, void, int32_t, SensorsEvent, int32_t,
- const SensorsEvent&>
- EventNotification;
-
- class SensorDetectedInitOp;
- class SensorLostInitOp;
- class EventInitOp;
-
- void ErrorNtf(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU);
-
- void SensorDetectedNtf(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU);
-
- void SensorLostNtf(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU);
-
- void EventNtf(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU);
-
- void HandleNtf(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes);
-
-private:
- unsigned long mProtocolVersion;
-};
-
-/**
- * This class implements the public interface to the Sensors poll
- * component. Use |SensorsInterface::GetPollInterface| to retrieve
- * an instance. All methods run on the main thread.
- */
-class GonkSensorsPollInterface final
-{
-public:
- GonkSensorsPollInterface(GonkSensorsPollModule* aModule);
- ~GonkSensorsPollInterface();
-
- /**
- * This method sets the notification handler for poll notifications. Call
- * this method immediately after registering the module. Otherwise you won't
- * be able able to receive poll notifications. You may not free the handler
- * class while the poll component is regsitered.
- *
- * @param aNotificationHandler An instance of a poll notification handler.
- */
- void SetNotificationHandler(
- GonkSensorsPollNotificationHandler* aNotificationHandler);
-
- /**
- * This method sets the protocol version. You should set it to the
- * value that has been returned from the backend when registering the
- * Poll service. You cannot send or receive messages before setting
- * the protocol version.
- *
- * @param aProtocolVersion
- * @return NS_OK for supported versions, or an XPCOM error code otherwise.
- */
- nsresult SetProtocolVersion(unsigned long aProtocolVersion);
-
- /**
- * Enables an existing sensor. The sensor id will have been delivered in
- * a SensorDetectedNotification.
- *
- * @param aId The sensor's id.
- * @param aRes The result handler.
- */
- void EnableSensor(int32_t aId, GonkSensorsPollResultHandler* aRes);
-
- /**
- * Disables an existing sensor. The sensor id will have been delivered in
- * a SensorDetectedNotification.
- *
- * @param aId The sensor's id.
- * @param aRes The result handler.
- */
- void DisableSensor(int32_t aId, GonkSensorsPollResultHandler* aRes);
-
- /**
- * Sets the period for a sensor. The sensor id will have been delivered in
- * a SensorDetectedNotification. The value for the period should be between
- * the sensor's minimum and maximum period.
- *
- * @param aId The sensor's id.
- * @param aPeriod The sensor's new period.
- * @param aRes The result handler.
- */
- void SetPeriod(int32_t aId, uint64_t aPeriod, GonkSensorsPollResultHandler* aRes);
-
-private:
- void DispatchError(GonkSensorsPollResultHandler* aRes, SensorsError aError);
- void DispatchError(GonkSensorsPollResultHandler* aRes, nsresult aRv);
-
- GonkSensorsPollModule* mModule;
-};
-
-} // hal
-} // namespace mozilla
-
-#endif // hal_gonk_GonkSensorsPollInterface_h
diff --git a/hal/gonk/GonkSensorsRegistryInterface.cpp b/hal/gonk/GonkSensorsRegistryInterface.cpp
deleted file mode 100644
index 601dc7a2a..000000000
--- a/hal/gonk/GonkSensorsRegistryInterface.cpp
+++ /dev/null
@@ -1,213 +0,0 @@
-/* -*- 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 "GonkSensorsRegistryInterface.h"
-#include "GonkSensorsHelpers.h"
-#include "HalLog.h"
-#include <mozilla/UniquePtr.h>
-
-namespace mozilla {
-namespace hal {
-
-using namespace mozilla::ipc;
-
-//
-// GonkSensorsRegistryResultHandler
-//
-
-void
-GonkSensorsRegistryResultHandler::OnError(SensorsError aError)
-{
- HAL_ERR("Received error code %d", static_cast<int>(aError));
-}
-
-void
-GonkSensorsRegistryResultHandler::RegisterModule(uint32_t aProtocolVersion)
-{ }
-
-void
-GonkSensorsRegistryResultHandler::UnregisterModule()
-{ }
-
-GonkSensorsRegistryResultHandler::~GonkSensorsRegistryResultHandler()
-{ }
-
-//
-// GonkSensorsRegistryModule
-//
-
-GonkSensorsRegistryModule::~GonkSensorsRegistryModule()
-{ }
-
-void
-GonkSensorsRegistryModule::HandleSvc(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- DaemonSocketResultHandler* aRes)
-{
- static void (GonkSensorsRegistryModule::* const HandleRsp[])(
- const DaemonSocketPDUHeader&,
- DaemonSocketPDU&,
- GonkSensorsRegistryResultHandler*) = {
- [OPCODE_ERROR] = &GonkSensorsRegistryModule::ErrorRsp,
- [OPCODE_REGISTER_MODULE] = &GonkSensorsRegistryModule::RegisterModuleRsp,
- [OPCODE_UNREGISTER_MODULE] = &GonkSensorsRegistryModule::UnregisterModuleRsp
- };
-
- if ((aHeader.mOpcode >= MOZ_ARRAY_LENGTH(HandleRsp)) ||
- !HandleRsp[aHeader.mOpcode]) {
- HAL_ERR("Sensors registry response opcode %d unknown", aHeader.mOpcode);
- return;
- }
-
- RefPtr<GonkSensorsRegistryResultHandler> res =
- static_cast<GonkSensorsRegistryResultHandler*>(aRes);
-
- if (!res) {
- return; // Return early if no result handler has been set
- }
-
- (this->*(HandleRsp[aHeader.mOpcode]))(aHeader, aPDU, res);
-}
-
-// Commands
-//
-
-nsresult
-GonkSensorsRegistryModule::RegisterModuleCmd(
- uint8_t aId, GonkSensorsRegistryResultHandler* aRes)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- UniquePtr<DaemonSocketPDU> pdu =
- MakeUnique<DaemonSocketPDU>(SERVICE_ID, OPCODE_REGISTER_MODULE, 0);
-
- nsresult rv = PackPDU(aId, *pdu);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = Send(pdu.get(), aRes);
- if (NS_FAILED(rv)) {
- return rv;
- }
- Unused << pdu.release();
- return NS_OK;
-}
-
-nsresult
-GonkSensorsRegistryModule::UnregisterModuleCmd(
- uint8_t aId, GonkSensorsRegistryResultHandler* aRes)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- UniquePtr<DaemonSocketPDU> pdu =
- MakeUnique<DaemonSocketPDU>(SERVICE_ID, OPCODE_UNREGISTER_MODULE, 0);
-
- nsresult rv = PackPDU(aId, *pdu);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = Send(pdu.get(), aRes);
- if (NS_FAILED(rv)) {
- return rv;
- }
- Unused << pdu.release();
- return NS_OK;
-}
-
-// Responses
-//
-
-void
-GonkSensorsRegistryModule::ErrorRsp(
- const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU, GonkSensorsRegistryResultHandler* aRes)
-{
- ErrorRunnable::Dispatch(
- aRes, &GonkSensorsRegistryResultHandler::OnError, UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsRegistryModule::RegisterModuleRsp(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- GonkSensorsRegistryResultHandler* aRes)
-{
- Uint32ResultRunnable::Dispatch(
- aRes,
- &GonkSensorsRegistryResultHandler::RegisterModule,
- UnpackPDUInitOp(aPDU));
-}
-
-void
-GonkSensorsRegistryModule::UnregisterModuleRsp(
- const DaemonSocketPDUHeader& aHeader, DaemonSocketPDU& aPDU,
- GonkSensorsRegistryResultHandler* aRes)
-{
- ResultRunnable::Dispatch(
- aRes,
- &GonkSensorsRegistryResultHandler::UnregisterModule,
- UnpackPDUInitOp(aPDU));
-}
-
-//
-// GonkSensorsRegistryInterface
-//
-
-GonkSensorsRegistryInterface::GonkSensorsRegistryInterface(
- GonkSensorsRegistryModule* aModule)
- : mModule(aModule)
-{ }
-
-GonkSensorsRegistryInterface::~GonkSensorsRegistryInterface()
-{ }
-
-void
-GonkSensorsRegistryInterface::RegisterModule(
- uint8_t aId, GonkSensorsRegistryResultHandler* aRes)
-{
- MOZ_ASSERT(mModule);
-
- nsresult rv = mModule->RegisterModuleCmd(aId, aRes);
- if (NS_FAILED(rv)) {
- DispatchError(aRes, rv);
- }
-}
-
-void
-GonkSensorsRegistryInterface::UnregisterModule(
- uint8_t aId, GonkSensorsRegistryResultHandler* aRes)
-{
- MOZ_ASSERT(mModule);
-
- nsresult rv = mModule->UnregisterModuleCmd(aId, aRes);
- if (NS_FAILED(rv)) {
- DispatchError(aRes, rv);
- }
-}
-
-void
-GonkSensorsRegistryInterface::DispatchError(
- GonkSensorsRegistryResultHandler* aRes, SensorsError aError)
-{
- DaemonResultRunnable1<GonkSensorsRegistryResultHandler, void,
- SensorsError, SensorsError>::Dispatch(
- aRes, &GonkSensorsRegistryResultHandler::OnError,
- ConstantInitOp1<SensorsError>(aError));
-}
-
-void
-GonkSensorsRegistryInterface::DispatchError(
- GonkSensorsRegistryResultHandler* aRes, nsresult aRv)
-{
- SensorsError error;
-
- if (NS_FAILED(Convert(aRv, error))) {
- error = SENSORS_ERROR_FAIL;
- }
- DispatchError(aRes, error);
-}
-
-} // namespace hal
-} // namespace mozilla
diff --git a/hal/gonk/GonkSensorsRegistryInterface.h b/hal/gonk/GonkSensorsRegistryInterface.h
deleted file mode 100644
index a9d98d653..000000000
--- a/hal/gonk/GonkSensorsRegistryInterface.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/* -*- 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/. */
-
-/*
- * The registry interface gives yo access to the Sensors daemon's Registry
- * service. The purpose of the service is to register and setup all other
- * services, and make them available.
- *
- * All public methods and callback methods run on the main thread.
- */
-
-#ifndef hal_gonk_GonkSensorsRegistryInterface_h
-#define hal_gonk_GonkSensorsRegistryInterface_h
-
-#include <mozilla/ipc/DaemonRunnables.h>
-#include <mozilla/ipc/DaemonSocketMessageHandlers.h>
-#include "SensorsTypes.h"
-
-namespace mozilla {
-namespace ipc {
-
-class DaemonSocketPDU;
-class DaemonSocketPDUHeader;
-
-}
-}
-
-namespace mozilla {
-namespace hal {
-
-class SensorsInterface;
-
-using mozilla::ipc::DaemonSocketPDU;
-using mozilla::ipc::DaemonSocketPDUHeader;
-using mozilla::ipc::DaemonSocketResultHandler;
-
-/**
- * This class is the result-handler interface for the Sensors
- * Registry interface. Methods always run on the main thread.
- */
-class GonkSensorsRegistryResultHandler : public DaemonSocketResultHandler
-{
-public:
-
- /**
- * Called if a registry command failed.
- *
- * @param aError The error code.
- */
- virtual void OnError(SensorsError aError);
-
- /**
- * The callback method for |GonkSensorsRegistryInterface::RegisterModule|.
- *
- * @param aProtocolVersion The daemon's protocol version. Make sure it's
- * compatible with Gecko's implementation.
- */
- virtual void RegisterModule(uint32_t aProtocolVersion);
-
- /**
- * The callback method for |SensorsRegsitryInterface::UnregisterModule|.
- */
- virtual void UnregisterModule();
-
-protected:
- virtual ~GonkSensorsRegistryResultHandler();
-};
-
-/**
- * This is the module class for the Sensors registry component. It handles
- * PDU packing and unpacking. Methods are either executed on the main thread
- * or the I/O thread.
- *
- * This is an internal class, use |GonkSensorsRegistryInterface| instead.
- */
-class GonkSensorsRegistryModule
-{
-public:
- enum {
- SERVICE_ID = 0x00
- };
-
- enum {
- OPCODE_ERROR = 0x00,
- OPCODE_REGISTER_MODULE = 0x01,
- OPCODE_UNREGISTER_MODULE = 0x02
- };
-
- virtual nsresult Send(DaemonSocketPDU* aPDU,
- DaemonSocketResultHandler* aRes) = 0;
-
- //
- // Commands
- //
-
- nsresult RegisterModuleCmd(uint8_t aId,
- GonkSensorsRegistryResultHandler* aRes);
-
- nsresult UnregisterModuleCmd(uint8_t aId,
- GonkSensorsRegistryResultHandler* aRes);
-
-protected:
- virtual ~GonkSensorsRegistryModule();
-
- void HandleSvc(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU, DaemonSocketResultHandler* aRes);
-
- //
- // Responses
- //
-
- typedef mozilla::ipc::DaemonResultRunnable0<
- GonkSensorsRegistryResultHandler, void>
- ResultRunnable;
-
- typedef mozilla::ipc::DaemonResultRunnable1<
- GonkSensorsRegistryResultHandler, void, uint32_t, uint32_t>
- Uint32ResultRunnable;
-
- typedef mozilla::ipc::DaemonResultRunnable1<
- GonkSensorsRegistryResultHandler, void, SensorsError, SensorsError>
- ErrorRunnable;
-
- void ErrorRsp(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- GonkSensorsRegistryResultHandler* aRes);
-
- void RegisterModuleRsp(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- GonkSensorsRegistryResultHandler* aRes);
-
- void UnregisterModuleRsp(const DaemonSocketPDUHeader& aHeader,
- DaemonSocketPDU& aPDU,
- GonkSensorsRegistryResultHandler* aRes);
-};
-
-/**
- * This class implements the public interface to the Sensors Registry
- * component. Use |SensorsInterface::GetRegistryInterface| to retrieve
- * an instance. All methods run on the main thread.
- */
-class GonkSensorsRegistryInterface final
-{
-public:
- GonkSensorsRegistryInterface(GonkSensorsRegistryModule* aModule);
- ~GonkSensorsRegistryInterface();
-
- /**
- * Sends a RegisterModule command to the Sensors daemon. When the
- * result handler's |RegisterModule| method gets called, the service
- * has been registered successfully and can be used.
- *
- * @param aId The id of the service that is to be registered.
- * @param aRes The result handler.
- */
- void RegisterModule(uint8_t aId, GonkSensorsRegistryResultHandler* aRes);
-
- /**
- * Sends an UnregisterModule command to the Sensors daemon. The service
- * should not be used afterwards until it has been registered again.
- *
- * @param aId The id of the service that is to be unregistered.
- * @param aRes The result handler.
- */
- void UnregisterModule(uint8_t aId, GonkSensorsRegistryResultHandler* aRes);
-
-private:
- void DispatchError(GonkSensorsRegistryResultHandler* aRes,
- SensorsError aError);
- void DispatchError(GonkSensorsRegistryResultHandler* aRes,
- nsresult aRv);
-
- GonkSensorsRegistryModule* mModule;
-};
-
-} // namespace hal
-} // namespace mozilla
-
-#endif // hal_gonk_GonkSensorsRegistryInterface_h
diff --git a/hal/gonk/GonkSwitch.cpp b/hal/gonk/GonkSwitch.cpp
deleted file mode 100644
index b2c31c973..000000000
--- a/hal/gonk/GonkSwitch.cpp
+++ /dev/null
@@ -1,479 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <fcntl.h>
-#include <sysutils/NetlinkEvent.h>
-
-#include "base/message_loop.h"
-#include "base/task.h"
-
-#include "Hal.h"
-#include "HalLog.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/RefPtr.h"
-#include "mozilla/Monitor.h"
-#include "nsPrintfCString.h"
-#include "nsXULAppAPI.h"
-#include "nsThreadUtils.h"
-#include "UeventPoller.h"
-
-using namespace mozilla::hal;
-
-#define SWITCH_HEADSET_DEVPATH "/devices/virtual/switch/h2w"
-#define SWITCH_USB_DEVPATH_GB "/devices/virtual/switch/usb_configuration"
-#define SWITCH_USB_DEVPATH_ICS "/devices/virtual/android_usb/android0"
-
-namespace mozilla {
-namespace hal_impl {
-/**
- * The uevent for a usb on GB insertion looks like:
- *
- * change@/devices/virtual/switch/usb_configuration
- * ACTION=change
- * DEVPATH=/devices/virtual/switch/usb_configuration
- * SUBSYSTEM=switch
- * SWITCH_NAME=usb_configuration
- * SWITCH_STATE=0
- * SEQNUM=5038
- */
-class SwitchHandler
-{
-public:
- NS_INLINE_DECL_REFCOUNTING(SwitchHandler)
-
- SwitchHandler(const char* aDevPath, SwitchDevice aDevice)
- : mDevPath(aDevPath),
- mState(SWITCH_STATE_UNKNOWN),
- mDevice(aDevice)
- {
- GetInitialState();
- }
-
- bool CheckEvent(NetlinkEvent* aEvent)
- {
- if (strcmp(GetSubsystem(), aEvent->getSubsystem()) ||
- strcmp(mDevPath, aEvent->findParam("DEVPATH"))) {
- return false;
- }
-
- mState = ConvertState(GetStateString(aEvent));
- return mState != SWITCH_STATE_UNKNOWN;
- }
-
- SwitchState GetState()
- {
- return mState;
- }
-
- SwitchDevice GetType()
- {
- return mDevice;
- }
-protected:
- virtual ~SwitchHandler()
- {
- }
-
- virtual const char* GetSubsystem()
- {
- return "switch";
- }
-
- virtual const char* GetStateString(NetlinkEvent* aEvent)
- {
- return aEvent->findParam("SWITCH_STATE");
- }
-
- void GetInitialState()
- {
- nsPrintfCString statePath("/sys%s/state", mDevPath);
- int fd = open(statePath.get(), O_RDONLY);
- if (fd <= 0) {
- return;
- }
-
- ScopedClose autoClose(fd);
- char state[16];
- ssize_t bytesRead = read(fd, state, sizeof(state));
- if (bytesRead < 0) {
- HAL_ERR("Read data from %s fails", statePath.get());
- return;
- }
-
- if (state[bytesRead - 1] == '\n') {
- bytesRead--;
- }
-
- state[bytesRead] = '\0';
- mState = ConvertState(state);
- }
-
- virtual SwitchState ConvertState(const char* aState)
- {
- MOZ_ASSERT(aState);
- return aState[0] == '0' ? SWITCH_STATE_OFF : SWITCH_STATE_ON;
- }
-
- const char* mDevPath;
- SwitchState mState;
- SwitchDevice mDevice;
-};
-
-/**
- * The uevent delivered for the USB configuration under ICS looks like,
- *
- * change@/devices/virtual/android_usb/android0
- * ACTION=change
- * DEVPATH=/devices/virtual/android_usb/android0
- * SUBSYSTEM=android_usb
- * USB_STATE=CONFIGURED
- * SEQNUM=1802
- */
-class SwitchHandlerUsbIcs: public SwitchHandler
-{
-public:
- SwitchHandlerUsbIcs(const char* aDevPath) : SwitchHandler(aDevPath, SWITCH_USB)
- {
- SwitchHandler::GetInitialState();
- }
-
- virtual ~SwitchHandlerUsbIcs() { }
-
-protected:
- virtual const char* GetSubsystem()
- {
- return "android_usb";
- }
-
- virtual const char* GetStateString(NetlinkEvent* aEvent)
- {
- return aEvent->findParam("USB_STATE");
- }
-
- SwitchState ConvertState(const char* aState)
- {
- MOZ_ASSERT(aState);
- return strcmp(aState, "CONFIGURED") == 0 ? SWITCH_STATE_ON : SWITCH_STATE_OFF;
- }
-};
-
-/**
- * The uevent delivered for the headset under ICS looks like,
- *
- * change@/devices/virtual/switch/h2w
- * ACTION=change
- * DEVPATH=/devices/virtual/switch/h2w
- * SUBSYSTEM=switch
- * SWITCH_NAME=h2w
- * SWITCH_STATE=2 // Headset with no mic
- * SEQNUM=2581
- * On Otoro, SWITCH_NAME could be Headset/No Device when plug/unplug.
- * change@/devices/virtual/switch/h2w
- * ACTION=change
- * DEVPATH=/devices/virtual/switch/h2w
- * SUBSYSTEM=switch
- * SWITCH_NAME=Headset
- * SWITCH_STATE=1 // Headset with mic
- * SEQNUM=1602
- */
-class SwitchHandlerHeadphone: public SwitchHandler
-{
-public:
- SwitchHandlerHeadphone(const char* aDevPath) :
- SwitchHandler(aDevPath, SWITCH_HEADPHONES)
- {
- SwitchHandler::GetInitialState();
- }
-
- virtual ~SwitchHandlerHeadphone() { }
-
-protected:
- SwitchState ConvertState(const char* aState)
- {
- MOZ_ASSERT(aState);
-
- return aState[0] == '0' ? SWITCH_STATE_OFF :
- (aState[0] == '1' ? SWITCH_STATE_HEADSET : SWITCH_STATE_HEADPHONE);
- }
-};
-
-
-typedef nsTArray<RefPtr<SwitchHandler> > SwitchHandlerArray;
-
-class SwitchEventRunnable : public Runnable
-{
-public:
- SwitchEventRunnable(SwitchEvent& aEvent) : mEvent(aEvent)
- {
- }
-
- NS_IMETHOD Run() override
- {
- NotifySwitchChange(mEvent);
- return NS_OK;
- }
-private:
- SwitchEvent mEvent;
-};
-
-class SwitchEventObserver final : public IUeventObserver
-{
- ~SwitchEventObserver()
- {
- mHandler.Clear();
- }
-
-public:
- NS_INLINE_DECL_REFCOUNTING(SwitchEventObserver)
- SwitchEventObserver()
- : mEnableCount(0),
- mHeadphonesFromInputDev(false)
- {
- Init();
- }
-
- int GetEnableCount()
- {
- return mEnableCount;
- }
-
- void EnableSwitch(SwitchDevice aDevice)
- {
- mEventInfo[aDevice].mEnabled = true;
- mEnableCount++;
- }
-
- void DisableSwitch(SwitchDevice aDevice)
- {
- mEventInfo[aDevice].mEnabled = false;
- mEnableCount--;
- }
-
- void Notify(const NetlinkEvent& aEvent)
- {
- SwitchState currState;
-
- SwitchDevice device = GetEventInfo(aEvent, currState);
- if (device == SWITCH_DEVICE_UNKNOWN) {
- return;
- }
-
- EventInfo& info = mEventInfo[device];
- if (currState == info.mEvent.status()) {
- return;
- }
-
- info.mEvent.status() = currState;
-
- if (info.mEnabled) {
- NS_DispatchToMainThread(new SwitchEventRunnable(info.mEvent));
- }
- }
-
- void Notify(SwitchDevice aDevice, SwitchState aState)
- {
- EventInfo& info = mEventInfo[aDevice];
- if (aState == info.mEvent.status()) {
- return;
- }
-
- info.mEvent.status() = aState;
-
- if (info.mEnabled) {
- NS_DispatchToMainThread(new SwitchEventRunnable(info.mEvent));
- }
- }
-
- SwitchState GetCurrentInformation(SwitchDevice aDevice)
- {
- return mEventInfo[aDevice].mEvent.status();
- }
-
- void NotifyAnEvent(SwitchDevice aDevice)
- {
- EventInfo& info = mEventInfo[aDevice];
- if (info.mEvent.status() != SWITCH_STATE_UNKNOWN) {
- NS_DispatchToMainThread(new SwitchEventRunnable(info.mEvent));
- }
- }
-
- bool GetHeadphonesFromInputDev()
- {
- return mHeadphonesFromInputDev;
- }
-
-private:
- class EventInfo
- {
- public:
- EventInfo() : mEnabled(false)
- {
- mEvent.status() = SWITCH_STATE_UNKNOWN;
- mEvent.device() = SWITCH_DEVICE_UNKNOWN;
- }
- SwitchEvent mEvent;
- bool mEnabled;
- };
-
- EventInfo mEventInfo[NUM_SWITCH_DEVICE];
- size_t mEnableCount;
- SwitchHandlerArray mHandler;
- bool mHeadphonesFromInputDev;
-
- // This function might also get called on the main thread
- // (from IsHeadphoneEventFromInputDev)
- void Init()
- {
- RefPtr<SwitchHandlerHeadphone> switchHeadPhone =
- new SwitchHandlerHeadphone(SWITCH_HEADSET_DEVPATH);
-
- // If the initial state is unknown, it means the headphone event is from input dev
- mHeadphonesFromInputDev = switchHeadPhone->GetState() == SWITCH_STATE_UNKNOWN ? true : false;
-
- if (!mHeadphonesFromInputDev) {
- mHandler.AppendElement(switchHeadPhone);
- } else {
- // If headphone status will be notified from input dev then initialize
- // status to "off" and wait for event notification.
- mEventInfo[SWITCH_HEADPHONES].mEvent.device() = SWITCH_HEADPHONES;
- mEventInfo[SWITCH_HEADPHONES].mEvent.status() = SWITCH_STATE_OFF;
- }
- mHandler.AppendElement(new SwitchHandler(SWITCH_USB_DEVPATH_GB, SWITCH_USB));
- mHandler.AppendElement(new SwitchHandlerUsbIcs(SWITCH_USB_DEVPATH_ICS));
-
- SwitchHandlerArray::index_type handlerIndex;
- SwitchHandlerArray::size_type numHandlers = mHandler.Length();
-
- for (handlerIndex = 0; handlerIndex < numHandlers; handlerIndex++) {
- SwitchState state = mHandler[handlerIndex]->GetState();
- if (state == SWITCH_STATE_UNKNOWN) {
- continue;
- }
-
- SwitchDevice device = mHandler[handlerIndex]->GetType();
- mEventInfo[device].mEvent.device() = device;
- mEventInfo[device].mEvent.status() = state;
- }
- }
-
- SwitchDevice GetEventInfo(const NetlinkEvent& aEvent, SwitchState& aState)
- {
- //working around the android code not being const-correct
- NetlinkEvent *e = const_cast<NetlinkEvent*>(&aEvent);
-
- for (size_t i = 0; i < mHandler.Length(); i++) {
- if (mHandler[i]->CheckEvent(e)) {
- aState = mHandler[i]->GetState();
- return mHandler[i]->GetType();
- }
- }
- return SWITCH_DEVICE_UNKNOWN;
- }
-};
-
-static RefPtr<SwitchEventObserver> sSwitchObserver;
-
-static void
-InitializeResourceIfNeed()
-{
- if (!sSwitchObserver) {
- sSwitchObserver = new SwitchEventObserver();
- RegisterUeventListener(sSwitchObserver);
- }
-}
-
-static void
-ReleaseResourceIfNeed()
-{
- if (sSwitchObserver->GetEnableCount() == 0) {
- UnregisterUeventListener(sSwitchObserver);
- sSwitchObserver = nullptr;
- }
-}
-
-static void
-EnableSwitchNotificationsIOThread(SwitchDevice aDevice, Monitor *aMonitor)
-{
- InitializeResourceIfNeed();
- sSwitchObserver->EnableSwitch(aDevice);
- {
- MonitorAutoLock lock(*aMonitor);
- lock.Notify();
- }
-
- // Notify the latest state if IO thread has the information.
- if (sSwitchObserver->GetEnableCount() > 1) {
- sSwitchObserver->NotifyAnEvent(aDevice);
- }
-}
-
-void
-EnableSwitchNotifications(SwitchDevice aDevice)
-{
- Monitor monitor("EnableSwitch.monitor");
- {
- MonitorAutoLock lock(monitor);
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(EnableSwitchNotificationsIOThread, aDevice, &monitor));
- lock.Wait();
- }
-}
-
-static void
-DisableSwitchNotificationsIOThread(SwitchDevice aDevice)
-{
- MOZ_ASSERT(sSwitchObserver->GetEnableCount());
- sSwitchObserver->DisableSwitch(aDevice);
- ReleaseResourceIfNeed();
-}
-
-void
-DisableSwitchNotifications(SwitchDevice aDevice)
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(DisableSwitchNotificationsIOThread, aDevice));
-}
-
-SwitchState
-GetCurrentSwitchState(SwitchDevice aDevice)
-{
- MOZ_ASSERT(sSwitchObserver && sSwitchObserver->GetEnableCount());
- return sSwitchObserver->GetCurrentInformation(aDevice);
-}
-
-static void
-NotifySwitchStateIOThread(SwitchDevice aDevice, SwitchState aState)
-{
- InitializeResourceIfNeed();
- sSwitchObserver->Notify(aDevice, aState);
-}
-
-void NotifySwitchStateFromInputDevice(SwitchDevice aDevice, SwitchState aState)
-{
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(NotifySwitchStateIOThread, aDevice, aState));
-}
-
-bool IsHeadphoneEventFromInputDev()
-{
- // Instead of calling InitializeResourceIfNeed, create new SwitchEventObserver
- // to prevent calling RegisterUeventListener in main thread.
- RefPtr<SwitchEventObserver> switchObserver = new SwitchEventObserver();
- return switchObserver->GetHeadphonesFromInputDev();
-}
-
-} // hal_impl
-} //mozilla
diff --git a/hal/gonk/SensorsTypes.h b/hal/gonk/SensorsTypes.h
deleted file mode 100644
index 35c852f5a..000000000
--- a/hal/gonk/SensorsTypes.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/* -*- 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 hal_gonk_SensorsTypes_h
-#define hal_gonk_SensorsTypes_h
-
-namespace mozilla {
-namespace hal {
-
-enum SensorsDeliveryMode {
- SENSORS_DELIVERY_MODE_BEST_EFFORT,
- SENSORS_DELIVERY_MODE_IMMEDIATE
-};
-
-enum SensorsError {
- SENSORS_ERROR_NONE,
- SENSORS_ERROR_FAIL,
- SENSORS_ERROR_NOT_READY,
- SENSORS_ERROR_NOMEM,
- SENSORS_ERROR_BUSY,
- SENSORS_ERROR_DONE,
- SENSORS_ERROR_UNSUPPORTED,
- SENSORS_ERROR_PARM_INVALID
-};
-
-enum SensorsStatus {
- SENSORS_STATUS_NO_CONTACT,
- SENSORS_STATUS_UNRELIABLE,
- SENSORS_STATUS_ACCURACY_LOW,
- SENSORS_STATUS_ACCURACY_MEDIUM,
- SENSORS_STATUS_ACCURACY_HIGH
-};
-
-enum SensorsTriggerMode {
- SENSORS_TRIGGER_MODE_CONTINUOUS,
- SENSORS_TRIGGER_MODE_ON_CHANGE,
- SENSORS_TRIGGER_MODE_ONE_SHOT,
- SENSORS_TRIGGER_MODE_SPECIAL
-};
-
-enum SensorsType {
- SENSORS_TYPE_ACCELEROMETER,
- SENSORS_TYPE_GEOMAGNETIC_FIELD,
- SENSORS_TYPE_ORIENTATION,
- SENSORS_TYPE_GYROSCOPE,
- SENSORS_TYPE_LIGHT,
- SENSORS_TYPE_PRESSURE,
- SENSORS_TYPE_TEMPERATURE,
- SENSORS_TYPE_PROXIMITY,
- SENSORS_TYPE_GRAVITY,
- SENSORS_TYPE_LINEAR_ACCELERATION,
- SENSORS_TYPE_ROTATION_VECTOR,
- SENSORS_TYPE_RELATIVE_HUMIDITY,
- SENSORS_TYPE_AMBIENT_TEMPERATURE,
- SENSORS_TYPE_MAGNETIC_FIELD_UNCALIBRATED,
- SENSORS_TYPE_GAME_ROTATION_VECTOR,
- SENSORS_TYPE_GYROSCOPE_UNCALIBRATED,
- SENSORS_TYPE_SIGNIFICANT_MOTION,
- SENSORS_TYPE_STEP_DETECTED,
- SENSORS_TYPE_STEP_COUNTER,
- SENSORS_TYPE_GEOMAGNETIC_ROTATION_VECTOR,
- SENSORS_TYPE_HEART_RATE,
- SENSORS_TYPE_TILT_DETECTOR,
- SENSORS_TYPE_WAKE_GESTURE,
- SENSORS_TYPE_GLANCE_GESTURE,
- SENSORS_TYPE_PICK_UP_GESTURE,
- SENSORS_TYPE_WRIST_TILT_GESTURE,
- SENSORS_NUM_TYPES
-};
-
-struct SensorsEvent {
- SensorsType mType;
- SensorsStatus mStatus;
- SensorsDeliveryMode mDeliveryMode;
- int64_t mTimestamp;
- union {
- float mFloat[6];
- uint64_t mUint[1];
- } mData;
-};
-
-/**
- * |SensorsSensor| represents a device sensor; either single or composite.
- */
-struct SensorsSensor {
- SensorsSensor(int32_t aId, SensorsType aType,
- float aRange, float aResolution,
- float aPower, int32_t aMinPeriod,
- int32_t aMaxPeriod,
- SensorsTriggerMode aTriggerMode,
- SensorsDeliveryMode aDeliveryMode)
- : mId(aId)
- , mType(aType)
- , mRange(aRange)
- , mResolution(aResolution)
- , mPower(aPower)
- , mMinPeriod(aMinPeriod)
- , mMaxPeriod(aMaxPeriod)
- , mTriggerMode(aTriggerMode)
- , mDeliveryMode(aDeliveryMode)
- { }
-
- int32_t mId;
- SensorsType mType;
- float mRange;
- float mResolution;
- float mPower;
- int32_t mMinPeriod;
- int32_t mMaxPeriod;
- SensorsTriggerMode mTriggerMode;
- SensorsDeliveryMode mDeliveryMode;
-};
-
-/**
- * |SensorClass| represents the status of a specific sensor type.
- */
-struct SensorsSensorClass {
- SensorsSensorClass()
- : mActivated(0)
- , mMinValue(0)
- , mMaxValue(0)
- { }
-
- void UpdateFromSensor(const SensorsSensor& aSensor)
- {
- mMaxValue = std::max(aSensor.mRange, mMaxValue);
- }
-
- uint32_t mActivated;
- float mMinValue;
- float mMaxValue;
-};
-
-} // namespace hal
-} // namespace mozilla
-
-#endif // hal_gonk_SensorsTypes_h
diff --git a/hal/gonk/SystemService.cpp b/hal/gonk/SystemService.cpp
deleted file mode 100644
index 2b98f5fdd..000000000
--- a/hal/gonk/SystemService.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/* -*- 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/. */
-
-#include "Hal.h"
-
-#include <cutils/properties.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "HalLog.h"
-#include "nsITimer.h"
-#include "mozilla/Unused.h"
-
-namespace mozilla {
-namespace hal_impl {
-
-static const int sRetryInterval = 100; // ms
-
-bool
-SystemServiceIsRunning(const char* aSvcName)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- char key[PROPERTY_KEY_MAX];
- auto res = snprintf(key, sizeof(key), "init.svc.%s", aSvcName);
-
- if (res < 0) {
- HAL_ERR("snprintf: %s", strerror(errno));
- return false;
- } else if (static_cast<size_t>(res) >= sizeof(key)) {
- HAL_ERR("snprintf: trunctated service name %s", aSvcName);
- return false;
- }
-
- char value[PROPERTY_VALUE_MAX];
- Unused << NS_WARN_IF(property_get(key, value, "") < 0);
-
- return !strcmp(value, "running");
-}
-
-class StartSystemServiceTimerCallback final : public nsITimerCallback
-{
- NS_DECL_THREADSAFE_ISUPPORTS;
-
-public:
- StartSystemServiceTimerCallback(const char* aSvcName, const char* aArgs)
- : mSvcName(aSvcName)
- , mArgs(aArgs)
- {
- MOZ_COUNT_CTOR_INHERITED(StartSystemServiceTimerCallback,
- nsITimerCallback);
- }
-
- NS_IMETHOD Notify(nsITimer* aTimer) override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- return StartSystemService(mSvcName.get(), mArgs.get());
- }
-
-protected:
- ~StartSystemServiceTimerCallback()
- {
- MOZ_COUNT_DTOR_INHERITED(StartSystemServiceTimerCallback,
- nsITimerCallback);
- }
-
-private:
- nsCString mSvcName;
- nsCString mArgs;
-};
-
-NS_IMPL_ISUPPORTS0(StartSystemServiceTimerCallback);
-
-nsresult
-StartSystemService(const char* aSvcName, const char* aArgs)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- char value[PROPERTY_VALUE_MAX];
- auto res = snprintf(value, sizeof(value), "%s:%s", aSvcName, aArgs);
-
- if (res < 0) {
- HAL_ERR("snprintf: %s", strerror(errno));
- return NS_ERROR_FAILURE;
- } else if (static_cast<size_t>(res) >= sizeof(value)) {
- HAL_ERR("snprintf: trunctated service name %s", aSvcName);
- return NS_ERROR_OUT_OF_MEMORY;
- }
-
- if (NS_WARN_IF(property_set("ctl.start", value) < 0)) {
- return NS_ERROR_FAILURE;
- }
-
- /* If the system service is not running, re-try later to start it.
- *
- * This condition happens when we restart a service immediately
- * after it crashed, as the service state remains 'stopping'
- * instead of 'stopped'. Due to the limitation of property service,
- * hereby add delay. See Bug 1143925 Comment 41.
- */
- if (!SystemServiceIsRunning(aSvcName)) {
- nsCOMPtr<nsITimer> timer = do_CreateInstance("@mozilla.org/timer;1");
- if (!timer) {
- return NS_ERROR_FAILURE;
- }
-
- RefPtr<StartSystemServiceTimerCallback> timerCallback =
- new StartSystemServiceTimerCallback(aSvcName, aArgs);
-
- timer->InitWithCallback(timerCallback,
- sRetryInterval,
- nsITimer::TYPE_ONE_SHOT);
- }
-
- return NS_OK;
-}
-
-void
-StopSystemService(const char* aSvcName)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- Unused << NS_WARN_IF(property_set("ctl.stop", aSvcName));
-}
-
-} // namespace hal_impl
-} // namespace mozilla
diff --git a/hal/gonk/UeventPoller.cpp b/hal/gonk/UeventPoller.cpp
deleted file mode 100644
index 3fbe850ed..000000000
--- a/hal/gonk/UeventPoller.cpp
+++ /dev/null
@@ -1,312 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <signal.h>
-#include <string.h>
-#include <strings.h>
-#include <unistd.h>
-
-#include <arpa/inet.h>
-#include <linux/types.h>
-#include <linux/netlink.h>
-#include <netinet/in.h>
-#include <sys/socket.h>
-
-#include "HalLog.h"
-#include "nsDebug.h"
-#include "base/message_loop.h"
-#include "base/task.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/Monitor.h"
-#include "nsThreadUtils.h"
-#include "nsXULAppAPI.h"
-
-#include "UeventPoller.h"
-
-using namespace mozilla;
-
-namespace mozilla {
-namespace hal_impl {
-
-static void ShutdownUevent();
-
-class NetlinkPoller : public MessageLoopForIO::Watcher
-{
-public:
- NetlinkPoller() : mSocket(-1),
- mIOLoop(MessageLoopForIO::current())
- {
- }
-
- virtual ~NetlinkPoller() {}
-
- bool OpenSocket();
-
- virtual void OnFileCanReadWithoutBlocking(int fd);
-
- // no writing to the netlink socket
- virtual void OnFileCanWriteWithoutBlocking(int fd)
- {
- MOZ_CRASH("Must not write to netlink socket");
- }
-
- MessageLoopForIO *GetIOLoop () const { return mIOLoop; }
- void RegisterObserver(IUeventObserver *aObserver)
- {
- mUeventObserverList.AddObserver(aObserver);
- }
-
- void UnregisterObserver(IUeventObserver *aObserver)
- {
- mUeventObserverList.RemoveObserver(aObserver);
- if (mUeventObserverList.Length() == 0) {
- ShutdownUevent(); // this will destroy self
- }
- }
-
-private:
- ScopedClose mSocket;
- MessageLoopForIO* mIOLoop;
- MessageLoopForIO::FileDescriptorWatcher mReadWatcher;
-
- const static int kBuffsize = 64 * 1024;
- uint8_t mBuffer [kBuffsize];
-
- typedef ObserverList<NetlinkEvent> UeventObserverList;
- UeventObserverList mUeventObserverList;
-};
-
-bool
-NetlinkPoller::OpenSocket()
-{
- mSocket.rwget() = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
- if (mSocket.get() < 0) {
- return false;
- }
-
- int sz = kBuffsize;
-
- if (setsockopt(mSocket.get(), SOL_SOCKET, SO_RCVBUFFORCE, &sz,
- sizeof(sz)) < 0) {
- return false;
- }
-
- // add FD_CLOEXEC flag
- int flags = fcntl(mSocket.get(), F_GETFD);
- if (flags == -1) {
- return false;
- }
- flags |= FD_CLOEXEC;
- if (fcntl(mSocket.get(), F_SETFD, flags) == -1) {
- return false;
- }
-
- // set non-blocking
- if (fcntl(mSocket.get(), F_SETFL, O_NONBLOCK) == -1) {
- return false;
- }
-
- struct sockaddr_nl saddr;
- bzero(&saddr, sizeof(saddr));
- saddr.nl_family = AF_NETLINK;
- saddr.nl_groups = 1;
- saddr.nl_pid = gettid();
-
- do {
- if (bind(mSocket.get(), (struct sockaddr *)&saddr, sizeof(saddr)) == 0) {
- break;
- }
-
- if (errno != EADDRINUSE) {
- return false;
- }
-
- if (saddr.nl_pid == 0) {
- return false;
- }
-
- // Once there was any other place in the same process assigning saddr.nl_pid by
- // gettid(), we can detect it and print warning message.
- HAL_LOG("The netlink socket address saddr.nl_pid=%u is in use. "
- "Let the kernel re-assign.\n", saddr.nl_pid);
- saddr.nl_pid = 0;
- } while (true);
-
- if (!mIOLoop->WatchFileDescriptor(mSocket.get(),
- true,
- MessageLoopForIO::WATCH_READ,
- &mReadWatcher,
- this)) {
- return false;
- }
-
- return true;
-}
-
-static StaticAutoPtr<NetlinkPoller> sPoller;
-
-class UeventInitTask : public Runnable
-{
- NS_IMETHOD Run() override
- {
- if (!sPoller) {
- return NS_OK;
- }
- if (sPoller->OpenSocket()) {
- return NS_OK;
- }
- sPoller->GetIOLoop()->PostDelayedTask(MakeAndAddRef<UeventInitTask>(),
- 1000);
- return NS_OK;
- }
-};
-
-void
-NetlinkPoller::OnFileCanReadWithoutBlocking(int fd)
-{
- MOZ_ASSERT(fd == mSocket.get());
- while (true) {
- int ret = read(fd, mBuffer, kBuffsize);
- if (ret == -1) {
- if (errno == EAGAIN || errno == EWOULDBLOCK) {
- return;
- }
- if (errno == EINTR) {
- continue;
- }
- }
- if (ret <= 0) {
- // fatal error on netlink socket which should not happen
- _exit(1);
- }
- NetlinkEvent netlinkEvent;
- netlinkEvent.decode(reinterpret_cast<char*>(mBuffer), ret);
- mUeventObserverList.Broadcast(netlinkEvent);
- }
-}
-
-static bool sShutdown = false;
-
-class ShutdownNetlinkPoller;
-static StaticAutoPtr<ShutdownNetlinkPoller> sShutdownPoller;
-static Monitor* sMonitor = nullptr;
-
-class ShutdownNetlinkPoller {
-public:
- ~ShutdownNetlinkPoller()
- {
- // This is called from KillClearOnShutdown() on the main thread.
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(XRE_GetIOMessageLoop());
-
- {
- MonitorAutoLock lock(*sMonitor);
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(ShutdownUeventIOThread));
-
- while (!sShutdown) {
- lock.Wait();
- }
- }
-
- sShutdown = true;
- delete sMonitor;
- }
-
- static void MaybeInit()
- {
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- if (sShutdown || sMonitor) {
- // Don't init twice or init after shutdown.
- return;
- }
-
- sMonitor = new Monitor("ShutdownNetlinkPoller.monitor");
- {
- ShutdownNetlinkPoller* shutdownPoller = new ShutdownNetlinkPoller();
-
- nsCOMPtr<nsIRunnable> runnable = NS_NewRunnableFunction([=] () -> void
- {
- sShutdownPoller = shutdownPoller;
- ClearOnShutdown(&sShutdownPoller); // Must run on the main thread.
- });
- MOZ_ASSERT(runnable);
- MOZ_ALWAYS_SUCCEEDS(
- NS_DispatchToMainThread(runnable, NS_DISPATCH_NORMAL));
- }
- }
-private:
- ShutdownNetlinkPoller() = default;
- static void ShutdownUeventIOThread()
- {
- MonitorAutoLock l(*sMonitor);
- ShutdownUevent(); // Must run on the IO thread.
- sShutdown = true;
- l.NotifyAll();
- }
-};
-
-static void
-InitializeUevent()
-{
- MOZ_ASSERT(!sPoller);
- sPoller = new NetlinkPoller();
- sPoller->GetIOLoop()->PostTask(MakeAndAddRef<UeventInitTask>());
-
- ShutdownNetlinkPoller::MaybeInit();
-}
-
-static void
-ShutdownUevent()
-{
- sPoller = nullptr;
-}
-
-void
-RegisterUeventListener(IUeventObserver *aObserver)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- if (sShutdown) {
- return;
- }
-
- if (!sPoller) {
- InitializeUevent();
- }
- sPoller->RegisterObserver(aObserver);
-}
-
-void
-UnregisterUeventListener(IUeventObserver *aObserver)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- if (sShutdown) {
- return;
- }
-
- sPoller->UnregisterObserver(aObserver);
-}
-
-} // hal_impl
-} // mozilla
-
diff --git a/hal/gonk/UeventPoller.h b/hal/gonk/UeventPoller.h
deleted file mode 100644
index ba121cec2..000000000
--- a/hal/gonk/UeventPoller.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _mozilla_uevent_poller_h_
-#define _mozilla_uevent_poller_h_
-
-#include <sysutils/NetlinkEvent.h>
-#include "mozilla/Observer.h"
-
-class NetlinkEvent;
-
-namespace mozilla {
-namespace hal_impl {
-
-typedef mozilla::Observer<NetlinkEvent> IUeventObserver;
-
-/**
- * Register for uevent notification. Note that the method should run on the
- * <b> IO Thread </b>
- * @aObserver the observer to be added. The observer's Notify() is only called
- * on the <b> IO Thread </b>
- */
-void RegisterUeventListener(IUeventObserver *aObserver);
-
-/**
- * Unregister for uevent notification. Note that the method should run on the
- * <b> IO Thread </b>
- * @aObserver the observer to be removed
- */
-void UnregisterUeventListener(IUeventObserver *aObserver);
-
-}
-}
-
-#endif
-
diff --git a/hal/gonk/fanotify.h b/hal/gonk/fanotify.h
deleted file mode 100644
index e715d3bf9..000000000
--- a/hal/gonk/fanotify.h
+++ /dev/null
@@ -1,118 +0,0 @@
-#ifndef _LINUX_FANOTIFY_H
-#define _LINUX_FANOTIFY_H
-
-/* This is a Linux header generated by "make headers_install" */
-
-#include <linux/types.h>
-
-/* the following events that user-space can register for */
-#define FAN_ACCESS 0x00000001 /* File was accessed */
-#define FAN_MODIFY 0x00000002 /* File was modified */
-#define FAN_CLOSE_WRITE 0x00000008 /* Writtable file closed */
-#define FAN_CLOSE_NOWRITE 0x00000010 /* Unwrittable file closed */
-#define FAN_OPEN 0x00000020 /* File was opened */
-
-#define FAN_Q_OVERFLOW 0x00004000 /* Event queued overflowed */
-
-#define FAN_OPEN_PERM 0x00010000 /* File open in perm check */
-#define FAN_ACCESS_PERM 0x00020000 /* File accessed in perm check */
-
-#define FAN_ONDIR 0x40000000 /* event occurred against dir */
-
-#define FAN_EVENT_ON_CHILD 0x08000000 /* interested in child events */
-
-/* helper events */
-#define FAN_CLOSE (FAN_CLOSE_WRITE | FAN_CLOSE_NOWRITE) /* close */
-
-/* flags used for fanotify_init() */
-#define FAN_CLOEXEC 0x00000001
-#define FAN_NONBLOCK 0x00000002
-
-/* These are NOT bitwise flags. Both bits are used togther. */
-#define FAN_CLASS_NOTIF 0x00000000
-#define FAN_CLASS_CONTENT 0x00000004
-#define FAN_CLASS_PRE_CONTENT 0x00000008
-#define FAN_ALL_CLASS_BITS (FAN_CLASS_NOTIF | FAN_CLASS_CONTENT | \
- FAN_CLASS_PRE_CONTENT)
-
-#define FAN_UNLIMITED_QUEUE 0x00000010
-#define FAN_UNLIMITED_MARKS 0x00000020
-
-#define FAN_ALL_INIT_FLAGS (FAN_CLOEXEC | FAN_NONBLOCK | \
- FAN_ALL_CLASS_BITS | FAN_UNLIMITED_QUEUE |\
- FAN_UNLIMITED_MARKS)
-
-/* flags used for fanotify_modify_mark() */
-#define FAN_MARK_ADD 0x00000001
-#define FAN_MARK_REMOVE 0x00000002
-#define FAN_MARK_DONT_FOLLOW 0x00000004
-#define FAN_MARK_ONLYDIR 0x00000008
-#define FAN_MARK_MOUNT 0x00000010
-#define FAN_MARK_IGNORED_MASK 0x00000020
-#define FAN_MARK_IGNORED_SURV_MODIFY 0x00000040
-#define FAN_MARK_FLUSH 0x00000080
-
-#define FAN_ALL_MARK_FLAGS (FAN_MARK_ADD |\
- FAN_MARK_REMOVE |\
- FAN_MARK_DONT_FOLLOW |\
- FAN_MARK_ONLYDIR |\
- FAN_MARK_MOUNT |\
- FAN_MARK_IGNORED_MASK |\
- FAN_MARK_IGNORED_SURV_MODIFY |\
- FAN_MARK_FLUSH)
-
-/*
- * All of the events - we build the list by hand so that we can add flags in
- * the future and not break backward compatibility. Apps will get only the
- * events that they originally wanted. Be sure to add new events here!
- */
-#define FAN_ALL_EVENTS (FAN_ACCESS |\
- FAN_MODIFY |\
- FAN_CLOSE |\
- FAN_OPEN)
-
-/*
- * All events which require a permission response from userspace
- */
-#define FAN_ALL_PERM_EVENTS (FAN_OPEN_PERM |\
- FAN_ACCESS_PERM)
-
-#define FAN_ALL_OUTGOING_EVENTS (FAN_ALL_EVENTS |\
- FAN_ALL_PERM_EVENTS |\
- FAN_Q_OVERFLOW)
-
-#define FANOTIFY_METADATA_VERSION 3
-
-struct fanotify_event_metadata {
- __u32 event_len;
- __u8 vers;
- __u8 reserved;
- __u16 metadata_len;
- __u64 mask;
- __s32 fd;
- __s32 pid;
-};
-
-struct fanotify_response {
- __s32 fd;
- __u32 response;
-};
-
-/* Legit userspace responses to a _PERM event */
-#define FAN_ALLOW 0x01
-#define FAN_DENY 0x02
-/* No fd set in event */
-#define FAN_NOFD -1
-
-/* Helper functions to deal with fanotify_event_metadata buffers */
-#define FAN_EVENT_METADATA_LEN (sizeof(struct fanotify_event_metadata))
-
-#define FAN_EVENT_NEXT(meta, len) ((len) -= (meta)->event_len, \
- (struct fanotify_event_metadata*)(((char *)(meta)) + \
- (meta)->event_len))
-
-#define FAN_EVENT_OK(meta, len) ((long)(len) >= (long)FAN_EVENT_METADATA_LEN && \
- (long)(meta)->event_len >= (long)FAN_EVENT_METADATA_LEN && \
- (long)(meta)->event_len <= (long)(len))
-
-#endif /* _LINUX_FANOTIFY_H */
diff --git a/hal/gonk/nsIRecoveryService.idl b/hal/gonk/nsIRecoveryService.idl
deleted file mode 100644
index ecbb39c0e..000000000
--- a/hal/gonk/nsIRecoveryService.idl
+++ /dev/null
@@ -1,39 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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(bc24fb33-a0c1-49ca-aa43-05f167e02fb6)]
-interface nsIRecoveryService : nsISupports
-{
- /**
- * Possible values of fotaStatus.result. These should stay in sync with
- * librecovery/librecovery.h
- */
- const long FOTA_UPDATE_UNKNOWN = 0;
- const long FOTA_UPDATE_FAIL = 1;
- const long FOTA_UPDATE_SUCCESS = 2;
-
- /**
- * Uses recovery to wipe the data and cache partitions. If this call is
- * successful, the device should reboot before the function call ever returns.
- *
- * @throws NS_ERROR_FAILURE when rebooting into recovery fails for some reason.
- */
- void factoryReset(in string reason);
-
- /**
- * Use recovery to install an OTA update.zip. If this call is
- * successful, the device should reboot before the function call ever returns.
- *
- * @throws NS_ERROR_FAILURE when rebooting into recovery fails for some reason.
- */
- void installFotaUpdate(in string updatePath);
-
- /**
- * @return The status of the last FOTA update. One of FOTA_UPDATE_UNKNOWN,
- * FOTA_UPDATE_FAIL, FOTA_UPDATE_SUCCESS.
- */
- long getFotaUpdateStatus();
-};
diff --git a/hal/gonk/tavarua.h b/hal/gonk/tavarua.h
deleted file mode 100644
index 4eb3483a8..000000000
--- a/hal/gonk/tavarua.h
+++ /dev/null
@@ -1,484 +0,0 @@
-#ifndef __LINUX_TAVARUA_H
-#define __LINUX_TAVARUA_H
-
-/* This is a Linux header generated by "make headers_install" */
-
-#include <stdint.h>
-#include <linux/ioctl.h>
-#include <linux/videodev2.h>
-
-
-#undef FM_DEBUG
-
-/* constants */
-#define RDS_BLOCKS_NUM (4)
-#define BYTES_PER_BLOCK (3)
-#define MAX_PS_LENGTH (96)
-#define MAX_RT_LENGTH (64)
-
-#define XFRDAT0 (0x20)
-#define XFRDAT1 (0x21)
-#define XFRDAT2 (0x22)
-
-#define INTDET_PEEK_MSB (0x88)
-#define INTDET_PEEK_LSB (0x26)
-
-#define RMSSI_PEEK_MSB (0x88)
-#define RMSSI_PEEK_LSB (0xA8)
-
-#define MPX_DCC_BYPASS_POKE_MSB (0x88)
-#define MPX_DCC_BYPASS_POKE_LSB (0xC0)
-
-#define MPX_DCC_PEEK_MSB_REG1 (0x88)
-#define MPX_DCC_PEEK_LSB_REG1 (0xC2)
-
-#define MPX_DCC_PEEK_MSB_REG2 (0x88)
-#define MPX_DCC_PEEK_LSB_REG2 (0xC3)
-
-#define MPX_DCC_PEEK_MSB_REG3 (0x88)
-#define MPX_DCC_PEEK_LSB_REG3 (0xC4)
-
-#define ON_CHANNEL_TH_MSB (0x0B)
-#define ON_CHANNEL_TH_LSB (0xA8)
-
-#define OFF_CHANNEL_TH_MSB (0x0B)
-#define OFF_CHANNEL_TH_LSB (0xAC)
-
-#define ENF_200Khz (1)
-#define SRCH200KHZ_OFFSET (7)
-#define SRCH_MASK (1 << SRCH200KHZ_OFFSET)
-
-/* Standard buffer size */
-#define STD_BUF_SIZE (128)
-/* Search direction */
-#define SRCH_DIR_UP (0)
-#define SRCH_DIR_DOWN (1)
-
-/* control options */
-#define CTRL_ON (1)
-#define CTRL_OFF (0)
-
-#define US_LOW_BAND (87.5)
-#define US_HIGH_BAND (108)
-
-/* constant for Tx */
-
-#define MASK_PI (0x0000FFFF)
-#define MASK_PI_MSB (0x0000FF00)
-#define MASK_PI_LSB (0x000000FF)
-#define MASK_PTY (0x0000001F)
-#define MASK_TXREPCOUNT (0x0000000F)
-
-#undef FMDBG
-#ifdef FM_DEBUG
- #define FMDBG(fmt, args...) printk(KERN_INFO "tavarua_radio: " fmt, ##args)
-#else
- #define FMDBG(fmt, args...)
-#endif
-
-#undef FMDERR
-#define FMDERR(fmt, args...) printk(KERN_INFO "tavarua_radio: " fmt, ##args)
-
-#undef FMDBG_I2C
-#ifdef FM_DEBUG_I2C
- #define FMDBG_I2C(fmt, args...) printk(KERN_INFO "fm_i2c: " fmt, ##args)
-#else
- #define FMDBG_I2C(fmt, args...)
-#endif
-
-/* function declarations */
-/* FM Core audio paths. */
-#define TAVARUA_AUDIO_OUT_ANALOG_OFF (0)
-#define TAVARUA_AUDIO_OUT_ANALOG_ON (1)
-#define TAVARUA_AUDIO_OUT_DIGITAL_OFF (0)
-#define TAVARUA_AUDIO_OUT_DIGITAL_ON (1)
-
-int tavarua_set_audio_path(int digital_on, int analog_on);
-
-/* defines and enums*/
-
-#define MARIMBA_A0 0x01010013
-#define MARIMBA_2_1 0x02010204
-#define BAHAMA_1_0 0x0302010A
-#define BAHAMA_2_0 0x04020205
-#define WAIT_TIMEOUT 2000
-#define RADIO_INIT_TIME 15
-#define TAVARUA_DELAY 10
-/*
- * The frequency is set in units of 62.5 Hz when using V4L2_TUNER_CAP_LOW,
- * 62.5 kHz otherwise.
- * The tuner is able to have a channel spacing of 50, 100 or 200 kHz.
- * tuner->capability is therefore set to V4L2_TUNER_CAP_LOW
- * The FREQ_MUL is then: 1 MHz / 62.5 Hz = 16000
- */
-#define FREQ_MUL (1000000 / 62.5)
-
-enum v4l2_cid_private_tavarua_t {
- V4L2_CID_PRIVATE_TAVARUA_SRCHMODE = (V4L2_CID_PRIVATE_BASE + 1),
- V4L2_CID_PRIVATE_TAVARUA_SCANDWELL,
- V4L2_CID_PRIVATE_TAVARUA_SRCHON,
- V4L2_CID_PRIVATE_TAVARUA_STATE,
- V4L2_CID_PRIVATE_TAVARUA_TRANSMIT_MODE,
- V4L2_CID_PRIVATE_TAVARUA_RDSGROUP_MASK,
- V4L2_CID_PRIVATE_TAVARUA_REGION,
- V4L2_CID_PRIVATE_TAVARUA_SIGNAL_TH,
- V4L2_CID_PRIVATE_TAVARUA_SRCH_PTY,
- V4L2_CID_PRIVATE_TAVARUA_SRCH_PI,
- V4L2_CID_PRIVATE_TAVARUA_SRCH_CNT,
- V4L2_CID_PRIVATE_TAVARUA_EMPHASIS,
- V4L2_CID_PRIVATE_TAVARUA_RDS_STD,
- V4L2_CID_PRIVATE_TAVARUA_SPACING,
- V4L2_CID_PRIVATE_TAVARUA_RDSON,
- V4L2_CID_PRIVATE_TAVARUA_RDSGROUP_PROC,
- V4L2_CID_PRIVATE_TAVARUA_LP_MODE,
- V4L2_CID_PRIVATE_TAVARUA_ANTENNA,
- V4L2_CID_PRIVATE_TAVARUA_RDSD_BUF,
- V4L2_CID_PRIVATE_TAVARUA_PSALL,
- /*v4l2 Tx controls*/
- V4L2_CID_PRIVATE_TAVARUA_TX_SETPSREPEATCOUNT,
- V4L2_CID_PRIVATE_TAVARUA_STOP_RDS_TX_PS_NAME,
- V4L2_CID_PRIVATE_TAVARUA_STOP_RDS_TX_RT,
- V4L2_CID_PRIVATE_TAVARUA_IOVERC,
- V4L2_CID_PRIVATE_TAVARUA_INTDET,
- V4L2_CID_PRIVATE_TAVARUA_MPX_DCC,
- V4L2_CID_PRIVATE_TAVARUA_AF_JUMP,
- V4L2_CID_PRIVATE_TAVARUA_RSSI_DELTA,
- V4L2_CID_PRIVATE_TAVARUA_HLSI,
-
- /*
- * Here we have IOCTl's that are specific to IRIS
- * (V4L2_CID_PRIVATE_BASE + 0x1E to V4L2_CID_PRIVATE_BASE + 0x28)
- */
- V4L2_CID_PRIVATE_SOFT_MUTE,/* 0x800001E*/
- V4L2_CID_PRIVATE_RIVA_ACCS_ADDR,
- V4L2_CID_PRIVATE_RIVA_ACCS_LEN,
- V4L2_CID_PRIVATE_RIVA_PEEK,
- V4L2_CID_PRIVATE_RIVA_POKE,
- V4L2_CID_PRIVATE_SSBI_ACCS_ADDR,
- V4L2_CID_PRIVATE_SSBI_PEEK,
- V4L2_CID_PRIVATE_SSBI_POKE,
- V4L2_CID_PRIVATE_TX_TONE,
- V4L2_CID_PRIVATE_RDS_GRP_COUNTERS,
- V4L2_CID_PRIVATE_SET_NOTCH_FILTER,/* 0x8000028 */
-
- V4L2_CID_PRIVATE_TAVARUA_SET_AUDIO_PATH,/* 0x8000029 */
- V4L2_CID_PRIVATE_TAVARUA_DO_CALIBRATION,/* 0x800002A : IRIS */
- V4L2_CID_PRIVATE_TAVARUA_SRCH_ALGORITHM,/* 0x800002B */
- V4L2_CID_PRIVATE_IRIS_GET_SINR, /* 0x800002C : IRIS */
- V4L2_CID_PRIVATE_INTF_LOW_THRESHOLD, /* 0x800002D */
- V4L2_CID_PRIVATE_INTF_HIGH_THRESHOLD, /* 0x800002E */
- V4L2_CID_PRIVATE_SINR_THRESHOLD, /* 0x800002F : IRIS */
- V4L2_CID_PRIVATE_SINR_SAMPLES, /* 0x8000030 : IRIS */
-
-};
-
-enum tavarua_buf_t {
- TAVARUA_BUF_SRCH_LIST,
- TAVARUA_BUF_EVENTS,
- TAVARUA_BUF_RT_RDS,
- TAVARUA_BUF_PS_RDS,
- TAVARUA_BUF_RAW_RDS,
- TAVARUA_BUF_AF_LIST,
- TAVARUA_BUF_MAX
-};
-
-enum tavarua_xfr_t {
- TAVARUA_XFR_SYNC,
- TAVARUA_XFR_ERROR,
- TAVARUA_XFR_SRCH_LIST,
- TAVARUA_XFR_RT_RDS,
- TAVARUA_XFR_PS_RDS,
- TAVARUA_XFR_AF_LIST,
- TAVARUA_XFR_MAX
-};
-
-enum channel_spacing {
- FM_CH_SPACE_200KHZ,
- FM_CH_SPACE_100KHZ,
- FM_CH_SPACE_50KHZ
-};
-
-enum step_size {
- NO_SRCH200khz,
- ENF_SRCH200khz
-};
-
-enum emphasis {
- EMP_75,
- EMP_50
-};
-
-enum rds_std {
- RBDS_STD,
- RDS_STD
-};
-
-/* offsets */
-#define RAW_RDS 0x0F
-#define RDS_BLOCK 3
-
-/* registers*/
-#define MARIMBA_XO_BUFF_CNTRL 0x07
-#define RADIO_REGISTERS 0x30
-#define XFR_REG_NUM 16
-#define STATUS_REG_NUM 3
-
-/* TX constants */
-#define HEADER_SIZE 4
-#define TX_ON 0x80
-#define TAVARUA_TX_RT RDS_RT_0
-#define TAVARUA_TX_PS RDS_PS_0
-
-enum register_t {
- STATUS_REG1 = 0,
- STATUS_REG2,
- STATUS_REG3,
- RDCTRL,
- FREQ,
- TUNECTRL,
- SRCHRDS1,
- SRCHRDS2,
- SRCHCTRL,
- IOCTRL,
- RDSCTRL,
- ADVCTRL,
- AUDIOCTRL,
- RMSSI,
- IOVERC,
- AUDIOIND = 0x1E,
- XFRCTRL,
- FM_CTL0 = 0xFF,
- LEAKAGE_CNTRL = 0xFE,
-};
-#define BAHAMA_RBIAS_CTL1 0x07
-#define BAHAMA_FM_MODE_REG 0xFD
-#define BAHAMA_FM_CTL1_REG 0xFE
-#define BAHAMA_FM_CTL0_REG 0xFF
-#define BAHAMA_FM_MODE_NORMAL 0x00
-#define BAHAMA_LDO_DREG_CTL0 0xF0
-#define BAHAMA_LDO_AREG_CTL0 0xF4
-
-/* Radio Control */
-#define RDCTRL_STATE_OFFSET 0
-#define RDCTRL_STATE_MASK (3 << RDCTRL_STATE_OFFSET)
-#define RDCTRL_BAND_OFFSET 2
-#define RDCTRL_BAND_MASK (1 << RDCTRL_BAND_OFFSET)
-#define RDCTRL_CHSPACE_OFFSET 3
-#define RDCTRL_CHSPACE_MASK (3 << RDCTRL_CHSPACE_OFFSET)
-#define RDCTRL_DEEMPHASIS_OFFSET 5
-#define RDCTRL_DEEMPHASIS_MASK (1 << RDCTRL_DEEMPHASIS_OFFSET)
-#define RDCTRL_HLSI_OFFSET 6
-#define RDCTRL_HLSI_MASK (3 << RDCTRL_HLSI_OFFSET)
-#define RDSAF_OFFSET 6
-#define RDSAF_MASK (1 << RDSAF_OFFSET)
-
-/* Tune Control */
-#define TUNE_STATION 0x01
-#define ADD_OFFSET (1 << 1)
-#define SIGSTATE (1 << 5)
-#define MOSTSTATE (1 << 6)
-#define RDSSYNC (1 << 7)
-/* Search Control */
-#define SRCH_MODE_OFFSET 0
-#define SRCH_MODE_MASK (7 << SRCH_MODE_OFFSET)
-#define SRCH_DIR_OFFSET 3
-#define SRCH_DIR_MASK (1 << SRCH_DIR_OFFSET)
-#define SRCH_DWELL_OFFSET 4
-#define SRCH_DWELL_MASK (7 << SRCH_DWELL_OFFSET)
-#define SRCH_STATE_OFFSET 7
-#define SRCH_STATE_MASK (1 << SRCH_STATE_OFFSET)
-
-/* I/O Control */
-#define IOC_HRD_MUTE 0x03
-#define IOC_SFT_MUTE (1 << 2)
-#define IOC_MON_STR (1 << 3)
-#define IOC_SIG_BLND (1 << 4)
-#define IOC_INTF_BLND (1 << 5)
-#define IOC_ANTENNA (1 << 6)
-#define IOC_ANTENNA_OFFSET 6
-#define IOC_ANTENNA_MASK (1 << IOC_ANTENNA_OFFSET)
-
-/* RDS Control */
-#define RDS_ON 0x01
-#define RDSCTRL_STANDARD_OFFSET 1
-#define RDSCTRL_STANDARD_MASK (1 << RDSCTRL_STANDARD_OFFSET)
-
-/* Advanced features controls */
-#define RDSRTEN (1 << 3)
-#define RDSPSEN (1 << 4)
-
-/* Audio path control */
-#define AUDIORX_ANALOG_OFFSET 0
-#define AUDIORX_ANALOG_MASK (1 << AUDIORX_ANALOG_OFFSET)
-#define AUDIORX_DIGITAL_OFFSET 1
-#define AUDIORX_DIGITAL_MASK (1 << AUDIORX_DIGITAL_OFFSET)
-#define AUDIOTX_OFFSET 2
-#define AUDIOTX_MASK (1 << AUDIOTX_OFFSET)
-#define I2SCTRL_OFFSET 3
-#define I2SCTRL_MASK (1 << I2SCTRL_OFFSET)
-
-/* Search options */
-enum search_t {
- SEEK,
- SCAN,
- SCAN_FOR_STRONG,
- SCAN_FOR_WEAK,
- RDS_SEEK_PTY,
- RDS_SCAN_PTY,
- RDS_SEEK_PI,
- RDS_AF_JUMP,
-};
-
-enum audio_path {
- FM_DIGITAL_PATH,
- FM_ANALOG_PATH
-};
-#define SRCH_MODE 0x07
-#define SRCH_DIR 0x08 /* 0-up 1-down */
-#define SCAN_DWELL 0x70
-#define SRCH_ON 0x80
-
-/* RDS CONFIG */
-#define RDS_CONFIG_PSALL 0x01
-
-#define FM_ENABLE 0x22
-#define SET_REG_FIELD(reg, val, offset, mask) \
- (reg = (reg & ~mask) | (((val) << offset) & mask))
-#define GET_REG_FIELD(reg, offset, mask) ((reg & mask) >> offset)
-#define RSH_DATA(val, offset) ((val) >> (offset))
-#define LSH_DATA(val, offset) ((val) << (offset))
-#define GET_ABS_VAL(val) ((val) & (0xFF))
-
-enum radio_state_t {
- FM_OFF,
- FM_RECV,
- FM_TRANS,
- FM_RESET,
-};
-
-#define XFRCTRL_WRITE (1 << 7)
-
-/* Interrupt status */
-
-/* interrupt register 1 */
-#define READY (1 << 0) /* Radio ready after powerup or reset */
-#define TUNE (1 << 1) /* Tune completed */
-#define SEARCH (1 << 2) /* Search completed (read FREQ) */
-#define SCANNEXT (1 << 3) /* Scanning for next station */
-#define SIGNAL (1 << 4) /* Signal indicator change (read SIGSTATE) */
-#define INTF (1 << 5) /* Interference cnt has fallen outside range */
-#define SYNC (1 << 6) /* RDS sync state change (read RDSSYNC) */
-#define AUDIO (1 << 7) /* Audio Control indicator (read AUDIOIND) */
-
-/* interrupt register 2 */
-#define RDSDAT (1 << 0) /* New unread RDS data group available */
-#define BLOCKB (1 << 1) /* Block-B match condition exists */
-#define PROGID (1 << 2) /* Block-A or Block-C matched stored PI value*/
-#define RDSPS (1 << 3) /* New RDS Program Service Table available */
-#define RDSRT (1 << 4) /* New RDS Radio Text available */
-#define RDSAF (1 << 5) /* New RDS AF List available */
-#define TXRDSDAT (1 << 6) /* Transmitted an RDS group */
-#define TXRDSDONE (1 << 7) /* RDS raw group one-shot transmit completed */
-
-/* interrupt register 3 */
-#define TRANSFER (1 << 0) /* Data transfer (XFR) completed */
-#define RDSPROC (1 << 1) /* Dynamic RDS Processing complete */
-#define ERROR (1 << 7) /* Err occurred.Read code to determine cause */
-
-
-#define FM_TX_PWR_LVL_0 0 /* Lowest power lvl that can be set for Tx */
-#define FM_TX_PWR_LVL_MAX 7 /* Max power lvl for Tx */
-/* Transfer */
-enum tavarua_xfr_ctrl_t {
- RDS_PS_0 = 0x01,
- RDS_PS_1,
- RDS_PS_2,
- RDS_PS_3,
- RDS_PS_4,
- RDS_PS_5,
- RDS_PS_6,
- RDS_RT_0,
- RDS_RT_1,
- RDS_RT_2,
- RDS_RT_3,
- RDS_RT_4,
- RDS_AF_0,
- RDS_AF_1,
- RDS_CONFIG,
- RDS_TX_GROUPS,
- RDS_COUNT_0,
- RDS_COUNT_1,
- RDS_COUNT_2,
- RADIO_CONFIG,
- RX_CONFIG,
- RX_TIMERS,
- RX_STATIONS_0,
- RX_STATIONS_1,
- INT_CTRL,
- ERROR_CODE,
- CHIPID,
- CAL_DAT_0 = 0x20,
- CAL_DAT_1,
- CAL_DAT_2,
- CAL_DAT_3,
- CAL_CFG_0,
- CAL_CFG_1,
- DIG_INTF_0,
- DIG_INTF_1,
- DIG_AGC_0,
- DIG_AGC_1,
- DIG_AGC_2,
- DIG_AUDIO_0,
- DIG_AUDIO_1,
- DIG_AUDIO_2,
- DIG_AUDIO_3,
- DIG_AUDIO_4,
- DIG_RXRDS,
- DIG_DCC,
- DIG_SPUR,
- DIG_MPXDCC,
- DIG_PILOT,
- DIG_DEMOD,
- DIG_MOST,
- DIG_TX_0,
- DIG_TX_1,
- PHY_TXGAIN = 0x3B,
- PHY_CONFIG,
- PHY_TXBLOCK,
- PHY_TCB,
- XFR_PEEK_MODE = 0x40,
- XFR_POKE_MODE = 0xC0,
- TAVARUA_XFR_CTRL_MAX
-};
-
-enum tavarua_evt_t {
- TAVARUA_EVT_RADIO_READY,
- TAVARUA_EVT_TUNE_SUCC,
- TAVARUA_EVT_SEEK_COMPLETE,
- TAVARUA_EVT_SCAN_NEXT,
- TAVARUA_EVT_NEW_RAW_RDS,
- TAVARUA_EVT_NEW_RT_RDS,
- TAVARUA_EVT_NEW_PS_RDS,
- TAVARUA_EVT_ERROR,
- TAVARUA_EVT_BELOW_TH,
- TAVARUA_EVT_ABOVE_TH,
- TAVARUA_EVT_STEREO,
- TAVARUA_EVT_MONO,
- TAVARUA_EVT_RDS_AVAIL,
- TAVARUA_EVT_RDS_NOT_AVAIL,
- TAVARUA_EVT_NEW_SRCH_LIST,
- TAVARUA_EVT_NEW_AF_LIST,
- TAVARUA_EVT_TXRDSDAT,
- TAVARUA_EVT_TXRDSDONE,
- TAVARUA_EVT_RADIO_DISABLED
-};
-
-enum tavarua_region_t {
- TAVARUA_REGION_US,
- TAVARUA_REGION_EU,
- TAVARUA_REGION_JAPAN,
- TAVARUA_REGION_JAPAN_WIDE,
- TAVARUA_REGION_OTHER
-};
-
-#endif /* __LINUX_TAVARUA_H */
diff --git a/hal/linux/LinuxPower.cpp b/hal/linux/LinuxPower.cpp
index 70ab4a3f6..626d1ac0c 100644
--- a/hal/linux/LinuxPower.cpp
+++ b/hal/linux/LinuxPower.cpp
@@ -12,28 +12,9 @@
#include "mozilla/Services.h"
#include "MainThreadUtils.h"
-#if defined(MOZ_WIDGET_GONK)
-#include "cutils/android_reboot.h"
-#include "cutils/properties.h"
-#endif
-
namespace mozilla {
namespace hal_impl {
-#if (defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 19)
-static void
-PowerCtl(const char* aValue, int aCmd)
-{
- // this invokes init's powerctl builtin via /init.rc
- property_set("sys.powerctl", aValue);
- // device should reboot in few moments, but if it doesn't - call
- // android_reboot() to make sure that init isn't stuck somewhere
- sleep(10);
- HAL_LOG("Powerctl call takes too long, forcing %s.", aValue);
- android_reboot(aCmd, 0, nullptr);
-}
-#endif
-
void
Reboot()
{
@@ -44,14 +25,8 @@ Reboot()
}
}
-#if !defined(MOZ_WIDGET_GONK)
sync();
reboot(RB_AUTOBOOT);
-#elif (ANDROID_VERSION < 19)
- android_reboot(ANDROID_RB_RESTART, 0, nullptr);
-#else
- PowerCtl("reboot", ANDROID_RB_RESTART);
-#endif
}
void
@@ -64,14 +39,8 @@ PowerOff()
}
}
-#if !defined(MOZ_WIDGET_GONK)
sync();
reboot(RB_POWER_OFF);
-#elif (ANDROID_VERSION < 19)
- android_reboot(ANDROID_RB_POWEROFF, 0, nullptr);
-#else
- PowerCtl("shutdown", ANDROID_RB_POWEROFF);
-#endif
}
// Structure to specify how watchdog pthread is going to work.
diff --git a/hal/moz.build b/hal/moz.build
index c17379f22..3e1bae404 100644
--- a/hal/moz.build
+++ b/hal/moz.build
@@ -4,12 +4,6 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-XPIDL_SOURCES += [
- 'gonk/nsIRecoveryService.idl',
-]
-
-XPIDL_MODULE = 'hal'
-
EXPORTS.mozilla += [
'Hal.h',
'HalImpl.h',
@@ -45,24 +39,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
SOURCES += [
'android/AndroidHal.cpp',
]
-elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- UNIFIED_SOURCES += [
- 'gonk/GonkDiskSpaceWatcher.cpp',
- 'gonk/GonkSensor.cpp',
- 'gonk/GonkSensorsHelpers.cpp',
- 'gonk/GonkSensorsInterface.cpp',
- 'gonk/GonkSensorsPollInterface.cpp',
- 'gonk/GonkSensorsRegistryInterface.cpp',
- 'gonk/GonkSwitch.cpp',
- 'gonk/SystemService.cpp',
- 'gonk/UeventPoller.cpp',
- 'linux/LinuxMemory.cpp',
- 'linux/LinuxPower.cpp',
- ]
- # GonkHal.cpp cannot be built in unified mode because it relies on HalImpl.h.
- SOURCES += [
- 'gonk/GonkHal.cpp',
- ]
elif CONFIG['OS_TARGET'] == 'Linux':
UNIFIED_SOURCES += [
'fallback/FallbackAlarm.cpp',
@@ -130,19 +106,17 @@ else:
'fallback/FallbackVibration.cpp',
]
-# Fallbacks for backends implemented on Gonk only.
-if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
- UNIFIED_SOURCES += [
- 'fallback/FallbackDiskSpaceWatcher.cpp',
- 'fallback/FallbackFactoryReset.cpp',
- 'fallback/FallbackProcessPriority.cpp',
- 'fallback/FallbackScreenPower.cpp',
- 'fallback/FallbackSwitch.cpp',
- 'fallback/FallbackSystemService.cpp',
- 'fallback/FallbackThreadPriority.cpp',
- 'fallback/FallbackTime.cpp',
- 'fallback/FallbackWakeLocks.cpp',
- ]
+UNIFIED_SOURCES += [
+ 'fallback/FallbackDiskSpaceWatcher.cpp',
+ 'fallback/FallbackFactoryReset.cpp',
+ 'fallback/FallbackProcessPriority.cpp',
+ 'fallback/FallbackScreenPower.cpp',
+ 'fallback/FallbackSwitch.cpp',
+ 'fallback/FallbackSystemService.cpp',
+ 'fallback/FallbackThreadPriority.cpp',
+ 'fallback/FallbackTime.cpp',
+ 'fallback/FallbackWakeLocks.cpp',
+]
# Fallbacks for backends implemented on Android only.
if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android':
@@ -169,16 +143,6 @@ if CONFIG['MOZ_GAMEPAD']:
'/dom/base',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- # So that we can call nsScreenManagerGonk::GetConfiguration().
- LOCAL_INCLUDES += [
- '/widget',
- '/widget/gonk',
- ]
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- LOCAL_INCLUDES += ['%' + '%s/hardware/libhardware_legacy/include' % CONFIG['ANDROID_SOURCE']]
-
CFLAGS += CONFIG['GLIB_CFLAGS']
CFLAGS += CONFIG['MOZ_DBUS_GLIB_CFLAGS']
CXXFLAGS += CONFIG['GLIB_CFLAGS']
diff --git a/intl/lwbrk/nsJISx4051LineBreaker.cpp b/intl/lwbrk/nsJISx4051LineBreaker.cpp
index 1b262fa2c..fe4191a5f 100644
--- a/intl/lwbrk/nsJISx4051LineBreaker.cpp
+++ b/intl/lwbrk/nsJISx4051LineBreaker.cpp
@@ -553,10 +553,8 @@ GetClass(uint32_t u)
/* ZWJ = 42, [ZWJ]*/ CLASS_CHARACTER
};
-#if ENABLE_INTL_API
static_assert(U_LB_COUNT == mozilla::ArrayLength(sUnicodeLineBreakToClass),
"Gecko vs ICU LineBreak class mismatch");
-#endif
auto cls = mozilla::unicode::GetLineBreakClass(u);
MOZ_ASSERT(cls < mozilla::ArrayLength(sUnicodeLineBreakToClass));
diff --git a/intl/unicharutil/moz.build b/intl/unicharutil/moz.build
index 461fd255e..7b93396fc 100644
--- a/intl/unicharutil/moz.build
+++ b/intl/unicharutil/moz.build
@@ -27,17 +27,9 @@ UNIFIED_SOURCES += [
'nsCategoryImp.cpp',
'nsEntityConverter.cpp',
'nsSaveAsCharset.cpp',
+ 'nsUnicodeNormalizer.cpp',
]
-if CONFIG['ENABLE_INTL_API']:
- UNIFIED_SOURCES += [
- 'nsUnicodeNormalizer_ICU.cpp',
- ]
-else:
- UNIFIED_SOURCES += [
- 'nsUnicodeNormalizer.cpp',
- ]
-
FINAL_LIBRARY = 'xul'
if CONFIG['GNU_CXX']:
diff --git a/intl/unicharutil/normalization_data.h b/intl/unicharutil/normalization_data.h
deleted file mode 100644
index 90dcd9f4e..000000000
--- a/intl/unicharutil/normalization_data.h
+++ /dev/null
@@ -1,5247 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-
-/* This file is modified from JPNIC's mDNKit, it is under both MPL and
- * JPNIC's license.
- */
-
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this
- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/*
- * Copyright (c) 2000,2002 Japan Network Information Center.
- * All rights reserved.
- *
- * By using this file, you agree to the terms and conditions set forth bellow.
- *
- * LICENSE TERMS AND CONDITIONS
- *
- * The following License Terms and Conditions apply, unless a different
- * license is obtained from Japan Network Information Center ("JPNIC"),
- * a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda,
- * Chiyoda-ku, Tokyo 101-0047, Japan.
- *
- * 1. Use, Modification and Redistribution (including distribution of any
- * modified or derived work) in source and/or binary forms is permitted
- * under this License Terms and Conditions.
- *
- * 2. Redistribution of source code must retain the copyright notices as they
- * appear in each source code file, this License Terms and Conditions.
- *
- * 3. Redistribution in binary form must reproduce the Copyright Notice,
- * this License Terms and Conditions, in the documentation and/or other
- * materials provided with the distribution. For the purposes of binary
- * distribution the "Copyright Notice" refers to the following language:
- * "Copyright (c) 2000-2002 Japan Network Information Center. All rights reserved."
- *
- * 4. The name of JPNIC may not be used to endorse or promote products
- * derived from this Software without specific prior written approval of
- * JPNIC.
- *
- * 5. Disclaimer/Limitation of Liability: THIS SOFTWARE IS PROVIDED BY JPNIC
- * "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 JPNIC 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 DAMAGES.
- */
-
-/* $Id: normalization_data.h,v 1.1 2005/04/05 23:00:13 jshin%mailaps.org Exp $ */
-/* $-Id: generate_normalize_data.pl,v 1.9 2002/11/29 09:08:13 ishisone Exp -$ */
-/*
- * Do not edit this file!
- * This file is generated from UnicodeData.txt, CompositionExclusions-1.txt,
- * SpecialCasing.txt and CaseFolding.txt.
- */
-
-
-/*
- * Canonical Class
- */
-
-#define CANON_CLASS_BITS_0 9
-#define CANON_CLASS_BITS_1 7
-#define CANON_CLASS_BITS_2 5
-
-static const char16_t canon_class_imap[] = {
- 272, 400, 528, 656, 784, 784, 784, 784,
- 784, 784, 912, 784, 784, 784, 784, 1040,
- 1168, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 1296, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 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, 2, 3, 4, 0, 0, 0, 0,
- 0, 0, 0, 0, 5, 0, 0, 0,
- 0, 0, 0, 0, 6, 7, 8, 0,
- 9, 0, 10, 11, 0, 0, 12, 13,
- 14, 15, 16, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 17, 18, 0, 0, 17, 19, 0,
- 0, 17, 19, 0, 0, 17, 19, 0,
- 0, 17, 19, 0, 0, 0, 19, 0,
- 0, 0, 20, 0, 0, 17, 19, 0,
- 0, 0, 19, 0, 0, 0, 21, 0,
- 0, 22, 23, 0, 0, 24, 25, 0,
- 26, 27, 0, 28, 29, 0, 30, 0,
- 0, 31, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 32, 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,
- 33, 33, 0, 0, 0, 0, 34, 0,
- 0, 0, 0, 0, 0, 35, 0, 0,
- 0, 36, 0, 0, 0, 0, 0, 0,
- 37, 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, 38, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 39, 40,
- 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,
- 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, 41, 0, 0, 42, 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, 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, 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, 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, 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,
- 43, 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, 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, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 44, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 45, 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, 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,
- 46, 47, 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, 48, 49, 50, 0, 0,
- 0, 0, 51, 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, 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,
-};
-
-static const struct {
- unsigned char tbl[32];
-} canon_class_table[] = {
- {{
- 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,
- }},
- {{
- 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230,
- 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 232,
- 220, 220, 220, 220, 232, 216, 220, 220, 220, 220,
- }},
- {{
- 220, 202, 202, 220, 220, 220, 220, 202, 202, 220, 220,
- 220, 220, 220, 220, 220, 220, 220, 220, 220, 1, 1,
- 1, 1, 1, 220, 220, 220, 220, 230, 230, 230,
- }},
- {{
- 230, 230, 230, 230, 230, 240, 230, 220, 220, 220, 230,
- 230, 230, 220, 220, 0, 230, 230, 230, 220, 220, 220,
- 220, 230, 232, 220, 220, 230, 233, 234, 234, 233,
- }},
- {{
- 234, 234, 233, 230, 230, 230, 230, 230, 230, 230, 230,
- 230, 230, 230, 230, 230, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 230, 230, 230, 230, 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, 220, 230, 230, 230, 230,
- 220, 230, 230, 230, 222, 220, 230, 230, 230, 230,
- }},
- {{
- 230, 230, 220, 220, 220, 220, 220, 220, 230, 230, 220,
- 230, 230, 222, 228, 230, 10, 11, 12, 13, 14, 15,
- 16, 17, 18, 19, 0, 20, 21, 22, 0, 23,
- }},
- {{
- 0, 24, 25, 0, 230, 220, 0, 18, 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, 230, 230, 230, 230, 230, 230,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 27, 28, 29, 30, 31, 32, 33, 34, 230, 230, 220,
- 220, 230, 230, 230, 230, 230, 220, 230, 230, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 35, 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,
- 230, 230, 230, 230, 230, 230, 230, 0, 0, 230,
- }},
- {{
- 230, 230, 230, 220, 230, 0, 0, 230, 230, 0, 220,
- 230, 230, 220, 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, 36, 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, 230, 220, 230, 230, 220, 230,
- 230, 220, 220, 220, 230, 220, 220, 230, 220, 230,
- }},
- {{
- 230, 230, 220, 230, 220, 230, 220, 230, 220, 230, 230,
- 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, 7, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 9, 0, 0, 0, 230, 220, 230, 230, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 9, 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, 9, 0, 0, 0, 0, 0, 0, 0, 84,
- 91, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
- 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, 103, 103, 9, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 107, 107, 107,
- 107, 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, 118, 118, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 122, 122, 122,
- 122, 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, 220, 220, 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, 220,
- 0, 220, 0, 216, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 129, 130, 0, 132, 0,
- 0, 0, 0, 0, 130, 130, 130, 130, 0, 0,
- }},
- {{
- 130, 0, 230, 230, 9, 0, 230, 230, 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, 220, 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, 7, 0, 9, 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, 230,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 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, 9, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 230, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 228, 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, 222, 230, 220, 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, 230, 220, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 230, 230, 220, 230, 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, 230, 230, 1, 1, 230, 230,
- 230, 230, 1, 1, 1, 230, 230, 0, 0, 0,
- }},
- {{
- 0, 230, 0, 0, 0, 1, 1, 230, 220, 230, 1,
- 1, 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, 218,
- 228, 232, 222, 224, 224, 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, 8, 8, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 9, 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, 26, 0,
- }},
- {{
- 230, 230, 230, 230, 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, 220, 0, 230, 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, 230, 1, 220, 0, 0, 0, 0, 9,
- }},
- {{
- 0, 0, 0, 0, 0, 216, 216, 1, 1, 1, 0,
- 0, 0, 226, 216, 216, 216, 216, 216, 0, 0, 0,
- 0, 0, 0, 0, 0, 220, 220, 220, 220, 220,
- }},
- {{
- 220, 220, 220, 0, 0, 230, 230, 230, 230, 230, 220,
- 220, 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, 230,
- 230, 230, 230, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 230, 230, 230, 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,
- }},
-};
-
-/*
- * Canonical Composition
- */
-
-#define CANON_COMPOSE_BITS_0 9
-#define CANON_COMPOSE_BITS_1 7
-#define CANON_COMPOSE_BITS_2 5
-
-static const char16_t compose_imap[] = {
- 272, 400, 528, 656, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 0, 1, 2, 3, 0, 4, 5, 6,
- 7, 0, 8, 9, 0, 10, 0, 11,
- 0, 12, 0, 0, 13, 0, 0, 0,
- 0, 0, 0, 0, 14, 15, 16, 0,
- 17, 18, 19, 20, 0, 0, 21, 22,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 23, 24, 0, 0, 0, 25, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 26, 0, 0, 0, 0, 27, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 28, 0, 29, 0, 30, 0,
- 0, 0, 31, 0, 0, 32, 33, 0,
- 0, 0, 34, 0, 0, 0, 35, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 36, 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, 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, 37, 38, 39, 0, 40, 41, 0,
- 42, 43, 44, 45, 0, 46, 47, 48,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 49, 0, 50, 0,
- 51, 52, 53, 54, 55, 56, 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, 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, 57, 58, 59, 60, 61, 62,
- 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,
- 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,
- 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,
- 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,
-};
-
-static const struct {
- uint32_t tbl[32];
-} compose_table[] = {
- {{
- 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,
- 65537, 65538, 65539, 0,
- }},
- {{
- 0, 1048580, 196628, 327703, 393244, 1114146, 65587,
- 458804, 458811, 983106, 65617, 327762, 393303, 196701,
- 589920, 1048681, 131193, 0, 524411, 458883, 458890,
- 1245329, 131236, 393382, 131244, 589998, 393399, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 1048765, 196813, 327888, 393429, 1114331, 65772,
- 458989, 524532, 917756, 131338, 327948, 393489, 196887,
- 590106, 1048867, 131379, 0, 524597, 459069, 524612,
- 1245516, 131423, 459105, 131432, 655722, 393588, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 0, 196986, 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, 262525, 0, 65921, 65922, 131459,
- 65925, 0, 0, 262534, 0, 0, 0,
- 0, 65930, 0, 0, 0, 0, 262539,
- 197007, 65938, 0, 65939, 0, 0, 0,
- 262548, 0, 0, 0,
- }},
- {{
- 0, 0, 262552, 0, 65948, 65949, 131486,
- 65952, 0, 0, 262561, 0, 0, 0,
- 0, 65957, 0, 0, 0, 0, 262566,
- 197034, 65965, 0, 65966, 0, 0, 0,
- 262575, 0, 0, 0,
- }},
- {{
- 0, 0, 262579, 262583, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 131515, 131517, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 131519, 131521,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 65987, 65988,
- 0, 0, 0, 0,
- }},
- {{
- 65989, 65990, 0, 0, 0, 0, 0,
- 0, 65991, 65992, 65993, 65994, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 65995,
- }},
- {{
- 328140, 328145, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 328150, 328155, 0, 0, 0, 0,
- 0, 0, 66016, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 66017, 66018, 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, 66019,
- 66020, 66021, 66022, 0, 0, 0, 0,
- 66023, 66024, 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, 66025, 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, 459242, 0, 0, 0,
- 262641, 0, 328181, 0, 459258, 0, 0,
- 0, 0, 0, 262657,
- }},
- {{
- 0, 66053, 0, 0, 0, 393734, 0,
- 0, 0, 328204, 0, 0, 66065, 0,
- 66066, 0, 0, 524819, 0, 0, 0,
- 262683, 0, 393759, 0, 524837, 0, 0,
- 0, 0, 0, 262701,
- }},
- {{
- 0, 131633, 0, 0, 0, 524851, 0,
- 0, 0, 393787, 197185, 197188, 0, 0,
- 66119, 0, 0, 0, 131656, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 66122,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 131659, 0, 0, 66125, 0,
- 197198, 131665, 66131, 262740, 0, 66136, 0,
- 0, 0, 66137, 0,
- }},
- {{
- 0, 0, 0, 262746, 0, 0, 0,
- 66142, 0, 0, 0, 66143, 0, 66144,
- 0, 0, 131681, 0, 0, 66147, 0,
- 197220, 131687, 66153, 262762, 0, 66158, 0,
- 0, 0, 66159, 0,
- }},
- {{
- 0, 0, 0, 262768, 0, 0, 0,
- 66164, 0, 0, 0, 66165, 0, 66166,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 66167, 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, 66168,
- 66169, 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, 66170, 66171, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 0, 66172, 66173, 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,
- 197246, 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, 66177, 0, 66178, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 66179, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 66180, 0, 0,
- 66181, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 0, 66182, 0, 0, 0, 0, 0,
- 0, 0, 66183, 0, 0, 66184, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 131721, 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,
- 197259, 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, 66190, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 131727,
- 66193, 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, 66194,
- 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, 66195,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 197268,
- 0, 0, 0, 66199, 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, 131736,
- 66202, 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, 197275, 0, 0,
- 66206, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 66207, 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, 66208, 66209, 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, 66210, 66211,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 66212, 66213, 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,
- }},
- {{
- 131750, 131752, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 66218, 66219, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 66220, 66221,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 262830, 262834, 66230, 66231, 66232, 66233, 66234,
- 66235, 262844, 262848, 66244, 66245, 66246, 66247,
- 66248, 66249, 131786, 131788, 0, 0, 0,
- 0, 0, 0, 131790, 131792, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 262866, 262870, 66266, 66267, 66268, 66269, 66270,
- 66271, 262880, 262884, 66280, 66281, 66282, 66283,
- 66284, 66285, 197358, 197361, 0, 0, 0,
- 0, 0, 0, 197364, 197367, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 131834, 131836, 0, 0, 0, 0, 0,
- 0, 131838, 131840, 0, 0, 0, 0,
- 0, 0, 197378, 197381, 0, 0, 0,
- 0, 0, 0, 0, 197384, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 262923, 262927, 66323, 66324, 66325, 66326, 66327,
- 66328, 262937, 262941, 66337, 66338, 66339, 66340,
- 66341, 66342, 66343, 0, 0, 0, 66344,
- 0, 0, 0, 0, 0, 0, 0,
- 66345, 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, 66346, 0, 0, 0, 0, 0,
- 0, 0, 0, 197419,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 66350,
- 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, 66351, 0, 0, 0, 0, 0,
- 0, 0, 197424, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 66355, 0, 66356, 0, 66357,
- 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, 66358, 0, 66359, 0, 66360,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 66361, 0, 0, 0,
- 0, 66362, 0, 0, 66363, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 66364, 0, 66365, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 66366, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 66367, 0, 66368, 0,
- 0, 66369, 0, 0, 0, 0, 66370,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 66371, 0, 0, 66372, 66373, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 66374, 66375, 0,
- 0, 66376, 66377, 0, 0, 66378, 66379,
- 66380, 66381, 0, 0,
- }},
- {{
- 0, 0, 66382, 66383, 0, 0, 66384,
- 66385, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 66386, 66387, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 66388, 0, 0, 0, 0,
- 0, 66389, 66390, 0, 66391, 0, 0,
- 0, 0, 0, 0, 66392, 66393, 66394,
- 66395, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 66396,
- 0, 0, 0, 0, 66397, 0, 66398,
- 0, 66399, 0, 66400, 0, 66401, 0,
- 66402, 0, 66403, 0, 66404, 0, 66405,
- 0, 66406, 0, 66407,
- }},
- {{
- 0, 66408, 0, 0, 66409, 0, 66410,
- 0, 66411, 0, 0, 0, 0, 0,
- 0, 131948, 0, 0, 131950, 0, 0,
- 131952, 0, 0, 131954, 0, 0, 131956,
- 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, 66422, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 66423,
- 0, 0, 0, 0, 66424, 0, 66425,
- 0, 66426, 0, 66427, 0, 66428, 0,
- 66429, 0, 66430, 0, 66431, 0, 66432,
- 0, 66433, 0, 66434,
- }},
- {{
- 0, 66435, 0, 0, 66436, 0, 66437,
- 0, 66438, 0, 0, 0, 0, 0,
- 0, 131975, 0, 0, 131977, 0, 0,
- 131979, 0, 0, 131981, 0, 0, 131983,
- 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 66449, 66450, 66451, 66452, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
- 0, 66453, 0, 0,
- }},
-};
-
-static const struct composition compose_seq[] = {
- { 0x00000000, 0x00000000 }, { 0x00000338, 0x0000226e },
- { 0x00000338, 0x00002260 }, { 0x00000338, 0x0000226f },
- { 0x00000300, 0x000000c0 }, { 0x00000301, 0x000000c1 },
- { 0x00000302, 0x000000c2 }, { 0x00000303, 0x000000c3 },
- { 0x00000304, 0x00000100 }, { 0x00000306, 0x00000102 },
- { 0x00000307, 0x00000226 }, { 0x00000308, 0x000000c4 },
- { 0x00000309, 0x00001ea2 }, { 0x0000030a, 0x000000c5 },
- { 0x0000030c, 0x000001cd }, { 0x0000030f, 0x00000200 },
- { 0x00000311, 0x00000202 }, { 0x00000323, 0x00001ea0 },
- { 0x00000325, 0x00001e00 }, { 0x00000328, 0x00000104 },
- { 0x00000307, 0x00001e02 }, { 0x00000323, 0x00001e04 },
- { 0x00000331, 0x00001e06 }, { 0x00000301, 0x00000106 },
- { 0x00000302, 0x00000108 }, { 0x00000307, 0x0000010a },
- { 0x0000030c, 0x0000010c }, { 0x00000327, 0x000000c7 },
- { 0x00000307, 0x00001e0a }, { 0x0000030c, 0x0000010e },
- { 0x00000323, 0x00001e0c }, { 0x00000327, 0x00001e10 },
- { 0x0000032d, 0x00001e12 }, { 0x00000331, 0x00001e0e },
- { 0x00000300, 0x000000c8 }, { 0x00000301, 0x000000c9 },
- { 0x00000302, 0x000000ca }, { 0x00000303, 0x00001ebc },
- { 0x00000304, 0x00000112 }, { 0x00000306, 0x00000114 },
- { 0x00000307, 0x00000116 }, { 0x00000308, 0x000000cb },
- { 0x00000309, 0x00001eba }, { 0x0000030c, 0x0000011a },
- { 0x0000030f, 0x00000204 }, { 0x00000311, 0x00000206 },
- { 0x00000323, 0x00001eb8 }, { 0x00000327, 0x00000228 },
- { 0x00000328, 0x00000118 }, { 0x0000032d, 0x00001e18 },
- { 0x00000330, 0x00001e1a }, { 0x00000307, 0x00001e1e },
- { 0x00000301, 0x000001f4 }, { 0x00000302, 0x0000011c },
- { 0x00000304, 0x00001e20 }, { 0x00000306, 0x0000011e },
- { 0x00000307, 0x00000120 }, { 0x0000030c, 0x000001e6 },
- { 0x00000327, 0x00000122 }, { 0x00000302, 0x00000124 },
- { 0x00000307, 0x00001e22 }, { 0x00000308, 0x00001e26 },
- { 0x0000030c, 0x0000021e }, { 0x00000323, 0x00001e24 },
- { 0x00000327, 0x00001e28 }, { 0x0000032e, 0x00001e2a },
- { 0x00000300, 0x000000cc }, { 0x00000301, 0x000000cd },
- { 0x00000302, 0x000000ce }, { 0x00000303, 0x00000128 },
- { 0x00000304, 0x0000012a }, { 0x00000306, 0x0000012c },
- { 0x00000307, 0x00000130 }, { 0x00000308, 0x000000cf },
- { 0x00000309, 0x00001ec8 }, { 0x0000030c, 0x000001cf },
- { 0x0000030f, 0x00000208 }, { 0x00000311, 0x0000020a },
- { 0x00000323, 0x00001eca }, { 0x00000328, 0x0000012e },
- { 0x00000330, 0x00001e2c }, { 0x00000302, 0x00000134 },
- { 0x00000301, 0x00001e30 }, { 0x0000030c, 0x000001e8 },
- { 0x00000323, 0x00001e32 }, { 0x00000327, 0x00000136 },
- { 0x00000331, 0x00001e34 }, { 0x00000301, 0x00000139 },
- { 0x0000030c, 0x0000013d }, { 0x00000323, 0x00001e36 },
- { 0x00000327, 0x0000013b }, { 0x0000032d, 0x00001e3c },
- { 0x00000331, 0x00001e3a }, { 0x00000301, 0x00001e3e },
- { 0x00000307, 0x00001e40 }, { 0x00000323, 0x00001e42 },
- { 0x00000300, 0x000001f8 }, { 0x00000301, 0x00000143 },
- { 0x00000303, 0x000000d1 }, { 0x00000307, 0x00001e44 },
- { 0x0000030c, 0x00000147 }, { 0x00000323, 0x00001e46 },
- { 0x00000327, 0x00000145 }, { 0x0000032d, 0x00001e4a },
- { 0x00000331, 0x00001e48 }, { 0x00000300, 0x000000d2 },
- { 0x00000301, 0x000000d3 }, { 0x00000302, 0x000000d4 },
- { 0x00000303, 0x000000d5 }, { 0x00000304, 0x0000014c },
- { 0x00000306, 0x0000014e }, { 0x00000307, 0x0000022e },
- { 0x00000308, 0x000000d6 }, { 0x00000309, 0x00001ece },
- { 0x0000030b, 0x00000150 }, { 0x0000030c, 0x000001d1 },
- { 0x0000030f, 0x0000020c }, { 0x00000311, 0x0000020e },
- { 0x0000031b, 0x000001a0 }, { 0x00000323, 0x00001ecc },
- { 0x00000328, 0x000001ea }, { 0x00000301, 0x00001e54 },
- { 0x00000307, 0x00001e56 }, { 0x00000301, 0x00000154 },
- { 0x00000307, 0x00001e58 }, { 0x0000030c, 0x00000158 },
- { 0x0000030f, 0x00000210 }, { 0x00000311, 0x00000212 },
- { 0x00000323, 0x00001e5a }, { 0x00000327, 0x00000156 },
- { 0x00000331, 0x00001e5e }, { 0x00000301, 0x0000015a },
- { 0x00000302, 0x0000015c }, { 0x00000307, 0x00001e60 },
- { 0x0000030c, 0x00000160 }, { 0x00000323, 0x00001e62 },
- { 0x00000326, 0x00000218 }, { 0x00000327, 0x0000015e },
- { 0x00000307, 0x00001e6a }, { 0x0000030c, 0x00000164 },
- { 0x00000323, 0x00001e6c }, { 0x00000326, 0x0000021a },
- { 0x00000327, 0x00000162 }, { 0x0000032d, 0x00001e70 },
- { 0x00000331, 0x00001e6e }, { 0x00000300, 0x000000d9 },
- { 0x00000301, 0x000000da }, { 0x00000302, 0x000000db },
- { 0x00000303, 0x00000168 }, { 0x00000304, 0x0000016a },
- { 0x00000306, 0x0000016c }, { 0x00000308, 0x000000dc },
- { 0x00000309, 0x00001ee6 }, { 0x0000030a, 0x0000016e },
- { 0x0000030b, 0x00000170 }, { 0x0000030c, 0x000001d3 },
- { 0x0000030f, 0x00000214 }, { 0x00000311, 0x00000216 },
- { 0x0000031b, 0x000001af }, { 0x00000323, 0x00001ee4 },
- { 0x00000324, 0x00001e72 }, { 0x00000328, 0x00000172 },
- { 0x0000032d, 0x00001e76 }, { 0x00000330, 0x00001e74 },
- { 0x00000303, 0x00001e7c }, { 0x00000323, 0x00001e7e },
- { 0x00000300, 0x00001e80 }, { 0x00000301, 0x00001e82 },
- { 0x00000302, 0x00000174 }, { 0x00000307, 0x00001e86 },
- { 0x00000308, 0x00001e84 }, { 0x00000323, 0x00001e88 },
- { 0x00000307, 0x00001e8a }, { 0x00000308, 0x00001e8c },
- { 0x00000300, 0x00001ef2 }, { 0x00000301, 0x000000dd },
- { 0x00000302, 0x00000176 }, { 0x00000303, 0x00001ef8 },
- { 0x00000304, 0x00000232 }, { 0x00000307, 0x00001e8e },
- { 0x00000308, 0x00000178 }, { 0x00000309, 0x00001ef6 },
- { 0x00000323, 0x00001ef4 }, { 0x00000301, 0x00000179 },
- { 0x00000302, 0x00001e90 }, { 0x00000307, 0x0000017b },
- { 0x0000030c, 0x0000017d }, { 0x00000323, 0x00001e92 },
- { 0x00000331, 0x00001e94 }, { 0x00000300, 0x000000e0 },
- { 0x00000301, 0x000000e1 }, { 0x00000302, 0x000000e2 },
- { 0x00000303, 0x000000e3 }, { 0x00000304, 0x00000101 },
- { 0x00000306, 0x00000103 }, { 0x00000307, 0x00000227 },
- { 0x00000308, 0x000000e4 }, { 0x00000309, 0x00001ea3 },
- { 0x0000030a, 0x000000e5 }, { 0x0000030c, 0x000001ce },
- { 0x0000030f, 0x00000201 }, { 0x00000311, 0x00000203 },
- { 0x00000323, 0x00001ea1 }, { 0x00000325, 0x00001e01 },
- { 0x00000328, 0x00000105 }, { 0x00000307, 0x00001e03 },
- { 0x00000323, 0x00001e05 }, { 0x00000331, 0x00001e07 },
- { 0x00000301, 0x00000107 }, { 0x00000302, 0x00000109 },
- { 0x00000307, 0x0000010b }, { 0x0000030c, 0x0000010d },
- { 0x00000327, 0x000000e7 }, { 0x00000307, 0x00001e0b },
- { 0x0000030c, 0x0000010f }, { 0x00000323, 0x00001e0d },
- { 0x00000327, 0x00001e11 }, { 0x0000032d, 0x00001e13 },
- { 0x00000331, 0x00001e0f }, { 0x00000300, 0x000000e8 },
- { 0x00000301, 0x000000e9 }, { 0x00000302, 0x000000ea },
- { 0x00000303, 0x00001ebd }, { 0x00000304, 0x00000113 },
- { 0x00000306, 0x00000115 }, { 0x00000307, 0x00000117 },
- { 0x00000308, 0x000000eb }, { 0x00000309, 0x00001ebb },
- { 0x0000030c, 0x0000011b }, { 0x0000030f, 0x00000205 },
- { 0x00000311, 0x00000207 }, { 0x00000323, 0x00001eb9 },
- { 0x00000327, 0x00000229 }, { 0x00000328, 0x00000119 },
- { 0x0000032d, 0x00001e19 }, { 0x00000330, 0x00001e1b },
- { 0x00000307, 0x00001e1f }, { 0x00000301, 0x000001f5 },
- { 0x00000302, 0x0000011d }, { 0x00000304, 0x00001e21 },
- { 0x00000306, 0x0000011f }, { 0x00000307, 0x00000121 },
- { 0x0000030c, 0x000001e7 }, { 0x00000327, 0x00000123 },
- { 0x00000302, 0x00000125 }, { 0x00000307, 0x00001e23 },
- { 0x00000308, 0x00001e27 }, { 0x0000030c, 0x0000021f },
- { 0x00000323, 0x00001e25 }, { 0x00000327, 0x00001e29 },
- { 0x0000032e, 0x00001e2b }, { 0x00000331, 0x00001e96 },
- { 0x00000300, 0x000000ec }, { 0x00000301, 0x000000ed },
- { 0x00000302, 0x000000ee }, { 0x00000303, 0x00000129 },
- { 0x00000304, 0x0000012b }, { 0x00000306, 0x0000012d },
- { 0x00000308, 0x000000ef }, { 0x00000309, 0x00001ec9 },
- { 0x0000030c, 0x000001d0 }, { 0x0000030f, 0x00000209 },
- { 0x00000311, 0x0000020b }, { 0x00000323, 0x00001ecb },
- { 0x00000328, 0x0000012f }, { 0x00000330, 0x00001e2d },
- { 0x00000302, 0x00000135 }, { 0x0000030c, 0x000001f0 },
- { 0x00000301, 0x00001e31 }, { 0x0000030c, 0x000001e9 },
- { 0x00000323, 0x00001e33 }, { 0x00000327, 0x00000137 },
- { 0x00000331, 0x00001e35 }, { 0x00000301, 0x0000013a },
- { 0x0000030c, 0x0000013e }, { 0x00000323, 0x00001e37 },
- { 0x00000327, 0x0000013c }, { 0x0000032d, 0x00001e3d },
- { 0x00000331, 0x00001e3b }, { 0x00000301, 0x00001e3f },
- { 0x00000307, 0x00001e41 }, { 0x00000323, 0x00001e43 },
- { 0x00000300, 0x000001f9 }, { 0x00000301, 0x00000144 },
- { 0x00000303, 0x000000f1 }, { 0x00000307, 0x00001e45 },
- { 0x0000030c, 0x00000148 }, { 0x00000323, 0x00001e47 },
- { 0x00000327, 0x00000146 }, { 0x0000032d, 0x00001e4b },
- { 0x00000331, 0x00001e49 }, { 0x00000300, 0x000000f2 },
- { 0x00000301, 0x000000f3 }, { 0x00000302, 0x000000f4 },
- { 0x00000303, 0x000000f5 }, { 0x00000304, 0x0000014d },
- { 0x00000306, 0x0000014f }, { 0x00000307, 0x0000022f },
- { 0x00000308, 0x000000f6 }, { 0x00000309, 0x00001ecf },
- { 0x0000030b, 0x00000151 }, { 0x0000030c, 0x000001d2 },
- { 0x0000030f, 0x0000020d }, { 0x00000311, 0x0000020f },
- { 0x0000031b, 0x000001a1 }, { 0x00000323, 0x00001ecd },
- { 0x00000328, 0x000001eb }, { 0x00000301, 0x00001e55 },
- { 0x00000307, 0x00001e57 }, { 0x00000301, 0x00000155 },
- { 0x00000307, 0x00001e59 }, { 0x0000030c, 0x00000159 },
- { 0x0000030f, 0x00000211 }, { 0x00000311, 0x00000213 },
- { 0x00000323, 0x00001e5b }, { 0x00000327, 0x00000157 },
- { 0x00000331, 0x00001e5f }, { 0x00000301, 0x0000015b },
- { 0x00000302, 0x0000015d }, { 0x00000307, 0x00001e61 },
- { 0x0000030c, 0x00000161 }, { 0x00000323, 0x00001e63 },
- { 0x00000326, 0x00000219 }, { 0x00000327, 0x0000015f },
- { 0x00000307, 0x00001e6b }, { 0x00000308, 0x00001e97 },
- { 0x0000030c, 0x00000165 }, { 0x00000323, 0x00001e6d },
- { 0x00000326, 0x0000021b }, { 0x00000327, 0x00000163 },
- { 0x0000032d, 0x00001e71 }, { 0x00000331, 0x00001e6f },
- { 0x00000300, 0x000000f9 }, { 0x00000301, 0x000000fa },
- { 0x00000302, 0x000000fb }, { 0x00000303, 0x00000169 },
- { 0x00000304, 0x0000016b }, { 0x00000306, 0x0000016d },
- { 0x00000308, 0x000000fc }, { 0x00000309, 0x00001ee7 },
- { 0x0000030a, 0x0000016f }, { 0x0000030b, 0x00000171 },
- { 0x0000030c, 0x000001d4 }, { 0x0000030f, 0x00000215 },
- { 0x00000311, 0x00000217 }, { 0x0000031b, 0x000001b0 },
- { 0x00000323, 0x00001ee5 }, { 0x00000324, 0x00001e73 },
- { 0x00000328, 0x00000173 }, { 0x0000032d, 0x00001e77 },
- { 0x00000330, 0x00001e75 }, { 0x00000303, 0x00001e7d },
- { 0x00000323, 0x00001e7f }, { 0x00000300, 0x00001e81 },
- { 0x00000301, 0x00001e83 }, { 0x00000302, 0x00000175 },
- { 0x00000307, 0x00001e87 }, { 0x00000308, 0x00001e85 },
- { 0x0000030a, 0x00001e98 }, { 0x00000323, 0x00001e89 },
- { 0x00000307, 0x00001e8b }, { 0x00000308, 0x00001e8d },
- { 0x00000300, 0x00001ef3 }, { 0x00000301, 0x000000fd },
- { 0x00000302, 0x00000177 }, { 0x00000303, 0x00001ef9 },
- { 0x00000304, 0x00000233 }, { 0x00000307, 0x00001e8f },
- { 0x00000308, 0x000000ff }, { 0x00000309, 0x00001ef7 },
- { 0x0000030a, 0x00001e99 }, { 0x00000323, 0x00001ef5 },
- { 0x00000301, 0x0000017a }, { 0x00000302, 0x00001e91 },
- { 0x00000307, 0x0000017c }, { 0x0000030c, 0x0000017e },
- { 0x00000323, 0x00001e93 }, { 0x00000331, 0x00001e95 },
- { 0x00000300, 0x00001fed }, { 0x00000301, 0x00000385 },
- { 0x00000342, 0x00001fc1 }, { 0x00000300, 0x00001ea6 },
- { 0x00000301, 0x00001ea4 }, { 0x00000303, 0x00001eaa },
- { 0x00000309, 0x00001ea8 }, { 0x00000304, 0x000001de },
- { 0x00000301, 0x000001fa }, { 0x00000301, 0x000001fc },
- { 0x00000304, 0x000001e2 }, { 0x00000301, 0x00001e08 },
- { 0x00000300, 0x00001ec0 }, { 0x00000301, 0x00001ebe },
- { 0x00000303, 0x00001ec4 }, { 0x00000309, 0x00001ec2 },
- { 0x00000301, 0x00001e2e }, { 0x00000300, 0x00001ed2 },
- { 0x00000301, 0x00001ed0 }, { 0x00000303, 0x00001ed6 },
- { 0x00000309, 0x00001ed4 }, { 0x00000301, 0x00001e4c },
- { 0x00000304, 0x0000022c }, { 0x00000308, 0x00001e4e },
- { 0x00000304, 0x0000022a }, { 0x00000301, 0x000001fe },
- { 0x00000300, 0x000001db }, { 0x00000301, 0x000001d7 },
- { 0x00000304, 0x000001d5 }, { 0x0000030c, 0x000001d9 },
- { 0x00000300, 0x00001ea7 }, { 0x00000301, 0x00001ea5 },
- { 0x00000303, 0x00001eab }, { 0x00000309, 0x00001ea9 },
- { 0x00000304, 0x000001df }, { 0x00000301, 0x000001fb },
- { 0x00000301, 0x000001fd }, { 0x00000304, 0x000001e3 },
- { 0x00000301, 0x00001e09 }, { 0x00000300, 0x00001ec1 },
- { 0x00000301, 0x00001ebf }, { 0x00000303, 0x00001ec5 },
- { 0x00000309, 0x00001ec3 }, { 0x00000301, 0x00001e2f },
- { 0x00000300, 0x00001ed3 }, { 0x00000301, 0x00001ed1 },
- { 0x00000303, 0x00001ed7 }, { 0x00000309, 0x00001ed5 },
- { 0x00000301, 0x00001e4d }, { 0x00000304, 0x0000022d },
- { 0x00000308, 0x00001e4f }, { 0x00000304, 0x0000022b },
- { 0x00000301, 0x000001ff }, { 0x00000300, 0x000001dc },
- { 0x00000301, 0x000001d8 }, { 0x00000304, 0x000001d6 },
- { 0x0000030c, 0x000001da }, { 0x00000300, 0x00001eb0 },
- { 0x00000301, 0x00001eae }, { 0x00000303, 0x00001eb4 },
- { 0x00000309, 0x00001eb2 }, { 0x00000300, 0x00001eb1 },
- { 0x00000301, 0x00001eaf }, { 0x00000303, 0x00001eb5 },
- { 0x00000309, 0x00001eb3 }, { 0x00000300, 0x00001e14 },
- { 0x00000301, 0x00001e16 }, { 0x00000300, 0x00001e15 },
- { 0x00000301, 0x00001e17 }, { 0x00000300, 0x00001e50 },
- { 0x00000301, 0x00001e52 }, { 0x00000300, 0x00001e51 },
- { 0x00000301, 0x00001e53 }, { 0x00000307, 0x00001e64 },
- { 0x00000307, 0x00001e65 }, { 0x00000307, 0x00001e66 },
- { 0x00000307, 0x00001e67 }, { 0x00000301, 0x00001e78 },
- { 0x00000301, 0x00001e79 }, { 0x00000308, 0x00001e7a },
- { 0x00000308, 0x00001e7b }, { 0x00000307, 0x00001e9b },
- { 0x00000300, 0x00001edc }, { 0x00000301, 0x00001eda },
- { 0x00000303, 0x00001ee0 }, { 0x00000309, 0x00001ede },
- { 0x00000323, 0x00001ee2 }, { 0x00000300, 0x00001edd },
- { 0x00000301, 0x00001edb }, { 0x00000303, 0x00001ee1 },
- { 0x00000309, 0x00001edf }, { 0x00000323, 0x00001ee3 },
- { 0x00000300, 0x00001eea }, { 0x00000301, 0x00001ee8 },
- { 0x00000303, 0x00001eee }, { 0x00000309, 0x00001eec },
- { 0x00000323, 0x00001ef0 }, { 0x00000300, 0x00001eeb },
- { 0x00000301, 0x00001ee9 }, { 0x00000303, 0x00001eef },
- { 0x00000309, 0x00001eed }, { 0x00000323, 0x00001ef1 },
- { 0x0000030c, 0x000001ee }, { 0x00000304, 0x000001ec },
- { 0x00000304, 0x000001ed }, { 0x00000304, 0x000001e0 },
- { 0x00000304, 0x000001e1 }, { 0x00000306, 0x00001e1c },
- { 0x00000306, 0x00001e1d }, { 0x00000304, 0x00000230 },
- { 0x00000304, 0x00000231 }, { 0x0000030c, 0x000001ef },
- { 0x00000300, 0x00001fba }, { 0x00000301, 0x00000386 },
- { 0x00000304, 0x00001fb9 }, { 0x00000306, 0x00001fb8 },
- { 0x00000313, 0x00001f08 }, { 0x00000314, 0x00001f09 },
- { 0x00000345, 0x00001fbc }, { 0x00000300, 0x00001fc8 },
- { 0x00000301, 0x00000388 }, { 0x00000313, 0x00001f18 },
- { 0x00000314, 0x00001f19 }, { 0x00000300, 0x00001fca },
- { 0x00000301, 0x00000389 }, { 0x00000313, 0x00001f28 },
- { 0x00000314, 0x00001f29 }, { 0x00000345, 0x00001fcc },
- { 0x00000300, 0x00001fda }, { 0x00000301, 0x0000038a },
- { 0x00000304, 0x00001fd9 }, { 0x00000306, 0x00001fd8 },
- { 0x00000308, 0x000003aa }, { 0x00000313, 0x00001f38 },
- { 0x00000314, 0x00001f39 }, { 0x00000300, 0x00001ff8 },
- { 0x00000301, 0x0000038c }, { 0x00000313, 0x00001f48 },
- { 0x00000314, 0x00001f49 }, { 0x00000314, 0x00001fec },
- { 0x00000300, 0x00001fea }, { 0x00000301, 0x0000038e },
- { 0x00000304, 0x00001fe9 }, { 0x00000306, 0x00001fe8 },
- { 0x00000308, 0x000003ab }, { 0x00000314, 0x00001f59 },
- { 0x00000300, 0x00001ffa }, { 0x00000301, 0x0000038f },
- { 0x00000313, 0x00001f68 }, { 0x00000314, 0x00001f69 },
- { 0x00000345, 0x00001ffc }, { 0x00000345, 0x00001fb4 },
- { 0x00000345, 0x00001fc4 }, { 0x00000300, 0x00001f70 },
- { 0x00000301, 0x000003ac }, { 0x00000304, 0x00001fb1 },
- { 0x00000306, 0x00001fb0 }, { 0x00000313, 0x00001f00 },
- { 0x00000314, 0x00001f01 }, { 0x00000342, 0x00001fb6 },
- { 0x00000345, 0x00001fb3 }, { 0x00000300, 0x00001f72 },
- { 0x00000301, 0x000003ad }, { 0x00000313, 0x00001f10 },
- { 0x00000314, 0x00001f11 }, { 0x00000300, 0x00001f74 },
- { 0x00000301, 0x000003ae }, { 0x00000313, 0x00001f20 },
- { 0x00000314, 0x00001f21 }, { 0x00000342, 0x00001fc6 },
- { 0x00000345, 0x00001fc3 }, { 0x00000300, 0x00001f76 },
- { 0x00000301, 0x000003af }, { 0x00000304, 0x00001fd1 },
- { 0x00000306, 0x00001fd0 }, { 0x00000308, 0x000003ca },
- { 0x00000313, 0x00001f30 }, { 0x00000314, 0x00001f31 },
- { 0x00000342, 0x00001fd6 }, { 0x00000300, 0x00001f78 },
- { 0x00000301, 0x000003cc }, { 0x00000313, 0x00001f40 },
- { 0x00000314, 0x00001f41 }, { 0x00000313, 0x00001fe4 },
- { 0x00000314, 0x00001fe5 }, { 0x00000300, 0x00001f7a },
- { 0x00000301, 0x000003cd }, { 0x00000304, 0x00001fe1 },
- { 0x00000306, 0x00001fe0 }, { 0x00000308, 0x000003cb },
- { 0x00000313, 0x00001f50 }, { 0x00000314, 0x00001f51 },
- { 0x00000342, 0x00001fe6 }, { 0x00000300, 0x00001f7c },
- { 0x00000301, 0x000003ce }, { 0x00000313, 0x00001f60 },
- { 0x00000314, 0x00001f61 }, { 0x00000342, 0x00001ff6 },
- { 0x00000345, 0x00001ff3 }, { 0x00000300, 0x00001fd2 },
- { 0x00000301, 0x00000390 }, { 0x00000342, 0x00001fd7 },
- { 0x00000300, 0x00001fe2 }, { 0x00000301, 0x000003b0 },
- { 0x00000342, 0x00001fe7 }, { 0x00000345, 0x00001ff4 },
- { 0x00000301, 0x000003d3 }, { 0x00000308, 0x000003d4 },
- { 0x00000308, 0x00000407 }, { 0x00000306, 0x000004d0 },
- { 0x00000308, 0x000004d2 }, { 0x00000301, 0x00000403 },
- { 0x00000300, 0x00000400 }, { 0x00000306, 0x000004d6 },
- { 0x00000308, 0x00000401 }, { 0x00000306, 0x000004c1 },
- { 0x00000308, 0x000004dc }, { 0x00000308, 0x000004de },
- { 0x00000300, 0x0000040d }, { 0x00000304, 0x000004e2 },
- { 0x00000306, 0x00000419 }, { 0x00000308, 0x000004e4 },
- { 0x00000301, 0x0000040c }, { 0x00000308, 0x000004e6 },
- { 0x00000304, 0x000004ee }, { 0x00000306, 0x0000040e },
- { 0x00000308, 0x000004f0 }, { 0x0000030b, 0x000004f2 },
- { 0x00000308, 0x000004f4 }, { 0x00000308, 0x000004f8 },
- { 0x00000308, 0x000004ec }, { 0x00000306, 0x000004d1 },
- { 0x00000308, 0x000004d3 }, { 0x00000301, 0x00000453 },
- { 0x00000300, 0x00000450 }, { 0x00000306, 0x000004d7 },
- { 0x00000308, 0x00000451 }, { 0x00000306, 0x000004c2 },
- { 0x00000308, 0x000004dd }, { 0x00000308, 0x000004df },
- { 0x00000300, 0x0000045d }, { 0x00000304, 0x000004e3 },
- { 0x00000306, 0x00000439 }, { 0x00000308, 0x000004e5 },
- { 0x00000301, 0x0000045c }, { 0x00000308, 0x000004e7 },
- { 0x00000304, 0x000004ef }, { 0x00000306, 0x0000045e },
- { 0x00000308, 0x000004f1 }, { 0x0000030b, 0x000004f3 },
- { 0x00000308, 0x000004f5 }, { 0x00000308, 0x000004f9 },
- { 0x00000308, 0x000004ed }, { 0x00000308, 0x00000457 },
- { 0x0000030f, 0x00000476 }, { 0x0000030f, 0x00000477 },
- { 0x00000308, 0x000004da }, { 0x00000308, 0x000004db },
- { 0x00000308, 0x000004ea }, { 0x00000308, 0x000004eb },
- { 0x00000653, 0x00000622 }, { 0x00000654, 0x00000623 },
- { 0x00000655, 0x00000625 }, { 0x00000654, 0x00000624 },
- { 0x00000654, 0x00000626 }, { 0x00000654, 0x000006c2 },
- { 0x00000654, 0x000006d3 }, { 0x00000654, 0x000006c0 },
- { 0x0000093c, 0x00000929 }, { 0x0000093c, 0x00000931 },
- { 0x0000093c, 0x00000934 }, { 0x000009be, 0x000009cb },
- { 0x000009d7, 0x000009cc }, { 0x00000b3e, 0x00000b4b },
- { 0x00000b56, 0x00000b48 }, { 0x00000b57, 0x00000b4c },
- { 0x00000bd7, 0x00000b94 }, { 0x00000bbe, 0x00000bca },
- { 0x00000bd7, 0x00000bcc }, { 0x00000bbe, 0x00000bcb },
- { 0x00000c56, 0x00000c48 }, { 0x00000cd5, 0x00000cc0 },
- { 0x00000cc2, 0x00000cca }, { 0x00000cd5, 0x00000cc7 },
- { 0x00000cd6, 0x00000cc8 }, { 0x00000cd5, 0x00000ccb },
- { 0x00000d3e, 0x00000d4a }, { 0x00000d57, 0x00000d4c },
- { 0x00000d3e, 0x00000d4b }, { 0x00000dca, 0x00000dda },
- { 0x00000dcf, 0x00000ddc }, { 0x00000ddf, 0x00000dde },
- { 0x00000dca, 0x00000ddd }, { 0x0000102e, 0x00001026 },
- { 0x00000304, 0x00001e38 }, { 0x00000304, 0x00001e39 },
- { 0x00000304, 0x00001e5c }, { 0x00000304, 0x00001e5d },
- { 0x00000307, 0x00001e68 }, { 0x00000307, 0x00001e69 },
- { 0x00000302, 0x00001eac }, { 0x00000306, 0x00001eb6 },
- { 0x00000302, 0x00001ead }, { 0x00000306, 0x00001eb7 },
- { 0x00000302, 0x00001ec6 }, { 0x00000302, 0x00001ec7 },
- { 0x00000302, 0x00001ed8 }, { 0x00000302, 0x00001ed9 },
- { 0x00000300, 0x00001f02 }, { 0x00000301, 0x00001f04 },
- { 0x00000342, 0x00001f06 }, { 0x00000345, 0x00001f80 },
- { 0x00000300, 0x00001f03 }, { 0x00000301, 0x00001f05 },
- { 0x00000342, 0x00001f07 }, { 0x00000345, 0x00001f81 },
- { 0x00000345, 0x00001f82 }, { 0x00000345, 0x00001f83 },
- { 0x00000345, 0x00001f84 }, { 0x00000345, 0x00001f85 },
- { 0x00000345, 0x00001f86 }, { 0x00000345, 0x00001f87 },
- { 0x00000300, 0x00001f0a }, { 0x00000301, 0x00001f0c },
- { 0x00000342, 0x00001f0e }, { 0x00000345, 0x00001f88 },
- { 0x00000300, 0x00001f0b }, { 0x00000301, 0x00001f0d },
- { 0x00000342, 0x00001f0f }, { 0x00000345, 0x00001f89 },
- { 0x00000345, 0x00001f8a }, { 0x00000345, 0x00001f8b },
- { 0x00000345, 0x00001f8c }, { 0x00000345, 0x00001f8d },
- { 0x00000345, 0x00001f8e }, { 0x00000345, 0x00001f8f },
- { 0x00000300, 0x00001f12 }, { 0x00000301, 0x00001f14 },
- { 0x00000300, 0x00001f13 }, { 0x00000301, 0x00001f15 },
- { 0x00000300, 0x00001f1a }, { 0x00000301, 0x00001f1c },
- { 0x00000300, 0x00001f1b }, { 0x00000301, 0x00001f1d },
- { 0x00000300, 0x00001f22 }, { 0x00000301, 0x00001f24 },
- { 0x00000342, 0x00001f26 }, { 0x00000345, 0x00001f90 },
- { 0x00000300, 0x00001f23 }, { 0x00000301, 0x00001f25 },
- { 0x00000342, 0x00001f27 }, { 0x00000345, 0x00001f91 },
- { 0x00000345, 0x00001f92 }, { 0x00000345, 0x00001f93 },
- { 0x00000345, 0x00001f94 }, { 0x00000345, 0x00001f95 },
- { 0x00000345, 0x00001f96 }, { 0x00000345, 0x00001f97 },
- { 0x00000300, 0x00001f2a }, { 0x00000301, 0x00001f2c },
- { 0x00000342, 0x00001f2e }, { 0x00000345, 0x00001f98 },
- { 0x00000300, 0x00001f2b }, { 0x00000301, 0x00001f2d },
- { 0x00000342, 0x00001f2f }, { 0x00000345, 0x00001f99 },
- { 0x00000345, 0x00001f9a }, { 0x00000345, 0x00001f9b },
- { 0x00000345, 0x00001f9c }, { 0x00000345, 0x00001f9d },
- { 0x00000345, 0x00001f9e }, { 0x00000345, 0x00001f9f },
- { 0x00000300, 0x00001f32 }, { 0x00000301, 0x00001f34 },
- { 0x00000342, 0x00001f36 }, { 0x00000300, 0x00001f33 },
- { 0x00000301, 0x00001f35 }, { 0x00000342, 0x00001f37 },
- { 0x00000300, 0x00001f3a }, { 0x00000301, 0x00001f3c },
- { 0x00000342, 0x00001f3e }, { 0x00000300, 0x00001f3b },
- { 0x00000301, 0x00001f3d }, { 0x00000342, 0x00001f3f },
- { 0x00000300, 0x00001f42 }, { 0x00000301, 0x00001f44 },
- { 0x00000300, 0x00001f43 }, { 0x00000301, 0x00001f45 },
- { 0x00000300, 0x00001f4a }, { 0x00000301, 0x00001f4c },
- { 0x00000300, 0x00001f4b }, { 0x00000301, 0x00001f4d },
- { 0x00000300, 0x00001f52 }, { 0x00000301, 0x00001f54 },
- { 0x00000342, 0x00001f56 }, { 0x00000300, 0x00001f53 },
- { 0x00000301, 0x00001f55 }, { 0x00000342, 0x00001f57 },
- { 0x00000300, 0x00001f5b }, { 0x00000301, 0x00001f5d },
- { 0x00000342, 0x00001f5f }, { 0x00000300, 0x00001f62 },
- { 0x00000301, 0x00001f64 }, { 0x00000342, 0x00001f66 },
- { 0x00000345, 0x00001fa0 }, { 0x00000300, 0x00001f63 },
- { 0x00000301, 0x00001f65 }, { 0x00000342, 0x00001f67 },
- { 0x00000345, 0x00001fa1 }, { 0x00000345, 0x00001fa2 },
- { 0x00000345, 0x00001fa3 }, { 0x00000345, 0x00001fa4 },
- { 0x00000345, 0x00001fa5 }, { 0x00000345, 0x00001fa6 },
- { 0x00000345, 0x00001fa7 }, { 0x00000300, 0x00001f6a },
- { 0x00000301, 0x00001f6c }, { 0x00000342, 0x00001f6e },
- { 0x00000345, 0x00001fa8 }, { 0x00000300, 0x00001f6b },
- { 0x00000301, 0x00001f6d }, { 0x00000342, 0x00001f6f },
- { 0x00000345, 0x00001fa9 }, { 0x00000345, 0x00001faa },
- { 0x00000345, 0x00001fab }, { 0x00000345, 0x00001fac },
- { 0x00000345, 0x00001fad }, { 0x00000345, 0x00001fae },
- { 0x00000345, 0x00001faf }, { 0x00000345, 0x00001fb2 },
- { 0x00000345, 0x00001fc2 }, { 0x00000345, 0x00001ff2 },
- { 0x00000345, 0x00001fb7 }, { 0x00000300, 0x00001fcd },
- { 0x00000301, 0x00001fce }, { 0x00000342, 0x00001fcf },
- { 0x00000345, 0x00001fc7 }, { 0x00000345, 0x00001ff7 },
- { 0x00000300, 0x00001fdd }, { 0x00000301, 0x00001fde },
- { 0x00000342, 0x00001fdf }, { 0x00000338, 0x0000219a },
- { 0x00000338, 0x0000219b }, { 0x00000338, 0x000021ae },
- { 0x00000338, 0x000021cd }, { 0x00000338, 0x000021cf },
- { 0x00000338, 0x000021ce }, { 0x00000338, 0x00002204 },
- { 0x00000338, 0x00002209 }, { 0x00000338, 0x0000220c },
- { 0x00000338, 0x00002224 }, { 0x00000338, 0x00002226 },
- { 0x00000338, 0x00002241 }, { 0x00000338, 0x00002244 },
- { 0x00000338, 0x00002247 }, { 0x00000338, 0x00002249 },
- { 0x00000338, 0x0000226d }, { 0x00000338, 0x00002262 },
- { 0x00000338, 0x00002270 }, { 0x00000338, 0x00002271 },
- { 0x00000338, 0x00002274 }, { 0x00000338, 0x00002275 },
- { 0x00000338, 0x00002278 }, { 0x00000338, 0x00002279 },
- { 0x00000338, 0x00002280 }, { 0x00000338, 0x00002281 },
- { 0x00000338, 0x000022e0 }, { 0x00000338, 0x000022e1 },
- { 0x00000338, 0x00002284 }, { 0x00000338, 0x00002285 },
- { 0x00000338, 0x00002288 }, { 0x00000338, 0x00002289 },
- { 0x00000338, 0x000022e2 }, { 0x00000338, 0x000022e3 },
- { 0x00000338, 0x000022ac }, { 0x00000338, 0x000022ad },
- { 0x00000338, 0x000022ae }, { 0x00000338, 0x000022af },
- { 0x00000338, 0x000022ea }, { 0x00000338, 0x000022eb },
- { 0x00000338, 0x000022ec }, { 0x00000338, 0x000022ed },
- { 0x00003099, 0x00003094 }, { 0x00003099, 0x0000304c },
- { 0x00003099, 0x0000304e }, { 0x00003099, 0x00003050 },
- { 0x00003099, 0x00003052 }, { 0x00003099, 0x00003054 },
- { 0x00003099, 0x00003056 }, { 0x00003099, 0x00003058 },
- { 0x00003099, 0x0000305a }, { 0x00003099, 0x0000305c },
- { 0x00003099, 0x0000305e }, { 0x00003099, 0x00003060 },
- { 0x00003099, 0x00003062 }, { 0x00003099, 0x00003065 },
- { 0x00003099, 0x00003067 }, { 0x00003099, 0x00003069 },
- { 0x00003099, 0x00003070 }, { 0x0000309a, 0x00003071 },
- { 0x00003099, 0x00003073 }, { 0x0000309a, 0x00003074 },
- { 0x00003099, 0x00003076 }, { 0x0000309a, 0x00003077 },
- { 0x00003099, 0x00003079 }, { 0x0000309a, 0x0000307a },
- { 0x00003099, 0x0000307c }, { 0x0000309a, 0x0000307d },
- { 0x00003099, 0x0000309e }, { 0x00003099, 0x000030f4 },
- { 0x00003099, 0x000030ac }, { 0x00003099, 0x000030ae },
- { 0x00003099, 0x000030b0 }, { 0x00003099, 0x000030b2 },
- { 0x00003099, 0x000030b4 }, { 0x00003099, 0x000030b6 },
- { 0x00003099, 0x000030b8 }, { 0x00003099, 0x000030ba },
- { 0x00003099, 0x000030bc }, { 0x00003099, 0x000030be },
- { 0x00003099, 0x000030c0 }, { 0x00003099, 0x000030c2 },
- { 0x00003099, 0x000030c5 }, { 0x00003099, 0x000030c7 },
- { 0x00003099, 0x000030c9 }, { 0x00003099, 0x000030d0 },
- { 0x0000309a, 0x000030d1 }, { 0x00003099, 0x000030d3 },
- { 0x0000309a, 0x000030d4 }, { 0x00003099, 0x000030d6 },
- { 0x0000309a, 0x000030d7 }, { 0x00003099, 0x000030d9 },
- { 0x0000309a, 0x000030da }, { 0x00003099, 0x000030dc },
- { 0x0000309a, 0x000030dd }, { 0x00003099, 0x000030f7 },
- { 0x00003099, 0x000030f8 }, { 0x00003099, 0x000030f9 },
- { 0x00003099, 0x000030fa }, { 0x00003099, 0x000030fe },
-};
-
-
-/*
- * Canonical/Compatibility Decomposition
- */
-
-#define DECOMP_BITS_0 9
-#define DECOMP_BITS_1 7
-#define DECOMP_BITS_2 5
-#define DECOMP_COMPAT 32768
-
-static const char16_t decompose_imap[] = {
- 272, 400, 528, 656, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 912,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 1040, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 1168,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 0, 0, 0, 0, 0, 1, 2, 3,
- 4, 5, 6, 7, 0, 8, 9, 10,
- 11, 12, 0, 0, 0, 13, 14, 15,
- 0, 0, 16, 17, 18, 19, 20, 21,
- 22, 23, 24, 25, 0, 0, 26, 27,
- 0, 0, 0, 0, 28, 0, 0, 0,
- 0, 29, 0, 30, 0, 0, 31, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 32, 33, 0, 0, 0, 34, 0,
- 0, 35, 36, 0, 0, 0, 0, 0,
- 0, 0, 37, 0, 38, 0, 39, 0,
- 0, 0, 40, 0, 0, 0, 41, 0,
- 0, 0, 42, 0, 0, 0, 43, 0,
- 0, 44, 0, 0, 0, 45, 46, 0,
- 47, 0, 48, 49, 50, 51, 0, 0,
- 0, 52, 0, 0, 0, 0, 0, 53,
- 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,
- 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, 54, 55, 56, 57, 58, 0, 0,
- 59, 60, 61, 62, 63, 64, 65, 66,
- 67, 68, 69, 70, 71, 72, 73, 74,
- 75, 76, 77, 78, 79, 80, 0, 0,
- 81, 82, 83, 84, 85, 86, 87, 0,
- 88, 89, 90, 91, 92, 93, 0, 94,
- 0, 95, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 96, 97, 98, 99, 100,
- 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,
- 101, 0, 0, 102, 0, 0, 103, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 104, 0, 0, 0, 0,
- 0, 0, 0, 0, 105, 0, 0, 106,
- 107, 108, 109, 110, 111, 112, 113, 0,
- 114, 115, 116, 117, 118, 119, 120, 121,
- 0, 122, 123, 124, 125, 0, 0, 0,
- 126, 127, 128, 129, 130, 131, 132, 133,
- 134, 135, 136, 137, 138, 139, 140, 141,
- 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,
- 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,
- 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,
- 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,
- 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,
- 142, 143, 144, 145, 146, 147, 148, 149,
- 150, 151, 152, 153, 154, 155, 156, 0,
- 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,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 197, 198, 0, 199, 200, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 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,
- 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,
- 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,
- 233, 234, 235, 236, 237, 238, 239, 240,
- 241, 242, 243, 244, 245, 246, 247, 248,
- 249, 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,
-};
-
-static const struct {
- char16_t tbl[32];
-} decompose_table[] = {
- {{
- 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,
- }},
- {{
- 32769, 0, 0, 0, 0, 0, 0, 0,
- 32770, 0, 32772, 0, 0, 0, 0, 32773,
- 0, 0, 32775, 32776, 32777, 32779, 0, 0,
- 32780, 32782, 32783, 0, 32784, 32787, 32790, 0,
- }},
- {{
- 25, 27, 29, 31, 33, 35, 0, 37,
- 39, 41, 43, 45, 47, 49, 51, 53,
- 0, 55, 57, 59, 61, 63, 65, 0,
- 0, 67, 69, 71, 73, 75, 0, 0,
- }},
- {{
- 77, 79, 81, 83, 85, 87, 0, 89,
- 91, 93, 95, 97, 99, 101, 103, 105,
- 0, 107, 109, 111, 113, 115, 117, 0,
- 0, 119, 121, 123, 125, 127, 0, 129,
- }},
- {{
- 131, 133, 135, 137, 139, 141, 143, 145,
- 147, 149, 151, 153, 155, 157, 159, 161,
- 0, 0, 163, 165, 167, 169, 171, 173,
- 175, 177, 179, 181, 183, 185, 187, 189,
- }},
- {{
- 191, 193, 195, 197, 199, 201, 0, 0,
- 203, 205, 207, 209, 211, 213, 215, 217,
- 219, 0, 32989, 32991, 225, 227, 229, 231,
- 0, 233, 235, 237, 239, 241, 243, 33013,
- }},
- {{
- 33015, 0, 0, 249, 251, 253, 255, 257,
- 259, 33029, 0, 0, 263, 265, 267, 269,
- 271, 273, 0, 0, 275, 277, 279, 281,
- 283, 285, 287, 289, 291, 293, 295, 297,
- }},
- {{
- 299, 301, 303, 305, 307, 309, 0, 0,
- 311, 313, 315, 317, 319, 321, 323, 325,
- 327, 329, 331, 333, 335, 337, 339, 341,
- 343, 345, 347, 349, 351, 353, 355, 33125,
- }},
- {{
- 358, 360, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 362,
- 364, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 33134, 33136, 33138, 33140,
- 33142, 33144, 33146, 33148, 33150, 384, 386, 388,
- 390, 392, 394, 396, 398, 400, 402, 404,
- 406, 408, 410, 412, 414, 0, 416, 418,
- }},
- {{
- 420, 422, 424, 426, 0, 0, 428, 430,
- 432, 434, 436, 438, 440, 442, 444, 446,
- 448, 33218, 33220, 33222, 456, 458, 0, 0,
- 460, 462, 464, 466, 468, 470, 472, 474,
- }},
- {{
- 476, 478, 480, 482, 484, 486, 488, 490,
- 492, 494, 496, 498, 500, 502, 504, 506,
- 508, 510, 512, 514, 516, 518, 520, 522,
- 524, 526, 528, 530, 0, 0, 532, 534,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 536, 538,
- 540, 542, 544, 546, 548, 550, 552, 554,
- 556, 558, 560, 562, 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,
- 33332, 33333, 33334, 33335, 33336, 33337, 33338, 33339,
- 33340, 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,
- 33341, 33343, 33345, 33347, 33349, 33351, 0, 0,
- }},
- {{
- 33353, 33354, 33355, 33356, 33357, 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,
- }},
- {{
- 590, 591, 0, 592, 593, 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, 595, 0, 0, 0,
- 0, 0, 33364, 0, 0, 0, 598, 0,
- }},
- {{
- 0, 0, 0, 0, 33367, 601, 603, 605,
- 606, 608, 610, 0, 612, 0, 614, 616,
- 618, 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, 620, 622, 624, 626, 628, 630,
- 632, 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, 634, 636, 638, 640, 642, 0,
- 33412, 33413, 33414, 647, 649, 33419, 33420, 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,
- 33421, 33422, 33423, 0, 33424, 33425, 0, 0,
- 0, 33426, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 659, 661, 0, 663, 0, 0, 0, 665,
- 0, 0, 0, 0, 667, 669, 671, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 673, 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, 675, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 677, 679, 0, 681, 0, 0, 0, 683,
- 0, 0, 0, 0, 685, 687, 689, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 691, 693,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 695, 697, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 699, 701, 703, 705, 0, 0, 707, 709,
- 0, 0, 711, 713, 715, 717, 719, 721,
- }},
- {{
- 0, 0, 723, 725, 727, 729, 731, 733,
- 0, 0, 735, 737, 739, 741, 743, 745,
- 747, 749, 751, 753, 755, 757, 0, 0,
- 759, 761, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 33531,
- 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, 765, 767, 769, 771, 773, 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, 33543, 33545, 33547,
- 33549, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 783, 0, 785, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 787, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 789, 0, 0, 0, 0, 0, 0,
- 0, 791, 0, 0, 793, 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,
- 795, 797, 799, 801, 803, 805, 807, 809,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 811, 813, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 815, 817, 0, 819,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 821, 0, 0, 823, 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, 825, 827, 829, 0, 0, 831, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 833, 0, 0, 835, 837, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 839, 841, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 843, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 845, 847, 849, 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,
- 851, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 853, 0, 0, 0, 0, 0, 0, 855,
- 857, 0, 859, 861, 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, 863, 865, 867, 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, 869, 0, 871, 873, 875, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 33645, 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, 33647, 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, 33649, 33651, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 33653, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 886, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 888, 0, 0,
- 0, 0, 890, 0, 0, 0, 0, 892,
- 0, 0, 0, 0, 894, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 896, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 898, 0, 900, 902, 33672,
- 906, 33676, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 910, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 912, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 914, 0, 0,
- }},
- {{
- 0, 0, 916, 0, 0, 0, 0, 918,
- 0, 0, 0, 0, 920, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 922, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 924, 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, 33694, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 33695, 33696, 33697, 0,
- 33698, 33699, 33700, 33701, 33702, 33703, 33704, 33705,
- 33706, 33707, 33708, 0, 33709, 33710, 33711, 33712,
- }},
- {{
- 33713, 33714, 33715, 33716, 33717, 33718, 33719, 33720,
- 33721, 33722, 33723, 33724, 33725, 33726, 0, 33727,
- 33728, 33729, 33730, 33731, 33732, 33733, 33734, 33735,
- 33736, 33737, 33738, 33739, 33740, 33741, 33742, 33743,
- }},
- {{
- 33744, 33745, 33746, 33747, 33748, 33749, 33750, 33751,
- 33752, 33753, 33754, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 33755, 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, 33756, 33757, 33758, 33759, 33760,
- }},
- {{
- 33761, 33762, 33763, 33764, 33765, 33766, 33767, 33768,
- 33769, 33770, 33771, 33772, 33773, 33774, 33775, 33776,
- 33777, 33778, 33779, 33780, 33781, 33782, 33783, 33784,
- 33785, 33786, 33787, 33788, 33789, 33790, 33791, 33792,
- }},
- {{
- 1025, 1027, 1029, 1031, 1033, 1035, 1037, 1039,
- 1041, 1043, 1045, 1047, 1049, 1051, 1053, 1055,
- 1057, 1059, 1061, 1063, 1065, 1067, 1069, 1071,
- 1073, 1075, 1077, 1079, 1081, 1083, 1085, 1087,
- }},
- {{
- 1089, 1091, 1093, 1095, 1097, 1099, 1101, 1103,
- 1105, 1107, 1109, 1111, 1113, 1115, 1117, 1119,
- 1121, 1123, 1125, 1127, 1129, 1131, 1133, 1135,
- 1137, 1139, 1141, 1143, 1145, 1147, 1149, 1151,
- }},
- {{
- 1153, 1155, 1157, 1159, 1161, 1163, 1165, 1167,
- 1169, 1171, 1173, 1175, 1177, 1179, 1181, 1183,
- 1185, 1187, 1189, 1191, 1193, 1195, 1197, 1199,
- 1201, 1203, 1205, 1207, 1209, 1211, 1213, 1215,
- }},
- {{
- 1217, 1219, 1221, 1223, 1225, 1227, 1229, 1231,
- 1233, 1235, 1237, 1239, 1241, 1243, 1245, 1247,
- 1249, 1251, 1253, 1255, 1257, 1259, 1261, 1263,
- 1265, 1267, 1269, 1271, 1273, 1275, 1277, 1279,
- }},
- {{
- 1281, 1283, 1285, 1287, 1289, 1291, 1293, 1295,
- 1297, 1299, 1301, 1303, 1305, 1307, 1309, 1311,
- 1313, 1315, 1317, 1319, 1321, 1323, 1325, 1327,
- 1329, 1331, 34101, 1335, 0, 0, 0, 0,
- }},
- {{
- 1337, 1339, 1341, 1343, 1345, 1347, 1349, 1351,
- 1353, 1355, 1357, 1359, 1361, 1363, 1365, 1367,
- 1369, 1371, 1373, 1375, 1377, 1379, 1381, 1383,
- 1385, 1387, 1389, 1391, 1393, 1395, 1397, 1399,
- }},
- {{
- 1401, 1403, 1405, 1407, 1409, 1411, 1413, 1415,
- 1417, 1419, 1421, 1423, 1425, 1427, 1429, 1431,
- 1433, 1435, 1437, 1439, 1441, 1443, 1445, 1447,
- 1449, 1451, 1453, 1455, 1457, 1459, 1461, 1463,
- }},
- {{
- 1465, 1467, 1469, 1471, 1473, 1475, 1477, 1479,
- 1481, 1483, 1485, 1487, 1489, 1491, 1493, 1495,
- 1497, 1499, 1501, 1503, 1505, 1507, 1509, 1511,
- 1513, 1515, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 1517, 1519, 1521, 1523, 1525, 1527, 1529, 1531,
- 1533, 1535, 1537, 1539, 1541, 1543, 1545, 1547,
- 1549, 1551, 1553, 1555, 1557, 1559, 0, 0,
- 1561, 1563, 1565, 1567, 1569, 1571, 0, 0,
- }},
- {{
- 1573, 1575, 1577, 1579, 1581, 1583, 1585, 1587,
- 1589, 1591, 1593, 1595, 1597, 1599, 1601, 1603,
- 1605, 1607, 1609, 1611, 1613, 1615, 1617, 1619,
- 1621, 1623, 1625, 1627, 1629, 1631, 1633, 1635,
- }},
- {{
- 1637, 1639, 1641, 1643, 1645, 1647, 0, 0,
- 1649, 1651, 1653, 1655, 1657, 1659, 0, 0,
- 1661, 1663, 1665, 1667, 1669, 1671, 1673, 1675,
- 0, 1677, 0, 1679, 0, 1681, 0, 1683,
- }},
- {{
- 1685, 1687, 1689, 1691, 1693, 1695, 1697, 1699,
- 1701, 1703, 1705, 1707, 1709, 1711, 1713, 1715,
- 1717, 1719, 1720, 1722, 1723, 1725, 1726, 1728,
- 1729, 1731, 1732, 1734, 1735, 1737, 0, 0,
- }},
- {{
- 1738, 1740, 1742, 1744, 1746, 1748, 1750, 1752,
- 1754, 1756, 1758, 1760, 1762, 1764, 1766, 1768,
- 1770, 1772, 1774, 1776, 1778, 1780, 1782, 1784,
- 1786, 1788, 1790, 1792, 1794, 1796, 1798, 1800,
- }},
- {{
- 1802, 1804, 1806, 1808, 1810, 1812, 1814, 1816,
- 1818, 1820, 1822, 1824, 1826, 1828, 1830, 1832,
- 1834, 1836, 1838, 1840, 1842, 0, 1844, 1846,
- 1848, 1850, 1852, 1854, 1855, 34625, 1859, 34628,
- }},
- {{
- 34630, 1864, 1866, 1868, 1870, 0, 1872, 1874,
- 1876, 1878, 1879, 1881, 1882, 1884, 1886, 1888,
- 1890, 1892, 1894, 1896, 0, 0, 1897, 1899,
- 1901, 1903, 1905, 1907, 0, 1908, 1910, 1912,
- }},
- {{
- 1914, 1916, 1918, 1920, 1921, 1923, 1925, 1927,
- 1929, 1931, 1933, 1935, 1936, 1938, 1940, 1941,
- 0, 0, 1942, 1944, 1946, 0, 1948, 1950,
- 1952, 1954, 1955, 1957, 1958, 1960, 34729, 0,
- }},
- {{
- 1963, 1964, 34733, 34734, 34735, 34736, 34737, 34738,
- 34739, 34740, 34741, 0, 0, 0, 0, 0,
- 0, 34742, 0, 0, 0, 0, 0, 34743,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 34745, 34746, 34748, 0,
- 0, 0, 0, 0, 0, 0, 0, 34751,
- 0, 0, 0, 34752, 34754, 0, 34757, 34759,
- 0, 0, 0, 0, 34762, 0, 34764, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 34766,
- 34768, 34770, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 34772,
- 0, 0, 0, 0, 0, 0, 0, 34776,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 34777, 34778, 0, 0, 34779, 34780, 34781, 34782,
- 34783, 34784, 34785, 34786, 34787, 34788, 34789, 34790,
- }},
- {{
- 34791, 34792, 34793, 34794, 34795, 34796, 34797, 34798,
- 34799, 34800, 34801, 34802, 34803, 34804, 34805, 0,
- 34806, 34807, 34808, 34809, 34810, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 34811, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 34813, 34816, 34819, 34820, 0, 34822, 34825, 34828,
- 0, 34829, 34831, 34832, 34833, 34834, 34835, 34836,
- 34837, 34838, 34839, 34840, 0, 34841, 34842, 0,
- 0, 34844, 34845, 34846, 34847, 34848, 0, 0,
- }},
- {{
- 34849, 34851, 34854, 0, 34856, 0, 2089, 0,
- 34858, 0, 2091, 2092, 34861, 34862, 0, 34863,
- 34864, 34865, 0, 34866, 34867, 34868, 34869, 34870,
- 34871, 34872, 0, 34873, 34876, 34877, 34878, 34879,
- }},
- {{
- 34880, 0, 0, 0, 0, 34881, 34882, 34883,
- 34884, 34885, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 34886, 34889, 34892, 34895, 34898,
- 34901, 34904, 34907, 34910, 34913, 34916, 34919, 34922,
- }},
- {{
- 34924, 34925, 34927, 34930, 34932, 34933, 34935, 34938,
- 34942, 34944, 34945, 34947, 34950, 34951, 34952, 34953,
- 34954, 34955, 34957, 34960, 34962, 34963, 34965, 34968,
- 34972, 34974, 34975, 34977, 34980, 34981, 34982, 34983,
- }},
- {{
- 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, 2216, 2218, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 2220, 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, 2222, 2224, 2226,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 2228, 0, 0, 0,
- 0, 2230, 0, 0, 2232, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 2234, 0, 2236, 0,
- 0, 0, 0, 0, 35006, 35008, 0, 35011,
- 35013, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 2248, 0, 0, 2250, 0, 0, 2252,
- 0, 2254, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2256, 0, 2258, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 2260, 2262, 2264,
- 2266, 2268, 0, 0, 2270, 2272, 0, 0,
- 2274, 2276, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2278, 2280, 0, 0, 2282, 2284, 0, 0,
- 2286, 2288, 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, 2290, 2292, 2294, 2296,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2298, 2300, 2302, 2304, 0, 0, 0, 0,
- 0, 0, 2306, 2308, 2310, 2312, 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, 2314, 2315, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 35084, 35085, 35086, 35087, 35088, 35089, 35090, 35091,
- 35092, 35093, 35095, 35097, 35099, 35101, 35103, 35105,
- 35107, 35109, 35111, 35113, 35115, 35118, 35121, 35124,
- 35127, 35130, 35133, 35136, 35139, 35142, 35146, 35150,
- }},
- {{
- 35154, 35158, 35162, 35166, 35170, 35174, 35178, 35182,
- 35186, 35188, 35190, 35192, 35194, 35196, 35198, 35200,
- 35202, 35204, 35207, 35210, 35213, 35216, 35219, 35222,
- 35225, 35228, 35231, 35234, 35237, 35240, 35243, 35246,
- }},
- {{
- 35249, 35252, 35255, 35258, 35261, 35264, 35267, 35270,
- 35273, 35276, 35279, 35282, 35285, 35288, 35291, 35294,
- 35297, 35300, 35303, 35306, 35309, 35312, 35315, 35316,
- 35317, 35318, 35319, 35320, 35321, 35322, 35323, 35324,
- }},
- {{
- 35325, 35326, 35327, 35328, 35329, 35330, 35331, 35332,
- 35333, 35334, 35335, 35336, 35337, 35338, 35339, 35340,
- 35341, 35342, 35343, 35344, 35345, 35346, 35347, 35348,
- 35349, 35350, 35351, 35352, 35353, 35354, 35355, 35356,
- }},
- {{
- 35357, 35358, 35359, 35360, 35361, 35362, 35363, 35364,
- 35365, 35366, 35367, 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, 35368, 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, 35372, 35375, 35377, 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, 2612, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 35382,
- 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, 35383,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 35384, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 35385, 35386, 35387, 35388, 35389, 35390, 35391, 35392,
- 35393, 35394, 35395, 35396, 35397, 35398, 35399, 35400,
- 35401, 35402, 35403, 35404, 35405, 35406, 35407, 35408,
- 35409, 35410, 35411, 35412, 35413, 35414, 35415, 35416,
- }},
- {{
- 35417, 35418, 35419, 35420, 35421, 35422, 35423, 35424,
- 35425, 35426, 35427, 35428, 35429, 35430, 35431, 35432,
- 35433, 35434, 35435, 35436, 35437, 35438, 35439, 35440,
- 35441, 35442, 35443, 35444, 35445, 35446, 35447, 35448,
- }},
- {{
- 35449, 35450, 35451, 35452, 35453, 35454, 35455, 35456,
- 35457, 35458, 35459, 35460, 35461, 35462, 35463, 35464,
- 35465, 35466, 35467, 35468, 35469, 35470, 35471, 35472,
- 35473, 35474, 35475, 35476, 35477, 35478, 35479, 35480,
- }},
- {{
- 35481, 35482, 35483, 35484, 35485, 35486, 35487, 35488,
- 35489, 35490, 35491, 35492, 35493, 35494, 35495, 35496,
- 35497, 35498, 35499, 35500, 35501, 35502, 35503, 35504,
- 35505, 35506, 35507, 35508, 35509, 35510, 35511, 35512,
- }},
- {{
- 35513, 35514, 35515, 35516, 35517, 35518, 35519, 35520,
- 35521, 35522, 35523, 35524, 35525, 35526, 35527, 35528,
- 35529, 35530, 35531, 35532, 35533, 35534, 35535, 35536,
- 35537, 35538, 35539, 35540, 35541, 35542, 35543, 35544,
- }},
- {{
- 35545, 35546, 35547, 35548, 35549, 35550, 35551, 35552,
- 35553, 35554, 35555, 35556, 35557, 35558, 35559, 35560,
- 35561, 35562, 35563, 35564, 35565, 35566, 35567, 35568,
- 35569, 35570, 35571, 35572, 35573, 35574, 35575, 35576,
- }},
- {{
- 35577, 35578, 35579, 35580, 35581, 35582, 35583, 35584,
- 35585, 35586, 35587, 35588, 35589, 35590, 35591, 35592,
- 35593, 35594, 35595, 35596, 35597, 35598, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 35599, 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, 35600, 0,
- 35601, 35602, 35603, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 2836, 0, 2838, 0,
- 2840, 0, 2842, 0, 2844, 0, 2846, 0,
- 2848, 0, 2850, 0, 2852, 0, 2854, 0,
- }},
- {{
- 2856, 0, 2858, 0, 0, 2860, 0, 2862,
- 0, 2864, 0, 0, 0, 0, 0, 0,
- 2866, 2868, 0, 2870, 2872, 0, 2874, 2876,
- 0, 2878, 2880, 0, 2882, 2884, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 2886, 0, 0, 0,
- 0, 0, 0, 35656, 35658, 0, 2892, 35662,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 2896, 0, 2898, 0,
- 2900, 0, 2902, 0, 2904, 0, 2906, 0,
- 2908, 0, 2910, 0, 2912, 0, 2914, 0,
- }},
- {{
- 2916, 0, 2918, 0, 0, 2920, 0, 2922,
- 0, 2924, 0, 0, 0, 0, 0, 0,
- 2926, 2928, 0, 2930, 2932, 0, 2934, 2936,
- 0, 2938, 2940, 0, 2942, 2944, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 2946, 0, 0, 2948,
- 2950, 2952, 2954, 0, 0, 0, 2956, 35726,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 35728, 35729, 35730, 35731, 35732, 35733, 35734,
- 35735, 35736, 35737, 35738, 35739, 35740, 35741, 35742,
- }},
- {{
- 35743, 35744, 35745, 35746, 35747, 35748, 35749, 35750,
- 35751, 35752, 35753, 35754, 35755, 35756, 35757, 35758,
- 35759, 35760, 35761, 35762, 35763, 35764, 35765, 35766,
- 35767, 35768, 35769, 35770, 35771, 35772, 35773, 35774,
- }},
- {{
- 35775, 35776, 35777, 35778, 35779, 35780, 35781, 35782,
- 35783, 35784, 35785, 35786, 35787, 35788, 35789, 35790,
- 35791, 35792, 35793, 35794, 35795, 35796, 35797, 35798,
- 35799, 35800, 35801, 35802, 35803, 35804, 35805, 35806,
- }},
- {{
- 35807, 35808, 35809, 35810, 35811, 35812, 35813, 35814,
- 35815, 35816, 35817, 35818, 35819, 35820, 35821, 0,
- 0, 0, 35822, 35823, 35824, 35825, 35826, 35827,
- 35828, 35829, 35830, 35831, 35832, 35833, 35834, 35835,
- }},
- {{
- 35836, 35839, 35842, 35845, 35848, 35851, 35854, 35857,
- 35860, 35863, 35866, 35869, 35872, 35875, 35878, 35882,
- 35886, 35890, 35894, 35898, 35902, 35906, 35910, 35914,
- 35918, 35922, 35926, 35930, 35934, 35938, 35945, 0,
- }},
- {{
- 35951, 35954, 35957, 35960, 35963, 35966, 35969, 35972,
- 35975, 35978, 35981, 35984, 35987, 35990, 35993, 35996,
- 35999, 36002, 36005, 36008, 36011, 36014, 36017, 36020,
- 36023, 36026, 36029, 36032, 36035, 36038, 36041, 36044,
- }},
- {{
- 36047, 36050, 36053, 36056, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 36059, 36062, 36064, 36066, 36068, 36070, 36072, 36074,
- 36076, 36078, 36080, 36082, 36084, 36086, 36088, 36090,
- }},
- {{
- 36092, 36093, 36094, 36095, 36096, 36097, 36098, 36099,
- 36100, 36101, 36102, 36103, 36104, 36105, 36106, 36108,
- 36110, 36112, 36114, 36116, 36118, 36120, 36122, 36124,
- 36126, 36128, 36130, 36132, 36134, 36139, 36143, 0,
- }},
- {{
- 36145, 36146, 36147, 36148, 36149, 36150, 36151, 36152,
- 36153, 36154, 36155, 36156, 36157, 36158, 36159, 36160,
- 36161, 36162, 36163, 36164, 36165, 36166, 36167, 36168,
- 36169, 36170, 36171, 36172, 36173, 36174, 36175, 36176,
- }},
- {{
- 36177, 36178, 36179, 36180, 36181, 36182, 36183, 36184,
- 36185, 36186, 36187, 36188, 36189, 36190, 36191, 36192,
- 36193, 36194, 36196, 36198, 36200, 36202, 36204, 36206,
- 36208, 36210, 36212, 36214, 36216, 36218, 36220, 36222,
- }},
- {{
- 36224, 36226, 36228, 36230, 36232, 36234, 36236, 36238,
- 36240, 36242, 36245, 36248, 36251, 36253, 36256, 36258,
- 36261, 36262, 36263, 36264, 36265, 36266, 36267, 36268,
- 36269, 36270, 36271, 36272, 36273, 36274, 36275, 36276,
- }},
- {{
- 36277, 36278, 36279, 36280, 36281, 36282, 36283, 36284,
- 36285, 36286, 36287, 36288, 36289, 36290, 36291, 36292,
- 36293, 36294, 36295, 36296, 36297, 36298, 36299, 36300,
- 36301, 36302, 36303, 36304, 36305, 36306, 36307, 0,
- }},
- {{
- 36308, 36312, 36316, 36320, 36323, 36327, 36330, 36333,
- 36338, 36342, 36345, 36348, 36351, 36355, 36359, 36362,
- 36365, 36367, 36370, 36374, 36378, 36380, 36385, 36391,
- 36396, 36399, 36404, 36409, 36413, 36416, 36419, 36422,
- }},
- {{
- 36426, 36431, 36435, 36438, 36441, 36444, 36446, 36448,
- 36450, 36452, 36455, 36458, 36463, 36466, 36470, 36475,
- 36478, 36480, 36482, 36487, 36491, 36496, 36499, 36504,
- 36506, 36509, 36512, 36515, 36518, 36521, 36525, 36528,
- }},
- {{
- 36530, 36533, 36536, 36539, 36543, 36546, 36549, 36552,
- 36557, 36561, 36563, 36568, 36570, 36574, 36578, 36581,
- 36584, 36587, 36591, 36593, 36596, 36600, 36602, 36607,
- 36610, 36612, 36614, 36616, 36618, 36620, 36622, 36624,
- }},
- {{
- 36626, 36628, 36630, 36633, 36636, 36639, 36642, 36645,
- 36648, 36651, 36654, 36657, 36660, 36663, 36666, 36669,
- 36672, 36675, 36678, 36680, 36682, 36685, 36687, 36689,
- 36691, 36694, 36697, 36699, 36701, 36703, 36705, 36707,
- }},
- {{
- 36711, 36713, 36715, 36717, 36719, 36721, 36723, 36725,
- 36727, 36730, 36734, 36736, 36738, 36740, 36742, 36744,
- 36746, 36748, 36751, 36754, 36757, 36760, 36762, 36764,
- 36766, 36768, 36770, 36772, 36774, 36776, 36778, 36780,
- }},
- {{
- 36783, 36786, 36788, 36791, 36794, 36797, 36799, 36802,
- 36805, 36809, 36811, 36814, 36817, 36820, 36823, 36828,
- 36834, 36836, 36838, 36840, 36842, 36844, 36846, 36848,
- 36850, 36852, 36854, 36856, 36858, 36860, 36862, 36864,
- }},
- {{
- 36866, 36868, 36870, 36874, 36876, 36878, 36880, 36884,
- 36887, 36889, 36891, 36893, 36895, 36897, 36899, 36901,
- 36903, 36905, 36907, 36910, 36912, 36914, 36917, 36920,
- 36922, 36926, 36929, 36931, 36933, 36935, 36937, 36940,
- }},
- {{
- 36943, 36945, 36947, 36949, 36951, 36953, 36955, 36957,
- 36959, 36961, 36964, 36967, 36970, 36973, 36976, 36979,
- 36982, 36985, 36988, 36991, 36994, 36997, 37000, 37003,
- 37006, 37009, 37012, 37015, 37018, 37021, 37024, 37027,
- }},
- {{
- 4262, 4263, 4264, 4265, 4266, 4267, 4268, 4269,
- 4270, 4271, 4272, 4273, 4274, 4275, 4276, 4277,
- 4278, 4279, 4280, 4281, 4282, 4283, 4284, 4285,
- 4286, 4287, 4288, 4289, 4290, 4291, 4292, 4293,
- }},
- {{
- 4294, 4295, 4296, 4297, 4298, 4299, 4300, 4301,
- 4302, 4303, 4304, 4305, 4306, 4307, 4308, 4309,
- 4310, 4311, 4312, 4313, 4314, 4315, 4316, 4317,
- 4318, 4319, 4320, 4321, 4322, 4323, 4324, 4325,
- }},
- {{
- 4326, 4327, 4328, 4329, 4330, 4331, 4332, 4333,
- 4334, 4335, 4336, 4337, 4338, 4339, 4340, 4341,
- 4342, 4343, 4344, 4345, 4346, 4347, 4348, 4349,
- 4350, 4351, 4352, 4353, 4354, 4355, 4356, 4357,
- }},
- {{
- 4358, 4359, 4360, 4361, 4362, 4363, 4364, 4365,
- 4366, 4367, 4368, 4369, 4370, 4371, 4372, 4373,
- 4374, 4375, 4376, 4377, 4378, 4379, 4380, 4381,
- 4382, 4383, 4384, 4385, 4386, 4387, 4388, 4389,
- }},
- {{
- 4390, 4391, 4392, 4393, 4394, 4395, 4396, 4397,
- 4398, 4399, 4400, 4401, 4402, 4403, 4404, 4405,
- 4406, 4407, 4408, 4409, 4410, 4411, 4412, 4413,
- 4414, 4415, 4416, 4417, 4418, 4419, 4420, 4421,
- }},
- {{
- 4422, 4423, 4424, 4425, 4426, 4427, 4428, 4429,
- 4430, 4431, 4432, 4433, 4434, 4435, 4436, 4437,
- 4438, 4439, 4440, 4441, 4442, 4443, 4444, 4445,
- 4446, 4447, 4448, 4449, 4450, 4451, 4452, 4453,
- }},
- {{
- 4454, 4455, 4456, 4457, 4458, 4459, 4460, 4461,
- 4462, 4463, 4464, 4465, 4466, 4467, 4468, 4469,
- 4470, 4471, 4472, 4473, 4474, 4475, 4476, 4477,
- 4478, 4479, 4480, 4481, 4482, 4483, 4484, 4485,
- }},
- {{
- 4486, 4487, 4488, 4489, 4490, 4491, 4492, 4493,
- 4494, 4495, 4496, 4497, 4498, 4499, 4500, 4501,
- 4502, 4503, 4504, 4505, 4506, 4507, 4508, 4509,
- 4510, 4511, 4512, 4513, 4514, 4515, 4516, 4517,
- }},
- {{
- 4518, 4519, 4520, 4521, 4522, 4523, 4524, 4525,
- 4526, 4527, 4528, 4529, 4530, 4531, 0, 0,
- 4532, 0, 4533, 0, 0, 4534, 4535, 4536,
- 4537, 4538, 4539, 4540, 4541, 4542, 4543, 0,
- }},
- {{
- 4544, 0, 4545, 0, 0, 4546, 4547, 0,
- 0, 0, 4548, 4549, 4550, 4551, 0, 0,
- 4552, 4553, 4554, 4555, 4556, 4557, 4558, 4559,
- 4560, 4561, 4562, 4563, 4564, 4565, 4566, 4567,
- }},
- {{
- 4568, 4569, 4570, 4571, 4572, 4573, 4574, 4575,
- 4576, 4577, 4578, 4579, 4580, 4581, 4582, 4583,
- 4584, 4585, 4586, 4587, 4588, 4589, 4590, 4591,
- 4592, 4593, 4594, 4595, 4596, 4597, 4598, 4599,
- }},
- {{
- 4600, 4601, 4602, 4603, 4604, 4605, 4606, 4607,
- 4608, 4609, 4610, 0, 0, 0, 0, 0,
- 4611, 4612, 4613, 4614, 4615, 4616, 4617, 4618,
- 4619, 4620, 4621, 4622, 4623, 4624, 4625, 4626,
- }},
- {{
- 4627, 4628, 4629, 4630, 4631, 4632, 4633, 4634,
- 4635, 4636, 4637, 4638, 4639, 4640, 4641, 4642,
- 4643, 4644, 4645, 4646, 4647, 4648, 4649, 4650,
- 4651, 4652, 4653, 4654, 4655, 4656, 4657, 4658,
- }},
- {{
- 4659, 4660, 4661, 4662, 4663, 4664, 4665, 4666,
- 4667, 4668, 4669, 4670, 4671, 4672, 4673, 4674,
- 4675, 4676, 4677, 4678, 4679, 4680, 4681, 4682,
- 4683, 4684, 4685, 4686, 4687, 4688, 4689, 4690,
- }},
- {{
- 4691, 4692, 4693, 4694, 4695, 4696, 4697, 4698,
- 4699, 4700, 4701, 4702, 4703, 4704, 4705, 4706,
- 4707, 4708, 4709, 4710, 4711, 4712, 4713, 4714,
- 4715, 4716, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 37485, 37487, 37489, 37491, 37494, 37497, 37499, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 37501, 37503, 37505, 37507, 37509,
- 0, 0, 0, 0, 0, 4743, 0, 4745,
- }},
- {{
- 37515, 37516, 37517, 37518, 37519, 37520, 37521, 37522,
- 37523, 37524, 4757, 4759, 4761, 4763, 4765, 4767,
- 4769, 4771, 4773, 4775, 4777, 4779, 4781, 0,
- 4783, 4785, 4787, 4789, 4791, 0, 4793, 0,
- }},
- {{
- 4795, 4797, 0, 4799, 4801, 0, 4803, 4805,
- 4807, 4809, 4811, 4813, 4815, 4817, 4819, 37589,
- 37591, 37592, 37593, 37594, 37595, 37596, 37597, 37598,
- 37599, 37600, 37601, 37602, 37603, 37604, 37605, 37606,
- }},
- {{
- 37607, 37608, 37609, 37610, 37611, 37612, 37613, 37614,
- 37615, 37616, 37617, 37618, 37619, 37620, 37621, 37622,
- 37623, 37624, 37625, 37626, 37627, 37628, 37629, 37630,
- 37631, 37632, 37633, 37634, 37635, 37636, 37637, 37638,
- }},
- {{
- 37639, 37640, 37641, 37642, 37643, 37644, 37645, 37646,
- 37647, 37648, 37649, 37650, 37651, 37652, 37653, 37654,
- 37655, 37656, 37657, 37658, 37659, 37660, 37661, 37662,
- 37663, 37664, 37665, 37666, 37667, 37668, 37669, 37670,
- }},
- {{
- 37671, 37672, 37673, 37674, 37675, 37676, 37677, 37678,
- 37679, 37680, 37681, 37682, 37683, 37684, 37685, 37686,
- 37687, 37688, 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, 37689, 37690, 37691, 37692, 37693,
- 37694, 37695, 37696, 37697, 37698, 37699, 37700, 37701,
- }},
- {{
- 37702, 37703, 37704, 37705, 37706, 37707, 37708, 37709,
- 37710, 37711, 37712, 37714, 37716, 37718, 37720, 37722,
- 37724, 37726, 37728, 37730, 37732, 37734, 37736, 37738,
- 37740, 37742, 37744, 37746, 37748, 37749, 37750, 37751,
- }},
- {{
- 37752, 37754, 37756, 37758, 37760, 37762, 37764, 37766,
- 37768, 37770, 37772, 37774, 37776, 37778, 37780, 37782,
- 37784, 37786, 37788, 37790, 37792, 37794, 37796, 37798,
- 37800, 37802, 37804, 37806, 37808, 37810, 37812, 37814,
- }},
- {{
- 37816, 37818, 37820, 37822, 37824, 37826, 37828, 37830,
- 37832, 37834, 37836, 37838, 37840, 37842, 37844, 37846,
- 37848, 37850, 37852, 37854, 37856, 37858, 37860, 37862,
- 37864, 37866, 37868, 37870, 37872, 37874, 37876, 37878,
- }},
- {{
- 37880, 37882, 37884, 37886, 37888, 37890, 37892, 37894,
- 37896, 37898, 37900, 37902, 37904, 37906, 37908, 37910,
- 37912, 37914, 37916, 37918, 37920, 37922, 37924, 37926,
- 37928, 37930, 37932, 37934, 37936, 37938, 37940, 37943,
- }},
- {{
- 37946, 37949, 37952, 37955, 37958, 37960, 37962, 37964,
- 37966, 37968, 37970, 37972, 37974, 37976, 37978, 37980,
- 37982, 37984, 37986, 37988, 37990, 37992, 37994, 37996,
- 37998, 38000, 38002, 38004, 38006, 38008, 38010, 38012,
- }},
- {{
- 38014, 38016, 38018, 38020, 38022, 38024, 38026, 38028,
- 38030, 38032, 38034, 38036, 38038, 38040, 38042, 38044,
- 38046, 38048, 38050, 38052, 38054, 38056, 38058, 38060,
- 38062, 38064, 38066, 38068, 38070, 38072, 38074, 38076,
- }},
- {{
- 38078, 38080, 38082, 38084, 38086, 38088, 38090, 38092,
- 38094, 38096, 38098, 38100, 38102, 38104, 38106, 38108,
- 38110, 38112, 38114, 38116, 38118, 38120, 38122, 38124,
- 38126, 38128, 38130, 38132, 38134, 38136, 38138, 38140,
- }},
- {{
- 38142, 38144, 38146, 38148, 38150, 38152, 38154, 38156,
- 38158, 38160, 38162, 38164, 38166, 38168, 38170, 38172,
- 38174, 38176, 38178, 38180, 38182, 38184, 38186, 38188,
- 38190, 38192, 38194, 38196, 38198, 38200, 38202, 38204,
- }},
- {{
- 38206, 38208, 38210, 38212, 38214, 38216, 38218, 38220,
- 38222, 38224, 38226, 38228, 38230, 38232, 38234, 38236,
- 38238, 38240, 38242, 38245, 38248, 38251, 38253, 38255,
- 38257, 38259, 38261, 38263, 38265, 38267, 38269, 38271,
- }},
- {{
- 38273, 38275, 38277, 38279, 38281, 38283, 38285, 38287,
- 38289, 38291, 38293, 38295, 38297, 38299, 38301, 38303,
- 38305, 38307, 38309, 38311, 38313, 38315, 38317, 38319,
- 38321, 38323, 38325, 38327, 38329, 38331, 38333, 38335,
- }},
- {{
- 38337, 38339, 38341, 38343, 38345, 38347, 38349, 38351,
- 38353, 38355, 38357, 38359, 38361, 38363, 38365, 38367,
- 38369, 38371, 38373, 38375, 38377, 38379, 38381, 38383,
- 38385, 38387, 38389, 38391, 38393, 38395, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 38397, 38400, 38403, 38406, 38409, 38412, 38415, 38418,
- 38421, 38424, 38427, 38430, 38433, 38436, 38439, 38442,
- }},
- {{
- 38445, 38448, 38451, 38454, 38457, 38460, 38463, 38466,
- 38469, 38472, 38475, 38478, 38481, 38484, 38487, 38490,
- 38493, 38496, 38499, 38502, 38505, 38508, 38511, 38514,
- 38517, 38520, 38523, 38526, 38529, 38532, 38535, 38538,
- }},
- {{
- 38541, 38544, 38547, 38550, 38553, 38556, 38559, 38562,
- 38565, 38568, 38571, 38574, 38577, 38580, 38583, 38586,
- 0, 0, 38589, 38592, 38595, 38598, 38601, 38604,
- 38607, 38610, 38613, 38616, 38619, 38622, 38625, 38628,
- }},
- {{
- 38631, 38634, 38637, 38640, 38643, 38646, 38649, 38652,
- 38655, 38658, 38661, 38664, 38667, 38670, 38673, 38676,
- 38679, 38682, 38685, 38688, 38691, 38694, 38697, 38700,
- 38703, 38706, 38709, 38712, 38715, 38718, 38721, 38724,
- }},
- {{
- 38727, 38730, 38733, 38736, 38739, 38742, 38745, 38748,
- 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,
- 38751, 38754, 38757, 38761, 38765, 38769, 38773, 38777,
- 38781, 38785, 38788, 38806, 38814, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 38818, 38819, 38820, 38821, 38822, 38823, 38824, 38825,
- 38826, 38827, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 38828, 38829, 38830, 38831, 38832, 38833, 38834, 38835,
- 38836, 38837, 38838, 38839, 38840, 38841, 38842, 38843,
- }},
- {{
- 38844, 38845, 38846, 38847, 38848, 0, 0, 38849,
- 38850, 38851, 38852, 38853, 38854, 38855, 38856, 38857,
- 38858, 38859, 38860, 0, 38861, 38862, 38863, 38864,
- 38865, 38866, 38867, 38868, 38869, 38870, 38871, 38872,
- }},
- {{
- 38873, 38874, 38875, 38876, 38877, 38878, 38879, 0,
- 38880, 38881, 38882, 38883, 0, 0, 0, 0,
- 38884, 38886, 38888, 0, 38890, 0, 38892, 38894,
- 38896, 38898, 38900, 38902, 38904, 38906, 38908, 38910,
- }},
- {{
- 38912, 38913, 38914, 38915, 38916, 38917, 38918, 38919,
- 38920, 38921, 38922, 38923, 38924, 38925, 38926, 38927,
- 38928, 38929, 38930, 38931, 38932, 38933, 38934, 38935,
- 38936, 38937, 38938, 38939, 38940, 38941, 38942, 38943,
- }},
- {{
- 38944, 38945, 38946, 38947, 38948, 38949, 38950, 38951,
- 38952, 38953, 38954, 38955, 38956, 38957, 38958, 38959,
- 38960, 38961, 38962, 38963, 38964, 38965, 38966, 38967,
- 38968, 38969, 38970, 38971, 38972, 38973, 38974, 38975,
- }},
- {{
- 38976, 38977, 38978, 38979, 38980, 38981, 38982, 38983,
- 38984, 38985, 38986, 38987, 38988, 38989, 38990, 38991,
- 38992, 38993, 38994, 38995, 38996, 38997, 38998, 38999,
- 39000, 39001, 39002, 39003, 39004, 39005, 39006, 39007,
- }},
- {{
- 39008, 39009, 39010, 39011, 39012, 39013, 39014, 39015,
- 39016, 39017, 39018, 39019, 39020, 39021, 39022, 39023,
- 39024, 39025, 39026, 39027, 39028, 39029, 39031, 39033,
- 39035, 39037, 39039, 39041, 39043, 0, 0, 0,
- }},
- {{
- 0, 39045, 39046, 39047, 39048, 39049, 39050, 39051,
- 39052, 39053, 39054, 39055, 39056, 39057, 39058, 39059,
- 39060, 39061, 39062, 39063, 39064, 39065, 39066, 39067,
- 39068, 39069, 39070, 39071, 39072, 39073, 39074, 39075,
- }},
- {{
- 39076, 39077, 39078, 39079, 39080, 39081, 39082, 39083,
- 39084, 39085, 39086, 39087, 39088, 39089, 39090, 39091,
- 39092, 39093, 39094, 39095, 39096, 39097, 39098, 39099,
- 39100, 39101, 39102, 39103, 39104, 39105, 39106, 39107,
- }},
- {{
- 39108, 39109, 39110, 39111, 39112, 39113, 39114, 39115,
- 39116, 39117, 39118, 39119, 39120, 39121, 39122, 39123,
- 39124, 39125, 39126, 39127, 39128, 39129, 39130, 39131,
- 39132, 39133, 39134, 39135, 39136, 39137, 39138, 39139,
- }},
- {{
- 39140, 39141, 39142, 39143, 39144, 39145, 39146, 39147,
- 39148, 39149, 39150, 39151, 39152, 39153, 39154, 39155,
- 39156, 39157, 39158, 39159, 39160, 39161, 39162, 39163,
- 39164, 39165, 39166, 39167, 39168, 39169, 39170, 39171,
- }},
- {{
- 39172, 39173, 39174, 39175, 39176, 39177, 39178, 39179,
- 39180, 39181, 39182, 39183, 39184, 39185, 39186, 39187,
- 39188, 39189, 39190, 39191, 39192, 39193, 39194, 39195,
- 39196, 39197, 39198, 39199, 39200, 39201, 39202, 39203,
- }},
- {{
- 39204, 39205, 39206, 39207, 39208, 39209, 39210, 39211,
- 39212, 39213, 39214, 39215, 39216, 39217, 39218, 39219,
- 39220, 39221, 39222, 39223, 39224, 39225, 39226, 39227,
- 39228, 39229, 39230, 39231, 39232, 39233, 39234, 0,
- }},
- {{
- 0, 0, 39235, 39236, 39237, 39238, 39239, 39240,
- 0, 0, 39241, 39242, 39243, 39244, 39245, 39246,
- 0, 0, 39247, 39248, 39249, 39250, 39251, 39252,
- 0, 0, 39253, 39254, 39255, 0, 0, 0,
- }},
- {{
- 39256, 39257, 39258, 39259, 39260, 39261, 39262, 0,
- 39263, 39264, 39265, 39266, 39267, 39268, 39269, 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, 6502, 6504,
- }},
- {{
- 6506, 6508, 6510, 6512, 6514, 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, 6516, 6518, 6520, 6522, 6524,
- }},
- {{
- 6526, 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,
- }},
- {{
- 39296, 39297, 39298, 39299, 39300, 39301, 39302, 39303,
- 39304, 39305, 39306, 39307, 39308, 39309, 39310, 39311,
- 39312, 39313, 39314, 39315, 39316, 39317, 39318, 39319,
- 39320, 39321, 39322, 39323, 39324, 39325, 39326, 39327,
- }},
- {{
- 39328, 39329, 39330, 39331, 39332, 39333, 39334, 39335,
- 39336, 39337, 39338, 39339, 39340, 39341, 39342, 39343,
- 39344, 39345, 39346, 39347, 39348, 39349, 39350, 39351,
- 39352, 39353, 39354, 39355, 39356, 39357, 39358, 39359,
- }},
- {{
- 39360, 39361, 39362, 39363, 39364, 39365, 39366, 39367,
- 39368, 39369, 39370, 39371, 39372, 39373, 39374, 39375,
- 39376, 39377, 39378, 39379, 39380, 0, 39381, 39382,
- 39383, 39384, 39385, 39386, 39387, 39388, 39389, 39390,
- }},
- {{
- 39391, 39392, 39393, 39394, 39395, 39396, 39397, 39398,
- 39399, 39400, 39401, 39402, 39403, 39404, 39405, 39406,
- 39407, 39408, 39409, 39410, 39411, 39412, 39413, 39414,
- 39415, 39416, 39417, 39418, 39419, 39420, 39421, 39422,
- }},
- {{
- 39423, 39424, 39425, 39426, 39427, 39428, 39429, 39430,
- 39431, 39432, 39433, 39434, 39435, 39436, 39437, 39438,
- 39439, 39440, 39441, 39442, 39443, 39444, 39445, 39446,
- 39447, 39448, 39449, 39450, 39451, 0, 39452, 39453,
- }},
- {{
- 0, 0, 39454, 0, 0, 39455, 39456, 0,
- 0, 39457, 39458, 39459, 39460, 0, 39461, 39462,
- 39463, 39464, 39465, 39466, 39467, 39468, 39469, 39470,
- 39471, 39472, 0, 39473, 0, 39474, 39475, 39476,
- }},
- {{
- 39477, 39478, 39479, 39480, 0, 39481, 39482, 39483,
- 39484, 39485, 39486, 39487, 39488, 39489, 39490, 39491,
- 39492, 39493, 39494, 39495, 39496, 39497, 39498, 39499,
- 39500, 39501, 39502, 39503, 39504, 39505, 39506, 39507,
- }},
- {{
- 39508, 39509, 39510, 39511, 39512, 39513, 39514, 39515,
- 39516, 39517, 39518, 39519, 39520, 39521, 39522, 39523,
- 39524, 39525, 39526, 39527, 39528, 39529, 39530, 39531,
- 39532, 39533, 39534, 39535, 39536, 39537, 39538, 39539,
- }},
- {{
- 39540, 39541, 39542, 39543, 39544, 39545, 0, 39546,
- 39547, 39548, 39549, 0, 0, 39550, 39551, 39552,
- 39553, 39554, 39555, 39556, 39557, 0, 39558, 39559,
- 39560, 39561, 39562, 39563, 39564, 0, 39565, 39566,
- }},
- {{
- 39567, 39568, 39569, 39570, 39571, 39572, 39573, 39574,
- 39575, 39576, 39577, 39578, 39579, 39580, 39581, 39582,
- 39583, 39584, 39585, 39586, 39587, 39588, 39589, 39590,
- 39591, 39592, 0, 39593, 39594, 39595, 39596, 0,
- }},
- {{
- 39597, 39598, 39599, 39600, 39601, 0, 39602, 0,
- 0, 0, 39603, 39604, 39605, 39606, 39607, 39608,
- 39609, 0, 39610, 39611, 39612, 39613, 39614, 39615,
- 39616, 39617, 39618, 39619, 39620, 39621, 39622, 39623,
- }},
- {{
- 39624, 39625, 39626, 39627, 39628, 39629, 39630, 39631,
- 39632, 39633, 39634, 39635, 39636, 39637, 39638, 39639,
- 39640, 39641, 39642, 39643, 39644, 39645, 39646, 39647,
- 39648, 39649, 39650, 39651, 39652, 39653, 39654, 39655,
- }},
- {{
- 39656, 39657, 39658, 39659, 39660, 39661, 39662, 39663,
- 39664, 39665, 39666, 39667, 39668, 39669, 39670, 39671,
- 39672, 39673, 39674, 39675, 39676, 39677, 39678, 39679,
- 39680, 39681, 39682, 39683, 39684, 39685, 39686, 39687,
- }},
- {{
- 39688, 39689, 39690, 39691, 39692, 39693, 39694, 39695,
- 39696, 39697, 39698, 39699, 39700, 39701, 39702, 39703,
- 39704, 39705, 39706, 39707, 39708, 39709, 39710, 39711,
- 39712, 39713, 39714, 39715, 39716, 39717, 39718, 39719,
- }},
- {{
- 39720, 39721, 39722, 39723, 39724, 39725, 39726, 39727,
- 39728, 39729, 39730, 39731, 39732, 39733, 39734, 39735,
- 39736, 39737, 39738, 39739, 39740, 39741, 39742, 39743,
- 39744, 39745, 39746, 39747, 39748, 39749, 39750, 39751,
- }},
- {{
- 39752, 39753, 39754, 39755, 39756, 39757, 39758, 39759,
- 39760, 39761, 39762, 39763, 39764, 39765, 39766, 39767,
- 39768, 39769, 39770, 39771, 39772, 39773, 39774, 39775,
- 39776, 39777, 39778, 39779, 39780, 39781, 39782, 39783,
- }},
- {{
- 39784, 39785, 39786, 39787, 39788, 39789, 39790, 39791,
- 39792, 39793, 39794, 39795, 39796, 39797, 39798, 39799,
- 39800, 39801, 39802, 39803, 39804, 39805, 39806, 39807,
- 39808, 39809, 39810, 39811, 39812, 39813, 39814, 39815,
- }},
- {{
- 39816, 39817, 39818, 39819, 39820, 39821, 39822, 39823,
- 39824, 39825, 39826, 39827, 39828, 39829, 39830, 39831,
- 39832, 39833, 39834, 39835, 39836, 39837, 39838, 39839,
- 39840, 39841, 39842, 39843, 39844, 39845, 39846, 39847,
- }},
- {{
- 39848, 39849, 39850, 39851, 39852, 39853, 39854, 39855,
- 39856, 39857, 39858, 39859, 39860, 39861, 39862, 39863,
- 39864, 39865, 39866, 39867, 39868, 39869, 39870, 39871,
- 39872, 39873, 39874, 39875, 39876, 39877, 39878, 39879,
- }},
- {{
- 39880, 39881, 39882, 39883, 39884, 39885, 39886, 39887,
- 39888, 39889, 39890, 39891, 39892, 39893, 39894, 39895,
- 39896, 39897, 39898, 39899, 39900, 39901, 39902, 39903,
- 39904, 39905, 39906, 39907, 39908, 39909, 39910, 39911,
- }},
- {{
- 39912, 39913, 39914, 39915, 39916, 39917, 39918, 39919,
- 39920, 39921, 39922, 39923, 39924, 39925, 39926, 39927,
- 39928, 39929, 39930, 39931, 39932, 39933, 39934, 39935,
- 39936, 39937, 39938, 39939, 39940, 39941, 39942, 39943,
- }},
- {{
- 39944, 39945, 39946, 39947, 39948, 39949, 0, 0,
- 39950, 39951, 39952, 39953, 39954, 39955, 39956, 39957,
- 39958, 39959, 39960, 39961, 39962, 39963, 39964, 39965,
- 39966, 39967, 39968, 39969, 39970, 39971, 39972, 39973,
- }},
- {{
- 39974, 39975, 39976, 39977, 39978, 39979, 39980, 39981,
- 39982, 39983, 39984, 39985, 39986, 39987, 39988, 39989,
- 39990, 39991, 39992, 39993, 39994, 39995, 39996, 39997,
- 39998, 39999, 40000, 40001, 40002, 40003, 40004, 40005,
- }},
- {{
- 40006, 40007, 40008, 40009, 40010, 40011, 40012, 40013,
- 40014, 40015, 40016, 40017, 40018, 40019, 40020, 40021,
- 40022, 40023, 40024, 40025, 40026, 40027, 40028, 40029,
- 40030, 40031, 40032, 40033, 40034, 40035, 40036, 40037,
- }},
- {{
- 40038, 40039, 40040, 40041, 40042, 40043, 40044, 40045,
- 40046, 40047, 40048, 40049, 40050, 40051, 40052, 40053,
- 40054, 40055, 40056, 40057, 40058, 40059, 40060, 40061,
- 40062, 40063, 40064, 40065, 40066, 40067, 40068, 40069,
- }},
- {{
- 40070, 40071, 40072, 40073, 40074, 40075, 40076, 40077,
- 40078, 40079, 40080, 40081, 40082, 40083, 40084, 40085,
- 40086, 40087, 40088, 40089, 40090, 40091, 40092, 40093,
- 40094, 40095, 40096, 40097, 40098, 40099, 40100, 40101,
- }},
- {{
- 40102, 40103, 40104, 40105, 40106, 40107, 40108, 40109,
- 40110, 40111, 40112, 40113, 40114, 40115, 40116, 40117,
- 40118, 40119, 40120, 40121, 40122, 40123, 40124, 40125,
- 40126, 40127, 40128, 40129, 40130, 40131, 40132, 40133,
- }},
- {{
- 40134, 40135, 40136, 40137, 40138, 40139, 40140, 40141,
- 40142, 40143, 40144, 40145, 40146, 40147, 40148, 40149,
- 40150, 40151, 40152, 40153, 40154, 40155, 40156, 40157,
- 40158, 40159, 40160, 40161, 40162, 40163, 40164, 40165,
- }},
- {{
- 40166, 40167, 40168, 40169, 40170, 40171, 40172, 40173,
- 40174, 40175, 40176, 40177, 40178, 40179, 40180, 40181,
- 40182, 40183, 40184, 40185, 40186, 40187, 40188, 40189,
- 40190, 40191, 40192, 40193, 40194, 40195, 40196, 40197,
- }},
- {{
- 40198, 40199, 40200, 40201, 40202, 40203, 40204, 40205,
- 40206, 40207, 40208, 40209, 40210, 40211, 40212, 40213,
- 40214, 40215, 40216, 40217, 40218, 40219, 40220, 40221,
- 40222, 40223, 40224, 40225, 40226, 40227, 40228, 40229,
- }},
- {{
- 40230, 40231, 40232, 40233, 40234, 40235, 40236, 40237,
- 40238, 40239, 0, 0, 0, 0, 40240, 40241,
- 40242, 40243, 40244, 40245, 40246, 40247, 40248, 40249,
- 40250, 40251, 40252, 40253, 40254, 40255, 40256, 40257,
- }},
- {{
- 40258, 40259, 40260, 40261, 40262, 40263, 40264, 40265,
- 40266, 40267, 40268, 40269, 40270, 40271, 40272, 40273,
- 40274, 40275, 40276, 40277, 40278, 40279, 40280, 40281,
- 40282, 40283, 40284, 40285, 40286, 40287, 40288, 40289,
- }},
- {{
- 7522, 7523, 7524, 7525, 7526, 7527, 7528, 7529,
- 7530, 7531, 7532, 7533, 7534, 7535, 7536, 7537,
- 7538, 7539, 7540, 7541, 7542, 7543, 7544, 7545,
- 7546, 7547, 7548, 7549, 7550, 7551, 7552, 7553,
- }},
- {{
- 7554, 7555, 7556, 7557, 7558, 7559, 7560, 7561,
- 7562, 7563, 7564, 7565, 7566, 7567, 7568, 7569,
- 7570, 7571, 7572, 7573, 7574, 7575, 7576, 7577,
- 7578, 7579, 7580, 7581, 7582, 7583, 7584, 7585,
- }},
- {{
- 7586, 7587, 7588, 7589, 7590, 7591, 7592, 7593,
- 7594, 7595, 7596, 7597, 7598, 7599, 7600, 7601,
- 7602, 7603, 7604, 7605, 7606, 7607, 7608, 7609,
- 7610, 7611, 7612, 7613, 7614, 7615, 7616, 7617,
- }},
- {{
- 7618, 7619, 7620, 7621, 7622, 7623, 7624, 7625,
- 7626, 7627, 7628, 7629, 7630, 7631, 7632, 7633,
- 7634, 7635, 7636, 7637, 7638, 7639, 7640, 7641,
- 7642, 7643, 7644, 7645, 7646, 7647, 7648, 7649,
- }},
- {{
- 7650, 7651, 7652, 7653, 7654, 7655, 7656, 7657,
- 7658, 7659, 7660, 7661, 7662, 7663, 7664, 7665,
- 7666, 7667, 7668, 7669, 7670, 7671, 7672, 7673,
- 7674, 7675, 7676, 7677, 7678, 7679, 7680, 7681,
- }},
- {{
- 7682, 7683, 7684, 7685, 7686, 7687, 7688, 7689,
- 7690, 7691, 7692, 7693, 7694, 7695, 7696, 7697,
- 7698, 7699, 7700, 7701, 7702, 7703, 7704, 7705,
- 7706, 7707, 7708, 7709, 7710, 7711, 7712, 7713,
- }},
- {{
- 7714, 7715, 7716, 7717, 7718, 7719, 7720, 7721,
- 7722, 7723, 7724, 7725, 7726, 7727, 7728, 7729,
- 7730, 7731, 7732, 7733, 7734, 7735, 7736, 7737,
- 7738, 7739, 7740, 7741, 7742, 7743, 7744, 7745,
- }},
- {{
- 7746, 7747, 7748, 7749, 7750, 7751, 7752, 7753,
- 7754, 7755, 7756, 7757, 7758, 7759, 7760, 7761,
- 7762, 7763, 7764, 7765, 7766, 7767, 7768, 7769,
- 7770, 7771, 7772, 7773, 7774, 7775, 7776, 7777,
- }},
- {{
- 7778, 7779, 7780, 7781, 7782, 7783, 7784, 7785,
- 7786, 7787, 7788, 7789, 7790, 7791, 7792, 7793,
- 7794, 7795, 7796, 7797, 7798, 7799, 7800, 7801,
- 7802, 7803, 7804, 7805, 7806, 7807, 7808, 7809,
- }},
- {{
- 7810, 7811, 7812, 7813, 7814, 7815, 7816, 7817,
- 7818, 7819, 7820, 7821, 7822, 7823, 7824, 7825,
- 7826, 7827, 7828, 7829, 7830, 7831, 7832, 7833,
- 7834, 7835, 7836, 7837, 7838, 7839, 7840, 7841,
- }},
- {{
- 7842, 7843, 7844, 7845, 7846, 7847, 7848, 7849,
- 7850, 7851, 7852, 7853, 7854, 7855, 7856, 7857,
- 7858, 7859, 7860, 7861, 7862, 7863, 7864, 7865,
- 7866, 7867, 7868, 7869, 7870, 7871, 7872, 7873,
- }},
- {{
- 7874, 7875, 7876, 7877, 7878, 7879, 7880, 7881,
- 7882, 7883, 7884, 7885, 7886, 7887, 7888, 7889,
- 7890, 7891, 7892, 7893, 7894, 7895, 7896, 7897,
- 7898, 7899, 7900, 7901, 7902, 7903, 7904, 7905,
- }},
- {{
- 7906, 7907, 7908, 7909, 7910, 7911, 7912, 7913,
- 7914, 7915, 7916, 7917, 7918, 7919, 7920, 7921,
- 7922, 7923, 7924, 7925, 7926, 7927, 7928, 7929,
- 7930, 7931, 7932, 7933, 7934, 7935, 7936, 7937,
- }},
- {{
- 7938, 7939, 7940, 7941, 7942, 7943, 7944, 7945,
- 7946, 7947, 7948, 7949, 7950, 7951, 7952, 7953,
- 7954, 7955, 7956, 7957, 7958, 7959, 7960, 7961,
- 7962, 7963, 7964, 7965, 7966, 7967, 7968, 7969,
- }},
- {{
- 7970, 7971, 7972, 7973, 7974, 7975, 7976, 7977,
- 7978, 7979, 7980, 7981, 7982, 7983, 7984, 7985,
- 7986, 7987, 7988, 7989, 7990, 7991, 7992, 7993,
- 7994, 7995, 7996, 7997, 7998, 7999, 8000, 8001,
- }},
- {{
- 8002, 8003, 8004, 8005, 8006, 8007, 8008, 8009,
- 8010, 8011, 8012, 8013, 8014, 8015, 8016, 8017,
- 8018, 8019, 8020, 8021, 8022, 8023, 8024, 8025,
- 8026, 8027, 8028, 8029, 8030, 8031, 8032, 8033,
- }},
- {{
- 8034, 8035, 8036, 8037, 8038, 8039, 8040, 8041,
- 8042, 8043, 8044, 8045, 8046, 8047, 8048, 8049,
- 8050, 8051, 8052, 8053, 8054, 8055, 8056, 8057,
- 8058, 8059, 8060, 8061, 8062, 8063, 0, 0,
- }},
-};
-static const uint32_t decompose_seq[] = {
- 0x00000000, 0x80000020, 0x00000020, 0x80000308,
- 0x80000061, 0x00000020, 0x80000304, 0x80000032,
- 0x80000033, 0x00000020, 0x80000301, 0x800003bc,
- 0x00000020, 0x80000327, 0x80000031, 0x8000006f,
- 0x00000031, 0x00002044, 0x80000034, 0x00000031,
- 0x00002044, 0x80000032, 0x00000033, 0x00002044,
- 0x80000034, 0x00000041, 0x80000300, 0x00000041,
- 0x80000301, 0x00000041, 0x80000302, 0x00000041,
- 0x80000303, 0x00000041, 0x80000308, 0x00000041,
- 0x8000030a, 0x00000043, 0x80000327, 0x00000045,
- 0x80000300, 0x00000045, 0x80000301, 0x00000045,
- 0x80000302, 0x00000045, 0x80000308, 0x00000049,
- 0x80000300, 0x00000049, 0x80000301, 0x00000049,
- 0x80000302, 0x00000049, 0x80000308, 0x0000004e,
- 0x80000303, 0x0000004f, 0x80000300, 0x0000004f,
- 0x80000301, 0x0000004f, 0x80000302, 0x0000004f,
- 0x80000303, 0x0000004f, 0x80000308, 0x00000055,
- 0x80000300, 0x00000055, 0x80000301, 0x00000055,
- 0x80000302, 0x00000055, 0x80000308, 0x00000059,
- 0x80000301, 0x00000061, 0x80000300, 0x00000061,
- 0x80000301, 0x00000061, 0x80000302, 0x00000061,
- 0x80000303, 0x00000061, 0x80000308, 0x00000061,
- 0x8000030a, 0x00000063, 0x80000327, 0x00000065,
- 0x80000300, 0x00000065, 0x80000301, 0x00000065,
- 0x80000302, 0x00000065, 0x80000308, 0x00000069,
- 0x80000300, 0x00000069, 0x80000301, 0x00000069,
- 0x80000302, 0x00000069, 0x80000308, 0x0000006e,
- 0x80000303, 0x0000006f, 0x80000300, 0x0000006f,
- 0x80000301, 0x0000006f, 0x80000302, 0x0000006f,
- 0x80000303, 0x0000006f, 0x80000308, 0x00000075,
- 0x80000300, 0x00000075, 0x80000301, 0x00000075,
- 0x80000302, 0x00000075, 0x80000308, 0x00000079,
- 0x80000301, 0x00000079, 0x80000308, 0x00000041,
- 0x80000304, 0x00000061, 0x80000304, 0x00000041,
- 0x80000306, 0x00000061, 0x80000306, 0x00000041,
- 0x80000328, 0x00000061, 0x80000328, 0x00000043,
- 0x80000301, 0x00000063, 0x80000301, 0x00000043,
- 0x80000302, 0x00000063, 0x80000302, 0x00000043,
- 0x80000307, 0x00000063, 0x80000307, 0x00000043,
- 0x8000030c, 0x00000063, 0x8000030c, 0x00000044,
- 0x8000030c, 0x00000064, 0x8000030c, 0x00000045,
- 0x80000304, 0x00000065, 0x80000304, 0x00000045,
- 0x80000306, 0x00000065, 0x80000306, 0x00000045,
- 0x80000307, 0x00000065, 0x80000307, 0x00000045,
- 0x80000328, 0x00000065, 0x80000328, 0x00000045,
- 0x8000030c, 0x00000065, 0x8000030c, 0x00000047,
- 0x80000302, 0x00000067, 0x80000302, 0x00000047,
- 0x80000306, 0x00000067, 0x80000306, 0x00000047,
- 0x80000307, 0x00000067, 0x80000307, 0x00000047,
- 0x80000327, 0x00000067, 0x80000327, 0x00000048,
- 0x80000302, 0x00000068, 0x80000302, 0x00000049,
- 0x80000303, 0x00000069, 0x80000303, 0x00000049,
- 0x80000304, 0x00000069, 0x80000304, 0x00000049,
- 0x80000306, 0x00000069, 0x80000306, 0x00000049,
- 0x80000328, 0x00000069, 0x80000328, 0x00000049,
- 0x80000307, 0x00000049, 0x8000004a, 0x00000069,
- 0x8000006a, 0x0000004a, 0x80000302, 0x0000006a,
- 0x80000302, 0x0000004b, 0x80000327, 0x0000006b,
- 0x80000327, 0x0000004c, 0x80000301, 0x0000006c,
- 0x80000301, 0x0000004c, 0x80000327, 0x0000006c,
- 0x80000327, 0x0000004c, 0x8000030c, 0x0000006c,
- 0x8000030c, 0x0000004c, 0x800000b7, 0x0000006c,
- 0x800000b7, 0x0000004e, 0x80000301, 0x0000006e,
- 0x80000301, 0x0000004e, 0x80000327, 0x0000006e,
- 0x80000327, 0x0000004e, 0x8000030c, 0x0000006e,
- 0x8000030c, 0x000002bc, 0x8000006e, 0x0000004f,
- 0x80000304, 0x0000006f, 0x80000304, 0x0000004f,
- 0x80000306, 0x0000006f, 0x80000306, 0x0000004f,
- 0x8000030b, 0x0000006f, 0x8000030b, 0x00000052,
- 0x80000301, 0x00000072, 0x80000301, 0x00000052,
- 0x80000327, 0x00000072, 0x80000327, 0x00000052,
- 0x8000030c, 0x00000072, 0x8000030c, 0x00000053,
- 0x80000301, 0x00000073, 0x80000301, 0x00000053,
- 0x80000302, 0x00000073, 0x80000302, 0x00000053,
- 0x80000327, 0x00000073, 0x80000327, 0x00000053,
- 0x8000030c, 0x00000073, 0x8000030c, 0x00000054,
- 0x80000327, 0x00000074, 0x80000327, 0x00000054,
- 0x8000030c, 0x00000074, 0x8000030c, 0x00000055,
- 0x80000303, 0x00000075, 0x80000303, 0x00000055,
- 0x80000304, 0x00000075, 0x80000304, 0x00000055,
- 0x80000306, 0x00000075, 0x80000306, 0x00000055,
- 0x8000030a, 0x00000075, 0x8000030a, 0x00000055,
- 0x8000030b, 0x00000075, 0x8000030b, 0x00000055,
- 0x80000328, 0x00000075, 0x80000328, 0x00000057,
- 0x80000302, 0x00000077, 0x80000302, 0x00000059,
- 0x80000302, 0x00000079, 0x80000302, 0x00000059,
- 0x80000308, 0x0000005a, 0x80000301, 0x0000007a,
- 0x80000301, 0x0000005a, 0x80000307, 0x0000007a,
- 0x80000307, 0x0000005a, 0x8000030c, 0x0000007a,
- 0x8000030c, 0x80000073, 0x0000004f, 0x8000031b,
- 0x0000006f, 0x8000031b, 0x00000055, 0x8000031b,
- 0x00000075, 0x8000031b, 0x00000044, 0x8000017d,
- 0x00000044, 0x8000017e, 0x00000064, 0x8000017e,
- 0x0000004c, 0x8000004a, 0x0000004c, 0x8000006a,
- 0x0000006c, 0x8000006a, 0x0000004e, 0x8000004a,
- 0x0000004e, 0x8000006a, 0x0000006e, 0x8000006a,
- 0x00000041, 0x8000030c, 0x00000061, 0x8000030c,
- 0x00000049, 0x8000030c, 0x00000069, 0x8000030c,
- 0x0000004f, 0x8000030c, 0x0000006f, 0x8000030c,
- 0x00000055, 0x8000030c, 0x00000075, 0x8000030c,
- 0x000000dc, 0x80000304, 0x000000fc, 0x80000304,
- 0x000000dc, 0x80000301, 0x000000fc, 0x80000301,
- 0x000000dc, 0x8000030c, 0x000000fc, 0x8000030c,
- 0x000000dc, 0x80000300, 0x000000fc, 0x80000300,
- 0x000000c4, 0x80000304, 0x000000e4, 0x80000304,
- 0x00000226, 0x80000304, 0x00000227, 0x80000304,
- 0x000000c6, 0x80000304, 0x000000e6, 0x80000304,
- 0x00000047, 0x8000030c, 0x00000067, 0x8000030c,
- 0x0000004b, 0x8000030c, 0x0000006b, 0x8000030c,
- 0x0000004f, 0x80000328, 0x0000006f, 0x80000328,
- 0x000001ea, 0x80000304, 0x000001eb, 0x80000304,
- 0x000001b7, 0x8000030c, 0x00000292, 0x8000030c,
- 0x0000006a, 0x8000030c, 0x00000044, 0x8000005a,
- 0x00000044, 0x8000007a, 0x00000064, 0x8000007a,
- 0x00000047, 0x80000301, 0x00000067, 0x80000301,
- 0x0000004e, 0x80000300, 0x0000006e, 0x80000300,
- 0x000000c5, 0x80000301, 0x000000e5, 0x80000301,
- 0x000000c6, 0x80000301, 0x000000e6, 0x80000301,
- 0x000000d8, 0x80000301, 0x000000f8, 0x80000301,
- 0x00000041, 0x8000030f, 0x00000061, 0x8000030f,
- 0x00000041, 0x80000311, 0x00000061, 0x80000311,
- 0x00000045, 0x8000030f, 0x00000065, 0x8000030f,
- 0x00000045, 0x80000311, 0x00000065, 0x80000311,
- 0x00000049, 0x8000030f, 0x00000069, 0x8000030f,
- 0x00000049, 0x80000311, 0x00000069, 0x80000311,
- 0x0000004f, 0x8000030f, 0x0000006f, 0x8000030f,
- 0x0000004f, 0x80000311, 0x0000006f, 0x80000311,
- 0x00000052, 0x8000030f, 0x00000072, 0x8000030f,
- 0x00000052, 0x80000311, 0x00000072, 0x80000311,
- 0x00000055, 0x8000030f, 0x00000075, 0x8000030f,
- 0x00000055, 0x80000311, 0x00000075, 0x80000311,
- 0x00000053, 0x80000326, 0x00000073, 0x80000326,
- 0x00000054, 0x80000326, 0x00000074, 0x80000326,
- 0x00000048, 0x8000030c, 0x00000068, 0x8000030c,
- 0x00000041, 0x80000307, 0x00000061, 0x80000307,
- 0x00000045, 0x80000327, 0x00000065, 0x80000327,
- 0x000000d6, 0x80000304, 0x000000f6, 0x80000304,
- 0x000000d5, 0x80000304, 0x000000f5, 0x80000304,
- 0x0000004f, 0x80000307, 0x0000006f, 0x80000307,
- 0x0000022e, 0x80000304, 0x0000022f, 0x80000304,
- 0x00000059, 0x80000304, 0x00000079, 0x80000304,
- 0x80000068, 0x80000266, 0x8000006a, 0x80000072,
- 0x80000279, 0x8000027b, 0x80000281, 0x80000077,
- 0x80000079, 0x00000020, 0x80000306, 0x00000020,
- 0x80000307, 0x00000020, 0x8000030a, 0x00000020,
- 0x80000328, 0x00000020, 0x80000303, 0x00000020,
- 0x8000030b, 0x80000263, 0x8000006c, 0x80000073,
- 0x80000078, 0x80000295, 0x80000300, 0x80000301,
- 0x80000313, 0x00000308, 0x80000301, 0x800002b9,
- 0x00000020, 0x80000345, 0x8000003b, 0x00000020,
- 0x80000301, 0x000000a8, 0x80000301, 0x00000391,
- 0x80000301, 0x800000b7, 0x00000395, 0x80000301,
- 0x00000397, 0x80000301, 0x00000399, 0x80000301,
- 0x0000039f, 0x80000301, 0x000003a5, 0x80000301,
- 0x000003a9, 0x80000301, 0x000003ca, 0x80000301,
- 0x00000399, 0x80000308, 0x000003a5, 0x80000308,
- 0x000003b1, 0x80000301, 0x000003b5, 0x80000301,
- 0x000003b7, 0x80000301, 0x000003b9, 0x80000301,
- 0x000003cb, 0x80000301, 0x000003b9, 0x80000308,
- 0x000003c5, 0x80000308, 0x000003bf, 0x80000301,
- 0x000003c5, 0x80000301, 0x000003c9, 0x80000301,
- 0x800003b2, 0x800003b8, 0x800003a5, 0x000003d2,
- 0x80000301, 0x000003d2, 0x80000308, 0x800003c6,
- 0x800003c0, 0x800003ba, 0x800003c1, 0x800003c2,
- 0x80000398, 0x800003b5, 0x800003a3, 0x00000415,
- 0x80000300, 0x00000415, 0x80000308, 0x00000413,
- 0x80000301, 0x00000406, 0x80000308, 0x0000041a,
- 0x80000301, 0x00000418, 0x80000300, 0x00000423,
- 0x80000306, 0x00000418, 0x80000306, 0x00000438,
- 0x80000306, 0x00000435, 0x80000300, 0x00000435,
- 0x80000308, 0x00000433, 0x80000301, 0x00000456,
- 0x80000308, 0x0000043a, 0x80000301, 0x00000438,
- 0x80000300, 0x00000443, 0x80000306, 0x00000474,
- 0x8000030f, 0x00000475, 0x8000030f, 0x00000416,
- 0x80000306, 0x00000436, 0x80000306, 0x00000410,
- 0x80000306, 0x00000430, 0x80000306, 0x00000410,
- 0x80000308, 0x00000430, 0x80000308, 0x00000415,
- 0x80000306, 0x00000435, 0x80000306, 0x000004d8,
- 0x80000308, 0x000004d9, 0x80000308, 0x00000416,
- 0x80000308, 0x00000436, 0x80000308, 0x00000417,
- 0x80000308, 0x00000437, 0x80000308, 0x00000418,
- 0x80000304, 0x00000438, 0x80000304, 0x00000418,
- 0x80000308, 0x00000438, 0x80000308, 0x0000041e,
- 0x80000308, 0x0000043e, 0x80000308, 0x000004e8,
- 0x80000308, 0x000004e9, 0x80000308, 0x0000042d,
- 0x80000308, 0x0000044d, 0x80000308, 0x00000423,
- 0x80000304, 0x00000443, 0x80000304, 0x00000423,
- 0x80000308, 0x00000443, 0x80000308, 0x00000423,
- 0x8000030b, 0x00000443, 0x8000030b, 0x00000427,
- 0x80000308, 0x00000447, 0x80000308, 0x0000042b,
- 0x80000308, 0x0000044b, 0x80000308, 0x00000565,
- 0x80000582, 0x00000627, 0x80000653, 0x00000627,
- 0x80000654, 0x00000648, 0x80000654, 0x00000627,
- 0x80000655, 0x0000064a, 0x80000654, 0x00000627,
- 0x80000674, 0x00000648, 0x80000674, 0x000006c7,
- 0x80000674, 0x0000064a, 0x80000674, 0x000006d5,
- 0x80000654, 0x000006c1, 0x80000654, 0x000006d2,
- 0x80000654, 0x00000928, 0x8000093c, 0x00000930,
- 0x8000093c, 0x00000933, 0x8000093c, 0x00000915,
- 0x8000093c, 0x00000916, 0x8000093c, 0x00000917,
- 0x8000093c, 0x0000091c, 0x8000093c, 0x00000921,
- 0x8000093c, 0x00000922, 0x8000093c, 0x0000092b,
- 0x8000093c, 0x0000092f, 0x8000093c, 0x000009c7,
- 0x800009be, 0x000009c7, 0x800009d7, 0x000009a1,
- 0x800009bc, 0x000009a2, 0x800009bc, 0x000009af,
- 0x800009bc, 0x00000a32, 0x80000a3c, 0x00000a38,
- 0x80000a3c, 0x00000a16, 0x80000a3c, 0x00000a17,
- 0x80000a3c, 0x00000a1c, 0x80000a3c, 0x00000a2b,
- 0x80000a3c, 0x00000b47, 0x80000b56, 0x00000b47,
- 0x80000b3e, 0x00000b47, 0x80000b57, 0x00000b21,
- 0x80000b3c, 0x00000b22, 0x80000b3c, 0x00000b92,
- 0x80000bd7, 0x00000bc6, 0x80000bbe, 0x00000bc7,
- 0x80000bbe, 0x00000bc6, 0x80000bd7, 0x00000c46,
- 0x80000c56, 0x00000cbf, 0x80000cd5, 0x00000cc6,
- 0x80000cd5, 0x00000cc6, 0x80000cd6, 0x00000cc6,
- 0x80000cc2, 0x00000cca, 0x80000cd5, 0x00000d46,
- 0x80000d3e, 0x00000d47, 0x80000d3e, 0x00000d46,
- 0x80000d57, 0x00000dd9, 0x80000dca, 0x00000dd9,
- 0x80000dcf, 0x00000ddc, 0x80000dca, 0x00000dd9,
- 0x80000ddf, 0x00000e4d, 0x80000e32, 0x00000ecd,
- 0x80000eb2, 0x00000eab, 0x80000e99, 0x00000eab,
- 0x80000ea1, 0x80000f0b, 0x00000f42, 0x80000fb7,
- 0x00000f4c, 0x80000fb7, 0x00000f51, 0x80000fb7,
- 0x00000f56, 0x80000fb7, 0x00000f5b, 0x80000fb7,
- 0x00000f40, 0x80000fb5, 0x00000f71, 0x80000f72,
- 0x00000f71, 0x80000f74, 0x00000fb2, 0x80000f80,
- 0x00000fb2, 0x80000f81, 0x00000fb3, 0x80000f80,
- 0x00000fb3, 0x80000f81, 0x00000f71, 0x80000f80,
- 0x00000f92, 0x80000fb7, 0x00000f9c, 0x80000fb7,
- 0x00000fa1, 0x80000fb7, 0x00000fa6, 0x80000fb7,
- 0x00000fab, 0x80000fb7, 0x00000f90, 0x80000fb5,
- 0x00001025, 0x8000102e, 0x800010dc, 0x80000041,
- 0x800000c6, 0x80000042, 0x80000044, 0x80000045,
- 0x8000018e, 0x80000047, 0x80000048, 0x80000049,
- 0x8000004a, 0x8000004b, 0x8000004c, 0x8000004d,
- 0x8000004e, 0x8000004f, 0x80000222, 0x80000050,
- 0x80000052, 0x80000054, 0x80000055, 0x80000057,
- 0x80000061, 0x80000250, 0x80000251, 0x80001d02,
- 0x80000062, 0x80000064, 0x80000065, 0x80000259,
- 0x8000025b, 0x8000025c, 0x80000067, 0x8000006b,
- 0x8000006d, 0x8000014b, 0x8000006f, 0x80000254,
- 0x80001d16, 0x80001d17, 0x80000070, 0x80000074,
- 0x80000075, 0x80001d1d, 0x8000026f, 0x80000076,
- 0x80001d25, 0x800003b2, 0x800003b3, 0x800003b4,
- 0x800003c6, 0x800003c7, 0x80000069, 0x80000072,
- 0x80000075, 0x80000076, 0x800003b2, 0x800003b3,
- 0x800003c1, 0x800003c6, 0x800003c7, 0x8000043d,
- 0x80000252, 0x80000063, 0x80000255, 0x800000f0,
- 0x8000025c, 0x80000066, 0x8000025f, 0x80000261,
- 0x80000265, 0x80000268, 0x80000269, 0x8000026a,
- 0x80001d7b, 0x8000029d, 0x8000026d, 0x80001d85,
- 0x8000029f, 0x80000271, 0x80000270, 0x80000272,
- 0x80000273, 0x80000274, 0x80000275, 0x80000278,
- 0x80000282, 0x80000283, 0x800001ab, 0x80000289,
- 0x8000028a, 0x80001d1c, 0x8000028b, 0x8000028c,
- 0x8000007a, 0x80000290, 0x80000291, 0x80000292,
- 0x800003b8, 0x00000041, 0x80000325, 0x00000061,
- 0x80000325, 0x00000042, 0x80000307, 0x00000062,
- 0x80000307, 0x00000042, 0x80000323, 0x00000062,
- 0x80000323, 0x00000042, 0x80000331, 0x00000062,
- 0x80000331, 0x000000c7, 0x80000301, 0x000000e7,
- 0x80000301, 0x00000044, 0x80000307, 0x00000064,
- 0x80000307, 0x00000044, 0x80000323, 0x00000064,
- 0x80000323, 0x00000044, 0x80000331, 0x00000064,
- 0x80000331, 0x00000044, 0x80000327, 0x00000064,
- 0x80000327, 0x00000044, 0x8000032d, 0x00000064,
- 0x8000032d, 0x00000112, 0x80000300, 0x00000113,
- 0x80000300, 0x00000112, 0x80000301, 0x00000113,
- 0x80000301, 0x00000045, 0x8000032d, 0x00000065,
- 0x8000032d, 0x00000045, 0x80000330, 0x00000065,
- 0x80000330, 0x00000228, 0x80000306, 0x00000229,
- 0x80000306, 0x00000046, 0x80000307, 0x00000066,
- 0x80000307, 0x00000047, 0x80000304, 0x00000067,
- 0x80000304, 0x00000048, 0x80000307, 0x00000068,
- 0x80000307, 0x00000048, 0x80000323, 0x00000068,
- 0x80000323, 0x00000048, 0x80000308, 0x00000068,
- 0x80000308, 0x00000048, 0x80000327, 0x00000068,
- 0x80000327, 0x00000048, 0x8000032e, 0x00000068,
- 0x8000032e, 0x00000049, 0x80000330, 0x00000069,
- 0x80000330, 0x000000cf, 0x80000301, 0x000000ef,
- 0x80000301, 0x0000004b, 0x80000301, 0x0000006b,
- 0x80000301, 0x0000004b, 0x80000323, 0x0000006b,
- 0x80000323, 0x0000004b, 0x80000331, 0x0000006b,
- 0x80000331, 0x0000004c, 0x80000323, 0x0000006c,
- 0x80000323, 0x00001e36, 0x80000304, 0x00001e37,
- 0x80000304, 0x0000004c, 0x80000331, 0x0000006c,
- 0x80000331, 0x0000004c, 0x8000032d, 0x0000006c,
- 0x8000032d, 0x0000004d, 0x80000301, 0x0000006d,
- 0x80000301, 0x0000004d, 0x80000307, 0x0000006d,
- 0x80000307, 0x0000004d, 0x80000323, 0x0000006d,
- 0x80000323, 0x0000004e, 0x80000307, 0x0000006e,
- 0x80000307, 0x0000004e, 0x80000323, 0x0000006e,
- 0x80000323, 0x0000004e, 0x80000331, 0x0000006e,
- 0x80000331, 0x0000004e, 0x8000032d, 0x0000006e,
- 0x8000032d, 0x000000d5, 0x80000301, 0x000000f5,
- 0x80000301, 0x000000d5, 0x80000308, 0x000000f5,
- 0x80000308, 0x0000014c, 0x80000300, 0x0000014d,
- 0x80000300, 0x0000014c, 0x80000301, 0x0000014d,
- 0x80000301, 0x00000050, 0x80000301, 0x00000070,
- 0x80000301, 0x00000050, 0x80000307, 0x00000070,
- 0x80000307, 0x00000052, 0x80000307, 0x00000072,
- 0x80000307, 0x00000052, 0x80000323, 0x00000072,
- 0x80000323, 0x00001e5a, 0x80000304, 0x00001e5b,
- 0x80000304, 0x00000052, 0x80000331, 0x00000072,
- 0x80000331, 0x00000053, 0x80000307, 0x00000073,
- 0x80000307, 0x00000053, 0x80000323, 0x00000073,
- 0x80000323, 0x0000015a, 0x80000307, 0x0000015b,
- 0x80000307, 0x00000160, 0x80000307, 0x00000161,
- 0x80000307, 0x00001e62, 0x80000307, 0x00001e63,
- 0x80000307, 0x00000054, 0x80000307, 0x00000074,
- 0x80000307, 0x00000054, 0x80000323, 0x00000074,
- 0x80000323, 0x00000054, 0x80000331, 0x00000074,
- 0x80000331, 0x00000054, 0x8000032d, 0x00000074,
- 0x8000032d, 0x00000055, 0x80000324, 0x00000075,
- 0x80000324, 0x00000055, 0x80000330, 0x00000075,
- 0x80000330, 0x00000055, 0x8000032d, 0x00000075,
- 0x8000032d, 0x00000168, 0x80000301, 0x00000169,
- 0x80000301, 0x0000016a, 0x80000308, 0x0000016b,
- 0x80000308, 0x00000056, 0x80000303, 0x00000076,
- 0x80000303, 0x00000056, 0x80000323, 0x00000076,
- 0x80000323, 0x00000057, 0x80000300, 0x00000077,
- 0x80000300, 0x00000057, 0x80000301, 0x00000077,
- 0x80000301, 0x00000057, 0x80000308, 0x00000077,
- 0x80000308, 0x00000057, 0x80000307, 0x00000077,
- 0x80000307, 0x00000057, 0x80000323, 0x00000077,
- 0x80000323, 0x00000058, 0x80000307, 0x00000078,
- 0x80000307, 0x00000058, 0x80000308, 0x00000078,
- 0x80000308, 0x00000059, 0x80000307, 0x00000079,
- 0x80000307, 0x0000005a, 0x80000302, 0x0000007a,
- 0x80000302, 0x0000005a, 0x80000323, 0x0000007a,
- 0x80000323, 0x0000005a, 0x80000331, 0x0000007a,
- 0x80000331, 0x00000068, 0x80000331, 0x00000074,
- 0x80000308, 0x00000077, 0x8000030a, 0x00000079,
- 0x8000030a, 0x00000061, 0x800002be, 0x0000017f,
- 0x80000307, 0x00000041, 0x80000323, 0x00000061,
- 0x80000323, 0x00000041, 0x80000309, 0x00000061,
- 0x80000309, 0x000000c2, 0x80000301, 0x000000e2,
- 0x80000301, 0x000000c2, 0x80000300, 0x000000e2,
- 0x80000300, 0x000000c2, 0x80000309, 0x000000e2,
- 0x80000309, 0x000000c2, 0x80000303, 0x000000e2,
- 0x80000303, 0x00001ea0, 0x80000302, 0x00001ea1,
- 0x80000302, 0x00000102, 0x80000301, 0x00000103,
- 0x80000301, 0x00000102, 0x80000300, 0x00000103,
- 0x80000300, 0x00000102, 0x80000309, 0x00000103,
- 0x80000309, 0x00000102, 0x80000303, 0x00000103,
- 0x80000303, 0x00001ea0, 0x80000306, 0x00001ea1,
- 0x80000306, 0x00000045, 0x80000323, 0x00000065,
- 0x80000323, 0x00000045, 0x80000309, 0x00000065,
- 0x80000309, 0x00000045, 0x80000303, 0x00000065,
- 0x80000303, 0x000000ca, 0x80000301, 0x000000ea,
- 0x80000301, 0x000000ca, 0x80000300, 0x000000ea,
- 0x80000300, 0x000000ca, 0x80000309, 0x000000ea,
- 0x80000309, 0x000000ca, 0x80000303, 0x000000ea,
- 0x80000303, 0x00001eb8, 0x80000302, 0x00001eb9,
- 0x80000302, 0x00000049, 0x80000309, 0x00000069,
- 0x80000309, 0x00000049, 0x80000323, 0x00000069,
- 0x80000323, 0x0000004f, 0x80000323, 0x0000006f,
- 0x80000323, 0x0000004f, 0x80000309, 0x0000006f,
- 0x80000309, 0x000000d4, 0x80000301, 0x000000f4,
- 0x80000301, 0x000000d4, 0x80000300, 0x000000f4,
- 0x80000300, 0x000000d4, 0x80000309, 0x000000f4,
- 0x80000309, 0x000000d4, 0x80000303, 0x000000f4,
- 0x80000303, 0x00001ecc, 0x80000302, 0x00001ecd,
- 0x80000302, 0x000001a0, 0x80000301, 0x000001a1,
- 0x80000301, 0x000001a0, 0x80000300, 0x000001a1,
- 0x80000300, 0x000001a0, 0x80000309, 0x000001a1,
- 0x80000309, 0x000001a0, 0x80000303, 0x000001a1,
- 0x80000303, 0x000001a0, 0x80000323, 0x000001a1,
- 0x80000323, 0x00000055, 0x80000323, 0x00000075,
- 0x80000323, 0x00000055, 0x80000309, 0x00000075,
- 0x80000309, 0x000001af, 0x80000301, 0x000001b0,
- 0x80000301, 0x000001af, 0x80000300, 0x000001b0,
- 0x80000300, 0x000001af, 0x80000309, 0x000001b0,
- 0x80000309, 0x000001af, 0x80000303, 0x000001b0,
- 0x80000303, 0x000001af, 0x80000323, 0x000001b0,
- 0x80000323, 0x00000059, 0x80000300, 0x00000079,
- 0x80000300, 0x00000059, 0x80000323, 0x00000079,
- 0x80000323, 0x00000059, 0x80000309, 0x00000079,
- 0x80000309, 0x00000059, 0x80000303, 0x00000079,
- 0x80000303, 0x000003b1, 0x80000313, 0x000003b1,
- 0x80000314, 0x00001f00, 0x80000300, 0x00001f01,
- 0x80000300, 0x00001f00, 0x80000301, 0x00001f01,
- 0x80000301, 0x00001f00, 0x80000342, 0x00001f01,
- 0x80000342, 0x00000391, 0x80000313, 0x00000391,
- 0x80000314, 0x00001f08, 0x80000300, 0x00001f09,
- 0x80000300, 0x00001f08, 0x80000301, 0x00001f09,
- 0x80000301, 0x00001f08, 0x80000342, 0x00001f09,
- 0x80000342, 0x000003b5, 0x80000313, 0x000003b5,
- 0x80000314, 0x00001f10, 0x80000300, 0x00001f11,
- 0x80000300, 0x00001f10, 0x80000301, 0x00001f11,
- 0x80000301, 0x00000395, 0x80000313, 0x00000395,
- 0x80000314, 0x00001f18, 0x80000300, 0x00001f19,
- 0x80000300, 0x00001f18, 0x80000301, 0x00001f19,
- 0x80000301, 0x000003b7, 0x80000313, 0x000003b7,
- 0x80000314, 0x00001f20, 0x80000300, 0x00001f21,
- 0x80000300, 0x00001f20, 0x80000301, 0x00001f21,
- 0x80000301, 0x00001f20, 0x80000342, 0x00001f21,
- 0x80000342, 0x00000397, 0x80000313, 0x00000397,
- 0x80000314, 0x00001f28, 0x80000300, 0x00001f29,
- 0x80000300, 0x00001f28, 0x80000301, 0x00001f29,
- 0x80000301, 0x00001f28, 0x80000342, 0x00001f29,
- 0x80000342, 0x000003b9, 0x80000313, 0x000003b9,
- 0x80000314, 0x00001f30, 0x80000300, 0x00001f31,
- 0x80000300, 0x00001f30, 0x80000301, 0x00001f31,
- 0x80000301, 0x00001f30, 0x80000342, 0x00001f31,
- 0x80000342, 0x00000399, 0x80000313, 0x00000399,
- 0x80000314, 0x00001f38, 0x80000300, 0x00001f39,
- 0x80000300, 0x00001f38, 0x80000301, 0x00001f39,
- 0x80000301, 0x00001f38, 0x80000342, 0x00001f39,
- 0x80000342, 0x000003bf, 0x80000313, 0x000003bf,
- 0x80000314, 0x00001f40, 0x80000300, 0x00001f41,
- 0x80000300, 0x00001f40, 0x80000301, 0x00001f41,
- 0x80000301, 0x0000039f, 0x80000313, 0x0000039f,
- 0x80000314, 0x00001f48, 0x80000300, 0x00001f49,
- 0x80000300, 0x00001f48, 0x80000301, 0x00001f49,
- 0x80000301, 0x000003c5, 0x80000313, 0x000003c5,
- 0x80000314, 0x00001f50, 0x80000300, 0x00001f51,
- 0x80000300, 0x00001f50, 0x80000301, 0x00001f51,
- 0x80000301, 0x00001f50, 0x80000342, 0x00001f51,
- 0x80000342, 0x000003a5, 0x80000314, 0x00001f59,
- 0x80000300, 0x00001f59, 0x80000301, 0x00001f59,
- 0x80000342, 0x000003c9, 0x80000313, 0x000003c9,
- 0x80000314, 0x00001f60, 0x80000300, 0x00001f61,
- 0x80000300, 0x00001f60, 0x80000301, 0x00001f61,
- 0x80000301, 0x00001f60, 0x80000342, 0x00001f61,
- 0x80000342, 0x000003a9, 0x80000313, 0x000003a9,
- 0x80000314, 0x00001f68, 0x80000300, 0x00001f69,
- 0x80000300, 0x00001f68, 0x80000301, 0x00001f69,
- 0x80000301, 0x00001f68, 0x80000342, 0x00001f69,
- 0x80000342, 0x000003b1, 0x80000300, 0x800003ac,
- 0x000003b5, 0x80000300, 0x800003ad, 0x000003b7,
- 0x80000300, 0x800003ae, 0x000003b9, 0x80000300,
- 0x800003af, 0x000003bf, 0x80000300, 0x800003cc,
- 0x000003c5, 0x80000300, 0x800003cd, 0x000003c9,
- 0x80000300, 0x800003ce, 0x00001f00, 0x80000345,
- 0x00001f01, 0x80000345, 0x00001f02, 0x80000345,
- 0x00001f03, 0x80000345, 0x00001f04, 0x80000345,
- 0x00001f05, 0x80000345, 0x00001f06, 0x80000345,
- 0x00001f07, 0x80000345, 0x00001f08, 0x80000345,
- 0x00001f09, 0x80000345, 0x00001f0a, 0x80000345,
- 0x00001f0b, 0x80000345, 0x00001f0c, 0x80000345,
- 0x00001f0d, 0x80000345, 0x00001f0e, 0x80000345,
- 0x00001f0f, 0x80000345, 0x00001f20, 0x80000345,
- 0x00001f21, 0x80000345, 0x00001f22, 0x80000345,
- 0x00001f23, 0x80000345, 0x00001f24, 0x80000345,
- 0x00001f25, 0x80000345, 0x00001f26, 0x80000345,
- 0x00001f27, 0x80000345, 0x00001f28, 0x80000345,
- 0x00001f29, 0x80000345, 0x00001f2a, 0x80000345,
- 0x00001f2b, 0x80000345, 0x00001f2c, 0x80000345,
- 0x00001f2d, 0x80000345, 0x00001f2e, 0x80000345,
- 0x00001f2f, 0x80000345, 0x00001f60, 0x80000345,
- 0x00001f61, 0x80000345, 0x00001f62, 0x80000345,
- 0x00001f63, 0x80000345, 0x00001f64, 0x80000345,
- 0x00001f65, 0x80000345, 0x00001f66, 0x80000345,
- 0x00001f67, 0x80000345, 0x00001f68, 0x80000345,
- 0x00001f69, 0x80000345, 0x00001f6a, 0x80000345,
- 0x00001f6b, 0x80000345, 0x00001f6c, 0x80000345,
- 0x00001f6d, 0x80000345, 0x00001f6e, 0x80000345,
- 0x00001f6f, 0x80000345, 0x000003b1, 0x80000306,
- 0x000003b1, 0x80000304, 0x00001f70, 0x80000345,
- 0x000003b1, 0x80000345, 0x000003ac, 0x80000345,
- 0x000003b1, 0x80000342, 0x00001fb6, 0x80000345,
- 0x00000391, 0x80000306, 0x00000391, 0x80000304,
- 0x00000391, 0x80000300, 0x80000386, 0x00000391,
- 0x80000345, 0x00000020, 0x80000313, 0x800003b9,
- 0x00000020, 0x80000313, 0x00000020, 0x80000342,
- 0x000000a8, 0x80000342, 0x00001f74, 0x80000345,
- 0x000003b7, 0x80000345, 0x000003ae, 0x80000345,
- 0x000003b7, 0x80000342, 0x00001fc6, 0x80000345,
- 0x00000395, 0x80000300, 0x80000388, 0x00000397,
- 0x80000300, 0x80000389, 0x00000397, 0x80000345,
- 0x00001fbf, 0x80000300, 0x00001fbf, 0x80000301,
- 0x00001fbf, 0x80000342, 0x000003b9, 0x80000306,
- 0x000003b9, 0x80000304, 0x000003ca, 0x80000300,
- 0x80000390, 0x000003b9, 0x80000342, 0x000003ca,
- 0x80000342, 0x00000399, 0x80000306, 0x00000399,
- 0x80000304, 0x00000399, 0x80000300, 0x8000038a,
- 0x00001ffe, 0x80000300, 0x00001ffe, 0x80000301,
- 0x00001ffe, 0x80000342, 0x000003c5, 0x80000306,
- 0x000003c5, 0x80000304, 0x000003cb, 0x80000300,
- 0x800003b0, 0x000003c1, 0x80000313, 0x000003c1,
- 0x80000314, 0x000003c5, 0x80000342, 0x000003cb,
- 0x80000342, 0x000003a5, 0x80000306, 0x000003a5,
- 0x80000304, 0x000003a5, 0x80000300, 0x8000038e,
- 0x000003a1, 0x80000314, 0x000000a8, 0x80000300,
- 0x80000385, 0x80000060, 0x00001f7c, 0x80000345,
- 0x000003c9, 0x80000345, 0x000003ce, 0x80000345,
- 0x000003c9, 0x80000342, 0x00001ff6, 0x80000345,
- 0x0000039f, 0x80000300, 0x8000038c, 0x000003a9,
- 0x80000300, 0x8000038f, 0x000003a9, 0x80000345,
- 0x800000b4, 0x00000020, 0x80000314, 0x80002002,
- 0x80002003, 0x80000020, 0x80000020, 0x80000020,
- 0x80000020, 0x80000020, 0x80000020, 0x80000020,
- 0x80000020, 0x80000020, 0x80002010, 0x00000020,
- 0x80000333, 0x8000002e, 0x0000002e, 0x8000002e,
- 0x0000002e, 0x0000002e, 0x8000002e, 0x80000020,
- 0x00002032, 0x80002032, 0x00002032, 0x00002032,
- 0x80002032, 0x00002035, 0x80002035, 0x00002035,
- 0x00002035, 0x80002035, 0x00000021, 0x80000021,
- 0x00000020, 0x80000305, 0x0000003f, 0x8000003f,
- 0x0000003f, 0x80000021, 0x00000021, 0x8000003f,
- 0x00002032, 0x00002032, 0x00002032, 0x80002032,
- 0x80000020, 0x80000030, 0x80000069, 0x80000034,
- 0x80000035, 0x80000036, 0x80000037, 0x80000038,
- 0x80000039, 0x8000002b, 0x80002212, 0x8000003d,
- 0x80000028, 0x80000029, 0x8000006e, 0x80000030,
- 0x80000031, 0x80000032, 0x80000033, 0x80000034,
- 0x80000035, 0x80000036, 0x80000037, 0x80000038,
- 0x80000039, 0x8000002b, 0x80002212, 0x8000003d,
- 0x80000028, 0x80000029, 0x80000061, 0x80000065,
- 0x8000006f, 0x80000078, 0x80000259, 0x00000052,
- 0x80000073, 0x00000061, 0x0000002f, 0x80000063,
- 0x00000061, 0x0000002f, 0x80000073, 0x80000043,
- 0x000000b0, 0x80000043, 0x00000063, 0x0000002f,
- 0x8000006f, 0x00000063, 0x0000002f, 0x80000075,
- 0x80000190, 0x000000b0, 0x80000046, 0x80000067,
- 0x80000048, 0x80000048, 0x80000048, 0x80000068,
- 0x80000127, 0x80000049, 0x80000049, 0x8000004c,
- 0x8000006c, 0x8000004e, 0x0000004e, 0x8000006f,
- 0x80000050, 0x80000051, 0x80000052, 0x80000052,
- 0x80000052, 0x00000053, 0x8000004d, 0x00000054,
- 0x00000045, 0x8000004c, 0x00000054, 0x8000004d,
- 0x8000005a, 0x800003a9, 0x8000005a, 0x8000004b,
- 0x800000c5, 0x80000042, 0x80000043, 0x80000065,
- 0x80000045, 0x80000046, 0x8000004d, 0x8000006f,
- 0x800005d0, 0x800005d1, 0x800005d2, 0x800005d3,
- 0x80000069, 0x00000046, 0x00000041, 0x80000058,
- 0x800003c0, 0x800003b3, 0x80000393, 0x800003a0,
- 0x80002211, 0x80000044, 0x80000064, 0x80000065,
- 0x80000069, 0x8000006a, 0x00000031, 0x00002044,
- 0x80000033, 0x00000032, 0x00002044, 0x80000033,
- 0x00000031, 0x00002044, 0x80000035, 0x00000032,
- 0x00002044, 0x80000035, 0x00000033, 0x00002044,
- 0x80000035, 0x00000034, 0x00002044, 0x80000035,
- 0x00000031, 0x00002044, 0x80000036, 0x00000035,
- 0x00002044, 0x80000036, 0x00000031, 0x00002044,
- 0x80000038, 0x00000033, 0x00002044, 0x80000038,
- 0x00000035, 0x00002044, 0x80000038, 0x00000037,
- 0x00002044, 0x80000038, 0x00000031, 0x80002044,
- 0x80000049, 0x00000049, 0x80000049, 0x00000049,
- 0x00000049, 0x80000049, 0x00000049, 0x80000056,
- 0x80000056, 0x00000056, 0x80000049, 0x00000056,
- 0x00000049, 0x80000049, 0x00000056, 0x00000049,
- 0x00000049, 0x80000049, 0x00000049, 0x80000058,
- 0x80000058, 0x00000058, 0x80000049, 0x00000058,
- 0x00000049, 0x80000049, 0x8000004c, 0x80000043,
- 0x80000044, 0x8000004d, 0x80000069, 0x00000069,
- 0x80000069, 0x00000069, 0x00000069, 0x80000069,
- 0x00000069, 0x80000076, 0x80000076, 0x00000076,
- 0x80000069, 0x00000076, 0x00000069, 0x80000069,
- 0x00000076, 0x00000069, 0x00000069, 0x80000069,
- 0x00000069, 0x80000078, 0x80000078, 0x00000078,
- 0x80000069, 0x00000078, 0x00000069, 0x80000069,
- 0x8000006c, 0x80000063, 0x80000064, 0x8000006d,
- 0x00002190, 0x80000338, 0x00002192, 0x80000338,
- 0x00002194, 0x80000338, 0x000021d0, 0x80000338,
- 0x000021d4, 0x80000338, 0x000021d2, 0x80000338,
- 0x00002203, 0x80000338, 0x00002208, 0x80000338,
- 0x0000220b, 0x80000338, 0x00002223, 0x80000338,
- 0x00002225, 0x80000338, 0x0000222b, 0x8000222b,
- 0x0000222b, 0x0000222b, 0x8000222b, 0x0000222e,
- 0x8000222e, 0x0000222e, 0x0000222e, 0x8000222e,
- 0x0000223c, 0x80000338, 0x00002243, 0x80000338,
- 0x00002245, 0x80000338, 0x00002248, 0x80000338,
- 0x0000003d, 0x80000338, 0x00002261, 0x80000338,
- 0x0000224d, 0x80000338, 0x0000003c, 0x80000338,
- 0x0000003e, 0x80000338, 0x00002264, 0x80000338,
- 0x00002265, 0x80000338, 0x00002272, 0x80000338,
- 0x00002273, 0x80000338, 0x00002276, 0x80000338,
- 0x00002277, 0x80000338, 0x0000227a, 0x80000338,
- 0x0000227b, 0x80000338, 0x00002282, 0x80000338,
- 0x00002283, 0x80000338, 0x00002286, 0x80000338,
- 0x00002287, 0x80000338, 0x000022a2, 0x80000338,
- 0x000022a8, 0x80000338, 0x000022a9, 0x80000338,
- 0x000022ab, 0x80000338, 0x0000227c, 0x80000338,
- 0x0000227d, 0x80000338, 0x00002291, 0x80000338,
- 0x00002292, 0x80000338, 0x000022b2, 0x80000338,
- 0x000022b3, 0x80000338, 0x000022b4, 0x80000338,
- 0x000022b5, 0x80000338, 0x80003008, 0x80003009,
- 0x80000031, 0x80000032, 0x80000033, 0x80000034,
- 0x80000035, 0x80000036, 0x80000037, 0x80000038,
- 0x80000039, 0x00000031, 0x80000030, 0x00000031,
- 0x80000031, 0x00000031, 0x80000032, 0x00000031,
- 0x80000033, 0x00000031, 0x80000034, 0x00000031,
- 0x80000035, 0x00000031, 0x80000036, 0x00000031,
- 0x80000037, 0x00000031, 0x80000038, 0x00000031,
- 0x80000039, 0x00000032, 0x80000030, 0x00000028,
- 0x00000031, 0x80000029, 0x00000028, 0x00000032,
- 0x80000029, 0x00000028, 0x00000033, 0x80000029,
- 0x00000028, 0x00000034, 0x80000029, 0x00000028,
- 0x00000035, 0x80000029, 0x00000028, 0x00000036,
- 0x80000029, 0x00000028, 0x00000037, 0x80000029,
- 0x00000028, 0x00000038, 0x80000029, 0x00000028,
- 0x00000039, 0x80000029, 0x00000028, 0x00000031,
- 0x00000030, 0x80000029, 0x00000028, 0x00000031,
- 0x00000031, 0x80000029, 0x00000028, 0x00000031,
- 0x00000032, 0x80000029, 0x00000028, 0x00000031,
- 0x00000033, 0x80000029, 0x00000028, 0x00000031,
- 0x00000034, 0x80000029, 0x00000028, 0x00000031,
- 0x00000035, 0x80000029, 0x00000028, 0x00000031,
- 0x00000036, 0x80000029, 0x00000028, 0x00000031,
- 0x00000037, 0x80000029, 0x00000028, 0x00000031,
- 0x00000038, 0x80000029, 0x00000028, 0x00000031,
- 0x00000039, 0x80000029, 0x00000028, 0x00000032,
- 0x00000030, 0x80000029, 0x00000031, 0x8000002e,
- 0x00000032, 0x8000002e, 0x00000033, 0x8000002e,
- 0x00000034, 0x8000002e, 0x00000035, 0x8000002e,
- 0x00000036, 0x8000002e, 0x00000037, 0x8000002e,
- 0x00000038, 0x8000002e, 0x00000039, 0x8000002e,
- 0x00000031, 0x00000030, 0x8000002e, 0x00000031,
- 0x00000031, 0x8000002e, 0x00000031, 0x00000032,
- 0x8000002e, 0x00000031, 0x00000033, 0x8000002e,
- 0x00000031, 0x00000034, 0x8000002e, 0x00000031,
- 0x00000035, 0x8000002e, 0x00000031, 0x00000036,
- 0x8000002e, 0x00000031, 0x00000037, 0x8000002e,
- 0x00000031, 0x00000038, 0x8000002e, 0x00000031,
- 0x00000039, 0x8000002e, 0x00000032, 0x00000030,
- 0x8000002e, 0x00000028, 0x00000061, 0x80000029,
- 0x00000028, 0x00000062, 0x80000029, 0x00000028,
- 0x00000063, 0x80000029, 0x00000028, 0x00000064,
- 0x80000029, 0x00000028, 0x00000065, 0x80000029,
- 0x00000028, 0x00000066, 0x80000029, 0x00000028,
- 0x00000067, 0x80000029, 0x00000028, 0x00000068,
- 0x80000029, 0x00000028, 0x00000069, 0x80000029,
- 0x00000028, 0x0000006a, 0x80000029, 0x00000028,
- 0x0000006b, 0x80000029, 0x00000028, 0x0000006c,
- 0x80000029, 0x00000028, 0x0000006d, 0x80000029,
- 0x00000028, 0x0000006e, 0x80000029, 0x00000028,
- 0x0000006f, 0x80000029, 0x00000028, 0x00000070,
- 0x80000029, 0x00000028, 0x00000071, 0x80000029,
- 0x00000028, 0x00000072, 0x80000029, 0x00000028,
- 0x00000073, 0x80000029, 0x00000028, 0x00000074,
- 0x80000029, 0x00000028, 0x00000075, 0x80000029,
- 0x00000028, 0x00000076, 0x80000029, 0x00000028,
- 0x00000077, 0x80000029, 0x00000028, 0x00000078,
- 0x80000029, 0x00000028, 0x00000079, 0x80000029,
- 0x00000028, 0x0000007a, 0x80000029, 0x80000041,
- 0x80000042, 0x80000043, 0x80000044, 0x80000045,
- 0x80000046, 0x80000047, 0x80000048, 0x80000049,
- 0x8000004a, 0x8000004b, 0x8000004c, 0x8000004d,
- 0x8000004e, 0x8000004f, 0x80000050, 0x80000051,
- 0x80000052, 0x80000053, 0x80000054, 0x80000055,
- 0x80000056, 0x80000057, 0x80000058, 0x80000059,
- 0x8000005a, 0x80000061, 0x80000062, 0x80000063,
- 0x80000064, 0x80000065, 0x80000066, 0x80000067,
- 0x80000068, 0x80000069, 0x8000006a, 0x8000006b,
- 0x8000006c, 0x8000006d, 0x8000006e, 0x8000006f,
- 0x80000070, 0x80000071, 0x80000072, 0x80000073,
- 0x80000074, 0x80000075, 0x80000076, 0x80000077,
- 0x80000078, 0x80000079, 0x8000007a, 0x80000030,
- 0x0000222b, 0x0000222b, 0x0000222b, 0x8000222b,
- 0x0000003a, 0x0000003a, 0x8000003d, 0x0000003d,
- 0x8000003d, 0x0000003d, 0x0000003d, 0x8000003d,
- 0x00002add, 0x80000338, 0x80002d61, 0x80006bcd,
- 0x80009f9f, 0x80004e00, 0x80004e28, 0x80004e36,
- 0x80004e3f, 0x80004e59, 0x80004e85, 0x80004e8c,
- 0x80004ea0, 0x80004eba, 0x8000513f, 0x80005165,
- 0x8000516b, 0x80005182, 0x80005196, 0x800051ab,
- 0x800051e0, 0x800051f5, 0x80005200, 0x8000529b,
- 0x800052f9, 0x80005315, 0x8000531a, 0x80005338,
- 0x80005341, 0x8000535c, 0x80005369, 0x80005382,
- 0x800053b6, 0x800053c8, 0x800053e3, 0x800056d7,
- 0x8000571f, 0x800058eb, 0x80005902, 0x8000590a,
- 0x80005915, 0x80005927, 0x80005973, 0x80005b50,
- 0x80005b80, 0x80005bf8, 0x80005c0f, 0x80005c22,
- 0x80005c38, 0x80005c6e, 0x80005c71, 0x80005ddb,
- 0x80005de5, 0x80005df1, 0x80005dfe, 0x80005e72,
- 0x80005e7a, 0x80005e7f, 0x80005ef4, 0x80005efe,
- 0x80005f0b, 0x80005f13, 0x80005f50, 0x80005f61,
- 0x80005f73, 0x80005fc3, 0x80006208, 0x80006236,
- 0x8000624b, 0x8000652f, 0x80006534, 0x80006587,
- 0x80006597, 0x800065a4, 0x800065b9, 0x800065e0,
- 0x800065e5, 0x800066f0, 0x80006708, 0x80006728,
- 0x80006b20, 0x80006b62, 0x80006b79, 0x80006bb3,
- 0x80006bcb, 0x80006bd4, 0x80006bdb, 0x80006c0f,
- 0x80006c14, 0x80006c34, 0x8000706b, 0x8000722a,
- 0x80007236, 0x8000723b, 0x8000723f, 0x80007247,
- 0x80007259, 0x8000725b, 0x800072ac, 0x80007384,
- 0x80007389, 0x800074dc, 0x800074e6, 0x80007518,
- 0x8000751f, 0x80007528, 0x80007530, 0x8000758b,
- 0x80007592, 0x80007676, 0x8000767d, 0x800076ae,
- 0x800076bf, 0x800076ee, 0x800077db, 0x800077e2,
- 0x800077f3, 0x8000793a, 0x800079b8, 0x800079be,
- 0x80007a74, 0x80007acb, 0x80007af9, 0x80007c73,
- 0x80007cf8, 0x80007f36, 0x80007f51, 0x80007f8a,
- 0x80007fbd, 0x80008001, 0x8000800c, 0x80008012,
- 0x80008033, 0x8000807f, 0x80008089, 0x800081e3,
- 0x800081ea, 0x800081f3, 0x800081fc, 0x8000820c,
- 0x8000821b, 0x8000821f, 0x8000826e, 0x80008272,
- 0x80008278, 0x8000864d, 0x8000866b, 0x80008840,
- 0x8000884c, 0x80008863, 0x8000897e, 0x8000898b,
- 0x800089d2, 0x80008a00, 0x80008c37, 0x80008c46,
- 0x80008c55, 0x80008c78, 0x80008c9d, 0x80008d64,
- 0x80008d70, 0x80008db3, 0x80008eab, 0x80008eca,
- 0x80008f9b, 0x80008fb0, 0x80008fb5, 0x80009091,
- 0x80009149, 0x800091c6, 0x800091cc, 0x800091d1,
- 0x80009577, 0x80009580, 0x8000961c, 0x800096b6,
- 0x800096b9, 0x800096e8, 0x80009751, 0x8000975e,
- 0x80009762, 0x80009769, 0x800097cb, 0x800097ed,
- 0x800097f3, 0x80009801, 0x800098a8, 0x800098db,
- 0x800098df, 0x80009996, 0x80009999, 0x800099ac,
- 0x80009aa8, 0x80009ad8, 0x80009adf, 0x80009b25,
- 0x80009b2f, 0x80009b32, 0x80009b3c, 0x80009b5a,
- 0x80009ce5, 0x80009e75, 0x80009e7f, 0x80009ea5,
- 0x80009ebb, 0x80009ec3, 0x80009ecd, 0x80009ed1,
- 0x80009ef9, 0x80009efd, 0x80009f0e, 0x80009f13,
- 0x80009f20, 0x80009f3b, 0x80009f4a, 0x80009f52,
- 0x80009f8d, 0x80009f9c, 0x80009fa0, 0x80000020,
- 0x80003012, 0x80005341, 0x80005344, 0x80005345,
- 0x0000304b, 0x80003099, 0x0000304d, 0x80003099,
- 0x0000304f, 0x80003099, 0x00003051, 0x80003099,
- 0x00003053, 0x80003099, 0x00003055, 0x80003099,
- 0x00003057, 0x80003099, 0x00003059, 0x80003099,
- 0x0000305b, 0x80003099, 0x0000305d, 0x80003099,
- 0x0000305f, 0x80003099, 0x00003061, 0x80003099,
- 0x00003064, 0x80003099, 0x00003066, 0x80003099,
- 0x00003068, 0x80003099, 0x0000306f, 0x80003099,
- 0x0000306f, 0x8000309a, 0x00003072, 0x80003099,
- 0x00003072, 0x8000309a, 0x00003075, 0x80003099,
- 0x00003075, 0x8000309a, 0x00003078, 0x80003099,
- 0x00003078, 0x8000309a, 0x0000307b, 0x80003099,
- 0x0000307b, 0x8000309a, 0x00003046, 0x80003099,
- 0x00000020, 0x80003099, 0x00000020, 0x8000309a,
- 0x0000309d, 0x80003099, 0x00003088, 0x8000308a,
- 0x000030ab, 0x80003099, 0x000030ad, 0x80003099,
- 0x000030af, 0x80003099, 0x000030b1, 0x80003099,
- 0x000030b3, 0x80003099, 0x000030b5, 0x80003099,
- 0x000030b7, 0x80003099, 0x000030b9, 0x80003099,
- 0x000030bb, 0x80003099, 0x000030bd, 0x80003099,
- 0x000030bf, 0x80003099, 0x000030c1, 0x80003099,
- 0x000030c4, 0x80003099, 0x000030c6, 0x80003099,
- 0x000030c8, 0x80003099, 0x000030cf, 0x80003099,
- 0x000030cf, 0x8000309a, 0x000030d2, 0x80003099,
- 0x000030d2, 0x8000309a, 0x000030d5, 0x80003099,
- 0x000030d5, 0x8000309a, 0x000030d8, 0x80003099,
- 0x000030d8, 0x8000309a, 0x000030db, 0x80003099,
- 0x000030db, 0x8000309a, 0x000030a6, 0x80003099,
- 0x000030ef, 0x80003099, 0x000030f0, 0x80003099,
- 0x000030f1, 0x80003099, 0x000030f2, 0x80003099,
- 0x000030fd, 0x80003099, 0x000030b3, 0x800030c8,
- 0x80001100, 0x80001101, 0x800011aa, 0x80001102,
- 0x800011ac, 0x800011ad, 0x80001103, 0x80001104,
- 0x80001105, 0x800011b0, 0x800011b1, 0x800011b2,
- 0x800011b3, 0x800011b4, 0x800011b5, 0x8000111a,
- 0x80001106, 0x80001107, 0x80001108, 0x80001121,
- 0x80001109, 0x8000110a, 0x8000110b, 0x8000110c,
- 0x8000110d, 0x8000110e, 0x8000110f, 0x80001110,
- 0x80001111, 0x80001112, 0x80001161, 0x80001162,
- 0x80001163, 0x80001164, 0x80001165, 0x80001166,
- 0x80001167, 0x80001168, 0x80001169, 0x8000116a,
- 0x8000116b, 0x8000116c, 0x8000116d, 0x8000116e,
- 0x8000116f, 0x80001170, 0x80001171, 0x80001172,
- 0x80001173, 0x80001174, 0x80001175, 0x80001160,
- 0x80001114, 0x80001115, 0x800011c7, 0x800011c8,
- 0x800011cc, 0x800011ce, 0x800011d3, 0x800011d7,
- 0x800011d9, 0x8000111c, 0x800011dd, 0x800011df,
- 0x8000111d, 0x8000111e, 0x80001120, 0x80001122,
- 0x80001123, 0x80001127, 0x80001129, 0x8000112b,
- 0x8000112c, 0x8000112d, 0x8000112e, 0x8000112f,
- 0x80001132, 0x80001136, 0x80001140, 0x80001147,
- 0x8000114c, 0x800011f1, 0x800011f2, 0x80001157,
- 0x80001158, 0x80001159, 0x80001184, 0x80001185,
- 0x80001188, 0x80001191, 0x80001192, 0x80001194,
- 0x8000119e, 0x800011a1, 0x80004e00, 0x80004e8c,
- 0x80004e09, 0x800056db, 0x80004e0a, 0x80004e2d,
- 0x80004e0b, 0x80007532, 0x80004e59, 0x80004e19,
- 0x80004e01, 0x80005929, 0x80005730, 0x80004eba,
- 0x00000028, 0x00001100, 0x80000029, 0x00000028,
- 0x00001102, 0x80000029, 0x00000028, 0x00001103,
- 0x80000029, 0x00000028, 0x00001105, 0x80000029,
- 0x00000028, 0x00001106, 0x80000029, 0x00000028,
- 0x00001107, 0x80000029, 0x00000028, 0x00001109,
- 0x80000029, 0x00000028, 0x0000110b, 0x80000029,
- 0x00000028, 0x0000110c, 0x80000029, 0x00000028,
- 0x0000110e, 0x80000029, 0x00000028, 0x0000110f,
- 0x80000029, 0x00000028, 0x00001110, 0x80000029,
- 0x00000028, 0x00001111, 0x80000029, 0x00000028,
- 0x00001112, 0x80000029, 0x00000028, 0x00001100,
- 0x00001161, 0x80000029, 0x00000028, 0x00001102,
- 0x00001161, 0x80000029, 0x00000028, 0x00001103,
- 0x00001161, 0x80000029, 0x00000028, 0x00001105,
- 0x00001161, 0x80000029, 0x00000028, 0x00001106,
- 0x00001161, 0x80000029, 0x00000028, 0x00001107,
- 0x00001161, 0x80000029, 0x00000028, 0x00001109,
- 0x00001161, 0x80000029, 0x00000028, 0x0000110b,
- 0x00001161, 0x80000029, 0x00000028, 0x0000110c,
- 0x00001161, 0x80000029, 0x00000028, 0x0000110e,
- 0x00001161, 0x80000029, 0x00000028, 0x0000110f,
- 0x00001161, 0x80000029, 0x00000028, 0x00001110,
- 0x00001161, 0x80000029, 0x00000028, 0x00001111,
- 0x00001161, 0x80000029, 0x00000028, 0x00001112,
- 0x00001161, 0x80000029, 0x00000028, 0x0000110c,
- 0x0000116e, 0x80000029, 0x00000028, 0x0000110b,
- 0x00001169, 0x0000110c, 0x00001165, 0x000011ab,
- 0x80000029, 0x00000028, 0x0000110b, 0x00001169,
- 0x00001112, 0x0000116e, 0x80000029, 0x00000028,
- 0x00004e00, 0x80000029, 0x00000028, 0x00004e8c,
- 0x80000029, 0x00000028, 0x00004e09, 0x80000029,
- 0x00000028, 0x000056db, 0x80000029, 0x00000028,
- 0x00004e94, 0x80000029, 0x00000028, 0x0000516d,
- 0x80000029, 0x00000028, 0x00004e03, 0x80000029,
- 0x00000028, 0x0000516b, 0x80000029, 0x00000028,
- 0x00004e5d, 0x80000029, 0x00000028, 0x00005341,
- 0x80000029, 0x00000028, 0x00006708, 0x80000029,
- 0x00000028, 0x0000706b, 0x80000029, 0x00000028,
- 0x00006c34, 0x80000029, 0x00000028, 0x00006728,
- 0x80000029, 0x00000028, 0x000091d1, 0x80000029,
- 0x00000028, 0x0000571f, 0x80000029, 0x00000028,
- 0x000065e5, 0x80000029, 0x00000028, 0x0000682a,
- 0x80000029, 0x00000028, 0x00006709, 0x80000029,
- 0x00000028, 0x0000793e, 0x80000029, 0x00000028,
- 0x0000540d, 0x80000029, 0x00000028, 0x00007279,
- 0x80000029, 0x00000028, 0x00008ca1, 0x80000029,
- 0x00000028, 0x0000795d, 0x80000029, 0x00000028,
- 0x000052b4, 0x80000029, 0x00000028, 0x00004ee3,
- 0x80000029, 0x00000028, 0x0000547c, 0x80000029,
- 0x00000028, 0x00005b66, 0x80000029, 0x00000028,
- 0x000076e3, 0x80000029, 0x00000028, 0x00004f01,
- 0x80000029, 0x00000028, 0x00008cc7, 0x80000029,
- 0x00000028, 0x00005354, 0x80000029, 0x00000028,
- 0x0000796d, 0x80000029, 0x00000028, 0x00004f11,
- 0x80000029, 0x00000028, 0x000081ea, 0x80000029,
- 0x00000028, 0x000081f3, 0x80000029, 0x00000050,
- 0x00000054, 0x80000045, 0x00000032, 0x80000031,
- 0x00000032, 0x80000032, 0x00000032, 0x80000033,
- 0x00000032, 0x80000034, 0x00000032, 0x80000035,
- 0x00000032, 0x80000036, 0x00000032, 0x80000037,
- 0x00000032, 0x80000038, 0x00000032, 0x80000039,
- 0x00000033, 0x80000030, 0x00000033, 0x80000031,
- 0x00000033, 0x80000032, 0x00000033, 0x80000033,
- 0x00000033, 0x80000034, 0x00000033, 0x80000035,
- 0x80001100, 0x80001102, 0x80001103, 0x80001105,
- 0x80001106, 0x80001107, 0x80001109, 0x8000110b,
- 0x8000110c, 0x8000110e, 0x8000110f, 0x80001110,
- 0x80001111, 0x80001112, 0x00001100, 0x80001161,
- 0x00001102, 0x80001161, 0x00001103, 0x80001161,
- 0x00001105, 0x80001161, 0x00001106, 0x80001161,
- 0x00001107, 0x80001161, 0x00001109, 0x80001161,
- 0x0000110b, 0x80001161, 0x0000110c, 0x80001161,
- 0x0000110e, 0x80001161, 0x0000110f, 0x80001161,
- 0x00001110, 0x80001161, 0x00001111, 0x80001161,
- 0x00001112, 0x80001161, 0x0000110e, 0x00001161,
- 0x000011b7, 0x00001100, 0x80001169, 0x0000110c,
- 0x0000116e, 0x0000110b, 0x80001174, 0x0000110b,
- 0x8000116e, 0x80004e00, 0x80004e8c, 0x80004e09,
- 0x800056db, 0x80004e94, 0x8000516d, 0x80004e03,
- 0x8000516b, 0x80004e5d, 0x80005341, 0x80006708,
- 0x8000706b, 0x80006c34, 0x80006728, 0x800091d1,
- 0x8000571f, 0x800065e5, 0x8000682a, 0x80006709,
- 0x8000793e, 0x8000540d, 0x80007279, 0x80008ca1,
- 0x8000795d, 0x800052b4, 0x800079d8, 0x80007537,
- 0x80005973, 0x80009069, 0x8000512a, 0x80005370,
- 0x80006ce8, 0x80009805, 0x80004f11, 0x80005199,
- 0x80006b63, 0x80004e0a, 0x80004e2d, 0x80004e0b,
- 0x80005de6, 0x800053f3, 0x8000533b, 0x80005b97,
- 0x80005b66, 0x800076e3, 0x80004f01, 0x80008cc7,
- 0x80005354, 0x8000591c, 0x00000033, 0x80000036,
- 0x00000033, 0x80000037, 0x00000033, 0x80000038,
- 0x00000033, 0x80000039, 0x00000034, 0x80000030,
- 0x00000034, 0x80000031, 0x00000034, 0x80000032,
- 0x00000034, 0x80000033, 0x00000034, 0x80000034,
- 0x00000034, 0x80000035, 0x00000034, 0x80000036,
- 0x00000034, 0x80000037, 0x00000034, 0x80000038,
- 0x00000034, 0x80000039, 0x00000035, 0x80000030,
- 0x00000031, 0x80006708, 0x00000032, 0x80006708,
- 0x00000033, 0x80006708, 0x00000034, 0x80006708,
- 0x00000035, 0x80006708, 0x00000036, 0x80006708,
- 0x00000037, 0x80006708, 0x00000038, 0x80006708,
- 0x00000039, 0x80006708, 0x00000031, 0x00000030,
- 0x80006708, 0x00000031, 0x00000031, 0x80006708,
- 0x00000031, 0x00000032, 0x80006708, 0x00000048,
- 0x80000067, 0x00000065, 0x00000072, 0x80000067,
- 0x00000065, 0x80000056, 0x0000004c, 0x00000054,
- 0x80000044, 0x800030a2, 0x800030a4, 0x800030a6,
- 0x800030a8, 0x800030aa, 0x800030ab, 0x800030ad,
- 0x800030af, 0x800030b1, 0x800030b3, 0x800030b5,
- 0x800030b7, 0x800030b9, 0x800030bb, 0x800030bd,
- 0x800030bf, 0x800030c1, 0x800030c4, 0x800030c6,
- 0x800030c8, 0x800030ca, 0x800030cb, 0x800030cc,
- 0x800030cd, 0x800030ce, 0x800030cf, 0x800030d2,
- 0x800030d5, 0x800030d8, 0x800030db, 0x800030de,
- 0x800030df, 0x800030e0, 0x800030e1, 0x800030e2,
- 0x800030e4, 0x800030e6, 0x800030e8, 0x800030e9,
- 0x800030ea, 0x800030eb, 0x800030ec, 0x800030ed,
- 0x800030ef, 0x800030f0, 0x800030f1, 0x800030f2,
- 0x000030a2, 0x000030d1, 0x000030fc, 0x800030c8,
- 0x000030a2, 0x000030eb, 0x000030d5, 0x800030a1,
- 0x000030a2, 0x000030f3, 0x000030da, 0x800030a2,
- 0x000030a2, 0x000030fc, 0x800030eb, 0x000030a4,
- 0x000030cb, 0x000030f3, 0x800030b0, 0x000030a4,
- 0x000030f3, 0x800030c1, 0x000030a6, 0x000030a9,
- 0x800030f3, 0x000030a8, 0x000030b9, 0x000030af,
- 0x000030fc, 0x800030c9, 0x000030a8, 0x000030fc,
- 0x000030ab, 0x800030fc, 0x000030aa, 0x000030f3,
- 0x800030b9, 0x000030aa, 0x000030fc, 0x800030e0,
- 0x000030ab, 0x000030a4, 0x800030ea, 0x000030ab,
- 0x000030e9, 0x000030c3, 0x800030c8, 0x000030ab,
- 0x000030ed, 0x000030ea, 0x800030fc, 0x000030ac,
- 0x000030ed, 0x800030f3, 0x000030ac, 0x000030f3,
- 0x800030de, 0x000030ae, 0x800030ac, 0x000030ae,
- 0x000030cb, 0x800030fc, 0x000030ad, 0x000030e5,
- 0x000030ea, 0x800030fc, 0x000030ae, 0x000030eb,
- 0x000030c0, 0x800030fc, 0x000030ad, 0x800030ed,
- 0x000030ad, 0x000030ed, 0x000030b0, 0x000030e9,
- 0x800030e0, 0x000030ad, 0x000030ed, 0x000030e1,
- 0x000030fc, 0x000030c8, 0x800030eb, 0x000030ad,
- 0x000030ed, 0x000030ef, 0x000030c3, 0x800030c8,
- 0x000030b0, 0x000030e9, 0x800030e0, 0x000030b0,
- 0x000030e9, 0x000030e0, 0x000030c8, 0x800030f3,
- 0x000030af, 0x000030eb, 0x000030bc, 0x000030a4,
- 0x800030ed, 0x000030af, 0x000030ed, 0x000030fc,
- 0x800030cd, 0x000030b1, 0x000030fc, 0x800030b9,
- 0x000030b3, 0x000030eb, 0x800030ca, 0x000030b3,
- 0x000030fc, 0x800030dd, 0x000030b5, 0x000030a4,
- 0x000030af, 0x800030eb, 0x000030b5, 0x000030f3,
- 0x000030c1, 0x000030fc, 0x800030e0, 0x000030b7,
- 0x000030ea, 0x000030f3, 0x800030b0, 0x000030bb,
- 0x000030f3, 0x800030c1, 0x000030bb, 0x000030f3,
- 0x800030c8, 0x000030c0, 0x000030fc, 0x800030b9,
- 0x000030c7, 0x800030b7, 0x000030c9, 0x800030eb,
- 0x000030c8, 0x800030f3, 0x000030ca, 0x800030ce,
- 0x000030ce, 0x000030c3, 0x800030c8, 0x000030cf,
- 0x000030a4, 0x800030c4, 0x000030d1, 0x000030fc,
- 0x000030bb, 0x000030f3, 0x800030c8, 0x000030d1,
- 0x000030fc, 0x800030c4, 0x000030d0, 0x000030fc,
- 0x000030ec, 0x800030eb, 0x000030d4, 0x000030a2,
- 0x000030b9, 0x000030c8, 0x800030eb, 0x000030d4,
- 0x000030af, 0x800030eb, 0x000030d4, 0x800030b3,
- 0x000030d3, 0x800030eb, 0x000030d5, 0x000030a1,
- 0x000030e9, 0x000030c3, 0x800030c9, 0x000030d5,
- 0x000030a3, 0x000030fc, 0x800030c8, 0x000030d6,
- 0x000030c3, 0x000030b7, 0x000030a7, 0x800030eb,
- 0x000030d5, 0x000030e9, 0x800030f3, 0x000030d8,
- 0x000030af, 0x000030bf, 0x000030fc, 0x800030eb,
- 0x000030da, 0x800030bd, 0x000030da, 0x000030cb,
- 0x800030d2, 0x000030d8, 0x000030eb, 0x800030c4,
- 0x000030da, 0x000030f3, 0x800030b9, 0x000030da,
- 0x000030fc, 0x800030b8, 0x000030d9, 0x000030fc,
- 0x800030bf, 0x000030dd, 0x000030a4, 0x000030f3,
- 0x800030c8, 0x000030dc, 0x000030eb, 0x800030c8,
- 0x000030db, 0x800030f3, 0x000030dd, 0x000030f3,
- 0x800030c9, 0x000030db, 0x000030fc, 0x800030eb,
- 0x000030db, 0x000030fc, 0x800030f3, 0x000030de,
- 0x000030a4, 0x000030af, 0x800030ed, 0x000030de,
- 0x000030a4, 0x800030eb, 0x000030de, 0x000030c3,
- 0x800030cf, 0x000030de, 0x000030eb, 0x800030af,
- 0x000030de, 0x000030f3, 0x000030b7, 0x000030e7,
- 0x800030f3, 0x000030df, 0x000030af, 0x000030ed,
- 0x800030f3, 0x000030df, 0x800030ea, 0x000030df,
- 0x000030ea, 0x000030d0, 0x000030fc, 0x800030eb,
- 0x000030e1, 0x800030ac, 0x000030e1, 0x000030ac,
- 0x000030c8, 0x800030f3, 0x000030e1, 0x000030fc,
- 0x000030c8, 0x800030eb, 0x000030e4, 0x000030fc,
- 0x800030c9, 0x000030e4, 0x000030fc, 0x800030eb,
- 0x000030e6, 0x000030a2, 0x800030f3, 0x000030ea,
- 0x000030c3, 0x000030c8, 0x800030eb, 0x000030ea,
- 0x800030e9, 0x000030eb, 0x000030d4, 0x800030fc,
- 0x000030eb, 0x000030fc, 0x000030d6, 0x800030eb,
- 0x000030ec, 0x800030e0, 0x000030ec, 0x000030f3,
- 0x000030c8, 0x000030b2, 0x800030f3, 0x000030ef,
- 0x000030c3, 0x800030c8, 0x00000030, 0x800070b9,
- 0x00000031, 0x800070b9, 0x00000032, 0x800070b9,
- 0x00000033, 0x800070b9, 0x00000034, 0x800070b9,
- 0x00000035, 0x800070b9, 0x00000036, 0x800070b9,
- 0x00000037, 0x800070b9, 0x00000038, 0x800070b9,
- 0x00000039, 0x800070b9, 0x00000031, 0x00000030,
- 0x800070b9, 0x00000031, 0x00000031, 0x800070b9,
- 0x00000031, 0x00000032, 0x800070b9, 0x00000031,
- 0x00000033, 0x800070b9, 0x00000031, 0x00000034,
- 0x800070b9, 0x00000031, 0x00000035, 0x800070b9,
- 0x00000031, 0x00000036, 0x800070b9, 0x00000031,
- 0x00000037, 0x800070b9, 0x00000031, 0x00000038,
- 0x800070b9, 0x00000031, 0x00000039, 0x800070b9,
- 0x00000032, 0x00000030, 0x800070b9, 0x00000032,
- 0x00000031, 0x800070b9, 0x00000032, 0x00000032,
- 0x800070b9, 0x00000032, 0x00000033, 0x800070b9,
- 0x00000032, 0x00000034, 0x800070b9, 0x00000068,
- 0x00000050, 0x80000061, 0x00000064, 0x80000061,
- 0x00000041, 0x80000055, 0x00000062, 0x00000061,
- 0x80000072, 0x0000006f, 0x80000056, 0x00000070,
- 0x80000063, 0x00000064, 0x8000006d, 0x00000064,
- 0x0000006d, 0x800000b2, 0x00000064, 0x0000006d,
- 0x800000b3, 0x00000049, 0x80000055, 0x00005e73,
- 0x80006210, 0x0000662d, 0x8000548c, 0x00005927,
- 0x80006b63, 0x0000660e, 0x80006cbb, 0x0000682a,
- 0x00005f0f, 0x00004f1a, 0x8000793e, 0x00000070,
- 0x80000041, 0x0000006e, 0x80000041, 0x000003bc,
- 0x80000041, 0x0000006d, 0x80000041, 0x0000006b,
- 0x80000041, 0x0000004b, 0x80000042, 0x0000004d,
- 0x80000042, 0x00000047, 0x80000042, 0x00000063,
- 0x00000061, 0x8000006c, 0x0000006b, 0x00000063,
- 0x00000061, 0x8000006c, 0x00000070, 0x80000046,
- 0x0000006e, 0x80000046, 0x000003bc, 0x80000046,
- 0x000003bc, 0x80000067, 0x0000006d, 0x80000067,
- 0x0000006b, 0x80000067, 0x00000048, 0x8000007a,
- 0x0000006b, 0x00000048, 0x8000007a, 0x0000004d,
- 0x00000048, 0x8000007a, 0x00000047, 0x00000048,
- 0x8000007a, 0x00000054, 0x00000048, 0x8000007a,
- 0x000003bc, 0x80002113, 0x0000006d, 0x80002113,
- 0x00000064, 0x80002113, 0x0000006b, 0x80002113,
- 0x00000066, 0x8000006d, 0x0000006e, 0x8000006d,
- 0x000003bc, 0x8000006d, 0x0000006d, 0x8000006d,
- 0x00000063, 0x8000006d, 0x0000006b, 0x8000006d,
- 0x0000006d, 0x0000006d, 0x800000b2, 0x00000063,
- 0x0000006d, 0x800000b2, 0x0000006d, 0x800000b2,
- 0x0000006b, 0x0000006d, 0x800000b2, 0x0000006d,
- 0x0000006d, 0x800000b3, 0x00000063, 0x0000006d,
- 0x800000b3, 0x0000006d, 0x800000b3, 0x0000006b,
- 0x0000006d, 0x800000b3, 0x0000006d, 0x00002215,
- 0x80000073, 0x0000006d, 0x00002215, 0x00000073,
- 0x800000b2, 0x00000050, 0x80000061, 0x0000006b,
- 0x00000050, 0x80000061, 0x0000004d, 0x00000050,
- 0x80000061, 0x00000047, 0x00000050, 0x80000061,
- 0x00000072, 0x00000061, 0x80000064, 0x00000072,
- 0x00000061, 0x00000064, 0x00002215, 0x80000073,
- 0x00000072, 0x00000061, 0x00000064, 0x00002215,
- 0x00000073, 0x800000b2, 0x00000070, 0x80000073,
- 0x0000006e, 0x80000073, 0x000003bc, 0x80000073,
- 0x0000006d, 0x80000073, 0x00000070, 0x80000056,
- 0x0000006e, 0x80000056, 0x000003bc, 0x80000056,
- 0x0000006d, 0x80000056, 0x0000006b, 0x80000056,
- 0x0000004d, 0x80000056, 0x00000070, 0x80000057,
- 0x0000006e, 0x80000057, 0x000003bc, 0x80000057,
- 0x0000006d, 0x80000057, 0x0000006b, 0x80000057,
- 0x0000004d, 0x80000057, 0x0000006b, 0x800003a9,
- 0x0000004d, 0x800003a9, 0x00000061, 0x0000002e,
- 0x0000006d, 0x8000002e, 0x00000042, 0x80000071,
- 0x00000063, 0x80000063, 0x00000063, 0x80000064,
- 0x00000043, 0x00002215, 0x0000006b, 0x80000067,
- 0x00000043, 0x0000006f, 0x8000002e, 0x00000064,
- 0x80000042, 0x00000047, 0x80000079, 0x00000068,
- 0x80000061, 0x00000048, 0x80000050, 0x00000069,
- 0x8000006e, 0x0000004b, 0x8000004b, 0x0000004b,
- 0x8000004d, 0x0000006b, 0x80000074, 0x0000006c,
- 0x8000006d, 0x0000006c, 0x8000006e, 0x0000006c,
- 0x0000006f, 0x80000067, 0x0000006c, 0x80000078,
- 0x0000006d, 0x80000062, 0x0000006d, 0x00000069,
- 0x8000006c, 0x0000006d, 0x0000006f, 0x8000006c,
- 0x00000050, 0x80000048, 0x00000070, 0x0000002e,
- 0x0000006d, 0x8000002e, 0x00000050, 0x00000050,
- 0x8000004d, 0x00000050, 0x80000052, 0x00000073,
- 0x80000072, 0x00000053, 0x80000076, 0x00000057,
- 0x80000062, 0x00000056, 0x00002215, 0x8000006d,
- 0x00000041, 0x00002215, 0x8000006d, 0x00000031,
- 0x800065e5, 0x00000032, 0x800065e5, 0x00000033,
- 0x800065e5, 0x00000034, 0x800065e5, 0x00000035,
- 0x800065e5, 0x00000036, 0x800065e5, 0x00000037,
- 0x800065e5, 0x00000038, 0x800065e5, 0x00000039,
- 0x800065e5, 0x00000031, 0x00000030, 0x800065e5,
- 0x00000031, 0x00000031, 0x800065e5, 0x00000031,
- 0x00000032, 0x800065e5, 0x00000031, 0x00000033,
- 0x800065e5, 0x00000031, 0x00000034, 0x800065e5,
- 0x00000031, 0x00000035, 0x800065e5, 0x00000031,
- 0x00000036, 0x800065e5, 0x00000031, 0x00000037,
- 0x800065e5, 0x00000031, 0x00000038, 0x800065e5,
- 0x00000031, 0x00000039, 0x800065e5, 0x00000032,
- 0x00000030, 0x800065e5, 0x00000032, 0x00000031,
- 0x800065e5, 0x00000032, 0x00000032, 0x800065e5,
- 0x00000032, 0x00000033, 0x800065e5, 0x00000032,
- 0x00000034, 0x800065e5, 0x00000032, 0x00000035,
- 0x800065e5, 0x00000032, 0x00000036, 0x800065e5,
- 0x00000032, 0x00000037, 0x800065e5, 0x00000032,
- 0x00000038, 0x800065e5, 0x00000032, 0x00000039,
- 0x800065e5, 0x00000033, 0x00000030, 0x800065e5,
- 0x00000033, 0x00000031, 0x800065e5, 0x00000067,
- 0x00000061, 0x8000006c, 0x80008c48, 0x800066f4,
- 0x80008eca, 0x80008cc8, 0x80006ed1, 0x80004e32,
- 0x800053e5, 0x80009f9c, 0x80009f9c, 0x80005951,
- 0x800091d1, 0x80005587, 0x80005948, 0x800061f6,
- 0x80007669, 0x80007f85, 0x8000863f, 0x800087ba,
- 0x800088f8, 0x8000908f, 0x80006a02, 0x80006d1b,
- 0x800070d9, 0x800073de, 0x8000843d, 0x8000916a,
- 0x800099f1, 0x80004e82, 0x80005375, 0x80006b04,
- 0x8000721b, 0x8000862d, 0x80009e1e, 0x80005d50,
- 0x80006feb, 0x800085cd, 0x80008964, 0x800062c9,
- 0x800081d8, 0x8000881f, 0x80005eca, 0x80006717,
- 0x80006d6a, 0x800072fc, 0x800090ce, 0x80004f86,
- 0x800051b7, 0x800052de, 0x800064c4, 0x80006ad3,
- 0x80007210, 0x800076e7, 0x80008001, 0x80008606,
- 0x8000865c, 0x80008def, 0x80009732, 0x80009b6f,
- 0x80009dfa, 0x8000788c, 0x8000797f, 0x80007da0,
- 0x800083c9, 0x80009304, 0x80009e7f, 0x80008ad6,
- 0x800058df, 0x80005f04, 0x80007c60, 0x8000807e,
- 0x80007262, 0x800078ca, 0x80008cc2, 0x800096f7,
- 0x800058d8, 0x80005c62, 0x80006a13, 0x80006dda,
- 0x80006f0f, 0x80007d2f, 0x80007e37, 0x8000964b,
- 0x800052d2, 0x8000808b, 0x800051dc, 0x800051cc,
- 0x80007a1c, 0x80007dbe, 0x800083f1, 0x80009675,
- 0x80008b80, 0x800062cf, 0x80006a02, 0x80008afe,
- 0x80004e39, 0x80005be7, 0x80006012, 0x80007387,
- 0x80007570, 0x80005317, 0x800078fb, 0x80004fbf,
- 0x80005fa9, 0x80004e0d, 0x80006ccc, 0x80006578,
- 0x80007d22, 0x800053c3, 0x8000585e, 0x80007701,
- 0x80008449, 0x80008aaa, 0x80006bba, 0x80008fb0,
- 0x80006c88, 0x800062fe, 0x800082e5, 0x800063a0,
- 0x80007565, 0x80004eae, 0x80005169, 0x800051c9,
- 0x80006881, 0x80007ce7, 0x8000826f, 0x80008ad2,
- 0x800091cf, 0x800052f5, 0x80005442, 0x80005973,
- 0x80005eec, 0x800065c5, 0x80006ffe, 0x8000792a,
- 0x800095ad, 0x80009a6a, 0x80009e97, 0x80009ece,
- 0x8000529b, 0x800066c6, 0x80006b77, 0x80008f62,
- 0x80005e74, 0x80006190, 0x80006200, 0x8000649a,
- 0x80006f23, 0x80007149, 0x80007489, 0x800079ca,
- 0x80007df4, 0x8000806f, 0x80008f26, 0x800084ee,
- 0x80009023, 0x8000934a, 0x80005217, 0x800052a3,
- 0x800054bd, 0x800070c8, 0x800088c2, 0x80008aaa,
- 0x80005ec9, 0x80005ff5, 0x8000637b, 0x80006bae,
- 0x80007c3e, 0x80007375, 0x80004ee4, 0x800056f9,
- 0x80005be7, 0x80005dba, 0x8000601c, 0x800073b2,
- 0x80007469, 0x80007f9a, 0x80008046, 0x80009234,
- 0x800096f6, 0x80009748, 0x80009818, 0x80004f8b,
- 0x800079ae, 0x800091b4, 0x800096b8, 0x800060e1,
- 0x80004e86, 0x800050da, 0x80005bee, 0x80005c3f,
- 0x80006599, 0x80006a02, 0x800071ce, 0x80007642,
- 0x800084fc, 0x8000907c, 0x80009f8d, 0x80006688,
- 0x8000962e, 0x80005289, 0x8000677b, 0x800067f3,
- 0x80006d41, 0x80006e9c, 0x80007409, 0x80007559,
- 0x8000786b, 0x80007d10, 0x8000985e, 0x8000516d,
- 0x8000622e, 0x80009678, 0x8000502b, 0x80005d19,
- 0x80006dea, 0x80008f2a, 0x80005f8b, 0x80006144,
- 0x80006817, 0x80007387, 0x80009686, 0x80005229,
- 0x8000540f, 0x80005c65, 0x80006613, 0x8000674e,
- 0x800068a8, 0x80006ce5, 0x80007406, 0x800075e2,
- 0x80007f79, 0x800088cf, 0x800088e1, 0x800091cc,
- 0x800096e2, 0x8000533f, 0x80006eba, 0x8000541d,
- 0x800071d0, 0x80007498, 0x800085fa, 0x800096a3,
- 0x80009c57, 0x80009e9f, 0x80006797, 0x80006dcb,
- 0x800081e8, 0x80007acb, 0x80007b20, 0x80007c92,
- 0x800072c0, 0x80007099, 0x80008b58, 0x80004ec0,
- 0x80008336, 0x8000523a, 0x80005207, 0x80005ea6,
- 0x800062d3, 0x80007cd6, 0x80005b85, 0x80006d1e,
- 0x800066b4, 0x80008f3b, 0x8000884c, 0x8000964d,
- 0x8000898b, 0x80005ed3, 0x80005140, 0x800055c0,
- 0x8000585a, 0x80006674, 0x800051de, 0x8000732a,
- 0x800076ca, 0x8000793c, 0x8000795e, 0x80007965,
- 0x8000798f, 0x80009756, 0x80007cbe, 0x80007fbd,
- 0x80008612, 0x80008af8, 0x80009038, 0x800090fd,
- 0x800098ef, 0x800098fc, 0x80009928, 0x80009db4,
- 0x80004fae, 0x800050e7, 0x8000514d, 0x800052c9,
- 0x800052e4, 0x80005351, 0x8000559d, 0x80005606,
- 0x80005668, 0x80005840, 0x800058a8, 0x80005c64,
- 0x80005c6e, 0x80006094, 0x80006168, 0x8000618e,
- 0x800061f2, 0x8000654f, 0x800065e2, 0x80006691,
- 0x80006885, 0x80006d77, 0x80006e1a, 0x80006f22,
- 0x8000716e, 0x8000722b, 0x80007422, 0x80007891,
- 0x8000793e, 0x80007949, 0x80007948, 0x80007950,
- 0x80007956, 0x8000795d, 0x8000798d, 0x8000798e,
- 0x80007a40, 0x80007a81, 0x80007bc0, 0x80007df4,
- 0x80007e09, 0x80007e41, 0x80007f72, 0x80008005,
- 0x800081ed, 0x80008279, 0x80008279, 0x80008457,
- 0x80008910, 0x80008996, 0x80008b01, 0x80008b39,
- 0x80008cd3, 0x80008d08, 0x80008fb6, 0x80009038,
- 0x800096e3, 0x800097ff, 0x8000983b, 0x80004e26,
- 0x800051b5, 0x80005168, 0x80004f80, 0x80005145,
- 0x80005180, 0x800052c7, 0x800052fa, 0x8000559d,
- 0x80005555, 0x80005599, 0x800055e2, 0x8000585a,
- 0x800058b3, 0x80005944, 0x80005954, 0x80005a62,
- 0x80005b28, 0x80005ed2, 0x80005ed9, 0x80005f69,
- 0x80005fad, 0x800060d8, 0x8000614e, 0x80006108,
- 0x8000618e, 0x80006160, 0x800061f2, 0x80006234,
- 0x800063c4, 0x8000641c, 0x80006452, 0x80006556,
- 0x80006674, 0x80006717, 0x8000671b, 0x80006756,
- 0x80006b79, 0x80006bba, 0x80006d41, 0x80006edb,
- 0x80006ecb, 0x80006f22, 0x8000701e, 0x8000716e,
- 0x800077a7, 0x80007235, 0x800072af, 0x8000732a,
- 0x80007471, 0x80007506, 0x8000753b, 0x8000761d,
- 0x8000761f, 0x800076ca, 0x800076db, 0x800076f4,
- 0x8000774a, 0x80007740, 0x800078cc, 0x80007ab1,
- 0x80007bc0, 0x80007c7b, 0x80007d5b, 0x80007df4,
- 0x80007f3e, 0x80008005, 0x80008352, 0x800083ef,
- 0x80008779, 0x80008941, 0x80008986, 0x80008996,
- 0x80008abf, 0x80008af8, 0x80008acb, 0x80008b01,
- 0x80008afe, 0x80008aed, 0x80008b39, 0x80008b8a,
- 0x80008d08, 0x80008f38, 0x80009072, 0x80009199,
- 0x80009276, 0x8000967c, 0x800096e3, 0x80009756,
- 0x800097db, 0x800097ff, 0x8000980b, 0x8000983b,
- 0x80009b12, 0x80009f9c, 0x8002284a, 0x80022844,
- 0x800233d5, 0x80003b9d, 0x80004018, 0x80004039,
- 0x80025249, 0x80025cd0, 0x80027ed3, 0x80009f43,
- 0x80009f8e, 0x00000066, 0x80000066, 0x00000066,
- 0x80000069, 0x00000066, 0x8000006c, 0x00000066,
- 0x00000066, 0x80000069, 0x00000066, 0x00000066,
- 0x8000006c, 0x0000017f, 0x80000074, 0x00000073,
- 0x80000074, 0x00000574, 0x80000576, 0x00000574,
- 0x80000565, 0x00000574, 0x8000056b, 0x0000057e,
- 0x80000576, 0x00000574, 0x8000056d, 0x000005d9,
- 0x800005b4, 0x000005f2, 0x800005b7, 0x800005e2,
- 0x800005d0, 0x800005d3, 0x800005d4, 0x800005db,
- 0x800005dc, 0x800005dd, 0x800005e8, 0x800005ea,
- 0x8000002b, 0x000005e9, 0x800005c1, 0x000005e9,
- 0x800005c2, 0x0000fb49, 0x800005c1, 0x0000fb49,
- 0x800005c2, 0x000005d0, 0x800005b7, 0x000005d0,
- 0x800005b8, 0x000005d0, 0x800005bc, 0x000005d1,
- 0x800005bc, 0x000005d2, 0x800005bc, 0x000005d3,
- 0x800005bc, 0x000005d4, 0x800005bc, 0x000005d5,
- 0x800005bc, 0x000005d6, 0x800005bc, 0x000005d8,
- 0x800005bc, 0x000005d9, 0x800005bc, 0x000005da,
- 0x800005bc, 0x000005db, 0x800005bc, 0x000005dc,
- 0x800005bc, 0x000005de, 0x800005bc, 0x000005e0,
- 0x800005bc, 0x000005e1, 0x800005bc, 0x000005e3,
- 0x800005bc, 0x000005e4, 0x800005bc, 0x000005e6,
- 0x800005bc, 0x000005e7, 0x800005bc, 0x000005e8,
- 0x800005bc, 0x000005e9, 0x800005bc, 0x000005ea,
- 0x800005bc, 0x000005d5, 0x800005b9, 0x000005d1,
- 0x800005bf, 0x000005db, 0x800005bf, 0x000005e4,
- 0x800005bf, 0x000005d0, 0x800005dc, 0x80000671,
- 0x80000671, 0x8000067b, 0x8000067b, 0x8000067b,
- 0x8000067b, 0x8000067e, 0x8000067e, 0x8000067e,
- 0x8000067e, 0x80000680, 0x80000680, 0x80000680,
- 0x80000680, 0x8000067a, 0x8000067a, 0x8000067a,
- 0x8000067a, 0x8000067f, 0x8000067f, 0x8000067f,
- 0x8000067f, 0x80000679, 0x80000679, 0x80000679,
- 0x80000679, 0x800006a4, 0x800006a4, 0x800006a4,
- 0x800006a4, 0x800006a6, 0x800006a6, 0x800006a6,
- 0x800006a6, 0x80000684, 0x80000684, 0x80000684,
- 0x80000684, 0x80000683, 0x80000683, 0x80000683,
- 0x80000683, 0x80000686, 0x80000686, 0x80000686,
- 0x80000686, 0x80000687, 0x80000687, 0x80000687,
- 0x80000687, 0x8000068d, 0x8000068d, 0x8000068c,
- 0x8000068c, 0x8000068e, 0x8000068e, 0x80000688,
- 0x80000688, 0x80000698, 0x80000698, 0x80000691,
- 0x80000691, 0x800006a9, 0x800006a9, 0x800006a9,
- 0x800006a9, 0x800006af, 0x800006af, 0x800006af,
- 0x800006af, 0x800006b3, 0x800006b3, 0x800006b3,
- 0x800006b3, 0x800006b1, 0x800006b1, 0x800006b1,
- 0x800006b1, 0x800006ba, 0x800006ba, 0x800006bb,
- 0x800006bb, 0x800006bb, 0x800006bb, 0x800006c0,
- 0x800006c0, 0x800006c1, 0x800006c1, 0x800006c1,
- 0x800006c1, 0x800006be, 0x800006be, 0x800006be,
- 0x800006be, 0x800006d2, 0x800006d2, 0x800006d3,
- 0x800006d3, 0x800006ad, 0x800006ad, 0x800006ad,
- 0x800006ad, 0x800006c7, 0x800006c7, 0x800006c6,
- 0x800006c6, 0x800006c8, 0x800006c8, 0x80000677,
- 0x800006cb, 0x800006cb, 0x800006c5, 0x800006c5,
- 0x800006c9, 0x800006c9, 0x800006d0, 0x800006d0,
- 0x800006d0, 0x800006d0, 0x80000649, 0x80000649,
- 0x00000626, 0x80000627, 0x00000626, 0x80000627,
- 0x00000626, 0x800006d5, 0x00000626, 0x800006d5,
- 0x00000626, 0x80000648, 0x00000626, 0x80000648,
- 0x00000626, 0x800006c7, 0x00000626, 0x800006c7,
- 0x00000626, 0x800006c6, 0x00000626, 0x800006c6,
- 0x00000626, 0x800006c8, 0x00000626, 0x800006c8,
- 0x00000626, 0x800006d0, 0x00000626, 0x800006d0,
- 0x00000626, 0x800006d0, 0x00000626, 0x80000649,
- 0x00000626, 0x80000649, 0x00000626, 0x80000649,
- 0x800006cc, 0x800006cc, 0x800006cc, 0x800006cc,
- 0x00000626, 0x8000062c, 0x00000626, 0x8000062d,
- 0x00000626, 0x80000645, 0x00000626, 0x80000649,
- 0x00000626, 0x8000064a, 0x00000628, 0x8000062c,
- 0x00000628, 0x8000062d, 0x00000628, 0x8000062e,
- 0x00000628, 0x80000645, 0x00000628, 0x80000649,
- 0x00000628, 0x8000064a, 0x0000062a, 0x8000062c,
- 0x0000062a, 0x8000062d, 0x0000062a, 0x8000062e,
- 0x0000062a, 0x80000645, 0x0000062a, 0x80000649,
- 0x0000062a, 0x8000064a, 0x0000062b, 0x8000062c,
- 0x0000062b, 0x80000645, 0x0000062b, 0x80000649,
- 0x0000062b, 0x8000064a, 0x0000062c, 0x8000062d,
- 0x0000062c, 0x80000645, 0x0000062d, 0x8000062c,
- 0x0000062d, 0x80000645, 0x0000062e, 0x8000062c,
- 0x0000062e, 0x8000062d, 0x0000062e, 0x80000645,
- 0x00000633, 0x8000062c, 0x00000633, 0x8000062d,
- 0x00000633, 0x8000062e, 0x00000633, 0x80000645,
- 0x00000635, 0x8000062d, 0x00000635, 0x80000645,
- 0x00000636, 0x8000062c, 0x00000636, 0x8000062d,
- 0x00000636, 0x8000062e, 0x00000636, 0x80000645,
- 0x00000637, 0x8000062d, 0x00000637, 0x80000645,
- 0x00000638, 0x80000645, 0x00000639, 0x8000062c,
- 0x00000639, 0x80000645, 0x0000063a, 0x8000062c,
- 0x0000063a, 0x80000645, 0x00000641, 0x8000062c,
- 0x00000641, 0x8000062d, 0x00000641, 0x8000062e,
- 0x00000641, 0x80000645, 0x00000641, 0x80000649,
- 0x00000641, 0x8000064a, 0x00000642, 0x8000062d,
- 0x00000642, 0x80000645, 0x00000642, 0x80000649,
- 0x00000642, 0x8000064a, 0x00000643, 0x80000627,
- 0x00000643, 0x8000062c, 0x00000643, 0x8000062d,
- 0x00000643, 0x8000062e, 0x00000643, 0x80000644,
- 0x00000643, 0x80000645, 0x00000643, 0x80000649,
- 0x00000643, 0x8000064a, 0x00000644, 0x8000062c,
- 0x00000644, 0x8000062d, 0x00000644, 0x8000062e,
- 0x00000644, 0x80000645, 0x00000644, 0x80000649,
- 0x00000644, 0x8000064a, 0x00000645, 0x8000062c,
- 0x00000645, 0x8000062d, 0x00000645, 0x8000062e,
- 0x00000645, 0x80000645, 0x00000645, 0x80000649,
- 0x00000645, 0x8000064a, 0x00000646, 0x8000062c,
- 0x00000646, 0x8000062d, 0x00000646, 0x8000062e,
- 0x00000646, 0x80000645, 0x00000646, 0x80000649,
- 0x00000646, 0x8000064a, 0x00000647, 0x8000062c,
- 0x00000647, 0x80000645, 0x00000647, 0x80000649,
- 0x00000647, 0x8000064a, 0x0000064a, 0x8000062c,
- 0x0000064a, 0x8000062d, 0x0000064a, 0x8000062e,
- 0x0000064a, 0x80000645, 0x0000064a, 0x80000649,
- 0x0000064a, 0x8000064a, 0x00000630, 0x80000670,
- 0x00000631, 0x80000670, 0x00000649, 0x80000670,
- 0x00000020, 0x0000064c, 0x80000651, 0x00000020,
- 0x0000064d, 0x80000651, 0x00000020, 0x0000064e,
- 0x80000651, 0x00000020, 0x0000064f, 0x80000651,
- 0x00000020, 0x00000650, 0x80000651, 0x00000020,
- 0x00000651, 0x80000670, 0x00000626, 0x80000631,
- 0x00000626, 0x80000632, 0x00000626, 0x80000645,
- 0x00000626, 0x80000646, 0x00000626, 0x80000649,
- 0x00000626, 0x8000064a, 0x00000628, 0x80000631,
- 0x00000628, 0x80000632, 0x00000628, 0x80000645,
- 0x00000628, 0x80000646, 0x00000628, 0x80000649,
- 0x00000628, 0x8000064a, 0x0000062a, 0x80000631,
- 0x0000062a, 0x80000632, 0x0000062a, 0x80000645,
- 0x0000062a, 0x80000646, 0x0000062a, 0x80000649,
- 0x0000062a, 0x8000064a, 0x0000062b, 0x80000631,
- 0x0000062b, 0x80000632, 0x0000062b, 0x80000645,
- 0x0000062b, 0x80000646, 0x0000062b, 0x80000649,
- 0x0000062b, 0x8000064a, 0x00000641, 0x80000649,
- 0x00000641, 0x8000064a, 0x00000642, 0x80000649,
- 0x00000642, 0x8000064a, 0x00000643, 0x80000627,
- 0x00000643, 0x80000644, 0x00000643, 0x80000645,
- 0x00000643, 0x80000649, 0x00000643, 0x8000064a,
- 0x00000644, 0x80000645, 0x00000644, 0x80000649,
- 0x00000644, 0x8000064a, 0x00000645, 0x80000627,
- 0x00000645, 0x80000645, 0x00000646, 0x80000631,
- 0x00000646, 0x80000632, 0x00000646, 0x80000645,
- 0x00000646, 0x80000646, 0x00000646, 0x80000649,
- 0x00000646, 0x8000064a, 0x00000649, 0x80000670,
- 0x0000064a, 0x80000631, 0x0000064a, 0x80000632,
- 0x0000064a, 0x80000645, 0x0000064a, 0x80000646,
- 0x0000064a, 0x80000649, 0x0000064a, 0x8000064a,
- 0x00000626, 0x8000062c, 0x00000626, 0x8000062d,
- 0x00000626, 0x8000062e, 0x00000626, 0x80000645,
- 0x00000626, 0x80000647, 0x00000628, 0x8000062c,
- 0x00000628, 0x8000062d, 0x00000628, 0x8000062e,
- 0x00000628, 0x80000645, 0x00000628, 0x80000647,
- 0x0000062a, 0x8000062c, 0x0000062a, 0x8000062d,
- 0x0000062a, 0x8000062e, 0x0000062a, 0x80000645,
- 0x0000062a, 0x80000647, 0x0000062b, 0x80000645,
- 0x0000062c, 0x8000062d, 0x0000062c, 0x80000645,
- 0x0000062d, 0x8000062c, 0x0000062d, 0x80000645,
- 0x0000062e, 0x8000062c, 0x0000062e, 0x80000645,
- 0x00000633, 0x8000062c, 0x00000633, 0x8000062d,
- 0x00000633, 0x8000062e, 0x00000633, 0x80000645,
- 0x00000635, 0x8000062d, 0x00000635, 0x8000062e,
- 0x00000635, 0x80000645, 0x00000636, 0x8000062c,
- 0x00000636, 0x8000062d, 0x00000636, 0x8000062e,
- 0x00000636, 0x80000645, 0x00000637, 0x8000062d,
- 0x00000638, 0x80000645, 0x00000639, 0x8000062c,
- 0x00000639, 0x80000645, 0x0000063a, 0x8000062c,
- 0x0000063a, 0x80000645, 0x00000641, 0x8000062c,
- 0x00000641, 0x8000062d, 0x00000641, 0x8000062e,
- 0x00000641, 0x80000645, 0x00000642, 0x8000062d,
- 0x00000642, 0x80000645, 0x00000643, 0x8000062c,
- 0x00000643, 0x8000062d, 0x00000643, 0x8000062e,
- 0x00000643, 0x80000644, 0x00000643, 0x80000645,
- 0x00000644, 0x8000062c, 0x00000644, 0x8000062d,
- 0x00000644, 0x8000062e, 0x00000644, 0x80000645,
- 0x00000644, 0x80000647, 0x00000645, 0x8000062c,
- 0x00000645, 0x8000062d, 0x00000645, 0x8000062e,
- 0x00000645, 0x80000645, 0x00000646, 0x8000062c,
- 0x00000646, 0x8000062d, 0x00000646, 0x8000062e,
- 0x00000646, 0x80000645, 0x00000646, 0x80000647,
- 0x00000647, 0x8000062c, 0x00000647, 0x80000645,
- 0x00000647, 0x80000670, 0x0000064a, 0x8000062c,
- 0x0000064a, 0x8000062d, 0x0000064a, 0x8000062e,
- 0x0000064a, 0x80000645, 0x0000064a, 0x80000647,
- 0x00000626, 0x80000645, 0x00000626, 0x80000647,
- 0x00000628, 0x80000645, 0x00000628, 0x80000647,
- 0x0000062a, 0x80000645, 0x0000062a, 0x80000647,
- 0x0000062b, 0x80000645, 0x0000062b, 0x80000647,
- 0x00000633, 0x80000645, 0x00000633, 0x80000647,
- 0x00000634, 0x80000645, 0x00000634, 0x80000647,
- 0x00000643, 0x80000644, 0x00000643, 0x80000645,
- 0x00000644, 0x80000645, 0x00000646, 0x80000645,
- 0x00000646, 0x80000647, 0x0000064a, 0x80000645,
- 0x0000064a, 0x80000647, 0x00000640, 0x0000064e,
- 0x80000651, 0x00000640, 0x0000064f, 0x80000651,
- 0x00000640, 0x00000650, 0x80000651, 0x00000637,
- 0x80000649, 0x00000637, 0x8000064a, 0x00000639,
- 0x80000649, 0x00000639, 0x8000064a, 0x0000063a,
- 0x80000649, 0x0000063a, 0x8000064a, 0x00000633,
- 0x80000649, 0x00000633, 0x8000064a, 0x00000634,
- 0x80000649, 0x00000634, 0x8000064a, 0x0000062d,
- 0x80000649, 0x0000062d, 0x8000064a, 0x0000062c,
- 0x80000649, 0x0000062c, 0x8000064a, 0x0000062e,
- 0x80000649, 0x0000062e, 0x8000064a, 0x00000635,
- 0x80000649, 0x00000635, 0x8000064a, 0x00000636,
- 0x80000649, 0x00000636, 0x8000064a, 0x00000634,
- 0x8000062c, 0x00000634, 0x8000062d, 0x00000634,
- 0x8000062e, 0x00000634, 0x80000645, 0x00000634,
- 0x80000631, 0x00000633, 0x80000631, 0x00000635,
- 0x80000631, 0x00000636, 0x80000631, 0x00000637,
- 0x80000649, 0x00000637, 0x8000064a, 0x00000639,
- 0x80000649, 0x00000639, 0x8000064a, 0x0000063a,
- 0x80000649, 0x0000063a, 0x8000064a, 0x00000633,
- 0x80000649, 0x00000633, 0x8000064a, 0x00000634,
- 0x80000649, 0x00000634, 0x8000064a, 0x0000062d,
- 0x80000649, 0x0000062d, 0x8000064a, 0x0000062c,
- 0x80000649, 0x0000062c, 0x8000064a, 0x0000062e,
- 0x80000649, 0x0000062e, 0x8000064a, 0x00000635,
- 0x80000649, 0x00000635, 0x8000064a, 0x00000636,
- 0x80000649, 0x00000636, 0x8000064a, 0x00000634,
- 0x8000062c, 0x00000634, 0x8000062d, 0x00000634,
- 0x8000062e, 0x00000634, 0x80000645, 0x00000634,
- 0x80000631, 0x00000633, 0x80000631, 0x00000635,
- 0x80000631, 0x00000636, 0x80000631, 0x00000634,
- 0x8000062c, 0x00000634, 0x8000062d, 0x00000634,
- 0x8000062e, 0x00000634, 0x80000645, 0x00000633,
- 0x80000647, 0x00000634, 0x80000647, 0x00000637,
- 0x80000645, 0x00000633, 0x8000062c, 0x00000633,
- 0x8000062d, 0x00000633, 0x8000062e, 0x00000634,
- 0x8000062c, 0x00000634, 0x8000062d, 0x00000634,
- 0x8000062e, 0x00000637, 0x80000645, 0x00000638,
- 0x80000645, 0x00000627, 0x8000064b, 0x00000627,
- 0x8000064b, 0x0000062a, 0x0000062c, 0x80000645,
- 0x0000062a, 0x0000062d, 0x8000062c, 0x0000062a,
- 0x0000062d, 0x8000062c, 0x0000062a, 0x0000062d,
- 0x80000645, 0x0000062a, 0x0000062e, 0x80000645,
- 0x0000062a, 0x00000645, 0x8000062c, 0x0000062a,
- 0x00000645, 0x8000062d, 0x0000062a, 0x00000645,
- 0x8000062e, 0x0000062c, 0x00000645, 0x8000062d,
- 0x0000062c, 0x00000645, 0x8000062d, 0x0000062d,
- 0x00000645, 0x8000064a, 0x0000062d, 0x00000645,
- 0x80000649, 0x00000633, 0x0000062d, 0x8000062c,
- 0x00000633, 0x0000062c, 0x8000062d, 0x00000633,
- 0x0000062c, 0x80000649, 0x00000633, 0x00000645,
- 0x8000062d, 0x00000633, 0x00000645, 0x8000062d,
- 0x00000633, 0x00000645, 0x8000062c, 0x00000633,
- 0x00000645, 0x80000645, 0x00000633, 0x00000645,
- 0x80000645, 0x00000635, 0x0000062d, 0x8000062d,
- 0x00000635, 0x0000062d, 0x8000062d, 0x00000635,
- 0x00000645, 0x80000645, 0x00000634, 0x0000062d,
- 0x80000645, 0x00000634, 0x0000062d, 0x80000645,
- 0x00000634, 0x0000062c, 0x8000064a, 0x00000634,
- 0x00000645, 0x8000062e, 0x00000634, 0x00000645,
- 0x8000062e, 0x00000634, 0x00000645, 0x80000645,
- 0x00000634, 0x00000645, 0x80000645, 0x00000636,
- 0x0000062d, 0x80000649, 0x00000636, 0x0000062e,
- 0x80000645, 0x00000636, 0x0000062e, 0x80000645,
- 0x00000637, 0x00000645, 0x8000062d, 0x00000637,
- 0x00000645, 0x8000062d, 0x00000637, 0x00000645,
- 0x80000645, 0x00000637, 0x00000645, 0x8000064a,
- 0x00000639, 0x0000062c, 0x80000645, 0x00000639,
- 0x00000645, 0x80000645, 0x00000639, 0x00000645,
- 0x80000645, 0x00000639, 0x00000645, 0x80000649,
- 0x0000063a, 0x00000645, 0x80000645, 0x0000063a,
- 0x00000645, 0x8000064a, 0x0000063a, 0x00000645,
- 0x80000649, 0x00000641, 0x0000062e, 0x80000645,
- 0x00000641, 0x0000062e, 0x80000645, 0x00000642,
- 0x00000645, 0x8000062d, 0x00000642, 0x00000645,
- 0x80000645, 0x00000644, 0x0000062d, 0x80000645,
- 0x00000644, 0x0000062d, 0x8000064a, 0x00000644,
- 0x0000062d, 0x80000649, 0x00000644, 0x0000062c,
- 0x8000062c, 0x00000644, 0x0000062c, 0x8000062c,
- 0x00000644, 0x0000062e, 0x80000645, 0x00000644,
- 0x0000062e, 0x80000645, 0x00000644, 0x00000645,
- 0x8000062d, 0x00000644, 0x00000645, 0x8000062d,
- 0x00000645, 0x0000062d, 0x8000062c, 0x00000645,
- 0x0000062d, 0x80000645, 0x00000645, 0x0000062d,
- 0x8000064a, 0x00000645, 0x0000062c, 0x8000062d,
- 0x00000645, 0x0000062c, 0x80000645, 0x00000645,
- 0x0000062e, 0x8000062c, 0x00000645, 0x0000062e,
- 0x80000645, 0x00000645, 0x0000062c, 0x8000062e,
- 0x00000647, 0x00000645, 0x8000062c, 0x00000647,
- 0x00000645, 0x80000645, 0x00000646, 0x0000062d,
- 0x80000645, 0x00000646, 0x0000062d, 0x80000649,
- 0x00000646, 0x0000062c, 0x80000645, 0x00000646,
- 0x0000062c, 0x80000645, 0x00000646, 0x0000062c,
- 0x80000649, 0x00000646, 0x00000645, 0x8000064a,
- 0x00000646, 0x00000645, 0x80000649, 0x0000064a,
- 0x00000645, 0x80000645, 0x0000064a, 0x00000645,
- 0x80000645, 0x00000628, 0x0000062e, 0x8000064a,
- 0x0000062a, 0x0000062c, 0x8000064a, 0x0000062a,
- 0x0000062c, 0x80000649, 0x0000062a, 0x0000062e,
- 0x8000064a, 0x0000062a, 0x0000062e, 0x80000649,
- 0x0000062a, 0x00000645, 0x8000064a, 0x0000062a,
- 0x00000645, 0x80000649, 0x0000062c, 0x00000645,
- 0x8000064a, 0x0000062c, 0x0000062d, 0x80000649,
- 0x0000062c, 0x00000645, 0x80000649, 0x00000633,
- 0x0000062e, 0x80000649, 0x00000635, 0x0000062d,
- 0x8000064a, 0x00000634, 0x0000062d, 0x8000064a,
- 0x00000636, 0x0000062d, 0x8000064a, 0x00000644,
- 0x0000062c, 0x8000064a, 0x00000644, 0x00000645,
- 0x8000064a, 0x0000064a, 0x0000062d, 0x8000064a,
- 0x0000064a, 0x0000062c, 0x8000064a, 0x0000064a,
- 0x00000645, 0x8000064a, 0x00000645, 0x00000645,
- 0x8000064a, 0x00000642, 0x00000645, 0x8000064a,
- 0x00000646, 0x0000062d, 0x8000064a, 0x00000642,
- 0x00000645, 0x8000062d, 0x00000644, 0x0000062d,
- 0x80000645, 0x00000639, 0x00000645, 0x8000064a,
- 0x00000643, 0x00000645, 0x8000064a, 0x00000646,
- 0x0000062c, 0x8000062d, 0x00000645, 0x0000062e,
- 0x8000064a, 0x00000644, 0x0000062c, 0x80000645,
- 0x00000643, 0x00000645, 0x80000645, 0x00000644,
- 0x0000062c, 0x80000645, 0x00000646, 0x0000062c,
- 0x8000062d, 0x0000062c, 0x0000062d, 0x8000064a,
- 0x0000062d, 0x0000062c, 0x8000064a, 0x00000645,
- 0x0000062c, 0x8000064a, 0x00000641, 0x00000645,
- 0x8000064a, 0x00000628, 0x0000062d, 0x8000064a,
- 0x00000643, 0x00000645, 0x80000645, 0x00000639,
- 0x0000062c, 0x80000645, 0x00000635, 0x00000645,
- 0x80000645, 0x00000633, 0x0000062e, 0x8000064a,
- 0x00000646, 0x0000062c, 0x8000064a, 0x00000635,
- 0x00000644, 0x800006d2, 0x00000642, 0x00000644,
- 0x800006d2, 0x00000627, 0x00000644, 0x00000644,
- 0x80000647, 0x00000627, 0x00000643, 0x00000628,
- 0x80000631, 0x00000645, 0x0000062d, 0x00000645,
- 0x8000062f, 0x00000635, 0x00000644, 0x00000639,
- 0x80000645, 0x00000631, 0x00000633, 0x00000648,
- 0x80000644, 0x00000639, 0x00000644, 0x0000064a,
- 0x80000647, 0x00000648, 0x00000633, 0x00000644,
- 0x80000645, 0x00000635, 0x00000644, 0x80000649,
- 0x00000635, 0x00000644, 0x00000649, 0x00000020,
- 0x00000627, 0x00000644, 0x00000644, 0x00000647,
- 0x00000020, 0x00000639, 0x00000644, 0x0000064a,
- 0x00000647, 0x00000020, 0x00000648, 0x00000633,
- 0x00000644, 0x80000645, 0x0000062c, 0x00000644,
- 0x00000020, 0x0000062c, 0x00000644, 0x00000627,
- 0x00000644, 0x80000647, 0x00000631, 0x000006cc,
- 0x00000627, 0x80000644, 0x8000002c, 0x80003001,
- 0x80003002, 0x8000003a, 0x8000003b, 0x80000021,
- 0x8000003f, 0x80003016, 0x80003017, 0x80002026,
- 0x80002025, 0x80002014, 0x80002013, 0x8000005f,
- 0x8000005f, 0x80000028, 0x80000029, 0x8000007b,
- 0x8000007d, 0x80003014, 0x80003015, 0x80003010,
- 0x80003011, 0x8000300a, 0x8000300b, 0x80003008,
- 0x80003009, 0x8000300c, 0x8000300d, 0x8000300e,
- 0x8000300f, 0x8000005b, 0x8000005d, 0x8000203e,
- 0x8000203e, 0x8000203e, 0x8000203e, 0x8000005f,
- 0x8000005f, 0x8000005f, 0x8000002c, 0x80003001,
- 0x8000002e, 0x8000003b, 0x8000003a, 0x8000003f,
- 0x80000021, 0x80002014, 0x80000028, 0x80000029,
- 0x8000007b, 0x8000007d, 0x80003014, 0x80003015,
- 0x80000023, 0x80000026, 0x8000002a, 0x8000002b,
- 0x8000002d, 0x8000003c, 0x8000003e, 0x8000003d,
- 0x8000005c, 0x80000024, 0x80000025, 0x80000040,
- 0x00000020, 0x8000064b, 0x00000640, 0x8000064b,
- 0x00000020, 0x8000064c, 0x00000020, 0x8000064d,
- 0x00000020, 0x8000064e, 0x00000640, 0x8000064e,
- 0x00000020, 0x8000064f, 0x00000640, 0x8000064f,
- 0x00000020, 0x80000650, 0x00000640, 0x80000650,
- 0x00000020, 0x80000651, 0x00000640, 0x80000651,
- 0x00000020, 0x80000652, 0x00000640, 0x80000652,
- 0x80000621, 0x80000622, 0x80000622, 0x80000623,
- 0x80000623, 0x80000624, 0x80000624, 0x80000625,
- 0x80000625, 0x80000626, 0x80000626, 0x80000626,
- 0x80000626, 0x80000627, 0x80000627, 0x80000628,
- 0x80000628, 0x80000628, 0x80000628, 0x80000629,
- 0x80000629, 0x8000062a, 0x8000062a, 0x8000062a,
- 0x8000062a, 0x8000062b, 0x8000062b, 0x8000062b,
- 0x8000062b, 0x8000062c, 0x8000062c, 0x8000062c,
- 0x8000062c, 0x8000062d, 0x8000062d, 0x8000062d,
- 0x8000062d, 0x8000062e, 0x8000062e, 0x8000062e,
- 0x8000062e, 0x8000062f, 0x8000062f, 0x80000630,
- 0x80000630, 0x80000631, 0x80000631, 0x80000632,
- 0x80000632, 0x80000633, 0x80000633, 0x80000633,
- 0x80000633, 0x80000634, 0x80000634, 0x80000634,
- 0x80000634, 0x80000635, 0x80000635, 0x80000635,
- 0x80000635, 0x80000636, 0x80000636, 0x80000636,
- 0x80000636, 0x80000637, 0x80000637, 0x80000637,
- 0x80000637, 0x80000638, 0x80000638, 0x80000638,
- 0x80000638, 0x80000639, 0x80000639, 0x80000639,
- 0x80000639, 0x8000063a, 0x8000063a, 0x8000063a,
- 0x8000063a, 0x80000641, 0x80000641, 0x80000641,
- 0x80000641, 0x80000642, 0x80000642, 0x80000642,
- 0x80000642, 0x80000643, 0x80000643, 0x80000643,
- 0x80000643, 0x80000644, 0x80000644, 0x80000644,
- 0x80000644, 0x80000645, 0x80000645, 0x80000645,
- 0x80000645, 0x80000646, 0x80000646, 0x80000646,
- 0x80000646, 0x80000647, 0x80000647, 0x80000647,
- 0x80000647, 0x80000648, 0x80000648, 0x80000649,
- 0x80000649, 0x8000064a, 0x8000064a, 0x8000064a,
- 0x8000064a, 0x00000644, 0x80000622, 0x00000644,
- 0x80000622, 0x00000644, 0x80000623, 0x00000644,
- 0x80000623, 0x00000644, 0x80000625, 0x00000644,
- 0x80000625, 0x00000644, 0x80000627, 0x00000644,
- 0x80000627, 0x80000021, 0x80000022, 0x80000023,
- 0x80000024, 0x80000025, 0x80000026, 0x80000027,
- 0x80000028, 0x80000029, 0x8000002a, 0x8000002b,
- 0x8000002c, 0x8000002d, 0x8000002e, 0x8000002f,
- 0x80000030, 0x80000031, 0x80000032, 0x80000033,
- 0x80000034, 0x80000035, 0x80000036, 0x80000037,
- 0x80000038, 0x80000039, 0x8000003a, 0x8000003b,
- 0x8000003c, 0x8000003d, 0x8000003e, 0x8000003f,
- 0x80000040, 0x80000041, 0x80000042, 0x80000043,
- 0x80000044, 0x80000045, 0x80000046, 0x80000047,
- 0x80000048, 0x80000049, 0x8000004a, 0x8000004b,
- 0x8000004c, 0x8000004d, 0x8000004e, 0x8000004f,
- 0x80000050, 0x80000051, 0x80000052, 0x80000053,
- 0x80000054, 0x80000055, 0x80000056, 0x80000057,
- 0x80000058, 0x80000059, 0x8000005a, 0x8000005b,
- 0x8000005c, 0x8000005d, 0x8000005e, 0x8000005f,
- 0x80000060, 0x80000061, 0x80000062, 0x80000063,
- 0x80000064, 0x80000065, 0x80000066, 0x80000067,
- 0x80000068, 0x80000069, 0x8000006a, 0x8000006b,
- 0x8000006c, 0x8000006d, 0x8000006e, 0x8000006f,
- 0x80000070, 0x80000071, 0x80000072, 0x80000073,
- 0x80000074, 0x80000075, 0x80000076, 0x80000077,
- 0x80000078, 0x80000079, 0x8000007a, 0x8000007b,
- 0x8000007c, 0x8000007d, 0x8000007e, 0x80002985,
- 0x80002986, 0x80003002, 0x8000300c, 0x8000300d,
- 0x80003001, 0x800030fb, 0x800030f2, 0x800030a1,
- 0x800030a3, 0x800030a5, 0x800030a7, 0x800030a9,
- 0x800030e3, 0x800030e5, 0x800030e7, 0x800030c3,
- 0x800030fc, 0x800030a2, 0x800030a4, 0x800030a6,
- 0x800030a8, 0x800030aa, 0x800030ab, 0x800030ad,
- 0x800030af, 0x800030b1, 0x800030b3, 0x800030b5,
- 0x800030b7, 0x800030b9, 0x800030bb, 0x800030bd,
- 0x800030bf, 0x800030c1, 0x800030c4, 0x800030c6,
- 0x800030c8, 0x800030ca, 0x800030cb, 0x800030cc,
- 0x800030cd, 0x800030ce, 0x800030cf, 0x800030d2,
- 0x800030d5, 0x800030d8, 0x800030db, 0x800030de,
- 0x800030df, 0x800030e0, 0x800030e1, 0x800030e2,
- 0x800030e4, 0x800030e6, 0x800030e8, 0x800030e9,
- 0x800030ea, 0x800030eb, 0x800030ec, 0x800030ed,
- 0x800030ef, 0x800030f3, 0x80003099, 0x8000309a,
- 0x80003164, 0x80003131, 0x80003132, 0x80003133,
- 0x80003134, 0x80003135, 0x80003136, 0x80003137,
- 0x80003138, 0x80003139, 0x8000313a, 0x8000313b,
- 0x8000313c, 0x8000313d, 0x8000313e, 0x8000313f,
- 0x80003140, 0x80003141, 0x80003142, 0x80003143,
- 0x80003144, 0x80003145, 0x80003146, 0x80003147,
- 0x80003148, 0x80003149, 0x8000314a, 0x8000314b,
- 0x8000314c, 0x8000314d, 0x8000314e, 0x8000314f,
- 0x80003150, 0x80003151, 0x80003152, 0x80003153,
- 0x80003154, 0x80003155, 0x80003156, 0x80003157,
- 0x80003158, 0x80003159, 0x8000315a, 0x8000315b,
- 0x8000315c, 0x8000315d, 0x8000315e, 0x8000315f,
- 0x80003160, 0x80003161, 0x80003162, 0x80003163,
- 0x800000a2, 0x800000a3, 0x800000ac, 0x800000af,
- 0x800000a6, 0x800000a5, 0x800020a9, 0x80002502,
- 0x80002190, 0x80002191, 0x80002192, 0x80002193,
- 0x800025a0, 0x800025cb, 0x0001d157, 0x8001d165,
- 0x0001d158, 0x8001d165, 0x0001d15f, 0x8001d16e,
- 0x0001d15f, 0x8001d16f, 0x0001d15f, 0x8001d170,
- 0x0001d15f, 0x8001d171, 0x0001d15f, 0x8001d172,
- 0x0001d1b9, 0x8001d165, 0x0001d1ba, 0x8001d165,
- 0x0001d1bb, 0x8001d16e, 0x0001d1bc, 0x8001d16e,
- 0x0001d1bb, 0x8001d16f, 0x0001d1bc, 0x8001d16f,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000069, 0x8000006a, 0x8000006b,
- 0x8000006c, 0x8000006d, 0x8000006e, 0x8000006f,
- 0x80000070, 0x80000071, 0x80000072, 0x80000073,
- 0x80000074, 0x80000075, 0x80000076, 0x80000077,
- 0x80000078, 0x80000079, 0x8000007a, 0x80000041,
- 0x80000042, 0x80000043, 0x80000044, 0x80000045,
- 0x80000046, 0x80000047, 0x80000048, 0x80000049,
- 0x8000004a, 0x8000004b, 0x8000004c, 0x8000004d,
- 0x8000004e, 0x8000004f, 0x80000050, 0x80000051,
- 0x80000052, 0x80000053, 0x80000054, 0x80000055,
- 0x80000056, 0x80000057, 0x80000058, 0x80000059,
- 0x8000005a, 0x80000061, 0x80000062, 0x80000063,
- 0x80000064, 0x80000065, 0x80000066, 0x80000067,
- 0x80000068, 0x80000069, 0x8000006a, 0x8000006b,
- 0x8000006c, 0x8000006d, 0x8000006e, 0x8000006f,
- 0x80000070, 0x80000071, 0x80000072, 0x80000073,
- 0x80000074, 0x80000075, 0x80000076, 0x80000077,
- 0x80000078, 0x80000079, 0x8000007a, 0x80000041,
- 0x80000043, 0x80000044, 0x80000047, 0x8000004a,
- 0x8000004b, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000053, 0x80000054, 0x80000055,
- 0x80000056, 0x80000057, 0x80000058, 0x80000059,
- 0x8000005a, 0x80000061, 0x80000062, 0x80000063,
- 0x80000064, 0x80000066, 0x80000068, 0x80000069,
- 0x8000006a, 0x8000006b, 0x8000006c, 0x8000006d,
- 0x8000006e, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000044, 0x80000045,
- 0x80000046, 0x80000047, 0x8000004a, 0x8000004b,
- 0x8000004c, 0x8000004d, 0x8000004e, 0x8000004f,
- 0x80000050, 0x80000051, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x80000061, 0x80000062, 0x80000063,
- 0x80000064, 0x80000065, 0x80000066, 0x80000067,
- 0x80000068, 0x80000069, 0x8000006a, 0x8000006b,
- 0x8000006c, 0x8000006d, 0x8000006e, 0x8000006f,
- 0x80000070, 0x80000071, 0x80000072, 0x80000073,
- 0x80000074, 0x80000075, 0x80000076, 0x80000077,
- 0x80000078, 0x80000079, 0x8000007a, 0x80000041,
- 0x80000042, 0x80000044, 0x80000045, 0x80000046,
- 0x80000047, 0x80000049, 0x8000004a, 0x8000004b,
- 0x8000004c, 0x8000004d, 0x8000004f, 0x80000053,
- 0x80000054, 0x80000055, 0x80000056, 0x80000057,
- 0x80000058, 0x80000059, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000041, 0x80000042, 0x80000043, 0x80000044,
- 0x80000045, 0x80000046, 0x80000047, 0x80000048,
- 0x80000049, 0x8000004a, 0x8000004b, 0x8000004c,
- 0x8000004d, 0x8000004e, 0x8000004f, 0x80000050,
- 0x80000051, 0x80000052, 0x80000053, 0x80000054,
- 0x80000055, 0x80000056, 0x80000057, 0x80000058,
- 0x80000059, 0x8000005a, 0x80000061, 0x80000062,
- 0x80000063, 0x80000064, 0x80000065, 0x80000066,
- 0x80000067, 0x80000068, 0x80000069, 0x8000006a,
- 0x8000006b, 0x8000006c, 0x8000006d, 0x8000006e,
- 0x8000006f, 0x80000070, 0x80000071, 0x80000072,
- 0x80000073, 0x80000074, 0x80000075, 0x80000076,
- 0x80000077, 0x80000078, 0x80000079, 0x8000007a,
- 0x80000131, 0x80000237, 0x80000391, 0x80000392,
- 0x80000393, 0x80000394, 0x80000395, 0x80000396,
- 0x80000397, 0x80000398, 0x80000399, 0x8000039a,
- 0x8000039b, 0x8000039c, 0x8000039d, 0x8000039e,
- 0x8000039f, 0x800003a0, 0x800003a1, 0x800003f4,
- 0x800003a3, 0x800003a4, 0x800003a5, 0x800003a6,
- 0x800003a7, 0x800003a8, 0x800003a9, 0x80002207,
- 0x800003b1, 0x800003b2, 0x800003b3, 0x800003b4,
- 0x800003b5, 0x800003b6, 0x800003b7, 0x800003b8,
- 0x800003b9, 0x800003ba, 0x800003bb, 0x800003bc,
- 0x800003bd, 0x800003be, 0x800003bf, 0x800003c0,
- 0x800003c1, 0x800003c2, 0x800003c3, 0x800003c4,
- 0x800003c5, 0x800003c6, 0x800003c7, 0x800003c8,
- 0x800003c9, 0x80002202, 0x800003f5, 0x800003d1,
- 0x800003f0, 0x800003d5, 0x800003f1, 0x800003d6,
- 0x80000391, 0x80000392, 0x80000393, 0x80000394,
- 0x80000395, 0x80000396, 0x80000397, 0x80000398,
- 0x80000399, 0x8000039a, 0x8000039b, 0x8000039c,
- 0x8000039d, 0x8000039e, 0x8000039f, 0x800003a0,
- 0x800003a1, 0x800003f4, 0x800003a3, 0x800003a4,
- 0x800003a5, 0x800003a6, 0x800003a7, 0x800003a8,
- 0x800003a9, 0x80002207, 0x800003b1, 0x800003b2,
- 0x800003b3, 0x800003b4, 0x800003b5, 0x800003b6,
- 0x800003b7, 0x800003b8, 0x800003b9, 0x800003ba,
- 0x800003bb, 0x800003bc, 0x800003bd, 0x800003be,
- 0x800003bf, 0x800003c0, 0x800003c1, 0x800003c2,
- 0x800003c3, 0x800003c4, 0x800003c5, 0x800003c6,
- 0x800003c7, 0x800003c8, 0x800003c9, 0x80002202,
- 0x800003f5, 0x800003d1, 0x800003f0, 0x800003d5,
- 0x800003f1, 0x800003d6, 0x80000391, 0x80000392,
- 0x80000393, 0x80000394, 0x80000395, 0x80000396,
- 0x80000397, 0x80000398, 0x80000399, 0x8000039a,
- 0x8000039b, 0x8000039c, 0x8000039d, 0x8000039e,
- 0x8000039f, 0x800003a0, 0x800003a1, 0x800003f4,
- 0x800003a3, 0x800003a4, 0x800003a5, 0x800003a6,
- 0x800003a7, 0x800003a8, 0x800003a9, 0x80002207,
- 0x800003b1, 0x800003b2, 0x800003b3, 0x800003b4,
- 0x800003b5, 0x800003b6, 0x800003b7, 0x800003b8,
- 0x800003b9, 0x800003ba, 0x800003bb, 0x800003bc,
- 0x800003bd, 0x800003be, 0x800003bf, 0x800003c0,
- 0x800003c1, 0x800003c2, 0x800003c3, 0x800003c4,
- 0x800003c5, 0x800003c6, 0x800003c7, 0x800003c8,
- 0x800003c9, 0x80002202, 0x800003f5, 0x800003d1,
- 0x800003f0, 0x800003d5, 0x800003f1, 0x800003d6,
- 0x80000391, 0x80000392, 0x80000393, 0x80000394,
- 0x80000395, 0x80000396, 0x80000397, 0x80000398,
- 0x80000399, 0x8000039a, 0x8000039b, 0x8000039c,
- 0x8000039d, 0x8000039e, 0x8000039f, 0x800003a0,
- 0x800003a1, 0x800003f4, 0x800003a3, 0x800003a4,
- 0x800003a5, 0x800003a6, 0x800003a7, 0x800003a8,
- 0x800003a9, 0x80002207, 0x800003b1, 0x800003b2,
- 0x800003b3, 0x800003b4, 0x800003b5, 0x800003b6,
- 0x800003b7, 0x800003b8, 0x800003b9, 0x800003ba,
- 0x800003bb, 0x800003bc, 0x800003bd, 0x800003be,
- 0x800003bf, 0x800003c0, 0x800003c1, 0x800003c2,
- 0x800003c3, 0x800003c4, 0x800003c5, 0x800003c6,
- 0x800003c7, 0x800003c8, 0x800003c9, 0x80002202,
- 0x800003f5, 0x800003d1, 0x800003f0, 0x800003d5,
- 0x800003f1, 0x800003d6, 0x80000391, 0x80000392,
- 0x80000393, 0x80000394, 0x80000395, 0x80000396,
- 0x80000397, 0x80000398, 0x80000399, 0x8000039a,
- 0x8000039b, 0x8000039c, 0x8000039d, 0x8000039e,
- 0x8000039f, 0x800003a0, 0x800003a1, 0x800003f4,
- 0x800003a3, 0x800003a4, 0x800003a5, 0x800003a6,
- 0x800003a7, 0x800003a8, 0x800003a9, 0x80002207,
- 0x800003b1, 0x800003b2, 0x800003b3, 0x800003b4,
- 0x800003b5, 0x800003b6, 0x800003b7, 0x800003b8,
- 0x800003b9, 0x800003ba, 0x800003bb, 0x800003bc,
- 0x800003bd, 0x800003be, 0x800003bf, 0x800003c0,
- 0x800003c1, 0x800003c2, 0x800003c3, 0x800003c4,
- 0x800003c5, 0x800003c6, 0x800003c7, 0x800003c8,
- 0x800003c9, 0x80002202, 0x800003f5, 0x800003d1,
- 0x800003f0, 0x800003d5, 0x800003f1, 0x800003d6,
- 0x80000030, 0x80000031, 0x80000032, 0x80000033,
- 0x80000034, 0x80000035, 0x80000036, 0x80000037,
- 0x80000038, 0x80000039, 0x80000030, 0x80000031,
- 0x80000032, 0x80000033, 0x80000034, 0x80000035,
- 0x80000036, 0x80000037, 0x80000038, 0x80000039,
- 0x80000030, 0x80000031, 0x80000032, 0x80000033,
- 0x80000034, 0x80000035, 0x80000036, 0x80000037,
- 0x80000038, 0x80000039, 0x80000030, 0x80000031,
- 0x80000032, 0x80000033, 0x80000034, 0x80000035,
- 0x80000036, 0x80000037, 0x80000038, 0x80000039,
- 0x80000030, 0x80000031, 0x80000032, 0x80000033,
- 0x80000034, 0x80000035, 0x80000036, 0x80000037,
- 0x80000038, 0x80000039, 0x80004e3d, 0x80004e38,
- 0x80004e41, 0x80020122, 0x80004f60, 0x80004fae,
- 0x80004fbb, 0x80005002, 0x8000507a, 0x80005099,
- 0x800050e7, 0x800050cf, 0x8000349e, 0x8002063a,
- 0x8000514d, 0x80005154, 0x80005164, 0x80005177,
- 0x8002051c, 0x800034b9, 0x80005167, 0x8000518d,
- 0x8002054b, 0x80005197, 0x800051a4, 0x80004ecc,
- 0x800051ac, 0x800051b5, 0x800291df, 0x800051f5,
- 0x80005203, 0x800034df, 0x8000523b, 0x80005246,
- 0x80005272, 0x80005277, 0x80003515, 0x800052c7,
- 0x800052c9, 0x800052e4, 0x800052fa, 0x80005305,
- 0x80005306, 0x80005317, 0x80005349, 0x80005351,
- 0x8000535a, 0x80005373, 0x8000537d, 0x8000537f,
- 0x8000537f, 0x8000537f, 0x80020a2c, 0x80007070,
- 0x800053ca, 0x800053df, 0x80020b63, 0x800053eb,
- 0x800053f1, 0x80005406, 0x8000549e, 0x80005438,
- 0x80005448, 0x80005468, 0x800054a2, 0x800054f6,
- 0x80005510, 0x80005553, 0x80005563, 0x80005584,
- 0x80005584, 0x80005599, 0x800055ab, 0x800055b3,
- 0x800055c2, 0x80005716, 0x80005606, 0x80005717,
- 0x80005651, 0x80005674, 0x80005207, 0x800058ee,
- 0x800057ce, 0x800057f4, 0x8000580d, 0x8000578b,
- 0x80005832, 0x80005831, 0x800058ac, 0x800214e4,
- 0x800058f2, 0x800058f7, 0x80005906, 0x8000591a,
- 0x80005922, 0x80005962, 0x800216a8, 0x800216ea,
- 0x800059ec, 0x80005a1b, 0x80005a27, 0x800059d8,
- 0x80005a66, 0x800036ee, 0x800036fc, 0x80005b08,
- 0x80005b3e, 0x80005b3e, 0x800219c8, 0x80005bc3,
- 0x80005bd8, 0x80005be7, 0x80005bf3, 0x80021b18,
- 0x80005bff, 0x80005c06, 0x80005f53, 0x80005c22,
- 0x80003781, 0x80005c60, 0x80005c6e, 0x80005cc0,
- 0x80005c8d, 0x80021de4, 0x80005d43, 0x80021de6,
- 0x80005d6e, 0x80005d6b, 0x80005d7c, 0x80005de1,
- 0x80005de2, 0x8000382f, 0x80005dfd, 0x80005e28,
- 0x80005e3d, 0x80005e69, 0x80003862, 0x80022183,
- 0x8000387c, 0x80005eb0, 0x80005eb3, 0x80005eb6,
- 0x80005eca, 0x8002a392, 0x80005efe, 0x80022331,
- 0x80022331, 0x80008201, 0x80005f22, 0x80005f22,
- 0x800038c7, 0x800232b8, 0x800261da, 0x80005f62,
- 0x80005f6b, 0x800038e3, 0x80005f9a, 0x80005fcd,
- 0x80005fd7, 0x80005ff9, 0x80006081, 0x8000393a,
- 0x8000391c, 0x80006094, 0x800226d4, 0x800060c7,
- 0x80006148, 0x8000614c, 0x8000614e, 0x8000614c,
- 0x8000617a, 0x8000618e, 0x800061b2, 0x800061a4,
- 0x800061af, 0x800061de, 0x800061f2, 0x800061f6,
- 0x80006210, 0x8000621b, 0x8000625d, 0x800062b1,
- 0x800062d4, 0x80006350, 0x80022b0c, 0x8000633d,
- 0x800062fc, 0x80006368, 0x80006383, 0x800063e4,
- 0x80022bf1, 0x80006422, 0x800063c5, 0x800063a9,
- 0x80003a2e, 0x80006469, 0x8000647e, 0x8000649d,
- 0x80006477, 0x80003a6c, 0x8000654f, 0x8000656c,
- 0x8002300a, 0x800065e3, 0x800066f8, 0x80006649,
- 0x80003b19, 0x80006691, 0x80003b08, 0x80003ae4,
- 0x80005192, 0x80005195, 0x80006700, 0x8000669c,
- 0x800080ad, 0x800043d9, 0x80006717, 0x8000671b,
- 0x80006721, 0x8000675e, 0x80006753, 0x800233c3,
- 0x80003b49, 0x800067fa, 0x80006785, 0x80006852,
- 0x80006885, 0x8002346d, 0x8000688e, 0x8000681f,
- 0x80006914, 0x80003b9d, 0x80006942, 0x800069a3,
- 0x800069ea, 0x80006aa8, 0x800236a3, 0x80006adb,
- 0x80003c18, 0x80006b21, 0x800238a7, 0x80006b54,
- 0x80003c4e, 0x80006b72, 0x80006b9f, 0x80006bba,
- 0x80006bbb, 0x80023a8d, 0x80021d0b, 0x80023afa,
- 0x80006c4e, 0x80023cbc, 0x80006cbf, 0x80006ccd,
- 0x80006c67, 0x80006d16, 0x80006d3e, 0x80006d77,
- 0x80006d41, 0x80006d69, 0x80006d78, 0x80006d85,
- 0x80023d1e, 0x80006d34, 0x80006e2f, 0x80006e6e,
- 0x80003d33, 0x80006ecb, 0x80006ec7, 0x80023ed1,
- 0x80006df9, 0x80006f6e, 0x80023f5e, 0x80023f8e,
- 0x80006fc6, 0x80007039, 0x8000701e, 0x8000701b,
- 0x80003d96, 0x8000704a, 0x8000707d, 0x80007077,
- 0x800070ad, 0x80020525, 0x80007145, 0x80024263,
- 0x8000719c, 0x800243ab, 0x80007228, 0x80007235,
- 0x80007250, 0x80024608, 0x80007280, 0x80007295,
- 0x80024735, 0x80024814, 0x8000737a, 0x8000738b,
- 0x80003eac, 0x800073a5, 0x80003eb8, 0x80003eb8,
- 0x80007447, 0x8000745c, 0x80007471, 0x80007485,
- 0x800074ca, 0x80003f1b, 0x80007524, 0x80024c36,
- 0x8000753e, 0x80024c92, 0x80007570, 0x8002219f,
- 0x80007610, 0x80024fa1, 0x80024fb8, 0x80025044,
- 0x80003ffc, 0x80004008, 0x800076f4, 0x800250f3,
- 0x800250f2, 0x80025119, 0x80025133, 0x8000771e,
- 0x8000771f, 0x8000771f, 0x8000774a, 0x80004039,
- 0x8000778b, 0x80004046, 0x80004096, 0x8002541d,
- 0x8000784e, 0x8000788c, 0x800078cc, 0x800040e3,
- 0x80025626, 0x80007956, 0x8002569a, 0x800256c5,
- 0x8000798f, 0x800079eb, 0x8000412f, 0x80007a40,
- 0x80007a4a, 0x80007a4f, 0x8002597c, 0x80025aa7,
- 0x80025aa7, 0x80007aee, 0x80004202, 0x80025bab,
- 0x80007bc6, 0x80007bc9, 0x80004227, 0x80025c80,
- 0x80007cd2, 0x800042a0, 0x80007ce8, 0x80007ce3,
- 0x80007d00, 0x80025f86, 0x80007d63, 0x80004301,
- 0x80007dc7, 0x80007e02, 0x80007e45, 0x80004334,
- 0x80026228, 0x80026247, 0x80004359, 0x800262d9,
- 0x80007f7a, 0x8002633e, 0x80007f95, 0x80007ffa,
- 0x80008005, 0x800264da, 0x80026523, 0x80008060,
- 0x800265a8, 0x80008070, 0x8002335f, 0x800043d5,
- 0x800080b2, 0x80008103, 0x8000440b, 0x8000813e,
- 0x80005ab5, 0x800267a7, 0x800267b5, 0x80023393,
- 0x8002339c, 0x80008201, 0x80008204, 0x80008f9e,
- 0x8000446b, 0x80008291, 0x8000828b, 0x8000829d,
- 0x800052b3, 0x800082b1, 0x800082b3, 0x800082bd,
- 0x800082e6, 0x80026b3c, 0x800082e5, 0x8000831d,
- 0x80008363, 0x800083ad, 0x80008323, 0x800083bd,
- 0x800083e7, 0x80008457, 0x80008353, 0x800083ca,
- 0x800083cc, 0x800083dc, 0x80026c36, 0x80026d6b,
- 0x80026cd5, 0x8000452b, 0x800084f1, 0x800084f3,
- 0x80008516, 0x800273ca, 0x80008564, 0x80026f2c,
- 0x8000455d, 0x80004561, 0x80026fb1, 0x800270d2,
- 0x8000456b, 0x80008650, 0x8000865c, 0x80008667,
- 0x80008669, 0x800086a9, 0x80008688, 0x8000870e,
- 0x800086e2, 0x80008779, 0x80008728, 0x8000876b,
- 0x80008786, 0x800045d7, 0x800087e1, 0x80008801,
- 0x800045f9, 0x80008860, 0x80008863, 0x80027667,
- 0x800088d7, 0x800088de, 0x80004635, 0x800088fa,
- 0x800034bb, 0x800278ae, 0x80027966, 0x800046be,
- 0x800046c7, 0x80008aa0, 0x80008aed, 0x80008b8a,
- 0x80008c55, 0x80027ca8, 0x80008cab, 0x80008cc1,
- 0x80008d1b, 0x80008d77, 0x80027f2f, 0x80020804,
- 0x80008dcb, 0x80008dbc, 0x80008df0, 0x800208de,
- 0x80008ed4, 0x80008f38, 0x800285d2, 0x800285ed,
- 0x80009094, 0x800090f1, 0x80009111, 0x8002872e,
- 0x8000911b, 0x80009238, 0x800092d7, 0x800092d8,
- 0x8000927c, 0x800093f9, 0x80009415, 0x80028bfa,
- 0x8000958b, 0x80004995, 0x800095b7, 0x80028d77,
- 0x800049e6, 0x800096c3, 0x80005db2, 0x80009723,
- 0x80029145, 0x8002921a, 0x80004a6e, 0x80004a76,
- 0x800097e0, 0x8002940a, 0x80004ab2, 0x80029496,
- 0x8000980b, 0x8000980b, 0x80009829, 0x800295b6,
- 0x800098e2, 0x80004b33, 0x80009929, 0x800099a7,
- 0x800099c2, 0x800099fe, 0x80004bce, 0x80029b30,
- 0x80009b12, 0x80009c40, 0x80009cfd, 0x80004cce,
- 0x80004ced, 0x80009d67, 0x8002a0ce, 0x80004cf8,
- 0x8002a105, 0x8002a20e, 0x8002a291, 0x80009ebb,
- 0x80004d56, 0x80009ef9, 0x80009efe, 0x80009f05,
- 0x80009f0f, 0x80009f16, 0x80009f3b, 0x8002a600,
-};
-
diff --git a/intl/unicharutil/nsUnicodeNormalizer.cpp b/intl/unicharutil/nsUnicodeNormalizer.cpp
index 16c3a969c..6f6c3d2dd 100644
--- a/intl/unicharutil/nsUnicodeNormalizer.cpp
+++ b/intl/unicharutil/nsUnicodeNormalizer.cpp
@@ -1,66 +1,16 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* This file is modified from JPNIC's mDNKit, it is under both MPL and
- * JPNIC's license.
- */
-
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-/*
- * Copyright (c) 2000,2002 Japan Network Information Center.
- * All rights reserved.
- *
- * By using this file, you agree to the terms and conditions set forth bellow.
- *
- * LICENSE TERMS AND CONDITIONS
- *
- * The following License Terms and Conditions apply, unless a different
- * license is obtained from Japan Network Information Center ("JPNIC"),
- * a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda,
- * Chiyoda-ku, Tokyo 101-0047, Japan.
- *
- * 1. Use, Modification and Redistribution (including distribution of any
- * modified or derived work) in source and/or binary forms is permitted
- * under this License Terms and Conditions.
- *
- * 2. Redistribution of source code must retain the copyright notices as they
- * appear in each source code file, this License Terms and Conditions.
- *
- * 3. Redistribution in binary form must reproduce the Copyright Notice,
- * this License Terms and Conditions, in the documentation and/or other
- * materials provided with the distribution. For the purposes of binary
- * distribution the "Copyright Notice" refers to the following language:
- * "Copyright (c) 2000-2002 Japan Network Information Center. All rights reserved."
- *
- * 4. The name of JPNIC may not be used to endorse or promote products
- * derived from this Software without specific prior written approval of
- * JPNIC.
- *
- * 5. Disclaimer/Limitation of Liability: THIS SOFTWARE IS PROVIDED BY JPNIC
- * "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 JPNIC 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 DAMAGES.
- */
-
-#include <string.h>
-
-#include "nsMemory.h"
#include "nsUnicodeNormalizer.h"
-#include "nsString.h"
-#include "mozilla/BinarySearch.h"
+#include "ICUUtils.h"
+#include "unicode/unorm2.h"
+#include "unicode/utext.h"
NS_IMPL_ISUPPORTS(nsUnicodeNormalizer, nsIUnicodeNormalizer)
-
nsUnicodeNormalizer::nsUnicodeNormalizer()
{
}
@@ -69,636 +19,80 @@ nsUnicodeNormalizer::~nsUnicodeNormalizer()
{
}
-
-
-#define END_BIT 0x80000000
-
-
-/*
- * Some constants for Hangul decomposition/composition.
- * These things were taken from unicode book.
- */
-#define SBase 0xac00
-#define LBase 0x1100
-#define VBase 0x1161
-#define TBase 0x11a7
-#define LCount 19
-#define VCount 21
-#define TCount 28
-#define SLast (SBase + LCount * VCount * TCount)
-
-struct composition {
- uint32_t c2; /* 2nd character */
- uint32_t comp; /* composed character */
-};
-
-
-#include "normalization_data.h"
-
-/*
- * Macro for multi-level index table.
- */
-#define LOOKUPTBL(vprefix, mprefix, v) \
- DMAP(vprefix)[\
- IMAP(vprefix)[\
- IMAP(vprefix)[IDX0(mprefix, v)] + IDX1(mprefix, v)\
- ]\
- ].tbl[IDX2(mprefix, v)]
-
-#define IDX0(mprefix, v) IDX_0(v, BITS1(mprefix), BITS2(mprefix))
-#define IDX1(mprefix, v) IDX_1(v, BITS1(mprefix), BITS2(mprefix))
-#define IDX2(mprefix, v) IDX_2(v, BITS1(mprefix), BITS2(mprefix))
-
-#define IDX_0(v, bits1, bits2) ((v) >> ((bits1) + (bits2)))
-#define IDX_1(v, bits1, bits2) (((v) >> (bits2)) & ((1 << (bits1)) - 1))
-#define IDX_2(v, bits1, bits2) ((v) & ((1 << (bits2)) - 1))
-
-#define BITS1(mprefix) mprefix ## _BITS_1
-#define BITS2(mprefix) mprefix ## _BITS_2
-
-#define IMAP(vprefix) vprefix ## _imap
-#define DMAP(vprefix) vprefix ## _table
-#define SEQ(vprefix) vprefix ## _seq
-
-static int32_t
-canonclass(uint32_t c) {
- /* Look up canonicalclass table. */
- return (LOOKUPTBL(canon_class, CANON_CLASS, c));
-}
-
-static int32_t
-decompose_char(uint32_t c, const uint32_t **seqp)
-{
- /* Look up decomposition table. */
- int32_t seqidx = LOOKUPTBL(decompose, DECOMP, c);
- *seqp = SEQ(decompose) + (seqidx & ~DECOMP_COMPAT);
- return (seqidx);
-}
-
-static int32_t
-compose_char(uint32_t c,
- const struct composition **compp)
-{
- /* Look up composition table. */
- int32_t seqidx = LOOKUPTBL(compose, CANON_COMPOSE, c);
- *compp = SEQ(compose) + (seqidx & 0xffff);
- return (seqidx >> 16);
-}
-
-static nsresult
-mdn__unicode_decompose(int32_t compat, uint32_t *v, size_t vlen,
- uint32_t c, int32_t *decomp_lenp)
-{
- uint32_t *vorg = v;
- int32_t seqidx;
- const uint32_t *seq;
-
- //assert(v != nullptr && vlen >= 0 && decomp_lenp != nullptr);
-
- /*
- * First, check for Hangul.
- */
- if (SBase <= c && c < SLast) {
- int32_t idx, t_offset, v_offset, l_offset;
-
- idx = c - SBase;
- t_offset = idx % TCount;
- idx /= TCount;
- v_offset = idx % VCount;
- l_offset = idx / VCount;
- if ((t_offset == 0 && vlen < 2) || (t_offset > 0 && vlen < 3))
- return (NS_ERROR_UNORM_MOREOUTPUT);
- *v++ = LBase + l_offset;
- *v++ = VBase + v_offset;
- if (t_offset > 0)
- *v++ = TBase + t_offset;
- *decomp_lenp = v - vorg;
- return (NS_OK);
- }
-
- /*
- * Look up decomposition table. If no decomposition is defined
- * or if it is a compatibility decomosition when canonical
- * decomposition requested, return 'NS_SUCCESS_UNORM_NOTFOUND'.
- */
- seqidx = decompose_char(c, &seq);
- if (seqidx == 0 || (compat == 0 && (seqidx & DECOMP_COMPAT) != 0))
- return (NS_SUCCESS_UNORM_NOTFOUND);
-
- /*
- * Copy the decomposed sequence. The end of the sequence are
- * marked with END_BIT.
- */
- do {
- uint32_t c;
- int32_t dlen;
- nsresult r;
-
- c = *seq & ~END_BIT;
-
- /* Decompose recursively. */
- r = mdn__unicode_decompose(compat, v, vlen, c, &dlen);
- if (r == NS_OK) {
- v += dlen;
- vlen -= dlen;
- } else if (r == NS_SUCCESS_UNORM_NOTFOUND) {
- if (vlen < 1)
- return (NS_ERROR_UNORM_MOREOUTPUT);
- *v++ = c;
- vlen--;
- } else {
- return (r);
- }
-
- } while ((*seq++ & END_BIT) == 0);
-
- *decomp_lenp = v - vorg;
-
- return (NS_OK);
-}
-
-static int32_t
-mdn__unicode_iscompositecandidate(uint32_t c)
-{
- const struct composition *dummy;
-
- /* Check for Hangul */
- if ((LBase <= c && c < LBase + LCount) || (SBase <= c && c < SLast))
- return (1);
-
- /*
- * Look up composition table. If there are no composition
- * that begins with the given character, it is not a
- * composition candidate.
- */
- if (compose_char(c, &dummy) == 0)
- return (0);
- else
- return (1);
-}
-
-namespace {
-
-struct SequenceAdaptor
-{
- const composition* const mSequence;
- explicit SequenceAdaptor(const composition* aSequence) : mSequence(aSequence) {}
- uint32_t operator[](size_t aIdx) const {
- return mSequence[aIdx].c2;
- }
-};
-
-} // namespace
-
-static nsresult
-mdn__unicode_compose(uint32_t c1, uint32_t c2, uint32_t *compp)
-{
- int32_t n;
- const struct composition *cseq;
-
- //assert(compp != nullptr);
-
- /*
- * Check for Hangul.
- */
- if (LBase <= c1 && c1 < LBase + LCount &&
- VBase <= c2 && c2 < VBase + VCount) {
- /*
- * Hangul L and V.
- */
- *compp = SBase +
- ((c1 - LBase) * VCount + (c2 - VBase)) * TCount;
- return (NS_OK);
- } else if (SBase <= c1 && c1 < SLast &&
- TBase <= c2 && c2 < TBase + TCount &&
- (c1 - SBase) % TCount == 0) {
- /*
- * Hangul LV and T.
- */
- *compp = c1 + (c2 - TBase);
- return (NS_OK);
- }
-
- /*
- * Look up composition table. If the result is 0, no composition
- * is defined. Otherwise, upper 16bits of the result contains
- * the number of composition that begins with 'c1', and the lower
- * 16bits is the offset in 'compose_seq'.
- */
- if ((n = compose_char(c1, &cseq)) == 0)
- return (NS_SUCCESS_UNORM_NOTFOUND);
-
- /*
- * The composite sequences are sorted by the 2nd character 'c2'.
- * So we can use binary search.
- */
- size_t idx;
- if (mozilla::BinarySearch(SequenceAdaptor(cseq), 0, n, c2, &idx)) {
- *compp = cseq[idx].comp;
- return (NS_OK);
- }
-
- return (NS_SUCCESS_UNORM_NOTFOUND);
-}
-
-
-#define WORKBUF_SIZE 128
-#define WORKBUF_SIZE_MAX 10000
-
-typedef struct {
- int32_t cur; /* pointing now processing character */
- int32_t last; /* pointing just after the last character */
- int32_t size; /* size of UCS and CLASS array */
- uint32_t *ucs; /* UCS-4 characters */
- int32_t *cclass; /* and their canonical classes */
- uint32_t ucs_buf[WORKBUF_SIZE]; /* local buffer */
- int32_t class_buf[WORKBUF_SIZE]; /* ditto */
-} workbuf_t;
-
-static nsresult decompose(workbuf_t *wb, uint32_t c, int32_t compat);
-static void get_class(workbuf_t *wb);
-static void reorder(workbuf_t *wb);
-static void compose(workbuf_t *wb);
-static nsresult flush_before_cur(workbuf_t *wb, nsAString& aToStr);
-static void workbuf_init(workbuf_t *wb);
-static void workbuf_free(workbuf_t *wb);
-static nsresult workbuf_extend(workbuf_t *wb);
-static nsresult workbuf_append(workbuf_t *wb, uint32_t c);
-static void workbuf_shift(workbuf_t *wb, int32_t shift);
-static void workbuf_removevoid(workbuf_t *wb);
-
-
-static nsresult
-mdn_normalize(bool do_composition, bool compat,
- const nsAString& aSrcStr, nsAString& aToStr)
-{
- workbuf_t wb;
- nsresult r = NS_OK;
- /*
- * Initialize working buffer.
- */
- workbuf_init(&wb);
-
- nsAString::const_iterator start, end;
- aSrcStr.BeginReading(start);
- aSrcStr.EndReading(end);
-
- while (start != end) {
- uint32_t c;
- char16_t curChar;
-
- //assert(wb.cur == wb.last);
-
- /*
- * Get one character from 'from'.
- */
- curChar= *start++;
-
- if (NS_IS_HIGH_SURROGATE(curChar) && start != end && NS_IS_LOW_SURROGATE(*(start)) ) {
- c = SURROGATE_TO_UCS4(curChar, *start);
- ++start;
- } else {
- c = curChar;
- }
-
- /*
- * Decompose it.
- */
- if ((r = decompose(&wb, c, compat)) != NS_OK)
- break;
-
- /*
- * Get canonical class.
- */
- get_class(&wb);
-
- /*
- * Reorder & compose.
- */
- for (; wb.cur < wb.last; wb.cur++) {
- if (wb.cur == 0) {
- continue;
- } else if (wb.cclass[wb.cur] > 0) {
- /*
- * This is not a starter. Try reordering.
- * Note that characters up to it are
- * already in canonical order.
- */
- reorder(&wb);
- continue;
- }
-
- /*
- * This is a starter character, and there are
- * some characters before it. Those characters
- * have been reordered properly, and
- * ready for composition.
- */
- if (do_composition && wb.cclass[0] == 0)
- compose(&wb);
-
- /*
- * If CUR points to a starter character,
- * then process of characters before CUR are
- * already finished, because any further
- * reordering/composition for them are blocked
- * by the starter CUR points.
- */
- if (wb.cur > 0 && wb.cclass[wb.cur] == 0) {
- /* Flush everything before CUR. */
- r = flush_before_cur(&wb, aToStr);
- if (r != NS_OK)
- break;
- }
- }
- }
-
- if (r == NS_OK) {
- if (do_composition && wb.cur > 0 && wb.cclass[0] == 0) {
- /*
- * There is some characters left in WB.
- * They are ordered, but not composed yet.
- * Now CUR points just after the last character in WB,
- * and since compose() tries to compose characters
- * between top and CUR inclusive, we must make CUR
- * one character back during compose().
- */
- wb.cur--;
- compose(&wb);
- wb.cur++;
- }
- /*
- * Call this even when WB.CUR == 0, to make TO
- * NUL-terminated.
- */
- r = flush_before_cur(&wb, aToStr);
- }
-
- workbuf_free(&wb);
-
- return (r);
-}
-
-static nsresult
-decompose(workbuf_t *wb, uint32_t c, int32_t compat) {
- nsresult r;
- int32_t dec_len;
-
-again:
- r = mdn__unicode_decompose(compat, wb->ucs + wb->last,
- wb->size - wb->last, c, &dec_len);
- switch (r) {
- case NS_OK:
- wb->last += dec_len;
- return (NS_OK);
- case NS_SUCCESS_UNORM_NOTFOUND:
- return (workbuf_append(wb, c));
- case NS_ERROR_UNORM_MOREOUTPUT:
- if ((r = workbuf_extend(wb)) != NS_OK)
- return (r);
- if (wb->size > WORKBUF_SIZE_MAX) {
- // "mdn__unormalize_form*: " "working buffer too large\n"
- return (NS_ERROR_FAILURE);
- }
- goto again;
- default:
- return (r);
- }
- /* NOTREACHED */
-}
-
-static void
-get_class(workbuf_t *wb) {
- int32_t i;
-
- for (i = wb->cur; i < wb->last; i++)
- wb->cclass[i] = canonclass(wb->ucs[i]);
-}
-
-static void
-reorder(workbuf_t *wb) {
- uint32_t c;
- int32_t i;
- int32_t cclass;
-
- //assert(wb != nullptr);
-
- i = wb->cur;
- c = wb->ucs[i];
- cclass = wb->cclass[i];
-
- while (i > 0 && wb->cclass[i - 1] > cclass) {
- wb->ucs[i] = wb->ucs[i - 1];
- wb->cclass[i] =wb->cclass[i - 1];
- i--;
- wb->ucs[i] = c;
- wb->cclass[i] = cclass;
- }
-}
-
-static void
-compose(workbuf_t *wb) {
- int32_t cur;
- uint32_t *ucs;
- int32_t *cclass;
- int32_t last_class;
- int32_t nvoids;
- int32_t i;
-
- //assert(wb != nullptr && wb->cclass[0] == 0);
-
- cur = wb->cur;
- ucs = wb->ucs;
- cclass = wb->cclass;
-
- /*
- * If there are no decomposition sequence that begins with
- * the top character, composition is impossible.
- */
- if (!mdn__unicode_iscompositecandidate(ucs[0]))
- return;
-
- last_class = 0;
- nvoids = 0;
- for (i = 1; i <= cur; i++) {
- uint32_t c;
- int32_t cl = cclass[i];
-
- if ((last_class < cl || cl == 0) &&
- mdn__unicode_compose(ucs[0], ucs[i],
- &c) == NS_OK) {
- /*
- * Replace the top character with the composed one.
- */
- ucs[0] = c;
- cclass[0] = canonclass(c);
-
- cclass[i] = -1; /* void this character */
- nvoids++;
- } else {
- last_class = cl;
- }
- }
-
- /* Purge void characters, if any. */
- if (nvoids > 0)
- workbuf_removevoid(wb);
-}
-
-static nsresult
-flush_before_cur(workbuf_t *wb, nsAString& aToStr)
-{
- int32_t i;
-
- for (i = 0; i < wb->cur; i++) {
- if (!IS_IN_BMP(wb->ucs[i])) {
- aToStr.Append((char16_t)H_SURROGATE(wb->ucs[i]));
- aToStr.Append((char16_t)L_SURROGATE(wb->ucs[i]));
- } else {
- aToStr.Append((char16_t)(wb->ucs[i]));
- }
- }
-
- workbuf_shift(wb, wb->cur);
-
- return (NS_OK);
-}
-
-static void
-workbuf_init(workbuf_t *wb) {
- wb->cur = 0;
- wb->last = 0;
- wb->size = WORKBUF_SIZE;
- wb->ucs = wb->ucs_buf;
- wb->cclass = wb->class_buf;
-}
-
-static void
-workbuf_free(workbuf_t *wb) {
- if (wb->ucs != wb->ucs_buf) {
- free(wb->ucs);
- free(wb->cclass);
- }
-}
-
static nsresult
-workbuf_extend(workbuf_t *wb) {
- int32_t newsize = wb->size * 3;
-
- if (wb->ucs == wb->ucs_buf) {
- wb->ucs = (uint32_t*)moz_xmalloc(sizeof(wb->ucs[0]) * newsize);
- if (!wb->ucs)
- return NS_ERROR_OUT_OF_MEMORY;
- wb->cclass = (int32_t*)moz_xmalloc(sizeof(wb->cclass[0]) * newsize);
- if (!wb->cclass) {
- free(wb->ucs);
- wb->ucs = nullptr;
- return NS_ERROR_OUT_OF_MEMORY;
- }
- } else {
- void* buf = moz_xrealloc(wb->ucs, sizeof(wb->ucs[0]) * newsize);
- if (!buf)
- return NS_ERROR_OUT_OF_MEMORY;
- wb->ucs = (uint32_t*)buf;
- buf = moz_xrealloc(wb->cclass, sizeof(wb->cclass[0]) * newsize);
- if (!buf)
- return NS_ERROR_OUT_OF_MEMORY;
- wb->cclass = (int32_t*)buf;
- }
- return (NS_OK);
-}
-
-static nsresult
-workbuf_append(workbuf_t *wb, uint32_t c) {
- nsresult r;
-
- if (wb->last >= wb->size && (r = workbuf_extend(wb)) != NS_OK)
- return (r);
- wb->ucs[wb->last++] = c;
- return (NS_OK);
-}
-
-static void
-workbuf_shift(workbuf_t *wb, int32_t shift) {
- int32_t nmove;
-
- //assert(wb != nullptr && wb->cur >= shift);
-
- nmove = wb->last - shift;
- memmove(&wb->ucs[0], &wb->ucs[shift],
- nmove * sizeof(wb->ucs[0]));
- memmove(&wb->cclass[0], &wb->cclass[shift],
- nmove * sizeof(wb->cclass[0]));
- wb->cur -= shift;
- wb->last -= shift;
-}
-
-static void
-workbuf_removevoid(workbuf_t *wb) {
- int32_t i, j;
- int32_t last = wb->last;
-
- for (i = j = 0; i < last; i++) {
- if (wb->cclass[i] >= 0) {
- if (j < i) {
- wb->ucs[j] = wb->ucs[i];
- wb->cclass[j] = wb->cclass[i];
- }
- j++;
- }
- }
- wb->cur -= last - j;
- wb->last = j;
-}
-
-nsresult
-nsUnicodeNormalizer::NormalizeUnicodeNFD( const nsAString& aSrc, nsAString& aDest)
-{
- return mdn_normalize(false, false, aSrc, aDest);
-}
-
-nsresult
-nsUnicodeNormalizer::NormalizeUnicodeNFC( const nsAString& aSrc, nsAString& aDest)
-{
- return mdn_normalize(true, false, aSrc, aDest);
-}
-
-nsresult
-nsUnicodeNormalizer::NormalizeUnicodeNFKD( const nsAString& aSrc, nsAString& aDest)
-{
- return mdn_normalize(false, true, aSrc, aDest);
+DoNormalization(const UNormalizer2* aNorm, const nsAString& aSrc,
+ nsAString& aDest)
+{
+ UErrorCode errorCode = U_ZERO_ERROR;
+ const int32_t length = aSrc.Length();
+ const UChar* src = reinterpret_cast<const UChar*>(aSrc.BeginReading());
+ // Initial guess for a capacity that is likely to be enough for most cases.
+ int32_t capacity = length + (length >> 8) + 8;
+ do {
+ aDest.SetLength(capacity);
+ UChar* dest = reinterpret_cast<UChar*>(aDest.BeginWriting());
+ int32_t len = unorm2_normalize(aNorm, src, aSrc.Length(), dest, capacity,
+ &errorCode);
+ if (U_SUCCESS(errorCode)) {
+ aDest.SetLength(len);
+ break;
+ }
+ if (errorCode == U_BUFFER_OVERFLOW_ERROR) {
+ // Buffer wasn't big enough; adjust to the reported size and try again.
+ capacity = len;
+ errorCode = U_ZERO_ERROR;
+ continue;
+ }
+ } while (false);
+ return ICUUtils::UErrorToNsResult(errorCode);
+}
+
+nsresult
+nsUnicodeNormalizer::NormalizeUnicodeNFD(const nsAString& aSrc,
+ nsAString& aDest)
+{
+ // The unorm2_getNF*Instance functions return static singletons that should
+ // not be deleted, so we just get them once on first use.
+ static UErrorCode errorCode = U_ZERO_ERROR;
+ static const UNormalizer2* norm = unorm2_getNFDInstance(&errorCode);
+ if (U_SUCCESS(errorCode)) {
+ return DoNormalization(norm, aSrc, aDest);
+ }
+ return ICUUtils::UErrorToNsResult(errorCode);
}
-nsresult
-nsUnicodeNormalizer::NormalizeUnicodeNFKC( const nsAString& aSrc, nsAString& aDest)
+nsresult
+nsUnicodeNormalizer::NormalizeUnicodeNFC(const nsAString& aSrc,
+ nsAString& aDest)
{
- return mdn_normalize(true, true, aSrc, aDest);
+ static UErrorCode errorCode = U_ZERO_ERROR;
+ static const UNormalizer2* norm = unorm2_getNFCInstance(&errorCode);
+ if (U_SUCCESS(errorCode)) {
+ return DoNormalization(norm, aSrc, aDest);
+ }
+ return ICUUtils::UErrorToNsResult(errorCode);
}
-bool
-nsUnicodeNormalizer::Compose(uint32_t a, uint32_t b, uint32_t *ab)
+nsresult
+nsUnicodeNormalizer::NormalizeUnicodeNFKD(const nsAString& aSrc,
+ nsAString& aDest)
{
- return mdn__unicode_compose(a, b, ab) == NS_OK;
+ static UErrorCode errorCode = U_ZERO_ERROR;
+ static const UNormalizer2* norm = unorm2_getNFKDInstance(&errorCode);
+ if (U_SUCCESS(errorCode)) {
+ return DoNormalization(norm, aSrc, aDest);
+ }
+ return ICUUtils::UErrorToNsResult(errorCode);
}
-bool
-nsUnicodeNormalizer::DecomposeNonRecursively(uint32_t c, uint32_t *c1, uint32_t *c2)
+nsresult
+nsUnicodeNormalizer::NormalizeUnicodeNFKC(const nsAString& aSrc,
+ nsAString& aDest)
{
- // We can't use mdn__unicode_decompose here, because that does a recursive
- // decomposition that may yield more than two characters, but the harfbuzz
- // callback wants just a single-step decomp that is guaranteed to produce
- // no more than two characters. So we do a low-level lookup in the table
- // of decomp sequences.
- const uint32_t *seq;
- uint32_t seqidx = decompose_char(c, &seq);
- if (seqidx == 0 || ((seqidx & DECOMP_COMPAT) != 0)) {
- return false;
- }
- *c1 = *seq & ~END_BIT;
- if (*seq & END_BIT) {
- *c2 = 0;
- } else {
- *c2 = *++seq & ~END_BIT;
+ static UErrorCode errorCode = U_ZERO_ERROR;
+ static const UNormalizer2* norm = unorm2_getNFKCInstance(&errorCode);
+ if (U_SUCCESS(errorCode)) {
+ return DoNormalization(norm, aSrc, aDest);
}
- return true;
+ return ICUUtils::UErrorToNsResult(errorCode);
}
diff --git a/intl/unicharutil/nsUnicodeNormalizer.h b/intl/unicharutil/nsUnicodeNormalizer.h
index 5d9f1fe24..e92e53f21 100644
--- a/intl/unicharutil/nsUnicodeNormalizer.h
+++ b/intl/unicharutil/nsUnicodeNormalizer.h
@@ -25,13 +25,6 @@ public:
NS_IMETHOD NormalizeUnicodeNFKD( const nsAString& aSrc, nsAString& aDest) override;
NS_IMETHOD NormalizeUnicodeNFKC( const nsAString& aSrc, nsAString& aDest) override;
-#if !ENABLE_INTL_API
- // Low-level access to the composition data needed for HarfBuzz callbacks;
- // only required when ICU is not available in the build.
- static bool Compose(uint32_t a, uint32_t b, uint32_t *ab);
- static bool DecomposeNonRecursively(uint32_t comp, uint32_t *c1, uint32_t *c2);
-#endif
-
private:
virtual ~nsUnicodeNormalizer();
};
diff --git a/intl/unicharutil/nsUnicodeNormalizer_ICU.cpp b/intl/unicharutil/nsUnicodeNormalizer_ICU.cpp
deleted file mode 100644
index 6f6c3d2dd..000000000
--- a/intl/unicharutil/nsUnicodeNormalizer_ICU.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsUnicodeNormalizer.h"
-#include "ICUUtils.h"
-#include "unicode/unorm2.h"
-#include "unicode/utext.h"
-
-NS_IMPL_ISUPPORTS(nsUnicodeNormalizer, nsIUnicodeNormalizer)
-
-nsUnicodeNormalizer::nsUnicodeNormalizer()
-{
-}
-
-nsUnicodeNormalizer::~nsUnicodeNormalizer()
-{
-}
-
-static nsresult
-DoNormalization(const UNormalizer2* aNorm, const nsAString& aSrc,
- nsAString& aDest)
-{
- UErrorCode errorCode = U_ZERO_ERROR;
- const int32_t length = aSrc.Length();
- const UChar* src = reinterpret_cast<const UChar*>(aSrc.BeginReading());
- // Initial guess for a capacity that is likely to be enough for most cases.
- int32_t capacity = length + (length >> 8) + 8;
- do {
- aDest.SetLength(capacity);
- UChar* dest = reinterpret_cast<UChar*>(aDest.BeginWriting());
- int32_t len = unorm2_normalize(aNorm, src, aSrc.Length(), dest, capacity,
- &errorCode);
- if (U_SUCCESS(errorCode)) {
- aDest.SetLength(len);
- break;
- }
- if (errorCode == U_BUFFER_OVERFLOW_ERROR) {
- // Buffer wasn't big enough; adjust to the reported size and try again.
- capacity = len;
- errorCode = U_ZERO_ERROR;
- continue;
- }
- } while (false);
- return ICUUtils::UErrorToNsResult(errorCode);
-}
-
-nsresult
-nsUnicodeNormalizer::NormalizeUnicodeNFD(const nsAString& aSrc,
- nsAString& aDest)
-{
- // The unorm2_getNF*Instance functions return static singletons that should
- // not be deleted, so we just get them once on first use.
- static UErrorCode errorCode = U_ZERO_ERROR;
- static const UNormalizer2* norm = unorm2_getNFDInstance(&errorCode);
- if (U_SUCCESS(errorCode)) {
- return DoNormalization(norm, aSrc, aDest);
- }
- return ICUUtils::UErrorToNsResult(errorCode);
-}
-
-nsresult
-nsUnicodeNormalizer::NormalizeUnicodeNFC(const nsAString& aSrc,
- nsAString& aDest)
-{
- static UErrorCode errorCode = U_ZERO_ERROR;
- static const UNormalizer2* norm = unorm2_getNFCInstance(&errorCode);
- if (U_SUCCESS(errorCode)) {
- return DoNormalization(norm, aSrc, aDest);
- }
- return ICUUtils::UErrorToNsResult(errorCode);
-}
-
-nsresult
-nsUnicodeNormalizer::NormalizeUnicodeNFKD(const nsAString& aSrc,
- nsAString& aDest)
-{
- static UErrorCode errorCode = U_ZERO_ERROR;
- static const UNormalizer2* norm = unorm2_getNFKDInstance(&errorCode);
- if (U_SUCCESS(errorCode)) {
- return DoNormalization(norm, aSrc, aDest);
- }
- return ICUUtils::UErrorToNsResult(errorCode);
-}
-
-nsresult
-nsUnicodeNormalizer::NormalizeUnicodeNFKC(const nsAString& aSrc,
- nsAString& aDest)
-{
- static UErrorCode errorCode = U_ZERO_ERROR;
- static const UNormalizer2* norm = unorm2_getNFKCInstance(&errorCode);
- if (U_SUCCESS(errorCode)) {
- return DoNormalization(norm, aSrc, aDest);
- }
- return ICUUtils::UErrorToNsResult(errorCode);
-}
diff --git a/intl/unicharutil/util/ICUUtils.cpp b/intl/unicharutil/util/ICUUtils.cpp
index 2bb33d854..63d7cf453 100644
--- a/intl/unicharutil/util/ICUUtils.cpp
+++ b/intl/unicharutil/util/ICUUtils.cpp
@@ -3,7 +3,6 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifdef MOZILLA_INTERNAL_API
-#ifdef ENABLE_INTL_API
#include "ICUUtils.h"
#include "mozilla/Preferences.h"
@@ -279,6 +278,5 @@ ICUUtils::ToICUString(nsAString& aMozString, UnicodeString& aICUString)
}
#endif
-#endif /* ENABLE_INTL_API */
#endif /* MOZILLA_INTERNAL_API */
diff --git a/intl/unicharutil/util/ICUUtils.h b/intl/unicharutil/util/ICUUtils.h
index 1fa8d4cc0..9f5fbd856 100644
--- a/intl/unicharutil/util/ICUUtils.h
+++ b/intl/unicharutil/util/ICUUtils.h
@@ -6,9 +6,6 @@
#ifndef mozilla_ICUUtils_h__
#define mozilla_ICUUtils_h__
-// We only build the ICU utils if we're building ICU:
-#ifdef ENABLE_INTL_API
-
// The ICU utils implementation needs internal things like XPCOM strings and
// nsGkAtom, so we only build when included into internal libs:
#ifdef MOZILLA_INTERNAL_API
@@ -107,7 +104,6 @@ public:
#endif
};
-#endif /* ENABLE_INTL_API */
#endif /* MOZILLA_INTERNAL_API */
#endif /* mozilla_ICUUtils_h__ */
diff --git a/intl/unicharutil/util/moz.build b/intl/unicharutil/util/moz.build
index 97547536b..02f50ab0e 100644
--- a/intl/unicharutil/util/moz.build
+++ b/intl/unicharutil/util/moz.build
@@ -39,7 +39,6 @@ if CONFIG['_MSC_VER']:
CFLAGS += ['-Zl']
CXXFLAGS += ['-Zl']
-if CONFIG['ENABLE_INTL_API']:
- USE_LIBS += ['icu']
+USE_LIBS += ['icu']
DIST_INSTALL = True
diff --git a/intl/unicharutil/util/nsUnicodeProperties.cpp b/intl/unicharutil/util/nsUnicodeProperties.cpp
index 9aa5ef8e3..71f684f0e 100644
--- a/intl/unicharutil/util/nsUnicodeProperties.cpp
+++ b/intl/unicharutil/util/nsUnicodeProperties.cpp
@@ -13,30 +13,6 @@
#define UNICODE_BMP_LIMIT 0x10000
#define UNICODE_LIMIT 0x110000
-#ifndef ENABLE_INTL_API
-static const nsCharProps1&
-GetCharProps1(uint32_t aCh)
-{
- if (aCh < UNICODE_BMP_LIMIT) {
- return sCharProp1Values[sCharProp1Pages[0][aCh >> kCharProp1CharBits]]
- [aCh & ((1 << kCharProp1CharBits) - 1)];
- }
- if (aCh < (kCharProp1MaxPlane + 1) * 0x10000) {
- return sCharProp1Values[sCharProp1Pages[sCharProp1Planes[(aCh >> 16) - 1]]
- [(aCh & 0xffff) >> kCharProp1CharBits]]
- [aCh & ((1 << kCharProp1CharBits) - 1)];
- }
-
- // Default values for unassigned
- static const nsCharProps1 undefined = {
- 0, // Index to mirrored char offsets
- 0, // Hangul Syllable type
- 0 // Combining class
- };
- return undefined;
-}
-#endif
-
const nsCharProps2&
GetCharProps2(uint32_t aCh)
{
@@ -54,19 +30,8 @@ GetCharProps2(uint32_t aCh)
// Default values for unassigned
using namespace mozilla::unicode;
static const nsCharProps2 undefined = {
-#if ENABLE_INTL_API
VERTICAL_ORIENTATION_R,
XIDMOD_NOT_CHARS
-#else
- uint8_t(Script::UNKNOWN),
- PAIRED_BRACKET_TYPE_NONE,
- 0, // EastAsianWidthFWH
- HB_UNICODE_GENERAL_CATEGORY_UNASSIGNED,
- eCharType_LeftToRight,
- XIDMOD_NOT_CHARS,
- -1, // Numeric Value
- VERTICAL_ORIENTATION_R
-#endif
};
return undefined;
}
@@ -133,7 +98,6 @@ const nsIUGenCategory::nsUGenCategory sDetailedToGeneralCategory[] = {
/* SPACE_SEPARATOR */ nsIUGenCategory::kSeparator
};
-#ifdef ENABLE_INTL_API
const hb_unicode_general_category_t sICUtoHBcategory[U_CHAR_CATEGORY_COUNT] = {
HB_UNICODE_GENERAL_CATEGORY_UNASSIGNED, // U_GENERAL_OTHER_TYPES = 0,
HB_UNICODE_GENERAL_CATEGORY_UPPERCASE_LETTER, // U_UPPERCASE_LETTER = 1,
@@ -166,141 +130,6 @@ const hb_unicode_general_category_t sICUtoHBcategory[U_CHAR_CATEGORY_COUNT] = {
HB_UNICODE_GENERAL_CATEGORY_INITIAL_PUNCTUATION, // U_INITIAL_PUNCTUATION = 28,
HB_UNICODE_GENERAL_CATEGORY_FINAL_PUNCTUATION, // U_FINAL_PUNCTUATION = 29,
};
-#endif
-
-#if !ENABLE_INTL_API
-uint8_t GetGeneralCategory(uint32_t aCh) {
- return GetCharProps2(aCh).mCategory;
-}
-
-nsCharType GetBidiCat(uint32_t aCh) {
- return nsCharType(GetCharProps2(aCh).mBidiCategory);
-}
-
-int8_t GetNumericValue(uint32_t aCh) {
- return GetCharProps2(aCh).mNumericValue;
-}
-
-uint32_t
-GetMirroredChar(uint32_t aCh)
-{
- return aCh + sMirrorOffsets[GetCharProps1(aCh).mMirrorOffsetIndex];
-}
-
-bool
-HasMirroredChar(uint32_t aCh)
-{
- return GetCharProps1(aCh).mMirrorOffsetIndex != 0;
-}
-
-uint8_t
-GetCombiningClass(uint32_t aCh)
-{
- return GetCharProps1(aCh).mCombiningClass;
-}
-
-uint8_t
-GetLineBreakClass(uint32_t aCh)
-{
- return GetCharProps2(aCh).mLineBreak;
-}
-
-Script
-GetScriptCode(uint32_t aCh)
-{
- return Script(GetCharProps2(aCh).mScriptCode);
-}
-
-uint32_t
-GetScriptTagForCode(Script aScriptCode)
-{
- // this will safely return 0 for negative script codes, too :)
- if (static_cast<uint32_t>(aScriptCode) > ArrayLength(sScriptCodeToTag)) {
- return 0;
- }
- return sScriptCodeToTag[static_cast<uint32_t>(aScriptCode)];
-}
-
-PairedBracketType GetPairedBracketType(uint32_t aCh)
-{
- return PairedBracketType(GetCharProps2(aCh).mPairedBracketType);
-}
-
-uint32_t GetPairedBracket(uint32_t aCh)
-{
- return GetPairedBracketType(aCh) != PAIRED_BRACKET_TYPE_NONE
- ? GetMirroredChar(aCh) : aCh;
-}
-
-static inline uint32_t
-GetCaseMapValue(uint32_t aCh)
-{
- if (aCh < UNICODE_BMP_LIMIT) {
- return sCaseMapValues[sCaseMapPages[0][aCh >> kCaseMapCharBits]]
- [aCh & ((1 << kCaseMapCharBits) - 1)];
- }
- if (aCh < (kCaseMapMaxPlane + 1) * 0x10000) {
- return sCaseMapValues[sCaseMapPages[sCaseMapPlanes[(aCh >> 16) - 1]]
- [(aCh & 0xffff) >> kCaseMapCharBits]]
- [aCh & ((1 << kCaseMapCharBits) - 1)];
- }
- return 0;
-}
-
-uint32_t
-GetUppercase(uint32_t aCh)
-{
- uint32_t mapValue = GetCaseMapValue(aCh);
- if (mapValue & (kLowerToUpper | kTitleToUpper)) {
- return aCh ^ (mapValue & kCaseMapCharMask);
- }
- if (mapValue & kLowerToTitle) {
- return GetUppercase(aCh ^ (mapValue & kCaseMapCharMask));
- }
- return aCh;
-}
-
-uint32_t
-GetLowercase(uint32_t aCh)
-{
- uint32_t mapValue = GetCaseMapValue(aCh);
- if (mapValue & kUpperToLower) {
- return aCh ^ (mapValue & kCaseMapCharMask);
- }
- if (mapValue & kTitleToUpper) {
- return GetLowercase(aCh ^ (mapValue & kCaseMapCharMask));
- }
- return aCh;
-}
-
-uint32_t
-GetTitlecaseForLower(uint32_t aCh)
-{
- uint32_t mapValue = GetCaseMapValue(aCh);
- if (mapValue & (kLowerToTitle | kLowerToUpper)) {
- return aCh ^ (mapValue & kCaseMapCharMask);
- }
- return aCh;
-}
-
-uint32_t
-GetTitlecaseForAll(uint32_t aCh)
-{
- uint32_t mapValue = GetCaseMapValue(aCh);
- if (mapValue & (kLowerToTitle | kLowerToUpper)) {
- return aCh ^ (mapValue & kCaseMapCharMask);
- }
- if (mapValue & kUpperToLower) {
- return GetTitlecaseForLower(aCh ^ (mapValue & kCaseMapCharMask));
- }
- return aCh;
-}
-
-bool IsEastAsianWidthFWH(uint32_t aCh)
-{
- return GetCharProps2(aCh).mEastAsianWidthFWH;
-}
-#endif
#define DEFINE_BMP_1PLANE_MAPPING_GET_FUNC(prefix_) \
uint32_t Get##prefix_(uint32_t aCh) \
@@ -329,31 +158,18 @@ IsClusterExtender(uint32_t aCh, uint8_t aCategory)
}
enum HSType {
-#if ENABLE_INTL_API
HST_NONE = U_HST_NOT_APPLICABLE,
HST_L = U_HST_LEADING_JAMO,
HST_V = U_HST_VOWEL_JAMO,
HST_T = U_HST_TRAILING_JAMO,
HST_LV = U_HST_LV_SYLLABLE,
HST_LVT = U_HST_LVT_SYLLABLE
-#else
- HST_NONE = 0x00,
- HST_L = 0x01,
- HST_V = 0x02,
- HST_T = 0x04,
- HST_LV = 0x03,
- HST_LVT = 0x07
-#endif
};
static HSType
GetHangulSyllableType(uint32_t aCh)
{
-#if ENABLE_INTL_API
return HSType(u_getIntPropertyValue(aCh, UCHAR_HANGUL_SYLLABLE_TYPE));
-#else
- return HSType(GetCharProps1(aCh).mHangulType);
-#endif
}
void
diff --git a/intl/unicharutil/util/nsUnicodeProperties.h b/intl/unicharutil/util/nsUnicodeProperties.h
index ba5526a4d..ee1d77252 100644
--- a/intl/unicharutil/util/nsUnicodeProperties.h
+++ b/intl/unicharutil/util/nsUnicodeProperties.h
@@ -12,10 +12,8 @@
#include "nsUnicodeScriptCodes.h"
#include "harfbuzz/hb.h"
-#if ENABLE_INTL_API
#include "unicode/uchar.h"
#include "unicode/uscript.h"
-#endif
const nsCharProps2& GetCharProps2(uint32_t aCh);
@@ -56,7 +54,16 @@ enum XidmodType {
XIDMOD_NOT_CHARS
};
-#if ENABLE_INTL_API // ICU is available, so simply forward to its API
+enum EmojiPresentation {
+ TextOnly = 0,
+ TextDefault = 1,
+ EmojiDefault = 2
+};
+
+const uint32_t kVariationSelector15 = 0xFE0E; // text presentation
+const uint32_t kVariationSelector16 = 0xFE0F; // emoji presentation
+
+// ICU is available, so simply forward to its API
extern const hb_unicode_general_category_t sICUtoHBcategory[];
@@ -172,46 +179,18 @@ IsEastAsianWidthFWH(uint32_t aCh)
return false;
}
-#else // not ENABLE_INTL_API
-
-// Return whether the char has a mirrored-pair counterpart.
-uint32_t GetMirroredChar(uint32_t aCh);
-
-bool HasMirroredChar(uint32_t aChr);
-
-uint8_t GetCombiningClass(uint32_t aCh);
-
-// returns the detailed General Category in terms of HB_UNICODE_* values
-uint8_t GetGeneralCategory(uint32_t aCh);
-
-nsCharType GetBidiCat(uint32_t aCh);
-
-uint8_t GetLineBreakClass(uint32_t aCh);
-
-Script GetScriptCode(uint32_t aCh);
-
-uint32_t GetScriptTagForCode(Script aScriptCode);
-
-PairedBracketType GetPairedBracketType(uint32_t aCh);
-uint32_t GetPairedBracket(uint32_t aCh);
-
-/**
- * Return the numeric value of the character. The value returned is the value
- * of the Numeric_Value in field 7 of the UCD, or -1 if field 7 is empty.
- * To restrict to decimal digits, the caller should also check whether
- * GetGeneralCategory returns HB_UNICODE_GENERAL_CATEGORY_DECIMAL_NUMBER
- */
-int8_t GetNumericValue(uint32_t aCh);
-
-uint32_t GetUppercase(uint32_t aCh);
-uint32_t GetLowercase(uint32_t aCh);
-uint32_t GetTitlecaseForLower(uint32_t aCh); // maps LC to titlecase, UC unchanged
-uint32_t GetTitlecaseForAll(uint32_t aCh); // maps both UC and LC to titlecase
-
-// Return whether the char has EastAsianWidth class F or W or H.
-bool IsEastAsianWidthFWH(uint32_t aCh);
+inline EmojiPresentation
+GetEmojiPresentation(uint32_t aCh)
+{
+ if (!u_hasBinaryProperty(aCh, UCHAR_EMOJI)) {
+ return TextOnly;
+ }
-#endif // !ENABLE_INTL_API
+ if (u_hasBinaryProperty(aCh, UCHAR_EMOJI_PRESENTATION)) {
+ return EmojiDefault;
+ }
+ return TextDefault;
+}
// returns the simplified Gen Category as defined in nsIUGenCategory
inline nsIUGenCategory::nsUGenCategory GetGenCategory(uint32_t aCh) {
diff --git a/intl/unicharutil/util/nsUnicodePropertyData.cpp b/intl/unicharutil/util/nsUnicodePropertyData.cpp
index f8b5a02bc..f3d63908e 100644
--- a/intl/unicharutil/util/nsUnicodePropertyData.cpp
+++ b/intl/unicharutil/util/nsUnicodePropertyData.cpp
@@ -68,380 +68,6 @@ Standard.
#include <stdint.h>
#include "harfbuzz/hb.h"
-#if !ENABLE_INTL_API
-static const uint32_t sScriptCodeToTag[] = {
- HB_TAG('Z','y','y','y'),
- HB_TAG('Z','i','n','h'),
- HB_TAG('A','r','a','b'),
- HB_TAG('A','r','m','n'),
- HB_TAG('B','e','n','g'),
- HB_TAG('B','o','p','o'),
- HB_TAG('C','h','e','r'),
- HB_TAG('C','o','p','t'),
- HB_TAG('C','y','r','l'),
- HB_TAG('D','s','r','t'),
- HB_TAG('D','e','v','a'),
- HB_TAG('E','t','h','i'),
- HB_TAG('G','e','o','r'),
- HB_TAG('G','o','t','h'),
- HB_TAG('G','r','e','k'),
- HB_TAG('G','u','j','r'),
- HB_TAG('G','u','r','u'),
- HB_TAG('H','a','n','i'),
- HB_TAG('H','a','n','g'),
- HB_TAG('H','e','b','r'),
- HB_TAG('H','i','r','a'),
- HB_TAG('K','n','d','a'),
- HB_TAG('K','a','n','a'),
- HB_TAG('K','h','m','r'),
- HB_TAG('L','a','o','o'),
- HB_TAG('L','a','t','n'),
- HB_TAG('M','l','y','m'),
- HB_TAG('M','o','n','g'),
- HB_TAG('M','y','m','r'),
- HB_TAG('O','g','a','m'),
- HB_TAG('I','t','a','l'),
- HB_TAG('O','r','y','a'),
- HB_TAG('R','u','n','r'),
- HB_TAG('S','i','n','h'),
- HB_TAG('S','y','r','c'),
- HB_TAG('T','a','m','l'),
- HB_TAG('T','e','l','u'),
- HB_TAG('T','h','a','a'),
- HB_TAG('T','h','a','i'),
- HB_TAG('T','i','b','t'),
- HB_TAG('C','a','n','s'),
- HB_TAG('Y','i','i','i'),
- HB_TAG('T','g','l','g'),
- HB_TAG('H','a','n','o'),
- HB_TAG('B','u','h','d'),
- HB_TAG('T','a','g','b'),
- HB_TAG('B','r','a','i'),
- HB_TAG('C','p','r','t'),
- HB_TAG('L','i','m','b'),
- HB_TAG('L','i','n','b'),
- HB_TAG('O','s','m','a'),
- HB_TAG('S','h','a','w'),
- HB_TAG('T','a','l','e'),
- HB_TAG('U','g','a','r'),
- HB_TAG('H','r','k','t'),
- HB_TAG('B','u','g','i'),
- HB_TAG('G','l','a','g'),
- HB_TAG('K','h','a','r'),
- HB_TAG('S','y','l','o'),
- HB_TAG('T','a','l','u'),
- HB_TAG('T','f','n','g'),
- HB_TAG('X','p','e','o'),
- HB_TAG('B','a','l','i'),
- HB_TAG('B','a','t','k'),
- HB_TAG('B','l','i','s'),
- HB_TAG('B','r','a','h'),
- HB_TAG('C','h','a','m'),
- HB_TAG('C','i','r','t'),
- HB_TAG('C','y','r','s'),
- HB_TAG('E','g','y','d'),
- HB_TAG('E','g','y','h'),
- HB_TAG('E','g','y','p'),
- HB_TAG('G','e','o','k'),
- HB_TAG('H','a','n','s'),
- HB_TAG('H','a','n','t'),
- HB_TAG('H','m','n','g'),
- HB_TAG('H','u','n','g'),
- HB_TAG('I','n','d','s'),
- HB_TAG('J','a','v','a'),
- HB_TAG('K','a','l','i'),
- HB_TAG('L','a','t','f'),
- HB_TAG('L','a','t','g'),
- HB_TAG('L','e','p','c'),
- HB_TAG('L','i','n','a'),
- HB_TAG('M','a','n','d'),
- HB_TAG('M','a','y','a'),
- HB_TAG('M','e','r','o'),
- HB_TAG('N','k','o','o'),
- HB_TAG('O','r','k','h'),
- HB_TAG('P','e','r','m'),
- HB_TAG('P','h','a','g'),
- HB_TAG('P','h','n','x'),
- HB_TAG('P','l','r','d'),
- HB_TAG('R','o','r','o'),
- HB_TAG('S','a','r','a'),
- HB_TAG('S','y','r','e'),
- HB_TAG('S','y','r','j'),
- HB_TAG('S','y','r','n'),
- HB_TAG('T','e','n','g'),
- HB_TAG('V','a','i','i'),
- HB_TAG('V','i','s','p'),
- HB_TAG('X','s','u','x'),
- HB_TAG('Z','x','x','x'),
- HB_TAG('Z','z','z','z'),
- HB_TAG('C','a','r','i'),
- HB_TAG('J','p','a','n'),
- HB_TAG('L','a','n','a'),
- HB_TAG('L','y','c','i'),
- HB_TAG('L','y','d','i'),
- HB_TAG('O','l','c','k'),
- HB_TAG('R','j','n','g'),
- HB_TAG('S','a','u','r'),
- HB_TAG('S','g','n','w'),
- HB_TAG('S','u','n','d'),
- HB_TAG('M','o','o','n'),
- HB_TAG('M','t','e','i'),
- HB_TAG('A','r','m','i'),
- HB_TAG('A','v','s','t'),
- HB_TAG('C','a','k','m'),
- HB_TAG('K','o','r','e'),
- HB_TAG('K','t','h','i'),
- HB_TAG('M','a','n','i'),
- HB_TAG('P','h','l','i'),
- HB_TAG('P','h','l','p'),
- HB_TAG('P','h','l','v'),
- HB_TAG('P','r','t','i'),
- HB_TAG('S','a','m','r'),
- HB_TAG('T','a','v','t'),
- HB_TAG('Z','m','t','h'),
- HB_TAG('Z','s','y','m'),
- HB_TAG('B','a','m','u'),
- HB_TAG('L','i','s','u'),
- HB_TAG('N','k','g','b'),
- HB_TAG('S','a','r','b'),
- HB_TAG('B','a','s','s'),
- HB_TAG('D','u','p','l'),
- HB_TAG('E','l','b','a'),
- HB_TAG('G','r','a','n'),
- HB_TAG('K','p','e','l'),
- HB_TAG('L','o','m','a'),
- HB_TAG('M','e','n','d'),
- HB_TAG('M','e','r','c'),
- HB_TAG('N','a','r','b'),
- HB_TAG('N','b','a','t'),
- HB_TAG('P','a','l','m'),
- HB_TAG('S','i','n','d'),
- HB_TAG('W','a','r','a'),
- HB_TAG('A','f','a','k'),
- HB_TAG('J','u','r','c'),
- HB_TAG('M','r','o','o'),
- HB_TAG('N','s','h','u'),
- HB_TAG('S','h','r','d'),
- HB_TAG('S','o','r','a'),
- HB_TAG('T','a','k','r'),
- HB_TAG('T','a','n','g'),
- HB_TAG('W','o','l','e'),
- HB_TAG('H','l','u','w'),
- HB_TAG('K','h','o','j'),
- HB_TAG('T','i','r','h'),
- HB_TAG('A','g','h','b'),
- HB_TAG('M','a','h','j'),
- HB_TAG('A','h','o','m'),
- HB_TAG('H','a','t','r'),
- HB_TAG('M','o','d','i'),
- HB_TAG('M','u','l','t'),
- HB_TAG('P','a','u','c'),
- HB_TAG('S','i','d','d')
-};
-#endif
-
-#if !ENABLE_INTL_API
-static const int16_t sMirrorOffsets[] = {
- 0,
- 1,
- -1,
- 2,
- -2,
- 16,
- -16,
- 3,
- -3,
- 2016,
- 138,
- 1824,
- 2104,
- 2108,
- 2106,
- -138,
- 8,
- 7,
- -8,
- -7,
- -1824,
- -2016,
- -2104,
- -2106,
- -2108
-};
-#endif
-
-
-#if !ENABLE_INTL_API
-#define kCharProp1MaxPlane 1
-#define kCharProp1IndexBits 11
-#define kCharProp1CharBits 5
-static const uint8_t sCharProp1Planes[1] = {1};
-
-static const uint8_t sCharProp1Pages[2][2048] = {
- {0,1,2,2,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,5,6,7,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,9,10,11,0,12,0,13,14,0,0,15,16,17,18,19,0,0,0,0,20,21,22,23,0,0,0,0,24,0,25,26,0,0,25,27,0,0,25,27,0,0,25,27,0,0,25,27,0,0,0,27,0,0,0,28,0,0,25,27,0,0,0,27,0,0,0,29,0,0,30,31,0,0,32,33,0,34,35,0,36,37,0,38,0,0,39,0,0,40,0,0,0,41,41,41,42,42,43,44,44,0,0,0,0,0,0,0,0,0,0,45,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,46,0,0,0,47,47,0,0,0,0,48,0,0,0,0,0,0,49,0,0,0,50,0,0,0,0,0,0,51,0,0,52,0,53,0,0,0,54,55,56,0,57,0,58,0,59,0,0,0,0,60,61,0,0,0,0,0,0,62,63,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,65,66,67,0,68,69,0,0,0,0,0,0,0,0,70,71,72,73,74,75,76,77,78,79,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,80,0,0,81,82,0,0,0,0,0,0,0,0,0,0,0,0,83,84,85,86,0,87,0,88,89,90,91,92,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,93,0,0,0,94,0,0,0,95,96,97,0,0,0,0,0,0,0,0,0,0,0,0,0,0,98,99,0,0,100,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,101,102,0,0,103,0,0,0,0,0,0,0,0,104,0,0,0,0,0,55,105,0,106,107,108,0,109,110,0,0,0,0,0,0,111,112,113,0,0,0,0,0,0,0,27,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,120,114,115,116,117,118,119,121,122,123,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,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,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,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,124,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,125,126,127,0,0,0,0,1,2,128,129,0,0,0,0},
- {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,130,0,0,0,0,0,0,0,131,0,0,0,132,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,133,134,0,0,0,0,0,135,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,104,94,0,136,0,0,137,138,0,109,0,0,139,0,0,140,0,0,0,0,0,141,0,25,27,142,0,0,0,0,0,0,0,0,0,0,143,0,0,0,0,0,0,94,144,0,0,94,0,0,0,145,0,0,0,146,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,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,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,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,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,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,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,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,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,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,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,147,0,148,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,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,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,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,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,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,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,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,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,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,0,0,0,0,0,0,0,0,0,0,149,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,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,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,150,151,152,0,0,0,0,153,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,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,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,154,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,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,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}
-};
-
-static const nsCharProps1 sCharProp1Values[155][32] = {
- {{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,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}, {1,0,0}, {2,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}, {3,0,0}, {0,0,0}, {4,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,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {3,0,0}, {0,0,0}, {4,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}, {5,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}, {6,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,232}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,232}, {0,0,216}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220},},
- {{0,0,220}, {0,0,202}, {0,0,202}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,202}, {0,0,202}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,240}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,232}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,233}, {0,0,234}, {0,0,234}, {0,0,233},},
- {{0,0,234}, {0,0,234}, {0,0,233}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,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,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,222}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230},},
- {{0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,222}, {0,0,228}, {0,0,230}, {0,0,10}, {0,0,11}, {0,0,12}, {0,0,13}, {0,0,14}, {0,0,15}, {0,0,16}, {0,0,17}, {0,0,18}, {0,0,19}, {0,0,19}, {0,0,20}, {0,0,21}, {0,0,22}, {0,0,0}, {0,0,23},},
- {{0,0,0}, {0,0,24}, {0,0,25}, {0,0,0}, {0,0,230}, {0,0,220}, {0,0,0}, {0,0,18}, {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,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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,30}, {0,0,31}, {0,0,32}, {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,27}, {0,0,28}, {0,0,29}, {0,0,30}, {0,0,31}, {0,0,32}, {0,0,33}, {0,0,34}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220},},
- {{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,35}, {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,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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,230},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {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,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,36}, {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,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,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,220}, {0,0,230},},
- {{0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {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,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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {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,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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,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,0}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,0}, {0,0,0}, {0,0,0}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,27}, {0,0,28}, {0,0,29}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230},},
- {{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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,7}, {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,9}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,9}, {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,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,9}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,84}, {0,0,91}, {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,9}, {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,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,0}, {0,0,0}, {0,0,0}, {0,0,103}, {0,0,103}, {0,0,9}, {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,107}, {0,0,107}, {0,0,107}, {0,0,107}, {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,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,0}, {0,0,0}, {0,0,118}, {0,0,118}, {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,122}, {0,0,122}, {0,0,122}, {0,0,122}, {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,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,0}, {0,0,0}, {0,0,220}, {0,0,220}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,220}, {0,0,0}, {0,0,220}, {0,0,0}, {0,0,216}, {1,0,0}, {2,0,0}, {1,0,0}, {2,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,129}, {0,0,130}, {0,0,0}, {0,0,132}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,130}, {0,0,130}, {0,0,130}, {0,0,130}, {0,0,0}, {0,0,0},},
- {{0,0,130}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,9}, {0,0,0}, {0,0,230}, {0,0,230}, {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,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,220}, {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,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,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,7}, {0,0,0}, {0,0,9}, {0,0,9}, {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,220}, {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,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0},},
- {{0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0},},
- {{0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0},},
- {{0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,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}, {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,230}, {0,0,230}, {0,0,230},},
- {{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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,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,0}, {0,0,0}, {0,0,0}, {0,0,9}, {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,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,9}, {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,230}, {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,228}, {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,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,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,222}, {0,0,230}, {0,0,220}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,220}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,9}, {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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,220},},
- {{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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {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,0,0}, {0,0,7}, {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,9}, {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,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,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,0,0}, {0,0,9}, {0,0,9}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,7}, {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,9}, {0,0,9}, {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,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,7}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,1}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220},},
- {{0,0,230}, {0,0,0}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,220}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,230}, {0,0,234}, {0,0,214}, {0,0,220}, {0,0,202}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,233}, {0,0,220}, {0,0,230}, {0,0,220},},
- {{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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,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,0,0}, {2,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,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}, {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,0,0}, {2,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,0,0}, {2,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,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,230}, {0,0,230}, {0,0,1}, {0,0,1}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,0}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,1}, {0,0,1}, {0,0,230}, {0,0,220}, {0,0,230}, {0,0,1}, {0,0,1}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {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,0,0}, {0,0,0}, {7,0,0}, {7,0,0}, {7,0,0}, {8,0,0}, {8,0,0}, {8,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {9,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,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}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,0}, {0,0,0}, {0,0,0}, {10,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,0,0}, {2,0,0}, {1,0,0}, {2,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,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0},},
- {{1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {11,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,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {12,0,0}, {0,0,0}, {13,0,0}, {14,0,0}, {0,0,0}, {14,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,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}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {15,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0},},
- {{1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {16,0,0}, {16,0,0}, {16,0,0}, {0,0,0}, {17,0,0}, {17,0,0}, {0,0,0}, {0,0,0}, {18,0,0}, {18,0,0}, {18,0,0}, {19,0,0}, {19,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,0,0}, {2,0,0}, {1,0,0}, {2,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,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,0,0}, {2,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,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,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,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,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {3,0,0}, {0,0,0}, {4,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0},},
- {{0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,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}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {7,0,0}, {1,0,0}, {2,0,0}, {8,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,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,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}, {20,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,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,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,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,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {21,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,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,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,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}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0},},
- {{2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0},},
- {{2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {22,0,0}, {0,0,0},},
- {{0,0,0}, {0,0,0}, {0,0,0}, {23,0,0}, {24,0,0}, {23,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,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,0,0}, {2,0,0}, {1,0,0}, {2,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,230}, {0,0,230}, {0,0,230}, {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,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,0}, {0,0,0}, {0,0,0}, {0,0,9},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230},},
- {{0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {1,0,0}, {2,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,0,0}, {2,0,0}, {0,0,0}, {0,0,0},},
- {{1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,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,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,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,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,218}, {0,0,228}, {0,0,232}, {0,0,222}, {0,0,224}, {0,0,224}, {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,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,8}, {0,0,8}, {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,230}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,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,230}, {0,0,230},},
- {{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,230}, {0,0,230}, {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,9}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,220}, {0,0,220}, {0,0,220}, {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,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,9}, {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,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,0}, {0,1,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}, {0,0,0}, {0,0,7}, {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,9}, {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,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,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230},},
- {{0,0,0}, {0,0,230}, {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,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,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,9}, {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,3,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,3,0}, {0,7,0}, {0,7,0}, {0,7,0},},
- {{0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,3,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0},},
- {{0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,3,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0},},
- {{0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,3,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0},},
- {{0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,3,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0},},
- {{0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,3,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0},},
- {{0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,3,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0}, {0,7,0},},
- {{0,7,0}, {0,7,0}, {0,7,0}, {0,7,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,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0},},
- {{0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,2,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0},},
- {{0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,0}, {0,4,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}, {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,26}, {0,0,0},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,230}, {0,0,230}, {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,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}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {1,0,0}, {2,0,0}, {0,0,0},},
- {{0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {1,0,0}, {2,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,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}, {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}, {3,0,0}, {0,0,0}, {4,0,0}, {0,0,0}, {1,0,0},},
- {{2,0,0}, {0,0,0}, {1,0,0}, {2,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,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}, {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,220}, {0,0,0}, {0,0,0},},
- {{0,0,220}, {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,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,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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,220}, {0,0,0}, {0,0,230}, {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,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,230}, {0,0,1}, {0,0,220}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,9},},
- {{0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,220}, {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,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,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,9}, {0,0,7}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,230}, {0,0,230}, {0,0,230}, {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,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,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,9}, {0,0,9}, {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,9}, {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,7}, {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,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,9}, {0,0,7}, {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,7}, {0,0,9}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,9}, {0,0,7}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0},},
- {{0,0,7}, {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,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,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,9}, {0,0,7}, {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,9}, {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,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}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,1}, {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,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,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,1}, {0,0,0},},
- {{0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,216}, {0,0,216}, {0,0,1}, {0,0,1}, {0,0,1}, {0,0,0}, {0,0,0}, {0,0,0}, {0,0,226}, {0,0,216}, {0,0,216}, {0,0,216}, {0,0,216}, {0,0,216}, {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,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220},},
- {{0,0,220}, {0,0,220}, {0,0,220}, {0,0,0}, {0,0,0}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,230}, {0,0,220}, {0,0,220}, {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,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,230}, {0,0,230}, {0,0,230}, {0,0,230}, {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,230}, {0,0,230}, {0,0,230}, {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,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,0}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {0,0,220}, {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},}
-};
-#endif
-
-#if ENABLE_INTL_API
#define kCharProp2MaxPlane 16
#define kCharProp2IndexBits 9
#define kCharProp2CharBits 7
@@ -674,1033 +300,6 @@ static const nsCharProps2 sCharProp2Values[216][128] = {
{{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10}},
{{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,10},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12},{1,12}}
};
-#endif
-
-#if !ENABLE_INTL_API
-#define kCharProp2MaxPlane 16
-#define kCharProp2IndexBits 12
-#define kCharProp2CharBits 4
-static const uint8_t sCharProp2Planes[16] = {1,2,3,4,4,4,4,4,4,4,4,4,4,5,6,6};
-
-static const uint16_t sCharProp2Pages[7][4096] = {
- {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,16,16,17,18,16,16,19,20,21,22,23,24,25,26,27,16,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,59,59,60,60,60,61,61,62,63,63,63,64,63,63,63,63,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,81,82,83,84,85,86,81,81,81,81,87,88,89,90,91,92,93,94,81,81,81,95,95,96,97,98,99,100,101,102,103,104,105,106,107,108,108,108,108,109,110,111,111,112,113,114,115,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,194,195,196,197,198,198,199,200,201,202,203,204,198,198,205,206,207,208,209,210,211,212,213,214,215,216,217,218,198,198,219,219,220,221,222,223,224,225,226,227,228,228,229,230,230,231,232,232,232,232,232,233,234,235,235,235,236,237,237,237,237,237,238,238,238,238,239,240,238,238,239,238,238,241,242,243,238,238,238,242,238,238,238,244,245,246,238,247,248,248,248,248,248,249,250,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,251,252,251,253,254,255,255,255,255,256,257,258,259,260,261,262,263,264,265,266,266,267,268,269,270,271,272,273,274,275,275,276,275,275,277,275,275,278,251,251,251,251,279,280,281,282,283,284,285,286,287,288,288,289,288,290,291,292,292,293,294,295,295,295,296,297,298,299,299,300,301,198,198,198,198,302,303,303,304,305,306,307,308,309,310,311,312,313,313,314,315,316,316,317,318,319,320,321,322,198,198,198,198,323,324,325,326,37,37,327,328,329,330,331,332,37,333,334,335,336,337,338,339,16,16,16,16,16,16,16,16,16,340,16,16,16,16,16,341,342,343,342,342,343,344,342,345,346,346,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,379,382,383,384,385,386,387,388,389,390,391,392,393,394,390,390,395,390,396,397,398,399,400,400,400,401,402,403,390,404,405,406,407,408,402,402,409,410,411,410,412,413,414,415,416,416,416,416,417,418,419,419,419,419,420,419,419,421,419,422,423,424,425,426,427,428,429,430,402,431,432,402,433,434,402,435,436,437,438,439,440,441,442,402,402,402,402,443,444,445,446,447,379,379,448,390,449,390,450,450,450,450,450,450,450,450,450,450,450,450,450,450,450,450,390,390,390,390,390,390,390,390,451,452,390,390,390,453,390,454,455,390,390,390,390,390,390,456,390,390,390,390,390,455,390,390,379,457,402,390,458,459,379,460,379,461,379,462,463,464,465,410,466,466,467,468,468,469,470,471,472,472,472,472,472,472,473,474,475,475,476,477,477,477,478,479,238,480,481,481,481,481,482,482,483,484,485,486,487,198,198,198,488,489,488,488,488,488,488,490,491,491,491,491,491,491,491,491,491,491,491,491,491,492,410,493,494,495,496,497,498,499,500,499,501,502,503,504,505,504,506,507,508,509,510,511,512,512,513,512,514,515,509,516,517,517,518,519,520,521,522,523,524,525,520,526,522,523,523,527,528,529,529,530,531,531,531,531,531,532,523,533,523,523,523,523,523,534,523,535,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,537,402,402,402,402,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,537,538,538,539,540,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,539,541,542,542,542,543,544,544,545,546,546,546,546,546,546,546,546,546,546,546,546,546,546,546,546,547,546,548,198,61,61,549,550,61,551,552,552,552,552,553,554,42,555,556,557,558,558,558,559,560,561,562,563,198,198,198,564,565,566,567,568,569,569,569,570,571,572,572,573,574,575,576,577,578,579,580,581,582,583,232,584,585,586,586,587,588,589,590,591,592,592,593,594,595,596,219,597,598,598,598,599,600,601,602,603,604,605,481,606,606,607,608,609,609,609,609,609,610,610,611,612,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,617,615,613,614,615,616,615,618,235,619,237,237,620,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,621,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,624,625,626,623,623,623,627,623,623,623,623,623,623,628,538,538,629,630,631,632,633,634,634,634,634,634,634,635,636,637,634,634,634,634,634,634,634,634,634,634,634,634,634,634,634,634,634,634,634,634,634,638,111,634,634,634,634,639,634,634,640,198,198,641,642,643,644,645,646,647,648,649,634,634,634,634,634,634,634,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666},
- {667,668,669,670,671,671,198,198,668,668,668,668,668,668,668,672,673,674,674,675,676,676,676,677,678,679,680,198,198,400,400,681,198,198,198,198,198,198,198,198,682,683,684,684,684,685,686,687,688,688,689,690,691,692,692,693,694,695,696,696,697,698,198,198,699,699,700,701,701,702,702,702,703,704,705,198,198,198,198,198,706,706,707,708,708,708,709,198,198,198,198,198,198,198,198,198,710,710,710,710,710,710,710,710,710,710,710,710,710,710,710,710,710,710,710,711,710,712,713,198,198,198,198,198,198,198,198,198,714,715,715,716,717,718,719,720,721,722,723,108,108,108,724,725,726,727,728,729,108,108,108,108,730,730,731,732,733,734,733,733,735,736,737,738,739,740,741,742,743,744,108,108,745,746,747,748,749,749,749,750,751,752,753,754,755,756,757,108,108,108,108,108,758,758,758,758,759,108,108,108,760,760,760,761,762,762,762,763,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,764,765,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,766,767,767,768,769,770,771,772,773,774,774,775,776,777,778,779,780,781,782,783,784,785,785,786,787,788,788,789,790,791,792,793,794,795,796,797,198,198,198,198,798,799,800,801,801,802,803,804,805,806,807,808,809,810,811,812,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,813,813,813,814,815,816,198,198,198,198,198,198,198,198,198,198,817,817,818,819,820,821,410,410,822,822,822,823,824,825,198,198,826,826,827,828,829,198,198,198,830,831,832,833,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,834,834,835,835,836,837,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,838,838,838,839,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,840,841,198,198,198,198,198,198,842,842,842,842,842,842,843,844,840,840,840,840,840,840,840,840,840,840,840,840,845,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,846,847,846,846,848,846,846,846,846,846,846,846,846,846,846,846,846,846,846,849,846,846,846,846,846,846,846,846,846,846,850,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,851,852,851,851,851,851,851,851,851,853,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,552,854,855,856,857,198,198,198,198,198,198,858,859,860,861,861,861,862,863,864,865,866,861,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,867,867,867,867,868,869,870,871,872,873,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,874,410,410,410,410,410,410,410,410,410,410,410,410,410,410,410,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,875,875,875,875,875,875,876,877,878,879,880,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,881,881,881,881,881,881,881,881,881,881,881,881,881,881,881,882,881,881,883,881,881,884,885,886,887,881,888,889,890,881,891,410,892,892,892,892,893,198,198,198,198,198,198,198,198,198,198,198,402,402,402,402,402,894,895,896,198,198,198,198,198,198,198,198,897,898,899,900,901,902,903,897,904,905,906,907,908,897,898,899,909,910,899,911,912,913,914,897,915,899,897,898,899,900,901,899,903,897,904,914,897,915,899,897,898,899,916,897,917,918,919,920,899,921,897,922,923,924,925,899,926,897,927,899,928,929,930,931,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,932,933,933,933,934,933,933,935,936,937,938,939,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,940,940,940,940,940,940,940,940,940,940,940,940,941,942,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,943,634,944,945,946,947,948,949,950,951,952,951,111,111,111,953,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,108,954,954,955,954,954,954,954,954,954,956,957,958,958,958,954,959,960,416,961,416,416,962,963,962,962,964,410,410,410,410,965,966,967,523,523,968,969,970,410,410,410,410,410,410,410,410,410,410,954,954,954,954,954,954,954,954,954,971,954,972,954,954,954,973,954,954,954,954,954,954,954,954,954,954,974,975,954,954,954,954,976,977,978,979,980,954,954,981,954,954,982,954,954,983,954,984,954,954,954,954,954,402,402,985,954,954,954,954,954,986,987,956,402,402,402,402,402,402,402,988,402,402,402,402,402,989,410,410,679,379,379,379,990,991,379,379,990,379,992,198,198,198,198,198,198,993,198,198,198,198,198,198,994,198,198,198,995,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198},
- {536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,996,538,538,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,997,536,536,536,536,536,536,536,536,536,536,536,536,536,998,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,536,999,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,623,627,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,1000},
- {538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,538,1000},
- {198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198},
- {1001,198,1002,1002,1002,1002,1002,1003,198,198,198,198,198,198,198,198,642,642,642,642,642,642,642,642,642,642,642,642,642,642,642,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198,198},
- {622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,622,1004}
-};
-
-static const nsCharProps2 sCharProp2Values[1005][16] = {
- {{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,8,8,-1,1,4},{0,0,0,0,7,8,-1,1,17},{0,0,0,0,8,8,-1,1,6},{0,0,0,0,9,8,-1,1,6},{0,0,0,0,7,8,-1,1,10},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9}},
- {{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,7,12,-1,1,9},{0,0,0,0,7,12,-1,1,9},{0,0,0,0,7,12,-1,1,9},{0,0,0,0,8,12,-1,1,9}},
- {{0,0,0,29,9,8,-1,1,26},{0,0,0,21,10,8,-1,1,11},{0,0,0,21,10,8,-1,1,23},{0,0,0,21,4,8,-1,1,2},{0,0,0,23,4,8,-1,1,22},{0,0,0,21,4,8,-1,1,21},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,1,-1,1,23},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,36},{0,0,0,21,10,8,-1,1,2},{0,0,0,25,3,8,-1,1,22},{0,0,0,21,6,8,-1,1,16},{0,0,0,17,3,1,-1,1,13},{0,0,0,21,6,1,-1,1,16},{0,0,0,21,6,8,-1,1,27}},
- {{0,0,0,13,2,0,0,1,19},{0,0,0,13,2,0,1,1,19},{0,0,0,13,2,0,2,1,19},{0,0,0,13,2,0,3,1,19},{0,0,0,13,2,0,4,1,19},{0,0,0,13,2,0,5,1,19},{0,0,0,13,2,0,6,1,19},{0,0,0,13,2,0,7,1,19},{0,0,0,13,2,0,8,1,19},{0,0,0,13,2,0,9,1,19},{0,0,0,21,6,1,-1,1,16},{0,0,0,21,10,8,-1,1,16},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,11}},
- {{0,0,0,21,10,8,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{0,1,0,22,10,8,-1,1,20},{0,0,0,21,10,8,-1,1,22},{0,2,0,18,10,8,-1,1,36},{0,0,0,24,10,8,-1,1,2},{0,0,0,16,10,0,-1,1,2}},
- {{0,0,0,24,10,8,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{0,1,0,22,10,8,-1,1,20},{0,0,0,25,10,8,-1,1,4},{0,2,0,18,10,8,-1,1,8},{0,0,0,25,10,8,-1,1,2},{0,0,0,0,18,12,-1,1,9}},
- {{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,7,8,-1,1,29},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9}},
- {{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9},{0,0,0,0,18,12,-1,1,9}},
- {{0,0,0,29,6,9,-1,1,12},{0,0,0,21,10,8,-1,1,20},{0,0,0,23,4,8,-1,1,21},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,26,10,8,-1,1,2},{0,0,0,21,10,8,-1,0,1},{0,0,0,24,10,9,-1,1,1},{0,0,0,26,10,8,-1,0,2},{25,0,0,7,0,9,-1,1,1},{0,0,0,20,10,8,-1,1,23},{0,0,0,25,10,8,-1,1,2},{0,0,0,1,18,10,-1,1,4},{0,0,0,26,10,8,-1,0,2},{0,0,0,24,10,9,-1,1,2}},
- {{0,0,0,26,4,8,-1,1,21},{0,0,0,25,4,8,-1,0,22},{0,0,0,15,2,9,2,1,1},{0,0,0,15,2,9,3,1,1},{0,0,0,24,10,9,-1,1,5},{0,0,0,5,0,9,-1,1,2},{0,0,0,21,10,8,-1,1,1},{0,0,0,21,10,1,-1,1,1},{0,0,0,24,10,9,-1,1,1},{0,0,0,15,2,9,1,1,1},{25,0,0,7,0,9,-1,1,1},{0,0,0,19,10,8,-1,1,23},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,21,10,8,-1,1,20}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{0,0,0,25,10,8,-1,0,1},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{0,0,0,25,10,8,-1,0,1},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,9,-1,1,2}},
- {{25,0,0,5,0,9,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,11,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,9,-1,1,2}},
- {{25,0,0,5,0,3,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,0,-1,1,2}},
- {{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,0,-1,1,2}},
- {{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,7,0,4,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2}},
- {{25,0,0,7,0,3,-1,1,2},{25,0,0,7,0,3,-1,1,2},{25,0,0,7,0,3,-1,1,2},{25,0,0,7,0,3,-1,1,2},{25,0,0,9,0,9,-1,1,2},{25,0,0,8,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,9,0,9,-1,1,2},{25,0,0,8,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,9,0,9,-1,1,2},{25,0,0,8,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2}},
- {{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,9,-1,1,2},{25,0,0,8,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2}},
- {{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2}},
- {{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,4,-1,1,2}},
- {{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2}},
- {{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2}},
- {{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2}},
- {{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,7,0,2,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,3,-1,1,2}},
- {{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{0,0,0,6,10,3,-1,1,2},{0,0,0,6,10,3,-1,1,2},{0,0,0,6,0,0,-1,1,2},{0,0,0,6,0,0,-1,1,2},{0,0,0,6,0,3,-1,1,2},{0,0,0,6,0,3,-1,1,2},{0,0,0,6,0,3,-1,1,2}},
- {{0,0,0,6,0,3,-1,1,2},{0,0,0,6,0,3,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,6,10,3,-1,1,2},{0,0,0,6,10,3,-1,1,1},{0,0,0,6,10,3,-1,1,5},{0,0,0,6,10,3,-1,1,1},{0,0,0,6,10,3,-1,1,1},{0,0,0,6,10,3,-1,1,1},{0,0,0,6,10,3,-1,1,5},{0,0,0,6,10,3,-1,1,1},{0,0,0,6,10,3,-1,1,2},{0,0,0,6,10,3,-1,1,2}},
- {{0,0,0,6,0,3,-1,1,1},{0,0,0,6,0,3,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,9,-1,1,1},{0,0,0,24,10,9,-1,1,1},{0,0,0,24,10,9,-1,1,1},{0,0,0,24,10,9,-1,1,1},{0,0,0,24,10,9,-1,1,2},{0,0,0,24,10,9,-1,1,1},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,5}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{5,0,0,24,10,8,-1,0,2},{5,0,0,24,10,8,-1,0,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,6,0,3,-1,1,2},{0,0,0,24,10,8,-1,1,2}},
- {{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2}},
- {{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,0,-1,1,9}},
- {{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9}},
- {{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,3,-1,1,9}},
- {{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9}},
- {{1,0,0,12,17,9,-1,1,9},{1,0,0,12,17,9,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,9,-1,1,9},{1,0,0,12,17,9,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,10,-1,1,12}},
- {{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,2,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,12},{1,0,0,12,17,3,-1,1,12},{1,0,0,12,17,3,-1,1,12},{1,0,0,12,17,3,-1,1,12}},
- {{1,0,0,12,17,3,-1,1,12},{1,0,0,12,17,3,-1,1,12},{1,0,0,12,17,3,-1,1,12},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9}},
- {{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{0,0,0,6,10,9,-1,1,2},{14,0,0,24,10,1,-1,1,2},{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{14,0,0,6,0,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{0,0,0,21,10,9,-1,1,16},{14,0,0,9,0,4,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{14,0,0,24,10,9,-1,1,2},{0,0,0,24,10,9,-1,1,2},{14,0,0,9,0,0,-1,1,2},{0,0,0,21,10,9,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2}},
- {{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,3,-1,1,2}},
- {{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,3,-1,1,2},{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2}},
- {{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2}},
- {{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,4,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,25,10,8,-1,1,2},{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,9,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2}},
- {{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2}},
- {{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2}},
- {{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2}},
- {{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,26,0,8,-1,1,2},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,11,17,8,-1,1,9},{8,0,0,11,17,8,-1,1,9},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2}},
- {{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2}},
- {{8,0,0,9,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2}},
- {{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2}},
- {{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2}},
- {{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{3,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{3,0,0,6,0,0,-1,1,2},{3,0,0,21,0,8,-1,1,2},{3,0,0,21,0,8,-1,1,2},{3,0,0,21,0,8,-1,1,2},{3,0,0,21,0,8,-1,1,2},{3,0,0,21,0,8,-1,1,2},{3,0,0,21,0,8,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2}},
- {{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2}},
- {{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,0,-1,1,2},{3,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,21,0,8,-1,1,16},{3,0,0,17,10,1,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{3,0,0,26,10,8,-1,1,2},{3,0,0,26,10,8,-1,1,2},{3,0,0,23,4,8,-1,1,22}},
- {{103,0,0,2,1,12,-1,1,0},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9}},
- {{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,4,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9}},
- {{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,0,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,17,1,8,-1,1,4},{19,0,0,12,17,2,-1,1,9}},
- {{19,0,0,21,1,8,-1,1,2},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,2,-1,1,9},{19,0,0,21,1,8,-1,1,2},{19,0,0,12,17,2,-1,1,9},{19,0,0,12,17,4,-1,1,9},{19,0,0,21,1,8,-1,1,11},{19,0,0,12,17,4,-1,1,9},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38}},
- {{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,7,1,0,-1,1,38},{19,0,0,21,1,1,-1,1,2},{19,0,0,21,1,1,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{2,0,0,1,5,8,-1,1,2},{2,0,0,1,5,8,-1,1,2},{2,0,0,1,5,8,-1,1,2},{2,0,0,1,5,8,-1,1,2},{2,0,0,1,5,8,-1,1,2},{0,0,0,1,5,8,-1,1,2},{2,0,0,25,10,8,-1,1,2},{2,0,0,25,10,8,-1,1,2},{2,0,0,25,13,8,-1,1,2},{2,0,0,21,4,8,-1,1,21},{2,0,0,21,4,8,-1,1,21},{2,0,0,23,13,8,-1,1,21},{0,0,0,21,6,8,-1,1,16},{2,0,0,21,13,8,-1,1,16},{2,0,0,26,10,8,-1,1,2},{2,0,0,26,10,8,-1,1,2}},
- {{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{0,0,0,21,13,8,-1,1,11},{0,0,0,1,13,10,-1,1,9},{103,0,0,2,13,12,-1,1,0},{2,0,0,21,13,8,-1,1,11},{0,0,0,21,13,8,-1,1,11}},
- {{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2}},
- {{0,0,0,6,13,7,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9}},
- {{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{1,0,0,12,17,0,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9}},
- {{2,0,0,13,5,0,0,1,19},{2,0,0,13,5,0,1,1,19},{2,0,0,13,5,0,2,1,19},{2,0,0,13,5,0,3,1,19},{2,0,0,13,5,0,4,1,19},{2,0,0,13,5,0,5,1,19},{2,0,0,13,5,0,6,1,19},{2,0,0,13,5,0,7,1,19},{2,0,0,13,5,0,8,1,19},{2,0,0,13,5,0,9,1,19},{2,0,0,21,4,8,-1,1,21},{2,0,0,21,5,8,-1,1,19},{2,0,0,21,5,8,-1,1,19},{2,0,0,21,13,8,-1,1,2},{2,0,0,7,13,4,-1,1,2},{2,0,0,7,13,4,-1,1,2}},
- {{1,0,0,12,17,0,-1,1,9},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,11,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2}},
- {{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,4,-1,1,2},{2,0,0,7,13,0,-1,1,2}},
- {{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,21,13,8,-1,1,11},{2,0,0,7,13,0,-1,1,2},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{0,0,0,1,5,8,-1,1,2},{2,0,0,26,10,8,-1,1,2},{2,0,0,12,17,2,-1,1,9}},
- {{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,6,13,0,-1,1,2},{2,0,0,6,13,0,-1,1,2},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,26,10,8,-1,1,2},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2}},
- {{2,0,0,13,2,0,0,1,19},{2,0,0,13,2,0,1,1,19},{2,0,0,13,2,0,2,1,19},{2,0,0,13,2,0,3,1,19},{2,0,0,13,2,0,4,1,19},{2,0,0,13,2,0,5,1,19},{2,0,0,13,2,0,6,1,19},{2,0,0,13,2,0,7,1,19},{2,0,0,13,2,0,8,1,19},{2,0,0,13,2,0,9,1,19},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,26,13,1,-1,1,2},{2,0,0,26,13,1,-1,1,2},{2,0,0,7,13,0,-1,1,2}},
- {{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{34,0,0,21,13,8,-1,1,2},{103,0,0,2,13,12,-1,1,0},{34,0,0,1,13,8,-1,1,2}},
- {{34,0,0,7,13,6,-1,1,2},{34,0,0,12,17,6,-1,1,9},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2}},
- {{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2}},
- {{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9}},
- {{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{34,0,0,12,17,6,-1,1,9},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2},{34,0,0,7,13,6,-1,1,2}},
- {{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2}},
- {{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,7,13,0,-1,1,2},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9},{37,0,0,12,17,0,-1,1,9}},
- {{37,0,0,12,17,0,-1,1,9},{37,0,0,7,13,0,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{87,0,0,13,1,6,0,1,19},{87,0,0,13,1,6,1,1,19},{87,0,0,13,1,6,2,1,19},{87,0,0,13,1,6,3,1,19},{87,0,0,13,1,6,4,1,19},{87,0,0,13,1,6,5,1,19},{87,0,0,13,1,6,6,1,19},{87,0,0,13,1,6,7,1,19},{87,0,0,13,1,6,8,1,19},{87,0,0,13,1,6,9,1,19},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2}},
- {{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2}},
- {{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,7,1,6,-1,1,2},{87,0,0,12,17,6,-1,1,9},{87,0,0,12,17,6,-1,1,9},{87,0,0,12,17,6,-1,1,9},{87,0,0,12,17,6,-1,1,9},{87,0,0,12,17,6,-1,1,9}},
- {{87,0,0,12,17,6,-1,1,9},{87,0,0,12,17,6,-1,1,9},{87,0,0,12,17,6,-1,1,9},{87,0,0,12,17,6,-1,1,9},{87,0,0,6,1,6,-1,1,2},{87,0,0,6,1,6,-1,1,2},{87,0,0,26,10,8,-1,1,2},{87,0,0,21,10,8,-1,1,2},{87,0,0,21,10,8,-1,1,16},{87,0,0,21,10,8,-1,1,11},{87,0,0,6,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2}},
- {{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,7,1,7,-1,1,2},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,6,1,7,-1,1,2},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9}},
- {{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,6,1,7,-1,1,2},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,6,1,7,-1,1,2},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{126,0,0,12,17,7,-1,1,9},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{126,0,0,21,1,8,-1,1,2},{103,0,0,2,1,12,-1,1,0}},
- {{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2}},
- {{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,7,1,6,-1,1,2},{84,0,0,12,17,6,-1,1,9},{84,0,0,12,17,6,-1,1,9},{84,0,0,12,17,6,-1,1,9},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{84,0,0,21,1,8,-1,1,2},{103,0,0,2,1,12,-1,1,0}},
- {{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,4,-1,1,2},{2,0,0,7,13,4,-1,1,2},{2,0,0,7,13,4,-1,1,2}},
- {{2,0,0,7,13,4,-1,1,2},{2,0,0,7,13,4,-1,1,2},{2,0,0,7,13,0,-1,1,2},{2,0,0,7,13,2,-1,1,2},{2,0,0,7,13,2,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9}},
- {{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9},{2,0,0,12,17,2,-1,1,9}},
- {{10,0,0,12,17,2,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,10,0,0,-1,1,9},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2}},
- {{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2}},
- {{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,12,17,0,-1,1,9},{10,0,0,10,0,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,7,0,0,-1,1,2},{10,0,0,10,0,0,-1,1,9},{10,0,0,10,0,0,-1,1,9}},
- {{10,0,0,10,0,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,10,0,0,-1,1,9},{10,0,0,10,0,0,-1,1,9},{10,0,0,10,0,0,-1,1,9},{10,0,0,10,0,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,10,0,4,-1,1,9},{10,0,0,10,0,0,-1,1,9}},
- {{10,0,0,7,0,0,-1,1,2},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{10,0,0,12,17,3,-1,1,9},{10,0,0,12,17,3,-1,1,9},{10,0,0,12,17,2,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{10,0,0,7,0,9,-1,1,2},{10,0,0,7,0,9,-1,1,2},{10,0,0,7,0,9,-1,1,2},{10,0,0,7,0,9,-1,1,2},{10,0,0,7,0,9,-1,1,2},{10,0,0,7,0,9,-1,1,2},{10,0,0,7,0,9,-1,1,2},{10,0,0,7,0,9,-1,1,2}},
- {{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,12,17,0,-1,1,9},{10,0,0,12,17,0,-1,1,9},{0,0,0,21,0,8,-1,1,4},{0,0,0,21,0,8,-1,1,4},{10,0,0,13,0,0,0,1,19},{10,0,0,13,0,0,1,1,19},{10,0,0,13,0,0,2,1,19},{10,0,0,13,0,0,3,1,19},{10,0,0,13,0,0,4,1,19},{10,0,0,13,0,0,5,1,19},{10,0,0,13,0,0,6,1,19},{10,0,0,13,0,0,7,1,19},{10,0,0,13,0,0,8,1,19},{10,0,0,13,0,0,9,1,19}},
- {{10,0,0,21,0,8,-1,1,2},{10,0,0,6,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,4,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2},{10,0,0,7,0,0,-1,1,2}},
- {{4,0,0,7,0,4,-1,1,2},{4,0,0,12,17,0,-1,1,9},{4,0,0,10,0,0,-1,1,9},{4,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,7,0,0,-1,1,2}},
- {{4,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2}},
- {{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2}},
- {{4,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{4,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,12,17,0,-1,1,9},{4,0,0,7,0,0,-1,1,2},{4,0,0,10,0,0,-1,1,9},{4,0,0,10,0,0,-1,1,9}},
- {{4,0,0,10,0,0,-1,1,9},{4,0,0,12,17,0,-1,1,9},{4,0,0,12,17,0,-1,1,9},{4,0,0,12,17,0,-1,1,9},{4,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,10,0,0,-1,1,9},{4,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,10,0,0,-1,1,9},{4,0,0,10,0,0,-1,1,9},{4,0,0,12,17,0,-1,1,9},{4,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,7,0,9,-1,1,2},{4,0,0,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{4,0,0,7,0,9,-1,1,2}},
- {{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,12,17,0,-1,1,9},{4,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{4,0,0,13,0,0,0,1,19},{4,0,0,13,0,0,1,1,19},{4,0,0,13,0,0,2,1,19},{4,0,0,13,0,0,3,1,19},{4,0,0,13,0,0,4,1,19},{4,0,0,13,0,0,5,1,19},{4,0,0,13,0,0,6,1,19},{4,0,0,13,0,0,7,1,19},{4,0,0,13,0,0,8,1,19},{4,0,0,13,0,0,9,1,19}},
- {{4,0,0,7,0,0,-1,1,2},{4,0,0,7,0,0,-1,1,2},{4,0,0,23,4,8,-1,1,21},{4,0,0,23,4,8,-1,1,21},{4,0,0,15,0,8,-1,1,2},{4,0,0,15,0,8,-1,1,2},{4,0,0,15,0,8,-1,1,2},{4,0,0,15,0,8,-1,1,2},{4,0,0,15,0,8,-1,1,2},{4,0,0,15,0,8,-1,1,21},{4,0,0,26,0,8,-1,1,2},{4,0,0,23,4,8,-1,1,22},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{16,0,0,12,17,0,-1,1,9},{16,0,0,12,17,0,-1,1,9},{16,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,0,-1,1,2}},
- {{16,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2}},
- {{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2}},
- {{16,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{16,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{16,0,0,10,0,0,-1,1,9},{16,0,0,10,0,0,-1,1,9}},
- {{16,0,0,10,0,0,-1,1,9},{16,0,0,12,17,0,-1,1,9},{16,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{16,0,0,12,17,0,-1,1,9},{16,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{16,0,0,12,17,0,-1,1,9},{16,0,0,12,17,0,-1,1,9},{16,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{16,0,0,12,17,2,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,9,-1,1,2},{16,0,0,7,0,9,-1,1,2},{16,0,0,7,0,9,-1,1,2},{16,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{16,0,0,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{16,0,0,13,0,0,0,1,19},{16,0,0,13,0,0,1,1,19},{16,0,0,13,0,0,2,1,19},{16,0,0,13,0,0,3,1,19},{16,0,0,13,0,0,4,1,19},{16,0,0,13,0,0,5,1,19},{16,0,0,13,0,0,6,1,19},{16,0,0,13,0,0,7,1,19},{16,0,0,13,0,0,8,1,19},{16,0,0,13,0,0,9,1,19}},
- {{16,0,0,12,17,0,-1,1,9},{16,0,0,12,17,0,-1,1,9},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,7,0,0,-1,1,2},{16,0,0,12,17,2,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{15,0,0,12,17,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{15,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{15,0,0,7,0,0,-1,1,2}},
- {{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2}},
- {{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2}},
- {{15,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{15,0,0,12,17,0,-1,1,9},{15,0,0,7,0,0,-1,1,2},{15,0,0,10,0,0,-1,1,9},{15,0,0,10,0,0,-1,1,9}},
- {{15,0,0,10,0,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{15,0,0,12,17,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{15,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{15,0,0,10,0,0,-1,1,9},{15,0,0,10,0,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{15,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{15,0,0,7,0,0,-1,1,2},{15,0,0,7,0,0,-1,1,2},{15,0,0,12,17,0,-1,1,9},{15,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{15,0,0,13,0,0,0,1,19},{15,0,0,13,0,0,1,1,19},{15,0,0,13,0,0,2,1,19},{15,0,0,13,0,0,3,1,19},{15,0,0,13,0,0,4,1,19},{15,0,0,13,0,0,5,1,19},{15,0,0,13,0,0,6,1,19},{15,0,0,13,0,0,7,1,19},{15,0,0,13,0,0,8,1,19},{15,0,0,13,0,0,9,1,19}},
- {{15,0,0,21,0,8,-1,1,2},{15,0,0,23,4,8,-1,1,22},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{15,0,0,7,0,2,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{31,0,0,12,17,0,-1,1,9},{31,0,0,10,0,0,-1,1,9},{31,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{31,0,0,7,0,0,-1,1,2}},
- {{31,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2}},
- {{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2}},
- {{31,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{31,0,0,12,17,0,-1,1,9},{31,0,0,7,0,0,-1,1,2},{31,0,0,10,0,0,-1,1,9},{31,0,0,12,17,0,-1,1,9}},
- {{31,0,0,10,0,0,-1,1,9},{31,0,0,12,17,0,-1,1,9},{31,0,0,12,17,0,-1,1,9},{31,0,0,12,17,0,-1,1,9},{31,0,0,12,17,2,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{31,0,0,10,0,0,-1,1,9},{31,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{31,0,0,10,0,0,-1,1,9},{31,0,0,10,0,0,-1,1,9},{31,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{31,0,0,12,17,0,-1,1,9},{31,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{31,0,0,7,0,9,-1,1,2},{31,0,0,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{31,0,0,7,0,0,-1,1,2}},
- {{31,0,0,7,0,0,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,12,17,2,-1,1,9},{31,0,0,12,17,2,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{31,0,0,13,0,0,0,1,19},{31,0,0,13,0,0,1,1,19},{31,0,0,13,0,0,2,1,19},{31,0,0,13,0,0,3,1,19},{31,0,0,13,0,0,4,1,19},{31,0,0,13,0,0,5,1,19},{31,0,0,13,0,0,6,1,19},{31,0,0,13,0,0,7,1,19},{31,0,0,13,0,0,8,1,19},{31,0,0,13,0,0,9,1,19}},
- {{31,0,0,26,0,8,-1,1,2},{31,0,0,7,0,0,-1,1,2},{31,0,0,15,0,8,-1,1,2},{31,0,0,15,0,8,-1,1,2},{31,0,0,15,0,8,-1,1,2},{31,0,0,15,0,8,-1,1,2},{31,0,0,15,0,8,-1,1,2},{31,0,0,15,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,12,17,0,-1,1,9},{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2}},
- {{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2}},
- {{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,10,0,0,-1,1,9},{35,0,0,10,0,0,-1,1,9}},
- {{35,0,0,12,17,0,-1,1,9},{35,0,0,10,0,0,-1,1,9},{35,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,10,0,0,-1,1,9},{35,0,0,10,0,0,-1,1,9},{35,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{35,0,0,10,0,0,-1,1,9},{35,0,0,10,0,0,-1,1,9},{35,0,0,10,0,0,-1,1,9},{35,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{35,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{35,0,0,13,0,0,0,1,19},{35,0,0,13,0,0,1,1,19},{35,0,0,13,0,0,2,1,19},{35,0,0,13,0,0,3,1,19},{35,0,0,13,0,0,4,1,19},{35,0,0,13,0,0,5,1,19},{35,0,0,13,0,0,6,1,19},{35,0,0,13,0,0,7,1,19},{35,0,0,13,0,0,8,1,19},{35,0,0,13,0,0,9,1,19}},
- {{35,0,0,15,0,8,-1,1,2},{35,0,0,15,0,8,-1,1,2},{35,0,0,15,0,8,-1,1,2},{35,0,0,26,10,8,-1,1,2},{35,0,0,26,10,8,-1,1,2},{35,0,0,26,10,8,-1,1,2},{35,0,0,26,10,8,-1,1,2},{35,0,0,26,10,8,-1,1,2},{35,0,0,26,10,8,-1,1,2},{35,0,0,23,4,8,-1,1,22},{35,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{36,0,0,12,17,4,-1,1,9},{36,0,0,10,0,0,-1,1,9},{36,0,0,10,0,0,-1,1,9},{36,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2}},
- {{36,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2}},
- {{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2}},
- {{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,4,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{36,0,0,7,0,0,-1,1,2},{36,0,0,12,17,0,-1,1,9},{36,0,0,12,17,0,-1,1,9}},
- {{36,0,0,12,17,0,-1,1,9},{36,0,0,10,0,0,-1,1,9},{36,0,0,10,0,0,-1,1,9},{36,0,0,10,0,0,-1,1,9},{36,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{36,0,0,12,17,0,-1,1,9},{36,0,0,12,17,0,-1,1,9},{36,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{36,0,0,12,17,0,-1,1,9},{36,0,0,12,17,0,-1,1,9},{36,0,0,12,17,0,-1,1,9},{36,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{36,0,0,12,17,0,-1,1,9},{36,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{36,0,0,7,0,4,-1,1,2},{36,0,0,7,0,4,-1,1,2},{36,0,0,7,0,2,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{36,0,0,7,0,0,-1,1,2},{36,0,0,7,0,0,-1,1,2},{36,0,0,12,17,2,-1,1,9},{36,0,0,12,17,2,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{36,0,0,13,0,0,0,1,19},{36,0,0,13,0,0,1,1,19},{36,0,0,13,0,0,2,1,19},{36,0,0,13,0,0,3,1,19},{36,0,0,13,0,0,4,1,19},{36,0,0,13,0,0,5,1,19},{36,0,0,13,0,0,6,1,19},{36,0,0,13,0,0,7,1,19},{36,0,0,13,0,0,8,1,19},{36,0,0,13,0,0,9,1,19}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{36,0,0,15,10,8,-1,1,2},{36,0,0,15,10,8,-1,1,2},{36,0,0,15,10,8,-1,1,2},{36,0,0,15,10,8,-1,1,2},{36,0,0,15,10,8,-1,1,2},{36,0,0,15,10,8,-1,1,2},{36,0,0,15,10,8,-1,1,2},{36,0,0,26,0,8,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{21,0,0,12,17,4,-1,1,9},{21,0,0,10,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2}},
- {{21,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2}},
- {{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2}},
- {{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{21,0,0,12,17,0,-1,1,9},{21,0,0,7,0,0,-1,1,2},{21,0,0,10,0,0,-1,1,9},{21,0,0,12,0,0,-1,1,9}},
- {{21,0,0,10,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{21,0,0,12,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{21,0,0,10,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{21,0,0,12,17,0,-1,1,9},{21,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{21,0,0,10,0,0,-1,1,9},{21,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{21,0,0,7,0,4,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{21,0,0,12,17,0,-1,1,9},{21,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{21,0,0,13,0,0,0,1,19},{21,0,0,13,0,0,1,1,19},{21,0,0,13,0,0,2,1,19},{21,0,0,13,0,0,3,1,19},{21,0,0,13,0,0,4,1,19},{21,0,0,13,0,0,5,1,19},{21,0,0,13,0,0,6,1,19},{21,0,0,13,0,0,7,1,19},{21,0,0,13,0,0,8,1,19},{21,0,0,13,0,0,9,1,19}},
- {{103,0,0,2,0,12,-1,1,0},{21,0,0,7,0,0,-1,1,2},{21,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{26,0,0,12,17,4,-1,1,9},{26,0,0,10,0,0,-1,1,9},{26,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2}},
- {{26,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2}},
- {{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2}},
- {{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{26,0,0,7,0,0,-1,1,2},{26,0,0,10,0,0,-1,1,9},{26,0,0,10,0,0,-1,1,9}},
- {{26,0,0,10,0,0,-1,1,9},{26,0,0,12,17,0,-1,1,9},{26,0,0,12,17,0,-1,1,9},{26,0,0,12,17,0,-1,1,9},{26,0,0,12,17,2,-1,1,9},{103,0,0,2,0,12,-1,1,0},{26,0,0,10,0,0,-1,1,9},{26,0,0,10,0,0,-1,1,9},{26,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{26,0,0,10,0,0,-1,1,9},{26,0,0,10,0,0,-1,1,9},{26,0,0,10,0,0,-1,1,9},{26,0,0,12,17,0,-1,1,9},{26,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{26,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{26,0,0,7,0,4,-1,1,2}},
- {{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,12,17,2,-1,1,9},{26,0,0,12,17,2,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{26,0,0,13,0,0,0,1,19},{26,0,0,13,0,0,1,1,19},{26,0,0,13,0,0,2,1,19},{26,0,0,13,0,0,3,1,19},{26,0,0,13,0,0,4,1,19},{26,0,0,13,0,0,5,1,19},{26,0,0,13,0,0,6,1,19},{26,0,0,13,0,0,7,1,19},{26,0,0,13,0,0,8,1,19},{26,0,0,13,0,0,9,1,19}},
- {{26,0,0,15,0,8,-1,1,2},{26,0,0,15,0,8,-1,1,2},{26,0,0,15,0,8,-1,1,2},{26,0,0,15,0,8,-1,1,2},{26,0,0,15,0,8,-1,1,2},{26,0,0,15,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{26,0,0,26,0,8,-1,1,21},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2},{26,0,0,7,0,0,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,3,-1,1,2}},
- {{33,0,0,7,0,3,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2}},
- {{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,3,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2}},
- {{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{33,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{33,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{33,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{33,0,0,10,0,0,-1,1,9}},
- {{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,0,-1,1,9},{33,0,0,12,17,0,-1,1,9},{33,0,0,12,17,0,-1,1,9},{33,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{33,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,3,-1,1,9}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{33,0,0,13,0,4,0,1,19},{33,0,0,13,0,4,1,1,19},{33,0,0,13,0,4,2,1,19},{33,0,0,13,0,4,3,1,19},{33,0,0,13,0,4,4,1,19},{33,0,0,13,0,4,5,1,19},{33,0,0,13,0,4,6,1,19},{33,0,0,13,0,4,7,1,19},{33,0,0,13,0,4,8,1,19},{33,0,0,13,0,4,9,1,19}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{33,0,0,10,0,0,-1,1,9},{33,0,0,10,0,3,-1,1,9},{33,0,0,21,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24}},
- {{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24}},
- {{38,0,0,7,0,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,9,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,23,4,8,-1,1,22}},
- {{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,7,0,0,-1,1,24},{38,0,0,6,0,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,12,17,0,-1,1,24},{38,0,0,21,0,8,-1,1,2}},
- {{38,0,0,13,0,0,0,1,19},{38,0,0,13,0,0,1,1,19},{38,0,0,13,0,0,2,1,19},{38,0,0,13,0,0,3,1,19},{38,0,0,13,0,0,4,1,19},{38,0,0,13,0,0,5,1,19},{38,0,0,13,0,0,6,1,19},{38,0,0,13,0,0,7,1,19},{38,0,0,13,0,0,8,1,19},{38,0,0,13,0,0,9,1,19},{38,0,0,21,0,8,-1,1,4},{38,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24}},
- {{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24}},
- {{24,0,0,7,0,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,9,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,6,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{24,0,0,12,17,0,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{24,0,0,13,0,0,0,1,19},{24,0,0,13,0,0,1,1,19},{24,0,0,13,0,0,2,1,19},{24,0,0,13,0,0,3,1,19},{24,0,0,13,0,0,4,1,19},{24,0,0,13,0,0,5,1,19},{24,0,0,13,0,0,6,1,19},{24,0,0,13,0,0,7,1,19},{24,0,0,13,0,0,8,1,19},{24,0,0,13,0,0,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{24,0,0,7,0,9,-1,1,24},{24,0,0,7,0,9,-1,1,24},{24,0,0,7,0,0,-1,1,24},{24,0,0,7,0,0,-1,1,24}},
- {{39,0,0,7,0,0,-1,1,2},{39,0,0,26,0,8,-1,1,5},{39,0,0,26,0,8,-1,1,5},{39,0,0,26,0,8,-1,1,5},{39,0,0,21,0,8,-1,1,5},{39,0,0,21,0,8,-1,1,2},{39,0,0,21,0,8,-1,1,5},{39,0,0,21,0,8,-1,1,5},{39,0,0,21,0,8,-1,1,12},{39,0,0,21,0,8,-1,1,5},{39,0,0,21,0,8,-1,1,5},{39,0,0,21,0,1,-1,1,4},{39,0,0,21,0,9,-1,1,12},{39,0,0,21,0,8,-1,1,11},{39,0,0,21,0,8,-1,1,11},{39,0,0,21,0,8,-1,1,11}},
- {{39,0,0,21,0,8,-1,1,11},{39,0,0,21,0,8,-1,1,11},{39,0,0,21,0,8,-1,1,12},{39,0,0,26,0,8,-1,1,2},{39,0,0,21,0,8,-1,1,11},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,12,17,3,-1,1,9},{39,0,0,12,17,3,-1,1,9},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2}},
- {{39,0,0,13,0,0,0,1,19},{39,0,0,13,0,0,1,1,19},{39,0,0,13,0,0,2,1,19},{39,0,0,13,0,0,3,1,19},{39,0,0,13,0,0,4,1,19},{39,0,0,13,0,0,5,1,19},{39,0,0,13,0,0,6,1,19},{39,0,0,13,0,0,7,1,19},{39,0,0,13,0,0,8,1,19},{39,0,0,13,0,0,9,1,19},{39,0,0,15,0,8,-1,1,2},{39,0,0,15,0,8,-1,1,2},{39,0,0,15,0,8,-1,1,2},{39,0,0,15,0,8,-1,1,2},{39,0,0,15,0,8,-1,1,2},{39,0,0,15,0,8,-1,1,2}},
- {{39,0,0,15,0,8,-1,1,2},{39,0,0,15,0,8,-1,1,2},{39,0,0,15,0,8,-1,1,2},{39,0,0,15,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,4},{39,0,0,12,17,0,-1,1,9},{39,0,0,26,0,8,-1,1,2},{39,0,0,12,17,0,-1,1,9},{39,0,0,26,0,8,-1,1,2},{39,0,0,12,17,2,-1,1,9},{39,1,0,22,10,8,-1,1,20},{39,2,0,18,10,8,-1,1,8},{39,1,0,22,10,8,-1,1,20},{39,2,0,18,10,8,-1,1,8},{39,0,0,10,0,0,-1,1,9},{39,0,0,10,0,0,-1,1,9}},
- {{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,9,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,9,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2}},
- {{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,9,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,9,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,9,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2}},
- {{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,9,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,11,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,11,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,10,0,0,-1,1,4}},
- {{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,21,0,8,-1,1,4},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,7,0,0,-1,1,2},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9}},
- {{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9}},
- {{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9}},
- {{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,9,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{39,0,0,12,17,0,-1,1,9},{103,0,0,2,0,12,-1,1,0},{39,0,0,26,0,8,-1,1,4},{39,0,0,26,0,8,-1,1,4}},
- {{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,12,17,0,-1,1,9},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{39,0,0,26,0,8,-1,1,2},{39,0,0,26,0,8,-1,1,2}},
- {{39,0,0,21,0,8,-1,1,5},{39,0,0,21,0,8,-1,1,5},{39,0,0,21,0,8,-1,1,4},{39,0,0,21,0,8,-1,1,5},{39,0,0,21,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{39,0,0,21,0,8,-1,1,12},{39,0,0,21,0,8,-1,1,12},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24}},
- {{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24}},
- {{28,0,0,12,17,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,7,0,0,-1,1,24}},
- {{28,0,0,13,0,0,0,1,19},{28,0,0,13,0,0,1,1,19},{28,0,0,13,0,0,2,1,19},{28,0,0,13,0,0,3,1,19},{28,0,0,13,0,0,4,1,19},{28,0,0,13,0,0,5,1,19},{28,0,0,13,0,0,6,1,19},{28,0,0,13,0,0,7,1,19},{28,0,0,13,0,0,8,1,19},{28,0,0,13,0,0,9,1,19},{28,0,0,21,0,8,-1,1,4},{28,0,0,21,0,8,-1,1,4},{28,0,0,21,0,8,-1,1,2},{28,0,0,21,0,8,-1,1,2},{28,0,0,21,0,8,-1,1,2},{28,0,0,21,0,8,-1,1,2}},
- {{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24}},
- {{28,0,0,12,17,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24}},
- {{28,0,0,7,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24}},
- {{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24}},
- {{28,0,0,13,0,0,0,1,19},{28,0,0,13,0,0,1,1,19},{28,0,0,13,0,0,2,1,19},{28,0,0,13,0,0,3,1,19},{28,0,0,13,0,0,4,1,19},{28,0,0,13,0,0,5,1,19},{28,0,0,13,0,0,6,1,19},{28,0,0,13,0,0,7,1,19},{28,0,0,13,0,0,8,1,19},{28,0,0,13,0,0,9,1,19},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,26,0,8,-1,1,24},{28,0,0,26,0,8,-1,1,24}},
- {{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2}},
- {{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{12,0,0,9,0,4,-1,1,2},{103,0,0,2,0,12,-1,1,0},{12,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{12,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2}},
- {{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,4,-1,1,2},{12,0,0,7,0,4,-1,1,2},{12,0,0,7,0,4,-1,1,2},{12,0,0,7,0,4,-1,1,2},{12,0,0,7,0,4,-1,1,2},{12,0,0,7,0,4,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{0,0,0,21,0,8,-1,1,2},{12,0,0,6,0,9,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2},{12,0,0,7,0,0,-1,1,2}},
- {{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33}},
- {{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,10,-1,0,33}},
- {{18,0,0,7,0,10,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35}},
- {{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35}},
- {{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34}},
- {{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34}},
- {{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2}},
- {{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2}},
- {{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2}},
- {{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{11,0,0,12,17,0,-1,1,9},{11,0,0,12,17,0,-1,1,9},{11,0,0,12,17,0,-1,1,9}},
- {{11,0,0,21,0,8,-1,1,2},{11,0,0,21,0,8,-1,1,4},{11,0,0,21,0,8,-1,1,2},{11,0,0,21,0,8,-1,1,2},{11,0,0,21,0,8,-1,1,2},{11,0,0,21,0,8,-1,1,2},{11,0,0,21,0,8,-1,1,2},{11,0,0,21,0,8,-1,1,2},{11,0,0,21,0,8,-1,1,2},{11,0,0,15,0,4,1,1,2},{11,0,0,15,0,4,2,1,2},{11,0,0,15,0,4,3,1,2},{11,0,0,15,0,4,4,1,2},{11,0,0,15,0,4,5,1,2},{11,0,0,15,0,4,6,1,2},{11,0,0,15,0,4,7,1,2}},
- {{11,0,0,15,0,4,8,1,2},{11,0,0,15,0,4,9,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{11,0,0,15,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{11,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2}},
- {{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{6,0,0,9,0,6,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{40,0,0,17,10,8,-1,1,4},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2}},
- {{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2}},
- {{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,21,0,8,-1,0,2},{40,0,0,21,0,8,-1,0,2},{40,0,0,7,0,5,-1,0,2}},
- {{29,0,0,29,9,8,-1,1,4},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2}},
- {{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,0,0,7,0,7,-1,1,2},{29,1,0,22,10,8,-1,1,20},{29,2,0,18,10,8,-1,1,8},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2}},
- {{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{0,0,0,21,0,8,-1,1,4},{0,0,0,21,0,8,-1,1,4},{0,0,0,21,0,8,-1,1,4},{32,0,0,14,0,7,-1,1,2},{32,0,0,14,0,7,-1,1,2}},
- {{32,0,0,14,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{32,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2}},
- {{42,0,0,7,0,7,-1,1,2},{42,0,0,7,0,7,-1,1,2},{42,0,0,12,17,7,-1,1,9},{42,0,0,12,17,7,-1,1,9},{42,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2}},
- {{43,0,0,7,0,7,-1,1,2},{43,0,0,7,0,7,-1,1,2},{43,0,0,12,17,7,-1,1,9},{43,0,0,12,17,7,-1,1,9},{43,0,0,12,17,7,-1,1,9},{0,0,0,21,0,8,-1,1,4},{0,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2}},
- {{44,0,0,7,0,7,-1,1,2},{44,0,0,7,0,7,-1,1,2},{44,0,0,12,17,7,-1,1,9},{44,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{45,0,0,7,0,7,-1,1,2},{45,0,0,7,0,7,-1,1,2}},
- {{45,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{45,0,0,12,17,7,-1,1,9},{45,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24}},
- {{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,11,-1,1,24},{23,0,0,7,0,11,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,4,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24}},
- {{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,7,0,0,-1,1,24},{23,0,0,12,17,10,-1,1,24},{23,0,0,12,17,10,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,10,0,0,-1,1,24}},
- {{23,0,0,10,0,0,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,10,0,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,3,-1,1,24},{23,0,0,12,17,3,-1,1,24},{23,0,0,12,17,3,-1,1,24},{23,0,0,12,17,3,-1,1,24},{23,0,0,12,17,3,-1,1,24}},
- {{23,0,0,12,17,3,-1,1,24},{23,0,0,12,17,4,-1,1,24},{23,0,0,12,17,0,-1,1,24},{23,0,0,12,17,4,-1,1,24},{23,0,0,21,0,8,-1,1,4},{23,0,0,21,0,8,-1,1,4},{23,0,0,21,0,8,-1,1,18},{23,0,0,6,0,0,-1,1,24},{23,0,0,21,0,8,-1,1,4},{23,0,0,21,0,8,-1,1,2},{23,0,0,21,0,8,-1,1,4},{23,0,0,23,4,8,-1,1,22},{23,0,0,7,0,0,-1,1,24},{23,0,0,12,17,4,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{23,0,0,13,0,0,0,1,19},{23,0,0,13,0,0,1,1,19},{23,0,0,13,0,0,2,1,19},{23,0,0,13,0,0,3,1,19},{23,0,0,13,0,0,4,1,19},{23,0,0,13,0,0,5,1,19},{23,0,0,13,0,0,6,1,19},{23,0,0,13,0,0,7,1,19},{23,0,0,13,0,0,8,1,19},{23,0,0,13,0,0,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{23,0,0,15,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{27,0,0,21,10,8,-1,1,2},{27,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,11},{0,0,0,21,10,8,-1,1,11},{27,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{27,0,0,17,10,8,-1,1,5},{27,0,0,21,10,8,-1,1,2},{27,0,0,21,10,8,-1,1,11},{27,0,0,21,10,8,-1,1,11},{27,0,0,21,10,8,-1,1,2},{27,0,0,12,17,10,-1,1,9},{27,0,0,12,17,10,-1,1,9},{27,0,0,12,17,10,-1,1,9},{27,0,0,1,18,10,-1,1,12},{103,0,0,2,0,12,-1,1,0}},
- {{27,0,0,13,0,5,0,1,19},{27,0,0,13,0,5,1,1,19},{27,0,0,13,0,5,2,1,19},{27,0,0,13,0,5,3,1,19},{27,0,0,13,0,5,4,1,19},{27,0,0,13,0,5,5,1,19},{27,0,0,13,0,5,6,1,19},{27,0,0,13,0,5,7,1,19},{27,0,0,13,0,5,8,1,19},{27,0,0,13,0,5,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2}},
- {{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,6,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2}},
- {{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,7,0,5,-1,1,2},{27,0,0,12,17,5,-1,1,9},{27,0,0,7,0,5,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{40,0,0,7,0,5,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2}},
- {{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{48,0,0,7,0,6,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{48,0,0,12,17,6,-1,1,9},{48,0,0,12,17,6,-1,1,9},{48,0,0,12,17,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,12,17,6,-1,1,9},{48,0,0,12,17,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,12,17,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,10,0,6,-1,1,9},{48,0,0,12,17,6,-1,1,9},{48,0,0,12,17,6,-1,1,9},{48,0,0,12,17,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{48,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{48,0,0,21,10,8,-1,1,11},{48,0,0,21,10,8,-1,1,11},{48,0,0,13,0,6,0,1,19},{48,0,0,13,0,6,1,1,19},{48,0,0,13,0,6,2,1,19},{48,0,0,13,0,6,3,1,19},{48,0,0,13,0,6,4,1,19},{48,0,0,13,0,6,5,1,19},{48,0,0,13,0,6,6,1,19},{48,0,0,13,0,6,7,1,19},{48,0,0,13,0,6,8,1,19},{48,0,0,13,0,6,9,1,19}},
- {{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24}},
- {{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{52,0,0,7,0,6,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24}},
- {{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{59,0,0,7,0,6,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{59,0,0,13,0,6,0,1,19},{59,0,0,13,0,6,1,1,19},{59,0,0,13,0,6,2,1,19},{59,0,0,13,0,6,3,1,19},{59,0,0,13,0,6,4,1,19},{59,0,0,13,0,6,5,1,19},{59,0,0,13,0,6,6,1,19},{59,0,0,13,0,6,7,1,19},{59,0,0,13,0,6,8,1,19},{59,0,0,13,0,6,9,1,19},{59,0,0,15,0,6,1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{59,0,0,26,10,8,-1,1,24},{59,0,0,26,10,8,-1,1,24}},
- {{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2},{23,0,0,26,10,8,-1,1,2}},
- {{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2}},
- {{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,7,0,7,-1,1,2},{55,0,0,12,17,7,-1,1,9},{55,0,0,12,17,7,-1,1,9},{55,0,0,10,0,7,-1,1,9},{55,0,0,10,0,7,-1,1,9},{55,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{55,0,0,21,0,8,-1,1,2},{55,0,0,21,0,8,-1,1,2}},
- {{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24}},
- {{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,7,0,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{103,0,0,2,0,12,-1,1,0}},
- {{106,0,0,12,17,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,10,0,6,-1,1,24}},
- {{106,0,0,10,0,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,10,0,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{106,0,0,12,17,6,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{106,0,0,12,17,6,-1,1,9}},
- {{106,0,0,13,0,6,0,1,19},{106,0,0,13,0,6,1,1,19},{106,0,0,13,0,6,2,1,19},{106,0,0,13,0,6,3,1,19},{106,0,0,13,0,6,4,1,19},{106,0,0,13,0,6,5,1,19},{106,0,0,13,0,6,6,1,19},{106,0,0,13,0,6,7,1,19},{106,0,0,13,0,6,8,1,19},{106,0,0,13,0,6,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,6,0,6,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{106,0,0,21,0,8,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,11,17,8,-1,1,9},{103,0,0,2,0,12,-1,1,0}},
- {{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,10,0,6,-1,1,9},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2}},
- {{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2}},
- {{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,12,17,6,-1,1,9},{62,0,0,10,0,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,10,0,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,10,0,6,-1,1,9},{62,0,0,10,0,6,-1,1,9},{62,0,0,10,0,6,-1,1,9}},
- {{62,0,0,10,0,6,-1,1,9},{62,0,0,10,0,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,10,0,6,-1,1,9},{62,0,0,10,0,6,-1,1,9},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{62,0,0,7,0,6,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{62,0,0,13,0,6,0,1,19},{62,0,0,13,0,6,1,1,19},{62,0,0,13,0,6,2,1,19},{62,0,0,13,0,6,3,1,19},{62,0,0,13,0,6,4,1,19},{62,0,0,13,0,6,5,1,19},{62,0,0,13,0,6,6,1,19},{62,0,0,13,0,6,7,1,19},{62,0,0,13,0,6,8,1,19},{62,0,0,13,0,6,9,1,19},{62,0,0,21,0,8,-1,1,4},{62,0,0,21,0,8,-1,1,4},{62,0,0,21,0,8,-1,1,2},{62,0,0,21,0,8,-1,1,4},{62,0,0,21,0,8,-1,1,4},{62,0,0,21,0,8,-1,1,4}},
- {{62,0,0,21,0,8,-1,1,4},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9}},
- {{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,12,17,6,-1,1,9},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{62,0,0,26,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{113,0,0,12,17,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,10,0,6,-1,1,9},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2}},
- {{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2}},
- {{113,0,0,7,0,6,-1,1,2},{113,0,0,10,0,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,10,0,6,-1,1,9},{113,0,0,10,0,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,10,0,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,12,17,6,-1,1,9},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2}},
- {{113,0,0,13,0,6,0,1,19},{113,0,0,13,0,6,1,1,19},{113,0,0,13,0,6,2,1,19},{113,0,0,13,0,6,3,1,19},{113,0,0,13,0,6,4,1,19},{113,0,0,13,0,6,5,1,19},{113,0,0,13,0,6,6,1,19},{113,0,0,13,0,6,7,1,19},{113,0,0,13,0,6,8,1,19},{113,0,0,13,0,6,9,1,19},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2},{113,0,0,7,0,6,-1,1,2}},
- {{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2}},
- {{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,7,0,6,-1,1,2},{63,0,0,12,17,6,-1,1,9},{63,0,0,10,0,6,-1,1,9},{63,0,0,12,17,6,-1,1,9},{63,0,0,12,17,6,-1,1,9},{63,0,0,10,0,6,-1,1,9},{63,0,0,10,0,6,-1,1,9},{63,0,0,10,0,6,-1,1,9},{63,0,0,12,17,6,-1,1,9},{63,0,0,10,0,6,-1,1,9},{63,0,0,12,17,6,-1,1,9}},
- {{63,0,0,12,17,6,-1,1,9},{63,0,0,12,17,6,-1,1,9},{63,0,0,10,0,6,-1,1,9},{63,0,0,10,0,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{63,0,0,21,0,8,-1,1,2},{63,0,0,21,0,8,-1,1,2},{63,0,0,21,0,8,-1,1,2},{63,0,0,21,0,8,-1,1,2}},
- {{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2}},
- {{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,10,0,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,12,17,6,-1,1,9},{82,0,0,12,17,6,-1,1,9},{82,0,0,12,17,6,-1,1,9},{82,0,0,12,17,6,-1,1,9}},
- {{82,0,0,12,17,6,-1,1,9},{82,0,0,12,17,6,-1,1,9},{82,0,0,12,17,6,-1,1,9},{82,0,0,12,17,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,10,0,6,-1,1,9},{82,0,0,12,17,6,-1,1,9},{82,0,0,12,17,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{82,0,0,21,0,8,-1,1,4},{82,0,0,21,0,8,-1,1,4},{82,0,0,21,0,8,-1,1,4},{82,0,0,21,0,8,-1,1,4},{82,0,0,21,0,8,-1,1,4}},
- {{82,0,0,13,0,6,0,1,19},{82,0,0,13,0,6,1,1,19},{82,0,0,13,0,6,2,1,19},{82,0,0,13,0,6,3,1,19},{82,0,0,13,0,6,4,1,19},{82,0,0,13,0,6,5,1,19},{82,0,0,13,0,6,6,1,19},{82,0,0,13,0,6,7,1,19},{82,0,0,13,0,6,8,1,19},{82,0,0,13,0,6,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2},{82,0,0,7,0,6,-1,1,2}},
- {{109,0,0,13,0,6,0,1,19},{109,0,0,13,0,6,1,1,19},{109,0,0,13,0,6,2,1,19},{109,0,0,13,0,6,3,1,19},{109,0,0,13,0,6,4,1,19},{109,0,0,13,0,6,5,1,19},{109,0,0,13,0,6,6,1,19},{109,0,0,13,0,6,7,1,19},{109,0,0,13,0,6,8,1,19},{109,0,0,13,0,6,9,1,19},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2}},
- {{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2}},
- {{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,7,0,6,-1,1,2},{109,0,0,6,0,6,-1,1,2},{109,0,0,6,0,6,-1,1,2},{109,0,0,6,0,6,-1,1,2},{109,0,0,6,0,6,-1,1,2},{109,0,0,6,0,6,-1,1,2},{109,0,0,6,0,6,-1,1,2},{109,0,0,21,0,8,-1,1,4},{109,0,0,21,0,8,-1,1,4}},
- {{113,0,0,21,0,8,-1,1,2},{113,0,0,21,0,8,-1,1,2},{113,0,0,21,0,8,-1,1,2},{113,0,0,21,0,8,-1,1,2},{113,0,0,21,0,8,-1,1,2},{113,0,0,21,0,8,-1,1,2},{113,0,0,21,0,8,-1,1,2},{113,0,0,21,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{0,0,0,21,0,8,-1,1,2},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9}},
- {{1,0,0,12,17,4,-1,1,9},{0,0,0,10,0,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{0,0,0,7,0,4,-1,1,2},{0,0,0,7,0,4,-1,1,2},{0,0,0,7,0,4,-1,1,2},{0,0,0,7,0,4,-1,1,2},{1,0,0,12,17,4,-1,1,9},{0,0,0,7,0,4,-1,1,2},{0,0,0,7,0,4,-1,1,2}},
- {{0,0,0,7,0,4,-1,1,2},{0,0,0,7,0,4,-1,1,2},{0,0,0,10,0,4,-1,1,9},{0,0,0,10,0,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{0,0,0,7,0,4,-1,1,2},{0,0,0,7,0,4,-1,1,2},{103,0,0,2,0,12,-1,1,0},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{14,0,0,5,0,3,-1,1,2},{14,0,0,5,0,3,-1,1,2},{14,0,0,5,0,3,-1,1,2},{14,0,0,5,0,3,-1,1,2},{14,0,0,5,0,3,-1,1,2},{8,0,0,5,0,3,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,3,-1,1,2}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,3,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,3,-1,1,2},{25,0,0,6,0,9,-1,1,2}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2}},
- {{14,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2}},
- {{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{8,0,0,6,0,9,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2}},
- {{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{14,0,0,6,0,9,-1,1,2}},
- {{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,3,-1,1,9}},
- {{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9}},
- {{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,4,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9}},
- {{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,3,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,9,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,9,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,9,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,9,0,0,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,8,0,0,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,24,10,9,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,24,10,9,-1,1,2}},
- {{14,0,0,24,10,9,-1,1,2},{14,0,0,24,10,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,24,10,9,-1,1,2},{14,0,0,24,10,9,-1,1,2},{14,0,0,24,10,9,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,24,10,9,-1,1,2},{14,0,0,24,10,9,-1,1,2},{14,0,0,24,10,9,-1,1,2}},
- {{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,9,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,24,10,9,-1,1,2},{14,0,0,24,10,9,-1,1,2},{14,0,0,24,10,9,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{14,0,0,5,0,0,-1,1,2},{14,0,0,5,0,0,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,9,0,0,-1,1,2},{14,0,0,9,0,9,-1,1,2},{14,0,0,8,0,0,-1,1,2},{14,0,0,24,10,9,-1,1,5},{14,0,0,24,10,9,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,12},{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,4},{0,0,0,29,9,9,-1,1,4},{0,0,0,1,18,10,-1,1,28},{1,0,0,1,18,1,-1,1,9},{1,0,0,1,18,1,-1,1,9},{0,0,0,1,0,10,-1,1,9},{0,0,0,1,1,10,-1,1,9}},
- {{0,0,0,17,10,1,-1,1,4},{0,0,0,17,10,9,-1,1,12},{0,0,0,17,10,8,-1,1,4},{0,0,0,17,10,8,-1,1,4},{0,0,0,17,10,8,-1,1,3},{0,0,0,17,10,8,-1,1,1},{0,0,0,21,10,8,-1,0,1},{0,0,0,21,10,9,-1,1,2},{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,1,-1,1,23},{0,0,0,22,10,8,-1,1,20},{0,0,0,20,10,8,-1,1,23},{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,8,-1,1,23},{0,0,0,22,10,8,-1,1,20},{0,0,0,20,10,8,-1,1,23}},
- {{0,0,0,21,10,8,-1,0,1},{0,0,0,21,10,8,-1,0,1},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,9,-1,1,15},{0,0,0,21,10,9,-1,1,15},{0,0,0,21,10,9,-1,1,15},{0,0,0,21,10,1,-1,1,4},{0,0,0,27,9,8,-1,1,6},{0,0,0,28,7,8,-1,1,6},{0,0,0,1,11,10,-1,1,9},{0,0,0,1,14,10,-1,1,9},{0,0,0,1,16,10,-1,1,9},{0,0,0,1,12,10,-1,1,9},{0,0,0,1,15,10,-1,1,9},{0,0,0,29,6,9,-1,1,12}},
- {{0,0,0,21,4,8,-1,0,21},{0,0,0,21,4,8,-1,0,21},{0,0,0,21,4,8,-1,1,21},{0,0,0,21,4,9,-1,1,21},{0,0,0,21,4,9,-1,1,21},{0,0,0,21,10,8,-1,1,21},{0,0,0,21,10,9,-1,1,21},{0,0,0,21,10,9,-1,1,21},{0,0,0,21,10,8,-1,1,2},{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,8,-1,1,23},{0,0,0,21,10,8,-1,0,1},{0,0,0,21,10,9,-1,0,18},{0,0,0,21,10,8,-1,1,18},{0,0,0,21,10,9,-1,1,2},{0,0,0,16,10,3,-1,1,2}},
- {{0,0,0,16,10,3,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,0,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,25,6,8,-1,1,16},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,0,0,21,10,9,-1,0,18},{0,0,0,21,10,9,-1,0,18},{0,0,0,21,10,9,-1,0,18},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2}},
- {{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,0,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,16,10,2,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,9,-1,1,2},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,29,9,9,-1,1,4}},
- {{0,0,0,1,18,10,-1,1,30},{0,0,0,1,18,10,-1,1,2},{0,0,0,1,18,10,-1,1,2},{0,0,0,1,18,10,-1,1,2},{0,0,0,1,18,10,-1,1,2},{103,0,0,2,0,12,-1,0,0},{0,0,0,1,20,10,-1,1,9},{0,0,0,1,21,10,-1,1,9},{0,0,0,1,19,10,-1,1,9},{0,0,0,1,22,10,-1,1,9},{0,0,0,1,18,11,-1,1,9},{0,0,0,1,18,11,-1,1,9},{0,0,0,1,18,11,-1,1,9},{0,0,0,1,18,11,-1,1,9},{0,0,0,1,18,11,-1,1,9},{0,0,0,1,18,11,-1,1,9}},
- {{0,0,0,15,2,9,0,1,2},{25,0,0,6,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,15,2,9,4,1,1},{0,0,0,15,2,9,5,1,2},{0,0,0,15,2,9,6,1,2},{0,0,0,15,2,9,7,1,2},{0,0,0,15,2,9,8,1,2},{0,0,0,15,2,9,9,1,2},{0,0,0,25,3,9,-1,1,2},{0,0,0,25,3,9,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,1,0,22,10,9,-1,1,20},{0,2,0,18,10,9,-1,1,8},{25,0,0,6,0,9,-1,1,1}},
- {{0,0,0,15,2,9,0,1,2},{0,0,0,15,2,9,1,1,1},{0,0,0,15,2,9,2,1,1},{0,0,0,15,2,9,3,1,1},{0,0,0,15,2,9,4,1,1},{0,0,0,15,2,9,5,1,2},{0,0,0,15,2,9,6,1,2},{0,0,0,15,2,9,7,1,2},{0,0,0,15,2,9,8,1,2},{0,0,0,15,2,9,9,1,2},{0,0,0,25,3,9,-1,1,2},{0,0,0,25,3,9,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,1,0,22,10,9,-1,1,20},{0,2,0,18,10,9,-1,1,8},{103,0,0,2,0,12,-1,1,0}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,21},{0,0,0,23,4,9,-1,1,22},{0,0,1,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22}},
- {{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,21},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,21},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,22},{0,0,0,23,4,8,-1,1,21},{103,0,0,2,4,12,-1,1,22}},
- {{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22},{103,0,0,2,4,12,-1,1,22}},
- {{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,11,17,8,-1,0,9},{1,0,0,11,17,8,-1,0,9},{1,0,0,11,17,8,-1,0,9}},
- {{1,0,0,11,17,8,-1,0,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,11,17,8,-1,0,9},{1,0,0,11,17,8,-1,0,9},{1,0,0,11,17,8,-1,0,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9},{1,0,0,12,17,7,-1,1,9}},
- {{1,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,10,9,-1,0,2},{0,0,0,26,10,9,-1,0,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,26,10,9,-1,0,21},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,9,-1,0,1},{0,0,0,26,10,9,-1,0,2},{0,0,0,9,0,9,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,9,-1,0,21},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,0,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,26,10,9,-1,0,22},{0,0,0,26,10,8,-1,0,2},{0,0,0,25,10,3,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,9,-1,0,2},{0,0,0,26,10,9,-1,0,1},{0,0,0,26,10,9,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,26,10,8,-1,0,2},{14,0,0,9,0,9,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,26,10,8,-1,0,2},{25,0,0,9,0,9,-1,1,2},{25,0,0,9,0,9,-1,1,1},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,26,4,3,-1,0,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{25,0,0,9,0,4,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,7,0,9,-1,0,2},{0,0,0,7,0,9,-1,0,2},{0,0,0,7,0,9,-1,0,2},{0,0,0,7,0,9,-1,0,2},{0,0,0,5,0,9,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,9,-1,0,2},{0,0,0,5,0,9,-1,0,2},{0,0,0,5,0,9,-1,0,2},{0,0,0,9,0,9,-1,0,2},{0,0,0,9,0,9,-1,0,2}},
- {{0,0,0,25,10,9,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,9,0,9,-1,0,2},{0,0,0,5,0,9,-1,0,2},{0,0,0,5,0,9,-1,0,2},{0,0,0,5,0,9,-1,0,2},{0,0,0,5,0,9,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{25,0,0,5,0,4,-1,1,2},{0,0,0,26,0,8,-1,0,2}},
- {{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,2},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,2}},
- {{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,2},{25,0,0,14,0,9,-1,0,2},{25,0,0,14,0,9,-1,0,2},{25,0,0,14,0,9,-1,0,2}},
- {{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,1},{25,0,0,14,0,9,-1,0,2},{25,0,0,14,0,9,-1,0,2},{25,0,0,14,0,9,-1,0,2},{25,0,0,14,0,9,-1,0,2},{25,0,0,14,0,9,-1,0,2},{25,0,0,14,0,9,-1,0,2}},
- {{25,0,0,14,0,4,-1,0,2},{25,0,0,14,0,4,-1,0,2},{25,0,0,14,0,4,-1,0,2},{25,0,0,9,0,4,-1,0,2},{25,0,0,5,0,4,-1,0,2},{25,0,0,14,0,4,-1,0,2},{25,0,0,14,0,4,-1,0,2},{25,0,0,14,0,4,-1,0,2},{25,0,0,14,0,4,-1,0,2},{0,0,0,15,10,9,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,3,8,-1,1,22},{0,0,0,25,4,8,-1,1,22},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,0,1},{0,0,0,25,10,8,-1,1,1}},
- {{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,9,-1,1,1},{0,0,0,25,10,9,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,9,-1,1,2}},
- {{0,0,0,25,10,9,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,0,1},{0,0,0,25,10,8,-1,0,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,1}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,15}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,1,1,22,10,11,-1,3,20},{0,2,1,18,10,11,-1,3,8},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2}},
- {{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2}},
- {{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,15,10,9,1,0,1},{0,0,0,15,10,9,2,0,1},{0,0,0,15,10,9,3,0,1},{0,0,0,15,10,9,4,0,1},{0,0,0,15,10,9,5,0,1},{0,0,0,15,10,9,6,0,1},{0,0,0,15,10,9,7,0,1},{0,0,0,15,10,9,8,0,1},{0,0,0,15,10,9,9,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1}},
- {{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,1,0,1},{0,0,0,15,10,9,2,0,1},{0,0,0,15,10,9,3,0,1},{0,0,0,15,10,9,4,0,1},{0,0,0,15,10,9,5,0,1},{0,0,0,15,10,9,6,0,1},{0,0,0,15,10,9,7,0,1},{0,0,0,15,10,9,8,0,1},{0,0,0,15,10,9,9,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1}},
- {{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,10,9,-1,0,1},{0,0,0,15,2,9,1,0,1},{0,0,0,15,2,9,2,0,1},{0,0,0,15,2,9,3,0,1},{0,0,0,15,2,9,4,0,1},{0,0,0,15,2,9,5,0,1},{0,0,0,15,2,9,6,0,1},{0,0,0,15,2,9,7,0,1},{0,0,0,15,2,9,8,0,1}},
- {{0,0,0,15,2,9,9,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,15,2,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1}},
- {{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1}},
- {{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,15,10,9,0,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1}},
- {{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,1,0,1},{0,0,0,15,10,8,2,0,1},{0,0,0,15,10,8,3,0,1},{0,0,0,15,10,8,4,0,1},{0,0,0,15,10,8,5,0,1},{0,0,0,15,10,8,6,0,1},{0,0,0,15,10,8,7,0,1},{0,0,0,15,10,8,8,0,1},{0,0,0,15,10,8,9,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,0,0,2}},
- {{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1}},
- {{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,1},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,25,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,1},{0,0,0,25,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1}},
- {{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,25,10,8,-1,0,1}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1}},
- {{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,23},{0,0,0,26,10,8,-1,0,23},{0,0,0,26,10,8,-1,0,23},{0,0,0,26,10,8,-1,0,23},{0,0,0,26,10,8,-1,0,23}},
- {{0,0,0,26,10,8,-1,0,23},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,11},{0,0,0,26,10,8,-1,0,11},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8}},
- {{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,0,0,15,10,8,1,0,1},{0,0,0,15,10,8,2,0,1},{0,0,0,15,10,8,3,0,1},{0,0,0,15,10,8,4,0,1},{0,0,0,15,10,8,5,0,1},{0,0,0,15,10,8,6,0,1},{0,0,0,15,10,8,7,0,1},{0,0,0,15,10,8,8,0,1},{0,0,0,15,10,8,9,0,1},{0,0,0,15,10,8,-1,0,1}},
- {{0,0,0,15,10,8,1,0,1},{0,0,0,15,10,8,2,0,1},{0,0,0,15,10,8,3,0,1},{0,0,0,15,10,8,4,0,1},{0,0,0,15,10,8,5,0,1},{0,0,0,15,10,8,6,0,1},{0,0,0,15,10,8,7,0,1},{0,0,0,15,10,8,8,0,1},{0,0,0,15,10,8,9,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,1,0,1},{0,0,0,15,10,8,2,0,1},{0,0,0,15,10,8,3,0,1},{0,0,0,15,10,8,4,0,1},{0,0,0,15,10,8,5,0,1},{0,0,0,15,10,8,6,0,1}},
- {{0,0,0,15,10,8,7,0,1},{0,0,0,15,10,8,8,0,1},{0,0,0,15,10,8,9,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8}},
- {{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2},{46,0,0,26,0,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20}},
- {{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,25,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,0,1},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2}},
- {{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{56,0,0,9,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2}},
- {{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{56,0,0,5,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{25,0,0,9,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,9,0,3,-1,1,2},{25,0,0,9,0,3,-1,1,2},{25,0,0,9,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2}},
- {{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,5,0,3,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2}},
- {{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2}},
- {{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,26,10,8,-1,1,2},{7,0,0,26,10,8,-1,1,2},{7,0,0,26,10,8,-1,1,2},{7,0,0,26,10,8,-1,1,2},{7,0,0,26,10,8,-1,1,2},{7,0,0,26,10,8,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{7,0,0,12,17,7,-1,1,9}},
- {{7,0,0,12,17,7,-1,1,9},{7,0,0,12,17,7,-1,1,9},{7,0,0,9,0,7,-1,1,2},{7,0,0,5,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{7,0,0,21,10,8,-1,1,11},{7,0,0,21,10,8,-1,1,4},{7,0,0,21,10,8,-1,1,4},{7,0,0,21,10,8,-1,1,4},{7,0,0,15,10,8,-1,1,2},{7,0,0,21,10,8,-1,1,11},{7,0,0,21,10,8,-1,1,4}},
- {{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2}},
- {{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{12,0,0,5,0,4,-1,1,2},{103,0,0,2,0,12,-1,1,0},{12,0,0,5,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{12,0,0,5,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2}},
- {{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{60,0,0,7,0,5,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{60,0,0,6,0,9,-1,1,2}},
- {{60,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{60,0,0,12,17,5,-1,1,9}},
- {{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9},{8,0,0,12,17,4,-1,1,9}},
- {{0,0,0,21,10,8,-1,1,23},{0,0,0,21,10,8,-1,1,23},{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,8,-1,1,23},{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,8,-1,1,23},{0,0,0,21,10,8,-1,1,23},{0,0,0,21,10,8,-1,1,23},{0,0,0,21,10,8,-1,1,23},{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,8,-1,1,23},{0,0,0,21,10,8,-1,1,23},{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,8,-1,1,23},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4}},
- {{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,2},{0,0,0,17,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,20},{0,0,0,21,10,8,-1,1,4},{0,0,0,17,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,8,-1,1,23},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2}},
- {{0,0,0,20,10,8,-1,1,23},{0,0,0,19,10,8,-1,1,23},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,1,0,22,10,8,-1,1,20},{0,2,0,18,10,8,-1,1,8},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,11},{0,0,0,6,10,8,-1,1,2}},
- {{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,21,10,8,-1,1,2},{0,0,0,17,10,8,-1,1,3},{0,0,0,17,10,8,-1,1,3},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,2}},
- {{0,0,0,17,10,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,22,10,8,-1,1,20},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14}},
- {{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,9,-1,0,14}},
- {{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,8,-1,0,14},{17,0,1,26,10,9,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14}},
- {{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{17,0,1,26,10,9,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,1,29,9,9,-1,0,4},{0,0,1,21,10,8,-1,2,8},{0,0,1,21,10,8,-1,2,8},{0,0,1,21,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{17,0,1,6,0,0,-1,0,18},{0,0,1,7,0,0,-1,0,14},{17,0,1,14,0,0,-1,0,14},{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8},{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8},{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8},{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8}},
- {{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8},{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8},{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8},{0,1,1,22,10,8,-1,3,20},{0,2,1,18,10,8,-1,3,8},{0,0,1,17,10,8,-1,3,18},{0,0,1,22,10,8,-1,3,20},{0,0,1,18,10,8,-1,3,8},{0,0,1,18,10,8,-1,3,8}},
- {{0,0,1,26,10,8,-1,0,14},{17,0,1,14,0,3,-1,0,14},{17,0,1,14,0,3,-1,0,14},{17,0,1,14,0,3,-1,0,14},{17,0,1,14,0,3,-1,0,14},{17,0,1,14,0,3,-1,0,14},{17,0,1,14,0,3,-1,0,14},{17,0,1,14,0,3,-1,0,14},{17,0,1,14,0,3,-1,0,14},{17,0,1,14,0,3,-1,0,14},{1,0,1,12,17,3,-1,0,9},{1,0,1,12,17,3,-1,0,9},{1,0,1,12,17,3,-1,0,9},{1,0,1,12,17,3,-1,0,9},{18,0,1,10,0,4,-1,0,9},{18,0,1,10,0,4,-1,0,9}},
- {{0,0,1,17,10,8,-1,3,14},{0,0,1,6,0,3,-1,0,14},{0,0,1,6,0,3,-1,0,14},{0,0,1,6,0,3,-1,0,14},{0,0,1,6,0,3,-1,0,14},{0,0,1,6,0,3,-1,0,9},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,10,8,-1,0,14},{17,0,1,14,0,9,-1,0,14},{17,0,1,14,0,9,-1,0,14},{17,0,1,14,0,9,-1,0,14},{17,0,1,6,0,3,-1,0,18},{0,0,1,7,0,3,-1,0,18},{0,0,1,21,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{103,0,0,2,0,12,-1,0,0},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14}},
- {{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14}},
- {{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14}},
- {{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,0,14}},
- {{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,0,14},{20,0,1,7,0,0,-1,2,37},{20,0,1,7,0,0,-1,2,37},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{1,0,1,12,17,0,-1,0,9},{1,0,1,12,17,0,-1,0,9},{0,0,1,24,10,9,-1,2,18},{0,0,1,24,10,9,-1,2,18},{20,0,1,6,0,0,-1,0,18},{20,0,1,6,0,0,-1,0,18},{20,0,1,7,0,9,-1,0,14}},
- {{0,0,1,17,10,1,-1,3,18},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14}},
- {{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14}},
- {{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14}},
- {{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14}},
- {{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,2,37},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{22,0,1,7,0,0,-1,0,14},{0,0,1,21,10,1,-1,0,18},{0,0,1,6,0,0,-1,3,37},{22,0,1,6,0,0,-1,0,18},{22,0,1,6,0,0,-1,0,18},{22,0,1,7,0,9,-1,0,14}},
- {{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14}},
- {{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14}},
- {{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,2,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{103,0,0,2,0,12,-1,0,0},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14}},
- {{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14}},
- {{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,10,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14}},
- {{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{18,0,1,7,0,9,-1,0,14},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,1,26,0,8,-1,0,14},{0,0,1,26,0,8,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14}},
- {{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{5,0,1,7,0,0,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14}},
- {{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{0,0,1,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37},{22,0,1,7,0,3,-1,2,37}},
- {{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14}},
- {{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,10,9,-1,0,14},{18,0,1,26,10,9,-1,0,14},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,15,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,0,15,0,8,-1,0,1},{0,0,0,15,0,8,-1,0,1},{0,0,0,15,0,8,-1,0,1},{0,0,0,15,0,8,-1,0,1},{0,0,0,15,0,8,-1,0,1},{0,0,0,15,0,8,-1,0,1},{0,0,0,15,0,8,-1,0,1},{0,0,0,15,0,8,-1,0,1}},
- {{0,0,1,26,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14}},
- {{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,0,9,-1,0,14},{18,0,1,26,10,9,-1,0,14},{18,0,1,26,10,9,-1,0,14},{18,0,1,26,10,9,-1,0,14},{0,0,1,26,0,8,-1,0,14}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14},{0,0,1,15,10,9,-1,0,14}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,10,9,-1,0,14}},
- {{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14}},
- {{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{22,0,1,26,0,9,-1,0,14},{103,0,0,2,0,12,-1,0,0}},
- {{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14}},
- {{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{22,0,1,26,0,9,-1,2,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,0,9,-1,2,14},{0,0,1,26,0,9,-1,2,14},{0,0,1,26,0,9,-1,2,14},{0,0,1,26,0,9,-1,2,14},{0,0,1,26,0,9,-1,2,14}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,26,10,9,-1,0,14}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,10,9,-1,0,14}},
- {{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14}},
- {{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14}},
- {{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14}},
- {{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14}},
- {{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,6,0,5,-1,0,18},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14}},
- {{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{41,0,1,7,0,5,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14}},
- {{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{41,0,1,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2}},
- {{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,7,0,6,-1,1,2},{131,0,0,6,0,6,-1,1,2},{131,0,0,6,0,6,-1,1,2},{131,0,0,6,0,6,-1,1,2},{131,0,0,6,0,6,-1,1,2},{131,0,0,6,0,6,-1,1,2},{131,0,0,6,0,6,-1,1,2},{131,0,0,21,0,8,-1,1,4},{131,0,0,21,0,8,-1,1,4}},
- {{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2}},
- {{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{99,0,0,6,0,6,-1,1,2},{99,0,0,21,10,8,-1,1,4},{99,0,0,21,10,8,-1,1,11},{99,0,0,21,10,8,-1,1,4}},
- {{99,0,0,13,0,6,0,1,19},{99,0,0,13,0,6,1,1,19},{99,0,0,13,0,6,2,1,19},{99,0,0,13,0,6,3,1,19},{99,0,0,13,0,6,4,1,19},{99,0,0,13,0,6,5,1,19},{99,0,0,13,0,6,6,1,19},{99,0,0,13,0,6,7,1,19},{99,0,0,13,0,6,8,1,19},{99,0,0,13,0,6,9,1,19},{99,0,0,7,0,6,-1,1,2},{99,0,0,7,0,6,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{8,0,0,9,0,0,-1,1,2},{8,0,0,5,0,0,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,7,0,4,-1,1,2},{8,0,0,12,17,2,-1,1,9}},
- {{8,0,0,11,17,8,-1,1,9},{8,0,0,11,17,8,-1,1,9},{8,0,0,11,17,8,-1,1,9},{8,0,0,21,10,8,-1,1,2},{8,0,0,12,17,0,-1,1,9},{8,0,0,12,17,0,-1,1,9},{8,0,0,12,17,0,-1,1,9},{8,0,0,12,17,0,-1,1,9},{8,0,0,12,17,0,-1,1,9},{8,0,0,12,17,0,-1,1,9},{8,0,0,12,17,0,-1,1,9},{8,0,0,12,17,0,-1,1,9},{8,0,0,12,17,2,-1,1,9},{8,0,0,12,17,2,-1,1,9},{8,0,0,21,10,8,-1,1,2},{8,0,0,6,10,0,-1,1,2}},
- {{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,9,0,4,-1,1,2},{8,0,0,5,0,4,-1,1,2},{8,0,0,6,0,9,-1,1,2},{8,0,0,6,0,9,-1,1,2},{8,0,0,12,17,2,-1,1,9},{8,0,0,12,17,0,-1,1,9}},
- {{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2}},
- {{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2},{130,0,0,14,0,6,-1,1,2}},
- {{130,0,0,12,17,6,-1,1,9},{130,0,0,12,17,6,-1,1,9},{130,0,0,21,0,8,-1,1,2},{130,0,0,21,0,8,-1,1,4},{130,0,0,21,0,8,-1,1,4},{130,0,0,21,0,8,-1,1,4},{130,0,0,21,0,8,-1,1,4},{130,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,6,10,0,-1,1,2}},
- {{0,0,0,24,10,8,-1,1,2},{0,0,0,24,10,8,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2}},
- {{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2}},
- {{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2}},
- {{25,0,0,6,0,9,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2}},
- {{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{0,0,0,6,10,0,-1,1,2},{0,0,0,24,0,8,-1,1,2},{0,0,0,24,0,8,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,7,0,2,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2}},
- {{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,9,0,0,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,4,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,9,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{25,0,0,7,0,4,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,5,0,0,-1,1,2},{25,0,0,7,0,4,-1,1,2},{25,0,0,7,0,4,-1,1,2},{25,0,0,7,0,4,-1,1,2},{25,0,0,7,0,4,-1,1,2},{25,0,0,7,0,4,-1,1,2}},
- {{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,12,17,6,-1,1,9},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,12,17,6,-1,1,9},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,12,17,6,-1,1,9},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2}},
- {{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2}},
- {{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,7,0,6,-1,1,2},{58,0,0,10,0,6,-1,1,9},{58,0,0,10,0,6,-1,1,9},{58,0,0,12,17,6,-1,1,9},{58,0,0,12,17,6,-1,1,9},{58,0,0,10,0,6,-1,1,9},{58,0,0,26,10,8,-1,1,2},{58,0,0,26,10,8,-1,1,2},{58,0,0,26,10,8,-1,1,2},{58,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,23,4,8,-1,1,21},{0,0,0,26,4,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2}},
- {{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,7,0,7,-1,1,2},{90,0,0,21,10,8,-1,1,5},{90,0,0,21,10,8,-1,1,5},{90,0,0,21,10,8,-1,1,11},{90,0,0,21,10,8,-1,1,11},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2}},
- {{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2}},
- {{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,7,0,6,-1,1,2},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9}},
- {{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,10,0,6,-1,1,9},{111,0,0,12,17,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{111,0,0,21,0,8,-1,1,4},{111,0,0,21,0,8,-1,1,4}},
- {{111,0,0,13,0,6,0,1,19},{111,0,0,13,0,6,1,1,19},{111,0,0,13,0,6,2,1,19},{111,0,0,13,0,6,3,1,19},{111,0,0,13,0,6,4,1,19},{111,0,0,13,0,6,5,1,19},{111,0,0,13,0,6,6,1,19},{111,0,0,13,0,6,7,1,19},{111,0,0,13,0,6,8,1,19},{111,0,0,13,0,6,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9}},
- {{10,0,0,12,17,4,-1,1,9},{10,0,0,12,17,4,-1,1,9},{10,0,0,7,0,4,-1,1,2},{10,0,0,7,0,4,-1,1,2},{10,0,0,7,0,4,-1,1,2},{10,0,0,7,0,4,-1,1,2},{10,0,0,7,0,4,-1,1,2},{10,0,0,7,0,4,-1,1,2},{10,0,0,21,0,8,-1,1,2},{10,0,0,21,0,8,-1,1,2},{10,0,0,21,0,8,-1,1,2},{10,0,0,7,0,4,-1,1,2},{10,0,0,21,0,8,-1,1,5},{10,0,0,7,0,4,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{79,0,0,13,0,6,0,1,19},{79,0,0,13,0,6,1,1,19},{79,0,0,13,0,6,2,1,19},{79,0,0,13,0,6,3,1,19},{79,0,0,13,0,6,4,1,19},{79,0,0,13,0,6,5,1,19},{79,0,0,13,0,6,6,1,19},{79,0,0,13,0,6,7,1,19},{79,0,0,13,0,6,8,1,19},{79,0,0,13,0,6,9,1,19},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2}},
- {{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2}},
- {{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,7,0,6,-1,1,2},{79,0,0,12,17,6,-1,1,9},{79,0,0,12,17,6,-1,1,9},{79,0,0,12,17,6,-1,1,9},{79,0,0,12,17,6,-1,1,9},{79,0,0,12,17,6,-1,1,9},{79,0,0,12,17,6,-1,1,9},{79,0,0,12,17,6,-1,1,9},{79,0,0,12,17,6,-1,1,9},{0,0,0,21,0,8,-1,1,4},{79,0,0,21,0,8,-1,1,4}},
- {{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2}},
- {{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,7,0,7,-1,1,2},{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9}},
- {{110,0,0,12,17,7,-1,1,9},{110,0,0,12,17,7,-1,1,9},{110,0,0,10,0,7,-1,1,9},{110,0,0,10,0,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{110,0,0,21,0,8,-1,1,2}},
- {{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{18,0,1,7,0,4,-1,0,33},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{78,0,0,12,17,6,-1,1,9},{78,0,0,12,17,6,-1,1,9},{78,0,0,12,17,6,-1,1,9},{78,0,0,10,0,6,-1,1,9},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2}},
- {{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2}},
- {{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,7,0,6,-1,1,2},{78,0,0,12,17,6,-1,1,9},{78,0,0,10,0,6,-1,1,9},{78,0,0,10,0,6,-1,1,9},{78,0,0,12,17,6,-1,1,9},{78,0,0,12,17,6,-1,1,9},{78,0,0,12,17,6,-1,1,9},{78,0,0,12,17,6,-1,1,9},{78,0,0,10,0,6,-1,1,9},{78,0,0,10,0,6,-1,1,9},{78,0,0,12,17,6,-1,1,9},{78,0,0,10,0,6,-1,1,9},{78,0,0,10,0,6,-1,1,9},{78,0,0,10,0,6,-1,1,9}},
- {{78,0,0,10,0,6,-1,1,9},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,4},{78,0,0,21,0,8,-1,1,4},{78,0,0,21,0,8,-1,1,4},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,6,0,7,-1,1,2}},
- {{78,0,0,13,0,6,0,1,19},{78,0,0,13,0,6,1,1,19},{78,0,0,13,0,6,2,1,19},{78,0,0,13,0,6,3,1,19},{78,0,0,13,0,6,4,1,19},{78,0,0,13,0,6,5,1,19},{78,0,0,13,0,6,6,1,19},{78,0,0,13,0,6,7,1,19},{78,0,0,13,0,6,8,1,19},{78,0,0,13,0,6,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{78,0,0,21,0,8,-1,1,2},{78,0,0,21,0,8,-1,1,2}},
- {{28,0,0,7,0,4,-1,1,24},{28,0,0,7,0,4,-1,1,24},{28,0,0,7,0,4,-1,1,24},{28,0,0,7,0,4,-1,1,24},{28,0,0,7,0,4,-1,1,24},{28,0,0,12,17,4,-1,1,24},{28,0,0,6,0,4,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24}},
- {{28,0,0,13,0,0,0,1,19},{28,0,0,13,0,0,1,1,19},{28,0,0,13,0,0,2,1,19},{28,0,0,13,0,0,3,1,19},{28,0,0,13,0,0,4,1,19},{28,0,0,13,0,0,5,1,19},{28,0,0,13,0,0,6,1,19},{28,0,0,13,0,0,7,1,19},{28,0,0,13,0,0,8,1,19},{28,0,0,13,0,0,9,1,19},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{103,0,0,2,0,12,-1,1,0}},
- {{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2}},
- {{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,12,17,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{66,0,0,10,0,6,-1,1,9}},
- {{66,0,0,10,0,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{66,0,0,10,0,6,-1,1,9},{66,0,0,10,0,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{66,0,0,12,17,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,12,17,6,-1,1,9},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,7,0,6,-1,1,2},{66,0,0,12,17,6,-1,1,9},{66,0,0,10,0,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{66,0,0,13,0,6,0,1,19},{66,0,0,13,0,6,1,1,19},{66,0,0,13,0,6,2,1,19},{66,0,0,13,0,6,3,1,19},{66,0,0,13,0,6,4,1,19},{66,0,0,13,0,6,5,1,19},{66,0,0,13,0,6,6,1,19},{66,0,0,13,0,6,7,1,19},{66,0,0,13,0,6,8,1,19},{66,0,0,13,0,6,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{66,0,0,21,0,8,-1,1,2},{66,0,0,21,0,8,-1,1,4},{66,0,0,21,0,8,-1,1,4},{66,0,0,21,0,8,-1,1,4}},
- {{28,0,0,6,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,26,0,8,-1,1,24},{28,0,0,26,0,8,-1,1,24},{28,0,0,26,0,8,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,12,17,0,-1,1,24},{28,0,0,10,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24},{28,0,0,7,0,0,-1,1,24}},
- {{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24}},
- {{127,0,0,12,17,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,12,17,6,-1,1,24},{127,0,0,12,17,6,-1,1,24},{127,0,0,12,17,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,12,17,6,-1,1,24},{127,0,0,12,17,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,12,17,6,-1,1,24},{127,0,0,12,17,6,-1,1,24}},
- {{127,0,0,7,0,6,-1,1,24},{127,0,0,12,17,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{127,0,0,7,0,6,-1,1,24},{127,0,0,7,0,6,-1,1,24},{127,0,0,6,0,6,-1,1,24},{127,0,0,21,0,8,-1,1,24},{127,0,0,21,0,8,-1,1,24}},
- {{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,10,0,6,-1,1,9},{115,0,0,12,17,6,-1,1,9},{115,0,0,12,17,6,-1,1,9},{115,0,0,10,0,6,-1,1,9},{115,0,0,10,0,6,-1,1,9}},
- {{115,0,0,21,0,8,-1,1,4},{115,0,0,21,0,8,-1,1,4},{115,0,0,7,0,6,-1,1,2},{115,0,0,6,0,6,-1,1,2},{115,0,0,6,0,6,-1,1,2},{115,0,0,10,0,6,-1,1,9},{115,0,0,12,17,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{11,0,0,7,0,0,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2}},
- {{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{25,0,0,5,0,4,-1,1,2},{0,0,0,24,0,8,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2},{25,0,0,6,0,9,-1,1,2}},
- {{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,2,-1,1,2},{25,0,0,5,0,4,-1,1,2},{14,0,0,5,0,4,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2},{6,0,0,5,0,6,-1,1,2}},
- {{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2}},
- {{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,7,0,6,-1,1,2},{115,0,0,10,0,6,-1,1,9},{115,0,0,10,0,6,-1,1,9},{115,0,0,12,17,6,-1,1,9},{115,0,0,10,0,6,-1,1,9},{115,0,0,10,0,6,-1,1,9},{115,0,0,12,17,6,-1,1,9},{115,0,0,10,0,6,-1,1,9},{115,0,0,10,0,6,-1,1,9},{115,0,0,21,0,8,-1,1,4},{115,0,0,10,0,6,-1,1,9},{115,0,0,12,17,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{115,0,0,13,0,6,0,1,19},{115,0,0,13,0,6,1,1,19},{115,0,0,13,0,6,2,1,19},{115,0,0,13,0,6,3,1,19},{115,0,0,13,0,6,4,1,19},{115,0,0,13,0,6,5,1,19},{115,0,0,13,0,6,6,1,19},{115,0,0,13,0,6,7,1,19},{115,0,0,13,0,6,8,1,19},{115,0,0,13,0,6,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{18,0,1,7,0,0,-1,0,31},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32}},
- {{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,31},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32}},
- {{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32}},
- {{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,31},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32}},
- {{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,31},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32}},
- {{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{18,0,1,7,0,0,-1,0,32},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{18,0,0,7,0,4,-1,0,35},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34}},
- {{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{18,0,0,7,0,4,-1,0,34},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25},{103,0,0,4,0,12,-1,1,25}},
- {{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0}},
- {{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14}},
- {{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14}},
- {{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,0,-1,0,14}},
- {{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14}},
- {{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14}},
- {{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{17,0,1,7,0,9,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14}},
- {{25,0,0,5,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{25,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{3,0,0,5,0,9,-1,1,2},{3,0,0,5,0,9,-1,1,2},{3,0,0,5,0,9,-1,1,2},{3,0,0,5,0,9,-1,1,2},{3,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{19,0,0,7,1,9,-1,1,38},{19,0,0,12,17,3,-1,1,9},{19,0,0,7,1,9,-1,1,38}},
- {{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,25,3,9,-1,1,2},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38}},
- {{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{103,0,0,2,1,12,-1,1,0},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{103,0,0,2,1,12,-1,1,0},{19,0,0,7,1,9,-1,1,38},{103,0,0,2,1,12,-1,1,0}},
- {{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{103,0,0,2,1,12,-1,1,0},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{103,0,0,2,1,12,-1,1,0},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38},{19,0,0,7,1,9,-1,1,38}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2}},
- {{2,0,0,24,13,8,-1,1,2},{2,0,0,24,13,8,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{0,0,0,18,10,8,-1,1,8},{0,0,0,22,10,8,-1,1,20}},
- {{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,23,13,9,-1,1,21},{2,0,0,26,10,8,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9},{1,0,0,12,17,10,-1,1,9}},
- {{0,0,1,21,10,9,-1,0,16},{0,0,1,21,10,9,-1,0,8},{0,0,1,21,10,9,-1,0,8},{0,0,1,21,10,9,-1,0,16},{0,0,1,21,10,9,-1,0,16},{0,0,1,21,10,9,-1,0,11},{0,0,1,21,10,9,-1,0,11},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,21,10,9,-1,0,15},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{1,0,0,12,17,3,-1,1,9},{8,0,0,12,17,3,-1,1,9},{8,0,0,12,17,3,-1,1,9}},
- {{0,0,1,21,10,9,-1,0,14},{0,0,1,17,10,9,-1,0,14},{0,0,1,17,10,9,-1,0,14},{0,0,1,16,10,9,-1,0,14},{0,0,1,16,10,9,-1,0,14},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,22,10,9,-1,0,20}},
- {{0,0,1,18,10,9,-1,0,8},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,21,10,8,-1,0,14},{0,0,1,21,10,8,-1,0,14},{0,0,1,22,10,9,-1,0,20},{0,0,1,18,10,9,-1,0,8},{0,0,1,21,10,9,-1,1,14},{0,0,1,21,10,9,-1,1,14},{0,0,1,21,10,9,-1,1,14},{0,0,1,21,10,9,-1,1,14},{0,0,1,16,10,9,-1,1,14},{0,0,1,16,10,9,-1,1,14},{0,0,1,16,10,9,-1,1,14}},
- {{0,0,1,21,6,9,-1,2,8},{0,0,1,21,10,9,-1,2,14},{0,0,1,21,6,9,-1,2,8},{103,0,0,2,0,12,-1,0,0},{0,0,1,21,10,9,-1,0,18},{0,0,1,21,6,9,-1,0,18},{0,0,1,21,10,9,-1,0,11},{0,0,1,21,10,9,-1,0,11},{0,0,1,17,10,9,-1,1,14},{0,1,1,22,10,9,-1,3,20},{0,2,1,18,10,9,-1,3,8},{0,1,1,22,10,9,-1,3,20},{0,2,1,18,10,9,-1,3,8},{0,1,1,22,10,9,-1,3,20},{0,2,1,18,10,9,-1,3,8},{0,0,1,21,4,9,-1,0,14}},
- {{0,0,1,21,10,9,-1,0,14},{0,0,1,21,10,9,-1,0,14},{0,0,1,25,3,9,-1,0,14},{0,0,1,17,3,9,-1,1,14},{0,0,1,25,10,9,-1,1,14},{0,0,1,25,10,9,-1,1,14},{0,0,1,25,10,9,-1,1,14},{103,0,0,2,0,12,-1,0,0},{0,0,1,21,10,9,-1,0,14},{0,0,1,23,4,9,-1,0,22},{0,0,1,21,4,9,-1,0,21},{0,0,1,21,10,9,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,3,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{0,0,0,1,18,10,-1,1,30}},
- {{103,0,0,2,0,12,-1,1,0},{0,0,1,21,10,9,-1,2,11},{0,0,1,21,10,9,-1,0,14},{0,0,1,21,4,9,-1,0,14},{0,0,1,23,4,9,-1,0,22},{0,0,1,21,4,9,-1,0,21},{0,0,1,21,10,9,-1,0,14},{0,0,1,21,10,9,-1,0,14},{0,1,1,22,10,9,-1,3,20},{0,2,1,18,10,9,-1,3,8},{0,0,1,21,10,9,-1,0,14},{0,0,1,25,3,9,-1,0,14},{0,0,1,21,6,9,-1,2,8},{0,0,1,17,3,9,-1,1,14},{0,0,1,21,6,9,-1,2,8},{0,0,1,21,6,9,-1,0,14}},
- {{0,0,1,13,2,9,0,0,14},{0,0,1,13,2,9,1,0,14},{0,0,1,13,2,9,2,0,14},{0,0,1,13,2,9,3,0,14},{0,0,1,13,2,9,4,0,14},{0,0,1,13,2,9,5,0,14},{0,0,1,13,2,9,6,0,14},{0,0,1,13,2,9,7,0,14},{0,0,1,13,2,9,8,0,14},{0,0,1,13,2,9,9,0,14},{0,0,1,21,6,9,-1,3,18},{0,0,1,21,10,9,-1,3,18},{0,0,1,25,10,9,-1,1,14},{0,0,1,25,10,9,-1,1,14},{0,0,1,25,10,9,-1,1,14},{0,0,1,21,10,9,-1,2,11}},
- {{0,0,1,21,10,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14}},
- {{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{25,0,1,9,0,9,-1,0,14},{0,1,1,22,10,9,-1,3,20},{0,0,1,21,10,9,-1,0,14},{0,2,1,18,10,9,-1,3,8},{0,0,1,24,10,9,-1,0,14},{0,0,1,16,10,9,-1,3,14}},
- {{0,0,1,24,10,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14}},
- {{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{25,0,1,5,0,9,-1,0,14},{0,1,1,22,10,9,-1,3,20},{0,0,1,25,10,9,-1,3,14},{0,2,1,18,10,9,-1,3,8},{0,0,1,25,10,9,-1,3,14},{0,1,1,22,10,9,-1,3,20}},
- {{0,2,1,18,10,9,-1,3,8},{0,0,1,21,10,9,-1,1,8},{0,1,1,22,10,9,-1,1,20},{0,2,1,18,10,9,-1,1,8},{0,0,1,21,10,9,-1,1,8},{0,0,1,21,10,9,-1,1,18},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,37}},
- {{0,0,1,6,0,9,-1,1,37},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2}},
- {{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2}},
- {{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{22,0,1,7,0,9,-1,1,2},{0,0,1,6,0,9,-1,1,18},{0,0,1,6,0,9,-1,1,18}},
- {{18,0,1,7,0,10,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2}},
- {{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{18,0,1,7,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,1,23,4,9,-1,0,21},{0,0,1,23,4,9,-1,0,22},{0,0,1,25,10,9,-1,0,14},{0,0,1,24,10,9,-1,3,14},{0,0,1,26,10,9,-1,0,14},{0,0,1,23,4,9,-1,0,22},{0,0,1,23,4,9,-1,0,22},{103,0,0,2,0,12,-1,0,0},{0,0,1,26,10,9,-1,1,2},{0,0,1,25,10,9,-1,1,2},{0,0,1,25,10,9,-1,1,2},{0,0,1,25,10,9,-1,1,2},{0,0,1,25,10,9,-1,1,2},{0,0,1,26,10,9,-1,1,2},{0,0,1,26,10,9,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{0,0,0,1,10,8,-1,1,9},{0,0,0,1,10,8,-1,1,9},{0,0,0,1,10,8,-1,1,9},{0,0,0,26,10,8,-1,0,7},{0,0,0,26,10,8,-1,0,1},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2}},
- {{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2}},
- {{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2}},
- {{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{49,0,0,7,0,7,-1,1,2}},
- {{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{49,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,21,0,8,-1,1,4},{0,0,0,21,10,8,-1,1,4},{0,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2}},
- {{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2}},
- {{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{0,0,0,15,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2}},
- {{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2}},
- {{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,14,10,4,-1,1,2},{14,0,0,15,10,8,-1,1,2},{14,0,0,15,10,8,-1,1,2},{14,0,0,15,10,8,-1,1,2},{14,0,0,15,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2}},
- {{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,15,10,8,-1,1,2},{14,0,0,15,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{14,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{0,0,0,26,0,8,-1,1,2},{1,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2}},
- {{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{107,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2},{104,0,0,7,0,7,-1,1,2}},
- {{104,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{1,0,0,12,17,4,-1,1,9},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2}},
- {{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{0,0,0,15,2,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2},{30,0,0,7,0,7,-1,1,2}},
- {{30,0,0,15,0,8,-1,1,2},{30,0,0,15,0,8,-1,1,2},{30,0,0,15,0,8,-1,1,2},{30,0,0,15,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2}},
- {{13,0,0,7,0,7,-1,1,2},{13,0,0,14,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,7,0,7,-1,1,2},{13,0,0,14,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2}},
- {{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,7,0,7,-1,1,2},{89,0,0,12,17,7,-1,1,9},{89,0,0,12,17,7,-1,1,9},{89,0,0,12,17,7,-1,1,9},{89,0,0,12,17,7,-1,1,9},{89,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2}},
- {{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{53,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{53,0,0,21,0,8,-1,1,4}},
- {{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2}},
- {{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2},{61,0,0,7,0,7,-1,1,2}},
- {{61,0,0,21,0,8,-1,1,4},{61,0,0,14,0,7,-1,1,2},{61,0,0,14,0,7,-1,1,2},{61,0,0,14,0,7,-1,1,2},{61,0,0,14,0,7,-1,1,2},{61,0,0,14,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2}},
- {{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,9,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2}},
- {{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2},{9,0,0,5,0,7,-1,1,2}},
- {{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2},{51,0,0,7,0,7,-1,1,2}},
- {{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2}},
- {{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{50,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{50,0,0,13,0,7,0,1,19},{50,0,0,13,0,7,1,1,19},{50,0,0,13,0,7,2,1,19},{50,0,0,13,0,7,3,1,19},{50,0,0,13,0,7,4,1,19},{50,0,0,13,0,7,5,1,19},{50,0,0,13,0,7,6,1,19},{50,0,0,13,0,7,7,1,19},{50,0,0,13,0,7,8,1,19},{50,0,0,13,0,7,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2}},
- {{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{136,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2}},
- {{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{159,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{159,0,0,21,0,8,-1,1,2}},
- {{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2}},
- {{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{83,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{47,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2}},
- {{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2}},
- {{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{47,0,0,7,1,7,-1,1,2},{47,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{47,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{47,0,0,7,1,7,-1,1,2}},
- {{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2}},
- {{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{116,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{116,0,0,21,1,8,-1,1,4},{116,0,0,15,1,8,-1,1,2},{116,0,0,15,1,8,-1,1,2},{116,0,0,15,1,8,-1,1,2},{116,0,0,15,1,8,-1,1,2},{116,0,0,15,1,8,-1,1,2},{116,0,0,15,1,8,-1,1,2},{116,0,0,15,1,8,-1,1,2},{116,0,0,15,1,8,-1,1,2}},
- {{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2}},
- {{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,7,1,7,-1,1,2},{144,0,0,26,1,8,-1,1,2},{144,0,0,26,1,8,-1,1,2},{144,0,0,15,1,8,-1,1,2},{144,0,0,15,1,8,-1,1,2},{144,0,0,15,1,8,-1,1,2},{144,0,0,15,1,8,-1,1,2},{144,0,0,15,1,8,-1,1,2},{144,0,0,15,1,8,-1,1,2},{144,0,0,15,1,8,-1,1,2}},
- {{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2}},
- {{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{143,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0}},
- {{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{143,0,0,15,1,8,-1,1,2},{143,0,0,15,1,8,-1,1,2},{143,0,0,15,1,8,-1,1,2},{143,0,0,15,1,8,-1,1,2},{143,0,0,15,1,8,-1,1,2},{143,0,0,15,1,8,-1,1,2},{143,0,0,15,1,8,-1,1,2},{143,0,0,15,1,8,-1,1,2},{143,0,0,15,1,8,-1,1,2}},
- {{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2}},
- {{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{162,0,0,7,1,7,-1,1,2},{162,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{162,0,0,15,1,8,-1,1,2},{162,0,0,15,1,8,-1,1,2},{162,0,0,15,1,8,-1,1,2},{162,0,0,15,1,8,-1,1,2},{162,0,0,15,1,8,-1,1,2}},
- {{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2}},
- {{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,7,1,7,-1,1,2},{91,0,0,15,1,8,-1,1,2},{91,0,0,15,1,8,-1,1,2},{91,0,0,15,1,8,-1,1,2},{91,0,0,15,1,8,-1,1,2},{91,0,0,15,1,8,-1,1,2},{91,0,0,15,1,8,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{91,0,0,21,10,8,-1,1,4}},
- {{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2}},
- {{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{108,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{108,0,0,21,1,8,-1,1,2}},
- {{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2},{86,0,0,7,1,7,-1,0,2}},
- {{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2}},
- {{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,7,1,7,-1,1,2},{141,0,0,7,1,7,-1,1,2}},
- {{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2}},
- {{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2},{141,0,0,15,1,8,-1,1,2}},
- {{57,0,0,7,1,7,-1,1,2},{57,0,0,12,17,7,-1,1,9},{57,0,0,12,17,7,-1,1,9},{57,0,0,12,17,7,-1,1,9},{103,0,0,2,1,12,-1,1,0},{57,0,0,12,17,7,-1,1,9},{57,0,0,12,17,7,-1,1,9},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{57,0,0,12,17,7,-1,1,9},{57,0,0,12,17,7,-1,1,9},{57,0,0,12,17,7,-1,1,9},{57,0,0,12,17,7,-1,1,9}},
- {{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2}},
- {{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2}},
- {{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{57,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{57,0,0,12,17,7,-1,1,9},{57,0,0,12,17,7,-1,1,9},{57,0,0,12,17,7,-1,1,9},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{57,0,0,12,17,7,-1,1,9}},
- {{57,0,0,15,1,8,1,1,2},{57,0,0,15,1,8,2,1,2},{57,0,0,15,1,8,3,1,2},{57,0,0,15,1,8,4,1,2},{57,0,0,15,1,8,-1,1,2},{57,0,0,15,1,8,-1,1,2},{57,0,0,15,1,8,-1,1,2},{57,0,0,15,1,8,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{57,0,0,21,1,8,-1,1,4},{57,0,0,21,1,8,-1,1,4},{57,0,0,21,1,8,-1,1,4},{57,0,0,21,1,8,-1,1,4},{57,0,0,21,1,8,-1,1,4},{57,0,0,21,1,8,-1,1,4},{57,0,0,21,1,8,-1,1,4},{57,0,0,21,1,8,-1,1,4},{57,0,0,21,1,8,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2}},
- {{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,7,1,7,-1,1,2},{133,0,0,15,1,8,-1,1,2},{133,0,0,15,1,8,-1,1,2},{133,0,0,21,1,8,-1,1,2}},
- {{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2}},
- {{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,7,1,7,-1,1,2},{142,0,0,15,1,8,-1,1,2},{142,0,0,15,1,8,-1,1,2},{142,0,0,15,1,8,-1,1,2}},
- {{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,26,1,8,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2}},
- {{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2}},
- {{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,7,1,7,-1,1,2},{121,0,0,12,17,7,-1,1,9},{121,0,0,12,17,7,-1,1,9},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{121,0,0,15,1,8,-1,1,2},{121,0,0,15,1,8,-1,1,2},{121,0,0,15,1,8,-1,1,2},{121,0,0,15,1,8,-1,1,2},{121,0,0,15,1,8,-1,1,2}},
- {{121,0,0,21,1,8,-1,1,4},{121,0,0,21,1,8,-1,1,4},{121,0,0,21,1,8,-1,1,4},{121,0,0,21,1,8,-1,1,4},{121,0,0,21,1,8,-1,1,4},{121,0,0,21,1,8,-1,1,4},{121,0,0,21,1,8,-1,1,15},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2}},
- {{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{117,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{117,0,0,21,10,8,-1,1,4},{117,0,0,21,10,8,-1,1,4},{117,0,0,21,10,8,-1,1,4},{117,0,0,21,10,8,-1,1,4},{117,0,0,21,10,8,-1,1,4},{117,0,0,21,10,8,-1,1,4},{117,0,0,21,10,8,-1,1,4}},
- {{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2}},
- {{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{125,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{125,0,0,15,1,8,-1,1,2},{125,0,0,15,1,8,-1,1,2},{125,0,0,15,1,8,-1,1,2},{125,0,0,15,1,8,-1,1,2},{125,0,0,15,1,8,-1,1,2},{125,0,0,15,1,8,-1,1,2},{125,0,0,15,1,8,-1,1,2},{125,0,0,15,1,8,-1,1,2}},
- {{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2}},
- {{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{122,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{122,0,0,15,1,8,-1,1,2},{122,0,0,15,1,8,-1,1,2},{122,0,0,15,1,8,-1,1,2},{122,0,0,15,1,8,-1,1,2},{122,0,0,15,1,8,-1,1,2},{122,0,0,15,1,8,-1,1,2},{122,0,0,15,1,8,-1,1,2},{122,0,0,15,1,8,-1,1,2}},
- {{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2}},
- {{123,0,0,7,1,7,-1,1,2},{123,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{123,0,0,21,1,8,-1,1,2},{123,0,0,21,1,8,-1,1,2},{123,0,0,21,1,8,-1,1,2},{123,0,0,21,1,8,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{123,0,0,15,1,8,-1,1,2},{123,0,0,15,1,8,-1,1,2},{123,0,0,15,1,8,-1,1,2},{123,0,0,15,1,8,-1,1,2},{123,0,0,15,1,8,-1,1,2},{123,0,0,15,1,8,-1,1,2},{123,0,0,15,1,8,-1,1,2}},
- {{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2}},
- {{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{88,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2}},
- {{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{76,0,0,9,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2}},
- {{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{76,0,0,5,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{76,0,0,15,1,8,-1,1,2},{76,0,0,15,1,8,-1,1,2},{76,0,0,15,1,8,-1,1,2},{76,0,0,15,1,8,-1,1,2},{76,0,0,15,1,8,-1,1,2},{76,0,0,15,1,8,-1,1,2}},
- {{2,0,0,15,5,8,1,1,2},{2,0,0,15,5,8,2,1,2},{2,0,0,15,5,8,3,1,2},{2,0,0,15,5,8,4,1,2},{2,0,0,15,5,8,5,1,2},{2,0,0,15,5,8,6,1,2},{2,0,0,15,5,8,7,1,2},{2,0,0,15,5,8,8,1,2},{2,0,0,15,5,8,9,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2}},
- {{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{2,0,0,15,5,8,-1,1,2},{103,0,0,2,1,12,-1,1,0}},
- {{65,0,0,10,0,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,10,0,7,-1,1,9},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2}},
- {{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2}},
- {{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,7,0,7,-1,1,2},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9}},
- {{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,12,17,7,-1,1,9},{65,0,0,21,0,8,-1,1,4},{65,0,0,21,0,8,-1,1,4},{65,0,0,21,0,8,-1,1,2},{65,0,0,21,0,8,-1,1,2},{65,0,0,21,0,8,-1,1,2},{65,0,0,21,0,8,-1,1,2},{65,0,0,21,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{65,0,0,15,10,8,1,1,2},{65,0,0,15,10,8,2,1,2},{65,0,0,15,10,8,3,1,2},{65,0,0,15,10,8,4,1,2},{65,0,0,15,10,8,5,1,2},{65,0,0,15,10,8,6,1,2},{65,0,0,15,10,8,7,1,2},{65,0,0,15,10,8,8,1,2},{65,0,0,15,10,8,9,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2}},
- {{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,15,10,8,-1,1,2},{65,0,0,13,0,7,0,1,19},{65,0,0,13,0,7,1,1,19},{65,0,0,13,0,7,2,1,19},{65,0,0,13,0,7,3,1,19},{65,0,0,13,0,7,4,1,19},{65,0,0,13,0,7,5,1,19},{65,0,0,13,0,7,6,1,19},{65,0,0,13,0,7,7,1,19},{65,0,0,13,0,7,8,1,19},{65,0,0,13,0,7,9,1,19}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{65,0,0,12,17,7,-1,1,9}},
- {{120,0,0,12,17,7,-1,1,9},{120,0,0,12,17,7,-1,1,9},{120,0,0,10,0,7,-1,1,9},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2}},
- {{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2},{120,0,0,7,0,7,-1,1,2}},
- {{120,0,0,10,0,7,-1,1,9},{120,0,0,10,0,7,-1,1,9},{120,0,0,10,0,7,-1,1,9},{120,0,0,12,17,7,-1,1,9},{120,0,0,12,17,7,-1,1,9},{120,0,0,12,17,7,-1,1,9},{120,0,0,12,17,7,-1,1,9},{120,0,0,10,0,7,-1,1,9},{120,0,0,10,0,7,-1,1,9},{120,0,0,12,17,7,-1,1,9},{120,0,0,12,17,7,-1,1,9},{120,0,0,21,0,8,-1,1,2},{120,0,0,21,0,8,-1,1,2},{120,0,0,1,0,8,-1,1,2},{120,0,0,21,0,8,-1,1,4},{120,0,0,21,0,8,-1,1,4}},
- {{120,0,0,21,0,8,-1,1,4},{120,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2}},
- {{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{152,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{152,0,0,13,0,7,0,1,19},{152,0,0,13,0,7,1,1,19},{152,0,0,13,0,7,2,1,19},{152,0,0,13,0,7,3,1,19},{152,0,0,13,0,7,4,1,19},{152,0,0,13,0,7,5,1,19},{152,0,0,13,0,7,6,1,19},{152,0,0,13,0,7,7,1,19},{152,0,0,13,0,7,8,1,19},{152,0,0,13,0,7,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2}},
- {{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2}},
- {{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,7,0,6,-1,1,2},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,10,0,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9}},
- {{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{118,0,0,12,17,6,-1,1,9},{103,0,0,2,0,12,-1,1,0},{118,0,0,13,0,6,0,1,19},{118,0,0,13,0,6,1,1,19},{118,0,0,13,0,6,2,1,19},{118,0,0,13,0,6,3,1,19},{118,0,0,13,0,6,4,1,19},{118,0,0,13,0,6,5,1,19},{118,0,0,13,0,6,6,1,19},{118,0,0,13,0,6,7,1,19},{118,0,0,13,0,6,8,1,19},{118,0,0,13,0,6,9,1,19}},
- {{118,0,0,21,0,8,-1,1,4},{118,0,0,21,0,8,-1,1,4},{118,0,0,21,0,8,-1,1,4},{118,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2}},
- {{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,7,0,7,-1,1,2},{160,0,0,12,17,7,-1,1,9},{160,0,0,21,0,8,-1,1,2},{160,0,0,21,0,8,-1,1,5},{160,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,10,0,7,-1,1,9},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2}},
- {{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2}},
- {{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,10,0,7,-1,1,9},{151,0,0,10,0,7,-1,1,9},{151,0,0,10,0,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,10,0,7,-1,1,9}},
- {{151,0,0,10,0,7,-1,1,9},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,7,0,7,-1,1,2},{151,0,0,21,0,8,-1,1,4},{151,0,0,21,0,8,-1,1,4},{151,0,0,21,0,8,-1,1,2},{151,0,0,21,0,8,-1,1,4},{151,0,0,21,0,8,-1,1,2},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,12,17,7,-1,1,9},{151,0,0,21,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{151,0,0,13,0,7,0,1,19},{151,0,0,13,0,7,1,1,19},{151,0,0,13,0,7,2,1,19},{151,0,0,13,0,7,3,1,19},{151,0,0,13,0,7,4,1,19},{151,0,0,13,0,7,5,1,19},{151,0,0,13,0,7,6,1,19},{151,0,0,13,0,7,7,1,19},{151,0,0,13,0,7,8,1,19},{151,0,0,13,0,7,9,1,19},{151,0,0,7,0,7,-1,1,2},{151,0,0,21,0,8,-1,1,5},{151,0,0,7,0,7,-1,1,2},{151,0,0,21,0,8,-1,1,4},{151,0,0,21,0,8,-1,1,4},{151,0,0,21,0,8,-1,1,4}},
- {{103,0,0,2,0,12,-1,1,0},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2}},
- {{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{33,0,0,15,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2}},
- {{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2}},
- {{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,7,0,7,-1,1,2},{157,0,0,10,0,7,-1,1,9},{157,0,0,10,0,7,-1,1,9},{157,0,0,10,0,7,-1,1,9},{157,0,0,12,17,7,-1,1,9}},
- {{157,0,0,12,17,7,-1,1,9},{157,0,0,12,17,7,-1,1,9},{157,0,0,10,0,7,-1,1,9},{157,0,0,10,0,7,-1,1,9},{157,0,0,12,17,7,-1,1,9},{157,0,0,10,0,7,-1,1,9},{157,0,0,12,17,7,-1,1,9},{157,0,0,12,17,7,-1,1,9},{157,0,0,21,0,8,-1,1,4},{157,0,0,21,0,8,-1,1,4},{157,0,0,21,0,8,-1,1,2},{157,0,0,21,0,8,-1,1,4},{157,0,0,21,0,8,-1,1,4},{157,0,0,21,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{164,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{164,0,0,7,0,7,-1,1,2}},
- {{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{164,0,0,7,0,7,-1,1,2}},
- {{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,7,0,7,-1,1,2},{164,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2}},
- {{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,7,0,7,-1,1,2},{145,0,0,12,17,7,-1,1,9}},
- {{145,0,0,10,0,7,-1,1,9},{145,0,0,10,0,7,-1,1,9},{145,0,0,10,0,7,-1,1,9},{145,0,0,12,17,7,-1,1,9},{145,0,0,12,17,7,-1,1,9},{145,0,0,12,17,7,-1,1,9},{145,0,0,12,17,7,-1,1,9},{145,0,0,12,17,7,-1,1,9},{145,0,0,12,17,7,-1,1,9},{145,0,0,12,17,7,-1,1,9},{145,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{145,0,0,13,0,7,0,1,19},{145,0,0,13,0,7,1,1,19},{145,0,0,13,0,7,2,1,19},{145,0,0,13,0,7,3,1,19},{145,0,0,13,0,7,4,1,19},{145,0,0,13,0,7,5,1,19},{145,0,0,13,0,7,6,1,19},{145,0,0,13,0,7,7,1,19},{145,0,0,13,0,7,8,1,19},{145,0,0,13,0,7,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{137,0,0,7,0,7,-1,1,2}},
- {{137,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2}},
- {{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2}},
- {{137,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{137,0,0,12,17,7,-1,1,9},{137,0,0,7,0,7,-1,1,2},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9}},
- {{137,0,0,12,17,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{137,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{137,0,0,10,0,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2}},
- {{137,0,0,7,0,7,-1,1,2},{137,0,0,7,0,7,-1,1,2},{137,0,0,10,0,7,-1,1,9},{137,0,0,10,0,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{137,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2}},
- {{158,0,0,10,0,7,-1,1,9},{158,0,0,10,0,7,-1,1,9},{158,0,0,10,0,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,10,0,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,10,0,7,-1,1,9},{158,0,0,10,0,7,-1,1,9},{158,0,0,10,0,7,-1,1,9},{158,0,0,10,0,7,-1,1,9},{158,0,0,12,17,7,-1,1,9}},
- {{158,0,0,12,17,7,-1,1,9},{158,0,0,10,0,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,12,17,7,-1,1,9},{158,0,0,7,0,7,-1,1,2},{158,0,0,7,0,7,-1,1,2},{158,0,0,21,0,8,-1,1,2},{158,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{158,0,0,13,0,7,0,1,19},{158,0,0,13,0,7,1,1,19},{158,0,0,13,0,7,2,1,19},{158,0,0,13,0,7,3,1,19},{158,0,0,13,0,7,4,1,19},{158,0,0,13,0,7,5,1,19},{158,0,0,13,0,7,6,1,19},{158,0,0,13,0,7,7,1,19},{158,0,0,13,0,7,8,1,19},{158,0,0,13,0,7,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2}},
- {{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,10,0,7,-1,0,9}},
- {{166,0,0,10,0,7,-1,0,9},{166,0,0,10,0,7,-1,0,9},{166,0,0,12,17,7,-1,0,9},{166,0,0,12,17,7,-1,0,9},{166,0,0,12,17,7,-1,0,9},{166,0,0,12,17,7,-1,0,9},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{166,0,0,10,0,7,-1,0,9},{166,0,0,10,0,7,-1,0,9},{166,0,0,10,0,7,-1,0,9},{166,0,0,10,0,7,-1,0,9},{166,0,0,12,17,7,-1,0,9},{166,0,0,12,17,7,-1,0,9},{166,0,0,10,0,7,-1,0,9},{166,0,0,12,17,7,-1,0,9}},
- {{166,0,0,12,17,7,-1,0,9},{166,0,0,21,0,8,-1,0,5},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,11},{166,0,0,21,0,8,-1,0,11},{166,0,0,21,0,8,-1,0,2},{166,0,0,21,0,8,-1,0,2},{166,0,0,21,0,8,-1,0,2},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4}},
- {{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,21,0,8,-1,0,4},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,7,0,7,-1,0,2},{166,0,0,12,17,7,-1,0,9},{166,0,0,12,17,7,-1,0,9},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2},{163,0,0,7,0,7,-1,1,2}},
- {{163,0,0,10,0,7,-1,1,9},{163,0,0,10,0,7,-1,1,9},{163,0,0,10,0,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,10,0,7,-1,1,9},{163,0,0,10,0,7,-1,1,9},{163,0,0,12,17,7,-1,1,9},{163,0,0,10,0,7,-1,1,9},{163,0,0,12,17,7,-1,1,9}},
- {{163,0,0,12,17,7,-1,1,9},{163,0,0,21,0,8,-1,1,4},{163,0,0,21,0,8,-1,1,4},{163,0,0,21,0,8,-1,1,2},{163,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{163,0,0,13,0,7,0,1,19},{163,0,0,13,0,7,1,1,19},{163,0,0,13,0,7,2,1,19},{163,0,0,13,0,7,3,1,19},{163,0,0,13,0,7,4,1,19},{163,0,0,13,0,7,5,1,19},{163,0,0,13,0,7,6,1,19},{163,0,0,13,0,7,7,1,19},{163,0,0,13,0,7,8,1,19},{163,0,0,13,0,7,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2}},
- {{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,7,0,7,-1,1,2},{153,0,0,12,17,7,-1,1,9},{153,0,0,10,0,7,-1,1,9},{153,0,0,12,17,7,-1,1,9},{153,0,0,10,0,7,-1,1,9},{153,0,0,10,0,7,-1,1,9}},
- {{153,0,0,12,17,7,-1,1,9},{153,0,0,12,17,7,-1,1,9},{153,0,0,12,17,7,-1,1,9},{153,0,0,12,17,7,-1,1,9},{153,0,0,12,17,7,-1,1,9},{153,0,0,12,17,7,-1,1,9},{153,0,0,10,0,7,-1,1,9},{153,0,0,12,17,7,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{153,0,0,13,0,7,0,1,19},{153,0,0,13,0,7,1,1,19},{153,0,0,13,0,7,2,1,19},{153,0,0,13,0,7,3,1,19},{153,0,0,13,0,7,4,1,19},{153,0,0,13,0,7,5,1,19},{153,0,0,13,0,7,6,1,19},{153,0,0,13,0,7,7,1,19},{153,0,0,13,0,7,8,1,19},{153,0,0,13,0,7,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24}},
- {{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{161,0,0,7,0,7,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24}},
- {{161,0,0,10,0,7,-1,1,24},{161,0,0,10,0,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,10,0,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{161,0,0,12,17,7,-1,1,24},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{161,0,0,13,0,7,0,1,19},{161,0,0,13,0,7,1,1,19},{161,0,0,13,0,7,2,1,19},{161,0,0,13,0,7,3,1,19},{161,0,0,13,0,7,4,1,19},{161,0,0,13,0,7,5,1,19},{161,0,0,13,0,7,6,1,19},{161,0,0,13,0,7,7,1,19},{161,0,0,13,0,7,8,1,19},{161,0,0,13,0,7,9,1,19},{161,0,0,15,0,8,-1,1,24},{161,0,0,15,0,8,-1,1,24},{161,0,0,21,0,8,-1,1,4},{161,0,0,21,0,8,-1,1,4},{161,0,0,21,0,8,-1,1,4},{161,0,0,26,0,8,-1,1,24}},
- {{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2},{146,0,0,9,0,7,-1,1,2}},
- {{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2},{146,0,0,5,0,7,-1,1,2}},
- {{146,0,0,13,0,7,0,1,19},{146,0,0,13,0,7,1,1,19},{146,0,0,13,0,7,2,1,19},{146,0,0,13,0,7,3,1,19},{146,0,0,13,0,7,4,1,19},{146,0,0,13,0,7,5,1,19},{146,0,0,13,0,7,6,1,19},{146,0,0,13,0,7,7,1,19},{146,0,0,13,0,7,8,1,19},{146,0,0,13,0,7,9,1,19},{146,0,0,15,0,8,-1,1,2},{146,0,0,15,0,8,-1,1,2},{146,0,0,15,0,8,-1,1,2},{146,0,0,15,0,8,-1,1,2},{146,0,0,15,0,8,-1,1,2},{146,0,0,15,0,8,-1,1,2}},
- {{146,0,0,15,0,8,-1,1,2},{146,0,0,15,0,8,-1,1,2},{146,0,0,15,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{146,0,0,7,0,7,-1,1,2}},
- {{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2}},
- {{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{165,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2}},
- {{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2}},
- {{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{101,0,0,14,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{101,0,0,21,0,8,-1,1,4},{101,0,0,21,0,8,-1,1,4},{101,0,0,21,0,8,-1,1,4},{101,0,0,21,0,8,-1,1,4},{101,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{101,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2}},
- {{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,20},{71,0,0,7,0,7,-1,0,20},{71,0,0,7,0,7,-1,0,20},{71,0,0,7,0,7,-1,0,8},{71,0,0,7,0,7,-1,0,8},{71,0,0,7,0,7,-1,0,8},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2}},
- {{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,8},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,20},{71,0,0,7,0,7,-1,0,8},{71,0,0,7,0,7,-1,0,20},{71,0,0,7,0,7,-1,0,8},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2}},
- {{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,20},{71,0,0,7,0,7,-1,0,8},{71,0,0,7,0,7,-1,0,8},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2}},
- {{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{71,0,0,7,0,7,-1,0,2},{103,0,0,2,0,12,-1,0,0}},
- {{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2}},
- {{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,20},{156,0,0,7,0,7,-1,1,8}},
- {{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{156,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{130,0,0,7,0,6,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2}},
- {{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{149,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{149,0,0,13,0,7,0,1,19},{149,0,0,13,0,7,1,1,19},{149,0,0,13,0,7,2,1,19},{149,0,0,13,0,7,3,1,19},{149,0,0,13,0,7,4,1,19},{149,0,0,13,0,7,5,1,19},{149,0,0,13,0,7,6,1,19},{149,0,0,13,0,7,7,1,19},{149,0,0,13,0,7,8,1,19},{149,0,0,13,0,7,9,1,19},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{149,0,0,21,0,8,-1,1,4},{149,0,0,21,0,8,-1,1,4}},
- {{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2}},
- {{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{134,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{134,0,0,12,17,7,-1,1,9},{134,0,0,12,17,7,-1,1,9},{134,0,0,12,17,7,-1,1,9},{134,0,0,12,17,7,-1,1,9},{134,0,0,12,17,7,-1,1,9},{134,0,0,21,0,8,-1,1,4},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2}},
- {{75,0,0,12,17,7,-1,1,9},{75,0,0,12,17,7,-1,1,9},{75,0,0,12,17,7,-1,1,9},{75,0,0,12,17,7,-1,1,9},{75,0,0,12,17,7,-1,1,9},{75,0,0,12,17,7,-1,1,9},{75,0,0,12,17,7,-1,1,9},{75,0,0,21,0,8,-1,1,4},{75,0,0,21,0,8,-1,1,4},{75,0,0,21,0,8,-1,1,4},{75,0,0,21,0,8,-1,1,2},{75,0,0,21,0,8,-1,1,2},{75,0,0,26,0,8,-1,1,2},{75,0,0,26,0,8,-1,1,2},{75,0,0,26,0,8,-1,1,2},{75,0,0,26,0,8,-1,1,2}},
- {{75,0,0,6,0,7,-1,1,2},{75,0,0,6,0,7,-1,1,2},{75,0,0,6,0,7,-1,1,2},{75,0,0,6,0,7,-1,1,2},{75,0,0,21,0,8,-1,1,4},{75,0,0,26,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{75,0,0,13,0,7,0,1,19},{75,0,0,13,0,7,1,1,19},{75,0,0,13,0,7,2,1,19},{75,0,0,13,0,7,3,1,19},{75,0,0,13,0,7,4,1,19},{75,0,0,13,0,7,5,1,19},{75,0,0,13,0,7,6,1,19},{75,0,0,13,0,7,7,1,19},{75,0,0,13,0,7,8,1,19},{75,0,0,13,0,7,9,1,19},{103,0,0,2,0,12,-1,1,0},{75,0,0,15,0,8,-1,1,2},{75,0,0,15,0,8,-1,1,2},{75,0,0,15,0,8,-1,1,2},{75,0,0,15,0,8,-1,1,2},{75,0,0,15,0,8,-1,1,2}},
- {{75,0,0,15,0,8,-1,1,2},{75,0,0,15,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2}},
- {{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2},{75,0,0,7,0,7,-1,1,2}},
- {{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2}},
- {{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{92,0,0,7,0,5,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{92,0,0,7,0,5,-1,1,2},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9}},
- {{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9}},
- {{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{92,0,0,10,0,5,-1,1,9},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{92,0,0,12,17,5,-1,1,9}},
- {{92,0,0,12,17,5,-1,1,9},{92,0,0,12,17,5,-1,1,9},{92,0,0,12,17,5,-1,1,9},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2},{92,0,0,6,0,5,-1,1,2}},
- {{22,0,1,7,0,4,-1,0,14},{20,0,1,7,0,4,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2}},
- {{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{135,0,0,7,0,7,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{135,0,0,26,0,8,-1,1,2},{135,0,0,12,17,7,-1,1,9},{135,0,0,12,17,7,-1,1,9},{135,0,0,21,0,8,-1,1,4}},
- {{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2}},
- {{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2}},
- {{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2}},
- {{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,10,0,7,-1,0,9},{0,0,0,10,0,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,10,0,7,-1,0,9},{0,0,0,10,0,7,-1,0,9},{0,0,0,10,0,7,-1,0,9}},
- {{0,0,0,10,0,7,-1,0,9},{0,0,0,10,0,7,-1,0,9},{0,0,0,10,0,7,-1,0,9},{0,0,0,1,18,10,-1,0,9},{0,0,0,1,18,10,-1,0,9},{0,0,0,1,18,10,-1,0,9},{0,0,0,1,18,10,-1,0,9},{0,0,0,1,18,10,-1,0,9},{0,0,0,1,18,10,-1,0,9},{0,0,0,1,18,10,-1,0,9},{0,0,0,1,18,10,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9}},
- {{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2}},
- {{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{1,0,0,12,17,7,-1,0,9},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2}},
- {{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,9,-1,0,2}},
- {{0,0,0,26,0,9,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2}},
- {{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{0,0,0,26,0,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2}},
- {{14,0,0,26,10,8,-1,1,2},{14,0,0,26,10,8,-1,1,2},{14,0,0,12,17,7,-1,1,9},{14,0,0,12,17,7,-1,1,9},{14,0,0,12,17,7,-1,1,9},{14,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2}},
- {{0,0,0,15,0,8,-1,0,2},{0,0,0,15,0,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,25,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,25,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,25,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,25,10,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,25,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,25,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2}},
- {{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,25,10,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{0,0,0,9,0,9,-1,1,2},{0,0,0,5,0,9,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{0,0,0,13,2,9,0,1,19},{0,0,0,13,2,9,1,1,19}},
- {{0,0,0,13,2,9,2,1,19},{0,0,0,13,2,9,3,1,19},{0,0,0,13,2,9,4,1,19},{0,0,0,13,2,9,5,1,19},{0,0,0,13,2,9,6,1,19},{0,0,0,13,2,9,7,1,19},{0,0,0,13,2,9,8,1,19},{0,0,0,13,2,9,9,1,19},{0,0,0,13,2,9,0,1,19},{0,0,0,13,2,9,1,1,19},{0,0,0,13,2,9,2,1,19},{0,0,0,13,2,9,3,1,19},{0,0,0,13,2,9,4,1,19},{0,0,0,13,2,9,5,1,19},{0,0,0,13,2,9,6,1,19},{0,0,0,13,2,9,7,1,19}},
- {{0,0,0,13,2,9,8,1,19},{0,0,0,13,2,9,9,1,19},{0,0,0,13,2,9,0,1,19},{0,0,0,13,2,9,1,1,19},{0,0,0,13,2,9,2,1,19},{0,0,0,13,2,9,3,1,19},{0,0,0,13,2,9,4,1,19},{0,0,0,13,2,9,5,1,19},{0,0,0,13,2,9,6,1,19},{0,0,0,13,2,9,7,1,19},{0,0,0,13,2,9,8,1,19},{0,0,0,13,2,9,9,1,19},{0,0,0,13,2,9,0,1,19},{0,0,0,13,2,9,1,1,19},{0,0,0,13,2,9,2,1,19},{0,0,0,13,2,9,3,1,19}},
- {{0,0,0,13,2,9,4,1,19},{0,0,0,13,2,9,5,1,19},{0,0,0,13,2,9,6,1,19},{0,0,0,13,2,9,7,1,19},{0,0,0,13,2,9,8,1,19},{0,0,0,13,2,9,9,1,19},{0,0,0,13,2,9,0,1,19},{0,0,0,13,2,9,1,1,19},{0,0,0,13,2,9,2,1,19},{0,0,0,13,2,9,3,1,19},{0,0,0,13,2,9,4,1,19},{0,0,0,13,2,9,5,1,19},{0,0,0,13,2,9,6,1,19},{0,0,0,13,2,9,7,1,19},{0,0,0,13,2,9,8,1,19},{0,0,0,13,2,9,9,1,19}},
- {{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2}},
- {{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9}},
- {{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9}},
- {{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2}},
- {{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,12,17,7,-1,1,9},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2}},
- {{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,12,17,7,-1,1,9},{112,0,0,26,0,8,-1,1,2},{112,0,0,26,0,8,-1,1,2},{112,0,0,21,0,8,-1,1,4},{112,0,0,21,0,8,-1,1,4},{112,0,0,21,0,8,-1,1,4},{112,0,0,21,0,8,-1,1,4},{112,0,0,21,0,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9}},
- {{103,0,0,2,0,12,-1,1,0},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9},{112,0,0,12,17,7,-1,1,9}},
- {{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2}},
- {{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{140,0,0,7,1,7,-1,1,2},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{140,0,0,15,1,8,-1,1,2},{140,0,0,15,1,8,-1,1,2},{140,0,0,15,1,8,-1,1,2},{140,0,0,15,1,8,-1,1,2},{140,0,0,15,1,8,-1,1,2},{140,0,0,15,1,8,-1,1,2},{140,0,0,15,1,8,-1,1,2},{140,0,0,15,1,8,-1,1,2},{140,0,0,15,1,8,-1,1,2}},
- {{140,0,0,12,17,7,-1,1,9},{140,0,0,12,17,7,-1,1,9},{140,0,0,12,17,7,-1,1,9},{140,0,0,12,17,7,-1,1,9},{140,0,0,12,17,7,-1,1,9},{140,0,0,12,17,7,-1,1,9},{140,0,0,12,17,7,-1,1,9},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0},{103,0,0,2,1,12,-1,1,0}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2}},
- {{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{103,0,0,2,13,12,-1,1,0},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2},{2,0,0,7,13,9,-1,1,2}},
- {{2,0,0,25,10,8,-1,1,2},{2,0,0,25,10,8,-1,1,2},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0},{103,0,0,2,13,12,-1,1,0}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0}},
- {{103,0,0,2,0,12,-1,0,0},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,15,2,9,0,0,1},{0,0,0,15,2,9,0,0,1},{0,0,0,15,2,9,1,0,1},{0,0,0,15,2,9,2,0,1},{0,0,0,15,2,9,3,0,1},{0,0,0,15,2,9,4,0,1},{0,0,0,15,2,9,5,0,1},{0,0,0,15,2,9,6,0,1},{0,0,0,15,2,9,7,0,1},{0,0,0,15,2,9,8,0,1},{0,0,0,15,2,9,9,0,1},{0,0,0,15,10,8,-1,0,1},{0,0,0,15,10,8,-1,0,1},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,9,-1,0,2},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1}},
- {{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,10,9,-1,0,2},{0,0,0,26,10,9,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,0,9,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{0,0,0,26,0,8,-1,0,1},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39}},
- {{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39},{0,0,0,26,0,8,-1,0,39}},
- {{20,0,1,26,0,9,-1,2,14},{0,0,1,26,0,9,-1,2,14},{0,0,1,26,0,9,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,1,26,0,9,-1,0,14},{0,0,1,26,0,9,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,24,10,8,-1,0,2},{0,0,0,24,10,8,-1,0,2},{0,0,0,24,10,8,-1,0,2},{0,0,0,24,10,8,-1,0,2},{0,0,0,24,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,23},{0,0,0,26,10,8,-1,0,23},{0,0,0,26,10,8,-1,0,23},{0,0,0,26,10,8,-1,0,18},{0,0,0,26,10,8,-1,0,18},{0,0,0,26,10,8,-1,0,18},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2}},
- {{0,0,0,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{0,0,0,26,10,8,-1,0,14},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{0,0,0,26,10,8,-1,0,2},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0},{103,0,0,2,0,12,-1,0,0}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{0,0,0,26,10,8,-1,1,2},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{0,0,0,26,10,8,-1,1,14},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,26,10,8,-1,1,14},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14}},
- {{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14}},
- {{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14}},
- {{17,0,1,7,0,0,-1,0,14},{17,0,1,7,0,0,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14}},
- {{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,1,2,0,12,-1,0,14},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{103,0,0,2,0,12,-1,1,0},{0,0,0,1,18,11,-1,1,9},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}},
- {{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9}},
- {{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,10,-1,1,9},{0,0,0,1,18,11,-1,1,9}},
- {{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,3,0,12,-1,0,0},{103,0,0,2,0,12,-1,1,0},{103,0,0,2,0,12,-1,1,0}}
-};
-#endif
-
#define kFullWidthMaxPlane 0
#define kFullWidthIndexBits 10
@@ -1747,102 +346,6 @@ static const uint16_t sFullWidthInverseValues[13][64] = {
};
-#if !ENABLE_INTL_API
-#define kCaseMapMaxPlane 1
-#define kCaseMapIndexBits 11
-#define kCaseMapCharBits 5
-static const uint8_t sCaseMapPlanes[1] = {1};
-
-static const uint8_t sCaseMapPages[2][2048] = {
- {0,0,1,2,0,3,4,5,6,7,8,9,10,11,12,13,6,14,15,16,17,0,0,0,0,0,18,19,20,21,22,23,24,25,26,6,27,6,28,6,6,29,30,31,32,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,33,34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,35,36,37,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,0,0,0,0,0,0,0,0,0,0,0,38,0,0,0,0,6,6,6,6,39,6,6,6,40,41,42,43,41,44,45,46,0,0,0,0,0,0,0,0,0,47,48,49,50,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,51,52,53,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,54,55,56,57,6,6,6,58,59,60,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,0,0,0,0,0,0,0,0,6,61,62,0,0,0,0,63,6,64,65,66,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,67,68,69,70,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,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,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,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,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,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,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,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,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,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,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,71,72,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,73,74,75,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,0,76,77,78,79,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,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,80,81,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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,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}
-};
-
-static const uint32_t sCaseMapValues[82][32] = {
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x10000329,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x00000000,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x00000000},
- {0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x00000000,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000187},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000159,0x10000178,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x40000003,0x10000003,0x40000007,0x10000007,0x40000003,0x10000003,0x4000007f},
- {0x1000007f,0x40000003,0x10000003,0x40000007,0x10000007,0x40000003,0x10000003,0x4000000f,0x1000000f,0x00000000,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000187,0x40000003,0x10000003,0x40000007,0x10000007,0x40000003,0x10000003,0x1000012c},
- {0x100003c3,0x400003d2,0x40000001,0x10000001,0x40000001,0x10000001,0x400003d2,0x4000000f,0x1000000f,0x400003df,0x400003dd,0x40000007,0x10000007,0x00000000,0x40000053,0x400003d6,0x400003cb,0x40000003,0x10000003,0x400003f3,0x400003f7,0x10000063,0x400003ff,0x400003ff,0x40000001,0x10000001,0x100003a7,0x00000000,0x400003f3,0x400003ef,0x100003be,0x400003ea},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000326,0x4000000f,0x1000000f,0x4000032a,0x00000000,0x00000000,0x40000001,0x10000001,0x40000326,0x4000001f,0x1000001f,0x4000033b,0x40000339,0x40000007,0x10000007,0x40000003,0x10000003,0x40000325,0x40000001,0x10000001,0x00000000,0x00000000,0x40000001,0x10000001,0x00000000,0x10000048},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x40000002,0x80000001,0x20000003,0x4000000e,0x8000000f,0x20000001,0x40000006,0x80000001,0x20000007,0x40000003,0x10000003,0x4000001f,0x1000001f,0x40000003,0x10000003,0x40000007,0x10000007,0x40000003,0x10000003,0x4000000f,0x1000000f,0x40000003,0x10000003,0x40000007,0x10000007,0x10000053,0x40000001,0x10000001},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x40000002,0x80000003,0x20000001,0x40000001,0x10000001,0x40000063,0x40000048,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001},
- {0x400003be,0x00000000,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40002e5f,0x40000007,0x10000007,0x400003a7,0x40002e58,0x10002e41},
- {0x10002e3f,0x40000003,0x10000003,0x400003c3,0x400000cd,0x400000c9,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x10002e3f,0x10002e3c,0x10002e22,0x100003d2,0x100003d2,0x00000000,0x100003df,0x100003dd,0x00000000,0x100003d6,0x00000000,0x100003cb,0x1000a5f7,0x00000000,0x00000000,0x00000000},
- {0x100003f3,0x1000a5cd,0x00000000,0x100003f7,0x00000000,0x1000a5e8,0x1000a5cc,0x00000000,0x100003ff,0x100003ff,0x00000000,0x10002e09,0x1000a5c1,0x00000000,0x00000000,0x100003f3,0x00000000,0x10002e1f,0x100003ef,0x00000000,0x00000000,0x100003ea,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x10002e19,0x00000000,0x00000000},
- {0x10000326,0x00000000,0x00000000,0x1000032a,0x00000000,0x00000000,0x00000000,0x1000a536,0x10000326,0x100000cd,0x1000033b,0x10000339,0x100000c9,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x10000325,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x1000a52f,0x1000a52e,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x100000dc,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x10000086,0x10000082,0x10000082,0x00000000,0x4000008c},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x4000002a,0x00000000,0x40000025,0x40000027,0x40000025,0x00000000,0x40000040,0x00000000,0x40000043,0x40000041,0x00000000,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020},
- {0x40000060,0x40000060,0x00000000,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x1000002a,0x10000025,0x10000027,0x10000025,0x00000000,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020},
- {0x10000060,0x10000060,0x10000061,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000040,0x10000043,0x10000041,0x40000018,0x10000042,0x10000049,0x00000000,0x00000000,0x00000000,0x10000073,0x10000076,0x10000018,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x1000006a,0x10000050,0x1000000b,0x1000008c,0x4000004c,0x10000060,0x00000000,0x4000000f,0x1000000f,0x4000000b,0x40000001,0x10000001,0x00000000,0x40000086,0x40000082,0x40000082},
- {0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020,0x40000020},
- {0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020,0x10000020},
- {0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050},
- {0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001},
- {0x4000000f,0x40000003,0x10000003,0x40000007,0x10000007,0x40000003,0x10000003,0x4000000f,0x1000000f,0x40000003,0x10000003,0x40000007,0x10000007,0x40000003,0x10000003,0x1000000f,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050},
- {0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x400000d0,0x400000d0,0x400000d0,0x400000d0,0x400000d0,0x400000d0,0x400000d0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030},
- {0x100000d0,0x100000d0,0x100000d0,0x100000d0,0x100000d0,0x100000d0,0x100000d0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0,0x40003da0},
- {0x40003de0,0x40003de0,0x40003de0,0x40003de0,0x40003de0,0x40003de0,0x00000000,0x40003de0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40003de0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b8d0,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830,0x4000b830},
- {0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870,0x4000b870},
- {0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x4000b850,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x00000000,0x00000000,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x1000ba04,0x00000000,0x00000000,0x00000000,0x1000311e,0x00000000,0x00000000},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x100000fb,0x00000000,0x00000000,0x40001e41,0x00000000},
- {0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x00000000,0x00000000,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x00000000,0x00000000},
- {0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008},
- {0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x00000000,0x00000000,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x00000000,0x00000000,0x00000000,0x10000008,0x00000000,0x10000008,0x00000000,0x10000008,0x00000000,0x10000008,0x00000000,0x40000008,0x00000000,0x40000008,0x00000000,0x40000008,0x00000000,0x40000008},
- {0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x100000ca,0x100000ca,0x100000ba,0x100000ba,0x100000be,0x100000be,0x100000ac,0x100000ac,0x10000080,0x10000080,0x10000090,0x10000090,0x10000086,0x10000086,0x00000000,0x00000000},
- {0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x10000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x40000008,0x10000008,0x10000008,0x00000000,0x1000000f,0x00000000,0x00000000,0x00000000,0x00000000,0x40000008,0x40000008,0x400000ca,0x400000ca,0x4000000f,0x00000000,0x10001c27,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x1000000f,0x00000000,0x00000000,0x00000000,0x00000000,0x400000ba,0x400000ba,0x400000be,0x400000be,0x4000000f,0x00000000,0x00000000,0x00000000,0x10000008,0x10000008,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40000008,0x40000008,0x400000ac,0x400000ac,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x10000008,0x10000008,0x00000000,0x00000000,0x00000000,0x10000009,0x00000000,0x00000000,0x40000008,0x40000008,0x40000090,0x40000090,0x40000009,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x1000000f,0x00000000,0x00000000,0x00000000,0x00000000,0x40000080,0x40000080,0x40000086,0x40000086,0x4000000f,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x400022ef,0x00000000,0x00000000,0x00000000,0x40002141,0x400021ce,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x4000007c,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x1000007c,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x40000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010,0x10000010},
- {0x00000000,0x00000000,0x00000000,0x40000007,0x10000007,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40000066,0x40000066,0x4000006a,0x4000006a,0x4000006e,0x4000006e,0x4000006a,0x4000006a,0x40000066,0x40000066},
- {0x4000001a,0x4000001a,0x4000001e,0x4000001e,0x4000001a,0x4000001a,0x40000026,0x40000026,0x4000002a,0x4000002a,0x4000002e,0x4000002e,0x4000002a,0x4000002a,0x40000026,0x40000026,0x10000066,0x10000066,0x1000006a,0x1000006a,0x1000006e,0x1000006e,0x1000006a,0x1000006a,0x10000066,0x10000066,0x1000001a,0x1000001a,0x1000001e,0x1000001e,0x1000001a,0x1000001a},
- {0x10000026,0x10000026,0x1000002a,0x1000002a,0x1000002e,0x1000002e,0x1000002a,0x1000002a,0x10000026,0x10000026,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000030,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050,0x40000050},
- {0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x40000070,0x00000000,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030,0x10000030},
- {0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000050,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x10000070,0x00000000},
- {0x40000001,0x10000001,0x40002e09,0x4000311e,0x40002e19,0x10002e5f,0x10002e58,0x4000000f,0x1000000f,0x40000003,0x10000003,0x40000007,0x10000007,0x40002e3c,0x40002e1f,0x40002e3f,0x40002e22,0x00000000,0x40000001,0x10000001,0x00000000,0x40000003,0x10000003,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40002e41,0x40002e3f},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40000007,0x10000007,0x40000003,0x10000003,0x00000000,0x00000000,0x00000000,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0,0x10003da0},
- {0x10003de0,0x10003de0,0x10003de0,0x10003de0,0x10003de0,0x10003de0,0x00000000,0x10003de0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x10003de0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x40000003,0x10000003,0x40000007,0x10000007,0x4000ba04,0x40000001,0x10000001},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x40000007,0x10000007,0x4000a5e8,0x00000000,0x00000000,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001},
- {0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x40000001,0x10000001,0x4000a5cc,0x4000a5f7,0x4000a5cd,0x4000a5c1,0x00000000,0x00000000,0x4000a52e,0x4000a536,0x4000a52f,0x40000ce0,0x40000001,0x10000001,0x40000001,0x10000001,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x10000ce0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0,0x1000b8d0},
- {0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b830,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850},
- {0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b870,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850,0x1000b850},
- {0x00000000,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x00000000,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40000028,0x40000028,0x40000028,0x40000028,0x40000028,0x40000028,0x40000028,0x40000028,0x40000038,0x40000038,0x40000038,0x40000038,0x40000038,0x40000038,0x40000038,0x40000038,0x40000028,0x40000028,0x40000028,0x40000028,0x40000028,0x40000028,0x40000028,0x40000028,0x40000058,0x40000058,0x40000058,0x40000058,0x40000058,0x40000058,0x40000058,0x40000058},
- {0x40000068,0x40000068,0x40000068,0x40000068,0x40000068,0x40000068,0x40000068,0x40000068,0x10000028,0x10000028,0x10000028,0x10000028,0x10000028,0x10000028,0x10000028,0x10000028,0x10000038,0x10000038,0x10000038,0x10000038,0x10000038,0x10000038,0x10000038,0x10000038,0x10000028,0x10000028,0x10000028,0x10000028,0x10000028,0x10000028,0x10000028,0x10000028},
- {0x10000058,0x10000058,0x10000058,0x10000058,0x10000058,0x10000058,0x10000058,0x10000058,0x10000068,0x10000068,0x10000068,0x10000068,0x10000068,0x10000068,0x10000068,0x10000068,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040},
- {0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x40000040,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040},
- {0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x10000040,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
- {0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060,0x40000060},
- {0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060,0x10000060}
-};
-#endif
const uint32_t kTitleToUpper = 0x80000000;
const uint32_t kUpperToLower = 0x40000000;
const uint32_t kLowerToTitle = 0x20000000;
diff --git a/intl/unicharutil/util/nsUnicodeScriptCodes.h b/intl/unicharutil/util/nsUnicodeScriptCodes.h
index 40bc6039e..d07ac67ff 100644
--- a/intl/unicharutil/util/nsUnicodeScriptCodes.h
+++ b/intl/unicharutil/util/nsUnicodeScriptCodes.h
@@ -70,17 +70,6 @@ Standard.
#pragma pack(1)
-#if !ENABLE_INTL_API
-
-struct nsCharProps1 {
- unsigned char mMirrorOffsetIndex:5;
- unsigned char mHangulType:3;
- unsigned char mCombiningClass:8;
-};
-
-#endif
-
-#if ENABLE_INTL_API
struct nsCharProps2 {
// Currently only 6 bits are defined here, so 2 more could be added without
@@ -89,24 +78,6 @@ struct nsCharProps2 {
unsigned char mXidmod:4;
};
-#endif
-
-#if !ENABLE_INTL_API
-
-struct nsCharProps2 {
- unsigned char mScriptCode:8;
- unsigned char mPairedBracketType:2;
- unsigned char mEastAsianWidthFWH:1;
- unsigned char mCategory:5;
- unsigned char mBidiCategory:5;
- unsigned char mXidmod:4;
- signed char mNumericValue:5;
- unsigned char mVertOrient:2;
- unsigned char mLineBreak; // only 6 bits actually needed
-};
-
-#endif
-
#pragma pack()
namespace mozilla {
diff --git a/intl/unicharutil/util/objs.mozbuild b/intl/unicharutil/util/objs.mozbuild
index de9de37a7..448168473 100644
--- a/intl/unicharutil/util/objs.mozbuild
+++ b/intl/unicharutil/util/objs.mozbuild
@@ -6,14 +6,7 @@
intl_unicharutil_util_lcppsrcs = [
'GreekCasing.cpp',
-]
-
-if CONFIG['ENABLE_INTL_API']:
- intl_unicharutil_util_lcppsrcs += [
- 'ICUUtils.cpp',
- ]
-
-intl_unicharutil_util_lcppsrcs += [
+ 'ICUUtils.cpp',
'IrishCasing.cpp',
'nsBidiUtils.cpp',
'nsSpecialCasingData.cpp',
diff --git a/ipc/app/moz.build b/ipc/app/moz.build
index 55c338cb8..3e6461584 100644
--- a/ipc/app/moz.build
+++ b/ipc/app/moz.build
@@ -43,47 +43,10 @@ if CONFIG['OS_ARCH'] == 'WINNT':
'nss3.dll',
]
- if CONFIG['MOZ_SANDBOX']:
- # For sandbox includes and the include dependencies those have
- LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
- ]
-
- USE_LIBS += [
- 'sandbox_s',
- ]
-
- DELAYLOAD_DLLS += [
- 'winmm.dll',
- 'user32.dll',
- ]
-
DELAYLOAD_DLLS += [
'xul.dll',
]
-if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_TARGET'] in ('Linux', 'Android'):
- USE_LIBS += [
- 'mozsandbox',
- ]
-
- # gcc lto likes to put the top level asm in syscall.cc in a different partition
- # from the function using it which breaks the build. Work around that by
- # forcing there to be only one partition.
- if '-flto' in CONFIG['OS_CXXFLAGS'] and not CONFIG['CLANG_CXX']:
- LDFLAGS += ['--param lto-partitions=1']
-
-if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_TARGET'] == 'Darwin':
- # For sandbox includes and the include dependencies those have
- LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
- ]
- USE_LIBS += [
- 'mozsandbox',
- ]
-
if CONFIG['_MSC_VER']:
# Always enter a Windows program through wmain, whether or not we're
# a console application.
@@ -102,12 +65,6 @@ LDFLAGS += CONFIG['MOZ_ALLOW_HEAP_EXECUTE_FLAGS']
if CONFIG['OS_ARCH'] == 'WINNT' and not CONFIG['GNU_CC']:
LDFLAGS += ['/HEAP:0x40000']
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- OS_LIBS += [
- 'binder',
- 'utils',
- ]
-
if CONFIG['GNU_CXX']:
CXXFLAGS += ['-Wshadow']
diff --git a/ipc/app/pie/moz.build b/ipc/app/pie/moz.build
index 0247b25b4..6924199b5 100644
--- a/ipc/app/pie/moz.build
+++ b/ipc/app/pie/moz.build
@@ -16,15 +16,4 @@ LOCAL_INCLUDES += [
'/xpcom/base',
]
-if CONFIG['MOZ_SANDBOX']:
- USE_LIBS += [
- 'mozsandbox',
- ]
-
- # gcc lto likes to put the top level asm in syscall.cc in a different partition
- # from the function using it which breaks the build. Work around that by
- # forcing there to be only one partition.
- if '-flto' in CONFIG['OS_CXXFLAGS'] and not CONFIG['CLANG_CXX']:
- LDFLAGS += ['--param lto-partitions=1']
-
LDFLAGS += ['-pie']
diff --git a/ipc/chromium/moz.build b/ipc/chromium/moz.build
index aad46b59e..f047e7011 100644
--- a/ipc/chromium/moz.build
+++ b/ipc/chromium/moz.build
@@ -131,8 +131,6 @@ if os_linux:
]
DEFINES['ANDROID'] = True
DEFINES['_POSIX_MONOTONIC_CLOCK'] = 0
- if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DEFINES['HAVE_ANDROID_OS'] = True
if os_bsd or os_linux:
if 'gtk' in CONFIG['MOZ_WIDGET_TOOLKIT']:
diff --git a/ipc/chromium/src/base/platform_thread_posix.cc b/ipc/chromium/src/base/platform_thread_posix.cc
index 6c978336e..4acd95f23 100644
--- a/ipc/chromium/src/base/platform_thread_posix.cc
+++ b/ipc/chromium/src/base/platform_thread_posix.cc
@@ -48,11 +48,7 @@ PlatformThreadId PlatformThread::CurrentId() {
mach_port_deallocate(mach_task_self(), port);
return port;
#elif defined(OS_LINUX)
-#ifdef MOZ_WIDGET_GONK
- return (intptr_t) (pthread_self());
-#else
return syscall(__NR_gettid);
-#endif
#elif defined(OS_OPENBSD) || defined(__GLIBC__)
return (intptr_t) (pthread_self());
#elif defined(OS_NETBSD)
diff --git a/ipc/chromium/src/base/process_util_linux.cc b/ipc/chromium/src/base/process_util_linux.cc
index 204017db5..57388ccb0 100644
--- a/ipc/chromium/src/base/process_util_linux.cc
+++ b/ipc/chromium/src/base/process_util_linux.cc
@@ -24,24 +24,13 @@
#include "prenv.h"
#include "prmem.h"
-#ifdef MOZ_WIDGET_GONK
/*
- * AID_APP is the first application UID used by Android. We're using
- * it as our unprivilegied UID. This ensure the UID used is not
- * shared with any other processes than our own childs.
- */
-# include <private/android_filesystem_config.h>
-# define CHILD_UNPRIVILEGED_UID AID_APP
-# define CHILD_UNPRIVILEGED_GID AID_APP
-#else
-/*
- * On platforms that are not gonk based, we fall back to an arbitrary
- * UID. This is generally the UID for user `nobody', albeit it is not
+ * On our platforms we use an arbitrary UID.
+ * This is generally the UID for user `nobody', albeit it is not
* always the case.
*/
# define CHILD_UNPRIVILEGED_UID 65534
# define CHILD_UNPRIVILEGED_GID 65534
-#endif
namespace {
@@ -229,36 +218,6 @@ void SetCurrentProcessPrivileges(ChildPrivileges privs) {
gid_t gid = CHILD_UNPRIVILEGED_GID;
uid_t uid = CHILD_UNPRIVILEGED_UID;
-#ifdef MOZ_WIDGET_GONK
- {
- static bool checked_pix_max, pix_max_ok;
- if (!checked_pix_max) {
- checked_pix_max = true;
- int fd = open("/proc/sys/kernel/pid_max", O_CLOEXEC | O_RDONLY);
- if (fd < 0) {
- DLOG(ERROR) << "Failed to open pid_max";
- _exit(127);
- }
- char buf[PATH_MAX];
- ssize_t len = read(fd, buf, sizeof(buf) - 1);
- close(fd);
- if (len < 0) {
- DLOG(ERROR) << "Failed to read pid_max";
- _exit(127);
- }
- buf[len] = '\0';
- int pid_max = atoi(buf);
- pix_max_ok =
- (pid_max + CHILD_UNPRIVILEGED_UID > CHILD_UNPRIVILEGED_UID);
- }
- if (!pix_max_ok) {
- DLOG(ERROR) << "Can't safely get unique uid/gid";
- _exit(127);
- }
- gid += getpid();
- uid += getpid();
- }
-#endif
if (setgid(gid) != 0) {
DLOG(ERROR) << "FAILED TO setgid() CHILD PROCESS";
_exit(127);
diff --git a/ipc/contentproc/moz.build b/ipc/contentproc/moz.build
index 07cf0b97c..f9ded56ec 100644
--- a/ipc/contentproc/moz.build
+++ b/ipc/contentproc/moz.build
@@ -18,8 +18,3 @@ if CONFIG['OS_ARCH'] == 'WINNT':
'/xpcom/base',
]
-if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_ARCH'] == 'WINNT':
- LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
- ]
diff --git a/ipc/contentproc/plugin-container.cpp b/ipc/contentproc/plugin-container.cpp
index f293889b0..2fb9bd4f5 100644
--- a/ipc/contentproc/plugin-container.cpp
+++ b/ipc/contentproc/plugin-container.cpp
@@ -22,118 +22,10 @@
#include "GMPLoader.h"
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-#include "mozilla/sandboxing/SandboxInitialization.h"
-#include "mozilla/sandboxing/sandboxLogging.h"
-#endif
-
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
-#include "mozilla/Sandbox.h"
-#include "mozilla/SandboxInfo.h"
-#endif
-
-#ifdef MOZ_WIDGET_GONK
-# include <sys/time.h>
-# include <sys/resource.h>
-
-# include <binder/ProcessState.h>
-
-# ifdef LOGE_IF
-# undef LOGE_IF
-# endif
-
-# include <android/log.h>
-# define LOGE_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_print(ANDROID_LOG_ERROR, \
- "Gecko:MozillaRntimeMain", __VA_ARGS__)) \
- : (void)0 )
-
-# ifdef MOZ_CONTENT_SANDBOX
-# include "mozilla/Sandbox.h"
-# endif
-
-#endif // MOZ_WIDGET_GONK
-
-#ifdef MOZ_WIDGET_GONK
-static void
-InitializeBinder(void *aDummy) {
- // Change thread priority to 0 only during calling ProcessState::self().
- // The priority is registered to binder driver and used for default Binder
- // Thread's priority.
- // To change the process's priority to small value need's root permission.
- int curPrio = getpriority(PRIO_PROCESS, 0);
- int err = setpriority(PRIO_PROCESS, 0, 0);
- MOZ_ASSERT(!err);
- LOGE_IF(err, "setpriority failed. Current process needs root permission.");
- android::ProcessState::self()->startThreadPool();
- setpriority(PRIO_PROCESS, 0, curPrio);
-}
-#endif
-
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-class WinSandboxStarter : public mozilla::gmp::SandboxStarter {
-public:
- virtual bool Start(const char *aLibPath) override {
- if (IsSandboxedProcess()) {
- mozilla::sandboxing::LowerSandbox();
- }
- return true;
- }
-};
-#endif
-
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
-class LinuxSandboxStarter : public mozilla::gmp::SandboxStarter {
- LinuxSandboxStarter() { }
-public:
- static SandboxStarter* Make() {
- if (mozilla::SandboxInfo::Get().CanSandboxMedia()) {
- return new LinuxSandboxStarter();
- } else {
- // Sandboxing isn't possible, but the parent has already
- // checked that this plugin doesn't require it. (Bug 1074561)
- return nullptr;
- }
- }
- virtual bool Start(const char *aLibPath) override {
- mozilla::SetMediaPluginSandbox(aLibPath);
- return true;
- }
-};
-#endif
-
-#if defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
-class MacSandboxStarter : public mozilla::gmp::SandboxStarter {
-public:
- virtual bool Start(const char *aLibPath) override {
- std::string err;
- bool rv = mozilla::StartMacSandbox(mInfo, err);
- if (!rv) {
- fprintf(stderr, "sandbox_init() failed! Error \"%s\"\n", err.c_str());
- }
- return rv;
- }
- virtual void SetSandboxInfo(MacSandboxInfo* aSandboxInfo) override {
- mInfo = *aSandboxInfo;
- }
-private:
- MacSandboxInfo mInfo;
-};
-#endif
-
mozilla::gmp::SandboxStarter*
MakeSandboxStarter()
{
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- return new WinSandboxStarter();
-#elif defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
- return LinuxSandboxStarter::Make();
-#elif defined(XP_MACOSX) && defined(MOZ_GMP_SANDBOX)
- return new MacSandboxStarter();
-#else
return nullptr;
-#endif
}
int
@@ -147,36 +39,8 @@ content_process_main(int argc, char* argv[])
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
-
XRE_SetProcessType(argv[--argc]);
-#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
- // This has to happen while we're still single-threaded, and on
- // B2G that means before the Android Binder library is
- // initialized.
- mozilla::SandboxEarlyInit(XRE_GetProcessType());
-#endif
-
-#ifdef MOZ_WIDGET_GONK
- // This creates a ThreadPool for binder ipc. A ThreadPool is necessary to
- // receive binder calls, though not necessary to send binder calls.
- // ProcessState::Self() also needs to be called once on the main thread to
- // register the main thread with the binder driver.
-
- InitializeBinder(nullptr);
-#endif
-
#ifdef XP_WIN
// For plugins, this is done in PluginProcessChild::Init, as we need to
// avoid it for unsupported plugins. See PluginProcessChild::Init for
@@ -186,7 +50,7 @@ content_process_main(int argc, char* argv[])
SetDllDirectoryW(L"");
}
#endif
-#if !defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_WIDGET_GONK) && defined(MOZ_PLUGIN_CONTAINER)
+#if !defined(MOZ_WIDGET_ANDROID) && defined(MOZ_PLUGIN_CONTAINER)
// On desktop, the GMPLoader lives in plugin-container, so that its
// code can be covered by an EME/GMP vendor's voucher.
nsAutoPtr<mozilla::gmp::SandboxStarter> starter(MakeSandboxStarter());
diff --git a/ipc/dbus/DBusHelpers.cpp b/ipc/dbus/DBusHelpers.cpp
index 73b4596f2..f5c684572 100644
--- a/ipc/dbus/DBusHelpers.cpp
+++ b/ipc/dbus/DBusHelpers.cpp
@@ -14,12 +14,7 @@
#include "nsThreadUtils.h"
#undef CHROMIUM_LOG
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define CHROMIUM_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk", args);
-#else
#define CHROMIUM_LOG(args...) printf(args);
-#endif
namespace mozilla {
namespace ipc {
diff --git a/ipc/dbus/DBusUtils.cpp b/ipc/dbus/DBusUtils.cpp
index 6e36bca0f..7bcf749f8 100644
--- a/ipc/dbus/DBusUtils.cpp
+++ b/ipc/dbus/DBusUtils.cpp
@@ -20,12 +20,7 @@
#include "DBusUtils.h"
#undef CHROMIUM_LOG
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define CHROMIUM_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk", args);
-#else
#define CHROMIUM_LOG(args...) printf(args);
-#endif
namespace mozilla {
namespace ipc {
diff --git a/ipc/glue/GeckoChildProcessHost.cpp b/ipc/glue/GeckoChildProcessHost.cpp
index db8ab3d0a..e58408e0c 100644
--- a/ipc/glue/GeckoChildProcessHost.cpp
+++ b/ipc/glue/GeckoChildProcessHost.cpp
@@ -23,10 +23,6 @@
#include "prenv.h"
#include "nsXPCOMPrivate.h"
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
-#include "nsAppDirectoryServiceDefs.h"
-#endif
-
#include "nsExceptionHandler.h"
#include "nsDirectoryServiceDefs.h"
@@ -43,12 +39,6 @@
#ifdef XP_WIN
#include "nsIWinTaskbar.h"
#define NS_TASKBAR_CONTRACTID "@mozilla.org/windows-taskbar;1"
-
-#if defined(MOZ_SANDBOX)
-#include "mozilla/Preferences.h"
-#include "mozilla/sandboxing/sandboxLogging.h"
-#include "nsDirectoryServiceUtils.h"
-#endif
#endif
#include "nsTArray.h"
@@ -72,13 +62,9 @@ static const int kMagicAndroidSystemPropFd = 5;
#endif
static const bool kLowRightsSubprocesses =
- // We currently only attempt to drop privileges on gonk, because we
- // have no plugins or extensions to worry about breaking.
-#ifdef MOZ_WIDGET_GONK
- true
-#else
+ // We only attempted to drop privileges on gonk, because it
+ // had no plugins or extensions to worry about breaking.
false
-#endif
;
static bool
@@ -101,10 +87,6 @@ GeckoChildProcessHost::GeckoChildProcessHost(GeckoProcessType aProcessType,
mPrivileges(aPrivileges),
mMonitor("mozilla.ipc.GeckChildProcessHost.mMonitor"),
mProcessState(CREATING_CHANNEL),
-#if defined(MOZ_SANDBOX) && defined(XP_WIN)
- mEnableSandboxLogging(false),
- mSandboxLevel(0),
-#endif
mChildProcessHandle(0)
#if defined(MOZ_WIDGET_COCOA)
, mChildTask(MACH_PORT_NULL)
@@ -311,23 +293,6 @@ GeckoChildProcessHost::PrepareLaunch()
if (mProcessType == GeckoProcessType_Plugin) {
InitWindowsGroupID();
}
-
-#if defined(MOZ_CONTENT_SANDBOX)
- // We need to get the pref here as the process is launched off main thread.
- if (mProcessType == GeckoProcessType_Content) {
- mSandboxLevel = Preferences::GetInt("security.sandbox.content.level");
- mEnableSandboxLogging =
- Preferences::GetBool("security.sandbox.windows.log");
- }
-#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_WIN_SANDBOX_LOGGING");
-#endif
#endif
}
@@ -608,109 +573,10 @@ AddAppDirToCommandLine(std::vector<std::string>& aCmdLine)
aCmdLine.push_back(path.get());
#endif
}
-
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
- // Full path to the profile dir
- nsCOMPtr<nsIFile> profileDir;
- rv = directoryService->Get(NS_APP_USER_PROFILE_50_DIR,
- NS_GET_IID(nsIFile),
- getter_AddRefs(profileDir));
- if (NS_SUCCEEDED(rv)) {
- nsAutoCString path;
- MOZ_ALWAYS_SUCCEEDS(profileDir->GetNativePath(path));
- aCmdLine.push_back("-profile");
- aCmdLine.push_back(path.get());
- }
-#endif
- }
- }
-}
-
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-static void
-MaybeAddNsprLogFileAccess(std::vector<std::wstring>& aAllowedFilesReadWrite)
-{
- const char* nsprLogFileEnv = PR_GetEnv("NSPR_LOG_FILE");
- if (!nsprLogFileEnv) {
- return;
- }
-
- nsDependentCString nsprLogFilePath(nsprLogFileEnv);
- nsCOMPtr<nsIFile> nsprLogFile;
- nsresult rv = NS_NewNativeLocalFile(nsprLogFilePath, true,
- getter_AddRefs(nsprLogFile));
- if (NS_FAILED(rv)) {
- // Not an absolute path, try it as a relative one.
- nsresult rv = NS_GetSpecialDirectory(NS_OS_CURRENT_WORKING_DIR,
- getter_AddRefs(nsprLogFile));
- if (NS_FAILED(rv) || !nsprLogFile) {
- NS_WARNING("Failed to get current working directory");
- return;
- }
-
- rv = nsprLogFile->AppendRelativeNativePath(nsprLogFilePath);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
}
}
-
- nsAutoString resolvedFilePath;
- rv = nsprLogFile->GetPath(resolvedFilePath);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- // Update the environment variable as well as adding the rule, because the
- // Chromium sandbox can only allow access to fully qualified file paths. This
- // only affects the environment for the child process we're about to create,
- // because this will get reset to the original value in PerformAsyncLaunch.
- aAllowedFilesReadWrite.push_back(std::wstring(resolvedFilePath.get()));
- nsAutoCString resolvedEnvVar("NSPR_LOG_FILE=");
- AppendUTF16toUTF8(resolvedFilePath, resolvedEnvVar);
- PR_SetEnv(resolvedEnvVar.get());
}
-static void
-AddContentSandboxAllowedFiles(int32_t aSandboxLevel,
- std::vector<std::wstring>& aAllowedFilesRead)
-{
- if (aSandboxLevel < 1) {
- return;
- }
-
- nsCOMPtr<nsIFile> binDir;
- nsresult rv = NS_GetSpecialDirectory(NS_GRE_DIR, getter_AddRefs(binDir));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- nsAutoString binDirPath;
- rv = binDir->GetPath(binDirPath);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return;
- }
-
- // If bin directory is on a remote drive add read access.
- wchar_t volPath[MAX_PATH];
- if (!::GetVolumePathNameW(binDirPath.get(), volPath, MAX_PATH)) {
- return;
- }
-
- if (::GetDriveTypeW(volPath) != DRIVE_REMOTE) {
- return;
- }
-
- // Convert network share path to format for sandbox policy.
- if (Substring(binDirPath, 0, 2).Equals(L"\\\\")) {
- binDirPath.InsertLiteral(u"??\\UNC", 1);
- }
-
- binDirPath.AppendLiteral(u"\\*");
-
- aAllowedFilesRead.push_back(std::wstring(binDirPath.get()));
-}
-#endif
-
bool
GeckoChildProcessHost::PerformAsyncLaunchInternal(std::vector<std::string>& aExtraOpts, base::ProcessArchitecture arch)
{
@@ -829,33 +695,6 @@ GeckoChildProcessHost::PerformAsyncLaunchInternal(std::vector<std::string>& aExt
}
#endif // ANDROID
-#ifdef MOZ_WIDGET_GONK
- if (const char *ldPreloadPath = getenv("LD_PRELOAD")) {
- newEnvVars["LD_PRELOAD"] = ldPreloadPath;
- }
-#endif // MOZ_WIDGET_GONK
-
-#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
- // Preload libmozsandbox.so so that sandbox-related interpositions
- // can be defined there instead of in the executable.
- // (This could be made conditional on intent to use sandboxing, but
- // it's harmless for non-sandboxed processes.)
- {
- nsAutoCString preload;
- // Prepend this, because people can and do preload libpthread.
- // (See bug 1222500.)
- preload.AssignLiteral("libmozsandbox.so");
- if (const char* oldPreload = PR_GetEnv("LD_PRELOAD")) {
- // Doesn't matter if oldPreload is ""; extra separators are ignored.
- preload.Append(' ');
- preload.Append(oldPreload);
- }
- // Explicitly construct the std::string to make it clear that this
- // isn't retaining a pointer to the nsCString's buffer.
- newEnvVars["LD_PRELOAD"] = std::string(preload.get());
- }
-#endif
-
// remap the IPC socket fd to a well-known int, as the OS does for
// STDOUT_FILENO, for example
int srcChannelFd, dstChannelFd;
@@ -1021,85 +860,6 @@ GeckoChildProcessHost::PerformAsyncLaunchInternal(std::vector<std::string>& aExt
}
}
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- bool shouldSandboxCurrentProcess = false;
-
- // 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 defined(MOZ_CONTENT_SANDBOX)
- if (mSandboxLevel > 0 &&
- !PR_GetEnv("MOZ_DISABLE_CONTENT_SANDBOX")) {
- // 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.
- mSandboxBroker.SetSecurityLevelForContentProcess(mSandboxLevel);
- shouldSandboxCurrentProcess = true;
- AddContentSandboxAllowedFiles(mSandboxLevel, mAllowedFilesRead);
- }
-#endif // MOZ_CONTENT_SANDBOX
- break;
- case GeckoProcessType_Plugin:
- if (mSandboxLevel > 0 &&
- !PR_GetEnv("MOZ_DISABLE_NPAPI_SANDBOX")) {
- bool ok = mSandboxBroker.SetSecurityLevelForPluginProcess(mSandboxLevel);
- if (!ok) {
- return false;
- }
- shouldSandboxCurrentProcess = 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.
- bool isWidevine = std::any_of(aExtraOpts.begin(), aExtraOpts.end(),
- [](const std::string arg) { return arg.find("gmp-widevinecdm") != std::string::npos; });
- auto level = isWidevine ? SandboxBroker::Restricted : SandboxBroker::LockDown;
- bool ok = mSandboxBroker.SetSecurityLevelForGMPlugin(level);
- if (!ok) {
- return false;
- }
- shouldSandboxCurrentProcess = true;
- }
- break;
- case GeckoProcessType_GPU:
- break;
- case GeckoProcessType_Default:
- default:
- MOZ_CRASH("Bad process type in GeckoChildProcessHost");
- break;
- };
-
- if (shouldSandboxCurrentProcess) {
- MaybeAddNsprLogFileAccess(mAllowedFilesReadWrite);
- for (auto it = mAllowedFilesRead.begin();
- it != mAllowedFilesRead.end();
- ++it) {
- mSandboxBroker.AllowReadFile(it->c_str());
- }
-
- for (auto it = mAllowedFilesReadWrite.begin();
- it != mAllowedFilesReadWrite.end();
- ++it) {
- mSandboxBroker.AllowReadWriteFile(it->c_str());
- }
-
- for (auto it = mAllowedDirectories.begin();
- it != mAllowedDirectories.end();
- ++it) {
- mSandboxBroker.AllowDirectory(it->c_str());
- }
- }
-#endif // XP_WIN && MOZ_SANDBOX
-
// Add the application directory path (-appdir path)
AddAppDirToCommandLine(cmdLine);
@@ -1116,33 +876,8 @@ GeckoChildProcessHost::PerformAsyncLaunchInternal(std::vector<std::string>& aExt
// Process type
cmdLine.AppendLooseValue(UTF8ToWide(childProcessType));
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- if (shouldSandboxCurrentProcess) {
- if (mSandboxBroker.LaunchApp(cmdLine.program().c_str(),
- cmdLine.command_line_string().c_str(),
- mEnableSandboxLogging,
- &process)) {
- EnvironmentLog("MOZ_PROCESS_LOG").print(
- "==> process %d launched child process %d (%S)\n",
- base::GetCurrentProcId(), base::GetProcId(process),
- cmdLine.command_line_string().c_str());
- }
- } else
-#endif
{
base::LaunchApp(cmdLine, false, false, &process);
-
-#ifdef MOZ_SANDBOX
- // We need to be able to duplicate handles to some types of non-sandboxed
- // child processes.
- if (mProcessType == GeckoProcessType_Content ||
- mProcessType == GeckoProcessType_GPU ||
- mProcessType == GeckoProcessType_GMPlugin) {
- if (!mSandboxBroker.AddTargetPeer(process)) {
- NS_WARNING("Failed to add content process as target peer.");
- }
- }
-#endif
}
#else
diff --git a/ipc/glue/GeckoChildProcessHost.h b/ipc/glue/GeckoChildProcessHost.h
index 3d55564ac..d278d8928 100644
--- a/ipc/glue/GeckoChildProcessHost.h
+++ b/ipc/glue/GeckoChildProcessHost.h
@@ -21,10 +21,6 @@
#include "nsXULAppAPI.h" // for GeckoProcessType
#include "nsString.h"
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-#include "sandboxBroker.h"
-#endif
-
namespace mozilla {
namespace ipc {
@@ -153,15 +149,6 @@ protected:
#ifdef XP_WIN
void InitWindowsGroupID();
nsString mGroupId;
-
-#ifdef MOZ_SANDBOX
- SandboxBroker mSandboxBroker;
- std::vector<std::wstring> mAllowedFilesRead;
- std::vector<std::wstring> mAllowedFilesReadWrite;
- std::vector<std::wstring> mAllowedDirectories;
- bool mEnableSandboxLogging;
- int32_t mSandboxLevel;
-#endif
#endif // XP_WIN
#if defined(OS_POSIX)
diff --git a/ipc/glue/MessageChannel.cpp b/ipc/glue/MessageChannel.cpp
index 70e2387d5..7861f3e2d 100644
--- a/ipc/glue/MessageChannel.cpp
+++ b/ipc/glue/MessageChannel.cpp
@@ -27,13 +27,8 @@ using mozilla::Move;
// Undo the damage done by mozzconf.h
#undef compress
-// Logging seems to be somewhat broken on b2g.
-#ifdef MOZ_B2G
-#define IPC_LOG(...)
-#else
static mozilla::LazyLogModule sLogModule("ipc");
#define IPC_LOG(...) MOZ_LOG(sLogModule, LogLevel::Debug, (__VA_ARGS__))
-#endif
/*
* IPC design:
diff --git a/ipc/glue/ProtocolUtils.cpp b/ipc/glue/ProtocolUtils.cpp
index 4de131469..7d8a1153c 100644
--- a/ipc/glue/ProtocolUtils.cpp
+++ b/ipc/glue/ProtocolUtils.cpp
@@ -20,11 +20,6 @@
#include "mozilla/Unused.h"
#include "nsPrintfCString.h"
-#if defined(MOZ_SANDBOX) && defined(XP_WIN)
-#define TARGET_SANDBOX_EXPORTS
-#include "mozilla/sandboxTarget.h"
-#endif
-
#include "nsAutoPtr.h"
using namespace IPC;
@@ -162,17 +157,6 @@ bool DuplicateHandle(HANDLE aSourceHandle,
}
-#if defined(MOZ_SANDBOX)
- // Try the broker next (will fail if not sandboxed).
- if (SandboxTarget::Instance()->BrokerDuplicateHandle(aSourceHandle,
- aTargetProcessId,
- aTargetHandle,
- aDesiredAccess,
- aOptions)) {
- return true;
- }
-#endif
-
// Finally, see if we already have access to the process.
ScopedProcessHandle targetProcess(OpenProcess(PROCESS_DUP_HANDLE,
FALSE,
diff --git a/ipc/glue/moz.build b/ipc/glue/moz.build
index dd3a2e1ba..8caee1ffe 100644
--- a/ipc/glue/moz.build
+++ b/ipc/glue/moz.build
@@ -196,12 +196,5 @@ for var in ('MOZ_CHILD_PROCESS_NAME', 'MOZ_CHILD_PROCESS_NAME_PIE',
'MOZ_CHILD_PROCESS_BUNDLE', 'DLL_PREFIX', 'DLL_SUFFIX'):
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['GNU_CXX']:
CXXFLAGS += ['-Wno-shadow']
diff --git a/ipc/hal/DaemonRunnables.h b/ipc/hal/DaemonRunnables.h
deleted file mode 100644
index e4a528a9b..000000000
--- a/ipc/hal/DaemonRunnables.h
+++ /dev/null
@@ -1,950 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_DaemonRunnables_h
-#define mozilla_ipc_DaemonRunnables_h
-
-#include "mozilla/Unused.h"
-#include "mozilla/UniquePtr.h"
-#include "nsThreadUtils.h"
-
-namespace mozilla {
-namespace ipc {
-
-namespace details {
-
-class DaemonRunnable : public Runnable
-{
-protected:
- DaemonRunnable() = default;
- virtual ~DaemonRunnable() = default;
-
- template<typename Out, typename In>
- static Out& ConvertArg(In& aArg)
- {
- return aArg;
- }
-
- template<typename Out, typename In>
- static Out ConvertArg(UniquePtr<In>& aArg)
- {
- return aArg.get();
- }
-};
-
-} // namespace detail
-
-//
-// Result handling
-//
-// The classes of type |DaemonResultRunnable[0..3]| transfer a result
-// handler from the I/O thread to the main thread for execution. Call
-// the methods |Create| and |Dispatch| to create or create-and-dispatch
-// a result runnable.
-//
-// You need to specify the called method. The |Create| and |Dispatch|
-// methods of |DaemonResultRunnable[1..3]| receive an extra argument
-// for initializing the result's arguments. During creation, the result
-// runnable calls the supplied class's call operator with the result's
-// argument. This is where initialization and conversion from backend-
-// specific types is performed.
-//
-
-template <typename Obj, typename Res>
-class DaemonResultRunnable0 final : public details::DaemonRunnable
-{
-public:
- typedef DaemonResultRunnable0<Obj, Res> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType>
- Create(Obj* aObj, Res (Obj::*aMethod)(), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aObj, aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(Obj* aObj, Res (Obj::*aMethod)(), const InitOp& aInitOp)
- {
- if (!aObj) {
- return; // silently return if no result runnable has been given
- }
- RefPtr<SelfType> runnable = Create(aObj, aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- ((*mObj).*mMethod)();
- return NS_OK;
- }
-
-private:
- DaemonResultRunnable0(Obj* aObj, Res (Obj::*aMethod)())
- : mObj(aObj)
- , mMethod(aMethod)
- {
- MOZ_ASSERT(mObj);
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- return aInitOp();
- }
-
- RefPtr<Obj> mObj;
- void (Obj::*mMethod)();
-};
-
-template <typename Obj, typename Res, typename Tin1, typename Arg1>
-class DaemonResultRunnable1 final : public details::DaemonRunnable
-{
-public:
- typedef DaemonResultRunnable1<Obj, Res, Tin1, Arg1> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType>
- Create(Obj* aObj, Res (Obj::*aMethod)(Arg1), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aObj, aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(Obj* aObj, Res (Obj::*aMethod)(Arg1), const InitOp& aInitOp)
- {
- if (!aObj) {
- return; // silently return if no result runnable has been given
- }
- RefPtr<SelfType> runnable = Create(aObj, aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- ((*mObj).*mMethod)(ConvertArg<Arg1>(mArg1));
- return NS_OK;
- }
-
-private:
- DaemonResultRunnable1(Obj* aObj, Res (Obj::*aMethod)(Arg1))
- : mObj(aObj)
- , mMethod(aMethod)
- {
- MOZ_ASSERT(mObj);
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- return aInitOp(mArg1);
- }
-
- RefPtr<Obj> mObj;
- Res (Obj::*mMethod)(Arg1);
- Tin1 mArg1;
-};
-
-template <typename Obj, typename Res,
- typename Tin1, typename Tin2, typename Tin3,
- typename Arg1, typename Arg2, typename Arg3>
-class DaemonResultRunnable3 final : public details::DaemonRunnable
-{
-public:
- typedef DaemonResultRunnable3<Obj, Res,
- Tin1, Tin2, Tin3,
- Arg1, Arg2, Arg3> SelfType;
-
- template<typename InitOp>
- static already_AddRefed<SelfType>
- Create(Obj* aObj, Res (Obj::*aMethod)(Arg1, Arg2, Arg3),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aObj, aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template<typename InitOp>
- static void
- Dispatch(Obj* aObj, Res (Obj::*aMethod)(Arg1, Arg2, Arg3),
- const InitOp& aInitOp)
- {
- if (!aObj) {
- return; // silently return if no result runnable has been given
- }
- RefPtr<SelfType> runnable = Create(aObj, aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- ((*mObj).*mMethod)(ConvertArg<Arg1>(mArg1),
- ConvertArg<Arg2>(mArg2),
- ConvertArg<Arg3>(mArg3));
- return NS_OK;
- }
-
-private:
- DaemonResultRunnable3(Obj* aObj, Res (Obj::*aMethod)(Arg1, Arg2, Arg3))
- : mObj(aObj)
- , mMethod(aMethod)
- {
- MOZ_ASSERT(mObj);
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult
- Init(const InitOp& aInitOp)
- {
- return aInitOp(mArg1, mArg2, mArg3);
- }
-
- RefPtr<Obj> mObj;
- Res (Obj::*mMethod)(Arg1, Arg2, Arg3);
- Tin1 mArg1;
- Tin2 mArg2;
- Tin3 mArg3;
-};
-
-//
-// Notification handling
-//
-// The classes of type |DaemonNotificationRunnable[0..9]| transfer a
-// notification from the I/O thread to a notification handler on the
-// main thread. Call the methods |Create| and |Dispatch| to create or
-// create-and-dispatch a notification runnable.
-//
-// Like with result runnables, you need to specify the called method.
-// And like with result runnables, the |Create| and |Dispatch| methods
-// of |DaemonNotificationRunnable[1..9]| receive an extra argument
-// for initializing the notification's arguments. During creation, the
-// notification runnable calls the class's call operator with the
-// notification's argument. This is where initialization and conversion
-// from backend-specific types is performed.
-//
-
-template <typename ObjectWrapper, typename Res>
-class DaemonNotificationRunnable0 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable0<ObjectWrapper, Res> SelfType;
-
- template<typename InitOp>
- static already_AddRefed<SelfType>
- Create(Res (ObjectType::*aMethod)(), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template<typename InitOp>
- static void
- Dispatch(Res (ObjectType::*aMethod)(), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)();
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable0(Res (ObjectType::*aMethod)())
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- return aInitOp();
- }
-
- Res (ObjectType::*mMethod)();
-};
-
-template <typename ObjectWrapper, typename Res,
- typename Tin1, typename Arg1=Tin1>
-class DaemonNotificationRunnable1 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable1<ObjectWrapper, Res,
- Tin1, Arg1> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType>
- Create(Res (ObjectType::*aMethod)(Arg1), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(Res (ObjectType::*aMethod)(Arg1), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)(ConvertArg<Arg1>(mArg1));
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable1(Res (ObjectType::*aMethod)(Arg1))
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- nsresult rv = aInitOp(mArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
- }
-
- Res (ObjectType::*mMethod)(Arg1);
- Tin1 mArg1;
-};
-
-template <typename ObjectWrapper, typename Res,
- typename Tin1, typename Tin2,
- typename Arg1=Tin1, typename Arg2=Tin2>
-class DaemonNotificationRunnable2 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable2<ObjectWrapper, Res,
- Tin1, Tin2,
- Arg1, Arg2> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType>
- Create(Res (ObjectType::*aMethod)(Arg1, Arg2), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(Res (ObjectType::*aMethod)(Arg1, Arg2), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)(ConvertArg<Arg1>(mArg1),
- ConvertArg<Arg2>(mArg2));
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable2(
- Res (ObjectType::*aMethod)(Arg1, Arg2))
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- nsresult rv = aInitOp(mArg1, mArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
- }
-
- Res (ObjectType::*mMethod)(Arg1, Arg2);
- Tin1 mArg1;
- Tin2 mArg2;
-};
-
-template <typename ObjectWrapper, typename Res,
- typename Tin1, typename Tin2, typename Tin3,
- typename Arg1=Tin1, typename Arg2=Tin2, typename Arg3=Tin3>
-class DaemonNotificationRunnable3 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable3<ObjectWrapper, Res,
- Tin1, Tin2, Tin3,
- Arg1, Arg2, Arg3> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType>
- Create(Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3), const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)(ConvertArg<Arg1>(mArg1),
- ConvertArg<Arg2>(mArg2),
- ConvertArg<Arg3>(mArg3));
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable3(
- Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3))
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- nsresult rv = aInitOp(mArg1, mArg2, mArg3);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
- }
-
- Res (ObjectType::*mMethod)(Arg1, Arg2, Arg3);
- Tin1 mArg1;
- Tin2 mArg2;
- Tin3 mArg3;
-};
-
-template <typename ObjectWrapper, typename Res,
- typename Tin1, typename Tin2, typename Tin3, typename Tin4,
- typename Arg1=Tin1, typename Arg2=Tin2,
- typename Arg3=Tin3, typename Arg4=Tin4>
-class DaemonNotificationRunnable4 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable4<ObjectWrapper, Res,
- Tin1, Tin2, Tin3, Tin4, Arg1, Arg2, Arg3, Arg4> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType> Create(
- Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)(ConvertArg<Arg1>(mArg1),
- ConvertArg<Arg2>(mArg2),
- ConvertArg<Arg3>(mArg3),
- ConvertArg<Arg4>(mArg4));
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable4(
- Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4))
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- nsresult rv = aInitOp(mArg1, mArg2, mArg3, mArg4);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
- }
-
- Res (ObjectType::*mMethod)(Arg1, Arg2, Arg3, Arg4);
- Tin1 mArg1;
- Tin2 mArg2;
- Tin3 mArg3;
- Tin4 mArg4;
-};
-
-template <typename ObjectWrapper, typename Res,
- typename Tin1, typename Tin2, typename Tin3,
- typename Tin4, typename Tin5,
- typename Arg1=Tin1, typename Arg2=Tin2, typename Arg3=Tin3,
- typename Arg4=Tin4, typename Arg5=Tin5>
-class DaemonNotificationRunnable5 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable5<ObjectWrapper, Res,
- Tin1, Tin2, Tin3, Tin4, Tin5, Arg1, Arg2, Arg3, Arg4, Arg5> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType> Create(
- Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4, Arg5),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4, Arg5),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)(ConvertArg<Arg1>(mArg1),
- ConvertArg<Arg2>(mArg2),
- ConvertArg<Arg3>(mArg3),
- ConvertArg<Arg4>(mArg4),
- ConvertArg<Arg5>(mArg5));
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable5(
- Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4, Arg5))
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- nsresult rv = aInitOp(mArg1, mArg2, mArg3, mArg4, mArg5);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
- }
-
- Res (ObjectType::*mMethod)(Arg1, Arg2, Arg3, Arg4, Arg5);
- Tin1 mArg1;
- Tin2 mArg2;
- Tin3 mArg3;
- Tin4 mArg4;
- Tin5 mArg5;
-};
-
-template <typename ObjectWrapper, typename Res,
- typename Tin1, typename Tin2, typename Tin3,
- typename Tin4, typename Tin5, typename Tin6,
- typename Arg1=Tin1, typename Arg2=Tin2, typename Arg3=Tin3,
- typename Arg4=Tin4, typename Arg5=Tin5, typename Arg6=Tin6>
-class DaemonNotificationRunnable6 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable6<ObjectWrapper, Res,
- Tin1, Tin2, Tin3, Tin4, Tin5, Tin6, Arg1, Arg2, Arg3, Arg4, Arg5, Arg6>
- SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType> Create(
- Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)(ConvertArg<Arg1>(mArg1),
- ConvertArg<Arg2>(mArg2),
- ConvertArg<Arg3>(mArg3),
- ConvertArg<Arg4>(mArg4),
- ConvertArg<Arg5>(mArg5),
- ConvertArg<Arg6>(mArg6));
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable6(
- Res (ObjectType::*aMethod)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6))
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- nsresult rv = aInitOp(mArg1, mArg2, mArg3, mArg4, mArg5, mArg6);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
- }
-
- Res (ObjectType::*mMethod)(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6);
- Tin1 mArg1;
- Tin2 mArg2;
- Tin3 mArg3;
- Tin4 mArg4;
- Tin5 mArg5;
- Tin6 mArg6;
-};
-
-template <typename ObjectWrapper, typename Res,
- typename Tin1, typename Tin2, typename Tin3,
- typename Tin4, typename Tin5, typename Tin6,
- typename Tin7, typename Tin8,
- typename Arg1=Tin1, typename Arg2=Tin2, typename Arg3=Tin3,
- typename Arg4=Tin4, typename Arg5=Tin5, typename Arg6=Tin6,
- typename Arg7=Tin7, typename Arg8=Tin8>
-class DaemonNotificationRunnable8 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable8<ObjectWrapper, Res,
- Tin1, Tin2, Tin3, Tin4, Tin5, Tin6, Tin7, Tin8,
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType> Create(
- Res (ObjectType::*aMethod)(
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(
- Res (ObjectType::*aMethod)(
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)(ConvertArg<Arg1>(mArg1),
- ConvertArg<Arg2>(mArg2),
- ConvertArg<Arg3>(mArg3),
- ConvertArg<Arg4>(mArg4),
- ConvertArg<Arg5>(mArg5),
- ConvertArg<Arg6>(mArg6),
- ConvertArg<Arg7>(mArg7),
- ConvertArg<Arg8>(mArg8));
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable8(
- Res (ObjectType::*aMethod)(
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8))
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- nsresult rv = aInitOp(mArg1, mArg2, mArg3, mArg4,
- mArg5, mArg6, mArg7, mArg8);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
- }
-
- Res (ObjectType::*mMethod)(
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8);
- Tin1 mArg1;
- Tin2 mArg2;
- Tin3 mArg3;
- Tin4 mArg4;
- Tin5 mArg5;
- Tin6 mArg6;
- Tin7 mArg7;
- Tin8 mArg8;
-};
-
-template <typename ObjectWrapper, typename Res,
- typename Tin1, typename Tin2, typename Tin3,
- typename Tin4, typename Tin5, typename Tin6,
- typename Tin7, typename Tin8, typename Tin9,
- typename Arg1=Tin1, typename Arg2=Tin2, typename Arg3=Tin3,
- typename Arg4=Tin4, typename Arg5=Tin5, typename Arg6=Tin6,
- typename Arg7=Tin7, typename Arg8=Tin8, typename Arg9=Tin9>
-class DaemonNotificationRunnable9 final : public details::DaemonRunnable
-{
-public:
- typedef typename ObjectWrapper::ObjectType ObjectType;
- typedef DaemonNotificationRunnable9<ObjectWrapper, Res,
- Tin1, Tin2, Tin3, Tin4, Tin5, Tin6, Tin7, Tin8, Tin9,
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9> SelfType;
-
- template <typename InitOp>
- static already_AddRefed<SelfType> Create(
- Res (ObjectType::*aMethod)(
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable(new SelfType(aMethod));
- if (NS_FAILED(runnable->Init(aInitOp))) {
- return nullptr;
- }
- return runnable.forget();
- }
-
- template <typename InitOp>
- static void
- Dispatch(
- Res (ObjectType::*aMethod)(
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9),
- const InitOp& aInitOp)
- {
- RefPtr<SelfType> runnable = Create(aMethod, aInitOp);
- if (!runnable) {
- return;
- }
- Unused << NS_WARN_IF(NS_FAILED(NS_DispatchToMainThread(runnable)));
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- ObjectType* obj = ObjectWrapper::GetInstance();
- if (!obj) {
- NS_WARNING("Notification handler not initialized");
- } else {
- ((*obj).*mMethod)(ConvertArg<Arg1>(mArg1),
- ConvertArg<Arg2>(mArg2),
- ConvertArg<Arg3>(mArg3),
- ConvertArg<Arg4>(mArg4),
- ConvertArg<Arg5>(mArg5),
- ConvertArg<Arg6>(mArg6),
- ConvertArg<Arg7>(mArg7),
- ConvertArg<Arg8>(mArg8),
- ConvertArg<Arg9>(mArg9));
- }
- return NS_OK;
- }
-
-private:
- DaemonNotificationRunnable9(
- Res (ObjectType::*aMethod)(
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9))
- : mMethod(aMethod)
- {
- MOZ_ASSERT(mMethod);
- }
-
- template<typename InitOp>
- nsresult Init(const InitOp& aInitOp)
- {
- nsresult rv = aInitOp(mArg1, mArg2, mArg3, mArg4,
- mArg5, mArg6, mArg7, mArg8, mArg9);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
- }
-
- Res (ObjectType::*mMethod)(
- Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9);
- Tin1 mArg1;
- Tin2 mArg2;
- Tin3 mArg3;
- Tin4 mArg4;
- Tin5 mArg5;
- Tin6 mArg6;
- Tin7 mArg7;
- Tin8 mArg8;
- Tin9 mArg9;
-};
-
-}
-}
-
-#endif // mozilla_ipc_DaemonRunnables_h
diff --git a/ipc/hal/DaemonSocket.cpp b/ipc/hal/DaemonSocket.cpp
deleted file mode 100644
index 94c36b955..000000000
--- a/ipc/hal/DaemonSocket.cpp
+++ /dev/null
@@ -1,263 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "DaemonSocket.h"
-#include "mozilla/ipc/DaemonSocketConsumer.h"
-#include "mozilla/ipc/DaemonSocketPDU.h"
-#include "mozilla/UniquePtr.h"
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-
-#ifdef CHROMIUM_LOG
-#undef CHROMIUM_LOG
-#endif
-
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define CHROMIUM_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "I/O", args);
-#else
-#include <stdio.h>
-#define IODEBUG true
-#define CHROMIUM_LOG(args...) if (IODEBUG) printf(args);
-#endif
-
-namespace mozilla {
-namespace ipc {
-
-//
-// DaemonSocketIO
-//
-
-class DaemonSocketIO final : public ConnectionOrientedSocketIO
-{
-public:
- DaemonSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- int aFd, ConnectionStatus aConnectionStatus,
- UnixSocketConnector* aConnector,
- DaemonSocket* aConnection,
- DaemonSocketIOConsumer* aConsumer);
-
- ~DaemonSocketIO();
-
- // Methods for |DataSocketIO|
- //
-
- nsresult QueryReceiveBuffer(UnixSocketIOBuffer** aBuffer) override;
- void ConsumeBuffer() override;
- void DiscardBuffer() override;
-
- // Methods for |SocketIOBase|
- //
-
- SocketBase* GetSocketBase() override;
-
- bool IsShutdownOnConsumerThread() const override;
- bool IsShutdownOnIOThread() const override;
-
- void ShutdownOnConsumerThread() override;
- void ShutdownOnIOThread() override;
-
-private:
- DaemonSocket* mConnection;
- DaemonSocketIOConsumer* mConsumer;
- UniquePtr<DaemonSocketPDU> mPDU;
- bool mShuttingDownOnIOThread;
-};
-
-DaemonSocketIO::DaemonSocketIO(
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- int aFd,
- ConnectionStatus aConnectionStatus,
- UnixSocketConnector* aConnector,
- DaemonSocket* aConnection,
- DaemonSocketIOConsumer* aConsumer)
- : ConnectionOrientedSocketIO(aConsumerLoop,
- aIOLoop,
- aFd,
- aConnectionStatus,
- aConnector)
- , mConnection(aConnection)
- , mConsumer(aConsumer)
- , mShuttingDownOnIOThread(false)
-{
- MOZ_ASSERT(mConnection);
- MOZ_ASSERT(mConsumer);
-
- MOZ_COUNT_CTOR_INHERITED(DaemonSocketIO, ConnectionOrientedSocketIO);
-}
-
-DaemonSocketIO::~DaemonSocketIO()
-{
- MOZ_COUNT_DTOR_INHERITED(DaemonSocketIO, ConnectionOrientedSocketIO);
-}
-
-// |DataSocketIO|
-
-nsresult
-DaemonSocketIO::QueryReceiveBuffer(UnixSocketIOBuffer** aBuffer)
-{
- MOZ_ASSERT(aBuffer);
-
- if (!mPDU) {
- /* There's only one PDU for receiving. We reuse it every time. */
- mPDU = MakeUnique<DaemonSocketPDU>(DaemonSocketPDU::PDU_MAX_PAYLOAD_LENGTH);
- }
- *aBuffer = mPDU.get();
-
- return NS_OK;
-}
-
-void
-DaemonSocketIO::ConsumeBuffer()
-{
- MOZ_ASSERT(mConsumer);
-
- mConsumer->Handle(*mPDU);
-}
-
-void
-DaemonSocketIO::DiscardBuffer()
-{
- // Nothing to do.
-}
-
-// |SocketIOBase|
-
-SocketBase*
-DaemonSocketIO::GetSocketBase()
-{
- return mConnection;
-}
-
-bool
-DaemonSocketIO::IsShutdownOnConsumerThread() const
-{
- MOZ_ASSERT(IsConsumerThread());
-
- return mConnection == nullptr;
-}
-
-bool
-DaemonSocketIO::IsShutdownOnIOThread() const
-{
- return mShuttingDownOnIOThread;
-}
-
-void
-DaemonSocketIO::ShutdownOnConsumerThread()
-{
- MOZ_ASSERT(IsConsumerThread());
- MOZ_ASSERT(!IsShutdownOnConsumerThread());
-
- mConnection = nullptr;
-}
-
-void
-DaemonSocketIO::ShutdownOnIOThread()
-{
- MOZ_ASSERT(!IsConsumerThread());
- MOZ_ASSERT(!mShuttingDownOnIOThread);
-
- Close(); // will also remove fd from I/O loop
- mShuttingDownOnIOThread = true;
-}
-
-//
-// DaemonSocket
-//
-
-DaemonSocket::DaemonSocket(
- DaemonSocketIOConsumer* aIOConsumer,
- DaemonSocketConsumer* aConsumer,
- int aIndex)
- : mIO(nullptr)
- , mIOConsumer(aIOConsumer)
- , mConsumer(aConsumer)
- , mIndex(aIndex)
-{
- MOZ_ASSERT(mConsumer);
-
- MOZ_COUNT_CTOR_INHERITED(DaemonSocket, ConnectionOrientedSocket);
-}
-
-DaemonSocket::~DaemonSocket()
-{
- MOZ_COUNT_DTOR_INHERITED(DaemonSocket, ConnectionOrientedSocket);
-}
-
-// |ConnectionOrientedSocket|
-
-nsresult
-DaemonSocket::PrepareAccept(UnixSocketConnector* aConnector,
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ConnectionOrientedSocketIO*& aIO)
-{
- MOZ_ASSERT(!mIO);
-
- SetConnectionStatus(SOCKET_CONNECTING);
-
- mIO = new DaemonSocketIO(
- aConsumerLoop, aIOLoop, -1, UnixSocketWatcher::SOCKET_IS_CONNECTING,
- aConnector, this, mIOConsumer);
- aIO = mIO;
-
- return NS_OK;
-}
-
-// |DataSocket|
-
-void
-DaemonSocket::SendSocketData(UnixSocketIOBuffer* aBuffer)
-{
- MOZ_ASSERT(mIO);
- MOZ_ASSERT(mIO->IsConsumerThread());
-
- mIO->GetIOLoop()->PostTask(
- MakeAndAddRef<SocketIOSendTask<DaemonSocketIO, UnixSocketIOBuffer>>(
- mIO, aBuffer));
-}
-
-// |SocketBase|
-
-void
-DaemonSocket::Close()
-{
- if (!mIO) {
- CHROMIUM_LOG("HAL daemon already disconnected!");
- return;
- }
-
- MOZ_ASSERT(mIO->IsConsumerThread());
-
- mIO->ShutdownOnConsumerThread();
- mIO->GetIOLoop()->PostTask(MakeAndAddRef<SocketIOShutdownTask>(mIO));
- mIO = nullptr;
-
- NotifyDisconnect();
-}
-
-void
-DaemonSocket::OnConnectSuccess()
-{
- mConsumer->OnConnectSuccess(mIndex);
-}
-
-void
-DaemonSocket::OnConnectError()
-{
- mConsumer->OnConnectError(mIndex);
-}
-
-void
-DaemonSocket::OnDisconnect()
-{
- mConsumer->OnDisconnect(mIndex);
-}
-
-}
-}
diff --git a/ipc/hal/DaemonSocket.h b/ipc/hal/DaemonSocket.h
deleted file mode 100644
index 63d3a2e5c..000000000
--- a/ipc/hal/DaemonSocket.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_DaemonSocket_h
-#define mozilla_ipc_DaemonSocket_h
-
-#include "mozilla/ipc/ConnectionOrientedSocket.h"
-
-namespace mozilla {
-namespace ipc {
-
-class DaemonSocketConsumer;
-class DaemonSocketIO;
-class DaemonSocketIOConsumer;
-
-/**
- * |DaemonSocket| represents the socket to connect to the HAL daemon. It
- * offers connection establishment and sending PDUs. PDU receiving is
- * performed by |DaemonSocketIOConsumer|.
- */
-class DaemonSocket : public ConnectionOrientedSocket
-{
-public:
- DaemonSocket(DaemonSocketIOConsumer* aIOConsumer,
- DaemonSocketConsumer* aConsumer,
- int aIndex);
- virtual ~DaemonSocket();
-
- // Methods for |ConnectionOrientedSocket|
- //
-
- nsresult PrepareAccept(UnixSocketConnector* aConnector,
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ConnectionOrientedSocketIO*& aIO) override;
-
- // Methods for |DataSocket|
- //
-
- void SendSocketData(UnixSocketIOBuffer* aBuffer) override;
-
- // Methods for |SocketBase|
- //
-
- void Close() override;
- void OnConnectSuccess() override;
- void OnConnectError() override;
- void OnDisconnect() override;
-
-private:
- DaemonSocketIO* mIO;
- DaemonSocketIOConsumer* mIOConsumer;
- DaemonSocketConsumer* mConsumer;
- int mIndex;
-};
-
-}
-}
-
-#endif
diff --git a/ipc/hal/DaemonSocketConnector.cpp b/ipc/hal/DaemonSocketConnector.cpp
deleted file mode 100644
index 97106bdd0..000000000
--- a/ipc/hal/DaemonSocketConnector.cpp
+++ /dev/null
@@ -1,244 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "DaemonSocketConnector.h"
-#include <fcntl.h>
-#include <limits.h>
-#include <stddef.h>
-#include <string.h>
-#include <sys/un.h>
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-#include "prrng.h"
-
-#ifdef CHROMIUM_LOG
-#undef CHROMIUM_LOG
-#endif
-
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define CHROMIUM_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "I/O", args);
-#else
-#include <stdio.h>
-#define IODEBUG true
-#define CHROMIUM_LOG(args...) if (IODEBUG) printf(args);
-#endif
-
-namespace mozilla {
-namespace ipc {
-
-nsresult
-DaemonSocketConnector::CreateRandomAddressString(
- const nsACString& aPrefix, unsigned long aPostfixLength,
- nsACString& aAddress)
-{
- static const char sHexChar[16] = {
- [0x0] = '0', [0x1] = '1', [0x2] = '2', [0x3] = '3',
- [0x4] = '4', [0x5] = '5', [0x6] = '6', [0x7] = '7',
- [0x8] = '8', [0x9] = '9', [0xa] = 'a', [0xb] = 'b',
- [0xc] = 'c', [0xd] = 'd', [0xe] = 'e', [0xf] = 'f'
- };
-
- unsigned short seed[3];
-
- if (NS_WARN_IF(!PR_GetRandomNoise(seed, sizeof(seed)))) {
- return NS_ERROR_NOT_IMPLEMENTED;
- }
-
- aAddress = aPrefix;
- aAddress.Append('-');
-
- while (aPostfixLength) {
- // Android doesn't provide rand_r, so we use nrand48 here,
- // even though it's deprecated.
- long value = nrand48(seed);
-
- size_t bits = sizeof(value) * CHAR_BIT;
-
- while ((bits > 4) && aPostfixLength) {
- aAddress.Append(sHexChar[value&0xf]);
- bits -= 4;
- value >>= 4;
- --aPostfixLength;
- }
- }
-
- return NS_OK;
-}
-
-DaemonSocketConnector::DaemonSocketConnector(const nsACString& aSocketName)
- : mSocketName(aSocketName)
-{
- MOZ_COUNT_CTOR_INHERITED(DaemonSocketConnector, UnixSocketConnector);
-}
-
-DaemonSocketConnector::~DaemonSocketConnector()
-{
- MOZ_COUNT_CTOR_INHERITED(DaemonSocketConnector, UnixSocketConnector);
-}
-
-nsresult
-DaemonSocketConnector::CreateSocket(int& aFd) const
-{
- aFd = socket(AF_UNIX, SOCK_SEQPACKET, 0);
- if (aFd < 0) {
- CHROMIUM_LOG("Could not open daemon socket!");
- return NS_ERROR_FAILURE;
- }
-
- return NS_OK;
-}
-
-nsresult
-DaemonSocketConnector::SetSocketFlags(int aFd) const
-{
- static const int sReuseAddress = 1;
-
- // Set close-on-exec bit.
- int flags = TEMP_FAILURE_RETRY(fcntl(aFd, F_GETFD));
- if (flags < 0) {
- return NS_ERROR_FAILURE;
- }
- flags |= FD_CLOEXEC;
- int res = TEMP_FAILURE_RETRY(fcntl(aFd, F_SETFD, flags));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- // Set non-blocking status flag.
- flags = TEMP_FAILURE_RETRY(fcntl(aFd, F_GETFL));
- if (flags < 0) {
- return NS_ERROR_FAILURE;
- }
- flags |= O_NONBLOCK;
- res = TEMP_FAILURE_RETRY(fcntl(aFd, F_SETFL, flags));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- // Set socket addr to be reused even if kernel is still waiting to close.
- res = setsockopt(aFd, SOL_SOCKET, SO_REUSEADDR, &sReuseAddress,
- sizeof(sReuseAddress));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- return NS_OK;
-}
-
-nsresult
-DaemonSocketConnector::CreateAddress(struct sockaddr& aAddress,
- socklen_t& aAddressLength) const
-{
- static const size_t sNameOffset = 1;
-
- struct sockaddr_un* address =
- reinterpret_cast<struct sockaddr_un*>(&aAddress);
-
- size_t namesiz = mSocketName.Length() + 1; // include trailing '\0'
-
- if (NS_WARN_IF((sNameOffset + namesiz) > sizeof(address->sun_path))) {
- return NS_ERROR_FAILURE;
- }
-
- address->sun_family = AF_UNIX;
- memset(address->sun_path, '\0', sNameOffset); // abstract socket
- memcpy(address->sun_path + sNameOffset, mSocketName.get(), namesiz);
-
- aAddressLength =
- offsetof(struct sockaddr_un, sun_path) + sNameOffset + namesiz;
-
- return NS_OK;
-}
-
-// |UnixSocketConnector|
-
-nsresult
-DaemonSocketConnector::ConvertAddressToString(
- const struct sockaddr& aAddress, socklen_t aAddressLength,
- nsACString& aAddressString)
-{
- MOZ_ASSERT(aAddress.sa_family == AF_UNIX);
-
- const struct sockaddr_un* un =
- reinterpret_cast<const struct sockaddr_un*>(&aAddress);
-
- size_t len = aAddressLength - offsetof(struct sockaddr_un, sun_path);
-
- aAddressString.Assign(un->sun_path, len);
-
- return NS_OK;
-}
-
-nsresult
-DaemonSocketConnector::CreateListenSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aListenFd)
-{
- ScopedClose fd;
-
- nsresult rv = CreateSocket(fd.rwget());
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = SetSocketFlags(fd);
- if (NS_FAILED(rv)) {
- return rv;
- }
- if (aAddress && aAddressLength) {
- rv = CreateAddress(*aAddress, *aAddressLength);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
-
- aListenFd = fd.forget();
-
- return NS_OK;
-}
-
-nsresult
-DaemonSocketConnector::AcceptStreamSocket(int aListenFd,
- struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd)
-{
- ScopedClose fd(
- TEMP_FAILURE_RETRY(accept(aListenFd, aAddress, aAddressLength)));
- if (fd < 0) {
- CHROMIUM_LOG("Cannot accept file descriptor!");
- return NS_ERROR_FAILURE;
- }
- nsresult rv = SetSocketFlags(fd);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- aStreamFd = fd.forget();
-
- return NS_OK;
-}
-
-nsresult
-DaemonSocketConnector::CreateStreamSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd)
-{
- MOZ_CRASH("|DaemonSocketConnector| does not support "
- "creating stream sockets.");
- return NS_ERROR_ABORT;
-}
-
-nsresult
-DaemonSocketConnector::Duplicate(UnixSocketConnector*& aConnector)
-{
- aConnector = new DaemonSocketConnector(*this);
-
- return NS_OK;
-}
-
-} // namespace ipc
-} // namespace mozilla
diff --git a/ipc/hal/DaemonSocketConnector.h b/ipc/hal/DaemonSocketConnector.h
deleted file mode 100644
index b7f2b8045..000000000
--- a/ipc/hal/DaemonSocketConnector.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_DaemonSocketConnector_h
-#define mozilla_ipc_DaemonSocketConnector_h
-
-#include "mozilla/ipc/UnixSocketConnector.h"
-#include "nsString.h"
-
-namespace mozilla {
-namespace ipc {
-
-class DaemonSocketConnector final : public UnixSocketConnector
-{
-public:
- static nsresult CreateRandomAddressString(const nsACString& aPrefix,
- unsigned long aPostfixLength,
- nsACString& aAddress);
-
- DaemonSocketConnector(const nsACString& aSocketName);
- ~DaemonSocketConnector();
-
- // Methods for |UnixSocketConnector|
- //
-
- nsresult ConvertAddressToString(const struct sockaddr& aAddress,
- socklen_t aAddressLength,
- nsACString& aAddressString) override;
-
- nsresult CreateListenSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aListenFd) override;
-
- nsresult AcceptStreamSocket(int aListenFd,
- struct sockaddr* aAddress,
- socklen_t* aAddressLen,
- int& aStreamFd) override;
-
- nsresult CreateStreamSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd) override;
-
- nsresult Duplicate(UnixSocketConnector*& aConnector) override;
-
-private:
- nsresult CreateSocket(int& aFd) const;
- nsresult SetSocketFlags(int aFd) const;
- nsresult CreateAddress(struct sockaddr& aAddress,
- socklen_t& aAddressLength) const;
-
- nsCString mSocketName;
-};
-
-} // namespace ipc
-} // namespace mozilla
-
-#endif // mozilla_ipc_DaemonSocketConnector_h
diff --git a/ipc/hal/DaemonSocketConsumer.cpp b/ipc/hal/DaemonSocketConsumer.cpp
deleted file mode 100644
index ad57d5f57..000000000
--- a/ipc/hal/DaemonSocketConsumer.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "DaemonSocketConsumer.h"
-
-namespace mozilla {
-namespace ipc {
-
-//
-// DaemonSocketIOConsumer
-//
-
-DaemonSocketIOConsumer::DaemonSocketIOConsumer()
-{ }
-
-DaemonSocketIOConsumer::~DaemonSocketIOConsumer()
-{ }
-
-//
-// DaemonSocketConsumer
-//
-
-DaemonSocketConsumer::DaemonSocketConsumer()
-{ }
-
-DaemonSocketConsumer::~DaemonSocketConsumer()
-{ }
-
-}
-}
diff --git a/ipc/hal/DaemonSocketConsumer.h b/ipc/hal/DaemonSocketConsumer.h
deleted file mode 100644
index ababab893..000000000
--- a/ipc/hal/DaemonSocketConsumer.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_DaemonSocketConsumer_h
-#define mozilla_ipc_DaemonSocketConsumer_h
-
-namespace mozilla {
-namespace ipc {
-
-class DaemonSocketPDU;
-
-/**
- * |DaemonSocketIOConsumer| processes incoming PDUs from the
- * HAL daemon. Please note that its method |Handle| runs on a
- * different than the consumer thread.
- */
-class DaemonSocketIOConsumer
-{
-public:
- virtual ~DaemonSocketIOConsumer();
-
- virtual void Handle(DaemonSocketPDU& aPDU) = 0;
- virtual void StoreResultHandler(const DaemonSocketPDU& aPDU) = 0;
-
-protected:
- DaemonSocketIOConsumer();
-};
-
-/**
- * |DaemonSocketConsumer| handles socket events.
- */
-class DaemonSocketConsumer
-{
-public:
- /**
- * Callback for socket success. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the stream socket.
- */
- virtual void OnConnectSuccess(int aIndex) = 0;
-
- /**
- * Callback for socket errors. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the stream socket.
- */
- virtual void OnConnectError(int aIndex) = 0;
-
- /**
- * Callback for socket disconnect. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the stream socket.
- */
- virtual void OnDisconnect(int aIndex) = 0;
-
-protected:
- DaemonSocketConsumer();
- virtual ~DaemonSocketConsumer();
-};
-
-}
-}
-
-#endif
-
diff --git a/ipc/hal/DaemonSocketMessageHandlers.h b/ipc/hal/DaemonSocketMessageHandlers.h
deleted file mode 100644
index 184e687f1..000000000
--- a/ipc/hal/DaemonSocketMessageHandlers.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/* -*- 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/. */
-
-/*
- * Message handlers
- *
- * This file contains base classes for message handling.
- */
-
-#ifndef mozilla_ipc_DaemonSocketMessageHandlers_h
-#define mozilla_ipc_DaemonSocketMessageHandlers_h
-
-#include "nsISupportsImpl.h" // for ref-counting
-
-namespace mozilla {
-namespace ipc {
-
-/**
- * |DaemonSocketResultHandler| is the base class for all protocol-specific
- * result handlers. It currently only manages the reference counting.
- */
-class DaemonSocketResultHandler
-{
-public:
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(DaemonSocketResultHandler);
-
-protected:
- DaemonSocketResultHandler()
- { }
- virtual ~DaemonSocketResultHandler()
- { }
-};
-
-} // namespace ipc
-} // namespace mozilla
-
-#endif // mozilla_ipc_DaemonSocketMessageHandlers_h
diff --git a/ipc/hal/DaemonSocketPDU.cpp b/ipc/hal/DaemonSocketPDU.cpp
deleted file mode 100644
index de6aa0da7..000000000
--- a/ipc/hal/DaemonSocketPDU.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "DaemonSocketPDU.h"
-#include "mozilla/ipc/DaemonSocketConsumer.h"
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-
-#ifdef CHROMIUM_LOG
-#undef CHROMIUM_LOG
-#endif
-
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define CHROMIUM_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "I/O", args);
-#else
-#include <stdio.h>
-#define IODEBUG true
-#define CHROMIUM_LOG(args...) if (IODEBUG) printf(args);
-#endif
-
-namespace mozilla {
-namespace ipc {
-
-//
-// DaemonSocketPDU
-//
-
-DaemonSocketPDU::DaemonSocketPDU(uint8_t aService, uint8_t aOpcode,
- uint16_t aPayloadSize)
- : mConsumer(nullptr)
-{
- MOZ_COUNT_CTOR_INHERITED(DaemonSocketPDU, UnixSocketIOBuffer);
-
- // Allocate memory
- size_t availableSpace = PDU_HEADER_SIZE + aPayloadSize;
- ResetBuffer(new uint8_t[availableSpace], 0, 0, availableSpace);
-
- // Reserve PDU header
- uint8_t* data = Append(PDU_HEADER_SIZE);
- MOZ_ASSERT(data);
-
- // Setup PDU header
- data[PDU_OFF_SERVICE] = aService;
- data[PDU_OFF_OPCODE] = aOpcode;
- memcpy(data + PDU_OFF_LENGTH, &aPayloadSize, sizeof(aPayloadSize));
-}
-
-DaemonSocketPDU::DaemonSocketPDU(size_t aPayloadSize)
- : mConsumer(nullptr)
-{
- MOZ_COUNT_CTOR_INHERITED(DaemonSocketPDU, UnixSocketIOBuffer);
-
- size_t availableSpace = PDU_HEADER_SIZE + aPayloadSize;
- ResetBuffer(new uint8_t[availableSpace], 0, 0, availableSpace);
-}
-
-DaemonSocketPDU::~DaemonSocketPDU()
-{
- MOZ_COUNT_DTOR_INHERITED(DaemonSocketPDU, UnixSocketIOBuffer);
-
- UniquePtr<uint8_t[]> data(GetBuffer());
- ResetBuffer(nullptr, 0, 0, 0);
-}
-
-void
-DaemonSocketPDU::GetHeader(uint8_t& aService, uint8_t& aOpcode,
- uint16_t& aPayloadSize)
-{
- memcpy(&aService, GetData(PDU_OFF_SERVICE), sizeof(aService));
- memcpy(&aOpcode, GetData(PDU_OFF_OPCODE), sizeof(aOpcode));
- memcpy(&aPayloadSize, GetData(PDU_OFF_LENGTH), sizeof(aPayloadSize));
-}
-
-ssize_t
-DaemonSocketPDU::Send(int aFd)
-{
- struct iovec iv;
- memset(&iv, 0, sizeof(iv));
- iv.iov_base = GetData(GetLeadingSpace());
- iv.iov_len = GetSize();
-
- struct msghdr msg;
- memset(&msg, 0, sizeof(msg));
- msg.msg_iov = &iv;
- msg.msg_iovlen = 1;
- msg.msg_control = nullptr;
- msg.msg_controllen = 0;
-
- ssize_t res = TEMP_FAILURE_RETRY(sendmsg(aFd, &msg, 0));
- if (res < 0) {
- MOZ_ASSERT(errno != EBADF); /* internal error */
- OnError("sendmsg", errno);
- return -1;
- }
-
- Consume(res);
-
- if (mConsumer) {
- // We successfully sent a PDU, now store the
- // result handler in the consumer.
- mConsumer->StoreResultHandler(*this);
- }
-
- return res;
-}
-
-#define CMSGHDR_CONTAINS_FD(_cmsghdr) \
- ( ((_cmsghdr)->cmsg_level == SOL_SOCKET) && \
- ((_cmsghdr)->cmsg_type == SCM_RIGHTS) )
-
-ssize_t
-DaemonSocketPDU::Receive(int aFd)
-{
- struct iovec iv;
- memset(&iv, 0, sizeof(iv));
- iv.iov_base = GetData(0);
- iv.iov_len = GetAvailableSpace();
-
- uint8_t cmsgbuf[CMSG_SPACE(sizeof(int)* MAX_NFDS)];
-
- struct msghdr msg;
- memset(&msg, 0, sizeof(msg));
- msg.msg_iov = &iv;
- msg.msg_iovlen = 1;
- msg.msg_control = cmsgbuf;
- msg.msg_controllen = sizeof(cmsgbuf);
-
- ssize_t res = TEMP_FAILURE_RETRY(recvmsg(aFd, &msg, MSG_NOSIGNAL));
- if (res < 0) {
- MOZ_ASSERT(errno != EBADF); /* internal error */
- OnError("recvmsg", errno);
- return -1;
- }
- if (msg.msg_flags & (MSG_CTRUNC | MSG_OOB | MSG_ERRQUEUE)) {
- return -1;
- }
-
- SetRange(0, res);
-
- struct cmsghdr* chdr = CMSG_FIRSTHDR(&msg);
-
- for (; chdr; chdr = CMSG_NXTHDR(&msg, chdr)) {
- if (NS_WARN_IF(!CMSGHDR_CONTAINS_FD(chdr))) {
- continue;
- }
- // Retrieve sent file descriptors.
- size_t fdCount = (chdr->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr))) / sizeof(int);
- for (size_t i = 0; i < fdCount; i++) {
- int* receivedFd = static_cast<int*>(CMSG_DATA(chdr)) + i;
- mReceivedFds.AppendElement(*receivedFd);
- }
- }
-
- return res;
-}
-
-nsTArray<int>
-DaemonSocketPDU::AcquireFds()
-{
- // Forget all RAII object to avoid closing the fds.
- nsTArray<int> fds;
- for (auto& fd : mReceivedFds) {
- fds.AppendElement(fd.forget());
- }
- mReceivedFds.Clear();
- return fds;
-}
-
-nsresult
-DaemonSocketPDU::UpdateHeader()
-{
- size_t len = GetPayloadSize();
- if (len >= PDU_MAX_PAYLOAD_LENGTH) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
- uint16_t len16 = static_cast<uint16_t>(len);
-
- memcpy(GetData(PDU_OFF_LENGTH), &len16, sizeof(len16));
-
- return NS_OK;
-}
-
-size_t
-DaemonSocketPDU::GetPayloadSize() const
-{
- MOZ_ASSERT(GetSize() >= PDU_HEADER_SIZE);
-
- return GetSize() - PDU_HEADER_SIZE;
-}
-
-void
-DaemonSocketPDU::OnError(const char* aFunction, int aErrno)
-{
- CHROMIUM_LOG("%s failed with error %d (%s)",
- aFunction, aErrno, strerror(aErrno));
-}
-
-}
-}
diff --git a/ipc/hal/DaemonSocketPDU.h b/ipc/hal/DaemonSocketPDU.h
deleted file mode 100644
index ebc4e4419..000000000
--- a/ipc/hal/DaemonSocketPDU.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_DaemonSocketPDU_h
-#define mozilla_ipc_DaemonSocketPDU_h
-
-#include "mozilla/FileUtils.h"
-#include "mozilla/ipc/SocketBase.h"
-#include "mozilla/ipc/DaemonSocketMessageHandlers.h"
-#include "nsTArray.h"
-
-namespace mozilla {
-namespace ipc {
-
-static const size_t MAX_NFDS = 16;
-class DaemonSocketIOConsumer;
-
-/**
- * |DaemonSocketPDU| represents a single PDU that is transfered from or to
- * the HAL daemon. Each PDU contains exactly one command.
- *
- * A PDU as the following format
- *
- * | 1 | 1 | 2 | n |
- * | service | opcode | payload length | payload |
- *
- * Service and Opcode each require 1 byte, the payload length requires 2
- * bytes, and the payload requires the number of bytes as stored in the
- * payload-length field.
- *
- * Each service and opcode can have a different payload with individual
- * length. For the exact details of the HAL protocol, please refer to
- *
- * https://git.kernel.org/cgit/bluetooth/bluez.git/tree/android/hal-ipc-api.txt?id=5.24
- *
- */
-class DaemonSocketPDU final : public UnixSocketIOBuffer
-{
-public:
- enum {
- PDU_OFF_SERVICE = 0,
- PDU_OFF_OPCODE = 1,
- PDU_OFF_LENGTH = 2,
- PDU_OFF_PAYLOAD = 4,
- PDU_HEADER_SIZE = PDU_OFF_PAYLOAD,
- PDU_MAX_PAYLOAD_LENGTH = 1 << 16
- };
-
- DaemonSocketPDU(uint8_t aService, uint8_t aOpcode, uint16_t aPayloadSize);
- DaemonSocketPDU(size_t aPayloadSize);
- ~DaemonSocketPDU();
-
- void SetConsumer(DaemonSocketIOConsumer* aConsumer)
- {
- mConsumer = aConsumer;
- }
-
- void SetResultHandler(DaemonSocketResultHandler* aRes)
- {
- mRes = aRes;
- }
-
- DaemonSocketResultHandler* GetResultHandler() const
- {
- return mRes;
- }
-
- void GetHeader(uint8_t& aService, uint8_t& aOpcode,
- uint16_t& aPayloadSize);
-
- ssize_t Send(int aFd) override;
- ssize_t Receive(int aFd) override;
-
- nsTArray<int> AcquireFds();
-
- nsresult UpdateHeader();
-
-private:
- size_t GetPayloadSize() const;
- void OnError(const char* aFunction, int aErrno);
-
- DaemonSocketIOConsumer* mConsumer;
- RefPtr<DaemonSocketResultHandler> mRes;
- nsTArray<ScopedClose> mReceivedFds;
-};
-
-}
-}
-
-#endif
-
diff --git a/ipc/hal/DaemonSocketPDUHelpers.cpp b/ipc/hal/DaemonSocketPDUHelpers.cpp
deleted file mode 100644
index 6aaf21c33..000000000
--- a/ipc/hal/DaemonSocketPDUHelpers.cpp
+++ /dev/null
@@ -1,335 +0,0 @@
-/* -*- 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 "DaemonSocketPDUHelpers.h"
-#include <limits>
-
-// Enable this constant to abort Gecko on IPC errors. This is helpful
-// for debugging, but should *never* be enabled by default.
-#define MOZ_HAL_ABORT_ON_IPC_ERRORS (0)
-
-#ifdef CHROMIUM_LOG
-#undef CHROMIUM_LOG
-#endif
-
-#if defined(MOZ_WIDGET_GONK)
-
-#include <android/log.h>
-
-#define CHROMIUM_LOG(args...) \
- __android_log_print(ANDROID_LOG_INFO, "HAL-IPC", args);
-
-#define CHROMIUM_LOG_VA(fmt, ap) \
- __android_log_vprint(ANDROID_LOG_INFO, "HAL-IPC", fmt, ap);
-
-#else
-
-#include <stdio.h>
-
-#define IODEBUG true
-#define CHROMIUM_LOG(args...) if (IODEBUG) { printf(args); }
-#define CHROMIUM_LOG_VA(fmt, ap) if (IODEBUG) { vprintf(fmt, ap); }
-
-#endif
-
-namespace mozilla {
-namespace ipc {
-namespace DaemonSocketPDUHelpers {
-
-//
-// Logging
-//
-
-namespace detail {
-
-void
-LogProtocolError(const char* aFmt, ...)
-{
- va_list ap;
-
- va_start(ap, aFmt);
- CHROMIUM_LOG_VA(aFmt, ap);
- va_end(ap);
-
- if (MOZ_HAL_ABORT_ON_IPC_ERRORS) {
- MOZ_CRASH("HAL IPC protocol error");
- }
-}
-
-} // namespace detail
-
-//
-// Conversion
-//
-
-nsresult
-Convert(bool aIn, uint8_t& aOut)
-{
- static const uint8_t sValue[] = {
- [false] = 0x00,
- [true] = 0x01
- };
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn >= MOZ_ARRAY_LENGTH(sValue), bool, uint8_t)) {
- aOut = 0;
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = sValue[aIn];
- return NS_OK;
-}
-
-nsresult
-Convert(bool aIn, int32_t& aOut)
-{
- uint8_t out;
- nsresult rv = Convert(aIn, out);
- if (NS_FAILED(rv)) {
- out = 0; // silence compiler warning
- return rv;
- }
- aOut = static_cast<int32_t>(out);
- return NS_OK;
-}
-
-nsresult
-Convert(int aIn, uint8_t& aOut)
-{
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn < std::numeric_limits<uint8_t>::min(), int, uint8_t) ||
- MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn > std::numeric_limits<uint8_t>::max(), int, uint8_t)) {
- aOut = 0; // silences compiler warning
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<uint8_t>(aIn);
- return NS_OK;
-}
-
-nsresult
-Convert(int aIn, int16_t& aOut)
-{
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn < std::numeric_limits<int16_t>::min(), int, int16_t) ||
- MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn > std::numeric_limits<int16_t>::max(), int, int16_t)) {
- aOut = 0; // silences compiler warning
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<int16_t>(aIn);
- return NS_OK;
-}
-
-nsresult
-Convert(int aIn, int32_t& aOut)
-{
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn < std::numeric_limits<int32_t>::min(), int, int32_t) ||
- MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn > std::numeric_limits<int32_t>::max(), int, int32_t)) {
- aOut = 0; // silences compiler warning
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<int32_t>(aIn);
- return NS_OK;
-}
-
-nsresult
-Convert(uint8_t aIn, bool& aOut)
-{
- static const bool sBool[] = {
- [0x00] = false,
- [0x01] = true
- };
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn >= MOZ_ARRAY_LENGTH(sBool), uint8_t, bool)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = sBool[aIn];
- return NS_OK;
-}
-
-nsresult
-Convert(uint8_t aIn, char& aOut)
-{
- aOut = static_cast<char>(aIn);
- return NS_OK;
-}
-
-nsresult
-Convert(uint8_t aIn, int& aOut)
-{
- aOut = static_cast<int>(aIn);
- return NS_OK;
-}
-
-nsresult
-Convert(uint8_t aIn, unsigned long& aOut)
-{
- aOut = static_cast<unsigned long>(aIn);
- return NS_OK;
-}
-
-nsresult
-Convert(uint32_t aIn, int& aOut)
-{
- aOut = static_cast<int>(aIn);
- return NS_OK;
-}
-
-nsresult
-Convert(uint32_t aIn, uint8_t& aOut)
-{
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn < std::numeric_limits<uint8_t>::min(), uint32_t, uint8_t) ||
- MOZ_HAL_IPC_CONVERT_WARN_IF(
- aIn > std::numeric_limits<uint8_t>::max(), uint32_t, uint8_t)) {
- aOut = 0; // silences compiler warning
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<uint8_t>(aIn);
- return NS_OK;
-}
-
-nsresult
-Convert(size_t aIn, uint16_t& aOut)
-{
- if (MOZ_HAL_IPC_CONVERT_WARN_IF(aIn >= (1ul << 16), size_t, uint16_t)) {
- aOut = 0; // silences compiler warning
- return NS_ERROR_ILLEGAL_VALUE;
- }
- aOut = static_cast<uint16_t>(aIn);
- return NS_OK;
-}
-
-//
-// Packing
-//
-
-nsresult
-PackPDU(bool aIn, DaemonSocketPDU& aPDU)
-{
- return PackPDU(PackConversion<bool, uint8_t>(aIn), aPDU);
-}
-
-nsresult
-PackPDU(const DaemonSocketPDUHeader& aIn, DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn.mService, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn.mOpcode, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn.mLength, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return NS_OK;
-}
-
-//
-// Unpacking
-//
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, bool& aOut)
-{
- return UnpackPDU(aPDU, UnpackConversion<uint8_t, bool>(aOut));
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, char& aOut)
-{
- return UnpackPDU(aPDU, UnpackConversion<uint8_t, char>(aOut));
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, nsDependentCString& aOut)
-{
- // We get a pointer to the first character in the PDU, a length
- // of 1 ensures we consume the \0 byte. With 'str' pointing to
- // the string in the PDU, we can copy the actual bytes.
-
- const char* str = reinterpret_cast<const char*>(aPDU.Consume(1));
- if (MOZ_HAL_IPC_UNPACK_WARN_IF(!str, nsDependentCString)) {
- return NS_ERROR_ILLEGAL_VALUE; // end of PDU
- }
-
- const char* end = static_cast<char*>(memchr(str, '\0', aPDU.GetSize() + 1));
- if (MOZ_HAL_IPC_UNPACK_WARN_IF(!end, nsDependentCString)) {
- return NS_ERROR_ILLEGAL_VALUE; // no string terminator
- }
-
- ptrdiff_t len = end - str;
-
- const uint8_t* rest = aPDU.Consume(len);
- if (MOZ_HAL_IPC_UNPACK_WARN_IF(!rest, nsDependentCString)) {
- // We couldn't consume bytes that should have been there.
- return NS_ERROR_ILLEGAL_VALUE;
- }
-
- aOut.Rebind(str, len);
-
- return NS_OK;
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, const UnpackCString0& aOut)
-{
- nsDependentCString cstring;
-
- nsresult rv = UnpackPDU(aPDU, cstring);
- if (NS_FAILED(rv)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
-
- aOut.mString->AssignASCII(cstring.get(), cstring.Length());
-
- return NS_OK;
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, const UnpackString0& aOut)
-{
- nsDependentCString cstring;
-
- nsresult rv = UnpackPDU(aPDU, cstring);
- if (NS_FAILED(rv)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
-
- *aOut.mString = NS_ConvertUTF8toUTF16(cstring);
-
- return NS_OK;
-}
-
-//
-// Init operators
-//
-
-void
-PDUInitOp::WarnAboutTrailingData() const
-{
- size_t size = mPDU->GetSize();
-
- if (MOZ_LIKELY(!size)) {
- return;
- }
-
- uint8_t service, opcode;
- uint16_t payloadSize;
- mPDU->GetHeader(service, opcode, payloadSize);
-
- detail::LogProtocolError(
- "Unpacked PDU of type (%x,%x) still contains %zu Bytes of data.",
- service, opcode, size);
-}
-
-} // namespace DaemonSocketPDUHelpers
-} // namespace ipc
-} // namespace mozilla
diff --git a/ipc/hal/DaemonSocketPDUHelpers.h b/ipc/hal/DaemonSocketPDUHelpers.h
deleted file mode 100644
index 38a848e46..000000000
--- a/ipc/hal/DaemonSocketPDUHelpers.h
+++ /dev/null
@@ -1,1283 +0,0 @@
-/* -*- 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_DaemonSocketPDUHelpers_h
-#define mozilla_ipc_DaemonSocketPDUHelpers_h
-
-#include <stdint.h>
-#include "mozilla/ipc/DaemonSocketPDU.h"
-#include "mozilla/UniquePtr.h"
-#include "nsString.h"
-
-namespace mozilla {
-namespace ipc {
-
-struct DaemonSocketPDUHeader {
- DaemonSocketPDUHeader()
- : mService(0x00)
- , mOpcode(0x00)
- , mLength(0x00)
- { }
-
- DaemonSocketPDUHeader(uint8_t aService, uint8_t aOpcode, uint16_t aLength)
- : mService(aService)
- , mOpcode(aOpcode)
- , mLength(aLength)
- { }
-
- uint8_t mService;
- uint8_t mOpcode;
- uint16_t mLength;
-};
-
-namespace DaemonSocketPDUHelpers {
-
-//
-// Logging
-//
-// The HAL IPC logging macros below print clear error messages for
-// failed IPC operations. Use |MOZ_HAL_IPC_CONVERT_WARN_IF|,
-// |MOZ_HAL_IPC_PACK_WARN_IF| and |MOZ_HAL_IPC_UNPACK_WARN_IF| to
-// test for failures when processing PDUs.
-//
-// All macros accept the test condition as their first argument, and
-// additional type information: the convert macro takes the input and
-// output types, the pack macro takes the input type, and the unpack
-// macro takes output type. All macros return the result of the test
-// condition. If the test fails (i.e., the condition is true), they
-// output a warning to the log.
-//
-// Don't call the functions in the detail namespace. They are helpers
-// and not for general use.
-//
-
-namespace detail {
-
-void
-LogProtocolError(const char*, ...);
-
-inline bool
-ConvertWarnIfImpl(const char* aFile, unsigned long aLine,
- bool aCondition, const char* aExpr, const char* aIn,
- const char* aOut)
-{
- if (MOZ_UNLIKELY(aCondition)) {
- LogProtocolError("%s:%d: Convert('%s' to '%s') failed: %s",
- aFile, aLine, aIn, aOut, aExpr);
- }
- return aCondition;
-}
-
-inline bool
-PackWarnIfImpl(const char* aFile, unsigned long aLine,
- bool aCondition, const char* aExpr, const char* aIn)
-{
- if (MOZ_UNLIKELY(aCondition)) {
- LogProtocolError("%s:%d: Pack('%s') failed: %s",
- aFile, aLine, aIn, aExpr);
- }
- return aCondition;
-}
-
-inline bool
-UnpackWarnIfImpl(const char* aFile, unsigned long aLine,
- bool aCondition, const char* aExpr, const char* aOut)
-{
- if (MOZ_UNLIKELY(aCondition)) {
- LogProtocolError("%s:%d: Unpack('%s') failed: %s",
- aFile, aLine, aOut, aExpr);
- }
- return aCondition;
-}
-
-} // namespace detail
-
-#define MOZ_HAL_IPC_CONVERT_WARN_IF(condition, in, out) \
- ::mozilla::ipc::DaemonSocketPDUHelpers::detail:: \
- ConvertWarnIfImpl(__FILE__, __LINE__, condition, #condition, #in, #out)
-
-#define MOZ_HAL_IPC_PACK_WARN_IF(condition, in) \
- ::mozilla::ipc::DaemonSocketPDUHelpers::detail:: \
- PackWarnIfImpl(__FILE__, __LINE__, condition, #condition, #in)
-
-#define MOZ_HAL_IPC_UNPACK_WARN_IF(condition, out) \
- ::mozilla::ipc::DaemonSocketPDUHelpers::detail:: \
- UnpackWarnIfImpl(__FILE__, __LINE__, condition, #condition, #out)
-
-//
-// Conversion
-//
-// PDUs can only store primitive data types, such as integers or
-// byte arrays. Gecko often uses more complex data types, such as
-// enumators or stuctures. Conversion functions convert between
-// primitive data and internal Gecko's data types during a PDU's
-// packing and unpacking.
-//
-
-nsresult
-Convert(bool aIn, uint8_t& aOut);
-
-nsresult
-Convert(bool aIn, int32_t& aOut);
-
-nsresult
-Convert(int aIn, uint8_t& aOut);
-
-nsresult
-Convert(int aIn, int16_t& aOut);
-
-nsresult
-Convert(int aIn, int32_t& aOut);
-
-nsresult
-Convert(uint8_t aIn, bool& aOut);
-
-nsresult
-Convert(uint8_t aIn, char& aOut);
-
-nsresult
-Convert(uint8_t aIn, int& aOut);
-
-nsresult
-Convert(uint8_t aIn, unsigned long& aOut);
-
-nsresult
-Convert(uint32_t aIn, int& aOut);
-
-nsresult
-Convert(uint32_t aIn, uint8_t& aOut);
-
-nsresult
-Convert(size_t aIn, uint16_t& aOut);
-
-//
-// Packing
-//
-
-// introduce link errors on non-handled data types
-template <typename T>
-nsresult
-PackPDU(T aIn, DaemonSocketPDU& aPDU);
-
-nsresult
-PackPDU(bool aIn, DaemonSocketPDU& aPDU);
-
-inline nsresult
-PackPDU(uint8_t aIn, DaemonSocketPDU& aPDU)
-{
- return aPDU.Write(aIn);
-}
-
-inline nsresult
-PackPDU(uint16_t aIn, DaemonSocketPDU& aPDU)
-{
- return aPDU.Write(aIn);
-}
-
-inline nsresult
-PackPDU(int32_t aIn, DaemonSocketPDU& aPDU)
-{
- return aPDU.Write(aIn);
-}
-
-inline nsresult
-PackPDU(uint32_t aIn, DaemonSocketPDU& aPDU)
-{
- return aPDU.Write(aIn);
-}
-
-inline nsresult
-PackPDU(int64_t aIn, DaemonSocketPDU& aPDU)
-{
- return aPDU.Write(aIn);
-}
-
-inline nsresult
-PackPDU(uint64_t aIn, DaemonSocketPDU& aPDU)
-{
- return aPDU.Write(aIn);
-}
-
-inline nsresult
-PackPDU(float aIn, DaemonSocketPDU& aPDU)
-{
- return aPDU.Write(aIn);
-}
-
-inline nsresult
-PackPDU(double aIn, DaemonSocketPDU& aPDU)
-{
- return aPDU.Write(aIn);
-}
-
-nsresult
-PackPDU(const DaemonSocketPDUHeader& aIn, DaemonSocketPDU& aPDU);
-
-/* |PackConversion| is a helper for packing converted values. Pass
- * an instance of this structure to |PackPDU| to convert a value from
- * the input type to the output type and and write it to the PDU.
- */
-template<typename Tin, typename Tout>
-struct PackConversion {
- PackConversion(const Tin& aIn)
- : mIn(aIn)
- { }
-
- const Tin& mIn;
-};
-
-template<typename Tin, typename Tout>
-inline nsresult
-PackPDU(const PackConversion<Tin, Tout>& aIn, DaemonSocketPDU& aPDU)
-{
- Tout out;
-
- nsresult rv = Convert(aIn.mIn, out);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(out, aPDU);
-}
-
-/* |PackArray| is a helper for packing arrays. Pass an instance
- * of this structure as the first argument to |PackPDU| to pack
- * an array. The array's maximum default length is 255 elements.
- */
-template <typename T>
-struct PackArray
-{
- PackArray(const T* aData, size_t aLength)
- : mData(aData)
- , mLength(aLength)
- { }
-
- const T* mData;
- size_t mLength;
-};
-
-/* This implementation of |PackPDU| packs the length of an array
- * and the elements of the array one-by-one.
- */
-template<typename T>
-inline nsresult
-PackPDU(const PackArray<T>& aIn, DaemonSocketPDU& aPDU)
-{
- for (size_t i = 0; i < aIn.mLength; ++i) {
- nsresult rv = PackPDU(aIn.mData[i], aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
- return NS_OK;
-}
-
-template<>
-inline nsresult
-PackPDU<uint8_t>(const PackArray<uint8_t>& aIn, DaemonSocketPDU& aPDU)
-{
- /* Write raw bytes in one pass */
- return aPDU.Write(aIn.mData, aIn.mLength);
-}
-
-template<>
-inline nsresult
-PackPDU<char>(const PackArray<char>& aIn, DaemonSocketPDU& aPDU)
-{
- /* Write raw bytes in one pass */
- return aPDU.Write(aIn.mData, aIn.mLength);
-}
-
-/* |PackCString0| is a helper for packing 0-terminated C string,
- * including the \0 character. Pass an instance of this structure
- * as the first argument to |PackPDU| to pack a string.
- */
-struct PackCString0
-{
- PackCString0(const nsCString& aString)
- : mString(aString)
- { }
-
- const nsCString& mString;
-};
-
-/* This implementation of |PackPDU| packs a 0-terminated C string.
- */
-inline nsresult
-PackPDU(const PackCString0& aIn, DaemonSocketPDU& aPDU)
-{
- return PackPDU(
- PackArray<uint8_t>(reinterpret_cast<const uint8_t*>(aIn.mString.get()),
- aIn.mString.Length() + 1), aPDU);
-}
-
-/* |PackReversed| is a helper for packing data in reversed order. Pass an
- * instance of this structure as the first argument to |PackPDU| to pack data
- * in reversed order.
- */
-template<typename T>
-struct PackReversed
-{
- PackReversed(const T& aValue)
- : mValue(aValue)
- { }
-
- const T& mValue;
-};
-
-/* No general rules to pack data in reversed order. Signal a link error if the
- * type |T| of |PackReversed| is not defined explicitly.
- */
-template<typename T>
-nsresult
-PackPDU(const PackReversed<T>& aIn, DaemonSocketPDU& aPDU);
-
-/* This implementation of |PackPDU| packs elements in |PackArray| in reversed
- * order. (ex. reversed GATT UUID, see bug 1171866)
- */
-template<typename U>
-inline nsresult
-PackPDU(const PackReversed<PackArray<U>>& aIn, DaemonSocketPDU& aPDU)
-{
- for (size_t i = 0; i < aIn.mValue.mLength; ++i) {
- nsresult rv = PackPDU(aIn.mValue.mData[aIn.mValue.mLength - i - 1], aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
- return NS_OK;
-}
-
-/* |PackArray<PackReversed<U>>| is a helper for packing data of each element in
- * the reversed order. Pass an instance of this structure as the first argument
- * to |PackPDU| to pack data of each array element in the reversed order.
- *
- * Unlike |PackReversed<PackArray<U>>| which packed array elements in the
- * reversed order, here we use |PackReversed<U>| to pack data of each element
- * of |PackArray| in the reversed order.
- */
-template<typename U>
-struct PackArray<PackReversed<U>>
-{
- PackArray(const U* aData, size_t aLength)
- : mData(aData)
- , mLength(aLength)
- { }
-
- const U* mData;
- size_t mLength;
-};
-
-/* This implementation of |PackPDU| packs data of each element in |PackArray|
- * in the reversed order. (ex. reversed GATT UUID, see bug 1171866)
- */
-template<typename U>
-inline nsresult
-PackPDU(const PackArray<PackReversed<U>>& aIn, DaemonSocketPDU& aPDU)
-{
- for (size_t i = 0; i < aIn.mLength; ++i) {
- nsresult rv = PackPDU(PackReversed<U>(aIn.mData[i]), aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
- return NS_OK;
-}
-
-template <typename T1, typename T2>
-inline nsresult
-PackPDU(const T1& aIn1, const T2& aIn2, DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn1, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(aIn2, aPDU);
-}
-
-template <typename T1, typename T2, typename T3>
-inline nsresult
-PackPDU(const T1& aIn1, const T2& aIn2, const T3& aIn3,
- DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn1, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn2, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(aIn3, aPDU);
-}
-
-template <typename T1, typename T2, typename T3, typename T4>
-inline nsresult
-PackPDU(const T1& aIn1, const T2& aIn2, const T3& aIn3, const T4& aIn4,
- DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn1, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn2, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn3, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(aIn4, aPDU);
-}
-
-template <typename T1, typename T2, typename T3,
- typename T4, typename T5>
-inline nsresult
-PackPDU(const T1& aIn1, const T2& aIn2, const T3& aIn3,
- const T4& aIn4, const T5& aIn5,
- DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn1, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn2, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn3, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn4, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(aIn5, aPDU);
-}
-
-template <typename T1, typename T2, typename T3,
- typename T4, typename T5, typename T6>
-inline nsresult
-PackPDU(const T1& aIn1, const T2& aIn2, const T3& aIn3,
- const T4& aIn4, const T5& aIn5, const T6& aIn6,
- DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn1, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn2, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn3, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn4, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn5, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(aIn6, aPDU);
-}
-
-template <typename T1, typename T2, typename T3,
- typename T4, typename T5, typename T6,
- typename T7>
-inline nsresult
-PackPDU(const T1& aIn1, const T2& aIn2, const T3& aIn3,
- const T4& aIn4, const T5& aIn5, const T6& aIn6,
- const T7& aIn7, DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn1, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn2, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn3, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn4, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn5, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn6, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(aIn7, aPDU);
-}
-
-template <typename T1, typename T2, typename T3,
- typename T4, typename T5, typename T6,
- typename T7, typename T8>
-inline nsresult
-PackPDU(const T1& aIn1, const T2& aIn2, const T3& aIn3,
- const T4& aIn4, const T5& aIn5, const T6& aIn6,
- const T7& aIn7, const T8& aIn8, DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn1, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn2, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn3, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn4, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn5, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn6, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn7, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(aIn8, aPDU);
-}
-
-template <typename T1, typename T2, typename T3,
- typename T4, typename T5, typename T6,
- typename T7, typename T8, typename T9,
- typename T10, typename T11, typename T12,
- typename T13>
-inline nsresult
-PackPDU(const T1& aIn1, const T2& aIn2, const T3& aIn3,
- const T4& aIn4, const T5& aIn5, const T6& aIn6,
- const T7& aIn7, const T8& aIn8, const T9& aIn9,
- const T10& aIn10, const T11& aIn11, const T12& aIn12,
- const T13& aIn13, DaemonSocketPDU& aPDU)
-{
- nsresult rv = PackPDU(aIn1, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn2, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn3, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn4, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn5, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn6, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn7, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn8, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn9, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn10, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn11, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = PackPDU(aIn12, aPDU);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return PackPDU(aIn13, aPDU);
-}
-
-//
-// Unpacking
-//
-
-// introduce link errors on non-handled data types
-template <typename T>
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, T& aOut);
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, bool& aOut);
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, char& aOut);
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, int8_t& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, uint8_t& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, uint16_t& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, int32_t& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, uint32_t& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, int64_t& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, uint64_t& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, float& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, double& aOut)
-{
- return aPDU.Read(aOut);
-}
-
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, DaemonSocketPDUHeader& aOut)
-{
- nsresult rv = UnpackPDU(aPDU, aOut.mService);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(aPDU, aOut.mOpcode);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return UnpackPDU(aPDU, aOut.mLength);
-}
-
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, nsDependentCString& aOut);
-
-/* |UnpackCString0| is a helper for unpacking 0-terminated C string,
- * including the \0 character. Pass an instance of this structure
- * as the first argument to |UnpackPDU| to unpack a string.
- */
-struct UnpackCString0
-{
- UnpackCString0(nsCString& aString)
- : mString(&aString)
- { }
-
- nsCString* mString; // non-null by construction
-};
-
-/* This implementation of |UnpackPDU| unpacks a 0-terminated C string.
- */
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, const UnpackCString0& aOut);
-
-/* |UnpackString0| is a helper for unpacking 0-terminated C string,
- * including the \0 character. Pass an instance of this structure
- * as the first argument to |UnpackPDU| to unpack a C string and convert
- * it to wide-character encoding.
- */
-struct UnpackString0
-{
- UnpackString0(nsString& aString)
- : mString(&aString)
- { }
-
- nsString* mString; // non-null by construction
-};
-
-/* This implementation of |UnpackPDU| unpacks a 0-terminated C string
- * and converts it to wide-character encoding.
- */
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, const UnpackString0& aOut);
-
-/* |UnpackConversion| is a helper for convering unpacked values. Pass
- * an instance of this structure to |UnpackPDU| to read a value from
- * the PDU in the input type and convert it to the output type.
- */
-template<typename Tin, typename Tout>
-struct UnpackConversion {
- UnpackConversion(Tout& aOut)
- : mOut(aOut)
- { }
-
- Tout& mOut;
-};
-
-template<typename Tin, typename Tout>
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, const UnpackConversion<Tin, Tout>& aOut)
-{
- Tin in;
- nsresult rv = UnpackPDU(aPDU, in);
- if (NS_FAILED(rv)) {
- return rv;
- }
- return Convert(in, aOut.mOut);
-}
-
-/* |UnpackArray| is a helper for unpacking arrays. Pass an instance
- * of this structure as the second argument to |UnpackPDU| to unpack
- * an array.
- */
-template <typename T>
-struct UnpackArray
-{
- UnpackArray(T* aData, size_t aLength)
- : mData(aData)
- , mLength(aLength)
- { }
-
- UnpackArray(UniquePtr<T[]>& aData, size_t aLength)
- : mData(nullptr)
- , mLength(aLength)
- {
- aData.reset(new T[mLength]);
- mData = aData.get();
- }
-
- UnpackArray(UniquePtr<T>& aData, size_t aSize, size_t aElemSize)
- : mData(nullptr)
- , mLength(aSize / aElemSize)
- {
- aData.reset(new T[mLength]);
- mData = aData.get();
- }
-
- T* mData;
- size_t mLength;
-};
-
-template<typename T>
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, const UnpackArray<T>& aOut)
-{
- for (size_t i = 0; i < aOut.mLength; ++i) {
- nsresult rv = UnpackPDU(aPDU, aOut.mData[i]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
- return NS_OK;
-}
-
-template<typename T>
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, UnpackArray<T>& aOut)
-{
- for (size_t i = 0; i < aOut.mLength; ++i) {
- nsresult rv = UnpackPDU(aPDU, aOut.mData[i]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
- return NS_OK;
-}
-
-template<>
-inline nsresult
-UnpackPDU<uint8_t>(DaemonSocketPDU& aPDU, const UnpackArray<uint8_t>& aOut)
-{
- /* Read raw bytes in one pass */
- return aPDU.Read(aOut.mData, aOut.mLength);
-}
-
-template<typename T>
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, nsTArray<T>& aOut)
-{
- for (typename nsTArray<T>::size_type i = 0; i < aOut.Length(); ++i) {
- nsresult rv = UnpackPDU(aPDU, aOut[i]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
- return NS_OK;
-}
-
-/* |UnpackReversed| is a helper for unpacking data in reversed order. Pass an
- * instance of this structure as the second argument to |UnpackPDU| to unpack
- * data in reversed order.
- */
-template<typename T>
-struct UnpackReversed
-{
- UnpackReversed(T& aValue)
- : mValue(&aValue)
- { }
-
- UnpackReversed(T&& aValue)
- : mValue(&aValue)
- { }
-
- T* mValue;
-};
-
-/* No general rules to unpack data in reversed order. Signal a link error if
- * the type |T| of |UnpackReversed| is not defined explicitly.
- */
-template<typename T>
-nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, const UnpackReversed<T>& aOut);
-
-template<typename U>
-inline nsresult
-UnpackPDU(DaemonSocketPDU& aPDU, const UnpackReversed<UnpackArray<U>>& aOut)
-{
- for (size_t i = 0; i < aOut.mValue->mLength; ++i) {
- nsresult rv = UnpackPDU(aPDU,
- aOut.mValue->mData[aOut.mValue->mLength - i - 1]);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
- return NS_OK;
-}
-
-//
-// Init operators
-//
-
-//
-// Below are general-purpose init operators for Bluetooth. The classes
-// of type |ConstantInitOp[1..3]| initialize results or notifications
-// with constant values.
-//
-
-template <typename T1>
-class ConstantInitOp1 final
-{
-public:
- ConstantInitOp1(const T1& aArg1)
- : mArg1(aArg1)
- { }
-
- nsresult operator () (T1& aArg1) const
- {
- aArg1 = mArg1;
-
- return NS_OK;
- }
-
-private:
- const T1& mArg1;
-};
-
-template <typename T1, typename T2>
-class ConstantInitOp2 final
-{
-public:
- ConstantInitOp2(const T1& aArg1, const T2& aArg2)
- : mArg1(aArg1)
- , mArg2(aArg2)
- { }
-
- nsresult operator () (T1& aArg1, T2& aArg2) const
- {
- aArg1 = mArg1;
- aArg2 = mArg2;
-
- return NS_OK;
- }
-
-private:
- const T1& mArg1;
- const T2& mArg2;
-};
-
-template <typename T1, typename T2, typename T3>
-class ConstantInitOp3 final
-{
-public:
- ConstantInitOp3(const T1& aArg1, const T2& aArg2, const T3& aArg3)
- : mArg1(aArg1)
- , mArg2(aArg2)
- , mArg3(aArg3)
- { }
-
- nsresult operator () (T1& aArg1, T2& aArg2, T3& aArg3) const
- {
- aArg1 = mArg1;
- aArg2 = mArg2;
- aArg3 = mArg3;
-
- return NS_OK;
- }
-
-private:
- const T1& mArg1;
- const T2& mArg2;
- const T3& mArg3;
-};
-
-// |PDUInitOP| provides functionality for init operators that unpack PDUs.
-class PDUInitOp
-{
-protected:
- PDUInitOp(DaemonSocketPDU& aPDU)
- : mPDU(&aPDU)
- { }
-
- DaemonSocketPDU& GetPDU() const
- {
- return *mPDU; // cannot be nullptr
- }
-
- void WarnAboutTrailingData() const;
-
-private:
- DaemonSocketPDU* mPDU; // Hold pointer to allow for constant instances
-};
-
-// |UnpackPDUInitOp| is a general-purpose init operator for all variants
-// of |DaemonResultRunnable| and |DaemonNotificationRunnable|. The call
-// operators of |UnpackPDUInitOp| unpack a PDU into the supplied
-// arguments.
-class UnpackPDUInitOp final : private PDUInitOp
-{
-public:
- UnpackPDUInitOp(DaemonSocketPDU& aPDU)
- : PDUInitOp(aPDU)
- { }
-
- nsresult operator () () const
- {
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1>
- nsresult operator () (T1& aArg1) const
- {
- nsresult rv = UnpackPDU(GetPDU(), aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1, typename T2>
- nsresult operator () (T1& aArg1, T2& aArg2) const
- {
- DaemonSocketPDU& pdu = GetPDU();
-
- nsresult rv = UnpackPDU(pdu, aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1, typename T2, typename T3>
- nsresult operator () (T1& aArg1, T2& aArg2, T3& aArg3) const
- {
- DaemonSocketPDU& pdu = GetPDU();
-
- nsresult rv = UnpackPDU(pdu, aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg3);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1, typename T2, typename T3, typename T4>
- nsresult operator () (T1& aArg1, T2& aArg2, T3& aArg3, T4& aArg4) const
- {
- DaemonSocketPDU& pdu = GetPDU();
-
- nsresult rv = UnpackPDU(pdu, aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg3);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg4);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1, typename T2, typename T3, typename T4, typename T5>
- nsresult operator () (T1& aArg1, T2& aArg2, T3& aArg3, T4& aArg4,
- T5& aArg5) const
- {
- DaemonSocketPDU& pdu = GetPDU();
-
- nsresult rv = UnpackPDU(pdu, aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg3);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg4);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg5);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1, typename T2, typename T3, typename T4,
- typename T5, typename T6>
- nsresult operator () (T1& aArg1, T2& aArg2, T3& aArg3, T4& aArg4,
- T5& aArg5, T6& aArg6) const
- {
- DaemonSocketPDU& pdu = GetPDU();
-
- nsresult rv = UnpackPDU(pdu, aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg3);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg4);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg5);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg6);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7>
- nsresult operator () (T1& aArg1, T2& aArg2, T3& aArg3, T4& aArg4,
- T5& aArg5, T6& aArg6, T7& aArg7) const
- {
- DaemonSocketPDU& pdu = GetPDU();
-
- nsresult rv = UnpackPDU(pdu, aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg3);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg4);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg5);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg6);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg7);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8>
- nsresult operator () (T1& aArg1, T2& aArg2, T3& aArg3, T4& aArg4,
- T5& aArg5, T6& aArg6, T7& aArg7, T8& aArg8) const
- {
- DaemonSocketPDU& pdu = GetPDU();
-
- nsresult rv = UnpackPDU(pdu, aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg3);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg4);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg5);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg6);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg7);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg8);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-
- template<typename T1, typename T2, typename T3, typename T4, typename T5,
- typename T6, typename T7, typename T8, typename T9>
- nsresult operator () (T1& aArg1, T2& aArg2, T3& aArg3, T4& aArg4,
- T5& aArg5, T6& aArg6, T7& aArg7, T8& aArg8,
- T9& aArg9) const
- {
- DaemonSocketPDU& pdu = GetPDU();
-
- nsresult rv = UnpackPDU(pdu, aArg1);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg2);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg3);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg4);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg5);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg6);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg7);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg8);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = UnpackPDU(pdu, aArg9);
- if (NS_FAILED(rv)) {
- return rv;
- }
- WarnAboutTrailingData();
- return NS_OK;
- }
-};
-
-} // namespace DaemonSocketPDUHelpers
-
-} // namespace ipc
-} // namespace mozilla
-
-#endif // mozilla_ipc_DaemonSocketPDUHelpers_h
diff --git a/ipc/hal/moz.build b/ipc/hal/moz.build
deleted file mode 100644
index e97963b1e..000000000
--- a/ipc/hal/moz.build
+++ /dev/null
@@ -1,27 +0,0 @@
-# -*- 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 += [
- 'DaemonRunnables.h',
- 'DaemonSocket.h',
- 'DaemonSocketConnector.h',
- 'DaemonSocketConsumer.h',
- 'DaemonSocketMessageHandlers.h',
- 'DaemonSocketPDU.h',
- 'DaemonSocketPDUHelpers.h'
-]
-
-UNIFIED_SOURCES += [
- 'DaemonSocket.cpp',
- 'DaemonSocketConnector.cpp',
- 'DaemonSocketConsumer.cpp',
- 'DaemonSocketPDU.cpp',
- 'DaemonSocketPDUHelpers.cpp'
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
diff --git a/ipc/keystore/KeyStore.cpp b/ipc/keystore/KeyStore.cpp
deleted file mode 100644
index 992bc9075..000000000
--- a/ipc/keystore/KeyStore.cpp
+++ /dev/null
@@ -1,986 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=2 et ft=cpp: 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 <fcntl.h>
-#include <limits.h>
-#include <pwd.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define KEYSTORE_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
-#else
-#define KEYSTORE_LOG(args...) printf(args);
-#endif
-
-#include "KeyStore.h"
-#include "jsfriendapi.h"
-#include "KeyStoreConnector.h"
-#include "MainThreadUtils.h" // For NS_IsMainThread.
-#include "nsICryptoHash.h"
-
-#include "plbase64.h"
-#include "certdb.h"
-#include "ScopedNSSTypes.h"
-
-using namespace mozilla::ipc;
-#if ANDROID_VERSION >= 18
-// After Android 4.3, it uses binder to access keystore instead of unix socket.
-#include <android/log.h>
-#include <binder/BinderService.h>
-#include <binder/IPCThreadState.h>
-#include <binder/IServiceManager.h>
-#include <security/keystore/include/keystore/IKeystoreService.h>
-#include <security/keystore/include/keystore/keystore.h>
-
-using namespace android;
-
-namespace android {
-// This class is used to make compiler happy.
-class BpKeystoreService : public BpInterface<IKeystoreService>
-{
-public:
- BpKeystoreService(const sp<IBinder>& impl)
- : BpInterface<IKeystoreService>(impl)
- {
- }
-
- virtual int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {return 0;}
- virtual int32_t test() {return 0;}
- virtual int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int uid, int32_t flags) {return 0;}
- virtual int32_t del(const String16& name, int uid) {return 0;}
- virtual int32_t exist(const String16& name, int uid) {return 0;}
- virtual int32_t saw(const String16& name, int uid, Vector<String16>* matches) {return 0;}
- virtual int32_t reset() {return 0;}
- virtual int32_t password(const String16& password) {return 0;}
- virtual int32_t lock() {return 0;}
- virtual int32_t unlock(const String16& password) {return 0;}
- virtual int32_t zero() {return 0;}
- virtual int32_t import(const String16& name, const uint8_t* data, size_t length, int uid, int32_t flags) {return 0;}
- virtual int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out, size_t* outLength) {return 0;}
- virtual int32_t verify(const String16& name, const uint8_t* data, size_t dataLength, const uint8_t* signature, size_t signatureLength) {return 0;}
- virtual int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {return 0;}
- virtual int32_t del_key(const String16& name, int uid) {return 0;}
- virtual int32_t grant(const String16& name, int32_t granteeUid) {return 0;}
- virtual int32_t ungrant(const String16& name, int32_t granteeUid) {return 0;}
- virtual int64_t getmtime(const String16& name) {return 0;}
- virtual int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey, int32_t destUid) {return 0;}
- virtual int32_t clear_uid(int64_t uid) {return 0;}
-#if ANDROID_VERSION >= 21
- virtual int32_t generate(const String16& name, int32_t uid, int32_t keyType, int32_t keySize, int32_t flags, Vector<sp<KeystoreArg> >* args) {return 0;}
- virtual int32_t is_hardware_backed(const String16& keyType) {return 0;}
- virtual int32_t reset_uid(int32_t uid) {return 0;}
- virtual int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {return 0;}
- virtual int32_t password_uid(const String16& password, int32_t uid) {return 0;}
-#elif ANDROID_VERSION == 18
- virtual int32_t generate(const String16& name, int uid, int32_t flags) {return 0;}
- virtual int32_t is_hardware_backed() {return 0;}
-#else
- virtual int32_t generate(const String16& name, int32_t uid, int32_t keyType, int32_t keySize, int32_t flags, Vector<sp<KeystoreArg> >* args) {return 0;}
- virtual int32_t is_hardware_backed(const String16& keyType) {return 0;}
-#endif
-};
-
-IMPLEMENT_META_INTERFACE(KeystoreService, "android.security.keystore");
-
-// Here comes binder requests.
-status_t BnKeystoreService::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
- switch(code) {
- case TEST: {
- CHECK_INTERFACE(IKeystoreService, data, reply);
- reply->writeNoException();
- reply->writeInt32(test());
- return NO_ERROR;
- } break;
- case GET: {
- CHECK_INTERFACE(IKeystoreService, data, reply);
- String16 name = data.readString16();
- String8 tmp(name);
- uint8_t* data = NULL;
- size_t dataLength = 0;
- int32_t ret = get(name, &data, &dataLength);
-
- reply->writeNoException();
- if (ret == 1) {
- reply->writeInt32(dataLength);
- void* buf = reply->writeInplace(dataLength);
- memcpy(buf, data, dataLength);
- free(data);
- } else {
- reply->writeInt32(-1);
- }
- return NO_ERROR;
- } break;
- case GET_PUBKEY: {
- CHECK_INTERFACE(IKeystoreService, data, reply);
- String16 name = data.readString16();
- uint8_t* data = nullptr;
- size_t dataLength = 0;
- int32_t ret = get_pubkey(name, &data, &dataLength);
-
- reply->writeNoException();
- if (dataLength > 0 && data != nullptr) {
- reply->writeInt32(dataLength);
- void* buf = reply->writeInplace(dataLength);
- memcpy(buf, data, dataLength);
- free(data);
- } else {
- reply->writeInt32(-1);
- }
- reply->writeInt32(ret);
- return NO_ERROR;
- } break;
- case SIGN: {
- CHECK_INTERFACE(IKeystoreService, data, reply);
- String16 name = data.readString16();
- ssize_t signDataSize = data.readInt32();
- const uint8_t *signData = nullptr;
- if (signDataSize >= 0 && (size_t)signDataSize <= data.dataAvail()) {
- signData = (const uint8_t *)data.readInplace(signDataSize);
- }
-
- uint8_t *signResult = nullptr;
- size_t signResultSize;
- int32_t ret = sign(name, signData, (size_t)signDataSize, &signResult,
- &signResultSize);
-
- reply->writeNoException();
- if (signResultSize > 0 && signResult != nullptr) {
- reply->writeInt32(signResultSize);
- void* buf = reply->writeInplace(signResultSize);
- memcpy(buf, signResult, signResultSize);
- free(signResult);
- } else {
- reply->writeInt32(-1);
- }
- reply->writeInt32(ret);
- return NO_ERROR;
- } break;
- default:
- return NO_ERROR;
- }
-}
-
-// Provide service for binder.
-class KeyStoreService : public BnKeystoreService
- , public nsNSSShutDownObject
-{
-public:
- int32_t test() {
- uid_t callingUid = IPCThreadState::self()->getCallingUid();
- if (!mozilla::ipc::checkPermission(callingUid)) {
- return ::PERMISSION_DENIED;
- }
-
- return ::NO_ERROR;
- }
-
- int32_t get(const String16& name, uint8_t** item, size_t* itemLength) {
- nsNSSShutDownPreventionLock locker;
- if (isAlreadyShutDown()) {
- return ::SYSTEM_ERROR;
- }
-
- uid_t callingUid = IPCThreadState::self()->getCallingUid();
- if (!mozilla::ipc::checkPermission(callingUid)) {
- return ::PERMISSION_DENIED;
- }
-
- String8 certName(name);
- if (!strncmp(certName.string(), "WIFI_USERKEY_", 13)) {
- return getPrivateKey(certName.string(), (const uint8_t**)item, itemLength);
- }
-
- return getCertificate(certName.string(), (const uint8_t**)item, itemLength);
- }
-
- int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int uid, int32_t flags) {return ::UNDEFINED_ACTION;}
- int32_t del(const String16& name, int uid) {return ::UNDEFINED_ACTION;}
- int32_t exist(const String16& name, int uid) {return ::UNDEFINED_ACTION;}
- int32_t saw(const String16& name, int uid, Vector<String16>* matches) {return ::UNDEFINED_ACTION;}
- int32_t reset() {return ::UNDEFINED_ACTION;}
- int32_t password(const String16& password) {return ::UNDEFINED_ACTION;}
- int32_t lock() {return ::UNDEFINED_ACTION;}
- int32_t unlock(const String16& password) {return ::UNDEFINED_ACTION;}
- int32_t zero() {return ::UNDEFINED_ACTION;}
- int32_t import(const String16& name, const uint8_t* data, size_t length, int uid, int32_t flags) {return ::UNDEFINED_ACTION;}
- int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out, size_t* outLength)
- {
- nsNSSShutDownPreventionLock locker;
- if (isAlreadyShutDown()) {
- return ::SYSTEM_ERROR;
- }
-
- uid_t callingUid = IPCThreadState::self()->getCallingUid();
- if (!mozilla::ipc::checkPermission(callingUid)) {
- return ::PERMISSION_DENIED;
- }
-
- if (data == nullptr) {
- return ::SYSTEM_ERROR;
- }
-
- String8 keyName(name);
- if (!strncmp(keyName.string(), "WIFI_USERKEY_", 13)) {
- return signData(keyName.string(), data, length, out, outLength);
- }
-
- return ::UNDEFINED_ACTION;
- }
-
- int32_t verify(const String16& name, const uint8_t* data, size_t dataLength, const uint8_t* signature, size_t signatureLength) {return ::UNDEFINED_ACTION;}
- int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength) {
- nsNSSShutDownPreventionLock locker;
- if (isAlreadyShutDown()) {
- return ::SYSTEM_ERROR;
- }
-
- uid_t callingUid = IPCThreadState::self()->getCallingUid();
- if (!mozilla::ipc::checkPermission(callingUid)) {
- return ::PERMISSION_DENIED;
- }
-
- String8 keyName(name);
- if (!strncmp(keyName.string(), "WIFI_USERKEY_", 13)) {
- return getPublicKey(keyName.string(), (const uint8_t**)pubkey, pubkeyLength);
- }
-
- return ::UNDEFINED_ACTION;
- }
-
- int32_t del_key(const String16& name, int uid) {return ::UNDEFINED_ACTION;}
- int32_t grant(const String16& name, int32_t granteeUid) {return ::UNDEFINED_ACTION;}
- int32_t ungrant(const String16& name, int32_t granteeUid) {return ::UNDEFINED_ACTION;}
- int64_t getmtime(const String16& name) {return ::UNDEFINED_ACTION;}
- int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey, int32_t destUid) {return ::UNDEFINED_ACTION;}
- int32_t clear_uid(int64_t uid) {return ::UNDEFINED_ACTION;}
-#if ANDROID_VERSION >= 21
- virtual int32_t generate(const String16& name, int32_t uid, int32_t keyType, int32_t keySize, int32_t flags, Vector<sp<KeystoreArg> >* args) {return ::UNDEFINED_ACTION;}
- virtual int32_t is_hardware_backed(const String16& keyType) {return ::UNDEFINED_ACTION;}
- virtual int32_t reset_uid(int32_t uid) {return ::UNDEFINED_ACTION;;}
- virtual int32_t sync_uid(int32_t sourceUid, int32_t targetUid) {return ::UNDEFINED_ACTION;}
- virtual int32_t password_uid(const String16& password, int32_t uid) {return ::UNDEFINED_ACTION;}
-#elif ANDROID_VERSION == 18
- virtual int32_t generate(const String16& name, int uid, int32_t flags) {return ::UNDEFINED_ACTION;}
- virtual int32_t is_hardware_backed() {return ::UNDEFINED_ACTION;}
-#else
- virtual int32_t generate(const String16& name, int32_t uid, int32_t keyType, int32_t keySize, int32_t flags, Vector<sp<KeystoreArg> >* args) {return ::UNDEFINED_ACTION;}
- virtual int32_t is_hardware_backed(const String16& keyType) {return ::UNDEFINED_ACTION;}
-#endif
-
-protected:
- virtual void virtualDestroyNSSReference() {}
-
-private:
- ~KeyStoreService() {
- nsNSSShutDownPreventionLock locker;
- if (isAlreadyShutDown()) {
- return;
- }
- shutdown(ShutdownCalledFrom::Object);
- }
-};
-
-} // namespace android
-
-void startKeyStoreService()
-{
- android::sp<android::IServiceManager> sm = android::defaultServiceManager();
- android::sp<android::KeyStoreService> keyStoreService = new android::KeyStoreService();
- sm->addService(String16("android.security.keystore"), keyStoreService);
-}
-#else
-void startKeyStoreService() { return; }
-#endif
-
-static const char *CA_BEGIN = "-----BEGIN ",
- *CA_END = "-----END ",
- *CA_TAILER = "-----\n";
-
-namespace mozilla {
-namespace ipc {
-
-static const char* KEYSTORE_ALLOWED_USERS[] = {
- "root",
- "wifi",
- NULL
-};
-static const char* KEYSTORE_ALLOWED_PREFIXES[] = {
- "WIFI_SERVERCERT_",
- "WIFI_USERCERT_",
- "WIFI_USERKEY_",
- NULL
-};
-
-// Transform base64 certification data into DER format
-void
-FormatCaData(const char *aCaData, int aCaDataLength,
- const char *aName, const uint8_t **aFormatData,
- size_t *aFormatDataLength)
-{
- size_t bufSize = strlen(CA_BEGIN) + strlen(CA_END) + strlen(CA_TAILER) * 2 +
- strlen(aName) * 2 + aCaDataLength + aCaDataLength/CA_LINE_SIZE
- + 2;
- char *buf = (char *)malloc(bufSize);
- if (!buf) {
- *aFormatData = nullptr;
- return;
- }
-
- *aFormatDataLength = bufSize;
- *aFormatData = (const uint8_t *)buf;
-
- char *ptr = buf;
- size_t len;
-
- // Create DER header.
- len = snprintf(ptr, bufSize, "%s%s%s", CA_BEGIN, aName, CA_TAILER);
- ptr += len;
- bufSize -= len;
-
- // Split base64 data in lines.
- int copySize;
- while (aCaDataLength > 0) {
- copySize = (aCaDataLength > CA_LINE_SIZE) ? CA_LINE_SIZE : aCaDataLength;
-
- memcpy(ptr, aCaData, copySize);
- ptr += copySize;
- aCaData += copySize;
- aCaDataLength -= copySize;
- bufSize -= copySize;
-
- *ptr = '\n';
- ptr++;
- bufSize--;
- }
-
- // Create DEA tailer.
- snprintf(ptr, bufSize, "%s%s%s", CA_END, aName, CA_TAILER);
-}
-
-ResponseCode
-getCertificate(const char *aCertName, const uint8_t **aCertData,
- size_t *aCertDataLength)
-{
- // certificate name prefix check.
- if (!aCertName) {
- return KEY_NOT_FOUND;
- }
-
- const char **prefix = KEYSTORE_ALLOWED_PREFIXES;
- for (; *prefix; prefix++ ) {
- if (!strncmp(*prefix, aCertName, strlen(*prefix))) {
- break;
- }
- }
- if (!(*prefix)) {
- return KEY_NOT_FOUND;
- }
-
- // Get cert from NSS by name
- ScopedCERTCertificate cert(CERT_FindCertByNickname(CERT_GetDefaultCertDB(),
- aCertName));
-
- if (!cert) {
- return KEY_NOT_FOUND;
- }
-
- char *certDER = PL_Base64Encode((const char *)cert->derCert.data,
- cert->derCert.len, nullptr);
- if (!certDER) {
- return SYSTEM_ERROR;
- }
-
- FormatCaData(certDER, strlen(certDER), "CERTIFICATE", aCertData,
- aCertDataLength);
- PL_strfree(certDER);
-
- if (!(*aCertData)) {
- return SYSTEM_ERROR;
- }
-
- return SUCCESS;
-}
-
-ResponseCode getPrivateKey(const char *aKeyName, const uint8_t **aKeyData,
- size_t *aKeyDataLength)
-{
- *aKeyData = nullptr;
- // Get corresponding user certificate nickname
- char userCertName[128] = {0};
- snprintf(userCertName, sizeof(userCertName) - 1, "WIFI_USERCERT_%s", aKeyName + 13);
-
- // Get private key from user certificate.
- ScopedCERTCertificate userCert(
- CERT_FindCertByNickname(CERT_GetDefaultCertDB(), userCertName));
- if (!userCert) {
- return KEY_NOT_FOUND;
- }
-
- ScopedSECKEYPrivateKey privateKey(
- PK11_FindKeyByAnyCert(userCert.get(), nullptr));
- if (!privateKey) {
- return KEY_NOT_FOUND;
- }
-
- // Export private key in PKCS#12 encrypted format, no password.
- unsigned char pwstr[] = {0, 0};
- SECItem password = {siBuffer, pwstr, sizeof(pwstr)};
- ScopedSECKEYEncryptedPrivateKeyInfo encryptedPrivateKey(
- PK11_ExportEncryptedPrivKeyInfo(privateKey->pkcs11Slot,
- SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC4, &password, privateKey, 1,
- privateKey->wincx));
-
- if (!encryptedPrivateKey) {
- return KEY_NOT_FOUND;
- }
-
- // Decrypt into RSA private key.
- //
- // Generate key for PKCS#12 encryption, we use SHA1 with 1 iteration, as the
- // parameters used in PK11_ExportEncryptedPrivKeyInfo() above.
- // see: PKCS#12 v1.0, B.2.
- //
- uint8_t DSP[192] = {0};
- memset(DSP, 0x01, 64); // Diversifier part, ID = 1 for decryption.
- memset(DSP + 128, 0x00, 64); // Password part, no password.
-
- uint8_t *S = &DSP[64]; // Salt part.
- uint8_t *salt = encryptedPrivateKey->algorithm.parameters.data + 4;
- int saltLength = (int)encryptedPrivateKey->algorithm.parameters.data[3];
- if (saltLength <= 0) {
- return SYSTEM_ERROR;
- }
- for (int i = 0; i < 64; i++) {
- S[i] = salt[i % saltLength];
- }
-
- // Generate key by SHA-1
- nsresult rv;
- nsCOMPtr<nsICryptoHash> hash =
- do_CreateInstance("@mozilla.org/security/hash;1", &rv);
- if (NS_FAILED(rv)) {
- return SYSTEM_ERROR;
- }
-
- rv = hash->Init(nsICryptoHash::SHA1);
- if (NS_FAILED(rv)) {
- return SYSTEM_ERROR;
- }
-
- rv = hash->Update(DSP, sizeof(DSP));
- if (NS_FAILED(rv)) {
- return SYSTEM_ERROR;
- }
-
- nsCString hashResult;
- rv = hash->Finish(false, hashResult);
- if (NS_FAILED(rv)) {
- return SYSTEM_ERROR;
- }
-
- // First 40-bit as key for RC4.
- uint8_t key[5];
- memcpy(key, hashResult.get(), sizeof(key));
-
- ScopedPK11SlotInfo slot(PK11_GetInternalSlot());
- if (!slot) {
- return SYSTEM_ERROR;
- }
-
- SECItem keyItem = {siBuffer, key, sizeof(key)};
- ScopedPK11SymKey symKey(PK11_ImportSymKey(slot, CKM_RC4, PK11_OriginUnwrap,
- CKA_DECRYPT, &keyItem, nullptr));
- if (!symKey) {
- return SYSTEM_ERROR;
- }
-
- // Get expected decrypted data size then allocate memory.
- uint8_t *encryptedData = (uint8_t *)encryptedPrivateKey->encryptedData.data;
- unsigned int encryptedDataLen = encryptedPrivateKey->encryptedData.len;
- unsigned int decryptedDataLen = encryptedDataLen;
- SECStatus srv = PK11_Decrypt(symKey, CKM_RC4, &keyItem, nullptr,
- &decryptedDataLen, encryptedDataLen,
- encryptedData, encryptedDataLen);
- if (srv != SECSuccess) {
- return SYSTEM_ERROR;
- }
-
- ScopedSECItem decryptedData(::SECITEM_AllocItem(nullptr, nullptr,
- decryptedDataLen));
- if (!decryptedData) {
- return SYSTEM_ERROR;
- }
-
- // Decrypt by RC4.
- srv = PK11_Decrypt(symKey, CKM_RC4, &keyItem, decryptedData->data,
- &decryptedDataLen, decryptedData->len, encryptedData,
- encryptedDataLen);
- if (srv != SECSuccess) {
- return SYSTEM_ERROR;
- }
-
- // Export key in PEM format.
- char *keyPEM = PL_Base64Encode((const char *)decryptedData->data,
- decryptedDataLen, nullptr);
-
- if (!keyPEM) {
- return SYSTEM_ERROR;
- }
-
- FormatCaData(keyPEM, strlen(keyPEM), "PRIVATE KEY", aKeyData, aKeyDataLength);
- PL_strfree(keyPEM);
-
- if (!(*aKeyData)) {
- return SYSTEM_ERROR;
- }
-
- return SUCCESS;
-}
-
-ResponseCode getPublicKey(const char *aKeyName, const uint8_t **aKeyData,
- size_t *aKeyDataLength)
-{
- *aKeyData = nullptr;
-
- // Get corresponding user certificate nickname
- char userCertName[128] = {0};
- snprintf(userCertName, sizeof(userCertName) - 1, "WIFI_USERCERT_%s", aKeyName + 13);
-
- // Get public key from user certificate.
- ScopedCERTCertificate userCert(
- CERT_FindCertByNickname(CERT_GetDefaultCertDB(), userCertName));
- if (!userCert) {
- return KEY_NOT_FOUND;
- }
-
- // Get public key.
- ScopedSECKEYPublicKey publicKey(CERT_ExtractPublicKey(userCert));
- if (!publicKey) {
- return KEY_NOT_FOUND;
- }
-
- ScopedSECItem keyItem(PK11_DEREncodePublicKey(publicKey));
- if (!keyItem) {
- return KEY_NOT_FOUND;
- }
-
- size_t bufSize = keyItem->len;
- char *buf = (char *)malloc(bufSize);
- if (!buf) {
- return SYSTEM_ERROR;
- }
-
- memcpy(buf, keyItem->data, bufSize);
- *aKeyData = (const uint8_t *)buf;
- *aKeyDataLength = bufSize;
-
- return SUCCESS;
-}
-
-ResponseCode signData(const char *aKeyName, const uint8_t *data, size_t length,
- uint8_t **out, size_t *outLength)
-{
- *out = nullptr;
- // Get corresponding user certificate nickname
- char userCertName[128] = {0};
- snprintf(userCertName, sizeof(userCertName) - 1, "WIFI_USERCERT_%s", aKeyName + 13);
-
- // Get private key from user certificate.
- ScopedCERTCertificate userCert(
- CERT_FindCertByNickname(CERT_GetDefaultCertDB(), userCertName));
- if (!userCert) {
- return KEY_NOT_FOUND;
- }
-
- ScopedSECKEYPrivateKey privateKey(
- PK11_FindKeyByAnyCert(userCert.get(), nullptr));
- if (!privateKey) {
- return KEY_NOT_FOUND;
- }
-
- //
- // Find hash data from incoming data.
- //
- // Incoming data might be padded by PKCS-1 format:
- // 00 01 FF FF ... FF 00 || Hash of length 36
- // If the padding part exists, we have to ignore them.
- //
- uint8_t *hash = (uint8_t *)data;
- const size_t HASH_LENGTH = 36;
- if (length < HASH_LENGTH) {
- return VALUE_CORRUPTED;
- }
- if (hash[0] == 0x00 && hash[1] == 0x01 && hash[2] == 0xFF && hash[3] == 0xFF) {
- hash += 4;
- while (*hash == 0xFF) {
- if (hash + HASH_LENGTH > data + length) {
- return VALUE_CORRUPTED;
- }
- hash++;
- }
- if (*hash != 0x00) {
- return VALUE_CORRUPTED;
- }
- hash++;
- }
- if (hash + HASH_LENGTH != data + length) {
- return VALUE_CORRUPTED;
- }
- SECItem hashItem = {siBuffer, hash, HASH_LENGTH};
-
- // Sign hash.
- ScopedSECItem signItem(::SECITEM_AllocItem(nullptr, nullptr,
- PK11_SignatureLen(privateKey)));
- if (!signItem) {
- return SYSTEM_ERROR;
- }
-
- SECStatus srv;
- srv = PK11_Sign(privateKey, signItem.get(), &hashItem);
- if (srv != SECSuccess) {
- return SYSTEM_ERROR;
- }
-
- uint8_t *buf = (uint8_t *)malloc(signItem->len);
- if (!buf) {
- return SYSTEM_ERROR;
- }
-
- memcpy(buf, signItem->data, signItem->len);
- *out = buf;
- *outLength = signItem->len;
-
- return SUCCESS;
-}
-
-bool
-checkPermission(uid_t uid)
-{
- struct passwd *userInfo = getpwuid(uid);
- for (const char **user = KEYSTORE_ALLOWED_USERS; *user; user++ ) {
- if (!strcmp(*user, userInfo->pw_name)) {
- return true;
- }
- }
-
- return false;
-}
-
-//
-// KeyStore
-//
-
-KeyStore::KeyStore()
-: mShutdown(false)
-{
- MOZ_COUNT_CTOR(KeyStore);
- ::startKeyStoreService();
- Listen();
-}
-
-KeyStore::~KeyStore()
-{
- nsNSSShutDownPreventionLock locker;
- MOZ_COUNT_DTOR(KeyStore);
-
- if (isAlreadyShutDown()) {
- return;
- }
-
- shutdown(ShutdownCalledFrom::Object);
-
- MOZ_ASSERT(!mListenSocket);
- MOZ_ASSERT(!mStreamSocket);
-}
-
-void
-KeyStore::Shutdown()
-{
- // We set mShutdown first, so that |OnDisconnect| won't try to reconnect.
- mShutdown = true;
-
- if (mStreamSocket) {
- mStreamSocket->Close();
- mStreamSocket = nullptr;
- }
- if (mListenSocket) {
- mListenSocket->Close();
- mListenSocket = nullptr;
- }
-}
-
-void
-KeyStore::Listen()
-{
- // We only allocate one |StreamSocket|, but re-use it for every connection.
- if (mStreamSocket) {
- mStreamSocket->Close();
- } else {
- mStreamSocket = new StreamSocket(this, STREAM_SOCKET);
- }
-
- if (!mListenSocket) {
- // We only ever allocate one |ListenSocket|...
- mListenSocket = new ListenSocket(this, LISTEN_SOCKET);
- mListenSocket->Listen(new KeyStoreConnector(KEYSTORE_ALLOWED_USERS),
- mStreamSocket);
- } else {
- // ... but keep it open.
- mListenSocket->Listen(mStreamSocket);
- }
-
- ResetHandlerInfo();
-}
-
-void
-KeyStore::ResetHandlerInfo()
-{
- mHandlerInfo.state = STATE_IDLE;
- mHandlerInfo.command = 0;
- mHandlerInfo.paramCount = 0;
- mHandlerInfo.commandPattern = nullptr;
- for (int i = 0; i < MAX_PARAM; i++) {
- mHandlerInfo.param[i].length = 0;
- memset(mHandlerInfo.param[i].data, 0, VALUE_SIZE);
- }
-}
-
-bool
-KeyStore::CheckSize(UnixSocketBuffer *aMessage, size_t aExpectSize)
-{
- return (aMessage->GetSize() >= aExpectSize);
-}
-
-ResponseCode
-KeyStore::ReadCommand(UnixSocketBuffer *aMessage)
-{
- if (mHandlerInfo.state != STATE_IDLE) {
- NS_WARNING("Wrong state in ReadCommand()!");
- return SYSTEM_ERROR;
- }
-
- if (!CheckSize(aMessage, 1)) {
- NS_WARNING("Data size error in ReadCommand()!");
- return PROTOCOL_ERROR;
- }
-
- mHandlerInfo.command = *aMessage->GetData();
- aMessage->Consume(1);
-
- // Find corrsponding command pattern
- const struct ProtocolCommand *command = commands;
- while (command->command && command->command != mHandlerInfo.command) {
- command++;
- }
-
- if (!command->command) {
- NS_WARNING("Unsupported command!");
- return PROTOCOL_ERROR;
- }
-
- // Get command pattern.
- mHandlerInfo.commandPattern = command;
- if (command->paramNum) {
- // Read command parameter if needed.
- mHandlerInfo.state = STATE_READ_PARAM_LEN;
- } else {
- mHandlerInfo.state = STATE_PROCESSING;
- }
-
- return SUCCESS;
-}
-
-ResponseCode
-KeyStore::ReadLength(UnixSocketBuffer *aMessage)
-{
- if (mHandlerInfo.state != STATE_READ_PARAM_LEN) {
- NS_WARNING("Wrong state in ReadLength()!");
- return SYSTEM_ERROR;
- }
-
- if (!CheckSize(aMessage, 2)) {
- NS_WARNING("Data size error in ReadLength()!");
- return PROTOCOL_ERROR;
- }
-
- // Read length of command parameter.
- // FIXME: Depends on endianess and (sizeof(unsigned short) == 2)
- unsigned short dataLength;
- memcpy(&dataLength, aMessage->GetData(), 2);
- aMessage->Consume(2);
- mHandlerInfo.param[mHandlerInfo.paramCount].length = ntohs(dataLength);
-
- mHandlerInfo.state = STATE_READ_PARAM_DATA;
-
- return SUCCESS;
-}
-
-ResponseCode
-KeyStore::ReadData(UnixSocketBuffer *aMessage)
-{
- if (mHandlerInfo.state != STATE_READ_PARAM_DATA) {
- NS_WARNING("Wrong state in ReadData()!");
- return SYSTEM_ERROR;
- }
-
- if (!CheckSize(aMessage, mHandlerInfo.param[mHandlerInfo.paramCount].length)) {
- NS_WARNING("Data size error in ReadData()!");
- return PROTOCOL_ERROR;
- }
-
- // Read command parameter.
- memcpy(mHandlerInfo.param[mHandlerInfo.paramCount].data,
- aMessage->GetData(),
- mHandlerInfo.param[mHandlerInfo.paramCount].length);
- aMessage->Consume(mHandlerInfo.param[mHandlerInfo.paramCount].length);
- mHandlerInfo.paramCount++;
-
- if (mHandlerInfo.paramCount == mHandlerInfo.commandPattern->paramNum) {
- mHandlerInfo.state = STATE_PROCESSING;
- } else {
- mHandlerInfo.state = STATE_READ_PARAM_LEN;
- }
-
- return SUCCESS;
-}
-
-// Status response
-void
-KeyStore::SendResponse(ResponseCode aResponse)
-{
- MOZ_ASSERT(mStreamSocket);
-
- if (aResponse == NO_RESPONSE)
- return;
-
- uint8_t response = (uint8_t)aResponse;
- UnixSocketRawData* data = new UnixSocketRawData((const void *)&response, 1);
- mStreamSocket->SendSocketData(data);
-}
-
-// Data response
-void
-KeyStore::SendData(const uint8_t *aData, int aLength)
-{
- MOZ_ASSERT(mStreamSocket);
-
- unsigned short dataLength = htons(aLength);
-
- UnixSocketRawData* length = new UnixSocketRawData((const void *)&dataLength, 2);
- mStreamSocket->SendSocketData(length);
-
- UnixSocketRawData* data = new UnixSocketRawData((const void *)aData, aLength);
- mStreamSocket->SendSocketData(data);
-}
-
-// |StreamSocketConsumer|, |ListenSocketConsumer|
-
-void
-KeyStore::ReceiveSocketData(int aIndex, UniquePtr<UnixSocketBuffer>& aMessage)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- // Handle request.
- ResponseCode result = SUCCESS;
- while (aMessage->GetSize() ||
- mHandlerInfo.state == STATE_PROCESSING) {
- switch (mHandlerInfo.state) {
- case STATE_IDLE:
- result = ReadCommand(aMessage.get());
- break;
- case STATE_READ_PARAM_LEN:
- result = ReadLength(aMessage.get());
- break;
- case STATE_READ_PARAM_DATA:
- result = ReadData(aMessage.get());
- break;
- case STATE_PROCESSING:
- if (mHandlerInfo.command == 'g') {
- result = SYSTEM_ERROR;
-
- nsNSSShutDownPreventionLock locker;
- if (isAlreadyShutDown()) {
- break;
- }
-
- // Get CA
- const uint8_t *data;
- size_t dataLength;
- const char *name = (const char *)mHandlerInfo.param[0].data;
-
- if (!strncmp(name, "WIFI_USERKEY_", 13)) {
- result = getPrivateKey(name, &data, &dataLength);
- } else {
- result = getCertificate(name, &data, &dataLength);
- }
- if (result != SUCCESS) {
- break;
- }
-
- SendResponse(SUCCESS);
- SendData(data, (int)dataLength);
-
- free((void *)data);
- }
-
- ResetHandlerInfo();
- break;
- }
-
- if (result != SUCCESS) {
- SendResponse(result);
- ResetHandlerInfo();
- return;
- }
- }
-}
-
-void
-KeyStore::OnConnectSuccess(int aIndex)
-{
- if (aIndex == STREAM_SOCKET) {
- mShutdown = false;
- }
-}
-
-void
-KeyStore::OnConnectError(int aIndex)
-{
- if (mShutdown) {
- return;
- }
-
- if (aIndex == STREAM_SOCKET) {
- // Stream socket error; start listening again
- Listen();
- }
-}
-
-void
-KeyStore::OnDisconnect(int aIndex)
-{
- if (mShutdown) {
- return;
- }
-
- switch (aIndex) {
- case LISTEN_SOCKET:
- // Listen socket disconnected; start anew.
- mListenSocket = nullptr;
- Listen();
- break;
- case STREAM_SOCKET:
- // Stream socket disconnected; start listening again.
- Listen();
- break;
- }
-}
-
-} // namespace ipc
-} // namespace mozilla
diff --git a/ipc/keystore/KeyStore.h b/ipc/keystore/KeyStore.h
deleted file mode 100644
index c6bb09023..000000000
--- a/ipc/keystore/KeyStore.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=2 et ft=cpp: 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_KeyStore_h
-#define mozilla_ipc_KeyStore_h 1
-
-#include <sys/socket.h>
-#include <sys/un.h>
-#include "cert.h"
-#include "mozilla/ipc/ListenSocket.h"
-#include "mozilla/ipc/ListenSocketConsumer.h"
-#include "mozilla/ipc/StreamSocket.h"
-#include "mozilla/ipc/StreamSocketConsumer.h"
-#include "nsNSSShutDown.h"
-
-namespace mozilla {
-namespace ipc {
-
-enum ResponseCode {
- SUCCESS = 1,
- LOCKED = 2,
- UNINITIALIZED = 3,
- SYSTEM_ERROR = 4,
- PROTOCOL_ERROR = 5,
- PERMISSION_DENIED = 6,
- KEY_NOT_FOUND = 7,
- VALUE_CORRUPTED = 8,
- UNDEFINED_ACTION = 9,
- WRONG_PASSWORD_0 = 10,
- WRONG_PASSWORD_1 = 11,
- WRONG_PASSWORD_2 = 12,
- WRONG_PASSWORD_3 = 13, // MAX_RETRY = 4
- NO_RESPONSE
-};
-
-void FormatCaData(const uint8_t *aCaData, int aCaDataLength,
- const char *aName, const uint8_t **aFormatData,
- size_t *aFormatDataLength);
-
-ResponseCode getCertificate(const char *aCertName, const uint8_t **aCertData,
- size_t *aCertDataLength);
-ResponseCode getPrivateKey(const char *aKeyName, const uint8_t **aKeyData,
- size_t *aKeyDataLength);
-ResponseCode getPublicKey(const char *aKeyName, const uint8_t **aKeyData,
- size_t *aKeyDataLength);
-ResponseCode signData(const char *aKeyName, const uint8_t *data, size_t length,
- uint8_t **out, size_t *outLength);
-
-bool checkPermission(uid_t uid);
-
-static const int MAX_PARAM = 2;
-static const int KEY_SIZE = ((NAME_MAX - 15) / 2);
-static const int VALUE_SIZE = 32768;
-static const int PASSWORD_SIZE = VALUE_SIZE;
-
-static const int CA_LINE_SIZE = 64;
-
-struct ProtocolCommand {
- int8_t command;
- int paramNum;
-};
-
-static const struct ProtocolCommand commands[] = {
- {'g', 1}, // Get CA, command "g CERT_NAME"
- { 0, 0}
-};
-
-struct ProtocolParam{
- uint length;
- int8_t data[VALUE_SIZE];
-};
-
-typedef enum {
- STATE_IDLE,
- STATE_READ_PARAM_LEN,
- STATE_READ_PARAM_DATA,
- STATE_PROCESSING
-} ProtocolHandlerState;
-
-class KeyStore final
- : public StreamSocketConsumer
- , public ListenSocketConsumer
- , public nsNSSShutDownObject
-{
-public:
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(KeyStore)
-
- KeyStore();
-
- void Shutdown();
-
-protected:
- virtual void virtualDestroyNSSReference() {}
-
-private:
- enum SocketType {
- LISTEN_SOCKET,
- STREAM_SOCKET
- };
-
- ~KeyStore();
-
- struct {
- ProtocolHandlerState state;
- uint8_t command;
- struct ProtocolParam param[MAX_PARAM];
- int paramCount;
- const struct ProtocolCommand *commandPattern;
- } mHandlerInfo;
- void ResetHandlerInfo();
- void Listen();
-
- bool CheckSize(UnixSocketBuffer *aMessage, size_t aExpectSize);
- ResponseCode ReadCommand(UnixSocketBuffer *aMessage);
- ResponseCode ReadLength(UnixSocketBuffer *aMessage);
- ResponseCode ReadData(UnixSocketBuffer *aMessage);
- void SendResponse(ResponseCode response);
- void SendData(const uint8_t *data, int length);
-
- // Methods for |StreamSocketConsumer|
- //
-
- void ReceiveSocketData(int aIndex,
- UniquePtr<UnixSocketBuffer>& aMessage) override;
- void OnConnectSuccess(int aIndex) override;
- void OnConnectError(int aIndex) override;
- void OnDisconnect(int aIndex) override;
-
- bool mShutdown;
-
- RefPtr<ListenSocket> mListenSocket;
- RefPtr<StreamSocket> mStreamSocket;
-};
-
-} // namespace ipc
-} // namespace mozilla
-
-#endif // mozilla_ipc_KeyStore_h
diff --git a/ipc/keystore/KeyStoreConnector.cpp b/ipc/keystore/KeyStoreConnector.cpp
deleted file mode 100644
index 0e11fcec6..000000000
--- a/ipc/keystore/KeyStoreConnector.cpp
+++ /dev/null
@@ -1,239 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=2 et ft=cpp: 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 "KeyStoreConnector.h"
-#include <fcntl.h>
-#include <pwd.h>
-#include <sys/stat.h>
-#include <sys/un.h>
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-#include "nsThreadUtils.h" // For NS_IsMainThread.
-
-#ifdef MOZ_WIDGET_GONK
-#include <android/log.h>
-#define KEYSTORE_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
-#else
-#define KEYSTORE_LOG(args...) printf(args);
-#endif
-
-namespace mozilla {
-namespace ipc {
-
-static const char KEYSTORE_SOCKET_PATH[] = "/dev/socket/keystore";
-
-KeyStoreConnector::KeyStoreConnector(const char** const aAllowedUsers)
- : mAllowedUsers(aAllowedUsers)
-{
- MOZ_COUNT_CTOR_INHERITED(KeyStoreConnector, UnixSocketConnector);
-}
-
-KeyStoreConnector::~KeyStoreConnector()
-{
- MOZ_COUNT_DTOR_INHERITED(KeyStoreConnector, UnixSocketConnector);
-}
-
-nsresult
-KeyStoreConnector::CreateSocket(int& aFd) const
-{
- unlink(KEYSTORE_SOCKET_PATH);
-
- aFd = socket(AF_LOCAL, SOCK_STREAM, 0);
- if (aFd < 0) {
- KEYSTORE_LOG("Could not open KeyStore socket!");
- return NS_ERROR_FAILURE;
- }
-
- return NS_OK;
-}
-
-nsresult
-KeyStoreConnector::SetSocketFlags(int aFd) const
-{
- static const int sReuseAddress = 1;
-
- // Set close-on-exec bit.
- int flags = TEMP_FAILURE_RETRY(fcntl(aFd, F_GETFD));
- if (flags < 0) {
- return NS_ERROR_FAILURE;
- }
- flags |= FD_CLOEXEC;
- int res = TEMP_FAILURE_RETRY(fcntl(aFd, F_SETFD, flags));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- // Set non-blocking status flag.
- flags = TEMP_FAILURE_RETRY(fcntl(aFd, F_GETFL));
- if (flags < 0) {
- return NS_ERROR_FAILURE;
- }
- flags |= O_NONBLOCK;
- res = TEMP_FAILURE_RETRY(fcntl(aFd, F_SETFL, flags));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- // Set socket addr to be reused even if kernel is still waiting to close.
- res = setsockopt(aFd, SOL_SOCKET, SO_REUSEADDR, &sReuseAddress,
- sizeof(sReuseAddress));
- if (res < 0) {
- return NS_ERROR_FAILURE;
- }
-
- return NS_OK;
-}
-
-nsresult
-KeyStoreConnector::CheckPermission(int aFd) const
-{
- struct ucred userCred;
- socklen_t len = sizeof(userCred);
-
- if (getsockopt(aFd, SOL_SOCKET, SO_PEERCRED, &userCred, &len)) {
- return NS_ERROR_FAILURE;
- }
-
- const struct passwd* userInfo = getpwuid(userCred.uid);
- if (!userInfo) {
- return NS_ERROR_FAILURE;
- }
-
- if (!mAllowedUsers) {
- return NS_ERROR_FAILURE;
- }
-
- for (const char** user = mAllowedUsers; *user; ++user) {
- if (!strcmp(*user, userInfo->pw_name)) {
- return NS_OK;
- }
- }
-
- return NS_ERROR_FAILURE;
-}
-
-nsresult
-KeyStoreConnector::CreateAddress(struct sockaddr& aAddress,
- socklen_t& aAddressLength) const
-{
- struct sockaddr_un* address =
- reinterpret_cast<struct sockaddr_un*>(&aAddress);
-
- size_t namesiz = strlen(KEYSTORE_SOCKET_PATH) + 1; // include trailing '\0'
-
- if (namesiz > sizeof(address->sun_path)) {
- KEYSTORE_LOG("Address too long for socket struct!");
- return NS_ERROR_FAILURE;
- }
-
- address->sun_family = AF_UNIX;
- memcpy(address->sun_path, KEYSTORE_SOCKET_PATH, namesiz);
-
- aAddressLength = offsetof(struct sockaddr_un, sun_path) + namesiz;
-
- return NS_OK;
-}
-
-// |UnixSocketConnector|
-
-nsresult
-KeyStoreConnector::ConvertAddressToString(const struct sockaddr& aAddress,
- socklen_t aAddressLength,
- nsACString& aAddressString)
-{
- MOZ_ASSERT(aAddress.sa_family == AF_UNIX);
-
- const struct sockaddr_un* un =
- reinterpret_cast<const struct sockaddr_un*>(&aAddress);
-
- size_t len = aAddressLength - offsetof(struct sockaddr_un, sun_path);
-
- aAddressString.Assign(un->sun_path, len);
-
- return NS_OK;
-}
-
-nsresult
-KeyStoreConnector::CreateListenSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aListenFd)
-{
- ScopedClose fd;
-
- nsresult rv = CreateSocket(fd.rwget());
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = SetSocketFlags(fd);
- if (NS_FAILED(rv)) {
- return rv;
- }
- if (aAddress && aAddressLength) {
- rv = CreateAddress(*aAddress, *aAddressLength);
- if (NS_FAILED(rv)) {
- return rv;
- }
- }
-
- // Allow access for wpa_supplicant (different user, different group)
- //
- // TODO: Improve this by setting specific user/group for
- // wpa_supplicant by calling |fchmod| and |fchown|.
- //
- chmod(KEYSTORE_SOCKET_PATH, S_IRUSR|S_IWUSR|
- S_IRGRP|S_IWGRP|
- S_IROTH|S_IWOTH);
-
- aListenFd = fd.forget();
-
- return NS_OK;
-}
-
-nsresult
-KeyStoreConnector::AcceptStreamSocket(int aListenFd,
- struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd)
-{
- ScopedClose fd(
- TEMP_FAILURE_RETRY(accept(aListenFd, aAddress, aAddressLength)));
- if (fd < 0) {
- NS_WARNING("Cannot accept file descriptor!");
- return NS_ERROR_FAILURE;
- }
- nsresult rv = SetSocketFlags(fd);
- if (NS_FAILED(rv)) {
- return rv;
- }
- rv = CheckPermission(fd);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- aStreamFd = fd.forget();
-
- return NS_OK;
-}
-
-nsresult
-KeyStoreConnector::CreateStreamSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd)
-{
- MOZ_CRASH("|KeyStoreConnector| does not support creating stream sockets.");
- return NS_ERROR_FAILURE;
-}
-
-nsresult
-KeyStoreConnector::Duplicate(UnixSocketConnector*& aConnector)
-{
- aConnector = new KeyStoreConnector(*this);
-
- return NS_OK;
-}
-
-}
-}
diff --git a/ipc/keystore/KeyStoreConnector.h b/ipc/keystore/KeyStoreConnector.h
deleted file mode 100644
index 349b030de..000000000
--- a/ipc/keystore/KeyStoreConnector.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=2 et ft=cpp: 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_KeyStoreConnector_h
-#define mozilla_ipc_KeyStoreConnector_h
-
-#include "mozilla/ipc/UnixSocketConnector.h"
-
-namespace mozilla {
-namespace ipc {
-
-class KeyStoreConnector final : public UnixSocketConnector
-{
-public:
- KeyStoreConnector(const char** const aAllowedUsers);
- ~KeyStoreConnector();
-
- // Methods for |UnixSocketConnector|
- //
-
- nsresult ConvertAddressToString(const struct sockaddr& aAddress,
- socklen_t aAddressLength,
- nsACString& aAddressString) override;
-
- nsresult CreateListenSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aListenFd) override;
-
- nsresult AcceptStreamSocket(int aListenFd,
- struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd) override;
-
- nsresult CreateStreamSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd) override;
-
- nsresult Duplicate(UnixSocketConnector*& aConnector) override;
-
-private:
- nsresult CreateSocket(int& aFd) const;
- nsresult SetSocketFlags(int aFd) const;
- nsresult CheckPermission(int aFd) const;
- nsresult CreateAddress(struct sockaddr& aAddress,
- socklen_t& aAddressLength) const;
-
- const char** const mAllowedUsers;
-};
-
-}
-}
-
-#endif
diff --git a/ipc/keystore/moz.build b/ipc/keystore/moz.build
deleted file mode 100644
index e5df10a30..000000000
--- a/ipc/keystore/moz.build
+++ /dev/null
@@ -1,18 +0,0 @@
-# -*- 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 += [
- 'KeyStore.h'
-]
-
-SOURCES += [
- 'KeyStore.cpp',
- 'KeyStoreConnector.cpp'
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
diff --git a/ipc/moz.build b/ipc/moz.build
index d01b7bbed..320d8c5f0 100644
--- a/ipc/moz.build
+++ b/ipc/moz.build
@@ -14,12 +14,6 @@ DIRS += [
if CONFIG['MOZ_ENABLE_DBUS']:
DIRS += ['dbus']
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DIRS += ['unixfd', 'unixsocket']
-
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DIRS += ['hal', 'keystore', 'netd']
-
if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android':
DIRS += ['contentproc']
diff --git a/ipc/mscom/InterceptorLog.cpp b/ipc/mscom/InterceptorLog.cpp
index c2cd3c7df..3f3dc3f34 100644
--- a/ipc/mscom/InterceptorLog.cpp
+++ b/ipc/mscom/InterceptorLog.cpp
@@ -98,13 +98,8 @@ Logger::Logger(const nsACString& aLeafBaseName)
rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(logFileName));
} else if (procType == GeckoProcessType_Content) {
leafName.AppendLiteral("-Content-");
-#if defined(MOZ_CONTENT_SANDBOX)
- rv = NS_GetSpecialDirectory(NS_APP_CONTENT_PROCESS_TEMP_DIR,
- getter_AddRefs(logFileName));
-#else
rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR,
getter_AddRefs(logFileName));
-#endif // defined(MOZ_CONTENT_SANDBOX)
} else {
return;
}
diff --git a/ipc/netd/Netd.cpp b/ipc/netd/Netd.cpp
deleted file mode 100644
index 99350f250..000000000
--- a/ipc/netd/Netd.cpp
+++ /dev/null
@@ -1,374 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "Netd.h"
-#include <android/log.h>
-#include <cutils/sockets.h>
-#include <fcntl.h>
-#include <sys/socket.h>
-
-#include "android/log.h"
-#include "base/task.h"
-
-#include "nsWhitespaceTokenizer.h"
-#include "nsXULAppAPI.h"
-#include "nsString.h"
-#include "nsThreadUtils.h"
-#include "mozilla/RefPtr.h"
-#include "mozilla/Sprintf.h"
-#include "SystemProperty.h"
-
-#define NETD_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
-#define ICS_SYS_USB_RNDIS_MAC "/sys/class/android_usb/android0/f_rndis/ethaddr"
-#define INVALID_SOCKET -1
-#define MAX_RECONNECT_TIMES 10
-
-using mozilla::system::Property;
-
-namespace {
-
-RefPtr<mozilla::ipc::NetdClient> gNetdClient;
-RefPtr<mozilla::ipc::NetdConsumer> gNetdConsumer;
-
-class StopNetdConsumer : public mozilla::Runnable {
-public:
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(NS_IsMainThread());
-
- gNetdConsumer = nullptr;
- return NS_OK;
- }
-};
-
-bool
-InitRndisAddress()
-{
- char mac[20];
- char serialno[] = "1234567890ABCDEF";
- static const int kEthernetAddressLength = 6;
- char address[kEthernetAddressLength];
- int i = 0;
- int ret = 0;
- int length = 0;
- mozilla::ScopedClose fd;
-
- fd.rwget() = open(ICS_SYS_USB_RNDIS_MAC, O_WRONLY);
- if (fd.rwget() == -1) {
- NETD_LOG("Unable to open file %s.", ICS_SYS_USB_RNDIS_MAC);
- return false;
- }
-
- Property::Get("ro.serialno", serialno, "1234567890ABCDEF");
-
- memset(address, 0, sizeof(address));
- // First byte is 0x02 to signify a locally administered address.
- address[0] = 0x02;
- length = strlen(serialno);
- for (i = 0; i < length; i++) {
- address[i % (kEthernetAddressLength - 1) + 1] ^= serialno[i];
- }
-
- SprintfLiteral(mac, "%02x:%02x:%02x:%02x:%02x:%02x",
- address[0], address[1], address[2],
- address[3], address[4], address[5]);
- length = strlen(mac);
- ret = write(fd.get(), mac, length);
- if (ret != length) {
- NETD_LOG("Fail to write file %s.", ICS_SYS_USB_RNDIS_MAC);
- return false;
- }
- return true;
-}
-
-} // namespace
-
-namespace mozilla {
-namespace ipc {
-
-NetdClient::NetdClient()
- : LineWatcher('\0', MAX_COMMAND_SIZE)
- , mIOLoop(MessageLoopForIO::current())
- , mSocket(INVALID_SOCKET)
- , mCurrentWriteOffset(0)
- , mReConnectTimes(0)
-{
- MOZ_COUNT_CTOR(NetdClient);
-}
-
-NetdClient::~NetdClient()
-{
- MOZ_COUNT_DTOR(NetdClient);
-}
-
-bool
-NetdClient::OpenSocket()
-{
- mSocket.rwget() = socket_local_client("netd",
- ANDROID_SOCKET_NAMESPACE_RESERVED,
- SOCK_STREAM);
- if (mSocket.rwget() < 0) {
- NETD_LOG("Error connecting to : netd (%s) - will retry", strerror(errno));
- return false;
- }
- // Add FD_CLOEXEC flag.
- int flags = fcntl(mSocket.get(), F_GETFD);
- if (flags == -1) {
- NETD_LOG("Error doing fcntl with F_GETFD command(%s)", strerror(errno));
- return false;
- }
- flags |= FD_CLOEXEC;
- if (fcntl(mSocket.get(), F_SETFD, flags) == -1) {
- NETD_LOG("Error doing fcntl with F_SETFD command(%s)", strerror(errno));
- return false;
- }
- // Set non-blocking.
- if (fcntl(mSocket.get(), F_SETFL, O_NONBLOCK) == -1) {
- NETD_LOG("Error set non-blocking socket(%s)", strerror(errno));
- return false;
- }
- if (!MessageLoopForIO::current()->
- WatchFileDescriptor(mSocket.get(),
- true,
- MessageLoopForIO::WATCH_READ,
- &mReadWatcher,
- this)) {
- NETD_LOG("Error set socket read watcher(%s)", strerror(errno));
- return false;
- }
-
- if (!mOutgoingQ.empty()) {
- MessageLoopForIO::current()->
- WatchFileDescriptor(mSocket.get(),
- false,
- MessageLoopForIO::WATCH_WRITE,
- &mWriteWatcher,
- this);
- }
-
- NETD_LOG("Connected to netd");
- return true;
-}
-
-void NetdClient::OnLineRead(int aFd, nsDependentCSubstring& aMessage)
-{
- // Set errno to 0 first. For preventing to use the stale version of errno.
- errno = 0;
- // We found a line terminator. Each line is formatted as an
- // integer response code followed by the rest of the line.
- // Fish out the response code.
- int responseCode = strtol(aMessage.Data(), nullptr, 10);
- if (!errno) {
- NetdCommand* response = new NetdCommand();
- // Passing all the response message, including the line terminator.
- response->mSize = aMessage.Length();
- memcpy(response->mData, aMessage.Data(), aMessage.Length());
- gNetdConsumer->MessageReceived(response);
- }
-
- if (!responseCode) {
- NETD_LOG("Can't parse netd's response");
- }
-}
-
-void
-NetdClient::OnFileCanWriteWithoutBlocking(int aFd)
-{
- MOZ_ASSERT(aFd == mSocket.get());
- WriteNetdCommand();
-}
-
-void
-NetdClient::OnError()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- mReadWatcher.StopWatchingFileDescriptor();
- mWriteWatcher.StopWatchingFileDescriptor();
-
- mSocket.dispose();
- mCurrentWriteOffset = 0;
- mCurrentNetdCommand = nullptr;
- while (!mOutgoingQ.empty()) {
- delete mOutgoingQ.front();
- mOutgoingQ.pop();
- }
- Start();
-}
-
-// static
-void
-NetdClient::Start()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
-
- if (!gNetdClient) {
- NETD_LOG("Netd Client is not initialized");
- return;
- }
-
- if (!gNetdClient->OpenSocket()) {
- // Socket open failed, try again in a second.
- NETD_LOG("Fail to connect to Netd");
- if (++gNetdClient->mReConnectTimes > MAX_RECONNECT_TIMES) {
- NETD_LOG("Fail to connect to Netd after retry %d times", MAX_RECONNECT_TIMES);
- return;
- }
-
- MessageLoopForIO::current()->
- PostDelayedTask(NewRunnableFunction(NetdClient::Start),
- 1000);
- return;
- }
- gNetdClient->mReConnectTimes = 0;
-}
-
-// static
-void
-NetdClient::SendNetdCommandIOThread(NetdCommand* aMessage)
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(aMessage);
-
- if (!gNetdClient) {
- NETD_LOG("Netd Client is not initialized");
- return;
- }
-
- gNetdClient->mOutgoingQ.push(aMessage);
-
- if (gNetdClient->mSocket.get() == INVALID_SOCKET) {
- NETD_LOG("Netd connection is not established, push the message to queue");
- return;
- }
-
- gNetdClient->WriteNetdCommand();
-}
-
-void
-NetdClient::WriteNetdCommand()
-{
- if (!mCurrentNetdCommand) {
- mCurrentWriteOffset = 0;
- mCurrentNetdCommand = mOutgoingQ.front();
- mOutgoingQ.pop();
- }
-
- while (mCurrentWriteOffset < mCurrentNetdCommand->mSize) {
- ssize_t write_amount = mCurrentNetdCommand->mSize - mCurrentWriteOffset;
- ssize_t written = write(mSocket.get(),
- mCurrentNetdCommand->mData + mCurrentWriteOffset,
- write_amount);
- if (written < 0) {
- NETD_LOG("Cannot write to network, error %d\n", (int) written);
- OnError();
- return;
- }
-
- if (written > 0) {
- mCurrentWriteOffset += written;
- }
-
- if (written != write_amount) {
- NETD_LOG("WriteNetdCommand fail !!! Write is not completed");
- break;
- }
- }
-
- if (mCurrentWriteOffset != mCurrentNetdCommand->mSize) {
- MessageLoopForIO::current()->
- WatchFileDescriptor(mSocket.get(),
- false,
- MessageLoopForIO::WATCH_WRITE,
- &mWriteWatcher,
- this);
- return;
- }
-
- mCurrentNetdCommand = nullptr;
-}
-
-static void
-InitNetdIOThread()
-{
- bool result;
- char propValue[Property::VALUE_MAX_LENGTH];
-
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- MOZ_ASSERT(!gNetdClient);
-
- Property::Get("ro.build.version.sdk", propValue, "0");
- // Assign rndis address for usb tethering in ICS.
- if (atoi(propValue) >= 15) {
- result = InitRndisAddress();
- // We don't return here because InitRnsisAddress() function is related to
- // usb tethering only. Others service such as wifi tethering still need
- // to use ipc to communicate with netd.
- if (!result) {
- NETD_LOG("fail to give rndis interface an address");
- }
- }
- gNetdClient = new NetdClient();
- gNetdClient->Start();
-}
-
-static void
-ShutdownNetdIOThread()
-{
- MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
- nsCOMPtr<nsIRunnable> shutdownEvent = new StopNetdConsumer();
-
- gNetdClient = nullptr;
-
- NS_DispatchToMainThread(shutdownEvent);
-}
-
-void
-StartNetd(NetdConsumer* aNetdConsumer)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(aNetdConsumer);
- MOZ_ASSERT(gNetdConsumer == nullptr);
-
- gNetdConsumer = aNetdConsumer;
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(InitNetdIOThread));
-}
-
-void
-StopNetd()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- nsIThread* currentThread = NS_GetCurrentThread();
- NS_ASSERTION(currentThread, "This should never be null!");
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(ShutdownNetdIOThread));
-
- while (gNetdConsumer) {
- if (!NS_ProcessNextEvent(currentThread)) {
- NS_WARNING("Something bad happened!");
- break;
- }
- }
-}
-
-/**************************************************************************
-*
-* This function runs in net worker Thread context. The net worker thread
-* is created in dom/system/gonk/NetworkManager.js
-*
-**************************************************************************/
-void
-SendNetdCommand(NetdCommand* aMessage)
-{
- MOZ_ASSERT(aMessage);
-
- XRE_GetIOMessageLoop()->PostTask(
- NewRunnableFunction(NetdClient::SendNetdCommandIOThread, aMessage));
-}
-
-} // namespace ipc
-} // namespace mozilla
diff --git a/ipc/netd/Netd.h b/ipc/netd/Netd.h
deleted file mode 100644
index e4e20d2a8..000000000
--- a/ipc/netd/Netd.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_system_netd_h__
-#define mozilla_system_netd_h__
-
-#include "nsISupportsImpl.h"
-#include "nsAutoPtr.h"
-#include "base/message_loop.h"
-#include "mozilla/FileUtils.h"
-
-#define MAX_COMMAND_SIZE 4096
-
-namespace mozilla {
-namespace ipc {
-
-/*
- * Represents raw data going to or coming from the Netd socket.
- */
-struct NetdCommand
-{
- uint8_t mData[MAX_COMMAND_SIZE];
-
- // Number of octets in mData.
- size_t mSize;
-};
-
-class NetdConsumer
-{
-protected:
- virtual ~NetdConsumer() { }
-
-public:
- NS_INLINE_DECL_REFCOUNTING(NetdConsumer)
-
- virtual void MessageReceived(NetdCommand* aMessage) = 0;
-};
-
-class NetdWriteTask : public Runnable
-{
- NS_IMETHOD Run();
-};
-
-class NetdClient : public MessageLoopForIO::LineWatcher
-{
- virtual ~NetdClient();
-
-public:
- NS_INLINE_DECL_REFCOUNTING(NetdClient)
- typedef std::queue<NetdCommand*> NetdCommandQueue;
-
- NetdClient();
- static void Start();
- static void SendNetdCommandIOThread(NetdCommand* aMessage);
-
-private:
- void WriteNetdCommand();
- virtual void OnError();
- virtual void OnLineRead(int aFd, nsDependentCSubstring& aMessage);
- virtual void OnFileCanWriteWithoutBlocking(int aFd);
- bool OpenSocket();
-
- MessageLoopForIO *mIOLoop;
- MessageLoopForIO::FileDescriptorWatcher mReadWatcher;
- MessageLoopForIO::FileDescriptorWatcher mWriteWatcher;
- ScopedClose mSocket;
- NetdCommandQueue mOutgoingQ;
- nsAutoPtr<NetdCommand> mCurrentNetdCommand;
- size_t mCurrentWriteOffset;
- size_t mReConnectTimes;
-};
-
-void StartNetd(NetdConsumer *);
-void StopNetd();
-void SendNetdCommand(NetdCommand *);
-
-} // namespace ipc
-} // namespace mozilla
-
-#endif // mozilla_system_netd_h__
diff --git a/ipc/netd/moz.build b/ipc/netd/moz.build
deleted file mode 100644
index 23340cb93..000000000
--- a/ipc/netd/moz.build
+++ /dev/null
@@ -1,17 +0,0 @@
-# -*- 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 += [
- 'Netd.h',
-]
-
-SOURCES += [
- 'Netd.cpp',
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
diff --git a/ipc/ril/Ril.cpp b/ipc/ril/Ril.cpp
index 90fb12052..5c48643cc 100644
--- a/ipc/ril/Ril.cpp
+++ b/ipc/ril/Ril.cpp
@@ -21,12 +21,7 @@
#undef CHROMIUM_LOG
#endif
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define CHROMIUM_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk", args)
-#else
#define CHROMIUM_LOG(args...) printf(args);
-#endif
namespace mozilla {
namespace ipc {
diff --git a/ipc/ril/RilConnector.cpp b/ipc/ril/RilConnector.cpp
index 6e10beed7..7a86befaa 100644
--- a/ipc/ril/RilConnector.cpp
+++ b/ipc/ril/RilConnector.cpp
@@ -181,11 +181,7 @@ RilConnector::CreateStreamSocket(struct sockaddr* aAddress,
socklen_t* aAddressLength,
int& aStreamFd)
{
-#ifdef MOZ_WIDGET_GONK
- static const int sDomain = AF_UNIX;
-#else
static const int sDomain = AF_INET;
-#endif
ScopedClose fd;
diff --git a/ipc/unixfd/UnixFdWatcher.cpp b/ipc/unixfd/UnixFdWatcher.cpp
deleted file mode 100644
index 41289a90b..000000000
--- a/ipc/unixfd/UnixFdWatcher.cpp
+++ /dev/null
@@ -1,128 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 <fcntl.h>
-#include "UnixFdWatcher.h"
-
-#ifdef CHROMIUM_LOG
-#undef CHROMIUM_LOG
-#endif
-
-#if defined(MOZ_WIDGET_GONK)
-#include <android/log.h>
-#define CHROMIUM_LOG(args...) __android_log_print(ANDROID_LOG_INFO, "I/O", args);
-#else
-#include <stdio.h>
-#define IODEBUG true
-#define CHROMIUM_LOG(args...) if (IODEBUG) printf(args);
-#endif
-
-namespace mozilla {
-namespace ipc {
-
-UnixFdWatcher::~UnixFdWatcher()
-{
- NS_WARNING_ASSERTION(!IsOpen(), "mFd should have been closed already");
-}
-
-void
-UnixFdWatcher::Close()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == mIOLoop);
-
- if (NS_WARN_IF(!IsOpen())) {
- /* mFd should have been open */
- return;
- }
- OnClose();
- RemoveWatchers(READ_WATCHER|WRITE_WATCHER);
- mFd.dispose();
-}
-
-void
-UnixFdWatcher::AddWatchers(unsigned long aWatchers, bool aPersistent)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == mIOLoop);
- MOZ_ASSERT(IsOpen());
-
- // Before we add a watcher, we need to remove it! Removing is always
- // safe, but adding the same watcher twice can lead to endless loops
- // inside libevent.
- RemoveWatchers(aWatchers);
-
- if (aWatchers & READ_WATCHER) {
- MessageLoopForIO::current()->WatchFileDescriptor(
- mFd,
- aPersistent,
- MessageLoopForIO::WATCH_READ,
- &mReadWatcher,
- this);
- }
- if (aWatchers & WRITE_WATCHER) {
- MessageLoopForIO::current()->WatchFileDescriptor(
- mFd,
- aPersistent,
- MessageLoopForIO::WATCH_WRITE,
- &mWriteWatcher,
- this);
- }
-}
-
-void
-UnixFdWatcher::RemoveWatchers(unsigned long aWatchers)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == mIOLoop);
- MOZ_ASSERT(IsOpen());
-
- if (aWatchers & READ_WATCHER) {
- mReadWatcher.StopWatchingFileDescriptor();
- }
- if (aWatchers & WRITE_WATCHER) {
- mWriteWatcher.StopWatchingFileDescriptor();
- }
-}
-
-void
-UnixFdWatcher::OnError(const char* aFunction, int aErrno)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == mIOLoop);
-
- CHROMIUM_LOG("%s failed with error %d (%s)",
- aFunction, aErrno, strerror(aErrno));
-}
-
-UnixFdWatcher::UnixFdWatcher(MessageLoop* aIOLoop)
-: mIOLoop(aIOLoop)
-{
- MOZ_ASSERT(mIOLoop);
-}
-
-UnixFdWatcher::UnixFdWatcher(MessageLoop* aIOLoop, int aFd)
-: mIOLoop(aIOLoop)
-, mFd(aFd)
-{
- MOZ_ASSERT(mIOLoop);
-}
-
-void
-UnixFdWatcher::SetFd(int aFd)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == mIOLoop);
- MOZ_ASSERT(!IsOpen());
- MOZ_ASSERT(FdIsNonBlocking(aFd));
-
- mFd = aFd;
-}
-
-bool
-UnixFdWatcher::FdIsNonBlocking(int aFd)
-{
- int flags = TEMP_FAILURE_RETRY(fcntl(aFd, F_GETFL));
- return (flags > 0) && (flags & O_NONBLOCK);
-}
-
-}
-}
diff --git a/ipc/unixfd/UnixFdWatcher.h b/ipc/unixfd/UnixFdWatcher.h
deleted file mode 100644
index 676b1dbf0..000000000
--- a/ipc/unixfd/UnixFdWatcher.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_UnixFdWatcher_h
-#define mozilla_ipc_UnixFdWatcher_h
-
-#include "base/message_loop.h"
-#include "mozilla/FileUtils.h"
-
-namespace mozilla {
-namespace ipc {
-
-class UnixFdWatcher : public MessageLoopForIO::Watcher
-{
-public:
- enum {
- READ_WATCHER = 1<<0,
- WRITE_WATCHER = 1<<1
- };
-
- virtual ~UnixFdWatcher();
-
- MessageLoop* GetIOLoop() const
- {
- return mIOLoop;
- }
-
- int GetFd() const
- {
- return mFd;
- }
-
- bool IsOpen() const
- {
- return GetFd() >= 0;
- }
-
- virtual void Close();
-
- void AddWatchers(unsigned long aWatchers, bool aPersistent);
- void RemoveWatchers(unsigned long aWatchers);
-
- // Callback method that's run before closing the file descriptor
- virtual void OnClose() {};
-
- // Callback method that's run on POSIX errors
- virtual void OnError(const char* aFunction, int aErrno);
-
-protected:
- UnixFdWatcher(MessageLoop* aIOLoop);
- UnixFdWatcher(MessageLoop* aIOLoop, int aFd);
- void SetFd(int aFd);
-
-private:
- static bool FdIsNonBlocking(int aFd);
-
- MessageLoop* mIOLoop;
- ScopedClose mFd;
- MessageLoopForIO::FileDescriptorWatcher mReadWatcher;
- MessageLoopForIO::FileDescriptorWatcher mWriteWatcher;
-};
-
-}
-}
-
-#endif
diff --git a/ipc/unixfd/UnixFileWatcher.cpp b/ipc/unixfd/UnixFileWatcher.cpp
deleted file mode 100644
index 67e247b5b..000000000
--- a/ipc/unixfd/UnixFileWatcher.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 <fcntl.h>
-#include "UnixFileWatcher.h"
-
-namespace mozilla {
-namespace ipc {
-
-UnixFileWatcher::~UnixFileWatcher()
-{
-}
-
-nsresult
-UnixFileWatcher::Open(const char* aFilename, int aFlags, mode_t aMode)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(aFlags & O_NONBLOCK);
-
- int fd = TEMP_FAILURE_RETRY(open(aFilename, aFlags, aMode));
- if (fd < 0) {
- OnError("open", errno);
- return NS_ERROR_FAILURE;
- }
- SetFd(fd);
- OnOpened();
-
- return NS_OK;
-}
-
-UnixFileWatcher::UnixFileWatcher(MessageLoop* aIOLoop)
-: UnixFdWatcher(aIOLoop)
-{
-}
-
-UnixFileWatcher::UnixFileWatcher(MessageLoop* aIOLoop, int aFd)
-: UnixFdWatcher(aIOLoop, aFd)
-{
-}
-
-}
-}
diff --git a/ipc/unixfd/UnixFileWatcher.h b/ipc/unixfd/UnixFileWatcher.h
deleted file mode 100644
index 5a19b1005..000000000
--- a/ipc/unixfd/UnixFileWatcher.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_UnixFileWatcher_h
-#define mozilla_ipc_UnixFileWatcher_h
-
-#include "UnixFdWatcher.h"
-
-namespace mozilla {
-namespace ipc {
-
-class UnixFileWatcher : public UnixFdWatcher
-{
-public:
- virtual ~UnixFileWatcher();
-
- nsresult Open(const char* aFilename, int aFlags, mode_t aMode = 0);
-
- // Callback method for successful open requests
- virtual void OnOpened() {};
-
-protected:
- UnixFileWatcher(MessageLoop* aIOLoop);
- UnixFileWatcher(MessageLoop* aIOLoop, int aFd);
-};
-
-}
-}
-
-#endif
diff --git a/ipc/unixfd/UnixSocketWatcher.cpp b/ipc/unixfd/UnixSocketWatcher.cpp
deleted file mode 100644
index 2ce32e93d..000000000
--- a/ipc/unixfd/UnixSocketWatcher.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 <fcntl.h>
-#include "UnixSocketWatcher.h"
-
-namespace mozilla {
-namespace ipc {
-
-UnixSocketWatcher::~UnixSocketWatcher()
-{
-}
-
-void UnixSocketWatcher::Close()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
-
- mConnectionStatus = SOCKET_IS_DISCONNECTED;
- UnixFdWatcher::Close();
-}
-
-nsresult
-UnixSocketWatcher::Connect(const struct sockaddr* aAddr, socklen_t aAddrLen)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(IsOpen());
- MOZ_ASSERT(aAddr || !aAddrLen);
-
- if (TEMP_FAILURE_RETRY(connect(GetFd(), aAddr, aAddrLen) < 0)) {
- if (errno == EINPROGRESS) {
- mConnectionStatus = SOCKET_IS_CONNECTING;
- // Set up a write watch to receive the connect signal
- AddWatchers(WRITE_WATCHER, false);
- return NS_OK;
- }
- OnError("connect", errno);
- return NS_ERROR_FAILURE;
- }
-
- mConnectionStatus = SOCKET_IS_CONNECTED;
- OnConnected();
-
- return NS_OK;
-}
-
-nsresult
-UnixSocketWatcher::Listen(const struct sockaddr* aAddr, socklen_t aAddrLen)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(IsOpen());
- MOZ_ASSERT(aAddr || !aAddrLen);
-
- if (mConnectionStatus == SOCKET_IS_DISCONNECTED) {
- // We init the socket descriptor when we listen for the first time.
- if (bind(GetFd(), aAddr, aAddrLen) < 0) {
- OnError("bind", errno);
- return NS_ERROR_FAILURE;
- }
- if (listen(GetFd(), 1) < 0) {
- OnError("listen", errno);
- return NS_ERROR_FAILURE;
- }
- }
- mConnectionStatus = SOCKET_IS_LISTENING;
- OnListening();
-
- return NS_OK;
-}
-
-UnixSocketWatcher::UnixSocketWatcher(MessageLoop* aIOLoop)
-: UnixFdWatcher(aIOLoop)
-, mConnectionStatus(SOCKET_IS_DISCONNECTED)
-{
-}
-
-UnixSocketWatcher::UnixSocketWatcher(MessageLoop* aIOLoop, int aFd,
- ConnectionStatus aConnectionStatus)
-: UnixFdWatcher(aIOLoop, aFd)
-, mConnectionStatus(aConnectionStatus)
-{
-}
-
-void
-UnixSocketWatcher::SetSocket(int aFd, ConnectionStatus aConnectionStatus)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
-
- SetFd(aFd);
- mConnectionStatus = aConnectionStatus;
-}
-
-void
-UnixSocketWatcher::OnFileCanReadWithoutBlocking(int aFd)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(aFd == GetFd());
-
- if (mConnectionStatus == SOCKET_IS_CONNECTED) {
- OnSocketCanReceiveWithoutBlocking();
- } else if (mConnectionStatus == SOCKET_IS_LISTENING) {
- OnSocketCanAcceptWithoutBlocking();
- } else {
- NS_NOTREACHED("invalid connection state for reading");
- }
-}
-
-void
-UnixSocketWatcher::OnFileCanWriteWithoutBlocking(int aFd)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(aFd == GetFd());
-
- if (mConnectionStatus == SOCKET_IS_CONNECTED) {
- OnSocketCanSendWithoutBlocking();
- } else if (mConnectionStatus == SOCKET_IS_CONNECTING) {
- RemoveWatchers(WRITE_WATCHER);
- int error = 0;
- socklen_t len = sizeof(error);
- if (getsockopt(GetFd(), SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
- OnError("getsockopt", errno);
- } else if (error) {
- OnError("connect", error);
- } else {
- mConnectionStatus = SOCKET_IS_CONNECTED;
- OnConnected();
- }
- } else {
- NS_NOTREACHED("invalid connection state for writing");
- }
-}
-
-}
-}
diff --git a/ipc/unixfd/UnixSocketWatcher.h b/ipc/unixfd/UnixSocketWatcher.h
deleted file mode 100644
index 37a0acc0d..000000000
--- a/ipc/unixfd/UnixSocketWatcher.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_UnixSocketWatcher_h
-#define mozilla_ipc_UnixSocketWatcher_h
-
-#include <sys/socket.h>
-#include "UnixFdWatcher.h"
-
-namespace mozilla {
-namespace ipc {
-
-class UnixSocketWatcher : public UnixFdWatcher
-{
-public:
- enum ConnectionStatus {
- SOCKET_IS_DISCONNECTED = 0,
- SOCKET_IS_LISTENING,
- SOCKET_IS_CONNECTING,
- SOCKET_IS_CONNECTED
- };
-
- virtual ~UnixSocketWatcher();
-
- virtual void Close() override;
-
- ConnectionStatus GetConnectionStatus() const
- {
- return mConnectionStatus;
- }
-
- // Connect to a peer
- nsresult Connect(const struct sockaddr* aAddr, socklen_t aAddrLen);
-
- // Listen on socket for incoming connection requests
- nsresult Listen(const struct sockaddr* aAddr, socklen_t aAddrLen);
-
- // Callback method for successful connection requests
- virtual void OnConnected() {};
-
- // Callback method for successful listen requests
- virtual void OnListening() {};
-
- // Callback method for accepting from a listening socket
- virtual void OnSocketCanAcceptWithoutBlocking() {};
-
- // Callback method for receiving from socket
- virtual void OnSocketCanReceiveWithoutBlocking() {};
-
- // Callback method for sending on socket
- virtual void OnSocketCanSendWithoutBlocking() {};
-
-protected:
- UnixSocketWatcher(MessageLoop* aIOLoop);
- UnixSocketWatcher(MessageLoop* aIOLoop, int aFd,
- ConnectionStatus aConnectionStatus);
- void SetSocket(int aFd, ConnectionStatus aConnectionStatus);
-
-private:
- void OnFileCanReadWithoutBlocking(int aFd) override;
- void OnFileCanWriteWithoutBlocking(int aFd) override;
-
- ConnectionStatus mConnectionStatus;
-};
-
-}
-}
-
-#endif
diff --git a/ipc/unixfd/moz.build b/ipc/unixfd/moz.build
deleted file mode 100644
index fdc8a8709..000000000
--- a/ipc/unixfd/moz.build
+++ /dev/null
@@ -1,21 +0,0 @@
-# -*- 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 += [
- 'UnixFdWatcher.h',
- 'UnixFileWatcher.h',
- 'UnixSocketWatcher.h'
-]
-
-SOURCES += [
- 'UnixFdWatcher.cpp',
- 'UnixFileWatcher.cpp',
- 'UnixSocketWatcher.cpp'
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
diff --git a/ipc/unixsocket/ConnectionOrientedSocket.cpp b/ipc/unixsocket/ConnectionOrientedSocket.cpp
deleted file mode 100644
index abcfd1734..000000000
--- a/ipc/unixsocket/ConnectionOrientedSocket.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "ConnectionOrientedSocket.h"
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-#include "UnixSocketConnector.h"
-
-namespace mozilla {
-namespace ipc {
-
-//
-// ConnectionOrientedSocketIO
-//
-
-ConnectionOrientedSocketIO::ConnectionOrientedSocketIO(
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- int aFd, ConnectionStatus aConnectionStatus,
- UnixSocketConnector* aConnector)
- : DataSocketIO(aConsumerLoop)
- , UnixSocketWatcher(aIOLoop, aFd, aConnectionStatus)
- , mConnector(aConnector)
- , mPeerAddressLength(0)
-{
- MOZ_ASSERT(mConnector);
-
- MOZ_COUNT_CTOR_INHERITED(ConnectionOrientedSocketIO, DataSocketIO);
-}
-
-ConnectionOrientedSocketIO::ConnectionOrientedSocketIO(
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- UnixSocketConnector* aConnector)
- : DataSocketIO(aConsumerLoop)
- , UnixSocketWatcher(aIOLoop)
- , mConnector(aConnector)
- , mPeerAddressLength(0)
-{
- MOZ_ASSERT(mConnector);
-
- MOZ_COUNT_CTOR_INHERITED(ConnectionOrientedSocketIO, DataSocketIO);
-}
-
-ConnectionOrientedSocketIO::~ConnectionOrientedSocketIO()
-{
- MOZ_COUNT_DTOR_INHERITED(ConnectionOrientedSocketIO, DataSocketIO);
-}
-
-nsresult
-ConnectionOrientedSocketIO::Accept(int aFd,
- const struct sockaddr* aPeerAddress,
- socklen_t aPeerAddressLength)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTING);
-
- SetSocket(aFd, SOCKET_IS_CONNECTED);
-
- // Address setup
- mPeerAddressLength = aPeerAddressLength;
- memcpy(&mPeerAddress, aPeerAddress, mPeerAddressLength);
-
- // Signal success and start data transfer
- OnConnected();
-
- return NS_OK;
-}
-
-nsresult
-ConnectionOrientedSocketIO::Connect()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(!IsOpen());
-
- struct sockaddr* peerAddress =
- reinterpret_cast<struct sockaddr*>(&mPeerAddress);
- mPeerAddressLength = sizeof(mPeerAddress);
-
- int fd;
- nsresult rv = mConnector->CreateStreamSocket(peerAddress,
- &mPeerAddressLength,
- fd);
- if (NS_FAILED(rv)) {
- // Tell the consumer thread we've errored
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketEventTask>(this, SocketEventTask::CONNECT_ERROR));
- return NS_ERROR_FAILURE;
- }
-
- SetFd(fd);
-
- // calls OnConnected() on success, or OnError() otherwise
- rv = UnixSocketWatcher::Connect(peerAddress, mPeerAddressLength);
-
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- return NS_OK;
-}
-
-void
-ConnectionOrientedSocketIO::Send(UnixSocketIOBuffer* aBuffer)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
-
- EnqueueData(aBuffer);
- AddWatchers(WRITE_WATCHER, false);
-}
-
-// |UnixSocketWatcher|
-
-void
-ConnectionOrientedSocketIO::OnSocketCanReceiveWithoutBlocking()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTED); // see bug 990984
-
- ssize_t res = ReceiveData(GetFd());
- if (res < 0) {
- /* I/O error */
- RemoveWatchers(READ_WATCHER|WRITE_WATCHER);
- } else if (!res) {
- /* EOF or peer shutdown */
- RemoveWatchers(READ_WATCHER);
- }
-}
-
-void
-ConnectionOrientedSocketIO::OnSocketCanSendWithoutBlocking()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTED); // see bug 990984
- MOZ_ASSERT(!IsShutdownOnIOThread());
-
- nsresult rv = SendPendingData(GetFd());
- if (NS_FAILED(rv)) {
- return;
- }
-
- if (HasPendingData()) {
- AddWatchers(WRITE_WATCHER, false);
- }
-}
-
-void
-ConnectionOrientedSocketIO::OnConnected()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_CONNECTED);
-
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketEventTask>(this, SocketEventTask::CONNECT_SUCCESS));
-
- AddWatchers(READ_WATCHER, true);
- if (HasPendingData()) {
- AddWatchers(WRITE_WATCHER, false);
- }
-}
-
-void
-ConnectionOrientedSocketIO::OnListening()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
-
- NS_NOTREACHED("Invalid call to |ConnectionOrientedSocketIO::OnListening|");
-}
-
-void
-ConnectionOrientedSocketIO::OnError(const char* aFunction, int aErrno)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
-
- UnixFdWatcher::OnError(aFunction, aErrno);
-
- // Clean up watchers, status, fd
- Close();
-
- // Tell the consumer thread we've errored
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketEventTask>(this, SocketEventTask::CONNECT_ERROR));
-}
-
-//
-// ConnectionOrientedSocket
-//
-
-ConnectionOrientedSocket::ConnectionOrientedSocket()
-{
- MOZ_COUNT_CTOR_INHERITED(ConnectionOrientedSocket, DataSocket);
-}
-
-ConnectionOrientedSocket::~ConnectionOrientedSocket()
-{
- MOZ_COUNT_DTOR_INHERITED(ConnectionOrientedSocket, DataSocket);
-}
-
-}
-}
diff --git a/ipc/unixsocket/ConnectionOrientedSocket.h b/ipc/unixsocket/ConnectionOrientedSocket.h
deleted file mode 100644
index a1236ec4a..000000000
--- a/ipc/unixsocket/ConnectionOrientedSocket.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_ConnectionOrientedSocket_h
-#define mozilla_ipc_ConnectionOrientedSocket_h
-
-#include <sys/socket.h>
-#include "DataSocket.h"
-#include "mozilla/ipc/UnixSocketWatcher.h"
-
-class MessageLoop;
-
-namespace mozilla {
-namespace ipc {
-
-class UnixSocketConnector;
-
-/*
- * |ConnectionOrientedSocketIO| and |ConnectionOrientedSocket| define
- * interfaces for implementing stream sockets on I/O and consumer thread.
- * |ListenSocket| uses these classes to handle accepted sockets.
- */
-
-class ConnectionOrientedSocketIO
- : public DataSocketIO
- , public UnixSocketWatcher
-{
-public:
- virtual ~ConnectionOrientedSocketIO();
-
- nsresult Accept(int aFd,
- const struct sockaddr* aAddress,
- socklen_t aAddressLength);
-
- nsresult Connect();
-
- void Send(UnixSocketIOBuffer* aBuffer);
-
- // Methods for |UnixSocketWatcher|
- //
-
- void OnSocketCanReceiveWithoutBlocking() final;
- void OnSocketCanSendWithoutBlocking() final;
-
- void OnListening() final;
- void OnConnected() final;
- void OnError(const char* aFunction, int aErrno) final;
-
-protected:
- /**
- * Constructs an instance of |ConnectionOrientedSocketIO|
- *
- * @param aConsumerLoop The socket's consumer thread.
- * @param aIOLoop The socket's I/O loop.
- * @param aFd The socket file descriptor.
- * @param aConnectionStatus The connection status for |aFd|.
- * @param aConnector Connector object for socket-type-specific methods.
- */
- ConnectionOrientedSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- int aFd, ConnectionStatus aConnectionStatus,
- UnixSocketConnector* aConnector);
-
- /**
- * Constructs an instance of |ConnectionOrientedSocketIO|
- *
- * @param aConsumerLoop The socket's consumer thread.
- * @param aIOLoop The socket's I/O loop.
- * @param aConnector Connector object for socket-type-specific methods.
- */
- ConnectionOrientedSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- UnixSocketConnector* aConnector);
-
-private:
- /**
- * Connector object used to create the connection we are currently using.
- */
- UniquePtr<UnixSocketConnector> mConnector;
-
- /**
- * Number of valid bytes in |mPeerAddress|.
- */
- socklen_t mPeerAddressLength;
-
- /**
- * Address of the socket's current peer.
- */
- struct sockaddr_storage mPeerAddress;
-};
-
-class ConnectionOrientedSocket : public DataSocket
-{
-public:
- /**
- * Prepares an instance of |ConnectionOrientedSocket| in DISCONNECTED
- * state for accepting a connection. Consumer-thread only.
- *
- * @param aConnector The new connector object, owned by the
- * connection-oriented socket.
- * @param aConsumerLoop The socket's consumer thread.
- * @param aIOLoop The socket's I/O thread.
- * @param[out] aIO, Returns an instance of |ConnectionOrientedSocketIO|.
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- virtual nsresult PrepareAccept(UnixSocketConnector* aConnector,
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ConnectionOrientedSocketIO*& aIO) = 0;
-
-protected:
- ConnectionOrientedSocket();
- virtual ~ConnectionOrientedSocket();
-};
-
-}
-}
-
-#endif // mozilla_ipc_ConnectionOrientedSocket
diff --git a/ipc/unixsocket/DataSocket.cpp b/ipc/unixsocket/DataSocket.cpp
deleted file mode 100644
index 057c59203..000000000
--- a/ipc/unixsocket/DataSocket.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "DataSocket.h"
-#ifdef MOZ_TASK_TRACER
-#include "GeckoTaskTracer.h"
-#endif
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-
-#ifdef MOZ_TASK_TRACER
-using namespace mozilla::tasktracer;
-#endif
-
-namespace mozilla {
-namespace ipc {
-
-//
-// DataSocketIO
-//
-
-DataSocketIO::~DataSocketIO()
-{
- MOZ_COUNT_DTOR_INHERITED(DataSocketIO, SocketIOBase);
-}
-
-void
-DataSocketIO::EnqueueData(UnixSocketIOBuffer* aBuffer)
-{
- if (!aBuffer->GetSize()) {
- delete aBuffer; // delete empty data immediately
- return;
- }
- mOutgoingQ.AppendElement(aBuffer);
-}
-
-bool
-DataSocketIO::HasPendingData() const
-{
- return !mOutgoingQ.IsEmpty();
-}
-
-ssize_t
-DataSocketIO::ReceiveData(int aFd)
-{
- MOZ_ASSERT(aFd >= 0);
-
- UnixSocketIOBuffer* incoming;
- nsresult rv = QueryReceiveBuffer(&incoming);
- if (NS_FAILED(rv)) {
- /* an error occured */
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketRequestClosingTask>(this));
- return -1;
- }
-
- ssize_t res = incoming->Receive(aFd);
- if (res < 0) {
- /* an I/O error occured */
- DiscardBuffer();
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketRequestClosingTask>(this));
- return -1;
- } else if (!res) {
- /* EOF or peer shut down sending */
- DiscardBuffer();
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketRequestClosingTask>(this));
- return 0;
- }
-
-#ifdef MOZ_TASK_TRACER
- /* Make unix socket creation events to be the source events of TaskTracer,
- * and originate the rest correlation tasks from here.
- */
- AutoSourceEvent taskTracerEvent(SourceEventType::Unixsocket);
-#endif
-
- ConsumeBuffer();
-
- return res;
-}
-
-nsresult
-DataSocketIO::SendPendingData(int aFd)
-{
- MOZ_ASSERT(aFd >= 0);
-
- while (HasPendingData()) {
- UnixSocketIOBuffer* outgoing = mOutgoingQ.ElementAt(0);
-
- ssize_t res = outgoing->Send(aFd);
- if (res < 0) {
- /* an I/O error occured */
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketRequestClosingTask>(this));
- return NS_ERROR_FAILURE;
- } else if (!res && outgoing->GetSize()) {
- /* I/O is currently blocked; try again later */
- return NS_OK;
- }
- if (!outgoing->GetSize()) {
- mOutgoingQ.RemoveElementAt(0);
- delete outgoing;
- }
- }
-
- return NS_OK;
-}
-
-DataSocketIO::DataSocketIO(MessageLoop* aConsumerLoop)
- : SocketIOBase(aConsumerLoop)
-{
- MOZ_COUNT_CTOR_INHERITED(DataSocketIO, SocketIOBase);
-}
-
-//
-// DataSocket
-//
-
-DataSocket::DataSocket()
-{
- MOZ_COUNT_CTOR_INHERITED(DataSocket, SocketBase);
-}
-
-DataSocket::~DataSocket()
-{
- MOZ_COUNT_DTOR_INHERITED(DataSocket, SocketBase);
-}
-
-}
-}
diff --git a/ipc/unixsocket/DataSocket.h b/ipc/unixsocket/DataSocket.h
deleted file mode 100644
index 454333461..000000000
--- a/ipc/unixsocket/DataSocket.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/.
- */
-
-#ifndef mozilla_ipc_datasocket_h
-#define mozilla_ipc_datasocket_h
-
-#include "mozilla/ipc/SocketBase.h"
-#include "nsTArray.h"
-
-namespace mozilla {
-namespace ipc {
-
-//
-// DataSocket
-//
-
-/**
- * |DataSocket| represents a socket that can send or receive data. This
- * can be a stream-based socket, a datagram-based socket, or any other
- * socket that transfers data.
- */
-class DataSocket : public SocketBase
-{
-public:
- virtual ~DataSocket();
-
- /**
- * Queue data to be sent to the socket on the IO thread. Can only be called on
- * originating thread.
- *
- * @param aBuffer Data to be sent to socket
- */
- virtual void SendSocketData(UnixSocketIOBuffer* aBuffer) = 0;
-
-protected:
- DataSocket();
-};
-
-//
-// DataSocketIO
-//
-
-/**
- * |DataSocketIO| is a base class for Socket I/O classes that
- * transfer data on the I/O thread. It provides methods for the
- * most common read and write scenarios.
- */
-class DataSocketIO : public SocketIOBase
-{
-public:
- virtual ~DataSocketIO();
-
- /**
- * Allocates a buffer for receiving data from the socket. The method
- * shall return the buffer in the arguments. The buffer is owned by the
- * I/O class. |DataSocketIO| will never ask for more than one buffer
- * at a time, so I/O classes can handout the same buffer on each invokation
- * of this method. I/O-thread only.
- *
- * @param[out] aBuffer returns a pointer to the I/O buffer
- * @return NS_OK on success, or an error code otherwise
- */
- virtual nsresult QueryReceiveBuffer(UnixSocketIOBuffer** aBuffer) = 0;
-
- /**
- * Marks the current socket buffer to by consumed by the I/O class. The
- * class is resonsible for releasing the buffer afterwards. I/O-thread
- * only.
- *
- * @param aIndex the socket's index
- * @param[out] aBuffer the receive buffer
- * @param[out] aSize the receive buffer's size
- */
- virtual void ConsumeBuffer() = 0;
-
- /**
- * Marks the current socket buffer to be discarded. The I/O class is
- * resonsible for releasing the buffer's memory. I/O-thread only.
- *
- * @param aIndex the socket's index
- */
- virtual void DiscardBuffer() = 0;
-
- void EnqueueData(UnixSocketIOBuffer* aBuffer);
- bool HasPendingData() const;
-
- ssize_t ReceiveData(int aFd);
-
- nsresult SendPendingData(int aFd);
-
-protected:
- DataSocketIO(MessageLoop* aConsumerLoop);
-
-private:
- /**
- * Raw data queue. Must be pushed/popped from I/O thread only.
- */
- nsTArray<UnixSocketIOBuffer*> mOutgoingQ;
-};
-
-//
-// Tasks
-//
-
-/* |SocketIOSendTask| transfers an instance of |Tdata|, such as
- * |UnixSocketRawData|, to the I/O thread and queues it up for
- * sending the contained data.
- */
-template<typename Tio, typename Tdata>
-class SocketIOSendTask final : public SocketIOTask<Tio>
-{
-public:
- SocketIOSendTask(Tio* aIO, Tdata* aData)
- : SocketIOTask<Tio>(aIO)
- , mData(aData)
- {
- MOZ_ASSERT(aData);
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(!SocketIOTask<Tio>::IsCanceled());
-
- Tio* io = SocketIOTask<Tio>::GetIO();
- MOZ_ASSERT(!io->IsConsumerThread());
- MOZ_ASSERT(!io->IsShutdownOnIOThread());
-
- io->Send(mData);
-
- return NS_OK;
- }
-
-private:
- Tdata* mData;
-};
-
-}
-}
-
-#endif
diff --git a/ipc/unixsocket/ListenSocket.cpp b/ipc/unixsocket/ListenSocket.cpp
deleted file mode 100644
index c05a4d701..000000000
--- a/ipc/unixsocket/ListenSocket.cpp
+++ /dev/null
@@ -1,432 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "ListenSocket.h"
-#include <fcntl.h>
-#include "ConnectionOrientedSocket.h"
-#include "DataSocket.h"
-#include "ListenSocketConsumer.h"
-#include "mozilla/DebugOnly.h"
-#include "mozilla/RefPtr.h"
-#include "mozilla/Unused.h"
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-#include "nsXULAppAPI.h"
-#include "UnixSocketConnector.h"
-
-namespace mozilla {
-namespace ipc {
-
-//
-// ListenSocketIO
-//
-
-class ListenSocketIO final
- : public UnixSocketWatcher
- , public SocketIOBase
-{
-public:
- class ListenTask;
-
- ListenSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ListenSocket* aListenSocket,
- UnixSocketConnector* aConnector);
- ~ListenSocketIO();
-
- UnixSocketConnector* GetConnector() const;
-
- // Task callback methods
- //
-
- /**
- * Run bind/listen to prepare for further runs of accept()
- */
- void Listen(ConnectionOrientedSocketIO* aCOSocketIO);
-
- // I/O callback methods
- //
-
- void OnConnected() override;
- void OnError(const char* aFunction, int aErrno) override;
- void OnListening() override;
- void OnSocketCanAcceptWithoutBlocking() override;
-
- // Methods for |SocketIOBase|
- //
-
- SocketBase* GetSocketBase() override;
-
- bool IsShutdownOnConsumerThread() const override;
- bool IsShutdownOnIOThread() const override;
-
- void ShutdownOnConsumerThread() override;
- void ShutdownOnIOThread() override;
-
-private:
- void FireSocketError();
-
- /**
- * Consumer pointer. Non-thread-safe pointer, so should only be manipulated
- * directly from consumer thread. All non-consumer-thread accesses should
- * happen with mIO as container.
- */
- ListenSocket* mListenSocket;
-
- /**
- * Connector object used to create the connection we are currently using.
- */
- UniquePtr<UnixSocketConnector> mConnector;
-
- /**
- * If true, do not requeue whatever task we're running
- */
- bool mShuttingDownOnIOThread;
-
- /**
- * Number of valid bytes in |mAddress|
- */
- socklen_t mAddressLength;
-
- /**
- * Address structure of the socket currently in use
- */
- struct sockaddr_storage mAddress;
-
- ConnectionOrientedSocketIO* mCOSocketIO;
-};
-
-ListenSocketIO::ListenSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ListenSocket* aListenSocket,
- UnixSocketConnector* aConnector)
- : UnixSocketWatcher(aIOLoop)
- , SocketIOBase(aConsumerLoop)
- , mListenSocket(aListenSocket)
- , mConnector(aConnector)
- , mShuttingDownOnIOThread(false)
- , mAddressLength(0)
- , mCOSocketIO(nullptr)
-{
- MOZ_ASSERT(mListenSocket);
- MOZ_ASSERT(mConnector);
-
- MOZ_COUNT_CTOR_INHERITED(ListenSocketIO, SocketIOBase);
-}
-
-ListenSocketIO::~ListenSocketIO()
-{
- MOZ_ASSERT(IsConsumerThread());
- MOZ_ASSERT(IsShutdownOnConsumerThread());
-
- MOZ_COUNT_DTOR_INHERITED(ListenSocketIO, SocketIOBase);
-}
-
-UnixSocketConnector*
-ListenSocketIO::GetConnector() const
-{
- return mConnector.get();
-}
-
-void
-ListenSocketIO::Listen(ConnectionOrientedSocketIO* aCOSocketIO)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(mConnector);
- MOZ_ASSERT(aCOSocketIO);
-
- struct sockaddr* address = reinterpret_cast<struct sockaddr*>(&mAddress);
- mAddressLength = sizeof(mAddress);
-
- if (!IsOpen()) {
- int fd;
- nsresult rv = mConnector->CreateListenSocket(address, &mAddressLength,
- fd);
- if (NS_FAILED(rv)) {
- FireSocketError();
- return;
- }
- SetFd(fd);
- }
-
- mCOSocketIO = aCOSocketIO;
-
- // calls OnListening on success, or OnError otherwise
- DebugOnly<nsresult> rv = UnixSocketWatcher::Listen(address, mAddressLength);
- NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Listen failed");
-}
-
-void
-ListenSocketIO::OnConnected()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
-
- NS_NOTREACHED("Invalid call to |ListenSocketIO::OnConnected|");
-}
-
-void
-ListenSocketIO::OnListening()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_LISTENING);
-
- AddWatchers(READ_WATCHER, true);
-
- /* We signal a successful 'connection' to a local address for listening. */
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketEventTask>(this, SocketEventTask::CONNECT_SUCCESS));
-}
-
-void
-ListenSocketIO::OnError(const char* aFunction, int aErrno)
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
-
- UnixFdWatcher::OnError(aFunction, aErrno);
- FireSocketError();
-}
-
-void
-ListenSocketIO::FireSocketError()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
-
- // Clean up watchers, statuses, fds
- Close();
-
- // Tell the consumer thread we've errored
- GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketEventTask>(this, SocketEventTask::CONNECT_ERROR));
-}
-
-void
-ListenSocketIO::OnSocketCanAcceptWithoutBlocking()
-{
- MOZ_ASSERT(MessageLoopForIO::current() == GetIOLoop());
- MOZ_ASSERT(GetConnectionStatus() == SOCKET_IS_LISTENING);
- MOZ_ASSERT(mCOSocketIO);
-
- RemoveWatchers(READ_WATCHER|WRITE_WATCHER);
-
- struct sockaddr_storage storage;
- socklen_t addressLength = sizeof(storage);
-
- int fd;
- nsresult rv = mConnector->AcceptStreamSocket(
- GetFd(),
- reinterpret_cast<struct sockaddr*>(&storage), &addressLength,
- fd);
- if (NS_FAILED(rv)) {
- FireSocketError();
- return;
- }
-
- mCOSocketIO->Accept(fd,
- reinterpret_cast<struct sockaddr*>(&storage),
- addressLength);
-}
-
-// |SocketIOBase|
-
-SocketBase*
-ListenSocketIO::GetSocketBase()
-{
- return mListenSocket;
-}
-
-bool
-ListenSocketIO::IsShutdownOnConsumerThread() const
-{
- MOZ_ASSERT(IsConsumerThread());
-
- return mListenSocket == nullptr;
-}
-
-bool
-ListenSocketIO::IsShutdownOnIOThread() const
-{
- return mShuttingDownOnIOThread;
-}
-
-void
-ListenSocketIO::ShutdownOnConsumerThread()
-{
- MOZ_ASSERT(IsConsumerThread());
- MOZ_ASSERT(!IsShutdownOnConsumerThread());
-
- mListenSocket = nullptr;
-}
-
-void
-ListenSocketIO::ShutdownOnIOThread()
-{
- MOZ_ASSERT(!IsConsumerThread());
- MOZ_ASSERT(!mShuttingDownOnIOThread);
-
- Close(); // will also remove fd from I/O loop
- mShuttingDownOnIOThread = true;
-}
-
-//
-// Socket tasks
-//
-
-class ListenSocketIO::ListenTask final : public SocketIOTask<ListenSocketIO>
-{
-public:
- ListenTask(ListenSocketIO* aIO, ConnectionOrientedSocketIO* aCOSocketIO)
- : SocketIOTask<ListenSocketIO>(aIO)
- , mCOSocketIO(aCOSocketIO)
- {
- MOZ_ASSERT(mCOSocketIO);
-
- MOZ_COUNT_CTOR(ListenTask);
- }
-
- ~ListenTask()
- {
- MOZ_COUNT_DTOR(ListenTask);
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(!GetIO()->IsConsumerThread());
-
- if (!IsCanceled()) {
- GetIO()->Listen(mCOSocketIO);
- }
- return NS_OK;
- }
-
-private:
- ConnectionOrientedSocketIO* mCOSocketIO;
-};
-
-//
-// ListenSocket
-//
-
-ListenSocket::ListenSocket(ListenSocketConsumer* aConsumer, int aIndex)
- : mIO(nullptr)
- , mConsumer(aConsumer)
- , mIndex(aIndex)
-{
- MOZ_ASSERT(mConsumer);
-
- MOZ_COUNT_CTOR_INHERITED(ListenSocket, SocketBase);
-}
-
-ListenSocket::~ListenSocket()
-{
- MOZ_ASSERT(!mIO);
-
- MOZ_COUNT_DTOR_INHERITED(ListenSocket, SocketBase);
-}
-
-nsresult
-ListenSocket::Listen(UnixSocketConnector* aConnector,
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ConnectionOrientedSocket* aCOSocket)
-{
- MOZ_ASSERT(!mIO);
-
- mIO = new ListenSocketIO(aConsumerLoop, aIOLoop, this, aConnector);
-
- // Prepared I/O object, now start listening.
- nsresult rv = Listen(aCOSocket);
- if (NS_FAILED(rv)) {
- delete mIO;
- mIO = nullptr;
- return rv;
- }
-
- return NS_OK;
-}
-
-nsresult
-ListenSocket::Listen(UnixSocketConnector* aConnector,
- ConnectionOrientedSocket* aCOSocket)
-{
- return Listen(aConnector, MessageLoop::current(), XRE_GetIOMessageLoop(),
- aCOSocket);
-}
-
-nsresult
-ListenSocket::Listen(ConnectionOrientedSocket* aCOSocket)
-{
- MOZ_ASSERT(aCOSocket);
- MOZ_ASSERT(mIO);
-
- // We first prepare the connection-oriented socket with a
- // socket connector and a socket I/O class.
-
- UniquePtr<UnixSocketConnector> connector;
- nsresult rv = mIO->GetConnector()->Duplicate(connector);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- ConnectionOrientedSocketIO* io;
- rv = aCOSocket->PrepareAccept(connector.get(),
- mIO->GetConsumerThread(), mIO->GetIOLoop(),
- io);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- Unused << connector.release(); // now owned by |io|
-
- // Then we start listening for connection requests.
-
- SetConnectionStatus(SOCKET_LISTENING);
-
- mIO->GetIOLoop()->PostTask(
- MakeAndAddRef<ListenSocketIO::ListenTask>(mIO, io));
-
- return NS_OK;
-}
-
-// |SocketBase|
-
-void
-ListenSocket::Close()
-{
- if (!mIO) {
- return;
- }
-
- MOZ_ASSERT(mIO->IsConsumerThread());
-
- // From this point on, we consider mIO as being deleted. We sever
- // the relationship here so any future calls to listen or connect
- // will create a new implementation.
- mIO->ShutdownOnConsumerThread();
- mIO->GetIOLoop()->PostTask(MakeAndAddRef<SocketIOShutdownTask>(mIO));
- mIO = nullptr;
-
- NotifyDisconnect();
-}
-
-void
-ListenSocket::OnConnectSuccess()
-{
- mConsumer->OnConnectSuccess(mIndex);
-}
-
-void
-ListenSocket::OnConnectError()
-{
- mConsumer->OnConnectError(mIndex);
-}
-
-void
-ListenSocket::OnDisconnect()
-{
- mConsumer->OnDisconnect(mIndex);
-}
-
-} // namespace ipc
-} // namespace mozilla
diff --git a/ipc/unixsocket/ListenSocket.h b/ipc/unixsocket/ListenSocket.h
deleted file mode 100644
index 9bde4602d..000000000
--- a/ipc/unixsocket/ListenSocket.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_ListenSocket_h
-#define mozilla_ipc_ListenSocket_h
-
-#include "mozilla/ipc/SocketBase.h"
-#include "nsString.h"
-
-class MessageLoop;
-
-namespace mozilla {
-namespace ipc {
-
-class ConnectionOrientedSocket;
-class ListenSocketConsumer;
-class ListenSocketIO;
-class UnixSocketConnector;
-
-class ListenSocket final : public SocketBase
-{
-public:
- /**
- * Constructs an instance of |ListenSocket|.
- *
- * @param aConsumer The consumer for the socket.
- * @param aIndex An arbitrary index.
- */
- ListenSocket(ListenSocketConsumer* aConsumer, int aIndex);
-
- /**
- * Starts a task on the socket that will try to accept a new connection
- * in a non-blocking manner.
- *
- * @param aConnector Connector object for socket-type-specific functions
- * @param aConsumerLoop The socket's consumer thread.
- * @param aIOLoop The socket's I/O thread.
- * @param aCOSocket The connection-oriented socket for handling the
- * accepted connection.
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- nsresult Listen(UnixSocketConnector* aConnector,
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ConnectionOrientedSocket* aCOSocket);
-
- /**
- * Starts a task on the socket that will try to accept a new connection
- * in a non-blocking manner.
- *
- * @param aConnector Connector object for socket-type-specific functions
- * @param aCOSocket The connection-oriented socket for handling the
- * accepted connection.
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- nsresult Listen(UnixSocketConnector* aConnector,
- ConnectionOrientedSocket* aCOSocket);
-
- /**
- * Starts a task on the socket that will try to accept a new connection
- * in a non-blocking manner. This method re-uses a previously created
- * listen socket.
- *
- * @param aCOSocket The connection-oriented socket for handling the
- * accepted connection.
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- nsresult Listen(ConnectionOrientedSocket* aCOSocket);
-
- // Methods for |SocketBase|
- //
-
- void Close() override;
- void OnConnectSuccess() override;
- void OnConnectError() override;
- void OnDisconnect() override;
-
-protected:
- virtual ~ListenSocket();
-
-private:
- ListenSocketIO* mIO;
- ListenSocketConsumer* mConsumer;
- int mIndex;
-};
-
-} // namespace ipc
-} // namepsace mozilla
-
-#endif // mozilla_ipc_ListenSocket_h
diff --git a/ipc/unixsocket/ListenSocketConsumer.cpp b/ipc/unixsocket/ListenSocketConsumer.cpp
deleted file mode 100644
index f4de0c42e..000000000
--- a/ipc/unixsocket/ListenSocketConsumer.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "ListenSocketConsumer.h"
-
-namespace mozilla {
-namespace ipc {
-
-//
-// ListenSocketConsumer
-//
-
-ListenSocketConsumer::~ListenSocketConsumer()
-{ }
-
-}
-}
diff --git a/ipc/unixsocket/ListenSocketConsumer.h b/ipc/unixsocket/ListenSocketConsumer.h
deleted file mode 100644
index 8c9af3019..000000000
--- a/ipc/unixsocket/ListenSocketConsumer.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_listensocketconsumer_h
-#define mozilla_ipc_listensocketconsumer_h
-
-namespace mozilla {
-namespace ipc {
-
-/**
- * |ListenSocketConsumer| handles socket events.
- */
-class ListenSocketConsumer
-{
-public:
- virtual ~ListenSocketConsumer();
-
- /**
- * Callback for socket success. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the listening socket.
- */
- virtual void OnConnectSuccess(int aIndex) = 0;
-
- /**
- * Callback for socket errors. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the listening socket.
- */
- virtual void OnConnectError(int aIndex) = 0;
-
- /**
- * Callback for socket disconnect. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the listeing socket.
- */
- virtual void OnDisconnect(int aIndex) = 0;
-};
-
-}
-}
-
-#endif
diff --git a/ipc/unixsocket/SocketBase.cpp b/ipc/unixsocket/SocketBase.cpp
deleted file mode 100644
index b11729652..000000000
--- a/ipc/unixsocket/SocketBase.cpp
+++ /dev/null
@@ -1,449 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "SocketBase.h"
-#include <errno.h>
-#include <string.h>
-#include <unistd.h>
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-
-namespace mozilla {
-namespace ipc {
-
-//
-// UnixSocketIOBuffer
-//
-
-UnixSocketBuffer::UnixSocketBuffer()
- : mSize(0)
- , mOffset(0)
- , mAvailableSpace(0)
- , mData(nullptr)
-{
- MOZ_COUNT_CTOR(UnixSocketBuffer);
-}
-
-UnixSocketBuffer::~UnixSocketBuffer()
-{
- MOZ_COUNT_DTOR(UnixSocketBuffer);
-
- // Make sure that the caller released the buffer's memory.
- MOZ_ASSERT(!GetBuffer());
-}
-
-const uint8_t*
-UnixSocketBuffer::Consume(size_t aLen)
-{
- if (NS_WARN_IF(GetSize() < aLen)) {
- return nullptr;
- }
- uint8_t* data = mData + mOffset;
- mOffset += aLen;
- return data;
-}
-
-nsresult
-UnixSocketBuffer::Read(void* aValue, size_t aLen)
-{
- const uint8_t* data = Consume(aLen);
- if (!data) {
- return NS_ERROR_OUT_OF_MEMORY;
- }
- memcpy(aValue, data, aLen);
- return NS_OK;
-}
-
-uint8_t*
-UnixSocketBuffer::Append(size_t aLen)
-{
- if (((mAvailableSpace - mSize) < aLen)) {
- size_t availableSpace = mAvailableSpace + std::max(mAvailableSpace, aLen);
- uint8_t* data = new uint8_t[availableSpace];
- memcpy(data, mData, mSize);
- mData = data;
- mAvailableSpace = availableSpace;
- }
- uint8_t* data = mData + mSize;
- mSize += aLen;
- return data;
-}
-
-nsresult
-UnixSocketBuffer::Write(const void* aValue, size_t aLen)
-{
- uint8_t* data = Append(aLen);
- if (!data) {
- return NS_ERROR_OUT_OF_MEMORY;
- }
- memcpy(data, aValue, aLen);
- return NS_OK;
-}
-
-void
-UnixSocketBuffer::CleanupLeadingSpace()
-{
- if (GetLeadingSpace()) {
- if (GetSize() <= GetLeadingSpace()) {
- memcpy(mData, GetData(), GetSize());
- } else {
- memmove(mData, GetData(), GetSize());
- }
- mOffset = 0;
- }
-}
-
-//
-// UnixSocketIOBuffer
-//
-
-UnixSocketIOBuffer::UnixSocketIOBuffer()
-{
- MOZ_COUNT_CTOR_INHERITED(UnixSocketIOBuffer, UnixSocketBuffer);
-}
-
-UnixSocketIOBuffer::~UnixSocketIOBuffer()
-{
- MOZ_COUNT_DTOR_INHERITED(UnixSocketIOBuffer, UnixSocketBuffer);
-}
-
-//
-// UnixSocketRawData
-//
-
-UnixSocketRawData::UnixSocketRawData(const void* aData, size_t aSize)
-{
- MOZ_ASSERT(aData || !aSize);
-
- MOZ_COUNT_CTOR_INHERITED(UnixSocketRawData, UnixSocketIOBuffer);
-
- ResetBuffer(static_cast<uint8_t*>(memcpy(new uint8_t[aSize], aData, aSize)),
- 0, aSize, aSize);
-}
-
-UnixSocketRawData::UnixSocketRawData(UniquePtr<uint8_t[]> aData, size_t aSize)
-{
- MOZ_ASSERT(aData || !aSize);
-
- MOZ_COUNT_CTOR_INHERITED(UnixSocketRawData, UnixSocketIOBuffer);
-
- ResetBuffer(aData.release(), 0, aSize, aSize);
-}
-
-UnixSocketRawData::UnixSocketRawData(size_t aSize)
-{
- MOZ_COUNT_CTOR_INHERITED(UnixSocketRawData, UnixSocketIOBuffer);
-
- ResetBuffer(new uint8_t[aSize], 0, 0, aSize);
-}
-
-UnixSocketRawData::~UnixSocketRawData()
-{
- MOZ_COUNT_DTOR_INHERITED(UnixSocketRawData, UnixSocketIOBuffer);
-
- UniquePtr<uint8_t[]> data(GetBuffer());
- ResetBuffer(nullptr, 0, 0, 0);
-}
-
-ssize_t
-UnixSocketRawData::Receive(int aFd)
-{
- if (!GetTrailingSpace()) {
- if (!GetLeadingSpace()) {
- return -1; /* buffer is full */
- }
- /* free up space at the end of data buffer */
- CleanupLeadingSpace();
- }
-
- ssize_t res =
- TEMP_FAILURE_RETRY(read(aFd, GetTrailingBytes(), GetTrailingSpace()));
-
- if (res < 0) {
- /* I/O error */
- return -1;
- } else if (!res) {
- /* EOF or peer shutdown sending */
- return 0;
- }
-
- Append(res); /* mark read data as 'valid' */
-
- return res;
-}
-
-ssize_t
-UnixSocketRawData::Send(int aFd)
-{
- if (!GetSize()) {
- return 0;
- }
-
- ssize_t res = TEMP_FAILURE_RETRY(write(aFd, GetData(), GetSize()));
-
- if (res < 0) {
- if (errno == EAGAIN || errno == EWOULDBLOCK) {
- return 0; /* socket is blocked; try again later */
- }
- return -1;
- } else if (!res) {
- /* nothing written */
- return 0;
- }
-
- Consume(res);
-
- return res;
-}
-
-//
-// SocketBase
-//
-
-SocketConnectionStatus
-SocketBase::GetConnectionStatus() const
-{
- return mConnectionStatus;
-}
-
-int
-SocketBase::GetSuggestedConnectDelayMs() const
-{
- return mConnectDelayMs;
-}
-
-void
-SocketBase::NotifySuccess()
-{
- mConnectionStatus = SOCKET_CONNECTED;
- mConnectTimestamp = PR_IntervalNow();
- OnConnectSuccess();
-}
-
-void
-SocketBase::NotifyError()
-{
- mConnectionStatus = SOCKET_DISCONNECTED;
- mConnectDelayMs = CalculateConnectDelayMs();
- mConnectTimestamp = 0;
- OnConnectError();
-}
-
-void
-SocketBase::NotifyDisconnect()
-{
- mConnectionStatus = SOCKET_DISCONNECTED;
- mConnectDelayMs = CalculateConnectDelayMs();
- mConnectTimestamp = 0;
- OnDisconnect();
-}
-
-uint32_t
-SocketBase::CalculateConnectDelayMs() const
-{
- uint32_t connectDelayMs = mConnectDelayMs;
-
- if (mConnectTimestamp && (PR_IntervalNow()-mConnectTimestamp) > connectDelayMs) {
- // reset delay if connection has been opened for a while, or...
- connectDelayMs = 0;
- } else if (!connectDelayMs) {
- // ...start with a delay of ~1 sec, or...
- connectDelayMs = 1<<10;
- } else if (connectDelayMs < (1<<16)) {
- // ...otherwise increase delay by a factor of 2
- connectDelayMs <<= 1;
- }
- return connectDelayMs;
-}
-
-SocketBase::SocketBase()
-: mConnectionStatus(SOCKET_DISCONNECTED)
-, mConnectTimestamp(0)
-, mConnectDelayMs(0)
-{
- MOZ_COUNT_CTOR(SocketBase);
-}
-
-SocketBase::~SocketBase()
-{
- MOZ_ASSERT(mConnectionStatus == SOCKET_DISCONNECTED);
-
- MOZ_COUNT_DTOR(SocketBase);
-}
-
-void
-SocketBase::SetConnectionStatus(SocketConnectionStatus aConnectionStatus)
-{
- mConnectionStatus = aConnectionStatus;
-}
-
-//
-// SocketIOBase
-//
-
-SocketIOBase::SocketIOBase(MessageLoop* aConsumerLoop)
- : mConsumerLoop(aConsumerLoop)
-{
- MOZ_ASSERT(mConsumerLoop);
-
- MOZ_COUNT_CTOR(SocketIOBase);
-}
-
-SocketIOBase::~SocketIOBase()
-{
- MOZ_COUNT_DTOR(SocketIOBase);
-}
-
-MessageLoop*
-SocketIOBase::GetConsumerThread() const
-{
- return mConsumerLoop;
-}
-
-bool
-SocketIOBase::IsConsumerThread() const
-{
- return GetConsumerThread() == MessageLoop::current();
-}
-
-//
-// SocketEventTask
-//
-
-SocketEventTask::SocketEventTask(SocketIOBase* aIO, SocketEvent aEvent)
- : SocketTask<SocketIOBase>(aIO)
- , mEvent(aEvent)
-{
- MOZ_COUNT_CTOR(SocketEventTask);
-}
-
-SocketEventTask::~SocketEventTask()
-{
- MOZ_COUNT_DTOR(SocketEventTask);
-}
-
-NS_IMETHODIMP
-SocketEventTask::Run()
-{
- SocketIOBase* io = SocketTask<SocketIOBase>::GetIO();
-
- MOZ_ASSERT(io->IsConsumerThread());
-
- if (NS_WARN_IF(io->IsShutdownOnConsumerThread())) {
- // Since we've already explicitly closed and the close
- // happened before this, this isn't really an error.
- return NS_OK;
- }
-
- SocketBase* socketBase = io->GetSocketBase();
- MOZ_ASSERT(socketBase);
-
- if (mEvent == CONNECT_SUCCESS) {
- socketBase->NotifySuccess();
- } else if (mEvent == CONNECT_ERROR) {
- socketBase->NotifyError();
- } else if (mEvent == DISCONNECT) {
- socketBase->NotifyDisconnect();
- }
-
- return NS_OK;
-}
-
-//
-// SocketRequestClosingTask
-//
-
-SocketRequestClosingTask::SocketRequestClosingTask(SocketIOBase* aIO)
- : SocketTask<SocketIOBase>(aIO)
-{
- MOZ_COUNT_CTOR(SocketRequestClosingTask);
-}
-
-SocketRequestClosingTask::~SocketRequestClosingTask()
-{
- MOZ_COUNT_DTOR(SocketRequestClosingTask);
-}
-
-NS_IMETHODIMP
-SocketRequestClosingTask::Run()
-{
- SocketIOBase* io = SocketTask<SocketIOBase>::GetIO();
-
- MOZ_ASSERT(io->IsConsumerThread());
-
- if (NS_WARN_IF(io->IsShutdownOnConsumerThread())) {
- // Since we've already explicitly closed and the close
- // happened before this, this isn't really an error.
- return NS_OK;
- }
-
- SocketBase* socketBase = io->GetSocketBase();
- MOZ_ASSERT(socketBase);
-
- socketBase->Close();
-
- return NS_OK;
-}
-
-//
-// SocketDeleteInstanceTask
-//
-
-SocketDeleteInstanceTask::SocketDeleteInstanceTask(SocketIOBase* aIO)
- : mIO(aIO)
-{
- MOZ_COUNT_CTOR(SocketDeleteInstanceTask);
-}
-
-SocketDeleteInstanceTask::~SocketDeleteInstanceTask()
-{
- MOZ_COUNT_DTOR(SocketDeleteInstanceTask);
-}
-
-NS_IMETHODIMP
-SocketDeleteInstanceTask::Run()
-{
- mIO.reset(); // delete instance
- return NS_OK;
-}
-
-//
-// SocketIOShutdownTask
-//
-
-SocketIOShutdownTask::SocketIOShutdownTask(SocketIOBase* aIO)
- : SocketIOTask<SocketIOBase>(aIO)
-{
- MOZ_COUNT_CTOR(SocketIOShutdownTask);
-}
-
-SocketIOShutdownTask::~SocketIOShutdownTask()
-{
- MOZ_COUNT_DTOR(SocketIOShutdownTask);
-}
-
-NS_IMETHODIMP
-SocketIOShutdownTask::Run()
-{
- SocketIOBase* io = SocketIOTask<SocketIOBase>::GetIO();
-
- MOZ_ASSERT(!io->IsConsumerThread());
- MOZ_ASSERT(!io->IsShutdownOnIOThread());
-
- // At this point, there should be no new events on the I/O thread
- // after this one with the possible exception of an accept task,
- // which ShutdownOnIOThread will cancel for us. We are now fully
- // shut down, so we can send a message to the consumer thread to
- // delete |io| safely knowing that it's not reference any longer.
- io->ShutdownOnIOThread();
- io->GetConsumerThread()->PostTask(
- MakeAndAddRef<SocketDeleteInstanceTask>(io));
- return NS_OK;
-}
-
-}
-}
diff --git a/ipc/unixsocket/SocketBase.h b/ipc/unixsocket/SocketBase.h
deleted file mode 100644
index 191567fdb..000000000
--- a/ipc/unixsocket/SocketBase.h
+++ /dev/null
@@ -1,585 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/.
- */
-
-#ifndef mozilla_ipc_SocketBase_h
-#define mozilla_ipc_SocketBase_h
-
-#include "base/message_loop.h"
-#include "mozilla/UniquePtr.h"
-
-namespace mozilla {
-namespace ipc {
-
-//
-// UnixSocketBuffer
-//
-
-/**
- * |UnixSocketBuffer| implements a FIFO buffer that stores raw socket
- * data, either for sending on a socket or received from a socket.
- */
-class UnixSocketBuffer
-{
-public:
- virtual ~UnixSocketBuffer();
-
- const uint8_t* GetData() const
- {
- return mData + mOffset;
- }
-
- size_t GetSize() const
- {
- return mSize - mOffset;
- }
-
- const uint8_t* Consume(size_t aLen);
-
- nsresult Read(void* aValue, size_t aLen);
-
- nsresult Read(int8_t& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(uint8_t& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(int16_t& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(uint16_t& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(int32_t& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(uint32_t& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(int64_t& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(uint64_t& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(float& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- nsresult Read(double& aValue)
- {
- return Read(&aValue, sizeof(aValue));
- }
-
- uint8_t* Append(size_t aLen);
-
- nsresult Write(const void* aValue, size_t aLen);
-
- nsresult Write(int8_t aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(uint8_t aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(int16_t aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(uint16_t aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(int32_t aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(uint32_t aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(int64_t aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(uint64_t aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(float aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
- nsresult Write(double aValue)
- {
- return Write(&aValue, sizeof(aValue));
- }
-
-protected:
- UnixSocketBuffer();
-
- /**
- * Sets the raw memory. The caller is responsible for freeing
- * this memory.
- *
- * @param aData A pointer to the buffer's raw memory.
- * @param aOffset The start of valid bytes in |aData|.
- * @param aSize The number of valid bytes in |aData|.
- * @param aAvailableSpace The number of bytes in |aData|.
- */
- void ResetBuffer(uint8_t* aData,
- size_t aOffset, size_t aSize, size_t aAvailableSpace)
- {
- MOZ_ASSERT(aData || !aAvailableSpace);
- MOZ_ASSERT((aOffset + aSize) <= aAvailableSpace);
-
- mOffset = aOffset;
- mSize = aSize;
- mAvailableSpace = aAvailableSpace;
- mData = aData;
- }
-
- /**
- * Retrieves the memory buffer.
- *
- * @return A pointer to the buffer's raw memory.
- */
- uint8_t* GetBuffer()
- {
- return mData;
- }
-
- size_t GetLeadingSpace() const
- {
- return mOffset;
- }
-
- size_t GetTrailingSpace() const
- {
- return mAvailableSpace - mSize;
- }
-
- size_t GetAvailableSpace() const
- {
- return mAvailableSpace;
- }
-
- void* GetTrailingBytes()
- {
- return mData + mSize;
- }
-
- uint8_t* GetData(size_t aOffset)
- {
- MOZ_ASSERT(aOffset <= mSize);
-
- return mData + aOffset;
- }
-
- void SetRange(size_t aOffset, size_t aSize)
- {
- MOZ_ASSERT((aOffset + aSize) <= mAvailableSpace);
-
- mOffset = aOffset;
- mSize = mOffset + aSize;
- }
-
- void CleanupLeadingSpace();
-
-private:
- size_t mSize;
- size_t mOffset;
- size_t mAvailableSpace;
- uint8_t* mData;
-};
-
-//
-// UnixSocketIOBuffer
-//
-
-/**
- * |UnixSocketIOBuffer| is a |UnixSocketBuffer| that supports being
- * received on a socket or being send on a socket. Network protocols
- * might differ in their exact usage of Unix socket functions and
- * |UnixSocketIOBuffer| provides a protocol-neutral interface.
- */
-class UnixSocketIOBuffer : public UnixSocketBuffer
-{
-public:
- UnixSocketIOBuffer();
- virtual ~UnixSocketIOBuffer();
-
- /**
- * Receives data from aFd at the end of the buffer. The returned value
- * is the number of newly received bytes, or 0 if the peer shut down
- * its connection, or a negative value on errors.
- */
- virtual ssize_t Receive(int aFd) = 0;
-
- /**
- * Sends data to aFd from the beginning of the buffer. The returned value
- * is the number of bytes written, or a negative value on error.
- */
- virtual ssize_t Send(int aFd) = 0;
-};
-
-//
-// UnixSocketRawData
-//
-
-class UnixSocketRawData final : public UnixSocketIOBuffer
-{
-public:
- /**
- * This constructor copies aData of aSize bytes length into the
- * new instance of |UnixSocketRawData|.
- *
- * @param aData The buffer to copy.
- * @param aSize The number of bytes in |aData|.
- */
- UnixSocketRawData(const void* aData, size_t aSize);
-
- /**
- * This constructor takes ownership of the data in aData. The
- * data is assumed to be aSize bytes in length.
- *
- * @param aData The buffer to take ownership of.
- * @param aSize The number of bytes in |aData|.
- */
- UnixSocketRawData(UniquePtr<uint8_t[]> aData, size_t aSize);
-
- /**
- * This constructor reserves aSize bytes of space. Currently
- * it's only possible to fill this buffer by calling |Receive|.
- *
- * @param aSize The number of bytes to allocate.
- */
- UnixSocketRawData(size_t aSize);
-
- /**
- * The destructor releases the buffer's raw memory.
- */
- ~UnixSocketRawData();
-
- /**
- * Receives data from aFd at the end of the buffer. The returned value
- * is the number of newly received bytes, or 0 if the peer shut down
- * its connection, or a negative value on errors.
- */
- ssize_t Receive(int aFd) override;
-
- /**
- * Sends data to aFd from the beginning of the buffer. The returned value
- * is the number of bytes written, or a negative value on error.
- */
- ssize_t Send(int aFd) override;
-};
-
-enum SocketConnectionStatus {
- SOCKET_DISCONNECTED = 0,
- SOCKET_LISTENING = 1,
- SOCKET_CONNECTING = 2,
- SOCKET_CONNECTED = 3
-};
-
-//
-// SocketBase
-//
-
-class SocketBase
-{
-public:
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(SocketBase)
-
- SocketConnectionStatus GetConnectionStatus() const;
-
- int GetSuggestedConnectDelayMs() const;
-
- /**
- * Queues the internal representation of socket for deletion. Can be called
- * from consumer thread.
- */
- virtual void Close() = 0;
-
- /**
- * Callback for socket connect/accept success. Called after connect/accept has
- * finished. Will be run on consumer thread before any reads take place.
- */
- virtual void OnConnectSuccess() = 0;
-
- /**
- * Callback for socket connect/accept error. Will be run on consumer thread.
- */
- virtual void OnConnectError() = 0;
-
- /**
- * Callback for socket disconnect. Will be run on consumer thread.
- */
- virtual void OnDisconnect() = 0;
-
- /**
- * Called by implementation to notify consumer of success.
- */
- void NotifySuccess();
-
- /**
- * Called by implementation to notify consumer of error.
- */
- void NotifyError();
-
- /**
- * Called by implementation to notify consumer of disconnect.
- */
- void NotifyDisconnect();
-
-protected:
- SocketBase();
- virtual ~SocketBase();
-
- void SetConnectionStatus(SocketConnectionStatus aConnectionStatus);
-
-private:
- uint32_t CalculateConnectDelayMs() const;
-
- SocketConnectionStatus mConnectionStatus;
- PRIntervalTime mConnectTimestamp;
- uint32_t mConnectDelayMs;
-};
-
-//
-// SocketIOBase
-//
-
-/**
- * |SocketIOBase| is a base class for Socket I/O classes that
- * perform operations on the I/O thread.
- */
-class SocketIOBase
-{
-public:
- virtual ~SocketIOBase();
-
- /**
- * Implemented by socket I/O classes to return the current instance of
- * |SocketBase|.
- *
- * @return The current instance of |SocketBase|
- */
- virtual SocketBase* GetSocketBase() = 0;
-
- /**
- * Implemented by socket I/O classes to signal that the socket I/O class has
- * been shut down.
- *
- * @return True if the socket I/O class has been shut down, false otherwise.
- */
- virtual bool IsShutdownOnIOThread() const = 0;
-
- /**
- * Implemented by socket I/O classes to signal that socket class has
- * been shut down.
- *
- * @return True if the socket class has been shut down, false otherwise.
- */
- virtual bool IsShutdownOnConsumerThread() const = 0;
-
- /**
- * Signals to the socket I/O classes that it has been shut down.
- */
- virtual void ShutdownOnIOThread() = 0;
-
- /**
- * Signals to the socket I/O classes that the socket class has been
- * shut down.
- */
- virtual void ShutdownOnConsumerThread() = 0;
-
- /**
- * Returns the consumer thread.
- *
- * @return A pointer to the consumer thread.
- */
- MessageLoop* GetConsumerThread() const;
-
- /**
- * @return True if the current thread is the consumer thread, or false
- * otherwise.
- */
- bool IsConsumerThread() const;
-
-protected:
- SocketIOBase(MessageLoop* aConsumerLoop);
-
-private:
- MessageLoop* mConsumerLoop;
-};
-
-//
-// Socket tasks
-//
-
-/* |SocketTask| is a task for sending a message from
- * the I/O thread to the consumer thread.
- */
-template <typename T>
-class SocketTask : public CancelableRunnable
-{
-public:
- virtual ~SocketTask()
- { }
-
- T* GetIO() const
- {
- return mIO;
- }
-
-protected:
- SocketTask(T* aIO)
- : mIO(aIO)
- {
- MOZ_ASSERT(aIO);
- }
-
-private:
- T* mIO;
-};
-
-/**
- * |SocketEventTask| reports the connection state on the
- * I/O thread back to the consumer thread.
- */
-class SocketEventTask final : public SocketTask<SocketIOBase>
-{
-public:
- enum SocketEvent {
- CONNECT_SUCCESS,
- CONNECT_ERROR,
- DISCONNECT
- };
-
- SocketEventTask(SocketIOBase* aIO, SocketEvent aEvent);
- ~SocketEventTask();
-
- NS_IMETHOD Run() override;
-
-private:
- SocketEvent mEvent;
-};
-
-/**
- * |SocketRequestClosingTask| closes an instance of |SocketBase|
- * on the consumer thread.
- */
-class SocketRequestClosingTask final : public SocketTask<SocketIOBase>
-{
-public:
- SocketRequestClosingTask(SocketIOBase* aIO);
- ~SocketRequestClosingTask();
-
- NS_IMETHOD Run() override;
-};
-
-/**
- * |SocketDeleteInstanceTask| deletes an object on the consumer thread.
- */
-class SocketDeleteInstanceTask final : public Runnable
-{
-public:
- SocketDeleteInstanceTask(SocketIOBase* aIO);
- ~SocketDeleteInstanceTask();
-
- NS_IMETHOD Run() override;
-
-private:
- UniquePtr<SocketIOBase> mIO;
-};
-
-//
-// Socket I/O tasks
-//
-
-/* |SocketIOTask| holds a reference to a Socket I/O object. It's
- * supposed to run on the I/O thread.
- */
-template<typename Tio>
-class SocketIOTask : public CancelableRunnable
-{
-public:
- virtual ~SocketIOTask()
- { }
-
- Tio* GetIO() const
- {
- return mIO;
- }
-
- nsresult Cancel() override
- {
- mIO = nullptr;
- return NS_OK;
- }
-
- bool IsCanceled() const
- {
- return !mIO;
- }
-
-protected:
- SocketIOTask(Tio* aIO)
- : mIO(aIO)
- {
- MOZ_ASSERT(mIO);
- }
-
-private:
- Tio* mIO;
-};
-
-/**
- * |SocketIOShutdownTask| signals shutdown to the socket I/O class on
- * the I/O thread and sends it to the consumer thread for destruction.
- */
-class SocketIOShutdownTask final : public SocketIOTask<SocketIOBase>
-{
-public:
- SocketIOShutdownTask(SocketIOBase* aIO);
- ~SocketIOShutdownTask();
-
- NS_IMETHOD Run() override;
-};
-
-}
-}
-
-#endif
diff --git a/ipc/unixsocket/StreamSocket.cpp b/ipc/unixsocket/StreamSocket.cpp
deleted file mode 100644
index 04c37e554..000000000
--- a/ipc/unixsocket/StreamSocket.cpp
+++ /dev/null
@@ -1,482 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "StreamSocket.h"
-#include <fcntl.h>
-#include "mozilla/RefPtr.h"
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-#include "nsXULAppAPI.h"
-#include "StreamSocketConsumer.h"
-#include "UnixSocketConnector.h"
-
-static const size_t MAX_READ_SIZE = 1 << 16;
-
-namespace mozilla {
-namespace ipc {
-
-//
-// StreamSocketIO
-//
-
-class StreamSocketIO final : public ConnectionOrientedSocketIO
-{
-public:
- class ConnectTask;
- class DelayedConnectTask;
- class ReceiveTask;
-
- StreamSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- StreamSocket* aStreamSocket,
- UnixSocketConnector* aConnector);
- StreamSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- int aFd, ConnectionStatus aConnectionStatus,
- StreamSocket* aStreamSocket,
- UnixSocketConnector* aConnector);
- ~StreamSocketIO();
-
- StreamSocket* GetStreamSocket();
- DataSocket* GetDataSocket();
-
- // Delayed-task handling
- //
-
- void SetDelayedConnectTask(CancelableRunnable* aTask);
- void ClearDelayedConnectTask();
- void CancelDelayedConnectTask();
-
- // Methods for |DataSocket|
- //
-
- nsresult QueryReceiveBuffer(UnixSocketIOBuffer** aBuffer) override;
- void ConsumeBuffer() override;
- void DiscardBuffer() override;
-
- // Methods for |SocketIOBase|
- //
-
- SocketBase* GetSocketBase() override;
-
- bool IsShutdownOnConsumerThread() const override;
- bool IsShutdownOnIOThread() const override;
-
- void ShutdownOnConsumerThread() override;
- void ShutdownOnIOThread() override;
-
-private:
- /**
- * Consumer pointer. Non-thread-safe pointer, so should only be manipulated
- * directly from consumer thread. All non-consumer-thread accesses should
- * happen with mIO as container.
- */
- StreamSocket* mStreamSocket;
-
- /**
- * If true, do not requeue whatever task we're running
- */
- bool mShuttingDownOnIOThread;
-
- /**
- * Task member for delayed connect task. Should only be access on consumer
- * thread.
- */
- CancelableRunnable* mDelayedConnectTask;
-
- /**
- * I/O buffer for received data
- */
- UniquePtr<UnixSocketRawData> mBuffer;
-};
-
-StreamSocketIO::StreamSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- StreamSocket* aStreamSocket,
- UnixSocketConnector* aConnector)
- : ConnectionOrientedSocketIO(aConsumerLoop, aIOLoop, aConnector)
- , mStreamSocket(aStreamSocket)
- , mShuttingDownOnIOThread(false)
- , mDelayedConnectTask(nullptr)
-{
- MOZ_ASSERT(mStreamSocket);
-
- MOZ_COUNT_CTOR_INHERITED(StreamSocketIO, ConnectionOrientedSocketIO);
-}
-
-StreamSocketIO::StreamSocketIO(MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- int aFd, ConnectionStatus aConnectionStatus,
- StreamSocket* aStreamSocket,
- UnixSocketConnector* aConnector)
- : ConnectionOrientedSocketIO(aConsumerLoop,
- aIOLoop,
- aFd,
- aConnectionStatus,
- aConnector)
- , mStreamSocket(aStreamSocket)
- , mShuttingDownOnIOThread(false)
- , mDelayedConnectTask(nullptr)
-{
- MOZ_ASSERT(mStreamSocket);
-
- MOZ_COUNT_CTOR_INHERITED(StreamSocketIO, ConnectionOrientedSocketIO);
-}
-
-StreamSocketIO::~StreamSocketIO()
-{
- MOZ_ASSERT(IsConsumerThread());
- MOZ_ASSERT(IsShutdownOnConsumerThread());
-
- MOZ_COUNT_DTOR_INHERITED(StreamSocketIO, ConnectionOrientedSocketIO);
-}
-
-StreamSocket*
-StreamSocketIO::GetStreamSocket()
-{
- return mStreamSocket;
-}
-
-DataSocket*
-StreamSocketIO::GetDataSocket()
-{
- return GetStreamSocket();
-}
-
-void
-StreamSocketIO::SetDelayedConnectTask(CancelableRunnable* aTask)
-{
- MOZ_ASSERT(IsConsumerThread());
-
- mDelayedConnectTask = aTask;
-}
-
-void
-StreamSocketIO::ClearDelayedConnectTask()
-{
- MOZ_ASSERT(IsConsumerThread());
-
- mDelayedConnectTask = nullptr;
-}
-
-void
-StreamSocketIO::CancelDelayedConnectTask()
-{
- MOZ_ASSERT(IsConsumerThread());
-
- if (!mDelayedConnectTask) {
- return;
- }
-
- mDelayedConnectTask->Cancel();
- ClearDelayedConnectTask();
-}
-
-// |DataSocketIO|
-
-nsresult
-StreamSocketIO::QueryReceiveBuffer(UnixSocketIOBuffer** aBuffer)
-{
- MOZ_ASSERT(aBuffer);
-
- if (!mBuffer) {
- mBuffer = MakeUnique<UnixSocketRawData>(MAX_READ_SIZE);
- }
- *aBuffer = mBuffer.get();
-
- return NS_OK;
-}
-
-/**
- * |ReceiveTask| transfers data received on the I/O thread
- * to an instance of |StreamSocket| on the consumer thread.
- */
-class StreamSocketIO::ReceiveTask final : public SocketTask<StreamSocketIO>
-{
-public:
- ReceiveTask(StreamSocketIO* aIO, UnixSocketBuffer* aBuffer)
- : SocketTask<StreamSocketIO>(aIO)
- , mBuffer(aBuffer)
- {
- MOZ_COUNT_CTOR(ReceiveTask);
- }
-
- ~ReceiveTask()
- {
- MOZ_COUNT_DTOR(ReceiveTask);
- }
-
- NS_IMETHOD Run() override
- {
- StreamSocketIO* io = SocketTask<StreamSocketIO>::GetIO();
-
- MOZ_ASSERT(io->IsConsumerThread());
-
- if (NS_WARN_IF(io->IsShutdownOnConsumerThread())) {
- // Since we've already explicitly closed and the close
- // happened before this, this isn't really an error.
- return NS_OK;
- }
-
- StreamSocket* streamSocket = io->GetStreamSocket();
- MOZ_ASSERT(streamSocket);
-
- streamSocket->ReceiveSocketData(mBuffer);
-
- return NS_OK;
- }
-
-private:
- UniquePtr<UnixSocketBuffer> mBuffer;
-};
-
-void
-StreamSocketIO::ConsumeBuffer()
-{
- GetConsumerThread()->PostTask(
- MakeAndAddRef<ReceiveTask>(this, mBuffer.release()));
-}
-
-void
-StreamSocketIO::DiscardBuffer()
-{
- // Nothing to do.
-}
-
-// |SocketIOBase|
-
-SocketBase*
-StreamSocketIO::GetSocketBase()
-{
- return GetDataSocket();
-}
-
-bool
-StreamSocketIO::IsShutdownOnConsumerThread() const
-{
- MOZ_ASSERT(IsConsumerThread());
-
- return mStreamSocket == nullptr;
-}
-
-bool
-StreamSocketIO::IsShutdownOnIOThread() const
-{
- return mShuttingDownOnIOThread;
-}
-
-void
-StreamSocketIO::ShutdownOnConsumerThread()
-{
- MOZ_ASSERT(IsConsumerThread());
- MOZ_ASSERT(!IsShutdownOnConsumerThread());
-
- mStreamSocket = nullptr;
-}
-
-void
-StreamSocketIO::ShutdownOnIOThread()
-{
- MOZ_ASSERT(!IsConsumerThread());
- MOZ_ASSERT(!mShuttingDownOnIOThread);
-
- Close(); // will also remove fd from I/O loop
- mShuttingDownOnIOThread = true;
-}
-
-//
-// Socket tasks
-//
-
-class StreamSocketIO::ConnectTask final : public SocketIOTask<StreamSocketIO>
-{
-public:
- ConnectTask(StreamSocketIO* aIO)
- : SocketIOTask<StreamSocketIO>(aIO)
- {
- MOZ_COUNT_CTOR(ReceiveTask);
- }
-
- ~ConnectTask()
- {
- MOZ_COUNT_DTOR(ReceiveTask);
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(!GetIO()->IsConsumerThread());
- MOZ_ASSERT(!IsCanceled());
-
- GetIO()->Connect();
-
- return NS_OK;
- }
-};
-
-class StreamSocketIO::DelayedConnectTask final
- : public SocketIOTask<StreamSocketIO>
-{
-public:
- DelayedConnectTask(StreamSocketIO* aIO)
- : SocketIOTask<StreamSocketIO>(aIO)
- {
- MOZ_COUNT_CTOR(DelayedConnectTask);
- }
-
- ~DelayedConnectTask()
- {
- MOZ_COUNT_DTOR(DelayedConnectTask);
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(GetIO()->IsConsumerThread());
-
- if (IsCanceled()) {
- return NS_OK;
- }
-
- StreamSocketIO* io = GetIO();
- if (io->IsShutdownOnConsumerThread()) {
- return NS_OK;
- }
-
- io->ClearDelayedConnectTask();
- io->GetIOLoop()->PostTask(MakeAndAddRef<ConnectTask>(io));
-
- return NS_OK;
- }
-};
-
-//
-// StreamSocket
-//
-
-StreamSocket::StreamSocket(StreamSocketConsumer* aConsumer, int aIndex)
- : mIO(nullptr)
- , mConsumer(aConsumer)
- , mIndex(aIndex)
-{
- MOZ_ASSERT(mConsumer);
-
- MOZ_COUNT_CTOR_INHERITED(StreamSocket, ConnectionOrientedSocket);
-}
-
-StreamSocket::~StreamSocket()
-{
- MOZ_ASSERT(!mIO);
-
- MOZ_COUNT_DTOR_INHERITED(StreamSocket, ConnectionOrientedSocket);
-}
-
-void
-StreamSocket::ReceiveSocketData(UniquePtr<UnixSocketBuffer>& aBuffer)
-{
- mConsumer->ReceiveSocketData(mIndex, aBuffer);
-}
-
-nsresult
-StreamSocket::Connect(UnixSocketConnector* aConnector, int aDelayMs,
- MessageLoop* aConsumerLoop, MessageLoop* aIOLoop)
-{
- MOZ_ASSERT(!mIO);
-
- mIO = new StreamSocketIO(aConsumerLoop, aIOLoop, this, aConnector);
- SetConnectionStatus(SOCKET_CONNECTING);
-
- if (aDelayMs > 0) {
- RefPtr<StreamSocketIO::DelayedConnectTask> connectTask =
- MakeAndAddRef<StreamSocketIO::DelayedConnectTask>(mIO);
- mIO->SetDelayedConnectTask(connectTask);
- MessageLoop::current()->PostDelayedTask(connectTask.forget(), aDelayMs);
- } else {
- aIOLoop->PostTask(MakeAndAddRef<StreamSocketIO::ConnectTask>(mIO));
- }
-
- return NS_OK;
-}
-
-nsresult
-StreamSocket::Connect(UnixSocketConnector* aConnector, int aDelayMs)
-{
- return Connect(aConnector, aDelayMs,
- MessageLoop::current(), XRE_GetIOMessageLoop());
-}
-
-// |ConnectionOrientedSocket|
-
-nsresult
-StreamSocket::PrepareAccept(UnixSocketConnector* aConnector,
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ConnectionOrientedSocketIO*& aIO)
-{
- MOZ_ASSERT(!mIO);
- MOZ_ASSERT(aConnector);
-
- SetConnectionStatus(SOCKET_CONNECTING);
-
- mIO = new StreamSocketIO(aConsumerLoop, aIOLoop,
- -1, UnixSocketWatcher::SOCKET_IS_CONNECTING,
- this, aConnector);
- aIO = mIO;
-
- return NS_OK;
-}
-
-// |DataSocket|
-
-void
-StreamSocket::SendSocketData(UnixSocketIOBuffer* aBuffer)
-{
- MOZ_ASSERT(mIO);
- MOZ_ASSERT(mIO->IsConsumerThread());
- MOZ_ASSERT(!mIO->IsShutdownOnConsumerThread());
-
- mIO->GetIOLoop()->PostTask(
- MakeAndAddRef<SocketIOSendTask<StreamSocketIO, UnixSocketIOBuffer>>(
- mIO, aBuffer));
-}
-
-// |SocketBase|
-
-void
-StreamSocket::Close()
-{
- MOZ_ASSERT(mIO);
- MOZ_ASSERT(mIO->IsConsumerThread());
-
- mIO->CancelDelayedConnectTask();
-
- // From this point on, we consider |mIO| as being deleted. We sever
- // the relationship here so any future calls to |Connect| will create
- // a new I/O object.
- mIO->ShutdownOnConsumerThread();
- mIO->GetIOLoop()->PostTask(MakeAndAddRef<SocketIOShutdownTask>(mIO));
- mIO = nullptr;
-
- NotifyDisconnect();
-}
-
-void
-StreamSocket::OnConnectSuccess()
-{
- mConsumer->OnConnectSuccess(mIndex);
-}
-
-void
-StreamSocket::OnConnectError()
-{
- mConsumer->OnConnectError(mIndex);
-}
-
-void
-StreamSocket::OnDisconnect()
-{
- mConsumer->OnDisconnect(mIndex);
-}
-
-} // namespace ipc
-} // namespace mozilla
diff --git a/ipc/unixsocket/StreamSocket.h b/ipc/unixsocket/StreamSocket.h
deleted file mode 100644
index cb732389f..000000000
--- a/ipc/unixsocket/StreamSocket.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_streamsocket_h
-#define mozilla_ipc_streamsocket_h
-
-#include "ConnectionOrientedSocket.h"
-
-class MessageLoop;
-
-namespace mozilla {
-namespace ipc {
-
-class StreamSocketConsumer;
-class StreamSocketIO;
-class UnixSocketConnector;
-
-class StreamSocket final : public ConnectionOrientedSocket
-{
-public:
- /**
- * Constructs an instance of |StreamSocket|.
- *
- * @param aConsumer The consumer for the socket.
- * @param aIndex An arbitrary index.
- */
- StreamSocket(StreamSocketConsumer* aConsumer, int aIndex);
-
- /**
- * Method to be called whenever data is received. Consumer-thread only.
- *
- * @param aBuffer Data received from the socket.
- */
- void ReceiveSocketData(UniquePtr<UnixSocketBuffer>& aBuffer);
-
- /**
- * Starts a task on the socket that will try to connect to a socket in a
- * non-blocking manner.
- *
- * @param aConnector Connector object for socket type specific functions
- * @param aDelayMs Time delay in milliseconds.
- * @param aConsumerLoop The socket's consumer thread.
- * @param aIOLoop The socket's I/O thread.
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- nsresult Connect(UnixSocketConnector* aConnector, int aDelayMs,
- MessageLoop* aConsumerLoop, MessageLoop* aIOLoop);
-
- /**
- * Starts a task on the socket that will try to connect to a socket in a
- * non-blocking manner.
- *
- * @param aConnector Connector object for socket type specific functions
- * @param aDelayMs Time delay in milliseconds.
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- nsresult Connect(UnixSocketConnector* aConnector, int aDelayMs = 0);
-
- // Methods for |ConnectionOrientedSocket|
- //
-
- nsresult PrepareAccept(UnixSocketConnector* aConnector,
- MessageLoop* aConsumerLoop,
- MessageLoop* aIOLoop,
- ConnectionOrientedSocketIO*& aIO) override;
-
- // Methods for |DataSocket|
- //
-
- void SendSocketData(UnixSocketIOBuffer* aBuffer) override;
-
- // Methods for |SocketBase|
- //
-
- void Close() override;
- void OnConnectSuccess() override;
- void OnConnectError() override;
- void OnDisconnect() override;
-
-protected:
- virtual ~StreamSocket();
-
-private:
- StreamSocketIO* mIO;
- StreamSocketConsumer* mConsumer;
- int mIndex;
-};
-
-} // namespace ipc
-} // namepsace mozilla
-
-#endif // mozilla_ipc_streamsocket_h
diff --git a/ipc/unixsocket/StreamSocketConsumer.cpp b/ipc/unixsocket/StreamSocketConsumer.cpp
deleted file mode 100644
index bac9c1fe7..000000000
--- a/ipc/unixsocket/StreamSocketConsumer.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "StreamSocketConsumer.h"
-
-namespace mozilla {
-namespace ipc {
-
-//
-// StreamSocketConsumer
-//
-
-StreamSocketConsumer::~StreamSocketConsumer()
-{ }
-
-}
-}
diff --git a/ipc/unixsocket/StreamSocketConsumer.h b/ipc/unixsocket/StreamSocketConsumer.h
deleted file mode 100644
index d1f8c3d5b..000000000
--- a/ipc/unixsocket/StreamSocketConsumer.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_streamsocketconsumer_h
-#define mozilla_ipc_streamsocketconsumer_h
-
-#include "mozilla/UniquePtr.h"
-
-namespace mozilla {
-namespace ipc {
-
-class UnixSocketBuffer;
-
-/**
- * |StreamSocketConsumer| handles socket events and received data.
- */
-class StreamSocketConsumer
-{
-public:
- /**
- * Method to be called whenever data is received. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the stream socket.
- * @param aBuffer Data received from the socket.
- */
- virtual void ReceiveSocketData(int aIndex,
- UniquePtr<UnixSocketBuffer>& aBuffer) = 0;
-
- /**
- * Callback for socket success. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the stream socket.
- */
- virtual void OnConnectSuccess(int aIndex) = 0;
-
- /**
- * Callback for socket errors. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the stream socket.
- */
- virtual void OnConnectError(int aIndex) = 0;
-
- /**
- * Callback for socket disconnect. Consumer-thread only.
- *
- * @param aIndex The index that has been given to the stream socket.
- */
- virtual void OnDisconnect(int aIndex) = 0;
-
-protected:
- virtual ~StreamSocketConsumer();
-};
-
-}
-}
-
-#endif
diff --git a/ipc/unixsocket/UnixSocketConnector.cpp b/ipc/unixsocket/UnixSocketConnector.cpp
deleted file mode 100644
index eb38ff6de..000000000
--- a/ipc/unixsocket/UnixSocketConnector.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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 "UnixSocketConnector.h"
-#include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, MOZ_COUNT_DTOR
-
-namespace mozilla {
-namespace ipc {
-
-UnixSocketConnector::UnixSocketConnector()
-{
- MOZ_COUNT_CTOR(UnixSocketConnector);
-}
-
-UnixSocketConnector::~UnixSocketConnector()
-{
- MOZ_COUNT_DTOR(UnixSocketConnector);
-}
-
-nsresult
-UnixSocketConnector::Duplicate(UniquePtr<UnixSocketConnector>& aConnector)
-{
- UnixSocketConnector* connectorPtr;
- auto rv = Duplicate(connectorPtr);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- aConnector = Move(UniquePtr<UnixSocketConnector>(connectorPtr));
-
- return NS_OK;
-}
-
-}
-}
diff --git a/ipc/unixsocket/UnixSocketConnector.h b/ipc/unixsocket/UnixSocketConnector.h
deleted file mode 100644
index 21d2c7860..000000000
--- a/ipc/unixsocket/UnixSocketConnector.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
-/* 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/. */
-
-#ifndef mozilla_ipc_unixsocketconnector_h
-#define mozilla_ipc_unixsocketconnector_h
-
-#include <sys/socket.h>
-#include "mozilla/ipc/UnixSocketWatcher.h"
-#include "nsString.h"
-
-namespace mozilla {
-namespace ipc {
-
-/**
- * |UnixSocketConnector| defines the socket creation and connection/listening
- * functions for |UnixSocketConsumer|, et al. Due to the fact that socket setup
- * can vary between protocols (Unix sockets, TCP sockets, Bluetooth sockets, etc),
- * this allows the user to create whatever connection mechanism they need while
- * still depending on libevent for non-blocking communication handling.
- */
-class UnixSocketConnector
-{
-public:
- virtual ~UnixSocketConnector();
-
- /**
- * Converts an address to a human-readable string.
- *
- * @param aAddress A socket address
- * @param aAddressLength The number of valid bytes in |aAddress|
- * @param[out] aAddressString The resulting string
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- virtual nsresult ConvertAddressToString(const struct sockaddr& aAddress,
- socklen_t aAddressLength,
- nsACString& aAddressString) = 0;
-
- /**
- * Creates a listening socket. I/O thread only.
- *
- * @param[out] aAddress The listening socket's address
- * @param[out] aAddressLength The number of valid bytes in |aAddress|
- * @param[out] aListenFd The socket's file descriptor
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- virtual nsresult CreateListenSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aListenFd) = 0;
-
- /**
- * Accepts a stream socket from a listening socket. I/O thread only.
- *
- * @param aListenFd The listening socket
- * @param[out] aAddress Returns the stream socket's address
- * @param[out] aAddressLength Returns the number of valid bytes in |aAddress|
- * @param[out] aStreamFd The stream socket's file descriptor
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- virtual nsresult AcceptStreamSocket(int aListenFd,
- struct sockaddr* aAddress,
- socklen_t* aAddressLen,
- int& aStreamFd) = 0;
-
- /**
- * Creates a stream socket. I/O thread only.
- *
- * @param[in|out] aAddress The stream socket's address
- * @param[in|out] aAddressLength The number of valid bytes in |aAddress|
- * @param[out] aStreamFd The socket's file descriptor
- * @return NS_OK on success, or an XPCOM error code otherwise.
- */
- virtual nsresult CreateStreamSocket(struct sockaddr* aAddress,
- socklen_t* aAddressLength,
- int& aStreamFd) = 0;
-
- /**
- * Copies the instance of |UnixSocketConnector|. I/O thread only.
- *
- * @param[in] aConnector Returns a new instance of the connector class
- * @return NS_OK on success, or an XPCOM error code otherwise
- */
- virtual nsresult Duplicate(UnixSocketConnector*& aConnector) = 0;
-
- /**
- * Copies the instance of |UnixSocketConnector|. I/O thread only.
- *
- * @param[in] aConnector Returns a new instance of the connector class
- * @return NS_OK on success, or an XPCOM error code otherwise
- */
- nsresult Duplicate(UniquePtr<UnixSocketConnector>& aConnector);
-
-protected:
- UnixSocketConnector();
-};
-
-}
-}
-
-#endif
diff --git a/ipc/unixsocket/moz.build b/ipc/unixsocket/moz.build
deleted file mode 100644
index 523aac3cb..000000000
--- a/ipc/unixsocket/moz.build
+++ /dev/null
@@ -1,31 +0,0 @@
-# -*- 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 += [
- 'ConnectionOrientedSocket.h',
- 'DataSocket.h',
- 'ListenSocket.h',
- 'ListenSocketConsumer.h',
- 'SocketBase.h',
- 'StreamSocket.h',
- 'StreamSocketConsumer.h',
- 'UnixSocketConnector.h'
-]
-
-SOURCES += [
- 'ConnectionOrientedSocket.cpp',
- 'DataSocket.cpp',
- 'ListenSocket.cpp',
- 'ListenSocketConsumer.cpp',
- 'SocketBase.cpp',
- 'StreamSocket.cpp',
- 'StreamSocketConsumer.cpp',
- 'UnixSocketConnector.cpp'
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
diff --git a/js/public/Value.h b/js/public/Value.h
index a40e65c83..01666ed4e 100644
--- a/js/public/Value.h
+++ b/js/public/Value.h
@@ -140,12 +140,16 @@ static_assert(sizeof(JSValueShiftedTag) == sizeof(uint64_t),
#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_CLEAR | (type)))
+#define JSVAL_RAW64_UNDEFINED (uint64_t(JSVAL_TAG_UNDEFINED) << 32)
+
#define JSVAL_UPPER_EXCL_TAG_OF_PRIMITIVE_SET JSVAL_TAG_OBJECT
#define JSVAL_UPPER_INCL_TAG_OF_NUMBER_SET JSVAL_TAG_INT32
#define JSVAL_LOWER_INCL_TAG_OF_GCTHING_SET JSVAL_TAG_STRING
#elif defined(JS_PUNBOX64)
+#define JSVAL_RAW64_UNDEFINED (uint64_t(JSVAL_TAG_UNDEFINED) << JSVAL_TAG_SHIFT)
+
#define JSVAL_PAYLOAD_MASK 0x00007FFFFFFFFFFFLL
#define JSVAL_TAG_MASK 0xFFFF800000000000LL
#define JSVAL_TYPE_TO_TAG(type) ((JSValueTag)(JSVAL_TAG_MAX_DOUBLE | (type)))
@@ -817,7 +821,7 @@ class MOZ_NON_PARAM alignas(8) Value
double asDouble;
void* asPtr;
- layout() = default;
+ layout() : asBits(JSVAL_RAW64_UNDEFINED) {}
explicit constexpr layout(uint64_t bits) : asBits(bits) {}
explicit constexpr layout(double d) : asDouble(d) {}
} data;
@@ -843,7 +847,7 @@ class MOZ_NON_PARAM alignas(8) Value
size_t asWord;
uintptr_t asUIntPtr;
- layout() = default;
+ layout() : asBits(JSVAL_RAW64_UNDEFINED) {}
explicit constexpr layout(uint64_t bits) : asBits(bits) {}
explicit constexpr layout(double d) : asDouble(d) {}
} data;
@@ -871,7 +875,7 @@ class MOZ_NON_PARAM alignas(8) Value
double asDouble;
void* asPtr;
- layout() = default;
+ layout() : asBits(JSVAL_RAW64_UNDEFINED) {}
explicit constexpr layout(uint64_t bits) : asBits(bits) {}
explicit constexpr layout(double d) : asDouble(d) {}
} data;
@@ -895,7 +899,7 @@ class MOZ_NON_PARAM alignas(8) Value
size_t asWord;
uintptr_t asUIntPtr;
- layout() = default;
+ layout() : asBits(JSVAL_RAW64_UNDEFINED) {}
explicit constexpr layout(uint64_t bits) : asBits(bits) {}
explicit constexpr layout(double d) : asDouble(d) {}
} data;
@@ -948,8 +952,51 @@ class MOZ_NON_PARAM alignas(8) Value
}
} JS_HAZ_GC_POINTER;
+/**
+ * This is a null-constructible structure that can convert to and from
+ * a Value, allowing UninitializedValue to be stored in unions.
+ */
+struct MOZ_NON_PARAM alignas(8) UninitializedValue
+{
+ private:
+ uint64_t bits;
+
+ public:
+ UninitializedValue() = default;
+ UninitializedValue(const UninitializedValue&) = default;
+ MOZ_IMPLICIT UninitializedValue(const Value& val) : bits(val.asRawBits()) {}
+
+ inline uint64_t asRawBits() const {
+ return bits;
+ }
+
+ inline Value& asValueRef() {
+ return *reinterpret_cast<Value*>(this);
+ }
+ inline const Value& asValueRef() const {
+ return *reinterpret_cast<const Value*>(this);
+ }
+
+ inline operator Value&() {
+ return asValueRef();
+ }
+ inline operator Value const&() const {
+ return asValueRef();
+ }
+ inline operator Value() const {
+ return asValueRef();
+ }
+
+ inline void operator=(Value const& other) {
+ asValueRef() = other;
+ }
+};
+
static_assert(sizeof(Value) == 8, "Value size must leave three tag bits, be a binary power, and is ubiquitously depended upon everywhere");
+static_assert(sizeof(UninitializedValue) == sizeof(Value), "Value and UninitializedValue must be the same size");
+static_assert(alignof(UninitializedValue) == alignof(Value), "Value and UninitializedValue must have same alignment");
+
inline bool
IsOptimizedPlaceholderMagicValue(const Value& v)
{
diff --git a/js/src/aclocal.m4 b/js/src/aclocal.m4
index 627837a41..abbbd4873 100644
--- a/js/src/aclocal.m4
+++ b/js/src/aclocal.m4
@@ -25,7 +25,6 @@ builtin(include, ../../build/autoconf/zlib.m4)dnl
builtin(include, ../../build/autoconf/icu.m4)dnl
builtin(include, ../../build/autoconf/clang-plugin.m4)dnl
builtin(include, ../../build/autoconf/alloc.m4)dnl
-builtin(include, ../../build/autoconf/jemalloc.m4)dnl
builtin(include, ../../build/autoconf/sanitize.m4)dnl
builtin(include, ../../build/autoconf/ios.m4)dnl
diff --git a/js/src/builtin/Array.js b/js/src/builtin/Array.js
index 45f90a7b8..360dd2af1 100644
--- a/js/src/builtin/Array.js
+++ b/js/src/builtin/Array.js
@@ -900,11 +900,7 @@ function ArrayToLocaleString(locales, options) {
if (firstElement === undefined || firstElement === null) {
R = "";
} else {
-#if EXPOSE_INTL_API
R = ToString(callContentFunction(firstElement.toLocaleString, firstElement, locales, options));
-#else
- R = ToString(callContentFunction(firstElement.toLocaleString, firstElement));
-#endif
}
// Step 3 (reordered).
@@ -919,11 +915,7 @@ function ArrayToLocaleString(locales, options) {
// Steps 9.a, 9.c-e.
R += separator;
if (!(nextElement === undefined || nextElement === null)) {
-#if EXPOSE_INTL_API
R += ToString(callContentFunction(nextElement.toLocaleString, nextElement, locales, options));
-#else
- R += ToString(callContentFunction(nextElement.toLocaleString, nextElement));
-#endif
}
}
diff --git a/js/src/builtin/Intl.cpp b/js/src/builtin/Intl.cpp
index cd808cb10..71f7b58d4 100644
--- a/js/src/builtin/Intl.cpp
+++ b/js/src/builtin/Intl.cpp
@@ -23,7 +23,6 @@
#include "jsobj.h"
#include "builtin/IntlTimeZoneData.h"
-#if ENABLE_INTL_API
#include "unicode/ucal.h"
#include "unicode/ucol.h"
#include "unicode/udat.h"
@@ -32,7 +31,6 @@
#include "unicode/unum.h"
#include "unicode/unumsys.h"
#include "unicode/ustring.h"
-#endif
#include "vm/DateTime.h"
#include "vm/GlobalObject.h"
#include "vm/Interpreter.h"
@@ -60,603 +58,6 @@ using mozilla::PodCopy;
* http://userguide.icu-project.org/design#TOC-Error-Handling
*/
-
-/******************** ICU stubs ********************/
-
-#if !ENABLE_INTL_API
-
-/*
- * When the Internationalization API isn't enabled, we also shouldn't link
- * against ICU. However, we still want to compile this code in order to prevent
- * bit rot. The following stub implementations for ICU functions make this
- * possible. The functions using them should never be called, so they assert
- * and return error codes. Signatures adapted from ICU header files locid.h,
- * numsys.h, ucal.h, ucol.h, udat.h, udatpg.h, uenum.h, unum.h; see the ICU
- * directory for license.
- */
-
-typedef bool UBool;
-typedef char16_t UChar;
-typedef double UDate;
-
-enum UErrorCode {
- U_ZERO_ERROR,
- U_BUFFER_OVERFLOW_ERROR,
-};
-
-static inline UBool
-U_FAILURE(UErrorCode code)
-{
- MOZ_CRASH("U_FAILURE: Intl API disabled");
-}
-
-inline const UChar*
-Char16ToUChar(const char16_t* chars)
-{
- MOZ_CRASH("Char16ToUChar: Intl API disabled");
-}
-
-inline UChar*
-Char16ToUChar(char16_t* chars)
-{
- MOZ_CRASH("Char16ToUChar: Intl API disabled");
-}
-
-inline char16_t*
-UCharToChar16(UChar* chars)
-{
- MOZ_CRASH("UCharToChar16: Intl API disabled");
-}
-
-inline const char16_t*
-UCharToChar16(const UChar* chars)
-{
- MOZ_CRASH("UCharToChar16: Intl API disabled");
-}
-
-static int32_t
-u_strlen(const UChar* s)
-{
- MOZ_CRASH("u_strlen: Intl API disabled");
-}
-
-struct UEnumeration;
-
-static int32_t
-uenum_count(UEnumeration* en, UErrorCode* status)
-{
- MOZ_CRASH("uenum_count: Intl API disabled");
-}
-
-static const char*
-uenum_next(UEnumeration* en, int32_t* resultLength, UErrorCode* status)
-{
- MOZ_CRASH("uenum_next: Intl API disabled");
-}
-
-static void
-uenum_close(UEnumeration* en)
-{
- MOZ_CRASH("uenum_close: Intl API disabled");
-}
-
-struct UCollator;
-
-enum UColAttribute {
- UCOL_ALTERNATE_HANDLING,
- UCOL_CASE_FIRST,
- UCOL_CASE_LEVEL,
- UCOL_NORMALIZATION_MODE,
- UCOL_STRENGTH,
- UCOL_NUMERIC_COLLATION,
-};
-
-enum UColAttributeValue {
- UCOL_DEFAULT = -1,
- UCOL_PRIMARY = 0,
- UCOL_SECONDARY = 1,
- UCOL_TERTIARY = 2,
- UCOL_OFF = 16,
- UCOL_ON = 17,
- UCOL_SHIFTED = 20,
- UCOL_LOWER_FIRST = 24,
- UCOL_UPPER_FIRST = 25,
-};
-
-enum UCollationResult {
- UCOL_EQUAL = 0,
- UCOL_GREATER = 1,
- UCOL_LESS = -1
-};
-
-static int32_t
-ucol_countAvailable()
-{
- MOZ_CRASH("ucol_countAvailable: Intl API disabled");
-}
-
-static const char*
-ucol_getAvailable(int32_t localeIndex)
-{
- MOZ_CRASH("ucol_getAvailable: Intl API disabled");
-}
-
-static UCollator*
-ucol_open(const char* loc, UErrorCode* status)
-{
- MOZ_CRASH("ucol_open: Intl API disabled");
-}
-
-static void
-ucol_setAttribute(UCollator* coll, UColAttribute attr, UColAttributeValue value, UErrorCode* status)
-{
- MOZ_CRASH("ucol_setAttribute: Intl API disabled");
-}
-
-static UCollationResult
-ucol_strcoll(const UCollator* coll, const UChar* source, int32_t sourceLength,
- const UChar* target, int32_t targetLength)
-{
- MOZ_CRASH("ucol_strcoll: Intl API disabled");
-}
-
-static void
-ucol_close(UCollator* coll)
-{
- MOZ_CRASH("ucol_close: Intl API disabled");
-}
-
-static UEnumeration*
-ucol_getKeywordValuesForLocale(const char* key, const char* locale, UBool commonlyUsed,
- UErrorCode* status)
-{
- MOZ_CRASH("ucol_getKeywordValuesForLocale: Intl API disabled");
-}
-
-struct UParseError;
-struct UFieldPosition;
-struct UFieldPositionIterator;
-typedef void* UNumberFormat;
-
-enum UNumberFormatStyle {
- UNUM_DECIMAL = 1,
- UNUM_CURRENCY,
- UNUM_PERCENT,
- UNUM_CURRENCY_ISO,
- UNUM_CURRENCY_PLURAL,
-};
-
-enum UNumberFormatRoundingMode {
- UNUM_ROUND_HALFUP,
-};
-
-enum UNumberFormatAttribute {
- UNUM_GROUPING_USED,
- UNUM_MIN_INTEGER_DIGITS,
- UNUM_MAX_FRACTION_DIGITS,
- UNUM_MIN_FRACTION_DIGITS,
- UNUM_ROUNDING_MODE,
- UNUM_SIGNIFICANT_DIGITS_USED,
- UNUM_MIN_SIGNIFICANT_DIGITS,
- UNUM_MAX_SIGNIFICANT_DIGITS,
-};
-
-enum UNumberFormatTextAttribute {
- UNUM_CURRENCY_CODE,
-};
-
-static int32_t
-unum_countAvailable()
-{
- MOZ_CRASH("unum_countAvailable: Intl API disabled");
-}
-
-static const char*
-unum_getAvailable(int32_t localeIndex)
-{
- MOZ_CRASH("unum_getAvailable: Intl API disabled");
-}
-
-static UNumberFormat*
-unum_open(UNumberFormatStyle style, const UChar* pattern, int32_t patternLength,
- const char* locale, UParseError* parseErr, UErrorCode* status)
-{
- MOZ_CRASH("unum_open: Intl API disabled");
-}
-
-static void
-unum_setAttribute(UNumberFormat* fmt, UNumberFormatAttribute attr, int32_t newValue)
-{
- MOZ_CRASH("unum_setAttribute: Intl API disabled");
-}
-
-static int32_t
-unum_formatDouble(const UNumberFormat* fmt, double number, UChar* result,
- int32_t resultLength, UFieldPosition* pos, UErrorCode* status)
-{
- MOZ_CRASH("unum_formatDouble: Intl API disabled");
-}
-
-static void
-unum_close(UNumberFormat* fmt)
-{
- MOZ_CRASH("unum_close: Intl API disabled");
-}
-
-static void
-unum_setTextAttribute(UNumberFormat* fmt, UNumberFormatTextAttribute tag, const UChar* newValue,
- int32_t newValueLength, UErrorCode* status)
-{
- MOZ_CRASH("unum_setTextAttribute: Intl API disabled");
-}
-
-typedef void* UNumberingSystem;
-
-static UNumberingSystem*
-unumsys_open(const char* locale, UErrorCode* status)
-{
- MOZ_CRASH("unumsys_open: Intl API disabled");
-}
-
-static const char*
-unumsys_getName(const UNumberingSystem* unumsys)
-{
- MOZ_CRASH("unumsys_getName: Intl API disabled");
-}
-
-static void
-unumsys_close(UNumberingSystem* unumsys)
-{
- MOZ_CRASH("unumsys_close: Intl API disabled");
-}
-
-typedef void* UCalendar;
-
-enum UCalendarType {
- UCAL_TRADITIONAL,
- UCAL_DEFAULT = UCAL_TRADITIONAL,
- UCAL_GREGORIAN
-};
-
-enum UCalendarAttribute {
- UCAL_FIRST_DAY_OF_WEEK,
- UCAL_MINIMAL_DAYS_IN_FIRST_WEEK
-};
-
-enum UCalendarDaysOfWeek {
- UCAL_SUNDAY,
- UCAL_MONDAY,
- UCAL_TUESDAY,
- UCAL_WEDNESDAY,
- UCAL_THURSDAY,
- UCAL_FRIDAY,
- UCAL_SATURDAY
-};
-
-enum UCalendarWeekdayType {
- UCAL_WEEKDAY,
- UCAL_WEEKEND,
- UCAL_WEEKEND_ONSET,
- UCAL_WEEKEND_CEASE
-};
-
-enum UCalendarDateFields {
- UCAL_ERA,
- UCAL_YEAR,
- UCAL_MONTH,
- UCAL_WEEK_OF_YEAR,
- UCAL_WEEK_OF_MONTH,
- UCAL_DATE,
- UCAL_DAY_OF_YEAR,
- UCAL_DAY_OF_WEEK,
- UCAL_DAY_OF_WEEK_IN_MONTH,
- UCAL_AM_PM,
- UCAL_HOUR,
- UCAL_HOUR_OF_DAY,
- UCAL_MINUTE,
- UCAL_SECOND,
- UCAL_MILLISECOND,
- UCAL_ZONE_OFFSET,
- UCAL_DST_OFFSET,
- UCAL_YEAR_WOY,
- UCAL_DOW_LOCAL,
- UCAL_EXTENDED_YEAR,
- UCAL_JULIAN_DAY,
- UCAL_MILLISECONDS_IN_DAY,
- UCAL_IS_LEAP_MONTH,
- UCAL_FIELD_COUNT,
- UCAL_DAY_OF_MONTH = UCAL_DATE
-};
-
-enum UCalendarMonths {
- UCAL_JANUARY,
- UCAL_FEBRUARY,
- UCAL_MARCH,
- UCAL_APRIL,
- UCAL_MAY,
- UCAL_JUNE,
- UCAL_JULY,
- UCAL_AUGUST,
- UCAL_SEPTEMBER,
- UCAL_OCTOBER,
- UCAL_NOVEMBER,
- UCAL_DECEMBER,
- UCAL_UNDECIMBER
-};
-
-enum UCalendarAMPMs {
- UCAL_AM,
- UCAL_PM
-};
-
-static UCalendar*
-ucal_open(const UChar* zoneID, int32_t len, const char* locale,
- UCalendarType type, UErrorCode* status)
-{
- MOZ_CRASH("ucal_open: Intl API disabled");
-}
-
-static const char*
-ucal_getType(const UCalendar* cal, UErrorCode* status)
-{
- MOZ_CRASH("ucal_getType: Intl API disabled");
-}
-
-static UEnumeration*
-ucal_getKeywordValuesForLocale(const char* key, const char* locale,
- UBool commonlyUsed, UErrorCode* status)
-{
- MOZ_CRASH("ucal_getKeywordValuesForLocale: Intl API disabled");
-}
-
-static void
-ucal_close(UCalendar* cal)
-{
- MOZ_CRASH("ucal_close: Intl API disabled");
-}
-
-static UCalendarWeekdayType
-ucal_getDayOfWeekType(const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode* status)
-{
- MOZ_CRASH("ucal_getDayOfWeekType: Intl API disabled");
-}
-
-static int32_t
-ucal_getAttribute(const UCalendar* cal,
- UCalendarAttribute attr)
-{
- MOZ_CRASH("ucal_getAttribute: Intl API disabled");
-}
-
-static int32_t
-ucal_get(const UCalendar *cal, UCalendarDateFields field, UErrorCode *status)
-{
- MOZ_CRASH("ucal_get: Intl API disabled");
-}
-
-static UEnumeration*
-ucal_openTimeZones(UErrorCode* status)
-{
- MOZ_CRASH("ucal_openTimeZones: Intl API disabled");
-}
-
-static int32_t
-ucal_getCanonicalTimeZoneID(const UChar* id, int32_t len, UChar* result, int32_t resultCapacity,
- UBool* isSystemID, UErrorCode* status)
-{
- MOZ_CRASH("ucal_getCanonicalTimeZoneID: Intl API disabled");
-}
-
-static int32_t
-ucal_getDefaultTimeZone(UChar* result, int32_t resultCapacity, UErrorCode* status)
-{
- MOZ_CRASH("ucal_getDefaultTimeZone: Intl API disabled");
-}
-
-enum UDateTimePatternField {
- UDATPG_YEAR_FIELD,
- UDATPG_MONTH_FIELD,
- UDATPG_WEEK_OF_YEAR_FIELD,
- UDATPG_DAY_FIELD,
-};
-
-typedef void* UDateTimePatternGenerator;
-
-static UDateTimePatternGenerator*
-udatpg_open(const char* locale, UErrorCode* pErrorCode)
-{
- MOZ_CRASH("udatpg_open: Intl API disabled");
-}
-
-static int32_t
-udatpg_getBestPattern(UDateTimePatternGenerator* dtpg, const UChar* skeleton,
- int32_t length, UChar* bestPattern, int32_t capacity,
- UErrorCode* pErrorCode)
-{
- MOZ_CRASH("udatpg_getBestPattern: Intl API disabled");
-}
-
-static const UChar *
-udatpg_getAppendItemName(const UDateTimePatternGenerator *dtpg,
- UDateTimePatternField field,
- int32_t *pLength)
-{
- MOZ_CRASH("udatpg_getAppendItemName: Intl API disabled");
-}
-
-static void
-udatpg_close(UDateTimePatternGenerator* dtpg)
-{
- MOZ_CRASH("udatpg_close: Intl API disabled");
-}
-
-typedef void* UCalendar;
-typedef void* UDateFormat;
-
-enum UDateFormatField {
- UDAT_ERA_FIELD = 0,
- UDAT_YEAR_FIELD = 1,
- UDAT_MONTH_FIELD = 2,
- UDAT_DATE_FIELD = 3,
- UDAT_HOUR_OF_DAY1_FIELD = 4,
- UDAT_HOUR_OF_DAY0_FIELD = 5,
- UDAT_MINUTE_FIELD = 6,
- UDAT_SECOND_FIELD = 7,
- UDAT_FRACTIONAL_SECOND_FIELD = 8,
- UDAT_DAY_OF_WEEK_FIELD = 9,
- UDAT_DAY_OF_YEAR_FIELD = 10,
- UDAT_DAY_OF_WEEK_IN_MONTH_FIELD = 11,
- UDAT_WEEK_OF_YEAR_FIELD = 12,
- UDAT_WEEK_OF_MONTH_FIELD = 13,
- UDAT_AM_PM_FIELD = 14,
- UDAT_HOUR1_FIELD = 15,
- UDAT_HOUR0_FIELD = 16,
- UDAT_TIMEZONE_FIELD = 17,
- UDAT_YEAR_WOY_FIELD = 18,
- UDAT_DOW_LOCAL_FIELD = 19,
- UDAT_EXTENDED_YEAR_FIELD = 20,
- UDAT_JULIAN_DAY_FIELD = 21,
- UDAT_MILLISECONDS_IN_DAY_FIELD = 22,
- UDAT_TIMEZONE_RFC_FIELD = 23,
- UDAT_TIMEZONE_GENERIC_FIELD = 24,
- UDAT_STANDALONE_DAY_FIELD = 25,
- UDAT_STANDALONE_MONTH_FIELD = 26,
- UDAT_QUARTER_FIELD = 27,
- UDAT_STANDALONE_QUARTER_FIELD = 28,
- UDAT_TIMEZONE_SPECIAL_FIELD = 29,
- UDAT_YEAR_NAME_FIELD = 30,
- UDAT_TIMEZONE_LOCALIZED_GMT_OFFSET_FIELD = 31,
- UDAT_TIMEZONE_ISO_FIELD = 32,
- UDAT_TIMEZONE_ISO_LOCAL_FIELD = 33,
- UDAT_RELATED_YEAR_FIELD = 34,
- UDAT_AM_PM_MIDNIGHT_NOON_FIELD = 35,
- UDAT_FLEXIBLE_DAY_PERIOD_FIELD = 36,
- UDAT_TIME_SEPARATOR_FIELD = 37,
- UDAT_FIELD_COUNT = 38
-};
-
-enum UDateFormatStyle {
- UDAT_FULL,
- UDAT_LONG,
- UDAT_MEDIUM,
- UDAT_SHORT,
- UDAT_DEFAULT = UDAT_MEDIUM,
- UDAT_PATTERN = -2,
- UDAT_IGNORE = UDAT_PATTERN
-};
-
-enum UDateFormatSymbolType {
- UDAT_ERAS,
- UDAT_MONTHS,
- UDAT_SHORT_MONTHS,
- UDAT_WEEKDAYS,
- UDAT_SHORT_WEEKDAYS,
- UDAT_AM_PMS,
- UDAT_LOCALIZED_CHARS,
- UDAT_ERA_NAMES,
- UDAT_NARROW_MONTHS,
- UDAT_NARROW_WEEKDAYS,
- UDAT_STANDALONE_MONTHS,
- UDAT_STANDALONE_SHORT_MONTHS,
- UDAT_STANDALONE_NARROW_MONTHS,
- UDAT_STANDALONE_WEEKDAYS,
- UDAT_STANDALONE_SHORT_WEEKDAYS,
- UDAT_STANDALONE_NARROW_WEEKDAYS,
- UDAT_QUARTERS,
- UDAT_SHORT_QUARTERS,
- UDAT_STANDALONE_QUARTERS,
- UDAT_STANDALONE_SHORT_QUARTERS,
- UDAT_SHORTER_WEEKDAYS,
- UDAT_STANDALONE_SHORTER_WEEKDAYS,
- UDAT_CYCLIC_YEARS_WIDE,
- UDAT_CYCLIC_YEARS_ABBREVIATED,
- UDAT_CYCLIC_YEARS_NARROW,
- UDAT_ZODIAC_NAMES_WIDE,
- UDAT_ZODIAC_NAMES_ABBREVIATED,
- UDAT_ZODIAC_NAMES_NARROW
-};
-
-static int32_t
-udat_countAvailable()
-{
- MOZ_CRASH("udat_countAvailable: Intl API disabled");
-}
-
-static const char*
-udat_getAvailable(int32_t localeIndex)
-{
- MOZ_CRASH("udat_getAvailable: Intl API disabled");
-}
-
-static UDateFormat*
-udat_open(UDateFormatStyle timeStyle, UDateFormatStyle dateStyle, const char* locale,
- const UChar* tzID, int32_t tzIDLength, const UChar* pattern,
- int32_t patternLength, UErrorCode* status)
-{
- MOZ_CRASH("udat_open: Intl API disabled");
-}
-
-static const UCalendar*
-udat_getCalendar(const UDateFormat* fmt)
-{
- MOZ_CRASH("udat_getCalendar: Intl API disabled");
-}
-
-static void
-ucal_setGregorianChange(UCalendar* cal, UDate date, UErrorCode* pErrorCode)
-{
- MOZ_CRASH("ucal_setGregorianChange: Intl API disabled");
-}
-
-static int32_t
-udat_format(const UDateFormat* format, UDate dateToFormat, UChar* result,
- int32_t resultLength, UFieldPosition* position, UErrorCode* status)
-{
- MOZ_CRASH("udat_format: Intl API disabled");
-}
-
-static int32_t
-udat_formatForFields(const UDateFormat* format, UDate dateToFormat,
- UChar* result, int32_t resultLength, UFieldPositionIterator* fpositer,
- UErrorCode* status)
-{
- MOZ_CRASH("udat_formatForFields: Intl API disabled");
-}
-
-static UFieldPositionIterator*
-ufieldpositer_open(UErrorCode* status)
-{
- MOZ_CRASH("ufieldpositer_open: Intl API disabled");
-}
-
-static void
-ufieldpositer_close(UFieldPositionIterator* fpositer)
-{
- MOZ_CRASH("ufieldpositer_close: Intl API disabled");
-}
-
-static int32_t
-ufieldpositer_next(UFieldPositionIterator* fpositer, int32_t* beginIndex, int32_t* endIndex)
-{
- MOZ_CRASH("ufieldpositer_next: Intl API disabled");
-}
-
-static void
-udat_close(UDateFormat* format)
-{
- MOZ_CRASH("udat_close: Intl API disabled");
-}
-
-static int32_t
-udat_getSymbols(const UDateFormat *fmt, UDateFormatSymbolType type, int32_t symbolIndex,
- UChar *result, int32_t resultLength, UErrorCode *status)
-{
- MOZ_CRASH("udat_getSymbols: Intl API disabled");
-}
-
-#endif
-
-
/******************** Common to Intl constructors ********************/
static bool
@@ -706,7 +107,6 @@ intl_availableLocales(JSContext* cx, CountAvailable countAvailable,
if (!locales)
return false;
-#if ENABLE_INTL_API
uint32_t count = countAvailable();
RootedValue t(cx, BooleanValue(true));
for (uint32_t i = 0; i < count; i++) {
@@ -726,7 +126,7 @@ intl_availableLocales(JSContext* cx, CountAvailable countAvailable,
return false;
}
}
-#endif
+
result.setObject(*locales);
return true;
}
diff --git a/js/src/builtin/Intl.h b/js/src/builtin/Intl.h
index b2197060d..9a1e44913 100644
--- a/js/src/builtin/Intl.h
+++ b/js/src/builtin/Intl.h
@@ -16,9 +16,7 @@
#include "js/GCAPI.h"
#include "js/GCHashTable.h"
-#if ENABLE_INTL_API
#include "unicode/utypes.h"
-#endif
/*
* The Intl module specified by standard ECMA-402,
@@ -429,7 +427,6 @@ intl_GetCalendarInfo(JSContext* cx, unsigned argc, Value* vp);
extern MOZ_MUST_USE bool
intl_ComputeDisplayNames(JSContext* cx, unsigned argc, Value* vp);
-#if ENABLE_INTL_API
/**
* Cast char16_t* strings to UChar* strings used by ICU.
*/
@@ -456,7 +453,6 @@ UCharToChar16(const UChar* chars)
{
return reinterpret_cast<const char16_t*>(chars);
}
-#endif // ENABLE_INTL_API
} // namespace js
diff --git a/js/src/builtin/Intl.js b/js/src/builtin/Intl.js
index 509168d7a..6391c3e70 100644
--- a/js/src/builtin/Intl.js
+++ b/js/src/builtin/Intl.js
@@ -9,7 +9,8 @@
JSMSG_INVALID_OPTION_VALUE: false, JSMSG_INVALID_DIGITS_VALUE: false,
JSMSG_INTL_OBJECT_REINITED: false, JSMSG_INVALID_CURRENCY_CODE: false,
JSMSG_UNDEFINED_CURRENCY: false, JSMSG_INVALID_TIME_ZONE: false,
- JSMSG_DATE_NOT_FINITE: false,
+ JSMSG_DATE_NOT_FINITE: false, JSMSG_INVALID_KEYS_TYPE: false,
+ JSMSG_INVALID_KEY: false,
intl_Collator_availableLocales: false,
intl_availableCollations: false,
intl_CompareStrings: false,
@@ -3024,3 +3025,126 @@ function Intl_getCalendarInfo(locales) {
return result;
}
+
+/**
+ * This function is a custom method designed after Intl API, but currently
+ * not part of the spec or spec proposal.
+ * We want to use it internally to retrieve translated values from CLDR in
+ * order to ensure they're aligned with what Intl API returns.
+ *
+ * This API may one day be a foundation for an ECMA402 API spec proposal.
+ *
+ * The function takes two arguments - locales which is a list of locale strings
+ * and options which is an object with two optional properties:
+ *
+ * keys:
+ * an Array of string values that are paths to individual terms
+ *
+ * style:
+ * a String with a value "long", "short" or "narrow"
+ *
+ * It returns an object with properties:
+ *
+ * locale:
+ * a negotiated locale string
+ *
+ * style:
+ * negotiated style
+ *
+ * values:
+ * A key-value pair list of requested keys and corresponding
+ * translated values
+ *
+ */
+function Intl_getDisplayNames(locales, options) {
+ // 1. Let requestLocales be ? CanonicalizeLocaleList(locales).
+ const requestedLocales = CanonicalizeLocaleList(locales);
+
+ // 2. If options is undefined, then
+ if (options === undefined)
+ // a. Let options be ObjectCreate(%ObjectPrototype%).
+ options = {};
+ // 3. Else,
+ else
+ // a. Let options be ? ToObject(options).
+ options = ToObject(options);
+
+ const DateTimeFormat = dateTimeFormatInternalProperties;
+
+ // 4. Let localeData be %DateTimeFormat%.[[localeData]].
+ const localeData = DateTimeFormat.localeData;
+
+ // 5. Let opt be a new Record.
+ const localeOpt = new Record();
+ // 6. Set localeOpt.[[localeMatcher]] to "best fit".
+ localeOpt.localeMatcher = "best fit";
+
+ // 7. Let r be ResolveLocale(%DateTimeFormat%.[[availableLocales]], requestedLocales, localeOpt,
+ // %DateTimeFormat%.[[relevantExtensionKeys]], localeData).
+ const r = ResolveLocale(callFunction(DateTimeFormat.availableLocales, DateTimeFormat),
+ requestedLocales,
+ localeOpt,
+ DateTimeFormat.relevantExtensionKeys,
+ localeData);
+
+ // 8. Let style be ? GetOption(options, "style", "string", « "long", "short", "narrow" », "long").
+ const style = GetOption(options, "style", "string", ["long", "short", "narrow"], "long");
+ // 9. Let keys be ? Get(options, "keys").
+ let keys = options.keys;
+
+ // 10. If keys is undefined,
+ if (keys === undefined) {
+ // a. Let keys be ArrayCreate(0).
+ keys = [];
+ } else if (!IsObject(keys)) {
+ // 11. Else,
+ // a. If Type(keys) is not Object, throw a TypeError exception.
+ ThrowTypeError(JSMSG_INVALID_KEYS_TYPE);
+ }
+
+ // 12. Let processedKeys be ArrayCreate(0).
+ // (This really should be a List, but we use an Array here in order that
+ // |intl_ComputeDisplayNames| may infallibly access the list's length via
+ // |ArrayObject::length|.)
+ let processedKeys = [];
+ // 13. Let len be ? ToLength(? Get(keys, "length")).
+ let len = ToLength(keys.length);
+ // 14. Let i be 0.
+ // 15. Repeat, while i < len
+ for (let i = 0; i < len; i++) {
+ // a. Let processedKey be ? ToString(? Get(keys, i)).
+ // b. Perform ? CreateDataPropertyOrThrow(processedKeys, i, processedKey).
+ callFunction(std_Array_push, processedKeys, ToString(keys[i]));
+ }
+
+ // 16. Let names be ? ComputeDisplayNames(r.[[locale]], style, processedKeys).
+ const names = intl_ComputeDisplayNames(r.locale, style, processedKeys);
+
+ // 17. Let values be ObjectCreate(%ObjectPrototype%).
+ const values = {};
+
+ // 18. Set i to 0.
+ // 19. Repeat, while i < len
+ for (let i = 0; i < len; i++) {
+ // a. Let key be ? Get(processedKeys, i).
+ const key = processedKeys[i];
+ // b. Let name be ? Get(names, i).
+ const name = names[i];
+ // c. Assert: Type(name) is string.
+ assert(typeof name === "string", "unexpected non-string value");
+ // d. Assert: the length of name is greater than zero.
+ assert(name.length > 0, "empty string value");
+ // e. Perform ? DefinePropertyOrThrow(values, key, name).
+ _DefineDataProperty(values, key, name);
+ }
+
+ // 20. Let options be ObjectCreate(%ObjectPrototype%).
+ // 21. Perform ! DefinePropertyOrThrow(result, "locale", r.[[locale]]).
+ // 22. Perform ! DefinePropertyOrThrow(result, "style", style).
+ // 23. Perform ! DefinePropertyOrThrow(result, "values", values).
+ const result = { locale: r.locale, style, values };
+
+ // 24. Return result.
+ return result;
+
+}
diff --git a/js/src/builtin/String.js b/js/src/builtin/String.js
index 4202d0de6..6d1d335a0 100644
--- a/js/src/builtin/String.js
+++ b/js/src/builtin/String.js
@@ -659,11 +659,7 @@ function String_static_localeCompare(str1, str2) {
ThrowTypeError(JSMSG_MISSING_FUN_ARG, 0, "String.localeCompare");
var locales = arguments.length > 2 ? arguments[2] : undefined;
var options = arguments.length > 3 ? arguments[3] : undefined;
-#if EXPOSE_INTL_API
return callFunction(String_localeCompare, str1, str2, locales, options);
-#else
- return callFunction(std_String_localeCompare, str1, str2, locales, options);
-#endif
}
// ES6 draft 2014-04-27 B.2.3.3
@@ -855,14 +851,12 @@ function String_static_toLocaleUpperCase(string) {
return callFunction(std_String_toLocaleUpperCase, string);
}
-#if EXPOSE_INTL_API
function String_static_normalize(string) {
if (arguments.length < 1)
ThrowTypeError(JSMSG_MISSING_FUN_ARG, 0, 'String.normalize');
var form = arguments.length > 1 ? arguments[1] : undefined;
return callFunction(std_String_normalize, string, form);
}
-#endif
function String_static_concat(string, arg1) {
if (arguments.length < 1)
diff --git a/js/src/builtin/TestingFunctions.cpp b/js/src/builtin/TestingFunctions.cpp
index a14f9ba69..00637a7a5 100644
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -236,11 +236,7 @@ GetBuildConfiguration(JSContext* cx, unsigned argc, Value* vp)
if (!JS_SetProperty(cx, info, "binary-data", value))
return false;
-#ifdef EXPOSE_INTL_API
value = BooleanValue(true);
-#else
- value = BooleanValue(false);
-#endif
if (!JS_SetProperty(cx, info, "intl-api", value))
return false;
diff --git a/js/src/builtin/TypedArray.js b/js/src/builtin/TypedArray.js
index a2205dc92..a1934051d 100644
--- a/js/src/builtin/TypedArray.js
+++ b/js/src/builtin/TypedArray.js
@@ -1232,11 +1232,7 @@ function TypedArrayToLocaleString(locales = undefined, options = undefined) {
// Steps 6-7.
// Omit the 'if' clause in step 6, since typed arrays can't have undefined
// or null elements.
-#if EXPOSE_INTL_API
var R = ToString(callContentFunction(firstElement.toLocaleString, firstElement, locales, options));
-#else
- var R = ToString(callContentFunction(firstElement.toLocaleString, firstElement));
-#endif
// Step 3 (reordered).
// We don't (yet?) implement locale-dependent separators.
@@ -1258,11 +1254,7 @@ function TypedArrayToLocaleString(locales = undefined, options = undefined) {
// the error message. So despite bug 1079853, we can skip step 9.c.
// Step 9.d.
-#if EXPOSE_INTL_API
R = ToString(callContentFunction(nextElement.toLocaleString, nextElement, locales, options));
-#else
- R = ToString(callContentFunction(nextElement.toLocaleString, nextElement));
-#endif
// Step 9.e.
R = S + R;
diff --git a/js/src/gdb/moz.build b/js/src/gdb/moz.build
index 681f9807c..faa69eb7b 100644
--- a/js/src/gdb/moz.build
+++ b/js/src/gdb/moz.build
@@ -34,7 +34,7 @@ USE_LIBS += [
'static:js',
]
-if CONFIG['ENABLE_INTL_API'] and CONFIG['MOZ_ICU_DATA_ARCHIVE']:
+if CONFIG['MOZ_ICU_DATA_ARCHIVE']:
# The ICU libraries linked into libmozjs will not include the ICU data,
# so link it directly.
USE_LIBS += ['icudata']
diff --git a/js/src/jit/BaselineFrameInfo.h b/js/src/jit/BaselineFrameInfo.h
index 13bf0358d..1691270ac 100644
--- a/js/src/jit/BaselineFrameInfo.h
+++ b/js/src/jit/BaselineFrameInfo.h
@@ -67,7 +67,7 @@ class StackValue
union {
struct {
- Value v;
+ JS::UninitializedValue v;
} constant;
struct {
mozilla::AlignedStorage2<ValueOperand> reg;
@@ -112,7 +112,7 @@ class StackValue
}
Value constant() const {
MOZ_ASSERT(kind_ == Constant);
- return data.constant.v;
+ return data.constant.v.asValueRef();
}
ValueOperand reg() const {
MOZ_ASSERT(kind_ == Register);
diff --git a/js/src/jit/RegisterSets.h b/js/src/jit/RegisterSets.h
index 0a4045dd7..08ae53f16 100644
--- a/js/src/jit/RegisterSets.h
+++ b/js/src/jit/RegisterSets.h
@@ -226,13 +226,13 @@ class ConstantOrRegister
// Space to hold either a Value or a TypedOrValueRegister.
union U {
- Value constant;
+ JS::UninitializedValue constant;
TypedOrValueRegister reg;
} data;
- const Value& dataValue() const {
+ Value dataValue() const {
MOZ_ASSERT(constant());
- return data.constant;
+ return data.constant.asValueRef();
}
void setDataValue(const Value& value) {
MOZ_ASSERT(constant());
@@ -268,7 +268,7 @@ class ConstantOrRegister
return constant_;
}
- const Value& value() const {
+ Value value() const {
return dataValue();
}
diff --git a/js/src/jit/RematerializedFrame.cpp b/js/src/jit/RematerializedFrame.cpp
index cb324220c..32fad1267 100644
--- a/js/src/jit/RematerializedFrame.cpp
+++ b/js/src/jit/RematerializedFrame.cpp
@@ -61,9 +61,17 @@ RematerializedFrame::New(JSContext* cx, uint8_t* top, InlineFrameIterator& iter,
{
unsigned numFormals = iter.isFunctionFrame() ? iter.calleeTemplate()->nargs() : 0;
unsigned argSlots = Max(numFormals, iter.numActualArgs());
- size_t numBytes = sizeof(RematerializedFrame) +
- (argSlots + iter.script()->nfixed()) * sizeof(Value) -
- sizeof(Value); // 1 Value included in sizeof(RematerializedFrame)
+ unsigned extraSlots = argSlots + iter.script()->nfixed();
+
+ // One Value slot is included in sizeof(RematerializedFrame), so we can
+ // reduce the extra slot count by one. However, if there are zero slot
+ // allocations total, then reducing the slots by one will lead to
+ // the memory allocation being smaller than sizeof(RematerializedFrame).
+ if (extraSlots > 0)
+ extraSlots -= 1;
+
+ size_t numBytes = sizeof(RematerializedFrame) + (extraSlots * sizeof(Value));
+ MOZ_ASSERT(numBytes >= sizeof(RematerializedFrame));
void* buf = cx->pod_calloc<uint8_t>(numBytes);
if (!buf)
diff --git a/js/src/jsapi-tests/moz.build b/js/src/jsapi-tests/moz.build
index f7a6080aa..277a145b0 100644
--- a/js/src/jsapi-tests/moz.build
+++ b/js/src/jsapi-tests/moz.build
@@ -135,7 +135,7 @@ LOCAL_INCLUDES += [
'..',
]
-if CONFIG['ENABLE_INTL_API'] and CONFIG['MOZ_ICU_DATA_ARCHIVE']:
+if CONFIG['MOZ_ICU_DATA_ARCHIVE']:
# The ICU libraries linked into libmozjs will not include the ICU data,
# so link it directly.
USE_LIBS += ['icudata']
diff --git a/js/src/jsapi.h b/js/src/jsapi.h
index 989abe47c..c1195cc00 100644
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -5222,7 +5222,7 @@ JS_ResetDefaultLocale(JSContext* cx);
struct JSLocaleCallbacks {
JSLocaleToUpperCase localeToUpperCase;
JSLocaleToLowerCase localeToLowerCase;
- JSLocaleCompare localeCompare; // not used #if EXPOSE_INTL_API
+ JSLocaleCompare localeCompare; // not used
JSLocaleToUnicode localeToUnicode;
};
diff --git a/js/src/jsdate.cpp b/js/src/jsdate.cpp
index 00a8abf84..52294a5df 100755
--- a/js/src/jsdate.cpp
+++ b/js/src/jsdate.cpp
@@ -2743,77 +2743,6 @@ ToLocaleFormatHelper(JSContext* cx, HandleObject obj, const char* format, Mutabl
return true;
}
-#if !EXPOSE_INTL_API
-/* ES5 15.9.5.5. */
-MOZ_ALWAYS_INLINE bool
-date_toLocaleString_impl(JSContext* cx, const CallArgs& args)
-{
- /*
- * Use '%#c' for windows, because '%c' is backward-compatible and non-y2k
- * with msvc; '%#c' requests that a full year be used in the result string.
- */
- static const char format[] =
-#if defined(_WIN32) && !defined(__MWERKS__)
- "%#c"
-#else
- "%c"
-#endif
- ;
-
- Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
- return ToLocaleFormatHelper(cx, dateObj, format, args.rval());
-}
-
-static bool
-date_toLocaleString(JSContext* cx, unsigned argc, Value* vp)
-{
- CallArgs args = CallArgsFromVp(argc, vp);
- return CallNonGenericMethod<IsDate, date_toLocaleString_impl>(cx, args);
-}
-
-/* ES5 15.9.5.6. */
-MOZ_ALWAYS_INLINE bool
-date_toLocaleDateString_impl(JSContext* cx, const CallArgs& args)
-{
- /*
- * Use '%#x' for windows, because '%x' is backward-compatible and non-y2k
- * with msvc; '%#x' requests that a full year be used in the result string.
- */
- static const char format[] =
-#if defined(_WIN32) && !defined(__MWERKS__)
- "%#x"
-#else
- "%x"
-#endif
- ;
-
- Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
- return ToLocaleFormatHelper(cx, dateObj, format, args.rval());
-}
-
-static bool
-date_toLocaleDateString(JSContext* cx, unsigned argc, Value* vp)
-{
- CallArgs args = CallArgsFromVp(argc, vp);
- return CallNonGenericMethod<IsDate, date_toLocaleDateString_impl>(cx, args);
-}
-
-/* ES5 15.9.5.7. */
-MOZ_ALWAYS_INLINE bool
-date_toLocaleTimeString_impl(JSContext* cx, const CallArgs& args)
-{
- Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
- return ToLocaleFormatHelper(cx, dateObj, "%X", args.rval());
-}
-
-static bool
-date_toLocaleTimeString(JSContext* cx, unsigned argc, Value* vp)
-{
- CallArgs args = CallArgsFromVp(argc, vp);
- return CallNonGenericMethod<IsDate, date_toLocaleTimeString_impl>(cx, args);
-}
-#endif /* !EXPOSE_INTL_API */
-
MOZ_ALWAYS_INLINE bool
date_toLocaleFormat_impl(JSContext* cx, const CallArgs& args)
{
@@ -3037,15 +2966,9 @@ static const JSFunctionSpec date_methods[] = {
JS_FN("setUTCMilliseconds", date_setUTCMilliseconds, 1,0),
JS_FN("toUTCString", date_toGMTString, 0,0),
JS_FN("toLocaleFormat", date_toLocaleFormat, 0,0),
-#if EXPOSE_INTL_API
JS_SELF_HOSTED_FN(js_toLocaleString_str, "Date_toLocaleString", 0,0),
JS_SELF_HOSTED_FN("toLocaleDateString", "Date_toLocaleDateString", 0,0),
JS_SELF_HOSTED_FN("toLocaleTimeString", "Date_toLocaleTimeString", 0,0),
-#else
- JS_FN(js_toLocaleString_str, date_toLocaleString, 0,0),
- JS_FN("toLocaleDateString", date_toLocaleDateString, 0,0),
- JS_FN("toLocaleTimeString", date_toLocaleTimeString, 0,0),
-#endif
JS_FN("toDateString", date_toDateString, 0,0),
JS_FN("toTimeString", date_toTimeString, 0,0),
JS_FN("toISOString", date_toISOString, 0,0),
diff --git a/js/src/jsnum.cpp b/js/src/jsnum.cpp
index 8885737f7..28ed15159 100644
--- a/js/src/jsnum.cpp
+++ b/js/src/jsnum.cpp
@@ -724,141 +724,6 @@ js::num_toString(JSContext* cx, unsigned argc, Value* vp)
return CallNonGenericMethod<IsNumber, num_toString_impl>(cx, args);
}
-#if !EXPOSE_INTL_API
-MOZ_ALWAYS_INLINE bool
-num_toLocaleString_impl(JSContext* cx, const CallArgs& args)
-{
- MOZ_ASSERT(IsNumber(args.thisv()));
-
- double d = Extract(args.thisv());
-
- RootedString str(cx, NumberToStringWithBase<CanGC>(cx, d, 10));
- if (!str) {
- JS_ReportOutOfMemory(cx);
- return false;
- }
-
- /*
- * Create the string, move back to bytes to make string twiddling
- * a bit easier and so we can insert platform charset seperators.
- */
- JSAutoByteString numBytes(cx, str);
- if (!numBytes)
- return false;
- const char* num = numBytes.ptr();
- if (!num)
- return false;
-
- /*
- * Find the first non-integer value, whether it be a letter as in
- * 'Infinity', a decimal point, or an 'e' from exponential notation.
- */
- const char* nint = num;
- if (*nint == '-')
- nint++;
- while (*nint >= '0' && *nint <= '9')
- nint++;
- int digits = nint - num;
- const char* end = num + digits;
- if (!digits) {
- args.rval().setString(str);
- return true;
- }
-
- JSRuntime* rt = cx->runtime();
- size_t thousandsLength = strlen(rt->thousandsSeparator);
- size_t decimalLength = strlen(rt->decimalSeparator);
-
- /* Figure out how long resulting string will be. */
- int buflen = strlen(num);
- if (*nint == '.')
- buflen += decimalLength - 1; /* -1 to account for existing '.' */
-
- const char* numGrouping;
- const char* tmpGroup;
- numGrouping = tmpGroup = rt->numGrouping;
- int remainder = digits;
- if (*num == '-')
- remainder--;
-
- while (*tmpGroup != CHAR_MAX && *tmpGroup != '\0') {
- if (*tmpGroup >= remainder)
- break;
- buflen += thousandsLength;
- remainder -= *tmpGroup;
- tmpGroup++;
- }
-
- int nrepeat;
- if (*tmpGroup == '\0' && *numGrouping != '\0') {
- nrepeat = (remainder - 1) / tmpGroup[-1];
- buflen += thousandsLength * nrepeat;
- remainder -= nrepeat * tmpGroup[-1];
- } else {
- nrepeat = 0;
- }
- tmpGroup--;
-
- char* buf = cx->pod_malloc<char>(buflen + 1);
- if (!buf)
- return false;
-
- char* tmpDest = buf;
- const char* tmpSrc = num;
-
- while (*tmpSrc == '-' || remainder--) {
- MOZ_ASSERT(tmpDest - buf < buflen);
- *tmpDest++ = *tmpSrc++;
- }
- while (tmpSrc < end) {
- MOZ_ASSERT(tmpDest - buf + ptrdiff_t(thousandsLength) <= buflen);
- strcpy(tmpDest, rt->thousandsSeparator);
- tmpDest += thousandsLength;
- MOZ_ASSERT(tmpDest - buf + *tmpGroup <= buflen);
- js_memcpy(tmpDest, tmpSrc, *tmpGroup);
- tmpDest += *tmpGroup;
- tmpSrc += *tmpGroup;
- if (--nrepeat < 0)
- tmpGroup--;
- }
-
- if (*nint == '.') {
- MOZ_ASSERT(tmpDest - buf + ptrdiff_t(decimalLength) <= buflen);
- strcpy(tmpDest, rt->decimalSeparator);
- tmpDest += decimalLength;
- MOZ_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint + 1)) <= buflen);
- strcpy(tmpDest, nint + 1);
- } else {
- MOZ_ASSERT(tmpDest - buf + ptrdiff_t(strlen(nint)) <= buflen);
- strcpy(tmpDest, nint);
- }
-
- if (cx->runtime()->localeCallbacks && cx->runtime()->localeCallbacks->localeToUnicode) {
- Rooted<Value> v(cx, StringValue(str));
- bool ok = !!cx->runtime()->localeCallbacks->localeToUnicode(cx, buf, &v);
- if (ok)
- args.rval().set(v);
- js_free(buf);
- return ok;
- }
-
- str = NewStringCopyN<CanGC>(cx, buf, buflen);
- js_free(buf);
- if (!str)
- return false;
-
- args.rval().setString(str);
- return true;
-}
-
-static bool
-num_toLocaleString(JSContext* cx, unsigned argc, Value* vp)
-{
- CallArgs args = CallArgsFromVp(argc, vp);
- return CallNonGenericMethod<IsNumber, num_toLocaleString_impl>(cx, args);
-}
-#endif /* !EXPOSE_INTL_API */
-
MOZ_ALWAYS_INLINE bool
num_valueOf_impl(JSContext* cx, const CallArgs& args)
{
@@ -1075,11 +940,7 @@ static const JSFunctionSpec number_methods[] = {
JS_FN(js_toSource_str, num_toSource, 0, 0),
#endif
JS_FN(js_toString_str, num_toString, 1, 0),
-#if EXPOSE_INTL_API
JS_SELF_HOSTED_FN(js_toLocaleString_str, "Number_toLocaleString", 0,0),
-#else
- JS_FN(js_toLocaleString_str, num_toLocaleString, 0,0),
-#endif
JS_FN(js_valueOf_str, num_valueOf, 0, 0),
JS_FN("toFixed", num_toFixed, 1, 0),
JS_FN("toExponential", num_toExponential, 1, 0),
@@ -1130,76 +991,11 @@ js::FIX_FPU()
#endif
}
-bool
+void
js::InitRuntimeNumberState(JSRuntime* rt)
{
FIX_FPU();
-
- // XXX If EXPOSE_INTL_API becomes true all the time at some point,
- // js::InitRuntimeNumberState is no longer fallible, and we should
- // change its return type.
-#if !EXPOSE_INTL_API
- /* Copy locale-specific separators into the runtime strings. */
- const char* thousandsSeparator;
- const char* decimalPoint;
- const char* grouping;
-#ifdef HAVE_LOCALECONV
- struct lconv* locale = localeconv();
- thousandsSeparator = locale->thousands_sep;
- decimalPoint = locale->decimal_point;
- grouping = locale->grouping;
-#else
- thousandsSeparator = getenv("LOCALE_THOUSANDS_SEP");
- decimalPoint = getenv("LOCALE_DECIMAL_POINT");
- grouping = getenv("LOCALE_GROUPING");
-#endif
- if (!thousandsSeparator)
- thousandsSeparator = "'";
- if (!decimalPoint)
- decimalPoint = ".";
- if (!grouping)
- grouping = "\3\0";
-
- /*
- * We use single malloc to get the memory for all separator and grouping
- * strings.
- */
- size_t thousandsSeparatorSize = strlen(thousandsSeparator) + 1;
- size_t decimalPointSize = strlen(decimalPoint) + 1;
- size_t groupingSize = strlen(grouping) + 1;
-
- char* storage = js_pod_malloc<char>(thousandsSeparatorSize +
- decimalPointSize +
- groupingSize);
- if (!storage)
- return false;
-
- js_memcpy(storage, thousandsSeparator, thousandsSeparatorSize);
- rt->thousandsSeparator = storage;
- storage += thousandsSeparatorSize;
-
- js_memcpy(storage, decimalPoint, decimalPointSize);
- rt->decimalSeparator = storage;
- storage += decimalPointSize;
-
- js_memcpy(storage, grouping, groupingSize);
- rt->numGrouping = grouping;
-#endif /* !EXPOSE_INTL_API */
- return true;
-}
-
-#if !EXPOSE_INTL_API
-void
-js::FinishRuntimeNumberState(JSRuntime* rt)
-{
- /*
- * The free also releases the memory for decimalSeparator and numGrouping
- * strings.
- */
- char* storage = const_cast<char*>(rt->thousandsSeparator);
- js_free(storage);
}
-#endif
JSObject*
js::InitNumberClass(JSContext* cx, HandleObject obj)
diff --git a/js/src/jsnum.h b/js/src/jsnum.h
index 62b3d617f..8dff45f69 100644
--- a/js/src/jsnum.h
+++ b/js/src/jsnum.h
@@ -34,13 +34,7 @@ namespace js {
class StringBuffer;
-extern MOZ_MUST_USE bool
-InitRuntimeNumberState(JSRuntime* rt);
-
-#if !EXPOSE_INTL_API
-extern void
-FinishRuntimeNumberState(JSRuntime* rt);
-#endif
+void InitRuntimeNumberState(JSRuntime* rt);
/* Initialize the Number class, returning its prototype object. */
extern JSObject*
diff --git a/js/src/jsprototypes.h b/js/src/jsprototypes.h
index f409dce95..dc7cdb85a 100644
--- a/js/src/jsprototypes.h
+++ b/js/src/jsprototypes.h
@@ -37,11 +37,7 @@
#define TYPED_ARRAY_CLASP(type) (&TypedArrayObject::classes[Scalar::type])
#define ERROR_CLASP(type) (&ErrorObject::classes[type])
-#ifdef EXPOSE_INTL_API
#define IF_INTL(real,imaginary) real
-#else
-#define IF_INTL(real,imaginary) imaginary
-#endif
#ifdef ENABLE_BINARYDATA
#define IF_BDATA(real,imaginary) real
diff --git a/js/src/jsstr.cpp b/js/src/jsstr.cpp
index 7adeed620..01b407626 100644
--- a/js/src/jsstr.cpp
+++ b/js/src/jsstr.cpp
@@ -36,9 +36,7 @@
#include "jit/InlinableNatives.h"
#include "js/Conversions.h"
#include "js/UniquePtr.h"
-#if ENABLE_INTL_API
#include "unicode/unorm.h"
-#endif
#include "vm/GlobalObject.h"
#include "vm/Interpreter.h"
#include "vm/Opcodes.h"
@@ -899,38 +897,6 @@ js::str_toLocaleUpperCase(JSContext* cx, unsigned argc, Value* vp)
return ToUpperCaseHelper(cx, args);
}
-#if !EXPOSE_INTL_API
-bool
-js::str_localeCompare(JSContext* cx, unsigned argc, Value* vp)
-{
- CallArgs args = CallArgsFromVp(argc, vp);
- RootedString str(cx, ToStringForStringFunction(cx, args.thisv()));
- if (!str)
- return false;
-
- RootedString thatStr(cx, ToString<CanGC>(cx, args.get(0)));
- if (!thatStr)
- return false;
-
- if (cx->runtime()->localeCallbacks && cx->runtime()->localeCallbacks->localeCompare) {
- RootedValue result(cx);
- if (!cx->runtime()->localeCallbacks->localeCompare(cx, str, thatStr, &result))
- return false;
-
- args.rval().set(result);
- return true;
- }
-
- int32_t result;
- if (!CompareStrings(cx, str, thatStr, &result))
- return false;
-
- args.rval().setInt32(result);
- return true;
-}
-#endif
-
-#if EXPOSE_INTL_API
/* ES6 20140210 draft 21.1.3.12. */
bool
js::str_normalize(JSContext* cx, unsigned argc, Value* vp)
@@ -1007,7 +973,6 @@ js::str_normalize(JSContext* cx, unsigned argc, Value* vp)
args.rval().setString(ns);
return true;
}
-#endif
bool
js::str_charAt(JSContext* cx, unsigned argc, Value* vp)
@@ -2599,15 +2564,9 @@ static const JSFunctionSpec string_methods[] = {
JS_FN("trimRight", str_trimRight, 0,0),
JS_FN("toLocaleLowerCase", str_toLocaleLowerCase, 0,0),
JS_FN("toLocaleUpperCase", str_toLocaleUpperCase, 0,0),
-#if EXPOSE_INTL_API
JS_SELF_HOSTED_FN("localeCompare", "String_localeCompare", 1,0),
-#else
- JS_FN("localeCompare", str_localeCompare, 1,0),
-#endif
JS_SELF_HOSTED_FN("repeat", "String_repeat", 1,0),
-#if EXPOSE_INTL_API
JS_FN("normalize", str_normalize, 0,0),
-#endif
/* Perl-ish methods (search is actually Python-esque). */
JS_SELF_HOSTED_FN("match", "String_match", 1,0),
@@ -2918,9 +2877,7 @@ static const JSFunctionSpec string_static_methods[] = {
JS_SELF_HOSTED_FN("trimRight", "String_static_trimRight", 1,0),
JS_SELF_HOSTED_FN("toLocaleLowerCase","String_static_toLocaleLowerCase",1,0),
JS_SELF_HOSTED_FN("toLocaleUpperCase","String_static_toLocaleUpperCase",1,0),
-#if EXPOSE_INTL_API
JS_SELF_HOSTED_FN("normalize", "String_static_normalize", 1,0),
-#endif
JS_SELF_HOSTED_FN("concat", "String_static_concat", 2,0),
JS_SELF_HOSTED_FN("localeCompare", "String_static_localeCompare", 2,0),
diff --git a/js/src/jsstr.h b/js/src/jsstr.h
index 3b92aa21b..118118839 100644
--- a/js/src/jsstr.h
+++ b/js/src/jsstr.h
@@ -9,6 +9,7 @@
#include "mozilla/HashFunctions.h"
#include "mozilla/PodOperations.h"
+#include "mozilla/TextUtils.h"
#include <stdio.h>
@@ -95,7 +96,7 @@ struct JSSubString {
#define JS7_UNOCT(c) (JS7_UNDEC(c))
#define JS7_ISHEX(c) ((c) < 128 && isxdigit(c))
#define JS7_UNHEX(c) (unsigned)(JS7_ISDEC(c) ? (c) - '0' : 10 + tolower(c) - 'a')
-#define JS7_ISLET(c) ((c) < 128 && isalpha(c))
+#define JS7_ISLET(c) (mozilla::IsAsciiAlpha(c))
extern size_t
js_strlen(const char16_t* s);
@@ -377,13 +378,8 @@ str_toLocaleLowerCase(JSContext* cx, unsigned argc, Value* vp);
extern bool
str_toLocaleUpperCase(JSContext* cx, unsigned argc, Value* vp);
-#if !EXPOSE_INTL_API
-extern bool
-str_localeCompare(JSContext* cx, unsigned argc, Value* vp);
-#else
extern bool
str_normalize(JSContext* cx, unsigned argc, Value* vp);
-#endif
extern bool
str_concat(JSContext* cx, unsigned argc, Value* vp);
diff --git a/js/src/make-source-package.sh b/js/src/make-source-package.sh
index 6e44dd977..e6d3f6df5 100755
--- a/js/src/make-source-package.sh
+++ b/js/src/make-source-package.sh
@@ -151,7 +151,6 @@ case $cmd in
${TOPSRCDIR}/memory/moz.build \
${TOPSRCDIR}/memory/build \
${TOPSRCDIR}/memory/fallible \
- ${TOPSRCDIR}/memory/jemalloc \
${TOPSRCDIR}/memory/mozalloc \
${TOPSRCDIR}/memory/mozjemalloc \
${tgtpath}/memory
diff --git a/js/src/moz.build b/js/src/moz.build
index 2d4e83db3..a3283b5d6 100644
--- a/js/src/moz.build
+++ b/js/src/moz.build
@@ -645,18 +645,17 @@ else:
FORCE_STATIC_LIB = True
STATIC_LIBRARY_NAME = 'js_static'
-if CONFIG['ENABLE_INTL_API']:
- if not CONFIG['MOZ_ICU_DATA_ARCHIVE']:
- USE_LIBS += [
- 'icu',
- ]
- else:
- # Linking 'icu' will pull in the stubdata library,
- # which the shell doesn't want, so link the other bits.
- USE_LIBS += [
- 'icui18n',
- 'icuuc',
- ]
+if not CONFIG['MOZ_ICU_DATA_ARCHIVE']:
+ USE_LIBS += [
+ 'icu',
+ ]
+else:
+ # Linking 'icu' will pull in the stubdata library,
+ # which the shell doesn't want, so link the other bits.
+ USE_LIBS += [
+ 'icui18n',
+ 'icuuc',
+ ]
USE_LIBS += [
'nspr',
diff --git a/js/src/old-configure.in b/js/src/old-configure.in
index 1736cc5d4..8abea5956 100644
--- a/js/src/old-configure.in
+++ b/js/src/old-configure.in
@@ -734,12 +734,14 @@ case "$target" in
dnl VS2012+ defaults to -arch:SSE2. We want to target nothing
dnl more recent, so set that explicitly here unless another
dnl target arch has already been set.
+ changequote(,)
if test -z `echo $CFLAGS | grep -i [-/]arch:` ; then
CFLAGS="$CFLAGS -arch:SSE2"
- fi
+ fi
if test -z `echo $CXXFLAGS | grep -i [-/]arch:` ; then
CXXFLAGS="$CXXFLAGS -arch:SSE2"
fi
+ changequote([,])
fi
dnl VS2013+ requires -FS when parallel building by make -jN.
dnl If nothing, compiler sometimes causes C1041 error.
@@ -1534,6 +1536,14 @@ MOZ_ARG_ENABLE_STRING(ui-locale,
AC_SUBST(MOZ_UI_LOCALE)
dnl ========================================================
+dnl Build the tests?
+dnl ========================================================
+MOZ_ARG_ENABLE_BOOL(tests,
+[ --enable-tests Build test libraries & programs],
+ ENABLE_TESTS=1,
+ ENABLE_TESTS= )
+
+dnl ========================================================
dnl =
dnl = Module specific options
dnl =
@@ -2091,6 +2101,8 @@ AC_SUBST(MOZ_DEBUG_LDFLAGS)
AC_SUBST(WARNINGS_AS_ERRORS)
AC_SUBST(LIBICONV)
+AC_SUBST(ENABLE_TESTS)
+
AC_SUBST(ENABLE_STRIP)
AC_SUBST(PKG_SKIP_STRIP)
AC_SUBST(INCREMENTAL_LINKER)
@@ -2244,8 +2256,6 @@ AC_SUBST(JS_LIBRARY_NAME)
AC_SUBST(JS_CONFIG_MOZ_JS_LIBS)
AC_SUBST(JS_CONFIG_LIBS)
-MOZ_SUBCONFIGURE_JEMALLOC()
-
# Avoid using obsolete NSPR features
AC_DEFINE(NO_NSPR_10_SUPPORT)
diff --git a/js/src/shell/js.cpp b/js/src/shell/js.cpp
index 8d69ca942..8d144417a 100644
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -893,7 +893,6 @@ SetPromiseRejectionTrackerCallback(JSContext* cx, unsigned argc, Value* vp)
return true;
}
-#ifdef ENABLE_INTL_API
static bool
AddIntlExtras(JSContext* cx, unsigned argc, Value* vp)
{
@@ -916,7 +915,6 @@ AddIntlExtras(JSContext* cx, unsigned argc, Value* vp)
args.rval().setUndefined();
return true;
}
-#endif // ENABLE_INTL_API
static bool
EvalAndPrint(JSContext* cx, const char* bytes, size_t length,
@@ -6140,7 +6138,6 @@ static const JSFunctionSpecWithHelp shell_functions[] = {
"Sets the callback to be invoked whenever a Promise rejection is unhandled\n"
"or a previously-unhandled rejection becomes handled."),
-#ifdef ENABLE_INTL_API
JS_FN_HELP("addIntlExtras", AddIntlExtras, 1, 0,
"addIntlExtras(obj)",
"Adds various not-yet-standardized Intl functions as properties on the\n"
@@ -6148,7 +6145,6 @@ static const JSFunctionSpecWithHelp shell_functions[] = {
"functions and their behavior are experimental: don't depend upon them\n"
"unless you're willing to update your code if these experimental APIs change\n"
"underneath you."),
-#endif // ENABLE_INTL_API
JS_FS_HELP_END
};
diff --git a/js/src/shell/moz.build b/js/src/shell/moz.build
index 72ea8145c..e18bad238 100644
--- a/js/src/shell/moz.build
+++ b/js/src/shell/moz.build
@@ -36,7 +36,7 @@ LOCAL_INCLUDES += [
OS_LIBS += CONFIG['EDITLINE_LIBS']
OS_LIBS += CONFIG['MOZ_ZLIB_LIBS']
-if CONFIG['ENABLE_INTL_API'] and CONFIG['MOZ_ICU_DATA_ARCHIVE']:
+if CONFIG['MOZ_ICU_DATA_ARCHIVE']:
# The ICU libraries linked into libmozjs will not include the ICU data,
# so link it directly.
USE_LIBS += ['icudata']
diff --git a/js/src/threading/windows/ConditionVariable.cpp b/js/src/threading/windows/ConditionVariable.cpp
index 3c75a0f27..92e0249b7 100644
--- a/js/src/threading/windows/ConditionVariable.cpp
+++ b/js/src/threading/windows/ConditionVariable.cpp
@@ -54,8 +54,8 @@ js::ConditionVariable::notify_all()
void
js::ConditionVariable::wait(UniqueLock<Mutex>& lock)
{
- CRITICAL_SECTION* cs = &lock.lock.platformData()->criticalSection;
- bool r = SleepConditionVariableCS(&platformData()->cv_, cs, INFINITE);
+ SRWLOCK* srwlock = &lock.lock.platformData()->lock;
+ bool r = SleepConditionVariableSRW(&platformData()->cv_, srwlock, INFINITE, 0);
MOZ_RELEASE_ASSERT(r);
}
@@ -70,7 +70,7 @@ js::CVStatus
js::ConditionVariable::wait_for(UniqueLock<Mutex>& lock,
const mozilla::TimeDuration& rel_time)
{
- CRITICAL_SECTION* cs = &lock.lock.platformData()->criticalSection;
+ SRWLOCK* srwlock = &lock.lock.platformData()->lock;
// Note that DWORD is unsigned, so we have to be careful to clamp at 0.
// If rel_time is Forever, then ToMilliseconds is +inf, which evaluates as
@@ -82,7 +82,7 @@ js::ConditionVariable::wait_for(UniqueLock<Mutex>& lock,
? INFINITE
: static_cast<DWORD>(msecd);
- BOOL r = SleepConditionVariableCS(&platformData()->cv_, cs, msec);
+ BOOL r = SleepConditionVariableSRW(&platformData()->cv_, srwlock, msec, 0);
if (r)
return CVStatus::NoTimeout;
MOZ_RELEASE_ASSERT(GetLastError() == ERROR_TIMEOUT);
diff --git a/js/src/threading/windows/MutexImpl.cpp b/js/src/threading/windows/MutexImpl.cpp
index 385d1c8de..e838459b5 100644
--- a/js/src/threading/windows/MutexImpl.cpp
+++ b/js/src/threading/windows/MutexImpl.cpp
@@ -13,35 +13,6 @@
#include "threading/Mutex.h"
#include "threading/windows/MutexPlatformData.h"
-namespace {
-
-// We build with a toolkit that supports WinXP, so we have to probe
-// for modern features at runtime. This is necessary because Vista and
-// later automatically allocate and subsequently leak a debug info
-// object for each critical section that we allocate unless we tell it
-// not to. In order to tell it not to, we need the extra flags field
-// provided by the Ex version of InitializeCriticalSection.
-struct MutexNativeImports
-{
- using InitializeCriticalSectionExT = BOOL (WINAPI*)(CRITICAL_SECTION*, DWORD, DWORD);
- InitializeCriticalSectionExT InitializeCriticalSectionEx;
-
- MutexNativeImports() {
- HMODULE kernel32_dll = GetModuleHandle("kernel32.dll");
- MOZ_RELEASE_ASSERT(kernel32_dll != NULL);
- InitializeCriticalSectionEx = reinterpret_cast<InitializeCriticalSectionExT>(
- GetProcAddress(kernel32_dll, "InitializeCriticalSectionEx"));
- }
-
- bool hasInitializeCriticalSectionEx() const {
- return InitializeCriticalSectionEx;
- }
-};
-
-static MutexNativeImports NativeImports;
-
-} // (anonymous namespace)
-
js::detail::MutexImpl::MutexImpl()
{
AutoEnterOOMUnsafeRegion oom;
@@ -49,18 +20,7 @@ js::detail::MutexImpl::MutexImpl()
if (!platformData_)
oom.crash("js::Mutex::Mutex");
- // This number was adopted from NSPR.
- const static DWORD LockSpinCount = 1500;
- BOOL r;
- if (NativeImports.hasInitializeCriticalSectionEx()) {
- r = NativeImports.InitializeCriticalSectionEx(&platformData()->criticalSection,
- LockSpinCount,
- CRITICAL_SECTION_NO_DEBUG_INFO);
- } else {
- r = InitializeCriticalSectionAndSpinCount(&platformData()->criticalSection,
- LockSpinCount);
- }
- MOZ_RELEASE_ASSERT(r);
+ InitializeSRWLock(&platformData()->lock);
}
js::detail::MutexImpl::~MutexImpl()
@@ -68,18 +28,17 @@ js::detail::MutexImpl::~MutexImpl()
if (!platformData_)
return;
- DeleteCriticalSection(&platformData()->criticalSection);
js_delete(platformData());
}
void
js::detail::MutexImpl::lock()
{
- EnterCriticalSection(&platformData()->criticalSection);
+ AcquireSRWLockExclusive(&platformData()->lock);
}
void
js::detail::MutexImpl::unlock()
{
- LeaveCriticalSection(&platformData()->criticalSection);
+ ReleaseSRWLockExclusive(&platformData()->lock);
}
diff --git a/js/src/threading/windows/MutexPlatformData.h b/js/src/threading/windows/MutexPlatformData.h
index fbe7fc80d..1d741c5d0 100644
--- a/js/src/threading/windows/MutexPlatformData.h
+++ b/js/src/threading/windows/MutexPlatformData.h
@@ -13,7 +13,7 @@
struct js::detail::MutexImpl::PlatformData
{
- CRITICAL_SECTION criticalSection;
+ SRWLOCK lock;
};
#endif // platform_win_MutexPlatformData_h
diff --git a/js/src/vm/DateTime.cpp b/js/src/vm/DateTime.cpp
index e35ad4285..ba3145af2 100644
--- a/js/src/vm/DateTime.cpp
+++ b/js/src/vm/DateTime.cpp
@@ -13,9 +13,7 @@
#include "jsutil.h"
#include "js/Date.h"
-#if ENABLE_INTL_API
#include "unicode/timezone.h"
-#endif
using mozilla::Atomic;
using mozilla::ReleaseAcquire;
@@ -333,7 +331,7 @@ JS::ResetTimeZone()
{
js::DateTimeInfo::updateTimeZoneAdjustment();
-#if ENABLE_INTL_API && defined(ICU_TZ_HAS_RECREATE_DEFAULT)
+#if defined(ICU_TZ_HAS_RECREATE_DEFAULT)
TZInfo.acquire();
TZInfo.status = IcuTimeZoneInfo::NeedsUpdate;
TZInfo.release();
@@ -343,7 +341,7 @@ JS::ResetTimeZone()
void
js::ResyncICUDefaultTimeZone()
{
-#if ENABLE_INTL_API && defined(ICU_TZ_HAS_RECREATE_DEFAULT)
+#if defined(ICU_TZ_HAS_RECREATE_DEFAULT)
TZInfo.acquire();
if (TZInfo.status == IcuTimeZoneInfo::NeedsUpdate) {
icu::TimeZone::recreateDefault();
diff --git a/js/src/vm/GlobalObject.cpp b/js/src/vm/GlobalObject.cpp
index 280548cd6..c90b6b85f 100644
--- a/js/src/vm/GlobalObject.cpp
+++ b/js/src/vm/GlobalObject.cpp
@@ -17,9 +17,7 @@
#include "builtin/AtomicsObject.h"
#include "builtin/Eval.h"
-#if EXPOSE_INTL_API
-# include "builtin/Intl.h"
-#endif
+#include "builtin/Intl.h"
#include "builtin/MapObject.h"
#include "builtin/ModuleObject.h"
#include "builtin/Object.h"
diff --git a/js/src/vm/Initialization.cpp b/js/src/vm/Initialization.cpp
index 05cc087cc..39acdf9a8 100644
--- a/js/src/vm/Initialization.cpp
+++ b/js/src/vm/Initialization.cpp
@@ -20,10 +20,8 @@
#include "jit/ExecutableAllocator.h"
#include "jit/Ion.h"
#include "js/Utility.h"
-#if ENABLE_INTL_API
#include "unicode/uclean.h"
#include "unicode/utypes.h"
-#endif // ENABLE_INTL_API
#include "vm/DateTime.h"
#include "vm/HelperThreads.h"
#include "vm/Runtime.h"
@@ -113,12 +111,10 @@ JS::detail::InitWithFailureDiagnostic(bool isDebugBuild)
js::DateTimeInfo::init();
-#if EXPOSE_INTL_API
UErrorCode err = U_ZERO_ERROR;
u_init(&err);
if (U_FAILURE(err))
return "u_init() failed";
-#endif // EXPOSE_INTL_API
RETURN_IF_FAIL(js::CreateHelperThreadsState());
RETURN_IF_FAIL(FutexRuntime::initialize());
@@ -171,9 +167,7 @@ JS_ShutDown(void)
// to do it only when PRMJ_Now is eventually called.
PRMJ_NowShutdown();
-#if EXPOSE_INTL_API
u_cleanup();
-#endif // EXPOSE_INTL_API
if (!JSRuntime::hasLiveRuntimes())
js::jit::ReleaseProcessExecutableMemory();
@@ -188,11 +182,7 @@ JS_SetICUMemoryFunctions(JS_ICUAllocFn allocFn, JS_ICUReallocFn reallocFn, JS_IC
"must call JS_SetICUMemoryFunctions before any other JSAPI "
"operation (including JS_Init)");
-#if EXPOSE_INTL_API
UErrorCode status = U_ZERO_ERROR;
u_setMemoryFunctions(/* context = */ nullptr, allocFn, reallocFn, freeFn, &status);
return U_SUCCESS(status);
-#else
- return true;
-#endif
}
diff --git a/js/src/vm/Runtime.cpp b/js/src/vm/Runtime.cpp
index 0d6a3922c..174e23594 100644
--- a/js/src/vm/Runtime.cpp
+++ b/js/src/vm/Runtime.cpp
@@ -213,11 +213,6 @@ JSRuntime::JSRuntime(JSRuntime* parentRuntime)
warningReporter(nullptr),
buildIdOp(nullptr),
propertyRemovals(0),
-#if !EXPOSE_INTL_API
- thousandsSeparator(0),
- decimalSeparator(0),
- numGrouping(0),
-#endif
keepAtoms_(0),
trustedPrincipals_(nullptr),
beingDestroyed_(false),
@@ -330,8 +325,7 @@ JSRuntime::init(uint32_t maxbytes, uint32_t maxNurseryBytes)
/* The garbage collector depends on everything before this point being initialized. */
gcInitialized = true;
- if (!InitRuntimeNumberState(this))
- return false;
+ InitRuntimeNumberState(this);
JS::ResetTimeZone();
@@ -425,10 +419,6 @@ JSRuntime::destroyRuntime()
*/
FreeScriptData(this, lock);
-#if !EXPOSE_INTL_API
- FinishRuntimeNumberState(this);
-#endif
-
gc.finish();
atomsCompartment_ = nullptr;
diff --git a/js/src/vm/Runtime.h b/js/src/vm/Runtime.h
index 734543c4e..735adadf2 100644
--- a/js/src/vm/Runtime.h
+++ b/js/src/vm/Runtime.h
@@ -978,13 +978,6 @@ struct JSRuntime : public JS::shadow::Runtime,
*/
uint32_t propertyRemovals;
-#if !EXPOSE_INTL_API
- /* Number localization, used by jsnum.cpp. */
- const char* thousandsSeparator;
- const char* decimalSeparator;
- const char* numGrouping;
-#endif
-
private:
mozilla::Maybe<js::SharedImmutableStringsCache> sharedImmutableStrings_;
diff --git a/js/src/vm/SelfHosting.cpp b/js/src/vm/SelfHosting.cpp
index 9a8ec7679..653807ce8 100644
--- a/js/src/vm/SelfHosting.cpp
+++ b/js/src/vm/SelfHosting.cpp
@@ -2205,11 +2205,7 @@ static const JSFunctionSpec intrinsic_functions[] = {
JS_FN("std_String_trimRight", str_trimRight, 0,0),
JS_FN("std_String_toLocaleLowerCase", str_toLocaleLowerCase, 0,0),
JS_FN("std_String_toLocaleUpperCase", str_toLocaleUpperCase, 0,0),
-#if !EXPOSE_INTL_API
- JS_FN("std_String_localeCompare", str_localeCompare, 1,0),
-#else
JS_FN("std_String_normalize", str_normalize, 0,0),
-#endif
JS_FN("std_String_concat", str_concat, 1,0),
JS_FN("std_TypedArray_buffer", js::TypedArray_bufferGetter, 1,0),
diff --git a/js/src/wasm/AsmJS.cpp b/js/src/wasm/AsmJS.cpp
index b4f41c3d5..7fade24fb 100644
--- a/js/src/wasm/AsmJS.cpp
+++ b/js/src/wasm/AsmJS.cpp
@@ -857,7 +857,7 @@ class NumLit
private:
Which which_;
union {
- Value scalar_;
+ JS::UninitializedValue scalar_;
SimdConstant simd_;
} u;
@@ -880,7 +880,7 @@ class NumLit
int32_t toInt32() const {
MOZ_ASSERT(which_ == Fixnum || which_ == NegativeInt || which_ == BigUnsigned);
- return u.scalar_.toInt32();
+ return u.scalar_.asValueRef().toInt32();
}
uint32_t toUint32() const {
@@ -889,17 +889,17 @@ class NumLit
RawF64 toDouble() const {
MOZ_ASSERT(which_ == Double);
- return RawF64(u.scalar_.toDouble());
+ return RawF64(u.scalar_.asValueRef().toDouble());
}
RawF32 toFloat() const {
MOZ_ASSERT(which_ == Float);
- return RawF32(float(u.scalar_.toDouble()));
+ return RawF32(float(u.scalar_.asValueRef().toDouble()));
}
Value scalarValue() const {
MOZ_ASSERT(which_ != OutOfRangeInt);
- return u.scalar_;
+ return u.scalar_.asValueRef();
}
bool isSimd() const
diff --git a/js/xpconnect/shell/moz.build b/js/xpconnect/shell/moz.build
index ecc796f7f..d4f5d55af 100644
--- a/js/xpconnect/shell/moz.build
+++ b/js/xpconnect/shell/moz.build
@@ -35,22 +35,6 @@ if CONFIG['_MSC_VER']:
if CONFIG['OS_ARCH'] == 'WINNT':
RCINCLUDE = 'xpcshell.rc'
- if CONFIG['MOZ_SANDBOX']:
- # For sandbox includes and the include dependencies those have
- LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
- ]
-
- USE_LIBS += [
- 'sandbox_s',
- ]
-
- DELAYLOAD_DLLS += [
- 'winmm.dll',
- 'user32.dll',
- ]
-
DELAYLOAD_DLLS += [
'xul.dll',
]
diff --git a/js/xpconnect/shell/xpcshell.cpp b/js/xpconnect/shell/xpcshell.cpp
index ba979bc69..4eef3f6bf 100644
--- a/js/xpconnect/shell/xpcshell.cpp
+++ b/js/xpconnect/shell/xpcshell.cpp
@@ -22,9 +22,6 @@
#define XRE_DONT_PROTECT_DLL_LOAD
#define XRE_WANT_ENVIRON
#include "nsWindowsWMain.cpp"
-#ifdef MOZ_SANDBOX
-#include "mozilla/sandboxing/SandboxInitialization.h"
-#endif
#endif
#ifdef MOZ_WIDGET_GTK
@@ -53,13 +50,7 @@ main(int argc, char** argv, char** envp)
DllBlocklist_Initialize();
#endif
- XREShellData shellData;
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- shellData.sandboxBrokerServices =
- mozilla::sandboxing::GetInitializedBrokerServices();
-#endif
-
- int result = XRE_XPCShellMain(argc, argv, envp, &shellData);
+ int result = XRE_XPCShellMain(argc, argv, envp);
#ifdef XP_MACOSX
FinishAutoreleasePool();
diff --git a/js/xpconnect/src/XPCJSContext.cpp b/js/xpconnect/src/XPCJSContext.cpp
index f5f6a11bb..8862bca32 100644
--- a/js/xpconnect/src/XPCJSContext.cpp
+++ b/js/xpconnect/src/XPCJSContext.cpp
@@ -59,10 +59,6 @@
#include "nsIXULRuntime.h"
#include "nsJSPrincipals.h"
-#if defined(MOZ_JEMALLOC4)
-#include "mozmemory.h"
-#endif
-
#ifdef XP_WIN
#include <windows.h>
#endif
@@ -147,18 +143,6 @@ public:
mActive = false;
}
} else {
-#if defined(MOZ_JEMALLOC4)
- if (mPurge) {
- /* Jemalloc purges dirty pages regularly during free() when the
- * ratio of dirty pages compared to active pages is higher than
- * 1 << lg_dirty_mult. A high ratio can have an impact on
- * performance, so we use the default ratio of 8, but force a
- * regular purge of all remaining dirty pages, after cycle
- * collection. */
- Telemetry::AutoTimer<Telemetry::MEMORY_FREE_PURGED_PAGES_MS> timer;
- jemalloc_free_dirty_pages();
- }
-#endif
mActive = false;
}
return NS_OK;
diff --git a/js/xpconnect/src/XPCShellImpl.cpp b/js/xpconnect/src/XPCShellImpl.cpp
index 45d00d390..a6432856d 100644
--- a/js/xpconnect/src/XPCShellImpl.cpp
+++ b/js/xpconnect/src/XPCShellImpl.cpp
@@ -44,9 +44,6 @@
#ifdef XP_WIN
#include "mozilla/widget/AudioSession.h"
#include <windows.h>
-#if defined(MOZ_SANDBOX)
-#include "SandboxBroker.h"
-#endif
#endif
// all this crap is needed to do the interactive shell stuff
@@ -1235,11 +1232,8 @@ GetCurrentWorkingDirectory(nsAString& workingDirectory)
static JSSecurityCallbacks shellSecurityCallbacks;
int
-XRE_XPCShellMain(int argc, char** argv, char** envp,
- const XREShellData* aShellData)
+XRE_XPCShellMain(int argc, char** argv, char** envp)
{
- MOZ_ASSERT(aShellData);
-
JSContext* cx;
int result = 0;
nsresult rv;
@@ -1484,16 +1478,6 @@ XRE_XPCShellMain(int argc, char** argv, char** envp,
// Plugin may require audio session if installed plugin can initialize
// asynchronized.
AutoAudioSession audioSession;
-
-#if defined(MOZ_SANDBOX)
- // Required for sandboxed child processes.
- if (aShellData->sandboxBrokerServices) {
- SandboxBroker::Initialize(aShellData->sandboxBrokerServices);
- } else {
- NS_WARNING("Failed to initialize broker services, sandboxed "
- "processes will fail to start.");
- }
-#endif
#endif
{
diff --git a/js/xpconnect/src/XPCWrappedNative.cpp b/js/xpconnect/src/XPCWrappedNative.cpp
index acf92f3c3..a12e36baa 100644
--- a/js/xpconnect/src/XPCWrappedNative.cpp
+++ b/js/xpconnect/src/XPCWrappedNative.cpp
@@ -1785,9 +1785,12 @@ CallMethodHelper::ConvertIndependentParam(uint8_t i)
// indirectly, regardless of in/out-ness.
if (type_tag == nsXPTType::T_JSVAL) {
// Root the value.
- dp->val.j.setUndefined();
- if (!js::AddRawValueRoot(mCallContext, &dp->val.j, "XPCWrappedNative::CallMethod param"))
+ dp->val.j.asValueRef().setUndefined();
+ if (!js::AddRawValueRoot(mCallContext, &dp->val.j.asValueRef(),
+ "XPCWrappedNative::CallMethod param"))
+ {
return false;
+ }
}
// Flag cleanup for anything that isn't self-contained.
diff --git a/layout/base/FrameLayerBuilder.cpp b/layout/base/FrameLayerBuilder.cpp
index 9269c2ab6..183285439 100644
--- a/layout/base/FrameLayerBuilder.cpp
+++ b/layout/base/FrameLayerBuilder.cpp
@@ -2346,15 +2346,7 @@ ContainerState::GetLayerCreationHint(AnimatedGeometryRoot* aAnimatedGeometryRoot
break;
}
nsIScrollableFrame* scrollable = do_QueryFrame(fParent);
- if (scrollable
- #ifdef MOZ_B2G
- && scrollable->WantAsyncScroll()
- #endif
- ) {
- // WantAsyncScroll() returns false when the frame has overflow:hidden,
- // so we won't create tiled layers for overflow:hidden frames even if
- // they have a display port. The main purpose of the WantAsyncScroll check
- // is to allow the B2G camera app to use hardware composer for compositing.
+ if (scrollable) {
return LayerManager::SCROLLABLE;
}
}
diff --git a/layout/base/moz.build b/layout/base/moz.build
index 90fbf828c..d3e417f16 100644
--- a/layout/base/moz.build
+++ b/layout/base/moz.build
@@ -131,6 +131,7 @@ UNIFIED_SOURCES += [
'LayoutLogging.cpp',
'MaskLayerImageCache.cpp',
'MobileViewportManager.cpp',
+ 'nsBidi.cpp',
'nsBidiPresUtils.cpp',
'nsCaret.cpp',
'nsCounterManager.cpp',
@@ -165,21 +166,6 @@ UNIFIED_SOURCES += [
'ZoomConstraintsClient.cpp',
]
-if CONFIG['ENABLE_INTL_API']:
- EXPORTS += [
- 'nsBidi_ICU.h',
- ]
- UNIFIED_SOURCES += [
- 'nsBidi_ICU.cpp',
- ]
-else:
- EXPORTS += [
- 'nsBidi_noICU.h',
- ]
- UNIFIED_SOURCES += [
- 'nsBidi_noICU.cpp',
- ]
-
# nsPresArena.cpp needs to be built separately because it uses plarena.h.
# nsRefreshDriver.cpp needs to be built separately because of name clashes in the OS X headers
SOURCES += [
diff --git a/layout/base/nsBidi_ICU.cpp b/layout/base/nsBidi.cpp
index 482668e24..1d6975869 100644
--- a/layout/base/nsBidi_ICU.cpp
+++ b/layout/base/nsBidi.cpp
@@ -4,7 +4,7 @@
* License, v. 2.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 "nsBidi_ICU.h"
+#include "nsBidi.h"
#include "ICUUtils.h"
nsBidi::nsBidi()
diff --git a/layout/base/nsBidi.h b/layout/base/nsBidi.h
index c7c367092..731bc7116 100644
--- a/layout/base/nsBidi.h
+++ b/layout/base/nsBidi.h
@@ -7,10 +7,184 @@
#ifndef nsBidi_h__
#define nsBidi_h__
-#if ENABLE_INTL_API
-#include "nsBidi_ICU.h"
-#else
-#include "nsBidi_noICU.h"
-#endif
+#include "unicode/ubidi.h"
+#include "nsIFrame.h" // for nsBidiLevel/nsBidiDirection declarations
-#endif // _nsBidi_h_
+// nsBidi implemented as a simple wrapper around the bidi reordering engine
+// from ICU.
+// We could eliminate this and let callers use the ICU functions directly
+// once we no longer care about building without ICU available.
+
+class nsBidi
+{
+public:
+ /** @brief Default constructor.
+ *
+ * The nsBidi object is initially empty. It is assigned
+ * the Bidi properties of a paragraph by <code>SetPara()</code>.
+ */
+ explicit nsBidi();
+
+ /** @brief Destructor. */
+ virtual ~nsBidi();
+
+
+ /**
+ * Perform the Unicode Bidi algorithm.
+ *
+ * @param aText is a pointer to the single-paragraph text that the
+ * Bidi algorithm will be performed on
+ * (step (P1) of the algorithm is performed externally).
+ * <strong>The text must be (at least) <code>aLength</code> long.</strong>
+ *
+ * @param aLength is the length of the text; if <code>aLength==-1</code> then
+ * the text must be zero-terminated.
+ *
+ * @param aParaLevel specifies the default level for the paragraph;
+ * it is typically 0 (LTR) or 1 (RTL).
+ * If the function shall determine the paragraph level from the text,
+ * then <code>aParaLevel</code> can be set to
+ * either <code>NSBIDI_DEFAULT_LTR</code>
+ * or <code>NSBIDI_DEFAULT_RTL</code>;
+ * if there is no strongly typed character, then
+ * the desired default is used (0 for LTR or 1 for RTL).
+ * Any other value between 0 and <code>NSBIDI_MAX_EXPLICIT_LEVEL</code>
+ * is also valid, with odd levels indicating RTL.
+ */
+ nsresult SetPara(const char16_t *aText, int32_t aLength,
+ nsBidiLevel aParaLevel);
+
+ /**
+ * Get the directionality of the text.
+ *
+ * @param aDirection receives a <code>NSBIDI_XXX</code> value that indicates
+ * if the entire text represented by this object is unidirectional,
+ * and which direction, or if it is mixed-directional.
+ *
+ * @see nsBidiDirection
+ */
+ nsresult GetDirection(nsBidiDirection* aDirection);
+
+ /**
+ * Get the paragraph level of the text.
+ *
+ * @param aParaLevel receives a <code>NSBIDI_XXX</code> value indicating
+ * the paragraph level
+ *
+ * @see nsBidiLevel
+ */
+ nsresult GetParaLevel(nsBidiLevel* aParaLevel);
+
+ /**
+ * Get a logical run.
+ * This function returns information about a run and is used
+ * to retrieve runs in logical order.<p>
+ * This is especially useful for line-breaking on a paragraph.
+ *
+ * @param aLogicalStart is the first character of the run.
+ *
+ * @param aLogicalLimit will receive the limit of the run.
+ * The l-value that you point to here may be the
+ * same expression (variable) as the one for
+ * <code>aLogicalStart</code>.
+ * This pointer can be <code>nullptr</code> if this
+ * value is not necessary.
+ *
+ * @param aLevel will receive the level of the run.
+ * This pointer can be <code>nullptr</code> if this
+ * value is not necessary.
+ */
+ nsresult GetLogicalRun(int32_t aLogicalStart, int32_t* aLogicalLimit,
+ nsBidiLevel* aLevel);
+
+ /**
+ * Get the number of runs.
+ * This function may invoke the actual reordering on the
+ * <code>nsBidi</code> object, after <code>SetPara</code>
+ * may have resolved only the levels of the text. Therefore,
+ * <code>CountRuns</code> may have to allocate memory,
+ * and may fail doing so.
+ *
+ * @param aRunCount will receive the number of runs.
+ */
+ nsresult CountRuns(int32_t* aRunCount);
+
+ /**
+ * Get one run's logical start, length, and directionality,
+ * which can be 0 for LTR or 1 for RTL.
+ * In an RTL run, the character at the logical start is
+ * visually on the right of the displayed run.
+ * The length is the number of characters in the run.<p>
+ * <code>CountRuns</code> should be called
+ * before the runs are retrieved.
+ *
+ * @param aRunIndex is the number of the run in visual order, in the
+ * range <code>[0..CountRuns-1]</code>.
+ *
+ * @param aLogicalStart is the first logical character index in the text.
+ * The pointer may be <code>nullptr</code> if this index is not needed.
+ *
+ * @param aLength is the number of characters (at least one) in the run.
+ * The pointer may be <code>nullptr</code> if this is not needed.
+ *
+ * @param aDirection will receive the directionality of the run,
+ * <code>NSBIDI_LTR==0</code> or <code>NSBIDI_RTL==1</code>,
+ * never <code>NSBIDI_MIXED</code>.
+ *
+ * @see CountRuns<p>
+ *
+ * Example:
+ * @code
+ * int32_t i, count, logicalStart, visualIndex=0, length;
+ * nsBidiDirection dir;
+ * pBidi->CountRuns(&count);
+ * for(i=0; i<count; ++i) {
+ * pBidi->GetVisualRun(i, &logicalStart, &length, &dir);
+ * if(NSBIDI_LTR==dir) {
+ * do { // LTR
+ * show_char(text[logicalStart++], visualIndex++);
+ * } while(--length>0);
+ * } else {
+ * logicalStart+=length; // logicalLimit
+ * do { // RTL
+ * show_char(text[--logicalStart], visualIndex++);
+ * } while(--length>0);
+ * }
+ * }
+ * @endcode
+ *
+ * Note that in right-to-left runs, code like this places
+ * modifier letters before base characters and second surrogates
+ * before first ones.
+ */
+ nsresult GetVisualRun(int32_t aRunIndex, int32_t* aLogicalStart,
+ int32_t* aLength, nsBidiDirection* aDirection);
+
+ /**
+ * This is a convenience function that does not use a nsBidi object.
+ * It is intended to be used for when an application has determined the levels
+ * of objects (character sequences) and just needs to have them reordered (L2).
+ * This is equivalent to using <code>GetVisualMap</code> on a
+ * <code>nsBidi</code> object.
+ *
+ * @param aLevels is an array with <code>aLength</code> levels that have been
+ * determined by the application.
+ *
+ * @param aLength is the number of levels in the array, or, semantically,
+ * the number of objects to be reordered.
+ * It must be <code>aLength>0</code>.
+ *
+ * @param aIndexMap is a pointer to an array of <code>aLength</code>
+ * indexes which will reflect the reordering of the characters.
+ * The array does not need to be initialized.<p>
+ * The index map will result in
+ * <code>aIndexMap[aVisualIndex]==aLogicalIndex</code>.
+ */
+ static nsresult ReorderVisual(const nsBidiLevel* aLevels, int32_t aLength,
+ int32_t* aIndexMap);
+
+protected:
+ UBiDi* mBiDi;
+};
+
+#endif // nsBidi_h__
diff --git a/layout/base/nsBidi_ICU.h b/layout/base/nsBidi_ICU.h
deleted file mode 100644
index 3ead6e2bb..000000000
--- a/layout/base/nsBidi_ICU.h
+++ /dev/null
@@ -1,190 +0,0 @@
-/* -*- 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/. */
-
-#ifndef nsBidi_ICU_h__
-#define nsBidi_ICU_h__
-
-#include "unicode/ubidi.h"
-#include "nsIFrame.h" // for nsBidiLevel/nsBidiDirection declarations
-
-// nsBidi implemented as a simple wrapper around the bidi reordering engine
-// from ICU.
-// We could eliminate this and let callers use the ICU functions directly
-// once we no longer care about building without ICU available.
-
-class nsBidi
-{
-public:
- /** @brief Default constructor.
- *
- * The nsBidi object is initially empty. It is assigned
- * the Bidi properties of a paragraph by <code>SetPara()</code>.
- */
- explicit nsBidi();
-
- /** @brief Destructor. */
- virtual ~nsBidi();
-
-
- /**
- * Perform the Unicode Bidi algorithm.
- *
- * @param aText is a pointer to the single-paragraph text that the
- * Bidi algorithm will be performed on
- * (step (P1) of the algorithm is performed externally).
- * <strong>The text must be (at least) <code>aLength</code> long.</strong>
- *
- * @param aLength is the length of the text; if <code>aLength==-1</code> then
- * the text must be zero-terminated.
- *
- * @param aParaLevel specifies the default level for the paragraph;
- * it is typically 0 (LTR) or 1 (RTL).
- * If the function shall determine the paragraph level from the text,
- * then <code>aParaLevel</code> can be set to
- * either <code>NSBIDI_DEFAULT_LTR</code>
- * or <code>NSBIDI_DEFAULT_RTL</code>;
- * if there is no strongly typed character, then
- * the desired default is used (0 for LTR or 1 for RTL).
- * Any other value between 0 and <code>NSBIDI_MAX_EXPLICIT_LEVEL</code>
- * is also valid, with odd levels indicating RTL.
- */
- nsresult SetPara(const char16_t *aText, int32_t aLength,
- nsBidiLevel aParaLevel);
-
- /**
- * Get the directionality of the text.
- *
- * @param aDirection receives a <code>NSBIDI_XXX</code> value that indicates
- * if the entire text represented by this object is unidirectional,
- * and which direction, or if it is mixed-directional.
- *
- * @see nsBidiDirection
- */
- nsresult GetDirection(nsBidiDirection* aDirection);
-
- /**
- * Get the paragraph level of the text.
- *
- * @param aParaLevel receives a <code>NSBIDI_XXX</code> value indicating
- * the paragraph level
- *
- * @see nsBidiLevel
- */
- nsresult GetParaLevel(nsBidiLevel* aParaLevel);
-
- /**
- * Get a logical run.
- * This function returns information about a run and is used
- * to retrieve runs in logical order.<p>
- * This is especially useful for line-breaking on a paragraph.
- *
- * @param aLogicalStart is the first character of the run.
- *
- * @param aLogicalLimit will receive the limit of the run.
- * The l-value that you point to here may be the
- * same expression (variable) as the one for
- * <code>aLogicalStart</code>.
- * This pointer can be <code>nullptr</code> if this
- * value is not necessary.
- *
- * @param aLevel will receive the level of the run.
- * This pointer can be <code>nullptr</code> if this
- * value is not necessary.
- */
- nsresult GetLogicalRun(int32_t aLogicalStart, int32_t* aLogicalLimit,
- nsBidiLevel* aLevel);
-
- /**
- * Get the number of runs.
- * This function may invoke the actual reordering on the
- * <code>nsBidi</code> object, after <code>SetPara</code>
- * may have resolved only the levels of the text. Therefore,
- * <code>CountRuns</code> may have to allocate memory,
- * and may fail doing so.
- *
- * @param aRunCount will receive the number of runs.
- */
- nsresult CountRuns(int32_t* aRunCount);
-
- /**
- * Get one run's logical start, length, and directionality,
- * which can be 0 for LTR or 1 for RTL.
- * In an RTL run, the character at the logical start is
- * visually on the right of the displayed run.
- * The length is the number of characters in the run.<p>
- * <code>CountRuns</code> should be called
- * before the runs are retrieved.
- *
- * @param aRunIndex is the number of the run in visual order, in the
- * range <code>[0..CountRuns-1]</code>.
- *
- * @param aLogicalStart is the first logical character index in the text.
- * The pointer may be <code>nullptr</code> if this index is not needed.
- *
- * @param aLength is the number of characters (at least one) in the run.
- * The pointer may be <code>nullptr</code> if this is not needed.
- *
- * @param aDirection will receive the directionality of the run,
- * <code>NSBIDI_LTR==0</code> or <code>NSBIDI_RTL==1</code>,
- * never <code>NSBIDI_MIXED</code>.
- *
- * @see CountRuns<p>
- *
- * Example:
- * @code
- * int32_t i, count, logicalStart, visualIndex=0, length;
- * nsBidiDirection dir;
- * pBidi->CountRuns(&count);
- * for(i=0; i<count; ++i) {
- * pBidi->GetVisualRun(i, &logicalStart, &length, &dir);
- * if(NSBIDI_LTR==dir) {
- * do { // LTR
- * show_char(text[logicalStart++], visualIndex++);
- * } while(--length>0);
- * } else {
- * logicalStart+=length; // logicalLimit
- * do { // RTL
- * show_char(text[--logicalStart], visualIndex++);
- * } while(--length>0);
- * }
- * }
- * @endcode
- *
- * Note that in right-to-left runs, code like this places
- * modifier letters before base characters and second surrogates
- * before first ones.
- */
- nsresult GetVisualRun(int32_t aRunIndex, int32_t* aLogicalStart,
- int32_t* aLength, nsBidiDirection* aDirection);
-
- /**
- * This is a convenience function that does not use a nsBidi object.
- * It is intended to be used for when an application has determined the levels
- * of objects (character sequences) and just needs to have them reordered (L2).
- * This is equivalent to using <code>GetVisualMap</code> on a
- * <code>nsBidi</code> object.
- *
- * @param aLevels is an array with <code>aLength</code> levels that have been
- * determined by the application.
- *
- * @param aLength is the number of levels in the array, or, semantically,
- * the number of objects to be reordered.
- * It must be <code>aLength>0</code>.
- *
- * @param aIndexMap is a pointer to an array of <code>aLength</code>
- * indexes which will reflect the reordering of the characters.
- * The array does not need to be initialized.<p>
- * The index map will result in
- * <code>aIndexMap[aVisualIndex]==aLogicalIndex</code>.
- */
- static nsresult ReorderVisual(const nsBidiLevel* aLevels, int32_t aLength,
- int32_t* aIndexMap);
-
-protected:
- UBiDi* mBiDi;
-};
-
-#endif // _nsBidi_ICU_h_
diff --git a/layout/base/nsBidi_noICU.cpp b/layout/base/nsBidi_noICU.cpp
deleted file mode 100644
index 0b9c58e55..000000000
--- a/layout/base/nsBidi_noICU.cpp
+++ /dev/null
@@ -1,2089 +0,0 @@
-/* -*- 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 "nsBidi.h"
-#include "nsUnicodeProperties.h"
-#include "nsCRTGlue.h"
-
-using namespace mozilla::unicode;
-
-static_assert(mozilla::kBidiLevelNone > NSBIDI_MAX_EXPLICIT_LEVEL + 1,
- "The pseudo embedding level should be out-of-range");
-
-// These are #defined in <sys/regset.h> under Solaris 10 x86
-#undef CS
-#undef ES
-
-/* Comparing the description of the Bidi algorithm with this implementation
- is easier with the same names for the Bidi types in the code as there.
-*/
-enum {
- L = eCharType_LeftToRight,
- R = eCharType_RightToLeft,
- EN = eCharType_EuropeanNumber,
- ES = eCharType_EuropeanNumberSeparator,
- ET = eCharType_EuropeanNumberTerminator,
- AN = eCharType_ArabicNumber,
- CS = eCharType_CommonNumberSeparator,
- B = eCharType_BlockSeparator,
- S = eCharType_SegmentSeparator,
- WS = eCharType_WhiteSpaceNeutral,
- O_N = eCharType_OtherNeutral,
- LRE = eCharType_LeftToRightEmbedding,
- LRO = eCharType_LeftToRightOverride,
- AL = eCharType_RightToLeftArabic,
- RLE = eCharType_RightToLeftEmbedding,
- RLO = eCharType_RightToLeftOverride,
- PDF = eCharType_PopDirectionalFormat,
- NSM = eCharType_DirNonSpacingMark,
- BN = eCharType_BoundaryNeutral,
- LRI = eCharType_LeftToRightIsolate,
- RLI = eCharType_RightToLeftIsolate,
- FSI = eCharType_FirstStrongIsolate,
- PDI = eCharType_PopDirectionalIsolate,
- ENL, /* EN after W7 */ /* 23 */
- ENR, /* EN not subject to W7 */ /* 24 */
- dirPropCount
-};
-
-#define IS_STRONG_TYPE(dirProp) ((dirProp) <= R || (dirProp) == AL)
-
-/* to avoid some conditional statements, use tiny constant arrays */
-static Flags flagLR[2]={ DIRPROP_FLAG(L), DIRPROP_FLAG(R) };
-static Flags flagE[2]={ DIRPROP_FLAG(LRE), DIRPROP_FLAG(RLE) };
-static Flags flagO[2]={ DIRPROP_FLAG(LRO), DIRPROP_FLAG(RLO) };
-
-#define DIRPROP_FLAG_LR(level) flagLR[(level)&1]
-#define DIRPROP_FLAG_E(level) flagE[(level)&1]
-#define DIRPROP_FLAG_O(level) flagO[(level)&1]
-
-#define NO_OVERRIDE(level) ((level)&~NSBIDI_LEVEL_OVERRIDE)
-
-static inline uint8_t
-DirFromStrong(uint8_t aDirProp)
-{
- MOZ_ASSERT(IS_STRONG_TYPE(aDirProp));
- return aDirProp == L ? L : R;
-}
-
-/*
- * General implementation notes:
- *
- * Throughout the implementation, there are comments like (W2) that refer to
- * rules of the Bidi algorithm in its version 5, in this example to the second
- * rule of the resolution of weak types.
- *
- * For handling surrogate pairs, where two UChar's form one "abstract" (or UTF-32)
- * character according to UTF-16, the second UChar gets the directional property of
- * the entire character assigned, while the first one gets a BN, a boundary
- * neutral, type, which is ignored by most of the algorithm according to
- * rule (X9) and the implementation suggestions of the Bidi algorithm.
- *
- * Later, AdjustWSLevels() will set the level for each BN to that of the
- * following character (UChar), which results in surrogate pairs getting the
- * same level on each of their surrogates.
- *
- * In a UTF-8 implementation, the same thing could be done: the last byte of
- * a multi-byte sequence would get the "real" property, while all previous
- * bytes of that sequence would get BN.
- *
- * It is not possible to assign all those parts of a character the same real
- * property because this would fail in the resolution of weak types with rules
- * that look at immediately surrounding types.
- *
- * As a related topic, this implementation does not remove Boundary Neutral
- * types from the input, but ignores them whenever this is relevant.
- * For example, the loop for the resolution of the weak types reads
- * types until it finds a non-BN.
- * Also, explicit embedding codes are neither changed into BN nor removed.
- * They are only treated the same way real BNs are.
- * As stated before, AdjustWSLevels() takes care of them at the end.
- * For the purpose of conformance, the levels of all these codes
- * do not matter.
- *
- * Note that this implementation never modifies the dirProps
- * after the initial setup, except for FSI which is changed to either
- * LRI or RLI in GetDirProps(), and paired brackets which may be changed
- * to L or R according to N0.
- *
- *
- * In this implementation, the resolution of weak types (Wn),
- * neutrals (Nn), and the assignment of the resolved level (In)
- * are all done in one single loop, in ResolveImplicitLevels().
- * Changes of dirProp values are done on the fly, without writing
- * them back to the dirProps array.
- *
- *
- * This implementation contains code that allows to bypass steps of the
- * algorithm that are not needed on the specific paragraph
- * in order to speed up the most common cases considerably,
- * like text that is entirely LTR, or RTL text without numbers.
- *
- * Most of this is done by setting a bit for each directional property
- * in a flags variable and later checking for whether there are
- * any LTR characters or any RTL characters, or both, whether
- * there are any explicit embedding codes, etc.
- *
- * If the (Xn) steps are performed, then the flags are re-evaluated,
- * because they will then not contain the embedding codes any more
- * and will be adjusted for override codes, so that subsequently
- * more bypassing may be possible than what the initial flags suggested.
- *
- * If the text is not mixed-directional, then the
- * algorithm steps for the weak type resolution are not performed,
- * and all levels are set to the paragraph level.
- *
- * If there are no explicit embedding codes, then the (Xn) steps
- * are not performed.
- *
- * If embedding levels are supplied as a parameter, then all
- * explicit embedding codes are ignored, and the (Xn) steps
- * are not performed.
- *
- * White Space types could get the level of the run they belong to,
- * and are checked with a test of (flags&MASK_EMBEDDING) to
- * consider if the paragraph direction should be considered in
- * the flags variable.
- *
- * If there are no White Space types in the paragraph, then
- * (L1) is not necessary in AdjustWSLevels().
- */
-nsBidi::nsBidi()
-{
- Init();
-}
-
-nsBidi::~nsBidi()
-{
- Free();
-}
-
-void nsBidi::Init()
-{
- /* reset the object, all pointers nullptr, all flags false, all sizes 0 */
- mLength = 0;
- mParaLevel = 0;
- mFlags = 0;
- mDirection = NSBIDI_LTR;
- mTrailingWSStart = 0;
-
- mDirPropsSize = 0;
- mLevelsSize = 0;
- mRunsSize = 0;
- mIsolatesSize = 0;
-
- mRunCount = -1;
- mIsolateCount = -1;
-
- mDirProps=nullptr;
- mLevels=nullptr;
- mRuns=nullptr;
- mIsolates=nullptr;
-
- mDirPropsMemory=nullptr;
- mLevelsMemory=nullptr;
- mRunsMemory=nullptr;
- mIsolatesMemory=nullptr;
-}
-
-/*
- * We are allowed to allocate memory if aMemory==nullptr
- * for each array that we need.
- * We also try to grow and shrink memory as needed if we
- * allocate it.
- *
- * Assume aSizeNeeded>0.
- * If *aMemory!=nullptr, then assume *aSize>0.
- *
- * ### this realloc() may unnecessarily copy the old data,
- * which we know we don't need any more;
- * is this the best way to do this??
- */
-/*static*/
-bool
-nsBidi::GetMemory(void **aMemory, size_t *aSize, size_t aSizeNeeded)
-{
- /* check for existing memory */
- if(*aMemory==nullptr) {
- /* we need to allocate memory */
- *aMemory=malloc(aSizeNeeded);
- if (*aMemory!=nullptr) {
- *aSize=aSizeNeeded;
- return true;
- } else {
- *aSize=0;
- return false;
- }
- } else {
- /* there is some memory, is it enough or too much? */
- if(aSizeNeeded!=*aSize) {
- /* we may try to grow or shrink */
- void *memory=realloc(*aMemory, aSizeNeeded);
-
- if(memory!=nullptr) {
- *aMemory=memory;
- *aSize=aSizeNeeded;
- return true;
- } else {
- /* we failed to grow */
- return false;
- }
- } else {
- /* we have at least enough memory and must not allocate */
- return true;
- }
- }
-}
-
-void nsBidi::Free()
-{
- free(mDirPropsMemory);
- mDirPropsMemory = nullptr;
- free(mLevelsMemory);
- mLevelsMemory = nullptr;
- free(mRunsMemory);
- mRunsMemory = nullptr;
- free(mIsolatesMemory);
- mIsolatesMemory = nullptr;
-}
-
-/* SetPara ------------------------------------------------------------ */
-
-nsresult nsBidi::SetPara(const char16_t *aText, int32_t aLength,
- nsBidiLevel aParaLevel)
-{
- nsBidiDirection direction;
-
- /* check the argument values */
- if(aText==nullptr ||
- ((NSBIDI_MAX_EXPLICIT_LEVEL<aParaLevel) && !IS_DEFAULT_LEVEL(aParaLevel)) ||
- aLength<-1
- ) {
- return NS_ERROR_INVALID_ARG;
- }
-
- if(aLength==-1) {
- aLength = NS_strlen(aText);
- }
-
- /* initialize member data */
- mLength = aLength;
- mParaLevel=aParaLevel;
- mDirection=aParaLevel & 1 ? NSBIDI_RTL : NSBIDI_LTR;
- mTrailingWSStart=aLength; /* the levels[] will reflect the WS run */
-
- mDirProps=nullptr;
- mLevels=nullptr;
- mRuns=nullptr;
-
- if(aLength==0) {
- /*
- * For an empty paragraph, create an nsBidi object with the aParaLevel and
- * the flags and the direction set but without allocating zero-length arrays.
- * There is nothing more to do.
- */
- if(IS_DEFAULT_LEVEL(aParaLevel)) {
- mParaLevel&=1;
- }
- mFlags=DIRPROP_FLAG_LR(aParaLevel);
- mRunCount=0;
- return NS_OK;
- }
-
- mRunCount=-1;
-
- /*
- * Get the directional properties,
- * the flags bit-set, and
- * determine the partagraph level if necessary.
- */
- if(GETDIRPROPSMEMORY(aLength)) {
- mDirProps=mDirPropsMemory;
- GetDirProps(aText);
- } else {
- return NS_ERROR_OUT_OF_MEMORY;
- }
-
- /* determine explicit levels according to the (Xn) rules */
- if(GETLEVELSMEMORY(aLength)) {
- mLevels=mLevelsMemory;
- ResolveExplicitLevels(&direction, aText);
- } else {
- return NS_ERROR_OUT_OF_MEMORY;
- }
-
- /* allocate isolate memory */
- if (mIsolateCount <= SIMPLE_ISOLATES_SIZE) {
- mIsolates = mSimpleIsolates;
- } else {
- if (mIsolateCount * sizeof(Isolate) <= mIsolatesSize) {
- mIsolates = mIsolatesMemory;
- } else {
- if (GETISOLATESMEMORY(mIsolateCount)) {
- mIsolates = mIsolatesMemory;
- } else {
- return NS_ERROR_OUT_OF_MEMORY;
- }
- }
- }
- mIsolateCount = -1; /* current isolates stack entry == none */
-
- /*
- * The steps after (X9) in the Bidi algorithm are performed only if
- * the paragraph text has mixed directionality!
- */
- mDirection = direction;
- switch(direction) {
- case NSBIDI_LTR:
- /* make sure paraLevel is even */
- mParaLevel=(mParaLevel+1)&~1;
-
- /* all levels are implicitly at paraLevel (important for GetLevels()) */
- mTrailingWSStart=0;
- break;
- case NSBIDI_RTL:
- /* make sure paraLevel is odd */
- mParaLevel|=1;
-
- /* all levels are implicitly at paraLevel (important for GetLevels()) */
- mTrailingWSStart=0;
- break;
- default:
- /*
- * If there are no external levels specified and there
- * are no significant explicit level codes in the text,
- * then we can treat the entire paragraph as one run.
- * Otherwise, we need to perform the following rules on runs of
- * the text with the same embedding levels. (X10)
- * "Significant" explicit level codes are ones that actually
- * affect non-BN characters.
- * Examples for "insignificant" ones are empty embeddings
- * LRE-PDF, LRE-RLE-PDF-PDF, etc.
- */
- if(!(mFlags&DIRPROP_FLAG_MULTI_RUNS)) {
- ResolveImplicitLevels(0, aLength,
- GET_LR_FROM_LEVEL(mParaLevel),
- GET_LR_FROM_LEVEL(mParaLevel));
- } else {
- /* sor, eor: start and end types of same-level-run */
- nsBidiLevel *levels=mLevels;
- int32_t start, limit=0;
- nsBidiLevel level, nextLevel;
- DirProp sor, eor;
-
- /* determine the first sor and set eor to it because of the loop body (sor=eor there) */
- level=mParaLevel;
- nextLevel=levels[0];
- if(level<nextLevel) {
- eor=GET_LR_FROM_LEVEL(nextLevel);
- } else {
- eor=GET_LR_FROM_LEVEL(level);
- }
-
- do {
- /* determine start and limit of the run (end points just behind the run) */
-
- /* the values for this run's start are the same as for the previous run's end */
- sor=eor;
- start=limit;
- level=nextLevel;
-
- /* search for the limit of this run */
- while(++limit<aLength &&
- (levels[limit]==level ||
- (DIRPROP_FLAG(mDirProps[limit])&MASK_BN_EXPLICIT))) {}
-
- /* get the correct level of the next run */
- if(limit<aLength) {
- nextLevel=levels[limit];
- } else {
- nextLevel=mParaLevel;
- }
-
- /* determine eor from max(level, nextLevel); sor is last run's eor */
- if((level&~NSBIDI_LEVEL_OVERRIDE)<(nextLevel&~NSBIDI_LEVEL_OVERRIDE)) {
- eor=GET_LR_FROM_LEVEL(nextLevel);
- } else {
- eor=GET_LR_FROM_LEVEL(level);
- }
-
- /* if the run consists of overridden directional types, then there
- are no implicit types to be resolved */
- if(!(level&NSBIDI_LEVEL_OVERRIDE)) {
- ResolveImplicitLevels(start, limit, sor, eor);
- } else {
- do {
- levels[start++] &= ~NSBIDI_LEVEL_OVERRIDE;
- } while (start < limit);
- }
- } while(limit<aLength);
- }
-
- /* reset the embedding levels for some non-graphic characters (L1), (X9) */
- AdjustWSLevels();
- break;
- }
-
- return NS_OK;
-}
-
-/* perform (P2)..(P3) ------------------------------------------------------- */
-
-/*
- * Get the directional properties for the text,
- * calculate the flags bit-set, and
- * determine the partagraph level if necessary.
- */
-void nsBidi::GetDirProps(const char16_t *aText)
-{
- DirProp *dirProps=mDirPropsMemory; /* mDirProps is const */
-
- int32_t i=0, length=mLength;
- Flags flags=0; /* collect all directionalities in the text */
- char16_t uchar;
- DirProp dirProp;
-
- bool isDefaultLevel = IS_DEFAULT_LEVEL(mParaLevel);
-
- enum State {
- NOT_SEEKING_STRONG, /* 0: not after FSI */
- SEEKING_STRONG_FOR_PARA, /* 1: looking for first strong char in para */
- SEEKING_STRONG_FOR_FSI, /* 2: looking for first strong after FSI */
- LOOKING_FOR_PDI /* 3: found strong after FSI, looking for PDI */
- };
- State state;
-
- /* The following stacks are used to manage isolate sequences. Those
- sequences may be nested, but obviously never more deeply than the
- maximum explicit embedding level.
- lastStack is the index of the last used entry in the stack. A value of -1
- means that there is no open isolate sequence. */
- /* The following stack contains the position of the initiator of
- each open isolate sequence */
- int32_t isolateStartStack[NSBIDI_MAX_EXPLICIT_LEVEL + 1];
- /* The following stack contains the last known state before
- encountering the initiator of an isolate sequence */
- State previousStateStack[NSBIDI_MAX_EXPLICIT_LEVEL + 1];
- int32_t stackLast = -1;
-
- if(isDefaultLevel) {
- /*
- * see comment in nsBidi.h:
- * the DEFAULT_XXX values are designed so that
- * their bit 0 alone yields the intended default
- */
- mParaLevel &= 1;
- state = SEEKING_STRONG_FOR_PARA;
- } else {
- state = NOT_SEEKING_STRONG;
- }
-
- /* determine the paragraph level (P2..P3) */
- for(/* i = 0 above */; i < length;) {
- uchar=aText[i];
- if(!IS_FIRST_SURROGATE(uchar) || i+1==length || !IS_SECOND_SURROGATE(aText[i+1])) {
- /* not a surrogate pair */
- flags|=DIRPROP_FLAG(dirProps[i]=dirProp=GetBidiCat((uint32_t)uchar));
- } else {
- /* a surrogate pair */
- dirProps[i++]=BN; /* first surrogate in the pair gets the BN type */
- flags|=DIRPROP_FLAG(dirProps[i]=dirProp=GetBidiCat(GET_UTF_32(uchar, aText[i])))|DIRPROP_FLAG(BN);
- }
- ++i;
-
- switch (dirProp) {
- case L:
- if (state == SEEKING_STRONG_FOR_PARA) {
- mParaLevel = 0;
- state = NOT_SEEKING_STRONG;
- } else if (state == SEEKING_STRONG_FOR_FSI) {
- if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
- dirProps[isolateStartStack[stackLast]] = LRI;
- flags |= DIRPROP_FLAG(LRI);
- }
- state = LOOKING_FOR_PDI;
- }
- break;
-
- case R: case AL:
- if (state == SEEKING_STRONG_FOR_PARA) {
- mParaLevel = 1;
- state = NOT_SEEKING_STRONG;
- } else if (state == SEEKING_STRONG_FOR_FSI) {
- if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
- dirProps[isolateStartStack[stackLast]] = RLI;
- flags |= DIRPROP_FLAG(RLI);
- }
- state = LOOKING_FOR_PDI;
- }
- break;
-
- case FSI: case LRI: case RLI:
- stackLast++;
- if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
- isolateStartStack[stackLast] = i - 1;
- previousStateStack[stackLast] = state;
- }
- if (dirProp == FSI) {
- state = SEEKING_STRONG_FOR_FSI;
- } else {
- state = LOOKING_FOR_PDI;
- }
- break;
-
- case PDI:
- if (state == SEEKING_STRONG_FOR_FSI) {
- if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
- dirProps[isolateStartStack[stackLast]] = LRI;
- flags |= DIRPROP_FLAG(LRI);
- }
- }
- if (stackLast >= 0) {
- if (stackLast <= NSBIDI_MAX_EXPLICIT_LEVEL) {
- state = previousStateStack[stackLast];
- }
- stackLast--;
- }
- break;
-
- case B:
- // This shouldn't happen, since we don't support multiple paragraphs.
- NS_NOTREACHED("Unexpected paragraph separator");
- break;
-
- default:
- break;
- }
- }
-
- /* Ignore still open isolate sequences with overflow */
- if (stackLast > NSBIDI_MAX_EXPLICIT_LEVEL) {
- stackLast = NSBIDI_MAX_EXPLICIT_LEVEL;
- if (dirProps[previousStateStack[NSBIDI_MAX_EXPLICIT_LEVEL]] != FSI) {
- state = LOOKING_FOR_PDI;
- }
- }
-
- /* Resolve direction of still unresolved open FSI sequences */
- while (stackLast >= 0) {
- if (state == SEEKING_STRONG_FOR_FSI) {
- dirProps[isolateStartStack[stackLast]] = LRI;
- flags |= DIRPROP_FLAG(LRI);
- }
- state = previousStateStack[stackLast];
- stackLast--;
- }
-
- flags|=DIRPROP_FLAG_LR(mParaLevel);
-
- mFlags = flags;
-}
-
-/* Functions for handling paired brackets ----------------------------------- */
-
-/* In the mIsoRuns array, the first entry is used for text outside of any
- isolate sequence. Higher entries are used for each more deeply nested
- isolate sequence.
- mIsoRunLast is the index of the last used entry.
- The mOpenings array is used to note the data of opening brackets not yet
- matched by a closing bracket, or matched but still susceptible to change
- level.
- Each isoRun entry contains the index of the first and
- one-after-last openings entries for pending opening brackets it
- contains. The next mOpenings entry to use is the one-after-last of the
- most deeply nested isoRun entry.
- mIsoRuns entries also contain their current embedding level and the bidi
- class of the last-encountered strong character, since these will be needed
- to resolve the level of paired brackets. */
-
-nsBidi::BracketData::BracketData(const nsBidi *aBidi)
-{
- mIsoRunLast = 0;
- mIsoRuns[0].start = 0;
- mIsoRuns[0].limit = 0;
- mIsoRuns[0].level = aBidi->mParaLevel;
- mIsoRuns[0].lastStrong = mIsoRuns[0].lastBase = mIsoRuns[0].contextDir =
- GET_LR_FROM_LEVEL(aBidi->mParaLevel);
- mIsoRuns[0].contextPos = 0;
- mOpenings = mSimpleOpenings;
- mOpeningsCount = SIMPLE_OPENINGS_COUNT;
- mOpeningsMemory = nullptr;
-}
-
-nsBidi::BracketData::~BracketData()
-{
- free(mOpeningsMemory);
-}
-
-/* LRE, LRO, RLE, RLO, PDF */
-void
-nsBidi::BracketData::ProcessBoundary(int32_t aLastDirControlCharPos,
- nsBidiLevel aContextLevel,
- nsBidiLevel aEmbeddingLevel,
- const DirProp* aDirProps)
-{
- IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
- if (DIRPROP_FLAG(aDirProps[aLastDirControlCharPos]) & MASK_ISO) { /* after an isolate */
- return;
- }
- if (NO_OVERRIDE(aEmbeddingLevel) > NO_OVERRIDE(aContextLevel)) { /* not PDF */
- aContextLevel = aEmbeddingLevel;
- }
- lastIsoRun.limit = lastIsoRun.start;
- lastIsoRun.level = aEmbeddingLevel;
- lastIsoRun.lastStrong = lastIsoRun.lastBase = lastIsoRun.contextDir =
- GET_LR_FROM_LEVEL(aContextLevel);
- lastIsoRun.contextPos = aLastDirControlCharPos;
-}
-
-/* LRI or RLI */
-void
-nsBidi::BracketData::ProcessLRI_RLI(nsBidiLevel aLevel)
-{
- MOZ_ASSERT(mIsoRunLast <= NSBIDI_MAX_EXPLICIT_LEVEL);
- IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
- lastIsoRun.lastBase = O_N;
- IsoRun& currIsoRun = mIsoRuns[++mIsoRunLast];
- currIsoRun.start = currIsoRun.limit = lastIsoRun.limit;
- currIsoRun.level = aLevel;
- currIsoRun.lastStrong = currIsoRun.lastBase = currIsoRun.contextDir =
- GET_LR_FROM_LEVEL(aLevel);
- currIsoRun.contextPos = 0;
-}
-
-/* PDI */
-void
-nsBidi::BracketData::ProcessPDI()
-{
- MOZ_ASSERT(mIsoRunLast > 0);
- mIsoRuns[--mIsoRunLast].lastBase = O_N;
-}
-
-/* newly found opening bracket: create an openings entry */
-bool /* return true if success */
-nsBidi::BracketData::AddOpening(char16_t aMatch, int32_t aPosition)
-{
- IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
- if (lastIsoRun.limit >= mOpeningsCount) { /* no available new entry */
- if (!GETOPENINGSMEMORY(lastIsoRun.limit * 2)) {
- return false;
- }
- if (mOpenings == mSimpleOpenings) {
- memcpy(mOpeningsMemory, mSimpleOpenings,
- SIMPLE_OPENINGS_COUNT * sizeof(Opening));
- }
- mOpenings = mOpeningsMemory; /* may have changed */
- mOpeningsCount = mOpeningsSize / sizeof(Opening);
- }
- Opening& o = mOpenings[lastIsoRun.limit];
- o.position = aPosition;
- o.match = aMatch;
- o.contextDir = lastIsoRun.contextDir;
- o.contextPos = lastIsoRun.contextPos;
- o.flags = 0;
- lastIsoRun.limit++;
- return true;
-}
-
-/* change N0c1 to N0c2 when a preceding bracket is assigned the embedding level */
-void
-nsBidi::BracketData::FixN0c(int32_t aOpeningIndex, int32_t aNewPropPosition,
- DirProp aNewProp, DirProp* aDirProps)
-{
- /* This function calls itself recursively */
- IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
- for (int32_t k = aOpeningIndex + 1; k < lastIsoRun.limit; k++) {
- Opening& o = mOpenings[k];
- if (o.match >= 0) { /* not an N0c match */
- continue;
- }
- if (aNewPropPosition < o.contextPos) {
- break;
- }
- int32_t openingPosition = o.position;
- if (aNewPropPosition >= openingPosition) {
- continue;
- }
- if (aNewProp == o.contextDir) {
- break;
- }
- aDirProps[openingPosition] = aNewProp;
- int32_t closingPosition = -(o.match);
- aDirProps[closingPosition] = aNewProp;
- o.match = 0; /* prevent further changes */
- FixN0c(k, openingPosition, aNewProp, aDirProps);
- FixN0c(k, closingPosition, aNewProp, aDirProps);
- }
-}
-
-/* process closing bracket */
-DirProp /* return L or R if N0b or N0c, ON if N0d */
-nsBidi::BracketData::ProcessClosing(int32_t aOpenIdx, int32_t aPosition,
- DirProp* aDirProps)
-{
- IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
- Opening& o = mOpenings[aOpenIdx];
- DirProp newProp;
- DirProp direction = GET_LR_FROM_LEVEL(lastIsoRun.level);
- bool stable = true; // assume stable until proved otherwise
-
- /* The stable flag is set when brackets are paired and their
- level is resolved and cannot be changed by what will be
- found later in the source string.
- An unstable match can occur only when applying N0c, where
- the resolved level depends on the preceding context, and
- this context may be affected by text occurring later.
- Example: RTL paragraph containing: abc[(latin) HEBREW]
- When the closing parenthesis is encountered, it appears
- that N0c1 must be applied since 'abc' sets an opposite
- direction context and both parentheses receive level 2.
- However, when the closing square bracket is processed,
- N0b applies because of 'HEBREW' being included within the
- brackets, thus the square brackets are treated like R and
- receive level 1. However, this changes the preceding
- context of the opening parenthesis, and it now appears
- that N0c2 must be applied to the parentheses rather than
- N0c1. */
-
- if ((direction == 0 && o.flags & FOUND_L) ||
- (direction == 1 && o.flags & FOUND_R)) { /* N0b */
- newProp = direction;
- } else if (o.flags & (FOUND_L|FOUND_R)) { /* N0c */
- /* it is stable if there is no containing pair or in
- conditions too complicated and not worth checking */
- stable = (aOpenIdx == lastIsoRun.start);
- if (direction != o.contextDir) {
- newProp = o.contextDir; /* N0c1 */
- } else {
- newProp = direction; /* N0c2 */
- }
- } else {
- /* forget this and any brackets nested within this pair */
- lastIsoRun.limit = aOpenIdx;
- return O_N; /* N0d */
- }
- aDirProps[o.position] = newProp;
- aDirProps[aPosition] = newProp;
- /* Update nested N0c pairs that may be affected */
- FixN0c(aOpenIdx, o.position, newProp, aDirProps);
- if (stable) {
- /* forget any brackets nested within this pair */
- lastIsoRun.limit = aOpenIdx;
- } else {
- int32_t k;
- o.match = -aPosition;
- /* neutralize any unmatched opening between the current pair */
- for (k = aOpenIdx + 1; k < lastIsoRun.limit; k++) {
- Opening& oo = mOpenings[k];
- if (oo.position > aPosition) {
- break;
- }
- if (oo.match > 0) {
- oo.match = 0;
- }
- }
- }
- return newProp;
-}
-
-static inline bool
-IsMatchingCloseBracket(char16_t aCh1, char16_t aCh2)
-{
- // U+232A RIGHT-POINTING ANGLE BRACKET and U+3009 RIGHT ANGLE BRACKET
- // are canonical equivalents, so we special-case them here.
- return (aCh1 == aCh2) ||
- (aCh1 == 0x232A && aCh2 == 0x3009) ||
- (aCh2 == 0x232A && aCh1 == 0x3009);
-}
-
-/* Handle strong characters, digits and candidates for closing brackets. */
-/* Returns true if success. (The only failure mode is an OOM when trying
- to allocate memory for the Openings array.) */
-bool
-nsBidi::BracketData::ProcessChar(int32_t aPosition, char16_t aCh,
- DirProp* aDirProps, nsBidiLevel* aLevels)
-{
- IsoRun& lastIsoRun = mIsoRuns[mIsoRunLast];
- DirProp newProp;
- DirProp dirProp = aDirProps[aPosition];
- nsBidiLevel level = aLevels[aPosition];
- if (dirProp == O_N) {
- /* First see if it is a matching closing bracket. Hopefully, this is
- more efficient than checking if it is a closing bracket at all */
- for (int32_t idx = lastIsoRun.limit - 1; idx >= lastIsoRun.start; idx--) {
- if (!IsMatchingCloseBracket(aCh, mOpenings[idx].match)) {
- continue;
- }
- /* We have a match */
- newProp = ProcessClosing(idx, aPosition, aDirProps);
- if (newProp == O_N) { /* N0d */
- aCh = 0; /* prevent handling as an opening */
- break;
- }
- lastIsoRun.lastBase = O_N;
- lastIsoRun.contextDir = newProp;
- lastIsoRun.contextPos = aPosition;
- if (level & NSBIDI_LEVEL_OVERRIDE) { /* X4, X5 */
- newProp = GET_LR_FROM_LEVEL(level);
- lastIsoRun.lastStrong = newProp;
- uint16_t flag = DIRPROP_FLAG(newProp);
- for (int32_t i = lastIsoRun.start; i < idx; i++) {
- mOpenings[i].flags |= flag;
- }
- /* matching brackets are not overridden by LRO/RLO */
- aLevels[aPosition] &= ~NSBIDI_LEVEL_OVERRIDE;
- }
- /* matching brackets are not overridden by LRO/RLO */
- aLevels[mOpenings[idx].position] &= ~NSBIDI_LEVEL_OVERRIDE;
- return true;
- }
- /* We get here only if the ON character is not a matching closing
- bracket or it is a case of N0d */
- /* Now see if it is an opening bracket */
- char16_t match = GetPairedBracket(aCh);
- if (match != aCh && /* has a matching char */
- GetPairedBracketType(aCh) == PAIRED_BRACKET_TYPE_OPEN) { /* opening bracket */
- if (!AddOpening(match, aPosition)) {
- return false;
- }
- }
- }
- if (level & NSBIDI_LEVEL_OVERRIDE) { /* X4, X5 */
- newProp = GET_LR_FROM_LEVEL(level);
- if (dirProp != S && dirProp != WS && dirProp != O_N) {
- aDirProps[aPosition] = newProp;
- }
- lastIsoRun.lastBase = newProp;
- lastIsoRun.lastStrong = newProp;
- lastIsoRun.contextDir = newProp;
- lastIsoRun.contextPos = aPosition;
- } else if (IS_STRONG_TYPE(dirProp)) {
- newProp = DirFromStrong(dirProp);
- lastIsoRun.lastBase = dirProp;
- lastIsoRun.lastStrong = dirProp;
- lastIsoRun.contextDir = newProp;
- lastIsoRun.contextPos = aPosition;
- } else if (dirProp == EN) {
- lastIsoRun.lastBase = EN;
- if (lastIsoRun.lastStrong == L) {
- newProp = L; /* W7 */
- aDirProps[aPosition] = ENL;
- lastIsoRun.contextDir = L;
- lastIsoRun.contextPos = aPosition;
- } else {
- newProp = R; /* N0 */
- if (lastIsoRun.lastStrong == AL) {
- aDirProps[aPosition] = AN; /* W2 */
- } else {
- aDirProps[aPosition] = ENR;
- }
- lastIsoRun.contextDir = R;
- lastIsoRun.contextPos = aPosition;
- }
- } else if (dirProp == AN) {
- newProp = R; /* N0 */
- lastIsoRun.lastBase = AN;
- lastIsoRun.contextDir = R;
- lastIsoRun.contextPos = aPosition;
- } else if (dirProp == NSM) {
- /* if the last real char was ON, change NSM to ON so that it
- will stay ON even if the last real char is a bracket which
- may be changed to L or R */
- newProp = lastIsoRun.lastBase;
- if (newProp == O_N) {
- aDirProps[aPosition] = newProp;
- }
- } else {
- newProp = dirProp;
- lastIsoRun.lastBase = dirProp;
- }
- if (IS_STRONG_TYPE(newProp)) {
- uint16_t flag = DIRPROP_FLAG(DirFromStrong(newProp));
- for (int32_t i = lastIsoRun.start; i < lastIsoRun.limit; i++) {
- if (aPosition > mOpenings[i].position) {
- mOpenings[i].flags |= flag;
- }
- }
- }
- return true;
-}
-
-/* perform (X1)..(X9) ------------------------------------------------------- */
-
-/*
- * Resolve the explicit levels as specified by explicit embedding codes.
- * Recalculate the flags to have them reflect the real properties
- * after taking the explicit embeddings into account.
- *
- * The Bidi algorithm is designed to result in the same behavior whether embedding
- * levels are externally specified (from "styled text", supposedly the preferred
- * method) or set by explicit embedding codes (LRx, RLx, PDF, FSI, PDI) in the plain text.
- * That is why (X9) instructs to remove all not-isolate explicit codes (and BN).
- * However, in a real implementation, this removal of these codes and their index
- * positions in the plain text is undesirable since it would result in
- * reallocated, reindexed text.
- * Instead, this implementation leaves the codes in there and just ignores them
- * in the subsequent processing.
- * In order to get the same reordering behavior, positions with a BN or a not-isolate
- * explicit embedding code just get the same level assigned as the last "real"
- * character.
- *
- * Some implementations, not this one, then overwrite some of these
- * directionality properties at "real" same-level-run boundaries by
- * L or R codes so that the resolution of weak types can be performed on the
- * entire paragraph at once instead of having to parse it once more and
- * perform that resolution on same-level-runs.
- * This limits the scope of the implicit rules in effectively
- * the same way as the run limits.
- *
- * Instead, this implementation does not modify these codes.
- * On one hand, the paragraph has to be scanned for same-level-runs, but
- * on the other hand, this saves another loop to reset these codes,
- * or saves making and modifying a copy of dirProps[].
- *
- *
- * Note that (Pn) and (Xn) changed significantly from version 4 of the Bidi algorithm.
- *
- *
- * Handling the stack of explicit levels (Xn):
- *
- * With the Bidi stack of explicit levels, as pushed with each
- * LRE, RLE, LRO, and RLO, LRI, RLI, and FSI and popped with each PDF and PDI,
- * the explicit level must never exceed NSBIDI_MAX_EXPLICIT_LEVEL.
- *
- * In order to have a correct push-pop semantics even in the case of overflows,
- * overflow counters and a valid isolate counter are used as described in UAX#9
- * section 3.3.2 "Explicit Levels and Direction".
- *
- * This implementation assumes that NSBIDI_MAX_EXPLICIT_LEVEL is odd.
- */
-
-void nsBidi::ResolveExplicitLevels(nsBidiDirection *aDirection, const char16_t *aText)
-{
- DirProp *dirProps=mDirProps;
- nsBidiLevel *levels=mLevels;
-
- int32_t i=0, length=mLength;
- Flags flags=mFlags; /* collect all directionalities in the text */
- DirProp dirProp;
- nsBidiLevel level=mParaLevel;
- nsBidiDirection direction;
-
- mIsolateCount = 0;
-
- /* determine if the text is mixed-directional or single-directional */
- direction=DirectionFromFlags(flags);
-
- /* we may not need to resolve any explicit levels */
- if(direction!=NSBIDI_MIXED) {
- /* not mixed directionality: levels don't matter - trailingWSStart will be 0 */
- } else if(!(flags&(MASK_EXPLICIT|MASK_ISO))) {
- BracketData bracketData(this);
- /* no embeddings, set all levels to the paragraph level */
- for(i=0; i<length; ++i) {
- levels[i]=level;
- if (dirProps[i] == BN) {
- continue;
- }
- if (!bracketData.ProcessChar(i, aText[i], mDirProps, mLevels)) {
- NS_WARNING("BracketData::ProcessChar failed, out of memory?");
- // Ran out of memory for deeply-nested openings; give up and
- // return LTR. This could presumably result in incorrect display,
- // but in practice it won't happen except in some artificially-
- // constructed torture test -- which is just as likely to die
- // altogether with an OOM failure.
- *aDirection = NSBIDI_LTR;
- return;
- }
- }
- } else {
- /* continue to perform (Xn) */
-
- /* (X1) level is set for all codes, embeddingLevel keeps track of the push/pop operations */
- /* both variables may carry the NSBIDI_LEVEL_OVERRIDE flag to indicate the override status */
- nsBidiLevel embeddingLevel = level, newLevel;
- nsBidiLevel previousLevel = level; /* previous level for regular (not CC) characters */
- int32_t lastDirControlCharPos = 0; /* index of last effective LRx,RLx, PDx */
-
- uint16_t stack[NSBIDI_MAX_EXPLICIT_LEVEL + 2]; /* we never push anything >=NSBIDI_MAX_EXPLICIT_LEVEL
- but we need one more entry as base */
- int32_t stackLast = 0;
- int32_t overflowIsolateCount = 0;
- int32_t overflowEmbeddingCount = 0;
- int32_t validIsolateCount = 0;
-
- BracketData bracketData(this);
-
- stack[0] = level;
-
- /* recalculate the flags */
- flags=0;
-
- /* since we assume that this is a single paragraph, we ignore (X8) */
- for(i=0; i<length; ++i) {
- dirProp=dirProps[i];
- switch(dirProp) {
- case LRE:
- case RLE:
- case LRO:
- case RLO:
- /* (X2, X3, X4, X5) */
- flags |= DIRPROP_FLAG(BN);
- levels[i] = previousLevel;
- if (dirProp == LRE || dirProp == LRO) {
- newLevel = (embeddingLevel + 2) & ~(NSBIDI_LEVEL_OVERRIDE | 1); /* least greater even level */
- } else {
- newLevel = ((embeddingLevel & ~NSBIDI_LEVEL_OVERRIDE) + 1) | 1; /* least greater odd level */
- }
- if(newLevel <= NSBIDI_MAX_EXPLICIT_LEVEL && overflowIsolateCount == 0 && overflowEmbeddingCount == 0) {
- lastDirControlCharPos = i;
- embeddingLevel = newLevel;
- if (dirProp == LRO || dirProp == RLO) {
- embeddingLevel |= NSBIDI_LEVEL_OVERRIDE;
- }
- stackLast++;
- stack[stackLast] = embeddingLevel;
- /* we don't need to set NSBIDI_LEVEL_OVERRIDE off for LRE and RLE
- since this has already been done for newLevel which is
- the source for embeddingLevel.
- */
- } else {
- if (overflowIsolateCount == 0) {
- overflowEmbeddingCount++;
- }
- }
- break;
-
- case PDF:
- /* (X7) */
- flags |= DIRPROP_FLAG(BN);
- levels[i] = previousLevel;
- /* handle all the overflow cases first */
- if (overflowIsolateCount) {
- break;
- }
- if (overflowEmbeddingCount) {
- overflowEmbeddingCount--;
- break;
- }
- if (stackLast > 0 && stack[stackLast] < ISOLATE) { /* not an isolate entry */
- lastDirControlCharPos = i;
- stackLast--;
- embeddingLevel = stack[stackLast];
- }
- break;
-
- case LRI:
- case RLI:
- flags |= DIRPROP_FLAG(O_N) | DIRPROP_FLAG_LR(embeddingLevel);
- levels[i] = NO_OVERRIDE(embeddingLevel);
- if (NO_OVERRIDE(embeddingLevel) != NO_OVERRIDE(previousLevel)) {
- bracketData.ProcessBoundary(lastDirControlCharPos, previousLevel,
- embeddingLevel, mDirProps);
- flags |= DIRPROP_FLAG_MULTI_RUNS;
- }
- previousLevel = embeddingLevel;
- /* (X5a, X5b) */
- if (dirProp == LRI) {
- newLevel = (embeddingLevel + 2) & ~(NSBIDI_LEVEL_OVERRIDE | 1); /* least greater even level */
- } else {
- newLevel = ((embeddingLevel & ~NSBIDI_LEVEL_OVERRIDE) + 1) | 1; /* least greater odd level */
- }
- if (newLevel <= NSBIDI_MAX_EXPLICIT_LEVEL && overflowIsolateCount == 0 && overflowEmbeddingCount == 0) {
- flags |= DIRPROP_FLAG(dirProp);
- lastDirControlCharPos = i;
- previousLevel = embeddingLevel;
- validIsolateCount++;
- if (validIsolateCount > mIsolateCount) {
- mIsolateCount = validIsolateCount;
- }
- embeddingLevel = newLevel;
- stackLast++;
- stack[stackLast] = embeddingLevel + ISOLATE;
- bracketData.ProcessLRI_RLI(embeddingLevel);
- } else {
- /* make it so that it is handled by AdjustWSLevels() */
- dirProps[i] = WS;
- overflowIsolateCount++;
- }
- break;
-
- case PDI:
- if (NO_OVERRIDE(embeddingLevel) != NO_OVERRIDE(previousLevel)) {
- bracketData.ProcessBoundary(lastDirControlCharPos, previousLevel,
- embeddingLevel, mDirProps);
- flags |= DIRPROP_FLAG_MULTI_RUNS;
- }
- /* (X6a) */
- if (overflowIsolateCount) {
- overflowIsolateCount--;
- /* make it so that it is handled by AdjustWSLevels() */
- dirProps[i] = WS;
- } else if (validIsolateCount) {
- flags |= DIRPROP_FLAG(PDI);
- lastDirControlCharPos = i;
- overflowEmbeddingCount = 0;
- while (stack[stackLast] < ISOLATE) {
- /* pop embedding entries */
- /* until the last isolate entry */
- stackLast--;
-
- // Since validIsolateCount is true, there must be an isolate entry
- // on the stack, so the stack is guaranteed to not be empty.
- // Still, to eliminate a warning from coverity, we use an assertion.
- MOZ_ASSERT(stackLast > 0);
- }
- stackLast--; /* pop also the last isolate entry */
- MOZ_ASSERT(stackLast >= 0); // For coverity
- validIsolateCount--;
- bracketData.ProcessPDI();
- } else {
- /* make it so that it is handled by AdjustWSLevels() */
- dirProps[i] = WS;
- }
- embeddingLevel = stack[stackLast] & ~ISOLATE;
- flags |= DIRPROP_FLAG(O_N) | DIRPROP_FLAG_LR(embeddingLevel);
- previousLevel = embeddingLevel;
- levels[i] = NO_OVERRIDE(embeddingLevel);
- break;
-
- case B:
- /*
- * We do not expect to see a paragraph separator (B),
- */
- NS_NOTREACHED("Unexpected paragraph separator");
- break;
-
- case BN:
- /* BN, LRE, RLE, and PDF are supposed to be removed (X9) */
- /* they will get their levels set correctly in AdjustWSLevels() */
- levels[i] = previousLevel;
- flags |= DIRPROP_FLAG(BN);
- break;
-
- default:
- /* all other types get the "real" level */
- if (NO_OVERRIDE(embeddingLevel) != NO_OVERRIDE(previousLevel)) {
- bracketData.ProcessBoundary(lastDirControlCharPos, previousLevel,
- embeddingLevel, mDirProps);
- flags |= DIRPROP_FLAG_MULTI_RUNS;
- if (embeddingLevel & NSBIDI_LEVEL_OVERRIDE) {
- flags |= DIRPROP_FLAG_O(embeddingLevel);
- } else {
- flags |= DIRPROP_FLAG_E(embeddingLevel);
- }
- }
- previousLevel = embeddingLevel;
- levels[i] = embeddingLevel;
- if (!bracketData.ProcessChar(i, aText[i], mDirProps, mLevels)) {
- NS_WARNING("BracketData::ProcessChar failed, out of memory?");
- *aDirection = NSBIDI_LTR;
- return;
- }
- flags |= DIRPROP_FLAG(dirProps[i]);
- break;
- }
- }
-
- if(flags&MASK_EMBEDDING) {
- flags|=DIRPROP_FLAG_LR(mParaLevel);
- }
-
- /* subsequently, ignore the explicit codes and BN (X9) */
-
- /* again, determine if the text is mixed-directional or single-directional */
- mFlags=flags;
- direction=DirectionFromFlags(flags);
- }
-
- *aDirection = direction;
-}
-
-/* determine if the text is mixed-directional or single-directional */
-nsBidiDirection nsBidi::DirectionFromFlags(Flags aFlags)
-{
- /* if the text contains AN and neutrals, then some neutrals may become RTL */
- if(!(aFlags&MASK_RTL || (aFlags&DIRPROP_FLAG(AN) && aFlags&MASK_POSSIBLE_N))) {
- return NSBIDI_LTR;
- } else if(!(aFlags&MASK_LTR)) {
- return NSBIDI_RTL;
- } else {
- return NSBIDI_MIXED;
- }
-}
-
-/******************************************************************
- The Properties state machine table
-*******************************************************************
-
- All table cells are 8 bits:
- bits 0..4: next state
- bits 5..7: action to perform (if > 0)
-
- Cells may be of format "n" where n represents the next state
- (except for the rightmost column).
- Cells may also be of format "s(x,y)" where x represents an action
- to perform and y represents the next state.
-
-*******************************************************************
- Definitions and type for properties state table
-*******************************************************************
-*/
-#define IMPTABPROPS_COLUMNS 16
-#define IMPTABPROPS_RES (IMPTABPROPS_COLUMNS - 1)
-#define GET_STATEPROPS(cell) ((cell)&0x1f)
-#define GET_ACTIONPROPS(cell) ((cell)>>5)
-#undef s
-#define s(action, newState) ((uint8_t)(newState+(action<<5)))
-
-static const uint8_t groupProp[] = /* dirProp regrouped */
-{
-/* L R EN ES ET AN CS B S WS ON LRE LRO AL RLE RLO PDF NSM BN FSI LRI RLI PDI ENL ENR */
- 0, 1, 2, 7, 8, 3, 9, 6, 5, 4, 4, 10, 10, 12, 10, 10, 10, 11, 10, 4, 4, 4, 4, 13, 14
-};
-
-/******************************************************************
-
- PROPERTIES STATE TABLE
-
- In table impTabProps,
- - the ON column regroups ON and WS, FSI, RLI, LRI and PDI
- - the BN column regroups BN, LRE, RLE, LRO, RLO, PDF
- - the Res column is the reduced property assigned to a run
-
- Action 1: process current run1, init new run1
- 2: init new run2
- 3: process run1, process run2, init new run1
- 4: process run1, set run1=run2, init new run2
-
- Notes:
- 1) This table is used in ResolveImplicitLevels().
- 2) This table triggers actions when there is a change in the Bidi
- property of incoming characters (action 1).
- 3) Most such property sequences are processed immediately (in
- fact, passed to ProcessPropertySeq().
- 4) However, numbers are assembled as one sequence. This means
- that undefined situations (like CS following digits, until
- it is known if the next char will be a digit) are held until
- following chars define them.
- Example: digits followed by CS, then comes another CS or ON;
- the digits will be processed, then the CS assigned
- as the start of an ON sequence (action 3).
- 5) There are cases where more than one sequence must be
- processed, for instance digits followed by CS followed by L:
- the digits must be processed as one sequence, and the CS
- must be processed as an ON sequence, all this before starting
- assembling chars for the opening L sequence.
-
-
-*/
-static const uint8_t impTabProps[][IMPTABPROPS_COLUMNS] =
-{
-/* L , R , EN , AN , ON , S , B , ES , ET , CS , BN , NSM , AL , ENL , ENR , Res */
-/* 0 Init */ { 1 , 2 , 4 , 5 , 7 , 15 , 17 , 7 , 9 , 7 , 0 , 7 , 3 , 18 , 21 , DirProp_ON },
-/* 1 L */ { 1 , s(1,2), s(1,4), s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), s(1,9), s(1,7), 1 , 1 , s(1,3),s(1,18),s(1,21), DirProp_L },
-/* 2 R */ { s(1,1), 2 , s(1,4), s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), s(1,9), s(1,7), 2 , 2 , s(1,3),s(1,18),s(1,21), DirProp_R },
-/* 3 AL */ { s(1,1), s(1,2), s(1,6), s(1,6), s(1,8),s(1,16),s(1,17), s(1,8), s(1,8), s(1,8), 3 , 3 , 3 ,s(1,18),s(1,21), DirProp_R },
-/* 4 EN */ { s(1,1), s(1,2), 4 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,10), 11 ,s(2,10), 4 , 4 , s(1,3), 18 , 21 , DirProp_EN },
-/* 5 AN */ { s(1,1), s(1,2), s(1,4), 5 , s(1,7),s(1,15),s(1,17), s(1,7), s(1,9),s(2,12), 5 , 5 , s(1,3),s(1,18),s(1,21), DirProp_AN },
-/* 6 AL:EN/AN */ { s(1,1), s(1,2), 6 , 6 , s(1,8),s(1,16),s(1,17), s(1,8), s(1,8),s(2,13), 6 , 6 , s(1,3), 18 , 21 , DirProp_AN },
-/* 7 ON */ { s(1,1), s(1,2), s(1,4), s(1,5), 7 ,s(1,15),s(1,17), 7 ,s(2,14), 7 , 7 , 7 , s(1,3),s(1,18),s(1,21), DirProp_ON },
-/* 8 AL:ON */ { s(1,1), s(1,2), s(1,6), s(1,6), 8 ,s(1,16),s(1,17), 8 , 8 , 8 , 8 , 8 , s(1,3),s(1,18),s(1,21), DirProp_ON },
-/* 9 ET */ { s(1,1), s(1,2), 4 , s(1,5), 7 ,s(1,15),s(1,17), 7 , 9 , 7 , 9 , 9 , s(1,3), 18 , 21 , DirProp_ON },
-/*10 EN+ES/CS */ { s(3,1), s(3,2), 4 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7), 10 , s(4,7), s(3,3), 18 , 21 , DirProp_EN },
-/*11 EN+ET */ { s(1,1), s(1,2), 4 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), 11 , s(1,7), 11 , 11 , s(1,3), 18 , 21 , DirProp_EN },
-/*12 AN+CS */ { s(3,1), s(3,2), s(3,4), 5 , s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7), 12 , s(4,7), s(3,3),s(3,18),s(3,21), DirProp_AN },
-/*13 AL:EN/AN+CS */ { s(3,1), s(3,2), 6 , 6 , s(4,8),s(3,16),s(3,17), s(4,8), s(4,8), s(4,8), 13 , s(4,8), s(3,3), 18 , 21 , DirProp_AN },
-/*14 ON+ET */ { s(1,1), s(1,2), s(4,4), s(1,5), 7 ,s(1,15),s(1,17), 7 , 14 , 7 , 14 , 14 , s(1,3),s(4,18),s(4,21), DirProp_ON },
-/*15 S */ { s(1,1), s(1,2), s(1,4), s(1,5), s(1,7), 15 ,s(1,17), s(1,7), s(1,9), s(1,7), 15 , s(1,7), s(1,3),s(1,18),s(1,21), DirProp_S },
-/*16 AL:S */ { s(1,1), s(1,2), s(1,6), s(1,6), s(1,8), 16 ,s(1,17), s(1,8), s(1,8), s(1,8), 16 , s(1,8), s(1,3),s(1,18),s(1,21), DirProp_S },
-/*17 B */ { s(1,1), s(1,2), s(1,4), s(1,5), s(1,7),s(1,15), 17 , s(1,7), s(1,9), s(1,7), 17 , s(1,7), s(1,3),s(1,18),s(1,21), DirProp_B },
-/*18 ENL */ { s(1,1), s(1,2), 18 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,19), 20 ,s(2,19), 18 , 18 , s(1,3), 18 , 21 , DirProp_L },
-/*19 ENL+ES/CS */ { s(3,1), s(3,2), 18 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7), 19 , s(4,7), s(3,3), 18 , 21 , DirProp_L },
-/*20 ENL+ET */ { s(1,1), s(1,2), 18 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), 20 , s(1,7), 20 , 20 , s(1,3), 18 , 21 , DirProp_L },
-/*21 ENR */ { s(1,1), s(1,2), 21 , s(1,5), s(1,7),s(1,15),s(1,17),s(2,22), 23 ,s(2,22), 21 , 21 , s(1,3), 18 , 21 , DirProp_AN },
-/*22 ENR+ES/CS */ { s(3,1), s(3,2), 21 , s(3,5), s(4,7),s(3,15),s(3,17), s(4,7),s(4,14), s(4,7), 22 , s(4,7), s(3,3), 18 , 21 , DirProp_AN },
-/*23 ENR+ET */ { s(1,1), s(1,2), 21 , s(1,5), s(1,7),s(1,15),s(1,17), s(1,7), 23 , s(1,7), 23 , 23 , s(1,3), 18 , 21 , DirProp_AN }
-};
-
-/* we must undef macro s because the levels table have a different
- * structure (4 bits for action and 4 bits for next state.
- */
-#undef s
-
-/******************************************************************
- The levels state machine tables
-*******************************************************************
-
- All table cells are 8 bits:
- bits 0..3: next state
- bits 4..7: action to perform (if > 0)
-
- Cells may be of format "n" where n represents the next state
- (except for the rightmost column).
- Cells may also be of format "s(x,y)" where x represents an action
- to perform and y represents the next state.
-
- This format limits each table to 16 states each and to 15 actions.
-
-*******************************************************************
- Definitions and type for levels state tables
-*******************************************************************
-*/
-#define IMPTABLEVELS_RES (IMPTABLEVELS_COLUMNS - 1)
-#define GET_STATE(cell) ((cell)&0x0f)
-#define GET_ACTION(cell) ((cell)>>4)
-#define s(action, newState) ((uint8_t)(newState+(action<<4)))
-
-/******************************************************************
-
- LEVELS STATE TABLES
-
- In all levels state tables,
- - state 0 is the initial state
- - the Res column is the increment to add to the text level
- for this property sequence.
-
- The impAct arrays for each table of a pair map the local action
- numbers of the table to the total list of actions. For instance,
- action 2 in a given table corresponds to the action number which
- appears in entry [2] of the impAct array for that table.
- The first entry of all impAct arrays must be 0.
-
- Action 1: init conditional sequence
- 2: prepend conditional sequence to current sequence
- 3: set ON sequence to new level - 1
- 4: init EN/AN/ON sequence
- 5: fix EN/AN/ON sequence followed by R
- 6: set previous level sequence to level 2
-
- Notes:
- 1) These tables are used in ProcessPropertySeq(). The input
- is property sequences as determined by ResolveImplicitLevels.
- 2) Most such property sequences are processed immediately
- (levels are assigned).
- 3) However, some sequences cannot be assigned a final level till
- one or more following sequences are received. For instance,
- ON following an R sequence within an even-level paragraph.
- If the following sequence is R, the ON sequence will be
- assigned basic run level+1, and so will the R sequence.
- 4) S is generally handled like ON, since its level will be fixed
- to paragraph level in AdjustWSLevels().
-
-*/
-
-static const ImpTab impTabL = /* Even paragraph level */
-/* In this table, conditional sequences receive the higher possible level
- until proven otherwise.
-*/
-{
-/* L , R , EN , AN , ON , S , B , Res */
-/* 0 : init */ { 0 , 1 , 0 , 2 , 0 , 0 , 0 , 0 },
-/* 1 : R */ { 0 , 1 , 3 , 3 , s(1,4), s(1,4), 0 , 1 },
-/* 2 : AN */ { 0 , 1 , 0 , 2 , s(1,5), s(1,5), 0 , 2 },
-/* 3 : R+EN/AN */ { 0 , 1 , 3 , 3 , s(1,4), s(1,4), 0 , 2 },
-/* 4 : R+ON */ { s(2,0), 1 , 3 , 3 , 4 , 4 , s(2,0), 1 },
-/* 5 : AN+ON */ { s(2,0), 1 , s(2,0), 2 , 5 , 5 , s(2,0), 1 }
-};
-static const ImpTab impTabR = /* Odd paragraph level */
-/* In this table, conditional sequences receive the lower possible level
- until proven otherwise.
-*/
-{
-/* L , R , EN , AN , ON , S , B , Res */
-/* 0 : init */ { 1 , 0 , 2 , 2 , 0 , 0 , 0 , 0 },
-/* 1 : L */ { 1 , 0 , 1 , 3 , s(1,4), s(1,4), 0 , 1 },
-/* 2 : EN/AN */ { 1 , 0 , 2 , 2 , 0 , 0 , 0 , 1 },
-/* 3 : L+AN */ { 1 , 0 , 1 , 3 , 5 , 5 , 0 , 1 },
-/* 4 : L+ON */ { s(2,1), 0 , s(2,1), 3 , 4 , 4 , 0 , 0 },
-/* 5 : L+AN+ON */ { 1 , 0 , 1 , 3 , 5 , 5 , 0 , 0 }
-};
-
-#undef s
-
-static ImpAct impAct0 = {0,1,2,3,4,5,6};
-static PImpTab impTab[2] = {impTabL, impTabR};
-
-/*------------------------------------------------------------------------*/
-
-/* perform rules (Wn), (Nn), and (In) on a run of the text ------------------ */
-
-/*
- * This implementation of the (Wn) rules applies all rules in one pass.
- * In order to do so, it needs a look-ahead of typically 1 character
- * (except for W5: sequences of ET) and keeps track of changes
- * in a rule Wp that affect a later Wq (p<q).
- *
- * The (Nn) and (In) rules are also performed in that same single loop,
- * but effectively one iteration behind for white space.
- *
- * Since all implicit rules are performed in one step, it is not necessary
- * to actually store the intermediate directional properties in dirProps[].
- */
-
-void nsBidi::ProcessPropertySeq(LevState *pLevState, uint8_t _prop, int32_t start, int32_t limit)
-{
- uint8_t cell, oldStateSeq, actionSeq;
- PImpTab pImpTab = pLevState->pImpTab;
- PImpAct pImpAct = pLevState->pImpAct;
- nsBidiLevel* levels = mLevels;
- nsBidiLevel level, addLevel;
- int32_t start0, k;
-
- start0 = start; /* save original start position */
- oldStateSeq = (uint8_t)pLevState->state;
- cell = pImpTab[oldStateSeq][_prop];
- pLevState->state = GET_STATE(cell); /* isolate the new state */
- actionSeq = pImpAct[GET_ACTION(cell)]; /* isolate the action */
- addLevel = pImpTab[pLevState->state][IMPTABLEVELS_RES];
-
- if(actionSeq) {
- switch(actionSeq) {
- case 1: /* init ON seq */
- pLevState->startON = start0;
- break;
-
- case 2: /* prepend ON seq to current seq */
- MOZ_ASSERT(pLevState->startON >= 0, "no valid ON sequence start!");
- start = pLevState->startON;
- break;
-
- default: /* we should never get here */
- MOZ_ASSERT(false);
- break;
- }
- }
- if(addLevel || (start < start0)) {
- level = pLevState->runLevel + addLevel;
- if (start >= pLevState->runStart) {
- for (k = start; k < limit; k++) {
- levels[k] = level;
- }
- } else {
- DirProp *dirProps = mDirProps, dirProp;
- int32_t isolateCount = 0;
- for (k = start; k < limit; k++) {
- dirProp = dirProps[k];
- if (dirProp == PDI) {
- isolateCount--;
- }
- if (isolateCount == 0) {
- levels[k]=level;
- }
- if (dirProp == LRI || dirProp == RLI) {
- isolateCount++;
- }
- }
- }
- }
-}
-
-void nsBidi::ResolveImplicitLevels(int32_t aStart, int32_t aLimit,
- DirProp aSOR, DirProp aEOR)
-{
- const DirProp *dirProps = mDirProps;
- DirProp dirProp;
- LevState levState;
- int32_t i, start1, start2;
- uint16_t oldStateImp, stateImp, actionImp;
- uint8_t gprop, resProp, cell;
-
- /* initialize for property and levels state tables */
- levState.runStart = aStart;
- levState.runLevel = mLevels[aStart];
- levState.pImpTab = impTab[levState.runLevel & 1];
- levState.pImpAct = impAct0;
- levState.startON = -1; /* initialize to invalid start position */
-
- /* The isolates[] entries contain enough information to
- resume the bidi algorithm in the same state as it was
- when it was interrupted by an isolate sequence. */
- if (dirProps[aStart] == PDI && mIsolateCount >= 0) {
- start1 = mIsolates[mIsolateCount].start1;
- stateImp = mIsolates[mIsolateCount].stateImp;
- levState.state = mIsolates[mIsolateCount].state;
- mIsolateCount--;
- } else {
- levState.startON = -1;
- start1 = aStart;
- if (dirProps[aStart] == NSM) {
- stateImp = 1 + aSOR;
- } else {
- stateImp = 0;
- }
- levState.state = 0;
- ProcessPropertySeq(&levState, aSOR, aStart, aStart);
- }
- start2 = aStart;
-
- for (i = aStart; i <= aLimit; i++) {
- if (i >= aLimit) {
- int32_t k;
- for (k = aLimit - 1;
- k > aStart && (DIRPROP_FLAG(dirProps[k]) & MASK_BN_EXPLICIT); k--) {
- // empty loop body
- }
- dirProp = mDirProps[k];
- if (dirProp == LRI || dirProp == RLI) {
- break; /* no forced closing for sequence ending with LRI/RLI */
- }
- gprop = aEOR;
- } else {
- DirProp prop;
- prop = dirProps[i];
- gprop = groupProp[prop];
- }
- oldStateImp = stateImp;
- cell = impTabProps[oldStateImp][gprop];
- stateImp = GET_STATEPROPS(cell); /* isolate the new state */
- actionImp = GET_ACTIONPROPS(cell); /* isolate the action */
- if ((i == aLimit) && (actionImp == 0)) {
- /* there is an unprocessed sequence if its property == eor */
- actionImp = 1; /* process the last sequence */
- }
- if (actionImp) {
- resProp = impTabProps[oldStateImp][IMPTABPROPS_RES];
- switch (actionImp) {
- case 1: /* process current seq1, init new seq1 */
- ProcessPropertySeq(&levState, resProp, start1, i);
- start1 = i;
- break;
- case 2: /* init new seq2 */
- start2 = i;
- break;
- case 3: /* process seq1, process seq2, init new seq1 */
- ProcessPropertySeq(&levState, resProp, start1, start2);
- ProcessPropertySeq(&levState, DirProp_ON, start2, i);
- start1 = i;
- break;
- case 4: /* process seq1, set seq1=seq2, init new seq2 */
- ProcessPropertySeq(&levState, resProp, start1, start2);
- start1 = start2;
- start2 = i;
- break;
- default: /* we should never get here */
- MOZ_ASSERT(false);
- break;
- }
- }
- }
-
- for (i = aLimit - 1;
- i > aStart && (DIRPROP_FLAG(dirProps[i]) & MASK_BN_EXPLICIT); i--) {
- // empty loop body
- }
- dirProp = dirProps[i];
- if ((dirProp == LRI || dirProp == RLI) && aLimit < mLength) {
- mIsolateCount++;
- mIsolates[mIsolateCount].stateImp = stateImp;
- mIsolates[mIsolateCount].state = levState.state;
- mIsolates[mIsolateCount].start1 = start1;
- } else {
- ProcessPropertySeq(&levState, aEOR, aLimit, aLimit);
- }
-}
-
-
-/* perform (L1) and (X9) ---------------------------------------------------- */
-
-/*
- * Reset the embedding levels for some non-graphic characters (L1).
- * This function also sets appropriate levels for BN, and
- * explicit embedding types that are supposed to have been removed
- * from the paragraph in (X9).
- */
-void nsBidi::AdjustWSLevels()
-{
- const DirProp *dirProps=mDirProps;
- nsBidiLevel *levels=mLevels;
- int32_t i;
-
- if(mFlags&MASK_WS) {
- nsBidiLevel paraLevel=mParaLevel;
- Flags flag;
-
- i=mTrailingWSStart;
- while(i>0) {
- /* reset a sequence of WS/BN before eop and B/S to the paragraph paraLevel */
- while (i > 0 && DIRPROP_FLAG(dirProps[--i]) & MASK_WS) {
- levels[i]=paraLevel;
- }
-
- /* reset BN to the next character's paraLevel until B/S, which restarts above loop */
- /* here, i+1 is guaranteed to be <length */
- while(i>0) {
- flag = DIRPROP_FLAG(dirProps[--i]);
- if(flag&MASK_BN_EXPLICIT) {
- levels[i]=levels[i+1];
- } else if(flag&MASK_B_S) {
- levels[i]=paraLevel;
- break;
- }
- }
- }
- }
-}
-
-nsresult nsBidi::GetDirection(nsBidiDirection* aDirection)
-{
- *aDirection = mDirection;
- return NS_OK;
-}
-
-nsresult nsBidi::GetParaLevel(nsBidiLevel* aParaLevel)
-{
- *aParaLevel = mParaLevel;
- return NS_OK;
-}
-
-nsresult nsBidi::GetLogicalRun(int32_t aLogicalStart, int32_t *aLogicalLimit, nsBidiLevel *aLevel)
-{
- int32_t length = mLength;
-
- if(aLogicalStart<0 || length<=aLogicalStart) {
- return NS_ERROR_INVALID_ARG;
- }
-
- int32_t runCount, visualStart, logicalLimit, logicalFirst, i;
- Run iRun;
-
- /* CountRuns will check VALID_PARA_OR_LINE */
- nsresult rv = CountRuns(&runCount);
- if (NS_FAILED(rv)) {
- return rv;
- }
-
- visualStart = logicalLimit = 0;
- iRun = mRuns[0];
-
- for (i = 0; i < runCount; i++) {
- iRun = mRuns[i];
- logicalFirst = GET_INDEX(iRun.logicalStart);
- logicalLimit = logicalFirst + iRun.visualLimit - visualStart;
- if ((aLogicalStart >= logicalFirst) && (aLogicalStart < logicalLimit)) {
- break;
- }
- visualStart = iRun.visualLimit;
- }
- if (aLogicalLimit) {
- *aLogicalLimit = logicalLimit;
- }
- if (aLevel) {
- if (mDirection != NSBIDI_MIXED || aLogicalStart >= mTrailingWSStart) {
- *aLevel = mParaLevel;
- } else {
- *aLevel = mLevels[aLogicalStart];
- }
- }
- return NS_OK;
-}
-
-/* runs API functions ------------------------------------------------------- */
-
-nsresult nsBidi::CountRuns(int32_t* aRunCount)
-{
- if(mRunCount<0 && !GetRuns()) {
- return NS_ERROR_OUT_OF_MEMORY;
- } else {
- if (aRunCount)
- *aRunCount = mRunCount;
- return NS_OK;
- }
-}
-
-nsresult nsBidi::GetVisualRun(int32_t aRunIndex, int32_t *aLogicalStart, int32_t *aLength, nsBidiDirection *aDirection)
-{
- if( aRunIndex<0 ||
- (mRunCount==-1 && !GetRuns()) ||
- aRunIndex>=mRunCount
- ) {
- *aDirection = NSBIDI_LTR;
- return NS_OK;
- } else {
- int32_t start=mRuns[aRunIndex].logicalStart;
- if(aLogicalStart!=nullptr) {
- *aLogicalStart=GET_INDEX(start);
- }
- if(aLength!=nullptr) {
- if(aRunIndex>0) {
- *aLength=mRuns[aRunIndex].visualLimit-
- mRuns[aRunIndex-1].visualLimit;
- } else {
- *aLength=mRuns[0].visualLimit;
- }
- }
- *aDirection = (nsBidiDirection)GET_ODD_BIT(start);
- return NS_OK;
- }
-}
-
-/* compute the runs array --------------------------------------------------- */
-
-/*
- * Compute the runs array from the levels array.
- * After GetRuns() returns true, runCount is guaranteed to be >0
- * and the runs are reordered.
- * Odd-level runs have visualStart on their visual right edge and
- * they progress visually to the left.
- */
-bool nsBidi::GetRuns()
-{
- /*
- * This method returns immediately if the runs are already set. This
- * includes the case of length==0 (handled in setPara)..
- */
- if (mRunCount >= 0) {
- return true;
- }
-
- if(mDirection!=NSBIDI_MIXED) {
- /* simple, single-run case - this covers length==0 */
- GetSingleRun(mParaLevel);
- } else /* NSBIDI_MIXED, length>0 */ {
- /* mixed directionality */
- int32_t length=mLength, limit=mTrailingWSStart;
-
- /*
- * If there are WS characters at the end of the line
- * and the run preceding them has a level different from
- * paraLevel, then they will form their own run at paraLevel (L1).
- * Count them separately.
- * We need some special treatment for this in order to not
- * modify the levels array which a line nsBidi object shares
- * with its paragraph parent and its other line siblings.
- * In other words, for the trailing WS, it may be
- * levels[]!=paraLevel but we have to treat it like it were so.
- */
- nsBidiLevel *levels=mLevels;
- int32_t i, runCount;
- nsBidiLevel level=NSBIDI_DEFAULT_LTR; /* initialize with no valid level */
-
- /* count the runs, there is at least one non-WS run, and limit>0 */
- runCount=0;
- for(i=0; i<limit; ++i) {
- /* increment runCount at the start of each run */
- if(levels[i]!=level) {
- ++runCount;
- level=levels[i];
- }
- }
-
- /*
- * We don't need to see if the last run can be merged with a trailing
- * WS run because SetTrailingWSStart() would have done that.
- */
- if(runCount==1 && limit==length) {
- /* There is only one non-WS run and no trailing WS-run. */
- GetSingleRun(levels[0]);
- } else /* runCount>1 || limit<length */ {
- /* allocate and set the runs */
- Run *runs;
- int32_t runIndex, start;
- nsBidiLevel minLevel=NSBIDI_MAX_EXPLICIT_LEVEL+1, maxLevel=0;
-
- /* now, count a (non-mergable) WS run */
- if(limit<length) {
- ++runCount;
- }
-
- /* runCount>1 */
- if(GETRUNSMEMORY(runCount)) {
- runs=mRunsMemory;
- } else {
- return false;
- }
-
- /* set the runs */
- /* this could be optimized, e.g.: 464->444, 484->444, 575->555, 595->555 */
- /* however, that would take longer and make other functions more complicated */
- runIndex=0;
-
- /* search for the run ends */
- i = 0;
- do {
- /* prepare this run */
- start = i;
- level = levels[i];
- if(level<minLevel) {
- minLevel=level;
- }
- if(level>maxLevel) {
- maxLevel=level;
- }
-
- /* look for the run limit */
- while (++i < limit && levels[i] == level) {
- }
-
- /* i is another run limit */
- runs[runIndex].logicalStart = start;
- runs[runIndex].visualLimit = i - start;
- ++runIndex;
- } while (i < limit);
-
- if(limit<length) {
- /* there is a separate WS run */
- runs[runIndex].logicalStart=limit;
- runs[runIndex].visualLimit=length-limit;
- if(mParaLevel<minLevel) {
- minLevel=mParaLevel;
- }
- }
-
- /* set the object fields */
- mRuns=runs;
- mRunCount=runCount;
-
- ReorderLine(minLevel, maxLevel);
-
- /* now add the direction flags and adjust the visualLimit's to be just that */
- /* this loop will also handling the trailing WS run */
- limit = 0;
- for (i = 0; i < runCount; ++i) {
- ADD_ODD_BIT_FROM_LEVEL(runs[i].logicalStart, levels[runs[i].logicalStart]);
- limit += runs[i].visualLimit;
- runs[i].visualLimit = limit;
- }
-
- /* Set the "odd" bit for the trailing WS run. */
- /* For a RTL paragraph, it will be the *first* run in visual order. */
- if (runIndex < runCount) {
- int32_t trailingRun = (mParaLevel & 1) ? 0 : runIndex;
- ADD_ODD_BIT_FROM_LEVEL(runs[trailingRun].logicalStart, mParaLevel);
- }
- }
- }
-
- return true;
-}
-
-/* in trivial cases there is only one trivial run; called by GetRuns() */
-void nsBidi::GetSingleRun(nsBidiLevel aLevel)
-{
- /* simple, single-run case */
- mRuns=mSimpleRuns;
- mRunCount=1;
-
- /* fill and reorder the single run */
- mRuns[0].logicalStart=MAKE_INDEX_ODD_PAIR(0, aLevel);
- mRuns[0].visualLimit=mLength;
-}
-
-/* reorder the runs array (L2) ---------------------------------------------- */
-
-/*
- * Reorder the same-level runs in the runs array.
- * Here, runCount>1 and maxLevel>=minLevel>=paraLevel.
- * All the visualStart fields=logical start before reordering.
- * The "odd" bits are not set yet.
- *
- * Reordering with this data structure lends itself to some handy shortcuts:
- *
- * Since each run is moved but not modified, and since at the initial maxLevel
- * each sequence of same-level runs consists of only one run each, we
- * don't need to do anything there and can predecrement maxLevel.
- * In many simple cases, the reordering is thus done entirely in the
- * index mapping.
- * Also, reordering occurs only down to the lowest odd level that occurs,
- * which is minLevel|1. However, if the lowest level itself is odd, then
- * in the last reordering the sequence of the runs at this level or higher
- * will be all runs, and we don't need the elaborate loop to search for them.
- * This is covered by ++minLevel instead of minLevel|=1 followed
- * by an extra reorder-all after the reorder-some loop.
- * About a trailing WS run:
- * Such a run would need special treatment because its level is not
- * reflected in levels[] if this is not a paragraph object.
- * Instead, all characters from trailingWSStart on are implicitly at
- * paraLevel.
- * However, for all maxLevel>paraLevel, this run will never be reordered
- * and does not need to be taken into account. maxLevel==paraLevel is only reordered
- * if minLevel==paraLevel is odd, which is done in the extra segment.
- * This means that for the main reordering loop we don't need to consider
- * this run and can --runCount. If it is later part of the all-runs
- * reordering, then runCount is adjusted accordingly.
- */
-void nsBidi::ReorderLine(nsBidiLevel aMinLevel, nsBidiLevel aMaxLevel)
-{
- Run *runs, tempRun;
- nsBidiLevel *levels;
- int32_t firstRun, endRun, limitRun, runCount;
-
- /* nothing to do? */
- if(aMaxLevel<=(aMinLevel|1)) {
- return;
- }
-
- /*
- * Reorder only down to the lowest odd level
- * and reorder at an odd aMinLevel in a separate, simpler loop.
- * See comments above for why aMinLevel is always incremented.
- */
- ++aMinLevel;
-
- runs=mRuns;
- levels=mLevels;
- runCount=mRunCount;
-
- /* do not include the WS run at paraLevel<=old aMinLevel except in the simple loop */
- if(mTrailingWSStart<mLength) {
- --runCount;
- }
-
- while(--aMaxLevel>=aMinLevel) {
- firstRun=0;
-
- /* loop for all sequences of runs */
- for(;;) {
- /* look for a sequence of runs that are all at >=aMaxLevel */
- /* look for the first run of such a sequence */
- while(firstRun<runCount && levels[runs[firstRun].logicalStart]<aMaxLevel) {
- ++firstRun;
- }
- if(firstRun>=runCount) {
- break; /* no more such runs */
- }
-
- /* look for the limit run of such a sequence (the run behind it) */
- for(limitRun=firstRun; ++limitRun<runCount && levels[runs[limitRun].logicalStart]>=aMaxLevel;) {}
-
- /* Swap the entire sequence of runs from firstRun to limitRun-1. */
- endRun=limitRun-1;
- while(firstRun<endRun) {
- tempRun = runs[firstRun];
- runs[firstRun] = runs[endRun];
- runs[endRun] = tempRun;
- ++firstRun;
- --endRun;
- }
-
- if(limitRun==runCount) {
- break; /* no more such runs */
- } else {
- firstRun=limitRun+1;
- }
- }
- }
-
- /* now do aMaxLevel==old aMinLevel (==odd!), see above */
- if(!(aMinLevel&1)) {
- firstRun=0;
-
- /* include the trailing WS run in this complete reordering */
- if(mTrailingWSStart==mLength) {
- --runCount;
- }
-
- /* Swap the entire sequence of all runs. (endRun==runCount) */
- while(firstRun<runCount) {
- tempRun = runs[firstRun];
- runs[firstRun] = runs[runCount];
- runs[runCount] = tempRun;
- ++firstRun;
- --runCount;
- }
- }
-}
-
-nsresult nsBidi::ReorderVisual(const nsBidiLevel *aLevels, int32_t aLength, int32_t *aIndexMap)
-{
- int32_t start, end, limit, temp;
- nsBidiLevel minLevel, maxLevel;
-
- if(aIndexMap==nullptr ||
- !PrepareReorder(aLevels, aLength, aIndexMap, &minLevel, &maxLevel)) {
- return NS_OK;
- }
-
- /* nothing to do? */
- if(minLevel==maxLevel && (minLevel&1)==0) {
- return NS_OK;
- }
-
- /* reorder only down to the lowest odd level */
- minLevel|=1;
-
- /* loop maxLevel..minLevel */
- do {
- start=0;
-
- /* loop for all sequences of levels to reorder at the current maxLevel */
- for(;;) {
- /* look for a sequence of levels that are all at >=maxLevel */
- /* look for the first index of such a sequence */
- while(start<aLength && aLevels[start]<maxLevel) {
- ++start;
- }
- if(start>=aLength) {
- break; /* no more such runs */
- }
-
- /* look for the limit of such a sequence (the index behind it) */
- for(limit=start; ++limit<aLength && aLevels[limit]>=maxLevel;) {}
-
- /*
- * Swap the entire interval of indexes from start to limit-1.
- * We don't need to swap the levels for the purpose of this
- * algorithm: the sequence of levels that we look at does not
- * move anyway.
- */
- end=limit-1;
- while(start<end) {
- temp=aIndexMap[start];
- aIndexMap[start]=aIndexMap[end];
- aIndexMap[end]=temp;
-
- ++start;
- --end;
- }
-
- if(limit==aLength) {
- break; /* no more such sequences */
- } else {
- start=limit+1;
- }
- }
- } while(--maxLevel>=minLevel);
-
- return NS_OK;
-}
-
-bool nsBidi::PrepareReorder(const nsBidiLevel *aLevels, int32_t aLength,
- int32_t *aIndexMap,
- nsBidiLevel *aMinLevel, nsBidiLevel *aMaxLevel)
-{
- int32_t start;
- nsBidiLevel level, minLevel, maxLevel;
-
- if(aLevels==nullptr || aLength<=0) {
- return false;
- }
-
- /* determine minLevel and maxLevel */
- minLevel=NSBIDI_MAX_EXPLICIT_LEVEL+1;
- maxLevel=0;
- for(start=aLength; start>0;) {
- level=aLevels[--start];
- if(level>NSBIDI_MAX_EXPLICIT_LEVEL+1) {
- return false;
- }
- if(level<minLevel) {
- minLevel=level;
- }
- if(level>maxLevel) {
- maxLevel=level;
- }
- }
- *aMinLevel=minLevel;
- *aMaxLevel=maxLevel;
-
- /* initialize the index map */
- for(start=aLength; start>0;) {
- --start;
- aIndexMap[start]=start;
- }
-
- return true;
-}
diff --git a/layout/base/nsBidi_noICU.h b/layout/base/nsBidi_noICU.h
deleted file mode 100644
index a3f5aef1c..000000000
--- a/layout/base/nsBidi_noICU.h
+++ /dev/null
@@ -1,709 +0,0 @@
-/* -*- 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/. */
-
-#ifndef nsBidi_noICU_h__
-#define nsBidi_noICU_h__
-
-#include "nsBidiUtils.h"
-#include "nsIFrame.h" // for frame property declaration
-
-// Bidi reordering engine from ICU
-/*
- * javadoc-style comments are intended to be transformed into HTML
- * using DOC++ - see
- * http://www.zib.de/Visual/software/doc++/index.html .
- *
- * The HTML documentation is created with
- * doc++ -H nsBidi.h
- */
-
-/**
- * @mainpage BIDI algorithm for Mozilla (from ICU)
- *
- * <h2>BIDI algorithm for Mozilla</h2>
- *
- * This is an implementation of the Unicode Bidirectional algorithm.
- * The algorithm is defined in the
- * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Technical Report 9</a>,
- * version 5, also described in The Unicode Standard, Version 3.0 .<p>
- *
- * <h3>General remarks about the API:</h3>
- *
- * The <quote>limit</quote> of a sequence of characters is the position just after their
- * last character, i.e., one more than that position.<p>
- *
- * Some of the API functions provide access to <quote>runs</quote>.
- * Such a <quote>run</quote> is defined as a sequence of characters
- * that are at the same embedding level
- * after performing the BIDI algorithm.<p>
- *
- * @author Markus W. Scherer. Ported to Mozilla by Simon Montagu
- * @version 1.0
- */
-
-/**
- * Special value which can be returned by the mapping functions when a logical
- * index has no corresponding visual index or vice-versa.
- * @see GetVisualIndex
- * @see GetVisualMap
- * @see GetLogicalIndex
- * @see GetLogicalMap
- */
-#define NSBIDI_MAP_NOWHERE (-1)
-
-/* miscellaneous definitions ------------------------------------------------ */
-
-/* helper macros for each allocated array member */
-#define GETDIRPROPSMEMORY(length) nsBidi::GetMemory((void **)&mDirPropsMemory, \
- &mDirPropsSize, \
- (length))
-
-#define GETLEVELSMEMORY(length) nsBidi::GetMemory((void **)&mLevelsMemory, \
- &mLevelsSize, \
- (length))
-
-#define GETRUNSMEMORY(length) nsBidi::GetMemory((void **)&mRunsMemory, \
- &mRunsSize, \
- (length)*sizeof(Run))
-
-#define GETISOLATESMEMORY(length) nsBidi::GetMemory((void **)&mIsolatesMemory, \
- &mIsolatesSize, \
- (length)*sizeof(Isolate))
-
-#define GETOPENINGSMEMORY(length) nsBidi::GetMemory((void **)&mOpeningsMemory, \
- &mOpeningsSize, \
- (length)*sizeof(Opening))
-
-/*
- * Sometimes, bit values are more appropriate
- * to deal with directionality properties.
- * Abbreviations in these macro names refer to names
- * used in the Bidi algorithm.
- */
-typedef uint8_t DirProp;
-
-#define DIRPROP_FLAG(dir) (1UL<<(dir))
-
-/* special flag for multiple runs from explicit embedding codes */
-#define DIRPROP_FLAG_MULTI_RUNS (1UL<<31)
-
-/* are there any characters that are LTR or RTL? */
-#define MASK_LTR (DIRPROP_FLAG(L)|DIRPROP_FLAG(EN)|DIRPROP_FLAG(ENL)| \
- DIRPROP_FLAG(ENR)|DIRPROP_FLAG(AN)|DIRPROP_FLAG(LRE)| \
- DIRPROP_FLAG(LRO)|DIRPROP_FLAG(LRI))
-#define MASK_RTL (DIRPROP_FLAG(R)|DIRPROP_FLAG(AL)|DIRPROP_FLAG(RLE)| \
- DIRPROP_FLAG(RLO)|DIRPROP_FLAG(RLI))
-#define MASK_R_AL (DIRPROP_FLAG(R)|DIRPROP_FLAG(AL))
-
-/* explicit embedding codes */
-#define MASK_EXPLICIT (DIRPROP_FLAG(LRE)|DIRPROP_FLAG(LRO)|DIRPROP_FLAG(RLE)|DIRPROP_FLAG(RLO)|DIRPROP_FLAG(PDF))
-
-/* explicit isolate codes */
-#define MASK_ISO (DIRPROP_FLAG(LRI)|DIRPROP_FLAG(RLI)|DIRPROP_FLAG(FSI)|DIRPROP_FLAG(PDI))
-
-#define MASK_BN_EXPLICIT (DIRPROP_FLAG(BN)|MASK_EXPLICIT)
-
-/* paragraph and segment separators */
-#define MASK_B_S (DIRPROP_FLAG(B)|DIRPROP_FLAG(S))
-
-/* all types that are counted as White Space or Neutral in some steps */
-#define MASK_WS (MASK_B_S|DIRPROP_FLAG(WS)|MASK_BN_EXPLICIT|MASK_ISO)
-
-/* types that are neutrals or could becomes neutrals in (Wn) */
-#define MASK_POSSIBLE_N (DIRPROP_FLAG(O_N)|DIRPROP_FLAG(CS)|DIRPROP_FLAG(ES)|DIRPROP_FLAG(ET)|MASK_WS)
-
-/*
- * These types may be changed to "e",
- * the embedding type (L or R) of the run,
- * in the Bidi algorithm (N2)
- */
-#define MASK_EMBEDDING (DIRPROP_FLAG(NSM)|MASK_POSSIBLE_N)
-
-/* the dirProp's L and R are defined to 0 and 1 values in nsCharType */
-#define GET_LR_FROM_LEVEL(level) ((DirProp)((level)&1))
-
-#define IS_DEFAULT_LEVEL(level) (((level)&0xfe)==0xfe)
-
-/*
- * The following bit is used for the directional isolate status.
- * Stack entries corresponding to isolate sequences are greater than ISOLATE.
- */
-#define ISOLATE 0x0100
-
-/* number of isolate entries allocated initially without malloc */
-#define SIMPLE_ISOLATES_SIZE 5
-
-/* number of isolate run entries for paired brackets allocated initially without malloc */
-#define SIMPLE_OPENINGS_COUNT 8
-
-/* handle surrogate pairs --------------------------------------------------- */
-
-#define IS_FIRST_SURROGATE(uchar) (((uchar)&0xfc00)==0xd800)
-#define IS_SECOND_SURROGATE(uchar) (((uchar)&0xfc00)==0xdc00)
-
-/* get the UTF-32 value directly from the surrogate pseudo-characters */
-#define SURROGATE_OFFSET ((0xd800<<10UL)+0xdc00-0x10000)
-#define GET_UTF_32(first, second) (((first)<<10UL)+(second)-SURROGATE_OFFSET)
-
-#if !ENABLE_INTL_API // these are provided by ICU if present in the build
-
-#define UTF_ERROR_VALUE 0xffff
-/* definitions with forward iteration --------------------------------------- */
-
-/*
- * all the macros that go forward assume that
- * the initial offset is 0<=i<length;
- * they update the offset
- */
-
-/* fast versions, no error-checking */
-
-#define UTF16_APPEND_CHAR_UNSAFE(s, i, c){ \
- if((uint32_t)(c)<=0xffff) { \
- (s)[(i)++]=(char16_t)(c); \
- } else { \
- (s)[(i)++]=(char16_t)((c)>>10)+0xd7c0; \
- (s)[(i)++]=(char16_t)(c)&0x3ff|0xdc00; \
- } \
-}
-
-/* safe versions with error-checking and optional regularity-checking */
-
-#define UTF16_APPEND_CHAR_SAFE(s, i, length, c) { \
- if((PRUInt32)(c)<=0xffff) { \
- (s)[(i)++]=(char16_t)(c); \
- } else if((PRUInt32)(c)<=0x10ffff) { \
- if((i)+1<(length)) { \
- (s)[(i)++]=(char16_t)((c)>>10)+0xd7c0; \
- (s)[(i)++]=(char16_t)(c)&0x3ff|0xdc00; \
- } else /* not enough space */ { \
- (s)[(i)++]=UTF_ERROR_VALUE; \
- } \
- } else /* c>0x10ffff, write error value */ { \
- (s)[(i)++]=UTF_ERROR_VALUE; \
- } \
-}
-
-/* definitions with backward iteration -------------------------------------- */
-
-/*
- * all the macros that go backward assume that
- * the valid buffer range starts at offset 0
- * and that the initial offset is 0<i<=length;
- * they update the offset
- */
-
-/* fast versions, no error-checking */
-
-/*
- * Get a single code point from an offset that points behind the last
- * of the code units that belong to that code point.
- * Assume 0<=i<length.
- */
-#define UTF16_PREV_CHAR_UNSAFE(s, i, c) { \
- (c)=(s)[--(i)]; \
- if(IS_SECOND_SURROGATE(c)) { \
- (c)=GET_UTF_32((s)[--(i)], (c)); \
- } \
-}
-
-#define UTF16_BACK_1_UNSAFE(s, i) { \
- if(IS_SECOND_SURROGATE((s)[--(i)])) { \
- --(i); \
- } \
-}
-
-#define UTF16_BACK_N_UNSAFE(s, i, n) { \
- int32_t __N=(n); \
- while(__N>0) { \
- UTF16_BACK_1_UNSAFE(s, i); \
- --__N; \
- } \
-}
-
-/* safe versions with error-checking and optional regularity-checking */
-
-#define UTF16_PREV_CHAR_SAFE(s, start, i, c, strict) { \
- (c)=(s)[--(i)]; \
- if(IS_SECOND_SURROGATE(c)) { \
- char16_t __c2; \
- if((i)>(start) && IS_FIRST_SURROGATE(__c2=(s)[(i)-1])) { \
- --(i); \
- (c)=GET_UTF_32(__c2, (c)); \
- /* strict: ((c)&0xfffe)==0xfffe is caught by UTF_IS_ERROR() */ \
- } else if(strict) {\
- /* unmatched second surrogate */ \
- (c)=UTF_ERROR_VALUE; \
- } \
- } else if(strict && IS_FIRST_SURROGATE(c)) { \
- /* unmatched first surrogate */ \
- (c)=UTF_ERROR_VALUE; \
- /* else strict: (c)==0xfffe is caught by UTF_IS_ERROR() */ \
- } \
-}
-
-#define UTF16_BACK_1_SAFE(s, start, i) { \
- if(IS_SECOND_SURROGATE((s)[--(i)]) && (i)>(start) && IS_FIRST_SURROGATE((s)[(i)-1])) { \
- --(i); \
- } \
-}
-
-#define UTF16_BACK_N_SAFE(s, start, i, n) { \
- int32_t __N=(n); \
- while(__N>0 && (i)>(start)) { \
- UTF16_BACK_1_SAFE(s, start, i); \
- --__N; \
- } \
-}
-
-#define UTF_PREV_CHAR_UNSAFE(s, i, c) UTF16_PREV_CHAR_UNSAFE(s, i, c)
-#define UTF_PREV_CHAR_SAFE(s, start, i, c, strict) UTF16_PREV_CHAR_SAFE(s, start, i, c, strict)
-#define UTF_BACK_1_UNSAFE(s, i) UTF16_BACK_1_UNSAFE(s, i)
-#define UTF_BACK_1_SAFE(s, start, i) UTF16_BACK_1_SAFE(s, start, i)
-#define UTF_BACK_N_UNSAFE(s, i, n) UTF16_BACK_N_UNSAFE(s, i, n)
-#define UTF_BACK_N_SAFE(s, start, i, n) UTF16_BACK_N_SAFE(s, start, i, n)
-#define UTF_APPEND_CHAR_UNSAFE(s, i, c) UTF16_APPEND_CHAR_UNSAFE(s, i, c)
-#define UTF_APPEND_CHAR_SAFE(s, i, length, c) UTF16_APPEND_CHAR_SAFE(s, i, length, c)
-
-#define UTF_PREV_CHAR(s, start, i, c) UTF_PREV_CHAR_SAFE(s, start, i, c, false)
-#define UTF_BACK_1(s, start, i) UTF_BACK_1_SAFE(s, start, i)
-#define UTF_BACK_N(s, start, i, n) UTF_BACK_N_SAFE(s, start, i, n)
-#define UTF_APPEND_CHAR(s, i, length, c) UTF_APPEND_CHAR_SAFE(s, i, length, c)
-
-#endif // !ENABLE_INTL_API
-
-struct Isolate {
- int32_t start1;
- int16_t stateImp;
- int16_t state;
-};
-
-// For bracket matching
-
-#define FOUND_L DIRPROP_FLAG(L)
-#define FOUND_R DIRPROP_FLAG(R)
-
-struct Opening {
- int32_t position; /* position of opening bracket */
- int32_t match; /* matching char or -position of closing bracket */
- int32_t contextPos; /* position of last strong char found before opening */
- uint16_t flags; /* bits for L or R/AL found within the pair */
- DirProp contextDir; /* L or R according to last strong char before opening */
- uint8_t filler; /* to complete a nice multiple of 4 chars */
-};
-
-struct IsoRun {
- int32_t contextPos; /* position of char determining context */
- uint16_t start; /* index of first opening entry for this run */
- uint16_t limit; /* index after last opening entry for this run */
- nsBidiLevel level; /* level of this run */
- DirProp lastStrong; /* bidi class of last strong char found in this run */
- DirProp lastBase; /* bidi class of last base char found in this run */
- DirProp contextDir; /* L or R to use as context for following openings */
-};
-
-class nsBidi;
-
-/* Run structure for reordering --------------------------------------------- */
-
-typedef struct Run {
- int32_t logicalStart; /* first character of the run; b31 indicates even/odd level */
- int32_t visualLimit; /* last visual position of the run +1 */
-} Run;
-
-/* in a Run, logicalStart will get this bit set if the run level is odd */
-#define INDEX_ODD_BIT (1UL<<31)
-
-#define MAKE_INDEX_ODD_PAIR(index, level) (index|((uint32_t)level<<31))
-#define ADD_ODD_BIT_FROM_LEVEL(x, level) ((x)|=((uint32_t)level<<31))
-#define REMOVE_ODD_BIT(x) ((x)&=~INDEX_ODD_BIT)
-
-#define GET_INDEX(x) ((x)&~INDEX_ODD_BIT)
-#define GET_ODD_BIT(x) ((uint32_t)(x)>>31)
-#define IS_ODD_RUN(x) (((x)&INDEX_ODD_BIT)!=0)
-#define IS_EVEN_RUN(x) (((x)&INDEX_ODD_BIT)==0)
-
-typedef uint32_t Flags;
-
-enum { DirProp_L=0, DirProp_R=1, DirProp_EN=2, DirProp_AN=3, DirProp_ON=4, DirProp_S=5, DirProp_B=6 }; /* reduced dirProp */
-
-#define IMPTABLEVELS_COLUMNS (DirProp_B + 2)
-typedef const uint8_t ImpTab[][IMPTABLEVELS_COLUMNS];
-typedef const uint8_t (*PImpTab)[IMPTABLEVELS_COLUMNS];
-
-typedef const uint8_t ImpAct[];
-typedef const uint8_t *PImpAct;
-
-struct LevState {
- PImpTab pImpTab; /* level table pointer */
- PImpAct pImpAct; /* action map array */
- int32_t startON; /* start of ON sequence */
- int32_t state; /* current state */
- int32_t runStart; /* start position of the run */
- nsBidiLevel runLevel; /* run level before implicit solving */
-};
-
-/**
- * This class holds information about a paragraph of text
- * with Bidi-algorithm-related details, or about one line of
- * such a paragraph.<p>
- * Reordering can be done on a line, or on a paragraph which is
- * then interpreted as one single line.<p>
- *
- * On construction, the class is initially empty. It is assigned
- * the Bidi properties of a paragraph by <code>SetPara</code>
- * or the Bidi properties of a line of a paragraph by
- * <code>SetLine</code>.<p>
- * A Bidi class can be reused for as long as it is not deallocated
- * by calling its destructor.<p>
- * <code>SetPara</code> will allocate additional memory for
- * internal structures as necessary.
- */
-class nsBidi
-{
-public:
- /** @brief Default constructor.
- *
- * The nsBidi object is initially empty. It is assigned
- * the Bidi properties of a paragraph by <code>SetPara()</code>
- * or the Bidi properties of a line of a paragraph by
- * <code>GetLine()</code>.<p>
- * This object can be reused for as long as it is not destroyed.<p>
- * <code>SetPara()</code> will allocate additional memory for
- * internal structures as necessary.
- *
- */
- nsBidi();
-
- /** @brief Destructor. */
- virtual ~nsBidi();
-
-
- /**
- * Perform the Unicode Bidi algorithm. It is defined in the
- * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Technical Report 9</a>,
- * version 5,
- * also described in The Unicode Standard, Version 3.0 .<p>
- *
- * This function takes a single plain text paragraph with or without
- * externally specified embedding levels from <quote>styled</quote> text
- * and computes the left-right-directionality of each character.<p>
- *
- * If the entire paragraph consists of text of only one direction, then
- * the function may not perform all the steps described by the algorithm,
- * i.e., some levels may not be the same as if all steps were performed.
- * This is not relevant for unidirectional text.<br>
- * For example, in pure LTR text with numbers the numbers would get
- * a resolved level of 2 higher than the surrounding text according to
- * the algorithm. This implementation may set all resolved levels to
- * the same value in such a case.<p>
- *
- * The text must be externally split into separate paragraphs (rule P1).
- * Paragraph separators (B) should appear at most at the very end.
- *
- * @param aText is a pointer to the single-paragraph text that the
- * Bidi algorithm will be performed on
- * (step (P1) of the algorithm is performed externally).
- * <strong>The text must be (at least) <code>aLength</code> long.</strong>
- *
- * @param aLength is the length of the text; if <code>aLength==-1</code> then
- * the text must be zero-terminated.
- *
- * @param aParaLevel specifies the default level for the paragraph;
- * it is typically 0 (LTR) or 1 (RTL).
- * If the function shall determine the paragraph level from the text,
- * then <code>aParaLevel</code> can be set to
- * either <code>NSBIDI_DEFAULT_LTR</code>
- * or <code>NSBIDI_DEFAULT_RTL</code>;
- * if there is no strongly typed character, then
- * the desired default is used (0 for LTR or 1 for RTL).
- * Any other value between 0 and <code>NSBIDI_MAX_EXPLICIT_LEVEL</code> is also valid,
- * with odd levels indicating RTL.
- */
- nsresult SetPara(const char16_t *aText, int32_t aLength, nsBidiLevel aParaLevel);
-
- /**
- * Get the directionality of the text.
- *
- * @param aDirection receives a <code>NSBIDI_XXX</code> value that indicates if the entire text
- * represented by this object is unidirectional,
- * and which direction, or if it is mixed-directional.
- *
- * @see nsBidiDirection
- */
- nsresult GetDirection(nsBidiDirection* aDirection);
-
- /**
- * Get the paragraph level of the text.
- *
- * @param aParaLevel receives a <code>NSBIDI_XXX</code> value indicating the paragraph level
- *
- * @see nsBidiLevel
- */
- nsresult GetParaLevel(nsBidiLevel* aParaLevel);
-
- /**
- * Get a logical run.
- * This function returns information about a run and is used
- * to retrieve runs in logical order.<p>
- * This is especially useful for line-breaking on a paragraph.
- *
- * @param aLogicalStart is the first character of the run.
- *
- * @param aLogicalLimit will receive the limit of the run.
- * The l-value that you point to here may be the
- * same expression (variable) as the one for
- * <code>aLogicalStart</code>.
- * This pointer can be <code>nullptr</code> if this
- * value is not necessary.
- *
- * @param aLevel will receive the level of the run.
- * This pointer can be <code>nullptr</code> if this
- * value is not necessary.
- */
- nsresult GetLogicalRun(int32_t aLogicalStart, int32_t* aLogicalLimit, nsBidiLevel* aLevel);
-
- /**
- * Get the number of runs.
- * This function may invoke the actual reordering on the
- * <code>nsBidi</code> object, after <code>SetPara</code>
- * may have resolved only the levels of the text. Therefore,
- * <code>CountRuns</code> may have to allocate memory,
- * and may fail doing so.
- *
- * @param aRunCount will receive the number of runs.
- */
- nsresult CountRuns(int32_t* aRunCount);
-
- /**
- * Get one run's logical start, length, and directionality,
- * which can be 0 for LTR or 1 for RTL.
- * In an RTL run, the character at the logical start is
- * visually on the right of the displayed run.
- * The length is the number of characters in the run.<p>
- * <code>CountRuns</code> should be called
- * before the runs are retrieved.
- *
- * @param aRunIndex is the number of the run in visual order, in the
- * range <code>[0..CountRuns-1]</code>.
- *
- * @param aLogicalStart is the first logical character index in the text.
- * The pointer may be <code>nullptr</code> if this index is not needed.
- *
- * @param aLength is the number of characters (at least one) in the run.
- * The pointer may be <code>nullptr</code> if this is not needed.
- *
- * @param aDirection will receive the directionality of the run,
- * <code>NSBIDI_LTR==0</code> or <code>NSBIDI_RTL==1</code>,
- * never <code>NSBIDI_MIXED</code>.
- *
- * @see CountRuns<p>
- *
- * Example:
- * @code
- * int32_t i, count, logicalStart, visualIndex=0, length;
- * nsBidiDirection dir;
- * pBidi->CountRuns(&count);
- * for(i=0; i<count; ++i) {
- * pBidi->GetVisualRun(i, &logicalStart, &length, &dir);
- * if(NSBIDI_LTR==dir) {
- * do { // LTR
- * show_char(text[logicalStart++], visualIndex++);
- * } while(--length>0);
- * } else {
- * logicalStart+=length; // logicalLimit
- * do { // RTL
- * show_char(text[--logicalStart], visualIndex++);
- * } while(--length>0);
- * }
- * }
- * @endcode
- *
- * Note that in right-to-left runs, code like this places
- * modifier letters before base characters and second surrogates
- * before first ones.
- */
- nsresult GetVisualRun(int32_t aRunIndex, int32_t* aLogicalStart, int32_t* aLength, nsBidiDirection* aDirection);
-
- /**
- * This is a convenience function that does not use a nsBidi object.
- * It is intended to be used for when an application has determined the levels
- * of objects (character sequences) and just needs to have them reordered (L2).
- * This is equivalent to using <code>GetVisualMap</code> on a
- * <code>nsBidi</code> object.
- *
- * @param aLevels is an array with <code>aLength</code> levels that have been determined by
- * the application.
- *
- * @param aLength is the number of levels in the array, or, semantically,
- * the number of objects to be reordered.
- * It must be <code>aLength>0</code>.
- *
- * @param aIndexMap is a pointer to an array of <code>aLength</code>
- * indexes which will reflect the reordering of the characters.
- * The array does not need to be initialized.<p>
- * The index map will result in <code>aIndexMap[aVisualIndex]==aLogicalIndex</code>.
- */
- static nsresult ReorderVisual(const nsBidiLevel *aLevels, int32_t aLength, int32_t *aIndexMap);
-
- /**
- * Reverse a Right-To-Left run of Unicode text.
- *
- * This function preserves the integrity of characters with multiple
- * code units and (optionally) modifier letters.
- * Characters can be replaced by mirror-image characters
- * in the destination buffer. Note that "real" mirroring has
- * to be done in a rendering engine by glyph selection
- * and that for many "mirrored" characters there are no
- * Unicode characters as mirror-image equivalents.
- * There are also options to insert or remove Bidi control
- * characters; see the description of the <code>aDestSize</code>
- * and <code>aOptions</code> parameters and of the option bit flags.
- *
- * Since no Bidi controls are inserted here, this function will never
- * write more than <code>aSrcLength</code> characters to <code>aDest</code>.
- *
- * @param aSrc A pointer to the RTL run text.
- *
- * @param aSrcLength The length of the RTL run.
- * If the <code>NSBIDI_REMOVE_BIDI_CONTROLS</code> option
- * is set, then the destination length may be less than
- * <code>aSrcLength</code>.
- * If this option is not set, then the destination length
- * will be exactly <code>aSrcLength</code>.
- *
- * @param aDest A pointer to where the reordered text is to be copied.
- * <code>aSrc[aSrcLength]</code> and <code>aDest[aSrcLength]</code>
- * must not overlap.
- *
- * @param aOptions A bit set of options for the reordering that control
- * how the reordered text is written.
- *
- * @param aDestSize will receive the number of characters that were written to <code>aDest</code>.
- */
- nsresult WriteReverse(const char16_t *aSrc, int32_t aSrcLength, char16_t *aDest, uint16_t aOptions, int32_t *aDestSize);
-
-protected:
- friend class nsBidiPresUtils;
-
- class BracketData {
- public:
- explicit BracketData(const nsBidi* aBidi);
- ~BracketData();
-
- void ProcessBoundary(int32_t aLastDirControlCharPos,
- nsBidiLevel aContextLevel,
- nsBidiLevel aEmbeddingLevel,
- const DirProp* aDirProps);
- void ProcessLRI_RLI(nsBidiLevel aLevel);
- void ProcessPDI();
- bool AddOpening(char16_t aMatch, int32_t aPosition);
- void FixN0c(int32_t aOpeningIndex, int32_t aNewPropPosition,
- DirProp aNewProp, DirProp* aDirProps);
- DirProp ProcessClosing(int32_t aOpenIdx, int32_t aPosition,
- DirProp* aDirProps);
- bool ProcessChar(int32_t aPosition, char16_t aCh, DirProp* aDirProps,
- nsBidiLevel* aLevels);
-
- private:
- // array of opening entries which should be enough in most cases;
- // no malloc() needed
- Opening mSimpleOpenings[SIMPLE_OPENINGS_COUNT];
- Opening* mOpenings; // pointer to current array of entries,
- // either mSimpleOpenings or malloced array
-
- Opening* mOpeningsMemory;
- size_t mOpeningsSize;
-
- // array of nested isolated sequence entries; can never exceed
- // UBIDI_MAX_EXPLICIT_LEVEL
- // + 1 for index 0
- // + 1 for before the first isolated sequence
- IsoRun mIsoRuns[NSBIDI_MAX_EXPLICIT_LEVEL+2];
- int32_t mIsoRunLast; // index of last used entry in mIsoRuns
-
- int32_t mOpeningsCount; // number of allocated entries in mOpenings
- };
-
- /** length of the current text */
- int32_t mLength;
-
- /** memory sizes in bytes */
- size_t mDirPropsSize, mLevelsSize, mRunsSize;
- size_t mIsolatesSize;
-
- /** allocated memory */
- DirProp* mDirPropsMemory;
- nsBidiLevel* mLevelsMemory;
- Run* mRunsMemory;
- Isolate* mIsolatesMemory;
-
- DirProp* mDirProps;
- nsBidiLevel* mLevels;
-
- /** the paragraph level */
- nsBidiLevel mParaLevel;
-
- /** flags is a bit set for which directional properties are in the text */
- Flags mFlags;
-
- /** the overall paragraph or line directionality - see nsBidiDirection */
- nsBidiDirection mDirection;
-
- /** characters after trailingWSStart are WS and are */
- /* implicitly at the paraLevel (rule (L1)) - levels may not reflect that */
- int32_t mTrailingWSStart;
-
- /** fields for line reordering */
- int32_t mRunCount; /* ==-1: runs not set up yet */
- Run* mRuns;
-
- /** for non-mixed text, we only need a tiny array of runs (no malloc()) */
- Run mSimpleRuns[1];
-
- /* maxium of current nesting depth of isolate sequences */
- /* Within ResolveExplicitLevels() and checkExpicitLevels(), this is the maximal
- nesting encountered.
- Within ResolveImplicitLevels(), this is the index of the current isolates
- stack entry. */
- int32_t mIsolateCount;
- Isolate* mIsolates;
-
- /** for simple text, have a small stack (no malloc()) */
- Isolate mSimpleIsolates[SIMPLE_ISOLATES_SIZE];
-
-private:
-
- void Init();
-
- static bool GetMemory(void **aMemory, size_t* aSize, size_t aSizeNeeded);
-
- void Free();
-
- void GetDirProps(const char16_t *aText);
-
- void ResolveExplicitLevels(nsBidiDirection *aDirection, const char16_t *aText);
-
- nsBidiDirection DirectionFromFlags(Flags aFlags);
-
- void ProcessPropertySeq(LevState *pLevState, uint8_t _prop, int32_t start, int32_t limit);
-
- void ResolveImplicitLevels(int32_t aStart, int32_t aLimit, DirProp aSOR, DirProp aEOR);
-
- void AdjustWSLevels();
-
- void SetTrailingWSStart();
-
- bool GetRuns();
-
- void GetSingleRun(nsBidiLevel aLevel);
-
- void ReorderLine(nsBidiLevel aMinLevel, nsBidiLevel aMaxLevel);
-
- static bool PrepareReorder(const nsBidiLevel *aLevels, int32_t aLength, int32_t *aIndexMap, nsBidiLevel *aMinLevel, nsBidiLevel *aMaxLevel);
-};
-
-#endif // _nsBidi_noICU_h_
diff --git a/layout/base/nsCSSFrameConstructor.cpp b/layout/base/nsCSSFrameConstructor.cpp
index 767298b85..c63374541 100644
--- a/layout/base/nsCSSFrameConstructor.cpp
+++ b/layout/base/nsCSSFrameConstructor.cpp
@@ -3658,7 +3658,7 @@ nsCSSFrameConstructor::FindInputData(Element* aElement,
nsCSSAnonBoxes::buttonContent) },
// TODO: this is temporary until a frame is written: bug 635240.
SIMPLE_INT_CREATE(NS_FORM_INPUT_NUMBER, NS_NewNumberControlFrame),
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
// On Android/B2G, date/time input appears as a normal text box.
SIMPLE_INT_CREATE(NS_FORM_INPUT_TIME, NS_NewTextControlFrame),
SIMPLE_INT_CREATE(NS_FORM_INPUT_DATE, NS_NewTextControlFrame),
diff --git a/layout/base/nsIPresShell.h b/layout/base/nsIPresShell.h
index 5990402ed..4016cc0a9 100644
--- a/layout/base/nsIPresShell.h
+++ b/layout/base/nsIPresShell.h
@@ -51,10 +51,6 @@
#include "nsFrameState.h"
#include "Units.h"
-#ifdef MOZ_B2G
-#include "nsIHardwareKeyHandler.h"
-#endif
-
class nsDocShell;
class nsIDocument;
class nsIFrame;
@@ -1766,11 +1762,6 @@ protected:
// moving/sizing loop is running, see bug 491700 for details.
nsCOMPtr<nsITimer> mReflowContinueTimer;
-#ifdef MOZ_B2G
- // Forward hardware key events to the input-method-app
- nsCOMPtr<nsIHardwareKeyHandler> mHardwareKeyHandler;
-#endif // MOZ_B2G
-
#ifdef DEBUG
nsIFrame* mDrawEventTargetFrame;
diff --git a/layout/base/nsLayoutUtils.cpp b/layout/base/nsLayoutUtils.cpp
index c8c91b251..9d8dd81bf 100644
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -6653,8 +6653,9 @@ nsLayoutUtils::DrawSingleImage(gfxContext& aContext,
nscoord appUnitsPerCSSPixel = nsDeviceContext::AppUnitsPerCSSPixel();
CSSIntSize pixelImageSize(ComputeSizeForDrawingWithFallback(aImage, aDest.Size()));
if (pixelImageSize.width < 1 || pixelImageSize.height < 1) {
- NS_WARNING("Image width or height is non-positive");
- return DrawResult::TEMPORARY_ERROR;
+ NS_ASSERTION(pixelImageSize.width >= 0 && pixelImageSize.height >= 0,
+ "Image width or height is negative");
+ return DrawResult::SUCCESS; // no point in drawing a zero size image
}
nsSize imageSize(CSSPixel::ToAppUnits(pixelImageSize));
@@ -7013,7 +7014,8 @@ nsLayoutUtils::GetTextRunFlagsForStyle(nsStyleContext* aStyleContext,
nscoord aLetterSpacing)
{
uint32_t result = 0;
- if (aLetterSpacing != 0) {
+ if (aLetterSpacing != 0 ||
+ aStyleText->mTextJustify == StyleTextJustify::InterCharacter) {
result |= gfxTextRunFactory::TEXT_DISABLE_OPTIONAL_LIGATURES;
}
if (aStyleText->mControlCharacterVisibility == NS_STYLE_CONTROL_CHARACTER_VISIBILITY_HIDDEN) {
diff --git a/layout/base/nsPresShell.cpp b/layout/base/nsPresShell.cpp
index 42b39c860..0b88948c3 100644
--- a/layout/base/nsPresShell.cpp
+++ b/layout/base/nsPresShell.cpp
@@ -201,10 +201,6 @@
#include "nsIDocShellTreeOwner.h"
#endif
-#ifdef MOZ_B2G
-#include "nsIHardwareKeyHandler.h"
-#endif
-
#ifdef MOZ_TASK_TRACER
#include "GeckoTaskTracer.h"
using namespace mozilla::tasktracer;
@@ -7236,38 +7232,6 @@ PresShell::HandleKeyboardEvent(nsINode* aTarget,
DispatchAfterKeyboardEventInternal(chain, aEvent, aEvent.DefaultPrevented());
}
-#ifdef MOZ_B2G
-bool
-PresShell::ForwardKeyToInputMethodApp(nsINode* aTarget,
- WidgetKeyboardEvent& aEvent,
- nsEventStatus* aStatus)
-{
- if (!XRE_IsParentProcess() || aEvent.mIsSynthesizedByTIP ||
- aEvent.IsKeyEventOnPlugin()) {
- return false;
- }
-
- if (!mHardwareKeyHandler) {
- nsresult rv;
- mHardwareKeyHandler =
- do_GetService("@mozilla.org/HardwareKeyHandler;1", &rv);
- if (!NS_SUCCEEDED(rv) || !mHardwareKeyHandler) {
- return false;
- }
- }
-
- if (mHardwareKeyHandler->ForwardKeyToInputMethodApp(aTarget,
- aEvent.AsKeyboardEvent(),
- aStatus)) {
- // No need to dispatch the forwarded keyboard event to it's child process
- aEvent.mFlags.mNoCrossProcessBoundaryForwarding = true;
- return true;
- }
-
- return false;
-}
-#endif // MOZ_B2G
-
bool
PresShell::ForwardKeyToInputMethodAppOrDispatch(bool aIsTargetRemote,
nsINode* aTarget,
@@ -7275,41 +7239,9 @@ PresShell::ForwardKeyToInputMethodAppOrDispatch(bool aIsTargetRemote,
nsEventStatus* aStatus,
EventDispatchingCallback* aEventCB)
{
-#ifndef MOZ_B2G
- // No need to forward to input-method-app if the platform isn't run on B2G.
EventDispatcher::Dispatch(aTarget, mPresContext,
&aEvent, nullptr, aStatus, aEventCB);
return false;
-#else
- // In-process case: the event target is in the current process
- if (!aIsTargetRemote) {
- if(ForwardKeyToInputMethodApp(aTarget, aEvent, aStatus)) {
- return true;
- }
-
- // If the keyboard event isn't forwarded to the input-method-app,
- // then it should be dispatched to its event target directly.
- EventDispatcher::Dispatch(aTarget, mPresContext,
- &aEvent, nullptr, aStatus, aEventCB);
-
- return false;
- }
-
- // OOP case: the event target is in its child process.
- // Dispatch the keyboard event to the iframe that embeds the remote
- // event target first.
- EventDispatcher::Dispatch(aTarget, mPresContext,
- &aEvent, nullptr, aStatus, aEventCB);
-
- // If the event is defaultPrevented, then there is no need to forward it
- // to the input-method-app.
- if (aEvent.mFlags.mDefaultPrevented) {
- return false;
- }
-
- // Try forwarding to the input-method-app.
- return ForwardKeyToInputMethodApp(aTarget, aEvent, aStatus);
-#endif // MOZ_B2G
}
nsresult
diff --git a/layout/base/nsPresShell.h b/layout/base/nsPresShell.h
index ad4ede08b..7a9056a38 100644
--- a/layout/base/nsPresShell.h
+++ b/layout/base/nsPresShell.h
@@ -815,15 +815,6 @@ protected:
bool aEmbeddedCancelled,
size_t aChainIndex = 0);
-#ifdef MOZ_B2G
- // This method is used to forward the keyboard event to the input-method-app
- // before the event is dispatched to its event target.
- // Return true if it's successfully forwarded. Otherwise, return false.
- bool ForwardKeyToInputMethodApp(nsINode* aTarget,
- mozilla::WidgetKeyboardEvent& aEvent,
- nsEventStatus* aStatus);
-#endif // MOZ_B2G
-
// This method tries forwarding key events to the input-method-editor(IME).
// If the event isn't be forwarded, then it will be dispathed to its target.
// Return true when event is successfully forwarded to the input-method-editor.
diff --git a/layout/build/moz.build b/layout/build/moz.build
index a628f3ee2..5b607c171 100644
--- a/layout/build/moz.build
+++ b/layout/build/moz.build
@@ -39,7 +39,6 @@ LOCAL_INCLUDES += [
'/dom/jsurl',
'/dom/media',
'/dom/offline',
- '/dom/speakermanager',
'/dom/storage',
'/dom/svg',
'/dom/xbl',
@@ -73,10 +72,6 @@ elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
'/dom/system',
'/dom/system/android',
]
-elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- LOCAL_INCLUDES += [
- '/dom/system/gonk',
- ]
if CONFIG['MOZ_WEBSPEECH']:
LOCAL_INCLUDES += [
diff --git a/layout/build/nsLayoutModule.cpp b/layout/build/nsLayoutModule.cpp
index ab301a627..748bc11d8 100644
--- a/layout/build/nsLayoutModule.cpp
+++ b/layout/build/nsLayoutModule.cpp
@@ -100,20 +100,6 @@
#include "mozilla/dom/nsSynthVoiceRegistry.h"
#endif
-#ifdef MOZ_WIDGET_GONK
-#include "SystemWorkerManager.h"
-using mozilla::dom::gonk::SystemWorkerManager;
-#define SYSTEMWORKERMANAGER_CID \
- {0xd53b6524, 0x6ac3, 0x42b0, {0xae, 0xca, 0x62, 0xb3, 0xc4, 0xe5, 0x2b, 0x04}}
-#endif
-
-#ifdef MOZ_WIDGET_GONK
-#include "AudioManager.h"
-using mozilla::dom::gonk::AudioManager;
-#include "nsVolumeService.h"
-using mozilla::system::nsVolumeService;
-#endif
-
#include "mozilla/dom/PushNotifier.h"
using mozilla::dom::PushNotifier;
#define PUSHNOTIFIER_CID \
@@ -135,11 +121,9 @@ using mozilla::dom::AudioChannelAgent;
#include "nsSystemPrincipal.h"
#include "nsNullPrincipal.h"
#include "nsNetCID.h"
-#ifndef MOZ_WIDGET_GONK
#if defined(MOZ_WIDGET_ANDROID)
#include "nsHapticFeedback.h"
#endif
-#endif
#include "nsParserUtils.h"
#include "nsHTMLCanvasFrame.h"
@@ -201,9 +185,6 @@ static void Shutdown();
#include "nsIPresentationService.h"
-#ifdef MOZ_WIDGET_GONK
-#include "GonkGPSGeolocationProvider.h"
-#endif
#include "MediaManager.h"
#include "GMPService.h"
@@ -213,11 +194,6 @@ static void Shutdown();
#include "mozilla/TextInputProcessor.h"
-#ifdef MOZ_B2G
-#include "nsIHardwareKeyHandler.h"
-#include "mozilla/HardwareKeyHandler.h"
-#endif
-
using namespace mozilla;
using namespace mozilla::dom;
using mozilla::dom::power::PowerManagerService;
@@ -289,30 +265,18 @@ NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(ServiceWorkerManager,
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(WorkerDebuggerManager,
WorkerDebuggerManager::GetInstance)
-#ifdef MOZ_WIDGET_GONK
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(SystemWorkerManager,
- SystemWorkerManager::FactoryCreate)
-#endif
-
#ifdef MOZ_WEBSPEECH
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsSynthVoiceRegistry,
nsSynthVoiceRegistry::GetInstanceForService)
#endif
-#ifdef MOZ_WIDGET_GONK
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(AudioManager,
- AudioManager::GetInstance)
-#endif
-
NS_GENERIC_FACTORY_CONSTRUCTOR(AudioChannelAgent)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsDeviceSensors)
-#ifndef MOZ_WIDGET_GONK
#if defined(ANDROID)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsHapticFeedback)
#endif
-#endif
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(ThirdPartyUtil, Init)
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIPowerManagerService,
PowerManagerService::GetInstance)
@@ -321,16 +285,6 @@ NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsITimeService,
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIStreamingProtocolControllerService,
StreamingProtocolControllerService::GetInstance)
-#ifdef MOZ_WIDGET_GONK
-#ifndef DISABLE_MOZ_RIL_GEOLOC
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIGeolocationProvider,
- GonkGPSGeolocationProvider::GetSingleton)
-#endif
-// Since the nsVolumeService constructor calls into nsIPowerManagerService,
-// we need it to be constructed sometime after nsIPowerManagerService.
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsVolumeService,
- nsVolumeService::GetSingleton)
-#endif
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIMediaManagerService,
MediaManager::GetInstance)
NS_GENERIC_FACTORY_CONSTRUCTOR(PresentationDeviceManager)
@@ -608,11 +562,6 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(UDPSocketChild)
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(GeckoMediaPluginService, GeckoMediaPluginService::GetGeckoMediaPluginService)
-#ifdef MOZ_B2G
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIHardwareKeyHandler,
- HardwareKeyHandler::GetInstance)
-#endif
-
#ifdef ACCESSIBILITY
#include "xpcAccessibilityService.h"
@@ -712,13 +661,6 @@ NS_DEFINE_NAMED_CID(NOTIFICATIONTELEMETRYSERVICE_CID);
NS_DEFINE_NAMED_CID(PUSHNOTIFIER_CID);
NS_DEFINE_NAMED_CID(WORKERDEBUGGERMANAGER_CID);
-#ifdef MOZ_WIDGET_GONK
-NS_DEFINE_NAMED_CID(SYSTEMWORKERMANAGER_CID);
-#endif
-#ifdef MOZ_WIDGET_GONK
-NS_DEFINE_NAMED_CID(NS_AUDIOMANAGER_CID);
-NS_DEFINE_NAMED_CID(NS_VOLUMESERVICE_CID);
-#endif
NS_DEFINE_NAMED_CID(NS_AUDIOCHANNELAGENT_CID);
@@ -750,16 +692,9 @@ NS_DEFINE_NAMED_CID(THIRDPARTYUTIL_CID);
NS_DEFINE_NAMED_CID(NS_STRUCTUREDCLONECONTAINER_CID);
NS_DEFINE_NAMED_CID(NS_DEVICE_SENSORS_CID);
-#ifndef MOZ_WIDGET_GONK
#if defined(ANDROID)
NS_DEFINE_NAMED_CID(NS_HAPTICFEEDBACK_CID);
#endif
-#endif
-#ifndef DISABLE_MOZ_RIL_GEOLOC
-#ifdef MOZ_WIDGET_GONK
-NS_DEFINE_NAMED_CID(GONK_GPS_GEOLOCATION_PROVIDER_CID);
-#endif
-#endif
NS_DEFINE_NAMED_CID(NS_POWERMANAGERSERVICE_CID);
NS_DEFINE_NAMED_CID(OSFILECONSTANTSSERVICE_CID);
NS_DEFINE_NAMED_CID(UDPSOCKETCHILD_CID);
@@ -788,10 +723,6 @@ NS_DEFINE_NAMED_CID(PRESENTATION_TCP_SESSION_TRANSPORT_CID);
NS_DEFINE_NAMED_CID(TEXT_INPUT_PROCESSOR_CID);
-#ifdef MOZ_B2G
-NS_DEFINE_NAMED_CID(NS_HARDWARE_KEY_HANDLER_CID);
-#endif
-
static nsresult
CreateWindowCommandTableConstructor(nsISupports *aOuter,
REFNSIID aIID, void **aResult)
@@ -997,13 +928,6 @@ static const mozilla::Module::CIDEntry kLayoutCIDs[] = {
{ &kNOTIFICATIONTELEMETRYSERVICE_CID, false, nullptr, NotificationTelemetryServiceConstructor },
{ &kPUSHNOTIFIER_CID, false, nullptr, PushNotifierConstructor },
{ &kWORKERDEBUGGERMANAGER_CID, true, nullptr, WorkerDebuggerManagerConstructor },
-#ifdef MOZ_WIDGET_GONK
- { &kSYSTEMWORKERMANAGER_CID, true, nullptr, SystemWorkerManagerConstructor },
-#endif
-#ifdef MOZ_WIDGET_GONK
- { &kNS_AUDIOMANAGER_CID, true, nullptr, AudioManagerConstructor },
- { &kNS_VOLUMESERVICE_CID, true, nullptr, nsVolumeServiceConstructor },
-#endif
{ &kNS_AUDIOCHANNELAGENT_CID, true, nullptr, AudioChannelAgentConstructor },
{ &kNS_HTMLEDITOR_CID, false, nullptr, HTMLEditorConstructor },
{ &kNS_EDITORCONTROLLER_CID, false, nullptr, EditorControllerConstructor },
@@ -1039,11 +963,9 @@ static const mozilla::Module::CIDEntry kLayoutCIDs[] = {
{ &kNS_SYSTEMPRINCIPAL_CID, false, nullptr, nsSystemPrincipalConstructor },
{ &kNS_NULLPRINCIPAL_CID, false, nullptr, nsNullPrincipalConstructor },
{ &kNS_DEVICE_SENSORS_CID, false, nullptr, nsDeviceSensorsConstructor },
-#ifndef MOZ_WIDGET_GONK
#if defined(ANDROID)
{ &kNS_HAPTICFEEDBACK_CID, false, nullptr, nsHapticFeedbackConstructor },
#endif
-#endif
{ &kTHIRDPARTYUTIL_CID, false, nullptr, ThirdPartyUtilConstructor },
{ &kNS_STRUCTUREDCLONECONTAINER_CID, false, nullptr, nsStructuredCloneContainerConstructor },
{ &kNS_POWERMANAGERSERVICE_CID, false, nullptr, nsIPowerManagerServiceConstructor, Module::ALLOW_IN_GPU_PROCESS },
@@ -1052,9 +974,6 @@ static const mozilla::Module::CIDEntry kLayoutCIDs[] = {
{ &kGECKO_MEDIA_PLUGIN_SERVICE_CID, true, nullptr, GeckoMediaPluginServiceConstructor },
{ &kNS_TIMESERVICE_CID, false, nullptr, nsITimeServiceConstructor },
{ &kNS_MEDIASTREAMCONTROLLERSERVICE_CID, false, nullptr, nsIStreamingProtocolControllerServiceConstructor },
-#if defined(MOZ_WIDGET_GONK) && !defined(DISABLE_MOZ_RIL_GEOLOC)
- { &kGONK_GPS_GEOLOCATION_PROVIDER_CID, false, nullptr, nsIGeolocationProviderConstructor },
-#endif
{ &kNS_MEDIAMANAGERSERVICE_CID, false, nullptr, nsIMediaManagerServiceConstructor },
#ifdef ACCESSIBILITY
{ &kNS_ACCESSIBILITY_SERVICE_CID, false, nullptr, CreateA11yService },
@@ -1063,9 +982,6 @@ static const mozilla::Module::CIDEntry kLayoutCIDs[] = {
{ &kPRESENTATION_DEVICE_MANAGER_CID, false, nullptr, PresentationDeviceManagerConstructor },
{ &kPRESENTATION_TCP_SESSION_TRANSPORT_CID, false, nullptr, PresentationTCPSessionTransportConstructor },
{ &kTEXT_INPUT_PROCESSOR_CID, false, nullptr, TextInputProcessorConstructor },
-#ifdef MOZ_B2G
- { &kNS_HARDWARE_KEY_HANDLER_CID, false, nullptr, nsIHardwareKeyHandlerConstructor },
-#endif
{ nullptr }
};
@@ -1144,13 +1060,6 @@ static const mozilla::Module::ContractIDEntry kLayoutContracts[] = {
{ NOTIFICATIONTELEMETRYSERVICE_CONTRACTID, &kNOTIFICATIONTELEMETRYSERVICE_CID },
{ PUSHNOTIFIER_CONTRACTID, &kPUSHNOTIFIER_CID },
{ WORKERDEBUGGERMANAGER_CONTRACTID, &kWORKERDEBUGGERMANAGER_CID },
-#ifdef MOZ_WIDGET_GONK
- { SYSTEMWORKERMANAGER_CONTRACTID, &kSYSTEMWORKERMANAGER_CID },
-#endif
-#ifdef MOZ_WIDGET_GONK
- { NS_AUDIOMANAGER_CONTRACTID, &kNS_AUDIOMANAGER_CID },
- { NS_VOLUMESERVICE_CONTRACTID, &kNS_VOLUMESERVICE_CID },
-#endif
{ NS_AUDIOCHANNELAGENT_CONTRACTID, &kNS_AUDIOCHANNELAGENT_CID },
{ "@mozilla.org/editor/htmleditor;1", &kNS_HTMLEDITOR_CID },
{ "@mozilla.org/editor/editorcontroller;1", &kNS_EDITORCONTROLLER_CID },
@@ -1185,11 +1094,9 @@ static const mozilla::Module::ContractIDEntry kLayoutContracts[] = {
{ NS_SYSTEMPRINCIPAL_CONTRACTID, &kNS_SYSTEMPRINCIPAL_CID },
{ NS_NULLPRINCIPAL_CONTRACTID, &kNS_NULLPRINCIPAL_CID },
{ NS_DEVICE_SENSORS_CONTRACTID, &kNS_DEVICE_SENSORS_CID },
-#ifndef MOZ_WIDGET_GONK
#if defined(ANDROID)
{ "@mozilla.org/widget/hapticfeedback;1", &kNS_HAPTICFEEDBACK_CID },
#endif
-#endif
{ THIRDPARTYUTIL_CONTRACTID, &kTHIRDPARTYUTIL_CID },
{ NS_STRUCTUREDCLONECONTAINER_CONTRACTID, &kNS_STRUCTUREDCLONECONTAINER_CID },
{ POWERMANAGERSERVICE_CONTRACTID, &kNS_POWERMANAGERSERVICE_CID, Module::ALLOW_IN_GPU_PROCESS },
@@ -1197,9 +1104,6 @@ static const mozilla::Module::ContractIDEntry kLayoutContracts[] = {
{ "@mozilla.org/udp-socket-child;1", &kUDPSOCKETCHILD_CID },
{ TIMESERVICE_CONTRACTID, &kNS_TIMESERVICE_CID },
{ MEDIASTREAMCONTROLLERSERVICE_CONTRACTID, &kNS_MEDIASTREAMCONTROLLERSERVICE_CID },
-#if defined(MOZ_WIDGET_GONK) && !defined(DISABLE_MOZ_RIL_GEOLOC)
- { GONK_GPS_GEOLOCATION_PROVIDER_CONTRACTID, &kGONK_GPS_GEOLOCATION_PROVIDER_CID },
-#endif
{ MEDIAMANAGERSERVICE_CONTRACTID, &kNS_MEDIAMANAGERSERVICE_CID },
#ifdef ACCESSIBILITY
{ "@mozilla.org/accessibilityService;1", &kNS_ACCESSIBILITY_SERVICE_CID },
@@ -1210,9 +1114,6 @@ static const mozilla::Module::ContractIDEntry kLayoutContracts[] = {
{ PRESENTATION_DEVICE_MANAGER_CONTRACTID, &kPRESENTATION_DEVICE_MANAGER_CID },
{ PRESENTATION_TCP_SESSION_TRANSPORT_CONTRACTID, &kPRESENTATION_TCP_SESSION_TRANSPORT_CID },
{ "@mozilla.org/text-input-processor;1", &kTEXT_INPUT_PROCESSOR_CID },
-#ifdef MOZ_B2G
- { NS_HARDWARE_KEY_HANDLER_CONTRACTID, &kNS_HARDWARE_KEY_HANDLER_CID },
-#endif
{ nullptr }
};
@@ -1228,13 +1129,7 @@ static const mozilla::Module::CategoryEntry kLayoutCategories[] = {
{ "app-startup", "Push Notifier", "service," PUSHNOTIFIER_CONTRACTID },
{ "clear-origin-attributes-data", "QuotaManagerService", "service," QUOTAMANAGER_SERVICE_CONTRACTID },
{ OBSERVER_TOPIC_IDLE_DAILY, "QuotaManagerService", QUOTAMANAGER_SERVICE_CONTRACTID },
-#ifdef MOZ_WIDGET_GONK
- { "app-startup", "Volume Service", "service," NS_VOLUMESERVICE_CONTRACTID },
-#endif
CONTENTDLF_CATEGORIES
-#ifdef MOZ_WIDGET_GONK
- { "profile-after-change", "Gonk System Worker Manager", SYSTEMWORKERMANAGER_CONTRACTID },
-#endif
{ "profile-after-change", "PresentationDeviceManager", PRESENTATION_DEVICE_MANAGER_CONTRACTID },
{ "profile-after-change", "PresentationService", PRESENTATION_SERVICE_CONTRACTID },
{ "profile-after-change", "Notification Telemetry Service", NOTIFICATIONTELEMETRYSERVICE_CONTRACTID },
diff --git a/layout/build/nsLayoutStatics.cpp b/layout/build/nsLayoutStatics.cpp
index 3f534c8d8..0306626c4 100644
--- a/layout/build/nsLayoutStatics.cpp
+++ b/layout/build/nsLayoutStatics.cpp
@@ -100,11 +100,6 @@
#include "Latency.h"
#include "WebAudioUtils.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsVolumeService.h"
-using namespace mozilla::system;
-#endif
-
#include "nsError.h"
#include "nsJSEnvironment.h"
@@ -395,10 +390,6 @@ nsLayoutStatics::Shutdown()
AsyncLatencyLogger::ShutdownLogger();
WebAudioUtils::Shutdown();
-#ifdef MOZ_WIDGET_GONK
- nsVolumeService::Shutdown();
-#endif
-
#ifdef MOZ_WEBSPEECH
nsSynthVoiceRegistry::Shutdown();
#endif
diff --git a/layout/forms/nsNumberControlFrame.cpp b/layout/forms/nsNumberControlFrame.cpp
index 58421ecb9..74dec2bea 100644
--- a/layout/forms/nsNumberControlFrame.cpp
+++ b/layout/forms/nsNumberControlFrame.cpp
@@ -680,14 +680,12 @@ nsNumberControlFrame::SetValueOfAnonTextControl(const nsAString& aValue)
// state will be set to invalid) or if aValue can't be localized:
nsAutoString localizedValue(aValue);
-#ifdef ENABLE_INTL_API
// Try and localize the value we will set:
Decimal val = HTMLInputElement::StringToDecimal(aValue);
if (val.isFinite()) {
ICUUtils::LanguageTagIterForContent langTagIter(mContent);
ICUUtils::LocalizeNumber(val.toDouble(), langTagIter, localizedValue);
}
-#endif
// We need to update the value of our anonymous text control here. Note that
// this must be its value, and not its 'value' attribute (the default value),
@@ -706,7 +704,6 @@ nsNumberControlFrame::GetValueOfAnonTextControl(nsAString& aValue)
HTMLInputElement::FromContent(mTextField)->GetValue(aValue);
-#ifdef ENABLE_INTL_API
// Here we need to de-localize any number typed in by the user. That is, we
// need to convert it from the number format of the user's language, region,
// etc. to the format that the HTML 5 spec defines to be a "valid
@@ -747,7 +744,6 @@ nsNumberControlFrame::GetValueOfAnonTextControl(nsAString& aValue)
// as 12.345, but HTMLInputElement::StringToDecimal would parse it to NaN.
aValue.Truncate();
aValue.AppendFloat(value);
-#endif
}
bool
diff --git a/layout/generic/Selection.h b/layout/generic/Selection.h
index 3d5e334fc..5414d15c1 100644
--- a/layout/generic/Selection.h
+++ b/layout/generic/Selection.h
@@ -51,8 +51,9 @@ struct RangeData
namespace mozilla {
namespace dom {
-class Selection final : public nsISelectionPrivate,
+class Selection final : public nsISelection,
public nsWrapperCache,
+ public nsISelectionPrivate,
public nsSupportsWeakReference
{
protected:
@@ -63,7 +64,7 @@ public:
explicit Selection(nsFrameSelection *aList);
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
- NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Selection, nsISelectionPrivate)
+ NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Selection, nsISelection)
NS_DECL_NSISELECTION
NS_DECL_NSISELECTIONPRIVATE
diff --git a/layout/generic/nsGfxScrollFrame.cpp b/layout/generic/nsGfxScrollFrame.cpp
index f664845b6..ccdc3a0ce 100644
--- a/layout/generic/nsGfxScrollFrame.cpp
+++ b/layout/generic/nsGfxScrollFrame.cpp
@@ -1266,7 +1266,7 @@ ScrollFrameHelper::HandleScrollbarStyleSwitching()
}
}
-#if defined(MOZ_B2G) || defined(MOZ_WIDGET_ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
static bool IsFocused(nsIContent* aContent)
{
// Some content elements, like the GetContent() of a scroll frame
@@ -1315,7 +1315,7 @@ ScrollFrameHelper::WantAsyncScroll() const
bool isHScrollable = (scrollRange.width >= oneDevPixel) &&
(styles.mHorizontal != NS_STYLE_OVERFLOW_HIDDEN);
-#if defined(MOZ_B2G) || defined(MOZ_WIDGET_ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
// Mobile platforms need focus to scroll.
bool canScrollWithoutScrollbars = IsFocused(mOuter->GetContent());
#else
diff --git a/layout/generic/nsTextFrame.cpp b/layout/generic/nsTextFrame.cpp
index 00c0016fd..fa31443fd 100644
--- a/layout/generic/nsTextFrame.cpp
+++ b/layout/generic/nsTextFrame.cpp
@@ -2936,22 +2936,40 @@ nsTextFrame::GetTrimmedOffsets(const nsTextFragment* aFrag,
return offsets;
}
-static bool IsJustifiableCharacter(const nsTextFragment* aFrag, int32_t aPos,
+static bool IsJustifiableCharacter(const nsStyleText* aTextStyle,
+ const nsTextFragment* aFrag, int32_t aPos,
bool aLangIsCJ)
{
NS_ASSERTION(aPos >= 0, "negative position?!");
+
+ StyleTextJustify justifyStyle = aTextStyle->mTextJustify;
+ if (justifyStyle == StyleTextJustify::None) {
+ return false;
+ }
+
char16_t ch = aFrag->CharAt(aPos);
- if (ch == '\n' || ch == '\t' || ch == '\r')
+ if (ch == '\n' || ch == '\t' || ch == '\r') {
return true;
+ }
if (ch == ' ' || ch == CH_NBSP) {
// Don't justify spaces that are combined with diacriticals
- if (!aFrag->Is2b())
+ if (!aFrag->Is2b()) {
return true;
+ }
return !nsTextFrameUtils::IsSpaceCombiningSequenceTail(
- aFrag->Get2b() + aPos + 1, aFrag->GetLength() - (aPos + 1));
+ aFrag->Get2b() + aPos + 1, aFrag->GetLength() - (aPos + 1));
}
- if (ch < 0x2150u)
+
+ if (justifyStyle == StyleTextJustify::InterCharacter) {
+ return true;
+ } else if (justifyStyle == StyleTextJustify::InterWord) {
+ return false;
+ }
+
+ // text-justify: auto
+ if (ch < 0x2150u) {
return false;
+ }
if (aLangIsCJ) {
if ((0x2150u <= ch && ch <= 0x22ffu) || // Number Forms, Arrows, Mathematical Operators
(0x2460u <= ch && ch <= 0x24ffu) || // Enclosed Alphanumerics
@@ -3279,7 +3297,7 @@ PropertyProvider::ComputeJustification(
gfxSkipCharsIterator iter = run.GetPos();
for (uint32_t i = 0; i < length; ++i) {
uint32_t offset = originalOffset + i;
- if (!IsJustifiableCharacter(mFrag, offset, isCJ)) {
+ if (!IsJustifiableCharacter(mTextStyle, mFrag, offset, isCJ)) {
continue;
}
diff --git a/layout/reftests/transform-3d/animate-backface-hidden.html b/layout/reftests/transform-3d/animate-backface-hidden.html
index ce957bf73..27b587006 100644
--- a/layout/reftests/transform-3d/animate-backface-hidden.html
+++ b/layout/reftests/transform-3d/animate-backface-hidden.html
@@ -17,7 +17,7 @@ body { padding: 50px }
height: 200px; width: 200px;
backface-visibility: hidden;
/* use a -99.9s delay to start at 99.9% and then move to 0% */
- animation: flip 100s -99.9s linear 2;
+ animation: flip 100s -99.9s linear 2 paused;
}
</style>
@@ -27,7 +27,13 @@ body { padding: 50px }
<script>
-document.getElementById("test").addEventListener("animationiteration", IterationListener, false);
+document.getElementById("test").addEventListener("animationstart", StartListener, false);
+
+function StartListener(event) {
+ var test = document.getElementById("test");
+ test.style.animationPlayState = 'running';
+ test.addEventListener("animationiteration", IterationListener, false);
+}
function IterationListener(event) {
setTimeout(RemoveReftestWait, 0);
diff --git a/layout/reftests/transform-3d/animate-preserve3d-parent.html b/layout/reftests/transform-3d/animate-preserve3d-parent.html
index ae3fec196..d05beac6f 100644
--- a/layout/reftests/transform-3d/animate-preserve3d-parent.html
+++ b/layout/reftests/transform-3d/animate-preserve3d-parent.html
@@ -18,7 +18,7 @@ body { padding: 50px }
border: 1px solid black;
transform-style: preserve-3d;
/* use a -99.9s delay to start at 99.9% and then move to 0% */
- animation: spin 100s -99.9s linear 2;
+ animation: spin 100s -99.9s linear 2 paused;
}
#child {
@@ -39,7 +39,13 @@ body { padding: 50px }
<script>
-document.getElementById("parent").addEventListener("animationiteration", IterationListener, false);
+document.getElementById("parent").addEventListener("animationstart", StartListener, false);
+
+function StartListener(event) {
+ var test = document.getElementById("parent");
+ test.style.animationPlayState = 'running';
+ test.addEventListener("animationiteration", IterationListener, false);
+}
function IterationListener(event) {
setTimeout(RemoveReftestWait, 0);
diff --git a/layout/reftests/w3c-css/submitted/check-for-references.sh b/layout/reftests/w3c-css/submitted/check-for-references.sh
index 977cee3f4..c30e18515 100755
--- a/layout/reftests/w3c-css/submitted/check-for-references.sh
+++ b/layout/reftests/w3c-css/submitted/check-for-references.sh
@@ -15,7 +15,7 @@ do
else
echo "Unexpected type $TYPE for $DIRNAME/$TEST"
fi
- if grep "rel=\"$REFTYPE\"" "$DIRNAME/$TEST" | head -1 | grep -q "href=\"$REF\""
+ if grep "rel=\(\"$REFTYPE\"\|'$REFTYPE'\)" "$DIRNAME/$TEST" | head -1 | grep -q "href=\(\"$REF\"\|'$REF'\)"
then
#echo "Good link for $DIRNAME/$TEST"
echo -n
diff --git a/layout/reftests/w3c-css/submitted/text3/reftest.list b/layout/reftests/w3c-css/submitted/text3/reftest.list
index 2712e4363..a1e3d70d0 100644
--- a/layout/reftests/w3c-css/submitted/text3/reftest.list
+++ b/layout/reftests/w3c-css/submitted/text3/reftest.list
@@ -5,4 +5,9 @@
== text-align-match-parent-root-ltr.html text-align-match-parent-root-ltr-ref.html
== text-align-match-parent-root-rtl.html text-align-match-parent-root-rtl-ref.html
+pref(layout.css.text-justify.enabled,true) == text-justify-none-001.html text-justify-none-001-ref.html
+pref(layout.css.text-justify.enabled,true) == text-justify-inter-word-001.html text-justify-inter-word-001-ref.html
+pref(layout.css.text-justify.enabled,true) == text-justify-inter-character-001.html text-justify-inter-character-001-ref.html
+pref(layout.css.text-justify.enabled,true) == text-justify-distribute-001.html text-justify-inter-character-001-ref.html
+
== text-word-spacing-001.html text-word-spacing-ref.html
diff --git a/layout/reftests/w3c-css/submitted/text3/text-justify-distribute-001.html b/layout/reftests/w3c-css/submitted/text3/text-justify-distribute-001.html
new file mode 100644
index 000000000..4d29f0fee
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/text3/text-justify-distribute-001.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>CSS Text 7.4. Justification Method: text-justify: distribute</title>
+<link rel="author" title="Chun-Min (Jeremy) Chen" href="mailto:jeremychen@mozilla.com">
+<link rel="author" title="Mozilla" href="https://www.mozilla.org">
+<link rel="help" href="https://drafts.csswg.org/css-text-3/#text-justify-property">
+<link rel='match' href='text-justify-inter-character-001-ref.html'>
+<meta name="assert" content="text-justify:distribute means justification adjusts spacing between each pair of adjacent typographic character units.">
+<style type='text/css'>
+p {
+ font-size: 1.5em;
+ border: 1px solid black;
+ padding: 10px;
+ margin-right: 310px;
+}
+.test {
+ text-align-last: justify;
+ text-justify: distribute;
+}
+</style>
+</head>
+<body>
+<p lang="en" class="test">XX</p>
+<p lang="ja" class="test">文字</p>
+</body>
+</html>
diff --git a/layout/reftests/w3c-css/submitted/text3/text-justify-inter-character-001-ref.html b/layout/reftests/w3c-css/submitted/text3/text-justify-inter-character-001-ref.html
new file mode 100644
index 000000000..0a42a5cf8
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/text3/text-justify-inter-character-001-ref.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>CSS Text 7.4. Justification Method: text-justify: inter-character</title>
+<link rel="author" title="Chun-Min (Jeremy) Chen" href="mailto:jeremychen@mozilla.com">
+<link rel="author" title="Mozilla" href="https://www.mozilla.org">
+<style type='text/css'>
+p {
+ font-size: 1.5em;
+ border: 1px solid black;
+ padding: 10px;
+ margin-right: 310px;
+}
+.right {
+ float: right;
+}
+</style>
+</head>
+<body>
+<p lang="en">X<span class="right">X</span></p>
+<p lang="ja">文<span class="right">字</span></p>
+</body>
+</html>
diff --git a/layout/reftests/w3c-css/submitted/text3/text-justify-inter-character-001.html b/layout/reftests/w3c-css/submitted/text3/text-justify-inter-character-001.html
new file mode 100644
index 000000000..639ab7ecb
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/text3/text-justify-inter-character-001.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>CSS Text 7.4. Justification Method: text-justify: inter-character</title>
+<link rel="author" title="Chun-Min (Jeremy) Chen" href="mailto:jeremychen@mozilla.com">
+<link rel="author" title="Mozilla" href="https://www.mozilla.org">
+<link rel="help" href="https://drafts.csswg.org/css-text-3/#text-justify-property">
+<link rel='match' href='text-justify-inter-character-001-ref.html'>
+<meta name="assert" content="text-justify:inter-character means justification adjusts spacing between each pair of adjacent typographic character units.">
+<style type='text/css'>
+p {
+ font-size: 1.5em;
+ border: 1px solid black;
+ padding: 10px;
+ margin-right: 310px;
+}
+.test {
+ text-align-last: justify;
+ text-justify: inter-character;
+}
+</style>
+</head>
+<body>
+<p lang="en" class="test">XX</p>
+<p lang="ja" class="test">文字</p>
+</body>
+</html>
diff --git a/layout/reftests/w3c-css/submitted/text3/text-justify-inter-word-001-ref.html b/layout/reftests/w3c-css/submitted/text3/text-justify-inter-word-001-ref.html
new file mode 100644
index 000000000..687e864e7
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/text3/text-justify-inter-word-001-ref.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>CSS Text 7.4. Justification Method: text-justify: inter-word</title>
+<link rel="author" title="Chun-Min (Jeremy) Chen" href="mailto:jeremychen@mozilla.com">
+<link rel="author" title="Mozilla" href="https://www.mozilla.org">
+<style type='text/css'>
+p {
+ font-size: 1.5em;
+ border: 1px solid black;
+ padding: 10px;
+ margin-right: 310px;
+}
+.right {
+ float: right;
+}
+</style>
+</head>
+<body>
+<p lang="en">Latin<span class="right">text</span></p>
+<p lang="ja">日本<span class="right">文字</span></p>
+<p lang="th">อักษรไทย<span class="right">อักษรไทย</span></p>
+</body>
+</html>
diff --git a/layout/reftests/w3c-css/submitted/text3/text-justify-inter-word-001.html b/layout/reftests/w3c-css/submitted/text3/text-justify-inter-word-001.html
new file mode 100644
index 000000000..75aec2f5f
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/text3/text-justify-inter-word-001.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>CSS Text 7.4. Justification Method: text-justify: inter-word</title>
+<link rel="author" title="Chun-Min (Jeremy) Chen" href="mailto:jeremychen@mozilla.com">
+<link rel="author" title="Mozilla" href="https://www.mozilla.org">
+<link rel="help" href="https://drafts.csswg.org/css-text-3/#text-justify-property">
+<link rel='match' href='text-justify-inter-word-001-ref.html'>
+<meta name="assert" content="text-justify:inter-word means justification adjusts spacing at word separators only.">
+<style type='text/css'>
+p {
+ font-size: 1.5em;
+ border: 1px solid black;
+ padding: 10px;
+ margin-right: 310px;
+}
+.test {
+ text-align-last: justify;
+ text-justify: inter-word;
+}
+</style>
+</head>
+<body>
+<p lang="en" class="test">Latin text</p>
+<p lang="ja" class="test">日本 文字</p>
+<p lang="th" class="test">อักษรไทย อักษรไทย</p>
+</body>
+</html>
diff --git a/layout/reftests/w3c-css/submitted/text3/text-justify-none-001-ref.html b/layout/reftests/w3c-css/submitted/text3/text-justify-none-001-ref.html
new file mode 100644
index 000000000..c8500ac9f
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/text3/text-justify-none-001-ref.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>CSS Text 7.4. Justification Method: text-justify: none</title>
+<link rel="author" title="Chun-Min (Jeremy) Chen" href="mailto:jeremychen@mozilla.com">
+<link rel="author" title="Mozilla" href="https://www.mozilla.org">
+<style type='text/css'>
+p {
+ font-size: 1.5em;
+ border: 1px solid black;
+ padding: 10px;
+ margin-right: 310px;
+}
+</style>
+</head>
+<body>
+<p lang="en">Latin text</p>
+<p lang="ja">日本 文字</p>
+<p lang="th">อักษรไทย อักษรไทย</p>
+</body>
+</html>
diff --git a/layout/reftests/w3c-css/submitted/text3/text-justify-none-001.html b/layout/reftests/w3c-css/submitted/text3/text-justify-none-001.html
new file mode 100644
index 000000000..2b5511195
--- /dev/null
+++ b/layout/reftests/w3c-css/submitted/text3/text-justify-none-001.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>CSS Text 7.4. Justification Method: text-justify: none</title>
+<link rel="author" title="Chun-Min (Jeremy) Chen" href="mailto:jeremychen@mozilla.com">
+<link rel="author" title="Mozilla" href="https://www.mozilla.org">
+<link rel="help" href="https://drafts.csswg.org/css-text-3/#text-justify-property">
+<link rel='match' href='text-justify-none-001-ref.html'>
+<meta name="assert" content="text-justify:none means justification is disabled: there are no justification opportunities within the text.">
+<style type='text/css'>
+p {
+ font-size: 1.5em;
+ border: 1px solid black;
+ padding: 10px;
+ margin-right: 310px;
+}
+.test {
+ text-align-last: justify;
+ text-justify: none;
+}
+</style>
+</head>
+<body>
+<p lang="en" class="test">Latin text</p>
+<p lang="ja" class="test">日本 文字</p>
+<p lang="th" class="test">อักษรไทย อักษรไทย</p>
+</body>
+</html>
diff --git a/layout/style/AnimationCommon.h b/layout/style/AnimationCommon.h
index 37030411c..025c034a4 100644
--- a/layout/style/AnimationCommon.h
+++ b/layout/style/AnimationCommon.h
@@ -251,6 +251,26 @@ ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback,
aField.Traverse(&aCallback, aName);
}
+// Return the TransitionPhase or AnimationPhase to use when the animation
+// doesn't have a target effect.
+template <typename PhaseType>
+PhaseType GetAnimationPhaseWithoutEffect(const dom::Animation& aAnimation)
+{
+ MOZ_ASSERT(!aAnimation.GetEffect(),
+ "Should only be called when we do not have an effect");
+
+ Nullable<TimeDuration> currentTime = aAnimation.GetCurrentTime();
+ if (currentTime.IsNull()) {
+ return PhaseType::Idle;
+ }
+
+ // If we don't have a target effect, the duration will be zero so the phase is
+ // 'before' if the current time is less than zero.
+ return currentTime.Value() < TimeDuration()
+ ? PhaseType::Before
+ : PhaseType::After;
+};
+
} // namespace mozilla
#endif /* !defined(mozilla_css_AnimationCommon_h) */
diff --git a/layout/style/nsAnimationManager.cpp b/layout/style/nsAnimationManager.cpp
index ed2b5afc7..aa1b6fe78 100644
--- a/layout/style/nsAnimationManager.cpp
+++ b/layout/style/nsAnimationManager.cpp
@@ -33,11 +33,15 @@ using mozilla::dom::AnimationPlayState;
using mozilla::dom::KeyframeEffectReadOnly;
using mozilla::dom::CSSAnimation;
+typedef mozilla::ComputedTiming::AnimationPhase AnimationPhase;
+
namespace {
-// Pair of an event message and elapsed time used when determining the set of
-// events to queue.
-typedef Pair<EventMessage, StickyTimeDuration> EventPair;
+struct AnimationEventParams {
+ EventMessage mMessage;
+ StickyTimeDuration mElapsedTime;
+ TimeStamp mTimeStamp;
+};
} // anonymous namespace
@@ -154,12 +158,8 @@ CSSAnimation::HasLowerCompositeOrderThan(const CSSAnimation& aOther) const
}
void
-CSSAnimation::QueueEvents()
+CSSAnimation::QueueEvents(StickyTimeDuration aActiveTime)
{
- if (!mEffect) {
- return;
- }
-
// If the animation is pending, we ignore animation events until we finish
// pending.
if (mPendingState != PendingState::NotPending) {
@@ -194,77 +194,116 @@ CSSAnimation::QueueEvents()
}
nsAnimationManager* manager = presContext->AnimationManager();
- ComputedTiming computedTiming = mEffect->GetComputedTiming();
- if (computedTiming.mPhase == ComputedTiming::AnimationPhase::Null) {
- return; // do nothing
+ const StickyTimeDuration zeroDuration;
+ uint64_t currentIteration = 0;
+ ComputedTiming::AnimationPhase currentPhase;
+ StickyTimeDuration intervalStartTime;
+ StickyTimeDuration intervalEndTime;
+ StickyTimeDuration iterationStartTime;
+
+ if (!mEffect) {
+ currentPhase = GetAnimationPhaseWithoutEffect
+ <ComputedTiming::AnimationPhase>(*this);
+ } else {
+ ComputedTiming computedTiming = mEffect->GetComputedTiming();
+ currentPhase = computedTiming.mPhase;
+ currentIteration = computedTiming.mCurrentIteration;
+ if (currentPhase == mPreviousPhase &&
+ currentIteration == mPreviousIteration) {
+ return;
+ }
+ intervalStartTime =
+ std::max(std::min(StickyTimeDuration(-mEffect->SpecifiedTiming().mDelay),
+ computedTiming.mActiveDuration),
+ zeroDuration);
+ intervalEndTime =
+ std::max(std::min((EffectEnd() - mEffect->SpecifiedTiming().mDelay),
+ computedTiming.mActiveDuration),
+ zeroDuration);
+
+ uint64_t iterationBoundary = mPreviousIteration > currentIteration
+ ? currentIteration + 1
+ : currentIteration;
+ iterationStartTime =
+ computedTiming.mDuration.MultDouble(
+ (iterationBoundary - computedTiming.mIterationStart));
}
- // Note that script can change the start time, so we have to handle moving
- // backwards through the animation as well as forwards. An 'animationstart'
- // is dispatched if we enter the active phase (regardless if that is from
- // before or after the animation's active phase). An 'animationend' is
- // dispatched if we leave the active phase (regardless if that is to before
- // or after the animation's active phase).
-
- bool wasActive = mPreviousPhaseOrIteration != PREVIOUS_PHASE_BEFORE &&
- mPreviousPhaseOrIteration != PREVIOUS_PHASE_AFTER;
- bool isActive =
- computedTiming.mPhase == ComputedTiming::AnimationPhase::Active;
- bool isSameIteration =
- computedTiming.mCurrentIteration == mPreviousPhaseOrIteration;
- bool skippedActivePhase =
- (mPreviousPhaseOrIteration == PREVIOUS_PHASE_BEFORE &&
- computedTiming.mPhase == ComputedTiming::AnimationPhase::After) ||
- (mPreviousPhaseOrIteration == PREVIOUS_PHASE_AFTER &&
- computedTiming.mPhase == ComputedTiming::AnimationPhase::Before);
- bool skippedFirstIteration =
- isActive &&
- mPreviousPhaseOrIteration == PREVIOUS_PHASE_BEFORE &&
- computedTiming.mCurrentIteration > 0;
-
- MOZ_ASSERT(!skippedActivePhase || (!isActive && !wasActive),
- "skippedActivePhase only makes sense if we were & are inactive");
-
- if (computedTiming.mPhase == ComputedTiming::AnimationPhase::Before) {
- mPreviousPhaseOrIteration = PREVIOUS_PHASE_BEFORE;
- } else if (computedTiming.mPhase == ComputedTiming::AnimationPhase::Active) {
- mPreviousPhaseOrIteration = computedTiming.mCurrentIteration;
- } else if (computedTiming.mPhase == ComputedTiming::AnimationPhase::After) {
- mPreviousPhaseOrIteration = PREVIOUS_PHASE_AFTER;
+ TimeStamp startTimeStamp = ElapsedTimeToTimeStamp(intervalStartTime);
+ TimeStamp endTimeStamp = ElapsedTimeToTimeStamp(intervalEndTime);
+ TimeStamp iterationTimeStamp = ElapsedTimeToTimeStamp(iterationStartTime);
+
+ AutoTArray<AnimationEventParams, 2> events;
+
+ // Handle cancel event first
+ if ((mPreviousPhase != AnimationPhase::Idle &&
+ mPreviousPhase != AnimationPhase::After) &&
+ currentPhase == AnimationPhase::Idle) {
+ TimeStamp activeTimeStamp = ElapsedTimeToTimeStamp(aActiveTime);
+ events.AppendElement(AnimationEventParams{ eAnimationCancel,
+ aActiveTime,
+ activeTimeStamp });
}
- AutoTArray<EventPair, 2> events;
- StickyTimeDuration initialAdvance = StickyTimeDuration(InitialAdvance());
- StickyTimeDuration iterationStart = computedTiming.mDuration *
- computedTiming.mCurrentIteration;
- const StickyTimeDuration& activeDuration = computedTiming.mActiveDuration;
-
- if (skippedFirstIteration) {
- // Notify animationstart and animationiteration in same tick.
- events.AppendElement(EventPair(eAnimationStart, initialAdvance));
- events.AppendElement(EventPair(eAnimationIteration,
- std::max(iterationStart, initialAdvance)));
- } else if (!wasActive && isActive) {
- events.AppendElement(EventPair(eAnimationStart, initialAdvance));
- } else if (wasActive && !isActive) {
- events.AppendElement(EventPair(eAnimationEnd, activeDuration));
- } else if (wasActive && isActive && !isSameIteration) {
- events.AppendElement(EventPair(eAnimationIteration, iterationStart));
- } else if (skippedActivePhase) {
- events.AppendElement(EventPair(eAnimationStart,
- std::min(initialAdvance, activeDuration)));
- events.AppendElement(EventPair(eAnimationEnd, activeDuration));
- } else {
- return; // No events need to be sent
+ switch (mPreviousPhase) {
+ case AnimationPhase::Idle:
+ case AnimationPhase::Before:
+ if (currentPhase == AnimationPhase::Active) {
+ events.AppendElement(AnimationEventParams{ eAnimationStart,
+ intervalStartTime,
+ startTimeStamp });
+ } else if (currentPhase == AnimationPhase::After) {
+ events.AppendElement(AnimationEventParams{ eAnimationStart,
+ intervalStartTime,
+ startTimeStamp });
+ events.AppendElement(AnimationEventParams{ eAnimationEnd,
+ intervalEndTime,
+ endTimeStamp });
+ }
+ break;
+ case AnimationPhase::Active:
+ if (currentPhase == AnimationPhase::Before) {
+ events.AppendElement(AnimationEventParams{ eAnimationEnd,
+ intervalStartTime,
+ startTimeStamp });
+ } else if (currentPhase == AnimationPhase::Active) {
+ // The currentIteration must have changed or element we would have
+ // returned early above.
+ MOZ_ASSERT(currentIteration != mPreviousIteration);
+ events.AppendElement(AnimationEventParams{ eAnimationIteration,
+ iterationStartTime,
+ iterationTimeStamp });
+ } else if (currentPhase == AnimationPhase::After) {
+ events.AppendElement(AnimationEventParams{ eAnimationEnd,
+ intervalEndTime,
+ endTimeStamp });
+ }
+ break;
+ case AnimationPhase::After:
+ if (currentPhase == AnimationPhase::Before) {
+ events.AppendElement(AnimationEventParams{ eAnimationStart,
+ intervalEndTime,
+ startTimeStamp});
+ events.AppendElement(AnimationEventParams{ eAnimationEnd,
+ intervalStartTime,
+ endTimeStamp });
+ } else if (currentPhase == AnimationPhase::Active) {
+ events.AppendElement(AnimationEventParams{ eAnimationStart,
+ intervalEndTime,
+ endTimeStamp });
+ }
+ break;
}
- for (const EventPair& pair : events){
+ mPreviousPhase = currentPhase;
+ mPreviousIteration = currentIteration;
+
+ for (const AnimationEventParams& event : events){
manager->QueueEvent(
AnimationEventInfo(owningElement, owningPseudoType,
- pair.first(), mAnimationName,
- pair.second(),
- ElapsedTimeToTimeStamp(pair.second()),
+ event.mMessage, mAnimationName,
+ event.mElapsedTime, event.mTimeStamp,
this));
}
}
diff --git a/layout/style/nsAnimationManager.h b/layout/style/nsAnimationManager.h
index abe3aeeb8..d838d090a 100644
--- a/layout/style/nsAnimationManager.h
+++ b/layout/style/nsAnimationManager.h
@@ -76,7 +76,8 @@ public:
, mIsStylePaused(false)
, mPauseShouldStick(false)
, mNeedsNewAnimationIndexWhenRun(false)
- , mPreviousPhaseOrIteration(PREVIOUS_PHASE_BEFORE)
+ , mPreviousPhase(ComputedTiming::AnimationPhase::Idle)
+ , mPreviousIteration(0)
{
// We might need to drop this assertion once we add a script-accessible
// constructor but for animations generated from CSS markup the
@@ -109,8 +110,6 @@ public:
void PauseFromStyle();
void CancelFromStyle() override
{
- mOwningElement = OwningElementRef();
-
// When an animation is disassociated with style it enters an odd state
// where its composite order is undefined until it first transitions
// out of the idle state.
@@ -125,10 +124,15 @@ public:
mNeedsNewAnimationIndexWhenRun = true;
Animation::CancelFromStyle();
+
+ // We need to do this *after* calling CancelFromStyle() since
+ // CancelFromStyle might synchronously trigger a cancel event for which
+ // we need an owning element to target the event at.
+ mOwningElement = OwningElementRef();
}
void Tick() override;
- void QueueEvents();
+ void QueueEvents(StickyTimeDuration aActiveTime = StickyTimeDuration());
bool IsStylePaused() const { return mIsStylePaused; }
@@ -157,6 +161,10 @@ public:
// reflect changes to that markup.
bool IsTiedToMarkup() const { return mOwningElement.IsSet(); }
+ void MaybeQueueCancelEvent(StickyTimeDuration aActiveTime) override {
+ QueueEvents(aActiveTime);
+ }
+
protected:
virtual ~CSSAnimation()
{
@@ -257,13 +265,10 @@ protected:
// its animation index should be updated.
bool mNeedsNewAnimationIndexWhenRun;
- enum {
- PREVIOUS_PHASE_BEFORE = uint64_t(-1),
- PREVIOUS_PHASE_AFTER = uint64_t(-2)
- };
- // One of the PREVIOUS_PHASE_* constants, or an integer for the iteration
- // whose start we last notified on.
- uint64_t mPreviousPhaseOrIteration;
+ // Phase and current iteration from the previous time we queued events.
+ // This is used to determine what new events to dispatch.
+ ComputedTiming::AnimationPhase mPreviousPhase;
+ uint64_t mPreviousIteration;
};
} /* namespace dom */
diff --git a/layout/style/nsCSSKeywordList.h b/layout/style/nsCSSKeywordList.h
index 933ff6e7b..94968faca 100644
--- a/layout/style/nsCSSKeywordList.h
+++ b/layout/style/nsCSSKeywordList.h
@@ -238,6 +238,7 @@ CSS_KEY(disc, disc)
CSS_KEY(disclosure-closed, disclosure_closed)
CSS_KEY(disclosure-open, disclosure_open)
CSS_KEY(discretionary-ligatures, discretionary_ligatures)
+CSS_KEY(distribute, distribute)
CSS_KEY(dot, dot)
CSS_KEY(dotted, dotted)
CSS_KEY(double, double)
@@ -333,7 +334,8 @@ CSS_KEY(inline-start, inline_start)
CSS_KEY(inline-table, inline_table)
CSS_KEY(inset, inset)
CSS_KEY(inside, inside)
-// CSS_KEY(inter-character, inter_character) // TODO see bug 1055672
+CSS_KEY(inter-character, inter_character)
+CSS_KEY(inter-word, inter_word)
CSS_KEY(interpolatematrix, interpolatematrix)
CSS_KEY(intersect, intersect)
CSS_KEY(isolate, isolate)
diff --git a/layout/style/nsCSSPropList.h b/layout/style/nsCSSPropList.h
index 6931d8c2b..b04921dcb 100644
--- a/layout/style/nsCSSPropList.h
+++ b/layout/style/nsCSSPropList.h
@@ -4027,6 +4027,17 @@ CSS_PROP_TEXT(
nullptr,
offsetof(nsStyleText, mTextIndent),
eStyleAnimType_Coord)
+CSS_PROP_TEXT(
+ text-justify,
+ text_justify,
+ TextJustify,
+ CSS_PROPERTY_PARSE_VALUE |
+ CSS_PROPERTY_APPLIES_TO_PLACEHOLDER,
+ "layout.css.text-justify.enabled",
+ VARIANT_HK,
+ kTextJustifyKTable,
+ CSS_PROP_NO_OFFSET,
+ eStyleAnimType_Discrete)
CSS_PROP_VISIBILITY(
text-orientation,
text_orientation,
diff --git a/layout/style/nsCSSProps.cpp b/layout/style/nsCSSProps.cpp
index f3a7f898d..9805eae14 100644
--- a/layout/style/nsCSSProps.cpp
+++ b/layout/style/nsCSSProps.cpp
@@ -2035,6 +2035,17 @@ KTableEntry nsCSSProps::kTextAlignLastKTable[] = {
{ eCSSKeyword_UNKNOWN, -1 }
};
+const KTableEntry nsCSSProps::kTextJustifyKTable[] = {
+ { eCSSKeyword_none, StyleTextJustify::None },
+ { eCSSKeyword_auto, StyleTextJustify::Auto },
+ { eCSSKeyword_inter_word, StyleTextJustify::InterWord },
+ { eCSSKeyword_inter_character, StyleTextJustify::InterCharacter },
+ // For legacy reasons, UAs must also support the keyword "distribute" with
+ // the exact same meaning and behavior as "inter-character".
+ { eCSSKeyword_distribute, StyleTextJustify::InterCharacter },
+ { eCSSKeyword_UNKNOWN, -1 }
+};
+
const KTableEntry nsCSSProps::kTextCombineUprightKTable[] = {
{ eCSSKeyword_none, NS_STYLE_TEXT_COMBINE_UPRIGHT_NONE },
{ eCSSKeyword_all, NS_STYLE_TEXT_COMBINE_UPRIGHT_ALL },
diff --git a/layout/style/nsCSSProps.h b/layout/style/nsCSSProps.h
index ab78e6174..dfe35afd8 100644
--- a/layout/style/nsCSSProps.h
+++ b/layout/style/nsCSSProps.h
@@ -869,6 +869,7 @@ public:
static const KTableEntry kTextEmphasisPositionKTable[];
static const KTableEntry kTextEmphasisStyleFillKTable[];
static const KTableEntry kTextEmphasisStyleShapeKTable[];
+ static const KTableEntry kTextJustifyKTable[];
static const KTableEntry kTextOrientationKTable[];
static const KTableEntry kTextOverflowKTable[];
static const KTableEntry kTextTransformKTable[];
diff --git a/layout/style/nsComputedDOMStyle.cpp b/layout/style/nsComputedDOMStyle.cpp
index 4eb24b76b..4f8d3edf6 100644
--- a/layout/style/nsComputedDOMStyle.cpp
+++ b/layout/style/nsComputedDOMStyle.cpp
@@ -3875,6 +3875,16 @@ nsComputedDOMStyle::DoGetTextIndent()
}
already_AddRefed<CSSValue>
+nsComputedDOMStyle::DoGetTextJustify()
+{
+ RefPtr<nsROCSSPrimitiveValue> val = new nsROCSSPrimitiveValue;
+ val->SetIdent(
+ nsCSSProps::ValueToKeywordEnum(StyleText()->mTextJustify,
+ nsCSSProps::kTextJustifyKTable));
+ return val.forget();
+}
+
+already_AddRefed<CSSValue>
nsComputedDOMStyle::DoGetTextOrientation()
{
RefPtr<nsROCSSPrimitiveValue> val = new nsROCSSPrimitiveValue;
diff --git a/layout/style/nsComputedDOMStyle.h b/layout/style/nsComputedDOMStyle.h
index 223b29a14..27e2086e9 100644
--- a/layout/style/nsComputedDOMStyle.h
+++ b/layout/style/nsComputedDOMStyle.h
@@ -421,6 +421,7 @@ private:
already_AddRefed<CSSValue> DoGetTextEmphasisPosition();
already_AddRefed<CSSValue> DoGetTextEmphasisStyle();
already_AddRefed<CSSValue> DoGetTextIndent();
+ already_AddRefed<CSSValue> DoGetTextJustify();
already_AddRefed<CSSValue> DoGetTextOrientation();
already_AddRefed<CSSValue> DoGetTextOverflow();
already_AddRefed<CSSValue> DoGetTextTransform();
diff --git a/layout/style/nsComputedDOMStylePropertyList.h b/layout/style/nsComputedDOMStylePropertyList.h
index 7c0457e34..1983208ac 100644
--- a/layout/style/nsComputedDOMStylePropertyList.h
+++ b/layout/style/nsComputedDOMStylePropertyList.h
@@ -239,6 +239,7 @@ COMPUTED_STYLE_PROP(text_emphasis_color, TextEmphasisColor)
COMPUTED_STYLE_PROP(text_emphasis_position, TextEmphasisPosition)
COMPUTED_STYLE_PROP(text_emphasis_style, TextEmphasisStyle)
COMPUTED_STYLE_PROP(text_indent, TextIndent)
+COMPUTED_STYLE_PROP(text_justify, TextJustify)
COMPUTED_STYLE_PROP(text_orientation, TextOrientation)
COMPUTED_STYLE_PROP(text_overflow, TextOverflow)
COMPUTED_STYLE_PROP(text_shadow, TextShadow)
diff --git a/layout/style/nsRuleNode.cpp b/layout/style/nsRuleNode.cpp
index fa29fe0f1..9b9fc3948 100644
--- a/layout/style/nsRuleNode.cpp
+++ b/layout/style/nsRuleNode.cpp
@@ -1414,6 +1414,7 @@ struct SetEnumValueHelper
DEFINE_ENUM_CLASS_SETTER(StyleFillRule, Nonzero, Evenodd)
DEFINE_ENUM_CLASS_SETTER(StyleFloat, None, InlineEnd)
DEFINE_ENUM_CLASS_SETTER(StyleFloatEdge, ContentBox, MarginBox)
+ DEFINE_ENUM_CLASS_SETTER(StyleTextJustify, None, InterCharacter)
DEFINE_ENUM_CLASS_SETTER(StyleUserFocus, None, SelectMenu)
DEFINE_ENUM_CLASS_SETTER(StyleUserSelect, None, MozText)
DEFINE_ENUM_CLASS_SETTER(StyleUserInput, None, Auto)
@@ -4783,6 +4784,12 @@ nsRuleNode::ComputeTextData(void* aStartStruct,
SETCOORD_UNSET_INHERIT,
aContext, mPresContext, conditions);
+ // text-justify: enum, inherit, initial
+ SetValue(*aRuleData->ValueForTextJustify(), text->mTextJustify, conditions,
+ SETVAL_ENUMERATED | SETVAL_UNSET_INHERIT,
+ parentText->mTextJustify,
+ StyleTextJustify::Auto);
+
// text-transform: enum, inherit, initial
SetValue(*aRuleData->ValueForTextTransform(), text->mTextTransform, conditions,
SETVAL_ENUMERATED | SETVAL_UNSET_INHERIT,
diff --git a/layout/style/nsStyleConsts.h b/layout/style/nsStyleConsts.h
index ee78dcb64..be588113e 100644
--- a/layout/style/nsStyleConsts.h
+++ b/layout/style/nsStyleConsts.h
@@ -185,6 +185,14 @@ enum class StyleShapeSourceType : uint8_t {
Box,
};
+// text-justify
+enum class StyleTextJustify : uint8_t {
+ None,
+ Auto,
+ InterWord,
+ InterCharacter,
+};
+
// user-focus
enum class StyleUserFocus : uint8_t {
None,
diff --git a/layout/style/nsStyleStruct.cpp b/layout/style/nsStyleStruct.cpp
index 553239e0e..52491a288 100644
--- a/layout/style/nsStyleStruct.cpp
+++ b/layout/style/nsStyleStruct.cpp
@@ -3788,6 +3788,7 @@ nsStyleText::nsStyleText(StyleStructContext aContext)
, mTextAlignLast(NS_STYLE_TEXT_ALIGN_AUTO)
, mTextAlignTrue(false)
, mTextAlignLastTrue(false)
+ , mTextJustify(StyleTextJustify::Auto)
, mTextTransform(NS_STYLE_TEXT_TRANSFORM_NONE)
, mWhiteSpace(NS_STYLE_WHITESPACE_NORMAL)
, mWordBreak(NS_STYLE_WORDBREAK_NORMAL)
@@ -3824,6 +3825,7 @@ nsStyleText::nsStyleText(const nsStyleText& aSource)
, mTextAlignLast(aSource.mTextAlignLast)
, mTextAlignTrue(false)
, mTextAlignLastTrue(false)
+ , mTextJustify(aSource.mTextJustify)
, mTextTransform(aSource.mTextTransform)
, mWhiteSpace(aSource.mWhiteSpace)
, mWordBreak(aSource.mWordBreak)
@@ -3885,6 +3887,7 @@ nsStyleText::CalcDifference(const nsStyleText& aNewData) const
(mTextSizeAdjust != aNewData.mTextSizeAdjust) ||
(mLetterSpacing != aNewData.mLetterSpacing) ||
(mLineHeight != aNewData.mLineHeight) ||
+ (mTextJustify != aNewData.mTextJustify) ||
(mTextIndent != aNewData.mTextIndent) ||
(mWordSpacing != aNewData.mWordSpacing) ||
(mTabSize != aNewData.mTabSize)) {
diff --git a/layout/style/nsStyleStruct.h b/layout/style/nsStyleStruct.h
index 05a6be91e..1cadea840 100644
--- a/layout/style/nsStyleStruct.h
+++ b/layout/style/nsStyleStruct.h
@@ -2071,6 +2071,7 @@ struct MOZ_NEEDS_MEMMOVABLE_MEMBERS nsStyleText
uint8_t mTextAlignLast; // [inherited] see nsStyleConsts.h
bool mTextAlignTrue : 1; // [inherited] see nsStyleConsts.h
bool mTextAlignLastTrue : 1; // [inherited] see nsStyleConsts.h
+ mozilla::StyleTextJustify mTextJustify; // [inherited]
uint8_t mTextTransform; // [inherited] see nsStyleConsts.h
uint8_t mWhiteSpace; // [inherited] see nsStyleConsts.h
uint8_t mWordBreak; // [inherited] see nsStyleConsts.h
diff --git a/layout/style/nsTransitionManager.cpp b/layout/style/nsTransitionManager.cpp
index 4a1a5b7ad..118702e8f 100644
--- a/layout/style/nsTransitionManager.cpp
+++ b/layout/style/nsTransitionManager.cpp
@@ -46,8 +46,6 @@ using mozilla::dom::KeyframeEffectReadOnly;
using namespace mozilla;
using namespace mozilla::css;
-typedef mozilla::ComputedTiming::AnimationPhase AnimationPhase;
-
namespace {
struct TransitionEventParams {
EventMessage mMessage;
@@ -180,10 +178,9 @@ CSSTransition::UpdateTiming(SeekFlag aSeekFlag, SyncNotifyFlag aSyncNotifyFlag)
}
void
-CSSTransition::QueueEvents()
+CSSTransition::QueueEvents(StickyTimeDuration aActiveTime)
{
- if (!mEffect ||
- !mOwningElement.IsSet()) {
+ if (!mOwningElement.IsSet()) {
return;
}
@@ -197,69 +194,123 @@ CSSTransition::QueueEvents()
return;
}
- ComputedTiming computedTiming = mEffect->GetComputedTiming();
- const StickyTimeDuration zeroDuration;
- StickyTimeDuration intervalStartTime =
- std::max(std::min(StickyTimeDuration(-mEffect->SpecifiedTiming().mDelay),
- computedTiming.mActiveDuration), zeroDuration);
- StickyTimeDuration intervalEndTime =
- std::max(std::min((EffectEnd() - mEffect->SpecifiedTiming().mDelay),
- computedTiming.mActiveDuration), zeroDuration);
+ const StickyTimeDuration zeroDuration = StickyTimeDuration();
+
+ TransitionPhase currentPhase;
+ StickyTimeDuration intervalStartTime;
+ StickyTimeDuration intervalEndTime;
+
+ if (!mEffect) {
+ currentPhase = GetAnimationPhaseWithoutEffect<TransitionPhase>(*this);
+ intervalStartTime = zeroDuration;
+ intervalEndTime = zeroDuration;
+ } else {
+ ComputedTiming computedTiming = mEffect->GetComputedTiming();
+
+ currentPhase = static_cast<TransitionPhase>(computedTiming.mPhase);
+ intervalStartTime =
+ std::max(std::min(StickyTimeDuration(-mEffect->SpecifiedTiming().mDelay),
+ computedTiming.mActiveDuration), zeroDuration);
+ intervalEndTime =
+ std::max(std::min((EffectEnd() - mEffect->SpecifiedTiming().mDelay),
+ computedTiming.mActiveDuration), zeroDuration);
+ }
// TimeStamps to use for ordering the events when they are dispatched. We
// use a TimeStamp so we can compare events produced by different elements,
// perhaps even with different timelines.
// The zero timestamp is for transitionrun events where we ignore the delay
// for the purpose of ordering events.
- TimeStamp startTimeStamp = ElapsedTimeToTimeStamp(intervalStartTime);
- TimeStamp endTimeStamp = ElapsedTimeToTimeStamp(intervalEndTime);
+ TimeStamp zeroTimeStamp = AnimationTimeToTimeStamp(zeroDuration);
+ TimeStamp startTimeStamp = ElapsedTimeToTimeStamp(intervalStartTime);
+ TimeStamp endTimeStamp = ElapsedTimeToTimeStamp(intervalEndTime);
- TransitionPhase currentPhase;
if (mPendingState != PendingState::NotPending &&
(mPreviousTransitionPhase == TransitionPhase::Idle ||
mPreviousTransitionPhase == TransitionPhase::Pending))
{
currentPhase = TransitionPhase::Pending;
- } else {
- currentPhase = static_cast<TransitionPhase>(computedTiming.mPhase);
}
AutoTArray<TransitionEventParams, 3> events;
+
+ // Handle cancel events firts
+ if (mPreviousTransitionPhase != TransitionPhase::Idle &&
+ currentPhase == TransitionPhase::Idle) {
+ TimeStamp activeTimeStamp = ElapsedTimeToTimeStamp(aActiveTime);
+ events.AppendElement(TransitionEventParams{ eTransitionCancel,
+ aActiveTime,
+ activeTimeStamp });
+ }
+
+ // All other events
switch (mPreviousTransitionPhase) {
case TransitionPhase::Idle:
- if (currentPhase == TransitionPhase::After) {
+ if (currentPhase == TransitionPhase::Pending ||
+ currentPhase == TransitionPhase::Before) {
+ events.AppendElement(TransitionEventParams{ eTransitionRun,
+ intervalStartTime,
+ zeroTimeStamp });
+ } else if (currentPhase == TransitionPhase::Active) {
+ events.AppendElement(TransitionEventParams{ eTransitionRun,
+ intervalStartTime,
+ zeroTimeStamp });
+ events.AppendElement(TransitionEventParams{ eTransitionStart,
+ intervalStartTime,
+ startTimeStamp });
+ } else if (currentPhase == TransitionPhase::After) {
+ events.AppendElement(TransitionEventParams{ eTransitionRun,
+ intervalStartTime,
+ zeroTimeStamp });
+ events.AppendElement(TransitionEventParams{ eTransitionStart,
+ intervalStartTime,
+ startTimeStamp });
events.AppendElement(TransitionEventParams{ eTransitionEnd,
- intervalEndTime,
- endTimeStamp });
+ intervalEndTime,
+ endTimeStamp });
}
break;
case TransitionPhase::Pending:
case TransitionPhase::Before:
- if (currentPhase == TransitionPhase::After) {
+ if (currentPhase == TransitionPhase::Active) {
+ events.AppendElement(TransitionEventParams{ eTransitionStart,
+ intervalStartTime,
+ startTimeStamp });
+ } else if (currentPhase == TransitionPhase::After) {
+ events.AppendElement(TransitionEventParams{ eTransitionStart,
+ intervalStartTime,
+ startTimeStamp });
events.AppendElement(TransitionEventParams{ eTransitionEnd,
- intervalEndTime,
- endTimeStamp });
+ intervalEndTime,
+ endTimeStamp });
}
break;
case TransitionPhase::Active:
if (currentPhase == TransitionPhase::After) {
events.AppendElement(TransitionEventParams{ eTransitionEnd,
- intervalEndTime,
- endTimeStamp });
+ intervalEndTime,
+ endTimeStamp });
} else if (currentPhase == TransitionPhase::Before) {
events.AppendElement(TransitionEventParams{ eTransitionEnd,
- intervalStartTime,
- startTimeStamp });
+ intervalStartTime,
+ startTimeStamp });
}
break;
case TransitionPhase::After:
- if (currentPhase == TransitionPhase::Before) {
+ if (currentPhase == TransitionPhase::Active) {
+ events.AppendElement(TransitionEventParams{ eTransitionStart,
+ intervalEndTime,
+ startTimeStamp });
+ } else if (currentPhase == TransitionPhase::Before) {
+ events.AppendElement(TransitionEventParams{ eTransitionStart,
+ intervalEndTime,
+ startTimeStamp });
events.AppendElement(TransitionEventParams{ eTransitionEnd,
- intervalStartTime,
- endTimeStamp });
+ intervalStartTime,
+ endTimeStamp });
}
break;
}
diff --git a/layout/style/nsTransitionManager.h b/layout/style/nsTransitionManager.h
index 56ec61572..1c48cc8cd 100644
--- a/layout/style/nsTransitionManager.h
+++ b/layout/style/nsTransitionManager.h
@@ -214,6 +214,10 @@ public:
const TimeDuration& aStartTime,
double aPlaybackRate);
+ void MaybeQueueCancelEvent(StickyTimeDuration aActiveTime) override {
+ QueueEvents(aActiveTime);
+ }
+
protected:
virtual ~CSSTransition()
{
@@ -225,7 +229,10 @@ protected:
void UpdateTiming(SeekFlag aSeekFlag,
SyncNotifyFlag aSyncNotifyFlag) override;
- void QueueEvents();
+ void QueueEvents(StickyTimeDuration activeTime = StickyTimeDuration());
+
+
+ enum class TransitionPhase;
// The (pseudo-)element whose computed transition-property refers to this
// transition (if any).
@@ -250,7 +257,7 @@ protected:
// to be queued on this tick.
// See: https://drafts.csswg.org/css-transitions-2/#transition-phase
enum class TransitionPhase {
- Idle = static_cast<int>(ComputedTiming::AnimationPhase::Null),
+ Idle = static_cast<int>(ComputedTiming::AnimationPhase::Idle),
Before = static_cast<int>(ComputedTiming::AnimationPhase::Before),
Active = static_cast<int>(ComputedTiming::AnimationPhase::Active),
After = static_cast<int>(ComputedTiming::AnimationPhase::After),
diff --git a/layout/style/test/property_database.js b/layout/style/test/property_database.js
index 62d413d98..272931c15 100644
--- a/layout/style/test/property_database.js
+++ b/layout/style/test/property_database.js
@@ -5694,6 +5694,17 @@ if (IsCSSPropertyPrefEnabled("layout.css.text-combine-upright.enabled")) {
}
}
+if (IsCSSPropertyPrefEnabled("layout.css.text-justify.enabled")) {
+ gCSSProperties["text-justify"] = {
+ domProp: "textJustify",
+ inherited: true,
+ type: CSS_TYPE_LONGHAND,
+ initial_values: [ "auto" ],
+ other_values: [ "none", "inter-word", "inter-character", "distribute" ],
+ invalid_values: []
+ };
+}
+
if (IsCSSPropertyPrefEnabled("svg.paint-order.enabled")) {
gCSSProperties["paint-order"] = {
domProp: "paintOrder",
diff --git a/layout/style/test/test_animations.html b/layout/style/test/test_animations.html
index eaccba122..4019af77f 100644
--- a/layout/style/test/test_animations.html
+++ b/layout/style/test/test_animations.html
@@ -1195,9 +1195,6 @@ is_approx(px_to_num(cs.marginRight), 100 * gTF.ease_in(0.4), 0.01,
"large negative delay test at 0ms");
check_events([{ type: 'animationstart', target: div,
animationName: 'anim2', elapsedTime: 3.6,
- pseudoElement: "" },
- { type: 'animationiteration', target: div,
- animationName: 'anim2', elapsedTime: 3.6,
pseudoElement: "" }],
"right after start in large negative delay test");
advance_clock(380);
diff --git a/layout/style/test/test_animations_event_handler_attribute.html b/layout/style/test/test_animations_event_handler_attribute.html
index e5def2b34..036a77779 100644
--- a/layout/style/test/test_animations_event_handler_attribute.html
+++ b/layout/style/test/test_animations_event_handler_attribute.html
@@ -88,21 +88,55 @@ checkReceivedEvents("animationend", targets);
targets.forEach(div => { div.remove(); });
-// 2. Test CSS Transition event handlers.
+// 2a. Test CSS Transition event handlers (without transitioncancel)
-var targets = createAndRegisterTargets([ 'ontransitionend' ]);
+var targets = createAndRegisterTargets([ 'ontransitionrun',
+ 'ontransitionstart',
+ 'ontransitionend',
+ 'ontransitioncancel' ]);
targets.forEach(div => {
- div.style.transition = 'margin-left 100ms';
+ div.style.transition = 'margin-left 100ms 200ms';
getComputedStyle(div).marginLeft; // flush
div.style.marginLeft = "200px";
getComputedStyle(div).marginLeft; // flush
});
+advance_clock(0);
+checkReceivedEvents("transitionrun", targets);
+
+advance_clock(200);
+checkReceivedEvents("transitionstart", targets);
+
advance_clock(100);
checkReceivedEvents("transitionend", targets);
targets.forEach(div => { div.remove(); });
+// 2b. Test CSS Transition cancel event handler.
+
+var targets = createAndRegisterTargets([ 'ontransitioncancel' ]);
+targets.forEach(div => {
+ div.style.transition = 'margin-left 100ms 200ms';
+ getComputedStyle(div).marginLeft; // flush
+ div.style.marginLeft = "200px";
+ getComputedStyle(div).marginLeft; // flush
+});
+
+advance_clock(200);
+
+targets.forEach(div => {
+ div.style.display = "none"
+});
+getComputedStyle(targets[0]).display; // flush
+
+advance_clock(0);
+checkReceivedEvents("transitioncancel", targets);
+
+advance_clock(100);
+targets.forEach( div => { is(div.receivedEventType, undefined); });
+
+targets.forEach(div => { div.remove(); });
+
// 3. Test prefixed CSS Animation event handlers.
var targets = createAndRegisterTargets([ 'onwebkitanimationstart',
diff --git a/layout/style/test/test_animations_event_order.html b/layout/style/test/test_animations_event_order.html
index 5af7639cc..7204934d2 100644
--- a/layout/style/test/test_animations_event_order.html
+++ b/layout/style/test/test_animations_event_order.html
@@ -46,7 +46,10 @@ var gDisplay = document.getElementById('display');
[ 'animationstart',
'animationiteration',
'animationend',
- 'transitionend' ]
+ 'transitionrun',
+ 'transitionstart',
+ 'transitionend',
+ 'transitioncancel' ]
.forEach(event =>
gDisplay.addEventListener(event,
event => gEventsReceived.push(event),
@@ -322,9 +325,13 @@ getComputedStyle(divs[0]).marginLeft;
advance_clock(0);
advance_clock(10000);
-checkEventOrder([ divs[0], 'transitionend' ],
+checkEventOrder([ divs[0], 'transitionrun' ],
+ [ divs[0], 'transitionstart' ],
+ [ divs[1], 'transitionrun' ],
+ [ divs[1], 'transitionstart' ],
+ [ divs[0], 'transitionend' ],
[ divs[1], 'transitionend' ],
- 'Simultaneous transitionend on siblings');
+ 'Simultaneous transitionrun/start/end on siblings');
divs.forEach(div => div.remove());
divs = [];
@@ -360,10 +367,16 @@ getComputedStyle(divs[0]).marginLeft;
advance_clock(0);
advance_clock(10000);
-checkEventOrder([ divs[0], 'transitionend' ],
+checkEventOrder([ divs[0], 'transitionrun' ],
+ [ divs[0], 'transitionstart' ],
+ [ divs[2], 'transitionrun' ],
+ [ divs[2], 'transitionstart' ],
+ [ divs[1], 'transitionrun' ],
+ [ divs[1], 'transitionstart' ],
+ [ divs[0], 'transitionend' ],
[ divs[2], 'transitionend' ],
[ divs[1], 'transitionend' ],
- 'Simultaneous transitionend on children');
+ 'Simultaneous transitionrun/start/end on children');
divs.forEach(div => div.remove());
divs = [];
@@ -408,11 +421,19 @@ getComputedStyle(divs[0]).marginLeft;
advance_clock(0);
advance_clock(10000);
-checkEventOrder([ divs[0], 'transitionend' ],
+checkEventOrder([ divs[0], 'transitionrun' ],
+ [ divs[0], 'transitionstart' ],
+ [ divs[0], '::before', 'transitionrun' ],
+ [ divs[0], '::before', 'transitionstart' ],
+ [ divs[0], '::after', 'transitionrun' ],
+ [ divs[0], '::after', 'transitionstart' ],
+ [ divs[1], 'transitionrun' ],
+ [ divs[1], 'transitionstart' ],
+ [ divs[0], 'transitionend' ],
[ divs[0], '::before', 'transitionend' ],
[ divs[0], '::after', 'transitionend' ],
[ divs[1], 'transitionend' ],
- 'Simultaneous transitionend on pseudo-elements');
+ 'Simultaneous transitionrun/start/end on pseudo-elements');
divs.forEach(div => div.remove());
divs = [];
@@ -441,9 +462,13 @@ getComputedStyle(divs[0]).marginLeft;
advance_clock(0);
advance_clock(10000);
-checkEventOrder([ divs[1], 'transitionend' ],
+checkEventOrder([ divs[0], 'transitionrun' ],
+ [ divs[0], 'transitionstart' ],
+ [ divs[1], 'transitionrun' ],
+ [ divs[1], 'transitionstart' ],
+ [ divs[1], 'transitionend' ],
[ divs[0], 'transitionend' ],
- 'Sorting of transitionend events by time');
+ 'Sorting of transitionrun/start/end events by time');
divs.forEach(div => div.remove());
divs = [];
@@ -468,9 +493,13 @@ getComputedStyle(divs[0]).marginLeft;
advance_clock(0);
advance_clock(10 * 1000);
-checkEventOrder([ divs[1], 'transitionend' ],
+checkEventOrder([ divs[0], 'transitionrun' ],
+ [ divs[1], 'transitionrun' ],
+ [ divs[1], 'transitionstart' ],
+ [ divs[0], 'transitionstart' ],
+ [ divs[1], 'transitionend' ],
[ divs[0], 'transitionend' ],
- 'Sorting of transitionend events by time' +
+ 'Sorting of transitionrun/start/end events by time' +
'(including delay)');
divs.forEach(div => div.remove());
@@ -492,9 +521,14 @@ getComputedStyle(div).marginLeft;
advance_clock(0);
advance_clock(10000);
-checkEventOrder([ 'margin-left', 'transitionend' ],
+checkEventOrder([ 'margin-left', 'transitionrun' ],
+ [ 'margin-left', 'transitionstart' ],
+ [ 'opacity', 'transitionrun' ],
+ [ 'opacity', 'transitionstart' ],
+ [ 'margin-left', 'transitionend' ],
[ 'opacity', 'transitionend' ],
- 'Sorting of transitionend events by transition-property')
+ 'Sorting of transitionrun/start/end events by ' +
+ 'transition-property')
div.remove();
div = undefined;
@@ -519,7 +553,11 @@ getComputedStyle(divs[0]).marginLeft;
advance_clock(0);
advance_clock(10000);
-checkEventOrder([ divs[0], 'transitionend' ],
+checkEventOrder([ divs[0], 'transitionrun' ],
+ [ divs[0], 'transitionstart' ],
+ [ divs[1], 'transitionrun' ],
+ [ divs[1], 'transitionstart' ],
+ [ divs[0], 'transitionend' ],
[ divs[1], 'transitionend' ],
'Transition events are sorted by document position first, ' +
'before transition-property');
@@ -543,7 +581,11 @@ getComputedStyle(div).marginLeft;
advance_clock(0);
advance_clock(10000);
-checkEventOrder([ 'opacity', 'transitionend' ],
+checkEventOrder([ 'margin-left', 'transitionrun' ],
+ [ 'margin-left', 'transitionstart' ],
+ [ 'opacity', 'transitionrun' ],
+ [ 'opacity', 'transitionstart' ],
+ [ 'opacity', 'transitionend' ],
[ 'margin-left', 'transitionend' ],
'Transition events are sorted by time first, before ' +
'transition-property');
@@ -571,9 +613,50 @@ getComputedStyle(divs[0]).marginLeft;
advance_clock(0);
advance_clock(15 * 1000);
-checkEventOrder([ divs[1], 'transitionend' ],
+checkEventOrder([ divs[0], 'transitionrun' ],
+ [ divs[1], 'transitionrun' ],
+ [ divs[1], 'transitionstart' ],
+ [ divs[0], 'transitionstart' ],
+ [ divs[1], 'transitionend' ],
[ divs[0], 'transitionend' ],
- 'Simultaneous transitionend on siblings');
+ 'Simultaneous transitionrun/start/end on siblings');
+
+divs.forEach(div => div.remove());
+divs = [];
+
+// 4j. Test sorting transitions with cancel
+// The order of transitioncancel is based on StyleManager.
+// So this test looks like wrong result at a glance. However
+// the gecko will cancel div1's transition before div2 in this case.
+
+divs = [ document.createElement('div'),
+ document.createElement('div') ];
+divs.forEach((div, i) => {
+ gDisplay.appendChild(div);
+ div.style.marginLeft = '0px';
+ div.setAttribute('id', 'div' + i);
+});
+
+divs[0].style.transition = 'margin-left 10s 5s';
+divs[1].style.transition = 'margin-left 10s';
+
+getComputedStyle(divs[0]).marginLeft;
+divs.forEach(div => div.style.marginLeft = '100px');
+getComputedStyle(divs[0]).marginLeft;
+
+advance_clock(0);
+advance_clock(5 * 1000);
+divs.forEach(div => div.style.display = 'none' );
+getComputedStyle(divs[0]).display;
+advance_clock(10 * 1000);
+
+checkEventOrder([ divs[0], 'transitionrun' ],
+ [ divs[1], 'transitionrun' ],
+ [ divs[1], 'transitionstart' ],
+ [ divs[0], 'transitionstart' ],
+ [ divs[1], 'transitioncancel' ],
+ [ divs[0], 'transitioncancel' ],
+ 'Simultaneous transitionrun/start/cancel on siblings');
divs.forEach(div => div.remove());
divs = [];
diff --git a/layout/style/test/test_animations_omta.html b/layout/style/test/test_animations_omta.html
index 4b276c896..0b2a61ecc 100644
--- a/layout/style/test/test_animations_omta.html
+++ b/layout/style/test/test_animations_omta.html
@@ -1408,9 +1408,6 @@ addAsyncAnimTest(function *() {
"large negative delay test at 0ms");
check_events([{ type: 'animationstart', target: gDiv,
animationName: 'anim2', elapsedTime: 3.6,
- pseudoElement: "" },
- { type: 'animationiteration', target: gDiv,
- animationName: 'anim2', elapsedTime: 3.6,
pseudoElement: "" }],
"right after start in large negative delay test");
advance_clock(380);
diff --git a/layout/tools/reftest/bootstrap.js b/layout/tools/reftest/bootstrap.js
index c081335c2..18ca74f69 100644
--- a/layout/tools/reftest/bootstrap.js
+++ b/layout/tools/reftest/bootstrap.js
@@ -33,11 +33,6 @@ var WindowListener = {
};
function startup(data, reason) {
- // b2g is bootstrapped by b2g_start_script.js
- if (Services.appinfo.widgetToolkit == "gonk") {
- return;
- }
-
if (Services.appinfo.OS == "Android") {
Cm.addBootstrappedManifestLocation(data.installPath);
Services.wm.addListener(WindowListener);
@@ -66,10 +61,6 @@ function startup(data, reason) {
}
function shutdown(data, reason) {
- if (Services.appinfo.widgetToolkit == "gonk") {
- return;
- }
-
if (Services.appinfo.OS == "Android") {
Services.wm.removeListener(WindowListener);
Cm.removedBootstrappedManifestLocation(data.installPath);
diff --git a/layout/tools/reftest/reftest.jsm b/layout/tools/reftest/reftest.jsm
index 69d804453..bd9976b0f 100644
--- a/layout/tools/reftest/reftest.jsm
+++ b/layout/tools/reftest/reftest.jsm
@@ -324,11 +324,7 @@ this.OnRefTestLoad = function OnRefTestLoad(win)
if (Services.appinfo.OS == "Android") {
let doc;
- if (Services.appinfo.widgetToolkit == "gonk") {
- doc = gContainingWindow.document.getElementsByTagName("html")[0];
- } else {
- doc = gContainingWindow.document.getElementById('main-window');
- }
+ doc = gContainingWindow.document.getElementById('main-window');
while (doc.hasChildNodes()) {
doc.removeChild(doc.firstChild);
}
@@ -684,7 +680,7 @@ function BuildConditionSandbox(aURL) {
gWindowUtils.layerManagerRemote == true;
// Shortcuts for widget toolkits.
- sandbox.B2G = xr.widgetToolkit == "gonk";
+ sandbox.B2G = false;
sandbox.Android = xr.OS == "Android" && !sandbox.B2G;
sandbox.cocoaWidget = xr.widgetToolkit == "cocoa";
sandbox.gtkWidget = xr.widgetToolkit == "gtk2"
diff --git a/layout/tools/reftest/runreftest.py b/layout/tools/reftest/runreftest.py
index e1c20ccd9..7845903bd 100644
--- a/layout/tools/reftest/runreftest.py
+++ b/layout/tools/reftest/runreftest.py
@@ -598,11 +598,8 @@ class RefTest(object):
timeout = None
signal.signal(signal.SIGINT, lambda sigid, frame: None)
- if mozinfo.info.get('appname') == 'b2g' and mozinfo.info.get('toolkit') != 'gonk':
- runner_cls = mozrunner.Runner
- else:
- runner_cls = mozrunner.runners.get(mozinfo.info.get('appname', 'firefox'),
- mozrunner.Runner)
+ runner_cls = mozrunner.runners.get(mozinfo.info.get('appname', 'firefox'),
+ mozrunner.Runner)
runner = runner_cls(profile=profile,
binary=binary,
process_class=mozprocess.ProcessHandlerMixin,
diff --git a/media/ffvpx/COPYING.GPLv2 b/media/ffvpx/COPYING.GPLv2
deleted file mode 100644
index d159169d1..000000000
--- a/media/ffvpx/COPYING.GPLv2
+++ /dev/null
@@ -1,339 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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 2 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, write to the Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- <signature of Ty Coon>, 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License.
diff --git a/media/ffvpx/COPYING.GPLv3 b/media/ffvpx/COPYING.GPLv3
deleted file mode 100644
index 94a9ed024..000000000
--- a/media/ffvpx/COPYING.GPLv3
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- 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/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- <program> Copyright (C) <year> <name of author>
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/media/ffvpx/CREDITS b/media/ffvpx/CREDITS
deleted file mode 100644
index e29f0b853..000000000
--- a/media/ffvpx/CREDITS
+++ /dev/null
@@ -1,6 +0,0 @@
-See the Git history of the project (git://source.ffmpeg.org/ffmpeg) to
-get the names of people who have contributed to FFmpeg.
-
-To check the log, you can type the command "git log" in the FFmpeg
-source directory, or browse the online repository at
-http://source.ffmpeg.org.
diff --git a/media/ffvpx/Changelog b/media/ffvpx/Changelog
deleted file mode 100644
index 2e1cd36f5..000000000
--- a/media/ffvpx/Changelog
+++ /dev/null
@@ -1,1476 +0,0 @@
-Entries are sorted chronologically from oldest to youngest within each release,
-releases are sorted from youngest to oldest.
-
-version 3.0:
-- Common Encryption (CENC) MP4 encoding and decoding support
-- DXV decoding
-- extrastereo filter
-- ocr filter
-- alimiter filter
-- stereowiden filter
-- stereotools filter
-- rubberband filter
-- tremolo filter
-- agate filter
-- chromakey filter
-- maskedmerge filter
-- Screenpresso SPV1 decoding
-- chromaprint fingerprinting muxer
-- ffplay dynamic volume control
-- displace filter
-- selectivecolor filter
-- extensive native AAC encoder improvements and removal of experimental flag
-- ADPCM PSX decoder
-- 3dostr, dcstr, fsb, genh, vag, xvag, ads, msf, svag & vpk demuxer
-- zscale filter
-- wve demuxer
-- zero-copy Intel QSV transcoding in ffmpeg
-- shuffleframes filter
-- SDX2 DPCM decoder
-- vibrato filter
-- innoHeim/Rsupport Screen Capture Codec decoder
-- ADPCM AICA decoder
-- Interplay ACM demuxer and audio decoder
-- XMA1 & XMA2 decoder
-- realtime filter
-- anoisesrc audio filter source
-- IVR demuxer
-- compensationdelay filter
-- acompressor filter
-- support encoding 16-bit RLE SGI images
-- apulsator filter
-- sidechaingate audio filter
-- mipsdspr1 option has been renamed to mipsdsp
-- aemphasis filter
-- mips32r5 option has been removed
-- mips64r6 option has been removed
-- DXVA2-accelerated VP9 decoding
-- SOFAlizer: virtual binaural acoustics filter
-- VAAPI VP9 hwaccel
-- audio high-order multiband parametric equalizer
-- automatic bitstream filtering
-- showspectrumpic filter
-- libstagefright support removed
-- spectrumsynth filter
-- ahistogram filter
-- only seek with the right mouse button in ffplay
-- toggle full screen when double-clicking with the left mouse button in ffplay
-- afftfilt filter
-- convolution filter
-- libquvi support removed
-- support for dvaudio in wav and avi
-- libaacplus and libvo-aacenc support removed
-- Cineform HD decoder
-- new DCA decoder with full support for DTS-HD extensions
-- significant performance improvements in Windows Television (WTV) demuxer
-- nnedi deinterlacer
-- streamselect video and astreamselect audio filter
-- swaprect filter
-- metadata video and ametadata audio filter
-- SMPTE VC-2 HQ profile support for the Dirac decoder
-- SMPTE VC-2 native encoder supporting the HQ profile
-
-
-version 2.8:
-- colorkey video filter
-- BFSTM/BCSTM demuxer
-- little-endian ADPCM_THP decoder
-- Hap decoder and encoder
-- DirectDraw Surface image/texture decoder
-- ssim filter
-- optional new ASF demuxer
-- showvolume filter
-- Many improvements to the JPEG 2000 decoder
-- Go2Meeting decoding support
-- adrawgraph audio and drawgraph video filter
-- removegrain video filter
-- Intel QSV-accelerated MPEG-2 video and HEVC encoding
-- Intel QSV-accelerated MPEG-2 video and HEVC decoding
-- Intel QSV-accelerated VC-1 video decoding
-- libkvazaar HEVC encoder
-- erosion, dilation, deflate and inflate video filters
-- Dynamic Audio Normalizer as dynaudnorm filter
-- Reverse video and areverse audio filter
-- Random filter
-- deband filter
-- AAC fixed-point decoding
-- sidechaincompress audio filter
-- bitstream filter for converting HEVC from MP4 to Annex B
-- acrossfade audio filter
-- allyuv and allrgb video sources
-- atadenoise video filter
-- OS X VideoToolbox support
-- aphasemeter filter
-- showfreqs filter
-- vectorscope filter
-- waveform filter
-- hstack and vstack filter
-- Support DNx100 (1440x1080@8)
-- VAAPI hevc hwaccel
-- VDPAU hevc hwaccel
-- framerate filter
-- Switched default encoders for webm to VP9 and Opus
-- Removed experimental flag from the JPEG 2000 encoder
-
-
-version 2.7:
-- FFT video filter
-- TDSC decoder
-- DTS lossless extension (XLL) decoding (not lossless, disabled by default)
-- showwavespic filter
-- DTS decoding through libdcadec
-- Drop support for nvenc API before 5.0
-- nvenc HEVC encoder
-- Detelecine filter
-- Intel QSV-accelerated H.264 encoding
-- MMAL-accelerated H.264 decoding
-- basic APNG encoder and muxer with default extension "apng"
-- unpack DivX-style packed B-frames in MPEG-4 bitstream filter
-- WebM Live Chunk Muxer
-- nvenc level and tier options
-- chorus filter
-- Canopus HQ/HQA decoder
-- Automatically rotate videos based on metadata in ffmpeg
-- improved Quickdraw compatibility
-- VP9 high bit-depth and extended colorspaces decoding support
-- WebPAnimEncoder API when available for encoding and muxing WebP
-- Direct3D11-accelerated decoding
-- Support Secure Transport
-- Multipart JPEG demuxer
-
-
-version 2.6:
-- nvenc encoder
-- 10bit spp filter
-- colorlevels filter
-- RIFX format for *.wav files
-- RTP/mpegts muxer
-- non continuous cache protocol support
-- tblend filter
-- cropdetect support for non 8bpp, absolute (if limit >= 1) and relative (if limit < 1.0) threshold
-- Camellia symmetric block cipher
-- OpenH264 encoder wrapper
-- VOC seeking support
-- Closed caption Decoder
-- fspp, uspp, pp7 MPlayer postprocessing filters ported to native filters
-- showpalette filter
-- Twofish symmetric block cipher
-- Support DNx100 (960x720@8)
-- eq2 filter ported from libmpcodecs as eq filter
-- removed libmpcodecs
-- Changed default DNxHD colour range in QuickTime .mov derivatives to mpeg range
-- ported softpulldown filter from libmpcodecs as repeatfields filter
-- dcshift filter
-- RTP depacketizer for loss tolerant payload format for MP3 audio (RFC 5219)
-- RTP depacketizer for AC3 payload format (RFC 4184)
-- palettegen and paletteuse filters
-- VP9 RTP payload format (draft 0) experimental depacketizer
-- RTP depacketizer for DV (RFC 6469)
-- DXVA2-accelerated HEVC decoding
-- AAC ELD 480 decoding
-- Intel QSV-accelerated H.264 decoding
-- DSS SP decoder and DSS demuxer
-- Fix stsd atom corruption in DNxHD QuickTimes
-- Canopus HQX decoder
-- RTP depacketization of T.140 text (RFC 4103)
-- Port MIPS optimizations to 64-bit
-
-
-version 2.5:
-- HEVC/H.265 RTP payload format (draft v6) packetizer
-- SUP/PGS subtitle demuxer
-- ffprobe -show_pixel_formats option
-- CAST128 symmetric block cipher, ECB mode
-- STL subtitle demuxer and decoder
-- libutvideo YUV 4:2:2 10bit support
-- XCB-based screen-grabber
-- UDP-Lite support (RFC 3828)
-- xBR scaling filter
-- AVFoundation screen capturing support
-- ffserver supports codec private options
-- creating DASH compatible fragmented MP4, MPEG-DASH segmenting muxer
-- WebP muxer with animated WebP support
-- zygoaudio decoding support
-- APNG demuxer
-- postproc visualization support
-
-
-version 2.4:
-- Icecast protocol
-- ported lenscorrection filter from frei0r filter
-- large optimizations in dctdnoiz to make it usable
-- ICY metadata are now requested by default with the HTTP protocol
-- support for using metadata in stream specifiers in fftools
-- LZMA compression support in TIFF decoder
-- H.261 RTP payload format (RFC 4587) depacketizer and experimental packetizer
-- HEVC/H.265 RTP payload format (draft v6) depacketizer
-- added codecview filter to visualize information exported by some codecs
-- Matroska 3D support thorugh side data
-- HTML generation using texi2html is deprecated in favor of makeinfo/texi2any
-- silenceremove filter
-
-
-version 2.3:
-- AC3 fixed-point decoding
-- shuffleplanes filter
-- subfile protocol
-- Phantom Cine demuxer
-- replaygain data export
-- VP7 video decoder
-- Alias PIX image encoder and decoder
-- Improvements to the BRender PIX image decoder
-- Improvements to the XBM decoder
-- QTKit input device
-- improvements to OpenEXR image decoder
-- support decoding 16-bit RLE SGI images
-- GDI screen grabbing for Windows
-- alternative rendition support for HTTP Live Streaming
-- AVFoundation input device
-- Direct Stream Digital (DSD) decoder
-- Magic Lantern Video (MLV) demuxer
-- On2 AVC (Audio for Video) decoder
-- support for decoding through DXVA2 in ffmpeg
-- libbs2b-based stereo-to-binaural audio filter
-- libx264 reference frames count limiting depending on level
-- native Opus decoder
-- display matrix export and rotation API
-- WebVTT encoder
-- showcqt multimedia filter
-- zoompan filter
-- signalstats filter
-- hqx filter (hq2x, hq3x, hq4x)
-- flanger filter
-- Image format auto-detection
-- LRC demuxer and muxer
-- Samba protocol (via libsmbclient)
-- WebM DASH Manifest muxer
-- libfribidi support in drawtext
-
-
-version 2.2:
-
-- HNM version 4 demuxer and video decoder
-- Live HDS muxer
-- setsar/setdar filters now support variables in ratio expressions
-- elbg filter
-- string validation in ffprobe
-- support for decoding through VDPAU in ffmpeg (the -hwaccel option)
-- complete Voxware MetaSound decoder
-- remove mp3_header_compress bitstream filter
-- Windows resource files for shared libraries
-- aeval filter
-- stereoscopic 3d metadata handling
-- WebP encoding via libwebp
-- ATRAC3+ decoder
-- VP8 in Ogg demuxing
-- side & metadata support in NUT
-- framepack filter
-- XYZ12 rawvideo support in NUT
-- Exif metadata support in WebP decoder
-- OpenGL device
-- Use metadata_header_padding to control padding in ID3 tags (currently used in
- MP3, AIFF, and OMA files), FLAC header, and the AVI "junk" block.
-- Mirillis FIC video decoder
-- Support DNx444
-- libx265 encoder
-- dejudder filter
-- Autodetect VDA like all other hardware accelerations
-- aliases and defaults for Ogg subtypes (opus, spx)
-
-
-version 2.1:
-
-- aecho filter
-- perspective filter ported from libmpcodecs
-- ffprobe -show_programs option
-- compand filter
-- RTMP seek support
-- when transcoding with ffmpeg (i.e. not streamcopying), -ss is now accurate
- even when used as an input option. Previous behavior can be restored with
- the -noaccurate_seek option.
-- ffmpeg -t option can now be used for inputs, to limit the duration of
- data read from an input file
-- incomplete Voxware MetaSound decoder
-- read EXIF metadata from JPEG
-- DVB teletext decoder
-- phase filter ported from libmpcodecs
-- w3fdif filter
-- Opus support in Matroska
-- FFV1 version 1.3 is stable and no longer experimental
-- FFV1: YUVA(444,422,420) 9, 10 and 16 bit support
-- changed DTS stream id in lavf mpeg ps muxer from 0x8a to 0x88, to be
- more consistent with other muxers.
-- adelay filter
-- pullup filter ported from libmpcodecs
-- ffprobe -read_intervals option
-- Lossless and alpha support for WebP decoder
-- Error Resilient AAC syntax (ER AAC LC) decoding
-- Low Delay AAC (ER AAC LD) decoding
-- mux chapters in ASF files
-- SFTP protocol (via libssh)
-- libx264: add ability to encode in YUVJ422P and YUVJ444P
-- Fraps: use BT.709 colorspace by default for yuv, as reference fraps decoder does
-- make decoding alpha optional for prores, ffv1 and vp6 by setting
- the skip_alpha flag.
-- ladspa wrapper filter
-- native VP9 decoder
-- dpx parser
-- max_error_rate parameter in ffmpeg
-- PulseAudio output device
-- ReplayGain scanner
-- Enhanced Low Delay AAC (ER AAC ELD) decoding (no LD SBR support)
-- Linux framebuffer output device
-- HEVC decoder
-- raw HEVC, HEVC in MOV/MP4, HEVC in Matroska, HEVC in MPEG-TS demuxing
-- mergeplanes filter
-
-
-version 2.0:
-
-- curves filter
-- reference-counting for AVFrame and AVPacket data
-- ffmpeg now fails when input options are used for output file
- or vice versa
-- support for Monkey's Audio versions from 3.93
-- perms and aperms filters
-- audio filtering support in ffplay
-- 10% faster aac encoding on x86 and MIPS
-- sine audio filter source
-- WebP demuxing and decoding support
-- ffmpeg options -filter_script and -filter_complex_script, which allow a
- filtergraph description to be read from a file
-- OpenCL support
-- audio phaser filter
-- separatefields filter
-- libquvi demuxer
-- uniform options syntax across all filters
-- telecine filter
-- interlace filter
-- smptehdbars source
-- inverse telecine filters (fieldmatch and decimate)
-- colorbalance filter
-- colorchannelmixer filter
-- The matroska demuxer can now output proper verbatim ASS packets. It will
- become the default at the next libavformat major bump.
-- decent native animated GIF encoding
-- asetrate filter
-- interleave filter
-- timeline editing with filters
-- vidstabdetect and vidstabtransform filters for video stabilization using
- the vid.stab library
-- astats filter
-- trim and atrim filters
-- ffmpeg -t and -ss (output-only) options are now sample-accurate when
- transcoding audio
-- Matroska muxer can now put the index at the beginning of the file.
-- extractplanes filter
-- avectorscope filter
-- ADPCM DTK decoder
-- ADP demuxer
-- RSD demuxer
-- RedSpark demuxer
-- ADPCM IMA Radical decoder
-- zmq filters
-- DCT denoiser filter (dctdnoiz)
-- Wavelet denoiser filter ported from libmpcodecs as owdenoise (formerly "ow")
-- Apple Intermediate Codec decoder
-- Escape 130 video decoder
-- FTP protocol support
-- V4L2 output device
-- 3D LUT filter (lut3d)
-- SMPTE 302M audio encoder
-- support for slice multithreading in libavfilter
-- Hald CLUT support (generation and filtering)
-- VC-1 interlaced B-frame support
-- support for WavPack muxing (raw and in Matroska)
-- XVideo output device
-- vignette filter
-- True Audio (TTA) encoder
-- Go2Webinar decoder
-- mcdeint filter ported from libmpcodecs
-- sab filter ported from libmpcodecs
-- ffprobe -show_chapters option
-- WavPack encoding through libwavpack
-- rotate filter
-- spp filter ported from libmpcodecs
-- libgme support
-- psnr filter
-
-
-version 1.2:
-
-- VDPAU hardware acceleration through normal hwaccel
-- SRTP support
-- Error diffusion dither in Swscale
-- Chained Ogg support
-- Theora Midstream reconfiguration support
-- EVRC decoder
-- audio fade filter
-- filtering audio with unknown channel layout
-- allpass, bass, bandpass, bandreject, biquad, equalizer, highpass, lowpass
- and treble audio filter
-- improved showspectrum filter, with multichannel support and sox-like colors
-- histogram filter
-- tee muxer
-- il filter ported from libmpcodecs
-- support ID3v2 tags in ASF files
-- encrypted TTA stream decoding support
-- RF64 support in WAV muxer
-- noise filter ported from libmpcodecs
-- Subtitles character encoding conversion
-- blend filter
-- stereo3d filter ported from libmpcodecs
-
-
-version 1.1:
-
-- stream disposition information printing in ffprobe
-- filter for loudness analysis following EBU R128
-- Opus encoder using libopus
-- ffprobe -select_streams option
-- Pinnacle TARGA CineWave YUV16 decoder
-- TAK demuxer, decoder and parser
-- DTS-HD demuxer
-- remove -same_quant, it hasn't worked for years
-- FFM2 support
-- X-Face image encoder and decoder
-- 24-bit FLAC encoding
-- multi-channel ALAC encoding up to 7.1
-- metadata (INFO tag) support in WAV muxer
-- subtitles raw text decoder
-- support for building DLLs using MSVC
-- LVF demuxer
-- ffescape tool
-- metadata (info chunk) support in CAF muxer
-- field filter ported from libmpcodecs
-- AVR demuxer
-- geq filter ported from libmpcodecs
-- remove ffserver daemon mode
-- AST muxer/demuxer
-- new expansion syntax for drawtext
-- BRender PIX image decoder
-- ffprobe -show_entries option
-- ffprobe -sections option
-- ADPCM IMA Dialogic decoder
-- BRSTM demuxer
-- animated GIF decoder and demuxer
-- PVF demuxer
-- subtitles filter
-- IRCAM muxer/demuxer
-- Paris Audio File demuxer
-- Virtual concatenation demuxer
-- VobSub demuxer
-- JSON captions for TED talks decoding support
-- SOX Resampler support in libswresample
-- aselect filter
-- SGI RLE 8-bit / Silicon Graphics RLE 8-bit video decoder
-- Silicon Graphics Motion Video Compressor 1 & 2 decoder
-- Silicon Graphics Movie demuxer
-- apad filter
-- Resolution & pixel format change support with multithreading for H.264
-- documentation split into per-component manuals
-- pp (postproc) filter ported from MPlayer
-- NIST Sphere demuxer
-- MPL2, VPlayer, MPlayer, AQTitle, PJS and SubViewer v1 subtitles demuxers and decoders
-- Sony Wave64 muxer
-- adobe and limelight publisher authentication in RTMP
-- data: URI scheme
-- support building on the Plan 9 operating system
-- kerndeint filter ported from MPlayer
-- histeq filter ported from VirtualDub
-- Megalux Frame demuxer
-- 012v decoder
-- Improved AVC Intra decoding support
-
-
-version 1.0:
-
-- INI and flat output in ffprobe
-- Scene detection in libavfilter
-- Indeo Audio decoder
-- channelsplit audio filter
-- setnsamples audio filter
-- atempo filter
-- ffprobe -show_data option
-- RTMPT protocol support
-- iLBC encoding/decoding via libilbc
-- Microsoft Screen 1 decoder
-- join audio filter
-- audio channel mapping filter
-- Microsoft ATC Screen decoder
-- RTSP listen mode
-- TechSmith Screen Codec 2 decoder
-- AAC encoding via libfdk-aac
-- Microsoft Expression Encoder Screen decoder
-- RTMPS protocol support
-- RTMPTS protocol support
-- RTMPE protocol support
-- RTMPTE protocol support
-- showwaves and showspectrum filter
-- LucasArts SMUSH SANM playback support
-- LucasArts SMUSH VIMA audio decoder (ADPCM)
-- LucasArts SMUSH demuxer
-- SAMI, RealText and SubViewer demuxers and decoders
-- Heart Of Darkness PAF playback support
-- iec61883 device
-- asettb filter
-- new option: -progress
-- 3GPP Timed Text encoder/decoder
-- GeoTIFF decoder support
-- ffmpeg -(no)stdin option
-- Opus decoder using libopus
-- caca output device using libcaca
-- alphaextract and alphamerge filters
-- concat filter
-- flite filter
-- Canopus Lossless Codec decoder
-- bitmap subtitles in filters (experimental and temporary)
-- MP2 encoding via TwoLAME
-- bmp parser
-- smptebars source
-- asetpts filter
-- hue filter
-- ICO muxer
-- SubRip encoder and decoder without embedded timing
-- edge detection filter
-- framestep filter
-- ffmpeg -shortest option is now per-output file
- -pass and -passlogfile are now per-output stream
-- volume measurement filter
-- Ut Video encoder
-- Microsoft Screen 2 decoder
-- smartblur filter ported from MPlayer
-- CPiA decoder
-- decimate filter ported from MPlayer
-- RTP depacketization of JPEG
-- Smooth Streaming live segmenter muxer
-- F4V muxer
-- sendcmd and asendcmd filters
-- WebVTT demuxer and decoder (simple tags supported)
-- RTP packetization of JPEG
-- faststart option in the MOV/MP4 muxer
-- support for building with MSVC
-
-
-version 0.11:
-
-- Fixes: CVE-2012-2772, CVE-2012-2774, CVE-2012-2775, CVE-2012-2776, CVE-2012-2777,
- CVE-2012-2779, CVE-2012-2782, CVE-2012-2783, CVE-2012-2784, CVE-2012-2785,
- CVE-2012-2786, CVE-2012-2787, CVE-2012-2788, CVE-2012-2789, CVE-2012-2790,
- CVE-2012-2791, CVE-2012-2792, CVE-2012-2793, CVE-2012-2794, CVE-2012-2795,
- CVE-2012-2796, CVE-2012-2797, CVE-2012-2798, CVE-2012-2799, CVE-2012-2800,
- CVE-2012-2801, CVE-2012-2802, CVE-2012-2803, CVE-2012-2804,
-- v408 Quicktime and Microsoft AYUV Uncompressed 4:4:4:4 encoder and decoder
-- setfield filter
-- CDXL demuxer and decoder
-- Apple ProRes encoder
-- ffprobe -count_packets and -count_frames options
-- Sun Rasterfile Encoder
-- ID3v2 attached pictures reading and writing
-- WMA Lossless decoder
-- bluray protocol
-- blackdetect filter
-- libutvideo encoder wrapper (--enable-libutvideo)
-- swapuv filter
-- bbox filter
-- XBM encoder and decoder
-- RealAudio Lossless decoder
-- ZeroCodec decoder
-- tile video filter
-- Metal Gear Solid: The Twin Snakes demuxer
-- OpenEXR image decoder
-- removelogo filter
-- drop support for ffmpeg without libavfilter
-- drawtext video filter: fontconfig support
-- ffmpeg -benchmark_all option
-- super2xsai filter ported from libmpcodecs
-- add libavresample audio conversion library for compatibility
-- MicroDVD decoder
-- Avid Meridien (AVUI) encoder and decoder
-- accept + prefix to -pix_fmt option to disable automatic conversions.
-- complete audio filtering in libavfilter and ffmpeg
-- add fps filter
-- vorbis parser
-- png parser
-- audio mix filter
-- ffv1: support (draft) version 1.3
-
-
-version 0.10:
-
-- Fixes: CVE-2011-3929, CVE-2011-3934, CVE-2011-3935, CVE-2011-3936,
- CVE-2011-3937, CVE-2011-3940, CVE-2011-3941, CVE-2011-3944,
- CVE-2011-3945, CVE-2011-3946, CVE-2011-3947, CVE-2011-3949,
- CVE-2011-3950, CVE-2011-3951, CVE-2011-3952
-- v410 Quicktime Uncompressed 4:4:4 10-bit encoder and decoder
-- SBaGen (SBG) binaural beats script demuxer
-- OpenMG Audio muxer
-- Timecode extraction in DV and MOV
-- thumbnail video filter
-- XML output in ffprobe
-- asplit audio filter
-- tinterlace video filter
-- astreamsync audio filter
-- amerge audio filter
-- ISMV (Smooth Streaming) muxer
-- GSM audio parser
-- SMJPEG muxer
-- XWD encoder and decoder
-- Automatic thread count based on detection number of (available) CPU cores
-- y41p Brooktree Uncompressed 4:1:1 12-bit encoder and decoder
-- ffprobe -show_error option
-- Avid 1:1 10-bit RGB Packer codec
-- v308 Quicktime Uncompressed 4:4:4 encoder and decoder
-- yuv4 libquicktime packed 4:2:0 encoder and decoder
-- ffprobe -show_frames option
-- silencedetect audio filter
-- ffprobe -show_program_version, -show_library_versions, -show_versions options
-- rv34: frame-level multi-threading
-- optimized iMDCT transform on x86 using SSE for for mpegaudiodec
-- Improved PGS subtitle decoder
-- dumpgraph option to lavfi device
-- r210 and r10k encoders
-- ffwavesynth decoder
-- aviocat tool
-- ffeval tool
-- support encoding and decoding 4-channel SGI images
-
-
-version 0.9:
-
-- openal input device added
-- boxblur filter added
-- BWF muxer
-- Flash Screen Video 2 decoder
-- lavfi input device added
-- added avconv, which is almost the same for now, except
-for a few incompatible changes in the options, which will hopefully make them
-easier to use. The changes are:
- * The options placement is now strictly enforced! While in theory the
- options for ffmpeg should be given in [input options] -i INPUT [output
- options] OUTPUT order, in practice it was possible to give output options
- before the -i and it mostly worked. Except when it didn't - the behavior was
- a bit inconsistent. In avconv, it is not possible to mix input and output
- options. All non-global options are reset after an input or output filename.
- * All per-file options are now truly per-file - they apply only to the next
- input or output file and specifying different values for different files
- will now work properly (notably -ss and -t options).
- * All per-stream options are now truly per-stream - it is possible to
- specify which stream(s) should a given option apply to. See the Stream
- specifiers section in the avconv manual for details.
- * In ffmpeg some options (like -newvideo/-newaudio/...) are irregular in the
- sense that they're specified after the output filename instead of before,
- like all other options. In avconv this irregularity is removed, all options
- apply to the next input or output file.
- * -newvideo/-newaudio/-newsubtitle options were removed. Not only were they
- irregular and highly confusing, they were also redundant. In avconv the -map
- option will create new streams in the output file and map input streams to
- them. E.g. avconv -i INPUT -map 0 OUTPUT will create an output stream for
- each stream in the first input file.
- * The -map option now has slightly different and more powerful syntax:
- + Colons (':') are used to separate file index/stream type/stream index
- instead of dots. Comma (',') is used to separate the sync stream instead
- of colon.. This is done for consistency with other options.
- + It's possible to specify stream type. E.g. -map 0:a:2 creates an
- output stream from the third input audio stream.
- + Omitting the stream index now maps all the streams of the given type,
- not just the first. E.g. -map 0:s creates output streams for all the
- subtitle streams in the first input file.
- + Since -map can now match multiple streams, negative mappings were
- introduced. Negative mappings disable some streams from an already
- defined map. E.g. '-map 0 -map -0:a:1' means 'create output streams for
- all the stream in the first input file, except for the second audio
- stream'.
- * There is a new option -c (or -codec) for choosing the decoder/encoder to
- use, which makes it possible to precisely specify target stream(s) consistently with
- other options. E.g. -c:v lib264 sets the codec for all video streams, -c:a:0
- libvorbis sets the codec for the first audio stream and -c copy copies all
- the streams without reencoding. Old -vcodec/-acodec/-scodec options are now
- aliases to -c:v/a/s
- * It is now possible to precisely specify which stream should an AVOption
- apply to. E.g. -b:v:0 2M sets the bitrate for the first video stream, while
- -b:a 128k sets the bitrate for all audio streams. Note that the old -ab 128k
- syntax is deprecated and will stop working soon.
- * -map_chapters now takes only an input file index and applies to the next
- output file. This is consistent with how all the other options work.
- * -map_metadata now takes only an input metadata specifier and applies to
- the next output file. Output metadata specifier is now part of the option
- name, similarly to the AVOptions/map/codec feature above.
- * -metadata can now be used to set metadata on streams and chapters, e.g.
- -metadata:s:1 language=eng sets the language of the first stream to 'eng'.
- This made -vlang/-alang/-slang options redundant, so they were removed.
- * -qscale option now uses stream specifiers and applies to all streams, not
- just video. I.e. plain -qscale number would now apply to all streams. To get
- the old behavior, use -qscale:v. Also there is now a shortcut -q for -qscale
- and -aq is now an alias for -q:a.
- * -vbsf/-absf/-sbsf options were removed and replaced by a -bsf option which
- uses stream specifiers. Use -bsf:v/a/s instead of the old options.
- * -itsscale option now uses stream specifiers, so its argument is only the
- scale parameter.
- * -intra option was removed, use -g 0 for the same effect.
- * -psnr option was removed, use -flags +psnr for the same effect.
- * -vf option is now an alias to the new -filter option, which uses stream specifiers.
- * -vframes/-aframes/-dframes options are now aliases to the new -frames option.
- * -vtag/-atag/-stag options are now aliases to the new -tag option.
-- XMV demuxer
-- LOAS demuxer
-- ashowinfo filter added
-- Windows Media Image decoder
-- amovie source added
-- LATM muxer/demuxer
-- Speex encoder via libspeex
-- JSON output in ffprobe
-- WTV muxer
-- Optional C++ Support (needed for libstagefright)
-- H.264 Decoding on Android via Stagefright
-- Prores decoder
-- BIN/XBIN/ADF/IDF text file decoder
-- aconvert audio filter added
-- audio support to lavfi input device added
-- libcdio-paranoia input device for audio CD grabbing
-- Apple ProRes decoder
-- CELT in Ogg demuxing
-- G.723.1 demuxer and decoder
-- libmodplug support (--enable-libmodplug)
-- VC-1 interlaced decoding
-- libutvideo wrapper (--enable-libutvideo)
-- aevalsrc audio source added
-- Ut Video decoder
-- Speex encoding via libspeex
-- 4:2:2 H.264 decoding support
-- 4:2:2 and 4:4:4 H.264 encoding with libx264
-- Pulseaudio input device
-- Prores encoder
-- Video Decoder Acceleration (VDA) HWAccel module.
-- replacement Indeo 3 decoder
-- new ffmpeg option: -map_channel
-- volume audio filter added
-- earwax audio filter added
-- libv4l2 support (--enable-libv4l2)
-- TLS/SSL and HTTPS protocol support
-- AVOptions API rewritten and documented
-- most of CODEC_FLAG2_*, some CODEC_FLAG_* and many codec-specific fields in
- AVCodecContext deprecated. Codec private options should be used instead.
-- Properly working defaults in libx264 wrapper, support for native presets.
-- Encrypted OMA files support
-- Discworld II BMV decoding support
-- VBLE Decoder
-- OS X Video Decoder Acceleration (VDA) support
-- compact and csv output in ffprobe
-- pan audio filter
-- IFF Amiga Continuous Bitmap (ACBM) decoder
-- ass filter
-- CRI ADX audio format muxer and demuxer
-- Playstation Portable PMP format demuxer
-- Microsoft Windows ICO demuxer
-- life source
-- PCM format support in OMA demuxer
-- CLJR encoder
-- new option: -report
-- Dxtory capture format decoder
-- cellauto source
-- Simple segmenting muxer
-- Indeo 4 decoder
-- SMJPEG demuxer
-
-
-version 0.8:
-
-- many many things we forgot because we rather write code than changelogs
-- WebM support in Matroska de/muxer
-- low overhead Ogg muxing
-- MMS-TCP support
-- VP8 de/encoding via libvpx
-- Demuxer for On2's IVF format
-- Pictor/PC Paint decoder
-- HE-AAC v2 decoder
-- HE-AAC v2 encoding with libaacplus
-- libfaad2 wrapper removed
-- DTS-ES extension (XCh) decoding support
-- native VP8 decoder
-- RTSP tunneling over HTTP
-- RTP depacketization of SVQ3
-- -strict inofficial replaced by -strict unofficial
-- ffplay -exitonkeydown and -exitonmousedown options added
-- native GSM / GSM MS decoder
-- RTP depacketization of QDM2
-- ANSI/ASCII art playback system
-- Lego Mindstorms RSO de/muxer
-- libavcore added (and subsequently removed)
-- SubRip subtitle file muxer and demuxer
-- Chinese AVS encoding via libxavs
-- ffprobe -show_packets option added
-- RTP packetization of Theora and Vorbis
-- RTP depacketization of MP4A-LATM
-- RTP packetization and depacketization of VP8
-- hflip filter
-- Apple HTTP Live Streaming demuxer
-- a64 codec
-- MMS-HTTP support
-- G.722 ADPCM audio encoder/decoder
-- R10k video decoder
-- ocv_smooth filter
-- frei0r wrapper filter
-- change crop filter syntax to width:height:x:y
-- make the crop filter accept parametric expressions
-- make ffprobe accept AVFormatContext options
-- yadif filter
-- blackframe filter
-- Demuxer for Leitch/Harris' VR native stream format (LXF)
-- RTP depacketization of the X-QT QuickTime format
-- SAP (Session Announcement Protocol, RFC 2974) muxer and demuxer
-- cropdetect filter
-- ffmpeg -crop* options removed
-- transpose filter added
-- ffmpeg -force_key_frames option added
-- demuxer for receiving raw rtp:// URLs without an SDP description
-- single stream LATM/LOAS decoder
-- setpts filter added
-- Win64 support for optimized x86 assembly functions
-- MJPEG/AVI1 to JPEG/JFIF bitstream filter
-- ASS subtitle encoder and decoder
-- IEC 61937 encapsulation for E-AC-3, TrueHD, DTS-HD (for HDMI passthrough)
-- overlay filter added
-- rename aspect filter to setdar, and pixelaspect to setsar
-- IEC 61937 demuxer
-- Mobotix .mxg demuxer
-- frei0r source added
-- hqdn3d filter added
-- RTP depacketization of QCELP
-- FLAC parser added
-- gradfun filter added
-- AMR-WB decoder
-- replace the ocv_smooth filter with a more generic ocv filter
-- Windows Televison (WTV) demuxer
-- FFmpeg metadata format muxer and demuxer
-- SubRip (srt) subtitle encoder and decoder
-- floating-point AC-3 encoder added
-- Lagarith decoder
-- ffmpeg -copytb option added
-- IVF muxer added
-- Wing Commander IV movies decoder added
-- movie source added
-- Bink version 'b' audio and video decoder
-- Bitmap Brothers JV playback system
-- Apple HTTP Live Streaming protocol handler
-- sndio support for playback and record
-- Linux framebuffer input device added
-- Chronomaster DFA decoder
-- DPX image encoder
-- MicroDVD subtitle file muxer and demuxer
-- Playstation Portable PMP format demuxer
-- fieldorder video filter added
-- AAC encoding via libvo-aacenc
-- AMR-WB encoding via libvo-amrwbenc
-- xWMA demuxer
-- Mobotix MxPEG decoder
-- VP8 frame-multithreading
-- NEON optimizations for VP8
-- Lots of deprecated API cruft removed
-- fft and imdct optimizations for AVX (Sandy Bridge) processors
-- showinfo filter added
-- SMPTE 302M AES3 audio decoder
-- Apple Core Audio Format muxer
-- 9bit and 10bit per sample support in the H.264 decoder
-- 9bit and 10bit FFV1 encoding / decoding
-- split filter added
-- select filter added
-- sdl output device added
-- libmpcodecs video filter support (3 times as many filters than before)
-- mpeg2 aspect ratio dection fixed
-- libxvid aspect pickiness fixed
-- Frame multithreaded decoding
-- E-AC-3 audio encoder
-- ac3enc: add channel coupling support
-- floating-point sample format support to the ac3, eac3, dca, aac, and vorbis decoders.
-- H264/MPEG frame-level multi-threading
-- All av_metadata_* functions renamed to av_dict_* and moved to libavutil
-- 4:4:4 H.264 decoding support
-- 10-bit H.264 optimizations for x86
-- lut, lutrgb, and lutyuv filters added
-- buffersink libavfilter sink added
-- Bump libswscale for recently reported ABI break
-- New J2K encoder (via OpenJPEG)
-
-
-version 0.7:
-
-- all the changes for 0.8, but keeping API/ABI compatibility with the 0.6 release
-
-
-version 0.6:
-
-- PB-frame decoding for H.263
-- deprecated vhook subsystem removed
-- deprecated old scaler removed
-- VQF demuxer
-- Alpha channel scaler
-- PCX encoder
-- RTP packetization of H.263
-- RTP packetization of AMR
-- RTP depacketization of Vorbis
-- CorePNG decoding support
-- Cook multichannel decoding support
-- introduced avlanguage helpers in libavformat
-- 8088flex TMV demuxer and decoder
-- per-stream language-tags extraction in asfdec
-- V210 decoder and encoder
-- remaining GPL parts in AC-3 decoder converted to LGPL
-- QCP demuxer
-- SoX native format muxer and demuxer
-- AMR-NB decoding/encoding, AMR-WB decoding via OpenCORE libraries
-- DPX image decoder
-- Electronic Arts Madcow decoder
-- DivX (XSUB) subtitle encoder
-- nonfree libamr support for AMR-NB/WB decoding/encoding removed
-- experimental AAC encoder
-- RTP depacketization of ASF and RTSP from WMS servers
-- RTMP support in libavformat
-- noX handling for OPT_BOOL X options
-- Wave64 demuxer
-- IEC-61937 compatible Muxer
-- TwinVQ decoder
-- Bluray (PGS) subtitle decoder
-- LPCM support in MPEG-TS (HDMV RID as found on Blu-ray disks)
-- WMA Pro decoder
-- Core Audio Format demuxer
-- ATRAC1 decoder
-- MD STUDIO audio demuxer
-- RF64 support in WAV demuxer
-- MPEG-4 Audio Lossless Coding (ALS) decoder
-- -formats option split into -formats, -codecs, -bsfs, and -protocols
-- IV8 demuxer
-- CDG demuxer and decoder
-- R210 decoder
-- Auravision Aura 1 and 2 decoders
-- Deluxe Paint Animation playback system
-- SIPR decoder
-- Adobe Filmstrip muxer and demuxer
-- RTP depacketization of H.263
-- Bink demuxer and audio/video decoders
-- enable symbol versioning by default for linkers that support it
-- IFF PBM/ILBM bitmap decoder
-- concat protocol
-- Indeo 5 decoder
-- RTP depacketization of AMR
-- WMA Voice decoder
-- ffprobe tool
-- AMR-NB decoder
-- RTSP muxer
-- HE-AAC v1 decoder
-- Kega Game Video (KGV1) decoder
-- VorbisComment writing for FLAC, Ogg FLAC and Ogg Speex files
-- RTP depacketization of Theora
-- HTTP Digest authentication
-- RTMP/RTMPT/RTMPS/RTMPE/RTMPTE protocol support via librtmp
-- Psygnosis YOP demuxer and video decoder
-- spectral extension support in the E-AC-3 decoder
-- unsharp video filter
-- RTP hinting in the mov/3gp/mp4 muxer
-- Dirac in Ogg demuxing
-- seek to keyframes in Ogg
-- 4:2:2 and 4:4:4 Theora decoding
-- 35% faster VP3/Theora decoding
-- faster AAC decoding
-- faster H.264 decoding
-- RealAudio 1.0 (14.4K) encoder
-
-
-version 0.5:
-
-- DV50 AKA DVCPRO50 encoder, decoder, muxer and demuxer
-- TechSmith Camtasia (TSCC) video decoder
-- IBM Ultimotion (ULTI) video decoder
-- Sierra Online audio file demuxer and decoder
-- Apple QuickDraw (qdrw) video decoder
-- Creative ADPCM audio decoder (16 bits as well as 8 bits schemes)
-- Electronic Arts Multimedia (WVE/UV2/etc.) file demuxer
-- Miro VideoXL (VIXL) video decoder
-- H.261 video encoder
-- QPEG video decoder
-- Nullsoft Video (NSV) file demuxer
-- Shorten audio decoder
-- LOCO video decoder
-- Apple Lossless Audio Codec (ALAC) decoder
-- Winnov WNV1 video decoder
-- Autodesk Animator Studio Codec (AASC) decoder
-- Indeo 2 video decoder
-- Fraps FPS1 video decoder
-- Snow video encoder/decoder
-- Sonic audio encoder/decoder
-- Vorbis audio decoder
-- Macromedia ADPCM decoder
-- Duck TrueMotion 2 video decoder
-- support for decoding FLX and DTA extensions in FLIC files
-- H.264 custom quantization matrices support
-- ffserver fixed, it should now be usable again
-- QDM2 audio decoder
-- Real Cooker audio decoder
-- TrueSpeech audio decoder
-- WMA2 audio decoder fixed, now all files should play correctly
-- RealAudio 14.4 and 28.8 decoders fixed
-- JPEG-LS decoder
-- build system improvements
-- tabs and trailing whitespace removed from the codebase
-- CamStudio video decoder
-- AIFF/AIFF-C audio format, encoding and decoding
-- ADTS AAC file reading and writing
-- Creative VOC file reading and writing
-- American Laser Games multimedia (*.mm) playback system
-- Zip Motion Blocks Video decoder
-- improved Theora/VP3 decoder
-- True Audio (TTA) decoder
-- AVS demuxer and video decoder
-- JPEG-LS encoder
-- Smacker demuxer and decoder
-- NuppelVideo/MythTV demuxer and RTjpeg decoder
-- KMVC decoder
-- MPEG-2 intra VLC support
-- MPEG-2 4:2:2 encoder
-- Flash Screen Video decoder
-- GXF demuxer
-- Chinese AVS decoder
-- GXF muxer
-- MXF demuxer
-- VC-1/WMV3/WMV9 video decoder
-- MacIntel support
-- AviSynth support
-- VMware video decoder
-- VP5 video decoder
-- VP6 video decoder
-- WavPack lossless audio decoder
-- Targa (.TGA) picture decoder
-- Vorbis audio encoder
-- Delphine Software .cin demuxer/audio and video decoder
-- Tiertex .seq demuxer/video decoder
-- MTV demuxer
-- TIFF picture encoder and decoder
-- GIF picture decoder
-- Intel Music Coder decoder
-- Zip Motion Blocks Video encoder
-- Musepack decoder
-- Flash Screen Video encoder
-- Theora encoding via libtheora
-- BMP encoder
-- WMA encoder
-- GSM-MS encoder and decoder
-- DCA decoder
-- DXA demuxer and decoder
-- DNxHD decoder
-- Gamecube movie (.THP) playback system
-- Blackfin optimizations
-- Interplay C93 demuxer and video decoder
-- Bethsoft VID demuxer and video decoder
-- CRYO APC demuxer
-- ATRAC3 decoder
-- V.Flash PTX decoder
-- RoQ muxer, RoQ audio encoder
-- Renderware TXD demuxer and decoder
-- extern C declarations for C++ removed from headers
-- sws_flags command line option
-- codebook generator
-- RoQ video encoder
-- QTRLE encoder
-- OS/2 support removed and restored again
-- AC-3 decoder
-- NUT muxer
-- additional SPARC (VIS) optimizations
-- Matroska muxer
-- slice-based parallel H.264 decoding
-- Monkey's Audio demuxer and decoder
-- AMV audio and video decoder
-- DNxHD encoder
-- H.264 PAFF decoding
-- Nellymoser ASAO decoder
-- Beam Software SIFF demuxer and decoder
-- libvorbis Vorbis decoding removed in favor of native decoder
-- IntraX8 (J-Frame) subdecoder for WMV2 and VC-1
-- Ogg (Theora, Vorbis and FLAC) muxer
-- The "device" muxers and demuxers are now in a new libavdevice library
-- PC Paintbrush PCX decoder
-- Sun Rasterfile decoder
-- TechnoTrend PVA demuxer
-- Linux Media Labs MPEG-4 (LMLM4) demuxer
-- AVM2 (Flash 9) SWF muxer
-- QT variant of IMA ADPCM encoder
-- VFW grabber
-- iPod/iPhone compatible mp4 muxer
-- Mimic decoder
-- MSN TCP Webcam stream demuxer
-- RL2 demuxer / decoder
-- IFF demuxer
-- 8SVX audio decoder
-- non-recursive Makefiles
-- BFI demuxer
-- MAXIS EA XA (.xa) demuxer / decoder
-- BFI video decoder
-- OMA demuxer
-- MLP/TrueHD decoder
-- Electronic Arts CMV decoder
-- Motion Pixels Video decoder
-- Motion Pixels MVI demuxer
-- removed animated GIF decoder/demuxer
-- D-Cinema audio muxer
-- Electronic Arts TGV decoder
-- Apple Lossless Audio Codec (ALAC) encoder
-- AAC decoder
-- floating point PCM encoder/decoder
-- MXF muxer
-- DV100 AKA DVCPRO HD decoder and demuxer
-- E-AC-3 support added to AC-3 decoder
-- Nellymoser ASAO encoder
-- ASS and SSA demuxer and muxer
-- liba52 wrapper removed
-- SVQ3 watermark decoding support
-- Speex decoding via libspeex
-- Electronic Arts TGQ decoder
-- RV40 decoder
-- QCELP / PureVoice decoder
-- RV30 decoder
-- hybrid WavPack support
-- R3D REDCODE demuxer
-- ALSA support for playback and record
-- Electronic Arts TQI decoder
-- OpenJPEG based JPEG 2000 decoder
-- NC (NC4600) camera file demuxer
-- Gopher client support
-- MXF D-10 muxer
-- generic metadata API
-- flash ScreenVideo2 encoder
-
-
-version 0.4.9-pre1:
-
-- DV encoder, DV muxer
-- Microsoft RLE video decoder
-- Microsoft Video-1 decoder
-- Apple Animation (RLE) decoder
-- Apple Graphics (SMC) decoder
-- Apple Video (RPZA) decoder
-- Cinepak decoder
-- Sega FILM (CPK) file demuxer
-- Westwood multimedia support (VQA & AUD files)
-- Id Quake II CIN playback support
-- 8BPS video decoder
-- FLIC playback support
-- RealVideo 2.0 (RV20) decoder
-- Duck TrueMotion v1 (DUCK) video decoder
-- Sierra VMD demuxer and video decoder
-- MSZH and ZLIB decoder support
-- SVQ1 video encoder
-- AMR-WB support
-- PPC optimizations
-- rate distortion optimal cbp support
-- rate distorted optimal ac prediction for MPEG-4
-- rate distorted optimal lambda->qp support
-- AAC encoding with libfaac
-- Sunplus JPEG codec (SP5X) support
-- use Lagrange multipler instead of QP for ratecontrol
-- Theora/VP3 decoding support
-- XA and ADX ADPCM codecs
-- export MPEG-2 active display area / pan scan
-- Add support for configuring with IBM XLC
-- floating point AAN DCT
-- initial support for zygo video (not complete)
-- RGB ffv1 support
-- new audio/video parser API
-- av_log() system
-- av_read_frame() and av_seek_frame() support
-- missing last frame fixes
-- seek by mouse in ffplay
-- noise reduction of DCT coefficients
-- H.263 OBMC & 4MV support
-- H.263 alternative inter vlc support
-- H.263 loop filter
-- H.263 slice structured mode
-- interlaced DCT support for MPEG-2 encoding
-- stuffing to stay above min_bitrate
-- MB type & QP visualization
-- frame stepping for ffplay
-- interlaced motion estimation
-- alternate scantable support
-- SVCD scan offset support
-- closed GOP support
-- SSE2 FDCT
-- quantizer noise shaping
-- G.726 ADPCM audio codec
-- MS ADPCM encoding
-- multithreaded/SMP motion estimation
-- multithreaded/SMP encoding for MPEG-1/MPEG-2/MPEG-4/H.263
-- multithreaded/SMP decoding for MPEG-2
-- FLAC decoder
-- Metrowerks CodeWarrior suppport
-- H.263+ custom pcf support
-- nicer output for 'ffmpeg -formats'
-- Matroska demuxer
-- SGI image format, encoding and decoding
-- H.264 loop filter support
-- H.264 CABAC support
-- nicer looking arrows for the motion vector visualization
-- improved VCD support
-- audio timestamp drift compensation
-- MPEG-2 YUV 422/444 support
-- polyphase kaiser windowed sinc and blackman nuttall windowed sinc audio resample
-- better image scaling
-- H.261 support
-- correctly interleave packets during encoding
-- VIS optimized motion compensation
-- intra_dc_precision>0 encoding support
-- support reuse of motion vectors/MB types/field select values of the source video
-- more accurate deblock filter
-- padding support
-- many optimizations and bugfixes
-- FunCom ISS audio file demuxer and according ADPCM decoding
-
-
-version 0.4.8:
-
-- MPEG-2 video encoding (Michael)
-- Id RoQ playback subsystem (Mike Melanson and Tim Ferguson)
-- Wing Commander III Movie (.mve) file playback subsystem (Mike Melanson
- and Mario Brito)
-- Xan DPCM audio decoder (Mario Brito)
-- Interplay MVE playback subsystem (Mike Melanson)
-- Duck DK3 and DK4 ADPCM audio decoders (Mike Melanson)
-
-
-version 0.4.7:
-
-- RealAudio 1.0 (14_4) and 2.0 (28_8) native decoders. Author unknown, code from mplayerhq
- (originally from public domain player for Amiga at http://www.honeypot.net/audio)
-- current version now also compiles with older GCC (Fabrice)
-- 4X multimedia playback system including 4xm file demuxer (Mike
- Melanson), and 4X video and audio codecs (Michael)
-- Creative YUV (CYUV) decoder (Mike Melanson)
-- FFV1 codec (our very simple lossless intra only codec, compresses much better
- than HuffYUV) (Michael)
-- ASV1 (Asus), H.264, Intel indeo3 codecs have been added (various)
-- tiny PNG encoder and decoder, tiny GIF decoder, PAM decoder (PPM with
- alpha support), JPEG YUV colorspace support. (Fabrice Bellard)
-- ffplay has been replaced with a newer version which uses SDL (optionally)
- for multiplatform support (Fabrice)
-- Sorenson Version 3 codec (SVQ3) support has been added (decoding only) - donated
- by anonymous
-- AMR format has been added (Johannes Carlsson)
-- 3GP support has been added (Johannes Carlsson)
-- VP3 codec has been added (Mike Melanson)
-- more MPEG-1/2 fixes
-- better multiplatform support, MS Visual Studio fixes (various)
-- AltiVec optimizations (Magnus Damn and others)
-- SH4 processor support has been added (BERO)
-- new public interfaces (avcodec_get_pix_fmt) (Roman Shaposhnick)
-- VOB streaming support (Brian Foley)
-- better MP3 autodetection (Andriy Rysin)
-- qpel encoding (Michael)
-- 4mv+b frames encoding finally fixed (Michael)
-- chroma ME (Michael)
-- 5 comparison functions for ME (Michael)
-- B-frame encoding speedup (Michael)
-- WMV2 codec (unfinished - Michael)
-- user specified diamond size for EPZS (Michael)
-- Playstation STR playback subsystem, still experimental (Mike and Michael)
-- ASV2 codec (Michael)
-- CLJR decoder (Alex)
-
-.. And lots more new enhancements and fixes.
-
-
-version 0.4.6:
-
-- completely new integer only MPEG audio layer 1/2/3 decoder rewritten
- from scratch
-- Recoded DCT and motion vector search with gcc (no longer depends on nasm)
-- fix quantization bug in AC3 encoder
-- added PCM codecs and format. Corrected WAV/AVI/ASF PCM issues
-- added prototype ffplay program
-- added GOB header parsing on H.263/H.263+ decoder (Juanjo)
-- bug fix on MCBPC tables of H.263 (Juanjo)
-- bug fix on DC coefficients of H.263 (Juanjo)
-- added Advanced Prediction Mode on H.263/H.263+ decoder (Juanjo)
-- now we can decode H.263 streams found in QuickTime files (Juanjo)
-- now we can decode H.263 streams found in VIVO v1 files(Juanjo)
-- preliminary RTP "friendly" mode for H.263/H.263+ coding. (Juanjo)
-- added GOB header for H.263/H.263+ coding on RTP mode (Juanjo)
-- now H.263 picture size is returned on the first decoded frame (Juanjo)
-- added first regression tests
-- added MPEG-2 TS demuxer
-- new demux API for libav
-- more accurate and faster IDCT (Michael)
-- faster and entropy-controlled motion search (Michael)
-- two pass video encoding (Michael)
-- new video rate control (Michael)
-- added MSMPEG4V1, MSMPEGV2 and WMV1 support (Michael)
-- great performance improvement of video encoders and decoders (Michael)
-- new and faster bit readers and vlc parsers (Michael)
-- high quality encoding mode: tries all macroblock/VLC types (Michael)
-- added DV video decoder
-- preliminary RTP/RTSP support in ffserver and libavformat
-- H.263+ AIC decoding/encoding support (Juanjo)
-- VCD MPEG-PS mode (Juanjo)
-- PSNR stuff (Juanjo)
-- simple stats output (Juanjo)
-- 16-bit and 15-bit RGB/BGR/GBR support (Bisqwit)
-
-
-version 0.4.5:
-
-- some header fixes (Zdenek Kabelac <kabi at informatics.muni.cz>)
-- many MMX optimizations (Nick Kurshev <nickols_k at mail.ru>)
-- added configure system (actually a small shell script)
-- added MPEG audio layer 1/2/3 decoding using LGPL'ed mpglib by
- Michael Hipp (temporary solution - waiting for integer only
- decoder)
-- fixed VIDIOCSYNC interrupt
-- added Intel H.263 decoding support ('I263' AVI fourCC)
-- added Real Video 1.0 decoding (needs further testing)
-- simplified image formats again. Added PGM format (=grey
- pgm). Renamed old PGM to PGMYUV.
-- fixed msmpeg4 slice issues (tell me if you still find problems)
-- fixed OpenDivX bugs with newer versions (added VOL header decoding)
-- added support for MPlayer interface
-- added macroblock skip optimization
-- added MJPEG decoder
-- added mmx/mmxext IDCT from libmpeg2
-- added pgmyuvpipe, ppm, and ppm_pipe formats (original patch by Celer
- <celer at shell.scrypt.net>)
-- added pixel format conversion layer (e.g. for MJPEG or PPM)
-- added deinterlacing option
-- MPEG-1/2 fixes
-- MPEG-4 vol header fixes (Jonathan Marsden <snmjbm at pacbell.net>)
-- ARM optimizations (Lionel Ulmer <lionel.ulmer at free.fr>).
-- Windows porting of file converter
-- added MJPEG raw format (input/output)
-- added JPEG image format support (input/output)
-
-
-version 0.4.4:
-
-- fixed some std header definitions (Bjorn Lindgren
- <bjorn.e.lindgren at telia.com>).
-- added MPEG demuxer (MPEG-1 and 2 compatible).
-- added ASF demuxer
-- added prototype RM demuxer
-- added AC3 decoding (done with libac3 by Aaron Holtzman)
-- added decoding codec parameter guessing (.e.g. for MPEG, because the
- header does not include them)
-- fixed header generation in MPEG-1, AVI and ASF muxer: wmplayer can now
- play them (only tested video)
-- fixed H.263 white bug
-- fixed phase rounding in img resample filter
-- add MMX code for polyphase img resample filter
-- added CPU autodetection
-- added generic title/author/copyright/comment string handling (ASF and RM
- use them)
-- added SWF demux to extract MP3 track (not usable yet because no MP3
- decoder)
-- added fractional frame rate support
-- codecs are no longer searched by read_header() (should fix ffserver
- segfault)
-
-
-version 0.4.3:
-
-- BGR24 patch (initial patch by Jeroen Vreeken <pe1rxq at amsat.org>)
-- fixed raw yuv output
-- added motion rounding support in MPEG-4
-- fixed motion bug rounding in MSMPEG4
-- added B-frame handling in video core
-- added full MPEG-1 decoding support
-- added partial (frame only) MPEG-2 support
-- changed the FOURCC code for H.263 to "U263" to be able to see the
- +AVI/H.263 file with the UB Video H.263+ decoder. MPlayer works with
- this +codec ;) (JuanJo).
-- Halfpel motion estimation after MB type selection (JuanJo)
-- added pgm and .Y.U.V output format
-- suppressed 'img:' protocol. Simply use: /tmp/test%d.[pgm|Y] as input or
- output.
-- added pgmpipe I/O format (original patch from Martin Aumueller
- <lists at reserv.at>, but changed completely since we use a format
- instead of a protocol)
-
-
-version 0.4.2:
-
-- added H.263/MPEG-4/MSMPEG4 decoding support. MPEG-4 decoding support
- (for OpenDivX) is almost complete: 8x8 MVs and rounding are
- missing. MSMPEG4 support is complete.
-- added prototype MPEG-1 decoder. Only I- and P-frames handled yet (it
- can decode ffmpeg MPEGs :-)).
-- added libavcodec API documentation (see apiexample.c).
-- fixed image polyphase bug (the bottom of some images could be
- greenish)
-- added support for non clipped motion vectors (decoding only)
- and image sizes non-multiple of 16
-- added support for AC prediction (decoding only)
-- added file overwrite confirmation (can be disabled with -y)
-- added custom size picture to H.263 using H.263+ (Juanjo)
-
-
-version 0.4.1:
-
-- added MSMPEG4 (aka DivX) compatible encoder. Changed default codec
- of AVI and ASF to DIV3.
-- added -me option to set motion estimation method
- (default=log). suppressed redundant -hq option.
-- added options -acodec and -vcodec to force a given codec (useful for
- AVI for example)
-- fixed -an option
-- improved dct_quantize speed
-- factorized some motion estimation code
-
-
-version 0.4.0:
-
-- removing grab code from ffserver and moved it to ffmpeg. Added
- multistream support to ffmpeg.
-- added timeshifting support for live feeds (option ?date=xxx in the
- URL)
-- added high quality image resize code with polyphase filter (need
- mmx/see optimization). Enable multiple image size support in ffserver.
-- added multi live feed support in ffserver
-- suppressed master feature from ffserver (it should be done with an
- external program which opens the .ffm url and writes it to another
- ffserver)
-- added preliminary support for video stream parsing (WAV and AVI half
- done). Added proper support for audio/video file conversion in
- ffmpeg.
-- added preliminary support for video file sending from ffserver
-- redesigning I/O subsystem: now using URL based input and output
- (see avio.h)
-- added WAV format support
-- added "tty user interface" to ffmpeg to stop grabbing gracefully
-- added MMX/SSE optimizations to SAD (Sums of Absolutes Differences)
- (Juan J. Sierralta P. a.k.a. "Juanjo" <juanjo at atmlab.utfsm.cl>)
-- added MMX DCT from mpeg2_movie 1.5 (Juanjo)
-- added new motion estimation algorithms, log and phods (Juanjo)
-- changed directories: libav for format handling, libavcodec for
- codecs
-
-
-version 0.3.4:
-
-- added stereo in MPEG audio encoder
-
-
-version 0.3.3:
-
-- added 'high quality' mode which use motion vectors. It can be used in
- real time at low resolution.
-- fixed rounding problems which caused quality problems at high
- bitrates and large GOP size
-
-
-version 0.3.2: small fixes
-
-- ASF fixes
-- put_seek bug fix
-
-
-version 0.3.1: added avi/divx support
-
-- added AVI support
-- added MPEG-4 codec compatible with OpenDivX. It is based on the H.263 codec
-- added sound for flash format (not tested)
-
-
-version 0.3: initial public release
diff --git a/media/ffvpx/FILES b/media/ffvpx/FILES
new file mode 100644
index 000000000..ff8a2da43
--- /dev/null
+++ b/media/ffvpx/FILES
@@ -0,0 +1,282 @@
+./COPYING.LGPLv2.1
+./COPYING.LGPLv3
+./compat/va_copy.h
+./compat/w32pthreads.h
+./compat/atomics/win32/stdatomic.h
+./libavcodec/audioconvert.c
+./libavcodec/audioconvert.h
+./libavcodec/avpicture.c
+./libavcodec/bit_depth_template.c
+./libavcodec/fdctdsp.h
+./libavcodec/flacdata.c
+./libavcodec/flacdata.h
+./libavcodec/flacdsp_lpc_template.c
+./libavcodec/frame_thread_encoder.h
+./libavcodec/golomb.c
+./libavcodec/h263dsp.h
+./libavcodec/h264pred.c
+./libavcodec/h264pred.h
+./libavcodec/h264pred_template.c
+./libavcodec/log2_tab.c
+./libavcodec/mathtables.c
+./libavcodec/motion_est.h
+./libavcodec/mpeg12data.h
+./libavcodec/mpegpicture.h
+./libavcodec/mpegutils.h
+./libavcodec/mpegvideodsp.h
+./libavcodec/mpegvideoencdsp.h
+./libavcodec/parser.h
+./libavcodec/profiles.c
+./libavcodec/profiles.h
+./libavcodec/pthread.c
+./libavcodec/pthread_internal.h
+./libavcodec/qpeldsp.h
+./libavcodec/qsv_api.c
+./libavcodec/raw.h
+./libavcodec/rectangle.h
+./libavcodec/resample.c
+./libavcodec/resample2.c
+./libavcodec/reverse.c
+./libavcodec/rl.h
+./libavcodec/rnd_avg.h
+./libavcodec/unary.h
+./libavcodec/videodsp_template.c
+./libavcodec/vorbis_parser.c
+./libavcodec/vorbis_parser_internal.h
+./libavcodec/vp8data.h
+./libavcodec/vp9_parser.c
+./libavcodec/vp9dsp_10bpp.c
+./libavcodec/vp9dsp_12bpp.c
+./libavcodec/vp9dsp_8bpp.c
+./libavcodec/x86/constants.c
+./libavcodec/x86/flacdsp.asm
+./libavcodec/x86/mathops.h
+./libavcodec/x86/vp56_arith.h
+./libavcodec/x86/vp9dsp_init.h
+./libavcodec/x86/vp9dsp_init_10bpp.c
+./libavcodec/x86/vp9dsp_init_12bpp.c
+./libavcodec/x86/vp9intrapred.asm
+./libavcodec/x86/vp9itxfm_16bpp.asm
+./libavcodec/x86/vp9itxfm_template.asm
+./libavcodec/x86/vp9mc_16bpp.asm
+./libavcodec/x86/vp9lpf.asm
+./libavcodec/x86/vp9lpf_16bpp.asm
+./libavcodec/x86/constants.h
+./libavcodec/x86/flacdsp_init.c
+./libavcodec/x86/h264_intrapred.asm
+./libavcodec/x86/h264_intrapred_10bit.asm
+./libavcodec/x86/h264_intrapred_init.c
+./libavcodec/x86/videodsp.asm
+./libavcodec/x86/videodsp_init.c
+./libavcodec/x86/vp8dsp.asm
+./libavcodec/x86/vp8dsp_init.c
+./libavcodec/x86/vp8dsp_loopfilter.asm
+./libavcodec/x86/vp9dsp_init.c
+./libavcodec/x86/vp9dsp_init_16bpp.c
+./libavcodec/x86/vp9dsp_init_16bpp_template.c
+./libavcodec/x86/vp9intrapred_16bpp.asm
+./libavcodec/x86/vp9itxfm.asm
+./libavcodec/x86/vp9mc.asm
+./libavcodec/xiph.c
+./libavcodec/xiph.h
+./libavcodec/bsf.h
+./libavcodec/h264dsp.h
+./libavcodec/imgconvert.c
+./libavcodec/bsf.c
+./libavcodec/decode.c
+./libavcodec/decode.h
+./libavcodec/hwaccel.h
+./libavcodec/vp9block.c
+./libavcodec/vp9data.c
+./libavcodec/vp9dec.h
+./libavcodec/vp9lpf.c
+./libavcodec/vp9mvs.c
+./libavcodec/vp9prob.c
+./libavcodec/vp9recon.c
+./libavcodec/vp9shared.h
+./libavcodec/allcodecs.c
+./libavcodec/avcodec.h
+./libavcodec/avpacket.c
+./libavcodec/bitstream.c
+./libavcodec/blockdsp.h
+./libavcodec/bytestream.h
+./libavcodec/codec_desc.c
+./libavcodec/error_resilience.h
+./libavcodec/flac.c
+./libavcodec/flac.h
+./libavcodec/flac_parser.c
+./libavcodec/flacdec.c
+./libavcodec/flacdsp.c
+./libavcodec/flacdsp.h
+./libavcodec/flacdsp_template.c
+./libavcodec/get_bits.h
+./libavcodec/golomb.h
+./libavcodec/h264chroma.h
+./libavcodec/hpeldsp.h
+./libavcodec/idctdsp.h
+./libavcodec/internal.h
+./libavcodec/mathops.h
+./libavcodec/me_cmp.h
+./libavcodec/mpegvideo.h
+./libavcodec/options.c
+./libavcodec/options_table.h
+./libavcodec/parser.c
+./libavcodec/pixblockdsp.h
+./libavcodec/pthread_frame.c
+./libavcodec/pthread_slice.c
+./libavcodec/put_bits.h
+./libavcodec/ratecontrol.h
+./libavcodec/raw.c
+./libavcodec/thread.h
+./libavcodec/utils.c
+./libavcodec/version.h
+./libavcodec/videodsp.c
+./libavcodec/videodsp.h
+./libavcodec/vlc.h
+./libavcodec/vorbis_parser.h
+./libavcodec/vp3dsp.h
+./libavcodec/vp56.h
+./libavcodec/vp56dsp.h
+./libavcodec/vp56rac.c
+./libavcodec/vp8.c
+./libavcodec/vp8.h
+./libavcodec/vp8_parser.c
+./libavcodec/vp8dsp.c
+./libavcodec/vp8dsp.h
+./libavcodec/vp9.c
+./libavcodec/vp9.h
+./libavcodec/vp9_mc_template.c
+./libavcodec/vp9data.h
+./libavcodec/vp9dsp.c
+./libavcodec/vp9dsp.h
+./libavcodec/vp9dsp_template.c
+./libavcodec/bitstream_filters.c
+./libavcodec/bitstream_filter.c
+./libavcodec/bsf_list.c
+./libavcodec/null_bsf.c
+./libavutil/adler32.c
+./libavutil/atomic.c
+./libavutil/atomic.h
+./libavutil/atomic_win32.h
+./libavutil/avutilres.rc
+./libavutil/base64.c
+./libavutil/base64.h
+./libavutil/bprint.c
+./libavutil/bprint.h
+./libavutil/bswap.h
+./libavutil/color_utils.c
+./libavutil/color_utils.h
+./libavutil/colorspace.h
+./libavutil/common.h
+./libavutil/crc.c
+./libavutil/dict.h
+./libavutil/error.c
+./libavutil/error.h
+./libavutil/eval.h
+./libavutil/ffmath.h
+./libavutil/ffversion.h
+./libavutil/fifo.c
+./libavutil/fifo.h
+./libavutil/fixed_dsp.c
+./libavutil/fixed_dsp.h
+./libavutil/integer.c
+./libavutil/integer.h
+./libavutil/intfloat.h
+./libavutil/intmath.c
+./libavutil/intmath.h
+./libavutil/libm.h
+./libavutil/lls.c
+./libavutil/lls.h
+./libavutil/log2_tab.c
+./libavutil/macros.h
+./libavutil/mem_internal.h
+./libavutil/parseutils.h
+./libavutil/pixelutils.c
+./libavutil/pixelutils.h
+./libavutil/qsort.h
+./libavutil/rational.c
+./libavutil/replaygain.h
+./libavutil/reverse.c
+./libavutil/threadmessage.h
+./libavutil/time_internal.h
+./libavutil/x86/bswap.h
+./libavutil/x86/cpuid.asm
+./libavutil/x86/fixed_dsp.asm
+./libavutil/x86/fixed_dsp_init.c
+./libavutil/x86/intmath.h
+./libavutil/x86/intreadwrite.h
+./libavutil/x86/lls.asm
+./libavutil/x86/lls_init.c
+./libavutil/x86/pixelutils.asm
+./libavutil/x86/pixelutils.h
+./libavutil/x86/pixelutils_init.c
+./libavutil/x86/timer.h
+./libavutil/x86/asm.h
+./libavutil/x86/imgutils.asm
+./libavutil/x86/imgutils_init.c
+./libavutil/x86/cpu.c
+./libavutil/x86/cpu.h
+./libavutil/x86/emms.asm
+./libavutil/x86/emms.h
+./libavutil/x86/float_dsp.asm
+./libavutil/x86/float_dsp_init.c
+./libavutil/x86/x86inc.asm
+./libavutil/x86/x86util.asm
+./libavutil/adler32.h
+./libavutil/avassert.h
+./libavutil/avconfig.h
+./libavutil/crc.h
+./libavutil/dict.c
+./libavutil/dynarray.h
+./libavutil/log.h
+./libavutil/mathematics.h
+./libavutil/rational.h
+./libavutil/samplefmt.c
+./libavutil/samplefmt.h
+./libavutil/timestamp.h
+./libavutil/opt.c
+./libavutil/imgutils_internal.h
+./libavutil/reverse.h
+./libavutil/slicethread.c
+./libavutil/slicethread.h
+./libavutil/atomic_gcc.h
+./libavutil/attributes.h
+./libavutil/avstring.c
+./libavutil/avstring.h
+./libavutil/avutil.h
+./libavutil/buffer.c
+./libavutil/buffer.h
+./libavutil/buffer_internal.h
+./libavutil/channel_layout.c
+./libavutil/channel_layout.h
+./libavutil/cpu.c
+./libavutil/cpu.h
+./libavutil/cpu_internal.h
+./libavutil/eval.c
+./libavutil/float_dsp.c
+./libavutil/float_dsp.h
+./libavutil/frame.c
+./libavutil/frame.h
+./libavutil/hwcontext.h
+./libavutil/imgutils.c
+./libavutil/imgutils.h
+./libavutil/internal.h
+./libavutil/intreadwrite.h
+./libavutil/log.c
+./libavutil/mathematics.c
+./libavutil/mem.c
+./libavutil/mem.h
+./libavutil/opt.h
+./libavutil/parseutils.c
+./libavutil/pixdesc.c
+./libavutil/pixdesc.h
+./libavutil/pixfmt.h
+./libavutil/thread.h
+./libavutil/threadmessage.c
+./libavutil/time.c
+./libavutil/timecode.c
+./libavutil/timecode.h
+./libavutil/timer.h
+./libavutil/utils.c
+./libavutil/version.h
+
diff --git a/media/ffvpx/INSTALL.md b/media/ffvpx/INSTALL.md
deleted file mode 100644
index 5db912231..000000000
--- a/media/ffvpx/INSTALL.md
+++ /dev/null
@@ -1,17 +0,0 @@
-#Installing FFmpeg:
-
-1. Type `./configure` to create the configuration. A list of configure
-options is printed by running `configure --help`.
-
- `configure` can be launched from a directory different from the FFmpeg
-sources to build the objects out of tree. To do this, use an absolute
-path when launching `configure`, e.g. `/ffmpegdir/ffmpeg/configure`.
-
-2. Then type `make` to build FFmpeg. GNU Make 3.81 or later is required.
-
-3. Type `make install` to install all binaries and libraries you built.
-
-NOTICE
-------
-
- - Non system dependencies (e.g. libx264, libvpx) are disabled by default.
diff --git a/media/ffvpx/LICENSE.md b/media/ffvpx/LICENSE.md
deleted file mode 100644
index 0c53d0f5a..000000000
--- a/media/ffvpx/LICENSE.md
+++ /dev/null
@@ -1,114 +0,0 @@
-#FFmpeg:
-
-Most files in FFmpeg are under the GNU Lesser General Public License version 2.1
-or later (LGPL v2.1+). Read the file `COPYING.LGPLv2.1` for details. Some other
-files have MIT/X11/BSD-style licenses. In combination the LGPL v2.1+ applies to
-FFmpeg.
-
-Some optional parts of FFmpeg are licensed under the GNU General Public License
-version 2 or later (GPL v2+). See the file `COPYING.GPLv2` for details. None of
-these parts are used by default, you have to explicitly pass `--enable-gpl` to
-configure to activate them. In this case, FFmpeg's license changes to GPL v2+.
-
-Specifically, the GPL parts of FFmpeg are:
-
-- libpostproc
-- optional x86 optimizations in the files
- - `libavcodec/x86/flac_dsp_gpl.asm`
- - `libavcodec/x86/idct_mmx.c`
- - `libavfilter/x86/vf_removegrain.asm`
-- libutvideo encoding/decoding wrappers in
- `libavcodec/libutvideo*.cpp`
-- the X11 grabber in `libavdevice/x11grab.c`
-- the swresample test app in
- `libswresample/swresample-test.c`
-- the `texi2pod.pl` tool
-- the following filters in libavfilter:
- - `f_ebur128.c`
- - `vf_blackframe.c`
- - `vf_boxblur.c`
- - `vf_colormatrix.c`
- - `vf_cover_rect.c`
- - `vf_cropdetect.c`
- - `vf_delogo.c`
- - `vf_eq.c`
- - `vf_find_rect.c`
- - `vf_fspp.c`
- - `vf_geq.c`
- - `vf_histeq.c`
- - `vf_hqdn3d.c`
- - `vf_interlace.c`
- - `vf_kerndeint.c`
- - `vf_mcdeint.c`
- - `vf_mpdecimate.c`
- - `vf_owdenoise.c`
- - `vf_perspective.c`
- - `vf_phase.c`
- - `vf_pp.c`
- - `vf_pp7.c`
- - `vf_pullup.c`
- - `vf_sab.c`
- - `vf_smartblur.c`
- - `vf_repeatfields.c`
- - `vf_spp.c`
- - `vf_stereo3d.c`
- - `vf_super2xsai.c`
- - `vf_tinterlace.c`
- - `vf_uspp.c`
- - `vsrc_mptestsrc.c`
-
-Should you, for whatever reason, prefer to use version 3 of the (L)GPL, then
-the configure parameter `--enable-version3` will activate this licensing option
-for you. Read the file `COPYING.LGPLv3` or, if you have enabled GPL parts,
-`COPYING.GPLv3` to learn the exact legal terms that apply in this case.
-
-There are a handful of files under other licensing terms, namely:
-
-* The files `libavcodec/jfdctfst.c`, `libavcodec/jfdctint_template.c` and
- `libavcodec/jrevdct.c` are taken from libjpeg, see the top of the files for
- licensing details. Specifically note that you must credit the IJG in the
- documentation accompanying your program if you only distribute executables.
- You must also indicate any changes including additions and deletions to
- those three files in the documentation.
-* `tests/reference.pnm` is under the expat license.
-
-
-external libraries
-==================
-
-FFmpeg can be combined with a number of external libraries, which sometimes
-affect the licensing of binaries resulting from the combination.
-
-compatible libraries
---------------------
-
-The following libraries are under GPL:
-- frei0r
-- libcdio
-- librubberband
-- libutvideo
-- libvidstab
-- libx264
-- libx265
-- libxavs
-- libxvid
-
-When combining them with FFmpeg, FFmpeg needs to be licensed as GPL as well by
-passing `--enable-gpl` to configure.
-
-The OpenCORE and VisualOn libraries are under the Apache License 2.0. That
-license is incompatible with the LGPL v2.1 and the GPL v2, but not with
-version 3 of those licenses. So to combine these libraries with FFmpeg, the
-license version needs to be upgraded by passing `--enable-version3` to configure.
-
-incompatible libraries
-----------------------
-
-The Fraunhofer AAC library and FAAC are under licenses which
-are incompatible with the GPLv2 and v3. We do not know for certain if their
-licenses are compatible with the LGPL.
-If you wish to enable these libraries, pass `--enable-nonfree` to configure.
-But note that if you enable any of these libraries the resulting binary will
-be under a complex license mix that is more restrictive than the LGPL and that
-may result in additional obligations. It is possible that these
-restrictions cause the resulting binary to be unredistributeable.
diff --git a/media/ffvpx/MAINTAINERS b/media/ffvpx/MAINTAINERS
deleted file mode 100644
index e57150da9..000000000
--- a/media/ffvpx/MAINTAINERS
+++ /dev/null
@@ -1,619 +0,0 @@
-FFmpeg maintainers
-==================
-
-Below is a list of the people maintaining different parts of the
-FFmpeg code.
-
-Please try to keep entries where you are the maintainer up to date!
-
-Names in () mean that the maintainer currently has no time to maintain the code.
-A (CC <address>) after the name means that the maintainer prefers to be CC-ed on
-patches and related discussions.
-
-
-Project Leader
-==============
-
- final design decisions
-
-
-Applications
-============
-
-ffmpeg:
- ffmpeg.c Michael Niedermayer
-
-ffplay:
- ffplay.c Marton Balint
-
-ffprobe:
- ffprobe.c Stefano Sabatini
-
-ffserver:
- ffserver.c Reynaldo H. Verdejo Pinochet
-
-Commandline utility code:
- cmdutils.c, cmdutils.h Michael Niedermayer
-
-QuickTime faststart:
- tools/qt-faststart.c Baptiste Coudurier
-
-
-Miscellaneous Areas
-===================
-
-documentation Stefano Sabatini, Mike Melanson, Timothy Gu, Lou Logan
-build system (configure, makefiles) Diego Biurrun, Mans Rullgard
-project server Árpád Gereöffy, Michael Niedermayer, Reimar Doeffinger, Alexander Strasser, Lou Logan
-presets Robert Swain
-metadata subsystem Aurelien Jacobs
-release management Michael Niedermayer
-
-
-Communication
-=============
-
-website Deby Barbara Lepage
-fate.ffmpeg.org Timothy Gu
-Trac bug tracker Alexander Strasser, Michael Niedermayer, Carl Eugen Hoyos, Lou Logan
-mailing lists Michael Niedermayer, Baptiste Coudurier, Lou Logan
-Google+ Paul B Mahol, Michael Niedermayer, Alexander Strasser
-Twitter Lou Logan, Reynaldo H. Verdejo Pinochet
-Launchpad Timothy Gu
-
-
-libavutil
-=========
-
-External Interfaces:
- libavutil/avutil.h Michael Niedermayer
-Internal Interfaces:
- libavutil/common.h Michael Niedermayer
-
-Other:
- aes_ctr.c, aes_ctr.h Eran Kornblau
- bprint Nicolas George
- bswap.h
- des Reimar Doeffinger
- dynarray.h Nicolas George
- eval.c, eval.h Michael Niedermayer
- float_dsp Loren Merritt
- hash Reimar Doeffinger
- intfloat* Michael Niedermayer
- integer.c, integer.h Michael Niedermayer
- lzo Reimar Doeffinger
- mathematics.c, mathematics.h Michael Niedermayer
- mem.c, mem.h Michael Niedermayer
- opencl.c, opencl.h Wei Gao
- opt.c, opt.h Michael Niedermayer
- rational.c, rational.h Michael Niedermayer
- rc4 Reimar Doeffinger
- ripemd.c, ripemd.h James Almer
- timecode Clément Bœsch
-
-
-libavcodec
-==========
-
-Generic Parts:
- External Interfaces:
- avcodec.h Michael Niedermayer
- utility code:
- utils.c Michael Niedermayer
- audio and video frame extraction:
- parser.c Michael Niedermayer
- bitstream reading:
- bitstream.c, bitstream.h Michael Niedermayer
- CABAC:
- cabac.h, cabac.c Michael Niedermayer
- codec names:
- codec_names.sh Nicolas George
- DSP utilities:
- dsputils.c, dsputils.h Michael Niedermayer
- entropy coding:
- rangecoder.c, rangecoder.h Michael Niedermayer
- lzw.* Michael Niedermayer
- floating point AAN DCT:
- faandct.c, faandct.h Michael Niedermayer
- Golomb coding:
- golomb.c, golomb.h Michael Niedermayer
- LPC:
- lpc.c, lpc.h Justin Ruggles
- motion estimation:
- motion* Michael Niedermayer
- rate control:
- ratecontrol.c Michael Niedermayer
- libxvid_rc.c Michael Niedermayer
- simple IDCT:
- simple_idct.c, simple_idct.h Michael Niedermayer
- postprocessing:
- libpostproc/* Michael Niedermayer
- table generation:
- tableprint.c, tableprint.h Reimar Doeffinger
- fixed point FFT:
- fft* Zeljko Lukac
- Text Subtitles Clément Bœsch
-
-Codecs:
- 4xm.c Michael Niedermayer
- 8bps.c Roberto Togni
- 8svx.c Jaikrishnan Menon
- aacenc*, aaccoder.c Rostislav Pehlivanov
- aasc.c Kostya Shishkov
- ac3* Justin Ruggles
- alacenc.c Jaikrishnan Menon
- alsdec.c Thilo Borgmann
- apedec.c Kostya Shishkov
- ass* Aurelien Jacobs
- asv* Michael Niedermayer
- atrac3* Benjamin Larsson
- atrac3plus* Maxim Poliakovski
- bgmc.c, bgmc.h Thilo Borgmann
- bink.c Kostya Shishkov
- binkaudio.c Peter Ross
- bmp.c Mans Rullgard, Kostya Shishkov
- cavs* Stefan Gehrer
- cdxl.c Paul B Mahol
- celp_filters.* Vitor Sessak
- cinepak.c Roberto Togni
- cinepakenc.c Rl / Aetey G.T. AB
- ccaption_dec.c Anshul Maheshwari
- cljr Alex Beregszaszi
- cllc.c Derek Buitenhuis
- cook.c, cookdata.h Benjamin Larsson
- cpia.c Stephan Hilb
- crystalhd.c Philip Langdale
- cscd.c Reimar Doeffinger
- dca.c Kostya Shishkov, Benjamin Larsson
- dirac* Rostislav Pehlivanov
- dnxhd* Baptiste Coudurier
- dpcm.c Mike Melanson
- dss_sp.c Oleksij Rempel, Michael Niedermayer
- dv.c Roman Shaposhnik
- dvbsubdec.c Anshul Maheshwari
- dxa.c Kostya Shishkov
- eacmv*, eaidct*, eat* Peter Ross
- evrc* Paul B Mahol
- exif.c, exif.h Thilo Borgmann
- ffv1* Michael Niedermayer
- ffwavesynth.c Nicolas George
- fic.c Derek Buitenhuis
- flac* Justin Ruggles
- flashsv* Benjamin Larsson
- flicvideo.c Mike Melanson
- g722.c Martin Storsjo
- g726.c Roman Shaposhnik
- gifdec.c Baptiste Coudurier
- h261* Michael Niedermayer
- h263* Michael Niedermayer
- h264* Loren Merritt, Michael Niedermayer
- hap* Tom Butterworth
- huffyuv* Michael Niedermayer, Christophe Gisquet
- idcinvideo.c Mike Melanson
- imc* Benjamin Larsson
- indeo2* Kostya Shishkov
- indeo5* Kostya Shishkov
- interplayvideo.c Mike Melanson
- ivi* Kostya Shishkov
- jacosub* Clément Bœsch
- jpeg2000* Nicolas Bertrand
- jpeg_ls.c Kostya Shishkov
- jvdec.c Peter Ross
- kmvc.c Kostya Shishkov
- lcl*.c Roberto Togni, Reimar Doeffinger
- libcelt_dec.c Nicolas George
- libdirac* David Conrad
- libgsm.c Michel Bardiaux
- libkvazaar.c Arttu Ylä-Outinen
- libopenjpeg.c Jaikrishnan Menon
- libopenjpegenc.c Michael Bradshaw
- libschroedinger* David Conrad
- libspeexdec.c Justin Ruggles
- libtheoraenc.c David Conrad
- libutvideo* Carl Eugen Hoyos
- libvorbis.c David Conrad
- libvpx* James Zern
- libx264.c Mans Rullgard, Jason Garrett-Glaser
- libx265.c Derek Buitenhuis
- libxavs.c Stefan Gehrer
- libzvbi-teletextdec.c Marton Balint
- loco.c Kostya Shishkov
- lzo.h, lzo.c Reimar Doeffinger
- mdec.c Michael Niedermayer
- mimic.c Ramiro Polla
- mjpeg*.c Michael Niedermayer
- mlp* Ramiro Polla
- mmvideo.c Peter Ross
- mpc* Kostya Shishkov
- mpeg12.c, mpeg12data.h Michael Niedermayer
- mpegvideo.c, mpegvideo.h Michael Niedermayer
- mqc* Nicolas Bertrand
- msmpeg4.c, msmpeg4data.h Michael Niedermayer
- msrle.c Mike Melanson
- msvideo1.c Mike Melanson
- nellymoserdec.c Benjamin Larsson
- nuv.c Reimar Doeffinger
- nvenc.c Timo Rothenpieler
- paf.* Paul B Mahol
- pcx.c Ivo van Poorten
- pgssubdec.c Reimar Doeffinger
- ptx.c Ivo van Poorten
- qcelp* Reynaldo H. Verdejo Pinochet
- qdm2.c, qdm2data.h Roberto Togni, Benjamin Larsson
- qdrw.c Kostya Shishkov
- qpeg.c Kostya Shishkov
- qsv* Ivan Uskov
- qtrle.c Mike Melanson
- ra144.c, ra144.h, ra288.c, ra288.h Roberto Togni
- resample2.c Michael Niedermayer
- rl2.c Sascha Sommer
- rpza.c Roberto Togni
- rtjpeg.c, rtjpeg.h Reimar Doeffinger
- rv10.c Michael Niedermayer
- rv3* Kostya Shishkov
- rv4* Kostya Shishkov, Christophe Gisquet
- s3tc* Ivo van Poorten
- smacker.c Kostya Shishkov
- smc.c Mike Melanson
- smvjpegdec.c Ash Hughes
- snow* Michael Niedermayer, Loren Merritt
- sonic.c Alex Beregszaszi
- srt* Aurelien Jacobs
- sunrast.c Ivo van Poorten
- svq3.c Michael Niedermayer
- tak* Paul B Mahol
- targa.c Kostya Shishkov
- tiff.c Kostya Shishkov
- truemotion1* Mike Melanson
- truemotion2* Kostya Shishkov
- truespeech.c Kostya Shishkov
- tscc.c Kostya Shishkov
- tta.c Alex Beregszaszi, Jaikrishnan Menon
- ttaenc.c Paul B Mahol
- txd.c Ivo van Poorten
- ulti* Kostya Shishkov
- v410*.c Derek Buitenhuis
- vb.c Kostya Shishkov
- vble.c Derek Buitenhuis
- vc1* Kostya Shishkov, Christophe Gisquet
- vc2* Rostislav Pehlivanov
- vcr1.c Michael Niedermayer
- vda_h264_dec.c Xidorn Quan
- vima.c Paul B Mahol
- vmnc.c Kostya Shishkov
- vorbisdec.c Denes Balatoni, David Conrad
- vorbisenc.c Oded Shimon
- vp3* Mike Melanson
- vp5 Aurelien Jacobs
- vp6 Aurelien Jacobs
- vp8 David Conrad, Jason Garrett-Glaser, Ronald Bultje
- vp9 Ronald Bultje, Clément Bœsch
- vqavideo.c Mike Melanson
- wavpack.c Kostya Shishkov
- wmaprodec.c Sascha Sommer
- wmavoice.c Ronald S. Bultje
- wmv2.c Michael Niedermayer
- wnv1.c Kostya Shishkov
- xan.c Mike Melanson
- xbm* Paul B Mahol
- xface Stefano Sabatini
- xl.c Kostya Shishkov
- xvmc.c Ivan Kalvachev
- xwd* Paul B Mahol
- zerocodec.c Derek Buitenhuis
- zmbv* Kostya Shishkov
-
-Hardware acceleration:
- crystalhd.c Philip Langdale
- dxva2* Hendrik Leppkes, Laurent Aimar
- vaapi* Gwenole Beauchesne
- vda* Sebastien Zwickert
- vdpau* Philip Langdale, Carl Eugen Hoyos
- videotoolbox* Sebastien Zwickert
-
-
-libavdevice
-===========
- External Interface:
- libavdevice/avdevice.h
-
-
- avfoundation.m Thilo Borgmann
- decklink* Deti Fliegl
- dshow.c Roger Pack (CC rogerdpack@gmail.com)
- fbdev_enc.c Lukasz Marek
- gdigrab.c Roger Pack (CC rogerdpack@gmail.com)
- iec61883.c Georg Lippitsch
- lavfi Stefano Sabatini
- libdc1394.c Roman Shaposhnik
- opengl_enc.c Lukasz Marek
- pulse_audio_enc.c Lukasz Marek
- qtkit.m Thilo Borgmann
- sdl Stefano Sabatini
- v4l2.c Giorgio Vazzana
- vfwcap.c Ramiro Polla
- xv.c Lukasz Marek
-
-libavfilter
-===========
-
-Generic parts:
- graphdump.c Nicolas George
-
-Filters:
- f_drawgraph.c Paul B Mahol
- af_adelay.c Paul B Mahol
- af_aecho.c Paul B Mahol
- af_afade.c Paul B Mahol
- af_amerge.c Nicolas George
- af_aphaser.c Paul B Mahol
- af_aresample.c Michael Niedermayer
- af_astats.c Paul B Mahol
- af_atempo.c Pavel Koshevoy
- af_biquads.c Paul B Mahol
- af_chorus.c Paul B Mahol
- af_compand.c Paul B Mahol
- af_ladspa.c Paul B Mahol
- af_pan.c Nicolas George
- af_sidechaincompress.c Paul B Mahol
- af_silenceremove.c Paul B Mahol
- avf_aphasemeter.c Paul B Mahol
- avf_avectorscope.c Paul B Mahol
- avf_showcqt.c Muhammad Faiz
- vf_blend.c Paul B Mahol
- vf_chromakey.c Timo Rothenpieler
- vf_colorchannelmixer.c Paul B Mahol
- vf_colorbalance.c Paul B Mahol
- vf_colorkey.c Timo Rothenpieler
- vf_colorlevels.c Paul B Mahol
- vf_deband.c Paul B Mahol
- vf_dejudder.c Nicholas Robbins
- vf_delogo.c Jean Delvare (CC <jdelvare@suse.com>)
- vf_drawbox.c/drawgrid Andrey Utkin
- vf_extractplanes.c Paul B Mahol
- vf_histogram.c Paul B Mahol
- vf_hqx.c Clément Bœsch
- vf_idet.c Pascal Massimino
- vf_il.c Paul B Mahol
- vf_lenscorrection.c Daniel Oberhoff
- vf_mergeplanes.c Paul B Mahol
- vf_neighbor.c Paul B Mahol
- vf_psnr.c Paul B Mahol
- vf_random.c Paul B Mahol
- vf_scale.c Michael Niedermayer
- vf_separatefields.c Paul B Mahol
- vf_ssim.c Paul B Mahol
- vf_stereo3d.c Paul B Mahol
- vf_telecine.c Paul B Mahol
- vf_yadif.c Michael Niedermayer
- vf_zoompan.c Paul B Mahol
-
-Sources:
- vsrc_mandelbrot.c Michael Niedermayer
-
-libavformat
-===========
-
-Generic parts:
- External Interface:
- libavformat/avformat.h Michael Niedermayer
- Utility Code:
- libavformat/utils.c Michael Niedermayer
-
-
-Muxers/Demuxers:
- 4xm.c Mike Melanson
- aadec.c Vesselin Bontchev (vesselin.bontchev at yandex dot com)
- adtsenc.c Robert Swain
- afc.c Paul B Mahol
- aiffdec.c Baptiste Coudurier, Matthieu Bouron
- aiffenc.c Baptiste Coudurier, Matthieu Bouron
- ape.c Kostya Shishkov
- apngdec.c Benoit Fouet
- ass* Aurelien Jacobs
- astdec.c Paul B Mahol
- astenc.c James Almer
- avi* Michael Niedermayer
- avisynth.c AvxSynth Team (avxsynth.testing at gmail dot com)
- avr.c Paul B Mahol
- bink.c Peter Ross
- brstm.c Paul B Mahol
- caf* Peter Ross
- cdxl.c Paul B Mahol
- crc.c Michael Niedermayer
- daud.c Reimar Doeffinger
- dss.c Oleksij Rempel, Michael Niedermayer
- dtshddec.c Paul B Mahol
- dv.c Roman Shaposhnik
- dxa.c Kostya Shishkov
- electronicarts.c Peter Ross
- epafdec.c Paul B Mahol
- ffm* Baptiste Coudurier
- flac* Justin Ruggles
- flic.c Mike Melanson
- flvdec.c, flvenc.c Michael Niedermayer
- gxf.c Reimar Doeffinger
- gxfenc.c Baptiste Coudurier
- hls.c Anssi Hannula
- hls encryption (hlsenc.c) Christian Suloway
- idcin.c Mike Melanson
- idroqdec.c Mike Melanson
- iff.c Jaikrishnan Menon
- img2*.c Michael Niedermayer
- ipmovie.c Mike Melanson
- ircam* Paul B Mahol
- iss.c Stefan Gehrer
- jacosub* Clément Bœsch
- jvdec.c Peter Ross
- libmodplug.c Clément Bœsch
- libnut.c Oded Shimon
- lmlm4.c Ivo van Poorten
- lvfdec.c Paul B Mahol
- lxfdec.c Tomas Härdin
- matroska.c Aurelien Jacobs
- matroskadec.c Aurelien Jacobs
- matroskaenc.c David Conrad
- matroska subtitles (matroskaenc.c) John Peebles
- metadata* Aurelien Jacobs
- mgsts.c Paul B Mahol
- microdvd* Aurelien Jacobs
- mm.c Peter Ross
- mov.c Michael Niedermayer, Baptiste Coudurier
- movenc.c Baptiste Coudurier, Matthieu Bouron
- movenccenc.c Eran Kornblau
- mpc.c Kostya Shishkov
- mpeg.c Michael Niedermayer
- mpegenc.c Michael Niedermayer
- mpegts.c Marton Balint
- mpegtsenc.c Baptiste Coudurier
- msnwc_tcp.c Ramiro Polla
- mtv.c Reynaldo H. Verdejo Pinochet
- mxf* Baptiste Coudurier
- mxfdec.c Tomas Härdin
- nistspheredec.c Paul B Mahol
- nsvdec.c Francois Revol
- nut* Michael Niedermayer
- nuv.c Reimar Doeffinger
- oggdec.c, oggdec.h David Conrad
- oggenc.c Baptiste Coudurier
- oggparse*.c David Conrad
- oggparsedaala* Rostislav Pehlivanov
- oma.c Maxim Poliakovski
- paf.c Paul B Mahol
- psxstr.c Mike Melanson
- pva.c Ivo van Poorten
- pvfdec.c Paul B Mahol
- r3d.c Baptiste Coudurier
- raw.c Michael Niedermayer
- rdt.c Ronald S. Bultje
- rl2.c Sascha Sommer
- rmdec.c, rmenc.c Ronald S. Bultje, Kostya Shishkov
- rtmp* Kostya Shishkov
- rtp.c, rtpenc.c Martin Storsjo
- rtpdec_ac3.* Gilles Chanteperdrix
- rtpdec_dv.* Thomas Volkert
- rtpdec_h261.*, rtpenc_h261.* Thomas Volkert
- rtpdec_hevc.*, rtpenc_hevc.* Thomas Volkert
- rtpdec_mpa_robust.* Gilles Chanteperdrix
- rtpdec_asf.* Ronald S. Bultje
- rtpdec_vp9.c Thomas Volkert
- rtpenc_mpv.*, rtpenc_aac.* Martin Storsjo
- rtsp.c Luca Barbato
- sbgdec.c Nicolas George
- sdp.c Martin Storsjo
- segafilm.c Mike Melanson
- segment.c Stefano Sabatini
- siff.c Kostya Shishkov
- smacker.c Kostya Shishkov
- smjpeg* Paul B Mahol
- spdif* Anssi Hannula
- srtdec.c Aurelien Jacobs
- swf.c Baptiste Coudurier
- takdec.c Paul B Mahol
- tta.c Alex Beregszaszi
- txd.c Ivo van Poorten
- voc.c Aurelien Jacobs
- wav.c Michael Niedermayer
- wc3movie.c Mike Melanson
- webm dash (matroskaenc.c) Vignesh Venkatasubramanian
- webvtt* Matthew J Heaney
- westwood.c Mike Melanson
- wtv.c Peter Ross
- wv.c Kostya Shishkov
- wvenc.c Paul B Mahol
-
-Protocols:
- async.c Zhang Rui
- bluray.c Petri Hintukainen
- ftp.c Lukasz Marek
- http.c Ronald S. Bultje
- libssh.c Lukasz Marek
- mms*.c Ronald S. Bultje
- udp.c Luca Abeni
- icecast.c Marvin Scholz
-
-
-libswresample
-=============
-
-Generic parts:
- audioconvert.c Michael Niedermayer
- dither.c Michael Niedermayer
- rematrix*.c Michael Niedermayer
- swresample*.c Michael Niedermayer
-
-Resamplers:
- resample*.c Michael Niedermayer
- soxr_resample.c Rob Sykes
-
-
-Operating systems / CPU architectures
-=====================================
-
-Alpha Mans Rullgard, Falk Hueffner
-ARM Mans Rullgard
-AVR32 Mans Rullgard
-MIPS Mans Rullgard, Nedeljko Babic
-Mac OS X / PowerPC Romain Dolbeau, Guillaume Poirier
-Amiga / PowerPC Colin Ward
-Linux / PowerPC Luca Barbato
-Windows MinGW Alex Beregszaszi, Ramiro Polla
-Windows Cygwin Victor Paesa
-Windows MSVC Matthew Oliver, Hendrik Leppkes
-Windows ICL Matthew Oliver
-ADI/Blackfin DSP Marc Hoffman
-Sparc Roman Shaposhnik
-x86 Michael Niedermayer
-
-
-Releases
-========
-
-2.8 Michael Niedermayer
-2.7 Michael Niedermayer
-2.6 Michael Niedermayer
-2.5 Michael Niedermayer
-2.4 Michael Niedermayer
-
-If you want to maintain an older release, please contact us
-
-
-GnuPG Fingerprints of maintainers and contributors
-==================================================
-
-Alexander Strasser 1C96 78B7 83CB 8AA7 9AF5 D1EB A7D8 A57B A876 E58F
-Anssi Hannula 1A92 FF42 2DD9 8D2E 8AF7 65A9 4278 C520 513D F3CB
-Anton Khirnov 6D0C 6625 56F8 65D1 E5F5 814B B50A 1241 C067 07AB
-Ash Hughes 694D 43D2 D180 C7C7 6421 ABD3 A641 D0B7 623D 6029
-Attila Kinali 11F0 F9A6 A1D2 11F6 C745 D10C 6520 BCDD F2DF E765
-Baptiste Coudurier 8D77 134D 20CC 9220 201F C5DB 0AC9 325C 5C1A BAAA
-Ben Littler 3EE3 3723 E560 3214 A8CD 4DEB 2CDB FCE7 768C 8D2C
-Benoit Fouet B22A 4F4F 43EF 636B BB66 FCDC 0023 AE1E 2985 49C8
-Clément Bœsch 52D0 3A82 D445 F194 DB8B 2B16 87EE 2CB8 F4B8 FCF9
-Daniel Verkamp 78A6 07ED 782C 653E C628 B8B9 F0EB 8DD8 2F0E 21C7
-Diego Biurrun 8227 1E31 B6D9 4994 7427 E220 9CAE D6CC 4757 FCC5
-FFmpeg release signing key FCF9 86EA 15E6 E293 A564 4F10 B432 2F04 D676 58D8
-Ganesh Ajjanagadde C96A 848E 97C3 CEA2 AB72 5CE4 45F9 6A2D 3C36 FB1B
-Gwenole Beauchesne 2E63 B3A6 3E44 37E2 017D 2704 53C7 6266 B153 99C4
-Jaikrishnan Menon 61A1 F09F 01C9 2D45 78E1 C862 25DC 8831 AF70 D368
-Jean Delvare 7CA6 9F44 60F1 BDC4 1FD2 C858 A552 6B9B B3CD 4E6A
-Justin Ruggles 3136 ECC0 C10D 6C04 5F43 CA29 FCBE CD2A 3787 1EBF
-Loren Merritt ABD9 08F4 C920 3F65 D8BE 35D7 1540 DAA7 060F 56DE
-Lou Logan 7D68 DC73 CBEF EABB 671A B6CF 621C 2E28 82F8 DC3A
-Luca Barbato 6677 4209 213C 8843 5B67 29E7 E84C 78C2 84E9 0E34
-Michael Niedermayer 9FF2 128B 147E F673 0BAD F133 611E C787 040B 0FAB
-Nicolas George 24CE 01CE 9ACC 5CEB 74D8 8D9D B063 D997 36E5 4C93
-Panagiotis Issaris 6571 13A3 33D9 3726 F728 AA98 F643 B12E ECF3 E029
-Peter Ross A907 E02F A6E5 0CD2 34CD 20D2 6760 79C5 AC40 DD6B
-Philip Langdale 5DC5 8D66 5FBA 3A43 18EC 045E F8D6 B194 6A75 682E
-Reimar Doeffinger C61D 16E5 9E2C D10C 8958 38A4 0899 A2B9 06D4 D9C7
-Reinhard Tartler 9300 5DC2 7E87 6C37 ED7B CA9A 9808 3544 9453 48A4
-Reynaldo H. Verdejo Pinochet 6E27 CD34 170C C78E 4D4F 5F40 C18E 077F 3114 452A
-Robert Swain EE7A 56EA 4A81 A7B5 2001 A521 67FA 362D A2FC 3E71
-Sascha Sommer 38A0 F88B 868E 9D3A 97D4 D6A0 E823 706F 1E07 0D3C
-Stefano Sabatini 0D0B AD6B 5330 BBAD D3D6 6A0C 719C 2839 FC43 2D5F
-Stephan Hilb 4F38 0B3A 5F39 B99B F505 E562 8D5C 5554 4E17 8863
-Tiancheng "Timothy" Gu 9456 AFC0 814A 8139 E994 8351 7FE6 B095 B582 B0D4
-Tim Nicholson 38CF DB09 3ED0 F607 8B67 6CED 0C0B FC44 8B0B FC83
-Tomas Härdin A79D 4E3D F38F 763F 91F5 8B33 A01E 8AE0 41BB 2551
-Wei Gao 4269 7741 857A 0E60 9EC5 08D2 4744 4EFA 62C1 87B9
diff --git a/media/ffvpx/README.md b/media/ffvpx/README.md
deleted file mode 100644
index 241919193..000000000
--- a/media/ffvpx/README.md
+++ /dev/null
@@ -1,49 +0,0 @@
-FFmpeg README
-=============
-
-FFmpeg is a collection of libraries and tools to process multimedia content
-such as audio, video, subtitles and related metadata.
-
-## Libraries
-
-* `libavcodec` provides implementation of a wider range of codecs.
-* `libavformat` implements streaming protocols, container formats and basic I/O access.
-* `libavutil` includes hashers, decompressors and miscellaneous utility functions.
-* `libavfilter` provides a mean to alter decoded Audio and Video through chain of filters.
-* `libavdevice` provides an abstraction to access capture and playback devices.
-* `libswresample` implements audio mixing and resampling routines.
-* `libswscale` implements color conversion and scaling routines.
-
-## Tools
-
-* [ffmpeg](https://ffmpeg.org/ffmpeg.html) is a command line toolbox to
- manipulate, convert and stream multimedia content.
-* [ffplay](https://ffmpeg.org/ffplay.html) is a minimalistic multimedia player.
-* [ffprobe](https://ffmpeg.org/ffprobe.html) is a simple analysis tool to inspect
- multimedia content.
-* [ffserver](https://ffmpeg.org/ffserver.html) is a multimedia streaming server
- for live broadcasts.
-* Additional small tools such as `aviocat`, `ismindex` and `qt-faststart`.
-
-## Documentation
-
-The offline documentation is available in the **doc/** directory.
-
-The online documentation is available in the main [website](https://ffmpeg.org)
-and in the [wiki](https://trac.ffmpeg.org).
-
-### Examples
-
-Coding examples are available in the **doc/examples** directory.
-
-## License
-
-FFmpeg codebase is mainly LGPL-licensed with optional components licensed under
-GPL. Please refer to the LICENSE file for detailed information.
-
-## Contributing
-
-Patches should be submitted to the ffmpeg-devel mailing list using
-`git format-patch` or `git send-email`. Github pull requests should be
-avoided because they are not part of our review process. Few developers
-follow pull requests so they will likely be ignored.
diff --git a/media/ffvpx/README_MCP b/media/ffvpx/README_MCP
new file mode 100644
index 000000000..4555e08da
--- /dev/null
+++ b/media/ffvpx/README_MCP
@@ -0,0 +1,48 @@
+This directory contains files used in goanna builds from FFmpeg
+(http://ffmpeg.org). The current files are from FFmpeg as of
+Release 3.4.2
+All source files match their path from the library's source archive.
+
+Currently, we only use the vp8 and vp9 portion of the library, and only on x86
+based platforms. If this changes, configuration files will most likely
+need to be updated.
+
+AVX2 must be disabled on Linux 32 bits due to the use of yasm 1.1 on the build bots.
+Once yasm is upgraded to 1.2 or later, AVX2 code could be re-enabled.
+Add --disable-avx2 to configure on those platforms.
+
+configuration files were generated as follow using the configure script:
+./configure --disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl2 --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-decoder=flac --enable-asm --enable-x86asm
+
+config*:
+replace: /HAVE_(MALLOC_H|ARC4RANDOM|LOCALTIME_R|MEMALIGN|POSIX_MEMALIGN)/d
+
+config_darwin32.h:
+add to configure command: --disable-asm --disable-yasm --cc='clang -m32'
+
+config_unix32.h:
+add to configure command: --disable-asm --disable-x86asm --cc='clang -m32'
+replace: s/HAVE_SYSCTL 1/HAVE_SYSCTL 0/ and s/HAVE_MEMALIGN 1/HAVE_MEMALIGN 0/ and s/HAVE_POSIX_MEMALIGN 1/HAVE_POSIX_MEMALIGN 0/
+
+
+config_unix32.h/config_unix64.h/config_unix64.asm:
+replace: s/HAVE_SYSCTL 1/HAVE_SYSCTL 0
+
+config_win32/64.h/asm:
+add to configure command: --toolchain=msvc
+
+Regenerate defaults_disabled.{h,asm} with:
+$ grep -E ".*_(INDEV|OUTDEV|DECODER|ENCODER|DEMUXER|MUXER|PARSER|FILTER|HWACCEL|PROTOCOL|ENCODERS|DECODERS|HWACCELS|INDEVS|OUTDEVS|FILTERS|DEMUXERS|MUXERS|PROTOCOLS) 0" config.h > ~/Work/Mozilla/mozilla-central/media/ffvpx/defaults_disabled.h
+$ grep -E ".*_(INDEV|OUTDEV|DECODER|ENCODER|DEMUXER|MUXER|PARSER|FILTER|HWACCEL|PROTOCOL|ENCODERS|DECODERS|HWACCELS|INDEVS|OUTDEVS|FILTERS|DEMUXERS|MUXERS|PROTOCOLS) 0" config.asm > ~/Work/Mozilla/mozilla-central/media/ffvpx/defaults_disabled.asm
+
+All new decoders/muxers/encoders/... should be added in the list of dummy functions found in libavcodec/dummy_funcs.c
+otherwise linkage will fail on Windows. On other platforms they are optimised out and aren't necessary.
+The GNU comm utility is a useful tool to compare and extract only the changes.
+
+To update the source tree, perform a diff on the files listed in FILES.
+The diffs should typically apply to the ffvpx tree.
+e.g. something like this would do:
+Run in the ffmpeg original tree:
+$ for i in `cat $PATH_CENTRAL/media/ffvpx/FILES`; do diff $REV_LASTSYNC HEAD >> patch.diff; done
+Then apply patch.diff on the ffvpx tree.
+Compilation will reveal if any files are missing.
diff --git a/media/ffvpx/README_MOZILLA b/media/ffvpx/README_MOZILLA
deleted file mode 100644
index 7f42d0513..000000000
--- a/media/ffvpx/README_MOZILLA
+++ /dev/null
@@ -1,39 +0,0 @@
-This directory contains files used in goanna builds from FFmpeg
-(http://ffmpeg.org). The current files are from FFmpeg as of
-revision n3.2-65-gee56777
-All source files match their path from the library's source archive.
-
-Currently, we only use the vp8 and vp9 portion of the library, and only on x86
-based platforms. If this changes, configuration files will most likely
-need to be updated.
-
-AVX2 must be disabled on Linux due to the use of yasm 1.1 on the build bots.
-Once yasm is upgraded to 1.2 or later, AVX2 code could be re-enabled.
-Add --disable-avx2 to configure on those platforms.
-
-configuration files were generated as follow using the configure script:
-./configure --disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-asm --enable-yasm
-
-config*:
-replace: /HAVE_(MALLOC_H|ARC4RANDOM|LOCALTIME_R|MEMALIGN|POSIX_MEMALIGN)/d
-
-config_darwin32.h:
-add to configure command: --disable-asm --disable-yasm --cc='clang -m32'
-
-config_unix32.h:
-add to configure command: --disable-asm --disable-yasm --cc='clang -m32'
-replace: s/HAVE_SYSCTL 1/HAVE_SYSCTL 0/ and s/HAVE_MEMALIGN 1/HAVE_MEMALIGN 0/ and s/HAVE_POSIX_MEMALIGN 1/HAVE_POSIX_MEMALIGN 0/
-
-
-config_unix64.h/config_unix64.asm:
-replace: s/HAVE_SYSCTL 1/HAVE_SYSCTL 0
-
-config_win32/64.h/asm:
-add to configure command: --toolchain=msvc
-
-23 Sept 2016: libavcodec/pthread_frame.c has been patched so as to avoid
-generating large numbers of warnings from TSan (Thread Sanitizer) when
-decoding vp9 streams. This will likely be fixed upstream sometime soon.
-When resyncing with upstream, first un-apply the patch shown at
-https://bugzilla.mozilla.org/show_bug.cgi?id=1274256#c60, then resync,
-then assess whether the patch is still necessary.
diff --git a/media/ffvpx/RELEASE b/media/ffvpx/RELEASE
deleted file mode 100644
index 9f55b2ccb..000000000
--- a/media/ffvpx/RELEASE
+++ /dev/null
@@ -1 +0,0 @@
-3.0
diff --git a/media/ffvpx/RELEASE_NOTES b/media/ffvpx/RELEASE_NOTES
deleted file mode 100644
index 861dc04a1..000000000
--- a/media/ffvpx/RELEASE_NOTES
+++ /dev/null
@@ -1,15 +0,0 @@
-
- ┌─────────────────────────────────────────┐
- │ RELEASE NOTES for FFmpeg 3.0 "Einstein" │
- └─────────────────────────────────────────┘
-
- The FFmpeg Project proudly presents FFmpeg 3.0 "Einstein", about 5
- months after the release of FFmpeg 2.8.
-
- A complete Changelog is available at the root of the project, and the
- complete Git history on http://source.ffmpeg.org.
-
- We hope you will like this release as much as we enjoyed working on it, and
- as usual, if you have any questions about it, or any FFmpeg related topic,
- feel free to join us on the #ffmpeg IRC channel (on irc.freenode.net) or ask
- on the mailing-lists.
diff --git a/media/ffvpx/changes.patch b/media/ffvpx/changes.patch
index 9cb49afaf..49a49b26b 100644
--- a/media/ffvpx/changes.patch
+++ b/media/ffvpx/changes.patch
@@ -50,16 +50,3 @@ index 9fb8d0a..97ad3b9 100644
rgba_color[0] = rgba >> 24;
rgba_color[1] = rgba >> 16;
rgba_color[2] = rgba >> 8;
-diff --git a/media/ffvpx/libavcodec/options.c b/media/ffvpx/libavcodec/options.c
-index d8e3dbf..f25df2a 100644
---- a/media/ffvpx/libavcodec/options.c
-+++ b/media/ffvpx/libavcodec/options.c
-@@ -34,7 +34,7 @@
- #include <string.h>
-
- FF_DISABLE_DEPRECATION_WARNINGS
--#include "options_table.h"
-+#include "ff_options_table.h"
- FF_ENABLE_DEPRECATION_WARNINGS
-
- static const char* context_to_name(void* ptr) {
diff --git a/media/ffvpx/compat/atomics/win32/stdatomic.h b/media/ffvpx/compat/atomics/win32/stdatomic.h
new file mode 100644
index 000000000..bb8e6e7e1
--- /dev/null
+++ b/media/ffvpx/compat/atomics/win32/stdatomic.h
@@ -0,0 +1,181 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef COMPAT_ATOMICS_WIN32_STDATOMIC_H
+#define COMPAT_ATOMICS_WIN32_STDATOMIC_H
+
+#define WIN32_LEAN_AND_MEAN
+#include <stddef.h>
+#include <stdint.h>
+#include <windows.h>
+
+#define ATOMIC_FLAG_INIT 0
+
+#define ATOMIC_VAR_INIT(value) (value)
+
+#define atomic_init(obj, value) \
+do { \
+ *(obj) = (value); \
+} while(0)
+
+#define kill_dependency(y) ((void)0)
+
+#define atomic_thread_fence(order) \
+ MemoryBarrier();
+
+#define atomic_signal_fence(order) \
+ ((void)0)
+
+#define atomic_is_lock_free(obj) 0
+
+typedef intptr_t atomic_flag;
+typedef intptr_t atomic_bool;
+typedef intptr_t atomic_char;
+typedef intptr_t atomic_schar;
+typedef intptr_t atomic_uchar;
+typedef intptr_t atomic_short;
+typedef intptr_t atomic_ushort;
+typedef intptr_t atomic_int;
+typedef intptr_t atomic_uint;
+typedef intptr_t atomic_long;
+typedef intptr_t atomic_ulong;
+typedef intptr_t atomic_llong;
+typedef intptr_t atomic_ullong;
+typedef intptr_t atomic_wchar_t;
+typedef intptr_t atomic_int_least8_t;
+typedef intptr_t atomic_uint_least8_t;
+typedef intptr_t atomic_int_least16_t;
+typedef intptr_t atomic_uint_least16_t;
+typedef intptr_t atomic_int_least32_t;
+typedef intptr_t atomic_uint_least32_t;
+typedef intptr_t atomic_int_least64_t;
+typedef intptr_t atomic_uint_least64_t;
+typedef intptr_t atomic_int_fast8_t;
+typedef intptr_t atomic_uint_fast8_t;
+typedef intptr_t atomic_int_fast16_t;
+typedef intptr_t atomic_uint_fast16_t;
+typedef intptr_t atomic_int_fast32_t;
+typedef intptr_t atomic_uint_fast32_t;
+typedef intptr_t atomic_int_fast64_t;
+typedef intptr_t atomic_uint_fast64_t;
+typedef intptr_t atomic_intptr_t;
+typedef intptr_t atomic_uintptr_t;
+typedef intptr_t atomic_size_t;
+typedef intptr_t atomic_ptrdiff_t;
+typedef intptr_t atomic_intmax_t;
+typedef intptr_t atomic_uintmax_t;
+
+#define atomic_store(object, desired) \
+do { \
+ *(object) = (desired); \
+ MemoryBarrier(); \
+} while (0)
+
+#define atomic_store_explicit(object, desired, order) \
+ atomic_store(object, desired)
+
+#define atomic_load(object) \
+ (MemoryBarrier(), *(object))
+
+#define atomic_load_explicit(object, order) \
+ atomic_load(object)
+
+#define atomic_exchange(object, desired) \
+ InterlockedExchangePointer(object, desired);
+
+#define atomic_exchange_explicit(object, desired, order) \
+ atomic_exchange(object, desired)
+
+static inline int atomic_compare_exchange_strong(intptr_t *object, intptr_t *expected,
+ intptr_t desired)
+{
+ intptr_t old = *expected;
+ *expected = (intptr_t)InterlockedCompareExchangePointer(
+ (PVOID *)object, (PVOID)desired, (PVOID)old);
+ return *expected == old;
+}
+
+#define atomic_compare_exchange_strong_explicit(object, expected, desired, success, failure) \
+ atomic_compare_exchange_strong(object, expected, desired)
+
+#define atomic_compare_exchange_weak(object, expected, desired) \
+ atomic_compare_exchange_strong(object, expected, desired)
+
+#define atomic_compare_exchange_weak_explicit(object, expected, desired, success, failure) \
+ atomic_compare_exchange_weak(object, expected, desired)
+
+#ifdef _WIN64
+#define atomic_fetch_add(object, operand) \
+ InterlockedExchangeAdd64(object, operand)
+
+#define atomic_fetch_sub(object, operand) \
+ InterlockedExchangeAdd64(object, -(operand))
+
+#define atomic_fetch_or(object, operand) \
+ InterlockedOr64(object, operand)
+
+#define atomic_fetch_xor(object, operand) \
+ InterlockedXor64(object, operand)
+
+#define atomic_fetch_and(object, operand) \
+ InterlockedAnd64(object, operand)
+#else
+#define atomic_fetch_add(object, operand) \
+ InterlockedExchangeAdd(object, operand)
+
+#define atomic_fetch_sub(object, operand) \
+ InterlockedExchangeAdd(object, -(operand))
+
+#define atomic_fetch_or(object, operand) \
+ InterlockedOr(object, operand)
+
+#define atomic_fetch_xor(object, operand) \
+ InterlockedXor(object, operand)
+
+#define atomic_fetch_and(object, operand) \
+ InterlockedAnd(object, operand)
+#endif /* _WIN64 */
+
+#define atomic_fetch_add_explicit(object, operand, order) \
+ atomic_fetch_add(object, operand)
+
+#define atomic_fetch_sub_explicit(object, operand, order) \
+ atomic_fetch_sub(object, operand)
+
+#define atomic_fetch_or_explicit(object, operand, order) \
+ atomic_fetch_or(object, operand)
+
+#define atomic_fetch_xor_explicit(object, operand, order) \
+ atomic_fetch_xor(object, operand)
+
+#define atomic_fetch_and_explicit(object, operand, order) \
+ atomic_fetch_and(object, operand)
+
+#define atomic_flag_test_and_set(object) \
+ atomic_exchange(object, 1)
+
+#define atomic_flag_test_and_set_explicit(object, order) \
+ atomic_flag_test_and_set(object)
+
+#define atomic_flag_clear(object) \
+ atomic_store(object, 0)
+
+#define atomic_flag_clear_explicit(object, order) \
+ atomic_flag_clear(object)
+
+#endif /* COMPAT_ATOMICS_WIN32_STDATOMIC_H */
diff --git a/media/ffvpx/compat/w32pthreads.h b/media/ffvpx/compat/w32pthreads.h
index 4ac2a995b..eeead6051 100644
--- a/media/ffvpx/compat/w32pthreads.h
+++ b/media/ffvpx/compat/w32pthreads.h
@@ -77,7 +77,7 @@ typedef struct pthread_cond_t {
static av_unused unsigned __stdcall attribute_align_arg win32thread_worker(void *arg)
{
- pthread_t *h = arg;
+ pthread_t *h = (pthread_t*)arg;
h->ret = h->func(h->arg);
return 0;
}
@@ -270,7 +270,7 @@ static av_unused int pthread_cond_init(pthread_cond_t *cond, const void *unused_
}
/* non native condition variables */
- win32_cond = av_mallocz(sizeof(win32_cond_t));
+ win32_cond = (win32_cond_t*)av_mallocz(sizeof(win32_cond_t));
if (!win32_cond)
return ENOMEM;
cond->Ptr = win32_cond;
@@ -288,7 +288,7 @@ static av_unused int pthread_cond_init(pthread_cond_t *cond, const void *unused_
static av_unused int pthread_cond_destroy(pthread_cond_t *cond)
{
- win32_cond_t *win32_cond = cond->Ptr;
+ win32_cond_t *win32_cond = (win32_cond_t*)cond->Ptr;
/* native condition variables do not destroy */
if (cond_init)
return 0;
@@ -305,7 +305,7 @@ static av_unused int pthread_cond_destroy(pthread_cond_t *cond)
static av_unused int pthread_cond_broadcast(pthread_cond_t *cond)
{
- win32_cond_t *win32_cond = cond->Ptr;
+ win32_cond_t *win32_cond = (win32_cond_t*)cond->Ptr;
int have_waiter;
if (cond_broadcast) {
@@ -337,7 +337,7 @@ static av_unused int pthread_cond_broadcast(pthread_cond_t *cond)
static av_unused int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
- win32_cond_t *win32_cond = cond->Ptr;
+ win32_cond_t *win32_cond = (win32_cond_t*)cond->Ptr;
int last_waiter;
if (cond_wait) {
cond_wait(cond, mutex, INFINITE);
@@ -369,7 +369,7 @@ static av_unused int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mu
static av_unused int pthread_cond_signal(pthread_cond_t *cond)
{
- win32_cond_t *win32_cond = cond->Ptr;
+ win32_cond_t *win32_cond = (win32_cond_t*)cond->Ptr;
int have_waiter;
if (cond_signal) {
cond_signal(cond);
@@ -397,20 +397,20 @@ static av_unused int pthread_cond_signal(pthread_cond_t *cond)
static av_unused void w32thread_init(void)
{
#if _WIN32_WINNT < 0x0600
- HANDLE kernel_dll = GetModuleHandle(TEXT("kernel32.dll"));
+ HMODULE kernel_dll = GetModuleHandle(TEXT("kernel32.dll"));
/* if one is available, then they should all be available */
- cond_init =
- (void*)GetProcAddress(kernel_dll, "InitializeConditionVariable");
- cond_broadcast =
- (void*)GetProcAddress(kernel_dll, "WakeAllConditionVariable");
- cond_signal =
- (void*)GetProcAddress(kernel_dll, "WakeConditionVariable");
- cond_wait =
- (void*)GetProcAddress(kernel_dll, "SleepConditionVariableCS");
- initonce_begin =
- (void*)GetProcAddress(kernel_dll, "InitOnceBeginInitialize");
- initonce_complete =
- (void*)GetProcAddress(kernel_dll, "InitOnceComplete");
+ cond_init = (void (WINAPI*)(pthread_cond_t *))
+ GetProcAddress(kernel_dll, "InitializeConditionVariable");
+ cond_broadcast = (void (WINAPI*)(pthread_cond_t *))
+ GetProcAddress(kernel_dll, "WakeAllConditionVariable");
+ cond_signal = (void (WINAPI*)(pthread_cond_t *))
+ GetProcAddress(kernel_dll, "WakeConditionVariable");
+ cond_wait = (BOOL (WINAPI*)(pthread_cond_t *, pthread_mutex_t *, DWORD))
+ GetProcAddress(kernel_dll, "SleepConditionVariableCS");
+ initonce_begin = (BOOL (WINAPI*)(pthread_once_t *, DWORD, BOOL *, void **))
+ GetProcAddress(kernel_dll, "InitOnceBeginInitialize");
+ initonce_complete = (BOOL (WINAPI*)(pthread_once_t *, DWORD, void *))
+ GetProcAddress(kernel_dll, "InitOnceComplete");
#endif
}
diff --git a/media/ffvpx/config_common.h b/media/ffvpx/config_common.h
index 6ee60762f..dd3b3e170 100644
--- a/media/ffvpx/config_common.h
+++ b/media/ffvpx/config_common.h
@@ -1,3 +1,4 @@
#ifndef MOZ_FFVPX_CONFIG_COMMON_H
#define MOZ_FFVPX_CONFIG_COMMON_H
+#include "defaults_disabled.h"
#endif
diff --git a/media/ffvpx/config_darwin32.h b/media/ffvpx/config_darwin32.h
index de232dca2..f92be8737 100644
--- a/media/ffvpx/config_darwin32.h
+++ b/media/ffvpx/config_darwin32.h
@@ -384,15 +384,7 @@
#define HAVE_XLIB 0
#define CONFIG_BSFS 0
#define CONFIG_DECODERS 1
-#define CONFIG_ENCODERS 0
-#define CONFIG_HWACCELS 0
#define CONFIG_PARSERS 1
-#define CONFIG_INDEVS 0
-#define CONFIG_OUTDEVS 0
-#define CONFIG_FILTERS 0
-#define CONFIG_DEMUXERS 0
-#define CONFIG_MUXERS 0
-#define CONFIG_PROTOCOLS 0
#define CONFIG_DOC 0
#define CONFIG_HTMLPAGES 1
#define CONFIG_MANPAGES 1
@@ -514,7 +506,6 @@
#define CONFIG_VAAPI 0
#define CONFIG_VDA 0
#define CONFIG_VDPAU 0
-#define CONFIG_VIDEOTOOLBOX_HWACCEL 0
#define CONFIG_XVMC 0
#define CONFIG_FTRAPV 0
#define CONFIG_GRAY 0
@@ -579,7 +570,6 @@
#define CONFIG_FDCTDSP 0
#define CONFIG_FLACDSP 1
#define CONFIG_FMTCONVERT 0
-#define CONFIG_FRAME_THREAD_ENCODER 0
#define CONFIG_G722DSP 0
#define CONFIG_GOLOMB 1
#define CONFIG_GPLV3 0
@@ -655,1570 +645,10 @@
#define CONFIG_REMOVE_EXTRADATA_BSF 0
#define CONFIG_TEXT2MOVSUB_BSF 0
#define CONFIG_VP9_SUPERFRAME_BSF 0
-#define CONFIG_AASC_DECODER 0
-#define CONFIG_AIC_DECODER 0
-#define CONFIG_ALIAS_PIX_DECODER 0
-#define CONFIG_AMV_DECODER 0
-#define CONFIG_ANM_DECODER 0
-#define CONFIG_ANSI_DECODER 0
-#define CONFIG_APNG_DECODER 0
-#define CONFIG_ASV1_DECODER 0
-#define CONFIG_ASV2_DECODER 0
-#define CONFIG_AURA_DECODER 0
-#define CONFIG_AURA2_DECODER 0
-#define CONFIG_AVRP_DECODER 0
-#define CONFIG_AVRN_DECODER 0
-#define CONFIG_AVS_DECODER 0
-#define CONFIG_AVUI_DECODER 0
-#define CONFIG_AYUV_DECODER 0
-#define CONFIG_BETHSOFTVID_DECODER 0
-#define CONFIG_BFI_DECODER 0
-#define CONFIG_BINK_DECODER 0
-#define CONFIG_BMP_DECODER 0
-#define CONFIG_BMV_VIDEO_DECODER 0
-#define CONFIG_BRENDER_PIX_DECODER 0
-#define CONFIG_C93_DECODER 0
-#define CONFIG_CAVS_DECODER 0
-#define CONFIG_CDGRAPHICS_DECODER 0
-#define CONFIG_CDXL_DECODER 0
-#define CONFIG_CFHD_DECODER 0
-#define CONFIG_CINEPAK_DECODER 0
-#define CONFIG_CLJR_DECODER 0
-#define CONFIG_CLLC_DECODER 0
-#define CONFIG_COMFORTNOISE_DECODER 0
-#define CONFIG_CPIA_DECODER 0
-#define CONFIG_CSCD_DECODER 0
-#define CONFIG_CYUV_DECODER 0
-#define CONFIG_DDS_DECODER 0
-#define CONFIG_DFA_DECODER 0
-#define CONFIG_DIRAC_DECODER 0
-#define CONFIG_DNXHD_DECODER 0
-#define CONFIG_DPX_DECODER 0
-#define CONFIG_DSICINVIDEO_DECODER 0
-#define CONFIG_DVAUDIO_DECODER 0
-#define CONFIG_DVVIDEO_DECODER 0
-#define CONFIG_DXA_DECODER 0
-#define CONFIG_DXTORY_DECODER 0
-#define CONFIG_DXV_DECODER 0
-#define CONFIG_EACMV_DECODER 0
-#define CONFIG_EAMAD_DECODER 0
-#define CONFIG_EATGQ_DECODER 0
-#define CONFIG_EATGV_DECODER 0
-#define CONFIG_EATQI_DECODER 0
-#define CONFIG_EIGHTBPS_DECODER 0
-#define CONFIG_EIGHTSVX_EXP_DECODER 0
-#define CONFIG_EIGHTSVX_FIB_DECODER 0
-#define CONFIG_ESCAPE124_DECODER 0
-#define CONFIG_ESCAPE130_DECODER 0
-#define CONFIG_EXR_DECODER 0
-#define CONFIG_FFV1_DECODER 0
-#define CONFIG_FFVHUFF_DECODER 0
-#define CONFIG_FIC_DECODER 0
-#define CONFIG_FLASHSV_DECODER 0
-#define CONFIG_FLASHSV2_DECODER 0
-#define CONFIG_FLIC_DECODER 0
-#define CONFIG_FLV_DECODER 0
-#define CONFIG_FOURXM_DECODER 0
-#define CONFIG_FRAPS_DECODER 0
-#define CONFIG_FRWU_DECODER 0
-#define CONFIG_G2M_DECODER 0
-#define CONFIG_GIF_DECODER 0
-#define CONFIG_H261_DECODER 0
-#define CONFIG_H263_DECODER 0
-#define CONFIG_H263I_DECODER 0
-#define CONFIG_H263P_DECODER 0
-#define CONFIG_H264_DECODER 0
-#define CONFIG_H264_CRYSTALHD_DECODER 0
-#define CONFIG_H264_MEDIACODEC_DECODER 0
-#define CONFIG_H264_MMAL_DECODER 0
-#define CONFIG_H264_QSV_DECODER 0
-#define CONFIG_H264_VDA_DECODER 0
-#define CONFIG_H264_VDPAU_DECODER 0
-#define CONFIG_HAP_DECODER 0
-#define CONFIG_HEVC_DECODER 0
-#define CONFIG_HEVC_QSV_DECODER 0
-#define CONFIG_HNM4_VIDEO_DECODER 0
-#define CONFIG_HQ_HQA_DECODER 0
-#define CONFIG_HQX_DECODER 0
-#define CONFIG_HUFFYUV_DECODER 0
-#define CONFIG_IDCIN_DECODER 0
-#define CONFIG_IFF_ILBM_DECODER 0
-#define CONFIG_INDEO2_DECODER 0
-#define CONFIG_INDEO3_DECODER 0
-#define CONFIG_INDEO4_DECODER 0
-#define CONFIG_INDEO5_DECODER 0
-#define CONFIG_INTERPLAY_VIDEO_DECODER 0
-#define CONFIG_JPEG2000_DECODER 0
-#define CONFIG_JPEGLS_DECODER 0
-#define CONFIG_JV_DECODER 0
-#define CONFIG_KGV1_DECODER 0
-#define CONFIG_KMVC_DECODER 0
-#define CONFIG_LAGARITH_DECODER 0
-#define CONFIG_LOCO_DECODER 0
-#define CONFIG_M101_DECODER 0
-#define CONFIG_MAGICYUV_DECODER 0
-#define CONFIG_MDEC_DECODER 0
-#define CONFIG_MIMIC_DECODER 0
-#define CONFIG_MJPEG_DECODER 0
-#define CONFIG_MJPEGB_DECODER 0
-#define CONFIG_MMVIDEO_DECODER 0
-#define CONFIG_MOTIONPIXELS_DECODER 0
-#define CONFIG_MPEG_XVMC_DECODER 0
-#define CONFIG_MPEG1VIDEO_DECODER 0
-#define CONFIG_MPEG2VIDEO_DECODER 0
-#define CONFIG_MPEG4_DECODER 0
-#define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG4_MMAL_DECODER 0
-#define CONFIG_MPEG4_VDPAU_DECODER 0
-#define CONFIG_MPEGVIDEO_DECODER 0
-#define CONFIG_MPEG_VDPAU_DECODER 0
-#define CONFIG_MPEG1_VDPAU_DECODER 0
-#define CONFIG_MPEG2_MMAL_DECODER 0
-#define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG2_QSV_DECODER 0
-#define CONFIG_MSA1_DECODER 0
-#define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MSMPEG4V1_DECODER 0
-#define CONFIG_MSMPEG4V2_DECODER 0
-#define CONFIG_MSMPEG4V3_DECODER 0
-#define CONFIG_MSRLE_DECODER 0
-#define CONFIG_MSS1_DECODER 0
-#define CONFIG_MSS2_DECODER 0
-#define CONFIG_MSVIDEO1_DECODER 0
-#define CONFIG_MSZH_DECODER 0
-#define CONFIG_MTS2_DECODER 0
-#define CONFIG_MVC1_DECODER 0
-#define CONFIG_MVC2_DECODER 0
-#define CONFIG_MXPEG_DECODER 0
-#define CONFIG_NUV_DECODER 0
-#define CONFIG_PAF_VIDEO_DECODER 0
-#define CONFIG_PAM_DECODER 0
-#define CONFIG_PBM_DECODER 0
-#define CONFIG_PCX_DECODER 0
-#define CONFIG_PGM_DECODER 0
-#define CONFIG_PGMYUV_DECODER 0
-#define CONFIG_PICTOR_DECODER 0
-#define CONFIG_PNG_DECODER 0
-#define CONFIG_PPM_DECODER 0
-#define CONFIG_PRORES_DECODER 0
-#define CONFIG_PRORES_LGPL_DECODER 0
-#define CONFIG_PTX_DECODER 0
-#define CONFIG_QDRAW_DECODER 0
-#define CONFIG_QPEG_DECODER 0
-#define CONFIG_QTRLE_DECODER 0
-#define CONFIG_R10K_DECODER 0
-#define CONFIG_R210_DECODER 0
-#define CONFIG_RAWVIDEO_DECODER 0
-#define CONFIG_RL2_DECODER 0
-#define CONFIG_ROQ_DECODER 0
-#define CONFIG_RPZA_DECODER 0
-#define CONFIG_RSCC_DECODER 0
-#define CONFIG_RV10_DECODER 0
-#define CONFIG_RV20_DECODER 0
-#define CONFIG_RV30_DECODER 0
-#define CONFIG_RV40_DECODER 0
-#define CONFIG_S302M_DECODER 0
-#define CONFIG_SANM_DECODER 0
-#define CONFIG_SCREENPRESSO_DECODER 0
-#define CONFIG_SDX2_DPCM_DECODER 0
-#define CONFIG_SGI_DECODER 0
-#define CONFIG_SGIRLE_DECODER 0
-#define CONFIG_SHEERVIDEO_DECODER 0
-#define CONFIG_SMACKER_DECODER 0
-#define CONFIG_SMC_DECODER 0
-#define CONFIG_SMVJPEG_DECODER 0
-#define CONFIG_SNOW_DECODER 0
-#define CONFIG_SP5X_DECODER 0
-#define CONFIG_SUNRAST_DECODER 0
-#define CONFIG_SVQ1_DECODER 0
-#define CONFIG_SVQ3_DECODER 0
-#define CONFIG_TARGA_DECODER 0
-#define CONFIG_TARGA_Y216_DECODER 0
-#define CONFIG_TDSC_DECODER 0
-#define CONFIG_THEORA_DECODER 0
-#define CONFIG_THP_DECODER 0
-#define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-#define CONFIG_TIFF_DECODER 0
-#define CONFIG_TMV_DECODER 0
-#define CONFIG_TRUEMOTION1_DECODER 0
-#define CONFIG_TRUEMOTION2_DECODER 0
-#define CONFIG_TRUEMOTION2RT_DECODER 0
-#define CONFIG_TSCC_DECODER 0
-#define CONFIG_TSCC2_DECODER 0
-#define CONFIG_TXD_DECODER 0
-#define CONFIG_ULTI_DECODER 0
-#define CONFIG_UTVIDEO_DECODER 0
-#define CONFIG_V210_DECODER 0
-#define CONFIG_V210X_DECODER 0
-#define CONFIG_V308_DECODER 0
-#define CONFIG_V408_DECODER 0
-#define CONFIG_V410_DECODER 0
-#define CONFIG_VB_DECODER 0
-#define CONFIG_VBLE_DECODER 0
-#define CONFIG_VC1_DECODER 0
-#define CONFIG_VC1_CRYSTALHD_DECODER 0
-#define CONFIG_VC1_VDPAU_DECODER 0
-#define CONFIG_VC1IMAGE_DECODER 0
-#define CONFIG_VC1_MMAL_DECODER 0
-#define CONFIG_VC1_QSV_DECODER 0
-#define CONFIG_VCR1_DECODER 0
-#define CONFIG_VMDVIDEO_DECODER 0
-#define CONFIG_VMNC_DECODER 0
-#define CONFIG_VP3_DECODER 0
-#define CONFIG_VP5_DECODER 0
-#define CONFIG_VP6_DECODER 0
-#define CONFIG_VP6A_DECODER 0
-#define CONFIG_VP6F_DECODER 0
-#define CONFIG_VP7_DECODER 0
#define CONFIG_VP8_DECODER 1
#define CONFIG_VP9_DECODER 1
-#define CONFIG_VQA_DECODER 0
-#define CONFIG_WEBP_DECODER 0
-#define CONFIG_WMV1_DECODER 0
-#define CONFIG_WMV2_DECODER 0
-#define CONFIG_WMV3_DECODER 0
-#define CONFIG_WMV3_CRYSTALHD_DECODER 0
-#define CONFIG_WMV3_VDPAU_DECODER 0
-#define CONFIG_WMV3IMAGE_DECODER 0
-#define CONFIG_WNV1_DECODER 0
-#define CONFIG_XAN_WC3_DECODER 0
-#define CONFIG_XAN_WC4_DECODER 0
-#define CONFIG_XBM_DECODER 0
-#define CONFIG_XFACE_DECODER 0
-#define CONFIG_XL_DECODER 0
-#define CONFIG_XWD_DECODER 0
-#define CONFIG_Y41P_DECODER 0
-#define CONFIG_YLC_DECODER 0
-#define CONFIG_YOP_DECODER 0
-#define CONFIG_YUV4_DECODER 0
-#define CONFIG_ZERO12V_DECODER 0
-#define CONFIG_ZEROCODEC_DECODER 0
-#define CONFIG_ZLIB_DECODER 0
-#define CONFIG_ZMBV_DECODER 0
-#define CONFIG_AAC_DECODER 0
-#define CONFIG_AAC_FIXED_DECODER 0
-#define CONFIG_AAC_LATM_DECODER 0
-#define CONFIG_AC3_DECODER 0
-#define CONFIG_AC3_FIXED_DECODER 0
-#define CONFIG_ALAC_DECODER 0
-#define CONFIG_ALS_DECODER 0
-#define CONFIG_AMRNB_DECODER 0
-#define CONFIG_AMRWB_DECODER 0
-#define CONFIG_APE_DECODER 0
-#define CONFIG_ATRAC1_DECODER 0
-#define CONFIG_ATRAC3_DECODER 0
-#define CONFIG_ATRAC3P_DECODER 0
-#define CONFIG_BINKAUDIO_DCT_DECODER 0
-#define CONFIG_BINKAUDIO_RDFT_DECODER 0
-#define CONFIG_BMV_AUDIO_DECODER 0
-#define CONFIG_COOK_DECODER 0
-#define CONFIG_DCA_DECODER 0
-#define CONFIG_DSD_LSBF_DECODER 0
-#define CONFIG_DSD_MSBF_DECODER 0
-#define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-#define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-#define CONFIG_DSICINAUDIO_DECODER 0
-#define CONFIG_DSS_SP_DECODER 0
-#define CONFIG_DST_DECODER 0
-#define CONFIG_EAC3_DECODER 0
-#define CONFIG_EVRC_DECODER 0
-#define CONFIG_FFWAVESYNTH_DECODER 0
#define CONFIG_FLAC_DECODER 1
-#define CONFIG_G723_1_DECODER 0
-#define CONFIG_G729_DECODER 0
-#define CONFIG_GSM_DECODER 0
-#define CONFIG_GSM_MS_DECODER 0
-#define CONFIG_IAC_DECODER 0
-#define CONFIG_IMC_DECODER 0
-#define CONFIG_INTERPLAY_ACM_DECODER 0
-#define CONFIG_MACE3_DECODER 0
-#define CONFIG_MACE6_DECODER 0
-#define CONFIG_METASOUND_DECODER 0
-#define CONFIG_MLP_DECODER 0
-#define CONFIG_MP1_DECODER 0
-#define CONFIG_MP1FLOAT_DECODER 0
-#define CONFIG_MP2_DECODER 0
-#define CONFIG_MP2FLOAT_DECODER 0
-#define CONFIG_MP3_DECODER 0
-#define CONFIG_MP3FLOAT_DECODER 0
-#define CONFIG_MP3ADU_DECODER 0
-#define CONFIG_MP3ADUFLOAT_DECODER 0
-#define CONFIG_MP3ON4_DECODER 0
-#define CONFIG_MP3ON4FLOAT_DECODER 0
-#define CONFIG_MPC7_DECODER 0
-#define CONFIG_MPC8_DECODER 0
-#define CONFIG_NELLYMOSER_DECODER 0
-#define CONFIG_ON2AVC_DECODER 0
-#define CONFIG_OPUS_DECODER 0
-#define CONFIG_PAF_AUDIO_DECODER 0
-#define CONFIG_QCELP_DECODER 0
-#define CONFIG_QDM2_DECODER 0
-#define CONFIG_RA_144_DECODER 0
-#define CONFIG_RA_288_DECODER 0
-#define CONFIG_RALF_DECODER 0
-#define CONFIG_SHORTEN_DECODER 0
-#define CONFIG_SIPR_DECODER 0
-#define CONFIG_SMACKAUD_DECODER 0
-#define CONFIG_SONIC_DECODER 0
-#define CONFIG_TAK_DECODER 0
-#define CONFIG_TRUEHD_DECODER 0
-#define CONFIG_TRUESPEECH_DECODER 0
-#define CONFIG_TTA_DECODER 0
-#define CONFIG_TWINVQ_DECODER 0
-#define CONFIG_VMDAUDIO_DECODER 0
-#define CONFIG_VORBIS_DECODER 0
-#define CONFIG_WAVPACK_DECODER 0
-#define CONFIG_WMALOSSLESS_DECODER 0
-#define CONFIG_WMAPRO_DECODER 0
-#define CONFIG_WMAV1_DECODER 0
-#define CONFIG_WMAV2_DECODER 0
-#define CONFIG_WMAVOICE_DECODER 0
-#define CONFIG_WS_SND1_DECODER 0
-#define CONFIG_XMA1_DECODER 0
-#define CONFIG_XMA2_DECODER 0
-#define CONFIG_PCM_ALAW_DECODER 0
-#define CONFIG_PCM_BLURAY_DECODER 0
-#define CONFIG_PCM_DVD_DECODER 0
-#define CONFIG_PCM_F32BE_DECODER 0
-#define CONFIG_PCM_F32LE_DECODER 0
-#define CONFIG_PCM_F64BE_DECODER 0
-#define CONFIG_PCM_F64LE_DECODER 0
-#define CONFIG_PCM_LXF_DECODER 0
-#define CONFIG_PCM_MULAW_DECODER 0
-#define CONFIG_PCM_S8_DECODER 0
-#define CONFIG_PCM_S8_PLANAR_DECODER 0
-#define CONFIG_PCM_S16BE_DECODER 0
-#define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-#define CONFIG_PCM_S16LE_DECODER 0
-#define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S24BE_DECODER 0
-#define CONFIG_PCM_S24DAUD_DECODER 0
-#define CONFIG_PCM_S24LE_DECODER 0
-#define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S32BE_DECODER 0
-#define CONFIG_PCM_S32LE_DECODER 0
-#define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S64BE_DECODER 0
-#define CONFIG_PCM_S64LE_DECODER 0
-#define CONFIG_PCM_U8_DECODER 0
-#define CONFIG_PCM_U16BE_DECODER 0
-#define CONFIG_PCM_U16LE_DECODER 0
-#define CONFIG_PCM_U24BE_DECODER 0
-#define CONFIG_PCM_U24LE_DECODER 0
-#define CONFIG_PCM_U32BE_DECODER 0
-#define CONFIG_PCM_U32LE_DECODER 0
-#define CONFIG_PCM_ZORK_DECODER 0
-#define CONFIG_INTERPLAY_DPCM_DECODER 0
-#define CONFIG_ROQ_DPCM_DECODER 0
-#define CONFIG_SOL_DPCM_DECODER 0
-#define CONFIG_XAN_DPCM_DECODER 0
-#define CONFIG_ADPCM_4XM_DECODER 0
-#define CONFIG_ADPCM_ADX_DECODER 0
-#define CONFIG_ADPCM_AFC_DECODER 0
-#define CONFIG_ADPCM_AICA_DECODER 0
-#define CONFIG_ADPCM_CT_DECODER 0
-#define CONFIG_ADPCM_DTK_DECODER 0
-#define CONFIG_ADPCM_EA_DECODER 0
-#define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-#define CONFIG_ADPCM_EA_R1_DECODER 0
-#define CONFIG_ADPCM_EA_R2_DECODER 0
-#define CONFIG_ADPCM_EA_R3_DECODER 0
-#define CONFIG_ADPCM_EA_XAS_DECODER 0
-#define CONFIG_ADPCM_G722_DECODER 0
-#define CONFIG_ADPCM_G726_DECODER 0
-#define CONFIG_ADPCM_G726LE_DECODER 0
-#define CONFIG_ADPCM_IMA_AMV_DECODER 0
-#define CONFIG_ADPCM_IMA_APC_DECODER 0
-#define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-#define CONFIG_ADPCM_IMA_DK3_DECODER 0
-#define CONFIG_ADPCM_IMA_DK4_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-#define CONFIG_ADPCM_IMA_ISS_DECODER 0
-#define CONFIG_ADPCM_IMA_OKI_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_DECODER 0
-#define CONFIG_ADPCM_IMA_RAD_DECODER 0
-#define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-#define CONFIG_ADPCM_IMA_WAV_DECODER 0
-#define CONFIG_ADPCM_IMA_WS_DECODER 0
-#define CONFIG_ADPCM_MS_DECODER 0
-#define CONFIG_ADPCM_MTAF_DECODER 0
-#define CONFIG_ADPCM_PSX_DECODER 0
-#define CONFIG_ADPCM_SBPRO_2_DECODER 0
-#define CONFIG_ADPCM_SBPRO_3_DECODER 0
-#define CONFIG_ADPCM_SBPRO_4_DECODER 0
-#define CONFIG_ADPCM_SWF_DECODER 0
-#define CONFIG_ADPCM_THP_DECODER 0
-#define CONFIG_ADPCM_THP_LE_DECODER 0
-#define CONFIG_ADPCM_VIMA_DECODER 0
-#define CONFIG_ADPCM_XA_DECODER 0
-#define CONFIG_ADPCM_YAMAHA_DECODER 0
-#define CONFIG_SSA_DECODER 0
-#define CONFIG_ASS_DECODER 0
-#define CONFIG_CCAPTION_DECODER 0
-#define CONFIG_DVBSUB_DECODER 0
-#define CONFIG_DVDSUB_DECODER 0
-#define CONFIG_JACOSUB_DECODER 0
-#define CONFIG_MICRODVD_DECODER 0
-#define CONFIG_MOVTEXT_DECODER 0
-#define CONFIG_MPL2_DECODER 0
-#define CONFIG_PGSSUB_DECODER 0
-#define CONFIG_PJS_DECODER 0
-#define CONFIG_REALTEXT_DECODER 0
-#define CONFIG_SAMI_DECODER 0
-#define CONFIG_SRT_DECODER 0
-#define CONFIG_STL_DECODER 0
-#define CONFIG_SUBRIP_DECODER 0
-#define CONFIG_SUBVIEWER_DECODER 0
-#define CONFIG_SUBVIEWER1_DECODER 0
-#define CONFIG_TEXT_DECODER 0
-#define CONFIG_VPLAYER_DECODER 0
-#define CONFIG_WEBVTT_DECODER 0
-#define CONFIG_XSUB_DECODER 0
-#define CONFIG_AAC_AT_DECODER 0
-#define CONFIG_AC3_AT_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-#define CONFIG_ALAC_AT_DECODER 0
-#define CONFIG_AMR_NB_AT_DECODER 0
-#define CONFIG_EAC3_AT_DECODER 0
-#define CONFIG_GSM_MS_AT_DECODER 0
-#define CONFIG_ILBC_AT_DECODER 0
-#define CONFIG_MP1_AT_DECODER 0
-#define CONFIG_MP2_AT_DECODER 0
-#define CONFIG_MP3_AT_DECODER 0
-#define CONFIG_PCM_ALAW_AT_DECODER 0
-#define CONFIG_PCM_MULAW_AT_DECODER 0
-#define CONFIG_QDMC_AT_DECODER 0
-#define CONFIG_QDM2_AT_DECODER 0
-#define CONFIG_LIBCELT_DECODER 0
-#define CONFIG_LIBFDK_AAC_DECODER 0
-#define CONFIG_LIBGSM_DECODER 0
-#define CONFIG_LIBGSM_MS_DECODER 0
-#define CONFIG_LIBILBC_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-#define CONFIG_LIBOPENJPEG_DECODER 0
-#define CONFIG_LIBOPUS_DECODER 0
-#define CONFIG_LIBSCHROEDINGER_DECODER 0
-#define CONFIG_LIBSPEEX_DECODER 0
-#define CONFIG_LIBVORBIS_DECODER 0
-#define CONFIG_LIBVPX_VP8_DECODER 0
-#define CONFIG_LIBVPX_VP9_DECODER 0
-#define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-#define CONFIG_BINTEXT_DECODER 0
-#define CONFIG_XBIN_DECODER 0
-#define CONFIG_IDF_DECODER 0
-#define CONFIG_LIBOPENH264_DECODER 0
-#define CONFIG_H263_CUVID_DECODER 0
-#define CONFIG_H264_CUVID_DECODER 0
-#define CONFIG_HEVC_CUVID_DECODER 0
-#define CONFIG_HEVC_MEDIACODEC_DECODER 0
-#define CONFIG_MJPEG_CUVID_DECODER 0
-#define CONFIG_MPEG1_CUVID_DECODER 0
-#define CONFIG_MPEG2_CUVID_DECODER 0
-#define CONFIG_MPEG4_CUVID_DECODER 0
-#define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-#define CONFIG_VC1_CUVID_DECODER 0
-#define CONFIG_VP8_CUVID_DECODER 0
-#define CONFIG_VP8_MEDIACODEC_DECODER 0
-#define CONFIG_VP9_CUVID_DECODER 0
-#define CONFIG_VP9_MEDIACODEC_DECODER 0
-#define CONFIG_AA_DEMUXER 0
-#define CONFIG_AAC_DEMUXER 0
-#define CONFIG_AC3_DEMUXER 0
-#define CONFIG_ACM_DEMUXER 0
-#define CONFIG_ACT_DEMUXER 0
-#define CONFIG_ADF_DEMUXER 0
-#define CONFIG_ADP_DEMUXER 0
-#define CONFIG_ADS_DEMUXER 0
-#define CONFIG_ADX_DEMUXER 0
-#define CONFIG_AEA_DEMUXER 0
-#define CONFIG_AFC_DEMUXER 0
-#define CONFIG_AIFF_DEMUXER 0
-#define CONFIG_AIX_DEMUXER 0
-#define CONFIG_AMR_DEMUXER 0
-#define CONFIG_ANM_DEMUXER 0
-#define CONFIG_APC_DEMUXER 0
-#define CONFIG_APE_DEMUXER 0
-#define CONFIG_APNG_DEMUXER 0
-#define CONFIG_AQTITLE_DEMUXER 0
-#define CONFIG_ASF_DEMUXER 0
-#define CONFIG_ASF_O_DEMUXER 0
-#define CONFIG_ASS_DEMUXER 0
-#define CONFIG_AST_DEMUXER 0
-#define CONFIG_AU_DEMUXER 0
-#define CONFIG_AVI_DEMUXER 0
-#define CONFIG_AVISYNTH_DEMUXER 0
-#define CONFIG_AVR_DEMUXER 0
-#define CONFIG_AVS_DEMUXER 0
-#define CONFIG_BETHSOFTVID_DEMUXER 0
-#define CONFIG_BFI_DEMUXER 0
-#define CONFIG_BINTEXT_DEMUXER 0
-#define CONFIG_BINK_DEMUXER 0
-#define CONFIG_BIT_DEMUXER 0
-#define CONFIG_BMV_DEMUXER 0
-#define CONFIG_BFSTM_DEMUXER 0
-#define CONFIG_BRSTM_DEMUXER 0
-#define CONFIG_BOA_DEMUXER 0
-#define CONFIG_C93_DEMUXER 0
-#define CONFIG_CAF_DEMUXER 0
-#define CONFIG_CAVSVIDEO_DEMUXER 0
-#define CONFIG_CDG_DEMUXER 0
-#define CONFIG_CDXL_DEMUXER 0
-#define CONFIG_CINE_DEMUXER 0
-#define CONFIG_CONCAT_DEMUXER 0
-#define CONFIG_DATA_DEMUXER 0
-#define CONFIG_DAUD_DEMUXER 0
-#define CONFIG_DCSTR_DEMUXER 0
-#define CONFIG_DFA_DEMUXER 0
-#define CONFIG_DIRAC_DEMUXER 0
-#define CONFIG_DNXHD_DEMUXER 0
-#define CONFIG_DSF_DEMUXER 0
-#define CONFIG_DSICIN_DEMUXER 0
-#define CONFIG_DSS_DEMUXER 0
-#define CONFIG_DTS_DEMUXER 0
-#define CONFIG_DTSHD_DEMUXER 0
-#define CONFIG_DV_DEMUXER 0
-#define CONFIG_DVBSUB_DEMUXER 0
-#define CONFIG_DVBTXT_DEMUXER 0
-#define CONFIG_DXA_DEMUXER 0
-#define CONFIG_EA_DEMUXER 0
-#define CONFIG_EA_CDATA_DEMUXER 0
-#define CONFIG_EAC3_DEMUXER 0
-#define CONFIG_EPAF_DEMUXER 0
-#define CONFIG_FFM_DEMUXER 0
-#define CONFIG_FFMETADATA_DEMUXER 0
-#define CONFIG_FILMSTRIP_DEMUXER 0
-#define CONFIG_FLAC_DEMUXER 0
-#define CONFIG_FLIC_DEMUXER 0
-#define CONFIG_FLV_DEMUXER 0
-#define CONFIG_LIVE_FLV_DEMUXER 0
-#define CONFIG_FOURXM_DEMUXER 0
-#define CONFIG_FRM_DEMUXER 0
-#define CONFIG_FSB_DEMUXER 0
-#define CONFIG_G722_DEMUXER 0
-#define CONFIG_G723_1_DEMUXER 0
-#define CONFIG_G729_DEMUXER 0
-#define CONFIG_GENH_DEMUXER 0
-#define CONFIG_GIF_DEMUXER 0
-#define CONFIG_GSM_DEMUXER 0
-#define CONFIG_GXF_DEMUXER 0
-#define CONFIG_H261_DEMUXER 0
-#define CONFIG_H263_DEMUXER 0
-#define CONFIG_H264_DEMUXER 0
-#define CONFIG_HEVC_DEMUXER 0
-#define CONFIG_HLS_DEMUXER 0
-#define CONFIG_HNM_DEMUXER 0
-#define CONFIG_ICO_DEMUXER 0
-#define CONFIG_IDCIN_DEMUXER 0
-#define CONFIG_IDF_DEMUXER 0
-#define CONFIG_IFF_DEMUXER 0
-#define CONFIG_ILBC_DEMUXER 0
-#define CONFIG_IMAGE2_DEMUXER 0
-#define CONFIG_IMAGE2PIPE_DEMUXER 0
-#define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-#define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-#define CONFIG_INGENIENT_DEMUXER 0
-#define CONFIG_IPMOVIE_DEMUXER 0
-#define CONFIG_IRCAM_DEMUXER 0
-#define CONFIG_ISS_DEMUXER 0
-#define CONFIG_IV8_DEMUXER 0
-#define CONFIG_IVF_DEMUXER 0
-#define CONFIG_IVR_DEMUXER 0
-#define CONFIG_JACOSUB_DEMUXER 0
-#define CONFIG_JV_DEMUXER 0
-#define CONFIG_LMLM4_DEMUXER 0
-#define CONFIG_LOAS_DEMUXER 0
-#define CONFIG_LRC_DEMUXER 0
-#define CONFIG_LVF_DEMUXER 0
-#define CONFIG_LXF_DEMUXER 0
-#define CONFIG_M4V_DEMUXER 0
-#define CONFIG_MATROSKA_DEMUXER 0
-#define CONFIG_MGSTS_DEMUXER 0
-#define CONFIG_MICRODVD_DEMUXER 0
-#define CONFIG_MJPEG_DEMUXER 0
-#define CONFIG_MLP_DEMUXER 0
-#define CONFIG_MLV_DEMUXER 0
-#define CONFIG_MM_DEMUXER 0
-#define CONFIG_MMF_DEMUXER 0
-#define CONFIG_MOV_DEMUXER 0
-#define CONFIG_MP3_DEMUXER 0
-#define CONFIG_MPC_DEMUXER 0
-#define CONFIG_MPC8_DEMUXER 0
-#define CONFIG_MPEGPS_DEMUXER 0
-#define CONFIG_MPEGTS_DEMUXER 0
-#define CONFIG_MPEGTSRAW_DEMUXER 0
-#define CONFIG_MPEGVIDEO_DEMUXER 0
-#define CONFIG_MPJPEG_DEMUXER 0
-#define CONFIG_MPL2_DEMUXER 0
-#define CONFIG_MPSUB_DEMUXER 0
-#define CONFIG_MSF_DEMUXER 0
-#define CONFIG_MSNWC_TCP_DEMUXER 0
-#define CONFIG_MTAF_DEMUXER 0
-#define CONFIG_MTV_DEMUXER 0
-#define CONFIG_MUSX_DEMUXER 0
-#define CONFIG_MV_DEMUXER 0
-#define CONFIG_MVI_DEMUXER 0
-#define CONFIG_MXF_DEMUXER 0
-#define CONFIG_MXG_DEMUXER 0
-#define CONFIG_NC_DEMUXER 0
-#define CONFIG_NISTSPHERE_DEMUXER 0
-#define CONFIG_NSV_DEMUXER 0
-#define CONFIG_NUT_DEMUXER 0
-#define CONFIG_NUV_DEMUXER 0
-#define CONFIG_OGG_DEMUXER 0
-#define CONFIG_OMA_DEMUXER 0
-#define CONFIG_PAF_DEMUXER 0
-#define CONFIG_PCM_ALAW_DEMUXER 0
-#define CONFIG_PCM_MULAW_DEMUXER 0
-#define CONFIG_PCM_F64BE_DEMUXER 0
-#define CONFIG_PCM_F64LE_DEMUXER 0
-#define CONFIG_PCM_F32BE_DEMUXER 0
-#define CONFIG_PCM_F32LE_DEMUXER 0
-#define CONFIG_PCM_S32BE_DEMUXER 0
-#define CONFIG_PCM_S32LE_DEMUXER 0
-#define CONFIG_PCM_S24BE_DEMUXER 0
-#define CONFIG_PCM_S24LE_DEMUXER 0
-#define CONFIG_PCM_S16BE_DEMUXER 0
-#define CONFIG_PCM_S16LE_DEMUXER 0
-#define CONFIG_PCM_S8_DEMUXER 0
-#define CONFIG_PCM_U32BE_DEMUXER 0
-#define CONFIG_PCM_U32LE_DEMUXER 0
-#define CONFIG_PCM_U24BE_DEMUXER 0
-#define CONFIG_PCM_U24LE_DEMUXER 0
-#define CONFIG_PCM_U16BE_DEMUXER 0
-#define CONFIG_PCM_U16LE_DEMUXER 0
-#define CONFIG_PCM_U8_DEMUXER 0
-#define CONFIG_PJS_DEMUXER 0
-#define CONFIG_PMP_DEMUXER 0
-#define CONFIG_PVA_DEMUXER 0
-#define CONFIG_PVF_DEMUXER 0
-#define CONFIG_QCP_DEMUXER 0
-#define CONFIG_R3D_DEMUXER 0
-#define CONFIG_RAWVIDEO_DEMUXER 0
-#define CONFIG_REALTEXT_DEMUXER 0
-#define CONFIG_REDSPARK_DEMUXER 0
-#define CONFIG_RL2_DEMUXER 0
-#define CONFIG_RM_DEMUXER 0
-#define CONFIG_ROQ_DEMUXER 0
-#define CONFIG_RPL_DEMUXER 0
-#define CONFIG_RSD_DEMUXER 0
-#define CONFIG_RSO_DEMUXER 0
-#define CONFIG_RTP_DEMUXER 0
-#define CONFIG_RTSP_DEMUXER 0
-#define CONFIG_SAMI_DEMUXER 0
-#define CONFIG_SAP_DEMUXER 0
-#define CONFIG_SBG_DEMUXER 0
-#define CONFIG_SDP_DEMUXER 0
-#define CONFIG_SDR2_DEMUXER 0
-#define CONFIG_SEGAFILM_DEMUXER 0
-#define CONFIG_SHORTEN_DEMUXER 0
-#define CONFIG_SIFF_DEMUXER 0
-#define CONFIG_SLN_DEMUXER 0
-#define CONFIG_SMACKER_DEMUXER 0
-#define CONFIG_SMJPEG_DEMUXER 0
-#define CONFIG_SMUSH_DEMUXER 0
-#define CONFIG_SOL_DEMUXER 0
-#define CONFIG_SOX_DEMUXER 0
-#define CONFIG_SPDIF_DEMUXER 0
-#define CONFIG_SRT_DEMUXER 0
-#define CONFIG_STR_DEMUXER 0
-#define CONFIG_STL_DEMUXER 0
-#define CONFIG_SUBVIEWER1_DEMUXER 0
-#define CONFIG_SUBVIEWER_DEMUXER 0
-#define CONFIG_SUP_DEMUXER 0
-#define CONFIG_SVAG_DEMUXER 0
-#define CONFIG_SWF_DEMUXER 0
-#define CONFIG_TAK_DEMUXER 0
-#define CONFIG_TEDCAPTIONS_DEMUXER 0
-#define CONFIG_THP_DEMUXER 0
-#define CONFIG_THREEDOSTR_DEMUXER 0
-#define CONFIG_TIERTEXSEQ_DEMUXER 0
-#define CONFIG_TMV_DEMUXER 0
-#define CONFIG_TRUEHD_DEMUXER 0
-#define CONFIG_TTA_DEMUXER 0
-#define CONFIG_TXD_DEMUXER 0
-#define CONFIG_TTY_DEMUXER 0
-#define CONFIG_V210_DEMUXER 0
-#define CONFIG_V210X_DEMUXER 0
-#define CONFIG_VAG_DEMUXER 0
-#define CONFIG_VC1_DEMUXER 0
-#define CONFIG_VC1T_DEMUXER 0
-#define CONFIG_VIVO_DEMUXER 0
-#define CONFIG_VMD_DEMUXER 0
-#define CONFIG_VOBSUB_DEMUXER 0
-#define CONFIG_VOC_DEMUXER 0
-#define CONFIG_VPK_DEMUXER 0
-#define CONFIG_VPLAYER_DEMUXER 0
-#define CONFIG_VQF_DEMUXER 0
-#define CONFIG_W64_DEMUXER 0
-#define CONFIG_WAV_DEMUXER 0
-#define CONFIG_WC3_DEMUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-#define CONFIG_WEBVTT_DEMUXER 0
-#define CONFIG_WSAUD_DEMUXER 0
-#define CONFIG_WSD_DEMUXER 0
-#define CONFIG_WSVQA_DEMUXER 0
-#define CONFIG_WTV_DEMUXER 0
-#define CONFIG_WVE_DEMUXER 0
-#define CONFIG_WV_DEMUXER 0
-#define CONFIG_XA_DEMUXER 0
-#define CONFIG_XBIN_DEMUXER 0
-#define CONFIG_XMV_DEMUXER 0
-#define CONFIG_XVAG_DEMUXER 0
-#define CONFIG_XWMA_DEMUXER 0
-#define CONFIG_YOP_DEMUXER 0
-#define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-#define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-#define CONFIG_LIBGME_DEMUXER 0
-#define CONFIG_LIBMODPLUG_DEMUXER 0
-#define CONFIG_LIBNUT_DEMUXER 0
-#define CONFIG_LIBOPENMPT_DEMUXER 0
-#define CONFIG_A64MULTI_ENCODER 0
-#define CONFIG_A64MULTI5_ENCODER 0
-#define CONFIG_ALIAS_PIX_ENCODER 0
-#define CONFIG_AMV_ENCODER 0
-#define CONFIG_APNG_ENCODER 0
-#define CONFIG_ASV1_ENCODER 0
-#define CONFIG_ASV2_ENCODER 0
-#define CONFIG_AVRP_ENCODER 0
-#define CONFIG_AVUI_ENCODER 0
-#define CONFIG_AYUV_ENCODER 0
-#define CONFIG_BMP_ENCODER 0
-#define CONFIG_CINEPAK_ENCODER 0
-#define CONFIG_CLJR_ENCODER 0
-#define CONFIG_COMFORTNOISE_ENCODER 0
-#define CONFIG_DNXHD_ENCODER 0
-#define CONFIG_DPX_ENCODER 0
-#define CONFIG_DVVIDEO_ENCODER 0
-#define CONFIG_FFV1_ENCODER 0
-#define CONFIG_FFVHUFF_ENCODER 0
-#define CONFIG_FLASHSV_ENCODER 0
-#define CONFIG_FLASHSV2_ENCODER 0
-#define CONFIG_FLV_ENCODER 0
-#define CONFIG_GIF_ENCODER 0
-#define CONFIG_H261_ENCODER 0
-#define CONFIG_H263_ENCODER 0
-#define CONFIG_H263P_ENCODER 0
-#define CONFIG_HAP_ENCODER 0
-#define CONFIG_HUFFYUV_ENCODER 0
-#define CONFIG_JPEG2000_ENCODER 0
-#define CONFIG_JPEGLS_ENCODER 0
-#define CONFIG_LJPEG_ENCODER 0
-#define CONFIG_MJPEG_ENCODER 0
-#define CONFIG_MPEG1VIDEO_ENCODER 0
-#define CONFIG_MPEG2VIDEO_ENCODER 0
-#define CONFIG_MPEG4_ENCODER 0
-#define CONFIG_MSMPEG4V2_ENCODER 0
-#define CONFIG_MSMPEG4V3_ENCODER 0
-#define CONFIG_MSVIDEO1_ENCODER 0
-#define CONFIG_PAM_ENCODER 0
-#define CONFIG_PBM_ENCODER 0
-#define CONFIG_PCX_ENCODER 0
-#define CONFIG_PGM_ENCODER 0
-#define CONFIG_PGMYUV_ENCODER 0
-#define CONFIG_PNG_ENCODER 0
-#define CONFIG_PPM_ENCODER 0
-#define CONFIG_PRORES_ENCODER 0
-#define CONFIG_PRORES_AW_ENCODER 0
-#define CONFIG_PRORES_KS_ENCODER 0
-#define CONFIG_QTRLE_ENCODER 0
-#define CONFIG_R10K_ENCODER 0
-#define CONFIG_R210_ENCODER 0
-#define CONFIG_RAWVIDEO_ENCODER 0
-#define CONFIG_ROQ_ENCODER 0
-#define CONFIG_RV10_ENCODER 0
-#define CONFIG_RV20_ENCODER 0
-#define CONFIG_S302M_ENCODER 0
-#define CONFIG_SGI_ENCODER 0
-#define CONFIG_SNOW_ENCODER 0
-#define CONFIG_SUNRAST_ENCODER 0
-#define CONFIG_SVQ1_ENCODER 0
-#define CONFIG_TARGA_ENCODER 0
-#define CONFIG_TIFF_ENCODER 0
-#define CONFIG_UTVIDEO_ENCODER 0
-#define CONFIG_V210_ENCODER 0
-#define CONFIG_V308_ENCODER 0
-#define CONFIG_V408_ENCODER 0
-#define CONFIG_V410_ENCODER 0
-#define CONFIG_VC2_ENCODER 0
-#define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-#define CONFIG_WMV1_ENCODER 0
-#define CONFIG_WMV2_ENCODER 0
-#define CONFIG_XBM_ENCODER 0
-#define CONFIG_XFACE_ENCODER 0
-#define CONFIG_XWD_ENCODER 0
-#define CONFIG_Y41P_ENCODER 0
-#define CONFIG_YUV4_ENCODER 0
-#define CONFIG_ZLIB_ENCODER 0
-#define CONFIG_ZMBV_ENCODER 0
-#define CONFIG_AAC_ENCODER 0
-#define CONFIG_AC3_ENCODER 0
-#define CONFIG_AC3_FIXED_ENCODER 0
-#define CONFIG_ALAC_ENCODER 0
-#define CONFIG_DCA_ENCODER 0
-#define CONFIG_EAC3_ENCODER 0
-#define CONFIG_FLAC_ENCODER 0
-#define CONFIG_G723_1_ENCODER 0
-#define CONFIG_MLP_ENCODER 0
-#define CONFIG_MP2_ENCODER 0
-#define CONFIG_MP2FIXED_ENCODER 0
-#define CONFIG_NELLYMOSER_ENCODER 0
-#define CONFIG_RA_144_ENCODER 0
-#define CONFIG_SONIC_ENCODER 0
-#define CONFIG_SONIC_LS_ENCODER 0
-#define CONFIG_TRUEHD_ENCODER 0
-#define CONFIG_TTA_ENCODER 0
-#define CONFIG_VORBIS_ENCODER 0
-#define CONFIG_WAVPACK_ENCODER 0
-#define CONFIG_WMAV1_ENCODER 0
-#define CONFIG_WMAV2_ENCODER 0
-#define CONFIG_PCM_ALAW_ENCODER 0
-#define CONFIG_PCM_F32BE_ENCODER 0
-#define CONFIG_PCM_F32LE_ENCODER 0
-#define CONFIG_PCM_F64BE_ENCODER 0
-#define CONFIG_PCM_F64LE_ENCODER 0
-#define CONFIG_PCM_MULAW_ENCODER 0
-#define CONFIG_PCM_S8_ENCODER 0
-#define CONFIG_PCM_S8_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16BE_ENCODER 0
-#define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16LE_ENCODER 0
-#define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S24BE_ENCODER 0
-#define CONFIG_PCM_S24DAUD_ENCODER 0
-#define CONFIG_PCM_S24LE_ENCODER 0
-#define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S32BE_ENCODER 0
-#define CONFIG_PCM_S32LE_ENCODER 0
-#define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S64BE_ENCODER 0
-#define CONFIG_PCM_S64LE_ENCODER 0
-#define CONFIG_PCM_U8_ENCODER 0
-#define CONFIG_PCM_U16BE_ENCODER 0
-#define CONFIG_PCM_U16LE_ENCODER 0
-#define CONFIG_PCM_U24BE_ENCODER 0
-#define CONFIG_PCM_U24LE_ENCODER 0
-#define CONFIG_PCM_U32BE_ENCODER 0
-#define CONFIG_PCM_U32LE_ENCODER 0
-#define CONFIG_ROQ_DPCM_ENCODER 0
-#define CONFIG_ADPCM_ADX_ENCODER 0
-#define CONFIG_ADPCM_G722_ENCODER 0
-#define CONFIG_ADPCM_G726_ENCODER 0
-#define CONFIG_ADPCM_IMA_QT_ENCODER 0
-#define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-#define CONFIG_ADPCM_MS_ENCODER 0
-#define CONFIG_ADPCM_SWF_ENCODER 0
-#define CONFIG_ADPCM_YAMAHA_ENCODER 0
-#define CONFIG_SSA_ENCODER 0
-#define CONFIG_ASS_ENCODER 0
-#define CONFIG_DVBSUB_ENCODER 0
-#define CONFIG_DVDSUB_ENCODER 0
-#define CONFIG_MOVTEXT_ENCODER 0
-#define CONFIG_SRT_ENCODER 0
-#define CONFIG_SUBRIP_ENCODER 0
-#define CONFIG_TEXT_ENCODER 0
-#define CONFIG_WEBVTT_ENCODER 0
-#define CONFIG_XSUB_ENCODER 0
-#define CONFIG_AAC_AT_ENCODER 0
-#define CONFIG_ALAC_AT_ENCODER 0
-#define CONFIG_ILBC_AT_ENCODER 0
-#define CONFIG_PCM_ALAW_AT_ENCODER 0
-#define CONFIG_PCM_MULAW_AT_ENCODER 0
-#define CONFIG_LIBFDK_AAC_ENCODER 0
-#define CONFIG_LIBGSM_ENCODER 0
-#define CONFIG_LIBGSM_MS_ENCODER 0
-#define CONFIG_LIBILBC_ENCODER 0
-#define CONFIG_LIBMP3LAME_ENCODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-#define CONFIG_LIBOPENJPEG_ENCODER 0
-#define CONFIG_LIBOPUS_ENCODER 0
-#define CONFIG_LIBSCHROEDINGER_ENCODER 0
-#define CONFIG_LIBSHINE_ENCODER 0
-#define CONFIG_LIBSPEEX_ENCODER 0
-#define CONFIG_LIBTHEORA_ENCODER 0
-#define CONFIG_LIBTWOLAME_ENCODER 0
-#define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-#define CONFIG_LIBVORBIS_ENCODER 0
-#define CONFIG_LIBVPX_VP8_ENCODER 0
-#define CONFIG_LIBVPX_VP9_ENCODER 0
-#define CONFIG_LIBWAVPACK_ENCODER 0
-#define CONFIG_LIBWEBP_ANIM_ENCODER 0
-#define CONFIG_LIBWEBP_ENCODER 0
-#define CONFIG_LIBX262_ENCODER 0
-#define CONFIG_LIBX264_ENCODER 0
-#define CONFIG_LIBX264RGB_ENCODER 0
-#define CONFIG_LIBX265_ENCODER 0
-#define CONFIG_LIBXAVS_ENCODER 0
-#define CONFIG_LIBXVID_ENCODER 0
-#define CONFIG_LIBOPENH264_ENCODER 0
-#define CONFIG_H264_NVENC_ENCODER 0
-#define CONFIG_H264_OMX_ENCODER 0
-#define CONFIG_H264_QSV_ENCODER 0
-#define CONFIG_H264_VAAPI_ENCODER 0
-#define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-#define CONFIG_NVENC_ENCODER 0
-#define CONFIG_NVENC_H264_ENCODER 0
-#define CONFIG_NVENC_HEVC_ENCODER 0
-#define CONFIG_HEVC_NVENC_ENCODER 0
-#define CONFIG_HEVC_QSV_ENCODER 0
-#define CONFIG_HEVC_VAAPI_ENCODER 0
-#define CONFIG_LIBKVAZAAR_ENCODER 0
-#define CONFIG_MJPEG_VAAPI_ENCODER 0
-#define CONFIG_MPEG2_QSV_ENCODER 0
-#define CONFIG_ABENCH_FILTER 0
-#define CONFIG_ACOMPRESSOR_FILTER 0
-#define CONFIG_ACROSSFADE_FILTER 0
-#define CONFIG_ACRUSHER_FILTER 0
-#define CONFIG_ADELAY_FILTER 0
-#define CONFIG_AECHO_FILTER 0
-#define CONFIG_AEMPHASIS_FILTER 0
-#define CONFIG_AEVAL_FILTER 0
-#define CONFIG_AFADE_FILTER 0
-#define CONFIG_AFFTFILT_FILTER 0
-#define CONFIG_AFORMAT_FILTER 0
-#define CONFIG_AGATE_FILTER 0
-#define CONFIG_AINTERLEAVE_FILTER 0
-#define CONFIG_ALIMITER_FILTER 0
-#define CONFIG_ALLPASS_FILTER 0
-#define CONFIG_ALOOP_FILTER 0
-#define CONFIG_AMERGE_FILTER 0
-#define CONFIG_AMETADATA_FILTER 0
-#define CONFIG_AMIX_FILTER 0
-#define CONFIG_ANEQUALIZER_FILTER 0
-#define CONFIG_ANULL_FILTER 0
-#define CONFIG_APAD_FILTER 0
-#define CONFIG_APERMS_FILTER 0
-#define CONFIG_APHASER_FILTER 0
-#define CONFIG_APULSATOR_FILTER 0
-#define CONFIG_AREALTIME_FILTER 0
-#define CONFIG_ARESAMPLE_FILTER 0
-#define CONFIG_AREVERSE_FILTER 0
-#define CONFIG_ASELECT_FILTER 0
-#define CONFIG_ASENDCMD_FILTER 0
-#define CONFIG_ASETNSAMPLES_FILTER 0
-#define CONFIG_ASETPTS_FILTER 0
-#define CONFIG_ASETRATE_FILTER 0
-#define CONFIG_ASETTB_FILTER 0
-#define CONFIG_ASHOWINFO_FILTER 0
-#define CONFIG_ASIDEDATA_FILTER 0
-#define CONFIG_ASPLIT_FILTER 0
-#define CONFIG_ASTATS_FILTER 0
-#define CONFIG_ASTREAMSELECT_FILTER 0
-#define CONFIG_ASYNCTS_FILTER 0
-#define CONFIG_ATEMPO_FILTER 0
-#define CONFIG_ATRIM_FILTER 0
-#define CONFIG_AZMQ_FILTER 0
-#define CONFIG_BANDPASS_FILTER 0
-#define CONFIG_BANDREJECT_FILTER 0
-#define CONFIG_BASS_FILTER 0
-#define CONFIG_BIQUAD_FILTER 0
-#define CONFIG_BS2B_FILTER 0
-#define CONFIG_CHANNELMAP_FILTER 0
-#define CONFIG_CHANNELSPLIT_FILTER 0
-#define CONFIG_CHORUS_FILTER 0
-#define CONFIG_COMPAND_FILTER 0
-#define CONFIG_COMPENSATIONDELAY_FILTER 0
-#define CONFIG_CRYSTALIZER_FILTER 0
-#define CONFIG_DCSHIFT_FILTER 0
-#define CONFIG_DYNAUDNORM_FILTER 0
-#define CONFIG_EARWAX_FILTER 0
-#define CONFIG_EBUR128_FILTER 0
-#define CONFIG_EQUALIZER_FILTER 0
-#define CONFIG_EXTRASTEREO_FILTER 0
-#define CONFIG_FIREQUALIZER_FILTER 0
-#define CONFIG_FLANGER_FILTER 0
-#define CONFIG_HDCD_FILTER 0
-#define CONFIG_HIGHPASS_FILTER 0
-#define CONFIG_JOIN_FILTER 0
-#define CONFIG_LADSPA_FILTER 0
-#define CONFIG_LOUDNORM_FILTER 0
-#define CONFIG_LOWPASS_FILTER 0
-#define CONFIG_PAN_FILTER 0
-#define CONFIG_REPLAYGAIN_FILTER 0
-#define CONFIG_RESAMPLE_FILTER 0
-#define CONFIG_RUBBERBAND_FILTER 0
-#define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-#define CONFIG_SIDECHAINGATE_FILTER 0
-#define CONFIG_SILENCEDETECT_FILTER 0
-#define CONFIG_SILENCEREMOVE_FILTER 0
-#define CONFIG_SOFALIZER_FILTER 0
-#define CONFIG_STEREOTOOLS_FILTER 0
-#define CONFIG_STEREOWIDEN_FILTER 0
-#define CONFIG_TREBLE_FILTER 0
-#define CONFIG_TREMOLO_FILTER 0
-#define CONFIG_VIBRATO_FILTER 0
-#define CONFIG_VOLUME_FILTER 0
-#define CONFIG_VOLUMEDETECT_FILTER 0
-#define CONFIG_AEVALSRC_FILTER 0
-#define CONFIG_ANOISESRC_FILTER 0
-#define CONFIG_ANULLSRC_FILTER 0
-#define CONFIG_FLITE_FILTER 0
-#define CONFIG_SINE_FILTER 0
-#define CONFIG_ANULLSINK_FILTER 0
-#define CONFIG_ALPHAEXTRACT_FILTER 0
-#define CONFIG_ALPHAMERGE_FILTER 0
-#define CONFIG_ASS_FILTER 0
-#define CONFIG_ATADENOISE_FILTER 0
-#define CONFIG_AVGBLUR_FILTER 0
-#define CONFIG_BBOX_FILTER 0
-#define CONFIG_BENCH_FILTER 0
-#define CONFIG_BITPLANENOISE_FILTER 0
-#define CONFIG_BLACKDETECT_FILTER 0
-#define CONFIG_BLACKFRAME_FILTER 0
-#define CONFIG_BLEND_FILTER 0
-#define CONFIG_BOXBLUR_FILTER 0
-#define CONFIG_BWDIF_FILTER 0
-#define CONFIG_CHROMAKEY_FILTER 0
-#define CONFIG_CIESCOPE_FILTER 0
-#define CONFIG_CODECVIEW_FILTER 0
-#define CONFIG_COLORBALANCE_FILTER 0
-#define CONFIG_COLORCHANNELMIXER_FILTER 0
-#define CONFIG_COLORKEY_FILTER 0
-#define CONFIG_COLORLEVELS_FILTER 0
-#define CONFIG_COLORMATRIX_FILTER 0
-#define CONFIG_COLORSPACE_FILTER 0
-#define CONFIG_CONVOLUTION_FILTER 0
-#define CONFIG_COPY_FILTER 0
-#define CONFIG_COREIMAGE_FILTER 0
-#define CONFIG_COVER_RECT_FILTER 0
-#define CONFIG_CROP_FILTER 0
-#define CONFIG_CROPDETECT_FILTER 0
-#define CONFIG_CURVES_FILTER 0
-#define CONFIG_DATASCOPE_FILTER 0
-#define CONFIG_DCTDNOIZ_FILTER 0
-#define CONFIG_DEBAND_FILTER 0
-#define CONFIG_DECIMATE_FILTER 0
-#define CONFIG_DEFLATE_FILTER 0
-#define CONFIG_DEJUDDER_FILTER 0
-#define CONFIG_DELOGO_FILTER 0
-#define CONFIG_DESHAKE_FILTER 0
-#define CONFIG_DETELECINE_FILTER 0
-#define CONFIG_DILATION_FILTER 0
-#define CONFIG_DISPLACE_FILTER 0
-#define CONFIG_DRAWBOX_FILTER 0
-#define CONFIG_DRAWGRAPH_FILTER 0
-#define CONFIG_DRAWGRID_FILTER 0
-#define CONFIG_DRAWTEXT_FILTER 0
-#define CONFIG_EDGEDETECT_FILTER 0
-#define CONFIG_ELBG_FILTER 0
-#define CONFIG_EQ_FILTER 0
-#define CONFIG_EROSION_FILTER 0
-#define CONFIG_EXTRACTPLANES_FILTER 0
-#define CONFIG_FADE_FILTER 0
-#define CONFIG_FFTFILT_FILTER 0
-#define CONFIG_FIELD_FILTER 0
-#define CONFIG_FIELDHINT_FILTER 0
-#define CONFIG_FIELDMATCH_FILTER 0
-#define CONFIG_FIELDORDER_FILTER 0
-#define CONFIG_FIND_RECT_FILTER 0
-#define CONFIG_FORMAT_FILTER 0
-#define CONFIG_FPS_FILTER 0
-#define CONFIG_FRAMEPACK_FILTER 0
-#define CONFIG_FRAMERATE_FILTER 0
-#define CONFIG_FRAMESTEP_FILTER 0
-#define CONFIG_FREI0R_FILTER 0
-#define CONFIG_FSPP_FILTER 0
-#define CONFIG_GBLUR_FILTER 0
-#define CONFIG_GEQ_FILTER 0
-#define CONFIG_GRADFUN_FILTER 0
-#define CONFIG_HALDCLUT_FILTER 0
-#define CONFIG_HFLIP_FILTER 0
-#define CONFIG_HISTEQ_FILTER 0
-#define CONFIG_HISTOGRAM_FILTER 0
-#define CONFIG_HQDN3D_FILTER 0
-#define CONFIG_HQX_FILTER 0
-#define CONFIG_HSTACK_FILTER 0
-#define CONFIG_HUE_FILTER 0
-#define CONFIG_HWDOWNLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_CUDA_FILTER 0
-#define CONFIG_HYSTERESIS_FILTER 0
-#define CONFIG_IDET_FILTER 0
-#define CONFIG_IL_FILTER 0
-#define CONFIG_INFLATE_FILTER 0
-#define CONFIG_INTERLACE_FILTER 0
-#define CONFIG_INTERLEAVE_FILTER 0
-#define CONFIG_KERNDEINT_FILTER 0
-#define CONFIG_LENSCORRECTION_FILTER 0
-#define CONFIG_LOOP_FILTER 0
-#define CONFIG_LUT_FILTER 0
-#define CONFIG_LUT2_FILTER 0
-#define CONFIG_LUT3D_FILTER 0
-#define CONFIG_LUTRGB_FILTER 0
-#define CONFIG_LUTYUV_FILTER 0
-#define CONFIG_MASKEDCLAMP_FILTER 0
-#define CONFIG_MASKEDMERGE_FILTER 0
-#define CONFIG_MCDEINT_FILTER 0
-#define CONFIG_MERGEPLANES_FILTER 0
-#define CONFIG_MESTIMATE_FILTER 0
-#define CONFIG_METADATA_FILTER 0
-#define CONFIG_MINTERPOLATE_FILTER 0
-#define CONFIG_MPDECIMATE_FILTER 0
-#define CONFIG_NEGATE_FILTER 0
-#define CONFIG_NLMEANS_FILTER 0
-#define CONFIG_NNEDI_FILTER 0
-#define CONFIG_NOFORMAT_FILTER 0
-#define CONFIG_NOISE_FILTER 0
-#define CONFIG_NULL_FILTER 0
-#define CONFIG_OCR_FILTER 0
-#define CONFIG_OCV_FILTER 0
-#define CONFIG_OVERLAY_FILTER 0
-#define CONFIG_OWDENOISE_FILTER 0
-#define CONFIG_PAD_FILTER 0
-#define CONFIG_PALETTEGEN_FILTER 0
-#define CONFIG_PALETTEUSE_FILTER 0
-#define CONFIG_PERMS_FILTER 0
-#define CONFIG_PERSPECTIVE_FILTER 0
-#define CONFIG_PHASE_FILTER 0
-#define CONFIG_PIXDESCTEST_FILTER 0
-#define CONFIG_PP_FILTER 0
-#define CONFIG_PP7_FILTER 0
-#define CONFIG_PREWITT_FILTER 0
-#define CONFIG_PSNR_FILTER 0
-#define CONFIG_PULLUP_FILTER 0
-#define CONFIG_QP_FILTER 0
-#define CONFIG_RANDOM_FILTER 0
-#define CONFIG_READVITC_FILTER 0
-#define CONFIG_REALTIME_FILTER 0
-#define CONFIG_REMAP_FILTER 0
-#define CONFIG_REMOVEGRAIN_FILTER 0
-#define CONFIG_REMOVELOGO_FILTER 0
-#define CONFIG_REPEATFIELDS_FILTER 0
-#define CONFIG_REVERSE_FILTER 0
-#define CONFIG_ROTATE_FILTER 0
-#define CONFIG_SAB_FILTER 0
-#define CONFIG_SCALE_FILTER 0
-#define CONFIG_SCALE_NPP_FILTER 0
-#define CONFIG_SCALE_VAAPI_FILTER 0
-#define CONFIG_SCALE2REF_FILTER 0
-#define CONFIG_SELECT_FILTER 0
-#define CONFIG_SELECTIVECOLOR_FILTER 0
-#define CONFIG_SENDCMD_FILTER 0
-#define CONFIG_SEPARATEFIELDS_FILTER 0
-#define CONFIG_SETDAR_FILTER 0
-#define CONFIG_SETFIELD_FILTER 0
-#define CONFIG_SETPTS_FILTER 0
-#define CONFIG_SETSAR_FILTER 0
-#define CONFIG_SETTB_FILTER 0
-#define CONFIG_SHOWINFO_FILTER 0
-#define CONFIG_SHOWPALETTE_FILTER 0
-#define CONFIG_SHUFFLEFRAMES_FILTER 0
-#define CONFIG_SHUFFLEPLANES_FILTER 0
-#define CONFIG_SIDEDATA_FILTER 0
-#define CONFIG_SIGNALSTATS_FILTER 0
-#define CONFIG_SMARTBLUR_FILTER 0
-#define CONFIG_SOBEL_FILTER 0
-#define CONFIG_SPLIT_FILTER 0
-#define CONFIG_SPP_FILTER 0
-#define CONFIG_SSIM_FILTER 0
-#define CONFIG_STEREO3D_FILTER 0
-#define CONFIG_STREAMSELECT_FILTER 0
-#define CONFIG_SUBTITLES_FILTER 0
-#define CONFIG_SUPER2XSAI_FILTER 0
-#define CONFIG_SWAPRECT_FILTER 0
-#define CONFIG_SWAPUV_FILTER 0
-#define CONFIG_TBLEND_FILTER 0
-#define CONFIG_TELECINE_FILTER 0
-#define CONFIG_THUMBNAIL_FILTER 0
-#define CONFIG_TILE_FILTER 0
-#define CONFIG_TINTERLACE_FILTER 0
-#define CONFIG_TRANSPOSE_FILTER 0
-#define CONFIG_TRIM_FILTER 0
-#define CONFIG_UNSHARP_FILTER 0
-#define CONFIG_USPP_FILTER 0
-#define CONFIG_VAGUEDENOISER_FILTER 0
-#define CONFIG_VECTORSCOPE_FILTER 0
-#define CONFIG_VFLIP_FILTER 0
-#define CONFIG_VIDSTABDETECT_FILTER 0
-#define CONFIG_VIDSTABTRANSFORM_FILTER 0
-#define CONFIG_VIGNETTE_FILTER 0
-#define CONFIG_VSTACK_FILTER 0
-#define CONFIG_W3FDIF_FILTER 0
-#define CONFIG_WAVEFORM_FILTER 0
-#define CONFIG_WEAVE_FILTER 0
-#define CONFIG_XBR_FILTER 0
-#define CONFIG_YADIF_FILTER 0
-#define CONFIG_ZMQ_FILTER 0
-#define CONFIG_ZOOMPAN_FILTER 0
-#define CONFIG_ZSCALE_FILTER 0
-#define CONFIG_ALLRGB_FILTER 0
-#define CONFIG_ALLYUV_FILTER 0
-#define CONFIG_CELLAUTO_FILTER 0
-#define CONFIG_COLOR_FILTER 0
-#define CONFIG_COREIMAGESRC_FILTER 0
-#define CONFIG_FREI0R_SRC_FILTER 0
-#define CONFIG_HALDCLUTSRC_FILTER 0
-#define CONFIG_LIFE_FILTER 0
-#define CONFIG_MANDELBROT_FILTER 0
-#define CONFIG_MPTESTSRC_FILTER 0
-#define CONFIG_NULLSRC_FILTER 0
-#define CONFIG_RGBTESTSRC_FILTER 0
-#define CONFIG_SMPTEBARS_FILTER 0
-#define CONFIG_SMPTEHDBARS_FILTER 0
-#define CONFIG_TESTSRC_FILTER 0
-#define CONFIG_TESTSRC2_FILTER 0
-#define CONFIG_YUVTESTSRC_FILTER 0
-#define CONFIG_NULLSINK_FILTER 0
-#define CONFIG_ADRAWGRAPH_FILTER 0
-#define CONFIG_AHISTOGRAM_FILTER 0
-#define CONFIG_APHASEMETER_FILTER 0
-#define CONFIG_AVECTORSCOPE_FILTER 0
-#define CONFIG_CONCAT_FILTER 0
-#define CONFIG_SHOWCQT_FILTER 0
-#define CONFIG_SHOWFREQS_FILTER 0
-#define CONFIG_SHOWSPECTRUM_FILTER 0
-#define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-#define CONFIG_SHOWVOLUME_FILTER 0
-#define CONFIG_SHOWWAVES_FILTER 0
-#define CONFIG_SHOWWAVESPIC_FILTER 0
-#define CONFIG_SPECTRUMSYNTH_FILTER 0
-#define CONFIG_AMOVIE_FILTER 0
-#define CONFIG_MOVIE_FILTER 0
-#define CONFIG_H263_CUVID_HWACCEL 0
-#define CONFIG_H263_VAAPI_HWACCEL 0
-#define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_H264_CUVID_HWACCEL 0
-#define CONFIG_H264_D3D11VA_HWACCEL 0
-#define CONFIG_H264_DXVA2_HWACCEL 0
-#define CONFIG_H264_MEDIACODEC_HWACCEL 0
-#define CONFIG_H264_MMAL_HWACCEL 0
-#define CONFIG_H264_QSV_HWACCEL 0
-#define CONFIG_H264_VAAPI_HWACCEL 0
-#define CONFIG_H264_VDA_HWACCEL 0
-#define CONFIG_H264_VDA_OLD_HWACCEL 0
-#define CONFIG_H264_VDPAU_HWACCEL 0
-#define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_HEVC_CUVID_HWACCEL 0
-#define CONFIG_HEVC_D3D11VA_HWACCEL 0
-#define CONFIG_HEVC_DXVA2_HWACCEL 0
-#define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-#define CONFIG_HEVC_QSV_HWACCEL 0
-#define CONFIG_HEVC_VAAPI_HWACCEL 0
-#define CONFIG_HEVC_VDPAU_HWACCEL 0
-#define CONFIG_MJPEG_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_XVMC_HWACCEL 0
-#define CONFIG_MPEG1_VDPAU_HWACCEL 0
-#define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG2_CUVID_HWACCEL 0
-#define CONFIG_MPEG2_XVMC_HWACCEL 0
-#define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-#define CONFIG_MPEG2_DXVA2_HWACCEL 0
-#define CONFIG_MPEG2_MMAL_HWACCEL 0
-#define CONFIG_MPEG2_QSV_HWACCEL 0
-#define CONFIG_MPEG2_VAAPI_HWACCEL 0
-#define CONFIG_MPEG2_VDPAU_HWACCEL 0
-#define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG4_CUVID_HWACCEL 0
-#define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-#define CONFIG_MPEG4_MMAL_HWACCEL 0
-#define CONFIG_MPEG4_VAAPI_HWACCEL 0
-#define CONFIG_MPEG4_VDPAU_HWACCEL 0
-#define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_VC1_CUVID_HWACCEL 0
-#define CONFIG_VC1_D3D11VA_HWACCEL 0
-#define CONFIG_VC1_DXVA2_HWACCEL 0
-#define CONFIG_VC1_VAAPI_HWACCEL 0
-#define CONFIG_VC1_VDPAU_HWACCEL 0
-#define CONFIG_VC1_MMAL_HWACCEL 0
-#define CONFIG_VC1_QSV_HWACCEL 0
-#define CONFIG_VP8_CUVID_HWACCEL 0
-#define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_CUVID_HWACCEL 0
-#define CONFIG_VP9_D3D11VA_HWACCEL 0
-#define CONFIG_VP9_DXVA2_HWACCEL 0
-#define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_D3D11VA_HWACCEL 0
-#define CONFIG_WMV3_DXVA2_HWACCEL 0
-#define CONFIG_WMV3_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_VDPAU_HWACCEL 0
-#define CONFIG_ALSA_INDEV 0
-#define CONFIG_AVFOUNDATION_INDEV 0
-#define CONFIG_BKTR_INDEV 0
-#define CONFIG_DECKLINK_INDEV 0
-#define CONFIG_DSHOW_INDEV 0
-#define CONFIG_DV1394_INDEV 0
-#define CONFIG_FBDEV_INDEV 0
-#define CONFIG_GDIGRAB_INDEV 0
-#define CONFIG_IEC61883_INDEV 0
-#define CONFIG_JACK_INDEV 0
-#define CONFIG_LAVFI_INDEV 0
-#define CONFIG_OPENAL_INDEV 0
-#define CONFIG_OSS_INDEV 0
-#define CONFIG_PULSE_INDEV 0
-#define CONFIG_QTKIT_INDEV 0
-#define CONFIG_SNDIO_INDEV 0
-#define CONFIG_V4L2_INDEV 0
-#define CONFIG_VFWCAP_INDEV 0
-#define CONFIG_X11GRAB_INDEV 0
-#define CONFIG_X11GRAB_XCB_INDEV 0
-#define CONFIG_LIBCDIO_INDEV 0
-#define CONFIG_LIBDC1394_INDEV 0
-#define CONFIG_A64_MUXER 0
-#define CONFIG_AC3_MUXER 0
-#define CONFIG_ADTS_MUXER 0
-#define CONFIG_ADX_MUXER 0
-#define CONFIG_AIFF_MUXER 0
-#define CONFIG_AMR_MUXER 0
-#define CONFIG_APNG_MUXER 0
-#define CONFIG_ASF_MUXER 0
-#define CONFIG_ASS_MUXER 0
-#define CONFIG_AST_MUXER 0
-#define CONFIG_ASF_STREAM_MUXER 0
-#define CONFIG_AU_MUXER 0
-#define CONFIG_AVI_MUXER 0
-#define CONFIG_AVM2_MUXER 0
-#define CONFIG_BIT_MUXER 0
-#define CONFIG_CAF_MUXER 0
-#define CONFIG_CAVSVIDEO_MUXER 0
-#define CONFIG_CRC_MUXER 0
-#define CONFIG_DASH_MUXER 0
-#define CONFIG_DATA_MUXER 0
-#define CONFIG_DAUD_MUXER 0
-#define CONFIG_DIRAC_MUXER 0
-#define CONFIG_DNXHD_MUXER 0
-#define CONFIG_DTS_MUXER 0
-#define CONFIG_DV_MUXER 0
-#define CONFIG_EAC3_MUXER 0
-#define CONFIG_F4V_MUXER 0
-#define CONFIG_FFM_MUXER 0
-#define CONFIG_FFMETADATA_MUXER 0
-#define CONFIG_FIFO_MUXER 0
-#define CONFIG_FILMSTRIP_MUXER 0
-#define CONFIG_FLAC_MUXER 0
-#define CONFIG_FLV_MUXER 0
-#define CONFIG_FRAMECRC_MUXER 0
-#define CONFIG_FRAMEHASH_MUXER 0
-#define CONFIG_FRAMEMD5_MUXER 0
-#define CONFIG_G722_MUXER 0
-#define CONFIG_G723_1_MUXER 0
-#define CONFIG_GIF_MUXER 0
-#define CONFIG_GSM_MUXER 0
-#define CONFIG_GXF_MUXER 0
-#define CONFIG_H261_MUXER 0
-#define CONFIG_H263_MUXER 0
-#define CONFIG_H264_MUXER 0
-#define CONFIG_HASH_MUXER 0
-#define CONFIG_HDS_MUXER 0
-#define CONFIG_HEVC_MUXER 0
-#define CONFIG_HLS_MUXER 0
-#define CONFIG_ICO_MUXER 0
-#define CONFIG_ILBC_MUXER 0
-#define CONFIG_IMAGE2_MUXER 0
-#define CONFIG_IMAGE2PIPE_MUXER 0
-#define CONFIG_IPOD_MUXER 0
-#define CONFIG_IRCAM_MUXER 0
-#define CONFIG_ISMV_MUXER 0
-#define CONFIG_IVF_MUXER 0
-#define CONFIG_JACOSUB_MUXER 0
-#define CONFIG_LATM_MUXER 0
-#define CONFIG_LRC_MUXER 0
-#define CONFIG_M4V_MUXER 0
-#define CONFIG_MD5_MUXER 0
-#define CONFIG_MATROSKA_MUXER 0
-#define CONFIG_MATROSKA_AUDIO_MUXER 0
-#define CONFIG_MICRODVD_MUXER 0
-#define CONFIG_MJPEG_MUXER 0
-#define CONFIG_MLP_MUXER 0
-#define CONFIG_MMF_MUXER 0
-#define CONFIG_MOV_MUXER 0
-#define CONFIG_MP2_MUXER 0
-#define CONFIG_MP3_MUXER 0
-#define CONFIG_MP4_MUXER 0
-#define CONFIG_MPEG1SYSTEM_MUXER 0
-#define CONFIG_MPEG1VCD_MUXER 0
-#define CONFIG_MPEG1VIDEO_MUXER 0
-#define CONFIG_MPEG2DVD_MUXER 0
-#define CONFIG_MPEG2SVCD_MUXER 0
-#define CONFIG_MPEG2VIDEO_MUXER 0
-#define CONFIG_MPEG2VOB_MUXER 0
-#define CONFIG_MPEGTS_MUXER 0
-#define CONFIG_MPJPEG_MUXER 0
-#define CONFIG_MXF_MUXER 0
-#define CONFIG_MXF_D10_MUXER 0
-#define CONFIG_MXF_OPATOM_MUXER 0
-#define CONFIG_NULL_MUXER 0
-#define CONFIG_NUT_MUXER 0
-#define CONFIG_OGA_MUXER 0
-#define CONFIG_OGG_MUXER 0
-#define CONFIG_OGV_MUXER 0
-#define CONFIG_OMA_MUXER 0
-#define CONFIG_OPUS_MUXER 0
-#define CONFIG_PCM_ALAW_MUXER 0
-#define CONFIG_PCM_MULAW_MUXER 0
-#define CONFIG_PCM_F64BE_MUXER 0
-#define CONFIG_PCM_F64LE_MUXER 0
-#define CONFIG_PCM_F32BE_MUXER 0
-#define CONFIG_PCM_F32LE_MUXER 0
-#define CONFIG_PCM_S32BE_MUXER 0
-#define CONFIG_PCM_S32LE_MUXER 0
-#define CONFIG_PCM_S24BE_MUXER 0
-#define CONFIG_PCM_S24LE_MUXER 0
-#define CONFIG_PCM_S16BE_MUXER 0
-#define CONFIG_PCM_S16LE_MUXER 0
-#define CONFIG_PCM_S8_MUXER 0
-#define CONFIG_PCM_U32BE_MUXER 0
-#define CONFIG_PCM_U32LE_MUXER 0
-#define CONFIG_PCM_U24BE_MUXER 0
-#define CONFIG_PCM_U24LE_MUXER 0
-#define CONFIG_PCM_U16BE_MUXER 0
-#define CONFIG_PCM_U16LE_MUXER 0
-#define CONFIG_PCM_U8_MUXER 0
-#define CONFIG_PSP_MUXER 0
-#define CONFIG_RAWVIDEO_MUXER 0
-#define CONFIG_RM_MUXER 0
-#define CONFIG_ROQ_MUXER 0
-#define CONFIG_RSO_MUXER 0
-#define CONFIG_RTP_MUXER 0
-#define CONFIG_RTP_MPEGTS_MUXER 0
-#define CONFIG_RTSP_MUXER 0
-#define CONFIG_SAP_MUXER 0
-#define CONFIG_SEGMENT_MUXER 0
-#define CONFIG_STREAM_SEGMENT_MUXER 0
-#define CONFIG_SINGLEJPEG_MUXER 0
-#define CONFIG_SMJPEG_MUXER 0
-#define CONFIG_SMOOTHSTREAMING_MUXER 0
-#define CONFIG_SOX_MUXER 0
-#define CONFIG_SPX_MUXER 0
-#define CONFIG_SPDIF_MUXER 0
-#define CONFIG_SRT_MUXER 0
-#define CONFIG_SWF_MUXER 0
-#define CONFIG_TEE_MUXER 0
-#define CONFIG_TG2_MUXER 0
-#define CONFIG_TGP_MUXER 0
-#define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-#define CONFIG_TRUEHD_MUXER 0
-#define CONFIG_TTA_MUXER 0
-#define CONFIG_UNCODEDFRAMECRC_MUXER 0
-#define CONFIG_VC1_MUXER 0
-#define CONFIG_VC1T_MUXER 0
-#define CONFIG_VOC_MUXER 0
-#define CONFIG_W64_MUXER 0
-#define CONFIG_WAV_MUXER 0
-#define CONFIG_WEBM_MUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-#define CONFIG_WEBM_CHUNK_MUXER 0
-#define CONFIG_WEBP_MUXER 0
-#define CONFIG_WEBVTT_MUXER 0
-#define CONFIG_WTV_MUXER 0
-#define CONFIG_WV_MUXER 0
-#define CONFIG_YUV4MPEGPIPE_MUXER 0
-#define CONFIG_CHROMAPRINT_MUXER 0
-#define CONFIG_LIBNUT_MUXER 0
-#define CONFIG_ALSA_OUTDEV 0
-#define CONFIG_CACA_OUTDEV 0
-#define CONFIG_DECKLINK_OUTDEV 0
-#define CONFIG_FBDEV_OUTDEV 0
-#define CONFIG_OPENGL_OUTDEV 0
-#define CONFIG_OSS_OUTDEV 0
-#define CONFIG_PULSE_OUTDEV 0
-#define CONFIG_SDL2_OUTDEV 0
-#define CONFIG_SNDIO_OUTDEV 0
-#define CONFIG_V4L2_OUTDEV 0
-#define CONFIG_XV_OUTDEV 0
-#define CONFIG_AAC_PARSER 0
-#define CONFIG_AAC_LATM_PARSER 0
-#define CONFIG_AC3_PARSER 0
-#define CONFIG_ADX_PARSER 0
-#define CONFIG_BMP_PARSER 0
-#define CONFIG_CAVSVIDEO_PARSER 0
-#define CONFIG_COOK_PARSER 0
-#define CONFIG_DCA_PARSER 0
-#define CONFIG_DIRAC_PARSER 0
-#define CONFIG_DNXHD_PARSER 0
-#define CONFIG_DPX_PARSER 0
-#define CONFIG_DVAUDIO_PARSER 0
-#define CONFIG_DVBSUB_PARSER 0
-#define CONFIG_DVDSUB_PARSER 0
-#define CONFIG_DVD_NAV_PARSER 0
#define CONFIG_FLAC_PARSER 1
-#define CONFIG_G729_PARSER 0
-#define CONFIG_GSM_PARSER 0
-#define CONFIG_H261_PARSER 0
-#define CONFIG_H263_PARSER 0
-#define CONFIG_H264_PARSER 0
-#define CONFIG_HEVC_PARSER 0
-#define CONFIG_MJPEG_PARSER 0
-#define CONFIG_MLP_PARSER 0
-#define CONFIG_MPEG4VIDEO_PARSER 0
-#define CONFIG_MPEGAUDIO_PARSER 0
-#define CONFIG_MPEGVIDEO_PARSER 0
-#define CONFIG_OPUS_PARSER 0
-#define CONFIG_PNG_PARSER 0
-#define CONFIG_PNM_PARSER 0
-#define CONFIG_RV30_PARSER 0
-#define CONFIG_RV40_PARSER 0
-#define CONFIG_TAK_PARSER 0
-#define CONFIG_VC1_PARSER 0
-#define CONFIG_VORBIS_PARSER 0
-#define CONFIG_VP3_PARSER 0
#define CONFIG_VP8_PARSER 1
#define CONFIG_VP9_PARSER 1
-#define CONFIG_ASYNC_PROTOCOL 0
-#define CONFIG_BLURAY_PROTOCOL 0
-#define CONFIG_CACHE_PROTOCOL 0
-#define CONFIG_CONCAT_PROTOCOL 0
-#define CONFIG_CRYPTO_PROTOCOL 0
-#define CONFIG_DATA_PROTOCOL 0
-#define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-#define CONFIG_FFRTMPHTTP_PROTOCOL 0
-#define CONFIG_FILE_PROTOCOL 0
-#define CONFIG_FTP_PROTOCOL 0
-#define CONFIG_GOPHER_PROTOCOL 0
-#define CONFIG_HLS_PROTOCOL 0
-#define CONFIG_HTTP_PROTOCOL 0
-#define CONFIG_HTTPPROXY_PROTOCOL 0
-#define CONFIG_HTTPS_PROTOCOL 0
-#define CONFIG_ICECAST_PROTOCOL 0
-#define CONFIG_MMSH_PROTOCOL 0
-#define CONFIG_MMST_PROTOCOL 0
-#define CONFIG_MD5_PROTOCOL 0
-#define CONFIG_PIPE_PROTOCOL 0
-#define CONFIG_RTMP_PROTOCOL 0
-#define CONFIG_RTMPE_PROTOCOL 0
-#define CONFIG_RTMPS_PROTOCOL 0
-#define CONFIG_RTMPT_PROTOCOL 0
-#define CONFIG_RTMPTE_PROTOCOL 0
-#define CONFIG_RTMPTS_PROTOCOL 0
-#define CONFIG_RTP_PROTOCOL 0
-#define CONFIG_SCTP_PROTOCOL 0
-#define CONFIG_SRTP_PROTOCOL 0
-#define CONFIG_SUBFILE_PROTOCOL 0
-#define CONFIG_TEE_PROTOCOL 0
-#define CONFIG_TCP_PROTOCOL 0
-#define CONFIG_TLS_GNUTLS_PROTOCOL 0
-#define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-#define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-#define CONFIG_TLS_OPENSSL_PROTOCOL 0
-#define CONFIG_UDP_PROTOCOL 0
-#define CONFIG_UDPLITE_PROTOCOL 0
-#define CONFIG_UNIX_PROTOCOL 0
-#define CONFIG_LIBRTMP_PROTOCOL 0
-#define CONFIG_LIBRTMPE_PROTOCOL 0
-#define CONFIG_LIBRTMPS_PROTOCOL 0
-#define CONFIG_LIBRTMPT_PROTOCOL 0
-#define CONFIG_LIBRTMPTE_PROTOCOL 0
-#define CONFIG_LIBSSH_PROTOCOL 0
-#define CONFIG_LIBSMBCLIENT_PROTOCOL 0
#endif /* FFMPEG_CONFIG_H */
diff --git a/media/ffvpx/config_darwin64.asm b/media/ffvpx/config_darwin64.asm
index 0e386ee14..7eccf378e 100644
--- a/media/ffvpx/config_darwin64.asm
+++ b/media/ffvpx/config_darwin64.asm
@@ -63,8 +63,8 @@
%define HAVE_MIPSDSP 0
%define HAVE_MIPSDSPR2 0
%define HAVE_MSA 0
-%define HAVE_LOONGSON2 1
-%define HAVE_LOONGSON3 1
+%define HAVE_LOONGSON2 0
+%define HAVE_LOONGSON3 0
%define HAVE_MMI 0
%define HAVE_ARMV5TE_EXTERNAL 0
%define HAVE_ARMV6_EXTERNAL 0
@@ -162,32 +162,33 @@
%define HAVE_LOCAL_ALIGNED_16 1
%define HAVE_LOCAL_ALIGNED_32 1
%define HAVE_SIMD_ALIGN_16 1
+%define HAVE_SIMD_ALIGN_32 1
%define HAVE_ATOMICS_GCC 1
%define HAVE_ATOMICS_SUNCC 0
%define HAVE_ATOMICS_WIN32 0
%define HAVE_ATOMIC_CAS_PTR 0
-%define HAVE_ATOMIC_COMPARE_EXCHANGE 1
%define HAVE_MACHINE_RW_BARRIER 0
%define HAVE_MEMORYBARRIER 0
%define HAVE_MM_EMPTY 1
%define HAVE_RDTSC 0
%define HAVE_SARESTART 1
-%define HAVE_SEM_TIMEDWAIT 1
+%define HAVE_SEM_TIMEDWAIT 0
%define HAVE_SYNC_VAL_COMPARE_AND_SWAP 1
%define HAVE_CABS 1
%define HAVE_CEXP 1
%define HAVE_INLINE_ASM 1
%define HAVE_SYMVER 1
-%define HAVE_YASM 1
+%define HAVE_X86ASM 1
%define HAVE_BIGENDIAN 0
%define HAVE_FAST_UNALIGNED 1
-%define HAVE_ALSA_ASOUNDLIB_H 0
%define HAVE_ALTIVEC_H 0
%define HAVE_ARPA_INET_H 1
%define HAVE_ASM_TYPES_H 0
%define HAVE_CDIO_PARANOIA_H 0
%define HAVE_CDIO_PARANOIA_PARANOIA_H 0
-%define HAVE_DISPATCH_DISPATCH_H 0
+%define HAVE_CUDA_H 0
+%define HAVE_D3D11_H 0
+%define HAVE_DISPATCH_DISPATCH_H 1
%define HAVE_DEV_BKTR_IOCTL_BT848_H 0
%define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
%define HAVE_DEV_IC_BT8XX_H 0
@@ -196,7 +197,7 @@
%define HAVE_DIRECT_H 0
%define HAVE_DIRENT_H 1
%define HAVE_DLFCN_H 1
-%define HAVE_D3D11_H 0
+%define HAVE_DXGIDEBUG_H 0
%define HAVE_DXVA_H 0
%define HAVE_ES2_GL_H 0
%define HAVE_GSM_H 0
@@ -205,13 +206,15 @@
%define HAVE_MACHINE_IOCTL_BT848_H 0
%define HAVE_MACHINE_IOCTL_METEOR_H 0
%define HAVE_OPENCV2_CORE_CORE_C_H 0
+%define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+%define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
%define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
%define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
%define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
%define HAVE_OPENGL_GL3_H 0
%define HAVE_POLL_H 1
-%define HAVE_SNDIO_H 0
%define HAVE_SOUNDCARD_H 0
+%define HAVE_STDATOMIC_H 1
%define HAVE_SYS_MMAN_H 1
%define HAVE_SYS_PARAM_H 1
%define HAVE_SYS_RESOURCE_H 1
@@ -258,12 +261,11 @@
%define HAVE_TRUNCF 1
%define HAVE_ACCESS 1
%define HAVE_ALIGNED_MALLOC 0
-%define HAVE_CLOCK_GETTIME 0
+%define HAVE_CLOCK_GETTIME 1
%define HAVE_CLOSESOCKET 0
%define HAVE_COMMANDLINETOARGVW 0
%define HAVE_COTASKMEMFREE 0
%define HAVE_CRYPTGENRANDOM 0
-%define HAVE_DLOPEN 1
%define HAVE_FCNTL 1
%define HAVE_FLT_LIM 1
%define HAVE_FORK 1
@@ -304,18 +306,20 @@
%define HAVE_SYSCONF 1
%define HAVE_SYSCTL 1
%define HAVE_USLEEP 1
-%define HAVE_UTGETOSTYPEFROMSTRING 1
+%define HAVE_UTGETOSTYPEFROMSTRING 0
%define HAVE_VIRTUALALLOC 0
%define HAVE_WGLGETPROCADDRESS 0
%define HAVE_PTHREADS 1
%define HAVE_OS2THREADS 0
%define HAVE_W32THREADS 0
%define HAVE_AS_DN_DIRECTIVE 0
+%define HAVE_AS_FPU_DIRECTIVE 0
%define HAVE_AS_FUNC 0
%define HAVE_AS_OBJECT_ARCH 0
%define HAVE_ASM_MOD_Q 0
%define HAVE_ATTRIBUTE_MAY_ALIAS 1
%define HAVE_ATTRIBUTE_PACKED 1
+%define HAVE_BLOCKS_EXTENSION 1
%define HAVE_EBP_AVAILABLE 1
%define HAVE_EBX_AVAILABLE 1
%define HAVE_GNU_AS 0
@@ -332,6 +336,7 @@
%define HAVE_XFORM_ASM 0
%define HAVE_XMM_CLOBBERS 1
%define HAVE_CONDITION_VARIABLE_PTR 0
+%define HAVE_KCMVIDEOCODECTYPE_HEVC 0
%define HAVE_SOCKLEN_T 1
%define HAVE_STRUCT_ADDRINFO 1
%define HAVE_STRUCT_GROUP_SOURCE_REQ 1
@@ -348,50 +353,38 @@
%define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 0
%define HAVE_ATOMICS_NATIVE 1
%define HAVE_DOS_PATHS 0
-%define HAVE_DXVA2_LIB 0
-%define HAVE_DXVA2API_COBJ 0
%define HAVE_LIBC_MSVCRT 0
-%define HAVE_LIBDC1394_1 0
-%define HAVE_LIBDC1394_2 0
%define HAVE_MAKEINFO 1
-%define HAVE_MAKEINFO_HTML 1
+%define HAVE_MAKEINFO_HTML 0
%define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
%define HAVE_PERL 1
%define HAVE_POD2MAN 1
-%define HAVE_SDL2 0
%define HAVE_SECTION_DATA_REL_RO 0
%define HAVE_TEXI2HTML 0
%define HAVE_THREADS 1
+%define HAVE_UWP 0
%define HAVE_VAAPI_DRM 0
%define HAVE_VAAPI_X11 0
%define HAVE_VDPAU_X11 0
%define HAVE_WINRT 0
-%define HAVE_XLIB 0
-%define CONFIG_BSFS 0
-%define CONFIG_DECODERS 1
-%define CONFIG_ENCODERS 0
-%define CONFIG_HWACCELS 0
-%define CONFIG_PARSERS 1
-%define CONFIG_INDEVS 0
-%define CONFIG_OUTDEVS 0
-%define CONFIG_FILTERS 0
-%define CONFIG_DEMUXERS 0
-%define CONFIG_MUXERS 0
-%define CONFIG_PROTOCOLS 0
%define CONFIG_DOC 0
-%define CONFIG_HTMLPAGES 1
+%define CONFIG_HTMLPAGES 0
%define CONFIG_MANPAGES 1
%define CONFIG_PODPAGES 1
%define CONFIG_TXTPAGES 1
%define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
%define CONFIG_AVIO_READING_EXAMPLE 1
-%define CONFIG_DECODING_ENCODING_EXAMPLE 0
+%define CONFIG_DECODE_AUDIO_EXAMPLE 1
+%define CONFIG_DECODE_VIDEO_EXAMPLE 1
%define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+%define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+%define CONFIG_ENCODE_VIDEO_EXAMPLE 1
%define CONFIG_EXTRACT_MVS_EXAMPLE 0
%define CONFIG_FILTER_AUDIO_EXAMPLE 0
%define CONFIG_FILTERING_AUDIO_EXAMPLE 0
%define CONFIG_FILTERING_VIDEO_EXAMPLE 0
%define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+%define CONFIG_HW_DECODE_EXAMPLE 0
%define CONFIG_METADATA_EXAMPLE 0
%define CONFIG_MUXING_EXAMPLE 0
%define CONFIG_QSVDEC_EXAMPLE 0
@@ -400,27 +393,55 @@
%define CONFIG_SCALING_VIDEO_EXAMPLE 0
%define CONFIG_TRANSCODE_AAC_EXAMPLE 0
%define CONFIG_TRANSCODING_EXAMPLE 0
+%define CONFIG_ALSA 0
+%define CONFIG_APPKIT 1
+%define CONFIG_AVFOUNDATION 1
+%define CONFIG_BZLIB 1
+%define CONFIG_COREIMAGE 1
+%define CONFIG_ICONV 0
+%define CONFIG_JACK 0
+%define CONFIG_LIBXCB 0
+%define CONFIG_LIBXCB_SHM 0
+%define CONFIG_LIBXCB_SHAPE 0
+%define CONFIG_LIBXCB_XFIXES 0
+%define CONFIG_LZMA 0
+%define CONFIG_SCHANNEL 0
+%define CONFIG_SDL2 0
+%define CONFIG_SECURETRANSPORT 0
+%define CONFIG_SNDIO 0
+%define CONFIG_XLIB 1
+%define CONFIG_ZLIB 1
%define CONFIG_AVISYNTH 0
-%define CONFIG_BZLIB 0
-%define CONFIG_CHROMAPRINT 0
-%define CONFIG_CRYSTALHD 0
-%define CONFIG_DECKLINK 0
%define CONFIG_FREI0R 0
-%define CONFIG_GCRYPT 0
+%define CONFIG_LIBCDIO 0
+%define CONFIG_LIBRUBBERBAND 0
+%define CONFIG_LIBVIDSTAB 0
+%define CONFIG_LIBX264 0
+%define CONFIG_LIBX265 0
+%define CONFIG_LIBXAVS 0
+%define CONFIG_LIBXVID 0
+%define CONFIG_DECKLINK 0
+%define CONFIG_LIBNDI_NEWTEK 0
+%define CONFIG_LIBFDK_AAC 0
+%define CONFIG_OPENSSL 0
%define CONFIG_GMP 0
+%define CONFIG_LIBOPENCORE_AMRNB 0
+%define CONFIG_LIBOPENCORE_AMRWB 0
+%define CONFIG_LIBVO_AMRWBENC 0
+%define CONFIG_RKMPP 0
+%define CONFIG_LIBSMBCLIENT 0
+%define CONFIG_CHROMAPRINT 0
+%define CONFIG_GCRYPT 0
%define CONFIG_GNUTLS 0
-%define CONFIG_ICONV 0
%define CONFIG_JNI 0
%define CONFIG_LADSPA 0
%define CONFIG_LIBASS 0
%define CONFIG_LIBBLURAY 0
%define CONFIG_LIBBS2B 0
%define CONFIG_LIBCACA 0
-%define CONFIG_LIBCDIO 0
%define CONFIG_LIBCELT 0
%define CONFIG_LIBDC1394 0
-%define CONFIG_LIBEBUR128 0
-%define CONFIG_LIBFDK_AAC 0
+%define CONFIG_LIBDRM 0
%define CONFIG_LIBFLITE 0
%define CONFIG_LIBFONTCONFIG 0
%define CONFIG_LIBFREETYPE 0
@@ -432,18 +453,15 @@
%define CONFIG_LIBKVAZAAR 0
%define CONFIG_LIBMODPLUG 0
%define CONFIG_LIBMP3LAME 0
-%define CONFIG_LIBNUT 0
-%define CONFIG_LIBOPENCORE_AMRNB 0
-%define CONFIG_LIBOPENCORE_AMRWB 0
+%define CONFIG_LIBMYSOFA 0
%define CONFIG_LIBOPENCV 0
%define CONFIG_LIBOPENH264 0
%define CONFIG_LIBOPENJPEG 0
%define CONFIG_LIBOPENMPT 0
%define CONFIG_LIBOPUS 0
%define CONFIG_LIBPULSE 0
+%define CONFIG_LIBRSVG 0
%define CONFIG_LIBRTMP 0
-%define CONFIG_LIBRUBBERBAND 0
-%define CONFIG_LIBSCHROEDINGER 0
%define CONFIG_LIBSHINE 0
%define CONFIG_LIBSMBCLIENT 0
%define CONFIG_LIBSNAPPY 0
@@ -454,53 +472,37 @@
%define CONFIG_LIBTHEORA 0
%define CONFIG_LIBTWOLAME 0
%define CONFIG_LIBV4L2 0
-%define CONFIG_LIBVIDSTAB 0
-%define CONFIG_LIBVO_AMRWBENC 0
+%define CONFIG_LIBVMAF 0
%define CONFIG_LIBVORBIS 0
%define CONFIG_LIBVPX 0
%define CONFIG_LIBWAVPACK 0
%define CONFIG_LIBWEBP 0
-%define CONFIG_LIBX264 0
-%define CONFIG_LIBX265 0
-%define CONFIG_LIBXAVS 0
-%define CONFIG_LIBXCB 0
-%define CONFIG_LIBXCB_SHM 0
-%define CONFIG_LIBXCB_SHAPE 0
-%define CONFIG_LIBXCB_XFIXES 0
-%define CONFIG_LIBXVID 0
+%define CONFIG_LIBXML2 0
%define CONFIG_LIBZIMG 0
%define CONFIG_LIBZMQ 0
%define CONFIG_LIBZVBI 0
-%define CONFIG_LZMA 0
%define CONFIG_MEDIACODEC 0
-%define CONFIG_NETCDF 0
%define CONFIG_OPENAL 0
%define CONFIG_OPENCL 0
%define CONFIG_OPENGL 0
-%define CONFIG_OPENSSL 0
-%define CONFIG_SCHANNEL 0
-%define CONFIG_SDL 0
-%define CONFIG_SDL2 0
-%define CONFIG_SECURETRANSPORT 0
-%define CONFIG_VIDEOTOOLBOX 0
-%define CONFIG_X11GRAB 0
-%define CONFIG_XLIB 0
-%define CONFIG_ZLIB 0
-%define CONFIG_AUDIOTOOLBOX 0
+%define CONFIG_AUDIOTOOLBOX 1
+%define CONFIG_CRYSTALHD 0
%define CONFIG_CUDA 0
%define CONFIG_CUVID 0
%define CONFIG_D3D11VA 0
%define CONFIG_DXVA2 0
-%define CONFIG_LIBMFX 0
-%define CONFIG_LIBNPP 0
-%define CONFIG_MMAL 0
%define CONFIG_NVENC 0
-%define CONFIG_OMX 0
%define CONFIG_VAAPI 0
%define CONFIG_VDA 0
%define CONFIG_VDPAU 0
-%define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_VIDEOTOOLBOX 0
+%define CONFIG_V4L2_M2M 0
%define CONFIG_XVMC 0
+%define CONFIG_CUDA_SDK 0
+%define CONFIG_LIBNPP 0
+%define CONFIG_LIBMFX 0
+%define CONFIG_MMAL 0
+%define CONFIG_OMX 0
%define CONFIG_FTRAPV 0
%define CONFIG_GRAY 0
%define CONFIG_HARDCODED_TABLES 0
@@ -539,16 +541,27 @@
%define CONFIG_PIXELUTILS 0
%define CONFIG_NETWORK 0
%define CONFIG_RDFT 0
+%define CONFIG_AUTODETECT 0
%define CONFIG_FONTCONFIG 0
-%define CONFIG_MEMALIGN_HACK 0
+%define CONFIG_LINUX_PERF 0
%define CONFIG_MEMORY_POISONING 0
%define CONFIG_NEON_CLOBBER_TEST 0
+%define CONFIG_OSSFUZZ 0
%define CONFIG_PIC 1
-%define CONFIG_POD2MAN 1
-%define CONFIG_RAISE_MAJOR 0
%define CONFIG_THUMB 0
%define CONFIG_VALGRIND_BACKTRACE 0
%define CONFIG_XMM_CLOBBER_TEST 0
+%define CONFIG_BSFS 1
+%define CONFIG_DECODERS 1
+%define CONFIG_ENCODERS 0
+%define CONFIG_HWACCELS 0
+%define CONFIG_PARSERS 1
+%define CONFIG_INDEVS 0
+%define CONFIG_OUTDEVS 0
+%define CONFIG_FILTERS 0
+%define CONFIG_DEMUXERS 0
+%define CONFIG_MUXERS 0
+%define CONFIG_PROTOCOLS 0
%define CONFIG_AANDCTTABLES 0
%define CONFIG_AC3DSP 0
%define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -566,20 +579,22 @@
%define CONFIG_FMTCONVERT 0
%define CONFIG_FRAME_THREAD_ENCODER 0
%define CONFIG_G722DSP 0
-%define CONFIG_GOLOMB 1
+%define CONFIG_GOLOMB 0
%define CONFIG_GPLV3 0
%define CONFIG_H263DSP 0
%define CONFIG_H264CHROMA 0
%define CONFIG_H264DSP 0
+%define CONFIG_H264PARSE 0
%define CONFIG_H264PRED 1
%define CONFIG_H264QPEL 0
+%define CONFIG_HEVCPARSE 0
%define CONFIG_HPELDSP 0
%define CONFIG_HUFFMAN 0
%define CONFIG_HUFFYUVDSP 0
%define CONFIG_HUFFYUVENCDSP 0
%define CONFIG_IDCTDSP 0
%define CONFIG_IIRFILTER 0
-%define CONFIG_IMDCT15 0
+%define CONFIG_MDCT15 0
%define CONFIG_INTRAX8 0
%define CONFIG_ISO_MEDIA 0
%define CONFIG_IVIDSP 0
@@ -588,12 +603,14 @@
%define CONFIG_LIBX262 0
%define CONFIG_LLAUDDSP 0
%define CONFIG_LLVIDDSP 0
+%define CONFIG_LLVIDENCDSP 0
%define CONFIG_LPC 0
%define CONFIG_LZF 0
%define CONFIG_ME_CMP 0
%define CONFIG_MPEG_ER 0
%define CONFIG_MPEGAUDIO 0
%define CONFIG_MPEGAUDIODSP 0
+%define CONFIG_MPEGAUDIOHEADER 0
%define CONFIG_MPEGVIDEO 0
%define CONFIG_MPEGVIDEOENC 0
%define CONFIG_MSS34DSP 0
@@ -615,1594 +632,19 @@
%define CONFIG_TEXTUREDSP 0
%define CONFIG_TEXTUREDSPENC 0
%define CONFIG_TPELDSP 0
+%define CONFIG_VAAPI_1 0
%define CONFIG_VAAPI_ENCODE 0
%define CONFIG_VC1DSP 0
%define CONFIG_VIDEODSP 1
%define CONFIG_VP3DSP 0
%define CONFIG_VP56DSP 0
%define CONFIG_VP8DSP 1
-%define CONFIG_VT_BT2020 0
%define CONFIG_WMA_FREQS 0
%define CONFIG_WMV2DSP 0
-%define CONFIG_AAC_ADTSTOASC_BSF 0
-%define CONFIG_CHOMP_BSF 0
-%define CONFIG_DUMP_EXTRADATA_BSF 0
-%define CONFIG_DCA_CORE_BSF 0
-%define CONFIG_H264_MP4TOANNEXB_BSF 0
-%define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-%define CONFIG_IMX_DUMP_HEADER_BSF 0
-%define CONFIG_MJPEG2JPEG_BSF 0
-%define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-%define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-%define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-%define CONFIG_MOV2TEXTSUB_BSF 0
-%define CONFIG_NOISE_BSF 0
-%define CONFIG_REMOVE_EXTRADATA_BSF 0
-%define CONFIG_TEXT2MOVSUB_BSF 0
-%define CONFIG_VP9_SUPERFRAME_BSF 0
-%define CONFIG_AASC_DECODER 0
-%define CONFIG_AIC_DECODER 0
-%define CONFIG_ALIAS_PIX_DECODER 0
-%define CONFIG_AMV_DECODER 0
-%define CONFIG_ANM_DECODER 0
-%define CONFIG_ANSI_DECODER 0
-%define CONFIG_APNG_DECODER 0
-%define CONFIG_ASV1_DECODER 0
-%define CONFIG_ASV2_DECODER 0
-%define CONFIG_AURA_DECODER 0
-%define CONFIG_AURA2_DECODER 0
-%define CONFIG_AVRP_DECODER 0
-%define CONFIG_AVRN_DECODER 0
-%define CONFIG_AVS_DECODER 0
-%define CONFIG_AVUI_DECODER 0
-%define CONFIG_AYUV_DECODER 0
-%define CONFIG_BETHSOFTVID_DECODER 0
-%define CONFIG_BFI_DECODER 0
-%define CONFIG_BINK_DECODER 0
-%define CONFIG_BMP_DECODER 0
-%define CONFIG_BMV_VIDEO_DECODER 0
-%define CONFIG_BRENDER_PIX_DECODER 0
-%define CONFIG_C93_DECODER 0
-%define CONFIG_CAVS_DECODER 0
-%define CONFIG_CDGRAPHICS_DECODER 0
-%define CONFIG_CDXL_DECODER 0
-%define CONFIG_CFHD_DECODER 0
-%define CONFIG_CINEPAK_DECODER 0
-%define CONFIG_CLJR_DECODER 0
-%define CONFIG_CLLC_DECODER 0
-%define CONFIG_COMFORTNOISE_DECODER 0
-%define CONFIG_CPIA_DECODER 0
-%define CONFIG_CSCD_DECODER 0
-%define CONFIG_CYUV_DECODER 0
-%define CONFIG_DDS_DECODER 0
-%define CONFIG_DFA_DECODER 0
-%define CONFIG_DIRAC_DECODER 0
-%define CONFIG_DNXHD_DECODER 0
-%define CONFIG_DPX_DECODER 0
-%define CONFIG_DSICINVIDEO_DECODER 0
-%define CONFIG_DVAUDIO_DECODER 0
-%define CONFIG_DVVIDEO_DECODER 0
-%define CONFIG_DXA_DECODER 0
-%define CONFIG_DXTORY_DECODER 0
-%define CONFIG_DXV_DECODER 0
-%define CONFIG_EACMV_DECODER 0
-%define CONFIG_EAMAD_DECODER 0
-%define CONFIG_EATGQ_DECODER 0
-%define CONFIG_EATGV_DECODER 0
-%define CONFIG_EATQI_DECODER 0
-%define CONFIG_EIGHTBPS_DECODER 0
-%define CONFIG_EIGHTSVX_EXP_DECODER 0
-%define CONFIG_EIGHTSVX_FIB_DECODER 0
-%define CONFIG_ESCAPE124_DECODER 0
-%define CONFIG_ESCAPE130_DECODER 0
-%define CONFIG_EXR_DECODER 0
-%define CONFIG_FFV1_DECODER 0
-%define CONFIG_FFVHUFF_DECODER 0
-%define CONFIG_FIC_DECODER 0
-%define CONFIG_FLASHSV_DECODER 0
-%define CONFIG_FLASHSV2_DECODER 0
-%define CONFIG_FLIC_DECODER 0
-%define CONFIG_FLV_DECODER 0
-%define CONFIG_FOURXM_DECODER 0
-%define CONFIG_FRAPS_DECODER 0
-%define CONFIG_FRWU_DECODER 0
-%define CONFIG_G2M_DECODER 0
-%define CONFIG_GIF_DECODER 0
-%define CONFIG_H261_DECODER 0
-%define CONFIG_H263_DECODER 0
-%define CONFIG_H263I_DECODER 0
-%define CONFIG_H263P_DECODER 0
-%define CONFIG_H264_DECODER 0
-%define CONFIG_H264_CRYSTALHD_DECODER 0
-%define CONFIG_H264_MEDIACODEC_DECODER 0
-%define CONFIG_H264_MMAL_DECODER 0
-%define CONFIG_H264_QSV_DECODER 0
-%define CONFIG_H264_VDA_DECODER 0
-%define CONFIG_H264_VDPAU_DECODER 0
-%define CONFIG_HAP_DECODER 0
-%define CONFIG_HEVC_DECODER 0
-%define CONFIG_HEVC_QSV_DECODER 0
-%define CONFIG_HNM4_VIDEO_DECODER 0
-%define CONFIG_HQ_HQA_DECODER 0
-%define CONFIG_HQX_DECODER 0
-%define CONFIG_HUFFYUV_DECODER 0
-%define CONFIG_IDCIN_DECODER 0
-%define CONFIG_IFF_ILBM_DECODER 0
-%define CONFIG_INDEO2_DECODER 0
-%define CONFIG_INDEO3_DECODER 0
-%define CONFIG_INDEO4_DECODER 0
-%define CONFIG_INDEO5_DECODER 0
-%define CONFIG_INTERPLAY_VIDEO_DECODER 0
-%define CONFIG_JPEG2000_DECODER 0
-%define CONFIG_JPEGLS_DECODER 0
-%define CONFIG_JV_DECODER 0
-%define CONFIG_KGV1_DECODER 0
-%define CONFIG_KMVC_DECODER 0
-%define CONFIG_LAGARITH_DECODER 0
-%define CONFIG_LOCO_DECODER 0
-%define CONFIG_M101_DECODER 0
-%define CONFIG_MAGICYUV_DECODER 0
-%define CONFIG_MDEC_DECODER 0
-%define CONFIG_MIMIC_DECODER 0
-%define CONFIG_MJPEG_DECODER 0
-%define CONFIG_MJPEGB_DECODER 0
-%define CONFIG_MMVIDEO_DECODER 0
-%define CONFIG_MOTIONPIXELS_DECODER 0
-%define CONFIG_MPEG_XVMC_DECODER 0
-%define CONFIG_MPEG1VIDEO_DECODER 0
-%define CONFIG_MPEG2VIDEO_DECODER 0
-%define CONFIG_MPEG4_DECODER 0
-%define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-%define CONFIG_MPEG4_MMAL_DECODER 0
-%define CONFIG_MPEG4_VDPAU_DECODER 0
-%define CONFIG_MPEGVIDEO_DECODER 0
-%define CONFIG_MPEG_VDPAU_DECODER 0
-%define CONFIG_MPEG1_VDPAU_DECODER 0
-%define CONFIG_MPEG2_MMAL_DECODER 0
-%define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-%define CONFIG_MPEG2_QSV_DECODER 0
-%define CONFIG_MSA1_DECODER 0
-%define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-%define CONFIG_MSMPEG4V1_DECODER 0
-%define CONFIG_MSMPEG4V2_DECODER 0
-%define CONFIG_MSMPEG4V3_DECODER 0
-%define CONFIG_MSRLE_DECODER 0
-%define CONFIG_MSS1_DECODER 0
-%define CONFIG_MSS2_DECODER 0
-%define CONFIG_MSVIDEO1_DECODER 0
-%define CONFIG_MSZH_DECODER 0
-%define CONFIG_MTS2_DECODER 0
-%define CONFIG_MVC1_DECODER 0
-%define CONFIG_MVC2_DECODER 0
-%define CONFIG_MXPEG_DECODER 0
-%define CONFIG_NUV_DECODER 0
-%define CONFIG_PAF_VIDEO_DECODER 0
-%define CONFIG_PAM_DECODER 0
-%define CONFIG_PBM_DECODER 0
-%define CONFIG_PCX_DECODER 0
-%define CONFIG_PGM_DECODER 0
-%define CONFIG_PGMYUV_DECODER 0
-%define CONFIG_PICTOR_DECODER 0
-%define CONFIG_PNG_DECODER 0
-%define CONFIG_PPM_DECODER 0
-%define CONFIG_PRORES_DECODER 0
-%define CONFIG_PRORES_LGPL_DECODER 0
-%define CONFIG_PTX_DECODER 0
-%define CONFIG_QDRAW_DECODER 0
-%define CONFIG_QPEG_DECODER 0
-%define CONFIG_QTRLE_DECODER 0
-%define CONFIG_R10K_DECODER 0
-%define CONFIG_R210_DECODER 0
-%define CONFIG_RAWVIDEO_DECODER 0
-%define CONFIG_RL2_DECODER 0
-%define CONFIG_ROQ_DECODER 0
-%define CONFIG_RPZA_DECODER 0
-%define CONFIG_RSCC_DECODER 0
-%define CONFIG_RV10_DECODER 0
-%define CONFIG_RV20_DECODER 0
-%define CONFIG_RV30_DECODER 0
-%define CONFIG_RV40_DECODER 0
-%define CONFIG_S302M_DECODER 0
-%define CONFIG_SANM_DECODER 0
-%define CONFIG_SCREENPRESSO_DECODER 0
-%define CONFIG_SDX2_DPCM_DECODER 0
-%define CONFIG_SGI_DECODER 0
-%define CONFIG_SGIRLE_DECODER 0
-%define CONFIG_SHEERVIDEO_DECODER 0
-%define CONFIG_SMACKER_DECODER 0
-%define CONFIG_SMC_DECODER 0
-%define CONFIG_SMVJPEG_DECODER 0
-%define CONFIG_SNOW_DECODER 0
-%define CONFIG_SP5X_DECODER 0
-%define CONFIG_SUNRAST_DECODER 0
-%define CONFIG_SVQ1_DECODER 0
-%define CONFIG_SVQ3_DECODER 0
-%define CONFIG_TARGA_DECODER 0
-%define CONFIG_TARGA_Y216_DECODER 0
-%define CONFIG_TDSC_DECODER 0
-%define CONFIG_THEORA_DECODER 0
-%define CONFIG_THP_DECODER 0
-%define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-%define CONFIG_TIFF_DECODER 0
-%define CONFIG_TMV_DECODER 0
-%define CONFIG_TRUEMOTION1_DECODER 0
-%define CONFIG_TRUEMOTION2_DECODER 0
-%define CONFIG_TRUEMOTION2RT_DECODER 0
-%define CONFIG_TSCC_DECODER 0
-%define CONFIG_TSCC2_DECODER 0
-%define CONFIG_TXD_DECODER 0
-%define CONFIG_ULTI_DECODER 0
-%define CONFIG_UTVIDEO_DECODER 0
-%define CONFIG_V210_DECODER 0
-%define CONFIG_V210X_DECODER 0
-%define CONFIG_V308_DECODER 0
-%define CONFIG_V408_DECODER 0
-%define CONFIG_V410_DECODER 0
-%define CONFIG_VB_DECODER 0
-%define CONFIG_VBLE_DECODER 0
-%define CONFIG_VC1_DECODER 0
-%define CONFIG_VC1_CRYSTALHD_DECODER 0
-%define CONFIG_VC1_VDPAU_DECODER 0
-%define CONFIG_VC1IMAGE_DECODER 0
-%define CONFIG_VC1_MMAL_DECODER 0
-%define CONFIG_VC1_QSV_DECODER 0
-%define CONFIG_VCR1_DECODER 0
-%define CONFIG_VMDVIDEO_DECODER 0
-%define CONFIG_VMNC_DECODER 0
-%define CONFIG_VP3_DECODER 0
-%define CONFIG_VP5_DECODER 0
-%define CONFIG_VP6_DECODER 0
-%define CONFIG_VP6A_DECODER 0
-%define CONFIG_VP6F_DECODER 0
-%define CONFIG_VP7_DECODER 0
+%define CONFIG_NULL_BSF 1
%define CONFIG_VP8_DECODER 1
%define CONFIG_VP9_DECODER 1
-%define CONFIG_VQA_DECODER 0
-%define CONFIG_WEBP_DECODER 0
-%define CONFIG_WMV1_DECODER 0
-%define CONFIG_WMV2_DECODER 0
-%define CONFIG_WMV3_DECODER 0
-%define CONFIG_WMV3_CRYSTALHD_DECODER 0
-%define CONFIG_WMV3_VDPAU_DECODER 0
-%define CONFIG_WMV3IMAGE_DECODER 0
-%define CONFIG_WNV1_DECODER 0
-%define CONFIG_XAN_WC3_DECODER 0
-%define CONFIG_XAN_WC4_DECODER 0
-%define CONFIG_XBM_DECODER 0
-%define CONFIG_XFACE_DECODER 0
-%define CONFIG_XL_DECODER 0
-%define CONFIG_XWD_DECODER 0
-%define CONFIG_Y41P_DECODER 0
-%define CONFIG_YLC_DECODER 0
-%define CONFIG_YOP_DECODER 0
-%define CONFIG_YUV4_DECODER 0
-%define CONFIG_ZERO12V_DECODER 0
-%define CONFIG_ZEROCODEC_DECODER 0
-%define CONFIG_ZLIB_DECODER 0
-%define CONFIG_ZMBV_DECODER 0
-%define CONFIG_AAC_DECODER 0
-%define CONFIG_AAC_FIXED_DECODER 0
-%define CONFIG_AAC_LATM_DECODER 0
-%define CONFIG_AC3_DECODER 0
-%define CONFIG_AC3_FIXED_DECODER 0
-%define CONFIG_ALAC_DECODER 0
-%define CONFIG_ALS_DECODER 0
-%define CONFIG_AMRNB_DECODER 0
-%define CONFIG_AMRWB_DECODER 0
-%define CONFIG_APE_DECODER 0
-%define CONFIG_ATRAC1_DECODER 0
-%define CONFIG_ATRAC3_DECODER 0
-%define CONFIG_ATRAC3P_DECODER 0
-%define CONFIG_BINKAUDIO_DCT_DECODER 0
-%define CONFIG_BINKAUDIO_RDFT_DECODER 0
-%define CONFIG_BMV_AUDIO_DECODER 0
-%define CONFIG_COOK_DECODER 0
-%define CONFIG_DCA_DECODER 0
-%define CONFIG_DSD_LSBF_DECODER 0
-%define CONFIG_DSD_MSBF_DECODER 0
-%define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-%define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-%define CONFIG_DSICINAUDIO_DECODER 0
-%define CONFIG_DSS_SP_DECODER 0
-%define CONFIG_DST_DECODER 0
-%define CONFIG_EAC3_DECODER 0
-%define CONFIG_EVRC_DECODER 0
-%define CONFIG_FFWAVESYNTH_DECODER 0
%define CONFIG_FLAC_DECODER 1
-%define CONFIG_G723_1_DECODER 0
-%define CONFIG_G729_DECODER 0
-%define CONFIG_GSM_DECODER 0
-%define CONFIG_GSM_MS_DECODER 0
-%define CONFIG_IAC_DECODER 0
-%define CONFIG_IMC_DECODER 0
-%define CONFIG_INTERPLAY_ACM_DECODER 0
-%define CONFIG_MACE3_DECODER 0
-%define CONFIG_MACE6_DECODER 0
-%define CONFIG_METASOUND_DECODER 0
-%define CONFIG_MLP_DECODER 0
-%define CONFIG_MP1_DECODER 0
-%define CONFIG_MP1FLOAT_DECODER 0
-%define CONFIG_MP2_DECODER 0
-%define CONFIG_MP2FLOAT_DECODER 0
-%define CONFIG_MP3_DECODER 0
-%define CONFIG_MP3FLOAT_DECODER 0
-%define CONFIG_MP3ADU_DECODER 0
-%define CONFIG_MP3ADUFLOAT_DECODER 0
-%define CONFIG_MP3ON4_DECODER 0
-%define CONFIG_MP3ON4FLOAT_DECODER 0
-%define CONFIG_MPC7_DECODER 0
-%define CONFIG_MPC8_DECODER 0
-%define CONFIG_NELLYMOSER_DECODER 0
-%define CONFIG_ON2AVC_DECODER 0
-%define CONFIG_OPUS_DECODER 0
-%define CONFIG_PAF_AUDIO_DECODER 0
-%define CONFIG_QCELP_DECODER 0
-%define CONFIG_QDM2_DECODER 0
-%define CONFIG_RA_144_DECODER 0
-%define CONFIG_RA_288_DECODER 0
-%define CONFIG_RALF_DECODER 0
-%define CONFIG_SHORTEN_DECODER 0
-%define CONFIG_SIPR_DECODER 0
-%define CONFIG_SMACKAUD_DECODER 0
-%define CONFIG_SONIC_DECODER 0
-%define CONFIG_TAK_DECODER 0
-%define CONFIG_TRUEHD_DECODER 0
-%define CONFIG_TRUESPEECH_DECODER 0
-%define CONFIG_TTA_DECODER 0
-%define CONFIG_TWINVQ_DECODER 0
-%define CONFIG_VMDAUDIO_DECODER 0
-%define CONFIG_VORBIS_DECODER 0
-%define CONFIG_WAVPACK_DECODER 0
-%define CONFIG_WMALOSSLESS_DECODER 0
-%define CONFIG_WMAPRO_DECODER 0
-%define CONFIG_WMAV1_DECODER 0
-%define CONFIG_WMAV2_DECODER 0
-%define CONFIG_WMAVOICE_DECODER 0
-%define CONFIG_WS_SND1_DECODER 0
-%define CONFIG_XMA1_DECODER 0
-%define CONFIG_XMA2_DECODER 0
-%define CONFIG_PCM_ALAW_DECODER 0
-%define CONFIG_PCM_BLURAY_DECODER 0
-%define CONFIG_PCM_DVD_DECODER 0
-%define CONFIG_PCM_F32BE_DECODER 0
-%define CONFIG_PCM_F32LE_DECODER 0
-%define CONFIG_PCM_F64BE_DECODER 0
-%define CONFIG_PCM_F64LE_DECODER 0
-%define CONFIG_PCM_LXF_DECODER 0
-%define CONFIG_PCM_MULAW_DECODER 0
-%define CONFIG_PCM_S8_DECODER 0
-%define CONFIG_PCM_S8_PLANAR_DECODER 0
-%define CONFIG_PCM_S16BE_DECODER 0
-%define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-%define CONFIG_PCM_S16LE_DECODER 0
-%define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S24BE_DECODER 0
-%define CONFIG_PCM_S24DAUD_DECODER 0
-%define CONFIG_PCM_S24LE_DECODER 0
-%define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S32BE_DECODER 0
-%define CONFIG_PCM_S32LE_DECODER 0
-%define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S64BE_DECODER 0
-%define CONFIG_PCM_S64LE_DECODER 0
-%define CONFIG_PCM_U8_DECODER 0
-%define CONFIG_PCM_U16BE_DECODER 0
-%define CONFIG_PCM_U16LE_DECODER 0
-%define CONFIG_PCM_U24BE_DECODER 0
-%define CONFIG_PCM_U24LE_DECODER 0
-%define CONFIG_PCM_U32BE_DECODER 0
-%define CONFIG_PCM_U32LE_DECODER 0
-%define CONFIG_PCM_ZORK_DECODER 0
-%define CONFIG_INTERPLAY_DPCM_DECODER 0
-%define CONFIG_ROQ_DPCM_DECODER 0
-%define CONFIG_SOL_DPCM_DECODER 0
-%define CONFIG_XAN_DPCM_DECODER 0
-%define CONFIG_ADPCM_4XM_DECODER 0
-%define CONFIG_ADPCM_ADX_DECODER 0
-%define CONFIG_ADPCM_AFC_DECODER 0
-%define CONFIG_ADPCM_AICA_DECODER 0
-%define CONFIG_ADPCM_CT_DECODER 0
-%define CONFIG_ADPCM_DTK_DECODER 0
-%define CONFIG_ADPCM_EA_DECODER 0
-%define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-%define CONFIG_ADPCM_EA_R1_DECODER 0
-%define CONFIG_ADPCM_EA_R2_DECODER 0
-%define CONFIG_ADPCM_EA_R3_DECODER 0
-%define CONFIG_ADPCM_EA_XAS_DECODER 0
-%define CONFIG_ADPCM_G722_DECODER 0
-%define CONFIG_ADPCM_G726_DECODER 0
-%define CONFIG_ADPCM_G726LE_DECODER 0
-%define CONFIG_ADPCM_IMA_AMV_DECODER 0
-%define CONFIG_ADPCM_IMA_APC_DECODER 0
-%define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-%define CONFIG_ADPCM_IMA_DK3_DECODER 0
-%define CONFIG_ADPCM_IMA_DK4_DECODER 0
-%define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-%define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-%define CONFIG_ADPCM_IMA_ISS_DECODER 0
-%define CONFIG_ADPCM_IMA_OKI_DECODER 0
-%define CONFIG_ADPCM_IMA_QT_DECODER 0
-%define CONFIG_ADPCM_IMA_RAD_DECODER 0
-%define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-%define CONFIG_ADPCM_IMA_WAV_DECODER 0
-%define CONFIG_ADPCM_IMA_WS_DECODER 0
-%define CONFIG_ADPCM_MS_DECODER 0
-%define CONFIG_ADPCM_MTAF_DECODER 0
-%define CONFIG_ADPCM_PSX_DECODER 0
-%define CONFIG_ADPCM_SBPRO_2_DECODER 0
-%define CONFIG_ADPCM_SBPRO_3_DECODER 0
-%define CONFIG_ADPCM_SBPRO_4_DECODER 0
-%define CONFIG_ADPCM_SWF_DECODER 0
-%define CONFIG_ADPCM_THP_DECODER 0
-%define CONFIG_ADPCM_THP_LE_DECODER 0
-%define CONFIG_ADPCM_VIMA_DECODER 0
-%define CONFIG_ADPCM_XA_DECODER 0
-%define CONFIG_ADPCM_YAMAHA_DECODER 0
-%define CONFIG_SSA_DECODER 0
-%define CONFIG_ASS_DECODER 0
-%define CONFIG_CCAPTION_DECODER 0
-%define CONFIG_DVBSUB_DECODER 0
-%define CONFIG_DVDSUB_DECODER 0
-%define CONFIG_JACOSUB_DECODER 0
-%define CONFIG_MICRODVD_DECODER 0
-%define CONFIG_MOVTEXT_DECODER 0
-%define CONFIG_MPL2_DECODER 0
-%define CONFIG_PGSSUB_DECODER 0
-%define CONFIG_PJS_DECODER 0
-%define CONFIG_REALTEXT_DECODER 0
-%define CONFIG_SAMI_DECODER 0
-%define CONFIG_SRT_DECODER 0
-%define CONFIG_STL_DECODER 0
-%define CONFIG_SUBRIP_DECODER 0
-%define CONFIG_SUBVIEWER_DECODER 0
-%define CONFIG_SUBVIEWER1_DECODER 0
-%define CONFIG_TEXT_DECODER 0
-%define CONFIG_VPLAYER_DECODER 0
-%define CONFIG_WEBVTT_DECODER 0
-%define CONFIG_XSUB_DECODER 0
-%define CONFIG_AAC_AT_DECODER 0
-%define CONFIG_AC3_AT_DECODER 0
-%define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-%define CONFIG_ALAC_AT_DECODER 0
-%define CONFIG_AMR_NB_AT_DECODER 0
-%define CONFIG_EAC3_AT_DECODER 0
-%define CONFIG_GSM_MS_AT_DECODER 0
-%define CONFIG_ILBC_AT_DECODER 0
-%define CONFIG_MP1_AT_DECODER 0
-%define CONFIG_MP2_AT_DECODER 0
-%define CONFIG_MP3_AT_DECODER 0
-%define CONFIG_PCM_ALAW_AT_DECODER 0
-%define CONFIG_PCM_MULAW_AT_DECODER 0
-%define CONFIG_QDMC_AT_DECODER 0
-%define CONFIG_QDM2_AT_DECODER 0
-%define CONFIG_LIBCELT_DECODER 0
-%define CONFIG_LIBFDK_AAC_DECODER 0
-%define CONFIG_LIBGSM_DECODER 0
-%define CONFIG_LIBGSM_MS_DECODER 0
-%define CONFIG_LIBILBC_DECODER 0
-%define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-%define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-%define CONFIG_LIBOPENJPEG_DECODER 0
-%define CONFIG_LIBOPUS_DECODER 0
-%define CONFIG_LIBSCHROEDINGER_DECODER 0
-%define CONFIG_LIBSPEEX_DECODER 0
-%define CONFIG_LIBVORBIS_DECODER 0
-%define CONFIG_LIBVPX_VP8_DECODER 0
-%define CONFIG_LIBVPX_VP9_DECODER 0
-%define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-%define CONFIG_BINTEXT_DECODER 0
-%define CONFIG_XBIN_DECODER 0
-%define CONFIG_IDF_DECODER 0
-%define CONFIG_LIBOPENH264_DECODER 0
-%define CONFIG_H263_CUVID_DECODER 0
-%define CONFIG_H264_CUVID_DECODER 0
-%define CONFIG_HEVC_CUVID_DECODER 0
-%define CONFIG_HEVC_MEDIACODEC_DECODER 0
-%define CONFIG_MJPEG_CUVID_DECODER 0
-%define CONFIG_MPEG1_CUVID_DECODER 0
-%define CONFIG_MPEG2_CUVID_DECODER 0
-%define CONFIG_MPEG4_CUVID_DECODER 0
-%define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-%define CONFIG_VC1_CUVID_DECODER 0
-%define CONFIG_VP8_CUVID_DECODER 0
-%define CONFIG_VP8_MEDIACODEC_DECODER 0
-%define CONFIG_VP9_CUVID_DECODER 0
-%define CONFIG_VP9_MEDIACODEC_DECODER 0
-%define CONFIG_AA_DEMUXER 0
-%define CONFIG_AAC_DEMUXER 0
-%define CONFIG_AC3_DEMUXER 0
-%define CONFIG_ACM_DEMUXER 0
-%define CONFIG_ACT_DEMUXER 0
-%define CONFIG_ADF_DEMUXER 0
-%define CONFIG_ADP_DEMUXER 0
-%define CONFIG_ADS_DEMUXER 0
-%define CONFIG_ADX_DEMUXER 0
-%define CONFIG_AEA_DEMUXER 0
-%define CONFIG_AFC_DEMUXER 0
-%define CONFIG_AIFF_DEMUXER 0
-%define CONFIG_AIX_DEMUXER 0
-%define CONFIG_AMR_DEMUXER 0
-%define CONFIG_ANM_DEMUXER 0
-%define CONFIG_APC_DEMUXER 0
-%define CONFIG_APE_DEMUXER 0
-%define CONFIG_APNG_DEMUXER 0
-%define CONFIG_AQTITLE_DEMUXER 0
-%define CONFIG_ASF_DEMUXER 0
-%define CONFIG_ASF_O_DEMUXER 0
-%define CONFIG_ASS_DEMUXER 0
-%define CONFIG_AST_DEMUXER 0
-%define CONFIG_AU_DEMUXER 0
-%define CONFIG_AVI_DEMUXER 0
-%define CONFIG_AVISYNTH_DEMUXER 0
-%define CONFIG_AVR_DEMUXER 0
-%define CONFIG_AVS_DEMUXER 0
-%define CONFIG_BETHSOFTVID_DEMUXER 0
-%define CONFIG_BFI_DEMUXER 0
-%define CONFIG_BINTEXT_DEMUXER 0
-%define CONFIG_BINK_DEMUXER 0
-%define CONFIG_BIT_DEMUXER 0
-%define CONFIG_BMV_DEMUXER 0
-%define CONFIG_BFSTM_DEMUXER 0
-%define CONFIG_BRSTM_DEMUXER 0
-%define CONFIG_BOA_DEMUXER 0
-%define CONFIG_C93_DEMUXER 0
-%define CONFIG_CAF_DEMUXER 0
-%define CONFIG_CAVSVIDEO_DEMUXER 0
-%define CONFIG_CDG_DEMUXER 0
-%define CONFIG_CDXL_DEMUXER 0
-%define CONFIG_CINE_DEMUXER 0
-%define CONFIG_CONCAT_DEMUXER 0
-%define CONFIG_DATA_DEMUXER 0
-%define CONFIG_DAUD_DEMUXER 0
-%define CONFIG_DCSTR_DEMUXER 0
-%define CONFIG_DFA_DEMUXER 0
-%define CONFIG_DIRAC_DEMUXER 0
-%define CONFIG_DNXHD_DEMUXER 0
-%define CONFIG_DSF_DEMUXER 0
-%define CONFIG_DSICIN_DEMUXER 0
-%define CONFIG_DSS_DEMUXER 0
-%define CONFIG_DTS_DEMUXER 0
-%define CONFIG_DTSHD_DEMUXER 0
-%define CONFIG_DV_DEMUXER 0
-%define CONFIG_DVBSUB_DEMUXER 0
-%define CONFIG_DVBTXT_DEMUXER 0
-%define CONFIG_DXA_DEMUXER 0
-%define CONFIG_EA_DEMUXER 0
-%define CONFIG_EA_CDATA_DEMUXER 0
-%define CONFIG_EAC3_DEMUXER 0
-%define CONFIG_EPAF_DEMUXER 0
-%define CONFIG_FFM_DEMUXER 0
-%define CONFIG_FFMETADATA_DEMUXER 0
-%define CONFIG_FILMSTRIP_DEMUXER 0
-%define CONFIG_FLAC_DEMUXER 0
-%define CONFIG_FLIC_DEMUXER 0
-%define CONFIG_FLV_DEMUXER 0
-%define CONFIG_LIVE_FLV_DEMUXER 0
-%define CONFIG_FOURXM_DEMUXER 0
-%define CONFIG_FRM_DEMUXER 0
-%define CONFIG_FSB_DEMUXER 0
-%define CONFIG_G722_DEMUXER 0
-%define CONFIG_G723_1_DEMUXER 0
-%define CONFIG_G729_DEMUXER 0
-%define CONFIG_GENH_DEMUXER 0
-%define CONFIG_GIF_DEMUXER 0
-%define CONFIG_GSM_DEMUXER 0
-%define CONFIG_GXF_DEMUXER 0
-%define CONFIG_H261_DEMUXER 0
-%define CONFIG_H263_DEMUXER 0
-%define CONFIG_H264_DEMUXER 0
-%define CONFIG_HEVC_DEMUXER 0
-%define CONFIG_HLS_DEMUXER 0
-%define CONFIG_HNM_DEMUXER 0
-%define CONFIG_ICO_DEMUXER 0
-%define CONFIG_IDCIN_DEMUXER 0
-%define CONFIG_IDF_DEMUXER 0
-%define CONFIG_IFF_DEMUXER 0
-%define CONFIG_ILBC_DEMUXER 0
-%define CONFIG_IMAGE2_DEMUXER 0
-%define CONFIG_IMAGE2PIPE_DEMUXER 0
-%define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-%define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-%define CONFIG_INGENIENT_DEMUXER 0
-%define CONFIG_IPMOVIE_DEMUXER 0
-%define CONFIG_IRCAM_DEMUXER 0
-%define CONFIG_ISS_DEMUXER 0
-%define CONFIG_IV8_DEMUXER 0
-%define CONFIG_IVF_DEMUXER 0
-%define CONFIG_IVR_DEMUXER 0
-%define CONFIG_JACOSUB_DEMUXER 0
-%define CONFIG_JV_DEMUXER 0
-%define CONFIG_LMLM4_DEMUXER 0
-%define CONFIG_LOAS_DEMUXER 0
-%define CONFIG_LRC_DEMUXER 0
-%define CONFIG_LVF_DEMUXER 0
-%define CONFIG_LXF_DEMUXER 0
-%define CONFIG_M4V_DEMUXER 0
-%define CONFIG_MATROSKA_DEMUXER 0
-%define CONFIG_MGSTS_DEMUXER 0
-%define CONFIG_MICRODVD_DEMUXER 0
-%define CONFIG_MJPEG_DEMUXER 0
-%define CONFIG_MLP_DEMUXER 0
-%define CONFIG_MLV_DEMUXER 0
-%define CONFIG_MM_DEMUXER 0
-%define CONFIG_MMF_DEMUXER 0
-%define CONFIG_MOV_DEMUXER 0
-%define CONFIG_MP3_DEMUXER 0
-%define CONFIG_MPC_DEMUXER 0
-%define CONFIG_MPC8_DEMUXER 0
-%define CONFIG_MPEGPS_DEMUXER 0
-%define CONFIG_MPEGTS_DEMUXER 0
-%define CONFIG_MPEGTSRAW_DEMUXER 0
-%define CONFIG_MPEGVIDEO_DEMUXER 0
-%define CONFIG_MPJPEG_DEMUXER 0
-%define CONFIG_MPL2_DEMUXER 0
-%define CONFIG_MPSUB_DEMUXER 0
-%define CONFIG_MSF_DEMUXER 0
-%define CONFIG_MSNWC_TCP_DEMUXER 0
-%define CONFIG_MTAF_DEMUXER 0
-%define CONFIG_MTV_DEMUXER 0
-%define CONFIG_MUSX_DEMUXER 0
-%define CONFIG_MV_DEMUXER 0
-%define CONFIG_MVI_DEMUXER 0
-%define CONFIG_MXF_DEMUXER 0
-%define CONFIG_MXG_DEMUXER 0
-%define CONFIG_NC_DEMUXER 0
-%define CONFIG_NISTSPHERE_DEMUXER 0
-%define CONFIG_NSV_DEMUXER 0
-%define CONFIG_NUT_DEMUXER 0
-%define CONFIG_NUV_DEMUXER 0
-%define CONFIG_OGG_DEMUXER 0
-%define CONFIG_OMA_DEMUXER 0
-%define CONFIG_PAF_DEMUXER 0
-%define CONFIG_PCM_ALAW_DEMUXER 0
-%define CONFIG_PCM_MULAW_DEMUXER 0
-%define CONFIG_PCM_F64BE_DEMUXER 0
-%define CONFIG_PCM_F64LE_DEMUXER 0
-%define CONFIG_PCM_F32BE_DEMUXER 0
-%define CONFIG_PCM_F32LE_DEMUXER 0
-%define CONFIG_PCM_S32BE_DEMUXER 0
-%define CONFIG_PCM_S32LE_DEMUXER 0
-%define CONFIG_PCM_S24BE_DEMUXER 0
-%define CONFIG_PCM_S24LE_DEMUXER 0
-%define CONFIG_PCM_S16BE_DEMUXER 0
-%define CONFIG_PCM_S16LE_DEMUXER 0
-%define CONFIG_PCM_S8_DEMUXER 0
-%define CONFIG_PCM_U32BE_DEMUXER 0
-%define CONFIG_PCM_U32LE_DEMUXER 0
-%define CONFIG_PCM_U24BE_DEMUXER 0
-%define CONFIG_PCM_U24LE_DEMUXER 0
-%define CONFIG_PCM_U16BE_DEMUXER 0
-%define CONFIG_PCM_U16LE_DEMUXER 0
-%define CONFIG_PCM_U8_DEMUXER 0
-%define CONFIG_PJS_DEMUXER 0
-%define CONFIG_PMP_DEMUXER 0
-%define CONFIG_PVA_DEMUXER 0
-%define CONFIG_PVF_DEMUXER 0
-%define CONFIG_QCP_DEMUXER 0
-%define CONFIG_R3D_DEMUXER 0
-%define CONFIG_RAWVIDEO_DEMUXER 0
-%define CONFIG_REALTEXT_DEMUXER 0
-%define CONFIG_REDSPARK_DEMUXER 0
-%define CONFIG_RL2_DEMUXER 0
-%define CONFIG_RM_DEMUXER 0
-%define CONFIG_ROQ_DEMUXER 0
-%define CONFIG_RPL_DEMUXER 0
-%define CONFIG_RSD_DEMUXER 0
-%define CONFIG_RSO_DEMUXER 0
-%define CONFIG_RTP_DEMUXER 0
-%define CONFIG_RTSP_DEMUXER 0
-%define CONFIG_SAMI_DEMUXER 0
-%define CONFIG_SAP_DEMUXER 0
-%define CONFIG_SBG_DEMUXER 0
-%define CONFIG_SDP_DEMUXER 0
-%define CONFIG_SDR2_DEMUXER 0
-%define CONFIG_SEGAFILM_DEMUXER 0
-%define CONFIG_SHORTEN_DEMUXER 0
-%define CONFIG_SIFF_DEMUXER 0
-%define CONFIG_SLN_DEMUXER 0
-%define CONFIG_SMACKER_DEMUXER 0
-%define CONFIG_SMJPEG_DEMUXER 0
-%define CONFIG_SMUSH_DEMUXER 0
-%define CONFIG_SOL_DEMUXER 0
-%define CONFIG_SOX_DEMUXER 0
-%define CONFIG_SPDIF_DEMUXER 0
-%define CONFIG_SRT_DEMUXER 0
-%define CONFIG_STR_DEMUXER 0
-%define CONFIG_STL_DEMUXER 0
-%define CONFIG_SUBVIEWER1_DEMUXER 0
-%define CONFIG_SUBVIEWER_DEMUXER 0
-%define CONFIG_SUP_DEMUXER 0
-%define CONFIG_SVAG_DEMUXER 0
-%define CONFIG_SWF_DEMUXER 0
-%define CONFIG_TAK_DEMUXER 0
-%define CONFIG_TEDCAPTIONS_DEMUXER 0
-%define CONFIG_THP_DEMUXER 0
-%define CONFIG_THREEDOSTR_DEMUXER 0
-%define CONFIG_TIERTEXSEQ_DEMUXER 0
-%define CONFIG_TMV_DEMUXER 0
-%define CONFIG_TRUEHD_DEMUXER 0
-%define CONFIG_TTA_DEMUXER 0
-%define CONFIG_TXD_DEMUXER 0
-%define CONFIG_TTY_DEMUXER 0
-%define CONFIG_V210_DEMUXER 0
-%define CONFIG_V210X_DEMUXER 0
-%define CONFIG_VAG_DEMUXER 0
-%define CONFIG_VC1_DEMUXER 0
-%define CONFIG_VC1T_DEMUXER 0
-%define CONFIG_VIVO_DEMUXER 0
-%define CONFIG_VMD_DEMUXER 0
-%define CONFIG_VOBSUB_DEMUXER 0
-%define CONFIG_VOC_DEMUXER 0
-%define CONFIG_VPK_DEMUXER 0
-%define CONFIG_VPLAYER_DEMUXER 0
-%define CONFIG_VQF_DEMUXER 0
-%define CONFIG_W64_DEMUXER 0
-%define CONFIG_WAV_DEMUXER 0
-%define CONFIG_WC3_DEMUXER 0
-%define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-%define CONFIG_WEBVTT_DEMUXER 0
-%define CONFIG_WSAUD_DEMUXER 0
-%define CONFIG_WSD_DEMUXER 0
-%define CONFIG_WSVQA_DEMUXER 0
-%define CONFIG_WTV_DEMUXER 0
-%define CONFIG_WVE_DEMUXER 0
-%define CONFIG_WV_DEMUXER 0
-%define CONFIG_XA_DEMUXER 0
-%define CONFIG_XBIN_DEMUXER 0
-%define CONFIG_XMV_DEMUXER 0
-%define CONFIG_XVAG_DEMUXER 0
-%define CONFIG_XWMA_DEMUXER 0
-%define CONFIG_YOP_DEMUXER 0
-%define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-%define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-%define CONFIG_LIBGME_DEMUXER 0
-%define CONFIG_LIBMODPLUG_DEMUXER 0
-%define CONFIG_LIBNUT_DEMUXER 0
-%define CONFIG_LIBOPENMPT_DEMUXER 0
-%define CONFIG_A64MULTI_ENCODER 0
-%define CONFIG_A64MULTI5_ENCODER 0
-%define CONFIG_ALIAS_PIX_ENCODER 0
-%define CONFIG_AMV_ENCODER 0
-%define CONFIG_APNG_ENCODER 0
-%define CONFIG_ASV1_ENCODER 0
-%define CONFIG_ASV2_ENCODER 0
-%define CONFIG_AVRP_ENCODER 0
-%define CONFIG_AVUI_ENCODER 0
-%define CONFIG_AYUV_ENCODER 0
-%define CONFIG_BMP_ENCODER 0
-%define CONFIG_CINEPAK_ENCODER 0
-%define CONFIG_CLJR_ENCODER 0
-%define CONFIG_COMFORTNOISE_ENCODER 0
-%define CONFIG_DNXHD_ENCODER 0
-%define CONFIG_DPX_ENCODER 0
-%define CONFIG_DVVIDEO_ENCODER 0
-%define CONFIG_FFV1_ENCODER 0
-%define CONFIG_FFVHUFF_ENCODER 0
-%define CONFIG_FLASHSV_ENCODER 0
-%define CONFIG_FLASHSV2_ENCODER 0
-%define CONFIG_FLV_ENCODER 0
-%define CONFIG_GIF_ENCODER 0
-%define CONFIG_H261_ENCODER 0
-%define CONFIG_H263_ENCODER 0
-%define CONFIG_H263P_ENCODER 0
-%define CONFIG_HAP_ENCODER 0
-%define CONFIG_HUFFYUV_ENCODER 0
-%define CONFIG_JPEG2000_ENCODER 0
-%define CONFIG_JPEGLS_ENCODER 0
-%define CONFIG_LJPEG_ENCODER 0
-%define CONFIG_MJPEG_ENCODER 0
-%define CONFIG_MPEG1VIDEO_ENCODER 0
-%define CONFIG_MPEG2VIDEO_ENCODER 0
-%define CONFIG_MPEG4_ENCODER 0
-%define CONFIG_MSMPEG4V2_ENCODER 0
-%define CONFIG_MSMPEG4V3_ENCODER 0
-%define CONFIG_MSVIDEO1_ENCODER 0
-%define CONFIG_PAM_ENCODER 0
-%define CONFIG_PBM_ENCODER 0
-%define CONFIG_PCX_ENCODER 0
-%define CONFIG_PGM_ENCODER 0
-%define CONFIG_PGMYUV_ENCODER 0
-%define CONFIG_PNG_ENCODER 0
-%define CONFIG_PPM_ENCODER 0
-%define CONFIG_PRORES_ENCODER 0
-%define CONFIG_PRORES_AW_ENCODER 0
-%define CONFIG_PRORES_KS_ENCODER 0
-%define CONFIG_QTRLE_ENCODER 0
-%define CONFIG_R10K_ENCODER 0
-%define CONFIG_R210_ENCODER 0
-%define CONFIG_RAWVIDEO_ENCODER 0
-%define CONFIG_ROQ_ENCODER 0
-%define CONFIG_RV10_ENCODER 0
-%define CONFIG_RV20_ENCODER 0
-%define CONFIG_S302M_ENCODER 0
-%define CONFIG_SGI_ENCODER 0
-%define CONFIG_SNOW_ENCODER 0
-%define CONFIG_SUNRAST_ENCODER 0
-%define CONFIG_SVQ1_ENCODER 0
-%define CONFIG_TARGA_ENCODER 0
-%define CONFIG_TIFF_ENCODER 0
-%define CONFIG_UTVIDEO_ENCODER 0
-%define CONFIG_V210_ENCODER 0
-%define CONFIG_V308_ENCODER 0
-%define CONFIG_V408_ENCODER 0
-%define CONFIG_V410_ENCODER 0
-%define CONFIG_VC2_ENCODER 0
-%define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-%define CONFIG_WMV1_ENCODER 0
-%define CONFIG_WMV2_ENCODER 0
-%define CONFIG_XBM_ENCODER 0
-%define CONFIG_XFACE_ENCODER 0
-%define CONFIG_XWD_ENCODER 0
-%define CONFIG_Y41P_ENCODER 0
-%define CONFIG_YUV4_ENCODER 0
-%define CONFIG_ZLIB_ENCODER 0
-%define CONFIG_ZMBV_ENCODER 0
-%define CONFIG_AAC_ENCODER 0
-%define CONFIG_AC3_ENCODER 0
-%define CONFIG_AC3_FIXED_ENCODER 0
-%define CONFIG_ALAC_ENCODER 0
-%define CONFIG_DCA_ENCODER 0
-%define CONFIG_EAC3_ENCODER 0
-%define CONFIG_FLAC_ENCODER 0
-%define CONFIG_G723_1_ENCODER 0
-%define CONFIG_MLP_ENCODER 0
-%define CONFIG_MP2_ENCODER 0
-%define CONFIG_MP2FIXED_ENCODER 0
-%define CONFIG_NELLYMOSER_ENCODER 0
-%define CONFIG_RA_144_ENCODER 0
-%define CONFIG_SONIC_ENCODER 0
-%define CONFIG_SONIC_LS_ENCODER 0
-%define CONFIG_TRUEHD_ENCODER 0
-%define CONFIG_TTA_ENCODER 0
-%define CONFIG_VORBIS_ENCODER 0
-%define CONFIG_WAVPACK_ENCODER 0
-%define CONFIG_WMAV1_ENCODER 0
-%define CONFIG_WMAV2_ENCODER 0
-%define CONFIG_PCM_ALAW_ENCODER 0
-%define CONFIG_PCM_F32BE_ENCODER 0
-%define CONFIG_PCM_F32LE_ENCODER 0
-%define CONFIG_PCM_F64BE_ENCODER 0
-%define CONFIG_PCM_F64LE_ENCODER 0
-%define CONFIG_PCM_MULAW_ENCODER 0
-%define CONFIG_PCM_S8_ENCODER 0
-%define CONFIG_PCM_S8_PLANAR_ENCODER 0
-%define CONFIG_PCM_S16BE_ENCODER 0
-%define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S16LE_ENCODER 0
-%define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S24BE_ENCODER 0
-%define CONFIG_PCM_S24DAUD_ENCODER 0
-%define CONFIG_PCM_S24LE_ENCODER 0
-%define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S32BE_ENCODER 0
-%define CONFIG_PCM_S32LE_ENCODER 0
-%define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S64BE_ENCODER 0
-%define CONFIG_PCM_S64LE_ENCODER 0
-%define CONFIG_PCM_U8_ENCODER 0
-%define CONFIG_PCM_U16BE_ENCODER 0
-%define CONFIG_PCM_U16LE_ENCODER 0
-%define CONFIG_PCM_U24BE_ENCODER 0
-%define CONFIG_PCM_U24LE_ENCODER 0
-%define CONFIG_PCM_U32BE_ENCODER 0
-%define CONFIG_PCM_U32LE_ENCODER 0
-%define CONFIG_ROQ_DPCM_ENCODER 0
-%define CONFIG_ADPCM_ADX_ENCODER 0
-%define CONFIG_ADPCM_G722_ENCODER 0
-%define CONFIG_ADPCM_G726_ENCODER 0
-%define CONFIG_ADPCM_IMA_QT_ENCODER 0
-%define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-%define CONFIG_ADPCM_MS_ENCODER 0
-%define CONFIG_ADPCM_SWF_ENCODER 0
-%define CONFIG_ADPCM_YAMAHA_ENCODER 0
-%define CONFIG_SSA_ENCODER 0
-%define CONFIG_ASS_ENCODER 0
-%define CONFIG_DVBSUB_ENCODER 0
-%define CONFIG_DVDSUB_ENCODER 0
-%define CONFIG_MOVTEXT_ENCODER 0
-%define CONFIG_SRT_ENCODER 0
-%define CONFIG_SUBRIP_ENCODER 0
-%define CONFIG_TEXT_ENCODER 0
-%define CONFIG_WEBVTT_ENCODER 0
-%define CONFIG_XSUB_ENCODER 0
-%define CONFIG_AAC_AT_ENCODER 0
-%define CONFIG_ALAC_AT_ENCODER 0
-%define CONFIG_ILBC_AT_ENCODER 0
-%define CONFIG_PCM_ALAW_AT_ENCODER 0
-%define CONFIG_PCM_MULAW_AT_ENCODER 0
-%define CONFIG_LIBFDK_AAC_ENCODER 0
-%define CONFIG_LIBGSM_ENCODER 0
-%define CONFIG_LIBGSM_MS_ENCODER 0
-%define CONFIG_LIBILBC_ENCODER 0
-%define CONFIG_LIBMP3LAME_ENCODER 0
-%define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-%define CONFIG_LIBOPENJPEG_ENCODER 0
-%define CONFIG_LIBOPUS_ENCODER 0
-%define CONFIG_LIBSCHROEDINGER_ENCODER 0
-%define CONFIG_LIBSHINE_ENCODER 0
-%define CONFIG_LIBSPEEX_ENCODER 0
-%define CONFIG_LIBTHEORA_ENCODER 0
-%define CONFIG_LIBTWOLAME_ENCODER 0
-%define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-%define CONFIG_LIBVORBIS_ENCODER 0
-%define CONFIG_LIBVPX_VP8_ENCODER 0
-%define CONFIG_LIBVPX_VP9_ENCODER 0
-%define CONFIG_LIBWAVPACK_ENCODER 0
-%define CONFIG_LIBWEBP_ANIM_ENCODER 0
-%define CONFIG_LIBWEBP_ENCODER 0
-%define CONFIG_LIBX262_ENCODER 0
-%define CONFIG_LIBX264_ENCODER 0
-%define CONFIG_LIBX264RGB_ENCODER 0
-%define CONFIG_LIBX265_ENCODER 0
-%define CONFIG_LIBXAVS_ENCODER 0
-%define CONFIG_LIBXVID_ENCODER 0
-%define CONFIG_LIBOPENH264_ENCODER 0
-%define CONFIG_H264_NVENC_ENCODER 0
-%define CONFIG_H264_OMX_ENCODER 0
-%define CONFIG_H264_QSV_ENCODER 0
-%define CONFIG_H264_VAAPI_ENCODER 0
-%define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-%define CONFIG_NVENC_ENCODER 0
-%define CONFIG_NVENC_H264_ENCODER 0
-%define CONFIG_NVENC_HEVC_ENCODER 0
-%define CONFIG_HEVC_NVENC_ENCODER 0
-%define CONFIG_HEVC_QSV_ENCODER 0
-%define CONFIG_HEVC_VAAPI_ENCODER 0
-%define CONFIG_LIBKVAZAAR_ENCODER 0
-%define CONFIG_MJPEG_VAAPI_ENCODER 0
-%define CONFIG_MPEG2_QSV_ENCODER 0
-%define CONFIG_ABENCH_FILTER 0
-%define CONFIG_ACOMPRESSOR_FILTER 0
-%define CONFIG_ACROSSFADE_FILTER 0
-%define CONFIG_ACRUSHER_FILTER 0
-%define CONFIG_ADELAY_FILTER 0
-%define CONFIG_AECHO_FILTER 0
-%define CONFIG_AEMPHASIS_FILTER 0
-%define CONFIG_AEVAL_FILTER 0
-%define CONFIG_AFADE_FILTER 0
-%define CONFIG_AFFTFILT_FILTER 0
-%define CONFIG_AFORMAT_FILTER 0
-%define CONFIG_AGATE_FILTER 0
-%define CONFIG_AINTERLEAVE_FILTER 0
-%define CONFIG_ALIMITER_FILTER 0
-%define CONFIG_ALLPASS_FILTER 0
-%define CONFIG_ALOOP_FILTER 0
-%define CONFIG_AMERGE_FILTER 0
-%define CONFIG_AMETADATA_FILTER 0
-%define CONFIG_AMIX_FILTER 0
-%define CONFIG_ANEQUALIZER_FILTER 0
-%define CONFIG_ANULL_FILTER 0
-%define CONFIG_APAD_FILTER 0
-%define CONFIG_APERMS_FILTER 0
-%define CONFIG_APHASER_FILTER 0
-%define CONFIG_APULSATOR_FILTER 0
-%define CONFIG_AREALTIME_FILTER 0
-%define CONFIG_ARESAMPLE_FILTER 0
-%define CONFIG_AREVERSE_FILTER 0
-%define CONFIG_ASELECT_FILTER 0
-%define CONFIG_ASENDCMD_FILTER 0
-%define CONFIG_ASETNSAMPLES_FILTER 0
-%define CONFIG_ASETPTS_FILTER 0
-%define CONFIG_ASETRATE_FILTER 0
-%define CONFIG_ASETTB_FILTER 0
-%define CONFIG_ASHOWINFO_FILTER 0
-%define CONFIG_ASIDEDATA_FILTER 0
-%define CONFIG_ASPLIT_FILTER 0
-%define CONFIG_ASTATS_FILTER 0
-%define CONFIG_ASTREAMSELECT_FILTER 0
-%define CONFIG_ASYNCTS_FILTER 0
-%define CONFIG_ATEMPO_FILTER 0
-%define CONFIG_ATRIM_FILTER 0
-%define CONFIG_AZMQ_FILTER 0
-%define CONFIG_BANDPASS_FILTER 0
-%define CONFIG_BANDREJECT_FILTER 0
-%define CONFIG_BASS_FILTER 0
-%define CONFIG_BIQUAD_FILTER 0
-%define CONFIG_BS2B_FILTER 0
-%define CONFIG_CHANNELMAP_FILTER 0
-%define CONFIG_CHANNELSPLIT_FILTER 0
-%define CONFIG_CHORUS_FILTER 0
-%define CONFIG_COMPAND_FILTER 0
-%define CONFIG_COMPENSATIONDELAY_FILTER 0
-%define CONFIG_CRYSTALIZER_FILTER 0
-%define CONFIG_DCSHIFT_FILTER 0
-%define CONFIG_DYNAUDNORM_FILTER 0
-%define CONFIG_EARWAX_FILTER 0
-%define CONFIG_EBUR128_FILTER 0
-%define CONFIG_EQUALIZER_FILTER 0
-%define CONFIG_EXTRASTEREO_FILTER 0
-%define CONFIG_FIREQUALIZER_FILTER 0
-%define CONFIG_FLANGER_FILTER 0
-%define CONFIG_HDCD_FILTER 0
-%define CONFIG_HIGHPASS_FILTER 0
-%define CONFIG_JOIN_FILTER 0
-%define CONFIG_LADSPA_FILTER 0
-%define CONFIG_LOUDNORM_FILTER 0
-%define CONFIG_LOWPASS_FILTER 0
-%define CONFIG_PAN_FILTER 0
-%define CONFIG_REPLAYGAIN_FILTER 0
-%define CONFIG_RESAMPLE_FILTER 0
-%define CONFIG_RUBBERBAND_FILTER 0
-%define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-%define CONFIG_SIDECHAINGATE_FILTER 0
-%define CONFIG_SILENCEDETECT_FILTER 0
-%define CONFIG_SILENCEREMOVE_FILTER 0
-%define CONFIG_SOFALIZER_FILTER 0
-%define CONFIG_STEREOTOOLS_FILTER 0
-%define CONFIG_STEREOWIDEN_FILTER 0
-%define CONFIG_TREBLE_FILTER 0
-%define CONFIG_TREMOLO_FILTER 0
-%define CONFIG_VIBRATO_FILTER 0
-%define CONFIG_VOLUME_FILTER 0
-%define CONFIG_VOLUMEDETECT_FILTER 0
-%define CONFIG_AEVALSRC_FILTER 0
-%define CONFIG_ANOISESRC_FILTER 0
-%define CONFIG_ANULLSRC_FILTER 0
-%define CONFIG_FLITE_FILTER 0
-%define CONFIG_SINE_FILTER 0
-%define CONFIG_ANULLSINK_FILTER 0
-%define CONFIG_ALPHAEXTRACT_FILTER 0
-%define CONFIG_ALPHAMERGE_FILTER 0
-%define CONFIG_ASS_FILTER 0
-%define CONFIG_ATADENOISE_FILTER 0
-%define CONFIG_AVGBLUR_FILTER 0
-%define CONFIG_BBOX_FILTER 0
-%define CONFIG_BENCH_FILTER 0
-%define CONFIG_BITPLANENOISE_FILTER 0
-%define CONFIG_BLACKDETECT_FILTER 0
-%define CONFIG_BLACKFRAME_FILTER 0
-%define CONFIG_BLEND_FILTER 0
-%define CONFIG_BOXBLUR_FILTER 0
-%define CONFIG_BWDIF_FILTER 0
-%define CONFIG_CHROMAKEY_FILTER 0
-%define CONFIG_CIESCOPE_FILTER 0
-%define CONFIG_CODECVIEW_FILTER 0
-%define CONFIG_COLORBALANCE_FILTER 0
-%define CONFIG_COLORCHANNELMIXER_FILTER 0
-%define CONFIG_COLORKEY_FILTER 0
-%define CONFIG_COLORLEVELS_FILTER 0
-%define CONFIG_COLORMATRIX_FILTER 0
-%define CONFIG_COLORSPACE_FILTER 0
-%define CONFIG_CONVOLUTION_FILTER 0
-%define CONFIG_COPY_FILTER 0
-%define CONFIG_COREIMAGE_FILTER 0
-%define CONFIG_COVER_RECT_FILTER 0
-%define CONFIG_CROP_FILTER 0
-%define CONFIG_CROPDETECT_FILTER 0
-%define CONFIG_CURVES_FILTER 0
-%define CONFIG_DATASCOPE_FILTER 0
-%define CONFIG_DCTDNOIZ_FILTER 0
-%define CONFIG_DEBAND_FILTER 0
-%define CONFIG_DECIMATE_FILTER 0
-%define CONFIG_DEFLATE_FILTER 0
-%define CONFIG_DEJUDDER_FILTER 0
-%define CONFIG_DELOGO_FILTER 0
-%define CONFIG_DESHAKE_FILTER 0
-%define CONFIG_DETELECINE_FILTER 0
-%define CONFIG_DILATION_FILTER 0
-%define CONFIG_DISPLACE_FILTER 0
-%define CONFIG_DRAWBOX_FILTER 0
-%define CONFIG_DRAWGRAPH_FILTER 0
-%define CONFIG_DRAWGRID_FILTER 0
-%define CONFIG_DRAWTEXT_FILTER 0
-%define CONFIG_EDGEDETECT_FILTER 0
-%define CONFIG_ELBG_FILTER 0
-%define CONFIG_EQ_FILTER 0
-%define CONFIG_EROSION_FILTER 0
-%define CONFIG_EXTRACTPLANES_FILTER 0
-%define CONFIG_FADE_FILTER 0
-%define CONFIG_FFTFILT_FILTER 0
-%define CONFIG_FIELD_FILTER 0
-%define CONFIG_FIELDHINT_FILTER 0
-%define CONFIG_FIELDMATCH_FILTER 0
-%define CONFIG_FIELDORDER_FILTER 0
-%define CONFIG_FIND_RECT_FILTER 0
-%define CONFIG_FORMAT_FILTER 0
-%define CONFIG_FPS_FILTER 0
-%define CONFIG_FRAMEPACK_FILTER 0
-%define CONFIG_FRAMERATE_FILTER 0
-%define CONFIG_FRAMESTEP_FILTER 0
-%define CONFIG_FREI0R_FILTER 0
-%define CONFIG_FSPP_FILTER 0
-%define CONFIG_GBLUR_FILTER 0
-%define CONFIG_GEQ_FILTER 0
-%define CONFIG_GRADFUN_FILTER 0
-%define CONFIG_HALDCLUT_FILTER 0
-%define CONFIG_HFLIP_FILTER 0
-%define CONFIG_HISTEQ_FILTER 0
-%define CONFIG_HISTOGRAM_FILTER 0
-%define CONFIG_HQDN3D_FILTER 0
-%define CONFIG_HQX_FILTER 0
-%define CONFIG_HSTACK_FILTER 0
-%define CONFIG_HUE_FILTER 0
-%define CONFIG_HWDOWNLOAD_FILTER 0
-%define CONFIG_HWUPLOAD_FILTER 0
-%define CONFIG_HWUPLOAD_CUDA_FILTER 0
-%define CONFIG_HYSTERESIS_FILTER 0
-%define CONFIG_IDET_FILTER 0
-%define CONFIG_IL_FILTER 0
-%define CONFIG_INFLATE_FILTER 0
-%define CONFIG_INTERLACE_FILTER 0
-%define CONFIG_INTERLEAVE_FILTER 0
-%define CONFIG_KERNDEINT_FILTER 0
-%define CONFIG_LENSCORRECTION_FILTER 0
-%define CONFIG_LOOP_FILTER 0
-%define CONFIG_LUT_FILTER 0
-%define CONFIG_LUT2_FILTER 0
-%define CONFIG_LUT3D_FILTER 0
-%define CONFIG_LUTRGB_FILTER 0
-%define CONFIG_LUTYUV_FILTER 0
-%define CONFIG_MASKEDCLAMP_FILTER 0
-%define CONFIG_MASKEDMERGE_FILTER 0
-%define CONFIG_MCDEINT_FILTER 0
-%define CONFIG_MERGEPLANES_FILTER 0
-%define CONFIG_MESTIMATE_FILTER 0
-%define CONFIG_METADATA_FILTER 0
-%define CONFIG_MINTERPOLATE_FILTER 0
-%define CONFIG_MPDECIMATE_FILTER 0
-%define CONFIG_NEGATE_FILTER 0
-%define CONFIG_NLMEANS_FILTER 0
-%define CONFIG_NNEDI_FILTER 0
-%define CONFIG_NOFORMAT_FILTER 0
-%define CONFIG_NOISE_FILTER 0
-%define CONFIG_NULL_FILTER 0
-%define CONFIG_OCR_FILTER 0
-%define CONFIG_OCV_FILTER 0
-%define CONFIG_OVERLAY_FILTER 0
-%define CONFIG_OWDENOISE_FILTER 0
-%define CONFIG_PAD_FILTER 0
-%define CONFIG_PALETTEGEN_FILTER 0
-%define CONFIG_PALETTEUSE_FILTER 0
-%define CONFIG_PERMS_FILTER 0
-%define CONFIG_PERSPECTIVE_FILTER 0
-%define CONFIG_PHASE_FILTER 0
-%define CONFIG_PIXDESCTEST_FILTER 0
-%define CONFIG_PP_FILTER 0
-%define CONFIG_PP7_FILTER 0
-%define CONFIG_PREWITT_FILTER 0
-%define CONFIG_PSNR_FILTER 0
-%define CONFIG_PULLUP_FILTER 0
-%define CONFIG_QP_FILTER 0
-%define CONFIG_RANDOM_FILTER 0
-%define CONFIG_READVITC_FILTER 0
-%define CONFIG_REALTIME_FILTER 0
-%define CONFIG_REMAP_FILTER 0
-%define CONFIG_REMOVEGRAIN_FILTER 0
-%define CONFIG_REMOVELOGO_FILTER 0
-%define CONFIG_REPEATFIELDS_FILTER 0
-%define CONFIG_REVERSE_FILTER 0
-%define CONFIG_ROTATE_FILTER 0
-%define CONFIG_SAB_FILTER 0
-%define CONFIG_SCALE_FILTER 0
-%define CONFIG_SCALE_NPP_FILTER 0
-%define CONFIG_SCALE_VAAPI_FILTER 0
-%define CONFIG_SCALE2REF_FILTER 0
-%define CONFIG_SELECT_FILTER 0
-%define CONFIG_SELECTIVECOLOR_FILTER 0
-%define CONFIG_SENDCMD_FILTER 0
-%define CONFIG_SEPARATEFIELDS_FILTER 0
-%define CONFIG_SETDAR_FILTER 0
-%define CONFIG_SETFIELD_FILTER 0
-%define CONFIG_SETPTS_FILTER 0
-%define CONFIG_SETSAR_FILTER 0
-%define CONFIG_SETTB_FILTER 0
-%define CONFIG_SHOWINFO_FILTER 0
-%define CONFIG_SHOWPALETTE_FILTER 0
-%define CONFIG_SHUFFLEFRAMES_FILTER 0
-%define CONFIG_SHUFFLEPLANES_FILTER 0
-%define CONFIG_SIDEDATA_FILTER 0
-%define CONFIG_SIGNALSTATS_FILTER 0
-%define CONFIG_SMARTBLUR_FILTER 0
-%define CONFIG_SOBEL_FILTER 0
-%define CONFIG_SPLIT_FILTER 0
-%define CONFIG_SPP_FILTER 0
-%define CONFIG_SSIM_FILTER 0
-%define CONFIG_STEREO3D_FILTER 0
-%define CONFIG_STREAMSELECT_FILTER 0
-%define CONFIG_SUBTITLES_FILTER 0
-%define CONFIG_SUPER2XSAI_FILTER 0
-%define CONFIG_SWAPRECT_FILTER 0
-%define CONFIG_SWAPUV_FILTER 0
-%define CONFIG_TBLEND_FILTER 0
-%define CONFIG_TELECINE_FILTER 0
-%define CONFIG_THUMBNAIL_FILTER 0
-%define CONFIG_TILE_FILTER 0
-%define CONFIG_TINTERLACE_FILTER 0
-%define CONFIG_TRANSPOSE_FILTER 0
-%define CONFIG_TRIM_FILTER 0
-%define CONFIG_UNSHARP_FILTER 0
-%define CONFIG_USPP_FILTER 0
-%define CONFIG_VAGUEDENOISER_FILTER 0
-%define CONFIG_VECTORSCOPE_FILTER 0
-%define CONFIG_VFLIP_FILTER 0
-%define CONFIG_VIDSTABDETECT_FILTER 0
-%define CONFIG_VIDSTABTRANSFORM_FILTER 0
-%define CONFIG_VIGNETTE_FILTER 0
-%define CONFIG_VSTACK_FILTER 0
-%define CONFIG_W3FDIF_FILTER 0
-%define CONFIG_WAVEFORM_FILTER 0
-%define CONFIG_WEAVE_FILTER 0
-%define CONFIG_XBR_FILTER 0
-%define CONFIG_YADIF_FILTER 0
-%define CONFIG_ZMQ_FILTER 0
-%define CONFIG_ZOOMPAN_FILTER 0
-%define CONFIG_ZSCALE_FILTER 0
-%define CONFIG_ALLRGB_FILTER 0
-%define CONFIG_ALLYUV_FILTER 0
-%define CONFIG_CELLAUTO_FILTER 0
-%define CONFIG_COLOR_FILTER 0
-%define CONFIG_COREIMAGESRC_FILTER 0
-%define CONFIG_FREI0R_SRC_FILTER 0
-%define CONFIG_HALDCLUTSRC_FILTER 0
-%define CONFIG_LIFE_FILTER 0
-%define CONFIG_MANDELBROT_FILTER 0
-%define CONFIG_MPTESTSRC_FILTER 0
-%define CONFIG_NULLSRC_FILTER 0
-%define CONFIG_RGBTESTSRC_FILTER 0
-%define CONFIG_SMPTEBARS_FILTER 0
-%define CONFIG_SMPTEHDBARS_FILTER 0
-%define CONFIG_TESTSRC_FILTER 0
-%define CONFIG_TESTSRC2_FILTER 0
-%define CONFIG_YUVTESTSRC_FILTER 0
-%define CONFIG_NULLSINK_FILTER 0
-%define CONFIG_ADRAWGRAPH_FILTER 0
-%define CONFIG_AHISTOGRAM_FILTER 0
-%define CONFIG_APHASEMETER_FILTER 0
-%define CONFIG_AVECTORSCOPE_FILTER 0
-%define CONFIG_CONCAT_FILTER 0
-%define CONFIG_SHOWCQT_FILTER 0
-%define CONFIG_SHOWFREQS_FILTER 0
-%define CONFIG_SHOWSPECTRUM_FILTER 0
-%define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-%define CONFIG_SHOWVOLUME_FILTER 0
-%define CONFIG_SHOWWAVES_FILTER 0
-%define CONFIG_SHOWWAVESPIC_FILTER 0
-%define CONFIG_SPECTRUMSYNTH_FILTER 0
-%define CONFIG_AMOVIE_FILTER 0
-%define CONFIG_MOVIE_FILTER 0
-%define CONFIG_H263_CUVID_HWACCEL 0
-%define CONFIG_H263_VAAPI_HWACCEL 0
-%define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_H264_CUVID_HWACCEL 0
-%define CONFIG_H264_D3D11VA_HWACCEL 0
-%define CONFIG_H264_DXVA2_HWACCEL 0
-%define CONFIG_H264_MEDIACODEC_HWACCEL 0
-%define CONFIG_H264_MMAL_HWACCEL 0
-%define CONFIG_H264_QSV_HWACCEL 0
-%define CONFIG_H264_VAAPI_HWACCEL 0
-%define CONFIG_H264_VDA_HWACCEL 0
-%define CONFIG_H264_VDA_OLD_HWACCEL 0
-%define CONFIG_H264_VDPAU_HWACCEL 0
-%define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_HEVC_CUVID_HWACCEL 0
-%define CONFIG_HEVC_D3D11VA_HWACCEL 0
-%define CONFIG_HEVC_DXVA2_HWACCEL 0
-%define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-%define CONFIG_HEVC_QSV_HWACCEL 0
-%define CONFIG_HEVC_VAAPI_HWACCEL 0
-%define CONFIG_HEVC_VDPAU_HWACCEL 0
-%define CONFIG_MJPEG_CUVID_HWACCEL 0
-%define CONFIG_MPEG1_CUVID_HWACCEL 0
-%define CONFIG_MPEG1_XVMC_HWACCEL 0
-%define CONFIG_MPEG1_VDPAU_HWACCEL 0
-%define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_MPEG2_CUVID_HWACCEL 0
-%define CONFIG_MPEG2_XVMC_HWACCEL 0
-%define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-%define CONFIG_MPEG2_DXVA2_HWACCEL 0
-%define CONFIG_MPEG2_MMAL_HWACCEL 0
-%define CONFIG_MPEG2_QSV_HWACCEL 0
-%define CONFIG_MPEG2_VAAPI_HWACCEL 0
-%define CONFIG_MPEG2_VDPAU_HWACCEL 0
-%define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_MPEG4_CUVID_HWACCEL 0
-%define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-%define CONFIG_MPEG4_MMAL_HWACCEL 0
-%define CONFIG_MPEG4_VAAPI_HWACCEL 0
-%define CONFIG_MPEG4_VDPAU_HWACCEL 0
-%define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_VC1_CUVID_HWACCEL 0
-%define CONFIG_VC1_D3D11VA_HWACCEL 0
-%define CONFIG_VC1_DXVA2_HWACCEL 0
-%define CONFIG_VC1_VAAPI_HWACCEL 0
-%define CONFIG_VC1_VDPAU_HWACCEL 0
-%define CONFIG_VC1_MMAL_HWACCEL 0
-%define CONFIG_VC1_QSV_HWACCEL 0
-%define CONFIG_VP8_CUVID_HWACCEL 0
-%define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-%define CONFIG_VP9_CUVID_HWACCEL 0
-%define CONFIG_VP9_D3D11VA_HWACCEL 0
-%define CONFIG_VP9_DXVA2_HWACCEL 0
-%define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-%define CONFIG_VP9_VAAPI_HWACCEL 0
-%define CONFIG_WMV3_D3D11VA_HWACCEL 0
-%define CONFIG_WMV3_DXVA2_HWACCEL 0
-%define CONFIG_WMV3_VAAPI_HWACCEL 0
-%define CONFIG_WMV3_VDPAU_HWACCEL 0
-%define CONFIG_ALSA_INDEV 0
-%define CONFIG_AVFOUNDATION_INDEV 0
-%define CONFIG_BKTR_INDEV 0
-%define CONFIG_DECKLINK_INDEV 0
-%define CONFIG_DSHOW_INDEV 0
-%define CONFIG_DV1394_INDEV 0
-%define CONFIG_FBDEV_INDEV 0
-%define CONFIG_GDIGRAB_INDEV 0
-%define CONFIG_IEC61883_INDEV 0
-%define CONFIG_JACK_INDEV 0
-%define CONFIG_LAVFI_INDEV 0
-%define CONFIG_OPENAL_INDEV 0
-%define CONFIG_OSS_INDEV 0
-%define CONFIG_PULSE_INDEV 0
-%define CONFIG_QTKIT_INDEV 0
-%define CONFIG_SNDIO_INDEV 0
-%define CONFIG_V4L2_INDEV 0
-%define CONFIG_VFWCAP_INDEV 0
-%define CONFIG_X11GRAB_INDEV 0
-%define CONFIG_X11GRAB_XCB_INDEV 0
-%define CONFIG_LIBCDIO_INDEV 0
-%define CONFIG_LIBDC1394_INDEV 0
-%define CONFIG_A64_MUXER 0
-%define CONFIG_AC3_MUXER 0
-%define CONFIG_ADTS_MUXER 0
-%define CONFIG_ADX_MUXER 0
-%define CONFIG_AIFF_MUXER 0
-%define CONFIG_AMR_MUXER 0
-%define CONFIG_APNG_MUXER 0
-%define CONFIG_ASF_MUXER 0
-%define CONFIG_ASS_MUXER 0
-%define CONFIG_AST_MUXER 0
-%define CONFIG_ASF_STREAM_MUXER 0
-%define CONFIG_AU_MUXER 0
-%define CONFIG_AVI_MUXER 0
-%define CONFIG_AVM2_MUXER 0
-%define CONFIG_BIT_MUXER 0
-%define CONFIG_CAF_MUXER 0
-%define CONFIG_CAVSVIDEO_MUXER 0
-%define CONFIG_CRC_MUXER 0
-%define CONFIG_DASH_MUXER 0
-%define CONFIG_DATA_MUXER 0
-%define CONFIG_DAUD_MUXER 0
-%define CONFIG_DIRAC_MUXER 0
-%define CONFIG_DNXHD_MUXER 0
-%define CONFIG_DTS_MUXER 0
-%define CONFIG_DV_MUXER 0
-%define CONFIG_EAC3_MUXER 0
-%define CONFIG_F4V_MUXER 0
-%define CONFIG_FFM_MUXER 0
-%define CONFIG_FFMETADATA_MUXER 0
-%define CONFIG_FIFO_MUXER 0
-%define CONFIG_FILMSTRIP_MUXER 0
-%define CONFIG_FLAC_MUXER 0
-%define CONFIG_FLV_MUXER 0
-%define CONFIG_FRAMECRC_MUXER 0
-%define CONFIG_FRAMEHASH_MUXER 0
-%define CONFIG_FRAMEMD5_MUXER 0
-%define CONFIG_G722_MUXER 0
-%define CONFIG_G723_1_MUXER 0
-%define CONFIG_GIF_MUXER 0
-%define CONFIG_GSM_MUXER 0
-%define CONFIG_GXF_MUXER 0
-%define CONFIG_H261_MUXER 0
-%define CONFIG_H263_MUXER 0
-%define CONFIG_H264_MUXER 0
-%define CONFIG_HASH_MUXER 0
-%define CONFIG_HDS_MUXER 0
-%define CONFIG_HEVC_MUXER 0
-%define CONFIG_HLS_MUXER 0
-%define CONFIG_ICO_MUXER 0
-%define CONFIG_ILBC_MUXER 0
-%define CONFIG_IMAGE2_MUXER 0
-%define CONFIG_IMAGE2PIPE_MUXER 0
-%define CONFIG_IPOD_MUXER 0
-%define CONFIG_IRCAM_MUXER 0
-%define CONFIG_ISMV_MUXER 0
-%define CONFIG_IVF_MUXER 0
-%define CONFIG_JACOSUB_MUXER 0
-%define CONFIG_LATM_MUXER 0
-%define CONFIG_LRC_MUXER 0
-%define CONFIG_M4V_MUXER 0
-%define CONFIG_MD5_MUXER 0
-%define CONFIG_MATROSKA_MUXER 0
-%define CONFIG_MATROSKA_AUDIO_MUXER 0
-%define CONFIG_MICRODVD_MUXER 0
-%define CONFIG_MJPEG_MUXER 0
-%define CONFIG_MLP_MUXER 0
-%define CONFIG_MMF_MUXER 0
-%define CONFIG_MOV_MUXER 0
-%define CONFIG_MP2_MUXER 0
-%define CONFIG_MP3_MUXER 0
-%define CONFIG_MP4_MUXER 0
-%define CONFIG_MPEG1SYSTEM_MUXER 0
-%define CONFIG_MPEG1VCD_MUXER 0
-%define CONFIG_MPEG1VIDEO_MUXER 0
-%define CONFIG_MPEG2DVD_MUXER 0
-%define CONFIG_MPEG2SVCD_MUXER 0
-%define CONFIG_MPEG2VIDEO_MUXER 0
-%define CONFIG_MPEG2VOB_MUXER 0
-%define CONFIG_MPEGTS_MUXER 0
-%define CONFIG_MPJPEG_MUXER 0
-%define CONFIG_MXF_MUXER 0
-%define CONFIG_MXF_D10_MUXER 0
-%define CONFIG_MXF_OPATOM_MUXER 0
-%define CONFIG_NULL_MUXER 0
-%define CONFIG_NUT_MUXER 0
-%define CONFIG_OGA_MUXER 0
-%define CONFIG_OGG_MUXER 0
-%define CONFIG_OGV_MUXER 0
-%define CONFIG_OMA_MUXER 0
-%define CONFIG_OPUS_MUXER 0
-%define CONFIG_PCM_ALAW_MUXER 0
-%define CONFIG_PCM_MULAW_MUXER 0
-%define CONFIG_PCM_F64BE_MUXER 0
-%define CONFIG_PCM_F64LE_MUXER 0
-%define CONFIG_PCM_F32BE_MUXER 0
-%define CONFIG_PCM_F32LE_MUXER 0
-%define CONFIG_PCM_S32BE_MUXER 0
-%define CONFIG_PCM_S32LE_MUXER 0
-%define CONFIG_PCM_S24BE_MUXER 0
-%define CONFIG_PCM_S24LE_MUXER 0
-%define CONFIG_PCM_S16BE_MUXER 0
-%define CONFIG_PCM_S16LE_MUXER 0
-%define CONFIG_PCM_S8_MUXER 0
-%define CONFIG_PCM_U32BE_MUXER 0
-%define CONFIG_PCM_U32LE_MUXER 0
-%define CONFIG_PCM_U24BE_MUXER 0
-%define CONFIG_PCM_U24LE_MUXER 0
-%define CONFIG_PCM_U16BE_MUXER 0
-%define CONFIG_PCM_U16LE_MUXER 0
-%define CONFIG_PCM_U8_MUXER 0
-%define CONFIG_PSP_MUXER 0
-%define CONFIG_RAWVIDEO_MUXER 0
-%define CONFIG_RM_MUXER 0
-%define CONFIG_ROQ_MUXER 0
-%define CONFIG_RSO_MUXER 0
-%define CONFIG_RTP_MUXER 0
-%define CONFIG_RTP_MPEGTS_MUXER 0
-%define CONFIG_RTSP_MUXER 0
-%define CONFIG_SAP_MUXER 0
-%define CONFIG_SEGMENT_MUXER 0
-%define CONFIG_STREAM_SEGMENT_MUXER 0
-%define CONFIG_SINGLEJPEG_MUXER 0
-%define CONFIG_SMJPEG_MUXER 0
-%define CONFIG_SMOOTHSTREAMING_MUXER 0
-%define CONFIG_SOX_MUXER 0
-%define CONFIG_SPX_MUXER 0
-%define CONFIG_SPDIF_MUXER 0
-%define CONFIG_SRT_MUXER 0
-%define CONFIG_SWF_MUXER 0
-%define CONFIG_TEE_MUXER 0
-%define CONFIG_TG2_MUXER 0
-%define CONFIG_TGP_MUXER 0
-%define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-%define CONFIG_TRUEHD_MUXER 0
-%define CONFIG_TTA_MUXER 0
-%define CONFIG_UNCODEDFRAMECRC_MUXER 0
-%define CONFIG_VC1_MUXER 0
-%define CONFIG_VC1T_MUXER 0
-%define CONFIG_VOC_MUXER 0
-%define CONFIG_W64_MUXER 0
-%define CONFIG_WAV_MUXER 0
-%define CONFIG_WEBM_MUXER 0
-%define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-%define CONFIG_WEBM_CHUNK_MUXER 0
-%define CONFIG_WEBP_MUXER 0
-%define CONFIG_WEBVTT_MUXER 0
-%define CONFIG_WTV_MUXER 0
-%define CONFIG_WV_MUXER 0
-%define CONFIG_YUV4MPEGPIPE_MUXER 0
-%define CONFIG_CHROMAPRINT_MUXER 0
-%define CONFIG_LIBNUT_MUXER 0
-%define CONFIG_ALSA_OUTDEV 0
-%define CONFIG_CACA_OUTDEV 0
-%define CONFIG_DECKLINK_OUTDEV 0
-%define CONFIG_FBDEV_OUTDEV 0
-%define CONFIG_OPENGL_OUTDEV 0
-%define CONFIG_OSS_OUTDEV 0
-%define CONFIG_PULSE_OUTDEV 0
-%define CONFIG_SDL2_OUTDEV 0
-%define CONFIG_SNDIO_OUTDEV 0
-%define CONFIG_V4L2_OUTDEV 0
-%define CONFIG_XV_OUTDEV 0
-%define CONFIG_AAC_PARSER 0
-%define CONFIG_AAC_LATM_PARSER 0
-%define CONFIG_AC3_PARSER 0
-%define CONFIG_ADX_PARSER 0
-%define CONFIG_BMP_PARSER 0
-%define CONFIG_CAVSVIDEO_PARSER 0
-%define CONFIG_COOK_PARSER 0
-%define CONFIG_DCA_PARSER 0
-%define CONFIG_DIRAC_PARSER 0
-%define CONFIG_DNXHD_PARSER 0
-%define CONFIG_DPX_PARSER 0
-%define CONFIG_DVAUDIO_PARSER 0
-%define CONFIG_DVBSUB_PARSER 0
-%define CONFIG_DVDSUB_PARSER 0
-%define CONFIG_DVD_NAV_PARSER 0
-%define CONFIG_FLAC_PARSER 1
-%define CONFIG_G729_PARSER 0
-%define CONFIG_GSM_PARSER 0
-%define CONFIG_H261_PARSER 0
-%define CONFIG_H263_PARSER 0
-%define CONFIG_H264_PARSER 0
-%define CONFIG_HEVC_PARSER 0
-%define CONFIG_MJPEG_PARSER 0
-%define CONFIG_MLP_PARSER 0
-%define CONFIG_MPEG4VIDEO_PARSER 0
-%define CONFIG_MPEGAUDIO_PARSER 0
-%define CONFIG_MPEGVIDEO_PARSER 0
-%define CONFIG_OPUS_PARSER 0
-%define CONFIG_PNG_PARSER 0
-%define CONFIG_PNM_PARSER 0
-%define CONFIG_RV30_PARSER 0
-%define CONFIG_RV40_PARSER 0
-%define CONFIG_TAK_PARSER 0
-%define CONFIG_VC1_PARSER 0
-%define CONFIG_VORBIS_PARSER 0
-%define CONFIG_VP3_PARSER 0
+%define CONFIG_FLAC_PARSER 0
%define CONFIG_VP8_PARSER 1
%define CONFIG_VP9_PARSER 1
-%define CONFIG_ASYNC_PROTOCOL 0
-%define CONFIG_BLURAY_PROTOCOL 0
-%define CONFIG_CACHE_PROTOCOL 0
-%define CONFIG_CONCAT_PROTOCOL 0
-%define CONFIG_CRYPTO_PROTOCOL 0
-%define CONFIG_DATA_PROTOCOL 0
-%define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-%define CONFIG_FFRTMPHTTP_PROTOCOL 0
-%define CONFIG_FILE_PROTOCOL 0
-%define CONFIG_FTP_PROTOCOL 0
-%define CONFIG_GOPHER_PROTOCOL 0
-%define CONFIG_HLS_PROTOCOL 0
-%define CONFIG_HTTP_PROTOCOL 0
-%define CONFIG_HTTPPROXY_PROTOCOL 0
-%define CONFIG_HTTPS_PROTOCOL 0
-%define CONFIG_ICECAST_PROTOCOL 0
-%define CONFIG_MMSH_PROTOCOL 0
-%define CONFIG_MMST_PROTOCOL 0
-%define CONFIG_MD5_PROTOCOL 0
-%define CONFIG_PIPE_PROTOCOL 0
-%define CONFIG_RTMP_PROTOCOL 0
-%define CONFIG_RTMPE_PROTOCOL 0
-%define CONFIG_RTMPS_PROTOCOL 0
-%define CONFIG_RTMPT_PROTOCOL 0
-%define CONFIG_RTMPTE_PROTOCOL 0
-%define CONFIG_RTMPTS_PROTOCOL 0
-%define CONFIG_RTP_PROTOCOL 0
-%define CONFIG_SCTP_PROTOCOL 0
-%define CONFIG_SRTP_PROTOCOL 0
-%define CONFIG_SUBFILE_PROTOCOL 0
-%define CONFIG_TEE_PROTOCOL 0
-%define CONFIG_TCP_PROTOCOL 0
-%define CONFIG_TLS_GNUTLS_PROTOCOL 0
-%define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-%define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-%define CONFIG_TLS_OPENSSL_PROTOCOL 0
-%define CONFIG_UDP_PROTOCOL 0
-%define CONFIG_UDPLITE_PROTOCOL 0
-%define CONFIG_UNIX_PROTOCOL 0
-%define CONFIG_LIBRTMP_PROTOCOL 0
-%define CONFIG_LIBRTMPE_PROTOCOL 0
-%define CONFIG_LIBRTMPS_PROTOCOL 0
-%define CONFIG_LIBRTMPT_PROTOCOL 0
-%define CONFIG_LIBRTMPTE_PROTOCOL 0
-%define CONFIG_LIBSSH_PROTOCOL 0
-%define CONFIG_LIBSMBCLIENT_PROTOCOL 0
diff --git a/media/ffvpx/config_darwin64.h b/media/ffvpx/config_darwin64.h
index e1d42ad39..72f1d6dad 100644
--- a/media/ffvpx/config_darwin64.h
+++ b/media/ffvpx/config_darwin64.h
@@ -1,12 +1,12 @@
/* Automatically generated by configure - do not modify! */
#ifndef FFMPEG_CONFIG_H
#define FFMPEG_CONFIG_H
-#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-asm --enable-yasm"
+#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl2 --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vdpau --disable-videotoolbox --enable-decoder=flac --enable-asm --enable-x86asm"
#define FFMPEG_LICENSE "LGPL version 2.1 or later"
-#define CONFIG_THIS_YEAR 2016
+#define CONFIG_THIS_YEAR 2017
#define FFMPEG_DATADIR "/usr/local/share/ffmpeg"
#define AVCONV_DATADIR "/usr/local/share/ffmpeg"
-#define CC_IDENT "Apple LLVM version 7.0.2 (clang-700.1.81)"
+#define CC_IDENT "Apple LLVM version 9.0.0 (clang-900.0.38)"
#define av_restrict restrict
#define EXTERN_PREFIX "_"
#define EXTERN_ASM _
@@ -79,8 +79,8 @@
#define HAVE_MIPSDSP 0
#define HAVE_MIPSDSPR2 0
#define HAVE_MSA 0
-#define HAVE_LOONGSON2 1
-#define HAVE_LOONGSON3 1
+#define HAVE_LOONGSON2 0
+#define HAVE_LOONGSON3 0
#define HAVE_MMI 0
#define HAVE_ARMV5TE_EXTERNAL 0
#define HAVE_ARMV6_EXTERNAL 0
@@ -178,33 +178,33 @@
#define HAVE_LOCAL_ALIGNED_16 1
#define HAVE_LOCAL_ALIGNED_32 1
#define HAVE_SIMD_ALIGN_16 1
+#define HAVE_SIMD_ALIGN_32 1
#define HAVE_ATOMICS_GCC 1
#define HAVE_ATOMICS_SUNCC 0
#define HAVE_ATOMICS_WIN32 0
#define HAVE_ATOMIC_CAS_PTR 0
-#define HAVE_ATOMIC_COMPARE_EXCHANGE 1
#define HAVE_MACHINE_RW_BARRIER 0
#define HAVE_MEMORYBARRIER 0
#define HAVE_MM_EMPTY 1
#define HAVE_RDTSC 0
#define HAVE_SARESTART 1
-#define HAVE_SEM_TIMEDWAIT 1
+#define HAVE_SEM_TIMEDWAIT 0
#define HAVE_SYNC_VAL_COMPARE_AND_SWAP 1
#define HAVE_CABS 1
#define HAVE_CEXP 1
#define HAVE_INLINE_ASM 1
#define HAVE_SYMVER 1
-#define HAVE_YASM 1
+#define HAVE_X86ASM 1
#define HAVE_BIGENDIAN 0
#define HAVE_FAST_UNALIGNED 1
-#define HAVE_INCOMPATIBLE_LIBAV_ABI 0
-#define HAVE_ALSA_ASOUNDLIB_H 0
#define HAVE_ALTIVEC_H 0
#define HAVE_ARPA_INET_H 1
#define HAVE_ASM_TYPES_H 0
#define HAVE_CDIO_PARANOIA_H 0
#define HAVE_CDIO_PARANOIA_PARANOIA_H 0
-#define HAVE_DISPATCH_DISPATCH_H 0
+#define HAVE_CUDA_H 0
+#define HAVE_D3D11_H 0
+#define HAVE_DISPATCH_DISPATCH_H 1
#define HAVE_DEV_BKTR_IOCTL_BT848_H 0
#define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
#define HAVE_DEV_IC_BT8XX_H 0
@@ -213,7 +213,7 @@
#define HAVE_DIRECT_H 0
#define HAVE_DIRENT_H 1
#define HAVE_DLFCN_H 1
-#define HAVE_D3D11_H 0
+#define HAVE_DXGIDEBUG_H 0
#define HAVE_DXVA_H 0
#define HAVE_ES2_GL_H 0
#define HAVE_GSM_H 0
@@ -222,13 +222,15 @@
#define HAVE_MACHINE_IOCTL_BT848_H 0
#define HAVE_MACHINE_IOCTL_METEOR_H 0
#define HAVE_OPENCV2_CORE_CORE_C_H 0
+#define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+#define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
#define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
#define HAVE_OPENGL_GL3_H 0
#define HAVE_POLL_H 1
-#define HAVE_SNDIO_H 0
#define HAVE_SOUNDCARD_H 0
+#define HAVE_STDATOMIC_H 1
#define HAVE_SYS_MMAN_H 1
#define HAVE_SYS_PARAM_H 1
#define HAVE_SYS_RESOURCE_H 1
@@ -275,12 +277,11 @@
#define HAVE_TRUNCF 1
#define HAVE_ACCESS 1
#define HAVE_ALIGNED_MALLOC 0
-#define HAVE_CLOCK_GETTIME 0
+#define HAVE_CLOCK_GETTIME 1
#define HAVE_CLOSESOCKET 0
#define HAVE_COMMANDLINETOARGVW 0
#define HAVE_COTASKMEMFREE 0
#define HAVE_CRYPTGENRANDOM 0
-#define HAVE_DLOPEN 1
#define HAVE_FCNTL 1
#define HAVE_FLT_LIM 1
#define HAVE_FORK 1
@@ -319,19 +320,22 @@
#define HAVE_SLEEP 0
#define HAVE_STRERROR_R 1
#define HAVE_SYSCONF 1
+#define HAVE_SYSCTL 1
#define HAVE_USLEEP 1
-#define HAVE_UTGETOSTYPEFROMSTRING 1
+#define HAVE_UTGETOSTYPEFROMSTRING 0
#define HAVE_VIRTUALALLOC 0
#define HAVE_WGLGETPROCADDRESS 0
#define HAVE_PTHREADS 1
#define HAVE_OS2THREADS 0
#define HAVE_W32THREADS 0
#define HAVE_AS_DN_DIRECTIVE 0
+#define HAVE_AS_FPU_DIRECTIVE 0
#define HAVE_AS_FUNC 0
#define HAVE_AS_OBJECT_ARCH 0
#define HAVE_ASM_MOD_Q 0
#define HAVE_ATTRIBUTE_MAY_ALIAS 1
#define HAVE_ATTRIBUTE_PACKED 1
+#define HAVE_BLOCKS_EXTENSION 1
#define HAVE_EBP_AVAILABLE 1
#define HAVE_EBX_AVAILABLE 1
#define HAVE_GNU_AS 0
@@ -348,6 +352,7 @@
#define HAVE_XFORM_ASM 0
#define HAVE_XMM_CLOBBERS 1
#define HAVE_CONDITION_VARIABLE_PTR 0
+#define HAVE_KCMVIDEOCODECTYPE_HEVC 0
#define HAVE_SOCKLEN_T 1
#define HAVE_STRUCT_ADDRINFO 1
#define HAVE_STRUCT_GROUP_SOURCE_REQ 1
@@ -364,50 +369,38 @@
#define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 0
#define HAVE_ATOMICS_NATIVE 1
#define HAVE_DOS_PATHS 0
-#define HAVE_DXVA2_LIB 0
-#define HAVE_DXVA2API_COBJ 0
#define HAVE_LIBC_MSVCRT 0
-#define HAVE_LIBDC1394_1 0
-#define HAVE_LIBDC1394_2 0
#define HAVE_MAKEINFO 1
-#define HAVE_MAKEINFO_HTML 1
+#define HAVE_MAKEINFO_HTML 0
#define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
#define HAVE_PERL 1
#define HAVE_POD2MAN 1
-#define HAVE_SDL2 0
#define HAVE_SECTION_DATA_REL_RO 0
#define HAVE_TEXI2HTML 0
#define HAVE_THREADS 1
+#define HAVE_UWP 0
#define HAVE_VAAPI_DRM 0
#define HAVE_VAAPI_X11 0
#define HAVE_VDPAU_X11 0
#define HAVE_WINRT 0
-#define HAVE_XLIB 0
-#define CONFIG_BSFS 0
-#define CONFIG_DECODERS 1
-#define CONFIG_ENCODERS 0
-#define CONFIG_HWACCELS 0
-#define CONFIG_PARSERS 1
-#define CONFIG_INDEVS 0
-#define CONFIG_OUTDEVS 0
-#define CONFIG_FILTERS 0
-#define CONFIG_DEMUXERS 0
-#define CONFIG_MUXERS 0
-#define CONFIG_PROTOCOLS 0
#define CONFIG_DOC 0
-#define CONFIG_HTMLPAGES 1
+#define CONFIG_HTMLPAGES 0
#define CONFIG_MANPAGES 1
#define CONFIG_PODPAGES 1
#define CONFIG_TXTPAGES 1
#define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
#define CONFIG_AVIO_READING_EXAMPLE 1
-#define CONFIG_DECODING_ENCODING_EXAMPLE 0
+#define CONFIG_DECODE_AUDIO_EXAMPLE 1
+#define CONFIG_DECODE_VIDEO_EXAMPLE 1
#define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+#define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+#define CONFIG_ENCODE_VIDEO_EXAMPLE 1
#define CONFIG_EXTRACT_MVS_EXAMPLE 0
#define CONFIG_FILTER_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_VIDEO_EXAMPLE 0
#define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+#define CONFIG_HW_DECODE_EXAMPLE 0
#define CONFIG_METADATA_EXAMPLE 0
#define CONFIG_MUXING_EXAMPLE 0
#define CONFIG_QSVDEC_EXAMPLE 0
@@ -416,27 +409,55 @@
#define CONFIG_SCALING_VIDEO_EXAMPLE 0
#define CONFIG_TRANSCODE_AAC_EXAMPLE 0
#define CONFIG_TRANSCODING_EXAMPLE 0
+#define CONFIG_ALSA 0
+#define CONFIG_APPKIT 1
+#define CONFIG_AVFOUNDATION 1
+#define CONFIG_BZLIB 1
+#define CONFIG_COREIMAGE 1
+#define CONFIG_ICONV 0
+#define CONFIG_JACK 0
+#define CONFIG_LIBXCB 0
+#define CONFIG_LIBXCB_SHM 0
+#define CONFIG_LIBXCB_SHAPE 0
+#define CONFIG_LIBXCB_XFIXES 0
+#define CONFIG_LZMA 0
+#define CONFIG_SCHANNEL 0
+#define CONFIG_SDL2 0
+#define CONFIG_SECURETRANSPORT 0
+#define CONFIG_SNDIO 0
+#define CONFIG_XLIB 1
+#define CONFIG_ZLIB 1
#define CONFIG_AVISYNTH 0
-#define CONFIG_BZLIB 0
-#define CONFIG_CHROMAPRINT 0
-#define CONFIG_CRYSTALHD 0
-#define CONFIG_DECKLINK 0
#define CONFIG_FREI0R 0
-#define CONFIG_GCRYPT 0
+#define CONFIG_LIBCDIO 0
+#define CONFIG_LIBRUBBERBAND 0
+#define CONFIG_LIBVIDSTAB 0
+#define CONFIG_LIBX264 0
+#define CONFIG_LIBX265 0
+#define CONFIG_LIBXAVS 0
+#define CONFIG_LIBXVID 0
+#define CONFIG_DECKLINK 0
+#define CONFIG_LIBNDI_NEWTEK 0
+#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_OPENSSL 0
#define CONFIG_GMP 0
+#define CONFIG_LIBOPENCORE_AMRNB 0
+#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_RKMPP 0
+#define CONFIG_LIBSMBCLIENT 0
+#define CONFIG_CHROMAPRINT 0
+#define CONFIG_GCRYPT 0
#define CONFIG_GNUTLS 0
-#define CONFIG_ICONV 0
#define CONFIG_JNI 0
#define CONFIG_LADSPA 0
#define CONFIG_LIBASS 0
#define CONFIG_LIBBLURAY 0
#define CONFIG_LIBBS2B 0
#define CONFIG_LIBCACA 0
-#define CONFIG_LIBCDIO 0
#define CONFIG_LIBCELT 0
#define CONFIG_LIBDC1394 0
-#define CONFIG_LIBEBUR128 0
-#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_LIBDRM 0
#define CONFIG_LIBFLITE 0
#define CONFIG_LIBFONTCONFIG 0
#define CONFIG_LIBFREETYPE 0
@@ -448,18 +469,15 @@
#define CONFIG_LIBKVAZAAR 0
#define CONFIG_LIBMODPLUG 0
#define CONFIG_LIBMP3LAME 0
-#define CONFIG_LIBNUT 0
-#define CONFIG_LIBOPENCORE_AMRNB 0
-#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBMYSOFA 0
#define CONFIG_LIBOPENCV 0
#define CONFIG_LIBOPENH264 0
#define CONFIG_LIBOPENJPEG 0
#define CONFIG_LIBOPENMPT 0
#define CONFIG_LIBOPUS 0
#define CONFIG_LIBPULSE 0
+#define CONFIG_LIBRSVG 0
#define CONFIG_LIBRTMP 0
-#define CONFIG_LIBRUBBERBAND 0
-#define CONFIG_LIBSCHROEDINGER 0
#define CONFIG_LIBSHINE 0
#define CONFIG_LIBSMBCLIENT 0
#define CONFIG_LIBSNAPPY 0
@@ -470,53 +488,37 @@
#define CONFIG_LIBTHEORA 0
#define CONFIG_LIBTWOLAME 0
#define CONFIG_LIBV4L2 0
-#define CONFIG_LIBVIDSTAB 0
-#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_LIBVMAF 0
#define CONFIG_LIBVORBIS 0
#define CONFIG_LIBVPX 0
#define CONFIG_LIBWAVPACK 0
#define CONFIG_LIBWEBP 0
-#define CONFIG_LIBX264 0
-#define CONFIG_LIBX265 0
-#define CONFIG_LIBXAVS 0
-#define CONFIG_LIBXCB 0
-#define CONFIG_LIBXCB_SHM 0
-#define CONFIG_LIBXCB_SHAPE 0
-#define CONFIG_LIBXCB_XFIXES 0
-#define CONFIG_LIBXVID 0
+#define CONFIG_LIBXML2 0
#define CONFIG_LIBZIMG 0
#define CONFIG_LIBZMQ 0
#define CONFIG_LIBZVBI 0
-#define CONFIG_LZMA 0
#define CONFIG_MEDIACODEC 0
-#define CONFIG_NETCDF 0
#define CONFIG_OPENAL 0
#define CONFIG_OPENCL 0
#define CONFIG_OPENGL 0
-#define CONFIG_OPENSSL 0
-#define CONFIG_SCHANNEL 0
-#define CONFIG_SDL 0
-#define CONFIG_SDL2 0
-#define CONFIG_SECURETRANSPORT 0
-#define CONFIG_VIDEOTOOLBOX 0
-#define CONFIG_X11GRAB 0
-#define CONFIG_XLIB 0
-#define CONFIG_ZLIB 0
-#define CONFIG_AUDIOTOOLBOX 0
+#define CONFIG_AUDIOTOOLBOX 1
+#define CONFIG_CRYSTALHD 0
#define CONFIG_CUDA 0
#define CONFIG_CUVID 0
#define CONFIG_D3D11VA 0
#define CONFIG_DXVA2 0
-#define CONFIG_LIBMFX 0
-#define CONFIG_LIBNPP 0
-#define CONFIG_MMAL 0
#define CONFIG_NVENC 0
-#define CONFIG_OMX 0
#define CONFIG_VAAPI 0
#define CONFIG_VDA 0
#define CONFIG_VDPAU 0
-#define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_VIDEOTOOLBOX 0
+#define CONFIG_V4L2_M2M 0
#define CONFIG_XVMC 0
+#define CONFIG_CUDA_SDK 0
+#define CONFIG_LIBNPP 0
+#define CONFIG_LIBMFX 0
+#define CONFIG_MMAL 0
+#define CONFIG_OMX 0
#define CONFIG_FTRAPV 0
#define CONFIG_GRAY 0
#define CONFIG_HARDCODED_TABLES 0
@@ -555,16 +557,27 @@
#define CONFIG_PIXELUTILS 0
#define CONFIG_NETWORK 0
#define CONFIG_RDFT 0
+#define CONFIG_AUTODETECT 0
#define CONFIG_FONTCONFIG 0
-#define CONFIG_MEMALIGN_HACK 0
+#define CONFIG_LINUX_PERF 0
#define CONFIG_MEMORY_POISONING 0
#define CONFIG_NEON_CLOBBER_TEST 0
+#define CONFIG_OSSFUZZ 0
#define CONFIG_PIC 1
-#define CONFIG_POD2MAN 1
-#define CONFIG_RAISE_MAJOR 0
#define CONFIG_THUMB 0
#define CONFIG_VALGRIND_BACKTRACE 0
#define CONFIG_XMM_CLOBBER_TEST 0
+#define CONFIG_BSFS 1
+#define CONFIG_DECODERS 1
+#define CONFIG_ENCODERS 0
+#define CONFIG_HWACCELS 0
+#define CONFIG_PARSERS 1
+#define CONFIG_INDEVS 0
+#define CONFIG_OUTDEVS 0
+#define CONFIG_FILTERS 0
+#define CONFIG_DEMUXERS 0
+#define CONFIG_MUXERS 0
+#define CONFIG_PROTOCOLS 0
#define CONFIG_AANDCTTABLES 0
#define CONFIG_AC3DSP 0
#define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -582,20 +595,22 @@
#define CONFIG_FMTCONVERT 0
#define CONFIG_FRAME_THREAD_ENCODER 0
#define CONFIG_G722DSP 0
-#define CONFIG_GOLOMB 1
+#define CONFIG_GOLOMB 0
#define CONFIG_GPLV3 0
#define CONFIG_H263DSP 0
#define CONFIG_H264CHROMA 0
#define CONFIG_H264DSP 0
+#define CONFIG_H264PARSE 0
#define CONFIG_H264PRED 1
#define CONFIG_H264QPEL 0
+#define CONFIG_HEVCPARSE 0
#define CONFIG_HPELDSP 0
#define CONFIG_HUFFMAN 0
#define CONFIG_HUFFYUVDSP 0
#define CONFIG_HUFFYUVENCDSP 0
#define CONFIG_IDCTDSP 0
#define CONFIG_IIRFILTER 0
-#define CONFIG_IMDCT15 0
+#define CONFIG_MDCT15 0
#define CONFIG_INTRAX8 0
#define CONFIG_ISO_MEDIA 0
#define CONFIG_IVIDSP 0
@@ -604,12 +619,14 @@
#define CONFIG_LIBX262 0
#define CONFIG_LLAUDDSP 0
#define CONFIG_LLVIDDSP 0
+#define CONFIG_LLVIDENCDSP 0
#define CONFIG_LPC 0
#define CONFIG_LZF 0
#define CONFIG_ME_CMP 0
#define CONFIG_MPEG_ER 0
#define CONFIG_MPEGAUDIO 0
#define CONFIG_MPEGAUDIODSP 0
+#define CONFIG_MPEGAUDIOHEADER 0
#define CONFIG_MPEGVIDEO 0
#define CONFIG_MPEGVIDEOENC 0
#define CONFIG_MSS34DSP 0
@@ -631,1595 +648,20 @@
#define CONFIG_TEXTUREDSP 0
#define CONFIG_TEXTUREDSPENC 0
#define CONFIG_TPELDSP 0
+#define CONFIG_VAAPI_1 0
#define CONFIG_VAAPI_ENCODE 0
#define CONFIG_VC1DSP 0
#define CONFIG_VIDEODSP 1
#define CONFIG_VP3DSP 0
#define CONFIG_VP56DSP 0
#define CONFIG_VP8DSP 1
-#define CONFIG_VT_BT2020 0
#define CONFIG_WMA_FREQS 0
#define CONFIG_WMV2DSP 0
-#define CONFIG_AAC_ADTSTOASC_BSF 0
-#define CONFIG_CHOMP_BSF 0
-#define CONFIG_DUMP_EXTRADATA_BSF 0
-#define CONFIG_DCA_CORE_BSF 0
-#define CONFIG_H264_MP4TOANNEXB_BSF 0
-#define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-#define CONFIG_IMX_DUMP_HEADER_BSF 0
-#define CONFIG_MJPEG2JPEG_BSF 0
-#define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-#define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-#define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-#define CONFIG_MOV2TEXTSUB_BSF 0
-#define CONFIG_NOISE_BSF 0
-#define CONFIG_REMOVE_EXTRADATA_BSF 0
-#define CONFIG_TEXT2MOVSUB_BSF 0
-#define CONFIG_VP9_SUPERFRAME_BSF 0
-#define CONFIG_AASC_DECODER 0
-#define CONFIG_AIC_DECODER 0
-#define CONFIG_ALIAS_PIX_DECODER 0
-#define CONFIG_AMV_DECODER 0
-#define CONFIG_ANM_DECODER 0
-#define CONFIG_ANSI_DECODER 0
-#define CONFIG_APNG_DECODER 0
-#define CONFIG_ASV1_DECODER 0
-#define CONFIG_ASV2_DECODER 0
-#define CONFIG_AURA_DECODER 0
-#define CONFIG_AURA2_DECODER 0
-#define CONFIG_AVRP_DECODER 0
-#define CONFIG_AVRN_DECODER 0
-#define CONFIG_AVS_DECODER 0
-#define CONFIG_AVUI_DECODER 0
-#define CONFIG_AYUV_DECODER 0
-#define CONFIG_BETHSOFTVID_DECODER 0
-#define CONFIG_BFI_DECODER 0
-#define CONFIG_BINK_DECODER 0
-#define CONFIG_BMP_DECODER 0
-#define CONFIG_BMV_VIDEO_DECODER 0
-#define CONFIG_BRENDER_PIX_DECODER 0
-#define CONFIG_C93_DECODER 0
-#define CONFIG_CAVS_DECODER 0
-#define CONFIG_CDGRAPHICS_DECODER 0
-#define CONFIG_CDXL_DECODER 0
-#define CONFIG_CFHD_DECODER 0
-#define CONFIG_CINEPAK_DECODER 0
-#define CONFIG_CLJR_DECODER 0
-#define CONFIG_CLLC_DECODER 0
-#define CONFIG_COMFORTNOISE_DECODER 0
-#define CONFIG_CPIA_DECODER 0
-#define CONFIG_CSCD_DECODER 0
-#define CONFIG_CYUV_DECODER 0
-#define CONFIG_DDS_DECODER 0
-#define CONFIG_DFA_DECODER 0
-#define CONFIG_DIRAC_DECODER 0
-#define CONFIG_DNXHD_DECODER 0
-#define CONFIG_DPX_DECODER 0
-#define CONFIG_DSICINVIDEO_DECODER 0
-#define CONFIG_DVAUDIO_DECODER 0
-#define CONFIG_DVVIDEO_DECODER 0
-#define CONFIG_DXA_DECODER 0
-#define CONFIG_DXTORY_DECODER 0
-#define CONFIG_DXV_DECODER 0
-#define CONFIG_EACMV_DECODER 0
-#define CONFIG_EAMAD_DECODER 0
-#define CONFIG_EATGQ_DECODER 0
-#define CONFIG_EATGV_DECODER 0
-#define CONFIG_EATQI_DECODER 0
-#define CONFIG_EIGHTBPS_DECODER 0
-#define CONFIG_EIGHTSVX_EXP_DECODER 0
-#define CONFIG_EIGHTSVX_FIB_DECODER 0
-#define CONFIG_ESCAPE124_DECODER 0
-#define CONFIG_ESCAPE130_DECODER 0
-#define CONFIG_EXR_DECODER 0
-#define CONFIG_FFV1_DECODER 0
-#define CONFIG_FFVHUFF_DECODER 0
-#define CONFIG_FIC_DECODER 0
-#define CONFIG_FLASHSV_DECODER 0
-#define CONFIG_FLASHSV2_DECODER 0
-#define CONFIG_FLIC_DECODER 0
-#define CONFIG_FLV_DECODER 0
-#define CONFIG_FOURXM_DECODER 0
-#define CONFIG_FRAPS_DECODER 0
-#define CONFIG_FRWU_DECODER 0
-#define CONFIG_G2M_DECODER 0
-#define CONFIG_GIF_DECODER 0
-#define CONFIG_H261_DECODER 0
-#define CONFIG_H263_DECODER 0
-#define CONFIG_H263I_DECODER 0
-#define CONFIG_H263P_DECODER 0
-#define CONFIG_H264_DECODER 0
-#define CONFIG_H264_CRYSTALHD_DECODER 0
-#define CONFIG_H264_MEDIACODEC_DECODER 0
-#define CONFIG_H264_MMAL_DECODER 0
-#define CONFIG_H264_QSV_DECODER 0
-#define CONFIG_H264_VDA_DECODER 0
-#define CONFIG_H264_VDPAU_DECODER 0
-#define CONFIG_HAP_DECODER 0
-#define CONFIG_HEVC_DECODER 0
-#define CONFIG_HEVC_QSV_DECODER 0
-#define CONFIG_HNM4_VIDEO_DECODER 0
-#define CONFIG_HQ_HQA_DECODER 0
-#define CONFIG_HQX_DECODER 0
-#define CONFIG_HUFFYUV_DECODER 0
-#define CONFIG_IDCIN_DECODER 0
-#define CONFIG_IFF_ILBM_DECODER 0
-#define CONFIG_INDEO2_DECODER 0
-#define CONFIG_INDEO3_DECODER 0
-#define CONFIG_INDEO4_DECODER 0
-#define CONFIG_INDEO5_DECODER 0
-#define CONFIG_INTERPLAY_VIDEO_DECODER 0
-#define CONFIG_JPEG2000_DECODER 0
-#define CONFIG_JPEGLS_DECODER 0
-#define CONFIG_JV_DECODER 0
-#define CONFIG_KGV1_DECODER 0
-#define CONFIG_KMVC_DECODER 0
-#define CONFIG_LAGARITH_DECODER 0
-#define CONFIG_LOCO_DECODER 0
-#define CONFIG_M101_DECODER 0
-#define CONFIG_MAGICYUV_DECODER 0
-#define CONFIG_MDEC_DECODER 0
-#define CONFIG_MIMIC_DECODER 0
-#define CONFIG_MJPEG_DECODER 0
-#define CONFIG_MJPEGB_DECODER 0
-#define CONFIG_MMVIDEO_DECODER 0
-#define CONFIG_MOTIONPIXELS_DECODER 0
-#define CONFIG_MPEG_XVMC_DECODER 0
-#define CONFIG_MPEG1VIDEO_DECODER 0
-#define CONFIG_MPEG2VIDEO_DECODER 0
-#define CONFIG_MPEG4_DECODER 0
-#define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG4_MMAL_DECODER 0
-#define CONFIG_MPEG4_VDPAU_DECODER 0
-#define CONFIG_MPEGVIDEO_DECODER 0
-#define CONFIG_MPEG_VDPAU_DECODER 0
-#define CONFIG_MPEG1_VDPAU_DECODER 0
-#define CONFIG_MPEG2_MMAL_DECODER 0
-#define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG2_QSV_DECODER 0
-#define CONFIG_MSA1_DECODER 0
-#define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MSMPEG4V1_DECODER 0
-#define CONFIG_MSMPEG4V2_DECODER 0
-#define CONFIG_MSMPEG4V3_DECODER 0
-#define CONFIG_MSRLE_DECODER 0
-#define CONFIG_MSS1_DECODER 0
-#define CONFIG_MSS2_DECODER 0
-#define CONFIG_MSVIDEO1_DECODER 0
-#define CONFIG_MSZH_DECODER 0
-#define CONFIG_MTS2_DECODER 0
-#define CONFIG_MVC1_DECODER 0
-#define CONFIG_MVC2_DECODER 0
-#define CONFIG_MXPEG_DECODER 0
-#define CONFIG_NUV_DECODER 0
-#define CONFIG_PAF_VIDEO_DECODER 0
-#define CONFIG_PAM_DECODER 0
-#define CONFIG_PBM_DECODER 0
-#define CONFIG_PCX_DECODER 0
-#define CONFIG_PGM_DECODER 0
-#define CONFIG_PGMYUV_DECODER 0
-#define CONFIG_PICTOR_DECODER 0
-#define CONFIG_PNG_DECODER 0
-#define CONFIG_PPM_DECODER 0
-#define CONFIG_PRORES_DECODER 0
-#define CONFIG_PRORES_LGPL_DECODER 0
-#define CONFIG_PTX_DECODER 0
-#define CONFIG_QDRAW_DECODER 0
-#define CONFIG_QPEG_DECODER 0
-#define CONFIG_QTRLE_DECODER 0
-#define CONFIG_R10K_DECODER 0
-#define CONFIG_R210_DECODER 0
-#define CONFIG_RAWVIDEO_DECODER 0
-#define CONFIG_RL2_DECODER 0
-#define CONFIG_ROQ_DECODER 0
-#define CONFIG_RPZA_DECODER 0
-#define CONFIG_RSCC_DECODER 0
-#define CONFIG_RV10_DECODER 0
-#define CONFIG_RV20_DECODER 0
-#define CONFIG_RV30_DECODER 0
-#define CONFIG_RV40_DECODER 0
-#define CONFIG_S302M_DECODER 0
-#define CONFIG_SANM_DECODER 0
-#define CONFIG_SCREENPRESSO_DECODER 0
-#define CONFIG_SDX2_DPCM_DECODER 0
-#define CONFIG_SGI_DECODER 0
-#define CONFIG_SGIRLE_DECODER 0
-#define CONFIG_SHEERVIDEO_DECODER 0
-#define CONFIG_SMACKER_DECODER 0
-#define CONFIG_SMC_DECODER 0
-#define CONFIG_SMVJPEG_DECODER 0
-#define CONFIG_SNOW_DECODER 0
-#define CONFIG_SP5X_DECODER 0
-#define CONFIG_SUNRAST_DECODER 0
-#define CONFIG_SVQ1_DECODER 0
-#define CONFIG_SVQ3_DECODER 0
-#define CONFIG_TARGA_DECODER 0
-#define CONFIG_TARGA_Y216_DECODER 0
-#define CONFIG_TDSC_DECODER 0
-#define CONFIG_THEORA_DECODER 0
-#define CONFIG_THP_DECODER 0
-#define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-#define CONFIG_TIFF_DECODER 0
-#define CONFIG_TMV_DECODER 0
-#define CONFIG_TRUEMOTION1_DECODER 0
-#define CONFIG_TRUEMOTION2_DECODER 0
-#define CONFIG_TRUEMOTION2RT_DECODER 0
-#define CONFIG_TSCC_DECODER 0
-#define CONFIG_TSCC2_DECODER 0
-#define CONFIG_TXD_DECODER 0
-#define CONFIG_ULTI_DECODER 0
-#define CONFIG_UTVIDEO_DECODER 0
-#define CONFIG_V210_DECODER 0
-#define CONFIG_V210X_DECODER 0
-#define CONFIG_V308_DECODER 0
-#define CONFIG_V408_DECODER 0
-#define CONFIG_V410_DECODER 0
-#define CONFIG_VB_DECODER 0
-#define CONFIG_VBLE_DECODER 0
-#define CONFIG_VC1_DECODER 0
-#define CONFIG_VC1_CRYSTALHD_DECODER 0
-#define CONFIG_VC1_VDPAU_DECODER 0
-#define CONFIG_VC1IMAGE_DECODER 0
-#define CONFIG_VC1_MMAL_DECODER 0
-#define CONFIG_VC1_QSV_DECODER 0
-#define CONFIG_VCR1_DECODER 0
-#define CONFIG_VMDVIDEO_DECODER 0
-#define CONFIG_VMNC_DECODER 0
-#define CONFIG_VP3_DECODER 0
-#define CONFIG_VP5_DECODER 0
-#define CONFIG_VP6_DECODER 0
-#define CONFIG_VP6A_DECODER 0
-#define CONFIG_VP6F_DECODER 0
-#define CONFIG_VP7_DECODER 0
+#define CONFIG_NULL_BSF 1
#define CONFIG_VP8_DECODER 1
#define CONFIG_VP9_DECODER 1
-#define CONFIG_VQA_DECODER 0
-#define CONFIG_WEBP_DECODER 0
-#define CONFIG_WMV1_DECODER 0
-#define CONFIG_WMV2_DECODER 0
-#define CONFIG_WMV3_DECODER 0
-#define CONFIG_WMV3_CRYSTALHD_DECODER 0
-#define CONFIG_WMV3_VDPAU_DECODER 0
-#define CONFIG_WMV3IMAGE_DECODER 0
-#define CONFIG_WNV1_DECODER 0
-#define CONFIG_XAN_WC3_DECODER 0
-#define CONFIG_XAN_WC4_DECODER 0
-#define CONFIG_XBM_DECODER 0
-#define CONFIG_XFACE_DECODER 0
-#define CONFIG_XL_DECODER 0
-#define CONFIG_XWD_DECODER 0
-#define CONFIG_Y41P_DECODER 0
-#define CONFIG_YLC_DECODER 0
-#define CONFIG_YOP_DECODER 0
-#define CONFIG_YUV4_DECODER 0
-#define CONFIG_ZERO12V_DECODER 0
-#define CONFIG_ZEROCODEC_DECODER 0
-#define CONFIG_ZLIB_DECODER 0
-#define CONFIG_ZMBV_DECODER 0
-#define CONFIG_AAC_DECODER 0
-#define CONFIG_AAC_FIXED_DECODER 0
-#define CONFIG_AAC_LATM_DECODER 0
-#define CONFIG_AC3_DECODER 0
-#define CONFIG_AC3_FIXED_DECODER 0
-#define CONFIG_ALAC_DECODER 0
-#define CONFIG_ALS_DECODER 0
-#define CONFIG_AMRNB_DECODER 0
-#define CONFIG_AMRWB_DECODER 0
-#define CONFIG_APE_DECODER 0
-#define CONFIG_ATRAC1_DECODER 0
-#define CONFIG_ATRAC3_DECODER 0
-#define CONFIG_ATRAC3P_DECODER 0
-#define CONFIG_BINKAUDIO_DCT_DECODER 0
-#define CONFIG_BINKAUDIO_RDFT_DECODER 0
-#define CONFIG_BMV_AUDIO_DECODER 0
-#define CONFIG_COOK_DECODER 0
-#define CONFIG_DCA_DECODER 0
-#define CONFIG_DSD_LSBF_DECODER 0
-#define CONFIG_DSD_MSBF_DECODER 0
-#define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-#define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-#define CONFIG_DSICINAUDIO_DECODER 0
-#define CONFIG_DSS_SP_DECODER 0
-#define CONFIG_DST_DECODER 0
-#define CONFIG_EAC3_DECODER 0
-#define CONFIG_EVRC_DECODER 0
-#define CONFIG_FFWAVESYNTH_DECODER 0
#define CONFIG_FLAC_DECODER 1
-#define CONFIG_G723_1_DECODER 0
-#define CONFIG_G729_DECODER 0
-#define CONFIG_GSM_DECODER 0
-#define CONFIG_GSM_MS_DECODER 0
-#define CONFIG_IAC_DECODER 0
-#define CONFIG_IMC_DECODER 0
-#define CONFIG_INTERPLAY_ACM_DECODER 0
-#define CONFIG_MACE3_DECODER 0
-#define CONFIG_MACE6_DECODER 0
-#define CONFIG_METASOUND_DECODER 0
-#define CONFIG_MLP_DECODER 0
-#define CONFIG_MP1_DECODER 0
-#define CONFIG_MP1FLOAT_DECODER 0
-#define CONFIG_MP2_DECODER 0
-#define CONFIG_MP2FLOAT_DECODER 0
-#define CONFIG_MP3_DECODER 0
-#define CONFIG_MP3FLOAT_DECODER 0
-#define CONFIG_MP3ADU_DECODER 0
-#define CONFIG_MP3ADUFLOAT_DECODER 0
-#define CONFIG_MP3ON4_DECODER 0
-#define CONFIG_MP3ON4FLOAT_DECODER 0
-#define CONFIG_MPC7_DECODER 0
-#define CONFIG_MPC8_DECODER 0
-#define CONFIG_NELLYMOSER_DECODER 0
-#define CONFIG_ON2AVC_DECODER 0
-#define CONFIG_OPUS_DECODER 0
-#define CONFIG_PAF_AUDIO_DECODER 0
-#define CONFIG_QCELP_DECODER 0
-#define CONFIG_QDM2_DECODER 0
-#define CONFIG_RA_144_DECODER 0
-#define CONFIG_RA_288_DECODER 0
-#define CONFIG_RALF_DECODER 0
-#define CONFIG_SHORTEN_DECODER 0
-#define CONFIG_SIPR_DECODER 0
-#define CONFIG_SMACKAUD_DECODER 0
-#define CONFIG_SONIC_DECODER 0
-#define CONFIG_TAK_DECODER 0
-#define CONFIG_TRUEHD_DECODER 0
-#define CONFIG_TRUESPEECH_DECODER 0
-#define CONFIG_TTA_DECODER 0
-#define CONFIG_TWINVQ_DECODER 0
-#define CONFIG_VMDAUDIO_DECODER 0
-#define CONFIG_VORBIS_DECODER 0
-#define CONFIG_WAVPACK_DECODER 0
-#define CONFIG_WMALOSSLESS_DECODER 0
-#define CONFIG_WMAPRO_DECODER 0
-#define CONFIG_WMAV1_DECODER 0
-#define CONFIG_WMAV2_DECODER 0
-#define CONFIG_WMAVOICE_DECODER 0
-#define CONFIG_WS_SND1_DECODER 0
-#define CONFIG_XMA1_DECODER 0
-#define CONFIG_XMA2_DECODER 0
-#define CONFIG_PCM_ALAW_DECODER 0
-#define CONFIG_PCM_BLURAY_DECODER 0
-#define CONFIG_PCM_DVD_DECODER 0
-#define CONFIG_PCM_F32BE_DECODER 0
-#define CONFIG_PCM_F32LE_DECODER 0
-#define CONFIG_PCM_F64BE_DECODER 0
-#define CONFIG_PCM_F64LE_DECODER 0
-#define CONFIG_PCM_LXF_DECODER 0
-#define CONFIG_PCM_MULAW_DECODER 0
-#define CONFIG_PCM_S8_DECODER 0
-#define CONFIG_PCM_S8_PLANAR_DECODER 0
-#define CONFIG_PCM_S16BE_DECODER 0
-#define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-#define CONFIG_PCM_S16LE_DECODER 0
-#define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S24BE_DECODER 0
-#define CONFIG_PCM_S24DAUD_DECODER 0
-#define CONFIG_PCM_S24LE_DECODER 0
-#define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S32BE_DECODER 0
-#define CONFIG_PCM_S32LE_DECODER 0
-#define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S64BE_DECODER 0
-#define CONFIG_PCM_S64LE_DECODER 0
-#define CONFIG_PCM_U8_DECODER 0
-#define CONFIG_PCM_U16BE_DECODER 0
-#define CONFIG_PCM_U16LE_DECODER 0
-#define CONFIG_PCM_U24BE_DECODER 0
-#define CONFIG_PCM_U24LE_DECODER 0
-#define CONFIG_PCM_U32BE_DECODER 0
-#define CONFIG_PCM_U32LE_DECODER 0
-#define CONFIG_PCM_ZORK_DECODER 0
-#define CONFIG_INTERPLAY_DPCM_DECODER 0
-#define CONFIG_ROQ_DPCM_DECODER 0
-#define CONFIG_SOL_DPCM_DECODER 0
-#define CONFIG_XAN_DPCM_DECODER 0
-#define CONFIG_ADPCM_4XM_DECODER 0
-#define CONFIG_ADPCM_ADX_DECODER 0
-#define CONFIG_ADPCM_AFC_DECODER 0
-#define CONFIG_ADPCM_AICA_DECODER 0
-#define CONFIG_ADPCM_CT_DECODER 0
-#define CONFIG_ADPCM_DTK_DECODER 0
-#define CONFIG_ADPCM_EA_DECODER 0
-#define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-#define CONFIG_ADPCM_EA_R1_DECODER 0
-#define CONFIG_ADPCM_EA_R2_DECODER 0
-#define CONFIG_ADPCM_EA_R3_DECODER 0
-#define CONFIG_ADPCM_EA_XAS_DECODER 0
-#define CONFIG_ADPCM_G722_DECODER 0
-#define CONFIG_ADPCM_G726_DECODER 0
-#define CONFIG_ADPCM_G726LE_DECODER 0
-#define CONFIG_ADPCM_IMA_AMV_DECODER 0
-#define CONFIG_ADPCM_IMA_APC_DECODER 0
-#define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-#define CONFIG_ADPCM_IMA_DK3_DECODER 0
-#define CONFIG_ADPCM_IMA_DK4_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-#define CONFIG_ADPCM_IMA_ISS_DECODER 0
-#define CONFIG_ADPCM_IMA_OKI_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_DECODER 0
-#define CONFIG_ADPCM_IMA_RAD_DECODER 0
-#define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-#define CONFIG_ADPCM_IMA_WAV_DECODER 0
-#define CONFIG_ADPCM_IMA_WS_DECODER 0
-#define CONFIG_ADPCM_MS_DECODER 0
-#define CONFIG_ADPCM_MTAF_DECODER 0
-#define CONFIG_ADPCM_PSX_DECODER 0
-#define CONFIG_ADPCM_SBPRO_2_DECODER 0
-#define CONFIG_ADPCM_SBPRO_3_DECODER 0
-#define CONFIG_ADPCM_SBPRO_4_DECODER 0
-#define CONFIG_ADPCM_SWF_DECODER 0
-#define CONFIG_ADPCM_THP_DECODER 0
-#define CONFIG_ADPCM_THP_LE_DECODER 0
-#define CONFIG_ADPCM_VIMA_DECODER 0
-#define CONFIG_ADPCM_XA_DECODER 0
-#define CONFIG_ADPCM_YAMAHA_DECODER 0
-#define CONFIG_SSA_DECODER 0
-#define CONFIG_ASS_DECODER 0
-#define CONFIG_CCAPTION_DECODER 0
-#define CONFIG_DVBSUB_DECODER 0
-#define CONFIG_DVDSUB_DECODER 0
-#define CONFIG_JACOSUB_DECODER 0
-#define CONFIG_MICRODVD_DECODER 0
-#define CONFIG_MOVTEXT_DECODER 0
-#define CONFIG_MPL2_DECODER 0
-#define CONFIG_PGSSUB_DECODER 0
-#define CONFIG_PJS_DECODER 0
-#define CONFIG_REALTEXT_DECODER 0
-#define CONFIG_SAMI_DECODER 0
-#define CONFIG_SRT_DECODER 0
-#define CONFIG_STL_DECODER 0
-#define CONFIG_SUBRIP_DECODER 0
-#define CONFIG_SUBVIEWER_DECODER 0
-#define CONFIG_SUBVIEWER1_DECODER 0
-#define CONFIG_TEXT_DECODER 0
-#define CONFIG_VPLAYER_DECODER 0
-#define CONFIG_WEBVTT_DECODER 0
-#define CONFIG_XSUB_DECODER 0
-#define CONFIG_AAC_AT_DECODER 0
-#define CONFIG_AC3_AT_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-#define CONFIG_ALAC_AT_DECODER 0
-#define CONFIG_AMR_NB_AT_DECODER 0
-#define CONFIG_EAC3_AT_DECODER 0
-#define CONFIG_GSM_MS_AT_DECODER 0
-#define CONFIG_ILBC_AT_DECODER 0
-#define CONFIG_MP1_AT_DECODER 0
-#define CONFIG_MP2_AT_DECODER 0
-#define CONFIG_MP3_AT_DECODER 0
-#define CONFIG_PCM_ALAW_AT_DECODER 0
-#define CONFIG_PCM_MULAW_AT_DECODER 0
-#define CONFIG_QDMC_AT_DECODER 0
-#define CONFIG_QDM2_AT_DECODER 0
-#define CONFIG_LIBCELT_DECODER 0
-#define CONFIG_LIBFDK_AAC_DECODER 0
-#define CONFIG_LIBGSM_DECODER 0
-#define CONFIG_LIBGSM_MS_DECODER 0
-#define CONFIG_LIBILBC_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-#define CONFIG_LIBOPENJPEG_DECODER 0
-#define CONFIG_LIBOPUS_DECODER 0
-#define CONFIG_LIBSCHROEDINGER_DECODER 0
-#define CONFIG_LIBSPEEX_DECODER 0
-#define CONFIG_LIBVORBIS_DECODER 0
-#define CONFIG_LIBVPX_VP8_DECODER 0
-#define CONFIG_LIBVPX_VP9_DECODER 0
-#define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-#define CONFIG_BINTEXT_DECODER 0
-#define CONFIG_XBIN_DECODER 0
-#define CONFIG_IDF_DECODER 0
-#define CONFIG_LIBOPENH264_DECODER 0
-#define CONFIG_H263_CUVID_DECODER 0
-#define CONFIG_H264_CUVID_DECODER 0
-#define CONFIG_HEVC_CUVID_DECODER 0
-#define CONFIG_HEVC_MEDIACODEC_DECODER 0
-#define CONFIG_MJPEG_CUVID_DECODER 0
-#define CONFIG_MPEG1_CUVID_DECODER 0
-#define CONFIG_MPEG2_CUVID_DECODER 0
-#define CONFIG_MPEG4_CUVID_DECODER 0
-#define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-#define CONFIG_VC1_CUVID_DECODER 0
-#define CONFIG_VP8_CUVID_DECODER 0
-#define CONFIG_VP8_MEDIACODEC_DECODER 0
-#define CONFIG_VP9_CUVID_DECODER 0
-#define CONFIG_VP9_MEDIACODEC_DECODER 0
-#define CONFIG_AA_DEMUXER 0
-#define CONFIG_AAC_DEMUXER 0
-#define CONFIG_AC3_DEMUXER 0
-#define CONFIG_ACM_DEMUXER 0
-#define CONFIG_ACT_DEMUXER 0
-#define CONFIG_ADF_DEMUXER 0
-#define CONFIG_ADP_DEMUXER 0
-#define CONFIG_ADS_DEMUXER 0
-#define CONFIG_ADX_DEMUXER 0
-#define CONFIG_AEA_DEMUXER 0
-#define CONFIG_AFC_DEMUXER 0
-#define CONFIG_AIFF_DEMUXER 0
-#define CONFIG_AIX_DEMUXER 0
-#define CONFIG_AMR_DEMUXER 0
-#define CONFIG_ANM_DEMUXER 0
-#define CONFIG_APC_DEMUXER 0
-#define CONFIG_APE_DEMUXER 0
-#define CONFIG_APNG_DEMUXER 0
-#define CONFIG_AQTITLE_DEMUXER 0
-#define CONFIG_ASF_DEMUXER 0
-#define CONFIG_ASF_O_DEMUXER 0
-#define CONFIG_ASS_DEMUXER 0
-#define CONFIG_AST_DEMUXER 0
-#define CONFIG_AU_DEMUXER 0
-#define CONFIG_AVI_DEMUXER 0
-#define CONFIG_AVISYNTH_DEMUXER 0
-#define CONFIG_AVR_DEMUXER 0
-#define CONFIG_AVS_DEMUXER 0
-#define CONFIG_BETHSOFTVID_DEMUXER 0
-#define CONFIG_BFI_DEMUXER 0
-#define CONFIG_BINTEXT_DEMUXER 0
-#define CONFIG_BINK_DEMUXER 0
-#define CONFIG_BIT_DEMUXER 0
-#define CONFIG_BMV_DEMUXER 0
-#define CONFIG_BFSTM_DEMUXER 0
-#define CONFIG_BRSTM_DEMUXER 0
-#define CONFIG_BOA_DEMUXER 0
-#define CONFIG_C93_DEMUXER 0
-#define CONFIG_CAF_DEMUXER 0
-#define CONFIG_CAVSVIDEO_DEMUXER 0
-#define CONFIG_CDG_DEMUXER 0
-#define CONFIG_CDXL_DEMUXER 0
-#define CONFIG_CINE_DEMUXER 0
-#define CONFIG_CONCAT_DEMUXER 0
-#define CONFIG_DATA_DEMUXER 0
-#define CONFIG_DAUD_DEMUXER 0
-#define CONFIG_DCSTR_DEMUXER 0
-#define CONFIG_DFA_DEMUXER 0
-#define CONFIG_DIRAC_DEMUXER 0
-#define CONFIG_DNXHD_DEMUXER 0
-#define CONFIG_DSF_DEMUXER 0
-#define CONFIG_DSICIN_DEMUXER 0
-#define CONFIG_DSS_DEMUXER 0
-#define CONFIG_DTS_DEMUXER 0
-#define CONFIG_DTSHD_DEMUXER 0
-#define CONFIG_DV_DEMUXER 0
-#define CONFIG_DVBSUB_DEMUXER 0
-#define CONFIG_DVBTXT_DEMUXER 0
-#define CONFIG_DXA_DEMUXER 0
-#define CONFIG_EA_DEMUXER 0
-#define CONFIG_EA_CDATA_DEMUXER 0
-#define CONFIG_EAC3_DEMUXER 0
-#define CONFIG_EPAF_DEMUXER 0
-#define CONFIG_FFM_DEMUXER 0
-#define CONFIG_FFMETADATA_DEMUXER 0
-#define CONFIG_FILMSTRIP_DEMUXER 0
-#define CONFIG_FLAC_DEMUXER 0
-#define CONFIG_FLIC_DEMUXER 0
-#define CONFIG_FLV_DEMUXER 0
-#define CONFIG_LIVE_FLV_DEMUXER 0
-#define CONFIG_FOURXM_DEMUXER 0
-#define CONFIG_FRM_DEMUXER 0
-#define CONFIG_FSB_DEMUXER 0
-#define CONFIG_G722_DEMUXER 0
-#define CONFIG_G723_1_DEMUXER 0
-#define CONFIG_G729_DEMUXER 0
-#define CONFIG_GENH_DEMUXER 0
-#define CONFIG_GIF_DEMUXER 0
-#define CONFIG_GSM_DEMUXER 0
-#define CONFIG_GXF_DEMUXER 0
-#define CONFIG_H261_DEMUXER 0
-#define CONFIG_H263_DEMUXER 0
-#define CONFIG_H264_DEMUXER 0
-#define CONFIG_HEVC_DEMUXER 0
-#define CONFIG_HLS_DEMUXER 0
-#define CONFIG_HNM_DEMUXER 0
-#define CONFIG_ICO_DEMUXER 0
-#define CONFIG_IDCIN_DEMUXER 0
-#define CONFIG_IDF_DEMUXER 0
-#define CONFIG_IFF_DEMUXER 0
-#define CONFIG_ILBC_DEMUXER 0
-#define CONFIG_IMAGE2_DEMUXER 0
-#define CONFIG_IMAGE2PIPE_DEMUXER 0
-#define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-#define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-#define CONFIG_INGENIENT_DEMUXER 0
-#define CONFIG_IPMOVIE_DEMUXER 0
-#define CONFIG_IRCAM_DEMUXER 0
-#define CONFIG_ISS_DEMUXER 0
-#define CONFIG_IV8_DEMUXER 0
-#define CONFIG_IVF_DEMUXER 0
-#define CONFIG_IVR_DEMUXER 0
-#define CONFIG_JACOSUB_DEMUXER 0
-#define CONFIG_JV_DEMUXER 0
-#define CONFIG_LMLM4_DEMUXER 0
-#define CONFIG_LOAS_DEMUXER 0
-#define CONFIG_LRC_DEMUXER 0
-#define CONFIG_LVF_DEMUXER 0
-#define CONFIG_LXF_DEMUXER 0
-#define CONFIG_M4V_DEMUXER 0
-#define CONFIG_MATROSKA_DEMUXER 0
-#define CONFIG_MGSTS_DEMUXER 0
-#define CONFIG_MICRODVD_DEMUXER 0
-#define CONFIG_MJPEG_DEMUXER 0
-#define CONFIG_MLP_DEMUXER 0
-#define CONFIG_MLV_DEMUXER 0
-#define CONFIG_MM_DEMUXER 0
-#define CONFIG_MMF_DEMUXER 0
-#define CONFIG_MOV_DEMUXER 0
-#define CONFIG_MP3_DEMUXER 0
-#define CONFIG_MPC_DEMUXER 0
-#define CONFIG_MPC8_DEMUXER 0
-#define CONFIG_MPEGPS_DEMUXER 0
-#define CONFIG_MPEGTS_DEMUXER 0
-#define CONFIG_MPEGTSRAW_DEMUXER 0
-#define CONFIG_MPEGVIDEO_DEMUXER 0
-#define CONFIG_MPJPEG_DEMUXER 0
-#define CONFIG_MPL2_DEMUXER 0
-#define CONFIG_MPSUB_DEMUXER 0
-#define CONFIG_MSF_DEMUXER 0
-#define CONFIG_MSNWC_TCP_DEMUXER 0
-#define CONFIG_MTAF_DEMUXER 0
-#define CONFIG_MTV_DEMUXER 0
-#define CONFIG_MUSX_DEMUXER 0
-#define CONFIG_MV_DEMUXER 0
-#define CONFIG_MVI_DEMUXER 0
-#define CONFIG_MXF_DEMUXER 0
-#define CONFIG_MXG_DEMUXER 0
-#define CONFIG_NC_DEMUXER 0
-#define CONFIG_NISTSPHERE_DEMUXER 0
-#define CONFIG_NSV_DEMUXER 0
-#define CONFIG_NUT_DEMUXER 0
-#define CONFIG_NUV_DEMUXER 0
-#define CONFIG_OGG_DEMUXER 0
-#define CONFIG_OMA_DEMUXER 0
-#define CONFIG_PAF_DEMUXER 0
-#define CONFIG_PCM_ALAW_DEMUXER 0
-#define CONFIG_PCM_MULAW_DEMUXER 0
-#define CONFIG_PCM_F64BE_DEMUXER 0
-#define CONFIG_PCM_F64LE_DEMUXER 0
-#define CONFIG_PCM_F32BE_DEMUXER 0
-#define CONFIG_PCM_F32LE_DEMUXER 0
-#define CONFIG_PCM_S32BE_DEMUXER 0
-#define CONFIG_PCM_S32LE_DEMUXER 0
-#define CONFIG_PCM_S24BE_DEMUXER 0
-#define CONFIG_PCM_S24LE_DEMUXER 0
-#define CONFIG_PCM_S16BE_DEMUXER 0
-#define CONFIG_PCM_S16LE_DEMUXER 0
-#define CONFIG_PCM_S8_DEMUXER 0
-#define CONFIG_PCM_U32BE_DEMUXER 0
-#define CONFIG_PCM_U32LE_DEMUXER 0
-#define CONFIG_PCM_U24BE_DEMUXER 0
-#define CONFIG_PCM_U24LE_DEMUXER 0
-#define CONFIG_PCM_U16BE_DEMUXER 0
-#define CONFIG_PCM_U16LE_DEMUXER 0
-#define CONFIG_PCM_U8_DEMUXER 0
-#define CONFIG_PJS_DEMUXER 0
-#define CONFIG_PMP_DEMUXER 0
-#define CONFIG_PVA_DEMUXER 0
-#define CONFIG_PVF_DEMUXER 0
-#define CONFIG_QCP_DEMUXER 0
-#define CONFIG_R3D_DEMUXER 0
-#define CONFIG_RAWVIDEO_DEMUXER 0
-#define CONFIG_REALTEXT_DEMUXER 0
-#define CONFIG_REDSPARK_DEMUXER 0
-#define CONFIG_RL2_DEMUXER 0
-#define CONFIG_RM_DEMUXER 0
-#define CONFIG_ROQ_DEMUXER 0
-#define CONFIG_RPL_DEMUXER 0
-#define CONFIG_RSD_DEMUXER 0
-#define CONFIG_RSO_DEMUXER 0
-#define CONFIG_RTP_DEMUXER 0
-#define CONFIG_RTSP_DEMUXER 0
-#define CONFIG_SAMI_DEMUXER 0
-#define CONFIG_SAP_DEMUXER 0
-#define CONFIG_SBG_DEMUXER 0
-#define CONFIG_SDP_DEMUXER 0
-#define CONFIG_SDR2_DEMUXER 0
-#define CONFIG_SEGAFILM_DEMUXER 0
-#define CONFIG_SHORTEN_DEMUXER 0
-#define CONFIG_SIFF_DEMUXER 0
-#define CONFIG_SLN_DEMUXER 0
-#define CONFIG_SMACKER_DEMUXER 0
-#define CONFIG_SMJPEG_DEMUXER 0
-#define CONFIG_SMUSH_DEMUXER 0
-#define CONFIG_SOL_DEMUXER 0
-#define CONFIG_SOX_DEMUXER 0
-#define CONFIG_SPDIF_DEMUXER 0
-#define CONFIG_SRT_DEMUXER 0
-#define CONFIG_STR_DEMUXER 0
-#define CONFIG_STL_DEMUXER 0
-#define CONFIG_SUBVIEWER1_DEMUXER 0
-#define CONFIG_SUBVIEWER_DEMUXER 0
-#define CONFIG_SUP_DEMUXER 0
-#define CONFIG_SVAG_DEMUXER 0
-#define CONFIG_SWF_DEMUXER 0
-#define CONFIG_TAK_DEMUXER 0
-#define CONFIG_TEDCAPTIONS_DEMUXER 0
-#define CONFIG_THP_DEMUXER 0
-#define CONFIG_THREEDOSTR_DEMUXER 0
-#define CONFIG_TIERTEXSEQ_DEMUXER 0
-#define CONFIG_TMV_DEMUXER 0
-#define CONFIG_TRUEHD_DEMUXER 0
-#define CONFIG_TTA_DEMUXER 0
-#define CONFIG_TXD_DEMUXER 0
-#define CONFIG_TTY_DEMUXER 0
-#define CONFIG_V210_DEMUXER 0
-#define CONFIG_V210X_DEMUXER 0
-#define CONFIG_VAG_DEMUXER 0
-#define CONFIG_VC1_DEMUXER 0
-#define CONFIG_VC1T_DEMUXER 0
-#define CONFIG_VIVO_DEMUXER 0
-#define CONFIG_VMD_DEMUXER 0
-#define CONFIG_VOBSUB_DEMUXER 0
-#define CONFIG_VOC_DEMUXER 0
-#define CONFIG_VPK_DEMUXER 0
-#define CONFIG_VPLAYER_DEMUXER 0
-#define CONFIG_VQF_DEMUXER 0
-#define CONFIG_W64_DEMUXER 0
-#define CONFIG_WAV_DEMUXER 0
-#define CONFIG_WC3_DEMUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-#define CONFIG_WEBVTT_DEMUXER 0
-#define CONFIG_WSAUD_DEMUXER 0
-#define CONFIG_WSD_DEMUXER 0
-#define CONFIG_WSVQA_DEMUXER 0
-#define CONFIG_WTV_DEMUXER 0
-#define CONFIG_WVE_DEMUXER 0
-#define CONFIG_WV_DEMUXER 0
-#define CONFIG_XA_DEMUXER 0
-#define CONFIG_XBIN_DEMUXER 0
-#define CONFIG_XMV_DEMUXER 0
-#define CONFIG_XVAG_DEMUXER 0
-#define CONFIG_XWMA_DEMUXER 0
-#define CONFIG_YOP_DEMUXER 0
-#define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-#define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-#define CONFIG_LIBGME_DEMUXER 0
-#define CONFIG_LIBMODPLUG_DEMUXER 0
-#define CONFIG_LIBNUT_DEMUXER 0
-#define CONFIG_LIBOPENMPT_DEMUXER 0
-#define CONFIG_A64MULTI_ENCODER 0
-#define CONFIG_A64MULTI5_ENCODER 0
-#define CONFIG_ALIAS_PIX_ENCODER 0
-#define CONFIG_AMV_ENCODER 0
-#define CONFIG_APNG_ENCODER 0
-#define CONFIG_ASV1_ENCODER 0
-#define CONFIG_ASV2_ENCODER 0
-#define CONFIG_AVRP_ENCODER 0
-#define CONFIG_AVUI_ENCODER 0
-#define CONFIG_AYUV_ENCODER 0
-#define CONFIG_BMP_ENCODER 0
-#define CONFIG_CINEPAK_ENCODER 0
-#define CONFIG_CLJR_ENCODER 0
-#define CONFIG_COMFORTNOISE_ENCODER 0
-#define CONFIG_DNXHD_ENCODER 0
-#define CONFIG_DPX_ENCODER 0
-#define CONFIG_DVVIDEO_ENCODER 0
-#define CONFIG_FFV1_ENCODER 0
-#define CONFIG_FFVHUFF_ENCODER 0
-#define CONFIG_FLASHSV_ENCODER 0
-#define CONFIG_FLASHSV2_ENCODER 0
-#define CONFIG_FLV_ENCODER 0
-#define CONFIG_GIF_ENCODER 0
-#define CONFIG_H261_ENCODER 0
-#define CONFIG_H263_ENCODER 0
-#define CONFIG_H263P_ENCODER 0
-#define CONFIG_HAP_ENCODER 0
-#define CONFIG_HUFFYUV_ENCODER 0
-#define CONFIG_JPEG2000_ENCODER 0
-#define CONFIG_JPEGLS_ENCODER 0
-#define CONFIG_LJPEG_ENCODER 0
-#define CONFIG_MJPEG_ENCODER 0
-#define CONFIG_MPEG1VIDEO_ENCODER 0
-#define CONFIG_MPEG2VIDEO_ENCODER 0
-#define CONFIG_MPEG4_ENCODER 0
-#define CONFIG_MSMPEG4V2_ENCODER 0
-#define CONFIG_MSMPEG4V3_ENCODER 0
-#define CONFIG_MSVIDEO1_ENCODER 0
-#define CONFIG_PAM_ENCODER 0
-#define CONFIG_PBM_ENCODER 0
-#define CONFIG_PCX_ENCODER 0
-#define CONFIG_PGM_ENCODER 0
-#define CONFIG_PGMYUV_ENCODER 0
-#define CONFIG_PNG_ENCODER 0
-#define CONFIG_PPM_ENCODER 0
-#define CONFIG_PRORES_ENCODER 0
-#define CONFIG_PRORES_AW_ENCODER 0
-#define CONFIG_PRORES_KS_ENCODER 0
-#define CONFIG_QTRLE_ENCODER 0
-#define CONFIG_R10K_ENCODER 0
-#define CONFIG_R210_ENCODER 0
-#define CONFIG_RAWVIDEO_ENCODER 0
-#define CONFIG_ROQ_ENCODER 0
-#define CONFIG_RV10_ENCODER 0
-#define CONFIG_RV20_ENCODER 0
-#define CONFIG_S302M_ENCODER 0
-#define CONFIG_SGI_ENCODER 0
-#define CONFIG_SNOW_ENCODER 0
-#define CONFIG_SUNRAST_ENCODER 0
-#define CONFIG_SVQ1_ENCODER 0
-#define CONFIG_TARGA_ENCODER 0
-#define CONFIG_TIFF_ENCODER 0
-#define CONFIG_UTVIDEO_ENCODER 0
-#define CONFIG_V210_ENCODER 0
-#define CONFIG_V308_ENCODER 0
-#define CONFIG_V408_ENCODER 0
-#define CONFIG_V410_ENCODER 0
-#define CONFIG_VC2_ENCODER 0
-#define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-#define CONFIG_WMV1_ENCODER 0
-#define CONFIG_WMV2_ENCODER 0
-#define CONFIG_XBM_ENCODER 0
-#define CONFIG_XFACE_ENCODER 0
-#define CONFIG_XWD_ENCODER 0
-#define CONFIG_Y41P_ENCODER 0
-#define CONFIG_YUV4_ENCODER 0
-#define CONFIG_ZLIB_ENCODER 0
-#define CONFIG_ZMBV_ENCODER 0
-#define CONFIG_AAC_ENCODER 0
-#define CONFIG_AC3_ENCODER 0
-#define CONFIG_AC3_FIXED_ENCODER 0
-#define CONFIG_ALAC_ENCODER 0
-#define CONFIG_DCA_ENCODER 0
-#define CONFIG_EAC3_ENCODER 0
-#define CONFIG_FLAC_ENCODER 0
-#define CONFIG_G723_1_ENCODER 0
-#define CONFIG_MLP_ENCODER 0
-#define CONFIG_MP2_ENCODER 0
-#define CONFIG_MP2FIXED_ENCODER 0
-#define CONFIG_NELLYMOSER_ENCODER 0
-#define CONFIG_RA_144_ENCODER 0
-#define CONFIG_SONIC_ENCODER 0
-#define CONFIG_SONIC_LS_ENCODER 0
-#define CONFIG_TRUEHD_ENCODER 0
-#define CONFIG_TTA_ENCODER 0
-#define CONFIG_VORBIS_ENCODER 0
-#define CONFIG_WAVPACK_ENCODER 0
-#define CONFIG_WMAV1_ENCODER 0
-#define CONFIG_WMAV2_ENCODER 0
-#define CONFIG_PCM_ALAW_ENCODER 0
-#define CONFIG_PCM_F32BE_ENCODER 0
-#define CONFIG_PCM_F32LE_ENCODER 0
-#define CONFIG_PCM_F64BE_ENCODER 0
-#define CONFIG_PCM_F64LE_ENCODER 0
-#define CONFIG_PCM_MULAW_ENCODER 0
-#define CONFIG_PCM_S8_ENCODER 0
-#define CONFIG_PCM_S8_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16BE_ENCODER 0
-#define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16LE_ENCODER 0
-#define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S24BE_ENCODER 0
-#define CONFIG_PCM_S24DAUD_ENCODER 0
-#define CONFIG_PCM_S24LE_ENCODER 0
-#define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S32BE_ENCODER 0
-#define CONFIG_PCM_S32LE_ENCODER 0
-#define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S64BE_ENCODER 0
-#define CONFIG_PCM_S64LE_ENCODER 0
-#define CONFIG_PCM_U8_ENCODER 0
-#define CONFIG_PCM_U16BE_ENCODER 0
-#define CONFIG_PCM_U16LE_ENCODER 0
-#define CONFIG_PCM_U24BE_ENCODER 0
-#define CONFIG_PCM_U24LE_ENCODER 0
-#define CONFIG_PCM_U32BE_ENCODER 0
-#define CONFIG_PCM_U32LE_ENCODER 0
-#define CONFIG_ROQ_DPCM_ENCODER 0
-#define CONFIG_ADPCM_ADX_ENCODER 0
-#define CONFIG_ADPCM_G722_ENCODER 0
-#define CONFIG_ADPCM_G726_ENCODER 0
-#define CONFIG_ADPCM_IMA_QT_ENCODER 0
-#define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-#define CONFIG_ADPCM_MS_ENCODER 0
-#define CONFIG_ADPCM_SWF_ENCODER 0
-#define CONFIG_ADPCM_YAMAHA_ENCODER 0
-#define CONFIG_SSA_ENCODER 0
-#define CONFIG_ASS_ENCODER 0
-#define CONFIG_DVBSUB_ENCODER 0
-#define CONFIG_DVDSUB_ENCODER 0
-#define CONFIG_MOVTEXT_ENCODER 0
-#define CONFIG_SRT_ENCODER 0
-#define CONFIG_SUBRIP_ENCODER 0
-#define CONFIG_TEXT_ENCODER 0
-#define CONFIG_WEBVTT_ENCODER 0
-#define CONFIG_XSUB_ENCODER 0
-#define CONFIG_AAC_AT_ENCODER 0
-#define CONFIG_ALAC_AT_ENCODER 0
-#define CONFIG_ILBC_AT_ENCODER 0
-#define CONFIG_PCM_ALAW_AT_ENCODER 0
-#define CONFIG_PCM_MULAW_AT_ENCODER 0
-#define CONFIG_LIBFDK_AAC_ENCODER 0
-#define CONFIG_LIBGSM_ENCODER 0
-#define CONFIG_LIBGSM_MS_ENCODER 0
-#define CONFIG_LIBILBC_ENCODER 0
-#define CONFIG_LIBMP3LAME_ENCODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-#define CONFIG_LIBOPENJPEG_ENCODER 0
-#define CONFIG_LIBOPUS_ENCODER 0
-#define CONFIG_LIBSCHROEDINGER_ENCODER 0
-#define CONFIG_LIBSHINE_ENCODER 0
-#define CONFIG_LIBSPEEX_ENCODER 0
-#define CONFIG_LIBTHEORA_ENCODER 0
-#define CONFIG_LIBTWOLAME_ENCODER 0
-#define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-#define CONFIG_LIBVORBIS_ENCODER 0
-#define CONFIG_LIBVPX_VP8_ENCODER 0
-#define CONFIG_LIBVPX_VP9_ENCODER 0
-#define CONFIG_LIBWAVPACK_ENCODER 0
-#define CONFIG_LIBWEBP_ANIM_ENCODER 0
-#define CONFIG_LIBWEBP_ENCODER 0
-#define CONFIG_LIBX262_ENCODER 0
-#define CONFIG_LIBX264_ENCODER 0
-#define CONFIG_LIBX264RGB_ENCODER 0
-#define CONFIG_LIBX265_ENCODER 0
-#define CONFIG_LIBXAVS_ENCODER 0
-#define CONFIG_LIBXVID_ENCODER 0
-#define CONFIG_LIBOPENH264_ENCODER 0
-#define CONFIG_H264_NVENC_ENCODER 0
-#define CONFIG_H264_OMX_ENCODER 0
-#define CONFIG_H264_QSV_ENCODER 0
-#define CONFIG_H264_VAAPI_ENCODER 0
-#define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-#define CONFIG_NVENC_ENCODER 0
-#define CONFIG_NVENC_H264_ENCODER 0
-#define CONFIG_NVENC_HEVC_ENCODER 0
-#define CONFIG_HEVC_NVENC_ENCODER 0
-#define CONFIG_HEVC_QSV_ENCODER 0
-#define CONFIG_HEVC_VAAPI_ENCODER 0
-#define CONFIG_LIBKVAZAAR_ENCODER 0
-#define CONFIG_MJPEG_VAAPI_ENCODER 0
-#define CONFIG_MPEG2_QSV_ENCODER 0
-#define CONFIG_ABENCH_FILTER 0
-#define CONFIG_ACOMPRESSOR_FILTER 0
-#define CONFIG_ACROSSFADE_FILTER 0
-#define CONFIG_ACRUSHER_FILTER 0
-#define CONFIG_ADELAY_FILTER 0
-#define CONFIG_AECHO_FILTER 0
-#define CONFIG_AEMPHASIS_FILTER 0
-#define CONFIG_AEVAL_FILTER 0
-#define CONFIG_AFADE_FILTER 0
-#define CONFIG_AFFTFILT_FILTER 0
-#define CONFIG_AFORMAT_FILTER 0
-#define CONFIG_AGATE_FILTER 0
-#define CONFIG_AINTERLEAVE_FILTER 0
-#define CONFIG_ALIMITER_FILTER 0
-#define CONFIG_ALLPASS_FILTER 0
-#define CONFIG_ALOOP_FILTER 0
-#define CONFIG_AMERGE_FILTER 0
-#define CONFIG_AMETADATA_FILTER 0
-#define CONFIG_AMIX_FILTER 0
-#define CONFIG_ANEQUALIZER_FILTER 0
-#define CONFIG_ANULL_FILTER 0
-#define CONFIG_APAD_FILTER 0
-#define CONFIG_APERMS_FILTER 0
-#define CONFIG_APHASER_FILTER 0
-#define CONFIG_APULSATOR_FILTER 0
-#define CONFIG_AREALTIME_FILTER 0
-#define CONFIG_ARESAMPLE_FILTER 0
-#define CONFIG_AREVERSE_FILTER 0
-#define CONFIG_ASELECT_FILTER 0
-#define CONFIG_ASENDCMD_FILTER 0
-#define CONFIG_ASETNSAMPLES_FILTER 0
-#define CONFIG_ASETPTS_FILTER 0
-#define CONFIG_ASETRATE_FILTER 0
-#define CONFIG_ASETTB_FILTER 0
-#define CONFIG_ASHOWINFO_FILTER 0
-#define CONFIG_ASIDEDATA_FILTER 0
-#define CONFIG_ASPLIT_FILTER 0
-#define CONFIG_ASTATS_FILTER 0
-#define CONFIG_ASTREAMSELECT_FILTER 0
-#define CONFIG_ASYNCTS_FILTER 0
-#define CONFIG_ATEMPO_FILTER 0
-#define CONFIG_ATRIM_FILTER 0
-#define CONFIG_AZMQ_FILTER 0
-#define CONFIG_BANDPASS_FILTER 0
-#define CONFIG_BANDREJECT_FILTER 0
-#define CONFIG_BASS_FILTER 0
-#define CONFIG_BIQUAD_FILTER 0
-#define CONFIG_BS2B_FILTER 0
-#define CONFIG_CHANNELMAP_FILTER 0
-#define CONFIG_CHANNELSPLIT_FILTER 0
-#define CONFIG_CHORUS_FILTER 0
-#define CONFIG_COMPAND_FILTER 0
-#define CONFIG_COMPENSATIONDELAY_FILTER 0
-#define CONFIG_CRYSTALIZER_FILTER 0
-#define CONFIG_DCSHIFT_FILTER 0
-#define CONFIG_DYNAUDNORM_FILTER 0
-#define CONFIG_EARWAX_FILTER 0
-#define CONFIG_EBUR128_FILTER 0
-#define CONFIG_EQUALIZER_FILTER 0
-#define CONFIG_EXTRASTEREO_FILTER 0
-#define CONFIG_FIREQUALIZER_FILTER 0
-#define CONFIG_FLANGER_FILTER 0
-#define CONFIG_HDCD_FILTER 0
-#define CONFIG_HIGHPASS_FILTER 0
-#define CONFIG_JOIN_FILTER 0
-#define CONFIG_LADSPA_FILTER 0
-#define CONFIG_LOUDNORM_FILTER 0
-#define CONFIG_LOWPASS_FILTER 0
-#define CONFIG_PAN_FILTER 0
-#define CONFIG_REPLAYGAIN_FILTER 0
-#define CONFIG_RESAMPLE_FILTER 0
-#define CONFIG_RUBBERBAND_FILTER 0
-#define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-#define CONFIG_SIDECHAINGATE_FILTER 0
-#define CONFIG_SILENCEDETECT_FILTER 0
-#define CONFIG_SILENCEREMOVE_FILTER 0
-#define CONFIG_SOFALIZER_FILTER 0
-#define CONFIG_STEREOTOOLS_FILTER 0
-#define CONFIG_STEREOWIDEN_FILTER 0
-#define CONFIG_TREBLE_FILTER 0
-#define CONFIG_TREMOLO_FILTER 0
-#define CONFIG_VIBRATO_FILTER 0
-#define CONFIG_VOLUME_FILTER 0
-#define CONFIG_VOLUMEDETECT_FILTER 0
-#define CONFIG_AEVALSRC_FILTER 0
-#define CONFIG_ANOISESRC_FILTER 0
-#define CONFIG_ANULLSRC_FILTER 0
-#define CONFIG_FLITE_FILTER 0
-#define CONFIG_SINE_FILTER 0
-#define CONFIG_ANULLSINK_FILTER 0
-#define CONFIG_ALPHAEXTRACT_FILTER 0
-#define CONFIG_ALPHAMERGE_FILTER 0
-#define CONFIG_ASS_FILTER 0
-#define CONFIG_ATADENOISE_FILTER 0
-#define CONFIG_AVGBLUR_FILTER 0
-#define CONFIG_BBOX_FILTER 0
-#define CONFIG_BENCH_FILTER 0
-#define CONFIG_BITPLANENOISE_FILTER 0
-#define CONFIG_BLACKDETECT_FILTER 0
-#define CONFIG_BLACKFRAME_FILTER 0
-#define CONFIG_BLEND_FILTER 0
-#define CONFIG_BOXBLUR_FILTER 0
-#define CONFIG_BWDIF_FILTER 0
-#define CONFIG_CHROMAKEY_FILTER 0
-#define CONFIG_CIESCOPE_FILTER 0
-#define CONFIG_CODECVIEW_FILTER 0
-#define CONFIG_COLORBALANCE_FILTER 0
-#define CONFIG_COLORCHANNELMIXER_FILTER 0
-#define CONFIG_COLORKEY_FILTER 0
-#define CONFIG_COLORLEVELS_FILTER 0
-#define CONFIG_COLORMATRIX_FILTER 0
-#define CONFIG_COLORSPACE_FILTER 0
-#define CONFIG_CONVOLUTION_FILTER 0
-#define CONFIG_COPY_FILTER 0
-#define CONFIG_COREIMAGE_FILTER 0
-#define CONFIG_COVER_RECT_FILTER 0
-#define CONFIG_CROP_FILTER 0
-#define CONFIG_CROPDETECT_FILTER 0
-#define CONFIG_CURVES_FILTER 0
-#define CONFIG_DATASCOPE_FILTER 0
-#define CONFIG_DCTDNOIZ_FILTER 0
-#define CONFIG_DEBAND_FILTER 0
-#define CONFIG_DECIMATE_FILTER 0
-#define CONFIG_DEFLATE_FILTER 0
-#define CONFIG_DEJUDDER_FILTER 0
-#define CONFIG_DELOGO_FILTER 0
-#define CONFIG_DESHAKE_FILTER 0
-#define CONFIG_DETELECINE_FILTER 0
-#define CONFIG_DILATION_FILTER 0
-#define CONFIG_DISPLACE_FILTER 0
-#define CONFIG_DRAWBOX_FILTER 0
-#define CONFIG_DRAWGRAPH_FILTER 0
-#define CONFIG_DRAWGRID_FILTER 0
-#define CONFIG_DRAWTEXT_FILTER 0
-#define CONFIG_EDGEDETECT_FILTER 0
-#define CONFIG_ELBG_FILTER 0
-#define CONFIG_EQ_FILTER 0
-#define CONFIG_EROSION_FILTER 0
-#define CONFIG_EXTRACTPLANES_FILTER 0
-#define CONFIG_FADE_FILTER 0
-#define CONFIG_FFTFILT_FILTER 0
-#define CONFIG_FIELD_FILTER 0
-#define CONFIG_FIELDHINT_FILTER 0
-#define CONFIG_FIELDMATCH_FILTER 0
-#define CONFIG_FIELDORDER_FILTER 0
-#define CONFIG_FIND_RECT_FILTER 0
-#define CONFIG_FORMAT_FILTER 0
-#define CONFIG_FPS_FILTER 0
-#define CONFIG_FRAMEPACK_FILTER 0
-#define CONFIG_FRAMERATE_FILTER 0
-#define CONFIG_FRAMESTEP_FILTER 0
-#define CONFIG_FREI0R_FILTER 0
-#define CONFIG_FSPP_FILTER 0
-#define CONFIG_GBLUR_FILTER 0
-#define CONFIG_GEQ_FILTER 0
-#define CONFIG_GRADFUN_FILTER 0
-#define CONFIG_HALDCLUT_FILTER 0
-#define CONFIG_HFLIP_FILTER 0
-#define CONFIG_HISTEQ_FILTER 0
-#define CONFIG_HISTOGRAM_FILTER 0
-#define CONFIG_HQDN3D_FILTER 0
-#define CONFIG_HQX_FILTER 0
-#define CONFIG_HSTACK_FILTER 0
-#define CONFIG_HUE_FILTER 0
-#define CONFIG_HWDOWNLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_CUDA_FILTER 0
-#define CONFIG_HYSTERESIS_FILTER 0
-#define CONFIG_IDET_FILTER 0
-#define CONFIG_IL_FILTER 0
-#define CONFIG_INFLATE_FILTER 0
-#define CONFIG_INTERLACE_FILTER 0
-#define CONFIG_INTERLEAVE_FILTER 0
-#define CONFIG_KERNDEINT_FILTER 0
-#define CONFIG_LENSCORRECTION_FILTER 0
-#define CONFIG_LOOP_FILTER 0
-#define CONFIG_LUT_FILTER 0
-#define CONFIG_LUT2_FILTER 0
-#define CONFIG_LUT3D_FILTER 0
-#define CONFIG_LUTRGB_FILTER 0
-#define CONFIG_LUTYUV_FILTER 0
-#define CONFIG_MASKEDCLAMP_FILTER 0
-#define CONFIG_MASKEDMERGE_FILTER 0
-#define CONFIG_MCDEINT_FILTER 0
-#define CONFIG_MERGEPLANES_FILTER 0
-#define CONFIG_MESTIMATE_FILTER 0
-#define CONFIG_METADATA_FILTER 0
-#define CONFIG_MINTERPOLATE_FILTER 0
-#define CONFIG_MPDECIMATE_FILTER 0
-#define CONFIG_NEGATE_FILTER 0
-#define CONFIG_NLMEANS_FILTER 0
-#define CONFIG_NNEDI_FILTER 0
-#define CONFIG_NOFORMAT_FILTER 0
-#define CONFIG_NOISE_FILTER 0
-#define CONFIG_NULL_FILTER 0
-#define CONFIG_OCR_FILTER 0
-#define CONFIG_OCV_FILTER 0
-#define CONFIG_OVERLAY_FILTER 0
-#define CONFIG_OWDENOISE_FILTER 0
-#define CONFIG_PAD_FILTER 0
-#define CONFIG_PALETTEGEN_FILTER 0
-#define CONFIG_PALETTEUSE_FILTER 0
-#define CONFIG_PERMS_FILTER 0
-#define CONFIG_PERSPECTIVE_FILTER 0
-#define CONFIG_PHASE_FILTER 0
-#define CONFIG_PIXDESCTEST_FILTER 0
-#define CONFIG_PP_FILTER 0
-#define CONFIG_PP7_FILTER 0
-#define CONFIG_PREWITT_FILTER 0
-#define CONFIG_PSNR_FILTER 0
-#define CONFIG_PULLUP_FILTER 0
-#define CONFIG_QP_FILTER 0
-#define CONFIG_RANDOM_FILTER 0
-#define CONFIG_READVITC_FILTER 0
-#define CONFIG_REALTIME_FILTER 0
-#define CONFIG_REMAP_FILTER 0
-#define CONFIG_REMOVEGRAIN_FILTER 0
-#define CONFIG_REMOVELOGO_FILTER 0
-#define CONFIG_REPEATFIELDS_FILTER 0
-#define CONFIG_REVERSE_FILTER 0
-#define CONFIG_ROTATE_FILTER 0
-#define CONFIG_SAB_FILTER 0
-#define CONFIG_SCALE_FILTER 0
-#define CONFIG_SCALE_NPP_FILTER 0
-#define CONFIG_SCALE_VAAPI_FILTER 0
-#define CONFIG_SCALE2REF_FILTER 0
-#define CONFIG_SELECT_FILTER 0
-#define CONFIG_SELECTIVECOLOR_FILTER 0
-#define CONFIG_SENDCMD_FILTER 0
-#define CONFIG_SEPARATEFIELDS_FILTER 0
-#define CONFIG_SETDAR_FILTER 0
-#define CONFIG_SETFIELD_FILTER 0
-#define CONFIG_SETPTS_FILTER 0
-#define CONFIG_SETSAR_FILTER 0
-#define CONFIG_SETTB_FILTER 0
-#define CONFIG_SHOWINFO_FILTER 0
-#define CONFIG_SHOWPALETTE_FILTER 0
-#define CONFIG_SHUFFLEFRAMES_FILTER 0
-#define CONFIG_SHUFFLEPLANES_FILTER 0
-#define CONFIG_SIDEDATA_FILTER 0
-#define CONFIG_SIGNALSTATS_FILTER 0
-#define CONFIG_SMARTBLUR_FILTER 0
-#define CONFIG_SOBEL_FILTER 0
-#define CONFIG_SPLIT_FILTER 0
-#define CONFIG_SPP_FILTER 0
-#define CONFIG_SSIM_FILTER 0
-#define CONFIG_STEREO3D_FILTER 0
-#define CONFIG_STREAMSELECT_FILTER 0
-#define CONFIG_SUBTITLES_FILTER 0
-#define CONFIG_SUPER2XSAI_FILTER 0
-#define CONFIG_SWAPRECT_FILTER 0
-#define CONFIG_SWAPUV_FILTER 0
-#define CONFIG_TBLEND_FILTER 0
-#define CONFIG_TELECINE_FILTER 0
-#define CONFIG_THUMBNAIL_FILTER 0
-#define CONFIG_TILE_FILTER 0
-#define CONFIG_TINTERLACE_FILTER 0
-#define CONFIG_TRANSPOSE_FILTER 0
-#define CONFIG_TRIM_FILTER 0
-#define CONFIG_UNSHARP_FILTER 0
-#define CONFIG_USPP_FILTER 0
-#define CONFIG_VAGUEDENOISER_FILTER 0
-#define CONFIG_VECTORSCOPE_FILTER 0
-#define CONFIG_VFLIP_FILTER 0
-#define CONFIG_VIDSTABDETECT_FILTER 0
-#define CONFIG_VIDSTABTRANSFORM_FILTER 0
-#define CONFIG_VIGNETTE_FILTER 0
-#define CONFIG_VSTACK_FILTER 0
-#define CONFIG_W3FDIF_FILTER 0
-#define CONFIG_WAVEFORM_FILTER 0
-#define CONFIG_WEAVE_FILTER 0
-#define CONFIG_XBR_FILTER 0
-#define CONFIG_YADIF_FILTER 0
-#define CONFIG_ZMQ_FILTER 0
-#define CONFIG_ZOOMPAN_FILTER 0
-#define CONFIG_ZSCALE_FILTER 0
-#define CONFIG_ALLRGB_FILTER 0
-#define CONFIG_ALLYUV_FILTER 0
-#define CONFIG_CELLAUTO_FILTER 0
-#define CONFIG_COLOR_FILTER 0
-#define CONFIG_COREIMAGESRC_FILTER 0
-#define CONFIG_FREI0R_SRC_FILTER 0
-#define CONFIG_HALDCLUTSRC_FILTER 0
-#define CONFIG_LIFE_FILTER 0
-#define CONFIG_MANDELBROT_FILTER 0
-#define CONFIG_MPTESTSRC_FILTER 0
-#define CONFIG_NULLSRC_FILTER 0
-#define CONFIG_RGBTESTSRC_FILTER 0
-#define CONFIG_SMPTEBARS_FILTER 0
-#define CONFIG_SMPTEHDBARS_FILTER 0
-#define CONFIG_TESTSRC_FILTER 0
-#define CONFIG_TESTSRC2_FILTER 0
-#define CONFIG_YUVTESTSRC_FILTER 0
-#define CONFIG_NULLSINK_FILTER 0
-#define CONFIG_ADRAWGRAPH_FILTER 0
-#define CONFIG_AHISTOGRAM_FILTER 0
-#define CONFIG_APHASEMETER_FILTER 0
-#define CONFIG_AVECTORSCOPE_FILTER 0
-#define CONFIG_CONCAT_FILTER 0
-#define CONFIG_SHOWCQT_FILTER 0
-#define CONFIG_SHOWFREQS_FILTER 0
-#define CONFIG_SHOWSPECTRUM_FILTER 0
-#define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-#define CONFIG_SHOWVOLUME_FILTER 0
-#define CONFIG_SHOWWAVES_FILTER 0
-#define CONFIG_SHOWWAVESPIC_FILTER 0
-#define CONFIG_SPECTRUMSYNTH_FILTER 0
-#define CONFIG_AMOVIE_FILTER 0
-#define CONFIG_MOVIE_FILTER 0
-#define CONFIG_H263_CUVID_HWACCEL 0
-#define CONFIG_H263_VAAPI_HWACCEL 0
-#define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_H264_CUVID_HWACCEL 0
-#define CONFIG_H264_D3D11VA_HWACCEL 0
-#define CONFIG_H264_DXVA2_HWACCEL 0
-#define CONFIG_H264_MEDIACODEC_HWACCEL 0
-#define CONFIG_H264_MMAL_HWACCEL 0
-#define CONFIG_H264_QSV_HWACCEL 0
-#define CONFIG_H264_VAAPI_HWACCEL 0
-#define CONFIG_H264_VDA_HWACCEL 0
-#define CONFIG_H264_VDA_OLD_HWACCEL 0
-#define CONFIG_H264_VDPAU_HWACCEL 0
-#define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_HEVC_CUVID_HWACCEL 0
-#define CONFIG_HEVC_D3D11VA_HWACCEL 0
-#define CONFIG_HEVC_DXVA2_HWACCEL 0
-#define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-#define CONFIG_HEVC_QSV_HWACCEL 0
-#define CONFIG_HEVC_VAAPI_HWACCEL 0
-#define CONFIG_HEVC_VDPAU_HWACCEL 0
-#define CONFIG_MJPEG_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_XVMC_HWACCEL 0
-#define CONFIG_MPEG1_VDPAU_HWACCEL 0
-#define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG2_CUVID_HWACCEL 0
-#define CONFIG_MPEG2_XVMC_HWACCEL 0
-#define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-#define CONFIG_MPEG2_DXVA2_HWACCEL 0
-#define CONFIG_MPEG2_MMAL_HWACCEL 0
-#define CONFIG_MPEG2_QSV_HWACCEL 0
-#define CONFIG_MPEG2_VAAPI_HWACCEL 0
-#define CONFIG_MPEG2_VDPAU_HWACCEL 0
-#define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG4_CUVID_HWACCEL 0
-#define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-#define CONFIG_MPEG4_MMAL_HWACCEL 0
-#define CONFIG_MPEG4_VAAPI_HWACCEL 0
-#define CONFIG_MPEG4_VDPAU_HWACCEL 0
-#define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_VC1_CUVID_HWACCEL 0
-#define CONFIG_VC1_D3D11VA_HWACCEL 0
-#define CONFIG_VC1_DXVA2_HWACCEL 0
-#define CONFIG_VC1_VAAPI_HWACCEL 0
-#define CONFIG_VC1_VDPAU_HWACCEL 0
-#define CONFIG_VC1_MMAL_HWACCEL 0
-#define CONFIG_VC1_QSV_HWACCEL 0
-#define CONFIG_VP8_CUVID_HWACCEL 0
-#define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_CUVID_HWACCEL 0
-#define CONFIG_VP9_D3D11VA_HWACCEL 0
-#define CONFIG_VP9_DXVA2_HWACCEL 0
-#define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_D3D11VA_HWACCEL 0
-#define CONFIG_WMV3_DXVA2_HWACCEL 0
-#define CONFIG_WMV3_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_VDPAU_HWACCEL 0
-#define CONFIG_ALSA_INDEV 0
-#define CONFIG_AVFOUNDATION_INDEV 0
-#define CONFIG_BKTR_INDEV 0
-#define CONFIG_DECKLINK_INDEV 0
-#define CONFIG_DSHOW_INDEV 0
-#define CONFIG_DV1394_INDEV 0
-#define CONFIG_FBDEV_INDEV 0
-#define CONFIG_GDIGRAB_INDEV 0
-#define CONFIG_IEC61883_INDEV 0
-#define CONFIG_JACK_INDEV 0
-#define CONFIG_LAVFI_INDEV 0
-#define CONFIG_OPENAL_INDEV 0
-#define CONFIG_OSS_INDEV 0
-#define CONFIG_PULSE_INDEV 0
-#define CONFIG_QTKIT_INDEV 0
-#define CONFIG_SNDIO_INDEV 0
-#define CONFIG_V4L2_INDEV 0
-#define CONFIG_VFWCAP_INDEV 0
-#define CONFIG_X11GRAB_INDEV 0
-#define CONFIG_X11GRAB_XCB_INDEV 0
-#define CONFIG_LIBCDIO_INDEV 0
-#define CONFIG_LIBDC1394_INDEV 0
-#define CONFIG_A64_MUXER 0
-#define CONFIG_AC3_MUXER 0
-#define CONFIG_ADTS_MUXER 0
-#define CONFIG_ADX_MUXER 0
-#define CONFIG_AIFF_MUXER 0
-#define CONFIG_AMR_MUXER 0
-#define CONFIG_APNG_MUXER 0
-#define CONFIG_ASF_MUXER 0
-#define CONFIG_ASS_MUXER 0
-#define CONFIG_AST_MUXER 0
-#define CONFIG_ASF_STREAM_MUXER 0
-#define CONFIG_AU_MUXER 0
-#define CONFIG_AVI_MUXER 0
-#define CONFIG_AVM2_MUXER 0
-#define CONFIG_BIT_MUXER 0
-#define CONFIG_CAF_MUXER 0
-#define CONFIG_CAVSVIDEO_MUXER 0
-#define CONFIG_CRC_MUXER 0
-#define CONFIG_DASH_MUXER 0
-#define CONFIG_DATA_MUXER 0
-#define CONFIG_DAUD_MUXER 0
-#define CONFIG_DIRAC_MUXER 0
-#define CONFIG_DNXHD_MUXER 0
-#define CONFIG_DTS_MUXER 0
-#define CONFIG_DV_MUXER 0
-#define CONFIG_EAC3_MUXER 0
-#define CONFIG_F4V_MUXER 0
-#define CONFIG_FFM_MUXER 0
-#define CONFIG_FFMETADATA_MUXER 0
-#define CONFIG_FIFO_MUXER 0
-#define CONFIG_FILMSTRIP_MUXER 0
-#define CONFIG_FLAC_MUXER 0
-#define CONFIG_FLV_MUXER 0
-#define CONFIG_FRAMECRC_MUXER 0
-#define CONFIG_FRAMEHASH_MUXER 0
-#define CONFIG_FRAMEMD5_MUXER 0
-#define CONFIG_G722_MUXER 0
-#define CONFIG_G723_1_MUXER 0
-#define CONFIG_GIF_MUXER 0
-#define CONFIG_GSM_MUXER 0
-#define CONFIG_GXF_MUXER 0
-#define CONFIG_H261_MUXER 0
-#define CONFIG_H263_MUXER 0
-#define CONFIG_H264_MUXER 0
-#define CONFIG_HASH_MUXER 0
-#define CONFIG_HDS_MUXER 0
-#define CONFIG_HEVC_MUXER 0
-#define CONFIG_HLS_MUXER 0
-#define CONFIG_ICO_MUXER 0
-#define CONFIG_ILBC_MUXER 0
-#define CONFIG_IMAGE2_MUXER 0
-#define CONFIG_IMAGE2PIPE_MUXER 0
-#define CONFIG_IPOD_MUXER 0
-#define CONFIG_IRCAM_MUXER 0
-#define CONFIG_ISMV_MUXER 0
-#define CONFIG_IVF_MUXER 0
-#define CONFIG_JACOSUB_MUXER 0
-#define CONFIG_LATM_MUXER 0
-#define CONFIG_LRC_MUXER 0
-#define CONFIG_M4V_MUXER 0
-#define CONFIG_MD5_MUXER 0
-#define CONFIG_MATROSKA_MUXER 0
-#define CONFIG_MATROSKA_AUDIO_MUXER 0
-#define CONFIG_MICRODVD_MUXER 0
-#define CONFIG_MJPEG_MUXER 0
-#define CONFIG_MLP_MUXER 0
-#define CONFIG_MMF_MUXER 0
-#define CONFIG_MOV_MUXER 0
-#define CONFIG_MP2_MUXER 0
-#define CONFIG_MP3_MUXER 0
-#define CONFIG_MP4_MUXER 0
-#define CONFIG_MPEG1SYSTEM_MUXER 0
-#define CONFIG_MPEG1VCD_MUXER 0
-#define CONFIG_MPEG1VIDEO_MUXER 0
-#define CONFIG_MPEG2DVD_MUXER 0
-#define CONFIG_MPEG2SVCD_MUXER 0
-#define CONFIG_MPEG2VIDEO_MUXER 0
-#define CONFIG_MPEG2VOB_MUXER 0
-#define CONFIG_MPEGTS_MUXER 0
-#define CONFIG_MPJPEG_MUXER 0
-#define CONFIG_MXF_MUXER 0
-#define CONFIG_MXF_D10_MUXER 0
-#define CONFIG_MXF_OPATOM_MUXER 0
-#define CONFIG_NULL_MUXER 0
-#define CONFIG_NUT_MUXER 0
-#define CONFIG_OGA_MUXER 0
-#define CONFIG_OGG_MUXER 0
-#define CONFIG_OGV_MUXER 0
-#define CONFIG_OMA_MUXER 0
-#define CONFIG_OPUS_MUXER 0
-#define CONFIG_PCM_ALAW_MUXER 0
-#define CONFIG_PCM_MULAW_MUXER 0
-#define CONFIG_PCM_F64BE_MUXER 0
-#define CONFIG_PCM_F64LE_MUXER 0
-#define CONFIG_PCM_F32BE_MUXER 0
-#define CONFIG_PCM_F32LE_MUXER 0
-#define CONFIG_PCM_S32BE_MUXER 0
-#define CONFIG_PCM_S32LE_MUXER 0
-#define CONFIG_PCM_S24BE_MUXER 0
-#define CONFIG_PCM_S24LE_MUXER 0
-#define CONFIG_PCM_S16BE_MUXER 0
-#define CONFIG_PCM_S16LE_MUXER 0
-#define CONFIG_PCM_S8_MUXER 0
-#define CONFIG_PCM_U32BE_MUXER 0
-#define CONFIG_PCM_U32LE_MUXER 0
-#define CONFIG_PCM_U24BE_MUXER 0
-#define CONFIG_PCM_U24LE_MUXER 0
-#define CONFIG_PCM_U16BE_MUXER 0
-#define CONFIG_PCM_U16LE_MUXER 0
-#define CONFIG_PCM_U8_MUXER 0
-#define CONFIG_PSP_MUXER 0
-#define CONFIG_RAWVIDEO_MUXER 0
-#define CONFIG_RM_MUXER 0
-#define CONFIG_ROQ_MUXER 0
-#define CONFIG_RSO_MUXER 0
-#define CONFIG_RTP_MUXER 0
-#define CONFIG_RTP_MPEGTS_MUXER 0
-#define CONFIG_RTSP_MUXER 0
-#define CONFIG_SAP_MUXER 0
-#define CONFIG_SEGMENT_MUXER 0
-#define CONFIG_STREAM_SEGMENT_MUXER 0
-#define CONFIG_SINGLEJPEG_MUXER 0
-#define CONFIG_SMJPEG_MUXER 0
-#define CONFIG_SMOOTHSTREAMING_MUXER 0
-#define CONFIG_SOX_MUXER 0
-#define CONFIG_SPX_MUXER 0
-#define CONFIG_SPDIF_MUXER 0
-#define CONFIG_SRT_MUXER 0
-#define CONFIG_SWF_MUXER 0
-#define CONFIG_TEE_MUXER 0
-#define CONFIG_TG2_MUXER 0
-#define CONFIG_TGP_MUXER 0
-#define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-#define CONFIG_TRUEHD_MUXER 0
-#define CONFIG_TTA_MUXER 0
-#define CONFIG_UNCODEDFRAMECRC_MUXER 0
-#define CONFIG_VC1_MUXER 0
-#define CONFIG_VC1T_MUXER 0
-#define CONFIG_VOC_MUXER 0
-#define CONFIG_W64_MUXER 0
-#define CONFIG_WAV_MUXER 0
-#define CONFIG_WEBM_MUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-#define CONFIG_WEBM_CHUNK_MUXER 0
-#define CONFIG_WEBP_MUXER 0
-#define CONFIG_WEBVTT_MUXER 0
-#define CONFIG_WTV_MUXER 0
-#define CONFIG_WV_MUXER 0
-#define CONFIG_YUV4MPEGPIPE_MUXER 0
-#define CONFIG_CHROMAPRINT_MUXER 0
-#define CONFIG_LIBNUT_MUXER 0
-#define CONFIG_ALSA_OUTDEV 0
-#define CONFIG_CACA_OUTDEV 0
-#define CONFIG_DECKLINK_OUTDEV 0
-#define CONFIG_FBDEV_OUTDEV 0
-#define CONFIG_OPENGL_OUTDEV 0
-#define CONFIG_OSS_OUTDEV 0
-#define CONFIG_PULSE_OUTDEV 0
-#define CONFIG_SDL2_OUTDEV 0
-#define CONFIG_SNDIO_OUTDEV 0
-#define CONFIG_V4L2_OUTDEV 0
-#define CONFIG_XV_OUTDEV 0
-#define CONFIG_AAC_PARSER 0
-#define CONFIG_AAC_LATM_PARSER 0
-#define CONFIG_AC3_PARSER 0
-#define CONFIG_ADX_PARSER 0
-#define CONFIG_BMP_PARSER 0
-#define CONFIG_CAVSVIDEO_PARSER 0
-#define CONFIG_COOK_PARSER 0
-#define CONFIG_DCA_PARSER 0
-#define CONFIG_DIRAC_PARSER 0
-#define CONFIG_DNXHD_PARSER 0
-#define CONFIG_DPX_PARSER 0
-#define CONFIG_DVAUDIO_PARSER 0
-#define CONFIG_DVBSUB_PARSER 0
-#define CONFIG_DVDSUB_PARSER 0
-#define CONFIG_DVD_NAV_PARSER 0
-#define CONFIG_FLAC_PARSER 1
-#define CONFIG_G729_PARSER 0
-#define CONFIG_GSM_PARSER 0
-#define CONFIG_H261_PARSER 0
-#define CONFIG_H263_PARSER 0
-#define CONFIG_H264_PARSER 0
-#define CONFIG_HEVC_PARSER 0
-#define CONFIG_MJPEG_PARSER 0
-#define CONFIG_MLP_PARSER 0
-#define CONFIG_MPEG4VIDEO_PARSER 0
-#define CONFIG_MPEGAUDIO_PARSER 0
-#define CONFIG_MPEGVIDEO_PARSER 0
-#define CONFIG_OPUS_PARSER 0
-#define CONFIG_PNG_PARSER 0
-#define CONFIG_PNM_PARSER 0
-#define CONFIG_RV30_PARSER 0
-#define CONFIG_RV40_PARSER 0
-#define CONFIG_TAK_PARSER 0
-#define CONFIG_VC1_PARSER 0
-#define CONFIG_VORBIS_PARSER 0
-#define CONFIG_VP3_PARSER 0
+#define CONFIG_FLAC_PARSER 0
#define CONFIG_VP8_PARSER 1
#define CONFIG_VP9_PARSER 1
-#define CONFIG_ASYNC_PROTOCOL 0
-#define CONFIG_BLURAY_PROTOCOL 0
-#define CONFIG_CACHE_PROTOCOL 0
-#define CONFIG_CONCAT_PROTOCOL 0
-#define CONFIG_CRYPTO_PROTOCOL 0
-#define CONFIG_DATA_PROTOCOL 0
-#define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-#define CONFIG_FFRTMPHTTP_PROTOCOL 0
-#define CONFIG_FILE_PROTOCOL 0
-#define CONFIG_FTP_PROTOCOL 0
-#define CONFIG_GOPHER_PROTOCOL 0
-#define CONFIG_HLS_PROTOCOL 0
-#define CONFIG_HTTP_PROTOCOL 0
-#define CONFIG_HTTPPROXY_PROTOCOL 0
-#define CONFIG_HTTPS_PROTOCOL 0
-#define CONFIG_ICECAST_PROTOCOL 0
-#define CONFIG_MMSH_PROTOCOL 0
-#define CONFIG_MMST_PROTOCOL 0
-#define CONFIG_MD5_PROTOCOL 0
-#define CONFIG_PIPE_PROTOCOL 0
-#define CONFIG_RTMP_PROTOCOL 0
-#define CONFIG_RTMPE_PROTOCOL 0
-#define CONFIG_RTMPS_PROTOCOL 0
-#define CONFIG_RTMPT_PROTOCOL 0
-#define CONFIG_RTMPTE_PROTOCOL 0
-#define CONFIG_RTMPTS_PROTOCOL 0
-#define CONFIG_RTP_PROTOCOL 0
-#define CONFIG_SCTP_PROTOCOL 0
-#define CONFIG_SRTP_PROTOCOL 0
-#define CONFIG_SUBFILE_PROTOCOL 0
-#define CONFIG_TEE_PROTOCOL 0
-#define CONFIG_TCP_PROTOCOL 0
-#define CONFIG_TLS_GNUTLS_PROTOCOL 0
-#define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-#define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-#define CONFIG_TLS_OPENSSL_PROTOCOL 0
-#define CONFIG_UDP_PROTOCOL 0
-#define CONFIG_UDPLITE_PROTOCOL 0
-#define CONFIG_UNIX_PROTOCOL 0
-#define CONFIG_LIBRTMP_PROTOCOL 0
-#define CONFIG_LIBRTMPE_PROTOCOL 0
-#define CONFIG_LIBRTMPS_PROTOCOL 0
-#define CONFIG_LIBRTMPT_PROTOCOL 0
-#define CONFIG_LIBRTMPTE_PROTOCOL 0
-#define CONFIG_LIBSSH_PROTOCOL 0
-#define CONFIG_LIBSMBCLIENT_PROTOCOL 0
#endif /* FFMPEG_CONFIG_H */
diff --git a/media/ffvpx/config_unix32.h b/media/ffvpx/config_unix32.h
index 9318d1851..c2316caab 100644
--- a/media/ffvpx/config_unix32.h
+++ b/media/ffvpx/config_unix32.h
@@ -1,12 +1,12 @@
/* Automatically generated by configure - do not modify! */
#ifndef FFMPEG_CONFIG_H
#define FFMPEG_CONFIG_H
-#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-asm --enable-yasm --disable-asm --disable-yasm --cc='gcc -m32'"
+#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl2 --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-decoder=flac --disable-asm --disable-x86asm"
#define FFMPEG_LICENSE "LGPL version 2.1 or later"
-#define CONFIG_THIS_YEAR 2016
+#define CONFIG_THIS_YEAR 2017
#define FFMPEG_DATADIR "/usr/local/share/ffmpeg"
#define AVCONV_DATADIR "/usr/local/share/ffmpeg"
-#define CC_IDENT "gcc 4.6 (Ubuntu/Linaro 4.6.3-1ubuntu5)"
+#define CC_IDENT "gcc 6.3.0 (Ubuntu 6.3.0-12ubuntu2) 20170406"
#define av_restrict restrict
#define EXTERN_PREFIX ""
#define EXTERN_ASM
@@ -178,11 +178,11 @@
#define HAVE_LOCAL_ALIGNED_16 1
#define HAVE_LOCAL_ALIGNED_32 1
#define HAVE_SIMD_ALIGN_16 0
+#define HAVE_SIMD_ALIGN_32 0
#define HAVE_ATOMICS_GCC 1
#define HAVE_ATOMICS_SUNCC 0
#define HAVE_ATOMICS_WIN32 0
#define HAVE_ATOMIC_CAS_PTR 0
-#define HAVE_ATOMIC_COMPARE_EXCHANGE 0
#define HAVE_MACHINE_RW_BARRIER 0
#define HAVE_MEMORYBARRIER 0
#define HAVE_MM_EMPTY 0
@@ -194,15 +194,16 @@
#define HAVE_CEXP 1
#define HAVE_INLINE_ASM 1
#define HAVE_SYMVER 1
-#define HAVE_YASM 0
+#define HAVE_X86ASM 0
#define HAVE_BIGENDIAN 0
#define HAVE_FAST_UNALIGNED 0
-#define HAVE_ALSA_ASOUNDLIB_H 0
#define HAVE_ALTIVEC_H 0
#define HAVE_ARPA_INET_H 1
#define HAVE_ASM_TYPES_H 1
#define HAVE_CDIO_PARANOIA_H 0
#define HAVE_CDIO_PARANOIA_PARANOIA_H 0
+#define HAVE_CUDA_H 0
+#define HAVE_D3D11_H 0
#define HAVE_DISPATCH_DISPATCH_H 0
#define HAVE_DEV_BKTR_IOCTL_BT848_H 0
#define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
@@ -212,7 +213,7 @@
#define HAVE_DIRECT_H 0
#define HAVE_DIRENT_H 1
#define HAVE_DLFCN_H 1
-#define HAVE_D3D11_H 0
+#define HAVE_DXGIDEBUG_H 0
#define HAVE_DXVA_H 0
#define HAVE_ES2_GL_H 0
#define HAVE_GSM_H 0
@@ -221,13 +222,15 @@
#define HAVE_MACHINE_IOCTL_BT848_H 0
#define HAVE_MACHINE_IOCTL_METEOR_H 0
#define HAVE_OPENCV2_CORE_CORE_C_H 0
+#define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+#define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
#define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
#define HAVE_OPENGL_GL3_H 0
#define HAVE_POLL_H 1
-#define HAVE_SNDIO_H 0
#define HAVE_SOUNDCARD_H 0
+#define HAVE_STDATOMIC_H 1
#define HAVE_SYS_MMAN_H 1
#define HAVE_SYS_PARAM_H 1
#define HAVE_SYS_RESOURCE_H 1
@@ -279,7 +282,6 @@
#define HAVE_COMMANDLINETOARGVW 0
#define HAVE_COTASKMEMFREE 0
#define HAVE_CRYPTGENRANDOM 0
-#define HAVE_DLOPEN 1
#define HAVE_FCNTL 1
#define HAVE_FLT_LIM 1
#define HAVE_FORK 1
@@ -318,6 +320,7 @@
#define HAVE_SLEEP 0
#define HAVE_STRERROR_R 1
#define HAVE_SYSCONF 1
+#define HAVE_SYSCTL 0
#define HAVE_USLEEP 1
#define HAVE_UTGETOSTYPEFROMSTRING 0
#define HAVE_VIRTUALALLOC 0
@@ -326,11 +329,13 @@
#define HAVE_OS2THREADS 0
#define HAVE_W32THREADS 0
#define HAVE_AS_DN_DIRECTIVE 0
+#define HAVE_AS_FPU_DIRECTIVE 0
#define HAVE_AS_FUNC 0
#define HAVE_AS_OBJECT_ARCH 0
#define HAVE_ASM_MOD_Q 0
#define HAVE_ATTRIBUTE_MAY_ALIAS 1
#define HAVE_ATTRIBUTE_PACKED 1
+#define HAVE_BLOCKS_EXTENSION 0
#define HAVE_EBP_AVAILABLE 1
#define HAVE_EBX_AVAILABLE 1
#define HAVE_GNU_AS 0
@@ -347,6 +352,7 @@
#define HAVE_XFORM_ASM 0
#define HAVE_XMM_CLOBBERS 0
#define HAVE_CONDITION_VARIABLE_PTR 0
+#define HAVE_KCMVIDEOCODECTYPE_HEVC 0
#define HAVE_SOCKLEN_T 1
#define HAVE_STRUCT_ADDRINFO 1
#define HAVE_STRUCT_GROUP_SOURCE_REQ 1
@@ -363,36 +369,20 @@
#define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 1
#define HAVE_ATOMICS_NATIVE 1
#define HAVE_DOS_PATHS 0
-#define HAVE_DXVA2_LIB 0
-#define HAVE_DXVA2API_COBJ 0
#define HAVE_LIBC_MSVCRT 0
-#define HAVE_LIBDC1394_1 0
-#define HAVE_LIBDC1394_2 0
#define HAVE_MAKEINFO 0
#define HAVE_MAKEINFO_HTML 0
#define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
#define HAVE_PERL 1
#define HAVE_POD2MAN 1
-#define HAVE_SDL2 0
#define HAVE_SECTION_DATA_REL_RO 1
#define HAVE_TEXI2HTML 0
#define HAVE_THREADS 1
+#define HAVE_UWP 0
#define HAVE_VAAPI_DRM 0
#define HAVE_VAAPI_X11 0
#define HAVE_VDPAU_X11 0
#define HAVE_WINRT 0
-#define HAVE_XLIB 0
-#define CONFIG_BSFS 0
-#define CONFIG_DECODERS 1
-#define CONFIG_ENCODERS 0
-#define CONFIG_HWACCELS 0
-#define CONFIG_PARSERS 1
-#define CONFIG_INDEVS 0
-#define CONFIG_OUTDEVS 0
-#define CONFIG_FILTERS 0
-#define CONFIG_DEMUXERS 0
-#define CONFIG_MUXERS 0
-#define CONFIG_PROTOCOLS 0
#define CONFIG_DOC 0
#define CONFIG_HTMLPAGES 0
#define CONFIG_MANPAGES 1
@@ -400,13 +390,17 @@
#define CONFIG_TXTPAGES 0
#define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
#define CONFIG_AVIO_READING_EXAMPLE 1
-#define CONFIG_DECODING_ENCODING_EXAMPLE 0
+#define CONFIG_DECODE_AUDIO_EXAMPLE 1
+#define CONFIG_DECODE_VIDEO_EXAMPLE 1
#define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+#define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+#define CONFIG_ENCODE_VIDEO_EXAMPLE 1
#define CONFIG_EXTRACT_MVS_EXAMPLE 0
#define CONFIG_FILTER_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_VIDEO_EXAMPLE 0
#define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+#define CONFIG_HW_DECODE_EXAMPLE 0
#define CONFIG_METADATA_EXAMPLE 0
#define CONFIG_MUXING_EXAMPLE 0
#define CONFIG_QSVDEC_EXAMPLE 0
@@ -415,27 +409,55 @@
#define CONFIG_SCALING_VIDEO_EXAMPLE 0
#define CONFIG_TRANSCODE_AAC_EXAMPLE 0
#define CONFIG_TRANSCODING_EXAMPLE 0
-#define CONFIG_AVISYNTH 0
+#define CONFIG_ALSA 0
+#define CONFIG_APPKIT 0
+#define CONFIG_AVFOUNDATION 0
#define CONFIG_BZLIB 0
-#define CONFIG_CHROMAPRINT 0
-#define CONFIG_CRYSTALHD 0
-#define CONFIG_DECKLINK 0
+#define CONFIG_COREIMAGE 0
+#define CONFIG_ICONV 0
+#define CONFIG_JACK 0
+#define CONFIG_LIBXCB 0
+#define CONFIG_LIBXCB_SHM 0
+#define CONFIG_LIBXCB_SHAPE 0
+#define CONFIG_LIBXCB_XFIXES 0
+#define CONFIG_LZMA 0
+#define CONFIG_SCHANNEL 0
+#define CONFIG_SDL2 0
+#define CONFIG_SECURETRANSPORT 0
+#define CONFIG_SNDIO 0
+#define CONFIG_XLIB 1
+#define CONFIG_ZLIB 0
+#define CONFIG_AVISYNTH 0
#define CONFIG_FREI0R 0
-#define CONFIG_GCRYPT 0
+#define CONFIG_LIBCDIO 0
+#define CONFIG_LIBRUBBERBAND 0
+#define CONFIG_LIBVIDSTAB 0
+#define CONFIG_LIBX264 0
+#define CONFIG_LIBX265 0
+#define CONFIG_LIBXAVS 0
+#define CONFIG_LIBXVID 0
+#define CONFIG_DECKLINK 0
+#define CONFIG_LIBNDI_NEWTEK 0
+#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_OPENSSL 0
#define CONFIG_GMP 0
+#define CONFIG_LIBOPENCORE_AMRNB 0
+#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_RKMPP 0
+#define CONFIG_LIBSMBCLIENT 0
+#define CONFIG_CHROMAPRINT 0
+#define CONFIG_GCRYPT 0
#define CONFIG_GNUTLS 0
-#define CONFIG_ICONV 0
#define CONFIG_JNI 0
#define CONFIG_LADSPA 0
#define CONFIG_LIBASS 0
#define CONFIG_LIBBLURAY 0
#define CONFIG_LIBBS2B 0
#define CONFIG_LIBCACA 0
-#define CONFIG_LIBCDIO 0
#define CONFIG_LIBCELT 0
#define CONFIG_LIBDC1394 0
-#define CONFIG_LIBEBUR128 0
-#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_LIBDRM 0
#define CONFIG_LIBFLITE 0
#define CONFIG_LIBFONTCONFIG 0
#define CONFIG_LIBFREETYPE 0
@@ -447,18 +469,15 @@
#define CONFIG_LIBKVAZAAR 0
#define CONFIG_LIBMODPLUG 0
#define CONFIG_LIBMP3LAME 0
-#define CONFIG_LIBNUT 0
-#define CONFIG_LIBOPENCORE_AMRNB 0
-#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBMYSOFA 0
#define CONFIG_LIBOPENCV 0
#define CONFIG_LIBOPENH264 0
#define CONFIG_LIBOPENJPEG 0
#define CONFIG_LIBOPENMPT 0
#define CONFIG_LIBOPUS 0
#define CONFIG_LIBPULSE 0
+#define CONFIG_LIBRSVG 0
#define CONFIG_LIBRTMP 0
-#define CONFIG_LIBRUBBERBAND 0
-#define CONFIG_LIBSCHROEDINGER 0
#define CONFIG_LIBSHINE 0
#define CONFIG_LIBSMBCLIENT 0
#define CONFIG_LIBSNAPPY 0
@@ -469,52 +488,37 @@
#define CONFIG_LIBTHEORA 0
#define CONFIG_LIBTWOLAME 0
#define CONFIG_LIBV4L2 0
-#define CONFIG_LIBVIDSTAB 0
-#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_LIBVMAF 0
#define CONFIG_LIBVORBIS 0
#define CONFIG_LIBVPX 0
#define CONFIG_LIBWAVPACK 0
#define CONFIG_LIBWEBP 0
-#define CONFIG_LIBX264 0
-#define CONFIG_LIBX265 0
-#define CONFIG_LIBXAVS 0
-#define CONFIG_LIBXCB 0
-#define CONFIG_LIBXCB_SHM 0
-#define CONFIG_LIBXCB_SHAPE 0
-#define CONFIG_LIBXCB_XFIXES 0
-#define CONFIG_LIBXVID 0
+#define CONFIG_LIBXML2 0
#define CONFIG_LIBZIMG 0
#define CONFIG_LIBZMQ 0
#define CONFIG_LIBZVBI 0
-#define CONFIG_LZMA 0
#define CONFIG_MEDIACODEC 0
-#define CONFIG_NETCDF 0
#define CONFIG_OPENAL 0
#define CONFIG_OPENCL 0
#define CONFIG_OPENGL 0
-#define CONFIG_OPENSSL 0
-#define CONFIG_SCHANNEL 0
-#define CONFIG_SDL 0
-#define CONFIG_SDL2 0
-#define CONFIG_SECURETRANSPORT 0
-#define CONFIG_X11GRAB 0
-#define CONFIG_XLIB 0
-#define CONFIG_ZLIB 0
#define CONFIG_AUDIOTOOLBOX 0
-#define CONFIG_CUDA 0
-#define CONFIG_CUVID 0
+#define CONFIG_CRYSTALHD 0
+#define CONFIG_CUDA 1
+#define CONFIG_CUVID 1
#define CONFIG_D3D11VA 0
#define CONFIG_DXVA2 0
-#define CONFIG_LIBMFX 0
-#define CONFIG_LIBNPP 0
-#define CONFIG_MMAL 0
-#define CONFIG_NVENC 0
-#define CONFIG_OMX 0
+#define CONFIG_NVENC 1
#define CONFIG_VAAPI 0
#define CONFIG_VDA 0
#define CONFIG_VDPAU 0
-#define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_VIDEOTOOLBOX 0
+#define CONFIG_V4L2_M2M 1
#define CONFIG_XVMC 0
+#define CONFIG_CUDA_SDK 0
+#define CONFIG_LIBNPP 0
+#define CONFIG_LIBMFX 0
+#define CONFIG_MMAL 0
+#define CONFIG_OMX 0
#define CONFIG_FTRAPV 0
#define CONFIG_GRAY 0
#define CONFIG_HARDCODED_TABLES 0
@@ -553,16 +557,27 @@
#define CONFIG_PIXELUTILS 0
#define CONFIG_NETWORK 0
#define CONFIG_RDFT 0
+#define CONFIG_AUTODETECT 0
#define CONFIG_FONTCONFIG 0
-#define CONFIG_MEMALIGN_HACK 0
+#define CONFIG_LINUX_PERF 0
#define CONFIG_MEMORY_POISONING 0
#define CONFIG_NEON_CLOBBER_TEST 0
-#define CONFIG_PIC 0
-#define CONFIG_POD2MAN 1
-#define CONFIG_RAISE_MAJOR 0
+#define CONFIG_OSSFUZZ 0
+#define CONFIG_PIC 1
#define CONFIG_THUMB 0
#define CONFIG_VALGRIND_BACKTRACE 0
#define CONFIG_XMM_CLOBBER_TEST 0
+#define CONFIG_BSFS 1
+#define CONFIG_DECODERS 1
+#define CONFIG_ENCODERS 0
+#define CONFIG_HWACCELS 0
+#define CONFIG_PARSERS 1
+#define CONFIG_INDEVS 0
+#define CONFIG_OUTDEVS 0
+#define CONFIG_FILTERS 0
+#define CONFIG_DEMUXERS 0
+#define CONFIG_MUXERS 0
+#define CONFIG_PROTOCOLS 0
#define CONFIG_AANDCTTABLES 0
#define CONFIG_AC3DSP 0
#define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -580,20 +595,22 @@
#define CONFIG_FMTCONVERT 0
#define CONFIG_FRAME_THREAD_ENCODER 0
#define CONFIG_G722DSP 0
-#define CONFIG_GOLOMB 1
+#define CONFIG_GOLOMB 0
#define CONFIG_GPLV3 0
#define CONFIG_H263DSP 0
#define CONFIG_H264CHROMA 0
#define CONFIG_H264DSP 0
+#define CONFIG_H264PARSE 0
#define CONFIG_H264PRED 1
#define CONFIG_H264QPEL 0
+#define CONFIG_HEVCPARSE 0
#define CONFIG_HPELDSP 0
#define CONFIG_HUFFMAN 0
#define CONFIG_HUFFYUVDSP 0
#define CONFIG_HUFFYUVENCDSP 0
#define CONFIG_IDCTDSP 0
#define CONFIG_IIRFILTER 0
-#define CONFIG_IMDCT15 0
+#define CONFIG_MDCT15 0
#define CONFIG_INTRAX8 0
#define CONFIG_ISO_MEDIA 0
#define CONFIG_IVIDSP 0
@@ -602,12 +619,14 @@
#define CONFIG_LIBX262 0
#define CONFIG_LLAUDDSP 0
#define CONFIG_LLVIDDSP 0
+#define CONFIG_LLVIDENCDSP 0
#define CONFIG_LPC 0
#define CONFIG_LZF 0
#define CONFIG_ME_CMP 0
#define CONFIG_MPEG_ER 0
#define CONFIG_MPEGAUDIO 0
#define CONFIG_MPEGAUDIODSP 0
+#define CONFIG_MPEGAUDIOHEADER 0
#define CONFIG_MPEGVIDEO 0
#define CONFIG_MPEGVIDEOENC 0
#define CONFIG_MSS34DSP 0
@@ -629,1595 +648,20 @@
#define CONFIG_TEXTUREDSP 0
#define CONFIG_TEXTUREDSPENC 0
#define CONFIG_TPELDSP 0
+#define CONFIG_VAAPI_1 0
#define CONFIG_VAAPI_ENCODE 0
#define CONFIG_VC1DSP 0
#define CONFIG_VIDEODSP 1
#define CONFIG_VP3DSP 0
#define CONFIG_VP56DSP 0
#define CONFIG_VP8DSP 1
-#define CONFIG_VT_BT2020 0
#define CONFIG_WMA_FREQS 0
#define CONFIG_WMV2DSP 0
-#define CONFIG_AAC_ADTSTOASC_BSF 0
-#define CONFIG_CHOMP_BSF 0
-#define CONFIG_DUMP_EXTRADATA_BSF 0
-#define CONFIG_DCA_CORE_BSF 0
-#define CONFIG_H264_MP4TOANNEXB_BSF 0
-#define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-#define CONFIG_IMX_DUMP_HEADER_BSF 0
-#define CONFIG_MJPEG2JPEG_BSF 0
-#define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-#define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-#define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-#define CONFIG_MOV2TEXTSUB_BSF 0
-#define CONFIG_NOISE_BSF 0
-#define CONFIG_REMOVE_EXTRADATA_BSF 0
-#define CONFIG_TEXT2MOVSUB_BSF 0
-#define CONFIG_VP9_SUPERFRAME_BSF 0
-#define CONFIG_AASC_DECODER 0
-#define CONFIG_AIC_DECODER 0
-#define CONFIG_ALIAS_PIX_DECODER 0
-#define CONFIG_AMV_DECODER 0
-#define CONFIG_ANM_DECODER 0
-#define CONFIG_ANSI_DECODER 0
-#define CONFIG_APNG_DECODER 0
-#define CONFIG_ASV1_DECODER 0
-#define CONFIG_ASV2_DECODER 0
-#define CONFIG_AURA_DECODER 0
-#define CONFIG_AURA2_DECODER 0
-#define CONFIG_AVRP_DECODER 0
-#define CONFIG_AVRN_DECODER 0
-#define CONFIG_AVS_DECODER 0
-#define CONFIG_AVUI_DECODER 0
-#define CONFIG_AYUV_DECODER 0
-#define CONFIG_BETHSOFTVID_DECODER 0
-#define CONFIG_BFI_DECODER 0
-#define CONFIG_BINK_DECODER 0
-#define CONFIG_BMP_DECODER 0
-#define CONFIG_BMV_VIDEO_DECODER 0
-#define CONFIG_BRENDER_PIX_DECODER 0
-#define CONFIG_C93_DECODER 0
-#define CONFIG_CAVS_DECODER 0
-#define CONFIG_CDGRAPHICS_DECODER 0
-#define CONFIG_CDXL_DECODER 0
-#define CONFIG_CFHD_DECODER 0
-#define CONFIG_CINEPAK_DECODER 0
-#define CONFIG_CLJR_DECODER 0
-#define CONFIG_CLLC_DECODER 0
-#define CONFIG_COMFORTNOISE_DECODER 0
-#define CONFIG_CPIA_DECODER 0
-#define CONFIG_CSCD_DECODER 0
-#define CONFIG_CYUV_DECODER 0
-#define CONFIG_DDS_DECODER 0
-#define CONFIG_DFA_DECODER 0
-#define CONFIG_DIRAC_DECODER 0
-#define CONFIG_DNXHD_DECODER 0
-#define CONFIG_DPX_DECODER 0
-#define CONFIG_DSICINVIDEO_DECODER 0
-#define CONFIG_DVAUDIO_DECODER 0
-#define CONFIG_DVVIDEO_DECODER 0
-#define CONFIG_DXA_DECODER 0
-#define CONFIG_DXTORY_DECODER 0
-#define CONFIG_DXV_DECODER 0
-#define CONFIG_EACMV_DECODER 0
-#define CONFIG_EAMAD_DECODER 0
-#define CONFIG_EATGQ_DECODER 0
-#define CONFIG_EATGV_DECODER 0
-#define CONFIG_EATQI_DECODER 0
-#define CONFIG_EIGHTBPS_DECODER 0
-#define CONFIG_EIGHTSVX_EXP_DECODER 0
-#define CONFIG_EIGHTSVX_FIB_DECODER 0
-#define CONFIG_ESCAPE124_DECODER 0
-#define CONFIG_ESCAPE130_DECODER 0
-#define CONFIG_EXR_DECODER 0
-#define CONFIG_FFV1_DECODER 0
-#define CONFIG_FFVHUFF_DECODER 0
-#define CONFIG_FIC_DECODER 0
-#define CONFIG_FLASHSV_DECODER 0
-#define CONFIG_FLASHSV2_DECODER 0
-#define CONFIG_FLIC_DECODER 0
-#define CONFIG_FLV_DECODER 0
-#define CONFIG_FOURXM_DECODER 0
-#define CONFIG_FRAPS_DECODER 0
-#define CONFIG_FRWU_DECODER 0
-#define CONFIG_G2M_DECODER 0
-#define CONFIG_GIF_DECODER 0
-#define CONFIG_H261_DECODER 0
-#define CONFIG_H263_DECODER 0
-#define CONFIG_H263I_DECODER 0
-#define CONFIG_H263P_DECODER 0
-#define CONFIG_H264_DECODER 0
-#define CONFIG_H264_CRYSTALHD_DECODER 0
-#define CONFIG_H264_MEDIACODEC_DECODER 0
-#define CONFIG_H264_MMAL_DECODER 0
-#define CONFIG_H264_QSV_DECODER 0
-#define CONFIG_H264_VDA_DECODER 0
-#define CONFIG_H264_VDPAU_DECODER 0
-#define CONFIG_HAP_DECODER 0
-#define CONFIG_HEVC_DECODER 0
-#define CONFIG_HEVC_QSV_DECODER 0
-#define CONFIG_HNM4_VIDEO_DECODER 0
-#define CONFIG_HQ_HQA_DECODER 0
-#define CONFIG_HQX_DECODER 0
-#define CONFIG_HUFFYUV_DECODER 0
-#define CONFIG_IDCIN_DECODER 0
-#define CONFIG_IFF_ILBM_DECODER 0
-#define CONFIG_INDEO2_DECODER 0
-#define CONFIG_INDEO3_DECODER 0
-#define CONFIG_INDEO4_DECODER 0
-#define CONFIG_INDEO5_DECODER 0
-#define CONFIG_INTERPLAY_VIDEO_DECODER 0
-#define CONFIG_JPEG2000_DECODER 0
-#define CONFIG_JPEGLS_DECODER 0
-#define CONFIG_JV_DECODER 0
-#define CONFIG_KGV1_DECODER 0
-#define CONFIG_KMVC_DECODER 0
-#define CONFIG_LAGARITH_DECODER 0
-#define CONFIG_LOCO_DECODER 0
-#define CONFIG_M101_DECODER 0
-#define CONFIG_MAGICYUV_DECODER 0
-#define CONFIG_MDEC_DECODER 0
-#define CONFIG_MIMIC_DECODER 0
-#define CONFIG_MJPEG_DECODER 0
-#define CONFIG_MJPEGB_DECODER 0
-#define CONFIG_MMVIDEO_DECODER 0
-#define CONFIG_MOTIONPIXELS_DECODER 0
-#define CONFIG_MPEG_XVMC_DECODER 0
-#define CONFIG_MPEG1VIDEO_DECODER 0
-#define CONFIG_MPEG2VIDEO_DECODER 0
-#define CONFIG_MPEG4_DECODER 0
-#define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG4_MMAL_DECODER 0
-#define CONFIG_MPEG4_VDPAU_DECODER 0
-#define CONFIG_MPEGVIDEO_DECODER 0
-#define CONFIG_MPEG_VDPAU_DECODER 0
-#define CONFIG_MPEG1_VDPAU_DECODER 0
-#define CONFIG_MPEG2_MMAL_DECODER 0
-#define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG2_QSV_DECODER 0
-#define CONFIG_MSA1_DECODER 0
-#define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MSMPEG4V1_DECODER 0
-#define CONFIG_MSMPEG4V2_DECODER 0
-#define CONFIG_MSMPEG4V3_DECODER 0
-#define CONFIG_MSRLE_DECODER 0
-#define CONFIG_MSS1_DECODER 0
-#define CONFIG_MSS2_DECODER 0
-#define CONFIG_MSVIDEO1_DECODER 0
-#define CONFIG_MSZH_DECODER 0
-#define CONFIG_MTS2_DECODER 0
-#define CONFIG_MVC1_DECODER 0
-#define CONFIG_MVC2_DECODER 0
-#define CONFIG_MXPEG_DECODER 0
-#define CONFIG_NUV_DECODER 0
-#define CONFIG_PAF_VIDEO_DECODER 0
-#define CONFIG_PAM_DECODER 0
-#define CONFIG_PBM_DECODER 0
-#define CONFIG_PCX_DECODER 0
-#define CONFIG_PGM_DECODER 0
-#define CONFIG_PGMYUV_DECODER 0
-#define CONFIG_PICTOR_DECODER 0
-#define CONFIG_PNG_DECODER 0
-#define CONFIG_PPM_DECODER 0
-#define CONFIG_PRORES_DECODER 0
-#define CONFIG_PRORES_LGPL_DECODER 0
-#define CONFIG_PTX_DECODER 0
-#define CONFIG_QDRAW_DECODER 0
-#define CONFIG_QPEG_DECODER 0
-#define CONFIG_QTRLE_DECODER 0
-#define CONFIG_R10K_DECODER 0
-#define CONFIG_R210_DECODER 0
-#define CONFIG_RAWVIDEO_DECODER 0
-#define CONFIG_RL2_DECODER 0
-#define CONFIG_ROQ_DECODER 0
-#define CONFIG_RPZA_DECODER 0
-#define CONFIG_RSCC_DECODER 0
-#define CONFIG_RV10_DECODER 0
-#define CONFIG_RV20_DECODER 0
-#define CONFIG_RV30_DECODER 0
-#define CONFIG_RV40_DECODER 0
-#define CONFIG_S302M_DECODER 0
-#define CONFIG_SANM_DECODER 0
-#define CONFIG_SCREENPRESSO_DECODER 0
-#define CONFIG_SDX2_DPCM_DECODER 0
-#define CONFIG_SGI_DECODER 0
-#define CONFIG_SGIRLE_DECODER 0
-#define CONFIG_SHEERVIDEO_DECODER 0
-#define CONFIG_SMACKER_DECODER 0
-#define CONFIG_SMC_DECODER 0
-#define CONFIG_SMVJPEG_DECODER 0
-#define CONFIG_SNOW_DECODER 0
-#define CONFIG_SP5X_DECODER 0
-#define CONFIG_SUNRAST_DECODER 0
-#define CONFIG_SVQ1_DECODER 0
-#define CONFIG_SVQ3_DECODER 0
-#define CONFIG_TARGA_DECODER 0
-#define CONFIG_TARGA_Y216_DECODER 0
-#define CONFIG_TDSC_DECODER 0
-#define CONFIG_THEORA_DECODER 0
-#define CONFIG_THP_DECODER 0
-#define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-#define CONFIG_TIFF_DECODER 0
-#define CONFIG_TMV_DECODER 0
-#define CONFIG_TRUEMOTION1_DECODER 0
-#define CONFIG_TRUEMOTION2_DECODER 0
-#define CONFIG_TRUEMOTION2RT_DECODER 0
-#define CONFIG_TSCC_DECODER 0
-#define CONFIG_TSCC2_DECODER 0
-#define CONFIG_TXD_DECODER 0
-#define CONFIG_ULTI_DECODER 0
-#define CONFIG_UTVIDEO_DECODER 0
-#define CONFIG_V210_DECODER 0
-#define CONFIG_V210X_DECODER 0
-#define CONFIG_V308_DECODER 0
-#define CONFIG_V408_DECODER 0
-#define CONFIG_V410_DECODER 0
-#define CONFIG_VB_DECODER 0
-#define CONFIG_VBLE_DECODER 0
-#define CONFIG_VC1_DECODER 0
-#define CONFIG_VC1_CRYSTALHD_DECODER 0
-#define CONFIG_VC1_VDPAU_DECODER 0
-#define CONFIG_VC1IMAGE_DECODER 0
-#define CONFIG_VC1_MMAL_DECODER 0
-#define CONFIG_VC1_QSV_DECODER 0
-#define CONFIG_VCR1_DECODER 0
-#define CONFIG_VMDVIDEO_DECODER 0
-#define CONFIG_VMNC_DECODER 0
-#define CONFIG_VP3_DECODER 0
-#define CONFIG_VP5_DECODER 0
-#define CONFIG_VP6_DECODER 0
-#define CONFIG_VP6A_DECODER 0
-#define CONFIG_VP6F_DECODER 0
-#define CONFIG_VP7_DECODER 0
+#define CONFIG_NULL_BSF 1
#define CONFIG_VP8_DECODER 1
#define CONFIG_VP9_DECODER 1
-#define CONFIG_VQA_DECODER 0
-#define CONFIG_WEBP_DECODER 0
-#define CONFIG_WMV1_DECODER 0
-#define CONFIG_WMV2_DECODER 0
-#define CONFIG_WMV3_DECODER 0
-#define CONFIG_WMV3_CRYSTALHD_DECODER 0
-#define CONFIG_WMV3_VDPAU_DECODER 0
-#define CONFIG_WMV3IMAGE_DECODER 0
-#define CONFIG_WNV1_DECODER 0
-#define CONFIG_XAN_WC3_DECODER 0
-#define CONFIG_XAN_WC4_DECODER 0
-#define CONFIG_XBM_DECODER 0
-#define CONFIG_XFACE_DECODER 0
-#define CONFIG_XL_DECODER 0
-#define CONFIG_XWD_DECODER 0
-#define CONFIG_Y41P_DECODER 0
-#define CONFIG_YLC_DECODER 0
-#define CONFIG_YOP_DECODER 0
-#define CONFIG_YUV4_DECODER 0
-#define CONFIG_ZERO12V_DECODER 0
-#define CONFIG_ZEROCODEC_DECODER 0
-#define CONFIG_ZLIB_DECODER 0
-#define CONFIG_ZMBV_DECODER 0
-#define CONFIG_AAC_DECODER 0
-#define CONFIG_AAC_FIXED_DECODER 0
-#define CONFIG_AAC_LATM_DECODER 0
-#define CONFIG_AC3_DECODER 0
-#define CONFIG_AC3_FIXED_DECODER 0
-#define CONFIG_ALAC_DECODER 0
-#define CONFIG_ALS_DECODER 0
-#define CONFIG_AMRNB_DECODER 0
-#define CONFIG_AMRWB_DECODER 0
-#define CONFIG_APE_DECODER 0
-#define CONFIG_ATRAC1_DECODER 0
-#define CONFIG_ATRAC3_DECODER 0
-#define CONFIG_ATRAC3P_DECODER 0
-#define CONFIG_BINKAUDIO_DCT_DECODER 0
-#define CONFIG_BINKAUDIO_RDFT_DECODER 0
-#define CONFIG_BMV_AUDIO_DECODER 0
-#define CONFIG_COOK_DECODER 0
-#define CONFIG_DCA_DECODER 0
-#define CONFIG_DSD_LSBF_DECODER 0
-#define CONFIG_DSD_MSBF_DECODER 0
-#define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-#define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-#define CONFIG_DSICINAUDIO_DECODER 0
-#define CONFIG_DSS_SP_DECODER 0
-#define CONFIG_DST_DECODER 0
-#define CONFIG_EAC3_DECODER 0
-#define CONFIG_EVRC_DECODER 0
-#define CONFIG_FFWAVESYNTH_DECODER 0
#define CONFIG_FLAC_DECODER 1
-#define CONFIG_G723_1_DECODER 0
-#define CONFIG_G729_DECODER 0
-#define CONFIG_GSM_DECODER 0
-#define CONFIG_GSM_MS_DECODER 0
-#define CONFIG_IAC_DECODER 0
-#define CONFIG_IMC_DECODER 0
-#define CONFIG_INTERPLAY_ACM_DECODER 0
-#define CONFIG_MACE3_DECODER 0
-#define CONFIG_MACE6_DECODER 0
-#define CONFIG_METASOUND_DECODER 0
-#define CONFIG_MLP_DECODER 0
-#define CONFIG_MP1_DECODER 0
-#define CONFIG_MP1FLOAT_DECODER 0
-#define CONFIG_MP2_DECODER 0
-#define CONFIG_MP2FLOAT_DECODER 0
-#define CONFIG_MP3_DECODER 0
-#define CONFIG_MP3FLOAT_DECODER 0
-#define CONFIG_MP3ADU_DECODER 0
-#define CONFIG_MP3ADUFLOAT_DECODER 0
-#define CONFIG_MP3ON4_DECODER 0
-#define CONFIG_MP3ON4FLOAT_DECODER 0
-#define CONFIG_MPC7_DECODER 0
-#define CONFIG_MPC8_DECODER 0
-#define CONFIG_NELLYMOSER_DECODER 0
-#define CONFIG_ON2AVC_DECODER 0
-#define CONFIG_OPUS_DECODER 0
-#define CONFIG_PAF_AUDIO_DECODER 0
-#define CONFIG_QCELP_DECODER 0
-#define CONFIG_QDM2_DECODER 0
-#define CONFIG_RA_144_DECODER 0
-#define CONFIG_RA_288_DECODER 0
-#define CONFIG_RALF_DECODER 0
-#define CONFIG_SHORTEN_DECODER 0
-#define CONFIG_SIPR_DECODER 0
-#define CONFIG_SMACKAUD_DECODER 0
-#define CONFIG_SONIC_DECODER 0
-#define CONFIG_TAK_DECODER 0
-#define CONFIG_TRUEHD_DECODER 0
-#define CONFIG_TRUESPEECH_DECODER 0
-#define CONFIG_TTA_DECODER 0
-#define CONFIG_TWINVQ_DECODER 0
-#define CONFIG_VMDAUDIO_DECODER 0
-#define CONFIG_VORBIS_DECODER 0
-#define CONFIG_WAVPACK_DECODER 0
-#define CONFIG_WMALOSSLESS_DECODER 0
-#define CONFIG_WMAPRO_DECODER 0
-#define CONFIG_WMAV1_DECODER 0
-#define CONFIG_WMAV2_DECODER 0
-#define CONFIG_WMAVOICE_DECODER 0
-#define CONFIG_WS_SND1_DECODER 0
-#define CONFIG_XMA1_DECODER 0
-#define CONFIG_XMA2_DECODER 0
-#define CONFIG_PCM_ALAW_DECODER 0
-#define CONFIG_PCM_BLURAY_DECODER 0
-#define CONFIG_PCM_DVD_DECODER 0
-#define CONFIG_PCM_F32BE_DECODER 0
-#define CONFIG_PCM_F32LE_DECODER 0
-#define CONFIG_PCM_F64BE_DECODER 0
-#define CONFIG_PCM_F64LE_DECODER 0
-#define CONFIG_PCM_LXF_DECODER 0
-#define CONFIG_PCM_MULAW_DECODER 0
-#define CONFIG_PCM_S8_DECODER 0
-#define CONFIG_PCM_S8_PLANAR_DECODER 0
-#define CONFIG_PCM_S16BE_DECODER 0
-#define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-#define CONFIG_PCM_S16LE_DECODER 0
-#define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S24BE_DECODER 0
-#define CONFIG_PCM_S24DAUD_DECODER 0
-#define CONFIG_PCM_S24LE_DECODER 0
-#define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S32BE_DECODER 0
-#define CONFIG_PCM_S32LE_DECODER 0
-#define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S64BE_DECODER 0
-#define CONFIG_PCM_S64LE_DECODER 0
-#define CONFIG_PCM_U8_DECODER 0
-#define CONFIG_PCM_U16BE_DECODER 0
-#define CONFIG_PCM_U16LE_DECODER 0
-#define CONFIG_PCM_U24BE_DECODER 0
-#define CONFIG_PCM_U24LE_DECODER 0
-#define CONFIG_PCM_U32BE_DECODER 0
-#define CONFIG_PCM_U32LE_DECODER 0
-#define CONFIG_PCM_ZORK_DECODER 0
-#define CONFIG_INTERPLAY_DPCM_DECODER 0
-#define CONFIG_ROQ_DPCM_DECODER 0
-#define CONFIG_SOL_DPCM_DECODER 0
-#define CONFIG_XAN_DPCM_DECODER 0
-#define CONFIG_ADPCM_4XM_DECODER 0
-#define CONFIG_ADPCM_ADX_DECODER 0
-#define CONFIG_ADPCM_AFC_DECODER 0
-#define CONFIG_ADPCM_AICA_DECODER 0
-#define CONFIG_ADPCM_CT_DECODER 0
-#define CONFIG_ADPCM_DTK_DECODER 0
-#define CONFIG_ADPCM_EA_DECODER 0
-#define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-#define CONFIG_ADPCM_EA_R1_DECODER 0
-#define CONFIG_ADPCM_EA_R2_DECODER 0
-#define CONFIG_ADPCM_EA_R3_DECODER 0
-#define CONFIG_ADPCM_EA_XAS_DECODER 0
-#define CONFIG_ADPCM_G722_DECODER 0
-#define CONFIG_ADPCM_G726_DECODER 0
-#define CONFIG_ADPCM_G726LE_DECODER 0
-#define CONFIG_ADPCM_IMA_AMV_DECODER 0
-#define CONFIG_ADPCM_IMA_APC_DECODER 0
-#define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-#define CONFIG_ADPCM_IMA_DK3_DECODER 0
-#define CONFIG_ADPCM_IMA_DK4_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-#define CONFIG_ADPCM_IMA_ISS_DECODER 0
-#define CONFIG_ADPCM_IMA_OKI_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_DECODER 0
-#define CONFIG_ADPCM_IMA_RAD_DECODER 0
-#define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-#define CONFIG_ADPCM_IMA_WAV_DECODER 0
-#define CONFIG_ADPCM_IMA_WS_DECODER 0
-#define CONFIG_ADPCM_MS_DECODER 0
-#define CONFIG_ADPCM_MTAF_DECODER 0
-#define CONFIG_ADPCM_PSX_DECODER 0
-#define CONFIG_ADPCM_SBPRO_2_DECODER 0
-#define CONFIG_ADPCM_SBPRO_3_DECODER 0
-#define CONFIG_ADPCM_SBPRO_4_DECODER 0
-#define CONFIG_ADPCM_SWF_DECODER 0
-#define CONFIG_ADPCM_THP_DECODER 0
-#define CONFIG_ADPCM_THP_LE_DECODER 0
-#define CONFIG_ADPCM_VIMA_DECODER 0
-#define CONFIG_ADPCM_XA_DECODER 0
-#define CONFIG_ADPCM_YAMAHA_DECODER 0
-#define CONFIG_SSA_DECODER 0
-#define CONFIG_ASS_DECODER 0
-#define CONFIG_CCAPTION_DECODER 0
-#define CONFIG_DVBSUB_DECODER 0
-#define CONFIG_DVDSUB_DECODER 0
-#define CONFIG_JACOSUB_DECODER 0
-#define CONFIG_MICRODVD_DECODER 0
-#define CONFIG_MOVTEXT_DECODER 0
-#define CONFIG_MPL2_DECODER 0
-#define CONFIG_PGSSUB_DECODER 0
-#define CONFIG_PJS_DECODER 0
-#define CONFIG_REALTEXT_DECODER 0
-#define CONFIG_SAMI_DECODER 0
-#define CONFIG_SRT_DECODER 0
-#define CONFIG_STL_DECODER 0
-#define CONFIG_SUBRIP_DECODER 0
-#define CONFIG_SUBVIEWER_DECODER 0
-#define CONFIG_SUBVIEWER1_DECODER 0
-#define CONFIG_TEXT_DECODER 0
-#define CONFIG_VPLAYER_DECODER 0
-#define CONFIG_WEBVTT_DECODER 0
-#define CONFIG_XSUB_DECODER 0
-#define CONFIG_AAC_AT_DECODER 0
-#define CONFIG_AC3_AT_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-#define CONFIG_ALAC_AT_DECODER 0
-#define CONFIG_AMR_NB_AT_DECODER 0
-#define CONFIG_EAC3_AT_DECODER 0
-#define CONFIG_GSM_MS_AT_DECODER 0
-#define CONFIG_ILBC_AT_DECODER 0
-#define CONFIG_MP1_AT_DECODER 0
-#define CONFIG_MP2_AT_DECODER 0
-#define CONFIG_MP3_AT_DECODER 0
-#define CONFIG_PCM_ALAW_AT_DECODER 0
-#define CONFIG_PCM_MULAW_AT_DECODER 0
-#define CONFIG_QDMC_AT_DECODER 0
-#define CONFIG_QDM2_AT_DECODER 0
-#define CONFIG_LIBCELT_DECODER 0
-#define CONFIG_LIBFDK_AAC_DECODER 0
-#define CONFIG_LIBGSM_DECODER 0
-#define CONFIG_LIBGSM_MS_DECODER 0
-#define CONFIG_LIBILBC_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-#define CONFIG_LIBOPENJPEG_DECODER 0
-#define CONFIG_LIBOPUS_DECODER 0
-#define CONFIG_LIBSCHROEDINGER_DECODER 0
-#define CONFIG_LIBSPEEX_DECODER 0
-#define CONFIG_LIBVORBIS_DECODER 0
-#define CONFIG_LIBVPX_VP8_DECODER 0
-#define CONFIG_LIBVPX_VP9_DECODER 0
-#define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-#define CONFIG_BINTEXT_DECODER 0
-#define CONFIG_XBIN_DECODER 0
-#define CONFIG_IDF_DECODER 0
-#define CONFIG_LIBOPENH264_DECODER 0
-#define CONFIG_H263_CUVID_DECODER 0
-#define CONFIG_H264_CUVID_DECODER 0
-#define CONFIG_HEVC_CUVID_DECODER 0
-#define CONFIG_HEVC_MEDIACODEC_DECODER 0
-#define CONFIG_MJPEG_CUVID_DECODER 0
-#define CONFIG_MPEG1_CUVID_DECODER 0
-#define CONFIG_MPEG2_CUVID_DECODER 0
-#define CONFIG_MPEG4_CUVID_DECODER 0
-#define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-#define CONFIG_VC1_CUVID_DECODER 0
-#define CONFIG_VP8_CUVID_DECODER 0
-#define CONFIG_VP8_MEDIACODEC_DECODER 0
-#define CONFIG_VP9_CUVID_DECODER 0
-#define CONFIG_VP9_MEDIACODEC_DECODER 0
-#define CONFIG_AA_DEMUXER 0
-#define CONFIG_AAC_DEMUXER 0
-#define CONFIG_AC3_DEMUXER 0
-#define CONFIG_ACM_DEMUXER 0
-#define CONFIG_ACT_DEMUXER 0
-#define CONFIG_ADF_DEMUXER 0
-#define CONFIG_ADP_DEMUXER 0
-#define CONFIG_ADS_DEMUXER 0
-#define CONFIG_ADX_DEMUXER 0
-#define CONFIG_AEA_DEMUXER 0
-#define CONFIG_AFC_DEMUXER 0
-#define CONFIG_AIFF_DEMUXER 0
-#define CONFIG_AIX_DEMUXER 0
-#define CONFIG_AMR_DEMUXER 0
-#define CONFIG_ANM_DEMUXER 0
-#define CONFIG_APC_DEMUXER 0
-#define CONFIG_APE_DEMUXER 0
-#define CONFIG_APNG_DEMUXER 0
-#define CONFIG_AQTITLE_DEMUXER 0
-#define CONFIG_ASF_DEMUXER 0
-#define CONFIG_ASF_O_DEMUXER 0
-#define CONFIG_ASS_DEMUXER 0
-#define CONFIG_AST_DEMUXER 0
-#define CONFIG_AU_DEMUXER 0
-#define CONFIG_AVI_DEMUXER 0
-#define CONFIG_AVISYNTH_DEMUXER 0
-#define CONFIG_AVR_DEMUXER 0
-#define CONFIG_AVS_DEMUXER 0
-#define CONFIG_BETHSOFTVID_DEMUXER 0
-#define CONFIG_BFI_DEMUXER 0
-#define CONFIG_BINTEXT_DEMUXER 0
-#define CONFIG_BINK_DEMUXER 0
-#define CONFIG_BIT_DEMUXER 0
-#define CONFIG_BMV_DEMUXER 0
-#define CONFIG_BFSTM_DEMUXER 0
-#define CONFIG_BRSTM_DEMUXER 0
-#define CONFIG_BOA_DEMUXER 0
-#define CONFIG_C93_DEMUXER 0
-#define CONFIG_CAF_DEMUXER 0
-#define CONFIG_CAVSVIDEO_DEMUXER 0
-#define CONFIG_CDG_DEMUXER 0
-#define CONFIG_CDXL_DEMUXER 0
-#define CONFIG_CINE_DEMUXER 0
-#define CONFIG_CONCAT_DEMUXER 0
-#define CONFIG_DATA_DEMUXER 0
-#define CONFIG_DAUD_DEMUXER 0
-#define CONFIG_DCSTR_DEMUXER 0
-#define CONFIG_DFA_DEMUXER 0
-#define CONFIG_DIRAC_DEMUXER 0
-#define CONFIG_DNXHD_DEMUXER 0
-#define CONFIG_DSF_DEMUXER 0
-#define CONFIG_DSICIN_DEMUXER 0
-#define CONFIG_DSS_DEMUXER 0
-#define CONFIG_DTS_DEMUXER 0
-#define CONFIG_DTSHD_DEMUXER 0
-#define CONFIG_DV_DEMUXER 0
-#define CONFIG_DVBSUB_DEMUXER 0
-#define CONFIG_DVBTXT_DEMUXER 0
-#define CONFIG_DXA_DEMUXER 0
-#define CONFIG_EA_DEMUXER 0
-#define CONFIG_EA_CDATA_DEMUXER 0
-#define CONFIG_EAC3_DEMUXER 0
-#define CONFIG_EPAF_DEMUXER 0
-#define CONFIG_FFM_DEMUXER 0
-#define CONFIG_FFMETADATA_DEMUXER 0
-#define CONFIG_FILMSTRIP_DEMUXER 0
-#define CONFIG_FLAC_DEMUXER 0
-#define CONFIG_FLIC_DEMUXER 0
-#define CONFIG_FLV_DEMUXER 0
-#define CONFIG_LIVE_FLV_DEMUXER 0
-#define CONFIG_FOURXM_DEMUXER 0
-#define CONFIG_FRM_DEMUXER 0
-#define CONFIG_FSB_DEMUXER 0
-#define CONFIG_G722_DEMUXER 0
-#define CONFIG_G723_1_DEMUXER 0
-#define CONFIG_G729_DEMUXER 0
-#define CONFIG_GENH_DEMUXER 0
-#define CONFIG_GIF_DEMUXER 0
-#define CONFIG_GSM_DEMUXER 0
-#define CONFIG_GXF_DEMUXER 0
-#define CONFIG_H261_DEMUXER 0
-#define CONFIG_H263_DEMUXER 0
-#define CONFIG_H264_DEMUXER 0
-#define CONFIG_HEVC_DEMUXER 0
-#define CONFIG_HLS_DEMUXER 0
-#define CONFIG_HNM_DEMUXER 0
-#define CONFIG_ICO_DEMUXER 0
-#define CONFIG_IDCIN_DEMUXER 0
-#define CONFIG_IDF_DEMUXER 0
-#define CONFIG_IFF_DEMUXER 0
-#define CONFIG_ILBC_DEMUXER 0
-#define CONFIG_IMAGE2_DEMUXER 0
-#define CONFIG_IMAGE2PIPE_DEMUXER 0
-#define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-#define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-#define CONFIG_INGENIENT_DEMUXER 0
-#define CONFIG_IPMOVIE_DEMUXER 0
-#define CONFIG_IRCAM_DEMUXER 0
-#define CONFIG_ISS_DEMUXER 0
-#define CONFIG_IV8_DEMUXER 0
-#define CONFIG_IVF_DEMUXER 0
-#define CONFIG_IVR_DEMUXER 0
-#define CONFIG_JACOSUB_DEMUXER 0
-#define CONFIG_JV_DEMUXER 0
-#define CONFIG_LMLM4_DEMUXER 0
-#define CONFIG_LOAS_DEMUXER 0
-#define CONFIG_LRC_DEMUXER 0
-#define CONFIG_LVF_DEMUXER 0
-#define CONFIG_LXF_DEMUXER 0
-#define CONFIG_M4V_DEMUXER 0
-#define CONFIG_MATROSKA_DEMUXER 0
-#define CONFIG_MGSTS_DEMUXER 0
-#define CONFIG_MICRODVD_DEMUXER 0
-#define CONFIG_MJPEG_DEMUXER 0
-#define CONFIG_MLP_DEMUXER 0
-#define CONFIG_MLV_DEMUXER 0
-#define CONFIG_MM_DEMUXER 0
-#define CONFIG_MMF_DEMUXER 0
-#define CONFIG_MOV_DEMUXER 0
-#define CONFIG_MP3_DEMUXER 0
-#define CONFIG_MPC_DEMUXER 0
-#define CONFIG_MPC8_DEMUXER 0
-#define CONFIG_MPEGPS_DEMUXER 0
-#define CONFIG_MPEGTS_DEMUXER 0
-#define CONFIG_MPEGTSRAW_DEMUXER 0
-#define CONFIG_MPEGVIDEO_DEMUXER 0
-#define CONFIG_MPJPEG_DEMUXER 0
-#define CONFIG_MPL2_DEMUXER 0
-#define CONFIG_MPSUB_DEMUXER 0
-#define CONFIG_MSF_DEMUXER 0
-#define CONFIG_MSNWC_TCP_DEMUXER 0
-#define CONFIG_MTAF_DEMUXER 0
-#define CONFIG_MTV_DEMUXER 0
-#define CONFIG_MUSX_DEMUXER 0
-#define CONFIG_MV_DEMUXER 0
-#define CONFIG_MVI_DEMUXER 0
-#define CONFIG_MXF_DEMUXER 0
-#define CONFIG_MXG_DEMUXER 0
-#define CONFIG_NC_DEMUXER 0
-#define CONFIG_NISTSPHERE_DEMUXER 0
-#define CONFIG_NSV_DEMUXER 0
-#define CONFIG_NUT_DEMUXER 0
-#define CONFIG_NUV_DEMUXER 0
-#define CONFIG_OGG_DEMUXER 0
-#define CONFIG_OMA_DEMUXER 0
-#define CONFIG_PAF_DEMUXER 0
-#define CONFIG_PCM_ALAW_DEMUXER 0
-#define CONFIG_PCM_MULAW_DEMUXER 0
-#define CONFIG_PCM_F64BE_DEMUXER 0
-#define CONFIG_PCM_F64LE_DEMUXER 0
-#define CONFIG_PCM_F32BE_DEMUXER 0
-#define CONFIG_PCM_F32LE_DEMUXER 0
-#define CONFIG_PCM_S32BE_DEMUXER 0
-#define CONFIG_PCM_S32LE_DEMUXER 0
-#define CONFIG_PCM_S24BE_DEMUXER 0
-#define CONFIG_PCM_S24LE_DEMUXER 0
-#define CONFIG_PCM_S16BE_DEMUXER 0
-#define CONFIG_PCM_S16LE_DEMUXER 0
-#define CONFIG_PCM_S8_DEMUXER 0
-#define CONFIG_PCM_U32BE_DEMUXER 0
-#define CONFIG_PCM_U32LE_DEMUXER 0
-#define CONFIG_PCM_U24BE_DEMUXER 0
-#define CONFIG_PCM_U24LE_DEMUXER 0
-#define CONFIG_PCM_U16BE_DEMUXER 0
-#define CONFIG_PCM_U16LE_DEMUXER 0
-#define CONFIG_PCM_U8_DEMUXER 0
-#define CONFIG_PJS_DEMUXER 0
-#define CONFIG_PMP_DEMUXER 0
-#define CONFIG_PVA_DEMUXER 0
-#define CONFIG_PVF_DEMUXER 0
-#define CONFIG_QCP_DEMUXER 0
-#define CONFIG_R3D_DEMUXER 0
-#define CONFIG_RAWVIDEO_DEMUXER 0
-#define CONFIG_REALTEXT_DEMUXER 0
-#define CONFIG_REDSPARK_DEMUXER 0
-#define CONFIG_RL2_DEMUXER 0
-#define CONFIG_RM_DEMUXER 0
-#define CONFIG_ROQ_DEMUXER 0
-#define CONFIG_RPL_DEMUXER 0
-#define CONFIG_RSD_DEMUXER 0
-#define CONFIG_RSO_DEMUXER 0
-#define CONFIG_RTP_DEMUXER 0
-#define CONFIG_RTSP_DEMUXER 0
-#define CONFIG_SAMI_DEMUXER 0
-#define CONFIG_SAP_DEMUXER 0
-#define CONFIG_SBG_DEMUXER 0
-#define CONFIG_SDP_DEMUXER 0
-#define CONFIG_SDR2_DEMUXER 0
-#define CONFIG_SEGAFILM_DEMUXER 0
-#define CONFIG_SHORTEN_DEMUXER 0
-#define CONFIG_SIFF_DEMUXER 0
-#define CONFIG_SLN_DEMUXER 0
-#define CONFIG_SMACKER_DEMUXER 0
-#define CONFIG_SMJPEG_DEMUXER 0
-#define CONFIG_SMUSH_DEMUXER 0
-#define CONFIG_SOL_DEMUXER 0
-#define CONFIG_SOX_DEMUXER 0
-#define CONFIG_SPDIF_DEMUXER 0
-#define CONFIG_SRT_DEMUXER 0
-#define CONFIG_STR_DEMUXER 0
-#define CONFIG_STL_DEMUXER 0
-#define CONFIG_SUBVIEWER1_DEMUXER 0
-#define CONFIG_SUBVIEWER_DEMUXER 0
-#define CONFIG_SUP_DEMUXER 0
-#define CONFIG_SVAG_DEMUXER 0
-#define CONFIG_SWF_DEMUXER 0
-#define CONFIG_TAK_DEMUXER 0
-#define CONFIG_TEDCAPTIONS_DEMUXER 0
-#define CONFIG_THP_DEMUXER 0
-#define CONFIG_THREEDOSTR_DEMUXER 0
-#define CONFIG_TIERTEXSEQ_DEMUXER 0
-#define CONFIG_TMV_DEMUXER 0
-#define CONFIG_TRUEHD_DEMUXER 0
-#define CONFIG_TTA_DEMUXER 0
-#define CONFIG_TXD_DEMUXER 0
-#define CONFIG_TTY_DEMUXER 0
-#define CONFIG_V210_DEMUXER 0
-#define CONFIG_V210X_DEMUXER 0
-#define CONFIG_VAG_DEMUXER 0
-#define CONFIG_VC1_DEMUXER 0
-#define CONFIG_VC1T_DEMUXER 0
-#define CONFIG_VIVO_DEMUXER 0
-#define CONFIG_VMD_DEMUXER 0
-#define CONFIG_VOBSUB_DEMUXER 0
-#define CONFIG_VOC_DEMUXER 0
-#define CONFIG_VPK_DEMUXER 0
-#define CONFIG_VPLAYER_DEMUXER 0
-#define CONFIG_VQF_DEMUXER 0
-#define CONFIG_W64_DEMUXER 0
-#define CONFIG_WAV_DEMUXER 0
-#define CONFIG_WC3_DEMUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-#define CONFIG_WEBVTT_DEMUXER 0
-#define CONFIG_WSAUD_DEMUXER 0
-#define CONFIG_WSD_DEMUXER 0
-#define CONFIG_WSVQA_DEMUXER 0
-#define CONFIG_WTV_DEMUXER 0
-#define CONFIG_WVE_DEMUXER 0
-#define CONFIG_WV_DEMUXER 0
-#define CONFIG_XA_DEMUXER 0
-#define CONFIG_XBIN_DEMUXER 0
-#define CONFIG_XMV_DEMUXER 0
-#define CONFIG_XVAG_DEMUXER 0
-#define CONFIG_XWMA_DEMUXER 0
-#define CONFIG_YOP_DEMUXER 0
-#define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-#define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-#define CONFIG_LIBGME_DEMUXER 0
-#define CONFIG_LIBMODPLUG_DEMUXER 0
-#define CONFIG_LIBNUT_DEMUXER 0
-#define CONFIG_LIBOPENMPT_DEMUXER 0
-#define CONFIG_A64MULTI_ENCODER 0
-#define CONFIG_A64MULTI5_ENCODER 0
-#define CONFIG_ALIAS_PIX_ENCODER 0
-#define CONFIG_AMV_ENCODER 0
-#define CONFIG_APNG_ENCODER 0
-#define CONFIG_ASV1_ENCODER 0
-#define CONFIG_ASV2_ENCODER 0
-#define CONFIG_AVRP_ENCODER 0
-#define CONFIG_AVUI_ENCODER 0
-#define CONFIG_AYUV_ENCODER 0
-#define CONFIG_BMP_ENCODER 0
-#define CONFIG_CINEPAK_ENCODER 0
-#define CONFIG_CLJR_ENCODER 0
-#define CONFIG_COMFORTNOISE_ENCODER 0
-#define CONFIG_DNXHD_ENCODER 0
-#define CONFIG_DPX_ENCODER 0
-#define CONFIG_DVVIDEO_ENCODER 0
-#define CONFIG_FFV1_ENCODER 0
-#define CONFIG_FFVHUFF_ENCODER 0
-#define CONFIG_FLASHSV_ENCODER 0
-#define CONFIG_FLASHSV2_ENCODER 0
-#define CONFIG_FLV_ENCODER 0
-#define CONFIG_GIF_ENCODER 0
-#define CONFIG_H261_ENCODER 0
-#define CONFIG_H263_ENCODER 0
-#define CONFIG_H263P_ENCODER 0
-#define CONFIG_HAP_ENCODER 0
-#define CONFIG_HUFFYUV_ENCODER 0
-#define CONFIG_JPEG2000_ENCODER 0
-#define CONFIG_JPEGLS_ENCODER 0
-#define CONFIG_LJPEG_ENCODER 0
-#define CONFIG_MJPEG_ENCODER 0
-#define CONFIG_MPEG1VIDEO_ENCODER 0
-#define CONFIG_MPEG2VIDEO_ENCODER 0
-#define CONFIG_MPEG4_ENCODER 0
-#define CONFIG_MSMPEG4V2_ENCODER 0
-#define CONFIG_MSMPEG4V3_ENCODER 0
-#define CONFIG_MSVIDEO1_ENCODER 0
-#define CONFIG_PAM_ENCODER 0
-#define CONFIG_PBM_ENCODER 0
-#define CONFIG_PCX_ENCODER 0
-#define CONFIG_PGM_ENCODER 0
-#define CONFIG_PGMYUV_ENCODER 0
-#define CONFIG_PNG_ENCODER 0
-#define CONFIG_PPM_ENCODER 0
-#define CONFIG_PRORES_ENCODER 0
-#define CONFIG_PRORES_AW_ENCODER 0
-#define CONFIG_PRORES_KS_ENCODER 0
-#define CONFIG_QTRLE_ENCODER 0
-#define CONFIG_R10K_ENCODER 0
-#define CONFIG_R210_ENCODER 0
-#define CONFIG_RAWVIDEO_ENCODER 0
-#define CONFIG_ROQ_ENCODER 0
-#define CONFIG_RV10_ENCODER 0
-#define CONFIG_RV20_ENCODER 0
-#define CONFIG_S302M_ENCODER 0
-#define CONFIG_SGI_ENCODER 0
-#define CONFIG_SNOW_ENCODER 0
-#define CONFIG_SUNRAST_ENCODER 0
-#define CONFIG_SVQ1_ENCODER 0
-#define CONFIG_TARGA_ENCODER 0
-#define CONFIG_TIFF_ENCODER 0
-#define CONFIG_UTVIDEO_ENCODER 0
-#define CONFIG_V210_ENCODER 0
-#define CONFIG_V308_ENCODER 0
-#define CONFIG_V408_ENCODER 0
-#define CONFIG_V410_ENCODER 0
-#define CONFIG_VC2_ENCODER 0
-#define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-#define CONFIG_WMV1_ENCODER 0
-#define CONFIG_WMV2_ENCODER 0
-#define CONFIG_XBM_ENCODER 0
-#define CONFIG_XFACE_ENCODER 0
-#define CONFIG_XWD_ENCODER 0
-#define CONFIG_Y41P_ENCODER 0
-#define CONFIG_YUV4_ENCODER 0
-#define CONFIG_ZLIB_ENCODER 0
-#define CONFIG_ZMBV_ENCODER 0
-#define CONFIG_AAC_ENCODER 0
-#define CONFIG_AC3_ENCODER 0
-#define CONFIG_AC3_FIXED_ENCODER 0
-#define CONFIG_ALAC_ENCODER 0
-#define CONFIG_DCA_ENCODER 0
-#define CONFIG_EAC3_ENCODER 0
-#define CONFIG_FLAC_ENCODER 0
-#define CONFIG_G723_1_ENCODER 0
-#define CONFIG_MLP_ENCODER 0
-#define CONFIG_MP2_ENCODER 0
-#define CONFIG_MP2FIXED_ENCODER 0
-#define CONFIG_NELLYMOSER_ENCODER 0
-#define CONFIG_RA_144_ENCODER 0
-#define CONFIG_SONIC_ENCODER 0
-#define CONFIG_SONIC_LS_ENCODER 0
-#define CONFIG_TRUEHD_ENCODER 0
-#define CONFIG_TTA_ENCODER 0
-#define CONFIG_VORBIS_ENCODER 0
-#define CONFIG_WAVPACK_ENCODER 0
-#define CONFIG_WMAV1_ENCODER 0
-#define CONFIG_WMAV2_ENCODER 0
-#define CONFIG_PCM_ALAW_ENCODER 0
-#define CONFIG_PCM_F32BE_ENCODER 0
-#define CONFIG_PCM_F32LE_ENCODER 0
-#define CONFIG_PCM_F64BE_ENCODER 0
-#define CONFIG_PCM_F64LE_ENCODER 0
-#define CONFIG_PCM_MULAW_ENCODER 0
-#define CONFIG_PCM_S8_ENCODER 0
-#define CONFIG_PCM_S8_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16BE_ENCODER 0
-#define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16LE_ENCODER 0
-#define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S24BE_ENCODER 0
-#define CONFIG_PCM_S24DAUD_ENCODER 0
-#define CONFIG_PCM_S24LE_ENCODER 0
-#define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S32BE_ENCODER 0
-#define CONFIG_PCM_S32LE_ENCODER 0
-#define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S64BE_ENCODER 0
-#define CONFIG_PCM_S64LE_ENCODER 0
-#define CONFIG_PCM_U8_ENCODER 0
-#define CONFIG_PCM_U16BE_ENCODER 0
-#define CONFIG_PCM_U16LE_ENCODER 0
-#define CONFIG_PCM_U24BE_ENCODER 0
-#define CONFIG_PCM_U24LE_ENCODER 0
-#define CONFIG_PCM_U32BE_ENCODER 0
-#define CONFIG_PCM_U32LE_ENCODER 0
-#define CONFIG_ROQ_DPCM_ENCODER 0
-#define CONFIG_ADPCM_ADX_ENCODER 0
-#define CONFIG_ADPCM_G722_ENCODER 0
-#define CONFIG_ADPCM_G726_ENCODER 0
-#define CONFIG_ADPCM_IMA_QT_ENCODER 0
-#define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-#define CONFIG_ADPCM_MS_ENCODER 0
-#define CONFIG_ADPCM_SWF_ENCODER 0
-#define CONFIG_ADPCM_YAMAHA_ENCODER 0
-#define CONFIG_SSA_ENCODER 0
-#define CONFIG_ASS_ENCODER 0
-#define CONFIG_DVBSUB_ENCODER 0
-#define CONFIG_DVDSUB_ENCODER 0
-#define CONFIG_MOVTEXT_ENCODER 0
-#define CONFIG_SRT_ENCODER 0
-#define CONFIG_SUBRIP_ENCODER 0
-#define CONFIG_TEXT_ENCODER 0
-#define CONFIG_WEBVTT_ENCODER 0
-#define CONFIG_XSUB_ENCODER 0
-#define CONFIG_AAC_AT_ENCODER 0
-#define CONFIG_ALAC_AT_ENCODER 0
-#define CONFIG_ILBC_AT_ENCODER 0
-#define CONFIG_PCM_ALAW_AT_ENCODER 0
-#define CONFIG_PCM_MULAW_AT_ENCODER 0
-#define CONFIG_LIBFDK_AAC_ENCODER 0
-#define CONFIG_LIBGSM_ENCODER 0
-#define CONFIG_LIBGSM_MS_ENCODER 0
-#define CONFIG_LIBILBC_ENCODER 0
-#define CONFIG_LIBMP3LAME_ENCODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-#define CONFIG_LIBOPENJPEG_ENCODER 0
-#define CONFIG_LIBOPUS_ENCODER 0
-#define CONFIG_LIBSCHROEDINGER_ENCODER 0
-#define CONFIG_LIBSHINE_ENCODER 0
-#define CONFIG_LIBSPEEX_ENCODER 0
-#define CONFIG_LIBTHEORA_ENCODER 0
-#define CONFIG_LIBTWOLAME_ENCODER 0
-#define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-#define CONFIG_LIBVORBIS_ENCODER 0
-#define CONFIG_LIBVPX_VP8_ENCODER 0
-#define CONFIG_LIBVPX_VP9_ENCODER 0
-#define CONFIG_LIBWAVPACK_ENCODER 0
-#define CONFIG_LIBWEBP_ANIM_ENCODER 0
-#define CONFIG_LIBWEBP_ENCODER 0
-#define CONFIG_LIBX262_ENCODER 0
-#define CONFIG_LIBX264_ENCODER 0
-#define CONFIG_LIBX264RGB_ENCODER 0
-#define CONFIG_LIBX265_ENCODER 0
-#define CONFIG_LIBXAVS_ENCODER 0
-#define CONFIG_LIBXVID_ENCODER 0
-#define CONFIG_LIBOPENH264_ENCODER 0
-#define CONFIG_H264_NVENC_ENCODER 0
-#define CONFIG_H264_OMX_ENCODER 0
-#define CONFIG_H264_QSV_ENCODER 0
-#define CONFIG_H264_VAAPI_ENCODER 0
-#define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-#define CONFIG_NVENC_ENCODER 0
-#define CONFIG_NVENC_H264_ENCODER 0
-#define CONFIG_NVENC_HEVC_ENCODER 0
-#define CONFIG_HEVC_NVENC_ENCODER 0
-#define CONFIG_HEVC_QSV_ENCODER 0
-#define CONFIG_HEVC_VAAPI_ENCODER 0
-#define CONFIG_LIBKVAZAAR_ENCODER 0
-#define CONFIG_MJPEG_VAAPI_ENCODER 0
-#define CONFIG_MPEG2_QSV_ENCODER 0
-#define CONFIG_ABENCH_FILTER 0
-#define CONFIG_ACOMPRESSOR_FILTER 0
-#define CONFIG_ACROSSFADE_FILTER 0
-#define CONFIG_ACRUSHER_FILTER 0
-#define CONFIG_ADELAY_FILTER 0
-#define CONFIG_AECHO_FILTER 0
-#define CONFIG_AEMPHASIS_FILTER 0
-#define CONFIG_AEVAL_FILTER 0
-#define CONFIG_AFADE_FILTER 0
-#define CONFIG_AFFTFILT_FILTER 0
-#define CONFIG_AFORMAT_FILTER 0
-#define CONFIG_AGATE_FILTER 0
-#define CONFIG_AINTERLEAVE_FILTER 0
-#define CONFIG_ALIMITER_FILTER 0
-#define CONFIG_ALLPASS_FILTER 0
-#define CONFIG_ALOOP_FILTER 0
-#define CONFIG_AMERGE_FILTER 0
-#define CONFIG_AMETADATA_FILTER 0
-#define CONFIG_AMIX_FILTER 0
-#define CONFIG_ANEQUALIZER_FILTER 0
-#define CONFIG_ANULL_FILTER 0
-#define CONFIG_APAD_FILTER 0
-#define CONFIG_APERMS_FILTER 0
-#define CONFIG_APHASER_FILTER 0
-#define CONFIG_APULSATOR_FILTER 0
-#define CONFIG_AREALTIME_FILTER 0
-#define CONFIG_ARESAMPLE_FILTER 0
-#define CONFIG_AREVERSE_FILTER 0
-#define CONFIG_ASELECT_FILTER 0
-#define CONFIG_ASENDCMD_FILTER 0
-#define CONFIG_ASETNSAMPLES_FILTER 0
-#define CONFIG_ASETPTS_FILTER 0
-#define CONFIG_ASETRATE_FILTER 0
-#define CONFIG_ASETTB_FILTER 0
-#define CONFIG_ASHOWINFO_FILTER 0
-#define CONFIG_ASIDEDATA_FILTER 0
-#define CONFIG_ASPLIT_FILTER 0
-#define CONFIG_ASTATS_FILTER 0
-#define CONFIG_ASTREAMSELECT_FILTER 0
-#define CONFIG_ASYNCTS_FILTER 0
-#define CONFIG_ATEMPO_FILTER 0
-#define CONFIG_ATRIM_FILTER 0
-#define CONFIG_AZMQ_FILTER 0
-#define CONFIG_BANDPASS_FILTER 0
-#define CONFIG_BANDREJECT_FILTER 0
-#define CONFIG_BASS_FILTER 0
-#define CONFIG_BIQUAD_FILTER 0
-#define CONFIG_BS2B_FILTER 0
-#define CONFIG_CHANNELMAP_FILTER 0
-#define CONFIG_CHANNELSPLIT_FILTER 0
-#define CONFIG_CHORUS_FILTER 0
-#define CONFIG_COMPAND_FILTER 0
-#define CONFIG_COMPENSATIONDELAY_FILTER 0
-#define CONFIG_CRYSTALIZER_FILTER 0
-#define CONFIG_DCSHIFT_FILTER 0
-#define CONFIG_DYNAUDNORM_FILTER 0
-#define CONFIG_EARWAX_FILTER 0
-#define CONFIG_EBUR128_FILTER 0
-#define CONFIG_EQUALIZER_FILTER 0
-#define CONFIG_EXTRASTEREO_FILTER 0
-#define CONFIG_FIREQUALIZER_FILTER 0
-#define CONFIG_FLANGER_FILTER 0
-#define CONFIG_HDCD_FILTER 0
-#define CONFIG_HIGHPASS_FILTER 0
-#define CONFIG_JOIN_FILTER 0
-#define CONFIG_LADSPA_FILTER 0
-#define CONFIG_LOUDNORM_FILTER 0
-#define CONFIG_LOWPASS_FILTER 0
-#define CONFIG_PAN_FILTER 0
-#define CONFIG_REPLAYGAIN_FILTER 0
-#define CONFIG_RESAMPLE_FILTER 0
-#define CONFIG_RUBBERBAND_FILTER 0
-#define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-#define CONFIG_SIDECHAINGATE_FILTER 0
-#define CONFIG_SILENCEDETECT_FILTER 0
-#define CONFIG_SILENCEREMOVE_FILTER 0
-#define CONFIG_SOFALIZER_FILTER 0
-#define CONFIG_STEREOTOOLS_FILTER 0
-#define CONFIG_STEREOWIDEN_FILTER 0
-#define CONFIG_TREBLE_FILTER 0
-#define CONFIG_TREMOLO_FILTER 0
-#define CONFIG_VIBRATO_FILTER 0
-#define CONFIG_VOLUME_FILTER 0
-#define CONFIG_VOLUMEDETECT_FILTER 0
-#define CONFIG_AEVALSRC_FILTER 0
-#define CONFIG_ANOISESRC_FILTER 0
-#define CONFIG_ANULLSRC_FILTER 0
-#define CONFIG_FLITE_FILTER 0
-#define CONFIG_SINE_FILTER 0
-#define CONFIG_ANULLSINK_FILTER 0
-#define CONFIG_ALPHAEXTRACT_FILTER 0
-#define CONFIG_ALPHAMERGE_FILTER 0
-#define CONFIG_ASS_FILTER 0
-#define CONFIG_ATADENOISE_FILTER 0
-#define CONFIG_AVGBLUR_FILTER 0
-#define CONFIG_BBOX_FILTER 0
-#define CONFIG_BENCH_FILTER 0
-#define CONFIG_BITPLANENOISE_FILTER 0
-#define CONFIG_BLACKDETECT_FILTER 0
-#define CONFIG_BLACKFRAME_FILTER 0
-#define CONFIG_BLEND_FILTER 0
-#define CONFIG_BOXBLUR_FILTER 0
-#define CONFIG_BWDIF_FILTER 0
-#define CONFIG_CHROMAKEY_FILTER 0
-#define CONFIG_CIESCOPE_FILTER 0
-#define CONFIG_CODECVIEW_FILTER 0
-#define CONFIG_COLORBALANCE_FILTER 0
-#define CONFIG_COLORCHANNELMIXER_FILTER 0
-#define CONFIG_COLORKEY_FILTER 0
-#define CONFIG_COLORLEVELS_FILTER 0
-#define CONFIG_COLORMATRIX_FILTER 0
-#define CONFIG_COLORSPACE_FILTER 0
-#define CONFIG_CONVOLUTION_FILTER 0
-#define CONFIG_COPY_FILTER 0
-#define CONFIG_COREIMAGE_FILTER 0
-#define CONFIG_COVER_RECT_FILTER 0
-#define CONFIG_CROP_FILTER 0
-#define CONFIG_CROPDETECT_FILTER 0
-#define CONFIG_CURVES_FILTER 0
-#define CONFIG_DATASCOPE_FILTER 0
-#define CONFIG_DCTDNOIZ_FILTER 0
-#define CONFIG_DEBAND_FILTER 0
-#define CONFIG_DECIMATE_FILTER 0
-#define CONFIG_DEFLATE_FILTER 0
-#define CONFIG_DEJUDDER_FILTER 0
-#define CONFIG_DELOGO_FILTER 0
-#define CONFIG_DESHAKE_FILTER 0
-#define CONFIG_DETELECINE_FILTER 0
-#define CONFIG_DILATION_FILTER 0
-#define CONFIG_DISPLACE_FILTER 0
-#define CONFIG_DRAWBOX_FILTER 0
-#define CONFIG_DRAWGRAPH_FILTER 0
-#define CONFIG_DRAWGRID_FILTER 0
-#define CONFIG_DRAWTEXT_FILTER 0
-#define CONFIG_EDGEDETECT_FILTER 0
-#define CONFIG_ELBG_FILTER 0
-#define CONFIG_EQ_FILTER 0
-#define CONFIG_EROSION_FILTER 0
-#define CONFIG_EXTRACTPLANES_FILTER 0
-#define CONFIG_FADE_FILTER 0
-#define CONFIG_FFTFILT_FILTER 0
-#define CONFIG_FIELD_FILTER 0
-#define CONFIG_FIELDHINT_FILTER 0
-#define CONFIG_FIELDMATCH_FILTER 0
-#define CONFIG_FIELDORDER_FILTER 0
-#define CONFIG_FIND_RECT_FILTER 0
-#define CONFIG_FORMAT_FILTER 0
-#define CONFIG_FPS_FILTER 0
-#define CONFIG_FRAMEPACK_FILTER 0
-#define CONFIG_FRAMERATE_FILTER 0
-#define CONFIG_FRAMESTEP_FILTER 0
-#define CONFIG_FREI0R_FILTER 0
-#define CONFIG_FSPP_FILTER 0
-#define CONFIG_GBLUR_FILTER 0
-#define CONFIG_GEQ_FILTER 0
-#define CONFIG_GRADFUN_FILTER 0
-#define CONFIG_HALDCLUT_FILTER 0
-#define CONFIG_HFLIP_FILTER 0
-#define CONFIG_HISTEQ_FILTER 0
-#define CONFIG_HISTOGRAM_FILTER 0
-#define CONFIG_HQDN3D_FILTER 0
-#define CONFIG_HQX_FILTER 0
-#define CONFIG_HSTACK_FILTER 0
-#define CONFIG_HUE_FILTER 0
-#define CONFIG_HWDOWNLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_CUDA_FILTER 0
-#define CONFIG_HYSTERESIS_FILTER 0
-#define CONFIG_IDET_FILTER 0
-#define CONFIG_IL_FILTER 0
-#define CONFIG_INFLATE_FILTER 0
-#define CONFIG_INTERLACE_FILTER 0
-#define CONFIG_INTERLEAVE_FILTER 0
-#define CONFIG_KERNDEINT_FILTER 0
-#define CONFIG_LENSCORRECTION_FILTER 0
-#define CONFIG_LOOP_FILTER 0
-#define CONFIG_LUT_FILTER 0
-#define CONFIG_LUT2_FILTER 0
-#define CONFIG_LUT3D_FILTER 0
-#define CONFIG_LUTRGB_FILTER 0
-#define CONFIG_LUTYUV_FILTER 0
-#define CONFIG_MASKEDCLAMP_FILTER 0
-#define CONFIG_MASKEDMERGE_FILTER 0
-#define CONFIG_MCDEINT_FILTER 0
-#define CONFIG_MERGEPLANES_FILTER 0
-#define CONFIG_MESTIMATE_FILTER 0
-#define CONFIG_METADATA_FILTER 0
-#define CONFIG_MINTERPOLATE_FILTER 0
-#define CONFIG_MPDECIMATE_FILTER 0
-#define CONFIG_NEGATE_FILTER 0
-#define CONFIG_NLMEANS_FILTER 0
-#define CONFIG_NNEDI_FILTER 0
-#define CONFIG_NOFORMAT_FILTER 0
-#define CONFIG_NOISE_FILTER 0
-#define CONFIG_NULL_FILTER 0
-#define CONFIG_OCR_FILTER 0
-#define CONFIG_OCV_FILTER 0
-#define CONFIG_OVERLAY_FILTER 0
-#define CONFIG_OWDENOISE_FILTER 0
-#define CONFIG_PAD_FILTER 0
-#define CONFIG_PALETTEGEN_FILTER 0
-#define CONFIG_PALETTEUSE_FILTER 0
-#define CONFIG_PERMS_FILTER 0
-#define CONFIG_PERSPECTIVE_FILTER 0
-#define CONFIG_PHASE_FILTER 0
-#define CONFIG_PIXDESCTEST_FILTER 0
-#define CONFIG_PP_FILTER 0
-#define CONFIG_PP7_FILTER 0
-#define CONFIG_PREWITT_FILTER 0
-#define CONFIG_PSNR_FILTER 0
-#define CONFIG_PULLUP_FILTER 0
-#define CONFIG_QP_FILTER 0
-#define CONFIG_RANDOM_FILTER 0
-#define CONFIG_READVITC_FILTER 0
-#define CONFIG_REALTIME_FILTER 0
-#define CONFIG_REMAP_FILTER 0
-#define CONFIG_REMOVEGRAIN_FILTER 0
-#define CONFIG_REMOVELOGO_FILTER 0
-#define CONFIG_REPEATFIELDS_FILTER 0
-#define CONFIG_REVERSE_FILTER 0
-#define CONFIG_ROTATE_FILTER 0
-#define CONFIG_SAB_FILTER 0
-#define CONFIG_SCALE_FILTER 0
-#define CONFIG_SCALE_NPP_FILTER 0
-#define CONFIG_SCALE_VAAPI_FILTER 0
-#define CONFIG_SCALE2REF_FILTER 0
-#define CONFIG_SELECT_FILTER 0
-#define CONFIG_SELECTIVECOLOR_FILTER 0
-#define CONFIG_SENDCMD_FILTER 0
-#define CONFIG_SEPARATEFIELDS_FILTER 0
-#define CONFIG_SETDAR_FILTER 0
-#define CONFIG_SETFIELD_FILTER 0
-#define CONFIG_SETPTS_FILTER 0
-#define CONFIG_SETSAR_FILTER 0
-#define CONFIG_SETTB_FILTER 0
-#define CONFIG_SHOWINFO_FILTER 0
-#define CONFIG_SHOWPALETTE_FILTER 0
-#define CONFIG_SHUFFLEFRAMES_FILTER 0
-#define CONFIG_SHUFFLEPLANES_FILTER 0
-#define CONFIG_SIDEDATA_FILTER 0
-#define CONFIG_SIGNALSTATS_FILTER 0
-#define CONFIG_SMARTBLUR_FILTER 0
-#define CONFIG_SOBEL_FILTER 0
-#define CONFIG_SPLIT_FILTER 0
-#define CONFIG_SPP_FILTER 0
-#define CONFIG_SSIM_FILTER 0
-#define CONFIG_STEREO3D_FILTER 0
-#define CONFIG_STREAMSELECT_FILTER 0
-#define CONFIG_SUBTITLES_FILTER 0
-#define CONFIG_SUPER2XSAI_FILTER 0
-#define CONFIG_SWAPRECT_FILTER 0
-#define CONFIG_SWAPUV_FILTER 0
-#define CONFIG_TBLEND_FILTER 0
-#define CONFIG_TELECINE_FILTER 0
-#define CONFIG_THUMBNAIL_FILTER 0
-#define CONFIG_TILE_FILTER 0
-#define CONFIG_TINTERLACE_FILTER 0
-#define CONFIG_TRANSPOSE_FILTER 0
-#define CONFIG_TRIM_FILTER 0
-#define CONFIG_UNSHARP_FILTER 0
-#define CONFIG_USPP_FILTER 0
-#define CONFIG_VAGUEDENOISER_FILTER 0
-#define CONFIG_VECTORSCOPE_FILTER 0
-#define CONFIG_VFLIP_FILTER 0
-#define CONFIG_VIDSTABDETECT_FILTER 0
-#define CONFIG_VIDSTABTRANSFORM_FILTER 0
-#define CONFIG_VIGNETTE_FILTER 0
-#define CONFIG_VSTACK_FILTER 0
-#define CONFIG_W3FDIF_FILTER 0
-#define CONFIG_WAVEFORM_FILTER 0
-#define CONFIG_WEAVE_FILTER 0
-#define CONFIG_XBR_FILTER 0
-#define CONFIG_YADIF_FILTER 0
-#define CONFIG_ZMQ_FILTER 0
-#define CONFIG_ZOOMPAN_FILTER 0
-#define CONFIG_ZSCALE_FILTER 0
-#define CONFIG_ALLRGB_FILTER 0
-#define CONFIG_ALLYUV_FILTER 0
-#define CONFIG_CELLAUTO_FILTER 0
-#define CONFIG_COLOR_FILTER 0
-#define CONFIG_COREIMAGESRC_FILTER 0
-#define CONFIG_FREI0R_SRC_FILTER 0
-#define CONFIG_HALDCLUTSRC_FILTER 0
-#define CONFIG_LIFE_FILTER 0
-#define CONFIG_MANDELBROT_FILTER 0
-#define CONFIG_MPTESTSRC_FILTER 0
-#define CONFIG_NULLSRC_FILTER 0
-#define CONFIG_RGBTESTSRC_FILTER 0
-#define CONFIG_SMPTEBARS_FILTER 0
-#define CONFIG_SMPTEHDBARS_FILTER 0
-#define CONFIG_TESTSRC_FILTER 0
-#define CONFIG_TESTSRC2_FILTER 0
-#define CONFIG_YUVTESTSRC_FILTER 0
-#define CONFIG_NULLSINK_FILTER 0
-#define CONFIG_ADRAWGRAPH_FILTER 0
-#define CONFIG_AHISTOGRAM_FILTER 0
-#define CONFIG_APHASEMETER_FILTER 0
-#define CONFIG_AVECTORSCOPE_FILTER 0
-#define CONFIG_CONCAT_FILTER 0
-#define CONFIG_SHOWCQT_FILTER 0
-#define CONFIG_SHOWFREQS_FILTER 0
-#define CONFIG_SHOWSPECTRUM_FILTER 0
-#define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-#define CONFIG_SHOWVOLUME_FILTER 0
-#define CONFIG_SHOWWAVES_FILTER 0
-#define CONFIG_SHOWWAVESPIC_FILTER 0
-#define CONFIG_SPECTRUMSYNTH_FILTER 0
-#define CONFIG_AMOVIE_FILTER 0
-#define CONFIG_MOVIE_FILTER 0
-#define CONFIG_H263_CUVID_HWACCEL 0
-#define CONFIG_H263_VAAPI_HWACCEL 0
-#define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_H264_CUVID_HWACCEL 0
-#define CONFIG_H264_D3D11VA_HWACCEL 0
-#define CONFIG_H264_DXVA2_HWACCEL 0
-#define CONFIG_H264_MEDIACODEC_HWACCEL 0
-#define CONFIG_H264_MMAL_HWACCEL 0
-#define CONFIG_H264_QSV_HWACCEL 0
-#define CONFIG_H264_VAAPI_HWACCEL 0
-#define CONFIG_H264_VDA_HWACCEL 0
-#define CONFIG_H264_VDA_OLD_HWACCEL 0
-#define CONFIG_H264_VDPAU_HWACCEL 0
-#define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_HEVC_CUVID_HWACCEL 0
-#define CONFIG_HEVC_D3D11VA_HWACCEL 0
-#define CONFIG_HEVC_DXVA2_HWACCEL 0
-#define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-#define CONFIG_HEVC_QSV_HWACCEL 0
-#define CONFIG_HEVC_VAAPI_HWACCEL 0
-#define CONFIG_HEVC_VDPAU_HWACCEL 0
-#define CONFIG_MJPEG_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_XVMC_HWACCEL 0
-#define CONFIG_MPEG1_VDPAU_HWACCEL 0
-#define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG2_CUVID_HWACCEL 0
-#define CONFIG_MPEG2_XVMC_HWACCEL 0
-#define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-#define CONFIG_MPEG2_DXVA2_HWACCEL 0
-#define CONFIG_MPEG2_MMAL_HWACCEL 0
-#define CONFIG_MPEG2_QSV_HWACCEL 0
-#define CONFIG_MPEG2_VAAPI_HWACCEL 0
-#define CONFIG_MPEG2_VDPAU_HWACCEL 0
-#define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG4_CUVID_HWACCEL 0
-#define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-#define CONFIG_MPEG4_MMAL_HWACCEL 0
-#define CONFIG_MPEG4_VAAPI_HWACCEL 0
-#define CONFIG_MPEG4_VDPAU_HWACCEL 0
-#define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_VC1_CUVID_HWACCEL 0
-#define CONFIG_VC1_D3D11VA_HWACCEL 0
-#define CONFIG_VC1_DXVA2_HWACCEL 0
-#define CONFIG_VC1_VAAPI_HWACCEL 0
-#define CONFIG_VC1_VDPAU_HWACCEL 0
-#define CONFIG_VC1_MMAL_HWACCEL 0
-#define CONFIG_VC1_QSV_HWACCEL 0
-#define CONFIG_VP8_CUVID_HWACCEL 0
-#define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_CUVID_HWACCEL 0
-#define CONFIG_VP9_D3D11VA_HWACCEL 0
-#define CONFIG_VP9_DXVA2_HWACCEL 0
-#define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_D3D11VA_HWACCEL 0
-#define CONFIG_WMV3_DXVA2_HWACCEL 0
-#define CONFIG_WMV3_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_VDPAU_HWACCEL 0
-#define CONFIG_ALSA_INDEV 0
-#define CONFIG_AVFOUNDATION_INDEV 0
-#define CONFIG_BKTR_INDEV 0
-#define CONFIG_DECKLINK_INDEV 0
-#define CONFIG_DSHOW_INDEV 0
-#define CONFIG_DV1394_INDEV 0
-#define CONFIG_FBDEV_INDEV 0
-#define CONFIG_GDIGRAB_INDEV 0
-#define CONFIG_IEC61883_INDEV 0
-#define CONFIG_JACK_INDEV 0
-#define CONFIG_LAVFI_INDEV 0
-#define CONFIG_OPENAL_INDEV 0
-#define CONFIG_OSS_INDEV 0
-#define CONFIG_PULSE_INDEV 0
-#define CONFIG_QTKIT_INDEV 0
-#define CONFIG_SNDIO_INDEV 0
-#define CONFIG_V4L2_INDEV 0
-#define CONFIG_VFWCAP_INDEV 0
-#define CONFIG_X11GRAB_INDEV 0
-#define CONFIG_X11GRAB_XCB_INDEV 0
-#define CONFIG_LIBCDIO_INDEV 0
-#define CONFIG_LIBDC1394_INDEV 0
-#define CONFIG_A64_MUXER 0
-#define CONFIG_AC3_MUXER 0
-#define CONFIG_ADTS_MUXER 0
-#define CONFIG_ADX_MUXER 0
-#define CONFIG_AIFF_MUXER 0
-#define CONFIG_AMR_MUXER 0
-#define CONFIG_APNG_MUXER 0
-#define CONFIG_ASF_MUXER 0
-#define CONFIG_ASS_MUXER 0
-#define CONFIG_AST_MUXER 0
-#define CONFIG_ASF_STREAM_MUXER 0
-#define CONFIG_AU_MUXER 0
-#define CONFIG_AVI_MUXER 0
-#define CONFIG_AVM2_MUXER 0
-#define CONFIG_BIT_MUXER 0
-#define CONFIG_CAF_MUXER 0
-#define CONFIG_CAVSVIDEO_MUXER 0
-#define CONFIG_CRC_MUXER 0
-#define CONFIG_DASH_MUXER 0
-#define CONFIG_DATA_MUXER 0
-#define CONFIG_DAUD_MUXER 0
-#define CONFIG_DIRAC_MUXER 0
-#define CONFIG_DNXHD_MUXER 0
-#define CONFIG_DTS_MUXER 0
-#define CONFIG_DV_MUXER 0
-#define CONFIG_EAC3_MUXER 0
-#define CONFIG_F4V_MUXER 0
-#define CONFIG_FFM_MUXER 0
-#define CONFIG_FFMETADATA_MUXER 0
-#define CONFIG_FIFO_MUXER 0
-#define CONFIG_FILMSTRIP_MUXER 0
-#define CONFIG_FLAC_MUXER 0
-#define CONFIG_FLV_MUXER 0
-#define CONFIG_FRAMECRC_MUXER 0
-#define CONFIG_FRAMEHASH_MUXER 0
-#define CONFIG_FRAMEMD5_MUXER 0
-#define CONFIG_G722_MUXER 0
-#define CONFIG_G723_1_MUXER 0
-#define CONFIG_GIF_MUXER 0
-#define CONFIG_GSM_MUXER 0
-#define CONFIG_GXF_MUXER 0
-#define CONFIG_H261_MUXER 0
-#define CONFIG_H263_MUXER 0
-#define CONFIG_H264_MUXER 0
-#define CONFIG_HASH_MUXER 0
-#define CONFIG_HDS_MUXER 0
-#define CONFIG_HEVC_MUXER 0
-#define CONFIG_HLS_MUXER 0
-#define CONFIG_ICO_MUXER 0
-#define CONFIG_ILBC_MUXER 0
-#define CONFIG_IMAGE2_MUXER 0
-#define CONFIG_IMAGE2PIPE_MUXER 0
-#define CONFIG_IPOD_MUXER 0
-#define CONFIG_IRCAM_MUXER 0
-#define CONFIG_ISMV_MUXER 0
-#define CONFIG_IVF_MUXER 0
-#define CONFIG_JACOSUB_MUXER 0
-#define CONFIG_LATM_MUXER 0
-#define CONFIG_LRC_MUXER 0
-#define CONFIG_M4V_MUXER 0
-#define CONFIG_MD5_MUXER 0
-#define CONFIG_MATROSKA_MUXER 0
-#define CONFIG_MATROSKA_AUDIO_MUXER 0
-#define CONFIG_MICRODVD_MUXER 0
-#define CONFIG_MJPEG_MUXER 0
-#define CONFIG_MLP_MUXER 0
-#define CONFIG_MMF_MUXER 0
-#define CONFIG_MOV_MUXER 0
-#define CONFIG_MP2_MUXER 0
-#define CONFIG_MP3_MUXER 0
-#define CONFIG_MP4_MUXER 0
-#define CONFIG_MPEG1SYSTEM_MUXER 0
-#define CONFIG_MPEG1VCD_MUXER 0
-#define CONFIG_MPEG1VIDEO_MUXER 0
-#define CONFIG_MPEG2DVD_MUXER 0
-#define CONFIG_MPEG2SVCD_MUXER 0
-#define CONFIG_MPEG2VIDEO_MUXER 0
-#define CONFIG_MPEG2VOB_MUXER 0
-#define CONFIG_MPEGTS_MUXER 0
-#define CONFIG_MPJPEG_MUXER 0
-#define CONFIG_MXF_MUXER 0
-#define CONFIG_MXF_D10_MUXER 0
-#define CONFIG_MXF_OPATOM_MUXER 0
-#define CONFIG_NULL_MUXER 0
-#define CONFIG_NUT_MUXER 0
-#define CONFIG_OGA_MUXER 0
-#define CONFIG_OGG_MUXER 0
-#define CONFIG_OGV_MUXER 0
-#define CONFIG_OMA_MUXER 0
-#define CONFIG_OPUS_MUXER 0
-#define CONFIG_PCM_ALAW_MUXER 0
-#define CONFIG_PCM_MULAW_MUXER 0
-#define CONFIG_PCM_F64BE_MUXER 0
-#define CONFIG_PCM_F64LE_MUXER 0
-#define CONFIG_PCM_F32BE_MUXER 0
-#define CONFIG_PCM_F32LE_MUXER 0
-#define CONFIG_PCM_S32BE_MUXER 0
-#define CONFIG_PCM_S32LE_MUXER 0
-#define CONFIG_PCM_S24BE_MUXER 0
-#define CONFIG_PCM_S24LE_MUXER 0
-#define CONFIG_PCM_S16BE_MUXER 0
-#define CONFIG_PCM_S16LE_MUXER 0
-#define CONFIG_PCM_S8_MUXER 0
-#define CONFIG_PCM_U32BE_MUXER 0
-#define CONFIG_PCM_U32LE_MUXER 0
-#define CONFIG_PCM_U24BE_MUXER 0
-#define CONFIG_PCM_U24LE_MUXER 0
-#define CONFIG_PCM_U16BE_MUXER 0
-#define CONFIG_PCM_U16LE_MUXER 0
-#define CONFIG_PCM_U8_MUXER 0
-#define CONFIG_PSP_MUXER 0
-#define CONFIG_RAWVIDEO_MUXER 0
-#define CONFIG_RM_MUXER 0
-#define CONFIG_ROQ_MUXER 0
-#define CONFIG_RSO_MUXER 0
-#define CONFIG_RTP_MUXER 0
-#define CONFIG_RTP_MPEGTS_MUXER 0
-#define CONFIG_RTSP_MUXER 0
-#define CONFIG_SAP_MUXER 0
-#define CONFIG_SEGMENT_MUXER 0
-#define CONFIG_STREAM_SEGMENT_MUXER 0
-#define CONFIG_SINGLEJPEG_MUXER 0
-#define CONFIG_SMJPEG_MUXER 0
-#define CONFIG_SMOOTHSTREAMING_MUXER 0
-#define CONFIG_SOX_MUXER 0
-#define CONFIG_SPX_MUXER 0
-#define CONFIG_SPDIF_MUXER 0
-#define CONFIG_SRT_MUXER 0
-#define CONFIG_SWF_MUXER 0
-#define CONFIG_TEE_MUXER 0
-#define CONFIG_TG2_MUXER 0
-#define CONFIG_TGP_MUXER 0
-#define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-#define CONFIG_TRUEHD_MUXER 0
-#define CONFIG_TTA_MUXER 0
-#define CONFIG_UNCODEDFRAMECRC_MUXER 0
-#define CONFIG_VC1_MUXER 0
-#define CONFIG_VC1T_MUXER 0
-#define CONFIG_VOC_MUXER 0
-#define CONFIG_W64_MUXER 0
-#define CONFIG_WAV_MUXER 0
-#define CONFIG_WEBM_MUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-#define CONFIG_WEBM_CHUNK_MUXER 0
-#define CONFIG_WEBP_MUXER 0
-#define CONFIG_WEBVTT_MUXER 0
-#define CONFIG_WTV_MUXER 0
-#define CONFIG_WV_MUXER 0
-#define CONFIG_YUV4MPEGPIPE_MUXER 0
-#define CONFIG_CHROMAPRINT_MUXER 0
-#define CONFIG_LIBNUT_MUXER 0
-#define CONFIG_ALSA_OUTDEV 0
-#define CONFIG_CACA_OUTDEV 0
-#define CONFIG_DECKLINK_OUTDEV 0
-#define CONFIG_FBDEV_OUTDEV 0
-#define CONFIG_OPENGL_OUTDEV 0
-#define CONFIG_OSS_OUTDEV 0
-#define CONFIG_PULSE_OUTDEV 0
-#define CONFIG_SDL2_OUTDEV 0
-#define CONFIG_SNDIO_OUTDEV 0
-#define CONFIG_V4L2_OUTDEV 0
-#define CONFIG_XV_OUTDEV 0
-#define CONFIG_AAC_PARSER 0
-#define CONFIG_AAC_LATM_PARSER 0
-#define CONFIG_AC3_PARSER 0
-#define CONFIG_ADX_PARSER 0
-#define CONFIG_BMP_PARSER 0
-#define CONFIG_CAVSVIDEO_PARSER 0
-#define CONFIG_COOK_PARSER 0
-#define CONFIG_DCA_PARSER 0
-#define CONFIG_DIRAC_PARSER 0
-#define CONFIG_DNXHD_PARSER 0
-#define CONFIG_DPX_PARSER 0
-#define CONFIG_DVAUDIO_PARSER 0
-#define CONFIG_DVBSUB_PARSER 0
-#define CONFIG_DVDSUB_PARSER 0
-#define CONFIG_DVD_NAV_PARSER 0
-#define CONFIG_FLAC_PARSER 1
-#define CONFIG_G729_PARSER 0
-#define CONFIG_GSM_PARSER 0
-#define CONFIG_H261_PARSER 0
-#define CONFIG_H263_PARSER 0
-#define CONFIG_H264_PARSER 0
-#define CONFIG_HEVC_PARSER 0
-#define CONFIG_MJPEG_PARSER 0
-#define CONFIG_MLP_PARSER 0
-#define CONFIG_MPEG4VIDEO_PARSER 0
-#define CONFIG_MPEGAUDIO_PARSER 0
-#define CONFIG_MPEGVIDEO_PARSER 0
-#define CONFIG_OPUS_PARSER 0
-#define CONFIG_PNG_PARSER 0
-#define CONFIG_PNM_PARSER 0
-#define CONFIG_RV30_PARSER 0
-#define CONFIG_RV40_PARSER 0
-#define CONFIG_TAK_PARSER 0
-#define CONFIG_VC1_PARSER 0
-#define CONFIG_VORBIS_PARSER 0
-#define CONFIG_VP3_PARSER 0
+#define CONFIG_FLAC_PARSER 0
#define CONFIG_VP8_PARSER 1
#define CONFIG_VP9_PARSER 1
-#define CONFIG_ASYNC_PROTOCOL 0
-#define CONFIG_BLURAY_PROTOCOL 0
-#define CONFIG_CACHE_PROTOCOL 0
-#define CONFIG_CONCAT_PROTOCOL 0
-#define CONFIG_CRYPTO_PROTOCOL 0
-#define CONFIG_DATA_PROTOCOL 0
-#define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-#define CONFIG_FFRTMPHTTP_PROTOCOL 0
-#define CONFIG_FILE_PROTOCOL 0
-#define CONFIG_FTP_PROTOCOL 0
-#define CONFIG_GOPHER_PROTOCOL 0
-#define CONFIG_HLS_PROTOCOL 0
-#define CONFIG_HTTP_PROTOCOL 0
-#define CONFIG_HTTPPROXY_PROTOCOL 0
-#define CONFIG_HTTPS_PROTOCOL 0
-#define CONFIG_ICECAST_PROTOCOL 0
-#define CONFIG_MMSH_PROTOCOL 0
-#define CONFIG_MMST_PROTOCOL 0
-#define CONFIG_MD5_PROTOCOL 0
-#define CONFIG_PIPE_PROTOCOL 0
-#define CONFIG_RTMP_PROTOCOL 0
-#define CONFIG_RTMPE_PROTOCOL 0
-#define CONFIG_RTMPS_PROTOCOL 0
-#define CONFIG_RTMPT_PROTOCOL 0
-#define CONFIG_RTMPTE_PROTOCOL 0
-#define CONFIG_RTMPTS_PROTOCOL 0
-#define CONFIG_RTP_PROTOCOL 0
-#define CONFIG_SCTP_PROTOCOL 0
-#define CONFIG_SRTP_PROTOCOL 0
-#define CONFIG_SUBFILE_PROTOCOL 0
-#define CONFIG_TEE_PROTOCOL 0
-#define CONFIG_TCP_PROTOCOL 0
-#define CONFIG_TLS_GNUTLS_PROTOCOL 0
-#define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-#define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-#define CONFIG_TLS_OPENSSL_PROTOCOL 0
-#define CONFIG_UDP_PROTOCOL 0
-#define CONFIG_UDPLITE_PROTOCOL 0
-#define CONFIG_UNIX_PROTOCOL 0
-#define CONFIG_LIBRTMP_PROTOCOL 0
-#define CONFIG_LIBRTMPE_PROTOCOL 0
-#define CONFIG_LIBRTMPS_PROTOCOL 0
-#define CONFIG_LIBRTMPT_PROTOCOL 0
-#define CONFIG_LIBRTMPTE_PROTOCOL 0
-#define CONFIG_LIBSSH_PROTOCOL 0
-#define CONFIG_LIBSMBCLIENT_PROTOCOL 0
#endif /* FFMPEG_CONFIG_H */
diff --git a/media/ffvpx/config_unix64.asm b/media/ffvpx/config_unix64.asm
index 61cfce6a6..beb7f3b02 100644
--- a/media/ffvpx/config_unix64.asm
+++ b/media/ffvpx/config_unix64.asm
@@ -40,7 +40,7 @@
%define HAVE_AMD3DNOW 1
%define HAVE_AMD3DNOWEXT 1
%define HAVE_AVX 1
-%define HAVE_AVX2 0
+%define HAVE_AVX2 1
%define HAVE_FMA3 1
%define HAVE_FMA4 1
%define HAVE_MMX 1
@@ -63,8 +63,8 @@
%define HAVE_MIPSDSP 0
%define HAVE_MIPSDSPR2 0
%define HAVE_MSA 0
-%define HAVE_LOONGSON2 1
-%define HAVE_LOONGSON3 1
+%define HAVE_LOONGSON2 0
+%define HAVE_LOONGSON3 0
%define HAVE_MMI 0
%define HAVE_ARMV5TE_EXTERNAL 0
%define HAVE_ARMV6_EXTERNAL 0
@@ -84,7 +84,7 @@
%define HAVE_AMD3DNOW_EXTERNAL 1
%define HAVE_AMD3DNOWEXT_EXTERNAL 1
%define HAVE_AVX_EXTERNAL 1
-%define HAVE_AVX2_EXTERNAL 0
+%define HAVE_AVX2_EXTERNAL 1
%define HAVE_FMA3_EXTERNAL 1
%define HAVE_FMA4_EXTERNAL 1
%define HAVE_MMX_EXTERNAL 1
@@ -128,7 +128,7 @@
%define HAVE_AMD3DNOW_INLINE 1
%define HAVE_AMD3DNOWEXT_INLINE 1
%define HAVE_AVX_INLINE 1
-%define HAVE_AVX2_INLINE 0
+%define HAVE_AVX2_INLINE 1
%define HAVE_FMA3_INLINE 1
%define HAVE_FMA4_INLINE 1
%define HAVE_MMX_INLINE 1
@@ -162,11 +162,11 @@
%define HAVE_LOCAL_ALIGNED_16 1
%define HAVE_LOCAL_ALIGNED_32 1
%define HAVE_SIMD_ALIGN_16 1
+%define HAVE_SIMD_ALIGN_32 1
%define HAVE_ATOMICS_GCC 1
%define HAVE_ATOMICS_SUNCC 0
%define HAVE_ATOMICS_WIN32 0
%define HAVE_ATOMIC_CAS_PTR 0
-%define HAVE_ATOMIC_COMPARE_EXCHANGE 0
%define HAVE_MACHINE_RW_BARRIER 0
%define HAVE_MEMORYBARRIER 0
%define HAVE_MM_EMPTY 1
@@ -178,15 +178,16 @@
%define HAVE_CEXP 1
%define HAVE_INLINE_ASM 1
%define HAVE_SYMVER 1
-%define HAVE_YASM 1
+%define HAVE_X86ASM 1
%define HAVE_BIGENDIAN 0
%define HAVE_FAST_UNALIGNED 1
-%define HAVE_ALSA_ASOUNDLIB_H 0
%define HAVE_ALTIVEC_H 0
%define HAVE_ARPA_INET_H 1
%define HAVE_ASM_TYPES_H 1
%define HAVE_CDIO_PARANOIA_H 0
%define HAVE_CDIO_PARANOIA_PARANOIA_H 0
+%define HAVE_CUDA_H 0
+%define HAVE_D3D11_H 0
%define HAVE_DISPATCH_DISPATCH_H 0
%define HAVE_DEV_BKTR_IOCTL_BT848_H 0
%define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
@@ -196,7 +197,7 @@
%define HAVE_DIRECT_H 0
%define HAVE_DIRENT_H 1
%define HAVE_DLFCN_H 1
-%define HAVE_D3D11_H 0
+%define HAVE_DXGIDEBUG_H 0
%define HAVE_DXVA_H 0
%define HAVE_ES2_GL_H 0
%define HAVE_GSM_H 0
@@ -205,13 +206,15 @@
%define HAVE_MACHINE_IOCTL_BT848_H 0
%define HAVE_MACHINE_IOCTL_METEOR_H 0
%define HAVE_OPENCV2_CORE_CORE_C_H 0
+%define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+%define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
%define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
%define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
%define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
%define HAVE_OPENGL_GL3_H 0
%define HAVE_POLL_H 1
-%define HAVE_SNDIO_H 0
%define HAVE_SOUNDCARD_H 0
+%define HAVE_STDATOMIC_H 1
%define HAVE_SYS_MMAN_H 1
%define HAVE_SYS_PARAM_H 1
%define HAVE_SYS_RESOURCE_H 1
@@ -263,7 +266,6 @@
%define HAVE_COMMANDLINETOARGVW 0
%define HAVE_COTASKMEMFREE 0
%define HAVE_CRYPTGENRANDOM 0
-%define HAVE_DLOPEN 1
%define HAVE_FCNTL 1
%define HAVE_FLT_LIM 1
%define HAVE_FORK 1
@@ -311,11 +313,13 @@
%define HAVE_OS2THREADS 0
%define HAVE_W32THREADS 0
%define HAVE_AS_DN_DIRECTIVE 0
+%define HAVE_AS_FPU_DIRECTIVE 0
%define HAVE_AS_FUNC 0
%define HAVE_AS_OBJECT_ARCH 0
%define HAVE_ASM_MOD_Q 0
%define HAVE_ATTRIBUTE_MAY_ALIAS 1
%define HAVE_ATTRIBUTE_PACKED 1
+%define HAVE_BLOCKS_EXTENSION 0
%define HAVE_EBP_AVAILABLE 1
%define HAVE_EBX_AVAILABLE 1
%define HAVE_GNU_AS 0
@@ -332,6 +336,7 @@
%define HAVE_XFORM_ASM 0
%define HAVE_XMM_CLOBBERS 1
%define HAVE_CONDITION_VARIABLE_PTR 0
+%define HAVE_KCMVIDEOCODECTYPE_HEVC 0
%define HAVE_SOCKLEN_T 1
%define HAVE_STRUCT_ADDRINFO 1
%define HAVE_STRUCT_GROUP_SOURCE_REQ 1
@@ -348,36 +353,20 @@
%define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 1
%define HAVE_ATOMICS_NATIVE 1
%define HAVE_DOS_PATHS 0
-%define HAVE_DXVA2_LIB 0
-%define HAVE_DXVA2API_COBJ 0
%define HAVE_LIBC_MSVCRT 0
-%define HAVE_LIBDC1394_1 0
-%define HAVE_LIBDC1394_2 0
%define HAVE_MAKEINFO 0
%define HAVE_MAKEINFO_HTML 0
%define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
%define HAVE_PERL 1
%define HAVE_POD2MAN 1
-%define HAVE_SDL2 0
%define HAVE_SECTION_DATA_REL_RO 1
%define HAVE_TEXI2HTML 0
%define HAVE_THREADS 1
+%define HAVE_UWP 0
%define HAVE_VAAPI_DRM 0
%define HAVE_VAAPI_X11 0
%define HAVE_VDPAU_X11 0
%define HAVE_WINRT 0
-%define HAVE_XLIB 0
-%define CONFIG_BSFS 0
-%define CONFIG_DECODERS 1
-%define CONFIG_ENCODERS 0
-%define CONFIG_HWACCELS 0
-%define CONFIG_PARSERS 1
-%define CONFIG_INDEVS 0
-%define CONFIG_OUTDEVS 0
-%define CONFIG_FILTERS 0
-%define CONFIG_DEMUXERS 0
-%define CONFIG_MUXERS 0
-%define CONFIG_PROTOCOLS 0
%define CONFIG_DOC 0
%define CONFIG_HTMLPAGES 0
%define CONFIG_MANPAGES 1
@@ -385,13 +374,17 @@
%define CONFIG_TXTPAGES 0
%define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
%define CONFIG_AVIO_READING_EXAMPLE 1
-%define CONFIG_DECODING_ENCODING_EXAMPLE 0
+%define CONFIG_DECODE_AUDIO_EXAMPLE 1
+%define CONFIG_DECODE_VIDEO_EXAMPLE 1
%define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+%define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+%define CONFIG_ENCODE_VIDEO_EXAMPLE 1
%define CONFIG_EXTRACT_MVS_EXAMPLE 0
%define CONFIG_FILTER_AUDIO_EXAMPLE 0
%define CONFIG_FILTERING_AUDIO_EXAMPLE 0
%define CONFIG_FILTERING_VIDEO_EXAMPLE 0
%define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+%define CONFIG_HW_DECODE_EXAMPLE 0
%define CONFIG_METADATA_EXAMPLE 0
%define CONFIG_MUXING_EXAMPLE 0
%define CONFIG_QSVDEC_EXAMPLE 0
@@ -400,27 +393,55 @@
%define CONFIG_SCALING_VIDEO_EXAMPLE 0
%define CONFIG_TRANSCODE_AAC_EXAMPLE 0
%define CONFIG_TRANSCODING_EXAMPLE 0
-%define CONFIG_AVISYNTH 0
+%define CONFIG_ALSA 1
+%define CONFIG_APPKIT 0
+%define CONFIG_AVFOUNDATION 0
%define CONFIG_BZLIB 0
-%define CONFIG_CHROMAPRINT 0
-%define CONFIG_CRYSTALHD 0
-%define CONFIG_DECKLINK 0
+%define CONFIG_COREIMAGE 0
+%define CONFIG_ICONV 0
+%define CONFIG_JACK 0
+%define CONFIG_LIBXCB 0
+%define CONFIG_LIBXCB_SHM 0
+%define CONFIG_LIBXCB_SHAPE 0
+%define CONFIG_LIBXCB_XFIXES 0
+%define CONFIG_LZMA 1
+%define CONFIG_SCHANNEL 0
+%define CONFIG_SDL2 0
+%define CONFIG_SECURETRANSPORT 0
+%define CONFIG_SNDIO 0
+%define CONFIG_XLIB 1
+%define CONFIG_ZLIB 1
+%define CONFIG_AVISYNTH 0
%define CONFIG_FREI0R 0
-%define CONFIG_GCRYPT 0
+%define CONFIG_LIBCDIO 0
+%define CONFIG_LIBRUBBERBAND 0
+%define CONFIG_LIBVIDSTAB 0
+%define CONFIG_LIBX264 0
+%define CONFIG_LIBX265 0
+%define CONFIG_LIBXAVS 0
+%define CONFIG_LIBXVID 0
+%define CONFIG_DECKLINK 0
+%define CONFIG_LIBNDI_NEWTEK 0
+%define CONFIG_LIBFDK_AAC 0
+%define CONFIG_OPENSSL 0
%define CONFIG_GMP 0
+%define CONFIG_LIBOPENCORE_AMRNB 0
+%define CONFIG_LIBOPENCORE_AMRWB 0
+%define CONFIG_LIBVO_AMRWBENC 0
+%define CONFIG_RKMPP 0
+%define CONFIG_LIBSMBCLIENT 0
+%define CONFIG_CHROMAPRINT 0
+%define CONFIG_GCRYPT 0
%define CONFIG_GNUTLS 0
-%define CONFIG_ICONV 0
%define CONFIG_JNI 0
%define CONFIG_LADSPA 0
%define CONFIG_LIBASS 0
%define CONFIG_LIBBLURAY 0
%define CONFIG_LIBBS2B 0
%define CONFIG_LIBCACA 0
-%define CONFIG_LIBCDIO 0
%define CONFIG_LIBCELT 0
%define CONFIG_LIBDC1394 0
-%define CONFIG_LIBEBUR128 0
-%define CONFIG_LIBFDK_AAC 0
+%define CONFIG_LIBDRM 0
%define CONFIG_LIBFLITE 0
%define CONFIG_LIBFONTCONFIG 0
%define CONFIG_LIBFREETYPE 0
@@ -432,18 +453,15 @@
%define CONFIG_LIBKVAZAAR 0
%define CONFIG_LIBMODPLUG 0
%define CONFIG_LIBMP3LAME 0
-%define CONFIG_LIBNUT 0
-%define CONFIG_LIBOPENCORE_AMRNB 0
-%define CONFIG_LIBOPENCORE_AMRWB 0
+%define CONFIG_LIBMYSOFA 0
%define CONFIG_LIBOPENCV 0
%define CONFIG_LIBOPENH264 0
%define CONFIG_LIBOPENJPEG 0
%define CONFIG_LIBOPENMPT 0
%define CONFIG_LIBOPUS 0
%define CONFIG_LIBPULSE 0
+%define CONFIG_LIBRSVG 0
%define CONFIG_LIBRTMP 0
-%define CONFIG_LIBRUBBERBAND 0
-%define CONFIG_LIBSCHROEDINGER 0
%define CONFIG_LIBSHINE 0
%define CONFIG_LIBSMBCLIENT 0
%define CONFIG_LIBSNAPPY 0
@@ -454,53 +472,37 @@
%define CONFIG_LIBTHEORA 0
%define CONFIG_LIBTWOLAME 0
%define CONFIG_LIBV4L2 0
-%define CONFIG_LIBVIDSTAB 0
-%define CONFIG_LIBVO_AMRWBENC 0
+%define CONFIG_LIBVMAF 0
%define CONFIG_LIBVORBIS 0
%define CONFIG_LIBVPX 0
%define CONFIG_LIBWAVPACK 0
%define CONFIG_LIBWEBP 0
-%define CONFIG_LIBX264 0
-%define CONFIG_LIBX265 0
-%define CONFIG_LIBXAVS 0
-%define CONFIG_LIBXCB 0
-%define CONFIG_LIBXCB_SHM 0
-%define CONFIG_LIBXCB_SHAPE 0
-%define CONFIG_LIBXCB_XFIXES 0
-%define CONFIG_LIBXVID 0
+%define CONFIG_LIBXML2 0
%define CONFIG_LIBZIMG 0
%define CONFIG_LIBZMQ 0
%define CONFIG_LIBZVBI 0
-%define CONFIG_LZMA 0
%define CONFIG_MEDIACODEC 0
-%define CONFIG_NETCDF 0
%define CONFIG_OPENAL 0
%define CONFIG_OPENCL 0
%define CONFIG_OPENGL 0
-%define CONFIG_OPENSSL 0
-%define CONFIG_SCHANNEL 0
-%define CONFIG_SDL 0
-%define CONFIG_SDL2 0
-%define CONFIG_SECURETRANSPORT 0
-%define CONFIG_VIDEOTOOLBOX 0
-%define CONFIG_X11GRAB 0
-%define CONFIG_XLIB 0
-%define CONFIG_ZLIB 0
%define CONFIG_AUDIOTOOLBOX 0
-%define CONFIG_CUDA 0
-%define CONFIG_CUVID 0
+%define CONFIG_CRYSTALHD 0
+%define CONFIG_CUDA 1
+%define CONFIG_CUVID 1
%define CONFIG_D3D11VA 0
%define CONFIG_DXVA2 0
-%define CONFIG_LIBMFX 0
-%define CONFIG_LIBNPP 0
-%define CONFIG_MMAL 0
-%define CONFIG_NVENC 0
-%define CONFIG_OMX 0
+%define CONFIG_NVENC 1
%define CONFIG_VAAPI 0
%define CONFIG_VDA 0
%define CONFIG_VDPAU 0
-%define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_VIDEOTOOLBOX 0
+%define CONFIG_V4L2_M2M 1
%define CONFIG_XVMC 0
+%define CONFIG_CUDA_SDK 0
+%define CONFIG_LIBNPP 0
+%define CONFIG_LIBMFX 0
+%define CONFIG_MMAL 0
+%define CONFIG_OMX 0
%define CONFIG_FTRAPV 0
%define CONFIG_GRAY 0
%define CONFIG_HARDCODED_TABLES 0
@@ -539,16 +541,27 @@
%define CONFIG_PIXELUTILS 0
%define CONFIG_NETWORK 0
%define CONFIG_RDFT 0
+%define CONFIG_AUTODETECT 0
%define CONFIG_FONTCONFIG 0
-%define CONFIG_MEMALIGN_HACK 0
+%define CONFIG_LINUX_PERF 0
%define CONFIG_MEMORY_POISONING 0
%define CONFIG_NEON_CLOBBER_TEST 0
+%define CONFIG_OSSFUZZ 0
%define CONFIG_PIC 1
-%define CONFIG_POD2MAN 1
-%define CONFIG_RAISE_MAJOR 0
%define CONFIG_THUMB 0
%define CONFIG_VALGRIND_BACKTRACE 0
%define CONFIG_XMM_CLOBBER_TEST 0
+%define CONFIG_BSFS 1
+%define CONFIG_DECODERS 1
+%define CONFIG_ENCODERS 0
+%define CONFIG_HWACCELS 0
+%define CONFIG_PARSERS 1
+%define CONFIG_INDEVS 0
+%define CONFIG_OUTDEVS 0
+%define CONFIG_FILTERS 0
+%define CONFIG_DEMUXERS 0
+%define CONFIG_MUXERS 0
+%define CONFIG_PROTOCOLS 0
%define CONFIG_AANDCTTABLES 0
%define CONFIG_AC3DSP 0
%define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -566,20 +579,22 @@
%define CONFIG_FMTCONVERT 0
%define CONFIG_FRAME_THREAD_ENCODER 0
%define CONFIG_G722DSP 0
-%define CONFIG_GOLOMB 1
+%define CONFIG_GOLOMB 0
%define CONFIG_GPLV3 0
%define CONFIG_H263DSP 0
%define CONFIG_H264CHROMA 0
%define CONFIG_H264DSP 0
+%define CONFIG_H264PARSE 0
%define CONFIG_H264PRED 1
%define CONFIG_H264QPEL 0
+%define CONFIG_HEVCPARSE 0
%define CONFIG_HPELDSP 0
%define CONFIG_HUFFMAN 0
%define CONFIG_HUFFYUVDSP 0
%define CONFIG_HUFFYUVENCDSP 0
%define CONFIG_IDCTDSP 0
%define CONFIG_IIRFILTER 0
-%define CONFIG_IMDCT15 0
+%define CONFIG_MDCT15 0
%define CONFIG_INTRAX8 0
%define CONFIG_ISO_MEDIA 0
%define CONFIG_IVIDSP 0
@@ -588,12 +603,14 @@
%define CONFIG_LIBX262 0
%define CONFIG_LLAUDDSP 0
%define CONFIG_LLVIDDSP 0
+%define CONFIG_LLVIDENCDSP 0
%define CONFIG_LPC 0
%define CONFIG_LZF 0
%define CONFIG_ME_CMP 0
%define CONFIG_MPEG_ER 0
%define CONFIG_MPEGAUDIO 0
%define CONFIG_MPEGAUDIODSP 0
+%define CONFIG_MPEGAUDIOHEADER 0
%define CONFIG_MPEGVIDEO 0
%define CONFIG_MPEGVIDEOENC 0
%define CONFIG_MSS34DSP 0
@@ -615,1594 +632,19 @@
%define CONFIG_TEXTUREDSP 0
%define CONFIG_TEXTUREDSPENC 0
%define CONFIG_TPELDSP 0
+%define CONFIG_VAAPI_1 0
%define CONFIG_VAAPI_ENCODE 0
%define CONFIG_VC1DSP 0
%define CONFIG_VIDEODSP 1
%define CONFIG_VP3DSP 0
%define CONFIG_VP56DSP 0
%define CONFIG_VP8DSP 1
-%define CONFIG_VT_BT2020 0
%define CONFIG_WMA_FREQS 0
%define CONFIG_WMV2DSP 0
-%define CONFIG_AAC_ADTSTOASC_BSF 0
-%define CONFIG_CHOMP_BSF 0
-%define CONFIG_DUMP_EXTRADATA_BSF 0
-%define CONFIG_DCA_CORE_BSF 0
-%define CONFIG_H264_MP4TOANNEXB_BSF 0
-%define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-%define CONFIG_IMX_DUMP_HEADER_BSF 0
-%define CONFIG_MJPEG2JPEG_BSF 0
-%define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-%define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-%define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-%define CONFIG_MOV2TEXTSUB_BSF 0
-%define CONFIG_NOISE_BSF 0
-%define CONFIG_REMOVE_EXTRADATA_BSF 0
-%define CONFIG_TEXT2MOVSUB_BSF 0
-%define CONFIG_VP9_SUPERFRAME_BSF 0
-%define CONFIG_AASC_DECODER 0
-%define CONFIG_AIC_DECODER 0
-%define CONFIG_ALIAS_PIX_DECODER 0
-%define CONFIG_AMV_DECODER 0
-%define CONFIG_ANM_DECODER 0
-%define CONFIG_ANSI_DECODER 0
-%define CONFIG_APNG_DECODER 0
-%define CONFIG_ASV1_DECODER 0
-%define CONFIG_ASV2_DECODER 0
-%define CONFIG_AURA_DECODER 0
-%define CONFIG_AURA2_DECODER 0
-%define CONFIG_AVRP_DECODER 0
-%define CONFIG_AVRN_DECODER 0
-%define CONFIG_AVS_DECODER 0
-%define CONFIG_AVUI_DECODER 0
-%define CONFIG_AYUV_DECODER 0
-%define CONFIG_BETHSOFTVID_DECODER 0
-%define CONFIG_BFI_DECODER 0
-%define CONFIG_BINK_DECODER 0
-%define CONFIG_BMP_DECODER 0
-%define CONFIG_BMV_VIDEO_DECODER 0
-%define CONFIG_BRENDER_PIX_DECODER 0
-%define CONFIG_C93_DECODER 0
-%define CONFIG_CAVS_DECODER 0
-%define CONFIG_CDGRAPHICS_DECODER 0
-%define CONFIG_CDXL_DECODER 0
-%define CONFIG_CFHD_DECODER 0
-%define CONFIG_CINEPAK_DECODER 0
-%define CONFIG_CLJR_DECODER 0
-%define CONFIG_CLLC_DECODER 0
-%define CONFIG_COMFORTNOISE_DECODER 0
-%define CONFIG_CPIA_DECODER 0
-%define CONFIG_CSCD_DECODER 0
-%define CONFIG_CYUV_DECODER 0
-%define CONFIG_DDS_DECODER 0
-%define CONFIG_DFA_DECODER 0
-%define CONFIG_DIRAC_DECODER 0
-%define CONFIG_DNXHD_DECODER 0
-%define CONFIG_DPX_DECODER 0
-%define CONFIG_DSICINVIDEO_DECODER 0
-%define CONFIG_DVAUDIO_DECODER 0
-%define CONFIG_DVVIDEO_DECODER 0
-%define CONFIG_DXA_DECODER 0
-%define CONFIG_DXTORY_DECODER 0
-%define CONFIG_DXV_DECODER 0
-%define CONFIG_EACMV_DECODER 0
-%define CONFIG_EAMAD_DECODER 0
-%define CONFIG_EATGQ_DECODER 0
-%define CONFIG_EATGV_DECODER 0
-%define CONFIG_EATQI_DECODER 0
-%define CONFIG_EIGHTBPS_DECODER 0
-%define CONFIG_EIGHTSVX_EXP_DECODER 0
-%define CONFIG_EIGHTSVX_FIB_DECODER 0
-%define CONFIG_ESCAPE124_DECODER 0
-%define CONFIG_ESCAPE130_DECODER 0
-%define CONFIG_EXR_DECODER 0
-%define CONFIG_FFV1_DECODER 0
-%define CONFIG_FFVHUFF_DECODER 0
-%define CONFIG_FIC_DECODER 0
-%define CONFIG_FLASHSV_DECODER 0
-%define CONFIG_FLASHSV2_DECODER 0
-%define CONFIG_FLIC_DECODER 0
-%define CONFIG_FLV_DECODER 0
-%define CONFIG_FOURXM_DECODER 0
-%define CONFIG_FRAPS_DECODER 0
-%define CONFIG_FRWU_DECODER 0
-%define CONFIG_G2M_DECODER 0
-%define CONFIG_GIF_DECODER 0
-%define CONFIG_H261_DECODER 0
-%define CONFIG_H263_DECODER 0
-%define CONFIG_H263I_DECODER 0
-%define CONFIG_H263P_DECODER 0
-%define CONFIG_H264_DECODER 0
-%define CONFIG_H264_CRYSTALHD_DECODER 0
-%define CONFIG_H264_MEDIACODEC_DECODER 0
-%define CONFIG_H264_MMAL_DECODER 0
-%define CONFIG_H264_QSV_DECODER 0
-%define CONFIG_H264_VDA_DECODER 0
-%define CONFIG_H264_VDPAU_DECODER 0
-%define CONFIG_HAP_DECODER 0
-%define CONFIG_HEVC_DECODER 0
-%define CONFIG_HEVC_QSV_DECODER 0
-%define CONFIG_HNM4_VIDEO_DECODER 0
-%define CONFIG_HQ_HQA_DECODER 0
-%define CONFIG_HQX_DECODER 0
-%define CONFIG_HUFFYUV_DECODER 0
-%define CONFIG_IDCIN_DECODER 0
-%define CONFIG_IFF_ILBM_DECODER 0
-%define CONFIG_INDEO2_DECODER 0
-%define CONFIG_INDEO3_DECODER 0
-%define CONFIG_INDEO4_DECODER 0
-%define CONFIG_INDEO5_DECODER 0
-%define CONFIG_INTERPLAY_VIDEO_DECODER 0
-%define CONFIG_JPEG2000_DECODER 0
-%define CONFIG_JPEGLS_DECODER 0
-%define CONFIG_JV_DECODER 0
-%define CONFIG_KGV1_DECODER 0
-%define CONFIG_KMVC_DECODER 0
-%define CONFIG_LAGARITH_DECODER 0
-%define CONFIG_LOCO_DECODER 0
-%define CONFIG_M101_DECODER 0
-%define CONFIG_MAGICYUV_DECODER 0
-%define CONFIG_MDEC_DECODER 0
-%define CONFIG_MIMIC_DECODER 0
-%define CONFIG_MJPEG_DECODER 0
-%define CONFIG_MJPEGB_DECODER 0
-%define CONFIG_MMVIDEO_DECODER 0
-%define CONFIG_MOTIONPIXELS_DECODER 0
-%define CONFIG_MPEG_XVMC_DECODER 0
-%define CONFIG_MPEG1VIDEO_DECODER 0
-%define CONFIG_MPEG2VIDEO_DECODER 0
-%define CONFIG_MPEG4_DECODER 0
-%define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-%define CONFIG_MPEG4_MMAL_DECODER 0
-%define CONFIG_MPEG4_VDPAU_DECODER 0
-%define CONFIG_MPEGVIDEO_DECODER 0
-%define CONFIG_MPEG_VDPAU_DECODER 0
-%define CONFIG_MPEG1_VDPAU_DECODER 0
-%define CONFIG_MPEG2_MMAL_DECODER 0
-%define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-%define CONFIG_MPEG2_QSV_DECODER 0
-%define CONFIG_MSA1_DECODER 0
-%define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-%define CONFIG_MSMPEG4V1_DECODER 0
-%define CONFIG_MSMPEG4V2_DECODER 0
-%define CONFIG_MSMPEG4V3_DECODER 0
-%define CONFIG_MSRLE_DECODER 0
-%define CONFIG_MSS1_DECODER 0
-%define CONFIG_MSS2_DECODER 0
-%define CONFIG_MSVIDEO1_DECODER 0
-%define CONFIG_MSZH_DECODER 0
-%define CONFIG_MTS2_DECODER 0
-%define CONFIG_MVC1_DECODER 0
-%define CONFIG_MVC2_DECODER 0
-%define CONFIG_MXPEG_DECODER 0
-%define CONFIG_NUV_DECODER 0
-%define CONFIG_PAF_VIDEO_DECODER 0
-%define CONFIG_PAM_DECODER 0
-%define CONFIG_PBM_DECODER 0
-%define CONFIG_PCX_DECODER 0
-%define CONFIG_PGM_DECODER 0
-%define CONFIG_PGMYUV_DECODER 0
-%define CONFIG_PICTOR_DECODER 0
-%define CONFIG_PNG_DECODER 0
-%define CONFIG_PPM_DECODER 0
-%define CONFIG_PRORES_DECODER 0
-%define CONFIG_PRORES_LGPL_DECODER 0
-%define CONFIG_PTX_DECODER 0
-%define CONFIG_QDRAW_DECODER 0
-%define CONFIG_QPEG_DECODER 0
-%define CONFIG_QTRLE_DECODER 0
-%define CONFIG_R10K_DECODER 0
-%define CONFIG_R210_DECODER 0
-%define CONFIG_RAWVIDEO_DECODER 0
-%define CONFIG_RL2_DECODER 0
-%define CONFIG_ROQ_DECODER 0
-%define CONFIG_RPZA_DECODER 0
-%define CONFIG_RSCC_DECODER 0
-%define CONFIG_RV10_DECODER 0
-%define CONFIG_RV20_DECODER 0
-%define CONFIG_RV30_DECODER 0
-%define CONFIG_RV40_DECODER 0
-%define CONFIG_S302M_DECODER 0
-%define CONFIG_SANM_DECODER 0
-%define CONFIG_SCREENPRESSO_DECODER 0
-%define CONFIG_SDX2_DPCM_DECODER 0
-%define CONFIG_SGI_DECODER 0
-%define CONFIG_SGIRLE_DECODER 0
-%define CONFIG_SHEERVIDEO_DECODER 0
-%define CONFIG_SMACKER_DECODER 0
-%define CONFIG_SMC_DECODER 0
-%define CONFIG_SMVJPEG_DECODER 0
-%define CONFIG_SNOW_DECODER 0
-%define CONFIG_SP5X_DECODER 0
-%define CONFIG_SUNRAST_DECODER 0
-%define CONFIG_SVQ1_DECODER 0
-%define CONFIG_SVQ3_DECODER 0
-%define CONFIG_TARGA_DECODER 0
-%define CONFIG_TARGA_Y216_DECODER 0
-%define CONFIG_TDSC_DECODER 0
-%define CONFIG_THEORA_DECODER 0
-%define CONFIG_THP_DECODER 0
-%define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-%define CONFIG_TIFF_DECODER 0
-%define CONFIG_TMV_DECODER 0
-%define CONFIG_TRUEMOTION1_DECODER 0
-%define CONFIG_TRUEMOTION2_DECODER 0
-%define CONFIG_TRUEMOTION2RT_DECODER 0
-%define CONFIG_TSCC_DECODER 0
-%define CONFIG_TSCC2_DECODER 0
-%define CONFIG_TXD_DECODER 0
-%define CONFIG_ULTI_DECODER 0
-%define CONFIG_UTVIDEO_DECODER 0
-%define CONFIG_V210_DECODER 0
-%define CONFIG_V210X_DECODER 0
-%define CONFIG_V308_DECODER 0
-%define CONFIG_V408_DECODER 0
-%define CONFIG_V410_DECODER 0
-%define CONFIG_VB_DECODER 0
-%define CONFIG_VBLE_DECODER 0
-%define CONFIG_VC1_DECODER 0
-%define CONFIG_VC1_CRYSTALHD_DECODER 0
-%define CONFIG_VC1_VDPAU_DECODER 0
-%define CONFIG_VC1IMAGE_DECODER 0
-%define CONFIG_VC1_MMAL_DECODER 0
-%define CONFIG_VC1_QSV_DECODER 0
-%define CONFIG_VCR1_DECODER 0
-%define CONFIG_VMDVIDEO_DECODER 0
-%define CONFIG_VMNC_DECODER 0
-%define CONFIG_VP3_DECODER 0
-%define CONFIG_VP5_DECODER 0
-%define CONFIG_VP6_DECODER 0
-%define CONFIG_VP6A_DECODER 0
-%define CONFIG_VP6F_DECODER 0
-%define CONFIG_VP7_DECODER 0
+%define CONFIG_NULL_BSF 1
%define CONFIG_VP8_DECODER 1
%define CONFIG_VP9_DECODER 1
-%define CONFIG_VQA_DECODER 0
-%define CONFIG_WEBP_DECODER 0
-%define CONFIG_WMV1_DECODER 0
-%define CONFIG_WMV2_DECODER 0
-%define CONFIG_WMV3_DECODER 0
-%define CONFIG_WMV3_CRYSTALHD_DECODER 0
-%define CONFIG_WMV3_VDPAU_DECODER 0
-%define CONFIG_WMV3IMAGE_DECODER 0
-%define CONFIG_WNV1_DECODER 0
-%define CONFIG_XAN_WC3_DECODER 0
-%define CONFIG_XAN_WC4_DECODER 0
-%define CONFIG_XBM_DECODER 0
-%define CONFIG_XFACE_DECODER 0
-%define CONFIG_XL_DECODER 0
-%define CONFIG_XWD_DECODER 0
-%define CONFIG_Y41P_DECODER 0
-%define CONFIG_YLC_DECODER 0
-%define CONFIG_YOP_DECODER 0
-%define CONFIG_YUV4_DECODER 0
-%define CONFIG_ZERO12V_DECODER 0
-%define CONFIG_ZEROCODEC_DECODER 0
-%define CONFIG_ZLIB_DECODER 0
-%define CONFIG_ZMBV_DECODER 0
-%define CONFIG_AAC_DECODER 0
-%define CONFIG_AAC_FIXED_DECODER 0
-%define CONFIG_AAC_LATM_DECODER 0
-%define CONFIG_AC3_DECODER 0
-%define CONFIG_AC3_FIXED_DECODER 0
-%define CONFIG_ALAC_DECODER 0
-%define CONFIG_ALS_DECODER 0
-%define CONFIG_AMRNB_DECODER 0
-%define CONFIG_AMRWB_DECODER 0
-%define CONFIG_APE_DECODER 0
-%define CONFIG_ATRAC1_DECODER 0
-%define CONFIG_ATRAC3_DECODER 0
-%define CONFIG_ATRAC3P_DECODER 0
-%define CONFIG_BINKAUDIO_DCT_DECODER 0
-%define CONFIG_BINKAUDIO_RDFT_DECODER 0
-%define CONFIG_BMV_AUDIO_DECODER 0
-%define CONFIG_COOK_DECODER 0
-%define CONFIG_DCA_DECODER 0
-%define CONFIG_DSD_LSBF_DECODER 0
-%define CONFIG_DSD_MSBF_DECODER 0
-%define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-%define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-%define CONFIG_DSICINAUDIO_DECODER 0
-%define CONFIG_DSS_SP_DECODER 0
-%define CONFIG_DST_DECODER 0
-%define CONFIG_EAC3_DECODER 0
-%define CONFIG_EVRC_DECODER 0
-%define CONFIG_FFWAVESYNTH_DECODER 0
%define CONFIG_FLAC_DECODER 1
-%define CONFIG_G723_1_DECODER 0
-%define CONFIG_G729_DECODER 0
-%define CONFIG_GSM_DECODER 0
-%define CONFIG_GSM_MS_DECODER 0
-%define CONFIG_IAC_DECODER 0
-%define CONFIG_IMC_DECODER 0
-%define CONFIG_INTERPLAY_ACM_DECODER 0
-%define CONFIG_MACE3_DECODER 0
-%define CONFIG_MACE6_DECODER 0
-%define CONFIG_METASOUND_DECODER 0
-%define CONFIG_MLP_DECODER 0
-%define CONFIG_MP1_DECODER 0
-%define CONFIG_MP1FLOAT_DECODER 0
-%define CONFIG_MP2_DECODER 0
-%define CONFIG_MP2FLOAT_DECODER 0
-%define CONFIG_MP3_DECODER 0
-%define CONFIG_MP3FLOAT_DECODER 0
-%define CONFIG_MP3ADU_DECODER 0
-%define CONFIG_MP3ADUFLOAT_DECODER 0
-%define CONFIG_MP3ON4_DECODER 0
-%define CONFIG_MP3ON4FLOAT_DECODER 0
-%define CONFIG_MPC7_DECODER 0
-%define CONFIG_MPC8_DECODER 0
-%define CONFIG_NELLYMOSER_DECODER 0
-%define CONFIG_ON2AVC_DECODER 0
-%define CONFIG_OPUS_DECODER 0
-%define CONFIG_PAF_AUDIO_DECODER 0
-%define CONFIG_QCELP_DECODER 0
-%define CONFIG_QDM2_DECODER 0
-%define CONFIG_RA_144_DECODER 0
-%define CONFIG_RA_288_DECODER 0
-%define CONFIG_RALF_DECODER 0
-%define CONFIG_SHORTEN_DECODER 0
-%define CONFIG_SIPR_DECODER 0
-%define CONFIG_SMACKAUD_DECODER 0
-%define CONFIG_SONIC_DECODER 0
-%define CONFIG_TAK_DECODER 0
-%define CONFIG_TRUEHD_DECODER 0
-%define CONFIG_TRUESPEECH_DECODER 0
-%define CONFIG_TTA_DECODER 0
-%define CONFIG_TWINVQ_DECODER 0
-%define CONFIG_VMDAUDIO_DECODER 0
-%define CONFIG_VORBIS_DECODER 0
-%define CONFIG_WAVPACK_DECODER 0
-%define CONFIG_WMALOSSLESS_DECODER 0
-%define CONFIG_WMAPRO_DECODER 0
-%define CONFIG_WMAV1_DECODER 0
-%define CONFIG_WMAV2_DECODER 0
-%define CONFIG_WMAVOICE_DECODER 0
-%define CONFIG_WS_SND1_DECODER 0
-%define CONFIG_XMA1_DECODER 0
-%define CONFIG_XMA2_DECODER 0
-%define CONFIG_PCM_ALAW_DECODER 0
-%define CONFIG_PCM_BLURAY_DECODER 0
-%define CONFIG_PCM_DVD_DECODER 0
-%define CONFIG_PCM_F32BE_DECODER 0
-%define CONFIG_PCM_F32LE_DECODER 0
-%define CONFIG_PCM_F64BE_DECODER 0
-%define CONFIG_PCM_F64LE_DECODER 0
-%define CONFIG_PCM_LXF_DECODER 0
-%define CONFIG_PCM_MULAW_DECODER 0
-%define CONFIG_PCM_S8_DECODER 0
-%define CONFIG_PCM_S8_PLANAR_DECODER 0
-%define CONFIG_PCM_S16BE_DECODER 0
-%define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-%define CONFIG_PCM_S16LE_DECODER 0
-%define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S24BE_DECODER 0
-%define CONFIG_PCM_S24DAUD_DECODER 0
-%define CONFIG_PCM_S24LE_DECODER 0
-%define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S32BE_DECODER 0
-%define CONFIG_PCM_S32LE_DECODER 0
-%define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S64BE_DECODER 0
-%define CONFIG_PCM_S64LE_DECODER 0
-%define CONFIG_PCM_U8_DECODER 0
-%define CONFIG_PCM_U16BE_DECODER 0
-%define CONFIG_PCM_U16LE_DECODER 0
-%define CONFIG_PCM_U24BE_DECODER 0
-%define CONFIG_PCM_U24LE_DECODER 0
-%define CONFIG_PCM_U32BE_DECODER 0
-%define CONFIG_PCM_U32LE_DECODER 0
-%define CONFIG_PCM_ZORK_DECODER 0
-%define CONFIG_INTERPLAY_DPCM_DECODER 0
-%define CONFIG_ROQ_DPCM_DECODER 0
-%define CONFIG_SOL_DPCM_DECODER 0
-%define CONFIG_XAN_DPCM_DECODER 0
-%define CONFIG_ADPCM_4XM_DECODER 0
-%define CONFIG_ADPCM_ADX_DECODER 0
-%define CONFIG_ADPCM_AFC_DECODER 0
-%define CONFIG_ADPCM_AICA_DECODER 0
-%define CONFIG_ADPCM_CT_DECODER 0
-%define CONFIG_ADPCM_DTK_DECODER 0
-%define CONFIG_ADPCM_EA_DECODER 0
-%define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-%define CONFIG_ADPCM_EA_R1_DECODER 0
-%define CONFIG_ADPCM_EA_R2_DECODER 0
-%define CONFIG_ADPCM_EA_R3_DECODER 0
-%define CONFIG_ADPCM_EA_XAS_DECODER 0
-%define CONFIG_ADPCM_G722_DECODER 0
-%define CONFIG_ADPCM_G726_DECODER 0
-%define CONFIG_ADPCM_G726LE_DECODER 0
-%define CONFIG_ADPCM_IMA_AMV_DECODER 0
-%define CONFIG_ADPCM_IMA_APC_DECODER 0
-%define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-%define CONFIG_ADPCM_IMA_DK3_DECODER 0
-%define CONFIG_ADPCM_IMA_DK4_DECODER 0
-%define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-%define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-%define CONFIG_ADPCM_IMA_ISS_DECODER 0
-%define CONFIG_ADPCM_IMA_OKI_DECODER 0
-%define CONFIG_ADPCM_IMA_QT_DECODER 0
-%define CONFIG_ADPCM_IMA_RAD_DECODER 0
-%define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-%define CONFIG_ADPCM_IMA_WAV_DECODER 0
-%define CONFIG_ADPCM_IMA_WS_DECODER 0
-%define CONFIG_ADPCM_MS_DECODER 0
-%define CONFIG_ADPCM_MTAF_DECODER 0
-%define CONFIG_ADPCM_PSX_DECODER 0
-%define CONFIG_ADPCM_SBPRO_2_DECODER 0
-%define CONFIG_ADPCM_SBPRO_3_DECODER 0
-%define CONFIG_ADPCM_SBPRO_4_DECODER 0
-%define CONFIG_ADPCM_SWF_DECODER 0
-%define CONFIG_ADPCM_THP_DECODER 0
-%define CONFIG_ADPCM_THP_LE_DECODER 0
-%define CONFIG_ADPCM_VIMA_DECODER 0
-%define CONFIG_ADPCM_XA_DECODER 0
-%define CONFIG_ADPCM_YAMAHA_DECODER 0
-%define CONFIG_SSA_DECODER 0
-%define CONFIG_ASS_DECODER 0
-%define CONFIG_CCAPTION_DECODER 0
-%define CONFIG_DVBSUB_DECODER 0
-%define CONFIG_DVDSUB_DECODER 0
-%define CONFIG_JACOSUB_DECODER 0
-%define CONFIG_MICRODVD_DECODER 0
-%define CONFIG_MOVTEXT_DECODER 0
-%define CONFIG_MPL2_DECODER 0
-%define CONFIG_PGSSUB_DECODER 0
-%define CONFIG_PJS_DECODER 0
-%define CONFIG_REALTEXT_DECODER 0
-%define CONFIG_SAMI_DECODER 0
-%define CONFIG_SRT_DECODER 0
-%define CONFIG_STL_DECODER 0
-%define CONFIG_SUBRIP_DECODER 0
-%define CONFIG_SUBVIEWER_DECODER 0
-%define CONFIG_SUBVIEWER1_DECODER 0
-%define CONFIG_TEXT_DECODER 0
-%define CONFIG_VPLAYER_DECODER 0
-%define CONFIG_WEBVTT_DECODER 0
-%define CONFIG_XSUB_DECODER 0
-%define CONFIG_AAC_AT_DECODER 0
-%define CONFIG_AC3_AT_DECODER 0
-%define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-%define CONFIG_ALAC_AT_DECODER 0
-%define CONFIG_AMR_NB_AT_DECODER 0
-%define CONFIG_EAC3_AT_DECODER 0
-%define CONFIG_GSM_MS_AT_DECODER 0
-%define CONFIG_ILBC_AT_DECODER 0
-%define CONFIG_MP1_AT_DECODER 0
-%define CONFIG_MP2_AT_DECODER 0
-%define CONFIG_MP3_AT_DECODER 0
-%define CONFIG_PCM_ALAW_AT_DECODER 0
-%define CONFIG_PCM_MULAW_AT_DECODER 0
-%define CONFIG_QDMC_AT_DECODER 0
-%define CONFIG_QDM2_AT_DECODER 0
-%define CONFIG_LIBCELT_DECODER 0
-%define CONFIG_LIBFDK_AAC_DECODER 0
-%define CONFIG_LIBGSM_DECODER 0
-%define CONFIG_LIBGSM_MS_DECODER 0
-%define CONFIG_LIBILBC_DECODER 0
-%define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-%define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-%define CONFIG_LIBOPENJPEG_DECODER 0
-%define CONFIG_LIBOPUS_DECODER 0
-%define CONFIG_LIBSCHROEDINGER_DECODER 0
-%define CONFIG_LIBSPEEX_DECODER 0
-%define CONFIG_LIBVORBIS_DECODER 0
-%define CONFIG_LIBVPX_VP8_DECODER 0
-%define CONFIG_LIBVPX_VP9_DECODER 0
-%define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-%define CONFIG_BINTEXT_DECODER 0
-%define CONFIG_XBIN_DECODER 0
-%define CONFIG_IDF_DECODER 0
-%define CONFIG_LIBOPENH264_DECODER 0
-%define CONFIG_H263_CUVID_DECODER 0
-%define CONFIG_H264_CUVID_DECODER 0
-%define CONFIG_HEVC_CUVID_DECODER 0
-%define CONFIG_HEVC_MEDIACODEC_DECODER 0
-%define CONFIG_MJPEG_CUVID_DECODER 0
-%define CONFIG_MPEG1_CUVID_DECODER 0
-%define CONFIG_MPEG2_CUVID_DECODER 0
-%define CONFIG_MPEG4_CUVID_DECODER 0
-%define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-%define CONFIG_VC1_CUVID_DECODER 0
-%define CONFIG_VP8_CUVID_DECODER 0
-%define CONFIG_VP8_MEDIACODEC_DECODER 0
-%define CONFIG_VP9_CUVID_DECODER 0
-%define CONFIG_VP9_MEDIACODEC_DECODER 0
-%define CONFIG_AA_DEMUXER 0
-%define CONFIG_AAC_DEMUXER 0
-%define CONFIG_AC3_DEMUXER 0
-%define CONFIG_ACM_DEMUXER 0
-%define CONFIG_ACT_DEMUXER 0
-%define CONFIG_ADF_DEMUXER 0
-%define CONFIG_ADP_DEMUXER 0
-%define CONFIG_ADS_DEMUXER 0
-%define CONFIG_ADX_DEMUXER 0
-%define CONFIG_AEA_DEMUXER 0
-%define CONFIG_AFC_DEMUXER 0
-%define CONFIG_AIFF_DEMUXER 0
-%define CONFIG_AIX_DEMUXER 0
-%define CONFIG_AMR_DEMUXER 0
-%define CONFIG_ANM_DEMUXER 0
-%define CONFIG_APC_DEMUXER 0
-%define CONFIG_APE_DEMUXER 0
-%define CONFIG_APNG_DEMUXER 0
-%define CONFIG_AQTITLE_DEMUXER 0
-%define CONFIG_ASF_DEMUXER 0
-%define CONFIG_ASF_O_DEMUXER 0
-%define CONFIG_ASS_DEMUXER 0
-%define CONFIG_AST_DEMUXER 0
-%define CONFIG_AU_DEMUXER 0
-%define CONFIG_AVI_DEMUXER 0
-%define CONFIG_AVISYNTH_DEMUXER 0
-%define CONFIG_AVR_DEMUXER 0
-%define CONFIG_AVS_DEMUXER 0
-%define CONFIG_BETHSOFTVID_DEMUXER 0
-%define CONFIG_BFI_DEMUXER 0
-%define CONFIG_BINTEXT_DEMUXER 0
-%define CONFIG_BINK_DEMUXER 0
-%define CONFIG_BIT_DEMUXER 0
-%define CONFIG_BMV_DEMUXER 0
-%define CONFIG_BFSTM_DEMUXER 0
-%define CONFIG_BRSTM_DEMUXER 0
-%define CONFIG_BOA_DEMUXER 0
-%define CONFIG_C93_DEMUXER 0
-%define CONFIG_CAF_DEMUXER 0
-%define CONFIG_CAVSVIDEO_DEMUXER 0
-%define CONFIG_CDG_DEMUXER 0
-%define CONFIG_CDXL_DEMUXER 0
-%define CONFIG_CINE_DEMUXER 0
-%define CONFIG_CONCAT_DEMUXER 0
-%define CONFIG_DATA_DEMUXER 0
-%define CONFIG_DAUD_DEMUXER 0
-%define CONFIG_DCSTR_DEMUXER 0
-%define CONFIG_DFA_DEMUXER 0
-%define CONFIG_DIRAC_DEMUXER 0
-%define CONFIG_DNXHD_DEMUXER 0
-%define CONFIG_DSF_DEMUXER 0
-%define CONFIG_DSICIN_DEMUXER 0
-%define CONFIG_DSS_DEMUXER 0
-%define CONFIG_DTS_DEMUXER 0
-%define CONFIG_DTSHD_DEMUXER 0
-%define CONFIG_DV_DEMUXER 0
-%define CONFIG_DVBSUB_DEMUXER 0
-%define CONFIG_DVBTXT_DEMUXER 0
-%define CONFIG_DXA_DEMUXER 0
-%define CONFIG_EA_DEMUXER 0
-%define CONFIG_EA_CDATA_DEMUXER 0
-%define CONFIG_EAC3_DEMUXER 0
-%define CONFIG_EPAF_DEMUXER 0
-%define CONFIG_FFM_DEMUXER 0
-%define CONFIG_FFMETADATA_DEMUXER 0
-%define CONFIG_FILMSTRIP_DEMUXER 0
-%define CONFIG_FLAC_DEMUXER 0
-%define CONFIG_FLIC_DEMUXER 0
-%define CONFIG_FLV_DEMUXER 0
-%define CONFIG_LIVE_FLV_DEMUXER 0
-%define CONFIG_FOURXM_DEMUXER 0
-%define CONFIG_FRM_DEMUXER 0
-%define CONFIG_FSB_DEMUXER 0
-%define CONFIG_G722_DEMUXER 0
-%define CONFIG_G723_1_DEMUXER 0
-%define CONFIG_G729_DEMUXER 0
-%define CONFIG_GENH_DEMUXER 0
-%define CONFIG_GIF_DEMUXER 0
-%define CONFIG_GSM_DEMUXER 0
-%define CONFIG_GXF_DEMUXER 0
-%define CONFIG_H261_DEMUXER 0
-%define CONFIG_H263_DEMUXER 0
-%define CONFIG_H264_DEMUXER 0
-%define CONFIG_HEVC_DEMUXER 0
-%define CONFIG_HLS_DEMUXER 0
-%define CONFIG_HNM_DEMUXER 0
-%define CONFIG_ICO_DEMUXER 0
-%define CONFIG_IDCIN_DEMUXER 0
-%define CONFIG_IDF_DEMUXER 0
-%define CONFIG_IFF_DEMUXER 0
-%define CONFIG_ILBC_DEMUXER 0
-%define CONFIG_IMAGE2_DEMUXER 0
-%define CONFIG_IMAGE2PIPE_DEMUXER 0
-%define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-%define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-%define CONFIG_INGENIENT_DEMUXER 0
-%define CONFIG_IPMOVIE_DEMUXER 0
-%define CONFIG_IRCAM_DEMUXER 0
-%define CONFIG_ISS_DEMUXER 0
-%define CONFIG_IV8_DEMUXER 0
-%define CONFIG_IVF_DEMUXER 0
-%define CONFIG_IVR_DEMUXER 0
-%define CONFIG_JACOSUB_DEMUXER 0
-%define CONFIG_JV_DEMUXER 0
-%define CONFIG_LMLM4_DEMUXER 0
-%define CONFIG_LOAS_DEMUXER 0
-%define CONFIG_LRC_DEMUXER 0
-%define CONFIG_LVF_DEMUXER 0
-%define CONFIG_LXF_DEMUXER 0
-%define CONFIG_M4V_DEMUXER 0
-%define CONFIG_MATROSKA_DEMUXER 0
-%define CONFIG_MGSTS_DEMUXER 0
-%define CONFIG_MICRODVD_DEMUXER 0
-%define CONFIG_MJPEG_DEMUXER 0
-%define CONFIG_MLP_DEMUXER 0
-%define CONFIG_MLV_DEMUXER 0
-%define CONFIG_MM_DEMUXER 0
-%define CONFIG_MMF_DEMUXER 0
-%define CONFIG_MOV_DEMUXER 0
-%define CONFIG_MP3_DEMUXER 0
-%define CONFIG_MPC_DEMUXER 0
-%define CONFIG_MPC8_DEMUXER 0
-%define CONFIG_MPEGPS_DEMUXER 0
-%define CONFIG_MPEGTS_DEMUXER 0
-%define CONFIG_MPEGTSRAW_DEMUXER 0
-%define CONFIG_MPEGVIDEO_DEMUXER 0
-%define CONFIG_MPJPEG_DEMUXER 0
-%define CONFIG_MPL2_DEMUXER 0
-%define CONFIG_MPSUB_DEMUXER 0
-%define CONFIG_MSF_DEMUXER 0
-%define CONFIG_MSNWC_TCP_DEMUXER 0
-%define CONFIG_MTAF_DEMUXER 0
-%define CONFIG_MTV_DEMUXER 0
-%define CONFIG_MUSX_DEMUXER 0
-%define CONFIG_MV_DEMUXER 0
-%define CONFIG_MVI_DEMUXER 0
-%define CONFIG_MXF_DEMUXER 0
-%define CONFIG_MXG_DEMUXER 0
-%define CONFIG_NC_DEMUXER 0
-%define CONFIG_NISTSPHERE_DEMUXER 0
-%define CONFIG_NSV_DEMUXER 0
-%define CONFIG_NUT_DEMUXER 0
-%define CONFIG_NUV_DEMUXER 0
-%define CONFIG_OGG_DEMUXER 0
-%define CONFIG_OMA_DEMUXER 0
-%define CONFIG_PAF_DEMUXER 0
-%define CONFIG_PCM_ALAW_DEMUXER 0
-%define CONFIG_PCM_MULAW_DEMUXER 0
-%define CONFIG_PCM_F64BE_DEMUXER 0
-%define CONFIG_PCM_F64LE_DEMUXER 0
-%define CONFIG_PCM_F32BE_DEMUXER 0
-%define CONFIG_PCM_F32LE_DEMUXER 0
-%define CONFIG_PCM_S32BE_DEMUXER 0
-%define CONFIG_PCM_S32LE_DEMUXER 0
-%define CONFIG_PCM_S24BE_DEMUXER 0
-%define CONFIG_PCM_S24LE_DEMUXER 0
-%define CONFIG_PCM_S16BE_DEMUXER 0
-%define CONFIG_PCM_S16LE_DEMUXER 0
-%define CONFIG_PCM_S8_DEMUXER 0
-%define CONFIG_PCM_U32BE_DEMUXER 0
-%define CONFIG_PCM_U32LE_DEMUXER 0
-%define CONFIG_PCM_U24BE_DEMUXER 0
-%define CONFIG_PCM_U24LE_DEMUXER 0
-%define CONFIG_PCM_U16BE_DEMUXER 0
-%define CONFIG_PCM_U16LE_DEMUXER 0
-%define CONFIG_PCM_U8_DEMUXER 0
-%define CONFIG_PJS_DEMUXER 0
-%define CONFIG_PMP_DEMUXER 0
-%define CONFIG_PVA_DEMUXER 0
-%define CONFIG_PVF_DEMUXER 0
-%define CONFIG_QCP_DEMUXER 0
-%define CONFIG_R3D_DEMUXER 0
-%define CONFIG_RAWVIDEO_DEMUXER 0
-%define CONFIG_REALTEXT_DEMUXER 0
-%define CONFIG_REDSPARK_DEMUXER 0
-%define CONFIG_RL2_DEMUXER 0
-%define CONFIG_RM_DEMUXER 0
-%define CONFIG_ROQ_DEMUXER 0
-%define CONFIG_RPL_DEMUXER 0
-%define CONFIG_RSD_DEMUXER 0
-%define CONFIG_RSO_DEMUXER 0
-%define CONFIG_RTP_DEMUXER 0
-%define CONFIG_RTSP_DEMUXER 0
-%define CONFIG_SAMI_DEMUXER 0
-%define CONFIG_SAP_DEMUXER 0
-%define CONFIG_SBG_DEMUXER 0
-%define CONFIG_SDP_DEMUXER 0
-%define CONFIG_SDR2_DEMUXER 0
-%define CONFIG_SEGAFILM_DEMUXER 0
-%define CONFIG_SHORTEN_DEMUXER 0
-%define CONFIG_SIFF_DEMUXER 0
-%define CONFIG_SLN_DEMUXER 0
-%define CONFIG_SMACKER_DEMUXER 0
-%define CONFIG_SMJPEG_DEMUXER 0
-%define CONFIG_SMUSH_DEMUXER 0
-%define CONFIG_SOL_DEMUXER 0
-%define CONFIG_SOX_DEMUXER 0
-%define CONFIG_SPDIF_DEMUXER 0
-%define CONFIG_SRT_DEMUXER 0
-%define CONFIG_STR_DEMUXER 0
-%define CONFIG_STL_DEMUXER 0
-%define CONFIG_SUBVIEWER1_DEMUXER 0
-%define CONFIG_SUBVIEWER_DEMUXER 0
-%define CONFIG_SUP_DEMUXER 0
-%define CONFIG_SVAG_DEMUXER 0
-%define CONFIG_SWF_DEMUXER 0
-%define CONFIG_TAK_DEMUXER 0
-%define CONFIG_TEDCAPTIONS_DEMUXER 0
-%define CONFIG_THP_DEMUXER 0
-%define CONFIG_THREEDOSTR_DEMUXER 0
-%define CONFIG_TIERTEXSEQ_DEMUXER 0
-%define CONFIG_TMV_DEMUXER 0
-%define CONFIG_TRUEHD_DEMUXER 0
-%define CONFIG_TTA_DEMUXER 0
-%define CONFIG_TXD_DEMUXER 0
-%define CONFIG_TTY_DEMUXER 0
-%define CONFIG_V210_DEMUXER 0
-%define CONFIG_V210X_DEMUXER 0
-%define CONFIG_VAG_DEMUXER 0
-%define CONFIG_VC1_DEMUXER 0
-%define CONFIG_VC1T_DEMUXER 0
-%define CONFIG_VIVO_DEMUXER 0
-%define CONFIG_VMD_DEMUXER 0
-%define CONFIG_VOBSUB_DEMUXER 0
-%define CONFIG_VOC_DEMUXER 0
-%define CONFIG_VPK_DEMUXER 0
-%define CONFIG_VPLAYER_DEMUXER 0
-%define CONFIG_VQF_DEMUXER 0
-%define CONFIG_W64_DEMUXER 0
-%define CONFIG_WAV_DEMUXER 0
-%define CONFIG_WC3_DEMUXER 0
-%define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-%define CONFIG_WEBVTT_DEMUXER 0
-%define CONFIG_WSAUD_DEMUXER 0
-%define CONFIG_WSD_DEMUXER 0
-%define CONFIG_WSVQA_DEMUXER 0
-%define CONFIG_WTV_DEMUXER 0
-%define CONFIG_WVE_DEMUXER 0
-%define CONFIG_WV_DEMUXER 0
-%define CONFIG_XA_DEMUXER 0
-%define CONFIG_XBIN_DEMUXER 0
-%define CONFIG_XMV_DEMUXER 0
-%define CONFIG_XVAG_DEMUXER 0
-%define CONFIG_XWMA_DEMUXER 0
-%define CONFIG_YOP_DEMUXER 0
-%define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-%define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-%define CONFIG_LIBGME_DEMUXER 0
-%define CONFIG_LIBMODPLUG_DEMUXER 0
-%define CONFIG_LIBNUT_DEMUXER 0
-%define CONFIG_LIBOPENMPT_DEMUXER 0
-%define CONFIG_A64MULTI_ENCODER 0
-%define CONFIG_A64MULTI5_ENCODER 0
-%define CONFIG_ALIAS_PIX_ENCODER 0
-%define CONFIG_AMV_ENCODER 0
-%define CONFIG_APNG_ENCODER 0
-%define CONFIG_ASV1_ENCODER 0
-%define CONFIG_ASV2_ENCODER 0
-%define CONFIG_AVRP_ENCODER 0
-%define CONFIG_AVUI_ENCODER 0
-%define CONFIG_AYUV_ENCODER 0
-%define CONFIG_BMP_ENCODER 0
-%define CONFIG_CINEPAK_ENCODER 0
-%define CONFIG_CLJR_ENCODER 0
-%define CONFIG_COMFORTNOISE_ENCODER 0
-%define CONFIG_DNXHD_ENCODER 0
-%define CONFIG_DPX_ENCODER 0
-%define CONFIG_DVVIDEO_ENCODER 0
-%define CONFIG_FFV1_ENCODER 0
-%define CONFIG_FFVHUFF_ENCODER 0
-%define CONFIG_FLASHSV_ENCODER 0
-%define CONFIG_FLASHSV2_ENCODER 0
-%define CONFIG_FLV_ENCODER 0
-%define CONFIG_GIF_ENCODER 0
-%define CONFIG_H261_ENCODER 0
-%define CONFIG_H263_ENCODER 0
-%define CONFIG_H263P_ENCODER 0
-%define CONFIG_HAP_ENCODER 0
-%define CONFIG_HUFFYUV_ENCODER 0
-%define CONFIG_JPEG2000_ENCODER 0
-%define CONFIG_JPEGLS_ENCODER 0
-%define CONFIG_LJPEG_ENCODER 0
-%define CONFIG_MJPEG_ENCODER 0
-%define CONFIG_MPEG1VIDEO_ENCODER 0
-%define CONFIG_MPEG2VIDEO_ENCODER 0
-%define CONFIG_MPEG4_ENCODER 0
-%define CONFIG_MSMPEG4V2_ENCODER 0
-%define CONFIG_MSMPEG4V3_ENCODER 0
-%define CONFIG_MSVIDEO1_ENCODER 0
-%define CONFIG_PAM_ENCODER 0
-%define CONFIG_PBM_ENCODER 0
-%define CONFIG_PCX_ENCODER 0
-%define CONFIG_PGM_ENCODER 0
-%define CONFIG_PGMYUV_ENCODER 0
-%define CONFIG_PNG_ENCODER 0
-%define CONFIG_PPM_ENCODER 0
-%define CONFIG_PRORES_ENCODER 0
-%define CONFIG_PRORES_AW_ENCODER 0
-%define CONFIG_PRORES_KS_ENCODER 0
-%define CONFIG_QTRLE_ENCODER 0
-%define CONFIG_R10K_ENCODER 0
-%define CONFIG_R210_ENCODER 0
-%define CONFIG_RAWVIDEO_ENCODER 0
-%define CONFIG_ROQ_ENCODER 0
-%define CONFIG_RV10_ENCODER 0
-%define CONFIG_RV20_ENCODER 0
-%define CONFIG_S302M_ENCODER 0
-%define CONFIG_SGI_ENCODER 0
-%define CONFIG_SNOW_ENCODER 0
-%define CONFIG_SUNRAST_ENCODER 0
-%define CONFIG_SVQ1_ENCODER 0
-%define CONFIG_TARGA_ENCODER 0
-%define CONFIG_TIFF_ENCODER 0
-%define CONFIG_UTVIDEO_ENCODER 0
-%define CONFIG_V210_ENCODER 0
-%define CONFIG_V308_ENCODER 0
-%define CONFIG_V408_ENCODER 0
-%define CONFIG_V410_ENCODER 0
-%define CONFIG_VC2_ENCODER 0
-%define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-%define CONFIG_WMV1_ENCODER 0
-%define CONFIG_WMV2_ENCODER 0
-%define CONFIG_XBM_ENCODER 0
-%define CONFIG_XFACE_ENCODER 0
-%define CONFIG_XWD_ENCODER 0
-%define CONFIG_Y41P_ENCODER 0
-%define CONFIG_YUV4_ENCODER 0
-%define CONFIG_ZLIB_ENCODER 0
-%define CONFIG_ZMBV_ENCODER 0
-%define CONFIG_AAC_ENCODER 0
-%define CONFIG_AC3_ENCODER 0
-%define CONFIG_AC3_FIXED_ENCODER 0
-%define CONFIG_ALAC_ENCODER 0
-%define CONFIG_DCA_ENCODER 0
-%define CONFIG_EAC3_ENCODER 0
-%define CONFIG_FLAC_ENCODER 0
-%define CONFIG_G723_1_ENCODER 0
-%define CONFIG_MLP_ENCODER 0
-%define CONFIG_MP2_ENCODER 0
-%define CONFIG_MP2FIXED_ENCODER 0
-%define CONFIG_NELLYMOSER_ENCODER 0
-%define CONFIG_RA_144_ENCODER 0
-%define CONFIG_SONIC_ENCODER 0
-%define CONFIG_SONIC_LS_ENCODER 0
-%define CONFIG_TRUEHD_ENCODER 0
-%define CONFIG_TTA_ENCODER 0
-%define CONFIG_VORBIS_ENCODER 0
-%define CONFIG_WAVPACK_ENCODER 0
-%define CONFIG_WMAV1_ENCODER 0
-%define CONFIG_WMAV2_ENCODER 0
-%define CONFIG_PCM_ALAW_ENCODER 0
-%define CONFIG_PCM_F32BE_ENCODER 0
-%define CONFIG_PCM_F32LE_ENCODER 0
-%define CONFIG_PCM_F64BE_ENCODER 0
-%define CONFIG_PCM_F64LE_ENCODER 0
-%define CONFIG_PCM_MULAW_ENCODER 0
-%define CONFIG_PCM_S8_ENCODER 0
-%define CONFIG_PCM_S8_PLANAR_ENCODER 0
-%define CONFIG_PCM_S16BE_ENCODER 0
-%define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S16LE_ENCODER 0
-%define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S24BE_ENCODER 0
-%define CONFIG_PCM_S24DAUD_ENCODER 0
-%define CONFIG_PCM_S24LE_ENCODER 0
-%define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S32BE_ENCODER 0
-%define CONFIG_PCM_S32LE_ENCODER 0
-%define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S64BE_ENCODER 0
-%define CONFIG_PCM_S64LE_ENCODER 0
-%define CONFIG_PCM_U8_ENCODER 0
-%define CONFIG_PCM_U16BE_ENCODER 0
-%define CONFIG_PCM_U16LE_ENCODER 0
-%define CONFIG_PCM_U24BE_ENCODER 0
-%define CONFIG_PCM_U24LE_ENCODER 0
-%define CONFIG_PCM_U32BE_ENCODER 0
-%define CONFIG_PCM_U32LE_ENCODER 0
-%define CONFIG_ROQ_DPCM_ENCODER 0
-%define CONFIG_ADPCM_ADX_ENCODER 0
-%define CONFIG_ADPCM_G722_ENCODER 0
-%define CONFIG_ADPCM_G726_ENCODER 0
-%define CONFIG_ADPCM_IMA_QT_ENCODER 0
-%define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-%define CONFIG_ADPCM_MS_ENCODER 0
-%define CONFIG_ADPCM_SWF_ENCODER 0
-%define CONFIG_ADPCM_YAMAHA_ENCODER 0
-%define CONFIG_SSA_ENCODER 0
-%define CONFIG_ASS_ENCODER 0
-%define CONFIG_DVBSUB_ENCODER 0
-%define CONFIG_DVDSUB_ENCODER 0
-%define CONFIG_MOVTEXT_ENCODER 0
-%define CONFIG_SRT_ENCODER 0
-%define CONFIG_SUBRIP_ENCODER 0
-%define CONFIG_TEXT_ENCODER 0
-%define CONFIG_WEBVTT_ENCODER 0
-%define CONFIG_XSUB_ENCODER 0
-%define CONFIG_AAC_AT_ENCODER 0
-%define CONFIG_ALAC_AT_ENCODER 0
-%define CONFIG_ILBC_AT_ENCODER 0
-%define CONFIG_PCM_ALAW_AT_ENCODER 0
-%define CONFIG_PCM_MULAW_AT_ENCODER 0
-%define CONFIG_LIBFDK_AAC_ENCODER 0
-%define CONFIG_LIBGSM_ENCODER 0
-%define CONFIG_LIBGSM_MS_ENCODER 0
-%define CONFIG_LIBILBC_ENCODER 0
-%define CONFIG_LIBMP3LAME_ENCODER 0
-%define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-%define CONFIG_LIBOPENJPEG_ENCODER 0
-%define CONFIG_LIBOPUS_ENCODER 0
-%define CONFIG_LIBSCHROEDINGER_ENCODER 0
-%define CONFIG_LIBSHINE_ENCODER 0
-%define CONFIG_LIBSPEEX_ENCODER 0
-%define CONFIG_LIBTHEORA_ENCODER 0
-%define CONFIG_LIBTWOLAME_ENCODER 0
-%define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-%define CONFIG_LIBVORBIS_ENCODER 0
-%define CONFIG_LIBVPX_VP8_ENCODER 0
-%define CONFIG_LIBVPX_VP9_ENCODER 0
-%define CONFIG_LIBWAVPACK_ENCODER 0
-%define CONFIG_LIBWEBP_ANIM_ENCODER 0
-%define CONFIG_LIBWEBP_ENCODER 0
-%define CONFIG_LIBX262_ENCODER 0
-%define CONFIG_LIBX264_ENCODER 0
-%define CONFIG_LIBX264RGB_ENCODER 0
-%define CONFIG_LIBX265_ENCODER 0
-%define CONFIG_LIBXAVS_ENCODER 0
-%define CONFIG_LIBXVID_ENCODER 0
-%define CONFIG_LIBOPENH264_ENCODER 0
-%define CONFIG_H264_NVENC_ENCODER 0
-%define CONFIG_H264_OMX_ENCODER 0
-%define CONFIG_H264_QSV_ENCODER 0
-%define CONFIG_H264_VAAPI_ENCODER 0
-%define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-%define CONFIG_NVENC_ENCODER 0
-%define CONFIG_NVENC_H264_ENCODER 0
-%define CONFIG_NVENC_HEVC_ENCODER 0
-%define CONFIG_HEVC_NVENC_ENCODER 0
-%define CONFIG_HEVC_QSV_ENCODER 0
-%define CONFIG_HEVC_VAAPI_ENCODER 0
-%define CONFIG_LIBKVAZAAR_ENCODER 0
-%define CONFIG_MJPEG_VAAPI_ENCODER 0
-%define CONFIG_MPEG2_QSV_ENCODER 0
-%define CONFIG_ABENCH_FILTER 0
-%define CONFIG_ACOMPRESSOR_FILTER 0
-%define CONFIG_ACROSSFADE_FILTER 0
-%define CONFIG_ACRUSHER_FILTER 0
-%define CONFIG_ADELAY_FILTER 0
-%define CONFIG_AECHO_FILTER 0
-%define CONFIG_AEMPHASIS_FILTER 0
-%define CONFIG_AEVAL_FILTER 0
-%define CONFIG_AFADE_FILTER 0
-%define CONFIG_AFFTFILT_FILTER 0
-%define CONFIG_AFORMAT_FILTER 0
-%define CONFIG_AGATE_FILTER 0
-%define CONFIG_AINTERLEAVE_FILTER 0
-%define CONFIG_ALIMITER_FILTER 0
-%define CONFIG_ALLPASS_FILTER 0
-%define CONFIG_ALOOP_FILTER 0
-%define CONFIG_AMERGE_FILTER 0
-%define CONFIG_AMETADATA_FILTER 0
-%define CONFIG_AMIX_FILTER 0
-%define CONFIG_ANEQUALIZER_FILTER 0
-%define CONFIG_ANULL_FILTER 0
-%define CONFIG_APAD_FILTER 0
-%define CONFIG_APERMS_FILTER 0
-%define CONFIG_APHASER_FILTER 0
-%define CONFIG_APULSATOR_FILTER 0
-%define CONFIG_AREALTIME_FILTER 0
-%define CONFIG_ARESAMPLE_FILTER 0
-%define CONFIG_AREVERSE_FILTER 0
-%define CONFIG_ASELECT_FILTER 0
-%define CONFIG_ASENDCMD_FILTER 0
-%define CONFIG_ASETNSAMPLES_FILTER 0
-%define CONFIG_ASETPTS_FILTER 0
-%define CONFIG_ASETRATE_FILTER 0
-%define CONFIG_ASETTB_FILTER 0
-%define CONFIG_ASHOWINFO_FILTER 0
-%define CONFIG_ASIDEDATA_FILTER 0
-%define CONFIG_ASPLIT_FILTER 0
-%define CONFIG_ASTATS_FILTER 0
-%define CONFIG_ASTREAMSELECT_FILTER 0
-%define CONFIG_ASYNCTS_FILTER 0
-%define CONFIG_ATEMPO_FILTER 0
-%define CONFIG_ATRIM_FILTER 0
-%define CONFIG_AZMQ_FILTER 0
-%define CONFIG_BANDPASS_FILTER 0
-%define CONFIG_BANDREJECT_FILTER 0
-%define CONFIG_BASS_FILTER 0
-%define CONFIG_BIQUAD_FILTER 0
-%define CONFIG_BS2B_FILTER 0
-%define CONFIG_CHANNELMAP_FILTER 0
-%define CONFIG_CHANNELSPLIT_FILTER 0
-%define CONFIG_CHORUS_FILTER 0
-%define CONFIG_COMPAND_FILTER 0
-%define CONFIG_COMPENSATIONDELAY_FILTER 0
-%define CONFIG_CRYSTALIZER_FILTER 0
-%define CONFIG_DCSHIFT_FILTER 0
-%define CONFIG_DYNAUDNORM_FILTER 0
-%define CONFIG_EARWAX_FILTER 0
-%define CONFIG_EBUR128_FILTER 0
-%define CONFIG_EQUALIZER_FILTER 0
-%define CONFIG_EXTRASTEREO_FILTER 0
-%define CONFIG_FIREQUALIZER_FILTER 0
-%define CONFIG_FLANGER_FILTER 0
-%define CONFIG_HDCD_FILTER 0
-%define CONFIG_HIGHPASS_FILTER 0
-%define CONFIG_JOIN_FILTER 0
-%define CONFIG_LADSPA_FILTER 0
-%define CONFIG_LOUDNORM_FILTER 0
-%define CONFIG_LOWPASS_FILTER 0
-%define CONFIG_PAN_FILTER 0
-%define CONFIG_REPLAYGAIN_FILTER 0
-%define CONFIG_RESAMPLE_FILTER 0
-%define CONFIG_RUBBERBAND_FILTER 0
-%define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-%define CONFIG_SIDECHAINGATE_FILTER 0
-%define CONFIG_SILENCEDETECT_FILTER 0
-%define CONFIG_SILENCEREMOVE_FILTER 0
-%define CONFIG_SOFALIZER_FILTER 0
-%define CONFIG_STEREOTOOLS_FILTER 0
-%define CONFIG_STEREOWIDEN_FILTER 0
-%define CONFIG_TREBLE_FILTER 0
-%define CONFIG_TREMOLO_FILTER 0
-%define CONFIG_VIBRATO_FILTER 0
-%define CONFIG_VOLUME_FILTER 0
-%define CONFIG_VOLUMEDETECT_FILTER 0
-%define CONFIG_AEVALSRC_FILTER 0
-%define CONFIG_ANOISESRC_FILTER 0
-%define CONFIG_ANULLSRC_FILTER 0
-%define CONFIG_FLITE_FILTER 0
-%define CONFIG_SINE_FILTER 0
-%define CONFIG_ANULLSINK_FILTER 0
-%define CONFIG_ALPHAEXTRACT_FILTER 0
-%define CONFIG_ALPHAMERGE_FILTER 0
-%define CONFIG_ASS_FILTER 0
-%define CONFIG_ATADENOISE_FILTER 0
-%define CONFIG_AVGBLUR_FILTER 0
-%define CONFIG_BBOX_FILTER 0
-%define CONFIG_BENCH_FILTER 0
-%define CONFIG_BITPLANENOISE_FILTER 0
-%define CONFIG_BLACKDETECT_FILTER 0
-%define CONFIG_BLACKFRAME_FILTER 0
-%define CONFIG_BLEND_FILTER 0
-%define CONFIG_BOXBLUR_FILTER 0
-%define CONFIG_BWDIF_FILTER 0
-%define CONFIG_CHROMAKEY_FILTER 0
-%define CONFIG_CIESCOPE_FILTER 0
-%define CONFIG_CODECVIEW_FILTER 0
-%define CONFIG_COLORBALANCE_FILTER 0
-%define CONFIG_COLORCHANNELMIXER_FILTER 0
-%define CONFIG_COLORKEY_FILTER 0
-%define CONFIG_COLORLEVELS_FILTER 0
-%define CONFIG_COLORMATRIX_FILTER 0
-%define CONFIG_COLORSPACE_FILTER 0
-%define CONFIG_CONVOLUTION_FILTER 0
-%define CONFIG_COPY_FILTER 0
-%define CONFIG_COREIMAGE_FILTER 0
-%define CONFIG_COVER_RECT_FILTER 0
-%define CONFIG_CROP_FILTER 0
-%define CONFIG_CROPDETECT_FILTER 0
-%define CONFIG_CURVES_FILTER 0
-%define CONFIG_DATASCOPE_FILTER 0
-%define CONFIG_DCTDNOIZ_FILTER 0
-%define CONFIG_DEBAND_FILTER 0
-%define CONFIG_DECIMATE_FILTER 0
-%define CONFIG_DEFLATE_FILTER 0
-%define CONFIG_DEJUDDER_FILTER 0
-%define CONFIG_DELOGO_FILTER 0
-%define CONFIG_DESHAKE_FILTER 0
-%define CONFIG_DETELECINE_FILTER 0
-%define CONFIG_DILATION_FILTER 0
-%define CONFIG_DISPLACE_FILTER 0
-%define CONFIG_DRAWBOX_FILTER 0
-%define CONFIG_DRAWGRAPH_FILTER 0
-%define CONFIG_DRAWGRID_FILTER 0
-%define CONFIG_DRAWTEXT_FILTER 0
-%define CONFIG_EDGEDETECT_FILTER 0
-%define CONFIG_ELBG_FILTER 0
-%define CONFIG_EQ_FILTER 0
-%define CONFIG_EROSION_FILTER 0
-%define CONFIG_EXTRACTPLANES_FILTER 0
-%define CONFIG_FADE_FILTER 0
-%define CONFIG_FFTFILT_FILTER 0
-%define CONFIG_FIELD_FILTER 0
-%define CONFIG_FIELDHINT_FILTER 0
-%define CONFIG_FIELDMATCH_FILTER 0
-%define CONFIG_FIELDORDER_FILTER 0
-%define CONFIG_FIND_RECT_FILTER 0
-%define CONFIG_FORMAT_FILTER 0
-%define CONFIG_FPS_FILTER 0
-%define CONFIG_FRAMEPACK_FILTER 0
-%define CONFIG_FRAMERATE_FILTER 0
-%define CONFIG_FRAMESTEP_FILTER 0
-%define CONFIG_FREI0R_FILTER 0
-%define CONFIG_FSPP_FILTER 0
-%define CONFIG_GBLUR_FILTER 0
-%define CONFIG_GEQ_FILTER 0
-%define CONFIG_GRADFUN_FILTER 0
-%define CONFIG_HALDCLUT_FILTER 0
-%define CONFIG_HFLIP_FILTER 0
-%define CONFIG_HISTEQ_FILTER 0
-%define CONFIG_HISTOGRAM_FILTER 0
-%define CONFIG_HQDN3D_FILTER 0
-%define CONFIG_HQX_FILTER 0
-%define CONFIG_HSTACK_FILTER 0
-%define CONFIG_HUE_FILTER 0
-%define CONFIG_HWDOWNLOAD_FILTER 0
-%define CONFIG_HWUPLOAD_FILTER 0
-%define CONFIG_HWUPLOAD_CUDA_FILTER 0
-%define CONFIG_HYSTERESIS_FILTER 0
-%define CONFIG_IDET_FILTER 0
-%define CONFIG_IL_FILTER 0
-%define CONFIG_INFLATE_FILTER 0
-%define CONFIG_INTERLACE_FILTER 0
-%define CONFIG_INTERLEAVE_FILTER 0
-%define CONFIG_KERNDEINT_FILTER 0
-%define CONFIG_LENSCORRECTION_FILTER 0
-%define CONFIG_LOOP_FILTER 0
-%define CONFIG_LUT_FILTER 0
-%define CONFIG_LUT2_FILTER 0
-%define CONFIG_LUT3D_FILTER 0
-%define CONFIG_LUTRGB_FILTER 0
-%define CONFIG_LUTYUV_FILTER 0
-%define CONFIG_MASKEDCLAMP_FILTER 0
-%define CONFIG_MASKEDMERGE_FILTER 0
-%define CONFIG_MCDEINT_FILTER 0
-%define CONFIG_MERGEPLANES_FILTER 0
-%define CONFIG_MESTIMATE_FILTER 0
-%define CONFIG_METADATA_FILTER 0
-%define CONFIG_MINTERPOLATE_FILTER 0
-%define CONFIG_MPDECIMATE_FILTER 0
-%define CONFIG_NEGATE_FILTER 0
-%define CONFIG_NLMEANS_FILTER 0
-%define CONFIG_NNEDI_FILTER 0
-%define CONFIG_NOFORMAT_FILTER 0
-%define CONFIG_NOISE_FILTER 0
-%define CONFIG_NULL_FILTER 0
-%define CONFIG_OCR_FILTER 0
-%define CONFIG_OCV_FILTER 0
-%define CONFIG_OVERLAY_FILTER 0
-%define CONFIG_OWDENOISE_FILTER 0
-%define CONFIG_PAD_FILTER 0
-%define CONFIG_PALETTEGEN_FILTER 0
-%define CONFIG_PALETTEUSE_FILTER 0
-%define CONFIG_PERMS_FILTER 0
-%define CONFIG_PERSPECTIVE_FILTER 0
-%define CONFIG_PHASE_FILTER 0
-%define CONFIG_PIXDESCTEST_FILTER 0
-%define CONFIG_PP_FILTER 0
-%define CONFIG_PP7_FILTER 0
-%define CONFIG_PREWITT_FILTER 0
-%define CONFIG_PSNR_FILTER 0
-%define CONFIG_PULLUP_FILTER 0
-%define CONFIG_QP_FILTER 0
-%define CONFIG_RANDOM_FILTER 0
-%define CONFIG_READVITC_FILTER 0
-%define CONFIG_REALTIME_FILTER 0
-%define CONFIG_REMAP_FILTER 0
-%define CONFIG_REMOVEGRAIN_FILTER 0
-%define CONFIG_REMOVELOGO_FILTER 0
-%define CONFIG_REPEATFIELDS_FILTER 0
-%define CONFIG_REVERSE_FILTER 0
-%define CONFIG_ROTATE_FILTER 0
-%define CONFIG_SAB_FILTER 0
-%define CONFIG_SCALE_FILTER 0
-%define CONFIG_SCALE_NPP_FILTER 0
-%define CONFIG_SCALE_VAAPI_FILTER 0
-%define CONFIG_SCALE2REF_FILTER 0
-%define CONFIG_SELECT_FILTER 0
-%define CONFIG_SELECTIVECOLOR_FILTER 0
-%define CONFIG_SENDCMD_FILTER 0
-%define CONFIG_SEPARATEFIELDS_FILTER 0
-%define CONFIG_SETDAR_FILTER 0
-%define CONFIG_SETFIELD_FILTER 0
-%define CONFIG_SETPTS_FILTER 0
-%define CONFIG_SETSAR_FILTER 0
-%define CONFIG_SETTB_FILTER 0
-%define CONFIG_SHOWINFO_FILTER 0
-%define CONFIG_SHOWPALETTE_FILTER 0
-%define CONFIG_SHUFFLEFRAMES_FILTER 0
-%define CONFIG_SHUFFLEPLANES_FILTER 0
-%define CONFIG_SIDEDATA_FILTER 0
-%define CONFIG_SIGNALSTATS_FILTER 0
-%define CONFIG_SMARTBLUR_FILTER 0
-%define CONFIG_SOBEL_FILTER 0
-%define CONFIG_SPLIT_FILTER 0
-%define CONFIG_SPP_FILTER 0
-%define CONFIG_SSIM_FILTER 0
-%define CONFIG_STEREO3D_FILTER 0
-%define CONFIG_STREAMSELECT_FILTER 0
-%define CONFIG_SUBTITLES_FILTER 0
-%define CONFIG_SUPER2XSAI_FILTER 0
-%define CONFIG_SWAPRECT_FILTER 0
-%define CONFIG_SWAPUV_FILTER 0
-%define CONFIG_TBLEND_FILTER 0
-%define CONFIG_TELECINE_FILTER 0
-%define CONFIG_THUMBNAIL_FILTER 0
-%define CONFIG_TILE_FILTER 0
-%define CONFIG_TINTERLACE_FILTER 0
-%define CONFIG_TRANSPOSE_FILTER 0
-%define CONFIG_TRIM_FILTER 0
-%define CONFIG_UNSHARP_FILTER 0
-%define CONFIG_USPP_FILTER 0
-%define CONFIG_VAGUEDENOISER_FILTER 0
-%define CONFIG_VECTORSCOPE_FILTER 0
-%define CONFIG_VFLIP_FILTER 0
-%define CONFIG_VIDSTABDETECT_FILTER 0
-%define CONFIG_VIDSTABTRANSFORM_FILTER 0
-%define CONFIG_VIGNETTE_FILTER 0
-%define CONFIG_VSTACK_FILTER 0
-%define CONFIG_W3FDIF_FILTER 0
-%define CONFIG_WAVEFORM_FILTER 0
-%define CONFIG_WEAVE_FILTER 0
-%define CONFIG_XBR_FILTER 0
-%define CONFIG_YADIF_FILTER 0
-%define CONFIG_ZMQ_FILTER 0
-%define CONFIG_ZOOMPAN_FILTER 0
-%define CONFIG_ZSCALE_FILTER 0
-%define CONFIG_ALLRGB_FILTER 0
-%define CONFIG_ALLYUV_FILTER 0
-%define CONFIG_CELLAUTO_FILTER 0
-%define CONFIG_COLOR_FILTER 0
-%define CONFIG_COREIMAGESRC_FILTER 0
-%define CONFIG_FREI0R_SRC_FILTER 0
-%define CONFIG_HALDCLUTSRC_FILTER 0
-%define CONFIG_LIFE_FILTER 0
-%define CONFIG_MANDELBROT_FILTER 0
-%define CONFIG_MPTESTSRC_FILTER 0
-%define CONFIG_NULLSRC_FILTER 0
-%define CONFIG_RGBTESTSRC_FILTER 0
-%define CONFIG_SMPTEBARS_FILTER 0
-%define CONFIG_SMPTEHDBARS_FILTER 0
-%define CONFIG_TESTSRC_FILTER 0
-%define CONFIG_TESTSRC2_FILTER 0
-%define CONFIG_YUVTESTSRC_FILTER 0
-%define CONFIG_NULLSINK_FILTER 0
-%define CONFIG_ADRAWGRAPH_FILTER 0
-%define CONFIG_AHISTOGRAM_FILTER 0
-%define CONFIG_APHASEMETER_FILTER 0
-%define CONFIG_AVECTORSCOPE_FILTER 0
-%define CONFIG_CONCAT_FILTER 0
-%define CONFIG_SHOWCQT_FILTER 0
-%define CONFIG_SHOWFREQS_FILTER 0
-%define CONFIG_SHOWSPECTRUM_FILTER 0
-%define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-%define CONFIG_SHOWVOLUME_FILTER 0
-%define CONFIG_SHOWWAVES_FILTER 0
-%define CONFIG_SHOWWAVESPIC_FILTER 0
-%define CONFIG_SPECTRUMSYNTH_FILTER 0
-%define CONFIG_AMOVIE_FILTER 0
-%define CONFIG_MOVIE_FILTER 0
-%define CONFIG_H263_CUVID_HWACCEL 0
-%define CONFIG_H263_VAAPI_HWACCEL 0
-%define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_H264_CUVID_HWACCEL 0
-%define CONFIG_H264_D3D11VA_HWACCEL 0
-%define CONFIG_H264_DXVA2_HWACCEL 0
-%define CONFIG_H264_MEDIACODEC_HWACCEL 0
-%define CONFIG_H264_MMAL_HWACCEL 0
-%define CONFIG_H264_QSV_HWACCEL 0
-%define CONFIG_H264_VAAPI_HWACCEL 0
-%define CONFIG_H264_VDA_HWACCEL 0
-%define CONFIG_H264_VDA_OLD_HWACCEL 0
-%define CONFIG_H264_VDPAU_HWACCEL 0
-%define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_HEVC_CUVID_HWACCEL 0
-%define CONFIG_HEVC_D3D11VA_HWACCEL 0
-%define CONFIG_HEVC_DXVA2_HWACCEL 0
-%define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-%define CONFIG_HEVC_QSV_HWACCEL 0
-%define CONFIG_HEVC_VAAPI_HWACCEL 0
-%define CONFIG_HEVC_VDPAU_HWACCEL 0
-%define CONFIG_MJPEG_CUVID_HWACCEL 0
-%define CONFIG_MPEG1_CUVID_HWACCEL 0
-%define CONFIG_MPEG1_XVMC_HWACCEL 0
-%define CONFIG_MPEG1_VDPAU_HWACCEL 0
-%define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_MPEG2_CUVID_HWACCEL 0
-%define CONFIG_MPEG2_XVMC_HWACCEL 0
-%define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-%define CONFIG_MPEG2_DXVA2_HWACCEL 0
-%define CONFIG_MPEG2_MMAL_HWACCEL 0
-%define CONFIG_MPEG2_QSV_HWACCEL 0
-%define CONFIG_MPEG2_VAAPI_HWACCEL 0
-%define CONFIG_MPEG2_VDPAU_HWACCEL 0
-%define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_MPEG4_CUVID_HWACCEL 0
-%define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-%define CONFIG_MPEG4_MMAL_HWACCEL 0
-%define CONFIG_MPEG4_VAAPI_HWACCEL 0
-%define CONFIG_MPEG4_VDPAU_HWACCEL 0
-%define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_VC1_CUVID_HWACCEL 0
-%define CONFIG_VC1_D3D11VA_HWACCEL 0
-%define CONFIG_VC1_DXVA2_HWACCEL 0
-%define CONFIG_VC1_VAAPI_HWACCEL 0
-%define CONFIG_VC1_VDPAU_HWACCEL 0
-%define CONFIG_VC1_MMAL_HWACCEL 0
-%define CONFIG_VC1_QSV_HWACCEL 0
-%define CONFIG_VP8_CUVID_HWACCEL 0
-%define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-%define CONFIG_VP9_CUVID_HWACCEL 0
-%define CONFIG_VP9_D3D11VA_HWACCEL 0
-%define CONFIG_VP9_DXVA2_HWACCEL 0
-%define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-%define CONFIG_VP9_VAAPI_HWACCEL 0
-%define CONFIG_WMV3_D3D11VA_HWACCEL 0
-%define CONFIG_WMV3_DXVA2_HWACCEL 0
-%define CONFIG_WMV3_VAAPI_HWACCEL 0
-%define CONFIG_WMV3_VDPAU_HWACCEL 0
-%define CONFIG_ALSA_INDEV 0
-%define CONFIG_AVFOUNDATION_INDEV 0
-%define CONFIG_BKTR_INDEV 0
-%define CONFIG_DECKLINK_INDEV 0
-%define CONFIG_DSHOW_INDEV 0
-%define CONFIG_DV1394_INDEV 0
-%define CONFIG_FBDEV_INDEV 0
-%define CONFIG_GDIGRAB_INDEV 0
-%define CONFIG_IEC61883_INDEV 0
-%define CONFIG_JACK_INDEV 0
-%define CONFIG_LAVFI_INDEV 0
-%define CONFIG_OPENAL_INDEV 0
-%define CONFIG_OSS_INDEV 0
-%define CONFIG_PULSE_INDEV 0
-%define CONFIG_QTKIT_INDEV 0
-%define CONFIG_SNDIO_INDEV 0
-%define CONFIG_V4L2_INDEV 0
-%define CONFIG_VFWCAP_INDEV 0
-%define CONFIG_X11GRAB_INDEV 0
-%define CONFIG_X11GRAB_XCB_INDEV 0
-%define CONFIG_LIBCDIO_INDEV 0
-%define CONFIG_LIBDC1394_INDEV 0
-%define CONFIG_A64_MUXER 0
-%define CONFIG_AC3_MUXER 0
-%define CONFIG_ADTS_MUXER 0
-%define CONFIG_ADX_MUXER 0
-%define CONFIG_AIFF_MUXER 0
-%define CONFIG_AMR_MUXER 0
-%define CONFIG_APNG_MUXER 0
-%define CONFIG_ASF_MUXER 0
-%define CONFIG_ASS_MUXER 0
-%define CONFIG_AST_MUXER 0
-%define CONFIG_ASF_STREAM_MUXER 0
-%define CONFIG_AU_MUXER 0
-%define CONFIG_AVI_MUXER 0
-%define CONFIG_AVM2_MUXER 0
-%define CONFIG_BIT_MUXER 0
-%define CONFIG_CAF_MUXER 0
-%define CONFIG_CAVSVIDEO_MUXER 0
-%define CONFIG_CRC_MUXER 0
-%define CONFIG_DASH_MUXER 0
-%define CONFIG_DATA_MUXER 0
-%define CONFIG_DAUD_MUXER 0
-%define CONFIG_DIRAC_MUXER 0
-%define CONFIG_DNXHD_MUXER 0
-%define CONFIG_DTS_MUXER 0
-%define CONFIG_DV_MUXER 0
-%define CONFIG_EAC3_MUXER 0
-%define CONFIG_F4V_MUXER 0
-%define CONFIG_FFM_MUXER 0
-%define CONFIG_FFMETADATA_MUXER 0
-%define CONFIG_FIFO_MUXER 0
-%define CONFIG_FILMSTRIP_MUXER 0
-%define CONFIG_FLAC_MUXER 0
-%define CONFIG_FLV_MUXER 0
-%define CONFIG_FRAMECRC_MUXER 0
-%define CONFIG_FRAMEHASH_MUXER 0
-%define CONFIG_FRAMEMD5_MUXER 0
-%define CONFIG_G722_MUXER 0
-%define CONFIG_G723_1_MUXER 0
-%define CONFIG_GIF_MUXER 0
-%define CONFIG_GSM_MUXER 0
-%define CONFIG_GXF_MUXER 0
-%define CONFIG_H261_MUXER 0
-%define CONFIG_H263_MUXER 0
-%define CONFIG_H264_MUXER 0
-%define CONFIG_HASH_MUXER 0
-%define CONFIG_HDS_MUXER 0
-%define CONFIG_HEVC_MUXER 0
-%define CONFIG_HLS_MUXER 0
-%define CONFIG_ICO_MUXER 0
-%define CONFIG_ILBC_MUXER 0
-%define CONFIG_IMAGE2_MUXER 0
-%define CONFIG_IMAGE2PIPE_MUXER 0
-%define CONFIG_IPOD_MUXER 0
-%define CONFIG_IRCAM_MUXER 0
-%define CONFIG_ISMV_MUXER 0
-%define CONFIG_IVF_MUXER 0
-%define CONFIG_JACOSUB_MUXER 0
-%define CONFIG_LATM_MUXER 0
-%define CONFIG_LRC_MUXER 0
-%define CONFIG_M4V_MUXER 0
-%define CONFIG_MD5_MUXER 0
-%define CONFIG_MATROSKA_MUXER 0
-%define CONFIG_MATROSKA_AUDIO_MUXER 0
-%define CONFIG_MICRODVD_MUXER 0
-%define CONFIG_MJPEG_MUXER 0
-%define CONFIG_MLP_MUXER 0
-%define CONFIG_MMF_MUXER 0
-%define CONFIG_MOV_MUXER 0
-%define CONFIG_MP2_MUXER 0
-%define CONFIG_MP3_MUXER 0
-%define CONFIG_MP4_MUXER 0
-%define CONFIG_MPEG1SYSTEM_MUXER 0
-%define CONFIG_MPEG1VCD_MUXER 0
-%define CONFIG_MPEG1VIDEO_MUXER 0
-%define CONFIG_MPEG2DVD_MUXER 0
-%define CONFIG_MPEG2SVCD_MUXER 0
-%define CONFIG_MPEG2VIDEO_MUXER 0
-%define CONFIG_MPEG2VOB_MUXER 0
-%define CONFIG_MPEGTS_MUXER 0
-%define CONFIG_MPJPEG_MUXER 0
-%define CONFIG_MXF_MUXER 0
-%define CONFIG_MXF_D10_MUXER 0
-%define CONFIG_MXF_OPATOM_MUXER 0
-%define CONFIG_NULL_MUXER 0
-%define CONFIG_NUT_MUXER 0
-%define CONFIG_OGA_MUXER 0
-%define CONFIG_OGG_MUXER 0
-%define CONFIG_OGV_MUXER 0
-%define CONFIG_OMA_MUXER 0
-%define CONFIG_OPUS_MUXER 0
-%define CONFIG_PCM_ALAW_MUXER 0
-%define CONFIG_PCM_MULAW_MUXER 0
-%define CONFIG_PCM_F64BE_MUXER 0
-%define CONFIG_PCM_F64LE_MUXER 0
-%define CONFIG_PCM_F32BE_MUXER 0
-%define CONFIG_PCM_F32LE_MUXER 0
-%define CONFIG_PCM_S32BE_MUXER 0
-%define CONFIG_PCM_S32LE_MUXER 0
-%define CONFIG_PCM_S24BE_MUXER 0
-%define CONFIG_PCM_S24LE_MUXER 0
-%define CONFIG_PCM_S16BE_MUXER 0
-%define CONFIG_PCM_S16LE_MUXER 0
-%define CONFIG_PCM_S8_MUXER 0
-%define CONFIG_PCM_U32BE_MUXER 0
-%define CONFIG_PCM_U32LE_MUXER 0
-%define CONFIG_PCM_U24BE_MUXER 0
-%define CONFIG_PCM_U24LE_MUXER 0
-%define CONFIG_PCM_U16BE_MUXER 0
-%define CONFIG_PCM_U16LE_MUXER 0
-%define CONFIG_PCM_U8_MUXER 0
-%define CONFIG_PSP_MUXER 0
-%define CONFIG_RAWVIDEO_MUXER 0
-%define CONFIG_RM_MUXER 0
-%define CONFIG_ROQ_MUXER 0
-%define CONFIG_RSO_MUXER 0
-%define CONFIG_RTP_MUXER 0
-%define CONFIG_RTP_MPEGTS_MUXER 0
-%define CONFIG_RTSP_MUXER 0
-%define CONFIG_SAP_MUXER 0
-%define CONFIG_SEGMENT_MUXER 0
-%define CONFIG_STREAM_SEGMENT_MUXER 0
-%define CONFIG_SINGLEJPEG_MUXER 0
-%define CONFIG_SMJPEG_MUXER 0
-%define CONFIG_SMOOTHSTREAMING_MUXER 0
-%define CONFIG_SOX_MUXER 0
-%define CONFIG_SPX_MUXER 0
-%define CONFIG_SPDIF_MUXER 0
-%define CONFIG_SRT_MUXER 0
-%define CONFIG_SWF_MUXER 0
-%define CONFIG_TEE_MUXER 0
-%define CONFIG_TG2_MUXER 0
-%define CONFIG_TGP_MUXER 0
-%define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-%define CONFIG_TRUEHD_MUXER 0
-%define CONFIG_TTA_MUXER 0
-%define CONFIG_UNCODEDFRAMECRC_MUXER 0
-%define CONFIG_VC1_MUXER 0
-%define CONFIG_VC1T_MUXER 0
-%define CONFIG_VOC_MUXER 0
-%define CONFIG_W64_MUXER 0
-%define CONFIG_WAV_MUXER 0
-%define CONFIG_WEBM_MUXER 0
-%define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-%define CONFIG_WEBM_CHUNK_MUXER 0
-%define CONFIG_WEBP_MUXER 0
-%define CONFIG_WEBVTT_MUXER 0
-%define CONFIG_WTV_MUXER 0
-%define CONFIG_WV_MUXER 0
-%define CONFIG_YUV4MPEGPIPE_MUXER 0
-%define CONFIG_CHROMAPRINT_MUXER 0
-%define CONFIG_LIBNUT_MUXER 0
-%define CONFIG_ALSA_OUTDEV 0
-%define CONFIG_CACA_OUTDEV 0
-%define CONFIG_DECKLINK_OUTDEV 0
-%define CONFIG_FBDEV_OUTDEV 0
-%define CONFIG_OPENGL_OUTDEV 0
-%define CONFIG_OSS_OUTDEV 0
-%define CONFIG_PULSE_OUTDEV 0
-%define CONFIG_SDL2_OUTDEV 0
-%define CONFIG_SNDIO_OUTDEV 0
-%define CONFIG_V4L2_OUTDEV 0
-%define CONFIG_XV_OUTDEV 0
-%define CONFIG_AAC_PARSER 0
-%define CONFIG_AAC_LATM_PARSER 0
-%define CONFIG_AC3_PARSER 0
-%define CONFIG_ADX_PARSER 0
-%define CONFIG_BMP_PARSER 0
-%define CONFIG_CAVSVIDEO_PARSER 0
-%define CONFIG_COOK_PARSER 0
-%define CONFIG_DCA_PARSER 0
-%define CONFIG_DIRAC_PARSER 0
-%define CONFIG_DNXHD_PARSER 0
-%define CONFIG_DPX_PARSER 0
-%define CONFIG_DVAUDIO_PARSER 0
-%define CONFIG_DVBSUB_PARSER 0
-%define CONFIG_DVDSUB_PARSER 0
-%define CONFIG_DVD_NAV_PARSER 0
-%define CONFIG_FLAC_PARSER 1
-%define CONFIG_G729_PARSER 0
-%define CONFIG_GSM_PARSER 0
-%define CONFIG_H261_PARSER 0
-%define CONFIG_H263_PARSER 0
-%define CONFIG_H264_PARSER 0
-%define CONFIG_HEVC_PARSER 0
-%define CONFIG_MJPEG_PARSER 0
-%define CONFIG_MLP_PARSER 0
-%define CONFIG_MPEG4VIDEO_PARSER 0
-%define CONFIG_MPEGAUDIO_PARSER 0
-%define CONFIG_MPEGVIDEO_PARSER 0
-%define CONFIG_OPUS_PARSER 0
-%define CONFIG_PNG_PARSER 0
-%define CONFIG_PNM_PARSER 0
-%define CONFIG_RV30_PARSER 0
-%define CONFIG_RV40_PARSER 0
-%define CONFIG_TAK_PARSER 0
-%define CONFIG_VC1_PARSER 0
-%define CONFIG_VORBIS_PARSER 0
-%define CONFIG_VP3_PARSER 0
+%define CONFIG_FLAC_PARSER 0
%define CONFIG_VP8_PARSER 1
%define CONFIG_VP9_PARSER 1
-%define CONFIG_ASYNC_PROTOCOL 0
-%define CONFIG_BLURAY_PROTOCOL 0
-%define CONFIG_CACHE_PROTOCOL 0
-%define CONFIG_CONCAT_PROTOCOL 0
-%define CONFIG_CRYPTO_PROTOCOL 0
-%define CONFIG_DATA_PROTOCOL 0
-%define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-%define CONFIG_FFRTMPHTTP_PROTOCOL 0
-%define CONFIG_FILE_PROTOCOL 0
-%define CONFIG_FTP_PROTOCOL 0
-%define CONFIG_GOPHER_PROTOCOL 0
-%define CONFIG_HLS_PROTOCOL 0
-%define CONFIG_HTTP_PROTOCOL 0
-%define CONFIG_HTTPPROXY_PROTOCOL 0
-%define CONFIG_HTTPS_PROTOCOL 0
-%define CONFIG_ICECAST_PROTOCOL 0
-%define CONFIG_MMSH_PROTOCOL 0
-%define CONFIG_MMST_PROTOCOL 0
-%define CONFIG_MD5_PROTOCOL 0
-%define CONFIG_PIPE_PROTOCOL 0
-%define CONFIG_RTMP_PROTOCOL 0
-%define CONFIG_RTMPE_PROTOCOL 0
-%define CONFIG_RTMPS_PROTOCOL 0
-%define CONFIG_RTMPT_PROTOCOL 0
-%define CONFIG_RTMPTE_PROTOCOL 0
-%define CONFIG_RTMPTS_PROTOCOL 0
-%define CONFIG_RTP_PROTOCOL 0
-%define CONFIG_SCTP_PROTOCOL 0
-%define CONFIG_SRTP_PROTOCOL 0
-%define CONFIG_SUBFILE_PROTOCOL 0
-%define CONFIG_TEE_PROTOCOL 0
-%define CONFIG_TCP_PROTOCOL 0
-%define CONFIG_TLS_GNUTLS_PROTOCOL 0
-%define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-%define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-%define CONFIG_TLS_OPENSSL_PROTOCOL 0
-%define CONFIG_UDP_PROTOCOL 0
-%define CONFIG_UDPLITE_PROTOCOL 0
-%define CONFIG_UNIX_PROTOCOL 0
-%define CONFIG_LIBRTMP_PROTOCOL 0
-%define CONFIG_LIBRTMPE_PROTOCOL 0
-%define CONFIG_LIBRTMPS_PROTOCOL 0
-%define CONFIG_LIBRTMPT_PROTOCOL 0
-%define CONFIG_LIBRTMPTE_PROTOCOL 0
-%define CONFIG_LIBSSH_PROTOCOL 0
-%define CONFIG_LIBSMBCLIENT_PROTOCOL 0
diff --git a/media/ffvpx/config_unix64.h b/media/ffvpx/config_unix64.h
index 26d6be5d4..97bc765f8 100644
--- a/media/ffvpx/config_unix64.h
+++ b/media/ffvpx/config_unix64.h
@@ -1,12 +1,12 @@
/* Automatically generated by configure - do not modify! */
#ifndef FFMPEG_CONFIG_H
#define FFMPEG_CONFIG_H
-#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-asm --enable-yasm --disable-avx2"
+#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl2 --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-decoder=flac --enable-asm --enable-x86asm"
#define FFMPEG_LICENSE "LGPL version 2.1 or later"
-#define CONFIG_THIS_YEAR 2016
+#define CONFIG_THIS_YEAR 2017
#define FFMPEG_DATADIR "/usr/local/share/ffmpeg"
#define AVCONV_DATADIR "/usr/local/share/ffmpeg"
-#define CC_IDENT "gcc 4.6 (Ubuntu/Linaro 4.6.3-1ubuntu5)"
+#define CC_IDENT "gcc 6.3.0 (Ubuntu 6.3.0-12ubuntu2) 20170406"
#define av_restrict restrict
#define EXTERN_PREFIX ""
#define EXTERN_ASM
@@ -56,7 +56,7 @@
#define HAVE_AMD3DNOW 1
#define HAVE_AMD3DNOWEXT 1
#define HAVE_AVX 1
-#define HAVE_AVX2 0
+#define HAVE_AVX2 1
#define HAVE_FMA3 1
#define HAVE_FMA4 1
#define HAVE_MMX 1
@@ -79,8 +79,8 @@
#define HAVE_MIPSDSP 0
#define HAVE_MIPSDSPR2 0
#define HAVE_MSA 0
-#define HAVE_LOONGSON2 1
-#define HAVE_LOONGSON3 1
+#define HAVE_LOONGSON2 0
+#define HAVE_LOONGSON3 0
#define HAVE_MMI 0
#define HAVE_ARMV5TE_EXTERNAL 0
#define HAVE_ARMV6_EXTERNAL 0
@@ -100,7 +100,7 @@
#define HAVE_AMD3DNOW_EXTERNAL 1
#define HAVE_AMD3DNOWEXT_EXTERNAL 1
#define HAVE_AVX_EXTERNAL 1
-#define HAVE_AVX2_EXTERNAL 0
+#define HAVE_AVX2_EXTERNAL 1
#define HAVE_FMA3_EXTERNAL 1
#define HAVE_FMA4_EXTERNAL 1
#define HAVE_MMX_EXTERNAL 1
@@ -144,7 +144,7 @@
#define HAVE_AMD3DNOW_INLINE 1
#define HAVE_AMD3DNOWEXT_INLINE 1
#define HAVE_AVX_INLINE 1
-#define HAVE_AVX2_INLINE 0
+#define HAVE_AVX2_INLINE 1
#define HAVE_FMA3_INLINE 1
#define HAVE_FMA4_INLINE 1
#define HAVE_MMX_INLINE 1
@@ -178,11 +178,11 @@
#define HAVE_LOCAL_ALIGNED_16 1
#define HAVE_LOCAL_ALIGNED_32 1
#define HAVE_SIMD_ALIGN_16 1
+#define HAVE_SIMD_ALIGN_32 1
#define HAVE_ATOMICS_GCC 1
#define HAVE_ATOMICS_SUNCC 0
#define HAVE_ATOMICS_WIN32 0
#define HAVE_ATOMIC_CAS_PTR 0
-#define HAVE_ATOMIC_COMPARE_EXCHANGE 0
#define HAVE_MACHINE_RW_BARRIER 0
#define HAVE_MEMORYBARRIER 0
#define HAVE_MM_EMPTY 1
@@ -194,15 +194,16 @@
#define HAVE_CEXP 1
#define HAVE_INLINE_ASM 1
#define HAVE_SYMVER 1
-#define HAVE_YASM 1
+#define HAVE_X86ASM 1
#define HAVE_BIGENDIAN 0
#define HAVE_FAST_UNALIGNED 1
-#define HAVE_ALSA_ASOUNDLIB_H 0
#define HAVE_ALTIVEC_H 0
#define HAVE_ARPA_INET_H 1
#define HAVE_ASM_TYPES_H 1
#define HAVE_CDIO_PARANOIA_H 0
#define HAVE_CDIO_PARANOIA_PARANOIA_H 0
+#define HAVE_CUDA_H 0
+#define HAVE_D3D11_H 0
#define HAVE_DISPATCH_DISPATCH_H 0
#define HAVE_DEV_BKTR_IOCTL_BT848_H 0
#define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
@@ -212,7 +213,7 @@
#define HAVE_DIRECT_H 0
#define HAVE_DIRENT_H 1
#define HAVE_DLFCN_H 1
-#define HAVE_D3D11_H 0
+#define HAVE_DXGIDEBUG_H 0
#define HAVE_DXVA_H 0
#define HAVE_ES2_GL_H 0
#define HAVE_GSM_H 0
@@ -221,13 +222,15 @@
#define HAVE_MACHINE_IOCTL_BT848_H 0
#define HAVE_MACHINE_IOCTL_METEOR_H 0
#define HAVE_OPENCV2_CORE_CORE_C_H 0
+#define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+#define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
#define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
#define HAVE_OPENGL_GL3_H 0
#define HAVE_POLL_H 1
-#define HAVE_SNDIO_H 0
#define HAVE_SOUNDCARD_H 0
+#define HAVE_STDATOMIC_H 1
#define HAVE_SYS_MMAN_H 1
#define HAVE_SYS_PARAM_H 1
#define HAVE_SYS_RESOURCE_H 1
@@ -279,7 +282,6 @@
#define HAVE_COMMANDLINETOARGVW 0
#define HAVE_COTASKMEMFREE 0
#define HAVE_CRYPTGENRANDOM 0
-#define HAVE_DLOPEN 1
#define HAVE_FCNTL 1
#define HAVE_FLT_LIM 1
#define HAVE_FORK 1
@@ -318,6 +320,7 @@
#define HAVE_SLEEP 0
#define HAVE_STRERROR_R 1
#define HAVE_SYSCONF 1
+#define HAVE_SYSCTL 0
#define HAVE_USLEEP 1
#define HAVE_UTGETOSTYPEFROMSTRING 0
#define HAVE_VIRTUALALLOC 0
@@ -326,11 +329,13 @@
#define HAVE_OS2THREADS 0
#define HAVE_W32THREADS 0
#define HAVE_AS_DN_DIRECTIVE 0
+#define HAVE_AS_FPU_DIRECTIVE 0
#define HAVE_AS_FUNC 0
#define HAVE_AS_OBJECT_ARCH 0
#define HAVE_ASM_MOD_Q 0
#define HAVE_ATTRIBUTE_MAY_ALIAS 1
#define HAVE_ATTRIBUTE_PACKED 1
+#define HAVE_BLOCKS_EXTENSION 0
#define HAVE_EBP_AVAILABLE 1
#define HAVE_EBX_AVAILABLE 1
#define HAVE_GNU_AS 0
@@ -347,6 +352,7 @@
#define HAVE_XFORM_ASM 0
#define HAVE_XMM_CLOBBERS 1
#define HAVE_CONDITION_VARIABLE_PTR 0
+#define HAVE_KCMVIDEOCODECTYPE_HEVC 0
#define HAVE_SOCKLEN_T 1
#define HAVE_STRUCT_ADDRINFO 1
#define HAVE_STRUCT_GROUP_SOURCE_REQ 1
@@ -363,36 +369,20 @@
#define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 1
#define HAVE_ATOMICS_NATIVE 1
#define HAVE_DOS_PATHS 0
-#define HAVE_DXVA2_LIB 0
-#define HAVE_DXVA2API_COBJ 0
#define HAVE_LIBC_MSVCRT 0
-#define HAVE_LIBDC1394_1 0
-#define HAVE_LIBDC1394_2 0
#define HAVE_MAKEINFO 0
#define HAVE_MAKEINFO_HTML 0
#define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
#define HAVE_PERL 1
#define HAVE_POD2MAN 1
-#define HAVE_SDL2 0
#define HAVE_SECTION_DATA_REL_RO 1
#define HAVE_TEXI2HTML 0
#define HAVE_THREADS 1
+#define HAVE_UWP 0
#define HAVE_VAAPI_DRM 0
#define HAVE_VAAPI_X11 0
#define HAVE_VDPAU_X11 0
#define HAVE_WINRT 0
-#define HAVE_XLIB 0
-#define CONFIG_BSFS 0
-#define CONFIG_DECODERS 1
-#define CONFIG_ENCODERS 0
-#define CONFIG_HWACCELS 0
-#define CONFIG_PARSERS 1
-#define CONFIG_INDEVS 0
-#define CONFIG_OUTDEVS 0
-#define CONFIG_FILTERS 0
-#define CONFIG_DEMUXERS 0
-#define CONFIG_MUXERS 0
-#define CONFIG_PROTOCOLS 0
#define CONFIG_DOC 0
#define CONFIG_HTMLPAGES 0
#define CONFIG_MANPAGES 1
@@ -400,13 +390,17 @@
#define CONFIG_TXTPAGES 0
#define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
#define CONFIG_AVIO_READING_EXAMPLE 1
-#define CONFIG_DECODING_ENCODING_EXAMPLE 0
+#define CONFIG_DECODE_AUDIO_EXAMPLE 1
+#define CONFIG_DECODE_VIDEO_EXAMPLE 1
#define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+#define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+#define CONFIG_ENCODE_VIDEO_EXAMPLE 1
#define CONFIG_EXTRACT_MVS_EXAMPLE 0
#define CONFIG_FILTER_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_VIDEO_EXAMPLE 0
#define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+#define CONFIG_HW_DECODE_EXAMPLE 0
#define CONFIG_METADATA_EXAMPLE 0
#define CONFIG_MUXING_EXAMPLE 0
#define CONFIG_QSVDEC_EXAMPLE 0
@@ -415,27 +409,55 @@
#define CONFIG_SCALING_VIDEO_EXAMPLE 0
#define CONFIG_TRANSCODE_AAC_EXAMPLE 0
#define CONFIG_TRANSCODING_EXAMPLE 0
-#define CONFIG_AVISYNTH 0
+#define CONFIG_ALSA 1
+#define CONFIG_APPKIT 0
+#define CONFIG_AVFOUNDATION 0
#define CONFIG_BZLIB 0
-#define CONFIG_CHROMAPRINT 0
-#define CONFIG_CRYSTALHD 0
-#define CONFIG_DECKLINK 0
+#define CONFIG_COREIMAGE 0
+#define CONFIG_ICONV 0
+#define CONFIG_JACK 0
+#define CONFIG_LIBXCB 0
+#define CONFIG_LIBXCB_SHM 0
+#define CONFIG_LIBXCB_SHAPE 0
+#define CONFIG_LIBXCB_XFIXES 0
+#define CONFIG_LZMA 1
+#define CONFIG_SCHANNEL 0
+#define CONFIG_SDL2 0
+#define CONFIG_SECURETRANSPORT 0
+#define CONFIG_SNDIO 0
+#define CONFIG_XLIB 1
+#define CONFIG_ZLIB 1
+#define CONFIG_AVISYNTH 0
#define CONFIG_FREI0R 0
-#define CONFIG_GCRYPT 0
+#define CONFIG_LIBCDIO 0
+#define CONFIG_LIBRUBBERBAND 0
+#define CONFIG_LIBVIDSTAB 0
+#define CONFIG_LIBX264 0
+#define CONFIG_LIBX265 0
+#define CONFIG_LIBXAVS 0
+#define CONFIG_LIBXVID 0
+#define CONFIG_DECKLINK 0
+#define CONFIG_LIBNDI_NEWTEK 0
+#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_OPENSSL 0
#define CONFIG_GMP 0
+#define CONFIG_LIBOPENCORE_AMRNB 0
+#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_RKMPP 0
+#define CONFIG_LIBSMBCLIENT 0
+#define CONFIG_CHROMAPRINT 0
+#define CONFIG_GCRYPT 0
#define CONFIG_GNUTLS 0
-#define CONFIG_ICONV 0
#define CONFIG_JNI 0
#define CONFIG_LADSPA 0
#define CONFIG_LIBASS 0
#define CONFIG_LIBBLURAY 0
#define CONFIG_LIBBS2B 0
#define CONFIG_LIBCACA 0
-#define CONFIG_LIBCDIO 0
#define CONFIG_LIBCELT 0
#define CONFIG_LIBDC1394 0
-#define CONFIG_LIBEBUR128 0
-#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_LIBDRM 0
#define CONFIG_LIBFLITE 0
#define CONFIG_LIBFONTCONFIG 0
#define CONFIG_LIBFREETYPE 0
@@ -447,18 +469,15 @@
#define CONFIG_LIBKVAZAAR 0
#define CONFIG_LIBMODPLUG 0
#define CONFIG_LIBMP3LAME 0
-#define CONFIG_LIBNUT 0
-#define CONFIG_LIBOPENCORE_AMRNB 0
-#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBMYSOFA 0
#define CONFIG_LIBOPENCV 0
#define CONFIG_LIBOPENH264 0
#define CONFIG_LIBOPENJPEG 0
#define CONFIG_LIBOPENMPT 0
#define CONFIG_LIBOPUS 0
#define CONFIG_LIBPULSE 0
+#define CONFIG_LIBRSVG 0
#define CONFIG_LIBRTMP 0
-#define CONFIG_LIBRUBBERBAND 0
-#define CONFIG_LIBSCHROEDINGER 0
#define CONFIG_LIBSHINE 0
#define CONFIG_LIBSMBCLIENT 0
#define CONFIG_LIBSNAPPY 0
@@ -469,53 +488,37 @@
#define CONFIG_LIBTHEORA 0
#define CONFIG_LIBTWOLAME 0
#define CONFIG_LIBV4L2 0
-#define CONFIG_LIBVIDSTAB 0
-#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_LIBVMAF 0
#define CONFIG_LIBVORBIS 0
#define CONFIG_LIBVPX 0
#define CONFIG_LIBWAVPACK 0
#define CONFIG_LIBWEBP 0
-#define CONFIG_LIBX264 0
-#define CONFIG_LIBX265 0
-#define CONFIG_LIBXAVS 0
-#define CONFIG_LIBXCB 0
-#define CONFIG_LIBXCB_SHM 0
-#define CONFIG_LIBXCB_SHAPE 0
-#define CONFIG_LIBXCB_XFIXES 0
-#define CONFIG_LIBXVID 0
+#define CONFIG_LIBXML2 0
#define CONFIG_LIBZIMG 0
#define CONFIG_LIBZMQ 0
#define CONFIG_LIBZVBI 0
-#define CONFIG_LZMA 0
#define CONFIG_MEDIACODEC 0
-#define CONFIG_NETCDF 0
#define CONFIG_OPENAL 0
#define CONFIG_OPENCL 0
#define CONFIG_OPENGL 0
-#define CONFIG_OPENSSL 0
-#define CONFIG_SCHANNEL 0
-#define CONFIG_SDL 0
-#define CONFIG_SDL2 0
-#define CONFIG_SECURETRANSPORT 0
-#define CONFIG_VIDEOTOOLBOX 0
-#define CONFIG_X11GRAB 0
-#define CONFIG_XLIB 0
-#define CONFIG_ZLIB 0
#define CONFIG_AUDIOTOOLBOX 0
-#define CONFIG_CUDA 0
-#define CONFIG_CUVID 0
+#define CONFIG_CRYSTALHD 0
+#define CONFIG_CUDA 1
+#define CONFIG_CUVID 1
#define CONFIG_D3D11VA 0
#define CONFIG_DXVA2 0
-#define CONFIG_LIBMFX 0
-#define CONFIG_LIBNPP 0
-#define CONFIG_MMAL 0
-#define CONFIG_NVENC 0
-#define CONFIG_OMX 0
+#define CONFIG_NVENC 1
#define CONFIG_VAAPI 0
#define CONFIG_VDA 0
#define CONFIG_VDPAU 0
-#define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_VIDEOTOOLBOX 0
+#define CONFIG_V4L2_M2M 1
#define CONFIG_XVMC 0
+#define CONFIG_CUDA_SDK 0
+#define CONFIG_LIBNPP 0
+#define CONFIG_LIBMFX 0
+#define CONFIG_MMAL 0
+#define CONFIG_OMX 0
#define CONFIG_FTRAPV 0
#define CONFIG_GRAY 0
#define CONFIG_HARDCODED_TABLES 0
@@ -554,16 +557,27 @@
#define CONFIG_PIXELUTILS 0
#define CONFIG_NETWORK 0
#define CONFIG_RDFT 0
+#define CONFIG_AUTODETECT 0
#define CONFIG_FONTCONFIG 0
-#define CONFIG_MEMALIGN_HACK 0
+#define CONFIG_LINUX_PERF 0
#define CONFIG_MEMORY_POISONING 0
#define CONFIG_NEON_CLOBBER_TEST 0
+#define CONFIG_OSSFUZZ 0
#define CONFIG_PIC 1
-#define CONFIG_POD2MAN 1
-#define CONFIG_RAISE_MAJOR 0
#define CONFIG_THUMB 0
#define CONFIG_VALGRIND_BACKTRACE 0
#define CONFIG_XMM_CLOBBER_TEST 0
+#define CONFIG_BSFS 1
+#define CONFIG_DECODERS 1
+#define CONFIG_ENCODERS 0
+#define CONFIG_HWACCELS 0
+#define CONFIG_PARSERS 1
+#define CONFIG_INDEVS 0
+#define CONFIG_OUTDEVS 0
+#define CONFIG_FILTERS 0
+#define CONFIG_DEMUXERS 0
+#define CONFIG_MUXERS 0
+#define CONFIG_PROTOCOLS 0
#define CONFIG_AANDCTTABLES 0
#define CONFIG_AC3DSP 0
#define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -581,20 +595,22 @@
#define CONFIG_FMTCONVERT 0
#define CONFIG_FRAME_THREAD_ENCODER 0
#define CONFIG_G722DSP 0
-#define CONFIG_GOLOMB 1
+#define CONFIG_GOLOMB 0
#define CONFIG_GPLV3 0
#define CONFIG_H263DSP 0
#define CONFIG_H264CHROMA 0
#define CONFIG_H264DSP 0
+#define CONFIG_H264PARSE 0
#define CONFIG_H264PRED 1
#define CONFIG_H264QPEL 0
+#define CONFIG_HEVCPARSE 0
#define CONFIG_HPELDSP 0
#define CONFIG_HUFFMAN 0
#define CONFIG_HUFFYUVDSP 0
#define CONFIG_HUFFYUVENCDSP 0
#define CONFIG_IDCTDSP 0
#define CONFIG_IIRFILTER 0
-#define CONFIG_IMDCT15 0
+#define CONFIG_MDCT15 0
#define CONFIG_INTRAX8 0
#define CONFIG_ISO_MEDIA 0
#define CONFIG_IVIDSP 0
@@ -603,12 +619,14 @@
#define CONFIG_LIBX262 0
#define CONFIG_LLAUDDSP 0
#define CONFIG_LLVIDDSP 0
+#define CONFIG_LLVIDENCDSP 0
#define CONFIG_LPC 0
#define CONFIG_LZF 0
#define CONFIG_ME_CMP 0
#define CONFIG_MPEG_ER 0
#define CONFIG_MPEGAUDIO 0
#define CONFIG_MPEGAUDIODSP 0
+#define CONFIG_MPEGAUDIOHEADER 0
#define CONFIG_MPEGVIDEO 0
#define CONFIG_MPEGVIDEOENC 0
#define CONFIG_MSS34DSP 0
@@ -630,1595 +648,20 @@
#define CONFIG_TEXTUREDSP 0
#define CONFIG_TEXTUREDSPENC 0
#define CONFIG_TPELDSP 0
+#define CONFIG_VAAPI_1 0
#define CONFIG_VAAPI_ENCODE 0
#define CONFIG_VC1DSP 0
#define CONFIG_VIDEODSP 1
#define CONFIG_VP3DSP 0
#define CONFIG_VP56DSP 0
#define CONFIG_VP8DSP 1
-#define CONFIG_VT_BT2020 0
#define CONFIG_WMA_FREQS 0
#define CONFIG_WMV2DSP 0
-#define CONFIG_AAC_ADTSTOASC_BSF 0
-#define CONFIG_CHOMP_BSF 0
-#define CONFIG_DUMP_EXTRADATA_BSF 0
-#define CONFIG_DCA_CORE_BSF 0
-#define CONFIG_H264_MP4TOANNEXB_BSF 0
-#define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-#define CONFIG_IMX_DUMP_HEADER_BSF 0
-#define CONFIG_MJPEG2JPEG_BSF 0
-#define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-#define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-#define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-#define CONFIG_MOV2TEXTSUB_BSF 0
-#define CONFIG_NOISE_BSF 0
-#define CONFIG_REMOVE_EXTRADATA_BSF 0
-#define CONFIG_TEXT2MOVSUB_BSF 0
-#define CONFIG_VP9_SUPERFRAME_BSF 0
-#define CONFIG_AASC_DECODER 0
-#define CONFIG_AIC_DECODER 0
-#define CONFIG_ALIAS_PIX_DECODER 0
-#define CONFIG_AMV_DECODER 0
-#define CONFIG_ANM_DECODER 0
-#define CONFIG_ANSI_DECODER 0
-#define CONFIG_APNG_DECODER 0
-#define CONFIG_ASV1_DECODER 0
-#define CONFIG_ASV2_DECODER 0
-#define CONFIG_AURA_DECODER 0
-#define CONFIG_AURA2_DECODER 0
-#define CONFIG_AVRP_DECODER 0
-#define CONFIG_AVRN_DECODER 0
-#define CONFIG_AVS_DECODER 0
-#define CONFIG_AVUI_DECODER 0
-#define CONFIG_AYUV_DECODER 0
-#define CONFIG_BETHSOFTVID_DECODER 0
-#define CONFIG_BFI_DECODER 0
-#define CONFIG_BINK_DECODER 0
-#define CONFIG_BMP_DECODER 0
-#define CONFIG_BMV_VIDEO_DECODER 0
-#define CONFIG_BRENDER_PIX_DECODER 0
-#define CONFIG_C93_DECODER 0
-#define CONFIG_CAVS_DECODER 0
-#define CONFIG_CDGRAPHICS_DECODER 0
-#define CONFIG_CDXL_DECODER 0
-#define CONFIG_CFHD_DECODER 0
-#define CONFIG_CINEPAK_DECODER 0
-#define CONFIG_CLJR_DECODER 0
-#define CONFIG_CLLC_DECODER 0
-#define CONFIG_COMFORTNOISE_DECODER 0
-#define CONFIG_CPIA_DECODER 0
-#define CONFIG_CSCD_DECODER 0
-#define CONFIG_CYUV_DECODER 0
-#define CONFIG_DDS_DECODER 0
-#define CONFIG_DFA_DECODER 0
-#define CONFIG_DIRAC_DECODER 0
-#define CONFIG_DNXHD_DECODER 0
-#define CONFIG_DPX_DECODER 0
-#define CONFIG_DSICINVIDEO_DECODER 0
-#define CONFIG_DVAUDIO_DECODER 0
-#define CONFIG_DVVIDEO_DECODER 0
-#define CONFIG_DXA_DECODER 0
-#define CONFIG_DXTORY_DECODER 0
-#define CONFIG_DXV_DECODER 0
-#define CONFIG_EACMV_DECODER 0
-#define CONFIG_EAMAD_DECODER 0
-#define CONFIG_EATGQ_DECODER 0
-#define CONFIG_EATGV_DECODER 0
-#define CONFIG_EATQI_DECODER 0
-#define CONFIG_EIGHTBPS_DECODER 0
-#define CONFIG_EIGHTSVX_EXP_DECODER 0
-#define CONFIG_EIGHTSVX_FIB_DECODER 0
-#define CONFIG_ESCAPE124_DECODER 0
-#define CONFIG_ESCAPE130_DECODER 0
-#define CONFIG_EXR_DECODER 0
-#define CONFIG_FFV1_DECODER 0
-#define CONFIG_FFVHUFF_DECODER 0
-#define CONFIG_FIC_DECODER 0
-#define CONFIG_FLASHSV_DECODER 0
-#define CONFIG_FLASHSV2_DECODER 0
-#define CONFIG_FLIC_DECODER 0
-#define CONFIG_FLV_DECODER 0
-#define CONFIG_FOURXM_DECODER 0
-#define CONFIG_FRAPS_DECODER 0
-#define CONFIG_FRWU_DECODER 0
-#define CONFIG_G2M_DECODER 0
-#define CONFIG_GIF_DECODER 0
-#define CONFIG_H261_DECODER 0
-#define CONFIG_H263_DECODER 0
-#define CONFIG_H263I_DECODER 0
-#define CONFIG_H263P_DECODER 0
-#define CONFIG_H264_DECODER 0
-#define CONFIG_H264_CRYSTALHD_DECODER 0
-#define CONFIG_H264_MEDIACODEC_DECODER 0
-#define CONFIG_H264_MMAL_DECODER 0
-#define CONFIG_H264_QSV_DECODER 0
-#define CONFIG_H264_VDA_DECODER 0
-#define CONFIG_H264_VDPAU_DECODER 0
-#define CONFIG_HAP_DECODER 0
-#define CONFIG_HEVC_DECODER 0
-#define CONFIG_HEVC_QSV_DECODER 0
-#define CONFIG_HNM4_VIDEO_DECODER 0
-#define CONFIG_HQ_HQA_DECODER 0
-#define CONFIG_HQX_DECODER 0
-#define CONFIG_HUFFYUV_DECODER 0
-#define CONFIG_IDCIN_DECODER 0
-#define CONFIG_IFF_ILBM_DECODER 0
-#define CONFIG_INDEO2_DECODER 0
-#define CONFIG_INDEO3_DECODER 0
-#define CONFIG_INDEO4_DECODER 0
-#define CONFIG_INDEO5_DECODER 0
-#define CONFIG_INTERPLAY_VIDEO_DECODER 0
-#define CONFIG_JPEG2000_DECODER 0
-#define CONFIG_JPEGLS_DECODER 0
-#define CONFIG_JV_DECODER 0
-#define CONFIG_KGV1_DECODER 0
-#define CONFIG_KMVC_DECODER 0
-#define CONFIG_LAGARITH_DECODER 0
-#define CONFIG_LOCO_DECODER 0
-#define CONFIG_M101_DECODER 0
-#define CONFIG_MAGICYUV_DECODER 0
-#define CONFIG_MDEC_DECODER 0
-#define CONFIG_MIMIC_DECODER 0
-#define CONFIG_MJPEG_DECODER 0
-#define CONFIG_MJPEGB_DECODER 0
-#define CONFIG_MMVIDEO_DECODER 0
-#define CONFIG_MOTIONPIXELS_DECODER 0
-#define CONFIG_MPEG_XVMC_DECODER 0
-#define CONFIG_MPEG1VIDEO_DECODER 0
-#define CONFIG_MPEG2VIDEO_DECODER 0
-#define CONFIG_MPEG4_DECODER 0
-#define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG4_MMAL_DECODER 0
-#define CONFIG_MPEG4_VDPAU_DECODER 0
-#define CONFIG_MPEGVIDEO_DECODER 0
-#define CONFIG_MPEG_VDPAU_DECODER 0
-#define CONFIG_MPEG1_VDPAU_DECODER 0
-#define CONFIG_MPEG2_MMAL_DECODER 0
-#define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG2_QSV_DECODER 0
-#define CONFIG_MSA1_DECODER 0
-#define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MSMPEG4V1_DECODER 0
-#define CONFIG_MSMPEG4V2_DECODER 0
-#define CONFIG_MSMPEG4V3_DECODER 0
-#define CONFIG_MSRLE_DECODER 0
-#define CONFIG_MSS1_DECODER 0
-#define CONFIG_MSS2_DECODER 0
-#define CONFIG_MSVIDEO1_DECODER 0
-#define CONFIG_MSZH_DECODER 0
-#define CONFIG_MTS2_DECODER 0
-#define CONFIG_MVC1_DECODER 0
-#define CONFIG_MVC2_DECODER 0
-#define CONFIG_MXPEG_DECODER 0
-#define CONFIG_NUV_DECODER 0
-#define CONFIG_PAF_VIDEO_DECODER 0
-#define CONFIG_PAM_DECODER 0
-#define CONFIG_PBM_DECODER 0
-#define CONFIG_PCX_DECODER 0
-#define CONFIG_PGM_DECODER 0
-#define CONFIG_PGMYUV_DECODER 0
-#define CONFIG_PICTOR_DECODER 0
-#define CONFIG_PNG_DECODER 0
-#define CONFIG_PPM_DECODER 0
-#define CONFIG_PRORES_DECODER 0
-#define CONFIG_PRORES_LGPL_DECODER 0
-#define CONFIG_PTX_DECODER 0
-#define CONFIG_QDRAW_DECODER 0
-#define CONFIG_QPEG_DECODER 0
-#define CONFIG_QTRLE_DECODER 0
-#define CONFIG_R10K_DECODER 0
-#define CONFIG_R210_DECODER 0
-#define CONFIG_RAWVIDEO_DECODER 0
-#define CONFIG_RL2_DECODER 0
-#define CONFIG_ROQ_DECODER 0
-#define CONFIG_RPZA_DECODER 0
-#define CONFIG_RSCC_DECODER 0
-#define CONFIG_RV10_DECODER 0
-#define CONFIG_RV20_DECODER 0
-#define CONFIG_RV30_DECODER 0
-#define CONFIG_RV40_DECODER 0
-#define CONFIG_S302M_DECODER 0
-#define CONFIG_SANM_DECODER 0
-#define CONFIG_SCREENPRESSO_DECODER 0
-#define CONFIG_SDX2_DPCM_DECODER 0
-#define CONFIG_SGI_DECODER 0
-#define CONFIG_SGIRLE_DECODER 0
-#define CONFIG_SHEERVIDEO_DECODER 0
-#define CONFIG_SMACKER_DECODER 0
-#define CONFIG_SMC_DECODER 0
-#define CONFIG_SMVJPEG_DECODER 0
-#define CONFIG_SNOW_DECODER 0
-#define CONFIG_SP5X_DECODER 0
-#define CONFIG_SUNRAST_DECODER 0
-#define CONFIG_SVQ1_DECODER 0
-#define CONFIG_SVQ3_DECODER 0
-#define CONFIG_TARGA_DECODER 0
-#define CONFIG_TARGA_Y216_DECODER 0
-#define CONFIG_TDSC_DECODER 0
-#define CONFIG_THEORA_DECODER 0
-#define CONFIG_THP_DECODER 0
-#define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-#define CONFIG_TIFF_DECODER 0
-#define CONFIG_TMV_DECODER 0
-#define CONFIG_TRUEMOTION1_DECODER 0
-#define CONFIG_TRUEMOTION2_DECODER 0
-#define CONFIG_TRUEMOTION2RT_DECODER 0
-#define CONFIG_TSCC_DECODER 0
-#define CONFIG_TSCC2_DECODER 0
-#define CONFIG_TXD_DECODER 0
-#define CONFIG_ULTI_DECODER 0
-#define CONFIG_UTVIDEO_DECODER 0
-#define CONFIG_V210_DECODER 0
-#define CONFIG_V210X_DECODER 0
-#define CONFIG_V308_DECODER 0
-#define CONFIG_V408_DECODER 0
-#define CONFIG_V410_DECODER 0
-#define CONFIG_VB_DECODER 0
-#define CONFIG_VBLE_DECODER 0
-#define CONFIG_VC1_DECODER 0
-#define CONFIG_VC1_CRYSTALHD_DECODER 0
-#define CONFIG_VC1_VDPAU_DECODER 0
-#define CONFIG_VC1IMAGE_DECODER 0
-#define CONFIG_VC1_MMAL_DECODER 0
-#define CONFIG_VC1_QSV_DECODER 0
-#define CONFIG_VCR1_DECODER 0
-#define CONFIG_VMDVIDEO_DECODER 0
-#define CONFIG_VMNC_DECODER 0
-#define CONFIG_VP3_DECODER 0
-#define CONFIG_VP5_DECODER 0
-#define CONFIG_VP6_DECODER 0
-#define CONFIG_VP6A_DECODER 0
-#define CONFIG_VP6F_DECODER 0
-#define CONFIG_VP7_DECODER 0
+#define CONFIG_NULL_BSF 1
#define CONFIG_VP8_DECODER 1
#define CONFIG_VP9_DECODER 1
-#define CONFIG_VQA_DECODER 0
-#define CONFIG_WEBP_DECODER 0
-#define CONFIG_WMV1_DECODER 0
-#define CONFIG_WMV2_DECODER 0
-#define CONFIG_WMV3_DECODER 0
-#define CONFIG_WMV3_CRYSTALHD_DECODER 0
-#define CONFIG_WMV3_VDPAU_DECODER 0
-#define CONFIG_WMV3IMAGE_DECODER 0
-#define CONFIG_WNV1_DECODER 0
-#define CONFIG_XAN_WC3_DECODER 0
-#define CONFIG_XAN_WC4_DECODER 0
-#define CONFIG_XBM_DECODER 0
-#define CONFIG_XFACE_DECODER 0
-#define CONFIG_XL_DECODER 0
-#define CONFIG_XWD_DECODER 0
-#define CONFIG_Y41P_DECODER 0
-#define CONFIG_YLC_DECODER 0
-#define CONFIG_YOP_DECODER 0
-#define CONFIG_YUV4_DECODER 0
-#define CONFIG_ZERO12V_DECODER 0
-#define CONFIG_ZEROCODEC_DECODER 0
-#define CONFIG_ZLIB_DECODER 0
-#define CONFIG_ZMBV_DECODER 0
-#define CONFIG_AAC_DECODER 0
-#define CONFIG_AAC_FIXED_DECODER 0
-#define CONFIG_AAC_LATM_DECODER 0
-#define CONFIG_AC3_DECODER 0
-#define CONFIG_AC3_FIXED_DECODER 0
-#define CONFIG_ALAC_DECODER 0
-#define CONFIG_ALS_DECODER 0
-#define CONFIG_AMRNB_DECODER 0
-#define CONFIG_AMRWB_DECODER 0
-#define CONFIG_APE_DECODER 0
-#define CONFIG_ATRAC1_DECODER 0
-#define CONFIG_ATRAC3_DECODER 0
-#define CONFIG_ATRAC3P_DECODER 0
-#define CONFIG_BINKAUDIO_DCT_DECODER 0
-#define CONFIG_BINKAUDIO_RDFT_DECODER 0
-#define CONFIG_BMV_AUDIO_DECODER 0
-#define CONFIG_COOK_DECODER 0
-#define CONFIG_DCA_DECODER 0
-#define CONFIG_DSD_LSBF_DECODER 0
-#define CONFIG_DSD_MSBF_DECODER 0
-#define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-#define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-#define CONFIG_DSICINAUDIO_DECODER 0
-#define CONFIG_DSS_SP_DECODER 0
-#define CONFIG_DST_DECODER 0
-#define CONFIG_EAC3_DECODER 0
-#define CONFIG_EVRC_DECODER 0
-#define CONFIG_FFWAVESYNTH_DECODER 0
#define CONFIG_FLAC_DECODER 1
-#define CONFIG_G723_1_DECODER 0
-#define CONFIG_G729_DECODER 0
-#define CONFIG_GSM_DECODER 0
-#define CONFIG_GSM_MS_DECODER 0
-#define CONFIG_IAC_DECODER 0
-#define CONFIG_IMC_DECODER 0
-#define CONFIG_INTERPLAY_ACM_DECODER 0
-#define CONFIG_MACE3_DECODER 0
-#define CONFIG_MACE6_DECODER 0
-#define CONFIG_METASOUND_DECODER 0
-#define CONFIG_MLP_DECODER 0
-#define CONFIG_MP1_DECODER 0
-#define CONFIG_MP1FLOAT_DECODER 0
-#define CONFIG_MP2_DECODER 0
-#define CONFIG_MP2FLOAT_DECODER 0
-#define CONFIG_MP3_DECODER 0
-#define CONFIG_MP3FLOAT_DECODER 0
-#define CONFIG_MP3ADU_DECODER 0
-#define CONFIG_MP3ADUFLOAT_DECODER 0
-#define CONFIG_MP3ON4_DECODER 0
-#define CONFIG_MP3ON4FLOAT_DECODER 0
-#define CONFIG_MPC7_DECODER 0
-#define CONFIG_MPC8_DECODER 0
-#define CONFIG_NELLYMOSER_DECODER 0
-#define CONFIG_ON2AVC_DECODER 0
-#define CONFIG_OPUS_DECODER 0
-#define CONFIG_PAF_AUDIO_DECODER 0
-#define CONFIG_QCELP_DECODER 0
-#define CONFIG_QDM2_DECODER 0
-#define CONFIG_RA_144_DECODER 0
-#define CONFIG_RA_288_DECODER 0
-#define CONFIG_RALF_DECODER 0
-#define CONFIG_SHORTEN_DECODER 0
-#define CONFIG_SIPR_DECODER 0
-#define CONFIG_SMACKAUD_DECODER 0
-#define CONFIG_SONIC_DECODER 0
-#define CONFIG_TAK_DECODER 0
-#define CONFIG_TRUEHD_DECODER 0
-#define CONFIG_TRUESPEECH_DECODER 0
-#define CONFIG_TTA_DECODER 0
-#define CONFIG_TWINVQ_DECODER 0
-#define CONFIG_VMDAUDIO_DECODER 0
-#define CONFIG_VORBIS_DECODER 0
-#define CONFIG_WAVPACK_DECODER 0
-#define CONFIG_WMALOSSLESS_DECODER 0
-#define CONFIG_WMAPRO_DECODER 0
-#define CONFIG_WMAV1_DECODER 0
-#define CONFIG_WMAV2_DECODER 0
-#define CONFIG_WMAVOICE_DECODER 0
-#define CONFIG_WS_SND1_DECODER 0
-#define CONFIG_XMA1_DECODER 0
-#define CONFIG_XMA2_DECODER 0
-#define CONFIG_PCM_ALAW_DECODER 0
-#define CONFIG_PCM_BLURAY_DECODER 0
-#define CONFIG_PCM_DVD_DECODER 0
-#define CONFIG_PCM_F32BE_DECODER 0
-#define CONFIG_PCM_F32LE_DECODER 0
-#define CONFIG_PCM_F64BE_DECODER 0
-#define CONFIG_PCM_F64LE_DECODER 0
-#define CONFIG_PCM_LXF_DECODER 0
-#define CONFIG_PCM_MULAW_DECODER 0
-#define CONFIG_PCM_S8_DECODER 0
-#define CONFIG_PCM_S8_PLANAR_DECODER 0
-#define CONFIG_PCM_S16BE_DECODER 0
-#define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-#define CONFIG_PCM_S16LE_DECODER 0
-#define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S24BE_DECODER 0
-#define CONFIG_PCM_S24DAUD_DECODER 0
-#define CONFIG_PCM_S24LE_DECODER 0
-#define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S32BE_DECODER 0
-#define CONFIG_PCM_S32LE_DECODER 0
-#define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S64BE_DECODER 0
-#define CONFIG_PCM_S64LE_DECODER 0
-#define CONFIG_PCM_U8_DECODER 0
-#define CONFIG_PCM_U16BE_DECODER 0
-#define CONFIG_PCM_U16LE_DECODER 0
-#define CONFIG_PCM_U24BE_DECODER 0
-#define CONFIG_PCM_U24LE_DECODER 0
-#define CONFIG_PCM_U32BE_DECODER 0
-#define CONFIG_PCM_U32LE_DECODER 0
-#define CONFIG_PCM_ZORK_DECODER 0
-#define CONFIG_INTERPLAY_DPCM_DECODER 0
-#define CONFIG_ROQ_DPCM_DECODER 0
-#define CONFIG_SOL_DPCM_DECODER 0
-#define CONFIG_XAN_DPCM_DECODER 0
-#define CONFIG_ADPCM_4XM_DECODER 0
-#define CONFIG_ADPCM_ADX_DECODER 0
-#define CONFIG_ADPCM_AFC_DECODER 0
-#define CONFIG_ADPCM_AICA_DECODER 0
-#define CONFIG_ADPCM_CT_DECODER 0
-#define CONFIG_ADPCM_DTK_DECODER 0
-#define CONFIG_ADPCM_EA_DECODER 0
-#define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-#define CONFIG_ADPCM_EA_R1_DECODER 0
-#define CONFIG_ADPCM_EA_R2_DECODER 0
-#define CONFIG_ADPCM_EA_R3_DECODER 0
-#define CONFIG_ADPCM_EA_XAS_DECODER 0
-#define CONFIG_ADPCM_G722_DECODER 0
-#define CONFIG_ADPCM_G726_DECODER 0
-#define CONFIG_ADPCM_G726LE_DECODER 0
-#define CONFIG_ADPCM_IMA_AMV_DECODER 0
-#define CONFIG_ADPCM_IMA_APC_DECODER 0
-#define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-#define CONFIG_ADPCM_IMA_DK3_DECODER 0
-#define CONFIG_ADPCM_IMA_DK4_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-#define CONFIG_ADPCM_IMA_ISS_DECODER 0
-#define CONFIG_ADPCM_IMA_OKI_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_DECODER 0
-#define CONFIG_ADPCM_IMA_RAD_DECODER 0
-#define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-#define CONFIG_ADPCM_IMA_WAV_DECODER 0
-#define CONFIG_ADPCM_IMA_WS_DECODER 0
-#define CONFIG_ADPCM_MS_DECODER 0
-#define CONFIG_ADPCM_MTAF_DECODER 0
-#define CONFIG_ADPCM_PSX_DECODER 0
-#define CONFIG_ADPCM_SBPRO_2_DECODER 0
-#define CONFIG_ADPCM_SBPRO_3_DECODER 0
-#define CONFIG_ADPCM_SBPRO_4_DECODER 0
-#define CONFIG_ADPCM_SWF_DECODER 0
-#define CONFIG_ADPCM_THP_DECODER 0
-#define CONFIG_ADPCM_THP_LE_DECODER 0
-#define CONFIG_ADPCM_VIMA_DECODER 0
-#define CONFIG_ADPCM_XA_DECODER 0
-#define CONFIG_ADPCM_YAMAHA_DECODER 0
-#define CONFIG_SSA_DECODER 0
-#define CONFIG_ASS_DECODER 0
-#define CONFIG_CCAPTION_DECODER 0
-#define CONFIG_DVBSUB_DECODER 0
-#define CONFIG_DVDSUB_DECODER 0
-#define CONFIG_JACOSUB_DECODER 0
-#define CONFIG_MICRODVD_DECODER 0
-#define CONFIG_MOVTEXT_DECODER 0
-#define CONFIG_MPL2_DECODER 0
-#define CONFIG_PGSSUB_DECODER 0
-#define CONFIG_PJS_DECODER 0
-#define CONFIG_REALTEXT_DECODER 0
-#define CONFIG_SAMI_DECODER 0
-#define CONFIG_SRT_DECODER 0
-#define CONFIG_STL_DECODER 0
-#define CONFIG_SUBRIP_DECODER 0
-#define CONFIG_SUBVIEWER_DECODER 0
-#define CONFIG_SUBVIEWER1_DECODER 0
-#define CONFIG_TEXT_DECODER 0
-#define CONFIG_VPLAYER_DECODER 0
-#define CONFIG_WEBVTT_DECODER 0
-#define CONFIG_XSUB_DECODER 0
-#define CONFIG_AAC_AT_DECODER 0
-#define CONFIG_AC3_AT_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-#define CONFIG_ALAC_AT_DECODER 0
-#define CONFIG_AMR_NB_AT_DECODER 0
-#define CONFIG_EAC3_AT_DECODER 0
-#define CONFIG_GSM_MS_AT_DECODER 0
-#define CONFIG_ILBC_AT_DECODER 0
-#define CONFIG_MP1_AT_DECODER 0
-#define CONFIG_MP2_AT_DECODER 0
-#define CONFIG_MP3_AT_DECODER 0
-#define CONFIG_PCM_ALAW_AT_DECODER 0
-#define CONFIG_PCM_MULAW_AT_DECODER 0
-#define CONFIG_QDMC_AT_DECODER 0
-#define CONFIG_QDM2_AT_DECODER 0
-#define CONFIG_LIBCELT_DECODER 0
-#define CONFIG_LIBFDK_AAC_DECODER 0
-#define CONFIG_LIBGSM_DECODER 0
-#define CONFIG_LIBGSM_MS_DECODER 0
-#define CONFIG_LIBILBC_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-#define CONFIG_LIBOPENJPEG_DECODER 0
-#define CONFIG_LIBOPUS_DECODER 0
-#define CONFIG_LIBSCHROEDINGER_DECODER 0
-#define CONFIG_LIBSPEEX_DECODER 0
-#define CONFIG_LIBVORBIS_DECODER 0
-#define CONFIG_LIBVPX_VP8_DECODER 0
-#define CONFIG_LIBVPX_VP9_DECODER 0
-#define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-#define CONFIG_BINTEXT_DECODER 0
-#define CONFIG_XBIN_DECODER 0
-#define CONFIG_IDF_DECODER 0
-#define CONFIG_LIBOPENH264_DECODER 0
-#define CONFIG_H263_CUVID_DECODER 0
-#define CONFIG_H264_CUVID_DECODER 0
-#define CONFIG_HEVC_CUVID_DECODER 0
-#define CONFIG_HEVC_MEDIACODEC_DECODER 0
-#define CONFIG_MJPEG_CUVID_DECODER 0
-#define CONFIG_MPEG1_CUVID_DECODER 0
-#define CONFIG_MPEG2_CUVID_DECODER 0
-#define CONFIG_MPEG4_CUVID_DECODER 0
-#define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-#define CONFIG_VC1_CUVID_DECODER 0
-#define CONFIG_VP8_CUVID_DECODER 0
-#define CONFIG_VP8_MEDIACODEC_DECODER 0
-#define CONFIG_VP9_CUVID_DECODER 0
-#define CONFIG_VP9_MEDIACODEC_DECODER 0
-#define CONFIG_AA_DEMUXER 0
-#define CONFIG_AAC_DEMUXER 0
-#define CONFIG_AC3_DEMUXER 0
-#define CONFIG_ACM_DEMUXER 0
-#define CONFIG_ACT_DEMUXER 0
-#define CONFIG_ADF_DEMUXER 0
-#define CONFIG_ADP_DEMUXER 0
-#define CONFIG_ADS_DEMUXER 0
-#define CONFIG_ADX_DEMUXER 0
-#define CONFIG_AEA_DEMUXER 0
-#define CONFIG_AFC_DEMUXER 0
-#define CONFIG_AIFF_DEMUXER 0
-#define CONFIG_AIX_DEMUXER 0
-#define CONFIG_AMR_DEMUXER 0
-#define CONFIG_ANM_DEMUXER 0
-#define CONFIG_APC_DEMUXER 0
-#define CONFIG_APE_DEMUXER 0
-#define CONFIG_APNG_DEMUXER 0
-#define CONFIG_AQTITLE_DEMUXER 0
-#define CONFIG_ASF_DEMUXER 0
-#define CONFIG_ASF_O_DEMUXER 0
-#define CONFIG_ASS_DEMUXER 0
-#define CONFIG_AST_DEMUXER 0
-#define CONFIG_AU_DEMUXER 0
-#define CONFIG_AVI_DEMUXER 0
-#define CONFIG_AVISYNTH_DEMUXER 0
-#define CONFIG_AVR_DEMUXER 0
-#define CONFIG_AVS_DEMUXER 0
-#define CONFIG_BETHSOFTVID_DEMUXER 0
-#define CONFIG_BFI_DEMUXER 0
-#define CONFIG_BINTEXT_DEMUXER 0
-#define CONFIG_BINK_DEMUXER 0
-#define CONFIG_BIT_DEMUXER 0
-#define CONFIG_BMV_DEMUXER 0
-#define CONFIG_BFSTM_DEMUXER 0
-#define CONFIG_BRSTM_DEMUXER 0
-#define CONFIG_BOA_DEMUXER 0
-#define CONFIG_C93_DEMUXER 0
-#define CONFIG_CAF_DEMUXER 0
-#define CONFIG_CAVSVIDEO_DEMUXER 0
-#define CONFIG_CDG_DEMUXER 0
-#define CONFIG_CDXL_DEMUXER 0
-#define CONFIG_CINE_DEMUXER 0
-#define CONFIG_CONCAT_DEMUXER 0
-#define CONFIG_DATA_DEMUXER 0
-#define CONFIG_DAUD_DEMUXER 0
-#define CONFIG_DCSTR_DEMUXER 0
-#define CONFIG_DFA_DEMUXER 0
-#define CONFIG_DIRAC_DEMUXER 0
-#define CONFIG_DNXHD_DEMUXER 0
-#define CONFIG_DSF_DEMUXER 0
-#define CONFIG_DSICIN_DEMUXER 0
-#define CONFIG_DSS_DEMUXER 0
-#define CONFIG_DTS_DEMUXER 0
-#define CONFIG_DTSHD_DEMUXER 0
-#define CONFIG_DV_DEMUXER 0
-#define CONFIG_DVBSUB_DEMUXER 0
-#define CONFIG_DVBTXT_DEMUXER 0
-#define CONFIG_DXA_DEMUXER 0
-#define CONFIG_EA_DEMUXER 0
-#define CONFIG_EA_CDATA_DEMUXER 0
-#define CONFIG_EAC3_DEMUXER 0
-#define CONFIG_EPAF_DEMUXER 0
-#define CONFIG_FFM_DEMUXER 0
-#define CONFIG_FFMETADATA_DEMUXER 0
-#define CONFIG_FILMSTRIP_DEMUXER 0
-#define CONFIG_FLAC_DEMUXER 0
-#define CONFIG_FLIC_DEMUXER 0
-#define CONFIG_FLV_DEMUXER 0
-#define CONFIG_LIVE_FLV_DEMUXER 0
-#define CONFIG_FOURXM_DEMUXER 0
-#define CONFIG_FRM_DEMUXER 0
-#define CONFIG_FSB_DEMUXER 0
-#define CONFIG_G722_DEMUXER 0
-#define CONFIG_G723_1_DEMUXER 0
-#define CONFIG_G729_DEMUXER 0
-#define CONFIG_GENH_DEMUXER 0
-#define CONFIG_GIF_DEMUXER 0
-#define CONFIG_GSM_DEMUXER 0
-#define CONFIG_GXF_DEMUXER 0
-#define CONFIG_H261_DEMUXER 0
-#define CONFIG_H263_DEMUXER 0
-#define CONFIG_H264_DEMUXER 0
-#define CONFIG_HEVC_DEMUXER 0
-#define CONFIG_HLS_DEMUXER 0
-#define CONFIG_HNM_DEMUXER 0
-#define CONFIG_ICO_DEMUXER 0
-#define CONFIG_IDCIN_DEMUXER 0
-#define CONFIG_IDF_DEMUXER 0
-#define CONFIG_IFF_DEMUXER 0
-#define CONFIG_ILBC_DEMUXER 0
-#define CONFIG_IMAGE2_DEMUXER 0
-#define CONFIG_IMAGE2PIPE_DEMUXER 0
-#define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-#define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-#define CONFIG_INGENIENT_DEMUXER 0
-#define CONFIG_IPMOVIE_DEMUXER 0
-#define CONFIG_IRCAM_DEMUXER 0
-#define CONFIG_ISS_DEMUXER 0
-#define CONFIG_IV8_DEMUXER 0
-#define CONFIG_IVF_DEMUXER 0
-#define CONFIG_IVR_DEMUXER 0
-#define CONFIG_JACOSUB_DEMUXER 0
-#define CONFIG_JV_DEMUXER 0
-#define CONFIG_LMLM4_DEMUXER 0
-#define CONFIG_LOAS_DEMUXER 0
-#define CONFIG_LRC_DEMUXER 0
-#define CONFIG_LVF_DEMUXER 0
-#define CONFIG_LXF_DEMUXER 0
-#define CONFIG_M4V_DEMUXER 0
-#define CONFIG_MATROSKA_DEMUXER 0
-#define CONFIG_MGSTS_DEMUXER 0
-#define CONFIG_MICRODVD_DEMUXER 0
-#define CONFIG_MJPEG_DEMUXER 0
-#define CONFIG_MLP_DEMUXER 0
-#define CONFIG_MLV_DEMUXER 0
-#define CONFIG_MM_DEMUXER 0
-#define CONFIG_MMF_DEMUXER 0
-#define CONFIG_MOV_DEMUXER 0
-#define CONFIG_MP3_DEMUXER 0
-#define CONFIG_MPC_DEMUXER 0
-#define CONFIG_MPC8_DEMUXER 0
-#define CONFIG_MPEGPS_DEMUXER 0
-#define CONFIG_MPEGTS_DEMUXER 0
-#define CONFIG_MPEGTSRAW_DEMUXER 0
-#define CONFIG_MPEGVIDEO_DEMUXER 0
-#define CONFIG_MPJPEG_DEMUXER 0
-#define CONFIG_MPL2_DEMUXER 0
-#define CONFIG_MPSUB_DEMUXER 0
-#define CONFIG_MSF_DEMUXER 0
-#define CONFIG_MSNWC_TCP_DEMUXER 0
-#define CONFIG_MTAF_DEMUXER 0
-#define CONFIG_MTV_DEMUXER 0
-#define CONFIG_MUSX_DEMUXER 0
-#define CONFIG_MV_DEMUXER 0
-#define CONFIG_MVI_DEMUXER 0
-#define CONFIG_MXF_DEMUXER 0
-#define CONFIG_MXG_DEMUXER 0
-#define CONFIG_NC_DEMUXER 0
-#define CONFIG_NISTSPHERE_DEMUXER 0
-#define CONFIG_NSV_DEMUXER 0
-#define CONFIG_NUT_DEMUXER 0
-#define CONFIG_NUV_DEMUXER 0
-#define CONFIG_OGG_DEMUXER 0
-#define CONFIG_OMA_DEMUXER 0
-#define CONFIG_PAF_DEMUXER 0
-#define CONFIG_PCM_ALAW_DEMUXER 0
-#define CONFIG_PCM_MULAW_DEMUXER 0
-#define CONFIG_PCM_F64BE_DEMUXER 0
-#define CONFIG_PCM_F64LE_DEMUXER 0
-#define CONFIG_PCM_F32BE_DEMUXER 0
-#define CONFIG_PCM_F32LE_DEMUXER 0
-#define CONFIG_PCM_S32BE_DEMUXER 0
-#define CONFIG_PCM_S32LE_DEMUXER 0
-#define CONFIG_PCM_S24BE_DEMUXER 0
-#define CONFIG_PCM_S24LE_DEMUXER 0
-#define CONFIG_PCM_S16BE_DEMUXER 0
-#define CONFIG_PCM_S16LE_DEMUXER 0
-#define CONFIG_PCM_S8_DEMUXER 0
-#define CONFIG_PCM_U32BE_DEMUXER 0
-#define CONFIG_PCM_U32LE_DEMUXER 0
-#define CONFIG_PCM_U24BE_DEMUXER 0
-#define CONFIG_PCM_U24LE_DEMUXER 0
-#define CONFIG_PCM_U16BE_DEMUXER 0
-#define CONFIG_PCM_U16LE_DEMUXER 0
-#define CONFIG_PCM_U8_DEMUXER 0
-#define CONFIG_PJS_DEMUXER 0
-#define CONFIG_PMP_DEMUXER 0
-#define CONFIG_PVA_DEMUXER 0
-#define CONFIG_PVF_DEMUXER 0
-#define CONFIG_QCP_DEMUXER 0
-#define CONFIG_R3D_DEMUXER 0
-#define CONFIG_RAWVIDEO_DEMUXER 0
-#define CONFIG_REALTEXT_DEMUXER 0
-#define CONFIG_REDSPARK_DEMUXER 0
-#define CONFIG_RL2_DEMUXER 0
-#define CONFIG_RM_DEMUXER 0
-#define CONFIG_ROQ_DEMUXER 0
-#define CONFIG_RPL_DEMUXER 0
-#define CONFIG_RSD_DEMUXER 0
-#define CONFIG_RSO_DEMUXER 0
-#define CONFIG_RTP_DEMUXER 0
-#define CONFIG_RTSP_DEMUXER 0
-#define CONFIG_SAMI_DEMUXER 0
-#define CONFIG_SAP_DEMUXER 0
-#define CONFIG_SBG_DEMUXER 0
-#define CONFIG_SDP_DEMUXER 0
-#define CONFIG_SDR2_DEMUXER 0
-#define CONFIG_SEGAFILM_DEMUXER 0
-#define CONFIG_SHORTEN_DEMUXER 0
-#define CONFIG_SIFF_DEMUXER 0
-#define CONFIG_SLN_DEMUXER 0
-#define CONFIG_SMACKER_DEMUXER 0
-#define CONFIG_SMJPEG_DEMUXER 0
-#define CONFIG_SMUSH_DEMUXER 0
-#define CONFIG_SOL_DEMUXER 0
-#define CONFIG_SOX_DEMUXER 0
-#define CONFIG_SPDIF_DEMUXER 0
-#define CONFIG_SRT_DEMUXER 0
-#define CONFIG_STR_DEMUXER 0
-#define CONFIG_STL_DEMUXER 0
-#define CONFIG_SUBVIEWER1_DEMUXER 0
-#define CONFIG_SUBVIEWER_DEMUXER 0
-#define CONFIG_SUP_DEMUXER 0
-#define CONFIG_SVAG_DEMUXER 0
-#define CONFIG_SWF_DEMUXER 0
-#define CONFIG_TAK_DEMUXER 0
-#define CONFIG_TEDCAPTIONS_DEMUXER 0
-#define CONFIG_THP_DEMUXER 0
-#define CONFIG_THREEDOSTR_DEMUXER 0
-#define CONFIG_TIERTEXSEQ_DEMUXER 0
-#define CONFIG_TMV_DEMUXER 0
-#define CONFIG_TRUEHD_DEMUXER 0
-#define CONFIG_TTA_DEMUXER 0
-#define CONFIG_TXD_DEMUXER 0
-#define CONFIG_TTY_DEMUXER 0
-#define CONFIG_V210_DEMUXER 0
-#define CONFIG_V210X_DEMUXER 0
-#define CONFIG_VAG_DEMUXER 0
-#define CONFIG_VC1_DEMUXER 0
-#define CONFIG_VC1T_DEMUXER 0
-#define CONFIG_VIVO_DEMUXER 0
-#define CONFIG_VMD_DEMUXER 0
-#define CONFIG_VOBSUB_DEMUXER 0
-#define CONFIG_VOC_DEMUXER 0
-#define CONFIG_VPK_DEMUXER 0
-#define CONFIG_VPLAYER_DEMUXER 0
-#define CONFIG_VQF_DEMUXER 0
-#define CONFIG_W64_DEMUXER 0
-#define CONFIG_WAV_DEMUXER 0
-#define CONFIG_WC3_DEMUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-#define CONFIG_WEBVTT_DEMUXER 0
-#define CONFIG_WSAUD_DEMUXER 0
-#define CONFIG_WSD_DEMUXER 0
-#define CONFIG_WSVQA_DEMUXER 0
-#define CONFIG_WTV_DEMUXER 0
-#define CONFIG_WVE_DEMUXER 0
-#define CONFIG_WV_DEMUXER 0
-#define CONFIG_XA_DEMUXER 0
-#define CONFIG_XBIN_DEMUXER 0
-#define CONFIG_XMV_DEMUXER 0
-#define CONFIG_XVAG_DEMUXER 0
-#define CONFIG_XWMA_DEMUXER 0
-#define CONFIG_YOP_DEMUXER 0
-#define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-#define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-#define CONFIG_LIBGME_DEMUXER 0
-#define CONFIG_LIBMODPLUG_DEMUXER 0
-#define CONFIG_LIBNUT_DEMUXER 0
-#define CONFIG_LIBOPENMPT_DEMUXER 0
-#define CONFIG_A64MULTI_ENCODER 0
-#define CONFIG_A64MULTI5_ENCODER 0
-#define CONFIG_ALIAS_PIX_ENCODER 0
-#define CONFIG_AMV_ENCODER 0
-#define CONFIG_APNG_ENCODER 0
-#define CONFIG_ASV1_ENCODER 0
-#define CONFIG_ASV2_ENCODER 0
-#define CONFIG_AVRP_ENCODER 0
-#define CONFIG_AVUI_ENCODER 0
-#define CONFIG_AYUV_ENCODER 0
-#define CONFIG_BMP_ENCODER 0
-#define CONFIG_CINEPAK_ENCODER 0
-#define CONFIG_CLJR_ENCODER 0
-#define CONFIG_COMFORTNOISE_ENCODER 0
-#define CONFIG_DNXHD_ENCODER 0
-#define CONFIG_DPX_ENCODER 0
-#define CONFIG_DVVIDEO_ENCODER 0
-#define CONFIG_FFV1_ENCODER 0
-#define CONFIG_FFVHUFF_ENCODER 0
-#define CONFIG_FLASHSV_ENCODER 0
-#define CONFIG_FLASHSV2_ENCODER 0
-#define CONFIG_FLV_ENCODER 0
-#define CONFIG_GIF_ENCODER 0
-#define CONFIG_H261_ENCODER 0
-#define CONFIG_H263_ENCODER 0
-#define CONFIG_H263P_ENCODER 0
-#define CONFIG_HAP_ENCODER 0
-#define CONFIG_HUFFYUV_ENCODER 0
-#define CONFIG_JPEG2000_ENCODER 0
-#define CONFIG_JPEGLS_ENCODER 0
-#define CONFIG_LJPEG_ENCODER 0
-#define CONFIG_MJPEG_ENCODER 0
-#define CONFIG_MPEG1VIDEO_ENCODER 0
-#define CONFIG_MPEG2VIDEO_ENCODER 0
-#define CONFIG_MPEG4_ENCODER 0
-#define CONFIG_MSMPEG4V2_ENCODER 0
-#define CONFIG_MSMPEG4V3_ENCODER 0
-#define CONFIG_MSVIDEO1_ENCODER 0
-#define CONFIG_PAM_ENCODER 0
-#define CONFIG_PBM_ENCODER 0
-#define CONFIG_PCX_ENCODER 0
-#define CONFIG_PGM_ENCODER 0
-#define CONFIG_PGMYUV_ENCODER 0
-#define CONFIG_PNG_ENCODER 0
-#define CONFIG_PPM_ENCODER 0
-#define CONFIG_PRORES_ENCODER 0
-#define CONFIG_PRORES_AW_ENCODER 0
-#define CONFIG_PRORES_KS_ENCODER 0
-#define CONFIG_QTRLE_ENCODER 0
-#define CONFIG_R10K_ENCODER 0
-#define CONFIG_R210_ENCODER 0
-#define CONFIG_RAWVIDEO_ENCODER 0
-#define CONFIG_ROQ_ENCODER 0
-#define CONFIG_RV10_ENCODER 0
-#define CONFIG_RV20_ENCODER 0
-#define CONFIG_S302M_ENCODER 0
-#define CONFIG_SGI_ENCODER 0
-#define CONFIG_SNOW_ENCODER 0
-#define CONFIG_SUNRAST_ENCODER 0
-#define CONFIG_SVQ1_ENCODER 0
-#define CONFIG_TARGA_ENCODER 0
-#define CONFIG_TIFF_ENCODER 0
-#define CONFIG_UTVIDEO_ENCODER 0
-#define CONFIG_V210_ENCODER 0
-#define CONFIG_V308_ENCODER 0
-#define CONFIG_V408_ENCODER 0
-#define CONFIG_V410_ENCODER 0
-#define CONFIG_VC2_ENCODER 0
-#define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-#define CONFIG_WMV1_ENCODER 0
-#define CONFIG_WMV2_ENCODER 0
-#define CONFIG_XBM_ENCODER 0
-#define CONFIG_XFACE_ENCODER 0
-#define CONFIG_XWD_ENCODER 0
-#define CONFIG_Y41P_ENCODER 0
-#define CONFIG_YUV4_ENCODER 0
-#define CONFIG_ZLIB_ENCODER 0
-#define CONFIG_ZMBV_ENCODER 0
-#define CONFIG_AAC_ENCODER 0
-#define CONFIG_AC3_ENCODER 0
-#define CONFIG_AC3_FIXED_ENCODER 0
-#define CONFIG_ALAC_ENCODER 0
-#define CONFIG_DCA_ENCODER 0
-#define CONFIG_EAC3_ENCODER 0
-#define CONFIG_FLAC_ENCODER 0
-#define CONFIG_G723_1_ENCODER 0
-#define CONFIG_MLP_ENCODER 0
-#define CONFIG_MP2_ENCODER 0
-#define CONFIG_MP2FIXED_ENCODER 0
-#define CONFIG_NELLYMOSER_ENCODER 0
-#define CONFIG_RA_144_ENCODER 0
-#define CONFIG_SONIC_ENCODER 0
-#define CONFIG_SONIC_LS_ENCODER 0
-#define CONFIG_TRUEHD_ENCODER 0
-#define CONFIG_TTA_ENCODER 0
-#define CONFIG_VORBIS_ENCODER 0
-#define CONFIG_WAVPACK_ENCODER 0
-#define CONFIG_WMAV1_ENCODER 0
-#define CONFIG_WMAV2_ENCODER 0
-#define CONFIG_PCM_ALAW_ENCODER 0
-#define CONFIG_PCM_F32BE_ENCODER 0
-#define CONFIG_PCM_F32LE_ENCODER 0
-#define CONFIG_PCM_F64BE_ENCODER 0
-#define CONFIG_PCM_F64LE_ENCODER 0
-#define CONFIG_PCM_MULAW_ENCODER 0
-#define CONFIG_PCM_S8_ENCODER 0
-#define CONFIG_PCM_S8_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16BE_ENCODER 0
-#define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16LE_ENCODER 0
-#define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S24BE_ENCODER 0
-#define CONFIG_PCM_S24DAUD_ENCODER 0
-#define CONFIG_PCM_S24LE_ENCODER 0
-#define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S32BE_ENCODER 0
-#define CONFIG_PCM_S32LE_ENCODER 0
-#define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S64BE_ENCODER 0
-#define CONFIG_PCM_S64LE_ENCODER 0
-#define CONFIG_PCM_U8_ENCODER 0
-#define CONFIG_PCM_U16BE_ENCODER 0
-#define CONFIG_PCM_U16LE_ENCODER 0
-#define CONFIG_PCM_U24BE_ENCODER 0
-#define CONFIG_PCM_U24LE_ENCODER 0
-#define CONFIG_PCM_U32BE_ENCODER 0
-#define CONFIG_PCM_U32LE_ENCODER 0
-#define CONFIG_ROQ_DPCM_ENCODER 0
-#define CONFIG_ADPCM_ADX_ENCODER 0
-#define CONFIG_ADPCM_G722_ENCODER 0
-#define CONFIG_ADPCM_G726_ENCODER 0
-#define CONFIG_ADPCM_IMA_QT_ENCODER 0
-#define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-#define CONFIG_ADPCM_MS_ENCODER 0
-#define CONFIG_ADPCM_SWF_ENCODER 0
-#define CONFIG_ADPCM_YAMAHA_ENCODER 0
-#define CONFIG_SSA_ENCODER 0
-#define CONFIG_ASS_ENCODER 0
-#define CONFIG_DVBSUB_ENCODER 0
-#define CONFIG_DVDSUB_ENCODER 0
-#define CONFIG_MOVTEXT_ENCODER 0
-#define CONFIG_SRT_ENCODER 0
-#define CONFIG_SUBRIP_ENCODER 0
-#define CONFIG_TEXT_ENCODER 0
-#define CONFIG_WEBVTT_ENCODER 0
-#define CONFIG_XSUB_ENCODER 0
-#define CONFIG_AAC_AT_ENCODER 0
-#define CONFIG_ALAC_AT_ENCODER 0
-#define CONFIG_ILBC_AT_ENCODER 0
-#define CONFIG_PCM_ALAW_AT_ENCODER 0
-#define CONFIG_PCM_MULAW_AT_ENCODER 0
-#define CONFIG_LIBFDK_AAC_ENCODER 0
-#define CONFIG_LIBGSM_ENCODER 0
-#define CONFIG_LIBGSM_MS_ENCODER 0
-#define CONFIG_LIBILBC_ENCODER 0
-#define CONFIG_LIBMP3LAME_ENCODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-#define CONFIG_LIBOPENJPEG_ENCODER 0
-#define CONFIG_LIBOPUS_ENCODER 0
-#define CONFIG_LIBSCHROEDINGER_ENCODER 0
-#define CONFIG_LIBSHINE_ENCODER 0
-#define CONFIG_LIBSPEEX_ENCODER 0
-#define CONFIG_LIBTHEORA_ENCODER 0
-#define CONFIG_LIBTWOLAME_ENCODER 0
-#define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-#define CONFIG_LIBVORBIS_ENCODER 0
-#define CONFIG_LIBVPX_VP8_ENCODER 0
-#define CONFIG_LIBVPX_VP9_ENCODER 0
-#define CONFIG_LIBWAVPACK_ENCODER 0
-#define CONFIG_LIBWEBP_ANIM_ENCODER 0
-#define CONFIG_LIBWEBP_ENCODER 0
-#define CONFIG_LIBX262_ENCODER 0
-#define CONFIG_LIBX264_ENCODER 0
-#define CONFIG_LIBX264RGB_ENCODER 0
-#define CONFIG_LIBX265_ENCODER 0
-#define CONFIG_LIBXAVS_ENCODER 0
-#define CONFIG_LIBXVID_ENCODER 0
-#define CONFIG_LIBOPENH264_ENCODER 0
-#define CONFIG_H264_NVENC_ENCODER 0
-#define CONFIG_H264_OMX_ENCODER 0
-#define CONFIG_H264_QSV_ENCODER 0
-#define CONFIG_H264_VAAPI_ENCODER 0
-#define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-#define CONFIG_NVENC_ENCODER 0
-#define CONFIG_NVENC_H264_ENCODER 0
-#define CONFIG_NVENC_HEVC_ENCODER 0
-#define CONFIG_HEVC_NVENC_ENCODER 0
-#define CONFIG_HEVC_QSV_ENCODER 0
-#define CONFIG_HEVC_VAAPI_ENCODER 0
-#define CONFIG_LIBKVAZAAR_ENCODER 0
-#define CONFIG_MJPEG_VAAPI_ENCODER 0
-#define CONFIG_MPEG2_QSV_ENCODER 0
-#define CONFIG_ABENCH_FILTER 0
-#define CONFIG_ACOMPRESSOR_FILTER 0
-#define CONFIG_ACROSSFADE_FILTER 0
-#define CONFIG_ACRUSHER_FILTER 0
-#define CONFIG_ADELAY_FILTER 0
-#define CONFIG_AECHO_FILTER 0
-#define CONFIG_AEMPHASIS_FILTER 0
-#define CONFIG_AEVAL_FILTER 0
-#define CONFIG_AFADE_FILTER 0
-#define CONFIG_AFFTFILT_FILTER 0
-#define CONFIG_AFORMAT_FILTER 0
-#define CONFIG_AGATE_FILTER 0
-#define CONFIG_AINTERLEAVE_FILTER 0
-#define CONFIG_ALIMITER_FILTER 0
-#define CONFIG_ALLPASS_FILTER 0
-#define CONFIG_ALOOP_FILTER 0
-#define CONFIG_AMERGE_FILTER 0
-#define CONFIG_AMETADATA_FILTER 0
-#define CONFIG_AMIX_FILTER 0
-#define CONFIG_ANEQUALIZER_FILTER 0
-#define CONFIG_ANULL_FILTER 0
-#define CONFIG_APAD_FILTER 0
-#define CONFIG_APERMS_FILTER 0
-#define CONFIG_APHASER_FILTER 0
-#define CONFIG_APULSATOR_FILTER 0
-#define CONFIG_AREALTIME_FILTER 0
-#define CONFIG_ARESAMPLE_FILTER 0
-#define CONFIG_AREVERSE_FILTER 0
-#define CONFIG_ASELECT_FILTER 0
-#define CONFIG_ASENDCMD_FILTER 0
-#define CONFIG_ASETNSAMPLES_FILTER 0
-#define CONFIG_ASETPTS_FILTER 0
-#define CONFIG_ASETRATE_FILTER 0
-#define CONFIG_ASETTB_FILTER 0
-#define CONFIG_ASHOWINFO_FILTER 0
-#define CONFIG_ASIDEDATA_FILTER 0
-#define CONFIG_ASPLIT_FILTER 0
-#define CONFIG_ASTATS_FILTER 0
-#define CONFIG_ASTREAMSELECT_FILTER 0
-#define CONFIG_ASYNCTS_FILTER 0
-#define CONFIG_ATEMPO_FILTER 0
-#define CONFIG_ATRIM_FILTER 0
-#define CONFIG_AZMQ_FILTER 0
-#define CONFIG_BANDPASS_FILTER 0
-#define CONFIG_BANDREJECT_FILTER 0
-#define CONFIG_BASS_FILTER 0
-#define CONFIG_BIQUAD_FILTER 0
-#define CONFIG_BS2B_FILTER 0
-#define CONFIG_CHANNELMAP_FILTER 0
-#define CONFIG_CHANNELSPLIT_FILTER 0
-#define CONFIG_CHORUS_FILTER 0
-#define CONFIG_COMPAND_FILTER 0
-#define CONFIG_COMPENSATIONDELAY_FILTER 0
-#define CONFIG_CRYSTALIZER_FILTER 0
-#define CONFIG_DCSHIFT_FILTER 0
-#define CONFIG_DYNAUDNORM_FILTER 0
-#define CONFIG_EARWAX_FILTER 0
-#define CONFIG_EBUR128_FILTER 0
-#define CONFIG_EQUALIZER_FILTER 0
-#define CONFIG_EXTRASTEREO_FILTER 0
-#define CONFIG_FIREQUALIZER_FILTER 0
-#define CONFIG_FLANGER_FILTER 0
-#define CONFIG_HDCD_FILTER 0
-#define CONFIG_HIGHPASS_FILTER 0
-#define CONFIG_JOIN_FILTER 0
-#define CONFIG_LADSPA_FILTER 0
-#define CONFIG_LOUDNORM_FILTER 0
-#define CONFIG_LOWPASS_FILTER 0
-#define CONFIG_PAN_FILTER 0
-#define CONFIG_REPLAYGAIN_FILTER 0
-#define CONFIG_RESAMPLE_FILTER 0
-#define CONFIG_RUBBERBAND_FILTER 0
-#define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-#define CONFIG_SIDECHAINGATE_FILTER 0
-#define CONFIG_SILENCEDETECT_FILTER 0
-#define CONFIG_SILENCEREMOVE_FILTER 0
-#define CONFIG_SOFALIZER_FILTER 0
-#define CONFIG_STEREOTOOLS_FILTER 0
-#define CONFIG_STEREOWIDEN_FILTER 0
-#define CONFIG_TREBLE_FILTER 0
-#define CONFIG_TREMOLO_FILTER 0
-#define CONFIG_VIBRATO_FILTER 0
-#define CONFIG_VOLUME_FILTER 0
-#define CONFIG_VOLUMEDETECT_FILTER 0
-#define CONFIG_AEVALSRC_FILTER 0
-#define CONFIG_ANOISESRC_FILTER 0
-#define CONFIG_ANULLSRC_FILTER 0
-#define CONFIG_FLITE_FILTER 0
-#define CONFIG_SINE_FILTER 0
-#define CONFIG_ANULLSINK_FILTER 0
-#define CONFIG_ALPHAEXTRACT_FILTER 0
-#define CONFIG_ALPHAMERGE_FILTER 0
-#define CONFIG_ASS_FILTER 0
-#define CONFIG_ATADENOISE_FILTER 0
-#define CONFIG_AVGBLUR_FILTER 0
-#define CONFIG_BBOX_FILTER 0
-#define CONFIG_BENCH_FILTER 0
-#define CONFIG_BITPLANENOISE_FILTER 0
-#define CONFIG_BLACKDETECT_FILTER 0
-#define CONFIG_BLACKFRAME_FILTER 0
-#define CONFIG_BLEND_FILTER 0
-#define CONFIG_BOXBLUR_FILTER 0
-#define CONFIG_BWDIF_FILTER 0
-#define CONFIG_CHROMAKEY_FILTER 0
-#define CONFIG_CIESCOPE_FILTER 0
-#define CONFIG_CODECVIEW_FILTER 0
-#define CONFIG_COLORBALANCE_FILTER 0
-#define CONFIG_COLORCHANNELMIXER_FILTER 0
-#define CONFIG_COLORKEY_FILTER 0
-#define CONFIG_COLORLEVELS_FILTER 0
-#define CONFIG_COLORMATRIX_FILTER 0
-#define CONFIG_COLORSPACE_FILTER 0
-#define CONFIG_CONVOLUTION_FILTER 0
-#define CONFIG_COPY_FILTER 0
-#define CONFIG_COREIMAGE_FILTER 0
-#define CONFIG_COVER_RECT_FILTER 0
-#define CONFIG_CROP_FILTER 0
-#define CONFIG_CROPDETECT_FILTER 0
-#define CONFIG_CURVES_FILTER 0
-#define CONFIG_DATASCOPE_FILTER 0
-#define CONFIG_DCTDNOIZ_FILTER 0
-#define CONFIG_DEBAND_FILTER 0
-#define CONFIG_DECIMATE_FILTER 0
-#define CONFIG_DEFLATE_FILTER 0
-#define CONFIG_DEJUDDER_FILTER 0
-#define CONFIG_DELOGO_FILTER 0
-#define CONFIG_DESHAKE_FILTER 0
-#define CONFIG_DETELECINE_FILTER 0
-#define CONFIG_DILATION_FILTER 0
-#define CONFIG_DISPLACE_FILTER 0
-#define CONFIG_DRAWBOX_FILTER 0
-#define CONFIG_DRAWGRAPH_FILTER 0
-#define CONFIG_DRAWGRID_FILTER 0
-#define CONFIG_DRAWTEXT_FILTER 0
-#define CONFIG_EDGEDETECT_FILTER 0
-#define CONFIG_ELBG_FILTER 0
-#define CONFIG_EQ_FILTER 0
-#define CONFIG_EROSION_FILTER 0
-#define CONFIG_EXTRACTPLANES_FILTER 0
-#define CONFIG_FADE_FILTER 0
-#define CONFIG_FFTFILT_FILTER 0
-#define CONFIG_FIELD_FILTER 0
-#define CONFIG_FIELDHINT_FILTER 0
-#define CONFIG_FIELDMATCH_FILTER 0
-#define CONFIG_FIELDORDER_FILTER 0
-#define CONFIG_FIND_RECT_FILTER 0
-#define CONFIG_FORMAT_FILTER 0
-#define CONFIG_FPS_FILTER 0
-#define CONFIG_FRAMEPACK_FILTER 0
-#define CONFIG_FRAMERATE_FILTER 0
-#define CONFIG_FRAMESTEP_FILTER 0
-#define CONFIG_FREI0R_FILTER 0
-#define CONFIG_FSPP_FILTER 0
-#define CONFIG_GBLUR_FILTER 0
-#define CONFIG_GEQ_FILTER 0
-#define CONFIG_GRADFUN_FILTER 0
-#define CONFIG_HALDCLUT_FILTER 0
-#define CONFIG_HFLIP_FILTER 0
-#define CONFIG_HISTEQ_FILTER 0
-#define CONFIG_HISTOGRAM_FILTER 0
-#define CONFIG_HQDN3D_FILTER 0
-#define CONFIG_HQX_FILTER 0
-#define CONFIG_HSTACK_FILTER 0
-#define CONFIG_HUE_FILTER 0
-#define CONFIG_HWDOWNLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_CUDA_FILTER 0
-#define CONFIG_HYSTERESIS_FILTER 0
-#define CONFIG_IDET_FILTER 0
-#define CONFIG_IL_FILTER 0
-#define CONFIG_INFLATE_FILTER 0
-#define CONFIG_INTERLACE_FILTER 0
-#define CONFIG_INTERLEAVE_FILTER 0
-#define CONFIG_KERNDEINT_FILTER 0
-#define CONFIG_LENSCORRECTION_FILTER 0
-#define CONFIG_LOOP_FILTER 0
-#define CONFIG_LUT_FILTER 0
-#define CONFIG_LUT2_FILTER 0
-#define CONFIG_LUT3D_FILTER 0
-#define CONFIG_LUTRGB_FILTER 0
-#define CONFIG_LUTYUV_FILTER 0
-#define CONFIG_MASKEDCLAMP_FILTER 0
-#define CONFIG_MASKEDMERGE_FILTER 0
-#define CONFIG_MCDEINT_FILTER 0
-#define CONFIG_MERGEPLANES_FILTER 0
-#define CONFIG_MESTIMATE_FILTER 0
-#define CONFIG_METADATA_FILTER 0
-#define CONFIG_MINTERPOLATE_FILTER 0
-#define CONFIG_MPDECIMATE_FILTER 0
-#define CONFIG_NEGATE_FILTER 0
-#define CONFIG_NLMEANS_FILTER 0
-#define CONFIG_NNEDI_FILTER 0
-#define CONFIG_NOFORMAT_FILTER 0
-#define CONFIG_NOISE_FILTER 0
-#define CONFIG_NULL_FILTER 0
-#define CONFIG_OCR_FILTER 0
-#define CONFIG_OCV_FILTER 0
-#define CONFIG_OVERLAY_FILTER 0
-#define CONFIG_OWDENOISE_FILTER 0
-#define CONFIG_PAD_FILTER 0
-#define CONFIG_PALETTEGEN_FILTER 0
-#define CONFIG_PALETTEUSE_FILTER 0
-#define CONFIG_PERMS_FILTER 0
-#define CONFIG_PERSPECTIVE_FILTER 0
-#define CONFIG_PHASE_FILTER 0
-#define CONFIG_PIXDESCTEST_FILTER 0
-#define CONFIG_PP_FILTER 0
-#define CONFIG_PP7_FILTER 0
-#define CONFIG_PREWITT_FILTER 0
-#define CONFIG_PSNR_FILTER 0
-#define CONFIG_PULLUP_FILTER 0
-#define CONFIG_QP_FILTER 0
-#define CONFIG_RANDOM_FILTER 0
-#define CONFIG_READVITC_FILTER 0
-#define CONFIG_REALTIME_FILTER 0
-#define CONFIG_REMAP_FILTER 0
-#define CONFIG_REMOVEGRAIN_FILTER 0
-#define CONFIG_REMOVELOGO_FILTER 0
-#define CONFIG_REPEATFIELDS_FILTER 0
-#define CONFIG_REVERSE_FILTER 0
-#define CONFIG_ROTATE_FILTER 0
-#define CONFIG_SAB_FILTER 0
-#define CONFIG_SCALE_FILTER 0
-#define CONFIG_SCALE_NPP_FILTER 0
-#define CONFIG_SCALE_VAAPI_FILTER 0
-#define CONFIG_SCALE2REF_FILTER 0
-#define CONFIG_SELECT_FILTER 0
-#define CONFIG_SELECTIVECOLOR_FILTER 0
-#define CONFIG_SENDCMD_FILTER 0
-#define CONFIG_SEPARATEFIELDS_FILTER 0
-#define CONFIG_SETDAR_FILTER 0
-#define CONFIG_SETFIELD_FILTER 0
-#define CONFIG_SETPTS_FILTER 0
-#define CONFIG_SETSAR_FILTER 0
-#define CONFIG_SETTB_FILTER 0
-#define CONFIG_SHOWINFO_FILTER 0
-#define CONFIG_SHOWPALETTE_FILTER 0
-#define CONFIG_SHUFFLEFRAMES_FILTER 0
-#define CONFIG_SHUFFLEPLANES_FILTER 0
-#define CONFIG_SIDEDATA_FILTER 0
-#define CONFIG_SIGNALSTATS_FILTER 0
-#define CONFIG_SMARTBLUR_FILTER 0
-#define CONFIG_SOBEL_FILTER 0
-#define CONFIG_SPLIT_FILTER 0
-#define CONFIG_SPP_FILTER 0
-#define CONFIG_SSIM_FILTER 0
-#define CONFIG_STEREO3D_FILTER 0
-#define CONFIG_STREAMSELECT_FILTER 0
-#define CONFIG_SUBTITLES_FILTER 0
-#define CONFIG_SUPER2XSAI_FILTER 0
-#define CONFIG_SWAPRECT_FILTER 0
-#define CONFIG_SWAPUV_FILTER 0
-#define CONFIG_TBLEND_FILTER 0
-#define CONFIG_TELECINE_FILTER 0
-#define CONFIG_THUMBNAIL_FILTER 0
-#define CONFIG_TILE_FILTER 0
-#define CONFIG_TINTERLACE_FILTER 0
-#define CONFIG_TRANSPOSE_FILTER 0
-#define CONFIG_TRIM_FILTER 0
-#define CONFIG_UNSHARP_FILTER 0
-#define CONFIG_USPP_FILTER 0
-#define CONFIG_VAGUEDENOISER_FILTER 0
-#define CONFIG_VECTORSCOPE_FILTER 0
-#define CONFIG_VFLIP_FILTER 0
-#define CONFIG_VIDSTABDETECT_FILTER 0
-#define CONFIG_VIDSTABTRANSFORM_FILTER 0
-#define CONFIG_VIGNETTE_FILTER 0
-#define CONFIG_VSTACK_FILTER 0
-#define CONFIG_W3FDIF_FILTER 0
-#define CONFIG_WAVEFORM_FILTER 0
-#define CONFIG_WEAVE_FILTER 0
-#define CONFIG_XBR_FILTER 0
-#define CONFIG_YADIF_FILTER 0
-#define CONFIG_ZMQ_FILTER 0
-#define CONFIG_ZOOMPAN_FILTER 0
-#define CONFIG_ZSCALE_FILTER 0
-#define CONFIG_ALLRGB_FILTER 0
-#define CONFIG_ALLYUV_FILTER 0
-#define CONFIG_CELLAUTO_FILTER 0
-#define CONFIG_COLOR_FILTER 0
-#define CONFIG_COREIMAGESRC_FILTER 0
-#define CONFIG_FREI0R_SRC_FILTER 0
-#define CONFIG_HALDCLUTSRC_FILTER 0
-#define CONFIG_LIFE_FILTER 0
-#define CONFIG_MANDELBROT_FILTER 0
-#define CONFIG_MPTESTSRC_FILTER 0
-#define CONFIG_NULLSRC_FILTER 0
-#define CONFIG_RGBTESTSRC_FILTER 0
-#define CONFIG_SMPTEBARS_FILTER 0
-#define CONFIG_SMPTEHDBARS_FILTER 0
-#define CONFIG_TESTSRC_FILTER 0
-#define CONFIG_TESTSRC2_FILTER 0
-#define CONFIG_YUVTESTSRC_FILTER 0
-#define CONFIG_NULLSINK_FILTER 0
-#define CONFIG_ADRAWGRAPH_FILTER 0
-#define CONFIG_AHISTOGRAM_FILTER 0
-#define CONFIG_APHASEMETER_FILTER 0
-#define CONFIG_AVECTORSCOPE_FILTER 0
-#define CONFIG_CONCAT_FILTER 0
-#define CONFIG_SHOWCQT_FILTER 0
-#define CONFIG_SHOWFREQS_FILTER 0
-#define CONFIG_SHOWSPECTRUM_FILTER 0
-#define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-#define CONFIG_SHOWVOLUME_FILTER 0
-#define CONFIG_SHOWWAVES_FILTER 0
-#define CONFIG_SHOWWAVESPIC_FILTER 0
-#define CONFIG_SPECTRUMSYNTH_FILTER 0
-#define CONFIG_AMOVIE_FILTER 0
-#define CONFIG_MOVIE_FILTER 0
-#define CONFIG_H263_CUVID_HWACCEL 0
-#define CONFIG_H263_VAAPI_HWACCEL 0
-#define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_H264_CUVID_HWACCEL 0
-#define CONFIG_H264_D3D11VA_HWACCEL 0
-#define CONFIG_H264_DXVA2_HWACCEL 0
-#define CONFIG_H264_MEDIACODEC_HWACCEL 0
-#define CONFIG_H264_MMAL_HWACCEL 0
-#define CONFIG_H264_QSV_HWACCEL 0
-#define CONFIG_H264_VAAPI_HWACCEL 0
-#define CONFIG_H264_VDA_HWACCEL 0
-#define CONFIG_H264_VDA_OLD_HWACCEL 0
-#define CONFIG_H264_VDPAU_HWACCEL 0
-#define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_HEVC_CUVID_HWACCEL 0
-#define CONFIG_HEVC_D3D11VA_HWACCEL 0
-#define CONFIG_HEVC_DXVA2_HWACCEL 0
-#define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-#define CONFIG_HEVC_QSV_HWACCEL 0
-#define CONFIG_HEVC_VAAPI_HWACCEL 0
-#define CONFIG_HEVC_VDPAU_HWACCEL 0
-#define CONFIG_MJPEG_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_XVMC_HWACCEL 0
-#define CONFIG_MPEG1_VDPAU_HWACCEL 0
-#define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG2_CUVID_HWACCEL 0
-#define CONFIG_MPEG2_XVMC_HWACCEL 0
-#define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-#define CONFIG_MPEG2_DXVA2_HWACCEL 0
-#define CONFIG_MPEG2_MMAL_HWACCEL 0
-#define CONFIG_MPEG2_QSV_HWACCEL 0
-#define CONFIG_MPEG2_VAAPI_HWACCEL 0
-#define CONFIG_MPEG2_VDPAU_HWACCEL 0
-#define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG4_CUVID_HWACCEL 0
-#define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-#define CONFIG_MPEG4_MMAL_HWACCEL 0
-#define CONFIG_MPEG4_VAAPI_HWACCEL 0
-#define CONFIG_MPEG4_VDPAU_HWACCEL 0
-#define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_VC1_CUVID_HWACCEL 0
-#define CONFIG_VC1_D3D11VA_HWACCEL 0
-#define CONFIG_VC1_DXVA2_HWACCEL 0
-#define CONFIG_VC1_VAAPI_HWACCEL 0
-#define CONFIG_VC1_VDPAU_HWACCEL 0
-#define CONFIG_VC1_MMAL_HWACCEL 0
-#define CONFIG_VC1_QSV_HWACCEL 0
-#define CONFIG_VP8_CUVID_HWACCEL 0
-#define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_CUVID_HWACCEL 0
-#define CONFIG_VP9_D3D11VA_HWACCEL 0
-#define CONFIG_VP9_DXVA2_HWACCEL 0
-#define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_D3D11VA_HWACCEL 0
-#define CONFIG_WMV3_DXVA2_HWACCEL 0
-#define CONFIG_WMV3_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_VDPAU_HWACCEL 0
-#define CONFIG_ALSA_INDEV 0
-#define CONFIG_AVFOUNDATION_INDEV 0
-#define CONFIG_BKTR_INDEV 0
-#define CONFIG_DECKLINK_INDEV 0
-#define CONFIG_DSHOW_INDEV 0
-#define CONFIG_DV1394_INDEV 0
-#define CONFIG_FBDEV_INDEV 0
-#define CONFIG_GDIGRAB_INDEV 0
-#define CONFIG_IEC61883_INDEV 0
-#define CONFIG_JACK_INDEV 0
-#define CONFIG_LAVFI_INDEV 0
-#define CONFIG_OPENAL_INDEV 0
-#define CONFIG_OSS_INDEV 0
-#define CONFIG_PULSE_INDEV 0
-#define CONFIG_QTKIT_INDEV 0
-#define CONFIG_SNDIO_INDEV 0
-#define CONFIG_V4L2_INDEV 0
-#define CONFIG_VFWCAP_INDEV 0
-#define CONFIG_X11GRAB_INDEV 0
-#define CONFIG_X11GRAB_XCB_INDEV 0
-#define CONFIG_LIBCDIO_INDEV 0
-#define CONFIG_LIBDC1394_INDEV 0
-#define CONFIG_A64_MUXER 0
-#define CONFIG_AC3_MUXER 0
-#define CONFIG_ADTS_MUXER 0
-#define CONFIG_ADX_MUXER 0
-#define CONFIG_AIFF_MUXER 0
-#define CONFIG_AMR_MUXER 0
-#define CONFIG_APNG_MUXER 0
-#define CONFIG_ASF_MUXER 0
-#define CONFIG_ASS_MUXER 0
-#define CONFIG_AST_MUXER 0
-#define CONFIG_ASF_STREAM_MUXER 0
-#define CONFIG_AU_MUXER 0
-#define CONFIG_AVI_MUXER 0
-#define CONFIG_AVM2_MUXER 0
-#define CONFIG_BIT_MUXER 0
-#define CONFIG_CAF_MUXER 0
-#define CONFIG_CAVSVIDEO_MUXER 0
-#define CONFIG_CRC_MUXER 0
-#define CONFIG_DASH_MUXER 0
-#define CONFIG_DATA_MUXER 0
-#define CONFIG_DAUD_MUXER 0
-#define CONFIG_DIRAC_MUXER 0
-#define CONFIG_DNXHD_MUXER 0
-#define CONFIG_DTS_MUXER 0
-#define CONFIG_DV_MUXER 0
-#define CONFIG_EAC3_MUXER 0
-#define CONFIG_F4V_MUXER 0
-#define CONFIG_FFM_MUXER 0
-#define CONFIG_FFMETADATA_MUXER 0
-#define CONFIG_FIFO_MUXER 0
-#define CONFIG_FILMSTRIP_MUXER 0
-#define CONFIG_FLAC_MUXER 0
-#define CONFIG_FLV_MUXER 0
-#define CONFIG_FRAMECRC_MUXER 0
-#define CONFIG_FRAMEHASH_MUXER 0
-#define CONFIG_FRAMEMD5_MUXER 0
-#define CONFIG_G722_MUXER 0
-#define CONFIG_G723_1_MUXER 0
-#define CONFIG_GIF_MUXER 0
-#define CONFIG_GSM_MUXER 0
-#define CONFIG_GXF_MUXER 0
-#define CONFIG_H261_MUXER 0
-#define CONFIG_H263_MUXER 0
-#define CONFIG_H264_MUXER 0
-#define CONFIG_HASH_MUXER 0
-#define CONFIG_HDS_MUXER 0
-#define CONFIG_HEVC_MUXER 0
-#define CONFIG_HLS_MUXER 0
-#define CONFIG_ICO_MUXER 0
-#define CONFIG_ILBC_MUXER 0
-#define CONFIG_IMAGE2_MUXER 0
-#define CONFIG_IMAGE2PIPE_MUXER 0
-#define CONFIG_IPOD_MUXER 0
-#define CONFIG_IRCAM_MUXER 0
-#define CONFIG_ISMV_MUXER 0
-#define CONFIG_IVF_MUXER 0
-#define CONFIG_JACOSUB_MUXER 0
-#define CONFIG_LATM_MUXER 0
-#define CONFIG_LRC_MUXER 0
-#define CONFIG_M4V_MUXER 0
-#define CONFIG_MD5_MUXER 0
-#define CONFIG_MATROSKA_MUXER 0
-#define CONFIG_MATROSKA_AUDIO_MUXER 0
-#define CONFIG_MICRODVD_MUXER 0
-#define CONFIG_MJPEG_MUXER 0
-#define CONFIG_MLP_MUXER 0
-#define CONFIG_MMF_MUXER 0
-#define CONFIG_MOV_MUXER 0
-#define CONFIG_MP2_MUXER 0
-#define CONFIG_MP3_MUXER 0
-#define CONFIG_MP4_MUXER 0
-#define CONFIG_MPEG1SYSTEM_MUXER 0
-#define CONFIG_MPEG1VCD_MUXER 0
-#define CONFIG_MPEG1VIDEO_MUXER 0
-#define CONFIG_MPEG2DVD_MUXER 0
-#define CONFIG_MPEG2SVCD_MUXER 0
-#define CONFIG_MPEG2VIDEO_MUXER 0
-#define CONFIG_MPEG2VOB_MUXER 0
-#define CONFIG_MPEGTS_MUXER 0
-#define CONFIG_MPJPEG_MUXER 0
-#define CONFIG_MXF_MUXER 0
-#define CONFIG_MXF_D10_MUXER 0
-#define CONFIG_MXF_OPATOM_MUXER 0
-#define CONFIG_NULL_MUXER 0
-#define CONFIG_NUT_MUXER 0
-#define CONFIG_OGA_MUXER 0
-#define CONFIG_OGG_MUXER 0
-#define CONFIG_OGV_MUXER 0
-#define CONFIG_OMA_MUXER 0
-#define CONFIG_OPUS_MUXER 0
-#define CONFIG_PCM_ALAW_MUXER 0
-#define CONFIG_PCM_MULAW_MUXER 0
-#define CONFIG_PCM_F64BE_MUXER 0
-#define CONFIG_PCM_F64LE_MUXER 0
-#define CONFIG_PCM_F32BE_MUXER 0
-#define CONFIG_PCM_F32LE_MUXER 0
-#define CONFIG_PCM_S32BE_MUXER 0
-#define CONFIG_PCM_S32LE_MUXER 0
-#define CONFIG_PCM_S24BE_MUXER 0
-#define CONFIG_PCM_S24LE_MUXER 0
-#define CONFIG_PCM_S16BE_MUXER 0
-#define CONFIG_PCM_S16LE_MUXER 0
-#define CONFIG_PCM_S8_MUXER 0
-#define CONFIG_PCM_U32BE_MUXER 0
-#define CONFIG_PCM_U32LE_MUXER 0
-#define CONFIG_PCM_U24BE_MUXER 0
-#define CONFIG_PCM_U24LE_MUXER 0
-#define CONFIG_PCM_U16BE_MUXER 0
-#define CONFIG_PCM_U16LE_MUXER 0
-#define CONFIG_PCM_U8_MUXER 0
-#define CONFIG_PSP_MUXER 0
-#define CONFIG_RAWVIDEO_MUXER 0
-#define CONFIG_RM_MUXER 0
-#define CONFIG_ROQ_MUXER 0
-#define CONFIG_RSO_MUXER 0
-#define CONFIG_RTP_MUXER 0
-#define CONFIG_RTP_MPEGTS_MUXER 0
-#define CONFIG_RTSP_MUXER 0
-#define CONFIG_SAP_MUXER 0
-#define CONFIG_SEGMENT_MUXER 0
-#define CONFIG_STREAM_SEGMENT_MUXER 0
-#define CONFIG_SINGLEJPEG_MUXER 0
-#define CONFIG_SMJPEG_MUXER 0
-#define CONFIG_SMOOTHSTREAMING_MUXER 0
-#define CONFIG_SOX_MUXER 0
-#define CONFIG_SPX_MUXER 0
-#define CONFIG_SPDIF_MUXER 0
-#define CONFIG_SRT_MUXER 0
-#define CONFIG_SWF_MUXER 0
-#define CONFIG_TEE_MUXER 0
-#define CONFIG_TG2_MUXER 0
-#define CONFIG_TGP_MUXER 0
-#define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-#define CONFIG_TRUEHD_MUXER 0
-#define CONFIG_TTA_MUXER 0
-#define CONFIG_UNCODEDFRAMECRC_MUXER 0
-#define CONFIG_VC1_MUXER 0
-#define CONFIG_VC1T_MUXER 0
-#define CONFIG_VOC_MUXER 0
-#define CONFIG_W64_MUXER 0
-#define CONFIG_WAV_MUXER 0
-#define CONFIG_WEBM_MUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-#define CONFIG_WEBM_CHUNK_MUXER 0
-#define CONFIG_WEBP_MUXER 0
-#define CONFIG_WEBVTT_MUXER 0
-#define CONFIG_WTV_MUXER 0
-#define CONFIG_WV_MUXER 0
-#define CONFIG_YUV4MPEGPIPE_MUXER 0
-#define CONFIG_CHROMAPRINT_MUXER 0
-#define CONFIG_LIBNUT_MUXER 0
-#define CONFIG_ALSA_OUTDEV 0
-#define CONFIG_CACA_OUTDEV 0
-#define CONFIG_DECKLINK_OUTDEV 0
-#define CONFIG_FBDEV_OUTDEV 0
-#define CONFIG_OPENGL_OUTDEV 0
-#define CONFIG_OSS_OUTDEV 0
-#define CONFIG_PULSE_OUTDEV 0
-#define CONFIG_SDL2_OUTDEV 0
-#define CONFIG_SNDIO_OUTDEV 0
-#define CONFIG_V4L2_OUTDEV 0
-#define CONFIG_XV_OUTDEV 0
-#define CONFIG_AAC_PARSER 0
-#define CONFIG_AAC_LATM_PARSER 0
-#define CONFIG_AC3_PARSER 0
-#define CONFIG_ADX_PARSER 0
-#define CONFIG_BMP_PARSER 0
-#define CONFIG_CAVSVIDEO_PARSER 0
-#define CONFIG_COOK_PARSER 0
-#define CONFIG_DCA_PARSER 0
-#define CONFIG_DIRAC_PARSER 0
-#define CONFIG_DNXHD_PARSER 0
-#define CONFIG_DPX_PARSER 0
-#define CONFIG_DVAUDIO_PARSER 0
-#define CONFIG_DVBSUB_PARSER 0
-#define CONFIG_DVDSUB_PARSER 0
-#define CONFIG_DVD_NAV_PARSER 0
-#define CONFIG_FLAC_PARSER 1
-#define CONFIG_G729_PARSER 0
-#define CONFIG_GSM_PARSER 0
-#define CONFIG_H261_PARSER 0
-#define CONFIG_H263_PARSER 0
-#define CONFIG_H264_PARSER 0
-#define CONFIG_HEVC_PARSER 0
-#define CONFIG_MJPEG_PARSER 0
-#define CONFIG_MLP_PARSER 0
-#define CONFIG_MPEG4VIDEO_PARSER 0
-#define CONFIG_MPEGAUDIO_PARSER 0
-#define CONFIG_MPEGVIDEO_PARSER 0
-#define CONFIG_OPUS_PARSER 0
-#define CONFIG_PNG_PARSER 0
-#define CONFIG_PNM_PARSER 0
-#define CONFIG_RV30_PARSER 0
-#define CONFIG_RV40_PARSER 0
-#define CONFIG_TAK_PARSER 0
-#define CONFIG_VC1_PARSER 0
-#define CONFIG_VORBIS_PARSER 0
-#define CONFIG_VP3_PARSER 0
+#define CONFIG_FLAC_PARSER 0
#define CONFIG_VP8_PARSER 1
#define CONFIG_VP9_PARSER 1
-#define CONFIG_ASYNC_PROTOCOL 0
-#define CONFIG_BLURAY_PROTOCOL 0
-#define CONFIG_CACHE_PROTOCOL 0
-#define CONFIG_CONCAT_PROTOCOL 0
-#define CONFIG_CRYPTO_PROTOCOL 0
-#define CONFIG_DATA_PROTOCOL 0
-#define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-#define CONFIG_FFRTMPHTTP_PROTOCOL 0
-#define CONFIG_FILE_PROTOCOL 0
-#define CONFIG_FTP_PROTOCOL 0
-#define CONFIG_GOPHER_PROTOCOL 0
-#define CONFIG_HLS_PROTOCOL 0
-#define CONFIG_HTTP_PROTOCOL 0
-#define CONFIG_HTTPPROXY_PROTOCOL 0
-#define CONFIG_HTTPS_PROTOCOL 0
-#define CONFIG_ICECAST_PROTOCOL 0
-#define CONFIG_MMSH_PROTOCOL 0
-#define CONFIG_MMST_PROTOCOL 0
-#define CONFIG_MD5_PROTOCOL 0
-#define CONFIG_PIPE_PROTOCOL 0
-#define CONFIG_RTMP_PROTOCOL 0
-#define CONFIG_RTMPE_PROTOCOL 0
-#define CONFIG_RTMPS_PROTOCOL 0
-#define CONFIG_RTMPT_PROTOCOL 0
-#define CONFIG_RTMPTE_PROTOCOL 0
-#define CONFIG_RTMPTS_PROTOCOL 0
-#define CONFIG_RTP_PROTOCOL 0
-#define CONFIG_SCTP_PROTOCOL 0
-#define CONFIG_SRTP_PROTOCOL 0
-#define CONFIG_SUBFILE_PROTOCOL 0
-#define CONFIG_TEE_PROTOCOL 0
-#define CONFIG_TCP_PROTOCOL 0
-#define CONFIG_TLS_GNUTLS_PROTOCOL 0
-#define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-#define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-#define CONFIG_TLS_OPENSSL_PROTOCOL 0
-#define CONFIG_UDP_PROTOCOL 0
-#define CONFIG_UDPLITE_PROTOCOL 0
-#define CONFIG_UNIX_PROTOCOL 0
-#define CONFIG_LIBRTMP_PROTOCOL 0
-#define CONFIG_LIBRTMPE_PROTOCOL 0
-#define CONFIG_LIBRTMPS_PROTOCOL 0
-#define CONFIG_LIBRTMPT_PROTOCOL 0
-#define CONFIG_LIBRTMPTE_PROTOCOL 0
-#define CONFIG_LIBSSH_PROTOCOL 0
-#define CONFIG_LIBSMBCLIENT_PROTOCOL 0
#endif /* FFMPEG_CONFIG_H */
diff --git a/media/ffvpx/config_win32.asm b/media/ffvpx/config_win32.asm
index 85eef2216..c804c0155 100644
--- a/media/ffvpx/config_win32.asm
+++ b/media/ffvpx/config_win32.asm
@@ -63,8 +63,8 @@
%define HAVE_MIPSDSP 0
%define HAVE_MIPSDSPR2 0
%define HAVE_MSA 0
-%define HAVE_LOONGSON2 1
-%define HAVE_LOONGSON3 1
+%define HAVE_LOONGSON2 0
+%define HAVE_LOONGSON3 0
%define HAVE_MMI 0
%define HAVE_ARMV5TE_EXTERNAL 0
%define HAVE_ARMV6_EXTERNAL 0
@@ -162,31 +162,32 @@
%define HAVE_LOCAL_ALIGNED_16 1
%define HAVE_LOCAL_ALIGNED_32 1
%define HAVE_SIMD_ALIGN_16 1
+%define HAVE_SIMD_ALIGN_32 1
%define HAVE_ATOMICS_GCC 0
%define HAVE_ATOMICS_SUNCC 0
%define HAVE_ATOMICS_WIN32 1
%define HAVE_ATOMIC_CAS_PTR 0
-%define HAVE_ATOMIC_COMPARE_EXCHANGE 0
%define HAVE_MACHINE_RW_BARRIER 0
%define HAVE_MEMORYBARRIER 1
%define HAVE_MM_EMPTY 1
%define HAVE_RDTSC 1
%define HAVE_SARESTART 0
-%define HAVE_SEM_TIMEDWAIT 1
+%define HAVE_SEM_TIMEDWAIT 0
%define HAVE_SYNC_VAL_COMPARE_AND_SWAP 0
%define HAVE_CABS 0
%define HAVE_CEXP 0
%define HAVE_INLINE_ASM 0
%define HAVE_SYMVER 0
-%define HAVE_YASM 1
+%define HAVE_X86ASM 1
%define HAVE_BIGENDIAN 0
%define HAVE_FAST_UNALIGNED 1
-%define HAVE_ALSA_ASOUNDLIB_H 0
%define HAVE_ALTIVEC_H 0
%define HAVE_ARPA_INET_H 0
%define HAVE_ASM_TYPES_H 0
%define HAVE_CDIO_PARANOIA_H 0
%define HAVE_CDIO_PARANOIA_PARANOIA_H 0
+%define HAVE_CUDA_H 0
+%define HAVE_D3D11_H 1
%define HAVE_DISPATCH_DISPATCH_H 0
%define HAVE_DEV_BKTR_IOCTL_BT848_H 0
%define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
@@ -196,7 +197,7 @@
%define HAVE_DIRECT_H 1
%define HAVE_DIRENT_H 0
%define HAVE_DLFCN_H 0
-%define HAVE_D3D11_H 1
+%define HAVE_DXGIDEBUG_H 1
%define HAVE_DXVA_H 1
%define HAVE_ES2_GL_H 0
%define HAVE_GSM_H 0
@@ -205,13 +206,15 @@
%define HAVE_MACHINE_IOCTL_BT848_H 0
%define HAVE_MACHINE_IOCTL_METEOR_H 0
%define HAVE_OPENCV2_CORE_CORE_C_H 0
+%define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+%define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
%define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
%define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
%define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
%define HAVE_OPENGL_GL3_H 0
%define HAVE_POLL_H 0
-%define HAVE_SNDIO_H 0
%define HAVE_SOUNDCARD_H 0
+%define HAVE_STDATOMIC_H 0
%define HAVE_SYS_MMAN_H 0
%define HAVE_SYS_PARAM_H 0
%define HAVE_SYS_RESOURCE_H 0
@@ -263,7 +266,6 @@
%define HAVE_COMMANDLINETOARGVW 1
%define HAVE_COTASKMEMFREE 1
%define HAVE_CRYPTGENRANDOM 1
-%define HAVE_DLOPEN 0
%define HAVE_FCNTL 0
%define HAVE_FLT_LIM 1
%define HAVE_FORK 0
@@ -283,7 +285,7 @@
%define HAVE_ISATTY 1
%define HAVE_JACK_PORT_GET_LATENCY_RANGE 0
%define HAVE_KBHIT 1
-%define HAVE_LOADLIBRARY 0
+%define HAVE_LOADLIBRARY 1
%define HAVE_LSTAT 0
%define HAVE_LZO1X_999_COMPRESS 0
%define HAVE_MACH_ABSOLUTE_TIME 0
@@ -311,11 +313,13 @@
%define HAVE_OS2THREADS 0
%define HAVE_W32THREADS 1
%define HAVE_AS_DN_DIRECTIVE 0
+%define HAVE_AS_FPU_DIRECTIVE 0
%define HAVE_AS_FUNC 0
%define HAVE_AS_OBJECT_ARCH 0
%define HAVE_ASM_MOD_Q 0
%define HAVE_ATTRIBUTE_MAY_ALIAS 0
%define HAVE_ATTRIBUTE_PACKED 0
+%define HAVE_BLOCKS_EXTENSION 0
%define HAVE_EBP_AVAILABLE 0
%define HAVE_EBX_AVAILABLE 0
%define HAVE_GNU_AS 0
@@ -332,12 +336,13 @@
%define HAVE_XFORM_ASM 0
%define HAVE_XMM_CLOBBERS 0
%define HAVE_CONDITION_VARIABLE_PTR 1
+%define HAVE_KCMVIDEOCODECTYPE_HEVC 0
%define HAVE_SOCKLEN_T 1
%define HAVE_STRUCT_ADDRINFO 1
%define HAVE_STRUCT_GROUP_SOURCE_REQ 1
%define HAVE_STRUCT_IP_MREQ_SOURCE 1
%define HAVE_STRUCT_IPV6_MREQ 1
-%define HAVE_STRUCT_MSGHDR_MSG_FLAGS 1
+%define HAVE_STRUCT_MSGHDR_MSG_FLAGS 0
%define HAVE_STRUCT_POLLFD 0
%define HAVE_STRUCT_RUSAGE_RU_MAXRSS 0
%define HAVE_STRUCT_SCTP_EVENT_SUBSCRIBE 0
@@ -348,36 +353,20 @@
%define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 0
%define HAVE_ATOMICS_NATIVE 1
%define HAVE_DOS_PATHS 1
-%define HAVE_DXVA2_LIB 0
-%define HAVE_DXVA2API_COBJ 1
%define HAVE_LIBC_MSVCRT 1
-%define HAVE_LIBDC1394_1 0
-%define HAVE_LIBDC1394_2 0
%define HAVE_MAKEINFO 1
%define HAVE_MAKEINFO_HTML 0
%define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
%define HAVE_PERL 1
%define HAVE_POD2MAN 1
-%define HAVE_SDL2 0
%define HAVE_SECTION_DATA_REL_RO 0
%define HAVE_TEXI2HTML 0
%define HAVE_THREADS 1
+%define HAVE_UWP 0
%define HAVE_VAAPI_DRM 0
%define HAVE_VAAPI_X11 0
%define HAVE_VDPAU_X11 0
%define HAVE_WINRT 0
-%define HAVE_XLIB 0
-%define CONFIG_BSFS 0
-%define CONFIG_DECODERS 1
-%define CONFIG_ENCODERS 0
-%define CONFIG_HWACCELS 0
-%define CONFIG_PARSERS 1
-%define CONFIG_INDEVS 0
-%define CONFIG_OUTDEVS 0
-%define CONFIG_FILTERS 0
-%define CONFIG_DEMUXERS 0
-%define CONFIG_MUXERS 0
-%define CONFIG_PROTOCOLS 0
%define CONFIG_DOC 0
%define CONFIG_HTMLPAGES 0
%define CONFIG_MANPAGES 1
@@ -385,13 +374,17 @@
%define CONFIG_TXTPAGES 1
%define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
%define CONFIG_AVIO_READING_EXAMPLE 1
-%define CONFIG_DECODING_ENCODING_EXAMPLE 0
+%define CONFIG_DECODE_AUDIO_EXAMPLE 1
+%define CONFIG_DECODE_VIDEO_EXAMPLE 1
%define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+%define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+%define CONFIG_ENCODE_VIDEO_EXAMPLE 1
%define CONFIG_EXTRACT_MVS_EXAMPLE 0
%define CONFIG_FILTER_AUDIO_EXAMPLE 0
%define CONFIG_FILTERING_AUDIO_EXAMPLE 0
%define CONFIG_FILTERING_VIDEO_EXAMPLE 0
%define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+%define CONFIG_HW_DECODE_EXAMPLE 0
%define CONFIG_METADATA_EXAMPLE 0
%define CONFIG_MUXING_EXAMPLE 0
%define CONFIG_QSVDEC_EXAMPLE 0
@@ -400,27 +393,55 @@
%define CONFIG_SCALING_VIDEO_EXAMPLE 0
%define CONFIG_TRANSCODE_AAC_EXAMPLE 0
%define CONFIG_TRANSCODING_EXAMPLE 0
-%define CONFIG_AVISYNTH 0
+%define CONFIG_ALSA 0
+%define CONFIG_APPKIT 0
+%define CONFIG_AVFOUNDATION 0
%define CONFIG_BZLIB 0
-%define CONFIG_CHROMAPRINT 0
-%define CONFIG_CRYSTALHD 0
-%define CONFIG_DECKLINK 0
+%define CONFIG_COREIMAGE 0
+%define CONFIG_ICONV 0
+%define CONFIG_JACK 0
+%define CONFIG_LIBXCB 0
+%define CONFIG_LIBXCB_SHM 0
+%define CONFIG_LIBXCB_SHAPE 0
+%define CONFIG_LIBXCB_XFIXES 0
+%define CONFIG_LZMA 0
+%define CONFIG_SCHANNEL 1
+%define CONFIG_SDL2 0
+%define CONFIG_SECURETRANSPORT 0
+%define CONFIG_SNDIO 0
+%define CONFIG_XLIB 1
+%define CONFIG_ZLIB 0
+%define CONFIG_AVISYNTH 0
%define CONFIG_FREI0R 0
-%define CONFIG_GCRYPT 0
+%define CONFIG_LIBCDIO 0
+%define CONFIG_LIBRUBBERBAND 0
+%define CONFIG_LIBVIDSTAB 0
+%define CONFIG_LIBX264 0
+%define CONFIG_LIBX265 0
+%define CONFIG_LIBXAVS 0
+%define CONFIG_LIBXVID 0
+%define CONFIG_DECKLINK 0
+%define CONFIG_LIBNDI_NEWTEK 0
+%define CONFIG_LIBFDK_AAC 0
+%define CONFIG_OPENSSL 0
%define CONFIG_GMP 0
+%define CONFIG_LIBOPENCORE_AMRNB 0
+%define CONFIG_LIBOPENCORE_AMRWB 0
+%define CONFIG_LIBVO_AMRWBENC 0
+%define CONFIG_RKMPP 0
+%define CONFIG_LIBSMBCLIENT 0
+%define CONFIG_CHROMAPRINT 0
+%define CONFIG_GCRYPT 0
%define CONFIG_GNUTLS 0
-%define CONFIG_ICONV 0
%define CONFIG_JNI 0
%define CONFIG_LADSPA 0
%define CONFIG_LIBASS 0
%define CONFIG_LIBBLURAY 0
%define CONFIG_LIBBS2B 0
%define CONFIG_LIBCACA 0
-%define CONFIG_LIBCDIO 0
%define CONFIG_LIBCELT 0
%define CONFIG_LIBDC1394 0
-%define CONFIG_LIBEBUR128 0
-%define CONFIG_LIBFDK_AAC 0
+%define CONFIG_LIBDRM 0
%define CONFIG_LIBFLITE 0
%define CONFIG_LIBFONTCONFIG 0
%define CONFIG_LIBFREETYPE 0
@@ -432,18 +453,15 @@
%define CONFIG_LIBKVAZAAR 0
%define CONFIG_LIBMODPLUG 0
%define CONFIG_LIBMP3LAME 0
-%define CONFIG_LIBNUT 0
-%define CONFIG_LIBOPENCORE_AMRNB 0
-%define CONFIG_LIBOPENCORE_AMRWB 0
+%define CONFIG_LIBMYSOFA 0
%define CONFIG_LIBOPENCV 0
%define CONFIG_LIBOPENH264 0
%define CONFIG_LIBOPENJPEG 0
%define CONFIG_LIBOPENMPT 0
%define CONFIG_LIBOPUS 0
%define CONFIG_LIBPULSE 0
+%define CONFIG_LIBRSVG 0
%define CONFIG_LIBRTMP 0
-%define CONFIG_LIBRUBBERBAND 0
-%define CONFIG_LIBSCHROEDINGER 0
%define CONFIG_LIBSHINE 0
%define CONFIG_LIBSMBCLIENT 0
%define CONFIG_LIBSNAPPY 0
@@ -454,53 +472,37 @@
%define CONFIG_LIBTHEORA 0
%define CONFIG_LIBTWOLAME 0
%define CONFIG_LIBV4L2 0
-%define CONFIG_LIBVIDSTAB 0
-%define CONFIG_LIBVO_AMRWBENC 0
+%define CONFIG_LIBVMAF 0
%define CONFIG_LIBVORBIS 0
%define CONFIG_LIBVPX 0
%define CONFIG_LIBWAVPACK 0
%define CONFIG_LIBWEBP 0
-%define CONFIG_LIBX264 0
-%define CONFIG_LIBX265 0
-%define CONFIG_LIBXAVS 0
-%define CONFIG_LIBXCB 0
-%define CONFIG_LIBXCB_SHM 0
-%define CONFIG_LIBXCB_SHAPE 0
-%define CONFIG_LIBXCB_XFIXES 0
-%define CONFIG_LIBXVID 0
+%define CONFIG_LIBXML2 0
%define CONFIG_LIBZIMG 0
%define CONFIG_LIBZMQ 0
%define CONFIG_LIBZVBI 0
-%define CONFIG_LZMA 0
%define CONFIG_MEDIACODEC 0
-%define CONFIG_NETCDF 0
%define CONFIG_OPENAL 0
%define CONFIG_OPENCL 0
%define CONFIG_OPENGL 0
-%define CONFIG_OPENSSL 0
-%define CONFIG_SCHANNEL 1
-%define CONFIG_SDL 0
-%define CONFIG_SDL2 0
-%define CONFIG_SECURETRANSPORT 0
-%define CONFIG_VIDEOTOOLBOX 0
-%define CONFIG_X11GRAB 0
-%define CONFIG_XLIB 0
-%define CONFIG_ZLIB 0
%define CONFIG_AUDIOTOOLBOX 0
-%define CONFIG_CUDA 0
-%define CONFIG_CUVID 0
+%define CONFIG_CRYSTALHD 0
+%define CONFIG_CUDA 1
+%define CONFIG_CUVID 1
%define CONFIG_D3D11VA 0
%define CONFIG_DXVA2 0
-%define CONFIG_LIBMFX 0
-%define CONFIG_LIBNPP 0
-%define CONFIG_MMAL 0
-%define CONFIG_NVENC 0
-%define CONFIG_OMX 0
+%define CONFIG_NVENC 1
%define CONFIG_VAAPI 0
%define CONFIG_VDA 0
%define CONFIG_VDPAU 0
-%define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_VIDEOTOOLBOX 0
+%define CONFIG_V4L2_M2M 0
%define CONFIG_XVMC 0
+%define CONFIG_CUDA_SDK 0
+%define CONFIG_LIBNPP 0
+%define CONFIG_LIBMFX 0
+%define CONFIG_MMAL 0
+%define CONFIG_OMX 0
%define CONFIG_FTRAPV 0
%define CONFIG_GRAY 0
%define CONFIG_HARDCODED_TABLES 0
@@ -539,16 +541,27 @@
%define CONFIG_PIXELUTILS 0
%define CONFIG_NETWORK 0
%define CONFIG_RDFT 0
+%define CONFIG_AUTODETECT 0
%define CONFIG_FONTCONFIG 0
-%define CONFIG_MEMALIGN_HACK 0
+%define CONFIG_LINUX_PERF 0
%define CONFIG_MEMORY_POISONING 0
%define CONFIG_NEON_CLOBBER_TEST 0
+%define CONFIG_OSSFUZZ 0
%define CONFIG_PIC 0
-%define CONFIG_POD2MAN 1
-%define CONFIG_RAISE_MAJOR 0
%define CONFIG_THUMB 0
%define CONFIG_VALGRIND_BACKTRACE 0
%define CONFIG_XMM_CLOBBER_TEST 0
+%define CONFIG_BSFS 1
+%define CONFIG_DECODERS 1
+%define CONFIG_ENCODERS 0
+%define CONFIG_HWACCELS 0
+%define CONFIG_PARSERS 1
+%define CONFIG_INDEVS 0
+%define CONFIG_OUTDEVS 0
+%define CONFIG_FILTERS 0
+%define CONFIG_DEMUXERS 0
+%define CONFIG_MUXERS 0
+%define CONFIG_PROTOCOLS 0
%define CONFIG_AANDCTTABLES 0
%define CONFIG_AC3DSP 0
%define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -566,20 +579,22 @@
%define CONFIG_FMTCONVERT 0
%define CONFIG_FRAME_THREAD_ENCODER 0
%define CONFIG_G722DSP 0
-%define CONFIG_GOLOMB 1
+%define CONFIG_GOLOMB 0
%define CONFIG_GPLV3 0
%define CONFIG_H263DSP 0
%define CONFIG_H264CHROMA 0
%define CONFIG_H264DSP 0
+%define CONFIG_H264PARSE 0
%define CONFIG_H264PRED 1
%define CONFIG_H264QPEL 0
+%define CONFIG_HEVCPARSE 0
%define CONFIG_HPELDSP 0
%define CONFIG_HUFFMAN 0
%define CONFIG_HUFFYUVDSP 0
%define CONFIG_HUFFYUVENCDSP 0
%define CONFIG_IDCTDSP 0
%define CONFIG_IIRFILTER 0
-%define CONFIG_IMDCT15 0
+%define CONFIG_MDCT15 0
%define CONFIG_INTRAX8 0
%define CONFIG_ISO_MEDIA 0
%define CONFIG_IVIDSP 0
@@ -588,12 +603,14 @@
%define CONFIG_LIBX262 0
%define CONFIG_LLAUDDSP 0
%define CONFIG_LLVIDDSP 0
+%define CONFIG_LLVIDENCDSP 0
%define CONFIG_LPC 0
%define CONFIG_LZF 0
%define CONFIG_ME_CMP 0
%define CONFIG_MPEG_ER 0
%define CONFIG_MPEGAUDIO 0
%define CONFIG_MPEGAUDIODSP 0
+%define CONFIG_MPEGAUDIOHEADER 0
%define CONFIG_MPEGVIDEO 0
%define CONFIG_MPEGVIDEOENC 0
%define CONFIG_MSS34DSP 0
@@ -615,1594 +632,19 @@
%define CONFIG_TEXTUREDSP 0
%define CONFIG_TEXTUREDSPENC 0
%define CONFIG_TPELDSP 0
+%define CONFIG_VAAPI_1 0
%define CONFIG_VAAPI_ENCODE 0
%define CONFIG_VC1DSP 0
%define CONFIG_VIDEODSP 1
%define CONFIG_VP3DSP 0
%define CONFIG_VP56DSP 0
%define CONFIG_VP8DSP 1
-%define CONFIG_VT_BT2020 0
%define CONFIG_WMA_FREQS 0
%define CONFIG_WMV2DSP 0
-%define CONFIG_AAC_ADTSTOASC_BSF 0
-%define CONFIG_CHOMP_BSF 0
-%define CONFIG_DUMP_EXTRADATA_BSF 0
-%define CONFIG_DCA_CORE_BSF 0
-%define CONFIG_H264_MP4TOANNEXB_BSF 0
-%define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-%define CONFIG_IMX_DUMP_HEADER_BSF 0
-%define CONFIG_MJPEG2JPEG_BSF 0
-%define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-%define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-%define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-%define CONFIG_MOV2TEXTSUB_BSF 0
-%define CONFIG_NOISE_BSF 0
-%define CONFIG_REMOVE_EXTRADATA_BSF 0
-%define CONFIG_TEXT2MOVSUB_BSF 0
-%define CONFIG_VP9_SUPERFRAME_BSF 0
-%define CONFIG_AASC_DECODER 0
-%define CONFIG_AIC_DECODER 0
-%define CONFIG_ALIAS_PIX_DECODER 0
-%define CONFIG_AMV_DECODER 0
-%define CONFIG_ANM_DECODER 0
-%define CONFIG_ANSI_DECODER 0
-%define CONFIG_APNG_DECODER 0
-%define CONFIG_ASV1_DECODER 0
-%define CONFIG_ASV2_DECODER 0
-%define CONFIG_AURA_DECODER 0
-%define CONFIG_AURA2_DECODER 0
-%define CONFIG_AVRP_DECODER 0
-%define CONFIG_AVRN_DECODER 0
-%define CONFIG_AVS_DECODER 0
-%define CONFIG_AVUI_DECODER 0
-%define CONFIG_AYUV_DECODER 0
-%define CONFIG_BETHSOFTVID_DECODER 0
-%define CONFIG_BFI_DECODER 0
-%define CONFIG_BINK_DECODER 0
-%define CONFIG_BMP_DECODER 0
-%define CONFIG_BMV_VIDEO_DECODER 0
-%define CONFIG_BRENDER_PIX_DECODER 0
-%define CONFIG_C93_DECODER 0
-%define CONFIG_CAVS_DECODER 0
-%define CONFIG_CDGRAPHICS_DECODER 0
-%define CONFIG_CDXL_DECODER 0
-%define CONFIG_CFHD_DECODER 0
-%define CONFIG_CINEPAK_DECODER 0
-%define CONFIG_CLJR_DECODER 0
-%define CONFIG_CLLC_DECODER 0
-%define CONFIG_COMFORTNOISE_DECODER 0
-%define CONFIG_CPIA_DECODER 0
-%define CONFIG_CSCD_DECODER 0
-%define CONFIG_CYUV_DECODER 0
-%define CONFIG_DDS_DECODER 0
-%define CONFIG_DFA_DECODER 0
-%define CONFIG_DIRAC_DECODER 0
-%define CONFIG_DNXHD_DECODER 0
-%define CONFIG_DPX_DECODER 0
-%define CONFIG_DSICINVIDEO_DECODER 0
-%define CONFIG_DVAUDIO_DECODER 0
-%define CONFIG_DVVIDEO_DECODER 0
-%define CONFIG_DXA_DECODER 0
-%define CONFIG_DXTORY_DECODER 0
-%define CONFIG_DXV_DECODER 0
-%define CONFIG_EACMV_DECODER 0
-%define CONFIG_EAMAD_DECODER 0
-%define CONFIG_EATGQ_DECODER 0
-%define CONFIG_EATGV_DECODER 0
-%define CONFIG_EATQI_DECODER 0
-%define CONFIG_EIGHTBPS_DECODER 0
-%define CONFIG_EIGHTSVX_EXP_DECODER 0
-%define CONFIG_EIGHTSVX_FIB_DECODER 0
-%define CONFIG_ESCAPE124_DECODER 0
-%define CONFIG_ESCAPE130_DECODER 0
-%define CONFIG_EXR_DECODER 0
-%define CONFIG_FFV1_DECODER 0
-%define CONFIG_FFVHUFF_DECODER 0
-%define CONFIG_FIC_DECODER 0
-%define CONFIG_FLASHSV_DECODER 0
-%define CONFIG_FLASHSV2_DECODER 0
-%define CONFIG_FLIC_DECODER 0
-%define CONFIG_FLV_DECODER 0
-%define CONFIG_FOURXM_DECODER 0
-%define CONFIG_FRAPS_DECODER 0
-%define CONFIG_FRWU_DECODER 0
-%define CONFIG_G2M_DECODER 0
-%define CONFIG_GIF_DECODER 0
-%define CONFIG_H261_DECODER 0
-%define CONFIG_H263_DECODER 0
-%define CONFIG_H263I_DECODER 0
-%define CONFIG_H263P_DECODER 0
-%define CONFIG_H264_DECODER 0
-%define CONFIG_H264_CRYSTALHD_DECODER 0
-%define CONFIG_H264_MEDIACODEC_DECODER 0
-%define CONFIG_H264_MMAL_DECODER 0
-%define CONFIG_H264_QSV_DECODER 0
-%define CONFIG_H264_VDA_DECODER 0
-%define CONFIG_H264_VDPAU_DECODER 0
-%define CONFIG_HAP_DECODER 0
-%define CONFIG_HEVC_DECODER 0
-%define CONFIG_HEVC_QSV_DECODER 0
-%define CONFIG_HNM4_VIDEO_DECODER 0
-%define CONFIG_HQ_HQA_DECODER 0
-%define CONFIG_HQX_DECODER 0
-%define CONFIG_HUFFYUV_DECODER 0
-%define CONFIG_IDCIN_DECODER 0
-%define CONFIG_IFF_ILBM_DECODER 0
-%define CONFIG_INDEO2_DECODER 0
-%define CONFIG_INDEO3_DECODER 0
-%define CONFIG_INDEO4_DECODER 0
-%define CONFIG_INDEO5_DECODER 0
-%define CONFIG_INTERPLAY_VIDEO_DECODER 0
-%define CONFIG_JPEG2000_DECODER 0
-%define CONFIG_JPEGLS_DECODER 0
-%define CONFIG_JV_DECODER 0
-%define CONFIG_KGV1_DECODER 0
-%define CONFIG_KMVC_DECODER 0
-%define CONFIG_LAGARITH_DECODER 0
-%define CONFIG_LOCO_DECODER 0
-%define CONFIG_M101_DECODER 0
-%define CONFIG_MAGICYUV_DECODER 0
-%define CONFIG_MDEC_DECODER 0
-%define CONFIG_MIMIC_DECODER 0
-%define CONFIG_MJPEG_DECODER 0
-%define CONFIG_MJPEGB_DECODER 0
-%define CONFIG_MMVIDEO_DECODER 0
-%define CONFIG_MOTIONPIXELS_DECODER 0
-%define CONFIG_MPEG_XVMC_DECODER 0
-%define CONFIG_MPEG1VIDEO_DECODER 0
-%define CONFIG_MPEG2VIDEO_DECODER 0
-%define CONFIG_MPEG4_DECODER 0
-%define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-%define CONFIG_MPEG4_MMAL_DECODER 0
-%define CONFIG_MPEG4_VDPAU_DECODER 0
-%define CONFIG_MPEGVIDEO_DECODER 0
-%define CONFIG_MPEG_VDPAU_DECODER 0
-%define CONFIG_MPEG1_VDPAU_DECODER 0
-%define CONFIG_MPEG2_MMAL_DECODER 0
-%define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-%define CONFIG_MPEG2_QSV_DECODER 0
-%define CONFIG_MSA1_DECODER 0
-%define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-%define CONFIG_MSMPEG4V1_DECODER 0
-%define CONFIG_MSMPEG4V2_DECODER 0
-%define CONFIG_MSMPEG4V3_DECODER 0
-%define CONFIG_MSRLE_DECODER 0
-%define CONFIG_MSS1_DECODER 0
-%define CONFIG_MSS2_DECODER 0
-%define CONFIG_MSVIDEO1_DECODER 0
-%define CONFIG_MSZH_DECODER 0
-%define CONFIG_MTS2_DECODER 0
-%define CONFIG_MVC1_DECODER 0
-%define CONFIG_MVC2_DECODER 0
-%define CONFIG_MXPEG_DECODER 0
-%define CONFIG_NUV_DECODER 0
-%define CONFIG_PAF_VIDEO_DECODER 0
-%define CONFIG_PAM_DECODER 0
-%define CONFIG_PBM_DECODER 0
-%define CONFIG_PCX_DECODER 0
-%define CONFIG_PGM_DECODER 0
-%define CONFIG_PGMYUV_DECODER 0
-%define CONFIG_PICTOR_DECODER 0
-%define CONFIG_PNG_DECODER 0
-%define CONFIG_PPM_DECODER 0
-%define CONFIG_PRORES_DECODER 0
-%define CONFIG_PRORES_LGPL_DECODER 0
-%define CONFIG_PTX_DECODER 0
-%define CONFIG_QDRAW_DECODER 0
-%define CONFIG_QPEG_DECODER 0
-%define CONFIG_QTRLE_DECODER 0
-%define CONFIG_R10K_DECODER 0
-%define CONFIG_R210_DECODER 0
-%define CONFIG_RAWVIDEO_DECODER 0
-%define CONFIG_RL2_DECODER 0
-%define CONFIG_ROQ_DECODER 0
-%define CONFIG_RPZA_DECODER 0
-%define CONFIG_RSCC_DECODER 0
-%define CONFIG_RV10_DECODER 0
-%define CONFIG_RV20_DECODER 0
-%define CONFIG_RV30_DECODER 0
-%define CONFIG_RV40_DECODER 0
-%define CONFIG_S302M_DECODER 0
-%define CONFIG_SANM_DECODER 0
-%define CONFIG_SCREENPRESSO_DECODER 0
-%define CONFIG_SDX2_DPCM_DECODER 0
-%define CONFIG_SGI_DECODER 0
-%define CONFIG_SGIRLE_DECODER 0
-%define CONFIG_SHEERVIDEO_DECODER 0
-%define CONFIG_SMACKER_DECODER 0
-%define CONFIG_SMC_DECODER 0
-%define CONFIG_SMVJPEG_DECODER 0
-%define CONFIG_SNOW_DECODER 0
-%define CONFIG_SP5X_DECODER 0
-%define CONFIG_SUNRAST_DECODER 0
-%define CONFIG_SVQ1_DECODER 0
-%define CONFIG_SVQ3_DECODER 0
-%define CONFIG_TARGA_DECODER 0
-%define CONFIG_TARGA_Y216_DECODER 0
-%define CONFIG_TDSC_DECODER 0
-%define CONFIG_THEORA_DECODER 0
-%define CONFIG_THP_DECODER 0
-%define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-%define CONFIG_TIFF_DECODER 0
-%define CONFIG_TMV_DECODER 0
-%define CONFIG_TRUEMOTION1_DECODER 0
-%define CONFIG_TRUEMOTION2_DECODER 0
-%define CONFIG_TRUEMOTION2RT_DECODER 0
-%define CONFIG_TSCC_DECODER 0
-%define CONFIG_TSCC2_DECODER 0
-%define CONFIG_TXD_DECODER 0
-%define CONFIG_ULTI_DECODER 0
-%define CONFIG_UTVIDEO_DECODER 0
-%define CONFIG_V210_DECODER 0
-%define CONFIG_V210X_DECODER 0
-%define CONFIG_V308_DECODER 0
-%define CONFIG_V408_DECODER 0
-%define CONFIG_V410_DECODER 0
-%define CONFIG_VB_DECODER 0
-%define CONFIG_VBLE_DECODER 0
-%define CONFIG_VC1_DECODER 0
-%define CONFIG_VC1_CRYSTALHD_DECODER 0
-%define CONFIG_VC1_VDPAU_DECODER 0
-%define CONFIG_VC1IMAGE_DECODER 0
-%define CONFIG_VC1_MMAL_DECODER 0
-%define CONFIG_VC1_QSV_DECODER 0
-%define CONFIG_VCR1_DECODER 0
-%define CONFIG_VMDVIDEO_DECODER 0
-%define CONFIG_VMNC_DECODER 0
-%define CONFIG_VP3_DECODER 0
-%define CONFIG_VP5_DECODER 0
-%define CONFIG_VP6_DECODER 0
-%define CONFIG_VP6A_DECODER 0
-%define CONFIG_VP6F_DECODER 0
-%define CONFIG_VP7_DECODER 0
+%define CONFIG_NULL_BSF 1
%define CONFIG_VP8_DECODER 1
%define CONFIG_VP9_DECODER 1
-%define CONFIG_VQA_DECODER 0
-%define CONFIG_WEBP_DECODER 0
-%define CONFIG_WMV1_DECODER 0
-%define CONFIG_WMV2_DECODER 0
-%define CONFIG_WMV3_DECODER 0
-%define CONFIG_WMV3_CRYSTALHD_DECODER 0
-%define CONFIG_WMV3_VDPAU_DECODER 0
-%define CONFIG_WMV3IMAGE_DECODER 0
-%define CONFIG_WNV1_DECODER 0
-%define CONFIG_XAN_WC3_DECODER 0
-%define CONFIG_XAN_WC4_DECODER 0
-%define CONFIG_XBM_DECODER 0
-%define CONFIG_XFACE_DECODER 0
-%define CONFIG_XL_DECODER 0
-%define CONFIG_XWD_DECODER 0
-%define CONFIG_Y41P_DECODER 0
-%define CONFIG_YLC_DECODER 0
-%define CONFIG_YOP_DECODER 0
-%define CONFIG_YUV4_DECODER 0
-%define CONFIG_ZERO12V_DECODER 0
-%define CONFIG_ZEROCODEC_DECODER 0
-%define CONFIG_ZLIB_DECODER 0
-%define CONFIG_ZMBV_DECODER 0
-%define CONFIG_AAC_DECODER 0
-%define CONFIG_AAC_FIXED_DECODER 0
-%define CONFIG_AAC_LATM_DECODER 0
-%define CONFIG_AC3_DECODER 0
-%define CONFIG_AC3_FIXED_DECODER 0
-%define CONFIG_ALAC_DECODER 0
-%define CONFIG_ALS_DECODER 0
-%define CONFIG_AMRNB_DECODER 0
-%define CONFIG_AMRWB_DECODER 0
-%define CONFIG_APE_DECODER 0
-%define CONFIG_ATRAC1_DECODER 0
-%define CONFIG_ATRAC3_DECODER 0
-%define CONFIG_ATRAC3P_DECODER 0
-%define CONFIG_BINKAUDIO_DCT_DECODER 0
-%define CONFIG_BINKAUDIO_RDFT_DECODER 0
-%define CONFIG_BMV_AUDIO_DECODER 0
-%define CONFIG_COOK_DECODER 0
-%define CONFIG_DCA_DECODER 0
-%define CONFIG_DSD_LSBF_DECODER 0
-%define CONFIG_DSD_MSBF_DECODER 0
-%define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-%define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-%define CONFIG_DSICINAUDIO_DECODER 0
-%define CONFIG_DSS_SP_DECODER 0
-%define CONFIG_DST_DECODER 0
-%define CONFIG_EAC3_DECODER 0
-%define CONFIG_EVRC_DECODER 0
-%define CONFIG_FFWAVESYNTH_DECODER 0
%define CONFIG_FLAC_DECODER 1
-%define CONFIG_G723_1_DECODER 0
-%define CONFIG_G729_DECODER 0
-%define CONFIG_GSM_DECODER 0
-%define CONFIG_GSM_MS_DECODER 0
-%define CONFIG_IAC_DECODER 0
-%define CONFIG_IMC_DECODER 0
-%define CONFIG_INTERPLAY_ACM_DECODER 0
-%define CONFIG_MACE3_DECODER 0
-%define CONFIG_MACE6_DECODER 0
-%define CONFIG_METASOUND_DECODER 0
-%define CONFIG_MLP_DECODER 0
-%define CONFIG_MP1_DECODER 0
-%define CONFIG_MP1FLOAT_DECODER 0
-%define CONFIG_MP2_DECODER 0
-%define CONFIG_MP2FLOAT_DECODER 0
-%define CONFIG_MP3_DECODER 0
-%define CONFIG_MP3FLOAT_DECODER 0
-%define CONFIG_MP3ADU_DECODER 0
-%define CONFIG_MP3ADUFLOAT_DECODER 0
-%define CONFIG_MP3ON4_DECODER 0
-%define CONFIG_MP3ON4FLOAT_DECODER 0
-%define CONFIG_MPC7_DECODER 0
-%define CONFIG_MPC8_DECODER 0
-%define CONFIG_NELLYMOSER_DECODER 0
-%define CONFIG_ON2AVC_DECODER 0
-%define CONFIG_OPUS_DECODER 0
-%define CONFIG_PAF_AUDIO_DECODER 0
-%define CONFIG_QCELP_DECODER 0
-%define CONFIG_QDM2_DECODER 0
-%define CONFIG_RA_144_DECODER 0
-%define CONFIG_RA_288_DECODER 0
-%define CONFIG_RALF_DECODER 0
-%define CONFIG_SHORTEN_DECODER 0
-%define CONFIG_SIPR_DECODER 0
-%define CONFIG_SMACKAUD_DECODER 0
-%define CONFIG_SONIC_DECODER 0
-%define CONFIG_TAK_DECODER 0
-%define CONFIG_TRUEHD_DECODER 0
-%define CONFIG_TRUESPEECH_DECODER 0
-%define CONFIG_TTA_DECODER 0
-%define CONFIG_TWINVQ_DECODER 0
-%define CONFIG_VMDAUDIO_DECODER 0
-%define CONFIG_VORBIS_DECODER 0
-%define CONFIG_WAVPACK_DECODER 0
-%define CONFIG_WMALOSSLESS_DECODER 0
-%define CONFIG_WMAPRO_DECODER 0
-%define CONFIG_WMAV1_DECODER 0
-%define CONFIG_WMAV2_DECODER 0
-%define CONFIG_WMAVOICE_DECODER 0
-%define CONFIG_WS_SND1_DECODER 0
-%define CONFIG_XMA1_DECODER 0
-%define CONFIG_XMA2_DECODER 0
-%define CONFIG_PCM_ALAW_DECODER 0
-%define CONFIG_PCM_BLURAY_DECODER 0
-%define CONFIG_PCM_DVD_DECODER 0
-%define CONFIG_PCM_F32BE_DECODER 0
-%define CONFIG_PCM_F32LE_DECODER 0
-%define CONFIG_PCM_F64BE_DECODER 0
-%define CONFIG_PCM_F64LE_DECODER 0
-%define CONFIG_PCM_LXF_DECODER 0
-%define CONFIG_PCM_MULAW_DECODER 0
-%define CONFIG_PCM_S8_DECODER 0
-%define CONFIG_PCM_S8_PLANAR_DECODER 0
-%define CONFIG_PCM_S16BE_DECODER 0
-%define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-%define CONFIG_PCM_S16LE_DECODER 0
-%define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S24BE_DECODER 0
-%define CONFIG_PCM_S24DAUD_DECODER 0
-%define CONFIG_PCM_S24LE_DECODER 0
-%define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S32BE_DECODER 0
-%define CONFIG_PCM_S32LE_DECODER 0
-%define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S64BE_DECODER 0
-%define CONFIG_PCM_S64LE_DECODER 0
-%define CONFIG_PCM_U8_DECODER 0
-%define CONFIG_PCM_U16BE_DECODER 0
-%define CONFIG_PCM_U16LE_DECODER 0
-%define CONFIG_PCM_U24BE_DECODER 0
-%define CONFIG_PCM_U24LE_DECODER 0
-%define CONFIG_PCM_U32BE_DECODER 0
-%define CONFIG_PCM_U32LE_DECODER 0
-%define CONFIG_PCM_ZORK_DECODER 0
-%define CONFIG_INTERPLAY_DPCM_DECODER 0
-%define CONFIG_ROQ_DPCM_DECODER 0
-%define CONFIG_SOL_DPCM_DECODER 0
-%define CONFIG_XAN_DPCM_DECODER 0
-%define CONFIG_ADPCM_4XM_DECODER 0
-%define CONFIG_ADPCM_ADX_DECODER 0
-%define CONFIG_ADPCM_AFC_DECODER 0
-%define CONFIG_ADPCM_AICA_DECODER 0
-%define CONFIG_ADPCM_CT_DECODER 0
-%define CONFIG_ADPCM_DTK_DECODER 0
-%define CONFIG_ADPCM_EA_DECODER 0
-%define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-%define CONFIG_ADPCM_EA_R1_DECODER 0
-%define CONFIG_ADPCM_EA_R2_DECODER 0
-%define CONFIG_ADPCM_EA_R3_DECODER 0
-%define CONFIG_ADPCM_EA_XAS_DECODER 0
-%define CONFIG_ADPCM_G722_DECODER 0
-%define CONFIG_ADPCM_G726_DECODER 0
-%define CONFIG_ADPCM_G726LE_DECODER 0
-%define CONFIG_ADPCM_IMA_AMV_DECODER 0
-%define CONFIG_ADPCM_IMA_APC_DECODER 0
-%define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-%define CONFIG_ADPCM_IMA_DK3_DECODER 0
-%define CONFIG_ADPCM_IMA_DK4_DECODER 0
-%define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-%define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-%define CONFIG_ADPCM_IMA_ISS_DECODER 0
-%define CONFIG_ADPCM_IMA_OKI_DECODER 0
-%define CONFIG_ADPCM_IMA_QT_DECODER 0
-%define CONFIG_ADPCM_IMA_RAD_DECODER 0
-%define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-%define CONFIG_ADPCM_IMA_WAV_DECODER 0
-%define CONFIG_ADPCM_IMA_WS_DECODER 0
-%define CONFIG_ADPCM_MS_DECODER 0
-%define CONFIG_ADPCM_MTAF_DECODER 0
-%define CONFIG_ADPCM_PSX_DECODER 0
-%define CONFIG_ADPCM_SBPRO_2_DECODER 0
-%define CONFIG_ADPCM_SBPRO_3_DECODER 0
-%define CONFIG_ADPCM_SBPRO_4_DECODER 0
-%define CONFIG_ADPCM_SWF_DECODER 0
-%define CONFIG_ADPCM_THP_DECODER 0
-%define CONFIG_ADPCM_THP_LE_DECODER 0
-%define CONFIG_ADPCM_VIMA_DECODER 0
-%define CONFIG_ADPCM_XA_DECODER 0
-%define CONFIG_ADPCM_YAMAHA_DECODER 0
-%define CONFIG_SSA_DECODER 0
-%define CONFIG_ASS_DECODER 0
-%define CONFIG_CCAPTION_DECODER 0
-%define CONFIG_DVBSUB_DECODER 0
-%define CONFIG_DVDSUB_DECODER 0
-%define CONFIG_JACOSUB_DECODER 0
-%define CONFIG_MICRODVD_DECODER 0
-%define CONFIG_MOVTEXT_DECODER 0
-%define CONFIG_MPL2_DECODER 0
-%define CONFIG_PGSSUB_DECODER 0
-%define CONFIG_PJS_DECODER 0
-%define CONFIG_REALTEXT_DECODER 0
-%define CONFIG_SAMI_DECODER 0
-%define CONFIG_SRT_DECODER 0
-%define CONFIG_STL_DECODER 0
-%define CONFIG_SUBRIP_DECODER 0
-%define CONFIG_SUBVIEWER_DECODER 0
-%define CONFIG_SUBVIEWER1_DECODER 0
-%define CONFIG_TEXT_DECODER 0
-%define CONFIG_VPLAYER_DECODER 0
-%define CONFIG_WEBVTT_DECODER 0
-%define CONFIG_XSUB_DECODER 0
-%define CONFIG_AAC_AT_DECODER 0
-%define CONFIG_AC3_AT_DECODER 0
-%define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-%define CONFIG_ALAC_AT_DECODER 0
-%define CONFIG_AMR_NB_AT_DECODER 0
-%define CONFIG_EAC3_AT_DECODER 0
-%define CONFIG_GSM_MS_AT_DECODER 0
-%define CONFIG_ILBC_AT_DECODER 0
-%define CONFIG_MP1_AT_DECODER 0
-%define CONFIG_MP2_AT_DECODER 0
-%define CONFIG_MP3_AT_DECODER 0
-%define CONFIG_PCM_ALAW_AT_DECODER 0
-%define CONFIG_PCM_MULAW_AT_DECODER 0
-%define CONFIG_QDMC_AT_DECODER 0
-%define CONFIG_QDM2_AT_DECODER 0
-%define CONFIG_LIBCELT_DECODER 0
-%define CONFIG_LIBFDK_AAC_DECODER 0
-%define CONFIG_LIBGSM_DECODER 0
-%define CONFIG_LIBGSM_MS_DECODER 0
-%define CONFIG_LIBILBC_DECODER 0
-%define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-%define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-%define CONFIG_LIBOPENJPEG_DECODER 0
-%define CONFIG_LIBOPUS_DECODER 0
-%define CONFIG_LIBSCHROEDINGER_DECODER 0
-%define CONFIG_LIBSPEEX_DECODER 0
-%define CONFIG_LIBVORBIS_DECODER 0
-%define CONFIG_LIBVPX_VP8_DECODER 0
-%define CONFIG_LIBVPX_VP9_DECODER 0
-%define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-%define CONFIG_BINTEXT_DECODER 0
-%define CONFIG_XBIN_DECODER 0
-%define CONFIG_IDF_DECODER 0
-%define CONFIG_LIBOPENH264_DECODER 0
-%define CONFIG_H263_CUVID_DECODER 0
-%define CONFIG_H264_CUVID_DECODER 0
-%define CONFIG_HEVC_CUVID_DECODER 0
-%define CONFIG_HEVC_MEDIACODEC_DECODER 0
-%define CONFIG_MJPEG_CUVID_DECODER 0
-%define CONFIG_MPEG1_CUVID_DECODER 0
-%define CONFIG_MPEG2_CUVID_DECODER 0
-%define CONFIG_MPEG4_CUVID_DECODER 0
-%define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-%define CONFIG_VC1_CUVID_DECODER 0
-%define CONFIG_VP8_CUVID_DECODER 0
-%define CONFIG_VP8_MEDIACODEC_DECODER 0
-%define CONFIG_VP9_CUVID_DECODER 0
-%define CONFIG_VP9_MEDIACODEC_DECODER 0
-%define CONFIG_AA_DEMUXER 0
-%define CONFIG_AAC_DEMUXER 0
-%define CONFIG_AC3_DEMUXER 0
-%define CONFIG_ACM_DEMUXER 0
-%define CONFIG_ACT_DEMUXER 0
-%define CONFIG_ADF_DEMUXER 0
-%define CONFIG_ADP_DEMUXER 0
-%define CONFIG_ADS_DEMUXER 0
-%define CONFIG_ADX_DEMUXER 0
-%define CONFIG_AEA_DEMUXER 0
-%define CONFIG_AFC_DEMUXER 0
-%define CONFIG_AIFF_DEMUXER 0
-%define CONFIG_AIX_DEMUXER 0
-%define CONFIG_AMR_DEMUXER 0
-%define CONFIG_ANM_DEMUXER 0
-%define CONFIG_APC_DEMUXER 0
-%define CONFIG_APE_DEMUXER 0
-%define CONFIG_APNG_DEMUXER 0
-%define CONFIG_AQTITLE_DEMUXER 0
-%define CONFIG_ASF_DEMUXER 0
-%define CONFIG_ASF_O_DEMUXER 0
-%define CONFIG_ASS_DEMUXER 0
-%define CONFIG_AST_DEMUXER 0
-%define CONFIG_AU_DEMUXER 0
-%define CONFIG_AVI_DEMUXER 0
-%define CONFIG_AVISYNTH_DEMUXER 0
-%define CONFIG_AVR_DEMUXER 0
-%define CONFIG_AVS_DEMUXER 0
-%define CONFIG_BETHSOFTVID_DEMUXER 0
-%define CONFIG_BFI_DEMUXER 0
-%define CONFIG_BINTEXT_DEMUXER 0
-%define CONFIG_BINK_DEMUXER 0
-%define CONFIG_BIT_DEMUXER 0
-%define CONFIG_BMV_DEMUXER 0
-%define CONFIG_BFSTM_DEMUXER 0
-%define CONFIG_BRSTM_DEMUXER 0
-%define CONFIG_BOA_DEMUXER 0
-%define CONFIG_C93_DEMUXER 0
-%define CONFIG_CAF_DEMUXER 0
-%define CONFIG_CAVSVIDEO_DEMUXER 0
-%define CONFIG_CDG_DEMUXER 0
-%define CONFIG_CDXL_DEMUXER 0
-%define CONFIG_CINE_DEMUXER 0
-%define CONFIG_CONCAT_DEMUXER 0
-%define CONFIG_DATA_DEMUXER 0
-%define CONFIG_DAUD_DEMUXER 0
-%define CONFIG_DCSTR_DEMUXER 0
-%define CONFIG_DFA_DEMUXER 0
-%define CONFIG_DIRAC_DEMUXER 0
-%define CONFIG_DNXHD_DEMUXER 0
-%define CONFIG_DSF_DEMUXER 0
-%define CONFIG_DSICIN_DEMUXER 0
-%define CONFIG_DSS_DEMUXER 0
-%define CONFIG_DTS_DEMUXER 0
-%define CONFIG_DTSHD_DEMUXER 0
-%define CONFIG_DV_DEMUXER 0
-%define CONFIG_DVBSUB_DEMUXER 0
-%define CONFIG_DVBTXT_DEMUXER 0
-%define CONFIG_DXA_DEMUXER 0
-%define CONFIG_EA_DEMUXER 0
-%define CONFIG_EA_CDATA_DEMUXER 0
-%define CONFIG_EAC3_DEMUXER 0
-%define CONFIG_EPAF_DEMUXER 0
-%define CONFIG_FFM_DEMUXER 0
-%define CONFIG_FFMETADATA_DEMUXER 0
-%define CONFIG_FILMSTRIP_DEMUXER 0
-%define CONFIG_FLAC_DEMUXER 0
-%define CONFIG_FLIC_DEMUXER 0
-%define CONFIG_FLV_DEMUXER 0
-%define CONFIG_LIVE_FLV_DEMUXER 0
-%define CONFIG_FOURXM_DEMUXER 0
-%define CONFIG_FRM_DEMUXER 0
-%define CONFIG_FSB_DEMUXER 0
-%define CONFIG_G722_DEMUXER 0
-%define CONFIG_G723_1_DEMUXER 0
-%define CONFIG_G729_DEMUXER 0
-%define CONFIG_GENH_DEMUXER 0
-%define CONFIG_GIF_DEMUXER 0
-%define CONFIG_GSM_DEMUXER 0
-%define CONFIG_GXF_DEMUXER 0
-%define CONFIG_H261_DEMUXER 0
-%define CONFIG_H263_DEMUXER 0
-%define CONFIG_H264_DEMUXER 0
-%define CONFIG_HEVC_DEMUXER 0
-%define CONFIG_HLS_DEMUXER 0
-%define CONFIG_HNM_DEMUXER 0
-%define CONFIG_ICO_DEMUXER 0
-%define CONFIG_IDCIN_DEMUXER 0
-%define CONFIG_IDF_DEMUXER 0
-%define CONFIG_IFF_DEMUXER 0
-%define CONFIG_ILBC_DEMUXER 0
-%define CONFIG_IMAGE2_DEMUXER 0
-%define CONFIG_IMAGE2PIPE_DEMUXER 0
-%define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-%define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-%define CONFIG_INGENIENT_DEMUXER 0
-%define CONFIG_IPMOVIE_DEMUXER 0
-%define CONFIG_IRCAM_DEMUXER 0
-%define CONFIG_ISS_DEMUXER 0
-%define CONFIG_IV8_DEMUXER 0
-%define CONFIG_IVF_DEMUXER 0
-%define CONFIG_IVR_DEMUXER 0
-%define CONFIG_JACOSUB_DEMUXER 0
-%define CONFIG_JV_DEMUXER 0
-%define CONFIG_LMLM4_DEMUXER 0
-%define CONFIG_LOAS_DEMUXER 0
-%define CONFIG_LRC_DEMUXER 0
-%define CONFIG_LVF_DEMUXER 0
-%define CONFIG_LXF_DEMUXER 0
-%define CONFIG_M4V_DEMUXER 0
-%define CONFIG_MATROSKA_DEMUXER 0
-%define CONFIG_MGSTS_DEMUXER 0
-%define CONFIG_MICRODVD_DEMUXER 0
-%define CONFIG_MJPEG_DEMUXER 0
-%define CONFIG_MLP_DEMUXER 0
-%define CONFIG_MLV_DEMUXER 0
-%define CONFIG_MM_DEMUXER 0
-%define CONFIG_MMF_DEMUXER 0
-%define CONFIG_MOV_DEMUXER 0
-%define CONFIG_MP3_DEMUXER 0
-%define CONFIG_MPC_DEMUXER 0
-%define CONFIG_MPC8_DEMUXER 0
-%define CONFIG_MPEGPS_DEMUXER 0
-%define CONFIG_MPEGTS_DEMUXER 0
-%define CONFIG_MPEGTSRAW_DEMUXER 0
-%define CONFIG_MPEGVIDEO_DEMUXER 0
-%define CONFIG_MPJPEG_DEMUXER 0
-%define CONFIG_MPL2_DEMUXER 0
-%define CONFIG_MPSUB_DEMUXER 0
-%define CONFIG_MSF_DEMUXER 0
-%define CONFIG_MSNWC_TCP_DEMUXER 0
-%define CONFIG_MTAF_DEMUXER 0
-%define CONFIG_MTV_DEMUXER 0
-%define CONFIG_MUSX_DEMUXER 0
-%define CONFIG_MV_DEMUXER 0
-%define CONFIG_MVI_DEMUXER 0
-%define CONFIG_MXF_DEMUXER 0
-%define CONFIG_MXG_DEMUXER 0
-%define CONFIG_NC_DEMUXER 0
-%define CONFIG_NISTSPHERE_DEMUXER 0
-%define CONFIG_NSV_DEMUXER 0
-%define CONFIG_NUT_DEMUXER 0
-%define CONFIG_NUV_DEMUXER 0
-%define CONFIG_OGG_DEMUXER 0
-%define CONFIG_OMA_DEMUXER 0
-%define CONFIG_PAF_DEMUXER 0
-%define CONFIG_PCM_ALAW_DEMUXER 0
-%define CONFIG_PCM_MULAW_DEMUXER 0
-%define CONFIG_PCM_F64BE_DEMUXER 0
-%define CONFIG_PCM_F64LE_DEMUXER 0
-%define CONFIG_PCM_F32BE_DEMUXER 0
-%define CONFIG_PCM_F32LE_DEMUXER 0
-%define CONFIG_PCM_S32BE_DEMUXER 0
-%define CONFIG_PCM_S32LE_DEMUXER 0
-%define CONFIG_PCM_S24BE_DEMUXER 0
-%define CONFIG_PCM_S24LE_DEMUXER 0
-%define CONFIG_PCM_S16BE_DEMUXER 0
-%define CONFIG_PCM_S16LE_DEMUXER 0
-%define CONFIG_PCM_S8_DEMUXER 0
-%define CONFIG_PCM_U32BE_DEMUXER 0
-%define CONFIG_PCM_U32LE_DEMUXER 0
-%define CONFIG_PCM_U24BE_DEMUXER 0
-%define CONFIG_PCM_U24LE_DEMUXER 0
-%define CONFIG_PCM_U16BE_DEMUXER 0
-%define CONFIG_PCM_U16LE_DEMUXER 0
-%define CONFIG_PCM_U8_DEMUXER 0
-%define CONFIG_PJS_DEMUXER 0
-%define CONFIG_PMP_DEMUXER 0
-%define CONFIG_PVA_DEMUXER 0
-%define CONFIG_PVF_DEMUXER 0
-%define CONFIG_QCP_DEMUXER 0
-%define CONFIG_R3D_DEMUXER 0
-%define CONFIG_RAWVIDEO_DEMUXER 0
-%define CONFIG_REALTEXT_DEMUXER 0
-%define CONFIG_REDSPARK_DEMUXER 0
-%define CONFIG_RL2_DEMUXER 0
-%define CONFIG_RM_DEMUXER 0
-%define CONFIG_ROQ_DEMUXER 0
-%define CONFIG_RPL_DEMUXER 0
-%define CONFIG_RSD_DEMUXER 0
-%define CONFIG_RSO_DEMUXER 0
-%define CONFIG_RTP_DEMUXER 0
-%define CONFIG_RTSP_DEMUXER 0
-%define CONFIG_SAMI_DEMUXER 0
-%define CONFIG_SAP_DEMUXER 0
-%define CONFIG_SBG_DEMUXER 0
-%define CONFIG_SDP_DEMUXER 0
-%define CONFIG_SDR2_DEMUXER 0
-%define CONFIG_SEGAFILM_DEMUXER 0
-%define CONFIG_SHORTEN_DEMUXER 0
-%define CONFIG_SIFF_DEMUXER 0
-%define CONFIG_SLN_DEMUXER 0
-%define CONFIG_SMACKER_DEMUXER 0
-%define CONFIG_SMJPEG_DEMUXER 0
-%define CONFIG_SMUSH_DEMUXER 0
-%define CONFIG_SOL_DEMUXER 0
-%define CONFIG_SOX_DEMUXER 0
-%define CONFIG_SPDIF_DEMUXER 0
-%define CONFIG_SRT_DEMUXER 0
-%define CONFIG_STR_DEMUXER 0
-%define CONFIG_STL_DEMUXER 0
-%define CONFIG_SUBVIEWER1_DEMUXER 0
-%define CONFIG_SUBVIEWER_DEMUXER 0
-%define CONFIG_SUP_DEMUXER 0
-%define CONFIG_SVAG_DEMUXER 0
-%define CONFIG_SWF_DEMUXER 0
-%define CONFIG_TAK_DEMUXER 0
-%define CONFIG_TEDCAPTIONS_DEMUXER 0
-%define CONFIG_THP_DEMUXER 0
-%define CONFIG_THREEDOSTR_DEMUXER 0
-%define CONFIG_TIERTEXSEQ_DEMUXER 0
-%define CONFIG_TMV_DEMUXER 0
-%define CONFIG_TRUEHD_DEMUXER 0
-%define CONFIG_TTA_DEMUXER 0
-%define CONFIG_TXD_DEMUXER 0
-%define CONFIG_TTY_DEMUXER 0
-%define CONFIG_V210_DEMUXER 0
-%define CONFIG_V210X_DEMUXER 0
-%define CONFIG_VAG_DEMUXER 0
-%define CONFIG_VC1_DEMUXER 0
-%define CONFIG_VC1T_DEMUXER 0
-%define CONFIG_VIVO_DEMUXER 0
-%define CONFIG_VMD_DEMUXER 0
-%define CONFIG_VOBSUB_DEMUXER 0
-%define CONFIG_VOC_DEMUXER 0
-%define CONFIG_VPK_DEMUXER 0
-%define CONFIG_VPLAYER_DEMUXER 0
-%define CONFIG_VQF_DEMUXER 0
-%define CONFIG_W64_DEMUXER 0
-%define CONFIG_WAV_DEMUXER 0
-%define CONFIG_WC3_DEMUXER 0
-%define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-%define CONFIG_WEBVTT_DEMUXER 0
-%define CONFIG_WSAUD_DEMUXER 0
-%define CONFIG_WSD_DEMUXER 0
-%define CONFIG_WSVQA_DEMUXER 0
-%define CONFIG_WTV_DEMUXER 0
-%define CONFIG_WVE_DEMUXER 0
-%define CONFIG_WV_DEMUXER 0
-%define CONFIG_XA_DEMUXER 0
-%define CONFIG_XBIN_DEMUXER 0
-%define CONFIG_XMV_DEMUXER 0
-%define CONFIG_XVAG_DEMUXER 0
-%define CONFIG_XWMA_DEMUXER 0
-%define CONFIG_YOP_DEMUXER 0
-%define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-%define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-%define CONFIG_LIBGME_DEMUXER 0
-%define CONFIG_LIBMODPLUG_DEMUXER 0
-%define CONFIG_LIBNUT_DEMUXER 0
-%define CONFIG_LIBOPENMPT_DEMUXER 0
-%define CONFIG_A64MULTI_ENCODER 0
-%define CONFIG_A64MULTI5_ENCODER 0
-%define CONFIG_ALIAS_PIX_ENCODER 0
-%define CONFIG_AMV_ENCODER 0
-%define CONFIG_APNG_ENCODER 0
-%define CONFIG_ASV1_ENCODER 0
-%define CONFIG_ASV2_ENCODER 0
-%define CONFIG_AVRP_ENCODER 0
-%define CONFIG_AVUI_ENCODER 0
-%define CONFIG_AYUV_ENCODER 0
-%define CONFIG_BMP_ENCODER 0
-%define CONFIG_CINEPAK_ENCODER 0
-%define CONFIG_CLJR_ENCODER 0
-%define CONFIG_COMFORTNOISE_ENCODER 0
-%define CONFIG_DNXHD_ENCODER 0
-%define CONFIG_DPX_ENCODER 0
-%define CONFIG_DVVIDEO_ENCODER 0
-%define CONFIG_FFV1_ENCODER 0
-%define CONFIG_FFVHUFF_ENCODER 0
-%define CONFIG_FLASHSV_ENCODER 0
-%define CONFIG_FLASHSV2_ENCODER 0
-%define CONFIG_FLV_ENCODER 0
-%define CONFIG_GIF_ENCODER 0
-%define CONFIG_H261_ENCODER 0
-%define CONFIG_H263_ENCODER 0
-%define CONFIG_H263P_ENCODER 0
-%define CONFIG_HAP_ENCODER 0
-%define CONFIG_HUFFYUV_ENCODER 0
-%define CONFIG_JPEG2000_ENCODER 0
-%define CONFIG_JPEGLS_ENCODER 0
-%define CONFIG_LJPEG_ENCODER 0
-%define CONFIG_MJPEG_ENCODER 0
-%define CONFIG_MPEG1VIDEO_ENCODER 0
-%define CONFIG_MPEG2VIDEO_ENCODER 0
-%define CONFIG_MPEG4_ENCODER 0
-%define CONFIG_MSMPEG4V2_ENCODER 0
-%define CONFIG_MSMPEG4V3_ENCODER 0
-%define CONFIG_MSVIDEO1_ENCODER 0
-%define CONFIG_PAM_ENCODER 0
-%define CONFIG_PBM_ENCODER 0
-%define CONFIG_PCX_ENCODER 0
-%define CONFIG_PGM_ENCODER 0
-%define CONFIG_PGMYUV_ENCODER 0
-%define CONFIG_PNG_ENCODER 0
-%define CONFIG_PPM_ENCODER 0
-%define CONFIG_PRORES_ENCODER 0
-%define CONFIG_PRORES_AW_ENCODER 0
-%define CONFIG_PRORES_KS_ENCODER 0
-%define CONFIG_QTRLE_ENCODER 0
-%define CONFIG_R10K_ENCODER 0
-%define CONFIG_R210_ENCODER 0
-%define CONFIG_RAWVIDEO_ENCODER 0
-%define CONFIG_ROQ_ENCODER 0
-%define CONFIG_RV10_ENCODER 0
-%define CONFIG_RV20_ENCODER 0
-%define CONFIG_S302M_ENCODER 0
-%define CONFIG_SGI_ENCODER 0
-%define CONFIG_SNOW_ENCODER 0
-%define CONFIG_SUNRAST_ENCODER 0
-%define CONFIG_SVQ1_ENCODER 0
-%define CONFIG_TARGA_ENCODER 0
-%define CONFIG_TIFF_ENCODER 0
-%define CONFIG_UTVIDEO_ENCODER 0
-%define CONFIG_V210_ENCODER 0
-%define CONFIG_V308_ENCODER 0
-%define CONFIG_V408_ENCODER 0
-%define CONFIG_V410_ENCODER 0
-%define CONFIG_VC2_ENCODER 0
-%define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-%define CONFIG_WMV1_ENCODER 0
-%define CONFIG_WMV2_ENCODER 0
-%define CONFIG_XBM_ENCODER 0
-%define CONFIG_XFACE_ENCODER 0
-%define CONFIG_XWD_ENCODER 0
-%define CONFIG_Y41P_ENCODER 0
-%define CONFIG_YUV4_ENCODER 0
-%define CONFIG_ZLIB_ENCODER 0
-%define CONFIG_ZMBV_ENCODER 0
-%define CONFIG_AAC_ENCODER 0
-%define CONFIG_AC3_ENCODER 0
-%define CONFIG_AC3_FIXED_ENCODER 0
-%define CONFIG_ALAC_ENCODER 0
-%define CONFIG_DCA_ENCODER 0
-%define CONFIG_EAC3_ENCODER 0
-%define CONFIG_FLAC_ENCODER 0
-%define CONFIG_G723_1_ENCODER 0
-%define CONFIG_MLP_ENCODER 0
-%define CONFIG_MP2_ENCODER 0
-%define CONFIG_MP2FIXED_ENCODER 0
-%define CONFIG_NELLYMOSER_ENCODER 0
-%define CONFIG_RA_144_ENCODER 0
-%define CONFIG_SONIC_ENCODER 0
-%define CONFIG_SONIC_LS_ENCODER 0
-%define CONFIG_TRUEHD_ENCODER 0
-%define CONFIG_TTA_ENCODER 0
-%define CONFIG_VORBIS_ENCODER 0
-%define CONFIG_WAVPACK_ENCODER 0
-%define CONFIG_WMAV1_ENCODER 0
-%define CONFIG_WMAV2_ENCODER 0
-%define CONFIG_PCM_ALAW_ENCODER 0
-%define CONFIG_PCM_F32BE_ENCODER 0
-%define CONFIG_PCM_F32LE_ENCODER 0
-%define CONFIG_PCM_F64BE_ENCODER 0
-%define CONFIG_PCM_F64LE_ENCODER 0
-%define CONFIG_PCM_MULAW_ENCODER 0
-%define CONFIG_PCM_S8_ENCODER 0
-%define CONFIG_PCM_S8_PLANAR_ENCODER 0
-%define CONFIG_PCM_S16BE_ENCODER 0
-%define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S16LE_ENCODER 0
-%define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S24BE_ENCODER 0
-%define CONFIG_PCM_S24DAUD_ENCODER 0
-%define CONFIG_PCM_S24LE_ENCODER 0
-%define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S32BE_ENCODER 0
-%define CONFIG_PCM_S32LE_ENCODER 0
-%define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S64BE_ENCODER 0
-%define CONFIG_PCM_S64LE_ENCODER 0
-%define CONFIG_PCM_U8_ENCODER 0
-%define CONFIG_PCM_U16BE_ENCODER 0
-%define CONFIG_PCM_U16LE_ENCODER 0
-%define CONFIG_PCM_U24BE_ENCODER 0
-%define CONFIG_PCM_U24LE_ENCODER 0
-%define CONFIG_PCM_U32BE_ENCODER 0
-%define CONFIG_PCM_U32LE_ENCODER 0
-%define CONFIG_ROQ_DPCM_ENCODER 0
-%define CONFIG_ADPCM_ADX_ENCODER 0
-%define CONFIG_ADPCM_G722_ENCODER 0
-%define CONFIG_ADPCM_G726_ENCODER 0
-%define CONFIG_ADPCM_IMA_QT_ENCODER 0
-%define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-%define CONFIG_ADPCM_MS_ENCODER 0
-%define CONFIG_ADPCM_SWF_ENCODER 0
-%define CONFIG_ADPCM_YAMAHA_ENCODER 0
-%define CONFIG_SSA_ENCODER 0
-%define CONFIG_ASS_ENCODER 0
-%define CONFIG_DVBSUB_ENCODER 0
-%define CONFIG_DVDSUB_ENCODER 0
-%define CONFIG_MOVTEXT_ENCODER 0
-%define CONFIG_SRT_ENCODER 0
-%define CONFIG_SUBRIP_ENCODER 0
-%define CONFIG_TEXT_ENCODER 0
-%define CONFIG_WEBVTT_ENCODER 0
-%define CONFIG_XSUB_ENCODER 0
-%define CONFIG_AAC_AT_ENCODER 0
-%define CONFIG_ALAC_AT_ENCODER 0
-%define CONFIG_ILBC_AT_ENCODER 0
-%define CONFIG_PCM_ALAW_AT_ENCODER 0
-%define CONFIG_PCM_MULAW_AT_ENCODER 0
-%define CONFIG_LIBFDK_AAC_ENCODER 0
-%define CONFIG_LIBGSM_ENCODER 0
-%define CONFIG_LIBGSM_MS_ENCODER 0
-%define CONFIG_LIBILBC_ENCODER 0
-%define CONFIG_LIBMP3LAME_ENCODER 0
-%define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-%define CONFIG_LIBOPENJPEG_ENCODER 0
-%define CONFIG_LIBOPUS_ENCODER 0
-%define CONFIG_LIBSCHROEDINGER_ENCODER 0
-%define CONFIG_LIBSHINE_ENCODER 0
-%define CONFIG_LIBSPEEX_ENCODER 0
-%define CONFIG_LIBTHEORA_ENCODER 0
-%define CONFIG_LIBTWOLAME_ENCODER 0
-%define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-%define CONFIG_LIBVORBIS_ENCODER 0
-%define CONFIG_LIBVPX_VP8_ENCODER 0
-%define CONFIG_LIBVPX_VP9_ENCODER 0
-%define CONFIG_LIBWAVPACK_ENCODER 0
-%define CONFIG_LIBWEBP_ANIM_ENCODER 0
-%define CONFIG_LIBWEBP_ENCODER 0
-%define CONFIG_LIBX262_ENCODER 0
-%define CONFIG_LIBX264_ENCODER 0
-%define CONFIG_LIBX264RGB_ENCODER 0
-%define CONFIG_LIBX265_ENCODER 0
-%define CONFIG_LIBXAVS_ENCODER 0
-%define CONFIG_LIBXVID_ENCODER 0
-%define CONFIG_LIBOPENH264_ENCODER 0
-%define CONFIG_H264_NVENC_ENCODER 0
-%define CONFIG_H264_OMX_ENCODER 0
-%define CONFIG_H264_QSV_ENCODER 0
-%define CONFIG_H264_VAAPI_ENCODER 0
-%define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-%define CONFIG_NVENC_ENCODER 0
-%define CONFIG_NVENC_H264_ENCODER 0
-%define CONFIG_NVENC_HEVC_ENCODER 0
-%define CONFIG_HEVC_NVENC_ENCODER 0
-%define CONFIG_HEVC_QSV_ENCODER 0
-%define CONFIG_HEVC_VAAPI_ENCODER 0
-%define CONFIG_LIBKVAZAAR_ENCODER 0
-%define CONFIG_MJPEG_VAAPI_ENCODER 0
-%define CONFIG_MPEG2_QSV_ENCODER 0
-%define CONFIG_ABENCH_FILTER 0
-%define CONFIG_ACOMPRESSOR_FILTER 0
-%define CONFIG_ACROSSFADE_FILTER 0
-%define CONFIG_ACRUSHER_FILTER 0
-%define CONFIG_ADELAY_FILTER 0
-%define CONFIG_AECHO_FILTER 0
-%define CONFIG_AEMPHASIS_FILTER 0
-%define CONFIG_AEVAL_FILTER 0
-%define CONFIG_AFADE_FILTER 0
-%define CONFIG_AFFTFILT_FILTER 0
-%define CONFIG_AFORMAT_FILTER 0
-%define CONFIG_AGATE_FILTER 0
-%define CONFIG_AINTERLEAVE_FILTER 0
-%define CONFIG_ALIMITER_FILTER 0
-%define CONFIG_ALLPASS_FILTER 0
-%define CONFIG_ALOOP_FILTER 0
-%define CONFIG_AMERGE_FILTER 0
-%define CONFIG_AMETADATA_FILTER 0
-%define CONFIG_AMIX_FILTER 0
-%define CONFIG_ANEQUALIZER_FILTER 0
-%define CONFIG_ANULL_FILTER 0
-%define CONFIG_APAD_FILTER 0
-%define CONFIG_APERMS_FILTER 0
-%define CONFIG_APHASER_FILTER 0
-%define CONFIG_APULSATOR_FILTER 0
-%define CONFIG_AREALTIME_FILTER 0
-%define CONFIG_ARESAMPLE_FILTER 0
-%define CONFIG_AREVERSE_FILTER 0
-%define CONFIG_ASELECT_FILTER 0
-%define CONFIG_ASENDCMD_FILTER 0
-%define CONFIG_ASETNSAMPLES_FILTER 0
-%define CONFIG_ASETPTS_FILTER 0
-%define CONFIG_ASETRATE_FILTER 0
-%define CONFIG_ASETTB_FILTER 0
-%define CONFIG_ASHOWINFO_FILTER 0
-%define CONFIG_ASIDEDATA_FILTER 0
-%define CONFIG_ASPLIT_FILTER 0
-%define CONFIG_ASTATS_FILTER 0
-%define CONFIG_ASTREAMSELECT_FILTER 0
-%define CONFIG_ASYNCTS_FILTER 0
-%define CONFIG_ATEMPO_FILTER 0
-%define CONFIG_ATRIM_FILTER 0
-%define CONFIG_AZMQ_FILTER 0
-%define CONFIG_BANDPASS_FILTER 0
-%define CONFIG_BANDREJECT_FILTER 0
-%define CONFIG_BASS_FILTER 0
-%define CONFIG_BIQUAD_FILTER 0
-%define CONFIG_BS2B_FILTER 0
-%define CONFIG_CHANNELMAP_FILTER 0
-%define CONFIG_CHANNELSPLIT_FILTER 0
-%define CONFIG_CHORUS_FILTER 0
-%define CONFIG_COMPAND_FILTER 0
-%define CONFIG_COMPENSATIONDELAY_FILTER 0
-%define CONFIG_CRYSTALIZER_FILTER 0
-%define CONFIG_DCSHIFT_FILTER 0
-%define CONFIG_DYNAUDNORM_FILTER 0
-%define CONFIG_EARWAX_FILTER 0
-%define CONFIG_EBUR128_FILTER 0
-%define CONFIG_EQUALIZER_FILTER 0
-%define CONFIG_EXTRASTEREO_FILTER 0
-%define CONFIG_FIREQUALIZER_FILTER 0
-%define CONFIG_FLANGER_FILTER 0
-%define CONFIG_HDCD_FILTER 0
-%define CONFIG_HIGHPASS_FILTER 0
-%define CONFIG_JOIN_FILTER 0
-%define CONFIG_LADSPA_FILTER 0
-%define CONFIG_LOUDNORM_FILTER 0
-%define CONFIG_LOWPASS_FILTER 0
-%define CONFIG_PAN_FILTER 0
-%define CONFIG_REPLAYGAIN_FILTER 0
-%define CONFIG_RESAMPLE_FILTER 0
-%define CONFIG_RUBBERBAND_FILTER 0
-%define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-%define CONFIG_SIDECHAINGATE_FILTER 0
-%define CONFIG_SILENCEDETECT_FILTER 0
-%define CONFIG_SILENCEREMOVE_FILTER 0
-%define CONFIG_SOFALIZER_FILTER 0
-%define CONFIG_STEREOTOOLS_FILTER 0
-%define CONFIG_STEREOWIDEN_FILTER 0
-%define CONFIG_TREBLE_FILTER 0
-%define CONFIG_TREMOLO_FILTER 0
-%define CONFIG_VIBRATO_FILTER 0
-%define CONFIG_VOLUME_FILTER 0
-%define CONFIG_VOLUMEDETECT_FILTER 0
-%define CONFIG_AEVALSRC_FILTER 0
-%define CONFIG_ANOISESRC_FILTER 0
-%define CONFIG_ANULLSRC_FILTER 0
-%define CONFIG_FLITE_FILTER 0
-%define CONFIG_SINE_FILTER 0
-%define CONFIG_ANULLSINK_FILTER 0
-%define CONFIG_ALPHAEXTRACT_FILTER 0
-%define CONFIG_ALPHAMERGE_FILTER 0
-%define CONFIG_ASS_FILTER 0
-%define CONFIG_ATADENOISE_FILTER 0
-%define CONFIG_AVGBLUR_FILTER 0
-%define CONFIG_BBOX_FILTER 0
-%define CONFIG_BENCH_FILTER 0
-%define CONFIG_BITPLANENOISE_FILTER 0
-%define CONFIG_BLACKDETECT_FILTER 0
-%define CONFIG_BLACKFRAME_FILTER 0
-%define CONFIG_BLEND_FILTER 0
-%define CONFIG_BOXBLUR_FILTER 0
-%define CONFIG_BWDIF_FILTER 0
-%define CONFIG_CHROMAKEY_FILTER 0
-%define CONFIG_CIESCOPE_FILTER 0
-%define CONFIG_CODECVIEW_FILTER 0
-%define CONFIG_COLORBALANCE_FILTER 0
-%define CONFIG_COLORCHANNELMIXER_FILTER 0
-%define CONFIG_COLORKEY_FILTER 0
-%define CONFIG_COLORLEVELS_FILTER 0
-%define CONFIG_COLORMATRIX_FILTER 0
-%define CONFIG_COLORSPACE_FILTER 0
-%define CONFIG_CONVOLUTION_FILTER 0
-%define CONFIG_COPY_FILTER 0
-%define CONFIG_COREIMAGE_FILTER 0
-%define CONFIG_COVER_RECT_FILTER 0
-%define CONFIG_CROP_FILTER 0
-%define CONFIG_CROPDETECT_FILTER 0
-%define CONFIG_CURVES_FILTER 0
-%define CONFIG_DATASCOPE_FILTER 0
-%define CONFIG_DCTDNOIZ_FILTER 0
-%define CONFIG_DEBAND_FILTER 0
-%define CONFIG_DECIMATE_FILTER 0
-%define CONFIG_DEFLATE_FILTER 0
-%define CONFIG_DEJUDDER_FILTER 0
-%define CONFIG_DELOGO_FILTER 0
-%define CONFIG_DESHAKE_FILTER 0
-%define CONFIG_DETELECINE_FILTER 0
-%define CONFIG_DILATION_FILTER 0
-%define CONFIG_DISPLACE_FILTER 0
-%define CONFIG_DRAWBOX_FILTER 0
-%define CONFIG_DRAWGRAPH_FILTER 0
-%define CONFIG_DRAWGRID_FILTER 0
-%define CONFIG_DRAWTEXT_FILTER 0
-%define CONFIG_EDGEDETECT_FILTER 0
-%define CONFIG_ELBG_FILTER 0
-%define CONFIG_EQ_FILTER 0
-%define CONFIG_EROSION_FILTER 0
-%define CONFIG_EXTRACTPLANES_FILTER 0
-%define CONFIG_FADE_FILTER 0
-%define CONFIG_FFTFILT_FILTER 0
-%define CONFIG_FIELD_FILTER 0
-%define CONFIG_FIELDHINT_FILTER 0
-%define CONFIG_FIELDMATCH_FILTER 0
-%define CONFIG_FIELDORDER_FILTER 0
-%define CONFIG_FIND_RECT_FILTER 0
-%define CONFIG_FORMAT_FILTER 0
-%define CONFIG_FPS_FILTER 0
-%define CONFIG_FRAMEPACK_FILTER 0
-%define CONFIG_FRAMERATE_FILTER 0
-%define CONFIG_FRAMESTEP_FILTER 0
-%define CONFIG_FREI0R_FILTER 0
-%define CONFIG_FSPP_FILTER 0
-%define CONFIG_GBLUR_FILTER 0
-%define CONFIG_GEQ_FILTER 0
-%define CONFIG_GRADFUN_FILTER 0
-%define CONFIG_HALDCLUT_FILTER 0
-%define CONFIG_HFLIP_FILTER 0
-%define CONFIG_HISTEQ_FILTER 0
-%define CONFIG_HISTOGRAM_FILTER 0
-%define CONFIG_HQDN3D_FILTER 0
-%define CONFIG_HQX_FILTER 0
-%define CONFIG_HSTACK_FILTER 0
-%define CONFIG_HUE_FILTER 0
-%define CONFIG_HWDOWNLOAD_FILTER 0
-%define CONFIG_HWUPLOAD_FILTER 0
-%define CONFIG_HWUPLOAD_CUDA_FILTER 0
-%define CONFIG_HYSTERESIS_FILTER 0
-%define CONFIG_IDET_FILTER 0
-%define CONFIG_IL_FILTER 0
-%define CONFIG_INFLATE_FILTER 0
-%define CONFIG_INTERLACE_FILTER 0
-%define CONFIG_INTERLEAVE_FILTER 0
-%define CONFIG_KERNDEINT_FILTER 0
-%define CONFIG_LENSCORRECTION_FILTER 0
-%define CONFIG_LOOP_FILTER 0
-%define CONFIG_LUT_FILTER 0
-%define CONFIG_LUT2_FILTER 0
-%define CONFIG_LUT3D_FILTER 0
-%define CONFIG_LUTRGB_FILTER 0
-%define CONFIG_LUTYUV_FILTER 0
-%define CONFIG_MASKEDCLAMP_FILTER 0
-%define CONFIG_MASKEDMERGE_FILTER 0
-%define CONFIG_MCDEINT_FILTER 0
-%define CONFIG_MERGEPLANES_FILTER 0
-%define CONFIG_MESTIMATE_FILTER 0
-%define CONFIG_METADATA_FILTER 0
-%define CONFIG_MINTERPOLATE_FILTER 0
-%define CONFIG_MPDECIMATE_FILTER 0
-%define CONFIG_NEGATE_FILTER 0
-%define CONFIG_NLMEANS_FILTER 0
-%define CONFIG_NNEDI_FILTER 0
-%define CONFIG_NOFORMAT_FILTER 0
-%define CONFIG_NOISE_FILTER 0
-%define CONFIG_NULL_FILTER 0
-%define CONFIG_OCR_FILTER 0
-%define CONFIG_OCV_FILTER 0
-%define CONFIG_OVERLAY_FILTER 0
-%define CONFIG_OWDENOISE_FILTER 0
-%define CONFIG_PAD_FILTER 0
-%define CONFIG_PALETTEGEN_FILTER 0
-%define CONFIG_PALETTEUSE_FILTER 0
-%define CONFIG_PERMS_FILTER 0
-%define CONFIG_PERSPECTIVE_FILTER 0
-%define CONFIG_PHASE_FILTER 0
-%define CONFIG_PIXDESCTEST_FILTER 0
-%define CONFIG_PP_FILTER 0
-%define CONFIG_PP7_FILTER 0
-%define CONFIG_PREWITT_FILTER 0
-%define CONFIG_PSNR_FILTER 0
-%define CONFIG_PULLUP_FILTER 0
-%define CONFIG_QP_FILTER 0
-%define CONFIG_RANDOM_FILTER 0
-%define CONFIG_READVITC_FILTER 0
-%define CONFIG_REALTIME_FILTER 0
-%define CONFIG_REMAP_FILTER 0
-%define CONFIG_REMOVEGRAIN_FILTER 0
-%define CONFIG_REMOVELOGO_FILTER 0
-%define CONFIG_REPEATFIELDS_FILTER 0
-%define CONFIG_REVERSE_FILTER 0
-%define CONFIG_ROTATE_FILTER 0
-%define CONFIG_SAB_FILTER 0
-%define CONFIG_SCALE_FILTER 0
-%define CONFIG_SCALE_NPP_FILTER 0
-%define CONFIG_SCALE_VAAPI_FILTER 0
-%define CONFIG_SCALE2REF_FILTER 0
-%define CONFIG_SELECT_FILTER 0
-%define CONFIG_SELECTIVECOLOR_FILTER 0
-%define CONFIG_SENDCMD_FILTER 0
-%define CONFIG_SEPARATEFIELDS_FILTER 0
-%define CONFIG_SETDAR_FILTER 0
-%define CONFIG_SETFIELD_FILTER 0
-%define CONFIG_SETPTS_FILTER 0
-%define CONFIG_SETSAR_FILTER 0
-%define CONFIG_SETTB_FILTER 0
-%define CONFIG_SHOWINFO_FILTER 0
-%define CONFIG_SHOWPALETTE_FILTER 0
-%define CONFIG_SHUFFLEFRAMES_FILTER 0
-%define CONFIG_SHUFFLEPLANES_FILTER 0
-%define CONFIG_SIDEDATA_FILTER 0
-%define CONFIG_SIGNALSTATS_FILTER 0
-%define CONFIG_SMARTBLUR_FILTER 0
-%define CONFIG_SOBEL_FILTER 0
-%define CONFIG_SPLIT_FILTER 0
-%define CONFIG_SPP_FILTER 0
-%define CONFIG_SSIM_FILTER 0
-%define CONFIG_STEREO3D_FILTER 0
-%define CONFIG_STREAMSELECT_FILTER 0
-%define CONFIG_SUBTITLES_FILTER 0
-%define CONFIG_SUPER2XSAI_FILTER 0
-%define CONFIG_SWAPRECT_FILTER 0
-%define CONFIG_SWAPUV_FILTER 0
-%define CONFIG_TBLEND_FILTER 0
-%define CONFIG_TELECINE_FILTER 0
-%define CONFIG_THUMBNAIL_FILTER 0
-%define CONFIG_TILE_FILTER 0
-%define CONFIG_TINTERLACE_FILTER 0
-%define CONFIG_TRANSPOSE_FILTER 0
-%define CONFIG_TRIM_FILTER 0
-%define CONFIG_UNSHARP_FILTER 0
-%define CONFIG_USPP_FILTER 0
-%define CONFIG_VAGUEDENOISER_FILTER 0
-%define CONFIG_VECTORSCOPE_FILTER 0
-%define CONFIG_VFLIP_FILTER 0
-%define CONFIG_VIDSTABDETECT_FILTER 0
-%define CONFIG_VIDSTABTRANSFORM_FILTER 0
-%define CONFIG_VIGNETTE_FILTER 0
-%define CONFIG_VSTACK_FILTER 0
-%define CONFIG_W3FDIF_FILTER 0
-%define CONFIG_WAVEFORM_FILTER 0
-%define CONFIG_WEAVE_FILTER 0
-%define CONFIG_XBR_FILTER 0
-%define CONFIG_YADIF_FILTER 0
-%define CONFIG_ZMQ_FILTER 0
-%define CONFIG_ZOOMPAN_FILTER 0
-%define CONFIG_ZSCALE_FILTER 0
-%define CONFIG_ALLRGB_FILTER 0
-%define CONFIG_ALLYUV_FILTER 0
-%define CONFIG_CELLAUTO_FILTER 0
-%define CONFIG_COLOR_FILTER 0
-%define CONFIG_COREIMAGESRC_FILTER 0
-%define CONFIG_FREI0R_SRC_FILTER 0
-%define CONFIG_HALDCLUTSRC_FILTER 0
-%define CONFIG_LIFE_FILTER 0
-%define CONFIG_MANDELBROT_FILTER 0
-%define CONFIG_MPTESTSRC_FILTER 0
-%define CONFIG_NULLSRC_FILTER 0
-%define CONFIG_RGBTESTSRC_FILTER 0
-%define CONFIG_SMPTEBARS_FILTER 0
-%define CONFIG_SMPTEHDBARS_FILTER 0
-%define CONFIG_TESTSRC_FILTER 0
-%define CONFIG_TESTSRC2_FILTER 0
-%define CONFIG_YUVTESTSRC_FILTER 0
-%define CONFIG_NULLSINK_FILTER 0
-%define CONFIG_ADRAWGRAPH_FILTER 0
-%define CONFIG_AHISTOGRAM_FILTER 0
-%define CONFIG_APHASEMETER_FILTER 0
-%define CONFIG_AVECTORSCOPE_FILTER 0
-%define CONFIG_CONCAT_FILTER 0
-%define CONFIG_SHOWCQT_FILTER 0
-%define CONFIG_SHOWFREQS_FILTER 0
-%define CONFIG_SHOWSPECTRUM_FILTER 0
-%define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-%define CONFIG_SHOWVOLUME_FILTER 0
-%define CONFIG_SHOWWAVES_FILTER 0
-%define CONFIG_SHOWWAVESPIC_FILTER 0
-%define CONFIG_SPECTRUMSYNTH_FILTER 0
-%define CONFIG_AMOVIE_FILTER 0
-%define CONFIG_MOVIE_FILTER 0
-%define CONFIG_H263_CUVID_HWACCEL 0
-%define CONFIG_H263_VAAPI_HWACCEL 0
-%define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_H264_CUVID_HWACCEL 0
-%define CONFIG_H264_D3D11VA_HWACCEL 0
-%define CONFIG_H264_DXVA2_HWACCEL 0
-%define CONFIG_H264_MEDIACODEC_HWACCEL 0
-%define CONFIG_H264_MMAL_HWACCEL 0
-%define CONFIG_H264_QSV_HWACCEL 0
-%define CONFIG_H264_VAAPI_HWACCEL 0
-%define CONFIG_H264_VDA_HWACCEL 0
-%define CONFIG_H264_VDA_OLD_HWACCEL 0
-%define CONFIG_H264_VDPAU_HWACCEL 0
-%define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_HEVC_CUVID_HWACCEL 0
-%define CONFIG_HEVC_D3D11VA_HWACCEL 0
-%define CONFIG_HEVC_DXVA2_HWACCEL 0
-%define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-%define CONFIG_HEVC_QSV_HWACCEL 0
-%define CONFIG_HEVC_VAAPI_HWACCEL 0
-%define CONFIG_HEVC_VDPAU_HWACCEL 0
-%define CONFIG_MJPEG_CUVID_HWACCEL 0
-%define CONFIG_MPEG1_CUVID_HWACCEL 0
-%define CONFIG_MPEG1_XVMC_HWACCEL 0
-%define CONFIG_MPEG1_VDPAU_HWACCEL 0
-%define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_MPEG2_CUVID_HWACCEL 0
-%define CONFIG_MPEG2_XVMC_HWACCEL 0
-%define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-%define CONFIG_MPEG2_DXVA2_HWACCEL 0
-%define CONFIG_MPEG2_MMAL_HWACCEL 0
-%define CONFIG_MPEG2_QSV_HWACCEL 0
-%define CONFIG_MPEG2_VAAPI_HWACCEL 0
-%define CONFIG_MPEG2_VDPAU_HWACCEL 0
-%define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_MPEG4_CUVID_HWACCEL 0
-%define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-%define CONFIG_MPEG4_MMAL_HWACCEL 0
-%define CONFIG_MPEG4_VAAPI_HWACCEL 0
-%define CONFIG_MPEG4_VDPAU_HWACCEL 0
-%define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_VC1_CUVID_HWACCEL 0
-%define CONFIG_VC1_D3D11VA_HWACCEL 0
-%define CONFIG_VC1_DXVA2_HWACCEL 0
-%define CONFIG_VC1_VAAPI_HWACCEL 0
-%define CONFIG_VC1_VDPAU_HWACCEL 0
-%define CONFIG_VC1_MMAL_HWACCEL 0
-%define CONFIG_VC1_QSV_HWACCEL 0
-%define CONFIG_VP8_CUVID_HWACCEL 0
-%define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-%define CONFIG_VP9_CUVID_HWACCEL 0
-%define CONFIG_VP9_D3D11VA_HWACCEL 0
-%define CONFIG_VP9_DXVA2_HWACCEL 0
-%define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-%define CONFIG_VP9_VAAPI_HWACCEL 0
-%define CONFIG_WMV3_D3D11VA_HWACCEL 0
-%define CONFIG_WMV3_DXVA2_HWACCEL 0
-%define CONFIG_WMV3_VAAPI_HWACCEL 0
-%define CONFIG_WMV3_VDPAU_HWACCEL 0
-%define CONFIG_ALSA_INDEV 0
-%define CONFIG_AVFOUNDATION_INDEV 0
-%define CONFIG_BKTR_INDEV 0
-%define CONFIG_DECKLINK_INDEV 0
-%define CONFIG_DSHOW_INDEV 0
-%define CONFIG_DV1394_INDEV 0
-%define CONFIG_FBDEV_INDEV 0
-%define CONFIG_GDIGRAB_INDEV 0
-%define CONFIG_IEC61883_INDEV 0
-%define CONFIG_JACK_INDEV 0
-%define CONFIG_LAVFI_INDEV 0
-%define CONFIG_OPENAL_INDEV 0
-%define CONFIG_OSS_INDEV 0
-%define CONFIG_PULSE_INDEV 0
-%define CONFIG_QTKIT_INDEV 0
-%define CONFIG_SNDIO_INDEV 0
-%define CONFIG_V4L2_INDEV 0
-%define CONFIG_VFWCAP_INDEV 0
-%define CONFIG_X11GRAB_INDEV 0
-%define CONFIG_X11GRAB_XCB_INDEV 0
-%define CONFIG_LIBCDIO_INDEV 0
-%define CONFIG_LIBDC1394_INDEV 0
-%define CONFIG_A64_MUXER 0
-%define CONFIG_AC3_MUXER 0
-%define CONFIG_ADTS_MUXER 0
-%define CONFIG_ADX_MUXER 0
-%define CONFIG_AIFF_MUXER 0
-%define CONFIG_AMR_MUXER 0
-%define CONFIG_APNG_MUXER 0
-%define CONFIG_ASF_MUXER 0
-%define CONFIG_ASS_MUXER 0
-%define CONFIG_AST_MUXER 0
-%define CONFIG_ASF_STREAM_MUXER 0
-%define CONFIG_AU_MUXER 0
-%define CONFIG_AVI_MUXER 0
-%define CONFIG_AVM2_MUXER 0
-%define CONFIG_BIT_MUXER 0
-%define CONFIG_CAF_MUXER 0
-%define CONFIG_CAVSVIDEO_MUXER 0
-%define CONFIG_CRC_MUXER 0
-%define CONFIG_DASH_MUXER 0
-%define CONFIG_DATA_MUXER 0
-%define CONFIG_DAUD_MUXER 0
-%define CONFIG_DIRAC_MUXER 0
-%define CONFIG_DNXHD_MUXER 0
-%define CONFIG_DTS_MUXER 0
-%define CONFIG_DV_MUXER 0
-%define CONFIG_EAC3_MUXER 0
-%define CONFIG_F4V_MUXER 0
-%define CONFIG_FFM_MUXER 0
-%define CONFIG_FFMETADATA_MUXER 0
-%define CONFIG_FIFO_MUXER 0
-%define CONFIG_FILMSTRIP_MUXER 0
-%define CONFIG_FLAC_MUXER 0
-%define CONFIG_FLV_MUXER 0
-%define CONFIG_FRAMECRC_MUXER 0
-%define CONFIG_FRAMEHASH_MUXER 0
-%define CONFIG_FRAMEMD5_MUXER 0
-%define CONFIG_G722_MUXER 0
-%define CONFIG_G723_1_MUXER 0
-%define CONFIG_GIF_MUXER 0
-%define CONFIG_GSM_MUXER 0
-%define CONFIG_GXF_MUXER 0
-%define CONFIG_H261_MUXER 0
-%define CONFIG_H263_MUXER 0
-%define CONFIG_H264_MUXER 0
-%define CONFIG_HASH_MUXER 0
-%define CONFIG_HDS_MUXER 0
-%define CONFIG_HEVC_MUXER 0
-%define CONFIG_HLS_MUXER 0
-%define CONFIG_ICO_MUXER 0
-%define CONFIG_ILBC_MUXER 0
-%define CONFIG_IMAGE2_MUXER 0
-%define CONFIG_IMAGE2PIPE_MUXER 0
-%define CONFIG_IPOD_MUXER 0
-%define CONFIG_IRCAM_MUXER 0
-%define CONFIG_ISMV_MUXER 0
-%define CONFIG_IVF_MUXER 0
-%define CONFIG_JACOSUB_MUXER 0
-%define CONFIG_LATM_MUXER 0
-%define CONFIG_LRC_MUXER 0
-%define CONFIG_M4V_MUXER 0
-%define CONFIG_MD5_MUXER 0
-%define CONFIG_MATROSKA_MUXER 0
-%define CONFIG_MATROSKA_AUDIO_MUXER 0
-%define CONFIG_MICRODVD_MUXER 0
-%define CONFIG_MJPEG_MUXER 0
-%define CONFIG_MLP_MUXER 0
-%define CONFIG_MMF_MUXER 0
-%define CONFIG_MOV_MUXER 0
-%define CONFIG_MP2_MUXER 0
-%define CONFIG_MP3_MUXER 0
-%define CONFIG_MP4_MUXER 0
-%define CONFIG_MPEG1SYSTEM_MUXER 0
-%define CONFIG_MPEG1VCD_MUXER 0
-%define CONFIG_MPEG1VIDEO_MUXER 0
-%define CONFIG_MPEG2DVD_MUXER 0
-%define CONFIG_MPEG2SVCD_MUXER 0
-%define CONFIG_MPEG2VIDEO_MUXER 0
-%define CONFIG_MPEG2VOB_MUXER 0
-%define CONFIG_MPEGTS_MUXER 0
-%define CONFIG_MPJPEG_MUXER 0
-%define CONFIG_MXF_MUXER 0
-%define CONFIG_MXF_D10_MUXER 0
-%define CONFIG_MXF_OPATOM_MUXER 0
-%define CONFIG_NULL_MUXER 0
-%define CONFIG_NUT_MUXER 0
-%define CONFIG_OGA_MUXER 0
-%define CONFIG_OGG_MUXER 0
-%define CONFIG_OGV_MUXER 0
-%define CONFIG_OMA_MUXER 0
-%define CONFIG_OPUS_MUXER 0
-%define CONFIG_PCM_ALAW_MUXER 0
-%define CONFIG_PCM_MULAW_MUXER 0
-%define CONFIG_PCM_F64BE_MUXER 0
-%define CONFIG_PCM_F64LE_MUXER 0
-%define CONFIG_PCM_F32BE_MUXER 0
-%define CONFIG_PCM_F32LE_MUXER 0
-%define CONFIG_PCM_S32BE_MUXER 0
-%define CONFIG_PCM_S32LE_MUXER 0
-%define CONFIG_PCM_S24BE_MUXER 0
-%define CONFIG_PCM_S24LE_MUXER 0
-%define CONFIG_PCM_S16BE_MUXER 0
-%define CONFIG_PCM_S16LE_MUXER 0
-%define CONFIG_PCM_S8_MUXER 0
-%define CONFIG_PCM_U32BE_MUXER 0
-%define CONFIG_PCM_U32LE_MUXER 0
-%define CONFIG_PCM_U24BE_MUXER 0
-%define CONFIG_PCM_U24LE_MUXER 0
-%define CONFIG_PCM_U16BE_MUXER 0
-%define CONFIG_PCM_U16LE_MUXER 0
-%define CONFIG_PCM_U8_MUXER 0
-%define CONFIG_PSP_MUXER 0
-%define CONFIG_RAWVIDEO_MUXER 0
-%define CONFIG_RM_MUXER 0
-%define CONFIG_ROQ_MUXER 0
-%define CONFIG_RSO_MUXER 0
-%define CONFIG_RTP_MUXER 0
-%define CONFIG_RTP_MPEGTS_MUXER 0
-%define CONFIG_RTSP_MUXER 0
-%define CONFIG_SAP_MUXER 0
-%define CONFIG_SEGMENT_MUXER 0
-%define CONFIG_STREAM_SEGMENT_MUXER 0
-%define CONFIG_SINGLEJPEG_MUXER 0
-%define CONFIG_SMJPEG_MUXER 0
-%define CONFIG_SMOOTHSTREAMING_MUXER 0
-%define CONFIG_SOX_MUXER 0
-%define CONFIG_SPX_MUXER 0
-%define CONFIG_SPDIF_MUXER 0
-%define CONFIG_SRT_MUXER 0
-%define CONFIG_SWF_MUXER 0
-%define CONFIG_TEE_MUXER 0
-%define CONFIG_TG2_MUXER 0
-%define CONFIG_TGP_MUXER 0
-%define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-%define CONFIG_TRUEHD_MUXER 0
-%define CONFIG_TTA_MUXER 0
-%define CONFIG_UNCODEDFRAMECRC_MUXER 0
-%define CONFIG_VC1_MUXER 0
-%define CONFIG_VC1T_MUXER 0
-%define CONFIG_VOC_MUXER 0
-%define CONFIG_W64_MUXER 0
-%define CONFIG_WAV_MUXER 0
-%define CONFIG_WEBM_MUXER 0
-%define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-%define CONFIG_WEBM_CHUNK_MUXER 0
-%define CONFIG_WEBP_MUXER 0
-%define CONFIG_WEBVTT_MUXER 0
-%define CONFIG_WTV_MUXER 0
-%define CONFIG_WV_MUXER 0
-%define CONFIG_YUV4MPEGPIPE_MUXER 0
-%define CONFIG_CHROMAPRINT_MUXER 0
-%define CONFIG_LIBNUT_MUXER 0
-%define CONFIG_ALSA_OUTDEV 0
-%define CONFIG_CACA_OUTDEV 0
-%define CONFIG_DECKLINK_OUTDEV 0
-%define CONFIG_FBDEV_OUTDEV 0
-%define CONFIG_OPENGL_OUTDEV 0
-%define CONFIG_OSS_OUTDEV 0
-%define CONFIG_PULSE_OUTDEV 0
-%define CONFIG_SDL2_OUTDEV 0
-%define CONFIG_SNDIO_OUTDEV 0
-%define CONFIG_V4L2_OUTDEV 0
-%define CONFIG_XV_OUTDEV 0
-%define CONFIG_AAC_PARSER 0
-%define CONFIG_AAC_LATM_PARSER 0
-%define CONFIG_AC3_PARSER 0
-%define CONFIG_ADX_PARSER 0
-%define CONFIG_BMP_PARSER 0
-%define CONFIG_CAVSVIDEO_PARSER 0
-%define CONFIG_COOK_PARSER 0
-%define CONFIG_DCA_PARSER 0
-%define CONFIG_DIRAC_PARSER 0
-%define CONFIG_DNXHD_PARSER 0
-%define CONFIG_DPX_PARSER 0
-%define CONFIG_DVAUDIO_PARSER 0
-%define CONFIG_DVBSUB_PARSER 0
-%define CONFIG_DVDSUB_PARSER 0
-%define CONFIG_DVD_NAV_PARSER 0
-%define CONFIG_FLAC_PARSER 1
-%define CONFIG_G729_PARSER 0
-%define CONFIG_GSM_PARSER 0
-%define CONFIG_H261_PARSER 0
-%define CONFIG_H263_PARSER 0
-%define CONFIG_H264_PARSER 0
-%define CONFIG_HEVC_PARSER 0
-%define CONFIG_MJPEG_PARSER 0
-%define CONFIG_MLP_PARSER 0
-%define CONFIG_MPEG4VIDEO_PARSER 0
-%define CONFIG_MPEGAUDIO_PARSER 0
-%define CONFIG_MPEGVIDEO_PARSER 0
-%define CONFIG_OPUS_PARSER 0
-%define CONFIG_PNG_PARSER 0
-%define CONFIG_PNM_PARSER 0
-%define CONFIG_RV30_PARSER 0
-%define CONFIG_RV40_PARSER 0
-%define CONFIG_TAK_PARSER 0
-%define CONFIG_VC1_PARSER 0
-%define CONFIG_VORBIS_PARSER 0
-%define CONFIG_VP3_PARSER 0
+%define CONFIG_FLAC_PARSER 0
%define CONFIG_VP8_PARSER 1
%define CONFIG_VP9_PARSER 1
-%define CONFIG_ASYNC_PROTOCOL 0
-%define CONFIG_BLURAY_PROTOCOL 0
-%define CONFIG_CACHE_PROTOCOL 0
-%define CONFIG_CONCAT_PROTOCOL 0
-%define CONFIG_CRYPTO_PROTOCOL 0
-%define CONFIG_DATA_PROTOCOL 0
-%define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-%define CONFIG_FFRTMPHTTP_PROTOCOL 0
-%define CONFIG_FILE_PROTOCOL 0
-%define CONFIG_FTP_PROTOCOL 0
-%define CONFIG_GOPHER_PROTOCOL 0
-%define CONFIG_HLS_PROTOCOL 0
-%define CONFIG_HTTP_PROTOCOL 0
-%define CONFIG_HTTPPROXY_PROTOCOL 0
-%define CONFIG_HTTPS_PROTOCOL 0
-%define CONFIG_ICECAST_PROTOCOL 0
-%define CONFIG_MMSH_PROTOCOL 0
-%define CONFIG_MMST_PROTOCOL 0
-%define CONFIG_MD5_PROTOCOL 0
-%define CONFIG_PIPE_PROTOCOL 0
-%define CONFIG_RTMP_PROTOCOL 0
-%define CONFIG_RTMPE_PROTOCOL 0
-%define CONFIG_RTMPS_PROTOCOL 0
-%define CONFIG_RTMPT_PROTOCOL 0
-%define CONFIG_RTMPTE_PROTOCOL 0
-%define CONFIG_RTMPTS_PROTOCOL 0
-%define CONFIG_RTP_PROTOCOL 0
-%define CONFIG_SCTP_PROTOCOL 0
-%define CONFIG_SRTP_PROTOCOL 0
-%define CONFIG_SUBFILE_PROTOCOL 0
-%define CONFIG_TEE_PROTOCOL 0
-%define CONFIG_TCP_PROTOCOL 0
-%define CONFIG_TLS_GNUTLS_PROTOCOL 0
-%define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-%define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-%define CONFIG_TLS_OPENSSL_PROTOCOL 0
-%define CONFIG_UDP_PROTOCOL 0
-%define CONFIG_UDPLITE_PROTOCOL 0
-%define CONFIG_UNIX_PROTOCOL 0
-%define CONFIG_LIBRTMP_PROTOCOL 0
-%define CONFIG_LIBRTMPE_PROTOCOL 0
-%define CONFIG_LIBRTMPS_PROTOCOL 0
-%define CONFIG_LIBRTMPT_PROTOCOL 0
-%define CONFIG_LIBRTMPTE_PROTOCOL 0
-%define CONFIG_LIBSSH_PROTOCOL 0
-%define CONFIG_LIBSMBCLIENT_PROTOCOL 0
diff --git a/media/ffvpx/config_win32.h b/media/ffvpx/config_win32.h
index b23b2ad9f..36bb2d3c3 100644
--- a/media/ffvpx/config_win32.h
+++ b/media/ffvpx/config_win32.h
@@ -1,12 +1,12 @@
/* Automatically generated by configure - do not modify! */
#ifndef FFMPEG_CONFIG_H
#define FFMPEG_CONFIG_H
-#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-asm --enable-yasm --toolchain=msvc"
+#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl2 --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vdpau --disable-videotoolbox --enable-decoder=flac --enable-asm --enable-x86asm --toolchain=msvc"
#define FFMPEG_LICENSE "LGPL version 2.1 or later"
-#define CONFIG_THIS_YEAR 2016
+#define CONFIG_THIS_YEAR 2017
#define FFMPEG_DATADIR "/usr/local/share/ffmpeg"
#define AVCONV_DATADIR "/usr/local/share/ffmpeg"
-#define CC_IDENT "Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x86"
+#define CC_IDENT "Microsoft (R) C/C++ Optimizing Compiler Version 19.11.25508.2 for x86"
#define av_restrict __restrict
#define EXTERN_PREFIX "_"
#define EXTERN_ASM _
@@ -79,8 +79,8 @@
#define HAVE_MIPSDSP 0
#define HAVE_MIPSDSPR2 0
#define HAVE_MSA 0
-#define HAVE_LOONGSON2 1
-#define HAVE_LOONGSON3 1
+#define HAVE_LOONGSON2 0
+#define HAVE_LOONGSON3 0
#define HAVE_MMI 0
#define HAVE_ARMV5TE_EXTERNAL 0
#define HAVE_ARMV6_EXTERNAL 0
@@ -172,37 +172,38 @@
#define HAVE_MMI_INLINE 0
#define HAVE_ALIGNED_STACK 0
#define HAVE_FAST_64BIT 0
-#define HAVE_FAST_CLZ 1
+#define HAVE_FAST_CLZ 0
#define HAVE_FAST_CMOV 0
#define HAVE_LOCAL_ALIGNED_8 1
#define HAVE_LOCAL_ALIGNED_16 1
#define HAVE_LOCAL_ALIGNED_32 1
#define HAVE_SIMD_ALIGN_16 1
+#define HAVE_SIMD_ALIGN_32 1
#define HAVE_ATOMICS_GCC 0
#define HAVE_ATOMICS_SUNCC 0
#define HAVE_ATOMICS_WIN32 1
#define HAVE_ATOMIC_CAS_PTR 0
-#define HAVE_ATOMIC_COMPARE_EXCHANGE 0
#define HAVE_MACHINE_RW_BARRIER 0
#define HAVE_MEMORYBARRIER 1
#define HAVE_MM_EMPTY 1
#define HAVE_RDTSC 1
#define HAVE_SARESTART 0
-#define HAVE_SEM_TIMEDWAIT 1
+#define HAVE_SEM_TIMEDWAIT 0
#define HAVE_SYNC_VAL_COMPARE_AND_SWAP 0
#define HAVE_CABS 0
#define HAVE_CEXP 0
#define HAVE_INLINE_ASM 0
#define HAVE_SYMVER 0
-#define HAVE_YASM 1
+#define HAVE_X86ASM 1
#define HAVE_BIGENDIAN 0
#define HAVE_FAST_UNALIGNED 1
-#define HAVE_ALSA_ASOUNDLIB_H 0
#define HAVE_ALTIVEC_H 0
#define HAVE_ARPA_INET_H 0
#define HAVE_ASM_TYPES_H 0
#define HAVE_CDIO_PARANOIA_H 0
#define HAVE_CDIO_PARANOIA_PARANOIA_H 0
+#define HAVE_CUDA_H 0
+#define HAVE_D3D11_H 1
#define HAVE_DISPATCH_DISPATCH_H 0
#define HAVE_DEV_BKTR_IOCTL_BT848_H 0
#define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
@@ -212,7 +213,7 @@
#define HAVE_DIRECT_H 1
#define HAVE_DIRENT_H 0
#define HAVE_DLFCN_H 0
-#define HAVE_D3D11_H 1
+#define HAVE_DXGIDEBUG_H 1
#define HAVE_DXVA_H 1
#define HAVE_ES2_GL_H 0
#define HAVE_GSM_H 0
@@ -221,13 +222,15 @@
#define HAVE_MACHINE_IOCTL_BT848_H 0
#define HAVE_MACHINE_IOCTL_METEOR_H 0
#define HAVE_OPENCV2_CORE_CORE_C_H 0
+#define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+#define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
#define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
#define HAVE_OPENGL_GL3_H 0
#define HAVE_POLL_H 0
-#define HAVE_SNDIO_H 0
#define HAVE_SOUNDCARD_H 0
+#define HAVE_STDATOMIC_H 0
#define HAVE_SYS_MMAN_H 0
#define HAVE_SYS_PARAM_H 0
#define HAVE_SYS_RESOURCE_H 0
@@ -279,7 +282,6 @@
#define HAVE_COMMANDLINETOARGVW 1
#define HAVE_COTASKMEMFREE 1
#define HAVE_CRYPTGENRANDOM 1
-#define HAVE_DLOPEN 0
#define HAVE_FCNTL 0
#define HAVE_FLT_LIM 1
#define HAVE_FORK 0
@@ -299,7 +301,7 @@
#define HAVE_ISATTY 1
#define HAVE_JACK_PORT_GET_LATENCY_RANGE 0
#define HAVE_KBHIT 1
-#define HAVE_LOADLIBRARY 0
+#define HAVE_LOADLIBRARY 1
#define HAVE_LSTAT 0
#define HAVE_LZO1X_999_COMPRESS 0
#define HAVE_MACH_ABSOLUTE_TIME 0
@@ -318,6 +320,7 @@
#define HAVE_SLEEP 1
#define HAVE_STRERROR_R 0
#define HAVE_SYSCONF 0
+#define HAVE_SYSCTL 0
#define HAVE_USLEEP 0
#define HAVE_UTGETOSTYPEFROMSTRING 0
#define HAVE_VIRTUALALLOC 1
@@ -326,11 +329,13 @@
#define HAVE_OS2THREADS 0
#define HAVE_W32THREADS 1
#define HAVE_AS_DN_DIRECTIVE 0
+#define HAVE_AS_FPU_DIRECTIVE 0
#define HAVE_AS_FUNC 0
#define HAVE_AS_OBJECT_ARCH 0
#define HAVE_ASM_MOD_Q 0
#define HAVE_ATTRIBUTE_MAY_ALIAS 0
#define HAVE_ATTRIBUTE_PACKED 0
+#define HAVE_BLOCKS_EXTENSION 0
#define HAVE_EBP_AVAILABLE 0
#define HAVE_EBX_AVAILABLE 0
#define HAVE_GNU_AS 0
@@ -347,12 +352,13 @@
#define HAVE_XFORM_ASM 0
#define HAVE_XMM_CLOBBERS 0
#define HAVE_CONDITION_VARIABLE_PTR 1
+#define HAVE_KCMVIDEOCODECTYPE_HEVC 0
#define HAVE_SOCKLEN_T 1
#define HAVE_STRUCT_ADDRINFO 1
#define HAVE_STRUCT_GROUP_SOURCE_REQ 1
#define HAVE_STRUCT_IP_MREQ_SOURCE 1
#define HAVE_STRUCT_IPV6_MREQ 1
-#define HAVE_STRUCT_MSGHDR_MSG_FLAGS 1
+#define HAVE_STRUCT_MSGHDR_MSG_FLAGS 0
#define HAVE_STRUCT_POLLFD 0
#define HAVE_STRUCT_RUSAGE_RU_MAXRSS 0
#define HAVE_STRUCT_SCTP_EVENT_SUBSCRIBE 0
@@ -363,36 +369,20 @@
#define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 0
#define HAVE_ATOMICS_NATIVE 1
#define HAVE_DOS_PATHS 1
-#define HAVE_DXVA2_LIB 0
-#define HAVE_DXVA2API_COBJ 1
#define HAVE_LIBC_MSVCRT 1
-#define HAVE_LIBDC1394_1 0
-#define HAVE_LIBDC1394_2 0
#define HAVE_MAKEINFO 1
#define HAVE_MAKEINFO_HTML 0
#define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
#define HAVE_PERL 1
#define HAVE_POD2MAN 1
-#define HAVE_SDL2 0
#define HAVE_SECTION_DATA_REL_RO 0
#define HAVE_TEXI2HTML 0
#define HAVE_THREADS 1
+#define HAVE_UWP 0
#define HAVE_VAAPI_DRM 0
#define HAVE_VAAPI_X11 0
#define HAVE_VDPAU_X11 0
#define HAVE_WINRT 0
-#define HAVE_XLIB 0
-#define CONFIG_BSFS 0
-#define CONFIG_DECODERS 1
-#define CONFIG_ENCODERS 0
-#define CONFIG_HWACCELS 0
-#define CONFIG_PARSERS 1
-#define CONFIG_INDEVS 0
-#define CONFIG_OUTDEVS 0
-#define CONFIG_FILTERS 0
-#define CONFIG_DEMUXERS 0
-#define CONFIG_MUXERS 0
-#define CONFIG_PROTOCOLS 0
#define CONFIG_DOC 0
#define CONFIG_HTMLPAGES 0
#define CONFIG_MANPAGES 1
@@ -400,13 +390,17 @@
#define CONFIG_TXTPAGES 1
#define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
#define CONFIG_AVIO_READING_EXAMPLE 1
-#define CONFIG_DECODING_ENCODING_EXAMPLE 0
+#define CONFIG_DECODE_AUDIO_EXAMPLE 1
+#define CONFIG_DECODE_VIDEO_EXAMPLE 1
#define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+#define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+#define CONFIG_ENCODE_VIDEO_EXAMPLE 1
#define CONFIG_EXTRACT_MVS_EXAMPLE 0
#define CONFIG_FILTER_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_VIDEO_EXAMPLE 0
#define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+#define CONFIG_HW_DECODE_EXAMPLE 0
#define CONFIG_METADATA_EXAMPLE 0
#define CONFIG_MUXING_EXAMPLE 0
#define CONFIG_QSVDEC_EXAMPLE 0
@@ -415,27 +409,55 @@
#define CONFIG_SCALING_VIDEO_EXAMPLE 0
#define CONFIG_TRANSCODE_AAC_EXAMPLE 0
#define CONFIG_TRANSCODING_EXAMPLE 0
-#define CONFIG_AVISYNTH 0
+#define CONFIG_ALSA 0
+#define CONFIG_APPKIT 0
+#define CONFIG_AVFOUNDATION 0
#define CONFIG_BZLIB 0
-#define CONFIG_CHROMAPRINT 0
-#define CONFIG_CRYSTALHD 0
-#define CONFIG_DECKLINK 0
+#define CONFIG_COREIMAGE 0
+#define CONFIG_ICONV 0
+#define CONFIG_JACK 0
+#define CONFIG_LIBXCB 0
+#define CONFIG_LIBXCB_SHM 0
+#define CONFIG_LIBXCB_SHAPE 0
+#define CONFIG_LIBXCB_XFIXES 0
+#define CONFIG_LZMA 0
+#define CONFIG_SCHANNEL 1
+#define CONFIG_SDL2 0
+#define CONFIG_SECURETRANSPORT 0
+#define CONFIG_SNDIO 0
+#define CONFIG_XLIB 1
+#define CONFIG_ZLIB 0
+#define CONFIG_AVISYNTH 0
#define CONFIG_FREI0R 0
-#define CONFIG_GCRYPT 0
+#define CONFIG_LIBCDIO 0
+#define CONFIG_LIBRUBBERBAND 0
+#define CONFIG_LIBVIDSTAB 0
+#define CONFIG_LIBX264 0
+#define CONFIG_LIBX265 0
+#define CONFIG_LIBXAVS 0
+#define CONFIG_LIBXVID 0
+#define CONFIG_DECKLINK 0
+#define CONFIG_LIBNDI_NEWTEK 0
+#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_OPENSSL 0
#define CONFIG_GMP 0
+#define CONFIG_LIBOPENCORE_AMRNB 0
+#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_RKMPP 0
+#define CONFIG_LIBSMBCLIENT 0
+#define CONFIG_CHROMAPRINT 0
+#define CONFIG_GCRYPT 0
#define CONFIG_GNUTLS 0
-#define CONFIG_ICONV 0
#define CONFIG_JNI 0
#define CONFIG_LADSPA 0
#define CONFIG_LIBASS 0
#define CONFIG_LIBBLURAY 0
#define CONFIG_LIBBS2B 0
#define CONFIG_LIBCACA 0
-#define CONFIG_LIBCDIO 0
#define CONFIG_LIBCELT 0
#define CONFIG_LIBDC1394 0
-#define CONFIG_LIBEBUR128 0
-#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_LIBDRM 0
#define CONFIG_LIBFLITE 0
#define CONFIG_LIBFONTCONFIG 0
#define CONFIG_LIBFREETYPE 0
@@ -447,18 +469,15 @@
#define CONFIG_LIBKVAZAAR 0
#define CONFIG_LIBMODPLUG 0
#define CONFIG_LIBMP3LAME 0
-#define CONFIG_LIBNUT 0
-#define CONFIG_LIBOPENCORE_AMRNB 0
-#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBMYSOFA 0
#define CONFIG_LIBOPENCV 0
#define CONFIG_LIBOPENH264 0
#define CONFIG_LIBOPENJPEG 0
#define CONFIG_LIBOPENMPT 0
#define CONFIG_LIBOPUS 0
#define CONFIG_LIBPULSE 0
+#define CONFIG_LIBRSVG 0
#define CONFIG_LIBRTMP 0
-#define CONFIG_LIBRUBBERBAND 0
-#define CONFIG_LIBSCHROEDINGER 0
#define CONFIG_LIBSHINE 0
#define CONFIG_LIBSMBCLIENT 0
#define CONFIG_LIBSNAPPY 0
@@ -469,53 +488,37 @@
#define CONFIG_LIBTHEORA 0
#define CONFIG_LIBTWOLAME 0
#define CONFIG_LIBV4L2 0
-#define CONFIG_LIBVIDSTAB 0
-#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_LIBVMAF 0
#define CONFIG_LIBVORBIS 0
#define CONFIG_LIBVPX 0
#define CONFIG_LIBWAVPACK 0
#define CONFIG_LIBWEBP 0
-#define CONFIG_LIBX264 0
-#define CONFIG_LIBX265 0
-#define CONFIG_LIBXAVS 0
-#define CONFIG_LIBXCB 0
-#define CONFIG_LIBXCB_SHM 0
-#define CONFIG_LIBXCB_SHAPE 0
-#define CONFIG_LIBXCB_XFIXES 0
-#define CONFIG_LIBXVID 0
+#define CONFIG_LIBXML2 0
#define CONFIG_LIBZIMG 0
#define CONFIG_LIBZMQ 0
#define CONFIG_LIBZVBI 0
-#define CONFIG_LZMA 0
#define CONFIG_MEDIACODEC 0
-#define CONFIG_NETCDF 0
#define CONFIG_OPENAL 0
#define CONFIG_OPENCL 0
#define CONFIG_OPENGL 0
-#define CONFIG_OPENSSL 0
-#define CONFIG_SCHANNEL 1
-#define CONFIG_SDL 0
-#define CONFIG_SDL2 0
-#define CONFIG_SECURETRANSPORT 0
-#define CONFIG_VIDEOTOOLBOX 0
-#define CONFIG_X11GRAB 0
-#define CONFIG_XLIB 0
-#define CONFIG_ZLIB 0
#define CONFIG_AUDIOTOOLBOX 0
-#define CONFIG_CUDA 0
-#define CONFIG_CUVID 0
+#define CONFIG_CRYSTALHD 0
+#define CONFIG_CUDA 1
+#define CONFIG_CUVID 1
#define CONFIG_D3D11VA 0
#define CONFIG_DXVA2 0
-#define CONFIG_LIBMFX 0
-#define CONFIG_LIBNPP 0
-#define CONFIG_MMAL 0
-#define CONFIG_NVENC 0
-#define CONFIG_OMX 0
+#define CONFIG_NVENC 1
#define CONFIG_VAAPI 0
#define CONFIG_VDA 0
#define CONFIG_VDPAU 0
-#define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_VIDEOTOOLBOX 0
+#define CONFIG_V4L2_M2M 0
#define CONFIG_XVMC 0
+#define CONFIG_CUDA_SDK 0
+#define CONFIG_LIBNPP 0
+#define CONFIG_LIBMFX 0
+#define CONFIG_MMAL 0
+#define CONFIG_OMX 0
#define CONFIG_FTRAPV 0
#define CONFIG_GRAY 0
#define CONFIG_HARDCODED_TABLES 0
@@ -554,16 +557,27 @@
#define CONFIG_PIXELUTILS 0
#define CONFIG_NETWORK 0
#define CONFIG_RDFT 0
+#define CONFIG_AUTODETECT 0
#define CONFIG_FONTCONFIG 0
-#define CONFIG_MEMALIGN_HACK 0
+#define CONFIG_LINUX_PERF 0
#define CONFIG_MEMORY_POISONING 0
#define CONFIG_NEON_CLOBBER_TEST 0
+#define CONFIG_OSSFUZZ 0
#define CONFIG_PIC 0
-#define CONFIG_POD2MAN 1
-#define CONFIG_RAISE_MAJOR 0
#define CONFIG_THUMB 0
#define CONFIG_VALGRIND_BACKTRACE 0
#define CONFIG_XMM_CLOBBER_TEST 0
+#define CONFIG_BSFS 1
+#define CONFIG_DECODERS 1
+#define CONFIG_ENCODERS 0
+#define CONFIG_HWACCELS 0
+#define CONFIG_PARSERS 1
+#define CONFIG_INDEVS 0
+#define CONFIG_OUTDEVS 0
+#define CONFIG_FILTERS 0
+#define CONFIG_DEMUXERS 0
+#define CONFIG_MUXERS 0
+#define CONFIG_PROTOCOLS 0
#define CONFIG_AANDCTTABLES 0
#define CONFIG_AC3DSP 0
#define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -581,20 +595,22 @@
#define CONFIG_FMTCONVERT 0
#define CONFIG_FRAME_THREAD_ENCODER 0
#define CONFIG_G722DSP 0
-#define CONFIG_GOLOMB 1
+#define CONFIG_GOLOMB 0
#define CONFIG_GPLV3 0
#define CONFIG_H263DSP 0
#define CONFIG_H264CHROMA 0
#define CONFIG_H264DSP 0
+#define CONFIG_H264PARSE 0
#define CONFIG_H264PRED 1
#define CONFIG_H264QPEL 0
+#define CONFIG_HEVCPARSE 0
#define CONFIG_HPELDSP 0
#define CONFIG_HUFFMAN 0
#define CONFIG_HUFFYUVDSP 0
#define CONFIG_HUFFYUVENCDSP 0
#define CONFIG_IDCTDSP 0
#define CONFIG_IIRFILTER 0
-#define CONFIG_IMDCT15 0
+#define CONFIG_MDCT15 0
#define CONFIG_INTRAX8 0
#define CONFIG_ISO_MEDIA 0
#define CONFIG_IVIDSP 0
@@ -603,12 +619,14 @@
#define CONFIG_LIBX262 0
#define CONFIG_LLAUDDSP 0
#define CONFIG_LLVIDDSP 0
+#define CONFIG_LLVIDENCDSP 0
#define CONFIG_LPC 0
#define CONFIG_LZF 0
#define CONFIG_ME_CMP 0
#define CONFIG_MPEG_ER 0
#define CONFIG_MPEGAUDIO 0
#define CONFIG_MPEGAUDIODSP 0
+#define CONFIG_MPEGAUDIOHEADER 0
#define CONFIG_MPEGVIDEO 0
#define CONFIG_MPEGVIDEOENC 0
#define CONFIG_MSS34DSP 0
@@ -630,1595 +648,20 @@
#define CONFIG_TEXTUREDSP 0
#define CONFIG_TEXTUREDSPENC 0
#define CONFIG_TPELDSP 0
+#define CONFIG_VAAPI_1 0
#define CONFIG_VAAPI_ENCODE 0
#define CONFIG_VC1DSP 0
#define CONFIG_VIDEODSP 1
#define CONFIG_VP3DSP 0
#define CONFIG_VP56DSP 0
#define CONFIG_VP8DSP 1
-#define CONFIG_VT_BT2020 0
#define CONFIG_WMA_FREQS 0
#define CONFIG_WMV2DSP 0
-#define CONFIG_AAC_ADTSTOASC_BSF 0
-#define CONFIG_CHOMP_BSF 0
-#define CONFIG_DUMP_EXTRADATA_BSF 0
-#define CONFIG_DCA_CORE_BSF 0
-#define CONFIG_H264_MP4TOANNEXB_BSF 0
-#define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-#define CONFIG_IMX_DUMP_HEADER_BSF 0
-#define CONFIG_MJPEG2JPEG_BSF 0
-#define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-#define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-#define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-#define CONFIG_MOV2TEXTSUB_BSF 0
-#define CONFIG_NOISE_BSF 0
-#define CONFIG_REMOVE_EXTRADATA_BSF 0
-#define CONFIG_TEXT2MOVSUB_BSF 0
-#define CONFIG_VP9_SUPERFRAME_BSF 0
-#define CONFIG_AASC_DECODER 0
-#define CONFIG_AIC_DECODER 0
-#define CONFIG_ALIAS_PIX_DECODER 0
-#define CONFIG_AMV_DECODER 0
-#define CONFIG_ANM_DECODER 0
-#define CONFIG_ANSI_DECODER 0
-#define CONFIG_APNG_DECODER 0
-#define CONFIG_ASV1_DECODER 0
-#define CONFIG_ASV2_DECODER 0
-#define CONFIG_AURA_DECODER 0
-#define CONFIG_AURA2_DECODER 0
-#define CONFIG_AVRP_DECODER 0
-#define CONFIG_AVRN_DECODER 0
-#define CONFIG_AVS_DECODER 0
-#define CONFIG_AVUI_DECODER 0
-#define CONFIG_AYUV_DECODER 0
-#define CONFIG_BETHSOFTVID_DECODER 0
-#define CONFIG_BFI_DECODER 0
-#define CONFIG_BINK_DECODER 0
-#define CONFIG_BMP_DECODER 0
-#define CONFIG_BMV_VIDEO_DECODER 0
-#define CONFIG_BRENDER_PIX_DECODER 0
-#define CONFIG_C93_DECODER 0
-#define CONFIG_CAVS_DECODER 0
-#define CONFIG_CDGRAPHICS_DECODER 0
-#define CONFIG_CDXL_DECODER 0
-#define CONFIG_CFHD_DECODER 0
-#define CONFIG_CINEPAK_DECODER 0
-#define CONFIG_CLJR_DECODER 0
-#define CONFIG_CLLC_DECODER 0
-#define CONFIG_COMFORTNOISE_DECODER 0
-#define CONFIG_CPIA_DECODER 0
-#define CONFIG_CSCD_DECODER 0
-#define CONFIG_CYUV_DECODER 0
-#define CONFIG_DDS_DECODER 0
-#define CONFIG_DFA_DECODER 0
-#define CONFIG_DIRAC_DECODER 0
-#define CONFIG_DNXHD_DECODER 0
-#define CONFIG_DPX_DECODER 0
-#define CONFIG_DSICINVIDEO_DECODER 0
-#define CONFIG_DVAUDIO_DECODER 0
-#define CONFIG_DVVIDEO_DECODER 0
-#define CONFIG_DXA_DECODER 0
-#define CONFIG_DXTORY_DECODER 0
-#define CONFIG_DXV_DECODER 0
-#define CONFIG_EACMV_DECODER 0
-#define CONFIG_EAMAD_DECODER 0
-#define CONFIG_EATGQ_DECODER 0
-#define CONFIG_EATGV_DECODER 0
-#define CONFIG_EATQI_DECODER 0
-#define CONFIG_EIGHTBPS_DECODER 0
-#define CONFIG_EIGHTSVX_EXP_DECODER 0
-#define CONFIG_EIGHTSVX_FIB_DECODER 0
-#define CONFIG_ESCAPE124_DECODER 0
-#define CONFIG_ESCAPE130_DECODER 0
-#define CONFIG_EXR_DECODER 0
-#define CONFIG_FFV1_DECODER 0
-#define CONFIG_FFVHUFF_DECODER 0
-#define CONFIG_FIC_DECODER 0
-#define CONFIG_FLASHSV_DECODER 0
-#define CONFIG_FLASHSV2_DECODER 0
-#define CONFIG_FLIC_DECODER 0
-#define CONFIG_FLV_DECODER 0
-#define CONFIG_FOURXM_DECODER 0
-#define CONFIG_FRAPS_DECODER 0
-#define CONFIG_FRWU_DECODER 0
-#define CONFIG_G2M_DECODER 0
-#define CONFIG_GIF_DECODER 0
-#define CONFIG_H261_DECODER 0
-#define CONFIG_H263_DECODER 0
-#define CONFIG_H263I_DECODER 0
-#define CONFIG_H263P_DECODER 0
-#define CONFIG_H264_DECODER 0
-#define CONFIG_H264_CRYSTALHD_DECODER 0
-#define CONFIG_H264_MEDIACODEC_DECODER 0
-#define CONFIG_H264_MMAL_DECODER 0
-#define CONFIG_H264_QSV_DECODER 0
-#define CONFIG_H264_VDA_DECODER 0
-#define CONFIG_H264_VDPAU_DECODER 0
-#define CONFIG_HAP_DECODER 0
-#define CONFIG_HEVC_DECODER 0
-#define CONFIG_HEVC_QSV_DECODER 0
-#define CONFIG_HNM4_VIDEO_DECODER 0
-#define CONFIG_HQ_HQA_DECODER 0
-#define CONFIG_HQX_DECODER 0
-#define CONFIG_HUFFYUV_DECODER 0
-#define CONFIG_IDCIN_DECODER 0
-#define CONFIG_IFF_ILBM_DECODER 0
-#define CONFIG_INDEO2_DECODER 0
-#define CONFIG_INDEO3_DECODER 0
-#define CONFIG_INDEO4_DECODER 0
-#define CONFIG_INDEO5_DECODER 0
-#define CONFIG_INTERPLAY_VIDEO_DECODER 0
-#define CONFIG_JPEG2000_DECODER 0
-#define CONFIG_JPEGLS_DECODER 0
-#define CONFIG_JV_DECODER 0
-#define CONFIG_KGV1_DECODER 0
-#define CONFIG_KMVC_DECODER 0
-#define CONFIG_LAGARITH_DECODER 0
-#define CONFIG_LOCO_DECODER 0
-#define CONFIG_M101_DECODER 0
-#define CONFIG_MAGICYUV_DECODER 0
-#define CONFIG_MDEC_DECODER 0
-#define CONFIG_MIMIC_DECODER 0
-#define CONFIG_MJPEG_DECODER 0
-#define CONFIG_MJPEGB_DECODER 0
-#define CONFIG_MMVIDEO_DECODER 0
-#define CONFIG_MOTIONPIXELS_DECODER 0
-#define CONFIG_MPEG_XVMC_DECODER 0
-#define CONFIG_MPEG1VIDEO_DECODER 0
-#define CONFIG_MPEG2VIDEO_DECODER 0
-#define CONFIG_MPEG4_DECODER 0
-#define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG4_MMAL_DECODER 0
-#define CONFIG_MPEG4_VDPAU_DECODER 0
-#define CONFIG_MPEGVIDEO_DECODER 0
-#define CONFIG_MPEG_VDPAU_DECODER 0
-#define CONFIG_MPEG1_VDPAU_DECODER 0
-#define CONFIG_MPEG2_MMAL_DECODER 0
-#define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG2_QSV_DECODER 0
-#define CONFIG_MSA1_DECODER 0
-#define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MSMPEG4V1_DECODER 0
-#define CONFIG_MSMPEG4V2_DECODER 0
-#define CONFIG_MSMPEG4V3_DECODER 0
-#define CONFIG_MSRLE_DECODER 0
-#define CONFIG_MSS1_DECODER 0
-#define CONFIG_MSS2_DECODER 0
-#define CONFIG_MSVIDEO1_DECODER 0
-#define CONFIG_MSZH_DECODER 0
-#define CONFIG_MTS2_DECODER 0
-#define CONFIG_MVC1_DECODER 0
-#define CONFIG_MVC2_DECODER 0
-#define CONFIG_MXPEG_DECODER 0
-#define CONFIG_NUV_DECODER 0
-#define CONFIG_PAF_VIDEO_DECODER 0
-#define CONFIG_PAM_DECODER 0
-#define CONFIG_PBM_DECODER 0
-#define CONFIG_PCX_DECODER 0
-#define CONFIG_PGM_DECODER 0
-#define CONFIG_PGMYUV_DECODER 0
-#define CONFIG_PICTOR_DECODER 0
-#define CONFIG_PNG_DECODER 0
-#define CONFIG_PPM_DECODER 0
-#define CONFIG_PRORES_DECODER 0
-#define CONFIG_PRORES_LGPL_DECODER 0
-#define CONFIG_PTX_DECODER 0
-#define CONFIG_QDRAW_DECODER 0
-#define CONFIG_QPEG_DECODER 0
-#define CONFIG_QTRLE_DECODER 0
-#define CONFIG_R10K_DECODER 0
-#define CONFIG_R210_DECODER 0
-#define CONFIG_RAWVIDEO_DECODER 0
-#define CONFIG_RL2_DECODER 0
-#define CONFIG_ROQ_DECODER 0
-#define CONFIG_RPZA_DECODER 0
-#define CONFIG_RSCC_DECODER 0
-#define CONFIG_RV10_DECODER 0
-#define CONFIG_RV20_DECODER 0
-#define CONFIG_RV30_DECODER 0
-#define CONFIG_RV40_DECODER 0
-#define CONFIG_S302M_DECODER 0
-#define CONFIG_SANM_DECODER 0
-#define CONFIG_SCREENPRESSO_DECODER 0
-#define CONFIG_SDX2_DPCM_DECODER 0
-#define CONFIG_SGI_DECODER 0
-#define CONFIG_SGIRLE_DECODER 0
-#define CONFIG_SHEERVIDEO_DECODER 0
-#define CONFIG_SMACKER_DECODER 0
-#define CONFIG_SMC_DECODER 0
-#define CONFIG_SMVJPEG_DECODER 0
-#define CONFIG_SNOW_DECODER 0
-#define CONFIG_SP5X_DECODER 0
-#define CONFIG_SUNRAST_DECODER 0
-#define CONFIG_SVQ1_DECODER 0
-#define CONFIG_SVQ3_DECODER 0
-#define CONFIG_TARGA_DECODER 0
-#define CONFIG_TARGA_Y216_DECODER 0
-#define CONFIG_TDSC_DECODER 0
-#define CONFIG_THEORA_DECODER 0
-#define CONFIG_THP_DECODER 0
-#define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-#define CONFIG_TIFF_DECODER 0
-#define CONFIG_TMV_DECODER 0
-#define CONFIG_TRUEMOTION1_DECODER 0
-#define CONFIG_TRUEMOTION2_DECODER 0
-#define CONFIG_TRUEMOTION2RT_DECODER 0
-#define CONFIG_TSCC_DECODER 0
-#define CONFIG_TSCC2_DECODER 0
-#define CONFIG_TXD_DECODER 0
-#define CONFIG_ULTI_DECODER 0
-#define CONFIG_UTVIDEO_DECODER 0
-#define CONFIG_V210_DECODER 0
-#define CONFIG_V210X_DECODER 0
-#define CONFIG_V308_DECODER 0
-#define CONFIG_V408_DECODER 0
-#define CONFIG_V410_DECODER 0
-#define CONFIG_VB_DECODER 0
-#define CONFIG_VBLE_DECODER 0
-#define CONFIG_VC1_DECODER 0
-#define CONFIG_VC1_CRYSTALHD_DECODER 0
-#define CONFIG_VC1_VDPAU_DECODER 0
-#define CONFIG_VC1IMAGE_DECODER 0
-#define CONFIG_VC1_MMAL_DECODER 0
-#define CONFIG_VC1_QSV_DECODER 0
-#define CONFIG_VCR1_DECODER 0
-#define CONFIG_VMDVIDEO_DECODER 0
-#define CONFIG_VMNC_DECODER 0
-#define CONFIG_VP3_DECODER 0
-#define CONFIG_VP5_DECODER 0
-#define CONFIG_VP6_DECODER 0
-#define CONFIG_VP6A_DECODER 0
-#define CONFIG_VP6F_DECODER 0
-#define CONFIG_VP7_DECODER 0
+#define CONFIG_NULL_BSF 1
#define CONFIG_VP8_DECODER 1
#define CONFIG_VP9_DECODER 1
-#define CONFIG_VQA_DECODER 0
-#define CONFIG_WEBP_DECODER 0
-#define CONFIG_WMV1_DECODER 0
-#define CONFIG_WMV2_DECODER 0
-#define CONFIG_WMV3_DECODER 0
-#define CONFIG_WMV3_CRYSTALHD_DECODER 0
-#define CONFIG_WMV3_VDPAU_DECODER 0
-#define CONFIG_WMV3IMAGE_DECODER 0
-#define CONFIG_WNV1_DECODER 0
-#define CONFIG_XAN_WC3_DECODER 0
-#define CONFIG_XAN_WC4_DECODER 0
-#define CONFIG_XBM_DECODER 0
-#define CONFIG_XFACE_DECODER 0
-#define CONFIG_XL_DECODER 0
-#define CONFIG_XWD_DECODER 0
-#define CONFIG_Y41P_DECODER 0
-#define CONFIG_YLC_DECODER 0
-#define CONFIG_YOP_DECODER 0
-#define CONFIG_YUV4_DECODER 0
-#define CONFIG_ZERO12V_DECODER 0
-#define CONFIG_ZEROCODEC_DECODER 0
-#define CONFIG_ZLIB_DECODER 0
-#define CONFIG_ZMBV_DECODER 0
-#define CONFIG_AAC_DECODER 0
-#define CONFIG_AAC_FIXED_DECODER 0
-#define CONFIG_AAC_LATM_DECODER 0
-#define CONFIG_AC3_DECODER 0
-#define CONFIG_AC3_FIXED_DECODER 0
-#define CONFIG_ALAC_DECODER 0
-#define CONFIG_ALS_DECODER 0
-#define CONFIG_AMRNB_DECODER 0
-#define CONFIG_AMRWB_DECODER 0
-#define CONFIG_APE_DECODER 0
-#define CONFIG_ATRAC1_DECODER 0
-#define CONFIG_ATRAC3_DECODER 0
-#define CONFIG_ATRAC3P_DECODER 0
-#define CONFIG_BINKAUDIO_DCT_DECODER 0
-#define CONFIG_BINKAUDIO_RDFT_DECODER 0
-#define CONFIG_BMV_AUDIO_DECODER 0
-#define CONFIG_COOK_DECODER 0
-#define CONFIG_DCA_DECODER 0
-#define CONFIG_DSD_LSBF_DECODER 0
-#define CONFIG_DSD_MSBF_DECODER 0
-#define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-#define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-#define CONFIG_DSICINAUDIO_DECODER 0
-#define CONFIG_DSS_SP_DECODER 0
-#define CONFIG_DST_DECODER 0
-#define CONFIG_EAC3_DECODER 0
-#define CONFIG_EVRC_DECODER 0
-#define CONFIG_FFWAVESYNTH_DECODER 0
#define CONFIG_FLAC_DECODER 1
-#define CONFIG_G723_1_DECODER 0
-#define CONFIG_G729_DECODER 0
-#define CONFIG_GSM_DECODER 0
-#define CONFIG_GSM_MS_DECODER 0
-#define CONFIG_IAC_DECODER 0
-#define CONFIG_IMC_DECODER 0
-#define CONFIG_INTERPLAY_ACM_DECODER 0
-#define CONFIG_MACE3_DECODER 0
-#define CONFIG_MACE6_DECODER 0
-#define CONFIG_METASOUND_DECODER 0
-#define CONFIG_MLP_DECODER 0
-#define CONFIG_MP1_DECODER 0
-#define CONFIG_MP1FLOAT_DECODER 0
-#define CONFIG_MP2_DECODER 0
-#define CONFIG_MP2FLOAT_DECODER 0
-#define CONFIG_MP3_DECODER 0
-#define CONFIG_MP3FLOAT_DECODER 0
-#define CONFIG_MP3ADU_DECODER 0
-#define CONFIG_MP3ADUFLOAT_DECODER 0
-#define CONFIG_MP3ON4_DECODER 0
-#define CONFIG_MP3ON4FLOAT_DECODER 0
-#define CONFIG_MPC7_DECODER 0
-#define CONFIG_MPC8_DECODER 0
-#define CONFIG_NELLYMOSER_DECODER 0
-#define CONFIG_ON2AVC_DECODER 0
-#define CONFIG_OPUS_DECODER 0
-#define CONFIG_PAF_AUDIO_DECODER 0
-#define CONFIG_QCELP_DECODER 0
-#define CONFIG_QDM2_DECODER 0
-#define CONFIG_RA_144_DECODER 0
-#define CONFIG_RA_288_DECODER 0
-#define CONFIG_RALF_DECODER 0
-#define CONFIG_SHORTEN_DECODER 0
-#define CONFIG_SIPR_DECODER 0
-#define CONFIG_SMACKAUD_DECODER 0
-#define CONFIG_SONIC_DECODER 0
-#define CONFIG_TAK_DECODER 0
-#define CONFIG_TRUEHD_DECODER 0
-#define CONFIG_TRUESPEECH_DECODER 0
-#define CONFIG_TTA_DECODER 0
-#define CONFIG_TWINVQ_DECODER 0
-#define CONFIG_VMDAUDIO_DECODER 0
-#define CONFIG_VORBIS_DECODER 0
-#define CONFIG_WAVPACK_DECODER 0
-#define CONFIG_WMALOSSLESS_DECODER 0
-#define CONFIG_WMAPRO_DECODER 0
-#define CONFIG_WMAV1_DECODER 0
-#define CONFIG_WMAV2_DECODER 0
-#define CONFIG_WMAVOICE_DECODER 0
-#define CONFIG_WS_SND1_DECODER 0
-#define CONFIG_XMA1_DECODER 0
-#define CONFIG_XMA2_DECODER 0
-#define CONFIG_PCM_ALAW_DECODER 0
-#define CONFIG_PCM_BLURAY_DECODER 0
-#define CONFIG_PCM_DVD_DECODER 0
-#define CONFIG_PCM_F32BE_DECODER 0
-#define CONFIG_PCM_F32LE_DECODER 0
-#define CONFIG_PCM_F64BE_DECODER 0
-#define CONFIG_PCM_F64LE_DECODER 0
-#define CONFIG_PCM_LXF_DECODER 0
-#define CONFIG_PCM_MULAW_DECODER 0
-#define CONFIG_PCM_S8_DECODER 0
-#define CONFIG_PCM_S8_PLANAR_DECODER 0
-#define CONFIG_PCM_S16BE_DECODER 0
-#define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-#define CONFIG_PCM_S16LE_DECODER 0
-#define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S24BE_DECODER 0
-#define CONFIG_PCM_S24DAUD_DECODER 0
-#define CONFIG_PCM_S24LE_DECODER 0
-#define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S32BE_DECODER 0
-#define CONFIG_PCM_S32LE_DECODER 0
-#define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S64BE_DECODER 0
-#define CONFIG_PCM_S64LE_DECODER 0
-#define CONFIG_PCM_U8_DECODER 0
-#define CONFIG_PCM_U16BE_DECODER 0
-#define CONFIG_PCM_U16LE_DECODER 0
-#define CONFIG_PCM_U24BE_DECODER 0
-#define CONFIG_PCM_U24LE_DECODER 0
-#define CONFIG_PCM_U32BE_DECODER 0
-#define CONFIG_PCM_U32LE_DECODER 0
-#define CONFIG_PCM_ZORK_DECODER 0
-#define CONFIG_INTERPLAY_DPCM_DECODER 0
-#define CONFIG_ROQ_DPCM_DECODER 0
-#define CONFIG_SOL_DPCM_DECODER 0
-#define CONFIG_XAN_DPCM_DECODER 0
-#define CONFIG_ADPCM_4XM_DECODER 0
-#define CONFIG_ADPCM_ADX_DECODER 0
-#define CONFIG_ADPCM_AFC_DECODER 0
-#define CONFIG_ADPCM_AICA_DECODER 0
-#define CONFIG_ADPCM_CT_DECODER 0
-#define CONFIG_ADPCM_DTK_DECODER 0
-#define CONFIG_ADPCM_EA_DECODER 0
-#define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-#define CONFIG_ADPCM_EA_R1_DECODER 0
-#define CONFIG_ADPCM_EA_R2_DECODER 0
-#define CONFIG_ADPCM_EA_R3_DECODER 0
-#define CONFIG_ADPCM_EA_XAS_DECODER 0
-#define CONFIG_ADPCM_G722_DECODER 0
-#define CONFIG_ADPCM_G726_DECODER 0
-#define CONFIG_ADPCM_G726LE_DECODER 0
-#define CONFIG_ADPCM_IMA_AMV_DECODER 0
-#define CONFIG_ADPCM_IMA_APC_DECODER 0
-#define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-#define CONFIG_ADPCM_IMA_DK3_DECODER 0
-#define CONFIG_ADPCM_IMA_DK4_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-#define CONFIG_ADPCM_IMA_ISS_DECODER 0
-#define CONFIG_ADPCM_IMA_OKI_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_DECODER 0
-#define CONFIG_ADPCM_IMA_RAD_DECODER 0
-#define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-#define CONFIG_ADPCM_IMA_WAV_DECODER 0
-#define CONFIG_ADPCM_IMA_WS_DECODER 0
-#define CONFIG_ADPCM_MS_DECODER 0
-#define CONFIG_ADPCM_MTAF_DECODER 0
-#define CONFIG_ADPCM_PSX_DECODER 0
-#define CONFIG_ADPCM_SBPRO_2_DECODER 0
-#define CONFIG_ADPCM_SBPRO_3_DECODER 0
-#define CONFIG_ADPCM_SBPRO_4_DECODER 0
-#define CONFIG_ADPCM_SWF_DECODER 0
-#define CONFIG_ADPCM_THP_DECODER 0
-#define CONFIG_ADPCM_THP_LE_DECODER 0
-#define CONFIG_ADPCM_VIMA_DECODER 0
-#define CONFIG_ADPCM_XA_DECODER 0
-#define CONFIG_ADPCM_YAMAHA_DECODER 0
-#define CONFIG_SSA_DECODER 0
-#define CONFIG_ASS_DECODER 0
-#define CONFIG_CCAPTION_DECODER 0
-#define CONFIG_DVBSUB_DECODER 0
-#define CONFIG_DVDSUB_DECODER 0
-#define CONFIG_JACOSUB_DECODER 0
-#define CONFIG_MICRODVD_DECODER 0
-#define CONFIG_MOVTEXT_DECODER 0
-#define CONFIG_MPL2_DECODER 0
-#define CONFIG_PGSSUB_DECODER 0
-#define CONFIG_PJS_DECODER 0
-#define CONFIG_REALTEXT_DECODER 0
-#define CONFIG_SAMI_DECODER 0
-#define CONFIG_SRT_DECODER 0
-#define CONFIG_STL_DECODER 0
-#define CONFIG_SUBRIP_DECODER 0
-#define CONFIG_SUBVIEWER_DECODER 0
-#define CONFIG_SUBVIEWER1_DECODER 0
-#define CONFIG_TEXT_DECODER 0
-#define CONFIG_VPLAYER_DECODER 0
-#define CONFIG_WEBVTT_DECODER 0
-#define CONFIG_XSUB_DECODER 0
-#define CONFIG_AAC_AT_DECODER 0
-#define CONFIG_AC3_AT_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-#define CONFIG_ALAC_AT_DECODER 0
-#define CONFIG_AMR_NB_AT_DECODER 0
-#define CONFIG_EAC3_AT_DECODER 0
-#define CONFIG_GSM_MS_AT_DECODER 0
-#define CONFIG_ILBC_AT_DECODER 0
-#define CONFIG_MP1_AT_DECODER 0
-#define CONFIG_MP2_AT_DECODER 0
-#define CONFIG_MP3_AT_DECODER 0
-#define CONFIG_PCM_ALAW_AT_DECODER 0
-#define CONFIG_PCM_MULAW_AT_DECODER 0
-#define CONFIG_QDMC_AT_DECODER 0
-#define CONFIG_QDM2_AT_DECODER 0
-#define CONFIG_LIBCELT_DECODER 0
-#define CONFIG_LIBFDK_AAC_DECODER 0
-#define CONFIG_LIBGSM_DECODER 0
-#define CONFIG_LIBGSM_MS_DECODER 0
-#define CONFIG_LIBILBC_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-#define CONFIG_LIBOPENJPEG_DECODER 0
-#define CONFIG_LIBOPUS_DECODER 0
-#define CONFIG_LIBSCHROEDINGER_DECODER 0
-#define CONFIG_LIBSPEEX_DECODER 0
-#define CONFIG_LIBVORBIS_DECODER 0
-#define CONFIG_LIBVPX_VP8_DECODER 0
-#define CONFIG_LIBVPX_VP9_DECODER 0
-#define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-#define CONFIG_BINTEXT_DECODER 0
-#define CONFIG_XBIN_DECODER 0
-#define CONFIG_IDF_DECODER 0
-#define CONFIG_LIBOPENH264_DECODER 0
-#define CONFIG_H263_CUVID_DECODER 0
-#define CONFIG_H264_CUVID_DECODER 0
-#define CONFIG_HEVC_CUVID_DECODER 0
-#define CONFIG_HEVC_MEDIACODEC_DECODER 0
-#define CONFIG_MJPEG_CUVID_DECODER 0
-#define CONFIG_MPEG1_CUVID_DECODER 0
-#define CONFIG_MPEG2_CUVID_DECODER 0
-#define CONFIG_MPEG4_CUVID_DECODER 0
-#define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-#define CONFIG_VC1_CUVID_DECODER 0
-#define CONFIG_VP8_CUVID_DECODER 0
-#define CONFIG_VP8_MEDIACODEC_DECODER 0
-#define CONFIG_VP9_CUVID_DECODER 0
-#define CONFIG_VP9_MEDIACODEC_DECODER 0
-#define CONFIG_AA_DEMUXER 0
-#define CONFIG_AAC_DEMUXER 0
-#define CONFIG_AC3_DEMUXER 0
-#define CONFIG_ACM_DEMUXER 0
-#define CONFIG_ACT_DEMUXER 0
-#define CONFIG_ADF_DEMUXER 0
-#define CONFIG_ADP_DEMUXER 0
-#define CONFIG_ADS_DEMUXER 0
-#define CONFIG_ADX_DEMUXER 0
-#define CONFIG_AEA_DEMUXER 0
-#define CONFIG_AFC_DEMUXER 0
-#define CONFIG_AIFF_DEMUXER 0
-#define CONFIG_AIX_DEMUXER 0
-#define CONFIG_AMR_DEMUXER 0
-#define CONFIG_ANM_DEMUXER 0
-#define CONFIG_APC_DEMUXER 0
-#define CONFIG_APE_DEMUXER 0
-#define CONFIG_APNG_DEMUXER 0
-#define CONFIG_AQTITLE_DEMUXER 0
-#define CONFIG_ASF_DEMUXER 0
-#define CONFIG_ASF_O_DEMUXER 0
-#define CONFIG_ASS_DEMUXER 0
-#define CONFIG_AST_DEMUXER 0
-#define CONFIG_AU_DEMUXER 0
-#define CONFIG_AVI_DEMUXER 0
-#define CONFIG_AVISYNTH_DEMUXER 0
-#define CONFIG_AVR_DEMUXER 0
-#define CONFIG_AVS_DEMUXER 0
-#define CONFIG_BETHSOFTVID_DEMUXER 0
-#define CONFIG_BFI_DEMUXER 0
-#define CONFIG_BINTEXT_DEMUXER 0
-#define CONFIG_BINK_DEMUXER 0
-#define CONFIG_BIT_DEMUXER 0
-#define CONFIG_BMV_DEMUXER 0
-#define CONFIG_BFSTM_DEMUXER 0
-#define CONFIG_BRSTM_DEMUXER 0
-#define CONFIG_BOA_DEMUXER 0
-#define CONFIG_C93_DEMUXER 0
-#define CONFIG_CAF_DEMUXER 0
-#define CONFIG_CAVSVIDEO_DEMUXER 0
-#define CONFIG_CDG_DEMUXER 0
-#define CONFIG_CDXL_DEMUXER 0
-#define CONFIG_CINE_DEMUXER 0
-#define CONFIG_CONCAT_DEMUXER 0
-#define CONFIG_DATA_DEMUXER 0
-#define CONFIG_DAUD_DEMUXER 0
-#define CONFIG_DCSTR_DEMUXER 0
-#define CONFIG_DFA_DEMUXER 0
-#define CONFIG_DIRAC_DEMUXER 0
-#define CONFIG_DNXHD_DEMUXER 0
-#define CONFIG_DSF_DEMUXER 0
-#define CONFIG_DSICIN_DEMUXER 0
-#define CONFIG_DSS_DEMUXER 0
-#define CONFIG_DTS_DEMUXER 0
-#define CONFIG_DTSHD_DEMUXER 0
-#define CONFIG_DV_DEMUXER 0
-#define CONFIG_DVBSUB_DEMUXER 0
-#define CONFIG_DVBTXT_DEMUXER 0
-#define CONFIG_DXA_DEMUXER 0
-#define CONFIG_EA_DEMUXER 0
-#define CONFIG_EA_CDATA_DEMUXER 0
-#define CONFIG_EAC3_DEMUXER 0
-#define CONFIG_EPAF_DEMUXER 0
-#define CONFIG_FFM_DEMUXER 0
-#define CONFIG_FFMETADATA_DEMUXER 0
-#define CONFIG_FILMSTRIP_DEMUXER 0
-#define CONFIG_FLAC_DEMUXER 0
-#define CONFIG_FLIC_DEMUXER 0
-#define CONFIG_FLV_DEMUXER 0
-#define CONFIG_LIVE_FLV_DEMUXER 0
-#define CONFIG_FOURXM_DEMUXER 0
-#define CONFIG_FRM_DEMUXER 0
-#define CONFIG_FSB_DEMUXER 0
-#define CONFIG_G722_DEMUXER 0
-#define CONFIG_G723_1_DEMUXER 0
-#define CONFIG_G729_DEMUXER 0
-#define CONFIG_GENH_DEMUXER 0
-#define CONFIG_GIF_DEMUXER 0
-#define CONFIG_GSM_DEMUXER 0
-#define CONFIG_GXF_DEMUXER 0
-#define CONFIG_H261_DEMUXER 0
-#define CONFIG_H263_DEMUXER 0
-#define CONFIG_H264_DEMUXER 0
-#define CONFIG_HEVC_DEMUXER 0
-#define CONFIG_HLS_DEMUXER 0
-#define CONFIG_HNM_DEMUXER 0
-#define CONFIG_ICO_DEMUXER 0
-#define CONFIG_IDCIN_DEMUXER 0
-#define CONFIG_IDF_DEMUXER 0
-#define CONFIG_IFF_DEMUXER 0
-#define CONFIG_ILBC_DEMUXER 0
-#define CONFIG_IMAGE2_DEMUXER 0
-#define CONFIG_IMAGE2PIPE_DEMUXER 0
-#define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-#define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-#define CONFIG_INGENIENT_DEMUXER 0
-#define CONFIG_IPMOVIE_DEMUXER 0
-#define CONFIG_IRCAM_DEMUXER 0
-#define CONFIG_ISS_DEMUXER 0
-#define CONFIG_IV8_DEMUXER 0
-#define CONFIG_IVF_DEMUXER 0
-#define CONFIG_IVR_DEMUXER 0
-#define CONFIG_JACOSUB_DEMUXER 0
-#define CONFIG_JV_DEMUXER 0
-#define CONFIG_LMLM4_DEMUXER 0
-#define CONFIG_LOAS_DEMUXER 0
-#define CONFIG_LRC_DEMUXER 0
-#define CONFIG_LVF_DEMUXER 0
-#define CONFIG_LXF_DEMUXER 0
-#define CONFIG_M4V_DEMUXER 0
-#define CONFIG_MATROSKA_DEMUXER 0
-#define CONFIG_MGSTS_DEMUXER 0
-#define CONFIG_MICRODVD_DEMUXER 0
-#define CONFIG_MJPEG_DEMUXER 0
-#define CONFIG_MLP_DEMUXER 0
-#define CONFIG_MLV_DEMUXER 0
-#define CONFIG_MM_DEMUXER 0
-#define CONFIG_MMF_DEMUXER 0
-#define CONFIG_MOV_DEMUXER 0
-#define CONFIG_MP3_DEMUXER 0
-#define CONFIG_MPC_DEMUXER 0
-#define CONFIG_MPC8_DEMUXER 0
-#define CONFIG_MPEGPS_DEMUXER 0
-#define CONFIG_MPEGTS_DEMUXER 0
-#define CONFIG_MPEGTSRAW_DEMUXER 0
-#define CONFIG_MPEGVIDEO_DEMUXER 0
-#define CONFIG_MPJPEG_DEMUXER 0
-#define CONFIG_MPL2_DEMUXER 0
-#define CONFIG_MPSUB_DEMUXER 0
-#define CONFIG_MSF_DEMUXER 0
-#define CONFIG_MSNWC_TCP_DEMUXER 0
-#define CONFIG_MTAF_DEMUXER 0
-#define CONFIG_MTV_DEMUXER 0
-#define CONFIG_MUSX_DEMUXER 0
-#define CONFIG_MV_DEMUXER 0
-#define CONFIG_MVI_DEMUXER 0
-#define CONFIG_MXF_DEMUXER 0
-#define CONFIG_MXG_DEMUXER 0
-#define CONFIG_NC_DEMUXER 0
-#define CONFIG_NISTSPHERE_DEMUXER 0
-#define CONFIG_NSV_DEMUXER 0
-#define CONFIG_NUT_DEMUXER 0
-#define CONFIG_NUV_DEMUXER 0
-#define CONFIG_OGG_DEMUXER 0
-#define CONFIG_OMA_DEMUXER 0
-#define CONFIG_PAF_DEMUXER 0
-#define CONFIG_PCM_ALAW_DEMUXER 0
-#define CONFIG_PCM_MULAW_DEMUXER 0
-#define CONFIG_PCM_F64BE_DEMUXER 0
-#define CONFIG_PCM_F64LE_DEMUXER 0
-#define CONFIG_PCM_F32BE_DEMUXER 0
-#define CONFIG_PCM_F32LE_DEMUXER 0
-#define CONFIG_PCM_S32BE_DEMUXER 0
-#define CONFIG_PCM_S32LE_DEMUXER 0
-#define CONFIG_PCM_S24BE_DEMUXER 0
-#define CONFIG_PCM_S24LE_DEMUXER 0
-#define CONFIG_PCM_S16BE_DEMUXER 0
-#define CONFIG_PCM_S16LE_DEMUXER 0
-#define CONFIG_PCM_S8_DEMUXER 0
-#define CONFIG_PCM_U32BE_DEMUXER 0
-#define CONFIG_PCM_U32LE_DEMUXER 0
-#define CONFIG_PCM_U24BE_DEMUXER 0
-#define CONFIG_PCM_U24LE_DEMUXER 0
-#define CONFIG_PCM_U16BE_DEMUXER 0
-#define CONFIG_PCM_U16LE_DEMUXER 0
-#define CONFIG_PCM_U8_DEMUXER 0
-#define CONFIG_PJS_DEMUXER 0
-#define CONFIG_PMP_DEMUXER 0
-#define CONFIG_PVA_DEMUXER 0
-#define CONFIG_PVF_DEMUXER 0
-#define CONFIG_QCP_DEMUXER 0
-#define CONFIG_R3D_DEMUXER 0
-#define CONFIG_RAWVIDEO_DEMUXER 0
-#define CONFIG_REALTEXT_DEMUXER 0
-#define CONFIG_REDSPARK_DEMUXER 0
-#define CONFIG_RL2_DEMUXER 0
-#define CONFIG_RM_DEMUXER 0
-#define CONFIG_ROQ_DEMUXER 0
-#define CONFIG_RPL_DEMUXER 0
-#define CONFIG_RSD_DEMUXER 0
-#define CONFIG_RSO_DEMUXER 0
-#define CONFIG_RTP_DEMUXER 0
-#define CONFIG_RTSP_DEMUXER 0
-#define CONFIG_SAMI_DEMUXER 0
-#define CONFIG_SAP_DEMUXER 0
-#define CONFIG_SBG_DEMUXER 0
-#define CONFIG_SDP_DEMUXER 0
-#define CONFIG_SDR2_DEMUXER 0
-#define CONFIG_SEGAFILM_DEMUXER 0
-#define CONFIG_SHORTEN_DEMUXER 0
-#define CONFIG_SIFF_DEMUXER 0
-#define CONFIG_SLN_DEMUXER 0
-#define CONFIG_SMACKER_DEMUXER 0
-#define CONFIG_SMJPEG_DEMUXER 0
-#define CONFIG_SMUSH_DEMUXER 0
-#define CONFIG_SOL_DEMUXER 0
-#define CONFIG_SOX_DEMUXER 0
-#define CONFIG_SPDIF_DEMUXER 0
-#define CONFIG_SRT_DEMUXER 0
-#define CONFIG_STR_DEMUXER 0
-#define CONFIG_STL_DEMUXER 0
-#define CONFIG_SUBVIEWER1_DEMUXER 0
-#define CONFIG_SUBVIEWER_DEMUXER 0
-#define CONFIG_SUP_DEMUXER 0
-#define CONFIG_SVAG_DEMUXER 0
-#define CONFIG_SWF_DEMUXER 0
-#define CONFIG_TAK_DEMUXER 0
-#define CONFIG_TEDCAPTIONS_DEMUXER 0
-#define CONFIG_THP_DEMUXER 0
-#define CONFIG_THREEDOSTR_DEMUXER 0
-#define CONFIG_TIERTEXSEQ_DEMUXER 0
-#define CONFIG_TMV_DEMUXER 0
-#define CONFIG_TRUEHD_DEMUXER 0
-#define CONFIG_TTA_DEMUXER 0
-#define CONFIG_TXD_DEMUXER 0
-#define CONFIG_TTY_DEMUXER 0
-#define CONFIG_V210_DEMUXER 0
-#define CONFIG_V210X_DEMUXER 0
-#define CONFIG_VAG_DEMUXER 0
-#define CONFIG_VC1_DEMUXER 0
-#define CONFIG_VC1T_DEMUXER 0
-#define CONFIG_VIVO_DEMUXER 0
-#define CONFIG_VMD_DEMUXER 0
-#define CONFIG_VOBSUB_DEMUXER 0
-#define CONFIG_VOC_DEMUXER 0
-#define CONFIG_VPK_DEMUXER 0
-#define CONFIG_VPLAYER_DEMUXER 0
-#define CONFIG_VQF_DEMUXER 0
-#define CONFIG_W64_DEMUXER 0
-#define CONFIG_WAV_DEMUXER 0
-#define CONFIG_WC3_DEMUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-#define CONFIG_WEBVTT_DEMUXER 0
-#define CONFIG_WSAUD_DEMUXER 0
-#define CONFIG_WSD_DEMUXER 0
-#define CONFIG_WSVQA_DEMUXER 0
-#define CONFIG_WTV_DEMUXER 0
-#define CONFIG_WVE_DEMUXER 0
-#define CONFIG_WV_DEMUXER 0
-#define CONFIG_XA_DEMUXER 0
-#define CONFIG_XBIN_DEMUXER 0
-#define CONFIG_XMV_DEMUXER 0
-#define CONFIG_XVAG_DEMUXER 0
-#define CONFIG_XWMA_DEMUXER 0
-#define CONFIG_YOP_DEMUXER 0
-#define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-#define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-#define CONFIG_LIBGME_DEMUXER 0
-#define CONFIG_LIBMODPLUG_DEMUXER 0
-#define CONFIG_LIBNUT_DEMUXER 0
-#define CONFIG_LIBOPENMPT_DEMUXER 0
-#define CONFIG_A64MULTI_ENCODER 0
-#define CONFIG_A64MULTI5_ENCODER 0
-#define CONFIG_ALIAS_PIX_ENCODER 0
-#define CONFIG_AMV_ENCODER 0
-#define CONFIG_APNG_ENCODER 0
-#define CONFIG_ASV1_ENCODER 0
-#define CONFIG_ASV2_ENCODER 0
-#define CONFIG_AVRP_ENCODER 0
-#define CONFIG_AVUI_ENCODER 0
-#define CONFIG_AYUV_ENCODER 0
-#define CONFIG_BMP_ENCODER 0
-#define CONFIG_CINEPAK_ENCODER 0
-#define CONFIG_CLJR_ENCODER 0
-#define CONFIG_COMFORTNOISE_ENCODER 0
-#define CONFIG_DNXHD_ENCODER 0
-#define CONFIG_DPX_ENCODER 0
-#define CONFIG_DVVIDEO_ENCODER 0
-#define CONFIG_FFV1_ENCODER 0
-#define CONFIG_FFVHUFF_ENCODER 0
-#define CONFIG_FLASHSV_ENCODER 0
-#define CONFIG_FLASHSV2_ENCODER 0
-#define CONFIG_FLV_ENCODER 0
-#define CONFIG_GIF_ENCODER 0
-#define CONFIG_H261_ENCODER 0
-#define CONFIG_H263_ENCODER 0
-#define CONFIG_H263P_ENCODER 0
-#define CONFIG_HAP_ENCODER 0
-#define CONFIG_HUFFYUV_ENCODER 0
-#define CONFIG_JPEG2000_ENCODER 0
-#define CONFIG_JPEGLS_ENCODER 0
-#define CONFIG_LJPEG_ENCODER 0
-#define CONFIG_MJPEG_ENCODER 0
-#define CONFIG_MPEG1VIDEO_ENCODER 0
-#define CONFIG_MPEG2VIDEO_ENCODER 0
-#define CONFIG_MPEG4_ENCODER 0
-#define CONFIG_MSMPEG4V2_ENCODER 0
-#define CONFIG_MSMPEG4V3_ENCODER 0
-#define CONFIG_MSVIDEO1_ENCODER 0
-#define CONFIG_PAM_ENCODER 0
-#define CONFIG_PBM_ENCODER 0
-#define CONFIG_PCX_ENCODER 0
-#define CONFIG_PGM_ENCODER 0
-#define CONFIG_PGMYUV_ENCODER 0
-#define CONFIG_PNG_ENCODER 0
-#define CONFIG_PPM_ENCODER 0
-#define CONFIG_PRORES_ENCODER 0
-#define CONFIG_PRORES_AW_ENCODER 0
-#define CONFIG_PRORES_KS_ENCODER 0
-#define CONFIG_QTRLE_ENCODER 0
-#define CONFIG_R10K_ENCODER 0
-#define CONFIG_R210_ENCODER 0
-#define CONFIG_RAWVIDEO_ENCODER 0
-#define CONFIG_ROQ_ENCODER 0
-#define CONFIG_RV10_ENCODER 0
-#define CONFIG_RV20_ENCODER 0
-#define CONFIG_S302M_ENCODER 0
-#define CONFIG_SGI_ENCODER 0
-#define CONFIG_SNOW_ENCODER 0
-#define CONFIG_SUNRAST_ENCODER 0
-#define CONFIG_SVQ1_ENCODER 0
-#define CONFIG_TARGA_ENCODER 0
-#define CONFIG_TIFF_ENCODER 0
-#define CONFIG_UTVIDEO_ENCODER 0
-#define CONFIG_V210_ENCODER 0
-#define CONFIG_V308_ENCODER 0
-#define CONFIG_V408_ENCODER 0
-#define CONFIG_V410_ENCODER 0
-#define CONFIG_VC2_ENCODER 0
-#define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-#define CONFIG_WMV1_ENCODER 0
-#define CONFIG_WMV2_ENCODER 0
-#define CONFIG_XBM_ENCODER 0
-#define CONFIG_XFACE_ENCODER 0
-#define CONFIG_XWD_ENCODER 0
-#define CONFIG_Y41P_ENCODER 0
-#define CONFIG_YUV4_ENCODER 0
-#define CONFIG_ZLIB_ENCODER 0
-#define CONFIG_ZMBV_ENCODER 0
-#define CONFIG_AAC_ENCODER 0
-#define CONFIG_AC3_ENCODER 0
-#define CONFIG_AC3_FIXED_ENCODER 0
-#define CONFIG_ALAC_ENCODER 0
-#define CONFIG_DCA_ENCODER 0
-#define CONFIG_EAC3_ENCODER 0
-#define CONFIG_FLAC_ENCODER 0
-#define CONFIG_G723_1_ENCODER 0
-#define CONFIG_MLP_ENCODER 0
-#define CONFIG_MP2_ENCODER 0
-#define CONFIG_MP2FIXED_ENCODER 0
-#define CONFIG_NELLYMOSER_ENCODER 0
-#define CONFIG_RA_144_ENCODER 0
-#define CONFIG_SONIC_ENCODER 0
-#define CONFIG_SONIC_LS_ENCODER 0
-#define CONFIG_TRUEHD_ENCODER 0
-#define CONFIG_TTA_ENCODER 0
-#define CONFIG_VORBIS_ENCODER 0
-#define CONFIG_WAVPACK_ENCODER 0
-#define CONFIG_WMAV1_ENCODER 0
-#define CONFIG_WMAV2_ENCODER 0
-#define CONFIG_PCM_ALAW_ENCODER 0
-#define CONFIG_PCM_F32BE_ENCODER 0
-#define CONFIG_PCM_F32LE_ENCODER 0
-#define CONFIG_PCM_F64BE_ENCODER 0
-#define CONFIG_PCM_F64LE_ENCODER 0
-#define CONFIG_PCM_MULAW_ENCODER 0
-#define CONFIG_PCM_S8_ENCODER 0
-#define CONFIG_PCM_S8_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16BE_ENCODER 0
-#define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16LE_ENCODER 0
-#define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S24BE_ENCODER 0
-#define CONFIG_PCM_S24DAUD_ENCODER 0
-#define CONFIG_PCM_S24LE_ENCODER 0
-#define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S32BE_ENCODER 0
-#define CONFIG_PCM_S32LE_ENCODER 0
-#define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S64BE_ENCODER 0
-#define CONFIG_PCM_S64LE_ENCODER 0
-#define CONFIG_PCM_U8_ENCODER 0
-#define CONFIG_PCM_U16BE_ENCODER 0
-#define CONFIG_PCM_U16LE_ENCODER 0
-#define CONFIG_PCM_U24BE_ENCODER 0
-#define CONFIG_PCM_U24LE_ENCODER 0
-#define CONFIG_PCM_U32BE_ENCODER 0
-#define CONFIG_PCM_U32LE_ENCODER 0
-#define CONFIG_ROQ_DPCM_ENCODER 0
-#define CONFIG_ADPCM_ADX_ENCODER 0
-#define CONFIG_ADPCM_G722_ENCODER 0
-#define CONFIG_ADPCM_G726_ENCODER 0
-#define CONFIG_ADPCM_IMA_QT_ENCODER 0
-#define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-#define CONFIG_ADPCM_MS_ENCODER 0
-#define CONFIG_ADPCM_SWF_ENCODER 0
-#define CONFIG_ADPCM_YAMAHA_ENCODER 0
-#define CONFIG_SSA_ENCODER 0
-#define CONFIG_ASS_ENCODER 0
-#define CONFIG_DVBSUB_ENCODER 0
-#define CONFIG_DVDSUB_ENCODER 0
-#define CONFIG_MOVTEXT_ENCODER 0
-#define CONFIG_SRT_ENCODER 0
-#define CONFIG_SUBRIP_ENCODER 0
-#define CONFIG_TEXT_ENCODER 0
-#define CONFIG_WEBVTT_ENCODER 0
-#define CONFIG_XSUB_ENCODER 0
-#define CONFIG_AAC_AT_ENCODER 0
-#define CONFIG_ALAC_AT_ENCODER 0
-#define CONFIG_ILBC_AT_ENCODER 0
-#define CONFIG_PCM_ALAW_AT_ENCODER 0
-#define CONFIG_PCM_MULAW_AT_ENCODER 0
-#define CONFIG_LIBFDK_AAC_ENCODER 0
-#define CONFIG_LIBGSM_ENCODER 0
-#define CONFIG_LIBGSM_MS_ENCODER 0
-#define CONFIG_LIBILBC_ENCODER 0
-#define CONFIG_LIBMP3LAME_ENCODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-#define CONFIG_LIBOPENJPEG_ENCODER 0
-#define CONFIG_LIBOPUS_ENCODER 0
-#define CONFIG_LIBSCHROEDINGER_ENCODER 0
-#define CONFIG_LIBSHINE_ENCODER 0
-#define CONFIG_LIBSPEEX_ENCODER 0
-#define CONFIG_LIBTHEORA_ENCODER 0
-#define CONFIG_LIBTWOLAME_ENCODER 0
-#define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-#define CONFIG_LIBVORBIS_ENCODER 0
-#define CONFIG_LIBVPX_VP8_ENCODER 0
-#define CONFIG_LIBVPX_VP9_ENCODER 0
-#define CONFIG_LIBWAVPACK_ENCODER 0
-#define CONFIG_LIBWEBP_ANIM_ENCODER 0
-#define CONFIG_LIBWEBP_ENCODER 0
-#define CONFIG_LIBX262_ENCODER 0
-#define CONFIG_LIBX264_ENCODER 0
-#define CONFIG_LIBX264RGB_ENCODER 0
-#define CONFIG_LIBX265_ENCODER 0
-#define CONFIG_LIBXAVS_ENCODER 0
-#define CONFIG_LIBXVID_ENCODER 0
-#define CONFIG_LIBOPENH264_ENCODER 0
-#define CONFIG_H264_NVENC_ENCODER 0
-#define CONFIG_H264_OMX_ENCODER 0
-#define CONFIG_H264_QSV_ENCODER 0
-#define CONFIG_H264_VAAPI_ENCODER 0
-#define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-#define CONFIG_NVENC_ENCODER 0
-#define CONFIG_NVENC_H264_ENCODER 0
-#define CONFIG_NVENC_HEVC_ENCODER 0
-#define CONFIG_HEVC_NVENC_ENCODER 0
-#define CONFIG_HEVC_QSV_ENCODER 0
-#define CONFIG_HEVC_VAAPI_ENCODER 0
-#define CONFIG_LIBKVAZAAR_ENCODER 0
-#define CONFIG_MJPEG_VAAPI_ENCODER 0
-#define CONFIG_MPEG2_QSV_ENCODER 0
-#define CONFIG_ABENCH_FILTER 0
-#define CONFIG_ACOMPRESSOR_FILTER 0
-#define CONFIG_ACROSSFADE_FILTER 0
-#define CONFIG_ACRUSHER_FILTER 0
-#define CONFIG_ADELAY_FILTER 0
-#define CONFIG_AECHO_FILTER 0
-#define CONFIG_AEMPHASIS_FILTER 0
-#define CONFIG_AEVAL_FILTER 0
-#define CONFIG_AFADE_FILTER 0
-#define CONFIG_AFFTFILT_FILTER 0
-#define CONFIG_AFORMAT_FILTER 0
-#define CONFIG_AGATE_FILTER 0
-#define CONFIG_AINTERLEAVE_FILTER 0
-#define CONFIG_ALIMITER_FILTER 0
-#define CONFIG_ALLPASS_FILTER 0
-#define CONFIG_ALOOP_FILTER 0
-#define CONFIG_AMERGE_FILTER 0
-#define CONFIG_AMETADATA_FILTER 0
-#define CONFIG_AMIX_FILTER 0
-#define CONFIG_ANEQUALIZER_FILTER 0
-#define CONFIG_ANULL_FILTER 0
-#define CONFIG_APAD_FILTER 0
-#define CONFIG_APERMS_FILTER 0
-#define CONFIG_APHASER_FILTER 0
-#define CONFIG_APULSATOR_FILTER 0
-#define CONFIG_AREALTIME_FILTER 0
-#define CONFIG_ARESAMPLE_FILTER 0
-#define CONFIG_AREVERSE_FILTER 0
-#define CONFIG_ASELECT_FILTER 0
-#define CONFIG_ASENDCMD_FILTER 0
-#define CONFIG_ASETNSAMPLES_FILTER 0
-#define CONFIG_ASETPTS_FILTER 0
-#define CONFIG_ASETRATE_FILTER 0
-#define CONFIG_ASETTB_FILTER 0
-#define CONFIG_ASHOWINFO_FILTER 0
-#define CONFIG_ASIDEDATA_FILTER 0
-#define CONFIG_ASPLIT_FILTER 0
-#define CONFIG_ASTATS_FILTER 0
-#define CONFIG_ASTREAMSELECT_FILTER 0
-#define CONFIG_ASYNCTS_FILTER 0
-#define CONFIG_ATEMPO_FILTER 0
-#define CONFIG_ATRIM_FILTER 0
-#define CONFIG_AZMQ_FILTER 0
-#define CONFIG_BANDPASS_FILTER 0
-#define CONFIG_BANDREJECT_FILTER 0
-#define CONFIG_BASS_FILTER 0
-#define CONFIG_BIQUAD_FILTER 0
-#define CONFIG_BS2B_FILTER 0
-#define CONFIG_CHANNELMAP_FILTER 0
-#define CONFIG_CHANNELSPLIT_FILTER 0
-#define CONFIG_CHORUS_FILTER 0
-#define CONFIG_COMPAND_FILTER 0
-#define CONFIG_COMPENSATIONDELAY_FILTER 0
-#define CONFIG_CRYSTALIZER_FILTER 0
-#define CONFIG_DCSHIFT_FILTER 0
-#define CONFIG_DYNAUDNORM_FILTER 0
-#define CONFIG_EARWAX_FILTER 0
-#define CONFIG_EBUR128_FILTER 0
-#define CONFIG_EQUALIZER_FILTER 0
-#define CONFIG_EXTRASTEREO_FILTER 0
-#define CONFIG_FIREQUALIZER_FILTER 0
-#define CONFIG_FLANGER_FILTER 0
-#define CONFIG_HDCD_FILTER 0
-#define CONFIG_HIGHPASS_FILTER 0
-#define CONFIG_JOIN_FILTER 0
-#define CONFIG_LADSPA_FILTER 0
-#define CONFIG_LOUDNORM_FILTER 0
-#define CONFIG_LOWPASS_FILTER 0
-#define CONFIG_PAN_FILTER 0
-#define CONFIG_REPLAYGAIN_FILTER 0
-#define CONFIG_RESAMPLE_FILTER 0
-#define CONFIG_RUBBERBAND_FILTER 0
-#define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-#define CONFIG_SIDECHAINGATE_FILTER 0
-#define CONFIG_SILENCEDETECT_FILTER 0
-#define CONFIG_SILENCEREMOVE_FILTER 0
-#define CONFIG_SOFALIZER_FILTER 0
-#define CONFIG_STEREOTOOLS_FILTER 0
-#define CONFIG_STEREOWIDEN_FILTER 0
-#define CONFIG_TREBLE_FILTER 0
-#define CONFIG_TREMOLO_FILTER 0
-#define CONFIG_VIBRATO_FILTER 0
-#define CONFIG_VOLUME_FILTER 0
-#define CONFIG_VOLUMEDETECT_FILTER 0
-#define CONFIG_AEVALSRC_FILTER 0
-#define CONFIG_ANOISESRC_FILTER 0
-#define CONFIG_ANULLSRC_FILTER 0
-#define CONFIG_FLITE_FILTER 0
-#define CONFIG_SINE_FILTER 0
-#define CONFIG_ANULLSINK_FILTER 0
-#define CONFIG_ALPHAEXTRACT_FILTER 0
-#define CONFIG_ALPHAMERGE_FILTER 0
-#define CONFIG_ASS_FILTER 0
-#define CONFIG_ATADENOISE_FILTER 0
-#define CONFIG_AVGBLUR_FILTER 0
-#define CONFIG_BBOX_FILTER 0
-#define CONFIG_BENCH_FILTER 0
-#define CONFIG_BITPLANENOISE_FILTER 0
-#define CONFIG_BLACKDETECT_FILTER 0
-#define CONFIG_BLACKFRAME_FILTER 0
-#define CONFIG_BLEND_FILTER 0
-#define CONFIG_BOXBLUR_FILTER 0
-#define CONFIG_BWDIF_FILTER 0
-#define CONFIG_CHROMAKEY_FILTER 0
-#define CONFIG_CIESCOPE_FILTER 0
-#define CONFIG_CODECVIEW_FILTER 0
-#define CONFIG_COLORBALANCE_FILTER 0
-#define CONFIG_COLORCHANNELMIXER_FILTER 0
-#define CONFIG_COLORKEY_FILTER 0
-#define CONFIG_COLORLEVELS_FILTER 0
-#define CONFIG_COLORMATRIX_FILTER 0
-#define CONFIG_COLORSPACE_FILTER 0
-#define CONFIG_CONVOLUTION_FILTER 0
-#define CONFIG_COPY_FILTER 0
-#define CONFIG_COREIMAGE_FILTER 0
-#define CONFIG_COVER_RECT_FILTER 0
-#define CONFIG_CROP_FILTER 0
-#define CONFIG_CROPDETECT_FILTER 0
-#define CONFIG_CURVES_FILTER 0
-#define CONFIG_DATASCOPE_FILTER 0
-#define CONFIG_DCTDNOIZ_FILTER 0
-#define CONFIG_DEBAND_FILTER 0
-#define CONFIG_DECIMATE_FILTER 0
-#define CONFIG_DEFLATE_FILTER 0
-#define CONFIG_DEJUDDER_FILTER 0
-#define CONFIG_DELOGO_FILTER 0
-#define CONFIG_DESHAKE_FILTER 0
-#define CONFIG_DETELECINE_FILTER 0
-#define CONFIG_DILATION_FILTER 0
-#define CONFIG_DISPLACE_FILTER 0
-#define CONFIG_DRAWBOX_FILTER 0
-#define CONFIG_DRAWGRAPH_FILTER 0
-#define CONFIG_DRAWGRID_FILTER 0
-#define CONFIG_DRAWTEXT_FILTER 0
-#define CONFIG_EDGEDETECT_FILTER 0
-#define CONFIG_ELBG_FILTER 0
-#define CONFIG_EQ_FILTER 0
-#define CONFIG_EROSION_FILTER 0
-#define CONFIG_EXTRACTPLANES_FILTER 0
-#define CONFIG_FADE_FILTER 0
-#define CONFIG_FFTFILT_FILTER 0
-#define CONFIG_FIELD_FILTER 0
-#define CONFIG_FIELDHINT_FILTER 0
-#define CONFIG_FIELDMATCH_FILTER 0
-#define CONFIG_FIELDORDER_FILTER 0
-#define CONFIG_FIND_RECT_FILTER 0
-#define CONFIG_FORMAT_FILTER 0
-#define CONFIG_FPS_FILTER 0
-#define CONFIG_FRAMEPACK_FILTER 0
-#define CONFIG_FRAMERATE_FILTER 0
-#define CONFIG_FRAMESTEP_FILTER 0
-#define CONFIG_FREI0R_FILTER 0
-#define CONFIG_FSPP_FILTER 0
-#define CONFIG_GBLUR_FILTER 0
-#define CONFIG_GEQ_FILTER 0
-#define CONFIG_GRADFUN_FILTER 0
-#define CONFIG_HALDCLUT_FILTER 0
-#define CONFIG_HFLIP_FILTER 0
-#define CONFIG_HISTEQ_FILTER 0
-#define CONFIG_HISTOGRAM_FILTER 0
-#define CONFIG_HQDN3D_FILTER 0
-#define CONFIG_HQX_FILTER 0
-#define CONFIG_HSTACK_FILTER 0
-#define CONFIG_HUE_FILTER 0
-#define CONFIG_HWDOWNLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_CUDA_FILTER 0
-#define CONFIG_HYSTERESIS_FILTER 0
-#define CONFIG_IDET_FILTER 0
-#define CONFIG_IL_FILTER 0
-#define CONFIG_INFLATE_FILTER 0
-#define CONFIG_INTERLACE_FILTER 0
-#define CONFIG_INTERLEAVE_FILTER 0
-#define CONFIG_KERNDEINT_FILTER 0
-#define CONFIG_LENSCORRECTION_FILTER 0
-#define CONFIG_LOOP_FILTER 0
-#define CONFIG_LUT_FILTER 0
-#define CONFIG_LUT2_FILTER 0
-#define CONFIG_LUT3D_FILTER 0
-#define CONFIG_LUTRGB_FILTER 0
-#define CONFIG_LUTYUV_FILTER 0
-#define CONFIG_MASKEDCLAMP_FILTER 0
-#define CONFIG_MASKEDMERGE_FILTER 0
-#define CONFIG_MCDEINT_FILTER 0
-#define CONFIG_MERGEPLANES_FILTER 0
-#define CONFIG_MESTIMATE_FILTER 0
-#define CONFIG_METADATA_FILTER 0
-#define CONFIG_MINTERPOLATE_FILTER 0
-#define CONFIG_MPDECIMATE_FILTER 0
-#define CONFIG_NEGATE_FILTER 0
-#define CONFIG_NLMEANS_FILTER 0
-#define CONFIG_NNEDI_FILTER 0
-#define CONFIG_NOFORMAT_FILTER 0
-#define CONFIG_NOISE_FILTER 0
-#define CONFIG_NULL_FILTER 0
-#define CONFIG_OCR_FILTER 0
-#define CONFIG_OCV_FILTER 0
-#define CONFIG_OVERLAY_FILTER 0
-#define CONFIG_OWDENOISE_FILTER 0
-#define CONFIG_PAD_FILTER 0
-#define CONFIG_PALETTEGEN_FILTER 0
-#define CONFIG_PALETTEUSE_FILTER 0
-#define CONFIG_PERMS_FILTER 0
-#define CONFIG_PERSPECTIVE_FILTER 0
-#define CONFIG_PHASE_FILTER 0
-#define CONFIG_PIXDESCTEST_FILTER 0
-#define CONFIG_PP_FILTER 0
-#define CONFIG_PP7_FILTER 0
-#define CONFIG_PREWITT_FILTER 0
-#define CONFIG_PSNR_FILTER 0
-#define CONFIG_PULLUP_FILTER 0
-#define CONFIG_QP_FILTER 0
-#define CONFIG_RANDOM_FILTER 0
-#define CONFIG_READVITC_FILTER 0
-#define CONFIG_REALTIME_FILTER 0
-#define CONFIG_REMAP_FILTER 0
-#define CONFIG_REMOVEGRAIN_FILTER 0
-#define CONFIG_REMOVELOGO_FILTER 0
-#define CONFIG_REPEATFIELDS_FILTER 0
-#define CONFIG_REVERSE_FILTER 0
-#define CONFIG_ROTATE_FILTER 0
-#define CONFIG_SAB_FILTER 0
-#define CONFIG_SCALE_FILTER 0
-#define CONFIG_SCALE_NPP_FILTER 0
-#define CONFIG_SCALE_VAAPI_FILTER 0
-#define CONFIG_SCALE2REF_FILTER 0
-#define CONFIG_SELECT_FILTER 0
-#define CONFIG_SELECTIVECOLOR_FILTER 0
-#define CONFIG_SENDCMD_FILTER 0
-#define CONFIG_SEPARATEFIELDS_FILTER 0
-#define CONFIG_SETDAR_FILTER 0
-#define CONFIG_SETFIELD_FILTER 0
-#define CONFIG_SETPTS_FILTER 0
-#define CONFIG_SETSAR_FILTER 0
-#define CONFIG_SETTB_FILTER 0
-#define CONFIG_SHOWINFO_FILTER 0
-#define CONFIG_SHOWPALETTE_FILTER 0
-#define CONFIG_SHUFFLEFRAMES_FILTER 0
-#define CONFIG_SHUFFLEPLANES_FILTER 0
-#define CONFIG_SIDEDATA_FILTER 0
-#define CONFIG_SIGNALSTATS_FILTER 0
-#define CONFIG_SMARTBLUR_FILTER 0
-#define CONFIG_SOBEL_FILTER 0
-#define CONFIG_SPLIT_FILTER 0
-#define CONFIG_SPP_FILTER 0
-#define CONFIG_SSIM_FILTER 0
-#define CONFIG_STEREO3D_FILTER 0
-#define CONFIG_STREAMSELECT_FILTER 0
-#define CONFIG_SUBTITLES_FILTER 0
-#define CONFIG_SUPER2XSAI_FILTER 0
-#define CONFIG_SWAPRECT_FILTER 0
-#define CONFIG_SWAPUV_FILTER 0
-#define CONFIG_TBLEND_FILTER 0
-#define CONFIG_TELECINE_FILTER 0
-#define CONFIG_THUMBNAIL_FILTER 0
-#define CONFIG_TILE_FILTER 0
-#define CONFIG_TINTERLACE_FILTER 0
-#define CONFIG_TRANSPOSE_FILTER 0
-#define CONFIG_TRIM_FILTER 0
-#define CONFIG_UNSHARP_FILTER 0
-#define CONFIG_USPP_FILTER 0
-#define CONFIG_VAGUEDENOISER_FILTER 0
-#define CONFIG_VECTORSCOPE_FILTER 0
-#define CONFIG_VFLIP_FILTER 0
-#define CONFIG_VIDSTABDETECT_FILTER 0
-#define CONFIG_VIDSTABTRANSFORM_FILTER 0
-#define CONFIG_VIGNETTE_FILTER 0
-#define CONFIG_VSTACK_FILTER 0
-#define CONFIG_W3FDIF_FILTER 0
-#define CONFIG_WAVEFORM_FILTER 0
-#define CONFIG_WEAVE_FILTER 0
-#define CONFIG_XBR_FILTER 0
-#define CONFIG_YADIF_FILTER 0
-#define CONFIG_ZMQ_FILTER 0
-#define CONFIG_ZOOMPAN_FILTER 0
-#define CONFIG_ZSCALE_FILTER 0
-#define CONFIG_ALLRGB_FILTER 0
-#define CONFIG_ALLYUV_FILTER 0
-#define CONFIG_CELLAUTO_FILTER 0
-#define CONFIG_COLOR_FILTER 0
-#define CONFIG_COREIMAGESRC_FILTER 0
-#define CONFIG_FREI0R_SRC_FILTER 0
-#define CONFIG_HALDCLUTSRC_FILTER 0
-#define CONFIG_LIFE_FILTER 0
-#define CONFIG_MANDELBROT_FILTER 0
-#define CONFIG_MPTESTSRC_FILTER 0
-#define CONFIG_NULLSRC_FILTER 0
-#define CONFIG_RGBTESTSRC_FILTER 0
-#define CONFIG_SMPTEBARS_FILTER 0
-#define CONFIG_SMPTEHDBARS_FILTER 0
-#define CONFIG_TESTSRC_FILTER 0
-#define CONFIG_TESTSRC2_FILTER 0
-#define CONFIG_YUVTESTSRC_FILTER 0
-#define CONFIG_NULLSINK_FILTER 0
-#define CONFIG_ADRAWGRAPH_FILTER 0
-#define CONFIG_AHISTOGRAM_FILTER 0
-#define CONFIG_APHASEMETER_FILTER 0
-#define CONFIG_AVECTORSCOPE_FILTER 0
-#define CONFIG_CONCAT_FILTER 0
-#define CONFIG_SHOWCQT_FILTER 0
-#define CONFIG_SHOWFREQS_FILTER 0
-#define CONFIG_SHOWSPECTRUM_FILTER 0
-#define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-#define CONFIG_SHOWVOLUME_FILTER 0
-#define CONFIG_SHOWWAVES_FILTER 0
-#define CONFIG_SHOWWAVESPIC_FILTER 0
-#define CONFIG_SPECTRUMSYNTH_FILTER 0
-#define CONFIG_AMOVIE_FILTER 0
-#define CONFIG_MOVIE_FILTER 0
-#define CONFIG_H263_CUVID_HWACCEL 0
-#define CONFIG_H263_VAAPI_HWACCEL 0
-#define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_H264_CUVID_HWACCEL 0
-#define CONFIG_H264_D3D11VA_HWACCEL 0
-#define CONFIG_H264_DXVA2_HWACCEL 0
-#define CONFIG_H264_MEDIACODEC_HWACCEL 0
-#define CONFIG_H264_MMAL_HWACCEL 0
-#define CONFIG_H264_QSV_HWACCEL 0
-#define CONFIG_H264_VAAPI_HWACCEL 0
-#define CONFIG_H264_VDA_HWACCEL 0
-#define CONFIG_H264_VDA_OLD_HWACCEL 0
-#define CONFIG_H264_VDPAU_HWACCEL 0
-#define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_HEVC_CUVID_HWACCEL 0
-#define CONFIG_HEVC_D3D11VA_HWACCEL 0
-#define CONFIG_HEVC_DXVA2_HWACCEL 0
-#define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-#define CONFIG_HEVC_QSV_HWACCEL 0
-#define CONFIG_HEVC_VAAPI_HWACCEL 0
-#define CONFIG_HEVC_VDPAU_HWACCEL 0
-#define CONFIG_MJPEG_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_XVMC_HWACCEL 0
-#define CONFIG_MPEG1_VDPAU_HWACCEL 0
-#define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG2_CUVID_HWACCEL 0
-#define CONFIG_MPEG2_XVMC_HWACCEL 0
-#define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-#define CONFIG_MPEG2_DXVA2_HWACCEL 0
-#define CONFIG_MPEG2_MMAL_HWACCEL 0
-#define CONFIG_MPEG2_QSV_HWACCEL 0
-#define CONFIG_MPEG2_VAAPI_HWACCEL 0
-#define CONFIG_MPEG2_VDPAU_HWACCEL 0
-#define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG4_CUVID_HWACCEL 0
-#define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-#define CONFIG_MPEG4_MMAL_HWACCEL 0
-#define CONFIG_MPEG4_VAAPI_HWACCEL 0
-#define CONFIG_MPEG4_VDPAU_HWACCEL 0
-#define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_VC1_CUVID_HWACCEL 0
-#define CONFIG_VC1_D3D11VA_HWACCEL 0
-#define CONFIG_VC1_DXVA2_HWACCEL 0
-#define CONFIG_VC1_VAAPI_HWACCEL 0
-#define CONFIG_VC1_VDPAU_HWACCEL 0
-#define CONFIG_VC1_MMAL_HWACCEL 0
-#define CONFIG_VC1_QSV_HWACCEL 0
-#define CONFIG_VP8_CUVID_HWACCEL 0
-#define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_CUVID_HWACCEL 0
-#define CONFIG_VP9_D3D11VA_HWACCEL 0
-#define CONFIG_VP9_DXVA2_HWACCEL 0
-#define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_D3D11VA_HWACCEL 0
-#define CONFIG_WMV3_DXVA2_HWACCEL 0
-#define CONFIG_WMV3_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_VDPAU_HWACCEL 0
-#define CONFIG_ALSA_INDEV 0
-#define CONFIG_AVFOUNDATION_INDEV 0
-#define CONFIG_BKTR_INDEV 0
-#define CONFIG_DECKLINK_INDEV 0
-#define CONFIG_DSHOW_INDEV 0
-#define CONFIG_DV1394_INDEV 0
-#define CONFIG_FBDEV_INDEV 0
-#define CONFIG_GDIGRAB_INDEV 0
-#define CONFIG_IEC61883_INDEV 0
-#define CONFIG_JACK_INDEV 0
-#define CONFIG_LAVFI_INDEV 0
-#define CONFIG_OPENAL_INDEV 0
-#define CONFIG_OSS_INDEV 0
-#define CONFIG_PULSE_INDEV 0
-#define CONFIG_QTKIT_INDEV 0
-#define CONFIG_SNDIO_INDEV 0
-#define CONFIG_V4L2_INDEV 0
-#define CONFIG_VFWCAP_INDEV 0
-#define CONFIG_X11GRAB_INDEV 0
-#define CONFIG_X11GRAB_XCB_INDEV 0
-#define CONFIG_LIBCDIO_INDEV 0
-#define CONFIG_LIBDC1394_INDEV 0
-#define CONFIG_A64_MUXER 0
-#define CONFIG_AC3_MUXER 0
-#define CONFIG_ADTS_MUXER 0
-#define CONFIG_ADX_MUXER 0
-#define CONFIG_AIFF_MUXER 0
-#define CONFIG_AMR_MUXER 0
-#define CONFIG_APNG_MUXER 0
-#define CONFIG_ASF_MUXER 0
-#define CONFIG_ASS_MUXER 0
-#define CONFIG_AST_MUXER 0
-#define CONFIG_ASF_STREAM_MUXER 0
-#define CONFIG_AU_MUXER 0
-#define CONFIG_AVI_MUXER 0
-#define CONFIG_AVM2_MUXER 0
-#define CONFIG_BIT_MUXER 0
-#define CONFIG_CAF_MUXER 0
-#define CONFIG_CAVSVIDEO_MUXER 0
-#define CONFIG_CRC_MUXER 0
-#define CONFIG_DASH_MUXER 0
-#define CONFIG_DATA_MUXER 0
-#define CONFIG_DAUD_MUXER 0
-#define CONFIG_DIRAC_MUXER 0
-#define CONFIG_DNXHD_MUXER 0
-#define CONFIG_DTS_MUXER 0
-#define CONFIG_DV_MUXER 0
-#define CONFIG_EAC3_MUXER 0
-#define CONFIG_F4V_MUXER 0
-#define CONFIG_FFM_MUXER 0
-#define CONFIG_FFMETADATA_MUXER 0
-#define CONFIG_FIFO_MUXER 0
-#define CONFIG_FILMSTRIP_MUXER 0
-#define CONFIG_FLAC_MUXER 0
-#define CONFIG_FLV_MUXER 0
-#define CONFIG_FRAMECRC_MUXER 0
-#define CONFIG_FRAMEHASH_MUXER 0
-#define CONFIG_FRAMEMD5_MUXER 0
-#define CONFIG_G722_MUXER 0
-#define CONFIG_G723_1_MUXER 0
-#define CONFIG_GIF_MUXER 0
-#define CONFIG_GSM_MUXER 0
-#define CONFIG_GXF_MUXER 0
-#define CONFIG_H261_MUXER 0
-#define CONFIG_H263_MUXER 0
-#define CONFIG_H264_MUXER 0
-#define CONFIG_HASH_MUXER 0
-#define CONFIG_HDS_MUXER 0
-#define CONFIG_HEVC_MUXER 0
-#define CONFIG_HLS_MUXER 0
-#define CONFIG_ICO_MUXER 0
-#define CONFIG_ILBC_MUXER 0
-#define CONFIG_IMAGE2_MUXER 0
-#define CONFIG_IMAGE2PIPE_MUXER 0
-#define CONFIG_IPOD_MUXER 0
-#define CONFIG_IRCAM_MUXER 0
-#define CONFIG_ISMV_MUXER 0
-#define CONFIG_IVF_MUXER 0
-#define CONFIG_JACOSUB_MUXER 0
-#define CONFIG_LATM_MUXER 0
-#define CONFIG_LRC_MUXER 0
-#define CONFIG_M4V_MUXER 0
-#define CONFIG_MD5_MUXER 0
-#define CONFIG_MATROSKA_MUXER 0
-#define CONFIG_MATROSKA_AUDIO_MUXER 0
-#define CONFIG_MICRODVD_MUXER 0
-#define CONFIG_MJPEG_MUXER 0
-#define CONFIG_MLP_MUXER 0
-#define CONFIG_MMF_MUXER 0
-#define CONFIG_MOV_MUXER 0
-#define CONFIG_MP2_MUXER 0
-#define CONFIG_MP3_MUXER 0
-#define CONFIG_MP4_MUXER 0
-#define CONFIG_MPEG1SYSTEM_MUXER 0
-#define CONFIG_MPEG1VCD_MUXER 0
-#define CONFIG_MPEG1VIDEO_MUXER 0
-#define CONFIG_MPEG2DVD_MUXER 0
-#define CONFIG_MPEG2SVCD_MUXER 0
-#define CONFIG_MPEG2VIDEO_MUXER 0
-#define CONFIG_MPEG2VOB_MUXER 0
-#define CONFIG_MPEGTS_MUXER 0
-#define CONFIG_MPJPEG_MUXER 0
-#define CONFIG_MXF_MUXER 0
-#define CONFIG_MXF_D10_MUXER 0
-#define CONFIG_MXF_OPATOM_MUXER 0
-#define CONFIG_NULL_MUXER 0
-#define CONFIG_NUT_MUXER 0
-#define CONFIG_OGA_MUXER 0
-#define CONFIG_OGG_MUXER 0
-#define CONFIG_OGV_MUXER 0
-#define CONFIG_OMA_MUXER 0
-#define CONFIG_OPUS_MUXER 0
-#define CONFIG_PCM_ALAW_MUXER 0
-#define CONFIG_PCM_MULAW_MUXER 0
-#define CONFIG_PCM_F64BE_MUXER 0
-#define CONFIG_PCM_F64LE_MUXER 0
-#define CONFIG_PCM_F32BE_MUXER 0
-#define CONFIG_PCM_F32LE_MUXER 0
-#define CONFIG_PCM_S32BE_MUXER 0
-#define CONFIG_PCM_S32LE_MUXER 0
-#define CONFIG_PCM_S24BE_MUXER 0
-#define CONFIG_PCM_S24LE_MUXER 0
-#define CONFIG_PCM_S16BE_MUXER 0
-#define CONFIG_PCM_S16LE_MUXER 0
-#define CONFIG_PCM_S8_MUXER 0
-#define CONFIG_PCM_U32BE_MUXER 0
-#define CONFIG_PCM_U32LE_MUXER 0
-#define CONFIG_PCM_U24BE_MUXER 0
-#define CONFIG_PCM_U24LE_MUXER 0
-#define CONFIG_PCM_U16BE_MUXER 0
-#define CONFIG_PCM_U16LE_MUXER 0
-#define CONFIG_PCM_U8_MUXER 0
-#define CONFIG_PSP_MUXER 0
-#define CONFIG_RAWVIDEO_MUXER 0
-#define CONFIG_RM_MUXER 0
-#define CONFIG_ROQ_MUXER 0
-#define CONFIG_RSO_MUXER 0
-#define CONFIG_RTP_MUXER 0
-#define CONFIG_RTP_MPEGTS_MUXER 0
-#define CONFIG_RTSP_MUXER 0
-#define CONFIG_SAP_MUXER 0
-#define CONFIG_SEGMENT_MUXER 0
-#define CONFIG_STREAM_SEGMENT_MUXER 0
-#define CONFIG_SINGLEJPEG_MUXER 0
-#define CONFIG_SMJPEG_MUXER 0
-#define CONFIG_SMOOTHSTREAMING_MUXER 0
-#define CONFIG_SOX_MUXER 0
-#define CONFIG_SPX_MUXER 0
-#define CONFIG_SPDIF_MUXER 0
-#define CONFIG_SRT_MUXER 0
-#define CONFIG_SWF_MUXER 0
-#define CONFIG_TEE_MUXER 0
-#define CONFIG_TG2_MUXER 0
-#define CONFIG_TGP_MUXER 0
-#define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-#define CONFIG_TRUEHD_MUXER 0
-#define CONFIG_TTA_MUXER 0
-#define CONFIG_UNCODEDFRAMECRC_MUXER 0
-#define CONFIG_VC1_MUXER 0
-#define CONFIG_VC1T_MUXER 0
-#define CONFIG_VOC_MUXER 0
-#define CONFIG_W64_MUXER 0
-#define CONFIG_WAV_MUXER 0
-#define CONFIG_WEBM_MUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-#define CONFIG_WEBM_CHUNK_MUXER 0
-#define CONFIG_WEBP_MUXER 0
-#define CONFIG_WEBVTT_MUXER 0
-#define CONFIG_WTV_MUXER 0
-#define CONFIG_WV_MUXER 0
-#define CONFIG_YUV4MPEGPIPE_MUXER 0
-#define CONFIG_CHROMAPRINT_MUXER 0
-#define CONFIG_LIBNUT_MUXER 0
-#define CONFIG_ALSA_OUTDEV 0
-#define CONFIG_CACA_OUTDEV 0
-#define CONFIG_DECKLINK_OUTDEV 0
-#define CONFIG_FBDEV_OUTDEV 0
-#define CONFIG_OPENGL_OUTDEV 0
-#define CONFIG_OSS_OUTDEV 0
-#define CONFIG_PULSE_OUTDEV 0
-#define CONFIG_SDL2_OUTDEV 0
-#define CONFIG_SNDIO_OUTDEV 0
-#define CONFIG_V4L2_OUTDEV 0
-#define CONFIG_XV_OUTDEV 0
-#define CONFIG_AAC_PARSER 0
-#define CONFIG_AAC_LATM_PARSER 0
-#define CONFIG_AC3_PARSER 0
-#define CONFIG_ADX_PARSER 0
-#define CONFIG_BMP_PARSER 0
-#define CONFIG_CAVSVIDEO_PARSER 0
-#define CONFIG_COOK_PARSER 0
-#define CONFIG_DCA_PARSER 0
-#define CONFIG_DIRAC_PARSER 0
-#define CONFIG_DNXHD_PARSER 0
-#define CONFIG_DPX_PARSER 0
-#define CONFIG_DVAUDIO_PARSER 0
-#define CONFIG_DVBSUB_PARSER 0
-#define CONFIG_DVDSUB_PARSER 0
-#define CONFIG_DVD_NAV_PARSER 0
-#define CONFIG_FLAC_PARSER 1
-#define CONFIG_G729_PARSER 0
-#define CONFIG_GSM_PARSER 0
-#define CONFIG_H261_PARSER 0
-#define CONFIG_H263_PARSER 0
-#define CONFIG_H264_PARSER 0
-#define CONFIG_HEVC_PARSER 0
-#define CONFIG_MJPEG_PARSER 0
-#define CONFIG_MLP_PARSER 0
-#define CONFIG_MPEG4VIDEO_PARSER 0
-#define CONFIG_MPEGAUDIO_PARSER 0
-#define CONFIG_MPEGVIDEO_PARSER 0
-#define CONFIG_OPUS_PARSER 0
-#define CONFIG_PNG_PARSER 0
-#define CONFIG_PNM_PARSER 0
-#define CONFIG_RV30_PARSER 0
-#define CONFIG_RV40_PARSER 0
-#define CONFIG_TAK_PARSER 0
-#define CONFIG_VC1_PARSER 0
-#define CONFIG_VORBIS_PARSER 0
-#define CONFIG_VP3_PARSER 0
+#define CONFIG_FLAC_PARSER 0
#define CONFIG_VP8_PARSER 1
#define CONFIG_VP9_PARSER 1
-#define CONFIG_ASYNC_PROTOCOL 0
-#define CONFIG_BLURAY_PROTOCOL 0
-#define CONFIG_CACHE_PROTOCOL 0
-#define CONFIG_CONCAT_PROTOCOL 0
-#define CONFIG_CRYPTO_PROTOCOL 0
-#define CONFIG_DATA_PROTOCOL 0
-#define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-#define CONFIG_FFRTMPHTTP_PROTOCOL 0
-#define CONFIG_FILE_PROTOCOL 0
-#define CONFIG_FTP_PROTOCOL 0
-#define CONFIG_GOPHER_PROTOCOL 0
-#define CONFIG_HLS_PROTOCOL 0
-#define CONFIG_HTTP_PROTOCOL 0
-#define CONFIG_HTTPPROXY_PROTOCOL 0
-#define CONFIG_HTTPS_PROTOCOL 0
-#define CONFIG_ICECAST_PROTOCOL 0
-#define CONFIG_MMSH_PROTOCOL 0
-#define CONFIG_MMST_PROTOCOL 0
-#define CONFIG_MD5_PROTOCOL 0
-#define CONFIG_PIPE_PROTOCOL 0
-#define CONFIG_RTMP_PROTOCOL 0
-#define CONFIG_RTMPE_PROTOCOL 0
-#define CONFIG_RTMPS_PROTOCOL 0
-#define CONFIG_RTMPT_PROTOCOL 0
-#define CONFIG_RTMPTE_PROTOCOL 0
-#define CONFIG_RTMPTS_PROTOCOL 0
-#define CONFIG_RTP_PROTOCOL 0
-#define CONFIG_SCTP_PROTOCOL 0
-#define CONFIG_SRTP_PROTOCOL 0
-#define CONFIG_SUBFILE_PROTOCOL 0
-#define CONFIG_TEE_PROTOCOL 0
-#define CONFIG_TCP_PROTOCOL 0
-#define CONFIG_TLS_GNUTLS_PROTOCOL 0
-#define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-#define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-#define CONFIG_TLS_OPENSSL_PROTOCOL 0
-#define CONFIG_UDP_PROTOCOL 0
-#define CONFIG_UDPLITE_PROTOCOL 0
-#define CONFIG_UNIX_PROTOCOL 0
-#define CONFIG_LIBRTMP_PROTOCOL 0
-#define CONFIG_LIBRTMPE_PROTOCOL 0
-#define CONFIG_LIBRTMPS_PROTOCOL 0
-#define CONFIG_LIBRTMPT_PROTOCOL 0
-#define CONFIG_LIBRTMPTE_PROTOCOL 0
-#define CONFIG_LIBSSH_PROTOCOL 0
-#define CONFIG_LIBSMBCLIENT_PROTOCOL 0
#endif /* FFMPEG_CONFIG_H */
diff --git a/media/ffvpx/config_win64.asm b/media/ffvpx/config_win64.asm
index d2ff06486..58c61e970 100644
--- a/media/ffvpx/config_win64.asm
+++ b/media/ffvpx/config_win64.asm
@@ -63,8 +63,8 @@
%define HAVE_MIPSDSP 0
%define HAVE_MIPSDSPR2 0
%define HAVE_MSA 0
-%define HAVE_LOONGSON2 1
-%define HAVE_LOONGSON3 1
+%define HAVE_LOONGSON2 0
+%define HAVE_LOONGSON3 0
%define HAVE_MMI 0
%define HAVE_ARMV5TE_EXTERNAL 0
%define HAVE_ARMV6_EXTERNAL 0
@@ -156,37 +156,38 @@
%define HAVE_MMI_INLINE 0
%define HAVE_ALIGNED_STACK 1
%define HAVE_FAST_64BIT 1
-%define HAVE_FAST_CLZ 1
+%define HAVE_FAST_CLZ 0
%define HAVE_FAST_CMOV 1
%define HAVE_LOCAL_ALIGNED_8 1
%define HAVE_LOCAL_ALIGNED_16 1
%define HAVE_LOCAL_ALIGNED_32 1
%define HAVE_SIMD_ALIGN_16 1
+%define HAVE_SIMD_ALIGN_32 1
%define HAVE_ATOMICS_GCC 0
%define HAVE_ATOMICS_SUNCC 0
%define HAVE_ATOMICS_WIN32 1
%define HAVE_ATOMIC_CAS_PTR 0
-%define HAVE_ATOMIC_COMPARE_EXCHANGE 0
%define HAVE_MACHINE_RW_BARRIER 0
%define HAVE_MEMORYBARRIER 1
%define HAVE_MM_EMPTY 0
%define HAVE_RDTSC 1
%define HAVE_SARESTART 0
-%define HAVE_SEM_TIMEDWAIT 1
+%define HAVE_SEM_TIMEDWAIT 0
%define HAVE_SYNC_VAL_COMPARE_AND_SWAP 0
%define HAVE_CABS 0
%define HAVE_CEXP 0
%define HAVE_INLINE_ASM 0
%define HAVE_SYMVER 0
-%define HAVE_YASM 1
+%define HAVE_X86ASM 1
%define HAVE_BIGENDIAN 0
%define HAVE_FAST_UNALIGNED 1
-%define HAVE_ALSA_ASOUNDLIB_H 0
%define HAVE_ALTIVEC_H 0
%define HAVE_ARPA_INET_H 0
%define HAVE_ASM_TYPES_H 0
%define HAVE_CDIO_PARANOIA_H 0
%define HAVE_CDIO_PARANOIA_PARANOIA_H 0
+%define HAVE_CUDA_H 0
+%define HAVE_D3D11_H 1
%define HAVE_DISPATCH_DISPATCH_H 0
%define HAVE_DEV_BKTR_IOCTL_BT848_H 0
%define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
@@ -196,7 +197,7 @@
%define HAVE_DIRECT_H 1
%define HAVE_DIRENT_H 0
%define HAVE_DLFCN_H 0
-%define HAVE_D3D11_H 1
+%define HAVE_DXGIDEBUG_H 1
%define HAVE_DXVA_H 1
%define HAVE_ES2_GL_H 0
%define HAVE_GSM_H 0
@@ -205,13 +206,15 @@
%define HAVE_MACHINE_IOCTL_BT848_H 0
%define HAVE_MACHINE_IOCTL_METEOR_H 0
%define HAVE_OPENCV2_CORE_CORE_C_H 0
+%define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+%define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
%define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
%define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
%define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
%define HAVE_OPENGL_GL3_H 0
%define HAVE_POLL_H 0
-%define HAVE_SNDIO_H 0
%define HAVE_SOUNDCARD_H 0
+%define HAVE_STDATOMIC_H 0
%define HAVE_SYS_MMAN_H 0
%define HAVE_SYS_PARAM_H 0
%define HAVE_SYS_RESOURCE_H 0
@@ -263,7 +266,6 @@
%define HAVE_COMMANDLINETOARGVW 1
%define HAVE_COTASKMEMFREE 1
%define HAVE_CRYPTGENRANDOM 1
-%define HAVE_DLOPEN 0
%define HAVE_FCNTL 0
%define HAVE_FLT_LIM 1
%define HAVE_FORK 0
@@ -283,7 +285,7 @@
%define HAVE_ISATTY 1
%define HAVE_JACK_PORT_GET_LATENCY_RANGE 0
%define HAVE_KBHIT 1
-%define HAVE_LOADLIBRARY 0
+%define HAVE_LOADLIBRARY 1
%define HAVE_LSTAT 0
%define HAVE_LZO1X_999_COMPRESS 0
%define HAVE_MACH_ABSOLUTE_TIME 0
@@ -311,11 +313,13 @@
%define HAVE_OS2THREADS 0
%define HAVE_W32THREADS 1
%define HAVE_AS_DN_DIRECTIVE 0
+%define HAVE_AS_FPU_DIRECTIVE 0
%define HAVE_AS_FUNC 0
%define HAVE_AS_OBJECT_ARCH 0
%define HAVE_ASM_MOD_Q 0
%define HAVE_ATTRIBUTE_MAY_ALIAS 0
%define HAVE_ATTRIBUTE_PACKED 0
+%define HAVE_BLOCKS_EXTENSION 0
%define HAVE_EBP_AVAILABLE 0
%define HAVE_EBX_AVAILABLE 0
%define HAVE_GNU_AS 0
@@ -332,12 +336,13 @@
%define HAVE_XFORM_ASM 0
%define HAVE_XMM_CLOBBERS 0
%define HAVE_CONDITION_VARIABLE_PTR 1
+%define HAVE_KCMVIDEOCODECTYPE_HEVC 0
%define HAVE_SOCKLEN_T 1
%define HAVE_STRUCT_ADDRINFO 1
%define HAVE_STRUCT_GROUP_SOURCE_REQ 1
%define HAVE_STRUCT_IP_MREQ_SOURCE 1
%define HAVE_STRUCT_IPV6_MREQ 1
-%define HAVE_STRUCT_MSGHDR_MSG_FLAGS 1
+%define HAVE_STRUCT_MSGHDR_MSG_FLAGS 0
%define HAVE_STRUCT_POLLFD 0
%define HAVE_STRUCT_RUSAGE_RU_MAXRSS 0
%define HAVE_STRUCT_SCTP_EVENT_SUBSCRIBE 0
@@ -348,36 +353,20 @@
%define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 0
%define HAVE_ATOMICS_NATIVE 1
%define HAVE_DOS_PATHS 1
-%define HAVE_DXVA2_LIB 0
-%define HAVE_DXVA2API_COBJ 1
%define HAVE_LIBC_MSVCRT 1
-%define HAVE_LIBDC1394_1 0
-%define HAVE_LIBDC1394_2 0
%define HAVE_MAKEINFO 1
%define HAVE_MAKEINFO_HTML 0
%define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
%define HAVE_PERL 1
%define HAVE_POD2MAN 1
-%define HAVE_SDL2 0
%define HAVE_SECTION_DATA_REL_RO 0
%define HAVE_TEXI2HTML 0
%define HAVE_THREADS 1
+%define HAVE_UWP 0
%define HAVE_VAAPI_DRM 0
%define HAVE_VAAPI_X11 0
%define HAVE_VDPAU_X11 0
%define HAVE_WINRT 0
-%define HAVE_XLIB 0
-%define CONFIG_BSFS 0
-%define CONFIG_DECODERS 1
-%define CONFIG_ENCODERS 0
-%define CONFIG_HWACCELS 0
-%define CONFIG_PARSERS 1
-%define CONFIG_INDEVS 0
-%define CONFIG_OUTDEVS 0
-%define CONFIG_FILTERS 0
-%define CONFIG_DEMUXERS 0
-%define CONFIG_MUXERS 0
-%define CONFIG_PROTOCOLS 0
%define CONFIG_DOC 0
%define CONFIG_HTMLPAGES 0
%define CONFIG_MANPAGES 1
@@ -385,13 +374,17 @@
%define CONFIG_TXTPAGES 1
%define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
%define CONFIG_AVIO_READING_EXAMPLE 1
-%define CONFIG_DECODING_ENCODING_EXAMPLE 0
+%define CONFIG_DECODE_AUDIO_EXAMPLE 1
+%define CONFIG_DECODE_VIDEO_EXAMPLE 1
%define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+%define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+%define CONFIG_ENCODE_VIDEO_EXAMPLE 1
%define CONFIG_EXTRACT_MVS_EXAMPLE 0
%define CONFIG_FILTER_AUDIO_EXAMPLE 0
%define CONFIG_FILTERING_AUDIO_EXAMPLE 0
%define CONFIG_FILTERING_VIDEO_EXAMPLE 0
%define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+%define CONFIG_HW_DECODE_EXAMPLE 0
%define CONFIG_METADATA_EXAMPLE 0
%define CONFIG_MUXING_EXAMPLE 0
%define CONFIG_QSVDEC_EXAMPLE 0
@@ -400,27 +393,55 @@
%define CONFIG_SCALING_VIDEO_EXAMPLE 0
%define CONFIG_TRANSCODE_AAC_EXAMPLE 0
%define CONFIG_TRANSCODING_EXAMPLE 0
-%define CONFIG_AVISYNTH 0
+%define CONFIG_ALSA 0
+%define CONFIG_APPKIT 0
+%define CONFIG_AVFOUNDATION 0
%define CONFIG_BZLIB 0
-%define CONFIG_CHROMAPRINT 0
-%define CONFIG_CRYSTALHD 0
-%define CONFIG_DECKLINK 0
+%define CONFIG_COREIMAGE 0
+%define CONFIG_ICONV 0
+%define CONFIG_JACK 0
+%define CONFIG_LIBXCB 0
+%define CONFIG_LIBXCB_SHM 0
+%define CONFIG_LIBXCB_SHAPE 0
+%define CONFIG_LIBXCB_XFIXES 0
+%define CONFIG_LZMA 0
+%define CONFIG_SCHANNEL 1
+%define CONFIG_SDL2 0
+%define CONFIG_SECURETRANSPORT 0
+%define CONFIG_SNDIO 0
+%define CONFIG_XLIB 1
+%define CONFIG_ZLIB 0
+%define CONFIG_AVISYNTH 0
%define CONFIG_FREI0R 0
-%define CONFIG_GCRYPT 0
+%define CONFIG_LIBCDIO 0
+%define CONFIG_LIBRUBBERBAND 0
+%define CONFIG_LIBVIDSTAB 0
+%define CONFIG_LIBX264 0
+%define CONFIG_LIBX265 0
+%define CONFIG_LIBXAVS 0
+%define CONFIG_LIBXVID 0
+%define CONFIG_DECKLINK 0
+%define CONFIG_LIBNDI_NEWTEK 0
+%define CONFIG_LIBFDK_AAC 0
+%define CONFIG_OPENSSL 0
%define CONFIG_GMP 0
+%define CONFIG_LIBOPENCORE_AMRNB 0
+%define CONFIG_LIBOPENCORE_AMRWB 0
+%define CONFIG_LIBVO_AMRWBENC 0
+%define CONFIG_RKMPP 0
+%define CONFIG_LIBSMBCLIENT 0
+%define CONFIG_CHROMAPRINT 0
+%define CONFIG_GCRYPT 0
%define CONFIG_GNUTLS 0
-%define CONFIG_ICONV 0
%define CONFIG_JNI 0
%define CONFIG_LADSPA 0
%define CONFIG_LIBASS 0
%define CONFIG_LIBBLURAY 0
%define CONFIG_LIBBS2B 0
%define CONFIG_LIBCACA 0
-%define CONFIG_LIBCDIO 0
%define CONFIG_LIBCELT 0
%define CONFIG_LIBDC1394 0
-%define CONFIG_LIBEBUR128 0
-%define CONFIG_LIBFDK_AAC 0
+%define CONFIG_LIBDRM 0
%define CONFIG_LIBFLITE 0
%define CONFIG_LIBFONTCONFIG 0
%define CONFIG_LIBFREETYPE 0
@@ -432,18 +453,15 @@
%define CONFIG_LIBKVAZAAR 0
%define CONFIG_LIBMODPLUG 0
%define CONFIG_LIBMP3LAME 0
-%define CONFIG_LIBNUT 0
-%define CONFIG_LIBOPENCORE_AMRNB 0
-%define CONFIG_LIBOPENCORE_AMRWB 0
+%define CONFIG_LIBMYSOFA 0
%define CONFIG_LIBOPENCV 0
%define CONFIG_LIBOPENH264 0
%define CONFIG_LIBOPENJPEG 0
%define CONFIG_LIBOPENMPT 0
%define CONFIG_LIBOPUS 0
%define CONFIG_LIBPULSE 0
+%define CONFIG_LIBRSVG 0
%define CONFIG_LIBRTMP 0
-%define CONFIG_LIBRUBBERBAND 0
-%define CONFIG_LIBSCHROEDINGER 0
%define CONFIG_LIBSHINE 0
%define CONFIG_LIBSMBCLIENT 0
%define CONFIG_LIBSNAPPY 0
@@ -454,53 +472,37 @@
%define CONFIG_LIBTHEORA 0
%define CONFIG_LIBTWOLAME 0
%define CONFIG_LIBV4L2 0
-%define CONFIG_LIBVIDSTAB 0
-%define CONFIG_LIBVO_AMRWBENC 0
+%define CONFIG_LIBVMAF 0
%define CONFIG_LIBVORBIS 0
%define CONFIG_LIBVPX 0
%define CONFIG_LIBWAVPACK 0
%define CONFIG_LIBWEBP 0
-%define CONFIG_LIBX264 0
-%define CONFIG_LIBX265 0
-%define CONFIG_LIBXAVS 0
-%define CONFIG_LIBXCB 0
-%define CONFIG_LIBXCB_SHM 0
-%define CONFIG_LIBXCB_SHAPE 0
-%define CONFIG_LIBXCB_XFIXES 0
-%define CONFIG_LIBXVID 0
+%define CONFIG_LIBXML2 0
%define CONFIG_LIBZIMG 0
%define CONFIG_LIBZMQ 0
%define CONFIG_LIBZVBI 0
-%define CONFIG_LZMA 0
%define CONFIG_MEDIACODEC 0
-%define CONFIG_NETCDF 0
%define CONFIG_OPENAL 0
%define CONFIG_OPENCL 0
%define CONFIG_OPENGL 0
-%define CONFIG_OPENSSL 0
-%define CONFIG_SCHANNEL 1
-%define CONFIG_SDL 0
-%define CONFIG_SDL2 0
-%define CONFIG_SECURETRANSPORT 0
-%define CONFIG_VIDEOTOOLBOX 0
-%define CONFIG_X11GRAB 0
-%define CONFIG_XLIB 0
-%define CONFIG_ZLIB 0
%define CONFIG_AUDIOTOOLBOX 0
-%define CONFIG_CUDA 0
-%define CONFIG_CUVID 0
+%define CONFIG_CRYSTALHD 0
+%define CONFIG_CUDA 1
+%define CONFIG_CUVID 1
%define CONFIG_D3D11VA 0
%define CONFIG_DXVA2 0
-%define CONFIG_LIBMFX 0
-%define CONFIG_LIBNPP 0
-%define CONFIG_MMAL 0
-%define CONFIG_NVENC 0
-%define CONFIG_OMX 0
+%define CONFIG_NVENC 1
%define CONFIG_VAAPI 0
%define CONFIG_VDA 0
%define CONFIG_VDPAU 0
-%define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_VIDEOTOOLBOX 0
+%define CONFIG_V4L2_M2M 0
%define CONFIG_XVMC 0
+%define CONFIG_CUDA_SDK 0
+%define CONFIG_LIBNPP 0
+%define CONFIG_LIBMFX 0
+%define CONFIG_MMAL 0
+%define CONFIG_OMX 0
%define CONFIG_FTRAPV 0
%define CONFIG_GRAY 0
%define CONFIG_HARDCODED_TABLES 0
@@ -539,16 +541,27 @@
%define CONFIG_PIXELUTILS 0
%define CONFIG_NETWORK 0
%define CONFIG_RDFT 0
+%define CONFIG_AUTODETECT 0
%define CONFIG_FONTCONFIG 0
-%define CONFIG_MEMALIGN_HACK 0
+%define CONFIG_LINUX_PERF 0
%define CONFIG_MEMORY_POISONING 0
%define CONFIG_NEON_CLOBBER_TEST 0
+%define CONFIG_OSSFUZZ 0
%define CONFIG_PIC 1
-%define CONFIG_POD2MAN 1
-%define CONFIG_RAISE_MAJOR 0
%define CONFIG_THUMB 0
%define CONFIG_VALGRIND_BACKTRACE 0
%define CONFIG_XMM_CLOBBER_TEST 0
+%define CONFIG_BSFS 1
+%define CONFIG_DECODERS 1
+%define CONFIG_ENCODERS 0
+%define CONFIG_HWACCELS 0
+%define CONFIG_PARSERS 1
+%define CONFIG_INDEVS 0
+%define CONFIG_OUTDEVS 0
+%define CONFIG_FILTERS 0
+%define CONFIG_DEMUXERS 0
+%define CONFIG_MUXERS 0
+%define CONFIG_PROTOCOLS 0
%define CONFIG_AANDCTTABLES 0
%define CONFIG_AC3DSP 0
%define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -566,20 +579,22 @@
%define CONFIG_FMTCONVERT 0
%define CONFIG_FRAME_THREAD_ENCODER 0
%define CONFIG_G722DSP 0
-%define CONFIG_GOLOMB 1
+%define CONFIG_GOLOMB 0
%define CONFIG_GPLV3 0
%define CONFIG_H263DSP 0
%define CONFIG_H264CHROMA 0
%define CONFIG_H264DSP 0
+%define CONFIG_H264PARSE 0
%define CONFIG_H264PRED 1
%define CONFIG_H264QPEL 0
+%define CONFIG_HEVCPARSE 0
%define CONFIG_HPELDSP 0
%define CONFIG_HUFFMAN 0
%define CONFIG_HUFFYUVDSP 0
%define CONFIG_HUFFYUVENCDSP 0
%define CONFIG_IDCTDSP 0
%define CONFIG_IIRFILTER 0
-%define CONFIG_IMDCT15 0
+%define CONFIG_MDCT15 0
%define CONFIG_INTRAX8 0
%define CONFIG_ISO_MEDIA 0
%define CONFIG_IVIDSP 0
@@ -588,12 +603,14 @@
%define CONFIG_LIBX262 0
%define CONFIG_LLAUDDSP 0
%define CONFIG_LLVIDDSP 0
+%define CONFIG_LLVIDENCDSP 0
%define CONFIG_LPC 0
%define CONFIG_LZF 0
%define CONFIG_ME_CMP 0
%define CONFIG_MPEG_ER 0
%define CONFIG_MPEGAUDIO 0
%define CONFIG_MPEGAUDIODSP 0
+%define CONFIG_MPEGAUDIOHEADER 0
%define CONFIG_MPEGVIDEO 0
%define CONFIG_MPEGVIDEOENC 0
%define CONFIG_MSS34DSP 0
@@ -615,1594 +632,19 @@
%define CONFIG_TEXTUREDSP 0
%define CONFIG_TEXTUREDSPENC 0
%define CONFIG_TPELDSP 0
+%define CONFIG_VAAPI_1 0
%define CONFIG_VAAPI_ENCODE 0
%define CONFIG_VC1DSP 0
%define CONFIG_VIDEODSP 1
%define CONFIG_VP3DSP 0
%define CONFIG_VP56DSP 0
%define CONFIG_VP8DSP 1
-%define CONFIG_VT_BT2020 0
%define CONFIG_WMA_FREQS 0
%define CONFIG_WMV2DSP 0
-%define CONFIG_AAC_ADTSTOASC_BSF 0
-%define CONFIG_CHOMP_BSF 0
-%define CONFIG_DUMP_EXTRADATA_BSF 0
-%define CONFIG_DCA_CORE_BSF 0
-%define CONFIG_H264_MP4TOANNEXB_BSF 0
-%define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-%define CONFIG_IMX_DUMP_HEADER_BSF 0
-%define CONFIG_MJPEG2JPEG_BSF 0
-%define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-%define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-%define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-%define CONFIG_MOV2TEXTSUB_BSF 0
-%define CONFIG_NOISE_BSF 0
-%define CONFIG_REMOVE_EXTRADATA_BSF 0
-%define CONFIG_TEXT2MOVSUB_BSF 0
-%define CONFIG_VP9_SUPERFRAME_BSF 0
-%define CONFIG_AASC_DECODER 0
-%define CONFIG_AIC_DECODER 0
-%define CONFIG_ALIAS_PIX_DECODER 0
-%define CONFIG_AMV_DECODER 0
-%define CONFIG_ANM_DECODER 0
-%define CONFIG_ANSI_DECODER 0
-%define CONFIG_APNG_DECODER 0
-%define CONFIG_ASV1_DECODER 0
-%define CONFIG_ASV2_DECODER 0
-%define CONFIG_AURA_DECODER 0
-%define CONFIG_AURA2_DECODER 0
-%define CONFIG_AVRP_DECODER 0
-%define CONFIG_AVRN_DECODER 0
-%define CONFIG_AVS_DECODER 0
-%define CONFIG_AVUI_DECODER 0
-%define CONFIG_AYUV_DECODER 0
-%define CONFIG_BETHSOFTVID_DECODER 0
-%define CONFIG_BFI_DECODER 0
-%define CONFIG_BINK_DECODER 0
-%define CONFIG_BMP_DECODER 0
-%define CONFIG_BMV_VIDEO_DECODER 0
-%define CONFIG_BRENDER_PIX_DECODER 0
-%define CONFIG_C93_DECODER 0
-%define CONFIG_CAVS_DECODER 0
-%define CONFIG_CDGRAPHICS_DECODER 0
-%define CONFIG_CDXL_DECODER 0
-%define CONFIG_CFHD_DECODER 0
-%define CONFIG_CINEPAK_DECODER 0
-%define CONFIG_CLJR_DECODER 0
-%define CONFIG_CLLC_DECODER 0
-%define CONFIG_COMFORTNOISE_DECODER 0
-%define CONFIG_CPIA_DECODER 0
-%define CONFIG_CSCD_DECODER 0
-%define CONFIG_CYUV_DECODER 0
-%define CONFIG_DDS_DECODER 0
-%define CONFIG_DFA_DECODER 0
-%define CONFIG_DIRAC_DECODER 0
-%define CONFIG_DNXHD_DECODER 0
-%define CONFIG_DPX_DECODER 0
-%define CONFIG_DSICINVIDEO_DECODER 0
-%define CONFIG_DVAUDIO_DECODER 0
-%define CONFIG_DVVIDEO_DECODER 0
-%define CONFIG_DXA_DECODER 0
-%define CONFIG_DXTORY_DECODER 0
-%define CONFIG_DXV_DECODER 0
-%define CONFIG_EACMV_DECODER 0
-%define CONFIG_EAMAD_DECODER 0
-%define CONFIG_EATGQ_DECODER 0
-%define CONFIG_EATGV_DECODER 0
-%define CONFIG_EATQI_DECODER 0
-%define CONFIG_EIGHTBPS_DECODER 0
-%define CONFIG_EIGHTSVX_EXP_DECODER 0
-%define CONFIG_EIGHTSVX_FIB_DECODER 0
-%define CONFIG_ESCAPE124_DECODER 0
-%define CONFIG_ESCAPE130_DECODER 0
-%define CONFIG_EXR_DECODER 0
-%define CONFIG_FFV1_DECODER 0
-%define CONFIG_FFVHUFF_DECODER 0
-%define CONFIG_FIC_DECODER 0
-%define CONFIG_FLASHSV_DECODER 0
-%define CONFIG_FLASHSV2_DECODER 0
-%define CONFIG_FLIC_DECODER 0
-%define CONFIG_FLV_DECODER 0
-%define CONFIG_FOURXM_DECODER 0
-%define CONFIG_FRAPS_DECODER 0
-%define CONFIG_FRWU_DECODER 0
-%define CONFIG_G2M_DECODER 0
-%define CONFIG_GIF_DECODER 0
-%define CONFIG_H261_DECODER 0
-%define CONFIG_H263_DECODER 0
-%define CONFIG_H263I_DECODER 0
-%define CONFIG_H263P_DECODER 0
-%define CONFIG_H264_DECODER 0
-%define CONFIG_H264_CRYSTALHD_DECODER 0
-%define CONFIG_H264_MEDIACODEC_DECODER 0
-%define CONFIG_H264_MMAL_DECODER 0
-%define CONFIG_H264_QSV_DECODER 0
-%define CONFIG_H264_VDA_DECODER 0
-%define CONFIG_H264_VDPAU_DECODER 0
-%define CONFIG_HAP_DECODER 0
-%define CONFIG_HEVC_DECODER 0
-%define CONFIG_HEVC_QSV_DECODER 0
-%define CONFIG_HNM4_VIDEO_DECODER 0
-%define CONFIG_HQ_HQA_DECODER 0
-%define CONFIG_HQX_DECODER 0
-%define CONFIG_HUFFYUV_DECODER 0
-%define CONFIG_IDCIN_DECODER 0
-%define CONFIG_IFF_ILBM_DECODER 0
-%define CONFIG_INDEO2_DECODER 0
-%define CONFIG_INDEO3_DECODER 0
-%define CONFIG_INDEO4_DECODER 0
-%define CONFIG_INDEO5_DECODER 0
-%define CONFIG_INTERPLAY_VIDEO_DECODER 0
-%define CONFIG_JPEG2000_DECODER 0
-%define CONFIG_JPEGLS_DECODER 0
-%define CONFIG_JV_DECODER 0
-%define CONFIG_KGV1_DECODER 0
-%define CONFIG_KMVC_DECODER 0
-%define CONFIG_LAGARITH_DECODER 0
-%define CONFIG_LOCO_DECODER 0
-%define CONFIG_M101_DECODER 0
-%define CONFIG_MAGICYUV_DECODER 0
-%define CONFIG_MDEC_DECODER 0
-%define CONFIG_MIMIC_DECODER 0
-%define CONFIG_MJPEG_DECODER 0
-%define CONFIG_MJPEGB_DECODER 0
-%define CONFIG_MMVIDEO_DECODER 0
-%define CONFIG_MOTIONPIXELS_DECODER 0
-%define CONFIG_MPEG_XVMC_DECODER 0
-%define CONFIG_MPEG1VIDEO_DECODER 0
-%define CONFIG_MPEG2VIDEO_DECODER 0
-%define CONFIG_MPEG4_DECODER 0
-%define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-%define CONFIG_MPEG4_MMAL_DECODER 0
-%define CONFIG_MPEG4_VDPAU_DECODER 0
-%define CONFIG_MPEGVIDEO_DECODER 0
-%define CONFIG_MPEG_VDPAU_DECODER 0
-%define CONFIG_MPEG1_VDPAU_DECODER 0
-%define CONFIG_MPEG2_MMAL_DECODER 0
-%define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-%define CONFIG_MPEG2_QSV_DECODER 0
-%define CONFIG_MSA1_DECODER 0
-%define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-%define CONFIG_MSMPEG4V1_DECODER 0
-%define CONFIG_MSMPEG4V2_DECODER 0
-%define CONFIG_MSMPEG4V3_DECODER 0
-%define CONFIG_MSRLE_DECODER 0
-%define CONFIG_MSS1_DECODER 0
-%define CONFIG_MSS2_DECODER 0
-%define CONFIG_MSVIDEO1_DECODER 0
-%define CONFIG_MSZH_DECODER 0
-%define CONFIG_MTS2_DECODER 0
-%define CONFIG_MVC1_DECODER 0
-%define CONFIG_MVC2_DECODER 0
-%define CONFIG_MXPEG_DECODER 0
-%define CONFIG_NUV_DECODER 0
-%define CONFIG_PAF_VIDEO_DECODER 0
-%define CONFIG_PAM_DECODER 0
-%define CONFIG_PBM_DECODER 0
-%define CONFIG_PCX_DECODER 0
-%define CONFIG_PGM_DECODER 0
-%define CONFIG_PGMYUV_DECODER 0
-%define CONFIG_PICTOR_DECODER 0
-%define CONFIG_PNG_DECODER 0
-%define CONFIG_PPM_DECODER 0
-%define CONFIG_PRORES_DECODER 0
-%define CONFIG_PRORES_LGPL_DECODER 0
-%define CONFIG_PTX_DECODER 0
-%define CONFIG_QDRAW_DECODER 0
-%define CONFIG_QPEG_DECODER 0
-%define CONFIG_QTRLE_DECODER 0
-%define CONFIG_R10K_DECODER 0
-%define CONFIG_R210_DECODER 0
-%define CONFIG_RAWVIDEO_DECODER 0
-%define CONFIG_RL2_DECODER 0
-%define CONFIG_ROQ_DECODER 0
-%define CONFIG_RPZA_DECODER 0
-%define CONFIG_RSCC_DECODER 0
-%define CONFIG_RV10_DECODER 0
-%define CONFIG_RV20_DECODER 0
-%define CONFIG_RV30_DECODER 0
-%define CONFIG_RV40_DECODER 0
-%define CONFIG_S302M_DECODER 0
-%define CONFIG_SANM_DECODER 0
-%define CONFIG_SCREENPRESSO_DECODER 0
-%define CONFIG_SDX2_DPCM_DECODER 0
-%define CONFIG_SGI_DECODER 0
-%define CONFIG_SGIRLE_DECODER 0
-%define CONFIG_SHEERVIDEO_DECODER 0
-%define CONFIG_SMACKER_DECODER 0
-%define CONFIG_SMC_DECODER 0
-%define CONFIG_SMVJPEG_DECODER 0
-%define CONFIG_SNOW_DECODER 0
-%define CONFIG_SP5X_DECODER 0
-%define CONFIG_SUNRAST_DECODER 0
-%define CONFIG_SVQ1_DECODER 0
-%define CONFIG_SVQ3_DECODER 0
-%define CONFIG_TARGA_DECODER 0
-%define CONFIG_TARGA_Y216_DECODER 0
-%define CONFIG_TDSC_DECODER 0
-%define CONFIG_THEORA_DECODER 0
-%define CONFIG_THP_DECODER 0
-%define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-%define CONFIG_TIFF_DECODER 0
-%define CONFIG_TMV_DECODER 0
-%define CONFIG_TRUEMOTION1_DECODER 0
-%define CONFIG_TRUEMOTION2_DECODER 0
-%define CONFIG_TRUEMOTION2RT_DECODER 0
-%define CONFIG_TSCC_DECODER 0
-%define CONFIG_TSCC2_DECODER 0
-%define CONFIG_TXD_DECODER 0
-%define CONFIG_ULTI_DECODER 0
-%define CONFIG_UTVIDEO_DECODER 0
-%define CONFIG_V210_DECODER 0
-%define CONFIG_V210X_DECODER 0
-%define CONFIG_V308_DECODER 0
-%define CONFIG_V408_DECODER 0
-%define CONFIG_V410_DECODER 0
-%define CONFIG_VB_DECODER 0
-%define CONFIG_VBLE_DECODER 0
-%define CONFIG_VC1_DECODER 0
-%define CONFIG_VC1_CRYSTALHD_DECODER 0
-%define CONFIG_VC1_VDPAU_DECODER 0
-%define CONFIG_VC1IMAGE_DECODER 0
-%define CONFIG_VC1_MMAL_DECODER 0
-%define CONFIG_VC1_QSV_DECODER 0
-%define CONFIG_VCR1_DECODER 0
-%define CONFIG_VMDVIDEO_DECODER 0
-%define CONFIG_VMNC_DECODER 0
-%define CONFIG_VP3_DECODER 0
-%define CONFIG_VP5_DECODER 0
-%define CONFIG_VP6_DECODER 0
-%define CONFIG_VP6A_DECODER 0
-%define CONFIG_VP6F_DECODER 0
-%define CONFIG_VP7_DECODER 0
+%define CONFIG_NULL_BSF 1
%define CONFIG_VP8_DECODER 1
%define CONFIG_VP9_DECODER 1
-%define CONFIG_VQA_DECODER 0
-%define CONFIG_WEBP_DECODER 0
-%define CONFIG_WMV1_DECODER 0
-%define CONFIG_WMV2_DECODER 0
-%define CONFIG_WMV3_DECODER 0
-%define CONFIG_WMV3_CRYSTALHD_DECODER 0
-%define CONFIG_WMV3_VDPAU_DECODER 0
-%define CONFIG_WMV3IMAGE_DECODER 0
-%define CONFIG_WNV1_DECODER 0
-%define CONFIG_XAN_WC3_DECODER 0
-%define CONFIG_XAN_WC4_DECODER 0
-%define CONFIG_XBM_DECODER 0
-%define CONFIG_XFACE_DECODER 0
-%define CONFIG_XL_DECODER 0
-%define CONFIG_XWD_DECODER 0
-%define CONFIG_Y41P_DECODER 0
-%define CONFIG_YLC_DECODER 0
-%define CONFIG_YOP_DECODER 0
-%define CONFIG_YUV4_DECODER 0
-%define CONFIG_ZERO12V_DECODER 0
-%define CONFIG_ZEROCODEC_DECODER 0
-%define CONFIG_ZLIB_DECODER 0
-%define CONFIG_ZMBV_DECODER 0
-%define CONFIG_AAC_DECODER 0
-%define CONFIG_AAC_FIXED_DECODER 0
-%define CONFIG_AAC_LATM_DECODER 0
-%define CONFIG_AC3_DECODER 0
-%define CONFIG_AC3_FIXED_DECODER 0
-%define CONFIG_ALAC_DECODER 0
-%define CONFIG_ALS_DECODER 0
-%define CONFIG_AMRNB_DECODER 0
-%define CONFIG_AMRWB_DECODER 0
-%define CONFIG_APE_DECODER 0
-%define CONFIG_ATRAC1_DECODER 0
-%define CONFIG_ATRAC3_DECODER 0
-%define CONFIG_ATRAC3P_DECODER 0
-%define CONFIG_BINKAUDIO_DCT_DECODER 0
-%define CONFIG_BINKAUDIO_RDFT_DECODER 0
-%define CONFIG_BMV_AUDIO_DECODER 0
-%define CONFIG_COOK_DECODER 0
-%define CONFIG_DCA_DECODER 0
-%define CONFIG_DSD_LSBF_DECODER 0
-%define CONFIG_DSD_MSBF_DECODER 0
-%define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-%define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-%define CONFIG_DSICINAUDIO_DECODER 0
-%define CONFIG_DSS_SP_DECODER 0
-%define CONFIG_DST_DECODER 0
-%define CONFIG_EAC3_DECODER 0
-%define CONFIG_EVRC_DECODER 0
-%define CONFIG_FFWAVESYNTH_DECODER 0
%define CONFIG_FLAC_DECODER 1
-%define CONFIG_G723_1_DECODER 0
-%define CONFIG_G729_DECODER 0
-%define CONFIG_GSM_DECODER 0
-%define CONFIG_GSM_MS_DECODER 0
-%define CONFIG_IAC_DECODER 0
-%define CONFIG_IMC_DECODER 0
-%define CONFIG_INTERPLAY_ACM_DECODER 0
-%define CONFIG_MACE3_DECODER 0
-%define CONFIG_MACE6_DECODER 0
-%define CONFIG_METASOUND_DECODER 0
-%define CONFIG_MLP_DECODER 0
-%define CONFIG_MP1_DECODER 0
-%define CONFIG_MP1FLOAT_DECODER 0
-%define CONFIG_MP2_DECODER 0
-%define CONFIG_MP2FLOAT_DECODER 0
-%define CONFIG_MP3_DECODER 0
-%define CONFIG_MP3FLOAT_DECODER 0
-%define CONFIG_MP3ADU_DECODER 0
-%define CONFIG_MP3ADUFLOAT_DECODER 0
-%define CONFIG_MP3ON4_DECODER 0
-%define CONFIG_MP3ON4FLOAT_DECODER 0
-%define CONFIG_MPC7_DECODER 0
-%define CONFIG_MPC8_DECODER 0
-%define CONFIG_NELLYMOSER_DECODER 0
-%define CONFIG_ON2AVC_DECODER 0
-%define CONFIG_OPUS_DECODER 0
-%define CONFIG_PAF_AUDIO_DECODER 0
-%define CONFIG_QCELP_DECODER 0
-%define CONFIG_QDM2_DECODER 0
-%define CONFIG_RA_144_DECODER 0
-%define CONFIG_RA_288_DECODER 0
-%define CONFIG_RALF_DECODER 0
-%define CONFIG_SHORTEN_DECODER 0
-%define CONFIG_SIPR_DECODER 0
-%define CONFIG_SMACKAUD_DECODER 0
-%define CONFIG_SONIC_DECODER 0
-%define CONFIG_TAK_DECODER 0
-%define CONFIG_TRUEHD_DECODER 0
-%define CONFIG_TRUESPEECH_DECODER 0
-%define CONFIG_TTA_DECODER 0
-%define CONFIG_TWINVQ_DECODER 0
-%define CONFIG_VMDAUDIO_DECODER 0
-%define CONFIG_VORBIS_DECODER 0
-%define CONFIG_WAVPACK_DECODER 0
-%define CONFIG_WMALOSSLESS_DECODER 0
-%define CONFIG_WMAPRO_DECODER 0
-%define CONFIG_WMAV1_DECODER 0
-%define CONFIG_WMAV2_DECODER 0
-%define CONFIG_WMAVOICE_DECODER 0
-%define CONFIG_WS_SND1_DECODER 0
-%define CONFIG_XMA1_DECODER 0
-%define CONFIG_XMA2_DECODER 0
-%define CONFIG_PCM_ALAW_DECODER 0
-%define CONFIG_PCM_BLURAY_DECODER 0
-%define CONFIG_PCM_DVD_DECODER 0
-%define CONFIG_PCM_F32BE_DECODER 0
-%define CONFIG_PCM_F32LE_DECODER 0
-%define CONFIG_PCM_F64BE_DECODER 0
-%define CONFIG_PCM_F64LE_DECODER 0
-%define CONFIG_PCM_LXF_DECODER 0
-%define CONFIG_PCM_MULAW_DECODER 0
-%define CONFIG_PCM_S8_DECODER 0
-%define CONFIG_PCM_S8_PLANAR_DECODER 0
-%define CONFIG_PCM_S16BE_DECODER 0
-%define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-%define CONFIG_PCM_S16LE_DECODER 0
-%define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S24BE_DECODER 0
-%define CONFIG_PCM_S24DAUD_DECODER 0
-%define CONFIG_PCM_S24LE_DECODER 0
-%define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S32BE_DECODER 0
-%define CONFIG_PCM_S32LE_DECODER 0
-%define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-%define CONFIG_PCM_S64BE_DECODER 0
-%define CONFIG_PCM_S64LE_DECODER 0
-%define CONFIG_PCM_U8_DECODER 0
-%define CONFIG_PCM_U16BE_DECODER 0
-%define CONFIG_PCM_U16LE_DECODER 0
-%define CONFIG_PCM_U24BE_DECODER 0
-%define CONFIG_PCM_U24LE_DECODER 0
-%define CONFIG_PCM_U32BE_DECODER 0
-%define CONFIG_PCM_U32LE_DECODER 0
-%define CONFIG_PCM_ZORK_DECODER 0
-%define CONFIG_INTERPLAY_DPCM_DECODER 0
-%define CONFIG_ROQ_DPCM_DECODER 0
-%define CONFIG_SOL_DPCM_DECODER 0
-%define CONFIG_XAN_DPCM_DECODER 0
-%define CONFIG_ADPCM_4XM_DECODER 0
-%define CONFIG_ADPCM_ADX_DECODER 0
-%define CONFIG_ADPCM_AFC_DECODER 0
-%define CONFIG_ADPCM_AICA_DECODER 0
-%define CONFIG_ADPCM_CT_DECODER 0
-%define CONFIG_ADPCM_DTK_DECODER 0
-%define CONFIG_ADPCM_EA_DECODER 0
-%define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-%define CONFIG_ADPCM_EA_R1_DECODER 0
-%define CONFIG_ADPCM_EA_R2_DECODER 0
-%define CONFIG_ADPCM_EA_R3_DECODER 0
-%define CONFIG_ADPCM_EA_XAS_DECODER 0
-%define CONFIG_ADPCM_G722_DECODER 0
-%define CONFIG_ADPCM_G726_DECODER 0
-%define CONFIG_ADPCM_G726LE_DECODER 0
-%define CONFIG_ADPCM_IMA_AMV_DECODER 0
-%define CONFIG_ADPCM_IMA_APC_DECODER 0
-%define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-%define CONFIG_ADPCM_IMA_DK3_DECODER 0
-%define CONFIG_ADPCM_IMA_DK4_DECODER 0
-%define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-%define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-%define CONFIG_ADPCM_IMA_ISS_DECODER 0
-%define CONFIG_ADPCM_IMA_OKI_DECODER 0
-%define CONFIG_ADPCM_IMA_QT_DECODER 0
-%define CONFIG_ADPCM_IMA_RAD_DECODER 0
-%define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-%define CONFIG_ADPCM_IMA_WAV_DECODER 0
-%define CONFIG_ADPCM_IMA_WS_DECODER 0
-%define CONFIG_ADPCM_MS_DECODER 0
-%define CONFIG_ADPCM_MTAF_DECODER 0
-%define CONFIG_ADPCM_PSX_DECODER 0
-%define CONFIG_ADPCM_SBPRO_2_DECODER 0
-%define CONFIG_ADPCM_SBPRO_3_DECODER 0
-%define CONFIG_ADPCM_SBPRO_4_DECODER 0
-%define CONFIG_ADPCM_SWF_DECODER 0
-%define CONFIG_ADPCM_THP_DECODER 0
-%define CONFIG_ADPCM_THP_LE_DECODER 0
-%define CONFIG_ADPCM_VIMA_DECODER 0
-%define CONFIG_ADPCM_XA_DECODER 0
-%define CONFIG_ADPCM_YAMAHA_DECODER 0
-%define CONFIG_SSA_DECODER 0
-%define CONFIG_ASS_DECODER 0
-%define CONFIG_CCAPTION_DECODER 0
-%define CONFIG_DVBSUB_DECODER 0
-%define CONFIG_DVDSUB_DECODER 0
-%define CONFIG_JACOSUB_DECODER 0
-%define CONFIG_MICRODVD_DECODER 0
-%define CONFIG_MOVTEXT_DECODER 0
-%define CONFIG_MPL2_DECODER 0
-%define CONFIG_PGSSUB_DECODER 0
-%define CONFIG_PJS_DECODER 0
-%define CONFIG_REALTEXT_DECODER 0
-%define CONFIG_SAMI_DECODER 0
-%define CONFIG_SRT_DECODER 0
-%define CONFIG_STL_DECODER 0
-%define CONFIG_SUBRIP_DECODER 0
-%define CONFIG_SUBVIEWER_DECODER 0
-%define CONFIG_SUBVIEWER1_DECODER 0
-%define CONFIG_TEXT_DECODER 0
-%define CONFIG_VPLAYER_DECODER 0
-%define CONFIG_WEBVTT_DECODER 0
-%define CONFIG_XSUB_DECODER 0
-%define CONFIG_AAC_AT_DECODER 0
-%define CONFIG_AC3_AT_DECODER 0
-%define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-%define CONFIG_ALAC_AT_DECODER 0
-%define CONFIG_AMR_NB_AT_DECODER 0
-%define CONFIG_EAC3_AT_DECODER 0
-%define CONFIG_GSM_MS_AT_DECODER 0
-%define CONFIG_ILBC_AT_DECODER 0
-%define CONFIG_MP1_AT_DECODER 0
-%define CONFIG_MP2_AT_DECODER 0
-%define CONFIG_MP3_AT_DECODER 0
-%define CONFIG_PCM_ALAW_AT_DECODER 0
-%define CONFIG_PCM_MULAW_AT_DECODER 0
-%define CONFIG_QDMC_AT_DECODER 0
-%define CONFIG_QDM2_AT_DECODER 0
-%define CONFIG_LIBCELT_DECODER 0
-%define CONFIG_LIBFDK_AAC_DECODER 0
-%define CONFIG_LIBGSM_DECODER 0
-%define CONFIG_LIBGSM_MS_DECODER 0
-%define CONFIG_LIBILBC_DECODER 0
-%define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-%define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-%define CONFIG_LIBOPENJPEG_DECODER 0
-%define CONFIG_LIBOPUS_DECODER 0
-%define CONFIG_LIBSCHROEDINGER_DECODER 0
-%define CONFIG_LIBSPEEX_DECODER 0
-%define CONFIG_LIBVORBIS_DECODER 0
-%define CONFIG_LIBVPX_VP8_DECODER 0
-%define CONFIG_LIBVPX_VP9_DECODER 0
-%define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-%define CONFIG_BINTEXT_DECODER 0
-%define CONFIG_XBIN_DECODER 0
-%define CONFIG_IDF_DECODER 0
-%define CONFIG_LIBOPENH264_DECODER 0
-%define CONFIG_H263_CUVID_DECODER 0
-%define CONFIG_H264_CUVID_DECODER 0
-%define CONFIG_HEVC_CUVID_DECODER 0
-%define CONFIG_HEVC_MEDIACODEC_DECODER 0
-%define CONFIG_MJPEG_CUVID_DECODER 0
-%define CONFIG_MPEG1_CUVID_DECODER 0
-%define CONFIG_MPEG2_CUVID_DECODER 0
-%define CONFIG_MPEG4_CUVID_DECODER 0
-%define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-%define CONFIG_VC1_CUVID_DECODER 0
-%define CONFIG_VP8_CUVID_DECODER 0
-%define CONFIG_VP8_MEDIACODEC_DECODER 0
-%define CONFIG_VP9_CUVID_DECODER 0
-%define CONFIG_VP9_MEDIACODEC_DECODER 0
-%define CONFIG_AA_DEMUXER 0
-%define CONFIG_AAC_DEMUXER 0
-%define CONFIG_AC3_DEMUXER 0
-%define CONFIG_ACM_DEMUXER 0
-%define CONFIG_ACT_DEMUXER 0
-%define CONFIG_ADF_DEMUXER 0
-%define CONFIG_ADP_DEMUXER 0
-%define CONFIG_ADS_DEMUXER 0
-%define CONFIG_ADX_DEMUXER 0
-%define CONFIG_AEA_DEMUXER 0
-%define CONFIG_AFC_DEMUXER 0
-%define CONFIG_AIFF_DEMUXER 0
-%define CONFIG_AIX_DEMUXER 0
-%define CONFIG_AMR_DEMUXER 0
-%define CONFIG_ANM_DEMUXER 0
-%define CONFIG_APC_DEMUXER 0
-%define CONFIG_APE_DEMUXER 0
-%define CONFIG_APNG_DEMUXER 0
-%define CONFIG_AQTITLE_DEMUXER 0
-%define CONFIG_ASF_DEMUXER 0
-%define CONFIG_ASF_O_DEMUXER 0
-%define CONFIG_ASS_DEMUXER 0
-%define CONFIG_AST_DEMUXER 0
-%define CONFIG_AU_DEMUXER 0
-%define CONFIG_AVI_DEMUXER 0
-%define CONFIG_AVISYNTH_DEMUXER 0
-%define CONFIG_AVR_DEMUXER 0
-%define CONFIG_AVS_DEMUXER 0
-%define CONFIG_BETHSOFTVID_DEMUXER 0
-%define CONFIG_BFI_DEMUXER 0
-%define CONFIG_BINTEXT_DEMUXER 0
-%define CONFIG_BINK_DEMUXER 0
-%define CONFIG_BIT_DEMUXER 0
-%define CONFIG_BMV_DEMUXER 0
-%define CONFIG_BFSTM_DEMUXER 0
-%define CONFIG_BRSTM_DEMUXER 0
-%define CONFIG_BOA_DEMUXER 0
-%define CONFIG_C93_DEMUXER 0
-%define CONFIG_CAF_DEMUXER 0
-%define CONFIG_CAVSVIDEO_DEMUXER 0
-%define CONFIG_CDG_DEMUXER 0
-%define CONFIG_CDXL_DEMUXER 0
-%define CONFIG_CINE_DEMUXER 0
-%define CONFIG_CONCAT_DEMUXER 0
-%define CONFIG_DATA_DEMUXER 0
-%define CONFIG_DAUD_DEMUXER 0
-%define CONFIG_DCSTR_DEMUXER 0
-%define CONFIG_DFA_DEMUXER 0
-%define CONFIG_DIRAC_DEMUXER 0
-%define CONFIG_DNXHD_DEMUXER 0
-%define CONFIG_DSF_DEMUXER 0
-%define CONFIG_DSICIN_DEMUXER 0
-%define CONFIG_DSS_DEMUXER 0
-%define CONFIG_DTS_DEMUXER 0
-%define CONFIG_DTSHD_DEMUXER 0
-%define CONFIG_DV_DEMUXER 0
-%define CONFIG_DVBSUB_DEMUXER 0
-%define CONFIG_DVBTXT_DEMUXER 0
-%define CONFIG_DXA_DEMUXER 0
-%define CONFIG_EA_DEMUXER 0
-%define CONFIG_EA_CDATA_DEMUXER 0
-%define CONFIG_EAC3_DEMUXER 0
-%define CONFIG_EPAF_DEMUXER 0
-%define CONFIG_FFM_DEMUXER 0
-%define CONFIG_FFMETADATA_DEMUXER 0
-%define CONFIG_FILMSTRIP_DEMUXER 0
-%define CONFIG_FLAC_DEMUXER 0
-%define CONFIG_FLIC_DEMUXER 0
-%define CONFIG_FLV_DEMUXER 0
-%define CONFIG_LIVE_FLV_DEMUXER 0
-%define CONFIG_FOURXM_DEMUXER 0
-%define CONFIG_FRM_DEMUXER 0
-%define CONFIG_FSB_DEMUXER 0
-%define CONFIG_G722_DEMUXER 0
-%define CONFIG_G723_1_DEMUXER 0
-%define CONFIG_G729_DEMUXER 0
-%define CONFIG_GENH_DEMUXER 0
-%define CONFIG_GIF_DEMUXER 0
-%define CONFIG_GSM_DEMUXER 0
-%define CONFIG_GXF_DEMUXER 0
-%define CONFIG_H261_DEMUXER 0
-%define CONFIG_H263_DEMUXER 0
-%define CONFIG_H264_DEMUXER 0
-%define CONFIG_HEVC_DEMUXER 0
-%define CONFIG_HLS_DEMUXER 0
-%define CONFIG_HNM_DEMUXER 0
-%define CONFIG_ICO_DEMUXER 0
-%define CONFIG_IDCIN_DEMUXER 0
-%define CONFIG_IDF_DEMUXER 0
-%define CONFIG_IFF_DEMUXER 0
-%define CONFIG_ILBC_DEMUXER 0
-%define CONFIG_IMAGE2_DEMUXER 0
-%define CONFIG_IMAGE2PIPE_DEMUXER 0
-%define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-%define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-%define CONFIG_INGENIENT_DEMUXER 0
-%define CONFIG_IPMOVIE_DEMUXER 0
-%define CONFIG_IRCAM_DEMUXER 0
-%define CONFIG_ISS_DEMUXER 0
-%define CONFIG_IV8_DEMUXER 0
-%define CONFIG_IVF_DEMUXER 0
-%define CONFIG_IVR_DEMUXER 0
-%define CONFIG_JACOSUB_DEMUXER 0
-%define CONFIG_JV_DEMUXER 0
-%define CONFIG_LMLM4_DEMUXER 0
-%define CONFIG_LOAS_DEMUXER 0
-%define CONFIG_LRC_DEMUXER 0
-%define CONFIG_LVF_DEMUXER 0
-%define CONFIG_LXF_DEMUXER 0
-%define CONFIG_M4V_DEMUXER 0
-%define CONFIG_MATROSKA_DEMUXER 0
-%define CONFIG_MGSTS_DEMUXER 0
-%define CONFIG_MICRODVD_DEMUXER 0
-%define CONFIG_MJPEG_DEMUXER 0
-%define CONFIG_MLP_DEMUXER 0
-%define CONFIG_MLV_DEMUXER 0
-%define CONFIG_MM_DEMUXER 0
-%define CONFIG_MMF_DEMUXER 0
-%define CONFIG_MOV_DEMUXER 0
-%define CONFIG_MP3_DEMUXER 0
-%define CONFIG_MPC_DEMUXER 0
-%define CONFIG_MPC8_DEMUXER 0
-%define CONFIG_MPEGPS_DEMUXER 0
-%define CONFIG_MPEGTS_DEMUXER 0
-%define CONFIG_MPEGTSRAW_DEMUXER 0
-%define CONFIG_MPEGVIDEO_DEMUXER 0
-%define CONFIG_MPJPEG_DEMUXER 0
-%define CONFIG_MPL2_DEMUXER 0
-%define CONFIG_MPSUB_DEMUXER 0
-%define CONFIG_MSF_DEMUXER 0
-%define CONFIG_MSNWC_TCP_DEMUXER 0
-%define CONFIG_MTAF_DEMUXER 0
-%define CONFIG_MTV_DEMUXER 0
-%define CONFIG_MUSX_DEMUXER 0
-%define CONFIG_MV_DEMUXER 0
-%define CONFIG_MVI_DEMUXER 0
-%define CONFIG_MXF_DEMUXER 0
-%define CONFIG_MXG_DEMUXER 0
-%define CONFIG_NC_DEMUXER 0
-%define CONFIG_NISTSPHERE_DEMUXER 0
-%define CONFIG_NSV_DEMUXER 0
-%define CONFIG_NUT_DEMUXER 0
-%define CONFIG_NUV_DEMUXER 0
-%define CONFIG_OGG_DEMUXER 0
-%define CONFIG_OMA_DEMUXER 0
-%define CONFIG_PAF_DEMUXER 0
-%define CONFIG_PCM_ALAW_DEMUXER 0
-%define CONFIG_PCM_MULAW_DEMUXER 0
-%define CONFIG_PCM_F64BE_DEMUXER 0
-%define CONFIG_PCM_F64LE_DEMUXER 0
-%define CONFIG_PCM_F32BE_DEMUXER 0
-%define CONFIG_PCM_F32LE_DEMUXER 0
-%define CONFIG_PCM_S32BE_DEMUXER 0
-%define CONFIG_PCM_S32LE_DEMUXER 0
-%define CONFIG_PCM_S24BE_DEMUXER 0
-%define CONFIG_PCM_S24LE_DEMUXER 0
-%define CONFIG_PCM_S16BE_DEMUXER 0
-%define CONFIG_PCM_S16LE_DEMUXER 0
-%define CONFIG_PCM_S8_DEMUXER 0
-%define CONFIG_PCM_U32BE_DEMUXER 0
-%define CONFIG_PCM_U32LE_DEMUXER 0
-%define CONFIG_PCM_U24BE_DEMUXER 0
-%define CONFIG_PCM_U24LE_DEMUXER 0
-%define CONFIG_PCM_U16BE_DEMUXER 0
-%define CONFIG_PCM_U16LE_DEMUXER 0
-%define CONFIG_PCM_U8_DEMUXER 0
-%define CONFIG_PJS_DEMUXER 0
-%define CONFIG_PMP_DEMUXER 0
-%define CONFIG_PVA_DEMUXER 0
-%define CONFIG_PVF_DEMUXER 0
-%define CONFIG_QCP_DEMUXER 0
-%define CONFIG_R3D_DEMUXER 0
-%define CONFIG_RAWVIDEO_DEMUXER 0
-%define CONFIG_REALTEXT_DEMUXER 0
-%define CONFIG_REDSPARK_DEMUXER 0
-%define CONFIG_RL2_DEMUXER 0
-%define CONFIG_RM_DEMUXER 0
-%define CONFIG_ROQ_DEMUXER 0
-%define CONFIG_RPL_DEMUXER 0
-%define CONFIG_RSD_DEMUXER 0
-%define CONFIG_RSO_DEMUXER 0
-%define CONFIG_RTP_DEMUXER 0
-%define CONFIG_RTSP_DEMUXER 0
-%define CONFIG_SAMI_DEMUXER 0
-%define CONFIG_SAP_DEMUXER 0
-%define CONFIG_SBG_DEMUXER 0
-%define CONFIG_SDP_DEMUXER 0
-%define CONFIG_SDR2_DEMUXER 0
-%define CONFIG_SEGAFILM_DEMUXER 0
-%define CONFIG_SHORTEN_DEMUXER 0
-%define CONFIG_SIFF_DEMUXER 0
-%define CONFIG_SLN_DEMUXER 0
-%define CONFIG_SMACKER_DEMUXER 0
-%define CONFIG_SMJPEG_DEMUXER 0
-%define CONFIG_SMUSH_DEMUXER 0
-%define CONFIG_SOL_DEMUXER 0
-%define CONFIG_SOX_DEMUXER 0
-%define CONFIG_SPDIF_DEMUXER 0
-%define CONFIG_SRT_DEMUXER 0
-%define CONFIG_STR_DEMUXER 0
-%define CONFIG_STL_DEMUXER 0
-%define CONFIG_SUBVIEWER1_DEMUXER 0
-%define CONFIG_SUBVIEWER_DEMUXER 0
-%define CONFIG_SUP_DEMUXER 0
-%define CONFIG_SVAG_DEMUXER 0
-%define CONFIG_SWF_DEMUXER 0
-%define CONFIG_TAK_DEMUXER 0
-%define CONFIG_TEDCAPTIONS_DEMUXER 0
-%define CONFIG_THP_DEMUXER 0
-%define CONFIG_THREEDOSTR_DEMUXER 0
-%define CONFIG_TIERTEXSEQ_DEMUXER 0
-%define CONFIG_TMV_DEMUXER 0
-%define CONFIG_TRUEHD_DEMUXER 0
-%define CONFIG_TTA_DEMUXER 0
-%define CONFIG_TXD_DEMUXER 0
-%define CONFIG_TTY_DEMUXER 0
-%define CONFIG_V210_DEMUXER 0
-%define CONFIG_V210X_DEMUXER 0
-%define CONFIG_VAG_DEMUXER 0
-%define CONFIG_VC1_DEMUXER 0
-%define CONFIG_VC1T_DEMUXER 0
-%define CONFIG_VIVO_DEMUXER 0
-%define CONFIG_VMD_DEMUXER 0
-%define CONFIG_VOBSUB_DEMUXER 0
-%define CONFIG_VOC_DEMUXER 0
-%define CONFIG_VPK_DEMUXER 0
-%define CONFIG_VPLAYER_DEMUXER 0
-%define CONFIG_VQF_DEMUXER 0
-%define CONFIG_W64_DEMUXER 0
-%define CONFIG_WAV_DEMUXER 0
-%define CONFIG_WC3_DEMUXER 0
-%define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-%define CONFIG_WEBVTT_DEMUXER 0
-%define CONFIG_WSAUD_DEMUXER 0
-%define CONFIG_WSD_DEMUXER 0
-%define CONFIG_WSVQA_DEMUXER 0
-%define CONFIG_WTV_DEMUXER 0
-%define CONFIG_WVE_DEMUXER 0
-%define CONFIG_WV_DEMUXER 0
-%define CONFIG_XA_DEMUXER 0
-%define CONFIG_XBIN_DEMUXER 0
-%define CONFIG_XMV_DEMUXER 0
-%define CONFIG_XVAG_DEMUXER 0
-%define CONFIG_XWMA_DEMUXER 0
-%define CONFIG_YOP_DEMUXER 0
-%define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-%define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-%define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-%define CONFIG_LIBGME_DEMUXER 0
-%define CONFIG_LIBMODPLUG_DEMUXER 0
-%define CONFIG_LIBNUT_DEMUXER 0
-%define CONFIG_LIBOPENMPT_DEMUXER 0
-%define CONFIG_A64MULTI_ENCODER 0
-%define CONFIG_A64MULTI5_ENCODER 0
-%define CONFIG_ALIAS_PIX_ENCODER 0
-%define CONFIG_AMV_ENCODER 0
-%define CONFIG_APNG_ENCODER 0
-%define CONFIG_ASV1_ENCODER 0
-%define CONFIG_ASV2_ENCODER 0
-%define CONFIG_AVRP_ENCODER 0
-%define CONFIG_AVUI_ENCODER 0
-%define CONFIG_AYUV_ENCODER 0
-%define CONFIG_BMP_ENCODER 0
-%define CONFIG_CINEPAK_ENCODER 0
-%define CONFIG_CLJR_ENCODER 0
-%define CONFIG_COMFORTNOISE_ENCODER 0
-%define CONFIG_DNXHD_ENCODER 0
-%define CONFIG_DPX_ENCODER 0
-%define CONFIG_DVVIDEO_ENCODER 0
-%define CONFIG_FFV1_ENCODER 0
-%define CONFIG_FFVHUFF_ENCODER 0
-%define CONFIG_FLASHSV_ENCODER 0
-%define CONFIG_FLASHSV2_ENCODER 0
-%define CONFIG_FLV_ENCODER 0
-%define CONFIG_GIF_ENCODER 0
-%define CONFIG_H261_ENCODER 0
-%define CONFIG_H263_ENCODER 0
-%define CONFIG_H263P_ENCODER 0
-%define CONFIG_HAP_ENCODER 0
-%define CONFIG_HUFFYUV_ENCODER 0
-%define CONFIG_JPEG2000_ENCODER 0
-%define CONFIG_JPEGLS_ENCODER 0
-%define CONFIG_LJPEG_ENCODER 0
-%define CONFIG_MJPEG_ENCODER 0
-%define CONFIG_MPEG1VIDEO_ENCODER 0
-%define CONFIG_MPEG2VIDEO_ENCODER 0
-%define CONFIG_MPEG4_ENCODER 0
-%define CONFIG_MSMPEG4V2_ENCODER 0
-%define CONFIG_MSMPEG4V3_ENCODER 0
-%define CONFIG_MSVIDEO1_ENCODER 0
-%define CONFIG_PAM_ENCODER 0
-%define CONFIG_PBM_ENCODER 0
-%define CONFIG_PCX_ENCODER 0
-%define CONFIG_PGM_ENCODER 0
-%define CONFIG_PGMYUV_ENCODER 0
-%define CONFIG_PNG_ENCODER 0
-%define CONFIG_PPM_ENCODER 0
-%define CONFIG_PRORES_ENCODER 0
-%define CONFIG_PRORES_AW_ENCODER 0
-%define CONFIG_PRORES_KS_ENCODER 0
-%define CONFIG_QTRLE_ENCODER 0
-%define CONFIG_R10K_ENCODER 0
-%define CONFIG_R210_ENCODER 0
-%define CONFIG_RAWVIDEO_ENCODER 0
-%define CONFIG_ROQ_ENCODER 0
-%define CONFIG_RV10_ENCODER 0
-%define CONFIG_RV20_ENCODER 0
-%define CONFIG_S302M_ENCODER 0
-%define CONFIG_SGI_ENCODER 0
-%define CONFIG_SNOW_ENCODER 0
-%define CONFIG_SUNRAST_ENCODER 0
-%define CONFIG_SVQ1_ENCODER 0
-%define CONFIG_TARGA_ENCODER 0
-%define CONFIG_TIFF_ENCODER 0
-%define CONFIG_UTVIDEO_ENCODER 0
-%define CONFIG_V210_ENCODER 0
-%define CONFIG_V308_ENCODER 0
-%define CONFIG_V408_ENCODER 0
-%define CONFIG_V410_ENCODER 0
-%define CONFIG_VC2_ENCODER 0
-%define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-%define CONFIG_WMV1_ENCODER 0
-%define CONFIG_WMV2_ENCODER 0
-%define CONFIG_XBM_ENCODER 0
-%define CONFIG_XFACE_ENCODER 0
-%define CONFIG_XWD_ENCODER 0
-%define CONFIG_Y41P_ENCODER 0
-%define CONFIG_YUV4_ENCODER 0
-%define CONFIG_ZLIB_ENCODER 0
-%define CONFIG_ZMBV_ENCODER 0
-%define CONFIG_AAC_ENCODER 0
-%define CONFIG_AC3_ENCODER 0
-%define CONFIG_AC3_FIXED_ENCODER 0
-%define CONFIG_ALAC_ENCODER 0
-%define CONFIG_DCA_ENCODER 0
-%define CONFIG_EAC3_ENCODER 0
-%define CONFIG_FLAC_ENCODER 0
-%define CONFIG_G723_1_ENCODER 0
-%define CONFIG_MLP_ENCODER 0
-%define CONFIG_MP2_ENCODER 0
-%define CONFIG_MP2FIXED_ENCODER 0
-%define CONFIG_NELLYMOSER_ENCODER 0
-%define CONFIG_RA_144_ENCODER 0
-%define CONFIG_SONIC_ENCODER 0
-%define CONFIG_SONIC_LS_ENCODER 0
-%define CONFIG_TRUEHD_ENCODER 0
-%define CONFIG_TTA_ENCODER 0
-%define CONFIG_VORBIS_ENCODER 0
-%define CONFIG_WAVPACK_ENCODER 0
-%define CONFIG_WMAV1_ENCODER 0
-%define CONFIG_WMAV2_ENCODER 0
-%define CONFIG_PCM_ALAW_ENCODER 0
-%define CONFIG_PCM_F32BE_ENCODER 0
-%define CONFIG_PCM_F32LE_ENCODER 0
-%define CONFIG_PCM_F64BE_ENCODER 0
-%define CONFIG_PCM_F64LE_ENCODER 0
-%define CONFIG_PCM_MULAW_ENCODER 0
-%define CONFIG_PCM_S8_ENCODER 0
-%define CONFIG_PCM_S8_PLANAR_ENCODER 0
-%define CONFIG_PCM_S16BE_ENCODER 0
-%define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S16LE_ENCODER 0
-%define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S24BE_ENCODER 0
-%define CONFIG_PCM_S24DAUD_ENCODER 0
-%define CONFIG_PCM_S24LE_ENCODER 0
-%define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S32BE_ENCODER 0
-%define CONFIG_PCM_S32LE_ENCODER 0
-%define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-%define CONFIG_PCM_S64BE_ENCODER 0
-%define CONFIG_PCM_S64LE_ENCODER 0
-%define CONFIG_PCM_U8_ENCODER 0
-%define CONFIG_PCM_U16BE_ENCODER 0
-%define CONFIG_PCM_U16LE_ENCODER 0
-%define CONFIG_PCM_U24BE_ENCODER 0
-%define CONFIG_PCM_U24LE_ENCODER 0
-%define CONFIG_PCM_U32BE_ENCODER 0
-%define CONFIG_PCM_U32LE_ENCODER 0
-%define CONFIG_ROQ_DPCM_ENCODER 0
-%define CONFIG_ADPCM_ADX_ENCODER 0
-%define CONFIG_ADPCM_G722_ENCODER 0
-%define CONFIG_ADPCM_G726_ENCODER 0
-%define CONFIG_ADPCM_IMA_QT_ENCODER 0
-%define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-%define CONFIG_ADPCM_MS_ENCODER 0
-%define CONFIG_ADPCM_SWF_ENCODER 0
-%define CONFIG_ADPCM_YAMAHA_ENCODER 0
-%define CONFIG_SSA_ENCODER 0
-%define CONFIG_ASS_ENCODER 0
-%define CONFIG_DVBSUB_ENCODER 0
-%define CONFIG_DVDSUB_ENCODER 0
-%define CONFIG_MOVTEXT_ENCODER 0
-%define CONFIG_SRT_ENCODER 0
-%define CONFIG_SUBRIP_ENCODER 0
-%define CONFIG_TEXT_ENCODER 0
-%define CONFIG_WEBVTT_ENCODER 0
-%define CONFIG_XSUB_ENCODER 0
-%define CONFIG_AAC_AT_ENCODER 0
-%define CONFIG_ALAC_AT_ENCODER 0
-%define CONFIG_ILBC_AT_ENCODER 0
-%define CONFIG_PCM_ALAW_AT_ENCODER 0
-%define CONFIG_PCM_MULAW_AT_ENCODER 0
-%define CONFIG_LIBFDK_AAC_ENCODER 0
-%define CONFIG_LIBGSM_ENCODER 0
-%define CONFIG_LIBGSM_MS_ENCODER 0
-%define CONFIG_LIBILBC_ENCODER 0
-%define CONFIG_LIBMP3LAME_ENCODER 0
-%define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-%define CONFIG_LIBOPENJPEG_ENCODER 0
-%define CONFIG_LIBOPUS_ENCODER 0
-%define CONFIG_LIBSCHROEDINGER_ENCODER 0
-%define CONFIG_LIBSHINE_ENCODER 0
-%define CONFIG_LIBSPEEX_ENCODER 0
-%define CONFIG_LIBTHEORA_ENCODER 0
-%define CONFIG_LIBTWOLAME_ENCODER 0
-%define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-%define CONFIG_LIBVORBIS_ENCODER 0
-%define CONFIG_LIBVPX_VP8_ENCODER 0
-%define CONFIG_LIBVPX_VP9_ENCODER 0
-%define CONFIG_LIBWAVPACK_ENCODER 0
-%define CONFIG_LIBWEBP_ANIM_ENCODER 0
-%define CONFIG_LIBWEBP_ENCODER 0
-%define CONFIG_LIBX262_ENCODER 0
-%define CONFIG_LIBX264_ENCODER 0
-%define CONFIG_LIBX264RGB_ENCODER 0
-%define CONFIG_LIBX265_ENCODER 0
-%define CONFIG_LIBXAVS_ENCODER 0
-%define CONFIG_LIBXVID_ENCODER 0
-%define CONFIG_LIBOPENH264_ENCODER 0
-%define CONFIG_H264_NVENC_ENCODER 0
-%define CONFIG_H264_OMX_ENCODER 0
-%define CONFIG_H264_QSV_ENCODER 0
-%define CONFIG_H264_VAAPI_ENCODER 0
-%define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-%define CONFIG_NVENC_ENCODER 0
-%define CONFIG_NVENC_H264_ENCODER 0
-%define CONFIG_NVENC_HEVC_ENCODER 0
-%define CONFIG_HEVC_NVENC_ENCODER 0
-%define CONFIG_HEVC_QSV_ENCODER 0
-%define CONFIG_HEVC_VAAPI_ENCODER 0
-%define CONFIG_LIBKVAZAAR_ENCODER 0
-%define CONFIG_MJPEG_VAAPI_ENCODER 0
-%define CONFIG_MPEG2_QSV_ENCODER 0
-%define CONFIG_ABENCH_FILTER 0
-%define CONFIG_ACOMPRESSOR_FILTER 0
-%define CONFIG_ACROSSFADE_FILTER 0
-%define CONFIG_ACRUSHER_FILTER 0
-%define CONFIG_ADELAY_FILTER 0
-%define CONFIG_AECHO_FILTER 0
-%define CONFIG_AEMPHASIS_FILTER 0
-%define CONFIG_AEVAL_FILTER 0
-%define CONFIG_AFADE_FILTER 0
-%define CONFIG_AFFTFILT_FILTER 0
-%define CONFIG_AFORMAT_FILTER 0
-%define CONFIG_AGATE_FILTER 0
-%define CONFIG_AINTERLEAVE_FILTER 0
-%define CONFIG_ALIMITER_FILTER 0
-%define CONFIG_ALLPASS_FILTER 0
-%define CONFIG_ALOOP_FILTER 0
-%define CONFIG_AMERGE_FILTER 0
-%define CONFIG_AMETADATA_FILTER 0
-%define CONFIG_AMIX_FILTER 0
-%define CONFIG_ANEQUALIZER_FILTER 0
-%define CONFIG_ANULL_FILTER 0
-%define CONFIG_APAD_FILTER 0
-%define CONFIG_APERMS_FILTER 0
-%define CONFIG_APHASER_FILTER 0
-%define CONFIG_APULSATOR_FILTER 0
-%define CONFIG_AREALTIME_FILTER 0
-%define CONFIG_ARESAMPLE_FILTER 0
-%define CONFIG_AREVERSE_FILTER 0
-%define CONFIG_ASELECT_FILTER 0
-%define CONFIG_ASENDCMD_FILTER 0
-%define CONFIG_ASETNSAMPLES_FILTER 0
-%define CONFIG_ASETPTS_FILTER 0
-%define CONFIG_ASETRATE_FILTER 0
-%define CONFIG_ASETTB_FILTER 0
-%define CONFIG_ASHOWINFO_FILTER 0
-%define CONFIG_ASIDEDATA_FILTER 0
-%define CONFIG_ASPLIT_FILTER 0
-%define CONFIG_ASTATS_FILTER 0
-%define CONFIG_ASTREAMSELECT_FILTER 0
-%define CONFIG_ASYNCTS_FILTER 0
-%define CONFIG_ATEMPO_FILTER 0
-%define CONFIG_ATRIM_FILTER 0
-%define CONFIG_AZMQ_FILTER 0
-%define CONFIG_BANDPASS_FILTER 0
-%define CONFIG_BANDREJECT_FILTER 0
-%define CONFIG_BASS_FILTER 0
-%define CONFIG_BIQUAD_FILTER 0
-%define CONFIG_BS2B_FILTER 0
-%define CONFIG_CHANNELMAP_FILTER 0
-%define CONFIG_CHANNELSPLIT_FILTER 0
-%define CONFIG_CHORUS_FILTER 0
-%define CONFIG_COMPAND_FILTER 0
-%define CONFIG_COMPENSATIONDELAY_FILTER 0
-%define CONFIG_CRYSTALIZER_FILTER 0
-%define CONFIG_DCSHIFT_FILTER 0
-%define CONFIG_DYNAUDNORM_FILTER 0
-%define CONFIG_EARWAX_FILTER 0
-%define CONFIG_EBUR128_FILTER 0
-%define CONFIG_EQUALIZER_FILTER 0
-%define CONFIG_EXTRASTEREO_FILTER 0
-%define CONFIG_FIREQUALIZER_FILTER 0
-%define CONFIG_FLANGER_FILTER 0
-%define CONFIG_HDCD_FILTER 0
-%define CONFIG_HIGHPASS_FILTER 0
-%define CONFIG_JOIN_FILTER 0
-%define CONFIG_LADSPA_FILTER 0
-%define CONFIG_LOUDNORM_FILTER 0
-%define CONFIG_LOWPASS_FILTER 0
-%define CONFIG_PAN_FILTER 0
-%define CONFIG_REPLAYGAIN_FILTER 0
-%define CONFIG_RESAMPLE_FILTER 0
-%define CONFIG_RUBBERBAND_FILTER 0
-%define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-%define CONFIG_SIDECHAINGATE_FILTER 0
-%define CONFIG_SILENCEDETECT_FILTER 0
-%define CONFIG_SILENCEREMOVE_FILTER 0
-%define CONFIG_SOFALIZER_FILTER 0
-%define CONFIG_STEREOTOOLS_FILTER 0
-%define CONFIG_STEREOWIDEN_FILTER 0
-%define CONFIG_TREBLE_FILTER 0
-%define CONFIG_TREMOLO_FILTER 0
-%define CONFIG_VIBRATO_FILTER 0
-%define CONFIG_VOLUME_FILTER 0
-%define CONFIG_VOLUMEDETECT_FILTER 0
-%define CONFIG_AEVALSRC_FILTER 0
-%define CONFIG_ANOISESRC_FILTER 0
-%define CONFIG_ANULLSRC_FILTER 0
-%define CONFIG_FLITE_FILTER 0
-%define CONFIG_SINE_FILTER 0
-%define CONFIG_ANULLSINK_FILTER 0
-%define CONFIG_ALPHAEXTRACT_FILTER 0
-%define CONFIG_ALPHAMERGE_FILTER 0
-%define CONFIG_ASS_FILTER 0
-%define CONFIG_ATADENOISE_FILTER 0
-%define CONFIG_AVGBLUR_FILTER 0
-%define CONFIG_BBOX_FILTER 0
-%define CONFIG_BENCH_FILTER 0
-%define CONFIG_BITPLANENOISE_FILTER 0
-%define CONFIG_BLACKDETECT_FILTER 0
-%define CONFIG_BLACKFRAME_FILTER 0
-%define CONFIG_BLEND_FILTER 0
-%define CONFIG_BOXBLUR_FILTER 0
-%define CONFIG_BWDIF_FILTER 0
-%define CONFIG_CHROMAKEY_FILTER 0
-%define CONFIG_CIESCOPE_FILTER 0
-%define CONFIG_CODECVIEW_FILTER 0
-%define CONFIG_COLORBALANCE_FILTER 0
-%define CONFIG_COLORCHANNELMIXER_FILTER 0
-%define CONFIG_COLORKEY_FILTER 0
-%define CONFIG_COLORLEVELS_FILTER 0
-%define CONFIG_COLORMATRIX_FILTER 0
-%define CONFIG_COLORSPACE_FILTER 0
-%define CONFIG_CONVOLUTION_FILTER 0
-%define CONFIG_COPY_FILTER 0
-%define CONFIG_COREIMAGE_FILTER 0
-%define CONFIG_COVER_RECT_FILTER 0
-%define CONFIG_CROP_FILTER 0
-%define CONFIG_CROPDETECT_FILTER 0
-%define CONFIG_CURVES_FILTER 0
-%define CONFIG_DATASCOPE_FILTER 0
-%define CONFIG_DCTDNOIZ_FILTER 0
-%define CONFIG_DEBAND_FILTER 0
-%define CONFIG_DECIMATE_FILTER 0
-%define CONFIG_DEFLATE_FILTER 0
-%define CONFIG_DEJUDDER_FILTER 0
-%define CONFIG_DELOGO_FILTER 0
-%define CONFIG_DESHAKE_FILTER 0
-%define CONFIG_DETELECINE_FILTER 0
-%define CONFIG_DILATION_FILTER 0
-%define CONFIG_DISPLACE_FILTER 0
-%define CONFIG_DRAWBOX_FILTER 0
-%define CONFIG_DRAWGRAPH_FILTER 0
-%define CONFIG_DRAWGRID_FILTER 0
-%define CONFIG_DRAWTEXT_FILTER 0
-%define CONFIG_EDGEDETECT_FILTER 0
-%define CONFIG_ELBG_FILTER 0
-%define CONFIG_EQ_FILTER 0
-%define CONFIG_EROSION_FILTER 0
-%define CONFIG_EXTRACTPLANES_FILTER 0
-%define CONFIG_FADE_FILTER 0
-%define CONFIG_FFTFILT_FILTER 0
-%define CONFIG_FIELD_FILTER 0
-%define CONFIG_FIELDHINT_FILTER 0
-%define CONFIG_FIELDMATCH_FILTER 0
-%define CONFIG_FIELDORDER_FILTER 0
-%define CONFIG_FIND_RECT_FILTER 0
-%define CONFIG_FORMAT_FILTER 0
-%define CONFIG_FPS_FILTER 0
-%define CONFIG_FRAMEPACK_FILTER 0
-%define CONFIG_FRAMERATE_FILTER 0
-%define CONFIG_FRAMESTEP_FILTER 0
-%define CONFIG_FREI0R_FILTER 0
-%define CONFIG_FSPP_FILTER 0
-%define CONFIG_GBLUR_FILTER 0
-%define CONFIG_GEQ_FILTER 0
-%define CONFIG_GRADFUN_FILTER 0
-%define CONFIG_HALDCLUT_FILTER 0
-%define CONFIG_HFLIP_FILTER 0
-%define CONFIG_HISTEQ_FILTER 0
-%define CONFIG_HISTOGRAM_FILTER 0
-%define CONFIG_HQDN3D_FILTER 0
-%define CONFIG_HQX_FILTER 0
-%define CONFIG_HSTACK_FILTER 0
-%define CONFIG_HUE_FILTER 0
-%define CONFIG_HWDOWNLOAD_FILTER 0
-%define CONFIG_HWUPLOAD_FILTER 0
-%define CONFIG_HWUPLOAD_CUDA_FILTER 0
-%define CONFIG_HYSTERESIS_FILTER 0
-%define CONFIG_IDET_FILTER 0
-%define CONFIG_IL_FILTER 0
-%define CONFIG_INFLATE_FILTER 0
-%define CONFIG_INTERLACE_FILTER 0
-%define CONFIG_INTERLEAVE_FILTER 0
-%define CONFIG_KERNDEINT_FILTER 0
-%define CONFIG_LENSCORRECTION_FILTER 0
-%define CONFIG_LOOP_FILTER 0
-%define CONFIG_LUT_FILTER 0
-%define CONFIG_LUT2_FILTER 0
-%define CONFIG_LUT3D_FILTER 0
-%define CONFIG_LUTRGB_FILTER 0
-%define CONFIG_LUTYUV_FILTER 0
-%define CONFIG_MASKEDCLAMP_FILTER 0
-%define CONFIG_MASKEDMERGE_FILTER 0
-%define CONFIG_MCDEINT_FILTER 0
-%define CONFIG_MERGEPLANES_FILTER 0
-%define CONFIG_MESTIMATE_FILTER 0
-%define CONFIG_METADATA_FILTER 0
-%define CONFIG_MINTERPOLATE_FILTER 0
-%define CONFIG_MPDECIMATE_FILTER 0
-%define CONFIG_NEGATE_FILTER 0
-%define CONFIG_NLMEANS_FILTER 0
-%define CONFIG_NNEDI_FILTER 0
-%define CONFIG_NOFORMAT_FILTER 0
-%define CONFIG_NOISE_FILTER 0
-%define CONFIG_NULL_FILTER 0
-%define CONFIG_OCR_FILTER 0
-%define CONFIG_OCV_FILTER 0
-%define CONFIG_OVERLAY_FILTER 0
-%define CONFIG_OWDENOISE_FILTER 0
-%define CONFIG_PAD_FILTER 0
-%define CONFIG_PALETTEGEN_FILTER 0
-%define CONFIG_PALETTEUSE_FILTER 0
-%define CONFIG_PERMS_FILTER 0
-%define CONFIG_PERSPECTIVE_FILTER 0
-%define CONFIG_PHASE_FILTER 0
-%define CONFIG_PIXDESCTEST_FILTER 0
-%define CONFIG_PP_FILTER 0
-%define CONFIG_PP7_FILTER 0
-%define CONFIG_PREWITT_FILTER 0
-%define CONFIG_PSNR_FILTER 0
-%define CONFIG_PULLUP_FILTER 0
-%define CONFIG_QP_FILTER 0
-%define CONFIG_RANDOM_FILTER 0
-%define CONFIG_READVITC_FILTER 0
-%define CONFIG_REALTIME_FILTER 0
-%define CONFIG_REMAP_FILTER 0
-%define CONFIG_REMOVEGRAIN_FILTER 0
-%define CONFIG_REMOVELOGO_FILTER 0
-%define CONFIG_REPEATFIELDS_FILTER 0
-%define CONFIG_REVERSE_FILTER 0
-%define CONFIG_ROTATE_FILTER 0
-%define CONFIG_SAB_FILTER 0
-%define CONFIG_SCALE_FILTER 0
-%define CONFIG_SCALE_NPP_FILTER 0
-%define CONFIG_SCALE_VAAPI_FILTER 0
-%define CONFIG_SCALE2REF_FILTER 0
-%define CONFIG_SELECT_FILTER 0
-%define CONFIG_SELECTIVECOLOR_FILTER 0
-%define CONFIG_SENDCMD_FILTER 0
-%define CONFIG_SEPARATEFIELDS_FILTER 0
-%define CONFIG_SETDAR_FILTER 0
-%define CONFIG_SETFIELD_FILTER 0
-%define CONFIG_SETPTS_FILTER 0
-%define CONFIG_SETSAR_FILTER 0
-%define CONFIG_SETTB_FILTER 0
-%define CONFIG_SHOWINFO_FILTER 0
-%define CONFIG_SHOWPALETTE_FILTER 0
-%define CONFIG_SHUFFLEFRAMES_FILTER 0
-%define CONFIG_SHUFFLEPLANES_FILTER 0
-%define CONFIG_SIDEDATA_FILTER 0
-%define CONFIG_SIGNALSTATS_FILTER 0
-%define CONFIG_SMARTBLUR_FILTER 0
-%define CONFIG_SOBEL_FILTER 0
-%define CONFIG_SPLIT_FILTER 0
-%define CONFIG_SPP_FILTER 0
-%define CONFIG_SSIM_FILTER 0
-%define CONFIG_STEREO3D_FILTER 0
-%define CONFIG_STREAMSELECT_FILTER 0
-%define CONFIG_SUBTITLES_FILTER 0
-%define CONFIG_SUPER2XSAI_FILTER 0
-%define CONFIG_SWAPRECT_FILTER 0
-%define CONFIG_SWAPUV_FILTER 0
-%define CONFIG_TBLEND_FILTER 0
-%define CONFIG_TELECINE_FILTER 0
-%define CONFIG_THUMBNAIL_FILTER 0
-%define CONFIG_TILE_FILTER 0
-%define CONFIG_TINTERLACE_FILTER 0
-%define CONFIG_TRANSPOSE_FILTER 0
-%define CONFIG_TRIM_FILTER 0
-%define CONFIG_UNSHARP_FILTER 0
-%define CONFIG_USPP_FILTER 0
-%define CONFIG_VAGUEDENOISER_FILTER 0
-%define CONFIG_VECTORSCOPE_FILTER 0
-%define CONFIG_VFLIP_FILTER 0
-%define CONFIG_VIDSTABDETECT_FILTER 0
-%define CONFIG_VIDSTABTRANSFORM_FILTER 0
-%define CONFIG_VIGNETTE_FILTER 0
-%define CONFIG_VSTACK_FILTER 0
-%define CONFIG_W3FDIF_FILTER 0
-%define CONFIG_WAVEFORM_FILTER 0
-%define CONFIG_WEAVE_FILTER 0
-%define CONFIG_XBR_FILTER 0
-%define CONFIG_YADIF_FILTER 0
-%define CONFIG_ZMQ_FILTER 0
-%define CONFIG_ZOOMPAN_FILTER 0
-%define CONFIG_ZSCALE_FILTER 0
-%define CONFIG_ALLRGB_FILTER 0
-%define CONFIG_ALLYUV_FILTER 0
-%define CONFIG_CELLAUTO_FILTER 0
-%define CONFIG_COLOR_FILTER 0
-%define CONFIG_COREIMAGESRC_FILTER 0
-%define CONFIG_FREI0R_SRC_FILTER 0
-%define CONFIG_HALDCLUTSRC_FILTER 0
-%define CONFIG_LIFE_FILTER 0
-%define CONFIG_MANDELBROT_FILTER 0
-%define CONFIG_MPTESTSRC_FILTER 0
-%define CONFIG_NULLSRC_FILTER 0
-%define CONFIG_RGBTESTSRC_FILTER 0
-%define CONFIG_SMPTEBARS_FILTER 0
-%define CONFIG_SMPTEHDBARS_FILTER 0
-%define CONFIG_TESTSRC_FILTER 0
-%define CONFIG_TESTSRC2_FILTER 0
-%define CONFIG_YUVTESTSRC_FILTER 0
-%define CONFIG_NULLSINK_FILTER 0
-%define CONFIG_ADRAWGRAPH_FILTER 0
-%define CONFIG_AHISTOGRAM_FILTER 0
-%define CONFIG_APHASEMETER_FILTER 0
-%define CONFIG_AVECTORSCOPE_FILTER 0
-%define CONFIG_CONCAT_FILTER 0
-%define CONFIG_SHOWCQT_FILTER 0
-%define CONFIG_SHOWFREQS_FILTER 0
-%define CONFIG_SHOWSPECTRUM_FILTER 0
-%define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-%define CONFIG_SHOWVOLUME_FILTER 0
-%define CONFIG_SHOWWAVES_FILTER 0
-%define CONFIG_SHOWWAVESPIC_FILTER 0
-%define CONFIG_SPECTRUMSYNTH_FILTER 0
-%define CONFIG_AMOVIE_FILTER 0
-%define CONFIG_MOVIE_FILTER 0
-%define CONFIG_H263_CUVID_HWACCEL 0
-%define CONFIG_H263_VAAPI_HWACCEL 0
-%define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_H264_CUVID_HWACCEL 0
-%define CONFIG_H264_D3D11VA_HWACCEL 0
-%define CONFIG_H264_DXVA2_HWACCEL 0
-%define CONFIG_H264_MEDIACODEC_HWACCEL 0
-%define CONFIG_H264_MMAL_HWACCEL 0
-%define CONFIG_H264_QSV_HWACCEL 0
-%define CONFIG_H264_VAAPI_HWACCEL 0
-%define CONFIG_H264_VDA_HWACCEL 0
-%define CONFIG_H264_VDA_OLD_HWACCEL 0
-%define CONFIG_H264_VDPAU_HWACCEL 0
-%define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_HEVC_CUVID_HWACCEL 0
-%define CONFIG_HEVC_D3D11VA_HWACCEL 0
-%define CONFIG_HEVC_DXVA2_HWACCEL 0
-%define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-%define CONFIG_HEVC_QSV_HWACCEL 0
-%define CONFIG_HEVC_VAAPI_HWACCEL 0
-%define CONFIG_HEVC_VDPAU_HWACCEL 0
-%define CONFIG_MJPEG_CUVID_HWACCEL 0
-%define CONFIG_MPEG1_CUVID_HWACCEL 0
-%define CONFIG_MPEG1_XVMC_HWACCEL 0
-%define CONFIG_MPEG1_VDPAU_HWACCEL 0
-%define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_MPEG2_CUVID_HWACCEL 0
-%define CONFIG_MPEG2_XVMC_HWACCEL 0
-%define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-%define CONFIG_MPEG2_DXVA2_HWACCEL 0
-%define CONFIG_MPEG2_MMAL_HWACCEL 0
-%define CONFIG_MPEG2_QSV_HWACCEL 0
-%define CONFIG_MPEG2_VAAPI_HWACCEL 0
-%define CONFIG_MPEG2_VDPAU_HWACCEL 0
-%define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_MPEG4_CUVID_HWACCEL 0
-%define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-%define CONFIG_MPEG4_MMAL_HWACCEL 0
-%define CONFIG_MPEG4_VAAPI_HWACCEL 0
-%define CONFIG_MPEG4_VDPAU_HWACCEL 0
-%define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-%define CONFIG_VC1_CUVID_HWACCEL 0
-%define CONFIG_VC1_D3D11VA_HWACCEL 0
-%define CONFIG_VC1_DXVA2_HWACCEL 0
-%define CONFIG_VC1_VAAPI_HWACCEL 0
-%define CONFIG_VC1_VDPAU_HWACCEL 0
-%define CONFIG_VC1_MMAL_HWACCEL 0
-%define CONFIG_VC1_QSV_HWACCEL 0
-%define CONFIG_VP8_CUVID_HWACCEL 0
-%define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-%define CONFIG_VP9_CUVID_HWACCEL 0
-%define CONFIG_VP9_D3D11VA_HWACCEL 0
-%define CONFIG_VP9_DXVA2_HWACCEL 0
-%define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-%define CONFIG_VP9_VAAPI_HWACCEL 0
-%define CONFIG_WMV3_D3D11VA_HWACCEL 0
-%define CONFIG_WMV3_DXVA2_HWACCEL 0
-%define CONFIG_WMV3_VAAPI_HWACCEL 0
-%define CONFIG_WMV3_VDPAU_HWACCEL 0
-%define CONFIG_ALSA_INDEV 0
-%define CONFIG_AVFOUNDATION_INDEV 0
-%define CONFIG_BKTR_INDEV 0
-%define CONFIG_DECKLINK_INDEV 0
-%define CONFIG_DSHOW_INDEV 0
-%define CONFIG_DV1394_INDEV 0
-%define CONFIG_FBDEV_INDEV 0
-%define CONFIG_GDIGRAB_INDEV 0
-%define CONFIG_IEC61883_INDEV 0
-%define CONFIG_JACK_INDEV 0
-%define CONFIG_LAVFI_INDEV 0
-%define CONFIG_OPENAL_INDEV 0
-%define CONFIG_OSS_INDEV 0
-%define CONFIG_PULSE_INDEV 0
-%define CONFIG_QTKIT_INDEV 0
-%define CONFIG_SNDIO_INDEV 0
-%define CONFIG_V4L2_INDEV 0
-%define CONFIG_VFWCAP_INDEV 0
-%define CONFIG_X11GRAB_INDEV 0
-%define CONFIG_X11GRAB_XCB_INDEV 0
-%define CONFIG_LIBCDIO_INDEV 0
-%define CONFIG_LIBDC1394_INDEV 0
-%define CONFIG_A64_MUXER 0
-%define CONFIG_AC3_MUXER 0
-%define CONFIG_ADTS_MUXER 0
-%define CONFIG_ADX_MUXER 0
-%define CONFIG_AIFF_MUXER 0
-%define CONFIG_AMR_MUXER 0
-%define CONFIG_APNG_MUXER 0
-%define CONFIG_ASF_MUXER 0
-%define CONFIG_ASS_MUXER 0
-%define CONFIG_AST_MUXER 0
-%define CONFIG_ASF_STREAM_MUXER 0
-%define CONFIG_AU_MUXER 0
-%define CONFIG_AVI_MUXER 0
-%define CONFIG_AVM2_MUXER 0
-%define CONFIG_BIT_MUXER 0
-%define CONFIG_CAF_MUXER 0
-%define CONFIG_CAVSVIDEO_MUXER 0
-%define CONFIG_CRC_MUXER 0
-%define CONFIG_DASH_MUXER 0
-%define CONFIG_DATA_MUXER 0
-%define CONFIG_DAUD_MUXER 0
-%define CONFIG_DIRAC_MUXER 0
-%define CONFIG_DNXHD_MUXER 0
-%define CONFIG_DTS_MUXER 0
-%define CONFIG_DV_MUXER 0
-%define CONFIG_EAC3_MUXER 0
-%define CONFIG_F4V_MUXER 0
-%define CONFIG_FFM_MUXER 0
-%define CONFIG_FFMETADATA_MUXER 0
-%define CONFIG_FIFO_MUXER 0
-%define CONFIG_FILMSTRIP_MUXER 0
-%define CONFIG_FLAC_MUXER 0
-%define CONFIG_FLV_MUXER 0
-%define CONFIG_FRAMECRC_MUXER 0
-%define CONFIG_FRAMEHASH_MUXER 0
-%define CONFIG_FRAMEMD5_MUXER 0
-%define CONFIG_G722_MUXER 0
-%define CONFIG_G723_1_MUXER 0
-%define CONFIG_GIF_MUXER 0
-%define CONFIG_GSM_MUXER 0
-%define CONFIG_GXF_MUXER 0
-%define CONFIG_H261_MUXER 0
-%define CONFIG_H263_MUXER 0
-%define CONFIG_H264_MUXER 0
-%define CONFIG_HASH_MUXER 0
-%define CONFIG_HDS_MUXER 0
-%define CONFIG_HEVC_MUXER 0
-%define CONFIG_HLS_MUXER 0
-%define CONFIG_ICO_MUXER 0
-%define CONFIG_ILBC_MUXER 0
-%define CONFIG_IMAGE2_MUXER 0
-%define CONFIG_IMAGE2PIPE_MUXER 0
-%define CONFIG_IPOD_MUXER 0
-%define CONFIG_IRCAM_MUXER 0
-%define CONFIG_ISMV_MUXER 0
-%define CONFIG_IVF_MUXER 0
-%define CONFIG_JACOSUB_MUXER 0
-%define CONFIG_LATM_MUXER 0
-%define CONFIG_LRC_MUXER 0
-%define CONFIG_M4V_MUXER 0
-%define CONFIG_MD5_MUXER 0
-%define CONFIG_MATROSKA_MUXER 0
-%define CONFIG_MATROSKA_AUDIO_MUXER 0
-%define CONFIG_MICRODVD_MUXER 0
-%define CONFIG_MJPEG_MUXER 0
-%define CONFIG_MLP_MUXER 0
-%define CONFIG_MMF_MUXER 0
-%define CONFIG_MOV_MUXER 0
-%define CONFIG_MP2_MUXER 0
-%define CONFIG_MP3_MUXER 0
-%define CONFIG_MP4_MUXER 0
-%define CONFIG_MPEG1SYSTEM_MUXER 0
-%define CONFIG_MPEG1VCD_MUXER 0
-%define CONFIG_MPEG1VIDEO_MUXER 0
-%define CONFIG_MPEG2DVD_MUXER 0
-%define CONFIG_MPEG2SVCD_MUXER 0
-%define CONFIG_MPEG2VIDEO_MUXER 0
-%define CONFIG_MPEG2VOB_MUXER 0
-%define CONFIG_MPEGTS_MUXER 0
-%define CONFIG_MPJPEG_MUXER 0
-%define CONFIG_MXF_MUXER 0
-%define CONFIG_MXF_D10_MUXER 0
-%define CONFIG_MXF_OPATOM_MUXER 0
-%define CONFIG_NULL_MUXER 0
-%define CONFIG_NUT_MUXER 0
-%define CONFIG_OGA_MUXER 0
-%define CONFIG_OGG_MUXER 0
-%define CONFIG_OGV_MUXER 0
-%define CONFIG_OMA_MUXER 0
-%define CONFIG_OPUS_MUXER 0
-%define CONFIG_PCM_ALAW_MUXER 0
-%define CONFIG_PCM_MULAW_MUXER 0
-%define CONFIG_PCM_F64BE_MUXER 0
-%define CONFIG_PCM_F64LE_MUXER 0
-%define CONFIG_PCM_F32BE_MUXER 0
-%define CONFIG_PCM_F32LE_MUXER 0
-%define CONFIG_PCM_S32BE_MUXER 0
-%define CONFIG_PCM_S32LE_MUXER 0
-%define CONFIG_PCM_S24BE_MUXER 0
-%define CONFIG_PCM_S24LE_MUXER 0
-%define CONFIG_PCM_S16BE_MUXER 0
-%define CONFIG_PCM_S16LE_MUXER 0
-%define CONFIG_PCM_S8_MUXER 0
-%define CONFIG_PCM_U32BE_MUXER 0
-%define CONFIG_PCM_U32LE_MUXER 0
-%define CONFIG_PCM_U24BE_MUXER 0
-%define CONFIG_PCM_U24LE_MUXER 0
-%define CONFIG_PCM_U16BE_MUXER 0
-%define CONFIG_PCM_U16LE_MUXER 0
-%define CONFIG_PCM_U8_MUXER 0
-%define CONFIG_PSP_MUXER 0
-%define CONFIG_RAWVIDEO_MUXER 0
-%define CONFIG_RM_MUXER 0
-%define CONFIG_ROQ_MUXER 0
-%define CONFIG_RSO_MUXER 0
-%define CONFIG_RTP_MUXER 0
-%define CONFIG_RTP_MPEGTS_MUXER 0
-%define CONFIG_RTSP_MUXER 0
-%define CONFIG_SAP_MUXER 0
-%define CONFIG_SEGMENT_MUXER 0
-%define CONFIG_STREAM_SEGMENT_MUXER 0
-%define CONFIG_SINGLEJPEG_MUXER 0
-%define CONFIG_SMJPEG_MUXER 0
-%define CONFIG_SMOOTHSTREAMING_MUXER 0
-%define CONFIG_SOX_MUXER 0
-%define CONFIG_SPX_MUXER 0
-%define CONFIG_SPDIF_MUXER 0
-%define CONFIG_SRT_MUXER 0
-%define CONFIG_SWF_MUXER 0
-%define CONFIG_TEE_MUXER 0
-%define CONFIG_TG2_MUXER 0
-%define CONFIG_TGP_MUXER 0
-%define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-%define CONFIG_TRUEHD_MUXER 0
-%define CONFIG_TTA_MUXER 0
-%define CONFIG_UNCODEDFRAMECRC_MUXER 0
-%define CONFIG_VC1_MUXER 0
-%define CONFIG_VC1T_MUXER 0
-%define CONFIG_VOC_MUXER 0
-%define CONFIG_W64_MUXER 0
-%define CONFIG_WAV_MUXER 0
-%define CONFIG_WEBM_MUXER 0
-%define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-%define CONFIG_WEBM_CHUNK_MUXER 0
-%define CONFIG_WEBP_MUXER 0
-%define CONFIG_WEBVTT_MUXER 0
-%define CONFIG_WTV_MUXER 0
-%define CONFIG_WV_MUXER 0
-%define CONFIG_YUV4MPEGPIPE_MUXER 0
-%define CONFIG_CHROMAPRINT_MUXER 0
-%define CONFIG_LIBNUT_MUXER 0
-%define CONFIG_ALSA_OUTDEV 0
-%define CONFIG_CACA_OUTDEV 0
-%define CONFIG_DECKLINK_OUTDEV 0
-%define CONFIG_FBDEV_OUTDEV 0
-%define CONFIG_OPENGL_OUTDEV 0
-%define CONFIG_OSS_OUTDEV 0
-%define CONFIG_PULSE_OUTDEV 0
-%define CONFIG_SDL2_OUTDEV 0
-%define CONFIG_SNDIO_OUTDEV 0
-%define CONFIG_V4L2_OUTDEV 0
-%define CONFIG_XV_OUTDEV 0
-%define CONFIG_AAC_PARSER 0
-%define CONFIG_AAC_LATM_PARSER 0
-%define CONFIG_AC3_PARSER 0
-%define CONFIG_ADX_PARSER 0
-%define CONFIG_BMP_PARSER 0
-%define CONFIG_CAVSVIDEO_PARSER 0
-%define CONFIG_COOK_PARSER 0
-%define CONFIG_DCA_PARSER 0
-%define CONFIG_DIRAC_PARSER 0
-%define CONFIG_DNXHD_PARSER 0
-%define CONFIG_DPX_PARSER 0
-%define CONFIG_DVAUDIO_PARSER 0
-%define CONFIG_DVBSUB_PARSER 0
-%define CONFIG_DVDSUB_PARSER 0
-%define CONFIG_DVD_NAV_PARSER 0
-%define CONFIG_FLAC_PARSER 1
-%define CONFIG_G729_PARSER 0
-%define CONFIG_GSM_PARSER 0
-%define CONFIG_H261_PARSER 0
-%define CONFIG_H263_PARSER 0
-%define CONFIG_H264_PARSER 0
-%define CONFIG_HEVC_PARSER 0
-%define CONFIG_MJPEG_PARSER 0
-%define CONFIG_MLP_PARSER 0
-%define CONFIG_MPEG4VIDEO_PARSER 0
-%define CONFIG_MPEGAUDIO_PARSER 0
-%define CONFIG_MPEGVIDEO_PARSER 0
-%define CONFIG_OPUS_PARSER 0
-%define CONFIG_PNG_PARSER 0
-%define CONFIG_PNM_PARSER 0
-%define CONFIG_RV30_PARSER 0
-%define CONFIG_RV40_PARSER 0
-%define CONFIG_TAK_PARSER 0
-%define CONFIG_VC1_PARSER 0
-%define CONFIG_VORBIS_PARSER 0
-%define CONFIG_VP3_PARSER 0
+%define CONFIG_FLAC_PARSER 0
%define CONFIG_VP8_PARSER 1
%define CONFIG_VP9_PARSER 1
-%define CONFIG_ASYNC_PROTOCOL 0
-%define CONFIG_BLURAY_PROTOCOL 0
-%define CONFIG_CACHE_PROTOCOL 0
-%define CONFIG_CONCAT_PROTOCOL 0
-%define CONFIG_CRYPTO_PROTOCOL 0
-%define CONFIG_DATA_PROTOCOL 0
-%define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-%define CONFIG_FFRTMPHTTP_PROTOCOL 0
-%define CONFIG_FILE_PROTOCOL 0
-%define CONFIG_FTP_PROTOCOL 0
-%define CONFIG_GOPHER_PROTOCOL 0
-%define CONFIG_HLS_PROTOCOL 0
-%define CONFIG_HTTP_PROTOCOL 0
-%define CONFIG_HTTPPROXY_PROTOCOL 0
-%define CONFIG_HTTPS_PROTOCOL 0
-%define CONFIG_ICECAST_PROTOCOL 0
-%define CONFIG_MMSH_PROTOCOL 0
-%define CONFIG_MMST_PROTOCOL 0
-%define CONFIG_MD5_PROTOCOL 0
-%define CONFIG_PIPE_PROTOCOL 0
-%define CONFIG_RTMP_PROTOCOL 0
-%define CONFIG_RTMPE_PROTOCOL 0
-%define CONFIG_RTMPS_PROTOCOL 0
-%define CONFIG_RTMPT_PROTOCOL 0
-%define CONFIG_RTMPTE_PROTOCOL 0
-%define CONFIG_RTMPTS_PROTOCOL 0
-%define CONFIG_RTP_PROTOCOL 0
-%define CONFIG_SCTP_PROTOCOL 0
-%define CONFIG_SRTP_PROTOCOL 0
-%define CONFIG_SUBFILE_PROTOCOL 0
-%define CONFIG_TEE_PROTOCOL 0
-%define CONFIG_TCP_PROTOCOL 0
-%define CONFIG_TLS_GNUTLS_PROTOCOL 0
-%define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-%define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-%define CONFIG_TLS_OPENSSL_PROTOCOL 0
-%define CONFIG_UDP_PROTOCOL 0
-%define CONFIG_UDPLITE_PROTOCOL 0
-%define CONFIG_UNIX_PROTOCOL 0
-%define CONFIG_LIBRTMP_PROTOCOL 0
-%define CONFIG_LIBRTMPE_PROTOCOL 0
-%define CONFIG_LIBRTMPS_PROTOCOL 0
-%define CONFIG_LIBRTMPT_PROTOCOL 0
-%define CONFIG_LIBRTMPTE_PROTOCOL 0
-%define CONFIG_LIBSSH_PROTOCOL 0
-%define CONFIG_LIBSMBCLIENT_PROTOCOL 0
diff --git a/media/ffvpx/config_win64.h b/media/ffvpx/config_win64.h
index 64d09d226..b74b8d507 100644
--- a/media/ffvpx/config_win64.h
+++ b/media/ffvpx/config_win64.h
@@ -1,12 +1,12 @@
/* Automatically generated by configure - do not modify! */
#ifndef FFMPEG_CONFIG_H
#define FFMPEG_CONFIG_H
-#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vda --disable-vdpau --disable-videotoolbox --enable-asm --enable-yasm --toolchain=msvc"
+#define FFMPEG_CONFIGURATION "--disable-everything --disable-protocols --disable-demuxers --disable-muxers --disable-filters --disable-programs --disable-doc --disable-parsers --enable-parser=vp8 --enable-parser=vp9 --enable-decoder=vp8 --enable-decoder=vp9 --disable-static --enable-shared --disable-debug --disable-sdl2 --disable-libxcb --disable-securetransport --disable-iconv --disable-swresample --disable-swscale --disable-avdevice --disable-avfilter --disable-avformat --disable-d3d11va --disable-dxva2 --disable-vaapi --disable-vdpau --disable-videotoolbox --enable-decoder=flac --enable-asm --enable-yasm --toolchain=msvc"
#define FFMPEG_LICENSE "LGPL version 2.1 or later"
-#define CONFIG_THIS_YEAR 2016
+#define CONFIG_THIS_YEAR 2017
#define FFMPEG_DATADIR "/usr/local/share/ffmpeg"
#define AVCONV_DATADIR "/usr/local/share/ffmpeg"
-#define CC_IDENT "Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64"
+#define CC_IDENT "Microsoft (R) C/C++ Optimizing Compiler Version 19.11.25508.2 for x64"
#define av_restrict __restrict
#define EXTERN_PREFIX ""
#define EXTERN_ASM
@@ -79,8 +79,8 @@
#define HAVE_MIPSDSP 0
#define HAVE_MIPSDSPR2 0
#define HAVE_MSA 0
-#define HAVE_LOONGSON2 1
-#define HAVE_LOONGSON3 1
+#define HAVE_LOONGSON2 0
+#define HAVE_LOONGSON3 0
#define HAVE_MMI 0
#define HAVE_ARMV5TE_EXTERNAL 0
#define HAVE_ARMV6_EXTERNAL 0
@@ -172,37 +172,38 @@
#define HAVE_MMI_INLINE 0
#define HAVE_ALIGNED_STACK 1
#define HAVE_FAST_64BIT 1
-#define HAVE_FAST_CLZ 1
+#define HAVE_FAST_CLZ 0
#define HAVE_FAST_CMOV 1
#define HAVE_LOCAL_ALIGNED_8 1
#define HAVE_LOCAL_ALIGNED_16 1
#define HAVE_LOCAL_ALIGNED_32 1
#define HAVE_SIMD_ALIGN_16 1
+#define HAVE_SIMD_ALIGN_32 1
#define HAVE_ATOMICS_GCC 0
#define HAVE_ATOMICS_SUNCC 0
#define HAVE_ATOMICS_WIN32 1
#define HAVE_ATOMIC_CAS_PTR 0
-#define HAVE_ATOMIC_COMPARE_EXCHANGE 0
#define HAVE_MACHINE_RW_BARRIER 0
#define HAVE_MEMORYBARRIER 1
#define HAVE_MM_EMPTY 0
#define HAVE_RDTSC 1
#define HAVE_SARESTART 0
-#define HAVE_SEM_TIMEDWAIT 1
+#define HAVE_SEM_TIMEDWAIT 0
#define HAVE_SYNC_VAL_COMPARE_AND_SWAP 0
#define HAVE_CABS 0
#define HAVE_CEXP 0
#define HAVE_INLINE_ASM 0
#define HAVE_SYMVER 0
-#define HAVE_YASM 1
+#define HAVE_X86ASM 1
#define HAVE_BIGENDIAN 0
#define HAVE_FAST_UNALIGNED 1
-#define HAVE_ALSA_ASOUNDLIB_H 0
#define HAVE_ALTIVEC_H 0
#define HAVE_ARPA_INET_H 0
#define HAVE_ASM_TYPES_H 0
#define HAVE_CDIO_PARANOIA_H 0
#define HAVE_CDIO_PARANOIA_PARANOIA_H 0
+#define HAVE_CUDA_H 0
+#define HAVE_D3D11_H 1
#define HAVE_DISPATCH_DISPATCH_H 0
#define HAVE_DEV_BKTR_IOCTL_BT848_H 0
#define HAVE_DEV_BKTR_IOCTL_METEOR_H 0
@@ -212,7 +213,7 @@
#define HAVE_DIRECT_H 1
#define HAVE_DIRENT_H 0
#define HAVE_DLFCN_H 0
-#define HAVE_D3D11_H 1
+#define HAVE_DXGIDEBUG_H 1
#define HAVE_DXVA_H 1
#define HAVE_ES2_GL_H 0
#define HAVE_GSM_H 0
@@ -221,13 +222,15 @@
#define HAVE_MACHINE_IOCTL_BT848_H 0
#define HAVE_MACHINE_IOCTL_METEOR_H 0
#define HAVE_OPENCV2_CORE_CORE_C_H 0
+#define HAVE_OPENJPEG_2_3_OPENJPEG_H 0
+#define HAVE_OPENJPEG_2_2_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_1_OPENJPEG_H 0
#define HAVE_OPENJPEG_2_0_OPENJPEG_H 0
#define HAVE_OPENJPEG_1_5_OPENJPEG_H 0
#define HAVE_OPENGL_GL3_H 0
#define HAVE_POLL_H 0
-#define HAVE_SNDIO_H 0
#define HAVE_SOUNDCARD_H 0
+#define HAVE_STDATOMIC_H 0
#define HAVE_SYS_MMAN_H 0
#define HAVE_SYS_PARAM_H 0
#define HAVE_SYS_RESOURCE_H 0
@@ -279,7 +282,6 @@
#define HAVE_COMMANDLINETOARGVW 1
#define HAVE_COTASKMEMFREE 1
#define HAVE_CRYPTGENRANDOM 1
-#define HAVE_DLOPEN 0
#define HAVE_FCNTL 0
#define HAVE_FLT_LIM 1
#define HAVE_FORK 0
@@ -299,7 +301,7 @@
#define HAVE_ISATTY 1
#define HAVE_JACK_PORT_GET_LATENCY_RANGE 0
#define HAVE_KBHIT 1
-#define HAVE_LOADLIBRARY 0
+#define HAVE_LOADLIBRARY 1
#define HAVE_LSTAT 0
#define HAVE_LZO1X_999_COMPRESS 0
#define HAVE_MACH_ABSOLUTE_TIME 0
@@ -326,11 +328,13 @@
#define HAVE_OS2THREADS 0
#define HAVE_W32THREADS 1
#define HAVE_AS_DN_DIRECTIVE 0
+#define HAVE_AS_FPU_DIRECTIVE 0
#define HAVE_AS_FUNC 0
#define HAVE_AS_OBJECT_ARCH 0
#define HAVE_ASM_MOD_Q 0
#define HAVE_ATTRIBUTE_MAY_ALIAS 0
#define HAVE_ATTRIBUTE_PACKED 0
+#define HAVE_BLOCKS_EXTENSION 0
#define HAVE_EBP_AVAILABLE 0
#define HAVE_EBX_AVAILABLE 0
#define HAVE_GNU_AS 0
@@ -347,12 +351,13 @@
#define HAVE_XFORM_ASM 0
#define HAVE_XMM_CLOBBERS 0
#define HAVE_CONDITION_VARIABLE_PTR 1
+#define HAVE_KCMVIDEOCODECTYPE_HEVC 0
#define HAVE_SOCKLEN_T 1
#define HAVE_STRUCT_ADDRINFO 1
#define HAVE_STRUCT_GROUP_SOURCE_REQ 1
#define HAVE_STRUCT_IP_MREQ_SOURCE 1
#define HAVE_STRUCT_IPV6_MREQ 1
-#define HAVE_STRUCT_MSGHDR_MSG_FLAGS 1
+#define HAVE_STRUCT_MSGHDR_MSG_FLAGS 0
#define HAVE_STRUCT_POLLFD 0
#define HAVE_STRUCT_RUSAGE_RU_MAXRSS 0
#define HAVE_STRUCT_SCTP_EVENT_SUBSCRIBE 0
@@ -363,36 +368,20 @@
#define HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE 0
#define HAVE_ATOMICS_NATIVE 1
#define HAVE_DOS_PATHS 1
-#define HAVE_DXVA2_LIB 0
-#define HAVE_DXVA2API_COBJ 1
#define HAVE_LIBC_MSVCRT 1
-#define HAVE_LIBDC1394_1 0
-#define HAVE_LIBDC1394_2 0
#define HAVE_MAKEINFO 1
#define HAVE_MAKEINFO_HTML 0
#define HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS 0
#define HAVE_PERL 1
#define HAVE_POD2MAN 1
-#define HAVE_SDL2 0
#define HAVE_SECTION_DATA_REL_RO 0
#define HAVE_TEXI2HTML 0
#define HAVE_THREADS 1
+#define HAVE_UWP 0
#define HAVE_VAAPI_DRM 0
#define HAVE_VAAPI_X11 0
#define HAVE_VDPAU_X11 0
#define HAVE_WINRT 0
-#define HAVE_XLIB 0
-#define CONFIG_BSFS 0
-#define CONFIG_DECODERS 1
-#define CONFIG_ENCODERS 0
-#define CONFIG_HWACCELS 0
-#define CONFIG_PARSERS 1
-#define CONFIG_INDEVS 0
-#define CONFIG_OUTDEVS 0
-#define CONFIG_FILTERS 0
-#define CONFIG_DEMUXERS 0
-#define CONFIG_MUXERS 0
-#define CONFIG_PROTOCOLS 0
#define CONFIG_DOC 0
#define CONFIG_HTMLPAGES 0
#define CONFIG_MANPAGES 1
@@ -400,13 +389,17 @@
#define CONFIG_TXTPAGES 1
#define CONFIG_AVIO_DIR_CMD_EXAMPLE 1
#define CONFIG_AVIO_READING_EXAMPLE 1
-#define CONFIG_DECODING_ENCODING_EXAMPLE 0
+#define CONFIG_DECODE_AUDIO_EXAMPLE 1
+#define CONFIG_DECODE_VIDEO_EXAMPLE 1
#define CONFIG_DEMUXING_DECODING_EXAMPLE 0
+#define CONFIG_ENCODE_AUDIO_EXAMPLE 1
+#define CONFIG_ENCODE_VIDEO_EXAMPLE 1
#define CONFIG_EXTRACT_MVS_EXAMPLE 0
#define CONFIG_FILTER_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_AUDIO_EXAMPLE 0
#define CONFIG_FILTERING_VIDEO_EXAMPLE 0
#define CONFIG_HTTP_MULTICLIENT_EXAMPLE 0
+#define CONFIG_HW_DECODE_EXAMPLE 0
#define CONFIG_METADATA_EXAMPLE 0
#define CONFIG_MUXING_EXAMPLE 0
#define CONFIG_QSVDEC_EXAMPLE 0
@@ -415,27 +408,55 @@
#define CONFIG_SCALING_VIDEO_EXAMPLE 0
#define CONFIG_TRANSCODE_AAC_EXAMPLE 0
#define CONFIG_TRANSCODING_EXAMPLE 0
-#define CONFIG_AVISYNTH 0
+#define CONFIG_ALSA 0
+#define CONFIG_APPKIT 0
+#define CONFIG_AVFOUNDATION 0
#define CONFIG_BZLIB 0
-#define CONFIG_CHROMAPRINT 0
-#define CONFIG_CRYSTALHD 0
-#define CONFIG_DECKLINK 0
+#define CONFIG_COREIMAGE 0
+#define CONFIG_ICONV 0
+#define CONFIG_JACK 0
+#define CONFIG_LIBXCB 0
+#define CONFIG_LIBXCB_SHM 0
+#define CONFIG_LIBXCB_SHAPE 0
+#define CONFIG_LIBXCB_XFIXES 0
+#define CONFIG_LZMA 0
+#define CONFIG_SCHANNEL 1
+#define CONFIG_SDL2 0
+#define CONFIG_SECURETRANSPORT 0
+#define CONFIG_SNDIO 0
+#define CONFIG_XLIB 1
+#define CONFIG_ZLIB 0
+#define CONFIG_AVISYNTH 0
#define CONFIG_FREI0R 0
-#define CONFIG_GCRYPT 0
+#define CONFIG_LIBCDIO 0
+#define CONFIG_LIBRUBBERBAND 0
+#define CONFIG_LIBVIDSTAB 0
+#define CONFIG_LIBX264 0
+#define CONFIG_LIBX265 0
+#define CONFIG_LIBXAVS 0
+#define CONFIG_LIBXVID 0
+#define CONFIG_DECKLINK 0
+#define CONFIG_LIBNDI_NEWTEK 0
+#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_OPENSSL 0
#define CONFIG_GMP 0
+#define CONFIG_LIBOPENCORE_AMRNB 0
+#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_RKMPP 0
+#define CONFIG_LIBSMBCLIENT 0
+#define CONFIG_CHROMAPRINT 0
+#define CONFIG_GCRYPT 0
#define CONFIG_GNUTLS 0
-#define CONFIG_ICONV 0
#define CONFIG_JNI 0
#define CONFIG_LADSPA 0
#define CONFIG_LIBASS 0
#define CONFIG_LIBBLURAY 0
#define CONFIG_LIBBS2B 0
#define CONFIG_LIBCACA 0
-#define CONFIG_LIBCDIO 0
#define CONFIG_LIBCELT 0
#define CONFIG_LIBDC1394 0
-#define CONFIG_LIBEBUR128 0
-#define CONFIG_LIBFDK_AAC 0
+#define CONFIG_LIBDRM 0
#define CONFIG_LIBFLITE 0
#define CONFIG_LIBFONTCONFIG 0
#define CONFIG_LIBFREETYPE 0
@@ -447,18 +468,15 @@
#define CONFIG_LIBKVAZAAR 0
#define CONFIG_LIBMODPLUG 0
#define CONFIG_LIBMP3LAME 0
-#define CONFIG_LIBNUT 0
-#define CONFIG_LIBOPENCORE_AMRNB 0
-#define CONFIG_LIBOPENCORE_AMRWB 0
+#define CONFIG_LIBMYSOFA 0
#define CONFIG_LIBOPENCV 0
#define CONFIG_LIBOPENH264 0
#define CONFIG_LIBOPENJPEG 0
#define CONFIG_LIBOPENMPT 0
#define CONFIG_LIBOPUS 0
#define CONFIG_LIBPULSE 0
+#define CONFIG_LIBRSVG 0
#define CONFIG_LIBRTMP 0
-#define CONFIG_LIBRUBBERBAND 0
-#define CONFIG_LIBSCHROEDINGER 0
#define CONFIG_LIBSHINE 0
#define CONFIG_LIBSMBCLIENT 0
#define CONFIG_LIBSNAPPY 0
@@ -469,53 +487,37 @@
#define CONFIG_LIBTHEORA 0
#define CONFIG_LIBTWOLAME 0
#define CONFIG_LIBV4L2 0
-#define CONFIG_LIBVIDSTAB 0
-#define CONFIG_LIBVO_AMRWBENC 0
+#define CONFIG_LIBVMAF 0
#define CONFIG_LIBVORBIS 0
#define CONFIG_LIBVPX 0
#define CONFIG_LIBWAVPACK 0
#define CONFIG_LIBWEBP 0
-#define CONFIG_LIBX264 0
-#define CONFIG_LIBX265 0
-#define CONFIG_LIBXAVS 0
-#define CONFIG_LIBXCB 0
-#define CONFIG_LIBXCB_SHM 0
-#define CONFIG_LIBXCB_SHAPE 0
-#define CONFIG_LIBXCB_XFIXES 0
-#define CONFIG_LIBXVID 0
+#define CONFIG_LIBXML2 0
#define CONFIG_LIBZIMG 0
#define CONFIG_LIBZMQ 0
#define CONFIG_LIBZVBI 0
-#define CONFIG_LZMA 0
#define CONFIG_MEDIACODEC 0
-#define CONFIG_NETCDF 0
#define CONFIG_OPENAL 0
#define CONFIG_OPENCL 0
#define CONFIG_OPENGL 0
-#define CONFIG_OPENSSL 0
-#define CONFIG_SCHANNEL 1
-#define CONFIG_SDL 0
-#define CONFIG_SDL2 0
-#define CONFIG_SECURETRANSPORT 0
-#define CONFIG_VIDEOTOOLBOX 0
-#define CONFIG_X11GRAB 0
-#define CONFIG_XLIB 0
-#define CONFIG_ZLIB 0
#define CONFIG_AUDIOTOOLBOX 0
-#define CONFIG_CUDA 0
-#define CONFIG_CUVID 0
+#define CONFIG_CRYSTALHD 0
+#define CONFIG_CUDA 1
+#define CONFIG_CUVID 1
#define CONFIG_D3D11VA 0
#define CONFIG_DXVA2 0
-#define CONFIG_LIBMFX 0
-#define CONFIG_LIBNPP 0
-#define CONFIG_MMAL 0
-#define CONFIG_NVENC 0
-#define CONFIG_OMX 0
+#define CONFIG_NVENC 1
#define CONFIG_VAAPI 0
#define CONFIG_VDA 0
#define CONFIG_VDPAU 0
-#define CONFIG_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_VIDEOTOOLBOX 0
+#define CONFIG_V4L2_M2M 0
#define CONFIG_XVMC 0
+#define CONFIG_CUDA_SDK 0
+#define CONFIG_LIBNPP 0
+#define CONFIG_LIBMFX 0
+#define CONFIG_MMAL 0
+#define CONFIG_OMX 0
#define CONFIG_FTRAPV 0
#define CONFIG_GRAY 0
#define CONFIG_HARDCODED_TABLES 0
@@ -554,16 +556,27 @@
#define CONFIG_PIXELUTILS 0
#define CONFIG_NETWORK 0
#define CONFIG_RDFT 0
+#define CONFIG_AUTODETECT 0
#define CONFIG_FONTCONFIG 0
-#define CONFIG_MEMALIGN_HACK 0
+#define CONFIG_LINUX_PERF 0
#define CONFIG_MEMORY_POISONING 0
#define CONFIG_NEON_CLOBBER_TEST 0
+#define CONFIG_OSSFUZZ 0
#define CONFIG_PIC 1
-#define CONFIG_POD2MAN 1
-#define CONFIG_RAISE_MAJOR 0
#define CONFIG_THUMB 0
#define CONFIG_VALGRIND_BACKTRACE 0
#define CONFIG_XMM_CLOBBER_TEST 0
+#define CONFIG_BSFS 1
+#define CONFIG_DECODERS 1
+#define CONFIG_ENCODERS 0
+#define CONFIG_HWACCELS 0
+#define CONFIG_PARSERS 1
+#define CONFIG_INDEVS 0
+#define CONFIG_OUTDEVS 0
+#define CONFIG_FILTERS 0
+#define CONFIG_DEMUXERS 0
+#define CONFIG_MUXERS 0
+#define CONFIG_PROTOCOLS 0
#define CONFIG_AANDCTTABLES 0
#define CONFIG_AC3DSP 0
#define CONFIG_AUDIO_FRAME_QUEUE 0
@@ -581,20 +594,22 @@
#define CONFIG_FMTCONVERT 0
#define CONFIG_FRAME_THREAD_ENCODER 0
#define CONFIG_G722DSP 0
-#define CONFIG_GOLOMB 1
+#define CONFIG_GOLOMB 0
#define CONFIG_GPLV3 0
#define CONFIG_H263DSP 0
#define CONFIG_H264CHROMA 0
#define CONFIG_H264DSP 0
+#define CONFIG_H264PARSE 0
#define CONFIG_H264PRED 1
#define CONFIG_H264QPEL 0
+#define CONFIG_HEVCPARSE 0
#define CONFIG_HPELDSP 0
#define CONFIG_HUFFMAN 0
#define CONFIG_HUFFYUVDSP 0
#define CONFIG_HUFFYUVENCDSP 0
#define CONFIG_IDCTDSP 0
#define CONFIG_IIRFILTER 0
-#define CONFIG_IMDCT15 0
+#define CONFIG_MDCT15 0
#define CONFIG_INTRAX8 0
#define CONFIG_ISO_MEDIA 0
#define CONFIG_IVIDSP 0
@@ -603,12 +618,14 @@
#define CONFIG_LIBX262 0
#define CONFIG_LLAUDDSP 0
#define CONFIG_LLVIDDSP 0
+#define CONFIG_LLVIDENCDSP 0
#define CONFIG_LPC 0
#define CONFIG_LZF 0
#define CONFIG_ME_CMP 0
#define CONFIG_MPEG_ER 0
#define CONFIG_MPEGAUDIO 0
#define CONFIG_MPEGAUDIODSP 0
+#define CONFIG_MPEGAUDIOHEADER 0
#define CONFIG_MPEGVIDEO 0
#define CONFIG_MPEGVIDEOENC 0
#define CONFIG_MSS34DSP 0
@@ -630,1595 +647,20 @@
#define CONFIG_TEXTUREDSP 0
#define CONFIG_TEXTUREDSPENC 0
#define CONFIG_TPELDSP 0
+#define CONFIG_VAAPI_1 0
#define CONFIG_VAAPI_ENCODE 0
#define CONFIG_VC1DSP 0
#define CONFIG_VIDEODSP 1
#define CONFIG_VP3DSP 0
#define CONFIG_VP56DSP 0
#define CONFIG_VP8DSP 1
-#define CONFIG_VT_BT2020 0
#define CONFIG_WMA_FREQS 0
#define CONFIG_WMV2DSP 0
-#define CONFIG_AAC_ADTSTOASC_BSF 0
-#define CONFIG_CHOMP_BSF 0
-#define CONFIG_DUMP_EXTRADATA_BSF 0
-#define CONFIG_DCA_CORE_BSF 0
-#define CONFIG_H264_MP4TOANNEXB_BSF 0
-#define CONFIG_HEVC_MP4TOANNEXB_BSF 0
-#define CONFIG_IMX_DUMP_HEADER_BSF 0
-#define CONFIG_MJPEG2JPEG_BSF 0
-#define CONFIG_MJPEGA_DUMP_HEADER_BSF 0
-#define CONFIG_MP3_HEADER_DECOMPRESS_BSF 0
-#define CONFIG_MPEG4_UNPACK_BFRAMES_BSF 0
-#define CONFIG_MOV2TEXTSUB_BSF 0
-#define CONFIG_NOISE_BSF 0
-#define CONFIG_REMOVE_EXTRADATA_BSF 0
-#define CONFIG_TEXT2MOVSUB_BSF 0
-#define CONFIG_VP9_SUPERFRAME_BSF 0
-#define CONFIG_AASC_DECODER 0
-#define CONFIG_AIC_DECODER 0
-#define CONFIG_ALIAS_PIX_DECODER 0
-#define CONFIG_AMV_DECODER 0
-#define CONFIG_ANM_DECODER 0
-#define CONFIG_ANSI_DECODER 0
-#define CONFIG_APNG_DECODER 0
-#define CONFIG_ASV1_DECODER 0
-#define CONFIG_ASV2_DECODER 0
-#define CONFIG_AURA_DECODER 0
-#define CONFIG_AURA2_DECODER 0
-#define CONFIG_AVRP_DECODER 0
-#define CONFIG_AVRN_DECODER 0
-#define CONFIG_AVS_DECODER 0
-#define CONFIG_AVUI_DECODER 0
-#define CONFIG_AYUV_DECODER 0
-#define CONFIG_BETHSOFTVID_DECODER 0
-#define CONFIG_BFI_DECODER 0
-#define CONFIG_BINK_DECODER 0
-#define CONFIG_BMP_DECODER 0
-#define CONFIG_BMV_VIDEO_DECODER 0
-#define CONFIG_BRENDER_PIX_DECODER 0
-#define CONFIG_C93_DECODER 0
-#define CONFIG_CAVS_DECODER 0
-#define CONFIG_CDGRAPHICS_DECODER 0
-#define CONFIG_CDXL_DECODER 0
-#define CONFIG_CFHD_DECODER 0
-#define CONFIG_CINEPAK_DECODER 0
-#define CONFIG_CLJR_DECODER 0
-#define CONFIG_CLLC_DECODER 0
-#define CONFIG_COMFORTNOISE_DECODER 0
-#define CONFIG_CPIA_DECODER 0
-#define CONFIG_CSCD_DECODER 0
-#define CONFIG_CYUV_DECODER 0
-#define CONFIG_DDS_DECODER 0
-#define CONFIG_DFA_DECODER 0
-#define CONFIG_DIRAC_DECODER 0
-#define CONFIG_DNXHD_DECODER 0
-#define CONFIG_DPX_DECODER 0
-#define CONFIG_DSICINVIDEO_DECODER 0
-#define CONFIG_DVAUDIO_DECODER 0
-#define CONFIG_DVVIDEO_DECODER 0
-#define CONFIG_DXA_DECODER 0
-#define CONFIG_DXTORY_DECODER 0
-#define CONFIG_DXV_DECODER 0
-#define CONFIG_EACMV_DECODER 0
-#define CONFIG_EAMAD_DECODER 0
-#define CONFIG_EATGQ_DECODER 0
-#define CONFIG_EATGV_DECODER 0
-#define CONFIG_EATQI_DECODER 0
-#define CONFIG_EIGHTBPS_DECODER 0
-#define CONFIG_EIGHTSVX_EXP_DECODER 0
-#define CONFIG_EIGHTSVX_FIB_DECODER 0
-#define CONFIG_ESCAPE124_DECODER 0
-#define CONFIG_ESCAPE130_DECODER 0
-#define CONFIG_EXR_DECODER 0
-#define CONFIG_FFV1_DECODER 0
-#define CONFIG_FFVHUFF_DECODER 0
-#define CONFIG_FIC_DECODER 0
-#define CONFIG_FLASHSV_DECODER 0
-#define CONFIG_FLASHSV2_DECODER 0
-#define CONFIG_FLIC_DECODER 0
-#define CONFIG_FLV_DECODER 0
-#define CONFIG_FOURXM_DECODER 0
-#define CONFIG_FRAPS_DECODER 0
-#define CONFIG_FRWU_DECODER 0
-#define CONFIG_G2M_DECODER 0
-#define CONFIG_GIF_DECODER 0
-#define CONFIG_H261_DECODER 0
-#define CONFIG_H263_DECODER 0
-#define CONFIG_H263I_DECODER 0
-#define CONFIG_H263P_DECODER 0
-#define CONFIG_H264_DECODER 0
-#define CONFIG_H264_CRYSTALHD_DECODER 0
-#define CONFIG_H264_MEDIACODEC_DECODER 0
-#define CONFIG_H264_MMAL_DECODER 0
-#define CONFIG_H264_QSV_DECODER 0
-#define CONFIG_H264_VDA_DECODER 0
-#define CONFIG_H264_VDPAU_DECODER 0
-#define CONFIG_HAP_DECODER 0
-#define CONFIG_HEVC_DECODER 0
-#define CONFIG_HEVC_QSV_DECODER 0
-#define CONFIG_HNM4_VIDEO_DECODER 0
-#define CONFIG_HQ_HQA_DECODER 0
-#define CONFIG_HQX_DECODER 0
-#define CONFIG_HUFFYUV_DECODER 0
-#define CONFIG_IDCIN_DECODER 0
-#define CONFIG_IFF_ILBM_DECODER 0
-#define CONFIG_INDEO2_DECODER 0
-#define CONFIG_INDEO3_DECODER 0
-#define CONFIG_INDEO4_DECODER 0
-#define CONFIG_INDEO5_DECODER 0
-#define CONFIG_INTERPLAY_VIDEO_DECODER 0
-#define CONFIG_JPEG2000_DECODER 0
-#define CONFIG_JPEGLS_DECODER 0
-#define CONFIG_JV_DECODER 0
-#define CONFIG_KGV1_DECODER 0
-#define CONFIG_KMVC_DECODER 0
-#define CONFIG_LAGARITH_DECODER 0
-#define CONFIG_LOCO_DECODER 0
-#define CONFIG_M101_DECODER 0
-#define CONFIG_MAGICYUV_DECODER 0
-#define CONFIG_MDEC_DECODER 0
-#define CONFIG_MIMIC_DECODER 0
-#define CONFIG_MJPEG_DECODER 0
-#define CONFIG_MJPEGB_DECODER 0
-#define CONFIG_MMVIDEO_DECODER 0
-#define CONFIG_MOTIONPIXELS_DECODER 0
-#define CONFIG_MPEG_XVMC_DECODER 0
-#define CONFIG_MPEG1VIDEO_DECODER 0
-#define CONFIG_MPEG2VIDEO_DECODER 0
-#define CONFIG_MPEG4_DECODER 0
-#define CONFIG_MPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG4_MMAL_DECODER 0
-#define CONFIG_MPEG4_VDPAU_DECODER 0
-#define CONFIG_MPEGVIDEO_DECODER 0
-#define CONFIG_MPEG_VDPAU_DECODER 0
-#define CONFIG_MPEG1_VDPAU_DECODER 0
-#define CONFIG_MPEG2_MMAL_DECODER 0
-#define CONFIG_MPEG2_CRYSTALHD_DECODER 0
-#define CONFIG_MPEG2_QSV_DECODER 0
-#define CONFIG_MSA1_DECODER 0
-#define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
-#define CONFIG_MSMPEG4V1_DECODER 0
-#define CONFIG_MSMPEG4V2_DECODER 0
-#define CONFIG_MSMPEG4V3_DECODER 0
-#define CONFIG_MSRLE_DECODER 0
-#define CONFIG_MSS1_DECODER 0
-#define CONFIG_MSS2_DECODER 0
-#define CONFIG_MSVIDEO1_DECODER 0
-#define CONFIG_MSZH_DECODER 0
-#define CONFIG_MTS2_DECODER 0
-#define CONFIG_MVC1_DECODER 0
-#define CONFIG_MVC2_DECODER 0
-#define CONFIG_MXPEG_DECODER 0
-#define CONFIG_NUV_DECODER 0
-#define CONFIG_PAF_VIDEO_DECODER 0
-#define CONFIG_PAM_DECODER 0
-#define CONFIG_PBM_DECODER 0
-#define CONFIG_PCX_DECODER 0
-#define CONFIG_PGM_DECODER 0
-#define CONFIG_PGMYUV_DECODER 0
-#define CONFIG_PICTOR_DECODER 0
-#define CONFIG_PNG_DECODER 0
-#define CONFIG_PPM_DECODER 0
-#define CONFIG_PRORES_DECODER 0
-#define CONFIG_PRORES_LGPL_DECODER 0
-#define CONFIG_PTX_DECODER 0
-#define CONFIG_QDRAW_DECODER 0
-#define CONFIG_QPEG_DECODER 0
-#define CONFIG_QTRLE_DECODER 0
-#define CONFIG_R10K_DECODER 0
-#define CONFIG_R210_DECODER 0
-#define CONFIG_RAWVIDEO_DECODER 0
-#define CONFIG_RL2_DECODER 0
-#define CONFIG_ROQ_DECODER 0
-#define CONFIG_RPZA_DECODER 0
-#define CONFIG_RSCC_DECODER 0
-#define CONFIG_RV10_DECODER 0
-#define CONFIG_RV20_DECODER 0
-#define CONFIG_RV30_DECODER 0
-#define CONFIG_RV40_DECODER 0
-#define CONFIG_S302M_DECODER 0
-#define CONFIG_SANM_DECODER 0
-#define CONFIG_SCREENPRESSO_DECODER 0
-#define CONFIG_SDX2_DPCM_DECODER 0
-#define CONFIG_SGI_DECODER 0
-#define CONFIG_SGIRLE_DECODER 0
-#define CONFIG_SHEERVIDEO_DECODER 0
-#define CONFIG_SMACKER_DECODER 0
-#define CONFIG_SMC_DECODER 0
-#define CONFIG_SMVJPEG_DECODER 0
-#define CONFIG_SNOW_DECODER 0
-#define CONFIG_SP5X_DECODER 0
-#define CONFIG_SUNRAST_DECODER 0
-#define CONFIG_SVQ1_DECODER 0
-#define CONFIG_SVQ3_DECODER 0
-#define CONFIG_TARGA_DECODER 0
-#define CONFIG_TARGA_Y216_DECODER 0
-#define CONFIG_TDSC_DECODER 0
-#define CONFIG_THEORA_DECODER 0
-#define CONFIG_THP_DECODER 0
-#define CONFIG_TIERTEXSEQVIDEO_DECODER 0
-#define CONFIG_TIFF_DECODER 0
-#define CONFIG_TMV_DECODER 0
-#define CONFIG_TRUEMOTION1_DECODER 0
-#define CONFIG_TRUEMOTION2_DECODER 0
-#define CONFIG_TRUEMOTION2RT_DECODER 0
-#define CONFIG_TSCC_DECODER 0
-#define CONFIG_TSCC2_DECODER 0
-#define CONFIG_TXD_DECODER 0
-#define CONFIG_ULTI_DECODER 0
-#define CONFIG_UTVIDEO_DECODER 0
-#define CONFIG_V210_DECODER 0
-#define CONFIG_V210X_DECODER 0
-#define CONFIG_V308_DECODER 0
-#define CONFIG_V408_DECODER 0
-#define CONFIG_V410_DECODER 0
-#define CONFIG_VB_DECODER 0
-#define CONFIG_VBLE_DECODER 0
-#define CONFIG_VC1_DECODER 0
-#define CONFIG_VC1_CRYSTALHD_DECODER 0
-#define CONFIG_VC1_VDPAU_DECODER 0
-#define CONFIG_VC1IMAGE_DECODER 0
-#define CONFIG_VC1_MMAL_DECODER 0
-#define CONFIG_VC1_QSV_DECODER 0
-#define CONFIG_VCR1_DECODER 0
-#define CONFIG_VMDVIDEO_DECODER 0
-#define CONFIG_VMNC_DECODER 0
-#define CONFIG_VP3_DECODER 0
-#define CONFIG_VP5_DECODER 0
-#define CONFIG_VP6_DECODER 0
-#define CONFIG_VP6A_DECODER 0
-#define CONFIG_VP6F_DECODER 0
-#define CONFIG_VP7_DECODER 0
+#define CONFIG_NULL_BSF 1
#define CONFIG_VP8_DECODER 1
#define CONFIG_VP9_DECODER 1
-#define CONFIG_VQA_DECODER 0
-#define CONFIG_WEBP_DECODER 0
-#define CONFIG_WMV1_DECODER 0
-#define CONFIG_WMV2_DECODER 0
-#define CONFIG_WMV3_DECODER 0
-#define CONFIG_WMV3_CRYSTALHD_DECODER 0
-#define CONFIG_WMV3_VDPAU_DECODER 0
-#define CONFIG_WMV3IMAGE_DECODER 0
-#define CONFIG_WNV1_DECODER 0
-#define CONFIG_XAN_WC3_DECODER 0
-#define CONFIG_XAN_WC4_DECODER 0
-#define CONFIG_XBM_DECODER 0
-#define CONFIG_XFACE_DECODER 0
-#define CONFIG_XL_DECODER 0
-#define CONFIG_XWD_DECODER 0
-#define CONFIG_Y41P_DECODER 0
-#define CONFIG_YLC_DECODER 0
-#define CONFIG_YOP_DECODER 0
-#define CONFIG_YUV4_DECODER 0
-#define CONFIG_ZERO12V_DECODER 0
-#define CONFIG_ZEROCODEC_DECODER 0
-#define CONFIG_ZLIB_DECODER 0
-#define CONFIG_ZMBV_DECODER 0
-#define CONFIG_AAC_DECODER 0
-#define CONFIG_AAC_FIXED_DECODER 0
-#define CONFIG_AAC_LATM_DECODER 0
-#define CONFIG_AC3_DECODER 0
-#define CONFIG_AC3_FIXED_DECODER 0
-#define CONFIG_ALAC_DECODER 0
-#define CONFIG_ALS_DECODER 0
-#define CONFIG_AMRNB_DECODER 0
-#define CONFIG_AMRWB_DECODER 0
-#define CONFIG_APE_DECODER 0
-#define CONFIG_ATRAC1_DECODER 0
-#define CONFIG_ATRAC3_DECODER 0
-#define CONFIG_ATRAC3P_DECODER 0
-#define CONFIG_BINKAUDIO_DCT_DECODER 0
-#define CONFIG_BINKAUDIO_RDFT_DECODER 0
-#define CONFIG_BMV_AUDIO_DECODER 0
-#define CONFIG_COOK_DECODER 0
-#define CONFIG_DCA_DECODER 0
-#define CONFIG_DSD_LSBF_DECODER 0
-#define CONFIG_DSD_MSBF_DECODER 0
-#define CONFIG_DSD_LSBF_PLANAR_DECODER 0
-#define CONFIG_DSD_MSBF_PLANAR_DECODER 0
-#define CONFIG_DSICINAUDIO_DECODER 0
-#define CONFIG_DSS_SP_DECODER 0
-#define CONFIG_DST_DECODER 0
-#define CONFIG_EAC3_DECODER 0
-#define CONFIG_EVRC_DECODER 0
-#define CONFIG_FFWAVESYNTH_DECODER 0
#define CONFIG_FLAC_DECODER 1
-#define CONFIG_G723_1_DECODER 0
-#define CONFIG_G729_DECODER 0
-#define CONFIG_GSM_DECODER 0
-#define CONFIG_GSM_MS_DECODER 0
-#define CONFIG_IAC_DECODER 0
-#define CONFIG_IMC_DECODER 0
-#define CONFIG_INTERPLAY_ACM_DECODER 0
-#define CONFIG_MACE3_DECODER 0
-#define CONFIG_MACE6_DECODER 0
-#define CONFIG_METASOUND_DECODER 0
-#define CONFIG_MLP_DECODER 0
-#define CONFIG_MP1_DECODER 0
-#define CONFIG_MP1FLOAT_DECODER 0
-#define CONFIG_MP2_DECODER 0
-#define CONFIG_MP2FLOAT_DECODER 0
-#define CONFIG_MP3_DECODER 0
-#define CONFIG_MP3FLOAT_DECODER 0
-#define CONFIG_MP3ADU_DECODER 0
-#define CONFIG_MP3ADUFLOAT_DECODER 0
-#define CONFIG_MP3ON4_DECODER 0
-#define CONFIG_MP3ON4FLOAT_DECODER 0
-#define CONFIG_MPC7_DECODER 0
-#define CONFIG_MPC8_DECODER 0
-#define CONFIG_NELLYMOSER_DECODER 0
-#define CONFIG_ON2AVC_DECODER 0
-#define CONFIG_OPUS_DECODER 0
-#define CONFIG_PAF_AUDIO_DECODER 0
-#define CONFIG_QCELP_DECODER 0
-#define CONFIG_QDM2_DECODER 0
-#define CONFIG_RA_144_DECODER 0
-#define CONFIG_RA_288_DECODER 0
-#define CONFIG_RALF_DECODER 0
-#define CONFIG_SHORTEN_DECODER 0
-#define CONFIG_SIPR_DECODER 0
-#define CONFIG_SMACKAUD_DECODER 0
-#define CONFIG_SONIC_DECODER 0
-#define CONFIG_TAK_DECODER 0
-#define CONFIG_TRUEHD_DECODER 0
-#define CONFIG_TRUESPEECH_DECODER 0
-#define CONFIG_TTA_DECODER 0
-#define CONFIG_TWINVQ_DECODER 0
-#define CONFIG_VMDAUDIO_DECODER 0
-#define CONFIG_VORBIS_DECODER 0
-#define CONFIG_WAVPACK_DECODER 0
-#define CONFIG_WMALOSSLESS_DECODER 0
-#define CONFIG_WMAPRO_DECODER 0
-#define CONFIG_WMAV1_DECODER 0
-#define CONFIG_WMAV2_DECODER 0
-#define CONFIG_WMAVOICE_DECODER 0
-#define CONFIG_WS_SND1_DECODER 0
-#define CONFIG_XMA1_DECODER 0
-#define CONFIG_XMA2_DECODER 0
-#define CONFIG_PCM_ALAW_DECODER 0
-#define CONFIG_PCM_BLURAY_DECODER 0
-#define CONFIG_PCM_DVD_DECODER 0
-#define CONFIG_PCM_F32BE_DECODER 0
-#define CONFIG_PCM_F32LE_DECODER 0
-#define CONFIG_PCM_F64BE_DECODER 0
-#define CONFIG_PCM_F64LE_DECODER 0
-#define CONFIG_PCM_LXF_DECODER 0
-#define CONFIG_PCM_MULAW_DECODER 0
-#define CONFIG_PCM_S8_DECODER 0
-#define CONFIG_PCM_S8_PLANAR_DECODER 0
-#define CONFIG_PCM_S16BE_DECODER 0
-#define CONFIG_PCM_S16BE_PLANAR_DECODER 0
-#define CONFIG_PCM_S16LE_DECODER 0
-#define CONFIG_PCM_S16LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S24BE_DECODER 0
-#define CONFIG_PCM_S24DAUD_DECODER 0
-#define CONFIG_PCM_S24LE_DECODER 0
-#define CONFIG_PCM_S24LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S32BE_DECODER 0
-#define CONFIG_PCM_S32LE_DECODER 0
-#define CONFIG_PCM_S32LE_PLANAR_DECODER 0
-#define CONFIG_PCM_S64BE_DECODER 0
-#define CONFIG_PCM_S64LE_DECODER 0
-#define CONFIG_PCM_U8_DECODER 0
-#define CONFIG_PCM_U16BE_DECODER 0
-#define CONFIG_PCM_U16LE_DECODER 0
-#define CONFIG_PCM_U24BE_DECODER 0
-#define CONFIG_PCM_U24LE_DECODER 0
-#define CONFIG_PCM_U32BE_DECODER 0
-#define CONFIG_PCM_U32LE_DECODER 0
-#define CONFIG_PCM_ZORK_DECODER 0
-#define CONFIG_INTERPLAY_DPCM_DECODER 0
-#define CONFIG_ROQ_DPCM_DECODER 0
-#define CONFIG_SOL_DPCM_DECODER 0
-#define CONFIG_XAN_DPCM_DECODER 0
-#define CONFIG_ADPCM_4XM_DECODER 0
-#define CONFIG_ADPCM_ADX_DECODER 0
-#define CONFIG_ADPCM_AFC_DECODER 0
-#define CONFIG_ADPCM_AICA_DECODER 0
-#define CONFIG_ADPCM_CT_DECODER 0
-#define CONFIG_ADPCM_DTK_DECODER 0
-#define CONFIG_ADPCM_EA_DECODER 0
-#define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
-#define CONFIG_ADPCM_EA_R1_DECODER 0
-#define CONFIG_ADPCM_EA_R2_DECODER 0
-#define CONFIG_ADPCM_EA_R3_DECODER 0
-#define CONFIG_ADPCM_EA_XAS_DECODER 0
-#define CONFIG_ADPCM_G722_DECODER 0
-#define CONFIG_ADPCM_G726_DECODER 0
-#define CONFIG_ADPCM_G726LE_DECODER 0
-#define CONFIG_ADPCM_IMA_AMV_DECODER 0
-#define CONFIG_ADPCM_IMA_APC_DECODER 0
-#define CONFIG_ADPCM_IMA_DAT4_DECODER 0
-#define CONFIG_ADPCM_IMA_DK3_DECODER 0
-#define CONFIG_ADPCM_IMA_DK4_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
-#define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
-#define CONFIG_ADPCM_IMA_ISS_DECODER 0
-#define CONFIG_ADPCM_IMA_OKI_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_DECODER 0
-#define CONFIG_ADPCM_IMA_RAD_DECODER 0
-#define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
-#define CONFIG_ADPCM_IMA_WAV_DECODER 0
-#define CONFIG_ADPCM_IMA_WS_DECODER 0
-#define CONFIG_ADPCM_MS_DECODER 0
-#define CONFIG_ADPCM_MTAF_DECODER 0
-#define CONFIG_ADPCM_PSX_DECODER 0
-#define CONFIG_ADPCM_SBPRO_2_DECODER 0
-#define CONFIG_ADPCM_SBPRO_3_DECODER 0
-#define CONFIG_ADPCM_SBPRO_4_DECODER 0
-#define CONFIG_ADPCM_SWF_DECODER 0
-#define CONFIG_ADPCM_THP_DECODER 0
-#define CONFIG_ADPCM_THP_LE_DECODER 0
-#define CONFIG_ADPCM_VIMA_DECODER 0
-#define CONFIG_ADPCM_XA_DECODER 0
-#define CONFIG_ADPCM_YAMAHA_DECODER 0
-#define CONFIG_SSA_DECODER 0
-#define CONFIG_ASS_DECODER 0
-#define CONFIG_CCAPTION_DECODER 0
-#define CONFIG_DVBSUB_DECODER 0
-#define CONFIG_DVDSUB_DECODER 0
-#define CONFIG_JACOSUB_DECODER 0
-#define CONFIG_MICRODVD_DECODER 0
-#define CONFIG_MOVTEXT_DECODER 0
-#define CONFIG_MPL2_DECODER 0
-#define CONFIG_PGSSUB_DECODER 0
-#define CONFIG_PJS_DECODER 0
-#define CONFIG_REALTEXT_DECODER 0
-#define CONFIG_SAMI_DECODER 0
-#define CONFIG_SRT_DECODER 0
-#define CONFIG_STL_DECODER 0
-#define CONFIG_SUBRIP_DECODER 0
-#define CONFIG_SUBVIEWER_DECODER 0
-#define CONFIG_SUBVIEWER1_DECODER 0
-#define CONFIG_TEXT_DECODER 0
-#define CONFIG_VPLAYER_DECODER 0
-#define CONFIG_WEBVTT_DECODER 0
-#define CONFIG_XSUB_DECODER 0
-#define CONFIG_AAC_AT_DECODER 0
-#define CONFIG_AC3_AT_DECODER 0
-#define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
-#define CONFIG_ALAC_AT_DECODER 0
-#define CONFIG_AMR_NB_AT_DECODER 0
-#define CONFIG_EAC3_AT_DECODER 0
-#define CONFIG_GSM_MS_AT_DECODER 0
-#define CONFIG_ILBC_AT_DECODER 0
-#define CONFIG_MP1_AT_DECODER 0
-#define CONFIG_MP2_AT_DECODER 0
-#define CONFIG_MP3_AT_DECODER 0
-#define CONFIG_PCM_ALAW_AT_DECODER 0
-#define CONFIG_PCM_MULAW_AT_DECODER 0
-#define CONFIG_QDMC_AT_DECODER 0
-#define CONFIG_QDM2_AT_DECODER 0
-#define CONFIG_LIBCELT_DECODER 0
-#define CONFIG_LIBFDK_AAC_DECODER 0
-#define CONFIG_LIBGSM_DECODER 0
-#define CONFIG_LIBGSM_MS_DECODER 0
-#define CONFIG_LIBILBC_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
-#define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
-#define CONFIG_LIBOPENJPEG_DECODER 0
-#define CONFIG_LIBOPUS_DECODER 0
-#define CONFIG_LIBSCHROEDINGER_DECODER 0
-#define CONFIG_LIBSPEEX_DECODER 0
-#define CONFIG_LIBVORBIS_DECODER 0
-#define CONFIG_LIBVPX_VP8_DECODER 0
-#define CONFIG_LIBVPX_VP9_DECODER 0
-#define CONFIG_LIBZVBI_TELETEXT_DECODER 0
-#define CONFIG_BINTEXT_DECODER 0
-#define CONFIG_XBIN_DECODER 0
-#define CONFIG_IDF_DECODER 0
-#define CONFIG_LIBOPENH264_DECODER 0
-#define CONFIG_H263_CUVID_DECODER 0
-#define CONFIG_H264_CUVID_DECODER 0
-#define CONFIG_HEVC_CUVID_DECODER 0
-#define CONFIG_HEVC_MEDIACODEC_DECODER 0
-#define CONFIG_MJPEG_CUVID_DECODER 0
-#define CONFIG_MPEG1_CUVID_DECODER 0
-#define CONFIG_MPEG2_CUVID_DECODER 0
-#define CONFIG_MPEG4_CUVID_DECODER 0
-#define CONFIG_MPEG4_MEDIACODEC_DECODER 0
-#define CONFIG_VC1_CUVID_DECODER 0
-#define CONFIG_VP8_CUVID_DECODER 0
-#define CONFIG_VP8_MEDIACODEC_DECODER 0
-#define CONFIG_VP9_CUVID_DECODER 0
-#define CONFIG_VP9_MEDIACODEC_DECODER 0
-#define CONFIG_AA_DEMUXER 0
-#define CONFIG_AAC_DEMUXER 0
-#define CONFIG_AC3_DEMUXER 0
-#define CONFIG_ACM_DEMUXER 0
-#define CONFIG_ACT_DEMUXER 0
-#define CONFIG_ADF_DEMUXER 0
-#define CONFIG_ADP_DEMUXER 0
-#define CONFIG_ADS_DEMUXER 0
-#define CONFIG_ADX_DEMUXER 0
-#define CONFIG_AEA_DEMUXER 0
-#define CONFIG_AFC_DEMUXER 0
-#define CONFIG_AIFF_DEMUXER 0
-#define CONFIG_AIX_DEMUXER 0
-#define CONFIG_AMR_DEMUXER 0
-#define CONFIG_ANM_DEMUXER 0
-#define CONFIG_APC_DEMUXER 0
-#define CONFIG_APE_DEMUXER 0
-#define CONFIG_APNG_DEMUXER 0
-#define CONFIG_AQTITLE_DEMUXER 0
-#define CONFIG_ASF_DEMUXER 0
-#define CONFIG_ASF_O_DEMUXER 0
-#define CONFIG_ASS_DEMUXER 0
-#define CONFIG_AST_DEMUXER 0
-#define CONFIG_AU_DEMUXER 0
-#define CONFIG_AVI_DEMUXER 0
-#define CONFIG_AVISYNTH_DEMUXER 0
-#define CONFIG_AVR_DEMUXER 0
-#define CONFIG_AVS_DEMUXER 0
-#define CONFIG_BETHSOFTVID_DEMUXER 0
-#define CONFIG_BFI_DEMUXER 0
-#define CONFIG_BINTEXT_DEMUXER 0
-#define CONFIG_BINK_DEMUXER 0
-#define CONFIG_BIT_DEMUXER 0
-#define CONFIG_BMV_DEMUXER 0
-#define CONFIG_BFSTM_DEMUXER 0
-#define CONFIG_BRSTM_DEMUXER 0
-#define CONFIG_BOA_DEMUXER 0
-#define CONFIG_C93_DEMUXER 0
-#define CONFIG_CAF_DEMUXER 0
-#define CONFIG_CAVSVIDEO_DEMUXER 0
-#define CONFIG_CDG_DEMUXER 0
-#define CONFIG_CDXL_DEMUXER 0
-#define CONFIG_CINE_DEMUXER 0
-#define CONFIG_CONCAT_DEMUXER 0
-#define CONFIG_DATA_DEMUXER 0
-#define CONFIG_DAUD_DEMUXER 0
-#define CONFIG_DCSTR_DEMUXER 0
-#define CONFIG_DFA_DEMUXER 0
-#define CONFIG_DIRAC_DEMUXER 0
-#define CONFIG_DNXHD_DEMUXER 0
-#define CONFIG_DSF_DEMUXER 0
-#define CONFIG_DSICIN_DEMUXER 0
-#define CONFIG_DSS_DEMUXER 0
-#define CONFIG_DTS_DEMUXER 0
-#define CONFIG_DTSHD_DEMUXER 0
-#define CONFIG_DV_DEMUXER 0
-#define CONFIG_DVBSUB_DEMUXER 0
-#define CONFIG_DVBTXT_DEMUXER 0
-#define CONFIG_DXA_DEMUXER 0
-#define CONFIG_EA_DEMUXER 0
-#define CONFIG_EA_CDATA_DEMUXER 0
-#define CONFIG_EAC3_DEMUXER 0
-#define CONFIG_EPAF_DEMUXER 0
-#define CONFIG_FFM_DEMUXER 0
-#define CONFIG_FFMETADATA_DEMUXER 0
-#define CONFIG_FILMSTRIP_DEMUXER 0
-#define CONFIG_FLAC_DEMUXER 0
-#define CONFIG_FLIC_DEMUXER 0
-#define CONFIG_FLV_DEMUXER 0
-#define CONFIG_LIVE_FLV_DEMUXER 0
-#define CONFIG_FOURXM_DEMUXER 0
-#define CONFIG_FRM_DEMUXER 0
-#define CONFIG_FSB_DEMUXER 0
-#define CONFIG_G722_DEMUXER 0
-#define CONFIG_G723_1_DEMUXER 0
-#define CONFIG_G729_DEMUXER 0
-#define CONFIG_GENH_DEMUXER 0
-#define CONFIG_GIF_DEMUXER 0
-#define CONFIG_GSM_DEMUXER 0
-#define CONFIG_GXF_DEMUXER 0
-#define CONFIG_H261_DEMUXER 0
-#define CONFIG_H263_DEMUXER 0
-#define CONFIG_H264_DEMUXER 0
-#define CONFIG_HEVC_DEMUXER 0
-#define CONFIG_HLS_DEMUXER 0
-#define CONFIG_HNM_DEMUXER 0
-#define CONFIG_ICO_DEMUXER 0
-#define CONFIG_IDCIN_DEMUXER 0
-#define CONFIG_IDF_DEMUXER 0
-#define CONFIG_IFF_DEMUXER 0
-#define CONFIG_ILBC_DEMUXER 0
-#define CONFIG_IMAGE2_DEMUXER 0
-#define CONFIG_IMAGE2PIPE_DEMUXER 0
-#define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
-#define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
-#define CONFIG_INGENIENT_DEMUXER 0
-#define CONFIG_IPMOVIE_DEMUXER 0
-#define CONFIG_IRCAM_DEMUXER 0
-#define CONFIG_ISS_DEMUXER 0
-#define CONFIG_IV8_DEMUXER 0
-#define CONFIG_IVF_DEMUXER 0
-#define CONFIG_IVR_DEMUXER 0
-#define CONFIG_JACOSUB_DEMUXER 0
-#define CONFIG_JV_DEMUXER 0
-#define CONFIG_LMLM4_DEMUXER 0
-#define CONFIG_LOAS_DEMUXER 0
-#define CONFIG_LRC_DEMUXER 0
-#define CONFIG_LVF_DEMUXER 0
-#define CONFIG_LXF_DEMUXER 0
-#define CONFIG_M4V_DEMUXER 0
-#define CONFIG_MATROSKA_DEMUXER 0
-#define CONFIG_MGSTS_DEMUXER 0
-#define CONFIG_MICRODVD_DEMUXER 0
-#define CONFIG_MJPEG_DEMUXER 0
-#define CONFIG_MLP_DEMUXER 0
-#define CONFIG_MLV_DEMUXER 0
-#define CONFIG_MM_DEMUXER 0
-#define CONFIG_MMF_DEMUXER 0
-#define CONFIG_MOV_DEMUXER 0
-#define CONFIG_MP3_DEMUXER 0
-#define CONFIG_MPC_DEMUXER 0
-#define CONFIG_MPC8_DEMUXER 0
-#define CONFIG_MPEGPS_DEMUXER 0
-#define CONFIG_MPEGTS_DEMUXER 0
-#define CONFIG_MPEGTSRAW_DEMUXER 0
-#define CONFIG_MPEGVIDEO_DEMUXER 0
-#define CONFIG_MPJPEG_DEMUXER 0
-#define CONFIG_MPL2_DEMUXER 0
-#define CONFIG_MPSUB_DEMUXER 0
-#define CONFIG_MSF_DEMUXER 0
-#define CONFIG_MSNWC_TCP_DEMUXER 0
-#define CONFIG_MTAF_DEMUXER 0
-#define CONFIG_MTV_DEMUXER 0
-#define CONFIG_MUSX_DEMUXER 0
-#define CONFIG_MV_DEMUXER 0
-#define CONFIG_MVI_DEMUXER 0
-#define CONFIG_MXF_DEMUXER 0
-#define CONFIG_MXG_DEMUXER 0
-#define CONFIG_NC_DEMUXER 0
-#define CONFIG_NISTSPHERE_DEMUXER 0
-#define CONFIG_NSV_DEMUXER 0
-#define CONFIG_NUT_DEMUXER 0
-#define CONFIG_NUV_DEMUXER 0
-#define CONFIG_OGG_DEMUXER 0
-#define CONFIG_OMA_DEMUXER 0
-#define CONFIG_PAF_DEMUXER 0
-#define CONFIG_PCM_ALAW_DEMUXER 0
-#define CONFIG_PCM_MULAW_DEMUXER 0
-#define CONFIG_PCM_F64BE_DEMUXER 0
-#define CONFIG_PCM_F64LE_DEMUXER 0
-#define CONFIG_PCM_F32BE_DEMUXER 0
-#define CONFIG_PCM_F32LE_DEMUXER 0
-#define CONFIG_PCM_S32BE_DEMUXER 0
-#define CONFIG_PCM_S32LE_DEMUXER 0
-#define CONFIG_PCM_S24BE_DEMUXER 0
-#define CONFIG_PCM_S24LE_DEMUXER 0
-#define CONFIG_PCM_S16BE_DEMUXER 0
-#define CONFIG_PCM_S16LE_DEMUXER 0
-#define CONFIG_PCM_S8_DEMUXER 0
-#define CONFIG_PCM_U32BE_DEMUXER 0
-#define CONFIG_PCM_U32LE_DEMUXER 0
-#define CONFIG_PCM_U24BE_DEMUXER 0
-#define CONFIG_PCM_U24LE_DEMUXER 0
-#define CONFIG_PCM_U16BE_DEMUXER 0
-#define CONFIG_PCM_U16LE_DEMUXER 0
-#define CONFIG_PCM_U8_DEMUXER 0
-#define CONFIG_PJS_DEMUXER 0
-#define CONFIG_PMP_DEMUXER 0
-#define CONFIG_PVA_DEMUXER 0
-#define CONFIG_PVF_DEMUXER 0
-#define CONFIG_QCP_DEMUXER 0
-#define CONFIG_R3D_DEMUXER 0
-#define CONFIG_RAWVIDEO_DEMUXER 0
-#define CONFIG_REALTEXT_DEMUXER 0
-#define CONFIG_REDSPARK_DEMUXER 0
-#define CONFIG_RL2_DEMUXER 0
-#define CONFIG_RM_DEMUXER 0
-#define CONFIG_ROQ_DEMUXER 0
-#define CONFIG_RPL_DEMUXER 0
-#define CONFIG_RSD_DEMUXER 0
-#define CONFIG_RSO_DEMUXER 0
-#define CONFIG_RTP_DEMUXER 0
-#define CONFIG_RTSP_DEMUXER 0
-#define CONFIG_SAMI_DEMUXER 0
-#define CONFIG_SAP_DEMUXER 0
-#define CONFIG_SBG_DEMUXER 0
-#define CONFIG_SDP_DEMUXER 0
-#define CONFIG_SDR2_DEMUXER 0
-#define CONFIG_SEGAFILM_DEMUXER 0
-#define CONFIG_SHORTEN_DEMUXER 0
-#define CONFIG_SIFF_DEMUXER 0
-#define CONFIG_SLN_DEMUXER 0
-#define CONFIG_SMACKER_DEMUXER 0
-#define CONFIG_SMJPEG_DEMUXER 0
-#define CONFIG_SMUSH_DEMUXER 0
-#define CONFIG_SOL_DEMUXER 0
-#define CONFIG_SOX_DEMUXER 0
-#define CONFIG_SPDIF_DEMUXER 0
-#define CONFIG_SRT_DEMUXER 0
-#define CONFIG_STR_DEMUXER 0
-#define CONFIG_STL_DEMUXER 0
-#define CONFIG_SUBVIEWER1_DEMUXER 0
-#define CONFIG_SUBVIEWER_DEMUXER 0
-#define CONFIG_SUP_DEMUXER 0
-#define CONFIG_SVAG_DEMUXER 0
-#define CONFIG_SWF_DEMUXER 0
-#define CONFIG_TAK_DEMUXER 0
-#define CONFIG_TEDCAPTIONS_DEMUXER 0
-#define CONFIG_THP_DEMUXER 0
-#define CONFIG_THREEDOSTR_DEMUXER 0
-#define CONFIG_TIERTEXSEQ_DEMUXER 0
-#define CONFIG_TMV_DEMUXER 0
-#define CONFIG_TRUEHD_DEMUXER 0
-#define CONFIG_TTA_DEMUXER 0
-#define CONFIG_TXD_DEMUXER 0
-#define CONFIG_TTY_DEMUXER 0
-#define CONFIG_V210_DEMUXER 0
-#define CONFIG_V210X_DEMUXER 0
-#define CONFIG_VAG_DEMUXER 0
-#define CONFIG_VC1_DEMUXER 0
-#define CONFIG_VC1T_DEMUXER 0
-#define CONFIG_VIVO_DEMUXER 0
-#define CONFIG_VMD_DEMUXER 0
-#define CONFIG_VOBSUB_DEMUXER 0
-#define CONFIG_VOC_DEMUXER 0
-#define CONFIG_VPK_DEMUXER 0
-#define CONFIG_VPLAYER_DEMUXER 0
-#define CONFIG_VQF_DEMUXER 0
-#define CONFIG_W64_DEMUXER 0
-#define CONFIG_WAV_DEMUXER 0
-#define CONFIG_WC3_DEMUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
-#define CONFIG_WEBVTT_DEMUXER 0
-#define CONFIG_WSAUD_DEMUXER 0
-#define CONFIG_WSD_DEMUXER 0
-#define CONFIG_WSVQA_DEMUXER 0
-#define CONFIG_WTV_DEMUXER 0
-#define CONFIG_WVE_DEMUXER 0
-#define CONFIG_WV_DEMUXER 0
-#define CONFIG_XA_DEMUXER 0
-#define CONFIG_XBIN_DEMUXER 0
-#define CONFIG_XMV_DEMUXER 0
-#define CONFIG_XVAG_DEMUXER 0
-#define CONFIG_XWMA_DEMUXER 0
-#define CONFIG_YOP_DEMUXER 0
-#define CONFIG_YUV4MPEGPIPE_DEMUXER 0
-#define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
-#define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
-#define CONFIG_LIBGME_DEMUXER 0
-#define CONFIG_LIBMODPLUG_DEMUXER 0
-#define CONFIG_LIBNUT_DEMUXER 0
-#define CONFIG_LIBOPENMPT_DEMUXER 0
-#define CONFIG_A64MULTI_ENCODER 0
-#define CONFIG_A64MULTI5_ENCODER 0
-#define CONFIG_ALIAS_PIX_ENCODER 0
-#define CONFIG_AMV_ENCODER 0
-#define CONFIG_APNG_ENCODER 0
-#define CONFIG_ASV1_ENCODER 0
-#define CONFIG_ASV2_ENCODER 0
-#define CONFIG_AVRP_ENCODER 0
-#define CONFIG_AVUI_ENCODER 0
-#define CONFIG_AYUV_ENCODER 0
-#define CONFIG_BMP_ENCODER 0
-#define CONFIG_CINEPAK_ENCODER 0
-#define CONFIG_CLJR_ENCODER 0
-#define CONFIG_COMFORTNOISE_ENCODER 0
-#define CONFIG_DNXHD_ENCODER 0
-#define CONFIG_DPX_ENCODER 0
-#define CONFIG_DVVIDEO_ENCODER 0
-#define CONFIG_FFV1_ENCODER 0
-#define CONFIG_FFVHUFF_ENCODER 0
-#define CONFIG_FLASHSV_ENCODER 0
-#define CONFIG_FLASHSV2_ENCODER 0
-#define CONFIG_FLV_ENCODER 0
-#define CONFIG_GIF_ENCODER 0
-#define CONFIG_H261_ENCODER 0
-#define CONFIG_H263_ENCODER 0
-#define CONFIG_H263P_ENCODER 0
-#define CONFIG_HAP_ENCODER 0
-#define CONFIG_HUFFYUV_ENCODER 0
-#define CONFIG_JPEG2000_ENCODER 0
-#define CONFIG_JPEGLS_ENCODER 0
-#define CONFIG_LJPEG_ENCODER 0
-#define CONFIG_MJPEG_ENCODER 0
-#define CONFIG_MPEG1VIDEO_ENCODER 0
-#define CONFIG_MPEG2VIDEO_ENCODER 0
-#define CONFIG_MPEG4_ENCODER 0
-#define CONFIG_MSMPEG4V2_ENCODER 0
-#define CONFIG_MSMPEG4V3_ENCODER 0
-#define CONFIG_MSVIDEO1_ENCODER 0
-#define CONFIG_PAM_ENCODER 0
-#define CONFIG_PBM_ENCODER 0
-#define CONFIG_PCX_ENCODER 0
-#define CONFIG_PGM_ENCODER 0
-#define CONFIG_PGMYUV_ENCODER 0
-#define CONFIG_PNG_ENCODER 0
-#define CONFIG_PPM_ENCODER 0
-#define CONFIG_PRORES_ENCODER 0
-#define CONFIG_PRORES_AW_ENCODER 0
-#define CONFIG_PRORES_KS_ENCODER 0
-#define CONFIG_QTRLE_ENCODER 0
-#define CONFIG_R10K_ENCODER 0
-#define CONFIG_R210_ENCODER 0
-#define CONFIG_RAWVIDEO_ENCODER 0
-#define CONFIG_ROQ_ENCODER 0
-#define CONFIG_RV10_ENCODER 0
-#define CONFIG_RV20_ENCODER 0
-#define CONFIG_S302M_ENCODER 0
-#define CONFIG_SGI_ENCODER 0
-#define CONFIG_SNOW_ENCODER 0
-#define CONFIG_SUNRAST_ENCODER 0
-#define CONFIG_SVQ1_ENCODER 0
-#define CONFIG_TARGA_ENCODER 0
-#define CONFIG_TIFF_ENCODER 0
-#define CONFIG_UTVIDEO_ENCODER 0
-#define CONFIG_V210_ENCODER 0
-#define CONFIG_V308_ENCODER 0
-#define CONFIG_V408_ENCODER 0
-#define CONFIG_V410_ENCODER 0
-#define CONFIG_VC2_ENCODER 0
-#define CONFIG_WRAPPED_AVFRAME_ENCODER 0
-#define CONFIG_WMV1_ENCODER 0
-#define CONFIG_WMV2_ENCODER 0
-#define CONFIG_XBM_ENCODER 0
-#define CONFIG_XFACE_ENCODER 0
-#define CONFIG_XWD_ENCODER 0
-#define CONFIG_Y41P_ENCODER 0
-#define CONFIG_YUV4_ENCODER 0
-#define CONFIG_ZLIB_ENCODER 0
-#define CONFIG_ZMBV_ENCODER 0
-#define CONFIG_AAC_ENCODER 0
-#define CONFIG_AC3_ENCODER 0
-#define CONFIG_AC3_FIXED_ENCODER 0
-#define CONFIG_ALAC_ENCODER 0
-#define CONFIG_DCA_ENCODER 0
-#define CONFIG_EAC3_ENCODER 0
-#define CONFIG_FLAC_ENCODER 0
-#define CONFIG_G723_1_ENCODER 0
-#define CONFIG_MLP_ENCODER 0
-#define CONFIG_MP2_ENCODER 0
-#define CONFIG_MP2FIXED_ENCODER 0
-#define CONFIG_NELLYMOSER_ENCODER 0
-#define CONFIG_RA_144_ENCODER 0
-#define CONFIG_SONIC_ENCODER 0
-#define CONFIG_SONIC_LS_ENCODER 0
-#define CONFIG_TRUEHD_ENCODER 0
-#define CONFIG_TTA_ENCODER 0
-#define CONFIG_VORBIS_ENCODER 0
-#define CONFIG_WAVPACK_ENCODER 0
-#define CONFIG_WMAV1_ENCODER 0
-#define CONFIG_WMAV2_ENCODER 0
-#define CONFIG_PCM_ALAW_ENCODER 0
-#define CONFIG_PCM_F32BE_ENCODER 0
-#define CONFIG_PCM_F32LE_ENCODER 0
-#define CONFIG_PCM_F64BE_ENCODER 0
-#define CONFIG_PCM_F64LE_ENCODER 0
-#define CONFIG_PCM_MULAW_ENCODER 0
-#define CONFIG_PCM_S8_ENCODER 0
-#define CONFIG_PCM_S8_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16BE_ENCODER 0
-#define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S16LE_ENCODER 0
-#define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S24BE_ENCODER 0
-#define CONFIG_PCM_S24DAUD_ENCODER 0
-#define CONFIG_PCM_S24LE_ENCODER 0
-#define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S32BE_ENCODER 0
-#define CONFIG_PCM_S32LE_ENCODER 0
-#define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
-#define CONFIG_PCM_S64BE_ENCODER 0
-#define CONFIG_PCM_S64LE_ENCODER 0
-#define CONFIG_PCM_U8_ENCODER 0
-#define CONFIG_PCM_U16BE_ENCODER 0
-#define CONFIG_PCM_U16LE_ENCODER 0
-#define CONFIG_PCM_U24BE_ENCODER 0
-#define CONFIG_PCM_U24LE_ENCODER 0
-#define CONFIG_PCM_U32BE_ENCODER 0
-#define CONFIG_PCM_U32LE_ENCODER 0
-#define CONFIG_ROQ_DPCM_ENCODER 0
-#define CONFIG_ADPCM_ADX_ENCODER 0
-#define CONFIG_ADPCM_G722_ENCODER 0
-#define CONFIG_ADPCM_G726_ENCODER 0
-#define CONFIG_ADPCM_IMA_QT_ENCODER 0
-#define CONFIG_ADPCM_IMA_WAV_ENCODER 0
-#define CONFIG_ADPCM_MS_ENCODER 0
-#define CONFIG_ADPCM_SWF_ENCODER 0
-#define CONFIG_ADPCM_YAMAHA_ENCODER 0
-#define CONFIG_SSA_ENCODER 0
-#define CONFIG_ASS_ENCODER 0
-#define CONFIG_DVBSUB_ENCODER 0
-#define CONFIG_DVDSUB_ENCODER 0
-#define CONFIG_MOVTEXT_ENCODER 0
-#define CONFIG_SRT_ENCODER 0
-#define CONFIG_SUBRIP_ENCODER 0
-#define CONFIG_TEXT_ENCODER 0
-#define CONFIG_WEBVTT_ENCODER 0
-#define CONFIG_XSUB_ENCODER 0
-#define CONFIG_AAC_AT_ENCODER 0
-#define CONFIG_ALAC_AT_ENCODER 0
-#define CONFIG_ILBC_AT_ENCODER 0
-#define CONFIG_PCM_ALAW_AT_ENCODER 0
-#define CONFIG_PCM_MULAW_AT_ENCODER 0
-#define CONFIG_LIBFDK_AAC_ENCODER 0
-#define CONFIG_LIBGSM_ENCODER 0
-#define CONFIG_LIBGSM_MS_ENCODER 0
-#define CONFIG_LIBILBC_ENCODER 0
-#define CONFIG_LIBMP3LAME_ENCODER 0
-#define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
-#define CONFIG_LIBOPENJPEG_ENCODER 0
-#define CONFIG_LIBOPUS_ENCODER 0
-#define CONFIG_LIBSCHROEDINGER_ENCODER 0
-#define CONFIG_LIBSHINE_ENCODER 0
-#define CONFIG_LIBSPEEX_ENCODER 0
-#define CONFIG_LIBTHEORA_ENCODER 0
-#define CONFIG_LIBTWOLAME_ENCODER 0
-#define CONFIG_LIBVO_AMRWBENC_ENCODER 0
-#define CONFIG_LIBVORBIS_ENCODER 0
-#define CONFIG_LIBVPX_VP8_ENCODER 0
-#define CONFIG_LIBVPX_VP9_ENCODER 0
-#define CONFIG_LIBWAVPACK_ENCODER 0
-#define CONFIG_LIBWEBP_ANIM_ENCODER 0
-#define CONFIG_LIBWEBP_ENCODER 0
-#define CONFIG_LIBX262_ENCODER 0
-#define CONFIG_LIBX264_ENCODER 0
-#define CONFIG_LIBX264RGB_ENCODER 0
-#define CONFIG_LIBX265_ENCODER 0
-#define CONFIG_LIBXAVS_ENCODER 0
-#define CONFIG_LIBXVID_ENCODER 0
-#define CONFIG_LIBOPENH264_ENCODER 0
-#define CONFIG_H264_NVENC_ENCODER 0
-#define CONFIG_H264_OMX_ENCODER 0
-#define CONFIG_H264_QSV_ENCODER 0
-#define CONFIG_H264_VAAPI_ENCODER 0
-#define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
-#define CONFIG_NVENC_ENCODER 0
-#define CONFIG_NVENC_H264_ENCODER 0
-#define CONFIG_NVENC_HEVC_ENCODER 0
-#define CONFIG_HEVC_NVENC_ENCODER 0
-#define CONFIG_HEVC_QSV_ENCODER 0
-#define CONFIG_HEVC_VAAPI_ENCODER 0
-#define CONFIG_LIBKVAZAAR_ENCODER 0
-#define CONFIG_MJPEG_VAAPI_ENCODER 0
-#define CONFIG_MPEG2_QSV_ENCODER 0
-#define CONFIG_ABENCH_FILTER 0
-#define CONFIG_ACOMPRESSOR_FILTER 0
-#define CONFIG_ACROSSFADE_FILTER 0
-#define CONFIG_ACRUSHER_FILTER 0
-#define CONFIG_ADELAY_FILTER 0
-#define CONFIG_AECHO_FILTER 0
-#define CONFIG_AEMPHASIS_FILTER 0
-#define CONFIG_AEVAL_FILTER 0
-#define CONFIG_AFADE_FILTER 0
-#define CONFIG_AFFTFILT_FILTER 0
-#define CONFIG_AFORMAT_FILTER 0
-#define CONFIG_AGATE_FILTER 0
-#define CONFIG_AINTERLEAVE_FILTER 0
-#define CONFIG_ALIMITER_FILTER 0
-#define CONFIG_ALLPASS_FILTER 0
-#define CONFIG_ALOOP_FILTER 0
-#define CONFIG_AMERGE_FILTER 0
-#define CONFIG_AMETADATA_FILTER 0
-#define CONFIG_AMIX_FILTER 0
-#define CONFIG_ANEQUALIZER_FILTER 0
-#define CONFIG_ANULL_FILTER 0
-#define CONFIG_APAD_FILTER 0
-#define CONFIG_APERMS_FILTER 0
-#define CONFIG_APHASER_FILTER 0
-#define CONFIG_APULSATOR_FILTER 0
-#define CONFIG_AREALTIME_FILTER 0
-#define CONFIG_ARESAMPLE_FILTER 0
-#define CONFIG_AREVERSE_FILTER 0
-#define CONFIG_ASELECT_FILTER 0
-#define CONFIG_ASENDCMD_FILTER 0
-#define CONFIG_ASETNSAMPLES_FILTER 0
-#define CONFIG_ASETPTS_FILTER 0
-#define CONFIG_ASETRATE_FILTER 0
-#define CONFIG_ASETTB_FILTER 0
-#define CONFIG_ASHOWINFO_FILTER 0
-#define CONFIG_ASIDEDATA_FILTER 0
-#define CONFIG_ASPLIT_FILTER 0
-#define CONFIG_ASTATS_FILTER 0
-#define CONFIG_ASTREAMSELECT_FILTER 0
-#define CONFIG_ASYNCTS_FILTER 0
-#define CONFIG_ATEMPO_FILTER 0
-#define CONFIG_ATRIM_FILTER 0
-#define CONFIG_AZMQ_FILTER 0
-#define CONFIG_BANDPASS_FILTER 0
-#define CONFIG_BANDREJECT_FILTER 0
-#define CONFIG_BASS_FILTER 0
-#define CONFIG_BIQUAD_FILTER 0
-#define CONFIG_BS2B_FILTER 0
-#define CONFIG_CHANNELMAP_FILTER 0
-#define CONFIG_CHANNELSPLIT_FILTER 0
-#define CONFIG_CHORUS_FILTER 0
-#define CONFIG_COMPAND_FILTER 0
-#define CONFIG_COMPENSATIONDELAY_FILTER 0
-#define CONFIG_CRYSTALIZER_FILTER 0
-#define CONFIG_DCSHIFT_FILTER 0
-#define CONFIG_DYNAUDNORM_FILTER 0
-#define CONFIG_EARWAX_FILTER 0
-#define CONFIG_EBUR128_FILTER 0
-#define CONFIG_EQUALIZER_FILTER 0
-#define CONFIG_EXTRASTEREO_FILTER 0
-#define CONFIG_FIREQUALIZER_FILTER 0
-#define CONFIG_FLANGER_FILTER 0
-#define CONFIG_HDCD_FILTER 0
-#define CONFIG_HIGHPASS_FILTER 0
-#define CONFIG_JOIN_FILTER 0
-#define CONFIG_LADSPA_FILTER 0
-#define CONFIG_LOUDNORM_FILTER 0
-#define CONFIG_LOWPASS_FILTER 0
-#define CONFIG_PAN_FILTER 0
-#define CONFIG_REPLAYGAIN_FILTER 0
-#define CONFIG_RESAMPLE_FILTER 0
-#define CONFIG_RUBBERBAND_FILTER 0
-#define CONFIG_SIDECHAINCOMPRESS_FILTER 0
-#define CONFIG_SIDECHAINGATE_FILTER 0
-#define CONFIG_SILENCEDETECT_FILTER 0
-#define CONFIG_SILENCEREMOVE_FILTER 0
-#define CONFIG_SOFALIZER_FILTER 0
-#define CONFIG_STEREOTOOLS_FILTER 0
-#define CONFIG_STEREOWIDEN_FILTER 0
-#define CONFIG_TREBLE_FILTER 0
-#define CONFIG_TREMOLO_FILTER 0
-#define CONFIG_VIBRATO_FILTER 0
-#define CONFIG_VOLUME_FILTER 0
-#define CONFIG_VOLUMEDETECT_FILTER 0
-#define CONFIG_AEVALSRC_FILTER 0
-#define CONFIG_ANOISESRC_FILTER 0
-#define CONFIG_ANULLSRC_FILTER 0
-#define CONFIG_FLITE_FILTER 0
-#define CONFIG_SINE_FILTER 0
-#define CONFIG_ANULLSINK_FILTER 0
-#define CONFIG_ALPHAEXTRACT_FILTER 0
-#define CONFIG_ALPHAMERGE_FILTER 0
-#define CONFIG_ASS_FILTER 0
-#define CONFIG_ATADENOISE_FILTER 0
-#define CONFIG_AVGBLUR_FILTER 0
-#define CONFIG_BBOX_FILTER 0
-#define CONFIG_BENCH_FILTER 0
-#define CONFIG_BITPLANENOISE_FILTER 0
-#define CONFIG_BLACKDETECT_FILTER 0
-#define CONFIG_BLACKFRAME_FILTER 0
-#define CONFIG_BLEND_FILTER 0
-#define CONFIG_BOXBLUR_FILTER 0
-#define CONFIG_BWDIF_FILTER 0
-#define CONFIG_CHROMAKEY_FILTER 0
-#define CONFIG_CIESCOPE_FILTER 0
-#define CONFIG_CODECVIEW_FILTER 0
-#define CONFIG_COLORBALANCE_FILTER 0
-#define CONFIG_COLORCHANNELMIXER_FILTER 0
-#define CONFIG_COLORKEY_FILTER 0
-#define CONFIG_COLORLEVELS_FILTER 0
-#define CONFIG_COLORMATRIX_FILTER 0
-#define CONFIG_COLORSPACE_FILTER 0
-#define CONFIG_CONVOLUTION_FILTER 0
-#define CONFIG_COPY_FILTER 0
-#define CONFIG_COREIMAGE_FILTER 0
-#define CONFIG_COVER_RECT_FILTER 0
-#define CONFIG_CROP_FILTER 0
-#define CONFIG_CROPDETECT_FILTER 0
-#define CONFIG_CURVES_FILTER 0
-#define CONFIG_DATASCOPE_FILTER 0
-#define CONFIG_DCTDNOIZ_FILTER 0
-#define CONFIG_DEBAND_FILTER 0
-#define CONFIG_DECIMATE_FILTER 0
-#define CONFIG_DEFLATE_FILTER 0
-#define CONFIG_DEJUDDER_FILTER 0
-#define CONFIG_DELOGO_FILTER 0
-#define CONFIG_DESHAKE_FILTER 0
-#define CONFIG_DETELECINE_FILTER 0
-#define CONFIG_DILATION_FILTER 0
-#define CONFIG_DISPLACE_FILTER 0
-#define CONFIG_DRAWBOX_FILTER 0
-#define CONFIG_DRAWGRAPH_FILTER 0
-#define CONFIG_DRAWGRID_FILTER 0
-#define CONFIG_DRAWTEXT_FILTER 0
-#define CONFIG_EDGEDETECT_FILTER 0
-#define CONFIG_ELBG_FILTER 0
-#define CONFIG_EQ_FILTER 0
-#define CONFIG_EROSION_FILTER 0
-#define CONFIG_EXTRACTPLANES_FILTER 0
-#define CONFIG_FADE_FILTER 0
-#define CONFIG_FFTFILT_FILTER 0
-#define CONFIG_FIELD_FILTER 0
-#define CONFIG_FIELDHINT_FILTER 0
-#define CONFIG_FIELDMATCH_FILTER 0
-#define CONFIG_FIELDORDER_FILTER 0
-#define CONFIG_FIND_RECT_FILTER 0
-#define CONFIG_FORMAT_FILTER 0
-#define CONFIG_FPS_FILTER 0
-#define CONFIG_FRAMEPACK_FILTER 0
-#define CONFIG_FRAMERATE_FILTER 0
-#define CONFIG_FRAMESTEP_FILTER 0
-#define CONFIG_FREI0R_FILTER 0
-#define CONFIG_FSPP_FILTER 0
-#define CONFIG_GBLUR_FILTER 0
-#define CONFIG_GEQ_FILTER 0
-#define CONFIG_GRADFUN_FILTER 0
-#define CONFIG_HALDCLUT_FILTER 0
-#define CONFIG_HFLIP_FILTER 0
-#define CONFIG_HISTEQ_FILTER 0
-#define CONFIG_HISTOGRAM_FILTER 0
-#define CONFIG_HQDN3D_FILTER 0
-#define CONFIG_HQX_FILTER 0
-#define CONFIG_HSTACK_FILTER 0
-#define CONFIG_HUE_FILTER 0
-#define CONFIG_HWDOWNLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_FILTER 0
-#define CONFIG_HWUPLOAD_CUDA_FILTER 0
-#define CONFIG_HYSTERESIS_FILTER 0
-#define CONFIG_IDET_FILTER 0
-#define CONFIG_IL_FILTER 0
-#define CONFIG_INFLATE_FILTER 0
-#define CONFIG_INTERLACE_FILTER 0
-#define CONFIG_INTERLEAVE_FILTER 0
-#define CONFIG_KERNDEINT_FILTER 0
-#define CONFIG_LENSCORRECTION_FILTER 0
-#define CONFIG_LOOP_FILTER 0
-#define CONFIG_LUT_FILTER 0
-#define CONFIG_LUT2_FILTER 0
-#define CONFIG_LUT3D_FILTER 0
-#define CONFIG_LUTRGB_FILTER 0
-#define CONFIG_LUTYUV_FILTER 0
-#define CONFIG_MASKEDCLAMP_FILTER 0
-#define CONFIG_MASKEDMERGE_FILTER 0
-#define CONFIG_MCDEINT_FILTER 0
-#define CONFIG_MERGEPLANES_FILTER 0
-#define CONFIG_MESTIMATE_FILTER 0
-#define CONFIG_METADATA_FILTER 0
-#define CONFIG_MINTERPOLATE_FILTER 0
-#define CONFIG_MPDECIMATE_FILTER 0
-#define CONFIG_NEGATE_FILTER 0
-#define CONFIG_NLMEANS_FILTER 0
-#define CONFIG_NNEDI_FILTER 0
-#define CONFIG_NOFORMAT_FILTER 0
-#define CONFIG_NOISE_FILTER 0
-#define CONFIG_NULL_FILTER 0
-#define CONFIG_OCR_FILTER 0
-#define CONFIG_OCV_FILTER 0
-#define CONFIG_OVERLAY_FILTER 0
-#define CONFIG_OWDENOISE_FILTER 0
-#define CONFIG_PAD_FILTER 0
-#define CONFIG_PALETTEGEN_FILTER 0
-#define CONFIG_PALETTEUSE_FILTER 0
-#define CONFIG_PERMS_FILTER 0
-#define CONFIG_PERSPECTIVE_FILTER 0
-#define CONFIG_PHASE_FILTER 0
-#define CONFIG_PIXDESCTEST_FILTER 0
-#define CONFIG_PP_FILTER 0
-#define CONFIG_PP7_FILTER 0
-#define CONFIG_PREWITT_FILTER 0
-#define CONFIG_PSNR_FILTER 0
-#define CONFIG_PULLUP_FILTER 0
-#define CONFIG_QP_FILTER 0
-#define CONFIG_RANDOM_FILTER 0
-#define CONFIG_READVITC_FILTER 0
-#define CONFIG_REALTIME_FILTER 0
-#define CONFIG_REMAP_FILTER 0
-#define CONFIG_REMOVEGRAIN_FILTER 0
-#define CONFIG_REMOVELOGO_FILTER 0
-#define CONFIG_REPEATFIELDS_FILTER 0
-#define CONFIG_REVERSE_FILTER 0
-#define CONFIG_ROTATE_FILTER 0
-#define CONFIG_SAB_FILTER 0
-#define CONFIG_SCALE_FILTER 0
-#define CONFIG_SCALE_NPP_FILTER 0
-#define CONFIG_SCALE_VAAPI_FILTER 0
-#define CONFIG_SCALE2REF_FILTER 0
-#define CONFIG_SELECT_FILTER 0
-#define CONFIG_SELECTIVECOLOR_FILTER 0
-#define CONFIG_SENDCMD_FILTER 0
-#define CONFIG_SEPARATEFIELDS_FILTER 0
-#define CONFIG_SETDAR_FILTER 0
-#define CONFIG_SETFIELD_FILTER 0
-#define CONFIG_SETPTS_FILTER 0
-#define CONFIG_SETSAR_FILTER 0
-#define CONFIG_SETTB_FILTER 0
-#define CONFIG_SHOWINFO_FILTER 0
-#define CONFIG_SHOWPALETTE_FILTER 0
-#define CONFIG_SHUFFLEFRAMES_FILTER 0
-#define CONFIG_SHUFFLEPLANES_FILTER 0
-#define CONFIG_SIDEDATA_FILTER 0
-#define CONFIG_SIGNALSTATS_FILTER 0
-#define CONFIG_SMARTBLUR_FILTER 0
-#define CONFIG_SOBEL_FILTER 0
-#define CONFIG_SPLIT_FILTER 0
-#define CONFIG_SPP_FILTER 0
-#define CONFIG_SSIM_FILTER 0
-#define CONFIG_STEREO3D_FILTER 0
-#define CONFIG_STREAMSELECT_FILTER 0
-#define CONFIG_SUBTITLES_FILTER 0
-#define CONFIG_SUPER2XSAI_FILTER 0
-#define CONFIG_SWAPRECT_FILTER 0
-#define CONFIG_SWAPUV_FILTER 0
-#define CONFIG_TBLEND_FILTER 0
-#define CONFIG_TELECINE_FILTER 0
-#define CONFIG_THUMBNAIL_FILTER 0
-#define CONFIG_TILE_FILTER 0
-#define CONFIG_TINTERLACE_FILTER 0
-#define CONFIG_TRANSPOSE_FILTER 0
-#define CONFIG_TRIM_FILTER 0
-#define CONFIG_UNSHARP_FILTER 0
-#define CONFIG_USPP_FILTER 0
-#define CONFIG_VAGUEDENOISER_FILTER 0
-#define CONFIG_VECTORSCOPE_FILTER 0
-#define CONFIG_VFLIP_FILTER 0
-#define CONFIG_VIDSTABDETECT_FILTER 0
-#define CONFIG_VIDSTABTRANSFORM_FILTER 0
-#define CONFIG_VIGNETTE_FILTER 0
-#define CONFIG_VSTACK_FILTER 0
-#define CONFIG_W3FDIF_FILTER 0
-#define CONFIG_WAVEFORM_FILTER 0
-#define CONFIG_WEAVE_FILTER 0
-#define CONFIG_XBR_FILTER 0
-#define CONFIG_YADIF_FILTER 0
-#define CONFIG_ZMQ_FILTER 0
-#define CONFIG_ZOOMPAN_FILTER 0
-#define CONFIG_ZSCALE_FILTER 0
-#define CONFIG_ALLRGB_FILTER 0
-#define CONFIG_ALLYUV_FILTER 0
-#define CONFIG_CELLAUTO_FILTER 0
-#define CONFIG_COLOR_FILTER 0
-#define CONFIG_COREIMAGESRC_FILTER 0
-#define CONFIG_FREI0R_SRC_FILTER 0
-#define CONFIG_HALDCLUTSRC_FILTER 0
-#define CONFIG_LIFE_FILTER 0
-#define CONFIG_MANDELBROT_FILTER 0
-#define CONFIG_MPTESTSRC_FILTER 0
-#define CONFIG_NULLSRC_FILTER 0
-#define CONFIG_RGBTESTSRC_FILTER 0
-#define CONFIG_SMPTEBARS_FILTER 0
-#define CONFIG_SMPTEHDBARS_FILTER 0
-#define CONFIG_TESTSRC_FILTER 0
-#define CONFIG_TESTSRC2_FILTER 0
-#define CONFIG_YUVTESTSRC_FILTER 0
-#define CONFIG_NULLSINK_FILTER 0
-#define CONFIG_ADRAWGRAPH_FILTER 0
-#define CONFIG_AHISTOGRAM_FILTER 0
-#define CONFIG_APHASEMETER_FILTER 0
-#define CONFIG_AVECTORSCOPE_FILTER 0
-#define CONFIG_CONCAT_FILTER 0
-#define CONFIG_SHOWCQT_FILTER 0
-#define CONFIG_SHOWFREQS_FILTER 0
-#define CONFIG_SHOWSPECTRUM_FILTER 0
-#define CONFIG_SHOWSPECTRUMPIC_FILTER 0
-#define CONFIG_SHOWVOLUME_FILTER 0
-#define CONFIG_SHOWWAVES_FILTER 0
-#define CONFIG_SHOWWAVESPIC_FILTER 0
-#define CONFIG_SPECTRUMSYNTH_FILTER 0
-#define CONFIG_AMOVIE_FILTER 0
-#define CONFIG_MOVIE_FILTER 0
-#define CONFIG_H263_CUVID_HWACCEL 0
-#define CONFIG_H263_VAAPI_HWACCEL 0
-#define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_H264_CUVID_HWACCEL 0
-#define CONFIG_H264_D3D11VA_HWACCEL 0
-#define CONFIG_H264_DXVA2_HWACCEL 0
-#define CONFIG_H264_MEDIACODEC_HWACCEL 0
-#define CONFIG_H264_MMAL_HWACCEL 0
-#define CONFIG_H264_QSV_HWACCEL 0
-#define CONFIG_H264_VAAPI_HWACCEL 0
-#define CONFIG_H264_VDA_HWACCEL 0
-#define CONFIG_H264_VDA_OLD_HWACCEL 0
-#define CONFIG_H264_VDPAU_HWACCEL 0
-#define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_HEVC_CUVID_HWACCEL 0
-#define CONFIG_HEVC_D3D11VA_HWACCEL 0
-#define CONFIG_HEVC_DXVA2_HWACCEL 0
-#define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
-#define CONFIG_HEVC_QSV_HWACCEL 0
-#define CONFIG_HEVC_VAAPI_HWACCEL 0
-#define CONFIG_HEVC_VDPAU_HWACCEL 0
-#define CONFIG_MJPEG_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_CUVID_HWACCEL 0
-#define CONFIG_MPEG1_XVMC_HWACCEL 0
-#define CONFIG_MPEG1_VDPAU_HWACCEL 0
-#define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG2_CUVID_HWACCEL 0
-#define CONFIG_MPEG2_XVMC_HWACCEL 0
-#define CONFIG_MPEG2_D3D11VA_HWACCEL 0
-#define CONFIG_MPEG2_DXVA2_HWACCEL 0
-#define CONFIG_MPEG2_MMAL_HWACCEL 0
-#define CONFIG_MPEG2_QSV_HWACCEL 0
-#define CONFIG_MPEG2_VAAPI_HWACCEL 0
-#define CONFIG_MPEG2_VDPAU_HWACCEL 0
-#define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_MPEG4_CUVID_HWACCEL 0
-#define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
-#define CONFIG_MPEG4_MMAL_HWACCEL 0
-#define CONFIG_MPEG4_VAAPI_HWACCEL 0
-#define CONFIG_MPEG4_VDPAU_HWACCEL 0
-#define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
-#define CONFIG_VC1_CUVID_HWACCEL 0
-#define CONFIG_VC1_D3D11VA_HWACCEL 0
-#define CONFIG_VC1_DXVA2_HWACCEL 0
-#define CONFIG_VC1_VAAPI_HWACCEL 0
-#define CONFIG_VC1_VDPAU_HWACCEL 0
-#define CONFIG_VC1_MMAL_HWACCEL 0
-#define CONFIG_VC1_QSV_HWACCEL 0
-#define CONFIG_VP8_CUVID_HWACCEL 0
-#define CONFIG_VP8_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_CUVID_HWACCEL 0
-#define CONFIG_VP9_D3D11VA_HWACCEL 0
-#define CONFIG_VP9_DXVA2_HWACCEL 0
-#define CONFIG_VP9_MEDIACODEC_HWACCEL 0
-#define CONFIG_VP9_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_D3D11VA_HWACCEL 0
-#define CONFIG_WMV3_DXVA2_HWACCEL 0
-#define CONFIG_WMV3_VAAPI_HWACCEL 0
-#define CONFIG_WMV3_VDPAU_HWACCEL 0
-#define CONFIG_ALSA_INDEV 0
-#define CONFIG_AVFOUNDATION_INDEV 0
-#define CONFIG_BKTR_INDEV 0
-#define CONFIG_DECKLINK_INDEV 0
-#define CONFIG_DSHOW_INDEV 0
-#define CONFIG_DV1394_INDEV 0
-#define CONFIG_FBDEV_INDEV 0
-#define CONFIG_GDIGRAB_INDEV 0
-#define CONFIG_IEC61883_INDEV 0
-#define CONFIG_JACK_INDEV 0
-#define CONFIG_LAVFI_INDEV 0
-#define CONFIG_OPENAL_INDEV 0
-#define CONFIG_OSS_INDEV 0
-#define CONFIG_PULSE_INDEV 0
-#define CONFIG_QTKIT_INDEV 0
-#define CONFIG_SNDIO_INDEV 0
-#define CONFIG_V4L2_INDEV 0
-#define CONFIG_VFWCAP_INDEV 0
-#define CONFIG_X11GRAB_INDEV 0
-#define CONFIG_X11GRAB_XCB_INDEV 0
-#define CONFIG_LIBCDIO_INDEV 0
-#define CONFIG_LIBDC1394_INDEV 0
-#define CONFIG_A64_MUXER 0
-#define CONFIG_AC3_MUXER 0
-#define CONFIG_ADTS_MUXER 0
-#define CONFIG_ADX_MUXER 0
-#define CONFIG_AIFF_MUXER 0
-#define CONFIG_AMR_MUXER 0
-#define CONFIG_APNG_MUXER 0
-#define CONFIG_ASF_MUXER 0
-#define CONFIG_ASS_MUXER 0
-#define CONFIG_AST_MUXER 0
-#define CONFIG_ASF_STREAM_MUXER 0
-#define CONFIG_AU_MUXER 0
-#define CONFIG_AVI_MUXER 0
-#define CONFIG_AVM2_MUXER 0
-#define CONFIG_BIT_MUXER 0
-#define CONFIG_CAF_MUXER 0
-#define CONFIG_CAVSVIDEO_MUXER 0
-#define CONFIG_CRC_MUXER 0
-#define CONFIG_DASH_MUXER 0
-#define CONFIG_DATA_MUXER 0
-#define CONFIG_DAUD_MUXER 0
-#define CONFIG_DIRAC_MUXER 0
-#define CONFIG_DNXHD_MUXER 0
-#define CONFIG_DTS_MUXER 0
-#define CONFIG_DV_MUXER 0
-#define CONFIG_EAC3_MUXER 0
-#define CONFIG_F4V_MUXER 0
-#define CONFIG_FFM_MUXER 0
-#define CONFIG_FFMETADATA_MUXER 0
-#define CONFIG_FIFO_MUXER 0
-#define CONFIG_FILMSTRIP_MUXER 0
-#define CONFIG_FLAC_MUXER 0
-#define CONFIG_FLV_MUXER 0
-#define CONFIG_FRAMECRC_MUXER 0
-#define CONFIG_FRAMEHASH_MUXER 0
-#define CONFIG_FRAMEMD5_MUXER 0
-#define CONFIG_G722_MUXER 0
-#define CONFIG_G723_1_MUXER 0
-#define CONFIG_GIF_MUXER 0
-#define CONFIG_GSM_MUXER 0
-#define CONFIG_GXF_MUXER 0
-#define CONFIG_H261_MUXER 0
-#define CONFIG_H263_MUXER 0
-#define CONFIG_H264_MUXER 0
-#define CONFIG_HASH_MUXER 0
-#define CONFIG_HDS_MUXER 0
-#define CONFIG_HEVC_MUXER 0
-#define CONFIG_HLS_MUXER 0
-#define CONFIG_ICO_MUXER 0
-#define CONFIG_ILBC_MUXER 0
-#define CONFIG_IMAGE2_MUXER 0
-#define CONFIG_IMAGE2PIPE_MUXER 0
-#define CONFIG_IPOD_MUXER 0
-#define CONFIG_IRCAM_MUXER 0
-#define CONFIG_ISMV_MUXER 0
-#define CONFIG_IVF_MUXER 0
-#define CONFIG_JACOSUB_MUXER 0
-#define CONFIG_LATM_MUXER 0
-#define CONFIG_LRC_MUXER 0
-#define CONFIG_M4V_MUXER 0
-#define CONFIG_MD5_MUXER 0
-#define CONFIG_MATROSKA_MUXER 0
-#define CONFIG_MATROSKA_AUDIO_MUXER 0
-#define CONFIG_MICRODVD_MUXER 0
-#define CONFIG_MJPEG_MUXER 0
-#define CONFIG_MLP_MUXER 0
-#define CONFIG_MMF_MUXER 0
-#define CONFIG_MOV_MUXER 0
-#define CONFIG_MP2_MUXER 0
-#define CONFIG_MP3_MUXER 0
-#define CONFIG_MP4_MUXER 0
-#define CONFIG_MPEG1SYSTEM_MUXER 0
-#define CONFIG_MPEG1VCD_MUXER 0
-#define CONFIG_MPEG1VIDEO_MUXER 0
-#define CONFIG_MPEG2DVD_MUXER 0
-#define CONFIG_MPEG2SVCD_MUXER 0
-#define CONFIG_MPEG2VIDEO_MUXER 0
-#define CONFIG_MPEG2VOB_MUXER 0
-#define CONFIG_MPEGTS_MUXER 0
-#define CONFIG_MPJPEG_MUXER 0
-#define CONFIG_MXF_MUXER 0
-#define CONFIG_MXF_D10_MUXER 0
-#define CONFIG_MXF_OPATOM_MUXER 0
-#define CONFIG_NULL_MUXER 0
-#define CONFIG_NUT_MUXER 0
-#define CONFIG_OGA_MUXER 0
-#define CONFIG_OGG_MUXER 0
-#define CONFIG_OGV_MUXER 0
-#define CONFIG_OMA_MUXER 0
-#define CONFIG_OPUS_MUXER 0
-#define CONFIG_PCM_ALAW_MUXER 0
-#define CONFIG_PCM_MULAW_MUXER 0
-#define CONFIG_PCM_F64BE_MUXER 0
-#define CONFIG_PCM_F64LE_MUXER 0
-#define CONFIG_PCM_F32BE_MUXER 0
-#define CONFIG_PCM_F32LE_MUXER 0
-#define CONFIG_PCM_S32BE_MUXER 0
-#define CONFIG_PCM_S32LE_MUXER 0
-#define CONFIG_PCM_S24BE_MUXER 0
-#define CONFIG_PCM_S24LE_MUXER 0
-#define CONFIG_PCM_S16BE_MUXER 0
-#define CONFIG_PCM_S16LE_MUXER 0
-#define CONFIG_PCM_S8_MUXER 0
-#define CONFIG_PCM_U32BE_MUXER 0
-#define CONFIG_PCM_U32LE_MUXER 0
-#define CONFIG_PCM_U24BE_MUXER 0
-#define CONFIG_PCM_U24LE_MUXER 0
-#define CONFIG_PCM_U16BE_MUXER 0
-#define CONFIG_PCM_U16LE_MUXER 0
-#define CONFIG_PCM_U8_MUXER 0
-#define CONFIG_PSP_MUXER 0
-#define CONFIG_RAWVIDEO_MUXER 0
-#define CONFIG_RM_MUXER 0
-#define CONFIG_ROQ_MUXER 0
-#define CONFIG_RSO_MUXER 0
-#define CONFIG_RTP_MUXER 0
-#define CONFIG_RTP_MPEGTS_MUXER 0
-#define CONFIG_RTSP_MUXER 0
-#define CONFIG_SAP_MUXER 0
-#define CONFIG_SEGMENT_MUXER 0
-#define CONFIG_STREAM_SEGMENT_MUXER 0
-#define CONFIG_SINGLEJPEG_MUXER 0
-#define CONFIG_SMJPEG_MUXER 0
-#define CONFIG_SMOOTHSTREAMING_MUXER 0
-#define CONFIG_SOX_MUXER 0
-#define CONFIG_SPX_MUXER 0
-#define CONFIG_SPDIF_MUXER 0
-#define CONFIG_SRT_MUXER 0
-#define CONFIG_SWF_MUXER 0
-#define CONFIG_TEE_MUXER 0
-#define CONFIG_TG2_MUXER 0
-#define CONFIG_TGP_MUXER 0
-#define CONFIG_MKVTIMESTAMP_V2_MUXER 0
-#define CONFIG_TRUEHD_MUXER 0
-#define CONFIG_TTA_MUXER 0
-#define CONFIG_UNCODEDFRAMECRC_MUXER 0
-#define CONFIG_VC1_MUXER 0
-#define CONFIG_VC1T_MUXER 0
-#define CONFIG_VOC_MUXER 0
-#define CONFIG_W64_MUXER 0
-#define CONFIG_WAV_MUXER 0
-#define CONFIG_WEBM_MUXER 0
-#define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
-#define CONFIG_WEBM_CHUNK_MUXER 0
-#define CONFIG_WEBP_MUXER 0
-#define CONFIG_WEBVTT_MUXER 0
-#define CONFIG_WTV_MUXER 0
-#define CONFIG_WV_MUXER 0
-#define CONFIG_YUV4MPEGPIPE_MUXER 0
-#define CONFIG_CHROMAPRINT_MUXER 0
-#define CONFIG_LIBNUT_MUXER 0
-#define CONFIG_ALSA_OUTDEV 0
-#define CONFIG_CACA_OUTDEV 0
-#define CONFIG_DECKLINK_OUTDEV 0
-#define CONFIG_FBDEV_OUTDEV 0
-#define CONFIG_OPENGL_OUTDEV 0
-#define CONFIG_OSS_OUTDEV 0
-#define CONFIG_PULSE_OUTDEV 0
-#define CONFIG_SDL2_OUTDEV 0
-#define CONFIG_SNDIO_OUTDEV 0
-#define CONFIG_V4L2_OUTDEV 0
-#define CONFIG_XV_OUTDEV 0
-#define CONFIG_AAC_PARSER 0
-#define CONFIG_AAC_LATM_PARSER 0
-#define CONFIG_AC3_PARSER 0
-#define CONFIG_ADX_PARSER 0
-#define CONFIG_BMP_PARSER 0
-#define CONFIG_CAVSVIDEO_PARSER 0
-#define CONFIG_COOK_PARSER 0
-#define CONFIG_DCA_PARSER 0
-#define CONFIG_DIRAC_PARSER 0
-#define CONFIG_DNXHD_PARSER 0
-#define CONFIG_DPX_PARSER 0
-#define CONFIG_DVAUDIO_PARSER 0
-#define CONFIG_DVBSUB_PARSER 0
-#define CONFIG_DVDSUB_PARSER 0
-#define CONFIG_DVD_NAV_PARSER 0
-#define CONFIG_FLAC_PARSER 1
-#define CONFIG_G729_PARSER 0
-#define CONFIG_GSM_PARSER 0
-#define CONFIG_H261_PARSER 0
-#define CONFIG_H263_PARSER 0
-#define CONFIG_H264_PARSER 0
-#define CONFIG_HEVC_PARSER 0
-#define CONFIG_MJPEG_PARSER 0
-#define CONFIG_MLP_PARSER 0
-#define CONFIG_MPEG4VIDEO_PARSER 0
-#define CONFIG_MPEGAUDIO_PARSER 0
-#define CONFIG_MPEGVIDEO_PARSER 0
-#define CONFIG_OPUS_PARSER 0
-#define CONFIG_PNG_PARSER 0
-#define CONFIG_PNM_PARSER 0
-#define CONFIG_RV30_PARSER 0
-#define CONFIG_RV40_PARSER 0
-#define CONFIG_TAK_PARSER 0
-#define CONFIG_VC1_PARSER 0
-#define CONFIG_VORBIS_PARSER 0
-#define CONFIG_VP3_PARSER 0
+#define CONFIG_FLAC_PARSER 0
#define CONFIG_VP8_PARSER 1
#define CONFIG_VP9_PARSER 1
-#define CONFIG_ASYNC_PROTOCOL 0
-#define CONFIG_BLURAY_PROTOCOL 0
-#define CONFIG_CACHE_PROTOCOL 0
-#define CONFIG_CONCAT_PROTOCOL 0
-#define CONFIG_CRYPTO_PROTOCOL 0
-#define CONFIG_DATA_PROTOCOL 0
-#define CONFIG_FFRTMPCRYPT_PROTOCOL 0
-#define CONFIG_FFRTMPHTTP_PROTOCOL 0
-#define CONFIG_FILE_PROTOCOL 0
-#define CONFIG_FTP_PROTOCOL 0
-#define CONFIG_GOPHER_PROTOCOL 0
-#define CONFIG_HLS_PROTOCOL 0
-#define CONFIG_HTTP_PROTOCOL 0
-#define CONFIG_HTTPPROXY_PROTOCOL 0
-#define CONFIG_HTTPS_PROTOCOL 0
-#define CONFIG_ICECAST_PROTOCOL 0
-#define CONFIG_MMSH_PROTOCOL 0
-#define CONFIG_MMST_PROTOCOL 0
-#define CONFIG_MD5_PROTOCOL 0
-#define CONFIG_PIPE_PROTOCOL 0
-#define CONFIG_RTMP_PROTOCOL 0
-#define CONFIG_RTMPE_PROTOCOL 0
-#define CONFIG_RTMPS_PROTOCOL 0
-#define CONFIG_RTMPT_PROTOCOL 0
-#define CONFIG_RTMPTE_PROTOCOL 0
-#define CONFIG_RTMPTS_PROTOCOL 0
-#define CONFIG_RTP_PROTOCOL 0
-#define CONFIG_SCTP_PROTOCOL 0
-#define CONFIG_SRTP_PROTOCOL 0
-#define CONFIG_SUBFILE_PROTOCOL 0
-#define CONFIG_TEE_PROTOCOL 0
-#define CONFIG_TCP_PROTOCOL 0
-#define CONFIG_TLS_GNUTLS_PROTOCOL 0
-#define CONFIG_TLS_SCHANNEL_PROTOCOL 0
-#define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
-#define CONFIG_TLS_OPENSSL_PROTOCOL 0
-#define CONFIG_UDP_PROTOCOL 0
-#define CONFIG_UDPLITE_PROTOCOL 0
-#define CONFIG_UNIX_PROTOCOL 0
-#define CONFIG_LIBRTMP_PROTOCOL 0
-#define CONFIG_LIBRTMPE_PROTOCOL 0
-#define CONFIG_LIBRTMPS_PROTOCOL 0
-#define CONFIG_LIBRTMPT_PROTOCOL 0
-#define CONFIG_LIBRTMPTE_PROTOCOL 0
-#define CONFIG_LIBSSH_PROTOCOL 0
-#define CONFIG_LIBSMBCLIENT_PROTOCOL 0
#endif /* FFMPEG_CONFIG_H */
diff --git a/media/ffvpx/defaults_disabled.asm b/media/ffvpx/defaults_disabled.asm
new file mode 100644
index 000000000..a9fde4c52
--- /dev/null
+++ b/media/ffvpx/defaults_disabled.asm
@@ -0,0 +1,1674 @@
+%define CONFIG_ENCODERS 0
+%define CONFIG_HWACCELS 0
+%define CONFIG_INDEVS 0
+%define CONFIG_OUTDEVS 0
+%define CONFIG_FILTERS 0
+%define CONFIG_DEMUXERS 0
+%define CONFIG_MUXERS 0
+%define CONFIG_PROTOCOLS 0
+%define CONFIG_FRAME_THREAD_ENCODER 0
+%define CONFIG_AASC_DECODER 0
+%define CONFIG_AIC_DECODER 0
+%define CONFIG_ALIAS_PIX_DECODER 0
+%define CONFIG_AMV_DECODER 0
+%define CONFIG_ANM_DECODER 0
+%define CONFIG_ANSI_DECODER 0
+%define CONFIG_APNG_DECODER 0
+%define CONFIG_ASV1_DECODER 0
+%define CONFIG_ASV2_DECODER 0
+%define CONFIG_AURA_DECODER 0
+%define CONFIG_AURA2_DECODER 0
+%define CONFIG_AVRP_DECODER 0
+%define CONFIG_AVRN_DECODER 0
+%define CONFIG_AVS_DECODER 0
+%define CONFIG_AVUI_DECODER 0
+%define CONFIG_AYUV_DECODER 0
+%define CONFIG_BETHSOFTVID_DECODER 0
+%define CONFIG_BFI_DECODER 0
+%define CONFIG_BINK_DECODER 0
+%define CONFIG_BMP_DECODER 0
+%define CONFIG_BMV_VIDEO_DECODER 0
+%define CONFIG_BRENDER_PIX_DECODER 0
+%define CONFIG_C93_DECODER 0
+%define CONFIG_CAVS_DECODER 0
+%define CONFIG_CDGRAPHICS_DECODER 0
+%define CONFIG_CDXL_DECODER 0
+%define CONFIG_CFHD_DECODER 0
+%define CONFIG_CINEPAK_DECODER 0
+%define CONFIG_CLEARVIDEO_DECODER 0
+%define CONFIG_CLJR_DECODER 0
+%define CONFIG_CLLC_DECODER 0
+%define CONFIG_COMFORTNOISE_DECODER 0
+%define CONFIG_CPIA_DECODER 0
+%define CONFIG_CSCD_DECODER 0
+%define CONFIG_CYUV_DECODER 0
+%define CONFIG_DDS_DECODER 0
+%define CONFIG_DFA_DECODER 0
+%define CONFIG_DIRAC_DECODER 0
+%define CONFIG_DNXHD_DECODER 0
+%define CONFIG_DPX_DECODER 0
+%define CONFIG_DSICINVIDEO_DECODER 0
+%define CONFIG_DVAUDIO_DECODER 0
+%define CONFIG_DVVIDEO_DECODER 0
+%define CONFIG_DXA_DECODER 0
+%define CONFIG_DXTORY_DECODER 0
+%define CONFIG_DXV_DECODER 0
+%define CONFIG_EACMV_DECODER 0
+%define CONFIG_EAMAD_DECODER 0
+%define CONFIG_EATGQ_DECODER 0
+%define CONFIG_EATGV_DECODER 0
+%define CONFIG_EATQI_DECODER 0
+%define CONFIG_EIGHTBPS_DECODER 0
+%define CONFIG_EIGHTSVX_EXP_DECODER 0
+%define CONFIG_EIGHTSVX_FIB_DECODER 0
+%define CONFIG_ESCAPE124_DECODER 0
+%define CONFIG_ESCAPE130_DECODER 0
+%define CONFIG_EXR_DECODER 0
+%define CONFIG_FFV1_DECODER 0
+%define CONFIG_FFVHUFF_DECODER 0
+%define CONFIG_FIC_DECODER 0
+%define CONFIG_FITS_DECODER 0
+%define CONFIG_FLASHSV_DECODER 0
+%define CONFIG_FLASHSV2_DECODER 0
+%define CONFIG_FLIC_DECODER 0
+%define CONFIG_FLV_DECODER 0
+%define CONFIG_FMVC_DECODER 0
+%define CONFIG_FOURXM_DECODER 0
+%define CONFIG_FRAPS_DECODER 0
+%define CONFIG_FRWU_DECODER 0
+%define CONFIG_G2M_DECODER 0
+%define CONFIG_GDV_DECODER 0
+%define CONFIG_GIF_DECODER 0
+%define CONFIG_H261_DECODER 0
+%define CONFIG_H263_DECODER 0
+%define CONFIG_H263I_DECODER 0
+%define CONFIG_H263P_DECODER 0
+%define CONFIG_H263_V4L2M2M_DECODER 0
+%define CONFIG_H264_DECODER 0
+%define CONFIG_H264_CRYSTALHD_DECODER 0
+%define CONFIG_H264_V4L2M2M_DECODER 0
+%define CONFIG_H264_MEDIACODEC_DECODER 0
+%define CONFIG_H264_MMAL_DECODER 0
+%define CONFIG_H264_QSV_DECODER 0
+%define CONFIG_H264_RKMPP_DECODER 0
+%define CONFIG_H264_VDA_DECODER 0
+%define CONFIG_H264_VDPAU_DECODER 0
+%define CONFIG_HAP_DECODER 0
+%define CONFIG_HEVC_DECODER 0
+%define CONFIG_HEVC_QSV_DECODER 0
+%define CONFIG_HEVC_RKMPP_DECODER 0
+%define CONFIG_HEVC_V4L2M2M_DECODER 0
+%define CONFIG_HNM4_VIDEO_DECODER 0
+%define CONFIG_HQ_HQA_DECODER 0
+%define CONFIG_HQX_DECODER 0
+%define CONFIG_HUFFYUV_DECODER 0
+%define CONFIG_IDCIN_DECODER 0
+%define CONFIG_IFF_ILBM_DECODER 0
+%define CONFIG_INDEO2_DECODER 0
+%define CONFIG_INDEO3_DECODER 0
+%define CONFIG_INDEO4_DECODER 0
+%define CONFIG_INDEO5_DECODER 0
+%define CONFIG_INTERPLAY_VIDEO_DECODER 0
+%define CONFIG_JPEG2000_DECODER 0
+%define CONFIG_JPEGLS_DECODER 0
+%define CONFIG_JV_DECODER 0
+%define CONFIG_KGV1_DECODER 0
+%define CONFIG_KMVC_DECODER 0
+%define CONFIG_LAGARITH_DECODER 0
+%define CONFIG_LOCO_DECODER 0
+%define CONFIG_M101_DECODER 0
+%define CONFIG_MAGICYUV_DECODER 0
+%define CONFIG_MDEC_DECODER 0
+%define CONFIG_MIMIC_DECODER 0
+%define CONFIG_MJPEG_DECODER 0
+%define CONFIG_MJPEGB_DECODER 0
+%define CONFIG_MMVIDEO_DECODER 0
+%define CONFIG_MOTIONPIXELS_DECODER 0
+%define CONFIG_MPEG_XVMC_DECODER 0
+%define CONFIG_MPEG1VIDEO_DECODER 0
+%define CONFIG_MPEG2VIDEO_DECODER 0
+%define CONFIG_MPEG4_DECODER 0
+%define CONFIG_MPEG4_CRYSTALHD_DECODER 0
+%define CONFIG_MPEG4_V4L2M2M_DECODER 0
+%define CONFIG_MPEG4_MMAL_DECODER 0
+%define CONFIG_MPEG4_VDPAU_DECODER 0
+%define CONFIG_MPEGVIDEO_DECODER 0
+%define CONFIG_MPEG_VDPAU_DECODER 0
+%define CONFIG_MPEG1_VDPAU_DECODER 0
+%define CONFIG_MPEG1_V4L2M2M_DECODER 0
+%define CONFIG_MPEG2_MMAL_DECODER 0
+%define CONFIG_MPEG2_CRYSTALHD_DECODER 0
+%define CONFIG_MPEG2_V4L2M2M_DECODER 0
+%define CONFIG_MPEG2_QSV_DECODER 0
+%define CONFIG_MPEG2_MEDIACODEC_DECODER 0
+%define CONFIG_MSA1_DECODER 0
+%define CONFIG_MSCC_DECODER 0
+%define CONFIG_MSMPEG4V1_DECODER 0
+%define CONFIG_MSMPEG4V2_DECODER 0
+%define CONFIG_MSMPEG4V3_DECODER 0
+%define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
+%define CONFIG_MSRLE_DECODER 0
+%define CONFIG_MSS1_DECODER 0
+%define CONFIG_MSS2_DECODER 0
+%define CONFIG_MSVIDEO1_DECODER 0
+%define CONFIG_MSZH_DECODER 0
+%define CONFIG_MTS2_DECODER 0
+%define CONFIG_MVC1_DECODER 0
+%define CONFIG_MVC2_DECODER 0
+%define CONFIG_MXPEG_DECODER 0
+%define CONFIG_NUV_DECODER 0
+%define CONFIG_PAF_VIDEO_DECODER 0
+%define CONFIG_PAM_DECODER 0
+%define CONFIG_PBM_DECODER 0
+%define CONFIG_PCX_DECODER 0
+%define CONFIG_PGM_DECODER 0
+%define CONFIG_PGMYUV_DECODER 0
+%define CONFIG_PICTOR_DECODER 0
+%define CONFIG_PIXLET_DECODER 0
+%define CONFIG_PNG_DECODER 0
+%define CONFIG_PPM_DECODER 0
+%define CONFIG_PRORES_DECODER 0
+%define CONFIG_PRORES_LGPL_DECODER 0
+%define CONFIG_PSD_DECODER 0
+%define CONFIG_PTX_DECODER 0
+%define CONFIG_QDRAW_DECODER 0
+%define CONFIG_QPEG_DECODER 0
+%define CONFIG_QTRLE_DECODER 0
+%define CONFIG_R10K_DECODER 0
+%define CONFIG_R210_DECODER 0
+%define CONFIG_RAWVIDEO_DECODER 0
+%define CONFIG_RL2_DECODER 0
+%define CONFIG_ROQ_DECODER 0
+%define CONFIG_RPZA_DECODER 0
+%define CONFIG_RSCC_DECODER 0
+%define CONFIG_RV10_DECODER 0
+%define CONFIG_RV20_DECODER 0
+%define CONFIG_RV30_DECODER 0
+%define CONFIG_RV40_DECODER 0
+%define CONFIG_S302M_DECODER 0
+%define CONFIG_SANM_DECODER 0
+%define CONFIG_SCPR_DECODER 0
+%define CONFIG_SCREENPRESSO_DECODER 0
+%define CONFIG_SDX2_DPCM_DECODER 0
+%define CONFIG_SGI_DECODER 0
+%define CONFIG_SGIRLE_DECODER 0
+%define CONFIG_SHEERVIDEO_DECODER 0
+%define CONFIG_SMACKER_DECODER 0
+%define CONFIG_SMC_DECODER 0
+%define CONFIG_SMVJPEG_DECODER 0
+%define CONFIG_SNOW_DECODER 0
+%define CONFIG_SP5X_DECODER 0
+%define CONFIG_SPEEDHQ_DECODER 0
+%define CONFIG_SRGC_DECODER 0
+%define CONFIG_SUNRAST_DECODER 0
+%define CONFIG_SVQ1_DECODER 0
+%define CONFIG_SVQ3_DECODER 0
+%define CONFIG_TARGA_DECODER 0
+%define CONFIG_TARGA_Y216_DECODER 0
+%define CONFIG_TDSC_DECODER 0
+%define CONFIG_THEORA_DECODER 0
+%define CONFIG_THP_DECODER 0
+%define CONFIG_TIERTEXSEQVIDEO_DECODER 0
+%define CONFIG_TIFF_DECODER 0
+%define CONFIG_TMV_DECODER 0
+%define CONFIG_TRUEMOTION1_DECODER 0
+%define CONFIG_TRUEMOTION2_DECODER 0
+%define CONFIG_TRUEMOTION2RT_DECODER 0
+%define CONFIG_TSCC_DECODER 0
+%define CONFIG_TSCC2_DECODER 0
+%define CONFIG_TXD_DECODER 0
+%define CONFIG_ULTI_DECODER 0
+%define CONFIG_UTVIDEO_DECODER 0
+%define CONFIG_V210_DECODER 0
+%define CONFIG_V210X_DECODER 0
+%define CONFIG_V308_DECODER 0
+%define CONFIG_V408_DECODER 0
+%define CONFIG_V410_DECODER 0
+%define CONFIG_VB_DECODER 0
+%define CONFIG_VBLE_DECODER 0
+%define CONFIG_VC1_DECODER 0
+%define CONFIG_VC1_CRYSTALHD_DECODER 0
+%define CONFIG_VC1_VDPAU_DECODER 0
+%define CONFIG_VC1IMAGE_DECODER 0
+%define CONFIG_VC1_MMAL_DECODER 0
+%define CONFIG_VC1_QSV_DECODER 0
+%define CONFIG_VC1_V4L2M2M_DECODER 0
+%define CONFIG_VCR1_DECODER 0
+%define CONFIG_VMDVIDEO_DECODER 0
+%define CONFIG_VMNC_DECODER 0
+%define CONFIG_VP3_DECODER 0
+%define CONFIG_VP5_DECODER 0
+%define CONFIG_VP6_DECODER 0
+%define CONFIG_VP6A_DECODER 0
+%define CONFIG_VP6F_DECODER 0
+%define CONFIG_VP7_DECODER 0
+%define CONFIG_VP8_RKMPP_DECODER 0
+%define CONFIG_VP8_V4L2M2M_DECODER 0
+%define CONFIG_VP9_RKMPP_DECODER 0
+%define CONFIG_VP9_V4L2M2M_DECODER 0
+%define CONFIG_VQA_DECODER 0
+%define CONFIG_BITPACKED_DECODER 0
+%define CONFIG_WEBP_DECODER 0
+%define CONFIG_WRAPPED_AVFRAME_DECODER 0
+%define CONFIG_WMV1_DECODER 0
+%define CONFIG_WMV2_DECODER 0
+%define CONFIG_WMV3_DECODER 0
+%define CONFIG_WMV3_CRYSTALHD_DECODER 0
+%define CONFIG_WMV3_VDPAU_DECODER 0
+%define CONFIG_WMV3IMAGE_DECODER 0
+%define CONFIG_WNV1_DECODER 0
+%define CONFIG_XAN_WC3_DECODER 0
+%define CONFIG_XAN_WC4_DECODER 0
+%define CONFIG_XBM_DECODER 0
+%define CONFIG_XFACE_DECODER 0
+%define CONFIG_XL_DECODER 0
+%define CONFIG_XPM_DECODER 0
+%define CONFIG_XWD_DECODER 0
+%define CONFIG_Y41P_DECODER 0
+%define CONFIG_YLC_DECODER 0
+%define CONFIG_YOP_DECODER 0
+%define CONFIG_YUV4_DECODER 0
+%define CONFIG_ZERO12V_DECODER 0
+%define CONFIG_ZEROCODEC_DECODER 0
+%define CONFIG_ZLIB_DECODER 0
+%define CONFIG_ZMBV_DECODER 0
+%define CONFIG_AAC_DECODER 0
+%define CONFIG_AAC_FIXED_DECODER 0
+%define CONFIG_AAC_LATM_DECODER 0
+%define CONFIG_AC3_DECODER 0
+%define CONFIG_AC3_FIXED_DECODER 0
+%define CONFIG_ALAC_DECODER 0
+%define CONFIG_ALS_DECODER 0
+%define CONFIG_AMRNB_DECODER 0
+%define CONFIG_AMRWB_DECODER 0
+%define CONFIG_APE_DECODER 0
+%define CONFIG_ATRAC1_DECODER 0
+%define CONFIG_ATRAC3_DECODER 0
+%define CONFIG_ATRAC3AL_DECODER 0
+%define CONFIG_ATRAC3P_DECODER 0
+%define CONFIG_ATRAC3PAL_DECODER 0
+%define CONFIG_BINKAUDIO_DCT_DECODER 0
+%define CONFIG_BINKAUDIO_RDFT_DECODER 0
+%define CONFIG_BMV_AUDIO_DECODER 0
+%define CONFIG_COOK_DECODER 0
+%define CONFIG_DCA_DECODER 0
+%define CONFIG_DOLBY_E_DECODER 0
+%define CONFIG_DSD_LSBF_DECODER 0
+%define CONFIG_DSD_MSBF_DECODER 0
+%define CONFIG_DSD_LSBF_PLANAR_DECODER 0
+%define CONFIG_DSD_MSBF_PLANAR_DECODER 0
+%define CONFIG_DSICINAUDIO_DECODER 0
+%define CONFIG_DSS_SP_DECODER 0
+%define CONFIG_DST_DECODER 0
+%define CONFIG_EAC3_DECODER 0
+%define CONFIG_EVRC_DECODER 0
+%define CONFIG_FFWAVESYNTH_DECODER 0
+%define CONFIG_G723_1_DECODER 0
+%define CONFIG_G729_DECODER 0
+%define CONFIG_GSM_DECODER 0
+%define CONFIG_GSM_MS_DECODER 0
+%define CONFIG_IAC_DECODER 0
+%define CONFIG_IMC_DECODER 0
+%define CONFIG_INTERPLAY_ACM_DECODER 0
+%define CONFIG_MACE3_DECODER 0
+%define CONFIG_MACE6_DECODER 0
+%define CONFIG_METASOUND_DECODER 0
+%define CONFIG_MLP_DECODER 0
+%define CONFIG_MP1_DECODER 0
+%define CONFIG_MP1FLOAT_DECODER 0
+%define CONFIG_MP2_DECODER 0
+%define CONFIG_MP2FLOAT_DECODER 0
+%define CONFIG_MP3_DECODER 0
+%define CONFIG_MP3FLOAT_DECODER 0
+%define CONFIG_MP3ADU_DECODER 0
+%define CONFIG_MP3ADUFLOAT_DECODER 0
+%define CONFIG_MP3ON4_DECODER 0
+%define CONFIG_MP3ON4FLOAT_DECODER 0
+%define CONFIG_MPC7_DECODER 0
+%define CONFIG_MPC8_DECODER 0
+%define CONFIG_NELLYMOSER_DECODER 0
+%define CONFIG_ON2AVC_DECODER 0
+%define CONFIG_OPUS_DECODER 0
+%define CONFIG_PAF_AUDIO_DECODER 0
+%define CONFIG_QCELP_DECODER 0
+%define CONFIG_QDM2_DECODER 0
+%define CONFIG_QDMC_DECODER 0
+%define CONFIG_RA_144_DECODER 0
+%define CONFIG_RA_288_DECODER 0
+%define CONFIG_RALF_DECODER 0
+%define CONFIG_SHORTEN_DECODER 0
+%define CONFIG_SIPR_DECODER 0
+%define CONFIG_SMACKAUD_DECODER 0
+%define CONFIG_SONIC_DECODER 0
+%define CONFIG_TAK_DECODER 0
+%define CONFIG_TRUEHD_DECODER 0
+%define CONFIG_TRUESPEECH_DECODER 0
+%define CONFIG_TTA_DECODER 0
+%define CONFIG_TWINVQ_DECODER 0
+%define CONFIG_VMDAUDIO_DECODER 0
+%define CONFIG_VORBIS_DECODER 0
+%define CONFIG_WAVPACK_DECODER 0
+%define CONFIG_WMALOSSLESS_DECODER 0
+%define CONFIG_WMAPRO_DECODER 0
+%define CONFIG_WMAV1_DECODER 0
+%define CONFIG_WMAV2_DECODER 0
+%define CONFIG_WMAVOICE_DECODER 0
+%define CONFIG_WS_SND1_DECODER 0
+%define CONFIG_XMA1_DECODER 0
+%define CONFIG_XMA2_DECODER 0
+%define CONFIG_PCM_ALAW_DECODER 0
+%define CONFIG_PCM_BLURAY_DECODER 0
+%define CONFIG_PCM_DVD_DECODER 0
+%define CONFIG_PCM_F16LE_DECODER 0
+%define CONFIG_PCM_F24LE_DECODER 0
+%define CONFIG_PCM_F32BE_DECODER 0
+%define CONFIG_PCM_F32LE_DECODER 0
+%define CONFIG_PCM_F64BE_DECODER 0
+%define CONFIG_PCM_F64LE_DECODER 0
+%define CONFIG_PCM_LXF_DECODER 0
+%define CONFIG_PCM_MULAW_DECODER 0
+%define CONFIG_PCM_S8_DECODER 0
+%define CONFIG_PCM_S8_PLANAR_DECODER 0
+%define CONFIG_PCM_S16BE_DECODER 0
+%define CONFIG_PCM_S16BE_PLANAR_DECODER 0
+%define CONFIG_PCM_S16LE_DECODER 0
+%define CONFIG_PCM_S16LE_PLANAR_DECODER 0
+%define CONFIG_PCM_S24BE_DECODER 0
+%define CONFIG_PCM_S24DAUD_DECODER 0
+%define CONFIG_PCM_S24LE_DECODER 0
+%define CONFIG_PCM_S24LE_PLANAR_DECODER 0
+%define CONFIG_PCM_S32BE_DECODER 0
+%define CONFIG_PCM_S32LE_DECODER 0
+%define CONFIG_PCM_S32LE_PLANAR_DECODER 0
+%define CONFIG_PCM_S64BE_DECODER 0
+%define CONFIG_PCM_S64LE_DECODER 0
+%define CONFIG_PCM_U8_DECODER 0
+%define CONFIG_PCM_U16BE_DECODER 0
+%define CONFIG_PCM_U16LE_DECODER 0
+%define CONFIG_PCM_U24BE_DECODER 0
+%define CONFIG_PCM_U24LE_DECODER 0
+%define CONFIG_PCM_U32BE_DECODER 0
+%define CONFIG_PCM_U32LE_DECODER 0
+%define CONFIG_PCM_ZORK_DECODER 0
+%define CONFIG_GREMLIN_DPCM_DECODER 0
+%define CONFIG_INTERPLAY_DPCM_DECODER 0
+%define CONFIG_ROQ_DPCM_DECODER 0
+%define CONFIG_SOL_DPCM_DECODER 0
+%define CONFIG_XAN_DPCM_DECODER 0
+%define CONFIG_ADPCM_4XM_DECODER 0
+%define CONFIG_ADPCM_ADX_DECODER 0
+%define CONFIG_ADPCM_AFC_DECODER 0
+%define CONFIG_ADPCM_AICA_DECODER 0
+%define CONFIG_ADPCM_CT_DECODER 0
+%define CONFIG_ADPCM_DTK_DECODER 0
+%define CONFIG_ADPCM_EA_DECODER 0
+%define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
+%define CONFIG_ADPCM_EA_R1_DECODER 0
+%define CONFIG_ADPCM_EA_R2_DECODER 0
+%define CONFIG_ADPCM_EA_R3_DECODER 0
+%define CONFIG_ADPCM_EA_XAS_DECODER 0
+%define CONFIG_ADPCM_G722_DECODER 0
+%define CONFIG_ADPCM_G726_DECODER 0
+%define CONFIG_ADPCM_G726LE_DECODER 0
+%define CONFIG_ADPCM_IMA_AMV_DECODER 0
+%define CONFIG_ADPCM_IMA_APC_DECODER 0
+%define CONFIG_ADPCM_IMA_DAT4_DECODER 0
+%define CONFIG_ADPCM_IMA_DK3_DECODER 0
+%define CONFIG_ADPCM_IMA_DK4_DECODER 0
+%define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
+%define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
+%define CONFIG_ADPCM_IMA_ISS_DECODER 0
+%define CONFIG_ADPCM_IMA_OKI_DECODER 0
+%define CONFIG_ADPCM_IMA_QT_DECODER 0
+%define CONFIG_ADPCM_IMA_RAD_DECODER 0
+%define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
+%define CONFIG_ADPCM_IMA_WAV_DECODER 0
+%define CONFIG_ADPCM_IMA_WS_DECODER 0
+%define CONFIG_ADPCM_MS_DECODER 0
+%define CONFIG_ADPCM_MTAF_DECODER 0
+%define CONFIG_ADPCM_PSX_DECODER 0
+%define CONFIG_ADPCM_SBPRO_2_DECODER 0
+%define CONFIG_ADPCM_SBPRO_3_DECODER 0
+%define CONFIG_ADPCM_SBPRO_4_DECODER 0
+%define CONFIG_ADPCM_SWF_DECODER 0
+%define CONFIG_ADPCM_THP_DECODER 0
+%define CONFIG_ADPCM_THP_LE_DECODER 0
+%define CONFIG_ADPCM_VIMA_DECODER 0
+%define CONFIG_ADPCM_XA_DECODER 0
+%define CONFIG_ADPCM_YAMAHA_DECODER 0
+%define CONFIG_SSA_DECODER 0
+%define CONFIG_ASS_DECODER 0
+%define CONFIG_CCAPTION_DECODER 0
+%define CONFIG_DVBSUB_DECODER 0
+%define CONFIG_DVDSUB_DECODER 0
+%define CONFIG_JACOSUB_DECODER 0
+%define CONFIG_MICRODVD_DECODER 0
+%define CONFIG_MOVTEXT_DECODER 0
+%define CONFIG_MPL2_DECODER 0
+%define CONFIG_PGSSUB_DECODER 0
+%define CONFIG_PJS_DECODER 0
+%define CONFIG_REALTEXT_DECODER 0
+%define CONFIG_SAMI_DECODER 0
+%define CONFIG_SRT_DECODER 0
+%define CONFIG_STL_DECODER 0
+%define CONFIG_SUBRIP_DECODER 0
+%define CONFIG_SUBVIEWER_DECODER 0
+%define CONFIG_SUBVIEWER1_DECODER 0
+%define CONFIG_TEXT_DECODER 0
+%define CONFIG_VPLAYER_DECODER 0
+%define CONFIG_WEBVTT_DECODER 0
+%define CONFIG_XSUB_DECODER 0
+%define CONFIG_AAC_AT_DECODER 0
+%define CONFIG_AC3_AT_DECODER 0
+%define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
+%define CONFIG_ALAC_AT_DECODER 0
+%define CONFIG_AMR_NB_AT_DECODER 0
+%define CONFIG_EAC3_AT_DECODER 0
+%define CONFIG_GSM_MS_AT_DECODER 0
+%define CONFIG_ILBC_AT_DECODER 0
+%define CONFIG_MP1_AT_DECODER 0
+%define CONFIG_MP2_AT_DECODER 0
+%define CONFIG_MP3_AT_DECODER 0
+%define CONFIG_PCM_ALAW_AT_DECODER 0
+%define CONFIG_PCM_MULAW_AT_DECODER 0
+%define CONFIG_QDMC_AT_DECODER 0
+%define CONFIG_QDM2_AT_DECODER 0
+%define CONFIG_LIBCELT_DECODER 0
+%define CONFIG_LIBFDK_AAC_DECODER 0
+%define CONFIG_LIBGSM_DECODER 0
+%define CONFIG_LIBGSM_MS_DECODER 0
+%define CONFIG_LIBILBC_DECODER 0
+%define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
+%define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
+%define CONFIG_LIBOPENJPEG_DECODER 0
+%define CONFIG_LIBOPUS_DECODER 0
+%define CONFIG_LIBRSVG_DECODER 0
+%define CONFIG_LIBSPEEX_DECODER 0
+%define CONFIG_LIBVORBIS_DECODER 0
+%define CONFIG_LIBVPX_VP8_DECODER 0
+%define CONFIG_LIBVPX_VP9_DECODER 0
+%define CONFIG_LIBZVBI_TELETEXT_DECODER 0
+%define CONFIG_BINTEXT_DECODER 0
+%define CONFIG_XBIN_DECODER 0
+%define CONFIG_IDF_DECODER 0
+%define CONFIG_LIBOPENH264_DECODER 0
+%define CONFIG_H264_CUVID_DECODER 0
+%define CONFIG_HEVC_CUVID_DECODER 0
+%define CONFIG_HEVC_MEDIACODEC_DECODER 0
+%define CONFIG_MJPEG_CUVID_DECODER 0
+%define CONFIG_MPEG1_CUVID_DECODER 0
+%define CONFIG_MPEG2_CUVID_DECODER 0
+%define CONFIG_MPEG4_CUVID_DECODER 0
+%define CONFIG_MPEG4_MEDIACODEC_DECODER 0
+%define CONFIG_VC1_CUVID_DECODER 0
+%define CONFIG_VP8_CUVID_DECODER 0
+%define CONFIG_VP8_MEDIACODEC_DECODER 0
+%define CONFIG_VP8_QSV_DECODER 0
+%define CONFIG_VP9_CUVID_DECODER 0
+%define CONFIG_VP9_MEDIACODEC_DECODER 0
+%define CONFIG_AA_DEMUXER 0
+%define CONFIG_AAC_DEMUXER 0
+%define CONFIG_AC3_DEMUXER 0
+%define CONFIG_ACM_DEMUXER 0
+%define CONFIG_ACT_DEMUXER 0
+%define CONFIG_ADF_DEMUXER 0
+%define CONFIG_ADP_DEMUXER 0
+%define CONFIG_ADS_DEMUXER 0
+%define CONFIG_ADX_DEMUXER 0
+%define CONFIG_AEA_DEMUXER 0
+%define CONFIG_AFC_DEMUXER 0
+%define CONFIG_AIFF_DEMUXER 0
+%define CONFIG_AIX_DEMUXER 0
+%define CONFIG_AMR_DEMUXER 0
+%define CONFIG_ANM_DEMUXER 0
+%define CONFIG_APC_DEMUXER 0
+%define CONFIG_APE_DEMUXER 0
+%define CONFIG_APNG_DEMUXER 0
+%define CONFIG_AQTITLE_DEMUXER 0
+%define CONFIG_ASF_DEMUXER 0
+%define CONFIG_ASF_O_DEMUXER 0
+%define CONFIG_ASS_DEMUXER 0
+%define CONFIG_AST_DEMUXER 0
+%define CONFIG_AU_DEMUXER 0
+%define CONFIG_AVI_DEMUXER 0
+%define CONFIG_AVISYNTH_DEMUXER 0
+%define CONFIG_AVR_DEMUXER 0
+%define CONFIG_AVS_DEMUXER 0
+%define CONFIG_BETHSOFTVID_DEMUXER 0
+%define CONFIG_BFI_DEMUXER 0
+%define CONFIG_BINTEXT_DEMUXER 0
+%define CONFIG_BINK_DEMUXER 0
+%define CONFIG_BIT_DEMUXER 0
+%define CONFIG_BMV_DEMUXER 0
+%define CONFIG_BFSTM_DEMUXER 0
+%define CONFIG_BRSTM_DEMUXER 0
+%define CONFIG_BOA_DEMUXER 0
+%define CONFIG_C93_DEMUXER 0
+%define CONFIG_CAF_DEMUXER 0
+%define CONFIG_CAVSVIDEO_DEMUXER 0
+%define CONFIG_CDG_DEMUXER 0
+%define CONFIG_CDXL_DEMUXER 0
+%define CONFIG_CINE_DEMUXER 0
+%define CONFIG_CONCAT_DEMUXER 0
+%define CONFIG_DASH_DEMUXER 0
+%define CONFIG_DATA_DEMUXER 0
+%define CONFIG_DAUD_DEMUXER 0
+%define CONFIG_DCSTR_DEMUXER 0
+%define CONFIG_DFA_DEMUXER 0
+%define CONFIG_DIRAC_DEMUXER 0
+%define CONFIG_DNXHD_DEMUXER 0
+%define CONFIG_DSF_DEMUXER 0
+%define CONFIG_DSICIN_DEMUXER 0
+%define CONFIG_DSS_DEMUXER 0
+%define CONFIG_DTS_DEMUXER 0
+%define CONFIG_DTSHD_DEMUXER 0
+%define CONFIG_DV_DEMUXER 0
+%define CONFIG_DVBSUB_DEMUXER 0
+%define CONFIG_DVBTXT_DEMUXER 0
+%define CONFIG_DXA_DEMUXER 0
+%define CONFIG_EA_DEMUXER 0
+%define CONFIG_EA_CDATA_DEMUXER 0
+%define CONFIG_EAC3_DEMUXER 0
+%define CONFIG_EPAF_DEMUXER 0
+%define CONFIG_FFM_DEMUXER 0
+%define CONFIG_FFMETADATA_DEMUXER 0
+%define CONFIG_FILMSTRIP_DEMUXER 0
+%define CONFIG_FITS_DEMUXER 0
+%define CONFIG_FLAC_DEMUXER 0
+%define CONFIG_FLIC_DEMUXER 0
+%define CONFIG_FLV_DEMUXER 0
+%define CONFIG_LIVE_FLV_DEMUXER 0
+%define CONFIG_FOURXM_DEMUXER 0
+%define CONFIG_FRM_DEMUXER 0
+%define CONFIG_FSB_DEMUXER 0
+%define CONFIG_G722_DEMUXER 0
+%define CONFIG_G723_1_DEMUXER 0
+%define CONFIG_G726_DEMUXER 0
+%define CONFIG_G726LE_DEMUXER 0
+%define CONFIG_G729_DEMUXER 0
+%define CONFIG_GDV_DEMUXER 0
+%define CONFIG_GENH_DEMUXER 0
+%define CONFIG_GIF_DEMUXER 0
+%define CONFIG_GSM_DEMUXER 0
+%define CONFIG_GXF_DEMUXER 0
+%define CONFIG_H261_DEMUXER 0
+%define CONFIG_H263_DEMUXER 0
+%define CONFIG_H264_DEMUXER 0
+%define CONFIG_HEVC_DEMUXER 0
+%define CONFIG_HLS_DEMUXER 0
+%define CONFIG_HNM_DEMUXER 0
+%define CONFIG_ICO_DEMUXER 0
+%define CONFIG_IDCIN_DEMUXER 0
+%define CONFIG_IDF_DEMUXER 0
+%define CONFIG_IFF_DEMUXER 0
+%define CONFIG_ILBC_DEMUXER 0
+%define CONFIG_IMAGE2_DEMUXER 0
+%define CONFIG_IMAGE2PIPE_DEMUXER 0
+%define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
+%define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
+%define CONFIG_INGENIENT_DEMUXER 0
+%define CONFIG_IPMOVIE_DEMUXER 0
+%define CONFIG_IRCAM_DEMUXER 0
+%define CONFIG_ISS_DEMUXER 0
+%define CONFIG_IV8_DEMUXER 0
+%define CONFIG_IVF_DEMUXER 0
+%define CONFIG_IVR_DEMUXER 0
+%define CONFIG_JACOSUB_DEMUXER 0
+%define CONFIG_JV_DEMUXER 0
+%define CONFIG_LMLM4_DEMUXER 0
+%define CONFIG_LOAS_DEMUXER 0
+%define CONFIG_LRC_DEMUXER 0
+%define CONFIG_LVF_DEMUXER 0
+%define CONFIG_LXF_DEMUXER 0
+%define CONFIG_M4V_DEMUXER 0
+%define CONFIG_MATROSKA_DEMUXER 0
+%define CONFIG_MGSTS_DEMUXER 0
+%define CONFIG_MICRODVD_DEMUXER 0
+%define CONFIG_MJPEG_DEMUXER 0
+%define CONFIG_MJPEG_2000_DEMUXER 0
+%define CONFIG_MLP_DEMUXER 0
+%define CONFIG_MLV_DEMUXER 0
+%define CONFIG_MM_DEMUXER 0
+%define CONFIG_MMF_DEMUXER 0
+%define CONFIG_MOV_DEMUXER 0
+%define CONFIG_MP3_DEMUXER 0
+%define CONFIG_MPC_DEMUXER 0
+%define CONFIG_MPC8_DEMUXER 0
+%define CONFIG_MPEGPS_DEMUXER 0
+%define CONFIG_MPEGTS_DEMUXER 0
+%define CONFIG_MPEGTSRAW_DEMUXER 0
+%define CONFIG_MPEGVIDEO_DEMUXER 0
+%define CONFIG_MPJPEG_DEMUXER 0
+%define CONFIG_MPL2_DEMUXER 0
+%define CONFIG_MPSUB_DEMUXER 0
+%define CONFIG_MSF_DEMUXER 0
+%define CONFIG_MSNWC_TCP_DEMUXER 0
+%define CONFIG_MTAF_DEMUXER 0
+%define CONFIG_MTV_DEMUXER 0
+%define CONFIG_MUSX_DEMUXER 0
+%define CONFIG_MV_DEMUXER 0
+%define CONFIG_MVI_DEMUXER 0
+%define CONFIG_MXF_DEMUXER 0
+%define CONFIG_MXG_DEMUXER 0
+%define CONFIG_NC_DEMUXER 0
+%define CONFIG_NISTSPHERE_DEMUXER 0
+%define CONFIG_NSV_DEMUXER 0
+%define CONFIG_NUT_DEMUXER 0
+%define CONFIG_NUV_DEMUXER 0
+%define CONFIG_OGG_DEMUXER 0
+%define CONFIG_OMA_DEMUXER 0
+%define CONFIG_PAF_DEMUXER 0
+%define CONFIG_PCM_ALAW_DEMUXER 0
+%define CONFIG_PCM_MULAW_DEMUXER 0
+%define CONFIG_PCM_F64BE_DEMUXER 0
+%define CONFIG_PCM_F64LE_DEMUXER 0
+%define CONFIG_PCM_F32BE_DEMUXER 0
+%define CONFIG_PCM_F32LE_DEMUXER 0
+%define CONFIG_PCM_S32BE_DEMUXER 0
+%define CONFIG_PCM_S32LE_DEMUXER 0
+%define CONFIG_PCM_S24BE_DEMUXER 0
+%define CONFIG_PCM_S24LE_DEMUXER 0
+%define CONFIG_PCM_S16BE_DEMUXER 0
+%define CONFIG_PCM_S16LE_DEMUXER 0
+%define CONFIG_PCM_S8_DEMUXER 0
+%define CONFIG_PCM_U32BE_DEMUXER 0
+%define CONFIG_PCM_U32LE_DEMUXER 0
+%define CONFIG_PCM_U24BE_DEMUXER 0
+%define CONFIG_PCM_U24LE_DEMUXER 0
+%define CONFIG_PCM_U16BE_DEMUXER 0
+%define CONFIG_PCM_U16LE_DEMUXER 0
+%define CONFIG_PCM_U8_DEMUXER 0
+%define CONFIG_PJS_DEMUXER 0
+%define CONFIG_PMP_DEMUXER 0
+%define CONFIG_PVA_DEMUXER 0
+%define CONFIG_PVF_DEMUXER 0
+%define CONFIG_QCP_DEMUXER 0
+%define CONFIG_R3D_DEMUXER 0
+%define CONFIG_RAWVIDEO_DEMUXER 0
+%define CONFIG_REALTEXT_DEMUXER 0
+%define CONFIG_REDSPARK_DEMUXER 0
+%define CONFIG_RL2_DEMUXER 0
+%define CONFIG_RM_DEMUXER 0
+%define CONFIG_ROQ_DEMUXER 0
+%define CONFIG_RPL_DEMUXER 0
+%define CONFIG_RSD_DEMUXER 0
+%define CONFIG_RSO_DEMUXER 0
+%define CONFIG_RTP_DEMUXER 0
+%define CONFIG_RTSP_DEMUXER 0
+%define CONFIG_S337M_DEMUXER 0
+%define CONFIG_SAMI_DEMUXER 0
+%define CONFIG_SAP_DEMUXER 0
+%define CONFIG_SBG_DEMUXER 0
+%define CONFIG_SCC_DEMUXER 0
+%define CONFIG_SDP_DEMUXER 0
+%define CONFIG_SDR2_DEMUXER 0
+%define CONFIG_SDS_DEMUXER 0
+%define CONFIG_SDX_DEMUXER 0
+%define CONFIG_SEGAFILM_DEMUXER 0
+%define CONFIG_SHORTEN_DEMUXER 0
+%define CONFIG_SIFF_DEMUXER 0
+%define CONFIG_SLN_DEMUXER 0
+%define CONFIG_SMACKER_DEMUXER 0
+%define CONFIG_SMJPEG_DEMUXER 0
+%define CONFIG_SMUSH_DEMUXER 0
+%define CONFIG_SOL_DEMUXER 0
+%define CONFIG_SOX_DEMUXER 0
+%define CONFIG_SPDIF_DEMUXER 0
+%define CONFIG_SRT_DEMUXER 0
+%define CONFIG_STR_DEMUXER 0
+%define CONFIG_STL_DEMUXER 0
+%define CONFIG_SUBVIEWER1_DEMUXER 0
+%define CONFIG_SUBVIEWER_DEMUXER 0
+%define CONFIG_SUP_DEMUXER 0
+%define CONFIG_SVAG_DEMUXER 0
+%define CONFIG_SWF_DEMUXER 0
+%define CONFIG_TAK_DEMUXER 0
+%define CONFIG_TEDCAPTIONS_DEMUXER 0
+%define CONFIG_THP_DEMUXER 0
+%define CONFIG_THREEDOSTR_DEMUXER 0
+%define CONFIG_TIERTEXSEQ_DEMUXER 0
+%define CONFIG_TMV_DEMUXER 0
+%define CONFIG_TRUEHD_DEMUXER 0
+%define CONFIG_TTA_DEMUXER 0
+%define CONFIG_TXD_DEMUXER 0
+%define CONFIG_TTY_DEMUXER 0
+%define CONFIG_V210_DEMUXER 0
+%define CONFIG_V210X_DEMUXER 0
+%define CONFIG_VAG_DEMUXER 0
+%define CONFIG_VC1_DEMUXER 0
+%define CONFIG_VC1T_DEMUXER 0
+%define CONFIG_VIVO_DEMUXER 0
+%define CONFIG_VMD_DEMUXER 0
+%define CONFIG_VOBSUB_DEMUXER 0
+%define CONFIG_VOC_DEMUXER 0
+%define CONFIG_VPK_DEMUXER 0
+%define CONFIG_VPLAYER_DEMUXER 0
+%define CONFIG_VQF_DEMUXER 0
+%define CONFIG_W64_DEMUXER 0
+%define CONFIG_WAV_DEMUXER 0
+%define CONFIG_WC3_DEMUXER 0
+%define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
+%define CONFIG_WEBVTT_DEMUXER 0
+%define CONFIG_WSAUD_DEMUXER 0
+%define CONFIG_WSD_DEMUXER 0
+%define CONFIG_WSVQA_DEMUXER 0
+%define CONFIG_WTV_DEMUXER 0
+%define CONFIG_WVE_DEMUXER 0
+%define CONFIG_WV_DEMUXER 0
+%define CONFIG_XA_DEMUXER 0
+%define CONFIG_XBIN_DEMUXER 0
+%define CONFIG_XMV_DEMUXER 0
+%define CONFIG_XVAG_DEMUXER 0
+%define CONFIG_XWMA_DEMUXER 0
+%define CONFIG_YOP_DEMUXER 0
+%define CONFIG_YUV4MPEGPIPE_DEMUXER 0
+%define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_PSD_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_SVG_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
+%define CONFIG_IMAGE_XPM_PIPE_DEMUXER 0
+%define CONFIG_LIBGME_DEMUXER 0
+%define CONFIG_LIBMODPLUG_DEMUXER 0
+%define CONFIG_LIBOPENMPT_DEMUXER 0
+%define CONFIG_A64MULTI_ENCODER 0
+%define CONFIG_A64MULTI5_ENCODER 0
+%define CONFIG_ALIAS_PIX_ENCODER 0
+%define CONFIG_AMV_ENCODER 0
+%define CONFIG_APNG_ENCODER 0
+%define CONFIG_ASV1_ENCODER 0
+%define CONFIG_ASV2_ENCODER 0
+%define CONFIG_AVRP_ENCODER 0
+%define CONFIG_AVUI_ENCODER 0
+%define CONFIG_AYUV_ENCODER 0
+%define CONFIG_BMP_ENCODER 0
+%define CONFIG_CINEPAK_ENCODER 0
+%define CONFIG_CLJR_ENCODER 0
+%define CONFIG_COMFORTNOISE_ENCODER 0
+%define CONFIG_DNXHD_ENCODER 0
+%define CONFIG_DPX_ENCODER 0
+%define CONFIG_DVVIDEO_ENCODER 0
+%define CONFIG_FFV1_ENCODER 0
+%define CONFIG_FFVHUFF_ENCODER 0
+%define CONFIG_FITS_ENCODER 0
+%define CONFIG_FLASHSV_ENCODER 0
+%define CONFIG_FLASHSV2_ENCODER 0
+%define CONFIG_FLV_ENCODER 0
+%define CONFIG_GIF_ENCODER 0
+%define CONFIG_H261_ENCODER 0
+%define CONFIG_H263_ENCODER 0
+%define CONFIG_H263P_ENCODER 0
+%define CONFIG_HAP_ENCODER 0
+%define CONFIG_HUFFYUV_ENCODER 0
+%define CONFIG_JPEG2000_ENCODER 0
+%define CONFIG_JPEGLS_ENCODER 0
+%define CONFIG_LJPEG_ENCODER 0
+%define CONFIG_MJPEG_ENCODER 0
+%define CONFIG_MPEG1VIDEO_ENCODER 0
+%define CONFIG_MPEG2VIDEO_ENCODER 0
+%define CONFIG_MPEG4_ENCODER 0
+%define CONFIG_MSMPEG4V2_ENCODER 0
+%define CONFIG_MSMPEG4V3_ENCODER 0
+%define CONFIG_MSVIDEO1_ENCODER 0
+%define CONFIG_PAM_ENCODER 0
+%define CONFIG_PBM_ENCODER 0
+%define CONFIG_PCX_ENCODER 0
+%define CONFIG_PGM_ENCODER 0
+%define CONFIG_PGMYUV_ENCODER 0
+%define CONFIG_PNG_ENCODER 0
+%define CONFIG_PPM_ENCODER 0
+%define CONFIG_PRORES_ENCODER 0
+%define CONFIG_PRORES_AW_ENCODER 0
+%define CONFIG_PRORES_KS_ENCODER 0
+%define CONFIG_QTRLE_ENCODER 0
+%define CONFIG_R10K_ENCODER 0
+%define CONFIG_R210_ENCODER 0
+%define CONFIG_RAWVIDEO_ENCODER 0
+%define CONFIG_ROQ_ENCODER 0
+%define CONFIG_RV10_ENCODER 0
+%define CONFIG_RV20_ENCODER 0
+%define CONFIG_S302M_ENCODER 0
+%define CONFIG_SGI_ENCODER 0
+%define CONFIG_SNOW_ENCODER 0
+%define CONFIG_SUNRAST_ENCODER 0
+%define CONFIG_SVQ1_ENCODER 0
+%define CONFIG_TARGA_ENCODER 0
+%define CONFIG_TIFF_ENCODER 0
+%define CONFIG_UTVIDEO_ENCODER 0
+%define CONFIG_V210_ENCODER 0
+%define CONFIG_V308_ENCODER 0
+%define CONFIG_V408_ENCODER 0
+%define CONFIG_V410_ENCODER 0
+%define CONFIG_VC2_ENCODER 0
+%define CONFIG_WRAPPED_AVFRAME_ENCODER 0
+%define CONFIG_WMV1_ENCODER 0
+%define CONFIG_WMV2_ENCODER 0
+%define CONFIG_XBM_ENCODER 0
+%define CONFIG_XFACE_ENCODER 0
+%define CONFIG_XWD_ENCODER 0
+%define CONFIG_Y41P_ENCODER 0
+%define CONFIG_YUV4_ENCODER 0
+%define CONFIG_ZLIB_ENCODER 0
+%define CONFIG_ZMBV_ENCODER 0
+%define CONFIG_AAC_ENCODER 0
+%define CONFIG_AC3_ENCODER 0
+%define CONFIG_AC3_FIXED_ENCODER 0
+%define CONFIG_ALAC_ENCODER 0
+%define CONFIG_DCA_ENCODER 0
+%define CONFIG_EAC3_ENCODER 0
+%define CONFIG_FLAC_ENCODER 0
+%define CONFIG_G723_1_ENCODER 0
+%define CONFIG_MLP_ENCODER 0
+%define CONFIG_MP2_ENCODER 0
+%define CONFIG_MP2FIXED_ENCODER 0
+%define CONFIG_NELLYMOSER_ENCODER 0
+%define CONFIG_OPUS_ENCODER 0
+%define CONFIG_RA_144_ENCODER 0
+%define CONFIG_SONIC_ENCODER 0
+%define CONFIG_SONIC_LS_ENCODER 0
+%define CONFIG_TRUEHD_ENCODER 0
+%define CONFIG_TTA_ENCODER 0
+%define CONFIG_VORBIS_ENCODER 0
+%define CONFIG_WAVPACK_ENCODER 0
+%define CONFIG_WMAV1_ENCODER 0
+%define CONFIG_WMAV2_ENCODER 0
+%define CONFIG_PCM_ALAW_ENCODER 0
+%define CONFIG_PCM_F32BE_ENCODER 0
+%define CONFIG_PCM_F32LE_ENCODER 0
+%define CONFIG_PCM_F64BE_ENCODER 0
+%define CONFIG_PCM_F64LE_ENCODER 0
+%define CONFIG_PCM_MULAW_ENCODER 0
+%define CONFIG_PCM_S8_ENCODER 0
+%define CONFIG_PCM_S8_PLANAR_ENCODER 0
+%define CONFIG_PCM_S16BE_ENCODER 0
+%define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
+%define CONFIG_PCM_S16LE_ENCODER 0
+%define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
+%define CONFIG_PCM_S24BE_ENCODER 0
+%define CONFIG_PCM_S24DAUD_ENCODER 0
+%define CONFIG_PCM_S24LE_ENCODER 0
+%define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
+%define CONFIG_PCM_S32BE_ENCODER 0
+%define CONFIG_PCM_S32LE_ENCODER 0
+%define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
+%define CONFIG_PCM_S64BE_ENCODER 0
+%define CONFIG_PCM_S64LE_ENCODER 0
+%define CONFIG_PCM_U8_ENCODER 0
+%define CONFIG_PCM_U16BE_ENCODER 0
+%define CONFIG_PCM_U16LE_ENCODER 0
+%define CONFIG_PCM_U24BE_ENCODER 0
+%define CONFIG_PCM_U24LE_ENCODER 0
+%define CONFIG_PCM_U32BE_ENCODER 0
+%define CONFIG_PCM_U32LE_ENCODER 0
+%define CONFIG_ROQ_DPCM_ENCODER 0
+%define CONFIG_ADPCM_ADX_ENCODER 0
+%define CONFIG_ADPCM_G722_ENCODER 0
+%define CONFIG_ADPCM_G726_ENCODER 0
+%define CONFIG_ADPCM_G726LE_ENCODER 0
+%define CONFIG_ADPCM_IMA_QT_ENCODER 0
+%define CONFIG_ADPCM_IMA_WAV_ENCODER 0
+%define CONFIG_ADPCM_MS_ENCODER 0
+%define CONFIG_ADPCM_SWF_ENCODER 0
+%define CONFIG_ADPCM_YAMAHA_ENCODER 0
+%define CONFIG_SSA_ENCODER 0
+%define CONFIG_ASS_ENCODER 0
+%define CONFIG_DVBSUB_ENCODER 0
+%define CONFIG_DVDSUB_ENCODER 0
+%define CONFIG_MOVTEXT_ENCODER 0
+%define CONFIG_SRT_ENCODER 0
+%define CONFIG_SUBRIP_ENCODER 0
+%define CONFIG_TEXT_ENCODER 0
+%define CONFIG_WEBVTT_ENCODER 0
+%define CONFIG_XSUB_ENCODER 0
+%define CONFIG_AAC_AT_ENCODER 0
+%define CONFIG_ALAC_AT_ENCODER 0
+%define CONFIG_ILBC_AT_ENCODER 0
+%define CONFIG_PCM_ALAW_AT_ENCODER 0
+%define CONFIG_PCM_MULAW_AT_ENCODER 0
+%define CONFIG_LIBFDK_AAC_ENCODER 0
+%define CONFIG_LIBGSM_ENCODER 0
+%define CONFIG_LIBGSM_MS_ENCODER 0
+%define CONFIG_LIBILBC_ENCODER 0
+%define CONFIG_LIBMP3LAME_ENCODER 0
+%define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
+%define CONFIG_LIBOPENJPEG_ENCODER 0
+%define CONFIG_LIBOPUS_ENCODER 0
+%define CONFIG_LIBSHINE_ENCODER 0
+%define CONFIG_LIBSPEEX_ENCODER 0
+%define CONFIG_LIBTHEORA_ENCODER 0
+%define CONFIG_LIBTWOLAME_ENCODER 0
+%define CONFIG_LIBVO_AMRWBENC_ENCODER 0
+%define CONFIG_LIBVORBIS_ENCODER 0
+%define CONFIG_LIBVPX_VP8_ENCODER 0
+%define CONFIG_LIBVPX_VP9_ENCODER 0
+%define CONFIG_LIBWAVPACK_ENCODER 0
+%define CONFIG_LIBWEBP_ANIM_ENCODER 0
+%define CONFIG_LIBWEBP_ENCODER 0
+%define CONFIG_LIBX262_ENCODER 0
+%define CONFIG_LIBX264_ENCODER 0
+%define CONFIG_LIBX264RGB_ENCODER 0
+%define CONFIG_LIBX265_ENCODER 0
+%define CONFIG_LIBXAVS_ENCODER 0
+%define CONFIG_LIBXVID_ENCODER 0
+%define CONFIG_H263_V4L2M2M_ENCODER 0
+%define CONFIG_LIBOPENH264_ENCODER 0
+%define CONFIG_H264_NVENC_ENCODER 0
+%define CONFIG_H264_OMX_ENCODER 0
+%define CONFIG_H264_QSV_ENCODER 0
+%define CONFIG_H264_V4L2M2M_ENCODER 0
+%define CONFIG_H264_VAAPI_ENCODER 0
+%define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
+%define CONFIG_NVENC_ENCODER 0
+%define CONFIG_NVENC_H264_ENCODER 0
+%define CONFIG_NVENC_HEVC_ENCODER 0
+%define CONFIG_HEVC_NVENC_ENCODER 0
+%define CONFIG_HEVC_QSV_ENCODER 0
+%define CONFIG_HEVC_V4L2M2M_ENCODER 0
+%define CONFIG_HEVC_VAAPI_ENCODER 0
+%define CONFIG_LIBKVAZAAR_ENCODER 0
+%define CONFIG_MJPEG_VAAPI_ENCODER 0
+%define CONFIG_MPEG2_QSV_ENCODER 0
+%define CONFIG_MPEG2_VAAPI_ENCODER 0
+%define CONFIG_MPEG4_V4L2M2M_ENCODER 0
+%define CONFIG_VP8_V4L2M2M_ENCODER 0
+%define CONFIG_VP8_VAAPI_ENCODER 0
+%define CONFIG_VP9_VAAPI_ENCODER 0
+%define CONFIG_ABENCH_FILTER 0
+%define CONFIG_ACOMPRESSOR_FILTER 0
+%define CONFIG_ACOPY_FILTER 0
+%define CONFIG_ACROSSFADE_FILTER 0
+%define CONFIG_ACRUSHER_FILTER 0
+%define CONFIG_ADELAY_FILTER 0
+%define CONFIG_AECHO_FILTER 0
+%define CONFIG_AEMPHASIS_FILTER 0
+%define CONFIG_AEVAL_FILTER 0
+%define CONFIG_AFADE_FILTER 0
+%define CONFIG_AFFTFILT_FILTER 0
+%define CONFIG_AFIR_FILTER 0
+%define CONFIG_AFORMAT_FILTER 0
+%define CONFIG_AGATE_FILTER 0
+%define CONFIG_AINTERLEAVE_FILTER 0
+%define CONFIG_ALIMITER_FILTER 0
+%define CONFIG_ALLPASS_FILTER 0
+%define CONFIG_ALOOP_FILTER 0
+%define CONFIG_AMERGE_FILTER 0
+%define CONFIG_AMETADATA_FILTER 0
+%define CONFIG_AMIX_FILTER 0
+%define CONFIG_ANEQUALIZER_FILTER 0
+%define CONFIG_ANULL_FILTER 0
+%define CONFIG_APAD_FILTER 0
+%define CONFIG_APERMS_FILTER 0
+%define CONFIG_APHASER_FILTER 0
+%define CONFIG_APULSATOR_FILTER 0
+%define CONFIG_AREALTIME_FILTER 0
+%define CONFIG_ARESAMPLE_FILTER 0
+%define CONFIG_AREVERSE_FILTER 0
+%define CONFIG_ASELECT_FILTER 0
+%define CONFIG_ASENDCMD_FILTER 0
+%define CONFIG_ASETNSAMPLES_FILTER 0
+%define CONFIG_ASETPTS_FILTER 0
+%define CONFIG_ASETRATE_FILTER 0
+%define CONFIG_ASETTB_FILTER 0
+%define CONFIG_ASHOWINFO_FILTER 0
+%define CONFIG_ASIDEDATA_FILTER 0
+%define CONFIG_ASPLIT_FILTER 0
+%define CONFIG_ASTATS_FILTER 0
+%define CONFIG_ASTREAMSELECT_FILTER 0
+%define CONFIG_ATEMPO_FILTER 0
+%define CONFIG_ATRIM_FILTER 0
+%define CONFIG_AZMQ_FILTER 0
+%define CONFIG_BANDPASS_FILTER 0
+%define CONFIG_BANDREJECT_FILTER 0
+%define CONFIG_BASS_FILTER 0
+%define CONFIG_BIQUAD_FILTER 0
+%define CONFIG_BS2B_FILTER 0
+%define CONFIG_CHANNELMAP_FILTER 0
+%define CONFIG_CHANNELSPLIT_FILTER 0
+%define CONFIG_CHORUS_FILTER 0
+%define CONFIG_COMPAND_FILTER 0
+%define CONFIG_COMPENSATIONDELAY_FILTER 0
+%define CONFIG_CROSSFEED_FILTER 0
+%define CONFIG_CRYSTALIZER_FILTER 0
+%define CONFIG_DCSHIFT_FILTER 0
+%define CONFIG_DYNAUDNORM_FILTER 0
+%define CONFIG_EARWAX_FILTER 0
+%define CONFIG_EBUR128_FILTER 0
+%define CONFIG_EQUALIZER_FILTER 0
+%define CONFIG_EXTRASTEREO_FILTER 0
+%define CONFIG_FIREQUALIZER_FILTER 0
+%define CONFIG_FLANGER_FILTER 0
+%define CONFIG_HAAS_FILTER 0
+%define CONFIG_HDCD_FILTER 0
+%define CONFIG_HEADPHONE_FILTER 0
+%define CONFIG_HIGHPASS_FILTER 0
+%define CONFIG_JOIN_FILTER 0
+%define CONFIG_LADSPA_FILTER 0
+%define CONFIG_LOUDNORM_FILTER 0
+%define CONFIG_LOWPASS_FILTER 0
+%define CONFIG_PAN_FILTER 0
+%define CONFIG_REPLAYGAIN_FILTER 0
+%define CONFIG_RESAMPLE_FILTER 0
+%define CONFIG_RUBBERBAND_FILTER 0
+%define CONFIG_SIDECHAINCOMPRESS_FILTER 0
+%define CONFIG_SIDECHAINGATE_FILTER 0
+%define CONFIG_SILENCEDETECT_FILTER 0
+%define CONFIG_SILENCEREMOVE_FILTER 0
+%define CONFIG_SOFALIZER_FILTER 0
+%define CONFIG_STEREOTOOLS_FILTER 0
+%define CONFIG_STEREOWIDEN_FILTER 0
+%define CONFIG_SUPEREQUALIZER_FILTER 0
+%define CONFIG_SURROUND_FILTER 0
+%define CONFIG_TREBLE_FILTER 0
+%define CONFIG_TREMOLO_FILTER 0
+%define CONFIG_VIBRATO_FILTER 0
+%define CONFIG_VOLUME_FILTER 0
+%define CONFIG_VOLUMEDETECT_FILTER 0
+%define CONFIG_AEVALSRC_FILTER 0
+%define CONFIG_ANOISESRC_FILTER 0
+%define CONFIG_ANULLSRC_FILTER 0
+%define CONFIG_FLITE_FILTER 0
+%define CONFIG_SINE_FILTER 0
+%define CONFIG_ANULLSINK_FILTER 0
+%define CONFIG_ALPHAEXTRACT_FILTER 0
+%define CONFIG_ALPHAMERGE_FILTER 0
+%define CONFIG_ASS_FILTER 0
+%define CONFIG_ATADENOISE_FILTER 0
+%define CONFIG_AVGBLUR_FILTER 0
+%define CONFIG_BBOX_FILTER 0
+%define CONFIG_BENCH_FILTER 0
+%define CONFIG_BITPLANENOISE_FILTER 0
+%define CONFIG_BLACKDETECT_FILTER 0
+%define CONFIG_BLACKFRAME_FILTER 0
+%define CONFIG_BLEND_FILTER 0
+%define CONFIG_BOXBLUR_FILTER 0
+%define CONFIG_BWDIF_FILTER 0
+%define CONFIG_CHROMAKEY_FILTER 0
+%define CONFIG_CIESCOPE_FILTER 0
+%define CONFIG_CODECVIEW_FILTER 0
+%define CONFIG_COLORBALANCE_FILTER 0
+%define CONFIG_COLORCHANNELMIXER_FILTER 0
+%define CONFIG_COLORKEY_FILTER 0
+%define CONFIG_COLORLEVELS_FILTER 0
+%define CONFIG_COLORMATRIX_FILTER 0
+%define CONFIG_COLORSPACE_FILTER 0
+%define CONFIG_CONVOLUTION_FILTER 0
+%define CONFIG_CONVOLVE_FILTER 0
+%define CONFIG_COPY_FILTER 0
+%define CONFIG_COREIMAGE_FILTER 0
+%define CONFIG_COVER_RECT_FILTER 0
+%define CONFIG_CROP_FILTER 0
+%define CONFIG_CROPDETECT_FILTER 0
+%define CONFIG_CURVES_FILTER 0
+%define CONFIG_DATASCOPE_FILTER 0
+%define CONFIG_DCTDNOIZ_FILTER 0
+%define CONFIG_DEBAND_FILTER 0
+%define CONFIG_DECIMATE_FILTER 0
+%define CONFIG_DEFLATE_FILTER 0
+%define CONFIG_DEFLICKER_FILTER 0
+%define CONFIG_DEINTERLACE_QSV_FILTER 0
+%define CONFIG_DEINTERLACE_VAAPI_FILTER 0
+%define CONFIG_DEJUDDER_FILTER 0
+%define CONFIG_DELOGO_FILTER 0
+%define CONFIG_DESHAKE_FILTER 0
+%define CONFIG_DESPILL_FILTER 0
+%define CONFIG_DETELECINE_FILTER 0
+%define CONFIG_DILATION_FILTER 0
+%define CONFIG_DISPLACE_FILTER 0
+%define CONFIG_DOUBLEWEAVE_FILTER 0
+%define CONFIG_DRAWBOX_FILTER 0
+%define CONFIG_DRAWGRAPH_FILTER 0
+%define CONFIG_DRAWGRID_FILTER 0
+%define CONFIG_DRAWTEXT_FILTER 0
+%define CONFIG_EDGEDETECT_FILTER 0
+%define CONFIG_ELBG_FILTER 0
+%define CONFIG_EQ_FILTER 0
+%define CONFIG_EROSION_FILTER 0
+%define CONFIG_EXTRACTPLANES_FILTER 0
+%define CONFIG_FADE_FILTER 0
+%define CONFIG_FFTFILT_FILTER 0
+%define CONFIG_FIELD_FILTER 0
+%define CONFIG_FIELDHINT_FILTER 0
+%define CONFIG_FIELDMATCH_FILTER 0
+%define CONFIG_FIELDORDER_FILTER 0
+%define CONFIG_FIND_RECT_FILTER 0
+%define CONFIG_FLOODFILL_FILTER 0
+%define CONFIG_FORMAT_FILTER 0
+%define CONFIG_FPS_FILTER 0
+%define CONFIG_FRAMEPACK_FILTER 0
+%define CONFIG_FRAMERATE_FILTER 0
+%define CONFIG_FRAMESTEP_FILTER 0
+%define CONFIG_FREI0R_FILTER 0
+%define CONFIG_FSPP_FILTER 0
+%define CONFIG_GBLUR_FILTER 0
+%define CONFIG_GEQ_FILTER 0
+%define CONFIG_GRADFUN_FILTER 0
+%define CONFIG_HALDCLUT_FILTER 0
+%define CONFIG_HFLIP_FILTER 0
+%define CONFIG_HISTEQ_FILTER 0
+%define CONFIG_HISTOGRAM_FILTER 0
+%define CONFIG_HQDN3D_FILTER 0
+%define CONFIG_HQX_FILTER 0
+%define CONFIG_HSTACK_FILTER 0
+%define CONFIG_HUE_FILTER 0
+%define CONFIG_HWDOWNLOAD_FILTER 0
+%define CONFIG_HWMAP_FILTER 0
+%define CONFIG_HWUPLOAD_FILTER 0
+%define CONFIG_HWUPLOAD_CUDA_FILTER 0
+%define CONFIG_HYSTERESIS_FILTER 0
+%define CONFIG_IDET_FILTER 0
+%define CONFIG_IL_FILTER 0
+%define CONFIG_INFLATE_FILTER 0
+%define CONFIG_INTERLACE_FILTER 0
+%define CONFIG_INTERLEAVE_FILTER 0
+%define CONFIG_KERNDEINT_FILTER 0
+%define CONFIG_LENSCORRECTION_FILTER 0
+%define CONFIG_LIBVMAF_FILTER 0
+%define CONFIG_LIMITER_FILTER 0
+%define CONFIG_LOOP_FILTER 0
+%define CONFIG_LUMAKEY_FILTER 0
+%define CONFIG_LUT_FILTER 0
+%define CONFIG_LUT2_FILTER 0
+%define CONFIG_LUT3D_FILTER 0
+%define CONFIG_LUTRGB_FILTER 0
+%define CONFIG_LUTYUV_FILTER 0
+%define CONFIG_MASKEDCLAMP_FILTER 0
+%define CONFIG_MASKEDMERGE_FILTER 0
+%define CONFIG_MCDEINT_FILTER 0
+%define CONFIG_MERGEPLANES_FILTER 0
+%define CONFIG_MESTIMATE_FILTER 0
+%define CONFIG_METADATA_FILTER 0
+%define CONFIG_MIDEQUALIZER_FILTER 0
+%define CONFIG_MINTERPOLATE_FILTER 0
+%define CONFIG_MPDECIMATE_FILTER 0
+%define CONFIG_NEGATE_FILTER 0
+%define CONFIG_NLMEANS_FILTER 0
+%define CONFIG_NNEDI_FILTER 0
+%define CONFIG_NOFORMAT_FILTER 0
+%define CONFIG_NOISE_FILTER 0
+%define CONFIG_NULL_FILTER 0
+%define CONFIG_OCR_FILTER 0
+%define CONFIG_OCV_FILTER 0
+%define CONFIG_OSCILLOSCOPE_FILTER 0
+%define CONFIG_OVERLAY_FILTER 0
+%define CONFIG_OWDENOISE_FILTER 0
+%define CONFIG_PAD_FILTER 0
+%define CONFIG_PALETTEGEN_FILTER 0
+%define CONFIG_PALETTEUSE_FILTER 0
+%define CONFIG_PERMS_FILTER 0
+%define CONFIG_PERSPECTIVE_FILTER 0
+%define CONFIG_PHASE_FILTER 0
+%define CONFIG_PIXDESCTEST_FILTER 0
+%define CONFIG_PIXSCOPE_FILTER 0
+%define CONFIG_PP_FILTER 0
+%define CONFIG_PP7_FILTER 0
+%define CONFIG_PREMULTIPLY_FILTER 0
+%define CONFIG_PREWITT_FILTER 0
+%define CONFIG_PSEUDOCOLOR_FILTER 0
+%define CONFIG_PSNR_FILTER 0
+%define CONFIG_PULLUP_FILTER 0
+%define CONFIG_QP_FILTER 0
+%define CONFIG_RANDOM_FILTER 0
+%define CONFIG_READEIA608_FILTER 0
+%define CONFIG_READVITC_FILTER 0
+%define CONFIG_REALTIME_FILTER 0
+%define CONFIG_REMAP_FILTER 0
+%define CONFIG_REMOVEGRAIN_FILTER 0
+%define CONFIG_REMOVELOGO_FILTER 0
+%define CONFIG_REPEATFIELDS_FILTER 0
+%define CONFIG_REVERSE_FILTER 0
+%define CONFIG_ROBERTS_FILTER 0
+%define CONFIG_ROTATE_FILTER 0
+%define CONFIG_SAB_FILTER 0
+%define CONFIG_SCALE_FILTER 0
+%define CONFIG_SCALE_CUDA_FILTER 0
+%define CONFIG_SCALE_NPP_FILTER 0
+%define CONFIG_SCALE_QSV_FILTER 0
+%define CONFIG_SCALE_VAAPI_FILTER 0
+%define CONFIG_SCALE2REF_FILTER 0
+%define CONFIG_SELECT_FILTER 0
+%define CONFIG_SELECTIVECOLOR_FILTER 0
+%define CONFIG_SENDCMD_FILTER 0
+%define CONFIG_SEPARATEFIELDS_FILTER 0
+%define CONFIG_SETDAR_FILTER 0
+%define CONFIG_SETFIELD_FILTER 0
+%define CONFIG_SETPTS_FILTER 0
+%define CONFIG_SETSAR_FILTER 0
+%define CONFIG_SETTB_FILTER 0
+%define CONFIG_SHOWINFO_FILTER 0
+%define CONFIG_SHOWPALETTE_FILTER 0
+%define CONFIG_SHUFFLEFRAMES_FILTER 0
+%define CONFIG_SHUFFLEPLANES_FILTER 0
+%define CONFIG_SIDEDATA_FILTER 0
+%define CONFIG_SIGNALSTATS_FILTER 0
+%define CONFIG_SIGNATURE_FILTER 0
+%define CONFIG_SMARTBLUR_FILTER 0
+%define CONFIG_SOBEL_FILTER 0
+%define CONFIG_SPLIT_FILTER 0
+%define CONFIG_SPP_FILTER 0
+%define CONFIG_SSIM_FILTER 0
+%define CONFIG_STEREO3D_FILTER 0
+%define CONFIG_STREAMSELECT_FILTER 0
+%define CONFIG_SUBTITLES_FILTER 0
+%define CONFIG_SUPER2XSAI_FILTER 0
+%define CONFIG_SWAPRECT_FILTER 0
+%define CONFIG_SWAPUV_FILTER 0
+%define CONFIG_TBLEND_FILTER 0
+%define CONFIG_TELECINE_FILTER 0
+%define CONFIG_THRESHOLD_FILTER 0
+%define CONFIG_THUMBNAIL_FILTER 0
+%define CONFIG_THUMBNAIL_CUDA_FILTER 0
+%define CONFIG_TILE_FILTER 0
+%define CONFIG_TINTERLACE_FILTER 0
+%define CONFIG_TLUT2_FILTER 0
+%define CONFIG_TONEMAP_FILTER 0
+%define CONFIG_TRANSPOSE_FILTER 0
+%define CONFIG_TRIM_FILTER 0
+%define CONFIG_UNPREMULTIPLY_FILTER 0
+%define CONFIG_UNSHARP_FILTER 0
+%define CONFIG_USPP_FILTER 0
+%define CONFIG_VAGUEDENOISER_FILTER 0
+%define CONFIG_VECTORSCOPE_FILTER 0
+%define CONFIG_VFLIP_FILTER 0
+%define CONFIG_VIDSTABDETECT_FILTER 0
+%define CONFIG_VIDSTABTRANSFORM_FILTER 0
+%define CONFIG_VIGNETTE_FILTER 0
+%define CONFIG_VMAFMOTION_FILTER 0
+%define CONFIG_VSTACK_FILTER 0
+%define CONFIG_W3FDIF_FILTER 0
+%define CONFIG_WAVEFORM_FILTER 0
+%define CONFIG_WEAVE_FILTER 0
+%define CONFIG_XBR_FILTER 0
+%define CONFIG_YADIF_FILTER 0
+%define CONFIG_ZMQ_FILTER 0
+%define CONFIG_ZOOMPAN_FILTER 0
+%define CONFIG_ZSCALE_FILTER 0
+%define CONFIG_ALLRGB_FILTER 0
+%define CONFIG_ALLYUV_FILTER 0
+%define CONFIG_CELLAUTO_FILTER 0
+%define CONFIG_COLOR_FILTER 0
+%define CONFIG_COREIMAGESRC_FILTER 0
+%define CONFIG_FREI0R_SRC_FILTER 0
+%define CONFIG_HALDCLUTSRC_FILTER 0
+%define CONFIG_LIFE_FILTER 0
+%define CONFIG_MANDELBROT_FILTER 0
+%define CONFIG_MPTESTSRC_FILTER 0
+%define CONFIG_NULLSRC_FILTER 0
+%define CONFIG_RGBTESTSRC_FILTER 0
+%define CONFIG_SMPTEBARS_FILTER 0
+%define CONFIG_SMPTEHDBARS_FILTER 0
+%define CONFIG_TESTSRC_FILTER 0
+%define CONFIG_TESTSRC2_FILTER 0
+%define CONFIG_YUVTESTSRC_FILTER 0
+%define CONFIG_NULLSINK_FILTER 0
+%define CONFIG_ABITSCOPE_FILTER 0
+%define CONFIG_ADRAWGRAPH_FILTER 0
+%define CONFIG_AHISTOGRAM_FILTER 0
+%define CONFIG_APHASEMETER_FILTER 0
+%define CONFIG_AVECTORSCOPE_FILTER 0
+%define CONFIG_CONCAT_FILTER 0
+%define CONFIG_SHOWCQT_FILTER 0
+%define CONFIG_SHOWFREQS_FILTER 0
+%define CONFIG_SHOWSPECTRUM_FILTER 0
+%define CONFIG_SHOWSPECTRUMPIC_FILTER 0
+%define CONFIG_SHOWVOLUME_FILTER 0
+%define CONFIG_SHOWWAVES_FILTER 0
+%define CONFIG_SHOWWAVESPIC_FILTER 0
+%define CONFIG_SPECTRUMSYNTH_FILTER 0
+%define CONFIG_AMOVIE_FILTER 0
+%define CONFIG_MOVIE_FILTER 0
+%define CONFIG_H263_VAAPI_HWACCEL 0
+%define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_H264_CUVID_HWACCEL 0
+%define CONFIG_H264_D3D11VA_HWACCEL 0
+%define CONFIG_H264_D3D11VA2_HWACCEL 0
+%define CONFIG_H264_DXVA2_HWACCEL 0
+%define CONFIG_H264_MEDIACODEC_HWACCEL 0
+%define CONFIG_H264_MMAL_HWACCEL 0
+%define CONFIG_H264_QSV_HWACCEL 0
+%define CONFIG_H264_VAAPI_HWACCEL 0
+%define CONFIG_H264_VDA_HWACCEL 0
+%define CONFIG_H264_VDA_OLD_HWACCEL 0
+%define CONFIG_H264_VDPAU_HWACCEL 0
+%define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_HEVC_CUVID_HWACCEL 0
+%define CONFIG_HEVC_D3D11VA_HWACCEL 0
+%define CONFIG_HEVC_D3D11VA2_HWACCEL 0
+%define CONFIG_HEVC_DXVA2_HWACCEL 0
+%define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
+%define CONFIG_HEVC_QSV_HWACCEL 0
+%define CONFIG_HEVC_VAAPI_HWACCEL 0
+%define CONFIG_HEVC_VDPAU_HWACCEL 0
+%define CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_MJPEG_CUVID_HWACCEL 0
+%define CONFIG_MPEG1_CUVID_HWACCEL 0
+%define CONFIG_MPEG1_XVMC_HWACCEL 0
+%define CONFIG_MPEG1_VDPAU_HWACCEL 0
+%define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_MPEG2_CUVID_HWACCEL 0
+%define CONFIG_MPEG2_XVMC_HWACCEL 0
+%define CONFIG_MPEG2_D3D11VA_HWACCEL 0
+%define CONFIG_MPEG2_D3D11VA2_HWACCEL 0
+%define CONFIG_MPEG2_DXVA2_HWACCEL 0
+%define CONFIG_MPEG2_MMAL_HWACCEL 0
+%define CONFIG_MPEG2_QSV_HWACCEL 0
+%define CONFIG_MPEG2_VAAPI_HWACCEL 0
+%define CONFIG_MPEG2_VDPAU_HWACCEL 0
+%define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_MPEG2_MEDIACODEC_HWACCEL 0
+%define CONFIG_MPEG4_CUVID_HWACCEL 0
+%define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
+%define CONFIG_MPEG4_MMAL_HWACCEL 0
+%define CONFIG_MPEG4_VAAPI_HWACCEL 0
+%define CONFIG_MPEG4_VDPAU_HWACCEL 0
+%define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
+%define CONFIG_VC1_CUVID_HWACCEL 0
+%define CONFIG_VC1_D3D11VA_HWACCEL 0
+%define CONFIG_VC1_D3D11VA2_HWACCEL 0
+%define CONFIG_VC1_DXVA2_HWACCEL 0
+%define CONFIG_VC1_VAAPI_HWACCEL 0
+%define CONFIG_VC1_VDPAU_HWACCEL 0
+%define CONFIG_VC1_MMAL_HWACCEL 0
+%define CONFIG_VC1_QSV_HWACCEL 0
+%define CONFIG_VP8_CUVID_HWACCEL 0
+%define CONFIG_VP8_MEDIACODEC_HWACCEL 0
+%define CONFIG_VP8_QSV_HWACCEL 0
+%define CONFIG_VP9_CUVID_HWACCEL 0
+%define CONFIG_VP9_D3D11VA_HWACCEL 0
+%define CONFIG_VP9_D3D11VA2_HWACCEL 0
+%define CONFIG_VP9_DXVA2_HWACCEL 0
+%define CONFIG_VP9_MEDIACODEC_HWACCEL 0
+%define CONFIG_VP9_VAAPI_HWACCEL 0
+%define CONFIG_WMV3_D3D11VA_HWACCEL 0
+%define CONFIG_WMV3_D3D11VA2_HWACCEL 0
+%define CONFIG_WMV3_DXVA2_HWACCEL 0
+%define CONFIG_WMV3_VAAPI_HWACCEL 0
+%define CONFIG_WMV3_VDPAU_HWACCEL 0
+%define CONFIG_ALSA_INDEV 0
+%define CONFIG_AVFOUNDATION_INDEV 0
+%define CONFIG_BKTR_INDEV 0
+%define CONFIG_DECKLINK_INDEV 0
+%define CONFIG_LIBNDI_NEWTEK_INDEV 0
+%define CONFIG_DSHOW_INDEV 0
+%define CONFIG_FBDEV_INDEV 0
+%define CONFIG_GDIGRAB_INDEV 0
+%define CONFIG_IEC61883_INDEV 0
+%define CONFIG_JACK_INDEV 0
+%define CONFIG_KMSGRAB_INDEV 0
+%define CONFIG_LAVFI_INDEV 0
+%define CONFIG_OPENAL_INDEV 0
+%define CONFIG_OSS_INDEV 0
+%define CONFIG_PULSE_INDEV 0
+%define CONFIG_SNDIO_INDEV 0
+%define CONFIG_V4L2_INDEV 0
+%define CONFIG_VFWCAP_INDEV 0
+%define CONFIG_XCBGRAB_INDEV 0
+%define CONFIG_LIBCDIO_INDEV 0
+%define CONFIG_LIBDC1394_INDEV 0
+%define CONFIG_A64_MUXER 0
+%define CONFIG_AC3_MUXER 0
+%define CONFIG_ADTS_MUXER 0
+%define CONFIG_ADX_MUXER 0
+%define CONFIG_AIFF_MUXER 0
+%define CONFIG_AMR_MUXER 0
+%define CONFIG_APNG_MUXER 0
+%define CONFIG_ASF_MUXER 0
+%define CONFIG_ASS_MUXER 0
+%define CONFIG_AST_MUXER 0
+%define CONFIG_ASF_STREAM_MUXER 0
+%define CONFIG_AU_MUXER 0
+%define CONFIG_AVI_MUXER 0
+%define CONFIG_AVM2_MUXER 0
+%define CONFIG_BIT_MUXER 0
+%define CONFIG_CAF_MUXER 0
+%define CONFIG_CAVSVIDEO_MUXER 0
+%define CONFIG_CRC_MUXER 0
+%define CONFIG_DASH_MUXER 0
+%define CONFIG_DATA_MUXER 0
+%define CONFIG_DAUD_MUXER 0
+%define CONFIG_DIRAC_MUXER 0
+%define CONFIG_DNXHD_MUXER 0
+%define CONFIG_DTS_MUXER 0
+%define CONFIG_DV_MUXER 0
+%define CONFIG_EAC3_MUXER 0
+%define CONFIG_F4V_MUXER 0
+%define CONFIG_FFM_MUXER 0
+%define CONFIG_FFMETADATA_MUXER 0
+%define CONFIG_FIFO_MUXER 0
+%define CONFIG_FILMSTRIP_MUXER 0
+%define CONFIG_FITS_MUXER 0
+%define CONFIG_FLAC_MUXER 0
+%define CONFIG_FLV_MUXER 0
+%define CONFIG_FRAMECRC_MUXER 0
+%define CONFIG_FRAMEHASH_MUXER 0
+%define CONFIG_FRAMEMD5_MUXER 0
+%define CONFIG_G722_MUXER 0
+%define CONFIG_G723_1_MUXER 0
+%define CONFIG_G726_MUXER 0
+%define CONFIG_G726LE_MUXER 0
+%define CONFIG_GIF_MUXER 0
+%define CONFIG_GSM_MUXER 0
+%define CONFIG_GXF_MUXER 0
+%define CONFIG_H261_MUXER 0
+%define CONFIG_H263_MUXER 0
+%define CONFIG_H264_MUXER 0
+%define CONFIG_HASH_MUXER 0
+%define CONFIG_HDS_MUXER 0
+%define CONFIG_HEVC_MUXER 0
+%define CONFIG_HLS_MUXER 0
+%define CONFIG_ICO_MUXER 0
+%define CONFIG_ILBC_MUXER 0
+%define CONFIG_IMAGE2_MUXER 0
+%define CONFIG_IMAGE2PIPE_MUXER 0
+%define CONFIG_IPOD_MUXER 0
+%define CONFIG_IRCAM_MUXER 0
+%define CONFIG_ISMV_MUXER 0
+%define CONFIG_IVF_MUXER 0
+%define CONFIG_JACOSUB_MUXER 0
+%define CONFIG_LATM_MUXER 0
+%define CONFIG_LRC_MUXER 0
+%define CONFIG_M4V_MUXER 0
+%define CONFIG_MD5_MUXER 0
+%define CONFIG_MATROSKA_MUXER 0
+%define CONFIG_MATROSKA_AUDIO_MUXER 0
+%define CONFIG_MICRODVD_MUXER 0
+%define CONFIG_MJPEG_MUXER 0
+%define CONFIG_MLP_MUXER 0
+%define CONFIG_MMF_MUXER 0
+%define CONFIG_MOV_MUXER 0
+%define CONFIG_MP2_MUXER 0
+%define CONFIG_MP3_MUXER 0
+%define CONFIG_MP4_MUXER 0
+%define CONFIG_MPEG1SYSTEM_MUXER 0
+%define CONFIG_MPEG1VCD_MUXER 0
+%define CONFIG_MPEG1VIDEO_MUXER 0
+%define CONFIG_MPEG2DVD_MUXER 0
+%define CONFIG_MPEG2SVCD_MUXER 0
+%define CONFIG_MPEG2VIDEO_MUXER 0
+%define CONFIG_MPEG2VOB_MUXER 0
+%define CONFIG_MPEGTS_MUXER 0
+%define CONFIG_MPJPEG_MUXER 0
+%define CONFIG_MXF_MUXER 0
+%define CONFIG_MXF_D10_MUXER 0
+%define CONFIG_MXF_OPATOM_MUXER 0
+%define CONFIG_NULL_MUXER 0
+%define CONFIG_NUT_MUXER 0
+%define CONFIG_OGA_MUXER 0
+%define CONFIG_OGG_MUXER 0
+%define CONFIG_OGV_MUXER 0
+%define CONFIG_OMA_MUXER 0
+%define CONFIG_OPUS_MUXER 0
+%define CONFIG_PCM_ALAW_MUXER 0
+%define CONFIG_PCM_MULAW_MUXER 0
+%define CONFIG_PCM_F64BE_MUXER 0
+%define CONFIG_PCM_F64LE_MUXER 0
+%define CONFIG_PCM_F32BE_MUXER 0
+%define CONFIG_PCM_F32LE_MUXER 0
+%define CONFIG_PCM_S32BE_MUXER 0
+%define CONFIG_PCM_S32LE_MUXER 0
+%define CONFIG_PCM_S24BE_MUXER 0
+%define CONFIG_PCM_S24LE_MUXER 0
+%define CONFIG_PCM_S16BE_MUXER 0
+%define CONFIG_PCM_S16LE_MUXER 0
+%define CONFIG_PCM_S8_MUXER 0
+%define CONFIG_PCM_U32BE_MUXER 0
+%define CONFIG_PCM_U32LE_MUXER 0
+%define CONFIG_PCM_U24BE_MUXER 0
+%define CONFIG_PCM_U24LE_MUXER 0
+%define CONFIG_PCM_U16BE_MUXER 0
+%define CONFIG_PCM_U16LE_MUXER 0
+%define CONFIG_PCM_U8_MUXER 0
+%define CONFIG_PSP_MUXER 0
+%define CONFIG_RAWVIDEO_MUXER 0
+%define CONFIG_RM_MUXER 0
+%define CONFIG_ROQ_MUXER 0
+%define CONFIG_RSO_MUXER 0
+%define CONFIG_RTP_MUXER 0
+%define CONFIG_RTP_MPEGTS_MUXER 0
+%define CONFIG_RTSP_MUXER 0
+%define CONFIG_SAP_MUXER 0
+%define CONFIG_SCC_MUXER 0
+%define CONFIG_SEGMENT_MUXER 0
+%define CONFIG_STREAM_SEGMENT_MUXER 0
+%define CONFIG_SINGLEJPEG_MUXER 0
+%define CONFIG_SMJPEG_MUXER 0
+%define CONFIG_SMOOTHSTREAMING_MUXER 0
+%define CONFIG_SOX_MUXER 0
+%define CONFIG_SPX_MUXER 0
+%define CONFIG_SPDIF_MUXER 0
+%define CONFIG_SRT_MUXER 0
+%define CONFIG_SUP_MUXER 0
+%define CONFIG_SWF_MUXER 0
+%define CONFIG_TEE_MUXER 0
+%define CONFIG_TG2_MUXER 0
+%define CONFIG_TGP_MUXER 0
+%define CONFIG_MKVTIMESTAMP_V2_MUXER 0
+%define CONFIG_TRUEHD_MUXER 0
+%define CONFIG_TTA_MUXER 0
+%define CONFIG_UNCODEDFRAMECRC_MUXER 0
+%define CONFIG_VC1_MUXER 0
+%define CONFIG_VC1T_MUXER 0
+%define CONFIG_VOC_MUXER 0
+%define CONFIG_W64_MUXER 0
+%define CONFIG_WAV_MUXER 0
+%define CONFIG_WEBM_MUXER 0
+%define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
+%define CONFIG_WEBM_CHUNK_MUXER 0
+%define CONFIG_WEBP_MUXER 0
+%define CONFIG_WEBVTT_MUXER 0
+%define CONFIG_WTV_MUXER 0
+%define CONFIG_WV_MUXER 0
+%define CONFIG_YUV4MPEGPIPE_MUXER 0
+%define CONFIG_CHROMAPRINT_MUXER 0
+%define CONFIG_ALSA_OUTDEV 0
+%define CONFIG_CACA_OUTDEV 0
+%define CONFIG_DECKLINK_OUTDEV 0
+%define CONFIG_LIBNDI_NEWTEK_OUTDEV 0
+%define CONFIG_FBDEV_OUTDEV 0
+%define CONFIG_OPENGL_OUTDEV 0
+%define CONFIG_OSS_OUTDEV 0
+%define CONFIG_PULSE_OUTDEV 0
+%define CONFIG_SDL2_OUTDEV 0
+%define CONFIG_SNDIO_OUTDEV 0
+%define CONFIG_V4L2_OUTDEV 0
+%define CONFIG_XV_OUTDEV 0
+%define CONFIG_AAC_PARSER 0
+%define CONFIG_AAC_LATM_PARSER 0
+%define CONFIG_AC3_PARSER 0
+%define CONFIG_ADX_PARSER 0
+%define CONFIG_BMP_PARSER 0
+%define CONFIG_CAVSVIDEO_PARSER 0
+%define CONFIG_COOK_PARSER 0
+%define CONFIG_DCA_PARSER 0
+%define CONFIG_DIRAC_PARSER 0
+%define CONFIG_DNXHD_PARSER 0
+%define CONFIG_DPX_PARSER 0
+%define CONFIG_DVAUDIO_PARSER 0
+%define CONFIG_DVBSUB_PARSER 0
+%define CONFIG_DVDSUB_PARSER 0
+%define CONFIG_DVD_NAV_PARSER 0
+%define CONFIG_G729_PARSER 0
+%define CONFIG_GSM_PARSER 0
+%define CONFIG_H261_PARSER 0
+%define CONFIG_H263_PARSER 0
+%define CONFIG_H264_PARSER 0
+%define CONFIG_HEVC_PARSER 0
+%define CONFIG_MJPEG_PARSER 0
+%define CONFIG_MLP_PARSER 0
+%define CONFIG_MPEG4VIDEO_PARSER 0
+%define CONFIG_MPEGAUDIO_PARSER 0
+%define CONFIG_MPEGVIDEO_PARSER 0
+%define CONFIG_OPUS_PARSER 0
+%define CONFIG_PNG_PARSER 0
+%define CONFIG_PNM_PARSER 0
+%define CONFIG_RV30_PARSER 0
+%define CONFIG_RV40_PARSER 0
+%define CONFIG_SIPR_PARSER 0
+%define CONFIG_TAK_PARSER 0
+%define CONFIG_VC1_PARSER 0
+%define CONFIG_VORBIS_PARSER 0
+%define CONFIG_VP3_PARSER 0
+%define CONFIG_XMA_PARSER 0
+%define CONFIG_ASYNC_PROTOCOL 0
+%define CONFIG_BLURAY_PROTOCOL 0
+%define CONFIG_CACHE_PROTOCOL 0
+%define CONFIG_CONCAT_PROTOCOL 0
+%define CONFIG_CRYPTO_PROTOCOL 0
+%define CONFIG_DATA_PROTOCOL 0
+%define CONFIG_FFRTMPCRYPT_PROTOCOL 0
+%define CONFIG_FFRTMPHTTP_PROTOCOL 0
+%define CONFIG_FILE_PROTOCOL 0
+%define CONFIG_FTP_PROTOCOL 0
+%define CONFIG_GOPHER_PROTOCOL 0
+%define CONFIG_HLS_PROTOCOL 0
+%define CONFIG_HTTP_PROTOCOL 0
+%define CONFIG_HTTPPROXY_PROTOCOL 0
+%define CONFIG_HTTPS_PROTOCOL 0
+%define CONFIG_ICECAST_PROTOCOL 0
+%define CONFIG_MMSH_PROTOCOL 0
+%define CONFIG_MMST_PROTOCOL 0
+%define CONFIG_MD5_PROTOCOL 0
+%define CONFIG_PIPE_PROTOCOL 0
+%define CONFIG_PROMPEG_PROTOCOL 0
+%define CONFIG_RTMP_PROTOCOL 0
+%define CONFIG_RTMPE_PROTOCOL 0
+%define CONFIG_RTMPS_PROTOCOL 0
+%define CONFIG_RTMPT_PROTOCOL 0
+%define CONFIG_RTMPTE_PROTOCOL 0
+%define CONFIG_RTMPTS_PROTOCOL 0
+%define CONFIG_RTP_PROTOCOL 0
+%define CONFIG_SCTP_PROTOCOL 0
+%define CONFIG_SRTP_PROTOCOL 0
+%define CONFIG_SUBFILE_PROTOCOL 0
+%define CONFIG_TEE_PROTOCOL 0
+%define CONFIG_TCP_PROTOCOL 0
+%define CONFIG_TLS_GNUTLS_PROTOCOL 0
+%define CONFIG_TLS_SCHANNEL_PROTOCOL 0
+%define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
+%define CONFIG_TLS_OPENSSL_PROTOCOL 0
+%define CONFIG_UDP_PROTOCOL 0
+%define CONFIG_UDPLITE_PROTOCOL 0
+%define CONFIG_UNIX_PROTOCOL 0
+%define CONFIG_LIBRTMP_PROTOCOL 0
+%define CONFIG_LIBRTMPE_PROTOCOL 0
+%define CONFIG_LIBRTMPS_PROTOCOL 0
+%define CONFIG_LIBRTMPT_PROTOCOL 0
+%define CONFIG_LIBRTMPTE_PROTOCOL 0
+%define CONFIG_LIBSSH_PROTOCOL 0
+%define CONFIG_LIBSMBCLIENT_PROTOCOL 0
diff --git a/media/ffvpx/defaults_disabled.h b/media/ffvpx/defaults_disabled.h
new file mode 100644
index 000000000..e526aa9e7
--- /dev/null
+++ b/media/ffvpx/defaults_disabled.h
@@ -0,0 +1,1674 @@
+#define CONFIG_ENCODERS 0
+#define CONFIG_HWACCELS 0
+#define CONFIG_INDEVS 0
+#define CONFIG_OUTDEVS 0
+#define CONFIG_FILTERS 0
+#define CONFIG_DEMUXERS 0
+#define CONFIG_MUXERS 0
+#define CONFIG_PROTOCOLS 0
+#define CONFIG_FRAME_THREAD_ENCODER 0
+#define CONFIG_AASC_DECODER 0
+#define CONFIG_AIC_DECODER 0
+#define CONFIG_ALIAS_PIX_DECODER 0
+#define CONFIG_AMV_DECODER 0
+#define CONFIG_ANM_DECODER 0
+#define CONFIG_ANSI_DECODER 0
+#define CONFIG_APNG_DECODER 0
+#define CONFIG_ASV1_DECODER 0
+#define CONFIG_ASV2_DECODER 0
+#define CONFIG_AURA_DECODER 0
+#define CONFIG_AURA2_DECODER 0
+#define CONFIG_AVRP_DECODER 0
+#define CONFIG_AVRN_DECODER 0
+#define CONFIG_AVS_DECODER 0
+#define CONFIG_AVUI_DECODER 0
+#define CONFIG_AYUV_DECODER 0
+#define CONFIG_BETHSOFTVID_DECODER 0
+#define CONFIG_BFI_DECODER 0
+#define CONFIG_BINK_DECODER 0
+#define CONFIG_BMP_DECODER 0
+#define CONFIG_BMV_VIDEO_DECODER 0
+#define CONFIG_BRENDER_PIX_DECODER 0
+#define CONFIG_C93_DECODER 0
+#define CONFIG_CAVS_DECODER 0
+#define CONFIG_CDGRAPHICS_DECODER 0
+#define CONFIG_CDXL_DECODER 0
+#define CONFIG_CFHD_DECODER 0
+#define CONFIG_CINEPAK_DECODER 0
+#define CONFIG_CLEARVIDEO_DECODER 0
+#define CONFIG_CLJR_DECODER 0
+#define CONFIG_CLLC_DECODER 0
+#define CONFIG_COMFORTNOISE_DECODER 0
+#define CONFIG_CPIA_DECODER 0
+#define CONFIG_CSCD_DECODER 0
+#define CONFIG_CYUV_DECODER 0
+#define CONFIG_DDS_DECODER 0
+#define CONFIG_DFA_DECODER 0
+#define CONFIG_DIRAC_DECODER 0
+#define CONFIG_DNXHD_DECODER 0
+#define CONFIG_DPX_DECODER 0
+#define CONFIG_DSICINVIDEO_DECODER 0
+#define CONFIG_DVAUDIO_DECODER 0
+#define CONFIG_DVVIDEO_DECODER 0
+#define CONFIG_DXA_DECODER 0
+#define CONFIG_DXTORY_DECODER 0
+#define CONFIG_DXV_DECODER 0
+#define CONFIG_EACMV_DECODER 0
+#define CONFIG_EAMAD_DECODER 0
+#define CONFIG_EATGQ_DECODER 0
+#define CONFIG_EATGV_DECODER 0
+#define CONFIG_EATQI_DECODER 0
+#define CONFIG_EIGHTBPS_DECODER 0
+#define CONFIG_EIGHTSVX_EXP_DECODER 0
+#define CONFIG_EIGHTSVX_FIB_DECODER 0
+#define CONFIG_ESCAPE124_DECODER 0
+#define CONFIG_ESCAPE130_DECODER 0
+#define CONFIG_EXR_DECODER 0
+#define CONFIG_FFV1_DECODER 0
+#define CONFIG_FFVHUFF_DECODER 0
+#define CONFIG_FIC_DECODER 0
+#define CONFIG_FITS_DECODER 0
+#define CONFIG_FLASHSV_DECODER 0
+#define CONFIG_FLASHSV2_DECODER 0
+#define CONFIG_FLIC_DECODER 0
+#define CONFIG_FLV_DECODER 0
+#define CONFIG_FMVC_DECODER 0
+#define CONFIG_FOURXM_DECODER 0
+#define CONFIG_FRAPS_DECODER 0
+#define CONFIG_FRWU_DECODER 0
+#define CONFIG_G2M_DECODER 0
+#define CONFIG_GDV_DECODER 0
+#define CONFIG_GIF_DECODER 0
+#define CONFIG_H261_DECODER 0
+#define CONFIG_H263_DECODER 0
+#define CONFIG_H263I_DECODER 0
+#define CONFIG_H263P_DECODER 0
+#define CONFIG_H263_V4L2M2M_DECODER 0
+#define CONFIG_H264_DECODER 0
+#define CONFIG_H264_CRYSTALHD_DECODER 0
+#define CONFIG_H264_V4L2M2M_DECODER 0
+#define CONFIG_H264_MEDIACODEC_DECODER 0
+#define CONFIG_H264_MMAL_DECODER 0
+#define CONFIG_H264_QSV_DECODER 0
+#define CONFIG_H264_RKMPP_DECODER 0
+#define CONFIG_H264_VDA_DECODER 0
+#define CONFIG_H264_VDPAU_DECODER 0
+#define CONFIG_HAP_DECODER 0
+#define CONFIG_HEVC_DECODER 0
+#define CONFIG_HEVC_QSV_DECODER 0
+#define CONFIG_HEVC_RKMPP_DECODER 0
+#define CONFIG_HEVC_V4L2M2M_DECODER 0
+#define CONFIG_HNM4_VIDEO_DECODER 0
+#define CONFIG_HQ_HQA_DECODER 0
+#define CONFIG_HQX_DECODER 0
+#define CONFIG_HUFFYUV_DECODER 0
+#define CONFIG_IDCIN_DECODER 0
+#define CONFIG_IFF_ILBM_DECODER 0
+#define CONFIG_INDEO2_DECODER 0
+#define CONFIG_INDEO3_DECODER 0
+#define CONFIG_INDEO4_DECODER 0
+#define CONFIG_INDEO5_DECODER 0
+#define CONFIG_INTERPLAY_VIDEO_DECODER 0
+#define CONFIG_JPEG2000_DECODER 0
+#define CONFIG_JPEGLS_DECODER 0
+#define CONFIG_JV_DECODER 0
+#define CONFIG_KGV1_DECODER 0
+#define CONFIG_KMVC_DECODER 0
+#define CONFIG_LAGARITH_DECODER 0
+#define CONFIG_LOCO_DECODER 0
+#define CONFIG_M101_DECODER 0
+#define CONFIG_MAGICYUV_DECODER 0
+#define CONFIG_MDEC_DECODER 0
+#define CONFIG_MIMIC_DECODER 0
+#define CONFIG_MJPEG_DECODER 0
+#define CONFIG_MJPEGB_DECODER 0
+#define CONFIG_MMVIDEO_DECODER 0
+#define CONFIG_MOTIONPIXELS_DECODER 0
+#define CONFIG_MPEG_XVMC_DECODER 0
+#define CONFIG_MPEG1VIDEO_DECODER 0
+#define CONFIG_MPEG2VIDEO_DECODER 0
+#define CONFIG_MPEG4_DECODER 0
+#define CONFIG_MPEG4_CRYSTALHD_DECODER 0
+#define CONFIG_MPEG4_V4L2M2M_DECODER 0
+#define CONFIG_MPEG4_MMAL_DECODER 0
+#define CONFIG_MPEG4_VDPAU_DECODER 0
+#define CONFIG_MPEGVIDEO_DECODER 0
+#define CONFIG_MPEG_VDPAU_DECODER 0
+#define CONFIG_MPEG1_VDPAU_DECODER 0
+#define CONFIG_MPEG1_V4L2M2M_DECODER 0
+#define CONFIG_MPEG2_MMAL_DECODER 0
+#define CONFIG_MPEG2_CRYSTALHD_DECODER 0
+#define CONFIG_MPEG2_V4L2M2M_DECODER 0
+#define CONFIG_MPEG2_QSV_DECODER 0
+#define CONFIG_MPEG2_MEDIACODEC_DECODER 0
+#define CONFIG_MSA1_DECODER 0
+#define CONFIG_MSCC_DECODER 0
+#define CONFIG_MSMPEG4V1_DECODER 0
+#define CONFIG_MSMPEG4V2_DECODER 0
+#define CONFIG_MSMPEG4V3_DECODER 0
+#define CONFIG_MSMPEG4_CRYSTALHD_DECODER 0
+#define CONFIG_MSRLE_DECODER 0
+#define CONFIG_MSS1_DECODER 0
+#define CONFIG_MSS2_DECODER 0
+#define CONFIG_MSVIDEO1_DECODER 0
+#define CONFIG_MSZH_DECODER 0
+#define CONFIG_MTS2_DECODER 0
+#define CONFIG_MVC1_DECODER 0
+#define CONFIG_MVC2_DECODER 0
+#define CONFIG_MXPEG_DECODER 0
+#define CONFIG_NUV_DECODER 0
+#define CONFIG_PAF_VIDEO_DECODER 0
+#define CONFIG_PAM_DECODER 0
+#define CONFIG_PBM_DECODER 0
+#define CONFIG_PCX_DECODER 0
+#define CONFIG_PGM_DECODER 0
+#define CONFIG_PGMYUV_DECODER 0
+#define CONFIG_PICTOR_DECODER 0
+#define CONFIG_PIXLET_DECODER 0
+#define CONFIG_PNG_DECODER 0
+#define CONFIG_PPM_DECODER 0
+#define CONFIG_PRORES_DECODER 0
+#define CONFIG_PRORES_LGPL_DECODER 0
+#define CONFIG_PSD_DECODER 0
+#define CONFIG_PTX_DECODER 0
+#define CONFIG_QDRAW_DECODER 0
+#define CONFIG_QPEG_DECODER 0
+#define CONFIG_QTRLE_DECODER 0
+#define CONFIG_R10K_DECODER 0
+#define CONFIG_R210_DECODER 0
+#define CONFIG_RAWVIDEO_DECODER 0
+#define CONFIG_RL2_DECODER 0
+#define CONFIG_ROQ_DECODER 0
+#define CONFIG_RPZA_DECODER 0
+#define CONFIG_RSCC_DECODER 0
+#define CONFIG_RV10_DECODER 0
+#define CONFIG_RV20_DECODER 0
+#define CONFIG_RV30_DECODER 0
+#define CONFIG_RV40_DECODER 0
+#define CONFIG_S302M_DECODER 0
+#define CONFIG_SANM_DECODER 0
+#define CONFIG_SCPR_DECODER 0
+#define CONFIG_SCREENPRESSO_DECODER 0
+#define CONFIG_SDX2_DPCM_DECODER 0
+#define CONFIG_SGI_DECODER 0
+#define CONFIG_SGIRLE_DECODER 0
+#define CONFIG_SHEERVIDEO_DECODER 0
+#define CONFIG_SMACKER_DECODER 0
+#define CONFIG_SMC_DECODER 0
+#define CONFIG_SMVJPEG_DECODER 0
+#define CONFIG_SNOW_DECODER 0
+#define CONFIG_SP5X_DECODER 0
+#define CONFIG_SPEEDHQ_DECODER 0
+#define CONFIG_SRGC_DECODER 0
+#define CONFIG_SUNRAST_DECODER 0
+#define CONFIG_SVQ1_DECODER 0
+#define CONFIG_SVQ3_DECODER 0
+#define CONFIG_TARGA_DECODER 0
+#define CONFIG_TARGA_Y216_DECODER 0
+#define CONFIG_TDSC_DECODER 0
+#define CONFIG_THEORA_DECODER 0
+#define CONFIG_THP_DECODER 0
+#define CONFIG_TIERTEXSEQVIDEO_DECODER 0
+#define CONFIG_TIFF_DECODER 0
+#define CONFIG_TMV_DECODER 0
+#define CONFIG_TRUEMOTION1_DECODER 0
+#define CONFIG_TRUEMOTION2_DECODER 0
+#define CONFIG_TRUEMOTION2RT_DECODER 0
+#define CONFIG_TSCC_DECODER 0
+#define CONFIG_TSCC2_DECODER 0
+#define CONFIG_TXD_DECODER 0
+#define CONFIG_ULTI_DECODER 0
+#define CONFIG_UTVIDEO_DECODER 0
+#define CONFIG_V210_DECODER 0
+#define CONFIG_V210X_DECODER 0
+#define CONFIG_V308_DECODER 0
+#define CONFIG_V408_DECODER 0
+#define CONFIG_V410_DECODER 0
+#define CONFIG_VB_DECODER 0
+#define CONFIG_VBLE_DECODER 0
+#define CONFIG_VC1_DECODER 0
+#define CONFIG_VC1_CRYSTALHD_DECODER 0
+#define CONFIG_VC1_VDPAU_DECODER 0
+#define CONFIG_VC1IMAGE_DECODER 0
+#define CONFIG_VC1_MMAL_DECODER 0
+#define CONFIG_VC1_QSV_DECODER 0
+#define CONFIG_VC1_V4L2M2M_DECODER 0
+#define CONFIG_VCR1_DECODER 0
+#define CONFIG_VMDVIDEO_DECODER 0
+#define CONFIG_VMNC_DECODER 0
+#define CONFIG_VP3_DECODER 0
+#define CONFIG_VP5_DECODER 0
+#define CONFIG_VP6_DECODER 0
+#define CONFIG_VP6A_DECODER 0
+#define CONFIG_VP6F_DECODER 0
+#define CONFIG_VP7_DECODER 0
+#define CONFIG_VP8_RKMPP_DECODER 0
+#define CONFIG_VP8_V4L2M2M_DECODER 0
+#define CONFIG_VP9_RKMPP_DECODER 0
+#define CONFIG_VP9_V4L2M2M_DECODER 0
+#define CONFIG_VQA_DECODER 0
+#define CONFIG_BITPACKED_DECODER 0
+#define CONFIG_WEBP_DECODER 0
+#define CONFIG_WRAPPED_AVFRAME_DECODER 0
+#define CONFIG_WMV1_DECODER 0
+#define CONFIG_WMV2_DECODER 0
+#define CONFIG_WMV3_DECODER 0
+#define CONFIG_WMV3_CRYSTALHD_DECODER 0
+#define CONFIG_WMV3_VDPAU_DECODER 0
+#define CONFIG_WMV3IMAGE_DECODER 0
+#define CONFIG_WNV1_DECODER 0
+#define CONFIG_XAN_WC3_DECODER 0
+#define CONFIG_XAN_WC4_DECODER 0
+#define CONFIG_XBM_DECODER 0
+#define CONFIG_XFACE_DECODER 0
+#define CONFIG_XL_DECODER 0
+#define CONFIG_XPM_DECODER 0
+#define CONFIG_XWD_DECODER 0
+#define CONFIG_Y41P_DECODER 0
+#define CONFIG_YLC_DECODER 0
+#define CONFIG_YOP_DECODER 0
+#define CONFIG_YUV4_DECODER 0
+#define CONFIG_ZERO12V_DECODER 0
+#define CONFIG_ZEROCODEC_DECODER 0
+#define CONFIG_ZLIB_DECODER 0
+#define CONFIG_ZMBV_DECODER 0
+#define CONFIG_AAC_DECODER 0
+#define CONFIG_AAC_FIXED_DECODER 0
+#define CONFIG_AAC_LATM_DECODER 0
+#define CONFIG_AC3_DECODER 0
+#define CONFIG_AC3_FIXED_DECODER 0
+#define CONFIG_ALAC_DECODER 0
+#define CONFIG_ALS_DECODER 0
+#define CONFIG_AMRNB_DECODER 0
+#define CONFIG_AMRWB_DECODER 0
+#define CONFIG_APE_DECODER 0
+#define CONFIG_ATRAC1_DECODER 0
+#define CONFIG_ATRAC3_DECODER 0
+#define CONFIG_ATRAC3AL_DECODER 0
+#define CONFIG_ATRAC3P_DECODER 0
+#define CONFIG_ATRAC3PAL_DECODER 0
+#define CONFIG_BINKAUDIO_DCT_DECODER 0
+#define CONFIG_BINKAUDIO_RDFT_DECODER 0
+#define CONFIG_BMV_AUDIO_DECODER 0
+#define CONFIG_COOK_DECODER 0
+#define CONFIG_DCA_DECODER 0
+#define CONFIG_DOLBY_E_DECODER 0
+#define CONFIG_DSD_LSBF_DECODER 0
+#define CONFIG_DSD_MSBF_DECODER 0
+#define CONFIG_DSD_LSBF_PLANAR_DECODER 0
+#define CONFIG_DSD_MSBF_PLANAR_DECODER 0
+#define CONFIG_DSICINAUDIO_DECODER 0
+#define CONFIG_DSS_SP_DECODER 0
+#define CONFIG_DST_DECODER 0
+#define CONFIG_EAC3_DECODER 0
+#define CONFIG_EVRC_DECODER 0
+#define CONFIG_FFWAVESYNTH_DECODER 0
+#define CONFIG_G723_1_DECODER 0
+#define CONFIG_G729_DECODER 0
+#define CONFIG_GSM_DECODER 0
+#define CONFIG_GSM_MS_DECODER 0
+#define CONFIG_IAC_DECODER 0
+#define CONFIG_IMC_DECODER 0
+#define CONFIG_INTERPLAY_ACM_DECODER 0
+#define CONFIG_MACE3_DECODER 0
+#define CONFIG_MACE6_DECODER 0
+#define CONFIG_METASOUND_DECODER 0
+#define CONFIG_MLP_DECODER 0
+#define CONFIG_MP1_DECODER 0
+#define CONFIG_MP1FLOAT_DECODER 0
+#define CONFIG_MP2_DECODER 0
+#define CONFIG_MP2FLOAT_DECODER 0
+#define CONFIG_MP3_DECODER 0
+#define CONFIG_MP3FLOAT_DECODER 0
+#define CONFIG_MP3ADU_DECODER 0
+#define CONFIG_MP3ADUFLOAT_DECODER 0
+#define CONFIG_MP3ON4_DECODER 0
+#define CONFIG_MP3ON4FLOAT_DECODER 0
+#define CONFIG_MPC7_DECODER 0
+#define CONFIG_MPC8_DECODER 0
+#define CONFIG_NELLYMOSER_DECODER 0
+#define CONFIG_ON2AVC_DECODER 0
+#define CONFIG_OPUS_DECODER 0
+#define CONFIG_PAF_AUDIO_DECODER 0
+#define CONFIG_QCELP_DECODER 0
+#define CONFIG_QDM2_DECODER 0
+#define CONFIG_QDMC_DECODER 0
+#define CONFIG_RA_144_DECODER 0
+#define CONFIG_RA_288_DECODER 0
+#define CONFIG_RALF_DECODER 0
+#define CONFIG_SHORTEN_DECODER 0
+#define CONFIG_SIPR_DECODER 0
+#define CONFIG_SMACKAUD_DECODER 0
+#define CONFIG_SONIC_DECODER 0
+#define CONFIG_TAK_DECODER 0
+#define CONFIG_TRUEHD_DECODER 0
+#define CONFIG_TRUESPEECH_DECODER 0
+#define CONFIG_TTA_DECODER 0
+#define CONFIG_TWINVQ_DECODER 0
+#define CONFIG_VMDAUDIO_DECODER 0
+#define CONFIG_VORBIS_DECODER 0
+#define CONFIG_WAVPACK_DECODER 0
+#define CONFIG_WMALOSSLESS_DECODER 0
+#define CONFIG_WMAPRO_DECODER 0
+#define CONFIG_WMAV1_DECODER 0
+#define CONFIG_WMAV2_DECODER 0
+#define CONFIG_WMAVOICE_DECODER 0
+#define CONFIG_WS_SND1_DECODER 0
+#define CONFIG_XMA1_DECODER 0
+#define CONFIG_XMA2_DECODER 0
+#define CONFIG_PCM_ALAW_DECODER 0
+#define CONFIG_PCM_BLURAY_DECODER 0
+#define CONFIG_PCM_DVD_DECODER 0
+#define CONFIG_PCM_F16LE_DECODER 0
+#define CONFIG_PCM_F24LE_DECODER 0
+#define CONFIG_PCM_F32BE_DECODER 0
+#define CONFIG_PCM_F32LE_DECODER 0
+#define CONFIG_PCM_F64BE_DECODER 0
+#define CONFIG_PCM_F64LE_DECODER 0
+#define CONFIG_PCM_LXF_DECODER 0
+#define CONFIG_PCM_MULAW_DECODER 0
+#define CONFIG_PCM_S8_DECODER 0
+#define CONFIG_PCM_S8_PLANAR_DECODER 0
+#define CONFIG_PCM_S16BE_DECODER 0
+#define CONFIG_PCM_S16BE_PLANAR_DECODER 0
+#define CONFIG_PCM_S16LE_DECODER 0
+#define CONFIG_PCM_S16LE_PLANAR_DECODER 0
+#define CONFIG_PCM_S24BE_DECODER 0
+#define CONFIG_PCM_S24DAUD_DECODER 0
+#define CONFIG_PCM_S24LE_DECODER 0
+#define CONFIG_PCM_S24LE_PLANAR_DECODER 0
+#define CONFIG_PCM_S32BE_DECODER 0
+#define CONFIG_PCM_S32LE_DECODER 0
+#define CONFIG_PCM_S32LE_PLANAR_DECODER 0
+#define CONFIG_PCM_S64BE_DECODER 0
+#define CONFIG_PCM_S64LE_DECODER 0
+#define CONFIG_PCM_U8_DECODER 0
+#define CONFIG_PCM_U16BE_DECODER 0
+#define CONFIG_PCM_U16LE_DECODER 0
+#define CONFIG_PCM_U24BE_DECODER 0
+#define CONFIG_PCM_U24LE_DECODER 0
+#define CONFIG_PCM_U32BE_DECODER 0
+#define CONFIG_PCM_U32LE_DECODER 0
+#define CONFIG_PCM_ZORK_DECODER 0
+#define CONFIG_GREMLIN_DPCM_DECODER 0
+#define CONFIG_INTERPLAY_DPCM_DECODER 0
+#define CONFIG_ROQ_DPCM_DECODER 0
+#define CONFIG_SOL_DPCM_DECODER 0
+#define CONFIG_XAN_DPCM_DECODER 0
+#define CONFIG_ADPCM_4XM_DECODER 0
+#define CONFIG_ADPCM_ADX_DECODER 0
+#define CONFIG_ADPCM_AFC_DECODER 0
+#define CONFIG_ADPCM_AICA_DECODER 0
+#define CONFIG_ADPCM_CT_DECODER 0
+#define CONFIG_ADPCM_DTK_DECODER 0
+#define CONFIG_ADPCM_EA_DECODER 0
+#define CONFIG_ADPCM_EA_MAXIS_XA_DECODER 0
+#define CONFIG_ADPCM_EA_R1_DECODER 0
+#define CONFIG_ADPCM_EA_R2_DECODER 0
+#define CONFIG_ADPCM_EA_R3_DECODER 0
+#define CONFIG_ADPCM_EA_XAS_DECODER 0
+#define CONFIG_ADPCM_G722_DECODER 0
+#define CONFIG_ADPCM_G726_DECODER 0
+#define CONFIG_ADPCM_G726LE_DECODER 0
+#define CONFIG_ADPCM_IMA_AMV_DECODER 0
+#define CONFIG_ADPCM_IMA_APC_DECODER 0
+#define CONFIG_ADPCM_IMA_DAT4_DECODER 0
+#define CONFIG_ADPCM_IMA_DK3_DECODER 0
+#define CONFIG_ADPCM_IMA_DK4_DECODER 0
+#define CONFIG_ADPCM_IMA_EA_EACS_DECODER 0
+#define CONFIG_ADPCM_IMA_EA_SEAD_DECODER 0
+#define CONFIG_ADPCM_IMA_ISS_DECODER 0
+#define CONFIG_ADPCM_IMA_OKI_DECODER 0
+#define CONFIG_ADPCM_IMA_QT_DECODER 0
+#define CONFIG_ADPCM_IMA_RAD_DECODER 0
+#define CONFIG_ADPCM_IMA_SMJPEG_DECODER 0
+#define CONFIG_ADPCM_IMA_WAV_DECODER 0
+#define CONFIG_ADPCM_IMA_WS_DECODER 0
+#define CONFIG_ADPCM_MS_DECODER 0
+#define CONFIG_ADPCM_MTAF_DECODER 0
+#define CONFIG_ADPCM_PSX_DECODER 0
+#define CONFIG_ADPCM_SBPRO_2_DECODER 0
+#define CONFIG_ADPCM_SBPRO_3_DECODER 0
+#define CONFIG_ADPCM_SBPRO_4_DECODER 0
+#define CONFIG_ADPCM_SWF_DECODER 0
+#define CONFIG_ADPCM_THP_DECODER 0
+#define CONFIG_ADPCM_THP_LE_DECODER 0
+#define CONFIG_ADPCM_VIMA_DECODER 0
+#define CONFIG_ADPCM_XA_DECODER 0
+#define CONFIG_ADPCM_YAMAHA_DECODER 0
+#define CONFIG_SSA_DECODER 0
+#define CONFIG_ASS_DECODER 0
+#define CONFIG_CCAPTION_DECODER 0
+#define CONFIG_DVBSUB_DECODER 0
+#define CONFIG_DVDSUB_DECODER 0
+#define CONFIG_JACOSUB_DECODER 0
+#define CONFIG_MICRODVD_DECODER 0
+#define CONFIG_MOVTEXT_DECODER 0
+#define CONFIG_MPL2_DECODER 0
+#define CONFIG_PGSSUB_DECODER 0
+#define CONFIG_PJS_DECODER 0
+#define CONFIG_REALTEXT_DECODER 0
+#define CONFIG_SAMI_DECODER 0
+#define CONFIG_SRT_DECODER 0
+#define CONFIG_STL_DECODER 0
+#define CONFIG_SUBRIP_DECODER 0
+#define CONFIG_SUBVIEWER_DECODER 0
+#define CONFIG_SUBVIEWER1_DECODER 0
+#define CONFIG_TEXT_DECODER 0
+#define CONFIG_VPLAYER_DECODER 0
+#define CONFIG_WEBVTT_DECODER 0
+#define CONFIG_XSUB_DECODER 0
+#define CONFIG_AAC_AT_DECODER 0
+#define CONFIG_AC3_AT_DECODER 0
+#define CONFIG_ADPCM_IMA_QT_AT_DECODER 0
+#define CONFIG_ALAC_AT_DECODER 0
+#define CONFIG_AMR_NB_AT_DECODER 0
+#define CONFIG_EAC3_AT_DECODER 0
+#define CONFIG_GSM_MS_AT_DECODER 0
+#define CONFIG_ILBC_AT_DECODER 0
+#define CONFIG_MP1_AT_DECODER 0
+#define CONFIG_MP2_AT_DECODER 0
+#define CONFIG_MP3_AT_DECODER 0
+#define CONFIG_PCM_ALAW_AT_DECODER 0
+#define CONFIG_PCM_MULAW_AT_DECODER 0
+#define CONFIG_QDMC_AT_DECODER 0
+#define CONFIG_QDM2_AT_DECODER 0
+#define CONFIG_LIBCELT_DECODER 0
+#define CONFIG_LIBFDK_AAC_DECODER 0
+#define CONFIG_LIBGSM_DECODER 0
+#define CONFIG_LIBGSM_MS_DECODER 0
+#define CONFIG_LIBILBC_DECODER 0
+#define CONFIG_LIBOPENCORE_AMRNB_DECODER 0
+#define CONFIG_LIBOPENCORE_AMRWB_DECODER 0
+#define CONFIG_LIBOPENJPEG_DECODER 0
+#define CONFIG_LIBOPUS_DECODER 0
+#define CONFIG_LIBRSVG_DECODER 0
+#define CONFIG_LIBSPEEX_DECODER 0
+#define CONFIG_LIBVORBIS_DECODER 0
+#define CONFIG_LIBVPX_VP8_DECODER 0
+#define CONFIG_LIBVPX_VP9_DECODER 0
+#define CONFIG_LIBZVBI_TELETEXT_DECODER 0
+#define CONFIG_BINTEXT_DECODER 0
+#define CONFIG_XBIN_DECODER 0
+#define CONFIG_IDF_DECODER 0
+#define CONFIG_LIBOPENH264_DECODER 0
+#define CONFIG_H264_CUVID_DECODER 0
+#define CONFIG_HEVC_CUVID_DECODER 0
+#define CONFIG_HEVC_MEDIACODEC_DECODER 0
+#define CONFIG_MJPEG_CUVID_DECODER 0
+#define CONFIG_MPEG1_CUVID_DECODER 0
+#define CONFIG_MPEG2_CUVID_DECODER 0
+#define CONFIG_MPEG4_CUVID_DECODER 0
+#define CONFIG_MPEG4_MEDIACODEC_DECODER 0
+#define CONFIG_VC1_CUVID_DECODER 0
+#define CONFIG_VP8_CUVID_DECODER 0
+#define CONFIG_VP8_MEDIACODEC_DECODER 0
+#define CONFIG_VP8_QSV_DECODER 0
+#define CONFIG_VP9_CUVID_DECODER 0
+#define CONFIG_VP9_MEDIACODEC_DECODER 0
+#define CONFIG_AA_DEMUXER 0
+#define CONFIG_AAC_DEMUXER 0
+#define CONFIG_AC3_DEMUXER 0
+#define CONFIG_ACM_DEMUXER 0
+#define CONFIG_ACT_DEMUXER 0
+#define CONFIG_ADF_DEMUXER 0
+#define CONFIG_ADP_DEMUXER 0
+#define CONFIG_ADS_DEMUXER 0
+#define CONFIG_ADX_DEMUXER 0
+#define CONFIG_AEA_DEMUXER 0
+#define CONFIG_AFC_DEMUXER 0
+#define CONFIG_AIFF_DEMUXER 0
+#define CONFIG_AIX_DEMUXER 0
+#define CONFIG_AMR_DEMUXER 0
+#define CONFIG_ANM_DEMUXER 0
+#define CONFIG_APC_DEMUXER 0
+#define CONFIG_APE_DEMUXER 0
+#define CONFIG_APNG_DEMUXER 0
+#define CONFIG_AQTITLE_DEMUXER 0
+#define CONFIG_ASF_DEMUXER 0
+#define CONFIG_ASF_O_DEMUXER 0
+#define CONFIG_ASS_DEMUXER 0
+#define CONFIG_AST_DEMUXER 0
+#define CONFIG_AU_DEMUXER 0
+#define CONFIG_AVI_DEMUXER 0
+#define CONFIG_AVISYNTH_DEMUXER 0
+#define CONFIG_AVR_DEMUXER 0
+#define CONFIG_AVS_DEMUXER 0
+#define CONFIG_BETHSOFTVID_DEMUXER 0
+#define CONFIG_BFI_DEMUXER 0
+#define CONFIG_BINTEXT_DEMUXER 0
+#define CONFIG_BINK_DEMUXER 0
+#define CONFIG_BIT_DEMUXER 0
+#define CONFIG_BMV_DEMUXER 0
+#define CONFIG_BFSTM_DEMUXER 0
+#define CONFIG_BRSTM_DEMUXER 0
+#define CONFIG_BOA_DEMUXER 0
+#define CONFIG_C93_DEMUXER 0
+#define CONFIG_CAF_DEMUXER 0
+#define CONFIG_CAVSVIDEO_DEMUXER 0
+#define CONFIG_CDG_DEMUXER 0
+#define CONFIG_CDXL_DEMUXER 0
+#define CONFIG_CINE_DEMUXER 0
+#define CONFIG_CONCAT_DEMUXER 0
+#define CONFIG_DASH_DEMUXER 0
+#define CONFIG_DATA_DEMUXER 0
+#define CONFIG_DAUD_DEMUXER 0
+#define CONFIG_DCSTR_DEMUXER 0
+#define CONFIG_DFA_DEMUXER 0
+#define CONFIG_DIRAC_DEMUXER 0
+#define CONFIG_DNXHD_DEMUXER 0
+#define CONFIG_DSF_DEMUXER 0
+#define CONFIG_DSICIN_DEMUXER 0
+#define CONFIG_DSS_DEMUXER 0
+#define CONFIG_DTS_DEMUXER 0
+#define CONFIG_DTSHD_DEMUXER 0
+#define CONFIG_DV_DEMUXER 0
+#define CONFIG_DVBSUB_DEMUXER 0
+#define CONFIG_DVBTXT_DEMUXER 0
+#define CONFIG_DXA_DEMUXER 0
+#define CONFIG_EA_DEMUXER 0
+#define CONFIG_EA_CDATA_DEMUXER 0
+#define CONFIG_EAC3_DEMUXER 0
+#define CONFIG_EPAF_DEMUXER 0
+#define CONFIG_FFM_DEMUXER 0
+#define CONFIG_FFMETADATA_DEMUXER 0
+#define CONFIG_FILMSTRIP_DEMUXER 0
+#define CONFIG_FITS_DEMUXER 0
+#define CONFIG_FLAC_DEMUXER 0
+#define CONFIG_FLIC_DEMUXER 0
+#define CONFIG_FLV_DEMUXER 0
+#define CONFIG_LIVE_FLV_DEMUXER 0
+#define CONFIG_FOURXM_DEMUXER 0
+#define CONFIG_FRM_DEMUXER 0
+#define CONFIG_FSB_DEMUXER 0
+#define CONFIG_G722_DEMUXER 0
+#define CONFIG_G723_1_DEMUXER 0
+#define CONFIG_G726_DEMUXER 0
+#define CONFIG_G726LE_DEMUXER 0
+#define CONFIG_G729_DEMUXER 0
+#define CONFIG_GDV_DEMUXER 0
+#define CONFIG_GENH_DEMUXER 0
+#define CONFIG_GIF_DEMUXER 0
+#define CONFIG_GSM_DEMUXER 0
+#define CONFIG_GXF_DEMUXER 0
+#define CONFIG_H261_DEMUXER 0
+#define CONFIG_H263_DEMUXER 0
+#define CONFIG_H264_DEMUXER 0
+#define CONFIG_HEVC_DEMUXER 0
+#define CONFIG_HLS_DEMUXER 0
+#define CONFIG_HNM_DEMUXER 0
+#define CONFIG_ICO_DEMUXER 0
+#define CONFIG_IDCIN_DEMUXER 0
+#define CONFIG_IDF_DEMUXER 0
+#define CONFIG_IFF_DEMUXER 0
+#define CONFIG_ILBC_DEMUXER 0
+#define CONFIG_IMAGE2_DEMUXER 0
+#define CONFIG_IMAGE2PIPE_DEMUXER 0
+#define CONFIG_IMAGE2_ALIAS_PIX_DEMUXER 0
+#define CONFIG_IMAGE2_BRENDER_PIX_DEMUXER 0
+#define CONFIG_INGENIENT_DEMUXER 0
+#define CONFIG_IPMOVIE_DEMUXER 0
+#define CONFIG_IRCAM_DEMUXER 0
+#define CONFIG_ISS_DEMUXER 0
+#define CONFIG_IV8_DEMUXER 0
+#define CONFIG_IVF_DEMUXER 0
+#define CONFIG_IVR_DEMUXER 0
+#define CONFIG_JACOSUB_DEMUXER 0
+#define CONFIG_JV_DEMUXER 0
+#define CONFIG_LMLM4_DEMUXER 0
+#define CONFIG_LOAS_DEMUXER 0
+#define CONFIG_LRC_DEMUXER 0
+#define CONFIG_LVF_DEMUXER 0
+#define CONFIG_LXF_DEMUXER 0
+#define CONFIG_M4V_DEMUXER 0
+#define CONFIG_MATROSKA_DEMUXER 0
+#define CONFIG_MGSTS_DEMUXER 0
+#define CONFIG_MICRODVD_DEMUXER 0
+#define CONFIG_MJPEG_DEMUXER 0
+#define CONFIG_MJPEG_2000_DEMUXER 0
+#define CONFIG_MLP_DEMUXER 0
+#define CONFIG_MLV_DEMUXER 0
+#define CONFIG_MM_DEMUXER 0
+#define CONFIG_MMF_DEMUXER 0
+#define CONFIG_MOV_DEMUXER 0
+#define CONFIG_MP3_DEMUXER 0
+#define CONFIG_MPC_DEMUXER 0
+#define CONFIG_MPC8_DEMUXER 0
+#define CONFIG_MPEGPS_DEMUXER 0
+#define CONFIG_MPEGTS_DEMUXER 0
+#define CONFIG_MPEGTSRAW_DEMUXER 0
+#define CONFIG_MPEGVIDEO_DEMUXER 0
+#define CONFIG_MPJPEG_DEMUXER 0
+#define CONFIG_MPL2_DEMUXER 0
+#define CONFIG_MPSUB_DEMUXER 0
+#define CONFIG_MSF_DEMUXER 0
+#define CONFIG_MSNWC_TCP_DEMUXER 0
+#define CONFIG_MTAF_DEMUXER 0
+#define CONFIG_MTV_DEMUXER 0
+#define CONFIG_MUSX_DEMUXER 0
+#define CONFIG_MV_DEMUXER 0
+#define CONFIG_MVI_DEMUXER 0
+#define CONFIG_MXF_DEMUXER 0
+#define CONFIG_MXG_DEMUXER 0
+#define CONFIG_NC_DEMUXER 0
+#define CONFIG_NISTSPHERE_DEMUXER 0
+#define CONFIG_NSV_DEMUXER 0
+#define CONFIG_NUT_DEMUXER 0
+#define CONFIG_NUV_DEMUXER 0
+#define CONFIG_OGG_DEMUXER 0
+#define CONFIG_OMA_DEMUXER 0
+#define CONFIG_PAF_DEMUXER 0
+#define CONFIG_PCM_ALAW_DEMUXER 0
+#define CONFIG_PCM_MULAW_DEMUXER 0
+#define CONFIG_PCM_F64BE_DEMUXER 0
+#define CONFIG_PCM_F64LE_DEMUXER 0
+#define CONFIG_PCM_F32BE_DEMUXER 0
+#define CONFIG_PCM_F32LE_DEMUXER 0
+#define CONFIG_PCM_S32BE_DEMUXER 0
+#define CONFIG_PCM_S32LE_DEMUXER 0
+#define CONFIG_PCM_S24BE_DEMUXER 0
+#define CONFIG_PCM_S24LE_DEMUXER 0
+#define CONFIG_PCM_S16BE_DEMUXER 0
+#define CONFIG_PCM_S16LE_DEMUXER 0
+#define CONFIG_PCM_S8_DEMUXER 0
+#define CONFIG_PCM_U32BE_DEMUXER 0
+#define CONFIG_PCM_U32LE_DEMUXER 0
+#define CONFIG_PCM_U24BE_DEMUXER 0
+#define CONFIG_PCM_U24LE_DEMUXER 0
+#define CONFIG_PCM_U16BE_DEMUXER 0
+#define CONFIG_PCM_U16LE_DEMUXER 0
+#define CONFIG_PCM_U8_DEMUXER 0
+#define CONFIG_PJS_DEMUXER 0
+#define CONFIG_PMP_DEMUXER 0
+#define CONFIG_PVA_DEMUXER 0
+#define CONFIG_PVF_DEMUXER 0
+#define CONFIG_QCP_DEMUXER 0
+#define CONFIG_R3D_DEMUXER 0
+#define CONFIG_RAWVIDEO_DEMUXER 0
+#define CONFIG_REALTEXT_DEMUXER 0
+#define CONFIG_REDSPARK_DEMUXER 0
+#define CONFIG_RL2_DEMUXER 0
+#define CONFIG_RM_DEMUXER 0
+#define CONFIG_ROQ_DEMUXER 0
+#define CONFIG_RPL_DEMUXER 0
+#define CONFIG_RSD_DEMUXER 0
+#define CONFIG_RSO_DEMUXER 0
+#define CONFIG_RTP_DEMUXER 0
+#define CONFIG_RTSP_DEMUXER 0
+#define CONFIG_S337M_DEMUXER 0
+#define CONFIG_SAMI_DEMUXER 0
+#define CONFIG_SAP_DEMUXER 0
+#define CONFIG_SBG_DEMUXER 0
+#define CONFIG_SCC_DEMUXER 0
+#define CONFIG_SDP_DEMUXER 0
+#define CONFIG_SDR2_DEMUXER 0
+#define CONFIG_SDS_DEMUXER 0
+#define CONFIG_SDX_DEMUXER 0
+#define CONFIG_SEGAFILM_DEMUXER 0
+#define CONFIG_SHORTEN_DEMUXER 0
+#define CONFIG_SIFF_DEMUXER 0
+#define CONFIG_SLN_DEMUXER 0
+#define CONFIG_SMACKER_DEMUXER 0
+#define CONFIG_SMJPEG_DEMUXER 0
+#define CONFIG_SMUSH_DEMUXER 0
+#define CONFIG_SOL_DEMUXER 0
+#define CONFIG_SOX_DEMUXER 0
+#define CONFIG_SPDIF_DEMUXER 0
+#define CONFIG_SRT_DEMUXER 0
+#define CONFIG_STR_DEMUXER 0
+#define CONFIG_STL_DEMUXER 0
+#define CONFIG_SUBVIEWER1_DEMUXER 0
+#define CONFIG_SUBVIEWER_DEMUXER 0
+#define CONFIG_SUP_DEMUXER 0
+#define CONFIG_SVAG_DEMUXER 0
+#define CONFIG_SWF_DEMUXER 0
+#define CONFIG_TAK_DEMUXER 0
+#define CONFIG_TEDCAPTIONS_DEMUXER 0
+#define CONFIG_THP_DEMUXER 0
+#define CONFIG_THREEDOSTR_DEMUXER 0
+#define CONFIG_TIERTEXSEQ_DEMUXER 0
+#define CONFIG_TMV_DEMUXER 0
+#define CONFIG_TRUEHD_DEMUXER 0
+#define CONFIG_TTA_DEMUXER 0
+#define CONFIG_TXD_DEMUXER 0
+#define CONFIG_TTY_DEMUXER 0
+#define CONFIG_V210_DEMUXER 0
+#define CONFIG_V210X_DEMUXER 0
+#define CONFIG_VAG_DEMUXER 0
+#define CONFIG_VC1_DEMUXER 0
+#define CONFIG_VC1T_DEMUXER 0
+#define CONFIG_VIVO_DEMUXER 0
+#define CONFIG_VMD_DEMUXER 0
+#define CONFIG_VOBSUB_DEMUXER 0
+#define CONFIG_VOC_DEMUXER 0
+#define CONFIG_VPK_DEMUXER 0
+#define CONFIG_VPLAYER_DEMUXER 0
+#define CONFIG_VQF_DEMUXER 0
+#define CONFIG_W64_DEMUXER 0
+#define CONFIG_WAV_DEMUXER 0
+#define CONFIG_WC3_DEMUXER 0
+#define CONFIG_WEBM_DASH_MANIFEST_DEMUXER 0
+#define CONFIG_WEBVTT_DEMUXER 0
+#define CONFIG_WSAUD_DEMUXER 0
+#define CONFIG_WSD_DEMUXER 0
+#define CONFIG_WSVQA_DEMUXER 0
+#define CONFIG_WTV_DEMUXER 0
+#define CONFIG_WVE_DEMUXER 0
+#define CONFIG_WV_DEMUXER 0
+#define CONFIG_XA_DEMUXER 0
+#define CONFIG_XBIN_DEMUXER 0
+#define CONFIG_XMV_DEMUXER 0
+#define CONFIG_XVAG_DEMUXER 0
+#define CONFIG_XWMA_DEMUXER 0
+#define CONFIG_YOP_DEMUXER 0
+#define CONFIG_YUV4MPEGPIPE_DEMUXER 0
+#define CONFIG_IMAGE_BMP_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_DDS_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_DPX_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_EXR_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_J2K_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_JPEG_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_JPEGLS_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PAM_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PBM_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PCX_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PGMYUV_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PGM_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PICTOR_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PNG_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PPM_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_PSD_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_QDRAW_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_SGI_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_SVG_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_SUNRAST_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_TIFF_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_WEBP_PIPE_DEMUXER 0
+#define CONFIG_IMAGE_XPM_PIPE_DEMUXER 0
+#define CONFIG_LIBGME_DEMUXER 0
+#define CONFIG_LIBMODPLUG_DEMUXER 0
+#define CONFIG_LIBOPENMPT_DEMUXER 0
+#define CONFIG_A64MULTI_ENCODER 0
+#define CONFIG_A64MULTI5_ENCODER 0
+#define CONFIG_ALIAS_PIX_ENCODER 0
+#define CONFIG_AMV_ENCODER 0
+#define CONFIG_APNG_ENCODER 0
+#define CONFIG_ASV1_ENCODER 0
+#define CONFIG_ASV2_ENCODER 0
+#define CONFIG_AVRP_ENCODER 0
+#define CONFIG_AVUI_ENCODER 0
+#define CONFIG_AYUV_ENCODER 0
+#define CONFIG_BMP_ENCODER 0
+#define CONFIG_CINEPAK_ENCODER 0
+#define CONFIG_CLJR_ENCODER 0
+#define CONFIG_COMFORTNOISE_ENCODER 0
+#define CONFIG_DNXHD_ENCODER 0
+#define CONFIG_DPX_ENCODER 0
+#define CONFIG_DVVIDEO_ENCODER 0
+#define CONFIG_FFV1_ENCODER 0
+#define CONFIG_FFVHUFF_ENCODER 0
+#define CONFIG_FITS_ENCODER 0
+#define CONFIG_FLASHSV_ENCODER 0
+#define CONFIG_FLASHSV2_ENCODER 0
+#define CONFIG_FLV_ENCODER 0
+#define CONFIG_GIF_ENCODER 0
+#define CONFIG_H261_ENCODER 0
+#define CONFIG_H263_ENCODER 0
+#define CONFIG_H263P_ENCODER 0
+#define CONFIG_HAP_ENCODER 0
+#define CONFIG_HUFFYUV_ENCODER 0
+#define CONFIG_JPEG2000_ENCODER 0
+#define CONFIG_JPEGLS_ENCODER 0
+#define CONFIG_LJPEG_ENCODER 0
+#define CONFIG_MJPEG_ENCODER 0
+#define CONFIG_MPEG1VIDEO_ENCODER 0
+#define CONFIG_MPEG2VIDEO_ENCODER 0
+#define CONFIG_MPEG4_ENCODER 0
+#define CONFIG_MSMPEG4V2_ENCODER 0
+#define CONFIG_MSMPEG4V3_ENCODER 0
+#define CONFIG_MSVIDEO1_ENCODER 0
+#define CONFIG_PAM_ENCODER 0
+#define CONFIG_PBM_ENCODER 0
+#define CONFIG_PCX_ENCODER 0
+#define CONFIG_PGM_ENCODER 0
+#define CONFIG_PGMYUV_ENCODER 0
+#define CONFIG_PNG_ENCODER 0
+#define CONFIG_PPM_ENCODER 0
+#define CONFIG_PRORES_ENCODER 0
+#define CONFIG_PRORES_AW_ENCODER 0
+#define CONFIG_PRORES_KS_ENCODER 0
+#define CONFIG_QTRLE_ENCODER 0
+#define CONFIG_R10K_ENCODER 0
+#define CONFIG_R210_ENCODER 0
+#define CONFIG_RAWVIDEO_ENCODER 0
+#define CONFIG_ROQ_ENCODER 0
+#define CONFIG_RV10_ENCODER 0
+#define CONFIG_RV20_ENCODER 0
+#define CONFIG_S302M_ENCODER 0
+#define CONFIG_SGI_ENCODER 0
+#define CONFIG_SNOW_ENCODER 0
+#define CONFIG_SUNRAST_ENCODER 0
+#define CONFIG_SVQ1_ENCODER 0
+#define CONFIG_TARGA_ENCODER 0
+#define CONFIG_TIFF_ENCODER 0
+#define CONFIG_UTVIDEO_ENCODER 0
+#define CONFIG_V210_ENCODER 0
+#define CONFIG_V308_ENCODER 0
+#define CONFIG_V408_ENCODER 0
+#define CONFIG_V410_ENCODER 0
+#define CONFIG_VC2_ENCODER 0
+#define CONFIG_WRAPPED_AVFRAME_ENCODER 0
+#define CONFIG_WMV1_ENCODER 0
+#define CONFIG_WMV2_ENCODER 0
+#define CONFIG_XBM_ENCODER 0
+#define CONFIG_XFACE_ENCODER 0
+#define CONFIG_XWD_ENCODER 0
+#define CONFIG_Y41P_ENCODER 0
+#define CONFIG_YUV4_ENCODER 0
+#define CONFIG_ZLIB_ENCODER 0
+#define CONFIG_ZMBV_ENCODER 0
+#define CONFIG_AAC_ENCODER 0
+#define CONFIG_AC3_ENCODER 0
+#define CONFIG_AC3_FIXED_ENCODER 0
+#define CONFIG_ALAC_ENCODER 0
+#define CONFIG_DCA_ENCODER 0
+#define CONFIG_EAC3_ENCODER 0
+#define CONFIG_FLAC_ENCODER 0
+#define CONFIG_G723_1_ENCODER 0
+#define CONFIG_MLP_ENCODER 0
+#define CONFIG_MP2_ENCODER 0
+#define CONFIG_MP2FIXED_ENCODER 0
+#define CONFIG_NELLYMOSER_ENCODER 0
+#define CONFIG_OPUS_ENCODER 0
+#define CONFIG_RA_144_ENCODER 0
+#define CONFIG_SONIC_ENCODER 0
+#define CONFIG_SONIC_LS_ENCODER 0
+#define CONFIG_TRUEHD_ENCODER 0
+#define CONFIG_TTA_ENCODER 0
+#define CONFIG_VORBIS_ENCODER 0
+#define CONFIG_WAVPACK_ENCODER 0
+#define CONFIG_WMAV1_ENCODER 0
+#define CONFIG_WMAV2_ENCODER 0
+#define CONFIG_PCM_ALAW_ENCODER 0
+#define CONFIG_PCM_F32BE_ENCODER 0
+#define CONFIG_PCM_F32LE_ENCODER 0
+#define CONFIG_PCM_F64BE_ENCODER 0
+#define CONFIG_PCM_F64LE_ENCODER 0
+#define CONFIG_PCM_MULAW_ENCODER 0
+#define CONFIG_PCM_S8_ENCODER 0
+#define CONFIG_PCM_S8_PLANAR_ENCODER 0
+#define CONFIG_PCM_S16BE_ENCODER 0
+#define CONFIG_PCM_S16BE_PLANAR_ENCODER 0
+#define CONFIG_PCM_S16LE_ENCODER 0
+#define CONFIG_PCM_S16LE_PLANAR_ENCODER 0
+#define CONFIG_PCM_S24BE_ENCODER 0
+#define CONFIG_PCM_S24DAUD_ENCODER 0
+#define CONFIG_PCM_S24LE_ENCODER 0
+#define CONFIG_PCM_S24LE_PLANAR_ENCODER 0
+#define CONFIG_PCM_S32BE_ENCODER 0
+#define CONFIG_PCM_S32LE_ENCODER 0
+#define CONFIG_PCM_S32LE_PLANAR_ENCODER 0
+#define CONFIG_PCM_S64BE_ENCODER 0
+#define CONFIG_PCM_S64LE_ENCODER 0
+#define CONFIG_PCM_U8_ENCODER 0
+#define CONFIG_PCM_U16BE_ENCODER 0
+#define CONFIG_PCM_U16LE_ENCODER 0
+#define CONFIG_PCM_U24BE_ENCODER 0
+#define CONFIG_PCM_U24LE_ENCODER 0
+#define CONFIG_PCM_U32BE_ENCODER 0
+#define CONFIG_PCM_U32LE_ENCODER 0
+#define CONFIG_ROQ_DPCM_ENCODER 0
+#define CONFIG_ADPCM_ADX_ENCODER 0
+#define CONFIG_ADPCM_G722_ENCODER 0
+#define CONFIG_ADPCM_G726_ENCODER 0
+#define CONFIG_ADPCM_G726LE_ENCODER 0
+#define CONFIG_ADPCM_IMA_QT_ENCODER 0
+#define CONFIG_ADPCM_IMA_WAV_ENCODER 0
+#define CONFIG_ADPCM_MS_ENCODER 0
+#define CONFIG_ADPCM_SWF_ENCODER 0
+#define CONFIG_ADPCM_YAMAHA_ENCODER 0
+#define CONFIG_SSA_ENCODER 0
+#define CONFIG_ASS_ENCODER 0
+#define CONFIG_DVBSUB_ENCODER 0
+#define CONFIG_DVDSUB_ENCODER 0
+#define CONFIG_MOVTEXT_ENCODER 0
+#define CONFIG_SRT_ENCODER 0
+#define CONFIG_SUBRIP_ENCODER 0
+#define CONFIG_TEXT_ENCODER 0
+#define CONFIG_WEBVTT_ENCODER 0
+#define CONFIG_XSUB_ENCODER 0
+#define CONFIG_AAC_AT_ENCODER 0
+#define CONFIG_ALAC_AT_ENCODER 0
+#define CONFIG_ILBC_AT_ENCODER 0
+#define CONFIG_PCM_ALAW_AT_ENCODER 0
+#define CONFIG_PCM_MULAW_AT_ENCODER 0
+#define CONFIG_LIBFDK_AAC_ENCODER 0
+#define CONFIG_LIBGSM_ENCODER 0
+#define CONFIG_LIBGSM_MS_ENCODER 0
+#define CONFIG_LIBILBC_ENCODER 0
+#define CONFIG_LIBMP3LAME_ENCODER 0
+#define CONFIG_LIBOPENCORE_AMRNB_ENCODER 0
+#define CONFIG_LIBOPENJPEG_ENCODER 0
+#define CONFIG_LIBOPUS_ENCODER 0
+#define CONFIG_LIBSHINE_ENCODER 0
+#define CONFIG_LIBSPEEX_ENCODER 0
+#define CONFIG_LIBTHEORA_ENCODER 0
+#define CONFIG_LIBTWOLAME_ENCODER 0
+#define CONFIG_LIBVO_AMRWBENC_ENCODER 0
+#define CONFIG_LIBVORBIS_ENCODER 0
+#define CONFIG_LIBVPX_VP8_ENCODER 0
+#define CONFIG_LIBVPX_VP9_ENCODER 0
+#define CONFIG_LIBWAVPACK_ENCODER 0
+#define CONFIG_LIBWEBP_ANIM_ENCODER 0
+#define CONFIG_LIBWEBP_ENCODER 0
+#define CONFIG_LIBX262_ENCODER 0
+#define CONFIG_LIBX264_ENCODER 0
+#define CONFIG_LIBX264RGB_ENCODER 0
+#define CONFIG_LIBX265_ENCODER 0
+#define CONFIG_LIBXAVS_ENCODER 0
+#define CONFIG_LIBXVID_ENCODER 0
+#define CONFIG_H263_V4L2M2M_ENCODER 0
+#define CONFIG_LIBOPENH264_ENCODER 0
+#define CONFIG_H264_NVENC_ENCODER 0
+#define CONFIG_H264_OMX_ENCODER 0
+#define CONFIG_H264_QSV_ENCODER 0
+#define CONFIG_H264_V4L2M2M_ENCODER 0
+#define CONFIG_H264_VAAPI_ENCODER 0
+#define CONFIG_H264_VIDEOTOOLBOX_ENCODER 0
+#define CONFIG_NVENC_ENCODER 0
+#define CONFIG_NVENC_H264_ENCODER 0
+#define CONFIG_NVENC_HEVC_ENCODER 0
+#define CONFIG_HEVC_NVENC_ENCODER 0
+#define CONFIG_HEVC_QSV_ENCODER 0
+#define CONFIG_HEVC_V4L2M2M_ENCODER 0
+#define CONFIG_HEVC_VAAPI_ENCODER 0
+#define CONFIG_LIBKVAZAAR_ENCODER 0
+#define CONFIG_MJPEG_VAAPI_ENCODER 0
+#define CONFIG_MPEG2_QSV_ENCODER 0
+#define CONFIG_MPEG2_VAAPI_ENCODER 0
+#define CONFIG_MPEG4_V4L2M2M_ENCODER 0
+#define CONFIG_VP8_V4L2M2M_ENCODER 0
+#define CONFIG_VP8_VAAPI_ENCODER 0
+#define CONFIG_VP9_VAAPI_ENCODER 0
+#define CONFIG_ABENCH_FILTER 0
+#define CONFIG_ACOMPRESSOR_FILTER 0
+#define CONFIG_ACOPY_FILTER 0
+#define CONFIG_ACROSSFADE_FILTER 0
+#define CONFIG_ACRUSHER_FILTER 0
+#define CONFIG_ADELAY_FILTER 0
+#define CONFIG_AECHO_FILTER 0
+#define CONFIG_AEMPHASIS_FILTER 0
+#define CONFIG_AEVAL_FILTER 0
+#define CONFIG_AFADE_FILTER 0
+#define CONFIG_AFFTFILT_FILTER 0
+#define CONFIG_AFIR_FILTER 0
+#define CONFIG_AFORMAT_FILTER 0
+#define CONFIG_AGATE_FILTER 0
+#define CONFIG_AINTERLEAVE_FILTER 0
+#define CONFIG_ALIMITER_FILTER 0
+#define CONFIG_ALLPASS_FILTER 0
+#define CONFIG_ALOOP_FILTER 0
+#define CONFIG_AMERGE_FILTER 0
+#define CONFIG_AMETADATA_FILTER 0
+#define CONFIG_AMIX_FILTER 0
+#define CONFIG_ANEQUALIZER_FILTER 0
+#define CONFIG_ANULL_FILTER 0
+#define CONFIG_APAD_FILTER 0
+#define CONFIG_APERMS_FILTER 0
+#define CONFIG_APHASER_FILTER 0
+#define CONFIG_APULSATOR_FILTER 0
+#define CONFIG_AREALTIME_FILTER 0
+#define CONFIG_ARESAMPLE_FILTER 0
+#define CONFIG_AREVERSE_FILTER 0
+#define CONFIG_ASELECT_FILTER 0
+#define CONFIG_ASENDCMD_FILTER 0
+#define CONFIG_ASETNSAMPLES_FILTER 0
+#define CONFIG_ASETPTS_FILTER 0
+#define CONFIG_ASETRATE_FILTER 0
+#define CONFIG_ASETTB_FILTER 0
+#define CONFIG_ASHOWINFO_FILTER 0
+#define CONFIG_ASIDEDATA_FILTER 0
+#define CONFIG_ASPLIT_FILTER 0
+#define CONFIG_ASTATS_FILTER 0
+#define CONFIG_ASTREAMSELECT_FILTER 0
+#define CONFIG_ATEMPO_FILTER 0
+#define CONFIG_ATRIM_FILTER 0
+#define CONFIG_AZMQ_FILTER 0
+#define CONFIG_BANDPASS_FILTER 0
+#define CONFIG_BANDREJECT_FILTER 0
+#define CONFIG_BASS_FILTER 0
+#define CONFIG_BIQUAD_FILTER 0
+#define CONFIG_BS2B_FILTER 0
+#define CONFIG_CHANNELMAP_FILTER 0
+#define CONFIG_CHANNELSPLIT_FILTER 0
+#define CONFIG_CHORUS_FILTER 0
+#define CONFIG_COMPAND_FILTER 0
+#define CONFIG_COMPENSATIONDELAY_FILTER 0
+#define CONFIG_CROSSFEED_FILTER 0
+#define CONFIG_CRYSTALIZER_FILTER 0
+#define CONFIG_DCSHIFT_FILTER 0
+#define CONFIG_DYNAUDNORM_FILTER 0
+#define CONFIG_EARWAX_FILTER 0
+#define CONFIG_EBUR128_FILTER 0
+#define CONFIG_EQUALIZER_FILTER 0
+#define CONFIG_EXTRASTEREO_FILTER 0
+#define CONFIG_FIREQUALIZER_FILTER 0
+#define CONFIG_FLANGER_FILTER 0
+#define CONFIG_HAAS_FILTER 0
+#define CONFIG_HDCD_FILTER 0
+#define CONFIG_HEADPHONE_FILTER 0
+#define CONFIG_HIGHPASS_FILTER 0
+#define CONFIG_JOIN_FILTER 0
+#define CONFIG_LADSPA_FILTER 0
+#define CONFIG_LOUDNORM_FILTER 0
+#define CONFIG_LOWPASS_FILTER 0
+#define CONFIG_PAN_FILTER 0
+#define CONFIG_REPLAYGAIN_FILTER 0
+#define CONFIG_RESAMPLE_FILTER 0
+#define CONFIG_RUBBERBAND_FILTER 0
+#define CONFIG_SIDECHAINCOMPRESS_FILTER 0
+#define CONFIG_SIDECHAINGATE_FILTER 0
+#define CONFIG_SILENCEDETECT_FILTER 0
+#define CONFIG_SILENCEREMOVE_FILTER 0
+#define CONFIG_SOFALIZER_FILTER 0
+#define CONFIG_STEREOTOOLS_FILTER 0
+#define CONFIG_STEREOWIDEN_FILTER 0
+#define CONFIG_SUPEREQUALIZER_FILTER 0
+#define CONFIG_SURROUND_FILTER 0
+#define CONFIG_TREBLE_FILTER 0
+#define CONFIG_TREMOLO_FILTER 0
+#define CONFIG_VIBRATO_FILTER 0
+#define CONFIG_VOLUME_FILTER 0
+#define CONFIG_VOLUMEDETECT_FILTER 0
+#define CONFIG_AEVALSRC_FILTER 0
+#define CONFIG_ANOISESRC_FILTER 0
+#define CONFIG_ANULLSRC_FILTER 0
+#define CONFIG_FLITE_FILTER 0
+#define CONFIG_SINE_FILTER 0
+#define CONFIG_ANULLSINK_FILTER 0
+#define CONFIG_ALPHAEXTRACT_FILTER 0
+#define CONFIG_ALPHAMERGE_FILTER 0
+#define CONFIG_ASS_FILTER 0
+#define CONFIG_ATADENOISE_FILTER 0
+#define CONFIG_AVGBLUR_FILTER 0
+#define CONFIG_BBOX_FILTER 0
+#define CONFIG_BENCH_FILTER 0
+#define CONFIG_BITPLANENOISE_FILTER 0
+#define CONFIG_BLACKDETECT_FILTER 0
+#define CONFIG_BLACKFRAME_FILTER 0
+#define CONFIG_BLEND_FILTER 0
+#define CONFIG_BOXBLUR_FILTER 0
+#define CONFIG_BWDIF_FILTER 0
+#define CONFIG_CHROMAKEY_FILTER 0
+#define CONFIG_CIESCOPE_FILTER 0
+#define CONFIG_CODECVIEW_FILTER 0
+#define CONFIG_COLORBALANCE_FILTER 0
+#define CONFIG_COLORCHANNELMIXER_FILTER 0
+#define CONFIG_COLORKEY_FILTER 0
+#define CONFIG_COLORLEVELS_FILTER 0
+#define CONFIG_COLORMATRIX_FILTER 0
+#define CONFIG_COLORSPACE_FILTER 0
+#define CONFIG_CONVOLUTION_FILTER 0
+#define CONFIG_CONVOLVE_FILTER 0
+#define CONFIG_COPY_FILTER 0
+#define CONFIG_COREIMAGE_FILTER 0
+#define CONFIG_COVER_RECT_FILTER 0
+#define CONFIG_CROP_FILTER 0
+#define CONFIG_CROPDETECT_FILTER 0
+#define CONFIG_CURVES_FILTER 0
+#define CONFIG_DATASCOPE_FILTER 0
+#define CONFIG_DCTDNOIZ_FILTER 0
+#define CONFIG_DEBAND_FILTER 0
+#define CONFIG_DECIMATE_FILTER 0
+#define CONFIG_DEFLATE_FILTER 0
+#define CONFIG_DEFLICKER_FILTER 0
+#define CONFIG_DEINTERLACE_QSV_FILTER 0
+#define CONFIG_DEINTERLACE_VAAPI_FILTER 0
+#define CONFIG_DEJUDDER_FILTER 0
+#define CONFIG_DELOGO_FILTER 0
+#define CONFIG_DESHAKE_FILTER 0
+#define CONFIG_DESPILL_FILTER 0
+#define CONFIG_DETELECINE_FILTER 0
+#define CONFIG_DILATION_FILTER 0
+#define CONFIG_DISPLACE_FILTER 0
+#define CONFIG_DOUBLEWEAVE_FILTER 0
+#define CONFIG_DRAWBOX_FILTER 0
+#define CONFIG_DRAWGRAPH_FILTER 0
+#define CONFIG_DRAWGRID_FILTER 0
+#define CONFIG_DRAWTEXT_FILTER 0
+#define CONFIG_EDGEDETECT_FILTER 0
+#define CONFIG_ELBG_FILTER 0
+#define CONFIG_EQ_FILTER 0
+#define CONFIG_EROSION_FILTER 0
+#define CONFIG_EXTRACTPLANES_FILTER 0
+#define CONFIG_FADE_FILTER 0
+#define CONFIG_FFTFILT_FILTER 0
+#define CONFIG_FIELD_FILTER 0
+#define CONFIG_FIELDHINT_FILTER 0
+#define CONFIG_FIELDMATCH_FILTER 0
+#define CONFIG_FIELDORDER_FILTER 0
+#define CONFIG_FIND_RECT_FILTER 0
+#define CONFIG_FLOODFILL_FILTER 0
+#define CONFIG_FORMAT_FILTER 0
+#define CONFIG_FPS_FILTER 0
+#define CONFIG_FRAMEPACK_FILTER 0
+#define CONFIG_FRAMERATE_FILTER 0
+#define CONFIG_FRAMESTEP_FILTER 0
+#define CONFIG_FREI0R_FILTER 0
+#define CONFIG_FSPP_FILTER 0
+#define CONFIG_GBLUR_FILTER 0
+#define CONFIG_GEQ_FILTER 0
+#define CONFIG_GRADFUN_FILTER 0
+#define CONFIG_HALDCLUT_FILTER 0
+#define CONFIG_HFLIP_FILTER 0
+#define CONFIG_HISTEQ_FILTER 0
+#define CONFIG_HISTOGRAM_FILTER 0
+#define CONFIG_HQDN3D_FILTER 0
+#define CONFIG_HQX_FILTER 0
+#define CONFIG_HSTACK_FILTER 0
+#define CONFIG_HUE_FILTER 0
+#define CONFIG_HWDOWNLOAD_FILTER 0
+#define CONFIG_HWMAP_FILTER 0
+#define CONFIG_HWUPLOAD_FILTER 0
+#define CONFIG_HWUPLOAD_CUDA_FILTER 0
+#define CONFIG_HYSTERESIS_FILTER 0
+#define CONFIG_IDET_FILTER 0
+#define CONFIG_IL_FILTER 0
+#define CONFIG_INFLATE_FILTER 0
+#define CONFIG_INTERLACE_FILTER 0
+#define CONFIG_INTERLEAVE_FILTER 0
+#define CONFIG_KERNDEINT_FILTER 0
+#define CONFIG_LENSCORRECTION_FILTER 0
+#define CONFIG_LIBVMAF_FILTER 0
+#define CONFIG_LIMITER_FILTER 0
+#define CONFIG_LOOP_FILTER 0
+#define CONFIG_LUMAKEY_FILTER 0
+#define CONFIG_LUT_FILTER 0
+#define CONFIG_LUT2_FILTER 0
+#define CONFIG_LUT3D_FILTER 0
+#define CONFIG_LUTRGB_FILTER 0
+#define CONFIG_LUTYUV_FILTER 0
+#define CONFIG_MASKEDCLAMP_FILTER 0
+#define CONFIG_MASKEDMERGE_FILTER 0
+#define CONFIG_MCDEINT_FILTER 0
+#define CONFIG_MERGEPLANES_FILTER 0
+#define CONFIG_MESTIMATE_FILTER 0
+#define CONFIG_METADATA_FILTER 0
+#define CONFIG_MIDEQUALIZER_FILTER 0
+#define CONFIG_MINTERPOLATE_FILTER 0
+#define CONFIG_MPDECIMATE_FILTER 0
+#define CONFIG_NEGATE_FILTER 0
+#define CONFIG_NLMEANS_FILTER 0
+#define CONFIG_NNEDI_FILTER 0
+#define CONFIG_NOFORMAT_FILTER 0
+#define CONFIG_NOISE_FILTER 0
+#define CONFIG_NULL_FILTER 0
+#define CONFIG_OCR_FILTER 0
+#define CONFIG_OCV_FILTER 0
+#define CONFIG_OSCILLOSCOPE_FILTER 0
+#define CONFIG_OVERLAY_FILTER 0
+#define CONFIG_OWDENOISE_FILTER 0
+#define CONFIG_PAD_FILTER 0
+#define CONFIG_PALETTEGEN_FILTER 0
+#define CONFIG_PALETTEUSE_FILTER 0
+#define CONFIG_PERMS_FILTER 0
+#define CONFIG_PERSPECTIVE_FILTER 0
+#define CONFIG_PHASE_FILTER 0
+#define CONFIG_PIXDESCTEST_FILTER 0
+#define CONFIG_PIXSCOPE_FILTER 0
+#define CONFIG_PP_FILTER 0
+#define CONFIG_PP7_FILTER 0
+#define CONFIG_PREMULTIPLY_FILTER 0
+#define CONFIG_PREWITT_FILTER 0
+#define CONFIG_PSEUDOCOLOR_FILTER 0
+#define CONFIG_PSNR_FILTER 0
+#define CONFIG_PULLUP_FILTER 0
+#define CONFIG_QP_FILTER 0
+#define CONFIG_RANDOM_FILTER 0
+#define CONFIG_READEIA608_FILTER 0
+#define CONFIG_READVITC_FILTER 0
+#define CONFIG_REALTIME_FILTER 0
+#define CONFIG_REMAP_FILTER 0
+#define CONFIG_REMOVEGRAIN_FILTER 0
+#define CONFIG_REMOVELOGO_FILTER 0
+#define CONFIG_REPEATFIELDS_FILTER 0
+#define CONFIG_REVERSE_FILTER 0
+#define CONFIG_ROBERTS_FILTER 0
+#define CONFIG_ROTATE_FILTER 0
+#define CONFIG_SAB_FILTER 0
+#define CONFIG_SCALE_FILTER 0
+#define CONFIG_SCALE_CUDA_FILTER 0
+#define CONFIG_SCALE_NPP_FILTER 0
+#define CONFIG_SCALE_QSV_FILTER 0
+#define CONFIG_SCALE_VAAPI_FILTER 0
+#define CONFIG_SCALE2REF_FILTER 0
+#define CONFIG_SELECT_FILTER 0
+#define CONFIG_SELECTIVECOLOR_FILTER 0
+#define CONFIG_SENDCMD_FILTER 0
+#define CONFIG_SEPARATEFIELDS_FILTER 0
+#define CONFIG_SETDAR_FILTER 0
+#define CONFIG_SETFIELD_FILTER 0
+#define CONFIG_SETPTS_FILTER 0
+#define CONFIG_SETSAR_FILTER 0
+#define CONFIG_SETTB_FILTER 0
+#define CONFIG_SHOWINFO_FILTER 0
+#define CONFIG_SHOWPALETTE_FILTER 0
+#define CONFIG_SHUFFLEFRAMES_FILTER 0
+#define CONFIG_SHUFFLEPLANES_FILTER 0
+#define CONFIG_SIDEDATA_FILTER 0
+#define CONFIG_SIGNALSTATS_FILTER 0
+#define CONFIG_SIGNATURE_FILTER 0
+#define CONFIG_SMARTBLUR_FILTER 0
+#define CONFIG_SOBEL_FILTER 0
+#define CONFIG_SPLIT_FILTER 0
+#define CONFIG_SPP_FILTER 0
+#define CONFIG_SSIM_FILTER 0
+#define CONFIG_STEREO3D_FILTER 0
+#define CONFIG_STREAMSELECT_FILTER 0
+#define CONFIG_SUBTITLES_FILTER 0
+#define CONFIG_SUPER2XSAI_FILTER 0
+#define CONFIG_SWAPRECT_FILTER 0
+#define CONFIG_SWAPUV_FILTER 0
+#define CONFIG_TBLEND_FILTER 0
+#define CONFIG_TELECINE_FILTER 0
+#define CONFIG_THRESHOLD_FILTER 0
+#define CONFIG_THUMBNAIL_FILTER 0
+#define CONFIG_THUMBNAIL_CUDA_FILTER 0
+#define CONFIG_TILE_FILTER 0
+#define CONFIG_TINTERLACE_FILTER 0
+#define CONFIG_TLUT2_FILTER 0
+#define CONFIG_TONEMAP_FILTER 0
+#define CONFIG_TRANSPOSE_FILTER 0
+#define CONFIG_TRIM_FILTER 0
+#define CONFIG_UNPREMULTIPLY_FILTER 0
+#define CONFIG_UNSHARP_FILTER 0
+#define CONFIG_USPP_FILTER 0
+#define CONFIG_VAGUEDENOISER_FILTER 0
+#define CONFIG_VECTORSCOPE_FILTER 0
+#define CONFIG_VFLIP_FILTER 0
+#define CONFIG_VIDSTABDETECT_FILTER 0
+#define CONFIG_VIDSTABTRANSFORM_FILTER 0
+#define CONFIG_VIGNETTE_FILTER 0
+#define CONFIG_VMAFMOTION_FILTER 0
+#define CONFIG_VSTACK_FILTER 0
+#define CONFIG_W3FDIF_FILTER 0
+#define CONFIG_WAVEFORM_FILTER 0
+#define CONFIG_WEAVE_FILTER 0
+#define CONFIG_XBR_FILTER 0
+#define CONFIG_YADIF_FILTER 0
+#define CONFIG_ZMQ_FILTER 0
+#define CONFIG_ZOOMPAN_FILTER 0
+#define CONFIG_ZSCALE_FILTER 0
+#define CONFIG_ALLRGB_FILTER 0
+#define CONFIG_ALLYUV_FILTER 0
+#define CONFIG_CELLAUTO_FILTER 0
+#define CONFIG_COLOR_FILTER 0
+#define CONFIG_COREIMAGESRC_FILTER 0
+#define CONFIG_FREI0R_SRC_FILTER 0
+#define CONFIG_HALDCLUTSRC_FILTER 0
+#define CONFIG_LIFE_FILTER 0
+#define CONFIG_MANDELBROT_FILTER 0
+#define CONFIG_MPTESTSRC_FILTER 0
+#define CONFIG_NULLSRC_FILTER 0
+#define CONFIG_RGBTESTSRC_FILTER 0
+#define CONFIG_SMPTEBARS_FILTER 0
+#define CONFIG_SMPTEHDBARS_FILTER 0
+#define CONFIG_TESTSRC_FILTER 0
+#define CONFIG_TESTSRC2_FILTER 0
+#define CONFIG_YUVTESTSRC_FILTER 0
+#define CONFIG_NULLSINK_FILTER 0
+#define CONFIG_ABITSCOPE_FILTER 0
+#define CONFIG_ADRAWGRAPH_FILTER 0
+#define CONFIG_AHISTOGRAM_FILTER 0
+#define CONFIG_APHASEMETER_FILTER 0
+#define CONFIG_AVECTORSCOPE_FILTER 0
+#define CONFIG_CONCAT_FILTER 0
+#define CONFIG_SHOWCQT_FILTER 0
+#define CONFIG_SHOWFREQS_FILTER 0
+#define CONFIG_SHOWSPECTRUM_FILTER 0
+#define CONFIG_SHOWSPECTRUMPIC_FILTER 0
+#define CONFIG_SHOWVOLUME_FILTER 0
+#define CONFIG_SHOWWAVES_FILTER 0
+#define CONFIG_SHOWWAVESPIC_FILTER 0
+#define CONFIG_SPECTRUMSYNTH_FILTER 0
+#define CONFIG_AMOVIE_FILTER 0
+#define CONFIG_MOVIE_FILTER 0
+#define CONFIG_H263_VAAPI_HWACCEL 0
+#define CONFIG_H263_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_H264_CUVID_HWACCEL 0
+#define CONFIG_H264_D3D11VA_HWACCEL 0
+#define CONFIG_H264_D3D11VA2_HWACCEL 0
+#define CONFIG_H264_DXVA2_HWACCEL 0
+#define CONFIG_H264_MEDIACODEC_HWACCEL 0
+#define CONFIG_H264_MMAL_HWACCEL 0
+#define CONFIG_H264_QSV_HWACCEL 0
+#define CONFIG_H264_VAAPI_HWACCEL 0
+#define CONFIG_H264_VDA_HWACCEL 0
+#define CONFIG_H264_VDA_OLD_HWACCEL 0
+#define CONFIG_H264_VDPAU_HWACCEL 0
+#define CONFIG_H264_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_HEVC_CUVID_HWACCEL 0
+#define CONFIG_HEVC_D3D11VA_HWACCEL 0
+#define CONFIG_HEVC_D3D11VA2_HWACCEL 0
+#define CONFIG_HEVC_DXVA2_HWACCEL 0
+#define CONFIG_HEVC_MEDIACODEC_HWACCEL 0
+#define CONFIG_HEVC_QSV_HWACCEL 0
+#define CONFIG_HEVC_VAAPI_HWACCEL 0
+#define CONFIG_HEVC_VDPAU_HWACCEL 0
+#define CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_MJPEG_CUVID_HWACCEL 0
+#define CONFIG_MPEG1_CUVID_HWACCEL 0
+#define CONFIG_MPEG1_XVMC_HWACCEL 0
+#define CONFIG_MPEG1_VDPAU_HWACCEL 0
+#define CONFIG_MPEG1_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_MPEG2_CUVID_HWACCEL 0
+#define CONFIG_MPEG2_XVMC_HWACCEL 0
+#define CONFIG_MPEG2_D3D11VA_HWACCEL 0
+#define CONFIG_MPEG2_D3D11VA2_HWACCEL 0
+#define CONFIG_MPEG2_DXVA2_HWACCEL 0
+#define CONFIG_MPEG2_MMAL_HWACCEL 0
+#define CONFIG_MPEG2_QSV_HWACCEL 0
+#define CONFIG_MPEG2_VAAPI_HWACCEL 0
+#define CONFIG_MPEG2_VDPAU_HWACCEL 0
+#define CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_MPEG2_MEDIACODEC_HWACCEL 0
+#define CONFIG_MPEG4_CUVID_HWACCEL 0
+#define CONFIG_MPEG4_MEDIACODEC_HWACCEL 0
+#define CONFIG_MPEG4_MMAL_HWACCEL 0
+#define CONFIG_MPEG4_VAAPI_HWACCEL 0
+#define CONFIG_MPEG4_VDPAU_HWACCEL 0
+#define CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL 0
+#define CONFIG_VC1_CUVID_HWACCEL 0
+#define CONFIG_VC1_D3D11VA_HWACCEL 0
+#define CONFIG_VC1_D3D11VA2_HWACCEL 0
+#define CONFIG_VC1_DXVA2_HWACCEL 0
+#define CONFIG_VC1_VAAPI_HWACCEL 0
+#define CONFIG_VC1_VDPAU_HWACCEL 0
+#define CONFIG_VC1_MMAL_HWACCEL 0
+#define CONFIG_VC1_QSV_HWACCEL 0
+#define CONFIG_VP8_CUVID_HWACCEL 0
+#define CONFIG_VP8_MEDIACODEC_HWACCEL 0
+#define CONFIG_VP8_QSV_HWACCEL 0
+#define CONFIG_VP9_CUVID_HWACCEL 0
+#define CONFIG_VP9_D3D11VA_HWACCEL 0
+#define CONFIG_VP9_D3D11VA2_HWACCEL 0
+#define CONFIG_VP9_DXVA2_HWACCEL 0
+#define CONFIG_VP9_MEDIACODEC_HWACCEL 0
+#define CONFIG_VP9_VAAPI_HWACCEL 0
+#define CONFIG_WMV3_D3D11VA_HWACCEL 0
+#define CONFIG_WMV3_D3D11VA2_HWACCEL 0
+#define CONFIG_WMV3_DXVA2_HWACCEL 0
+#define CONFIG_WMV3_VAAPI_HWACCEL 0
+#define CONFIG_WMV3_VDPAU_HWACCEL 0
+#define CONFIG_ALSA_INDEV 0
+#define CONFIG_AVFOUNDATION_INDEV 0
+#define CONFIG_BKTR_INDEV 0
+#define CONFIG_DECKLINK_INDEV 0
+#define CONFIG_LIBNDI_NEWTEK_INDEV 0
+#define CONFIG_DSHOW_INDEV 0
+#define CONFIG_FBDEV_INDEV 0
+#define CONFIG_GDIGRAB_INDEV 0
+#define CONFIG_IEC61883_INDEV 0
+#define CONFIG_JACK_INDEV 0
+#define CONFIG_KMSGRAB_INDEV 0
+#define CONFIG_LAVFI_INDEV 0
+#define CONFIG_OPENAL_INDEV 0
+#define CONFIG_OSS_INDEV 0
+#define CONFIG_PULSE_INDEV 0
+#define CONFIG_SNDIO_INDEV 0
+#define CONFIG_V4L2_INDEV 0
+#define CONFIG_VFWCAP_INDEV 0
+#define CONFIG_XCBGRAB_INDEV 0
+#define CONFIG_LIBCDIO_INDEV 0
+#define CONFIG_LIBDC1394_INDEV 0
+#define CONFIG_A64_MUXER 0
+#define CONFIG_AC3_MUXER 0
+#define CONFIG_ADTS_MUXER 0
+#define CONFIG_ADX_MUXER 0
+#define CONFIG_AIFF_MUXER 0
+#define CONFIG_AMR_MUXER 0
+#define CONFIG_APNG_MUXER 0
+#define CONFIG_ASF_MUXER 0
+#define CONFIG_ASS_MUXER 0
+#define CONFIG_AST_MUXER 0
+#define CONFIG_ASF_STREAM_MUXER 0
+#define CONFIG_AU_MUXER 0
+#define CONFIG_AVI_MUXER 0
+#define CONFIG_AVM2_MUXER 0
+#define CONFIG_BIT_MUXER 0
+#define CONFIG_CAF_MUXER 0
+#define CONFIG_CAVSVIDEO_MUXER 0
+#define CONFIG_CRC_MUXER 0
+#define CONFIG_DASH_MUXER 0
+#define CONFIG_DATA_MUXER 0
+#define CONFIG_DAUD_MUXER 0
+#define CONFIG_DIRAC_MUXER 0
+#define CONFIG_DNXHD_MUXER 0
+#define CONFIG_DTS_MUXER 0
+#define CONFIG_DV_MUXER 0
+#define CONFIG_EAC3_MUXER 0
+#define CONFIG_F4V_MUXER 0
+#define CONFIG_FFM_MUXER 0
+#define CONFIG_FFMETADATA_MUXER 0
+#define CONFIG_FIFO_MUXER 0
+#define CONFIG_FILMSTRIP_MUXER 0
+#define CONFIG_FITS_MUXER 0
+#define CONFIG_FLAC_MUXER 0
+#define CONFIG_FLV_MUXER 0
+#define CONFIG_FRAMECRC_MUXER 0
+#define CONFIG_FRAMEHASH_MUXER 0
+#define CONFIG_FRAMEMD5_MUXER 0
+#define CONFIG_G722_MUXER 0
+#define CONFIG_G723_1_MUXER 0
+#define CONFIG_G726_MUXER 0
+#define CONFIG_G726LE_MUXER 0
+#define CONFIG_GIF_MUXER 0
+#define CONFIG_GSM_MUXER 0
+#define CONFIG_GXF_MUXER 0
+#define CONFIG_H261_MUXER 0
+#define CONFIG_H263_MUXER 0
+#define CONFIG_H264_MUXER 0
+#define CONFIG_HASH_MUXER 0
+#define CONFIG_HDS_MUXER 0
+#define CONFIG_HEVC_MUXER 0
+#define CONFIG_HLS_MUXER 0
+#define CONFIG_ICO_MUXER 0
+#define CONFIG_ILBC_MUXER 0
+#define CONFIG_IMAGE2_MUXER 0
+#define CONFIG_IMAGE2PIPE_MUXER 0
+#define CONFIG_IPOD_MUXER 0
+#define CONFIG_IRCAM_MUXER 0
+#define CONFIG_ISMV_MUXER 0
+#define CONFIG_IVF_MUXER 0
+#define CONFIG_JACOSUB_MUXER 0
+#define CONFIG_LATM_MUXER 0
+#define CONFIG_LRC_MUXER 0
+#define CONFIG_M4V_MUXER 0
+#define CONFIG_MD5_MUXER 0
+#define CONFIG_MATROSKA_MUXER 0
+#define CONFIG_MATROSKA_AUDIO_MUXER 0
+#define CONFIG_MICRODVD_MUXER 0
+#define CONFIG_MJPEG_MUXER 0
+#define CONFIG_MLP_MUXER 0
+#define CONFIG_MMF_MUXER 0
+#define CONFIG_MOV_MUXER 0
+#define CONFIG_MP2_MUXER 0
+#define CONFIG_MP3_MUXER 0
+#define CONFIG_MP4_MUXER 0
+#define CONFIG_MPEG1SYSTEM_MUXER 0
+#define CONFIG_MPEG1VCD_MUXER 0
+#define CONFIG_MPEG1VIDEO_MUXER 0
+#define CONFIG_MPEG2DVD_MUXER 0
+#define CONFIG_MPEG2SVCD_MUXER 0
+#define CONFIG_MPEG2VIDEO_MUXER 0
+#define CONFIG_MPEG2VOB_MUXER 0
+#define CONFIG_MPEGTS_MUXER 0
+#define CONFIG_MPJPEG_MUXER 0
+#define CONFIG_MXF_MUXER 0
+#define CONFIG_MXF_D10_MUXER 0
+#define CONFIG_MXF_OPATOM_MUXER 0
+#define CONFIG_NULL_MUXER 0
+#define CONFIG_NUT_MUXER 0
+#define CONFIG_OGA_MUXER 0
+#define CONFIG_OGG_MUXER 0
+#define CONFIG_OGV_MUXER 0
+#define CONFIG_OMA_MUXER 0
+#define CONFIG_OPUS_MUXER 0
+#define CONFIG_PCM_ALAW_MUXER 0
+#define CONFIG_PCM_MULAW_MUXER 0
+#define CONFIG_PCM_F64BE_MUXER 0
+#define CONFIG_PCM_F64LE_MUXER 0
+#define CONFIG_PCM_F32BE_MUXER 0
+#define CONFIG_PCM_F32LE_MUXER 0
+#define CONFIG_PCM_S32BE_MUXER 0
+#define CONFIG_PCM_S32LE_MUXER 0
+#define CONFIG_PCM_S24BE_MUXER 0
+#define CONFIG_PCM_S24LE_MUXER 0
+#define CONFIG_PCM_S16BE_MUXER 0
+#define CONFIG_PCM_S16LE_MUXER 0
+#define CONFIG_PCM_S8_MUXER 0
+#define CONFIG_PCM_U32BE_MUXER 0
+#define CONFIG_PCM_U32LE_MUXER 0
+#define CONFIG_PCM_U24BE_MUXER 0
+#define CONFIG_PCM_U24LE_MUXER 0
+#define CONFIG_PCM_U16BE_MUXER 0
+#define CONFIG_PCM_U16LE_MUXER 0
+#define CONFIG_PCM_U8_MUXER 0
+#define CONFIG_PSP_MUXER 0
+#define CONFIG_RAWVIDEO_MUXER 0
+#define CONFIG_RM_MUXER 0
+#define CONFIG_ROQ_MUXER 0
+#define CONFIG_RSO_MUXER 0
+#define CONFIG_RTP_MUXER 0
+#define CONFIG_RTP_MPEGTS_MUXER 0
+#define CONFIG_RTSP_MUXER 0
+#define CONFIG_SAP_MUXER 0
+#define CONFIG_SCC_MUXER 0
+#define CONFIG_SEGMENT_MUXER 0
+#define CONFIG_STREAM_SEGMENT_MUXER 0
+#define CONFIG_SINGLEJPEG_MUXER 0
+#define CONFIG_SMJPEG_MUXER 0
+#define CONFIG_SMOOTHSTREAMING_MUXER 0
+#define CONFIG_SOX_MUXER 0
+#define CONFIG_SPX_MUXER 0
+#define CONFIG_SPDIF_MUXER 0
+#define CONFIG_SRT_MUXER 0
+#define CONFIG_SUP_MUXER 0
+#define CONFIG_SWF_MUXER 0
+#define CONFIG_TEE_MUXER 0
+#define CONFIG_TG2_MUXER 0
+#define CONFIG_TGP_MUXER 0
+#define CONFIG_MKVTIMESTAMP_V2_MUXER 0
+#define CONFIG_TRUEHD_MUXER 0
+#define CONFIG_TTA_MUXER 0
+#define CONFIG_UNCODEDFRAMECRC_MUXER 0
+#define CONFIG_VC1_MUXER 0
+#define CONFIG_VC1T_MUXER 0
+#define CONFIG_VOC_MUXER 0
+#define CONFIG_W64_MUXER 0
+#define CONFIG_WAV_MUXER 0
+#define CONFIG_WEBM_MUXER 0
+#define CONFIG_WEBM_DASH_MANIFEST_MUXER 0
+#define CONFIG_WEBM_CHUNK_MUXER 0
+#define CONFIG_WEBP_MUXER 0
+#define CONFIG_WEBVTT_MUXER 0
+#define CONFIG_WTV_MUXER 0
+#define CONFIG_WV_MUXER 0
+#define CONFIG_YUV4MPEGPIPE_MUXER 0
+#define CONFIG_CHROMAPRINT_MUXER 0
+#define CONFIG_ALSA_OUTDEV 0
+#define CONFIG_CACA_OUTDEV 0
+#define CONFIG_DECKLINK_OUTDEV 0
+#define CONFIG_LIBNDI_NEWTEK_OUTDEV 0
+#define CONFIG_FBDEV_OUTDEV 0
+#define CONFIG_OPENGL_OUTDEV 0
+#define CONFIG_OSS_OUTDEV 0
+#define CONFIG_PULSE_OUTDEV 0
+#define CONFIG_SDL2_OUTDEV 0
+#define CONFIG_SNDIO_OUTDEV 0
+#define CONFIG_V4L2_OUTDEV 0
+#define CONFIG_XV_OUTDEV 0
+#define CONFIG_AAC_PARSER 0
+#define CONFIG_AAC_LATM_PARSER 0
+#define CONFIG_AC3_PARSER 0
+#define CONFIG_ADX_PARSER 0
+#define CONFIG_BMP_PARSER 0
+#define CONFIG_CAVSVIDEO_PARSER 0
+#define CONFIG_COOK_PARSER 0
+#define CONFIG_DCA_PARSER 0
+#define CONFIG_DIRAC_PARSER 0
+#define CONFIG_DNXHD_PARSER 0
+#define CONFIG_DPX_PARSER 0
+#define CONFIG_DVAUDIO_PARSER 0
+#define CONFIG_DVBSUB_PARSER 0
+#define CONFIG_DVDSUB_PARSER 0
+#define CONFIG_DVD_NAV_PARSER 0
+#define CONFIG_G729_PARSER 0
+#define CONFIG_GSM_PARSER 0
+#define CONFIG_H261_PARSER 0
+#define CONFIG_H263_PARSER 0
+#define CONFIG_H264_PARSER 0
+#define CONFIG_HEVC_PARSER 0
+#define CONFIG_MJPEG_PARSER 0
+#define CONFIG_MLP_PARSER 0
+#define CONFIG_MPEG4VIDEO_PARSER 0
+#define CONFIG_MPEGAUDIO_PARSER 0
+#define CONFIG_MPEGVIDEO_PARSER 0
+#define CONFIG_OPUS_PARSER 0
+#define CONFIG_PNG_PARSER 0
+#define CONFIG_PNM_PARSER 0
+#define CONFIG_RV30_PARSER 0
+#define CONFIG_RV40_PARSER 0
+#define CONFIG_SIPR_PARSER 0
+#define CONFIG_TAK_PARSER 0
+#define CONFIG_VC1_PARSER 0
+#define CONFIG_VORBIS_PARSER 0
+#define CONFIG_VP3_PARSER 0
+#define CONFIG_XMA_PARSER 0
+#define CONFIG_ASYNC_PROTOCOL 0
+#define CONFIG_BLURAY_PROTOCOL 0
+#define CONFIG_CACHE_PROTOCOL 0
+#define CONFIG_CONCAT_PROTOCOL 0
+#define CONFIG_CRYPTO_PROTOCOL 0
+#define CONFIG_DATA_PROTOCOL 0
+#define CONFIG_FFRTMPCRYPT_PROTOCOL 0
+#define CONFIG_FFRTMPHTTP_PROTOCOL 0
+#define CONFIG_FILE_PROTOCOL 0
+#define CONFIG_FTP_PROTOCOL 0
+#define CONFIG_GOPHER_PROTOCOL 0
+#define CONFIG_HLS_PROTOCOL 0
+#define CONFIG_HTTP_PROTOCOL 0
+#define CONFIG_HTTPPROXY_PROTOCOL 0
+#define CONFIG_HTTPS_PROTOCOL 0
+#define CONFIG_ICECAST_PROTOCOL 0
+#define CONFIG_MMSH_PROTOCOL 0
+#define CONFIG_MMST_PROTOCOL 0
+#define CONFIG_MD5_PROTOCOL 0
+#define CONFIG_PIPE_PROTOCOL 0
+#define CONFIG_PROMPEG_PROTOCOL 0
+#define CONFIG_RTMP_PROTOCOL 0
+#define CONFIG_RTMPE_PROTOCOL 0
+#define CONFIG_RTMPS_PROTOCOL 0
+#define CONFIG_RTMPT_PROTOCOL 0
+#define CONFIG_RTMPTE_PROTOCOL 0
+#define CONFIG_RTMPTS_PROTOCOL 0
+#define CONFIG_RTP_PROTOCOL 0
+#define CONFIG_SCTP_PROTOCOL 0
+#define CONFIG_SRTP_PROTOCOL 0
+#define CONFIG_SUBFILE_PROTOCOL 0
+#define CONFIG_TEE_PROTOCOL 0
+#define CONFIG_TCP_PROTOCOL 0
+#define CONFIG_TLS_GNUTLS_PROTOCOL 0
+#define CONFIG_TLS_SCHANNEL_PROTOCOL 0
+#define CONFIG_TLS_SECURETRANSPORT_PROTOCOL 0
+#define CONFIG_TLS_OPENSSL_PROTOCOL 0
+#define CONFIG_UDP_PROTOCOL 0
+#define CONFIG_UDPLITE_PROTOCOL 0
+#define CONFIG_UNIX_PROTOCOL 0
+#define CONFIG_LIBRTMP_PROTOCOL 0
+#define CONFIG_LIBRTMPE_PROTOCOL 0
+#define CONFIG_LIBRTMPS_PROTOCOL 0
+#define CONFIG_LIBRTMPT_PROTOCOL 0
+#define CONFIG_LIBRTMPTE_PROTOCOL 0
+#define CONFIG_LIBSSH_PROTOCOL 0
+#define CONFIG_LIBSMBCLIENT_PROTOCOL 0
diff --git a/media/ffvpx/ffvpxcommon.mozbuild b/media/ffvpx/ffvpxcommon.mozbuild
index 6d17e8807..620158694 100644
--- a/media/ffvpx/ffvpxcommon.mozbuild
+++ b/media/ffvpx/ffvpxcommon.mozbuild
@@ -29,6 +29,8 @@ if CONFIG['FFVPX_ASFLAGS']:
else:
# Default to unix, similar to how ASFLAGS setup works in configure.in
ASFLAGS += ['-Pconfig_unix64.asm']
+ # default disabled components
+ ASFLAGS += ['-Pdefaults_disabled.asm']
LOCAL_INCLUDES += ['/media/ffvpx']
@@ -51,6 +53,8 @@ if CONFIG['GNU_CC']:
'-Wno-incompatible-pointer-types-discards-qualifiers',
'-Wno-string-conversion',
'-Wno-visibility',
+ # Workaround for https://bugs.llvm.org/show_bug.cgi?id=26828#c4 :
+ '-ffreestanding',
]
else:
CFLAGS += [
@@ -87,6 +91,7 @@ elif CONFIG['_MSC_VER']:
'-wd4057', '-wd4204', '-wd4706', '-wd4305', '-wd4152', '-wd4324',
'-we4013', '-wd4100', '-wd4214', '-wd4307', '-wd4273', '-wd4554',
]
+ LOCAL_INCLUDES += ['/media/ffvpx/compat/atomics/win32']
DEFINES['HAVE_AV_CONFIG_H'] = True
diff --git a/media/ffvpx/libavcodec/allcodecs.c b/media/ffvpx/libavcodec/allcodecs.c
index b592aa3b2..4f34312e6 100644
--- a/media/ffvpx/libavcodec/allcodecs.c
+++ b/media/ffvpx/libavcodec/allcodecs.c
@@ -25,6 +25,7 @@
*/
#include "config.h"
+#include "libavutil/thread.h"
#include "avcodec.h"
#include "version.h"
@@ -58,20 +59,14 @@
av_register_codec_parser(&ff_##x##_parser); \
}
-void avcodec_register_all(void)
+static void register_all(void)
{
- static int initialized;
-
- if (initialized)
- return;
- initialized = 1;
-
/* hardware accelerators */
- REGISTER_HWACCEL(H263_CUVID, h263_cuvid);
REGISTER_HWACCEL(H263_VAAPI, h263_vaapi);
REGISTER_HWACCEL(H263_VIDEOTOOLBOX, h263_videotoolbox);
REGISTER_HWACCEL(H264_CUVID, h264_cuvid);
REGISTER_HWACCEL(H264_D3D11VA, h264_d3d11va);
+ REGISTER_HWACCEL(H264_D3D11VA2, h264_d3d11va2);
REGISTER_HWACCEL(H264_DXVA2, h264_dxva2);
REGISTER_HWACCEL(H264_MEDIACODEC, h264_mediacodec);
REGISTER_HWACCEL(H264_MMAL, h264_mmal);
@@ -83,11 +78,13 @@ void avcodec_register_all(void)
REGISTER_HWACCEL(H264_VIDEOTOOLBOX, h264_videotoolbox);
REGISTER_HWACCEL(HEVC_CUVID, hevc_cuvid);
REGISTER_HWACCEL(HEVC_D3D11VA, hevc_d3d11va);
+ REGISTER_HWACCEL(HEVC_D3D11VA2, hevc_d3d11va2);
REGISTER_HWACCEL(HEVC_DXVA2, hevc_dxva2);
REGISTER_HWACCEL(HEVC_MEDIACODEC, hevc_mediacodec);
REGISTER_HWACCEL(HEVC_QSV, hevc_qsv);
REGISTER_HWACCEL(HEVC_VAAPI, hevc_vaapi);
REGISTER_HWACCEL(HEVC_VDPAU, hevc_vdpau);
+ REGISTER_HWACCEL(HEVC_VIDEOTOOLBOX, hevc_videotoolbox);
REGISTER_HWACCEL(MJPEG_CUVID, mjpeg_cuvid);
REGISTER_HWACCEL(MPEG1_CUVID, mpeg1_cuvid);
REGISTER_HWACCEL(MPEG1_XVMC, mpeg1_xvmc);
@@ -96,12 +93,14 @@ void avcodec_register_all(void)
REGISTER_HWACCEL(MPEG2_CUVID, mpeg2_cuvid);
REGISTER_HWACCEL(MPEG2_XVMC, mpeg2_xvmc);
REGISTER_HWACCEL(MPEG2_D3D11VA, mpeg2_d3d11va);
+ REGISTER_HWACCEL(MPEG2_D3D11VA2, mpeg2_d3d11va2);
REGISTER_HWACCEL(MPEG2_DXVA2, mpeg2_dxva2);
REGISTER_HWACCEL(MPEG2_MMAL, mpeg2_mmal);
REGISTER_HWACCEL(MPEG2_QSV, mpeg2_qsv);
REGISTER_HWACCEL(MPEG2_VAAPI, mpeg2_vaapi);
REGISTER_HWACCEL(MPEG2_VDPAU, mpeg2_vdpau);
REGISTER_HWACCEL(MPEG2_VIDEOTOOLBOX, mpeg2_videotoolbox);
+ REGISTER_HWACCEL(MPEG2_MEDIACODEC, mpeg2_mediacodec);
REGISTER_HWACCEL(MPEG4_CUVID, mpeg4_cuvid);
REGISTER_HWACCEL(MPEG4_MEDIACODEC, mpeg4_mediacodec);
REGISTER_HWACCEL(MPEG4_MMAL, mpeg4_mmal);
@@ -110,6 +109,7 @@ void avcodec_register_all(void)
REGISTER_HWACCEL(MPEG4_VIDEOTOOLBOX, mpeg4_videotoolbox);
REGISTER_HWACCEL(VC1_CUVID, vc1_cuvid);
REGISTER_HWACCEL(VC1_D3D11VA, vc1_d3d11va);
+ REGISTER_HWACCEL(VC1_D3D11VA2, vc1_d3d11va2);
REGISTER_HWACCEL(VC1_DXVA2, vc1_dxva2);
REGISTER_HWACCEL(VC1_VAAPI, vc1_vaapi);
REGISTER_HWACCEL(VC1_VDPAU, vc1_vdpau);
@@ -117,12 +117,15 @@ void avcodec_register_all(void)
REGISTER_HWACCEL(VC1_QSV, vc1_qsv);
REGISTER_HWACCEL(VP8_CUVID, vp8_cuvid);
REGISTER_HWACCEL(VP8_MEDIACODEC, vp8_mediacodec);
+ REGISTER_HWACCEL(VP8_QSV, vp8_qsv);
REGISTER_HWACCEL(VP9_CUVID, vp9_cuvid);
REGISTER_HWACCEL(VP9_D3D11VA, vp9_d3d11va);
+ REGISTER_HWACCEL(VP9_D3D11VA2, vp9_d3d11va2);
REGISTER_HWACCEL(VP9_DXVA2, vp9_dxva2);
REGISTER_HWACCEL(VP9_MEDIACODEC, vp9_mediacodec);
REGISTER_HWACCEL(VP9_VAAPI, vp9_vaapi);
REGISTER_HWACCEL(WMV3_D3D11VA, wmv3_d3d11va);
+ REGISTER_HWACCEL(WMV3_D3D11VA2, wmv3_d3d11va2);
REGISTER_HWACCEL(WMV3_DXVA2, wmv3_dxva2);
REGISTER_HWACCEL(WMV3_VAAPI, wmv3_vaapi);
REGISTER_HWACCEL(WMV3_VDPAU, wmv3_vdpau);
@@ -158,6 +161,7 @@ void avcodec_register_all(void)
REGISTER_DECODER(CDXL, cdxl);
REGISTER_DECODER(CFHD, cfhd);
REGISTER_ENCDEC (CINEPAK, cinepak);
+ REGISTER_DECODER(CLEARVIDEO, clearvideo);
REGISTER_ENCDEC (CLJR, cljr);
REGISTER_DECODER(CLLC, cllc);
REGISTER_ENCDEC (COMFORTNOISE, comfortnoise);
@@ -189,24 +193,30 @@ void avcodec_register_all(void)
REGISTER_ENCDEC (FFV1, ffv1);
REGISTER_ENCDEC (FFVHUFF, ffvhuff);
REGISTER_DECODER(FIC, fic);
+ REGISTER_ENCDEC (FITS, fits);
REGISTER_ENCDEC (FLASHSV, flashsv);
REGISTER_ENCDEC (FLASHSV2, flashsv2);
REGISTER_DECODER(FLIC, flic);
REGISTER_ENCDEC (FLV, flv);
+ REGISTER_DECODER(FMVC, fmvc);
REGISTER_DECODER(FOURXM, fourxm);
REGISTER_DECODER(FRAPS, fraps);
REGISTER_DECODER(FRWU, frwu);
REGISTER_DECODER(G2M, g2m);
+ REGISTER_DECODER(GDV, gdv);
REGISTER_ENCDEC (GIF, gif);
REGISTER_ENCDEC (H261, h261);
REGISTER_ENCDEC (H263, h263);
REGISTER_DECODER(H263I, h263i);
REGISTER_ENCDEC (H263P, h263p);
+ REGISTER_DECODER(H263_V4L2M2M, h263_v4l2m2m);
REGISTER_DECODER(H264, h264);
REGISTER_DECODER(H264_CRYSTALHD, h264_crystalhd);
+ REGISTER_DECODER(H264_V4L2M2M, h264_v4l2m2m);
REGISTER_DECODER(H264_MEDIACODEC, h264_mediacodec);
REGISTER_DECODER(H264_MMAL, h264_mmal);
REGISTER_DECODER(H264_QSV, h264_qsv);
+ REGISTER_DECODER(H264_RKMPP, h264_rkmpp);
REGISTER_DECODER(H264_VDA, h264_vda);
#if FF_API_VDPAU
REGISTER_DECODER(H264_VDPAU, h264_vdpau);
@@ -214,6 +224,8 @@ void avcodec_register_all(void)
REGISTER_ENCDEC (HAP, hap);
REGISTER_DECODER(HEVC, hevc);
REGISTER_DECODER(HEVC_QSV, hevc_qsv);
+ REGISTER_DECODER(HEVC_RKMPP, hevc_rkmpp);
+ REGISTER_DECODER(HEVC_V4L2M2M, hevc_v4l2m2m);
REGISTER_DECODER(HNM4_VIDEO, hnm4_video);
REGISTER_DECODER(HQ_HQA, hq_hqa);
REGISTER_DECODER(HQX, hqx);
@@ -248,6 +260,7 @@ void avcodec_register_all(void)
REGISTER_ENCDEC (MPEG2VIDEO, mpeg2video);
REGISTER_ENCDEC (MPEG4, mpeg4);
REGISTER_DECODER(MPEG4_CRYSTALHD, mpeg4_crystalhd);
+ REGISTER_DECODER(MPEG4_V4L2M2M, mpeg4_v4l2m2m);
REGISTER_DECODER(MPEG4_MMAL, mpeg4_mmal);
#if FF_API_VDPAU
REGISTER_DECODER(MPEG4_VDPAU, mpeg4_vdpau);
@@ -257,14 +270,18 @@ void avcodec_register_all(void)
REGISTER_DECODER(MPEG_VDPAU, mpeg_vdpau);
REGISTER_DECODER(MPEG1_VDPAU, mpeg1_vdpau);
#endif
+ REGISTER_DECODER(MPEG1_V4L2M2M, mpeg1_v4l2m2m);
REGISTER_DECODER(MPEG2_MMAL, mpeg2_mmal);
REGISTER_DECODER(MPEG2_CRYSTALHD, mpeg2_crystalhd);
+ REGISTER_DECODER(MPEG2_V4L2M2M, mpeg2_v4l2m2m);
REGISTER_DECODER(MPEG2_QSV, mpeg2_qsv);
+ REGISTER_DECODER(MPEG2_MEDIACODEC, mpeg2_mediacodec);
REGISTER_DECODER(MSA1, msa1);
- REGISTER_DECODER(MSMPEG4_CRYSTALHD, msmpeg4_crystalhd);
+ REGISTER_DECODER(MSCC, mscc);
REGISTER_DECODER(MSMPEG4V1, msmpeg4v1);
REGISTER_ENCDEC (MSMPEG4V2, msmpeg4v2);
REGISTER_ENCDEC (MSMPEG4V3, msmpeg4v3);
+ REGISTER_DECODER(MSMPEG4_CRYSTALHD, msmpeg4_crystalhd);
REGISTER_DECODER(MSRLE, msrle);
REGISTER_DECODER(MSS1, mss1);
REGISTER_DECODER(MSS2, mss2);
@@ -282,12 +299,14 @@ void avcodec_register_all(void)
REGISTER_ENCDEC (PGM, pgm);
REGISTER_ENCDEC (PGMYUV, pgmyuv);
REGISTER_DECODER(PICTOR, pictor);
+ REGISTER_DECODER(PIXLET, pixlet);
REGISTER_ENCDEC (PNG, png);
REGISTER_ENCDEC (PPM, ppm);
REGISTER_ENCDEC (PRORES, prores);
REGISTER_ENCODER(PRORES_AW, prores_aw);
REGISTER_ENCODER(PRORES_KS, prores_ks);
REGISTER_DECODER(PRORES_LGPL, prores_lgpl);
+ REGISTER_DECODER(PSD, psd);
REGISTER_DECODER(PTX, ptx);
REGISTER_DECODER(QDRAW, qdraw);
REGISTER_DECODER(QPEG, qpeg);
@@ -305,6 +324,7 @@ void avcodec_register_all(void)
REGISTER_DECODER(RV40, rv40);
REGISTER_ENCDEC (S302M, s302m);
REGISTER_DECODER(SANM, sanm);
+ REGISTER_DECODER(SCPR, scpr);
REGISTER_DECODER(SCREENPRESSO, screenpresso);
REGISTER_DECODER(SDX2_DPCM, sdx2_dpcm);
REGISTER_ENCDEC (SGI, sgi);
@@ -315,6 +335,8 @@ void avcodec_register_all(void)
REGISTER_DECODER(SMVJPEG, smvjpeg);
REGISTER_ENCDEC (SNOW, snow);
REGISTER_DECODER(SP5X, sp5x);
+ REGISTER_DECODER(SPEEDHQ, speedhq);
+ REGISTER_DECODER(SRGC, srgc);
REGISTER_ENCDEC (SUNRAST, sunrast);
REGISTER_ENCDEC (SVQ1, svq1);
REGISTER_DECODER(SVQ3, svq3);
@@ -349,6 +371,7 @@ void avcodec_register_all(void)
REGISTER_DECODER(VC1IMAGE, vc1image);
REGISTER_DECODER(VC1_MMAL, vc1_mmal);
REGISTER_DECODER(VC1_QSV, vc1_qsv);
+ REGISTER_DECODER(VC1_V4L2M2M, vc1_v4l2m2m);
REGISTER_ENCODER(VC2, vc2);
REGISTER_DECODER(VCR1, vcr1);
REGISTER_DECODER(VMDVIDEO, vmdvideo);
@@ -360,10 +383,15 @@ void avcodec_register_all(void)
REGISTER_DECODER(VP6F, vp6f);
REGISTER_DECODER(VP7, vp7);
REGISTER_DECODER(VP8, vp8);
+ REGISTER_DECODER(VP8_RKMPP, vp8_rkmpp);
+ REGISTER_DECODER(VP8_V4L2M2M, vp8_v4l2m2m);
REGISTER_DECODER(VP9, vp9);
+ REGISTER_DECODER(VP9_RKMPP, vp9_rkmpp);
+ REGISTER_DECODER(VP9_V4L2M2M, vp9_v4l2m2m);
REGISTER_DECODER(VQA, vqa);
+ REGISTER_DECODER(BITPACKED, bitpacked);
REGISTER_DECODER(WEBP, webp);
- REGISTER_ENCODER(WRAPPED_AVFRAME, wrapped_avframe);
+ REGISTER_ENCDEC (WRAPPED_AVFRAME, wrapped_avframe);
REGISTER_ENCDEC (WMV1, wmv1);
REGISTER_ENCDEC (WMV2, wmv2);
REGISTER_DECODER(WMV3, wmv3);
@@ -378,6 +406,7 @@ void avcodec_register_all(void)
REGISTER_ENCDEC (XBM, xbm);
REGISTER_ENCDEC (XFACE, xface);
REGISTER_DECODER(XL, xl);
+ REGISTER_DECODER(XPM, xpm);
REGISTER_ENCDEC (XWD, xwd);
REGISTER_ENCDEC (Y41P, y41p);
REGISTER_DECODER(YLC, ylc);
@@ -401,12 +430,15 @@ void avcodec_register_all(void)
REGISTER_DECODER(APE, ape);
REGISTER_DECODER(ATRAC1, atrac1);
REGISTER_DECODER(ATRAC3, atrac3);
+ REGISTER_DECODER(ATRAC3AL, atrac3al);
REGISTER_DECODER(ATRAC3P, atrac3p);
+ REGISTER_DECODER(ATRAC3PAL, atrac3pal);
REGISTER_DECODER(BINKAUDIO_DCT, binkaudio_dct);
REGISTER_DECODER(BINKAUDIO_RDFT, binkaudio_rdft);
REGISTER_DECODER(BMV_AUDIO, bmv_audio);
REGISTER_DECODER(COOK, cook);
REGISTER_ENCDEC (DCA, dca);
+ REGISTER_DECODER(DOLBY_E, dolby_e);
REGISTER_DECODER(DSD_LSBF, dsd_lsbf);
REGISTER_DECODER(DSD_MSBF, dsd_msbf);
REGISTER_DECODER(DSD_LSBF_PLANAR, dsd_lsbf_planar);
@@ -444,10 +476,11 @@ void avcodec_register_all(void)
REGISTER_DECODER(MPC8, mpc8);
REGISTER_ENCDEC (NELLYMOSER, nellymoser);
REGISTER_DECODER(ON2AVC, on2avc);
- REGISTER_DECODER(OPUS, opus);
+ REGISTER_ENCDEC (OPUS, opus);
REGISTER_DECODER(PAF_AUDIO, paf_audio);
REGISTER_DECODER(QCELP, qcelp);
REGISTER_DECODER(QDM2, qdm2);
+ REGISTER_DECODER(QDMC, qdmc);
REGISTER_ENCDEC (RA_144, ra_144);
REGISTER_DECODER(RA_288, ra_288);
REGISTER_DECODER(RALF, ralf);
@@ -477,6 +510,8 @@ void avcodec_register_all(void)
REGISTER_ENCDEC (PCM_ALAW, pcm_alaw);
REGISTER_DECODER(PCM_BLURAY, pcm_bluray);
REGISTER_DECODER(PCM_DVD, pcm_dvd);
+ REGISTER_DECODER(PCM_F16LE, pcm_f16le);
+ REGISTER_DECODER(PCM_F24LE, pcm_f24le);
REGISTER_ENCDEC (PCM_F32BE, pcm_f32be);
REGISTER_ENCDEC (PCM_F32LE, pcm_f32le);
REGISTER_ENCDEC (PCM_F64BE, pcm_f64be);
@@ -508,6 +543,7 @@ void avcodec_register_all(void)
REGISTER_DECODER(PCM_ZORK, pcm_zork);
/* DPCM codecs */
+ REGISTER_DECODER(GREMLIN_DPCM, gremlin_dpcm);
REGISTER_DECODER(INTERPLAY_DPCM, interplay_dpcm);
REGISTER_ENCDEC (ROQ_DPCM, roq_dpcm);
REGISTER_DECODER(SOL_DPCM, sol_dpcm);
@@ -528,7 +564,7 @@ void avcodec_register_all(void)
REGISTER_DECODER(ADPCM_EA_XAS, adpcm_ea_xas);
REGISTER_ENCDEC (ADPCM_G722, adpcm_g722);
REGISTER_ENCDEC (ADPCM_G726, adpcm_g726);
- REGISTER_DECODER(ADPCM_G726LE, adpcm_g726le);
+ REGISTER_ENCDEC (ADPCM_G726LE, adpcm_g726le);
REGISTER_DECODER(ADPCM_IMA_AMV, adpcm_ima_amv);
REGISTER_DECODER(ADPCM_IMA_APC, adpcm_ima_apc);
REGISTER_DECODER(ADPCM_IMA_DAT4, adpcm_ima_dat4);
@@ -606,7 +642,7 @@ void avcodec_register_all(void)
REGISTER_DECODER(LIBOPENCORE_AMRWB, libopencore_amrwb);
REGISTER_ENCDEC (LIBOPENJPEG, libopenjpeg);
REGISTER_ENCDEC (LIBOPUS, libopus);
- REGISTER_ENCDEC (LIBSCHROEDINGER, libschroedinger);
+ REGISTER_DECODER(LIBRSVG, librsvg);
REGISTER_ENCODER(LIBSHINE, libshine);
REGISTER_ENCDEC (LIBSPEEX, libspeex);
REGISTER_ENCODER(LIBTHEORA, libtheora);
@@ -633,12 +669,13 @@ void avcodec_register_all(void)
/* external libraries, that shouldn't be used by default if one of the
* above is available */
+ REGISTER_ENCODER(H263_V4L2M2M, h263_v4l2m2m);
REGISTER_ENCDEC (LIBOPENH264, libopenh264);
- REGISTER_DECODER(H263_CUVID, h263_cuvid);
REGISTER_DECODER(H264_CUVID, h264_cuvid);
REGISTER_ENCODER(H264_NVENC, h264_nvenc);
REGISTER_ENCODER(H264_OMX, h264_omx);
REGISTER_ENCODER(H264_QSV, h264_qsv);
+ REGISTER_ENCODER(H264_V4L2M2M, h264_v4l2m2m);
REGISTER_ENCODER(H264_VAAPI, h264_vaapi);
REGISTER_ENCODER(H264_VIDEOTOOLBOX, h264_videotoolbox);
#if FF_API_NVENC_OLD_NAME
@@ -650,6 +687,7 @@ void avcodec_register_all(void)
REGISTER_DECODER(HEVC_MEDIACODEC, hevc_mediacodec);
REGISTER_ENCODER(HEVC_NVENC, hevc_nvenc);
REGISTER_ENCODER(HEVC_QSV, hevc_qsv);
+ REGISTER_ENCODER(HEVC_V4L2M2M, hevc_v4l2m2m);
REGISTER_ENCODER(HEVC_VAAPI, hevc_vaapi);
REGISTER_ENCODER(LIBKVAZAAR, libkvazaar);
REGISTER_DECODER(MJPEG_CUVID, mjpeg_cuvid);
@@ -657,13 +695,19 @@ void avcodec_register_all(void)
REGISTER_DECODER(MPEG1_CUVID, mpeg1_cuvid);
REGISTER_DECODER(MPEG2_CUVID, mpeg2_cuvid);
REGISTER_ENCODER(MPEG2_QSV, mpeg2_qsv);
+ REGISTER_ENCODER(MPEG2_VAAPI, mpeg2_vaapi);
REGISTER_DECODER(MPEG4_CUVID, mpeg4_cuvid);
REGISTER_DECODER(MPEG4_MEDIACODEC, mpeg4_mediacodec);
+ REGISTER_ENCODER(MPEG4_V4L2M2M, mpeg4_v4l2m2m);
REGISTER_DECODER(VC1_CUVID, vc1_cuvid);
REGISTER_DECODER(VP8_CUVID, vp8_cuvid);
REGISTER_DECODER(VP8_MEDIACODEC, vp8_mediacodec);
+ REGISTER_DECODER(VP8_QSV, vp8_qsv);
+ REGISTER_ENCODER(VP8_V4L2M2M, vp8_v4l2m2m);
+ REGISTER_ENCODER(VP8_VAAPI, vp8_vaapi);
REGISTER_DECODER(VP9_CUVID, vp9_cuvid);
REGISTER_DECODER(VP9_MEDIACODEC, vp9_mediacodec);
+ REGISTER_ENCODER(VP9_VAAPI, vp9_vaapi);
/* parsers */
REGISTER_PARSER(AAC, aac);
@@ -698,10 +742,19 @@ void avcodec_register_all(void)
REGISTER_PARSER(PNM, pnm);
REGISTER_PARSER(RV30, rv30);
REGISTER_PARSER(RV40, rv40);
+ REGISTER_PARSER(SIPR, sipr);
REGISTER_PARSER(TAK, tak);
REGISTER_PARSER(VC1, vc1);
REGISTER_PARSER(VORBIS, vorbis);
REGISTER_PARSER(VP3, vp3);
REGISTER_PARSER(VP8, vp8);
REGISTER_PARSER(VP9, vp9);
+ REGISTER_PARSER(XMA, xma);
+}
+
+void avcodec_register_all(void)
+{
+ static AVOnce control = AV_ONCE_INIT;
+
+ ff_thread_once(&control, register_all);
}
diff --git a/media/ffvpx/libavcodec/avcodec.h b/media/ffvpx/libavcodec/avcodec.h
index e5e7f4225..18c3e3ea1 100644
--- a/media/ffvpx/libavcodec/avcodec.h
+++ b/media/ffvpx/libavcodec/avcodec.h
@@ -89,7 +89,7 @@
* - Send valid input:
* - For decoding, call avcodec_send_packet() to give the decoder raw
* compressed data in an AVPacket.
- * - For encoding, call avcodec_send_frame() to give the decoder an AVFrame
+ * - For encoding, call avcodec_send_frame() to give the encoder an AVFrame
* containing uncompressed audio or video.
* In both cases, it is recommended that AVPackets and AVFrames are
* refcounted, or libavcodec might have to copy the input data. (libavformat
@@ -112,6 +112,12 @@
* are filled. This situation is handled transparently if you follow the steps
* outlined above.
*
+ * In theory, sending input can result in EAGAIN - this should happen only if
+ * not all output was received. You can use this to structure alternative decode
+ * or encode loops other than the one suggested above. For example, you could
+ * try sending new input on each iteration, and try to receive output if that
+ * returns EAGAIN.
+ *
* End of stream situations. These require "flushing" (aka draining) the codec,
* as the codec might buffer multiple frames or packets internally for
* performance or out of necessity (consider B-frames).
@@ -136,8 +142,9 @@
*
* Not all codecs will follow a rigid and predictable dataflow; the only
* guarantee is that an AVERROR(EAGAIN) return value on a send/receive call on
- * one end implies that a receive/send call on the other end will succeed. In
- * general, no codec will permit unlimited buffering of input or output.
+ * one end implies that a receive/send call on the other end will succeed, or
+ * at least will not fail with AVERROR(EAGAIN). In general, no codec will
+ * permit unlimited buffering of input or output.
*
* This API replaces the following legacy functions:
* - avcodec_decode_video2() and avcodec_decode_audio4():
@@ -146,7 +153,8 @@
* Unlike with the old video decoding API, multiple frames might result from
* a packet. For audio, splitting the input packet into frames by partially
* decoding packets becomes transparent to the API user. You never need to
- * feed an AVPacket to the API twice.
+ * feed an AVPacket to the API twice (unless it is rejected with AVERROR(EAGAIN) - then
+ * no data was read from the packet).
* Additionally, sending a flush/draining packet is required only once.
* - avcodec_encode_video2()/avcodec_encode_audio2():
* Use avcodec_send_frame() to feed input to the encoder, then use
@@ -159,7 +167,22 @@
* and will result in undefined behavior.
*
* Some codecs might require using the new API; using the old API will return
- * an error when calling it.
+ * an error when calling it. All codecs support the new API.
+ *
+ * A codec is not allowed to return AVERROR(EAGAIN) for both sending and receiving. This
+ * would be an invalid state, which could put the codec user into an endless
+ * loop. The API has no concept of time either: it cannot happen that trying to
+ * do avcodec_send_packet() results in AVERROR(EAGAIN), but a repeated call 1 second
+ * later accepts the packet (with no other receive/flush API calls involved).
+ * The API is a strict state machine, and the passage of time is not supposed
+ * to influence it. Some timing-dependent behavior might still be deemed
+ * acceptable in certain cases. But it must never result in both send/receive
+ * returning EAGAIN at the same time at any point. It must also absolutely be
+ * avoided that the current state is "unstable" and can "flip-flop" between
+ * the send/receive APIs allowing progress. For example, it's not allowed that
+ * the codec randomly decides that it actually wants to consume a packet now
+ * instead of returning a frame, after it just returned AVERROR(EAGAIN) on an
+ * avcodec_send_packet() call.
* @}
*/
@@ -411,6 +434,20 @@ enum AVCodecID {
AV_CODEC_ID_MAGICYUV,
AV_CODEC_ID_SHEERVIDEO,
AV_CODEC_ID_YLC,
+ AV_CODEC_ID_PSD,
+ AV_CODEC_ID_PIXLET,
+ AV_CODEC_ID_SPEEDHQ,
+ AV_CODEC_ID_FMVC,
+ AV_CODEC_ID_SCPR,
+ AV_CODEC_ID_CLEARVIDEO,
+ AV_CODEC_ID_XPM,
+ AV_CODEC_ID_AV1,
+ AV_CODEC_ID_BITPACKED,
+ AV_CODEC_ID_MSCC,
+ AV_CODEC_ID_SRGC,
+ AV_CODEC_ID_SVG,
+ AV_CODEC_ID_GDV,
+ AV_CODEC_ID_FITS,
/* various PCM "codecs" */
AV_CODEC_ID_FIRST_AUDIO = 0x10000, ///< A dummy id pointing at the start of audio codecs
@@ -448,6 +485,8 @@ enum AVCodecID {
AV_CODEC_ID_PCM_S64LE = 0x10800,
AV_CODEC_ID_PCM_S64BE,
+ AV_CODEC_ID_PCM_F16LE,
+ AV_CODEC_ID_PCM_F24LE,
/* various ADPCM codecs */
AV_CODEC_ID_ADPCM_IMA_QT = 0x11000,
@@ -511,6 +550,7 @@ enum AVCodecID {
AV_CODEC_ID_SOL_DPCM,
AV_CODEC_ID_SDX2_DPCM = 0x14800,
+ AV_CODEC_ID_GREMLIN_DPCM,
/* audio codecs */
AV_CODEC_ID_MP2 = 0x15000,
@@ -598,6 +638,9 @@ enum AVCodecID {
AV_CODEC_ID_XMA1,
AV_CODEC_ID_XMA2,
AV_CODEC_ID_DST,
+ AV_CODEC_ID_ATRAC3AL,
+ AV_CODEC_ID_ATRAC3PAL,
+ AV_CODEC_ID_DOLBY_E,
/* subtitle codecs */
AV_CODEC_ID_FIRST_SUBTITLE = 0x17000, ///< A dummy ID pointing at the start of subtitle codecs.
@@ -689,7 +732,7 @@ typedef struct AVCodecDescriptor {
/**
* Codec uses only intra compression.
- * Video codecs only.
+ * Video and audio codecs only.
*/
#define AV_CODEC_PROP_INTRA_ONLY (1 << 0)
/**
@@ -1360,6 +1403,11 @@ typedef struct AVCPBProperties {
* @{
*/
enum AVPacketSideDataType {
+ /**
+ * An AV_PKT_DATA_PALETTE side data packet contains exactly AVPALETTE_SIZE
+ * bytes worth of palette. This side data signals that a new palette is
+ * present.
+ */
AV_PKT_DATA_PALETTE,
/**
@@ -1533,10 +1581,40 @@ enum AVPacketSideDataType {
/**
* Mastering display metadata (based on SMPTE-2086:2014). This metadata
- * should be associated with a video stream and containts data in the form
+ * should be associated with a video stream and contains data in the form
* of the AVMasteringDisplayMetadata struct.
*/
- AV_PKT_DATA_MASTERING_DISPLAY_METADATA
+ AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
+
+ /**
+ * This side data should be associated with a video stream and corresponds
+ * to the AVSphericalMapping structure.
+ */
+ AV_PKT_DATA_SPHERICAL,
+
+ /**
+ * Content light level (based on CTA-861.3). This metadata should be
+ * associated with a video stream and contains data in the form of the
+ * AVContentLightMetadata struct.
+ */
+ AV_PKT_DATA_CONTENT_LIGHT_LEVEL,
+
+ /**
+ * ATSC A53 Part 4 Closed Captions. This metadata should be associated with
+ * a video stream. A53 CC bitstream is stored as uint8_t in AVPacketSideData.data.
+ * The number of bytes of CC data is AVPacketSideData.size.
+ */
+ AV_PKT_DATA_A53_CC,
+
+ /**
+ * The number of side data elements (in fact a bit more than it).
+ * This is not part of the public API/ABI in the sense that it may
+ * change when new side data types are added.
+ * This must stay the last enum value.
+ * If its value becomes huge, some code using it
+ * needs to be updated as it assumes it to be smaller than other limits.
+ */
+ AV_PKT_DATA_NB
};
#define AV_PKT_DATA_QUALITY_FACTOR AV_PKT_DATA_QUALITY_STATS //DEPRECATED
@@ -1638,6 +1716,13 @@ typedef struct AVPacket {
* after decoding.
**/
#define AV_PKT_FLAG_DISCARD 0x0004
+/**
+ * The packet comes from a trusted source.
+ *
+ * Otherwise-unsafe constructs such as arbitrary pointers to data
+ * outside the packet may be followed.
+ */
+#define AV_PKT_FLAG_TRUSTED 0x0008
enum AVSideDataParamChangeFlags {
AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT = 0x0001,
@@ -1665,7 +1750,7 @@ enum AVFieldOrder {
* New fields can be added to the end with minor version bumps.
* Removal, reordering and changes to existing fields require a major
* version bump.
- * Please use AVOptions (av_opt* / av_set/get*()) to access these fields from user
+ * You can use AVOptions (av_opt* / av_set/get*()) to access these fields from user
* applications.
* The name string for AVOptions options matches the associated command line
* parameter name and can be found in libavcodec/options_table.h
@@ -2605,6 +2690,7 @@ typedef struct AVCodecContext {
* - encoding: unused
* - decoding: set by the caller before avcodec_open2().
*/
+ attribute_deprecated
int refcounted_frames;
/* - encoding parameters */
@@ -2936,8 +3022,8 @@ typedef struct AVCodecContext {
#define FF_DEBUG_MMCO 0x00000800
#define FF_DEBUG_BUGS 0x00001000
#if FF_API_DEBUG_MV
-#define FF_DEBUG_VIS_QP 0x00002000 ///< only access through AVOptions from outside libavcodec
-#define FF_DEBUG_VIS_MB_TYPE 0x00004000 ///< only access through AVOptions from outside libavcodec
+#define FF_DEBUG_VIS_QP 0x00002000
+#define FF_DEBUG_VIS_MB_TYPE 0x00004000
#endif
#define FF_DEBUG_BUFFERS 0x00008000
#define FF_DEBUG_THREADS 0x00010000
@@ -2947,7 +3033,6 @@ typedef struct AVCodecContext {
#if FF_API_DEBUG_MV
/**
* debug
- * Code outside libavcodec should access this field using AVOptions
* - encoding: Set by user.
* - decoding: Set by user.
*/
@@ -3061,6 +3146,7 @@ typedef struct AVCodecContext {
#if FF_API_ARCH_ALPHA
#define FF_IDCT_SIMPLEALPHA 23
#endif
+#define FF_IDCT_NONE 24 /* Used by XvMC to extract IDCT coefficients with FF_IDCT_PERM_NONE */
#define FF_IDCT_SIMPLEAUTO 128
/**
@@ -3082,8 +3168,6 @@ typedef struct AVCodecContext {
* low resolution decoding, 1-> 1/2 size, 2->1/4 size
* - encoding: unused
* - decoding: Set by user.
- * Code outside libavcodec should access this field using:
- * av_codec_{get,set}_lowres(avctx)
*/
int lowres;
#endif
@@ -3384,8 +3468,6 @@ typedef struct AVCodecContext {
/**
* Timebase in which pkt_dts/pts and AVPacket.dts/pts are.
- * Code outside libavcodec should access this field using:
- * av_codec_{get,set}_pkt_timebase(avctx)
* - encoding unused.
* - decoding set by user.
*/
@@ -3393,8 +3475,6 @@ typedef struct AVCodecContext {
/**
* AVCodecDescriptor
- * Code outside libavcodec should access this field using:
- * av_codec_{get,set}_codec_descriptor(avctx)
* - encoding: unused.
* - decoding: set by libavcodec.
*/
@@ -3405,8 +3485,6 @@ typedef struct AVCodecContext {
* low resolution decoding, 1-> 1/2 size, 2->1/4 size
* - encoding: unused
* - decoding: Set by user.
- * Code outside libavcodec should access this field using:
- * av_codec_{get,set}_lowres(avctx)
*/
int lowres;
#endif
@@ -3447,7 +3525,6 @@ typedef struct AVCodecContext {
* However for formats that do not use pre-multiplied alpha
* there might be serious artefacts (though e.g. libswscale currently
* assumes pre-multiplied alpha anyway).
- * Code outside libavcodec should access this field using AVOptions
*
* - decoding: set by user
* - encoding: unused
@@ -3464,7 +3541,6 @@ typedef struct AVCodecContext {
#if !FF_API_DEBUG_MV
/**
* debug motion vectors
- * Code outside libavcodec should access this field using AVOptions
* - encoding: Set by user.
* - decoding: Set by user.
*/
@@ -3476,7 +3552,6 @@ typedef struct AVCodecContext {
/**
* custom intra quantization matrix
- * Code outside libavcodec should access this field using av_codec_g/set_chroma_intra_matrix()
* - encoding: Set by user, can be NULL.
* - decoding: unused.
*/
@@ -3485,8 +3560,6 @@ typedef struct AVCodecContext {
/**
* dump format separator.
* can be ", " or "\n " or anything else
- * Code outside libavcodec should access this field using AVOptions
- * (NO direct access).
* - encoding: Set by user.
* - decoding: Set by user.
*/
@@ -3496,13 +3569,12 @@ typedef struct AVCodecContext {
* ',' separated list of allowed decoders.
* If NULL then all are allowed
* - encoding: unused
- * - decoding: set by user through AVOPtions (NO direct access)
+ * - decoding: set by user
*/
char *codec_whitelist;
- /*
+ /**
* Properties of the stream that gets decoded
- * To be accessed through av_codec_get_properties() (NO direct access)
* - encoding: unused
* - decoding: set by libavcodec
*/
@@ -3522,7 +3594,8 @@ typedef struct AVCodecContext {
/**
* A reference to the AVHWFramesContext describing the input (for encoding)
* or output (decoding) frames. The reference is set by the caller and
- * afterwards owned (and freed) by libavcodec.
+ * afterwards owned (and freed) by libavcodec - it should never be read by
+ * the caller after being set.
*
* - decoding: This field should be set by the caller from the get_format()
* callback. The previous reference (if any) will always be
@@ -3564,6 +3637,71 @@ typedef struct AVCodecContext {
*/
int trailing_padding;
+ /**
+ * The number of pixels per image to maximally accept.
+ *
+ * - decoding: set by user
+ * - encoding: set by user
+ */
+ int64_t max_pixels;
+
+ /**
+ * A reference to the AVHWDeviceContext describing the device which will
+ * be used by a hardware encoder/decoder. The reference is set by the
+ * caller and afterwards owned (and freed) by libavcodec.
+ *
+ * This should be used if either the codec device does not require
+ * hardware frames or any that are used are to be allocated internally by
+ * libavcodec. If the user wishes to supply any of the frames used as
+ * encoder input or decoder output then hw_frames_ctx should be used
+ * instead. When hw_frames_ctx is set in get_format() for a decoder, this
+ * field will be ignored while decoding the associated stream segment, but
+ * may again be used on a following one after another get_format() call.
+ *
+ * For both encoders and decoders this field should be set before
+ * avcodec_open2() is called and must not be written to thereafter.
+ *
+ * Note that some decoders may require this field to be set initially in
+ * order to support hw_frames_ctx at all - in that case, all frames
+ * contexts used must be created on the same device.
+ */
+ AVBufferRef *hw_device_ctx;
+
+ /**
+ * Bit set of AV_HWACCEL_FLAG_* flags, which affect hardware accelerated
+ * decoding (if active).
+ * - encoding: unused
+ * - decoding: Set by user (either before avcodec_open2(), or in the
+ * AVCodecContext.get_format callback)
+ */
+ int hwaccel_flags;
+
+ /**
+ * Video decoding only. Certain video codecs support cropping, meaning that
+ * only a sub-rectangle of the decoded frame is intended for display. This
+ * option controls how cropping is handled by libavcodec.
+ *
+ * When set to 1 (the default), libavcodec will apply cropping internally.
+ * I.e. it will modify the output frame width/height fields and offset the
+ * data pointers (only by as much as possible while preserving alignment, or
+ * by the full amount if the AV_CODEC_FLAG_UNALIGNED flag is set) so that
+ * the frames output by the decoder refer only to the cropped area. The
+ * crop_* fields of the output frames will be zero.
+ *
+ * When set to 0, the width/height fields of the output frames will be set
+ * to the coded dimensions and the crop_* fields will describe the cropping
+ * rectangle. Applying the cropping is left to the caller.
+ *
+ * @warning When hardware acceleration with opaque output frames is used,
+ * libavcodec is unable to apply cropping from the top/left border.
+ *
+ * @note when this option is set to zero, the width/height fields of the
+ * AVCodecContext and output AVFrames have different meanings. The codec
+ * context fields store display dimensions (with the coded dimensions in
+ * coded_width/height), while the frame fields store the coded dimensions
+ * (with the display dimensions being determined by the crop_* fields).
+ */
+ int apply_cropping;
} AVCodecContext;
AVRational av_codec_get_pkt_timebase (const AVCodecContext *avctx);
@@ -3623,7 +3761,7 @@ typedef struct AVCodec {
const int *supported_samplerates; ///< array of supported audio samplerates, or NULL if unknown, array is terminated by 0
const enum AVSampleFormat *sample_fmts; ///< array of supported sample formats, or NULL if unknown, array is terminated by -1
const uint64_t *channel_layouts; ///< array of support channel layouts, or NULL if unknown. array is terminated by 0
- uint8_t max_lowres; ///< maximum value for lowres supported by the decoder, no direct access, use av_codec_get_max_lowres()
+ uint8_t max_lowres; ///< maximum value for lowres supported by the decoder
const AVClass *priv_class; ///< AVClass for the private context
const AVProfile *profiles; ///< array of recognized profiles, or NULL if unknown, array is terminated by {FF_PROFILE_UNKNOWN}
@@ -3684,20 +3822,22 @@ typedef struct AVCodec {
int (*decode)(AVCodecContext *, void *outdata, int *outdata_size, AVPacket *avpkt);
int (*close)(AVCodecContext *);
/**
- * Decode/encode API with decoupled packet/frame dataflow. The API is the
+ * Encode API with decoupled packet/frame dataflow. The API is the
* same as the avcodec_ prefixed APIs (avcodec_send_frame() etc.), except
* that:
* - never called if the codec is closed or the wrong type,
- * - AVPacket parameter change side data is applied right before calling
- * AVCodec->send_packet,
- * - if AV_CODEC_CAP_DELAY is not set, drain packets or frames are never sent,
- * - only one drain packet is ever passed down (until the next flush()),
- * - a drain AVPacket is always NULL (no need to check for avpkt->size).
+ * - if AV_CODEC_CAP_DELAY is not set, drain frames are never sent,
+ * - only one drain frame is ever passed down,
*/
int (*send_frame)(AVCodecContext *avctx, const AVFrame *frame);
- int (*send_packet)(AVCodecContext *avctx, const AVPacket *avpkt);
- int (*receive_frame)(AVCodecContext *avctx, AVFrame *frame);
int (*receive_packet)(AVCodecContext *avctx, AVPacket *avpkt);
+
+ /**
+ * Decode API with decoupled packet/frame dataflow. This function is called
+ * to get one output frame. It should call ff_decode_get_packet() to obtain
+ * input data.
+ */
+ int (*receive_frame)(AVCodecContext *avctx, AVFrame *frame);
/**
* Flush buffers.
* Will be called when seeking
@@ -3708,6 +3848,12 @@ typedef struct AVCodec {
* See FF_CODEC_CAP_* in internal.h
*/
int caps_internal;
+
+ /**
+ * Decoding only, a comma-separated list of bitstream filters to apply to
+ * packets before decoding.
+ */
+ const char *bsfs;
} AVCodec;
int av_codec_get_max_lowres(const AVCodec *codec);
@@ -3749,7 +3895,7 @@ typedef struct AVHWAccel {
/**
* Hardware accelerated codec capabilities.
- * see HWACCEL_CODEC_CAP_*
+ * see AV_HWACCEL_CODEC_CAP_*
*/
int capabilities;
@@ -3820,7 +3966,7 @@ typedef struct AVHWAccel {
/**
* Called for every Macroblock in a slice.
*
- * XvMC uses it to replace the ff_mpv_decode_mb().
+ * XvMC uses it to replace the ff_mpv_reconstruct_mb().
* Instead of decoding to raw picture, MB parameters are
* stored in an array provided by the video driver.
*
@@ -3850,9 +3996,20 @@ typedef struct AVHWAccel {
* AVCodecInternal.hwaccel_priv_data.
*/
int priv_data_size;
+
+ /**
+ * Internal hwaccel capabilities.
+ */
+ int caps_internal;
} AVHWAccel;
/**
+ * HWAccel is experimental and is thus avoided in favor of non experimental
+ * codecs
+ */
+#define AV_HWACCEL_CODEC_CAP_EXPERIMENTAL 0x0200
+
+/**
* Hardware acceleration should be used for decoding even if the codec level
* used is unknown or higher than the maximum supported level reported by the
* hardware driver.
@@ -3869,6 +4026,20 @@ typedef struct AVHWAccel {
#define AV_HWACCEL_FLAG_ALLOW_HIGH_DEPTH (1 << 1)
/**
+ * Hardware acceleration should still be attempted for decoding when the
+ * codec profile does not match the reported capabilities of the hardware.
+ *
+ * For example, this can be used to try to decode baseline profile H.264
+ * streams in hardware - it will often succeed, because many streams marked
+ * as baseline profile actually conform to constrained baseline profile.
+ *
+ * @warning If the stream is actually not supported then the behaviour is
+ * undefined, and may include returning entirely incorrect output
+ * while indicating success.
+ */
+#define AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH (1 << 2)
+
+/**
* @}
*/
@@ -4377,13 +4548,13 @@ AVPacket *av_packet_alloc(void);
* @see av_packet_alloc
* @see av_packet_ref
*/
-AVPacket *av_packet_clone(AVPacket *src);
+AVPacket *av_packet_clone(const AVPacket *src);
/**
* Free the packet, if the packet is reference counted, it will be
* unreferenced first.
*
- * @param packet packet to be freed. The pointer will be set to NULL.
+ * @param pkt packet to be freed. The pointer will be set to NULL.
* @note passing NULL is a no-op.
*/
void av_packet_free(AVPacket **pkt);
@@ -4452,14 +4623,20 @@ int av_dup_packet(AVPacket *pkt);
* Copy packet, including contents
*
* @return 0 on success, negative AVERROR on fail
+ *
+ * @deprecated Use av_packet_ref
*/
+attribute_deprecated
int av_copy_packet(AVPacket *dst, const AVPacket *src);
/**
* Copy packet side data
*
* @return 0 on success, negative AVERROR on fail
+ *
+ * @deprecated Use av_packet_copy_props
*/
+attribute_deprecated
int av_copy_packet_side_data(AVPacket *dst, const AVPacket *src);
/**
@@ -4518,12 +4695,16 @@ int av_packet_shrink_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
* @param size pointer for side information size to store (optional)
* @return pointer to data if present or NULL otherwise
*/
-uint8_t* av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+uint8_t* av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type,
int *size);
+#if FF_API_MERGE_SD_API
+attribute_deprecated
int av_packet_merge_side_data(AVPacket *pkt);
+attribute_deprecated
int av_packet_split_side_data(AVPacket *pkt);
+#endif
const char *av_packet_side_data_name(enum AVPacketSideDataType type);
@@ -4823,13 +5004,13 @@ int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
* and reusing a get_buffer written for video codecs would probably perform badly
* due to a potentially very different allocation pattern.
*
- * Some decoders (those marked with CODEC_CAP_DELAY) have a delay between input
+ * Some decoders (those marked with AV_CODEC_CAP_DELAY) have a delay between input
* and output. This means that for some packets they will not immediately
* produce decoded output and need to be flushed at the end of decoding to get
* all the decoded data. Flushing is done by calling this function with packets
* with avpkt->data set to NULL and avpkt->size set to 0 until it stops
* returning subtitles. It is safe to flush even those decoders that are not
- * marked with CODEC_CAP_DELAY, then no subtitles will be returned.
+ * marked with AV_CODEC_CAP_DELAY, then no subtitles will be returned.
*
* @note The AVCodecContext MUST have been opened with @ref avcodec_open2()
* before packets may be fed to the decoder.
@@ -4883,8 +5064,10 @@ int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
* a flush packet.
*
* @return 0 on success, otherwise negative error code:
- * AVERROR(EAGAIN): input is not accepted right now - the packet must be
- * resent after trying to read output
+ * AVERROR(EAGAIN): input is not accepted in the current state - user
+ * must read output with avcodec_receive_frame() (once
+ * all output is read, the packet should be resent, and
+ * the call will not fail with EAGAIN).
* AVERROR_EOF: the decoder has been flushed, and no new packets can
* be sent to it (also returned if more than 1 flush
* packet is sent)
@@ -4905,7 +5088,7 @@ int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt);
*
* @return
* 0: success, a frame was returned
- * AVERROR(EAGAIN): output is not available right now - user must try
+ * AVERROR(EAGAIN): output is not available in this state - user must try
* to send new input
* AVERROR_EOF: the decoder has been fully flushed, and there will be
* no more output frames
@@ -4938,8 +5121,10 @@ int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame);
* avctx->frame_size for all frames except the last.
* The final frame may be smaller than avctx->frame_size.
* @return 0 on success, otherwise negative error code:
- * AVERROR(EAGAIN): input is not accepted right now - the frame must be
- * resent after trying to read output packets
+ * AVERROR(EAGAIN): input is not accepted in the current state - user
+ * must read output with avcodec_receive_packet() (once
+ * all output is read, the packet should be resent, and
+ * the call will not fail with EAGAIN).
* AVERROR_EOF: the encoder has been flushed, and no new frames can
* be sent to it
* AVERROR(EINVAL): codec not opened, refcounted_frames not set, it is a
@@ -4957,8 +5142,8 @@ int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame);
* encoder. Note that the function will always call
* av_frame_unref(frame) before doing anything else.
* @return 0 on success, otherwise negative error code:
- * AVERROR(EAGAIN): output is not available right now - user must try
- * to send input
+ * AVERROR(EAGAIN): output is not available in the current state - user
+ * must try to send input
* AVERROR_EOF: the encoder has been fully flushed, and there will be
* no more output packets
* AVERROR(EINVAL): codec not opened, or it is an encoder
@@ -5509,22 +5694,14 @@ int av_picture_pad(AVPicture *dst, const AVPicture *src, int height, int width,
* @{
*/
+#if FF_API_GETCHROMA
/**
- * Utility function to access log2_chroma_w log2_chroma_h from
- * the pixel format AVPixFmtDescriptor.
- *
- * This function asserts that pix_fmt is valid. See av_pix_fmt_get_chroma_sub_sample
- * for one that returns a failure code and continues in case of invalid
- * pix_fmts.
- *
- * @param[in] pix_fmt the pixel format
- * @param[out] h_shift store log2_chroma_w
- * @param[out] v_shift store log2_chroma_h
- *
- * @see av_pix_fmt_get_chroma_sub_sample
+ * @deprecated Use av_pix_fmt_get_chroma_sub_sample
*/
+attribute_deprecated
void avcodec_get_chroma_sub_sample(enum AVPixelFormat pix_fmt, int *h_shift, int *v_shift);
+#endif
/**
* Return a value representing the fourCC code associated to the
@@ -5584,6 +5761,7 @@ attribute_deprecated
void avcodec_set_dimensions(AVCodecContext *s, int width, int height);
#endif
+#if FF_API_TAG_STRING
/**
* Put a string representing the codec tag codec_tag in buf.
*
@@ -5592,8 +5770,12 @@ void avcodec_set_dimensions(AVCodecContext *s, int width, int height);
* @param codec_tag codec tag to assign
* @return the length of the string that would have been generated if
* enough space had been available, excluding the trailing null
+ *
+ * @deprecated see av_fourcc_make_string() and av_fourcc2str().
*/
+attribute_deprecated
size_t av_get_codec_tag_string(char *buf, size_t buf_size, unsigned int codec_tag);
+#endif
void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode);
@@ -5706,7 +5888,7 @@ int av_get_audio_frame_duration2(AVCodecParameters *par, int frame_bytes);
#if FF_API_OLD_BSF
typedef struct AVBitStreamFilterContext {
void *priv_data;
- struct AVBitStreamFilter *filter;
+ const struct AVBitStreamFilter *filter;
AVCodecParserContext *parser;
struct AVBitStreamFilterContext *next;
/**
@@ -5753,12 +5935,15 @@ typedef struct AVBSFContext {
void *priv_data;
/**
- * Parameters of the input stream. Set by the caller before av_bsf_init().
+ * Parameters of the input stream. This field is allocated in
+ * av_bsf_alloc(), it needs to be filled by the caller before
+ * av_bsf_init().
*/
AVCodecParameters *par_in;
/**
- * Parameters of the output stream. Set by the filter in av_bsf_init().
+ * Parameters of the output stream. This field is allocated in
+ * av_bsf_alloc(), it is set by the filter in av_bsf_init().
*/
AVCodecParameters *par_out;
@@ -5936,8 +6121,7 @@ int av_bsf_init(AVBSFContext *ctx);
* av_bsf_receive_packet() repeatedly until it returns AVERROR(EAGAIN) or
* AVERROR_EOF.
*
- * @param pkt the packet to filter. pkt must contain some payload (i.e data or
- * side data must be present in pkt). The bitstream filter will take ownership of
+ * @param pkt the packet to filter. The bitstream filter will take ownership of
* the packet and reset the contents of pkt. pkt is not touched if an error occurs.
* This parameter may be NULL, which signals the end of the stream (i.e. no more
* packets will be sent). That will cause the filter to output any packets it
diff --git a/media/ffvpx/libavcodec/avdct.h b/media/ffvpx/libavcodec/avdct.h
deleted file mode 100644
index 272422e44..000000000
--- a/media/ffvpx/libavcodec/avdct.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVCODEC_AVDCT_H
-#define AVCODEC_AVDCT_H
-
-#include "libavutil/opt.h"
-
-/**
- * AVDCT context.
- * @note function pointers can be NULL if the specific features have been
- * disabled at build time.
- */
-typedef struct AVDCT {
- const AVClass *av_class;
-
- void (*idct)(int16_t *block /* align 16 */);
-
- /**
- * IDCT input permutation.
- * Several optimized IDCTs need a permutated input (relative to the
- * normal order of the reference IDCT).
- * This permutation must be performed before the idct_put/add.
- * Note, normally this can be merged with the zigzag/alternate scan<br>
- * An example to avoid confusion:
- * - (->decode coeffs -> zigzag reorder -> dequant -> reference IDCT -> ...)
- * - (x -> reference DCT -> reference IDCT -> x)
- * - (x -> reference DCT -> simple_mmx_perm = idct_permutation
- * -> simple_idct_mmx -> x)
- * - (-> decode coeffs -> zigzag reorder -> simple_mmx_perm -> dequant
- * -> simple_idct_mmx -> ...)
- */
- uint8_t idct_permutation[64];
-
- void (*fdct)(int16_t *block /* align 16 */);
-
-
- /**
- * DCT algorithm.
- * must use AVOptions to set this field.
- */
- int dct_algo;
-
- /**
- * IDCT algorithm.
- * must use AVOptions to set this field.
- */
- int idct_algo;
-
- void (*get_pixels)(int16_t *block /* align 16 */,
- const uint8_t *pixels /* align 8 */,
- ptrdiff_t line_size);
-
- int bits_per_sample;
-} AVDCT;
-
-/**
- * Allocates a AVDCT context.
- * This needs to be initialized with avcodec_dct_init() after optionally
- * configuring it with AVOptions.
- *
- * To free it use av_free()
- */
-AVDCT *avcodec_dct_alloc(void);
-int avcodec_dct_init(AVDCT *);
-
-const AVClass *avcodec_dct_get_class(void);
-
-#endif /* AVCODEC_AVDCT_H */
diff --git a/media/ffvpx/libavcodec/avpacket.c b/media/ffvpx/libavcodec/avpacket.c
index e5a8bdbe4..d1f4ea9eb 100644
--- a/media/ffvpx/libavcodec/avpacket.c
+++ b/media/ffvpx/libavcodec/avpacket.c
@@ -247,8 +247,6 @@ failed_alloc:
av_packet_unref(pkt);
return AVERROR(ENOMEM);
}
-FF_ENABLE_DEPRECATION_WARNINGS
-#endif
int av_dup_packet(AVPacket *pkt)
{
@@ -266,6 +264,8 @@ int av_copy_packet(AVPacket *dst, const AVPacket *src)
*dst = *src;
return copy_packet_data(dst, src, 0);
}
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
void av_packet_free_side_data(AVPacket *pkt)
{
@@ -296,9 +296,20 @@ int av_packet_add_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
uint8_t *data, size_t size)
{
AVPacketSideData *tmp;
- int elems = pkt->side_data_elems;
+ int i, elems = pkt->side_data_elems;
+
+ for (i = 0; i < elems; i++) {
+ AVPacketSideData *sd = &pkt->side_data[i];
+
+ if (sd->type == type) {
+ av_free(sd->data);
+ sd->data = data;
+ sd->size = size;
+ return 0;
+ }
+ }
- if ((unsigned)elems + 1 > INT_MAX / sizeof(*pkt->side_data))
+ if ((unsigned)elems + 1 > AV_PKT_DATA_NB)
return AVERROR(ERANGE);
tmp = av_realloc(pkt->side_data, (elems + 1) * sizeof(*tmp));
@@ -336,7 +347,7 @@ uint8_t *av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
return data;
}
-uint8_t *av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
+uint8_t *av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type,
int *size)
{
int i;
@@ -348,6 +359,8 @@ uint8_t *av_packet_get_side_data(AVPacket *pkt, enum AVPacketSideDataType type,
return pkt->side_data[i].data;
}
}
+ if (size)
+ *size = 0;
return NULL;
}
@@ -372,10 +385,15 @@ const char *av_packet_side_data_name(enum AVPacketSideDataType type)
case AV_PKT_DATA_METADATA_UPDATE: return "Metadata Update";
case AV_PKT_DATA_MPEGTS_STREAM_ID: return "MPEGTS Stream ID";
case AV_PKT_DATA_MASTERING_DISPLAY_METADATA: return "Mastering display metadata";
+ case AV_PKT_DATA_CONTENT_LIGHT_LEVEL: return "Content light level metadata";
+ case AV_PKT_DATA_SPHERICAL: return "Spherical Mapping";
+ case AV_PKT_DATA_A53_CC: return "A53 Closed Captions";
}
return NULL;
}
+#if FF_API_MERGE_SD_API
+
#define FF_MERGE_MARKER 0x8c4d9d108e25e9feULL
int av_packet_merge_side_data(AVPacket *pkt){
@@ -431,6 +449,9 @@ int av_packet_split_side_data(AVPacket *pkt){
p-= size+5;
}
+ if (i > AV_PKT_DATA_NB)
+ return AVERROR(ERANGE);
+
pkt->side_data = av_malloc_array(i, sizeof(*pkt->side_data));
if (!pkt->side_data)
return AVERROR(ENOMEM);
@@ -456,6 +477,35 @@ int av_packet_split_side_data(AVPacket *pkt){
}
return 0;
}
+#endif
+
+#if FF_API_MERGE_SD
+int ff_packet_split_and_drop_side_data(AVPacket *pkt){
+ if (!pkt->side_data_elems && pkt->size >12 && AV_RB64(pkt->data + pkt->size - 8) == FF_MERGE_MARKER){
+ int i;
+ unsigned int size;
+ uint8_t *p;
+
+ p = pkt->data + pkt->size - 8 - 5;
+ for (i=1; ; i++){
+ size = AV_RB32(p);
+ if (size>INT_MAX - 5 || p - pkt->data < size)
+ return 0;
+ if (p[4]&128)
+ break;
+ if (p - pkt->data < size + 5)
+ return 0;
+ p-= size+5;
+ if (i > AV_PKT_DATA_NB)
+ return 0;
+ }
+ pkt->size = p - pkt->data - size;
+ av_assert0(pkt->size >= 0);
+ return 1;
+ }
+ return 0;
+}
+#endif
uint8_t *av_packet_pack_dictionary(AVDictionary *dict, int *size)
{
@@ -505,7 +555,7 @@ int av_packet_unpack_dictionary(const uint8_t *data, int size, AVDictionary **di
const uint8_t *key = data;
const uint8_t *val = data + strlen(key) + 1;
- if (val >= end)
+ if (val >= end || !*key)
return AVERROR_INVALIDDATA;
ret = av_dict_set(dict, key, val, 0);
@@ -607,7 +657,7 @@ fail:
return ret;
}
-AVPacket *av_packet_clone(AVPacket *src)
+AVPacket *av_packet_clone(const AVPacket *src)
{
AVPacket *ret = av_packet_alloc();
diff --git a/media/ffvpx/libavcodec/bitstream.c b/media/ffvpx/libavcodec/bitstream.c
index 562ca1cb8..ed528fe4a 100644
--- a/media/ffvpx/libavcodec/bitstream.c
+++ b/media/ffvpx/libavcodec/bitstream.c
@@ -28,7 +28,6 @@
* bitstream api.
*/
-#include "libavutil/atomic.h"
#include "libavutil/avassert.h"
#include "libavutil/qsort.h"
#include "avcodec.h"
@@ -99,9 +98,11 @@ void avpriv_copy_bits(PutBitContext *pb, const uint8_t *src, int length)
case 2: \
v = *(const uint16_t *)ptr; \
break; \
- default: \
+ case 4: \
v = *(const uint32_t *)ptr; \
break; \
+ default: \
+ av_assert1(0); \
} \
}
@@ -126,14 +127,6 @@ static int alloc_table(VLC *vlc, int size, int use_static)
return index;
}
-static av_always_inline uint32_t bitswap_32(uint32_t x)
-{
- return (uint32_t)ff_reverse[ x & 0xFF] << 24 |
- (uint32_t)ff_reverse[(x >> 8) & 0xFF] << 16 |
- (uint32_t)ff_reverse[(x >> 16) & 0xFF] << 8 |
- (uint32_t)ff_reverse[ x >> 24];
-}
-
typedef struct VLCcode {
uint8_t bits;
uint16_t symbol;
@@ -183,7 +176,7 @@ static int build_table(VLC *vlc, int table_nb_bits, int nb_codes,
n = codes[i].bits;
code = codes[i].code;
symbol = codes[i].symbol;
- ff_dlog(NULL, "i=%d n=%d code=0x%x\n", i, n, code);
+ ff_dlog(NULL, "i=%d n=%d code=0x%"PRIx32"\n", i, n, code);
if (n <= table_nb_bits) {
/* no need to add another table */
j = code >> (32 - table_nb_bits);
@@ -264,7 +257,7 @@ static int build_table(VLC *vlc, int table_nb_bits, int nb_codes,
'bits' or 'codes' tables.
'xxx_size' : gives the number of bytes of each entry of the 'bits'
- or 'codes' tables.
+ or 'codes' tables. Currently 1,2 and 4 are supported.
'wrap' and 'size' make it possible to use any memory configuration and types
(byte/word/long) to store the 'bits', 'codes', and 'symbols' tables.
@@ -317,7 +310,8 @@ int ff_init_vlc_sparse(VLC *vlc_arg, int nb_bits, int nb_codes,
} \
GET_DATA(buf[j].code, codes, i, codes_wrap, codes_size); \
if (buf[j].code >= (1LL<<buf[j].bits)) { \
- av_log(NULL, AV_LOG_ERROR, "Invalid code %x for %d in init_vlc\n", buf[j].code, i);\
+ av_log(NULL, AV_LOG_ERROR, "Invalid code %"PRIx32" for %d in " \
+ "init_vlc\n", buf[j].code, i); \
if (!(flags & INIT_VLC_USE_NEW_STATIC)) \
av_free(buf); \
return -1; \
diff --git a/media/ffvpx/libavcodec/bitstream_filter.c b/media/ffvpx/libavcodec/bitstream_filter.c
new file mode 100644
index 000000000..8599b90d4
--- /dev/null
+++ b/media/ffvpx/libavcodec/bitstream_filter.c
@@ -0,0 +1,185 @@
+/*
+ * copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <string.h>
+
+#include "avcodec.h"
+#include "libavutil/internal.h"
+#include "libavutil/mem.h"
+#include "libavutil/opt.h"
+
+#if FF_API_OLD_BSF
+FF_DISABLE_DEPRECATION_WARNINGS
+
+AVBitStreamFilter *av_bitstream_filter_next(const AVBitStreamFilter *f)
+{
+ const AVBitStreamFilter *filter = NULL;
+ void *opaque = NULL;
+
+ while (filter != f)
+ filter = av_bsf_next(&opaque);
+
+ return av_bsf_next(&opaque);
+}
+
+void av_register_bitstream_filter(AVBitStreamFilter *bsf)
+{
+}
+
+typedef struct BSFCompatContext {
+ AVBSFContext *ctx;
+ int extradata_updated;
+} BSFCompatContext;
+
+AVBitStreamFilterContext *av_bitstream_filter_init(const char *name)
+{
+ AVBitStreamFilterContext *ctx = NULL;
+ BSFCompatContext *priv = NULL;
+ const AVBitStreamFilter *bsf;
+
+ bsf = av_bsf_get_by_name(name);
+ if (!bsf)
+ return NULL;
+
+ ctx = av_mallocz(sizeof(*ctx));
+ if (!ctx)
+ return NULL;
+
+ priv = av_mallocz(sizeof(*priv));
+ if (!priv)
+ goto fail;
+
+
+ ctx->filter = bsf;
+ ctx->priv_data = priv;
+
+ return ctx;
+
+fail:
+ if (priv)
+ av_bsf_free(&priv->ctx);
+ av_freep(&priv);
+ av_freep(&ctx);
+ return NULL;
+}
+
+void av_bitstream_filter_close(AVBitStreamFilterContext *bsfc)
+{
+ BSFCompatContext *priv;
+
+ if (!bsfc)
+ return;
+
+ priv = bsfc->priv_data;
+
+ av_bsf_free(&priv->ctx);
+ av_freep(&bsfc->priv_data);
+ av_free(bsfc);
+}
+
+int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc,
+ AVCodecContext *avctx, const char *args,
+ uint8_t **poutbuf, int *poutbuf_size,
+ const uint8_t *buf, int buf_size, int keyframe)
+{
+ BSFCompatContext *priv = bsfc->priv_data;
+ AVPacket pkt = { 0 };
+ int ret;
+
+ if (!priv->ctx) {
+ ret = av_bsf_alloc(bsfc->filter, &priv->ctx);
+ if (ret < 0)
+ return ret;
+
+ ret = avcodec_parameters_from_context(priv->ctx->par_in, avctx);
+ if (ret < 0)
+ return ret;
+
+ priv->ctx->time_base_in = avctx->time_base;
+
+ if (bsfc->args && bsfc->filter->priv_class) {
+ const AVOption *opt = av_opt_next(priv->ctx->priv_data, NULL);
+ const char * shorthand[2] = {NULL};
+
+ if (opt)
+ shorthand[0] = opt->name;
+
+ ret = av_opt_set_from_string(priv->ctx->priv_data, bsfc->args, shorthand, "=", ":");
+ if (ret < 0)
+ return ret;
+ }
+
+ ret = av_bsf_init(priv->ctx);
+ if (ret < 0)
+ return ret;
+ }
+
+ pkt.data = buf;
+ pkt.size = buf_size;
+
+ ret = av_bsf_send_packet(priv->ctx, &pkt);
+ if (ret < 0)
+ return ret;
+
+ *poutbuf = NULL;
+ *poutbuf_size = 0;
+
+ ret = av_bsf_receive_packet(priv->ctx, &pkt);
+ if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
+ return 0;
+ else if (ret < 0)
+ return ret;
+
+ *poutbuf = av_malloc(pkt.size + AV_INPUT_BUFFER_PADDING_SIZE);
+ if (!*poutbuf) {
+ av_packet_unref(&pkt);
+ return AVERROR(ENOMEM);
+ }
+
+ *poutbuf_size = pkt.size;
+ memcpy(*poutbuf, pkt.data, pkt.size);
+
+ av_packet_unref(&pkt);
+
+ /* drain all the remaining packets we cannot return */
+ while (ret >= 0) {
+ ret = av_bsf_receive_packet(priv->ctx, &pkt);
+ av_packet_unref(&pkt);
+ }
+
+ if (!priv->extradata_updated) {
+ /* update extradata in avctx from the output codec parameters */
+ if (priv->ctx->par_out->extradata_size && (!args || !strstr(args, "private_spspps_buf"))) {
+ av_freep(&avctx->extradata);
+ avctx->extradata_size = 0;
+ avctx->extradata = av_mallocz(priv->ctx->par_out->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
+ if (!avctx->extradata)
+ return AVERROR(ENOMEM);
+ memcpy(avctx->extradata, priv->ctx->par_out->extradata, priv->ctx->par_out->extradata_size);
+ avctx->extradata_size = priv->ctx->par_out->extradata_size;
+ }
+
+ priv->extradata_updated = 1;
+ }
+
+ return 1;
+}
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
diff --git a/media/ffvpx/libavcodec/bitstream_filters.c b/media/ffvpx/libavcodec/bitstream_filters.c
new file mode 100644
index 000000000..ce34de640
--- /dev/null
+++ b/media/ffvpx/libavcodec/bitstream_filters.c
@@ -0,0 +1,91 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config.h"
+
+#include "libavutil/common.h"
+#include "libavutil/log.h"
+
+#include "avcodec.h"
+#include "bsf.h"
+
+extern const AVBitStreamFilter ff_aac_adtstoasc_bsf;
+extern const AVBitStreamFilter ff_chomp_bsf;
+extern const AVBitStreamFilter ff_dump_extradata_bsf;
+extern const AVBitStreamFilter ff_dca_core_bsf;
+extern const AVBitStreamFilter ff_extract_extradata_bsf;
+extern const AVBitStreamFilter ff_h264_mp4toannexb_bsf;
+extern const AVBitStreamFilter ff_hevc_mp4toannexb_bsf;
+extern const AVBitStreamFilter ff_imx_dump_header_bsf;
+extern const AVBitStreamFilter ff_mjpeg2jpeg_bsf;
+extern const AVBitStreamFilter ff_mjpega_dump_header_bsf;
+extern const AVBitStreamFilter ff_mp3_header_decompress_bsf;
+extern const AVBitStreamFilter ff_mpeg4_unpack_bframes_bsf;
+extern const AVBitStreamFilter ff_mov2textsub_bsf;
+extern const AVBitStreamFilter ff_noise_bsf;
+extern const AVBitStreamFilter ff_null_bsf;
+extern const AVBitStreamFilter ff_remove_extradata_bsf;
+extern const AVBitStreamFilter ff_text2movsub_bsf;
+extern const AVBitStreamFilter ff_vp9_raw_reorder_bsf;
+extern const AVBitStreamFilter ff_vp9_superframe_bsf;
+extern const AVBitStreamFilter ff_vp9_superframe_split_bsf;
+
+#include "libavcodec/bsf_list.c"
+
+const AVBitStreamFilter *av_bsf_next(void **opaque)
+{
+ uintptr_t i = (uintptr_t)*opaque;
+ const AVBitStreamFilter *f = bitstream_filters[i];
+
+ if (f)
+ *opaque = (void*)(i + 1);
+
+ return f;
+}
+
+const AVBitStreamFilter *av_bsf_get_by_name(const char *name)
+{
+ int i;
+
+ for (i = 0; bitstream_filters[i]; i++) {
+ const AVBitStreamFilter *f = bitstream_filters[i];
+ if (!strcmp(f->name, name))
+ return f;
+ }
+
+ return NULL;
+}
+
+const AVClass *ff_bsf_child_class_next(const AVClass *prev)
+{
+ int i;
+
+ /* find the filter that corresponds to prev */
+ for (i = 0; prev && bitstream_filters[i]; i++) {
+ if (bitstream_filters[i]->priv_class == prev) {
+ i++;
+ break;
+ }
+ }
+
+ /* find next filter with priv options */
+ for (; bitstream_filters[i]; i++)
+ if (bitstream_filters[i]->priv_class)
+ return bitstream_filters[i]->priv_class;
+ return NULL;
+}
diff --git a/media/ffvpx/libavcodec/blockdsp.h b/media/ffvpx/libavcodec/blockdsp.h
index 95e1d0f32..6e27a02ba 100644
--- a/media/ffvpx/libavcodec/blockdsp.h
+++ b/media/ffvpx/libavcodec/blockdsp.h
@@ -19,6 +19,7 @@
#ifndef AVCODEC_BLOCKDSP_H
#define AVCODEC_BLOCKDSP_H
+#include <stddef.h>
#include <stdint.h>
#include "avcodec.h"
@@ -29,7 +30,7 @@
* h for op_pixels_func is limited to { width / 2, width },
* but never larger than 16 and never smaller than 4. */
typedef void (*op_fill_func)(uint8_t *block /* align width (8 or 16) */,
- uint8_t value, int line_size, int h);
+ uint8_t value, ptrdiff_t line_size, int h);
typedef struct BlockDSPContext {
void (*clear_block)(int16_t *block /* align 16 */);
diff --git a/media/ffvpx/libavcodec/bsf.c b/media/ffvpx/libavcodec/bsf.c
new file mode 100644
index 000000000..38b423101
--- /dev/null
+++ b/media/ffvpx/libavcodec/bsf.c
@@ -0,0 +1,542 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <string.h>
+
+#include "libavutil/log.h"
+#include "libavutil/mem.h"
+#include "libavutil/opt.h"
+#include "libavutil/avstring.h"
+#include "libavutil/bprint.h"
+
+#include "avcodec.h"
+#include "bsf.h"
+
+struct AVBSFInternal {
+ AVPacket *buffer_pkt;
+ int eof;
+};
+
+void av_bsf_free(AVBSFContext **pctx)
+{
+ AVBSFContext *ctx;
+
+ if (!pctx || !*pctx)
+ return;
+ ctx = *pctx;
+
+ if (ctx->filter->close)
+ ctx->filter->close(ctx);
+ if (ctx->filter->priv_class && ctx->priv_data)
+ av_opt_free(ctx->priv_data);
+
+ av_opt_free(ctx);
+
+ av_packet_free(&ctx->internal->buffer_pkt);
+ av_freep(&ctx->internal);
+ av_freep(&ctx->priv_data);
+
+ avcodec_parameters_free(&ctx->par_in);
+ avcodec_parameters_free(&ctx->par_out);
+
+ av_freep(pctx);
+}
+
+static void *bsf_child_next(void *obj, void *prev)
+{
+ AVBSFContext *ctx = obj;
+ if (!prev && ctx->filter->priv_class)
+ return ctx->priv_data;
+ return NULL;
+}
+
+static const AVClass bsf_class = {
+ .class_name = "AVBSFContext",
+ .item_name = av_default_item_name,
+ .version = LIBAVUTIL_VERSION_INT,
+ .child_next = bsf_child_next,
+ .child_class_next = ff_bsf_child_class_next,
+};
+
+const AVClass *av_bsf_get_class(void)
+{
+ return &bsf_class;
+}
+
+int av_bsf_alloc(const AVBitStreamFilter *filter, AVBSFContext **pctx)
+{
+ AVBSFContext *ctx;
+ int ret;
+
+ ctx = av_mallocz(sizeof(*ctx));
+ if (!ctx)
+ return AVERROR(ENOMEM);
+
+ ctx->av_class = &bsf_class;
+ ctx->filter = filter;
+
+ ctx->par_in = avcodec_parameters_alloc();
+ ctx->par_out = avcodec_parameters_alloc();
+ if (!ctx->par_in || !ctx->par_out) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+
+ ctx->internal = av_mallocz(sizeof(*ctx->internal));
+ if (!ctx->internal) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+
+ ctx->internal->buffer_pkt = av_packet_alloc();
+ if (!ctx->internal->buffer_pkt) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+
+ av_opt_set_defaults(ctx);
+
+ /* allocate priv data and init private options */
+ if (filter->priv_data_size) {
+ ctx->priv_data = av_mallocz(filter->priv_data_size);
+ if (!ctx->priv_data) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ if (filter->priv_class) {
+ *(const AVClass **)ctx->priv_data = filter->priv_class;
+ av_opt_set_defaults(ctx->priv_data);
+ }
+ }
+
+ *pctx = ctx;
+ return 0;
+fail:
+ av_bsf_free(&ctx);
+ return ret;
+}
+
+int av_bsf_init(AVBSFContext *ctx)
+{
+ int ret, i;
+
+ /* check that the codec is supported */
+ if (ctx->filter->codec_ids) {
+ for (i = 0; ctx->filter->codec_ids[i] != AV_CODEC_ID_NONE; i++)
+ if (ctx->par_in->codec_id == ctx->filter->codec_ids[i])
+ break;
+ if (ctx->filter->codec_ids[i] == AV_CODEC_ID_NONE) {
+ const AVCodecDescriptor *desc = avcodec_descriptor_get(ctx->par_in->codec_id);
+ av_log(ctx, AV_LOG_ERROR, "Codec '%s' (%d) is not supported by the "
+ "bitstream filter '%s'. Supported codecs are: ",
+ desc ? desc->name : "unknown", ctx->par_in->codec_id, ctx->filter->name);
+ for (i = 0; ctx->filter->codec_ids[i] != AV_CODEC_ID_NONE; i++) {
+ desc = avcodec_descriptor_get(ctx->filter->codec_ids[i]);
+ av_log(ctx, AV_LOG_ERROR, "%s (%d) ",
+ desc ? desc->name : "unknown", ctx->filter->codec_ids[i]);
+ }
+ av_log(ctx, AV_LOG_ERROR, "\n");
+ return AVERROR(EINVAL);
+ }
+ }
+
+ /* initialize output parameters to be the same as input
+ * init below might overwrite that */
+ ret = avcodec_parameters_copy(ctx->par_out, ctx->par_in);
+ if (ret < 0)
+ return ret;
+
+ ctx->time_base_out = ctx->time_base_in;
+
+ if (ctx->filter->init) {
+ ret = ctx->filter->init(ctx);
+ if (ret < 0)
+ return ret;
+ }
+
+ return 0;
+}
+
+int av_bsf_send_packet(AVBSFContext *ctx, AVPacket *pkt)
+{
+ if (!pkt || (!pkt->data && !pkt->side_data_elems)) {
+ ctx->internal->eof = 1;
+ return 0;
+ }
+
+ if (ctx->internal->eof) {
+ av_log(ctx, AV_LOG_ERROR, "A non-NULL packet sent after an EOF.\n");
+ return AVERROR(EINVAL);
+ }
+
+ if (ctx->internal->buffer_pkt->data ||
+ ctx->internal->buffer_pkt->side_data_elems)
+ return AVERROR(EAGAIN);
+
+ av_packet_move_ref(ctx->internal->buffer_pkt, pkt);
+
+ return 0;
+}
+
+int av_bsf_receive_packet(AVBSFContext *ctx, AVPacket *pkt)
+{
+ return ctx->filter->filter(ctx, pkt);
+}
+
+int ff_bsf_get_packet(AVBSFContext *ctx, AVPacket **pkt)
+{
+ AVBSFInternal *in = ctx->internal;
+ AVPacket *tmp_pkt;
+
+ if (in->eof)
+ return AVERROR_EOF;
+
+ if (!ctx->internal->buffer_pkt->data &&
+ !ctx->internal->buffer_pkt->side_data_elems)
+ return AVERROR(EAGAIN);
+
+ tmp_pkt = av_packet_alloc();
+ if (!tmp_pkt)
+ return AVERROR(ENOMEM);
+
+ *pkt = ctx->internal->buffer_pkt;
+ ctx->internal->buffer_pkt = tmp_pkt;
+
+ return 0;
+}
+
+int ff_bsf_get_packet_ref(AVBSFContext *ctx, AVPacket *pkt)
+{
+ AVBSFInternal *in = ctx->internal;
+
+ if (in->eof)
+ return AVERROR_EOF;
+
+ if (!ctx->internal->buffer_pkt->data &&
+ !ctx->internal->buffer_pkt->side_data_elems)
+ return AVERROR(EAGAIN);
+
+ av_packet_move_ref(pkt, ctx->internal->buffer_pkt);
+
+ return 0;
+}
+
+typedef struct BSFListContext {
+ const AVClass *class;
+
+ AVBSFContext **bsfs;
+ int nb_bsfs;
+
+ unsigned idx; // index of currently processed BSF
+ unsigned flushed_idx; // index of BSF being flushed
+
+ char * item_name;
+} BSFListContext;
+
+
+static int bsf_list_init(AVBSFContext *bsf)
+{
+ BSFListContext *lst = bsf->priv_data;
+ int ret, i;
+ const AVCodecParameters *cod_par = bsf->par_in;
+ AVRational tb = bsf->time_base_in;
+
+ for (i = 0; i < lst->nb_bsfs; ++i) {
+ ret = avcodec_parameters_copy(lst->bsfs[i]->par_in, cod_par);
+ if (ret < 0)
+ goto fail;
+
+ lst->bsfs[i]->time_base_in = tb;
+
+ ret = av_bsf_init(lst->bsfs[i]);
+ if (ret < 0)
+ goto fail;
+
+ cod_par = lst->bsfs[i]->par_out;
+ tb = lst->bsfs[i]->time_base_out;
+ }
+
+ bsf->time_base_out = tb;
+ ret = avcodec_parameters_copy(bsf->par_out, cod_par);
+
+fail:
+ return ret;
+}
+
+static int bsf_list_filter(AVBSFContext *bsf, AVPacket *out)
+{
+ BSFListContext *lst = bsf->priv_data;
+ int ret;
+
+ if (!lst->nb_bsfs)
+ return ff_bsf_get_packet_ref(bsf, out);
+
+ while (1) {
+ if (lst->idx > lst->flushed_idx) {
+ ret = av_bsf_receive_packet(lst->bsfs[lst->idx-1], out);
+ if (ret == AVERROR(EAGAIN)) {
+ /* no more packets from idx-1, try with previous */
+ ret = 0;
+ lst->idx--;
+ continue;
+ } else if (ret == AVERROR_EOF) {
+ /* filter idx-1 is done, continue with idx...nb_bsfs */
+ lst->flushed_idx = lst->idx;
+ continue;
+ }else if (ret < 0) {
+ /* filtering error */
+ break;
+ }
+ } else {
+ ret = ff_bsf_get_packet_ref(bsf, out);
+ if (ret == AVERROR_EOF) {
+ lst->idx = lst->flushed_idx;
+ } else if (ret < 0)
+ break;
+ }
+
+ if (lst->idx < lst->nb_bsfs) {
+ AVPacket *pkt;
+ if (ret == AVERROR_EOF && lst->idx == lst->flushed_idx) {
+ /* ff_bsf_get_packet_ref returned EOF and idx is first
+ * filter of yet not flushed filter chain */
+ pkt = NULL;
+ } else {
+ pkt = out;
+ }
+ ret = av_bsf_send_packet(lst->bsfs[lst->idx], pkt);
+ if (ret < 0)
+ break;
+ lst->idx++;
+ } else {
+ /* The end of filter chain, break to return result */
+ break;
+ }
+ }
+
+ if (ret < 0)
+ av_packet_unref(out);
+
+ return ret;
+}
+
+static void bsf_list_close(AVBSFContext *bsf)
+{
+ BSFListContext *lst = bsf->priv_data;
+ int i;
+
+ for (i = 0; i < lst->nb_bsfs; ++i)
+ av_bsf_free(&lst->bsfs[i]);
+ av_freep(&lst->bsfs);
+ av_freep(&lst->item_name);
+}
+
+static const char *bsf_list_item_name(void *ctx)
+{
+ static const char *null_filter_name = "null";
+ AVBSFContext *bsf_ctx = ctx;
+ BSFListContext *lst = bsf_ctx->priv_data;
+
+ if (!lst->nb_bsfs)
+ return null_filter_name;
+
+ if (!lst->item_name) {
+ int i;
+ AVBPrint bp;
+ av_bprint_init(&bp, 16, 128);
+
+ av_bprintf(&bp, "bsf_list(");
+ for (i = 0; i < lst->nb_bsfs; i++)
+ av_bprintf(&bp, i ? ",%s" : "%s", lst->bsfs[i]->filter->name);
+ av_bprintf(&bp, ")");
+
+ av_bprint_finalize(&bp, &lst->item_name);
+ }
+
+ return lst->item_name;
+}
+
+static const AVClass bsf_list_class = {
+ .class_name = "bsf_list",
+ .item_name = bsf_list_item_name,
+ .version = LIBAVUTIL_VERSION_INT,
+};
+
+const AVBitStreamFilter ff_list_bsf = {
+ .name = "bsf_list",
+ .priv_data_size = sizeof(BSFListContext),
+ .priv_class = &bsf_list_class,
+ .init = bsf_list_init,
+ .filter = bsf_list_filter,
+ .close = bsf_list_close,
+};
+
+struct AVBSFList {
+ AVBSFContext **bsfs;
+ int nb_bsfs;
+};
+
+AVBSFList *av_bsf_list_alloc(void)
+{
+ return av_mallocz(sizeof(AVBSFList));
+}
+
+void av_bsf_list_free(AVBSFList **lst)
+{
+ int i;
+
+ if (!*lst)
+ return;
+
+ for (i = 0; i < (*lst)->nb_bsfs; ++i)
+ av_bsf_free(&(*lst)->bsfs[i]);
+ av_free((*lst)->bsfs);
+ av_freep(lst);
+}
+
+int av_bsf_list_append(AVBSFList *lst, AVBSFContext *bsf)
+{
+ return av_dynarray_add_nofree(&lst->bsfs, &lst->nb_bsfs, bsf);
+}
+
+int av_bsf_list_append2(AVBSFList *lst, const char *bsf_name, AVDictionary ** options)
+{
+ int ret;
+ const AVBitStreamFilter *filter;
+ AVBSFContext *bsf;
+
+ filter = av_bsf_get_by_name(bsf_name);
+ if (!filter)
+ return AVERROR_BSF_NOT_FOUND;
+
+ ret = av_bsf_alloc(filter, &bsf);
+ if (ret < 0)
+ return ret;
+
+ if (options) {
+ ret = av_opt_set_dict2(bsf, options, AV_OPT_SEARCH_CHILDREN);
+ if (ret < 0)
+ goto end;
+ }
+
+ ret = av_bsf_list_append(lst, bsf);
+
+end:
+ if (ret < 0)
+ av_bsf_free(&bsf);
+
+ return ret;
+}
+
+int av_bsf_list_finalize(AVBSFList **lst, AVBSFContext **bsf)
+{
+ int ret = 0;
+ BSFListContext *ctx;
+
+ if ((*lst)->nb_bsfs == 1) {
+ *bsf = (*lst)->bsfs[0];
+ av_freep(&(*lst)->bsfs);
+ (*lst)->nb_bsfs = 0;
+ goto end;
+ }
+
+ ret = av_bsf_alloc(&ff_list_bsf, bsf);
+ if (ret < 0)
+ return ret;
+
+ ctx = (*bsf)->priv_data;
+
+ ctx->bsfs = (*lst)->bsfs;
+ ctx->nb_bsfs = (*lst)->nb_bsfs;
+
+end:
+ av_freep(lst);
+ return ret;
+}
+
+static int bsf_parse_single(const char *str, AVBSFList *bsf_lst)
+{
+ char *bsf_name, *bsf_options_str, *buf;
+ AVDictionary *bsf_options = NULL;
+ int ret = 0;
+
+ if (!(buf = av_strdup(str)))
+ return AVERROR(ENOMEM);
+
+ bsf_name = av_strtok(buf, "=", &bsf_options_str);
+ if (!bsf_name) {
+ ret = AVERROR(EINVAL);
+ goto end;
+ }
+
+ if (bsf_options_str) {
+ ret = av_dict_parse_string(&bsf_options, bsf_options_str, "=", ":", 0);
+ if (ret < 0)
+ goto end;
+ }
+
+ ret = av_bsf_list_append2(bsf_lst, bsf_name, &bsf_options);
+
+ av_dict_free(&bsf_options);
+end:
+ av_free(buf);
+ return ret;
+}
+
+int av_bsf_list_parse_str(const char *str, AVBSFContext **bsf_lst)
+{
+ AVBSFList *lst;
+ char *bsf_str, *buf, *dup, *saveptr;
+ int ret;
+
+ if (!str)
+ return av_bsf_get_null_filter(bsf_lst);
+
+ lst = av_bsf_list_alloc();
+ if (!lst)
+ return AVERROR(ENOMEM);
+
+ if (!(dup = buf = av_strdup(str))) {
+ ret = AVERROR(ENOMEM);
+ goto end;
+ }
+
+ while (1) {
+ bsf_str = av_strtok(buf, ",", &saveptr);
+ if (!bsf_str)
+ break;
+
+ ret = bsf_parse_single(bsf_str, lst);
+ if (ret < 0)
+ goto end;
+
+ buf = NULL;
+ }
+
+ ret = av_bsf_list_finalize(&lst, bsf_lst);
+end:
+ if (ret < 0)
+ av_bsf_list_free(&lst);
+ av_free(dup);
+ return ret;
+}
+
+int av_bsf_get_null_filter(AVBSFContext **bsf)
+{
+ return av_bsf_alloc(&ff_list_bsf, bsf);
+}
diff --git a/media/ffvpx/libavcodec/bsf_list.c b/media/ffvpx/libavcodec/bsf_list.c
new file mode 100644
index 000000000..d31ece942
--- /dev/null
+++ b/media/ffvpx/libavcodec/bsf_list.c
@@ -0,0 +1,3 @@
+static const AVBitStreamFilter * const bitstream_filters[] = {
+ &ff_null_bsf,
+ NULL };
diff --git a/media/ffvpx/libavcodec/bytestream.h b/media/ffvpx/libavcodec/bytestream.h
index 7c05ea6cf..7be7fc22f 100644
--- a/media/ffvpx/libavcodec/bytestream.h
+++ b/media/ffvpx/libavcodec/bytestream.h
@@ -94,7 +94,7 @@ DEF(unsigned int, be24, 3, AV_RB24, AV_WB24)
DEF(unsigned int, be16, 2, AV_RB16, AV_WB16)
DEF(unsigned int, byte, 1, AV_RB8 , AV_WB8)
-#if HAVE_BIGENDIAN
+#if AV_HAVE_BIGENDIAN
# define bytestream2_get_ne16 bytestream2_get_be16
# define bytestream2_get_ne24 bytestream2_get_be24
# define bytestream2_get_ne32 bytestream2_get_be32
diff --git a/media/ffvpx/libavcodec/codec_desc.c b/media/ffvpx/libavcodec/codec_desc.c
index d862cc8f6..6a13bbbf0 100644
--- a/media/ffvpx/libavcodec/codec_desc.c
+++ b/media/ffvpx/libavcodec/codec_desc.c
@@ -170,6 +170,14 @@ static const AVCodecDescriptor codec_descriptors[] = {
.props = AV_CODEC_PROP_LOSSY,
},
{
+ .id = AV_CODEC_ID_SVG,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "svg",
+ .long_name = NULL_IF_CONFIG_SMALL("Scalable Vector Graphics"),
+ .props = AV_CODEC_PROP_LOSSLESS,
+ .mime_types= MT("image/svg+xml"),
+ },
+ {
.id = AV_CODEC_ID_SVQ1,
.type = AVMEDIA_TYPE_VIDEO,
.name = "svq1",
@@ -520,7 +528,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.type = AVMEDIA_TYPE_VIDEO,
.name = "fraps",
.long_name = NULL_IF_CONFIG_SMALL("Fraps"),
- .props = AV_CODEC_PROP_LOSSLESS,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_TRUEMOTION2,
@@ -665,6 +673,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.name = "dnxhd",
.long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
.props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSY,
+ .profiles = NULL_IF_CONFIG_SMALL(ff_dnxhd_profiles),
},
{
.id = AV_CODEC_ID_THP,
@@ -1106,7 +1115,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.type = AVMEDIA_TYPE_VIDEO,
.name = "y41p",
.long_name = NULL_IF_CONFIG_SMALL("Uncompressed YUV 4:1:1 12-bit"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_ESCAPE130,
@@ -1120,56 +1129,56 @@ static const AVCodecDescriptor codec_descriptors[] = {
.type = AVMEDIA_TYPE_VIDEO,
.name = "avrp",
.long_name = NULL_IF_CONFIG_SMALL("Avid 1:1 10-bit RGB Packer"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_012V,
.type = AVMEDIA_TYPE_VIDEO,
.name = "012v",
.long_name = NULL_IF_CONFIG_SMALL("Uncompressed 4:2:2 10-bit"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_AVUI,
.type = AVMEDIA_TYPE_VIDEO,
.name = "avui",
.long_name = NULL_IF_CONFIG_SMALL("Avid Meridien Uncompressed"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_AYUV,
.type = AVMEDIA_TYPE_VIDEO,
.name = "ayuv",
.long_name = NULL_IF_CONFIG_SMALL("Uncompressed packed MS 4:4:4:4"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_TARGA_Y216,
.type = AVMEDIA_TYPE_VIDEO,
.name = "targa_y216",
.long_name = NULL_IF_CONFIG_SMALL("Pinnacle TARGA CineWave YUV16"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_V308,
.type = AVMEDIA_TYPE_VIDEO,
.name = "v308",
.long_name = NULL_IF_CONFIG_SMALL("Uncompressed packed 4:4:4"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_V408,
.type = AVMEDIA_TYPE_VIDEO,
.name = "v408",
.long_name = NULL_IF_CONFIG_SMALL("Uncompressed packed QT 4:4:4:4"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_YUV4,
.type = AVMEDIA_TYPE_VIDEO,
.name = "yuv4",
.long_name = NULL_IF_CONFIG_SMALL("Uncompressed packed 4:2:0"),
- .props = AV_CODEC_PROP_INTRA_ONLY,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_AVRN,
@@ -1272,7 +1281,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.id = AV_CODEC_ID_HAP,
.type = AVMEDIA_TYPE_VIDEO,
.name = "hap",
- .long_name = NULL_IF_CONFIG_SMALL("Vidvox Hap decoder"),
+ .long_name = NULL_IF_CONFIG_SMALL("Vidvox Hap"),
.props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSY,
},
{
@@ -1290,6 +1299,13 @@ static const AVCodecDescriptor codec_descriptors[] = {
.props = AV_CODEC_PROP_LOSSLESS,
},
{
+ .id = AV_CODEC_ID_SPEEDHQ,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "speedhq",
+ .long_name = NULL_IF_CONFIG_SMALL("NewTek SpeedHQ"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSY,
+ },
+ {
.id = AV_CODEC_ID_WRAPPED_AVFRAME,
.type = AVMEDIA_TYPE_VIDEO,
.name = "wrapped_avframe",
@@ -1303,6 +1319,104 @@ static const AVCodecDescriptor codec_descriptors[] = {
.long_name = NULL_IF_CONFIG_SMALL("innoHeim/Rsupport Screen Capture Codec"),
.props = AV_CODEC_PROP_LOSSLESS,
},
+ {
+ .id = AV_CODEC_ID_MAGICYUV,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "magicyuv",
+ .long_name = NULL_IF_CONFIG_SMALL("MagicYUV video"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_TRUEMOTION2RT,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "truemotion2rt",
+ .long_name = NULL_IF_CONFIG_SMALL("Duck TrueMotion 2.0 Real Time"),
+ .props = AV_CODEC_PROP_LOSSY,
+ },
+ {
+ .id = AV_CODEC_ID_CFHD,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "cfhd",
+ .long_name = NULL_IF_CONFIG_SMALL("Cineform HD"),
+ .props = AV_CODEC_PROP_LOSSY,
+ },
+ {
+ .id = AV_CODEC_ID_SHEERVIDEO,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "sheervideo",
+ .long_name = NULL_IF_CONFIG_SMALL("BitJazz SheerVideo"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_YLC,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "ylc",
+ .long_name = NULL_IF_CONFIG_SMALL("YUY2 Lossless Codec"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_PIXLET,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "pixlet",
+ .long_name = NULL_IF_CONFIG_SMALL("Apple Pixlet"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSY,
+ },
+ {
+ .id = AV_CODEC_ID_FMVC,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "fmvc",
+ .long_name = NULL_IF_CONFIG_SMALL("FM Screen Capture Codec"),
+ .props = AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_SCPR,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "scpr",
+ .long_name = NULL_IF_CONFIG_SMALL("ScreenPressor"),
+ .props = AV_CODEC_PROP_LOSSLESS | AV_CODEC_PROP_LOSSY,
+ },
+ {
+ .id = AV_CODEC_ID_CLEARVIDEO,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "clearvideo",
+ .long_name = NULL_IF_CONFIG_SMALL("Iterated Systems ClearVideo"),
+ .props = AV_CODEC_PROP_LOSSY,
+ },
+ {
+ .id = AV_CODEC_ID_AV1,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "av1",
+ .long_name = NULL_IF_CONFIG_SMALL("Alliance for Open Media AV1"),
+ .props = AV_CODEC_PROP_LOSSY,
+ },
+ {
+ .id = AV_CODEC_ID_BITPACKED,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "bitpacked",
+ .long_name = NULL_IF_CONFIG_SMALL("Bitpacked"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_MSCC,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "mscc",
+ .long_name = NULL_IF_CONFIG_SMALL("Mandsoft Screen Capture Codec"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_SRGC,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "srgc",
+ .long_name = NULL_IF_CONFIG_SMALL("Screen Recorder Gold Codec"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_GDV,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "gdv",
+ .long_name = NULL_IF_CONFIG_SMALL("Gremlin Digital Video"),
+ .props = AV_CODEC_PROP_LOSSY,
+ },
/* image codecs */
{
@@ -1350,6 +1464,13 @@ static const AVCodecDescriptor codec_descriptors[] = {
AV_CODEC_PROP_LOSSLESS,
},
{
+ .id = AV_CODEC_ID_FITS,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "fits",
+ .long_name = NULL_IF_CONFIG_SMALL("FITS (Flexible Image Transport System)"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ },
+ {
.id = AV_CODEC_ID_GIF,
.type = AVMEDIA_TYPE_VIDEO,
.name = "gif",
@@ -1425,6 +1546,13 @@ static const AVCodecDescriptor codec_descriptors[] = {
.props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
+ .id = AV_CODEC_ID_PSD,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "psd",
+ .long_name = NULL_IF_CONFIG_SMALL("Photoshop PSD file"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ },
+ {
.id = AV_CODEC_ID_PTX,
.type = AVMEDIA_TYPE_VIDEO,
.name = "ptx",
@@ -1511,6 +1639,15 @@ static const AVCodecDescriptor codec_descriptors[] = {
.name = "xbm",
.long_name = NULL_IF_CONFIG_SMALL("XBM (X BitMap) image"),
.props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ .mime_types= MT("image/x-xbitmap"),
+ },
+ {
+ .id = AV_CODEC_ID_XPM,
+ .type = AVMEDIA_TYPE_VIDEO,
+ .name = "xpm",
+ .long_name = NULL_IF_CONFIG_SMALL("XPM (X PixMap) image"),
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
+ .mime_types= MT("image/x-xpixmap"),
},
{
.id = AV_CODEC_ID_XWD,
@@ -1528,41 +1665,6 @@ static const AVCodecDescriptor codec_descriptors[] = {
.props = AV_CODEC_PROP_LOSSLESS,
.mime_types= MT("image/png"),
},
- {
- .id = AV_CODEC_ID_CFHD,
- .type = AVMEDIA_TYPE_VIDEO,
- .name = "cfhd",
- .long_name = NULL_IF_CONFIG_SMALL("Cineform HD"),
- .props = AV_CODEC_PROP_LOSSY,
- },
- {
- .id = AV_CODEC_ID_TRUEMOTION2RT,
- .type = AVMEDIA_TYPE_VIDEO,
- .name = "truemotion2rt",
- .long_name = NULL_IF_CONFIG_SMALL("Duck TrueMotion 2.0 Real Time"),
- .props = AV_CODEC_PROP_LOSSY,
- },
- {
- .id = AV_CODEC_ID_MAGICYUV,
- .type = AVMEDIA_TYPE_VIDEO,
- .name = "magicyuv",
- .long_name = NULL_IF_CONFIG_SMALL("MagicYUV Lossless Video"),
- .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
- },
- {
- .id = AV_CODEC_ID_SHEERVIDEO,
- .type = AVMEDIA_TYPE_VIDEO,
- .name = "sheervideo",
- .long_name = NULL_IF_CONFIG_SMALL("BitJazz SheerVideo"),
- .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
- },
- {
- .id = AV_CODEC_ID_YLC,
- .type = AVMEDIA_TYPE_VIDEO,
- .name = "ylc",
- .long_name = NULL_IF_CONFIG_SMALL("YUY2 Lossless Codec"),
- .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
- },
/* various PCM "codecs" */
{
@@ -1636,6 +1738,20 @@ static const AVCodecDescriptor codec_descriptors[] = {
.props = AV_CODEC_PROP_LOSSLESS,
},
{
+ .id = AV_CODEC_ID_PCM_S64LE,
+ .type = AVMEDIA_TYPE_AUDIO,
+ .name = "pcm_s64le",
+ .long_name = NULL_IF_CONFIG_SMALL("PCM signed 64-bit little-endian"),
+ .props = AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_PCM_S64BE,
+ .type = AVMEDIA_TYPE_AUDIO,
+ .name = "pcm_s64be",
+ .long_name = NULL_IF_CONFIG_SMALL("PCM signed 64-bit big-endian"),
+ .props = AV_CODEC_PROP_LOSSLESS,
+ },
+ {
.id = AV_CODEC_ID_PCM_U32LE,
.type = AVMEDIA_TYPE_AUDIO,
.name = "pcm_u32le",
@@ -1727,6 +1843,20 @@ static const AVCodecDescriptor codec_descriptors[] = {
.props = AV_CODEC_PROP_LOSSLESS,
},
{
+ .id = AV_CODEC_ID_PCM_F16LE,
+ .type = AVMEDIA_TYPE_AUDIO,
+ .name = "pcm_f16le",
+ .long_name = NULL_IF_CONFIG_SMALL("PCM 16.8 floating point little-endian"),
+ .props = AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_PCM_F24LE,
+ .type = AVMEDIA_TYPE_AUDIO,
+ .name = "pcm_f24le",
+ .long_name = NULL_IF_CONFIG_SMALL("PCM 24.0 floating point little-endian"),
+ .props = AV_CODEC_PROP_LOSSLESS,
+ },
+ {
.id = AV_CODEC_ID_PCM_F32BE,
.type = AVMEDIA_TYPE_AUDIO,
.name = "pcm_f32be",
@@ -2133,6 +2263,13 @@ static const AVCodecDescriptor codec_descriptors[] = {
.long_name = NULL_IF_CONFIG_SMALL("DPCM Squareroot-Delta-Exact"),
.props = AV_CODEC_PROP_LOSSY,
},
+ {
+ .id = AV_CODEC_ID_GREMLIN_DPCM,
+ .type = AVMEDIA_TYPE_AUDIO,
+ .name = "gremlin_dpcm",
+ .long_name = NULL_IF_CONFIG_SMALL("DPCM Gremlin"),
+ .props = AV_CODEC_PROP_LOSSY,
+ },
/* audio codecs */
{
@@ -2226,7 +2363,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.type = AVMEDIA_TYPE_AUDIO,
.name = "flac",
.long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
- .props = AV_CODEC_PROP_LOSSLESS,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_MP3ADU,
@@ -2254,7 +2391,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.type = AVMEDIA_TYPE_AUDIO,
.name = "alac",
.long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
- .props = AV_CODEC_PROP_LOSSLESS,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_WESTWOOD_SND1,
@@ -2281,7 +2418,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.id = AV_CODEC_ID_COOK,
.type = AVMEDIA_TYPE_AUDIO,
.name = "cook",
- .long_name = NULL_IF_CONFIG_SMALL("Cook / Cooker / Goanna (RealAudio G2)"),
+ .long_name = NULL_IF_CONFIG_SMALL("Cook / Cooker / Gecko (RealAudio G2)"),
.props = AV_CODEC_PROP_LOSSY,
},
{
@@ -2296,7 +2433,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.type = AVMEDIA_TYPE_AUDIO,
.name = "tta",
.long_name = NULL_IF_CONFIG_SMALL("TTA (True Audio)"),
- .props = AV_CODEC_PROP_LOSSLESS,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_SMACKAUDIO,
@@ -2317,7 +2454,8 @@ static const AVCodecDescriptor codec_descriptors[] = {
.type = AVMEDIA_TYPE_AUDIO,
.name = "wavpack",
.long_name = NULL_IF_CONFIG_SMALL("WavPack"),
- .props = AV_CODEC_PROP_LOSSY | AV_CODEC_PROP_LOSSLESS,
+ .props = AV_CODEC_PROP_INTRA_ONLY |
+ AV_CODEC_PROP_LOSSY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_DSICINAUDIO,
@@ -2427,6 +2565,20 @@ static const AVCodecDescriptor codec_descriptors[] = {
.props = AV_CODEC_PROP_LOSSY,
},
{
+ .id = AV_CODEC_ID_ATRAC3PAL,
+ .type = AVMEDIA_TYPE_AUDIO,
+ .name = "atrac3pal",
+ .long_name = NULL_IF_CONFIG_SMALL("ATRAC3+ AL (Adaptive TRansform Acoustic Coding 3+ Advanced Lossless)"),
+ .props = AV_CODEC_PROP_LOSSLESS,
+ },
+ {
+ .id = AV_CODEC_ID_ATRAC3AL,
+ .type = AVMEDIA_TYPE_AUDIO,
+ .name = "atrac3al",
+ .long_name = NULL_IF_CONFIG_SMALL("ATRAC3 AL (Adaptive TRansform Acoustic Coding 3 Advanced Lossless)"),
+ .props = AV_CODEC_PROP_LOSSLESS,
+ },
+ {
.id = AV_CODEC_ID_EAC3,
.type = AVMEDIA_TYPE_AUDIO,
.name = "eac3",
@@ -2526,6 +2678,13 @@ static const AVCodecDescriptor codec_descriptors[] = {
.props = AV_CODEC_PROP_LOSSY,
},
{
+ .id = AV_CODEC_ID_DOLBY_E,
+ .type = AVMEDIA_TYPE_AUDIO,
+ .name = "dolby_e",
+ .long_name = NULL_IF_CONFIG_SMALL("Dolby E"),
+ .props = AV_CODEC_PROP_LOSSY,
+ },
+ {
.id = AV_CODEC_ID_G729,
.type = AVMEDIA_TYPE_AUDIO,
.name = "g729",
@@ -2611,7 +2770,7 @@ static const AVCodecDescriptor codec_descriptors[] = {
.type = AVMEDIA_TYPE_AUDIO,
.name = "tak",
.long_name = NULL_IF_CONFIG_SMALL("TAK (Tom's lossless Audio Kompressor)"),
- .props = AV_CODEC_PROP_LOSSLESS,
+ .props = AV_CODEC_PROP_INTRA_ONLY | AV_CODEC_PROP_LOSSLESS,
},
{
.id = AV_CODEC_ID_METASOUND,
@@ -2949,6 +3108,12 @@ static const AVCodecDescriptor codec_descriptors[] = {
.long_name = NULL_IF_CONFIG_SMALL("binary data"),
.mime_types= MT("application/octet-stream"),
},
+ {
+ .id = AV_CODEC_ID_SCTE_35,
+ .type = AVMEDIA_TYPE_DATA,
+ .name = "scte_35",
+ .long_name = NULL_IF_CONFIG_SMALL("SCTE 35 Message Queue"),
+ },
/* deprecated codec ids */
};
diff --git a/media/ffvpx/libavcodec/dct.h b/media/ffvpx/libavcodec/dct.h
deleted file mode 100644
index 05297ba9d..000000000
--- a/media/ffvpx/libavcodec/dct.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * (I)DCT Transforms
- * Copyright (c) 2009 Peter Ross <pross@xvid.org>
- * Copyright (c) 2010 Alex Converse <alex.converse@gmail.com>
- * Copyright (c) 2010 Vitor Sessak
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#if !defined(AVCODEC_DCT_H) && (!defined(FFT_FLOAT) || FFT_FLOAT)
-#define AVCODEC_DCT_H
-
-#include <stdint.h>
-
-#include "rdft.h"
-
-struct DCTContext {
- int nbits;
- int inverse;
- RDFTContext rdft;
- const float *costab;
- FFTSample *csc2;
- void (*dct_calc)(struct DCTContext *s, FFTSample *data);
- void (*dct32)(FFTSample *out, const FFTSample *in);
-};
-
-/**
- * Set up DCT.
- * @param nbits size of the input array:
- * (1 << nbits) for DCT-II, DCT-III and DST-I
- * (1 << nbits) + 1 for DCT-I
- *
- * @note the first element of the input of DST-I is ignored
- */
-int ff_dct_init(DCTContext *s, int nbits, enum DCTTransformType type);
-void ff_dct_end (DCTContext *s);
-
-void ff_dct_init_x86(DCTContext *s);
-
-void ff_fdct_ifast(int16_t *data);
-void ff_fdct_ifast248(int16_t *data);
-void ff_jpeg_fdct_islow_8(int16_t *data);
-void ff_jpeg_fdct_islow_10(int16_t *data);
-void ff_fdct248_islow_8(int16_t *data);
-void ff_fdct248_islow_10(int16_t *data);
-
-void ff_j_rev_dct(int16_t *data);
-void ff_j_rev_dct4(int16_t *data);
-void ff_j_rev_dct2(int16_t *data);
-void ff_j_rev_dct1(int16_t *data);
-void ff_jref_idct_put(uint8_t *dest, int line_size, int16_t *block);
-void ff_jref_idct_add(uint8_t *dest, int line_size, int16_t *block);
-
-#endif /* AVCODEC_DCT_H */
diff --git a/media/ffvpx/libavcodec/decode.c b/media/ffvpx/libavcodec/decode.c
new file mode 100644
index 000000000..fb1824be1
--- /dev/null
+++ b/media/ffvpx/libavcodec/decode.c
@@ -0,0 +1,1761 @@
+/*
+ * generic decoding-related code
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdint.h>
+#include <string.h>
+
+#include "config.h"
+
+#if CONFIG_ICONV
+# include <iconv.h>
+#endif
+
+#include "libavutil/avassert.h"
+#include "libavutil/avstring.h"
+#include "libavutil/bprint.h"
+#include "libavutil/common.h"
+#include "libavutil/frame.h"
+#include "libavutil/hwcontext.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/internal.h"
+#include "libavutil/intmath.h"
+
+#include "avcodec.h"
+#include "bytestream.h"
+#include "decode.h"
+#include "internal.h"
+#include "thread.h"
+
+static int apply_param_change(AVCodecContext *avctx, const AVPacket *avpkt)
+{
+ int size = 0, ret;
+ const uint8_t *data;
+ uint32_t flags;
+ int64_t val;
+
+ data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
+ if (!data)
+ return 0;
+
+ if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
+ av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
+ "changes, but PARAM_CHANGE side data was sent to it.\n");
+ ret = AVERROR(EINVAL);
+ goto fail2;
+ }
+
+ if (size < 4)
+ goto fail;
+
+ flags = bytestream_get_le32(&data);
+ size -= 4;
+
+ if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
+ if (size < 4)
+ goto fail;
+ val = bytestream_get_le32(&data);
+ if (val <= 0 || val > INT_MAX) {
+ av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
+ ret = AVERROR_INVALIDDATA;
+ goto fail2;
+ }
+ avctx->channels = val;
+ size -= 4;
+ }
+ if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
+ if (size < 8)
+ goto fail;
+ avctx->channel_layout = bytestream_get_le64(&data);
+ size -= 8;
+ }
+ if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
+ if (size < 4)
+ goto fail;
+ val = bytestream_get_le32(&data);
+ if (val <= 0 || val > INT_MAX) {
+ av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
+ ret = AVERROR_INVALIDDATA;
+ goto fail2;
+ }
+ avctx->sample_rate = val;
+ size -= 4;
+ }
+ if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
+ if (size < 8)
+ goto fail;
+ avctx->width = bytestream_get_le32(&data);
+ avctx->height = bytestream_get_le32(&data);
+ size -= 8;
+ ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
+ if (ret < 0)
+ goto fail2;
+ }
+
+ return 0;
+fail:
+ av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
+ ret = AVERROR_INVALIDDATA;
+fail2:
+ if (ret < 0) {
+ av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
+ if (avctx->err_recognition & AV_EF_EXPLODE)
+ return ret;
+ }
+ return 0;
+}
+
+static int extract_packet_props(AVCodecInternal *avci, const AVPacket *pkt)
+{
+ int ret = 0;
+
+ av_packet_unref(avci->last_pkt_props);
+ if (pkt) {
+ ret = av_packet_copy_props(avci->last_pkt_props, pkt);
+ if (!ret)
+ avci->last_pkt_props->size = pkt->size; // HACK: Needed for ff_init_buffer_info().
+ }
+ return ret;
+}
+
+static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
+{
+ int ret;
+
+ /* move the original frame to our backup */
+ av_frame_unref(avci->to_free);
+ av_frame_move_ref(avci->to_free, frame);
+
+ /* now copy everything except the AVBufferRefs back
+ * note that we make a COPY of the side data, so calling av_frame_free() on
+ * the caller's frame will work properly */
+ ret = av_frame_copy_props(frame, avci->to_free);
+ if (ret < 0)
+ return ret;
+
+ memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
+ memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
+ if (avci->to_free->extended_data != avci->to_free->data) {
+ int planes = avci->to_free->channels;
+ int size = planes * sizeof(*frame->extended_data);
+
+ if (!size) {
+ av_frame_unref(frame);
+ return AVERROR_BUG;
+ }
+
+ frame->extended_data = av_malloc(size);
+ if (!frame->extended_data) {
+ av_frame_unref(frame);
+ return AVERROR(ENOMEM);
+ }
+ memcpy(frame->extended_data, avci->to_free->extended_data,
+ size);
+ } else
+ frame->extended_data = frame->data;
+
+ frame->format = avci->to_free->format;
+ frame->width = avci->to_free->width;
+ frame->height = avci->to_free->height;
+ frame->channel_layout = avci->to_free->channel_layout;
+ frame->nb_samples = avci->to_free->nb_samples;
+ frame->channels = avci->to_free->channels;
+
+ return 0;
+}
+
+static int bsfs_init(AVCodecContext *avctx)
+{
+ AVCodecInternal *avci = avctx->internal;
+ DecodeFilterContext *s = &avci->filter;
+ const char *bsfs_str;
+ int ret;
+
+ if (s->nb_bsfs)
+ return 0;
+
+ bsfs_str = avctx->codec->bsfs ? avctx->codec->bsfs : "null";
+ while (bsfs_str && *bsfs_str) {
+ AVBSFContext **tmp;
+ const AVBitStreamFilter *filter;
+ char *bsf;
+
+ bsf = av_get_token(&bsfs_str, ",");
+ if (!bsf) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+
+ filter = av_bsf_get_by_name(bsf);
+ if (!filter) {
+ av_log(avctx, AV_LOG_ERROR, "A non-existing bitstream filter %s "
+ "requested by a decoder. This is a bug, please report it.\n",
+ bsf);
+ ret = AVERROR_BUG;
+ av_freep(&bsf);
+ goto fail;
+ }
+ av_freep(&bsf);
+
+ tmp = av_realloc_array(s->bsfs, s->nb_bsfs + 1, sizeof(*s->bsfs));
+ if (!tmp) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ s->bsfs = tmp;
+ s->nb_bsfs++;
+
+ ret = av_bsf_alloc(filter, &s->bsfs[s->nb_bsfs - 1]);
+ if (ret < 0)
+ goto fail;
+
+ if (s->nb_bsfs == 1) {
+ /* We do not currently have an API for passing the input timebase into decoders,
+ * but no filters used here should actually need it.
+ * So we make up some plausible-looking number (the MPEG 90kHz timebase) */
+ s->bsfs[s->nb_bsfs - 1]->time_base_in = (AVRational){ 1, 90000 };
+ ret = avcodec_parameters_from_context(s->bsfs[s->nb_bsfs - 1]->par_in,
+ avctx);
+ } else {
+ s->bsfs[s->nb_bsfs - 1]->time_base_in = s->bsfs[s->nb_bsfs - 2]->time_base_out;
+ ret = avcodec_parameters_copy(s->bsfs[s->nb_bsfs - 1]->par_in,
+ s->bsfs[s->nb_bsfs - 2]->par_out);
+ }
+ if (ret < 0)
+ goto fail;
+
+ ret = av_bsf_init(s->bsfs[s->nb_bsfs - 1]);
+ if (ret < 0)
+ goto fail;
+ }
+
+ return 0;
+fail:
+ ff_decode_bsfs_uninit(avctx);
+ return ret;
+}
+
+/* try to get one output packet from the filter chain */
+static int bsfs_poll(AVCodecContext *avctx, AVPacket *pkt)
+{
+ DecodeFilterContext *s = &avctx->internal->filter;
+ int idx, ret;
+
+ /* start with the last filter in the chain */
+ idx = s->nb_bsfs - 1;
+ while (idx >= 0) {
+ /* request a packet from the currently selected filter */
+ ret = av_bsf_receive_packet(s->bsfs[idx], pkt);
+ if (ret == AVERROR(EAGAIN)) {
+ /* no packets available, try the next filter up the chain */
+ ret = 0;
+ idx--;
+ continue;
+ } else if (ret < 0 && ret != AVERROR_EOF) {
+ return ret;
+ }
+
+ /* got a packet or EOF -- pass it to the caller or to the next filter
+ * down the chain */
+ if (idx == s->nb_bsfs - 1) {
+ return ret;
+ } else {
+ idx++;
+ ret = av_bsf_send_packet(s->bsfs[idx], ret < 0 ? NULL : pkt);
+ if (ret < 0) {
+ av_log(avctx, AV_LOG_ERROR,
+ "Error pre-processing a packet before decoding\n");
+ av_packet_unref(pkt);
+ return ret;
+ }
+ }
+ }
+
+ return AVERROR(EAGAIN);
+}
+
+int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt)
+{
+ AVCodecInternal *avci = avctx->internal;
+ int ret;
+
+ if (avci->draining)
+ return AVERROR_EOF;
+
+ ret = bsfs_poll(avctx, pkt);
+ if (ret == AVERROR_EOF)
+ avci->draining = 1;
+ if (ret < 0)
+ return ret;
+
+ ret = extract_packet_props(avctx->internal, pkt);
+ if (ret < 0)
+ goto finish;
+
+ ret = apply_param_change(avctx, pkt);
+ if (ret < 0)
+ goto finish;
+
+ if (avctx->codec->receive_frame)
+ avci->compat_decode_consumed += pkt->size;
+
+ return 0;
+finish:
+ av_packet_unref(pkt);
+ return ret;
+}
+
+/**
+ * Attempt to guess proper monotonic timestamps for decoded video frames
+ * which might have incorrect times. Input timestamps may wrap around, in
+ * which case the output will as well.
+ *
+ * @param pts the pts field of the decoded AVPacket, as passed through
+ * AVFrame.pts
+ * @param dts the dts field of the decoded AVPacket
+ * @return one of the input values, may be AV_NOPTS_VALUE
+ */
+static int64_t guess_correct_pts(AVCodecContext *ctx,
+ int64_t reordered_pts, int64_t dts)
+{
+ int64_t pts = AV_NOPTS_VALUE;
+
+ if (dts != AV_NOPTS_VALUE) {
+ ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
+ ctx->pts_correction_last_dts = dts;
+ } else if (reordered_pts != AV_NOPTS_VALUE)
+ ctx->pts_correction_last_dts = reordered_pts;
+
+ if (reordered_pts != AV_NOPTS_VALUE) {
+ ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
+ ctx->pts_correction_last_pts = reordered_pts;
+ } else if(dts != AV_NOPTS_VALUE)
+ ctx->pts_correction_last_pts = dts;
+
+ if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
+ && reordered_pts != AV_NOPTS_VALUE)
+ pts = reordered_pts;
+ else
+ pts = dts;
+
+ return pts;
+}
+
+/*
+ * The core of the receive_frame_wrapper for the decoders implementing
+ * the simple API. Certain decoders might consume partial packets without
+ * returning any output, so this function needs to be called in a loop until it
+ * returns EAGAIN.
+ **/
+static int decode_simple_internal(AVCodecContext *avctx, AVFrame *frame)
+{
+ AVCodecInternal *avci = avctx->internal;
+ DecodeSimpleContext *ds = &avci->ds;
+ AVPacket *pkt = ds->in_pkt;
+ // copy to ensure we do not change pkt
+ AVPacket tmp;
+ int got_frame, actual_got_frame, did_split;
+ int ret;
+
+ if (!pkt->data && !avci->draining) {
+ av_packet_unref(pkt);
+ ret = ff_decode_get_packet(avctx, pkt);
+ if (ret < 0 && ret != AVERROR_EOF)
+ return ret;
+ }
+
+ // Some codecs (at least wma lossless) will crash when feeding drain packets
+ // after EOF was signaled.
+ if (avci->draining_done)
+ return AVERROR_EOF;
+
+ if (!pkt->data &&
+ !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY ||
+ avctx->active_thread_type & FF_THREAD_FRAME))
+ return AVERROR_EOF;
+
+ tmp = *pkt;
+#if FF_API_MERGE_SD
+FF_DISABLE_DEPRECATION_WARNINGS
+ did_split = avci->compat_decode_partial_size ?
+ ff_packet_split_and_drop_side_data(&tmp) :
+ av_packet_split_side_data(&tmp);
+
+ if (did_split) {
+ ret = extract_packet_props(avctx->internal, &tmp);
+ if (ret < 0)
+ return ret;
+
+ ret = apply_param_change(avctx, &tmp);
+ if (ret < 0)
+ return ret;
+ }
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
+
+ got_frame = 0;
+
+ if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME) {
+ ret = ff_thread_decode_frame(avctx, frame, &got_frame, &tmp);
+ } else {
+ ret = avctx->codec->decode(avctx, frame, &got_frame, &tmp);
+
+ if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
+ frame->pkt_dts = pkt->dts;
+ if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
+ if(!avctx->has_b_frames)
+ frame->pkt_pos = pkt->pos;
+ //FIXME these should be under if(!avctx->has_b_frames)
+ /* get_buffer is supposed to set frame parameters */
+ if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
+ if (!frame->sample_aspect_ratio.num) frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
+ if (!frame->width) frame->width = avctx->width;
+ if (!frame->height) frame->height = avctx->height;
+ if (frame->format == AV_PIX_FMT_NONE) frame->format = avctx->pix_fmt;
+ }
+ }
+ }
+ emms_c();
+ actual_got_frame = got_frame;
+
+ if (avctx->codec->type == AVMEDIA_TYPE_VIDEO) {
+ if (frame->flags & AV_FRAME_FLAG_DISCARD)
+ got_frame = 0;
+ if (got_frame)
+ frame->best_effort_timestamp = guess_correct_pts(avctx,
+ frame->pts,
+ frame->pkt_dts);
+ } else if (avctx->codec->type == AVMEDIA_TYPE_AUDIO) {
+ uint8_t *side;
+ int side_size;
+ uint32_t discard_padding = 0;
+ uint8_t skip_reason = 0;
+ uint8_t discard_reason = 0;
+
+ if (ret >= 0 && got_frame) {
+ frame->best_effort_timestamp = guess_correct_pts(avctx,
+ frame->pts,
+ frame->pkt_dts);
+ if (frame->format == AV_SAMPLE_FMT_NONE)
+ frame->format = avctx->sample_fmt;
+ if (!frame->channel_layout)
+ frame->channel_layout = avctx->channel_layout;
+ if (!frame->channels)
+ frame->channels = avctx->channels;
+ if (!frame->sample_rate)
+ frame->sample_rate = avctx->sample_rate;
+ }
+
+ side= av_packet_get_side_data(avci->last_pkt_props, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
+ if(side && side_size>=10) {
+ avctx->internal->skip_samples = AV_RL32(side) * avctx->internal->skip_samples_multiplier;
+ discard_padding = AV_RL32(side + 4);
+ av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
+ avctx->internal->skip_samples, (int)discard_padding);
+ skip_reason = AV_RL8(side + 8);
+ discard_reason = AV_RL8(side + 9);
+ }
+
+ if ((frame->flags & AV_FRAME_FLAG_DISCARD) && got_frame &&
+ !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
+ avctx->internal->skip_samples = FFMAX(0, avctx->internal->skip_samples - frame->nb_samples);
+ got_frame = 0;
+ }
+
+ if (avctx->internal->skip_samples > 0 && got_frame &&
+ !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
+ if(frame->nb_samples <= avctx->internal->skip_samples){
+ got_frame = 0;
+ avctx->internal->skip_samples -= frame->nb_samples;
+ av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
+ avctx->internal->skip_samples);
+ } else {
+ av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
+ frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
+ if(avctx->pkt_timebase.num && avctx->sample_rate) {
+ int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
+ (AVRational){1, avctx->sample_rate},
+ avctx->pkt_timebase);
+ if(frame->pts!=AV_NOPTS_VALUE)
+ frame->pts += diff_ts;
+#if FF_API_PKT_PTS
+FF_DISABLE_DEPRECATION_WARNINGS
+ if(frame->pkt_pts!=AV_NOPTS_VALUE)
+ frame->pkt_pts += diff_ts;
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
+ if(frame->pkt_dts!=AV_NOPTS_VALUE)
+ frame->pkt_dts += diff_ts;
+ if (frame->pkt_duration >= diff_ts)
+ frame->pkt_duration -= diff_ts;
+ } else {
+ av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
+ }
+ av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
+ avctx->internal->skip_samples, frame->nb_samples);
+ frame->nb_samples -= avctx->internal->skip_samples;
+ avctx->internal->skip_samples = 0;
+ }
+ }
+
+ if (discard_padding > 0 && discard_padding <= frame->nb_samples && got_frame &&
+ !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
+ if (discard_padding == frame->nb_samples) {
+ got_frame = 0;
+ } else {
+ if(avctx->pkt_timebase.num && avctx->sample_rate) {
+ int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
+ (AVRational){1, avctx->sample_rate},
+ avctx->pkt_timebase);
+ frame->pkt_duration = diff_ts;
+ } else {
+ av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
+ }
+ av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
+ (int)discard_padding, frame->nb_samples);
+ frame->nb_samples -= discard_padding;
+ }
+ }
+
+ if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && got_frame) {
+ AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
+ if (fside) {
+ AV_WL32(fside->data, avctx->internal->skip_samples);
+ AV_WL32(fside->data + 4, discard_padding);
+ AV_WL8(fside->data + 8, skip_reason);
+ AV_WL8(fside->data + 9, discard_reason);
+ avctx->internal->skip_samples = 0;
+ }
+ }
+ }
+#if FF_API_MERGE_SD
+ if (did_split) {
+ av_packet_free_side_data(&tmp);
+ if(ret == tmp.size)
+ ret = pkt->size;
+ }
+#endif
+
+ if (avctx->codec->type == AVMEDIA_TYPE_AUDIO &&
+ !avci->showed_multi_packet_warning &&
+ ret >= 0 && ret != pkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
+ av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
+ avci->showed_multi_packet_warning = 1;
+ }
+
+ if (!got_frame)
+ av_frame_unref(frame);
+
+ if (ret >= 0 && avctx->codec->type == AVMEDIA_TYPE_VIDEO && !(avctx->flags & AV_CODEC_FLAG_TRUNCATED))
+ ret = pkt->size;
+
+#if FF_API_AVCTX_TIMEBASE
+ if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
+ avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
+#endif
+
+ /* do not stop draining when actual_got_frame != 0 or ret < 0 */
+ /* got_frame == 0 but actual_got_frame != 0 when frame is discarded */
+ if (avctx->internal->draining && !actual_got_frame) {
+ if (ret < 0) {
+ /* prevent infinite loop if a decoder wrongly always return error on draining */
+ /* reasonable nb_errors_max = maximum b frames + thread count */
+ int nb_errors_max = 20 + (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME ?
+ avctx->thread_count : 1);
+
+ if (avci->nb_draining_errors++ >= nb_errors_max) {
+ av_log(avctx, AV_LOG_ERROR, "Too many errors when draining, this is a bug. "
+ "Stop draining and force EOF.\n");
+ avci->draining_done = 1;
+ ret = AVERROR_BUG;
+ }
+ } else {
+ avci->draining_done = 1;
+ }
+ }
+
+ avci->compat_decode_consumed += ret;
+
+ if (ret >= pkt->size || ret < 0) {
+ av_packet_unref(pkt);
+ } else {
+ int consumed = ret;
+
+ pkt->data += consumed;
+ pkt->size -= consumed;
+ avci->last_pkt_props->size -= consumed; // See extract_packet_props() comment.
+ pkt->pts = AV_NOPTS_VALUE;
+ pkt->dts = AV_NOPTS_VALUE;
+ avci->last_pkt_props->pts = AV_NOPTS_VALUE;
+ avci->last_pkt_props->dts = AV_NOPTS_VALUE;
+ }
+
+ if (got_frame)
+ av_assert0(frame->buf[0]);
+
+ return ret < 0 ? ret : 0;
+}
+
+static int decode_simple_receive_frame(AVCodecContext *avctx, AVFrame *frame)
+{
+ int ret;
+
+ while (!frame->buf[0]) {
+ ret = decode_simple_internal(avctx, frame);
+ if (ret < 0)
+ return ret;
+ }
+
+ return 0;
+}
+
+static int decode_receive_frame_internal(AVCodecContext *avctx, AVFrame *frame)
+{
+ AVCodecInternal *avci = avctx->internal;
+ int ret;
+
+ av_assert0(!frame->buf[0]);
+
+ if (avctx->codec->receive_frame)
+ ret = avctx->codec->receive_frame(avctx, frame);
+ else
+ ret = decode_simple_receive_frame(avctx, frame);
+
+ if (ret == AVERROR_EOF)
+ avci->draining_done = 1;
+
+ return ret;
+}
+
+int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
+{
+ AVCodecInternal *avci = avctx->internal;
+ int ret;
+
+ if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
+ return AVERROR(EINVAL);
+
+ if (avctx->internal->draining)
+ return AVERROR_EOF;
+
+ if (avpkt && !avpkt->size && avpkt->data)
+ return AVERROR(EINVAL);
+
+ ret = bsfs_init(avctx);
+ if (ret < 0)
+ return ret;
+
+ av_packet_unref(avci->buffer_pkt);
+ if (avpkt && (avpkt->data || avpkt->side_data_elems)) {
+ ret = av_packet_ref(avci->buffer_pkt, avpkt);
+ if (ret < 0)
+ return ret;
+ }
+
+ ret = av_bsf_send_packet(avci->filter.bsfs[0], avci->buffer_pkt);
+ if (ret < 0) {
+ av_packet_unref(avci->buffer_pkt);
+ return ret;
+ }
+
+ if (!avci->buffer_frame->buf[0]) {
+ ret = decode_receive_frame_internal(avctx, avci->buffer_frame);
+ if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
+ return ret;
+ }
+
+ return 0;
+}
+
+static int apply_cropping(AVCodecContext *avctx, AVFrame *frame)
+{
+ /* make sure we are noisy about decoders returning invalid cropping data */
+ if (frame->crop_left >= INT_MAX - frame->crop_right ||
+ frame->crop_top >= INT_MAX - frame->crop_bottom ||
+ (frame->crop_left + frame->crop_right) >= frame->width ||
+ (frame->crop_top + frame->crop_bottom) >= frame->height) {
+ av_log(avctx, AV_LOG_WARNING,
+ "Invalid cropping information set by a decoder: "
+ "%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER"/%"SIZE_SPECIFIER" "
+ "(frame size %dx%d). This is a bug, please report it\n",
+ frame->crop_left, frame->crop_right, frame->crop_top, frame->crop_bottom,
+ frame->width, frame->height);
+ frame->crop_left = 0;
+ frame->crop_right = 0;
+ frame->crop_top = 0;
+ frame->crop_bottom = 0;
+ return 0;
+ }
+
+ if (!avctx->apply_cropping)
+ return 0;
+
+ return av_frame_apply_cropping(frame, avctx->flags & AV_CODEC_FLAG_UNALIGNED ?
+ AV_FRAME_CROP_UNALIGNED : 0);
+}
+
+int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
+{
+ AVCodecInternal *avci = avctx->internal;
+ int ret;
+
+ av_frame_unref(frame);
+
+ if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
+ return AVERROR(EINVAL);
+
+ ret = bsfs_init(avctx);
+ if (ret < 0)
+ return ret;
+
+ if (avci->buffer_frame->buf[0]) {
+ av_frame_move_ref(frame, avci->buffer_frame);
+ } else {
+ ret = decode_receive_frame_internal(avctx, frame);
+ if (ret < 0)
+ return ret;
+ }
+
+ if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
+ ret = apply_cropping(avctx, frame);
+ if (ret < 0) {
+ av_frame_unref(frame);
+ return ret;
+ }
+ }
+
+ avctx->frame_number++;
+
+ return 0;
+}
+
+static int compat_decode(AVCodecContext *avctx, AVFrame *frame,
+ int *got_frame, const AVPacket *pkt)
+{
+ AVCodecInternal *avci = avctx->internal;
+ int ret = 0;
+
+ av_assert0(avci->compat_decode_consumed == 0);
+
+ if (avci->draining_done && pkt && pkt->size != 0) {
+ av_log(avctx, AV_LOG_WARNING, "Got unexpected packet after EOF\n");
+ avcodec_flush_buffers(avctx);
+ }
+
+ *got_frame = 0;
+ avci->compat_decode = 1;
+
+ if (avci->compat_decode_partial_size > 0 &&
+ avci->compat_decode_partial_size != pkt->size) {
+ av_log(avctx, AV_LOG_ERROR,
+ "Got unexpected packet size after a partial decode\n");
+ ret = AVERROR(EINVAL);
+ goto finish;
+ }
+
+ if (!avci->compat_decode_partial_size) {
+ ret = avcodec_send_packet(avctx, pkt);
+ if (ret == AVERROR_EOF)
+ ret = 0;
+ else if (ret == AVERROR(EAGAIN)) {
+ /* we fully drain all the output in each decode call, so this should not
+ * ever happen */
+ ret = AVERROR_BUG;
+ goto finish;
+ } else if (ret < 0)
+ goto finish;
+ }
+
+ while (ret >= 0) {
+ ret = avcodec_receive_frame(avctx, frame);
+ if (ret < 0) {
+ if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
+ ret = 0;
+ goto finish;
+ }
+
+ if (frame != avci->compat_decode_frame) {
+ if (!avctx->refcounted_frames) {
+ ret = unrefcount_frame(avci, frame);
+ if (ret < 0)
+ goto finish;
+ }
+
+ *got_frame = 1;
+ frame = avci->compat_decode_frame;
+ } else {
+ if (!avci->compat_decode_warned) {
+ av_log(avctx, AV_LOG_WARNING, "The deprecated avcodec_decode_* "
+ "API cannot return all the frames for this decoder. "
+ "Some frames will be dropped. Update your code to the "
+ "new decoding API to fix this.\n");
+ avci->compat_decode_warned = 1;
+ }
+ }
+
+ if (avci->draining || (!avctx->codec->bsfs && avci->compat_decode_consumed < pkt->size))
+ break;
+ }
+
+finish:
+ if (ret == 0) {
+ /* if there are any bsfs then assume full packet is always consumed */
+ if (avctx->codec->bsfs)
+ ret = pkt->size;
+ else
+ ret = FFMIN(avci->compat_decode_consumed, pkt->size);
+ }
+ avci->compat_decode_consumed = 0;
+ avci->compat_decode_partial_size = (ret >= 0) ? pkt->size - ret : 0;
+
+ return ret;
+}
+
+int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
+ int *got_picture_ptr,
+ const AVPacket *avpkt)
+{
+ return compat_decode(avctx, picture, got_picture_ptr, avpkt);
+}
+
+int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
+ AVFrame *frame,
+ int *got_frame_ptr,
+ const AVPacket *avpkt)
+{
+ return compat_decode(avctx, frame, got_frame_ptr, avpkt);
+}
+
+static void get_subtitle_defaults(AVSubtitle *sub)
+{
+ memset(sub, 0, sizeof(*sub));
+ sub->pts = AV_NOPTS_VALUE;
+}
+
+#define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
+static int recode_subtitle(AVCodecContext *avctx,
+ AVPacket *outpkt, const AVPacket *inpkt)
+{
+#if CONFIG_ICONV
+ iconv_t cd = (iconv_t)-1;
+ int ret = 0;
+ char *inb, *outb;
+ size_t inl, outl;
+ AVPacket tmp;
+#endif
+
+ if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
+ return 0;
+
+#if CONFIG_ICONV
+ cd = iconv_open("UTF-8", avctx->sub_charenc);
+ av_assert0(cd != (iconv_t)-1);
+
+ inb = inpkt->data;
+ inl = inpkt->size;
+
+ if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
+ av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
+ ret = AVERROR(ENOMEM);
+ goto end;
+ }
+
+ ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
+ if (ret < 0)
+ goto end;
+ outpkt->buf = tmp.buf;
+ outpkt->data = tmp.data;
+ outpkt->size = tmp.size;
+ outb = outpkt->data;
+ outl = outpkt->size;
+
+ if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
+ iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
+ outl >= outpkt->size || inl != 0) {
+ ret = FFMIN(AVERROR(errno), -1);
+ av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
+ "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
+ av_packet_unref(&tmp);
+ goto end;
+ }
+ outpkt->size -= outl;
+ memset(outpkt->data + outpkt->size, 0, outl);
+
+end:
+ if (cd != (iconv_t)-1)
+ iconv_close(cd);
+ return ret;
+#else
+ av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
+ return AVERROR(EINVAL);
+#endif
+}
+
+static int utf8_check(const uint8_t *str)
+{
+ const uint8_t *byte;
+ uint32_t codepoint, min;
+
+ while (*str) {
+ byte = str;
+ GET_UTF8(codepoint, *(byte++), return 0;);
+ min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
+ 1 << (5 * (byte - str) - 4);
+ if (codepoint < min || codepoint >= 0x110000 ||
+ codepoint == 0xFFFE /* BOM */ ||
+ codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
+ return 0;
+ str = byte;
+ }
+ return 1;
+}
+
+#if FF_API_ASS_TIMING
+static void insert_ts(AVBPrint *buf, int ts)
+{
+ if (ts == -1) {
+ av_bprintf(buf, "9:59:59.99,");
+ } else {
+ int h, m, s;
+
+ h = ts/360000; ts -= 360000*h;
+ m = ts/ 6000; ts -= 6000*m;
+ s = ts/ 100; ts -= 100*s;
+ av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
+ }
+}
+
+static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
+{
+ int i;
+ AVBPrint buf;
+
+ av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
+
+ for (i = 0; i < sub->num_rects; i++) {
+ char *final_dialog;
+ const char *dialog;
+ AVSubtitleRect *rect = sub->rects[i];
+ int ts_start, ts_duration = -1;
+ long int layer;
+
+ if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
+ continue;
+
+ av_bprint_clear(&buf);
+
+ /* skip ReadOrder */
+ dialog = strchr(rect->ass, ',');
+ if (!dialog)
+ continue;
+ dialog++;
+
+ /* extract Layer or Marked */
+ layer = strtol(dialog, (char**)&dialog, 10);
+ if (*dialog != ',')
+ continue;
+ dialog++;
+
+ /* rescale timing to ASS time base (ms) */
+ ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
+ if (pkt->duration != -1)
+ ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
+ sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
+
+ /* construct ASS (standalone file form with timestamps) string */
+ av_bprintf(&buf, "Dialogue: %ld,", layer);
+ insert_ts(&buf, ts_start);
+ insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
+ av_bprintf(&buf, "%s\r\n", dialog);
+
+ final_dialog = av_strdup(buf.str);
+ if (!av_bprint_is_complete(&buf) || !final_dialog) {
+ av_freep(&final_dialog);
+ av_bprint_finalize(&buf, NULL);
+ return AVERROR(ENOMEM);
+ }
+ av_freep(&rect->ass);
+ rect->ass = final_dialog;
+ }
+
+ av_bprint_finalize(&buf, NULL);
+ return 0;
+}
+#endif
+
+int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
+ int *got_sub_ptr,
+ AVPacket *avpkt)
+{
+ int i, ret = 0;
+ AVCodecInternal *avci = avctx->internal;
+
+ if (!avpkt->data && avpkt->size) {
+ av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
+ return AVERROR(EINVAL);
+ }
+ if (!avctx->codec)
+ return AVERROR(EINVAL);
+ if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
+ av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
+ return AVERROR(EINVAL);
+ }
+
+ *got_sub_ptr = 0;
+ get_subtitle_defaults(sub);
+
+ if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
+ AVPacket pkt_recoded;
+ AVPacket tmp = *avpkt;
+#if FF_API_MERGE_SD
+FF_DISABLE_DEPRECATION_WARNINGS
+ int did_split = avci->compat_decode_partial_size ?
+ ff_packet_split_and_drop_side_data(&tmp) :
+ av_packet_split_side_data(&tmp);
+ //apply_param_change(avctx, &tmp);
+
+ if (did_split) {
+ /* FFMIN() prevents overflow in case the packet wasn't allocated with
+ * proper padding.
+ * If the side data is smaller than the buffer padding size, the
+ * remaining bytes should have already been filled with zeros by the
+ * original packet allocation anyway. */
+ memset(tmp.data + tmp.size, 0,
+ FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
+ }
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
+
+ pkt_recoded = tmp;
+ ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
+ if (ret < 0) {
+ *got_sub_ptr = 0;
+ } else {
+ ret = extract_packet_props(avctx->internal, &pkt_recoded);
+ if (ret < 0)
+ return ret;
+
+ if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
+ sub->pts = av_rescale_q(avpkt->pts,
+ avctx->pkt_timebase, AV_TIME_BASE_Q);
+ ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
+ av_assert1((ret >= 0) >= !!*got_sub_ptr &&
+ !!*got_sub_ptr >= !!sub->num_rects);
+
+#if FF_API_ASS_TIMING
+ if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
+ && *got_sub_ptr && sub->num_rects) {
+ const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
+ : avctx->time_base;
+ int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
+ if (err < 0)
+ ret = err;
+ }
+#endif
+
+ if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
+ avctx->pkt_timebase.num) {
+ AVRational ms = { 1, 1000 };
+ sub->end_display_time = av_rescale_q(avpkt->duration,
+ avctx->pkt_timebase, ms);
+ }
+
+ if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
+ sub->format = 0;
+ else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
+ sub->format = 1;
+
+ for (i = 0; i < sub->num_rects; i++) {
+ if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
+ av_log(avctx, AV_LOG_ERROR,
+ "Invalid UTF-8 in decoded subtitles text; "
+ "maybe missing -sub_charenc option\n");
+ avsubtitle_free(sub);
+ ret = AVERROR_INVALIDDATA;
+ break;
+ }
+ }
+
+ if (tmp.data != pkt_recoded.data) { // did we recode?
+ /* prevent from destroying side data from original packet */
+ pkt_recoded.side_data = NULL;
+ pkt_recoded.side_data_elems = 0;
+
+ av_packet_unref(&pkt_recoded);
+ }
+ }
+
+#if FF_API_MERGE_SD
+ if (did_split) {
+ av_packet_free_side_data(&tmp);
+ if(ret == tmp.size)
+ ret = avpkt->size;
+ }
+#endif
+
+ if (*got_sub_ptr)
+ avctx->frame_number++;
+ }
+
+ return ret;
+}
+
+static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
+{
+ const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+ return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
+}
+
+enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
+{
+ while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
+ ++fmt;
+ return fmt[0];
+}
+
+static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
+ enum AVPixelFormat pix_fmt)
+{
+ AVHWAccel *hwaccel = NULL;
+
+ while ((hwaccel = av_hwaccel_next(hwaccel)))
+ if (hwaccel->id == codec_id
+ && hwaccel->pix_fmt == pix_fmt)
+ return hwaccel;
+ return NULL;
+}
+
+static int setup_hwaccel(AVCodecContext *avctx,
+ const enum AVPixelFormat fmt,
+ const char *name)
+{
+ AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
+ int ret = 0;
+
+ if (!hwa) {
+ av_log(avctx, AV_LOG_ERROR,
+ "Could not find an AVHWAccel for the pixel format: %s",
+ name);
+ return AVERROR(ENOENT);
+ }
+
+ if (hwa->capabilities & AV_HWACCEL_CODEC_CAP_EXPERIMENTAL &&
+ avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
+ av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
+ hwa->name);
+ return AVERROR_PATCHWELCOME;
+ }
+
+ if (hwa->priv_data_size) {
+ avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
+ if (!avctx->internal->hwaccel_priv_data)
+ return AVERROR(ENOMEM);
+ }
+
+ avctx->hwaccel = hwa;
+ if (hwa->init) {
+ ret = hwa->init(avctx);
+ if (ret < 0) {
+ av_freep(&avctx->internal->hwaccel_priv_data);
+ avctx->hwaccel = NULL;
+ return ret;
+ }
+ }
+
+ return 0;
+}
+
+int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
+{
+ const AVPixFmtDescriptor *desc;
+ enum AVPixelFormat *choices;
+ enum AVPixelFormat ret;
+ unsigned n = 0;
+
+ while (fmt[n] != AV_PIX_FMT_NONE)
+ ++n;
+
+ av_assert0(n >= 1);
+ avctx->sw_pix_fmt = fmt[n - 1];
+ av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
+
+ choices = av_malloc_array(n + 1, sizeof(*choices));
+ if (!choices)
+ return AV_PIX_FMT_NONE;
+
+ memcpy(choices, fmt, (n + 1) * sizeof(*choices));
+
+ for (;;) {
+ if (avctx->hwaccel && avctx->hwaccel->uninit)
+ avctx->hwaccel->uninit(avctx);
+ av_freep(&avctx->internal->hwaccel_priv_data);
+ avctx->hwaccel = NULL;
+
+ av_buffer_unref(&avctx->hw_frames_ctx);
+
+ ret = avctx->get_format(avctx, choices);
+
+ desc = av_pix_fmt_desc_get(ret);
+ if (!desc) {
+ ret = AV_PIX_FMT_NONE;
+ break;
+ }
+
+ if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
+ break;
+#if FF_API_CAP_VDPAU
+ if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
+ break;
+#endif
+
+ if (avctx->hw_frames_ctx) {
+ AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
+ if (hw_frames_ctx->format != ret) {
+ av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
+ "does not match the format of provided AVHWFramesContext\n");
+ ret = AV_PIX_FMT_NONE;
+ break;
+ }
+ }
+
+ if (!setup_hwaccel(avctx, ret, desc->name))
+ break;
+
+ /* Remove failed hwaccel from choices */
+ for (n = 0; choices[n] != ret; n++)
+ av_assert0(choices[n] != AV_PIX_FMT_NONE);
+
+ do
+ choices[n] = choices[n + 1];
+ while (choices[n++] != AV_PIX_FMT_NONE);
+ }
+
+ av_freep(&choices);
+ return ret;
+}
+
+static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
+{
+ FramePool *pool = avctx->internal->pool;
+ int i, ret;
+
+ switch (avctx->codec_type) {
+ case AVMEDIA_TYPE_VIDEO: {
+ uint8_t *data[4];
+ int linesize[4];
+ int size[4] = { 0 };
+ int w = frame->width;
+ int h = frame->height;
+ int tmpsize, unaligned;
+
+ if (pool->format == frame->format &&
+ pool->width == frame->width && pool->height == frame->height)
+ return 0;
+
+ avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
+
+ do {
+ // NOTE: do not align linesizes individually, this breaks e.g. assumptions
+ // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
+ ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
+ if (ret < 0)
+ return ret;
+ // increase alignment of w for next try (rhs gives the lowest bit set in w)
+ w += w & ~(w - 1);
+
+ unaligned = 0;
+ for (i = 0; i < 4; i++)
+ unaligned |= linesize[i] % pool->stride_align[i];
+ } while (unaligned);
+
+ tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
+ NULL, linesize);
+ if (tmpsize < 0)
+ return -1;
+
+ for (i = 0; i < 3 && data[i + 1]; i++)
+ size[i] = data[i + 1] - data[i];
+ size[i] = tmpsize - (data[i] - data[0]);
+
+ for (i = 0; i < 4; i++) {
+ av_buffer_pool_uninit(&pool->pools[i]);
+ pool->linesize[i] = linesize[i];
+ if (size[i]) {
+ pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
+ CONFIG_MEMORY_POISONING ?
+ NULL :
+ av_buffer_allocz);
+ if (!pool->pools[i]) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ }
+ }
+ pool->format = frame->format;
+ pool->width = frame->width;
+ pool->height = frame->height;
+
+ break;
+ }
+ case AVMEDIA_TYPE_AUDIO: {
+ int ch = frame->channels; //av_get_channel_layout_nb_channels(frame->channel_layout);
+ int planar = av_sample_fmt_is_planar(frame->format);
+ int planes = planar ? ch : 1;
+
+ if (pool->format == frame->format && pool->planes == planes &&
+ pool->channels == ch && frame->nb_samples == pool->samples)
+ return 0;
+
+ av_buffer_pool_uninit(&pool->pools[0]);
+ ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
+ frame->nb_samples, frame->format, 0);
+ if (ret < 0)
+ goto fail;
+
+ pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
+ if (!pool->pools[0]) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+
+ pool->format = frame->format;
+ pool->planes = planes;
+ pool->channels = ch;
+ pool->samples = frame->nb_samples;
+ break;
+ }
+ default: av_assert0(0);
+ }
+ return 0;
+fail:
+ for (i = 0; i < 4; i++)
+ av_buffer_pool_uninit(&pool->pools[i]);
+ pool->format = -1;
+ pool->planes = pool->channels = pool->samples = 0;
+ pool->width = pool->height = 0;
+ return ret;
+}
+
+static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
+{
+ FramePool *pool = avctx->internal->pool;
+ int planes = pool->planes;
+ int i;
+
+ frame->linesize[0] = pool->linesize[0];
+
+ if (planes > AV_NUM_DATA_POINTERS) {
+ frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
+ frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
+ frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
+ sizeof(*frame->extended_buf));
+ if (!frame->extended_data || !frame->extended_buf) {
+ av_freep(&frame->extended_data);
+ av_freep(&frame->extended_buf);
+ return AVERROR(ENOMEM);
+ }
+ } else {
+ frame->extended_data = frame->data;
+ av_assert0(frame->nb_extended_buf == 0);
+ }
+
+ for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
+ frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
+ if (!frame->buf[i])
+ goto fail;
+ frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
+ }
+ for (i = 0; i < frame->nb_extended_buf; i++) {
+ frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
+ if (!frame->extended_buf[i])
+ goto fail;
+ frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
+ }
+
+ if (avctx->debug & FF_DEBUG_BUFFERS)
+ av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
+
+ return 0;
+fail:
+ av_frame_unref(frame);
+ return AVERROR(ENOMEM);
+}
+
+static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
+{
+ FramePool *pool = s->internal->pool;
+ const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
+ int i;
+
+ if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
+ av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
+ return -1;
+ }
+
+ if (!desc) {
+ av_log(s, AV_LOG_ERROR,
+ "Unable to get pixel format descriptor for format %s\n",
+ av_get_pix_fmt_name(pic->format));
+ return AVERROR(EINVAL);
+ }
+
+ memset(pic->data, 0, sizeof(pic->data));
+ pic->extended_data = pic->data;
+
+ for (i = 0; i < 4 && pool->pools[i]; i++) {
+ pic->linesize[i] = pool->linesize[i];
+
+ pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
+ if (!pic->buf[i])
+ goto fail;
+
+ pic->data[i] = pic->buf[i]->data;
+ }
+ for (; i < AV_NUM_DATA_POINTERS; i++) {
+ pic->data[i] = NULL;
+ pic->linesize[i] = 0;
+ }
+ if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
+ desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
+ avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
+
+ if (s->debug & FF_DEBUG_BUFFERS)
+ av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
+
+ return 0;
+fail:
+ av_frame_unref(pic);
+ return AVERROR(ENOMEM);
+}
+
+int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
+{
+ int ret;
+
+ if (avctx->hw_frames_ctx) {
+ ret = av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
+ frame->width = avctx->coded_width;
+ frame->height = avctx->coded_height;
+ return ret;
+ }
+
+ if ((ret = update_frame_pool(avctx, frame)) < 0)
+ return ret;
+
+ switch (avctx->codec_type) {
+ case AVMEDIA_TYPE_VIDEO:
+ return video_get_buffer(avctx, frame);
+ case AVMEDIA_TYPE_AUDIO:
+ return audio_get_buffer(avctx, frame);
+ default:
+ return -1;
+ }
+}
+
+static int add_metadata_from_side_data(const AVPacket *avpkt, AVFrame *frame)
+{
+ int size;
+ const uint8_t *side_metadata;
+
+ AVDictionary **frame_md = &frame->metadata;
+
+ side_metadata = av_packet_get_side_data(avpkt,
+ AV_PKT_DATA_STRINGS_METADATA, &size);
+ return av_packet_unpack_dictionary(side_metadata, size, frame_md);
+}
+
+int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
+{
+ const AVPacket *pkt = avctx->internal->last_pkt_props;
+ int i;
+ static const struct {
+ enum AVPacketSideDataType packet;
+ enum AVFrameSideDataType frame;
+ } sd[] = {
+ { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
+ { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
+ { AV_PKT_DATA_SPHERICAL, AV_FRAME_DATA_SPHERICAL },
+ { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
+ { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
+ { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
+ { AV_PKT_DATA_CONTENT_LIGHT_LEVEL, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL },
+ { AV_PKT_DATA_A53_CC, AV_FRAME_DATA_A53_CC },
+ };
+
+ if (pkt) {
+ frame->pts = pkt->pts;
+#if FF_API_PKT_PTS
+FF_DISABLE_DEPRECATION_WARNINGS
+ frame->pkt_pts = pkt->pts;
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
+ frame->pkt_pos = pkt->pos;
+ frame->pkt_duration = pkt->duration;
+ frame->pkt_size = pkt->size;
+
+ for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
+ int size;
+ uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
+ if (packet_sd) {
+ AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
+ sd[i].frame,
+ size);
+ if (!frame_sd)
+ return AVERROR(ENOMEM);
+
+ memcpy(frame_sd->data, packet_sd, size);
+ }
+ }
+ add_metadata_from_side_data(pkt, frame);
+
+ if (pkt->flags & AV_PKT_FLAG_DISCARD) {
+ frame->flags |= AV_FRAME_FLAG_DISCARD;
+ } else {
+ frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
+ }
+ }
+ frame->reordered_opaque = avctx->reordered_opaque;
+
+ if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
+ frame->color_primaries = avctx->color_primaries;
+ if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
+ frame->color_trc = avctx->color_trc;
+ if (frame->colorspace == AVCOL_SPC_UNSPECIFIED)
+ frame->colorspace = avctx->colorspace;
+ if (frame->color_range == AVCOL_RANGE_UNSPECIFIED)
+ frame->color_range = avctx->color_range;
+ if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
+ frame->chroma_location = avctx->chroma_sample_location;
+
+ switch (avctx->codec->type) {
+ case AVMEDIA_TYPE_VIDEO:
+ frame->format = avctx->pix_fmt;
+ if (!frame->sample_aspect_ratio.num)
+ frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
+
+ if (frame->width && frame->height &&
+ av_image_check_sar(frame->width, frame->height,
+ frame->sample_aspect_ratio) < 0) {
+ av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
+ frame->sample_aspect_ratio.num,
+ frame->sample_aspect_ratio.den);
+ frame->sample_aspect_ratio = (AVRational){ 0, 1 };
+ }
+
+ break;
+ case AVMEDIA_TYPE_AUDIO:
+ if (!frame->sample_rate)
+ frame->sample_rate = avctx->sample_rate;
+ if (frame->format < 0)
+ frame->format = avctx->sample_fmt;
+ if (!frame->channel_layout) {
+ if (avctx->channel_layout) {
+ if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
+ avctx->channels) {
+ av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
+ "configuration.\n");
+ return AVERROR(EINVAL);
+ }
+
+ frame->channel_layout = avctx->channel_layout;
+ } else {
+ if (avctx->channels > FF_SANE_NB_CHANNELS) {
+ av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
+ avctx->channels);
+ return AVERROR(ENOSYS);
+ }
+ }
+ }
+ frame->channels = avctx->channels;
+ break;
+ }
+ return 0;
+}
+
+int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
+{
+ return ff_init_buffer_info(avctx, frame);
+}
+
+static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
+{
+ if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
+ int i;
+ int num_planes = av_pix_fmt_count_planes(frame->format);
+ const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
+ int flags = desc ? desc->flags : 0;
+ if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
+ num_planes = 2;
+ for (i = 0; i < num_planes; i++) {
+ av_assert0(frame->data[i]);
+ }
+ // For now do not enforce anything for palette of pseudopal formats
+ if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
+ num_planes = 2;
+ // For formats without data like hwaccel allow unused pointers to be non-NULL.
+ for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
+ if (frame->data[i])
+ av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
+ frame->data[i] = NULL;
+ }
+ }
+}
+
+static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
+{
+ const AVHWAccel *hwaccel = avctx->hwaccel;
+ int override_dimensions = 1;
+ int ret;
+
+ if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
+ if ((ret = av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx)) < 0 || avctx->pix_fmt<0) {
+ av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
+ return AVERROR(EINVAL);
+ }
+
+ if (frame->width <= 0 || frame->height <= 0) {
+ frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
+ frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
+ override_dimensions = 0;
+ }
+
+ if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
+ av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
+ return AVERROR(EINVAL);
+ }
+ }
+ ret = ff_decode_frame_props(avctx, frame);
+ if (ret < 0)
+ return ret;
+
+ if (hwaccel) {
+ if (hwaccel->alloc_frame) {
+ ret = hwaccel->alloc_frame(avctx, frame);
+ goto end;
+ }
+ } else
+ avctx->sw_pix_fmt = avctx->pix_fmt;
+
+ ret = avctx->get_buffer2(avctx, frame, flags);
+ if (ret >= 0)
+ validate_avframe_allocation(avctx, frame);
+
+end:
+ if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions &&
+ !(avctx->codec->caps_internal & FF_CODEC_CAP_EXPORTS_CROPPING)) {
+ frame->width = avctx->width;
+ frame->height = avctx->height;
+ }
+
+ return ret;
+}
+
+int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
+{
+ int ret = get_buffer_internal(avctx, frame, flags);
+ if (ret < 0) {
+ av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
+ frame->width = frame->height = 0;
+ }
+ return ret;
+}
+
+static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
+{
+ AVFrame *tmp;
+ int ret;
+
+ av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
+
+ if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
+ av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
+ frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
+ av_frame_unref(frame);
+ }
+
+ ff_init_buffer_info(avctx, frame);
+
+ if (!frame->data[0])
+ return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
+
+ if (av_frame_is_writable(frame))
+ return ff_decode_frame_props(avctx, frame);
+
+ tmp = av_frame_alloc();
+ if (!tmp)
+ return AVERROR(ENOMEM);
+
+ av_frame_move_ref(tmp, frame);
+
+ ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
+ if (ret < 0) {
+ av_frame_free(&tmp);
+ return ret;
+ }
+
+ av_frame_copy(frame, tmp);
+ av_frame_free(&tmp);
+
+ return 0;
+}
+
+int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
+{
+ int ret = reget_buffer_internal(avctx, frame);
+ if (ret < 0)
+ av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
+ return ret;
+}
+
+void avcodec_flush_buffers(AVCodecContext *avctx)
+{
+ avctx->internal->draining = 0;
+ avctx->internal->draining_done = 0;
+ avctx->internal->nb_draining_errors = 0;
+ av_frame_unref(avctx->internal->buffer_frame);
+ av_frame_unref(avctx->internal->compat_decode_frame);
+ av_packet_unref(avctx->internal->buffer_pkt);
+ avctx->internal->buffer_pkt_valid = 0;
+
+ av_packet_unref(avctx->internal->ds.in_pkt);
+
+ if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
+ ff_thread_flush(avctx);
+ else if (avctx->codec->flush)
+ avctx->codec->flush(avctx);
+
+ avctx->pts_correction_last_pts =
+ avctx->pts_correction_last_dts = INT64_MIN;
+
+ ff_decode_bsfs_uninit(avctx);
+
+ if (!avctx->refcounted_frames)
+ av_frame_unref(avctx->internal->to_free);
+}
+
+void ff_decode_bsfs_uninit(AVCodecContext *avctx)
+{
+ DecodeFilterContext *s = &avctx->internal->filter;
+ int i;
+
+ for (i = 0; i < s->nb_bsfs; i++)
+ av_bsf_free(&s->bsfs[i]);
+ av_freep(&s->bsfs);
+ s->nb_bsfs = 0;
+}
diff --git a/media/ffvpx/libavcodec/decode.h b/media/ffvpx/libavcodec/decode.h
new file mode 100644
index 000000000..c9630228d
--- /dev/null
+++ b/media/ffvpx/libavcodec/decode.h
@@ -0,0 +1,39 @@
+/*
+ * generic decoding-related code
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_DECODE_H
+#define AVCODEC_DECODE_H
+
+#include "avcodec.h"
+
+/**
+ * Called by decoders to get the next packet for decoding.
+ *
+ * @param pkt An empty packet to be filled with data.
+ * @return 0 if a new reference has been successfully written to pkt
+ * AVERROR(EAGAIN) if no data is currently available
+ * AVERROR_EOF if and end of stream has been reached, so no more data
+ * will be available
+ */
+int ff_decode_get_packet(AVCodecContext *avctx, AVPacket *pkt);
+
+void ff_decode_bsfs_uninit(AVCodecContext *avctx);
+
+#endif /* AVCODEC_DECODE_H */
diff --git a/media/ffvpx/libavcodec/dummy_funcs.c b/media/ffvpx/libavcodec/dummy_funcs.c
index 200e1d266..21b469f7e 100644
--- a/media/ffvpx/libavcodec/dummy_funcs.c
+++ b/media/ffvpx/libavcodec/dummy_funcs.c
@@ -73,6 +73,16 @@ AVHWAccel ff_hevc_mediacodec_hwaccel;
AVHWAccel ff_mpeg4_mediacodec_hwaccel;
AVHWAccel ff_vp8_mediacodec_hwaccel;
AVHWAccel ff_vp9_mediacodec_hwaccel;
+/* Added by FFmpeg 3.4 */
+AVHWAccel ff_h264_d3d11va2_hwaccel;
+AVHWAccel ff_hevc_d3d11va2_hwaccel;
+AVHWAccel ff_hevc_videotoolbox_hwaccel;
+AVHWAccel ff_mpeg2_d3d11va2_hwaccel;
+AVHWAccel ff_mpeg2_mediacodec_hwaccel;
+AVHWAccel ff_vc1_d3d11va2_hwaccel;
+AVHWAccel ff_vp8_qsv_hwaccel;
+AVHWAccel ff_vp9_d3d11va2_hwaccel;
+AVHWAccel ff_wmv3_d3d11va2_hwaccel;
AVCodec ff_a64multi_encoder;
AVCodec ff_a64multi5_encoder;
@@ -741,6 +751,54 @@ AVCodec ff_pcm_s64be_decoder;
AVCodec ff_pcm_s64be_encoder;
AVCodec ff_truehd_encoder;
AVCodec ff_mlp_encoder;
+/* Added by FFmpeg 3.4 */
+AVCodec ff_clearvideo_decoder;
+AVCodec ff_fits_encoder;
+AVCodec ff_fits_decoder;
+AVCodec ff_fmvc_decoder;
+AVCodec ff_gdv_decoder;
+AVCodec ff_h263_v4l2m2m_decoder;
+AVCodec ff_h264_v4l2m2m_decoder;
+AVCodec ff_h264_rkmpp_decoder;
+AVCodec ff_hevc_rkmpp_decoder;
+AVCodec ff_hevc_v4l2m2m_decoder;
+AVCodec ff_mpeg4_v4l2m2m_decoder;
+AVCodec ff_mpeg1_v4l2m2m_decoder;
+AVCodec ff_mpeg2_v4l2m2m_decoder;
+AVCodec ff_mpeg2_mediacodec_decoder;
+AVCodec ff_mscc_decoder;
+AVCodec ff_pixlet_decoder;
+AVCodec ff_psd_decoder;
+AVCodec ff_scpr_decoder;
+AVCodec ff_speedhq_decoder;
+AVCodec ff_srgc_decoder;
+AVCodec ff_vc1_v4l2m2m_decoder;
+AVCodec ff_vp8_rkmpp_decoder;
+AVCodec ff_vp8_v4l2m2m_decoder;
+AVCodec ff_vp9_rkmpp_decoder;
+AVCodec ff_vp9_v4l2m2m_decoder;
+AVCodec ff_bitpacked_decoder;
+AVCodec ff_wrapped_avframe_decoder;
+AVCodec ff_xpm_decoder;
+AVCodec ff_atrac3al_decoder;
+AVCodec ff_atrac3pal_decoder;
+AVCodec ff_dolby_e_decoder;
+AVCodec ff_opus_encoder;
+AVCodec ff_qdmc_decoder;
+AVCodec ff_pcm_f16le_decoder;
+AVCodec ff_pcm_f24le_decoder;
+AVCodec ff_gremlin_dpcm_decoder;
+AVCodec ff_adpcm_g726le_encoder;
+AVCodec ff_librsvg_decoder;
+AVCodec ff_h263_v4l2m2m_encoder;
+AVCodec ff_h264_v4l2m2m_encoder;
+AVCodec ff_hevc_v4l2m2m_encoder;
+AVCodec ff_mpeg2_vaapi_encoder;
+AVCodec ff_mpeg4_v4l2m2m_encoder;
+AVCodec ff_vp8_qsv_decoder;
+AVCodec ff_vp8_v4l2m2m_encoder;
+AVCodec ff_vp8_vaapi_encoder;
+AVCodec ff_vp9_vaapi_encoder;
AVCodecParser ff_aac_parser;
AVCodecParser ff_aac_latm_parser;
@@ -777,6 +835,10 @@ AVCodecParser ff_tak_parser;
AVCodecParser ff_vc1_parser;
AVCodecParser ff_vorbis_parser;
AVCodecParser ff_vp3_parser;
+/* Added by FFmpeg 3.4 */
+AVCodecParser ff_sipr_parser;
+AVCodecParser ff_xma_parser;
+
AVBitStreamFilter ff_aac_adtstoasc_bsf;
AVBitStreamFilter ff_chomp_bsf;
AVBitStreamFilter ff_dump_extradata_bsf;
@@ -806,12 +868,15 @@ int ff_thread_video_encode_frame(AVCodecContext *avctx, AVPacket *pkt, const AVF
void ff_videodsp_init_aarch64(VideoDSPContext *ctx, int bpc) {}
void ff_videodsp_init_arm(VideoDSPContext *ctx, int bpc) {}
void ff_videodsp_init_ppc(VideoDSPContext *ctx, int bpc) {}
+void ff_videodsp_init_mips(VideoDSPContext *ctx, int bpc) {}
void ff_vp7dsp_init(VP8DSPContext *c) {}
void ff_vp78dsp_init_arm(VP8DSPContext *c) {}
void ff_vp78dsp_init_ppc(VP8DSPContext *c) {}
void ff_vp8dsp_init_arm(VP8DSPContext *c) {}
void ff_vp8dsp_init_mips(VP8DSPContext *c) {}
void ff_vp9dsp_init_mips(VP9DSPContext *dsp, int bpp) {}
+void ff_vp9dsp_init_aarch64(VP9DSPContext *dsp, int bpp) {}
+void ff_vp9dsp_init_arm(VP9DSPContext *dsp, int bpp) {}
void ff_flacdsp_init_arm(FLACDSPContext *c, enum AVSampleFormat fmt, int channels, int bps) {}
#if !defined(HAVE_64BIT_BUILD)
void ff_flac_decorrelate_indep8_16_sse2(uint8_t **out, int32_t **in, int channels, int len, int shift) {}
@@ -819,11 +884,3 @@ void ff_flac_decorrelate_indep8_32_avx(uint8_t **out, int32_t **in, int channels
void ff_flac_decorrelate_indep8_16_avx(uint8_t **out, int32_t **in, int channels, int len, int shift) {}
void ff_flac_decorrelate_indep8_32_sse2(uint8_t **out, int32_t **in, int channels, int len, int shift) {}
#endif
-void av_bitstream_filter_close(AVBitStreamFilterContext *bsf) {}
-int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc,
- AVCodecContext *avctx, const char *args,
- uint8_t **poutbuf, int *poutbuf_size,
- const uint8_t *buf, int buf_size, int keyframe) { return 0; }
-AVBitStreamFilterContext *av_bitstream_filter_init(const char *name) { return NULL;}
-AVBitStreamFilter *av_bitstream_filter_next(const AVBitStreamFilter *f) { return NULL; }
-void av_register_bitstream_filter(AVBitStreamFilter *bsf) {}
diff --git a/media/ffvpx/libavcodec/error_resilience.h b/media/ffvpx/libavcodec/error_resilience.h
index d444ec3a3..27c200869 100644
--- a/media/ffvpx/libavcodec/error_resilience.h
+++ b/media/ffvpx/libavcodec/error_resilience.h
@@ -57,8 +57,8 @@ typedef struct ERContext {
int *mb_index2xy;
int mb_num;
int mb_width, mb_height;
- int mb_stride;
- int b8_stride;
+ ptrdiff_t mb_stride;
+ ptrdiff_t b8_stride;
volatile int error_count;
int error_occurred;
diff --git a/media/ffvpx/libavcodec/flac.c b/media/ffvpx/libavcodec/flac.c
index f5154b914..5ffbf9319 100644
--- a/media/ffvpx/libavcodec/flac.c
+++ b/media/ffvpx/libavcodec/flac.c
@@ -201,7 +201,7 @@ void ff_flac_set_channel_layout(AVCodecContext *avctx)
avctx->channel_layout = 0;
}
-void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
+int ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
const uint8_t *buffer)
{
GetBitContext gb;
@@ -213,6 +213,7 @@ void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
av_log(avctx, AV_LOG_WARNING, "invalid max blocksize: %d\n",
s->max_blocksize);
s->max_blocksize = 16;
+ return AVERROR_INVALIDDATA;
}
skip_bits(&gb, 24); /* skip min frame size */
@@ -222,6 +223,12 @@ void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
s->channels = get_bits(&gb, 3) + 1;
s->bps = get_bits(&gb, 5) + 1;
+ if (s->bps < 4) {
+ av_log(avctx, AV_LOG_ERROR, "invalid bps: %d\n", s->bps);
+ s->bps = 16;
+ return AVERROR_INVALIDDATA;
+ }
+
avctx->channels = s->channels;
avctx->sample_rate = s->samplerate;
avctx->bits_per_raw_sample = s->bps;
@@ -234,4 +241,6 @@ void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
skip_bits_long(&gb, 64); /* md5 sum */
skip_bits_long(&gb, 64); /* md5 sum */
+
+ return 0;
}
diff --git a/media/ffvpx/libavcodec/flac.h b/media/ffvpx/libavcodec/flac.h
index 96d971c9d..991ab43f3 100644
--- a/media/ffvpx/libavcodec/flac.h
+++ b/media/ffvpx/libavcodec/flac.h
@@ -95,8 +95,10 @@ typedef struct FLACFrameInfo {
* @param[out] avctx codec context to set basic stream parameters
* @param[out] s where parsed information is stored
* @param[in] buffer pointer to start of 34-byte streaminfo data
+ *
+ * @return negative error code on faiure or >= 0 on success
*/
-void ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
+int ff_flac_parse_streaminfo(AVCodecContext *avctx, struct FLACStreaminfo *s,
const uint8_t *buffer);
/**
diff --git a/media/ffvpx/libavcodec/flac_parser.c b/media/ffvpx/libavcodec/flac_parser.c
index f5cc35a4f..84da23f32 100644
--- a/media/ffvpx/libavcodec/flac_parser.c
+++ b/media/ffvpx/libavcodec/flac_parser.c
@@ -586,10 +586,12 @@ static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,
temp = curr->next;
av_freep(&curr->link_penalty);
av_free(curr);
+ fpc->nb_headers_buffered--;
}
fpc->headers = fpc->best_header->next;
av_freep(&fpc->best_header->link_penalty);
av_freep(&fpc->best_header);
+ fpc->nb_headers_buffered--;
}
/* Find and score new headers. */
@@ -638,7 +640,7 @@ static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,
read_end - read_start, NULL);
} else {
int8_t pad[MAX_FRAME_HEADER_SIZE] = { 0 };
- av_fifo_generic_write(fpc->fifo_buf, (void*) pad, sizeof(pad), NULL);
+ av_fifo_generic_write(fpc->fifo_buf, pad, sizeof(pad), NULL);
}
/* Tag headers and update sequences. */
diff --git a/media/ffvpx/libavcodec/flacdec.c b/media/ffvpx/libavcodec/flacdec.c
index b7237e18f..3d41a1af7 100644
--- a/media/ffvpx/libavcodec/flacdec.c
+++ b/media/ffvpx/libavcodec/flacdec.c
@@ -109,7 +109,9 @@ static av_cold int flac_decode_init(AVCodecContext *avctx)
return AVERROR_INVALIDDATA;
/* initialize based on the demuxer-supplied streamdata header */
- ff_flac_parse_streaminfo(avctx, &s->flac_stream_info, streaminfo);
+ ret = ff_flac_parse_streaminfo(avctx, &s->flac_stream_info, streaminfo);
+ if (ret < 0)
+ return ret;
ret = allocate_buffers(s);
if (ret < 0)
return ret;
@@ -175,7 +177,9 @@ static int parse_streaminfo(FLACContext *s, const uint8_t *buf, int buf_size)
metadata_size != FLAC_STREAMINFO_SIZE) {
return AVERROR_INVALIDDATA;
}
- ff_flac_parse_streaminfo(s->avctx, &s->flac_stream_info, &buf[8]);
+ ret = ff_flac_parse_streaminfo(s->avctx, &s->flac_stream_info, &buf[8]);
+ if (ret < 0)
+ return ret;
ret = allocate_buffers(s);
if (ret < 0)
return ret;
@@ -201,12 +205,12 @@ static int get_metadata_size(const uint8_t *buf, int buf_size)
buf += 4;
do {
if (buf_end - buf < 4)
- return 0;
+ return AVERROR_INVALIDDATA;
flac_parse_block_header(buf, &metadata_last, NULL, &metadata_size);
buf += 4;
if (buf_end - buf < metadata_size) {
/* need more data in order to read the complete header */
- return 0;
+ return AVERROR_INVALIDDATA;
}
buf += metadata_size;
} while (!metadata_last);
@@ -254,8 +258,15 @@ static int decode_residuals(FLACContext *s, int32_t *decoded, int pred_order)
for (; i < samples; i++)
*decoded++ = get_sbits_long(&s->gb, tmp);
} else {
+ int real_limit = tmp ? (INT_MAX >> tmp) + 2 : INT_MAX;
for (; i < samples; i++) {
- *decoded++ = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);
+ int v = get_sr_golomb_flac(&s->gb, tmp, real_limit, 0);
+ if (v == 0x80000000){
+ av_log(s->avctx, AV_LOG_ERROR, "invalid residual\n");
+ return AVERROR_INVALIDDATA;
+ }
+
+ *decoded++ = v;
}
}
i= 0;
@@ -268,7 +279,8 @@ static int decode_subframe_fixed(FLACContext *s, int32_t *decoded,
int pred_order, int bps)
{
const int blocksize = s->blocksize;
- int av_uninit(a), av_uninit(b), av_uninit(c), av_uninit(d), i;
+ unsigned av_uninit(a), av_uninit(b), av_uninit(c), av_uninit(d);
+ int i;
int ret;
/* warm up samples */
@@ -286,7 +298,7 @@ static int decode_subframe_fixed(FLACContext *s, int32_t *decoded,
if (pred_order > 2)
c = b - decoded[pred_order-2] + decoded[pred_order-3];
if (pred_order > 3)
- d = c - decoded[pred_order-2] + 2*decoded[pred_order-3] - decoded[pred_order-4];
+ d = c - decoded[pred_order-2] + 2U*decoded[pred_order-3] - decoded[pred_order-4];
switch (pred_order) {
case 0:
@@ -315,7 +327,7 @@ static int decode_subframe_fixed(FLACContext *s, int32_t *decoded,
return 0;
}
-static void lpc_analyze_remodulate(int32_t *decoded, const int coeffs[32],
+static void lpc_analyze_remodulate(SUINT32 *decoded, const int coeffs[32],
int order, int qlevel, int len, int bps)
{
int i, j;
@@ -331,7 +343,7 @@ static void lpc_analyze_remodulate(int32_t *decoded, const int coeffs[32],
for (i = len - 1; i >= order; i--) {
int64_t p = 0;
for (j = 0; j < order; j++)
- p += coeffs[j] * (int64_t)decoded[i-order+j];
+ p += coeffs[j] * (int64_t)(int32_t)decoded[i-order+j];
decoded[i] -= p >> qlevel;
}
for (i = order; i < len; i++, decoded++) {
@@ -444,10 +456,10 @@ static inline int decode_subframe(FLACContext *s, int channel)
return AVERROR_INVALIDDATA;
}
- if (wasted) {
+ if (wasted && wasted < 32) {
int i;
for (i = 0; i < s->blocksize; i++)
- decoded[i] <<= wasted;
+ decoded[i] = (unsigned)decoded[i] << wasted;
}
return 0;
diff --git a/media/ffvpx/libavcodec/flacdsp.c b/media/ffvpx/libavcodec/flacdsp.c
index 30b66484e..bc9a5dbed 100644
--- a/media/ffvpx/libavcodec/flacdsp.c
+++ b/media/ffvpx/libavcodec/flacdsp.c
@@ -49,8 +49,8 @@ static void flac_lpc_16_c(int32_t *decoded, const int coeffs[32],
int i, j;
for (i = pred_order; i < len - 1; i += 2, decoded += 2) {
- int c = coeffs[0];
- int d = decoded[0];
+ SUINT c = coeffs[0];
+ SUINT d = decoded[0];
int s0 = 0, s1 = 0;
for (j = 1; j < pred_order; j++) {
s0 += c*d;
@@ -59,15 +59,15 @@ static void flac_lpc_16_c(int32_t *decoded, const int coeffs[32],
c = coeffs[j];
}
s0 += c*d;
- d = decoded[j] += s0 >> qlevel;
+ d = decoded[j] += (SUINT)(s0 >> qlevel);
s1 += c*d;
- decoded[j + 1] += s1 >> qlevel;
+ decoded[j + 1] += (SUINT)(s1 >> qlevel);
}
if (i < len) {
int sum = 0;
for (j = 0; j < pred_order; j++)
- sum += coeffs[j] * decoded[j];
- decoded[j] += sum >> qlevel;
+ sum += coeffs[j] * (SUINT)decoded[j];
+ decoded[j] = decoded[j] + (unsigned)(sum >> qlevel);
}
}
diff --git a/media/ffvpx/libavcodec/flacdsp.h b/media/ffvpx/libavcodec/flacdsp.h
index f5cbd9472..7bb0dd0e9 100644
--- a/media/ffvpx/libavcodec/flacdsp.h
+++ b/media/ffvpx/libavcodec/flacdsp.h
@@ -20,6 +20,7 @@
#define AVCODEC_FLACDSP_H
#include <stdint.h>
+#include "libavutil/internal.h"
#include "libavutil/samplefmt.h"
typedef struct FLACDSPContext {
diff --git a/media/ffvpx/libavcodec/flacdsp_template.c b/media/ffvpx/libavcodec/flacdsp_template.c
index 62c0a15ff..776c78da7 100644
--- a/media/ffvpx/libavcodec/flacdsp_template.c
+++ b/media/ffvpx/libavcodec/flacdsp_template.c
@@ -56,7 +56,7 @@ static void FUNC(flac_decorrelate_indep_c)(uint8_t **out, int32_t **in,
for (j = 0; j < len; j++)
for (i = 0; i < channels; i++)
- S(samples, i, j) = in[i][j] << shift;
+ S(samples, i, j) = (int)((unsigned)in[i][j] << shift);
}
static void FUNC(flac_decorrelate_ls_c)(uint8_t **out, int32_t **in,
diff --git a/media/ffvpx/libavcodec/get_bits.h b/media/ffvpx/libavcodec/get_bits.h
index 0f183e035..0c7f5ff0c 100644
--- a/media/ffvpx/libavcodec/get_bits.h
+++ b/media/ffvpx/libavcodec/get_bits.h
@@ -229,6 +229,20 @@ static inline int get_xbits(GetBitContext *s, int n)
return (NEG_USR32(sign ^ cache, n) ^ sign) - sign;
}
+static inline int get_xbits_le(GetBitContext *s, int n)
+{
+ register int sign;
+ register int32_t cache;
+ OPEN_READER(re, s);
+ av_assert2(n>0 && n<=25);
+ UPDATE_CACHE_LE(re, s);
+ cache = GET_CACHE(re, s);
+ sign = sign_extend(~cache, n) >> 31;
+ LAST_SKIP_BITS(re, s, n);
+ CLOSE_READER(re, s);
+ return (zero_extend(sign ^ cache, n) ^ sign) - sign;
+}
+
static inline int get_sbits(GetBitContext *s, int n)
{
register int tmp;
@@ -331,6 +345,7 @@ static inline void skip_bits1(GetBitContext *s)
*/
static inline unsigned int get_bits_long(GetBitContext *s, int n)
{
+ av_assert2(n>=0 && n<=32);
if (!n) {
return 0;
} else if (n <= MIN_CACHE_BITS) {
@@ -369,6 +384,10 @@ static inline uint64_t get_bits64(GetBitContext *s, int n)
*/
static inline int get_sbits_long(GetBitContext *s, int n)
{
+ // sign_extend(x, 0) is undefined
+ if (!n)
+ return 0;
+
return sign_extend(get_bits_long(s, n), n);
}
@@ -531,6 +550,7 @@ static inline const uint8_t *align_get_bits(GetBitContext *s)
* @param max_depth is the number of times bits bits must be read to completely
* read the longest vlc code
* = (max_vlc_length + bits - 1) / bits
+ * @returns the code parsed or -1 if no vlc matches
*/
static av_always_inline int get_vlc2(GetBitContext *s, VLC_TYPE (*table)[2],
int bits, int max_depth)
diff --git a/media/ffvpx/libavcodec/golomb.h b/media/ffvpx/libavcodec/golomb.h
index 917ea54e1..efb1eff8a 100644
--- a/media/ffvpx/libavcodec/golomb.h
+++ b/media/ffvpx/libavcodec/golomb.h
@@ -314,6 +314,8 @@ static inline int get_ur_golomb_jpegls(GetBitContext *gb, int k, int limit,
log = av_log2(buf);
+ av_assert2(k <= 31);
+
if (log - k >= 32 - MIN_CACHE_BITS + (MIN_CACHE_BITS == 32) &&
32 - log < limit) {
buf >>= log - k;
@@ -325,8 +327,10 @@ static inline int get_ur_golomb_jpegls(GetBitContext *gb, int k, int limit,
} else {
int i;
for (i = 0; i < limit && SHOW_UBITS(re, gb, 1) == 0; i++) {
- if (gb->size_in_bits <= re_index)
+ if (gb->size_in_bits <= re_index) {
+ CLOSE_READER(re, gb);
return -1;
+ }
LAST_SKIP_BITS(re, gb, 1);
UPDATE_CACHE(re, gb);
}
@@ -348,16 +352,17 @@ static inline int get_ur_golomb_jpegls(GetBitContext *gb, int k, int limit,
buf = 0;
}
- CLOSE_READER(re, gb);
- return buf + (i << k);
+ buf += ((SUINT)i << k);
} else if (i == limit - 1) {
buf = SHOW_UBITS(re, gb, esc_len);
LAST_SKIP_BITS(re, gb, esc_len);
- CLOSE_READER(re, gb);
- return buf + 1;
- } else
- return -1;
+ buf ++;
+ } else {
+ buf = -1;
+ }
+ CLOSE_READER(re, gb);
+ return buf;
}
}
@@ -445,19 +450,20 @@ static inline int get_te(GetBitContext *s, int r, char *file, const char *func,
return i;
}
-#define get_ue_golomb(a) get_ue(a, __FILE__, __PRETTY_FUNCTION__, __LINE__)
-#define get_se_golomb(a) get_se(a, __FILE__, __PRETTY_FUNCTION__, __LINE__)
-#define get_te_golomb(a, r) get_te(a, r, __FILE__, __PRETTY_FUNCTION__, __LINE__)
-#define get_te0_golomb(a, r) get_te(a, r, __FILE__, __PRETTY_FUNCTION__, __LINE__)
+#define get_ue_golomb(a) get_ue(a, __FILE__, __func__, __LINE__)
+#define get_se_golomb(a) get_se(a, __FILE__, __func__, __LINE__)
+#define get_te_golomb(a, r) get_te(a, r, __FILE__, __func__, __LINE__)
+#define get_te0_golomb(a, r) get_te(a, r, __FILE__, __func__, __LINE__)
#endif /* TRACE */
/**
- * write unsigned exp golomb code.
+ * write unsigned exp golomb code. 2^16 - 2 at most
*/
static inline void set_ue_golomb(PutBitContext *pb, int i)
{
av_assert2(i >= 0);
+ av_assert2(i <= 0xFFFE);
if (i < 256)
put_bits(pb, ff_ue_golomb_len[i], i + 1);
@@ -468,6 +474,21 @@ static inline void set_ue_golomb(PutBitContext *pb, int i)
}
/**
+ * write unsigned exp golomb code. 2^32-2 at most.
+ */
+static inline void set_ue_golomb_long(PutBitContext *pb, uint32_t i)
+{
+ av_assert2(i <= (UINT32_MAX - 1));
+
+ if (i < 256)
+ put_bits(pb, ff_ue_golomb_len[i], i + 1);
+ else {
+ int e = av_log2(i + 1);
+ put_bits64(pb, 2 * e + 1, i + 1);
+ }
+}
+
+/**
* write truncated unsigned exp golomb code.
*/
static inline void set_te_golomb(PutBitContext *pb, int i, int range)
@@ -486,19 +507,9 @@ static inline void set_te_golomb(PutBitContext *pb, int i, int range)
*/
static inline void set_se_golomb(PutBitContext *pb, int i)
{
-#if 0
- if (i <= 0)
- i = -2 * i;
- else
- i = 2 * i - 1;
-#elif 1
i = 2 * i - 1;
if (i < 0)
i ^= -1; //FIXME check if gcc does the right thing
-#else
- i = 2 * i - 1;
- i ^= (i >> 31);
-#endif
set_ue_golomb(pb, i);
}
diff --git a/media/ffvpx/libavcodec/h264chroma.h b/media/ffvpx/libavcodec/h264chroma.h
index e0f45ad13..5c89fd12d 100644
--- a/media/ffvpx/libavcodec/h264chroma.h
+++ b/media/ffvpx/libavcodec/h264chroma.h
@@ -19,9 +19,10 @@
#ifndef AVCODEC_H264CHROMA_H
#define AVCODEC_H264CHROMA_H
+#include <stddef.h>
#include <stdint.h>
-typedef void (*h264_chroma_mc_func)(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int srcStride, int h, int x, int y);
+typedef void (*h264_chroma_mc_func)(uint8_t *dst /*align 8*/, uint8_t *src /*align 1*/, ptrdiff_t srcStride, int h, int x, int y);
typedef struct H264ChromaContext {
h264_chroma_mc_func put_h264_chroma_pixels_tab[4];
diff --git a/media/ffvpx/libavcodec/hpeldsp.h b/media/ffvpx/libavcodec/hpeldsp.h
index 1a3cea54b..768139bfc 100644
--- a/media/ffvpx/libavcodec/hpeldsp.h
+++ b/media/ffvpx/libavcodec/hpeldsp.h
@@ -76,6 +76,8 @@ typedef struct HpelDSPContext {
* @param pixels source
* @param line_size number of bytes in a horizontal line of block
* @param h height
+ * @note The size is kept at [4][4] to match the above pixel_tabs and avoid
+ * out of bounds reads in the motion estimation code.
*/
op_pixels_func put_no_rnd_pixels_tab[4][4];
diff --git a/media/ffvpx/libavcodec/hwaccel.h b/media/ffvpx/libavcodec/hwaccel.h
new file mode 100644
index 000000000..124fbbf1f
--- /dev/null
+++ b/media/ffvpx/libavcodec/hwaccel.h
@@ -0,0 +1,24 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_HWACCEL_H
+#define AVCODEC_HWACCEL_H
+
+#define HWACCEL_CAP_ASYNC_SAFE (1 << 0)
+
+#endif /* AVCODEC_HWACCEL_H */
diff --git a/media/ffvpx/libavcodec/idctdsp.h b/media/ffvpx/libavcodec/idctdsp.h
index b180a6762..26221f6a9 100644
--- a/media/ffvpx/libavcodec/idctdsp.h
+++ b/media/ffvpx/libavcodec/idctdsp.h
@@ -21,6 +21,8 @@
#include <stdint.h>
+#include "config.h"
+
#include "avcodec.h"
/**
@@ -51,13 +53,13 @@ int ff_init_scantable_permutation_x86(uint8_t *idct_permutation,
typedef struct IDCTDSPContext {
/* pixel ops : interface with DCT */
void (*put_pixels_clamped)(const int16_t *block /* align 16 */,
- uint8_t *pixels /* align 8 */,
+ uint8_t *av_restrict pixels /* align 8 */,
ptrdiff_t line_size);
void (*put_signed_pixels_clamped)(const int16_t *block /* align 16 */,
- uint8_t *pixels /* align 8 */,
+ uint8_t *av_restrict pixels /* align 8 */,
ptrdiff_t line_size);
void (*add_pixels_clamped)(const int16_t *block /* align 16 */,
- uint8_t *pixels /* align 8 */,
+ uint8_t *av_restrict pixels /* align 8 */,
ptrdiff_t line_size);
void (*idct)(int16_t *block /* align 16 */);
@@ -68,14 +70,14 @@ typedef struct IDCTDSPContext {
* @param line_size size in bytes of a horizontal line of dest
*/
void (*idct_put)(uint8_t *dest /* align 8 */,
- int line_size, int16_t *block /* align 16 */);
+ ptrdiff_t line_size, int16_t *block /* align 16 */);
/**
* block -> idct -> add dest -> clip to unsigned 8 bit -> dest.
* @param line_size size in bytes of a horizontal line of dest
*/
void (*idct_add)(uint8_t *dest /* align 8 */,
- int line_size, int16_t *block /* align 16 */);
+ ptrdiff_t line_size, int16_t *block /* align 16 */);
/**
* IDCT input permutation.
@@ -95,11 +97,15 @@ typedef struct IDCTDSPContext {
enum idct_permutation_type perm_type;
} IDCTDSPContext;
-extern void (*ff_put_pixels_clamped)(const int16_t *block, uint8_t *pixels, ptrdiff_t line_size);
-extern void (*ff_add_pixels_clamped)(const int16_t *block, uint8_t *pixels, ptrdiff_t line_size);
+void ff_put_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels,
+ ptrdiff_t line_size);
+void ff_add_pixels_clamped_c(const int16_t *block, uint8_t *av_restrict pixels,
+ ptrdiff_t line_size);
void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx);
+void ff_idctdsp_init_aarch64(IDCTDSPContext *c, AVCodecContext *avctx,
+ unsigned high_bit_depth);
void ff_idctdsp_init_alpha(IDCTDSPContext *c, AVCodecContext *avctx,
unsigned high_bit_depth);
void ff_idctdsp_init_arm(IDCTDSPContext *c, AVCodecContext *avctx,
diff --git a/media/ffvpx/libavcodec/internal.h b/media/ffvpx/libavcodec/internal.h
index 35b9630b5..faa923c11 100644
--- a/media/ffvpx/libavcodec/internal.h
+++ b/media/ffvpx/libavcodec/internal.h
@@ -48,8 +48,8 @@
#define FF_CODEC_CAP_INIT_CLEANUP (1 << 1)
/**
* Decoders marked with FF_CODEC_CAP_SETS_PKT_DTS want to set
- * AVFrame.pkt_dts manually. If the flag is set, utils.c won't overwrite
- * this field. If it's unset, utils.c tries to guess the pkt_dts field
+ * AVFrame.pkt_dts manually. If the flag is set, decode.c won't overwrite
+ * this field. If it's unset, decode.c tries to guess the pkt_dts field
* from the input AVPacket.
*/
#define FF_CODEC_CAP_SETS_PKT_DTS (1 << 2)
@@ -58,6 +58,16 @@
* skipped due to the skip_frame setting.
*/
#define FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM (1 << 3)
+/**
+ * The decoder sets the cropping fields in the output frames manually.
+ * If this cap is set, the generic code will initialize output frame
+ * dimensions to coded rather than display values.
+ */
+#define FF_CODEC_CAP_EXPORTS_CROPPING (1 << 4)
+/**
+ * Codec initializes slice-based threading with a main function
+ */
+#define FF_CODEC_CAP_SLICE_THREAD_HAS_MF (1 << 5)
#ifdef TRACE
# define ff_tlog(ctx, ...) av_log(ctx, AV_LOG_TRACE, __VA_ARGS__)
@@ -70,11 +80,18 @@
#define FF_DEFAULT_QUANT_BIAS 999999
#endif
+#if !FF_API_QSCALE_TYPE
+#define FF_QSCALE_TYPE_MPEG1 0
+#define FF_QSCALE_TYPE_MPEG2 1
+#define FF_QSCALE_TYPE_H264 2
+#define FF_QSCALE_TYPE_VP56 3
+#endif
+
#define FF_SANE_NB_CHANNELS 64U
#define FF_SIGNBIT(x) ((x) >> CHAR_BIT * sizeof(x) - 1)
-#if HAVE_AVX
+#if HAVE_SIMD_ALIGN_32
# define STRIDE_ALIGN 32
#elif HAVE_SIMD_ALIGN_16
# define STRIDE_ALIGN 16
@@ -101,6 +118,16 @@ typedef struct FramePool {
int samples;
} FramePool;
+typedef struct DecodeSimpleContext {
+ AVPacket *in_pkt;
+ AVFrame *out_frame;
+} DecodeSimpleContext;
+
+typedef struct DecodeFilterContext {
+ AVBSFContext **bsfs;
+ int nb_bsfs;
+} DecodeFilterContext;
+
typedef struct AVCodecInternal {
/**
* Whether the parent AVCodecContext is a copy of the context which had
@@ -137,11 +164,14 @@ typedef struct AVCodecInternal {
void *thread_ctx;
+ DecodeSimpleContext ds;
+ DecodeFilterContext filter;
+
/**
- * Current packet as passed into the decoder, to avoid having to pass the
- * packet into every function.
+ * Properties (timestamps+side data) extracted from the last packet passed
+ * for decoding.
*/
- AVPacket *pkt;
+ AVPacket *last_pkt_props;
/**
* temporary buffer used for encoders to store their bitstream
@@ -173,7 +203,23 @@ typedef struct AVCodecInternal {
int buffer_pkt_valid; // encoding: packet without data can be valid
AVFrame *buffer_frame;
int draining_done;
+ /* set to 1 when the caller is using the old decoding API */
+ int compat_decode;
+ int compat_decode_warned;
+ /* this variable is set by the decoder internals to signal to the old
+ * API compat wrappers the amount of data consumed from the last packet */
+ size_t compat_decode_consumed;
+ /* when a partial packet has been consumed, this stores the remaining size
+ * of the packet (that should be submitted in the next decode call */
+ size_t compat_decode_partial_size;
+ AVFrame *compat_decode_frame;
+
int showed_multi_packet_warning;
+
+ int skip_samples_multiplier;
+
+ /* to prevent infinite loop on errors when draining */
+ int nb_draining_errors;
} AVCodecInternal;
struct AVCodecDefault {
@@ -262,7 +308,7 @@ static av_always_inline int64_t ff_samples_to_time_base(AVCodecContext *avctx,
static av_always_inline float ff_exp2fi(int x) {
/* Normal range */
if (-126 <= x && x <= 128)
- return av_int2float(x+127 << 23);
+ return av_int2float((x+127) << 23);
/* Too large */
else if (x > 128)
return INFINITY;
@@ -327,6 +373,10 @@ int ff_set_sar(AVCodecContext *avctx, AVRational sar);
int ff_side_data_update_matrix_encoding(AVFrame *frame,
enum AVMatrixEncoding matrix_encoding);
+#if FF_API_MERGE_SD
+int ff_packet_split_and_drop_side_data(AVPacket *pkt);
+#endif
+
/**
* Select the (possibly hardware accelerated) pixel format.
* This is a wrapper around AVCodecContext.get_format() and should be used
@@ -361,4 +411,10 @@ int ff_side_data_set_encoder_stats(AVPacket *pkt, int quality, int64_t *error, i
int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len,
void **data, size_t *sei_size);
+/**
+ * Get an estimated video bitrate based on frame size, frame rate and coded
+ * bits per pixel.
+ */
+int64_t ff_guess_coded_bitrate(AVCodecContext *avctx);
+
#endif /* AVCODEC_INTERNAL_H */
diff --git a/media/ffvpx/libavcodec/mathops.h b/media/ffvpx/libavcodec/mathops.h
index 5168dc2ce..1c3566431 100644
--- a/media/ffvpx/libavcodec/mathops.h
+++ b/media/ffvpx/libavcodec/mathops.h
@@ -25,6 +25,7 @@
#include <stdint.h>
#include "libavutil/common.h"
+#include "libavutil/reverse.h"
#include "config.h"
#define MAX_NEG_CROP 1024
@@ -96,15 +97,6 @@ static av_always_inline unsigned UMULH(unsigned a, unsigned b){
#define mid_pred mid_pred
static inline av_const int mid_pred(int a, int b, int c)
{
-#if 0
- int t= (a-b)&((a-b)>>31);
- a-=t;
- b+=t;
- b-= (b-c)&((b-c)>>31);
- b+= (a-b)&((a-b)>>31);
-
- return b;
-#else
if(a>b){
if(c>b){
if(c>a) b=a;
@@ -117,7 +109,6 @@ static inline av_const int mid_pred(int a, int b, int c)
}
}
return b;
-#endif
}
#endif
@@ -249,4 +240,12 @@ static inline int8_t ff_u8_to_s8(uint8_t a)
return b.s8;
}
+static av_always_inline uint32_t bitswap_32(uint32_t x)
+{
+ return (uint32_t)ff_reverse[ x & 0xFF] << 24 |
+ (uint32_t)ff_reverse[(x >> 8) & 0xFF] << 16 |
+ (uint32_t)ff_reverse[(x >> 16) & 0xFF] << 8 |
+ (uint32_t)ff_reverse[ x >> 24];
+}
+
#endif /* AVCODEC_MATHOPS_H */
diff --git a/media/ffvpx/libavcodec/me_cmp.h b/media/ffvpx/libavcodec/me_cmp.h
index 5666f59ad..0dbbcbb1d 100644
--- a/media/ffvpx/libavcodec/me_cmp.h
+++ b/media/ffvpx/libavcodec/me_cmp.h
@@ -76,7 +76,7 @@ typedef struct MECmpContext {
me_cmp_func frame_skip_cmp[6]; // only width 8 used
me_cmp_func pix_abs[2][4];
- me_cmp_func median_sad[2];
+ me_cmp_func median_sad[6];
} MECmpContext;
void ff_me_cmp_init_static(void);
diff --git a/media/ffvpx/libavcodec/moz.build b/media/ffvpx/libavcodec/moz.build
index 443bbe978..9980e1556 100644
--- a/media/ffvpx/libavcodec/moz.build
+++ b/media/ffvpx/libavcodec/moz.build
@@ -16,7 +16,11 @@ SOURCES += [
'avpacket.c',
'avpicture.c',
'bitstream.c',
+ 'bitstream_filter.c',
+ 'bitstream_filters.c',
+ 'bsf.c',
'codec_desc.c',
+ 'decode.c',
'dummy_funcs.c',
'flac.c',
'flac_parser.c',
@@ -28,6 +32,7 @@ SOURCES += [
'imgconvert.c',
'log2_tab.c',
'mathtables.c',
+ 'null_bsf.c',
'options.c',
'parser.c',
'profiles.c',
@@ -48,10 +53,16 @@ SOURCES += [
'vp8dsp.c',
'vp9.c',
'vp9_parser.c',
+ 'vp9block.c',
+ 'vp9data.c',
'vp9dsp.c',
'vp9dsp_10bpp.c',
'vp9dsp_12bpp.c',
'vp9dsp_8bpp.c',
+ 'vp9lpf.c',
+ 'vp9mvs.c',
+ 'vp9prob.c',
+ 'vp9recon.c',
'xiph.c'
]
diff --git a/media/ffvpx/libavcodec/mpegvideo.h b/media/ffvpx/libavcodec/mpegvideo.h
index c82fa3e1a..e9eb633d1 100644
--- a/media/ffvpx/libavcodec/mpegvideo.h
+++ b/media/ffvpx/libavcodec/mpegvideo.h
@@ -422,6 +422,7 @@ typedef struct MpegEncContext {
struct MJpegContext *mjpeg_ctx;
int esc_pos;
int pred;
+ int huffman;
/* MSMPEG4 specific */
int mv_table_index;
@@ -679,7 +680,7 @@ void ff_mpv_common_end(MpegEncContext *s);
void ff_mpv_decode_defaults(MpegEncContext *s);
void ff_mpv_decode_init(MpegEncContext *s, AVCodecContext *avctx);
-void ff_mpv_decode_mb(MpegEncContext *s, int16_t block[12][64]);
+void ff_mpv_reconstruct_mb(MpegEncContext *s, int16_t block[12][64]);
void ff_mpv_report_decode_progress(MpegEncContext *s);
int ff_mpv_frame_start(MpegEncContext *s, AVCodecContext *avctx);
diff --git a/media/ffvpx/libavutil/wchar_filename.h b/media/ffvpx/libavcodec/null_bsf.c
index 2ade321be..feb71248a 100644
--- a/media/ffvpx/libavutil/wchar_filename.h
+++ b/media/ffvpx/libavcodec/null_bsf.c
@@ -16,30 +16,28 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-#ifndef AVUTIL_WCHAR_FILENAME_H
-#define AVUTIL_WCHAR_FILENAME_H
+/**
+ * @file
+ * Null bitstream filter -- pass the input through unchanged.
+ */
-#if defined(_WIN32) && !defined(__MINGW32CE__)
-#include <windows.h>
-#include "mem.h"
+#include "avcodec.h"
+#include "bsf.h"
-av_warn_unused_result
-static inline int utf8towchar(const char *filename_utf8, wchar_t **filename_w)
+static int null_filter(AVBSFContext *ctx, AVPacket *out)
{
- int num_chars;
- num_chars = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, filename_utf8, -1, NULL, 0);
- if (num_chars <= 0) {
- *filename_w = NULL;
- return 0;
- }
- *filename_w = (wchar_t *)av_mallocz_array(num_chars, sizeof(wchar_t));
- if (!*filename_w) {
- errno = ENOMEM;
- return -1;
- }
- MultiByteToWideChar(CP_UTF8, 0, filename_utf8, -1, *filename_w, num_chars);
+ AVPacket *in;
+ int ret;
+
+ ret = ff_bsf_get_packet(ctx, &in);
+ if (ret < 0)
+ return ret;
+ av_packet_move_ref(out, in);
+ av_packet_free(&in);
return 0;
}
-#endif
-#endif /* AVUTIL_WCHAR_FILENAME_H */
+const AVBitStreamFilter ff_null_bsf = {
+ .name = "null",
+ .filter = null_filter,
+};
diff --git a/media/ffvpx/libavcodec/options.c b/media/ffvpx/libavcodec/options.c
index f25df2ab3..82e12179a 100644
--- a/media/ffvpx/libavcodec/options.c
+++ b/media/ffvpx/libavcodec/options.c
@@ -34,7 +34,7 @@
#include <string.h>
FF_DISABLE_DEPRECATION_WARNINGS
-#include "ff_options_table.h"
+#include "options_table.h"
FF_ENABLE_DEPRECATION_WARNINGS
static const char* context_to_name(void* ptr) {
@@ -119,6 +119,7 @@ static int init_context_defaults(AVCodecContext *s, const AVCodec *codec)
s->execute2 = avcodec_default_execute2;
s->sample_aspect_ratio = (AVRational){0,1};
s->pix_fmt = AV_PIX_FMT_NONE;
+ s->sw_pix_fmt = AV_PIX_FMT_NONE;
s->sample_fmt = AV_SAMPLE_FMT_NONE;
s->reordered_opaque = AV_NOPTS_VALUE;
@@ -187,6 +188,31 @@ void avcodec_free_context(AVCodecContext **pavctx)
}
#if FF_API_COPY_CONTEXT
+static void copy_context_reset(AVCodecContext *avctx)
+{
+ int i;
+
+ av_opt_free(avctx);
+#if FF_API_CODED_FRAME
+FF_DISABLE_DEPRECATION_WARNINGS
+ av_frame_free(&avctx->coded_frame);
+FF_ENABLE_DEPRECATION_WARNINGS
+#endif
+ av_freep(&avctx->rc_override);
+ av_freep(&avctx->intra_matrix);
+ av_freep(&avctx->inter_matrix);
+ av_freep(&avctx->extradata);
+ av_freep(&avctx->subtitle_header);
+ av_buffer_unref(&avctx->hw_frames_ctx);
+ av_buffer_unref(&avctx->hw_device_ctx);
+ for (i = 0; i < avctx->nb_coded_side_data; i++)
+ av_freep(&avctx->coded_side_data[i].data);
+ av_freep(&avctx->coded_side_data);
+ avctx->subtitle_header_size = 0;
+ avctx->nb_coded_side_data = 0;
+ avctx->extradata_size = 0;
+}
+
int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
{
const AVCodec *orig_codec = dest->codec;
@@ -199,12 +225,7 @@ int avcodec_copy_context(AVCodecContext *dest, const AVCodecContext *src)
return AVERROR(EINVAL);
}
- av_opt_free(dest);
- av_freep(&dest->rc_override);
- av_freep(&dest->intra_matrix);
- av_freep(&dest->inter_matrix);
- av_freep(&dest->extradata);
- av_freep(&dest->subtitle_header);
+ copy_context_reset(dest);
memcpy(dest, src, sizeof(*dest));
av_opt_copy(dest, src);
@@ -229,11 +250,14 @@ FF_ENABLE_DEPRECATION_WARNINGS
/* reallocate values that should be allocated separately */
dest->extradata = NULL;
+ dest->coded_side_data = NULL;
dest->intra_matrix = NULL;
dest->inter_matrix = NULL;
dest->rc_override = NULL;
dest->subtitle_header = NULL;
dest->hw_frames_ctx = NULL;
+ dest->hw_device_ctx = NULL;
+ dest->nb_coded_side_data = 0;
#define alloc_and_copy_or_fail(obj, size, pad) \
if (src->obj && size > 0) { \
@@ -263,15 +287,7 @@ FF_ENABLE_DEPRECATION_WARNINGS
return 0;
fail:
- av_freep(&dest->subtitle_header);
- av_freep(&dest->rc_override);
- av_freep(&dest->intra_matrix);
- av_freep(&dest->inter_matrix);
- av_freep(&dest->extradata);
- av_buffer_unref(&dest->hw_frames_ctx);
- dest->subtitle_header_size = 0;
- dest->extradata_size = 0;
- av_opt_free(dest);
+ copy_context_reset(dest);
return AVERROR(ENOMEM);
}
#endif
diff --git a/media/ffvpx/libavcodec/options_table.h b/media/ffvpx/libavcodec/options_table.h
new file mode 100644
index 000000000..2ac37c3ff
--- /dev/null
+++ b/media/ffvpx/libavcodec/options_table.h
@@ -0,0 +1,594 @@
+/*
+ * Copyright (c) 2001 Fabrice Bellard
+ * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_OPTIONS_TABLE_H
+#define AVCODEC_OPTIONS_TABLE_H
+
+#include <float.h>
+#include <limits.h>
+#include <stdint.h>
+
+#include "libavutil/opt.h"
+#include "avcodec.h"
+#include "version.h"
+
+#define OFFSET(x) offsetof(AVCodecContext,x)
+#define DEFAULT 0 //should be NAN but it does not work as it is not a constant in glibc as required by ANSI/ISO C
+//these names are too long to be readable
+#define V AV_OPT_FLAG_VIDEO_PARAM
+#define A AV_OPT_FLAG_AUDIO_PARAM
+#define S AV_OPT_FLAG_SUBTITLE_PARAM
+#define E AV_OPT_FLAG_ENCODING_PARAM
+#define D AV_OPT_FLAG_DECODING_PARAM
+
+#define AV_CODEC_DEFAULT_BITRATE 200*1000
+
+static const AVOption avcodec_options[] = {
+{"b", "set bitrate (in bits/s)", OFFSET(bit_rate), AV_OPT_TYPE_INT64, {.i64 = AV_CODEC_DEFAULT_BITRATE }, 0, INT64_MAX, A|V|E},
+{"ab", "set bitrate (in bits/s)", OFFSET(bit_rate), AV_OPT_TYPE_INT64, {.i64 = 128*1000 }, 0, INT_MAX, A|E},
+{"bt", "Set video bitrate tolerance (in bits/s). In 1-pass mode, bitrate tolerance specifies how far "
+ "ratecontrol is willing to deviate from the target average bitrate value. This is not related "
+ "to minimum/maximum bitrate. Lowering tolerance too much has an adverse effect on quality.",
+ OFFSET(bit_rate_tolerance), AV_OPT_TYPE_INT, {.i64 = AV_CODEC_DEFAULT_BITRATE*20 }, 1, INT_MAX, V|E},
+{"flags", NULL, OFFSET(flags), AV_OPT_TYPE_FLAGS, {.i64 = DEFAULT }, 0, UINT_MAX, V|A|S|E|D, "flags"},
+{"unaligned", "allow decoders to produce unaligned output", 0, AV_OPT_TYPE_CONST, { .i64 = AV_CODEC_FLAG_UNALIGNED }, INT_MIN, INT_MAX, V | D, "flags" },
+{"mv4", "use four motion vectors per macroblock (MPEG-4)", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_4MV }, INT_MIN, INT_MAX, V|E, "flags"},
+{"qpel", "use 1/4-pel motion compensation", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_QPEL }, INT_MIN, INT_MAX, V|E, "flags"},
+{"loop", "use loop filter", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_LOOP_FILTER }, INT_MIN, INT_MAX, V|E, "flags"},
+{"qscale", "use fixed qscale", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_QSCALE }, INT_MIN, INT_MAX, 0, "flags"},
+#if FF_API_GMC
+{"gmc", "use gmc", 0, AV_OPT_TYPE_CONST, {.i64 = CODEC_FLAG_GMC }, INT_MIN, INT_MAX, V|E, "flags"},
+#endif
+#if FF_API_MV0
+{"mv0", "always try a mb with mv=<0,0>", 0, AV_OPT_TYPE_CONST, {.i64 = CODEC_FLAG_MV0 }, INT_MIN, INT_MAX, V|E, "flags"},
+#endif
+#if FF_API_INPUT_PRESERVED
+{"input_preserved", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = CODEC_FLAG_INPUT_PRESERVED }, INT_MIN, INT_MAX, 0, "flags"},
+#endif
+{"pass1", "use internal 2-pass ratecontrol in first pass mode", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_PASS1 }, INT_MIN, INT_MAX, 0, "flags"},
+{"pass2", "use internal 2-pass ratecontrol in second pass mode", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_PASS2 }, INT_MIN, INT_MAX, 0, "flags"},
+{"gray", "only decode/encode grayscale", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_GRAY }, INT_MIN, INT_MAX, V|E|D, "flags"},
+#if FF_API_EMU_EDGE
+{"emu_edge", "do not draw edges", 0, AV_OPT_TYPE_CONST, {.i64 = CODEC_FLAG_EMU_EDGE }, INT_MIN, INT_MAX, 0, "flags"},
+#endif
+{"psnr", "error[?] variables will be set during encoding", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_PSNR }, INT_MIN, INT_MAX, V|E, "flags"},
+{"truncated", "Input bitstream might be randomly truncated", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_TRUNCATED }, INT_MIN, INT_MAX, V|D, "flags"},
+#if FF_API_NORMALIZE_AQP
+{"naq", "normalize adaptive quantization", 0, AV_OPT_TYPE_CONST, {.i64 = CODEC_FLAG_NORMALIZE_AQP }, INT_MIN, INT_MAX, V|E, "flags"},
+#endif
+{"ildct", "use interlaced DCT", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_INTERLACED_DCT }, INT_MIN, INT_MAX, V|E, "flags"},
+{"low_delay", "force low delay", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_LOW_DELAY }, INT_MIN, INT_MAX, V|D|E, "flags"},
+{"global_header", "place global headers in extradata instead of every keyframe", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_GLOBAL_HEADER }, INT_MIN, INT_MAX, V|A|E, "flags"},
+{"bitexact", "use only bitexact functions (except (I)DCT)", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_BITEXACT }, INT_MIN, INT_MAX, A|V|S|D|E, "flags"},
+{"aic", "H.263 advanced intra coding / MPEG-4 AC prediction", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_AC_PRED }, INT_MIN, INT_MAX, V|E, "flags"},
+{"ilme", "interlaced motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_INTERLACED_ME }, INT_MIN, INT_MAX, V|E, "flags"},
+{"cgop", "closed GOP", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_CLOSED_GOP }, INT_MIN, INT_MAX, V|E, "flags"},
+{"output_corrupt", "Output even potentially corrupted frames", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG_OUTPUT_CORRUPT }, INT_MIN, INT_MAX, V|D, "flags"},
+{"fast", "allow non-spec-compliant speedup tricks", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_FAST }, INT_MIN, INT_MAX, V|E, "flags2"},
+{"noout", "skip bitstream encoding", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_NO_OUTPUT }, INT_MIN, INT_MAX, V|E, "flags2"},
+{"ignorecrop", "ignore cropping information from sps", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_IGNORE_CROP }, INT_MIN, INT_MAX, V|D, "flags2"},
+{"local_header", "place global headers at every keyframe instead of in extradata", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_LOCAL_HEADER }, INT_MIN, INT_MAX, V|E, "flags2"},
+{"chunks", "Frame data might be split into multiple chunks", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_CHUNKS }, INT_MIN, INT_MAX, V|D, "flags2"},
+{"showall", "Show all frames before the first keyframe", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_SHOW_ALL }, INT_MIN, INT_MAX, V|D, "flags2"},
+{"export_mvs", "export motion vectors through frame side data", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_EXPORT_MVS}, INT_MIN, INT_MAX, V|D, "flags2"},
+{"skip_manual", "do not skip samples and export skip information as frame side data", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_SKIP_MANUAL}, INT_MIN, INT_MAX, V|D, "flags2"},
+{"ass_ro_flush_noop", "do not reset ASS ReadOrder field on flush", 0, AV_OPT_TYPE_CONST, {.i64 = AV_CODEC_FLAG2_RO_FLUSH_NOOP}, INT_MIN, INT_MAX, S|D, "flags2"},
+#if FF_API_MOTION_EST
+{"me_method", "set motion estimation method", OFFSET(me_method), AV_OPT_TYPE_INT, {.i64 = ME_EPZS }, INT_MIN, INT_MAX, V|E, "me_method"},
+{"zero", "zero motion estimation (fastest)", 0, AV_OPT_TYPE_CONST, {.i64 = ME_ZERO }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"full", "full motion estimation (slowest)", 0, AV_OPT_TYPE_CONST, {.i64 = ME_FULL }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"epzs", "EPZS motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_EPZS }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"esa", "esa motion estimation (alias for full)", 0, AV_OPT_TYPE_CONST, {.i64 = ME_FULL }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"tesa", "tesa motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_TESA }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"dia", "diamond motion estimation (alias for EPZS)", 0, AV_OPT_TYPE_CONST, {.i64 = ME_EPZS }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"log", "log motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_LOG }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"phods", "phods motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_PHODS }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"x1", "X1 motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_X1 }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"hex", "hex motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_HEX }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"umh", "umh motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_UMH }, INT_MIN, INT_MAX, V|E, "me_method" },
+{"iter", "iter motion estimation", 0, AV_OPT_TYPE_CONST, {.i64 = ME_ITER }, INT_MIN, INT_MAX, V|E, "me_method" },
+#endif
+{"time_base", NULL, OFFSET(time_base), AV_OPT_TYPE_RATIONAL, {.dbl = 0}, 0, INT_MAX},
+{"g", "set the group of picture (GOP) size", OFFSET(gop_size), AV_OPT_TYPE_INT, {.i64 = 12 }, INT_MIN, INT_MAX, V|E},
+{"ar", "set audio sampling rate (in Hz)", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX, A|D|E},
+{"ac", "set number of audio channels", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX, A|D|E},
+{"cutoff", "set cutoff bandwidth", OFFSET(cutoff), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, A|E},
+{"frame_size", NULL, OFFSET(frame_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX, A|E},
+{"frame_number", NULL, OFFSET(frame_number), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"delay", NULL, OFFSET(delay), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"qcomp", "video quantizer scale compression (VBR). Constant of ratecontrol equation. "
+ "Recommended range for default rc_eq: 0.0-1.0",
+ OFFSET(qcompress), AV_OPT_TYPE_FLOAT, {.dbl = 0.5 }, -FLT_MAX, FLT_MAX, V|E},
+{"qblur", "video quantizer scale blur (VBR)", OFFSET(qblur), AV_OPT_TYPE_FLOAT, {.dbl = 0.5 }, -1, FLT_MAX, V|E},
+{"qmin", "minimum video quantizer scale (VBR)", OFFSET(qmin), AV_OPT_TYPE_INT, {.i64 = 2 }, -1, 69, V|E},
+{"qmax", "maximum video quantizer scale (VBR)", OFFSET(qmax), AV_OPT_TYPE_INT, {.i64 = 31 }, -1, 1024, V|E},
+{"qdiff", "maximum difference between the quantizer scales (VBR)", OFFSET(max_qdiff), AV_OPT_TYPE_INT, {.i64 = 3 }, INT_MIN, INT_MAX, V|E},
+{"bf", "set maximum number of B-frames between non-B-frames", OFFSET(max_b_frames), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, -1, INT_MAX, V|E},
+{"b_qfactor", "QP factor between P- and B-frames", OFFSET(b_quant_factor), AV_OPT_TYPE_FLOAT, {.dbl = 1.25 }, -FLT_MAX, FLT_MAX, V|E},
+#if FF_API_RC_STRATEGY
+{"rc_strategy", "ratecontrol method", OFFSET(rc_strategy), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+#if FF_API_PRIVATE_OPT
+{"b_strategy", "strategy to choose between I/P/B-frames", OFFSET(b_frame_strategy), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, V|E},
+{"ps", "RTP payload size in bytes", OFFSET(rtp_payload_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+#if FF_API_STAT_BITS
+{"mv_bits", NULL, OFFSET(mv_bits), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"header_bits", NULL, OFFSET(header_bits), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"i_tex_bits", NULL, OFFSET(i_tex_bits), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"p_tex_bits", NULL, OFFSET(p_tex_bits), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"i_count", NULL, OFFSET(i_count), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"p_count", NULL, OFFSET(p_count), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"skip_count", NULL, OFFSET(skip_count), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"misc_bits", NULL, OFFSET(misc_bits), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"frame_bits", NULL, OFFSET(frame_bits), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+#endif
+{"codec_tag", NULL, OFFSET(codec_tag), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"bug", "work around not autodetected encoder bugs", OFFSET(workaround_bugs), AV_OPT_TYPE_FLAGS, {.i64 = FF_BUG_AUTODETECT }, INT_MIN, INT_MAX, V|D, "bug"},
+{"autodetect", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_AUTODETECT }, INT_MIN, INT_MAX, V|D, "bug"},
+#if FF_API_OLD_MSMPEG4
+{"old_msmpeg4", "some old lavc-generated MSMPEG4v3 files (no autodetection)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_OLD_MSMPEG4 }, INT_MIN, INT_MAX, V|D, "bug"},
+#endif
+{"xvid_ilace", "Xvid interlacing bug (autodetected if FOURCC == XVIX)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_XVID_ILACE }, INT_MIN, INT_MAX, V|D, "bug"},
+{"ump4", "(autodetected if FOURCC == UMP4)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_UMP4 }, INT_MIN, INT_MAX, V|D, "bug"},
+{"no_padding", "padding bug (autodetected)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_NO_PADDING }, INT_MIN, INT_MAX, V|D, "bug"},
+{"amv", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_AMV }, INT_MIN, INT_MAX, V|D, "bug"},
+#if FF_API_AC_VLC
+{"ac_vlc", "illegal VLC bug (autodetected per FOURCC)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_AC_VLC }, INT_MIN, INT_MAX, V|D, "bug"},
+#endif
+{"qpel_chroma", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_QPEL_CHROMA }, INT_MIN, INT_MAX, V|D, "bug"},
+{"std_qpel", "old standard qpel (autodetected per FOURCC/version)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_STD_QPEL }, INT_MIN, INT_MAX, V|D, "bug"},
+{"qpel_chroma2", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_QPEL_CHROMA2 }, INT_MIN, INT_MAX, V|D, "bug"},
+{"direct_blocksize", "direct-qpel-blocksize bug (autodetected per FOURCC/version)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_DIRECT_BLOCKSIZE }, INT_MIN, INT_MAX, V|D, "bug"},
+{"edge", "edge padding bug (autodetected per FOURCC/version)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_EDGE }, INT_MIN, INT_MAX, V|D, "bug"},
+{"hpel_chroma", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_HPEL_CHROMA }, INT_MIN, INT_MAX, V|D, "bug"},
+{"dc_clip", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_DC_CLIP }, INT_MIN, INT_MAX, V|D, "bug"},
+{"ms", "work around various bugs in Microsoft's broken decoders", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_MS }, INT_MIN, INT_MAX, V|D, "bug"},
+{"trunc", "truncated frames", 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_TRUNCATED}, INT_MIN, INT_MAX, V|D, "bug"},
+{"iedge", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_BUG_IEDGE }, INT_MIN, INT_MAX, V|D, "bug"},
+{"strict", "how strictly to follow the standards", OFFSET(strict_std_compliance), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, A|V|D|E, "strict"},
+{"very", "strictly conform to a older more strict version of the spec or reference software", 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_VERY_STRICT }, INT_MIN, INT_MAX, A|V|D|E, "strict"},
+{"strict", "strictly conform to all the things in the spec no matter what the consequences", 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_STRICT }, INT_MIN, INT_MAX, A|V|D|E, "strict"},
+{"normal", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_NORMAL }, INT_MIN, INT_MAX, A|V|D|E, "strict"},
+{"unofficial", "allow unofficial extensions", 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_UNOFFICIAL }, INT_MIN, INT_MAX, A|V|D|E, "strict"},
+{"experimental", "allow non-standardized experimental things", 0, AV_OPT_TYPE_CONST, {.i64 = FF_COMPLIANCE_EXPERIMENTAL }, INT_MIN, INT_MAX, A|V|D|E, "strict"},
+{"b_qoffset", "QP offset between P- and B-frames", OFFSET(b_quant_offset), AV_OPT_TYPE_FLOAT, {.dbl = 1.25 }, -FLT_MAX, FLT_MAX, V|E},
+{"err_detect", "set error detection flags", OFFSET(err_recognition), AV_OPT_TYPE_FLAGS, {.i64 = 0 }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"crccheck", "verify embedded CRCs", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_CRCCHECK }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"bitstream", "detect bitstream specification deviations", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_BITSTREAM }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"buffer", "detect improper bitstream length", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_BUFFER }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"explode", "abort decoding on minor error detection", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_EXPLODE }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"ignore_err", "ignore errors", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_IGNORE_ERR }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"careful", "consider things that violate the spec, are fast to check and have not been seen in the wild as errors", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_CAREFUL }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"compliant", "consider all spec non compliancies as errors", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_COMPLIANT }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"aggressive", "consider things that a sane encoder should not do as an error", 0, AV_OPT_TYPE_CONST, {.i64 = AV_EF_AGGRESSIVE }, INT_MIN, INT_MAX, A|V|D, "err_detect"},
+{"has_b_frames", NULL, OFFSET(has_b_frames), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX},
+{"block_align", NULL, OFFSET(block_align), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX},
+#if FF_API_PRIVATE_OPT
+{"mpeg_quant", "use MPEG quantizers instead of H.263", OFFSET(mpeg_quant), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+#if FF_API_MPV_OPT
+{"qsquish", "deprecated, use encoder private options instead", OFFSET(rc_qsquish), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, 0, 99, V|E},
+{"rc_qmod_amp", "deprecated, use encoder private options instead", OFFSET(rc_qmod_amp), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, -FLT_MAX, FLT_MAX, V|E},
+{"rc_qmod_freq", "deprecated, use encoder private options instead", OFFSET(rc_qmod_freq), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+{"rc_override_count", NULL, OFFSET(rc_override_count), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+#if FF_API_MPV_OPT
+{"rc_eq", "deprecated, use encoder private options instead", OFFSET(rc_eq), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, V|E},
+#endif
+{"maxrate", "maximum bitrate (in bits/s). Used for VBV together with bufsize.", OFFSET(rc_max_rate), AV_OPT_TYPE_INT64, {.i64 = DEFAULT }, 0, INT_MAX, V|A|E},
+{"minrate", "minimum bitrate (in bits/s). Most useful in setting up a CBR encode. It is of little use otherwise.",
+ OFFSET(rc_min_rate), AV_OPT_TYPE_INT64, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
+{"bufsize", "set ratecontrol buffer size (in bits)", OFFSET(rc_buffer_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, A|V|E},
+#if FF_API_MPV_OPT
+{"rc_buf_aggressivity", "deprecated, use encoder private options instead", OFFSET(rc_buffer_aggressivity), AV_OPT_TYPE_FLOAT, {.dbl = 1.0 }, -FLT_MAX, FLT_MAX, V|E},
+#endif
+{"i_qfactor", "QP factor between P- and I-frames", OFFSET(i_quant_factor), AV_OPT_TYPE_FLOAT, {.dbl = -0.8 }, -FLT_MAX, FLT_MAX, V|E},
+{"i_qoffset", "QP offset between P- and I-frames", OFFSET(i_quant_offset), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, -FLT_MAX, FLT_MAX, V|E},
+#if FF_API_MPV_OPT
+{"rc_init_cplx", "deprecated, use encoder private options instead", OFFSET(rc_initial_cplx), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, -FLT_MAX, FLT_MAX, V|E},
+#endif
+{"dct", "DCT algorithm", OFFSET(dct_algo), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX, V|E, "dct"},
+{"auto", "autoselect a good one", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DCT_AUTO }, INT_MIN, INT_MAX, V|E, "dct"},
+{"fastint", "fast integer", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DCT_FASTINT }, INT_MIN, INT_MAX, V|E, "dct"},
+{"int", "accurate integer", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DCT_INT }, INT_MIN, INT_MAX, V|E, "dct"},
+{"mmx", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DCT_MMX }, INT_MIN, INT_MAX, V|E, "dct"},
+{"altivec", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DCT_ALTIVEC }, INT_MIN, INT_MAX, V|E, "dct"},
+{"faan", "floating point AAN DCT", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DCT_FAAN }, INT_MIN, INT_MAX, V|E, "dct"},
+{"lumi_mask", "compresses bright areas stronger than medium ones", OFFSET(lumi_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
+{"tcplx_mask", "temporal complexity masking", OFFSET(temporal_cplx_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
+{"scplx_mask", "spatial complexity masking", OFFSET(spatial_cplx_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
+{"p_mask", "inter masking", OFFSET(p_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
+{"dark_mask", "compresses dark areas stronger than medium ones", OFFSET(dark_masking), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, -FLT_MAX, FLT_MAX, V|E},
+{"idct", "select IDCT implementation", OFFSET(idct_algo), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX, V|E|D, "idct"},
+{"auto", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_AUTO }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"int", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_INT }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"simple", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLE }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"simplemmx", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLEMMX }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"arm", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_ARM }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"altivec", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_ALTIVEC }, INT_MIN, INT_MAX, V|E|D, "idct"},
+#if FF_API_ARCH_SH4
+{"sh4", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SH4 }, INT_MIN, INT_MAX, V|E|D, "idct"},
+#endif
+{"simplearm", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLEARM }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"simplearmv5te", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLEARMV5TE }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"simplearmv6", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLEARMV6 }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"simpleneon", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLENEON }, INT_MIN, INT_MAX, V|E|D, "idct"},
+#if FF_API_ARCH_ALPHA
+{"simplealpha", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLEALPHA }, INT_MIN, INT_MAX, V|E|D, "idct"},
+#endif
+#if FF_API_UNUSED_MEMBERS
+{"ipp", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_IPP }, INT_MIN, INT_MAX, V|E|D, "idct"},
+#endif /* FF_API_UNUSED_MEMBERS */
+{"xvid", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_XVID }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"xvidmmx", "deprecated, for compatibility only", 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_XVID }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"faani", "floating point AAN IDCT", 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_FAAN }, INT_MIN, INT_MAX, V|D|E, "idct"},
+{"simpleauto", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_IDCT_SIMPLEAUTO }, INT_MIN, INT_MAX, V|E|D, "idct"},
+{"slice_count", NULL, OFFSET(slice_count), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+{"ec", "set error concealment strategy", OFFSET(error_concealment), AV_OPT_TYPE_FLAGS, {.i64 = 3 }, INT_MIN, INT_MAX, V|D, "ec"},
+{"guess_mvs", "iterative motion vector (MV) search (slow)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_EC_GUESS_MVS }, INT_MIN, INT_MAX, V|D, "ec"},
+{"deblock", "use strong deblock filter for damaged MBs", 0, AV_OPT_TYPE_CONST, {.i64 = FF_EC_DEBLOCK }, INT_MIN, INT_MAX, V|D, "ec"},
+{"favor_inter", "favor predicting from the previous frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_EC_FAVOR_INTER }, INT_MIN, INT_MAX, V|D, "ec"},
+{"bits_per_coded_sample", NULL, OFFSET(bits_per_coded_sample), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX},
+#if FF_API_PRIVATE_OPT
+{"pred", "prediction method", OFFSET(prediction_method), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E, "pred"},
+{"left", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PRED_LEFT }, INT_MIN, INT_MAX, V|E, "pred"},
+{"plane", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PRED_PLANE }, INT_MIN, INT_MAX, V|E, "pred"},
+{"median", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PRED_MEDIAN }, INT_MIN, INT_MAX, V|E, "pred"},
+#endif
+{"aspect", "sample aspect ratio", OFFSET(sample_aspect_ratio), AV_OPT_TYPE_RATIONAL, {.dbl = 0}, 0, 10, V|E},
+{"sar", "sample aspect ratio", OFFSET(sample_aspect_ratio), AV_OPT_TYPE_RATIONAL, {.dbl = 0}, 0, 10, V|E},
+{"debug", "print specific debug info", OFFSET(debug), AV_OPT_TYPE_FLAGS, {.i64 = DEFAULT }, 0, INT_MAX, V|A|S|E|D, "debug"},
+{"pict", "picture info", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_PICT_INFO }, INT_MIN, INT_MAX, V|D, "debug"},
+{"rc", "rate control", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_RC }, INT_MIN, INT_MAX, V|E, "debug"},
+{"bitstream", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_BITSTREAM }, INT_MIN, INT_MAX, V|D, "debug"},
+{"mb_type", "macroblock (MB) type", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_MB_TYPE }, INT_MIN, INT_MAX, V|D, "debug"},
+{"qp", "per-block quantization parameter (QP)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_QP }, INT_MIN, INT_MAX, V|D, "debug"},
+#if FF_API_DEBUG_MV
+{"mv", "motion vector", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_MV }, INT_MIN, INT_MAX, V|D, "debug"},
+#endif
+{"dct_coeff", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_DCT_COEFF }, INT_MIN, INT_MAX, V|D, "debug"},
+{"green_metadata", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_GREEN_MD }, INT_MIN, INT_MAX, V|D, "debug"},
+{"skip", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_SKIP }, INT_MIN, INT_MAX, V|D, "debug"},
+{"startcode", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_STARTCODE }, INT_MIN, INT_MAX, V|D, "debug"},
+#if FF_API_UNUSED_MEMBERS
+{"pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_PTS }, INT_MIN, INT_MAX, V|D, "debug"},
+#endif /* FF_API_UNUSED_MEMBERS */
+{"er", "error recognition", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_ER }, INT_MIN, INT_MAX, V|D, "debug"},
+{"mmco", "memory management control operations (H.264)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_MMCO }, INT_MIN, INT_MAX, V|D, "debug"},
+{"bugs", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_BUGS }, INT_MIN, INT_MAX, V|D, "debug"},
+#if FF_API_DEBUG_MV
+{"vis_qp", "visualize quantization parameter (QP), lower QP are tinted greener", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_VIS_QP }, INT_MIN, INT_MAX, V|D, "debug"},
+{"vis_mb_type", "visualize block types", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_VIS_MB_TYPE }, INT_MIN, INT_MAX, V|D, "debug"},
+#endif
+{"buffers", "picture buffer allocations", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_BUFFERS }, INT_MIN, INT_MAX, V|D, "debug"},
+{"thread_ops", "threading operations", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_THREADS }, INT_MIN, INT_MAX, V|A|D, "debug"},
+{"nomc", "skip motion compensation", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_NOMC }, INT_MIN, INT_MAX, V|A|D, "debug"},
+#if FF_API_VISMV
+{"vismv", "visualize motion vectors (MVs) (deprecated)", OFFSET(debug_mv), AV_OPT_TYPE_FLAGS, {.i64 = DEFAULT }, 0, INT_MAX, V|D, "debug_mv"},
+{"pf", "forward predicted MVs of P-frames", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_VIS_MV_P_FOR }, INT_MIN, INT_MAX, V|D, "debug_mv"},
+{"bf", "forward predicted MVs of B-frames", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_VIS_MV_B_FOR }, INT_MIN, INT_MAX, V|D, "debug_mv"},
+{"bb", "backward predicted MVs of B-frames", 0, AV_OPT_TYPE_CONST, {.i64 = FF_DEBUG_VIS_MV_B_BACK }, INT_MIN, INT_MAX, V|D, "debug_mv"},
+#endif
+{"cmp", "full-pel ME compare function", OFFSET(me_cmp), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"subcmp", "sub-pel ME compare function", OFFSET(me_sub_cmp), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"mbcmp", "macroblock compare function", OFFSET(mb_cmp), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"ildctcmp", "interlaced DCT compare function", OFFSET(ildct_cmp), AV_OPT_TYPE_INT, {.i64 = FF_CMP_VSAD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"dia_size", "diamond type & size for motion estimation", OFFSET(dia_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+{"last_pred", "amount of motion predictors from the previous frame", OFFSET(last_predictor_count), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#if FF_API_PRIVATE_OPT
+{"preme", "pre motion estimation", OFFSET(pre_me), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+{"precmp", "pre motion estimation compare function", OFFSET(me_pre_cmp), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"sad", "sum of absolute differences, fast", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_SAD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"sse", "sum of squared errors", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_SSE }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"satd", "sum of absolute Hadamard transformed differences", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_SATD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"dct", "sum of absolute DCT transformed differences", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_DCT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"psnr", "sum of squared quantization errors (avoid, low quality)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_PSNR }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"bit", "number of bits needed for the block", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_BIT }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"rd", "rate distortion optimal, slow", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_RD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"zero", "0", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_ZERO }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"vsad", "sum of absolute vertical differences", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_VSAD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"vsse", "sum of squared vertical differences", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_VSSE }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"nsse", "noise preserving sum of squared differences", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_NSSE }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+#if CONFIG_SNOW_ENCODER
+{"w53", "5/3 wavelet, only used in snow", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_W53 }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"w97", "9/7 wavelet, only used in snow", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_W97 }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+#endif
+{"dctmax", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_DCTMAX }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"chroma", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_CHROMA }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"msad", "sum of absolute differences, median predicted", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CMP_MEDIAN_SAD }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+{"pre_dia_size", "diamond type & size for motion estimation pre-pass", OFFSET(pre_dia_size), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+{"subq", "sub-pel motion estimation quality", OFFSET(me_subpel_quality), AV_OPT_TYPE_INT, {.i64 = 8 }, INT_MIN, INT_MAX, V|E},
+#if FF_API_AFD
+{"dtg_active_format", NULL, OFFSET(dtg_active_format), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+#endif
+{"me_range", "limit motion vectors range (1023 for DivX player)", OFFSET(me_range), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#if FF_API_QUANT_BIAS
+{"ibias", "intra quant bias", OFFSET(intra_quant_bias), AV_OPT_TYPE_INT, {.i64 = FF_DEFAULT_QUANT_BIAS }, INT_MIN, INT_MAX, V|E},
+{"pbias", "inter quant bias", OFFSET(inter_quant_bias), AV_OPT_TYPE_INT, {.i64 = FF_DEFAULT_QUANT_BIAS }, INT_MIN, INT_MAX, V|E},
+#endif
+{"global_quality", NULL, OFFSET(global_quality), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
+#if FF_API_CODER_TYPE
+{"coder", NULL, OFFSET(coder_type), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E, "coder"},
+{"vlc", "variable length coder / Huffman coder", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CODER_TYPE_VLC }, INT_MIN, INT_MAX, V|E, "coder"},
+{"ac", "arithmetic coder", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CODER_TYPE_AC }, INT_MIN, INT_MAX, V|E, "coder"},
+{"raw", "raw (no encoding)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CODER_TYPE_RAW }, INT_MIN, INT_MAX, V|E, "coder"},
+{"rle", "run-length coder", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CODER_TYPE_RLE }, INT_MIN, INT_MAX, V|E, "coder"},
+#if FF_API_UNUSED_MEMBERS
+{"deflate", "deflate-based coder", 0, AV_OPT_TYPE_CONST, {.i64 = FF_CODER_TYPE_DEFLATE }, INT_MIN, INT_MAX, V|E, "coder"},
+#endif /* FF_API_UNUSED_MEMBERS */
+#endif /* FF_API_CODER_TYPE */
+#if FF_API_PRIVATE_OPT
+{"context", "context model", OFFSET(context_model), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+{"slice_flags", NULL, OFFSET(slice_flags), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+#if FF_API_XVMC
+{"xvmc_acceleration", NULL, OFFSET(xvmc_acceleration), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+#endif /* FF_API_XVMC */
+{"mbd", "macroblock decision algorithm (high quality mode)", OFFSET(mb_decision), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, 2, V|E, "mbd"},
+{"simple", "use mbcmp", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MB_DECISION_SIMPLE }, INT_MIN, INT_MAX, V|E, "mbd"},
+{"bits", "use fewest bits", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MB_DECISION_BITS }, INT_MIN, INT_MAX, V|E, "mbd"},
+{"rd", "use best rate distortion", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MB_DECISION_RD }, INT_MIN, INT_MAX, V|E, "mbd"},
+#if FF_API_STREAM_CODEC_TAG
+{"stream_codec_tag", NULL, OFFSET(stream_codec_tag), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX},
+#endif
+#if FF_API_PRIVATE_OPT
+{"sc_threshold", "scene change threshold", OFFSET(scenechange_threshold), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+#if FF_API_MPV_OPT
+{"lmin", "deprecated, use encoder private options instead", OFFSET(lmin), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, V|E},
+{"lmax", "deprecated, use encoder private options instead", OFFSET(lmax), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, V|E},
+#endif
+#if FF_API_PRIVATE_OPT
+{"nr", "noise reduction", OFFSET(noise_reduction), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+{"rc_init_occupancy", "number of bits which should be loaded into the rc buffer before decoding starts", OFFSET(rc_initial_buffer_occupancy), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+{"flags2", NULL, OFFSET(flags2), AV_OPT_TYPE_FLAGS, {.i64 = DEFAULT}, 0, UINT_MAX, V|A|E|D, "flags2"},
+#if FF_API_ERROR_RATE
+{"error", NULL, OFFSET(error_rate), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+{"threads", "set the number of threads", OFFSET(thread_count), AV_OPT_TYPE_INT, {.i64 = 1 }, 0, INT_MAX, V|A|E|D, "threads"},
+{"auto", "autodetect a suitable number of threads to use", 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, INT_MIN, INT_MAX, V|E|D, "threads"},
+#if FF_API_MPV_OPT
+{"me_threshold", "motion estimation threshold", OFFSET(me_threshold), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+{"mb_threshold", "macroblock threshold", OFFSET(mb_threshold), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+{"dc", "intra_dc_precision", OFFSET(intra_dc_precision), AV_OPT_TYPE_INT, {.i64 = 0 }, -8, 16, V|E},
+{"nssew", "nsse weight", OFFSET(nsse_weight), AV_OPT_TYPE_INT, {.i64 = 8 }, INT_MIN, INT_MAX, V|E},
+{"skip_top", "number of macroblock rows at the top which are skipped", OFFSET(skip_top), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|D},
+{"skip_bottom", "number of macroblock rows at the bottom which are skipped", OFFSET(skip_bottom), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|D},
+{"profile", NULL, OFFSET(profile), AV_OPT_TYPE_INT, {.i64 = FF_PROFILE_UNKNOWN }, INT_MIN, INT_MAX, V|A|E, "profile"},
+{"unknown", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_UNKNOWN }, INT_MIN, INT_MAX, V|A|E, "profile"},
+{"aac_main", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_AAC_MAIN }, INT_MIN, INT_MAX, A|E, "profile"},
+{"aac_low", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_AAC_LOW }, INT_MIN, INT_MAX, A|E, "profile"},
+{"aac_ssr", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_AAC_SSR }, INT_MIN, INT_MAX, A|E, "profile"},
+{"aac_ltp", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_AAC_LTP }, INT_MIN, INT_MAX, A|E, "profile"},
+{"aac_he", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_AAC_HE }, INT_MIN, INT_MAX, A|E, "profile"},
+{"aac_he_v2", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_AAC_HE_V2 }, INT_MIN, INT_MAX, A|E, "profile"},
+{"aac_ld", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_AAC_LD }, INT_MIN, INT_MAX, A|E, "profile"},
+{"aac_eld", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_AAC_ELD }, INT_MIN, INT_MAX, A|E, "profile"},
+{"mpeg2_aac_low", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_MPEG2_AAC_LOW }, INT_MIN, INT_MAX, A|E, "profile"},
+{"mpeg2_aac_he", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_MPEG2_AAC_HE }, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_DTS }, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts_es", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_DTS_ES }, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts_96_24", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_DTS_96_24 }, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts_hd_hra", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_DTS_HD_HRA }, INT_MIN, INT_MAX, A|E, "profile"},
+{"dts_hd_ma", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_DTS_HD_MA }, INT_MIN, INT_MAX, A|E, "profile"},
+{"mpeg4_sp", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_MPEG4_SIMPLE }, INT_MIN, INT_MAX, V|E, "profile"},
+{"mpeg4_core", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_MPEG4_CORE }, INT_MIN, INT_MAX, V|E, "profile"},
+{"mpeg4_main", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_MPEG4_MAIN }, INT_MIN, INT_MAX, V|E, "profile"},
+{"mpeg4_asp", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_MPEG4_ADVANCED_SIMPLE }, INT_MIN, INT_MAX, V|E, "profile"},
+{"main10", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_PROFILE_HEVC_MAIN_10 }, INT_MIN, INT_MAX, V|E, "profile"},
+{"level", NULL, OFFSET(level), AV_OPT_TYPE_INT, {.i64 = FF_LEVEL_UNKNOWN }, INT_MIN, INT_MAX, V|A|E, "level"},
+{"unknown", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LEVEL_UNKNOWN }, INT_MIN, INT_MAX, V|A|E, "level"},
+{"lowres", "decode at 1= 1/2, 2=1/4, 3=1/8 resolutions", OFFSET(lowres), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, V|A|D},
+#if FF_API_PRIVATE_OPT
+{"skip_threshold", "frame skip threshold", OFFSET(frame_skip_threshold), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+{"skip_factor", "frame skip factor", OFFSET(frame_skip_factor), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+{"skip_exp", "frame skip exponent", OFFSET(frame_skip_exp), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+{"skipcmp", "frame skip compare function", OFFSET(frame_skip_cmp), AV_OPT_TYPE_INT, {.i64 = FF_CMP_DCTMAX }, INT_MIN, INT_MAX, V|E, "cmp_func"},
+#endif
+#if FF_API_MPV_OPT
+{"border_mask", "deprecated, use encoder private options instead", OFFSET(border_masking), AV_OPT_TYPE_FLOAT, {.dbl = DEFAULT }, -FLT_MAX, FLT_MAX, V|E},
+#endif
+{"mblmin", "minimum macroblock Lagrange factor (VBR)", OFFSET(mb_lmin), AV_OPT_TYPE_INT, {.i64 = FF_QP2LAMBDA * 2 }, 1, FF_LAMBDA_MAX, V|E},
+{"mblmax", "maximum macroblock Lagrange factor (VBR)", OFFSET(mb_lmax), AV_OPT_TYPE_INT, {.i64 = FF_QP2LAMBDA * 31 }, 1, FF_LAMBDA_MAX, V|E},
+#if FF_API_PRIVATE_OPT
+{"mepc", "motion estimation bitrate penalty compensation (1.0 = 256)", OFFSET(me_penalty_compensation), AV_OPT_TYPE_INT, {.i64 = 256 }, INT_MIN, INT_MAX, V|E},
+#endif
+{"skip_loop_filter", "skip loop filtering process for the selected frames", OFFSET(skip_loop_filter), AV_OPT_TYPE_INT, {.i64 = AVDISCARD_DEFAULT }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"skip_idct" , "skip IDCT/dequantization for the selected frames", OFFSET(skip_idct), AV_OPT_TYPE_INT, {.i64 = AVDISCARD_DEFAULT }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"skip_frame" , "skip decoding for the selected frames", OFFSET(skip_frame), AV_OPT_TYPE_INT, {.i64 = AVDISCARD_DEFAULT }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"none" , "discard no frame", 0, AV_OPT_TYPE_CONST, {.i64 = AVDISCARD_NONE }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"default" , "discard useless frames", 0, AV_OPT_TYPE_CONST, {.i64 = AVDISCARD_DEFAULT }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"noref" , "discard all non-reference frames", 0, AV_OPT_TYPE_CONST, {.i64 = AVDISCARD_NONREF }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"bidir" , "discard all bidirectional frames", 0, AV_OPT_TYPE_CONST, {.i64 = AVDISCARD_BIDIR }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"nokey" , "discard all frames except keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = AVDISCARD_NONKEY }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"nointra" , "discard all frames except I frames", 0, AV_OPT_TYPE_CONST, {.i64 = AVDISCARD_NONINTRA}, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"all" , "discard all frames", 0, AV_OPT_TYPE_CONST, {.i64 = AVDISCARD_ALL }, INT_MIN, INT_MAX, V|D, "avdiscard"},
+{"bidir_refine", "refine the two motion vectors used in bidirectional macroblocks", OFFSET(bidir_refine), AV_OPT_TYPE_INT, {.i64 = 1 }, 0, 4, V|E},
+#if FF_API_PRIVATE_OPT
+{"brd_scale", "downscale frames for dynamic B-frame decision", OFFSET(brd_scale), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, 10, V|E},
+#endif
+{"keyint_min", "minimum interval between IDR-frames", OFFSET(keyint_min), AV_OPT_TYPE_INT, {.i64 = 25 }, INT_MIN, INT_MAX, V|E},
+{"refs", "reference frames to consider for motion compensation", OFFSET(refs), AV_OPT_TYPE_INT, {.i64 = 1 }, INT_MIN, INT_MAX, V|E},
+#if FF_API_PRIVATE_OPT
+{"chromaoffset", "chroma QP offset from luma", OFFSET(chromaoffset), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|E},
+#endif
+{"trellis", "rate-distortion optimal quantization", OFFSET(trellis), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, INT_MIN, INT_MAX, V|A|E},
+#if FF_API_UNUSED_MEMBERS
+{"sc_factor", "multiplied by qscale for each frame and added to scene_change_score", OFFSET(scenechange_factor), AV_OPT_TYPE_INT, {.i64 = 6 }, 0, INT_MAX, V|E},
+#endif /* FF_API_UNUSED_MEMBERS */
+{"mv0_threshold", NULL, OFFSET(mv0_threshold), AV_OPT_TYPE_INT, {.i64 = 256 }, 0, INT_MAX, V|E},
+#if FF_API_PRIVATE_OPT
+{"b_sensitivity", "adjust sensitivity of b_frame_strategy 1", OFFSET(b_sensitivity), AV_OPT_TYPE_INT, {.i64 = 40 }, 1, INT_MAX, V|E},
+#endif
+{"compression_level", NULL, OFFSET(compression_level), AV_OPT_TYPE_INT, {.i64 = FF_COMPRESSION_DEFAULT }, INT_MIN, INT_MAX, V|A|E},
+#if FF_API_PRIVATE_OPT
+{"min_prediction_order", NULL, OFFSET(min_prediction_order), AV_OPT_TYPE_INT, {.i64 = -1 }, INT_MIN, INT_MAX, A|E},
+{"max_prediction_order", NULL, OFFSET(max_prediction_order), AV_OPT_TYPE_INT, {.i64 = -1 }, INT_MIN, INT_MAX, A|E},
+{"timecode_frame_start", "GOP timecode frame start number, in non-drop-frame format", OFFSET(timecode_frame_start), AV_OPT_TYPE_INT64, {.i64 = -1 }, -1, INT64_MAX, V|E},
+#endif
+{"bits_per_raw_sample", NULL, OFFSET(bits_per_raw_sample), AV_OPT_TYPE_INT, {.i64 = DEFAULT }, 0, INT_MAX},
+{"channel_layout", NULL, OFFSET(channel_layout), AV_OPT_TYPE_UINT64, {.i64 = DEFAULT }, 0, UINT64_MAX, A|E|D, "channel_layout"},
+{"request_channel_layout", NULL, OFFSET(request_channel_layout), AV_OPT_TYPE_UINT64, {.i64 = DEFAULT }, 0, UINT64_MAX, A|D, "request_channel_layout"},
+{"rc_max_vbv_use", NULL, OFFSET(rc_max_available_vbv_use), AV_OPT_TYPE_FLOAT, {.dbl = 0 }, 0.0, FLT_MAX, V|E},
+{"rc_min_vbv_use", NULL, OFFSET(rc_min_vbv_overflow_use), AV_OPT_TYPE_FLOAT, {.dbl = 3 }, 0.0, FLT_MAX, V|E},
+{"ticks_per_frame", NULL, OFFSET(ticks_per_frame), AV_OPT_TYPE_INT, {.i64 = 1 }, 1, INT_MAX, A|V|E|D},
+{"color_primaries", "color primaries", OFFSET(color_primaries), AV_OPT_TYPE_INT, {.i64 = AVCOL_PRI_UNSPECIFIED }, 1, INT_MAX, V|E|D, "color_primaries_type"},
+{"bt709", "BT.709", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_BT709 }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"unknown", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"bt470m", "BT.470 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_BT470M }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"bt470bg", "BT.470 BG", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_BT470BG }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"smpte170m", "SMPTE 170 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_SMPTE170M }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"smpte240m", "SMPTE 240 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_SMPTE240M }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"film", "Film", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_FILM }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"bt2020", "BT.2020", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_BT2020 }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"smpte428", "SMPTE 428-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_SMPTE428 }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"smpte428_1", "SMPTE 428-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_SMPTE428 }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"smpte431", "SMPTE 431-2", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_SMPTE431 }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"smpte432", "SMPTE 422-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_SMPTE432 }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"jedec-p22", "JEDEC P22", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_JEDEC_P22 }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"unspecified", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_PRI_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "color_primaries_type"},
+{"color_trc", "color transfer characteristics", OFFSET(color_trc), AV_OPT_TYPE_INT, {.i64 = AVCOL_TRC_UNSPECIFIED }, 1, INT_MAX, V|E|D, "color_trc_type"},
+{"bt709", "BT.709", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT709 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"unknown", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"gamma22", "BT.470 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA22 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"gamma28", "BT.470 BG", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_GAMMA28 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"smpte170m", "SMPTE 170 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE170M }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"smpte240m", "SMPTE 240 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE240M }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"linear", "Linear", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LINEAR }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"log100", "Log", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"log316", "Log square root", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"iec61966-2-4", "IEC 61966-2-4", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"bt1361e", "BT.1361", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"iec61966-2-1", "IEC 61966-2-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"bt2020-10", "BT.2020 - 10 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"bt2020-12", "BT.2020 - 12 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"smpte2084", "SMPTE 2084", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE2084 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"smpte428", "SMPTE 428-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE428 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"arib-std-b67", "ARIB STD-B67", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_ARIB_STD_B67 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"unspecified", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"log", "Log", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"log_sqrt", "Log square root", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_LOG_SQRT }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"iec61966_2_4", "IEC 61966-2-4", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_4 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"bt1361", "BT.1361", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT1361_ECG }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"iec61966_2_1", "IEC 61966-2-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_IEC61966_2_1 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"bt2020_10bit", "BT.2020 - 10 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_10 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"bt2020_12bit", "BT.2020 - 12 bit", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_BT2020_12 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"smpte428_1", "SMPTE 428-1", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_TRC_SMPTE428 }, INT_MIN, INT_MAX, V|E|D, "color_trc_type"},
+{"colorspace", "color space", OFFSET(colorspace), AV_OPT_TYPE_INT, {.i64 = AVCOL_SPC_UNSPECIFIED }, 0, INT_MAX, V|E|D, "colorspace_type"},
+{"rgb", "RGB", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_RGB }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"bt709", "BT.709", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_BT709 }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"unknown", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"fcc", "FCC", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_FCC }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"bt470bg", "BT.470 BG", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_BT470BG }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"smpte170m", "SMPTE 170 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_SMPTE170M }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"smpte240m", "SMPTE 240 M", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_SMPTE240M }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"ycgco", "YCGCO", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_YCGCO }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"bt2020nc", "BT.2020 NCL", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_BT2020_NCL }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"bt2020c", "BT.2020 CL", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_BT2020_CL }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"smpte2085", "SMPTE 2085", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_SMPTE2085 }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"unspecified", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"ycocg", "YCGCO", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_YCGCO }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"bt2020_ncl", "BT.2020 NCL", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_BT2020_NCL }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"bt2020_cl", "BT.2020 CL", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_SPC_BT2020_CL }, INT_MIN, INT_MAX, V|E|D, "colorspace_type"},
+{"color_range", "color range", OFFSET(color_range), AV_OPT_TYPE_INT, {.i64 = AVCOL_RANGE_UNSPECIFIED }, 0, INT_MAX, V|E|D, "color_range_type"},
+{"unknown", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "color_range_type"},
+{"tv", "MPEG (219*2^(n-8))", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_MPEG }, INT_MIN, INT_MAX, V|E|D, "color_range_type"},
+{"pc", "JPEG (2^n-1)", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_JPEG }, INT_MIN, INT_MAX, V|E|D, "color_range_type"},
+{"unspecified", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "color_range_type"},
+{"mpeg", "MPEG (219*2^(n-8))", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_MPEG }, INT_MIN, INT_MAX, V|E|D, "color_range_type"},
+{"jpeg", "JPEG (2^n-1)", 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_JPEG }, INT_MIN, INT_MAX, V|E|D, "color_range_type"},
+{"chroma_sample_location", "chroma sample location", OFFSET(chroma_sample_location), AV_OPT_TYPE_INT, {.i64 = AVCHROMA_LOC_UNSPECIFIED }, 0, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"unknown", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCHROMA_LOC_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"left", "Left", 0, AV_OPT_TYPE_CONST, {.i64 = AVCHROMA_LOC_LEFT }, INT_MIN, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"center", "Center", 0, AV_OPT_TYPE_CONST, {.i64 = AVCHROMA_LOC_CENTER }, INT_MIN, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"topleft", "Top-left", 0, AV_OPT_TYPE_CONST, {.i64 = AVCHROMA_LOC_TOPLEFT }, INT_MIN, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"top", "Top", 0, AV_OPT_TYPE_CONST, {.i64 = AVCHROMA_LOC_TOP }, INT_MIN, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"bottomleft", "Bottom-left", 0, AV_OPT_TYPE_CONST, {.i64 = AVCHROMA_LOC_BOTTOMLEFT }, INT_MIN, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"bottom", "Bottom", 0, AV_OPT_TYPE_CONST, {.i64 = AVCHROMA_LOC_BOTTOM }, INT_MIN, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"unspecified", "Unspecified", 0, AV_OPT_TYPE_CONST, {.i64 = AVCHROMA_LOC_UNSPECIFIED }, INT_MIN, INT_MAX, V|E|D, "chroma_sample_location_type"},
+{"log_level_offset", "set the log level offset", OFFSET(log_level_offset), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX },
+{"slices", "set the number of slices, used in parallelized encoding", OFFSET(slices), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, V|E},
+{"thread_type", "select multithreading type", OFFSET(thread_type), AV_OPT_TYPE_FLAGS, {.i64 = FF_THREAD_SLICE|FF_THREAD_FRAME }, 0, INT_MAX, V|A|E|D, "thread_type"},
+{"slice", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_THREAD_SLICE }, INT_MIN, INT_MAX, V|E|D, "thread_type"},
+{"frame", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_THREAD_FRAME }, INT_MIN, INT_MAX, V|E|D, "thread_type"},
+{"audio_service_type", "audio service type", OFFSET(audio_service_type), AV_OPT_TYPE_INT, {.i64 = AV_AUDIO_SERVICE_TYPE_MAIN }, 0, AV_AUDIO_SERVICE_TYPE_NB-1, A|E, "audio_service_type"},
+{"ma", "Main Audio Service", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_MAIN }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"ef", "Effects", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_EFFECTS }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"vi", "Visually Impaired", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_VISUALLY_IMPAIRED }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"hi", "Hearing Impaired", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_HEARING_IMPAIRED }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"di", "Dialogue", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_DIALOGUE }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"co", "Commentary", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_COMMENTARY }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"em", "Emergency", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_EMERGENCY }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"vo", "Voice Over", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_VOICE_OVER }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"ka", "Karaoke", 0, AV_OPT_TYPE_CONST, {.i64 = AV_AUDIO_SERVICE_TYPE_KARAOKE }, INT_MIN, INT_MAX, A|E, "audio_service_type"},
+{"request_sample_fmt", "sample format audio decoders should prefer", OFFSET(request_sample_fmt), AV_OPT_TYPE_SAMPLE_FMT, {.i64=AV_SAMPLE_FMT_NONE}, -1, INT_MAX, A|D, "request_sample_fmt"},
+{"pkt_timebase", NULL, OFFSET(pkt_timebase), AV_OPT_TYPE_RATIONAL, {.dbl = 0 }, 0, INT_MAX, 0},
+{"sub_charenc", "set input text subtitles character encoding", OFFSET(sub_charenc), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, S|D},
+{"sub_charenc_mode", "set input text subtitles character encoding mode", OFFSET(sub_charenc_mode), AV_OPT_TYPE_FLAGS, {.i64 = FF_SUB_CHARENC_MODE_AUTOMATIC}, -1, INT_MAX, S|D, "sub_charenc_mode"},
+{"do_nothing", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_SUB_CHARENC_MODE_DO_NOTHING}, INT_MIN, INT_MAX, S|D, "sub_charenc_mode"},
+{"auto", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_SUB_CHARENC_MODE_AUTOMATIC}, INT_MIN, INT_MAX, S|D, "sub_charenc_mode"},
+{"pre_decoder", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_SUB_CHARENC_MODE_PRE_DECODER}, INT_MIN, INT_MAX, S|D, "sub_charenc_mode"},
+#if FF_API_ASS_TIMING
+{"sub_text_format", "set decoded text subtitle format", OFFSET(sub_text_format), AV_OPT_TYPE_INT, {.i64 = FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS}, 0, 1, S|D, "sub_text_format"},
+#else
+{"sub_text_format", "set decoded text subtitle format", OFFSET(sub_text_format), AV_OPT_TYPE_INT, {.i64 = FF_SUB_TEXT_FMT_ASS}, 0, 1, S|D, "sub_text_format"},
+#endif
+{"ass", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_SUB_TEXT_FMT_ASS}, INT_MIN, INT_MAX, S|D, "sub_text_format"},
+#if FF_API_ASS_TIMING
+{"ass_with_timings", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS}, INT_MIN, INT_MAX, S|D, "sub_text_format"},
+#endif
+{"refcounted_frames", NULL, OFFSET(refcounted_frames), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, A|V|D },
+#if FF_API_SIDEDATA_ONLY_PKT
+{"side_data_only_packets", NULL, OFFSET(side_data_only_packets), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, A|V|E },
+#endif
+{"apply_cropping", NULL, OFFSET(apply_cropping), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, V | D },
+{"skip_alpha", "Skip processing alpha", OFFSET(skip_alpha), AV_OPT_TYPE_BOOL, {.i64 = 0 }, 0, 1, V|D },
+{"field_order", "Field order", OFFSET(field_order), AV_OPT_TYPE_INT, {.i64 = AV_FIELD_UNKNOWN }, 0, 5, V|D|E, "field_order" },
+{"progressive", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AV_FIELD_PROGRESSIVE }, 0, 0, V|D|E, "field_order" },
+{"tt", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AV_FIELD_TT }, 0, 0, V|D|E, "field_order" },
+{"bb", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AV_FIELD_BB }, 0, 0, V|D|E, "field_order" },
+{"tb", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AV_FIELD_TB }, 0, 0, V|D|E, "field_order" },
+{"bt", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AV_FIELD_BT }, 0, 0, V|D|E, "field_order" },
+{"dump_separator", "set information dump field separator", OFFSET(dump_separator), AV_OPT_TYPE_STRING, {.str = NULL}, CHAR_MIN, CHAR_MAX, A|V|S|D|E},
+{"codec_whitelist", "List of decoders that are allowed to be used", OFFSET(codec_whitelist), AV_OPT_TYPE_STRING, { .str = NULL }, CHAR_MIN, CHAR_MAX, A|V|S|D },
+{"pixel_format", "set pixel format", OFFSET(pix_fmt), AV_OPT_TYPE_PIXEL_FMT, {.i64=AV_PIX_FMT_NONE}, -1, INT_MAX, 0 },
+{"video_size", "set video size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str=NULL}, 0, INT_MAX, 0 },
+{"max_pixels", "Maximum number of pixels", OFFSET(max_pixels), AV_OPT_TYPE_INT64, {.i64 = INT_MAX }, 0, INT_MAX, A|V|S|D|E },
+{"hwaccel_flags", NULL, OFFSET(hwaccel_flags), AV_OPT_TYPE_FLAGS, {.i64 = AV_HWACCEL_FLAG_IGNORE_LEVEL }, 0, UINT_MAX, V|D, "hwaccel_flags"},
+{"ignore_level", "ignore level even if the codec level used is unknown or higher than the maximum supported level reported by the hardware driver", 0, AV_OPT_TYPE_CONST, { .i64 = AV_HWACCEL_FLAG_IGNORE_LEVEL }, INT_MIN, INT_MAX, V | D, "hwaccel_flags" },
+{"allow_high_depth", "allow to output YUV pixel formats with a different chroma sampling than 4:2:0 and/or other than 8 bits per component", 0, AV_OPT_TYPE_CONST, {.i64 = AV_HWACCEL_FLAG_ALLOW_HIGH_DEPTH }, INT_MIN, INT_MAX, V | D, "hwaccel_flags"},
+{"allow_profile_mismatch", "attempt to decode anyway if HW accelerated decoder's supported profiles do not exactly match the stream", 0, AV_OPT_TYPE_CONST, {.i64 = AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH }, INT_MIN, INT_MAX, V | D, "hwaccel_flags"},
+{NULL},
+};
+
+#undef A
+#undef V
+#undef S
+#undef E
+#undef D
+#undef DEFAULT
+#undef OFFSET
+
+#endif /* AVCODEC_OPTIONS_TABLE_H */
diff --git a/media/ffvpx/libavcodec/parser.c b/media/ffvpx/libavcodec/parser.c
index 30cfc55cb..670680ea7 100644
--- a/media/ffvpx/libavcodec/parser.c
+++ b/media/ffvpx/libavcodec/parser.c
@@ -20,6 +20,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+#include <inttypes.h>
#include <stdint.h>
#include <string.h>
@@ -251,7 +252,7 @@ int ff_combine_frame(ParseContext *pc, int next,
const uint8_t **buf, int *buf_size)
{
if (pc->overread) {
- ff_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
+ ff_dlog(NULL, "overread %d, state:%"PRIX32" next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
ff_dlog(NULL, "%X %X %X %X\n",
(*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);
@@ -284,6 +285,8 @@ int ff_combine_frame(ParseContext *pc, int next,
return -1;
}
+ av_assert0(next >= 0 || pc->buffer);
+
*buf_size =
pc->overread_index = pc->index + next;
@@ -314,7 +317,7 @@ int ff_combine_frame(ParseContext *pc, int next,
}
if (pc->overread) {
- ff_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
+ ff_dlog(NULL, "overread %d, state:%"PRIX32" next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
ff_dlog(NULL, "%X %X %X %X\n",
(*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);
diff --git a/media/ffvpx/libavcodec/pixblockdsp.h b/media/ffvpx/libavcodec/pixblockdsp.h
index 79ed86c3a..e036700ff 100644
--- a/media/ffvpx/libavcodec/pixblockdsp.h
+++ b/media/ffvpx/libavcodec/pixblockdsp.h
@@ -21,16 +21,23 @@
#include <stdint.h>
+#include "config.h"
+
#include "avcodec.h"
typedef struct PixblockDSPContext {
- void (*get_pixels)(int16_t *block /* align 16 */,
+ void (*get_pixels)(int16_t *av_restrict block /* align 16 */,
const uint8_t *pixels /* align 8 */,
- ptrdiff_t line_size);
- void (*diff_pixels)(int16_t *block /* align 16 */,
+ ptrdiff_t stride);
+ void (*diff_pixels)(int16_t *av_restrict block /* align 16 */,
const uint8_t *s1 /* align 8 */,
const uint8_t *s2 /* align 8 */,
- int stride);
+ ptrdiff_t stride);
+ void (*diff_pixels_unaligned)(int16_t *av_restrict block /* align 16 */,
+ const uint8_t *s1,
+ const uint8_t *s2,
+ ptrdiff_t stride);
+
} PixblockDSPContext;
void ff_pixblockdsp_init(PixblockDSPContext *c, AVCodecContext *avctx);
diff --git a/media/ffvpx/libavcodec/profiles.c b/media/ffvpx/libavcodec/profiles.c
index da745e139..30498efed 100644
--- a/media/ffvpx/libavcodec/profiles.c
+++ b/media/ffvpx/libavcodec/profiles.c
@@ -46,6 +46,16 @@ const AVProfile ff_dca_profiles[] = {
{ FF_PROFILE_UNKNOWN },
};
+const AVProfile ff_dnxhd_profiles[] = {
+ { FF_PROFILE_DNXHD, "DNXHD"},
+ { FF_PROFILE_DNXHR_LB, "DNXHR LB"},
+ { FF_PROFILE_DNXHR_SQ, "DNXHR SQ"},
+ { FF_PROFILE_DNXHR_HQ, "DNXHR HQ" },
+ { FF_PROFILE_DNXHR_HQX, "DNXHR HQX"},
+ { FF_PROFILE_DNXHR_444, "DNXHR 444"},
+ { FF_PROFILE_UNKNOWN },
+};
+
const AVProfile ff_h264_profiles[] = {
{ FF_PROFILE_H264_BASELINE, "Baseline" },
{ FF_PROFILE_H264_CONSTRAINED_BASELINE, "Constrained Baseline" },
@@ -60,6 +70,8 @@ const AVProfile ff_h264_profiles[] = {
{ FF_PROFILE_H264_HIGH_444_PREDICTIVE, "High 4:4:4 Predictive" },
{ FF_PROFILE_H264_HIGH_444_INTRA, "High 4:4:4 Intra" },
{ FF_PROFILE_H264_CAVLC_444, "CAVLC 4:4:4" },
+ { FF_PROFILE_H264_MULTIVIEW_HIGH, "Multiview High" },
+ { FF_PROFILE_H264_STEREO_HIGH, "Stereo High" },
{ FF_PROFILE_UNKNOWN },
};
diff --git a/media/ffvpx/libavcodec/profiles.h b/media/ffvpx/libavcodec/profiles.h
index c86c683ab..eb18b406a 100644
--- a/media/ffvpx/libavcodec/profiles.h
+++ b/media/ffvpx/libavcodec/profiles.h
@@ -23,6 +23,7 @@
extern const AVProfile ff_aac_profiles[];
extern const AVProfile ff_dca_profiles[];
+extern const AVProfile ff_dnxhd_profiles[];
extern const AVProfile ff_h264_profiles[];
extern const AVProfile ff_hevc_profiles[];
extern const AVProfile ff_jpeg2000_profiles[];
diff --git a/media/ffvpx/libavcodec/pthread_frame.c b/media/ffvpx/libavcodec/pthread_frame.c
index a10fcbfe7..2c702c737 100644
--- a/media/ffvpx/libavcodec/pthread_frame.c
+++ b/media/ffvpx/libavcodec/pthread_frame.c
@@ -24,9 +24,11 @@
#include "config.h"
+#include <stdatomic.h>
#include <stdint.h>
#include "avcodec.h"
+#include "hwaccel.h"
#include "internal.h"
#include "pthread_internal.h"
#include "thread.h"
@@ -43,29 +45,28 @@
#include "libavutil/opt.h"
#include "libavutil/thread.h"
-#if defined(MOZ_TSAN)
-typedef _Atomic(int) atomic_int;
-#else
-typedef volatile int atomic_int;
-#endif
+enum {
+ ///< Set when the thread is awaiting a packet.
+ STATE_INPUT_READY,
+ ///< Set before the codec has called ff_thread_finish_setup().
+ STATE_SETTING_UP,
+ /**
+ * Set when the codec calls get_buffer().
+ * State is returned to STATE_SETTING_UP afterwards.
+ */
+ STATE_GET_BUFFER,
+ /**
+ * Set when the codec calls get_format().
+ * State is returned to STATE_SETTING_UP afterwards.
+ */
+ STATE_GET_FORMAT,
+ ///< Set after the codec has called ff_thread_finish_setup().
+ STATE_SETUP_FINISHED,
+};
/**
* Context used by codec threads and stored in their AVCodecInternal thread_ctx.
*/
-typedef enum {
- STATE_INPUT_READY, ///< Set when the thread is awaiting a packet.
- STATE_SETTING_UP, ///< Set before the codec has called ff_thread_finish_setup().
- STATE_GET_BUFFER, /**<
- * Set when the codec calls get_buffer().
- * State is returned to STATE_SETTING_UP afterwards.
- */
- STATE_GET_FORMAT, /**<
- * Set when the codec calls get_format().
- * State is returned to STATE_SETTING_UP afterwards.
- */
- STATE_SETUP_FINISHED ///< Set after the codec has called ff_thread_finish_setup().
-} State;
-
typedef struct PerThreadContext {
struct FrameThreadContext *parent;
@@ -103,6 +104,11 @@ typedef struct PerThreadContext {
enum AVPixelFormat result_format; ///< get_format() result
int die; ///< Set when the thread should exit.
+
+ int hwaccel_serializing;
+ int async_serializing;
+
+ atomic_int debug_threads; ///< Set if the FF_DEBUG_THREADS option is set.
} PerThreadContext;
/**
@@ -113,6 +119,14 @@ typedef struct FrameThreadContext {
PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
pthread_mutex_t buffer_mutex; ///< Mutex used to protect get/release_buffer().
+ /**
+ * This lock is used for ensuring threads run in serial when hwaccel
+ * is used.
+ */
+ pthread_mutex_t hwaccel_mutex;
+ pthread_mutex_t async_mutex;
+ pthread_cond_t async_cond;
+ int async_lock;
int next_decoding; ///< The next context to submit a packet to.
int next_finished; ///< The next context to return output from.
@@ -126,6 +140,24 @@ typedef struct FrameThreadContext {
#define THREAD_SAFE_CALLBACKS(avctx) \
((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
+static void async_lock(FrameThreadContext *fctx)
+{
+ pthread_mutex_lock(&fctx->async_mutex);
+ while (fctx->async_lock)
+ pthread_cond_wait(&fctx->async_cond, &fctx->async_mutex);
+ fctx->async_lock = 1;
+ pthread_mutex_unlock(&fctx->async_mutex);
+}
+
+static void async_unlock(FrameThreadContext *fctx)
+{
+ pthread_mutex_lock(&fctx->async_mutex);
+ av_assert0(fctx->async_lock);
+ fctx->async_lock = 0;
+ pthread_cond_broadcast(&fctx->async_cond);
+ pthread_mutex_unlock(&fctx->async_mutex);
+}
+
/**
* Codec worker thread.
*
@@ -141,14 +173,29 @@ static attribute_align_arg void *frame_worker_thread(void *arg)
pthread_mutex_lock(&p->mutex);
while (1) {
- while (p->state == STATE_INPUT_READY && !p->die)
- pthread_cond_wait(&p->input_cond, &p->mutex);
+ while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
+ pthread_cond_wait(&p->input_cond, &p->mutex);
if (p->die) break;
if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
ff_thread_finish_setup(avctx);
+ /* If a decoder supports hwaccel, then it must call ff_get_format().
+ * Since that call must happen before ff_thread_finish_setup(), the
+ * decoder is required to implement update_thread_context() and call
+ * ff_thread_finish_setup() manually. Therefore the above
+ * ff_thread_finish_setup() call did not happen and hwaccel_serializing
+ * cannot be true here. */
+ av_assert0(!p->hwaccel_serializing);
+
+ /* if the previous thread uses hwaccel then we take the lock to ensure
+ * the threads don't run concurrently */
+ if (avctx->hwaccel) {
+ pthread_mutex_lock(&p->parent->hwaccel_mutex);
+ p->hwaccel_serializing = 1;
+ }
+
av_frame_unref(p->frame);
p->got_frame = 0;
p->result = codec->decode(avctx, p->frame, &p->got_frame, &p->avpkt);
@@ -160,17 +207,23 @@ static attribute_align_arg void *frame_worker_thread(void *arg)
av_frame_unref(p->frame);
}
- if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
+ if (atomic_load(&p->state) == STATE_SETTING_UP)
+ ff_thread_finish_setup(avctx);
+
+ if (p->hwaccel_serializing) {
+ p->hwaccel_serializing = 0;
+ pthread_mutex_unlock(&p->parent->hwaccel_mutex);
+ }
+
+ if (p->async_serializing) {
+ p->async_serializing = 0;
+
+ async_unlock(p->parent);
+ }
pthread_mutex_lock(&p->progress_mutex);
-#if 0 //BUFREF-FIXME
- for (i = 0; i < MAX_BUFFERS; i++)
- if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
- p->progress[i][0] = INT_MAX;
- p->progress[i][1] = INT_MAX;
- }
-#endif
- p->state = STATE_INPUT_READY;
+
+ atomic_store(&p->state, STATE_INPUT_READY);
pthread_cond_broadcast(&p->progress_cond);
pthread_cond_signal(&p->output_cond);
@@ -193,12 +246,13 @@ static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src,
{
int err = 0;
- if (dst != src) {
+ if (dst != src && (for_user || !(av_codec_get_codec_descriptor(src)->props & AV_CODEC_PROP_INTRA_ONLY))) {
dst->time_base = src->time_base;
dst->framerate = src->framerate;
dst->width = src->width;
dst->height = src->height;
dst->pix_fmt = src->pix_fmt;
+ dst->sw_pix_fmt = src->sw_pix_fmt;
dst->coded_width = src->coded_width;
dst->coded_height = src->coded_height;
@@ -234,6 +288,19 @@ FF_ENABLE_DEPRECATION_WARNINGS
dst->sample_fmt = src->sample_fmt;
dst->channel_layout = src->channel_layout;
dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
+
+ if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
+ (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
+ av_buffer_unref(&dst->hw_frames_ctx);
+
+ if (src->hw_frames_ctx) {
+ dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
+ if (!dst->hw_frames_ctx)
+ return AVERROR(ENOMEM);
+ }
+ }
+
+ dst->hwaccel_flags = src->hwaccel_flags;
}
if (for_user) {
@@ -315,24 +382,35 @@ static void release_delayed_buffers(PerThreadContext *p)
}
}
-static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
+static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
+ AVPacket *avpkt)
{
FrameThreadContext *fctx = p->parent;
PerThreadContext *prev_thread = fctx->prev_thread;
const AVCodec *codec = p->avctx->codec;
+ int ret;
if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
return 0;
pthread_mutex_lock(&p->mutex);
+ ret = update_context_from_user(p->avctx, user_avctx);
+ if (ret) {
+ pthread_mutex_unlock(&p->mutex);
+ return ret;
+ }
+ atomic_store_explicit(&p->debug_threads,
+ (p->avctx->debug & FF_DEBUG_THREADS) != 0,
+ memory_order_relaxed);
+
release_delayed_buffers(p);
if (prev_thread) {
int err;
- if (prev_thread->state == STATE_SETTING_UP) {
+ if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
pthread_mutex_lock(&prev_thread->progress_mutex);
- while (prev_thread->state == STATE_SETTING_UP)
+ while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
pthread_mutex_unlock(&prev_thread->progress_mutex);
}
@@ -345,9 +423,14 @@ static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
}
av_packet_unref(&p->avpkt);
- av_packet_ref(&p->avpkt, avpkt);
+ ret = av_packet_ref(&p->avpkt, avpkt);
+ if (ret < 0) {
+ pthread_mutex_unlock(&p->mutex);
+ av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
+ return ret;
+ }
- p->state = STATE_SETTING_UP;
+ atomic_store(&p->state, STATE_SETTING_UP);
pthread_cond_signal(&p->input_cond);
pthread_mutex_unlock(&p->mutex);
@@ -360,14 +443,13 @@ static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
if (!p->avctx->thread_safe_callbacks && (
p->avctx->get_format != avcodec_default_get_format ||
p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
- while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
+ while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
int call_done = 1;
pthread_mutex_lock(&p->progress_mutex);
- while (p->state == STATE_SETTING_UP)
+ while (atomic_load(&p->state) == STATE_SETTING_UP)
pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
- State p_state = (State)p->state;
- switch (p_state) {
+ switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
case STATE_GET_BUFFER:
p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
break;
@@ -379,7 +461,7 @@ static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
break;
}
if (call_done) {
- p->state = STATE_SETTING_UP;
+ atomic_store(&p->state, STATE_SETTING_UP);
pthread_cond_signal(&p->progress_cond);
}
pthread_mutex_unlock(&p->progress_mutex);
@@ -401,15 +483,18 @@ int ff_thread_decode_frame(AVCodecContext *avctx,
PerThreadContext *p;
int err;
+ /* release the async lock, permitting blocked hwaccel threads to
+ * go forward while we are in this function */
+ async_unlock(fctx);
+
/*
* Submit a packet to the next decoding thread.
*/
p = &fctx->threads[fctx->next_decoding];
- err = update_context_from_user(p->avctx, avctx);
- if (err) return err;
- err = submit_packet(p, avpkt);
- if (err) return err;
+ err = submit_packet(p, avctx, avpkt);
+ if (err)
+ goto finish;
/*
* If we're still receiving the initial packets, don't return a frame.
@@ -420,23 +505,25 @@ int ff_thread_decode_frame(AVCodecContext *avctx,
if (fctx->delaying) {
*got_picture_ptr=0;
- if (avpkt->size)
- return avpkt->size;
+ if (avpkt->size) {
+ err = avpkt->size;
+ goto finish;
+ }
}
/*
* Return the next available frame from the oldest thread.
* If we're at the end of the stream, then we have to skip threads that
- * didn't output a frame, because we don't want to accidentally signal
- * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
+ * didn't output a frame/error, because we don't want to accidentally signal
+ * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
*/
do {
p = &fctx->threads[finished++];
- if (p->state != STATE_INPUT_READY) {
+ if (atomic_load(&p->state) != STATE_INPUT_READY) {
pthread_mutex_lock(&p->progress_mutex);
- while (p->state != STATE_INPUT_READY)
+ while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
pthread_cond_wait(&p->output_cond, &p->progress_mutex);
pthread_mutex_unlock(&p->progress_mutex);
}
@@ -444,20 +531,19 @@ int ff_thread_decode_frame(AVCodecContext *avctx,
av_frame_move_ref(picture, p->frame);
*got_picture_ptr = p->got_frame;
picture->pkt_dts = p->avpkt.dts;
-
- if (p->result < 0)
- err = p->result;
+ err = p->result;
/*
* A later call with avkpt->size == 0 may loop over all threads,
- * including this one, searching for a frame to return before being
+ * including this one, searching for a frame/error to return before being
* stopped by the "finished != fctx->next_finished" condition.
- * Make sure we don't mistakenly return the same frame again.
+ * Make sure we don't mistakenly return the same frame/error again.
*/
p->got_frame = 0;
+ p->result = 0;
if (finished >= avctx->thread_count) finished = 0;
- } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
+ } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
update_context_from_thread(avctx, p->avctx, 1);
@@ -465,16 +551,12 @@ int ff_thread_decode_frame(AVCodecContext *avctx,
fctx->next_finished = finished;
- /*
- * When no frame was found while flushing, but an error occurred in
- * any thread, return it instead of 0.
- * Otherwise the error can get lost.
- */
- if (!avpkt->size && !*got_picture_ptr)
- return err;
-
/* return the size of the consumed packet if no error occurred */
- return (p->result >= 0) ? avpkt->size : p->result;
+ if (err >= 0)
+ err = avpkt->size;
+finish:
+ async_lock(fctx);
+ return err;
}
void ff_thread_report_progress(ThreadFrame *f, int n, int field)
@@ -482,15 +564,20 @@ void ff_thread_report_progress(ThreadFrame *f, int n, int field)
PerThreadContext *p;
atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
- if (!progress || progress[field] >= n) return;
+ if (!progress ||
+ atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
+ return;
- p = f->owner->internal->thread_ctx;
+ p = f->owner[field]->internal->thread_ctx;
- if (f->owner->debug&FF_DEBUG_THREADS)
- av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
+ if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
+ av_log(f->owner[field], AV_LOG_DEBUG,
+ "%p finished %d field %d\n", progress, n, field);
pthread_mutex_lock(&p->progress_mutex);
- progress[field] = n;
+
+ atomic_store_explicit(&progress[field], n, memory_order_release);
+
pthread_cond_broadcast(&p->progress_cond);
pthread_mutex_unlock(&p->progress_mutex);
}
@@ -500,15 +587,18 @@ void ff_thread_await_progress(ThreadFrame *f, int n, int field)
PerThreadContext *p;
atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
- if (!progress || progress[field] >= n) return;
+ if (!progress ||
+ atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
+ return;
- p = f->owner->internal->thread_ctx;
+ p = f->owner[field]->internal->thread_ctx;
- if (f->owner->debug&FF_DEBUG_THREADS)
- av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
+ if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
+ av_log(f->owner[field], AV_LOG_DEBUG,
+ "thread awaiting %d field %d from %p\n", n, field, progress);
pthread_mutex_lock(&p->progress_mutex);
- while (progress[field] < n)
+ while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
pthread_mutex_unlock(&p->progress_mutex);
}
@@ -518,12 +608,26 @@ void ff_thread_finish_setup(AVCodecContext *avctx) {
if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
- if(p->state == STATE_SETUP_FINISHED){
- av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
+ if (avctx->hwaccel && !p->hwaccel_serializing) {
+ pthread_mutex_lock(&p->parent->hwaccel_mutex);
+ p->hwaccel_serializing = 1;
+ }
+
+ /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
+ if (avctx->hwaccel &&
+ !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
+ p->async_serializing = 1;
+
+ async_lock(p->parent);
}
pthread_mutex_lock(&p->progress_mutex);
- p->state = STATE_SETUP_FINISHED;
+ if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
+ av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
+ }
+
+ atomic_store(&p->state, STATE_SETUP_FINISHED);
+
pthread_cond_broadcast(&p->progress_cond);
pthread_mutex_unlock(&p->progress_mutex);
}
@@ -533,17 +637,21 @@ static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count
{
int i;
+ async_unlock(fctx);
+
for (i = 0; i < thread_count; i++) {
PerThreadContext *p = &fctx->threads[i];
- if (p->state != STATE_INPUT_READY) {
+ if (atomic_load(&p->state) != STATE_INPUT_READY) {
pthread_mutex_lock(&p->progress_mutex);
- while (p->state != STATE_INPUT_READY)
+ while (atomic_load(&p->state) != STATE_INPUT_READY)
pthread_cond_wait(&p->output_cond, &p->progress_mutex);
pthread_mutex_unlock(&p->progress_mutex);
}
p->got_frame = 0;
}
+
+ async_lock(fctx);
}
void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
@@ -596,13 +704,20 @@ void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
av_freep(&p->avctx->slice_offset);
}
- if (p->avctx)
+ if (p->avctx) {
av_freep(&p->avctx->internal);
+ av_buffer_unref(&p->avctx->hw_frames_ctx);
+ }
+
av_freep(&p->avctx);
}
av_freep(&fctx->threads);
pthread_mutex_destroy(&fctx->buffer_mutex);
+ pthread_mutex_destroy(&fctx->hwaccel_mutex);
+ pthread_mutex_destroy(&fctx->async_mutex);
+ pthread_cond_destroy(&fctx->async_cond);
+
av_freep(&avctx->internal->thread_ctx);
if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
@@ -624,8 +739,10 @@ int ff_frame_thread_init(AVCodecContext *avctx)
if (!thread_count) {
int nb_cpus = av_cpu_count();
+#if FF_API_DEBUG_MV
if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
nb_cpus = 1;
+#endif
// use number of cores + 1 as thread count if there is more than one
if (nb_cpus > 1)
thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
@@ -649,6 +766,11 @@ int ff_frame_thread_init(AVCodecContext *avctx)
}
pthread_mutex_init(&fctx->buffer_mutex, NULL);
+ pthread_mutex_init(&fctx->hwaccel_mutex, NULL);
+ pthread_mutex_init(&fctx->async_mutex, NULL);
+ pthread_cond_init(&fctx->async_cond, NULL);
+
+ fctx->async_lock = 1;
fctx->delaying = 1;
for (i = 0; i < thread_count; i++) {
@@ -686,7 +808,7 @@ int ff_frame_thread_init(AVCodecContext *avctx)
}
*copy->internal = *src->internal;
copy->internal->thread_ctx = p;
- copy->internal->pkt = &p->avpkt;
+ copy->internal->last_pkt_props = &p->avpkt;
if (!i) {
src = copy;
@@ -710,6 +832,8 @@ int ff_frame_thread_init(AVCodecContext *avctx)
if (err) goto error;
+ atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
+
err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
p->thread_init= !err;
if(!p->thread_init)
@@ -745,6 +869,7 @@ void ff_thread_flush(AVCodecContext *avctx)
// Make sure decode flush calls with size=0 won't return old frames
p->got_frame = 0;
av_frame_unref(p->frame);
+ p->result = 0;
release_delayed_buffers(p);
@@ -756,7 +881,7 @@ void ff_thread_flush(AVCodecContext *avctx)
int ff_thread_can_start_frame(AVCodecContext *avctx)
{
PerThreadContext *p = avctx->internal->thread_ctx;
- if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
+ if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
(avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
return 0;
}
@@ -768,28 +893,29 @@ static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int
PerThreadContext *p = avctx->internal->thread_ctx;
int err;
- f->owner = avctx;
+ f->owner[0] = f->owner[1] = avctx;
ff_init_buffer_info(avctx, f->f);
if (!(avctx->active_thread_type & FF_THREAD_FRAME))
return ff_get_buffer(avctx, f->f, flags);
- if (p->state != STATE_SETTING_UP &&
+ if (atomic_load(&p->state) != STATE_SETTING_UP &&
(avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
return -1;
}
if (avctx->internal->allocate_progress) {
- int *progress;
- f->progress = av_buffer_alloc(2 * sizeof(int));
+ atomic_int *progress;
+ f->progress = av_buffer_alloc(2 * sizeof(*progress));
if (!f->progress) {
return AVERROR(ENOMEM);
}
- progress = (int*)f->progress->data;
+ progress = (atomic_int*)f->progress->data;
- progress[0] = progress[1] = -1;
+ atomic_init(&progress[0], -1);
+ atomic_init(&progress[1], -1);
}
pthread_mutex_lock(&p->parent->buffer_mutex);
@@ -800,10 +926,10 @@ static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int
pthread_mutex_lock(&p->progress_mutex);
p->requested_frame = f->f;
p->requested_flags = flags;
- p->state = STATE_GET_BUFFER;
+ atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
pthread_cond_broadcast(&p->progress_cond);
- while (p->state != STATE_SETTING_UP)
+ while (atomic_load(&p->state) != STATE_SETTING_UP)
pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
err = p->result;
@@ -828,16 +954,16 @@ enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixe
if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
avctx->get_format == avcodec_default_get_format)
return ff_get_format(avctx, fmt);
- if (p->state != STATE_SETTING_UP) {
+ if (atomic_load(&p->state) != STATE_SETTING_UP) {
av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
return -1;
}
pthread_mutex_lock(&p->progress_mutex);
p->available_formats = fmt;
- p->state = STATE_GET_FORMAT;
+ atomic_store(&p->state, STATE_GET_FORMAT);
pthread_cond_broadcast(&p->progress_cond);
- while (p->state != STATE_SETTING_UP)
+ while (atomic_load(&p->state) != STATE_SETTING_UP)
pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
res = p->result_format;
@@ -871,7 +997,7 @@ void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
av_buffer_unref(&f->progress);
- f->owner = NULL;
+ f->owner[0] = f->owner[1] = NULL;
if (can_direct_free) {
av_frame_unref(f->f);
diff --git a/media/ffvpx/libavcodec/pthread_slice.c b/media/ffvpx/libavcodec/pthread_slice.c
index 96a7643f6..d659f9b0b 100644
--- a/media/ffvpx/libavcodec/pthread_slice.c
+++ b/media/ffvpx/libavcodec/pthread_slice.c
@@ -34,26 +34,21 @@
#include "libavutil/cpu.h"
#include "libavutil/mem.h"
#include "libavutil/thread.h"
+#include "libavutil/slicethread.h"
typedef int (action_func)(AVCodecContext *c, void *arg);
typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
+typedef int (main_func)(AVCodecContext *c);
typedef struct SliceThreadContext {
- pthread_t *workers;
+ AVSliceThread *thread;
action_func *func;
action_func2 *func2;
+ main_func *mainfunc;
void *args;
int *rets;
- int job_count;
int job_size;
- pthread_cond_t last_job_cond;
- pthread_cond_t current_job_cond;
- pthread_mutex_t current_job_lock;
- unsigned current_execute;
- int current_job;
- int done;
-
int *entries;
int entries_count;
int thread_count;
@@ -61,43 +56,22 @@ typedef struct SliceThreadContext {
pthread_mutex_t *progress_mutex;
} SliceThreadContext;
-static void* attribute_align_arg worker(void *v)
-{
- AVCodecContext *avctx = v;
+static void main_function(void *priv) {
+ AVCodecContext *avctx = priv;
SliceThreadContext *c = avctx->internal->thread_ctx;
- unsigned last_execute = 0;
- int our_job = c->job_count;
- int thread_count = avctx->thread_count;
- int self_id;
-
- pthread_mutex_lock(&c->current_job_lock);
- self_id = c->current_job++;
- for (;;){
- int ret;
- while (our_job >= c->job_count) {
- if (c->current_job == thread_count + c->job_count)
- pthread_cond_signal(&c->last_job_cond);
-
- while (last_execute == c->current_execute && !c->done)
- pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
- last_execute = c->current_execute;
- our_job = self_id;
-
- if (c->done) {
- pthread_mutex_unlock(&c->current_job_lock);
- return NULL;
- }
- }
- pthread_mutex_unlock(&c->current_job_lock);
+ c->mainfunc(avctx);
+}
- ret = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
- c->func2(avctx, c->args, our_job, self_id);
- if (c->rets)
- c->rets[our_job%c->job_count] = ret;
+static void worker_func(void *priv, int jobnr, int threadnr, int nb_jobs, int nb_threads)
+{
+ AVCodecContext *avctx = priv;
+ SliceThreadContext *c = avctx->internal->thread_ctx;
+ int ret;
- pthread_mutex_lock(&c->current_job_lock);
- our_job = c->current_job++;
- }
+ ret = c->func ? c->func(avctx, (char *)c->args + c->job_size * jobnr)
+ : c->func2(avctx, c->args, jobnr, threadnr);
+ if (c->rets)
+ c->rets[jobnr] = ret;
}
void ff_slice_thread_free(AVCodecContext *avctx)
@@ -105,40 +79,19 @@ void ff_slice_thread_free(AVCodecContext *avctx)
SliceThreadContext *c = avctx->internal->thread_ctx;
int i;
- pthread_mutex_lock(&c->current_job_lock);
- c->done = 1;
- pthread_cond_broadcast(&c->current_job_cond);
- for (i = 0; i < c->thread_count; i++)
- pthread_cond_broadcast(&c->progress_cond[i]);
- pthread_mutex_unlock(&c->current_job_lock);
-
- for (i=0; i<avctx->thread_count; i++)
- pthread_join(c->workers[i], NULL);
+ avpriv_slicethread_free(&c->thread);
for (i = 0; i < c->thread_count; i++) {
pthread_mutex_destroy(&c->progress_mutex[i]);
pthread_cond_destroy(&c->progress_cond[i]);
}
- pthread_mutex_destroy(&c->current_job_lock);
- pthread_cond_destroy(&c->current_job_cond);
- pthread_cond_destroy(&c->last_job_cond);
-
av_freep(&c->entries);
av_freep(&c->progress_mutex);
av_freep(&c->progress_cond);
-
- av_freep(&c->workers);
av_freep(&avctx->internal->thread_ctx);
}
-static av_always_inline void thread_park_workers(SliceThreadContext *c, int thread_count)
-{
- while (c->current_job != thread_count + c->job_count)
- pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
- pthread_mutex_unlock(&c->current_job_lock);
-}
-
static int thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
{
SliceThreadContext *c = avctx->internal->thread_ctx;
@@ -149,23 +102,12 @@ static int thread_execute(AVCodecContext *avctx, action_func* func, void *arg, i
if (job_count <= 0)
return 0;
- pthread_mutex_lock(&c->current_job_lock);
-
- c->current_job = avctx->thread_count;
- c->job_count = job_count;
c->job_size = job_size;
c->args = arg;
c->func = func;
- if (ret) {
- c->rets = ret;
- } else {
- c->rets = NULL;
- }
- c->current_execute++;
- pthread_cond_broadcast(&c->current_job_cond);
-
- thread_park_workers(c, avctx->thread_count);
+ c->rets = ret;
+ avpriv_slicethread_execute(c->thread, job_count, !!c->mainfunc );
return 0;
}
@@ -176,11 +118,19 @@ static int thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg
return thread_execute(avctx, NULL, arg, ret, job_count, 0);
}
+int ff_slice_thread_execute_with_mainfunc(AVCodecContext *avctx, action_func2* func2, main_func *mainfunc, void *arg, int *ret, int job_count)
+{
+ SliceThreadContext *c = avctx->internal->thread_ctx;
+ c->func2 = func2;
+ c->mainfunc = mainfunc;
+ return thread_execute(avctx, NULL, arg, ret, job_count, 0);
+}
+
int ff_slice_thread_init(AVCodecContext *avctx)
{
- int i;
SliceThreadContext *c;
int thread_count = avctx->thread_count;
+ static void (*mainfunc)(void *);
#if HAVE_W32THREADS
w32thread_init();
@@ -208,35 +158,17 @@ int ff_slice_thread_init(AVCodecContext *avctx)
return 0;
}
- c = av_mallocz(sizeof(SliceThreadContext));
- if (!c)
- return -1;
-
- c->workers = av_mallocz_array(thread_count, sizeof(pthread_t));
- if (!c->workers) {
- av_free(c);
- return -1;
- }
-
- avctx->internal->thread_ctx = c;
- c->current_job = 0;
- c->job_count = 0;
- c->job_size = 0;
- c->done = 0;
- pthread_cond_init(&c->current_job_cond, NULL);
- pthread_cond_init(&c->last_job_cond, NULL);
- pthread_mutex_init(&c->current_job_lock, NULL);
- pthread_mutex_lock(&c->current_job_lock);
- for (i=0; i<thread_count; i++) {
- if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
- avctx->thread_count = i;
- pthread_mutex_unlock(&c->current_job_lock);
- ff_thread_free(avctx);
- return -1;
- }
+ avctx->internal->thread_ctx = c = av_mallocz(sizeof(*c));
+ mainfunc = avctx->codec->caps_internal & FF_CODEC_CAP_SLICE_THREAD_HAS_MF ? &main_function : NULL;
+ if (!c || (thread_count = avpriv_slicethread_create(&c->thread, avctx, worker_func, mainfunc, thread_count)) <= 1) {
+ if (c)
+ avpriv_slicethread_free(&c->thread);
+ av_freep(&avctx->internal->thread_ctx);
+ avctx->thread_count = 1;
+ avctx->active_thread_type = 0;
+ return 0;
}
-
- thread_park_workers(c, thread_count);
+ avctx->thread_count = thread_count;
avctx->execute = thread_execute;
avctx->execute2 = thread_execute2;
diff --git a/media/ffvpx/libavcodec/put_bits.h b/media/ffvpx/libavcodec/put_bits.h
index 68ed39119..1ceb1cc76 100644
--- a/media/ffvpx/libavcodec/put_bits.h
+++ b/media/ffvpx/libavcodec/put_bits.h
@@ -119,6 +119,18 @@ static inline void flush_put_bits(PutBitContext *s)
s->bit_buf = 0;
}
+static inline void flush_put_bits_le(PutBitContext *s)
+{
+ while (s->bit_left < 32) {
+ av_assert0(s->buf_ptr < s->buf_end);
+ *s->buf_ptr++ = s->bit_buf;
+ s->bit_buf >>= 8;
+ s->bit_left += 8;
+ }
+ s->bit_left = 32;
+ s->bit_buf = 0;
+}
+
#ifdef BITSTREAM_WRITER_LE
#define avpriv_align_put_bits align_put_bits_unsupported_here
#define avpriv_put_string ff_put_string_unsupported_here
@@ -197,6 +209,34 @@ static inline void put_bits(PutBitContext *s, int n, unsigned int value)
s->bit_left = bit_left;
}
+static inline void put_bits_le(PutBitContext *s, int n, unsigned int value)
+{
+ unsigned int bit_buf;
+ int bit_left;
+
+ av_assert2(n <= 31 && value < (1U << n));
+
+ bit_buf = s->bit_buf;
+ bit_left = s->bit_left;
+
+ bit_buf |= value << (32 - bit_left);
+ if (n >= bit_left) {
+ if (3 < s->buf_end - s->buf_ptr) {
+ AV_WL32(s->buf_ptr, bit_buf);
+ s->buf_ptr += 4;
+ } else {
+ av_log(NULL, AV_LOG_ERROR, "Internal error, put_bits buffer too small\n");
+ av_assert2(0);
+ }
+ bit_buf = value >> bit_left;
+ bit_left += 32;
+ }
+ bit_left -= n;
+
+ s->bit_buf = bit_buf;
+ s->bit_left = bit_left;
+}
+
static inline void put_sbits(PutBitContext *pb, int n, int32_t value)
{
av_assert2(n >= 0 && n <= 31);
@@ -209,15 +249,72 @@ static inline void put_sbits(PutBitContext *pb, int n, int32_t value)
*/
static void av_unused put_bits32(PutBitContext *s, uint32_t value)
{
- int lo = value & 0xffff;
- int hi = value >> 16;
+ unsigned int bit_buf;
+ int bit_left;
+
+ bit_buf = s->bit_buf;
+ bit_left = s->bit_left;
+
#ifdef BITSTREAM_WRITER_LE
- put_bits(s, 16, lo);
- put_bits(s, 16, hi);
+ bit_buf |= value << (32 - bit_left);
+ if (3 < s->buf_end - s->buf_ptr) {
+ AV_WL32(s->buf_ptr, bit_buf);
+ s->buf_ptr += 4;
+ } else {
+ av_log(NULL, AV_LOG_ERROR, "Internal error, put_bits buffer too small\n");
+ av_assert2(0);
+ }
+ bit_buf = (uint64_t)value >> bit_left;
#else
- put_bits(s, 16, hi);
- put_bits(s, 16, lo);
+ bit_buf = (uint64_t)bit_buf << bit_left;
+ bit_buf |= value >> (32 - bit_left);
+ if (3 < s->buf_end - s->buf_ptr) {
+ AV_WB32(s->buf_ptr, bit_buf);
+ s->buf_ptr += 4;
+ } else {
+ av_log(NULL, AV_LOG_ERROR, "Internal error, put_bits buffer too small\n");
+ av_assert2(0);
+ }
+ bit_buf = value;
#endif
+
+ s->bit_buf = bit_buf;
+ s->bit_left = bit_left;
+}
+
+/**
+ * Write up to 64 bits into a bitstream.
+ */
+static inline void put_bits64(PutBitContext *s, int n, uint64_t value)
+{
+ av_assert2((n == 64) || (n < 64 && value < (UINT64_C(1) << n)));
+
+ if (n < 32)
+ put_bits(s, n, value);
+ else if (n == 32)
+ put_bits32(s, value);
+ else if (n < 64) {
+ uint32_t lo = value & 0xffffffff;
+ uint32_t hi = value >> 32;
+#ifdef BITSTREAM_WRITER_LE
+ put_bits32(s, lo);
+ put_bits(s, n - 32, hi);
+#else
+ put_bits(s, n - 32, hi);
+ put_bits32(s, lo);
+#endif
+ } else {
+ uint32_t lo = value & 0xffffffff;
+ uint32_t hi = value >> 32;
+#ifdef BITSTREAM_WRITER_LE
+ put_bits32(s, lo);
+ put_bits32(s, hi);
+#else
+ put_bits32(s, hi);
+ put_bits32(s, lo);
+#endif
+
+ }
}
/**
diff --git a/media/ffvpx/libavcodec/ratecontrol.h b/media/ffvpx/libavcodec/ratecontrol.h
index c15f9e258..2a7aaec64 100644
--- a/media/ffvpx/libavcodec/ratecontrol.h
+++ b/media/ffvpx/libavcodec/ratecontrol.h
@@ -96,8 +96,4 @@ void ff_rate_control_uninit(struct MpegEncContext *s);
int ff_vbv_update(struct MpegEncContext *s, int frame_size);
void ff_get_2pass_fcode(struct MpegEncContext *s);
-int ff_xvid_rate_control_init(struct MpegEncContext *s);
-void ff_xvid_rate_control_uninit(struct MpegEncContext *s);
-float ff_xvid_rate_estimate_qscale(struct MpegEncContext *s, int dry_run);
-
#endif /* AVCODEC_RATECONTROL_H */
diff --git a/media/ffvpx/libavcodec/raw.c b/media/ffvpx/libavcodec/raw.c
index f73a134a9..8da2a9735 100644
--- a/media/ffvpx/libavcodec/raw.c
+++ b/media/ffvpx/libavcodec/raw.c
@@ -119,6 +119,12 @@ const PixelFormatTag ff_raw_pix_fmt_tags[] = {
{ AV_PIX_FMT_RGB48BE, MKTAG( 48, 'R', 'G', 'B') },
{ AV_PIX_FMT_BGR48LE, MKTAG('B', 'G', 'R', 48 ) },
{ AV_PIX_FMT_BGR48BE, MKTAG( 48, 'B', 'G', 'R') },
+ { AV_PIX_FMT_GRAY9LE, MKTAG('Y', '1', 0 , 9 ) },
+ { AV_PIX_FMT_GRAY9BE, MKTAG( 9 , 0 , '1', 'Y') },
+ { AV_PIX_FMT_GRAY10LE, MKTAG('Y', '1', 0 , 10 ) },
+ { AV_PIX_FMT_GRAY10BE, MKTAG(10 , 0 , '1', 'Y') },
+ { AV_PIX_FMT_GRAY12LE, MKTAG('Y', '1', 0 , 12 ) },
+ { AV_PIX_FMT_GRAY12BE, MKTAG(12 , 0 , '1', 'Y') },
{ AV_PIX_FMT_GRAY16LE, MKTAG('Y', '1', 0 , 16 ) },
{ AV_PIX_FMT_GRAY16BE, MKTAG(16 , 0 , '1', 'Y') },
{ AV_PIX_FMT_YUV420P9LE, MKTAG('Y', '3', 11 , 9 ) },
@@ -266,6 +272,14 @@ const PixelFormatTag ff_raw_pix_fmt_tags[] = {
{ AV_PIX_FMT_YUV422P10BE, MKTAG('I', '2', 'A', 'B') },
{ AV_PIX_FMT_YUV444P10LE, MKTAG('I', '4', 'A', 'L') },
{ AV_PIX_FMT_YUV444P10BE, MKTAG('I', '4', 'A', 'B') },
+ { AV_PIX_FMT_YUV420P12LE, MKTAG('I', '0', 'C', 'L') },
+ { AV_PIX_FMT_YUV420P12BE, MKTAG('I', '0', 'C', 'B') },
+ { AV_PIX_FMT_YUV422P12LE, MKTAG('I', '2', 'C', 'L') },
+ { AV_PIX_FMT_YUV422P12BE, MKTAG('I', '2', 'C', 'B') },
+ { AV_PIX_FMT_YUV444P12LE, MKTAG('I', '4', 'C', 'L') },
+ { AV_PIX_FMT_YUV444P12BE, MKTAG('I', '4', 'C', 'B') },
+ { AV_PIX_FMT_YUV420P16LE, MKTAG('I', '0', 'F', 'L') },
+ { AV_PIX_FMT_YUV420P16BE, MKTAG('I', '0', 'F', 'B') },
{ AV_PIX_FMT_YUV444P16LE, MKTAG('I', '4', 'F', 'L') },
{ AV_PIX_FMT_YUV444P16BE, MKTAG('I', '4', 'F', 'B') },
diff --git a/media/ffvpx/libavcodec/thread.h b/media/ffvpx/libavcodec/thread.h
index c848d7ae8..318619316 100644
--- a/media/ffvpx/libavcodec/thread.h
+++ b/media/ffvpx/libavcodec/thread.h
@@ -34,7 +34,7 @@
typedef struct ThreadFrame {
AVFrame *f;
- AVCodecContext *owner;
+ AVCodecContext *owner[2];
// progress->data is an array of 2 ints holding progress for top/bottom
// fields
AVBufferRef *progress;
@@ -133,8 +133,10 @@ void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f);
int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src);
int ff_thread_init(AVCodecContext *s);
+int ff_slice_thread_execute_with_mainfunc(AVCodecContext *avctx,
+ int (*action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr),
+ int (*main_func)(AVCodecContext *c), void *arg, int *ret, int job_count);
void ff_thread_free(AVCodecContext *s);
-
int ff_alloc_entries(AVCodecContext *avctx, int count);
void ff_reset_entries(AVCodecContext *avctx);
void ff_thread_report_progress2(AVCodecContext *avctx, int field, int thread, int n);
diff --git a/media/ffvpx/libavcodec/utils.c b/media/ffvpx/libavcodec/utils.c
index 87de15fc6..0c47e761f 100644
--- a/media/ffvpx/libavcodec/utils.c
+++ b/media/ffvpx/libavcodec/utils.c
@@ -44,6 +44,7 @@
#include "libavutil/dict.h"
#include "libavutil/thread.h"
#include "avcodec.h"
+#include "decode.h"
#include "libavutil/opt.h"
#include "me_cmp.h"
#include "mpegvideo.h"
@@ -172,7 +173,7 @@ int av_codec_is_encoder(const AVCodec *codec)
int av_codec_is_decoder(const AVCodec *codec)
{
- return codec && (codec->decode || codec->send_packet);
+ return codec && (codec->decode || codec->receive_frame);
}
av_cold void avcodec_register(AVCodec *codec)
@@ -209,7 +210,7 @@ void avcodec_set_dimensions(AVCodecContext *s, int width, int height)
int ff_set_dimensions(AVCodecContext *s, int width, int height)
{
- int ret = av_image_check_size(width, height, 0, s);
+ int ret = av_image_check_size2(width, height, s->max_pixels, AV_PIX_FMT_NONE, 0, s);
if (ret < 0)
width = height = 0;
@@ -376,6 +377,10 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
w_align = 4;
h_align = 4;
}
+ if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
+ w_align = 8;
+ h_align = 8;
+ }
break;
case AV_PIX_FMT_PAL8:
case AV_PIX_FMT_BGR8:
@@ -385,7 +390,8 @@ void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
w_align = 4;
h_align = 4;
}
- if (s->codec_id == AV_CODEC_ID_JV) {
+ if (s->codec_id == AV_CODEC_ID_JV ||
+ s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
w_align = 8;
h_align = 8;
}
@@ -503,200 +509,6 @@ int avcodec_fill_audio_frame(AVFrame *frame, int nb_channels,
return ret;
}
-static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)
-{
- FramePool *pool = avctx->internal->pool;
- int i, ret;
-
- switch (avctx->codec_type) {
- case AVMEDIA_TYPE_VIDEO: {
- uint8_t *data[4];
- int linesize[4];
- int size[4] = { 0 };
- int w = frame->width;
- int h = frame->height;
- int tmpsize, unaligned;
-
- if (pool->format == frame->format &&
- pool->width == frame->width && pool->height == frame->height)
- return 0;
-
- avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);
-
- do {
- // NOTE: do not align linesizes individually, this breaks e.g. assumptions
- // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2
- ret = av_image_fill_linesizes(linesize, avctx->pix_fmt, w);
- if (ret < 0)
- return ret;
- // increase alignment of w for next try (rhs gives the lowest bit set in w)
- w += w & ~(w - 1);
-
- unaligned = 0;
- for (i = 0; i < 4; i++)
- unaligned |= linesize[i] % pool->stride_align[i];
- } while (unaligned);
-
- tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,
- NULL, linesize);
- if (tmpsize < 0)
- return -1;
-
- for (i = 0; i < 3 && data[i + 1]; i++)
- size[i] = data[i + 1] - data[i];
- size[i] = tmpsize - (data[i] - data[0]);
-
- for (i = 0; i < 4; i++) {
- av_buffer_pool_uninit(&pool->pools[i]);
- pool->linesize[i] = linesize[i];
- if (size[i]) {
- pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,
- CONFIG_MEMORY_POISONING ?
- NULL :
- av_buffer_allocz);
- if (!pool->pools[i]) {
- ret = AVERROR(ENOMEM);
- goto fail;
- }
- }
- }
- pool->format = frame->format;
- pool->width = frame->width;
- pool->height = frame->height;
-
- break;
- }
- case AVMEDIA_TYPE_AUDIO: {
- int ch = av_frame_get_channels(frame); //av_get_channel_layout_nb_channels(frame->channel_layout);
- int planar = av_sample_fmt_is_planar(frame->format);
- int planes = planar ? ch : 1;
-
- if (pool->format == frame->format && pool->planes == planes &&
- pool->channels == ch && frame->nb_samples == pool->samples)
- return 0;
-
- av_buffer_pool_uninit(&pool->pools[0]);
- ret = av_samples_get_buffer_size(&pool->linesize[0], ch,
- frame->nb_samples, frame->format, 0);
- if (ret < 0)
- goto fail;
-
- pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);
- if (!pool->pools[0]) {
- ret = AVERROR(ENOMEM);
- goto fail;
- }
-
- pool->format = frame->format;
- pool->planes = planes;
- pool->channels = ch;
- pool->samples = frame->nb_samples;
- break;
- }
- default: av_assert0(0);
- }
- return 0;
-fail:
- for (i = 0; i < 4; i++)
- av_buffer_pool_uninit(&pool->pools[i]);
- pool->format = -1;
- pool->planes = pool->channels = pool->samples = 0;
- pool->width = pool->height = 0;
- return ret;
-}
-
-static int audio_get_buffer(AVCodecContext *avctx, AVFrame *frame)
-{
- FramePool *pool = avctx->internal->pool;
- int planes = pool->planes;
- int i;
-
- frame->linesize[0] = pool->linesize[0];
-
- if (planes > AV_NUM_DATA_POINTERS) {
- frame->extended_data = av_mallocz_array(planes, sizeof(*frame->extended_data));
- frame->nb_extended_buf = planes - AV_NUM_DATA_POINTERS;
- frame->extended_buf = av_mallocz_array(frame->nb_extended_buf,
- sizeof(*frame->extended_buf));
- if (!frame->extended_data || !frame->extended_buf) {
- av_freep(&frame->extended_data);
- av_freep(&frame->extended_buf);
- return AVERROR(ENOMEM);
- }
- } else {
- frame->extended_data = frame->data;
- av_assert0(frame->nb_extended_buf == 0);
- }
-
- for (i = 0; i < FFMIN(planes, AV_NUM_DATA_POINTERS); i++) {
- frame->buf[i] = av_buffer_pool_get(pool->pools[0]);
- if (!frame->buf[i])
- goto fail;
- frame->extended_data[i] = frame->data[i] = frame->buf[i]->data;
- }
- for (i = 0; i < frame->nb_extended_buf; i++) {
- frame->extended_buf[i] = av_buffer_pool_get(pool->pools[0]);
- if (!frame->extended_buf[i])
- goto fail;
- frame->extended_data[i + AV_NUM_DATA_POINTERS] = frame->extended_buf[i]->data;
- }
-
- if (avctx->debug & FF_DEBUG_BUFFERS)
- av_log(avctx, AV_LOG_DEBUG, "default_get_buffer called on frame %p", frame);
-
- return 0;
-fail:
- av_frame_unref(frame);
- return AVERROR(ENOMEM);
-}
-
-static int video_get_buffer(AVCodecContext *s, AVFrame *pic)
-{
- FramePool *pool = s->internal->pool;
- const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pic->format);
- int i;
-
- if (pic->data[0] || pic->data[1] || pic->data[2] || pic->data[3]) {
- av_log(s, AV_LOG_ERROR, "pic->data[*]!=NULL in avcodec_default_get_buffer\n");
- return -1;
- }
-
- if (!desc) {
- av_log(s, AV_LOG_ERROR,
- "Unable to get pixel format descriptor for format %s\n",
- av_get_pix_fmt_name(pic->format));
- return AVERROR(EINVAL);
- }
-
- memset(pic->data, 0, sizeof(pic->data));
- pic->extended_data = pic->data;
-
- for (i = 0; i < 4 && pool->pools[i]; i++) {
- pic->linesize[i] = pool->linesize[i];
-
- pic->buf[i] = av_buffer_pool_get(pool->pools[i]);
- if (!pic->buf[i])
- goto fail;
-
- pic->data[i] = pic->buf[i]->data;
- }
- for (; i < AV_NUM_DATA_POINTERS; i++) {
- pic->data[i] = NULL;
- pic->linesize[i] = 0;
- }
- if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
- desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL)
- avpriv_set_systematic_pal2((uint32_t *)pic->data[1], pic->format);
-
- if (s->debug & FF_DEBUG_BUFFERS)
- av_log(s, AV_LOG_DEBUG, "default_get_buffer called on pic %p\n", pic);
-
- return 0;
-fail:
- av_frame_unref(pic);
- return AVERROR(ENOMEM);
-}
-
void ff_color_frame(AVFrame *frame, const int c[4])
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
@@ -720,287 +532,6 @@ void ff_color_frame(AVFrame *frame, const int c[4])
}
}
-int avcodec_default_get_buffer2(AVCodecContext *avctx, AVFrame *frame, int flags)
-{
- int ret;
-
- if (avctx->hw_frames_ctx)
- return av_hwframe_get_buffer(avctx->hw_frames_ctx, frame, 0);
-
- if ((ret = update_frame_pool(avctx, frame)) < 0)
- return ret;
-
- switch (avctx->codec_type) {
- case AVMEDIA_TYPE_VIDEO:
- return video_get_buffer(avctx, frame);
- case AVMEDIA_TYPE_AUDIO:
- return audio_get_buffer(avctx, frame);
- default:
- return -1;
- }
-}
-
-static int add_metadata_from_side_data(AVPacket *avpkt, AVFrame *frame)
-{
- int size;
- const uint8_t *side_metadata;
-
- AVDictionary **frame_md = avpriv_frame_get_metadatap(frame);
-
- side_metadata = av_packet_get_side_data(avpkt,
- AV_PKT_DATA_STRINGS_METADATA, &size);
- return av_packet_unpack_dictionary(side_metadata, size, frame_md);
-}
-
-int ff_init_buffer_info(AVCodecContext *avctx, AVFrame *frame)
-{
- AVPacket *pkt = avctx->internal->pkt;
- int i;
- static const struct {
- enum AVPacketSideDataType packet;
- enum AVFrameSideDataType frame;
- } sd[] = {
- { AV_PKT_DATA_REPLAYGAIN , AV_FRAME_DATA_REPLAYGAIN },
- { AV_PKT_DATA_DISPLAYMATRIX, AV_FRAME_DATA_DISPLAYMATRIX },
- { AV_PKT_DATA_STEREO3D, AV_FRAME_DATA_STEREO3D },
- { AV_PKT_DATA_AUDIO_SERVICE_TYPE, AV_FRAME_DATA_AUDIO_SERVICE_TYPE },
- { AV_PKT_DATA_MASTERING_DISPLAY_METADATA, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA },
- };
-
- if (pkt) {
- frame->pts = pkt->pts;
-#if FF_API_PKT_PTS
-FF_DISABLE_DEPRECATION_WARNINGS
- frame->pkt_pts = pkt->pts;
-FF_ENABLE_DEPRECATION_WARNINGS
-#endif
- av_frame_set_pkt_pos (frame, pkt->pos);
- av_frame_set_pkt_duration(frame, pkt->duration);
- av_frame_set_pkt_size (frame, pkt->size);
-
- for (i = 0; i < FF_ARRAY_ELEMS(sd); i++) {
- int size;
- uint8_t *packet_sd = av_packet_get_side_data(pkt, sd[i].packet, &size);
- if (packet_sd) {
- AVFrameSideData *frame_sd = av_frame_new_side_data(frame,
- sd[i].frame,
- size);
- if (!frame_sd)
- return AVERROR(ENOMEM);
-
- memcpy(frame_sd->data, packet_sd, size);
- }
- }
- add_metadata_from_side_data(pkt, frame);
-
- if (pkt->flags & AV_PKT_FLAG_DISCARD) {
- frame->flags |= AV_FRAME_FLAG_DISCARD;
- } else {
- frame->flags = (frame->flags & ~AV_FRAME_FLAG_DISCARD);
- }
- } else {
- frame->pts = AV_NOPTS_VALUE;
-#if FF_API_PKT_PTS
-FF_DISABLE_DEPRECATION_WARNINGS
- frame->pkt_pts = AV_NOPTS_VALUE;
-FF_ENABLE_DEPRECATION_WARNINGS
-#endif
- av_frame_set_pkt_pos (frame, -1);
- av_frame_set_pkt_duration(frame, 0);
- av_frame_set_pkt_size (frame, -1);
- }
- frame->reordered_opaque = avctx->reordered_opaque;
-
- if (frame->color_primaries == AVCOL_PRI_UNSPECIFIED)
- frame->color_primaries = avctx->color_primaries;
- if (frame->color_trc == AVCOL_TRC_UNSPECIFIED)
- frame->color_trc = avctx->color_trc;
- if (av_frame_get_colorspace(frame) == AVCOL_SPC_UNSPECIFIED)
- av_frame_set_colorspace(frame, avctx->colorspace);
- if (av_frame_get_color_range(frame) == AVCOL_RANGE_UNSPECIFIED)
- av_frame_set_color_range(frame, avctx->color_range);
- if (frame->chroma_location == AVCHROMA_LOC_UNSPECIFIED)
- frame->chroma_location = avctx->chroma_sample_location;
-
- switch (avctx->codec->type) {
- case AVMEDIA_TYPE_VIDEO:
- frame->format = avctx->pix_fmt;
- if (!frame->sample_aspect_ratio.num)
- frame->sample_aspect_ratio = avctx->sample_aspect_ratio;
-
- if (frame->width && frame->height &&
- av_image_check_sar(frame->width, frame->height,
- frame->sample_aspect_ratio) < 0) {
- av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
- frame->sample_aspect_ratio.num,
- frame->sample_aspect_ratio.den);
- frame->sample_aspect_ratio = (AVRational){ 0, 1 };
- }
-
- break;
- case AVMEDIA_TYPE_AUDIO:
- if (!frame->sample_rate)
- frame->sample_rate = avctx->sample_rate;
- if (frame->format < 0)
- frame->format = avctx->sample_fmt;
- if (!frame->channel_layout) {
- if (avctx->channel_layout) {
- if (av_get_channel_layout_nb_channels(avctx->channel_layout) !=
- avctx->channels) {
- av_log(avctx, AV_LOG_ERROR, "Inconsistent channel "
- "configuration.\n");
- return AVERROR(EINVAL);
- }
-
- frame->channel_layout = avctx->channel_layout;
- } else {
- if (avctx->channels > FF_SANE_NB_CHANNELS) {
- av_log(avctx, AV_LOG_ERROR, "Too many channels: %d.\n",
- avctx->channels);
- return AVERROR(ENOSYS);
- }
- }
- }
- av_frame_set_channels(frame, avctx->channels);
- break;
- }
- return 0;
-}
-
-int ff_decode_frame_props(AVCodecContext *avctx, AVFrame *frame)
-{
- return ff_init_buffer_info(avctx, frame);
-}
-
-static void validate_avframe_allocation(AVCodecContext *avctx, AVFrame *frame)
-{
- if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
- int i;
- int num_planes = av_pix_fmt_count_planes(frame->format);
- const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
- int flags = desc ? desc->flags : 0;
- if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PAL))
- num_planes = 2;
- for (i = 0; i < num_planes; i++) {
- av_assert0(frame->data[i]);
- }
- // For now do not enforce anything for palette of pseudopal formats
- if (num_planes == 1 && (flags & AV_PIX_FMT_FLAG_PSEUDOPAL))
- num_planes = 2;
- // For formats without data like hwaccel allow unused pointers to be non-NULL.
- for (i = num_planes; num_planes > 0 && i < FF_ARRAY_ELEMS(frame->data); i++) {
- if (frame->data[i])
- av_log(avctx, AV_LOG_ERROR, "Buffer returned by get_buffer2() did not zero unused plane pointers\n");
- frame->data[i] = NULL;
- }
- }
-}
-
-static int get_buffer_internal(AVCodecContext *avctx, AVFrame *frame, int flags)
-{
- const AVHWAccel *hwaccel = avctx->hwaccel;
- int override_dimensions = 1;
- int ret;
-
- if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
- if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0 || avctx->pix_fmt<0) {
- av_log(avctx, AV_LOG_ERROR, "video_get_buffer: image parameters invalid\n");
- return AVERROR(EINVAL);
- }
-
- if (frame->width <= 0 || frame->height <= 0) {
- frame->width = FFMAX(avctx->width, AV_CEIL_RSHIFT(avctx->coded_width, avctx->lowres));
- frame->height = FFMAX(avctx->height, AV_CEIL_RSHIFT(avctx->coded_height, avctx->lowres));
- override_dimensions = 0;
- }
-
- if (frame->data[0] || frame->data[1] || frame->data[2] || frame->data[3]) {
- av_log(avctx, AV_LOG_ERROR, "pic->data[*]!=NULL in get_buffer_internal\n");
- return AVERROR(EINVAL);
- }
- }
- ret = ff_decode_frame_props(avctx, frame);
- if (ret < 0)
- return ret;
-
- if (hwaccel) {
- if (hwaccel->alloc_frame) {
- ret = hwaccel->alloc_frame(avctx, frame);
- goto end;
- }
- } else
- avctx->sw_pix_fmt = avctx->pix_fmt;
-
- ret = avctx->get_buffer2(avctx, frame, flags);
- if (ret >= 0)
- validate_avframe_allocation(avctx, frame);
-
-end:
- if (avctx->codec_type == AVMEDIA_TYPE_VIDEO && !override_dimensions) {
- frame->width = avctx->width;
- frame->height = avctx->height;
- }
-
- return ret;
-}
-
-int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
-{
- int ret = get_buffer_internal(avctx, frame, flags);
- if (ret < 0) {
- av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
- frame->width = frame->height = 0;
- }
- return ret;
-}
-
-static int reget_buffer_internal(AVCodecContext *avctx, AVFrame *frame)
-{
- AVFrame *tmp;
- int ret;
-
- av_assert0(avctx->codec_type == AVMEDIA_TYPE_VIDEO);
-
- if (frame->data[0] && (frame->width != avctx->width || frame->height != avctx->height || frame->format != avctx->pix_fmt)) {
- av_log(avctx, AV_LOG_WARNING, "Picture changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s in reget buffer()\n",
- frame->width, frame->height, av_get_pix_fmt_name(frame->format), avctx->width, avctx->height, av_get_pix_fmt_name(avctx->pix_fmt));
- av_frame_unref(frame);
- }
-
- ff_init_buffer_info(avctx, frame);
-
- if (!frame->data[0])
- return ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
-
- if (av_frame_is_writable(frame))
- return ff_decode_frame_props(avctx, frame);
-
- tmp = av_frame_alloc();
- if (!tmp)
- return AVERROR(ENOMEM);
-
- av_frame_move_ref(tmp, frame);
-
- ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF);
- if (ret < 0) {
- av_frame_free(&tmp);
- return ret;
- }
-
- av_frame_copy(frame, tmp);
- av_frame_free(&tmp);
-
- return 0;
-}
-
-int ff_reget_buffer(AVCodecContext *avctx, AVFrame *frame)
-{
- int ret = reget_buffer_internal(avctx, frame);
- if (ret < 0)
- av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n");
- return ret;
-}
-
int avcodec_default_execute(AVCodecContext *c, int (*func)(AVCodecContext *c2, void *arg2), void *arg, int *ret, int count, int size)
{
int i;
@@ -1038,145 +569,6 @@ enum AVPixelFormat avpriv_find_pix_fmt(const PixelFormatTag *tags,
return AV_PIX_FMT_NONE;
}
-static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
-{
- const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
- return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
-}
-
-enum AVPixelFormat avcodec_default_get_format(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
-{
- while (*fmt != AV_PIX_FMT_NONE && is_hwaccel_pix_fmt(*fmt))
- ++fmt;
- return fmt[0];
-}
-
-static AVHWAccel *find_hwaccel(enum AVCodecID codec_id,
- enum AVPixelFormat pix_fmt)
-{
- AVHWAccel *hwaccel = NULL;
-
- while ((hwaccel = av_hwaccel_next(hwaccel)))
- if (hwaccel->id == codec_id
- && hwaccel->pix_fmt == pix_fmt)
- return hwaccel;
- return NULL;
-}
-
-static int setup_hwaccel(AVCodecContext *avctx,
- const enum AVPixelFormat fmt,
- const char *name)
-{
- AVHWAccel *hwa = find_hwaccel(avctx->codec_id, fmt);
- int ret = 0;
-
- if (avctx->active_thread_type & FF_THREAD_FRAME) {
- av_log(avctx, AV_LOG_WARNING,
- "Hardware accelerated decoding with frame threading is known to be unstable and its use is discouraged.\n");
- }
-
- if (!hwa) {
- av_log(avctx, AV_LOG_ERROR,
- "Could not find an AVHWAccel for the pixel format: %s",
- name);
- return AVERROR(ENOENT);
- }
-
- if (hwa->capabilities & HWACCEL_CODEC_CAP_EXPERIMENTAL &&
- avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
- av_log(avctx, AV_LOG_WARNING, "Ignoring experimental hwaccel: %s\n",
- hwa->name);
- return AVERROR_PATCHWELCOME;
- }
-
- if (hwa->priv_data_size) {
- avctx->internal->hwaccel_priv_data = av_mallocz(hwa->priv_data_size);
- if (!avctx->internal->hwaccel_priv_data)
- return AVERROR(ENOMEM);
- }
-
- if (hwa->init) {
- ret = hwa->init(avctx);
- if (ret < 0) {
- av_freep(&avctx->internal->hwaccel_priv_data);
- return ret;
- }
- }
-
- avctx->hwaccel = hwa;
-
- return 0;
-}
-
-int ff_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
-{
- const AVPixFmtDescriptor *desc;
- enum AVPixelFormat *choices;
- enum AVPixelFormat ret;
- unsigned n = 0;
-
- while (fmt[n] != AV_PIX_FMT_NONE)
- ++n;
-
- av_assert0(n >= 1);
- avctx->sw_pix_fmt = fmt[n - 1];
- av_assert2(!is_hwaccel_pix_fmt(avctx->sw_pix_fmt));
-
- choices = av_malloc_array(n + 1, sizeof(*choices));
- if (!choices)
- return AV_PIX_FMT_NONE;
-
- memcpy(choices, fmt, (n + 1) * sizeof(*choices));
-
- for (;;) {
- if (avctx->hwaccel && avctx->hwaccel->uninit)
- avctx->hwaccel->uninit(avctx);
- av_freep(&avctx->internal->hwaccel_priv_data);
- avctx->hwaccel = NULL;
-
- av_buffer_unref(&avctx->hw_frames_ctx);
-
- ret = avctx->get_format(avctx, choices);
-
- desc = av_pix_fmt_desc_get(ret);
- if (!desc) {
- ret = AV_PIX_FMT_NONE;
- break;
- }
-
- if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
- break;
-#if FF_API_CAP_VDPAU
- if (avctx->codec->capabilities&AV_CODEC_CAP_HWACCEL_VDPAU)
- break;
-#endif
-
- if (avctx->hw_frames_ctx) {
- AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
- if (hw_frames_ctx->format != ret) {
- av_log(avctx, AV_LOG_ERROR, "Format returned from get_buffer() "
- "does not match the format of provided AVHWFramesContext\n");
- ret = AV_PIX_FMT_NONE;
- break;
- }
- }
-
- if (!setup_hwaccel(avctx, ret, desc->name))
- break;
-
- /* Remove failed hwaccel from choices */
- for (n = 0; choices[n] != ret; n++)
- av_assert0(choices[n] != AV_PIX_FMT_NONE);
-
- do
- choices[n] = choices[n + 1];
- while (choices[n++] != AV_PIX_FMT_NONE);
- }
-
- av_freep(&choices);
- return ret;
-}
-
MAKE_ACCESSORS(AVCodecContext, codec, AVRational, pkt_timebase)
MAKE_ACCESSORS(AVCodecContext, codec, const AVCodecDescriptor *, codec_descriptor)
MAKE_ACCESSORS(AVCodecContext, codec, int, lowres)
@@ -1197,12 +589,6 @@ int avpriv_codec_get_cap_skip_frame_fill_param(const AVCodec *codec){
return !!(codec->caps_internal & FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM);
}
-static void get_subtitle_defaults(AVSubtitle *sub)
-{
- memset(sub, 0, sizeof(*sub));
- sub->pts = AV_NOPTS_VALUE;
-}
-
static int64_t get_bit_rate(AVCodecContext *ctx)
{
int64_t bit_rate;
@@ -1269,7 +655,7 @@ int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *code
if (ret < 0)
return ret;
- avctx->internal = av_mallocz(sizeof(AVCodecInternal));
+ avctx->internal = av_mallocz(sizeof(*avctx->internal));
if (!avctx->internal) {
ret = AVERROR(ENOMEM);
goto end;
@@ -1287,6 +673,12 @@ int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *code
goto free_and_end;
}
+ avctx->internal->compat_decode_frame = av_frame_alloc();
+ if (!avctx->internal->compat_decode_frame) {
+ ret = AVERROR(ENOMEM);
+ goto free_and_end;
+ }
+
avctx->internal->buffer_frame = av_frame_alloc();
if (!avctx->internal->buffer_frame) {
ret = AVERROR(ENOMEM);
@@ -1299,6 +691,20 @@ int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *code
goto free_and_end;
}
+ avctx->internal->ds.in_pkt = av_packet_alloc();
+ if (!avctx->internal->ds.in_pkt) {
+ ret = AVERROR(ENOMEM);
+ goto free_and_end;
+ }
+
+ avctx->internal->last_pkt_props = av_packet_alloc();
+ if (!avctx->internal->last_pkt_props) {
+ ret = AVERROR(ENOMEM);
+ goto free_and_end;
+ }
+
+ avctx->internal->skip_samples_multiplier = 1;
+
if (codec->priv_data_size > 0) {
if (!avctx->priv_data) {
avctx->priv_data = av_mallocz(codec->priv_data_size);
@@ -1337,8 +743,8 @@ int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *code
}
if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
- && ( av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0
- || av_image_check_size(avctx->width, avctx->height, 0, avctx) < 0)) {
+ && ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0
+ || av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) {
av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
ff_set_dimensions(avctx, 0, 0);
}
@@ -1561,11 +967,11 @@ FF_ENABLE_DEPRECATION_WARNINGS
}
if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
&& avctx->bit_rate>0 && avctx->bit_rate<1000) {
- av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", (int64_t)avctx->bit_rate, (int64_t)avctx->bit_rate);
+ av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate);
}
if (!avctx->rc_initial_buffer_occupancy)
- avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;
+ avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4;
if (avctx->ticks_per_frame && avctx->time_base.num &&
avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
@@ -1585,6 +991,17 @@ FF_ENABLE_DEPRECATION_WARNINGS
ret = AVERROR(EINVAL);
goto free_and_end;
}
+ if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
+ avctx->sw_pix_fmt != frames_ctx->sw_format) {
+ av_log(avctx, AV_LOG_ERROR,
+ "Mismatching AVCodecContext.sw_pix_fmt (%s) "
+ "and AVHWFramesContext.sw_format (%s)\n",
+ av_get_pix_fmt_name(avctx->sw_pix_fmt),
+ av_get_pix_fmt_name(frames_ctx->sw_format));
+ ret = AVERROR(EINVAL);
+ goto free_and_end;
+ }
+ avctx->sw_pix_fmt = frames_ctx->sw_format;
}
}
@@ -1709,9 +1126,14 @@ FF_ENABLE_DEPRECATION_WARNINGS
av_dict_free(&tmp);
av_freep(&avctx->priv_data);
if (avctx->internal) {
- av_packet_free(&avctx->internal->buffer_pkt);
- av_frame_free(&avctx->internal->buffer_frame);
av_frame_free(&avctx->internal->to_free);
+ av_frame_free(&avctx->internal->compat_decode_frame);
+ av_frame_free(&avctx->internal->buffer_frame);
+ av_packet_free(&avctx->internal->buffer_pkt);
+ av_packet_free(&avctx->internal->last_pkt_props);
+
+ av_packet_free(&avctx->internal->ds.in_pkt);
+
av_freep(&avctx->internal->pool);
}
av_freep(&avctx->internal);
@@ -1719,1032 +1141,6 @@ FF_ENABLE_DEPRECATION_WARNINGS
goto end;
}
-int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
-{
- if (avpkt->size < 0) {
- av_log(avctx, AV_LOG_ERROR, "Invalid negative user packet size %d\n", avpkt->size);
- return AVERROR(EINVAL);
- }
- if (size < 0 || size > INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE) {
- av_log(avctx, AV_LOG_ERROR, "Invalid minimum required packet size %"PRId64" (max allowed is %d)\n",
- size, INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE);
- return AVERROR(EINVAL);
- }
-
- if (avctx && 2*min_size < size) { // FIXME The factor needs to be finetuned
- av_assert0(!avpkt->data || avpkt->data != avctx->internal->byte_buffer);
- if (!avpkt->data || avpkt->size < size) {
- av_fast_padded_malloc(&avctx->internal->byte_buffer, &avctx->internal->byte_buffer_size, size);
- avpkt->data = avctx->internal->byte_buffer;
- avpkt->size = avctx->internal->byte_buffer_size;
- }
- }
-
- if (avpkt->data) {
- AVBufferRef *buf = avpkt->buf;
-
- if (avpkt->size < size) {
- av_log(avctx, AV_LOG_ERROR, "User packet is too small (%d < %"PRId64")\n", avpkt->size, size);
- return AVERROR(EINVAL);
- }
-
- av_init_packet(avpkt);
- avpkt->buf = buf;
- avpkt->size = size;
- return 0;
- } else {
- int ret = av_new_packet(avpkt, size);
- if (ret < 0)
- av_log(avctx, AV_LOG_ERROR, "Failed to allocate packet of size %"PRId64"\n", size);
- return ret;
- }
-}
-
-int ff_alloc_packet(AVPacket *avpkt, int size)
-{
- return ff_alloc_packet2(NULL, avpkt, size, 0);
-}
-
-/**
- * Pad last frame with silence.
- */
-static int pad_last_frame(AVCodecContext *s, AVFrame **dst, const AVFrame *src)
-{
- AVFrame *frame = NULL;
- int ret;
-
- if (!(frame = av_frame_alloc()))
- return AVERROR(ENOMEM);
-
- frame->format = src->format;
- frame->channel_layout = src->channel_layout;
- av_frame_set_channels(frame, av_frame_get_channels(src));
- frame->nb_samples = s->frame_size;
- ret = av_frame_get_buffer(frame, 32);
- if (ret < 0)
- goto fail;
-
- ret = av_frame_copy_props(frame, src);
- if (ret < 0)
- goto fail;
-
- if ((ret = av_samples_copy(frame->extended_data, src->extended_data, 0, 0,
- src->nb_samples, s->channels, s->sample_fmt)) < 0)
- goto fail;
- if ((ret = av_samples_set_silence(frame->extended_data, src->nb_samples,
- frame->nb_samples - src->nb_samples,
- s->channels, s->sample_fmt)) < 0)
- goto fail;
-
- *dst = frame;
-
- return 0;
-
-fail:
- av_frame_free(&frame);
- return ret;
-}
-
-int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,
- AVPacket *avpkt,
- const AVFrame *frame,
- int *got_packet_ptr)
-{
- AVFrame *extended_frame = NULL;
- AVFrame *padded_frame = NULL;
- int ret;
- AVPacket user_pkt = *avpkt;
- int needs_realloc = !user_pkt.data;
-
- *got_packet_ptr = 0;
-
- if (!avctx->codec->encode2) {
- av_log(avctx, AV_LOG_ERROR, "This encoder requires using the avcodec_send_frame() API.\n");
- return AVERROR(ENOSYS);
- }
-
- if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) {
- av_packet_unref(avpkt);
- av_init_packet(avpkt);
- return 0;
- }
-
- /* ensure that extended_data is properly set */
- if (frame && !frame->extended_data) {
- if (av_sample_fmt_is_planar(avctx->sample_fmt) &&
- avctx->channels > AV_NUM_DATA_POINTERS) {
- av_log(avctx, AV_LOG_ERROR, "Encoding to a planar sample format, "
- "with more than %d channels, but extended_data is not set.\n",
- AV_NUM_DATA_POINTERS);
- return AVERROR(EINVAL);
- }
- av_log(avctx, AV_LOG_WARNING, "extended_data is not set.\n");
-
- extended_frame = av_frame_alloc();
- if (!extended_frame)
- return AVERROR(ENOMEM);
-
- memcpy(extended_frame, frame, sizeof(AVFrame));
- extended_frame->extended_data = extended_frame->data;
- frame = extended_frame;
- }
-
- /* extract audio service type metadata */
- if (frame) {
- AVFrameSideData *sd = av_frame_get_side_data(frame, AV_FRAME_DATA_AUDIO_SERVICE_TYPE);
- if (sd && sd->size >= sizeof(enum AVAudioServiceType))
- avctx->audio_service_type = *(enum AVAudioServiceType*)sd->data;
- }
-
- /* check for valid frame size */
- if (frame) {
- if (avctx->codec->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME) {
- if (frame->nb_samples > avctx->frame_size) {
- av_log(avctx, AV_LOG_ERROR, "more samples than frame size (avcodec_encode_audio2)\n");
- ret = AVERROR(EINVAL);
- goto end;
- }
- } else if (!(avctx->codec->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE)) {
- if (frame->nb_samples < avctx->frame_size &&
- !avctx->internal->last_audio_frame) {
- ret = pad_last_frame(avctx, &padded_frame, frame);
- if (ret < 0)
- goto end;
-
- frame = padded_frame;
- avctx->internal->last_audio_frame = 1;
- }
-
- if (frame->nb_samples != avctx->frame_size) {
- av_log(avctx, AV_LOG_ERROR, "nb_samples (%d) != frame_size (%d) (avcodec_encode_audio2)\n", frame->nb_samples, avctx->frame_size);
- ret = AVERROR(EINVAL);
- goto end;
- }
- }
- }
-
- av_assert0(avctx->codec->encode2);
-
- ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
- if (!ret) {
- if (*got_packet_ptr) {
- if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY)) {
- if (avpkt->pts == AV_NOPTS_VALUE)
- avpkt->pts = frame->pts;
- if (!avpkt->duration)
- avpkt->duration = ff_samples_to_time_base(avctx,
- frame->nb_samples);
- }
- avpkt->dts = avpkt->pts;
- } else {
- avpkt->size = 0;
- }
- }
- if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
- needs_realloc = 0;
- if (user_pkt.data) {
- if (user_pkt.size >= avpkt->size) {
- memcpy(user_pkt.data, avpkt->data, avpkt->size);
- } else {
- av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
- avpkt->size = user_pkt.size;
- ret = -1;
- }
- avpkt->buf = user_pkt.buf;
- avpkt->data = user_pkt.data;
- } else {
- if (av_dup_packet(avpkt) < 0) {
- ret = AVERROR(ENOMEM);
- }
- }
- }
-
- if (!ret) {
- if (needs_realloc && avpkt->data) {
- ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);
- if (ret >= 0)
- avpkt->data = avpkt->buf->data;
- }
-
- avctx->frame_number++;
- }
-
- if (ret < 0 || !*got_packet_ptr) {
- av_packet_unref(avpkt);
- av_init_packet(avpkt);
- goto end;
- }
-
- /* NOTE: if we add any audio encoders which output non-keyframe packets,
- * this needs to be moved to the encoders, but for now we can do it
- * here to simplify things */
- avpkt->flags |= AV_PKT_FLAG_KEY;
-
-end:
- av_frame_free(&padded_frame);
- av_free(extended_frame);
-
-#if FF_API_AUDIOENC_DELAY
- avctx->delay = avctx->initial_padding;
-#endif
-
- return ret;
-}
-
-int attribute_align_arg avcodec_encode_video2(AVCodecContext *avctx,
- AVPacket *avpkt,
- const AVFrame *frame,
- int *got_packet_ptr)
-{
- int ret;
- AVPacket user_pkt = *avpkt;
- int needs_realloc = !user_pkt.data;
-
- *got_packet_ptr = 0;
-
- if (!avctx->codec->encode2) {
- av_log(avctx, AV_LOG_ERROR, "This encoder requires using the avcodec_send_frame() API.\n");
- return AVERROR(ENOSYS);
- }
-
- if(CONFIG_FRAME_THREAD_ENCODER &&
- avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))
- return ff_thread_video_encode_frame(avctx, avpkt, frame, got_packet_ptr);
-
- if ((avctx->flags&AV_CODEC_FLAG_PASS1) && avctx->stats_out)
- avctx->stats_out[0] = '\0';
-
- if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY) && !frame) {
- av_packet_unref(avpkt);
- av_init_packet(avpkt);
- avpkt->size = 0;
- return 0;
- }
-
- if (av_image_check_size(avctx->width, avctx->height, 0, avctx))
- return AVERROR(EINVAL);
-
- if (frame && frame->format == AV_PIX_FMT_NONE)
- av_log(avctx, AV_LOG_WARNING, "AVFrame.format is not set\n");
- if (frame && (frame->width == 0 || frame->height == 0))
- av_log(avctx, AV_LOG_WARNING, "AVFrame.width or height is not set\n");
-
- av_assert0(avctx->codec->encode2);
-
- ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);
- av_assert0(ret <= 0);
-
- emms_c();
-
- if (avpkt->data && avpkt->data == avctx->internal->byte_buffer) {
- needs_realloc = 0;
- if (user_pkt.data) {
- if (user_pkt.size >= avpkt->size) {
- memcpy(user_pkt.data, avpkt->data, avpkt->size);
- } else {
- av_log(avctx, AV_LOG_ERROR, "Provided packet is too small, needs to be %d\n", avpkt->size);
- avpkt->size = user_pkt.size;
- ret = -1;
- }
- avpkt->buf = user_pkt.buf;
- avpkt->data = user_pkt.data;
- } else {
- if (av_dup_packet(avpkt) < 0) {
- ret = AVERROR(ENOMEM);
- }
- }
- }
-
- if (!ret) {
- if (!*got_packet_ptr)
- avpkt->size = 0;
- else if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
- avpkt->pts = avpkt->dts = frame->pts;
-
- if (needs_realloc && avpkt->data) {
- ret = av_buffer_realloc(&avpkt->buf, avpkt->size + AV_INPUT_BUFFER_PADDING_SIZE);
- if (ret >= 0)
- avpkt->data = avpkt->buf->data;
- }
-
- avctx->frame_number++;
- }
-
- if (ret < 0 || !*got_packet_ptr)
- av_packet_unref(avpkt);
-
- return ret;
-}
-
-int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size,
- const AVSubtitle *sub)
-{
- int ret;
- if (sub->start_display_time) {
- av_log(avctx, AV_LOG_ERROR, "start_display_time must be 0.\n");
- return -1;
- }
-
- ret = avctx->codec->encode_sub(avctx, buf, buf_size, sub);
- avctx->frame_number++;
- return ret;
-}
-
-/**
- * Attempt to guess proper monotonic timestamps for decoded video frames
- * which might have incorrect times. Input timestamps may wrap around, in
- * which case the output will as well.
- *
- * @param pts the pts field of the decoded AVPacket, as passed through
- * AVFrame.pts
- * @param dts the dts field of the decoded AVPacket
- * @return one of the input values, may be AV_NOPTS_VALUE
- */
-static int64_t guess_correct_pts(AVCodecContext *ctx,
- int64_t reordered_pts, int64_t dts)
-{
- int64_t pts = AV_NOPTS_VALUE;
-
- if (dts != AV_NOPTS_VALUE) {
- ctx->pts_correction_num_faulty_dts += dts <= ctx->pts_correction_last_dts;
- ctx->pts_correction_last_dts = dts;
- } else if (reordered_pts != AV_NOPTS_VALUE)
- ctx->pts_correction_last_dts = reordered_pts;
-
- if (reordered_pts != AV_NOPTS_VALUE) {
- ctx->pts_correction_num_faulty_pts += reordered_pts <= ctx->pts_correction_last_pts;
- ctx->pts_correction_last_pts = reordered_pts;
- } else if(dts != AV_NOPTS_VALUE)
- ctx->pts_correction_last_pts = dts;
-
- if ((ctx->pts_correction_num_faulty_pts<=ctx->pts_correction_num_faulty_dts || dts == AV_NOPTS_VALUE)
- && reordered_pts != AV_NOPTS_VALUE)
- pts = reordered_pts;
- else
- pts = dts;
-
- return pts;
-}
-
-static int apply_param_change(AVCodecContext *avctx, AVPacket *avpkt)
-{
- int size = 0, ret;
- const uint8_t *data;
- uint32_t flags;
- int64_t val;
-
- data = av_packet_get_side_data(avpkt, AV_PKT_DATA_PARAM_CHANGE, &size);
- if (!data)
- return 0;
-
- if (!(avctx->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE)) {
- av_log(avctx, AV_LOG_ERROR, "This decoder does not support parameter "
- "changes, but PARAM_CHANGE side data was sent to it.\n");
- ret = AVERROR(EINVAL);
- goto fail2;
- }
-
- if (size < 4)
- goto fail;
-
- flags = bytestream_get_le32(&data);
- size -= 4;
-
- if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) {
- if (size < 4)
- goto fail;
- val = bytestream_get_le32(&data);
- if (val <= 0 || val > INT_MAX) {
- av_log(avctx, AV_LOG_ERROR, "Invalid channel count");
- ret = AVERROR_INVALIDDATA;
- goto fail2;
- }
- avctx->channels = val;
- size -= 4;
- }
- if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) {
- if (size < 8)
- goto fail;
- avctx->channel_layout = bytestream_get_le64(&data);
- size -= 8;
- }
- if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) {
- if (size < 4)
- goto fail;
- val = bytestream_get_le32(&data);
- if (val <= 0 || val > INT_MAX) {
- av_log(avctx, AV_LOG_ERROR, "Invalid sample rate");
- ret = AVERROR_INVALIDDATA;
- goto fail2;
- }
- avctx->sample_rate = val;
- size -= 4;
- }
- if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) {
- if (size < 8)
- goto fail;
- avctx->width = bytestream_get_le32(&data);
- avctx->height = bytestream_get_le32(&data);
- size -= 8;
- ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
- if (ret < 0)
- goto fail2;
- }
-
- return 0;
-fail:
- av_log(avctx, AV_LOG_ERROR, "PARAM_CHANGE side data too small.\n");
- ret = AVERROR_INVALIDDATA;
-fail2:
- if (ret < 0) {
- av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");
- if (avctx->err_recognition & AV_EF_EXPLODE)
- return ret;
- }
- return 0;
-}
-
-static int unrefcount_frame(AVCodecInternal *avci, AVFrame *frame)
-{
- int ret;
-
- /* move the original frame to our backup */
- av_frame_unref(avci->to_free);
- av_frame_move_ref(avci->to_free, frame);
-
- /* now copy everything except the AVBufferRefs back
- * note that we make a COPY of the side data, so calling av_frame_free() on
- * the caller's frame will work properly */
- ret = av_frame_copy_props(frame, avci->to_free);
- if (ret < 0)
- return ret;
-
- memcpy(frame->data, avci->to_free->data, sizeof(frame->data));
- memcpy(frame->linesize, avci->to_free->linesize, sizeof(frame->linesize));
- if (avci->to_free->extended_data != avci->to_free->data) {
- int planes = av_frame_get_channels(avci->to_free);
- int size = planes * sizeof(*frame->extended_data);
-
- if (!size) {
- av_frame_unref(frame);
- return AVERROR_BUG;
- }
-
- frame->extended_data = av_malloc(size);
- if (!frame->extended_data) {
- av_frame_unref(frame);
- return AVERROR(ENOMEM);
- }
- memcpy(frame->extended_data, avci->to_free->extended_data,
- size);
- } else
- frame->extended_data = frame->data;
-
- frame->format = avci->to_free->format;
- frame->width = avci->to_free->width;
- frame->height = avci->to_free->height;
- frame->channel_layout = avci->to_free->channel_layout;
- frame->nb_samples = avci->to_free->nb_samples;
- av_frame_set_channels(frame, av_frame_get_channels(avci->to_free));
-
- return 0;
-}
-
-int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
- int *got_picture_ptr,
- const AVPacket *avpkt)
-{
- AVCodecInternal *avci = avctx->internal;
- int ret;
- // copy to ensure we do not change avpkt
- AVPacket tmp = *avpkt;
-
- if (!avctx->codec)
- return AVERROR(EINVAL);
- if (avctx->codec->type != AVMEDIA_TYPE_VIDEO) {
- av_log(avctx, AV_LOG_ERROR, "Invalid media type for video\n");
- return AVERROR(EINVAL);
- }
-
- if (!avctx->codec->decode) {
- av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n");
- return AVERROR(ENOSYS);
- }
-
- *got_picture_ptr = 0;
- if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
- return AVERROR(EINVAL);
-
- avctx->internal->pkt = avpkt;
- ret = apply_param_change(avctx, avpkt);
- if (ret < 0)
- return ret;
-
- av_frame_unref(picture);
-
- if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size ||
- (avctx->active_thread_type & FF_THREAD_FRAME)) {
- int did_split = av_packet_split_side_data(&tmp);
- ret = apply_param_change(avctx, &tmp);
- if (ret < 0)
- goto fail;
-
- avctx->internal->pkt = &tmp;
- if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
- ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
- &tmp);
- else {
- ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
- &tmp);
- if (!(avctx->codec->caps_internal & FF_CODEC_CAP_SETS_PKT_DTS))
- picture->pkt_dts = avpkt->dts;
-
- if(!avctx->has_b_frames){
- av_frame_set_pkt_pos(picture, avpkt->pos);
- }
- //FIXME these should be under if(!avctx->has_b_frames)
- /* get_buffer is supposed to set frame parameters */
- if (!(avctx->codec->capabilities & AV_CODEC_CAP_DR1)) {
- if (!picture->sample_aspect_ratio.num) picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
- if (!picture->width) picture->width = avctx->width;
- if (!picture->height) picture->height = avctx->height;
- if (picture->format == AV_PIX_FMT_NONE) picture->format = avctx->pix_fmt;
- }
- }
-
-fail:
- emms_c(); //needed to avoid an emms_c() call before every return;
-
- avctx->internal->pkt = NULL;
- if (did_split) {
- av_packet_free_side_data(&tmp);
- if(ret == tmp.size)
- ret = avpkt->size;
- }
- if (picture->flags & AV_FRAME_FLAG_DISCARD) {
- *got_picture_ptr = 0;
- }
- if (*got_picture_ptr) {
- if (!avctx->refcounted_frames) {
- int err = unrefcount_frame(avci, picture);
- if (err < 0)
- return err;
- }
-
- avctx->frame_number++;
- av_frame_set_best_effort_timestamp(picture,
- guess_correct_pts(avctx,
- picture->pts,
- picture->pkt_dts));
- } else
- av_frame_unref(picture);
- } else
- ret = 0;
-
- /* many decoders assign whole AVFrames, thus overwriting extended_data;
- * make sure it's set correctly */
- av_assert0(!picture->extended_data || picture->extended_data == picture->data);
-
-#if FF_API_AVCTX_TIMEBASE
- if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
- avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
-#endif
-
- return ret;
-}
-
-int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,
- AVFrame *frame,
- int *got_frame_ptr,
- const AVPacket *avpkt)
-{
- AVCodecInternal *avci = avctx->internal;
- int ret = 0;
-
- *got_frame_ptr = 0;
-
- if (!avctx->codec)
- return AVERROR(EINVAL);
-
- if (!avctx->codec->decode) {
- av_log(avctx, AV_LOG_ERROR, "This decoder requires using the avcodec_send_packet() API.\n");
- return AVERROR(ENOSYS);
- }
-
- if (!avpkt->data && avpkt->size) {
- av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
- return AVERROR(EINVAL);
- }
- if (avctx->codec->type != AVMEDIA_TYPE_AUDIO) {
- av_log(avctx, AV_LOG_ERROR, "Invalid media type for audio\n");
- return AVERROR(EINVAL);
- }
-
- av_frame_unref(frame);
-
- if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
- uint8_t *side;
- int side_size;
- uint32_t discard_padding = 0;
- uint8_t skip_reason = 0;
- uint8_t discard_reason = 0;
- // copy to ensure we do not change avpkt
- AVPacket tmp = *avpkt;
- int did_split = av_packet_split_side_data(&tmp);
- ret = apply_param_change(avctx, &tmp);
- if (ret < 0)
- goto fail;
-
- avctx->internal->pkt = &tmp;
- if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
- ret = ff_thread_decode_frame(avctx, frame, got_frame_ptr, &tmp);
- else {
- ret = avctx->codec->decode(avctx, frame, got_frame_ptr, &tmp);
- av_assert0(ret <= tmp.size);
- frame->pkt_dts = avpkt->dts;
- }
- if (ret >= 0 && *got_frame_ptr) {
- avctx->frame_number++;
- av_frame_set_best_effort_timestamp(frame,
- guess_correct_pts(avctx,
- frame->pts,
- frame->pkt_dts));
- if (frame->format == AV_SAMPLE_FMT_NONE)
- frame->format = avctx->sample_fmt;
- if (!frame->channel_layout)
- frame->channel_layout = avctx->channel_layout;
- if (!av_frame_get_channels(frame))
- av_frame_set_channels(frame, avctx->channels);
- if (!frame->sample_rate)
- frame->sample_rate = avctx->sample_rate;
- }
-
- side= av_packet_get_side_data(avctx->internal->pkt, AV_PKT_DATA_SKIP_SAMPLES, &side_size);
- if(side && side_size>=10) {
- avctx->internal->skip_samples = AV_RL32(side);
- discard_padding = AV_RL32(side + 4);
- av_log(avctx, AV_LOG_DEBUG, "skip %d / discard %d samples due to side data\n",
- avctx->internal->skip_samples, (int)discard_padding);
- skip_reason = AV_RL8(side + 8);
- discard_reason = AV_RL8(side + 9);
- }
-
- if ((frame->flags & AV_FRAME_FLAG_DISCARD) && *got_frame_ptr &&
- !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
- avctx->internal->skip_samples -= frame->nb_samples;
- *got_frame_ptr = 0;
- }
-
- if (avctx->internal->skip_samples > 0 && *got_frame_ptr &&
- !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
- if(frame->nb_samples <= avctx->internal->skip_samples){
- *got_frame_ptr = 0;
- avctx->internal->skip_samples -= frame->nb_samples;
- av_log(avctx, AV_LOG_DEBUG, "skip whole frame, skip left: %d\n",
- avctx->internal->skip_samples);
- } else {
- av_samples_copy(frame->extended_data, frame->extended_data, 0, avctx->internal->skip_samples,
- frame->nb_samples - avctx->internal->skip_samples, avctx->channels, frame->format);
- if(avctx->pkt_timebase.num && avctx->sample_rate) {
- int64_t diff_ts = av_rescale_q(avctx->internal->skip_samples,
- (AVRational){1, avctx->sample_rate},
- avctx->pkt_timebase);
- if(frame->pts!=AV_NOPTS_VALUE)
- frame->pts += diff_ts;
-#if FF_API_PKT_PTS
-FF_DISABLE_DEPRECATION_WARNINGS
- if(frame->pkt_pts!=AV_NOPTS_VALUE)
- frame->pkt_pts += diff_ts;
-FF_ENABLE_DEPRECATION_WARNINGS
-#endif
- if(frame->pkt_dts!=AV_NOPTS_VALUE)
- frame->pkt_dts += diff_ts;
- if (av_frame_get_pkt_duration(frame) >= diff_ts)
- av_frame_set_pkt_duration(frame, av_frame_get_pkt_duration(frame) - diff_ts);
- } else {
- av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for skipped samples.\n");
- }
- av_log(avctx, AV_LOG_DEBUG, "skip %d/%d samples\n",
- avctx->internal->skip_samples, frame->nb_samples);
- frame->nb_samples -= avctx->internal->skip_samples;
- avctx->internal->skip_samples = 0;
- }
- }
-
- if (discard_padding > 0 && discard_padding <= frame->nb_samples && *got_frame_ptr &&
- !(avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL)) {
- if (discard_padding == frame->nb_samples) {
- *got_frame_ptr = 0;
- } else {
- if(avctx->pkt_timebase.num && avctx->sample_rate) {
- int64_t diff_ts = av_rescale_q(frame->nb_samples - discard_padding,
- (AVRational){1, avctx->sample_rate},
- avctx->pkt_timebase);
- av_frame_set_pkt_duration(frame, diff_ts);
- } else {
- av_log(avctx, AV_LOG_WARNING, "Could not update timestamps for discarded samples.\n");
- }
- av_log(avctx, AV_LOG_DEBUG, "discard %d/%d samples\n",
- (int)discard_padding, frame->nb_samples);
- frame->nb_samples -= discard_padding;
- }
- }
-
- if ((avctx->flags2 & AV_CODEC_FLAG2_SKIP_MANUAL) && *got_frame_ptr) {
- AVFrameSideData *fside = av_frame_new_side_data(frame, AV_FRAME_DATA_SKIP_SAMPLES, 10);
- if (fside) {
- AV_WL32(fside->data, avctx->internal->skip_samples);
- AV_WL32(fside->data + 4, discard_padding);
- AV_WL8(fside->data + 8, skip_reason);
- AV_WL8(fside->data + 9, discard_reason);
- avctx->internal->skip_samples = 0;
- }
- }
-fail:
- avctx->internal->pkt = NULL;
- if (did_split) {
- av_packet_free_side_data(&tmp);
- if(ret == tmp.size)
- ret = avpkt->size;
- }
-
- if (ret >= 0 && *got_frame_ptr) {
- if (!avctx->refcounted_frames) {
- int err = unrefcount_frame(avci, frame);
- if (err < 0)
- return err;
- }
- } else
- av_frame_unref(frame);
- }
-
- av_assert0(ret <= avpkt->size);
-
- if (!avci->showed_multi_packet_warning &&
- ret >= 0 && ret != avpkt->size && !(avctx->codec->capabilities & AV_CODEC_CAP_SUBFRAMES)) {
- av_log(avctx, AV_LOG_WARNING, "Multiple frames in a packet.\n");
- avci->showed_multi_packet_warning = 1;
- }
-
- return ret;
-}
-
-#define UTF8_MAX_BYTES 4 /* 5 and 6 bytes sequences should not be used */
-static int recode_subtitle(AVCodecContext *avctx,
- AVPacket *outpkt, const AVPacket *inpkt)
-{
-#if CONFIG_ICONV
- iconv_t cd = (iconv_t)-1;
- int ret = 0;
- char *inb, *outb;
- size_t inl, outl;
- AVPacket tmp;
-#endif
-
- if (avctx->sub_charenc_mode != FF_SUB_CHARENC_MODE_PRE_DECODER || inpkt->size == 0)
- return 0;
-
-#if CONFIG_ICONV
- cd = iconv_open("UTF-8", avctx->sub_charenc);
- av_assert0(cd != (iconv_t)-1);
-
- inb = inpkt->data;
- inl = inpkt->size;
-
- if (inl >= INT_MAX / UTF8_MAX_BYTES - AV_INPUT_BUFFER_PADDING_SIZE) {
- av_log(avctx, AV_LOG_ERROR, "Subtitles packet is too big for recoding\n");
- ret = AVERROR(ENOMEM);
- goto end;
- }
-
- ret = av_new_packet(&tmp, inl * UTF8_MAX_BYTES);
- if (ret < 0)
- goto end;
- outpkt->buf = tmp.buf;
- outpkt->data = tmp.data;
- outpkt->size = tmp.size;
- outb = outpkt->data;
- outl = outpkt->size;
-
- if (iconv(cd, &inb, &inl, &outb, &outl) == (size_t)-1 ||
- iconv(cd, NULL, NULL, &outb, &outl) == (size_t)-1 ||
- outl >= outpkt->size || inl != 0) {
- ret = FFMIN(AVERROR(errno), -1);
- av_log(avctx, AV_LOG_ERROR, "Unable to recode subtitle event \"%s\" "
- "from %s to UTF-8\n", inpkt->data, avctx->sub_charenc);
- av_packet_unref(&tmp);
- goto end;
- }
- outpkt->size -= outl;
- memset(outpkt->data + outpkt->size, 0, outl);
-
-end:
- if (cd != (iconv_t)-1)
- iconv_close(cd);
- return ret;
-#else
- av_log(avctx, AV_LOG_ERROR, "requesting subtitles recoding without iconv");
- return AVERROR(EINVAL);
-#endif
-}
-
-static int utf8_check(const uint8_t *str)
-{
- const uint8_t *byte;
- uint32_t codepoint, min;
-
- while (*str) {
- byte = str;
- GET_UTF8(codepoint, *(byte++), return 0;);
- min = byte - str == 1 ? 0 : byte - str == 2 ? 0x80 :
- 1 << (5 * (byte - str) - 4);
- if (codepoint < min || codepoint >= 0x110000 ||
- codepoint == 0xFFFE /* BOM */ ||
- codepoint >= 0xD800 && codepoint <= 0xDFFF /* surrogates */)
- return 0;
- str = byte;
- }
- return 1;
-}
-
-#if FF_API_ASS_TIMING
-static void insert_ts(AVBPrint *buf, int ts)
-{
- if (ts == -1) {
- av_bprintf(buf, "9:59:59.99,");
- } else {
- int h, m, s;
-
- h = ts/360000; ts -= 360000*h;
- m = ts/ 6000; ts -= 6000*m;
- s = ts/ 100; ts -= 100*s;
- av_bprintf(buf, "%d:%02d:%02d.%02d,", h, m, s, ts);
- }
-}
-
-static int convert_sub_to_old_ass_form(AVSubtitle *sub, const AVPacket *pkt, AVRational tb)
-{
- int i;
- AVBPrint buf;
-
- av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
-
- for (i = 0; i < sub->num_rects; i++) {
- char *final_dialog;
- const char *dialog;
- AVSubtitleRect *rect = sub->rects[i];
- int ts_start, ts_duration = -1;
- long int layer;
-
- if (rect->type != SUBTITLE_ASS || !strncmp(rect->ass, "Dialogue: ", 10))
- continue;
-
- av_bprint_clear(&buf);
-
- /* skip ReadOrder */
- dialog = strchr(rect->ass, ',');
- if (!dialog)
- continue;
- dialog++;
-
- /* extract Layer or Marked */
- layer = strtol(dialog, (char**)&dialog, 10);
- if (*dialog != ',')
- continue;
- dialog++;
-
- /* rescale timing to ASS time base (ms) */
- ts_start = av_rescale_q(pkt->pts, tb, av_make_q(1, 100));
- if (pkt->duration != -1)
- ts_duration = av_rescale_q(pkt->duration, tb, av_make_q(1, 100));
- sub->end_display_time = FFMAX(sub->end_display_time, 10 * ts_duration);
-
- /* construct ASS (standalone file form with timestamps) string */
- av_bprintf(&buf, "Dialogue: %ld,", layer);
- insert_ts(&buf, ts_start);
- insert_ts(&buf, ts_duration == -1 ? -1 : ts_start + ts_duration);
- av_bprintf(&buf, "%s\r\n", dialog);
-
- final_dialog = av_strdup(buf.str);
- if (!av_bprint_is_complete(&buf) || !final_dialog) {
- av_freep(&final_dialog);
- av_bprint_finalize(&buf, NULL);
- return AVERROR(ENOMEM);
- }
- av_freep(&rect->ass);
- rect->ass = final_dialog;
- }
-
- av_bprint_finalize(&buf, NULL);
- return 0;
-}
-#endif
-
-int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
- int *got_sub_ptr,
- AVPacket *avpkt)
-{
- int i, ret = 0;
-
- if (!avpkt->data && avpkt->size) {
- av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
- return AVERROR(EINVAL);
- }
- if (!avctx->codec)
- return AVERROR(EINVAL);
- if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
- av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
- return AVERROR(EINVAL);
- }
-
- *got_sub_ptr = 0;
- get_subtitle_defaults(sub);
-
- if ((avctx->codec->capabilities & AV_CODEC_CAP_DELAY) || avpkt->size) {
- AVPacket pkt_recoded;
- AVPacket tmp = *avpkt;
- int did_split = av_packet_split_side_data(&tmp);
- //apply_param_change(avctx, &tmp);
-
- if (did_split) {
- /* FFMIN() prevents overflow in case the packet wasn't allocated with
- * proper padding.
- * If the side data is smaller than the buffer padding size, the
- * remaining bytes should have already been filled with zeros by the
- * original packet allocation anyway. */
- memset(tmp.data + tmp.size, 0,
- FFMIN(avpkt->size - tmp.size, AV_INPUT_BUFFER_PADDING_SIZE));
- }
-
- pkt_recoded = tmp;
- ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
- if (ret < 0) {
- *got_sub_ptr = 0;
- } else {
- avctx->internal->pkt = &pkt_recoded;
-
- if (avctx->pkt_timebase.num && avpkt->pts != AV_NOPTS_VALUE)
- sub->pts = av_rescale_q(avpkt->pts,
- avctx->pkt_timebase, AV_TIME_BASE_Q);
- ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
- av_assert1((ret >= 0) >= !!*got_sub_ptr &&
- !!*got_sub_ptr >= !!sub->num_rects);
-
-#if FF_API_ASS_TIMING
- if (avctx->sub_text_format == FF_SUB_TEXT_FMT_ASS_WITH_TIMINGS
- && *got_sub_ptr && sub->num_rects) {
- const AVRational tb = avctx->pkt_timebase.num ? avctx->pkt_timebase
- : avctx->time_base;
- int err = convert_sub_to_old_ass_form(sub, avpkt, tb);
- if (err < 0)
- ret = err;
- }
-#endif
-
- if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
- avctx->pkt_timebase.num) {
- AVRational ms = { 1, 1000 };
- sub->end_display_time = av_rescale_q(avpkt->duration,
- avctx->pkt_timebase, ms);
- }
-
- for (i = 0; i < sub->num_rects; i++) {
- if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
- av_log(avctx, AV_LOG_ERROR,
- "Invalid UTF-8 in decoded subtitles text; "
- "maybe missing -sub_charenc option\n");
- avsubtitle_free(sub);
- return AVERROR_INVALIDDATA;
- }
- }
-
- if (tmp.data != pkt_recoded.data) { // did we recode?
- /* prevent from destroying side data from original packet */
- pkt_recoded.side_data = NULL;
- pkt_recoded.side_data_elems = 0;
-
- av_packet_unref(&pkt_recoded);
- }
- if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
- sub->format = 0;
- else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
- sub->format = 1;
- avctx->internal->pkt = NULL;
- }
-
- if (did_split) {
- av_packet_free_side_data(&tmp);
- if(ret == tmp.size)
- ret = avpkt->size;
- }
-
- if (*got_sub_ptr)
- avctx->frame_number++;
- }
-
- return ret;
-}
-
void avsubtitle_free(AVSubtitle *sub)
{
int i;
@@ -2761,263 +1157,7 @@ void avsubtitle_free(AVSubtitle *sub)
av_freep(&sub->rects);
- memset(sub, 0, sizeof(AVSubtitle));
-}
-
-static int do_decode(AVCodecContext *avctx, AVPacket *pkt)
-{
- int got_frame;
- int ret;
-
- av_assert0(!avctx->internal->buffer_frame->buf[0]);
-
- if (!pkt)
- pkt = avctx->internal->buffer_pkt;
-
- // This is the lesser evil. The field is for compatibility with legacy users
- // of the legacy API, and users using the new API should not be forced to
- // even know about this field.
- avctx->refcounted_frames = 1;
-
- // Some codecs (at least wma lossless) will crash when feeding drain packets
- // after EOF was signaled.
- if (avctx->internal->draining_done)
- return AVERROR_EOF;
-
- if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
- ret = avcodec_decode_video2(avctx, avctx->internal->buffer_frame,
- &got_frame, pkt);
- if (ret >= 0)
- ret = pkt->size;
- } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
- ret = avcodec_decode_audio4(avctx, avctx->internal->buffer_frame,
- &got_frame, pkt);
- } else {
- ret = AVERROR(EINVAL);
- }
-
- if (ret == AVERROR(EAGAIN))
- ret = pkt->size;
-
- if (ret < 0)
- return ret;
-
- if (avctx->internal->draining && !got_frame)
- avctx->internal->draining_done = 1;
-
- if (ret >= pkt->size) {
- av_packet_unref(avctx->internal->buffer_pkt);
- } else {
- int consumed = ret;
-
- if (pkt != avctx->internal->buffer_pkt) {
- av_packet_unref(avctx->internal->buffer_pkt);
- if ((ret = av_packet_ref(avctx->internal->buffer_pkt, pkt)) < 0)
- return ret;
- }
-
- avctx->internal->buffer_pkt->data += consumed;
- avctx->internal->buffer_pkt->size -= consumed;
- avctx->internal->buffer_pkt->pts = AV_NOPTS_VALUE;
- avctx->internal->buffer_pkt->dts = AV_NOPTS_VALUE;
- }
-
- if (got_frame)
- av_assert0(avctx->internal->buffer_frame->buf[0]);
-
- return 0;
-}
-
-int attribute_align_arg avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
-{
- int ret;
-
- if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
- return AVERROR(EINVAL);
-
- if (avctx->internal->draining)
- return AVERROR_EOF;
-
- if (avpkt && !avpkt->size && avpkt->data)
- return AVERROR(EINVAL);
-
- if (!avpkt || !avpkt->size) {
- avctx->internal->draining = 1;
- avpkt = NULL;
-
- if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
- return 0;
- }
-
- if (avctx->codec->send_packet) {
- if (avpkt) {
- AVPacket tmp = *avpkt;
- int did_split = av_packet_split_side_data(&tmp);
- ret = apply_param_change(avctx, &tmp);
- if (ret >= 0)
- ret = avctx->codec->send_packet(avctx, &tmp);
- if (did_split)
- av_packet_free_side_data(&tmp);
- return ret;
- } else {
- return avctx->codec->send_packet(avctx, NULL);
- }
- }
-
- // Emulation via old API. Assume avpkt is likely not refcounted, while
- // decoder output is always refcounted, and avoid copying.
-
- if (avctx->internal->buffer_pkt->size || avctx->internal->buffer_frame->buf[0])
- return AVERROR(EAGAIN);
-
- // The goal is decoding the first frame of the packet without using memcpy,
- // because the common case is having only 1 frame per packet (especially
- // with video, but audio too). In other cases, it can't be avoided, unless
- // the user is feeding refcounted packets.
- return do_decode(avctx, (AVPacket *)avpkt);
-}
-
-int attribute_align_arg avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
-{
- int ret;
-
- av_frame_unref(frame);
-
- if (!avcodec_is_open(avctx) || !av_codec_is_decoder(avctx->codec))
- return AVERROR(EINVAL);
-
- if (avctx->codec->receive_frame) {
- if (avctx->internal->draining && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
- return AVERROR_EOF;
- ret = avctx->codec->receive_frame(avctx, frame);
- if (ret >= 0) {
- if (av_frame_get_best_effort_timestamp(frame) == AV_NOPTS_VALUE) {
- av_frame_set_best_effort_timestamp(frame,
- guess_correct_pts(avctx, frame->pts, frame->pkt_dts));
- }
- }
- return ret;
- }
-
- // Emulation via old API.
-
- if (!avctx->internal->buffer_frame->buf[0]) {
- if (!avctx->internal->buffer_pkt->size && !avctx->internal->draining)
- return AVERROR(EAGAIN);
-
- while (1) {
- if ((ret = do_decode(avctx, avctx->internal->buffer_pkt)) < 0) {
- av_packet_unref(avctx->internal->buffer_pkt);
- return ret;
- }
- // Some audio decoders may consume partial data without returning
- // a frame (fate-wmapro-2ch). There is no way to make the caller
- // call avcodec_receive_frame() again without returning a frame,
- // so try to decode more in these cases.
- if (avctx->internal->buffer_frame->buf[0] ||
- !avctx->internal->buffer_pkt->size)
- break;
- }
- }
-
- if (!avctx->internal->buffer_frame->buf[0])
- return avctx->internal->draining ? AVERROR_EOF : AVERROR(EAGAIN);
-
- av_frame_move_ref(frame, avctx->internal->buffer_frame);
- return 0;
-}
-
-static int do_encode(AVCodecContext *avctx, const AVFrame *frame, int *got_packet)
-{
- int ret;
- *got_packet = 0;
-
- av_packet_unref(avctx->internal->buffer_pkt);
- avctx->internal->buffer_pkt_valid = 0;
-
- if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
- ret = avcodec_encode_video2(avctx, avctx->internal->buffer_pkt,
- frame, got_packet);
- } else if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {
- ret = avcodec_encode_audio2(avctx, avctx->internal->buffer_pkt,
- frame, got_packet);
- } else {
- ret = AVERROR(EINVAL);
- }
-
- if (ret >= 0 && *got_packet) {
- // Encoders must always return ref-counted buffers.
- // Side-data only packets have no data and can be not ref-counted.
- av_assert0(!avctx->internal->buffer_pkt->data || avctx->internal->buffer_pkt->buf);
- avctx->internal->buffer_pkt_valid = 1;
- ret = 0;
- } else {
- av_packet_unref(avctx->internal->buffer_pkt);
- }
-
- return ret;
-}
-
-int attribute_align_arg avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
-{
- if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
- return AVERROR(EINVAL);
-
- if (avctx->internal->draining)
- return AVERROR_EOF;
-
- if (!frame) {
- avctx->internal->draining = 1;
-
- if (!(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
- return 0;
- }
-
- if (avctx->codec->send_frame)
- return avctx->codec->send_frame(avctx, frame);
-
- // Emulation via old API. Do it here instead of avcodec_receive_packet, because:
- // 1. if the AVFrame is not refcounted, the copying will be much more
- // expensive than copying the packet data
- // 2. assume few users use non-refcounted AVPackets, so usually no copy is
- // needed
-
- if (avctx->internal->buffer_pkt_valid)
- return AVERROR(EAGAIN);
-
- return do_encode(avctx, frame, &(int){0});
-}
-
-int attribute_align_arg avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
-{
- av_packet_unref(avpkt);
-
- if (!avcodec_is_open(avctx) || !av_codec_is_encoder(avctx->codec))
- return AVERROR(EINVAL);
-
- if (avctx->codec->receive_packet) {
- if (avctx->internal->draining && !(avctx->codec->capabilities & AV_CODEC_CAP_DELAY))
- return AVERROR_EOF;
- return avctx->codec->receive_packet(avctx, avpkt);
- }
-
- // Emulation via old API.
-
- if (!avctx->internal->buffer_pkt_valid) {
- int got_packet;
- int ret;
- if (!avctx->internal->draining)
- return AVERROR(EAGAIN);
- ret = do_encode(avctx, NULL, &got_packet);
- if (ret < 0)
- return ret;
- if (ret >= 0 && !got_packet)
- return AVERROR_EOF;
- }
-
- av_packet_move_ref(avpkt, avctx->internal->buffer_pkt);
- avctx->internal->buffer_pkt_valid = 0;
- return 0;
+ memset(sub, 0, sizeof(*sub));
}
av_cold int avcodec_close(AVCodecContext *avctx)
@@ -3040,8 +1180,13 @@ av_cold int avcodec_close(AVCodecContext *avctx)
avctx->internal->byte_buffer_size = 0;
av_freep(&avctx->internal->byte_buffer);
av_frame_free(&avctx->internal->to_free);
+ av_frame_free(&avctx->internal->compat_decode_frame);
av_frame_free(&avctx->internal->buffer_frame);
av_packet_free(&avctx->internal->buffer_pkt);
+ av_packet_free(&avctx->internal->last_pkt_props);
+
+ av_packet_free(&avctx->internal->ds.in_pkt);
+
for (i = 0; i < FF_ARRAY_ELEMS(pool->pools); i++)
av_buffer_pool_uninit(&pool->pools[i]);
av_freep(&avctx->internal->pool);
@@ -3050,6 +1195,8 @@ av_cold int avcodec_close(AVCodecContext *avctx)
avctx->hwaccel->uninit(avctx);
av_freep(&avctx->internal->hwaccel_priv_data);
+ ff_decode_bsfs_uninit(avctx);
+
av_freep(&avctx->internal);
}
@@ -3059,6 +1206,7 @@ av_cold int avcodec_close(AVCodecContext *avctx)
avctx->nb_coded_side_data = 0;
av_buffer_unref(&avctx->hw_frames_ctx);
+ av_buffer_unref(&avctx->hw_device_ctx);
if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
av_opt_free(avctx->priv_data);
@@ -3215,12 +1363,9 @@ void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
", %d reference frame%s",
enc->refs, enc->refs > 1 ? "s" : "");
- if (enc->codec_tag) {
- char tag_buf[32];
- av_get_codec_tag_string(tag_buf, sizeof(tag_buf), enc->codec_tag);
- snprintf(buf + strlen(buf), buf_size - strlen(buf),
- " (%s / 0x%04X)", tag_buf, enc->codec_tag);
- }
+ if (enc->codec_tag)
+ snprintf(buf + strlen(buf), buf_size - strlen(buf), " (%s / 0x%04X)",
+ av_fourcc2str(enc->codec_tag), enc->codec_tag);
switch (enc->codec_type) {
case AVMEDIA_TYPE_VIDEO:
@@ -3377,7 +1522,7 @@ void avcodec_string(char *buf, int buf_size, AVCodecContext *enc, int encode)
", %"PRId64" kb/s", bitrate / 1000);
} else if (enc->rc_max_rate > 0) {
snprintf(buf + strlen(buf), buf_size - strlen(buf),
- ", max. %"PRId64" kb/s", (int64_t)enc->rc_max_rate / 1000);
+ ", max. %"PRId64" kb/s", enc->rc_max_rate / 1000);
}
}
@@ -3432,26 +1577,6 @@ const char *avcodec_license(void)
return LICENSE_PREFIX FFMPEG_LICENSE + sizeof(LICENSE_PREFIX) - 1;
}
-void avcodec_flush_buffers(AVCodecContext *avctx)
-{
- avctx->internal->draining = 0;
- avctx->internal->draining_done = 0;
- av_frame_unref(avctx->internal->buffer_frame);
- av_packet_unref(avctx->internal->buffer_pkt);
- avctx->internal->buffer_pkt_valid = 0;
-
- if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
- ff_thread_flush(avctx);
- else if (avctx->codec->flush)
- avctx->codec->flush(avctx);
-
- avctx->pts_correction_last_pts =
- avctx->pts_correction_last_dts = INT64_MIN;
-
- if (!avctx->refcounted_frames)
- av_frame_unref(avctx->internal->to_free);
-}
-
int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
{
switch (codec_id) {
@@ -3499,6 +1624,8 @@ int av_get_exact_bits_per_sample(enum AVCodecID codec_id)
case AV_CODEC_ID_PCM_U32LE:
case AV_CODEC_ID_PCM_F32BE:
case AV_CODEC_ID_PCM_F32LE:
+ case AV_CODEC_ID_PCM_F24LE:
+ case AV_CODEC_ID_PCM_F16LE:
return 32;
case AV_CODEC_ID_PCM_F64BE:
case AV_CODEC_ID_PCM_F64LE:
@@ -3595,6 +1722,9 @@ static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba,
if (id == AV_CODEC_ID_BINKAUDIO_DCT)
return (480 << (sr / 22050)) / ch;
}
+
+ if (id == AV_CODEC_ID_MP3)
+ return sr <= 24000 ? 576 : 1152;
}
if (ba > 0) {
@@ -3627,7 +1757,7 @@ static int get_audio_frame_duration(enum AVCodecID id, int sr, int ch, int ba,
if (bps > 0) {
/* calc from frame_bytes and bits_per_coded_sample */
- if (id == AV_CODEC_ID_ADPCM_G726)
+ if (id == AV_CODEC_ID_ADPCM_G726 || id == AV_CODEC_ID_ADPCM_G726LE)
return frame_bytes * 8 / bps;
}
@@ -3931,7 +2061,8 @@ int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
{
int ret;
- dst->owner = src->owner;
+ dst->owner[0] = src->owner[0];
+ dst->owner[1] = src->owner[1];
ret = av_frame_ref(dst->f, src->f);
if (ret < 0)
@@ -3941,7 +2072,7 @@ int ff_thread_ref_frame(ThreadFrame *dst, ThreadFrame *src)
if (src->progress &&
!(dst->progress = av_buffer_ref(src->progress))) {
- ff_thread_release_buffer(dst->owner, dst);
+ ff_thread_release_buffer(dst->owner[0], dst);
return AVERROR(ENOMEM);
}
@@ -3957,7 +2088,7 @@ enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixe
int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
{
- f->owner = avctx;
+ f->owner[0] = f->owner[1] = avctx;
return ff_get_buffer(avctx, f->f, flags);
}
@@ -4319,3 +2450,24 @@ int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len,
return 0;
}
+
+int64_t ff_guess_coded_bitrate(AVCodecContext *avctx)
+{
+ AVRational framerate = avctx->framerate;
+ int bits_per_coded_sample = avctx->bits_per_coded_sample;
+ int64_t bitrate;
+
+ if (!(framerate.num && framerate.den))
+ framerate = av_inv_q(avctx->time_base);
+ if (!(framerate.num && framerate.den))
+ return 0;
+
+ if (!bits_per_coded_sample) {
+ const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(avctx->pix_fmt);
+ bits_per_coded_sample = av_get_bits_per_pixel(desc);
+ }
+ bitrate = (int64_t)bits_per_coded_sample * avctx->width * avctx->height *
+ framerate.num / framerate.den;
+
+ return bitrate;
+}
diff --git a/media/ffvpx/libavcodec/version.h b/media/ffvpx/libavcodec/version.h
index ec8837a4e..10d9ac4eb 100644
--- a/media/ffvpx/libavcodec/version.h
+++ b/media/ffvpx/libavcodec/version.h
@@ -28,8 +28,8 @@
#include "libavutil/version.h"
#define LIBAVCODEC_VERSION_MAJOR 57
-#define LIBAVCODEC_VERSION_MINOR 64
-#define LIBAVCODEC_VERSION_MICRO 101
+#define LIBAVCODEC_VERSION_MINOR 107
+#define LIBAVCODEC_VERSION_MICRO 100
#define LIBAVCODEC_VERSION_INT AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
LIBAVCODEC_VERSION_MINOR, \
@@ -60,9 +60,6 @@
#ifndef FF_API_AVCODEC_RESAMPLE
#define FF_API_AVCODEC_RESAMPLE FF_API_AUDIO_CONVERT
#endif
-#ifndef FF_API_GETCHROMA
-#define FF_API_GETCHROMA (LIBAVCODEC_VERSION_MAJOR < 58)
-#endif
#ifndef FF_API_MISSING_SAMPLE
#define FF_API_MISSING_SAMPLE (LIBAVCODEC_VERSION_MAJOR < 58)
#endif
@@ -157,6 +154,9 @@
#ifndef FF_API_VAAPI_CONTEXT
#define FF_API_VAAPI_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 58)
#endif
+#ifndef FF_API_MERGE_SD
+#define FF_API_MERGE_SD (LIBAVCODEC_VERSION_MAJOR < 58)
+#endif
#ifndef FF_API_AVCTX_TIMEBASE
#define FF_API_AVCTX_TIMEBASE (LIBAVCODEC_VERSION_MAJOR < 59)
#endif
@@ -226,5 +226,18 @@
#ifndef FF_API_NVENC_OLD_NAME
#define FF_API_NVENC_OLD_NAME (LIBAVCODEC_VERSION_MAJOR < 59)
#endif
+#ifndef FF_API_STRUCT_VAAPI_CONTEXT
+#define FF_API_STRUCT_VAAPI_CONTEXT (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_MERGE_SD_API
+#define FF_API_MERGE_SD_API (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_TAG_STRING
+#define FF_API_TAG_STRING (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+#ifndef FF_API_GETCHROMA
+#define FF_API_GETCHROMA (LIBAVCODEC_VERSION_MAJOR < 59)
+#endif
+
#endif /* AVCODEC_VERSION_H */
diff --git a/media/ffvpx/libavcodec/videodsp.c b/media/ffvpx/libavcodec/videodsp.c
index ba618a7bb..ce9e9eb14 100644
--- a/media/ffvpx/libavcodec/videodsp.c
+++ b/media/ffvpx/libavcodec/videodsp.c
@@ -52,4 +52,6 @@ av_cold void ff_videodsp_init(VideoDSPContext *ctx, int bpc)
ff_videodsp_init_ppc(ctx, bpc);
if (ARCH_X86)
ff_videodsp_init_x86(ctx, bpc);
+ if (ARCH_MIPS)
+ ff_videodsp_init_mips(ctx, bpc);
}
diff --git a/media/ffvpx/libavcodec/videodsp.h b/media/ffvpx/libavcodec/videodsp.h
index fc01a31dc..c0545f22b 100644
--- a/media/ffvpx/libavcodec/videodsp.h
+++ b/media/ffvpx/libavcodec/videodsp.h
@@ -83,5 +83,6 @@ void ff_videodsp_init_aarch64(VideoDSPContext *ctx, int bpc);
void ff_videodsp_init_arm(VideoDSPContext *ctx, int bpc);
void ff_videodsp_init_ppc(VideoDSPContext *ctx, int bpc);
void ff_videodsp_init_x86(VideoDSPContext *ctx, int bpc);
+void ff_videodsp_init_mips(VideoDSPContext *ctx, int bpc);
#endif /* AVCODEC_VIDEODSP_H */
diff --git a/media/ffvpx/libavcodec/vlc.h b/media/ffvpx/libavcodec/vlc.h
index 9e38f8c6b..42ccddf3f 100644
--- a/media/ffvpx/libavcodec/vlc.h
+++ b/media/ffvpx/libavcodec/vlc.h
@@ -54,12 +54,28 @@ void ff_free_vlc(VLC *vlc);
#define INIT_VLC_LE 2
#define INIT_VLC_USE_NEW_STATIC 4
-#define INIT_VLC_STATIC(vlc, bits, a, b, c, d, e, f, g, static_size) \
+#define INIT_VLC_SPARSE_STATIC(vlc, bits, a, b, c, d, e, f, g, h, i, j, static_size) \
+ do { \
+ static VLC_TYPE table[static_size][2]; \
+ (vlc)->table = table; \
+ (vlc)->table_allocated = static_size; \
+ ff_init_vlc_sparse(vlc, bits, a, b, c, d, e, f, g, h, i, j, \
+ INIT_VLC_USE_NEW_STATIC); \
+ } while (0)
+
+#define INIT_LE_VLC_SPARSE_STATIC(vlc, bits, a, b, c, d, e, f, g, h, i, j, static_size) \
do { \
static VLC_TYPE table[static_size][2]; \
(vlc)->table = table; \
(vlc)->table_allocated = static_size; \
- init_vlc(vlc, bits, a, b, c, d, e, f, g, INIT_VLC_USE_NEW_STATIC); \
+ ff_init_vlc_sparse(vlc, bits, a, b, c, d, e, f, g, h, i, j, \
+ INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE); \
} while (0)
+#define INIT_VLC_STATIC(vlc, bits, a, b, c, d, e, f, g, static_size) \
+ INIT_VLC_SPARSE_STATIC(vlc, bits, a, b, c, d, e, f, g, NULL, 0, 0, static_size)
+
+#define INIT_LE_VLC_STATIC(vlc, bits, a, b, c, d, e, f, g, static_size) \
+ INIT_LE_VLC_SPARSE_STATIC(vlc, bits, a, b, c, d, e, f, g, NULL, 0, 0, static_size)
+
#endif /* AVCODEC_VLC_H */
diff --git a/media/ffvpx/libavcodec/vorbis_parser.h b/media/ffvpx/libavcodec/vorbis_parser.h
index 92050277e..789932ac4 100644
--- a/media/ffvpx/libavcodec/vorbis_parser.h
+++ b/media/ffvpx/libavcodec/vorbis_parser.h
@@ -32,9 +32,6 @@ typedef struct AVVorbisParseContext AVVorbisParseContext;
/**
* Allocate and initialize the Vorbis parser using headers in the extradata.
- *
- * @param avctx codec context
- * @param s Vorbis parser context
*/
AVVorbisParseContext *av_vorbis_parse_init(const uint8_t *extradata,
int extradata_size);
diff --git a/media/ffvpx/libavcodec/vp3dsp.h b/media/ffvpx/libavcodec/vp3dsp.h
index b95adae79..2fdad162c 100644
--- a/media/ffvpx/libavcodec/vp3dsp.h
+++ b/media/ffvpx/libavcodec/vp3dsp.h
@@ -38,11 +38,11 @@ typedef struct VP3DSPContext {
const uint8_t *b,
ptrdiff_t stride, int h);
- void (*idct_put)(uint8_t *dest, int line_size, int16_t *block);
- void (*idct_add)(uint8_t *dest, int line_size, int16_t *block);
- void (*idct_dc_add)(uint8_t *dest, int line_size, int16_t *block);
- void (*v_loop_filter)(uint8_t *src, int stride, int *bounding_values);
- void (*h_loop_filter)(uint8_t *src, int stride, int *bounding_values);
+ void (*idct_put)(uint8_t *dest, ptrdiff_t stride, int16_t *block);
+ void (*idct_add)(uint8_t *dest, ptrdiff_t stride, int16_t *block);
+ void (*idct_dc_add)(uint8_t *dest, ptrdiff_t stride, int16_t *block);
+ void (*v_loop_filter)(uint8_t *src, ptrdiff_t stride, int *bounding_values);
+ void (*h_loop_filter)(uint8_t *src, ptrdiff_t stride, int *bounding_values);
} VP3DSPContext;
void ff_vp3dsp_init(VP3DSPContext *c, int flags);
diff --git a/media/ffvpx/libavcodec/vp56.h b/media/ffvpx/libavcodec/vp56.h
index 56c30919b..b8dda9e73 100644
--- a/media/ffvpx/libavcodec/vp56.h
+++ b/media/ffvpx/libavcodec/vp56.h
@@ -26,6 +26,7 @@
#ifndef AVCODEC_VP56_H
#define AVCODEC_VP56_H
+#include "avcodec.h"
#include "get_bits.h"
#include "hpeldsp.h"
#include "bytestream.h"
@@ -72,9 +73,9 @@ typedef struct VP56mv {
typedef void (*VP56ParseVectorAdjustment)(VP56Context *s,
VP56mv *vect);
typedef void (*VP56Filter)(VP56Context *s, uint8_t *dst, uint8_t *src,
- int offset1, int offset2, int stride,
+ int offset1, int offset2, ptrdiff_t stride,
VP56mv mv, int mask, int select, int luma);
-typedef void (*VP56ParseCoeff)(VP56Context *s);
+typedef int (*VP56ParseCoeff)(VP56Context *s);
typedef void (*VP56DefaultModelsInit)(VP56Context *s);
typedef void (*VP56ParseVectorModels)(VP56Context *s);
typedef int (*VP56ParseCoeffModels)(VP56Context *s);
@@ -179,7 +180,7 @@ struct vp56_context {
int flip; /* are we flipping ? */
int frbi; /* first row block index in MB */
int srbi; /* second row block index in MB */
- int stride[4]; /* stride for each plan */
+ ptrdiff_t stride[4]; /* stride for each plan */
const uint8_t *vp56_coord_div;
VP56ParseVectorAdjustment parse_vector_adjustment;
@@ -203,6 +204,9 @@ struct vp56_context {
VLC runv_vlc[2];
VLC ract_vlc[2][3][6];
unsigned int nb_null[2][2]; /* number of consecutive NULL DC/AC */
+
+ int have_undamaged_frame;
+ int discard_frame;
};
@@ -221,7 +225,7 @@ int ff_vp56_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
*/
extern const uint8_t ff_vp56_norm_shift[256];
-void ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size);
+int ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size);
static av_always_inline unsigned int vp56_rac_renorm(VP56RangeCoder *c)
{
diff --git a/media/ffvpx/libavcodec/vp56dsp.h b/media/ffvpx/libavcodec/vp56dsp.h
index 7807baa4b..e35e232ea 100644
--- a/media/ffvpx/libavcodec/vp56dsp.h
+++ b/media/ffvpx/libavcodec/vp56dsp.h
@@ -21,22 +21,24 @@
#ifndef AVCODEC_VP56DSP_H
#define AVCODEC_VP56DSP_H
+#include <stddef.h>
#include <stdint.h>
-#include "avcodec.h"
typedef struct VP56DSPContext {
- void (*edge_filter_hor)(uint8_t *yuv, int stride, int t);
- void (*edge_filter_ver)(uint8_t *yuv, int stride, int t);
+ void (*edge_filter_hor)(uint8_t *yuv, ptrdiff_t stride, int t);
+ void (*edge_filter_ver)(uint8_t *yuv, ptrdiff_t stride, int t);
- void (*vp6_filter_diag4)(uint8_t *dst, uint8_t *src, int stride,
+ void (*vp6_filter_diag4)(uint8_t *dst, uint8_t *src, ptrdiff_t stride,
const int16_t *h_weights,const int16_t *v_weights);
} VP56DSPContext;
-void ff_vp6_filter_diag4_c(uint8_t *dst, uint8_t *src, int stride,
+void ff_vp6_filter_diag4_c(uint8_t *dst, uint8_t *src, ptrdiff_t stride,
const int16_t *h_weights, const int16_t *v_weights);
-void ff_vp56dsp_init(VP56DSPContext *s, enum AVCodecID codec);
-void ff_vp6dsp_init_arm(VP56DSPContext *s, enum AVCodecID codec);
-void ff_vp6dsp_init_x86(VP56DSPContext* c, enum AVCodecID codec);
+void ff_vp5dsp_init(VP56DSPContext *s);
+void ff_vp6dsp_init(VP56DSPContext *s);
+
+void ff_vp6dsp_init_arm(VP56DSPContext *s);
+void ff_vp6dsp_init_x86(VP56DSPContext *s);
#endif /* AVCODEC_VP56DSP_H */
diff --git a/media/ffvpx/libavcodec/vp56rac.c b/media/ffvpx/libavcodec/vp56rac.c
index 6061b7ee7..e70302bf8 100644
--- a/media/ffvpx/libavcodec/vp56rac.c
+++ b/media/ffvpx/libavcodec/vp56rac.c
@@ -37,11 +37,14 @@ const uint8_t ff_vp56_norm_shift[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,
};
-void ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size)
+int ff_vp56_init_range_decoder(VP56RangeCoder *c, const uint8_t *buf, int buf_size)
{
c->high = 255;
c->bits = -16;
c->buffer = buf;
c->end = buf + buf_size;
+ if (buf_size < 1)
+ return AVERROR_INVALIDDATA;
c->code_word = bytestream_get_be24(&c->buffer);
+ return 0;
}
diff --git a/media/ffvpx/libavcodec/vp8.c b/media/ffvpx/libavcodec/vp8.c
index c1c3eb707..7841a9d96 100644
--- a/media/ffvpx/libavcodec/vp8.c
+++ b/media/ffvpx/libavcodec/vp8.c
@@ -261,6 +261,7 @@ static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size)
{
const uint8_t *sizes = buf;
int i;
+ int ret;
s->num_coeff_partitions = 1 << vp8_rac_get_uint(&s->c, 2);
@@ -274,13 +275,13 @@ static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size)
if (buf_size - size < 0)
return -1;
- ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size);
+ ret = ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size);
+ if (ret < 0)
+ return ret;
buf += size;
buf_size -= size;
}
- ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size);
-
- return 0;
+ return ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size);
}
static void vp7_get_quants(VP8Context *s)
@@ -434,8 +435,8 @@ static void copy_chroma(AVFrame *dst, AVFrame *src, int width, int height)
}
}
-static void fade(uint8_t *dst, int dst_linesize,
- const uint8_t *src, int src_linesize,
+static void fade(uint8_t *dst, ptrdiff_t dst_linesize,
+ const uint8_t *src, ptrdiff_t src_linesize,
int width, int height,
int alpha, int beta)
{
@@ -518,7 +519,9 @@ static int vp7_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_si
memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, sizeof(s->put_pixels_tab));
- ff_vp56_init_range_decoder(c, buf, part1_size);
+ ret = ff_vp56_init_range_decoder(c, buf, part1_size);
+ if (ret < 0)
+ return ret;
buf += part1_size;
buf_size -= part1_size;
@@ -570,7 +573,9 @@ static int vp7_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_si
s->lf_delta.enabled = 0;
s->num_coeff_partitions = 1;
- ff_vp56_init_range_decoder(&s->coeff_partition[0], buf, buf_size);
+ ret = ff_vp56_init_range_decoder(&s->coeff_partition[0], buf, buf_size);
+ if (ret < 0)
+ return ret;
if (!s->macroblocks_base || /* first frame */
width != s->avctx->width || height != s->avctx->height ||
@@ -699,7 +704,9 @@ static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_si
memset(&s->lf_delta, 0, sizeof(s->lf_delta));
}
- ff_vp56_init_range_decoder(c, buf, header_size);
+ ret = ff_vp56_init_range_decoder(c, buf, header_size);
+ if (ret < 0)
+ return ret;
buf += header_size;
buf_size -= header_size;
@@ -765,7 +772,7 @@ static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_si
}
static av_always_inline
-void clamp_mv(VP8Context *s, VP56mv *dst, const VP56mv *src)
+void clamp_mv(VP8mvbounds *s, VP56mv *dst, const VP56mv *src)
{
dst->x = av_clip(src->x, av_clip(s->mv_min.x, INT16_MIN, INT16_MAX),
av_clip(s->mv_max.x, INT16_MIN, INT16_MAX));
@@ -1024,7 +1031,7 @@ void vp7_decode_mvs(VP8Context *s, VP8Macroblock *mb,
}
static av_always_inline
-void vp8_decode_mvs(VP8Context *s, VP8Macroblock *mb,
+void vp8_decode_mvs(VP8Context *s, VP8mvbounds *mv_bounds, VP8Macroblock *mb,
int mb_x, int mb_y, int layout)
{
VP8Macroblock *mb_edge[3] = { 0 /* top */,
@@ -1095,7 +1102,7 @@ void vp8_decode_mvs(VP8Context *s, VP8Macroblock *mb,
if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAREST]][1])) {
if (vp56_rac_get_prob_branchy(c, vp8_mode_contexts[cnt[CNT_NEAR]][2])) {
/* Choose the best mv out of 0,0 and the nearest mv */
- clamp_mv(s, &mb->mv, &near_mv[CNT_ZERO + (cnt[CNT_NEAREST] >= cnt[CNT_ZERO])]);
+ clamp_mv(mv_bounds, &mb->mv, &near_mv[CNT_ZERO + (cnt[CNT_NEAREST] >= cnt[CNT_ZERO])]);
cnt[CNT_SPLITMV] = ((mb_edge[VP8_EDGE_LEFT]->mode == VP8_MVMODE_SPLIT) +
(mb_edge[VP8_EDGE_TOP]->mode == VP8_MVMODE_SPLIT)) * 2 +
(mb_edge[VP8_EDGE_TOPLEFT]->mode == VP8_MVMODE_SPLIT);
@@ -1109,11 +1116,11 @@ void vp8_decode_mvs(VP8Context *s, VP8Macroblock *mb,
mb->bmv[0] = mb->mv;
}
} else {
- clamp_mv(s, &mb->mv, &near_mv[CNT_NEAR]);
+ clamp_mv(mv_bounds, &mb->mv, &near_mv[CNT_NEAR]);
mb->bmv[0] = mb->mv;
}
} else {
- clamp_mv(s, &mb->mv, &near_mv[CNT_NEAREST]);
+ clamp_mv(mv_bounds, &mb->mv, &near_mv[CNT_NEAREST]);
mb->bmv[0] = mb->mv;
}
} else {
@@ -1159,14 +1166,15 @@ void decode_intra4x4_modes(VP8Context *s, VP56RangeCoder *c, VP8Macroblock *mb,
}
static av_always_inline
-void decode_mb_mode(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y,
+void decode_mb_mode(VP8Context *s, VP8mvbounds *mv_bounds,
+ VP8Macroblock *mb, int mb_x, int mb_y,
uint8_t *segment, uint8_t *ref, int layout, int is_vp7)
{
VP56RangeCoder *c = &s->c;
- static const char *vp7_feature_name[] = { "q-index",
- "lf-delta",
- "partial-golden-update",
- "blit-pitch" };
+ static const char * const vp7_feature_name[] = { "q-index",
+ "lf-delta",
+ "partial-golden-update",
+ "blit-pitch" };
if (is_vp7) {
int i;
*segment = 0;
@@ -1223,7 +1231,7 @@ void decode_mb_mode(VP8Context *s, VP8Macroblock *mb, int mb_x, int mb_y,
if (is_vp7)
vp7_decode_mvs(s, mb, mb_x, mb_y, layout);
else
- vp8_decode_mvs(s, mb, mb_x, mb_y, layout);
+ vp8_decode_mvs(s, mv_bounds, mb, mb_x, mb_y, layout);
} else {
// intra MB, 16.1
mb->mode = vp8_rac_get_tree(c, vp8_pred16x16_tree_inter, s->prob->pred16x16);
@@ -1461,7 +1469,7 @@ void decode_mb_coeffs(VP8Context *s, VP8ThreadData *td, VP56RangeCoder *c,
static av_always_inline
void backup_mb_border(uint8_t *top_border, uint8_t *src_y,
uint8_t *src_cb, uint8_t *src_cr,
- int linesize, int uvlinesize, int simple)
+ ptrdiff_t linesize, ptrdiff_t uvlinesize, int simple)
{
AV_COPY128(top_border, src_y + 15 * linesize);
if (!simple) {
@@ -1472,7 +1480,7 @@ void backup_mb_border(uint8_t *top_border, uint8_t *src_y,
static av_always_inline
void xchg_mb_border(uint8_t *top_border, uint8_t *src_y, uint8_t *src_cb,
- uint8_t *src_cr, int linesize, int uvlinesize, int mb_x,
+ uint8_t *src_cr, ptrdiff_t linesize, ptrdiff_t uvlinesize, int mb_x,
int mb_y, int mb_width, int simple, int xchg)
{
uint8_t *top_border_m1 = top_border - 32; // for TL prediction
@@ -1625,7 +1633,8 @@ void intra_predict(VP8Context *s, VP8ThreadData *td, uint8_t *dst[3],
for (y = 0; y < 4; y++) {
uint8_t *topright = ptr + 4 - s->linesize;
for (x = 0; x < 4; x++) {
- int copy = 0, linesize = s->linesize;
+ int copy = 0;
+ ptrdiff_t linesize = s->linesize;
uint8_t *dst = ptr + 4 * x;
LOCAL_ALIGNED(4, uint8_t, copy_dst, [5 * 8]);
@@ -1731,7 +1740,7 @@ void vp8_mc_luma(VP8Context *s, VP8ThreadData *td, uint8_t *dst,
uint8_t *src = ref->f->data[0];
if (AV_RN32A(mv)) {
- int src_linesize = linesize;
+ ptrdiff_t src_linesize = linesize;
int mx = (mv->x * 2) & 7, mx_idx = subpel_idx[0][mx];
int my = (mv->y * 2) & 7, my_idx = subpel_idx[0][my];
@@ -2077,8 +2086,8 @@ void filter_mb(VP8Context *s, uint8_t *dst[3], VP8FilterStrength *f,
int filter_level = f->filter_level;
int inner_limit = f->inner_limit;
int inner_filter = f->inner_filter;
- int linesize = s->linesize;
- int uvlinesize = s->uvlinesize;
+ ptrdiff_t linesize = s->linesize;
+ ptrdiff_t uvlinesize = s->uvlinesize;
static const uint8_t hev_thresh_lut[2][64] = {
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
@@ -2164,7 +2173,7 @@ void filter_mb_simple(VP8Context *s, uint8_t *dst, VP8FilterStrength *f,
int filter_level = f->filter_level;
int inner_limit = f->inner_limit;
int inner_filter = f->inner_filter;
- int linesize = s->linesize;
+ ptrdiff_t linesize = s->linesize;
if (!filter_level)
return;
@@ -2197,8 +2206,8 @@ void vp78_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *curframe,
VP8Context *s = avctx->priv_data;
int mb_x, mb_y;
- s->mv_min.y = -MARGIN;
- s->mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;
+ s->mv_bounds.mv_min.y = -MARGIN;
+ s->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;
for (mb_y = 0; mb_y < s->mb_height; mb_y++) {
VP8Macroblock *mb = s->macroblocks_base +
((s->mb_width + 1) * (mb_y + 1) + 1);
@@ -2206,20 +2215,20 @@ void vp78_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *curframe,
AV_WN32A(s->intra4x4_pred_mode_left, DC_PRED * 0x01010101);
- s->mv_min.x = -MARGIN;
- s->mv_max.x = ((s->mb_width - 1) << 6) + MARGIN;
+ s->mv_bounds.mv_min.x = -MARGIN;
+ s->mv_bounds.mv_max.x = ((s->mb_width - 1) << 6) + MARGIN;
for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb_xy++, mb++) {
if (mb_y == 0)
AV_WN32A((mb - s->mb_width - 1)->intra4x4_pred_mode_top,
DC_PRED * 0x01010101);
- decode_mb_mode(s, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy,
+ decode_mb_mode(s, &s->mv_bounds, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy,
prev_frame && prev_frame->seg_map ?
prev_frame->seg_map->data + mb_xy : NULL, 1, is_vp7);
- s->mv_min.x -= 64;
- s->mv_max.x -= 64;
+ s->mv_bounds.mv_min.x -= 64;
+ s->mv_bounds.mv_max.x -= 64;
}
- s->mv_min.y -= 64;
- s->mv_max.y -= 64;
+ s->mv_bounds.mv_min.y -= 64;
+ s->mv_bounds.mv_max.y -= 64;
}
}
@@ -2239,15 +2248,15 @@ static void vp8_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *cur_frame,
#define check_thread_pos(td, otd, mb_x_check, mb_y_check) \
do { \
int tmp = (mb_y_check << 16) | (mb_x_check & 0xFFFF); \
- if (otd->thread_mb_pos < tmp) { \
+ if (atomic_load(&otd->thread_mb_pos) < tmp) { \
pthread_mutex_lock(&otd->lock); \
- td->wait_mb_pos = tmp; \
+ atomic_store(&td->wait_mb_pos, tmp); \
do { \
- if (otd->thread_mb_pos >= tmp) \
+ if (atomic_load(&otd->thread_mb_pos) >= tmp) \
break; \
pthread_cond_wait(&otd->cond, &otd->lock); \
} while (1); \
- td->wait_mb_pos = INT_MAX; \
+ atomic_store(&td->wait_mb_pos, INT_MAX); \
pthread_mutex_unlock(&otd->lock); \
} \
} while (0)
@@ -2258,12 +2267,10 @@ static void vp8_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *cur_frame,
int sliced_threading = (avctx->active_thread_type == FF_THREAD_SLICE) && \
(num_jobs > 1); \
int is_null = !next_td || !prev_td; \
- int pos_check = (is_null) ? 1 \
- : (next_td != td && \
- pos >= next_td->wait_mb_pos) || \
- (prev_td != td && \
- pos >= prev_td->wait_mb_pos); \
- td->thread_mb_pos = pos; \
+ int pos_check = (is_null) ? 1 : \
+ (next_td != td && pos >= atomic_load(&next_td->wait_mb_pos)) || \
+ (prev_td != td && pos >= atomic_load(&prev_td->wait_mb_pos)); \
+ atomic_store(&td->thread_mb_pos, pos); \
if (sliced_threading && pos_check) { \
pthread_mutex_lock(&td->lock); \
pthread_cond_broadcast(&td->cond); \
@@ -2275,12 +2282,12 @@ static void vp8_decode_mv_mb_modes(AVCodecContext *avctx, VP8Frame *cur_frame,
#define update_pos(td, mb_y, mb_x) while(0)
#endif
-static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata,
+static av_always_inline int decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata,
int jobnr, int threadnr, int is_vp7)
{
VP8Context *s = avctx->priv_data;
VP8ThreadData *prev_td, *next_td, *td = &s->thread_data[threadnr];
- int mb_y = td->thread_mb_pos >> 16;
+ int mb_y = atomic_load(&td->thread_mb_pos) >> 16;
int mb_x, mb_xy = mb_y * s->mb_width;
int num_jobs = s->num_jobs;
VP8Frame *curframe = s->curframe, *prev_frame = s->prev_frame;
@@ -2291,6 +2298,10 @@ static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void
curframe->tf.f->data[1] + 8 * mb_y * s->uvlinesize,
curframe->tf.f->data[2] + 8 * mb_y * s->uvlinesize
};
+
+ if (c->end <= c->buffer && c->bits >= 0)
+ return AVERROR_INVALIDDATA;
+
if (mb_y == 0)
prev_td = td;
else
@@ -2315,10 +2326,12 @@ static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void
if (!is_vp7 || mb_y == 0)
memset(td->left_nnz, 0, sizeof(td->left_nnz));
- s->mv_min.x = -MARGIN;
- s->mv_max.x = ((s->mb_width - 1) << 6) + MARGIN;
+ td->mv_bounds.mv_min.x = -MARGIN;
+ td->mv_bounds.mv_max.x = ((s->mb_width - 1) << 6) + MARGIN;
for (mb_x = 0; mb_x < s->mb_width; mb_x++, mb_xy++, mb++) {
+ if (c->end <= c->buffer && c->bits >= 0)
+ return AVERROR_INVALIDDATA;
// Wait for previous thread to read mb_x+2, and reach mb_y-1.
if (prev_td != td) {
if (threadnr != 0) {
@@ -2338,7 +2351,7 @@ static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void
dst[2] - dst[1], 2);
if (!s->mb_layout)
- decode_mb_mode(s, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy,
+ decode_mb_mode(s, &td->mv_bounds, mb, mb_x, mb_y, curframe->seg_map->data + mb_xy,
prev_frame && prev_frame->seg_map ?
prev_frame->seg_map->data + mb_xy : NULL, 0, is_vp7);
@@ -2385,8 +2398,8 @@ static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void
dst[0] += 16;
dst[1] += 8;
dst[2] += 8;
- s->mv_min.x -= 64;
- s->mv_max.x -= 64;
+ td->mv_bounds.mv_min.x -= 64;
+ td->mv_bounds.mv_max.x -= 64;
if (mb_x == s->mb_width + 1) {
update_pos(td, mb_y, s->mb_width + 3);
@@ -2394,18 +2407,19 @@ static av_always_inline void decode_mb_row_no_filter(AVCodecContext *avctx, void
update_pos(td, mb_y, mb_x);
}
}
+ return 0;
}
-static void vp7_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata,
+static int vp7_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata,
int jobnr, int threadnr)
{
- decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 1);
+ return decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 1);
}
-static void vp8_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata,
+static int vp8_decode_mb_row_no_filter(AVCodecContext *avctx, void *tdata,
int jobnr, int threadnr)
{
- decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 0);
+ return decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr, 0);
}
static av_always_inline void filter_mb_row(AVCodecContext *avctx, void *tdata,
@@ -2413,7 +2427,7 @@ static av_always_inline void filter_mb_row(AVCodecContext *avctx, void *tdata,
{
VP8Context *s = avctx->priv_data;
VP8ThreadData *td = &s->thread_data[threadnr];
- int mb_x, mb_y = td->thread_mb_pos >> 16, num_jobs = s->num_jobs;
+ int mb_x, mb_y = atomic_load(&td->thread_mb_pos) >> 16, num_jobs = s->num_jobs;
AVFrame *curframe = s->curframe->tf.f;
VP8Macroblock *mb;
VP8ThreadData *prev_td, *next_td;
@@ -2488,19 +2502,24 @@ int vp78_decode_mb_row_sliced(AVCodecContext *avctx, void *tdata, int jobnr,
VP8ThreadData *next_td = NULL, *prev_td = NULL;
VP8Frame *curframe = s->curframe;
int mb_y, num_jobs = s->num_jobs;
+ int ret;
td->thread_nr = threadnr;
+ td->mv_bounds.mv_min.y = -MARGIN - 64 * threadnr;
+ td->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN - 64 * threadnr;
for (mb_y = jobnr; mb_y < s->mb_height; mb_y += num_jobs) {
- if (mb_y >= s->mb_height)
- break;
- td->thread_mb_pos = mb_y << 16;
- s->decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr);
+ atomic_store(&td->thread_mb_pos, mb_y << 16);
+ ret = s->decode_mb_row_no_filter(avctx, tdata, jobnr, threadnr);
+ if (ret < 0) {
+ update_pos(td, s->mb_height, INT_MAX & 0xFFFF);
+ return ret;
+ }
if (s->deblock_filter)
s->filter_mb_row(avctx, tdata, jobnr, threadnr);
update_pos(td, mb_y, INT_MAX & 0xFFFF);
- s->mv_min.y -= 64;
- s->mv_max.y -= 64;
+ td->mv_bounds.mv_min.y -= 64 * num_jobs;
+ td->mv_bounds.mv_max.y -= 64 * num_jobs;
if (avctx->active_thread_type == FF_THREAD_FRAME)
ff_thread_report_progress(&curframe->tf, mb_y, 0);
@@ -2531,6 +2550,8 @@ int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
enum AVDiscard skip_thresh;
VP8Frame *av_uninit(curframe), *prev_frame;
+ av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVA420P || avctx->pix_fmt == AV_PIX_FMT_YUV420P);
+
if (is_vp7)
ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size);
else
@@ -2646,11 +2667,12 @@ int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,
s->num_jobs = num_jobs;
s->curframe = curframe;
s->prev_frame = prev_frame;
- s->mv_min.y = -MARGIN;
- s->mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;
+ s->mv_bounds.mv_min.y = -MARGIN;
+ s->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN;
for (i = 0; i < MAX_THREADS; i++) {
- s->thread_data[i].thread_mb_pos = 0;
- s->thread_data[i].wait_mb_pos = INT_MAX;
+ VP8ThreadData *td = &s->thread_data[i];
+ atomic_init(&td->thread_mb_pos, 0);
+ atomic_init(&td->wait_mb_pos, INT_MAX);
}
if (is_vp7)
avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL,
diff --git a/media/ffvpx/libavcodec/vp8.h b/media/ffvpx/libavcodec/vp8.h
index 374e1388e..8263997e3 100644
--- a/media/ffvpx/libavcodec/vp8.h
+++ b/media/ffvpx/libavcodec/vp8.h
@@ -26,6 +26,8 @@
#ifndef AVCODEC_VP8_H
#define AVCODEC_VP8_H
+#include <stdatomic.h>
+
#include "libavutil/buffer.h"
#include "libavutil/thread.h"
@@ -91,6 +93,16 @@ typedef struct VP8Macroblock {
VP56mv bmv[16];
} VP8Macroblock;
+typedef struct VP8intmv {
+ int x;
+ int y;
+} VP8intmv;
+
+typedef struct VP8mvbounds {
+ VP8intmv mv_min;
+ VP8intmv mv_max;
+} VP8mvbounds;
+
typedef struct VP8ThreadData {
DECLARE_ALIGNED(16, int16_t, block)[6][4][16];
DECLARE_ALIGNED(16, int16_t, block_dc)[16];
@@ -114,12 +126,13 @@ typedef struct VP8ThreadData {
pthread_mutex_t lock;
pthread_cond_t cond;
#endif
- int thread_mb_pos; // (mb_y << 16) | (mb_x & 0xFFFF)
- int wait_mb_pos; // What the current thread is waiting on.
+ atomic_int thread_mb_pos; // (mb_y << 16) | (mb_x & 0xFFFF)
+ atomic_int wait_mb_pos; // What the current thread is waiting on.
#define EDGE_EMU_LINESIZE 32
DECLARE_ALIGNED(16, uint8_t, edge_emu_buffer)[21 * EDGE_EMU_LINESIZE];
VP8FilterStrength *filter_strength;
+ VP8mvbounds mv_bounds;
} VP8ThreadData;
typedef struct VP8Frame {
@@ -127,11 +140,6 @@ typedef struct VP8Frame {
AVBufferRef *seg_map;
} VP8Frame;
-typedef struct VP8intmv {
- int x;
- int y;
-} VP8intmv;
-
#define MAX_THREADS 8
typedef struct VP8Context {
VP8ThreadData *thread_data;
@@ -143,15 +151,14 @@ typedef struct VP8Context {
uint16_t mb_width; /* number of horizontal MB */
uint16_t mb_height; /* number of vertical MB */
- int linesize;
- int uvlinesize;
+ ptrdiff_t linesize;
+ ptrdiff_t uvlinesize;
uint8_t keyframe;
uint8_t deblock_filter;
uint8_t mbskip_enabled;
uint8_t profile;
- VP8intmv mv_min;
- VP8intmv mv_max;
+ VP8mvbounds mv_bounds;
int8_t sign_bias[4]; ///< one state [0, 1] per ref frame type
int ref_count[3];
@@ -275,7 +282,7 @@ typedef struct VP8Context {
*/
int mb_layout;
- void (*decode_mb_row_no_filter)(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr);
+ int (*decode_mb_row_no_filter)(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr);
void (*filter_mb_row)(AVCodecContext *avctx, void *tdata, int jobnr, int threadnr);
int vp7;
diff --git a/media/ffvpx/libavcodec/vp8_parser.c b/media/ffvpx/libavcodec/vp8_parser.c
index afc7f991e..609f5077d 100644
--- a/media/ffvpx/libavcodec/vp8_parser.c
+++ b/media/ffvpx/libavcodec/vp8_parser.c
@@ -1,6 +1,4 @@
/*
- * Copyright (C) 2008 Michael Niedermayer
- *
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
@@ -18,15 +16,56 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-#include "parser.h"
+#include "libavutil/intreadwrite.h"
+
+#include "avcodec.h"
static int parse(AVCodecParserContext *s,
AVCodecContext *avctx,
const uint8_t **poutbuf, int *poutbuf_size,
const uint8_t *buf, int buf_size)
{
- s->pict_type = (buf[0] & 0x01) ? AV_PICTURE_TYPE_P
- : AV_PICTURE_TYPE_I;
+ unsigned int frame_type;
+ unsigned int profile;
+
+ if (buf_size < 3)
+ return buf_size;
+
+ frame_type = buf[0] & 1;
+ profile = (buf[0] >> 1) & 7;
+ if (profile > 3) {
+ av_log(avctx, AV_LOG_ERROR, "Invalid profile %u.\n", profile);
+ return buf_size;
+ }
+
+ avctx->profile = profile;
+ s->key_frame = frame_type == 0;
+ s->pict_type = frame_type ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I;
+ s->format = AV_PIX_FMT_YUV420P;
+ s->field_order = AV_FIELD_PROGRESSIVE;
+ s->picture_structure = AV_PICTURE_STRUCTURE_FRAME;
+
+ if (frame_type == 0) {
+ unsigned int sync_code;
+ unsigned int width, height;
+
+ if (buf_size < 10)
+ return buf_size;
+
+ sync_code = AV_RL24(buf + 3);
+ if (sync_code != 0x2a019d) {
+ av_log(avctx, AV_LOG_ERROR, "Invalid sync code %06x.\n", sync_code);
+ return buf_size;
+ }
+
+ width = AV_RL16(buf + 6) & 0x3fff;
+ height = AV_RL16(buf + 8) & 0x3fff;
+
+ s->width = width;
+ s->height = height;
+ s->coded_width = FFALIGN(width, 16);
+ s->coded_height = FFALIGN(height, 16);
+ }
*poutbuf = buf;
*poutbuf_size = buf_size;
diff --git a/media/ffvpx/libavcodec/vp8dsp.c b/media/ffvpx/libavcodec/vp8dsp.c
index 07bea69c7..fed5c67a9 100644
--- a/media/ffvpx/libavcodec/vp8dsp.c
+++ b/media/ffvpx/libavcodec/vp8dsp.c
@@ -53,7 +53,8 @@ static void name ## _idct_dc_add4y_c(uint8_t *dst, int16_t block[4][16], \
#if CONFIG_VP7_DECODER
static void vp7_luma_dc_wht_c(int16_t block[4][4][16], int16_t dc[16])
{
- int i, a1, b1, c1, d1;
+ int i;
+ unsigned a1, b1, c1, d1;
int16_t tmp[16];
for (i = 0; i < 4; i++) {
@@ -61,10 +62,10 @@ static void vp7_luma_dc_wht_c(int16_t block[4][4][16], int16_t dc[16])
b1 = (dc[i * 4 + 0] - dc[i * 4 + 2]) * 23170;
c1 = dc[i * 4 + 1] * 12540 - dc[i * 4 + 3] * 30274;
d1 = dc[i * 4 + 1] * 30274 + dc[i * 4 + 3] * 12540;
- tmp[i * 4 + 0] = (a1 + d1) >> 14;
- tmp[i * 4 + 3] = (a1 - d1) >> 14;
- tmp[i * 4 + 1] = (b1 + c1) >> 14;
- tmp[i * 4 + 2] = (b1 - c1) >> 14;
+ tmp[i * 4 + 0] = (int)(a1 + d1) >> 14;
+ tmp[i * 4 + 3] = (int)(a1 - d1) >> 14;
+ tmp[i * 4 + 1] = (int)(b1 + c1) >> 14;
+ tmp[i * 4 + 2] = (int)(b1 - c1) >> 14;
}
for (i = 0; i < 4; i++) {
@@ -73,10 +74,10 @@ static void vp7_luma_dc_wht_c(int16_t block[4][4][16], int16_t dc[16])
c1 = tmp[i + 4] * 12540 - tmp[i + 12] * 30274;
d1 = tmp[i + 4] * 30274 + tmp[i + 12] * 12540;
AV_ZERO64(dc + i * 4);
- block[0][i][0] = (a1 + d1 + 0x20000) >> 18;
- block[3][i][0] = (a1 - d1 + 0x20000) >> 18;
- block[1][i][0] = (b1 + c1 + 0x20000) >> 18;
- block[2][i][0] = (b1 - c1 + 0x20000) >> 18;
+ block[0][i][0] = (int)(a1 + d1 + 0x20000) >> 18;
+ block[3][i][0] = (int)(a1 - d1 + 0x20000) >> 18;
+ block[1][i][0] = (int)(b1 + c1 + 0x20000) >> 18;
+ block[2][i][0] = (int)(b1 - c1 + 0x20000) >> 18;
}
}
@@ -95,7 +96,8 @@ static void vp7_luma_dc_wht_dc_c(int16_t block[4][4][16], int16_t dc[16])
static void vp7_idct_add_c(uint8_t *dst, int16_t block[16], ptrdiff_t stride)
{
- int i, a1, b1, c1, d1;
+ int i;
+ unsigned a1, b1, c1, d1;
int16_t tmp[16];
for (i = 0; i < 4; i++) {
@@ -104,10 +106,10 @@ static void vp7_idct_add_c(uint8_t *dst, int16_t block[16], ptrdiff_t stride)
c1 = block[i * 4 + 1] * 12540 - block[i * 4 + 3] * 30274;
d1 = block[i * 4 + 1] * 30274 + block[i * 4 + 3] * 12540;
AV_ZERO64(block + i * 4);
- tmp[i * 4 + 0] = (a1 + d1) >> 14;
- tmp[i * 4 + 3] = (a1 - d1) >> 14;
- tmp[i * 4 + 1] = (b1 + c1) >> 14;
- tmp[i * 4 + 2] = (b1 - c1) >> 14;
+ tmp[i * 4 + 0] = (int)(a1 + d1) >> 14;
+ tmp[i * 4 + 3] = (int)(a1 - d1) >> 14;
+ tmp[i * 4 + 1] = (int)(b1 + c1) >> 14;
+ tmp[i * 4 + 2] = (int)(b1 - c1) >> 14;
}
for (i = 0; i < 4; i++) {
@@ -116,13 +118,13 @@ static void vp7_idct_add_c(uint8_t *dst, int16_t block[16], ptrdiff_t stride)
c1 = tmp[i + 4] * 12540 - tmp[i + 12] * 30274;
d1 = tmp[i + 4] * 30274 + tmp[i + 12] * 12540;
dst[0 * stride + i] = av_clip_uint8(dst[0 * stride + i] +
- ((a1 + d1 + 0x20000) >> 18));
+ ((int)(a1 + d1 + 0x20000) >> 18));
dst[3 * stride + i] = av_clip_uint8(dst[3 * stride + i] +
- ((a1 - d1 + 0x20000) >> 18));
+ ((int)(a1 - d1 + 0x20000) >> 18));
dst[1 * stride + i] = av_clip_uint8(dst[1 * stride + i] +
- ((b1 + c1 + 0x20000) >> 18));
+ ((int)(b1 + c1 + 0x20000) >> 18));
dst[2 * stride + i] = av_clip_uint8(dst[2 * stride + i] +
- ((b1 - c1 + 0x20000) >> 18));
+ ((int)(b1 - c1 + 0x20000) >> 18));
}
}
diff --git a/media/ffvpx/libavcodec/vp8dsp.h b/media/ffvpx/libavcodec/vp8dsp.h
index 0401c9221..eaae4aed6 100644
--- a/media/ffvpx/libavcodec/vp8dsp.h
+++ b/media/ffvpx/libavcodec/vp8dsp.h
@@ -70,12 +70,12 @@ typedef struct VP8DSPContext {
void (*vp8_h_loop_filter_simple)(uint8_t *dst, ptrdiff_t stride, int flim);
/**
- * first dimension: width>>3, height is assumed equal to width
+ * first dimension: 4-log2(width)
* second dimension: 0 if no vertical interpolation is needed;
* 1 4-tap vertical interpolation filter (my & 1)
* 2 6-tap vertical interpolation filter (!(my & 1))
* third dimension: same as second dimension, for horizontal interpolation
- * so something like put_vp8_epel_pixels_tab[width>>3][2*!!my-(my&1)][2*!!mx-(mx&1)](..., mx, my)
+ * so something like put_vp8_epel_pixels_tab[4-log2(width)][2*!!my-(my&1)][2*!!mx-(mx&1)](..., mx, my)
*/
vp8_mc_func put_vp8_epel_pixels_tab[3][3][3];
vp8_mc_func put_vp8_bilinear_pixels_tab[3][3][3];
diff --git a/media/ffvpx/libavcodec/vp9.c b/media/ffvpx/libavcodec/vp9.c
index 1aab6ba03..f2cf19424 100644
--- a/media/ffvpx/libavcodec/vp9.c
+++ b/media/ffvpx/libavcodec/vp9.c
@@ -30,176 +30,97 @@
#include "vp56.h"
#include "vp9.h"
#include "vp9data.h"
-#include "vp9dsp.h"
+#include "vp9dec.h"
#include "libavutil/avassert.h"
#include "libavutil/pixdesc.h"
#define VP9_SYNCCODE 0x498342
-struct VP9Filter {
- uint8_t level[8 * 8];
- uint8_t /* bit=col */ mask[2 /* 0=y, 1=uv */][2 /* 0=col, 1=row */]
- [8 /* rows */][4 /* 0=16, 1=8, 2=4, 3=inner4 */];
-};
+#if HAVE_THREADS
+static void vp9_free_entries(AVCodecContext *avctx) {
+ VP9Context *s = avctx->priv_data;
-typedef struct VP9Block {
- uint8_t seg_id, intra, comp, ref[2], mode[4], uvmode, skip;
- enum FilterMode filter;
- VP56mv mv[4 /* b_idx */][2 /* ref */];
- enum BlockSize bs;
- enum TxfmMode tx, uvtx;
- enum BlockLevel bl;
- enum BlockPartition bp;
-} VP9Block;
-
-typedef struct VP9Context {
- VP9SharedContext s;
-
- VP9DSPContext dsp;
- VideoDSPContext vdsp;
- GetBitContext gb;
- VP56RangeCoder c;
- VP56RangeCoder *c_b;
- unsigned c_b_size;
- VP9Block *b_base, *b;
- int pass;
- int row, row7, col, col7;
- uint8_t *dst[3];
- ptrdiff_t y_stride, uv_stride;
-
- uint8_t ss_h, ss_v;
- uint8_t last_bpp, bpp, bpp_index, bytesperpixel;
- uint8_t last_keyframe;
- // sb_cols/rows, rows/cols and last_fmt are used for allocating all internal
- // arrays, and are thus per-thread. w/h and gf_fmt are synced between threads
- // and are therefore per-stream. pix_fmt represents the value in the header
- // of the currently processed frame.
- int w, h;
- enum AVPixelFormat pix_fmt, last_fmt, gf_fmt;
- unsigned sb_cols, sb_rows, rows, cols;
- ThreadFrame next_refs[8];
-
- struct {
- uint8_t lim_lut[64];
- uint8_t mblim_lut[64];
- } filter_lut;
- unsigned tile_row_start, tile_row_end, tile_col_start, tile_col_end;
- struct {
- prob_context p;
- uint8_t coef[4][2][2][6][6][3];
- } prob_ctx[4];
- struct {
- prob_context p;
- uint8_t coef[4][2][2][6][6][11];
- } prob;
- struct {
- unsigned y_mode[4][10];
- unsigned uv_mode[10][10];
- unsigned filter[4][3];
- unsigned mv_mode[7][4];
- unsigned intra[4][2];
- unsigned comp[5][2];
- unsigned single_ref[5][2][2];
- unsigned comp_ref[5][2];
- unsigned tx32p[2][4];
- unsigned tx16p[2][3];
- unsigned tx8p[2][2];
- unsigned skip[3][2];
- unsigned mv_joint[4];
- struct {
- unsigned sign[2];
- unsigned classes[11];
- unsigned class0[2];
- unsigned bits[10][2];
- unsigned class0_fp[2][4];
- unsigned fp[4];
- unsigned class0_hp[2];
- unsigned hp[2];
- } mv_comp[2];
- unsigned partition[4][4][4];
- unsigned coef[4][2][2][6][6][3];
- unsigned eob[4][2][2][6][6][2];
- } counts;
-
- // contextual (left/above) cache
- DECLARE_ALIGNED(16, uint8_t, left_y_nnz_ctx)[16];
- DECLARE_ALIGNED(16, uint8_t, left_mode_ctx)[16];
- DECLARE_ALIGNED(16, VP56mv, left_mv_ctx)[16][2];
- DECLARE_ALIGNED(16, uint8_t, left_uv_nnz_ctx)[2][16];
- DECLARE_ALIGNED(8, uint8_t, left_partition_ctx)[8];
- DECLARE_ALIGNED(8, uint8_t, left_skip_ctx)[8];
- DECLARE_ALIGNED(8, uint8_t, left_txfm_ctx)[8];
- DECLARE_ALIGNED(8, uint8_t, left_segpred_ctx)[8];
- DECLARE_ALIGNED(8, uint8_t, left_intra_ctx)[8];
- DECLARE_ALIGNED(8, uint8_t, left_comp_ctx)[8];
- DECLARE_ALIGNED(8, uint8_t, left_ref_ctx)[8];
- DECLARE_ALIGNED(8, uint8_t, left_filter_ctx)[8];
- uint8_t *above_partition_ctx;
- uint8_t *above_mode_ctx;
- // FIXME maybe merge some of the below in a flags field?
- uint8_t *above_y_nnz_ctx;
- uint8_t *above_uv_nnz_ctx[2];
- uint8_t *above_skip_ctx; // 1bit
- uint8_t *above_txfm_ctx; // 2bit
- uint8_t *above_segpred_ctx; // 1bit
- uint8_t *above_intra_ctx; // 1bit
- uint8_t *above_comp_ctx; // 1bit
- uint8_t *above_ref_ctx; // 2bit
- uint8_t *above_filter_ctx;
- VP56mv (*above_mv_ctx)[2];
-
- // whole-frame cache
- uint8_t *intra_pred_data[3];
- struct VP9Filter *lflvl;
- DECLARE_ALIGNED(32, uint8_t, edge_emu_buffer)[135 * 144 * 2];
-
- // block reconstruction intermediates
- int block_alloc_using_2pass;
- int16_t *block_base, *block, *uvblock_base[2], *uvblock[2];
- uint8_t *eob_base, *uveob_base[2], *eob, *uveob[2];
- struct { int x, y; } min_mv, max_mv;
- DECLARE_ALIGNED(32, uint8_t, tmp_y)[64 * 64 * 2];
- DECLARE_ALIGNED(32, uint8_t, tmp_uv)[2][64 * 64 * 2];
- uint16_t mvscale[3][2];
- uint8_t mvstep[3][2];
-} VP9Context;
-
-static const uint8_t bwh_tab[2][N_BS_SIZES][2] = {
- {
- { 16, 16 }, { 16, 8 }, { 8, 16 }, { 8, 8 }, { 8, 4 }, { 4, 8 },
- { 4, 4 }, { 4, 2 }, { 2, 4 }, { 2, 2 }, { 2, 1 }, { 1, 2 }, { 1, 1 },
- }, {
- { 8, 8 }, { 8, 4 }, { 4, 8 }, { 4, 4 }, { 4, 2 }, { 2, 4 },
- { 2, 2 }, { 2, 1 }, { 1, 2 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 1, 1 },
+ if (avctx->active_thread_type & FF_THREAD_SLICE) {
+ pthread_mutex_destroy(&s->progress_mutex);
+ pthread_cond_destroy(&s->progress_cond);
+ av_freep(&s->entries);
}
-};
+}
+
+static int vp9_alloc_entries(AVCodecContext *avctx, int n) {
+ VP9Context *s = avctx->priv_data;
+ int i;
+
+ if (avctx->active_thread_type & FF_THREAD_SLICE) {
+ if (s->entries)
+ av_freep(&s->entries);
+
+ s->entries = av_malloc_array(n, sizeof(atomic_int));
+
+ if (!s->entries) {
+ av_freep(&s->entries);
+ return AVERROR(ENOMEM);
+ }
-static void vp9_unref_frame(AVCodecContext *ctx, VP9Frame *f)
+ for (i = 0; i < n; i++)
+ atomic_init(&s->entries[i], 0);
+
+ pthread_mutex_init(&s->progress_mutex, NULL);
+ pthread_cond_init(&s->progress_cond, NULL);
+ }
+ return 0;
+}
+
+static void vp9_report_tile_progress(VP9Context *s, int field, int n) {
+ pthread_mutex_lock(&s->progress_mutex);
+ atomic_fetch_add_explicit(&s->entries[field], n, memory_order_release);
+ pthread_cond_signal(&s->progress_cond);
+ pthread_mutex_unlock(&s->progress_mutex);
+}
+
+static void vp9_await_tile_progress(VP9Context *s, int field, int n) {
+ if (atomic_load_explicit(&s->entries[field], memory_order_acquire) >= n)
+ return;
+
+ pthread_mutex_lock(&s->progress_mutex);
+ while (atomic_load_explicit(&s->entries[field], memory_order_relaxed) != n)
+ pthread_cond_wait(&s->progress_cond, &s->progress_mutex);
+ pthread_mutex_unlock(&s->progress_mutex);
+}
+#else
+static void vp9_free_entries(AVCodecContext *avctx) {}
+static int vp9_alloc_entries(AVCodecContext *avctx, int n) { return 0; }
+#endif
+
+static void vp9_frame_unref(AVCodecContext *avctx, VP9Frame *f)
{
- ff_thread_release_buffer(ctx, &f->tf);
+ ff_thread_release_buffer(avctx, &f->tf);
av_buffer_unref(&f->extradata);
av_buffer_unref(&f->hwaccel_priv_buf);
f->segmentation_map = NULL;
f->hwaccel_picture_private = NULL;
}
-static int vp9_alloc_frame(AVCodecContext *ctx, VP9Frame *f)
+static int vp9_frame_alloc(AVCodecContext *avctx, VP9Frame *f)
{
- VP9Context *s = ctx->priv_data;
+ VP9Context *s = avctx->priv_data;
int ret, sz;
- if ((ret = ff_thread_get_buffer(ctx, &f->tf, AV_GET_BUFFER_FLAG_REF)) < 0)
+ ret = ff_thread_get_buffer(avctx, &f->tf, AV_GET_BUFFER_FLAG_REF);
+ if (ret < 0)
return ret;
+
sz = 64 * s->sb_cols * s->sb_rows;
- if (!(f->extradata = av_buffer_allocz(sz * (1 + sizeof(struct VP9mvrefPair))))) {
+ f->extradata = av_buffer_allocz(sz * (1 + sizeof(VP9mvrefPair)));
+ if (!f->extradata) {
goto fail;
}
f->segmentation_map = f->extradata->data;
- f->mv = (struct VP9mvrefPair *) (f->extradata->data + sz);
+ f->mv = (VP9mvrefPair *) (f->extradata->data + sz);
- if (ctx->hwaccel) {
- const AVHWAccel *hwaccel = ctx->hwaccel;
+ if (avctx->hwaccel) {
+ const AVHWAccel *hwaccel = avctx->hwaccel;
av_assert0(!f->hwaccel_picture_private);
if (hwaccel->frame_priv_data_size) {
f->hwaccel_priv_buf = av_buffer_allocz(hwaccel->frame_priv_data_size);
@@ -212,19 +133,21 @@ static int vp9_alloc_frame(AVCodecContext *ctx, VP9Frame *f)
return 0;
fail:
- vp9_unref_frame(ctx, f);
+ vp9_frame_unref(avctx, f);
return AVERROR(ENOMEM);
}
-static int vp9_ref_frame(AVCodecContext *ctx, VP9Frame *dst, VP9Frame *src)
+static int vp9_frame_ref(AVCodecContext *avctx, VP9Frame *dst, VP9Frame *src)
{
- int res;
+ int ret;
- if ((res = ff_thread_ref_frame(&dst->tf, &src->tf)) < 0) {
- return res;
- } else if (!(dst->extradata = av_buffer_ref(src->extradata))) {
+ ret = ff_thread_ref_frame(&dst->tf, &src->tf);
+ if (ret < 0)
+ return ret;
+
+ dst->extradata = av_buffer_ref(src->extradata);
+ if (!dst->extradata)
goto fail;
- }
dst->segmentation_map = src->segmentation_map;
dst->mv = src->mv;
@@ -240,44 +163,54 @@ static int vp9_ref_frame(AVCodecContext *ctx, VP9Frame *dst, VP9Frame *src)
return 0;
fail:
- vp9_unref_frame(ctx, dst);
+ vp9_frame_unref(avctx, dst);
return AVERROR(ENOMEM);
}
-static int update_size(AVCodecContext *ctx, int w, int h)
+static int update_size(AVCodecContext *avctx, int w, int h)
{
-#define HWACCEL_MAX (CONFIG_VP9_DXVA2_HWACCEL + CONFIG_VP9_D3D11VA_HWACCEL + CONFIG_VP9_VAAPI_HWACCEL)
+#define HWACCEL_MAX (CONFIG_VP9_DXVA2_HWACCEL + CONFIG_VP9_D3D11VA_HWACCEL * 2 + CONFIG_VP9_VAAPI_HWACCEL)
enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmtp = pix_fmts;
- VP9Context *s = ctx->priv_data;
+ VP9Context *s = avctx->priv_data;
uint8_t *p;
- int bytesperpixel = s->bytesperpixel, res, cols, rows;
+ int bytesperpixel = s->bytesperpixel, ret, cols, rows;
+ int lflvl_len, i;
av_assert0(w > 0 && h > 0);
if (!(s->pix_fmt == s->gf_fmt && w == s->w && h == s->h)) {
- if ((res = ff_set_dimensions(ctx, w, h)) < 0)
- return res;
+ if ((ret = ff_set_dimensions(avctx, w, h)) < 0)
+ return ret;
- if (s->pix_fmt == AV_PIX_FMT_YUV420P) {
+ switch (s->pix_fmt) {
+ case AV_PIX_FMT_YUV420P:
#if CONFIG_VP9_DXVA2_HWACCEL
*fmtp++ = AV_PIX_FMT_DXVA2_VLD;
#endif
#if CONFIG_VP9_D3D11VA_HWACCEL
*fmtp++ = AV_PIX_FMT_D3D11VA_VLD;
+ *fmtp++ = AV_PIX_FMT_D3D11;
#endif
#if CONFIG_VP9_VAAPI_HWACCEL
*fmtp++ = AV_PIX_FMT_VAAPI;
#endif
+ break;
+ case AV_PIX_FMT_YUV420P10:
+ case AV_PIX_FMT_YUV420P12:
+#if CONFIG_VP9_VAAPI_HWACCEL
+ *fmtp++ = AV_PIX_FMT_VAAPI;
+#endif
+ break;
}
*fmtp++ = s->pix_fmt;
*fmtp = AV_PIX_FMT_NONE;
- res = ff_thread_get_format(ctx, pix_fmts);
- if (res < 0)
- return res;
+ ret = ff_thread_get_format(avctx, pix_fmts);
+ if (ret < 0)
+ return ret;
- ctx->pix_fmt = res;
+ avctx->pix_fmt = ret;
s->gf_fmt = s->pix_fmt;
s->w = w;
s->h = h;
@@ -294,13 +227,14 @@ static int update_size(AVCodecContext *ctx, int w, int h)
s->sb_rows = (h + 63) >> 6;
s->cols = (w + 7) >> 3;
s->rows = (h + 7) >> 3;
+ lflvl_len = avctx->active_thread_type == FF_THREAD_SLICE ? s->sb_rows : 1;
#define assign(var, type, n) var = (type) p; p += s->sb_cols * (n) * sizeof(*var)
av_freep(&s->intra_pred_data[0]);
// FIXME we slightly over-allocate here for subsampled chroma, but a little
// bit of padding shouldn't affect performance...
p = av_malloc(s->sb_cols * (128 + 192 * bytesperpixel +
- sizeof(*s->lflvl) + 16 * sizeof(*s->above_mv_ctx)));
+ lflvl_len * sizeof(*s->lflvl) + 16 * sizeof(*s->above_mv_ctx)));
if (!p)
return AVERROR(ENOMEM);
assign(s->intra_pred_data[0], uint8_t *, 64 * bytesperpixel);
@@ -319,65 +253,78 @@ static int update_size(AVCodecContext *ctx, int w, int h)
assign(s->above_comp_ctx, uint8_t *, 8);
assign(s->above_ref_ctx, uint8_t *, 8);
assign(s->above_filter_ctx, uint8_t *, 8);
- assign(s->lflvl, struct VP9Filter *, 1);
+ assign(s->lflvl, VP9Filter *, lflvl_len);
#undef assign
- // these will be re-allocated a little later
- av_freep(&s->b_base);
- av_freep(&s->block_base);
+ if (s->td) {
+ for (i = 0; i < s->active_tile_cols; i++) {
+ av_freep(&s->td[i].b_base);
+ av_freep(&s->td[i].block_base);
+ }
+ }
- if (s->bpp != s->last_bpp) {
- ff_vp9dsp_init(&s->dsp, s->bpp, ctx->flags & AV_CODEC_FLAG_BITEXACT);
- ff_videodsp_init(&s->vdsp, s->bpp);
- s->last_bpp = s->bpp;
+ if (s->s.h.bpp != s->last_bpp) {
+ ff_vp9dsp_init(&s->dsp, s->s.h.bpp, avctx->flags & AV_CODEC_FLAG_BITEXACT);
+ ff_videodsp_init(&s->vdsp, s->s.h.bpp);
+ s->last_bpp = s->s.h.bpp;
}
return 0;
}
-static int update_block_buffers(AVCodecContext *ctx)
+static int update_block_buffers(AVCodecContext *avctx)
{
- VP9Context *s = ctx->priv_data;
+ int i;
+ VP9Context *s = avctx->priv_data;
int chroma_blocks, chroma_eobs, bytesperpixel = s->bytesperpixel;
+ VP9TileData *td = &s->td[0];
- if (s->b_base && s->block_base && s->block_alloc_using_2pass == s->s.frames[CUR_FRAME].uses_2pass)
+ if (td->b_base && td->block_base && s->block_alloc_using_2pass == s->s.frames[CUR_FRAME].uses_2pass)
return 0;
- av_free(s->b_base);
- av_free(s->block_base);
+ av_free(td->b_base);
+ av_free(td->block_base);
chroma_blocks = 64 * 64 >> (s->ss_h + s->ss_v);
chroma_eobs = 16 * 16 >> (s->ss_h + s->ss_v);
if (s->s.frames[CUR_FRAME].uses_2pass) {
int sbs = s->sb_cols * s->sb_rows;
- s->b_base = av_malloc_array(s->cols * s->rows, sizeof(VP9Block));
- s->block_base = av_mallocz(((64 * 64 + 2 * chroma_blocks) * bytesperpixel * sizeof(int16_t) +
+ td->b_base = av_malloc_array(s->cols * s->rows, sizeof(VP9Block));
+ td->block_base = av_mallocz(((64 * 64 + 2 * chroma_blocks) * bytesperpixel * sizeof(int16_t) +
16 * 16 + 2 * chroma_eobs) * sbs);
- if (!s->b_base || !s->block_base)
+ if (!td->b_base || !td->block_base)
return AVERROR(ENOMEM);
- s->uvblock_base[0] = s->block_base + sbs * 64 * 64 * bytesperpixel;
- s->uvblock_base[1] = s->uvblock_base[0] + sbs * chroma_blocks * bytesperpixel;
- s->eob_base = (uint8_t *) (s->uvblock_base[1] + sbs * chroma_blocks * bytesperpixel);
- s->uveob_base[0] = s->eob_base + 16 * 16 * sbs;
- s->uveob_base[1] = s->uveob_base[0] + chroma_eobs * sbs;
+ td->uvblock_base[0] = td->block_base + sbs * 64 * 64 * bytesperpixel;
+ td->uvblock_base[1] = td->uvblock_base[0] + sbs * chroma_blocks * bytesperpixel;
+ td->eob_base = (uint8_t *) (td->uvblock_base[1] + sbs * chroma_blocks * bytesperpixel);
+ td->uveob_base[0] = td->eob_base + 16 * 16 * sbs;
+ td->uveob_base[1] = td->uveob_base[0] + chroma_eobs * sbs;
} else {
- s->b_base = av_malloc(sizeof(VP9Block));
- s->block_base = av_mallocz((64 * 64 + 2 * chroma_blocks) * bytesperpixel * sizeof(int16_t) +
- 16 * 16 + 2 * chroma_eobs);
- if (!s->b_base || !s->block_base)
- return AVERROR(ENOMEM);
- s->uvblock_base[0] = s->block_base + 64 * 64 * bytesperpixel;
- s->uvblock_base[1] = s->uvblock_base[0] + chroma_blocks * bytesperpixel;
- s->eob_base = (uint8_t *) (s->uvblock_base[1] + chroma_blocks * bytesperpixel);
- s->uveob_base[0] = s->eob_base + 16 * 16;
- s->uveob_base[1] = s->uveob_base[0] + chroma_eobs;
+ for (i = 1; i < s->active_tile_cols; i++) {
+ if (s->td[i].b_base && s->td[i].block_base) {
+ av_free(s->td[i].b_base);
+ av_free(s->td[i].block_base);
+ }
+ }
+ for (i = 0; i < s->active_tile_cols; i++) {
+ s->td[i].b_base = av_malloc(sizeof(VP9Block));
+ s->td[i].block_base = av_mallocz((64 * 64 + 2 * chroma_blocks) * bytesperpixel * sizeof(int16_t) +
+ 16 * 16 + 2 * chroma_eobs);
+ if (!s->td[i].b_base || !s->td[i].block_base)
+ return AVERROR(ENOMEM);
+ s->td[i].uvblock_base[0] = s->td[i].block_base + 64 * 64 * bytesperpixel;
+ s->td[i].uvblock_base[1] = s->td[i].uvblock_base[0] + chroma_blocks * bytesperpixel;
+ s->td[i].eob_base = (uint8_t *) (s->td[i].uvblock_base[1] + chroma_blocks * bytesperpixel);
+ s->td[i].uveob_base[0] = s->td[i].eob_base + 16 * 16;
+ s->td[i].uveob_base[1] = s->td[i].uveob_base[0] + chroma_eobs;
+ }
}
s->block_alloc_using_2pass = s->s.frames[CUR_FRAME].uses_2pass;
return 0;
}
-// for some reason the sign bit is at the end, not the start, of a bit sequence
+// The sign bit is at the end, not the start, of a bit sequence
static av_always_inline int get_sbits_inv(GetBitContext *gb, int n)
{
int v = get_bits(gb, n);
@@ -386,7 +333,11 @@ static av_always_inline int get_sbits_inv(GetBitContext *gb, int n)
static av_always_inline int inv_recenter_nonneg(int v, int m)
{
- return v > 2 * m ? v : v & 1 ? m - ((v + 1) >> 1) : m + (v >> 1);
+ if (v > 2 * m)
+ return v;
+ if (v & 1)
+ return m - ((v + 1) >> 1);
+ return m + (v >> 1);
}
// differential forward probability updates
@@ -417,13 +368,13 @@ static int update_prob(VP56RangeCoder *c, int p)
/* This code is trying to do a differential probability update. For a
* current probability A in the range [1, 255], the difference to a new
- * probability of any value can be expressed differentially as 1-A,255-A
+ * probability of any value can be expressed differentially as 1-A, 255-A
* where some part of this (absolute range) exists both in positive as
* well as the negative part, whereas another part only exists in one
* half. We're trying to code this shared part differentially, i.e.
* times two where the value of the lowest bit specifies the sign, and
* the single part is then coded on top of this. This absolute difference
- * then again has a value of [0,254], but a bigger value in this range
+ * then again has a value of [0, 254], but a bigger value in this range
* indicates that we're further away from the original value A, so we
* can code this as a VLC code, since higher values are increasingly
* unlikely. The first 20 values in inv_map_table[] allow 'cheap, rough'
@@ -448,34 +399,34 @@ static int update_prob(VP56RangeCoder *c, int p)
255 - inv_recenter_nonneg(inv_map_table[d], 255 - p);
}
-static int read_colorspace_details(AVCodecContext *ctx)
+static int read_colorspace_details(AVCodecContext *avctx)
{
static const enum AVColorSpace colorspaces[8] = {
AVCOL_SPC_UNSPECIFIED, AVCOL_SPC_BT470BG, AVCOL_SPC_BT709, AVCOL_SPC_SMPTE170M,
AVCOL_SPC_SMPTE240M, AVCOL_SPC_BT2020_NCL, AVCOL_SPC_RESERVED, AVCOL_SPC_RGB,
};
- VP9Context *s = ctx->priv_data;
- int bits = ctx->profile <= 1 ? 0 : 1 + get_bits1(&s->gb); // 0:8, 1:10, 2:12
+ VP9Context *s = avctx->priv_data;
+ int bits = avctx->profile <= 1 ? 0 : 1 + get_bits1(&s->gb); // 0:8, 1:10, 2:12
s->bpp_index = bits;
- s->bpp = 8 + bits * 2;
- s->bytesperpixel = (7 + s->bpp) >> 3;
- ctx->colorspace = colorspaces[get_bits(&s->gb, 3)];
- if (ctx->colorspace == AVCOL_SPC_RGB) { // RGB = profile 1
+ s->s.h.bpp = 8 + bits * 2;
+ s->bytesperpixel = (7 + s->s.h.bpp) >> 3;
+ avctx->colorspace = colorspaces[get_bits(&s->gb, 3)];
+ if (avctx->colorspace == AVCOL_SPC_RGB) { // RGB = profile 1
static const enum AVPixelFormat pix_fmt_rgb[3] = {
AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12
};
s->ss_h = s->ss_v = 0;
- ctx->color_range = AVCOL_RANGE_JPEG;
+ avctx->color_range = AVCOL_RANGE_JPEG;
s->pix_fmt = pix_fmt_rgb[bits];
- if (ctx->profile & 1) {
+ if (avctx->profile & 1) {
if (get_bits1(&s->gb)) {
- av_log(ctx, AV_LOG_ERROR, "Reserved bit set in RGB\n");
+ av_log(avctx, AV_LOG_ERROR, "Reserved bit set in RGB\n");
return AVERROR_INVALIDDATA;
}
} else {
- av_log(ctx, AV_LOG_ERROR, "RGB not supported in profile %d\n",
- ctx->profile);
+ av_log(avctx, AV_LOG_ERROR, "RGB not supported in profile %d\n",
+ avctx->profile);
return AVERROR_INVALIDDATA;
}
} else {
@@ -487,18 +438,18 @@ static int read_colorspace_details(AVCodecContext *ctx)
{ { AV_PIX_FMT_YUV444P12, AV_PIX_FMT_YUV422P12 },
{ AV_PIX_FMT_YUV440P12, AV_PIX_FMT_YUV420P12 } }
};
- ctx->color_range = get_bits1(&s->gb) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
- if (ctx->profile & 1) {
+ avctx->color_range = get_bits1(&s->gb) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
+ if (avctx->profile & 1) {
s->ss_h = get_bits1(&s->gb);
s->ss_v = get_bits1(&s->gb);
s->pix_fmt = pix_fmt_for_ss[bits][s->ss_v][s->ss_h];
if (s->pix_fmt == AV_PIX_FMT_YUV420P) {
- av_log(ctx, AV_LOG_ERROR, "YUV 4:2:0 not supported in profile %d\n",
- ctx->profile);
+ av_log(avctx, AV_LOG_ERROR, "YUV 4:2:0 not supported in profile %d\n",
+ avctx->profile);
return AVERROR_INVALIDDATA;
} else if (get_bits1(&s->gb)) {
- av_log(ctx, AV_LOG_ERROR, "Profile %d color details reserved bit set\n",
- ctx->profile);
+ av_log(avctx, AV_LOG_ERROR, "Profile %d color details reserved bit set\n",
+ avctx->profile);
return AVERROR_INVALIDDATA;
}
} else {
@@ -510,48 +461,51 @@ static int read_colorspace_details(AVCodecContext *ctx)
return 0;
}
-static int decode_frame_header(AVCodecContext *ctx,
+static int decode_frame_header(AVCodecContext *avctx,
const uint8_t *data, int size, int *ref)
{
- VP9Context *s = ctx->priv_data;
- int c, i, j, k, l, m, n, w, h, max, size2, res, sharp;
+ VP9Context *s = avctx->priv_data;
+ int c, i, j, k, l, m, n, w, h, max, size2, ret, sharp;
int last_invisible;
const uint8_t *data2;
/* general header */
- if ((res = init_get_bits8(&s->gb, data, size)) < 0) {
- av_log(ctx, AV_LOG_ERROR, "Failed to initialize bitstream reader\n");
- return res;
+ if ((ret = init_get_bits8(&s->gb, data, size)) < 0) {
+ av_log(avctx, AV_LOG_ERROR, "Failed to initialize bitstream reader\n");
+ return ret;
}
if (get_bits(&s->gb, 2) != 0x2) { // frame marker
- av_log(ctx, AV_LOG_ERROR, "Invalid frame marker\n");
+ av_log(avctx, AV_LOG_ERROR, "Invalid frame marker\n");
return AVERROR_INVALIDDATA;
}
- ctx->profile = get_bits1(&s->gb);
- ctx->profile |= get_bits1(&s->gb) << 1;
- if (ctx->profile == 3) ctx->profile += get_bits1(&s->gb);
- if (ctx->profile > 3) {
- av_log(ctx, AV_LOG_ERROR, "Profile %d is not yet supported\n", ctx->profile);
+ avctx->profile = get_bits1(&s->gb);
+ avctx->profile |= get_bits1(&s->gb) << 1;
+ if (avctx->profile == 3) avctx->profile += get_bits1(&s->gb);
+ if (avctx->profile > 3) {
+ av_log(avctx, AV_LOG_ERROR, "Profile %d is not yet supported\n", avctx->profile);
return AVERROR_INVALIDDATA;
}
- s->s.h.profile = ctx->profile;
+ s->s.h.profile = avctx->profile;
if (get_bits1(&s->gb)) {
*ref = get_bits(&s->gb, 3);
return 0;
}
+
s->last_keyframe = s->s.h.keyframe;
- s->s.h.keyframe = !get_bits1(&s->gb);
- last_invisible = s->s.h.invisible;
- s->s.h.invisible = !get_bits1(&s->gb);
- s->s.h.errorres = get_bits1(&s->gb);
+ s->s.h.keyframe = !get_bits1(&s->gb);
+
+ last_invisible = s->s.h.invisible;
+ s->s.h.invisible = !get_bits1(&s->gb);
+ s->s.h.errorres = get_bits1(&s->gb);
s->s.h.use_last_frame_mvs = !s->s.h.errorres && !last_invisible;
+
if (s->s.h.keyframe) {
if (get_bits_long(&s->gb, 24) != VP9_SYNCCODE) { // synccode
- av_log(ctx, AV_LOG_ERROR, "Invalid sync code\n");
+ av_log(avctx, AV_LOG_ERROR, "Invalid sync code\n");
return AVERROR_INVALIDDATA;
}
- if ((res = read_colorspace_details(ctx)) < 0)
- return res;
+ if ((ret = read_colorspace_details(avctx)) < 0)
+ return ret;
// for profile 1, here follows the subsampling bits
s->s.h.refreshrefmask = 0xff;
w = get_bits(&s->gb, 16) + 1;
@@ -559,24 +513,24 @@ static int decode_frame_header(AVCodecContext *ctx,
if (get_bits1(&s->gb)) // display size
skip_bits(&s->gb, 32);
} else {
- s->s.h.intraonly = s->s.h.invisible ? get_bits1(&s->gb) : 0;
- s->s.h.resetctx = s->s.h.errorres ? 0 : get_bits(&s->gb, 2);
+ s->s.h.intraonly = s->s.h.invisible ? get_bits1(&s->gb) : 0;
+ s->s.h.resetctx = s->s.h.errorres ? 0 : get_bits(&s->gb, 2);
if (s->s.h.intraonly) {
if (get_bits_long(&s->gb, 24) != VP9_SYNCCODE) { // synccode
- av_log(ctx, AV_LOG_ERROR, "Invalid sync code\n");
+ av_log(avctx, AV_LOG_ERROR, "Invalid sync code\n");
return AVERROR_INVALIDDATA;
}
- if (ctx->profile >= 1) {
- if ((res = read_colorspace_details(ctx)) < 0)
- return res;
+ if (avctx->profile >= 1) {
+ if ((ret = read_colorspace_details(avctx)) < 0)
+ return ret;
} else {
s->ss_h = s->ss_v = 1;
- s->bpp = 8;
+ s->s.h.bpp = 8;
s->bpp_index = 0;
s->bytesperpixel = 1;
s->pix_fmt = AV_PIX_FMT_YUV420P;
- ctx->colorspace = AVCOL_SPC_BT470BG;
- ctx->color_range = AVCOL_RANGE_JPEG;
+ avctx->colorspace = AVCOL_SPC_BT470BG;
+ avctx->color_range = AVCOL_RANGE_MPEG;
}
s->s.h.refreshrefmask = get_bits(&s->gb, 8);
w = get_bits(&s->gb, 16) + 1;
@@ -594,7 +548,7 @@ static int decode_frame_header(AVCodecContext *ctx,
if (!s->s.refs[s->s.h.refidx[0]].f->buf[0] ||
!s->s.refs[s->s.h.refidx[1]].f->buf[0] ||
!s->s.refs[s->s.h.refidx[2]].f->buf[0]) {
- av_log(ctx, AV_LOG_ERROR, "Not all references are available\n");
+ av_log(avctx, AV_LOG_ERROR, "Not all references are available\n");
return AVERROR_INVALIDDATA;
}
if (get_bits1(&s->gb)) {
@@ -660,8 +614,20 @@ static int decode_frame_header(AVCodecContext *ctx,
sharp = get_bits(&s->gb, 3);
// if sharpness changed, reinit lim/mblim LUTs. if it didn't change, keep
// the old cache values since they are still valid
- if (s->s.h.filter.sharpness != sharp)
- memset(s->filter_lut.lim_lut, 0, sizeof(s->filter_lut.lim_lut));
+ if (s->s.h.filter.sharpness != sharp) {
+ for (i = 1; i <= 63; i++) {
+ int limit = i;
+
+ if (sharp > 0) {
+ limit >>= (sharp + 3) >> 2;
+ limit = FFMIN(limit, 9 - sharp);
+ }
+ limit = FFMAX(limit, 1);
+
+ s->filter_lut.lim_lut[i] = limit;
+ s->filter_lut.mblim_lut[i] = 2 * (i + 2) + limit;
+ }
+ }
s->s.h.filter.sharpness = sharp;
if ((s->s.h.lf_delta.enabled = get_bits1(&s->gb))) {
if ((s->s.h.lf_delta.updated = get_bits1(&s->gb))) {
@@ -682,7 +648,7 @@ static int decode_frame_header(AVCodecContext *ctx,
s->s.h.lossless = s->s.h.yac_qi == 0 && s->s.h.ydc_qdelta == 0 &&
s->s.h.uvdc_qdelta == 0 && s->s.h.uvac_qdelta == 0;
if (s->s.h.lossless)
- ctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
+ avctx->properties |= FF_CODEC_PROPERTY_LOSSLESS;
/* segmentation header info */
if ((s->s.h.segmentation.enabled = get_bits1(&s->gb))) {
@@ -690,11 +656,10 @@ static int decode_frame_header(AVCodecContext *ctx,
for (i = 0; i < 7; i++)
s->s.h.segmentation.prob[i] = get_bits1(&s->gb) ?
get_bits(&s->gb, 8) : 255;
- if ((s->s.h.segmentation.temporal = get_bits1(&s->gb))) {
+ if ((s->s.h.segmentation.temporal = get_bits1(&s->gb)))
for (i = 0; i < 3; i++)
s->s.h.segmentation.pred_prob[i] = get_bits1(&s->gb) ?
get_bits(&s->gb, 8) : 255;
- }
}
if (get_bits1(&s->gb)) {
@@ -728,10 +693,10 @@ static int decode_frame_header(AVCodecContext *ctx,
quvac = av_clip_uintp2(qyac + s->s.h.uvac_qdelta, 8);
qyac = av_clip_uintp2(qyac, 8);
- s->s.h.segmentation.feat[i].qmul[0][0] = vp9_dc_qlookup[s->bpp_index][qydc];
- s->s.h.segmentation.feat[i].qmul[0][1] = vp9_ac_qlookup[s->bpp_index][qyac];
- s->s.h.segmentation.feat[i].qmul[1][0] = vp9_dc_qlookup[s->bpp_index][quvdc];
- s->s.h.segmentation.feat[i].qmul[1][1] = vp9_ac_qlookup[s->bpp_index][quvac];
+ s->s.h.segmentation.feat[i].qmul[0][0] = ff_vp9_dc_qlookup[s->bpp_index][qydc];
+ s->s.h.segmentation.feat[i].qmul[0][1] = ff_vp9_ac_qlookup[s->bpp_index][qyac];
+ s->s.h.segmentation.feat[i].qmul[1][0] = ff_vp9_dc_qlookup[s->bpp_index][quvdc];
+ s->s.h.segmentation.feat[i].qmul[1][1] = ff_vp9_ac_qlookup[s->bpp_index][quvac];
sh = s->s.h.filter.level >= 32;
if (s->s.h.segmentation.enabled && s->s.h.segmentation.feat[i].lf_enabled) {
@@ -761,10 +726,10 @@ static int decode_frame_header(AVCodecContext *ctx,
}
/* tiling info */
- if ((res = update_size(ctx, w, h)) < 0) {
- av_log(ctx, AV_LOG_ERROR, "Failed to initialize decoder for %dx%d @ %d\n",
+ if ((ret = update_size(avctx, w, h)) < 0) {
+ av_log(avctx, AV_LOG_ERROR, "Failed to initialize decoder for %dx%d @ %d\n",
w, h, s->pix_fmt);
- return res;
+ return ret;
}
for (s->s.h.tiling.log2_tile_cols = 0;
s->sb_cols > (64 << s->s.h.tiling.log2_tile_cols);
@@ -780,12 +745,36 @@ static int decode_frame_header(AVCodecContext *ctx,
s->s.h.tiling.log2_tile_rows = decode012(&s->gb);
s->s.h.tiling.tile_rows = 1 << s->s.h.tiling.log2_tile_rows;
if (s->s.h.tiling.tile_cols != (1 << s->s.h.tiling.log2_tile_cols)) {
+ int n_range_coders;
+ VP56RangeCoder *rc;
+
+ if (s->td) {
+ for (i = 0; i < s->active_tile_cols; i++) {
+ av_free(s->td[i].b_base);
+ av_free(s->td[i].block_base);
+ }
+ av_free(s->td);
+ }
+
s->s.h.tiling.tile_cols = 1 << s->s.h.tiling.log2_tile_cols;
- s->c_b = av_fast_realloc(s->c_b, &s->c_b_size,
- sizeof(VP56RangeCoder) * s->s.h.tiling.tile_cols);
- if (!s->c_b) {
- av_log(ctx, AV_LOG_ERROR, "Ran out of memory during range coder init\n");
+ vp9_free_entries(avctx);
+ s->active_tile_cols = avctx->active_thread_type == FF_THREAD_SLICE ?
+ s->s.h.tiling.tile_cols : 1;
+ vp9_alloc_entries(avctx, s->sb_rows);
+ if (avctx->active_thread_type == FF_THREAD_SLICE) {
+ n_range_coders = 4; // max_tile_rows
+ } else {
+ n_range_coders = s->s.h.tiling.tile_cols;
+ }
+ s->td = av_mallocz_array(s->active_tile_cols, sizeof(VP9TileData) +
+ n_range_coders * sizeof(VP56RangeCoder));
+ if (!s->td)
return AVERROR(ENOMEM);
+ rc = (VP56RangeCoder *) &s->td[s->active_tile_cols];
+ for (i = 0; i < s->active_tile_cols; i++) {
+ s->td[i].s = s;
+ s->td[i].c_b = rc;
+ rc += n_range_coders;
}
}
@@ -795,17 +784,17 @@ static int decode_frame_header(AVCodecContext *ctx,
AVFrame *ref = s->s.refs[s->s.h.refidx[i]].f;
int refw = ref->width, refh = ref->height;
- if (ref->format != ctx->pix_fmt) {
- av_log(ctx, AV_LOG_ERROR,
+ if (ref->format != avctx->pix_fmt) {
+ av_log(avctx, AV_LOG_ERROR,
"Ref pixfmt (%s) did not match current frame (%s)",
av_get_pix_fmt_name(ref->format),
- av_get_pix_fmt_name(ctx->pix_fmt));
+ av_get_pix_fmt_name(avctx->pix_fmt));
return AVERROR_INVALIDDATA;
} else if (refw == w && refh == h) {
s->mvscale[i][0] = s->mvscale[i][1] = 0;
} else {
if (w * 2 < refw || h * 2 < refh || w > 16 * refw || h > 16 * refh) {
- av_log(ctx, AV_LOG_ERROR,
+ av_log(avctx, AV_LOG_ERROR,
"Invalid ref frame dimensions %dx%d for frame size %dx%d\n",
refw, refh, w, h);
return AVERROR_INVALIDDATA;
@@ -820,19 +809,19 @@ static int decode_frame_header(AVCodecContext *ctx,
if (s->s.h.keyframe || s->s.h.errorres || (s->s.h.intraonly && s->s.h.resetctx == 3)) {
s->prob_ctx[0].p = s->prob_ctx[1].p = s->prob_ctx[2].p =
- s->prob_ctx[3].p = vp9_default_probs;
- memcpy(s->prob_ctx[0].coef, vp9_default_coef_probs,
- sizeof(vp9_default_coef_probs));
- memcpy(s->prob_ctx[1].coef, vp9_default_coef_probs,
- sizeof(vp9_default_coef_probs));
- memcpy(s->prob_ctx[2].coef, vp9_default_coef_probs,
- sizeof(vp9_default_coef_probs));
- memcpy(s->prob_ctx[3].coef, vp9_default_coef_probs,
- sizeof(vp9_default_coef_probs));
+ s->prob_ctx[3].p = ff_vp9_default_probs;
+ memcpy(s->prob_ctx[0].coef, ff_vp9_default_coef_probs,
+ sizeof(ff_vp9_default_coef_probs));
+ memcpy(s->prob_ctx[1].coef, ff_vp9_default_coef_probs,
+ sizeof(ff_vp9_default_coef_probs));
+ memcpy(s->prob_ctx[2].coef, ff_vp9_default_coef_probs,
+ sizeof(ff_vp9_default_coef_probs));
+ memcpy(s->prob_ctx[3].coef, ff_vp9_default_coef_probs,
+ sizeof(ff_vp9_default_coef_probs));
} else if (s->s.h.intraonly && s->s.h.resetctx == 2) {
- s->prob_ctx[c].p = vp9_default_probs;
- memcpy(s->prob_ctx[c].coef, vp9_default_coef_probs,
- sizeof(vp9_default_coef_probs));
+ s->prob_ctx[c].p = ff_vp9_default_probs;
+ memcpy(s->prob_ctx[c].coef, ff_vp9_default_coef_probs,
+ sizeof(ff_vp9_default_coef_probs));
}
// next 16 bits is size of the rest of the header (arith-coded)
@@ -841,24 +830,30 @@ static int decode_frame_header(AVCodecContext *ctx,
data2 = align_get_bits(&s->gb);
if (size2 > size - (data2 - data)) {
- av_log(ctx, AV_LOG_ERROR, "Invalid compressed header size\n");
+ av_log(avctx, AV_LOG_ERROR, "Invalid compressed header size\n");
return AVERROR_INVALIDDATA;
}
- ff_vp56_init_range_decoder(&s->c, data2, size2);
+ ret = ff_vp56_init_range_decoder(&s->c, data2, size2);
+ if (ret < 0)
+ return ret;
+
if (vp56_rac_get_prob_branchy(&s->c, 128)) { // marker bit
- av_log(ctx, AV_LOG_ERROR, "Marker bit was set\n");
+ av_log(avctx, AV_LOG_ERROR, "Marker bit was set\n");
return AVERROR_INVALIDDATA;
}
- if (s->s.h.keyframe || s->s.h.intraonly) {
- memset(s->counts.coef, 0, sizeof(s->counts.coef));
- memset(s->counts.eob, 0, sizeof(s->counts.eob));
- } else {
- memset(&s->counts, 0, sizeof(s->counts));
+ for (i = 0; i < s->active_tile_cols; i++) {
+ if (s->s.h.keyframe || s->s.h.intraonly) {
+ memset(s->td[i].counts.coef, 0, sizeof(s->td[0].counts.coef));
+ memset(s->td[i].counts.eob, 0, sizeof(s->td[0].counts.eob));
+ } else {
+ memset(&s->td[i].counts, 0, sizeof(s->td[0].counts));
+ }
}
- // FIXME is it faster to not copy here, but do it down in the fw updates
- // as explicit copies if the fw update is missing (and skip the copy upon
- // fw update)?
+
+ /* FIXME is it faster to not copy here, but do it down in the fw updates
+ * as explicit copies if the fw update is missing (and skip the copy upon
+ * fw update)? */
s->prob.p = s->prob_ctx[c].p;
// txfm updates
@@ -899,13 +894,12 @@ static int decode_frame_header(AVCodecContext *ctx,
if (m >= 3 && l == 0) // dc only has 3 pt
break;
for (n = 0; n < 3; n++) {
- if (vp56_rac_get_prob_branchy(&s->c, 252)) {
+ if (vp56_rac_get_prob_branchy(&s->c, 252))
p[n] = update_prob(&s->c, r[n]);
- } else {
+ else
p[n] = r[n];
- }
}
- p[3] = 0;
+ memcpy(&p[3], ff_vp9_model_pareto8[p[2]], 8);
}
} else {
for (j = 0; j < 2; j++)
@@ -917,7 +911,7 @@ static int decode_frame_header(AVCodecContext *ctx,
if (m > 3 && l == 0) // dc only has 3 pt
break;
memcpy(p, r, 3);
- p[3] = 0;
+ memcpy(&p[3], ff_vp9_model_pareto8[p[2]], 8);
}
}
if (s->s.h.txfmmode == i)
@@ -988,7 +982,8 @@ static int decode_frame_header(AVCodecContext *ctx,
for (k = 0; k < 3; k++)
if (vp56_rac_get_prob_branchy(&s->c, 252))
s->prob.p.partition[3 - i][j][k] =
- update_prob(&s->c, s->prob.p.partition[3 - i][j][k]);
+ update_prob(&s->c,
+ s->prob.p.partition[3 - i][j][k]);
// mv fields don't use the update_prob subexp model for some reason
for (i = 0; i < 3; i++)
@@ -997,7 +992,8 @@ static int decode_frame_header(AVCodecContext *ctx,
for (i = 0; i < 2; i++) {
if (vp56_rac_get_prob_branchy(&s->c, 252))
- s->prob.p.mv_comp[i].sign = (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
+ s->prob.p.mv_comp[i].sign =
+ (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
for (j = 0; j < 10; j++)
if (vp56_rac_get_prob_branchy(&s->c, 252))
@@ -1005,7 +1001,8 @@ static int decode_frame_header(AVCodecContext *ctx,
(vp8_rac_get_uint(&s->c, 7) << 1) | 1;
if (vp56_rac_get_prob_branchy(&s->c, 252))
- s->prob.p.mv_comp[i].class0 = (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
+ s->prob.p.mv_comp[i].class0 =
+ (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
for (j = 0; j < 10; j++)
if (vp56_rac_get_prob_branchy(&s->c, 252))
@@ -1042,2354 +1039,13 @@ static int decode_frame_header(AVCodecContext *ctx,
return (data2 - data) + size2;
}
-static av_always_inline void clamp_mv(VP56mv *dst, const VP56mv *src,
- VP9Context *s)
-{
- dst->x = av_clip(src->x, s->min_mv.x, s->max_mv.x);
- dst->y = av_clip(src->y, s->min_mv.y, s->max_mv.y);
-}
-
-static void find_ref_mvs(VP9Context *s,
- VP56mv *pmv, int ref, int z, int idx, int sb)
-{
- static const int8_t mv_ref_blk_off[N_BS_SIZES][8][2] = {
- [BS_64x64] = {{ 3, -1 }, { -1, 3 }, { 4, -1 }, { -1, 4 },
- { -1, -1 }, { 0, -1 }, { -1, 0 }, { 6, -1 }},
- [BS_64x32] = {{ 0, -1 }, { -1, 0 }, { 4, -1 }, { -1, 2 },
- { -1, -1 }, { 0, -3 }, { -3, 0 }, { 2, -1 }},
- [BS_32x64] = {{ -1, 0 }, { 0, -1 }, { -1, 4 }, { 2, -1 },
- { -1, -1 }, { -3, 0 }, { 0, -3 }, { -1, 2 }},
- [BS_32x32] = {{ 1, -1 }, { -1, 1 }, { 2, -1 }, { -1, 2 },
- { -1, -1 }, { 0, -3 }, { -3, 0 }, { -3, -3 }},
- [BS_32x16] = {{ 0, -1 }, { -1, 0 }, { 2, -1 }, { -1, -1 },
- { -1, 1 }, { 0, -3 }, { -3, 0 }, { -3, -3 }},
- [BS_16x32] = {{ -1, 0 }, { 0, -1 }, { -1, 2 }, { -1, -1 },
- { 1, -1 }, { -3, 0 }, { 0, -3 }, { -3, -3 }},
- [BS_16x16] = {{ 0, -1 }, { -1, 0 }, { 1, -1 }, { -1, 1 },
- { -1, -1 }, { 0, -3 }, { -3, 0 }, { -3, -3 }},
- [BS_16x8] = {{ 0, -1 }, { -1, 0 }, { 1, -1 }, { -1, -1 },
- { 0, -2 }, { -2, 0 }, { -2, -1 }, { -1, -2 }},
- [BS_8x16] = {{ -1, 0 }, { 0, -1 }, { -1, 1 }, { -1, -1 },
- { -2, 0 }, { 0, -2 }, { -1, -2 }, { -2, -1 }},
- [BS_8x8] = {{ 0, -1 }, { -1, 0 }, { -1, -1 }, { 0, -2 },
- { -2, 0 }, { -1, -2 }, { -2, -1 }, { -2, -2 }},
- [BS_8x4] = {{ 0, -1 }, { -1, 0 }, { -1, -1 }, { 0, -2 },
- { -2, 0 }, { -1, -2 }, { -2, -1 }, { -2, -2 }},
- [BS_4x8] = {{ 0, -1 }, { -1, 0 }, { -1, -1 }, { 0, -2 },
- { -2, 0 }, { -1, -2 }, { -2, -1 }, { -2, -2 }},
- [BS_4x4] = {{ 0, -1 }, { -1, 0 }, { -1, -1 }, { 0, -2 },
- { -2, 0 }, { -1, -2 }, { -2, -1 }, { -2, -2 }},
- };
- VP9Block *b = s->b;
- int row = s->row, col = s->col, row7 = s->row7;
- const int8_t (*p)[2] = mv_ref_blk_off[b->bs];
-#define INVALID_MV 0x80008000U
- uint32_t mem = INVALID_MV, mem_sub8x8 = INVALID_MV;
- int i;
-
-#define RETURN_DIRECT_MV(mv) \
- do { \
- uint32_t m = AV_RN32A(&mv); \
- if (!idx) { \
- AV_WN32A(pmv, m); \
- return; \
- } else if (mem == INVALID_MV) { \
- mem = m; \
- } else if (m != mem) { \
- AV_WN32A(pmv, m); \
- return; \
- } \
- } while (0)
-
- if (sb >= 0) {
- if (sb == 2 || sb == 1) {
- RETURN_DIRECT_MV(b->mv[0][z]);
- } else if (sb == 3) {
- RETURN_DIRECT_MV(b->mv[2][z]);
- RETURN_DIRECT_MV(b->mv[1][z]);
- RETURN_DIRECT_MV(b->mv[0][z]);
- }
-
-#define RETURN_MV(mv) \
- do { \
- if (sb > 0) { \
- VP56mv tmp; \
- uint32_t m; \
- av_assert2(idx == 1); \
- av_assert2(mem != INVALID_MV); \
- if (mem_sub8x8 == INVALID_MV) { \
- clamp_mv(&tmp, &mv, s); \
- m = AV_RN32A(&tmp); \
- if (m != mem) { \
- AV_WN32A(pmv, m); \
- return; \
- } \
- mem_sub8x8 = AV_RN32A(&mv); \
- } else if (mem_sub8x8 != AV_RN32A(&mv)) { \
- clamp_mv(&tmp, &mv, s); \
- m = AV_RN32A(&tmp); \
- if (m != mem) { \
- AV_WN32A(pmv, m); \
- } else { \
- /* BUG I'm pretty sure this isn't the intention */ \
- AV_WN32A(pmv, 0); \
- } \
- return; \
- } \
- } else { \
- uint32_t m = AV_RN32A(&mv); \
- if (!idx) { \
- clamp_mv(pmv, &mv, s); \
- return; \
- } else if (mem == INVALID_MV) { \
- mem = m; \
- } else if (m != mem) { \
- clamp_mv(pmv, &mv, s); \
- return; \
- } \
- } \
- } while (0)
-
- if (row > 0) {
- struct VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[(row - 1) * s->sb_cols * 8 + col];
- if (mv->ref[0] == ref) {
- RETURN_MV(s->above_mv_ctx[2 * col + (sb & 1)][0]);
- } else if (mv->ref[1] == ref) {
- RETURN_MV(s->above_mv_ctx[2 * col + (sb & 1)][1]);
- }
- }
- if (col > s->tile_col_start) {
- struct VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[row * s->sb_cols * 8 + col - 1];
- if (mv->ref[0] == ref) {
- RETURN_MV(s->left_mv_ctx[2 * row7 + (sb >> 1)][0]);
- } else if (mv->ref[1] == ref) {
- RETURN_MV(s->left_mv_ctx[2 * row7 + (sb >> 1)][1]);
- }
- }
- i = 2;
- } else {
- i = 0;
- }
-
- // previously coded MVs in this neighbourhood, using same reference frame
- for (; i < 8; i++) {
- int c = p[i][0] + col, r = p[i][1] + row;
-
- if (c >= s->tile_col_start && c < s->cols && r >= 0 && r < s->rows) {
- struct VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[r * s->sb_cols * 8 + c];
-
- if (mv->ref[0] == ref) {
- RETURN_MV(mv->mv[0]);
- } else if (mv->ref[1] == ref) {
- RETURN_MV(mv->mv[1]);
- }
- }
- }
-
- // MV at this position in previous frame, using same reference frame
- if (s->s.h.use_last_frame_mvs) {
- struct VP9mvrefPair *mv = &s->s.frames[REF_FRAME_MVPAIR].mv[row * s->sb_cols * 8 + col];
-
- if (!s->s.frames[REF_FRAME_MVPAIR].uses_2pass)
- ff_thread_await_progress(&s->s.frames[REF_FRAME_MVPAIR].tf, row >> 3, 0);
- if (mv->ref[0] == ref) {
- RETURN_MV(mv->mv[0]);
- } else if (mv->ref[1] == ref) {
- RETURN_MV(mv->mv[1]);
- }
- }
-
-#define RETURN_SCALE_MV(mv, scale) \
- do { \
- if (scale) { \
- VP56mv mv_temp = { -mv.x, -mv.y }; \
- RETURN_MV(mv_temp); \
- } else { \
- RETURN_MV(mv); \
- } \
- } while (0)
-
- // previously coded MVs in this neighbourhood, using different reference frame
- for (i = 0; i < 8; i++) {
- int c = p[i][0] + col, r = p[i][1] + row;
-
- if (c >= s->tile_col_start && c < s->cols && r >= 0 && r < s->rows) {
- struct VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[r * s->sb_cols * 8 + c];
-
- if (mv->ref[0] != ref && mv->ref[0] >= 0) {
- RETURN_SCALE_MV(mv->mv[0], s->s.h.signbias[mv->ref[0]] != s->s.h.signbias[ref]);
- }
- if (mv->ref[1] != ref && mv->ref[1] >= 0 &&
- // BUG - libvpx has this condition regardless of whether
- // we used the first ref MV and pre-scaling
- AV_RN32A(&mv->mv[0]) != AV_RN32A(&mv->mv[1])) {
- RETURN_SCALE_MV(mv->mv[1], s->s.h.signbias[mv->ref[1]] != s->s.h.signbias[ref]);
- }
- }
- }
-
- // MV at this position in previous frame, using different reference frame
- if (s->s.h.use_last_frame_mvs) {
- struct VP9mvrefPair *mv = &s->s.frames[REF_FRAME_MVPAIR].mv[row * s->sb_cols * 8 + col];
-
- // no need to await_progress, because we already did that above
- if (mv->ref[0] != ref && mv->ref[0] >= 0) {
- RETURN_SCALE_MV(mv->mv[0], s->s.h.signbias[mv->ref[0]] != s->s.h.signbias[ref]);
- }
- if (mv->ref[1] != ref && mv->ref[1] >= 0 &&
- // BUG - libvpx has this condition regardless of whether
- // we used the first ref MV and pre-scaling
- AV_RN32A(&mv->mv[0]) != AV_RN32A(&mv->mv[1])) {
- RETURN_SCALE_MV(mv->mv[1], s->s.h.signbias[mv->ref[1]] != s->s.h.signbias[ref]);
- }
- }
-
- AV_ZERO32(pmv);
- clamp_mv(pmv, pmv, s);
-#undef INVALID_MV
-#undef RETURN_MV
-#undef RETURN_SCALE_MV
-}
-
-static av_always_inline int read_mv_component(VP9Context *s, int idx, int hp)
-{
- int bit, sign = vp56_rac_get_prob(&s->c, s->prob.p.mv_comp[idx].sign);
- int n, c = vp8_rac_get_tree(&s->c, vp9_mv_class_tree,
- s->prob.p.mv_comp[idx].classes);
-
- s->counts.mv_comp[idx].sign[sign]++;
- s->counts.mv_comp[idx].classes[c]++;
- if (c) {
- int m;
-
- for (n = 0, m = 0; m < c; m++) {
- bit = vp56_rac_get_prob(&s->c, s->prob.p.mv_comp[idx].bits[m]);
- n |= bit << m;
- s->counts.mv_comp[idx].bits[m][bit]++;
- }
- n <<= 3;
- bit = vp8_rac_get_tree(&s->c, vp9_mv_fp_tree, s->prob.p.mv_comp[idx].fp);
- n |= bit << 1;
- s->counts.mv_comp[idx].fp[bit]++;
- if (hp) {
- bit = vp56_rac_get_prob(&s->c, s->prob.p.mv_comp[idx].hp);
- s->counts.mv_comp[idx].hp[bit]++;
- n |= bit;
- } else {
- n |= 1;
- // bug in libvpx - we count for bw entropy purposes even if the
- // bit wasn't coded
- s->counts.mv_comp[idx].hp[1]++;
- }
- n += 8 << c;
- } else {
- n = vp56_rac_get_prob(&s->c, s->prob.p.mv_comp[idx].class0);
- s->counts.mv_comp[idx].class0[n]++;
- bit = vp8_rac_get_tree(&s->c, vp9_mv_fp_tree,
- s->prob.p.mv_comp[idx].class0_fp[n]);
- s->counts.mv_comp[idx].class0_fp[n][bit]++;
- n = (n << 3) | (bit << 1);
- if (hp) {
- bit = vp56_rac_get_prob(&s->c, s->prob.p.mv_comp[idx].class0_hp);
- s->counts.mv_comp[idx].class0_hp[bit]++;
- n |= bit;
- } else {
- n |= 1;
- // bug in libvpx - we count for bw entropy purposes even if the
- // bit wasn't coded
- s->counts.mv_comp[idx].class0_hp[1]++;
- }
- }
-
- return sign ? -(n + 1) : (n + 1);
-}
-
-static void fill_mv(VP9Context *s,
- VP56mv *mv, int mode, int sb)
-{
- VP9Block *b = s->b;
-
- if (mode == ZEROMV) {
- AV_ZERO64(mv);
- } else {
- int hp;
-
- // FIXME cache this value and reuse for other subblocks
- find_ref_mvs(s, &mv[0], b->ref[0], 0, mode == NEARMV,
- mode == NEWMV ? -1 : sb);
- // FIXME maybe move this code into find_ref_mvs()
- if ((mode == NEWMV || sb == -1) &&
- !(hp = s->s.h.highprecisionmvs && abs(mv[0].x) < 64 && abs(mv[0].y) < 64)) {
- if (mv[0].y & 1) {
- if (mv[0].y < 0)
- mv[0].y++;
- else
- mv[0].y--;
- }
- if (mv[0].x & 1) {
- if (mv[0].x < 0)
- mv[0].x++;
- else
- mv[0].x--;
- }
- }
- if (mode == NEWMV) {
- enum MVJoint j = vp8_rac_get_tree(&s->c, vp9_mv_joint_tree,
- s->prob.p.mv_joint);
-
- s->counts.mv_joint[j]++;
- if (j >= MV_JOINT_V)
- mv[0].y += read_mv_component(s, 0, hp);
- if (j & 1)
- mv[0].x += read_mv_component(s, 1, hp);
- }
-
- if (b->comp) {
- // FIXME cache this value and reuse for other subblocks
- find_ref_mvs(s, &mv[1], b->ref[1], 1, mode == NEARMV,
- mode == NEWMV ? -1 : sb);
- if ((mode == NEWMV || sb == -1) &&
- !(hp = s->s.h.highprecisionmvs && abs(mv[1].x) < 64 && abs(mv[1].y) < 64)) {
- if (mv[1].y & 1) {
- if (mv[1].y < 0)
- mv[1].y++;
- else
- mv[1].y--;
- }
- if (mv[1].x & 1) {
- if (mv[1].x < 0)
- mv[1].x++;
- else
- mv[1].x--;
- }
- }
- if (mode == NEWMV) {
- enum MVJoint j = vp8_rac_get_tree(&s->c, vp9_mv_joint_tree,
- s->prob.p.mv_joint);
-
- s->counts.mv_joint[j]++;
- if (j >= MV_JOINT_V)
- mv[1].y += read_mv_component(s, 0, hp);
- if (j & 1)
- mv[1].x += read_mv_component(s, 1, hp);
- }
- }
- }
-}
-
-static av_always_inline void setctx_2d(uint8_t *ptr, int w, int h,
- ptrdiff_t stride, int v)
-{
- switch (w) {
- case 1:
- do {
- *ptr = v;
- ptr += stride;
- } while (--h);
- break;
- case 2: {
- int v16 = v * 0x0101;
- do {
- AV_WN16A(ptr, v16);
- ptr += stride;
- } while (--h);
- break;
- }
- case 4: {
- uint32_t v32 = v * 0x01010101;
- do {
- AV_WN32A(ptr, v32);
- ptr += stride;
- } while (--h);
- break;
- }
- case 8: {
-#if HAVE_FAST_64BIT
- uint64_t v64 = v * 0x0101010101010101ULL;
- do {
- AV_WN64A(ptr, v64);
- ptr += stride;
- } while (--h);
-#else
- uint32_t v32 = v * 0x01010101;
- do {
- AV_WN32A(ptr, v32);
- AV_WN32A(ptr + 4, v32);
- ptr += stride;
- } while (--h);
-#endif
- break;
- }
- }
-}
-
-static void decode_mode(AVCodecContext *ctx)
-{
- static const uint8_t left_ctx[N_BS_SIZES] = {
- 0x0, 0x8, 0x0, 0x8, 0xc, 0x8, 0xc, 0xe, 0xc, 0xe, 0xf, 0xe, 0xf
- };
- static const uint8_t above_ctx[N_BS_SIZES] = {
- 0x0, 0x0, 0x8, 0x8, 0x8, 0xc, 0xc, 0xc, 0xe, 0xe, 0xe, 0xf, 0xf
- };
- static const uint8_t max_tx_for_bl_bp[N_BS_SIZES] = {
- TX_32X32, TX_32X32, TX_32X32, TX_32X32, TX_16X16, TX_16X16,
- TX_16X16, TX_8X8, TX_8X8, TX_8X8, TX_4X4, TX_4X4, TX_4X4
- };
- VP9Context *s = ctx->priv_data;
- VP9Block *b = s->b;
- int row = s->row, col = s->col, row7 = s->row7;
- enum TxfmMode max_tx = max_tx_for_bl_bp[b->bs];
- int bw4 = bwh_tab[1][b->bs][0], w4 = FFMIN(s->cols - col, bw4);
- int bh4 = bwh_tab[1][b->bs][1], h4 = FFMIN(s->rows - row, bh4), y;
- int have_a = row > 0, have_l = col > s->tile_col_start;
- int vref, filter_id;
-
- if (!s->s.h.segmentation.enabled) {
- b->seg_id = 0;
- } else if (s->s.h.keyframe || s->s.h.intraonly) {
- b->seg_id = !s->s.h.segmentation.update_map ? 0 :
- vp8_rac_get_tree(&s->c, vp9_segmentation_tree, s->s.h.segmentation.prob);
- } else if (!s->s.h.segmentation.update_map ||
- (s->s.h.segmentation.temporal &&
- vp56_rac_get_prob_branchy(&s->c,
- s->s.h.segmentation.pred_prob[s->above_segpred_ctx[col] +
- s->left_segpred_ctx[row7]]))) {
- if (!s->s.h.errorres && s->s.frames[REF_FRAME_SEGMAP].segmentation_map) {
- int pred = 8, x;
- uint8_t *refsegmap = s->s.frames[REF_FRAME_SEGMAP].segmentation_map;
-
- if (!s->s.frames[REF_FRAME_SEGMAP].uses_2pass)
- ff_thread_await_progress(&s->s.frames[REF_FRAME_SEGMAP].tf, row >> 3, 0);
- for (y = 0; y < h4; y++) {
- int idx_base = (y + row) * 8 * s->sb_cols + col;
- for (x = 0; x < w4; x++)
- pred = FFMIN(pred, refsegmap[idx_base + x]);
- }
- av_assert1(pred < 8);
- b->seg_id = pred;
- } else {
- b->seg_id = 0;
- }
-
- memset(&s->above_segpred_ctx[col], 1, w4);
- memset(&s->left_segpred_ctx[row7], 1, h4);
- } else {
- b->seg_id = vp8_rac_get_tree(&s->c, vp9_segmentation_tree,
- s->s.h.segmentation.prob);
-
- memset(&s->above_segpred_ctx[col], 0, w4);
- memset(&s->left_segpred_ctx[row7], 0, h4);
- }
- if (s->s.h.segmentation.enabled &&
- (s->s.h.segmentation.update_map || s->s.h.keyframe || s->s.h.intraonly)) {
- setctx_2d(&s->s.frames[CUR_FRAME].segmentation_map[row * 8 * s->sb_cols + col],
- bw4, bh4, 8 * s->sb_cols, b->seg_id);
- }
-
- b->skip = s->s.h.segmentation.enabled &&
- s->s.h.segmentation.feat[b->seg_id].skip_enabled;
- if (!b->skip) {
- int c = s->left_skip_ctx[row7] + s->above_skip_ctx[col];
- b->skip = vp56_rac_get_prob(&s->c, s->prob.p.skip[c]);
- s->counts.skip[c][b->skip]++;
- }
-
- if (s->s.h.keyframe || s->s.h.intraonly) {
- b->intra = 1;
- } else if (s->s.h.segmentation.enabled && s->s.h.segmentation.feat[b->seg_id].ref_enabled) {
- b->intra = !s->s.h.segmentation.feat[b->seg_id].ref_val;
- } else {
- int c, bit;
-
- if (have_a && have_l) {
- c = s->above_intra_ctx[col] + s->left_intra_ctx[row7];
- c += (c == 2);
- } else {
- c = have_a ? 2 * s->above_intra_ctx[col] :
- have_l ? 2 * s->left_intra_ctx[row7] : 0;
- }
- bit = vp56_rac_get_prob(&s->c, s->prob.p.intra[c]);
- s->counts.intra[c][bit]++;
- b->intra = !bit;
- }
-
- if ((b->intra || !b->skip) && s->s.h.txfmmode == TX_SWITCHABLE) {
- int c;
- if (have_a) {
- if (have_l) {
- c = (s->above_skip_ctx[col] ? max_tx :
- s->above_txfm_ctx[col]) +
- (s->left_skip_ctx[row7] ? max_tx :
- s->left_txfm_ctx[row7]) > max_tx;
- } else {
- c = s->above_skip_ctx[col] ? 1 :
- (s->above_txfm_ctx[col] * 2 > max_tx);
- }
- } else if (have_l) {
- c = s->left_skip_ctx[row7] ? 1 :
- (s->left_txfm_ctx[row7] * 2 > max_tx);
- } else {
- c = 1;
- }
- switch (max_tx) {
- case TX_32X32:
- b->tx = vp56_rac_get_prob(&s->c, s->prob.p.tx32p[c][0]);
- if (b->tx) {
- b->tx += vp56_rac_get_prob(&s->c, s->prob.p.tx32p[c][1]);
- if (b->tx == 2)
- b->tx += vp56_rac_get_prob(&s->c, s->prob.p.tx32p[c][2]);
- }
- s->counts.tx32p[c][b->tx]++;
- break;
- case TX_16X16:
- b->tx = vp56_rac_get_prob(&s->c, s->prob.p.tx16p[c][0]);
- if (b->tx)
- b->tx += vp56_rac_get_prob(&s->c, s->prob.p.tx16p[c][1]);
- s->counts.tx16p[c][b->tx]++;
- break;
- case TX_8X8:
- b->tx = vp56_rac_get_prob(&s->c, s->prob.p.tx8p[c]);
- s->counts.tx8p[c][b->tx]++;
- break;
- case TX_4X4:
- b->tx = TX_4X4;
- break;
- }
- } else {
- b->tx = FFMIN(max_tx, s->s.h.txfmmode);
- }
-
- if (s->s.h.keyframe || s->s.h.intraonly) {
- uint8_t *a = &s->above_mode_ctx[col * 2];
- uint8_t *l = &s->left_mode_ctx[(row7) << 1];
-
- b->comp = 0;
- if (b->bs > BS_8x8) {
- // FIXME the memory storage intermediates here aren't really
- // necessary, they're just there to make the code slightly
- // simpler for now
- b->mode[0] = a[0] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- vp9_default_kf_ymode_probs[a[0]][l[0]]);
- if (b->bs != BS_8x4) {
- b->mode[1] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- vp9_default_kf_ymode_probs[a[1]][b->mode[0]]);
- l[0] = a[1] = b->mode[1];
- } else {
- l[0] = a[1] = b->mode[1] = b->mode[0];
- }
- if (b->bs != BS_4x8) {
- b->mode[2] = a[0] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- vp9_default_kf_ymode_probs[a[0]][l[1]]);
- if (b->bs != BS_8x4) {
- b->mode[3] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- vp9_default_kf_ymode_probs[a[1]][b->mode[2]]);
- l[1] = a[1] = b->mode[3];
- } else {
- l[1] = a[1] = b->mode[3] = b->mode[2];
- }
- } else {
- b->mode[2] = b->mode[0];
- l[1] = a[1] = b->mode[3] = b->mode[1];
- }
- } else {
- b->mode[0] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- vp9_default_kf_ymode_probs[*a][*l]);
- b->mode[3] = b->mode[2] = b->mode[1] = b->mode[0];
- // FIXME this can probably be optimized
- memset(a, b->mode[0], bwh_tab[0][b->bs][0]);
- memset(l, b->mode[0], bwh_tab[0][b->bs][1]);
- }
- b->uvmode = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- vp9_default_kf_uvmode_probs[b->mode[3]]);
- } else if (b->intra) {
- b->comp = 0;
- if (b->bs > BS_8x8) {
- b->mode[0] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- s->prob.p.y_mode[0]);
- s->counts.y_mode[0][b->mode[0]]++;
- if (b->bs != BS_8x4) {
- b->mode[1] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- s->prob.p.y_mode[0]);
- s->counts.y_mode[0][b->mode[1]]++;
- } else {
- b->mode[1] = b->mode[0];
- }
- if (b->bs != BS_4x8) {
- b->mode[2] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- s->prob.p.y_mode[0]);
- s->counts.y_mode[0][b->mode[2]]++;
- if (b->bs != BS_8x4) {
- b->mode[3] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- s->prob.p.y_mode[0]);
- s->counts.y_mode[0][b->mode[3]]++;
- } else {
- b->mode[3] = b->mode[2];
- }
- } else {
- b->mode[2] = b->mode[0];
- b->mode[3] = b->mode[1];
- }
- } else {
- static const uint8_t size_group[10] = {
- 3, 3, 3, 3, 2, 2, 2, 1, 1, 1
- };
- int sz = size_group[b->bs];
-
- b->mode[0] = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- s->prob.p.y_mode[sz]);
- b->mode[1] = b->mode[2] = b->mode[3] = b->mode[0];
- s->counts.y_mode[sz][b->mode[3]]++;
- }
- b->uvmode = vp8_rac_get_tree(&s->c, vp9_intramode_tree,
- s->prob.p.uv_mode[b->mode[3]]);
- s->counts.uv_mode[b->mode[3]][b->uvmode]++;
- } else {
- static const uint8_t inter_mode_ctx_lut[14][14] = {
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
- { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2, 2, 1, 3 },
- { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2, 2, 1, 3 },
- { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 0, 3 },
- { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 3, 3, 4 },
- };
-
- if (s->s.h.segmentation.enabled && s->s.h.segmentation.feat[b->seg_id].ref_enabled) {
- av_assert2(s->s.h.segmentation.feat[b->seg_id].ref_val != 0);
- b->comp = 0;
- b->ref[0] = s->s.h.segmentation.feat[b->seg_id].ref_val - 1;
- } else {
- // read comp_pred flag
- if (s->s.h.comppredmode != PRED_SWITCHABLE) {
- b->comp = s->s.h.comppredmode == PRED_COMPREF;
- } else {
- int c;
-
- // FIXME add intra as ref=0xff (or -1) to make these easier?
- if (have_a) {
- if (have_l) {
- if (s->above_comp_ctx[col] && s->left_comp_ctx[row7]) {
- c = 4;
- } else if (s->above_comp_ctx[col]) {
- c = 2 + (s->left_intra_ctx[row7] ||
- s->left_ref_ctx[row7] == s->s.h.fixcompref);
- } else if (s->left_comp_ctx[row7]) {
- c = 2 + (s->above_intra_ctx[col] ||
- s->above_ref_ctx[col] == s->s.h.fixcompref);
- } else {
- c = (!s->above_intra_ctx[col] &&
- s->above_ref_ctx[col] == s->s.h.fixcompref) ^
- (!s->left_intra_ctx[row7] &&
- s->left_ref_ctx[row & 7] == s->s.h.fixcompref);
- }
- } else {
- c = s->above_comp_ctx[col] ? 3 :
- (!s->above_intra_ctx[col] && s->above_ref_ctx[col] == s->s.h.fixcompref);
- }
- } else if (have_l) {
- c = s->left_comp_ctx[row7] ? 3 :
- (!s->left_intra_ctx[row7] && s->left_ref_ctx[row7] == s->s.h.fixcompref);
- } else {
- c = 1;
- }
- b->comp = vp56_rac_get_prob(&s->c, s->prob.p.comp[c]);
- s->counts.comp[c][b->comp]++;
- }
-
- // read actual references
- // FIXME probably cache a few variables here to prevent repetitive
- // memory accesses below
- if (b->comp) /* two references */ {
- int fix_idx = s->s.h.signbias[s->s.h.fixcompref], var_idx = !fix_idx, c, bit;
-
- b->ref[fix_idx] = s->s.h.fixcompref;
- // FIXME can this codeblob be replaced by some sort of LUT?
- if (have_a) {
- if (have_l) {
- if (s->above_intra_ctx[col]) {
- if (s->left_intra_ctx[row7]) {
- c = 2;
- } else {
- c = 1 + 2 * (s->left_ref_ctx[row7] != s->s.h.varcompref[1]);
- }
- } else if (s->left_intra_ctx[row7]) {
- c = 1 + 2 * (s->above_ref_ctx[col] != s->s.h.varcompref[1]);
- } else {
- int refl = s->left_ref_ctx[row7], refa = s->above_ref_ctx[col];
-
- if (refl == refa && refa == s->s.h.varcompref[1]) {
- c = 0;
- } else if (!s->left_comp_ctx[row7] && !s->above_comp_ctx[col]) {
- if ((refa == s->s.h.fixcompref && refl == s->s.h.varcompref[0]) ||
- (refl == s->s.h.fixcompref && refa == s->s.h.varcompref[0])) {
- c = 4;
- } else {
- c = (refa == refl) ? 3 : 1;
- }
- } else if (!s->left_comp_ctx[row7]) {
- if (refa == s->s.h.varcompref[1] && refl != s->s.h.varcompref[1]) {
- c = 1;
- } else {
- c = (refl == s->s.h.varcompref[1] &&
- refa != s->s.h.varcompref[1]) ? 2 : 4;
- }
- } else if (!s->above_comp_ctx[col]) {
- if (refl == s->s.h.varcompref[1] && refa != s->s.h.varcompref[1]) {
- c = 1;
- } else {
- c = (refa == s->s.h.varcompref[1] &&
- refl != s->s.h.varcompref[1]) ? 2 : 4;
- }
- } else {
- c = (refl == refa) ? 4 : 2;
- }
- }
- } else {
- if (s->above_intra_ctx[col]) {
- c = 2;
- } else if (s->above_comp_ctx[col]) {
- c = 4 * (s->above_ref_ctx[col] != s->s.h.varcompref[1]);
- } else {
- c = 3 * (s->above_ref_ctx[col] != s->s.h.varcompref[1]);
- }
- }
- } else if (have_l) {
- if (s->left_intra_ctx[row7]) {
- c = 2;
- } else if (s->left_comp_ctx[row7]) {
- c = 4 * (s->left_ref_ctx[row7] != s->s.h.varcompref[1]);
- } else {
- c = 3 * (s->left_ref_ctx[row7] != s->s.h.varcompref[1]);
- }
- } else {
- c = 2;
- }
- bit = vp56_rac_get_prob(&s->c, s->prob.p.comp_ref[c]);
- b->ref[var_idx] = s->s.h.varcompref[bit];
- s->counts.comp_ref[c][bit]++;
- } else /* single reference */ {
- int bit, c;
-
- if (have_a && !s->above_intra_ctx[col]) {
- if (have_l && !s->left_intra_ctx[row7]) {
- if (s->left_comp_ctx[row7]) {
- if (s->above_comp_ctx[col]) {
- c = 1 + (!s->s.h.fixcompref || !s->left_ref_ctx[row7] ||
- !s->above_ref_ctx[col]);
- } else {
- c = (3 * !s->above_ref_ctx[col]) +
- (!s->s.h.fixcompref || !s->left_ref_ctx[row7]);
- }
- } else if (s->above_comp_ctx[col]) {
- c = (3 * !s->left_ref_ctx[row7]) +
- (!s->s.h.fixcompref || !s->above_ref_ctx[col]);
- } else {
- c = 2 * !s->left_ref_ctx[row7] + 2 * !s->above_ref_ctx[col];
- }
- } else if (s->above_intra_ctx[col]) {
- c = 2;
- } else if (s->above_comp_ctx[col]) {
- c = 1 + (!s->s.h.fixcompref || !s->above_ref_ctx[col]);
- } else {
- c = 4 * (!s->above_ref_ctx[col]);
- }
- } else if (have_l && !s->left_intra_ctx[row7]) {
- if (s->left_intra_ctx[row7]) {
- c = 2;
- } else if (s->left_comp_ctx[row7]) {
- c = 1 + (!s->s.h.fixcompref || !s->left_ref_ctx[row7]);
- } else {
- c = 4 * (!s->left_ref_ctx[row7]);
- }
- } else {
- c = 2;
- }
- bit = vp56_rac_get_prob(&s->c, s->prob.p.single_ref[c][0]);
- s->counts.single_ref[c][0][bit]++;
- if (!bit) {
- b->ref[0] = 0;
- } else {
- // FIXME can this codeblob be replaced by some sort of LUT?
- if (have_a) {
- if (have_l) {
- if (s->left_intra_ctx[row7]) {
- if (s->above_intra_ctx[col]) {
- c = 2;
- } else if (s->above_comp_ctx[col]) {
- c = 1 + 2 * (s->s.h.fixcompref == 1 ||
- s->above_ref_ctx[col] == 1);
- } else if (!s->above_ref_ctx[col]) {
- c = 3;
- } else {
- c = 4 * (s->above_ref_ctx[col] == 1);
- }
- } else if (s->above_intra_ctx[col]) {
- if (s->left_intra_ctx[row7]) {
- c = 2;
- } else if (s->left_comp_ctx[row7]) {
- c = 1 + 2 * (s->s.h.fixcompref == 1 ||
- s->left_ref_ctx[row7] == 1);
- } else if (!s->left_ref_ctx[row7]) {
- c = 3;
- } else {
- c = 4 * (s->left_ref_ctx[row7] == 1);
- }
- } else if (s->above_comp_ctx[col]) {
- if (s->left_comp_ctx[row7]) {
- if (s->left_ref_ctx[row7] == s->above_ref_ctx[col]) {
- c = 3 * (s->s.h.fixcompref == 1 ||
- s->left_ref_ctx[row7] == 1);
- } else {
- c = 2;
- }
- } else if (!s->left_ref_ctx[row7]) {
- c = 1 + 2 * (s->s.h.fixcompref == 1 ||
- s->above_ref_ctx[col] == 1);
- } else {
- c = 3 * (s->left_ref_ctx[row7] == 1) +
- (s->s.h.fixcompref == 1 || s->above_ref_ctx[col] == 1);
- }
- } else if (s->left_comp_ctx[row7]) {
- if (!s->above_ref_ctx[col]) {
- c = 1 + 2 * (s->s.h.fixcompref == 1 ||
- s->left_ref_ctx[row7] == 1);
- } else {
- c = 3 * (s->above_ref_ctx[col] == 1) +
- (s->s.h.fixcompref == 1 || s->left_ref_ctx[row7] == 1);
- }
- } else if (!s->above_ref_ctx[col]) {
- if (!s->left_ref_ctx[row7]) {
- c = 3;
- } else {
- c = 4 * (s->left_ref_ctx[row7] == 1);
- }
- } else if (!s->left_ref_ctx[row7]) {
- c = 4 * (s->above_ref_ctx[col] == 1);
- } else {
- c = 2 * (s->left_ref_ctx[row7] == 1) +
- 2 * (s->above_ref_ctx[col] == 1);
- }
- } else {
- if (s->above_intra_ctx[col] ||
- (!s->above_comp_ctx[col] && !s->above_ref_ctx[col])) {
- c = 2;
- } else if (s->above_comp_ctx[col]) {
- c = 3 * (s->s.h.fixcompref == 1 || s->above_ref_ctx[col] == 1);
- } else {
- c = 4 * (s->above_ref_ctx[col] == 1);
- }
- }
- } else if (have_l) {
- if (s->left_intra_ctx[row7] ||
- (!s->left_comp_ctx[row7] && !s->left_ref_ctx[row7])) {
- c = 2;
- } else if (s->left_comp_ctx[row7]) {
- c = 3 * (s->s.h.fixcompref == 1 || s->left_ref_ctx[row7] == 1);
- } else {
- c = 4 * (s->left_ref_ctx[row7] == 1);
- }
- } else {
- c = 2;
- }
- bit = vp56_rac_get_prob(&s->c, s->prob.p.single_ref[c][1]);
- s->counts.single_ref[c][1][bit]++;
- b->ref[0] = 1 + bit;
- }
- }
- }
-
- if (b->bs <= BS_8x8) {
- if (s->s.h.segmentation.enabled && s->s.h.segmentation.feat[b->seg_id].skip_enabled) {
- b->mode[0] = b->mode[1] = b->mode[2] = b->mode[3] = ZEROMV;
- } else {
- static const uint8_t off[10] = {
- 3, 0, 0, 1, 0, 0, 0, 0, 0, 0
- };
-
- // FIXME this needs to use the LUT tables from find_ref_mvs
- // because not all are -1,0/0,-1
- int c = inter_mode_ctx_lut[s->above_mode_ctx[col + off[b->bs]]]
- [s->left_mode_ctx[row7 + off[b->bs]]];
-
- b->mode[0] = vp8_rac_get_tree(&s->c, vp9_inter_mode_tree,
- s->prob.p.mv_mode[c]);
- b->mode[1] = b->mode[2] = b->mode[3] = b->mode[0];
- s->counts.mv_mode[c][b->mode[0] - 10]++;
- }
- }
-
- if (s->s.h.filtermode == FILTER_SWITCHABLE) {
- int c;
-
- if (have_a && s->above_mode_ctx[col] >= NEARESTMV) {
- if (have_l && s->left_mode_ctx[row7] >= NEARESTMV) {
- c = s->above_filter_ctx[col] == s->left_filter_ctx[row7] ?
- s->left_filter_ctx[row7] : 3;
- } else {
- c = s->above_filter_ctx[col];
- }
- } else if (have_l && s->left_mode_ctx[row7] >= NEARESTMV) {
- c = s->left_filter_ctx[row7];
- } else {
- c = 3;
- }
-
- filter_id = vp8_rac_get_tree(&s->c, vp9_filter_tree,
- s->prob.p.filter[c]);
- s->counts.filter[c][filter_id]++;
- b->filter = vp9_filter_lut[filter_id];
- } else {
- b->filter = s->s.h.filtermode;
- }
-
- if (b->bs > BS_8x8) {
- int c = inter_mode_ctx_lut[s->above_mode_ctx[col]][s->left_mode_ctx[row7]];
-
- b->mode[0] = vp8_rac_get_tree(&s->c, vp9_inter_mode_tree,
- s->prob.p.mv_mode[c]);
- s->counts.mv_mode[c][b->mode[0] - 10]++;
- fill_mv(s, b->mv[0], b->mode[0], 0);
-
- if (b->bs != BS_8x4) {
- b->mode[1] = vp8_rac_get_tree(&s->c, vp9_inter_mode_tree,
- s->prob.p.mv_mode[c]);
- s->counts.mv_mode[c][b->mode[1] - 10]++;
- fill_mv(s, b->mv[1], b->mode[1], 1);
- } else {
- b->mode[1] = b->mode[0];
- AV_COPY32(&b->mv[1][0], &b->mv[0][0]);
- AV_COPY32(&b->mv[1][1], &b->mv[0][1]);
- }
-
- if (b->bs != BS_4x8) {
- b->mode[2] = vp8_rac_get_tree(&s->c, vp9_inter_mode_tree,
- s->prob.p.mv_mode[c]);
- s->counts.mv_mode[c][b->mode[2] - 10]++;
- fill_mv(s, b->mv[2], b->mode[2], 2);
-
- if (b->bs != BS_8x4) {
- b->mode[3] = vp8_rac_get_tree(&s->c, vp9_inter_mode_tree,
- s->prob.p.mv_mode[c]);
- s->counts.mv_mode[c][b->mode[3] - 10]++;
- fill_mv(s, b->mv[3], b->mode[3], 3);
- } else {
- b->mode[3] = b->mode[2];
- AV_COPY32(&b->mv[3][0], &b->mv[2][0]);
- AV_COPY32(&b->mv[3][1], &b->mv[2][1]);
- }
- } else {
- b->mode[2] = b->mode[0];
- AV_COPY32(&b->mv[2][0], &b->mv[0][0]);
- AV_COPY32(&b->mv[2][1], &b->mv[0][1]);
- b->mode[3] = b->mode[1];
- AV_COPY32(&b->mv[3][0], &b->mv[1][0]);
- AV_COPY32(&b->mv[3][1], &b->mv[1][1]);
- }
- } else {
- fill_mv(s, b->mv[0], b->mode[0], -1);
- AV_COPY32(&b->mv[1][0], &b->mv[0][0]);
- AV_COPY32(&b->mv[2][0], &b->mv[0][0]);
- AV_COPY32(&b->mv[3][0], &b->mv[0][0]);
- AV_COPY32(&b->mv[1][1], &b->mv[0][1]);
- AV_COPY32(&b->mv[2][1], &b->mv[0][1]);
- AV_COPY32(&b->mv[3][1], &b->mv[0][1]);
- }
-
- vref = b->ref[b->comp ? s->s.h.signbias[s->s.h.varcompref[0]] : 0];
- }
-
-#if HAVE_FAST_64BIT
-#define SPLAT_CTX(var, val, n) \
- switch (n) { \
- case 1: var = val; break; \
- case 2: AV_WN16A(&var, val * 0x0101); break; \
- case 4: AV_WN32A(&var, val * 0x01010101); break; \
- case 8: AV_WN64A(&var, val * 0x0101010101010101ULL); break; \
- case 16: { \
- uint64_t v64 = val * 0x0101010101010101ULL; \
- AV_WN64A( &var, v64); \
- AV_WN64A(&((uint8_t *) &var)[8], v64); \
- break; \
- } \
- }
-#else
-#define SPLAT_CTX(var, val, n) \
- switch (n) { \
- case 1: var = val; break; \
- case 2: AV_WN16A(&var, val * 0x0101); break; \
- case 4: AV_WN32A(&var, val * 0x01010101); break; \
- case 8: { \
- uint32_t v32 = val * 0x01010101; \
- AV_WN32A( &var, v32); \
- AV_WN32A(&((uint8_t *) &var)[4], v32); \
- break; \
- } \
- case 16: { \
- uint32_t v32 = val * 0x01010101; \
- AV_WN32A( &var, v32); \
- AV_WN32A(&((uint8_t *) &var)[4], v32); \
- AV_WN32A(&((uint8_t *) &var)[8], v32); \
- AV_WN32A(&((uint8_t *) &var)[12], v32); \
- break; \
- } \
- }
-#endif
-
- switch (bwh_tab[1][b->bs][0]) {
-#define SET_CTXS(dir, off, n) \
- do { \
- SPLAT_CTX(s->dir##_skip_ctx[off], b->skip, n); \
- SPLAT_CTX(s->dir##_txfm_ctx[off], b->tx, n); \
- SPLAT_CTX(s->dir##_partition_ctx[off], dir##_ctx[b->bs], n); \
- if (!s->s.h.keyframe && !s->s.h.intraonly) { \
- SPLAT_CTX(s->dir##_intra_ctx[off], b->intra, n); \
- SPLAT_CTX(s->dir##_comp_ctx[off], b->comp, n); \
- SPLAT_CTX(s->dir##_mode_ctx[off], b->mode[3], n); \
- if (!b->intra) { \
- SPLAT_CTX(s->dir##_ref_ctx[off], vref, n); \
- if (s->s.h.filtermode == FILTER_SWITCHABLE) { \
- SPLAT_CTX(s->dir##_filter_ctx[off], filter_id, n); \
- } \
- } \
- } \
- } while (0)
- case 1: SET_CTXS(above, col, 1); break;
- case 2: SET_CTXS(above, col, 2); break;
- case 4: SET_CTXS(above, col, 4); break;
- case 8: SET_CTXS(above, col, 8); break;
- }
- switch (bwh_tab[1][b->bs][1]) {
- case 1: SET_CTXS(left, row7, 1); break;
- case 2: SET_CTXS(left, row7, 2); break;
- case 4: SET_CTXS(left, row7, 4); break;
- case 8: SET_CTXS(left, row7, 8); break;
- }
-#undef SPLAT_CTX
-#undef SET_CTXS
-
- if (!s->s.h.keyframe && !s->s.h.intraonly) {
- if (b->bs > BS_8x8) {
- int mv0 = AV_RN32A(&b->mv[3][0]), mv1 = AV_RN32A(&b->mv[3][1]);
-
- AV_COPY32(&s->left_mv_ctx[row7 * 2 + 0][0], &b->mv[1][0]);
- AV_COPY32(&s->left_mv_ctx[row7 * 2 + 0][1], &b->mv[1][1]);
- AV_WN32A(&s->left_mv_ctx[row7 * 2 + 1][0], mv0);
- AV_WN32A(&s->left_mv_ctx[row7 * 2 + 1][1], mv1);
- AV_COPY32(&s->above_mv_ctx[col * 2 + 0][0], &b->mv[2][0]);
- AV_COPY32(&s->above_mv_ctx[col * 2 + 0][1], &b->mv[2][1]);
- AV_WN32A(&s->above_mv_ctx[col * 2 + 1][0], mv0);
- AV_WN32A(&s->above_mv_ctx[col * 2 + 1][1], mv1);
- } else {
- int n, mv0 = AV_RN32A(&b->mv[3][0]), mv1 = AV_RN32A(&b->mv[3][1]);
-
- for (n = 0; n < w4 * 2; n++) {
- AV_WN32A(&s->above_mv_ctx[col * 2 + n][0], mv0);
- AV_WN32A(&s->above_mv_ctx[col * 2 + n][1], mv1);
- }
- for (n = 0; n < h4 * 2; n++) {
- AV_WN32A(&s->left_mv_ctx[row7 * 2 + n][0], mv0);
- AV_WN32A(&s->left_mv_ctx[row7 * 2 + n][1], mv1);
- }
- }
- }
-
- // FIXME kinda ugly
- for (y = 0; y < h4; y++) {
- int x, o = (row + y) * s->sb_cols * 8 + col;
- struct VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[o];
-
- if (b->intra) {
- for (x = 0; x < w4; x++) {
- mv[x].ref[0] =
- mv[x].ref[1] = -1;
- }
- } else if (b->comp) {
- for (x = 0; x < w4; x++) {
- mv[x].ref[0] = b->ref[0];
- mv[x].ref[1] = b->ref[1];
- AV_COPY32(&mv[x].mv[0], &b->mv[3][0]);
- AV_COPY32(&mv[x].mv[1], &b->mv[3][1]);
- }
- } else {
- for (x = 0; x < w4; x++) {
- mv[x].ref[0] = b->ref[0];
- mv[x].ref[1] = -1;
- AV_COPY32(&mv[x].mv[0], &b->mv[3][0]);
- }
- }
- }
-}
-
-// FIXME merge cnt/eob arguments?
-static av_always_inline int
-decode_coeffs_b_generic(VP56RangeCoder *c, int16_t *coef, int n_coeffs,
- int is_tx32x32, int is8bitsperpixel, int bpp, unsigned (*cnt)[6][3],
- unsigned (*eob)[6][2], uint8_t (*p)[6][11],
- int nnz, const int16_t *scan, const int16_t (*nb)[2],
- const int16_t *band_counts, const int16_t *qmul)
-{
- int i = 0, band = 0, band_left = band_counts[band];
- uint8_t *tp = p[0][nnz];
- uint8_t cache[1024];
-
- do {
- int val, rc;
-
- val = vp56_rac_get_prob_branchy(c, tp[0]); // eob
- eob[band][nnz][val]++;
- if (!val)
- break;
-
- skip_eob:
- if (!vp56_rac_get_prob_branchy(c, tp[1])) { // zero
- cnt[band][nnz][0]++;
- if (!--band_left)
- band_left = band_counts[++band];
- cache[scan[i]] = 0;
- nnz = (1 + cache[nb[i][0]] + cache[nb[i][1]]) >> 1;
- tp = p[band][nnz];
- if (++i == n_coeffs)
- break; //invalid input; blocks should end with EOB
- goto skip_eob;
- }
-
- rc = scan[i];
- if (!vp56_rac_get_prob_branchy(c, tp[2])) { // one
- cnt[band][nnz][1]++;
- val = 1;
- cache[rc] = 1;
- } else {
- // fill in p[3-10] (model fill) - only once per frame for each pos
- if (!tp[3])
- memcpy(&tp[3], vp9_model_pareto8[tp[2]], 8);
-
- cnt[band][nnz][2]++;
- if (!vp56_rac_get_prob_branchy(c, tp[3])) { // 2, 3, 4
- if (!vp56_rac_get_prob_branchy(c, tp[4])) {
- cache[rc] = val = 2;
- } else {
- val = 3 + vp56_rac_get_prob(c, tp[5]);
- cache[rc] = 3;
- }
- } else if (!vp56_rac_get_prob_branchy(c, tp[6])) { // cat1/2
- cache[rc] = 4;
- if (!vp56_rac_get_prob_branchy(c, tp[7])) {
- val = 5 + vp56_rac_get_prob(c, 159);
- } else {
- val = 7 + (vp56_rac_get_prob(c, 165) << 1);
- val += vp56_rac_get_prob(c, 145);
- }
- } else { // cat 3-6
- cache[rc] = 5;
- if (!vp56_rac_get_prob_branchy(c, tp[8])) {
- if (!vp56_rac_get_prob_branchy(c, tp[9])) {
- val = 11 + (vp56_rac_get_prob(c, 173) << 2);
- val += (vp56_rac_get_prob(c, 148) << 1);
- val += vp56_rac_get_prob(c, 140);
- } else {
- val = 19 + (vp56_rac_get_prob(c, 176) << 3);
- val += (vp56_rac_get_prob(c, 155) << 2);
- val += (vp56_rac_get_prob(c, 140) << 1);
- val += vp56_rac_get_prob(c, 135);
- }
- } else if (!vp56_rac_get_prob_branchy(c, tp[10])) {
- val = 35 + (vp56_rac_get_prob(c, 180) << 4);
- val += (vp56_rac_get_prob(c, 157) << 3);
- val += (vp56_rac_get_prob(c, 141) << 2);
- val += (vp56_rac_get_prob(c, 134) << 1);
- val += vp56_rac_get_prob(c, 130);
- } else {
- val = 67;
- if (!is8bitsperpixel) {
- if (bpp == 12) {
- val += vp56_rac_get_prob(c, 255) << 17;
- val += vp56_rac_get_prob(c, 255) << 16;
- }
- val += (vp56_rac_get_prob(c, 255) << 15);
- val += (vp56_rac_get_prob(c, 255) << 14);
- }
- val += (vp56_rac_get_prob(c, 254) << 13);
- val += (vp56_rac_get_prob(c, 254) << 12);
- val += (vp56_rac_get_prob(c, 254) << 11);
- val += (vp56_rac_get_prob(c, 252) << 10);
- val += (vp56_rac_get_prob(c, 249) << 9);
- val += (vp56_rac_get_prob(c, 243) << 8);
- val += (vp56_rac_get_prob(c, 230) << 7);
- val += (vp56_rac_get_prob(c, 196) << 6);
- val += (vp56_rac_get_prob(c, 177) << 5);
- val += (vp56_rac_get_prob(c, 153) << 4);
- val += (vp56_rac_get_prob(c, 140) << 3);
- val += (vp56_rac_get_prob(c, 133) << 2);
- val += (vp56_rac_get_prob(c, 130) << 1);
- val += vp56_rac_get_prob(c, 129);
- }
- }
- }
-#define STORE_COEF(c, i, v) do { \
- if (is8bitsperpixel) { \
- c[i] = v; \
- } else { \
- AV_WN32A(&c[i * 2], v); \
- } \
-} while (0)
- if (!--band_left)
- band_left = band_counts[++band];
- if (is_tx32x32)
- STORE_COEF(coef, rc, ((vp8_rac_get(c) ? -val : val) * qmul[!!i]) / 2);
- else
- STORE_COEF(coef, rc, (vp8_rac_get(c) ? -val : val) * qmul[!!i]);
- nnz = (1 + cache[nb[i][0]] + cache[nb[i][1]]) >> 1;
- tp = p[band][nnz];
- } while (++i < n_coeffs);
-
- return i;
-}
-
-static int decode_coeffs_b_8bpp(VP9Context *s, int16_t *coef, int n_coeffs,
- unsigned (*cnt)[6][3], unsigned (*eob)[6][2],
- uint8_t (*p)[6][11], int nnz, const int16_t *scan,
- const int16_t (*nb)[2], const int16_t *band_counts,
- const int16_t *qmul)
-{
- return decode_coeffs_b_generic(&s->c, coef, n_coeffs, 0, 1, 8, cnt, eob, p,
- nnz, scan, nb, band_counts, qmul);
-}
-
-static int decode_coeffs_b32_8bpp(VP9Context *s, int16_t *coef, int n_coeffs,
- unsigned (*cnt)[6][3], unsigned (*eob)[6][2],
- uint8_t (*p)[6][11], int nnz, const int16_t *scan,
- const int16_t (*nb)[2], const int16_t *band_counts,
- const int16_t *qmul)
-{
- return decode_coeffs_b_generic(&s->c, coef, n_coeffs, 1, 1, 8, cnt, eob, p,
- nnz, scan, nb, band_counts, qmul);
-}
-
-static int decode_coeffs_b_16bpp(VP9Context *s, int16_t *coef, int n_coeffs,
- unsigned (*cnt)[6][3], unsigned (*eob)[6][2],
- uint8_t (*p)[6][11], int nnz, const int16_t *scan,
- const int16_t (*nb)[2], const int16_t *band_counts,
- const int16_t *qmul)
-{
- return decode_coeffs_b_generic(&s->c, coef, n_coeffs, 0, 0, s->bpp, cnt, eob, p,
- nnz, scan, nb, band_counts, qmul);
-}
-
-static int decode_coeffs_b32_16bpp(VP9Context *s, int16_t *coef, int n_coeffs,
- unsigned (*cnt)[6][3], unsigned (*eob)[6][2],
- uint8_t (*p)[6][11], int nnz, const int16_t *scan,
- const int16_t (*nb)[2], const int16_t *band_counts,
- const int16_t *qmul)
-{
- return decode_coeffs_b_generic(&s->c, coef, n_coeffs, 1, 0, s->bpp, cnt, eob, p,
- nnz, scan, nb, band_counts, qmul);
-}
-
-static av_always_inline int decode_coeffs(AVCodecContext *ctx, int is8bitsperpixel)
-{
- VP9Context *s = ctx->priv_data;
- VP9Block *b = s->b;
- int row = s->row, col = s->col;
- uint8_t (*p)[6][11] = s->prob.coef[b->tx][0 /* y */][!b->intra];
- unsigned (*c)[6][3] = s->counts.coef[b->tx][0 /* y */][!b->intra];
- unsigned (*e)[6][2] = s->counts.eob[b->tx][0 /* y */][!b->intra];
- int w4 = bwh_tab[1][b->bs][0] << 1, h4 = bwh_tab[1][b->bs][1] << 1;
- int end_x = FFMIN(2 * (s->cols - col), w4);
- int end_y = FFMIN(2 * (s->rows - row), h4);
- int n, pl, x, y, res;
- int16_t (*qmul)[2] = s->s.h.segmentation.feat[b->seg_id].qmul;
- int tx = 4 * s->s.h.lossless + b->tx;
- const int16_t * const *yscans = vp9_scans[tx];
- const int16_t (* const *ynbs)[2] = vp9_scans_nb[tx];
- const int16_t *uvscan = vp9_scans[b->uvtx][DCT_DCT];
- const int16_t (*uvnb)[2] = vp9_scans_nb[b->uvtx][DCT_DCT];
- uint8_t *a = &s->above_y_nnz_ctx[col * 2];
- uint8_t *l = &s->left_y_nnz_ctx[(row & 7) << 1];
- static const int16_t band_counts[4][8] = {
- { 1, 2, 3, 4, 3, 16 - 13 },
- { 1, 2, 3, 4, 11, 64 - 21 },
- { 1, 2, 3, 4, 11, 256 - 21 },
- { 1, 2, 3, 4, 11, 1024 - 21 },
- };
- const int16_t *y_band_counts = band_counts[b->tx];
- const int16_t *uv_band_counts = band_counts[b->uvtx];
- int bytesperpixel = is8bitsperpixel ? 1 : 2;
- int total_coeff = 0;
-
-#define MERGE(la, end, step, rd) \
- for (n = 0; n < end; n += step) \
- la[n] = !!rd(&la[n])
-#define MERGE_CTX(step, rd) \
- do { \
- MERGE(l, end_y, step, rd); \
- MERGE(a, end_x, step, rd); \
- } while (0)
-
-#define DECODE_Y_COEF_LOOP(step, mode_index, v) \
- for (n = 0, y = 0; y < end_y; y += step) { \
- for (x = 0; x < end_x; x += step, n += step * step) { \
- enum TxfmType txtp = vp9_intra_txfm_type[b->mode[mode_index]]; \
- res = (is8bitsperpixel ? decode_coeffs_b##v##_8bpp : decode_coeffs_b##v##_16bpp) \
- (s, s->block + 16 * n * bytesperpixel, 16 * step * step, \
- c, e, p, a[x] + l[y], yscans[txtp], \
- ynbs[txtp], y_band_counts, qmul[0]); \
- a[x] = l[y] = !!res; \
- total_coeff |= !!res; \
- if (step >= 4) { \
- AV_WN16A(&s->eob[n], res); \
- } else { \
- s->eob[n] = res; \
- } \
- } \
- }
-
-#define SPLAT(la, end, step, cond) \
- if (step == 2) { \
- for (n = 1; n < end; n += step) \
- la[n] = la[n - 1]; \
- } else if (step == 4) { \
- if (cond) { \
- for (n = 0; n < end; n += step) \
- AV_WN32A(&la[n], la[n] * 0x01010101); \
- } else { \
- for (n = 0; n < end; n += step) \
- memset(&la[n + 1], la[n], FFMIN(end - n - 1, 3)); \
- } \
- } else /* step == 8 */ { \
- if (cond) { \
- if (HAVE_FAST_64BIT) { \
- for (n = 0; n < end; n += step) \
- AV_WN64A(&la[n], la[n] * 0x0101010101010101ULL); \
- } else { \
- for (n = 0; n < end; n += step) { \
- uint32_t v32 = la[n] * 0x01010101; \
- AV_WN32A(&la[n], v32); \
- AV_WN32A(&la[n + 4], v32); \
- } \
- } \
- } else { \
- for (n = 0; n < end; n += step) \
- memset(&la[n + 1], la[n], FFMIN(end - n - 1, 7)); \
- } \
- }
-#define SPLAT_CTX(step) \
- do { \
- SPLAT(a, end_x, step, end_x == w4); \
- SPLAT(l, end_y, step, end_y == h4); \
- } while (0)
-
- /* y tokens */
- switch (b->tx) {
- case TX_4X4:
- DECODE_Y_COEF_LOOP(1, b->bs > BS_8x8 ? n : 0,);
- break;
- case TX_8X8:
- MERGE_CTX(2, AV_RN16A);
- DECODE_Y_COEF_LOOP(2, 0,);
- SPLAT_CTX(2);
- break;
- case TX_16X16:
- MERGE_CTX(4, AV_RN32A);
- DECODE_Y_COEF_LOOP(4, 0,);
- SPLAT_CTX(4);
- break;
- case TX_32X32:
- MERGE_CTX(8, AV_RN64A);
- DECODE_Y_COEF_LOOP(8, 0, 32);
- SPLAT_CTX(8);
- break;
- }
-
-#define DECODE_UV_COEF_LOOP(step, v) \
- for (n = 0, y = 0; y < end_y; y += step) { \
- for (x = 0; x < end_x; x += step, n += step * step) { \
- res = (is8bitsperpixel ? decode_coeffs_b##v##_8bpp : decode_coeffs_b##v##_16bpp) \
- (s, s->uvblock[pl] + 16 * n * bytesperpixel, \
- 16 * step * step, c, e, p, a[x] + l[y], \
- uvscan, uvnb, uv_band_counts, qmul[1]); \
- a[x] = l[y] = !!res; \
- total_coeff |= !!res; \
- if (step >= 4) { \
- AV_WN16A(&s->uveob[pl][n], res); \
- } else { \
- s->uveob[pl][n] = res; \
- } \
- } \
- }
-
- p = s->prob.coef[b->uvtx][1 /* uv */][!b->intra];
- c = s->counts.coef[b->uvtx][1 /* uv */][!b->intra];
- e = s->counts.eob[b->uvtx][1 /* uv */][!b->intra];
- w4 >>= s->ss_h;
- end_x >>= s->ss_h;
- h4 >>= s->ss_v;
- end_y >>= s->ss_v;
- for (pl = 0; pl < 2; pl++) {
- a = &s->above_uv_nnz_ctx[pl][col << !s->ss_h];
- l = &s->left_uv_nnz_ctx[pl][(row & 7) << !s->ss_v];
- switch (b->uvtx) {
- case TX_4X4:
- DECODE_UV_COEF_LOOP(1,);
- break;
- case TX_8X8:
- MERGE_CTX(2, AV_RN16A);
- DECODE_UV_COEF_LOOP(2,);
- SPLAT_CTX(2);
- break;
- case TX_16X16:
- MERGE_CTX(4, AV_RN32A);
- DECODE_UV_COEF_LOOP(4,);
- SPLAT_CTX(4);
- break;
- case TX_32X32:
- MERGE_CTX(8, AV_RN64A);
- DECODE_UV_COEF_LOOP(8, 32);
- SPLAT_CTX(8);
- break;
- }
- }
-
- return total_coeff;
-}
-
-static int decode_coeffs_8bpp(AVCodecContext *ctx)
-{
- return decode_coeffs(ctx, 1);
-}
-
-static int decode_coeffs_16bpp(AVCodecContext *ctx)
-{
- return decode_coeffs(ctx, 0);
-}
-
-static av_always_inline int check_intra_mode(VP9Context *s, int mode, uint8_t **a,
- uint8_t *dst_edge, ptrdiff_t stride_edge,
- uint8_t *dst_inner, ptrdiff_t stride_inner,
- uint8_t *l, int col, int x, int w,
- int row, int y, enum TxfmMode tx,
- int p, int ss_h, int ss_v, int bytesperpixel)
-{
- int have_top = row > 0 || y > 0;
- int have_left = col > s->tile_col_start || x > 0;
- int have_right = x < w - 1;
- int bpp = s->bpp;
- static const uint8_t mode_conv[10][2 /* have_left */][2 /* have_top */] = {
- [VERT_PRED] = { { DC_127_PRED, VERT_PRED },
- { DC_127_PRED, VERT_PRED } },
- [HOR_PRED] = { { DC_129_PRED, DC_129_PRED },
- { HOR_PRED, HOR_PRED } },
- [DC_PRED] = { { DC_128_PRED, TOP_DC_PRED },
- { LEFT_DC_PRED, DC_PRED } },
- [DIAG_DOWN_LEFT_PRED] = { { DC_127_PRED, DIAG_DOWN_LEFT_PRED },
- { DC_127_PRED, DIAG_DOWN_LEFT_PRED } },
- [DIAG_DOWN_RIGHT_PRED] = { { DIAG_DOWN_RIGHT_PRED, DIAG_DOWN_RIGHT_PRED },
- { DIAG_DOWN_RIGHT_PRED, DIAG_DOWN_RIGHT_PRED } },
- [VERT_RIGHT_PRED] = { { VERT_RIGHT_PRED, VERT_RIGHT_PRED },
- { VERT_RIGHT_PRED, VERT_RIGHT_PRED } },
- [HOR_DOWN_PRED] = { { HOR_DOWN_PRED, HOR_DOWN_PRED },
- { HOR_DOWN_PRED, HOR_DOWN_PRED } },
- [VERT_LEFT_PRED] = { { DC_127_PRED, VERT_LEFT_PRED },
- { DC_127_PRED, VERT_LEFT_PRED } },
- [HOR_UP_PRED] = { { DC_129_PRED, DC_129_PRED },
- { HOR_UP_PRED, HOR_UP_PRED } },
- [TM_VP8_PRED] = { { DC_129_PRED, VERT_PRED },
- { HOR_PRED, TM_VP8_PRED } },
- };
- static const struct {
- uint8_t needs_left:1;
- uint8_t needs_top:1;
- uint8_t needs_topleft:1;
- uint8_t needs_topright:1;
- uint8_t invert_left:1;
- } edges[N_INTRA_PRED_MODES] = {
- [VERT_PRED] = { .needs_top = 1 },
- [HOR_PRED] = { .needs_left = 1 },
- [DC_PRED] = { .needs_top = 1, .needs_left = 1 },
- [DIAG_DOWN_LEFT_PRED] = { .needs_top = 1, .needs_topright = 1 },
- [DIAG_DOWN_RIGHT_PRED] = { .needs_left = 1, .needs_top = 1, .needs_topleft = 1 },
- [VERT_RIGHT_PRED] = { .needs_left = 1, .needs_top = 1, .needs_topleft = 1 },
- [HOR_DOWN_PRED] = { .needs_left = 1, .needs_top = 1, .needs_topleft = 1 },
- [VERT_LEFT_PRED] = { .needs_top = 1, .needs_topright = 1 },
- [HOR_UP_PRED] = { .needs_left = 1, .invert_left = 1 },
- [TM_VP8_PRED] = { .needs_left = 1, .needs_top = 1, .needs_topleft = 1 },
- [LEFT_DC_PRED] = { .needs_left = 1 },
- [TOP_DC_PRED] = { .needs_top = 1 },
- [DC_128_PRED] = { 0 },
- [DC_127_PRED] = { 0 },
- [DC_129_PRED] = { 0 }
- };
-
- av_assert2(mode >= 0 && mode < 10);
- mode = mode_conv[mode][have_left][have_top];
- if (edges[mode].needs_top) {
- uint8_t *top, *topleft;
- int n_px_need = 4 << tx, n_px_have = (((s->cols - col) << !ss_h) - x) * 4;
- int n_px_need_tr = 0;
-
- if (tx == TX_4X4 && edges[mode].needs_topright && have_right)
- n_px_need_tr = 4;
-
- // if top of sb64-row, use s->intra_pred_data[] instead of
- // dst[-stride] for intra prediction (it contains pre- instead of
- // post-loopfilter data)
- if (have_top) {
- top = !(row & 7) && !y ?
- s->intra_pred_data[p] + (col * (8 >> ss_h) + x * 4) * bytesperpixel :
- y == 0 ? &dst_edge[-stride_edge] : &dst_inner[-stride_inner];
- if (have_left)
- topleft = !(row & 7) && !y ?
- s->intra_pred_data[p] + (col * (8 >> ss_h) + x * 4) * bytesperpixel :
- y == 0 || x == 0 ? &dst_edge[-stride_edge] :
- &dst_inner[-stride_inner];
- }
-
- if (have_top &&
- (!edges[mode].needs_topleft || (have_left && top == topleft)) &&
- (tx != TX_4X4 || !edges[mode].needs_topright || have_right) &&
- n_px_need + n_px_need_tr <= n_px_have) {
- *a = top;
- } else {
- if (have_top) {
- if (n_px_need <= n_px_have) {
- memcpy(*a, top, n_px_need * bytesperpixel);
- } else {
-#define memset_bpp(c, i1, v, i2, num) do { \
- if (bytesperpixel == 1) { \
- memset(&(c)[(i1)], (v)[(i2)], (num)); \
- } else { \
- int n, val = AV_RN16A(&(v)[(i2) * 2]); \
- for (n = 0; n < (num); n++) { \
- AV_WN16A(&(c)[((i1) + n) * 2], val); \
- } \
- } \
-} while (0)
- memcpy(*a, top, n_px_have * bytesperpixel);
- memset_bpp(*a, n_px_have, (*a), n_px_have - 1, n_px_need - n_px_have);
- }
- } else {
-#define memset_val(c, val, num) do { \
- if (bytesperpixel == 1) { \
- memset((c), (val), (num)); \
- } else { \
- int n; \
- for (n = 0; n < (num); n++) { \
- AV_WN16A(&(c)[n * 2], (val)); \
- } \
- } \
-} while (0)
- memset_val(*a, (128 << (bpp - 8)) - 1, n_px_need);
- }
- if (edges[mode].needs_topleft) {
- if (have_left && have_top) {
-#define assign_bpp(c, i1, v, i2) do { \
- if (bytesperpixel == 1) { \
- (c)[(i1)] = (v)[(i2)]; \
- } else { \
- AV_COPY16(&(c)[(i1) * 2], &(v)[(i2) * 2]); \
- } \
-} while (0)
- assign_bpp(*a, -1, topleft, -1);
- } else {
-#define assign_val(c, i, v) do { \
- if (bytesperpixel == 1) { \
- (c)[(i)] = (v); \
- } else { \
- AV_WN16A(&(c)[(i) * 2], (v)); \
- } \
-} while (0)
- assign_val((*a), -1, (128 << (bpp - 8)) + (have_top ? +1 : -1));
- }
- }
- if (tx == TX_4X4 && edges[mode].needs_topright) {
- if (have_top && have_right &&
- n_px_need + n_px_need_tr <= n_px_have) {
- memcpy(&(*a)[4 * bytesperpixel], &top[4 * bytesperpixel], 4 * bytesperpixel);
- } else {
- memset_bpp(*a, 4, *a, 3, 4);
- }
- }
- }
- }
- if (edges[mode].needs_left) {
- if (have_left) {
- int n_px_need = 4 << tx, i, n_px_have = (((s->rows - row) << !ss_v) - y) * 4;
- uint8_t *dst = x == 0 ? dst_edge : dst_inner;
- ptrdiff_t stride = x == 0 ? stride_edge : stride_inner;
-
- if (edges[mode].invert_left) {
- if (n_px_need <= n_px_have) {
- for (i = 0; i < n_px_need; i++)
- assign_bpp(l, i, &dst[i * stride], -1);
- } else {
- for (i = 0; i < n_px_have; i++)
- assign_bpp(l, i, &dst[i * stride], -1);
- memset_bpp(l, n_px_have, l, n_px_have - 1, n_px_need - n_px_have);
- }
- } else {
- if (n_px_need <= n_px_have) {
- for (i = 0; i < n_px_need; i++)
- assign_bpp(l, n_px_need - 1 - i, &dst[i * stride], -1);
- } else {
- for (i = 0; i < n_px_have; i++)
- assign_bpp(l, n_px_need - 1 - i, &dst[i * stride], -1);
- memset_bpp(l, 0, l, n_px_need - n_px_have, n_px_need - n_px_have);
- }
- }
- } else {
- memset_val(l, (128 << (bpp - 8)) + 1, 4 << tx);
- }
- }
-
- return mode;
-}
-
-static av_always_inline void intra_recon(AVCodecContext *ctx, ptrdiff_t y_off,
- ptrdiff_t uv_off, int bytesperpixel)
-{
- VP9Context *s = ctx->priv_data;
- VP9Block *b = s->b;
- int row = s->row, col = s->col;
- int w4 = bwh_tab[1][b->bs][0] << 1, step1d = 1 << b->tx, n;
- int h4 = bwh_tab[1][b->bs][1] << 1, x, y, step = 1 << (b->tx * 2);
- int end_x = FFMIN(2 * (s->cols - col), w4);
- int end_y = FFMIN(2 * (s->rows - row), h4);
- int tx = 4 * s->s.h.lossless + b->tx, uvtx = b->uvtx + 4 * s->s.h.lossless;
- int uvstep1d = 1 << b->uvtx, p;
- uint8_t *dst = s->dst[0], *dst_r = s->s.frames[CUR_FRAME].tf.f->data[0] + y_off;
- LOCAL_ALIGNED_32(uint8_t, a_buf, [96]);
- LOCAL_ALIGNED_32(uint8_t, l, [64]);
-
- for (n = 0, y = 0; y < end_y; y += step1d) {
- uint8_t *ptr = dst, *ptr_r = dst_r;
- for (x = 0; x < end_x; x += step1d, ptr += 4 * step1d * bytesperpixel,
- ptr_r += 4 * step1d * bytesperpixel, n += step) {
- int mode = b->mode[b->bs > BS_8x8 && b->tx == TX_4X4 ?
- y * 2 + x : 0];
- uint8_t *a = &a_buf[32];
- enum TxfmType txtp = vp9_intra_txfm_type[mode];
- int eob = b->skip ? 0 : b->tx > TX_8X8 ? AV_RN16A(&s->eob[n]) : s->eob[n];
-
- mode = check_intra_mode(s, mode, &a, ptr_r,
- s->s.frames[CUR_FRAME].tf.f->linesize[0],
- ptr, s->y_stride, l,
- col, x, w4, row, y, b->tx, 0, 0, 0, bytesperpixel);
- s->dsp.intra_pred[b->tx][mode](ptr, s->y_stride, l, a);
- if (eob)
- s->dsp.itxfm_add[tx][txtp](ptr, s->y_stride,
- s->block + 16 * n * bytesperpixel, eob);
- }
- dst_r += 4 * step1d * s->s.frames[CUR_FRAME].tf.f->linesize[0];
- dst += 4 * step1d * s->y_stride;
- }
-
- // U/V
- w4 >>= s->ss_h;
- end_x >>= s->ss_h;
- end_y >>= s->ss_v;
- step = 1 << (b->uvtx * 2);
- for (p = 0; p < 2; p++) {
- dst = s->dst[1 + p];
- dst_r = s->s.frames[CUR_FRAME].tf.f->data[1 + p] + uv_off;
- for (n = 0, y = 0; y < end_y; y += uvstep1d) {
- uint8_t *ptr = dst, *ptr_r = dst_r;
- for (x = 0; x < end_x; x += uvstep1d, ptr += 4 * uvstep1d * bytesperpixel,
- ptr_r += 4 * uvstep1d * bytesperpixel, n += step) {
- int mode = b->uvmode;
- uint8_t *a = &a_buf[32];
- int eob = b->skip ? 0 : b->uvtx > TX_8X8 ? AV_RN16A(&s->uveob[p][n]) : s->uveob[p][n];
-
- mode = check_intra_mode(s, mode, &a, ptr_r,
- s->s.frames[CUR_FRAME].tf.f->linesize[1],
- ptr, s->uv_stride, l, col, x, w4, row, y,
- b->uvtx, p + 1, s->ss_h, s->ss_v, bytesperpixel);
- s->dsp.intra_pred[b->uvtx][mode](ptr, s->uv_stride, l, a);
- if (eob)
- s->dsp.itxfm_add[uvtx][DCT_DCT](ptr, s->uv_stride,
- s->uvblock[p] + 16 * n * bytesperpixel, eob);
- }
- dst_r += 4 * uvstep1d * s->s.frames[CUR_FRAME].tf.f->linesize[1];
- dst += 4 * uvstep1d * s->uv_stride;
- }
- }
-}
-
-static void intra_recon_8bpp(AVCodecContext *ctx, ptrdiff_t y_off, ptrdiff_t uv_off)
-{
- intra_recon(ctx, y_off, uv_off, 1);
-}
-
-static void intra_recon_16bpp(AVCodecContext *ctx, ptrdiff_t y_off, ptrdiff_t uv_off)
-{
- intra_recon(ctx, y_off, uv_off, 2);
-}
-
-static av_always_inline void mc_luma_unscaled(VP9Context *s, vp9_mc_func (*mc)[2],
- uint8_t *dst, ptrdiff_t dst_stride,
- const uint8_t *ref, ptrdiff_t ref_stride,
- ThreadFrame *ref_frame,
- ptrdiff_t y, ptrdiff_t x, const VP56mv *mv,
- int bw, int bh, int w, int h, int bytesperpixel)
-{
- int mx = mv->x, my = mv->y, th;
-
- y += my >> 3;
- x += mx >> 3;
- ref += y * ref_stride + x * bytesperpixel;
- mx &= 7;
- my &= 7;
- // FIXME bilinear filter only needs 0/1 pixels, not 3/4
- // we use +7 because the last 7 pixels of each sbrow can be changed in
- // the longest loopfilter of the next sbrow
- th = (y + bh + 4 * !!my + 7) >> 6;
- ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);
- if (x < !!mx * 3 || y < !!my * 3 ||
- x + !!mx * 4 > w - bw || y + !!my * 4 > h - bh) {
- s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
- ref - !!my * 3 * ref_stride - !!mx * 3 * bytesperpixel,
- 160, ref_stride,
- bw + !!mx * 7, bh + !!my * 7,
- x - !!mx * 3, y - !!my * 3, w, h);
- ref = s->edge_emu_buffer + !!my * 3 * 160 + !!mx * 3 * bytesperpixel;
- ref_stride = 160;
- }
- mc[!!mx][!!my](dst, dst_stride, ref, ref_stride, bh, mx << 1, my << 1);
-}
-
-static av_always_inline void mc_chroma_unscaled(VP9Context *s, vp9_mc_func (*mc)[2],
- uint8_t *dst_u, uint8_t *dst_v,
- ptrdiff_t dst_stride,
- const uint8_t *ref_u, ptrdiff_t src_stride_u,
- const uint8_t *ref_v, ptrdiff_t src_stride_v,
- ThreadFrame *ref_frame,
- ptrdiff_t y, ptrdiff_t x, const VP56mv *mv,
- int bw, int bh, int w, int h, int bytesperpixel)
-{
- int mx = mv->x * (1 << !s->ss_h), my = mv->y * (1 << !s->ss_v), th;
-
- y += my >> 4;
- x += mx >> 4;
- ref_u += y * src_stride_u + x * bytesperpixel;
- ref_v += y * src_stride_v + x * bytesperpixel;
- mx &= 15;
- my &= 15;
- // FIXME bilinear filter only needs 0/1 pixels, not 3/4
- // we use +7 because the last 7 pixels of each sbrow can be changed in
- // the longest loopfilter of the next sbrow
- th = (y + bh + 4 * !!my + 7) >> (6 - s->ss_v);
- ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);
- if (x < !!mx * 3 || y < !!my * 3 ||
- x + !!mx * 4 > w - bw || y + !!my * 4 > h - bh) {
- s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
- ref_u - !!my * 3 * src_stride_u - !!mx * 3 * bytesperpixel,
- 160, src_stride_u,
- bw + !!mx * 7, bh + !!my * 7,
- x - !!mx * 3, y - !!my * 3, w, h);
- ref_u = s->edge_emu_buffer + !!my * 3 * 160 + !!mx * 3 * bytesperpixel;
- mc[!!mx][!!my](dst_u, dst_stride, ref_u, 160, bh, mx, my);
-
- s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
- ref_v - !!my * 3 * src_stride_v - !!mx * 3 * bytesperpixel,
- 160, src_stride_v,
- bw + !!mx * 7, bh + !!my * 7,
- x - !!mx * 3, y - !!my * 3, w, h);
- ref_v = s->edge_emu_buffer + !!my * 3 * 160 + !!mx * 3 * bytesperpixel;
- mc[!!mx][!!my](dst_v, dst_stride, ref_v, 160, bh, mx, my);
- } else {
- mc[!!mx][!!my](dst_u, dst_stride, ref_u, src_stride_u, bh, mx, my);
- mc[!!mx][!!my](dst_v, dst_stride, ref_v, src_stride_v, bh, mx, my);
- }
-}
-
-#define mc_luma_dir(s, mc, dst, dst_ls, src, src_ls, tref, row, col, mv, \
- px, py, pw, ph, bw, bh, w, h, i) \
- mc_luma_unscaled(s, s->dsp.mc, dst, dst_ls, src, src_ls, tref, row, col, \
- mv, bw, bh, w, h, bytesperpixel)
-#define mc_chroma_dir(s, mc, dstu, dstv, dst_ls, srcu, srcu_ls, srcv, srcv_ls, tref, \
- row, col, mv, px, py, pw, ph, bw, bh, w, h, i) \
- mc_chroma_unscaled(s, s->dsp.mc, dstu, dstv, dst_ls, srcu, srcu_ls, srcv, srcv_ls, tref, \
- row, col, mv, bw, bh, w, h, bytesperpixel)
-#define SCALED 0
-#define FN(x) x##_8bpp
-#define BYTES_PER_PIXEL 1
-#include "vp9_mc_template.c"
-#undef FN
-#undef BYTES_PER_PIXEL
-#define FN(x) x##_16bpp
-#define BYTES_PER_PIXEL 2
-#include "vp9_mc_template.c"
-#undef mc_luma_dir
-#undef mc_chroma_dir
-#undef FN
-#undef BYTES_PER_PIXEL
-#undef SCALED
-
-static av_always_inline void mc_luma_scaled(VP9Context *s, vp9_scaled_mc_func smc,
- vp9_mc_func (*mc)[2],
- uint8_t *dst, ptrdiff_t dst_stride,
- const uint8_t *ref, ptrdiff_t ref_stride,
- ThreadFrame *ref_frame,
- ptrdiff_t y, ptrdiff_t x, const VP56mv *in_mv,
- int px, int py, int pw, int ph,
- int bw, int bh, int w, int h, int bytesperpixel,
- const uint16_t *scale, const uint8_t *step)
-{
- if (s->s.frames[CUR_FRAME].tf.f->width == ref_frame->f->width &&
- s->s.frames[CUR_FRAME].tf.f->height == ref_frame->f->height) {
- mc_luma_unscaled(s, mc, dst, dst_stride, ref, ref_stride, ref_frame,
- y, x, in_mv, bw, bh, w, h, bytesperpixel);
- } else {
-#define scale_mv(n, dim) (((int64_t)(n) * scale[dim]) >> 14)
- int mx, my;
- int refbw_m1, refbh_m1;
- int th;
- VP56mv mv;
-
- mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 8, (s->cols * 8 - x + px + 3) * 8);
- mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 8, (s->rows * 8 - y + py + 3) * 8);
- // BUG libvpx seems to scale the two components separately. This introduces
- // rounding errors but we have to reproduce them to be exactly compatible
- // with the output from libvpx...
- mx = scale_mv(mv.x * 2, 0) + scale_mv(x * 16, 0);
- my = scale_mv(mv.y * 2, 1) + scale_mv(y * 16, 1);
-
- y = my >> 4;
- x = mx >> 4;
- ref += y * ref_stride + x * bytesperpixel;
- mx &= 15;
- my &= 15;
- refbw_m1 = ((bw - 1) * step[0] + mx) >> 4;
- refbh_m1 = ((bh - 1) * step[1] + my) >> 4;
- // FIXME bilinear filter only needs 0/1 pixels, not 3/4
- // we use +7 because the last 7 pixels of each sbrow can be changed in
- // the longest loopfilter of the next sbrow
- th = (y + refbh_m1 + 4 + 7) >> 6;
- ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);
- if (x < 3 || y < 3 || x + 4 >= w - refbw_m1 || y + 4 >= h - refbh_m1) {
- s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
- ref - 3 * ref_stride - 3 * bytesperpixel,
- 288, ref_stride,
- refbw_m1 + 8, refbh_m1 + 8,
- x - 3, y - 3, w, h);
- ref = s->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;
- ref_stride = 288;
- }
- smc(dst, dst_stride, ref, ref_stride, bh, mx, my, step[0], step[1]);
- }
-}
-
-static av_always_inline void mc_chroma_scaled(VP9Context *s, vp9_scaled_mc_func smc,
- vp9_mc_func (*mc)[2],
- uint8_t *dst_u, uint8_t *dst_v,
- ptrdiff_t dst_stride,
- const uint8_t *ref_u, ptrdiff_t src_stride_u,
- const uint8_t *ref_v, ptrdiff_t src_stride_v,
- ThreadFrame *ref_frame,
- ptrdiff_t y, ptrdiff_t x, const VP56mv *in_mv,
- int px, int py, int pw, int ph,
- int bw, int bh, int w, int h, int bytesperpixel,
- const uint16_t *scale, const uint8_t *step)
-{
- if (s->s.frames[CUR_FRAME].tf.f->width == ref_frame->f->width &&
- s->s.frames[CUR_FRAME].tf.f->height == ref_frame->f->height) {
- mc_chroma_unscaled(s, mc, dst_u, dst_v, dst_stride, ref_u, src_stride_u,
- ref_v, src_stride_v, ref_frame,
- y, x, in_mv, bw, bh, w, h, bytesperpixel);
- } else {
- int mx, my;
- int refbw_m1, refbh_m1;
- int th;
- VP56mv mv;
-
- if (s->ss_h) {
- // BUG https://code.google.com/p/webm/issues/detail?id=820
- mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 16, (s->cols * 4 - x + px + 3) * 16);
- mx = scale_mv(mv.x, 0) + (scale_mv(x * 16, 0) & ~15) + (scale_mv(x * 32, 0) & 15);
- } else {
- mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 8, (s->cols * 8 - x + px + 3) * 8);
- mx = scale_mv(mv.x * 2, 0) + scale_mv(x * 16, 0);
- }
- if (s->ss_v) {
- // BUG https://code.google.com/p/webm/issues/detail?id=820
- mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 16, (s->rows * 4 - y + py + 3) * 16);
- my = scale_mv(mv.y, 1) + (scale_mv(y * 16, 1) & ~15) + (scale_mv(y * 32, 1) & 15);
- } else {
- mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 8, (s->rows * 8 - y + py + 3) * 8);
- my = scale_mv(mv.y * 2, 1) + scale_mv(y * 16, 1);
- }
-#undef scale_mv
- y = my >> 4;
- x = mx >> 4;
- ref_u += y * src_stride_u + x * bytesperpixel;
- ref_v += y * src_stride_v + x * bytesperpixel;
- mx &= 15;
- my &= 15;
- refbw_m1 = ((bw - 1) * step[0] + mx) >> 4;
- refbh_m1 = ((bh - 1) * step[1] + my) >> 4;
- // FIXME bilinear filter only needs 0/1 pixels, not 3/4
- // we use +7 because the last 7 pixels of each sbrow can be changed in
- // the longest loopfilter of the next sbrow
- th = (y + refbh_m1 + 4 + 7) >> (6 - s->ss_v);
- ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);
- if (x < 3 || y < 3 || x + 4 >= w - refbw_m1 || y + 4 >= h - refbh_m1) {
- s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
- ref_u - 3 * src_stride_u - 3 * bytesperpixel,
- 288, src_stride_u,
- refbw_m1 + 8, refbh_m1 + 8,
- x - 3, y - 3, w, h);
- ref_u = s->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;
- smc(dst_u, dst_stride, ref_u, 288, bh, mx, my, step[0], step[1]);
-
- s->vdsp.emulated_edge_mc(s->edge_emu_buffer,
- ref_v - 3 * src_stride_v - 3 * bytesperpixel,
- 288, src_stride_v,
- refbw_m1 + 8, refbh_m1 + 8,
- x - 3, y - 3, w, h);
- ref_v = s->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;
- smc(dst_v, dst_stride, ref_v, 288, bh, mx, my, step[0], step[1]);
- } else {
- smc(dst_u, dst_stride, ref_u, src_stride_u, bh, mx, my, step[0], step[1]);
- smc(dst_v, dst_stride, ref_v, src_stride_v, bh, mx, my, step[0], step[1]);
- }
- }
-}
-
-#define mc_luma_dir(s, mc, dst, dst_ls, src, src_ls, tref, row, col, mv, \
- px, py, pw, ph, bw, bh, w, h, i) \
- mc_luma_scaled(s, s->dsp.s##mc, s->dsp.mc, dst, dst_ls, src, src_ls, tref, row, col, \
- mv, px, py, pw, ph, bw, bh, w, h, bytesperpixel, \
- s->mvscale[b->ref[i]], s->mvstep[b->ref[i]])
-#define mc_chroma_dir(s, mc, dstu, dstv, dst_ls, srcu, srcu_ls, srcv, srcv_ls, tref, \
- row, col, mv, px, py, pw, ph, bw, bh, w, h, i) \
- mc_chroma_scaled(s, s->dsp.s##mc, s->dsp.mc, dstu, dstv, dst_ls, srcu, srcu_ls, srcv, srcv_ls, tref, \
- row, col, mv, px, py, pw, ph, bw, bh, w, h, bytesperpixel, \
- s->mvscale[b->ref[i]], s->mvstep[b->ref[i]])
-#define SCALED 1
-#define FN(x) x##_scaled_8bpp
-#define BYTES_PER_PIXEL 1
-#include "vp9_mc_template.c"
-#undef FN
-#undef BYTES_PER_PIXEL
-#define FN(x) x##_scaled_16bpp
-#define BYTES_PER_PIXEL 2
-#include "vp9_mc_template.c"
-#undef mc_luma_dir
-#undef mc_chroma_dir
-#undef FN
-#undef BYTES_PER_PIXEL
-#undef SCALED
-
-static av_always_inline void inter_recon(AVCodecContext *ctx, int bytesperpixel)
-{
- VP9Context *s = ctx->priv_data;
- VP9Block *b = s->b;
- int row = s->row, col = s->col;
-
- if (s->mvscale[b->ref[0]][0] || (b->comp && s->mvscale[b->ref[1]][0])) {
- if (bytesperpixel == 1) {
- inter_pred_scaled_8bpp(ctx);
- } else {
- inter_pred_scaled_16bpp(ctx);
- }
- } else {
- if (bytesperpixel == 1) {
- inter_pred_8bpp(ctx);
- } else {
- inter_pred_16bpp(ctx);
- }
- }
- if (!b->skip) {
- /* mostly copied intra_recon() */
-
- int w4 = bwh_tab[1][b->bs][0] << 1, step1d = 1 << b->tx, n;
- int h4 = bwh_tab[1][b->bs][1] << 1, x, y, step = 1 << (b->tx * 2);
- int end_x = FFMIN(2 * (s->cols - col), w4);
- int end_y = FFMIN(2 * (s->rows - row), h4);
- int tx = 4 * s->s.h.lossless + b->tx, uvtx = b->uvtx + 4 * s->s.h.lossless;
- int uvstep1d = 1 << b->uvtx, p;
- uint8_t *dst = s->dst[0];
-
- // y itxfm add
- for (n = 0, y = 0; y < end_y; y += step1d) {
- uint8_t *ptr = dst;
- for (x = 0; x < end_x; x += step1d,
- ptr += 4 * step1d * bytesperpixel, n += step) {
- int eob = b->tx > TX_8X8 ? AV_RN16A(&s->eob[n]) : s->eob[n];
-
- if (eob)
- s->dsp.itxfm_add[tx][DCT_DCT](ptr, s->y_stride,
- s->block + 16 * n * bytesperpixel, eob);
- }
- dst += 4 * s->y_stride * step1d;
- }
-
- // uv itxfm add
- end_x >>= s->ss_h;
- end_y >>= s->ss_v;
- step = 1 << (b->uvtx * 2);
- for (p = 0; p < 2; p++) {
- dst = s->dst[p + 1];
- for (n = 0, y = 0; y < end_y; y += uvstep1d) {
- uint8_t *ptr = dst;
- for (x = 0; x < end_x; x += uvstep1d,
- ptr += 4 * uvstep1d * bytesperpixel, n += step) {
- int eob = b->uvtx > TX_8X8 ? AV_RN16A(&s->uveob[p][n]) : s->uveob[p][n];
-
- if (eob)
- s->dsp.itxfm_add[uvtx][DCT_DCT](ptr, s->uv_stride,
- s->uvblock[p] + 16 * n * bytesperpixel, eob);
- }
- dst += 4 * uvstep1d * s->uv_stride;
- }
- }
- }
-}
-
-static void inter_recon_8bpp(AVCodecContext *ctx)
-{
- inter_recon(ctx, 1);
-}
-
-static void inter_recon_16bpp(AVCodecContext *ctx)
-{
- inter_recon(ctx, 2);
-}
-
-static av_always_inline void mask_edges(uint8_t (*mask)[8][4], int ss_h, int ss_v,
- int row_and_7, int col_and_7,
- int w, int h, int col_end, int row_end,
- enum TxfmMode tx, int skip_inter)
-{
- static const unsigned wide_filter_col_mask[2] = { 0x11, 0x01 };
- static const unsigned wide_filter_row_mask[2] = { 0x03, 0x07 };
-
- // FIXME I'm pretty sure all loops can be replaced by a single LUT if
- // we make VP9Filter.mask uint64_t (i.e. row/col all single variable)
- // and make the LUT 5-indexed (bl, bp, is_uv, tx and row/col), and then
- // use row_and_7/col_and_7 as shifts (1*col_and_7+8*row_and_7)
-
- // the intended behaviour of the vp9 loopfilter is to work on 8-pixel
- // edges. This means that for UV, we work on two subsampled blocks at
- // a time, and we only use the topleft block's mode information to set
- // things like block strength. Thus, for any block size smaller than
- // 16x16, ignore the odd portion of the block.
- if (tx == TX_4X4 && (ss_v | ss_h)) {
- if (h == ss_v) {
- if (row_and_7 & 1)
- return;
- if (!row_end)
- h += 1;
- }
- if (w == ss_h) {
- if (col_and_7 & 1)
- return;
- if (!col_end)
- w += 1;
- }
- }
-
- if (tx == TX_4X4 && !skip_inter) {
- int t = 1 << col_and_7, m_col = (t << w) - t, y;
- // on 32-px edges, use the 8-px wide loopfilter; else, use 4-px wide
- int m_row_8 = m_col & wide_filter_col_mask[ss_h], m_row_4 = m_col - m_row_8;
-
- for (y = row_and_7; y < h + row_and_7; y++) {
- int col_mask_id = 2 - !(y & wide_filter_row_mask[ss_v]);
-
- mask[0][y][1] |= m_row_8;
- mask[0][y][2] |= m_row_4;
- // for odd lines, if the odd col is not being filtered,
- // skip odd row also:
- // .---. <-- a
- // | |
- // |___| <-- b
- // ^ ^
- // c d
- //
- // if a/c are even row/col and b/d are odd, and d is skipped,
- // e.g. right edge of size-66x66.webm, then skip b also (bug)
- if ((ss_h & ss_v) && (col_end & 1) && (y & 1)) {
- mask[1][y][col_mask_id] |= (t << (w - 1)) - t;
- } else {
- mask[1][y][col_mask_id] |= m_col;
- }
- if (!ss_h)
- mask[0][y][3] |= m_col;
- if (!ss_v) {
- if (ss_h && (col_end & 1))
- mask[1][y][3] |= (t << (w - 1)) - t;
- else
- mask[1][y][3] |= m_col;
- }
- }
- } else {
- int y, t = 1 << col_and_7, m_col = (t << w) - t;
-
- if (!skip_inter) {
- int mask_id = (tx == TX_8X8);
- static const unsigned masks[4] = { 0xff, 0x55, 0x11, 0x01 };
- int l2 = tx + ss_h - 1, step1d;
- int m_row = m_col & masks[l2];
-
- // at odd UV col/row edges tx16/tx32 loopfilter edges, force
- // 8wd loopfilter to prevent going off the visible edge.
- if (ss_h && tx > TX_8X8 && (w ^ (w - 1)) == 1) {
- int m_row_16 = ((t << (w - 1)) - t) & masks[l2];
- int m_row_8 = m_row - m_row_16;
-
- for (y = row_and_7; y < h + row_and_7; y++) {
- mask[0][y][0] |= m_row_16;
- mask[0][y][1] |= m_row_8;
- }
- } else {
- for (y = row_and_7; y < h + row_and_7; y++)
- mask[0][y][mask_id] |= m_row;
- }
-
- l2 = tx + ss_v - 1;
- step1d = 1 << l2;
- if (ss_v && tx > TX_8X8 && (h ^ (h - 1)) == 1) {
- for (y = row_and_7; y < h + row_and_7 - 1; y += step1d)
- mask[1][y][0] |= m_col;
- if (y - row_and_7 == h - 1)
- mask[1][y][1] |= m_col;
- } else {
- for (y = row_and_7; y < h + row_and_7; y += step1d)
- mask[1][y][mask_id] |= m_col;
- }
- } else if (tx != TX_4X4) {
- int mask_id;
-
- mask_id = (tx == TX_8X8) || (h == ss_v);
- mask[1][row_and_7][mask_id] |= m_col;
- mask_id = (tx == TX_8X8) || (w == ss_h);
- for (y = row_and_7; y < h + row_and_7; y++)
- mask[0][y][mask_id] |= t;
- } else {
- int t8 = t & wide_filter_col_mask[ss_h], t4 = t - t8;
-
- for (y = row_and_7; y < h + row_and_7; y++) {
- mask[0][y][2] |= t4;
- mask[0][y][1] |= t8;
- }
- mask[1][row_and_7][2 - !(row_and_7 & wide_filter_row_mask[ss_v])] |= m_col;
- }
- }
-}
-
-static void decode_b(AVCodecContext *ctx, int row, int col,
- struct VP9Filter *lflvl, ptrdiff_t yoff, ptrdiff_t uvoff,
- enum BlockLevel bl, enum BlockPartition bp)
-{
- VP9Context *s = ctx->priv_data;
- VP9Block *b = s->b;
- enum BlockSize bs = bl * 3 + bp;
- int bytesperpixel = s->bytesperpixel;
- int w4 = bwh_tab[1][bs][0], h4 = bwh_tab[1][bs][1], lvl;
- int emu[2];
- AVFrame *f = s->s.frames[CUR_FRAME].tf.f;
-
- s->row = row;
- s->row7 = row & 7;
- s->col = col;
- s->col7 = col & 7;
- s->min_mv.x = -(128 + col * 64);
- s->min_mv.y = -(128 + row * 64);
- s->max_mv.x = 128 + (s->cols - col - w4) * 64;
- s->max_mv.y = 128 + (s->rows - row - h4) * 64;
- if (s->pass < 2) {
- b->bs = bs;
- b->bl = bl;
- b->bp = bp;
- decode_mode(ctx);
- b->uvtx = b->tx - ((s->ss_h && w4 * 2 == (1 << b->tx)) ||
- (s->ss_v && h4 * 2 == (1 << b->tx)));
-
- if (!b->skip) {
- int has_coeffs;
-
- if (bytesperpixel == 1) {
- has_coeffs = decode_coeffs_8bpp(ctx);
- } else {
- has_coeffs = decode_coeffs_16bpp(ctx);
- }
- if (!has_coeffs && b->bs <= BS_8x8 && !b->intra) {
- b->skip = 1;
- memset(&s->above_skip_ctx[col], 1, w4);
- memset(&s->left_skip_ctx[s->row7], 1, h4);
- }
- } else {
- int row7 = s->row7;
-
-#define SPLAT_ZERO_CTX(v, n) \
- switch (n) { \
- case 1: v = 0; break; \
- case 2: AV_ZERO16(&v); break; \
- case 4: AV_ZERO32(&v); break; \
- case 8: AV_ZERO64(&v); break; \
- case 16: AV_ZERO128(&v); break; \
- }
-#define SPLAT_ZERO_YUV(dir, var, off, n, dir2) \
- do { \
- SPLAT_ZERO_CTX(s->dir##_y_##var[off * 2], n * 2); \
- if (s->ss_##dir2) { \
- SPLAT_ZERO_CTX(s->dir##_uv_##var[0][off], n); \
- SPLAT_ZERO_CTX(s->dir##_uv_##var[1][off], n); \
- } else { \
- SPLAT_ZERO_CTX(s->dir##_uv_##var[0][off * 2], n * 2); \
- SPLAT_ZERO_CTX(s->dir##_uv_##var[1][off * 2], n * 2); \
- } \
- } while (0)
-
- switch (w4) {
- case 1: SPLAT_ZERO_YUV(above, nnz_ctx, col, 1, h); break;
- case 2: SPLAT_ZERO_YUV(above, nnz_ctx, col, 2, h); break;
- case 4: SPLAT_ZERO_YUV(above, nnz_ctx, col, 4, h); break;
- case 8: SPLAT_ZERO_YUV(above, nnz_ctx, col, 8, h); break;
- }
- switch (h4) {
- case 1: SPLAT_ZERO_YUV(left, nnz_ctx, row7, 1, v); break;
- case 2: SPLAT_ZERO_YUV(left, nnz_ctx, row7, 2, v); break;
- case 4: SPLAT_ZERO_YUV(left, nnz_ctx, row7, 4, v); break;
- case 8: SPLAT_ZERO_YUV(left, nnz_ctx, row7, 8, v); break;
- }
- }
-
- if (s->pass == 1) {
- s->b++;
- s->block += w4 * h4 * 64 * bytesperpixel;
- s->uvblock[0] += w4 * h4 * 64 * bytesperpixel >> (s->ss_h + s->ss_v);
- s->uvblock[1] += w4 * h4 * 64 * bytesperpixel >> (s->ss_h + s->ss_v);
- s->eob += 4 * w4 * h4;
- s->uveob[0] += 4 * w4 * h4 >> (s->ss_h + s->ss_v);
- s->uveob[1] += 4 * w4 * h4 >> (s->ss_h + s->ss_v);
-
- return;
- }
- }
-
- // emulated overhangs if the stride of the target buffer can't hold. This
- // makes it possible to support emu-edge and so on even if we have large block
- // overhangs
- emu[0] = (col + w4) * 8 * bytesperpixel > f->linesize[0] ||
- (row + h4) > s->rows;
- emu[1] = ((col + w4) * 8 >> s->ss_h) * bytesperpixel > f->linesize[1] ||
- (row + h4) > s->rows;
- if (emu[0]) {
- s->dst[0] = s->tmp_y;
- s->y_stride = 128;
- } else {
- s->dst[0] = f->data[0] + yoff;
- s->y_stride = f->linesize[0];
- }
- if (emu[1]) {
- s->dst[1] = s->tmp_uv[0];
- s->dst[2] = s->tmp_uv[1];
- s->uv_stride = 128;
- } else {
- s->dst[1] = f->data[1] + uvoff;
- s->dst[2] = f->data[2] + uvoff;
- s->uv_stride = f->linesize[1];
- }
- if (b->intra) {
- if (s->bpp > 8) {
- intra_recon_16bpp(ctx, yoff, uvoff);
- } else {
- intra_recon_8bpp(ctx, yoff, uvoff);
- }
- } else {
- if (s->bpp > 8) {
- inter_recon_16bpp(ctx);
- } else {
- inter_recon_8bpp(ctx);
- }
- }
- if (emu[0]) {
- int w = FFMIN(s->cols - col, w4) * 8, h = FFMIN(s->rows - row, h4) * 8, n, o = 0;
-
- for (n = 0; o < w; n++) {
- int bw = 64 >> n;
-
- av_assert2(n <= 4);
- if (w & bw) {
- s->dsp.mc[n][0][0][0][0](f->data[0] + yoff + o * bytesperpixel, f->linesize[0],
- s->tmp_y + o * bytesperpixel, 128, h, 0, 0);
- o += bw;
- }
- }
- }
- if (emu[1]) {
- int w = FFMIN(s->cols - col, w4) * 8 >> s->ss_h;
- int h = FFMIN(s->rows - row, h4) * 8 >> s->ss_v, n, o = 0;
-
- for (n = s->ss_h; o < w; n++) {
- int bw = 64 >> n;
-
- av_assert2(n <= 4);
- if (w & bw) {
- s->dsp.mc[n][0][0][0][0](f->data[1] + uvoff + o * bytesperpixel, f->linesize[1],
- s->tmp_uv[0] + o * bytesperpixel, 128, h, 0, 0);
- s->dsp.mc[n][0][0][0][0](f->data[2] + uvoff + o * bytesperpixel, f->linesize[2],
- s->tmp_uv[1] + o * bytesperpixel, 128, h, 0, 0);
- o += bw;
- }
- }
- }
-
- // pick filter level and find edges to apply filter to
- if (s->s.h.filter.level &&
- (lvl = s->s.h.segmentation.feat[b->seg_id].lflvl[b->intra ? 0 : b->ref[0] + 1]
- [b->mode[3] != ZEROMV]) > 0) {
- int x_end = FFMIN(s->cols - col, w4), y_end = FFMIN(s->rows - row, h4);
- int skip_inter = !b->intra && b->skip, col7 = s->col7, row7 = s->row7;
-
- setctx_2d(&lflvl->level[row7 * 8 + col7], w4, h4, 8, lvl);
- mask_edges(lflvl->mask[0], 0, 0, row7, col7, x_end, y_end, 0, 0, b->tx, skip_inter);
- if (s->ss_h || s->ss_v)
- mask_edges(lflvl->mask[1], s->ss_h, s->ss_v, row7, col7, x_end, y_end,
- s->cols & 1 && col + w4 >= s->cols ? s->cols & 7 : 0,
- s->rows & 1 && row + h4 >= s->rows ? s->rows & 7 : 0,
- b->uvtx, skip_inter);
-
- if (!s->filter_lut.lim_lut[lvl]) {
- int sharp = s->s.h.filter.sharpness;
- int limit = lvl;
-
- if (sharp > 0) {
- limit >>= (sharp + 3) >> 2;
- limit = FFMIN(limit, 9 - sharp);
- }
- limit = FFMAX(limit, 1);
-
- s->filter_lut.lim_lut[lvl] = limit;
- s->filter_lut.mblim_lut[lvl] = 2 * (lvl + 2) + limit;
- }
- }
-
- if (s->pass == 2) {
- s->b++;
- s->block += w4 * h4 * 64 * bytesperpixel;
- s->uvblock[0] += w4 * h4 * 64 * bytesperpixel >> (s->ss_v + s->ss_h);
- s->uvblock[1] += w4 * h4 * 64 * bytesperpixel >> (s->ss_v + s->ss_h);
- s->eob += 4 * w4 * h4;
- s->uveob[0] += 4 * w4 * h4 >> (s->ss_v + s->ss_h);
- s->uveob[1] += 4 * w4 * h4 >> (s->ss_v + s->ss_h);
- }
-}
-
-static void decode_sb(AVCodecContext *ctx, int row, int col, struct VP9Filter *lflvl,
+static void decode_sb(VP9TileData *td, int row, int col, VP9Filter *lflvl,
ptrdiff_t yoff, ptrdiff_t uvoff, enum BlockLevel bl)
{
- VP9Context *s = ctx->priv_data;
+ const VP9Context *s = td->s;
int c = ((s->above_partition_ctx[col] >> (3 - bl)) & 1) |
- (((s->left_partition_ctx[row & 0x7] >> (3 - bl)) & 1) << 1);
- const uint8_t *p = s->s.h.keyframe || s->s.h.intraonly ? vp9_default_kf_partition_probs[bl][c] :
+ (((td->left_partition_ctx[row & 0x7] >> (3 - bl)) & 1) << 1);
+ const uint8_t *p = s->s.h.keyframe || s->s.h.intraonly ? ff_vp9_default_kf_partition_probs[bl][c] :
s->prob.p.partition[bl][c];
enum BlockPartition bp;
ptrdiff_t hbs = 4 >> bl;
@@ -3398,75 +1054,75 @@ static void decode_sb(AVCodecContext *ctx, int row, int col, struct VP9Filter *l
int bytesperpixel = s->bytesperpixel;
if (bl == BL_8X8) {
- bp = vp8_rac_get_tree(&s->c, vp9_partition_tree, p);
- decode_b(ctx, row, col, lflvl, yoff, uvoff, bl, bp);
+ bp = vp8_rac_get_tree(td->c, ff_vp9_partition_tree, p);
+ ff_vp9_decode_block(td, row, col, lflvl, yoff, uvoff, bl, bp);
} else if (col + hbs < s->cols) { // FIXME why not <=?
if (row + hbs < s->rows) { // FIXME why not <=?
- bp = vp8_rac_get_tree(&s->c, vp9_partition_tree, p);
+ bp = vp8_rac_get_tree(td->c, ff_vp9_partition_tree, p);
switch (bp) {
case PARTITION_NONE:
- decode_b(ctx, row, col, lflvl, yoff, uvoff, bl, bp);
+ ff_vp9_decode_block(td, row, col, lflvl, yoff, uvoff, bl, bp);
break;
case PARTITION_H:
- decode_b(ctx, row, col, lflvl, yoff, uvoff, bl, bp);
+ ff_vp9_decode_block(td, row, col, lflvl, yoff, uvoff, bl, bp);
yoff += hbs * 8 * y_stride;
uvoff += hbs * 8 * uv_stride >> s->ss_v;
- decode_b(ctx, row + hbs, col, lflvl, yoff, uvoff, bl, bp);
+ ff_vp9_decode_block(td, row + hbs, col, lflvl, yoff, uvoff, bl, bp);
break;
case PARTITION_V:
- decode_b(ctx, row, col, lflvl, yoff, uvoff, bl, bp);
+ ff_vp9_decode_block(td, row, col, lflvl, yoff, uvoff, bl, bp);
yoff += hbs * 8 * bytesperpixel;
uvoff += hbs * 8 * bytesperpixel >> s->ss_h;
- decode_b(ctx, row, col + hbs, lflvl, yoff, uvoff, bl, bp);
+ ff_vp9_decode_block(td, row, col + hbs, lflvl, yoff, uvoff, bl, bp);
break;
case PARTITION_SPLIT:
- decode_sb(ctx, row, col, lflvl, yoff, uvoff, bl + 1);
- decode_sb(ctx, row, col + hbs, lflvl,
+ decode_sb(td, row, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb(td, row, col + hbs, lflvl,
yoff + 8 * hbs * bytesperpixel,
uvoff + (8 * hbs * bytesperpixel >> s->ss_h), bl + 1);
yoff += hbs * 8 * y_stride;
uvoff += hbs * 8 * uv_stride >> s->ss_v;
- decode_sb(ctx, row + hbs, col, lflvl, yoff, uvoff, bl + 1);
- decode_sb(ctx, row + hbs, col + hbs, lflvl,
+ decode_sb(td, row + hbs, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb(td, row + hbs, col + hbs, lflvl,
yoff + 8 * hbs * bytesperpixel,
uvoff + (8 * hbs * bytesperpixel >> s->ss_h), bl + 1);
break;
default:
av_assert0(0);
}
- } else if (vp56_rac_get_prob_branchy(&s->c, p[1])) {
+ } else if (vp56_rac_get_prob_branchy(td->c, p[1])) {
bp = PARTITION_SPLIT;
- decode_sb(ctx, row, col, lflvl, yoff, uvoff, bl + 1);
- decode_sb(ctx, row, col + hbs, lflvl,
+ decode_sb(td, row, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb(td, row, col + hbs, lflvl,
yoff + 8 * hbs * bytesperpixel,
uvoff + (8 * hbs * bytesperpixel >> s->ss_h), bl + 1);
} else {
bp = PARTITION_H;
- decode_b(ctx, row, col, lflvl, yoff, uvoff, bl, bp);
+ ff_vp9_decode_block(td, row, col, lflvl, yoff, uvoff, bl, bp);
}
} else if (row + hbs < s->rows) { // FIXME why not <=?
- if (vp56_rac_get_prob_branchy(&s->c, p[2])) {
+ if (vp56_rac_get_prob_branchy(td->c, p[2])) {
bp = PARTITION_SPLIT;
- decode_sb(ctx, row, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb(td, row, col, lflvl, yoff, uvoff, bl + 1);
yoff += hbs * 8 * y_stride;
uvoff += hbs * 8 * uv_stride >> s->ss_v;
- decode_sb(ctx, row + hbs, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb(td, row + hbs, col, lflvl, yoff, uvoff, bl + 1);
} else {
bp = PARTITION_V;
- decode_b(ctx, row, col, lflvl, yoff, uvoff, bl, bp);
+ ff_vp9_decode_block(td, row, col, lflvl, yoff, uvoff, bl, bp);
}
} else {
bp = PARTITION_SPLIT;
- decode_sb(ctx, row, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb(td, row, col, lflvl, yoff, uvoff, bl + 1);
}
- s->counts.partition[bl][c][bp]++;
+ td->counts.partition[bl][c][bp]++;
}
-static void decode_sb_mem(AVCodecContext *ctx, int row, int col, struct VP9Filter *lflvl,
+static void decode_sb_mem(VP9TileData *td, int row, int col, VP9Filter *lflvl,
ptrdiff_t yoff, ptrdiff_t uvoff, enum BlockLevel bl)
{
- VP9Context *s = ctx->priv_data;
- VP9Block *b = s->b;
+ const VP9Context *s = td->s;
+ VP9Block *b = td->b;
ptrdiff_t hbs = 4 >> bl;
AVFrame *f = s->s.frames[CUR_FRAME].tf.f;
ptrdiff_t y_stride = f->linesize[0], uv_stride = f->linesize[1];
@@ -3474,221 +1130,43 @@ static void decode_sb_mem(AVCodecContext *ctx, int row, int col, struct VP9Filte
if (bl == BL_8X8) {
av_assert2(b->bl == BL_8X8);
- decode_b(ctx, row, col, lflvl, yoff, uvoff, b->bl, b->bp);
- } else if (s->b->bl == bl) {
- decode_b(ctx, row, col, lflvl, yoff, uvoff, b->bl, b->bp);
+ ff_vp9_decode_block(td, row, col, lflvl, yoff, uvoff, b->bl, b->bp);
+ } else if (td->b->bl == bl) {
+ ff_vp9_decode_block(td, row, col, lflvl, yoff, uvoff, b->bl, b->bp);
if (b->bp == PARTITION_H && row + hbs < s->rows) {
yoff += hbs * 8 * y_stride;
uvoff += hbs * 8 * uv_stride >> s->ss_v;
- decode_b(ctx, row + hbs, col, lflvl, yoff, uvoff, b->bl, b->bp);
+ ff_vp9_decode_block(td, row + hbs, col, lflvl, yoff, uvoff, b->bl, b->bp);
} else if (b->bp == PARTITION_V && col + hbs < s->cols) {
yoff += hbs * 8 * bytesperpixel;
uvoff += hbs * 8 * bytesperpixel >> s->ss_h;
- decode_b(ctx, row, col + hbs, lflvl, yoff, uvoff, b->bl, b->bp);
+ ff_vp9_decode_block(td, row, col + hbs, lflvl, yoff, uvoff, b->bl, b->bp);
}
} else {
- decode_sb_mem(ctx, row, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb_mem(td, row, col, lflvl, yoff, uvoff, bl + 1);
if (col + hbs < s->cols) { // FIXME why not <=?
if (row + hbs < s->rows) {
- decode_sb_mem(ctx, row, col + hbs, lflvl, yoff + 8 * hbs * bytesperpixel,
+ decode_sb_mem(td, row, col + hbs, lflvl, yoff + 8 * hbs * bytesperpixel,
uvoff + (8 * hbs * bytesperpixel >> s->ss_h), bl + 1);
yoff += hbs * 8 * y_stride;
uvoff += hbs * 8 * uv_stride >> s->ss_v;
- decode_sb_mem(ctx, row + hbs, col, lflvl, yoff, uvoff, bl + 1);
- decode_sb_mem(ctx, row + hbs, col + hbs, lflvl,
+ decode_sb_mem(td, row + hbs, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb_mem(td, row + hbs, col + hbs, lflvl,
yoff + 8 * hbs * bytesperpixel,
uvoff + (8 * hbs * bytesperpixel >> s->ss_h), bl + 1);
} else {
yoff += hbs * 8 * bytesperpixel;
uvoff += hbs * 8 * bytesperpixel >> s->ss_h;
- decode_sb_mem(ctx, row, col + hbs, lflvl, yoff, uvoff, bl + 1);
+ decode_sb_mem(td, row, col + hbs, lflvl, yoff, uvoff, bl + 1);
}
} else if (row + hbs < s->rows) {
yoff += hbs * 8 * y_stride;
uvoff += hbs * 8 * uv_stride >> s->ss_v;
- decode_sb_mem(ctx, row + hbs, col, lflvl, yoff, uvoff, bl + 1);
+ decode_sb_mem(td, row + hbs, col, lflvl, yoff, uvoff, bl + 1);
}
}
}
-static av_always_inline void filter_plane_cols(VP9Context *s, int col, int ss_h, int ss_v,
- uint8_t *lvl, uint8_t (*mask)[4],
- uint8_t *dst, ptrdiff_t ls)
-{
- int y, x, bytesperpixel = s->bytesperpixel;
-
- // filter edges between columns (e.g. block1 | block2)
- for (y = 0; y < 8; y += 2 << ss_v, dst += 16 * ls, lvl += 16 << ss_v) {
- uint8_t *ptr = dst, *l = lvl, *hmask1 = mask[y], *hmask2 = mask[y + 1 + ss_v];
- unsigned hm1 = hmask1[0] | hmask1[1] | hmask1[2], hm13 = hmask1[3];
- unsigned hm2 = hmask2[1] | hmask2[2], hm23 = hmask2[3];
- unsigned hm = hm1 | hm2 | hm13 | hm23;
-
- for (x = 1; hm & ~(x - 1); x <<= 1, ptr += 8 * bytesperpixel >> ss_h) {
- if (col || x > 1) {
- if (hm1 & x) {
- int L = *l, H = L >> 4;
- int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
-
- if (hmask1[0] & x) {
- if (hmask2[0] & x) {
- av_assert2(l[8 << ss_v] == L);
- s->dsp.loop_filter_16[0](ptr, ls, E, I, H);
- } else {
- s->dsp.loop_filter_8[2][0](ptr, ls, E, I, H);
- }
- } else if (hm2 & x) {
- L = l[8 << ss_v];
- H |= (L >> 4) << 8;
- E |= s->filter_lut.mblim_lut[L] << 8;
- I |= s->filter_lut.lim_lut[L] << 8;
- s->dsp.loop_filter_mix2[!!(hmask1[1] & x)]
- [!!(hmask2[1] & x)]
- [0](ptr, ls, E, I, H);
- } else {
- s->dsp.loop_filter_8[!!(hmask1[1] & x)]
- [0](ptr, ls, E, I, H);
- }
- } else if (hm2 & x) {
- int L = l[8 << ss_v], H = L >> 4;
- int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
-
- s->dsp.loop_filter_8[!!(hmask2[1] & x)]
- [0](ptr + 8 * ls, ls, E, I, H);
- }
- }
- if (ss_h) {
- if (x & 0xAA)
- l += 2;
- } else {
- if (hm13 & x) {
- int L = *l, H = L >> 4;
- int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
-
- if (hm23 & x) {
- L = l[8 << ss_v];
- H |= (L >> 4) << 8;
- E |= s->filter_lut.mblim_lut[L] << 8;
- I |= s->filter_lut.lim_lut[L] << 8;
- s->dsp.loop_filter_mix2[0][0][0](ptr + 4 * bytesperpixel, ls, E, I, H);
- } else {
- s->dsp.loop_filter_8[0][0](ptr + 4 * bytesperpixel, ls, E, I, H);
- }
- } else if (hm23 & x) {
- int L = l[8 << ss_v], H = L >> 4;
- int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
-
- s->dsp.loop_filter_8[0][0](ptr + 8 * ls + 4 * bytesperpixel, ls, E, I, H);
- }
- l++;
- }
- }
- }
-}
-
-static av_always_inline void filter_plane_rows(VP9Context *s, int row, int ss_h, int ss_v,
- uint8_t *lvl, uint8_t (*mask)[4],
- uint8_t *dst, ptrdiff_t ls)
-{
- int y, x, bytesperpixel = s->bytesperpixel;
-
- // block1
- // filter edges between rows (e.g. ------)
- // block2
- for (y = 0; y < 8; y++, dst += 8 * ls >> ss_v) {
- uint8_t *ptr = dst, *l = lvl, *vmask = mask[y];
- unsigned vm = vmask[0] | vmask[1] | vmask[2], vm3 = vmask[3];
-
- for (x = 1; vm & ~(x - 1); x <<= (2 << ss_h), ptr += 16 * bytesperpixel, l += 2 << ss_h) {
- if (row || y) {
- if (vm & x) {
- int L = *l, H = L >> 4;
- int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
-
- if (vmask[0] & x) {
- if (vmask[0] & (x << (1 + ss_h))) {
- av_assert2(l[1 + ss_h] == L);
- s->dsp.loop_filter_16[1](ptr, ls, E, I, H);
- } else {
- s->dsp.loop_filter_8[2][1](ptr, ls, E, I, H);
- }
- } else if (vm & (x << (1 + ss_h))) {
- L = l[1 + ss_h];
- H |= (L >> 4) << 8;
- E |= s->filter_lut.mblim_lut[L] << 8;
- I |= s->filter_lut.lim_lut[L] << 8;
- s->dsp.loop_filter_mix2[!!(vmask[1] & x)]
- [!!(vmask[1] & (x << (1 + ss_h)))]
- [1](ptr, ls, E, I, H);
- } else {
- s->dsp.loop_filter_8[!!(vmask[1] & x)]
- [1](ptr, ls, E, I, H);
- }
- } else if (vm & (x << (1 + ss_h))) {
- int L = l[1 + ss_h], H = L >> 4;
- int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
-
- s->dsp.loop_filter_8[!!(vmask[1] & (x << (1 + ss_h)))]
- [1](ptr + 8 * bytesperpixel, ls, E, I, H);
- }
- }
- if (!ss_v) {
- if (vm3 & x) {
- int L = *l, H = L >> 4;
- int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
-
- if (vm3 & (x << (1 + ss_h))) {
- L = l[1 + ss_h];
- H |= (L >> 4) << 8;
- E |= s->filter_lut.mblim_lut[L] << 8;
- I |= s->filter_lut.lim_lut[L] << 8;
- s->dsp.loop_filter_mix2[0][0][1](ptr + ls * 4, ls, E, I, H);
- } else {
- s->dsp.loop_filter_8[0][1](ptr + ls * 4, ls, E, I, H);
- }
- } else if (vm3 & (x << (1 + ss_h))) {
- int L = l[1 + ss_h], H = L >> 4;
- int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
-
- s->dsp.loop_filter_8[0][1](ptr + ls * 4 + 8 * bytesperpixel, ls, E, I, H);
- }
- }
- }
- if (ss_v) {
- if (y & 1)
- lvl += 16;
- } else {
- lvl += 8;
- }
- }
-}
-
-static void loopfilter_sb(AVCodecContext *ctx, struct VP9Filter *lflvl,
- int row, int col, ptrdiff_t yoff, ptrdiff_t uvoff)
-{
- VP9Context *s = ctx->priv_data;
- AVFrame *f = s->s.frames[CUR_FRAME].tf.f;
- uint8_t *dst = f->data[0] + yoff;
- ptrdiff_t ls_y = f->linesize[0], ls_uv = f->linesize[1];
- uint8_t (*uv_masks)[8][4] = lflvl->mask[s->ss_h | s->ss_v];
- int p;
-
- // FIXME in how far can we interleave the v/h loopfilter calls? E.g.
- // if you think of them as acting on a 8x8 block max, we can interleave
- // each v/h within the single x loop, but that only works if we work on
- // 8 pixel blocks, and we won't always do that (we want at least 16px
- // to use SSE2 optimizations, perhaps 32 for AVX2)
-
- filter_plane_cols(s, col, 0, 0, lflvl->level, lflvl->mask[0][0], dst, ls_y);
- filter_plane_rows(s, row, 0, 0, lflvl->level, lflvl->mask[0][1], dst, ls_y);
-
- for (p = 0; p < 2; p++) {
- dst = f->data[1 + p] + uvoff;
- filter_plane_cols(s, col, s->ss_h, s->ss_v, lflvl->level, uv_masks[0], dst, ls_uv);
- filter_plane_rows(s, row, s->ss_h, s->ss_v, lflvl->level, uv_masks[1], dst, ls_uv);
- }
-}
-
static void set_tile_offset(int *start, int *end, int idx, int log2_n, int n)
{
int sb_start = ( idx * n) >> log2_n;
@@ -3697,300 +1175,302 @@ static void set_tile_offset(int *start, int *end, int idx, int log2_n, int n)
*end = FFMIN(sb_end, n) << 3;
}
-static av_always_inline void adapt_prob(uint8_t *p, unsigned ct0, unsigned ct1,
- int max_count, int update_factor)
+static void free_buffers(VP9Context *s)
{
- unsigned ct = ct0 + ct1, p2, p1;
-
- if (!ct)
- return;
-
- update_factor = FASTDIV(update_factor * FFMIN(ct, max_count), max_count);
- p1 = *p;
- p2 = ((((int64_t) ct0) << 8) + (ct >> 1)) / ct;
- p2 = av_clip(p2, 1, 255);
+ int i;
- // (p1 * (256 - update_factor) + p2 * update_factor + 128) >> 8
- *p = p1 + (((p2 - p1) * update_factor + 128) >> 8);
+ av_freep(&s->intra_pred_data[0]);
+ for (i = 0; i < s->active_tile_cols; i++) {
+ av_freep(&s->td[i].b_base);
+ av_freep(&s->td[i].block_base);
+ }
}
-static void adapt_probs(VP9Context *s)
+static av_cold int vp9_decode_free(AVCodecContext *avctx)
{
- int i, j, k, l, m;
- prob_context *p = &s->prob_ctx[s->s.h.framectxid].p;
- int uf = (s->s.h.keyframe || s->s.h.intraonly || !s->last_keyframe) ? 112 : 128;
-
- // coefficients
- for (i = 0; i < 4; i++)
- for (j = 0; j < 2; j++)
- for (k = 0; k < 2; k++)
- for (l = 0; l < 6; l++)
- for (m = 0; m < 6; m++) {
- uint8_t *pp = s->prob_ctx[s->s.h.framectxid].coef[i][j][k][l][m];
- unsigned *e = s->counts.eob[i][j][k][l][m];
- unsigned *c = s->counts.coef[i][j][k][l][m];
-
- if (l == 0 && m >= 3) // dc only has 3 pt
- break;
-
- adapt_prob(&pp[0], e[0], e[1], 24, uf);
- adapt_prob(&pp[1], c[0], c[1] + c[2], 24, uf);
- adapt_prob(&pp[2], c[1], c[2], 24, uf);
- }
+ VP9Context *s = avctx->priv_data;
+ int i;
- if (s->s.h.keyframe || s->s.h.intraonly) {
- memcpy(p->skip, s->prob.p.skip, sizeof(p->skip));
- memcpy(p->tx32p, s->prob.p.tx32p, sizeof(p->tx32p));
- memcpy(p->tx16p, s->prob.p.tx16p, sizeof(p->tx16p));
- memcpy(p->tx8p, s->prob.p.tx8p, sizeof(p->tx8p));
- return;
+ for (i = 0; i < 3; i++) {
+ if (s->s.frames[i].tf.f->buf[0])
+ vp9_frame_unref(avctx, &s->s.frames[i]);
+ av_frame_free(&s->s.frames[i].tf.f);
+ }
+ for (i = 0; i < 8; i++) {
+ if (s->s.refs[i].f->buf[0])
+ ff_thread_release_buffer(avctx, &s->s.refs[i]);
+ av_frame_free(&s->s.refs[i].f);
+ if (s->next_refs[i].f->buf[0])
+ ff_thread_release_buffer(avctx, &s->next_refs[i]);
+ av_frame_free(&s->next_refs[i].f);
}
- // skip flag
- for (i = 0; i < 3; i++)
- adapt_prob(&p->skip[i], s->counts.skip[i][0], s->counts.skip[i][1], 20, 128);
+ free_buffers(s);
+ vp9_free_entries(avctx);
+ av_freep(&s->td);
+ return 0;
+}
- // intra/inter flag
- for (i = 0; i < 4; i++)
- adapt_prob(&p->intra[i], s->counts.intra[i][0], s->counts.intra[i][1], 20, 128);
+static int decode_tiles(AVCodecContext *avctx,
+ const uint8_t *data, int size)
+{
+ VP9Context *s = avctx->priv_data;
+ VP9TileData *td = &s->td[0];
+ int row, col, tile_row, tile_col, ret;
+ int bytesperpixel;
+ int tile_row_start, tile_row_end, tile_col_start, tile_col_end;
+ AVFrame *f;
+ ptrdiff_t yoff, uvoff, ls_y, ls_uv;
- // comppred flag
- if (s->s.h.comppredmode == PRED_SWITCHABLE) {
- for (i = 0; i < 5; i++)
- adapt_prob(&p->comp[i], s->counts.comp[i][0], s->counts.comp[i][1], 20, 128);
- }
+ f = s->s.frames[CUR_FRAME].tf.f;
+ ls_y = f->linesize[0];
+ ls_uv =f->linesize[1];
+ bytesperpixel = s->bytesperpixel;
- // reference frames
- if (s->s.h.comppredmode != PRED_SINGLEREF) {
- for (i = 0; i < 5; i++)
- adapt_prob(&p->comp_ref[i], s->counts.comp_ref[i][0],
- s->counts.comp_ref[i][1], 20, 128);
- }
+ yoff = uvoff = 0;
+ for (tile_row = 0; tile_row < s->s.h.tiling.tile_rows; tile_row++) {
+ set_tile_offset(&tile_row_start, &tile_row_end,
+ tile_row, s->s.h.tiling.log2_tile_rows, s->sb_rows);
- if (s->s.h.comppredmode != PRED_COMPREF) {
- for (i = 0; i < 5; i++) {
- uint8_t *pp = p->single_ref[i];
- unsigned (*c)[2] = s->counts.single_ref[i];
+ for (tile_col = 0; tile_col < s->s.h.tiling.tile_cols; tile_col++) {
+ int64_t tile_size;
- adapt_prob(&pp[0], c[0][0], c[0][1], 20, 128);
- adapt_prob(&pp[1], c[1][0], c[1][1], 20, 128);
- }
- }
+ if (tile_col == s->s.h.tiling.tile_cols - 1 &&
+ tile_row == s->s.h.tiling.tile_rows - 1) {
+ tile_size = size;
+ } else {
+ tile_size = AV_RB32(data);
+ data += 4;
+ size -= 4;
+ }
+ if (tile_size > size) {
+ ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);
+ return AVERROR_INVALIDDATA;
+ }
+ ret = ff_vp56_init_range_decoder(&td->c_b[tile_col], data, tile_size);
+ if (ret < 0)
+ return ret;
+ if (vp56_rac_get_prob_branchy(&td->c_b[tile_col], 128)) { // marker bit
+ ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);
+ return AVERROR_INVALIDDATA;
+ }
+ data += tile_size;
+ size -= tile_size;
+ }
- // block partitioning
- for (i = 0; i < 4; i++)
- for (j = 0; j < 4; j++) {
- uint8_t *pp = p->partition[i][j];
- unsigned *c = s->counts.partition[i][j];
+ for (row = tile_row_start; row < tile_row_end;
+ row += 8, yoff += ls_y * 64, uvoff += ls_uv * 64 >> s->ss_v) {
+ VP9Filter *lflvl_ptr = s->lflvl;
+ ptrdiff_t yoff2 = yoff, uvoff2 = uvoff;
- adapt_prob(&pp[0], c[0], c[1] + c[2] + c[3], 20, 128);
- adapt_prob(&pp[1], c[1], c[2] + c[3], 20, 128);
- adapt_prob(&pp[2], c[2], c[3], 20, 128);
- }
+ for (tile_col = 0; tile_col < s->s.h.tiling.tile_cols; tile_col++) {
+ set_tile_offset(&tile_col_start, &tile_col_end,
+ tile_col, s->s.h.tiling.log2_tile_cols, s->sb_cols);
+ td->tile_col_start = tile_col_start;
+ if (s->pass != 2) {
+ memset(td->left_partition_ctx, 0, 8);
+ memset(td->left_skip_ctx, 0, 8);
+ if (s->s.h.keyframe || s->s.h.intraonly) {
+ memset(td->left_mode_ctx, DC_PRED, 16);
+ } else {
+ memset(td->left_mode_ctx, NEARESTMV, 8);
+ }
+ memset(td->left_y_nnz_ctx, 0, 16);
+ memset(td->left_uv_nnz_ctx, 0, 32);
+ memset(td->left_segpred_ctx, 0, 8);
- // tx size
- if (s->s.h.txfmmode == TX_SWITCHABLE) {
- for (i = 0; i < 2; i++) {
- unsigned *c16 = s->counts.tx16p[i], *c32 = s->counts.tx32p[i];
-
- adapt_prob(&p->tx8p[i], s->counts.tx8p[i][0], s->counts.tx8p[i][1], 20, 128);
- adapt_prob(&p->tx16p[i][0], c16[0], c16[1] + c16[2], 20, 128);
- adapt_prob(&p->tx16p[i][1], c16[1], c16[2], 20, 128);
- adapt_prob(&p->tx32p[i][0], c32[0], c32[1] + c32[2] + c32[3], 20, 128);
- adapt_prob(&p->tx32p[i][1], c32[1], c32[2] + c32[3], 20, 128);
- adapt_prob(&p->tx32p[i][2], c32[2], c32[3], 20, 128);
- }
- }
+ td->c = &td->c_b[tile_col];
+ }
- // interpolation filter
- if (s->s.h.filtermode == FILTER_SWITCHABLE) {
- for (i = 0; i < 4; i++) {
- uint8_t *pp = p->filter[i];
- unsigned *c = s->counts.filter[i];
+ for (col = tile_col_start;
+ col < tile_col_end;
+ col += 8, yoff2 += 64 * bytesperpixel,
+ uvoff2 += 64 * bytesperpixel >> s->ss_h, lflvl_ptr++) {
+ // FIXME integrate with lf code (i.e. zero after each
+ // use, similar to invtxfm coefficients, or similar)
+ if (s->pass != 1) {
+ memset(lflvl_ptr->mask, 0, sizeof(lflvl_ptr->mask));
+ }
- adapt_prob(&pp[0], c[0], c[1] + c[2], 20, 128);
- adapt_prob(&pp[1], c[1], c[2], 20, 128);
- }
- }
+ if (s->pass == 2) {
+ decode_sb_mem(td, row, col, lflvl_ptr,
+ yoff2, uvoff2, BL_64X64);
+ } else {
+ decode_sb(td, row, col, lflvl_ptr,
+ yoff2, uvoff2, BL_64X64);
+ }
+ }
+ }
- // inter modes
- for (i = 0; i < 7; i++) {
- uint8_t *pp = p->mv_mode[i];
- unsigned *c = s->counts.mv_mode[i];
+ if (s->pass == 1)
+ continue;
+
+ // backup pre-loopfilter reconstruction data for intra
+ // prediction of next row of sb64s
+ if (row + 8 < s->rows) {
+ memcpy(s->intra_pred_data[0],
+ f->data[0] + yoff + 63 * ls_y,
+ 8 * s->cols * bytesperpixel);
+ memcpy(s->intra_pred_data[1],
+ f->data[1] + uvoff + ((64 >> s->ss_v) - 1) * ls_uv,
+ 8 * s->cols * bytesperpixel >> s->ss_h);
+ memcpy(s->intra_pred_data[2],
+ f->data[2] + uvoff + ((64 >> s->ss_v) - 1) * ls_uv,
+ 8 * s->cols * bytesperpixel >> s->ss_h);
+ }
+
+ // loopfilter one row
+ if (s->s.h.filter.level) {
+ yoff2 = yoff;
+ uvoff2 = uvoff;
+ lflvl_ptr = s->lflvl;
+ for (col = 0; col < s->cols;
+ col += 8, yoff2 += 64 * bytesperpixel,
+ uvoff2 += 64 * bytesperpixel >> s->ss_h, lflvl_ptr++) {
+ ff_vp9_loopfilter_sb(avctx, lflvl_ptr, row, col,
+ yoff2, uvoff2);
+ }
+ }
- adapt_prob(&pp[0], c[2], c[1] + c[0] + c[3], 20, 128);
- adapt_prob(&pp[1], c[0], c[1] + c[3], 20, 128);
- adapt_prob(&pp[2], c[1], c[3], 20, 128);
+ // FIXME maybe we can make this more finegrained by running the
+ // loopfilter per-block instead of after each sbrow
+ // In fact that would also make intra pred left preparation easier?
+ ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, row >> 3, 0);
+ }
}
+ return 0;
+}
- // mv joints
- {
- uint8_t *pp = p->mv_joint;
- unsigned *c = s->counts.mv_joint;
+#if HAVE_THREADS
+static av_always_inline
+int decode_tiles_mt(AVCodecContext *avctx, void *tdata, int jobnr,
+ int threadnr)
+{
+ VP9Context *s = avctx->priv_data;
+ VP9TileData *td = &s->td[jobnr];
+ ptrdiff_t uvoff, yoff, ls_y, ls_uv;
+ int bytesperpixel = s->bytesperpixel, row, col, tile_row;
+ unsigned tile_cols_len;
+ int tile_row_start, tile_row_end, tile_col_start, tile_col_end;
+ VP9Filter *lflvl_ptr_base;
+ AVFrame *f;
- adapt_prob(&pp[0], c[0], c[1] + c[2] + c[3], 20, 128);
- adapt_prob(&pp[1], c[1], c[2] + c[3], 20, 128);
- adapt_prob(&pp[2], c[2], c[3], 20, 128);
- }
+ f = s->s.frames[CUR_FRAME].tf.f;
+ ls_y = f->linesize[0];
+ ls_uv =f->linesize[1];
- // mv components
- for (i = 0; i < 2; i++) {
- uint8_t *pp;
- unsigned *c, (*c2)[2], sum;
-
- adapt_prob(&p->mv_comp[i].sign, s->counts.mv_comp[i].sign[0],
- s->counts.mv_comp[i].sign[1], 20, 128);
-
- pp = p->mv_comp[i].classes;
- c = s->counts.mv_comp[i].classes;
- sum = c[1] + c[2] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8] + c[9] + c[10];
- adapt_prob(&pp[0], c[0], sum, 20, 128);
- sum -= c[1];
- adapt_prob(&pp[1], c[1], sum, 20, 128);
- sum -= c[2] + c[3];
- adapt_prob(&pp[2], c[2] + c[3], sum, 20, 128);
- adapt_prob(&pp[3], c[2], c[3], 20, 128);
- sum -= c[4] + c[5];
- adapt_prob(&pp[4], c[4] + c[5], sum, 20, 128);
- adapt_prob(&pp[5], c[4], c[5], 20, 128);
- sum -= c[6];
- adapt_prob(&pp[6], c[6], sum, 20, 128);
- adapt_prob(&pp[7], c[7] + c[8], c[9] + c[10], 20, 128);
- adapt_prob(&pp[8], c[7], c[8], 20, 128);
- adapt_prob(&pp[9], c[9], c[10], 20, 128);
-
- adapt_prob(&p->mv_comp[i].class0, s->counts.mv_comp[i].class0[0],
- s->counts.mv_comp[i].class0[1], 20, 128);
- pp = p->mv_comp[i].bits;
- c2 = s->counts.mv_comp[i].bits;
- for (j = 0; j < 10; j++)
- adapt_prob(&pp[j], c2[j][0], c2[j][1], 20, 128);
-
- for (j = 0; j < 2; j++) {
- pp = p->mv_comp[i].class0_fp[j];
- c = s->counts.mv_comp[i].class0_fp[j];
- adapt_prob(&pp[0], c[0], c[1] + c[2] + c[3], 20, 128);
- adapt_prob(&pp[1], c[1], c[2] + c[3], 20, 128);
- adapt_prob(&pp[2], c[2], c[3], 20, 128);
- }
- pp = p->mv_comp[i].fp;
- c = s->counts.mv_comp[i].fp;
- adapt_prob(&pp[0], c[0], c[1] + c[2] + c[3], 20, 128);
- adapt_prob(&pp[1], c[1], c[2] + c[3], 20, 128);
- adapt_prob(&pp[2], c[2], c[3], 20, 128);
+ set_tile_offset(&tile_col_start, &tile_col_end,
+ jobnr, s->s.h.tiling.log2_tile_cols, s->sb_cols);
+ td->tile_col_start = tile_col_start;
+ uvoff = (64 * bytesperpixel >> s->ss_h)*(tile_col_start >> 3);
+ yoff = (64 * bytesperpixel)*(tile_col_start >> 3);
+ lflvl_ptr_base = s->lflvl+(tile_col_start >> 3);
+
+ for (tile_row = 0; tile_row < s->s.h.tiling.tile_rows; tile_row++) {
+ set_tile_offset(&tile_row_start, &tile_row_end,
+ tile_row, s->s.h.tiling.log2_tile_rows, s->sb_rows);
+
+ td->c = &td->c_b[tile_row];
+ for (row = tile_row_start; row < tile_row_end;
+ row += 8, yoff += ls_y * 64, uvoff += ls_uv * 64 >> s->ss_v) {
+ ptrdiff_t yoff2 = yoff, uvoff2 = uvoff;
+ VP9Filter *lflvl_ptr = lflvl_ptr_base+s->sb_cols*(row >> 3);
+
+ memset(td->left_partition_ctx, 0, 8);
+ memset(td->left_skip_ctx, 0, 8);
+ if (s->s.h.keyframe || s->s.h.intraonly) {
+ memset(td->left_mode_ctx, DC_PRED, 16);
+ } else {
+ memset(td->left_mode_ctx, NEARESTMV, 8);
+ }
+ memset(td->left_y_nnz_ctx, 0, 16);
+ memset(td->left_uv_nnz_ctx, 0, 32);
+ memset(td->left_segpred_ctx, 0, 8);
- if (s->s.h.highprecisionmvs) {
- adapt_prob(&p->mv_comp[i].class0_hp, s->counts.mv_comp[i].class0_hp[0],
- s->counts.mv_comp[i].class0_hp[1], 20, 128);
- adapt_prob(&p->mv_comp[i].hp, s->counts.mv_comp[i].hp[0],
- s->counts.mv_comp[i].hp[1], 20, 128);
- }
- }
+ for (col = tile_col_start;
+ col < tile_col_end;
+ col += 8, yoff2 += 64 * bytesperpixel,
+ uvoff2 += 64 * bytesperpixel >> s->ss_h, lflvl_ptr++) {
+ // FIXME integrate with lf code (i.e. zero after each
+ // use, similar to invtxfm coefficients, or similar)
+ memset(lflvl_ptr->mask, 0, sizeof(lflvl_ptr->mask));
+ decode_sb(td, row, col, lflvl_ptr,
+ yoff2, uvoff2, BL_64X64);
+ }
- // y intra modes
- for (i = 0; i < 4; i++) {
- uint8_t *pp = p->y_mode[i];
- unsigned *c = s->counts.y_mode[i], sum, s2;
-
- sum = c[0] + c[1] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8] + c[9];
- adapt_prob(&pp[0], c[DC_PRED], sum, 20, 128);
- sum -= c[TM_VP8_PRED];
- adapt_prob(&pp[1], c[TM_VP8_PRED], sum, 20, 128);
- sum -= c[VERT_PRED];
- adapt_prob(&pp[2], c[VERT_PRED], sum, 20, 128);
- s2 = c[HOR_PRED] + c[DIAG_DOWN_RIGHT_PRED] + c[VERT_RIGHT_PRED];
- sum -= s2;
- adapt_prob(&pp[3], s2, sum, 20, 128);
- s2 -= c[HOR_PRED];
- adapt_prob(&pp[4], c[HOR_PRED], s2, 20, 128);
- adapt_prob(&pp[5], c[DIAG_DOWN_RIGHT_PRED], c[VERT_RIGHT_PRED], 20, 128);
- sum -= c[DIAG_DOWN_LEFT_PRED];
- adapt_prob(&pp[6], c[DIAG_DOWN_LEFT_PRED], sum, 20, 128);
- sum -= c[VERT_LEFT_PRED];
- adapt_prob(&pp[7], c[VERT_LEFT_PRED], sum, 20, 128);
- adapt_prob(&pp[8], c[HOR_DOWN_PRED], c[HOR_UP_PRED], 20, 128);
- }
+ // backup pre-loopfilter reconstruction data for intra
+ // prediction of next row of sb64s
+ tile_cols_len = tile_col_end - tile_col_start;
+ if (row + 8 < s->rows) {
+ memcpy(s->intra_pred_data[0] + (tile_col_start * 8 * bytesperpixel),
+ f->data[0] + yoff + 63 * ls_y,
+ 8 * tile_cols_len * bytesperpixel);
+ memcpy(s->intra_pred_data[1] + (tile_col_start * 8 * bytesperpixel >> s->ss_h),
+ f->data[1] + uvoff + ((64 >> s->ss_v) - 1) * ls_uv,
+ 8 * tile_cols_len * bytesperpixel >> s->ss_h);
+ memcpy(s->intra_pred_data[2] + (tile_col_start * 8 * bytesperpixel >> s->ss_h),
+ f->data[2] + uvoff + ((64 >> s->ss_v) - 1) * ls_uv,
+ 8 * tile_cols_len * bytesperpixel >> s->ss_h);
+ }
- // uv intra modes
- for (i = 0; i < 10; i++) {
- uint8_t *pp = p->uv_mode[i];
- unsigned *c = s->counts.uv_mode[i], sum, s2;
-
- sum = c[0] + c[1] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8] + c[9];
- adapt_prob(&pp[0], c[DC_PRED], sum, 20, 128);
- sum -= c[TM_VP8_PRED];
- adapt_prob(&pp[1], c[TM_VP8_PRED], sum, 20, 128);
- sum -= c[VERT_PRED];
- adapt_prob(&pp[2], c[VERT_PRED], sum, 20, 128);
- s2 = c[HOR_PRED] + c[DIAG_DOWN_RIGHT_PRED] + c[VERT_RIGHT_PRED];
- sum -= s2;
- adapt_prob(&pp[3], s2, sum, 20, 128);
- s2 -= c[HOR_PRED];
- adapt_prob(&pp[4], c[HOR_PRED], s2, 20, 128);
- adapt_prob(&pp[5], c[DIAG_DOWN_RIGHT_PRED], c[VERT_RIGHT_PRED], 20, 128);
- sum -= c[DIAG_DOWN_LEFT_PRED];
- adapt_prob(&pp[6], c[DIAG_DOWN_LEFT_PRED], sum, 20, 128);
- sum -= c[VERT_LEFT_PRED];
- adapt_prob(&pp[7], c[VERT_LEFT_PRED], sum, 20, 128);
- adapt_prob(&pp[8], c[HOR_DOWN_PRED], c[HOR_UP_PRED], 20, 128);
+ vp9_report_tile_progress(s, row >> 3, 1);
+ }
}
+ return 0;
}
-static void free_buffers(VP9Context *s)
+static av_always_inline
+int loopfilter_proc(AVCodecContext *avctx)
{
- av_freep(&s->intra_pred_data[0]);
- av_freep(&s->b_base);
- av_freep(&s->block_base);
-}
+ VP9Context *s = avctx->priv_data;
+ ptrdiff_t uvoff, yoff, ls_y, ls_uv;
+ VP9Filter *lflvl_ptr;
+ int bytesperpixel = s->bytesperpixel, col, i;
+ AVFrame *f;
-static av_cold int vp9_decode_free(AVCodecContext *ctx)
-{
- VP9Context *s = ctx->priv_data;
- int i;
+ f = s->s.frames[CUR_FRAME].tf.f;
+ ls_y = f->linesize[0];
+ ls_uv =f->linesize[1];
- for (i = 0; i < 3; i++) {
- if (s->s.frames[i].tf.f->buf[0])
- vp9_unref_frame(ctx, &s->s.frames[i]);
- av_frame_free(&s->s.frames[i].tf.f);
- }
- for (i = 0; i < 8; i++) {
- if (s->s.refs[i].f->buf[0])
- ff_thread_release_buffer(ctx, &s->s.refs[i]);
- av_frame_free(&s->s.refs[i].f);
- if (s->next_refs[i].f->buf[0])
- ff_thread_release_buffer(ctx, &s->next_refs[i]);
- av_frame_free(&s->next_refs[i].f);
- }
- free_buffers(s);
- av_freep(&s->c_b);
- s->c_b_size = 0;
+ for (i = 0; i < s->sb_rows; i++) {
+ vp9_await_tile_progress(s, i, s->s.h.tiling.tile_cols);
+ if (s->s.h.filter.level) {
+ yoff = (ls_y * 64)*i;
+ uvoff = (ls_uv * 64 >> s->ss_v)*i;
+ lflvl_ptr = s->lflvl+s->sb_cols*i;
+ for (col = 0; col < s->cols;
+ col += 8, yoff += 64 * bytesperpixel,
+ uvoff += 64 * bytesperpixel >> s->ss_h, lflvl_ptr++) {
+ ff_vp9_loopfilter_sb(avctx, lflvl_ptr, i << 3, col,
+ yoff, uvoff);
+ }
+ }
+ }
return 0;
}
+#endif
-
-static int vp9_decode_frame(AVCodecContext *ctx, void *frame,
+static int vp9_decode_frame(AVCodecContext *avctx, void *frame,
int *got_frame, AVPacket *pkt)
{
const uint8_t *data = pkt->data;
int size = pkt->size;
- VP9Context *s = ctx->priv_data;
- int res, tile_row, tile_col, i, ref, row, col;
+ VP9Context *s = avctx->priv_data;
+ int ret, i, j, ref;
int retain_segmap_ref = s->s.frames[REF_FRAME_SEGMAP].segmentation_map &&
(!s->s.h.segmentation.enabled || !s->s.h.segmentation.update_map);
- ptrdiff_t yoff, uvoff, ls_y, ls_uv;
AVFrame *f;
- int bytesperpixel;
- if ((res = decode_frame_header(ctx, data, size, &ref)) < 0) {
- return res;
- } else if (res == 0) {
+ if ((ret = decode_frame_header(avctx, data, size, &ref)) < 0) {
+ return ret;
+ } else if (ret == 0) {
if (!s->s.refs[ref].f->buf[0]) {
- av_log(ctx, AV_LOG_ERROR, "Requested reference %d not available\n", ref);
+ av_log(avctx, AV_LOG_ERROR, "Requested reference %d not available\n", ref);
return AVERROR_INVALIDDATA;
}
- if ((res = av_frame_ref(frame, s->s.refs[ref].f)) < 0)
- return res;
+ if ((ret = av_frame_ref(frame, s->s.refs[ref].f)) < 0)
+ return ret;
((AVFrame *)frame)->pts = pkt->pts;
#if FF_API_PKT_PTS
FF_DISABLE_DEPRECATION_WARNINGS
@@ -4000,73 +1480,70 @@ FF_ENABLE_DEPRECATION_WARNINGS
((AVFrame *)frame)->pkt_dts = pkt->dts;
for (i = 0; i < 8; i++) {
if (s->next_refs[i].f->buf[0])
- ff_thread_release_buffer(ctx, &s->next_refs[i]);
+ ff_thread_release_buffer(avctx, &s->next_refs[i]);
if (s->s.refs[i].f->buf[0] &&
- (res = ff_thread_ref_frame(&s->next_refs[i], &s->s.refs[i])) < 0)
- return res;
+ (ret = ff_thread_ref_frame(&s->next_refs[i], &s->s.refs[i])) < 0)
+ return ret;
}
*got_frame = 1;
return pkt->size;
}
- data += res;
- size -= res;
+ data += ret;
+ size -= ret;
if (!retain_segmap_ref || s->s.h.keyframe || s->s.h.intraonly) {
if (s->s.frames[REF_FRAME_SEGMAP].tf.f->buf[0])
- vp9_unref_frame(ctx, &s->s.frames[REF_FRAME_SEGMAP]);
+ vp9_frame_unref(avctx, &s->s.frames[REF_FRAME_SEGMAP]);
if (!s->s.h.keyframe && !s->s.h.intraonly && !s->s.h.errorres && s->s.frames[CUR_FRAME].tf.f->buf[0] &&
- (res = vp9_ref_frame(ctx, &s->s.frames[REF_FRAME_SEGMAP], &s->s.frames[CUR_FRAME])) < 0)
- return res;
+ (ret = vp9_frame_ref(avctx, &s->s.frames[REF_FRAME_SEGMAP], &s->s.frames[CUR_FRAME])) < 0)
+ return ret;
}
if (s->s.frames[REF_FRAME_MVPAIR].tf.f->buf[0])
- vp9_unref_frame(ctx, &s->s.frames[REF_FRAME_MVPAIR]);
+ vp9_frame_unref(avctx, &s->s.frames[REF_FRAME_MVPAIR]);
if (!s->s.h.intraonly && !s->s.h.keyframe && !s->s.h.errorres && s->s.frames[CUR_FRAME].tf.f->buf[0] &&
- (res = vp9_ref_frame(ctx, &s->s.frames[REF_FRAME_MVPAIR], &s->s.frames[CUR_FRAME])) < 0)
- return res;
+ (ret = vp9_frame_ref(avctx, &s->s.frames[REF_FRAME_MVPAIR], &s->s.frames[CUR_FRAME])) < 0)
+ return ret;
if (s->s.frames[CUR_FRAME].tf.f->buf[0])
- vp9_unref_frame(ctx, &s->s.frames[CUR_FRAME]);
- if ((res = vp9_alloc_frame(ctx, &s->s.frames[CUR_FRAME])) < 0)
- return res;
+ vp9_frame_unref(avctx, &s->s.frames[CUR_FRAME]);
+ if ((ret = vp9_frame_alloc(avctx, &s->s.frames[CUR_FRAME])) < 0)
+ return ret;
f = s->s.frames[CUR_FRAME].tf.f;
f->key_frame = s->s.h.keyframe;
f->pict_type = (s->s.h.keyframe || s->s.h.intraonly) ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
- ls_y = f->linesize[0];
- ls_uv =f->linesize[1];
if (s->s.frames[REF_FRAME_SEGMAP].tf.f->buf[0] &&
(s->s.frames[REF_FRAME_MVPAIR].tf.f->width != s->s.frames[CUR_FRAME].tf.f->width ||
s->s.frames[REF_FRAME_MVPAIR].tf.f->height != s->s.frames[CUR_FRAME].tf.f->height)) {
- vp9_unref_frame(ctx, &s->s.frames[REF_FRAME_SEGMAP]);
+ vp9_frame_unref(avctx, &s->s.frames[REF_FRAME_SEGMAP]);
}
// ref frame setup
for (i = 0; i < 8; i++) {
if (s->next_refs[i].f->buf[0])
- ff_thread_release_buffer(ctx, &s->next_refs[i]);
+ ff_thread_release_buffer(avctx, &s->next_refs[i]);
if (s->s.h.refreshrefmask & (1 << i)) {
- res = ff_thread_ref_frame(&s->next_refs[i], &s->s.frames[CUR_FRAME].tf);
+ ret = ff_thread_ref_frame(&s->next_refs[i], &s->s.frames[CUR_FRAME].tf);
} else if (s->s.refs[i].f->buf[0]) {
- res = ff_thread_ref_frame(&s->next_refs[i], &s->s.refs[i]);
- }
- if (res < 0)
- return res;
- }
-
- if (ctx->hwaccel) {
- res = ctx->hwaccel->start_frame(ctx, NULL, 0);
- if (res < 0)
- return res;
- res = ctx->hwaccel->decode_slice(ctx, pkt->data, pkt->size);
- if (res < 0)
- return res;
- res = ctx->hwaccel->end_frame(ctx);
- if (res < 0)
- return res;
+ ret = ff_thread_ref_frame(&s->next_refs[i], &s->s.refs[i]);
+ }
+ if (ret < 0)
+ return ret;
+ }
+
+ if (avctx->hwaccel) {
+ ret = avctx->hwaccel->start_frame(avctx, NULL, 0);
+ if (ret < 0)
+ return ret;
+ ret = avctx->hwaccel->decode_slice(avctx, pkt->data, pkt->size);
+ if (ret < 0)
+ return ret;
+ ret = avctx->hwaccel->end_frame(avctx);
+ if (ret < 0)
+ return ret;
goto finish;
}
// main tile decode loop
- bytesperpixel = s->bytesperpixel;
memset(s->above_partition_ctx, 0, s->cols);
memset(s->above_skip_ctx, 0, s->cols);
if (s->s.h.keyframe || s->s.h.intraonly) {
@@ -4079,11 +1556,11 @@ FF_ENABLE_DEPRECATION_WARNINGS
memset(s->above_uv_nnz_ctx[1], 0, s->sb_cols * 16 >> s->ss_h);
memset(s->above_segpred_ctx, 0, s->cols);
s->pass = s->s.frames[CUR_FRAME].uses_2pass =
- ctx->active_thread_type == FF_THREAD_FRAME && s->s.h.refreshctx && !s->s.h.parallelmode;
- if ((res = update_block_buffers(ctx)) < 0) {
- av_log(ctx, AV_LOG_ERROR,
+ avctx->active_thread_type == FF_THREAD_FRAME && s->s.h.refreshctx && !s->s.h.parallelmode;
+ if ((ret = update_block_buffers(avctx)) < 0) {
+ av_log(avctx, AV_LOG_ERROR,
"Failed to allocate block buffers\n");
- return res;
+ return ret;
}
if (s->s.h.refreshctx && s->s.h.parallelmode) {
int j, k, l, m;
@@ -4099,25 +1576,36 @@ FF_ENABLE_DEPRECATION_WARNINGS
break;
}
s->prob_ctx[s->s.h.framectxid].p = s->prob.p;
- ff_thread_finish_setup(ctx);
+ ff_thread_finish_setup(avctx);
} else if (!s->s.h.refreshctx) {
- ff_thread_finish_setup(ctx);
+ ff_thread_finish_setup(avctx);
+ }
+
+#if HAVE_THREADS
+ if (avctx->active_thread_type & FF_THREAD_SLICE) {
+ for (i = 0; i < s->sb_rows; i++)
+ atomic_store(&s->entries[i], 0);
}
+#endif
do {
- yoff = uvoff = 0;
- s->b = s->b_base;
- s->block = s->block_base;
- s->uvblock[0] = s->uvblock_base[0];
- s->uvblock[1] = s->uvblock_base[1];
- s->eob = s->eob_base;
- s->uveob[0] = s->uveob_base[0];
- s->uveob[1] = s->uveob_base[1];
-
- for (tile_row = 0; tile_row < s->s.h.tiling.tile_rows; tile_row++) {
- set_tile_offset(&s->tile_row_start, &s->tile_row_end,
- tile_row, s->s.h.tiling.log2_tile_rows, s->sb_rows);
- if (s->pass != 2) {
+ for (i = 0; i < s->active_tile_cols; i++) {
+ s->td[i].b = s->td[i].b_base;
+ s->td[i].block = s->td[i].block_base;
+ s->td[i].uvblock[0] = s->td[i].uvblock_base[0];
+ s->td[i].uvblock[1] = s->td[i].uvblock_base[1];
+ s->td[i].eob = s->td[i].eob_base;
+ s->td[i].uveob[0] = s->td[i].uveob_base[0];
+ s->td[i].uveob[1] = s->td[i].uveob_base[1];
+ }
+
+#if HAVE_THREADS
+ if (avctx->active_thread_type == FF_THREAD_SLICE) {
+ int tile_row, tile_col;
+
+ av_assert1(!s->pass);
+
+ for (tile_row = 0; tile_row < s->s.h.tiling.tile_rows; tile_row++) {
for (tile_col = 0; tile_col < s->s.h.tiling.tile_cols; tile_col++) {
int64_t tile_size;
@@ -4129,107 +1617,38 @@ FF_ENABLE_DEPRECATION_WARNINGS
data += 4;
size -= 4;
}
- if (tile_size > size) {
- ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);
+ if (tile_size > size)
return AVERROR_INVALIDDATA;
- }
- ff_vp56_init_range_decoder(&s->c_b[tile_col], data, tile_size);
- if (vp56_rac_get_prob_branchy(&s->c_b[tile_col], 128)) { // marker bit
- ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);
+ ret = ff_vp56_init_range_decoder(&s->td[tile_col].c_b[tile_row], data, tile_size);
+ if (ret < 0)
+ return ret;
+ if (vp56_rac_get_prob_branchy(&s->td[tile_col].c_b[tile_row], 128)) // marker bit
return AVERROR_INVALIDDATA;
- }
data += tile_size;
size -= tile_size;
}
}
- for (row = s->tile_row_start; row < s->tile_row_end;
- row += 8, yoff += ls_y * 64, uvoff += ls_uv * 64 >> s->ss_v) {
- struct VP9Filter *lflvl_ptr = s->lflvl;
- ptrdiff_t yoff2 = yoff, uvoff2 = uvoff;
-
- for (tile_col = 0; tile_col < s->s.h.tiling.tile_cols; tile_col++) {
- set_tile_offset(&s->tile_col_start, &s->tile_col_end,
- tile_col, s->s.h.tiling.log2_tile_cols, s->sb_cols);
-
- if (s->pass != 2) {
- memset(s->left_partition_ctx, 0, 8);
- memset(s->left_skip_ctx, 0, 8);
- if (s->s.h.keyframe || s->s.h.intraonly) {
- memset(s->left_mode_ctx, DC_PRED, 16);
- } else {
- memset(s->left_mode_ctx, NEARESTMV, 8);
- }
- memset(s->left_y_nnz_ctx, 0, 16);
- memset(s->left_uv_nnz_ctx, 0, 32);
- memset(s->left_segpred_ctx, 0, 8);
-
- memcpy(&s->c, &s->c_b[tile_col], sizeof(s->c));
- }
-
- for (col = s->tile_col_start;
- col < s->tile_col_end;
- col += 8, yoff2 += 64 * bytesperpixel,
- uvoff2 += 64 * bytesperpixel >> s->ss_h, lflvl_ptr++) {
- // FIXME integrate with lf code (i.e. zero after each
- // use, similar to invtxfm coefficients, or similar)
- if (s->pass != 1) {
- memset(lflvl_ptr->mask, 0, sizeof(lflvl_ptr->mask));
- }
-
- if (s->pass == 2) {
- decode_sb_mem(ctx, row, col, lflvl_ptr,
- yoff2, uvoff2, BL_64X64);
- } else {
- decode_sb(ctx, row, col, lflvl_ptr,
- yoff2, uvoff2, BL_64X64);
- }
- }
- if (s->pass != 2) {
- memcpy(&s->c_b[tile_col], &s->c, sizeof(s->c));
- }
- }
-
- if (s->pass == 1) {
- continue;
- }
-
- // backup pre-loopfilter reconstruction data for intra
- // prediction of next row of sb64s
- if (row + 8 < s->rows) {
- memcpy(s->intra_pred_data[0],
- f->data[0] + yoff + 63 * ls_y,
- 8 * s->cols * bytesperpixel);
- memcpy(s->intra_pred_data[1],
- f->data[1] + uvoff + ((64 >> s->ss_v) - 1) * ls_uv,
- 8 * s->cols * bytesperpixel >> s->ss_h);
- memcpy(s->intra_pred_data[2],
- f->data[2] + uvoff + ((64 >> s->ss_v) - 1) * ls_uv,
- 8 * s->cols * bytesperpixel >> s->ss_h);
- }
-
- // loopfilter one row
- if (s->s.h.filter.level) {
- yoff2 = yoff;
- uvoff2 = uvoff;
- lflvl_ptr = s->lflvl;
- for (col = 0; col < s->cols;
- col += 8, yoff2 += 64 * bytesperpixel,
- uvoff2 += 64 * bytesperpixel >> s->ss_h, lflvl_ptr++) {
- loopfilter_sb(ctx, lflvl_ptr, row, col, yoff2, uvoff2);
- }
- }
-
- // FIXME maybe we can make this more finegrained by running the
- // loopfilter per-block instead of after each sbrow
- // In fact that would also make intra pred left preparation easier?
- ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, row >> 3, 0);
+ ff_slice_thread_execute_with_mainfunc(avctx, decode_tiles_mt, loopfilter_proc, s->td, NULL, s->s.h.tiling.tile_cols);
+ } else
+#endif
+ {
+ ret = decode_tiles(avctx, data, size);
+ if (ret < 0) {
+ ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);
+ return ret;
}
}
+ // Sum all counts fields into td[0].counts for tile threading
+ if (avctx->active_thread_type == FF_THREAD_SLICE)
+ for (i = 1; i < s->s.h.tiling.tile_cols; i++)
+ for (j = 0; j < sizeof(s->td[i].counts) / sizeof(unsigned); j++)
+ ((unsigned *)&s->td[0].counts)[j] += ((unsigned *)&s->td[i].counts)[j];
+
if (s->pass < 2 && s->s.h.refreshctx && !s->s.h.parallelmode) {
- adapt_probs(s);
- ff_thread_finish_setup(ctx);
+ ff_vp9_adapt_probs(s);
+ ff_thread_finish_setup(avctx);
}
} while (s->pass++ == 1);
ff_thread_report_progress(&s->s.frames[CUR_FRAME].tf, INT_MAX, 0);
@@ -4238,42 +1657,42 @@ finish:
// ref frame setup
for (i = 0; i < 8; i++) {
if (s->s.refs[i].f->buf[0])
- ff_thread_release_buffer(ctx, &s->s.refs[i]);
+ ff_thread_release_buffer(avctx, &s->s.refs[i]);
if (s->next_refs[i].f->buf[0] &&
- (res = ff_thread_ref_frame(&s->s.refs[i], &s->next_refs[i])) < 0)
- return res;
+ (ret = ff_thread_ref_frame(&s->s.refs[i], &s->next_refs[i])) < 0)
+ return ret;
}
if (!s->s.h.invisible) {
- if ((res = av_frame_ref(frame, s->s.frames[CUR_FRAME].tf.f)) < 0)
- return res;
+ if ((ret = av_frame_ref(frame, s->s.frames[CUR_FRAME].tf.f)) < 0)
+ return ret;
*got_frame = 1;
}
return pkt->size;
}
-static void vp9_decode_flush(AVCodecContext *ctx)
+static void vp9_decode_flush(AVCodecContext *avctx)
{
- VP9Context *s = ctx->priv_data;
+ VP9Context *s = avctx->priv_data;
int i;
for (i = 0; i < 3; i++)
- vp9_unref_frame(ctx, &s->s.frames[i]);
+ vp9_frame_unref(avctx, &s->s.frames[i]);
for (i = 0; i < 8; i++)
- ff_thread_release_buffer(ctx, &s->s.refs[i]);
+ ff_thread_release_buffer(avctx, &s->s.refs[i]);
}
-static int init_frames(AVCodecContext *ctx)
+static int init_frames(AVCodecContext *avctx)
{
- VP9Context *s = ctx->priv_data;
+ VP9Context *s = avctx->priv_data;
int i;
for (i = 0; i < 3; i++) {
s->s.frames[i].tf.f = av_frame_alloc();
if (!s->s.frames[i].tf.f) {
- vp9_decode_free(ctx);
- av_log(ctx, AV_LOG_ERROR, "Failed to allocate frame buffer %d\n", i);
+ vp9_decode_free(avctx);
+ av_log(avctx, AV_LOG_ERROR, "Failed to allocate frame buffer %d\n", i);
return AVERROR(ENOMEM);
}
}
@@ -4281,8 +1700,8 @@ static int init_frames(AVCodecContext *ctx)
s->s.refs[i].f = av_frame_alloc();
s->next_refs[i].f = av_frame_alloc();
if (!s->s.refs[i].f || !s->next_refs[i].f) {
- vp9_decode_free(ctx);
- av_log(ctx, AV_LOG_ERROR, "Failed to allocate frame buffer %d\n", i);
+ vp9_decode_free(avctx);
+ av_log(avctx, AV_LOG_ERROR, "Failed to allocate frame buffer %d\n", i);
return AVERROR(ENOMEM);
}
}
@@ -4290,15 +1709,15 @@ static int init_frames(AVCodecContext *ctx)
return 0;
}
-static av_cold int vp9_decode_init(AVCodecContext *ctx)
+static av_cold int vp9_decode_init(AVCodecContext *avctx)
{
- VP9Context *s = ctx->priv_data;
+ VP9Context *s = avctx->priv_data;
- ctx->internal->allocate_progress = 1;
+ avctx->internal->allocate_progress = 1;
s->last_bpp = 0;
s->s.h.filter.sharpness = -1;
- return init_frames(ctx);
+ return init_frames(avctx);
}
#if HAVE_THREADS
@@ -4309,23 +1728,23 @@ static av_cold int vp9_decode_init_thread_copy(AVCodecContext *avctx)
static int vp9_decode_update_thread_context(AVCodecContext *dst, const AVCodecContext *src)
{
- int i, res;
+ int i, ret;
VP9Context *s = dst->priv_data, *ssrc = src->priv_data;
for (i = 0; i < 3; i++) {
if (s->s.frames[i].tf.f->buf[0])
- vp9_unref_frame(dst, &s->s.frames[i]);
+ vp9_frame_unref(dst, &s->s.frames[i]);
if (ssrc->s.frames[i].tf.f->buf[0]) {
- if ((res = vp9_ref_frame(dst, &s->s.frames[i], &ssrc->s.frames[i])) < 0)
- return res;
+ if ((ret = vp9_frame_ref(dst, &s->s.frames[i], &ssrc->s.frames[i])) < 0)
+ return ret;
}
}
for (i = 0; i < 8; i++) {
if (s->s.refs[i].f->buf[0])
ff_thread_release_buffer(dst, &s->s.refs[i]);
if (ssrc->next_refs[i].f->buf[0]) {
- if ((res = ff_thread_ref_frame(&s->s.refs[i], &ssrc->next_refs[i])) < 0)
- return res;
+ if ((ret = ff_thread_ref_frame(&s->s.refs[i], &ssrc->next_refs[i])) < 0)
+ return ret;
}
}
@@ -4341,7 +1760,7 @@ static int vp9_decode_update_thread_context(AVCodecContext *dst, const AVCodecCo
s->gf_fmt = ssrc->gf_fmt;
s->w = ssrc->w;
s->h = ssrc->h;
- s->bpp = ssrc->bpp;
+ s->s.h.bpp = ssrc->s.h.bpp;
s->bpp_index = ssrc->bpp_index;
s->pix_fmt = ssrc->pix_fmt;
memcpy(&s->prob_ctx, &ssrc->prob_ctx, sizeof(s->prob_ctx));
@@ -4362,7 +1781,8 @@ AVCodec ff_vp9_decoder = {
.init = vp9_decode_init,
.close = vp9_decode_free,
.decode = vp9_decode_frame,
- .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS,
+ .capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS | AV_CODEC_CAP_SLICE_THREADS,
+ .caps_internal = FF_CODEC_CAP_SLICE_THREAD_HAS_MF,
.flush = vp9_decode_flush,
.init_thread_copy = ONLY_IF_THREADS_ENABLED(vp9_decode_init_thread_copy),
.update_thread_context = ONLY_IF_THREADS_ENABLED(vp9_decode_update_thread_context),
diff --git a/media/ffvpx/libavcodec/vp9.h b/media/ffvpx/libavcodec/vp9.h
index df5bd4d85..c8d07ad98 100644
--- a/media/ffvpx/libavcodec/vp9.h
+++ b/media/ffvpx/libavcodec/vp9.h
@@ -24,42 +24,6 @@
#ifndef AVCODEC_VP9_H
#define AVCODEC_VP9_H
-#include <stdint.h>
-
-#include "thread.h"
-#include "vp56.h"
-
-enum BlockLevel {
- BL_64X64,
- BL_32X32,
- BL_16X16,
- BL_8X8,
-};
-
-enum BlockPartition {
- PARTITION_NONE, // [ ] <-.
- PARTITION_H, // [-] |
- PARTITION_V, // [|] |
- PARTITION_SPLIT, // [+] --'
-};
-
-enum BlockSize {
- BS_64x64,
- BS_64x32,
- BS_32x64,
- BS_32x32,
- BS_32x16,
- BS_16x32,
- BS_16x16,
- BS_16x8,
- BS_8x16,
- BS_8x8,
- BS_8x4,
- BS_4x8,
- BS_4x4,
- N_BS_SIZES,
-};
-
enum TxfmMode {
TX_4X4,
TX_8X8,
@@ -97,115 +61,13 @@ enum IntraPredMode {
N_INTRA_PRED_MODES
};
-enum InterPredMode {
- NEARESTMV = 10,
- NEARMV = 11,
- ZEROMV = 12,
- NEWMV = 13,
-};
-
enum FilterMode {
FILTER_8TAP_SMOOTH,
FILTER_8TAP_REGULAR,
FILTER_8TAP_SHARP,
FILTER_BILINEAR,
- FILTER_SWITCHABLE,
+ N_FILTERS,
+ FILTER_SWITCHABLE = N_FILTERS,
};
-enum CompPredMode {
- PRED_SINGLEREF,
- PRED_COMPREF,
- PRED_SWITCHABLE,
-};
-
-struct VP9mvrefPair {
- VP56mv mv[2];
- int8_t ref[2];
-};
-
-typedef struct VP9Frame {
- ThreadFrame tf;
- AVBufferRef *extradata;
- uint8_t *segmentation_map;
- struct VP9mvrefPair *mv;
- int uses_2pass;
-
- AVBufferRef *hwaccel_priv_buf;
- void *hwaccel_picture_private;
-} VP9Frame;
-
-typedef struct VP9BitstreamHeader {
- // bitstream header
- uint8_t profile;
- uint8_t keyframe;
- uint8_t invisible;
- uint8_t errorres;
- uint8_t intraonly;
- uint8_t resetctx;
- uint8_t refreshrefmask;
- uint8_t highprecisionmvs;
- enum FilterMode filtermode;
- uint8_t allowcompinter;
- uint8_t refreshctx;
- uint8_t parallelmode;
- uint8_t framectxid;
- uint8_t use_last_frame_mvs;
- uint8_t refidx[3];
- uint8_t signbias[3];
- uint8_t fixcompref;
- uint8_t varcompref[2];
- struct {
- uint8_t level;
- int8_t sharpness;
- } filter;
- struct {
- uint8_t enabled;
- uint8_t updated;
- int8_t mode[2];
- int8_t ref[4];
- } lf_delta;
- uint8_t yac_qi;
- int8_t ydc_qdelta, uvdc_qdelta, uvac_qdelta;
- uint8_t lossless;
-#define MAX_SEGMENT 8
- struct {
- uint8_t enabled;
- uint8_t temporal;
- uint8_t absolute_vals;
- uint8_t update_map;
- uint8_t prob[7];
- uint8_t pred_prob[3];
- struct {
- uint8_t q_enabled;
- uint8_t lf_enabled;
- uint8_t ref_enabled;
- uint8_t skip_enabled;
- uint8_t ref_val;
- int16_t q_val;
- int8_t lf_val;
- int16_t qmul[2][2];
- uint8_t lflvl[4][2];
- } feat[MAX_SEGMENT];
- } segmentation;
- enum TxfmMode txfmmode;
- enum CompPredMode comppredmode;
- struct {
- unsigned log2_tile_cols, log2_tile_rows;
- unsigned tile_cols, tile_rows;
- } tiling;
-
- int uncompressed_header_size;
- int compressed_header_size;
-} VP9BitstreamHeader;
-
-typedef struct VP9SharedContext {
- VP9BitstreamHeader h;
-
- ThreadFrame refs[8];
-#define CUR_FRAME 0
-#define REF_FRAME_MVPAIR 1
-#define REF_FRAME_SEGMAP 2
- VP9Frame frames[3];
-} VP9SharedContext;
-
#endif /* AVCODEC_VP9_H */
diff --git a/media/ffvpx/libavcodec/vp9_mc_template.c b/media/ffvpx/libavcodec/vp9_mc_template.c
index 38d9a6da9..31e692f36 100644
--- a/media/ffvpx/libavcodec/vp9_mc_template.c
+++ b/media/ffvpx/libavcodec/vp9_mc_template.c
@@ -27,19 +27,19 @@
(VP56mv) { .x = ROUNDED_DIV(a.x + b.x + c.x + d.x, 4), \
.y = ROUNDED_DIV(a.y + b.y + c.y + d.y, 4) }
-static void FN(inter_pred)(AVCodecContext *ctx)
+static void FN(inter_pred)(VP9TileData *td)
{
static const uint8_t bwlog_tab[2][N_BS_SIZES] = {
{ 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4 },
{ 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4 },
};
- VP9Context *s = ctx->priv_data;
- VP9Block *b = s->b;
- int row = s->row, col = s->col;
+ VP9Context *s = td->s;
+ VP9Block *b = td->b;
+ int row = td->row, col = td->col;
ThreadFrame *tref1 = &s->s.refs[s->s.h.refidx[b->ref[0]]], *tref2;
AVFrame *ref1 = tref1->f, *ref2;
int w1 = ref1->width, h1 = ref1->height, w2, h2;
- ptrdiff_t ls_y = s->y_stride, ls_uv = s->uv_stride;
+ ptrdiff_t ls_y = td->y_stride, ls_uv = td->uv_stride;
int bytesperpixel = BYTES_PER_PIXEL;
if (b->comp) {
@@ -55,26 +55,26 @@ static void FN(inter_pred)(AVCodecContext *ctx)
#if SCALED == 0
if (b->bs == BS_8x4) {
- mc_luma_dir(s, mc[3][b->filter][0], s->dst[0], ls_y,
+ mc_luma_dir(td, mc[3][b->filter][0], td->dst[0], ls_y,
ref1->data[0], ref1->linesize[0], tref1,
row << 3, col << 3, &b->mv[0][0],,,,, 8, 4, w1, h1, 0);
- mc_luma_dir(s, mc[3][b->filter][0],
- s->dst[0] + 4 * ls_y, ls_y,
+ mc_luma_dir(td, mc[3][b->filter][0],
+ td->dst[0] + 4 * ls_y, ls_y,
ref1->data[0], ref1->linesize[0], tref1,
(row << 3) + 4, col << 3, &b->mv[2][0],,,,, 8, 4, w1, h1, 0);
w1 = (w1 + s->ss_h) >> s->ss_h;
if (s->ss_v) {
h1 = (h1 + 1) >> 1;
uvmv = ROUNDED_DIV_MVx2(b->mv[0][0], b->mv[2][0]);
- mc_chroma_dir(s, mc[3 + s->ss_h][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[3 + s->ss_h][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << 2, col << (3 - s->ss_h),
&uvmv,,,,, 8 >> s->ss_h, 4, w1, h1, 0);
} else {
- mc_chroma_dir(s, mc[3 + s->ss_h][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[3 + s->ss_h][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << 3, col << (3 - s->ss_h),
@@ -87,8 +87,8 @@ static void FN(inter_pred)(AVCodecContext *ctx)
} else {
uvmv = ROUNDED_DIV_MVx2(b->mv[0][0], b->mv[2][0]);
}
- mc_chroma_dir(s, mc[3 + s->ss_h][b->filter][0],
- s->dst[1] + 4 * ls_uv, s->dst[2] + 4 * ls_uv, ls_uv,
+ mc_chroma_dir(td, mc[3 + s->ss_h][b->filter][0],
+ td->dst[1] + 4 * ls_uv, td->dst[2] + 4 * ls_uv, ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
(row << 3) + 4, col << (3 - s->ss_h),
@@ -96,26 +96,26 @@ static void FN(inter_pred)(AVCodecContext *ctx)
}
if (b->comp) {
- mc_luma_dir(s, mc[3][b->filter][1], s->dst[0], ls_y,
+ mc_luma_dir(td, mc[3][b->filter][1], td->dst[0], ls_y,
ref2->data[0], ref2->linesize[0], tref2,
row << 3, col << 3, &b->mv[0][1],,,,, 8, 4, w2, h2, 1);
- mc_luma_dir(s, mc[3][b->filter][1],
- s->dst[0] + 4 * ls_y, ls_y,
+ mc_luma_dir(td, mc[3][b->filter][1],
+ td->dst[0] + 4 * ls_y, ls_y,
ref2->data[0], ref2->linesize[0], tref2,
(row << 3) + 4, col << 3, &b->mv[2][1],,,,, 8, 4, w2, h2, 1);
w2 = (w2 + s->ss_h) >> s->ss_h;
if (s->ss_v) {
h2 = (h2 + 1) >> 1;
uvmv = ROUNDED_DIV_MVx2(b->mv[0][1], b->mv[2][1]);
- mc_chroma_dir(s, mc[3 + s->ss_h][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[3 + s->ss_h][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << 2, col << (3 - s->ss_h),
&uvmv,,,,, 8 >> s->ss_h, 4, w2, h2, 1);
} else {
- mc_chroma_dir(s, mc[3 + s->ss_h][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[3 + s->ss_h][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << 3, col << (3 - s->ss_h),
@@ -128,8 +128,8 @@ static void FN(inter_pred)(AVCodecContext *ctx)
} else {
uvmv = ROUNDED_DIV_MVx2(b->mv[0][1], b->mv[2][1]);
}
- mc_chroma_dir(s, mc[3 + s->ss_h][b->filter][1],
- s->dst[1] + 4 * ls_uv, s->dst[2] + 4 * ls_uv, ls_uv,
+ mc_chroma_dir(td, mc[3 + s->ss_h][b->filter][1],
+ td->dst[1] + 4 * ls_uv, td->dst[2] + 4 * ls_uv, ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
(row << 3) + 4, col << (3 - s->ss_h),
@@ -137,32 +137,32 @@ static void FN(inter_pred)(AVCodecContext *ctx)
}
}
} else if (b->bs == BS_4x8) {
- mc_luma_dir(s, mc[4][b->filter][0], s->dst[0], ls_y,
+ mc_luma_dir(td, mc[4][b->filter][0], td->dst[0], ls_y,
ref1->data[0], ref1->linesize[0], tref1,
row << 3, col << 3, &b->mv[0][0],,,,, 4, 8, w1, h1, 0);
- mc_luma_dir(s, mc[4][b->filter][0], s->dst[0] + 4 * bytesperpixel, ls_y,
+ mc_luma_dir(td, mc[4][b->filter][0], td->dst[0] + 4 * bytesperpixel, ls_y,
ref1->data[0], ref1->linesize[0], tref1,
row << 3, (col << 3) + 4, &b->mv[1][0],,,,, 4, 8, w1, h1, 0);
h1 = (h1 + s->ss_v) >> s->ss_v;
if (s->ss_h) {
w1 = (w1 + 1) >> 1;
uvmv = ROUNDED_DIV_MVx2(b->mv[0][0], b->mv[1][0]);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << (3 - s->ss_v), col << 2,
&uvmv,,,,, 4, 8 >> s->ss_v, w1, h1, 0);
} else {
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << (3 - s->ss_v), col << 3,
&b->mv[0][0],,,,, 4, 8 >> s->ss_v, w1, h1, 0);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1] + 4 * bytesperpixel,
- s->dst[2] + 4 * bytesperpixel, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1] + 4 * bytesperpixel,
+ td->dst[2] + 4 * bytesperpixel, ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << (3 - s->ss_v), (col << 3) + 4,
@@ -170,32 +170,32 @@ static void FN(inter_pred)(AVCodecContext *ctx)
}
if (b->comp) {
- mc_luma_dir(s, mc[4][b->filter][1], s->dst[0], ls_y,
+ mc_luma_dir(td, mc[4][b->filter][1], td->dst[0], ls_y,
ref2->data[0], ref2->linesize[0], tref2,
row << 3, col << 3, &b->mv[0][1],,,,, 4, 8, w2, h2, 1);
- mc_luma_dir(s, mc[4][b->filter][1], s->dst[0] + 4 * bytesperpixel, ls_y,
+ mc_luma_dir(td, mc[4][b->filter][1], td->dst[0] + 4 * bytesperpixel, ls_y,
ref2->data[0], ref2->linesize[0], tref2,
row << 3, (col << 3) + 4, &b->mv[1][1],,,,, 4, 8, w2, h2, 1);
h2 = (h2 + s->ss_v) >> s->ss_v;
if (s->ss_h) {
w2 = (w2 + 1) >> 1;
uvmv = ROUNDED_DIV_MVx2(b->mv[0][1], b->mv[1][1]);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << (3 - s->ss_v), col << 2,
&uvmv,,,,, 4, 8 >> s->ss_v, w2, h2, 1);
} else {
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << (3 - s->ss_v), col << 3,
&b->mv[0][1],,,,, 4, 8 >> s->ss_v, w2, h2, 1);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1] + 4 * bytesperpixel,
- s->dst[2] + 4 * bytesperpixel, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1] + 4 * bytesperpixel,
+ td->dst[2] + 4 * bytesperpixel, ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << (3 - s->ss_v), (col << 3) + 4,
@@ -205,25 +205,27 @@ static void FN(inter_pred)(AVCodecContext *ctx)
} else
#endif
{
+#if SCALED == 0
av_assert2(b->bs == BS_4x4);
+#endif
// FIXME if two horizontally adjacent blocks have the same MV,
// do a w8 instead of a w4 call
- mc_luma_dir(s, mc[4][b->filter][0], s->dst[0], ls_y,
+ mc_luma_dir(td, mc[4][b->filter][0], td->dst[0], ls_y,
ref1->data[0], ref1->linesize[0], tref1,
row << 3, col << 3, &b->mv[0][0],
0, 0, 8, 8, 4, 4, w1, h1, 0);
- mc_luma_dir(s, mc[4][b->filter][0], s->dst[0] + 4 * bytesperpixel, ls_y,
+ mc_luma_dir(td, mc[4][b->filter][0], td->dst[0] + 4 * bytesperpixel, ls_y,
ref1->data[0], ref1->linesize[0], tref1,
row << 3, (col << 3) + 4, &b->mv[1][0],
4, 0, 8, 8, 4, 4, w1, h1, 0);
- mc_luma_dir(s, mc[4][b->filter][0],
- s->dst[0] + 4 * ls_y, ls_y,
+ mc_luma_dir(td, mc[4][b->filter][0],
+ td->dst[0] + 4 * ls_y, ls_y,
ref1->data[0], ref1->linesize[0], tref1,
(row << 3) + 4, col << 3, &b->mv[2][0],
0, 4, 8, 8, 4, 4, w1, h1, 0);
- mc_luma_dir(s, mc[4][b->filter][0],
- s->dst[0] + 4 * ls_y + 4 * bytesperpixel, ls_y,
+ mc_luma_dir(td, mc[4][b->filter][0],
+ td->dst[0] + 4 * ls_y + 4 * bytesperpixel, ls_y,
ref1->data[0], ref1->linesize[0], tref1,
(row << 3) + 4, (col << 3) + 4, &b->mv[3][0],
4, 4, 8, 8, 4, 4, w1, h1, 0);
@@ -233,24 +235,24 @@ static void FN(inter_pred)(AVCodecContext *ctx)
w1 = (w1 + 1) >> 1;
uvmv = ROUNDED_DIV_MVx4(b->mv[0][0], b->mv[1][0],
b->mv[2][0], b->mv[3][0]);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << 2, col << 2,
&uvmv, 0, 0, 4, 4, 4, 4, w1, h1, 0);
} else {
uvmv = ROUNDED_DIV_MVx2(b->mv[0][0], b->mv[2][0]);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << 2, col << 3,
&uvmv, 0, 0, 8, 4, 4, 4, w1, h1, 0);
uvmv = ROUNDED_DIV_MVx2(b->mv[1][0], b->mv[3][0]);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1] + 4 * bytesperpixel,
- s->dst[2] + 4 * bytesperpixel, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1] + 4 * bytesperpixel,
+ td->dst[2] + 4 * bytesperpixel, ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << 2, (col << 3) + 4,
@@ -260,8 +262,8 @@ static void FN(inter_pred)(AVCodecContext *ctx)
if (s->ss_h) {
w1 = (w1 + 1) >> 1;
uvmv = ROUNDED_DIV_MVx2(b->mv[0][0], b->mv[1][0]);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << 3, col << 2,
@@ -270,35 +272,35 @@ static void FN(inter_pred)(AVCodecContext *ctx)
// bottom block
// https://code.google.com/p/webm/issues/detail?id=993
uvmv = ROUNDED_DIV_MVx2(b->mv[1][0], b->mv[2][0]);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1] + 4 * ls_uv, s->dst[2] + 4 * ls_uv, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1] + 4 * ls_uv, td->dst[2] + 4 * ls_uv, ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
(row << 3) + 4, col << 2,
&uvmv, 0, 4, 4, 8, 4, 4, w1, h1, 0);
} else {
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << 3, col << 3,
&b->mv[0][0], 0, 0, 8, 8, 4, 4, w1, h1, 0);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1] + 4 * bytesperpixel,
- s->dst[2] + 4 * bytesperpixel, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1] + 4 * bytesperpixel,
+ td->dst[2] + 4 * bytesperpixel, ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << 3, (col << 3) + 4,
&b->mv[1][0], 4, 0, 8, 8, 4, 4, w1, h1, 0);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1] + 4 * ls_uv, s->dst[2] + 4 * ls_uv, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1] + 4 * ls_uv, td->dst[2] + 4 * ls_uv, ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
(row << 3) + 4, col << 3,
&b->mv[2][0], 0, 4, 8, 8, 4, 4, w1, h1, 0);
- mc_chroma_dir(s, mc[4][b->filter][0],
- s->dst[1] + 4 * ls_uv + 4 * bytesperpixel,
- s->dst[2] + 4 * ls_uv + 4 * bytesperpixel, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][0],
+ td->dst[1] + 4 * ls_uv + 4 * bytesperpixel,
+ td->dst[2] + 4 * ls_uv + 4 * bytesperpixel, ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
(row << 3) + 4, (col << 3) + 4,
@@ -307,18 +309,18 @@ static void FN(inter_pred)(AVCodecContext *ctx)
}
if (b->comp) {
- mc_luma_dir(s, mc[4][b->filter][1], s->dst[0], ls_y,
+ mc_luma_dir(td, mc[4][b->filter][1], td->dst[0], ls_y,
ref2->data[0], ref2->linesize[0], tref2,
row << 3, col << 3, &b->mv[0][1], 0, 0, 8, 8, 4, 4, w2, h2, 1);
- mc_luma_dir(s, mc[4][b->filter][1], s->dst[0] + 4 * bytesperpixel, ls_y,
+ mc_luma_dir(td, mc[4][b->filter][1], td->dst[0] + 4 * bytesperpixel, ls_y,
ref2->data[0], ref2->linesize[0], tref2,
row << 3, (col << 3) + 4, &b->mv[1][1], 4, 0, 8, 8, 4, 4, w2, h2, 1);
- mc_luma_dir(s, mc[4][b->filter][1],
- s->dst[0] + 4 * ls_y, ls_y,
+ mc_luma_dir(td, mc[4][b->filter][1],
+ td->dst[0] + 4 * ls_y, ls_y,
ref2->data[0], ref2->linesize[0], tref2,
(row << 3) + 4, col << 3, &b->mv[2][1], 0, 4, 8, 8, 4, 4, w2, h2, 1);
- mc_luma_dir(s, mc[4][b->filter][1],
- s->dst[0] + 4 * ls_y + 4 * bytesperpixel, ls_y,
+ mc_luma_dir(td, mc[4][b->filter][1],
+ td->dst[0] + 4 * ls_y + 4 * bytesperpixel, ls_y,
ref2->data[0], ref2->linesize[0], tref2,
(row << 3) + 4, (col << 3) + 4, &b->mv[3][1], 4, 4, 8, 8, 4, 4, w2, h2, 1);
if (s->ss_v) {
@@ -327,24 +329,24 @@ static void FN(inter_pred)(AVCodecContext *ctx)
w2 = (w2 + 1) >> 1;
uvmv = ROUNDED_DIV_MVx4(b->mv[0][1], b->mv[1][1],
b->mv[2][1], b->mv[3][1]);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << 2, col << 2,
&uvmv, 0, 0, 4, 4, 4, 4, w2, h2, 1);
} else {
uvmv = ROUNDED_DIV_MVx2(b->mv[0][1], b->mv[2][1]);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << 2, col << 3,
&uvmv, 0, 0, 8, 4, 4, 4, w2, h2, 1);
uvmv = ROUNDED_DIV_MVx2(b->mv[1][1], b->mv[3][1]);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1] + 4 * bytesperpixel,
- s->dst[2] + 4 * bytesperpixel, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1] + 4 * bytesperpixel,
+ td->dst[2] + 4 * bytesperpixel, ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << 2, (col << 3) + 4,
@@ -354,8 +356,8 @@ static void FN(inter_pred)(AVCodecContext *ctx)
if (s->ss_h) {
w2 = (w2 + 1) >> 1;
uvmv = ROUNDED_DIV_MVx2(b->mv[0][1], b->mv[1][1]);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << 3, col << 2,
@@ -364,35 +366,35 @@ static void FN(inter_pred)(AVCodecContext *ctx)
// bottom block
// https://code.google.com/p/webm/issues/detail?id=993
uvmv = ROUNDED_DIV_MVx2(b->mv[1][1], b->mv[2][1]);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1] + 4 * ls_uv, s->dst[2] + 4 * ls_uv, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1] + 4 * ls_uv, td->dst[2] + 4 * ls_uv, ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
(row << 3) + 4, col << 2,
&uvmv, 0, 4, 4, 8, 4, 4, w2, h2, 1);
} else {
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << 3, col << 3,
&b->mv[0][1], 0, 0, 8, 8, 4, 4, w2, h2, 1);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1] + 4 * bytesperpixel,
- s->dst[2] + 4 * bytesperpixel, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1] + 4 * bytesperpixel,
+ td->dst[2] + 4 * bytesperpixel, ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << 3, (col << 3) + 4,
&b->mv[1][1], 4, 0, 8, 8, 4, 4, w2, h2, 1);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1] + 4 * ls_uv, s->dst[2] + 4 * ls_uv, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1] + 4 * ls_uv, td->dst[2] + 4 * ls_uv, ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
(row << 3) + 4, col << 3,
&b->mv[2][1], 0, 4, 8, 8, 4, 4, w2, h2, 1);
- mc_chroma_dir(s, mc[4][b->filter][1],
- s->dst[1] + 4 * ls_uv + 4 * bytesperpixel,
- s->dst[2] + 4 * ls_uv + 4 * bytesperpixel, ls_uv,
+ mc_chroma_dir(td, mc[4][b->filter][1],
+ td->dst[1] + 4 * ls_uv + 4 * bytesperpixel,
+ td->dst[2] + 4 * ls_uv + 4 * bytesperpixel, ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
(row << 3) + 4, (col << 3) + 4,
@@ -403,29 +405,31 @@ static void FN(inter_pred)(AVCodecContext *ctx)
}
} else {
int bwl = bwlog_tab[0][b->bs];
- int bw = bwh_tab[0][b->bs][0] * 4, bh = bwh_tab[0][b->bs][1] * 4;
- int uvbw = bwh_tab[s->ss_h][b->bs][0] * 4, uvbh = bwh_tab[s->ss_v][b->bs][1] * 4;
+ int bw = ff_vp9_bwh_tab[0][b->bs][0] * 4;
+ int bh = ff_vp9_bwh_tab[0][b->bs][1] * 4;
+ int uvbw = ff_vp9_bwh_tab[s->ss_h][b->bs][0] * 4;
+ int uvbh = ff_vp9_bwh_tab[s->ss_v][b->bs][1] * 4;
- mc_luma_dir(s, mc[bwl][b->filter][0], s->dst[0], ls_y,
+ mc_luma_dir(td, mc[bwl][b->filter][0], td->dst[0], ls_y,
ref1->data[0], ref1->linesize[0], tref1,
row << 3, col << 3, &b->mv[0][0], 0, 0, bw, bh, bw, bh, w1, h1, 0);
w1 = (w1 + s->ss_h) >> s->ss_h;
h1 = (h1 + s->ss_v) >> s->ss_v;
- mc_chroma_dir(s, mc[bwl + s->ss_h][b->filter][0],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[bwl + s->ss_h][b->filter][0],
+ td->dst[1], td->dst[2], ls_uv,
ref1->data[1], ref1->linesize[1],
ref1->data[2], ref1->linesize[2], tref1,
row << (3 - s->ss_v), col << (3 - s->ss_h),
&b->mv[0][0], 0, 0, uvbw, uvbh, uvbw, uvbh, w1, h1, 0);
if (b->comp) {
- mc_luma_dir(s, mc[bwl][b->filter][1], s->dst[0], ls_y,
+ mc_luma_dir(td, mc[bwl][b->filter][1], td->dst[0], ls_y,
ref2->data[0], ref2->linesize[0], tref2,
row << 3, col << 3, &b->mv[0][1], 0, 0, bw, bh, bw, bh, w2, h2, 1);
w2 = (w2 + s->ss_h) >> s->ss_h;
h2 = (h2 + s->ss_v) >> s->ss_v;
- mc_chroma_dir(s, mc[bwl + s->ss_h][b->filter][1],
- s->dst[1], s->dst[2], ls_uv,
+ mc_chroma_dir(td, mc[bwl + s->ss_h][b->filter][1],
+ td->dst[1], td->dst[2], ls_uv,
ref2->data[1], ref2->linesize[1],
ref2->data[2], ref2->linesize[2], tref2,
row << (3 - s->ss_v), col << (3 - s->ss_h),
diff --git a/media/ffvpx/libavcodec/vp9block.c b/media/ffvpx/libavcodec/vp9block.c
new file mode 100644
index 000000000..1c3f7a722
--- /dev/null
+++ b/media/ffvpx/libavcodec/vp9block.c
@@ -0,0 +1,1449 @@
+/*
+ * VP9 compatible video decoder
+ *
+ * Copyright (C) 2013 Ronald S. Bultje <rsbultje gmail com>
+ * Copyright (C) 2013 Clément Bœsch <u pkh me>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/avassert.h"
+
+#include "avcodec.h"
+#include "internal.h"
+#include "videodsp.h"
+#include "vp56.h"
+#include "vp9.h"
+#include "vp9data.h"
+#include "vp9dec.h"
+
+static av_always_inline void setctx_2d(uint8_t *ptr, int w, int h,
+ ptrdiff_t stride, int v)
+{
+ switch (w) {
+ case 1:
+ do {
+ *ptr = v;
+ ptr += stride;
+ } while (--h);
+ break;
+ case 2: {
+ int v16 = v * 0x0101;
+ do {
+ AV_WN16A(ptr, v16);
+ ptr += stride;
+ } while (--h);
+ break;
+ }
+ case 4: {
+ uint32_t v32 = v * 0x01010101;
+ do {
+ AV_WN32A(ptr, v32);
+ ptr += stride;
+ } while (--h);
+ break;
+ }
+ case 8: {
+#if HAVE_FAST_64BIT
+ uint64_t v64 = v * 0x0101010101010101ULL;
+ do {
+ AV_WN64A(ptr, v64);
+ ptr += stride;
+ } while (--h);
+#else
+ uint32_t v32 = v * 0x01010101;
+ do {
+ AV_WN32A(ptr, v32);
+ AV_WN32A(ptr + 4, v32);
+ ptr += stride;
+ } while (--h);
+#endif
+ break;
+ }
+ }
+}
+
+static void decode_mode(VP9TileData *td)
+{
+ static const uint8_t left_ctx[N_BS_SIZES] = {
+ 0x0, 0x8, 0x0, 0x8, 0xc, 0x8, 0xc, 0xe, 0xc, 0xe, 0xf, 0xe, 0xf
+ };
+ static const uint8_t above_ctx[N_BS_SIZES] = {
+ 0x0, 0x0, 0x8, 0x8, 0x8, 0xc, 0xc, 0xc, 0xe, 0xe, 0xe, 0xf, 0xf
+ };
+ static const uint8_t max_tx_for_bl_bp[N_BS_SIZES] = {
+ TX_32X32, TX_32X32, TX_32X32, TX_32X32, TX_16X16, TX_16X16,
+ TX_16X16, TX_8X8, TX_8X8, TX_8X8, TX_4X4, TX_4X4, TX_4X4
+ };
+ VP9Context *s = td->s;
+ VP9Block *b = td->b;
+ int row = td->row, col = td->col, row7 = td->row7;
+ enum TxfmMode max_tx = max_tx_for_bl_bp[b->bs];
+ int bw4 = ff_vp9_bwh_tab[1][b->bs][0], w4 = FFMIN(s->cols - col, bw4);
+ int bh4 = ff_vp9_bwh_tab[1][b->bs][1], h4 = FFMIN(s->rows - row, bh4), y;
+ int have_a = row > 0, have_l = col > td->tile_col_start;
+ int vref, filter_id;
+
+ if (!s->s.h.segmentation.enabled) {
+ b->seg_id = 0;
+ } else if (s->s.h.keyframe || s->s.h.intraonly) {
+ b->seg_id = !s->s.h.segmentation.update_map ? 0 :
+ vp8_rac_get_tree(td->c, ff_vp9_segmentation_tree, s->s.h.segmentation.prob);
+ } else if (!s->s.h.segmentation.update_map ||
+ (s->s.h.segmentation.temporal &&
+ vp56_rac_get_prob_branchy(td->c,
+ s->s.h.segmentation.pred_prob[s->above_segpred_ctx[col] +
+ td->left_segpred_ctx[row7]]))) {
+ if (!s->s.h.errorres && s->s.frames[REF_FRAME_SEGMAP].segmentation_map) {
+ int pred = 8, x;
+ uint8_t *refsegmap = s->s.frames[REF_FRAME_SEGMAP].segmentation_map;
+
+ if (!s->s.frames[REF_FRAME_SEGMAP].uses_2pass)
+ ff_thread_await_progress(&s->s.frames[REF_FRAME_SEGMAP].tf, row >> 3, 0);
+ for (y = 0; y < h4; y++) {
+ int idx_base = (y + row) * 8 * s->sb_cols + col;
+ for (x = 0; x < w4; x++)
+ pred = FFMIN(pred, refsegmap[idx_base + x]);
+ }
+ av_assert1(pred < 8);
+ b->seg_id = pred;
+ } else {
+ b->seg_id = 0;
+ }
+
+ memset(&s->above_segpred_ctx[col], 1, w4);
+ memset(&td->left_segpred_ctx[row7], 1, h4);
+ } else {
+ b->seg_id = vp8_rac_get_tree(td->c, ff_vp9_segmentation_tree,
+ s->s.h.segmentation.prob);
+
+ memset(&s->above_segpred_ctx[col], 0, w4);
+ memset(&td->left_segpred_ctx[row7], 0, h4);
+ }
+ if (s->s.h.segmentation.enabled &&
+ (s->s.h.segmentation.update_map || s->s.h.keyframe || s->s.h.intraonly)) {
+ setctx_2d(&s->s.frames[CUR_FRAME].segmentation_map[row * 8 * s->sb_cols + col],
+ bw4, bh4, 8 * s->sb_cols, b->seg_id);
+ }
+
+ b->skip = s->s.h.segmentation.enabled &&
+ s->s.h.segmentation.feat[b->seg_id].skip_enabled;
+ if (!b->skip) {
+ int c = td->left_skip_ctx[row7] + s->above_skip_ctx[col];
+ b->skip = vp56_rac_get_prob(td->c, s->prob.p.skip[c]);
+ td->counts.skip[c][b->skip]++;
+ }
+
+ if (s->s.h.keyframe || s->s.h.intraonly) {
+ b->intra = 1;
+ } else if (s->s.h.segmentation.enabled && s->s.h.segmentation.feat[b->seg_id].ref_enabled) {
+ b->intra = !s->s.h.segmentation.feat[b->seg_id].ref_val;
+ } else {
+ int c, bit;
+
+ if (have_a && have_l) {
+ c = s->above_intra_ctx[col] + td->left_intra_ctx[row7];
+ c += (c == 2);
+ } else {
+ c = have_a ? 2 * s->above_intra_ctx[col] :
+ have_l ? 2 * td->left_intra_ctx[row7] : 0;
+ }
+ bit = vp56_rac_get_prob(td->c, s->prob.p.intra[c]);
+ td->counts.intra[c][bit]++;
+ b->intra = !bit;
+ }
+
+ if ((b->intra || !b->skip) && s->s.h.txfmmode == TX_SWITCHABLE) {
+ int c;
+ if (have_a) {
+ if (have_l) {
+ c = (s->above_skip_ctx[col] ? max_tx :
+ s->above_txfm_ctx[col]) +
+ (td->left_skip_ctx[row7] ? max_tx :
+ td->left_txfm_ctx[row7]) > max_tx;
+ } else {
+ c = s->above_skip_ctx[col] ? 1 :
+ (s->above_txfm_ctx[col] * 2 > max_tx);
+ }
+ } else if (have_l) {
+ c = td->left_skip_ctx[row7] ? 1 :
+ (td->left_txfm_ctx[row7] * 2 > max_tx);
+ } else {
+ c = 1;
+ }
+ switch (max_tx) {
+ case TX_32X32:
+ b->tx = vp56_rac_get_prob(td->c, s->prob.p.tx32p[c][0]);
+ if (b->tx) {
+ b->tx += vp56_rac_get_prob(td->c, s->prob.p.tx32p[c][1]);
+ if (b->tx == 2)
+ b->tx += vp56_rac_get_prob(td->c, s->prob.p.tx32p[c][2]);
+ }
+ td->counts.tx32p[c][b->tx]++;
+ break;
+ case TX_16X16:
+ b->tx = vp56_rac_get_prob(td->c, s->prob.p.tx16p[c][0]);
+ if (b->tx)
+ b->tx += vp56_rac_get_prob(td->c, s->prob.p.tx16p[c][1]);
+ td->counts.tx16p[c][b->tx]++;
+ break;
+ case TX_8X8:
+ b->tx = vp56_rac_get_prob(td->c, s->prob.p.tx8p[c]);
+ td->counts.tx8p[c][b->tx]++;
+ break;
+ case TX_4X4:
+ b->tx = TX_4X4;
+ break;
+ }
+ } else {
+ b->tx = FFMIN(max_tx, s->s.h.txfmmode);
+ }
+
+ if (s->s.h.keyframe || s->s.h.intraonly) {
+ uint8_t *a = &s->above_mode_ctx[col * 2];
+ uint8_t *l = &td->left_mode_ctx[(row7) << 1];
+
+ b->comp = 0;
+ if (b->bs > BS_8x8) {
+ // FIXME the memory storage intermediates here aren't really
+ // necessary, they're just there to make the code slightly
+ // simpler for now
+ b->mode[0] =
+ a[0] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ ff_vp9_default_kf_ymode_probs[a[0]][l[0]]);
+ if (b->bs != BS_8x4) {
+ b->mode[1] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ ff_vp9_default_kf_ymode_probs[a[1]][b->mode[0]]);
+ l[0] =
+ a[1] = b->mode[1];
+ } else {
+ l[0] =
+ a[1] =
+ b->mode[1] = b->mode[0];
+ }
+ if (b->bs != BS_4x8) {
+ b->mode[2] =
+ a[0] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ ff_vp9_default_kf_ymode_probs[a[0]][l[1]]);
+ if (b->bs != BS_8x4) {
+ b->mode[3] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ ff_vp9_default_kf_ymode_probs[a[1]][b->mode[2]]);
+ l[1] =
+ a[1] = b->mode[3];
+ } else {
+ l[1] =
+ a[1] =
+ b->mode[3] = b->mode[2];
+ }
+ } else {
+ b->mode[2] = b->mode[0];
+ l[1] =
+ a[1] =
+ b->mode[3] = b->mode[1];
+ }
+ } else {
+ b->mode[0] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ ff_vp9_default_kf_ymode_probs[*a][*l]);
+ b->mode[3] =
+ b->mode[2] =
+ b->mode[1] = b->mode[0];
+ // FIXME this can probably be optimized
+ memset(a, b->mode[0], ff_vp9_bwh_tab[0][b->bs][0]);
+ memset(l, b->mode[0], ff_vp9_bwh_tab[0][b->bs][1]);
+ }
+ b->uvmode = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ ff_vp9_default_kf_uvmode_probs[b->mode[3]]);
+ } else if (b->intra) {
+ b->comp = 0;
+ if (b->bs > BS_8x8) {
+ b->mode[0] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ s->prob.p.y_mode[0]);
+ td->counts.y_mode[0][b->mode[0]]++;
+ if (b->bs != BS_8x4) {
+ b->mode[1] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ s->prob.p.y_mode[0]);
+ td->counts.y_mode[0][b->mode[1]]++;
+ } else {
+ b->mode[1] = b->mode[0];
+ }
+ if (b->bs != BS_4x8) {
+ b->mode[2] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ s->prob.p.y_mode[0]);
+ td->counts.y_mode[0][b->mode[2]]++;
+ if (b->bs != BS_8x4) {
+ b->mode[3] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ s->prob.p.y_mode[0]);
+ td->counts.y_mode[0][b->mode[3]]++;
+ } else {
+ b->mode[3] = b->mode[2];
+ }
+ } else {
+ b->mode[2] = b->mode[0];
+ b->mode[3] = b->mode[1];
+ }
+ } else {
+ static const uint8_t size_group[10] = {
+ 3, 3, 3, 3, 2, 2, 2, 1, 1, 1
+ };
+ int sz = size_group[b->bs];
+
+ b->mode[0] = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ s->prob.p.y_mode[sz]);
+ b->mode[1] =
+ b->mode[2] =
+ b->mode[3] = b->mode[0];
+ td->counts.y_mode[sz][b->mode[3]]++;
+ }
+ b->uvmode = vp8_rac_get_tree(td->c, ff_vp9_intramode_tree,
+ s->prob.p.uv_mode[b->mode[3]]);
+ td->counts.uv_mode[b->mode[3]][b->uvmode]++;
+ } else {
+ static const uint8_t inter_mode_ctx_lut[14][14] = {
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5 },
+ { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2, 2, 1, 3 },
+ { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 2, 2, 1, 3 },
+ { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 0, 3 },
+ { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 3, 3, 4 },
+ };
+
+ if (s->s.h.segmentation.enabled && s->s.h.segmentation.feat[b->seg_id].ref_enabled) {
+ av_assert2(s->s.h.segmentation.feat[b->seg_id].ref_val != 0);
+ b->comp = 0;
+ b->ref[0] = s->s.h.segmentation.feat[b->seg_id].ref_val - 1;
+ } else {
+ // read comp_pred flag
+ if (s->s.h.comppredmode != PRED_SWITCHABLE) {
+ b->comp = s->s.h.comppredmode == PRED_COMPREF;
+ } else {
+ int c;
+
+ // FIXME add intra as ref=0xff (or -1) to make these easier?
+ if (have_a) {
+ if (have_l) {
+ if (s->above_comp_ctx[col] && td->left_comp_ctx[row7]) {
+ c = 4;
+ } else if (s->above_comp_ctx[col]) {
+ c = 2 + (td->left_intra_ctx[row7] ||
+ td->left_ref_ctx[row7] == s->s.h.fixcompref);
+ } else if (td->left_comp_ctx[row7]) {
+ c = 2 + (s->above_intra_ctx[col] ||
+ s->above_ref_ctx[col] == s->s.h.fixcompref);
+ } else {
+ c = (!s->above_intra_ctx[col] &&
+ s->above_ref_ctx[col] == s->s.h.fixcompref) ^
+ (!td->left_intra_ctx[row7] &&
+ td->left_ref_ctx[row & 7] == s->s.h.fixcompref);
+ }
+ } else {
+ c = s->above_comp_ctx[col] ? 3 :
+ (!s->above_intra_ctx[col] && s->above_ref_ctx[col] == s->s.h.fixcompref);
+ }
+ } else if (have_l) {
+ c = td->left_comp_ctx[row7] ? 3 :
+ (!td->left_intra_ctx[row7] && td->left_ref_ctx[row7] == s->s.h.fixcompref);
+ } else {
+ c = 1;
+ }
+ b->comp = vp56_rac_get_prob(td->c, s->prob.p.comp[c]);
+ td->counts.comp[c][b->comp]++;
+ }
+
+ // read actual references
+ // FIXME probably cache a few variables here to prevent repetitive
+ // memory accesses below
+ if (b->comp) { /* two references */
+ int fix_idx = s->s.h.signbias[s->s.h.fixcompref], var_idx = !fix_idx, c, bit;
+
+ b->ref[fix_idx] = s->s.h.fixcompref;
+ // FIXME can this codeblob be replaced by some sort of LUT?
+ if (have_a) {
+ if (have_l) {
+ if (s->above_intra_ctx[col]) {
+ if (td->left_intra_ctx[row7]) {
+ c = 2;
+ } else {
+ c = 1 + 2 * (td->left_ref_ctx[row7] != s->s.h.varcompref[1]);
+ }
+ } else if (td->left_intra_ctx[row7]) {
+ c = 1 + 2 * (s->above_ref_ctx[col] != s->s.h.varcompref[1]);
+ } else {
+ int refl = td->left_ref_ctx[row7], refa = s->above_ref_ctx[col];
+
+ if (refl == refa && refa == s->s.h.varcompref[1]) {
+ c = 0;
+ } else if (!td->left_comp_ctx[row7] && !s->above_comp_ctx[col]) {
+ if ((refa == s->s.h.fixcompref && refl == s->s.h.varcompref[0]) ||
+ (refl == s->s.h.fixcompref && refa == s->s.h.varcompref[0])) {
+ c = 4;
+ } else {
+ c = (refa == refl) ? 3 : 1;
+ }
+ } else if (!td->left_comp_ctx[row7]) {
+ if (refa == s->s.h.varcompref[1] && refl != s->s.h.varcompref[1]) {
+ c = 1;
+ } else {
+ c = (refl == s->s.h.varcompref[1] &&
+ refa != s->s.h.varcompref[1]) ? 2 : 4;
+ }
+ } else if (!s->above_comp_ctx[col]) {
+ if (refl == s->s.h.varcompref[1] && refa != s->s.h.varcompref[1]) {
+ c = 1;
+ } else {
+ c = (refa == s->s.h.varcompref[1] &&
+ refl != s->s.h.varcompref[1]) ? 2 : 4;
+ }
+ } else {
+ c = (refl == refa) ? 4 : 2;
+ }
+ }
+ } else {
+ if (s->above_intra_ctx[col]) {
+ c = 2;
+ } else if (s->above_comp_ctx[col]) {
+ c = 4 * (s->above_ref_ctx[col] != s->s.h.varcompref[1]);
+ } else {
+ c = 3 * (s->above_ref_ctx[col] != s->s.h.varcompref[1]);
+ }
+ }
+ } else if (have_l) {
+ if (td->left_intra_ctx[row7]) {
+ c = 2;
+ } else if (td->left_comp_ctx[row7]) {
+ c = 4 * (td->left_ref_ctx[row7] != s->s.h.varcompref[1]);
+ } else {
+ c = 3 * (td->left_ref_ctx[row7] != s->s.h.varcompref[1]);
+ }
+ } else {
+ c = 2;
+ }
+ bit = vp56_rac_get_prob(td->c, s->prob.p.comp_ref[c]);
+ b->ref[var_idx] = s->s.h.varcompref[bit];
+ td->counts.comp_ref[c][bit]++;
+ } else /* single reference */ {
+ int bit, c;
+
+ if (have_a && !s->above_intra_ctx[col]) {
+ if (have_l && !td->left_intra_ctx[row7]) {
+ if (td->left_comp_ctx[row7]) {
+ if (s->above_comp_ctx[col]) {
+ c = 1 + (!s->s.h.fixcompref || !td->left_ref_ctx[row7] ||
+ !s->above_ref_ctx[col]);
+ } else {
+ c = (3 * !s->above_ref_ctx[col]) +
+ (!s->s.h.fixcompref || !td->left_ref_ctx[row7]);
+ }
+ } else if (s->above_comp_ctx[col]) {
+ c = (3 * !td->left_ref_ctx[row7]) +
+ (!s->s.h.fixcompref || !s->above_ref_ctx[col]);
+ } else {
+ c = 2 * !td->left_ref_ctx[row7] + 2 * !s->above_ref_ctx[col];
+ }
+ } else if (s->above_intra_ctx[col]) {
+ c = 2;
+ } else if (s->above_comp_ctx[col]) {
+ c = 1 + (!s->s.h.fixcompref || !s->above_ref_ctx[col]);
+ } else {
+ c = 4 * (!s->above_ref_ctx[col]);
+ }
+ } else if (have_l && !td->left_intra_ctx[row7]) {
+ if (td->left_intra_ctx[row7]) {
+ c = 2;
+ } else if (td->left_comp_ctx[row7]) {
+ c = 1 + (!s->s.h.fixcompref || !td->left_ref_ctx[row7]);
+ } else {
+ c = 4 * (!td->left_ref_ctx[row7]);
+ }
+ } else {
+ c = 2;
+ }
+ bit = vp56_rac_get_prob(td->c, s->prob.p.single_ref[c][0]);
+ td->counts.single_ref[c][0][bit]++;
+ if (!bit) {
+ b->ref[0] = 0;
+ } else {
+ // FIXME can this codeblob be replaced by some sort of LUT?
+ if (have_a) {
+ if (have_l) {
+ if (td->left_intra_ctx[row7]) {
+ if (s->above_intra_ctx[col]) {
+ c = 2;
+ } else if (s->above_comp_ctx[col]) {
+ c = 1 + 2 * (s->s.h.fixcompref == 1 ||
+ s->above_ref_ctx[col] == 1);
+ } else if (!s->above_ref_ctx[col]) {
+ c = 3;
+ } else {
+ c = 4 * (s->above_ref_ctx[col] == 1);
+ }
+ } else if (s->above_intra_ctx[col]) {
+ if (td->left_intra_ctx[row7]) {
+ c = 2;
+ } else if (td->left_comp_ctx[row7]) {
+ c = 1 + 2 * (s->s.h.fixcompref == 1 ||
+ td->left_ref_ctx[row7] == 1);
+ } else if (!td->left_ref_ctx[row7]) {
+ c = 3;
+ } else {
+ c = 4 * (td->left_ref_ctx[row7] == 1);
+ }
+ } else if (s->above_comp_ctx[col]) {
+ if (td->left_comp_ctx[row7]) {
+ if (td->left_ref_ctx[row7] == s->above_ref_ctx[col]) {
+ c = 3 * (s->s.h.fixcompref == 1 ||
+ td->left_ref_ctx[row7] == 1);
+ } else {
+ c = 2;
+ }
+ } else if (!td->left_ref_ctx[row7]) {
+ c = 1 + 2 * (s->s.h.fixcompref == 1 ||
+ s->above_ref_ctx[col] == 1);
+ } else {
+ c = 3 * (td->left_ref_ctx[row7] == 1) +
+ (s->s.h.fixcompref == 1 || s->above_ref_ctx[col] == 1);
+ }
+ } else if (td->left_comp_ctx[row7]) {
+ if (!s->above_ref_ctx[col]) {
+ c = 1 + 2 * (s->s.h.fixcompref == 1 ||
+ td->left_ref_ctx[row7] == 1);
+ } else {
+ c = 3 * (s->above_ref_ctx[col] == 1) +
+ (s->s.h.fixcompref == 1 || td->left_ref_ctx[row7] == 1);
+ }
+ } else if (!s->above_ref_ctx[col]) {
+ if (!td->left_ref_ctx[row7]) {
+ c = 3;
+ } else {
+ c = 4 * (td->left_ref_ctx[row7] == 1);
+ }
+ } else if (!td->left_ref_ctx[row7]) {
+ c = 4 * (s->above_ref_ctx[col] == 1);
+ } else {
+ c = 2 * (td->left_ref_ctx[row7] == 1) +
+ 2 * (s->above_ref_ctx[col] == 1);
+ }
+ } else {
+ if (s->above_intra_ctx[col] ||
+ (!s->above_comp_ctx[col] && !s->above_ref_ctx[col])) {
+ c = 2;
+ } else if (s->above_comp_ctx[col]) {
+ c = 3 * (s->s.h.fixcompref == 1 || s->above_ref_ctx[col] == 1);
+ } else {
+ c = 4 * (s->above_ref_ctx[col] == 1);
+ }
+ }
+ } else if (have_l) {
+ if (td->left_intra_ctx[row7] ||
+ (!td->left_comp_ctx[row7] && !td->left_ref_ctx[row7])) {
+ c = 2;
+ } else if (td->left_comp_ctx[row7]) {
+ c = 3 * (s->s.h.fixcompref == 1 || td->left_ref_ctx[row7] == 1);
+ } else {
+ c = 4 * (td->left_ref_ctx[row7] == 1);
+ }
+ } else {
+ c = 2;
+ }
+ bit = vp56_rac_get_prob(td->c, s->prob.p.single_ref[c][1]);
+ td->counts.single_ref[c][1][bit]++;
+ b->ref[0] = 1 + bit;
+ }
+ }
+ }
+
+ if (b->bs <= BS_8x8) {
+ if (s->s.h.segmentation.enabled && s->s.h.segmentation.feat[b->seg_id].skip_enabled) {
+ b->mode[0] =
+ b->mode[1] =
+ b->mode[2] =
+ b->mode[3] = ZEROMV;
+ } else {
+ static const uint8_t off[10] = {
+ 3, 0, 0, 1, 0, 0, 0, 0, 0, 0
+ };
+
+ // FIXME this needs to use the LUT tables from find_ref_mvs
+ // because not all are -1,0/0,-1
+ int c = inter_mode_ctx_lut[s->above_mode_ctx[col + off[b->bs]]]
+ [td->left_mode_ctx[row7 + off[b->bs]]];
+
+ b->mode[0] = vp8_rac_get_tree(td->c, ff_vp9_inter_mode_tree,
+ s->prob.p.mv_mode[c]);
+ b->mode[1] =
+ b->mode[2] =
+ b->mode[3] = b->mode[0];
+ td->counts.mv_mode[c][b->mode[0] - 10]++;
+ }
+ }
+
+ if (s->s.h.filtermode == FILTER_SWITCHABLE) {
+ int c;
+
+ if (have_a && s->above_mode_ctx[col] >= NEARESTMV) {
+ if (have_l && td->left_mode_ctx[row7] >= NEARESTMV) {
+ c = s->above_filter_ctx[col] == td->left_filter_ctx[row7] ?
+ td->left_filter_ctx[row7] : 3;
+ } else {
+ c = s->above_filter_ctx[col];
+ }
+ } else if (have_l && td->left_mode_ctx[row7] >= NEARESTMV) {
+ c = td->left_filter_ctx[row7];
+ } else {
+ c = 3;
+ }
+
+ filter_id = vp8_rac_get_tree(td->c, ff_vp9_filter_tree,
+ s->prob.p.filter[c]);
+ td->counts.filter[c][filter_id]++;
+ b->filter = ff_vp9_filter_lut[filter_id];
+ } else {
+ b->filter = s->s.h.filtermode;
+ }
+
+ if (b->bs > BS_8x8) {
+ int c = inter_mode_ctx_lut[s->above_mode_ctx[col]][td->left_mode_ctx[row7]];
+
+ b->mode[0] = vp8_rac_get_tree(td->c, ff_vp9_inter_mode_tree,
+ s->prob.p.mv_mode[c]);
+ td->counts.mv_mode[c][b->mode[0] - 10]++;
+ ff_vp9_fill_mv(td, b->mv[0], b->mode[0], 0);
+
+ if (b->bs != BS_8x4) {
+ b->mode[1] = vp8_rac_get_tree(td->c, ff_vp9_inter_mode_tree,
+ s->prob.p.mv_mode[c]);
+ td->counts.mv_mode[c][b->mode[1] - 10]++;
+ ff_vp9_fill_mv(td, b->mv[1], b->mode[1], 1);
+ } else {
+ b->mode[1] = b->mode[0];
+ AV_COPY32(&b->mv[1][0], &b->mv[0][0]);
+ AV_COPY32(&b->mv[1][1], &b->mv[0][1]);
+ }
+
+ if (b->bs != BS_4x8) {
+ b->mode[2] = vp8_rac_get_tree(td->c, ff_vp9_inter_mode_tree,
+ s->prob.p.mv_mode[c]);
+ td->counts.mv_mode[c][b->mode[2] - 10]++;
+ ff_vp9_fill_mv(td, b->mv[2], b->mode[2], 2);
+
+ if (b->bs != BS_8x4) {
+ b->mode[3] = vp8_rac_get_tree(td->c, ff_vp9_inter_mode_tree,
+ s->prob.p.mv_mode[c]);
+ td->counts.mv_mode[c][b->mode[3] - 10]++;
+ ff_vp9_fill_mv(td, b->mv[3], b->mode[3], 3);
+ } else {
+ b->mode[3] = b->mode[2];
+ AV_COPY32(&b->mv[3][0], &b->mv[2][0]);
+ AV_COPY32(&b->mv[3][1], &b->mv[2][1]);
+ }
+ } else {
+ b->mode[2] = b->mode[0];
+ AV_COPY32(&b->mv[2][0], &b->mv[0][0]);
+ AV_COPY32(&b->mv[2][1], &b->mv[0][1]);
+ b->mode[3] = b->mode[1];
+ AV_COPY32(&b->mv[3][0], &b->mv[1][0]);
+ AV_COPY32(&b->mv[3][1], &b->mv[1][1]);
+ }
+ } else {
+ ff_vp9_fill_mv(td, b->mv[0], b->mode[0], -1);
+ AV_COPY32(&b->mv[1][0], &b->mv[0][0]);
+ AV_COPY32(&b->mv[2][0], &b->mv[0][0]);
+ AV_COPY32(&b->mv[3][0], &b->mv[0][0]);
+ AV_COPY32(&b->mv[1][1], &b->mv[0][1]);
+ AV_COPY32(&b->mv[2][1], &b->mv[0][1]);
+ AV_COPY32(&b->mv[3][1], &b->mv[0][1]);
+ }
+
+ vref = b->ref[b->comp ? s->s.h.signbias[s->s.h.varcompref[0]] : 0];
+ }
+
+#if HAVE_FAST_64BIT
+#define SPLAT_CTX(var, val, n) \
+ switch (n) { \
+ case 1: var = val; break; \
+ case 2: AV_WN16A(&var, val * 0x0101); break; \
+ case 4: AV_WN32A(&var, val * 0x01010101); break; \
+ case 8: AV_WN64A(&var, val * 0x0101010101010101ULL); break; \
+ case 16: { \
+ uint64_t v64 = val * 0x0101010101010101ULL; \
+ AV_WN64A( &var, v64); \
+ AV_WN64A(&((uint8_t *) &var)[8], v64); \
+ break; \
+ } \
+ }
+#else
+#define SPLAT_CTX(var, val, n) \
+ switch (n) { \
+ case 1: var = val; break; \
+ case 2: AV_WN16A(&var, val * 0x0101); break; \
+ case 4: AV_WN32A(&var, val * 0x01010101); break; \
+ case 8: { \
+ uint32_t v32 = val * 0x01010101; \
+ AV_WN32A( &var, v32); \
+ AV_WN32A(&((uint8_t *) &var)[4], v32); \
+ break; \
+ } \
+ case 16: { \
+ uint32_t v32 = val * 0x01010101; \
+ AV_WN32A( &var, v32); \
+ AV_WN32A(&((uint8_t *) &var)[4], v32); \
+ AV_WN32A(&((uint8_t *) &var)[8], v32); \
+ AV_WN32A(&((uint8_t *) &var)[12], v32); \
+ break; \
+ } \
+ }
+#endif
+
+ switch (ff_vp9_bwh_tab[1][b->bs][0]) {
+#define SET_CTXS(perf, dir, off, n) \
+ do { \
+ SPLAT_CTX(perf->dir##_skip_ctx[off], b->skip, n); \
+ SPLAT_CTX(perf->dir##_txfm_ctx[off], b->tx, n); \
+ SPLAT_CTX(perf->dir##_partition_ctx[off], dir##_ctx[b->bs], n); \
+ if (!s->s.h.keyframe && !s->s.h.intraonly) { \
+ SPLAT_CTX(perf->dir##_intra_ctx[off], b->intra, n); \
+ SPLAT_CTX(perf->dir##_comp_ctx[off], b->comp, n); \
+ SPLAT_CTX(perf->dir##_mode_ctx[off], b->mode[3], n); \
+ if (!b->intra) { \
+ SPLAT_CTX(perf->dir##_ref_ctx[off], vref, n); \
+ if (s->s.h.filtermode == FILTER_SWITCHABLE) { \
+ SPLAT_CTX(perf->dir##_filter_ctx[off], filter_id, n); \
+ } \
+ } \
+ } \
+ } while (0)
+ case 1: SET_CTXS(s, above, col, 1); break;
+ case 2: SET_CTXS(s, above, col, 2); break;
+ case 4: SET_CTXS(s, above, col, 4); break;
+ case 8: SET_CTXS(s, above, col, 8); break;
+ }
+ switch (ff_vp9_bwh_tab[1][b->bs][1]) {
+ case 1: SET_CTXS(td, left, row7, 1); break;
+ case 2: SET_CTXS(td, left, row7, 2); break;
+ case 4: SET_CTXS(td, left, row7, 4); break;
+ case 8: SET_CTXS(td, left, row7, 8); break;
+ }
+#undef SPLAT_CTX
+#undef SET_CTXS
+
+ if (!s->s.h.keyframe && !s->s.h.intraonly) {
+ if (b->bs > BS_8x8) {
+ int mv0 = AV_RN32A(&b->mv[3][0]), mv1 = AV_RN32A(&b->mv[3][1]);
+
+ AV_COPY32(&td->left_mv_ctx[row7 * 2 + 0][0], &b->mv[1][0]);
+ AV_COPY32(&td->left_mv_ctx[row7 * 2 + 0][1], &b->mv[1][1]);
+ AV_WN32A(&td->left_mv_ctx[row7 * 2 + 1][0], mv0);
+ AV_WN32A(&td->left_mv_ctx[row7 * 2 + 1][1], mv1);
+ AV_COPY32(&s->above_mv_ctx[col * 2 + 0][0], &b->mv[2][0]);
+ AV_COPY32(&s->above_mv_ctx[col * 2 + 0][1], &b->mv[2][1]);
+ AV_WN32A(&s->above_mv_ctx[col * 2 + 1][0], mv0);
+ AV_WN32A(&s->above_mv_ctx[col * 2 + 1][1], mv1);
+ } else {
+ int n, mv0 = AV_RN32A(&b->mv[3][0]), mv1 = AV_RN32A(&b->mv[3][1]);
+
+ for (n = 0; n < w4 * 2; n++) {
+ AV_WN32A(&s->above_mv_ctx[col * 2 + n][0], mv0);
+ AV_WN32A(&s->above_mv_ctx[col * 2 + n][1], mv1);
+ }
+ for (n = 0; n < h4 * 2; n++) {
+ AV_WN32A(&td->left_mv_ctx[row7 * 2 + n][0], mv0);
+ AV_WN32A(&td->left_mv_ctx[row7 * 2 + n][1], mv1);
+ }
+ }
+ }
+
+ // FIXME kinda ugly
+ for (y = 0; y < h4; y++) {
+ int x, o = (row + y) * s->sb_cols * 8 + col;
+ VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[o];
+
+ if (b->intra) {
+ for (x = 0; x < w4; x++) {
+ mv[x].ref[0] =
+ mv[x].ref[1] = -1;
+ }
+ } else if (b->comp) {
+ for (x = 0; x < w4; x++) {
+ mv[x].ref[0] = b->ref[0];
+ mv[x].ref[1] = b->ref[1];
+ AV_COPY32(&mv[x].mv[0], &b->mv[3][0]);
+ AV_COPY32(&mv[x].mv[1], &b->mv[3][1]);
+ }
+ } else {
+ for (x = 0; x < w4; x++) {
+ mv[x].ref[0] = b->ref[0];
+ mv[x].ref[1] = -1;
+ AV_COPY32(&mv[x].mv[0], &b->mv[3][0]);
+ }
+ }
+ }
+}
+
+// FIXME merge cnt/eob arguments?
+static av_always_inline int
+decode_coeffs_b_generic(VP56RangeCoder *c, int16_t *coef, int n_coeffs,
+ int is_tx32x32, int is8bitsperpixel, int bpp, unsigned (*cnt)[6][3],
+ unsigned (*eob)[6][2], uint8_t (*p)[6][11],
+ int nnz, const int16_t *scan, const int16_t (*nb)[2],
+ const int16_t *band_counts, int16_t *qmul)
+{
+ int i = 0, band = 0, band_left = band_counts[band];
+ const uint8_t *tp = p[0][nnz];
+ uint8_t cache[1024];
+
+ do {
+ int val, rc;
+
+ val = vp56_rac_get_prob_branchy(c, tp[0]); // eob
+ eob[band][nnz][val]++;
+ if (!val)
+ break;
+
+skip_eob:
+ if (!vp56_rac_get_prob_branchy(c, tp[1])) { // zero
+ cnt[band][nnz][0]++;
+ if (!--band_left)
+ band_left = band_counts[++band];
+ cache[scan[i]] = 0;
+ nnz = (1 + cache[nb[i][0]] + cache[nb[i][1]]) >> 1;
+ tp = p[band][nnz];
+ if (++i == n_coeffs)
+ break; //invalid input; blocks should end with EOB
+ goto skip_eob;
+ }
+
+ rc = scan[i];
+ if (!vp56_rac_get_prob_branchy(c, tp[2])) { // one
+ cnt[band][nnz][1]++;
+ val = 1;
+ cache[rc] = 1;
+ } else {
+ cnt[band][nnz][2]++;
+ if (!vp56_rac_get_prob_branchy(c, tp[3])) { // 2, 3, 4
+ if (!vp56_rac_get_prob_branchy(c, tp[4])) {
+ cache[rc] = val = 2;
+ } else {
+ val = 3 + vp56_rac_get_prob(c, tp[5]);
+ cache[rc] = 3;
+ }
+ } else if (!vp56_rac_get_prob_branchy(c, tp[6])) { // cat1/2
+ cache[rc] = 4;
+ if (!vp56_rac_get_prob_branchy(c, tp[7])) {
+ val = vp56_rac_get_prob(c, 159) + 5;
+ } else {
+ val = (vp56_rac_get_prob(c, 165) << 1) + 7;
+ val += vp56_rac_get_prob(c, 145);
+ }
+ } else { // cat 3-6
+ cache[rc] = 5;
+ if (!vp56_rac_get_prob_branchy(c, tp[8])) {
+ if (!vp56_rac_get_prob_branchy(c, tp[9])) {
+ val = 11 + (vp56_rac_get_prob(c, 173) << 2);
+ val += (vp56_rac_get_prob(c, 148) << 1);
+ val += vp56_rac_get_prob(c, 140);
+ } else {
+ val = 19 + (vp56_rac_get_prob(c, 176) << 3);
+ val += (vp56_rac_get_prob(c, 155) << 2);
+ val += (vp56_rac_get_prob(c, 140) << 1);
+ val += vp56_rac_get_prob(c, 135);
+ }
+ } else if (!vp56_rac_get_prob_branchy(c, tp[10])) {
+ val = (vp56_rac_get_prob(c, 180) << 4) + 35;
+ val += (vp56_rac_get_prob(c, 157) << 3);
+ val += (vp56_rac_get_prob(c, 141) << 2);
+ val += (vp56_rac_get_prob(c, 134) << 1);
+ val += vp56_rac_get_prob(c, 130);
+ } else {
+ val = 67;
+ if (!is8bitsperpixel) {
+ if (bpp == 12) {
+ val += vp56_rac_get_prob(c, 255) << 17;
+ val += vp56_rac_get_prob(c, 255) << 16;
+ }
+ val += (vp56_rac_get_prob(c, 255) << 15);
+ val += (vp56_rac_get_prob(c, 255) << 14);
+ }
+ val += (vp56_rac_get_prob(c, 254) << 13);
+ val += (vp56_rac_get_prob(c, 254) << 12);
+ val += (vp56_rac_get_prob(c, 254) << 11);
+ val += (vp56_rac_get_prob(c, 252) << 10);
+ val += (vp56_rac_get_prob(c, 249) << 9);
+ val += (vp56_rac_get_prob(c, 243) << 8);
+ val += (vp56_rac_get_prob(c, 230) << 7);
+ val += (vp56_rac_get_prob(c, 196) << 6);
+ val += (vp56_rac_get_prob(c, 177) << 5);
+ val += (vp56_rac_get_prob(c, 153) << 4);
+ val += (vp56_rac_get_prob(c, 140) << 3);
+ val += (vp56_rac_get_prob(c, 133) << 2);
+ val += (vp56_rac_get_prob(c, 130) << 1);
+ val += vp56_rac_get_prob(c, 129);
+ }
+ }
+ }
+#define STORE_COEF(c, i, v) do { \
+ if (is8bitsperpixel) { \
+ c[i] = v; \
+ } else { \
+ AV_WN32A(&c[i * 2], v); \
+ } \
+} while (0)
+ if (!--band_left)
+ band_left = band_counts[++band];
+ if (is_tx32x32)
+ STORE_COEF(coef, rc, (int)((vp8_rac_get(c) ? -val : val) * (unsigned)qmul[!!i]) / 2);
+ else
+ STORE_COEF(coef, rc, (vp8_rac_get(c) ? -val : val) * (unsigned)qmul[!!i]);
+ nnz = (1 + cache[nb[i][0]] + cache[nb[i][1]]) >> 1;
+ tp = p[band][nnz];
+ } while (++i < n_coeffs);
+
+ return i;
+}
+
+static int decode_coeffs_b_8bpp(VP9TileData *td, int16_t *coef, int n_coeffs,
+ unsigned (*cnt)[6][3], unsigned (*eob)[6][2],
+ uint8_t (*p)[6][11], int nnz, const int16_t *scan,
+ const int16_t (*nb)[2], const int16_t *band_counts,
+ int16_t *qmul)
+{
+ return decode_coeffs_b_generic(td->c, coef, n_coeffs, 0, 1, 8, cnt, eob, p,
+ nnz, scan, nb, band_counts, qmul);
+}
+
+static int decode_coeffs_b32_8bpp(VP9TileData *td, int16_t *coef, int n_coeffs,
+ unsigned (*cnt)[6][3], unsigned (*eob)[6][2],
+ uint8_t (*p)[6][11], int nnz, const int16_t *scan,
+ const int16_t (*nb)[2], const int16_t *band_counts,
+ int16_t *qmul)
+{
+ return decode_coeffs_b_generic(td->c, coef, n_coeffs, 1, 1, 8, cnt, eob, p,
+ nnz, scan, nb, band_counts, qmul);
+}
+
+static int decode_coeffs_b_16bpp(VP9TileData *td, int16_t *coef, int n_coeffs,
+ unsigned (*cnt)[6][3], unsigned (*eob)[6][2],
+ uint8_t (*p)[6][11], int nnz, const int16_t *scan,
+ const int16_t (*nb)[2], const int16_t *band_counts,
+ int16_t *qmul)
+{
+ return decode_coeffs_b_generic(td->c, coef, n_coeffs, 0, 0, td->s->s.h.bpp, cnt, eob, p,
+ nnz, scan, nb, band_counts, qmul);
+}
+
+static int decode_coeffs_b32_16bpp(VP9TileData *td, int16_t *coef, int n_coeffs,
+ unsigned (*cnt)[6][3], unsigned (*eob)[6][2],
+ uint8_t (*p)[6][11], int nnz, const int16_t *scan,
+ const int16_t (*nb)[2], const int16_t *band_counts,
+ int16_t *qmul)
+{
+ return decode_coeffs_b_generic(td->c, coef, n_coeffs, 1, 0, td->s->s.h.bpp, cnt, eob, p,
+ nnz, scan, nb, band_counts, qmul);
+}
+
+static av_always_inline int decode_coeffs(VP9TileData *td, int is8bitsperpixel)
+{
+ VP9Context *s = td->s;
+ VP9Block *b = td->b;
+ int row = td->row, col = td->col;
+ uint8_t (*p)[6][11] = s->prob.coef[b->tx][0 /* y */][!b->intra];
+ unsigned (*c)[6][3] = td->counts.coef[b->tx][0 /* y */][!b->intra];
+ unsigned (*e)[6][2] = td->counts.eob[b->tx][0 /* y */][!b->intra];
+ int w4 = ff_vp9_bwh_tab[1][b->bs][0] << 1, h4 = ff_vp9_bwh_tab[1][b->bs][1] << 1;
+ int end_x = FFMIN(2 * (s->cols - col), w4);
+ int end_y = FFMIN(2 * (s->rows - row), h4);
+ int n, pl, x, y, ret;
+ int16_t (*qmul)[2] = s->s.h.segmentation.feat[b->seg_id].qmul;
+ int tx = 4 * s->s.h.lossless + b->tx;
+ const int16_t * const *yscans = ff_vp9_scans[tx];
+ const int16_t (* const * ynbs)[2] = ff_vp9_scans_nb[tx];
+ const int16_t *uvscan = ff_vp9_scans[b->uvtx][DCT_DCT];
+ const int16_t (*uvnb)[2] = ff_vp9_scans_nb[b->uvtx][DCT_DCT];
+ uint8_t *a = &s->above_y_nnz_ctx[col * 2];
+ uint8_t *l = &td->left_y_nnz_ctx[(row & 7) << 1];
+ static const int16_t band_counts[4][8] = {
+ { 1, 2, 3, 4, 3, 16 - 13 },
+ { 1, 2, 3, 4, 11, 64 - 21 },
+ { 1, 2, 3, 4, 11, 256 - 21 },
+ { 1, 2, 3, 4, 11, 1024 - 21 },
+ };
+ const int16_t *y_band_counts = band_counts[b->tx];
+ const int16_t *uv_band_counts = band_counts[b->uvtx];
+ int bytesperpixel = is8bitsperpixel ? 1 : 2;
+ int total_coeff = 0;
+
+#define MERGE(la, end, step, rd) \
+ for (n = 0; n < end; n += step) \
+ la[n] = !!rd(&la[n])
+#define MERGE_CTX(step, rd) \
+ do { \
+ MERGE(l, end_y, step, rd); \
+ MERGE(a, end_x, step, rd); \
+ } while (0)
+
+#define DECODE_Y_COEF_LOOP(step, mode_index, v) \
+ for (n = 0, y = 0; y < end_y; y += step) { \
+ for (x = 0; x < end_x; x += step, n += step * step) { \
+ enum TxfmType txtp = ff_vp9_intra_txfm_type[b->mode[mode_index]]; \
+ ret = (is8bitsperpixel ? decode_coeffs_b##v##_8bpp : decode_coeffs_b##v##_16bpp) \
+ (td, td->block + 16 * n * bytesperpixel, 16 * step * step, \
+ c, e, p, a[x] + l[y], yscans[txtp], \
+ ynbs[txtp], y_band_counts, qmul[0]); \
+ a[x] = l[y] = !!ret; \
+ total_coeff |= !!ret; \
+ if (step >= 4) { \
+ AV_WN16A(&td->eob[n], ret); \
+ } else { \
+ td->eob[n] = ret; \
+ } \
+ } \
+ }
+
+#define SPLAT(la, end, step, cond) \
+ if (step == 2) { \
+ for (n = 1; n < end; n += step) \
+ la[n] = la[n - 1]; \
+ } else if (step == 4) { \
+ if (cond) { \
+ for (n = 0; n < end; n += step) \
+ AV_WN32A(&la[n], la[n] * 0x01010101); \
+ } else { \
+ for (n = 0; n < end; n += step) \
+ memset(&la[n + 1], la[n], FFMIN(end - n - 1, 3)); \
+ } \
+ } else /* step == 8 */ { \
+ if (cond) { \
+ if (HAVE_FAST_64BIT) { \
+ for (n = 0; n < end; n += step) \
+ AV_WN64A(&la[n], la[n] * 0x0101010101010101ULL); \
+ } else { \
+ for (n = 0; n < end; n += step) { \
+ uint32_t v32 = la[n] * 0x01010101; \
+ AV_WN32A(&la[n], v32); \
+ AV_WN32A(&la[n + 4], v32); \
+ } \
+ } \
+ } else { \
+ for (n = 0; n < end; n += step) \
+ memset(&la[n + 1], la[n], FFMIN(end - n - 1, 7)); \
+ } \
+ }
+#define SPLAT_CTX(step) \
+ do { \
+ SPLAT(a, end_x, step, end_x == w4); \
+ SPLAT(l, end_y, step, end_y == h4); \
+ } while (0)
+
+ /* y tokens */
+ switch (b->tx) {
+ case TX_4X4:
+ DECODE_Y_COEF_LOOP(1, b->bs > BS_8x8 ? n : 0,);
+ break;
+ case TX_8X8:
+ MERGE_CTX(2, AV_RN16A);
+ DECODE_Y_COEF_LOOP(2, 0,);
+ SPLAT_CTX(2);
+ break;
+ case TX_16X16:
+ MERGE_CTX(4, AV_RN32A);
+ DECODE_Y_COEF_LOOP(4, 0,);
+ SPLAT_CTX(4);
+ break;
+ case TX_32X32:
+ MERGE_CTX(8, AV_RN64A);
+ DECODE_Y_COEF_LOOP(8, 0, 32);
+ SPLAT_CTX(8);
+ break;
+ }
+
+#define DECODE_UV_COEF_LOOP(step, v) \
+ for (n = 0, y = 0; y < end_y; y += step) { \
+ for (x = 0; x < end_x; x += step, n += step * step) { \
+ ret = (is8bitsperpixel ? decode_coeffs_b##v##_8bpp : decode_coeffs_b##v##_16bpp) \
+ (td, td->uvblock[pl] + 16 * n * bytesperpixel, \
+ 16 * step * step, c, e, p, a[x] + l[y], \
+ uvscan, uvnb, uv_band_counts, qmul[1]); \
+ a[x] = l[y] = !!ret; \
+ total_coeff |= !!ret; \
+ if (step >= 4) { \
+ AV_WN16A(&td->uveob[pl][n], ret); \
+ } else { \
+ td->uveob[pl][n] = ret; \
+ } \
+ } \
+ }
+
+ p = s->prob.coef[b->uvtx][1 /* uv */][!b->intra];
+ c = td->counts.coef[b->uvtx][1 /* uv */][!b->intra];
+ e = td->counts.eob[b->uvtx][1 /* uv */][!b->intra];
+ w4 >>= s->ss_h;
+ end_x >>= s->ss_h;
+ h4 >>= s->ss_v;
+ end_y >>= s->ss_v;
+ for (pl = 0; pl < 2; pl++) {
+ a = &s->above_uv_nnz_ctx[pl][col << !s->ss_h];
+ l = &td->left_uv_nnz_ctx[pl][(row & 7) << !s->ss_v];
+ switch (b->uvtx) {
+ case TX_4X4:
+ DECODE_UV_COEF_LOOP(1,);
+ break;
+ case TX_8X8:
+ MERGE_CTX(2, AV_RN16A);
+ DECODE_UV_COEF_LOOP(2,);
+ SPLAT_CTX(2);
+ break;
+ case TX_16X16:
+ MERGE_CTX(4, AV_RN32A);
+ DECODE_UV_COEF_LOOP(4,);
+ SPLAT_CTX(4);
+ break;
+ case TX_32X32:
+ MERGE_CTX(8, AV_RN64A);
+ DECODE_UV_COEF_LOOP(8, 32);
+ SPLAT_CTX(8);
+ break;
+ }
+ }
+
+ return total_coeff;
+}
+
+static int decode_coeffs_8bpp(VP9TileData *td)
+{
+ return decode_coeffs(td, 1);
+}
+
+static int decode_coeffs_16bpp(VP9TileData *td)
+{
+ return decode_coeffs(td, 0);
+}
+
+static av_always_inline void mask_edges(uint8_t (*mask)[8][4], int ss_h, int ss_v,
+ int row_and_7, int col_and_7,
+ int w, int h, int col_end, int row_end,
+ enum TxfmMode tx, int skip_inter)
+{
+ static const unsigned wide_filter_col_mask[2] = { 0x11, 0x01 };
+ static const unsigned wide_filter_row_mask[2] = { 0x03, 0x07 };
+
+ // FIXME I'm pretty sure all loops can be replaced by a single LUT if
+ // we make VP9Filter.mask uint64_t (i.e. row/col all single variable)
+ // and make the LUT 5-indexed (bl, bp, is_uv, tx and row/col), and then
+ // use row_and_7/col_and_7 as shifts (1*col_and_7+8*row_and_7)
+
+ // the intended behaviour of the vp9 loopfilter is to work on 8-pixel
+ // edges. This means that for UV, we work on two subsampled blocks at
+ // a time, and we only use the topleft block's mode information to set
+ // things like block strength. Thus, for any block size smaller than
+ // 16x16, ignore the odd portion of the block.
+ if (tx == TX_4X4 && (ss_v | ss_h)) {
+ if (h == ss_v) {
+ if (row_and_7 & 1)
+ return;
+ if (!row_end)
+ h += 1;
+ }
+ if (w == ss_h) {
+ if (col_and_7 & 1)
+ return;
+ if (!col_end)
+ w += 1;
+ }
+ }
+
+ if (tx == TX_4X4 && !skip_inter) {
+ int t = 1 << col_and_7, m_col = (t << w) - t, y;
+ // on 32-px edges, use the 8-px wide loopfilter; else, use 4-px wide
+ int m_row_8 = m_col & wide_filter_col_mask[ss_h], m_row_4 = m_col - m_row_8;
+
+ for (y = row_and_7; y < h + row_and_7; y++) {
+ int col_mask_id = 2 - !(y & wide_filter_row_mask[ss_v]);
+
+ mask[0][y][1] |= m_row_8;
+ mask[0][y][2] |= m_row_4;
+ // for odd lines, if the odd col is not being filtered,
+ // skip odd row also:
+ // .---. <-- a
+ // | |
+ // |___| <-- b
+ // ^ ^
+ // c d
+ //
+ // if a/c are even row/col and b/d are odd, and d is skipped,
+ // e.g. right edge of size-66x66.webm, then skip b also (bug)
+ if ((ss_h & ss_v) && (col_end & 1) && (y & 1)) {
+ mask[1][y][col_mask_id] |= (t << (w - 1)) - t;
+ } else {
+ mask[1][y][col_mask_id] |= m_col;
+ }
+ if (!ss_h)
+ mask[0][y][3] |= m_col;
+ if (!ss_v) {
+ if (ss_h && (col_end & 1))
+ mask[1][y][3] |= (t << (w - 1)) - t;
+ else
+ mask[1][y][3] |= m_col;
+ }
+ }
+ } else {
+ int y, t = 1 << col_and_7, m_col = (t << w) - t;
+
+ if (!skip_inter) {
+ int mask_id = (tx == TX_8X8);
+ int l2 = tx + ss_h - 1, step1d;
+ static const unsigned masks[4] = { 0xff, 0x55, 0x11, 0x01 };
+ int m_row = m_col & masks[l2];
+
+ // at odd UV col/row edges tx16/tx32 loopfilter edges, force
+ // 8wd loopfilter to prevent going off the visible edge.
+ if (ss_h && tx > TX_8X8 && (w ^ (w - 1)) == 1) {
+ int m_row_16 = ((t << (w - 1)) - t) & masks[l2];
+ int m_row_8 = m_row - m_row_16;
+
+ for (y = row_and_7; y < h + row_and_7; y++) {
+ mask[0][y][0] |= m_row_16;
+ mask[0][y][1] |= m_row_8;
+ }
+ } else {
+ for (y = row_and_7; y < h + row_and_7; y++)
+ mask[0][y][mask_id] |= m_row;
+ }
+
+ l2 = tx + ss_v - 1;
+ step1d = 1 << l2;
+ if (ss_v && tx > TX_8X8 && (h ^ (h - 1)) == 1) {
+ for (y = row_and_7; y < h + row_and_7 - 1; y += step1d)
+ mask[1][y][0] |= m_col;
+ if (y - row_and_7 == h - 1)
+ mask[1][y][1] |= m_col;
+ } else {
+ for (y = row_and_7; y < h + row_and_7; y += step1d)
+ mask[1][y][mask_id] |= m_col;
+ }
+ } else if (tx != TX_4X4) {
+ int mask_id;
+
+ mask_id = (tx == TX_8X8) || (h == ss_v);
+ mask[1][row_and_7][mask_id] |= m_col;
+ mask_id = (tx == TX_8X8) || (w == ss_h);
+ for (y = row_and_7; y < h + row_and_7; y++)
+ mask[0][y][mask_id] |= t;
+ } else {
+ int t8 = t & wide_filter_col_mask[ss_h], t4 = t - t8;
+
+ for (y = row_and_7; y < h + row_and_7; y++) {
+ mask[0][y][2] |= t4;
+ mask[0][y][1] |= t8;
+ }
+ mask[1][row_and_7][2 - !(row_and_7 & wide_filter_row_mask[ss_v])] |= m_col;
+ }
+ }
+}
+
+void ff_vp9_decode_block(VP9TileData *td, int row, int col,
+ VP9Filter *lflvl, ptrdiff_t yoff, ptrdiff_t uvoff,
+ enum BlockLevel bl, enum BlockPartition bp)
+{
+ VP9Context *s = td->s;
+ VP9Block *b = td->b;
+ enum BlockSize bs = bl * 3 + bp;
+ int bytesperpixel = s->bytesperpixel;
+ int w4 = ff_vp9_bwh_tab[1][bs][0], h4 = ff_vp9_bwh_tab[1][bs][1], lvl;
+ int emu[2];
+ AVFrame *f = s->s.frames[CUR_FRAME].tf.f;
+
+ td->row = row;
+ td->row7 = row & 7;
+ td->col = col;
+ td->col7 = col & 7;
+
+ td->min_mv.x = -(128 + col * 64);
+ td->min_mv.y = -(128 + row * 64);
+ td->max_mv.x = 128 + (s->cols - col - w4) * 64;
+ td->max_mv.y = 128 + (s->rows - row - h4) * 64;
+
+ if (s->pass < 2) {
+ b->bs = bs;
+ b->bl = bl;
+ b->bp = bp;
+ decode_mode(td);
+ b->uvtx = b->tx - ((s->ss_h && w4 * 2 == (1 << b->tx)) ||
+ (s->ss_v && h4 * 2 == (1 << b->tx)));
+
+ if (!b->skip) {
+ int has_coeffs;
+
+ if (bytesperpixel == 1) {
+ has_coeffs = decode_coeffs_8bpp(td);
+ } else {
+ has_coeffs = decode_coeffs_16bpp(td);
+ }
+ if (!has_coeffs && b->bs <= BS_8x8 && !b->intra) {
+ b->skip = 1;
+ memset(&s->above_skip_ctx[col], 1, w4);
+ memset(&td->left_skip_ctx[td->row7], 1, h4);
+ }
+ } else {
+ int row7 = td->row7;
+
+#define SPLAT_ZERO_CTX(v, n) \
+ switch (n) { \
+ case 1: v = 0; break; \
+ case 2: AV_ZERO16(&v); break; \
+ case 4: AV_ZERO32(&v); break; \
+ case 8: AV_ZERO64(&v); break; \
+ case 16: AV_ZERO128(&v); break; \
+ }
+#define SPLAT_ZERO_YUV(dir, var, off, n, dir2) \
+ do { \
+ SPLAT_ZERO_CTX(dir##_y_##var[off * 2], n * 2); \
+ if (s->ss_##dir2) { \
+ SPLAT_ZERO_CTX(dir##_uv_##var[0][off], n); \
+ SPLAT_ZERO_CTX(dir##_uv_##var[1][off], n); \
+ } else { \
+ SPLAT_ZERO_CTX(dir##_uv_##var[0][off * 2], n * 2); \
+ SPLAT_ZERO_CTX(dir##_uv_##var[1][off * 2], n * 2); \
+ } \
+ } while (0)
+
+ switch (w4) {
+ case 1: SPLAT_ZERO_YUV(s->above, nnz_ctx, col, 1, h); break;
+ case 2: SPLAT_ZERO_YUV(s->above, nnz_ctx, col, 2, h); break;
+ case 4: SPLAT_ZERO_YUV(s->above, nnz_ctx, col, 4, h); break;
+ case 8: SPLAT_ZERO_YUV(s->above, nnz_ctx, col, 8, h); break;
+ }
+ switch (h4) {
+ case 1: SPLAT_ZERO_YUV(td->left, nnz_ctx, row7, 1, v); break;
+ case 2: SPLAT_ZERO_YUV(td->left, nnz_ctx, row7, 2, v); break;
+ case 4: SPLAT_ZERO_YUV(td->left, nnz_ctx, row7, 4, v); break;
+ case 8: SPLAT_ZERO_YUV(td->left, nnz_ctx, row7, 8, v); break;
+ }
+ }
+
+ if (s->pass == 1) {
+ s->td[0].b++;
+ s->td[0].block += w4 * h4 * 64 * bytesperpixel;
+ s->td[0].uvblock[0] += w4 * h4 * 64 * bytesperpixel >> (s->ss_h + s->ss_v);
+ s->td[0].uvblock[1] += w4 * h4 * 64 * bytesperpixel >> (s->ss_h + s->ss_v);
+ s->td[0].eob += 4 * w4 * h4;
+ s->td[0].uveob[0] += 4 * w4 * h4 >> (s->ss_h + s->ss_v);
+ s->td[0].uveob[1] += 4 * w4 * h4 >> (s->ss_h + s->ss_v);
+
+ return;
+ }
+ }
+
+ // emulated overhangs if the stride of the target buffer can't hold. This
+ // makes it possible to support emu-edge and so on even if we have large block
+ // overhangs
+ emu[0] = (col + w4) * 8 * bytesperpixel > f->linesize[0] ||
+ (row + h4) > s->rows;
+ emu[1] = ((col + w4) * 8 >> s->ss_h) * bytesperpixel > f->linesize[1] ||
+ (row + h4) > s->rows;
+ if (emu[0]) {
+ td->dst[0] = td->tmp_y;
+ td->y_stride = 128;
+ } else {
+ td->dst[0] = f->data[0] + yoff;
+ td->y_stride = f->linesize[0];
+ }
+ if (emu[1]) {
+ td->dst[1] = td->tmp_uv[0];
+ td->dst[2] = td->tmp_uv[1];
+ td->uv_stride = 128;
+ } else {
+ td->dst[1] = f->data[1] + uvoff;
+ td->dst[2] = f->data[2] + uvoff;
+ td->uv_stride = f->linesize[1];
+ }
+ if (b->intra) {
+ if (s->s.h.bpp > 8) {
+ ff_vp9_intra_recon_16bpp(td, yoff, uvoff);
+ } else {
+ ff_vp9_intra_recon_8bpp(td, yoff, uvoff);
+ }
+ } else {
+ if (s->s.h.bpp > 8) {
+ ff_vp9_inter_recon_16bpp(td);
+ } else {
+ ff_vp9_inter_recon_8bpp(td);
+ }
+ }
+ if (emu[0]) {
+ int w = FFMIN(s->cols - col, w4) * 8, h = FFMIN(s->rows - row, h4) * 8, n, o = 0;
+
+ for (n = 0; o < w; n++) {
+ int bw = 64 >> n;
+
+ av_assert2(n <= 4);
+ if (w & bw) {
+ s->dsp.mc[n][0][0][0][0](f->data[0] + yoff + o * bytesperpixel, f->linesize[0],
+ td->tmp_y + o * bytesperpixel, 128, h, 0, 0);
+ o += bw;
+ }
+ }
+ }
+ if (emu[1]) {
+ int w = FFMIN(s->cols - col, w4) * 8 >> s->ss_h;
+ int h = FFMIN(s->rows - row, h4) * 8 >> s->ss_v, n, o = 0;
+
+ for (n = s->ss_h; o < w; n++) {
+ int bw = 64 >> n;
+
+ av_assert2(n <= 4);
+ if (w & bw) {
+ s->dsp.mc[n][0][0][0][0](f->data[1] + uvoff + o * bytesperpixel, f->linesize[1],
+ td->tmp_uv[0] + o * bytesperpixel, 128, h, 0, 0);
+ s->dsp.mc[n][0][0][0][0](f->data[2] + uvoff + o * bytesperpixel, f->linesize[2],
+ td->tmp_uv[1] + o * bytesperpixel, 128, h, 0, 0);
+ o += bw;
+ }
+ }
+ }
+
+ // pick filter level and find edges to apply filter to
+ if (s->s.h.filter.level &&
+ (lvl = s->s.h.segmentation.feat[b->seg_id].lflvl[b->intra ? 0 : b->ref[0] + 1]
+ [b->mode[3] != ZEROMV]) > 0) {
+ int x_end = FFMIN(s->cols - col, w4), y_end = FFMIN(s->rows - row, h4);
+ int skip_inter = !b->intra && b->skip, col7 = td->col7, row7 = td->row7;
+
+ setctx_2d(&lflvl->level[row7 * 8 + col7], w4, h4, 8, lvl);
+ mask_edges(lflvl->mask[0], 0, 0, row7, col7, x_end, y_end, 0, 0, b->tx, skip_inter);
+ if (s->ss_h || s->ss_v)
+ mask_edges(lflvl->mask[1], s->ss_h, s->ss_v, row7, col7, x_end, y_end,
+ s->cols & 1 && col + w4 >= s->cols ? s->cols & 7 : 0,
+ s->rows & 1 && row + h4 >= s->rows ? s->rows & 7 : 0,
+ b->uvtx, skip_inter);
+ }
+
+ if (s->pass == 2) {
+ s->td[0].b++;
+ s->td[0].block += w4 * h4 * 64 * bytesperpixel;
+ s->td[0].uvblock[0] += w4 * h4 * 64 * bytesperpixel >> (s->ss_v + s->ss_h);
+ s->td[0].uvblock[1] += w4 * h4 * 64 * bytesperpixel >> (s->ss_v + s->ss_h);
+ s->td[0].eob += 4 * w4 * h4;
+ s->td[0].uveob[0] += 4 * w4 * h4 >> (s->ss_v + s->ss_h);
+ s->td[0].uveob[1] += 4 * w4 * h4 >> (s->ss_v + s->ss_h);
+ }
+}
diff --git a/media/ffvpx/libavcodec/vp9data.c b/media/ffvpx/libavcodec/vp9data.c
new file mode 100644
index 000000000..7af8a97b1
--- /dev/null
+++ b/media/ffvpx/libavcodec/vp9data.c
@@ -0,0 +1,2247 @@
+/*
+ * Copyright (C) 2013 Ronald S. Bultje <rsbultje gmail com>
+ * Copyright (C) 2013 Clément Bœsch <u pkh me>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "vp9.h"
+#include "vp9data.h"
+
+const uint8_t ff_vp9_bwh_tab[2][N_BS_SIZES][2] = {
+ {
+ { 16, 16 }, { 16, 8 }, { 8, 16 }, { 8, 8 }, { 8, 4 }, { 4, 8 },
+ { 4, 4 }, { 4, 2 }, { 2, 4 }, { 2, 2 }, { 2, 1 }, { 1, 2 }, { 1, 1 },
+ }, {
+ { 8, 8 }, { 8, 4 }, { 4, 8 }, { 4, 4 }, { 4, 2 }, { 2, 4 },
+ { 2, 2 }, { 2, 1 }, { 1, 2 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 1, 1 },
+ }
+};
+
+const int8_t ff_vp9_partition_tree[3][2] = {
+ { -PARTITION_NONE, 1 }, // '0'
+ { -PARTITION_H, 2 }, // '10'
+ { -PARTITION_V, -PARTITION_SPLIT }, // '110', '111'
+};
+
+const uint8_t ff_vp9_default_kf_partition_probs[4][4][3] = {
+ { /* 64x64 -> 32x32 */
+ { 174, 35, 49 } /* a/l both not split */,
+ { 68, 11, 27 } /* a split, l not split */,
+ { 57, 15, 9 } /* l split, a not split */,
+ { 12, 3, 3 } /* a/l both split */
+ }, { /* 32x32 -> 16x16 */
+ { 150, 40, 39 } /* a/l both not split */,
+ { 78, 12, 26 } /* a split, l not split */,
+ { 67, 33, 11 } /* l split, a not split */,
+ { 24, 7, 5 } /* a/l both split */,
+ }, { /* 16x16 -> 8x8 */
+ { 149, 53, 53 } /* a/l both not split */,
+ { 94, 20, 48 } /* a split, l not split */,
+ { 83, 53, 24 } /* l split, a not split */,
+ { 52, 18, 18 } /* a/l both split */,
+ }, { /* 8x8 -> 4x4 */
+ { 158, 97, 94 } /* a/l both not split */,
+ { 93, 24, 99 } /* a split, l not split */,
+ { 85, 119, 44 } /* l split, a not split */,
+ { 62, 59, 67 } /* a/l both split */,
+ },
+};
+
+const int8_t ff_vp9_segmentation_tree[7][2] = {
+ { 1, 2 },
+ { 3, 4 },
+ { 5, 6 },
+ { -0, -1 }, // '00x'
+ { -2, -3 }, // '01x'
+ { -4, -5 }, // '10x'
+ { -6, -7 }, // '11x'
+};
+
+const int8_t ff_vp9_intramode_tree[9][2] = {
+ { -DC_PRED, 1 }, // '0'
+ { -TM_VP8_PRED, 2 }, // '10'
+ { -VERT_PRED, 3 }, // '110'
+ { 4, 6 },
+ { -HOR_PRED, 5 }, // '11100'
+ { -DIAG_DOWN_RIGHT_PRED, -VERT_RIGHT_PRED }, // '11101x'
+ { -DIAG_DOWN_LEFT_PRED, 7 }, // '11110'
+ { -VERT_LEFT_PRED, 8 }, // '111110'
+ { -HOR_DOWN_PRED, -HOR_UP_PRED }, // '111111x'
+};
+
+const uint8_t ff_vp9_default_kf_ymode_probs[10][10][9] = {
+ { /* above = v */
+ { 43, 46, 168, 134, 107, 128, 69, 142, 92 } /* left = v */,
+ { 44, 29, 68, 159, 201, 177, 50, 57, 77 } /* left = h */,
+ { 63, 36, 126, 146, 123, 158, 60, 90, 96 } /* left = dc */,
+ { 58, 38, 76, 114, 97, 172, 78, 133, 92 } /* left = d45 */,
+ { 46, 41, 76, 140, 63, 184, 69, 112, 57 } /* left = d135 */,
+ { 38, 32, 85, 140, 46, 112, 54, 151, 133 } /* left = d117 */,
+ { 39, 27, 61, 131, 110, 175, 44, 75, 136 } /* left = d153 */,
+ { 47, 35, 80, 100, 74, 143, 64, 163, 74 } /* left = d63 */,
+ { 52, 30, 74, 113, 130, 175, 51, 64, 58 } /* left = d27 */,
+ { 36, 61, 116, 114, 128, 162, 80, 125, 82 } /* left = tm */
+ }, { /* above = h */
+ { 55, 44, 68, 166, 179, 192, 57, 57, 108 } /* left = v */,
+ { 42, 26, 11, 199, 241, 228, 23, 15, 85 } /* left = h */,
+ { 82, 26, 26, 171, 208, 204, 44, 32, 105 } /* left = dc */,
+ { 68, 42, 19, 131, 160, 199, 55, 52, 83 } /* left = d45 */,
+ { 58, 50, 25, 139, 115, 232, 39, 52, 118 } /* left = d135 */,
+ { 50, 35, 33, 153, 104, 162, 64, 59, 131 } /* left = d117 */,
+ { 44, 24, 16, 150, 177, 202, 33, 19, 156 } /* left = d153 */,
+ { 53, 49, 21, 110, 116, 168, 59, 80, 76 } /* left = d63 */,
+ { 55, 27, 12, 153, 203, 218, 26, 27, 49 } /* left = d27 */,
+ { 38, 72, 19, 168, 203, 212, 50, 50, 107 } /* left = tm */
+ }, { /* above = dc */
+ { 92, 45, 102, 136, 116, 180, 74, 90, 100 } /* left = v */,
+ { 73, 32, 19, 187, 222, 215, 46, 34, 100 } /* left = h */,
+ { 137, 30, 42, 148, 151, 207, 70, 52, 91 } /* left = dc */,
+ { 91, 30, 32, 116, 121, 186, 93, 86, 94 } /* left = d45 */,
+ { 72, 35, 36, 149, 68, 206, 68, 63, 105 } /* left = d135 */,
+ { 73, 31, 28, 138, 57, 124, 55, 122, 151 } /* left = d117 */,
+ { 67, 23, 21, 140, 126, 197, 40, 37, 171 } /* left = d153 */,
+ { 74, 32, 27, 107, 86, 160, 63, 134, 102 } /* left = d63 */,
+ { 86, 27, 28, 128, 154, 212, 45, 43, 53 } /* left = d27 */,
+ { 59, 67, 44, 140, 161, 202, 78, 67, 119 } /* left = tm */
+ }, { /* above = d45 */
+ { 59, 38, 83, 112, 103, 162, 98, 136, 90 } /* left = v */,
+ { 62, 30, 23, 158, 200, 207, 59, 57, 50 } /* left = h */,
+ { 103, 26, 36, 129, 132, 201, 83, 80, 93 } /* left = dc */,
+ { 67, 30, 29, 84, 86, 191, 102, 91, 59 } /* left = d45 */,
+ { 60, 32, 33, 112, 71, 220, 64, 89, 104 } /* left = d135 */,
+ { 53, 26, 34, 130, 56, 149, 84, 120, 103 } /* left = d117 */,
+ { 53, 21, 23, 133, 109, 210, 56, 77, 172 } /* left = d153 */,
+ { 61, 29, 29, 93, 97, 165, 83, 175, 162 } /* left = d63 */,
+ { 77, 19, 29, 112, 142, 228, 55, 66, 36 } /* left = d27 */,
+ { 47, 47, 43, 114, 137, 181, 100, 99, 95 } /* left = tm */
+ }, { /* above = d135 */
+ { 53, 40, 55, 139, 69, 183, 61, 80, 110 } /* left = v */,
+ { 40, 29, 19, 161, 180, 207, 43, 24, 91 } /* left = h */,
+ { 69, 23, 29, 128, 83, 199, 46, 44, 101 } /* left = dc */,
+ { 60, 34, 19, 105, 61, 198, 53, 64, 89 } /* left = d45 */,
+ { 52, 31, 22, 158, 40, 209, 58, 62, 89 } /* left = d135 */,
+ { 44, 31, 29, 147, 46, 158, 56, 102, 198 } /* left = d117 */,
+ { 35, 19, 12, 135, 87, 209, 41, 45, 167 } /* left = d153 */,
+ { 51, 38, 25, 113, 58, 164, 70, 93, 97 } /* left = d63 */,
+ { 55, 25, 21, 118, 95, 215, 38, 39, 66 } /* left = d27 */,
+ { 47, 54, 34, 146, 108, 203, 72, 103, 151 } /* left = tm */
+ }, { /* above = d117 */
+ { 46, 27, 80, 150, 55, 124, 55, 121, 135 } /* left = v */,
+ { 36, 23, 27, 165, 149, 166, 54, 64, 118 } /* left = h */,
+ { 64, 19, 37, 156, 66, 138, 49, 95, 133 } /* left = dc */,
+ { 53, 21, 36, 131, 63, 163, 60, 109, 81 } /* left = d45 */,
+ { 40, 26, 35, 154, 40, 185, 51, 97, 123 } /* left = d135 */,
+ { 35, 19, 34, 179, 19, 97, 48, 129, 124 } /* left = d117 */,
+ { 36, 20, 26, 136, 62, 164, 33, 77, 154 } /* left = d153 */,
+ { 45, 26, 28, 129, 45, 129, 49, 147, 123 } /* left = d63 */,
+ { 45, 18, 32, 130, 90, 157, 40, 79, 91 } /* left = d27 */,
+ { 38, 44, 51, 136, 74, 162, 57, 97, 121 } /* left = tm */
+ }, { /* above = d153 */
+ { 56, 39, 58, 133, 117, 173, 48, 53, 187 } /* left = v */,
+ { 35, 21, 12, 161, 212, 207, 20, 23, 145 } /* left = h */,
+ { 75, 17, 22, 136, 138, 185, 32, 34, 166 } /* left = dc */,
+ { 56, 29, 19, 117, 109, 181, 55, 68, 112 } /* left = d45 */,
+ { 47, 29, 17, 153, 64, 220, 59, 51, 114 } /* left = d135 */,
+ { 46, 16, 24, 136, 76, 147, 41, 64, 172 } /* left = d117 */,
+ { 34, 17, 11, 108, 152, 187, 13, 15, 209 } /* left = d153 */,
+ { 55, 30, 18, 122, 79, 179, 44, 88, 116 } /* left = d63 */,
+ { 51, 24, 14, 115, 133, 209, 32, 26, 104 } /* left = d27 */,
+ { 37, 49, 25, 129, 168, 164, 41, 54, 148 } /* left = tm */
+ }, { /* above = d63 */
+ { 48, 34, 86, 101, 92, 146, 78, 179, 134 } /* left = v */,
+ { 47, 22, 24, 138, 187, 178, 68, 69, 59 } /* left = h */,
+ { 78, 23, 39, 111, 117, 170, 74, 124, 94 } /* left = dc */,
+ { 56, 25, 33, 105, 112, 187, 95, 177, 129 } /* left = d45 */,
+ { 48, 31, 27, 114, 63, 183, 82, 116, 56 } /* left = d135 */,
+ { 43, 28, 37, 121, 63, 123, 61, 192, 169 } /* left = d117 */,
+ { 42, 17, 24, 109, 97, 177, 56, 76, 122 } /* left = d153 */,
+ { 46, 23, 32, 74, 86, 150, 67, 183, 88 } /* left = d63 */,
+ { 58, 18, 28, 105, 139, 182, 70, 92, 63 } /* left = d27 */,
+ { 36, 38, 48, 92, 122, 165, 88, 137, 91 } /* left = tm */
+ }, { /* above = d27 */
+ { 62, 44, 61, 123, 105, 189, 48, 57, 64 } /* left = v */,
+ { 47, 25, 17, 175, 222, 220, 24, 30, 86 } /* left = h */,
+ { 82, 22, 32, 127, 143, 213, 39, 41, 70 } /* left = dc */,
+ { 68, 36, 17, 106, 102, 206, 59, 74, 74 } /* left = d45 */,
+ { 57, 39, 23, 151, 68, 216, 55, 63, 58 } /* left = d135 */,
+ { 49, 30, 35, 141, 70, 168, 82, 40, 115 } /* left = d117 */,
+ { 51, 25, 15, 136, 129, 202, 38, 35, 139 } /* left = d153 */,
+ { 59, 39, 19, 114, 75, 180, 77, 104, 42 } /* left = d63 */,
+ { 68, 26, 16, 111, 141, 215, 29, 28, 28 } /* left = d27 */,
+ { 40, 61, 26, 126, 152, 206, 61, 59, 93 } /* left = tm */
+ }, { /* above = tm */
+ { 44, 78, 115, 132, 119, 173, 71, 112, 93 } /* left = v */,
+ { 39, 38, 21, 184, 227, 206, 42, 32, 64 } /* left = h */,
+ { 65, 70, 60, 155, 159, 199, 61, 60, 81 } /* left = dc */,
+ { 58, 47, 36, 124, 137, 193, 80, 82, 78 } /* left = d45 */,
+ { 49, 50, 35, 144, 95, 205, 63, 78, 59 } /* left = d135 */,
+ { 41, 53, 52, 148, 71, 142, 65, 128, 51 } /* left = d117 */,
+ { 40, 36, 28, 143, 143, 202, 40, 55, 137 } /* left = d153 */,
+ { 42, 44, 44, 104, 105, 164, 64, 130, 80 } /* left = d63 */,
+ { 52, 34, 29, 129, 183, 227, 42, 35, 43 } /* left = d27 */,
+ { 43, 81, 53, 140, 169, 204, 68, 84, 72 } /* left = tm */
+ }
+};
+
+const uint8_t ff_vp9_default_kf_uvmode_probs[10][9] = {
+ { 118, 15, 123, 148, 131, 101, 44, 93, 131 } /* y = v */,
+ { 113, 12, 23, 188, 226, 142, 26, 32, 125 } /* y = h */,
+ { 144, 11, 54, 157, 195, 130, 46, 58, 108 } /* y = dc */,
+ { 120, 11, 50, 123, 163, 135, 64, 77, 103 } /* y = d45 */,
+ { 113, 9, 36, 155, 111, 157, 32, 44, 161 } /* y = d135 */,
+ { 116, 9, 55, 176, 76, 96, 37, 61, 149 } /* y = d117 */,
+ { 115, 9, 28, 141, 161, 167, 21, 25, 193 } /* y = d153 */,
+ { 116, 12, 64, 120, 140, 125, 49, 115, 121 } /* y = d63 */,
+ { 120, 12, 32, 145, 195, 142, 32, 38, 86 } /* y = d27 */,
+ { 102, 19, 66, 162, 182, 122, 35, 59, 128 } /* y = tm */
+};
+
+const int8_t ff_vp9_inter_mode_tree[3][2] = {
+ { -ZEROMV, 1 }, // '0'
+ { -NEARESTMV, 2 }, // '10'
+ { -NEARMV, -NEWMV }, // '11x'
+};
+
+const int8_t ff_vp9_filter_tree[2][2] = {
+ { -0, 1 }, // '0'
+ { -1, -2 }, // '1x'
+};
+
+const enum FilterMode ff_vp9_filter_lut[3] = {
+ FILTER_8TAP_REGULAR,
+ FILTER_8TAP_SMOOTH,
+ FILTER_8TAP_SHARP,
+};
+
+const int16_t ff_vp9_dc_qlookup[3][256] = {
+ {
+ 4, 8, 8, 9, 10, 11, 12, 12,
+ 13, 14, 15, 16, 17, 18, 19, 19,
+ 20, 21, 22, 23, 24, 25, 26, 26,
+ 27, 28, 29, 30, 31, 32, 32, 33,
+ 34, 35, 36, 37, 38, 38, 39, 40,
+ 41, 42, 43, 43, 44, 45, 46, 47,
+ 48, 48, 49, 50, 51, 52, 53, 53,
+ 54, 55, 56, 57, 57, 58, 59, 60,
+ 61, 62, 62, 63, 64, 65, 66, 66,
+ 67, 68, 69, 70, 70, 71, 72, 73,
+ 74, 74, 75, 76, 77, 78, 78, 79,
+ 80, 81, 81, 82, 83, 84, 85, 85,
+ 87, 88, 90, 92, 93, 95, 96, 98,
+ 99, 101, 102, 104, 105, 107, 108, 110,
+ 111, 113, 114, 116, 117, 118, 120, 121,
+ 123, 125, 127, 129, 131, 134, 136, 138,
+ 140, 142, 144, 146, 148, 150, 152, 154,
+ 156, 158, 161, 164, 166, 169, 172, 174,
+ 177, 180, 182, 185, 187, 190, 192, 195,
+ 199, 202, 205, 208, 211, 214, 217, 220,
+ 223, 226, 230, 233, 237, 240, 243, 247,
+ 250, 253, 257, 261, 265, 269, 272, 276,
+ 280, 284, 288, 292, 296, 300, 304, 309,
+ 313, 317, 322, 326, 330, 335, 340, 344,
+ 349, 354, 359, 364, 369, 374, 379, 384,
+ 389, 395, 400, 406, 411, 417, 423, 429,
+ 435, 441, 447, 454, 461, 467, 475, 482,
+ 489, 497, 505, 513, 522, 530, 539, 549,
+ 559, 569, 579, 590, 602, 614, 626, 640,
+ 654, 668, 684, 700, 717, 736, 755, 775,
+ 796, 819, 843, 869, 896, 925, 955, 988,
+ 1022, 1058, 1098, 1139, 1184, 1232, 1282, 1336,
+ }, {
+ 4, 9, 10, 13, 15, 17, 20, 22,
+ 25, 28, 31, 34, 37, 40, 43, 47,
+ 50, 53, 57, 60, 64, 68, 71, 75,
+ 78, 82, 86, 90, 93, 97, 101, 105,
+ 109, 113, 116, 120, 124, 128, 132, 136,
+ 140, 143, 147, 151, 155, 159, 163, 166,
+ 170, 174, 178, 182, 185, 189, 193, 197,
+ 200, 204, 208, 212, 215, 219, 223, 226,
+ 230, 233, 237, 241, 244, 248, 251, 255,
+ 259, 262, 266, 269, 273, 276, 280, 283,
+ 287, 290, 293, 297, 300, 304, 307, 310,
+ 314, 317, 321, 324, 327, 331, 334, 337,
+ 343, 350, 356, 362, 369, 375, 381, 387,
+ 394, 400, 406, 412, 418, 424, 430, 436,
+ 442, 448, 454, 460, 466, 472, 478, 484,
+ 490, 499, 507, 516, 525, 533, 542, 550,
+ 559, 567, 576, 584, 592, 601, 609, 617,
+ 625, 634, 644, 655, 666, 676, 687, 698,
+ 708, 718, 729, 739, 749, 759, 770, 782,
+ 795, 807, 819, 831, 844, 856, 868, 880,
+ 891, 906, 920, 933, 947, 961, 975, 988,
+ 1001, 1015, 1030, 1045, 1061, 1076, 1090, 1105,
+ 1120, 1137, 1153, 1170, 1186, 1202, 1218, 1236,
+ 1253, 1271, 1288, 1306, 1323, 1342, 1361, 1379,
+ 1398, 1416, 1436, 1456, 1476, 1496, 1516, 1537,
+ 1559, 1580, 1601, 1624, 1647, 1670, 1692, 1717,
+ 1741, 1766, 1791, 1817, 1844, 1871, 1900, 1929,
+ 1958, 1990, 2021, 2054, 2088, 2123, 2159, 2197,
+ 2236, 2276, 2319, 2363, 2410, 2458, 2508, 2561,
+ 2616, 2675, 2737, 2802, 2871, 2944, 3020, 3102,
+ 3188, 3280, 3375, 3478, 3586, 3702, 3823, 3953,
+ 4089, 4236, 4394, 4559, 4737, 4929, 5130, 5347,
+ }, {
+ 4, 12, 18, 25, 33, 41, 50, 60,
+ 70, 80, 91, 103, 115, 127, 140, 153,
+ 166, 180, 194, 208, 222, 237, 251, 266,
+ 281, 296, 312, 327, 343, 358, 374, 390,
+ 405, 421, 437, 453, 469, 484, 500, 516,
+ 532, 548, 564, 580, 596, 611, 627, 643,
+ 659, 674, 690, 706, 721, 737, 752, 768,
+ 783, 798, 814, 829, 844, 859, 874, 889,
+ 904, 919, 934, 949, 964, 978, 993, 1008,
+ 1022, 1037, 1051, 1065, 1080, 1094, 1108, 1122,
+ 1136, 1151, 1165, 1179, 1192, 1206, 1220, 1234,
+ 1248, 1261, 1275, 1288, 1302, 1315, 1329, 1342,
+ 1368, 1393, 1419, 1444, 1469, 1494, 1519, 1544,
+ 1569, 1594, 1618, 1643, 1668, 1692, 1717, 1741,
+ 1765, 1789, 1814, 1838, 1862, 1885, 1909, 1933,
+ 1957, 1992, 2027, 2061, 2096, 2130, 2165, 2199,
+ 2233, 2267, 2300, 2334, 2367, 2400, 2434, 2467,
+ 2499, 2532, 2575, 2618, 2661, 2704, 2746, 2788,
+ 2830, 2872, 2913, 2954, 2995, 3036, 3076, 3127,
+ 3177, 3226, 3275, 3324, 3373, 3421, 3469, 3517,
+ 3565, 3621, 3677, 3733, 3788, 3843, 3897, 3951,
+ 4005, 4058, 4119, 4181, 4241, 4301, 4361, 4420,
+ 4479, 4546, 4612, 4677, 4742, 4807, 4871, 4942,
+ 5013, 5083, 5153, 5222, 5291, 5367, 5442, 5517,
+ 5591, 5665, 5745, 5825, 5905, 5984, 6063, 6149,
+ 6234, 6319, 6404, 6495, 6587, 6678, 6769, 6867,
+ 6966, 7064, 7163, 7269, 7376, 7483, 7599, 7715,
+ 7832, 7958, 8085, 8214, 8352, 8492, 8635, 8788,
+ 8945, 9104, 9275, 9450, 9639, 9832, 10031, 10245,
+ 10465, 10702, 10946, 11210, 11482, 11776, 12081, 12409,
+ 12750, 13118, 13501, 13913, 14343, 14807, 15290, 15812,
+ 16356, 16943, 17575, 18237, 18949, 19718, 20521, 21387,
+ }
+};
+
+const int16_t ff_vp9_ac_qlookup[3][256] = {
+ {
+ 4, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22,
+ 23, 24, 25, 26, 27, 28, 29, 30,
+ 31, 32, 33, 34, 35, 36, 37, 38,
+ 39, 40, 41, 42, 43, 44, 45, 46,
+ 47, 48, 49, 50, 51, 52, 53, 54,
+ 55, 56, 57, 58, 59, 60, 61, 62,
+ 63, 64, 65, 66, 67, 68, 69, 70,
+ 71, 72, 73, 74, 75, 76, 77, 78,
+ 79, 80, 81, 82, 83, 84, 85, 86,
+ 87, 88, 89, 90, 91, 92, 93, 94,
+ 95, 96, 97, 98, 99, 100, 101, 102,
+ 104, 106, 108, 110, 112, 114, 116, 118,
+ 120, 122, 124, 126, 128, 130, 132, 134,
+ 136, 138, 140, 142, 144, 146, 148, 150,
+ 152, 155, 158, 161, 164, 167, 170, 173,
+ 176, 179, 182, 185, 188, 191, 194, 197,
+ 200, 203, 207, 211, 215, 219, 223, 227,
+ 231, 235, 239, 243, 247, 251, 255, 260,
+ 265, 270, 275, 280, 285, 290, 295, 300,
+ 305, 311, 317, 323, 329, 335, 341, 347,
+ 353, 359, 366, 373, 380, 387, 394, 401,
+ 408, 416, 424, 432, 440, 448, 456, 465,
+ 474, 483, 492, 501, 510, 520, 530, 540,
+ 550, 560, 571, 582, 593, 604, 615, 627,
+ 639, 651, 663, 676, 689, 702, 715, 729,
+ 743, 757, 771, 786, 801, 816, 832, 848,
+ 864, 881, 898, 915, 933, 951, 969, 988,
+ 1007, 1026, 1046, 1066, 1087, 1108, 1129, 1151,
+ 1173, 1196, 1219, 1243, 1267, 1292, 1317, 1343,
+ 1369, 1396, 1423, 1451, 1479, 1508, 1537, 1567,
+ 1597, 1628, 1660, 1692, 1725, 1759, 1793, 1828,
+ }, {
+ 4, 9, 11, 13, 16, 18, 21, 24,
+ 27, 30, 33, 37, 40, 44, 48, 51,
+ 55, 59, 63, 67, 71, 75, 79, 83,
+ 88, 92, 96, 100, 105, 109, 114, 118,
+ 122, 127, 131, 136, 140, 145, 149, 154,
+ 158, 163, 168, 172, 177, 181, 186, 190,
+ 195, 199, 204, 208, 213, 217, 222, 226,
+ 231, 235, 240, 244, 249, 253, 258, 262,
+ 267, 271, 275, 280, 284, 289, 293, 297,
+ 302, 306, 311, 315, 319, 324, 328, 332,
+ 337, 341, 345, 349, 354, 358, 362, 367,
+ 371, 375, 379, 384, 388, 392, 396, 401,
+ 409, 417, 425, 433, 441, 449, 458, 466,
+ 474, 482, 490, 498, 506, 514, 523, 531,
+ 539, 547, 555, 563, 571, 579, 588, 596,
+ 604, 616, 628, 640, 652, 664, 676, 688,
+ 700, 713, 725, 737, 749, 761, 773, 785,
+ 797, 809, 825, 841, 857, 873, 889, 905,
+ 922, 938, 954, 970, 986, 1002, 1018, 1038,
+ 1058, 1078, 1098, 1118, 1138, 1158, 1178, 1198,
+ 1218, 1242, 1266, 1290, 1314, 1338, 1362, 1386,
+ 1411, 1435, 1463, 1491, 1519, 1547, 1575, 1603,
+ 1631, 1663, 1695, 1727, 1759, 1791, 1823, 1859,
+ 1895, 1931, 1967, 2003, 2039, 2079, 2119, 2159,
+ 2199, 2239, 2283, 2327, 2371, 2415, 2459, 2507,
+ 2555, 2603, 2651, 2703, 2755, 2807, 2859, 2915,
+ 2971, 3027, 3083, 3143, 3203, 3263, 3327, 3391,
+ 3455, 3523, 3591, 3659, 3731, 3803, 3876, 3952,
+ 4028, 4104, 4184, 4264, 4348, 4432, 4516, 4604,
+ 4692, 4784, 4876, 4972, 5068, 5168, 5268, 5372,
+ 5476, 5584, 5692, 5804, 5916, 6032, 6148, 6268,
+ 6388, 6512, 6640, 6768, 6900, 7036, 7172, 7312,
+ }, {
+ 4, 13, 19, 27, 35, 44, 54, 64,
+ 75, 87, 99, 112, 126, 139, 154, 168,
+ 183, 199, 214, 230, 247, 263, 280, 297,
+ 314, 331, 349, 366, 384, 402, 420, 438,
+ 456, 475, 493, 511, 530, 548, 567, 586,
+ 604, 623, 642, 660, 679, 698, 716, 735,
+ 753, 772, 791, 809, 828, 846, 865, 884,
+ 902, 920, 939, 957, 976, 994, 1012, 1030,
+ 1049, 1067, 1085, 1103, 1121, 1139, 1157, 1175,
+ 1193, 1211, 1229, 1246, 1264, 1282, 1299, 1317,
+ 1335, 1352, 1370, 1387, 1405, 1422, 1440, 1457,
+ 1474, 1491, 1509, 1526, 1543, 1560, 1577, 1595,
+ 1627, 1660, 1693, 1725, 1758, 1791, 1824, 1856,
+ 1889, 1922, 1954, 1987, 2020, 2052, 2085, 2118,
+ 2150, 2183, 2216, 2248, 2281, 2313, 2346, 2378,
+ 2411, 2459, 2508, 2556, 2605, 2653, 2701, 2750,
+ 2798, 2847, 2895, 2943, 2992, 3040, 3088, 3137,
+ 3185, 3234, 3298, 3362, 3426, 3491, 3555, 3619,
+ 3684, 3748, 3812, 3876, 3941, 4005, 4069, 4149,
+ 4230, 4310, 4390, 4470, 4550, 4631, 4711, 4791,
+ 4871, 4967, 5064, 5160, 5256, 5352, 5448, 5544,
+ 5641, 5737, 5849, 5961, 6073, 6185, 6297, 6410,
+ 6522, 6650, 6778, 6906, 7034, 7162, 7290, 7435,
+ 7579, 7723, 7867, 8011, 8155, 8315, 8475, 8635,
+ 8795, 8956, 9132, 9308, 9484, 9660, 9836, 10028,
+ 10220, 10412, 10604, 10812, 11020, 11228, 11437, 11661,
+ 11885, 12109, 12333, 12573, 12813, 13053, 13309, 13565,
+ 13821, 14093, 14365, 14637, 14925, 15213, 15502, 15806,
+ 16110, 16414, 16734, 17054, 17390, 17726, 18062, 18414,
+ 18766, 19134, 19502, 19886, 20270, 20670, 21070, 21486,
+ 21902, 22334, 22766, 23214, 23662, 24126, 24590, 25070,
+ 25551, 26047, 26559, 27071, 27599, 28143, 28687, 29247,
+ }
+};
+
+const enum TxfmType ff_vp9_intra_txfm_type[14] = {
+ [VERT_PRED] = ADST_DCT,
+ [HOR_PRED] = DCT_ADST,
+ [DC_PRED] = DCT_DCT,
+ [DIAG_DOWN_LEFT_PRED] = DCT_DCT,
+ [DIAG_DOWN_RIGHT_PRED] = ADST_ADST,
+ [VERT_RIGHT_PRED] = ADST_DCT,
+ [HOR_DOWN_PRED] = DCT_ADST,
+ [VERT_LEFT_PRED] = ADST_DCT,
+ [HOR_UP_PRED] = DCT_ADST,
+ [TM_VP8_PRED] = ADST_ADST,
+ [NEARESTMV] = DCT_DCT,
+ [NEARMV] = DCT_DCT,
+ [ZEROMV] = DCT_DCT,
+ [NEWMV] = DCT_DCT,
+};
+
+const int16_t ff_vp9_default_scan_4x4[16] = {
+ 0, 1, 4, 5,
+ 2, 8, 3, 6,
+ 12, 9, 7, 10,
+ 13, 11, 14, 15,
+};
+
+const int16_t ff_vp9_col_scan_4x4[16] = {
+ 0, 1, 2, 4,
+ 3, 5, 6, 8,
+ 7, 9, 10, 12,
+ 13, 11, 14, 15,
+};
+
+const int16_t ff_vp9_row_scan_4x4[16] = {
+ 0, 4, 1, 8,
+ 5, 12, 9, 2,
+ 6, 13, 3, 10,
+ 7, 14, 11, 15,
+};
+
+const int16_t ff_vp9_default_scan_8x8[64] = {
+ 0, 1, 8, 2, 9, 16, 10, 3,
+ 17, 24, 18, 11, 4, 25, 32, 19,
+ 12, 26, 5, 33, 20, 27, 40, 13,
+ 34, 6, 41, 28, 21, 35, 42, 48,
+ 14, 7, 36, 29, 43, 56, 49, 22,
+ 15, 37, 50, 44, 57, 30, 23, 51,
+ 45, 58, 38, 31, 52, 59, 39, 46,
+ 53, 60, 47, 54, 61, 55, 62, 63,
+};
+
+const int16_t ff_vp9_col_scan_8x8[64] = {
+ 0, 1, 2, 8, 3, 9, 4, 10,
+ 16, 5, 11, 17, 12, 18, 6, 24,
+ 19, 13, 25, 7, 26, 20, 32, 14,
+ 27, 21, 33, 28, 34, 15, 22, 35,
+ 40, 29, 41, 36, 23, 30, 42, 37,
+ 48, 43, 31, 44, 49, 38, 50, 56,
+ 45, 39, 51, 57, 52, 46, 58, 53,
+ 59, 47, 60, 54, 61, 55, 62, 63,
+};
+
+const int16_t ff_vp9_row_scan_8x8[64] = {
+ 0, 8, 16, 1, 9, 24, 2, 17,
+ 32, 10, 25, 3, 40, 18, 11, 33,
+ 26, 19, 4, 48, 41, 34, 12, 27,
+ 56, 20, 5, 42, 35, 13, 49, 28,
+ 6, 21, 43, 36, 14, 50, 29, 57,
+ 7, 44, 22, 37, 51, 15, 58, 30,
+ 23, 45, 52, 38, 59, 31, 46, 53,
+ 39, 60, 47, 61, 54, 62, 55, 63,
+};
+
+const int16_t ff_vp9_default_scan_16x16[256] = {
+ 0, 1, 16, 2, 17, 32, 3, 18, 33, 48, 4, 34, 19, 49, 20, 5,
+ 35, 64, 50, 36, 65, 21, 6, 51, 80, 66, 37, 22, 52, 7, 81, 67,
+ 38, 82, 53, 23, 96, 68, 8, 83, 97, 54, 39, 69, 112, 24, 98, 84,
+ 70, 55, 9, 40, 85, 99, 113, 128, 25, 114, 100, 71, 86, 56, 10, 41,
+ 115, 101, 129, 116, 72, 87, 26, 130, 144, 102, 57, 11, 42, 117, 131, 145,
+ 88, 103, 27, 73, 132, 118, 146, 58, 160, 12, 43, 133, 147, 104, 89, 119,
+ 161, 74, 148, 134, 28, 162, 59, 13, 176, 120, 149, 90, 135, 105, 163, 44,
+ 75, 177, 164, 29, 150, 121, 136, 178, 165, 14, 106, 60, 91, 151, 45, 179,
+ 192, 137, 166, 122, 76, 180, 152, 30, 61, 15, 107, 167, 181, 193, 92, 208,
+ 46, 138, 123, 153, 194, 77, 168, 182, 31, 195, 209, 183, 108, 139, 62, 154,
+ 47, 196, 93, 169, 210, 197, 224, 124, 184, 211, 78, 109, 170, 155, 63, 198,
+ 212, 185, 225, 240, 140, 94, 199, 125, 79, 213, 226, 171, 186, 156, 214, 200,
+ 110, 227, 141, 95, 241, 215, 228, 201, 126, 242, 187, 172, 157, 229, 111, 216,
+ 243, 142, 202, 230, 127, 217, 244, 173, 188, 231, 158, 203, 143, 245, 218, 232,
+ 189, 246, 159, 174, 233, 247, 219, 204, 175, 190, 248, 234, 205, 220, 249, 191,
+ 235, 221, 250, 206, 222, 251, 236, 207, 237, 223, 252, 238, 253, 239, 254, 255,
+};
+
+const int16_t ff_vp9_col_scan_16x16[256] = {
+ 0, 1, 2, 3, 16, 4, 17, 5, 18, 6, 19, 32, 20, 7, 33, 21,
+ 34, 8, 35, 22, 48, 36, 9, 49, 23, 50, 37, 10, 38, 51, 24, 64,
+ 52, 11, 65, 39, 25, 53, 66, 54, 40, 67, 12, 80, 26, 68, 55, 81,
+ 41, 69, 13, 27, 82, 56, 70, 83, 42, 14, 84, 96, 71, 28, 57, 85,
+ 97, 15, 72, 98, 43, 86, 58, 99, 29, 87, 100, 112, 73, 44, 101, 59,
+ 30, 113, 88, 114, 74, 128, 102, 45, 31, 115, 60, 103, 89, 116, 75, 129,
+ 117, 46, 104, 90, 61, 130, 118, 131, 132, 105, 76, 47, 119, 144, 91, 62,
+ 133, 106, 145, 120, 146, 134, 77, 147, 121, 92, 135, 148, 63, 107, 136, 122,
+ 93, 149, 160, 78, 150, 137, 108, 161, 162, 151, 123, 79, 138, 163, 152, 94,
+ 164, 109, 165, 153, 124, 139, 176, 166, 95, 177, 167, 110, 154, 178, 125, 179,
+ 140, 168, 155, 111, 180, 192, 181, 169, 141, 126, 182, 193, 194, 156, 183, 170,
+ 195, 127, 142, 196, 184, 208, 197, 157, 171, 143, 185, 198, 209, 199, 210, 172,
+ 158, 186, 211, 224, 212, 200, 240, 159, 213, 225, 187, 201, 173, 226, 214, 215,
+ 227, 202, 228, 188, 241, 216, 174, 229, 242, 203, 243, 217, 230, 175, 189, 244,
+ 231, 204, 218, 232, 245, 219, 246, 190, 233, 205, 191, 247, 234, 248, 220, 206,
+ 249, 235, 221, 207, 250, 236, 222, 251, 223, 237, 238, 252, 239, 253, 254, 255,
+};
+
+const int16_t ff_vp9_row_scan_16x16[256] = {
+ 0, 16, 32, 1, 48, 17, 64, 33, 2, 80, 18, 49, 96, 34, 3, 65,
+ 19, 112, 50, 81, 35, 4, 128, 66, 20, 97, 51, 82, 5, 144, 36, 67,
+ 113, 98, 21, 52, 160, 83, 129, 37, 68, 6, 114, 176, 99, 53, 22, 84,
+ 145, 38, 69, 130, 7, 115, 192, 100, 54, 23, 85, 161, 146, 131, 39, 70,
+ 208, 116, 8, 101, 177, 55, 86, 24, 162, 147, 132, 71, 224, 117, 40, 102,
+ 9, 148, 56, 87, 193, 163, 240, 133, 178, 25, 118, 72, 41, 103, 164, 10,
+ 149, 88, 134, 209, 179, 57, 119, 194, 26, 73, 165, 150, 104, 42, 135, 11,
+ 180, 120, 89, 225, 195, 58, 27, 210, 151, 181, 166, 74, 43, 105, 12, 136,
+ 90, 59, 241, 121, 28, 196, 167, 211, 152, 44, 182, 137, 75, 13, 226, 106,
+ 122, 60, 197, 91, 168, 29, 183, 153, 14, 76, 212, 138, 45, 107, 15, 198,
+ 92, 227, 169, 30, 123, 154, 61, 242, 184, 213, 139, 46, 77, 31, 108, 170,
+ 199, 185, 124, 228, 93, 155, 214, 62, 140, 243, 78, 47, 200, 109, 186, 171,
+ 201, 94, 63, 215, 229, 156, 79, 125, 141, 110, 216, 187, 172, 244, 202, 230,
+ 217, 95, 157, 126, 245, 111, 142, 231, 188, 127, 158, 218, 173, 232, 246, 233,
+ 203, 143, 247, 174, 189, 159, 219, 204, 248, 234, 249, 175, 190, 220, 205, 250,
+ 235, 191, 221, 251, 236, 206, 252, 222, 207, 237, 223, 253, 238, 254, 239, 255,
+};
+
+const int16_t ff_vp9_default_scan_32x32[1024] = {
+ 0, 1, 32, 2, 33, 64, 3, 34, 65, 4, 96, 35, 66, 5, 36, 97, 67, 128, 98, 68, 37, 6, 129, 99, 7, 160, 69, 38, 130, 100, 161, 131,
+ 39, 70, 8, 101, 162, 132, 192, 71, 40, 9, 102, 163, 133, 193, 72, 224, 103, 41, 164, 10, 194, 134, 165, 73, 104, 135, 225, 42, 195, 11, 256, 166,
+ 226, 196, 74, 105, 136, 43, 12, 167, 197, 227, 257, 75, 106, 137, 228, 44, 198, 168, 258, 288, 13, 229, 76, 107, 199, 138, 259, 169, 289, 45, 230, 260,
+ 200, 108, 14, 170, 139, 320, 290, 77, 231, 261, 46, 201, 140, 291, 109, 232, 321, 262, 171, 78, 292, 15, 322, 202, 263, 352, 172, 293, 233, 141, 323, 110,
+ 47, 203, 264, 234, 294, 353, 324, 16, 79, 204, 265, 295, 325, 173, 354, 142, 235, 384, 48, 296, 111, 266, 355, 326, 80, 17, 205, 236, 174, 356, 385, 327,
+ 143, 297, 267, 357, 386, 112, 49, 328, 298, 206, 416, 237, 358, 387, 81, 175, 18, 329, 359, 388, 299, 330, 389, 113, 417, 238, 360, 50, 207, 418, 390, 331,
+ 19, 448, 361, 82, 419, 391, 239, 51, 362, 420, 114, 449, 480, 421, 83, 363, 450, 422, 512, 451, 423, 115, 452, 481, 453, 482, 454, 544, 483, 455, 513, 484,
+ 514, 485, 515, 486, 545, 576, 487, 546, 547, 608, 577, 578, 579, 609, 610, 611, 20, 144, 268, 392, 516, 640, 21, 52, 145, 176, 269, 300, 393, 424, 517, 548,
+ 641, 672, 22, 53, 84, 146, 177, 208, 270, 301, 332, 394, 425, 456, 518, 549, 580, 642, 673, 704, 23, 54, 85, 116, 147, 178, 209, 240, 271, 302, 333, 364,
+ 395, 426, 457, 488, 519, 550, 581, 612, 643, 674, 705, 736, 55, 86, 117, 179, 210, 241, 303, 334, 365, 427, 458, 489, 551, 582, 613, 675, 706, 737, 87, 118,
+ 211, 242, 335, 366, 459, 490, 583, 614, 707, 738, 119, 243, 367, 491, 615, 739, 24, 148, 272, 396, 520, 644, 768, 25, 56, 149, 180, 273, 304, 397, 428, 521,
+ 552, 645, 676, 769, 800, 26, 57, 88, 150, 181, 212, 274, 305, 336, 398, 429, 460, 522, 553, 584, 646, 677, 708, 770, 801, 832, 27, 58, 89, 120, 151, 182,
+ 213, 244, 275, 306, 337, 368, 399, 430, 461, 492, 523, 554, 585, 616, 647, 678, 709, 740, 771, 802, 833, 864, 59, 90, 121, 183, 214, 245, 307, 338, 369, 431,
+ 462, 493, 555, 586, 617, 679, 710, 741, 803, 834, 865, 91, 122, 215, 246, 339, 370, 463, 494, 587, 618, 711, 742, 835, 866, 123, 247, 371, 495, 619, 743, 867,
+ 28, 152, 276, 400, 524, 648, 772, 896, 29, 60, 153, 184, 277, 308, 401, 432, 525, 556, 649, 680, 773, 804, 897, 928, 30, 61, 92, 154, 185, 216, 278, 309,
+ 340, 402, 433, 464, 526, 557, 588, 650, 681, 712, 774, 805, 836, 898, 929, 960, 31, 62, 93, 124, 155, 186, 217, 248, 279, 310, 341, 372, 403, 434, 465, 496,
+ 527, 558, 589, 620, 651, 682, 713, 744, 775, 806, 837, 868, 899, 930, 961, 992, 63, 94, 125, 187, 218, 249, 311, 342, 373, 435, 466, 497, 559, 590, 621, 683,
+ 714, 745, 807, 838, 869, 931, 962, 993, 95, 126, 219, 250, 343, 374, 467, 498, 591, 622, 715, 746, 839, 870, 963, 994, 127, 251, 375, 499, 623, 747, 871, 995,
+ 156, 280, 404, 528, 652, 776, 900, 157, 188, 281, 312, 405, 436, 529, 560, 653, 684, 777, 808, 901, 932, 158, 189, 220, 282, 313, 344, 406, 437, 468, 530, 561,
+ 592, 654, 685, 716, 778, 809, 840, 902, 933, 964, 159, 190, 221, 252, 283, 314, 345, 376, 407, 438, 469, 500, 531, 562, 593, 624, 655, 686, 717, 748, 779, 810,
+ 841, 872, 903, 934, 965, 996, 191, 222, 253, 315, 346, 377, 439, 470, 501, 563, 594, 625, 687, 718, 749, 811, 842, 873, 935, 966, 997, 223, 254, 347, 378, 471,
+ 502, 595, 626, 719, 750, 843, 874, 967, 998, 255, 379, 503, 627, 751, 875, 999, 284, 408, 532, 656, 780, 904, 285, 316, 409, 440, 533, 564, 657, 688, 781, 812,
+ 905, 936, 286, 317, 348, 410, 441, 472, 534, 565, 596, 658, 689, 720, 782, 813, 844, 906, 937, 968, 287, 318, 349, 380, 411, 442, 473, 504, 535, 566, 597, 628,
+ 659, 690, 721, 752, 783, 814, 845, 876, 907, 938, 969, 1000, 319, 350, 381, 443, 474, 505, 567, 598, 629, 691, 722, 753, 815, 846, 877, 939, 970, 1001, 351, 382,
+ 475, 506, 599, 630, 723, 754, 847, 878, 971, 1002, 383, 507, 631, 755, 879, 1003, 412, 536, 660, 784, 908, 413, 444, 537, 568, 661, 692, 785, 816, 909, 940, 414,
+ 445, 476, 538, 569, 600, 662, 693, 724, 786, 817, 848, 910, 941, 972, 415, 446, 477, 508, 539, 570, 601, 632, 663, 694, 725, 756, 787, 818, 849, 880, 911, 942,
+ 973, 1004, 447, 478, 509, 571, 602, 633, 695, 726, 757, 819, 850, 881, 943, 974, 1005, 479, 510, 603, 634, 727, 758, 851, 882, 975, 1006, 511, 635, 759, 883, 1007,
+ 540, 664, 788, 912, 541, 572, 665, 696, 789, 820, 913, 944, 542, 573, 604, 666, 697, 728, 790, 821, 852, 914, 945, 976, 543, 574, 605, 636, 667, 698, 729, 760,
+ 791, 822, 853, 884, 915, 946, 977, 1008, 575, 606, 637, 699, 730, 761, 823, 854, 885, 947, 978, 1009, 607, 638, 731, 762, 855, 886, 979, 1010, 639, 763, 887, 1011,
+ 668, 792, 916, 669, 700, 793, 824, 917, 948, 670, 701, 732, 794, 825, 856, 918, 949, 980, 671, 702, 733, 764, 795, 826, 857, 888, 919, 950, 981, 1012, 703, 734,
+ 765, 827, 858, 889, 951, 982, 1013, 735, 766, 859, 890, 983, 1014, 767, 891, 1015, 796, 920, 797, 828, 921, 952, 798, 829, 860, 922, 953, 984, 799, 830, 861, 892,
+ 923, 954, 985, 1016, 831, 862, 893, 955, 986, 1017, 863, 894, 987, 1018, 895, 1019, 924, 925, 956, 926, 957, 988, 927, 958, 989, 1020, 959, 990, 1021, 991, 1022, 1023,
+};
+
+const int16_t * const ff_vp9_scans[5][4] = {
+ {
+ ff_vp9_default_scan_4x4, ff_vp9_col_scan_4x4,
+ ff_vp9_row_scan_4x4, ff_vp9_default_scan_4x4
+ }, {
+ ff_vp9_default_scan_8x8, ff_vp9_col_scan_8x8,
+ ff_vp9_row_scan_8x8, ff_vp9_default_scan_8x8
+ }, {
+ ff_vp9_default_scan_16x16, ff_vp9_col_scan_16x16,
+ ff_vp9_row_scan_16x16, ff_vp9_default_scan_16x16
+ }, {
+ ff_vp9_default_scan_32x32, ff_vp9_default_scan_32x32,
+ ff_vp9_default_scan_32x32, ff_vp9_default_scan_32x32
+ }, { // lossless
+ ff_vp9_default_scan_4x4, ff_vp9_default_scan_4x4,
+ ff_vp9_default_scan_4x4, ff_vp9_default_scan_4x4
+ }
+};
+
+const int16_t ff_vp9_default_scan_4x4_nb[16][2] = {
+ { 0, 0 }, { 0, 0 }, { 4, 1 }, { 1, 1 },
+ { 4, 4 }, { 2, 2 }, { 5, 2 }, { 8, 8 },
+ { 8, 5 }, { 6, 3 }, { 9, 6 }, { 12, 9 },
+ { 10, 7 }, { 13, 10 }, { 14, 11 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_col_scan_4x4_nb[16][2] = {
+ { 0, 0 }, { 1, 1 }, { 0, 0 }, { 2, 2 },
+ { 4, 4 }, { 5, 5 }, { 4, 4 }, { 6, 6 },
+ { 8, 8 }, { 9, 9 }, { 8, 8 }, { 12, 12 },
+ { 10, 10 }, { 13, 13 }, { 14, 14 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_row_scan_4x4_nb[16][2] = {
+ { 0, 0 }, { 0, 0 }, { 4, 4 }, { 1, 1 },
+ { 8, 8 }, { 5, 5 }, { 1, 1 }, { 2, 2 },
+ { 9, 9 }, { 2, 2 }, { 6, 6 }, { 3, 3 },
+ { 10, 10 }, { 7, 7 }, { 11, 11 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_default_scan_8x8_nb[64][2] = {
+ { 0, 0 }, { 0, 0 }, { 1, 1 }, { 8, 1 },
+ { 8, 8 }, { 9, 2 }, { 2, 2 }, { 16, 9 },
+ { 16, 16 }, { 17, 10 }, { 10, 3 }, { 3, 3 },
+ { 24, 17 }, { 24, 24 }, { 18, 11 }, { 11, 4 },
+ { 25, 18 }, { 4, 4 }, { 32, 25 }, { 19, 12 },
+ { 26, 19 }, { 32, 32 }, { 12, 5 }, { 33, 26 },
+ { 5, 5 }, { 40, 33 }, { 27, 20 }, { 20, 13 },
+ { 34, 27 }, { 41, 34 }, { 40, 40 }, { 13, 6 },
+ { 6, 6 }, { 35, 28 }, { 28, 21 }, { 42, 35 },
+ { 48, 48 }, { 48, 41 }, { 21, 14 }, { 14, 7 },
+ { 36, 29 }, { 49, 42 }, { 43, 36 }, { 56, 49 },
+ { 29, 22 }, { 22, 15 }, { 50, 43 }, { 44, 37 },
+ { 57, 50 }, { 37, 30 }, { 30, 23 }, { 51, 44 },
+ { 58, 51 }, { 38, 31 }, { 45, 38 }, { 52, 45 },
+ { 59, 52 }, { 46, 39 }, { 53, 46 }, { 60, 53 },
+ { 54, 47 }, { 61, 54 }, { 62, 55 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_col_scan_8x8_nb[64][2] = {
+ { 0, 0 }, { 1, 1 }, { 0, 0 }, { 2, 2 },
+ { 8, 8 }, { 3, 3 }, { 9, 9 }, { 8, 8 },
+ { 4, 4 }, { 10, 10 }, { 16, 16 }, { 11, 11 },
+ { 17, 17 }, { 5, 5 }, { 16, 16 }, { 18, 18 },
+ { 12, 12 }, { 24, 24 }, { 6, 6 }, { 25, 25 },
+ { 19, 19 }, { 24, 24 }, { 13, 13 }, { 26, 26 },
+ { 20, 20 }, { 32, 32 }, { 27, 27 }, { 33, 33 },
+ { 14, 14 }, { 21, 21 }, { 34, 34 }, { 32, 32 },
+ { 28, 28 }, { 40, 40 }, { 35, 35 }, { 22, 22 },
+ { 29, 29 }, { 41, 41 }, { 36, 36 }, { 40, 40 },
+ { 42, 42 }, { 30, 30 }, { 43, 43 }, { 48, 48 },
+ { 37, 37 }, { 49, 49 }, { 48, 48 }, { 44, 44 },
+ { 38, 38 }, { 50, 50 }, { 56, 56 }, { 51, 51 },
+ { 45, 45 }, { 57, 57 }, { 52, 52 }, { 58, 58 },
+ { 46, 46 }, { 59, 59 }, { 53, 53 }, { 60, 60 },
+ { 54, 54 }, { 61, 61 }, { 62, 62 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_row_scan_8x8_nb[64][2] = {
+ { 0, 0 }, { 8, 8 }, { 0, 0 }, { 1, 1 },
+ { 16, 16 }, { 1, 1 }, { 9, 9 }, { 24, 24 },
+ { 2, 2 }, { 17, 17 }, { 2, 2 }, { 32, 32 },
+ { 10, 10 }, { 3, 3 }, { 25, 25 }, { 18, 18 },
+ { 11, 11 }, { 3, 3 }, { 40, 40 }, { 33, 33 },
+ { 26, 26 }, { 4, 4 }, { 19, 19 }, { 48, 48 },
+ { 12, 12 }, { 4, 4 }, { 34, 34 }, { 27, 27 },
+ { 5, 5 }, { 41, 41 }, { 20, 20 }, { 5, 5 },
+ { 13, 13 }, { 35, 35 }, { 28, 28 }, { 6, 6 },
+ { 42, 42 }, { 21, 21 }, { 49, 49 }, { 6, 6 },
+ { 36, 36 }, { 14, 14 }, { 29, 29 }, { 43, 43 },
+ { 7, 7 }, { 50, 50 }, { 22, 22 }, { 15, 15 },
+ { 37, 37 }, { 44, 44 }, { 30, 30 }, { 51, 51 },
+ { 23, 23 }, { 38, 38 }, { 45, 45 }, { 31, 31 },
+ { 52, 52 }, { 39, 39 }, { 53, 53 }, { 46, 46 },
+ { 54, 54 }, { 47, 47 }, { 55, 55 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_default_scan_16x16_nb[256][2] = {
+ { 0, 0 }, { 0, 0 }, { 1, 1 }, { 16, 1 },
+ { 16, 16 }, { 2, 2 }, { 17, 2 }, { 32, 17 },
+ { 32, 32 }, { 3, 3 }, { 33, 18 }, { 18, 3 },
+ { 48, 33 }, { 19, 4 }, { 4, 4 }, { 34, 19 },
+ { 48, 48 }, { 49, 34 }, { 35, 20 }, { 64, 49 },
+ { 20, 5 }, { 5, 5 }, { 50, 35 }, { 64, 64 },
+ { 65, 50 }, { 36, 21 }, { 21, 6 }, { 51, 36 },
+ { 6, 6 }, { 80, 65 }, { 66, 51 }, { 37, 22 },
+ { 81, 66 }, { 52, 37 }, { 22, 7 }, { 80, 80 },
+ { 67, 52 }, { 7, 7 }, { 82, 67 }, { 96, 81 },
+ { 53, 38 }, { 38, 23 }, { 68, 53 }, { 96, 96 },
+ { 23, 8 }, { 97, 82 }, { 83, 68 }, { 69, 54 },
+ { 54, 39 }, { 8, 8 }, { 39, 24 }, { 84, 69 },
+ { 98, 83 }, { 112, 97 }, { 112, 112 }, { 24, 9 },
+ { 113, 98 }, { 99, 84 }, { 70, 55 }, { 85, 70 },
+ { 55, 40 }, { 9, 9 }, { 40, 25 }, { 114, 99 },
+ { 100, 85 }, { 128, 113 }, { 115, 100 }, { 71, 56 },
+ { 86, 71 }, { 25, 10 }, { 129, 114 }, { 128, 128 },
+ { 101, 86 }, { 56, 41 }, { 10, 10 }, { 41, 26 },
+ { 116, 101 }, { 130, 115 }, { 144, 129 }, { 87, 72 },
+ { 102, 87 }, { 26, 11 }, { 72, 57 }, { 131, 116 },
+ { 117, 102 }, { 145, 130 }, { 57, 42 }, { 144, 144 },
+ { 11, 11 }, { 42, 27 }, { 132, 117 }, { 146, 131 },
+ { 103, 88 }, { 88, 73 }, { 118, 103 }, { 160, 145 },
+ { 73, 58 }, { 147, 132 }, { 133, 118 }, { 27, 12 },
+ { 161, 146 }, { 58, 43 }, { 12, 12 }, { 160, 160 },
+ { 119, 104 }, { 148, 133 }, { 89, 74 }, { 134, 119 },
+ { 104, 89 }, { 162, 147 }, { 43, 28 }, { 74, 59 },
+ { 176, 161 }, { 163, 148 }, { 28, 13 }, { 149, 134 },
+ { 120, 105 }, { 135, 120 }, { 177, 162 }, { 164, 149 },
+ { 13, 13 }, { 105, 90 }, { 59, 44 }, { 90, 75 },
+ { 150, 135 }, { 44, 29 }, { 178, 163 }, { 176, 176 },
+ { 136, 121 }, { 165, 150 }, { 121, 106 }, { 75, 60 },
+ { 179, 164 }, { 151, 136 }, { 29, 14 }, { 60, 45 },
+ { 14, 14 }, { 106, 91 }, { 166, 151 }, { 180, 165 },
+ { 192, 177 }, { 91, 76 }, { 192, 192 }, { 45, 30 },
+ { 137, 122 }, { 122, 107 }, { 152, 137 }, { 193, 178 },
+ { 76, 61 }, { 167, 152 }, { 181, 166 }, { 30, 15 },
+ { 194, 179 }, { 208, 193 }, { 182, 167 }, { 107, 92 },
+ { 138, 123 }, { 61, 46 }, { 153, 138 }, { 46, 31 },
+ { 195, 180 }, { 92, 77 }, { 168, 153 }, { 209, 194 },
+ { 196, 181 }, { 208, 208 }, { 123, 108 }, { 183, 168 },
+ { 210, 195 }, { 77, 62 }, { 108, 93 }, { 169, 154 },
+ { 154, 139 }, { 62, 47 }, { 197, 182 }, { 211, 196 },
+ { 184, 169 }, { 224, 209 }, { 224, 224 }, { 139, 124 },
+ { 93, 78 }, { 198, 183 }, { 124, 109 }, { 78, 63 },
+ { 212, 197 }, { 225, 210 }, { 170, 155 }, { 185, 170 },
+ { 155, 140 }, { 213, 198 }, { 199, 184 }, { 109, 94 },
+ { 226, 211 }, { 140, 125 }, { 94, 79 }, { 240, 225 },
+ { 214, 199 }, { 227, 212 }, { 200, 185 }, { 125, 110 },
+ { 241, 226 }, { 186, 171 }, { 171, 156 }, { 156, 141 },
+ { 228, 213 }, { 110, 95 }, { 215, 200 }, { 242, 227 },
+ { 141, 126 }, { 201, 186 }, { 229, 214 }, { 126, 111 },
+ { 216, 201 }, { 243, 228 }, { 172, 157 }, { 187, 172 },
+ { 230, 215 }, { 157, 142 }, { 202, 187 }, { 142, 127 },
+ { 244, 229 }, { 217, 202 }, { 231, 216 }, { 188, 173 },
+ { 245, 230 }, { 158, 143 }, { 173, 158 }, { 232, 217 },
+ { 246, 231 }, { 218, 203 }, { 203, 188 }, { 174, 159 },
+ { 189, 174 }, { 247, 232 }, { 233, 218 }, { 204, 189 },
+ { 219, 204 }, { 248, 233 }, { 190, 175 }, { 234, 219 },
+ { 220, 205 }, { 249, 234 }, { 205, 190 }, { 221, 206 },
+ { 250, 235 }, { 235, 220 }, { 206, 191 }, { 236, 221 },
+ { 222, 207 }, { 251, 236 }, { 237, 222 }, { 252, 237 },
+ { 238, 223 }, { 253, 238 }, { 254, 239 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_col_scan_16x16_nb[256][2] = {
+ { 0, 0 }, { 1, 1 }, { 2, 2 }, { 0, 0 },
+ { 3, 3 }, { 16, 16 }, { 4, 4 }, { 17, 17 },
+ { 5, 5 }, { 18, 18 }, { 16, 16 }, { 19, 19 },
+ { 6, 6 }, { 32, 32 }, { 20, 20 }, { 33, 33 },
+ { 7, 7 }, { 34, 34 }, { 21, 21 }, { 32, 32 },
+ { 35, 35 }, { 8, 8 }, { 48, 48 }, { 22, 22 },
+ { 49, 49 }, { 36, 36 }, { 9, 9 }, { 37, 37 },
+ { 50, 50 }, { 23, 23 }, { 48, 48 }, { 51, 51 },
+ { 10, 10 }, { 64, 64 }, { 38, 38 }, { 24, 24 },
+ { 52, 52 }, { 65, 65 }, { 53, 53 }, { 39, 39 },
+ { 66, 66 }, { 11, 11 }, { 64, 64 }, { 25, 25 },
+ { 67, 67 }, { 54, 54 }, { 80, 80 }, { 40, 40 },
+ { 68, 68 }, { 12, 12 }, { 26, 26 }, { 81, 81 },
+ { 55, 55 }, { 69, 69 }, { 82, 82 }, { 41, 41 },
+ { 13, 13 }, { 83, 83 }, { 80, 80 }, { 70, 70 },
+ { 27, 27 }, { 56, 56 }, { 84, 84 }, { 96, 96 },
+ { 14, 14 }, { 71, 71 }, { 97, 97 }, { 42, 42 },
+ { 85, 85 }, { 57, 57 }, { 98, 98 }, { 28, 28 },
+ { 86, 86 }, { 99, 99 }, { 96, 96 }, { 72, 72 },
+ { 43, 43 }, { 100, 100 }, { 58, 58 }, { 29, 29 },
+ { 112, 112 }, { 87, 87 }, { 113, 113 }, { 73, 73 },
+ { 112, 112 }, { 101, 101 }, { 44, 44 }, { 30, 30 },
+ { 114, 114 }, { 59, 59 }, { 102, 102 }, { 88, 88 },
+ { 115, 115 }, { 74, 74 }, { 128, 128 }, { 116, 116 },
+ { 45, 45 }, { 103, 103 }, { 89, 89 }, { 60, 60 },
+ { 129, 129 }, { 117, 117 }, { 130, 130 }, { 131, 131 },
+ { 104, 104 }, { 75, 75 }, { 46, 46 }, { 118, 118 },
+ { 128, 128 }, { 90, 90 }, { 61, 61 }, { 132, 132 },
+ { 105, 105 }, { 144, 144 }, { 119, 119 }, { 145, 145 },
+ { 133, 133 }, { 76, 76 }, { 146, 146 }, { 120, 120 },
+ { 91, 91 }, { 134, 134 }, { 147, 147 }, { 62, 62 },
+ { 106, 106 }, { 135, 135 }, { 121, 121 }, { 92, 92 },
+ { 148, 148 }, { 144, 144 }, { 77, 77 }, { 149, 149 },
+ { 136, 136 }, { 107, 107 }, { 160, 160 }, { 161, 161 },
+ { 150, 150 }, { 122, 122 }, { 78, 78 }, { 137, 137 },
+ { 162, 162 }, { 151, 151 }, { 93, 93 }, { 163, 163 },
+ { 108, 108 }, { 164, 164 }, { 152, 152 }, { 123, 123 },
+ { 138, 138 }, { 160, 160 }, { 165, 165 }, { 94, 94 },
+ { 176, 176 }, { 166, 166 }, { 109, 109 }, { 153, 153 },
+ { 177, 177 }, { 124, 124 }, { 178, 178 }, { 139, 139 },
+ { 167, 167 }, { 154, 154 }, { 110, 110 }, { 179, 179 },
+ { 176, 176 }, { 180, 180 }, { 168, 168 }, { 140, 140 },
+ { 125, 125 }, { 181, 181 }, { 192, 192 }, { 193, 193 },
+ { 155, 155 }, { 182, 182 }, { 169, 169 }, { 194, 194 },
+ { 126, 126 }, { 141, 141 }, { 195, 195 }, { 183, 183 },
+ { 192, 192 }, { 196, 196 }, { 156, 156 }, { 170, 170 },
+ { 142, 142 }, { 184, 184 }, { 197, 197 }, { 208, 208 },
+ { 198, 198 }, { 209, 209 }, { 171, 171 }, { 157, 157 },
+ { 185, 185 }, { 210, 210 }, { 208, 208 }, { 211, 211 },
+ { 199, 199 }, { 224, 224 }, { 158, 158 }, { 212, 212 },
+ { 224, 224 }, { 186, 186 }, { 200, 200 }, { 172, 172 },
+ { 225, 225 }, { 213, 213 }, { 214, 214 }, { 226, 226 },
+ { 201, 201 }, { 227, 227 }, { 187, 187 }, { 240, 240 },
+ { 215, 215 }, { 173, 173 }, { 228, 228 }, { 241, 241 },
+ { 202, 202 }, { 242, 242 }, { 216, 216 }, { 229, 229 },
+ { 174, 174 }, { 188, 188 }, { 243, 243 }, { 230, 230 },
+ { 203, 203 }, { 217, 217 }, { 231, 231 }, { 244, 244 },
+ { 218, 218 }, { 245, 245 }, { 189, 189 }, { 232, 232 },
+ { 204, 204 }, { 190, 190 }, { 246, 246 }, { 233, 233 },
+ { 247, 247 }, { 219, 219 }, { 205, 205 }, { 248, 248 },
+ { 234, 234 }, { 220, 220 }, { 206, 206 }, { 249, 249 },
+ { 235, 235 }, { 221, 221 }, { 250, 250 }, { 222, 222 },
+ { 236, 236 }, { 237, 237 }, { 251, 251 }, { 238, 238 },
+ { 252, 252 }, { 253, 253 }, { 254, 254 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_row_scan_16x16_nb[256][2] = {
+ { 0, 0 }, { 16, 16 }, { 0, 0 }, { 32, 32 },
+ { 1, 1 }, { 48, 48 }, { 17, 17 }, { 1, 1 },
+ { 64, 64 }, { 2, 2 }, { 33, 33 }, { 80, 80 },
+ { 18, 18 }, { 2, 2 }, { 49, 49 }, { 3, 3 },
+ { 96, 96 }, { 34, 34 }, { 65, 65 }, { 19, 19 },
+ { 3, 3 }, { 112, 112 }, { 50, 50 }, { 4, 4 },
+ { 81, 81 }, { 35, 35 }, { 66, 66 }, { 4, 4 },
+ { 128, 128 }, { 20, 20 }, { 51, 51 }, { 97, 97 },
+ { 82, 82 }, { 5, 5 }, { 36, 36 }, { 144, 144 },
+ { 67, 67 }, { 113, 113 }, { 21, 21 }, { 52, 52 },
+ { 5, 5 }, { 98, 98 }, { 160, 160 }, { 83, 83 },
+ { 37, 37 }, { 6, 6 }, { 68, 68 }, { 129, 129 },
+ { 22, 22 }, { 53, 53 }, { 114, 114 }, { 6, 6 },
+ { 99, 99 }, { 176, 176 }, { 84, 84 }, { 38, 38 },
+ { 7, 7 }, { 69, 69 }, { 145, 145 }, { 130, 130 },
+ { 115, 115 }, { 23, 23 }, { 54, 54 }, { 192, 192 },
+ { 100, 100 }, { 7, 7 }, { 85, 85 }, { 161, 161 },
+ { 39, 39 }, { 70, 70 }, { 8, 8 }, { 146, 146 },
+ { 131, 131 }, { 116, 116 }, { 55, 55 }, { 208, 208 },
+ { 101, 101 }, { 24, 24 }, { 86, 86 }, { 8, 8 },
+ { 132, 132 }, { 40, 40 }, { 71, 71 }, { 177, 177 },
+ { 147, 147 }, { 224, 224 }, { 117, 117 }, { 162, 162 },
+ { 9, 9 }, { 102, 102 }, { 56, 56 }, { 25, 25 },
+ { 87, 87 }, { 148, 148 }, { 9, 9 }, { 133, 133 },
+ { 72, 72 }, { 118, 118 }, { 193, 193 }, { 163, 163 },
+ { 41, 41 }, { 103, 103 }, { 178, 178 }, { 10, 10 },
+ { 57, 57 }, { 149, 149 }, { 134, 134 }, { 88, 88 },
+ { 26, 26 }, { 119, 119 }, { 10, 10 }, { 164, 164 },
+ { 104, 104 }, { 73, 73 }, { 209, 209 }, { 179, 179 },
+ { 42, 42 }, { 11, 11 }, { 194, 194 }, { 135, 135 },
+ { 165, 165 }, { 150, 150 }, { 58, 58 }, { 27, 27 },
+ { 89, 89 }, { 11, 11 }, { 120, 120 }, { 74, 74 },
+ { 43, 43 }, { 225, 225 }, { 105, 105 }, { 12, 12 },
+ { 180, 180 }, { 151, 151 }, { 195, 195 }, { 136, 136 },
+ { 28, 28 }, { 166, 166 }, { 121, 121 }, { 59, 59 },
+ { 12, 12 }, { 210, 210 }, { 90, 90 }, { 106, 106 },
+ { 44, 44 }, { 181, 181 }, { 75, 75 }, { 152, 152 },
+ { 13, 13 }, { 167, 167 }, { 137, 137 }, { 13, 13 },
+ { 60, 60 }, { 196, 196 }, { 122, 122 }, { 29, 29 },
+ { 91, 91 }, { 14, 14 }, { 182, 182 }, { 76, 76 },
+ { 211, 211 }, { 153, 153 }, { 14, 14 }, { 107, 107 },
+ { 138, 138 }, { 45, 45 }, { 226, 226 }, { 168, 168 },
+ { 197, 197 }, { 123, 123 }, { 30, 30 }, { 61, 61 },
+ { 15, 15 }, { 92, 92 }, { 154, 154 }, { 183, 183 },
+ { 169, 169 }, { 108, 108 }, { 212, 212 }, { 77, 77 },
+ { 139, 139 }, { 198, 198 }, { 46, 46 }, { 124, 124 },
+ { 227, 227 }, { 62, 62 }, { 31, 31 }, { 184, 184 },
+ { 93, 93 }, { 170, 170 }, { 155, 155 }, { 185, 185 },
+ { 78, 78 }, { 47, 47 }, { 199, 199 }, { 213, 213 },
+ { 140, 140 }, { 63, 63 }, { 109, 109 }, { 125, 125 },
+ { 94, 94 }, { 200, 200 }, { 171, 171 }, { 156, 156 },
+ { 228, 228 }, { 186, 186 }, { 214, 214 }, { 201, 201 },
+ { 79, 79 }, { 141, 141 }, { 110, 110 }, { 229, 229 },
+ { 95, 95 }, { 126, 126 }, { 215, 215 }, { 172, 172 },
+ { 111, 111 }, { 142, 142 }, { 202, 202 }, { 157, 157 },
+ { 216, 216 }, { 230, 230 }, { 217, 217 }, { 187, 187 },
+ { 127, 127 }, { 231, 231 }, { 158, 158 }, { 173, 173 },
+ { 143, 143 }, { 203, 203 }, { 188, 188 }, { 232, 232 },
+ { 218, 218 }, { 233, 233 }, { 159, 159 }, { 174, 174 },
+ { 204, 204 }, { 189, 189 }, { 234, 234 }, { 219, 219 },
+ { 175, 175 }, { 205, 205 }, { 235, 235 }, { 220, 220 },
+ { 190, 190 }, { 236, 236 }, { 206, 206 }, { 191, 191 },
+ { 221, 221 }, { 207, 207 }, { 237, 237 }, { 222, 222 },
+ { 238, 238 }, { 223, 223 }, { 239, 239 }, { 0, 0 },
+};
+
+const int16_t ff_vp9_default_scan_32x32_nb[1024][2] = {
+ { 0, 0 }, { 0, 0 }, { 1, 1 }, { 32, 1 },
+ { 32, 32 }, { 2, 2 }, { 33, 2 }, { 64, 33 },
+ { 3, 3 }, { 64, 64 }, { 34, 3 }, { 65, 34 },
+ { 4, 4 }, { 35, 4 }, { 96, 65 }, { 66, 35 },
+ { 96, 96 }, { 97, 66 }, { 67, 36 }, { 36, 5 },
+ { 5, 5 }, { 128, 97 }, { 98, 67 }, { 6, 6 },
+ { 128, 128 }, { 68, 37 }, { 37, 6 }, { 129, 98 },
+ { 99, 68 }, { 160, 129 }, { 130, 99 }, { 38, 7 },
+ { 69, 38 }, { 7, 7 }, { 100, 69 }, { 161, 130 },
+ { 131, 100 }, { 160, 160 }, { 70, 39 }, { 39, 8 },
+ { 8, 8 }, { 101, 70 }, { 162, 131 }, { 132, 101 },
+ { 192, 161 }, { 71, 40 }, { 192, 192 }, { 102, 71 },
+ { 40, 9 }, { 163, 132 }, { 9, 9 }, { 193, 162 },
+ { 133, 102 }, { 164, 133 }, { 72, 41 }, { 103, 72 },
+ { 134, 103 }, { 224, 193 }, { 41, 10 }, { 194, 163 },
+ { 10, 10 }, { 224, 224 }, { 165, 134 }, { 225, 194 },
+ { 195, 164 }, { 73, 42 }, { 104, 73 }, { 135, 104 },
+ { 42, 11 }, { 11, 11 }, { 166, 135 }, { 196, 165 },
+ { 226, 195 }, { 256, 225 }, { 74, 43 }, { 105, 74 },
+ { 136, 105 }, { 227, 196 }, { 43, 12 }, { 197, 166 },
+ { 167, 136 }, { 257, 226 }, { 256, 256 }, { 12, 12 },
+ { 228, 197 }, { 75, 44 }, { 106, 75 }, { 198, 167 },
+ { 137, 106 }, { 258, 227 }, { 168, 137 }, { 288, 257 },
+ { 44, 13 }, { 229, 198 }, { 259, 228 }, { 199, 168 },
+ { 107, 76 }, { 13, 13 }, { 169, 138 }, { 138, 107 },
+ { 288, 288 }, { 289, 258 }, { 76, 45 }, { 230, 199 },
+ { 260, 229 }, { 45, 14 }, { 200, 169 }, { 139, 108 },
+ { 290, 259 }, { 108, 77 }, { 231, 200 }, { 320, 289 },
+ { 261, 230 }, { 170, 139 }, { 77, 46 }, { 291, 260 },
+ { 14, 14 }, { 321, 290 }, { 201, 170 }, { 262, 231 },
+ { 320, 320 }, { 171, 140 }, { 292, 261 }, { 232, 201 },
+ { 140, 109 }, { 322, 291 }, { 109, 78 }, { 46, 15 },
+ { 202, 171 }, { 263, 232 }, { 233, 202 }, { 293, 262 },
+ { 352, 321 }, { 323, 292 }, { 15, 15 }, { 78, 47 },
+ { 203, 172 }, { 264, 233 }, { 294, 263 }, { 324, 293 },
+ { 172, 141 }, { 353, 322 }, { 141, 110 }, { 234, 203 },
+ { 352, 352 }, { 47, 16 }, { 295, 264 }, { 110, 79 },
+ { 265, 234 }, { 354, 323 }, { 325, 294 }, { 79, 48 },
+ { 16, 16 }, { 204, 173 }, { 235, 204 }, { 173, 142 },
+ { 355, 324 }, { 384, 353 }, { 326, 295 }, { 142, 111 },
+ { 296, 265 }, { 266, 235 }, { 356, 325 }, { 385, 354 },
+ { 111, 80 }, { 48, 17 }, { 327, 296 }, { 297, 266 },
+ { 205, 174 }, { 384, 384 }, { 236, 205 }, { 357, 326 },
+ { 386, 355 }, { 80, 49 }, { 174, 143 }, { 17, 17 },
+ { 328, 297 }, { 358, 327 }, { 387, 356 }, { 298, 267 },
+ { 329, 298 }, { 388, 357 }, { 112, 81 }, { 416, 385 },
+ { 237, 206 }, { 359, 328 }, { 49, 18 }, { 206, 175 },
+ { 417, 386 }, { 389, 358 }, { 330, 299 }, { 18, 18 },
+ { 416, 416 }, { 360, 329 }, { 81, 50 }, { 418, 387 },
+ { 390, 359 }, { 238, 207 }, { 50, 19 }, { 361, 330 },
+ { 419, 388 }, { 113, 82 }, { 448, 417 }, { 448, 448 },
+ { 420, 389 }, { 82, 51 }, { 362, 331 }, { 449, 418 },
+ { 421, 390 }, { 480, 480 }, { 450, 419 }, { 422, 391 },
+ { 114, 83 }, { 451, 420 }, { 480, 449 }, { 452, 421 },
+ { 481, 450 }, { 453, 422 }, { 512, 512 }, { 482, 451 },
+ { 454, 423 }, { 512, 481 }, { 483, 452 }, { 513, 482 },
+ { 484, 453 }, { 514, 483 }, { 485, 454 }, { 544, 513 },
+ { 544, 544 }, { 486, 455 }, { 545, 514 }, { 546, 515 },
+ { 576, 576 }, { 576, 545 }, { 577, 546 }, { 578, 547 },
+ { 608, 577 }, { 609, 578 }, { 610, 579 }, { 19, 19 },
+ { 143, 112 }, { 267, 236 }, { 391, 360 }, { 515, 484 },
+ { 608, 608 }, { 20, 20 }, { 51, 20 }, { 144, 113 },
+ { 175, 144 }, { 268, 237 }, { 299, 268 }, { 392, 361 },
+ { 423, 392 }, { 516, 485 }, { 547, 516 }, { 640, 609 },
+ { 640, 640 }, { 21, 21 }, { 52, 21 }, { 83, 52 },
+ { 145, 114 }, { 176, 145 }, { 207, 176 }, { 269, 238 },
+ { 300, 269 }, { 331, 300 }, { 393, 362 }, { 424, 393 },
+ { 455, 424 }, { 517, 486 }, { 548, 517 }, { 579, 548 },
+ { 641, 610 }, { 672, 641 }, { 672, 672 }, { 22, 22 },
+ { 53, 22 }, { 84, 53 }, { 115, 84 }, { 146, 115 },
+ { 177, 146 }, { 208, 177 }, { 239, 208 }, { 270, 239 },
+ { 301, 270 }, { 332, 301 }, { 363, 332 }, { 394, 363 },
+ { 425, 394 }, { 456, 425 }, { 487, 456 }, { 518, 487 },
+ { 549, 518 }, { 580, 549 }, { 611, 580 }, { 642, 611 },
+ { 673, 642 }, { 704, 673 }, { 704, 704 }, { 54, 23 },
+ { 85, 54 }, { 116, 85 }, { 178, 147 }, { 209, 178 },
+ { 240, 209 }, { 302, 271 }, { 333, 302 }, { 364, 333 },
+ { 426, 395 }, { 457, 426 }, { 488, 457 }, { 550, 519 },
+ { 581, 550 }, { 612, 581 }, { 674, 643 }, { 705, 674 },
+ { 736, 705 }, { 86, 55 }, { 117, 86 }, { 210, 179 },
+ { 241, 210 }, { 334, 303 }, { 365, 334 }, { 458, 427 },
+ { 489, 458 }, { 582, 551 }, { 613, 582 }, { 706, 675 },
+ { 737, 706 }, { 118, 87 }, { 242, 211 }, { 366, 335 },
+ { 490, 459 }, { 614, 583 }, { 738, 707 }, { 23, 23 },
+ { 147, 116 }, { 271, 240 }, { 395, 364 }, { 519, 488 },
+ { 643, 612 }, { 736, 736 }, { 24, 24 }, { 55, 24 },
+ { 148, 117 }, { 179, 148 }, { 272, 241 }, { 303, 272 },
+ { 396, 365 }, { 427, 396 }, { 520, 489 }, { 551, 520 },
+ { 644, 613 }, { 675, 644 }, { 768, 737 }, { 768, 768 },
+ { 25, 25 }, { 56, 25 }, { 87, 56 }, { 149, 118 },
+ { 180, 149 }, { 211, 180 }, { 273, 242 }, { 304, 273 },
+ { 335, 304 }, { 397, 366 }, { 428, 397 }, { 459, 428 },
+ { 521, 490 }, { 552, 521 }, { 583, 552 }, { 645, 614 },
+ { 676, 645 }, { 707, 676 }, { 769, 738 }, { 800, 769 },
+ { 800, 800 }, { 26, 26 }, { 57, 26 }, { 88, 57 },
+ { 119, 88 }, { 150, 119 }, { 181, 150 }, { 212, 181 },
+ { 243, 212 }, { 274, 243 }, { 305, 274 }, { 336, 305 },
+ { 367, 336 }, { 398, 367 }, { 429, 398 }, { 460, 429 },
+ { 491, 460 }, { 522, 491 }, { 553, 522 }, { 584, 553 },
+ { 615, 584 }, { 646, 615 }, { 677, 646 }, { 708, 677 },
+ { 739, 708 }, { 770, 739 }, { 801, 770 }, { 832, 801 },
+ { 832, 832 }, { 58, 27 }, { 89, 58 }, { 120, 89 },
+ { 182, 151 }, { 213, 182 }, { 244, 213 }, { 306, 275 },
+ { 337, 306 }, { 368, 337 }, { 430, 399 }, { 461, 430 },
+ { 492, 461 }, { 554, 523 }, { 585, 554 }, { 616, 585 },
+ { 678, 647 }, { 709, 678 }, { 740, 709 }, { 802, 771 },
+ { 833, 802 }, { 864, 833 }, { 90, 59 }, { 121, 90 },
+ { 214, 183 }, { 245, 214 }, { 338, 307 }, { 369, 338 },
+ { 462, 431 }, { 493, 462 }, { 586, 555 }, { 617, 586 },
+ { 710, 679 }, { 741, 710 }, { 834, 803 }, { 865, 834 },
+ { 122, 91 }, { 246, 215 }, { 370, 339 }, { 494, 463 },
+ { 618, 587 }, { 742, 711 }, { 866, 835 }, { 27, 27 },
+ { 151, 120 }, { 275, 244 }, { 399, 368 }, { 523, 492 },
+ { 647, 616 }, { 771, 740 }, { 864, 864 }, { 28, 28 },
+ { 59, 28 }, { 152, 121 }, { 183, 152 }, { 276, 245 },
+ { 307, 276 }, { 400, 369 }, { 431, 400 }, { 524, 493 },
+ { 555, 524 }, { 648, 617 }, { 679, 648 }, { 772, 741 },
+ { 803, 772 }, { 896, 865 }, { 896, 896 }, { 29, 29 },
+ { 60, 29 }, { 91, 60 }, { 153, 122 }, { 184, 153 },
+ { 215, 184 }, { 277, 246 }, { 308, 277 }, { 339, 308 },
+ { 401, 370 }, { 432, 401 }, { 463, 432 }, { 525, 494 },
+ { 556, 525 }, { 587, 556 }, { 649, 618 }, { 680, 649 },
+ { 711, 680 }, { 773, 742 }, { 804, 773 }, { 835, 804 },
+ { 897, 866 }, { 928, 897 }, { 928, 928 }, { 30, 30 },
+ { 61, 30 }, { 92, 61 }, { 123, 92 }, { 154, 123 },
+ { 185, 154 }, { 216, 185 }, { 247, 216 }, { 278, 247 },
+ { 309, 278 }, { 340, 309 }, { 371, 340 }, { 402, 371 },
+ { 433, 402 }, { 464, 433 }, { 495, 464 }, { 526, 495 },
+ { 557, 526 }, { 588, 557 }, { 619, 588 }, { 650, 619 },
+ { 681, 650 }, { 712, 681 }, { 743, 712 }, { 774, 743 },
+ { 805, 774 }, { 836, 805 }, { 867, 836 }, { 898, 867 },
+ { 929, 898 }, { 960, 929 }, { 960, 960 }, { 62, 31 },
+ { 93, 62 }, { 124, 93 }, { 186, 155 }, { 217, 186 },
+ { 248, 217 }, { 310, 279 }, { 341, 310 }, { 372, 341 },
+ { 434, 403 }, { 465, 434 }, { 496, 465 }, { 558, 527 },
+ { 589, 558 }, { 620, 589 }, { 682, 651 }, { 713, 682 },
+ { 744, 713 }, { 806, 775 }, { 837, 806 }, { 868, 837 },
+ { 930, 899 }, { 961, 930 }, { 992, 961 }, { 94, 63 },
+ { 125, 94 }, { 218, 187 }, { 249, 218 }, { 342, 311 },
+ { 373, 342 }, { 466, 435 }, { 497, 466 }, { 590, 559 },
+ { 621, 590 }, { 714, 683 }, { 745, 714 }, { 838, 807 },
+ { 869, 838 }, { 962, 931 }, { 993, 962 }, { 126, 95 },
+ { 250, 219 }, { 374, 343 }, { 498, 467 }, { 622, 591 },
+ { 746, 715 }, { 870, 839 }, { 994, 963 }, { 155, 124 },
+ { 279, 248 }, { 403, 372 }, { 527, 496 }, { 651, 620 },
+ { 775, 744 }, { 899, 868 }, { 156, 125 }, { 187, 156 },
+ { 280, 249 }, { 311, 280 }, { 404, 373 }, { 435, 404 },
+ { 528, 497 }, { 559, 528 }, { 652, 621 }, { 683, 652 },
+ { 776, 745 }, { 807, 776 }, { 900, 869 }, { 931, 900 },
+ { 157, 126 }, { 188, 157 }, { 219, 188 }, { 281, 250 },
+ { 312, 281 }, { 343, 312 }, { 405, 374 }, { 436, 405 },
+ { 467, 436 }, { 529, 498 }, { 560, 529 }, { 591, 560 },
+ { 653, 622 }, { 684, 653 }, { 715, 684 }, { 777, 746 },
+ { 808, 777 }, { 839, 808 }, { 901, 870 }, { 932, 901 },
+ { 963, 932 }, { 158, 127 }, { 189, 158 }, { 220, 189 },
+ { 251, 220 }, { 282, 251 }, { 313, 282 }, { 344, 313 },
+ { 375, 344 }, { 406, 375 }, { 437, 406 }, { 468, 437 },
+ { 499, 468 }, { 530, 499 }, { 561, 530 }, { 592, 561 },
+ { 623, 592 }, { 654, 623 }, { 685, 654 }, { 716, 685 },
+ { 747, 716 }, { 778, 747 }, { 809, 778 }, { 840, 809 },
+ { 871, 840 }, { 902, 871 }, { 933, 902 }, { 964, 933 },
+ { 995, 964 }, { 190, 159 }, { 221, 190 }, { 252, 221 },
+ { 314, 283 }, { 345, 314 }, { 376, 345 }, { 438, 407 },
+ { 469, 438 }, { 500, 469 }, { 562, 531 }, { 593, 562 },
+ { 624, 593 }, { 686, 655 }, { 717, 686 }, { 748, 717 },
+ { 810, 779 }, { 841, 810 }, { 872, 841 }, { 934, 903 },
+ { 965, 934 }, { 996, 965 }, { 222, 191 }, { 253, 222 },
+ { 346, 315 }, { 377, 346 }, { 470, 439 }, { 501, 470 },
+ { 594, 563 }, { 625, 594 }, { 718, 687 }, { 749, 718 },
+ { 842, 811 }, { 873, 842 }, { 966, 935 }, { 997, 966 },
+ { 254, 223 }, { 378, 347 }, { 502, 471 }, { 626, 595 },
+ { 750, 719 }, { 874, 843 }, { 998, 967 }, { 283, 252 },
+ { 407, 376 }, { 531, 500 }, { 655, 624 }, { 779, 748 },
+ { 903, 872 }, { 284, 253 }, { 315, 284 }, { 408, 377 },
+ { 439, 408 }, { 532, 501 }, { 563, 532 }, { 656, 625 },
+ { 687, 656 }, { 780, 749 }, { 811, 780 }, { 904, 873 },
+ { 935, 904 }, { 285, 254 }, { 316, 285 }, { 347, 316 },
+ { 409, 378 }, { 440, 409 }, { 471, 440 }, { 533, 502 },
+ { 564, 533 }, { 595, 564 }, { 657, 626 }, { 688, 657 },
+ { 719, 688 }, { 781, 750 }, { 812, 781 }, { 843, 812 },
+ { 905, 874 }, { 936, 905 }, { 967, 936 }, { 286, 255 },
+ { 317, 286 }, { 348, 317 }, { 379, 348 }, { 410, 379 },
+ { 441, 410 }, { 472, 441 }, { 503, 472 }, { 534, 503 },
+ { 565, 534 }, { 596, 565 }, { 627, 596 }, { 658, 627 },
+ { 689, 658 }, { 720, 689 }, { 751, 720 }, { 782, 751 },
+ { 813, 782 }, { 844, 813 }, { 875, 844 }, { 906, 875 },
+ { 937, 906 }, { 968, 937 }, { 999, 968 }, { 318, 287 },
+ { 349, 318 }, { 380, 349 }, { 442, 411 }, { 473, 442 },
+ { 504, 473 }, { 566, 535 }, { 597, 566 }, { 628, 597 },
+ { 690, 659 }, { 721, 690 }, { 752, 721 }, { 814, 783 },
+ { 845, 814 }, { 876, 845 }, { 938, 907 }, { 969, 938 },
+ { 1000, 969 }, { 350, 319 }, { 381, 350 }, { 474, 443 },
+ { 505, 474 }, { 598, 567 }, { 629, 598 }, { 722, 691 },
+ { 753, 722 }, { 846, 815 }, { 877, 846 }, { 970, 939 },
+ { 1001, 970 }, { 382, 351 }, { 506, 475 }, { 630, 599 },
+ { 754, 723 }, { 878, 847 }, { 1002, 971 }, { 411, 380 },
+ { 535, 504 }, { 659, 628 }, { 783, 752 }, { 907, 876 },
+ { 412, 381 }, { 443, 412 }, { 536, 505 }, { 567, 536 },
+ { 660, 629 }, { 691, 660 }, { 784, 753 }, { 815, 784 },
+ { 908, 877 }, { 939, 908 }, { 413, 382 }, { 444, 413 },
+ { 475, 444 }, { 537, 506 }, { 568, 537 }, { 599, 568 },
+ { 661, 630 }, { 692, 661 }, { 723, 692 }, { 785, 754 },
+ { 816, 785 }, { 847, 816 }, { 909, 878 }, { 940, 909 },
+ { 971, 940 }, { 414, 383 }, { 445, 414 }, { 476, 445 },
+ { 507, 476 }, { 538, 507 }, { 569, 538 }, { 600, 569 },
+ { 631, 600 }, { 662, 631 }, { 693, 662 }, { 724, 693 },
+ { 755, 724 }, { 786, 755 }, { 817, 786 }, { 848, 817 },
+ { 879, 848 }, { 910, 879 }, { 941, 910 }, { 972, 941 },
+ { 1003, 972 }, { 446, 415 }, { 477, 446 }, { 508, 477 },
+ { 570, 539 }, { 601, 570 }, { 632, 601 }, { 694, 663 },
+ { 725, 694 }, { 756, 725 }, { 818, 787 }, { 849, 818 },
+ { 880, 849 }, { 942, 911 }, { 973, 942 }, { 1004, 973 },
+ { 478, 447 }, { 509, 478 }, { 602, 571 }, { 633, 602 },
+ { 726, 695 }, { 757, 726 }, { 850, 819 }, { 881, 850 },
+ { 974, 943 }, { 1005, 974 }, { 510, 479 }, { 634, 603 },
+ { 758, 727 }, { 882, 851 }, { 1006, 975 }, { 539, 508 },
+ { 663, 632 }, { 787, 756 }, { 911, 880 }, { 540, 509 },
+ { 571, 540 }, { 664, 633 }, { 695, 664 }, { 788, 757 },
+ { 819, 788 }, { 912, 881 }, { 943, 912 }, { 541, 510 },
+ { 572, 541 }, { 603, 572 }, { 665, 634 }, { 696, 665 },
+ { 727, 696 }, { 789, 758 }, { 820, 789 }, { 851, 820 },
+ { 913, 882 }, { 944, 913 }, { 975, 944 }, { 542, 511 },
+ { 573, 542 }, { 604, 573 }, { 635, 604 }, { 666, 635 },
+ { 697, 666 }, { 728, 697 }, { 759, 728 }, { 790, 759 },
+ { 821, 790 }, { 852, 821 }, { 883, 852 }, { 914, 883 },
+ { 945, 914 }, { 976, 945 }, { 1007, 976 }, { 574, 543 },
+ { 605, 574 }, { 636, 605 }, { 698, 667 }, { 729, 698 },
+ { 760, 729 }, { 822, 791 }, { 853, 822 }, { 884, 853 },
+ { 946, 915 }, { 977, 946 }, { 1008, 977 }, { 606, 575 },
+ { 637, 606 }, { 730, 699 }, { 761, 730 }, { 854, 823 },
+ { 885, 854 }, { 978, 947 }, { 1009, 978 }, { 638, 607 },
+ { 762, 731 }, { 886, 855 }, { 1010, 979 }, { 667, 636 },
+ { 791, 760 }, { 915, 884 }, { 668, 637 }, { 699, 668 },
+ { 792, 761 }, { 823, 792 }, { 916, 885 }, { 947, 916 },
+ { 669, 638 }, { 700, 669 }, { 731, 700 }, { 793, 762 },
+ { 824, 793 }, { 855, 824 }, { 917, 886 }, { 948, 917 },
+ { 979, 948 }, { 670, 639 }, { 701, 670 }, { 732, 701 },
+ { 763, 732 }, { 794, 763 }, { 825, 794 }, { 856, 825 },
+ { 887, 856 }, { 918, 887 }, { 949, 918 }, { 980, 949 },
+ { 1011, 980 }, { 702, 671 }, { 733, 702 }, { 764, 733 },
+ { 826, 795 }, { 857, 826 }, { 888, 857 }, { 950, 919 },
+ { 981, 950 }, { 1012, 981 }, { 734, 703 }, { 765, 734 },
+ { 858, 827 }, { 889, 858 }, { 982, 951 }, { 1013, 982 },
+ { 766, 735 }, { 890, 859 }, { 1014, 983 }, { 795, 764 },
+ { 919, 888 }, { 796, 765 }, { 827, 796 }, { 920, 889 },
+ { 951, 920 }, { 797, 766 }, { 828, 797 }, { 859, 828 },
+ { 921, 890 }, { 952, 921 }, { 983, 952 }, { 798, 767 },
+ { 829, 798 }, { 860, 829 }, { 891, 860 }, { 922, 891 },
+ { 953, 922 }, { 984, 953 }, { 1015, 984 }, { 830, 799 },
+ { 861, 830 }, { 892, 861 }, { 954, 923 }, { 985, 954 },
+ { 1016, 985 }, { 862, 831 }, { 893, 862 }, { 986, 955 },
+ { 1017, 986 }, { 894, 863 }, { 1018, 987 }, { 923, 892 },
+ { 924, 893 }, { 955, 924 }, { 925, 894 }, { 956, 925 },
+ { 987, 956 }, { 926, 895 }, { 957, 926 }, { 988, 957 },
+ { 1019, 988 }, { 958, 927 }, { 989, 958 }, { 1020, 989 },
+ { 990, 959 }, { 1021, 990 }, { 1022, 991 }, { 0, 0 },
+};
+
+const int16_t (* const ff_vp9_scans_nb[5][4])[2] = {
+ {
+ ff_vp9_default_scan_4x4_nb, ff_vp9_col_scan_4x4_nb,
+ ff_vp9_row_scan_4x4_nb, ff_vp9_default_scan_4x4_nb
+ }, {
+ ff_vp9_default_scan_8x8_nb, ff_vp9_col_scan_8x8_nb,
+ ff_vp9_row_scan_8x8_nb, ff_vp9_default_scan_8x8_nb
+ }, {
+ ff_vp9_default_scan_16x16_nb, ff_vp9_col_scan_16x16_nb,
+ ff_vp9_row_scan_16x16_nb, ff_vp9_default_scan_16x16_nb
+ }, {
+ ff_vp9_default_scan_32x32_nb, ff_vp9_default_scan_32x32_nb,
+ ff_vp9_default_scan_32x32_nb, ff_vp9_default_scan_32x32_nb
+ }, { // lossless
+ ff_vp9_default_scan_4x4_nb, ff_vp9_default_scan_4x4_nb,
+ ff_vp9_default_scan_4x4_nb, ff_vp9_default_scan_4x4_nb
+ }
+};
+
+const uint8_t ff_vp9_model_pareto8[256][8] = {
+ { 6, 86, 128, 11, 87, 42, 91, 52 },
+ { 3, 86, 128, 6, 86, 23, 88, 29 },
+ { 6, 86, 128, 11, 87, 42, 91, 52 },
+ { 9, 86, 129, 17, 88, 61, 94, 76 },
+ { 12, 86, 129, 22, 88, 77, 97, 93 },
+ { 15, 87, 129, 28, 89, 93, 100, 110 },
+ { 17, 87, 129, 33, 90, 105, 103, 123 },
+ { 20, 88, 130, 38, 91, 118, 106, 136 },
+ { 23, 88, 130, 43, 91, 128, 108, 146 },
+ { 26, 89, 131, 48, 92, 139, 111, 156 },
+ { 28, 89, 131, 53, 93, 147, 114, 163 },
+ { 31, 90, 131, 58, 94, 156, 117, 171 },
+ { 34, 90, 131, 62, 94, 163, 119, 177 },
+ { 37, 90, 132, 66, 95, 171, 122, 184 },
+ { 39, 90, 132, 70, 96, 177, 124, 189 },
+ { 42, 91, 132, 75, 97, 183, 127, 194 },
+ { 44, 91, 132, 79, 97, 188, 129, 198 },
+ { 47, 92, 133, 83, 98, 193, 132, 202 },
+ { 49, 92, 133, 86, 99, 197, 134, 205 },
+ { 52, 93, 133, 90, 100, 201, 137, 208 },
+ { 54, 93, 133, 94, 100, 204, 139, 211 },
+ { 57, 94, 134, 98, 101, 208, 142, 214 },
+ { 59, 94, 134, 101, 102, 211, 144, 216 },
+ { 62, 94, 135, 105, 103, 214, 146, 218 },
+ { 64, 94, 135, 108, 103, 216, 148, 220 },
+ { 66, 95, 135, 111, 104, 219, 151, 222 },
+ { 68, 95, 135, 114, 105, 221, 153, 223 },
+ { 71, 96, 136, 117, 106, 224, 155, 225 },
+ { 73, 96, 136, 120, 106, 225, 157, 226 },
+ { 76, 97, 136, 123, 107, 227, 159, 228 },
+ { 78, 97, 136, 126, 108, 229, 160, 229 },
+ { 80, 98, 137, 129, 109, 231, 162, 231 },
+ { 82, 98, 137, 131, 109, 232, 164, 232 },
+ { 84, 98, 138, 134, 110, 234, 166, 233 },
+ { 86, 98, 138, 137, 111, 235, 168, 234 },
+ { 89, 99, 138, 140, 112, 236, 170, 235 },
+ { 91, 99, 138, 142, 112, 237, 171, 235 },
+ { 93, 100, 139, 145, 113, 238, 173, 236 },
+ { 95, 100, 139, 147, 114, 239, 174, 237 },
+ { 97, 101, 140, 149, 115, 240, 176, 238 },
+ { 99, 101, 140, 151, 115, 241, 177, 238 },
+ { 101, 102, 140, 154, 116, 242, 179, 239 },
+ { 103, 102, 140, 156, 117, 242, 180, 239 },
+ { 105, 103, 141, 158, 118, 243, 182, 240 },
+ { 107, 103, 141, 160, 118, 243, 183, 240 },
+ { 109, 104, 141, 162, 119, 244, 185, 241 },
+ { 111, 104, 141, 164, 119, 244, 186, 241 },
+ { 113, 104, 142, 166, 120, 245, 187, 242 },
+ { 114, 104, 142, 168, 121, 245, 188, 242 },
+ { 116, 105, 143, 170, 122, 246, 190, 243 },
+ { 118, 105, 143, 171, 122, 246, 191, 243 },
+ { 120, 106, 143, 173, 123, 247, 192, 244 },
+ { 121, 106, 143, 175, 124, 247, 193, 244 },
+ { 123, 107, 144, 177, 125, 248, 195, 244 },
+ { 125, 107, 144, 178, 125, 248, 196, 244 },
+ { 127, 108, 145, 180, 126, 249, 197, 245 },
+ { 128, 108, 145, 181, 127, 249, 198, 245 },
+ { 130, 109, 145, 183, 128, 249, 199, 245 },
+ { 132, 109, 145, 184, 128, 249, 200, 245 },
+ { 134, 110, 146, 186, 129, 250, 201, 246 },
+ { 135, 110, 146, 187, 130, 250, 202, 246 },
+ { 137, 111, 147, 189, 131, 251, 203, 246 },
+ { 138, 111, 147, 190, 131, 251, 204, 246 },
+ { 140, 112, 147, 192, 132, 251, 205, 247 },
+ { 141, 112, 147, 193, 132, 251, 206, 247 },
+ { 143, 113, 148, 194, 133, 251, 207, 247 },
+ { 144, 113, 148, 195, 134, 251, 207, 247 },
+ { 146, 114, 149, 197, 135, 252, 208, 248 },
+ { 147, 114, 149, 198, 135, 252, 209, 248 },
+ { 149, 115, 149, 199, 136, 252, 210, 248 },
+ { 150, 115, 149, 200, 137, 252, 210, 248 },
+ { 152, 115, 150, 201, 138, 252, 211, 248 },
+ { 153, 115, 150, 202, 138, 252, 212, 248 },
+ { 155, 116, 151, 204, 139, 253, 213, 249 },
+ { 156, 116, 151, 205, 139, 253, 213, 249 },
+ { 158, 117, 151, 206, 140, 253, 214, 249 },
+ { 159, 117, 151, 207, 141, 253, 215, 249 },
+ { 161, 118, 152, 208, 142, 253, 216, 249 },
+ { 162, 118, 152, 209, 142, 253, 216, 249 },
+ { 163, 119, 153, 210, 143, 253, 217, 249 },
+ { 164, 119, 153, 211, 143, 253, 217, 249 },
+ { 166, 120, 153, 212, 144, 254, 218, 250 },
+ { 167, 120, 153, 212, 145, 254, 219, 250 },
+ { 168, 121, 154, 213, 146, 254, 220, 250 },
+ { 169, 121, 154, 214, 146, 254, 220, 250 },
+ { 171, 122, 155, 215, 147, 254, 221, 250 },
+ { 172, 122, 155, 216, 147, 254, 221, 250 },
+ { 173, 123, 155, 217, 148, 254, 222, 250 },
+ { 174, 123, 155, 217, 149, 254, 222, 250 },
+ { 176, 124, 156, 218, 150, 254, 223, 250 },
+ { 177, 124, 156, 219, 150, 254, 223, 250 },
+ { 178, 125, 157, 220, 151, 254, 224, 251 },
+ { 179, 125, 157, 220, 151, 254, 224, 251 },
+ { 180, 126, 157, 221, 152, 254, 225, 251 },
+ { 181, 126, 157, 221, 152, 254, 225, 251 },
+ { 183, 127, 158, 222, 153, 254, 226, 251 },
+ { 184, 127, 158, 223, 154, 254, 226, 251 },
+ { 185, 128, 159, 224, 155, 255, 227, 251 },
+ { 186, 128, 159, 224, 155, 255, 227, 251 },
+ { 187, 129, 160, 225, 156, 255, 228, 251 },
+ { 188, 130, 160, 225, 156, 255, 228, 251 },
+ { 189, 131, 160, 226, 157, 255, 228, 251 },
+ { 190, 131, 160, 226, 158, 255, 228, 251 },
+ { 191, 132, 161, 227, 159, 255, 229, 251 },
+ { 192, 132, 161, 227, 159, 255, 229, 251 },
+ { 193, 133, 162, 228, 160, 255, 230, 252 },
+ { 194, 133, 162, 229, 160, 255, 230, 252 },
+ { 195, 134, 163, 230, 161, 255, 231, 252 },
+ { 196, 134, 163, 230, 161, 255, 231, 252 },
+ { 197, 135, 163, 231, 162, 255, 231, 252 },
+ { 198, 135, 163, 231, 162, 255, 231, 252 },
+ { 199, 136, 164, 232, 163, 255, 232, 252 },
+ { 200, 136, 164, 232, 164, 255, 232, 252 },
+ { 201, 137, 165, 233, 165, 255, 233, 252 },
+ { 201, 137, 165, 233, 165, 255, 233, 252 },
+ { 202, 138, 166, 233, 166, 255, 233, 252 },
+ { 203, 138, 166, 233, 166, 255, 233, 252 },
+ { 204, 139, 166, 234, 167, 255, 234, 252 },
+ { 205, 139, 166, 234, 167, 255, 234, 252 },
+ { 206, 140, 167, 235, 168, 255, 235, 252 },
+ { 206, 140, 167, 235, 168, 255, 235, 252 },
+ { 207, 141, 168, 236, 169, 255, 235, 252 },
+ { 208, 141, 168, 236, 170, 255, 235, 252 },
+ { 209, 142, 169, 237, 171, 255, 236, 252 },
+ { 209, 143, 169, 237, 171, 255, 236, 252 },
+ { 210, 144, 169, 237, 172, 255, 236, 252 },
+ { 211, 144, 169, 237, 172, 255, 236, 252 },
+ { 212, 145, 170, 238, 173, 255, 237, 252 },
+ { 213, 145, 170, 238, 173, 255, 237, 252 },
+ { 214, 146, 171, 239, 174, 255, 237, 253 },
+ { 214, 146, 171, 239, 174, 255, 237, 253 },
+ { 215, 147, 172, 240, 175, 255, 238, 253 },
+ { 215, 147, 172, 240, 175, 255, 238, 253 },
+ { 216, 148, 173, 240, 176, 255, 238, 253 },
+ { 217, 148, 173, 240, 176, 255, 238, 253 },
+ { 218, 149, 173, 241, 177, 255, 239, 253 },
+ { 218, 149, 173, 241, 178, 255, 239, 253 },
+ { 219, 150, 174, 241, 179, 255, 239, 253 },
+ { 219, 151, 174, 241, 179, 255, 239, 253 },
+ { 220, 152, 175, 242, 180, 255, 240, 253 },
+ { 221, 152, 175, 242, 180, 255, 240, 253 },
+ { 222, 153, 176, 242, 181, 255, 240, 253 },
+ { 222, 153, 176, 242, 181, 255, 240, 253 },
+ { 223, 154, 177, 243, 182, 255, 240, 253 },
+ { 223, 154, 177, 243, 182, 255, 240, 253 },
+ { 224, 155, 178, 244, 183, 255, 241, 253 },
+ { 224, 155, 178, 244, 183, 255, 241, 253 },
+ { 225, 156, 178, 244, 184, 255, 241, 253 },
+ { 225, 157, 178, 244, 184, 255, 241, 253 },
+ { 226, 158, 179, 244, 185, 255, 242, 253 },
+ { 227, 158, 179, 244, 185, 255, 242, 253 },
+ { 228, 159, 180, 245, 186, 255, 242, 253 },
+ { 228, 159, 180, 245, 186, 255, 242, 253 },
+ { 229, 160, 181, 245, 187, 255, 242, 253 },
+ { 229, 160, 181, 245, 187, 255, 242, 253 },
+ { 230, 161, 182, 246, 188, 255, 243, 253 },
+ { 230, 162, 182, 246, 188, 255, 243, 253 },
+ { 231, 163, 183, 246, 189, 255, 243, 253 },
+ { 231, 163, 183, 246, 189, 255, 243, 253 },
+ { 232, 164, 184, 247, 190, 255, 243, 253 },
+ { 232, 164, 184, 247, 190, 255, 243, 253 },
+ { 233, 165, 185, 247, 191, 255, 244, 253 },
+ { 233, 165, 185, 247, 191, 255, 244, 253 },
+ { 234, 166, 185, 247, 192, 255, 244, 253 },
+ { 234, 167, 185, 247, 192, 255, 244, 253 },
+ { 235, 168, 186, 248, 193, 255, 244, 253 },
+ { 235, 168, 186, 248, 193, 255, 244, 253 },
+ { 236, 169, 187, 248, 194, 255, 244, 253 },
+ { 236, 169, 187, 248, 194, 255, 244, 253 },
+ { 236, 170, 188, 248, 195, 255, 245, 253 },
+ { 236, 170, 188, 248, 195, 255, 245, 253 },
+ { 237, 171, 189, 249, 196, 255, 245, 254 },
+ { 237, 172, 189, 249, 196, 255, 245, 254 },
+ { 238, 173, 190, 249, 197, 255, 245, 254 },
+ { 238, 173, 190, 249, 197, 255, 245, 254 },
+ { 239, 174, 191, 249, 198, 255, 245, 254 },
+ { 239, 174, 191, 249, 198, 255, 245, 254 },
+ { 240, 175, 192, 249, 199, 255, 246, 254 },
+ { 240, 176, 192, 249, 199, 255, 246, 254 },
+ { 240, 177, 193, 250, 200, 255, 246, 254 },
+ { 240, 177, 193, 250, 200, 255, 246, 254 },
+ { 241, 178, 194, 250, 201, 255, 246, 254 },
+ { 241, 178, 194, 250, 201, 255, 246, 254 },
+ { 242, 179, 195, 250, 202, 255, 246, 254 },
+ { 242, 180, 195, 250, 202, 255, 246, 254 },
+ { 242, 181, 196, 250, 203, 255, 247, 254 },
+ { 242, 181, 196, 250, 203, 255, 247, 254 },
+ { 243, 182, 197, 251, 204, 255, 247, 254 },
+ { 243, 183, 197, 251, 204, 255, 247, 254 },
+ { 244, 184, 198, 251, 205, 255, 247, 254 },
+ { 244, 184, 198, 251, 205, 255, 247, 254 },
+ { 244, 185, 199, 251, 206, 255, 247, 254 },
+ { 244, 185, 199, 251, 206, 255, 247, 254 },
+ { 245, 186, 200, 251, 207, 255, 247, 254 },
+ { 245, 187, 200, 251, 207, 255, 247, 254 },
+ { 246, 188, 201, 252, 207, 255, 248, 254 },
+ { 246, 188, 201, 252, 207, 255, 248, 254 },
+ { 246, 189, 202, 252, 208, 255, 248, 254 },
+ { 246, 190, 202, 252, 208, 255, 248, 254 },
+ { 247, 191, 203, 252, 209, 255, 248, 254 },
+ { 247, 191, 203, 252, 209, 255, 248, 254 },
+ { 247, 192, 204, 252, 210, 255, 248, 254 },
+ { 247, 193, 204, 252, 210, 255, 248, 254 },
+ { 248, 194, 205, 252, 211, 255, 248, 254 },
+ { 248, 194, 205, 252, 211, 255, 248, 254 },
+ { 248, 195, 206, 252, 212, 255, 249, 254 },
+ { 248, 196, 206, 252, 212, 255, 249, 254 },
+ { 249, 197, 207, 253, 213, 255, 249, 254 },
+ { 249, 197, 207, 253, 213, 255, 249, 254 },
+ { 249, 198, 208, 253, 214, 255, 249, 254 },
+ { 249, 199, 209, 253, 214, 255, 249, 254 },
+ { 250, 200, 210, 253, 215, 255, 249, 254 },
+ { 250, 200, 210, 253, 215, 255, 249, 254 },
+ { 250, 201, 211, 253, 215, 255, 249, 254 },
+ { 250, 202, 211, 253, 215, 255, 249, 254 },
+ { 250, 203, 212, 253, 216, 255, 249, 254 },
+ { 250, 203, 212, 253, 216, 255, 249, 254 },
+ { 251, 204, 213, 253, 217, 255, 250, 254 },
+ { 251, 205, 213, 253, 217, 255, 250, 254 },
+ { 251, 206, 214, 254, 218, 255, 250, 254 },
+ { 251, 206, 215, 254, 218, 255, 250, 254 },
+ { 252, 207, 216, 254, 219, 255, 250, 254 },
+ { 252, 208, 216, 254, 219, 255, 250, 254 },
+ { 252, 209, 217, 254, 220, 255, 250, 254 },
+ { 252, 210, 217, 254, 220, 255, 250, 254 },
+ { 252, 211, 218, 254, 221, 255, 250, 254 },
+ { 252, 212, 218, 254, 221, 255, 250, 254 },
+ { 253, 213, 219, 254, 222, 255, 250, 254 },
+ { 253, 213, 220, 254, 222, 255, 250, 254 },
+ { 253, 214, 221, 254, 223, 255, 250, 254 },
+ { 253, 215, 221, 254, 223, 255, 250, 254 },
+ { 253, 216, 222, 254, 224, 255, 251, 254 },
+ { 253, 217, 223, 254, 224, 255, 251, 254 },
+ { 253, 218, 224, 254, 225, 255, 251, 254 },
+ { 253, 219, 224, 254, 225, 255, 251, 254 },
+ { 254, 220, 225, 254, 225, 255, 251, 254 },
+ { 254, 221, 226, 254, 225, 255, 251, 254 },
+ { 254, 222, 227, 255, 226, 255, 251, 254 },
+ { 254, 223, 227, 255, 226, 255, 251, 254 },
+ { 254, 224, 228, 255, 227, 255, 251, 254 },
+ { 254, 225, 229, 255, 227, 255, 251, 254 },
+ { 254, 226, 230, 255, 228, 255, 251, 254 },
+ { 254, 227, 230, 255, 229, 255, 251, 254 },
+ { 255, 228, 231, 255, 230, 255, 251, 254 },
+ { 255, 229, 232, 255, 230, 255, 251, 254 },
+ { 255, 230, 233, 255, 231, 255, 252, 254 },
+ { 255, 231, 234, 255, 231, 255, 252, 254 },
+ { 255, 232, 235, 255, 232, 255, 252, 254 },
+ { 255, 233, 236, 255, 232, 255, 252, 254 },
+ { 255, 235, 237, 255, 233, 255, 252, 254 },
+ { 255, 236, 238, 255, 234, 255, 252, 254 },
+ { 255, 238, 240, 255, 235, 255, 252, 255 },
+ { 255, 239, 241, 255, 235, 255, 252, 254 },
+ { 255, 241, 243, 255, 236, 255, 252, 254 },
+ { 255, 243, 245, 255, 237, 255, 252, 254 },
+ { 255, 246, 247, 255, 239, 255, 253, 255 },
+};
+
+const ProbContext ff_vp9_default_probs = {
+ { /* y_mode */
+ { 65, 32, 18, 144, 162, 194, 41, 51, 98 } /* bsize < 8x8 */,
+ { 132, 68, 18, 165, 217, 196, 45, 40, 78 } /* bsize < 16x16 */,
+ { 173, 80, 19, 176, 240, 193, 64, 35, 46 } /* bsize < 32x32 */,
+ { 221, 135, 38, 194, 248, 121, 96, 85, 29 } /* bsize >= 32x32 */
+ }, { /* uv_mode */
+ { 48, 12, 154, 155, 139, 90, 34, 117, 119 } /* y = v */,
+ { 67, 6, 25, 204, 243, 158, 13, 21, 96 } /* y = h */,
+ { 120, 7, 76, 176, 208, 126, 28, 54, 103 } /* y = dc */,
+ { 97, 5, 44, 131, 176, 139, 48, 68, 97 } /* y = d45 */,
+ { 83, 5, 42, 156, 111, 152, 26, 49, 152 } /* y = d135 */,
+ { 80, 5, 58, 178, 74, 83, 33, 62, 145 } /* y = d117 */,
+ { 86, 5, 32, 154, 192, 168, 14, 22, 163 } /* y = d153 */,
+ { 77, 7, 64, 116, 132, 122, 37, 126, 120 } /* y = d63 */,
+ { 85, 5, 32, 156, 216, 148, 19, 29, 73 } /* y = d27 */,
+ { 101, 21, 107, 181, 192, 103, 19, 67, 125 } /* y = tm */
+ }, { /* filter */
+ { 235, 162, },
+ { 36, 255, },
+ { 34, 3, },
+ { 149, 144, },
+ }, { /* mv_mode */
+ { 2, 173, 34 }, // 0 = both zero mv
+ { 7, 145, 85 }, // 1 = one zero mv + one a predicted mv
+ { 7, 166, 63 }, // 2 = two predicted mvs
+ { 7, 94, 66 }, // 3 = one predicted/zero and one new mv
+ { 8, 64, 46 }, // 4 = two new mvs
+ { 17, 81, 31 }, // 5 = one intra neighbor + x
+ { 25, 29, 30 }, // 6 = two intra neighbors
+ }, { /* intra */
+ 9, 102, 187, 225
+ }, { /* comp */
+ 239, 183, 119, 96, 41
+ }, { /* single_ref */
+ { 33, 16 },
+ { 77, 74 },
+ { 142, 142 },
+ { 172, 170 },
+ { 238, 247 }
+ }, { /* comp_ref */
+ 50, 126, 123, 221, 226
+ }, { /* tx32p */
+ { 3, 136, 37, },
+ { 5, 52, 13, },
+ }, { /* tx16p */
+ { 20, 152, },
+ { 15, 101, },
+ }, { /* tx8p */
+ 100, 66
+ }, { /* skip */
+ 192, 128, 64
+ }, { /* mv_joint */
+ 32, 64, 96
+ }, {
+ { /* mv vertical component */
+ 128, /* sign */
+ { 224, 144, 192, 168, 192, 176, 192, 198, 198, 245 }, /* class */
+ 216, /* class0 */
+ { 136, 140, 148, 160, 176, 192, 224, 234, 234, 240 }, /* bits */
+ { /* class0_fp */
+ { 128, 128, 64 },
+ { 96, 112, 64 }
+ },
+ { 64, 96, 64 }, /* fp */
+ 160, /* class0_hp bit */
+ 128, /* hp */
+ }, { /* mv horizontal component */
+ 128, /* sign */
+ { 216, 128, 176, 160, 176, 176, 192, 198, 198, 208 }, /* class */
+ 208, /* class0 */
+ { 136, 140, 148, 160, 176, 192, 224, 234, 234, 240 }, /* bits */
+ { /* class0_fp */
+ { 128, 128, 64 },
+ { 96, 112, 64 }
+ },
+ { 64, 96, 64 }, /* fp */
+ 160, /* class0_hp bit */
+ 128, /* hp */
+ }
+ }, { /* partition */
+ { /* 64x64 -> 32x32 */
+ { 222, 34, 30 } /* a/l both not split */,
+ { 72, 16, 44 } /* a split, l not split */,
+ { 58, 32, 12 } /* l split, a not split */,
+ { 10, 7, 6 } /* a/l both split */,
+ }, { /* 32x32 -> 16x16 */
+ { 177, 58, 59 } /* a/l both not split */,
+ { 68, 26, 63 } /* a split, l not split */,
+ { 52, 79, 25 } /* l split, a not split */,
+ { 17, 14, 12 } /* a/l both split */,
+ }, { /* 16x16 -> 8x8 */
+ { 174, 73, 87 } /* a/l both not split */,
+ { 92, 41, 83 } /* a split, l not split */,
+ { 82, 99, 50 } /* l split, a not split */,
+ { 53, 39, 39 } /* a/l both split */,
+ }, { /* 8x8 -> 4x4 */
+ { 199, 122, 141 } /* a/l both not split */,
+ { 147, 63, 159 } /* a split, l not split */,
+ { 148, 133, 118 } /* l split, a not split */,
+ { 121, 104, 114 } /* a/l both split */,
+ }
+ },
+};
+
+const uint8_t ff_vp9_default_coef_probs[4][2][2][6][6][3] = {
+ { /* tx = 4x4 */
+ { /* block Type 0 */
+ { /* Intra */
+ { /* Coeff Band 0 */
+ { 195, 29, 183 },
+ { 84, 49, 136 },
+ { 8, 42, 71 }
+ }, { /* Coeff Band 1 */
+ { 31, 107, 169 },
+ { 35, 99, 159 },
+ { 17, 82, 140 },
+ { 8, 66, 114 },
+ { 2, 44, 76 },
+ { 1, 19, 32 }
+ }, { /* Coeff Band 2 */
+ { 40, 132, 201 },
+ { 29, 114, 187 },
+ { 13, 91, 157 },
+ { 7, 75, 127 },
+ { 3, 58, 95 },
+ { 1, 28, 47 }
+ }, { /* Coeff Band 3 */
+ { 69, 142, 221 },
+ { 42, 122, 201 },
+ { 15, 91, 159 },
+ { 6, 67, 121 },
+ { 1, 42, 77 },
+ { 1, 17, 31 }
+ }, { /* Coeff Band 4 */
+ { 102, 148, 228 },
+ { 67, 117, 204 },
+ { 17, 82, 154 },
+ { 6, 59, 114 },
+ { 2, 39, 75 },
+ { 1, 15, 29 }
+ }, { /* Coeff Band 5 */
+ { 156, 57, 233 },
+ { 119, 57, 212 },
+ { 58, 48, 163 },
+ { 29, 40, 124 },
+ { 12, 30, 81 },
+ { 3, 12, 31 }
+ }
+ }, { /* Inter */
+ { /* Coeff Band 0 */
+ { 191, 107, 226 },
+ { 124, 117, 204 },
+ { 25, 99, 155 }
+ }, { /* Coeff Band 1 */
+ { 29, 148, 210 },
+ { 37, 126, 194 },
+ { 8, 93, 157 },
+ { 2, 68, 118 },
+ { 1, 39, 69 },
+ { 1, 17, 33 }
+ }, { /* Coeff Band 2 */
+ { 41, 151, 213 },
+ { 27, 123, 193 },
+ { 3, 82, 144 },
+ { 1, 58, 105 },
+ { 1, 32, 60 },
+ { 1, 13, 26 }
+ }, { /* Coeff Band 3 */
+ { 59, 159, 220 },
+ { 23, 126, 198 },
+ { 4, 88, 151 },
+ { 1, 66, 114 },
+ { 1, 38, 71 },
+ { 1, 18, 34 }
+ }, { /* Coeff Band 4 */
+ { 114, 136, 232 },
+ { 51, 114, 207 },
+ { 11, 83, 155 },
+ { 3, 56, 105 },
+ { 1, 33, 65 },
+ { 1, 17, 34 }
+ }, { /* Coeff Band 5 */
+ { 149, 65, 234 },
+ { 121, 57, 215 },
+ { 61, 49, 166 },
+ { 28, 36, 114 },
+ { 12, 25, 76 },
+ { 3, 16, 42 }
+ }
+ }
+ }, { /* block Type 1 */
+ { /* Intra */
+ { /* Coeff Band 0 */
+ { 214, 49, 220 },
+ { 132, 63, 188 },
+ { 42, 65, 137 }
+ }, { /* Coeff Band 1 */
+ { 85, 137, 221 },
+ { 104, 131, 216 },
+ { 49, 111, 192 },
+ { 21, 87, 155 },
+ { 2, 49, 87 },
+ { 1, 16, 28 }
+ }, { /* Coeff Band 2 */
+ { 89, 163, 230 },
+ { 90, 137, 220 },
+ { 29, 100, 183 },
+ { 10, 70, 135 },
+ { 2, 42, 81 },
+ { 1, 17, 33 }
+ }, { /* Coeff Band 3 */
+ { 108, 167, 237 },
+ { 55, 133, 222 },
+ { 15, 97, 179 },
+ { 4, 72, 135 },
+ { 1, 45, 85 },
+ { 1, 19, 38 }
+ }, { /* Coeff Band 4 */
+ { 124, 146, 240 },
+ { 66, 124, 224 },
+ { 17, 88, 175 },
+ { 4, 58, 122 },
+ { 1, 36, 75 },
+ { 1, 18, 37 }
+ }, { /* Coeff Band 5 */
+ { 141, 79, 241 },
+ { 126, 70, 227 },
+ { 66, 58, 182 },
+ { 30, 44, 136 },
+ { 12, 34, 96 },
+ { 2, 20, 47 }
+ }
+ }, { /* Inter */
+ { /* Coeff Band 0 */
+ { 229, 99, 249 },
+ { 143, 111, 235 },
+ { 46, 109, 192 }
+ }, { /* Coeff Band 1 */
+ { 82, 158, 236 },
+ { 94, 146, 224 },
+ { 25, 117, 191 },
+ { 9, 87, 149 },
+ { 3, 56, 99 },
+ { 1, 33, 57 }
+ }, { /* Coeff Band 2 */
+ { 83, 167, 237 },
+ { 68, 145, 222 },
+ { 10, 103, 177 },
+ { 2, 72, 131 },
+ { 1, 41, 79 },
+ { 1, 20, 39 }
+ }, { /* Coeff Band 3 */
+ { 99, 167, 239 },
+ { 47, 141, 224 },
+ { 10, 104, 178 },
+ { 2, 73, 133 },
+ { 1, 44, 85 },
+ { 1, 22, 47 }
+ }, { /* Coeff Band 4 */
+ { 127, 145, 243 },
+ { 71, 129, 228 },
+ { 17, 93, 177 },
+ { 3, 61, 124 },
+ { 1, 41, 84 },
+ { 1, 21, 52 }
+ }, { /* Coeff Band 5 */
+ { 157, 78, 244 },
+ { 140, 72, 231 },
+ { 69, 58, 184 },
+ { 31, 44, 137 },
+ { 14, 38, 105 },
+ { 8, 23, 61 }
+ }
+ }
+ }
+ }, { /* tx = 8x8 */
+ { /* block Type 0 */
+ { /* Intra */
+ { /* Coeff Band 0 */
+ { 125, 34, 187 },
+ { 52, 41, 133 },
+ { 6, 31, 56 }
+ }, { /* Coeff Band 1 */
+ { 37, 109, 153 },
+ { 51, 102, 147 },
+ { 23, 87, 128 },
+ { 8, 67, 101 },
+ { 1, 41, 63 },
+ { 1, 19, 29 }
+ }, { /* Coeff Band 2 */
+ { 31, 154, 185 },
+ { 17, 127, 175 },
+ { 6, 96, 145 },
+ { 2, 73, 114 },
+ { 1, 51, 82 },
+ { 1, 28, 45 }
+ }, { /* Coeff Band 3 */
+ { 23, 163, 200 },
+ { 10, 131, 185 },
+ { 2, 93, 148 },
+ { 1, 67, 111 },
+ { 1, 41, 69 },
+ { 1, 14, 24 }
+ }, { /* Coeff Band 4 */
+ { 29, 176, 217 },
+ { 12, 145, 201 },
+ { 3, 101, 156 },
+ { 1, 69, 111 },
+ { 1, 39, 63 },
+ { 1, 14, 23 }
+ }, { /* Coeff Band 5 */
+ { 57, 192, 233 },
+ { 25, 154, 215 },
+ { 6, 109, 167 },
+ { 3, 78, 118 },
+ { 1, 48, 69 },
+ { 1, 21, 29 }
+ }
+ }, { /* Inter */
+ { /* Coeff Band 0 */
+ { 202, 105, 245 },
+ { 108, 106, 216 },
+ { 18, 90, 144 }
+ }, { /* Coeff Band 1 */
+ { 33, 172, 219 },
+ { 64, 149, 206 },
+ { 14, 117, 177 },
+ { 5, 90, 141 },
+ { 2, 61, 95 },
+ { 1, 37, 57 }
+ }, { /* Coeff Band 2 */
+ { 33, 179, 220 },
+ { 11, 140, 198 },
+ { 1, 89, 148 },
+ { 1, 60, 104 },
+ { 1, 33, 57 },
+ { 1, 12, 21 }
+ }, { /* Coeff Band 3 */
+ { 30, 181, 221 },
+ { 8, 141, 198 },
+ { 1, 87, 145 },
+ { 1, 58, 100 },
+ { 1, 31, 55 },
+ { 1, 12, 20 }
+ }, { /* Coeff Band 4 */
+ { 32, 186, 224 },
+ { 7, 142, 198 },
+ { 1, 86, 143 },
+ { 1, 58, 100 },
+ { 1, 31, 55 },
+ { 1, 12, 22 }
+ }, { /* Coeff Band 5 */
+ { 57, 192, 227 },
+ { 20, 143, 204 },
+ { 3, 96, 154 },
+ { 1, 68, 112 },
+ { 1, 42, 69 },
+ { 1, 19, 32 }
+ }
+ }
+ }, { /* block Type 1 */
+ { /* Intra */
+ { /* Coeff Band 0 */
+ { 212, 35, 215 },
+ { 113, 47, 169 },
+ { 29, 48, 105 }
+ }, { /* Coeff Band 1 */
+ { 74, 129, 203 },
+ { 106, 120, 203 },
+ { 49, 107, 178 },
+ { 19, 84, 144 },
+ { 4, 50, 84 },
+ { 1, 15, 25 }
+ }, { /* Coeff Band 2 */
+ { 71, 172, 217 },
+ { 44, 141, 209 },
+ { 15, 102, 173 },
+ { 6, 76, 133 },
+ { 2, 51, 89 },
+ { 1, 24, 42 }
+ }, { /* Coeff Band 3 */
+ { 64, 185, 231 },
+ { 31, 148, 216 },
+ { 8, 103, 175 },
+ { 3, 74, 131 },
+ { 1, 46, 81 },
+ { 1, 18, 30 }
+ }, { /* Coeff Band 4 */
+ { 65, 196, 235 },
+ { 25, 157, 221 },
+ { 5, 105, 174 },
+ { 1, 67, 120 },
+ { 1, 38, 69 },
+ { 1, 15, 30 }
+ }, { /* Coeff Band 5 */
+ { 65, 204, 238 },
+ { 30, 156, 224 },
+ { 7, 107, 177 },
+ { 2, 70, 124 },
+ { 1, 42, 73 },
+ { 1, 18, 34 }
+ }
+ }, { /* Inter */
+ { /* Coeff Band 0 */
+ { 225, 86, 251 },
+ { 144, 104, 235 },
+ { 42, 99, 181 }
+ }, { /* Coeff Band 1 */
+ { 85, 175, 239 },
+ { 112, 165, 229 },
+ { 29, 136, 200 },
+ { 12, 103, 162 },
+ { 6, 77, 123 },
+ { 2, 53, 84 }
+ }, { /* Coeff Band 2 */
+ { 75, 183, 239 },
+ { 30, 155, 221 },
+ { 3, 106, 171 },
+ { 1, 74, 128 },
+ { 1, 44, 76 },
+ { 1, 17, 28 }
+ }, { /* Coeff Band 3 */
+ { 73, 185, 240 },
+ { 27, 159, 222 },
+ { 2, 107, 172 },
+ { 1, 75, 127 },
+ { 1, 42, 73 },
+ { 1, 17, 29 }
+ }, { /* Coeff Band 4 */
+ { 62, 190, 238 },
+ { 21, 159, 222 },
+ { 2, 107, 172 },
+ { 1, 72, 122 },
+ { 1, 40, 71 },
+ { 1, 18, 32 }
+ }, { /* Coeff Band 5 */
+ { 61, 199, 240 },
+ { 27, 161, 226 },
+ { 4, 113, 180 },
+ { 1, 76, 129 },
+ { 1, 46, 80 },
+ { 1, 23, 41 }
+ }
+ }
+ }
+ }, { /* tx = 16x16 */
+ { /* block Type 0 */
+ { /* Intra */
+ { /* Coeff Band 0 */
+ { 7, 27, 153 },
+ { 5, 30, 95 },
+ { 1, 16, 30 }
+ }, { /* Coeff Band 1 */
+ { 50, 75, 127 },
+ { 57, 75, 124 },
+ { 27, 67, 108 },
+ { 10, 54, 86 },
+ { 1, 33, 52 },
+ { 1, 12, 18 }
+ }, { /* Coeff Band 2 */
+ { 43, 125, 151 },
+ { 26, 108, 148 },
+ { 7, 83, 122 },
+ { 2, 59, 89 },
+ { 1, 38, 60 },
+ { 1, 17, 27 }
+ }, { /* Coeff Band 3 */
+ { 23, 144, 163 },
+ { 13, 112, 154 },
+ { 2, 75, 117 },
+ { 1, 50, 81 },
+ { 1, 31, 51 },
+ { 1, 14, 23 }
+ }, { /* Coeff Band 4 */
+ { 18, 162, 185 },
+ { 6, 123, 171 },
+ { 1, 78, 125 },
+ { 1, 51, 86 },
+ { 1, 31, 54 },
+ { 1, 14, 23 }
+ }, { /* Coeff Band 5 */
+ { 15, 199, 227 },
+ { 3, 150, 204 },
+ { 1, 91, 146 },
+ { 1, 55, 95 },
+ { 1, 30, 53 },
+ { 1, 11, 20 }
+ }
+ }, { /* Inter */
+ { /* Coeff Band 0 */
+ { 19, 55, 240 },
+ { 19, 59, 196 },
+ { 3, 52, 105 }
+ }, { /* Coeff Band 1 */
+ { 41, 166, 207 },
+ { 104, 153, 199 },
+ { 31, 123, 181 },
+ { 14, 101, 152 },
+ { 5, 72, 106 },
+ { 1, 36, 52 }
+ }, { /* Coeff Band 2 */
+ { 35, 176, 211 },
+ { 12, 131, 190 },
+ { 2, 88, 144 },
+ { 1, 60, 101 },
+ { 1, 36, 60 },
+ { 1, 16, 28 }
+ }, { /* Coeff Band 3 */
+ { 28, 183, 213 },
+ { 8, 134, 191 },
+ { 1, 86, 142 },
+ { 1, 56, 96 },
+ { 1, 30, 53 },
+ { 1, 12, 20 }
+ }, { /* Coeff Band 4 */
+ { 20, 190, 215 },
+ { 4, 135, 192 },
+ { 1, 84, 139 },
+ { 1, 53, 91 },
+ { 1, 28, 49 },
+ { 1, 11, 20 }
+ }, { /* Coeff Band 5 */
+ { 13, 196, 216 },
+ { 2, 137, 192 },
+ { 1, 86, 143 },
+ { 1, 57, 99 },
+ { 1, 32, 56 },
+ { 1, 13, 24 }
+ }
+ }
+ }, { /* block Type 1 */
+ { /* Intra */
+ { /* Coeff Band 0 */
+ { 211, 29, 217 },
+ { 96, 47, 156 },
+ { 22, 43, 87 }
+ }, { /* Coeff Band 1 */
+ { 78, 120, 193 },
+ { 111, 116, 186 },
+ { 46, 102, 164 },
+ { 15, 80, 128 },
+ { 2, 49, 76 },
+ { 1, 18, 28 }
+ }, { /* Coeff Band 2 */
+ { 71, 161, 203 },
+ { 42, 132, 192 },
+ { 10, 98, 150 },
+ { 3, 69, 109 },
+ { 1, 44, 70 },
+ { 1, 18, 29 }
+ }, { /* Coeff Band 3 */
+ { 57, 186, 211 },
+ { 30, 140, 196 },
+ { 4, 93, 146 },
+ { 1, 62, 102 },
+ { 1, 38, 65 },
+ { 1, 16, 27 }
+ }, { /* Coeff Band 4 */
+ { 47, 199, 217 },
+ { 14, 145, 196 },
+ { 1, 88, 142 },
+ { 1, 57, 98 },
+ { 1, 36, 62 },
+ { 1, 15, 26 }
+ }, { /* Coeff Band 5 */
+ { 26, 219, 229 },
+ { 5, 155, 207 },
+ { 1, 94, 151 },
+ { 1, 60, 104 },
+ { 1, 36, 62 },
+ { 1, 16, 28 }
+ }
+ }, { /* Inter */
+ { /* Coeff Band 0 */
+ { 233, 29, 248 },
+ { 146, 47, 220 },
+ { 43, 52, 140 }
+ }, { /* Coeff Band 1 */
+ { 100, 163, 232 },
+ { 179, 161, 222 },
+ { 63, 142, 204 },
+ { 37, 113, 174 },
+ { 26, 89, 137 },
+ { 18, 68, 97 }
+ }, { /* Coeff Band 2 */
+ { 85, 181, 230 },
+ { 32, 146, 209 },
+ { 7, 100, 164 },
+ { 3, 71, 121 },
+ { 1, 45, 77 },
+ { 1, 18, 30 }
+ }, { /* Coeff Band 3 */
+ { 65, 187, 230 },
+ { 20, 148, 207 },
+ { 2, 97, 159 },
+ { 1, 68, 116 },
+ { 1, 40, 70 },
+ { 1, 14, 29 }
+ }, { /* Coeff Band 4 */
+ { 40, 194, 227 },
+ { 8, 147, 204 },
+ { 1, 94, 155 },
+ { 1, 65, 112 },
+ { 1, 39, 66 },
+ { 1, 14, 26 }
+ }, { /* Coeff Band 5 */
+ { 16, 208, 228 },
+ { 3, 151, 207 },
+ { 1, 98, 160 },
+ { 1, 67, 117 },
+ { 1, 41, 74 },
+ { 1, 17, 31 }
+ }
+ }
+ }
+ }, { /* tx = 32x32 */
+ { /* block Type 0 */
+ { /* Intra */
+ { /* Coeff Band 0 */
+ { 17, 38, 140 },
+ { 7, 34, 80 },
+ { 1, 17, 29 }
+ }, { /* Coeff Band 1 */
+ { 37, 75, 128 },
+ { 41, 76, 128 },
+ { 26, 66, 116 },
+ { 12, 52, 94 },
+ { 2, 32, 55 },
+ { 1, 10, 16 }
+ }, { /* Coeff Band 2 */
+ { 50, 127, 154 },
+ { 37, 109, 152 },
+ { 16, 82, 121 },
+ { 5, 59, 85 },
+ { 1, 35, 54 },
+ { 1, 13, 20 }
+ }, { /* Coeff Band 3 */
+ { 40, 142, 167 },
+ { 17, 110, 157 },
+ { 2, 71, 112 },
+ { 1, 44, 72 },
+ { 1, 27, 45 },
+ { 1, 11, 17 }
+ }, { /* Coeff Band 4 */
+ { 30, 175, 188 },
+ { 9, 124, 169 },
+ { 1, 74, 116 },
+ { 1, 48, 78 },
+ { 1, 30, 49 },
+ { 1, 11, 18 }
+ }, { /* Coeff Band 5 */
+ { 10, 222, 223 },
+ { 2, 150, 194 },
+ { 1, 83, 128 },
+ { 1, 48, 79 },
+ { 1, 27, 45 },
+ { 1, 11, 17 }
+ }
+ }, { /* Inter */
+ { /* Coeff Band 0 */
+ { 36, 41, 235 },
+ { 29, 36, 193 },
+ { 10, 27, 111 }
+ }, { /* Coeff Band 1 */
+ { 85, 165, 222 },
+ { 177, 162, 215 },
+ { 110, 135, 195 },
+ { 57, 113, 168 },
+ { 23, 83, 120 },
+ { 10, 49, 61 }
+ }, { /* Coeff Band 2 */
+ { 85, 190, 223 },
+ { 36, 139, 200 },
+ { 5, 90, 146 },
+ { 1, 60, 103 },
+ { 1, 38, 65 },
+ { 1, 18, 30 }
+ }, { /* Coeff Band 3 */
+ { 72, 202, 223 },
+ { 23, 141, 199 },
+ { 2, 86, 140 },
+ { 1, 56, 97 },
+ { 1, 36, 61 },
+ { 1, 16, 27 }
+ }, { /* Coeff Band 4 */
+ { 55, 218, 225 },
+ { 13, 145, 200 },
+ { 1, 86, 141 },
+ { 1, 57, 99 },
+ { 1, 35, 61 },
+ { 1, 13, 22 }
+ }, { /* Coeff Band 5 */
+ { 15, 235, 212 },
+ { 1, 132, 184 },
+ { 1, 84, 139 },
+ { 1, 57, 97 },
+ { 1, 34, 56 },
+ { 1, 14, 23 }
+ }
+ }
+ }, { /* block Type 1 */
+ { /* Intra */
+ { /* Coeff Band 0 */
+ { 181, 21, 201 },
+ { 61, 37, 123 },
+ { 10, 38, 71 }
+ }, { /* Coeff Band 1 */
+ { 47, 106, 172 },
+ { 95, 104, 173 },
+ { 42, 93, 159 },
+ { 18, 77, 131 },
+ { 4, 50, 81 },
+ { 1, 17, 23 }
+ }, { /* Coeff Band 2 */
+ { 62, 147, 199 },
+ { 44, 130, 189 },
+ { 28, 102, 154 },
+ { 18, 75, 115 },
+ { 2, 44, 65 },
+ { 1, 12, 19 }
+ }, { /* Coeff Band 3 */
+ { 55, 153, 210 },
+ { 24, 130, 194 },
+ { 3, 93, 146 },
+ { 1, 61, 97 },
+ { 1, 31, 50 },
+ { 1, 10, 16 }
+ }, { /* Coeff Band 4 */
+ { 49, 186, 223 },
+ { 17, 148, 204 },
+ { 1, 96, 142 },
+ { 1, 53, 83 },
+ { 1, 26, 44 },
+ { 1, 11, 17 }
+ }, { /* Coeff Band 5 */
+ { 13, 217, 212 },
+ { 2, 136, 180 },
+ { 1, 78, 124 },
+ { 1, 50, 83 },
+ { 1, 29, 49 },
+ { 1, 14, 23 }
+ }
+ }, { /* Inter */
+ { /* Coeff Band 0 */
+ { 197, 13, 247 },
+ { 82, 17, 222 },
+ { 25, 17, 162 }
+ }, { /* Coeff Band 1 */
+ { 126, 186, 247 },
+ { 234, 191, 243 },
+ { 176, 177, 234 },
+ { 104, 158, 220 },
+ { 66, 128, 186 },
+ { 55, 90, 137 }
+ }, { /* Coeff Band 2 */
+ { 111, 197, 242 },
+ { 46, 158, 219 },
+ { 9, 104, 171 },
+ { 2, 65, 125 },
+ { 1, 44, 80 },
+ { 1, 17, 91 }
+ }, { /* Coeff Band 3 */
+ { 104, 208, 245 },
+ { 39, 168, 224 },
+ { 3, 109, 162 },
+ { 1, 79, 124 },
+ { 1, 50, 102 },
+ { 1, 43, 102 }
+ }, { /* Coeff Band 4 */
+ { 84, 220, 246 },
+ { 31, 177, 231 },
+ { 2, 115, 180 },
+ { 1, 79, 134 },
+ { 1, 55, 77 },
+ { 1, 60, 79 }
+ }, { /* Coeff Band 5 */
+ { 43, 243, 240 },
+ { 8, 180, 217 },
+ { 1, 115, 166 },
+ { 1, 84, 121 },
+ { 1, 51, 67 },
+ { 1, 16, 6 }
+ }
+ }
+ }
+ }
+};
+
+const int8_t ff_vp9_mv_joint_tree[3][2] = {
+ { -MV_JOINT_ZERO, 1 }, // '0'
+ { -MV_JOINT_H, 2 }, // '10'
+ { -MV_JOINT_V, -MV_JOINT_HV }, // '11x'
+};
+
+const int8_t ff_vp9_mv_class_tree[10][2] = {
+ { -0, 1 }, // '0'
+ { -1, 2 }, // '10'
+ { 3, 4 },
+ { -2, -3 }, // '110x'
+ { 5, 6 },
+ { -4, -5 }, // '1110x'
+ { -6, 7 }, // '11110'
+ { 8, 9 },
+ { -7, -8 }, // '111110x'
+ { -9, -10 }, // '111111x'
+};
+
+const int8_t ff_vp9_mv_fp_tree[3][2] = {
+ { -0, 1 }, // '0'
+ { -1, 2 }, // '10'
+ { -2, -3 }, // '11x'
+};
diff --git a/media/ffvpx/libavcodec/vp9data.h b/media/ffvpx/libavcodec/vp9data.h
index cb12e7e94..086dbdec0 100644
--- a/media/ffvpx/libavcodec/vp9data.h
+++ b/media/ffvpx/libavcodec/vp9data.h
@@ -24,2254 +24,48 @@
#include <stdint.h>
-#include "vp9.h"
-
-static const int8_t vp9_partition_tree[3][2] = {
- { -PARTITION_NONE, 1 }, // '0'
- { -PARTITION_H, 2 }, // '10'
- { -PARTITION_V, -PARTITION_SPLIT }, // '110', '111'
-};
-
-static const uint8_t vp9_default_kf_partition_probs[4][4][3] = {
- { /* 64x64 -> 32x32 */
- { 174, 35, 49 } /* a/l both not split */,
- { 68, 11, 27 } /* a split, l not split */,
- { 57, 15, 9 } /* l split, a not split */,
- { 12, 3, 3 } /* a/l both split */
- }, { /* 32x32 -> 16x16 */
- { 150, 40, 39 } /* a/l both not split */,
- { 78, 12, 26 } /* a split, l not split */,
- { 67, 33, 11 } /* l split, a not split */,
- { 24, 7, 5 } /* a/l both split */,
- }, { /* 16x16 -> 8x8 */
- { 149, 53, 53 } /* a/l both not split */,
- { 94, 20, 48 } /* a split, l not split */,
- { 83, 53, 24 } /* l split, a not split */,
- { 52, 18, 18 } /* a/l both split */,
- }, { /* 8x8 -> 4x4 */
- { 158, 97, 94 } /* a/l both not split */,
- { 93, 24, 99 } /* a split, l not split */,
- { 85, 119, 44 } /* l split, a not split */,
- { 62, 59, 67 } /* a/l both split */,
- },
-};
-
-static const int8_t vp9_segmentation_tree[7][2] = {
- { 1, 2 },
- { 3, 4 },
- { 5, 6 },
- { -0, -1 }, // '00x'
- { -2, -3 }, // '01x'
- { -4, -5 }, // '10x'
- { -6, -7 }, // '11x'
-};
-
-static const int8_t vp9_intramode_tree[9][2] = {
- { -DC_PRED, 1 }, // '0'
- { -TM_VP8_PRED, 2 }, // '10'
- { -VERT_PRED, 3 }, // '110'
- { 4, 6 },
- { -HOR_PRED, 5 }, // '11100'
- { -DIAG_DOWN_RIGHT_PRED, -VERT_RIGHT_PRED }, // '11101x'
- { -DIAG_DOWN_LEFT_PRED, 7 }, // '11110'
- { -VERT_LEFT_PRED, 8 }, // '111110'
- { -HOR_DOWN_PRED, -HOR_UP_PRED }, // '111111x'
-};
-
-static const uint8_t vp9_default_kf_ymode_probs[10][10][9] = {
- { /* above = v */
- { 43, 46, 168, 134, 107, 128, 69, 142, 92 } /* left = v */,
- { 44, 29, 68, 159, 201, 177, 50, 57, 77 } /* left = h */,
- { 63, 36, 126, 146, 123, 158, 60, 90, 96 } /* left = dc */,
- { 58, 38, 76, 114, 97, 172, 78, 133, 92 } /* left = d45 */,
- { 46, 41, 76, 140, 63, 184, 69, 112, 57 } /* left = d135 */,
- { 38, 32, 85, 140, 46, 112, 54, 151, 133 } /* left = d117 */,
- { 39, 27, 61, 131, 110, 175, 44, 75, 136 } /* left = d153 */,
- { 47, 35, 80, 100, 74, 143, 64, 163, 74 } /* left = d63 */,
- { 52, 30, 74, 113, 130, 175, 51, 64, 58 } /* left = d27 */,
- { 36, 61, 116, 114, 128, 162, 80, 125, 82 } /* left = tm */
- }, { /* above = h */
- { 55, 44, 68, 166, 179, 192, 57, 57, 108 } /* left = v */,
- { 42, 26, 11, 199, 241, 228, 23, 15, 85 } /* left = h */,
- { 82, 26, 26, 171, 208, 204, 44, 32, 105 } /* left = dc */,
- { 68, 42, 19, 131, 160, 199, 55, 52, 83 } /* left = d45 */,
- { 58, 50, 25, 139, 115, 232, 39, 52, 118 } /* left = d135 */,
- { 50, 35, 33, 153, 104, 162, 64, 59, 131 } /* left = d117 */,
- { 44, 24, 16, 150, 177, 202, 33, 19, 156 } /* left = d153 */,
- { 53, 49, 21, 110, 116, 168, 59, 80, 76 } /* left = d63 */,
- { 55, 27, 12, 153, 203, 218, 26, 27, 49 } /* left = d27 */,
- { 38, 72, 19, 168, 203, 212, 50, 50, 107 } /* left = tm */
- }, { /* above = dc */
- { 92, 45, 102, 136, 116, 180, 74, 90, 100 } /* left = v */,
- { 73, 32, 19, 187, 222, 215, 46, 34, 100 } /* left = h */,
- { 137, 30, 42, 148, 151, 207, 70, 52, 91 } /* left = dc */,
- { 91, 30, 32, 116, 121, 186, 93, 86, 94 } /* left = d45 */,
- { 72, 35, 36, 149, 68, 206, 68, 63, 105 } /* left = d135 */,
- { 73, 31, 28, 138, 57, 124, 55, 122, 151 } /* left = d117 */,
- { 67, 23, 21, 140, 126, 197, 40, 37, 171 } /* left = d153 */,
- { 74, 32, 27, 107, 86, 160, 63, 134, 102 } /* left = d63 */,
- { 86, 27, 28, 128, 154, 212, 45, 43, 53 } /* left = d27 */,
- { 59, 67, 44, 140, 161, 202, 78, 67, 119 } /* left = tm */
- }, { /* above = d45 */
- { 59, 38, 83, 112, 103, 162, 98, 136, 90 } /* left = v */,
- { 62, 30, 23, 158, 200, 207, 59, 57, 50 } /* left = h */,
- { 103, 26, 36, 129, 132, 201, 83, 80, 93 } /* left = dc */,
- { 67, 30, 29, 84, 86, 191, 102, 91, 59 } /* left = d45 */,
- { 60, 32, 33, 112, 71, 220, 64, 89, 104 } /* left = d135 */,
- { 53, 26, 34, 130, 56, 149, 84, 120, 103 } /* left = d117 */,
- { 53, 21, 23, 133, 109, 210, 56, 77, 172 } /* left = d153 */,
- { 61, 29, 29, 93, 97, 165, 83, 175, 162 } /* left = d63 */,
- { 77, 19, 29, 112, 142, 228, 55, 66, 36 } /* left = d27 */,
- { 47, 47, 43, 114, 137, 181, 100, 99, 95 } /* left = tm */
- }, { /* above = d135 */
- { 53, 40, 55, 139, 69, 183, 61, 80, 110 } /* left = v */,
- { 40, 29, 19, 161, 180, 207, 43, 24, 91 } /* left = h */,
- { 69, 23, 29, 128, 83, 199, 46, 44, 101 } /* left = dc */,
- { 60, 34, 19, 105, 61, 198, 53, 64, 89 } /* left = d45 */,
- { 52, 31, 22, 158, 40, 209, 58, 62, 89 } /* left = d135 */,
- { 44, 31, 29, 147, 46, 158, 56, 102, 198 } /* left = d117 */,
- { 35, 19, 12, 135, 87, 209, 41, 45, 167 } /* left = d153 */,
- { 51, 38, 25, 113, 58, 164, 70, 93, 97 } /* left = d63 */,
- { 55, 25, 21, 118, 95, 215, 38, 39, 66 } /* left = d27 */,
- { 47, 54, 34, 146, 108, 203, 72, 103, 151 } /* left = tm */
- }, { /* above = d117 */
- { 46, 27, 80, 150, 55, 124, 55, 121, 135 } /* left = v */,
- { 36, 23, 27, 165, 149, 166, 54, 64, 118 } /* left = h */,
- { 64, 19, 37, 156, 66, 138, 49, 95, 133 } /* left = dc */,
- { 53, 21, 36, 131, 63, 163, 60, 109, 81 } /* left = d45 */,
- { 40, 26, 35, 154, 40, 185, 51, 97, 123 } /* left = d135 */,
- { 35, 19, 34, 179, 19, 97, 48, 129, 124 } /* left = d117 */,
- { 36, 20, 26, 136, 62, 164, 33, 77, 154 } /* left = d153 */,
- { 45, 26, 28, 129, 45, 129, 49, 147, 123 } /* left = d63 */,
- { 45, 18, 32, 130, 90, 157, 40, 79, 91 } /* left = d27 */,
- { 38, 44, 51, 136, 74, 162, 57, 97, 121 } /* left = tm */
- }, { /* above = d153 */
- { 56, 39, 58, 133, 117, 173, 48, 53, 187 } /* left = v */,
- { 35, 21, 12, 161, 212, 207, 20, 23, 145 } /* left = h */,
- { 75, 17, 22, 136, 138, 185, 32, 34, 166 } /* left = dc */,
- { 56, 29, 19, 117, 109, 181, 55, 68, 112 } /* left = d45 */,
- { 47, 29, 17, 153, 64, 220, 59, 51, 114 } /* left = d135 */,
- { 46, 16, 24, 136, 76, 147, 41, 64, 172 } /* left = d117 */,
- { 34, 17, 11, 108, 152, 187, 13, 15, 209 } /* left = d153 */,
- { 55, 30, 18, 122, 79, 179, 44, 88, 116 } /* left = d63 */,
- { 51, 24, 14, 115, 133, 209, 32, 26, 104 } /* left = d27 */,
- { 37, 49, 25, 129, 168, 164, 41, 54, 148 } /* left = tm */
- }, { /* above = d63 */
- { 48, 34, 86, 101, 92, 146, 78, 179, 134 } /* left = v */,
- { 47, 22, 24, 138, 187, 178, 68, 69, 59 } /* left = h */,
- { 78, 23, 39, 111, 117, 170, 74, 124, 94 } /* left = dc */,
- { 56, 25, 33, 105, 112, 187, 95, 177, 129 } /* left = d45 */,
- { 48, 31, 27, 114, 63, 183, 82, 116, 56 } /* left = d135 */,
- { 43, 28, 37, 121, 63, 123, 61, 192, 169 } /* left = d117 */,
- { 42, 17, 24, 109, 97, 177, 56, 76, 122 } /* left = d153 */,
- { 46, 23, 32, 74, 86, 150, 67, 183, 88 } /* left = d63 */,
- { 58, 18, 28, 105, 139, 182, 70, 92, 63 } /* left = d27 */,
- { 36, 38, 48, 92, 122, 165, 88, 137, 91 } /* left = tm */
- }, { /* above = d27 */
- { 62, 44, 61, 123, 105, 189, 48, 57, 64 } /* left = v */,
- { 47, 25, 17, 175, 222, 220, 24, 30, 86 } /* left = h */,
- { 82, 22, 32, 127, 143, 213, 39, 41, 70 } /* left = dc */,
- { 68, 36, 17, 106, 102, 206, 59, 74, 74 } /* left = d45 */,
- { 57, 39, 23, 151, 68, 216, 55, 63, 58 } /* left = d135 */,
- { 49, 30, 35, 141, 70, 168, 82, 40, 115 } /* left = d117 */,
- { 51, 25, 15, 136, 129, 202, 38, 35, 139 } /* left = d153 */,
- { 59, 39, 19, 114, 75, 180, 77, 104, 42 } /* left = d63 */,
- { 68, 26, 16, 111, 141, 215, 29, 28, 28 } /* left = d27 */,
- { 40, 61, 26, 126, 152, 206, 61, 59, 93 } /* left = tm */
- }, { /* above = tm */
- { 44, 78, 115, 132, 119, 173, 71, 112, 93 } /* left = v */,
- { 39, 38, 21, 184, 227, 206, 42, 32, 64 } /* left = h */,
- { 65, 70, 60, 155, 159, 199, 61, 60, 81 } /* left = dc */,
- { 58, 47, 36, 124, 137, 193, 80, 82, 78 } /* left = d45 */,
- { 49, 50, 35, 144, 95, 205, 63, 78, 59 } /* left = d135 */,
- { 41, 53, 52, 148, 71, 142, 65, 128, 51 } /* left = d117 */,
- { 40, 36, 28, 143, 143, 202, 40, 55, 137 } /* left = d153 */,
- { 42, 44, 44, 104, 105, 164, 64, 130, 80 } /* left = d63 */,
- { 52, 34, 29, 129, 183, 227, 42, 35, 43 } /* left = d27 */,
- { 43, 81, 53, 140, 169, 204, 68, 84, 72 } /* left = tm */
- }
-};
-
-static const uint8_t vp9_default_kf_uvmode_probs[10][9] = {
- { 118, 15, 123, 148, 131, 101, 44, 93, 131 } /* y = v */,
- { 113, 12, 23, 188, 226, 142, 26, 32, 125 } /* y = h */,
- { 144, 11, 54, 157, 195, 130, 46, 58, 108 } /* y = dc */,
- { 120, 11, 50, 123, 163, 135, 64, 77, 103 } /* y = d45 */,
- { 113, 9, 36, 155, 111, 157, 32, 44, 161 } /* y = d135 */,
- { 116, 9, 55, 176, 76, 96, 37, 61, 149 } /* y = d117 */,
- { 115, 9, 28, 141, 161, 167, 21, 25, 193 } /* y = d153 */,
- { 116, 12, 64, 120, 140, 125, 49, 115, 121 } /* y = d63 */,
- { 120, 12, 32, 145, 195, 142, 32, 38, 86 } /* y = d27 */,
- { 102, 19, 66, 162, 182, 122, 35, 59, 128 } /* y = tm */
-};
-
-static const int8_t vp9_inter_mode_tree[3][2] = {
- { -ZEROMV, 1 }, // '0'
- { -NEARESTMV, 2 }, // '10'
- { -NEARMV, -NEWMV }, // '11x'
-};
-
-static const int8_t vp9_filter_tree[2][2] = {
- { -0, 1 }, // '0'
- { -1, -2 }, // '1x'
-};
-
-static const enum FilterMode vp9_filter_lut[3] = {
- FILTER_8TAP_REGULAR,
- FILTER_8TAP_SMOOTH,
- FILTER_8TAP_SHARP,
-};
-
-static const int16_t vp9_dc_qlookup[3][256] = {
- {
- 4, 8, 8, 9, 10, 11, 12, 12,
- 13, 14, 15, 16, 17, 18, 19, 19,
- 20, 21, 22, 23, 24, 25, 26, 26,
- 27, 28, 29, 30, 31, 32, 32, 33,
- 34, 35, 36, 37, 38, 38, 39, 40,
- 41, 42, 43, 43, 44, 45, 46, 47,
- 48, 48, 49, 50, 51, 52, 53, 53,
- 54, 55, 56, 57, 57, 58, 59, 60,
- 61, 62, 62, 63, 64, 65, 66, 66,
- 67, 68, 69, 70, 70, 71, 72, 73,
- 74, 74, 75, 76, 77, 78, 78, 79,
- 80, 81, 81, 82, 83, 84, 85, 85,
- 87, 88, 90, 92, 93, 95, 96, 98,
- 99, 101, 102, 104, 105, 107, 108, 110,
- 111, 113, 114, 116, 117, 118, 120, 121,
- 123, 125, 127, 129, 131, 134, 136, 138,
- 140, 142, 144, 146, 148, 150, 152, 154,
- 156, 158, 161, 164, 166, 169, 172, 174,
- 177, 180, 182, 185, 187, 190, 192, 195,
- 199, 202, 205, 208, 211, 214, 217, 220,
- 223, 226, 230, 233, 237, 240, 243, 247,
- 250, 253, 257, 261, 265, 269, 272, 276,
- 280, 284, 288, 292, 296, 300, 304, 309,
- 313, 317, 322, 326, 330, 335, 340, 344,
- 349, 354, 359, 364, 369, 374, 379, 384,
- 389, 395, 400, 406, 411, 417, 423, 429,
- 435, 441, 447, 454, 461, 467, 475, 482,
- 489, 497, 505, 513, 522, 530, 539, 549,
- 559, 569, 579, 590, 602, 614, 626, 640,
- 654, 668, 684, 700, 717, 736, 755, 775,
- 796, 819, 843, 869, 896, 925, 955, 988,
- 1022, 1058, 1098, 1139, 1184, 1232, 1282, 1336,
- }, {
- 4, 9, 10, 13, 15, 17, 20, 22,
- 25, 28, 31, 34, 37, 40, 43, 47,
- 50, 53, 57, 60, 64, 68, 71, 75,
- 78, 82, 86, 90, 93, 97, 101, 105,
- 109, 113, 116, 120, 124, 128, 132, 136,
- 140, 143, 147, 151, 155, 159, 163, 166,
- 170, 174, 178, 182, 185, 189, 193, 197,
- 200, 204, 208, 212, 215, 219, 223, 226,
- 230, 233, 237, 241, 244, 248, 251, 255,
- 259, 262, 266, 269, 273, 276, 280, 283,
- 287, 290, 293, 297, 300, 304, 307, 310,
- 314, 317, 321, 324, 327, 331, 334, 337,
- 343, 350, 356, 362, 369, 375, 381, 387,
- 394, 400, 406, 412, 418, 424, 430, 436,
- 442, 448, 454, 460, 466, 472, 478, 484,
- 490, 499, 507, 516, 525, 533, 542, 550,
- 559, 567, 576, 584, 592, 601, 609, 617,
- 625, 634, 644, 655, 666, 676, 687, 698,
- 708, 718, 729, 739, 749, 759, 770, 782,
- 795, 807, 819, 831, 844, 856, 868, 880,
- 891, 906, 920, 933, 947, 961, 975, 988,
- 1001, 1015, 1030, 1045, 1061, 1076, 1090, 1105,
- 1120, 1137, 1153, 1170, 1186, 1202, 1218, 1236,
- 1253, 1271, 1288, 1306, 1323, 1342, 1361, 1379,
- 1398, 1416, 1436, 1456, 1476, 1496, 1516, 1537,
- 1559, 1580, 1601, 1624, 1647, 1670, 1692, 1717,
- 1741, 1766, 1791, 1817, 1844, 1871, 1900, 1929,
- 1958, 1990, 2021, 2054, 2088, 2123, 2159, 2197,
- 2236, 2276, 2319, 2363, 2410, 2458, 2508, 2561,
- 2616, 2675, 2737, 2802, 2871, 2944, 3020, 3102,
- 3188, 3280, 3375, 3478, 3586, 3702, 3823, 3953,
- 4089, 4236, 4394, 4559, 4737, 4929, 5130, 5347,
- }, {
- 4, 12, 18, 25, 33, 41, 50, 60,
- 70, 80, 91, 103, 115, 127, 140, 153,
- 166, 180, 194, 208, 222, 237, 251, 266,
- 281, 296, 312, 327, 343, 358, 374, 390,
- 405, 421, 437, 453, 469, 484, 500, 516,
- 532, 548, 564, 580, 596, 611, 627, 643,
- 659, 674, 690, 706, 721, 737, 752, 768,
- 783, 798, 814, 829, 844, 859, 874, 889,
- 904, 919, 934, 949, 964, 978, 993, 1008,
- 1022, 1037, 1051, 1065, 1080, 1094, 1108, 1122,
- 1136, 1151, 1165, 1179, 1192, 1206, 1220, 1234,
- 1248, 1261, 1275, 1288, 1302, 1315, 1329, 1342,
- 1368, 1393, 1419, 1444, 1469, 1494, 1519, 1544,
- 1569, 1594, 1618, 1643, 1668, 1692, 1717, 1741,
- 1765, 1789, 1814, 1838, 1862, 1885, 1909, 1933,
- 1957, 1992, 2027, 2061, 2096, 2130, 2165, 2199,
- 2233, 2267, 2300, 2334, 2367, 2400, 2434, 2467,
- 2499, 2532, 2575, 2618, 2661, 2704, 2746, 2788,
- 2830, 2872, 2913, 2954, 2995, 3036, 3076, 3127,
- 3177, 3226, 3275, 3324, 3373, 3421, 3469, 3517,
- 3565, 3621, 3677, 3733, 3788, 3843, 3897, 3951,
- 4005, 4058, 4119, 4181, 4241, 4301, 4361, 4420,
- 4479, 4546, 4612, 4677, 4742, 4807, 4871, 4942,
- 5013, 5083, 5153, 5222, 5291, 5367, 5442, 5517,
- 5591, 5665, 5745, 5825, 5905, 5984, 6063, 6149,
- 6234, 6319, 6404, 6495, 6587, 6678, 6769, 6867,
- 6966, 7064, 7163, 7269, 7376, 7483, 7599, 7715,
- 7832, 7958, 8085, 8214, 8352, 8492, 8635, 8788,
- 8945, 9104, 9275, 9450, 9639, 9832, 10031, 10245,
- 10465, 10702, 10946, 11210, 11482, 11776, 12081, 12409,
- 12750, 13118, 13501, 13913, 14343, 14807, 15290, 15812,
- 16356, 16943, 17575, 18237, 18949, 19718, 20521, 21387,
- }
-};
-
-static const int16_t vp9_ac_qlookup[3][256] = {
- {
- 4, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22,
- 23, 24, 25, 26, 27, 28, 29, 30,
- 31, 32, 33, 34, 35, 36, 37, 38,
- 39, 40, 41, 42, 43, 44, 45, 46,
- 47, 48, 49, 50, 51, 52, 53, 54,
- 55, 56, 57, 58, 59, 60, 61, 62,
- 63, 64, 65, 66, 67, 68, 69, 70,
- 71, 72, 73, 74, 75, 76, 77, 78,
- 79, 80, 81, 82, 83, 84, 85, 86,
- 87, 88, 89, 90, 91, 92, 93, 94,
- 95, 96, 97, 98, 99, 100, 101, 102,
- 104, 106, 108, 110, 112, 114, 116, 118,
- 120, 122, 124, 126, 128, 130, 132, 134,
- 136, 138, 140, 142, 144, 146, 148, 150,
- 152, 155, 158, 161, 164, 167, 170, 173,
- 176, 179, 182, 185, 188, 191, 194, 197,
- 200, 203, 207, 211, 215, 219, 223, 227,
- 231, 235, 239, 243, 247, 251, 255, 260,
- 265, 270, 275, 280, 285, 290, 295, 300,
- 305, 311, 317, 323, 329, 335, 341, 347,
- 353, 359, 366, 373, 380, 387, 394, 401,
- 408, 416, 424, 432, 440, 448, 456, 465,
- 474, 483, 492, 501, 510, 520, 530, 540,
- 550, 560, 571, 582, 593, 604, 615, 627,
- 639, 651, 663, 676, 689, 702, 715, 729,
- 743, 757, 771, 786, 801, 816, 832, 848,
- 864, 881, 898, 915, 933, 951, 969, 988,
- 1007, 1026, 1046, 1066, 1087, 1108, 1129, 1151,
- 1173, 1196, 1219, 1243, 1267, 1292, 1317, 1343,
- 1369, 1396, 1423, 1451, 1479, 1508, 1537, 1567,
- 1597, 1628, 1660, 1692, 1725, 1759, 1793, 1828,
- }, {
- 4, 9, 11, 13, 16, 18, 21, 24,
- 27, 30, 33, 37, 40, 44, 48, 51,
- 55, 59, 63, 67, 71, 75, 79, 83,
- 88, 92, 96, 100, 105, 109, 114, 118,
- 122, 127, 131, 136, 140, 145, 149, 154,
- 158, 163, 168, 172, 177, 181, 186, 190,
- 195, 199, 204, 208, 213, 217, 222, 226,
- 231, 235, 240, 244, 249, 253, 258, 262,
- 267, 271, 275, 280, 284, 289, 293, 297,
- 302, 306, 311, 315, 319, 324, 328, 332,
- 337, 341, 345, 349, 354, 358, 362, 367,
- 371, 375, 379, 384, 388, 392, 396, 401,
- 409, 417, 425, 433, 441, 449, 458, 466,
- 474, 482, 490, 498, 506, 514, 523, 531,
- 539, 547, 555, 563, 571, 579, 588, 596,
- 604, 616, 628, 640, 652, 664, 676, 688,
- 700, 713, 725, 737, 749, 761, 773, 785,
- 797, 809, 825, 841, 857, 873, 889, 905,
- 922, 938, 954, 970, 986, 1002, 1018, 1038,
- 1058, 1078, 1098, 1118, 1138, 1158, 1178, 1198,
- 1218, 1242, 1266, 1290, 1314, 1338, 1362, 1386,
- 1411, 1435, 1463, 1491, 1519, 1547, 1575, 1603,
- 1631, 1663, 1695, 1727, 1759, 1791, 1823, 1859,
- 1895, 1931, 1967, 2003, 2039, 2079, 2119, 2159,
- 2199, 2239, 2283, 2327, 2371, 2415, 2459, 2507,
- 2555, 2603, 2651, 2703, 2755, 2807, 2859, 2915,
- 2971, 3027, 3083, 3143, 3203, 3263, 3327, 3391,
- 3455, 3523, 3591, 3659, 3731, 3803, 3876, 3952,
- 4028, 4104, 4184, 4264, 4348, 4432, 4516, 4604,
- 4692, 4784, 4876, 4972, 5068, 5168, 5268, 5372,
- 5476, 5584, 5692, 5804, 5916, 6032, 6148, 6268,
- 6388, 6512, 6640, 6768, 6900, 7036, 7172, 7312,
- }, {
- 4, 13, 19, 27, 35, 44, 54, 64,
- 75, 87, 99, 112, 126, 139, 154, 168,
- 183, 199, 214, 230, 247, 263, 280, 297,
- 314, 331, 349, 366, 384, 402, 420, 438,
- 456, 475, 493, 511, 530, 548, 567, 586,
- 604, 623, 642, 660, 679, 698, 716, 735,
- 753, 772, 791, 809, 828, 846, 865, 884,
- 902, 920, 939, 957, 976, 994, 1012, 1030,
- 1049, 1067, 1085, 1103, 1121, 1139, 1157, 1175,
- 1193, 1211, 1229, 1246, 1264, 1282, 1299, 1317,
- 1335, 1352, 1370, 1387, 1405, 1422, 1440, 1457,
- 1474, 1491, 1509, 1526, 1543, 1560, 1577, 1595,
- 1627, 1660, 1693, 1725, 1758, 1791, 1824, 1856,
- 1889, 1922, 1954, 1987, 2020, 2052, 2085, 2118,
- 2150, 2183, 2216, 2248, 2281, 2313, 2346, 2378,
- 2411, 2459, 2508, 2556, 2605, 2653, 2701, 2750,
- 2798, 2847, 2895, 2943, 2992, 3040, 3088, 3137,
- 3185, 3234, 3298, 3362, 3426, 3491, 3555, 3619,
- 3684, 3748, 3812, 3876, 3941, 4005, 4069, 4149,
- 4230, 4310, 4390, 4470, 4550, 4631, 4711, 4791,
- 4871, 4967, 5064, 5160, 5256, 5352, 5448, 5544,
- 5641, 5737, 5849, 5961, 6073, 6185, 6297, 6410,
- 6522, 6650, 6778, 6906, 7034, 7162, 7290, 7435,
- 7579, 7723, 7867, 8011, 8155, 8315, 8475, 8635,
- 8795, 8956, 9132, 9308, 9484, 9660, 9836, 10028,
- 10220, 10412, 10604, 10812, 11020, 11228, 11437, 11661,
- 11885, 12109, 12333, 12573, 12813, 13053, 13309, 13565,
- 13821, 14093, 14365, 14637, 14925, 15213, 15502, 15806,
- 16110, 16414, 16734, 17054, 17390, 17726, 18062, 18414,
- 18766, 19134, 19502, 19886, 20270, 20670, 21070, 21486,
- 21902, 22334, 22766, 23214, 23662, 24126, 24590, 25070,
- 25551, 26047, 26559, 27071, 27599, 28143, 28687, 29247,
- }
-};
-
-static const enum TxfmType vp9_intra_txfm_type[14] = {
- [VERT_PRED] = ADST_DCT,
- [HOR_PRED] = DCT_ADST,
- [DC_PRED] = DCT_DCT,
- [DIAG_DOWN_LEFT_PRED] = DCT_DCT,
- [DIAG_DOWN_RIGHT_PRED] = ADST_ADST,
- [VERT_RIGHT_PRED] = ADST_DCT,
- [HOR_DOWN_PRED] = DCT_ADST,
- [VERT_LEFT_PRED] = ADST_DCT,
- [HOR_UP_PRED] = DCT_ADST,
- [TM_VP8_PRED] = ADST_ADST,
- [NEARESTMV] = DCT_DCT,
- [NEARMV] = DCT_DCT,
- [ZEROMV] = DCT_DCT,
- [NEWMV] = DCT_DCT,
-};
-
-static const int16_t vp9_default_scan_4x4[16] = {
- 0, 1, 4, 5,
- 2, 8, 3, 6,
- 12, 9, 7, 10,
- 13, 11, 14, 15,
-};
-
-static const int16_t vp9_col_scan_4x4[16] = {
- 0, 1, 2, 4,
- 3, 5, 6, 8,
- 7, 9, 10, 12,
- 13, 11, 14, 15,
-};
-
-static const int16_t vp9_row_scan_4x4[16] = {
- 0, 4, 1, 8,
- 5, 12, 9, 2,
- 6, 13, 3, 10,
- 7, 14, 11, 15,
-};
-
-static const int16_t vp9_default_scan_8x8[64] = {
- 0, 1, 8, 2, 9, 16, 10, 3,
- 17, 24, 18, 11, 4, 25, 32, 19,
- 12, 26, 5, 33, 20, 27, 40, 13,
- 34, 6, 41, 28, 21, 35, 42, 48,
- 14, 7, 36, 29, 43, 56, 49, 22,
- 15, 37, 50, 44, 57, 30, 23, 51,
- 45, 58, 38, 31, 52, 59, 39, 46,
- 53, 60, 47, 54, 61, 55, 62, 63,
-};
-
-static const int16_t vp9_col_scan_8x8[64] = {
- 0, 1, 2, 8, 3, 9, 4, 10,
- 16, 5, 11, 17, 12, 18, 6, 24,
- 19, 13, 25, 7, 26, 20, 32, 14,
- 27, 21, 33, 28, 34, 15, 22, 35,
- 40, 29, 41, 36, 23, 30, 42, 37,
- 48, 43, 31, 44, 49, 38, 50, 56,
- 45, 39, 51, 57, 52, 46, 58, 53,
- 59, 47, 60, 54, 61, 55, 62, 63,
-};
-
-static const int16_t vp9_row_scan_8x8[64] = {
- 0, 8, 16, 1, 9, 24, 2, 17,
- 32, 10, 25, 3, 40, 18, 11, 33,
- 26, 19, 4, 48, 41, 34, 12, 27,
- 56, 20, 5, 42, 35, 13, 49, 28,
- 6, 21, 43, 36, 14, 50, 29, 57,
- 7, 44, 22, 37, 51, 15, 58, 30,
- 23, 45, 52, 38, 59, 31, 46, 53,
- 39, 60, 47, 61, 54, 62, 55, 63,
-};
-
-static const int16_t vp9_default_scan_16x16[256] = {
- 0, 1, 16, 2, 17, 32, 3, 18, 33, 48, 4, 34, 19, 49, 20, 5,
- 35, 64, 50, 36, 65, 21, 6, 51, 80, 66, 37, 22, 52, 7, 81, 67,
- 38, 82, 53, 23, 96, 68, 8, 83, 97, 54, 39, 69, 112, 24, 98, 84,
- 70, 55, 9, 40, 85, 99, 113, 128, 25, 114, 100, 71, 86, 56, 10, 41,
- 115, 101, 129, 116, 72, 87, 26, 130, 144, 102, 57, 11, 42, 117, 131, 145,
- 88, 103, 27, 73, 132, 118, 146, 58, 160, 12, 43, 133, 147, 104, 89, 119,
- 161, 74, 148, 134, 28, 162, 59, 13, 176, 120, 149, 90, 135, 105, 163, 44,
- 75, 177, 164, 29, 150, 121, 136, 178, 165, 14, 106, 60, 91, 151, 45, 179,
- 192, 137, 166, 122, 76, 180, 152, 30, 61, 15, 107, 167, 181, 193, 92, 208,
- 46, 138, 123, 153, 194, 77, 168, 182, 31, 195, 209, 183, 108, 139, 62, 154,
- 47, 196, 93, 169, 210, 197, 224, 124, 184, 211, 78, 109, 170, 155, 63, 198,
- 212, 185, 225, 240, 140, 94, 199, 125, 79, 213, 226, 171, 186, 156, 214, 200,
- 110, 227, 141, 95, 241, 215, 228, 201, 126, 242, 187, 172, 157, 229, 111, 216,
- 243, 142, 202, 230, 127, 217, 244, 173, 188, 231, 158, 203, 143, 245, 218, 232,
- 189, 246, 159, 174, 233, 247, 219, 204, 175, 190, 248, 234, 205, 220, 249, 191,
- 235, 221, 250, 206, 222, 251, 236, 207, 237, 223, 252, 238, 253, 239, 254, 255,
-};
-
-static const int16_t vp9_col_scan_16x16[256] = {
- 0, 1, 2, 3, 16, 4, 17, 5, 18, 6, 19, 32, 20, 7, 33, 21,
- 34, 8, 35, 22, 48, 36, 9, 49, 23, 50, 37, 10, 38, 51, 24, 64,
- 52, 11, 65, 39, 25, 53, 66, 54, 40, 67, 12, 80, 26, 68, 55, 81,
- 41, 69, 13, 27, 82, 56, 70, 83, 42, 14, 84, 96, 71, 28, 57, 85,
- 97, 15, 72, 98, 43, 86, 58, 99, 29, 87, 100, 112, 73, 44, 101, 59,
- 30, 113, 88, 114, 74, 128, 102, 45, 31, 115, 60, 103, 89, 116, 75, 129,
- 117, 46, 104, 90, 61, 130, 118, 131, 132, 105, 76, 47, 119, 144, 91, 62,
- 133, 106, 145, 120, 146, 134, 77, 147, 121, 92, 135, 148, 63, 107, 136, 122,
- 93, 149, 160, 78, 150, 137, 108, 161, 162, 151, 123, 79, 138, 163, 152, 94,
- 164, 109, 165, 153, 124, 139, 176, 166, 95, 177, 167, 110, 154, 178, 125, 179,
- 140, 168, 155, 111, 180, 192, 181, 169, 141, 126, 182, 193, 194, 156, 183, 170,
- 195, 127, 142, 196, 184, 208, 197, 157, 171, 143, 185, 198, 209, 199, 210, 172,
- 158, 186, 211, 224, 212, 200, 240, 159, 213, 225, 187, 201, 173, 226, 214, 215,
- 227, 202, 228, 188, 241, 216, 174, 229, 242, 203, 243, 217, 230, 175, 189, 244,
- 231, 204, 218, 232, 245, 219, 246, 190, 233, 205, 191, 247, 234, 248, 220, 206,
- 249, 235, 221, 207, 250, 236, 222, 251, 223, 237, 238, 252, 239, 253, 254, 255,
-};
-
-static const int16_t vp9_row_scan_16x16[256] = {
- 0, 16, 32, 1, 48, 17, 64, 33, 2, 80, 18, 49, 96, 34, 3, 65,
- 19, 112, 50, 81, 35, 4, 128, 66, 20, 97, 51, 82, 5, 144, 36, 67,
- 113, 98, 21, 52, 160, 83, 129, 37, 68, 6, 114, 176, 99, 53, 22, 84,
- 145, 38, 69, 130, 7, 115, 192, 100, 54, 23, 85, 161, 146, 131, 39, 70,
- 208, 116, 8, 101, 177, 55, 86, 24, 162, 147, 132, 71, 224, 117, 40, 102,
- 9, 148, 56, 87, 193, 163, 240, 133, 178, 25, 118, 72, 41, 103, 164, 10,
- 149, 88, 134, 209, 179, 57, 119, 194, 26, 73, 165, 150, 104, 42, 135, 11,
- 180, 120, 89, 225, 195, 58, 27, 210, 151, 181, 166, 74, 43, 105, 12, 136,
- 90, 59, 241, 121, 28, 196, 167, 211, 152, 44, 182, 137, 75, 13, 226, 106,
- 122, 60, 197, 91, 168, 29, 183, 153, 14, 76, 212, 138, 45, 107, 15, 198,
- 92, 227, 169, 30, 123, 154, 61, 242, 184, 213, 139, 46, 77, 31, 108, 170,
- 199, 185, 124, 228, 93, 155, 214, 62, 140, 243, 78, 47, 200, 109, 186, 171,
- 201, 94, 63, 215, 229, 156, 79, 125, 141, 110, 216, 187, 172, 244, 202, 230,
- 217, 95, 157, 126, 245, 111, 142, 231, 188, 127, 158, 218, 173, 232, 246, 233,
- 203, 143, 247, 174, 189, 159, 219, 204, 248, 234, 249, 175, 190, 220, 205, 250,
- 235, 191, 221, 251, 236, 206, 252, 222, 207, 237, 223, 253, 238, 254, 239, 255,
-};
-
-static const int16_t vp9_default_scan_32x32[1024] = {
- 0, 1, 32, 2, 33, 64, 3, 34, 65, 4, 96, 35, 66, 5, 36, 97, 67, 128, 98, 68, 37, 6, 129, 99, 7, 160, 69, 38, 130, 100, 161, 131,
- 39, 70, 8, 101, 162, 132, 192, 71, 40, 9, 102, 163, 133, 193, 72, 224, 103, 41, 164, 10, 194, 134, 165, 73, 104, 135, 225, 42, 195, 11, 256, 166,
- 226, 196, 74, 105, 136, 43, 12, 167, 197, 227, 257, 75, 106, 137, 228, 44, 198, 168, 258, 288, 13, 229, 76, 107, 199, 138, 259, 169, 289, 45, 230, 260,
- 200, 108, 14, 170, 139, 320, 290, 77, 231, 261, 46, 201, 140, 291, 109, 232, 321, 262, 171, 78, 292, 15, 322, 202, 263, 352, 172, 293, 233, 141, 323, 110,
- 47, 203, 264, 234, 294, 353, 324, 16, 79, 204, 265, 295, 325, 173, 354, 142, 235, 384, 48, 296, 111, 266, 355, 326, 80, 17, 205, 236, 174, 356, 385, 327,
- 143, 297, 267, 357, 386, 112, 49, 328, 298, 206, 416, 237, 358, 387, 81, 175, 18, 329, 359, 388, 299, 330, 389, 113, 417, 238, 360, 50, 207, 418, 390, 331,
- 19, 448, 361, 82, 419, 391, 239, 51, 362, 420, 114, 449, 480, 421, 83, 363, 450, 422, 512, 451, 423, 115, 452, 481, 453, 482, 454, 544, 483, 455, 513, 484,
- 514, 485, 515, 486, 545, 576, 487, 546, 547, 608, 577, 578, 579, 609, 610, 611, 20, 144, 268, 392, 516, 640, 21, 52, 145, 176, 269, 300, 393, 424, 517, 548,
- 641, 672, 22, 53, 84, 146, 177, 208, 270, 301, 332, 394, 425, 456, 518, 549, 580, 642, 673, 704, 23, 54, 85, 116, 147, 178, 209, 240, 271, 302, 333, 364,
- 395, 426, 457, 488, 519, 550, 581, 612, 643, 674, 705, 736, 55, 86, 117, 179, 210, 241, 303, 334, 365, 427, 458, 489, 551, 582, 613, 675, 706, 737, 87, 118,
- 211, 242, 335, 366, 459, 490, 583, 614, 707, 738, 119, 243, 367, 491, 615, 739, 24, 148, 272, 396, 520, 644, 768, 25, 56, 149, 180, 273, 304, 397, 428, 521,
- 552, 645, 676, 769, 800, 26, 57, 88, 150, 181, 212, 274, 305, 336, 398, 429, 460, 522, 553, 584, 646, 677, 708, 770, 801, 832, 27, 58, 89, 120, 151, 182,
- 213, 244, 275, 306, 337, 368, 399, 430, 461, 492, 523, 554, 585, 616, 647, 678, 709, 740, 771, 802, 833, 864, 59, 90, 121, 183, 214, 245, 307, 338, 369, 431,
- 462, 493, 555, 586, 617, 679, 710, 741, 803, 834, 865, 91, 122, 215, 246, 339, 370, 463, 494, 587, 618, 711, 742, 835, 866, 123, 247, 371, 495, 619, 743, 867,
- 28, 152, 276, 400, 524, 648, 772, 896, 29, 60, 153, 184, 277, 308, 401, 432, 525, 556, 649, 680, 773, 804, 897, 928, 30, 61, 92, 154, 185, 216, 278, 309,
- 340, 402, 433, 464, 526, 557, 588, 650, 681, 712, 774, 805, 836, 898, 929, 960, 31, 62, 93, 124, 155, 186, 217, 248, 279, 310, 341, 372, 403, 434, 465, 496,
- 527, 558, 589, 620, 651, 682, 713, 744, 775, 806, 837, 868, 899, 930, 961, 992, 63, 94, 125, 187, 218, 249, 311, 342, 373, 435, 466, 497, 559, 590, 621, 683,
- 714, 745, 807, 838, 869, 931, 962, 993, 95, 126, 219, 250, 343, 374, 467, 498, 591, 622, 715, 746, 839, 870, 963, 994, 127, 251, 375, 499, 623, 747, 871, 995,
- 156, 280, 404, 528, 652, 776, 900, 157, 188, 281, 312, 405, 436, 529, 560, 653, 684, 777, 808, 901, 932, 158, 189, 220, 282, 313, 344, 406, 437, 468, 530, 561,
- 592, 654, 685, 716, 778, 809, 840, 902, 933, 964, 159, 190, 221, 252, 283, 314, 345, 376, 407, 438, 469, 500, 531, 562, 593, 624, 655, 686, 717, 748, 779, 810,
- 841, 872, 903, 934, 965, 996, 191, 222, 253, 315, 346, 377, 439, 470, 501, 563, 594, 625, 687, 718, 749, 811, 842, 873, 935, 966, 997, 223, 254, 347, 378, 471,
- 502, 595, 626, 719, 750, 843, 874, 967, 998, 255, 379, 503, 627, 751, 875, 999, 284, 408, 532, 656, 780, 904, 285, 316, 409, 440, 533, 564, 657, 688, 781, 812,
- 905, 936, 286, 317, 348, 410, 441, 472, 534, 565, 596, 658, 689, 720, 782, 813, 844, 906, 937, 968, 287, 318, 349, 380, 411, 442, 473, 504, 535, 566, 597, 628,
- 659, 690, 721, 752, 783, 814, 845, 876, 907, 938, 969, 1000, 319, 350, 381, 443, 474, 505, 567, 598, 629, 691, 722, 753, 815, 846, 877, 939, 970, 1001, 351, 382,
- 475, 506, 599, 630, 723, 754, 847, 878, 971, 1002, 383, 507, 631, 755, 879, 1003, 412, 536, 660, 784, 908, 413, 444, 537, 568, 661, 692, 785, 816, 909, 940, 414,
- 445, 476, 538, 569, 600, 662, 693, 724, 786, 817, 848, 910, 941, 972, 415, 446, 477, 508, 539, 570, 601, 632, 663, 694, 725, 756, 787, 818, 849, 880, 911, 942,
- 973, 1004, 447, 478, 509, 571, 602, 633, 695, 726, 757, 819, 850, 881, 943, 974, 1005, 479, 510, 603, 634, 727, 758, 851, 882, 975, 1006, 511, 635, 759, 883, 1007,
- 540, 664, 788, 912, 541, 572, 665, 696, 789, 820, 913, 944, 542, 573, 604, 666, 697, 728, 790, 821, 852, 914, 945, 976, 543, 574, 605, 636, 667, 698, 729, 760,
- 791, 822, 853, 884, 915, 946, 977, 1008, 575, 606, 637, 699, 730, 761, 823, 854, 885, 947, 978, 1009, 607, 638, 731, 762, 855, 886, 979, 1010, 639, 763, 887, 1011,
- 668, 792, 916, 669, 700, 793, 824, 917, 948, 670, 701, 732, 794, 825, 856, 918, 949, 980, 671, 702, 733, 764, 795, 826, 857, 888, 919, 950, 981, 1012, 703, 734,
- 765, 827, 858, 889, 951, 982, 1013, 735, 766, 859, 890, 983, 1014, 767, 891, 1015, 796, 920, 797, 828, 921, 952, 798, 829, 860, 922, 953, 984, 799, 830, 861, 892,
- 923, 954, 985, 1016, 831, 862, 893, 955, 986, 1017, 863, 894, 987, 1018, 895, 1019, 924, 925, 956, 926, 957, 988, 927, 958, 989, 1020, 959, 990, 1021, 991, 1022, 1023,
-};
-
-static const int16_t * const vp9_scans[5][4] = {
- {
- vp9_default_scan_4x4, vp9_col_scan_4x4,
- vp9_row_scan_4x4, vp9_default_scan_4x4
- }, {
- vp9_default_scan_8x8, vp9_col_scan_8x8,
- vp9_row_scan_8x8, vp9_default_scan_8x8
- }, {
- vp9_default_scan_16x16, vp9_col_scan_16x16,
- vp9_row_scan_16x16, vp9_default_scan_16x16
- }, {
- vp9_default_scan_32x32, vp9_default_scan_32x32,
- vp9_default_scan_32x32, vp9_default_scan_32x32
- }, { // lossless
- vp9_default_scan_4x4, vp9_default_scan_4x4,
- vp9_default_scan_4x4, vp9_default_scan_4x4
- }
-};
-
-static const int16_t vp9_default_scan_4x4_nb[16][2] = {
- { 0, 0 }, { 0, 0 }, { 4, 1 }, { 1, 1 },
- { 4, 4 }, { 2, 2 }, { 5, 2 }, { 8, 8 },
- { 8, 5 }, { 6, 3 }, { 9, 6 }, { 12, 9 },
- { 10, 7 }, { 13, 10 }, { 14, 11 }, { 0, 0 },
-};
-
-static const int16_t vp9_col_scan_4x4_nb[16][2] = {
- { 0, 0 }, { 1, 1 }, { 0, 0 }, { 2, 2 },
- { 4, 4 }, { 5, 5 }, { 4, 4 }, { 6, 6 },
- { 8, 8 }, { 9, 9 }, { 8, 8 }, { 12, 12 },
- { 10, 10 }, { 13, 13 }, { 14, 14 }, { 0, 0 },
-};
-
-static const int16_t vp9_row_scan_4x4_nb[16][2] = {
- { 0, 0 }, { 0, 0 }, { 4, 4 }, { 1, 1 },
- { 8, 8 }, { 5, 5 }, { 1, 1 }, { 2, 2 },
- { 9, 9 }, { 2, 2 }, { 6, 6 }, { 3, 3 },
- { 10, 10 }, { 7, 7 }, { 11, 11 }, { 0, 0 },
-};
-
-static const int16_t vp9_default_scan_8x8_nb[64][2] = {
- { 0, 0 }, { 0, 0 }, { 1, 1 }, { 8, 1 },
- { 8, 8 }, { 9, 2 }, { 2, 2 }, { 16, 9 },
- { 16, 16 }, { 17, 10 }, { 10, 3 }, { 3, 3 },
- { 24, 17 }, { 24, 24 }, { 18, 11 }, { 11, 4 },
- { 25, 18 }, { 4, 4 }, { 32, 25 }, { 19, 12 },
- { 26, 19 }, { 32, 32 }, { 12, 5 }, { 33, 26 },
- { 5, 5 }, { 40, 33 }, { 27, 20 }, { 20, 13 },
- { 34, 27 }, { 41, 34 }, { 40, 40 }, { 13, 6 },
- { 6, 6 }, { 35, 28 }, { 28, 21 }, { 42, 35 },
- { 48, 48 }, { 48, 41 }, { 21, 14 }, { 14, 7 },
- { 36, 29 }, { 49, 42 }, { 43, 36 }, { 56, 49 },
- { 29, 22 }, { 22, 15 }, { 50, 43 }, { 44, 37 },
- { 57, 50 }, { 37, 30 }, { 30, 23 }, { 51, 44 },
- { 58, 51 }, { 38, 31 }, { 45, 38 }, { 52, 45 },
- { 59, 52 }, { 46, 39 }, { 53, 46 }, { 60, 53 },
- { 54, 47 }, { 61, 54 }, { 62, 55 }, { 0, 0 },
-};
-
-static const int16_t vp9_col_scan_8x8_nb[64][2] = {
- { 0, 0 }, { 1, 1 }, { 0, 0 }, { 2, 2 },
- { 8, 8 }, { 3, 3 }, { 9, 9 }, { 8, 8 },
- { 4, 4 }, { 10, 10 }, { 16, 16 }, { 11, 11 },
- { 17, 17 }, { 5, 5 }, { 16, 16 }, { 18, 18 },
- { 12, 12 }, { 24, 24 }, { 6, 6 }, { 25, 25 },
- { 19, 19 }, { 24, 24 }, { 13, 13 }, { 26, 26 },
- { 20, 20 }, { 32, 32 }, { 27, 27 }, { 33, 33 },
- { 14, 14 }, { 21, 21 }, { 34, 34 }, { 32, 32 },
- { 28, 28 }, { 40, 40 }, { 35, 35 }, { 22, 22 },
- { 29, 29 }, { 41, 41 }, { 36, 36 }, { 40, 40 },
- { 42, 42 }, { 30, 30 }, { 43, 43 }, { 48, 48 },
- { 37, 37 }, { 49, 49 }, { 48, 48 }, { 44, 44 },
- { 38, 38 }, { 50, 50 }, { 56, 56 }, { 51, 51 },
- { 45, 45 }, { 57, 57 }, { 52, 52 }, { 58, 58 },
- { 46, 46 }, { 59, 59 }, { 53, 53 }, { 60, 60 },
- { 54, 54 }, { 61, 61 }, { 62, 62 }, { 0, 0 },
-};
-
-static const int16_t vp9_row_scan_8x8_nb[64][2] = {
- { 0, 0 }, { 8, 8 }, { 0, 0 }, { 1, 1 },
- { 16, 16 }, { 1, 1 }, { 9, 9 }, { 24, 24 },
- { 2, 2 }, { 17, 17 }, { 2, 2 }, { 32, 32 },
- { 10, 10 }, { 3, 3 }, { 25, 25 }, { 18, 18 },
- { 11, 11 }, { 3, 3 }, { 40, 40 }, { 33, 33 },
- { 26, 26 }, { 4, 4 }, { 19, 19 }, { 48, 48 },
- { 12, 12 }, { 4, 4 }, { 34, 34 }, { 27, 27 },
- { 5, 5 }, { 41, 41 }, { 20, 20 }, { 5, 5 },
- { 13, 13 }, { 35, 35 }, { 28, 28 }, { 6, 6 },
- { 42, 42 }, { 21, 21 }, { 49, 49 }, { 6, 6 },
- { 36, 36 }, { 14, 14 }, { 29, 29 }, { 43, 43 },
- { 7, 7 }, { 50, 50 }, { 22, 22 }, { 15, 15 },
- { 37, 37 }, { 44, 44 }, { 30, 30 }, { 51, 51 },
- { 23, 23 }, { 38, 38 }, { 45, 45 }, { 31, 31 },
- { 52, 52 }, { 39, 39 }, { 53, 53 }, { 46, 46 },
- { 54, 54 }, { 47, 47 }, { 55, 55 }, { 0, 0 },
-};
-
-static const int16_t vp9_default_scan_16x16_nb[256][2] = {
- { 0, 0 }, { 0, 0 }, { 1, 1 }, { 16, 1 },
- { 16, 16 }, { 2, 2 }, { 17, 2 }, { 32, 17 },
- { 32, 32 }, { 3, 3 }, { 33, 18 }, { 18, 3 },
- { 48, 33 }, { 19, 4 }, { 4, 4 }, { 34, 19 },
- { 48, 48 }, { 49, 34 }, { 35, 20 }, { 64, 49 },
- { 20, 5 }, { 5, 5 }, { 50, 35 }, { 64, 64 },
- { 65, 50 }, { 36, 21 }, { 21, 6 }, { 51, 36 },
- { 6, 6 }, { 80, 65 }, { 66, 51 }, { 37, 22 },
- { 81, 66 }, { 52, 37 }, { 22, 7 }, { 80, 80 },
- { 67, 52 }, { 7, 7 }, { 82, 67 }, { 96, 81 },
- { 53, 38 }, { 38, 23 }, { 68, 53 }, { 96, 96 },
- { 23, 8 }, { 97, 82 }, { 83, 68 }, { 69, 54 },
- { 54, 39 }, { 8, 8 }, { 39, 24 }, { 84, 69 },
- { 98, 83 }, { 112, 97 }, { 112, 112 }, { 24, 9 },
- { 113, 98 }, { 99, 84 }, { 70, 55 }, { 85, 70 },
- { 55, 40 }, { 9, 9 }, { 40, 25 }, { 114, 99 },
- { 100, 85 }, { 128, 113 }, { 115, 100 }, { 71, 56 },
- { 86, 71 }, { 25, 10 }, { 129, 114 }, { 128, 128 },
- { 101, 86 }, { 56, 41 }, { 10, 10 }, { 41, 26 },
- { 116, 101 }, { 130, 115 }, { 144, 129 }, { 87, 72 },
- { 102, 87 }, { 26, 11 }, { 72, 57 }, { 131, 116 },
- { 117, 102 }, { 145, 130 }, { 57, 42 }, { 144, 144 },
- { 11, 11 }, { 42, 27 }, { 132, 117 }, { 146, 131 },
- { 103, 88 }, { 88, 73 }, { 118, 103 }, { 160, 145 },
- { 73, 58 }, { 147, 132 }, { 133, 118 }, { 27, 12 },
- { 161, 146 }, { 58, 43 }, { 12, 12 }, { 160, 160 },
- { 119, 104 }, { 148, 133 }, { 89, 74 }, { 134, 119 },
- { 104, 89 }, { 162, 147 }, { 43, 28 }, { 74, 59 },
- { 176, 161 }, { 163, 148 }, { 28, 13 }, { 149, 134 },
- { 120, 105 }, { 135, 120 }, { 177, 162 }, { 164, 149 },
- { 13, 13 }, { 105, 90 }, { 59, 44 }, { 90, 75 },
- { 150, 135 }, { 44, 29 }, { 178, 163 }, { 176, 176 },
- { 136, 121 }, { 165, 150 }, { 121, 106 }, { 75, 60 },
- { 179, 164 }, { 151, 136 }, { 29, 14 }, { 60, 45 },
- { 14, 14 }, { 106, 91 }, { 166, 151 }, { 180, 165 },
- { 192, 177 }, { 91, 76 }, { 192, 192 }, { 45, 30 },
- { 137, 122 }, { 122, 107 }, { 152, 137 }, { 193, 178 },
- { 76, 61 }, { 167, 152 }, { 181, 166 }, { 30, 15 },
- { 194, 179 }, { 208, 193 }, { 182, 167 }, { 107, 92 },
- { 138, 123 }, { 61, 46 }, { 153, 138 }, { 46, 31 },
- { 195, 180 }, { 92, 77 }, { 168, 153 }, { 209, 194 },
- { 196, 181 }, { 208, 208 }, { 123, 108 }, { 183, 168 },
- { 210, 195 }, { 77, 62 }, { 108, 93 }, { 169, 154 },
- { 154, 139 }, { 62, 47 }, { 197, 182 }, { 211, 196 },
- { 184, 169 }, { 224, 209 }, { 224, 224 }, { 139, 124 },
- { 93, 78 }, { 198, 183 }, { 124, 109 }, { 78, 63 },
- { 212, 197 }, { 225, 210 }, { 170, 155 }, { 185, 170 },
- { 155, 140 }, { 213, 198 }, { 199, 184 }, { 109, 94 },
- { 226, 211 }, { 140, 125 }, { 94, 79 }, { 240, 225 },
- { 214, 199 }, { 227, 212 }, { 200, 185 }, { 125, 110 },
- { 241, 226 }, { 186, 171 }, { 171, 156 }, { 156, 141 },
- { 228, 213 }, { 110, 95 }, { 215, 200 }, { 242, 227 },
- { 141, 126 }, { 201, 186 }, { 229, 214 }, { 126, 111 },
- { 216, 201 }, { 243, 228 }, { 172, 157 }, { 187, 172 },
- { 230, 215 }, { 157, 142 }, { 202, 187 }, { 142, 127 },
- { 244, 229 }, { 217, 202 }, { 231, 216 }, { 188, 173 },
- { 245, 230 }, { 158, 143 }, { 173, 158 }, { 232, 217 },
- { 246, 231 }, { 218, 203 }, { 203, 188 }, { 174, 159 },
- { 189, 174 }, { 247, 232 }, { 233, 218 }, { 204, 189 },
- { 219, 204 }, { 248, 233 }, { 190, 175 }, { 234, 219 },
- { 220, 205 }, { 249, 234 }, { 205, 190 }, { 221, 206 },
- { 250, 235 }, { 235, 220 }, { 206, 191 }, { 236, 221 },
- { 222, 207 }, { 251, 236 }, { 237, 222 }, { 252, 237 },
- { 238, 223 }, { 253, 238 }, { 254, 239 }, { 0, 0 },
-};
-
-static const int16_t vp9_col_scan_16x16_nb[256][2] = {
- { 0, 0 }, { 1, 1 }, { 2, 2 }, { 0, 0 },
- { 3, 3 }, { 16, 16 }, { 4, 4 }, { 17, 17 },
- { 5, 5 }, { 18, 18 }, { 16, 16 }, { 19, 19 },
- { 6, 6 }, { 32, 32 }, { 20, 20 }, { 33, 33 },
- { 7, 7 }, { 34, 34 }, { 21, 21 }, { 32, 32 },
- { 35, 35 }, { 8, 8 }, { 48, 48 }, { 22, 22 },
- { 49, 49 }, { 36, 36 }, { 9, 9 }, { 37, 37 },
- { 50, 50 }, { 23, 23 }, { 48, 48 }, { 51, 51 },
- { 10, 10 }, { 64, 64 }, { 38, 38 }, { 24, 24 },
- { 52, 52 }, { 65, 65 }, { 53, 53 }, { 39, 39 },
- { 66, 66 }, { 11, 11 }, { 64, 64 }, { 25, 25 },
- { 67, 67 }, { 54, 54 }, { 80, 80 }, { 40, 40 },
- { 68, 68 }, { 12, 12 }, { 26, 26 }, { 81, 81 },
- { 55, 55 }, { 69, 69 }, { 82, 82 }, { 41, 41 },
- { 13, 13 }, { 83, 83 }, { 80, 80 }, { 70, 70 },
- { 27, 27 }, { 56, 56 }, { 84, 84 }, { 96, 96 },
- { 14, 14 }, { 71, 71 }, { 97, 97 }, { 42, 42 },
- { 85, 85 }, { 57, 57 }, { 98, 98 }, { 28, 28 },
- { 86, 86 }, { 99, 99 }, { 96, 96 }, { 72, 72 },
- { 43, 43 }, { 100, 100 }, { 58, 58 }, { 29, 29 },
- { 112, 112 }, { 87, 87 }, { 113, 113 }, { 73, 73 },
- { 112, 112 }, { 101, 101 }, { 44, 44 }, { 30, 30 },
- { 114, 114 }, { 59, 59 }, { 102, 102 }, { 88, 88 },
- { 115, 115 }, { 74, 74 }, { 128, 128 }, { 116, 116 },
- { 45, 45 }, { 103, 103 }, { 89, 89 }, { 60, 60 },
- { 129, 129 }, { 117, 117 }, { 130, 130 }, { 131, 131 },
- { 104, 104 }, { 75, 75 }, { 46, 46 }, { 118, 118 },
- { 128, 128 }, { 90, 90 }, { 61, 61 }, { 132, 132 },
- { 105, 105 }, { 144, 144 }, { 119, 119 }, { 145, 145 },
- { 133, 133 }, { 76, 76 }, { 146, 146 }, { 120, 120 },
- { 91, 91 }, { 134, 134 }, { 147, 147 }, { 62, 62 },
- { 106, 106 }, { 135, 135 }, { 121, 121 }, { 92, 92 },
- { 148, 148 }, { 144, 144 }, { 77, 77 }, { 149, 149 },
- { 136, 136 }, { 107, 107 }, { 160, 160 }, { 161, 161 },
- { 150, 150 }, { 122, 122 }, { 78, 78 }, { 137, 137 },
- { 162, 162 }, { 151, 151 }, { 93, 93 }, { 163, 163 },
- { 108, 108 }, { 164, 164 }, { 152, 152 }, { 123, 123 },
- { 138, 138 }, { 160, 160 }, { 165, 165 }, { 94, 94 },
- { 176, 176 }, { 166, 166 }, { 109, 109 }, { 153, 153 },
- { 177, 177 }, { 124, 124 }, { 178, 178 }, { 139, 139 },
- { 167, 167 }, { 154, 154 }, { 110, 110 }, { 179, 179 },
- { 176, 176 }, { 180, 180 }, { 168, 168 }, { 140, 140 },
- { 125, 125 }, { 181, 181 }, { 192, 192 }, { 193, 193 },
- { 155, 155 }, { 182, 182 }, { 169, 169 }, { 194, 194 },
- { 126, 126 }, { 141, 141 }, { 195, 195 }, { 183, 183 },
- { 192, 192 }, { 196, 196 }, { 156, 156 }, { 170, 170 },
- { 142, 142 }, { 184, 184 }, { 197, 197 }, { 208, 208 },
- { 198, 198 }, { 209, 209 }, { 171, 171 }, { 157, 157 },
- { 185, 185 }, { 210, 210 }, { 208, 208 }, { 211, 211 },
- { 199, 199 }, { 224, 224 }, { 158, 158 }, { 212, 212 },
- { 224, 224 }, { 186, 186 }, { 200, 200 }, { 172, 172 },
- { 225, 225 }, { 213, 213 }, { 214, 214 }, { 226, 226 },
- { 201, 201 }, { 227, 227 }, { 187, 187 }, { 240, 240 },
- { 215, 215 }, { 173, 173 }, { 228, 228 }, { 241, 241 },
- { 202, 202 }, { 242, 242 }, { 216, 216 }, { 229, 229 },
- { 174, 174 }, { 188, 188 }, { 243, 243 }, { 230, 230 },
- { 203, 203 }, { 217, 217 }, { 231, 231 }, { 244, 244 },
- { 218, 218 }, { 245, 245 }, { 189, 189 }, { 232, 232 },
- { 204, 204 }, { 190, 190 }, { 246, 246 }, { 233, 233 },
- { 247, 247 }, { 219, 219 }, { 205, 205 }, { 248, 248 },
- { 234, 234 }, { 220, 220 }, { 206, 206 }, { 249, 249 },
- { 235, 235 }, { 221, 221 }, { 250, 250 }, { 222, 222 },
- { 236, 236 }, { 237, 237 }, { 251, 251 }, { 238, 238 },
- { 252, 252 }, { 253, 253 }, { 254, 254 }, { 0, 0 },
-};
-
-static const int16_t vp9_row_scan_16x16_nb[256][2] = {
- { 0, 0 }, { 16, 16 }, { 0, 0 }, { 32, 32 },
- { 1, 1 }, { 48, 48 }, { 17, 17 }, { 1, 1 },
- { 64, 64 }, { 2, 2 }, { 33, 33 }, { 80, 80 },
- { 18, 18 }, { 2, 2 }, { 49, 49 }, { 3, 3 },
- { 96, 96 }, { 34, 34 }, { 65, 65 }, { 19, 19 },
- { 3, 3 }, { 112, 112 }, { 50, 50 }, { 4, 4 },
- { 81, 81 }, { 35, 35 }, { 66, 66 }, { 4, 4 },
- { 128, 128 }, { 20, 20 }, { 51, 51 }, { 97, 97 },
- { 82, 82 }, { 5, 5 }, { 36, 36 }, { 144, 144 },
- { 67, 67 }, { 113, 113 }, { 21, 21 }, { 52, 52 },
- { 5, 5 }, { 98, 98 }, { 160, 160 }, { 83, 83 },
- { 37, 37 }, { 6, 6 }, { 68, 68 }, { 129, 129 },
- { 22, 22 }, { 53, 53 }, { 114, 114 }, { 6, 6 },
- { 99, 99 }, { 176, 176 }, { 84, 84 }, { 38, 38 },
- { 7, 7 }, { 69, 69 }, { 145, 145 }, { 130, 130 },
- { 115, 115 }, { 23, 23 }, { 54, 54 }, { 192, 192 },
- { 100, 100 }, { 7, 7 }, { 85, 85 }, { 161, 161 },
- { 39, 39 }, { 70, 70 }, { 8, 8 }, { 146, 146 },
- { 131, 131 }, { 116, 116 }, { 55, 55 }, { 208, 208 },
- { 101, 101 }, { 24, 24 }, { 86, 86 }, { 8, 8 },
- { 132, 132 }, { 40, 40 }, { 71, 71 }, { 177, 177 },
- { 147, 147 }, { 224, 224 }, { 117, 117 }, { 162, 162 },
- { 9, 9 }, { 102, 102 }, { 56, 56 }, { 25, 25 },
- { 87, 87 }, { 148, 148 }, { 9, 9 }, { 133, 133 },
- { 72, 72 }, { 118, 118 }, { 193, 193 }, { 163, 163 },
- { 41, 41 }, { 103, 103 }, { 178, 178 }, { 10, 10 },
- { 57, 57 }, { 149, 149 }, { 134, 134 }, { 88, 88 },
- { 26, 26 }, { 119, 119 }, { 10, 10 }, { 164, 164 },
- { 104, 104 }, { 73, 73 }, { 209, 209 }, { 179, 179 },
- { 42, 42 }, { 11, 11 }, { 194, 194 }, { 135, 135 },
- { 165, 165 }, { 150, 150 }, { 58, 58 }, { 27, 27 },
- { 89, 89 }, { 11, 11 }, { 120, 120 }, { 74, 74 },
- { 43, 43 }, { 225, 225 }, { 105, 105 }, { 12, 12 },
- { 180, 180 }, { 151, 151 }, { 195, 195 }, { 136, 136 },
- { 28, 28 }, { 166, 166 }, { 121, 121 }, { 59, 59 },
- { 12, 12 }, { 210, 210 }, { 90, 90 }, { 106, 106 },
- { 44, 44 }, { 181, 181 }, { 75, 75 }, { 152, 152 },
- { 13, 13 }, { 167, 167 }, { 137, 137 }, { 13, 13 },
- { 60, 60 }, { 196, 196 }, { 122, 122 }, { 29, 29 },
- { 91, 91 }, { 14, 14 }, { 182, 182 }, { 76, 76 },
- { 211, 211 }, { 153, 153 }, { 14, 14 }, { 107, 107 },
- { 138, 138 }, { 45, 45 }, { 226, 226 }, { 168, 168 },
- { 197, 197 }, { 123, 123 }, { 30, 30 }, { 61, 61 },
- { 15, 15 }, { 92, 92 }, { 154, 154 }, { 183, 183 },
- { 169, 169 }, { 108, 108 }, { 212, 212 }, { 77, 77 },
- { 139, 139 }, { 198, 198 }, { 46, 46 }, { 124, 124 },
- { 227, 227 }, { 62, 62 }, { 31, 31 }, { 184, 184 },
- { 93, 93 }, { 170, 170 }, { 155, 155 }, { 185, 185 },
- { 78, 78 }, { 47, 47 }, { 199, 199 }, { 213, 213 },
- { 140, 140 }, { 63, 63 }, { 109, 109 }, { 125, 125 },
- { 94, 94 }, { 200, 200 }, { 171, 171 }, { 156, 156 },
- { 228, 228 }, { 186, 186 }, { 214, 214 }, { 201, 201 },
- { 79, 79 }, { 141, 141 }, { 110, 110 }, { 229, 229 },
- { 95, 95 }, { 126, 126 }, { 215, 215 }, { 172, 172 },
- { 111, 111 }, { 142, 142 }, { 202, 202 }, { 157, 157 },
- { 216, 216 }, { 230, 230 }, { 217, 217 }, { 187, 187 },
- { 127, 127 }, { 231, 231 }, { 158, 158 }, { 173, 173 },
- { 143, 143 }, { 203, 203 }, { 188, 188 }, { 232, 232 },
- { 218, 218 }, { 233, 233 }, { 159, 159 }, { 174, 174 },
- { 204, 204 }, { 189, 189 }, { 234, 234 }, { 219, 219 },
- { 175, 175 }, { 205, 205 }, { 235, 235 }, { 220, 220 },
- { 190, 190 }, { 236, 236 }, { 206, 206 }, { 191, 191 },
- { 221, 221 }, { 207, 207 }, { 237, 237 }, { 222, 222 },
- { 238, 238 }, { 223, 223 }, { 239, 239 }, { 0, 0 },
-};
-
-static const int16_t vp9_default_scan_32x32_nb[1024][2] = {
- { 0, 0 }, { 0, 0 }, { 1, 1 }, { 32, 1 },
- { 32, 32 }, { 2, 2 }, { 33, 2 }, { 64, 33 },
- { 3, 3 }, { 64, 64 }, { 34, 3 }, { 65, 34 },
- { 4, 4 }, { 35, 4 }, { 96, 65 }, { 66, 35 },
- { 96, 96 }, { 97, 66 }, { 67, 36 }, { 36, 5 },
- { 5, 5 }, { 128, 97 }, { 98, 67 }, { 6, 6 },
- { 128, 128 }, { 68, 37 }, { 37, 6 }, { 129, 98 },
- { 99, 68 }, { 160, 129 }, { 130, 99 }, { 38, 7 },
- { 69, 38 }, { 7, 7 }, { 100, 69 }, { 161, 130 },
- { 131, 100 }, { 160, 160 }, { 70, 39 }, { 39, 8 },
- { 8, 8 }, { 101, 70 }, { 162, 131 }, { 132, 101 },
- { 192, 161 }, { 71, 40 }, { 192, 192 }, { 102, 71 },
- { 40, 9 }, { 163, 132 }, { 9, 9 }, { 193, 162 },
- { 133, 102 }, { 164, 133 }, { 72, 41 }, { 103, 72 },
- { 134, 103 }, { 224, 193 }, { 41, 10 }, { 194, 163 },
- { 10, 10 }, { 224, 224 }, { 165, 134 }, { 225, 194 },
- { 195, 164 }, { 73, 42 }, { 104, 73 }, { 135, 104 },
- { 42, 11 }, { 11, 11 }, { 166, 135 }, { 196, 165 },
- { 226, 195 }, { 256, 225 }, { 74, 43 }, { 105, 74 },
- { 136, 105 }, { 227, 196 }, { 43, 12 }, { 197, 166 },
- { 167, 136 }, { 257, 226 }, { 256, 256 }, { 12, 12 },
- { 228, 197 }, { 75, 44 }, { 106, 75 }, { 198, 167 },
- { 137, 106 }, { 258, 227 }, { 168, 137 }, { 288, 257 },
- { 44, 13 }, { 229, 198 }, { 259, 228 }, { 199, 168 },
- { 107, 76 }, { 13, 13 }, { 169, 138 }, { 138, 107 },
- { 288, 288 }, { 289, 258 }, { 76, 45 }, { 230, 199 },
- { 260, 229 }, { 45, 14 }, { 200, 169 }, { 139, 108 },
- { 290, 259 }, { 108, 77 }, { 231, 200 }, { 320, 289 },
- { 261, 230 }, { 170, 139 }, { 77, 46 }, { 291, 260 },
- { 14, 14 }, { 321, 290 }, { 201, 170 }, { 262, 231 },
- { 320, 320 }, { 171, 140 }, { 292, 261 }, { 232, 201 },
- { 140, 109 }, { 322, 291 }, { 109, 78 }, { 46, 15 },
- { 202, 171 }, { 263, 232 }, { 233, 202 }, { 293, 262 },
- { 352, 321 }, { 323, 292 }, { 15, 15 }, { 78, 47 },
- { 203, 172 }, { 264, 233 }, { 294, 263 }, { 324, 293 },
- { 172, 141 }, { 353, 322 }, { 141, 110 }, { 234, 203 },
- { 352, 352 }, { 47, 16 }, { 295, 264 }, { 110, 79 },
- { 265, 234 }, { 354, 323 }, { 325, 294 }, { 79, 48 },
- { 16, 16 }, { 204, 173 }, { 235, 204 }, { 173, 142 },
- { 355, 324 }, { 384, 353 }, { 326, 295 }, { 142, 111 },
- { 296, 265 }, { 266, 235 }, { 356, 325 }, { 385, 354 },
- { 111, 80 }, { 48, 17 }, { 327, 296 }, { 297, 266 },
- { 205, 174 }, { 384, 384 }, { 236, 205 }, { 357, 326 },
- { 386, 355 }, { 80, 49 }, { 174, 143 }, { 17, 17 },
- { 328, 297 }, { 358, 327 }, { 387, 356 }, { 298, 267 },
- { 329, 298 }, { 388, 357 }, { 112, 81 }, { 416, 385 },
- { 237, 206 }, { 359, 328 }, { 49, 18 }, { 206, 175 },
- { 417, 386 }, { 389, 358 }, { 330, 299 }, { 18, 18 },
- { 416, 416 }, { 360, 329 }, { 81, 50 }, { 418, 387 },
- { 390, 359 }, { 238, 207 }, { 50, 19 }, { 361, 330 },
- { 419, 388 }, { 113, 82 }, { 448, 417 }, { 448, 448 },
- { 420, 389 }, { 82, 51 }, { 362, 331 }, { 449, 418 },
- { 421, 390 }, { 480, 480 }, { 450, 419 }, { 422, 391 },
- { 114, 83 }, { 451, 420 }, { 480, 449 }, { 452, 421 },
- { 481, 450 }, { 453, 422 }, { 512, 512 }, { 482, 451 },
- { 454, 423 }, { 512, 481 }, { 483, 452 }, { 513, 482 },
- { 484, 453 }, { 514, 483 }, { 485, 454 }, { 544, 513 },
- { 544, 544 }, { 486, 455 }, { 545, 514 }, { 546, 515 },
- { 576, 576 }, { 576, 545 }, { 577, 546 }, { 578, 547 },
- { 608, 577 }, { 609, 578 }, { 610, 579 }, { 19, 19 },
- { 143, 112 }, { 267, 236 }, { 391, 360 }, { 515, 484 },
- { 608, 608 }, { 20, 20 }, { 51, 20 }, { 144, 113 },
- { 175, 144 }, { 268, 237 }, { 299, 268 }, { 392, 361 },
- { 423, 392 }, { 516, 485 }, { 547, 516 }, { 640, 609 },
- { 640, 640 }, { 21, 21 }, { 52, 21 }, { 83, 52 },
- { 145, 114 }, { 176, 145 }, { 207, 176 }, { 269, 238 },
- { 300, 269 }, { 331, 300 }, { 393, 362 }, { 424, 393 },
- { 455, 424 }, { 517, 486 }, { 548, 517 }, { 579, 548 },
- { 641, 610 }, { 672, 641 }, { 672, 672 }, { 22, 22 },
- { 53, 22 }, { 84, 53 }, { 115, 84 }, { 146, 115 },
- { 177, 146 }, { 208, 177 }, { 239, 208 }, { 270, 239 },
- { 301, 270 }, { 332, 301 }, { 363, 332 }, { 394, 363 },
- { 425, 394 }, { 456, 425 }, { 487, 456 }, { 518, 487 },
- { 549, 518 }, { 580, 549 }, { 611, 580 }, { 642, 611 },
- { 673, 642 }, { 704, 673 }, { 704, 704 }, { 54, 23 },
- { 85, 54 }, { 116, 85 }, { 178, 147 }, { 209, 178 },
- { 240, 209 }, { 302, 271 }, { 333, 302 }, { 364, 333 },
- { 426, 395 }, { 457, 426 }, { 488, 457 }, { 550, 519 },
- { 581, 550 }, { 612, 581 }, { 674, 643 }, { 705, 674 },
- { 736, 705 }, { 86, 55 }, { 117, 86 }, { 210, 179 },
- { 241, 210 }, { 334, 303 }, { 365, 334 }, { 458, 427 },
- { 489, 458 }, { 582, 551 }, { 613, 582 }, { 706, 675 },
- { 737, 706 }, { 118, 87 }, { 242, 211 }, { 366, 335 },
- { 490, 459 }, { 614, 583 }, { 738, 707 }, { 23, 23 },
- { 147, 116 }, { 271, 240 }, { 395, 364 }, { 519, 488 },
- { 643, 612 }, { 736, 736 }, { 24, 24 }, { 55, 24 },
- { 148, 117 }, { 179, 148 }, { 272, 241 }, { 303, 272 },
- { 396, 365 }, { 427, 396 }, { 520, 489 }, { 551, 520 },
- { 644, 613 }, { 675, 644 }, { 768, 737 }, { 768, 768 },
- { 25, 25 }, { 56, 25 }, { 87, 56 }, { 149, 118 },
- { 180, 149 }, { 211, 180 }, { 273, 242 }, { 304, 273 },
- { 335, 304 }, { 397, 366 }, { 428, 397 }, { 459, 428 },
- { 521, 490 }, { 552, 521 }, { 583, 552 }, { 645, 614 },
- { 676, 645 }, { 707, 676 }, { 769, 738 }, { 800, 769 },
- { 800, 800 }, { 26, 26 }, { 57, 26 }, { 88, 57 },
- { 119, 88 }, { 150, 119 }, { 181, 150 }, { 212, 181 },
- { 243, 212 }, { 274, 243 }, { 305, 274 }, { 336, 305 },
- { 367, 336 }, { 398, 367 }, { 429, 398 }, { 460, 429 },
- { 491, 460 }, { 522, 491 }, { 553, 522 }, { 584, 553 },
- { 615, 584 }, { 646, 615 }, { 677, 646 }, { 708, 677 },
- { 739, 708 }, { 770, 739 }, { 801, 770 }, { 832, 801 },
- { 832, 832 }, { 58, 27 }, { 89, 58 }, { 120, 89 },
- { 182, 151 }, { 213, 182 }, { 244, 213 }, { 306, 275 },
- { 337, 306 }, { 368, 337 }, { 430, 399 }, { 461, 430 },
- { 492, 461 }, { 554, 523 }, { 585, 554 }, { 616, 585 },
- { 678, 647 }, { 709, 678 }, { 740, 709 }, { 802, 771 },
- { 833, 802 }, { 864, 833 }, { 90, 59 }, { 121, 90 },
- { 214, 183 }, { 245, 214 }, { 338, 307 }, { 369, 338 },
- { 462, 431 }, { 493, 462 }, { 586, 555 }, { 617, 586 },
- { 710, 679 }, { 741, 710 }, { 834, 803 }, { 865, 834 },
- { 122, 91 }, { 246, 215 }, { 370, 339 }, { 494, 463 },
- { 618, 587 }, { 742, 711 }, { 866, 835 }, { 27, 27 },
- { 151, 120 }, { 275, 244 }, { 399, 368 }, { 523, 492 },
- { 647, 616 }, { 771, 740 }, { 864, 864 }, { 28, 28 },
- { 59, 28 }, { 152, 121 }, { 183, 152 }, { 276, 245 },
- { 307, 276 }, { 400, 369 }, { 431, 400 }, { 524, 493 },
- { 555, 524 }, { 648, 617 }, { 679, 648 }, { 772, 741 },
- { 803, 772 }, { 896, 865 }, { 896, 896 }, { 29, 29 },
- { 60, 29 }, { 91, 60 }, { 153, 122 }, { 184, 153 },
- { 215, 184 }, { 277, 246 }, { 308, 277 }, { 339, 308 },
- { 401, 370 }, { 432, 401 }, { 463, 432 }, { 525, 494 },
- { 556, 525 }, { 587, 556 }, { 649, 618 }, { 680, 649 },
- { 711, 680 }, { 773, 742 }, { 804, 773 }, { 835, 804 },
- { 897, 866 }, { 928, 897 }, { 928, 928 }, { 30, 30 },
- { 61, 30 }, { 92, 61 }, { 123, 92 }, { 154, 123 },
- { 185, 154 }, { 216, 185 }, { 247, 216 }, { 278, 247 },
- { 309, 278 }, { 340, 309 }, { 371, 340 }, { 402, 371 },
- { 433, 402 }, { 464, 433 }, { 495, 464 }, { 526, 495 },
- { 557, 526 }, { 588, 557 }, { 619, 588 }, { 650, 619 },
- { 681, 650 }, { 712, 681 }, { 743, 712 }, { 774, 743 },
- { 805, 774 }, { 836, 805 }, { 867, 836 }, { 898, 867 },
- { 929, 898 }, { 960, 929 }, { 960, 960 }, { 62, 31 },
- { 93, 62 }, { 124, 93 }, { 186, 155 }, { 217, 186 },
- { 248, 217 }, { 310, 279 }, { 341, 310 }, { 372, 341 },
- { 434, 403 }, { 465, 434 }, { 496, 465 }, { 558, 527 },
- { 589, 558 }, { 620, 589 }, { 682, 651 }, { 713, 682 },
- { 744, 713 }, { 806, 775 }, { 837, 806 }, { 868, 837 },
- { 930, 899 }, { 961, 930 }, { 992, 961 }, { 94, 63 },
- { 125, 94 }, { 218, 187 }, { 249, 218 }, { 342, 311 },
- { 373, 342 }, { 466, 435 }, { 497, 466 }, { 590, 559 },
- { 621, 590 }, { 714, 683 }, { 745, 714 }, { 838, 807 },
- { 869, 838 }, { 962, 931 }, { 993, 962 }, { 126, 95 },
- { 250, 219 }, { 374, 343 }, { 498, 467 }, { 622, 591 },
- { 746, 715 }, { 870, 839 }, { 994, 963 }, { 155, 124 },
- { 279, 248 }, { 403, 372 }, { 527, 496 }, { 651, 620 },
- { 775, 744 }, { 899, 868 }, { 156, 125 }, { 187, 156 },
- { 280, 249 }, { 311, 280 }, { 404, 373 }, { 435, 404 },
- { 528, 497 }, { 559, 528 }, { 652, 621 }, { 683, 652 },
- { 776, 745 }, { 807, 776 }, { 900, 869 }, { 931, 900 },
- { 157, 126 }, { 188, 157 }, { 219, 188 }, { 281, 250 },
- { 312, 281 }, { 343, 312 }, { 405, 374 }, { 436, 405 },
- { 467, 436 }, { 529, 498 }, { 560, 529 }, { 591, 560 },
- { 653, 622 }, { 684, 653 }, { 715, 684 }, { 777, 746 },
- { 808, 777 }, { 839, 808 }, { 901, 870 }, { 932, 901 },
- { 963, 932 }, { 158, 127 }, { 189, 158 }, { 220, 189 },
- { 251, 220 }, { 282, 251 }, { 313, 282 }, { 344, 313 },
- { 375, 344 }, { 406, 375 }, { 437, 406 }, { 468, 437 },
- { 499, 468 }, { 530, 499 }, { 561, 530 }, { 592, 561 },
- { 623, 592 }, { 654, 623 }, { 685, 654 }, { 716, 685 },
- { 747, 716 }, { 778, 747 }, { 809, 778 }, { 840, 809 },
- { 871, 840 }, { 902, 871 }, { 933, 902 }, { 964, 933 },
- { 995, 964 }, { 190, 159 }, { 221, 190 }, { 252, 221 },
- { 314, 283 }, { 345, 314 }, { 376, 345 }, { 438, 407 },
- { 469, 438 }, { 500, 469 }, { 562, 531 }, { 593, 562 },
- { 624, 593 }, { 686, 655 }, { 717, 686 }, { 748, 717 },
- { 810, 779 }, { 841, 810 }, { 872, 841 }, { 934, 903 },
- { 965, 934 }, { 996, 965 }, { 222, 191 }, { 253, 222 },
- { 346, 315 }, { 377, 346 }, { 470, 439 }, { 501, 470 },
- { 594, 563 }, { 625, 594 }, { 718, 687 }, { 749, 718 },
- { 842, 811 }, { 873, 842 }, { 966, 935 }, { 997, 966 },
- { 254, 223 }, { 378, 347 }, { 502, 471 }, { 626, 595 },
- { 750, 719 }, { 874, 843 }, { 998, 967 }, { 283, 252 },
- { 407, 376 }, { 531, 500 }, { 655, 624 }, { 779, 748 },
- { 903, 872 }, { 284, 253 }, { 315, 284 }, { 408, 377 },
- { 439, 408 }, { 532, 501 }, { 563, 532 }, { 656, 625 },
- { 687, 656 }, { 780, 749 }, { 811, 780 }, { 904, 873 },
- { 935, 904 }, { 285, 254 }, { 316, 285 }, { 347, 316 },
- { 409, 378 }, { 440, 409 }, { 471, 440 }, { 533, 502 },
- { 564, 533 }, { 595, 564 }, { 657, 626 }, { 688, 657 },
- { 719, 688 }, { 781, 750 }, { 812, 781 }, { 843, 812 },
- { 905, 874 }, { 936, 905 }, { 967, 936 }, { 286, 255 },
- { 317, 286 }, { 348, 317 }, { 379, 348 }, { 410, 379 },
- { 441, 410 }, { 472, 441 }, { 503, 472 }, { 534, 503 },
- { 565, 534 }, { 596, 565 }, { 627, 596 }, { 658, 627 },
- { 689, 658 }, { 720, 689 }, { 751, 720 }, { 782, 751 },
- { 813, 782 }, { 844, 813 }, { 875, 844 }, { 906, 875 },
- { 937, 906 }, { 968, 937 }, { 999, 968 }, { 318, 287 },
- { 349, 318 }, { 380, 349 }, { 442, 411 }, { 473, 442 },
- { 504, 473 }, { 566, 535 }, { 597, 566 }, { 628, 597 },
- { 690, 659 }, { 721, 690 }, { 752, 721 }, { 814, 783 },
- { 845, 814 }, { 876, 845 }, { 938, 907 }, { 969, 938 },
- { 1000, 969 }, { 350, 319 }, { 381, 350 }, { 474, 443 },
- { 505, 474 }, { 598, 567 }, { 629, 598 }, { 722, 691 },
- { 753, 722 }, { 846, 815 }, { 877, 846 }, { 970, 939 },
- { 1001, 970 }, { 382, 351 }, { 506, 475 }, { 630, 599 },
- { 754, 723 }, { 878, 847 }, { 1002, 971 }, { 411, 380 },
- { 535, 504 }, { 659, 628 }, { 783, 752 }, { 907, 876 },
- { 412, 381 }, { 443, 412 }, { 536, 505 }, { 567, 536 },
- { 660, 629 }, { 691, 660 }, { 784, 753 }, { 815, 784 },
- { 908, 877 }, { 939, 908 }, { 413, 382 }, { 444, 413 },
- { 475, 444 }, { 537, 506 }, { 568, 537 }, { 599, 568 },
- { 661, 630 }, { 692, 661 }, { 723, 692 }, { 785, 754 },
- { 816, 785 }, { 847, 816 }, { 909, 878 }, { 940, 909 },
- { 971, 940 }, { 414, 383 }, { 445, 414 }, { 476, 445 },
- { 507, 476 }, { 538, 507 }, { 569, 538 }, { 600, 569 },
- { 631, 600 }, { 662, 631 }, { 693, 662 }, { 724, 693 },
- { 755, 724 }, { 786, 755 }, { 817, 786 }, { 848, 817 },
- { 879, 848 }, { 910, 879 }, { 941, 910 }, { 972, 941 },
- { 1003, 972 }, { 446, 415 }, { 477, 446 }, { 508, 477 },
- { 570, 539 }, { 601, 570 }, { 632, 601 }, { 694, 663 },
- { 725, 694 }, { 756, 725 }, { 818, 787 }, { 849, 818 },
- { 880, 849 }, { 942, 911 }, { 973, 942 }, { 1004, 973 },
- { 478, 447 }, { 509, 478 }, { 602, 571 }, { 633, 602 },
- { 726, 695 }, { 757, 726 }, { 850, 819 }, { 881, 850 },
- { 974, 943 }, { 1005, 974 }, { 510, 479 }, { 634, 603 },
- { 758, 727 }, { 882, 851 }, { 1006, 975 }, { 539, 508 },
- { 663, 632 }, { 787, 756 }, { 911, 880 }, { 540, 509 },
- { 571, 540 }, { 664, 633 }, { 695, 664 }, { 788, 757 },
- { 819, 788 }, { 912, 881 }, { 943, 912 }, { 541, 510 },
- { 572, 541 }, { 603, 572 }, { 665, 634 }, { 696, 665 },
- { 727, 696 }, { 789, 758 }, { 820, 789 }, { 851, 820 },
- { 913, 882 }, { 944, 913 }, { 975, 944 }, { 542, 511 },
- { 573, 542 }, { 604, 573 }, { 635, 604 }, { 666, 635 },
- { 697, 666 }, { 728, 697 }, { 759, 728 }, { 790, 759 },
- { 821, 790 }, { 852, 821 }, { 883, 852 }, { 914, 883 },
- { 945, 914 }, { 976, 945 }, { 1007, 976 }, { 574, 543 },
- { 605, 574 }, { 636, 605 }, { 698, 667 }, { 729, 698 },
- { 760, 729 }, { 822, 791 }, { 853, 822 }, { 884, 853 },
- { 946, 915 }, { 977, 946 }, { 1008, 977 }, { 606, 575 },
- { 637, 606 }, { 730, 699 }, { 761, 730 }, { 854, 823 },
- { 885, 854 }, { 978, 947 }, { 1009, 978 }, { 638, 607 },
- { 762, 731 }, { 886, 855 }, { 1010, 979 }, { 667, 636 },
- { 791, 760 }, { 915, 884 }, { 668, 637 }, { 699, 668 },
- { 792, 761 }, { 823, 792 }, { 916, 885 }, { 947, 916 },
- { 669, 638 }, { 700, 669 }, { 731, 700 }, { 793, 762 },
- { 824, 793 }, { 855, 824 }, { 917, 886 }, { 948, 917 },
- { 979, 948 }, { 670, 639 }, { 701, 670 }, { 732, 701 },
- { 763, 732 }, { 794, 763 }, { 825, 794 }, { 856, 825 },
- { 887, 856 }, { 918, 887 }, { 949, 918 }, { 980, 949 },
- { 1011, 980 }, { 702, 671 }, { 733, 702 }, { 764, 733 },
- { 826, 795 }, { 857, 826 }, { 888, 857 }, { 950, 919 },
- { 981, 950 }, { 1012, 981 }, { 734, 703 }, { 765, 734 },
- { 858, 827 }, { 889, 858 }, { 982, 951 }, { 1013, 982 },
- { 766, 735 }, { 890, 859 }, { 1014, 983 }, { 795, 764 },
- { 919, 888 }, { 796, 765 }, { 827, 796 }, { 920, 889 },
- { 951, 920 }, { 797, 766 }, { 828, 797 }, { 859, 828 },
- { 921, 890 }, { 952, 921 }, { 983, 952 }, { 798, 767 },
- { 829, 798 }, { 860, 829 }, { 891, 860 }, { 922, 891 },
- { 953, 922 }, { 984, 953 }, { 1015, 984 }, { 830, 799 },
- { 861, 830 }, { 892, 861 }, { 954, 923 }, { 985, 954 },
- { 1016, 985 }, { 862, 831 }, { 893, 862 }, { 986, 955 },
- { 1017, 986 }, { 894, 863 }, { 1018, 987 }, { 923, 892 },
- { 924, 893 }, { 955, 924 }, { 925, 894 }, { 956, 925 },
- { 987, 956 }, { 926, 895 }, { 957, 926 }, { 988, 957 },
- { 1019, 988 }, { 958, 927 }, { 989, 958 }, { 1020, 989 },
- { 990, 959 }, { 1021, 990 }, { 1022, 991 }, { 0, 0 },
-};
-
-static const int16_t (* const vp9_scans_nb[5][4])[2] = {
- {
- vp9_default_scan_4x4_nb, vp9_col_scan_4x4_nb,
- vp9_row_scan_4x4_nb, vp9_default_scan_4x4_nb
- }, {
- vp9_default_scan_8x8_nb, vp9_col_scan_8x8_nb,
- vp9_row_scan_8x8_nb, vp9_default_scan_8x8_nb
- }, {
- vp9_default_scan_16x16_nb, vp9_col_scan_16x16_nb,
- vp9_row_scan_16x16_nb, vp9_default_scan_16x16_nb
- }, {
- vp9_default_scan_32x32_nb, vp9_default_scan_32x32_nb,
- vp9_default_scan_32x32_nb, vp9_default_scan_32x32_nb
- }, { // lossless
- vp9_default_scan_4x4_nb, vp9_default_scan_4x4_nb,
- vp9_default_scan_4x4_nb, vp9_default_scan_4x4_nb
- }
-};
-
-static const uint8_t vp9_model_pareto8[256][8] = {
- { 6, 86, 128, 11, 87, 42, 91, 52 },
- { 3, 86, 128, 6, 86, 23, 88, 29 },
- { 6, 86, 128, 11, 87, 42, 91, 52 },
- { 9, 86, 129, 17, 88, 61, 94, 76 },
- { 12, 86, 129, 22, 88, 77, 97, 93 },
- { 15, 87, 129, 28, 89, 93, 100, 110 },
- { 17, 87, 129, 33, 90, 105, 103, 123 },
- { 20, 88, 130, 38, 91, 118, 106, 136 },
- { 23, 88, 130, 43, 91, 128, 108, 146 },
- { 26, 89, 131, 48, 92, 139, 111, 156 },
- { 28, 89, 131, 53, 93, 147, 114, 163 },
- { 31, 90, 131, 58, 94, 156, 117, 171 },
- { 34, 90, 131, 62, 94, 163, 119, 177 },
- { 37, 90, 132, 66, 95, 171, 122, 184 },
- { 39, 90, 132, 70, 96, 177, 124, 189 },
- { 42, 91, 132, 75, 97, 183, 127, 194 },
- { 44, 91, 132, 79, 97, 188, 129, 198 },
- { 47, 92, 133, 83, 98, 193, 132, 202 },
- { 49, 92, 133, 86, 99, 197, 134, 205 },
- { 52, 93, 133, 90, 100, 201, 137, 208 },
- { 54, 93, 133, 94, 100, 204, 139, 211 },
- { 57, 94, 134, 98, 101, 208, 142, 214 },
- { 59, 94, 134, 101, 102, 211, 144, 216 },
- { 62, 94, 135, 105, 103, 214, 146, 218 },
- { 64, 94, 135, 108, 103, 216, 148, 220 },
- { 66, 95, 135, 111, 104, 219, 151, 222 },
- { 68, 95, 135, 114, 105, 221, 153, 223 },
- { 71, 96, 136, 117, 106, 224, 155, 225 },
- { 73, 96, 136, 120, 106, 225, 157, 226 },
- { 76, 97, 136, 123, 107, 227, 159, 228 },
- { 78, 97, 136, 126, 108, 229, 160, 229 },
- { 80, 98, 137, 129, 109, 231, 162, 231 },
- { 82, 98, 137, 131, 109, 232, 164, 232 },
- { 84, 98, 138, 134, 110, 234, 166, 233 },
- { 86, 98, 138, 137, 111, 235, 168, 234 },
- { 89, 99, 138, 140, 112, 236, 170, 235 },
- { 91, 99, 138, 142, 112, 237, 171, 235 },
- { 93, 100, 139, 145, 113, 238, 173, 236 },
- { 95, 100, 139, 147, 114, 239, 174, 237 },
- { 97, 101, 140, 149, 115, 240, 176, 238 },
- { 99, 101, 140, 151, 115, 241, 177, 238 },
- { 101, 102, 140, 154, 116, 242, 179, 239 },
- { 103, 102, 140, 156, 117, 242, 180, 239 },
- { 105, 103, 141, 158, 118, 243, 182, 240 },
- { 107, 103, 141, 160, 118, 243, 183, 240 },
- { 109, 104, 141, 162, 119, 244, 185, 241 },
- { 111, 104, 141, 164, 119, 244, 186, 241 },
- { 113, 104, 142, 166, 120, 245, 187, 242 },
- { 114, 104, 142, 168, 121, 245, 188, 242 },
- { 116, 105, 143, 170, 122, 246, 190, 243 },
- { 118, 105, 143, 171, 122, 246, 191, 243 },
- { 120, 106, 143, 173, 123, 247, 192, 244 },
- { 121, 106, 143, 175, 124, 247, 193, 244 },
- { 123, 107, 144, 177, 125, 248, 195, 244 },
- { 125, 107, 144, 178, 125, 248, 196, 244 },
- { 127, 108, 145, 180, 126, 249, 197, 245 },
- { 128, 108, 145, 181, 127, 249, 198, 245 },
- { 130, 109, 145, 183, 128, 249, 199, 245 },
- { 132, 109, 145, 184, 128, 249, 200, 245 },
- { 134, 110, 146, 186, 129, 250, 201, 246 },
- { 135, 110, 146, 187, 130, 250, 202, 246 },
- { 137, 111, 147, 189, 131, 251, 203, 246 },
- { 138, 111, 147, 190, 131, 251, 204, 246 },
- { 140, 112, 147, 192, 132, 251, 205, 247 },
- { 141, 112, 147, 193, 132, 251, 206, 247 },
- { 143, 113, 148, 194, 133, 251, 207, 247 },
- { 144, 113, 148, 195, 134, 251, 207, 247 },
- { 146, 114, 149, 197, 135, 252, 208, 248 },
- { 147, 114, 149, 198, 135, 252, 209, 248 },
- { 149, 115, 149, 199, 136, 252, 210, 248 },
- { 150, 115, 149, 200, 137, 252, 210, 248 },
- { 152, 115, 150, 201, 138, 252, 211, 248 },
- { 153, 115, 150, 202, 138, 252, 212, 248 },
- { 155, 116, 151, 204, 139, 253, 213, 249 },
- { 156, 116, 151, 205, 139, 253, 213, 249 },
- { 158, 117, 151, 206, 140, 253, 214, 249 },
- { 159, 117, 151, 207, 141, 253, 215, 249 },
- { 161, 118, 152, 208, 142, 253, 216, 249 },
- { 162, 118, 152, 209, 142, 253, 216, 249 },
- { 163, 119, 153, 210, 143, 253, 217, 249 },
- { 164, 119, 153, 211, 143, 253, 217, 249 },
- { 166, 120, 153, 212, 144, 254, 218, 250 },
- { 167, 120, 153, 212, 145, 254, 219, 250 },
- { 168, 121, 154, 213, 146, 254, 220, 250 },
- { 169, 121, 154, 214, 146, 254, 220, 250 },
- { 171, 122, 155, 215, 147, 254, 221, 250 },
- { 172, 122, 155, 216, 147, 254, 221, 250 },
- { 173, 123, 155, 217, 148, 254, 222, 250 },
- { 174, 123, 155, 217, 149, 254, 222, 250 },
- { 176, 124, 156, 218, 150, 254, 223, 250 },
- { 177, 124, 156, 219, 150, 254, 223, 250 },
- { 178, 125, 157, 220, 151, 254, 224, 251 },
- { 179, 125, 157, 220, 151, 254, 224, 251 },
- { 180, 126, 157, 221, 152, 254, 225, 251 },
- { 181, 126, 157, 221, 152, 254, 225, 251 },
- { 183, 127, 158, 222, 153, 254, 226, 251 },
- { 184, 127, 158, 223, 154, 254, 226, 251 },
- { 185, 128, 159, 224, 155, 255, 227, 251 },
- { 186, 128, 159, 224, 155, 255, 227, 251 },
- { 187, 129, 160, 225, 156, 255, 228, 251 },
- { 188, 130, 160, 225, 156, 255, 228, 251 },
- { 189, 131, 160, 226, 157, 255, 228, 251 },
- { 190, 131, 160, 226, 158, 255, 228, 251 },
- { 191, 132, 161, 227, 159, 255, 229, 251 },
- { 192, 132, 161, 227, 159, 255, 229, 251 },
- { 193, 133, 162, 228, 160, 255, 230, 252 },
- { 194, 133, 162, 229, 160, 255, 230, 252 },
- { 195, 134, 163, 230, 161, 255, 231, 252 },
- { 196, 134, 163, 230, 161, 255, 231, 252 },
- { 197, 135, 163, 231, 162, 255, 231, 252 },
- { 198, 135, 163, 231, 162, 255, 231, 252 },
- { 199, 136, 164, 232, 163, 255, 232, 252 },
- { 200, 136, 164, 232, 164, 255, 232, 252 },
- { 201, 137, 165, 233, 165, 255, 233, 252 },
- { 201, 137, 165, 233, 165, 255, 233, 252 },
- { 202, 138, 166, 233, 166, 255, 233, 252 },
- { 203, 138, 166, 233, 166, 255, 233, 252 },
- { 204, 139, 166, 234, 167, 255, 234, 252 },
- { 205, 139, 166, 234, 167, 255, 234, 252 },
- { 206, 140, 167, 235, 168, 255, 235, 252 },
- { 206, 140, 167, 235, 168, 255, 235, 252 },
- { 207, 141, 168, 236, 169, 255, 235, 252 },
- { 208, 141, 168, 236, 170, 255, 235, 252 },
- { 209, 142, 169, 237, 171, 255, 236, 252 },
- { 209, 143, 169, 237, 171, 255, 236, 252 },
- { 210, 144, 169, 237, 172, 255, 236, 252 },
- { 211, 144, 169, 237, 172, 255, 236, 252 },
- { 212, 145, 170, 238, 173, 255, 237, 252 },
- { 213, 145, 170, 238, 173, 255, 237, 252 },
- { 214, 146, 171, 239, 174, 255, 237, 253 },
- { 214, 146, 171, 239, 174, 255, 237, 253 },
- { 215, 147, 172, 240, 175, 255, 238, 253 },
- { 215, 147, 172, 240, 175, 255, 238, 253 },
- { 216, 148, 173, 240, 176, 255, 238, 253 },
- { 217, 148, 173, 240, 176, 255, 238, 253 },
- { 218, 149, 173, 241, 177, 255, 239, 253 },
- { 218, 149, 173, 241, 178, 255, 239, 253 },
- { 219, 150, 174, 241, 179, 255, 239, 253 },
- { 219, 151, 174, 241, 179, 255, 239, 253 },
- { 220, 152, 175, 242, 180, 255, 240, 253 },
- { 221, 152, 175, 242, 180, 255, 240, 253 },
- { 222, 153, 176, 242, 181, 255, 240, 253 },
- { 222, 153, 176, 242, 181, 255, 240, 253 },
- { 223, 154, 177, 243, 182, 255, 240, 253 },
- { 223, 154, 177, 243, 182, 255, 240, 253 },
- { 224, 155, 178, 244, 183, 255, 241, 253 },
- { 224, 155, 178, 244, 183, 255, 241, 253 },
- { 225, 156, 178, 244, 184, 255, 241, 253 },
- { 225, 157, 178, 244, 184, 255, 241, 253 },
- { 226, 158, 179, 244, 185, 255, 242, 253 },
- { 227, 158, 179, 244, 185, 255, 242, 253 },
- { 228, 159, 180, 245, 186, 255, 242, 253 },
- { 228, 159, 180, 245, 186, 255, 242, 253 },
- { 229, 160, 181, 245, 187, 255, 242, 253 },
- { 229, 160, 181, 245, 187, 255, 242, 253 },
- { 230, 161, 182, 246, 188, 255, 243, 253 },
- { 230, 162, 182, 246, 188, 255, 243, 253 },
- { 231, 163, 183, 246, 189, 255, 243, 253 },
- { 231, 163, 183, 246, 189, 255, 243, 253 },
- { 232, 164, 184, 247, 190, 255, 243, 253 },
- { 232, 164, 184, 247, 190, 255, 243, 253 },
- { 233, 165, 185, 247, 191, 255, 244, 253 },
- { 233, 165, 185, 247, 191, 255, 244, 253 },
- { 234, 166, 185, 247, 192, 255, 244, 253 },
- { 234, 167, 185, 247, 192, 255, 244, 253 },
- { 235, 168, 186, 248, 193, 255, 244, 253 },
- { 235, 168, 186, 248, 193, 255, 244, 253 },
- { 236, 169, 187, 248, 194, 255, 244, 253 },
- { 236, 169, 187, 248, 194, 255, 244, 253 },
- { 236, 170, 188, 248, 195, 255, 245, 253 },
- { 236, 170, 188, 248, 195, 255, 245, 253 },
- { 237, 171, 189, 249, 196, 255, 245, 254 },
- { 237, 172, 189, 249, 196, 255, 245, 254 },
- { 238, 173, 190, 249, 197, 255, 245, 254 },
- { 238, 173, 190, 249, 197, 255, 245, 254 },
- { 239, 174, 191, 249, 198, 255, 245, 254 },
- { 239, 174, 191, 249, 198, 255, 245, 254 },
- { 240, 175, 192, 249, 199, 255, 246, 254 },
- { 240, 176, 192, 249, 199, 255, 246, 254 },
- { 240, 177, 193, 250, 200, 255, 246, 254 },
- { 240, 177, 193, 250, 200, 255, 246, 254 },
- { 241, 178, 194, 250, 201, 255, 246, 254 },
- { 241, 178, 194, 250, 201, 255, 246, 254 },
- { 242, 179, 195, 250, 202, 255, 246, 254 },
- { 242, 180, 195, 250, 202, 255, 246, 254 },
- { 242, 181, 196, 250, 203, 255, 247, 254 },
- { 242, 181, 196, 250, 203, 255, 247, 254 },
- { 243, 182, 197, 251, 204, 255, 247, 254 },
- { 243, 183, 197, 251, 204, 255, 247, 254 },
- { 244, 184, 198, 251, 205, 255, 247, 254 },
- { 244, 184, 198, 251, 205, 255, 247, 254 },
- { 244, 185, 199, 251, 206, 255, 247, 254 },
- { 244, 185, 199, 251, 206, 255, 247, 254 },
- { 245, 186, 200, 251, 207, 255, 247, 254 },
- { 245, 187, 200, 251, 207, 255, 247, 254 },
- { 246, 188, 201, 252, 207, 255, 248, 254 },
- { 246, 188, 201, 252, 207, 255, 248, 254 },
- { 246, 189, 202, 252, 208, 255, 248, 254 },
- { 246, 190, 202, 252, 208, 255, 248, 254 },
- { 247, 191, 203, 252, 209, 255, 248, 254 },
- { 247, 191, 203, 252, 209, 255, 248, 254 },
- { 247, 192, 204, 252, 210, 255, 248, 254 },
- { 247, 193, 204, 252, 210, 255, 248, 254 },
- { 248, 194, 205, 252, 211, 255, 248, 254 },
- { 248, 194, 205, 252, 211, 255, 248, 254 },
- { 248, 195, 206, 252, 212, 255, 249, 254 },
- { 248, 196, 206, 252, 212, 255, 249, 254 },
- { 249, 197, 207, 253, 213, 255, 249, 254 },
- { 249, 197, 207, 253, 213, 255, 249, 254 },
- { 249, 198, 208, 253, 214, 255, 249, 254 },
- { 249, 199, 209, 253, 214, 255, 249, 254 },
- { 250, 200, 210, 253, 215, 255, 249, 254 },
- { 250, 200, 210, 253, 215, 255, 249, 254 },
- { 250, 201, 211, 253, 215, 255, 249, 254 },
- { 250, 202, 211, 253, 215, 255, 249, 254 },
- { 250, 203, 212, 253, 216, 255, 249, 254 },
- { 250, 203, 212, 253, 216, 255, 249, 254 },
- { 251, 204, 213, 253, 217, 255, 250, 254 },
- { 251, 205, 213, 253, 217, 255, 250, 254 },
- { 251, 206, 214, 254, 218, 255, 250, 254 },
- { 251, 206, 215, 254, 218, 255, 250, 254 },
- { 252, 207, 216, 254, 219, 255, 250, 254 },
- { 252, 208, 216, 254, 219, 255, 250, 254 },
- { 252, 209, 217, 254, 220, 255, 250, 254 },
- { 252, 210, 217, 254, 220, 255, 250, 254 },
- { 252, 211, 218, 254, 221, 255, 250, 254 },
- { 252, 212, 218, 254, 221, 255, 250, 254 },
- { 253, 213, 219, 254, 222, 255, 250, 254 },
- { 253, 213, 220, 254, 222, 255, 250, 254 },
- { 253, 214, 221, 254, 223, 255, 250, 254 },
- { 253, 215, 221, 254, 223, 255, 250, 254 },
- { 253, 216, 222, 254, 224, 255, 251, 254 },
- { 253, 217, 223, 254, 224, 255, 251, 254 },
- { 253, 218, 224, 254, 225, 255, 251, 254 },
- { 253, 219, 224, 254, 225, 255, 251, 254 },
- { 254, 220, 225, 254, 225, 255, 251, 254 },
- { 254, 221, 226, 254, 225, 255, 251, 254 },
- { 254, 222, 227, 255, 226, 255, 251, 254 },
- { 254, 223, 227, 255, 226, 255, 251, 254 },
- { 254, 224, 228, 255, 227, 255, 251, 254 },
- { 254, 225, 229, 255, 227, 255, 251, 254 },
- { 254, 226, 230, 255, 228, 255, 251, 254 },
- { 254, 227, 230, 255, 229, 255, 251, 254 },
- { 255, 228, 231, 255, 230, 255, 251, 254 },
- { 255, 229, 232, 255, 230, 255, 251, 254 },
- { 255, 230, 233, 255, 231, 255, 252, 254 },
- { 255, 231, 234, 255, 231, 255, 252, 254 },
- { 255, 232, 235, 255, 232, 255, 252, 254 },
- { 255, 233, 236, 255, 232, 255, 252, 254 },
- { 255, 235, 237, 255, 233, 255, 252, 254 },
- { 255, 236, 238, 255, 234, 255, 252, 254 },
- { 255, 238, 240, 255, 235, 255, 252, 255 },
- { 255, 239, 241, 255, 235, 255, 252, 254 },
- { 255, 241, 243, 255, 236, 255, 252, 254 },
- { 255, 243, 245, 255, 237, 255, 252, 254 },
- { 255, 246, 247, 255, 239, 255, 253, 255 },
-};
-
-typedef struct {
- uint8_t y_mode[4][9];
- uint8_t uv_mode[10][9];
- uint8_t filter[4][2];
- uint8_t mv_mode[7][3];
- uint8_t intra[4];
- uint8_t comp[5];
- uint8_t single_ref[5][2];
- uint8_t comp_ref[5];
- uint8_t tx32p[2][3];
- uint8_t tx16p[2][2];
- uint8_t tx8p[2];
- uint8_t skip[3];
- uint8_t mv_joint[3];
- struct {
- uint8_t sign;
- uint8_t classes[10];
- uint8_t class0;
- uint8_t bits[10];
- uint8_t class0_fp[2][3];
- uint8_t fp[3];
- uint8_t class0_hp;
- uint8_t hp;
- } mv_comp[2];
- uint8_t partition[4][4][3];
-} prob_context;
-
-static const prob_context vp9_default_probs = {
- { /* y_mode */
- { 65, 32, 18, 144, 162, 194, 41, 51, 98 } /* bsize < 8x8 */,
- { 132, 68, 18, 165, 217, 196, 45, 40, 78 } /* bsize < 16x16 */,
- { 173, 80, 19, 176, 240, 193, 64, 35, 46 } /* bsize < 32x32 */,
- { 221, 135, 38, 194, 248, 121, 96, 85, 29 } /* bsize >= 32x32 */
- }, { /* uv_mode */
- { 48, 12, 154, 155, 139, 90, 34, 117, 119 } /* y = v */,
- { 67, 6, 25, 204, 243, 158, 13, 21, 96 } /* y = h */,
- { 120, 7, 76, 176, 208, 126, 28, 54, 103 } /* y = dc */,
- { 97, 5, 44, 131, 176, 139, 48, 68, 97 } /* y = d45 */,
- { 83, 5, 42, 156, 111, 152, 26, 49, 152 } /* y = d135 */,
- { 80, 5, 58, 178, 74, 83, 33, 62, 145 } /* y = d117 */,
- { 86, 5, 32, 154, 192, 168, 14, 22, 163 } /* y = d153 */,
- { 77, 7, 64, 116, 132, 122, 37, 126, 120 } /* y = d63 */,
- { 85, 5, 32, 156, 216, 148, 19, 29, 73 } /* y = d27 */,
- { 101, 21, 107, 181, 192, 103, 19, 67, 125 } /* y = tm */
- }, { /* filter */
- { 235, 162, },
- { 36, 255, },
- { 34, 3, },
- { 149, 144, },
- }, { /* mv_mode */
- { 2, 173, 34}, // 0 = both zero mv
- { 7, 145, 85}, // 1 = one zero mv + one a predicted mv
- { 7, 166, 63}, // 2 = two predicted mvs
- { 7, 94, 66}, // 3 = one predicted/zero and one new mv
- { 8, 64, 46}, // 4 = two new mvs
- { 17, 81, 31}, // 5 = one intra neighbour + x
- { 25, 29, 30}, // 6 = two intra neighbours
- }, { /* intra */
- 9, 102, 187, 225
- }, { /* comp */
- 239, 183, 119, 96, 41
- }, { /* single_ref */
- { 33, 16 },
- { 77, 74 },
- { 142, 142 },
- { 172, 170 },
- { 238, 247 }
- }, { /* comp_ref */
- 50, 126, 123, 221, 226
- }, { /* tx32p */
- { 3, 136, 37, },
- { 5, 52, 13, },
- }, { /* tx16p */
- { 20, 152, },
- { 15, 101, },
- }, { /* tx8p */
- 100, 66
- }, { /* skip */
- 192, 128, 64
- }, { /* mv_joint */
- 32, 64, 96
- }, {
- { /* mv vertical component */
- 128, /* sign */
- { 224, 144, 192, 168, 192, 176, 192, 198, 198, 245 }, /* class */
- 216, /* class0 */
- { 136, 140, 148, 160, 176, 192, 224, 234, 234, 240}, /* bits */
- { /* class0_fp */
- { 128, 128, 64 },
- { 96, 112, 64 }
- },
- { 64, 96, 64 }, /* fp */
- 160, /* class0_hp bit */
- 128, /* hp */
- }, { /* mv horizontal component */
- 128, /* sign */
- { 216, 128, 176, 160, 176, 176, 192, 198, 198, 208 }, /* class */
- 208, /* class0 */
- { 136, 140, 148, 160, 176, 192, 224, 234, 234, 240 }, /* bits */
- { /* class0_fp */
- { 128, 128, 64 },
- { 96, 112, 64 }
- },
- { 64, 96, 64 }, /* fp */
- 160, /* class0_hp bit */
- 128, /* hp */
- }
- }, { /* partition */
- { /* 64x64 -> 32x32 */
- { 222, 34, 30 } /* a/l both not split */,
- { 72, 16, 44 } /* a split, l not split */,
- { 58, 32, 12 } /* l split, a not split */,
- { 10, 7, 6 } /* a/l both split */,
- }, { /* 32x32 -> 16x16 */
- { 177, 58, 59 } /* a/l both not split */,
- { 68, 26, 63 } /* a split, l not split */,
- { 52, 79, 25 } /* l split, a not split */,
- { 17, 14, 12 } /* a/l both split */,
- }, { /* 16x16 -> 8x8 */
- { 174, 73, 87 } /* a/l both not split */,
- { 92, 41, 83 } /* a split, l not split */,
- { 82, 99, 50 } /* l split, a not split */,
- { 53, 39, 39 } /* a/l both split */,
- }, { /* 8x8 -> 4x4 */
- { 199, 122, 141 } /* a/l both not split */,
- { 147, 63, 159 } /* a split, l not split */,
- { 148, 133, 118 } /* l split, a not split */,
- { 121, 104, 114 } /* a/l both split */,
- }
- },
-};
-
-static const uint8_t vp9_default_coef_probs[4][2][2][6][6][3] = {
- { /* tx = 4x4 */
- { /* block Type 0 */
- { /* Intra */
- { /* Coeff Band 0 */
- { 195, 29, 183 },
- { 84, 49, 136 },
- { 8, 42, 71 }
- }, { /* Coeff Band 1 */
- { 31, 107, 169 },
- { 35, 99, 159 },
- { 17, 82, 140 },
- { 8, 66, 114 },
- { 2, 44, 76 },
- { 1, 19, 32 }
- }, { /* Coeff Band 2 */
- { 40, 132, 201 },
- { 29, 114, 187 },
- { 13, 91, 157 },
- { 7, 75, 127 },
- { 3, 58, 95 },
- { 1, 28, 47 }
- }, { /* Coeff Band 3 */
- { 69, 142, 221 },
- { 42, 122, 201 },
- { 15, 91, 159 },
- { 6, 67, 121 },
- { 1, 42, 77 },
- { 1, 17, 31 }
- }, { /* Coeff Band 4 */
- { 102, 148, 228 },
- { 67, 117, 204 },
- { 17, 82, 154 },
- { 6, 59, 114 },
- { 2, 39, 75 },
- { 1, 15, 29 }
- }, { /* Coeff Band 5 */
- { 156, 57, 233 },
- { 119, 57, 212 },
- { 58, 48, 163 },
- { 29, 40, 124 },
- { 12, 30, 81 },
- { 3, 12, 31 }
- }
- }, { /* Inter */
- { /* Coeff Band 0 */
- { 191, 107, 226 },
- { 124, 117, 204 },
- { 25, 99, 155 }
- }, { /* Coeff Band 1 */
- { 29, 148, 210 },
- { 37, 126, 194 },
- { 8, 93, 157 },
- { 2, 68, 118 },
- { 1, 39, 69 },
- { 1, 17, 33 }
- }, { /* Coeff Band 2 */
- { 41, 151, 213 },
- { 27, 123, 193 },
- { 3, 82, 144 },
- { 1, 58, 105 },
- { 1, 32, 60 },
- { 1, 13, 26 }
- }, { /* Coeff Band 3 */
- { 59, 159, 220 },
- { 23, 126, 198 },
- { 4, 88, 151 },
- { 1, 66, 114 },
- { 1, 38, 71 },
- { 1, 18, 34 }
- }, { /* Coeff Band 4 */
- { 114, 136, 232 },
- { 51, 114, 207 },
- { 11, 83, 155 },
- { 3, 56, 105 },
- { 1, 33, 65 },
- { 1, 17, 34 }
- }, { /* Coeff Band 5 */
- { 149, 65, 234 },
- { 121, 57, 215 },
- { 61, 49, 166 },
- { 28, 36, 114 },
- { 12, 25, 76 },
- { 3, 16, 42 }
- }
- }
- }, { /* block Type 1 */
- { /* Intra */
- { /* Coeff Band 0 */
- { 214, 49, 220 },
- { 132, 63, 188 },
- { 42, 65, 137 }
- }, { /* Coeff Band 1 */
- { 85, 137, 221 },
- { 104, 131, 216 },
- { 49, 111, 192 },
- { 21, 87, 155 },
- { 2, 49, 87 },
- { 1, 16, 28 }
- }, { /* Coeff Band 2 */
- { 89, 163, 230 },
- { 90, 137, 220 },
- { 29, 100, 183 },
- { 10, 70, 135 },
- { 2, 42, 81 },
- { 1, 17, 33 }
- }, { /* Coeff Band 3 */
- { 108, 167, 237 },
- { 55, 133, 222 },
- { 15, 97, 179 },
- { 4, 72, 135 },
- { 1, 45, 85 },
- { 1, 19, 38 }
- }, { /* Coeff Band 4 */
- { 124, 146, 240 },
- { 66, 124, 224 },
- { 17, 88, 175 },
- { 4, 58, 122 },
- { 1, 36, 75 },
- { 1, 18, 37 }
- }, { /* Coeff Band 5 */
- { 141, 79, 241 },
- { 126, 70, 227 },
- { 66, 58, 182 },
- { 30, 44, 136 },
- { 12, 34, 96 },
- { 2, 20, 47 }
- }
- }, { /* Inter */
- { /* Coeff Band 0 */
- { 229, 99, 249 },
- { 143, 111, 235 },
- { 46, 109, 192 }
- }, { /* Coeff Band 1 */
- { 82, 158, 236 },
- { 94, 146, 224 },
- { 25, 117, 191 },
- { 9, 87, 149 },
- { 3, 56, 99 },
- { 1, 33, 57 }
- }, { /* Coeff Band 2 */
- { 83, 167, 237 },
- { 68, 145, 222 },
- { 10, 103, 177 },
- { 2, 72, 131 },
- { 1, 41, 79 },
- { 1, 20, 39 }
- }, { /* Coeff Band 3 */
- { 99, 167, 239 },
- { 47, 141, 224 },
- { 10, 104, 178 },
- { 2, 73, 133 },
- { 1, 44, 85 },
- { 1, 22, 47 }
- }, { /* Coeff Band 4 */
- { 127, 145, 243 },
- { 71, 129, 228 },
- { 17, 93, 177 },
- { 3, 61, 124 },
- { 1, 41, 84 },
- { 1, 21, 52 }
- }, { /* Coeff Band 5 */
- { 157, 78, 244 },
- { 140, 72, 231 },
- { 69, 58, 184 },
- { 31, 44, 137 },
- { 14, 38, 105 },
- { 8, 23, 61 }
- }
- }
- }
- }, { /* tx = 8x8 */
- { /* block Type 0 */
- { /* Intra */
- { /* Coeff Band 0 */
- { 125, 34, 187 },
- { 52, 41, 133 },
- { 6, 31, 56 }
- }, { /* Coeff Band 1 */
- { 37, 109, 153 },
- { 51, 102, 147 },
- { 23, 87, 128 },
- { 8, 67, 101 },
- { 1, 41, 63 },
- { 1, 19, 29 }
- }, { /* Coeff Band 2 */
- { 31, 154, 185 },
- { 17, 127, 175 },
- { 6, 96, 145 },
- { 2, 73, 114 },
- { 1, 51, 82 },
- { 1, 28, 45 }
- }, { /* Coeff Band 3 */
- { 23, 163, 200 },
- { 10, 131, 185 },
- { 2, 93, 148 },
- { 1, 67, 111 },
- { 1, 41, 69 },
- { 1, 14, 24 }
- }, { /* Coeff Band 4 */
- { 29, 176, 217 },
- { 12, 145, 201 },
- { 3, 101, 156 },
- { 1, 69, 111 },
- { 1, 39, 63 },
- { 1, 14, 23 }
- }, { /* Coeff Band 5 */
- { 57, 192, 233 },
- { 25, 154, 215 },
- { 6, 109, 167 },
- { 3, 78, 118 },
- { 1, 48, 69 },
- { 1, 21, 29 }
- }
- }, { /* Inter */
- { /* Coeff Band 0 */
- { 202, 105, 245 },
- { 108, 106, 216 },
- { 18, 90, 144 }
- }, { /* Coeff Band 1 */
- { 33, 172, 219 },
- { 64, 149, 206 },
- { 14, 117, 177 },
- { 5, 90, 141 },
- { 2, 61, 95 },
- { 1, 37, 57 }
- }, { /* Coeff Band 2 */
- { 33, 179, 220 },
- { 11, 140, 198 },
- { 1, 89, 148 },
- { 1, 60, 104 },
- { 1, 33, 57 },
- { 1, 12, 21 }
- }, { /* Coeff Band 3 */
- { 30, 181, 221 },
- { 8, 141, 198 },
- { 1, 87, 145 },
- { 1, 58, 100 },
- { 1, 31, 55 },
- { 1, 12, 20 }
- }, { /* Coeff Band 4 */
- { 32, 186, 224 },
- { 7, 142, 198 },
- { 1, 86, 143 },
- { 1, 58, 100 },
- { 1, 31, 55 },
- { 1, 12, 22 }
- }, { /* Coeff Band 5 */
- { 57, 192, 227 },
- { 20, 143, 204 },
- { 3, 96, 154 },
- { 1, 68, 112 },
- { 1, 42, 69 },
- { 1, 19, 32 }
- }
- }
- }, { /* block Type 1 */
- { /* Intra */
- { /* Coeff Band 0 */
- { 212, 35, 215 },
- { 113, 47, 169 },
- { 29, 48, 105 }
- }, { /* Coeff Band 1 */
- { 74, 129, 203 },
- { 106, 120, 203 },
- { 49, 107, 178 },
- { 19, 84, 144 },
- { 4, 50, 84 },
- { 1, 15, 25 }
- }, { /* Coeff Band 2 */
- { 71, 172, 217 },
- { 44, 141, 209 },
- { 15, 102, 173 },
- { 6, 76, 133 },
- { 2, 51, 89 },
- { 1, 24, 42 }
- }, { /* Coeff Band 3 */
- { 64, 185, 231 },
- { 31, 148, 216 },
- { 8, 103, 175 },
- { 3, 74, 131 },
- { 1, 46, 81 },
- { 1, 18, 30 }
- }, { /* Coeff Band 4 */
- { 65, 196, 235 },
- { 25, 157, 221 },
- { 5, 105, 174 },
- { 1, 67, 120 },
- { 1, 38, 69 },
- { 1, 15, 30 }
- }, { /* Coeff Band 5 */
- { 65, 204, 238 },
- { 30, 156, 224 },
- { 7, 107, 177 },
- { 2, 70, 124 },
- { 1, 42, 73 },
- { 1, 18, 34 }
- }
- }, { /* Inter */
- { /* Coeff Band 0 */
- { 225, 86, 251 },
- { 144, 104, 235 },
- { 42, 99, 181 }
- }, { /* Coeff Band 1 */
- { 85, 175, 239 },
- { 112, 165, 229 },
- { 29, 136, 200 },
- { 12, 103, 162 },
- { 6, 77, 123 },
- { 2, 53, 84 }
- }, { /* Coeff Band 2 */
- { 75, 183, 239 },
- { 30, 155, 221 },
- { 3, 106, 171 },
- { 1, 74, 128 },
- { 1, 44, 76 },
- { 1, 17, 28 }
- }, { /* Coeff Band 3 */
- { 73, 185, 240 },
- { 27, 159, 222 },
- { 2, 107, 172 },
- { 1, 75, 127 },
- { 1, 42, 73 },
- { 1, 17, 29 }
- }, { /* Coeff Band 4 */
- { 62, 190, 238 },
- { 21, 159, 222 },
- { 2, 107, 172 },
- { 1, 72, 122 },
- { 1, 40, 71 },
- { 1, 18, 32 }
- }, { /* Coeff Band 5 */
- { 61, 199, 240 },
- { 27, 161, 226 },
- { 4, 113, 180 },
- { 1, 76, 129 },
- { 1, 46, 80 },
- { 1, 23, 41 }
- }
- }
- }
- }, { /* tx = 16x16 */
- { /* block Type 0 */
- { /* Intra */
- { /* Coeff Band 0 */
- { 7, 27, 153 },
- { 5, 30, 95 },
- { 1, 16, 30 }
- }, { /* Coeff Band 1 */
- { 50, 75, 127 },
- { 57, 75, 124 },
- { 27, 67, 108 },
- { 10, 54, 86 },
- { 1, 33, 52 },
- { 1, 12, 18 }
- }, { /* Coeff Band 2 */
- { 43, 125, 151 },
- { 26, 108, 148 },
- { 7, 83, 122 },
- { 2, 59, 89 },
- { 1, 38, 60 },
- { 1, 17, 27 }
- }, { /* Coeff Band 3 */
- { 23, 144, 163 },
- { 13, 112, 154 },
- { 2, 75, 117 },
- { 1, 50, 81 },
- { 1, 31, 51 },
- { 1, 14, 23 }
- }, { /* Coeff Band 4 */
- { 18, 162, 185 },
- { 6, 123, 171 },
- { 1, 78, 125 },
- { 1, 51, 86 },
- { 1, 31, 54 },
- { 1, 14, 23 }
- }, { /* Coeff Band 5 */
- { 15, 199, 227 },
- { 3, 150, 204 },
- { 1, 91, 146 },
- { 1, 55, 95 },
- { 1, 30, 53 },
- { 1, 11, 20 }
- }
- }, { /* Inter */
- { /* Coeff Band 0 */
- { 19, 55, 240 },
- { 19, 59, 196 },
- { 3, 52, 105 }
- }, { /* Coeff Band 1 */
- { 41, 166, 207 },
- { 104, 153, 199 },
- { 31, 123, 181 },
- { 14, 101, 152 },
- { 5, 72, 106 },
- { 1, 36, 52 }
- }, { /* Coeff Band 2 */
- { 35, 176, 211 },
- { 12, 131, 190 },
- { 2, 88, 144 },
- { 1, 60, 101 },
- { 1, 36, 60 },
- { 1, 16, 28 }
- }, { /* Coeff Band 3 */
- { 28, 183, 213 },
- { 8, 134, 191 },
- { 1, 86, 142 },
- { 1, 56, 96 },
- { 1, 30, 53 },
- { 1, 12, 20 }
- }, { /* Coeff Band 4 */
- { 20, 190, 215 },
- { 4, 135, 192 },
- { 1, 84, 139 },
- { 1, 53, 91 },
- { 1, 28, 49 },
- { 1, 11, 20 }
- }, { /* Coeff Band 5 */
- { 13, 196, 216 },
- { 2, 137, 192 },
- { 1, 86, 143 },
- { 1, 57, 99 },
- { 1, 32, 56 },
- { 1, 13, 24 }
- }
- }
- }, { /* block Type 1 */
- { /* Intra */
- { /* Coeff Band 0 */
- { 211, 29, 217 },
- { 96, 47, 156 },
- { 22, 43, 87 }
- }, { /* Coeff Band 1 */
- { 78, 120, 193 },
- { 111, 116, 186 },
- { 46, 102, 164 },
- { 15, 80, 128 },
- { 2, 49, 76 },
- { 1, 18, 28 }
- }, { /* Coeff Band 2 */
- { 71, 161, 203 },
- { 42, 132, 192 },
- { 10, 98, 150 },
- { 3, 69, 109 },
- { 1, 44, 70 },
- { 1, 18, 29 }
- }, { /* Coeff Band 3 */
- { 57, 186, 211 },
- { 30, 140, 196 },
- { 4, 93, 146 },
- { 1, 62, 102 },
- { 1, 38, 65 },
- { 1, 16, 27 }
- }, { /* Coeff Band 4 */
- { 47, 199, 217 },
- { 14, 145, 196 },
- { 1, 88, 142 },
- { 1, 57, 98 },
- { 1, 36, 62 },
- { 1, 15, 26 }
- }, { /* Coeff Band 5 */
- { 26, 219, 229 },
- { 5, 155, 207 },
- { 1, 94, 151 },
- { 1, 60, 104 },
- { 1, 36, 62 },
- { 1, 16, 28 }
- }
- }, { /* Inter */
- { /* Coeff Band 0 */
- { 233, 29, 248 },
- { 146, 47, 220 },
- { 43, 52, 140 }
- }, { /* Coeff Band 1 */
- { 100, 163, 232 },
- { 179, 161, 222 },
- { 63, 142, 204 },
- { 37, 113, 174 },
- { 26, 89, 137 },
- { 18, 68, 97 }
- }, { /* Coeff Band 2 */
- { 85, 181, 230 },
- { 32, 146, 209 },
- { 7, 100, 164 },
- { 3, 71, 121 },
- { 1, 45, 77 },
- { 1, 18, 30 }
- }, { /* Coeff Band 3 */
- { 65, 187, 230 },
- { 20, 148, 207 },
- { 2, 97, 159 },
- { 1, 68, 116 },
- { 1, 40, 70 },
- { 1, 14, 29 }
- }, { /* Coeff Band 4 */
- { 40, 194, 227 },
- { 8, 147, 204 },
- { 1, 94, 155 },
- { 1, 65, 112 },
- { 1, 39, 66 },
- { 1, 14, 26 }
- }, { /* Coeff Band 5 */
- { 16, 208, 228 },
- { 3, 151, 207 },
- { 1, 98, 160 },
- { 1, 67, 117 },
- { 1, 41, 74 },
- { 1, 17, 31 }
- }
- }
- }
- }, { /* tx = 32x32 */
- { /* block Type 0 */
- { /* Intra */
- { /* Coeff Band 0 */
- { 17, 38, 140 },
- { 7, 34, 80 },
- { 1, 17, 29 }
- }, { /* Coeff Band 1 */
- { 37, 75, 128 },
- { 41, 76, 128 },
- { 26, 66, 116 },
- { 12, 52, 94 },
- { 2, 32, 55 },
- { 1, 10, 16 }
- }, { /* Coeff Band 2 */
- { 50, 127, 154 },
- { 37, 109, 152 },
- { 16, 82, 121 },
- { 5, 59, 85 },
- { 1, 35, 54 },
- { 1, 13, 20 }
- }, { /* Coeff Band 3 */
- { 40, 142, 167 },
- { 17, 110, 157 },
- { 2, 71, 112 },
- { 1, 44, 72 },
- { 1, 27, 45 },
- { 1, 11, 17 }
- }, { /* Coeff Band 4 */
- { 30, 175, 188 },
- { 9, 124, 169 },
- { 1, 74, 116 },
- { 1, 48, 78 },
- { 1, 30, 49 },
- { 1, 11, 18 }
- }, { /* Coeff Band 5 */
- { 10, 222, 223 },
- { 2, 150, 194 },
- { 1, 83, 128 },
- { 1, 48, 79 },
- { 1, 27, 45 },
- { 1, 11, 17 }
- }
- }, { /* Inter */
- { /* Coeff Band 0 */
- { 36, 41, 235 },
- { 29, 36, 193 },
- { 10, 27, 111 }
- }, { /* Coeff Band 1 */
- { 85, 165, 222 },
- { 177, 162, 215 },
- { 110, 135, 195 },
- { 57, 113, 168 },
- { 23, 83, 120 },
- { 10, 49, 61 }
- }, { /* Coeff Band 2 */
- { 85, 190, 223 },
- { 36, 139, 200 },
- { 5, 90, 146 },
- { 1, 60, 103 },
- { 1, 38, 65 },
- { 1, 18, 30 }
- }, { /* Coeff Band 3 */
- { 72, 202, 223 },
- { 23, 141, 199 },
- { 2, 86, 140 },
- { 1, 56, 97 },
- { 1, 36, 61 },
- { 1, 16, 27 }
- }, { /* Coeff Band 4 */
- { 55, 218, 225 },
- { 13, 145, 200 },
- { 1, 86, 141 },
- { 1, 57, 99 },
- { 1, 35, 61 },
- { 1, 13, 22 }
- }, { /* Coeff Band 5 */
- { 15, 235, 212 },
- { 1, 132, 184 },
- { 1, 84, 139 },
- { 1, 57, 97 },
- { 1, 34, 56 },
- { 1, 14, 23 }
- }
- }
- }, { /* block Type 1 */
- { /* Intra */
- { /* Coeff Band 0 */
- { 181, 21, 201 },
- { 61, 37, 123 },
- { 10, 38, 71 }
- }, { /* Coeff Band 1 */
- { 47, 106, 172 },
- { 95, 104, 173 },
- { 42, 93, 159 },
- { 18, 77, 131 },
- { 4, 50, 81 },
- { 1, 17, 23 }
- }, { /* Coeff Band 2 */
- { 62, 147, 199 },
- { 44, 130, 189 },
- { 28, 102, 154 },
- { 18, 75, 115 },
- { 2, 44, 65 },
- { 1, 12, 19 }
- }, { /* Coeff Band 3 */
- { 55, 153, 210 },
- { 24, 130, 194 },
- { 3, 93, 146 },
- { 1, 61, 97 },
- { 1, 31, 50 },
- { 1, 10, 16 }
- }, { /* Coeff Band 4 */
- { 49, 186, 223 },
- { 17, 148, 204 },
- { 1, 96, 142 },
- { 1, 53, 83 },
- { 1, 26, 44 },
- { 1, 11, 17 }
- }, { /* Coeff Band 5 */
- { 13, 217, 212 },
- { 2, 136, 180 },
- { 1, 78, 124 },
- { 1, 50, 83 },
- { 1, 29, 49 },
- { 1, 14, 23 }
- }
- }, { /* Inter */
- { /* Coeff Band 0 */
- { 197, 13, 247 },
- { 82, 17, 222 },
- { 25, 17, 162 }
- }, { /* Coeff Band 1 */
- { 126, 186, 247 },
- { 234, 191, 243 },
- { 176, 177, 234 },
- { 104, 158, 220 },
- { 66, 128, 186 },
- { 55, 90, 137 }
- }, { /* Coeff Band 2 */
- { 111, 197, 242 },
- { 46, 158, 219 },
- { 9, 104, 171 },
- { 2, 65, 125 },
- { 1, 44, 80 },
- { 1, 17, 91 }
- }, { /* Coeff Band 3 */
- { 104, 208, 245 },
- { 39, 168, 224 },
- { 3, 109, 162 },
- { 1, 79, 124 },
- { 1, 50, 102 },
- { 1, 43, 102 }
- }, { /* Coeff Band 4 */
- { 84, 220, 246 },
- { 31, 177, 231 },
- { 2, 115, 180 },
- { 1, 79, 134 },
- { 1, 55, 77 },
- { 1, 60, 79 }
- }, { /* Coeff Band 5 */
- { 43, 243, 240 },
- { 8, 180, 217 },
- { 1, 115, 166 },
- { 1, 84, 121 },
- { 1, 51, 67 },
- { 1, 16, 6 }
- }
- }
- }
- }
-};
-
-enum MVJoint {
- MV_JOINT_ZERO,
- MV_JOINT_H,
- MV_JOINT_V,
- MV_JOINT_HV,
-};
-
-static const int8_t vp9_mv_joint_tree[3][2] = {
- { -MV_JOINT_ZERO, 1 }, // '0'
- { -MV_JOINT_H, 2 }, // '10'
- { -MV_JOINT_V, -MV_JOINT_HV }, // '11x'
-};
-
-static const int8_t vp9_mv_class_tree[10][2] = {
- { -0, 1 }, // '0'
- { -1, 2 }, // '10'
- { 3, 4 },
- { -2, -3 }, // '110x'
- { 5, 6 },
- { -4, -5 }, // '1110x'
- { -6, 7 }, // '11110'
- { 8, 9 },
- { -7, -8 }, // '111110x'
- { -9, -10 }, // '111111x'
-};
-
-static const int8_t vp9_mv_fp_tree[3][2] = {
- { -0, 1 }, // '0'
- { -1, 2 }, // '10'
- { -2, -3 }, // '11x'
-};
+#include "vp9dec.h"
+
+extern const uint8_t ff_vp9_bwh_tab[2][N_BS_SIZES][2];
+extern const int8_t ff_vp9_partition_tree[3][2];
+extern const uint8_t ff_vp9_default_kf_partition_probs[4][4][3];
+extern const int8_t ff_vp9_segmentation_tree[7][2];
+extern const int8_t ff_vp9_intramode_tree[9][2];
+extern const uint8_t ff_vp9_default_kf_ymode_probs[10][10][9];
+extern const uint8_t ff_vp9_default_kf_uvmode_probs[10][9];
+extern const int8_t ff_vp9_inter_mode_tree[3][2];
+extern const int8_t ff_vp9_filter_tree[2][2];
+extern const enum FilterMode ff_vp9_filter_lut[3];
+extern const int16_t ff_vp9_dc_qlookup[3][256];
+extern const int16_t ff_vp9_ac_qlookup[3][256];
+extern const enum TxfmType ff_vp9_intra_txfm_type[14];
+extern const int16_t ff_vp9_default_scan_4x4[16];
+extern const int16_t ff_vp9_col_scan_4x4[16];
+extern const int16_t ff_vp9_row_scan_4x4[16];
+extern const int16_t ff_vp9_default_scan_8x8[64];
+extern const int16_t ff_vp9_col_scan_8x8[64];
+extern const int16_t ff_vp9_row_scan_8x8[64];
+extern const int16_t ff_vp9_default_scan_16x16[256];
+extern const int16_t ff_vp9_col_scan_16x16[256];
+extern const int16_t ff_vp9_row_scan_16x16[256];
+extern const int16_t ff_vp9_default_scan_32x32[1024];
+extern const int16_t * const ff_vp9_scans[5][4];
+extern const int16_t ff_vp9_default_scan_4x4_nb[16][2];
+extern const int16_t ff_vp9_col_scan_4x4_nb[16][2];
+extern const int16_t ff_vp9_row_scan_4x4_nb[16][2];
+extern const int16_t ff_vp9_default_scan_8x8_nb[64][2];
+extern const int16_t ff_vp9_col_scan_8x8_nb[64][2];
+extern const int16_t ff_vp9_row_scan_8x8_nb[64][2];
+extern const int16_t ff_vp9_default_scan_16x16_nb[256][2];
+extern const int16_t ff_vp9_col_scan_16x16_nb[256][2];
+extern const int16_t ff_vp9_row_scan_16x16_nb[256][2];
+extern const int16_t ff_vp9_default_scan_32x32_nb[1024][2];
+extern const int16_t (* const ff_vp9_scans_nb[5][4])[2];
+extern const uint8_t ff_vp9_model_pareto8[256][8];
+extern const ProbContext ff_vp9_default_probs;
+extern const uint8_t ff_vp9_default_coef_probs[4][2][2][6][6][3];
+extern const int8_t ff_vp9_mv_joint_tree[3][2];
+extern const int8_t ff_vp9_mv_class_tree[10][2];
+extern const int8_t ff_vp9_mv_fp_tree[3][2];
#endif /* AVCODEC_VP9DATA_H */
diff --git a/media/ffvpx/libavcodec/vp9dec.h b/media/ffvpx/libavcodec/vp9dec.h
new file mode 100644
index 000000000..66573edc7
--- /dev/null
+++ b/media/ffvpx/libavcodec/vp9dec.h
@@ -0,0 +1,240 @@
+/*
+ * VP9 compatible video decoder
+ *
+ * Copyright (C) 2013 Ronald S. Bultje <rsbultje gmail com>
+ * Copyright (C) 2013 Clément Bœsch <u pkh me>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VP9DEC_H
+#define AVCODEC_VP9DEC_H
+
+#include <stddef.h>
+#include <stdint.h>
+#include <stdatomic.h>
+
+#include "libavutil/buffer.h"
+#include "libavutil/thread.h"
+#include "libavutil/internal.h"
+
+#include "vp9.h"
+#include "vp9dsp.h"
+#include "vp9shared.h"
+
+enum MVJoint {
+ MV_JOINT_ZERO,
+ MV_JOINT_H,
+ MV_JOINT_V,
+ MV_JOINT_HV,
+};
+
+typedef struct ProbContext {
+ uint8_t y_mode[4][9];
+ uint8_t uv_mode[10][9];
+ uint8_t filter[4][2];
+ uint8_t mv_mode[7][3];
+ uint8_t intra[4];
+ uint8_t comp[5];
+ uint8_t single_ref[5][2];
+ uint8_t comp_ref[5];
+ uint8_t tx32p[2][3];
+ uint8_t tx16p[2][2];
+ uint8_t tx8p[2];
+ uint8_t skip[3];
+ uint8_t mv_joint[3];
+ struct {
+ uint8_t sign;
+ uint8_t classes[10];
+ uint8_t class0;
+ uint8_t bits[10];
+ uint8_t class0_fp[2][3];
+ uint8_t fp[3];
+ uint8_t class0_hp;
+ uint8_t hp;
+ } mv_comp[2];
+ uint8_t partition[4][4][3];
+} ProbContext;
+
+typedef struct VP9Filter {
+ uint8_t level[8 * 8];
+ uint8_t /* bit=col */ mask[2 /* 0=y, 1=uv */][2 /* 0=col, 1=row */]
+ [8 /* rows */][4 /* 0=16, 1=8, 2=4, 3=inner4 */];
+} VP9Filter;
+
+typedef struct VP9Block {
+ uint8_t seg_id, intra, comp, ref[2], mode[4], uvmode, skip;
+ enum FilterMode filter;
+ VP56mv mv[4 /* b_idx */][2 /* ref */];
+ enum BlockSize bs;
+ enum TxfmMode tx, uvtx;
+ enum BlockLevel bl;
+ enum BlockPartition bp;
+} VP9Block;
+
+typedef struct VP9TileData VP9TileData;
+
+typedef struct VP9Context {
+ VP9SharedContext s;
+ VP9TileData *td;
+
+ VP9DSPContext dsp;
+ VideoDSPContext vdsp;
+ GetBitContext gb;
+ VP56RangeCoder c;
+ int pass, active_tile_cols;
+
+#if HAVE_THREADS
+ pthread_mutex_t progress_mutex;
+ pthread_cond_t progress_cond;
+ atomic_int *entries;
+#endif
+
+ uint8_t ss_h, ss_v;
+ uint8_t last_bpp, bpp_index, bytesperpixel;
+ uint8_t last_keyframe;
+ // sb_cols/rows, rows/cols and last_fmt are used for allocating all internal
+ // arrays, and are thus per-thread. w/h and gf_fmt are synced between threads
+ // and are therefore per-stream. pix_fmt represents the value in the header
+ // of the currently processed frame.
+ int w, h;
+ enum AVPixelFormat pix_fmt, last_fmt, gf_fmt;
+ unsigned sb_cols, sb_rows, rows, cols;
+ ThreadFrame next_refs[8];
+
+ struct {
+ uint8_t lim_lut[64];
+ uint8_t mblim_lut[64];
+ } filter_lut;
+ struct {
+ ProbContext p;
+ uint8_t coef[4][2][2][6][6][3];
+ } prob_ctx[4];
+ struct {
+ ProbContext p;
+ uint8_t coef[4][2][2][6][6][11];
+ } prob;
+
+ // contextual (above) cache
+ uint8_t *above_partition_ctx;
+ uint8_t *above_mode_ctx;
+ // FIXME maybe merge some of the below in a flags field?
+ uint8_t *above_y_nnz_ctx;
+ uint8_t *above_uv_nnz_ctx[2];
+ uint8_t *above_skip_ctx; // 1bit
+ uint8_t *above_txfm_ctx; // 2bit
+ uint8_t *above_segpred_ctx; // 1bit
+ uint8_t *above_intra_ctx; // 1bit
+ uint8_t *above_comp_ctx; // 1bit
+ uint8_t *above_ref_ctx; // 2bit
+ uint8_t *above_filter_ctx;
+ VP56mv (*above_mv_ctx)[2];
+
+ // whole-frame cache
+ uint8_t *intra_pred_data[3];
+ VP9Filter *lflvl;
+
+ // block reconstruction intermediates
+ int block_alloc_using_2pass;
+ uint16_t mvscale[3][2];
+ uint8_t mvstep[3][2];
+} VP9Context;
+
+struct VP9TileData {
+ //VP9Context should be const, but because of the threading API(generates
+ //a lot of warnings) it's not.
+ VP9Context *s;
+ VP56RangeCoder *c_b;
+ VP56RangeCoder *c;
+ int row, row7, col, col7;
+ uint8_t *dst[3];
+ ptrdiff_t y_stride, uv_stride;
+ VP9Block *b_base, *b;
+ unsigned tile_col_start;
+
+ struct {
+ unsigned y_mode[4][10];
+ unsigned uv_mode[10][10];
+ unsigned filter[4][3];
+ unsigned mv_mode[7][4];
+ unsigned intra[4][2];
+ unsigned comp[5][2];
+ unsigned single_ref[5][2][2];
+ unsigned comp_ref[5][2];
+ unsigned tx32p[2][4];
+ unsigned tx16p[2][3];
+ unsigned tx8p[2][2];
+ unsigned skip[3][2];
+ unsigned mv_joint[4];
+ struct {
+ unsigned sign[2];
+ unsigned classes[11];
+ unsigned class0[2];
+ unsigned bits[10][2];
+ unsigned class0_fp[2][4];
+ unsigned fp[4];
+ unsigned class0_hp[2];
+ unsigned hp[2];
+ } mv_comp[2];
+ unsigned partition[4][4][4];
+ unsigned coef[4][2][2][6][6][3];
+ unsigned eob[4][2][2][6][6][2];
+ } counts;
+
+ // whole-frame cache
+ DECLARE_ALIGNED(32, uint8_t, edge_emu_buffer)[135 * 144 * 2];
+
+ // contextual (left) cache
+ DECLARE_ALIGNED(16, uint8_t, left_y_nnz_ctx)[16];
+ DECLARE_ALIGNED(16, uint8_t, left_mode_ctx)[16];
+ DECLARE_ALIGNED(16, VP56mv, left_mv_ctx)[16][2];
+ DECLARE_ALIGNED(16, uint8_t, left_uv_nnz_ctx)[2][16];
+ DECLARE_ALIGNED(8, uint8_t, left_partition_ctx)[8];
+ DECLARE_ALIGNED(8, uint8_t, left_skip_ctx)[8];
+ DECLARE_ALIGNED(8, uint8_t, left_txfm_ctx)[8];
+ DECLARE_ALIGNED(8, uint8_t, left_segpred_ctx)[8];
+ DECLARE_ALIGNED(8, uint8_t, left_intra_ctx)[8];
+ DECLARE_ALIGNED(8, uint8_t, left_comp_ctx)[8];
+ DECLARE_ALIGNED(8, uint8_t, left_ref_ctx)[8];
+ DECLARE_ALIGNED(8, uint8_t, left_filter_ctx)[8];
+ // block reconstruction intermediates
+ DECLARE_ALIGNED(32, uint8_t, tmp_y)[64 * 64 * 2];
+ DECLARE_ALIGNED(32, uint8_t, tmp_uv)[2][64 * 64 * 2];
+ struct { int x, y; } min_mv, max_mv;
+ int16_t *block_base, *block, *uvblock_base[2], *uvblock[2];
+ uint8_t *eob_base, *uveob_base[2], *eob, *uveob[2];
+};
+
+void ff_vp9_fill_mv(VP9TileData *td, VP56mv *mv, int mode, int sb);
+
+void ff_vp9_adapt_probs(VP9Context *s);
+
+void ff_vp9_decode_block(VP9TileData *td, int row, int col,
+ VP9Filter *lflvl, ptrdiff_t yoff, ptrdiff_t uvoff,
+ enum BlockLevel bl, enum BlockPartition bp);
+
+void ff_vp9_loopfilter_sb(AVCodecContext *avctx, VP9Filter *lflvl,
+ int row, int col, ptrdiff_t yoff, ptrdiff_t uvoff);
+
+void ff_vp9_intra_recon_8bpp(VP9TileData *td,
+ ptrdiff_t y_off, ptrdiff_t uv_off);
+void ff_vp9_intra_recon_16bpp(VP9TileData *td,
+ ptrdiff_t y_off, ptrdiff_t uv_off);
+void ff_vp9_inter_recon_8bpp(VP9TileData *td);
+void ff_vp9_inter_recon_16bpp(VP9TileData *td);
+
+#endif /* AVCODEC_VP9DEC_H */
diff --git a/media/ffvpx/libavcodec/vp9dsp.c b/media/ffvpx/libavcodec/vp9dsp.c
index 54e77e267..f6d73f73c 100644
--- a/media/ffvpx/libavcodec/vp9dsp.c
+++ b/media/ffvpx/libavcodec/vp9dsp.c
@@ -25,6 +25,62 @@
#include "libavutil/common.h"
#include "vp9dsp.h"
+const DECLARE_ALIGNED(16, int16_t, ff_vp9_subpel_filters)[3][16][8] = {
+ [FILTER_8TAP_REGULAR] = {
+ { 0, 0, 0, 128, 0, 0, 0, 0 },
+ { 0, 1, -5, 126, 8, -3, 1, 0 },
+ { -1, 3, -10, 122, 18, -6, 2, 0 },
+ { -1, 4, -13, 118, 27, -9, 3, -1 },
+ { -1, 4, -16, 112, 37, -11, 4, -1 },
+ { -1, 5, -18, 105, 48, -14, 4, -1 },
+ { -1, 5, -19, 97, 58, -16, 5, -1 },
+ { -1, 6, -19, 88, 68, -18, 5, -1 },
+ { -1, 6, -19, 78, 78, -19, 6, -1 },
+ { -1, 5, -18, 68, 88, -19, 6, -1 },
+ { -1, 5, -16, 58, 97, -19, 5, -1 },
+ { -1, 4, -14, 48, 105, -18, 5, -1 },
+ { -1, 4, -11, 37, 112, -16, 4, -1 },
+ { -1, 3, -9, 27, 118, -13, 4, -1 },
+ { 0, 2, -6, 18, 122, -10, 3, -1 },
+ { 0, 1, -3, 8, 126, -5, 1, 0 },
+ }, [FILTER_8TAP_SHARP] = {
+ { 0, 0, 0, 128, 0, 0, 0, 0 },
+ { -1, 3, -7, 127, 8, -3, 1, 0 },
+ { -2, 5, -13, 125, 17, -6, 3, -1 },
+ { -3, 7, -17, 121, 27, -10, 5, -2 },
+ { -4, 9, -20, 115, 37, -13, 6, -2 },
+ { -4, 10, -23, 108, 48, -16, 8, -3 },
+ { -4, 10, -24, 100, 59, -19, 9, -3 },
+ { -4, 11, -24, 90, 70, -21, 10, -4 },
+ { -4, 11, -23, 80, 80, -23, 11, -4 },
+ { -4, 10, -21, 70, 90, -24, 11, -4 },
+ { -3, 9, -19, 59, 100, -24, 10, -4 },
+ { -3, 8, -16, 48, 108, -23, 10, -4 },
+ { -2, 6, -13, 37, 115, -20, 9, -4 },
+ { -2, 5, -10, 27, 121, -17, 7, -3 },
+ { -1, 3, -6, 17, 125, -13, 5, -2 },
+ { 0, 1, -3, 8, 127, -7, 3, -1 },
+ }, [FILTER_8TAP_SMOOTH] = {
+ { 0, 0, 0, 128, 0, 0, 0, 0 },
+ { -3, -1, 32, 64, 38, 1, -3, 0 },
+ { -2, -2, 29, 63, 41, 2, -3, 0 },
+ { -2, -2, 26, 63, 43, 4, -4, 0 },
+ { -2, -3, 24, 62, 46, 5, -4, 0 },
+ { -2, -3, 21, 60, 49, 7, -4, 0 },
+ { -1, -4, 18, 59, 51, 9, -4, 0 },
+ { -1, -4, 16, 57, 53, 12, -4, -1 },
+ { -1, -4, 14, 55, 55, 14, -4, -1 },
+ { -1, -4, 12, 53, 57, 16, -4, -1 },
+ { 0, -4, 9, 51, 59, 18, -4, -1 },
+ { 0, -4, 7, 49, 60, 21, -3, -2 },
+ { 0, -4, 5, 46, 62, 24, -3, -2 },
+ { 0, -4, 4, 43, 63, 26, -2, -2 },
+ { 0, -3, 2, 41, 63, 29, -2, -2 },
+ { 0, -3, 1, 38, 64, 32, -1, -3 },
+ }
+};
+
+
av_cold void ff_vp9dsp_init(VP9DSPContext *dsp, int bpp, int bitexact)
{
if (bpp == 8) {
@@ -36,6 +92,8 @@ av_cold void ff_vp9dsp_init(VP9DSPContext *dsp, int bpp, int bitexact)
ff_vp9dsp_init_12(dsp);
}
+ if (ARCH_AARCH64) ff_vp9dsp_init_aarch64(dsp, bpp);
+ if (ARCH_ARM) ff_vp9dsp_init_arm(dsp, bpp);
if (ARCH_X86) ff_vp9dsp_init_x86(dsp, bpp, bitexact);
if (ARCH_MIPS) ff_vp9dsp_init_mips(dsp, bpp);
}
diff --git a/media/ffvpx/libavcodec/vp9dsp.h b/media/ffvpx/libavcodec/vp9dsp.h
index 733f5bfc4..e2256316a 100644
--- a/media/ffvpx/libavcodec/vp9dsp.h
+++ b/media/ffvpx/libavcodec/vp9dsp.h
@@ -27,7 +27,7 @@
#include <stddef.h>
#include <stdint.h>
-#include "vp9.h"
+#include "libavcodec/vp9.h"
typedef void (*vp9_mc_func)(uint8_t *dst, ptrdiff_t dst_stride,
const uint8_t *ref, ptrdiff_t ref_stride,
@@ -111,21 +111,25 @@ typedef struct VP9DSPContext {
*
* dst/stride are aligned by hsize
*/
- vp9_mc_func mc[5][4][2][2][2];
+ vp9_mc_func mc[5][N_FILTERS][2][2][2];
/*
* for scalable MC, first 3 dimensions identical to above, the other two
* don't exist since it changes per stepsize.
*/
- vp9_scaled_mc_func smc[5][4][2];
+ vp9_scaled_mc_func smc[5][N_FILTERS][2];
} VP9DSPContext;
+extern const int16_t ff_vp9_subpel_filters[3][16][8];
+
void ff_vp9dsp_init(VP9DSPContext *dsp, int bpp, int bitexact);
void ff_vp9dsp_init_8(VP9DSPContext *dsp);
void ff_vp9dsp_init_10(VP9DSPContext *dsp);
void ff_vp9dsp_init_12(VP9DSPContext *dsp);
+void ff_vp9dsp_init_aarch64(VP9DSPContext *dsp, int bpp);
+void ff_vp9dsp_init_arm(VP9DSPContext *dsp, int bpp);
void ff_vp9dsp_init_x86(VP9DSPContext *dsp, int bpp, int bitexact);
void ff_vp9dsp_init_mips(VP9DSPContext *dsp, int bpp);
diff --git a/media/ffvpx/libavcodec/vp9dsp_template.c b/media/ffvpx/libavcodec/vp9dsp_template.c
index 4d810fec3..bb54561a6 100644
--- a/media/ffvpx/libavcodec/vp9dsp_template.c
+++ b/media/ffvpx/libavcodec/vp9dsp_template.c
@@ -1991,61 +1991,6 @@ copy_avg_fn(4)
#endif /* BIT_DEPTH != 12 */
-static const int16_t vp9_subpel_filters[3][16][8] = {
- [FILTER_8TAP_REGULAR] = {
- { 0, 0, 0, 128, 0, 0, 0, 0 },
- { 0, 1, -5, 126, 8, -3, 1, 0 },
- { -1, 3, -10, 122, 18, -6, 2, 0 },
- { -1, 4, -13, 118, 27, -9, 3, -1 },
- { -1, 4, -16, 112, 37, -11, 4, -1 },
- { -1, 5, -18, 105, 48, -14, 4, -1 },
- { -1, 5, -19, 97, 58, -16, 5, -1 },
- { -1, 6, -19, 88, 68, -18, 5, -1 },
- { -1, 6, -19, 78, 78, -19, 6, -1 },
- { -1, 5, -18, 68, 88, -19, 6, -1 },
- { -1, 5, -16, 58, 97, -19, 5, -1 },
- { -1, 4, -14, 48, 105, -18, 5, -1 },
- { -1, 4, -11, 37, 112, -16, 4, -1 },
- { -1, 3, -9, 27, 118, -13, 4, -1 },
- { 0, 2, -6, 18, 122, -10, 3, -1 },
- { 0, 1, -3, 8, 126, -5, 1, 0 },
- }, [FILTER_8TAP_SHARP] = {
- { 0, 0, 0, 128, 0, 0, 0, 0 },
- { -1, 3, -7, 127, 8, -3, 1, 0 },
- { -2, 5, -13, 125, 17, -6, 3, -1 },
- { -3, 7, -17, 121, 27, -10, 5, -2 },
- { -4, 9, -20, 115, 37, -13, 6, -2 },
- { -4, 10, -23, 108, 48, -16, 8, -3 },
- { -4, 10, -24, 100, 59, -19, 9, -3 },
- { -4, 11, -24, 90, 70, -21, 10, -4 },
- { -4, 11, -23, 80, 80, -23, 11, -4 },
- { -4, 10, -21, 70, 90, -24, 11, -4 },
- { -3, 9, -19, 59, 100, -24, 10, -4 },
- { -3, 8, -16, 48, 108, -23, 10, -4 },
- { -2, 6, -13, 37, 115, -20, 9, -4 },
- { -2, 5, -10, 27, 121, -17, 7, -3 },
- { -1, 3, -6, 17, 125, -13, 5, -2 },
- { 0, 1, -3, 8, 127, -7, 3, -1 },
- }, [FILTER_8TAP_SMOOTH] = {
- { 0, 0, 0, 128, 0, 0, 0, 0 },
- { -3, -1, 32, 64, 38, 1, -3, 0 },
- { -2, -2, 29, 63, 41, 2, -3, 0 },
- { -2, -2, 26, 63, 43, 4, -4, 0 },
- { -2, -3, 24, 62, 46, 5, -4, 0 },
- { -2, -3, 21, 60, 49, 7, -4, 0 },
- { -1, -4, 18, 59, 51, 9, -4, 0 },
- { -1, -4, 16, 57, 53, 12, -4, -1 },
- { -1, -4, 14, 55, 55, 14, -4, -1 },
- { -1, -4, 12, 53, 57, 16, -4, -1 },
- { 0, -4, 9, 51, 59, 18, -4, -1 },
- { 0, -4, 7, 49, 60, 21, -3, -2 },
- { 0, -4, 5, 46, 62, 24, -3, -2 },
- { 0, -4, 4, 43, 63, 26, -2, -2 },
- { 0, -3, 2, 41, 63, 29, -2, -2 },
- { 0, -3, 1, 38, 64, 32, -1, -3 },
- }
-};
-
#define FILTER_8TAP(src, x, F, stride) \
av_clip_pixel((F[0] * src[x + -3 * stride] + \
F[1] * src[x + -2 * stride] + \
@@ -2155,7 +2100,7 @@ static void avg##_8tap_##type##_##sz##dir##_c(uint8_t *dst, ptrdiff_t dst_stride
int h, int mx, int my) \
{ \
avg##_8tap_1d_##dir##_c(dst, dst_stride, src, src_stride, sz, h, \
- vp9_subpel_filters[type_idx][dir_m]); \
+ ff_vp9_subpel_filters[type_idx][dir_m]); \
}
#define filter_fn_2d(sz, type, type_idx, avg) \
@@ -2164,8 +2109,8 @@ static void avg##_8tap_##type##_##sz##hv_c(uint8_t *dst, ptrdiff_t dst_stride, \
int h, int mx, int my) \
{ \
avg##_8tap_2d_hv_c(dst, dst_stride, src, src_stride, sz, h, \
- vp9_subpel_filters[type_idx][mx], \
- vp9_subpel_filters[type_idx][my]); \
+ ff_vp9_subpel_filters[type_idx][mx], \
+ ff_vp9_subpel_filters[type_idx][my]); \
}
#if BIT_DEPTH != 12
@@ -2454,7 +2399,7 @@ static void avg##_scaled_##type##_##sz##_c(uint8_t *dst, ptrdiff_t dst_stride, \
int h, int mx, int my, int dx, int dy) \
{ \
avg##_scaled_8tap_c(dst, dst_stride, src, src_stride, sz, h, mx, my, dx, dy, \
- vp9_subpel_filters[type_idx]); \
+ ff_vp9_subpel_filters[type_idx]); \
}
#if BIT_DEPTH != 12
diff --git a/media/ffvpx/libavcodec/vp9lpf.c b/media/ffvpx/libavcodec/vp9lpf.c
new file mode 100644
index 000000000..414cede85
--- /dev/null
+++ b/media/ffvpx/libavcodec/vp9lpf.c
@@ -0,0 +1,202 @@
+/*
+ * VP9 compatible video decoder
+ *
+ * Copyright (C) 2013 Ronald S. Bultje <rsbultje gmail com>
+ * Copyright (C) 2013 Clément Bœsch <u pkh me>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "vp9dec.h"
+
+static av_always_inline void filter_plane_cols(VP9Context *s, int col, int ss_h, int ss_v,
+ uint8_t *lvl, uint8_t (*mask)[4],
+ uint8_t *dst, ptrdiff_t ls)
+{
+ int y, x, bytesperpixel = s->bytesperpixel;
+
+ // filter edges between columns (e.g. block1 | block2)
+ for (y = 0; y < 8; y += 2 << ss_v, dst += 16 * ls, lvl += 16 << ss_v) {
+ uint8_t *ptr = dst, *l = lvl, *hmask1 = mask[y], *hmask2 = mask[y + 1 + ss_v];
+ unsigned hm1 = hmask1[0] | hmask1[1] | hmask1[2], hm13 = hmask1[3];
+ unsigned hm2 = hmask2[1] | hmask2[2], hm23 = hmask2[3];
+ unsigned hm = hm1 | hm2 | hm13 | hm23;
+
+ for (x = 1; hm & ~(x - 1); x <<= 1, ptr += 8 * bytesperpixel >> ss_h) {
+ if (col || x > 1) {
+ if (hm1 & x) {
+ int L = *l, H = L >> 4;
+ int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
+
+ if (hmask1[0] & x) {
+ if (hmask2[0] & x) {
+ av_assert2(l[8 << ss_v] == L);
+ s->dsp.loop_filter_16[0](ptr, ls, E, I, H);
+ } else {
+ s->dsp.loop_filter_8[2][0](ptr, ls, E, I, H);
+ }
+ } else if (hm2 & x) {
+ L = l[8 << ss_v];
+ H |= (L >> 4) << 8;
+ E |= s->filter_lut.mblim_lut[L] << 8;
+ I |= s->filter_lut.lim_lut[L] << 8;
+ s->dsp.loop_filter_mix2[!!(hmask1[1] & x)]
+ [!!(hmask2[1] & x)]
+ [0](ptr, ls, E, I, H);
+ } else {
+ s->dsp.loop_filter_8[!!(hmask1[1] & x)]
+ [0](ptr, ls, E, I, H);
+ }
+ } else if (hm2 & x) {
+ int L = l[8 << ss_v], H = L >> 4;
+ int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
+
+ s->dsp.loop_filter_8[!!(hmask2[1] & x)]
+ [0](ptr + 8 * ls, ls, E, I, H);
+ }
+ }
+ if (ss_h) {
+ if (x & 0xAA)
+ l += 2;
+ } else {
+ if (hm13 & x) {
+ int L = *l, H = L >> 4;
+ int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
+
+ if (hm23 & x) {
+ L = l[8 << ss_v];
+ H |= (L >> 4) << 8;
+ E |= s->filter_lut.mblim_lut[L] << 8;
+ I |= s->filter_lut.lim_lut[L] << 8;
+ s->dsp.loop_filter_mix2[0][0][0](ptr + 4 * bytesperpixel, ls, E, I, H);
+ } else {
+ s->dsp.loop_filter_8[0][0](ptr + 4 * bytesperpixel, ls, E, I, H);
+ }
+ } else if (hm23 & x) {
+ int L = l[8 << ss_v], H = L >> 4;
+ int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
+
+ s->dsp.loop_filter_8[0][0](ptr + 8 * ls + 4 * bytesperpixel, ls, E, I, H);
+ }
+ l++;
+ }
+ }
+ }
+}
+
+static av_always_inline void filter_plane_rows(VP9Context *s, int row, int ss_h, int ss_v,
+ uint8_t *lvl, uint8_t (*mask)[4],
+ uint8_t *dst, ptrdiff_t ls)
+{
+ int y, x, bytesperpixel = s->bytesperpixel;
+
+ // block1
+ // filter edges between rows (e.g. ------)
+ // block2
+ for (y = 0; y < 8; y++, dst += 8 * ls >> ss_v) {
+ uint8_t *ptr = dst, *l = lvl, *vmask = mask[y];
+ unsigned vm = vmask[0] | vmask[1] | vmask[2], vm3 = vmask[3];
+
+ for (x = 1; vm & ~(x - 1); x <<= (2 << ss_h), ptr += 16 * bytesperpixel, l += 2 << ss_h) {
+ if (row || y) {
+ if (vm & x) {
+ int L = *l, H = L >> 4;
+ int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
+
+ if (vmask[0] & x) {
+ if (vmask[0] & (x << (1 + ss_h))) {
+ av_assert2(l[1 + ss_h] == L);
+ s->dsp.loop_filter_16[1](ptr, ls, E, I, H);
+ } else {
+ s->dsp.loop_filter_8[2][1](ptr, ls, E, I, H);
+ }
+ } else if (vm & (x << (1 + ss_h))) {
+ L = l[1 + ss_h];
+ H |= (L >> 4) << 8;
+ E |= s->filter_lut.mblim_lut[L] << 8;
+ I |= s->filter_lut.lim_lut[L] << 8;
+ s->dsp.loop_filter_mix2[!!(vmask[1] & x)]
+ [!!(vmask[1] & (x << (1 + ss_h)))]
+ [1](ptr, ls, E, I, H);
+ } else {
+ s->dsp.loop_filter_8[!!(vmask[1] & x)]
+ [1](ptr, ls, E, I, H);
+ }
+ } else if (vm & (x << (1 + ss_h))) {
+ int L = l[1 + ss_h], H = L >> 4;
+ int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
+
+ s->dsp.loop_filter_8[!!(vmask[1] & (x << (1 + ss_h)))]
+ [1](ptr + 8 * bytesperpixel, ls, E, I, H);
+ }
+ }
+ if (!ss_v) {
+ if (vm3 & x) {
+ int L = *l, H = L >> 4;
+ int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
+
+ if (vm3 & (x << (1 + ss_h))) {
+ L = l[1 + ss_h];
+ H |= (L >> 4) << 8;
+ E |= s->filter_lut.mblim_lut[L] << 8;
+ I |= s->filter_lut.lim_lut[L] << 8;
+ s->dsp.loop_filter_mix2[0][0][1](ptr + ls * 4, ls, E, I, H);
+ } else {
+ s->dsp.loop_filter_8[0][1](ptr + ls * 4, ls, E, I, H);
+ }
+ } else if (vm3 & (x << (1 + ss_h))) {
+ int L = l[1 + ss_h], H = L >> 4;
+ int E = s->filter_lut.mblim_lut[L], I = s->filter_lut.lim_lut[L];
+
+ s->dsp.loop_filter_8[0][1](ptr + ls * 4 + 8 * bytesperpixel, ls, E, I, H);
+ }
+ }
+ }
+ if (ss_v) {
+ if (y & 1)
+ lvl += 16;
+ } else {
+ lvl += 8;
+ }
+ }
+}
+
+void ff_vp9_loopfilter_sb(AVCodecContext *avctx, VP9Filter *lflvl,
+ int row, int col, ptrdiff_t yoff, ptrdiff_t uvoff)
+{
+ VP9Context *s = avctx->priv_data;
+ AVFrame *f = s->s.frames[CUR_FRAME].tf.f;
+ uint8_t *dst = f->data[0] + yoff;
+ ptrdiff_t ls_y = f->linesize[0], ls_uv = f->linesize[1];
+ uint8_t (*uv_masks)[8][4] = lflvl->mask[s->ss_h | s->ss_v];
+ int p;
+
+ /* FIXME: In how far can we interleave the v/h loopfilter calls? E.g.
+ * if you think of them as acting on a 8x8 block max, we can interleave
+ * each v/h within the single x loop, but that only works if we work on
+ * 8 pixel blocks, and we won't always do that (we want at least 16px
+ * to use SSE2 optimizations, perhaps 32 for AVX2) */
+
+ filter_plane_cols(s, col, 0, 0, lflvl->level, lflvl->mask[0][0], dst, ls_y);
+ filter_plane_rows(s, row, 0, 0, lflvl->level, lflvl->mask[0][1], dst, ls_y);
+
+ for (p = 0; p < 2; p++) {
+ dst = f->data[1 + p] + uvoff;
+ filter_plane_cols(s, col, s->ss_h, s->ss_v, lflvl->level, uv_masks[0], dst, ls_uv);
+ filter_plane_rows(s, row, s->ss_h, s->ss_v, lflvl->level, uv_masks[1], dst, ls_uv);
+ }
+}
diff --git a/media/ffvpx/libavcodec/vp9mvs.c b/media/ffvpx/libavcodec/vp9mvs.c
new file mode 100644
index 000000000..88db1c341
--- /dev/null
+++ b/media/ffvpx/libavcodec/vp9mvs.c
@@ -0,0 +1,364 @@
+/*
+ * VP9 compatible video decoder
+ *
+ * Copyright (C) 2013 Ronald S. Bultje <rsbultje gmail com>
+ * Copyright (C) 2013 Clément Bœsch <u pkh me>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "internal.h"
+#include "vp56.h"
+#include "vp9.h"
+#include "vp9data.h"
+#include "vp9dec.h"
+
+static av_always_inline void clamp_mv(VP56mv *dst, const VP56mv *src,
+ VP9TileData *td)
+{
+ dst->x = av_clip(src->x, td->min_mv.x, td->max_mv.x);
+ dst->y = av_clip(src->y, td->min_mv.y, td->max_mv.y);
+}
+
+static void find_ref_mvs(VP9TileData *td,
+ VP56mv *pmv, int ref, int z, int idx, int sb)
+{
+ static const int8_t mv_ref_blk_off[N_BS_SIZES][8][2] = {
+ [BS_64x64] = { { 3, -1 }, { -1, 3 }, { 4, -1 }, { -1, 4 },
+ { -1, -1 }, { 0, -1 }, { -1, 0 }, { 6, -1 } },
+ [BS_64x32] = { { 0, -1 }, { -1, 0 }, { 4, -1 }, { -1, 2 },
+ { -1, -1 }, { 0, -3 }, { -3, 0 }, { 2, -1 } },
+ [BS_32x64] = { { -1, 0 }, { 0, -1 }, { -1, 4 }, { 2, -1 },
+ { -1, -1 }, { -3, 0 }, { 0, -3 }, { -1, 2 } },
+ [BS_32x32] = { { 1, -1 }, { -1, 1 }, { 2, -1 }, { -1, 2 },
+ { -1, -1 }, { 0, -3 }, { -3, 0 }, { -3, -3 } },
+ [BS_32x16] = { { 0, -1 }, { -1, 0 }, { 2, -1 }, { -1, -1 },
+ { -1, 1 }, { 0, -3 }, { -3, 0 }, { -3, -3 } },
+ [BS_16x32] = { { -1, 0 }, { 0, -1 }, { -1, 2 }, { -1, -1 },
+ { 1, -1 }, { -3, 0 }, { 0, -3 }, { -3, -3 } },
+ [BS_16x16] = { { 0, -1 }, { -1, 0 }, { 1, -1 }, { -1, 1 },
+ { -1, -1 }, { 0, -3 }, { -3, 0 }, { -3, -3 } },
+ [BS_16x8] = { { 0, -1 }, { -1, 0 }, { 1, -1 }, { -1, -1 },
+ { 0, -2 }, { -2, 0 }, { -2, -1 }, { -1, -2 } },
+ [BS_8x16] = { { -1, 0 }, { 0, -1 }, { -1, 1 }, { -1, -1 },
+ { -2, 0 }, { 0, -2 }, { -1, -2 }, { -2, -1 } },
+ [BS_8x8] = { { 0, -1 }, { -1, 0 }, { -1, -1 }, { 0, -2 },
+ { -2, 0 }, { -1, -2 }, { -2, -1 }, { -2, -2 } },
+ [BS_8x4] = { { 0, -1 }, { -1, 0 }, { -1, -1 }, { 0, -2 },
+ { -2, 0 }, { -1, -2 }, { -2, -1 }, { -2, -2 } },
+ [BS_4x8] = { { 0, -1 }, { -1, 0 }, { -1, -1 }, { 0, -2 },
+ { -2, 0 }, { -1, -2 }, { -2, -1 }, { -2, -2 } },
+ [BS_4x4] = { { 0, -1 }, { -1, 0 }, { -1, -1 }, { 0, -2 },
+ { -2, 0 }, { -1, -2 }, { -2, -1 }, { -2, -2 } },
+ };
+ VP9Context *s = td->s;
+ VP9Block *b = td->b;
+ int row = td->row, col = td->col, row7 = td->row7;
+ const int8_t (*p)[2] = mv_ref_blk_off[b->bs];
+#define INVALID_MV 0x80008000U
+ uint32_t mem = INVALID_MV, mem_sub8x8 = INVALID_MV;
+ int i;
+
+#define RETURN_DIRECT_MV(mv) \
+ do { \
+ uint32_t m = AV_RN32A(&mv); \
+ if (!idx) { \
+ AV_WN32A(pmv, m); \
+ return; \
+ } else if (mem == INVALID_MV) { \
+ mem = m; \
+ } else if (m != mem) { \
+ AV_WN32A(pmv, m); \
+ return; \
+ } \
+ } while (0)
+
+ if (sb >= 0) {
+ if (sb == 2 || sb == 1) {
+ RETURN_DIRECT_MV(b->mv[0][z]);
+ } else if (sb == 3) {
+ RETURN_DIRECT_MV(b->mv[2][z]);
+ RETURN_DIRECT_MV(b->mv[1][z]);
+ RETURN_DIRECT_MV(b->mv[0][z]);
+ }
+
+#define RETURN_MV(mv) \
+ do { \
+ if (sb > 0) { \
+ VP56mv tmp; \
+ uint32_t m; \
+ av_assert2(idx == 1); \
+ av_assert2(mem != INVALID_MV); \
+ if (mem_sub8x8 == INVALID_MV) { \
+ clamp_mv(&tmp, &mv, td); \
+ m = AV_RN32A(&tmp); \
+ if (m != mem) { \
+ AV_WN32A(pmv, m); \
+ return; \
+ } \
+ mem_sub8x8 = AV_RN32A(&mv); \
+ } else if (mem_sub8x8 != AV_RN32A(&mv)) { \
+ clamp_mv(&tmp, &mv, td); \
+ m = AV_RN32A(&tmp); \
+ if (m != mem) { \
+ AV_WN32A(pmv, m); \
+ } else { \
+ /* BUG I'm pretty sure this isn't the intention */ \
+ AV_WN32A(pmv, 0); \
+ } \
+ return; \
+ } \
+ } else { \
+ uint32_t m = AV_RN32A(&mv); \
+ if (!idx) { \
+ clamp_mv(pmv, &mv, td); \
+ return; \
+ } else if (mem == INVALID_MV) { \
+ mem = m; \
+ } else if (m != mem) { \
+ clamp_mv(pmv, &mv, td); \
+ return; \
+ } \
+ } \
+ } while (0)
+
+ if (row > 0) {
+ VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[(row - 1) * s->sb_cols * 8 + col];
+ if (mv->ref[0] == ref)
+ RETURN_MV(s->above_mv_ctx[2 * col + (sb & 1)][0]);
+ else if (mv->ref[1] == ref)
+ RETURN_MV(s->above_mv_ctx[2 * col + (sb & 1)][1]);
+ }
+ if (col > td->tile_col_start) {
+ VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[row * s->sb_cols * 8 + col - 1];
+ if (mv->ref[0] == ref)
+ RETURN_MV(td->left_mv_ctx[2 * row7 + (sb >> 1)][0]);
+ else if (mv->ref[1] == ref)
+ RETURN_MV(td->left_mv_ctx[2 * row7 + (sb >> 1)][1]);
+ }
+ i = 2;
+ } else {
+ i = 0;
+ }
+
+ // previously coded MVs in this neighborhood, using same reference frame
+ for (; i < 8; i++) {
+ int c = p[i][0] + col, r = p[i][1] + row;
+
+ if (c >= td->tile_col_start && c < s->cols &&
+ r >= 0 && r < s->rows) {
+ VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[r * s->sb_cols * 8 + c];
+
+ if (mv->ref[0] == ref)
+ RETURN_MV(mv->mv[0]);
+ else if (mv->ref[1] == ref)
+ RETURN_MV(mv->mv[1]);
+ }
+ }
+
+ // MV at this position in previous frame, using same reference frame
+ if (s->s.h.use_last_frame_mvs) {
+ VP9mvrefPair *mv = &s->s.frames[REF_FRAME_MVPAIR].mv[row * s->sb_cols * 8 + col];
+
+ if (!s->s.frames[REF_FRAME_MVPAIR].uses_2pass)
+ ff_thread_await_progress(&s->s.frames[REF_FRAME_MVPAIR].tf, row >> 3, 0);
+ if (mv->ref[0] == ref)
+ RETURN_MV(mv->mv[0]);
+ else if (mv->ref[1] == ref)
+ RETURN_MV(mv->mv[1]);
+ }
+
+#define RETURN_SCALE_MV(mv, scale) \
+ do { \
+ if (scale) { \
+ VP56mv mv_temp = { -mv.x, -mv.y }; \
+ RETURN_MV(mv_temp); \
+ } else { \
+ RETURN_MV(mv); \
+ } \
+ } while (0)
+
+ // previously coded MVs in this neighborhood, using different reference frame
+ for (i = 0; i < 8; i++) {
+ int c = p[i][0] + col, r = p[i][1] + row;
+
+ if (c >= td->tile_col_start && c < s->cols && r >= 0 && r < s->rows) {
+ VP9mvrefPair *mv = &s->s.frames[CUR_FRAME].mv[r * s->sb_cols * 8 + c];
+
+ if (mv->ref[0] != ref && mv->ref[0] >= 0)
+ RETURN_SCALE_MV(mv->mv[0],
+ s->s.h.signbias[mv->ref[0]] != s->s.h.signbias[ref]);
+ if (mv->ref[1] != ref && mv->ref[1] >= 0 &&
+ // BUG - libvpx has this condition regardless of whether
+ // we used the first ref MV and pre-scaling
+ AV_RN32A(&mv->mv[0]) != AV_RN32A(&mv->mv[1])) {
+ RETURN_SCALE_MV(mv->mv[1], s->s.h.signbias[mv->ref[1]] != s->s.h.signbias[ref]);
+ }
+ }
+ }
+
+ // MV at this position in previous frame, using different reference frame
+ if (s->s.h.use_last_frame_mvs) {
+ VP9mvrefPair *mv = &s->s.frames[REF_FRAME_MVPAIR].mv[row * s->sb_cols * 8 + col];
+
+ // no need to await_progress, because we already did that above
+ if (mv->ref[0] != ref && mv->ref[0] >= 0)
+ RETURN_SCALE_MV(mv->mv[0], s->s.h.signbias[mv->ref[0]] != s->s.h.signbias[ref]);
+ if (mv->ref[1] != ref && mv->ref[1] >= 0 &&
+ // BUG - libvpx has this condition regardless of whether
+ // we used the first ref MV and pre-scaling
+ AV_RN32A(&mv->mv[0]) != AV_RN32A(&mv->mv[1])) {
+ RETURN_SCALE_MV(mv->mv[1], s->s.h.signbias[mv->ref[1]] != s->s.h.signbias[ref]);
+ }
+ }
+
+ AV_ZERO32(pmv);
+ clamp_mv(pmv, pmv, td);
+#undef INVALID_MV
+#undef RETURN_MV
+#undef RETURN_SCALE_MV
+}
+
+static av_always_inline int read_mv_component(VP9TileData *td, int idx, int hp)
+{
+ VP9Context *s = td->s;
+ int bit, sign = vp56_rac_get_prob(td->c, s->prob.p.mv_comp[idx].sign);
+ int n, c = vp8_rac_get_tree(td->c, ff_vp9_mv_class_tree,
+ s->prob.p.mv_comp[idx].classes);
+
+ td->counts.mv_comp[idx].sign[sign]++;
+ td->counts.mv_comp[idx].classes[c]++;
+ if (c) {
+ int m;
+
+ for (n = 0, m = 0; m < c; m++) {
+ bit = vp56_rac_get_prob(td->c, s->prob.p.mv_comp[idx].bits[m]);
+ n |= bit << m;
+ td->counts.mv_comp[idx].bits[m][bit]++;
+ }
+ n <<= 3;
+ bit = vp8_rac_get_tree(td->c, ff_vp9_mv_fp_tree,
+ s->prob.p.mv_comp[idx].fp);
+ n |= bit << 1;
+ td->counts.mv_comp[idx].fp[bit]++;
+ if (hp) {
+ bit = vp56_rac_get_prob(td->c, s->prob.p.mv_comp[idx].hp);
+ td->counts.mv_comp[idx].hp[bit]++;
+ n |= bit;
+ } else {
+ n |= 1;
+ // bug in libvpx - we count for bw entropy purposes even if the
+ // bit wasn't coded
+ td->counts.mv_comp[idx].hp[1]++;
+ }
+ n += 8 << c;
+ } else {
+ n = vp56_rac_get_prob(td->c, s->prob.p.mv_comp[idx].class0);
+ td->counts.mv_comp[idx].class0[n]++;
+ bit = vp8_rac_get_tree(td->c, ff_vp9_mv_fp_tree,
+ s->prob.p.mv_comp[idx].class0_fp[n]);
+ td->counts.mv_comp[idx].class0_fp[n][bit]++;
+ n = (n << 3) | (bit << 1);
+ if (hp) {
+ bit = vp56_rac_get_prob(td->c, s->prob.p.mv_comp[idx].class0_hp);
+ td->counts.mv_comp[idx].class0_hp[bit]++;
+ n |= bit;
+ } else {
+ n |= 1;
+ // bug in libvpx - we count for bw entropy purposes even if the
+ // bit wasn't coded
+ td->counts.mv_comp[idx].class0_hp[1]++;
+ }
+ }
+
+ return sign ? -(n + 1) : (n + 1);
+}
+
+void ff_vp9_fill_mv(VP9TileData *td, VP56mv *mv, int mode, int sb)
+{
+ VP9Context *s = td->s;
+ VP9Block *b = td->b;
+
+ if (mode == ZEROMV) {
+ AV_ZERO64(mv);
+ } else {
+ int hp;
+
+ // FIXME cache this value and reuse for other subblocks
+ find_ref_mvs(td, &mv[0], b->ref[0], 0, mode == NEARMV,
+ mode == NEWMV ? -1 : sb);
+ // FIXME maybe move this code into find_ref_mvs()
+ if ((mode == NEWMV || sb == -1) &&
+ !(hp = s->s.h.highprecisionmvs &&
+ abs(mv[0].x) < 64 && abs(mv[0].y) < 64)) {
+ if (mv[0].y & 1) {
+ if (mv[0].y < 0)
+ mv[0].y++;
+ else
+ mv[0].y--;
+ }
+ if (mv[0].x & 1) {
+ if (mv[0].x < 0)
+ mv[0].x++;
+ else
+ mv[0].x--;
+ }
+ }
+ if (mode == NEWMV) {
+ enum MVJoint j = vp8_rac_get_tree(td->c, ff_vp9_mv_joint_tree,
+ s->prob.p.mv_joint);
+
+ td->counts.mv_joint[j]++;
+ if (j >= MV_JOINT_V)
+ mv[0].y += read_mv_component(td, 0, hp);
+ if (j & 1)
+ mv[0].x += read_mv_component(td, 1, hp);
+ }
+
+ if (b->comp) {
+ // FIXME cache this value and reuse for other subblocks
+ find_ref_mvs(td, &mv[1], b->ref[1], 1, mode == NEARMV,
+ mode == NEWMV ? -1 : sb);
+ if ((mode == NEWMV || sb == -1) &&
+ !(hp = s->s.h.highprecisionmvs &&
+ abs(mv[1].x) < 64 && abs(mv[1].y) < 64)) {
+ if (mv[1].y & 1) {
+ if (mv[1].y < 0)
+ mv[1].y++;
+ else
+ mv[1].y--;
+ }
+ if (mv[1].x & 1) {
+ if (mv[1].x < 0)
+ mv[1].x++;
+ else
+ mv[1].x--;
+ }
+ }
+ if (mode == NEWMV) {
+ enum MVJoint j = vp8_rac_get_tree(td->c, ff_vp9_mv_joint_tree,
+ s->prob.p.mv_joint);
+
+ td->counts.mv_joint[j]++;
+ if (j >= MV_JOINT_V)
+ mv[1].y += read_mv_component(td, 0, hp);
+ if (j & 1)
+ mv[1].x += read_mv_component(td, 1, hp);
+ }
+ }
+ }
+}
diff --git a/media/ffvpx/libavcodec/vp9prob.c b/media/ffvpx/libavcodec/vp9prob.c
new file mode 100644
index 000000000..fb295b482
--- /dev/null
+++ b/media/ffvpx/libavcodec/vp9prob.c
@@ -0,0 +1,274 @@
+/*
+ * VP9 compatible video decoder
+ *
+ * Copyright (C) 2013 Ronald S. Bultje <rsbultje gmail com>
+ * Copyright (C) 2013 Clément Bœsch <u pkh me>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "vp56.h"
+#include "vp9.h"
+#include "vp9data.h"
+#include "vp9dec.h"
+
+static av_always_inline void adapt_prob(uint8_t *p, unsigned ct0, unsigned ct1,
+ int max_count, int update_factor)
+{
+ unsigned ct = ct0 + ct1, p2, p1;
+
+ if (!ct)
+ return;
+
+ update_factor = FASTDIV(update_factor * FFMIN(ct, max_count), max_count);
+ p1 = *p;
+ p2 = ((((int64_t) ct0) << 8) + (ct >> 1)) / ct;
+ p2 = av_clip(p2, 1, 255);
+
+ // (p1 * (256 - update_factor) + p2 * update_factor + 128) >> 8
+ *p = p1 + (((p2 - p1) * update_factor + 128) >> 8);
+}
+
+void ff_vp9_adapt_probs(VP9Context *s)
+{
+ int i, j, k, l, m;
+ ProbContext *p = &s->prob_ctx[s->s.h.framectxid].p;
+ int uf = (s->s.h.keyframe || s->s.h.intraonly || !s->last_keyframe) ? 112 : 128;
+
+ // coefficients
+ for (i = 0; i < 4; i++)
+ for (j = 0; j < 2; j++)
+ for (k = 0; k < 2; k++)
+ for (l = 0; l < 6; l++)
+ for (m = 0; m < 6; m++) {
+ uint8_t *pp = s->prob_ctx[s->s.h.framectxid].coef[i][j][k][l][m];
+ unsigned *e = s->td[0].counts.eob[i][j][k][l][m];
+ unsigned *c = s->td[0].counts.coef[i][j][k][l][m];
+
+ if (l == 0 && m >= 3) // dc only has 3 pt
+ break;
+
+ adapt_prob(&pp[0], e[0], e[1], 24, uf);
+ adapt_prob(&pp[1], c[0], c[1] + c[2], 24, uf);
+ adapt_prob(&pp[2], c[1], c[2], 24, uf);
+ }
+
+ if (s->s.h.keyframe || s->s.h.intraonly) {
+ memcpy(p->skip, s->prob.p.skip, sizeof(p->skip));
+ memcpy(p->tx32p, s->prob.p.tx32p, sizeof(p->tx32p));
+ memcpy(p->tx16p, s->prob.p.tx16p, sizeof(p->tx16p));
+ memcpy(p->tx8p, s->prob.p.tx8p, sizeof(p->tx8p));
+ return;
+ }
+
+ // skip flag
+ for (i = 0; i < 3; i++)
+ adapt_prob(&p->skip[i], s->td[0].counts.skip[i][0],
+ s->td[0].counts.skip[i][1], 20, 128);
+
+ // intra/inter flag
+ for (i = 0; i < 4; i++)
+ adapt_prob(&p->intra[i], s->td[0].counts.intra[i][0],
+ s->td[0].counts.intra[i][1], 20, 128);
+
+ // comppred flag
+ if (s->s.h.comppredmode == PRED_SWITCHABLE) {
+ for (i = 0; i < 5; i++)
+ adapt_prob(&p->comp[i], s->td[0].counts.comp[i][0],
+ s->td[0].counts.comp[i][1], 20, 128);
+ }
+
+ // reference frames
+ if (s->s.h.comppredmode != PRED_SINGLEREF) {
+ for (i = 0; i < 5; i++)
+ adapt_prob(&p->comp_ref[i], s->td[0].counts.comp_ref[i][0],
+ s->td[0].counts.comp_ref[i][1], 20, 128);
+ }
+
+ if (s->s.h.comppredmode != PRED_COMPREF) {
+ for (i = 0; i < 5; i++) {
+ uint8_t *pp = p->single_ref[i];
+ unsigned (*c)[2] = s->td[0].counts.single_ref[i];
+
+ adapt_prob(&pp[0], c[0][0], c[0][1], 20, 128);
+ adapt_prob(&pp[1], c[1][0], c[1][1], 20, 128);
+ }
+ }
+
+ // block partitioning
+ for (i = 0; i < 4; i++)
+ for (j = 0; j < 4; j++) {
+ uint8_t *pp = p->partition[i][j];
+ unsigned *c = s->td[0].counts.partition[i][j];
+
+ adapt_prob(&pp[0], c[0], c[1] + c[2] + c[3], 20, 128);
+ adapt_prob(&pp[1], c[1], c[2] + c[3], 20, 128);
+ adapt_prob(&pp[2], c[2], c[3], 20, 128);
+ }
+
+ // tx size
+ if (s->s.h.txfmmode == TX_SWITCHABLE) {
+ for (i = 0; i < 2; i++) {
+ unsigned *c16 = s->td[0].counts.tx16p[i], *c32 = s->td[0].counts.tx32p[i];
+
+ adapt_prob(&p->tx8p[i], s->td[0].counts.tx8p[i][0],
+ s->td[0].counts.tx8p[i][1], 20, 128);
+ adapt_prob(&p->tx16p[i][0], c16[0], c16[1] + c16[2], 20, 128);
+ adapt_prob(&p->tx16p[i][1], c16[1], c16[2], 20, 128);
+ adapt_prob(&p->tx32p[i][0], c32[0], c32[1] + c32[2] + c32[3], 20, 128);
+ adapt_prob(&p->tx32p[i][1], c32[1], c32[2] + c32[3], 20, 128);
+ adapt_prob(&p->tx32p[i][2], c32[2], c32[3], 20, 128);
+ }
+ }
+
+ // interpolation filter
+ if (s->s.h.filtermode == FILTER_SWITCHABLE) {
+ for (i = 0; i < 4; i++) {
+ uint8_t *pp = p->filter[i];
+ unsigned *c = s->td[0].counts.filter[i];
+
+ adapt_prob(&pp[0], c[0], c[1] + c[2], 20, 128);
+ adapt_prob(&pp[1], c[1], c[2], 20, 128);
+ }
+ }
+
+ // inter modes
+ for (i = 0; i < 7; i++) {
+ uint8_t *pp = p->mv_mode[i];
+ unsigned *c = s->td[0].counts.mv_mode[i];
+
+ adapt_prob(&pp[0], c[2], c[1] + c[0] + c[3], 20, 128);
+ adapt_prob(&pp[1], c[0], c[1] + c[3], 20, 128);
+ adapt_prob(&pp[2], c[1], c[3], 20, 128);
+ }
+
+ // mv joints
+ {
+ uint8_t *pp = p->mv_joint;
+ unsigned *c = s->td[0].counts.mv_joint;
+
+ adapt_prob(&pp[0], c[0], c[1] + c[2] + c[3], 20, 128);
+ adapt_prob(&pp[1], c[1], c[2] + c[3], 20, 128);
+ adapt_prob(&pp[2], c[2], c[3], 20, 128);
+ }
+
+ // mv components
+ for (i = 0; i < 2; i++) {
+ uint8_t *pp;
+ unsigned *c, (*c2)[2], sum;
+
+ adapt_prob(&p->mv_comp[i].sign, s->td[0].counts.mv_comp[i].sign[0],
+ s->td[0].counts.mv_comp[i].sign[1], 20, 128);
+
+ pp = p->mv_comp[i].classes;
+ c = s->td[0].counts.mv_comp[i].classes;
+ sum = c[1] + c[2] + c[3] + c[4] + c[5] +
+ c[6] + c[7] + c[8] + c[9] + c[10];
+ adapt_prob(&pp[0], c[0], sum, 20, 128);
+ sum -= c[1];
+ adapt_prob(&pp[1], c[1], sum, 20, 128);
+ sum -= c[2] + c[3];
+ adapt_prob(&pp[2], c[2] + c[3], sum, 20, 128);
+ adapt_prob(&pp[3], c[2], c[3], 20, 128);
+ sum -= c[4] + c[5];
+ adapt_prob(&pp[4], c[4] + c[5], sum, 20, 128);
+ adapt_prob(&pp[5], c[4], c[5], 20, 128);
+ sum -= c[6];
+ adapt_prob(&pp[6], c[6], sum, 20, 128);
+ adapt_prob(&pp[7], c[7] + c[8], c[9] + c[10], 20, 128);
+ adapt_prob(&pp[8], c[7], c[8], 20, 128);
+ adapt_prob(&pp[9], c[9], c[10], 20, 128);
+
+ adapt_prob(&p->mv_comp[i].class0, s->td[0].counts.mv_comp[i].class0[0],
+ s->td[0].counts.mv_comp[i].class0[1], 20, 128);
+ pp = p->mv_comp[i].bits;
+ c2 = s->td[0].counts.mv_comp[i].bits;
+ for (j = 0; j < 10; j++)
+ adapt_prob(&pp[j], c2[j][0], c2[j][1], 20, 128);
+
+ for (j = 0; j < 2; j++) {
+ pp = p->mv_comp[i].class0_fp[j];
+ c = s->td[0].counts.mv_comp[i].class0_fp[j];
+ adapt_prob(&pp[0], c[0], c[1] + c[2] + c[3], 20, 128);
+ adapt_prob(&pp[1], c[1], c[2] + c[3], 20, 128);
+ adapt_prob(&pp[2], c[2], c[3], 20, 128);
+ }
+ pp = p->mv_comp[i].fp;
+ c = s->td[0].counts.mv_comp[i].fp;
+ adapt_prob(&pp[0], c[0], c[1] + c[2] + c[3], 20, 128);
+ adapt_prob(&pp[1], c[1], c[2] + c[3], 20, 128);
+ adapt_prob(&pp[2], c[2], c[3], 20, 128);
+
+ if (s->s.h.highprecisionmvs) {
+ adapt_prob(&p->mv_comp[i].class0_hp,
+ s->td[0].counts.mv_comp[i].class0_hp[0],
+ s->td[0].counts.mv_comp[i].class0_hp[1], 20, 128);
+ adapt_prob(&p->mv_comp[i].hp, s->td[0].counts.mv_comp[i].hp[0],
+ s->td[0].counts.mv_comp[i].hp[1], 20, 128);
+ }
+ }
+
+ // y intra modes
+ for (i = 0; i < 4; i++) {
+ uint8_t *pp = p->y_mode[i];
+ unsigned *c = s->td[0].counts.y_mode[i], sum, s2;
+
+ sum = c[0] + c[1] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8] + c[9];
+ adapt_prob(&pp[0], c[DC_PRED], sum, 20, 128);
+ sum -= c[TM_VP8_PRED];
+ adapt_prob(&pp[1], c[TM_VP8_PRED], sum, 20, 128);
+ sum -= c[VERT_PRED];
+ adapt_prob(&pp[2], c[VERT_PRED], sum, 20, 128);
+ s2 = c[HOR_PRED] + c[DIAG_DOWN_RIGHT_PRED] + c[VERT_RIGHT_PRED];
+ sum -= s2;
+ adapt_prob(&pp[3], s2, sum, 20, 128);
+ s2 -= c[HOR_PRED];
+ adapt_prob(&pp[4], c[HOR_PRED], s2, 20, 128);
+ adapt_prob(&pp[5], c[DIAG_DOWN_RIGHT_PRED], c[VERT_RIGHT_PRED],
+ 20, 128);
+ sum -= c[DIAG_DOWN_LEFT_PRED];
+ adapt_prob(&pp[6], c[DIAG_DOWN_LEFT_PRED], sum, 20, 128);
+ sum -= c[VERT_LEFT_PRED];
+ adapt_prob(&pp[7], c[VERT_LEFT_PRED], sum, 20, 128);
+ adapt_prob(&pp[8], c[HOR_DOWN_PRED], c[HOR_UP_PRED], 20, 128);
+ }
+
+ // uv intra modes
+ for (i = 0; i < 10; i++) {
+ uint8_t *pp = p->uv_mode[i];
+ unsigned *c = s->td[0].counts.uv_mode[i], sum, s2;
+
+ sum = c[0] + c[1] + c[3] + c[4] + c[5] + c[6] + c[7] + c[8] + c[9];
+ adapt_prob(&pp[0], c[DC_PRED], sum, 20, 128);
+ sum -= c[TM_VP8_PRED];
+ adapt_prob(&pp[1], c[TM_VP8_PRED], sum, 20, 128);
+ sum -= c[VERT_PRED];
+ adapt_prob(&pp[2], c[VERT_PRED], sum, 20, 128);
+ s2 = c[HOR_PRED] + c[DIAG_DOWN_RIGHT_PRED] + c[VERT_RIGHT_PRED];
+ sum -= s2;
+ adapt_prob(&pp[3], s2, sum, 20, 128);
+ s2 -= c[HOR_PRED];
+ adapt_prob(&pp[4], c[HOR_PRED], s2, 20, 128);
+ adapt_prob(&pp[5], c[DIAG_DOWN_RIGHT_PRED], c[VERT_RIGHT_PRED],
+ 20, 128);
+ sum -= c[DIAG_DOWN_LEFT_PRED];
+ adapt_prob(&pp[6], c[DIAG_DOWN_LEFT_PRED], sum, 20, 128);
+ sum -= c[VERT_LEFT_PRED];
+ adapt_prob(&pp[7], c[VERT_LEFT_PRED], sum, 20, 128);
+ adapt_prob(&pp[8], c[HOR_DOWN_PRED], c[HOR_UP_PRED], 20, 128);
+ }
+}
diff --git a/media/ffvpx/libavcodec/vp9recon.c b/media/ffvpx/libavcodec/vp9recon.c
new file mode 100644
index 000000000..49bb04e1f
--- /dev/null
+++ b/media/ffvpx/libavcodec/vp9recon.c
@@ -0,0 +1,644 @@
+/*
+ * VP9 compatible video decoder
+ *
+ * Copyright (C) 2013 Ronald S. Bultje <rsbultje gmail com>
+ * Copyright (C) 2013 Clément Bœsch <u pkh me>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavutil/avassert.h"
+
+#include "avcodec.h"
+#include "internal.h"
+#include "videodsp.h"
+#include "vp9data.h"
+#include "vp9dec.h"
+
+static av_always_inline int check_intra_mode(VP9TileData *td, int mode, uint8_t **a,
+ uint8_t *dst_edge, ptrdiff_t stride_edge,
+ uint8_t *dst_inner, ptrdiff_t stride_inner,
+ uint8_t *l, int col, int x, int w,
+ int row, int y, enum TxfmMode tx,
+ int p, int ss_h, int ss_v, int bytesperpixel)
+{
+ VP9Context *s = td->s;
+ int have_top = row > 0 || y > 0;
+ int have_left = col > td->tile_col_start || x > 0;
+ int have_right = x < w - 1;
+ int bpp = s->s.h.bpp;
+ static const uint8_t mode_conv[10][2 /* have_left */][2 /* have_top */] = {
+ [VERT_PRED] = { { DC_127_PRED, VERT_PRED },
+ { DC_127_PRED, VERT_PRED } },
+ [HOR_PRED] = { { DC_129_PRED, DC_129_PRED },
+ { HOR_PRED, HOR_PRED } },
+ [DC_PRED] = { { DC_128_PRED, TOP_DC_PRED },
+ { LEFT_DC_PRED, DC_PRED } },
+ [DIAG_DOWN_LEFT_PRED] = { { DC_127_PRED, DIAG_DOWN_LEFT_PRED },
+ { DC_127_PRED, DIAG_DOWN_LEFT_PRED } },
+ [DIAG_DOWN_RIGHT_PRED] = { { DIAG_DOWN_RIGHT_PRED, DIAG_DOWN_RIGHT_PRED },
+ { DIAG_DOWN_RIGHT_PRED, DIAG_DOWN_RIGHT_PRED } },
+ [VERT_RIGHT_PRED] = { { VERT_RIGHT_PRED, VERT_RIGHT_PRED },
+ { VERT_RIGHT_PRED, VERT_RIGHT_PRED } },
+ [HOR_DOWN_PRED] = { { HOR_DOWN_PRED, HOR_DOWN_PRED },
+ { HOR_DOWN_PRED, HOR_DOWN_PRED } },
+ [VERT_LEFT_PRED] = { { DC_127_PRED, VERT_LEFT_PRED },
+ { DC_127_PRED, VERT_LEFT_PRED } },
+ [HOR_UP_PRED] = { { DC_129_PRED, DC_129_PRED },
+ { HOR_UP_PRED, HOR_UP_PRED } },
+ [TM_VP8_PRED] = { { DC_129_PRED, VERT_PRED },
+ { HOR_PRED, TM_VP8_PRED } },
+ };
+ static const struct {
+ uint8_t needs_left:1;
+ uint8_t needs_top:1;
+ uint8_t needs_topleft:1;
+ uint8_t needs_topright:1;
+ uint8_t invert_left:1;
+ } edges[N_INTRA_PRED_MODES] = {
+ [VERT_PRED] = { .needs_top = 1 },
+ [HOR_PRED] = { .needs_left = 1 },
+ [DC_PRED] = { .needs_top = 1, .needs_left = 1 },
+ [DIAG_DOWN_LEFT_PRED] = { .needs_top = 1, .needs_topright = 1 },
+ [DIAG_DOWN_RIGHT_PRED] = { .needs_left = 1, .needs_top = 1,
+ .needs_topleft = 1 },
+ [VERT_RIGHT_PRED] = { .needs_left = 1, .needs_top = 1,
+ .needs_topleft = 1 },
+ [HOR_DOWN_PRED] = { .needs_left = 1, .needs_top = 1,
+ .needs_topleft = 1 },
+ [VERT_LEFT_PRED] = { .needs_top = 1, .needs_topright = 1 },
+ [HOR_UP_PRED] = { .needs_left = 1, .invert_left = 1 },
+ [TM_VP8_PRED] = { .needs_left = 1, .needs_top = 1,
+ .needs_topleft = 1 },
+ [LEFT_DC_PRED] = { .needs_left = 1 },
+ [TOP_DC_PRED] = { .needs_top = 1 },
+ [DC_128_PRED] = { 0 },
+ [DC_127_PRED] = { 0 },
+ [DC_129_PRED] = { 0 }
+ };
+
+ av_assert2(mode >= 0 && mode < 10);
+ mode = mode_conv[mode][have_left][have_top];
+ if (edges[mode].needs_top) {
+ uint8_t *top, *topleft;
+ int n_px_need = 4 << tx, n_px_have = (((s->cols - col) << !ss_h) - x) * 4;
+ int n_px_need_tr = 0;
+
+ if (tx == TX_4X4 && edges[mode].needs_topright && have_right)
+ n_px_need_tr = 4;
+
+ // if top of sb64-row, use s->intra_pred_data[] instead of
+ // dst[-stride] for intra prediction (it contains pre- instead of
+ // post-loopfilter data)
+ if (have_top) {
+ top = !(row & 7) && !y ?
+ s->intra_pred_data[p] + (col * (8 >> ss_h) + x * 4) * bytesperpixel :
+ y == 0 ? &dst_edge[-stride_edge] : &dst_inner[-stride_inner];
+ if (have_left)
+ topleft = !(row & 7) && !y ?
+ s->intra_pred_data[p] + (col * (8 >> ss_h) + x * 4) * bytesperpixel :
+ y == 0 || x == 0 ? &dst_edge[-stride_edge] :
+ &dst_inner[-stride_inner];
+ }
+
+ if (have_top &&
+ (!edges[mode].needs_topleft || (have_left && top == topleft)) &&
+ (tx != TX_4X4 || !edges[mode].needs_topright || have_right) &&
+ n_px_need + n_px_need_tr <= n_px_have) {
+ *a = top;
+ } else {
+ if (have_top) {
+ if (n_px_need <= n_px_have) {
+ memcpy(*a, top, n_px_need * bytesperpixel);
+ } else {
+#define memset_bpp(c, i1, v, i2, num) do { \
+ if (bytesperpixel == 1) { \
+ memset(&(c)[(i1)], (v)[(i2)], (num)); \
+ } else { \
+ int n, val = AV_RN16A(&(v)[(i2) * 2]); \
+ for (n = 0; n < (num); n++) { \
+ AV_WN16A(&(c)[((i1) + n) * 2], val); \
+ } \
+ } \
+} while (0)
+ memcpy(*a, top, n_px_have * bytesperpixel);
+ memset_bpp(*a, n_px_have, (*a), n_px_have - 1, n_px_need - n_px_have);
+ }
+ } else {
+#define memset_val(c, val, num) do { \
+ if (bytesperpixel == 1) { \
+ memset((c), (val), (num)); \
+ } else { \
+ int n; \
+ for (n = 0; n < (num); n++) { \
+ AV_WN16A(&(c)[n * 2], (val)); \
+ } \
+ } \
+} while (0)
+ memset_val(*a, (128 << (bpp - 8)) - 1, n_px_need);
+ }
+ if (edges[mode].needs_topleft) {
+ if (have_left && have_top) {
+#define assign_bpp(c, i1, v, i2) do { \
+ if (bytesperpixel == 1) { \
+ (c)[(i1)] = (v)[(i2)]; \
+ } else { \
+ AV_COPY16(&(c)[(i1) * 2], &(v)[(i2) * 2]); \
+ } \
+} while (0)
+ assign_bpp(*a, -1, topleft, -1);
+ } else {
+#define assign_val(c, i, v) do { \
+ if (bytesperpixel == 1) { \
+ (c)[(i)] = (v); \
+ } else { \
+ AV_WN16A(&(c)[(i) * 2], (v)); \
+ } \
+} while (0)
+ assign_val((*a), -1, (128 << (bpp - 8)) + (have_top ? +1 : -1));
+ }
+ }
+ if (tx == TX_4X4 && edges[mode].needs_topright) {
+ if (have_top && have_right &&
+ n_px_need + n_px_need_tr <= n_px_have) {
+ memcpy(&(*a)[4 * bytesperpixel], &top[4 * bytesperpixel], 4 * bytesperpixel);
+ } else {
+ memset_bpp(*a, 4, *a, 3, 4);
+ }
+ }
+ }
+ }
+ if (edges[mode].needs_left) {
+ if (have_left) {
+ int n_px_need = 4 << tx, i, n_px_have = (((s->rows - row) << !ss_v) - y) * 4;
+ uint8_t *dst = x == 0 ? dst_edge : dst_inner;
+ ptrdiff_t stride = x == 0 ? stride_edge : stride_inner;
+
+ if (edges[mode].invert_left) {
+ if (n_px_need <= n_px_have) {
+ for (i = 0; i < n_px_need; i++)
+ assign_bpp(l, i, &dst[i * stride], -1);
+ } else {
+ for (i = 0; i < n_px_have; i++)
+ assign_bpp(l, i, &dst[i * stride], -1);
+ memset_bpp(l, n_px_have, l, n_px_have - 1, n_px_need - n_px_have);
+ }
+ } else {
+ if (n_px_need <= n_px_have) {
+ for (i = 0; i < n_px_need; i++)
+ assign_bpp(l, n_px_need - 1 - i, &dst[i * stride], -1);
+ } else {
+ for (i = 0; i < n_px_have; i++)
+ assign_bpp(l, n_px_need - 1 - i, &dst[i * stride], -1);
+ memset_bpp(l, 0, l, n_px_need - n_px_have, n_px_need - n_px_have);
+ }
+ }
+ } else {
+ memset_val(l, (128 << (bpp - 8)) + 1, 4 << tx);
+ }
+ }
+
+ return mode;
+}
+
+static av_always_inline void intra_recon(VP9TileData *td, ptrdiff_t y_off,
+ ptrdiff_t uv_off, int bytesperpixel)
+{
+ VP9Context *s = td->s;
+ VP9Block *b = td->b;
+ int row = td->row, col = td->col;
+ int w4 = ff_vp9_bwh_tab[1][b->bs][0] << 1, step1d = 1 << b->tx, n;
+ int h4 = ff_vp9_bwh_tab[1][b->bs][1] << 1, x, y, step = 1 << (b->tx * 2);
+ int end_x = FFMIN(2 * (s->cols - col), w4);
+ int end_y = FFMIN(2 * (s->rows - row), h4);
+ int tx = 4 * s->s.h.lossless + b->tx, uvtx = b->uvtx + 4 * s->s.h.lossless;
+ int uvstep1d = 1 << b->uvtx, p;
+ uint8_t *dst = td->dst[0], *dst_r = s->s.frames[CUR_FRAME].tf.f->data[0] + y_off;
+ LOCAL_ALIGNED_32(uint8_t, a_buf, [96]);
+ LOCAL_ALIGNED_32(uint8_t, l, [64]);
+
+ for (n = 0, y = 0; y < end_y; y += step1d) {
+ uint8_t *ptr = dst, *ptr_r = dst_r;
+ for (x = 0; x < end_x; x += step1d, ptr += 4 * step1d * bytesperpixel,
+ ptr_r += 4 * step1d * bytesperpixel, n += step) {
+ int mode = b->mode[b->bs > BS_8x8 && b->tx == TX_4X4 ?
+ y * 2 + x : 0];
+ uint8_t *a = &a_buf[32];
+ enum TxfmType txtp = ff_vp9_intra_txfm_type[mode];
+ int eob = b->skip ? 0 : b->tx > TX_8X8 ? AV_RN16A(&td->eob[n]) : td->eob[n];
+
+ mode = check_intra_mode(td, mode, &a, ptr_r,
+ s->s.frames[CUR_FRAME].tf.f->linesize[0],
+ ptr, td->y_stride, l,
+ col, x, w4, row, y, b->tx, 0, 0, 0, bytesperpixel);
+ s->dsp.intra_pred[b->tx][mode](ptr, td->y_stride, l, a);
+ if (eob)
+ s->dsp.itxfm_add[tx][txtp](ptr, td->y_stride,
+ td->block + 16 * n * bytesperpixel, eob);
+ }
+ dst_r += 4 * step1d * s->s.frames[CUR_FRAME].tf.f->linesize[0];
+ dst += 4 * step1d * td->y_stride;
+ }
+
+ // U/V
+ w4 >>= s->ss_h;
+ end_x >>= s->ss_h;
+ end_y >>= s->ss_v;
+ step = 1 << (b->uvtx * 2);
+ for (p = 0; p < 2; p++) {
+ dst = td->dst[1 + p];
+ dst_r = s->s.frames[CUR_FRAME].tf.f->data[1 + p] + uv_off;
+ for (n = 0, y = 0; y < end_y; y += uvstep1d) {
+ uint8_t *ptr = dst, *ptr_r = dst_r;
+ for (x = 0; x < end_x; x += uvstep1d, ptr += 4 * uvstep1d * bytesperpixel,
+ ptr_r += 4 * uvstep1d * bytesperpixel, n += step) {
+ int mode = b->uvmode;
+ uint8_t *a = &a_buf[32];
+ int eob = b->skip ? 0 : b->uvtx > TX_8X8 ? AV_RN16A(&td->uveob[p][n]) : td->uveob[p][n];
+
+ mode = check_intra_mode(td, mode, &a, ptr_r,
+ s->s.frames[CUR_FRAME].tf.f->linesize[1],
+ ptr, td->uv_stride, l, col, x, w4, row, y,
+ b->uvtx, p + 1, s->ss_h, s->ss_v, bytesperpixel);
+ s->dsp.intra_pred[b->uvtx][mode](ptr, td->uv_stride, l, a);
+ if (eob)
+ s->dsp.itxfm_add[uvtx][DCT_DCT](ptr, td->uv_stride,
+ td->uvblock[p] + 16 * n * bytesperpixel, eob);
+ }
+ dst_r += 4 * uvstep1d * s->s.frames[CUR_FRAME].tf.f->linesize[1];
+ dst += 4 * uvstep1d * td->uv_stride;
+ }
+ }
+}
+
+void ff_vp9_intra_recon_8bpp(VP9TileData *td, ptrdiff_t y_off, ptrdiff_t uv_off)
+{
+ intra_recon(td, y_off, uv_off, 1);
+}
+
+void ff_vp9_intra_recon_16bpp(VP9TileData *td, ptrdiff_t y_off, ptrdiff_t uv_off)
+{
+ intra_recon(td, y_off, uv_off, 2);
+}
+
+static av_always_inline void mc_luma_unscaled(VP9TileData *td, vp9_mc_func (*mc)[2],
+ uint8_t *dst, ptrdiff_t dst_stride,
+ const uint8_t *ref, ptrdiff_t ref_stride,
+ ThreadFrame *ref_frame,
+ ptrdiff_t y, ptrdiff_t x, const VP56mv *mv,
+ int bw, int bh, int w, int h, int bytesperpixel)
+{
+ VP9Context *s = td->s;
+ int mx = mv->x, my = mv->y, th;
+
+ y += my >> 3;
+ x += mx >> 3;
+ ref += y * ref_stride + x * bytesperpixel;
+ mx &= 7;
+ my &= 7;
+ // FIXME bilinear filter only needs 0/1 pixels, not 3/4
+ // we use +7 because the last 7 pixels of each sbrow can be changed in
+ // the longest loopfilter of the next sbrow
+ th = (y + bh + 4 * !!my + 7) >> 6;
+ ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);
+ // The arm/aarch64 _hv filters read one more row than what actually is
+ // needed, so switch to emulated edge one pixel sooner vertically
+ // (!!my * 5) than horizontally (!!mx * 4).
+ if (x < !!mx * 3 || y < !!my * 3 ||
+ x + !!mx * 4 > w - bw || y + !!my * 5 > h - bh) {
+ s->vdsp.emulated_edge_mc(td->edge_emu_buffer,
+ ref - !!my * 3 * ref_stride - !!mx * 3 * bytesperpixel,
+ 160, ref_stride,
+ bw + !!mx * 7, bh + !!my * 7,
+ x - !!mx * 3, y - !!my * 3, w, h);
+ ref = td->edge_emu_buffer + !!my * 3 * 160 + !!mx * 3 * bytesperpixel;
+ ref_stride = 160;
+ }
+ mc[!!mx][!!my](dst, dst_stride, ref, ref_stride, bh, mx << 1, my << 1);
+}
+
+static av_always_inline void mc_chroma_unscaled(VP9TileData *td, vp9_mc_func (*mc)[2],
+ uint8_t *dst_u, uint8_t *dst_v,
+ ptrdiff_t dst_stride,
+ const uint8_t *ref_u, ptrdiff_t src_stride_u,
+ const uint8_t *ref_v, ptrdiff_t src_stride_v,
+ ThreadFrame *ref_frame,
+ ptrdiff_t y, ptrdiff_t x, const VP56mv *mv,
+ int bw, int bh, int w, int h, int bytesperpixel)
+{
+ VP9Context *s = td->s;
+ int mx = mv->x * (1 << !s->ss_h), my = mv->y * (1 << !s->ss_v), th;
+
+ y += my >> 4;
+ x += mx >> 4;
+ ref_u += y * src_stride_u + x * bytesperpixel;
+ ref_v += y * src_stride_v + x * bytesperpixel;
+ mx &= 15;
+ my &= 15;
+ // FIXME bilinear filter only needs 0/1 pixels, not 3/4
+ // we use +7 because the last 7 pixels of each sbrow can be changed in
+ // the longest loopfilter of the next sbrow
+ th = (y + bh + 4 * !!my + 7) >> (6 - s->ss_v);
+ ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);
+ // The arm/aarch64 _hv filters read one more row than what actually is
+ // needed, so switch to emulated edge one pixel sooner vertically
+ // (!!my * 5) than horizontally (!!mx * 4).
+ if (x < !!mx * 3 || y < !!my * 3 ||
+ x + !!mx * 4 > w - bw || y + !!my * 5 > h - bh) {
+ s->vdsp.emulated_edge_mc(td->edge_emu_buffer,
+ ref_u - !!my * 3 * src_stride_u - !!mx * 3 * bytesperpixel,
+ 160, src_stride_u,
+ bw + !!mx * 7, bh + !!my * 7,
+ x - !!mx * 3, y - !!my * 3, w, h);
+ ref_u = td->edge_emu_buffer + !!my * 3 * 160 + !!mx * 3 * bytesperpixel;
+ mc[!!mx][!!my](dst_u, dst_stride, ref_u, 160, bh, mx, my);
+
+ s->vdsp.emulated_edge_mc(td->edge_emu_buffer,
+ ref_v - !!my * 3 * src_stride_v - !!mx * 3 * bytesperpixel,
+ 160, src_stride_v,
+ bw + !!mx * 7, bh + !!my * 7,
+ x - !!mx * 3, y - !!my * 3, w, h);
+ ref_v = td->edge_emu_buffer + !!my * 3 * 160 + !!mx * 3 * bytesperpixel;
+ mc[!!mx][!!my](dst_v, dst_stride, ref_v, 160, bh, mx, my);
+ } else {
+ mc[!!mx][!!my](dst_u, dst_stride, ref_u, src_stride_u, bh, mx, my);
+ mc[!!mx][!!my](dst_v, dst_stride, ref_v, src_stride_v, bh, mx, my);
+ }
+}
+
+#define mc_luma_dir(td, mc, dst, dst_ls, src, src_ls, tref, row, col, mv, \
+ px, py, pw, ph, bw, bh, w, h, i) \
+ mc_luma_unscaled(td, s->dsp.mc, dst, dst_ls, src, src_ls, tref, row, col, \
+ mv, bw, bh, w, h, bytesperpixel)
+#define mc_chroma_dir(td, mc, dstu, dstv, dst_ls, srcu, srcu_ls, srcv, srcv_ls, tref, \
+ row, col, mv, px, py, pw, ph, bw, bh, w, h, i) \
+ mc_chroma_unscaled(td, s->dsp.mc, dstu, dstv, dst_ls, srcu, srcu_ls, srcv, srcv_ls, tref, \
+ row, col, mv, bw, bh, w, h, bytesperpixel)
+#define SCALED 0
+#define FN(x) x##_8bpp
+#define BYTES_PER_PIXEL 1
+#include "vp9_mc_template.c"
+#undef FN
+#undef BYTES_PER_PIXEL
+#define FN(x) x##_16bpp
+#define BYTES_PER_PIXEL 2
+#include "vp9_mc_template.c"
+#undef mc_luma_dir
+#undef mc_chroma_dir
+#undef FN
+#undef BYTES_PER_PIXEL
+#undef SCALED
+
+static av_always_inline void mc_luma_scaled(VP9TileData *td, vp9_scaled_mc_func smc,
+ vp9_mc_func (*mc)[2],
+ uint8_t *dst, ptrdiff_t dst_stride,
+ const uint8_t *ref, ptrdiff_t ref_stride,
+ ThreadFrame *ref_frame,
+ ptrdiff_t y, ptrdiff_t x, const VP56mv *in_mv,
+ int px, int py, int pw, int ph,
+ int bw, int bh, int w, int h, int bytesperpixel,
+ const uint16_t *scale, const uint8_t *step)
+{
+ VP9Context *s = td->s;
+ if (s->s.frames[CUR_FRAME].tf.f->width == ref_frame->f->width &&
+ s->s.frames[CUR_FRAME].tf.f->height == ref_frame->f->height) {
+ mc_luma_unscaled(td, mc, dst, dst_stride, ref, ref_stride, ref_frame,
+ y, x, in_mv, bw, bh, w, h, bytesperpixel);
+ } else {
+#define scale_mv(n, dim) (((int64_t)(n) * scale[dim]) >> 14)
+ int mx, my;
+ int refbw_m1, refbh_m1;
+ int th;
+ VP56mv mv;
+
+ mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 8, (s->cols * 8 - x + px + 3) * 8);
+ mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 8, (s->rows * 8 - y + py + 3) * 8);
+ // BUG libvpx seems to scale the two components separately. This introduces
+ // rounding errors but we have to reproduce them to be exactly compatible
+ // with the output from libvpx...
+ mx = scale_mv(mv.x * 2, 0) + scale_mv(x * 16, 0);
+ my = scale_mv(mv.y * 2, 1) + scale_mv(y * 16, 1);
+
+ y = my >> 4;
+ x = mx >> 4;
+ ref += y * ref_stride + x * bytesperpixel;
+ mx &= 15;
+ my &= 15;
+ refbw_m1 = ((bw - 1) * step[0] + mx) >> 4;
+ refbh_m1 = ((bh - 1) * step[1] + my) >> 4;
+ // FIXME bilinear filter only needs 0/1 pixels, not 3/4
+ // we use +7 because the last 7 pixels of each sbrow can be changed in
+ // the longest loopfilter of the next sbrow
+ th = (y + refbh_m1 + 4 + 7) >> 6;
+ ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);
+ // The arm/aarch64 _hv filters read one more row than what actually is
+ // needed, so switch to emulated edge one pixel sooner vertically
+ // (y + 5 >= h - refbh_m1) than horizontally (x + 4 >= w - refbw_m1).
+ if (x < 3 || y < 3 || x + 4 >= w - refbw_m1 || y + 5 >= h - refbh_m1) {
+ s->vdsp.emulated_edge_mc(td->edge_emu_buffer,
+ ref - 3 * ref_stride - 3 * bytesperpixel,
+ 288, ref_stride,
+ refbw_m1 + 8, refbh_m1 + 8,
+ x - 3, y - 3, w, h);
+ ref = td->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;
+ ref_stride = 288;
+ }
+ smc(dst, dst_stride, ref, ref_stride, bh, mx, my, step[0], step[1]);
+ }
+}
+
+static av_always_inline void mc_chroma_scaled(VP9TileData *td, vp9_scaled_mc_func smc,
+ vp9_mc_func (*mc)[2],
+ uint8_t *dst_u, uint8_t *dst_v,
+ ptrdiff_t dst_stride,
+ const uint8_t *ref_u, ptrdiff_t src_stride_u,
+ const uint8_t *ref_v, ptrdiff_t src_stride_v,
+ ThreadFrame *ref_frame,
+ ptrdiff_t y, ptrdiff_t x, const VP56mv *in_mv,
+ int px, int py, int pw, int ph,
+ int bw, int bh, int w, int h, int bytesperpixel,
+ const uint16_t *scale, const uint8_t *step)
+{
+ VP9Context *s = td->s;
+ if (s->s.frames[CUR_FRAME].tf.f->width == ref_frame->f->width &&
+ s->s.frames[CUR_FRAME].tf.f->height == ref_frame->f->height) {
+ mc_chroma_unscaled(td, mc, dst_u, dst_v, dst_stride, ref_u, src_stride_u,
+ ref_v, src_stride_v, ref_frame,
+ y, x, in_mv, bw, bh, w, h, bytesperpixel);
+ } else {
+ int mx, my;
+ int refbw_m1, refbh_m1;
+ int th;
+ VP56mv mv;
+
+ if (s->ss_h) {
+ // BUG https://code.google.com/p/webm/issues/detail?id=820
+ mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 16, (s->cols * 4 - x + px + 3) * 16);
+ mx = scale_mv(mv.x, 0) + (scale_mv(x * 16, 0) & ~15) + (scale_mv(x * 32, 0) & 15);
+ } else {
+ mv.x = av_clip(in_mv->x, -(x + pw - px + 4) * 8, (s->cols * 8 - x + px + 3) * 8);
+ mx = scale_mv(mv.x * 2, 0) + scale_mv(x * 16, 0);
+ }
+ if (s->ss_v) {
+ // BUG https://code.google.com/p/webm/issues/detail?id=820
+ mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 16, (s->rows * 4 - y + py + 3) * 16);
+ my = scale_mv(mv.y, 1) + (scale_mv(y * 16, 1) & ~15) + (scale_mv(y * 32, 1) & 15);
+ } else {
+ mv.y = av_clip(in_mv->y, -(y + ph - py + 4) * 8, (s->rows * 8 - y + py + 3) * 8);
+ my = scale_mv(mv.y * 2, 1) + scale_mv(y * 16, 1);
+ }
+#undef scale_mv
+ y = my >> 4;
+ x = mx >> 4;
+ ref_u += y * src_stride_u + x * bytesperpixel;
+ ref_v += y * src_stride_v + x * bytesperpixel;
+ mx &= 15;
+ my &= 15;
+ refbw_m1 = ((bw - 1) * step[0] + mx) >> 4;
+ refbh_m1 = ((bh - 1) * step[1] + my) >> 4;
+ // FIXME bilinear filter only needs 0/1 pixels, not 3/4
+ // we use +7 because the last 7 pixels of each sbrow can be changed in
+ // the longest loopfilter of the next sbrow
+ th = (y + refbh_m1 + 4 + 7) >> (6 - s->ss_v);
+ ff_thread_await_progress(ref_frame, FFMAX(th, 0), 0);
+ // The arm/aarch64 _hv filters read one more row than what actually is
+ // needed, so switch to emulated edge one pixel sooner vertically
+ // (y + 5 >= h - refbh_m1) than horizontally (x + 4 >= w - refbw_m1).
+ if (x < 3 || y < 3 || x + 4 >= w - refbw_m1 || y + 5 >= h - refbh_m1) {
+ s->vdsp.emulated_edge_mc(td->edge_emu_buffer,
+ ref_u - 3 * src_stride_u - 3 * bytesperpixel,
+ 288, src_stride_u,
+ refbw_m1 + 8, refbh_m1 + 8,
+ x - 3, y - 3, w, h);
+ ref_u = td->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;
+ smc(dst_u, dst_stride, ref_u, 288, bh, mx, my, step[0], step[1]);
+
+ s->vdsp.emulated_edge_mc(td->edge_emu_buffer,
+ ref_v - 3 * src_stride_v - 3 * bytesperpixel,
+ 288, src_stride_v,
+ refbw_m1 + 8, refbh_m1 + 8,
+ x - 3, y - 3, w, h);
+ ref_v = td->edge_emu_buffer + 3 * 288 + 3 * bytesperpixel;
+ smc(dst_v, dst_stride, ref_v, 288, bh, mx, my, step[0], step[1]);
+ } else {
+ smc(dst_u, dst_stride, ref_u, src_stride_u, bh, mx, my, step[0], step[1]);
+ smc(dst_v, dst_stride, ref_v, src_stride_v, bh, mx, my, step[0], step[1]);
+ }
+ }
+}
+
+#define mc_luma_dir(td, mc, dst, dst_ls, src, src_ls, tref, row, col, mv, \
+ px, py, pw, ph, bw, bh, w, h, i) \
+ mc_luma_scaled(td, s->dsp.s##mc, s->dsp.mc, dst, dst_ls, src, src_ls, tref, row, col, \
+ mv, px, py, pw, ph, bw, bh, w, h, bytesperpixel, \
+ s->mvscale[b->ref[i]], s->mvstep[b->ref[i]])
+#define mc_chroma_dir(td, mc, dstu, dstv, dst_ls, srcu, srcu_ls, srcv, srcv_ls, tref, \
+ row, col, mv, px, py, pw, ph, bw, bh, w, h, i) \
+ mc_chroma_scaled(td, s->dsp.s##mc, s->dsp.mc, dstu, dstv, dst_ls, srcu, srcu_ls, srcv, srcv_ls, tref, \
+ row, col, mv, px, py, pw, ph, bw, bh, w, h, bytesperpixel, \
+ s->mvscale[b->ref[i]], s->mvstep[b->ref[i]])
+#define SCALED 1
+#define FN(x) x##_scaled_8bpp
+#define BYTES_PER_PIXEL 1
+#include "vp9_mc_template.c"
+#undef FN
+#undef BYTES_PER_PIXEL
+#define FN(x) x##_scaled_16bpp
+#define BYTES_PER_PIXEL 2
+#include "vp9_mc_template.c"
+#undef mc_luma_dir
+#undef mc_chroma_dir
+#undef FN
+#undef BYTES_PER_PIXEL
+#undef SCALED
+
+static av_always_inline void inter_recon(VP9TileData *td, int bytesperpixel)
+{
+ VP9Context *s = td->s;
+ VP9Block *b = td->b;
+ int row = td->row, col = td->col;
+
+ if (s->mvscale[b->ref[0]][0] || (b->comp && s->mvscale[b->ref[1]][0])) {
+ if (bytesperpixel == 1) {
+ inter_pred_scaled_8bpp(td);
+ } else {
+ inter_pred_scaled_16bpp(td);
+ }
+ } else {
+ if (bytesperpixel == 1) {
+ inter_pred_8bpp(td);
+ } else {
+ inter_pred_16bpp(td);
+ }
+ }
+
+ if (!b->skip) {
+ /* mostly copied intra_recon() */
+
+ int w4 = ff_vp9_bwh_tab[1][b->bs][0] << 1, step1d = 1 << b->tx, n;
+ int h4 = ff_vp9_bwh_tab[1][b->bs][1] << 1, x, y, step = 1 << (b->tx * 2);
+ int end_x = FFMIN(2 * (s->cols - col), w4);
+ int end_y = FFMIN(2 * (s->rows - row), h4);
+ int tx = 4 * s->s.h.lossless + b->tx, uvtx = b->uvtx + 4 * s->s.h.lossless;
+ int uvstep1d = 1 << b->uvtx, p;
+ uint8_t *dst = td->dst[0];
+
+ // y itxfm add
+ for (n = 0, y = 0; y < end_y; y += step1d) {
+ uint8_t *ptr = dst;
+ for (x = 0; x < end_x; x += step1d,
+ ptr += 4 * step1d * bytesperpixel, n += step) {
+ int eob = b->tx > TX_8X8 ? AV_RN16A(&td->eob[n]) : td->eob[n];
+
+ if (eob)
+ s->dsp.itxfm_add[tx][DCT_DCT](ptr, td->y_stride,
+ td->block + 16 * n * bytesperpixel, eob);
+ }
+ dst += 4 * td->y_stride * step1d;
+ }
+
+ // uv itxfm add
+ end_x >>= s->ss_h;
+ end_y >>= s->ss_v;
+ step = 1 << (b->uvtx * 2);
+ for (p = 0; p < 2; p++) {
+ dst = td->dst[p + 1];
+ for (n = 0, y = 0; y < end_y; y += uvstep1d) {
+ uint8_t *ptr = dst;
+ for (x = 0; x < end_x; x += uvstep1d,
+ ptr += 4 * uvstep1d * bytesperpixel, n += step) {
+ int eob = b->uvtx > TX_8X8 ? AV_RN16A(&td->uveob[p][n]) : td->uveob[p][n];
+
+ if (eob)
+ s->dsp.itxfm_add[uvtx][DCT_DCT](ptr, td->uv_stride,
+ td->uvblock[p] + 16 * n * bytesperpixel, eob);
+ }
+ dst += 4 * uvstep1d * td->uv_stride;
+ }
+ }
+ }
+}
+
+void ff_vp9_inter_recon_8bpp(VP9TileData *td)
+{
+ inter_recon(td, 1);
+}
+
+void ff_vp9_inter_recon_16bpp(VP9TileData *td)
+{
+ inter_recon(td, 2);
+}
diff --git a/media/ffvpx/libavcodec/vp9shared.h b/media/ffvpx/libavcodec/vp9shared.h
new file mode 100644
index 000000000..54726df74
--- /dev/null
+++ b/media/ffvpx/libavcodec/vp9shared.h
@@ -0,0 +1,169 @@
+/*
+ * VP9 compatible video decoder
+ *
+ * Copyright (C) 2013 Ronald S. Bultje <rsbultje gmail com>
+ * Copyright (C) 2013 Clément Bœsch <u pkh me>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVCODEC_VP9SHARED_H
+#define AVCODEC_VP9SHARED_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "vp9.h"
+#include "thread.h"
+#include "vp56.h"
+
+enum BlockPartition {
+ PARTITION_NONE, // [ ] <-.
+ PARTITION_H, // [-] |
+ PARTITION_V, // [|] |
+ PARTITION_SPLIT, // [+] --'
+};
+
+enum InterPredMode {
+ NEARESTMV = 10,
+ NEARMV = 11,
+ ZEROMV = 12,
+ NEWMV = 13,
+};
+
+enum CompPredMode {
+ PRED_SINGLEREF,
+ PRED_COMPREF,
+ PRED_SWITCHABLE,
+};
+
+typedef struct VP9mvrefPair {
+ VP56mv mv[2];
+ int8_t ref[2];
+} VP9mvrefPair;
+
+typedef struct VP9Frame {
+ ThreadFrame tf;
+ AVBufferRef *extradata;
+ uint8_t *segmentation_map;
+ VP9mvrefPair *mv;
+ int uses_2pass;
+
+ AVBufferRef *hwaccel_priv_buf;
+ void *hwaccel_picture_private;
+} VP9Frame;
+
+enum BlockLevel {
+ BL_64X64,
+ BL_32X32,
+ BL_16X16,
+ BL_8X8,
+};
+
+enum BlockSize {
+ BS_64x64,
+ BS_64x32,
+ BS_32x64,
+ BS_32x32,
+ BS_32x16,
+ BS_16x32,
+ BS_16x16,
+ BS_16x8,
+ BS_8x16,
+ BS_8x8,
+ BS_8x4,
+ BS_4x8,
+ BS_4x4,
+ N_BS_SIZES,
+};
+
+typedef struct VP9BitstreamHeader {
+ // bitstream header
+ uint8_t profile;
+ uint8_t bpp;
+ uint8_t keyframe;
+ uint8_t invisible;
+ uint8_t errorres;
+ uint8_t intraonly;
+ uint8_t resetctx;
+ uint8_t refreshrefmask;
+ uint8_t highprecisionmvs;
+ enum FilterMode filtermode;
+ uint8_t allowcompinter;
+ uint8_t refreshctx;
+ uint8_t parallelmode;
+ uint8_t framectxid;
+ uint8_t use_last_frame_mvs;
+ uint8_t refidx[3];
+ uint8_t signbias[3];
+ uint8_t fixcompref;
+ uint8_t varcompref[2];
+ struct {
+ uint8_t level;
+ int8_t sharpness;
+ } filter;
+ struct {
+ uint8_t enabled;
+ uint8_t updated;
+ int8_t mode[2];
+ int8_t ref[4];
+ } lf_delta;
+ uint8_t yac_qi;
+ int8_t ydc_qdelta, uvdc_qdelta, uvac_qdelta;
+ uint8_t lossless;
+#define MAX_SEGMENT 8
+ struct {
+ uint8_t enabled;
+ uint8_t temporal;
+ uint8_t absolute_vals;
+ uint8_t update_map;
+ uint8_t prob[7];
+ uint8_t pred_prob[3];
+ struct {
+ uint8_t q_enabled;
+ uint8_t lf_enabled;
+ uint8_t ref_enabled;
+ uint8_t skip_enabled;
+ uint8_t ref_val;
+ int16_t q_val;
+ int8_t lf_val;
+ int16_t qmul[2][2];
+ uint8_t lflvl[4][2];
+ } feat[MAX_SEGMENT];
+ } segmentation;
+ enum TxfmMode txfmmode;
+ enum CompPredMode comppredmode;
+ struct {
+ unsigned log2_tile_cols, log2_tile_rows;
+ unsigned tile_cols, tile_rows;
+ } tiling;
+
+ int uncompressed_header_size;
+ int compressed_header_size;
+} VP9BitstreamHeader;
+
+typedef struct VP9SharedContext {
+ VP9BitstreamHeader h;
+
+ ThreadFrame refs[8];
+#define CUR_FRAME 0
+#define REF_FRAME_MVPAIR 1
+#define REF_FRAME_SEGMAP 2
+ VP9Frame frames[3];
+} VP9SharedContext;
+
+#endif /* AVCODEC_VP9SHARED_H */
diff --git a/media/ffvpx/libavcodec/x86/constants.h b/media/ffvpx/libavcodec/x86/constants.h
index b82aef9a4..bbb0ef844 100644
--- a/media/ffvpx/libavcodec/x86/constants.h
+++ b/media/ffvpx/libavcodec/x86/constants.h
@@ -43,6 +43,7 @@ extern const xmm_reg ff_pw_64;
extern const uint64_t ff_pw_96;
extern const uint64_t ff_pw_128;
extern const ymm_reg ff_pw_255;
+extern const ymm_reg ff_pw_256;
extern const ymm_reg ff_pw_512;
extern const ymm_reg ff_pw_1023;
extern const ymm_reg ff_pw_1024;
diff --git a/media/ffvpx/libavcodec/x86/flacdsp_init.c b/media/ffvpx/libavcodec/x86/flacdsp_init.c
index e28c5c932..1971f81b8 100644
--- a/media/ffvpx/libavcodec/x86/flacdsp_init.c
+++ b/media/ffvpx/libavcodec/x86/flacdsp_init.c
@@ -53,7 +53,7 @@ DECORRELATE_FUNCS(32, avx);
av_cold void ff_flacdsp_init_x86(FLACDSPContext *c, enum AVSampleFormat fmt, int channels,
int bps)
{
-#if HAVE_YASM
+#if HAVE_X86ASM
int cpu_flags = av_get_cpu_flags();
#if CONFIG_FLAC_DECODER
@@ -111,5 +111,5 @@ av_cold void ff_flacdsp_init_x86(FLACDSPContext *c, enum AVSampleFormat fmt, int
c->lpc16_encode = ff_flac_enc_lpc_16_sse4;
}
#endif
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
}
diff --git a/media/ffvpx/libavcodec/x86/h264_i386.h b/media/ffvpx/libavcodec/x86/h264_i386.h
deleted file mode 100644
index 19cd12838..000000000
--- a/media/ffvpx/libavcodec/x86/h264_i386.h
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * H.26L/H.264/AVC/JVT/14496-10/... encoder/decoder
- * Copyright (c) 2003 Michael Niedermayer <michaelni@gmx.at>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-/**
- * @file
- * H.264 / AVC / MPEG-4 part10 codec.
- * non-MMX i386-specific optimizations for H.264
- * @author Michael Niedermayer <michaelni@gmx.at>
- */
-
-#ifndef AVCODEC_X86_H264_I386_H
-#define AVCODEC_X86_H264_I386_H
-
-#include <stddef.h>
-
-#include "libavcodec/cabac.h"
-#include "cabac.h"
-
-#if HAVE_INLINE_ASM
-
-#if ARCH_X86_64
-#define REG64 "r"
-#else
-#define REG64 "m"
-#endif
-
-//FIXME use some macros to avoid duplicating get_cabac (cannot be done yet
-//as that would make optimization work hard)
-#if HAVE_7REGS && !BROKEN_COMPILER
-#define decode_significance decode_significance_x86
-static int decode_significance_x86(CABACContext *c, int max_coeff,
- uint8_t *significant_coeff_ctx_base,
- int *index, x86_reg last_off){
- void *end= significant_coeff_ctx_base + max_coeff - 1;
- int minusstart= -(intptr_t)significant_coeff_ctx_base;
- int minusindex= 4-(intptr_t)index;
- int bit;
- x86_reg coeff_count;
-
-#ifdef BROKEN_RELOCATIONS
- void *tables;
-
- __asm__ volatile(
- "lea "MANGLE(ff_h264_cabac_tables)", %0 \n\t"
- : "=&r"(tables)
- : NAMED_CONSTRAINTS_ARRAY(ff_h264_cabac_tables)
- );
-#endif
-
- __asm__ volatile(
- "3: \n\t"
-
- BRANCHLESS_GET_CABAC("%4", "%q4", "(%1)", "%3", "%w3",
- "%5", "%q5", "%k0", "%b0",
- "%c11(%6)", "%c12(%6)",
- AV_STRINGIFY(H264_NORM_SHIFT_OFFSET),
- AV_STRINGIFY(H264_LPS_RANGE_OFFSET),
- AV_STRINGIFY(H264_MLPS_STATE_OFFSET),
- "%13")
-
- "test $1, %4 \n\t"
- " jz 4f \n\t"
- "add %10, %1 \n\t"
-
- BRANCHLESS_GET_CABAC("%4", "%q4", "(%1)", "%3", "%w3",
- "%5", "%q5", "%k0", "%b0",
- "%c11(%6)", "%c12(%6)",
- AV_STRINGIFY(H264_NORM_SHIFT_OFFSET),
- AV_STRINGIFY(H264_LPS_RANGE_OFFSET),
- AV_STRINGIFY(H264_MLPS_STATE_OFFSET),
- "%13")
-
- "sub %10, %1 \n\t"
- "mov %2, %0 \n\t"
- "movl %7, %%ecx \n\t"
- "add %1, %%"FF_REG_c" \n\t"
- "movl %%ecx, (%0) \n\t"
-
- "test $1, %4 \n\t"
- " jnz 5f \n\t"
-
- "add"FF_OPSIZE" $4, %2 \n\t"
-
- "4: \n\t"
- "add $1, %1 \n\t"
- "cmp %8, %1 \n\t"
- " jb 3b \n\t"
- "mov %2, %0 \n\t"
- "movl %7, %%ecx \n\t"
- "add %1, %%"FF_REG_c" \n\t"
- "movl %%ecx, (%0) \n\t"
- "5: \n\t"
- "add %9, %k0 \n\t"
- "shr $2, %k0 \n\t"
- : "=&q"(coeff_count), "+r"(significant_coeff_ctx_base), "+m"(index),
- "+&r"(c->low), "=&r"(bit), "+&r"(c->range)
- : "r"(c), "m"(minusstart), "m"(end), "m"(minusindex), "m"(last_off),
- "i"(offsetof(CABACContext, bytestream)),
- "i"(offsetof(CABACContext, bytestream_end))
- TABLES_ARG
- : "%"FF_REG_c, "memory"
- );
- return coeff_count;
-}
-
-#define decode_significance_8x8 decode_significance_8x8_x86
-static int decode_significance_8x8_x86(CABACContext *c,
- uint8_t *significant_coeff_ctx_base,
- int *index, uint8_t *last_coeff_ctx_base, const uint8_t *sig_off){
- int minusindex= 4-(intptr_t)index;
- int bit;
- x86_reg coeff_count;
- x86_reg last=0;
- x86_reg state;
-
-#ifdef BROKEN_RELOCATIONS
- void *tables;
-
- __asm__ volatile(
- "lea "MANGLE(ff_h264_cabac_tables)", %0 \n\t"
- : "=&r"(tables)
- : NAMED_CONSTRAINTS_ARRAY(ff_h264_cabac_tables)
- );
-#endif
-
- __asm__ volatile(
- "mov %1, %6 \n\t"
- "3: \n\t"
-
- "mov %10, %0 \n\t"
- "movzb (%0, %6), %6 \n\t"
- "add %9, %6 \n\t"
-
- BRANCHLESS_GET_CABAC("%4", "%q4", "(%6)", "%3", "%w3",
- "%5", "%q5", "%k0", "%b0",
- "%c12(%7)", "%c13(%7)",
- AV_STRINGIFY(H264_NORM_SHIFT_OFFSET),
- AV_STRINGIFY(H264_LPS_RANGE_OFFSET),
- AV_STRINGIFY(H264_MLPS_STATE_OFFSET),
- "%15")
-
- "mov %1, %6 \n\t"
- "test $1, %4 \n\t"
- " jz 4f \n\t"
-
-#ifdef BROKEN_RELOCATIONS
- "movzb %c14(%15, %q6), %6\n\t"
-#else
- "movzb "MANGLE(ff_h264_cabac_tables)"+%c14(%6), %6\n\t"
-#endif
- "add %11, %6 \n\t"
-
- BRANCHLESS_GET_CABAC("%4", "%q4", "(%6)", "%3", "%w3",
- "%5", "%q5", "%k0", "%b0",
- "%c12(%7)", "%c13(%7)",
- AV_STRINGIFY(H264_NORM_SHIFT_OFFSET),
- AV_STRINGIFY(H264_LPS_RANGE_OFFSET),
- AV_STRINGIFY(H264_MLPS_STATE_OFFSET),
- "%15")
-
- "mov %2, %0 \n\t"
- "mov %1, %6 \n\t"
- "mov %k6, (%0) \n\t"
-
- "test $1, %4 \n\t"
- " jnz 5f \n\t"
-
- "add"FF_OPSIZE" $4, %2 \n\t"
-
- "4: \n\t"
- "add $1, %6 \n\t"
- "mov %6, %1 \n\t"
- "cmp $63, %6 \n\t"
- " jb 3b \n\t"
- "mov %2, %0 \n\t"
- "mov %k6, (%0) \n\t"
- "5: \n\t"
- "addl %8, %k0 \n\t"
- "shr $2, %k0 \n\t"
- : "=&q"(coeff_count), "+"REG64(last), "+"REG64(index), "+&r"(c->low),
- "=&r"(bit), "+&r"(c->range), "=&r"(state)
- : "r"(c), "m"(minusindex), "m"(significant_coeff_ctx_base),
- REG64(sig_off), REG64(last_coeff_ctx_base),
- "i"(offsetof(CABACContext, bytestream)),
- "i"(offsetof(CABACContext, bytestream_end)),
- "i"(H264_LAST_COEFF_FLAG_OFFSET_8x8_OFFSET) TABLES_ARG
- : "%"FF_REG_c, "memory"
- );
- return coeff_count;
-}
-#endif /* HAVE_7REGS && BROKEN_COMPILER */
-
-#endif /* HAVE_INLINE_ASM */
-#endif /* AVCODEC_X86_H264_I386_H */
diff --git a/media/ffvpx/libavcodec/x86/h264_intrapred.asm b/media/ffvpx/libavcodec/x86/h264_intrapred.asm
index c88d91b49..f3aa3172f 100644
--- a/media/ffvpx/libavcodec/x86/h264_intrapred.asm
+++ b/media/ffvpx/libavcodec/x86/h264_intrapred.asm
@@ -49,7 +49,7 @@ cextern pw_17
cextern pw_32
;-----------------------------------------------------------------------------
-; void ff_pred16x16_vertical_8(uint8_t *src, int stride)
+; void ff_pred16x16_vertical_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmx
@@ -85,7 +85,7 @@ cglobal pred16x16_vertical_8, 2,3
REP_RET
;-----------------------------------------------------------------------------
-; void ff_pred16x16_horizontal_8(uint8_t *src, int stride)
+; void ff_pred16x16_horizontal_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_H 0
@@ -126,7 +126,7 @@ INIT_XMM ssse3
PRED16x16_H
;-----------------------------------------------------------------------------
-; void ff_pred16x16_dc_8(uint8_t *src, int stride)
+; void ff_pred16x16_dc_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_DC 0
@@ -188,7 +188,7 @@ INIT_XMM ssse3
PRED16x16_DC
;-----------------------------------------------------------------------------
-; void ff_pred16x16_tm_vp8_8(uint8_t *src, int stride)
+; void ff_pred16x16_tm_vp8_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_TM 0
@@ -268,8 +268,45 @@ cglobal pred16x16_tm_vp8_8, 2,6,6
jg .loop
REP_RET
+%if HAVE_AVX2_EXTERNAL
+INIT_YMM avx2
+cglobal pred16x16_tm_vp8_8, 2, 4, 5, dst, stride, stride3, iteration
+ sub dstq, strideq
+ pmovzxbw m0, [dstq]
+ vpbroadcastb xm1, [r0-1]
+ pmovzxbw m1, xm1
+ psubw m0, m1
+ mov iterationd, 4
+ lea stride3q, [strideq*3]
+.loop:
+ vpbroadcastb xm1, [dstq+strideq*1-1]
+ vpbroadcastb xm2, [dstq+strideq*2-1]
+ vpbroadcastb xm3, [dstq+stride3q-1]
+ vpbroadcastb xm4, [dstq+strideq*4-1]
+ pmovzxbw m1, xm1
+ pmovzxbw m2, xm2
+ pmovzxbw m3, xm3
+ pmovzxbw m4, xm4
+ paddw m1, m0
+ paddw m2, m0
+ paddw m3, m0
+ paddw m4, m0
+ vpackuswb m1, m1, m2
+ vpackuswb m3, m3, m4
+ vpermq m1, m1, q3120
+ vpermq m3, m3, q3120
+ movdqa [dstq+strideq*1], xm1
+ vextracti128 [dstq+strideq*2], m1, 1
+ movdqa [dstq+stride3q*1], xm3
+ vextracti128 [dstq+strideq*4], m3, 1
+ lea dstq, [dstq+strideq*4]
+ dec iterationd
+ jg .loop
+ REP_RET
+%endif
+
;-----------------------------------------------------------------------------
-; void ff_pred16x16_plane_*_8(uint8_t *src, int stride)
+; void ff_pred16x16_plane_*_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro H264_PRED16x16_PLANE 1
@@ -550,7 +587,7 @@ H264_PRED16x16_PLANE rv40
H264_PRED16x16_PLANE svq3
;-----------------------------------------------------------------------------
-; void ff_pred8x8_plane_8(uint8_t *src, int stride)
+; void ff_pred8x8_plane_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro H264_PRED8x8_PLANE 0
@@ -724,7 +761,7 @@ INIT_XMM ssse3
H264_PRED8x8_PLANE
;-----------------------------------------------------------------------------
-; void ff_pred8x8_vertical_8(uint8_t *src, int stride)
+; void ff_pred8x8_vertical_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmx
@@ -741,7 +778,7 @@ cglobal pred8x8_vertical_8, 2,2
RET
;-----------------------------------------------------------------------------
-; void ff_pred8x8_horizontal_8(uint8_t *src, int stride)
+; void ff_pred8x8_horizontal_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8_H 0
@@ -769,7 +806,7 @@ INIT_MMX ssse3
PRED8x8_H
;-----------------------------------------------------------------------------
-; void ff_pred8x8_top_dc_8_mmxext(uint8_t *src, int stride)
+; void ff_pred8x8_top_dc_8_mmxext(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred8x8_top_dc_8, 2,5
@@ -803,7 +840,7 @@ cglobal pred8x8_top_dc_8, 2,5
RET
;-----------------------------------------------------------------------------
-; void ff_pred8x8_dc_8_mmxext(uint8_t *src, int stride)
+; void ff_pred8x8_dc_8_mmxext(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -864,7 +901,7 @@ cglobal pred8x8_dc_8, 2,5
RET
;-----------------------------------------------------------------------------
-; void ff_pred8x8_dc_rv40_8(uint8_t *src, int stride)
+; void ff_pred8x8_dc_rv40_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -901,7 +938,7 @@ cglobal pred8x8_dc_rv40_8, 2,7
REP_RET
;-----------------------------------------------------------------------------
-; void ff_pred8x8_tm_vp8_8(uint8_t *src, int stride)
+; void ff_pred8x8_tm_vp8_8(uint8_t *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8_TM 0
@@ -1014,7 +1051,7 @@ cglobal pred8x8_tm_vp8_8, 2,3,6
;-----------------------------------------------------------------------------
; void ff_pred8x8l_top_dc_8(uint8_t *src, int has_topleft, int has_topright,
-; int stride)
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_TOP_DC 0
cglobal pred8x8l_top_dc_8, 4,4
@@ -1070,7 +1107,7 @@ PRED8x8L_TOP_DC
;-----------------------------------------------------------------------------
; void ff_pred8x8l_dc_8(uint8_t *src, int has_topleft, int has_topright,
-; int stride)
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_DC 0
@@ -1174,7 +1211,7 @@ PRED8x8L_DC
;-----------------------------------------------------------------------------
; void ff_pred8x8l_horizontal_8(uint8_t *src, int has_topleft,
-; int has_topright, int stride)
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_HORIZONTAL 0
@@ -1246,7 +1283,7 @@ PRED8x8L_HORIZONTAL
;-----------------------------------------------------------------------------
; void ff_pred8x8l_vertical_8(uint8_t *src, int has_topleft, int has_topright,
-; int stride)
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_VERTICAL 0
@@ -1297,7 +1334,7 @@ PRED8x8L_VERTICAL
;-----------------------------------------------------------------------------
; void ff_pred8x8l_down_left_8(uint8_t *src, int has_topleft,
-; int has_topright, int stride)
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -1498,7 +1535,7 @@ PRED8x8L_DOWN_LEFT
;-----------------------------------------------------------------------------
; void ff_pred8x8l_down_right_8_mmxext(uint8_t *src, int has_topleft,
-; int has_topright, int stride)
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -1750,7 +1787,7 @@ PRED8x8L_DOWN_RIGHT
;-----------------------------------------------------------------------------
; void ff_pred8x8l_vertical_right_8(uint8_t *src, int has_topleft,
-; int has_topright, int stride)
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -1978,7 +2015,7 @@ PRED8x8L_VERTICAL_RIGHT
;-----------------------------------------------------------------------------
; void ff_pred8x8l_vertical_left_8(uint8_t *src, int has_topleft,
-; int has_topright, int stride)
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_VERTICAL_LEFT 0
@@ -2068,7 +2105,7 @@ PRED8x8L_VERTICAL_LEFT
;-----------------------------------------------------------------------------
; void ff_pred8x8l_horizontal_up_8(uint8_t *src, int has_topleft,
-; int has_topright, int stride)
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_HORIZONTAL_UP 0
@@ -2156,7 +2193,7 @@ PRED8x8L_HORIZONTAL_UP
;-----------------------------------------------------------------------------
; void ff_pred8x8l_horizontal_down_8(uint8_t *src, int has_topleft,
-; int has_topright, int stride)
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -2404,7 +2441,8 @@ INIT_MMX ssse3
PRED8x8L_HORIZONTAL_DOWN
;-------------------------------------------------------------------------------
-; void ff_pred4x4_dc_8_mmxext(uint8_t *src, const uint8_t *topright, int stride)
+; void ff_pred4x4_dc_8_mmxext(uint8_t *src, const uint8_t *topright,
+; ptrdiff_t stride)
;-------------------------------------------------------------------------------
INIT_MMX mmxext
@@ -2435,7 +2473,7 @@ cglobal pred4x4_dc_8, 3,5
;-----------------------------------------------------------------------------
; void ff_pred4x4_tm_vp8_8_mmxext(uint8_t *src, const uint8_t *topright,
-; int stride)
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED4x4_TM 0
@@ -2514,7 +2552,7 @@ cglobal pred4x4_tm_vp8_8, 3,3
;-----------------------------------------------------------------------------
; void ff_pred4x4_vertical_vp8_8_mmxext(uint8_t *src, const uint8_t *topright,
-; int stride)
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -2535,7 +2573,7 @@ cglobal pred4x4_vertical_vp8_8, 3,3
;-----------------------------------------------------------------------------
; void ff_pred4x4_down_left_8_mmxext(uint8_t *src, const uint8_t *topright,
-; int stride)
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_down_left_8, 3,3
@@ -2562,7 +2600,7 @@ cglobal pred4x4_down_left_8, 3,3
;------------------------------------------------------------------------------
; void ff_pred4x4_vertical_left_8_mmxext(uint8_t *src, const uint8_t *topright,
-; int stride)
+; ptrdiff_t stride)
;------------------------------------------------------------------------------
INIT_MMX mmxext
@@ -2588,7 +2626,7 @@ cglobal pred4x4_vertical_left_8, 3,3
;------------------------------------------------------------------------------
; void ff_pred4x4_horizontal_up_8_mmxext(uint8_t *src, const uint8_t *topright,
-; int stride)
+; ptrdiff_t stride)
;------------------------------------------------------------------------------
INIT_MMX mmxext
@@ -2622,7 +2660,8 @@ cglobal pred4x4_horizontal_up_8, 3,3
;------------------------------------------------------------------------------
; void ff_pred4x4_horizontal_down_8_mmxext(uint8_t *src,
-; const uint8_t *topright, int stride)
+; const uint8_t *topright,
+; ptrdiff_t stride)
;------------------------------------------------------------------------------
INIT_MMX mmxext
@@ -2658,7 +2697,8 @@ cglobal pred4x4_horizontal_down_8, 3,3
;-----------------------------------------------------------------------------
; void ff_pred4x4_vertical_right_8_mmxext(uint8_t *src,
-; const uint8_t *topright, int stride)
+; const uint8_t *topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -2689,7 +2729,7 @@ cglobal pred4x4_vertical_right_8, 3,3
;-----------------------------------------------------------------------------
; void ff_pred4x4_down_right_8_mmxext(uint8_t *src, const uint8_t *topright,
-; int stride)
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
diff --git a/media/ffvpx/libavcodec/x86/h264_intrapred_10bit.asm b/media/ffvpx/libavcodec/x86/h264_intrapred_10bit.asm
index 9e40cfe24..629e0a72e 100644
--- a/media/ffvpx/libavcodec/x86/h264_intrapred_10bit.asm
+++ b/media/ffvpx/libavcodec/x86/h264_intrapred_10bit.asm
@@ -51,7 +51,8 @@ SECTION .text
%endmacro
;-----------------------------------------------------------------------------
-; void ff_pred4x4_down_right(pixel *src, const pixel *topright, int stride)
+; void ff_pred4x4_down_right_10(pixel *src, const pixel *topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED4x4_DR 0
cglobal pred4x4_down_right_10, 3, 3
@@ -89,7 +90,8 @@ PRED4x4_DR
%endif
;------------------------------------------------------------------------------
-; void ff_pred4x4_vertical_right(pixel *src, const pixel *topright, int stride)
+; void ff_pred4x4_vertical_right_10(pixel *src, const pixel *topright,
+; ptrdiff_t stride)
;------------------------------------------------------------------------------
%macro PRED4x4_VR 0
cglobal pred4x4_vertical_right_10, 3, 3, 6
@@ -128,7 +130,8 @@ PRED4x4_VR
%endif
;-------------------------------------------------------------------------------
-; void ff_pred4x4_horizontal_down(pixel *src, const pixel *topright, int stride)
+; void ff_pred4x4_horizontal_down_10(pixel *src, const pixel *topright,
+; ptrdiff_t stride)
;-------------------------------------------------------------------------------
%macro PRED4x4_HD 0
cglobal pred4x4_horizontal_down_10, 3, 3
@@ -170,7 +173,7 @@ PRED4x4_HD
%endif
;-----------------------------------------------------------------------------
-; void ff_pred4x4_dc(pixel *src, const pixel *topright, int stride)
+; void ff_pred4x4_dc_10(pixel *src, const pixel *topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
@@ -195,7 +198,8 @@ cglobal pred4x4_dc_10, 3, 3
RET
;-----------------------------------------------------------------------------
-; void ff_pred4x4_down_left(pixel *src, const pixel *topright, int stride)
+; void ff_pred4x4_down_left_10(pixel *src, const pixel *topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED4x4_DL 0
cglobal pred4x4_down_left_10, 3, 3
@@ -225,7 +229,8 @@ PRED4x4_DL
%endif
;-----------------------------------------------------------------------------
-; void ff_pred4x4_vertical_left(pixel *src, const pixel *topright, int stride)
+; void ff_pred4x4_vertical_left_10(pixel *src, const pixel *topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED4x4_VL 0
cglobal pred4x4_vertical_left_10, 3, 3
@@ -254,7 +259,8 @@ PRED4x4_VL
%endif
;-----------------------------------------------------------------------------
-; void ff_pred4x4_horizontal_up(pixel *src, const pixel *topright, int stride)
+; void ff_pred4x4_horizontal_up_10(pixel *src, const pixel *topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_MMX mmxext
cglobal pred4x4_horizontal_up_10, 3, 3
@@ -288,7 +294,7 @@ cglobal pred4x4_horizontal_up_10, 3, 3
;-----------------------------------------------------------------------------
-; void ff_pred8x8_vertical(pixel *src, int stride)
+; void ff_pred8x8_vertical_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_XMM sse2
cglobal pred8x8_vertical_10, 2, 2
@@ -304,7 +310,7 @@ cglobal pred8x8_vertical_10, 2, 2
RET
;-----------------------------------------------------------------------------
-; void ff_pred8x8_horizontal(pixel *src, int stride)
+; void ff_pred8x8_horizontal_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_XMM sse2
cglobal pred8x8_horizontal_10, 2, 3
@@ -324,7 +330,7 @@ cglobal pred8x8_horizontal_10, 2, 3
REP_RET
;-----------------------------------------------------------------------------
-; void ff_predict_8x8_dc(pixel *src, int stride)
+; void ff_predict_8x8_dc_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro MOV8 2-3
; sort of a hack, but it works
@@ -411,7 +417,7 @@ INIT_XMM sse2
PRED8x8_DC pshuflw
;-----------------------------------------------------------------------------
-; void ff_pred8x8_top_dc(pixel *src, int stride)
+; void ff_pred8x8_top_dc_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_XMM sse2
cglobal pred8x8_top_dc_10, 2, 4
@@ -438,7 +444,7 @@ cglobal pred8x8_top_dc_10, 2, 4
RET
;-----------------------------------------------------------------------------
-; void ff_pred8x8_plane(pixel *src, int stride)
+; void ff_pred8x8_plane_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
INIT_XMM sse2
cglobal pred8x8_plane_10, 2, 7, 7
@@ -501,8 +507,8 @@ cglobal pred8x8_plane_10, 2, 7, 7
;-----------------------------------------------------------------------------
-; void ff_pred8x8l_128_dc(pixel *src, int has_topleft, int has_topright,
-; int stride)
+; void ff_pred8x8l_128_dc_10(pixel *src, int has_topleft, int has_topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_128_DC 0
cglobal pred8x8l_128_dc_10, 4, 4
@@ -526,8 +532,8 @@ INIT_XMM sse2
PRED8x8L_128_DC
;-----------------------------------------------------------------------------
-; void ff_pred8x8l_top_dc(pixel *src, int has_topleft, int has_topright,
-; int stride)
+; void ff_pred8x8l_top_dc_10(pixel *src, int has_topleft, int has_topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_TOP_DC 0
cglobal pred8x8l_top_dc_10, 4, 4, 6
@@ -566,7 +572,8 @@ PRED8x8L_TOP_DC
%endif
;-------------------------------------------------------------------------------
-; void ff_pred8x8l_dc(pixel *src, int has_topleft, int has_topright, int stride)
+; void ff_pred8x8l_dc_10(pixel *src, int has_topleft, int has_topright,
+; ptrdiff_t stride)
;-------------------------------------------------------------------------------
;TODO: see if scalar is faster
%macro PRED8x8L_DC 0
@@ -625,8 +632,8 @@ PRED8x8L_DC
%endif
;-----------------------------------------------------------------------------
-; void ff_pred8x8l_vertical(pixel *src, int has_topleft, int has_topright,
-; int stride)
+; void ff_pred8x8l_vertical_10(pixel *src, int has_topleft, int has_topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_VERTICAL 0
cglobal pred8x8l_vertical_10, 4, 4, 6
@@ -661,8 +668,8 @@ PRED8x8L_VERTICAL
%endif
;-----------------------------------------------------------------------------
-; void ff_pred8x8l_horizontal(uint8_t *src, int has_topleft, int has_topright,
-; int stride)
+; void ff_pred8x8l_horizontal_10(uint8_t *src, int has_topleft,
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_HORIZONTAL 0
cglobal pred8x8l_horizontal_10, 4, 4, 5
@@ -718,8 +725,8 @@ PRED8x8L_HORIZONTAL
%endif
;-----------------------------------------------------------------------------
-; void ff_pred8x8l_down_left(pixel *src, int has_topleft, int has_topright,
-; int stride)
+; void ff_pred8x8l_down_left_10(pixel *src, int has_topleft, int has_topright,
+; ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_DOWN_LEFT 0
cglobal pred8x8l_down_left_10, 4, 4, 7
@@ -787,8 +794,8 @@ PRED8x8L_DOWN_LEFT
%endif
;-----------------------------------------------------------------------------
-; void ff_pred8x8l_down_right(pixel *src, int has_topleft, int has_topright,
-; int stride)
+; void ff_pred8x8l_down_right_10(pixel *src, int has_topleft,
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_DOWN_RIGHT 0
; standard forbids this when has_topleft is false
@@ -862,8 +869,8 @@ PRED8x8L_DOWN_RIGHT
%endif
;-----------------------------------------------------------------------------
-; void ff_pred8x8l_vertical_right(pixel *src, int has_topleft,
-; int has_topright, int stride)
+; void ff_pred8x8l_vertical_right_10(pixel *src, int has_topleft,
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_VERTICAL_RIGHT 0
; likewise with 8x8l_down_right
@@ -933,8 +940,8 @@ PRED8x8L_VERTICAL_RIGHT
%endif
;-----------------------------------------------------------------------------
-; void ff_pred8x8l_horizontal_up(pixel *src, int has_topleft,
-; int has_topright, int stride)
+; void ff_pred8x8l_horizontal_up_10(pixel *src, int has_topleft,
+; int has_topright, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED8x8L_HORIZONTAL_UP 0
cglobal pred8x8l_horizontal_up_10, 4, 4, 6
@@ -996,7 +1003,7 @@ PRED8x8L_HORIZONTAL_UP
;-----------------------------------------------------------------------------
-; void ff_pred16x16_vertical(pixel *src, int stride)
+; void ff_pred16x16_vertical_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro MOV16 3-5
mova [%1+ 0], %2
@@ -1032,7 +1039,7 @@ INIT_XMM sse2
PRED16x16_VERTICAL
;-----------------------------------------------------------------------------
-; void ff_pred16x16_horizontal(pixel *src, int stride)
+; void ff_pred16x16_horizontal_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_HORIZONTAL 0
cglobal pred16x16_horizontal_10, 2, 3
@@ -1056,7 +1063,7 @@ INIT_XMM sse2
PRED16x16_HORIZONTAL
;-----------------------------------------------------------------------------
-; void ff_pred16x16_dc(pixel *src, int stride)
+; void ff_pred16x16_dc_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_DC 0
cglobal pred16x16_dc_10, 2, 6
@@ -1102,7 +1109,7 @@ INIT_XMM sse2
PRED16x16_DC
;-----------------------------------------------------------------------------
-; void ff_pred16x16_top_dc(pixel *src, int stride)
+; void ff_pred16x16_top_dc_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_TOP_DC 0
cglobal pred16x16_top_dc_10, 2, 3
@@ -1134,7 +1141,7 @@ INIT_XMM sse2
PRED16x16_TOP_DC
;-----------------------------------------------------------------------------
-; void ff_pred16x16_left_dc(pixel *src, int stride)
+; void ff_pred16x16_left_dc_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_LEFT_DC 0
cglobal pred16x16_left_dc_10, 2, 6
@@ -1171,7 +1178,7 @@ INIT_XMM sse2
PRED16x16_LEFT_DC
;-----------------------------------------------------------------------------
-; void ff_pred16x16_128_dc(pixel *src, int stride)
+; void ff_pred16x16_128_dc_10(pixel *src, ptrdiff_t stride)
;-----------------------------------------------------------------------------
%macro PRED16x16_128_DC 0
cglobal pred16x16_128_dc_10, 2,3
diff --git a/media/ffvpx/libavcodec/x86/h264_intrapred_init.c b/media/ffvpx/libavcodec/x86/h264_intrapred_init.c
index 528b92e49..bdd5125d6 100644
--- a/media/ffvpx/libavcodec/x86/h264_intrapred_init.c
+++ b/media/ffvpx/libavcodec/x86/h264_intrapred_init.c
@@ -127,6 +127,7 @@ PRED16x16(plane_svq3, 8, ssse3)
PRED16x16(tm_vp8, 8, mmx)
PRED16x16(tm_vp8, 8, mmxext)
PRED16x16(tm_vp8, 8, sse2)
+PRED16x16(tm_vp8, 8, avx2)
PRED8x8(top_dc, 8, mmxext)
PRED8x8(dc_rv40, 8, mmxext)
@@ -323,6 +324,12 @@ av_cold void ff_h264_pred_init_x86(H264PredContext *h, int codec_id,
}
}
}
+
+ if(EXTERNAL_AVX2(cpu_flags)){
+ if (codec_id == AV_CODEC_ID_VP8) {
+ h->pred16x16[PLANE_PRED8x8 ] = ff_pred16x16_tm_vp8_8_avx2;
+ }
+ }
} else if (bit_depth == 10) {
if (EXTERNAL_MMXEXT(cpu_flags)) {
h->pred4x4[DC_PRED ] = ff_pred4x4_dc_10_mmxext;
diff --git a/media/ffvpx/libavcodec/x86/videodsp.asm b/media/ffvpx/libavcodec/x86/videodsp.asm
index a807d3b88..e23786070 100644
--- a/media/ffvpx/libavcodec/x86/videodsp.asm
+++ b/media/ffvpx/libavcodec/x86/videodsp.asm
@@ -114,7 +114,7 @@ cglobal emu_edge_hvar, 5, 6, 1, dst, dst_stride, start_x, n_words, h, w
.x_loop: ; do {
movu [dstq+wq*2], m0 ; write($reg, $mmsize)
add wq, mmsize/2 ; w -= $mmsize/2
- cmp wq, -mmsize/2 ; } while (w > $mmsize/2)
+ cmp wq, -(mmsize/2) ; } while (w > $mmsize/2)
jl .x_loop
movu [dstq-mmsize], m0 ; write($reg, $mmsize)
add dstq, dst_strideq ; dst += dst_stride
diff --git a/media/ffvpx/libavcodec/x86/videodsp_init.c b/media/ffvpx/libavcodec/x86/videodsp_init.c
index 26e072bb1..eeebb4154 100644
--- a/media/ffvpx/libavcodec/x86/videodsp_init.c
+++ b/media/ffvpx/libavcodec/x86/videodsp_init.c
@@ -29,7 +29,7 @@
#include "libavutil/x86/cpu.h"
#include "libavcodec/videodsp.h"
-#if HAVE_YASM
+#if HAVE_X86ASM
typedef void emu_edge_vfix_func(uint8_t *dst, x86_reg dst_stride,
const uint8_t *src, x86_reg src_stride,
x86_reg start_y, x86_reg end_y, x86_reg bh);
@@ -271,14 +271,14 @@ static av_noinline void emulated_edge_mc_avx2(uint8_t *buf, const uint8_t *src,
hfixtbl_avx2, &ff_emu_edge_hvar_avx2);
}
#endif /* HAVE_AVX2_EXTERNAL */
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
void ff_prefetch_mmxext(uint8_t *buf, ptrdiff_t stride, int h);
void ff_prefetch_3dnow(uint8_t *buf, ptrdiff_t stride, int h);
av_cold void ff_videodsp_init_x86(VideoDSPContext *ctx, int bpc)
{
-#if HAVE_YASM
+#if HAVE_X86ASM
int cpu_flags = av_get_cpu_flags();
#if ARCH_X86_32
@@ -305,5 +305,5 @@ av_cold void ff_videodsp_init_x86(VideoDSPContext *ctx, int bpc)
ctx->emulated_edge_mc = emulated_edge_mc_avx2;
}
#endif
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
}
diff --git a/media/ffvpx/libavcodec/x86/vp8dsp.asm b/media/ffvpx/libavcodec/x86/vp8dsp.asm
index 538b3f4a9..e303b8029 100644
--- a/media/ffvpx/libavcodec/x86/vp8dsp.asm
+++ b/media/ffvpx/libavcodec/x86/vp8dsp.asm
@@ -156,8 +156,8 @@ SECTION .text
;-------------------------------------------------------------------------------
; subpel MC functions:
;
-; void ff_put_vp8_epel<size>_h<htap>v<vtap>_<opt>(uint8_t *dst, int deststride,
-; uint8_t *src, int srcstride,
+; void ff_put_vp8_epel<size>_h<htap>v<vtap>_<opt>(uint8_t *dst, ptrdiff_t deststride,
+; uint8_t *src, ptrdiff_t srcstride,
; int height, int mx, int my);
;-------------------------------------------------------------------------------
@@ -884,7 +884,7 @@ cglobal put_vp8_pixels16, 5, 5, 2, dst, dststride, src, srcstride, height
REP_RET
;-----------------------------------------------------------------------------
-; void ff_vp8_idct_dc_add_<opt>(uint8_t *dst, int16_t block[16], int stride);
+; void ff_vp8_idct_dc_add_<opt>(uint8_t *dst, int16_t block[16], ptrdiff_t stride);
;-----------------------------------------------------------------------------
%macro ADD_DC 4
@@ -906,6 +906,7 @@ cglobal put_vp8_pixels16, 5, 5, 2, dst, dststride, src, srcstride, height
%4 [dst2q+strideq+%3], m5
%endmacro
+%if ARCH_X86_32
INIT_MMX mmx
cglobal vp8_idct_dc_add, 3, 3, 0, dst, block, stride
; load data
@@ -929,8 +930,9 @@ cglobal vp8_idct_dc_add, 3, 3, 0, dst, block, stride
lea dst2q, [dst1q+strideq*2]
ADD_DC m0, m1, 0, movh
RET
+%endif
-INIT_XMM sse4
+%macro VP8_IDCT_DC_ADD 0
cglobal vp8_idct_dc_add, 3, 3, 6, dst, block, stride
; load data
movd m0, [blockq]
@@ -956,13 +958,28 @@ cglobal vp8_idct_dc_add, 3, 3, 6, dst, block, stride
paddw m4, m0
packuswb m2, m4
movd [dst1q], m2
+%if cpuflag(sse4)
pextrd [dst1q+strideq], m2, 1
pextrd [dst2q], m2, 2
pextrd [dst2q+strideq], m2, 3
+%else
+ psrldq m2, 4
+ movd [dst1q+strideq], m2
+ psrldq m2, 4
+ movd [dst2q], m2
+ psrldq m2, 4
+ movd [dst2q+strideq], m2
+%endif
RET
+%endmacro
+
+INIT_XMM sse2
+VP8_IDCT_DC_ADD
+INIT_XMM sse4
+VP8_IDCT_DC_ADD
;-----------------------------------------------------------------------------
-; void ff_vp8_idct_dc_add4y_<opt>(uint8_t *dst, int16_t block[4][16], int stride);
+; void ff_vp8_idct_dc_add4y_<opt>(uint8_t *dst, int16_t block[4][16], ptrdiff_t stride);
;-----------------------------------------------------------------------------
%if ARCH_X86_32
@@ -1035,7 +1052,7 @@ cglobal vp8_idct_dc_add4y, 3, 3, 6, dst, block, stride
RET
;-----------------------------------------------------------------------------
-; void ff_vp8_idct_dc_add4uv_<opt>(uint8_t *dst, int16_t block[4][16], int stride);
+; void ff_vp8_idct_dc_add4uv_<opt>(uint8_t *dst, int16_t block[4][16], ptrdiff_t stride);
;-----------------------------------------------------------------------------
INIT_MMX mmx
@@ -1077,7 +1094,7 @@ cglobal vp8_idct_dc_add4uv, 3, 3, 0, dst, block, stride
RET
;-----------------------------------------------------------------------------
-; void ff_vp8_idct_add_<opt>(uint8_t *dst, int16_t block[16], int stride);
+; void ff_vp8_idct_add_<opt>(uint8_t *dst, int16_t block[16], ptrdiff_t stride);
;-----------------------------------------------------------------------------
; calculate %1=mul_35468(%1)-mul_20091(%2); %2=mul_20091(%1)+mul_35468(%2)
diff --git a/media/ffvpx/libavcodec/x86/vp8dsp_init.c b/media/ffvpx/libavcodec/x86/vp8dsp_init.c
index 897d5a0e7..397b2518c 100644
--- a/media/ffvpx/libavcodec/x86/vp8dsp_init.c
+++ b/media/ffvpx/libavcodec/x86/vp8dsp_init.c
@@ -26,7 +26,7 @@
#include "libavutil/x86/cpu.h"
#include "libavcodec/vp8dsp.h"
-#if HAVE_YASM
+#if HAVE_X86ASM
/*
* MC functions
@@ -233,6 +233,8 @@ HVBILIN(ssse3, 8, 16, 16)
void ff_vp8_idct_dc_add_mmx(uint8_t *dst, int16_t block[16],
ptrdiff_t stride);
+void ff_vp8_idct_dc_add_sse2(uint8_t *dst, int16_t block[16],
+ ptrdiff_t stride);
void ff_vp8_idct_dc_add_sse4(uint8_t *dst, int16_t block[16],
ptrdiff_t stride);
void ff_vp8_idct_dc_add4y_mmx(uint8_t *dst, int16_t block[4][16],
@@ -288,7 +290,7 @@ DECLARE_LOOP_FILTER(sse2)
DECLARE_LOOP_FILTER(ssse3)
DECLARE_LOOP_FILTER(sse4)
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
#define VP8_LUMA_MC_FUNC(IDX, SIZE, OPT) \
c->put_vp8_epel_pixels_tab[IDX][0][2] = ff_put_vp8_epel ## SIZE ## _h6_ ## OPT; \
@@ -316,7 +318,7 @@ DECLARE_LOOP_FILTER(sse4)
av_cold void ff_vp78dsp_init_x86(VP8DSPContext *c)
{
-#if HAVE_YASM
+#if HAVE_X86ASM
int cpu_flags = av_get_cpu_flags();
if (EXTERNAL_MMX(cpu_flags)) {
@@ -346,7 +348,7 @@ av_cold void ff_vp78dsp_init_x86(VP8DSPContext *c)
c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_sse;
}
- if (HAVE_SSE2_EXTERNAL && cpu_flags & (AV_CPU_FLAG_SSE2 | AV_CPU_FLAG_SSE2SLOW)) {
+ if (EXTERNAL_SSE2(cpu_flags) || EXTERNAL_SSE2_SLOW(cpu_flags)) {
VP8_LUMA_MC_FUNC(0, 16, sse2);
VP8_MC_FUNC(1, 8, sse2);
VP8_BILINEAR_MC_FUNC(0, 16, sse2);
@@ -361,18 +363,18 @@ av_cold void ff_vp78dsp_init_x86(VP8DSPContext *c)
VP8_BILINEAR_MC_FUNC(1, 8, ssse3);
VP8_BILINEAR_MC_FUNC(2, 4, ssse3);
}
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
}
av_cold void ff_vp8dsp_init_x86(VP8DSPContext *c)
{
-#if HAVE_YASM
+#if HAVE_X86ASM
int cpu_flags = av_get_cpu_flags();
if (EXTERNAL_MMX(cpu_flags)) {
- c->vp8_idct_dc_add = ff_vp8_idct_dc_add_mmx;
c->vp8_idct_dc_add4uv = ff_vp8_idct_dc_add4uv_mmx;
#if ARCH_X86_32
+ c->vp8_idct_dc_add = ff_vp8_idct_dc_add_mmx;
c->vp8_idct_dc_add4y = ff_vp8_idct_dc_add4y_mmx;
c->vp8_idct_add = ff_vp8_idct_add_mmx;
c->vp8_luma_dc_wht = ff_vp8_luma_dc_wht_mmx;
@@ -416,7 +418,7 @@ av_cold void ff_vp8dsp_init_x86(VP8DSPContext *c)
c->vp8_luma_dc_wht = ff_vp8_luma_dc_wht_sse;
}
- if (HAVE_SSE2_EXTERNAL && cpu_flags & (AV_CPU_FLAG_SSE2 | AV_CPU_FLAG_SSE2SLOW)) {
+ if (EXTERNAL_SSE2(cpu_flags) || EXTERNAL_SSE2_SLOW(cpu_flags)) {
c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_sse2;
c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_sse2;
@@ -427,6 +429,7 @@ av_cold void ff_vp8dsp_init_x86(VP8DSPContext *c)
}
if (EXTERNAL_SSE2(cpu_flags)) {
+ c->vp8_idct_dc_add = ff_vp8_idct_dc_add_sse2;
c->vp8_idct_dc_add4y = ff_vp8_idct_dc_add4y_sse2;
c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_sse2;
@@ -460,5 +463,5 @@ av_cold void ff_vp8dsp_init_x86(VP8DSPContext *c)
c->vp8_h_loop_filter16y = ff_vp8_h_loop_filter16y_mbedge_sse4;
c->vp8_h_loop_filter8uv = ff_vp8_h_loop_filter8uv_mbedge_sse4;
}
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
}
diff --git a/media/ffvpx/libavcodec/x86/vp8dsp_loopfilter.asm b/media/ffvpx/libavcodec/x86/vp8dsp_loopfilter.asm
index 98bb6696a..caeb40526 100644
--- a/media/ffvpx/libavcodec/x86/vp8dsp_loopfilter.asm
+++ b/media/ffvpx/libavcodec/x86/vp8dsp_loopfilter.asm
@@ -43,7 +43,7 @@ cextern pb_80
SECTION .text
;-----------------------------------------------------------------------------
-; void ff_vp8_h/v_loop_filter_simple_<opt>(uint8_t *dst, int stride, int flim);
+; void ff_vp8_h/v_loop_filter_simple_<opt>(uint8_t *dst, ptrdiff_t stride, int flim);
;-----------------------------------------------------------------------------
; macro called with 7 mm register indexes as argument, and 4 regular registers
@@ -429,7 +429,7 @@ INIT_XMM sse4
SIMPLE_LOOPFILTER h, 5
;-----------------------------------------------------------------------------
-; void ff_vp8_h/v_loop_filter<size>_inner_<opt>(uint8_t *dst, [uint8_t *v,] int stride,
+; void ff_vp8_h/v_loop_filter<size>_inner_<opt>(uint8_t *dst, [uint8_t *v,] ptrdiff_t stride,
; int flimE, int flimI, int hev_thr);
;-----------------------------------------------------------------------------
@@ -921,7 +921,7 @@ INNER_LOOPFILTER v, 8
INNER_LOOPFILTER h, 8
;-----------------------------------------------------------------------------
-; void ff_vp8_h/v_loop_filter<size>_mbedge_<opt>(uint8_t *dst, [uint8_t *v,] int stride,
+; void ff_vp8_h/v_loop_filter<size>_mbedge_<opt>(uint8_t *dst, [uint8_t *v,] ptrdiff_t stride,
; int flimE, int flimI, int hev_thr);
;-----------------------------------------------------------------------------
diff --git a/media/ffvpx/libavcodec/x86/vp9dsp_init.c b/media/ffvpx/libavcodec/x86/vp9dsp_init.c
index cc781a009..837cce850 100644
--- a/media/ffvpx/libavcodec/x86/vp9dsp_init.c
+++ b/media/ffvpx/libavcodec/x86/vp9dsp_init.c
@@ -27,7 +27,7 @@
#include "libavcodec/vp9dsp.h"
#include "libavcodec/x86/vp9dsp_init.h"
-#if HAVE_YASM
+#if HAVE_X86ASM
decl_fpel_func(put, 4, , mmx);
decl_fpel_func(put, 8, , mmx);
@@ -114,7 +114,7 @@ itxfm_func(idct, idct, 32, sse2);
itxfm_func(idct, idct, 32, ssse3);
itxfm_func(idct, idct, 32, avx);
itxfm_func(iwht, iwht, 4, mmx);
-itxfm_func(idct, idct, 16, avx2);
+itxfm_funcs(16, avx2);
itxfm_func(idct, idct, 32, avx2);
#undef itxfm_func
@@ -212,11 +212,11 @@ ipred_func(32, tm, avx2);
#undef ipred_dir_tm_funcs
#undef ipred_dc_funcs
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
av_cold void ff_vp9dsp_init_x86(VP9DSPContext *dsp, int bpp, int bitexact)
{
-#if HAVE_YASM
+#if HAVE_X86ASM
int cpu_flags;
if (bpp == 10) {
@@ -391,6 +391,12 @@ av_cold void ff_vp9dsp_init_x86(VP9DSPContext *dsp, int bpp, int bitexact)
if (ARCH_X86_64) {
#if ARCH_X86_64 && HAVE_AVX2_EXTERNAL
dsp->itxfm_add[TX_16X16][DCT_DCT] = ff_vp9_idct_idct_16x16_add_avx2;
+ dsp->itxfm_add[TX_16X16][ADST_DCT] = ff_vp9_idct_iadst_16x16_add_avx2;
+ dsp->itxfm_add[TX_16X16][DCT_ADST] = ff_vp9_iadst_idct_16x16_add_avx2;
+ dsp->itxfm_add[TX_16X16][ADST_ADST] = ff_vp9_iadst_iadst_16x16_add_avx2;
+ dsp->itxfm_add[TX_32X32][ADST_ADST] =
+ dsp->itxfm_add[TX_32X32][ADST_DCT] =
+ dsp->itxfm_add[TX_32X32][DCT_ADST] =
dsp->itxfm_add[TX_32X32][DCT_DCT] = ff_vp9_idct_idct_32x32_add_avx2;
init_subpel3_32_64(0, put, 8, avx2);
init_subpel3_32_64(1, avg, 8, avx2);
@@ -406,5 +412,5 @@ av_cold void ff_vp9dsp_init_x86(VP9DSPContext *dsp, int bpp, int bitexact)
#undef init_subpel2
#undef init_subpel3
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
}
diff --git a/media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp.c b/media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp.c
index eb67499c9..60d10a12a 100644
--- a/media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp.c
+++ b/media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp.c
@@ -27,7 +27,7 @@
#include "libavcodec/vp9dsp.h"
#include "libavcodec/x86/vp9dsp_init.h"
-#if HAVE_YASM
+#if HAVE_X86ASM
decl_fpel_func(put, 8, , mmx);
decl_fpel_func(avg, 8, _16, mmxext);
@@ -51,6 +51,10 @@ decl_ipred_fns(h, 16, mmxext, sse2);
decl_ipred_fns(dc, 16, mmxext, sse2);
decl_ipred_fns(dc_top, 16, mmxext, sse2);
decl_ipred_fns(dc_left, 16, mmxext, sse2);
+decl_ipred_fn(dl, 16, 16, avx2);
+decl_ipred_fn(dl, 32, 16, avx2);
+decl_ipred_fn(dr, 16, 16, avx2);
+decl_ipred_fn(dr, 32, 16, avx2);
#define decl_ipred_dir_funcs(type) \
decl_ipred_fns(type, 16, sse2, sse2); \
@@ -63,11 +67,11 @@ decl_ipred_dir_funcs(vl);
decl_ipred_dir_funcs(vr);
decl_ipred_dir_funcs(hu);
decl_ipred_dir_funcs(hd);
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
av_cold void ff_vp9dsp_init_16bpp_x86(VP9DSPContext *dsp)
{
-#if HAVE_YASM
+#if HAVE_X86ASM
int cpu_flags = av_get_cpu_flags();
if (EXTERNAL_MMX(cpu_flags)) {
@@ -133,7 +137,13 @@ av_cold void ff_vp9dsp_init_16bpp_x86(VP9DSPContext *dsp)
init_fpel_func(2, 1, 32, avg, _16, avx2);
init_fpel_func(1, 1, 64, avg, _16, avx2);
init_fpel_func(0, 1, 128, avg, _16, avx2);
+ init_ipred_func(dl, DIAG_DOWN_LEFT, 16, 16, avx2);
+ init_ipred_func(dl, DIAG_DOWN_LEFT, 32, 16, avx2);
+ init_ipred_func(dr, DIAG_DOWN_RIGHT, 16, 16, avx2);
+#if ARCH_X86_64
+ init_ipred_func(dr, DIAG_DOWN_RIGHT, 32, 16, avx2);
+#endif
}
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
}
diff --git a/media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp_template.c b/media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp_template.c
index 4840b2844..b56afc7f5 100644
--- a/media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp_template.c
+++ b/media/ffvpx/libavcodec/x86/vp9dsp_init_16bpp_template.c
@@ -27,7 +27,7 @@
#include "libavcodec/vp9dsp.h"
#include "libavcodec/x86/vp9dsp_init.h"
-#if HAVE_YASM
+#if HAVE_X86ASM
extern const int16_t ff_filters_16bpp[3][15][4][16];
@@ -137,11 +137,11 @@ decl_itxfm_func(iadst, iadst, 4, BPC, sse2);
decl_itxfm_funcs(8, BPC, sse2);
decl_itxfm_funcs(16, BPC, sse2);
decl_itxfm_func(idct, idct, 32, BPC, sse2);
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
av_cold void INIT_FUNC(VP9DSPContext *dsp, int bitexact)
{
-#if HAVE_YASM
+#if HAVE_X86ASM
int cpu_flags = av_get_cpu_flags();
#define init_lpf_8_func(idx1, idx2, dir, wd, bpp, opt) \
@@ -234,7 +234,7 @@ av_cold void INIT_FUNC(VP9DSPContext *dsp, int bitexact)
#endif
}
-#endif /* HAVE_YASM */
+#endif /* HAVE_X86ASM */
ff_vp9dsp_init_16bpp_x86(dsp);
}
diff --git a/media/ffvpx/libavcodec/x86/vp9intrapred_16bpp.asm b/media/ffvpx/libavcodec/x86/vp9intrapred_16bpp.asm
index c0ac16d3e..32b698243 100644
--- a/media/ffvpx/libavcodec/x86/vp9intrapred_16bpp.asm
+++ b/media/ffvpx/libavcodec/x86/vp9intrapred_16bpp.asm
@@ -847,6 +847,108 @@ DL_FUNCS
INIT_XMM avx
DL_FUNCS
+%if HAVE_AVX2_EXTERNAL
+INIT_YMM avx2
+cglobal vp9_ipred_dl_16x16_16, 2, 4, 5, dst, stride, l, a
+ movifnidn aq, amp
+ mova m0, [aq] ; abcdefghijklmnop
+ vpbroadcastw xm1, [aq+30] ; pppppppp
+ vperm2i128 m2, m0, m1, q0201 ; ijklmnoppppppppp
+ vpalignr m3, m2, m0, 2 ; bcdefghijklmnopp
+ vpalignr m4, m2, m0, 4 ; cdefghijklmnoppp
+ LOWPASS 0, 3, 4 ; BCDEFGHIJKLMNOPp
+ vperm2i128 m2, m0, m1, q0201 ; JKLMNOPppppppppp
+ DEFINE_ARGS dst, stride, stride3, cnt
+ mov cntd, 2
+ lea stride3q, [strideq*3]
+
+.loop:
+ mova [dstq+strideq*0], m0
+ vpalignr m3, m2, m0, 2
+ vpalignr m4, m2, m0, 4
+ mova [dstq+strideq*1], m3
+ mova [dstq+strideq*2], m4
+ vpalignr m3, m2, m0, 6
+ vpalignr m4, m2, m0, 8
+ mova [dstq+stride3q ], m3
+ lea dstq, [dstq+strideq*4]
+ mova [dstq+strideq*0], m4
+ vpalignr m3, m2, m0, 10
+ vpalignr m4, m2, m0, 12
+ mova [dstq+strideq*1], m3
+ mova [dstq+strideq*2], m4
+ vpalignr m3, m2, m0, 14
+ mova [dstq+stride3q ], m3
+ lea dstq, [dstq+strideq*4]
+ mova m0, m2
+ vperm2i128 m2, m2, m2, q0101 ; pppppppppppppppp
+ dec cntd
+ jg .loop
+ RET
+
+cglobal vp9_ipred_dl_32x32_16, 2, 6, 7, dst, stride, l, a
+ movifnidn aq, amp
+ mova m0, [aq+mmsize*0+ 0] ; abcdefghijklmnop
+ mova m1, [aq+mmsize*1+ 0] ; qrstuvwxyz012345
+ vpbroadcastw xm4, [aq+mmsize*1+30] ; 55555555
+ vperm2i128 m5, m0, m1, q0201 ; ijklmnopqrstuvwx
+ vpalignr m2, m5, m0, 2 ; bcdefghijklmnopq
+ vpalignr m3, m5, m0, 4 ; cdefghijklmnopqr
+ LOWPASS 0, 2, 3 ; BCDEFGHIJKLMNOPQ
+ vperm2i128 m5, m1, m4, q0201 ; yz01234555555555
+ vpalignr m2, m5, m1, 2 ; rstuvwxyz0123455
+ vpalignr m3, m5, m1, 4 ; stuvwxyz01234555
+ LOWPASS 1, 2, 3 ; RSTUVWXYZ......5
+ vperm2i128 m2, m1, m4, q0201 ; Z......555555555
+ vperm2i128 m5, m0, m1, q0201 ; JKLMNOPQRSTUVWXY
+ DEFINE_ARGS dst, stride, stride3, cnt
+ lea stride3q, [strideq*3]
+ mov cntd, 4
+
+.loop:
+ mova [dstq+strideq*0 + 0], m0
+ mova [dstq+strideq*0 +32], m1
+ vpalignr m3, m5, m0, 2
+ vpalignr m4, m2, m1, 2
+ mova [dstq+strideq*1 + 0], m3
+ mova [dstq+strideq*1 +32], m4
+ vpalignr m3, m5, m0, 4
+ vpalignr m4, m2, m1, 4
+ mova [dstq+strideq*2 + 0], m3
+ mova [dstq+strideq*2 +32], m4
+ vpalignr m3, m5, m0, 6
+ vpalignr m4, m2, m1, 6
+ mova [dstq+stride3q*1+ 0], m3
+ mova [dstq+stride3q*1+32], m4
+ lea dstq, [dstq+strideq*4]
+ vpalignr m3, m5, m0, 8
+ vpalignr m4, m2, m1, 8
+ mova [dstq+strideq*0 + 0], m3
+ mova [dstq+strideq*0 +32], m4
+ vpalignr m3, m5, m0, 10
+ vpalignr m4, m2, m1, 10
+ mova [dstq+strideq*1 + 0], m3
+ mova [dstq+strideq*1 +32], m4
+ vpalignr m3, m5, m0, 12
+ vpalignr m4, m2, m1, 12
+ mova [dstq+strideq*2+ 0], m3
+ mova [dstq+strideq*2+32], m4
+ vpalignr m3, m5, m0, 14
+ vpalignr m4, m2, m1, 14
+ mova [dstq+stride3q+ 0], m3
+ mova [dstq+stride3q+ 32], m4
+ vpalignr m3, m5, m0, 16
+ vpalignr m4, m2, m1, 16
+ vperm2i128 m5, m3, m4, q0201
+ vperm2i128 m2, m4, m4, q0101
+ mova m0, m3
+ mova m1, m4
+ lea dstq, [dstq+strideq*4]
+ dec cntd
+ jg .loop
+ RET
+%endif
+
%macro DR_FUNCS 1 ; stack_mem_for_32x32_32bit_function
cglobal vp9_ipred_dr_4x4_16, 4, 4, 3, dst, stride, l, a
movh m0, [lq] ; wxyz....
@@ -1068,6 +1170,161 @@ DR_FUNCS 2
INIT_XMM avx
DR_FUNCS 2
+%if HAVE_AVX2_EXTERNAL
+INIT_YMM avx2
+cglobal vp9_ipred_dr_16x16_16, 4, 5, 6, dst, stride, l, a
+ mova m0, [lq] ; klmnopqrstuvwxyz
+ movu m1, [aq-2] ; *abcdefghijklmno
+ mova m2, [aq] ; abcdefghijklmnop
+ vperm2i128 m4, m2, m2, q2001 ; ijklmnop........
+ vpalignr m5, m4, m2, 2 ; bcdefghijklmnop.
+ vperm2i128 m3, m0, m1, q0201 ; stuvwxyz*abcdefg
+ LOWPASS 1, 2, 5 ; ABCDEFGHIJKLMNO.
+ vpalignr m4, m3, m0, 2 ; lmnopqrstuvwxyz*
+ vpalignr m5, m3, m0, 4 ; mnopqrstuvwxyz*a
+ LOWPASS 0, 4, 5 ; LMNOPQRSTUVWXYZ#
+ vperm2i128 m5, m0, m1, q0201 ; TUVWXYZ#ABCDEFGH
+ DEFINE_ARGS dst, stride, stride3, stride5, dst3
+ lea dst3q, [dstq+strideq*4]
+ lea stride3q, [strideq*3]
+ lea stride5q, [stride3q+strideq*2]
+
+ vpalignr m3, m5, m0, 2
+ vpalignr m4, m1, m5, 2
+ mova [dst3q+stride5q*2], m3 ; 14
+ mova [ dstq+stride3q*2], m4 ; 6
+ vpalignr m3, m5, m0, 4
+ vpalignr m4, m1, m5, 4
+ sub dst3q, strideq
+ mova [dst3q+stride5q*2], m3 ; 13
+ mova [dst3q+strideq*2 ], m4 ; 5
+ mova [dst3q+stride3q*4], m0 ; 15
+ vpalignr m3, m5, m0, 6
+ vpalignr m4, m1, m5, 6
+ mova [dstq+stride3q*4], m3 ; 12
+ mova [dst3q+strideq*1], m4 ; 4
+ vpalignr m3, m5, m0, 8
+ vpalignr m4, m1, m5, 8
+ mova [dst3q+strideq*8], m3 ; 11
+ mova [dst3q+strideq*0], m4 ; 3
+ vpalignr m3, m5, m0, 10
+ vpalignr m4, m1, m5, 10
+ mova [dstq+stride5q*2], m3 ; 10
+ mova [dstq+strideq*2 ], m4 ; 2
+ vpalignr m3, m5, m0, 12
+ vpalignr m4, m1, m5, 12
+ mova [dst3q+stride3q*2], m3 ; 9
+ mova [dstq+strideq*1 ], m4 ; 1
+ vpalignr m3, m5, m0, 14
+ vpalignr m4, m1, m5, 14
+ mova [dstq+strideq*8], m3 ; 8
+ mova [dstq+strideq*0], m4 ; 0
+ mova [dst3q+strideq*4], m5 ; 7
+ RET
+
+%if ARCH_X86_64
+cglobal vp9_ipred_dr_32x32_16, 4, 7, 10, dst, stride, l, a
+ mova m0, [lq+mmsize*0+0] ; l[0-15]
+ mova m1, [lq+mmsize*1+0] ; l[16-31]
+ movu m2, [aq+mmsize*0-2] ; *abcdefghijklmno
+ mova m3, [aq+mmsize*0+0] ; abcdefghijklmnop
+ mova m4, [aq+mmsize*1+0] ; qrstuvwxyz012345
+ vperm2i128 m5, m0, m1, q0201 ; lmnopqrstuvwxyz0
+ vpalignr m6, m5, m0, 2 ; mnopqrstuvwxyz01
+ vpalignr m7, m5, m0, 4 ; nopqrstuvwxyz012
+ LOWPASS 0, 6, 7 ; L[0-15]
+ vperm2i128 m7, m1, m2, q0201 ; stuvwxyz*abcdefg
+ vpalignr m5, m7, m1, 2 ; lmnopqrstuvwxyz*
+ vpalignr m6, m7, m1, 4 ; mnopqrstuvwxyz*a
+ LOWPASS 1, 5, 6 ; L[16-31]#
+ vperm2i128 m5, m3, m4, q0201 ; ijklmnopqrstuvwx
+ vpalignr m6, m5, m3, 2 ; bcdefghijklmnopq
+ LOWPASS 2, 3, 6 ; A[0-15]
+ movu m3, [aq+mmsize*1-2] ; pqrstuvwxyz01234
+ vperm2i128 m6, m4, m4, q2001 ; yz012345........
+ vpalignr m7, m6, m4, 2 ; rstuvwxyz012345.
+ LOWPASS 3, 4, 7 ; A[16-31].
+ vperm2i128 m4, m1, m2, q0201 ; TUVWXYZ#ABCDEFGH
+ vperm2i128 m5, m0, m1, q0201 ; L[7-15]L[16-23]
+ vperm2i128 m8, m2, m3, q0201 ; IJKLMNOPQRSTUVWX
+ DEFINE_ARGS dst8, stride, stride3, stride7, stride5, dst24, cnt
+ lea stride3q, [strideq*3]
+ lea stride5q, [stride3q+strideq*2]
+ lea stride7q, [strideq*4+stride3q]
+ lea dst24q, [dst8q+stride3q*8]
+ lea dst8q, [dst8q+strideq*8]
+ mov cntd, 2
+
+.loop:
+ mova [dst24q+stride7q+0 ], m0 ; 31 23 15 7
+ mova [dst24q+stride7q+32], m1
+ mova [dst8q+stride7q+0], m1
+ mova [dst8q+stride7q+32], m2
+ vpalignr m6, m4, m1, 2
+ vpalignr m7, m5, m0, 2
+ vpalignr m9, m8, m2, 2
+ mova [dst24q+stride3q*2+0], m7 ; 30 22 14 6
+ mova [dst24q+stride3q*2+32], m6
+ mova [dst8q+stride3q*2+0], m6
+ mova [dst8q+stride3q*2+32], m9
+ vpalignr m6, m4, m1, 4
+ vpalignr m7, m5, m0, 4
+ vpalignr m9, m8, m2, 4
+ mova [dst24q+stride5q+0], m7 ; 29 21 13 5
+ mova [dst24q+stride5q+32], m6
+ mova [dst8q+stride5q+0], m6
+ mova [dst8q+stride5q+32], m9
+ vpalignr m6, m4, m1, 6
+ vpalignr m7, m5, m0, 6
+ vpalignr m9, m8, m2, 6
+ mova [dst24q+strideq*4+0 ], m7 ; 28 20 12 4
+ mova [dst24q+strideq*4+32], m6
+ mova [dst8q+strideq*4+0], m6
+ mova [dst8q+strideq*4+32], m9
+ vpalignr m6, m4, m1, 8
+ vpalignr m7, m5, m0, 8
+ vpalignr m9, m8, m2, 8
+ mova [dst24q+stride3q+0 ], m7 ; 27 19 11 3
+ mova [dst24q+stride3q+32], m6
+ mova [dst8q+stride3q+0], m6
+ mova [dst8q+stride3q+32], m9
+ vpalignr m6, m4, m1, 10
+ vpalignr m7, m5, m0, 10
+ vpalignr m9, m8, m2, 10
+ mova [dst24q+strideq*2+0 ], m7 ; 26 18 10 2
+ mova [dst24q+strideq*2+32], m6
+ mova [dst8q+strideq*2+0], m6
+ mova [dst8q+strideq*2+32], m9
+ vpalignr m6, m4, m1, 12
+ vpalignr m7, m5, m0, 12
+ vpalignr m9, m8, m2, 12
+ mova [dst24q+strideq+0 ], m7 ; 25 17 9 1
+ mova [dst24q+strideq+32], m6
+ mova [dst8q+strideq+0], m6
+ mova [dst8q+strideq+32], m9
+ vpalignr m6, m4, m1, 14
+ vpalignr m7, m5, m0, 14
+ vpalignr m9, m8, m2, 14
+ mova [dst24q+strideq*0+0 ], m7 ; 24 16 8 0
+ mova [dst24q+strideq*0+32], m6
+ mova [dst8q+strideq*0+0], m6
+ mova [dst8q+strideq*0+32], m9
+ mova m0, m5
+ mova m5, m1
+ mova m1, m4
+ mova m4, m2
+ mova m2, m8
+ mova m8, m3
+ sub dst24q, stride7q
+ sub dst24q, strideq
+ sub dst8q, stride7q
+ sub dst8q, strideq
+ dec cntd
+ jg .loop
+ RET
+%endif
+%endif
+
%macro VL_FUNCS 1 ; stack_mem_for_32x32_32bit_function
cglobal vp9_ipred_vl_4x4_16, 2, 4, 3, dst, stride, l, a
movifnidn aq, amp
diff --git a/media/ffvpx/libavcodec/x86/vp9itxfm.asm b/media/ffvpx/libavcodec/x86/vp9itxfm.asm
index 57d6d353b..2c63fe514 100644
--- a/media/ffvpx/libavcodec/x86/vp9itxfm.asm
+++ b/media/ffvpx/libavcodec/x86/vp9itxfm.asm
@@ -1581,33 +1581,30 @@ cglobal vp9_idct_idct_16x16_add, 4, 4, 16, dst, stride, block, eob
VP9_IDCT16_YMM_1D
mova [blockq+224], m7
- mova [blockq+480], m15
- pxor m15, m15
; store
- VP9_IDCT8_WRITEx2 0, 1, 6, 7, 15, [pw_512], 6
+ VP9_IDCT8_WRITEx2 0, 1, 6, 7, unused, [pw_512], 6
lea dstq, [dstq+2*strideq]
- VP9_IDCT8_WRITEx2 2, 3, 6, 7, 15, [pw_512], 6
+ VP9_IDCT8_WRITEx2 2, 3, 6, 7, unused, [pw_512], 6
lea dstq, [dstq+2*strideq]
- VP9_IDCT8_WRITEx2 4, 5, 6, 7, 15, [pw_512], 6
+ VP9_IDCT8_WRITEx2 4, 5, 6, 7, unused, [pw_512], 6
lea dstq, [dstq+2*strideq]
mova m6, [blockq+192]
mova m7, [blockq+224]
- SWAP 0, 15
- mova m15, [blockq+480]
- VP9_IDCT8_WRITEx2 6, 7, 1, 2, 0, [pw_512], 6
+ VP9_IDCT8_WRITEx2 6, 7, 1, 2, unused, [pw_512], 6
lea dstq, [dstq+2*strideq]
- VP9_IDCT8_WRITEx2 8, 9, 1, 2, 0, [pw_512], 6
+ VP9_IDCT8_WRITEx2 8, 9, 1, 2, unused, [pw_512], 6
lea dstq, [dstq+2*strideq]
- VP9_IDCT8_WRITEx2 10, 11, 1, 2, 0, [pw_512], 6
+ VP9_IDCT8_WRITEx2 10, 11, 1, 2, unused, [pw_512], 6
lea dstq, [dstq+2*strideq]
- VP9_IDCT8_WRITEx2 12, 13, 1, 2, 0, [pw_512], 6
+ VP9_IDCT8_WRITEx2 12, 13, 1, 2, unused, [pw_512], 6
lea dstq, [dstq+2*strideq]
- VP9_IDCT8_WRITEx2 14, 15, 1, 2, 0, [pw_512], 6
+ VP9_IDCT8_WRITEx2 14, 15, 1, 2, unused, [pw_512], 6
lea dstq, [dstq+2*strideq]
; at the end of the loop, m0 should still be zero
; use that to zero out block coefficients
+ pxor m0, m0
ZERO_BLOCK blockq, 32, 16, m0
RET
%endif
@@ -1987,6 +1984,173 @@ IADST16_FN idct, IDCT16, iadst, IADST16, avx
IADST16_FN iadst, IADST16, idct, IDCT16, avx
IADST16_FN iadst, IADST16, iadst, IADST16, avx
+; in: data in m[0-15] except m0/m4, which are in [blockq+0] and [blockq+128]
+; out: m[0-15] except m6, which is in [blockq+192]
+; uses blockq as scratch space
+%macro VP9_IADST16_YMM_1D 0
+ mova [blockq+ 32], m3
+ mova [blockq+ 64], m7
+ mova [blockq+ 96], m8
+
+ ; first half of round 1
+ VP9_UNPACK_MULSUB_2D_4X 9, 6, 0, 3, 13160, 9760 ; m9/x=t7[d], m6/x=t6[d]
+ VP9_UNPACK_MULSUB_2D_4X 1, 14, 4, 7, 2404, 16207 ; m1/x=t15[d], m14/x=t14[d]
+ VP9_RND_SH_SUMSUB_BA 14, 6, 7, 3, 8, [pd_8192] ; m14=t6[w], m6=t14[w]
+ VP9_RND_SH_SUMSUB_BA 1, 9, 4, 0, 8, [pd_8192] ; m1=t7[w], m9=t15[w]
+
+ VP9_UNPACK_MULSUB_2D_4X 13, 2, 4, 7, 15893, 3981 ; m13/x=t3[d], m2/x=t2[d]
+ VP9_UNPACK_MULSUB_2D_4X 5, 10, 0, 3, 8423, 14053 ; m5/x=t11[d], m10/x=t10[d]
+ VP9_RND_SH_SUMSUB_BA 10, 2, 3, 7, 8, [pd_8192] ; m10=t2[w], m2=t10[w]
+ VP9_RND_SH_SUMSUB_BA 5, 13, 0, 4, 8, [pd_8192] ; m5=t3[w], m13=t11[w]
+
+ ; half of round 2 t8-15
+ VP9_UNPACK_MULSUB_2D_4X 2, 13, 4, 7, 9102, 13623 ; m2/x=t11[d], m13/x=t10[d]
+ VP9_UNPACK_MULSUB_2D_4X 9, 6, 3, 0, 13623, 9102 ; m9/x=t14[d], m6/x=t15[d]
+ VP9_RND_SH_SUMSUB_BA 9, 13, 3, 7, 8, [pd_8192] ; m9=t10[w], m13=t14[w]
+ VP9_RND_SH_SUMSUB_BA 6, 2, 0, 4, 8, [pd_8192] ; m6=t11[w], m2=t15[w]
+
+ SUMSUB_BA w, 14, 10, 8 ; m14=t2, m10=t6
+ SUMSUB_BA w, 1, 5, 8 ; m1=t3, m5=t7
+
+ mova m0, [blockq+ 0]
+ mova m4, [blockq+128]
+ mova m3, [blockq+ 32]
+ mova m7, [blockq+ 64]
+ mova m8, [blockq+ 96]
+ mova [blockq+ 0], m1
+ mova [blockq+128], m14
+ mova [blockq+ 32], m6
+ mova [blockq+ 64], m9
+ mova [blockq+ 96], m10
+
+ ; second half of round 1
+ VP9_UNPACK_MULSUB_2D_4X 15, 0, 1, 9, 16364, 804 ; m15/x=t1[d], m0/x=t0[d]
+ VP9_UNPACK_MULSUB_2D_4X 7, 8, 10, 6, 11003, 12140 ; m7/x=t9[d], m8/x=t8[d]
+ VP9_RND_SH_SUMSUB_BA 8, 0, 6, 9, 14, [pd_8192] ; m8=t0[w], m0=t8[w]
+ VP9_RND_SH_SUMSUB_BA 7, 15, 10, 1, 14, [pd_8192] ; m7=t1[w], m15=t9[w]
+
+ VP9_UNPACK_MULSUB_2D_4X 11, 4, 10, 6, 14811, 7005 ; m11/x=t5[d], m4/x=t4[d]
+ VP9_UNPACK_MULSUB_2D_4X 3, 12, 1, 9, 5520, 15426 ; m3/x=t13[d], m12/x=t12[d]
+ VP9_RND_SH_SUMSUB_BA 12, 4, 9, 6, 14, [pd_8192] ; m12=t4[w], m4=t12[w]
+ VP9_RND_SH_SUMSUB_BA 3, 11, 1, 10, 14, [pd_8192] ; m3=t5[w], m11=t13[w]
+
+ ; second half of round 2 t8-15
+ VP9_UNPACK_MULSUB_2D_4X 0, 15, 6, 10, 16069, 3196 ; m15/x=t8[d], m0/x=t9[d]
+ VP9_UNPACK_MULSUB_2D_4X 11, 4, 9, 1, 3196, 16069 ; m11/x=t12[d], m4/x=t13[d]
+ VP9_RND_SH_SUMSUB_BA 11, 15, 9, 10, 14, [pd_8192] ; m11=t8[w], m15=t12[w]
+ VP9_RND_SH_SUMSUB_BA 4, 0, 1, 6, 14, [pd_8192] ; m4=t9[w], m0=t13[w]
+
+ SUMSUB_BA w, 12, 8, 14 ; m12=t0, m8=t4
+ SUMSUB_BA w, 3, 7, 14 ; m3=t1, m7=t5
+
+ mova m10, [blockq+ 96]
+ mova [blockq+ 96], m12
+
+ ; round 3
+ VP9_UNPACK_MULSUB_2D_4X 15, 0, 9, 12, 15137, 6270 ; m15/x=t13[d], m0/x=t12[d]
+ VP9_UNPACK_MULSUB_2D_4X 2, 13, 1, 6, 6270, 15137 ; m2/x=t14[d], m13/x=t15[d]
+ VP9_RND_SH_SUMSUB_BA 2, 0, 1, 12, 14, [pd_8192] ; m2=out2[w], m0=t14a[w]
+ VP9_RND_SH_SUMSUB_BA 13, 15, 6, 9, 14, [pd_8192]
+ PSIGNW m13, [pw_m1] ; m13=out13[w], m15=t15a[w]
+
+ VP9_UNPACK_MULSUB_2D_4X 8, 7, 12, 9, 15137, 6270 ; m8/x=t5[d], m7/x=t4[d]
+ VP9_UNPACK_MULSUB_2D_4X 5, 10, 1, 6, 6270, 15137 ; m5/x=t6[d], m10/x=t7[d]
+ VP9_RND_SH_SUMSUB_BA 5, 7, 1, 9, 14, [pd_8192]
+ PSIGNW m5, [pw_m1] ; m5=out3[w], m7=t6[w]
+ VP9_RND_SH_SUMSUB_BA 10, 8, 6, 12, 14, [pd_8192] ; m10=out12[w], m8=t7[w]
+
+ mova m1, [blockq+ 0]
+ mova m14, [blockq+128]
+ mova m6, [blockq+ 32]
+ mova m9, [blockq+ 64]
+ mova m12, [blockq+ 96]
+ mova [blockq+ 0], m10
+ mova [blockq+128], m5
+
+ SUMSUB_BA w, 14, 12, 5 ; m14=out0, m12=t2a
+ SUMSUB_BA w, 1, 3, 5
+ PSIGNW m1, [pw_m1] ; m1=out15, m3=t3a
+
+ SUMSUB_BA w, 9, 11, 5
+ PSIGNW m9, [pw_m1] ; m9=out1, m11=t10
+ SUMSUB_BA w, 6, 4, 5 ; m6=out14, m4=t11
+
+ VP9_UNPACK_MULSUB_2W_4X 4, 11, 11585, 11585, [pd_8192], 5, 10 ; m4=out9, m11=out6
+ mova m5, [blockq+128]
+ mova [blockq+192], m11
+ PSIGNW m15, [pw_m1]
+ VP9_UNPACK_MULSUB_2W_4X 15, 0, 11585, 11585, [pd_8192], 10, 11 ; m15=out5, m0=out10
+
+ PSIGNW m3, [pw_m1]
+ VP9_UNPACK_MULSUB_2W_4X 3, 12, 11585, 11585, [pd_8192], 10, 11 ; m3=out7,m12=out8
+ VP9_UNPACK_MULSUB_2W_4X 8, 7, 11585, 11585, [pd_8192], 10, 11 ; m8=out11,m7=out4
+
+ mova m10, [blockq+ 0]
+
+ SWAP 0, 14, 6, 11, 8, 12, 10
+ SWAP 1, 9, 15, 4, 7, 3, 5
+ SWAP 5, 9, 15
+%endmacro
+
+%if ARCH_X86_64 && HAVE_AVX2_EXTERNAL
+%macro IADST16_YMM_FN 4
+INIT_YMM avx2
+cglobal vp9_%1_%3_16x16_add, 4, 4, 16, dst, stride, block, eob
+ mova m1, [blockq+ 32]
+ mova m2, [blockq+ 64]
+ mova m3, [blockq+ 96]
+ mova m5, [blockq+160]
+ mova m6, [blockq+192]
+ mova m7, [blockq+224]
+ mova m8, [blockq+256]
+ mova m9, [blockq+288]
+ mova m10, [blockq+320]
+ mova m11, [blockq+352]
+ mova m12, [blockq+384]
+ mova m13, [blockq+416]
+ mova m14, [blockq+448]
+ mova m15, [blockq+480]
+
+ VP9_%2_YMM_1D
+ TRANSPOSE16x16W 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, \
+ [blockq+192], [blockq+128], 1
+ mova [blockq+ 0], m0
+ VP9_%4_YMM_1D
+
+ mova [blockq+224], m7
+
+ ; store
+ VP9_IDCT8_WRITEx2 0, 1, 6, 7, unused, [pw_512], 6
+ lea dstq, [dstq+2*strideq]
+ VP9_IDCT8_WRITEx2 2, 3, 6, 7, unused, [pw_512], 6
+ lea dstq, [dstq+2*strideq]
+ VP9_IDCT8_WRITEx2 4, 5, 6, 7, unused, [pw_512], 6
+ lea dstq, [dstq+2*strideq]
+ mova m6, [blockq+192]
+ mova m7, [blockq+224]
+ VP9_IDCT8_WRITEx2 6, 7, 1, 2, unused, [pw_512], 6
+ lea dstq, [dstq+2*strideq]
+ VP9_IDCT8_WRITEx2 8, 9, 1, 2, unused, [pw_512], 6
+ lea dstq, [dstq+2*strideq]
+ VP9_IDCT8_WRITEx2 10, 11, 1, 2, unused, [pw_512], 6
+ lea dstq, [dstq+2*strideq]
+ VP9_IDCT8_WRITEx2 12, 13, 1, 2, unused, [pw_512], 6
+ lea dstq, [dstq+2*strideq]
+ VP9_IDCT8_WRITEx2 14, 15, 1, 2, unused, [pw_512], 6
+ lea dstq, [dstq+2*strideq]
+
+ ; at the end of the loop, m0 should still be zero
+ ; use that to zero out block coefficients
+ pxor m0, m0
+ ZERO_BLOCK blockq, 32, 16, m0
+ RET
+%endmacro
+
+IADST16_YMM_FN idct, IDCT16, iadst, IADST16
+IADST16_YMM_FN iadst, IADST16, idct, IDCT16
+IADST16_YMM_FN iadst, IADST16, iadst, IADST16
+%endif
+
;---------------------------------------------------------------------------------------------
; void vp9_idct_idct_32x32_add_<opt>(uint8_t *dst, ptrdiff_t stride, int16_t *block, int eob);
;---------------------------------------------------------------------------------------------
diff --git a/media/ffvpx/libavcodec/x86/vp9mc.asm b/media/ffvpx/libavcodec/x86/vp9mc.asm
index 9152ba541..f64161b2c 100644
--- a/media/ffvpx/libavcodec/x86/vp9mc.asm
+++ b/media/ffvpx/libavcodec/x86/vp9mc.asm
@@ -1,5 +1,5 @@
;******************************************************************************
-;* VP9 MC SIMD optimizations
+;* VP9 motion compensation SIMD optimizations
;*
;* Copyright (c) 2013 Ronald S. Bultje <rsbultje gmail com>
;*
@@ -440,9 +440,8 @@ cglobal vp9_%1_8tap_1d_v_ %+ %%px %+ _8, 4, 7, 11, dst, dstride, src, sstride, f
mova m10, [filteryq+96]
%endif
.loop:
- ; FIXME maybe reuse loads from previous rows, or just
- ; more generally unroll this to prevent multiple loads of
- ; the same data?
+ ; FIXME maybe reuse loads from previous rows, or just more generally
+ ; unroll this to prevent multiple loads of the same data?
movh m0, [srcq]
movh m1, [srcq+sstrideq]
movh m2, [srcq+sstrideq*2]
diff --git a/media/ffvpx/libavutil/atomic_gcc.h b/media/ffvpx/libavutil/atomic_gcc.h
index 5f9fc49ba..2bb43c3ce 100644
--- a/media/ffvpx/libavutil/atomic_gcc.h
+++ b/media/ffvpx/libavutil/atomic_gcc.h
@@ -28,40 +28,27 @@
#define avpriv_atomic_int_get atomic_int_get_gcc
static inline int atomic_int_get_gcc(volatile int *ptr)
{
-#if HAVE_ATOMIC_COMPARE_EXCHANGE
- return __atomic_load_n(ptr, __ATOMIC_SEQ_CST);
-#else
__sync_synchronize();
return *ptr;
-#endif
}
#define avpriv_atomic_int_set atomic_int_set_gcc
static inline void atomic_int_set_gcc(volatile int *ptr, int val)
{
-#if HAVE_ATOMIC_COMPARE_EXCHANGE
- __atomic_store_n(ptr, val, __ATOMIC_SEQ_CST);
-#else
*ptr = val;
__sync_synchronize();
-#endif
}
#define avpriv_atomic_int_add_and_fetch atomic_int_add_and_fetch_gcc
static inline int atomic_int_add_and_fetch_gcc(volatile int *ptr, int inc)
{
-#if HAVE_ATOMIC_COMPARE_EXCHANGE
- return __atomic_add_fetch(ptr, inc, __ATOMIC_SEQ_CST);
-#else
return __sync_add_and_fetch(ptr, inc);
-#endif
}
#define avpriv_atomic_ptr_cas atomic_ptr_cas_gcc
static inline void *atomic_ptr_cas_gcc(void * volatile *ptr,
void *oldval, void *newval)
{
-#if HAVE_SYNC_VAL_COMPARE_AND_SWAP
#ifdef __ARMCC_VERSION
// armcc will throw an error if ptr is not an integer type
volatile uintptr_t *tmp = (volatile uintptr_t*)ptr;
@@ -69,10 +56,6 @@ static inline void *atomic_ptr_cas_gcc(void * volatile *ptr,
#else
return __sync_val_compare_and_swap(ptr, oldval, newval);
#endif
-#else
- __atomic_compare_exchange_n(ptr, &oldval, newval, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST);
- return oldval;
-#endif
}
#endif /* AVUTIL_ATOMIC_GCC_H */
diff --git a/media/ffvpx/libavutil/atomic_suncc.h b/media/ffvpx/libavutil/atomic_suncc.h
deleted file mode 100644
index a75a37b47..000000000
--- a/media/ffvpx/libavutil/atomic_suncc.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVUTIL_ATOMIC_SUNCC_H
-#define AVUTIL_ATOMIC_SUNCC_H
-
-#include <atomic.h>
-#include <mbarrier.h>
-
-#include "atomic.h"
-
-#define avpriv_atomic_int_get atomic_int_get_suncc
-static inline int atomic_int_get_suncc(volatile int *ptr)
-{
- __machine_rw_barrier();
- return *ptr;
-}
-
-#define avpriv_atomic_int_set atomic_int_set_suncc
-static inline void atomic_int_set_suncc(volatile int *ptr, int val)
-{
- *ptr = val;
- __machine_rw_barrier();
-}
-
-#define avpriv_atomic_int_add_and_fetch atomic_int_add_and_fetch_suncc
-static inline int atomic_int_add_and_fetch_suncc(volatile int *ptr, int inc)
-{
- return atomic_add_int_nv(ptr, inc);
-}
-
-#define avpriv_atomic_ptr_cas atomic_ptr_cas_suncc
-static inline void *atomic_ptr_cas_suncc(void * volatile *ptr,
- void *oldval, void *newval)
-{
- return atomic_cas_ptr(ptr, oldval, newval);
-}
-
-#endif /* AVUTIL_ATOMIC_SUNCC_H */
diff --git a/media/ffvpx/libavutil/attributes.h b/media/ffvpx/libavutil/attributes.h
index 5c6b9deec..54d190111 100644
--- a/media/ffvpx/libavutil/attributes.h
+++ b/media/ffvpx/libavutil/attributes.h
@@ -121,8 +121,7 @@
#endif
#endif
-
-#if defined(__GNUC__)
+#if defined(__GNUC__) || defined(__clang__)
# define av_unused __attribute__((unused))
#else
# define av_unused
@@ -133,7 +132,7 @@
* away. This is useful for variables accessed only from inline
* assembler without the compiler being aware.
*/
-#if AV_GCC_VERSION_AT_LEAST(3,1)
+#if AV_GCC_VERSION_AT_LEAST(3,1) || defined(__clang__)
# define av_used __attribute__((used))
#else
# define av_used
diff --git a/media/ffvpx/libavutil/avconfig.h b/media/ffvpx/libavutil/avconfig.h
index 2ec333d15..f10aa6186 100644
--- a/media/ffvpx/libavutil/avconfig.h
+++ b/media/ffvpx/libavutil/avconfig.h
@@ -3,5 +3,4 @@
#define AVUTIL_AVCONFIG_H
#define AV_HAVE_BIGENDIAN 0
#define AV_HAVE_FAST_UNALIGNED 1
-#define AV_HAVE_INCOMPATIBLE_FORK_ABI 0
#endif /* AVUTIL_AVCONFIG_H */
diff --git a/media/ffvpx/libavutil/avstring.c b/media/ffvpx/libavutil/avstring.c
index 1787a1ef5..f03dd2514 100644
--- a/media/ffvpx/libavutil/avstring.c
+++ b/media/ffvpx/libavutil/avstring.c
@@ -231,6 +231,29 @@ int av_strncasecmp(const char *a, const char *b, size_t n)
return c1 - c2;
}
+char *av_strireplace(const char *str, const char *from, const char *to)
+{
+ char *ret = NULL;
+ const char *pstr2, *pstr = str;
+ size_t tolen = strlen(to), fromlen = strlen(from);
+ AVBPrint pbuf;
+
+ av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
+ while ((pstr2 = av_stristr(pstr, from))) {
+ av_bprint_append_data(&pbuf, pstr, pstr2 - pstr);
+ pstr = pstr2 + fromlen;
+ av_bprint_append_data(&pbuf, to, tolen);
+ }
+ av_bprint_append_data(&pbuf, pstr, strlen(pstr));
+ if (!av_bprint_is_complete(&pbuf)) {
+ av_bprint_finalize(&pbuf, NULL);
+ } else {
+ av_bprint_finalize(&pbuf, &ret);
+ }
+
+ return ret;
+}
+
const char *av_basename(const char *path)
{
char *p = strrchr(path, '/');
diff --git a/media/ffvpx/libavutil/avstring.h b/media/ffvpx/libavutil/avstring.h
index dd2876990..04d269564 100644
--- a/media/ffvpx/libavutil/avstring.h
+++ b/media/ffvpx/libavutil/avstring.h
@@ -266,6 +266,11 @@ int av_strcasecmp(const char *a, const char *b);
*/
int av_strncasecmp(const char *a, const char *b, size_t n);
+/**
+ * Locale-independent strings replace.
+ * @note This means only ASCII-range characters are replace
+ */
+char *av_strireplace(const char *str, const char *from, const char *to);
/**
* Thread safe basename.
diff --git a/media/ffvpx/libavutil/avutil.h b/media/ffvpx/libavutil/avutil.h
index 29dd830bf..4d633156d 100644
--- a/media/ffvpx/libavutil/avutil.h
+++ b/media/ffvpx/libavutil/avutil.h
@@ -118,6 +118,12 @@
*
* @}
*
+ * @defgroup lavu_video Video related
+ *
+ * @{
+ *
+ * @}
+ *
* @defgroup lavu_audio Audio related
*
* @{
@@ -337,6 +343,20 @@ FILE *av_fopen_utf8(const char *path, const char *mode);
*/
AVRational av_get_time_base_q(void);
+#define AV_FOURCC_MAX_STRING_SIZE 32
+
+#define av_fourcc2str(fourcc) av_fourcc_make_string((char[AV_FOURCC_MAX_STRING_SIZE]){0}, fourcc)
+
+/**
+ * Fill the provided buffer with a string containing a FourCC (four-character
+ * code) representation.
+ *
+ * @param buf a buffer with size in bytes of at least AV_FOURCC_MAX_STRING_SIZE
+ * @param fourcc the fourcc to represent
+ * @return the buffer in input
+ */
+char *av_fourcc_make_string(char *buf, uint32_t fourcc);
+
/**
* @}
* @}
diff --git a/media/ffvpx/libavutil/avutil.symbols b/media/ffvpx/libavutil/avutil.symbols
index 81cf6a8ef..ba68dc33c 100644
--- a/media/ffvpx/libavutil/avutil.symbols
+++ b/media/ffvpx/libavutil/avutil.symbols
@@ -57,9 +57,6 @@ av_dict_parse_string
av_dict_set
av_dict_set_int
av_dirname
-av_display_matrix_flip
-av_display_rotation_get
-av_display_rotation_set
av_div_q
av_dynarray2_add
av_dynarray_add
@@ -88,7 +85,9 @@ av_find_best_pix_fmt_of_2
av_find_info_tag
av_find_nearest_q_idx
av_force_cpu_flags
+av_fourcc_make_string
av_frame_alloc
+av_frame_apply_cropping
av_frame_clone
av_frame_copy
av_frame_copy_props
@@ -166,6 +165,7 @@ av_hwframe_get_buffer
av_image_alloc
av_image_check_sar
av_image_check_size
+av_image_check_size2
av_image_copy
av_image_copy_plane
av_image_copy_to_buffer
@@ -332,5 +332,8 @@ avutil_configuration
avutil_license
avutil_version
#ifdef XP_WIN
-avpriv_emms_yasm
+avpriv_emms_asm
#endif
+avpriv_slicethread_create
+avpriv_slicethread_execute
+avpriv_slicethread_free
diff --git a/media/ffvpx/libavutil/buffer.c b/media/ffvpx/libavutil/buffer.c
index 694e116a3..8d1aa5fa8 100644
--- a/media/ffvpx/libavutil/buffer.c
+++ b/media/ffvpx/libavutil/buffer.c
@@ -16,10 +16,10 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+#include <stdatomic.h>
#include <stdint.h>
#include <string.h>
-#include "atomic.h"
#include "buffer_internal.h"
#include "common.h"
#include "mem.h"
@@ -40,7 +40,8 @@ AVBufferRef *av_buffer_create(uint8_t *data, int size,
buf->size = size;
buf->free = free ? free : av_buffer_default_free;
buf->opaque = opaque;
- buf->refcount = 1;
+
+ atomic_init(&buf->refcount, 1);
if (flags & AV_BUFFER_FLAG_READONLY)
buf->flags |= BUFFER_FLAG_READONLY;
@@ -98,7 +99,7 @@ AVBufferRef *av_buffer_ref(AVBufferRef *buf)
*ret = *buf;
- avpriv_atomic_int_add_and_fetch(&buf->buffer->refcount, 1);
+ atomic_fetch_add_explicit(&buf->buffer->refcount, 1, memory_order_relaxed);
return ret;
}
@@ -115,7 +116,7 @@ static void buffer_replace(AVBufferRef **dst, AVBufferRef **src)
} else
av_freep(dst);
- if (!avpriv_atomic_int_add_and_fetch(&b->refcount, -1)) {
+ if (atomic_fetch_add_explicit(&b->refcount, -1, memory_order_acq_rel) == 1) {
b->free(b->opaque, b->data);
av_freep(&b);
}
@@ -134,7 +135,7 @@ int av_buffer_is_writable(const AVBufferRef *buf)
if (buf->buffer->flags & AV_BUFFER_FLAG_READONLY)
return 0;
- return avpriv_atomic_int_get(&buf->buffer->refcount) == 1;
+ return atomic_load(&buf->buffer->refcount) == 1;
}
void *av_buffer_get_opaque(const AVBufferRef *buf)
@@ -144,7 +145,7 @@ void *av_buffer_get_opaque(const AVBufferRef *buf)
int av_buffer_get_ref_count(const AVBufferRef *buf)
{
- return buf->buffer->refcount;
+ return atomic_load(&buf->buffer->refcount);
}
int av_buffer_make_writable(AVBufferRef **pbuf)
@@ -191,7 +192,7 @@ int av_buffer_realloc(AVBufferRef **pbuf, int size)
return 0;
if (!(buf->buffer->flags & BUFFER_FLAG_REALLOCATABLE) ||
- !av_buffer_is_writable(buf)) {
+ !av_buffer_is_writable(buf) || buf->data != buf->buffer->data) {
/* cannot realloc, allocate a new reallocable buffer and copy data */
AVBufferRef *new = NULL;
@@ -229,7 +230,7 @@ AVBufferPool *av_buffer_pool_init2(int size, void *opaque,
pool->alloc2 = alloc;
pool->pool_free = pool_free;
- avpriv_atomic_int_set(&pool->refcount, 1);
+ atomic_init(&pool->refcount, 1);
return pool;
}
@@ -245,7 +246,7 @@ AVBufferPool *av_buffer_pool_init(int size, AVBufferRef* (*alloc)(int size))
pool->size = size;
pool->alloc = alloc ? alloc : av_buffer_alloc;
- avpriv_atomic_int_set(&pool->refcount, 1);
+ atomic_init(&pool->refcount, 1);
return pool;
}
@@ -280,48 +281,10 @@ void av_buffer_pool_uninit(AVBufferPool **ppool)
pool = *ppool;
*ppool = NULL;
- if (!avpriv_atomic_int_add_and_fetch(&pool->refcount, -1))
+ if (atomic_fetch_add_explicit(&pool->refcount, -1, memory_order_acq_rel) == 1)
buffer_pool_free(pool);
}
-#if USE_ATOMICS
-/* remove the whole buffer list from the pool and return it */
-static BufferPoolEntry *get_pool(AVBufferPool *pool)
-{
- BufferPoolEntry *cur = *(void * volatile *)&pool->pool, *last = NULL;
-
- while (cur != last) {
- last = cur;
- cur = avpriv_atomic_ptr_cas((void * volatile *)&pool->pool, last, NULL);
- if (!cur)
- return NULL;
- }
-
- return cur;
-}
-
-static void add_to_pool(BufferPoolEntry *buf)
-{
- AVBufferPool *pool;
- BufferPoolEntry *cur, *end = buf;
-
- if (!buf)
- return;
- pool = buf->pool;
-
- while (end->next)
- end = end->next;
-
- while (avpriv_atomic_ptr_cas((void * volatile *)&pool->pool, NULL, buf)) {
- /* pool is not empty, retrieve it and append it to our list */
- cur = get_pool(pool);
- end->next = cur;
- while (end->next)
- end = end->next;
- }
-}
-#endif
-
static void pool_release_buffer(void *opaque, uint8_t *data)
{
BufferPoolEntry *buf = opaque;
@@ -330,16 +293,12 @@ static void pool_release_buffer(void *opaque, uint8_t *data)
if(CONFIG_MEMORY_POISONING)
memset(buf->data, FF_MEMORY_POISON, pool->size);
-#if USE_ATOMICS
- add_to_pool(buf);
-#else
ff_mutex_lock(&pool->mutex);
buf->next = pool->pool;
pool->pool = buf;
ff_mutex_unlock(&pool->mutex);
-#endif
- if (!avpriv_atomic_int_add_and_fetch(&pool->refcount, -1))
+ if (atomic_fetch_add_explicit(&pool->refcount, -1, memory_order_acq_rel) == 1)
buffer_pool_free(pool);
}
@@ -369,11 +328,6 @@ static AVBufferRef *pool_alloc_buffer(AVBufferPool *pool)
ret->buffer->opaque = buf;
ret->buffer->free = pool_release_buffer;
-#if USE_ATOMICS
- avpriv_atomic_int_add_and_fetch(&pool->refcount, 1);
- avpriv_atomic_int_add_and_fetch(&pool->nb_allocated, 1);
-#endif
-
return ret;
}
@@ -382,29 +336,6 @@ AVBufferRef *av_buffer_pool_get(AVBufferPool *pool)
AVBufferRef *ret;
BufferPoolEntry *buf;
-#if USE_ATOMICS
- /* check whether the pool is empty */
- buf = get_pool(pool);
- if (!buf && pool->refcount <= pool->nb_allocated) {
- av_log(NULL, AV_LOG_DEBUG, "Pool race dectected, spining to avoid overallocation and eventual OOM\n");
- while (!buf && avpriv_atomic_int_get(&pool->refcount) <= avpriv_atomic_int_get(&pool->nb_allocated))
- buf = get_pool(pool);
- }
-
- if (!buf)
- return pool_alloc_buffer(pool);
-
- /* keep the first entry, return the rest of the list to the pool */
- add_to_pool(buf->next);
- buf->next = NULL;
-
- ret = av_buffer_create(buf->data, pool->size, pool_release_buffer,
- buf, 0);
- if (!ret) {
- add_to_pool(buf);
- return NULL;
- }
-#else
ff_mutex_lock(&pool->mutex);
buf = pool->pool;
if (buf) {
@@ -418,10 +349,9 @@ AVBufferRef *av_buffer_pool_get(AVBufferPool *pool)
ret = pool_alloc_buffer(pool);
}
ff_mutex_unlock(&pool->mutex);
-#endif
if (ret)
- avpriv_atomic_int_add_and_fetch(&pool->refcount, 1);
+ atomic_fetch_add_explicit(&pool->refcount, 1, memory_order_relaxed);
return ret;
}
diff --git a/media/ffvpx/libavutil/buffer.h b/media/ffvpx/libavutil/buffer.h
index 0c0ce12cf..73b6bd0b1 100644
--- a/media/ffvpx/libavutil/buffer.h
+++ b/media/ffvpx/libavutil/buffer.h
@@ -256,9 +256,10 @@ AVBufferPool *av_buffer_pool_init(int size, AVBufferRef* (*alloc)(int size));
* @param alloc a function that will be used to allocate new buffers when the
* pool is empty.
* @param pool_free a function that will be called immediately before the pool
- * is freed. I.e. after av_buffer_pool_can_uninit() is called
- * by the pool and all the frames are returned to the pool and
- * freed. It is intended to uninitialize the user opaque data.
+ * is freed. I.e. after av_buffer_pool_uninit() is called
+ * by the caller and all the frames are returned to the pool
+ * and freed. It is intended to uninitialize the user opaque
+ * data.
* @return newly created buffer pool on success, NULL on error.
*/
AVBufferPool *av_buffer_pool_init2(int size, void *opaque,
diff --git a/media/ffvpx/libavutil/buffer_internal.h b/media/ffvpx/libavutil/buffer_internal.h
index 29ce8a643..54b67047e 100644
--- a/media/ffvpx/libavutil/buffer_internal.h
+++ b/media/ffvpx/libavutil/buffer_internal.h
@@ -19,6 +19,7 @@
#ifndef AVUTIL_BUFFER_INTERNAL_H
#define AVUTIL_BUFFER_INTERNAL_H
+#include <stdatomic.h>
#include <stdint.h>
#include "buffer.h"
@@ -40,7 +41,7 @@ struct AVBuffer {
/**
* number of existing AVBufferRef instances referring to this buffer
*/
- volatile int refcount;
+ atomic_uint refcount;
/**
* a callback for freeing the data
@@ -85,9 +86,7 @@ struct AVBufferPool {
* buffers have been released, then it's safe to free the pool and all
* the buffers in it.
*/
- volatile int refcount;
-
- volatile int nb_allocated;
+ atomic_uint refcount;
int size;
void *opaque;
diff --git a/media/ffvpx/libavutil/channel_layout.c b/media/ffvpx/libavutil/channel_layout.c
index 26c87c96a..3bd5ee29b 100644
--- a/media/ffvpx/libavutil/channel_layout.c
+++ b/media/ffvpx/libavutil/channel_layout.c
@@ -152,6 +152,28 @@ uint64_t av_get_channel_layout(const char *name)
return layout;
}
+int av_get_extended_channel_layout(const char *name, uint64_t* channel_layout, int* nb_channels)
+{
+ int nb = 0;
+ char *end;
+ uint64_t layout = av_get_channel_layout(name);
+
+ if (layout) {
+ *channel_layout = layout;
+ *nb_channels = av_get_channel_layout_nb_channels(layout);
+ return 0;
+ }
+
+ nb = strtol(name, &end, 10);
+ if (!errno && *end == 'C' && *(end + 1) == '\0' && nb > 0 && nb < 64) {
+ *channel_layout = 0;
+ *nb_channels = nb;
+ return 0;
+ }
+
+ return AVERROR(EINVAL);
+}
+
void av_bprint_channel_layout(struct AVBPrint *bp,
int nb_channels, uint64_t channel_layout)
{
diff --git a/media/ffvpx/libavutil/channel_layout.h b/media/ffvpx/libavutil/channel_layout.h
index ec7effead..50bb8f03c 100644
--- a/media/ffvpx/libavutil/channel_layout.h
+++ b/media/ffvpx/libavutil/channel_layout.h
@@ -131,22 +131,31 @@ enum AVMatrixEncoding {
* 5.0(side), 5.1, 5.1(side), 7.1, 7.1(wide), downmix);
* - the name of a single channel (FL, FR, FC, LFE, BL, BR, FLC, FRC, BC,
* SL, SR, TC, TFL, TFC, TFR, TBL, TBC, TBR, DL, DR);
- * - a number of channels, in decimal, optionally followed by 'c', yielding
+ * - a number of channels, in decimal, followed by 'c', yielding
* the default channel layout for that number of channels (@see
* av_get_default_channel_layout);
* - a channel layout mask, in hexadecimal starting with "0x" (see the
* AV_CH_* macros).
*
- * @warning Starting from the next major bump the trailing character
- * 'c' to specify a number of channels will be required, while a
- * channel layout mask could also be specified as a decimal number
- * (if and only if not followed by "c").
- *
* Example: "stereo+FC" = "2c+FC" = "2c+1c" = "0x7"
*/
uint64_t av_get_channel_layout(const char *name);
/**
+ * Return a channel layout and the number of channels based on the specified name.
+ *
+ * This function is similar to (@see av_get_channel_layout), but can also parse
+ * unknown channel layout specifications.
+ *
+ * @param[in] name channel layout specification string
+ * @param[out] channel_layout parsed channel layout (0 if unknown)
+ * @param[out] nb_channels number of channels
+ *
+ * @return 0 on success, AVERROR(EINVAL) if the parsing fails.
+ */
+int av_get_extended_channel_layout(const char *name, uint64_t* channel_layout, int* nb_channels);
+
+/**
* Return a description of a channel layout.
* If nb_channels is <= 0, it is guessed from the channel_layout.
*
diff --git a/media/ffvpx/libavutil/cpu.c b/media/ffvpx/libavutil/cpu.c
index f5785fc13..c8401b825 100644
--- a/media/ffvpx/libavutil/cpu.c
+++ b/media/ffvpx/libavutil/cpu.c
@@ -16,8 +16,11 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
+#include <stddef.h>
#include <stdint.h>
+#include <stdatomic.h>
+#include "attributes.h"
#include "cpu.h"
#include "cpu_internal.h"
#include "config.h"
@@ -44,10 +47,24 @@
#include <unistd.h>
#endif
-static int flags, checked;
+static atomic_int cpu_flags = ATOMIC_VAR_INIT(-1);
+
+static int get_cpu_flags(void)
+{
+ if (ARCH_AARCH64)
+ return ff_get_cpu_flags_aarch64();
+ if (ARCH_ARM)
+ return ff_get_cpu_flags_arm();
+ if (ARCH_PPC)
+ return ff_get_cpu_flags_ppc();
+ if (ARCH_X86)
+ return ff_get_cpu_flags_x86();
+ return 0;
+}
void av_force_cpu_flags(int arg){
- if ( (arg & ( AV_CPU_FLAG_3DNOW |
+ if (ARCH_X86 &&
+ (arg & ( AV_CPU_FLAG_3DNOW |
AV_CPU_FLAG_3DNOWEXT |
AV_CPU_FLAG_MMXEXT |
AV_CPU_FLAG_SSE |
@@ -69,33 +86,23 @@ void av_force_cpu_flags(int arg){
arg |= AV_CPU_FLAG_MMX;
}
- flags = arg;
- checked = arg != -1;
+ atomic_store_explicit(&cpu_flags, arg, memory_order_relaxed);
}
int av_get_cpu_flags(void)
{
- if (checked)
- return flags;
-
- if (ARCH_AARCH64)
- flags = ff_get_cpu_flags_aarch64();
- if (ARCH_ARM)
- flags = ff_get_cpu_flags_arm();
- if (ARCH_PPC)
- flags = ff_get_cpu_flags_ppc();
- if (ARCH_X86)
- flags = ff_get_cpu_flags_x86();
-
- checked = 1;
+ int flags = atomic_load_explicit(&cpu_flags, memory_order_relaxed);
+ if (flags == -1) {
+ flags = get_cpu_flags();
+ atomic_store_explicit(&cpu_flags, flags, memory_order_relaxed);
+ }
return flags;
}
void av_set_cpu_flags_mask(int mask)
{
- checked = 0;
- flags = av_get_cpu_flags() & mask;
- checked = 1;
+ atomic_store_explicit(&cpu_flags, get_cpu_flags() & mask,
+ memory_order_relaxed);
}
int av_parse_cpu_flags(const char *s)
@@ -294,3 +301,17 @@ int av_cpu_count(void)
return nb_cpus;
}
+
+size_t av_cpu_max_align(void)
+{
+ if (ARCH_AARCH64)
+ return ff_get_cpu_max_align_aarch64();
+ if (ARCH_ARM)
+ return ff_get_cpu_max_align_arm();
+ if (ARCH_PPC)
+ return ff_get_cpu_max_align_ppc();
+ if (ARCH_X86)
+ return ff_get_cpu_max_align_x86();
+
+ return 8;
+}
diff --git a/media/ffvpx/libavutil/cpu.h b/media/ffvpx/libavutil/cpu.h
index 4bff16714..9e5d40aff 100644
--- a/media/ffvpx/libavutil/cpu.h
+++ b/media/ffvpx/libavutil/cpu.h
@@ -21,6 +21,8 @@
#ifndef AVUTIL_CPU_H
#define AVUTIL_CPU_H
+#include <stddef.h>
+
#include "attributes.h"
#define AV_CPU_FLAG_FORCE 0x80000000 /* force usage of selected flags (OR) */
@@ -39,6 +41,7 @@
#define AV_CPU_FLAG_SSE3SLOW 0x20000000 ///< SSE3 supported, but usually not faster
///< than regular MMX/SSE (e.g. Core1)
#define AV_CPU_FLAG_SSSE3 0x0080 ///< Conroe SSSE3 functions
+#define AV_CPU_FLAG_SSSE3SLOW 0x4000000 ///< SSSE3 supported, but usually not faster
#define AV_CPU_FLAG_ATOM 0x10000000 ///< Atom processor, some SSSE3 instructions are slower
#define AV_CPU_FLAG_SSE4 0x0100 ///< Penryn SSE4.1 functions
#define AV_CPU_FLAG_SSE42 0x0200 ///< Nehalem SSE4.2 functions
@@ -85,8 +88,6 @@ void av_force_cpu_flags(int flags);
* Set a mask on flags returned by av_get_cpu_flags().
* This function is mainly useful for testing.
* Please use av_force_cpu_flags() and av_get_cpu_flags() instead which are more flexible
- *
- * @warning this function is not thread safe.
*/
attribute_deprecated void av_set_cpu_flags_mask(int mask);
@@ -114,4 +115,15 @@ int av_parse_cpu_caps(unsigned *flags, const char *s);
*/
int av_cpu_count(void);
+/**
+ * Get the maximum data alignment that may be required by FFmpeg.
+ *
+ * Note that this is affected by the build configuration and the CPU flags mask,
+ * so e.g. if the CPU supports AVX, but libavutil has been built with
+ * --disable-avx or the AV_CPU_FLAG_AVX flag has been disabled through
+ * av_set_cpu_flags_mask(), then this function will behave as if AVX is not
+ * present.
+ */
+size_t av_cpu_max_align(void);
+
#endif /* AVUTIL_CPU_H */
diff --git a/media/ffvpx/libavutil/cpu_internal.h b/media/ffvpx/libavutil/cpu_internal.h
index 6c352abe1..b8bf1e539 100644
--- a/media/ffvpx/libavutil/cpu_internal.h
+++ b/media/ffvpx/libavutil/cpu_internal.h
@@ -44,4 +44,9 @@ int ff_get_cpu_flags_arm(void);
int ff_get_cpu_flags_ppc(void);
int ff_get_cpu_flags_x86(void);
+size_t ff_get_cpu_max_align_aarch64(void);
+size_t ff_get_cpu_max_align_arm(void);
+size_t ff_get_cpu_max_align_ppc(void);
+size_t ff_get_cpu_max_align_x86(void);
+
#endif /* AVUTIL_CPU_INTERNAL_H */
diff --git a/media/ffvpx/libavutil/display.c b/media/ffvpx/libavutil/display.c
deleted file mode 100644
index a0076e067..000000000
--- a/media/ffvpx/libavutil/display.c
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2014 Vittorio Giovara <vittorio.giovara@gmail.com>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include <stdint.h>
-#include <string.h>
-#include <math.h>
-
-#include "display.h"
-#include "mathematics.h"
-
-// fixed point to double
-#define CONV_FP(x) ((double) (x)) / (1 << 16)
-
-// double to fixed point
-#define CONV_DB(x) (int32_t) ((x) * (1 << 16))
-
-double av_display_rotation_get(const int32_t matrix[9])
-{
- double rotation, scale[2];
-
- scale[0] = hypot(CONV_FP(matrix[0]), CONV_FP(matrix[3]));
- scale[1] = hypot(CONV_FP(matrix[1]), CONV_FP(matrix[4]));
-
- if (scale[0] == 0.0 || scale[1] == 0.0)
- return NAN;
-
- rotation = atan2(CONV_FP(matrix[1]) / scale[1],
- CONV_FP(matrix[0]) / scale[0]) * 180 / M_PI;
-
- return -rotation;
-}
-
-void av_display_rotation_set(int32_t matrix[9], double angle)
-{
- double radians = -angle * M_PI / 180.0f;
- double c = cos(radians);
- double s = sin(radians);
-
- memset(matrix, 0, 9 * sizeof(int32_t));
-
- matrix[0] = CONV_DB(c);
- matrix[1] = CONV_DB(-s);
- matrix[3] = CONV_DB(s);
- matrix[4] = CONV_DB(c);
- matrix[8] = 1 << 30;
-}
-
-void av_display_matrix_flip(int32_t matrix[9], int hflip, int vflip)
-{
- int i;
- const int flip[] = { 1 - 2 * (!!hflip), 1 - 2 * (!!vflip), 1 };
-
- if (hflip || vflip)
- for (i = 0; i < 9; i++)
- matrix[i] *= flip[i % 3];
-}
diff --git a/media/ffvpx/libavutil/display.h b/media/ffvpx/libavutil/display.h
deleted file mode 100644
index 39c15ee6b..000000000
--- a/media/ffvpx/libavutil/display.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2014 Vittorio Giovara <vittorio.giovara@gmail.com>
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVUTIL_DISPLAY_H
-#define AVUTIL_DISPLAY_H
-
-#include <stdint.h>
-#include "common.h"
-
-/**
- * The display transformation matrix specifies an affine transformation that
- * should be applied to video frames for correct presentation. It is compatible
- * with the matrices stored in the ISO/IEC 14496-12 container format.
- *
- * The data is a 3x3 matrix represented as a 9-element array:
- *
- * | a b u |
- * (a, b, u, c, d, v, x, y, w) -> | c d v |
- * | x y w |
- *
- * All numbers are stored in native endianness, as 16.16 fixed-point values,
- * except for u, v and w, which are stored as 2.30 fixed-point values.
- *
- * The transformation maps a point (p, q) in the source (pre-transformation)
- * frame to the point (p', q') in the destination (post-transformation) frame as
- * follows:
- * | a b u |
- * (p, q, 1) . | c d v | = z * (p', q', 1)
- * | x y w |
- *
- * The transformation can also be more explicitly written in components as
- * follows:
- * p' = (a * p + c * q + x) / z;
- * q' = (b * p + d * q + y) / z;
- * z = u * p + v * q + w
- */
-
-/**
- * Extract the rotation component of the transformation matrix.
- *
- * @param matrix the transformation matrix
- * @return the angle (in degrees) by which the transformation rotates the frame
- * counterclockwise. The angle will be in range [-180.0, 180.0],
- * or NaN if the matrix is singular.
- *
- * @note floating point numbers are inherently inexact, so callers are
- * recommended to round the return value to nearest integer before use.
- */
-double av_display_rotation_get(const int32_t matrix[9]);
-
-/**
- * Initialize a transformation matrix describing a pure counterclockwise
- * rotation by the specified angle (in degrees).
- *
- * @param matrix an allocated transformation matrix (will be fully overwritten
- * by this function)
- * @param angle rotation angle in degrees.
- */
-void av_display_rotation_set(int32_t matrix[9], double angle);
-
-/**
- * Flip the input matrix horizontally and/or vertically.
- *
- * @param matrix an allocated transformation matrix
- * @param hflip whether the matrix should be flipped horizontally
- * @param vflip whether the matrix should be flipped vertically
- */
-void av_display_matrix_flip(int32_t matrix[9], int hflip, int vflip);
-
-#endif /* AVUTIL_DISPLAY_H */
diff --git a/media/ffvpx/libavutil/dummy_funcs.c b/media/ffvpx/libavutil/dummy_funcs.c
index 2ea84a140..3a2381074 100644
--- a/media/ffvpx/libavutil/dummy_funcs.c
+++ b/media/ffvpx/libavutil/dummy_funcs.c
@@ -5,7 +5,6 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "avutil.h"
-#include "opt.h"
// cpu_internal.c
int ff_get_cpu_flags_aarch64(void) { return 0; }
@@ -19,65 +18,9 @@ void ff_float_dsp_init_arm(AVFloatDSPContext *fdsp) {}
void ff_float_dsp_init_ppc(AVFloatDSPContext *fdsp, int strict) {}
void ff_float_dsp_init_mips(AVFloatDSPContext *fdsp) {}
-// opt.c
-int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags) { return 0; }
-void av_opt_set_defaults(void *s) {}
-void av_opt_set_defaults2(void *s, int mask, int flags) {}
-int av_set_options_string(void *ctx, const char *opts,
- const char *key_val_sep, const char *pairs_sep) { return 0; }
-int av_opt_set_from_string(void *ctx, const char *opts,
- const char *const *shorthand,
- const char *key_val_sep, const char *pairs_sep) { return 0; }
-void av_opt_free(void *obj) {}
-int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name) { return 0; }
-int av_opt_set_dict(void *obj, struct AVDictionary **options) { return 0; }
-int av_opt_set_dict2(void *obj, struct AVDictionary **options, int search_flags) { return 0; }
-int av_opt_get_key_value(const char **ropts,
- const char *key_val_sep, const char *pairs_sep,
- unsigned flags,
- char **rkey, char **rval) { return 0; }
-int av_opt_eval_flags (void *obj, const AVOption *o, const char *val, int *flags_out) { return 0; }
-int av_opt_eval_int (void *obj, const AVOption *o, const char *val, int *int_out) { return 0; }
-int av_opt_eval_int64 (void *obj, const AVOption *o, const char *val, int64_t *int64_out) { return 0; }
-int av_opt_eval_float (void *obj, const AVOption *o, const char *val, float *float_out) { return 0; }
-int av_opt_eval_double(void *obj, const AVOption *o, const char *val, double *double_out) { return 0; }
-int av_opt_eval_q (void *obj, const AVOption *o, const char *val, AVRational *q_out) { return 0; }
-const AVOption *av_opt_find(void *obj, const char *name, const char *unit,
- int opt_flags, int search_flags) { return 0; }
-const AVOption *av_opt_find2(void *obj, const char *name, const char *unit,
- int opt_flags, int search_flags, void **target_obj) { return 0; }
-const AVOption *av_opt_next(const void *obj, const AVOption *prev) { return 0; }
-void *av_opt_child_next(void *obj, void *prev) { return 0; }
-const AVClass *av_opt_child_class_next(const AVClass *parent, const AVClass *prev) { return 0; }
-int av_opt_set (void *obj, const char *name, const char *val, int search_flags) { return 0; }
-int av_opt_set_int (void *obj, const char *name, int64_t val, int search_flags) { return 0; }
-int av_opt_set_double (void *obj, const char *name, double val, int search_flags) { return 0; }
-int av_opt_set_q (void *obj, const char *name, AVRational val, int search_flags) { return 0; }
-int av_opt_set_bin (void *obj, const char *name, const uint8_t *val, int size, int search_flags) { return 0; }
-int av_opt_set_image_size(void *obj, const char *name, int w, int h, int search_flags) { return 0; }
-int av_opt_set_pixel_fmt (void *obj, const char *name, enum AVPixelFormat fmt, int search_flags) { return 0; }
-int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags) { return 0; }
-int av_opt_set_video_rate(void *obj, const char *name, AVRational val, int search_flags) { return 0; }
-int av_opt_set_channel_layout(void *obj, const char *name, int64_t ch_layout, int search_flags) { return 0; }
-int av_opt_set_dict_val(void *obj, const char *name, const AVDictionary *val, int search_flags) { return 0; }
-int av_opt_get (void *obj, const char *name, int search_flags, uint8_t **out_val) { return 0; }
-int av_opt_get_int (void *obj, const char *name, int search_flags, int64_t *out_val) { return 0; }
-int av_opt_get_double (void *obj, const char *name, int search_flags, double *out_val) { return 0; }
-int av_opt_get_q (void *obj, const char *name, int search_flags, AVRational *out_val) { return 0; }
-int av_opt_get_image_size(void *obj, const char *name, int search_flags, int *w_out, int *h_out) { return 0; }
-int av_opt_get_pixel_fmt (void *obj, const char *name, int search_flags, enum AVPixelFormat *out_fmt) { return 0; }
-int av_opt_get_sample_fmt(void *obj, const char *name, int search_flags, enum AVSampleFormat *out_fmt) { return 0; }
-int av_opt_get_video_rate(void *obj, const char *name, int search_flags, AVRational *out_val) { return 0; }
-int av_opt_get_channel_layout(void *obj, const char *name, int search_flags, int64_t *ch_layout) { return 0; }
-int av_opt_get_dict_val(void *obj, const char *name, int search_flags, AVDictionary **out_val) { return 0; }
-void *av_opt_ptr(const AVClass *avclass, void *obj, const char *name) { return 0; }
-void av_opt_freep_ranges(AVOptionRanges **ranges) {}
-int av_opt_query_ranges(AVOptionRanges **b, void *obj, const char *key, int flags) { return 0; }
-int av_opt_copy(void *dest, const void *src) { return 0; }
-int av_opt_query_ranges_default(AVOptionRanges **b, void *obj, const char *key, int flags) { return 0; }
-int av_opt_is_set_to_default(void *obj, const AVOption *o) { return 0; }
-int av_opt_is_set_to_default_by_name(void *obj, const char *name, int search_flags) { return 0; }
-int av_opt_serialize(void *obj, int opt_flags, int flags, char **buffer,
- const char key_val_sep, const char pairs_sep) { return 0; }
-
int av_hwframe_get_buffer(struct AVBufferRef* hwframe_ref, struct AVFrame* frame, int flags) { return 0; }
+
+// cpu.c
+size_t ff_get_cpu_max_align_aarch64() { return 0; }
+size_t ff_get_cpu_max_align_arm() { return 0; }
+size_t ff_get_cpu_max_align_ppc() { return 0; }
diff --git a/media/ffvpx/libavutil/eval.c b/media/ffvpx/libavutil/eval.c
index fc12885c2..e5948793b 100644
--- a/media/ffvpx/libavutil/eval.c
+++ b/media/ffvpx/libavutil/eval.c
@@ -38,6 +38,7 @@
#include "fftime.h"
#include "avstring.h"
#include "timer.h"
+#include "reverse.h"
typedef struct Parser {
const AVClass *class;
@@ -152,9 +153,9 @@ struct AVExpr {
e_squish, e_gauss, e_ld, e_isnan, e_isinf,
e_mod, e_max, e_min, e_eq, e_gt, e_gte, e_lte, e_lt,
e_pow, e_mul, e_div, e_add,
- e_last, e_st, e_while, e_taylor, e_root, e_floor, e_ceil, e_trunc,
+ e_last, e_st, e_while, e_taylor, e_root, e_floor, e_ceil, e_trunc, e_round,
e_sqrt, e_not, e_random, e_hypot, e_gcd,
- e_if, e_ifnot, e_print, e_bitand, e_bitor, e_between, e_clip
+ e_if, e_ifnot, e_print, e_bitand, e_bitor, e_between, e_clip, e_atan2, e_lerp,
} type;
double value; // is sign in other types
union {
@@ -188,6 +189,7 @@ static double eval_expr(Parser *p, AVExpr *e)
case e_floor: return e->value * floor(eval_expr(p, e->param[0]));
case e_ceil : return e->value * ceil (eval_expr(p, e->param[0]));
case e_trunc: return e->value * trunc(eval_expr(p, e->param[0]));
+ case e_round: return e->value * round(eval_expr(p, e->param[0]));
case e_sqrt: return e->value * sqrt (eval_expr(p, e->param[0]));
case e_not: return e->value * (eval_expr(p, e->param[0]) == 0);
case e_if: return e->value * (eval_expr(p, e->param[0]) ? eval_expr(p, e->param[1]) :
@@ -206,6 +208,12 @@ static double eval_expr(Parser *p, AVExpr *e)
return e->value * (d >= eval_expr(p, e->param[1]) &&
d <= eval_expr(p, e->param[2]));
}
+ case e_lerp: {
+ double v0 = eval_expr(p, e->param[0]);
+ double v1 = eval_expr(p, e->param[1]);
+ double f = eval_expr(p, e->param[2]);
+ return v0 + (v1 - v0) * f;
+ }
case e_print: {
double x = eval_expr(p, e->param[0]);
int level = e->param[1] ? av_clip(eval_expr(p, e->param[1]), INT_MIN, INT_MAX) : AV_LOG_INFO;
@@ -305,6 +313,7 @@ static double eval_expr(Parser *p, AVExpr *e)
case e_last:return e->value * d2;
case e_st : return e->value * (p->var[av_clip(d, 0, VARS-1)]= d2);
case e_hypot:return e->value * hypot(d, d2);
+ case e_atan2:return e->value * atan2(d, d2);
case e_bitand: return isnan(d) || isnan(d2) ? NAN : e->value * ((long int)d & (long int)d2);
case e_bitor: return isnan(d) || isnan(d2) ? NAN : e->value * ((long int)d | (long int)d2);
}
@@ -438,6 +447,7 @@ static int parse_primary(AVExpr **e, Parser *p)
else if (strmatch(next, "floor" )) d->type = e_floor;
else if (strmatch(next, "ceil" )) d->type = e_ceil;
else if (strmatch(next, "trunc" )) d->type = e_trunc;
+ else if (strmatch(next, "round" )) d->type = e_round;
else if (strmatch(next, "sqrt" )) d->type = e_sqrt;
else if (strmatch(next, "not" )) d->type = e_not;
else if (strmatch(next, "pow" )) d->type = e_pow;
@@ -451,6 +461,8 @@ static int parse_primary(AVExpr **e, Parser *p)
else if (strmatch(next, "bitor" )) d->type = e_bitor;
else if (strmatch(next, "between"))d->type = e_between;
else if (strmatch(next, "clip" )) d->type = e_clip;
+ else if (strmatch(next, "atan2" )) d->type = e_atan2;
+ else if (strmatch(next, "lerp" )) d->type = e_lerp;
else {
for (i=0; p->func1_names && p->func1_names[i]; i++) {
if (strmatch(next, p->func1_names[i])) {
@@ -634,6 +646,7 @@ static int verify_expr(AVExpr *e)
case e_floor:
case e_ceil:
case e_trunc:
+ case e_round:
case e_sqrt:
case e_not:
case e_random:
@@ -648,6 +661,7 @@ static int verify_expr(AVExpr *e)
&& (!e->param[2] || verify_expr(e->param[2]));
case e_between:
case e_clip:
+ case e_lerp:
return verify_expr(e->param[0]) &&
verify_expr(e->param[1]) &&
verify_expr(e->param[2]);
diff --git a/media/ffvpx/libavutil/ffversion.h b/media/ffvpx/libavutil/ffversion.h
index cbeaf627b..3da2a6bf1 100644
--- a/media/ffvpx/libavutil/ffversion.h
+++ b/media/ffvpx/libavutil/ffversion.h
@@ -1,5 +1,5 @@
/* Automatically generated by version.sh, do not manually edit! */
#ifndef AVUTIL_FFVERSION_H
#define AVUTIL_FFVERSION_H
-#define FFMPEG_VERSION "n3.1.1-6-g86f9228"
+#define FFMPEG_VERSION "n3.4.2"
#endif /* AVUTIL_FFVERSION_H */
diff --git a/media/ffvpx/libavutil/float_dsp.c b/media/ffvpx/libavutil/float_dsp.c
index c85daffc6..1d4911d81 100644
--- a/media/ffvpx/libavutil/float_dsp.c
+++ b/media/ffvpx/libavutil/float_dsp.c
@@ -40,6 +40,14 @@ static void vector_fmac_scalar_c(float *dst, const float *src, float mul,
dst[i] += src[i] * mul;
}
+static void vector_dmac_scalar_c(double *dst, const double *src, double mul,
+ int len)
+{
+ int i;
+ for (i = 0; i < len; i++)
+ dst[i] += src[i] * mul;
+}
+
static void vector_fmul_scalar_c(float *dst, const float *src, float mul,
int len)
{
@@ -125,6 +133,7 @@ av_cold AVFloatDSPContext *avpriv_float_dsp_alloc(int bit_exact)
fdsp->vector_fmul = vector_fmul_c;
fdsp->vector_fmac_scalar = vector_fmac_scalar_c;
fdsp->vector_fmul_scalar = vector_fmul_scalar_c;
+ fdsp->vector_dmac_scalar = vector_dmac_scalar_c;
fdsp->vector_dmul_scalar = vector_dmul_scalar_c;
fdsp->vector_fmul_window = vector_fmul_window_c;
fdsp->vector_fmul_add = vector_fmul_add_c;
diff --git a/media/ffvpx/libavutil/float_dsp.h b/media/ffvpx/libavutil/float_dsp.h
index d1be38f94..2c24d9347 100644
--- a/media/ffvpx/libavutil/float_dsp.h
+++ b/media/ffvpx/libavutil/float_dsp.h
@@ -55,6 +55,22 @@ typedef struct AVFloatDSPContext {
int len);
/**
+ * Multiply a vector of doubles by a scalar double and add to
+ * destination vector. Source and destination vectors must
+ * overlap exactly or not at all.
+ *
+ * @param dst result vector
+ * constraints: 32-byte aligned
+ * @param src input vector
+ * constraints: 32-byte aligned
+ * @param mul scalar value
+ * @param len length of vector
+ * constraints: multiple of 16
+ */
+ void (*vector_dmac_scalar)(double *dst, const double *src, double mul,
+ int len);
+
+ /**
* Multiply a vector of floats by a scalar float. Source and
* destination vectors must overlap exactly or not at all.
*
diff --git a/media/ffvpx/libavutil/frame.c b/media/ffvpx/libavutil/frame.c
index 53e617422..d5fd2932e 100644
--- a/media/ffvpx/libavutil/frame.c
+++ b/media/ffvpx/libavutil/frame.c
@@ -26,6 +26,11 @@
#include "mem.h"
#include "samplefmt.h"
+
+static AVFrameSideData *frame_new_side_data(AVFrame *frame,
+ enum AVFrameSideDataType type,
+ AVBufferRef *buf);
+
MAKE_ACCESSORS(AVFrame, frame, int64_t, best_effort_timestamp)
MAKE_ACCESSORS(AVFrame, frame, int64_t, pkt_duration)
MAKE_ACCESSORS(AVFrame, frame, int64_t, pkt_pos)
@@ -176,6 +181,9 @@ static int get_video_buffer(AVFrame *frame, int align)
return ret;
if (!frame->linesize[0]) {
+ if (align <= 0)
+ align = 32; /* STRIDE_ALIGN. Should be av_cpu_max_align() */
+
for(i=1; i<=align; i+=i) {
ret = av_image_fill_linesizes(frame->linesize, frame->format,
FFALIGN(frame->width, i));
@@ -292,6 +300,10 @@ static int frame_copy_props(AVFrame *dst, const AVFrame *src, int force_copy)
dst->key_frame = src->key_frame;
dst->pict_type = src->pict_type;
dst->sample_aspect_ratio = src->sample_aspect_ratio;
+ dst->crop_top = src->crop_top;
+ dst->crop_bottom = src->crop_bottom;
+ dst->crop_left = src->crop_left;
+ dst->crop_right = src->crop_right;
dst->pts = src->pts;
dst->repeat_pict = src->repeat_pict;
dst->interlaced_frame = src->interlaced_frame;
@@ -344,18 +356,11 @@ FF_ENABLE_DEPRECATION_WARNINGS
}
memcpy(sd_dst->data, sd_src->data, sd_src->size);
} else {
- sd_dst = av_frame_new_side_data(dst, sd_src->type, 0);
+ sd_dst = frame_new_side_data(dst, sd_src->type, av_buffer_ref(sd_src->buf));
if (!sd_dst) {
wipe_side_data(dst);
return AVERROR(ENOMEM);
}
- sd_dst->buf = av_buffer_ref(sd_src->buf);
- if (!sd_dst->buf) {
- wipe_side_data(dst);
- return AVERROR(ENOMEM);
- }
- sd_dst->data = sd_dst->buf->data;
- sd_dst->size = sd_dst->buf->size;
}
av_dict_copy(&sd_dst->metadata, sd_src->metadata, 0);
}
@@ -377,6 +382,13 @@ FF_DISABLE_DEPRECATION_WARNINGS
FF_ENABLE_DEPRECATION_WARNINGS
#endif
+ av_buffer_unref(&dst->opaque_ref);
+ if (src->opaque_ref) {
+ dst->opaque_ref = av_buffer_ref(src->opaque_ref);
+ if (!dst->opaque_ref)
+ return AVERROR(ENOMEM);
+ }
+
return 0;
}
@@ -511,6 +523,8 @@ void av_frame_unref(AVFrame *frame)
av_buffer_unref(&frame->hw_frames_ctx);
+ av_buffer_unref(&frame->opaque_ref);
+
get_frame_defaults(frame);
}
@@ -622,40 +636,47 @@ AVBufferRef *av_frame_get_plane_buffer(AVFrame *frame, int plane)
return NULL;
}
-AVFrameSideData *av_frame_new_side_data(AVFrame *frame,
- enum AVFrameSideDataType type,
- int size)
+static AVFrameSideData *frame_new_side_data(AVFrame *frame,
+ enum AVFrameSideDataType type,
+ AVBufferRef *buf)
{
AVFrameSideData *ret, **tmp;
- if (frame->nb_side_data > INT_MAX / sizeof(*frame->side_data) - 1)
+ if (!buf)
return NULL;
+ if (frame->nb_side_data > INT_MAX / sizeof(*frame->side_data) - 1)
+ goto fail;
+
tmp = av_realloc(frame->side_data,
(frame->nb_side_data + 1) * sizeof(*frame->side_data));
if (!tmp)
- return NULL;
+ goto fail;
frame->side_data = tmp;
ret = av_mallocz(sizeof(*ret));
if (!ret)
- return NULL;
+ goto fail;
- if (size > 0) {
- ret->buf = av_buffer_alloc(size);
- if (!ret->buf) {
- av_freep(&ret);
- return NULL;
- }
-
- ret->data = ret->buf->data;
- ret->size = size;
- }
+ ret->buf = buf;
+ ret->data = ret->buf->data;
+ ret->size = buf->size;
ret->type = type;
frame->side_data[frame->nb_side_data++] = ret;
return ret;
+fail:
+ av_buffer_unref(&buf);
+ return NULL;
+}
+
+AVFrameSideData *av_frame_new_side_data(AVFrame *frame,
+ enum AVFrameSideDataType type,
+ int size)
+{
+
+ return frame_new_side_data(frame, type, av_buffer_alloc(size));
}
AVFrameSideData *av_frame_get_side_data(const AVFrame *frame,
@@ -723,7 +744,7 @@ int av_frame_copy(AVFrame *dst, const AVFrame *src)
if (dst->width > 0 && dst->height > 0)
return frame_copy_video(dst, src);
- else if (dst->nb_samples > 0 && dst->channel_layout)
+ else if (dst->nb_samples > 0 && dst->channels > 0)
return frame_copy_audio(dst, src);
return AVERROR(EINVAL);
@@ -758,7 +779,109 @@ const char *av_frame_side_data_name(enum AVFrameSideDataType type)
case AV_FRAME_DATA_SKIP_SAMPLES: return "Skip samples";
case AV_FRAME_DATA_AUDIO_SERVICE_TYPE: return "Audio service type";
case AV_FRAME_DATA_MASTERING_DISPLAY_METADATA: return "Mastering display metadata";
+ case AV_FRAME_DATA_CONTENT_LIGHT_LEVEL: return "Content light level metadata";
case AV_FRAME_DATA_GOP_TIMECODE: return "GOP timecode";
+ case AV_FRAME_DATA_ICC_PROFILE: return "ICC profile";
}
return NULL;
}
+
+static int calc_cropping_offsets(size_t offsets[4], const AVFrame *frame,
+ const AVPixFmtDescriptor *desc)
+{
+ int i, j;
+
+ for (i = 0; frame->data[i]; i++) {
+ const AVComponentDescriptor *comp = NULL;
+ int shift_x = (i == 1 || i == 2) ? desc->log2_chroma_w : 0;
+ int shift_y = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;
+
+ if (desc->flags & (AV_PIX_FMT_FLAG_PAL | AV_PIX_FMT_FLAG_PSEUDOPAL) && i == 1) {
+ offsets[i] = 0;
+ break;
+ }
+
+ /* find any component descriptor for this plane */
+ for (j = 0; j < desc->nb_components; j++) {
+ if (desc->comp[j].plane == i) {
+ comp = &desc->comp[j];
+ break;
+ }
+ }
+ if (!comp)
+ return AVERROR_BUG;
+
+ offsets[i] = (frame->crop_top >> shift_y) * frame->linesize[i] +
+ (frame->crop_left >> shift_x) * comp->step;
+ }
+
+ return 0;
+}
+
+int av_frame_apply_cropping(AVFrame *frame, int flags)
+{
+ const AVPixFmtDescriptor *desc;
+ size_t offsets[4];
+ int i;
+
+ if (!(frame->width > 0 && frame->height > 0))
+ return AVERROR(EINVAL);
+
+ if (frame->crop_left >= INT_MAX - frame->crop_right ||
+ frame->crop_top >= INT_MAX - frame->crop_bottom ||
+ (frame->crop_left + frame->crop_right) >= frame->width ||
+ (frame->crop_top + frame->crop_bottom) >= frame->height)
+ return AVERROR(ERANGE);
+
+ desc = av_pix_fmt_desc_get(frame->format);
+ if (!desc)
+ return AVERROR_BUG;
+
+ /* Apply just the right/bottom cropping for hwaccel formats. Bitstream
+ * formats cannot be easily handled here either (and corresponding decoders
+ * should not export any cropping anyway), so do the same for those as well.
+ * */
+ if (desc->flags & (AV_PIX_FMT_FLAG_BITSTREAM | AV_PIX_FMT_FLAG_HWACCEL)) {
+ frame->width -= frame->crop_right;
+ frame->height -= frame->crop_bottom;
+ frame->crop_right = 0;
+ frame->crop_bottom = 0;
+ return 0;
+ }
+
+ /* calculate the offsets for each plane */
+ calc_cropping_offsets(offsets, frame, desc);
+
+ /* adjust the offsets to avoid breaking alignment */
+ if (!(flags & AV_FRAME_CROP_UNALIGNED)) {
+ int log2_crop_align = frame->crop_left ? ff_ctz(frame->crop_left) : INT_MAX;
+ int min_log2_align = INT_MAX;
+
+ for (i = 0; frame->data[i]; i++) {
+ int log2_align = offsets[i] ? ff_ctz(offsets[i]) : INT_MAX;
+ min_log2_align = FFMIN(log2_align, min_log2_align);
+ }
+
+ /* we assume, and it should always be true, that the data alignment is
+ * related to the cropping alignment by a constant power-of-2 factor */
+ if (log2_crop_align < min_log2_align)
+ return AVERROR_BUG;
+
+ if (min_log2_align < 5) {
+ frame->crop_left &= ~((1 << (5 + log2_crop_align - min_log2_align)) - 1);
+ calc_cropping_offsets(offsets, frame, desc);
+ }
+ }
+
+ for (i = 0; frame->data[i]; i++)
+ frame->data[i] += offsets[i];
+
+ frame->width -= (frame->crop_left + frame->crop_right);
+ frame->height -= (frame->crop_top + frame->crop_bottom);
+ frame->crop_left = 0;
+ frame->crop_right = 0;
+ frame->crop_top = 0;
+ frame->crop_bottom = 0;
+
+ return 0;
+}
diff --git a/media/ffvpx/libavutil/frame.h b/media/ffvpx/libavutil/frame.h
index 8e51361e2..abe4f4fd1 100644
--- a/media/ffvpx/libavutil/frame.h
+++ b/media/ffvpx/libavutil/frame.h
@@ -25,6 +25,7 @@
#ifndef AVUTIL_FRAME_H
#define AVUTIL_FRAME_H
+#include <stddef.h>
#include <stdint.h>
#include "avutil.h"
@@ -120,7 +121,26 @@ enum AVFrameSideDataType {
* The GOP timecode in 25 bit timecode format. Data format is 64-bit integer.
* This is set on the first frame of a GOP that has a temporal reference of 0.
*/
- AV_FRAME_DATA_GOP_TIMECODE
+ AV_FRAME_DATA_GOP_TIMECODE,
+
+ /**
+ * The data represents the AVSphericalMapping structure defined in
+ * libavutil/spherical.h.
+ */
+ AV_FRAME_DATA_SPHERICAL,
+
+ /**
+ * Content light level (based on CTA-861.3). This payload contains data in
+ * the form of the AVContentLightMetadata struct.
+ */
+ AV_FRAME_DATA_CONTENT_LIGHT_LEVEL,
+
+ /**
+ * The data contains an ICC profile as an opaque octet buffer following the
+ * format described by ISO 15076-1 with an optional name defined in the
+ * metadata key entry "name".
+ */
+ AV_FRAME_DATA_ICC_PROFILE,
};
enum AVActiveFormatDescription {
@@ -173,9 +193,6 @@ typedef struct AVFrameSideData {
*
* sizeof(AVFrame) is not a part of the public ABI, so new fields may be added
* to the end with a minor bump.
- * Similarly fields that are marked as to be only accessed by
- * av_opt_ptr() can be reordered. This allows 2 forks to add fields
- * without breaking compatibility with each other.
*
* Fields can be accessed through AVOptions, the name string used, matches the
* C structure field name for fields accessible through AVOptions. The AVClass
@@ -231,9 +248,18 @@ typedef struct AVFrame {
uint8_t **extended_data;
/**
- * width and height of the video frame
+ * @name Video dimensions
+ * Video frames only. The coded dimensions (in pixels) of the video frame,
+ * i.e. the size of the rectangle that contains some well-defined values.
+ *
+ * @note The part of the frame intended for display/presentation is further
+ * restricted by the @ref cropping "Cropping rectangle".
+ * @{
*/
int width, height;
+ /**
+ * @}
+ */
/**
* number of audio samples (per channel) described by this frame
@@ -414,8 +440,6 @@ typedef struct AVFrame {
/**
* MPEG vs JPEG YUV range.
- * It must be accessed using av_frame_get_color_range() and
- * av_frame_set_color_range().
* - encoding: Set by user
* - decoding: Set by libavcodec
*/
@@ -427,8 +451,6 @@ typedef struct AVFrame {
/**
* YUV colorspace type.
- * It must be accessed using av_frame_get_colorspace() and
- * av_frame_set_colorspace().
* - encoding: Set by user
* - decoding: Set by libavcodec
*/
@@ -438,8 +460,6 @@ typedef struct AVFrame {
/**
* frame timestamp estimated using various heuristics, in stream time base
- * Code outside libavutil should access this field using:
- * av_frame_get_best_effort_timestamp(frame)
* - encoding: unused
* - decoding: set by libavcodec, read by user.
*/
@@ -447,8 +467,6 @@ typedef struct AVFrame {
/**
* reordered pos from the last AVPacket that has been input into the decoder
- * Code outside libavutil should access this field using:
- * av_frame_get_pkt_pos(frame)
* - encoding: unused
* - decoding: Read by user.
*/
@@ -457,8 +475,6 @@ typedef struct AVFrame {
/**
* duration of the corresponding packet, expressed in
* AVStream->time_base units, 0 if unknown.
- * Code outside libavutil should access this field using:
- * av_frame_get_pkt_duration(frame)
* - encoding: unused
* - decoding: Read by user.
*/
@@ -466,8 +482,6 @@ typedef struct AVFrame {
/**
* metadata.
- * Code outside libavutil should access this field using:
- * av_frame_get_metadata(frame)
* - encoding: Set by user.
* - decoding: Set by libavcodec.
*/
@@ -477,8 +491,6 @@ typedef struct AVFrame {
* decode error flags of the frame, set to a combination of
* FF_DECODE_ERROR_xxx flags if the decoder produced a frame, but there
* were errors during the decoding.
- * Code outside libavutil should access this field using:
- * av_frame_get_decode_error_flags(frame)
* - encoding: unused
* - decoding: set by libavcodec, read by user.
*/
@@ -488,8 +500,6 @@ typedef struct AVFrame {
/**
* number of audio channels, only used for audio.
- * Code outside libavutil should access this field using:
- * av_frame_get_channels(frame)
* - encoding: unused
* - decoding: Read by user.
*/
@@ -497,8 +507,7 @@ typedef struct AVFrame {
/**
* size of the corresponding packet containing the compressed
- * frame. It must be accessed using av_frame_get_pkt_size() and
- * av_frame_set_pkt_size().
+ * frame.
* It is set to a negative value if unknown.
* - encoding: unused
* - decoding: set by libavcodec, read by user.
@@ -508,13 +517,11 @@ typedef struct AVFrame {
#if FF_API_FRAME_QP
/**
* QP table
- * Not to be accessed directly from outside libavutil
*/
attribute_deprecated
int8_t *qscale_table;
/**
* QP store stride
- * Not to be accessed directly from outside libavutil
*/
attribute_deprecated
int qstride;
@@ -522,9 +529,6 @@ typedef struct AVFrame {
attribute_deprecated
int qscale_type;
- /**
- * Not to be accessed directly from outside libavutil
- */
AVBufferRef *qp_table_buf;
#endif
/**
@@ -532,12 +536,38 @@ typedef struct AVFrame {
* AVHWFramesContext describing the frame.
*/
AVBufferRef *hw_frames_ctx;
+
+ /**
+ * AVBufferRef for free use by the API user. FFmpeg will never check the
+ * contents of the buffer ref. FFmpeg calls av_buffer_unref() on it when
+ * the frame is unreferenced. av_frame_copy_props() calls create a new
+ * reference with av_buffer_ref() for the target frame's opaque_ref field.
+ *
+ * This is unrelated to the opaque field, although it serves a similar
+ * purpose.
+ */
+ AVBufferRef *opaque_ref;
+
+ /**
+ * @anchor cropping
+ * @name Cropping
+ * Video frames only. The number of pixels to discard from the the
+ * top/bottom/left/right border of the frame to obtain the sub-rectangle of
+ * the frame intended for presentation.
+ * @{
+ */
+ size_t crop_top;
+ size_t crop_bottom;
+ size_t crop_left;
+ size_t crop_right;
+ /**
+ * @}
+ */
} AVFrame;
/**
- * Accessors for some AVFrame fields.
- * The position of these field in the structure is not part of the ABI,
- * they should not be accessed directly outside libavutil.
+ * Accessors for some AVFrame fields. These used to be provided for ABI
+ * compatibility, and do not need to be used anymore.
*/
int64_t av_frame_get_best_effort_timestamp(const AVFrame *frame);
void av_frame_set_best_effort_timestamp(AVFrame *frame, int64_t val);
@@ -651,7 +681,9 @@ void av_frame_move_ref(AVFrame *dst, AVFrame *src);
* cases.
*
* @param frame frame in which to store the new buffers.
- * @param align required buffer size alignment
+ * @param align Required buffer size alignment. If equal to 0, alignment will be
+ * chosen automatically for the current CPU. It is highly
+ * recommended to pass 0 here unless you know what you are doing.
*
* @return 0 on success, a negative AVERROR on error.
*/
@@ -743,6 +775,40 @@ AVFrameSideData *av_frame_get_side_data(const AVFrame *frame,
*/
void av_frame_remove_side_data(AVFrame *frame, enum AVFrameSideDataType type);
+
+/**
+ * Flags for frame cropping.
+ */
+enum {
+ /**
+ * Apply the maximum possible cropping, even if it requires setting the
+ * AVFrame.data[] entries to unaligned pointers. Passing unaligned data
+ * to FFmpeg API is generally not allowed, and causes undefined behavior
+ * (such as crashes). You can pass unaligned data only to FFmpeg APIs that
+ * are explicitly documented to accept it. Use this flag only if you
+ * absolutely know what you are doing.
+ */
+ AV_FRAME_CROP_UNALIGNED = 1 << 0,
+};
+
+/**
+ * Crop the given video AVFrame according to its crop_left/crop_top/crop_right/
+ * crop_bottom fields. If cropping is successful, the function will adjust the
+ * data pointers and the width/height fields, and set the crop fields to 0.
+ *
+ * In all cases, the cropping boundaries will be rounded to the inherent
+ * alignment of the pixel format. In some cases, such as for opaque hwaccel
+ * formats, the left/top cropping is ignored. The crop fields are set to 0 even
+ * if the cropping was rounded or ignored.
+ *
+ * @param frame the frame which should be cropped
+ * @param flags Some combination of AV_FRAME_CROP_* flags, or 0.
+ *
+ * @return >= 0 on success, a negative AVERROR on error. If the cropping fields
+ * were invalid, AVERROR(ERANGE) is returned, and nothing is changed.
+ */
+int av_frame_apply_cropping(AVFrame *frame, int flags);
+
/**
* @return a string identifying the side data type
*/
diff --git a/media/ffvpx/libavutil/hwcontext.h b/media/ffvpx/libavutil/hwcontext.h
index 5e2af092a..03334e20e 100644
--- a/media/ffvpx/libavutil/hwcontext.h
+++ b/media/ffvpx/libavutil/hwcontext.h
@@ -30,6 +30,10 @@ enum AVHWDeviceType {
AV_HWDEVICE_TYPE_VAAPI,
AV_HWDEVICE_TYPE_DXVA2,
AV_HWDEVICE_TYPE_QSV,
+ AV_HWDEVICE_TYPE_VIDEOTOOLBOX,
+ AV_HWDEVICE_TYPE_NONE,
+ AV_HWDEVICE_TYPE_D3D11VA,
+ AV_HWDEVICE_TYPE_DRM,
};
typedef struct AVHWDeviceInternal AVHWDeviceInternal;
@@ -223,10 +227,36 @@ typedef struct AVHWFramesContext {
} AVHWFramesContext;
/**
- * Allocate an AVHWDeviceContext for a given pixel format.
+ * Look up an AVHWDeviceType by name.
*
- * @param format a hwaccel pixel format (AV_PIX_FMT_FLAG_HWACCEL must be set
- * on the corresponding format descriptor)
+ * @param name String name of the device type (case-insensitive).
+ * @return The type from enum AVHWDeviceType, or AV_HWDEVICE_TYPE_NONE if
+ * not found.
+ */
+enum AVHWDeviceType av_hwdevice_find_type_by_name(const char *name);
+
+/** Get the string name of an AVHWDeviceType.
+ *
+ * @param type Type from enum AVHWDeviceType.
+ * @return Pointer to a static string containing the name, or NULL if the type
+ * is not valid.
+ */
+const char *av_hwdevice_get_type_name(enum AVHWDeviceType type);
+
+/**
+ * Iterate over supported device types.
+ *
+ * @param type AV_HWDEVICE_TYPE_NONE initially, then the previous type
+ * returned by this function in subsequent iterations.
+ * @return The next usable device type from enum AVHWDeviceType, or
+ * AV_HWDEVICE_TYPE_NONE if there are no more.
+ */
+enum AVHWDeviceType av_hwdevice_iterate_types(enum AVHWDeviceType prev);
+
+/**
+ * Allocate an AVHWDeviceContext for a given hardware type.
+ *
+ * @param type the type of the hardware device to allocate.
* @return a reference to the newly created AVHWDeviceContext on success or NULL
* on failure.
*/
@@ -271,6 +301,32 @@ int av_hwdevice_ctx_create(AVBufferRef **device_ctx, enum AVHWDeviceType type,
const char *device, AVDictionary *opts, int flags);
/**
+ * Create a new device of the specified type from an existing device.
+ *
+ * If the source device is a device of the target type or was originally
+ * derived from such a device (possibly through one or more intermediate
+ * devices of other types), then this will return a reference to the
+ * existing device of the same type as is requested.
+ *
+ * Otherwise, it will attempt to derive a new device from the given source
+ * device. If direct derivation to the new type is not implemented, it will
+ * attempt the same derivation from each ancestor of the source device in
+ * turn looking for an implemented derivation method.
+ *
+ * @param dst_ctx On success, a reference to the newly-created
+ * AVHWDeviceContext.
+ * @param type The type of the new device to create.
+ * @param src_ctx A reference to an existing AVHWDeviceContext which will be
+ * used to create the new device.
+ * @param flags Currently unused; should be set to zero.
+ * @return Zero on success, a negative AVERROR code on failure.
+ */
+int av_hwdevice_ctx_create_derived(AVBufferRef **dst_ctx,
+ enum AVHWDeviceType type,
+ AVBufferRef *src_ctx, int flags);
+
+
+/**
* Allocate an AVHWFramesContext tied to a given device context.
*
* @param device_ctx a reference to a AVHWDeviceContext. This function will make
@@ -318,6 +374,14 @@ int av_hwframe_get_buffer(AVBufferRef *hwframe_ctx, AVFrame *frame, int flags);
* If dst->format is set, then this format will be used, otherwise (when
* dst->format is AV_PIX_FMT_NONE) the first acceptable format will be chosen.
*
+ * The two frames must have matching allocated dimensions (i.e. equal to
+ * AVHWFramesContext.width/height), since not all device types support
+ * transferring a sub-rectangle of the whole surface. The display dimensions
+ * (i.e. AVFrame.width/height) may be smaller than the allocated dimensions, but
+ * also have to be equal for both frames. When the display dimensions are
+ * smaller than the allocated dimensions, the content of the padding in the
+ * destination frame is unspecified.
+ *
* @param dst the destination frame. dst is not touched on failure.
* @param src the source frame.
* @param flags currently unused, should be set to zero
@@ -410,7 +474,7 @@ void *av_hwdevice_hwconfig_alloc(AVBufferRef *device_ctx);
* configuration is provided, returns the maximum possible capabilities
* of the device.
*
- * @param device_ctx a reference to the associated AVHWDeviceContext.
+ * @param ref a reference to the associated AVHWDeviceContext.
* @param hwconfig a filled HW-specific configuration structure, or NULL
* to return the maximum possible capabilities of the device.
* @return AVHWFramesConstraints structure describing the constraints
@@ -426,4 +490,93 @@ AVHWFramesConstraints *av_hwdevice_get_hwframe_constraints(AVBufferRef *ref,
*/
void av_hwframe_constraints_free(AVHWFramesConstraints **constraints);
+
+/**
+ * Flags to apply to frame mappings.
+ */
+enum {
+ /**
+ * The mapping must be readable.
+ */
+ AV_HWFRAME_MAP_READ = 1 << 0,
+ /**
+ * The mapping must be writeable.
+ */
+ AV_HWFRAME_MAP_WRITE = 1 << 1,
+ /**
+ * The mapped frame will be overwritten completely in subsequent
+ * operations, so the current frame data need not be loaded. Any values
+ * which are not overwritten are unspecified.
+ */
+ AV_HWFRAME_MAP_OVERWRITE = 1 << 2,
+ /**
+ * The mapping must be direct. That is, there must not be any copying in
+ * the map or unmap steps. Note that performance of direct mappings may
+ * be much lower than normal memory.
+ */
+ AV_HWFRAME_MAP_DIRECT = 1 << 3,
+};
+
+/**
+ * Map a hardware frame.
+ *
+ * This has a number of different possible effects, depending on the format
+ * and origin of the src and dst frames. On input, src should be a usable
+ * frame with valid buffers and dst should be blank (typically as just created
+ * by av_frame_alloc()). src should have an associated hwframe context, and
+ * dst may optionally have a format and associated hwframe context.
+ *
+ * If src was created by mapping a frame from the hwframe context of dst,
+ * then this function undoes the mapping - dst is replaced by a reference to
+ * the frame that src was originally mapped from.
+ *
+ * If both src and dst have an associated hwframe context, then this function
+ * attempts to map the src frame from its hardware context to that of dst and
+ * then fill dst with appropriate data to be usable there. This will only be
+ * possible if the hwframe contexts and associated devices are compatible -
+ * given compatible devices, av_hwframe_ctx_create_derived() can be used to
+ * create a hwframe context for dst in which mapping should be possible.
+ *
+ * If src has a hwframe context but dst does not, then the src frame is
+ * mapped to normal memory and should thereafter be usable as a normal frame.
+ * If the format is set on dst, then the mapping will attempt to create dst
+ * with that format and fail if it is not possible. If format is unset (is
+ * AV_PIX_FMT_NONE) then dst will be mapped with whatever the most appropriate
+ * format to use is (probably the sw_format of the src hwframe context).
+ *
+ * A return value of AVERROR(ENOSYS) indicates that the mapping is not
+ * possible with the given arguments and hwframe setup, while other return
+ * values indicate that it failed somehow.
+ *
+ * @param dst Destination frame, to contain the mapping.
+ * @param src Source frame, to be mapped.
+ * @param flags Some combination of AV_HWFRAME_MAP_* flags.
+ * @return Zero on success, negative AVERROR code on failure.
+ */
+int av_hwframe_map(AVFrame *dst, const AVFrame *src, int flags);
+
+
+/**
+ * Create and initialise an AVHWFramesContext as a mapping of another existing
+ * AVHWFramesContext on a different device.
+ *
+ * av_hwframe_ctx_init() should not be called after this.
+ *
+ * @param derived_frame_ctx On success, a reference to the newly created
+ * AVHWFramesContext.
+ * @param derived_device_ctx A reference to the device to create the new
+ * AVHWFramesContext on.
+ * @param source_frame_ctx A reference to an existing AVHWFramesContext
+ * which will be mapped to the derived context.
+ * @param flags Some combination of AV_HWFRAME_MAP_* flags, defining the
+ * mapping parameters to apply to frames which are allocated
+ * in the derived device.
+ * @return Zero on success, negative AVERROR code on failure.
+ */
+int av_hwframe_ctx_create_derived(AVBufferRef **derived_frame_ctx,
+ enum AVPixelFormat format,
+ AVBufferRef *derived_device_ctx,
+ AVBufferRef *source_frame_ctx,
+ int flags);
+
#endif /* AVUTIL_HWCONTEXT_H */
diff --git a/media/ffvpx/libavutil/imgutils.c b/media/ffvpx/libavutil/imgutils.c
index 37808e53d..500517880 100644
--- a/media/ffvpx/libavutil/imgutils.c
+++ b/media/ffvpx/libavutil/imgutils.c
@@ -24,6 +24,7 @@
#include "avassert.h"
#include "common.h"
#include "imgutils.h"
+#include "imgutils_internal.h"
#include "internal.h"
#include "intreadwrite.h"
#include "log.h"
@@ -248,19 +249,38 @@ static const AVClass imgutils_class = {
.parent_log_context_offset = offsetof(ImgUtils, log_ctx),
};
-int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx)
+int av_image_check_size2(unsigned int w, unsigned int h, int64_t max_pixels, enum AVPixelFormat pix_fmt, int log_offset, void *log_ctx)
{
ImgUtils imgutils = {
.class = &imgutils_class,
.log_offset = log_offset,
.log_ctx = log_ctx,
};
+ int64_t stride = av_image_get_linesize(pix_fmt, w, 0);
+ if (stride <= 0)
+ stride = 8LL*w;
+ stride += 128*8;
- if ((int)w>0 && (int)h>0 && (w+128)*(uint64_t)(h+128) < INT_MAX/8)
- return 0;
+ if ((int)w<=0 || (int)h<=0 || stride >= INT_MAX || stride*(uint64_t)(h+128) >= INT_MAX) {
+ av_log(&imgutils, AV_LOG_ERROR, "Picture size %ux%u is invalid\n", w, h);
+ return AVERROR(EINVAL);
+ }
- av_log(&imgutils, AV_LOG_ERROR, "Picture size %ux%u is invalid\n", w, h);
- return AVERROR(EINVAL);
+ if (max_pixels < INT64_MAX) {
+ if (w*(int64_t)h > max_pixels) {
+ av_log(&imgutils, AV_LOG_ERROR,
+ "Picture size %ux%u exceeds specified max pixel count %"PRId64", see the documentation if you wish to increase it\n",
+ w, h, max_pixels);
+ return AVERROR(EINVAL);
+ }
+ }
+
+ return 0;
+}
+
+int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx)
+{
+ return av_image_check_size2(w, h, INT64_MAX, AV_PIX_FMT_NONE, log_offset, log_ctx);
}
int av_image_check_sar(unsigned int w, unsigned int h, AVRational sar)
@@ -284,9 +304,9 @@ int av_image_check_sar(unsigned int w, unsigned int h, AVRational sar)
return AVERROR(EINVAL);
}
-void av_image_copy_plane(uint8_t *dst, int dst_linesize,
- const uint8_t *src, int src_linesize,
- int bytewidth, int height)
+static void image_copy_plane(uint8_t *dst, ptrdiff_t dst_linesize,
+ const uint8_t *src, ptrdiff_t src_linesize,
+ ptrdiff_t bytewidth, int height)
{
if (!dst || !src)
return;
@@ -299,9 +319,33 @@ void av_image_copy_plane(uint8_t *dst, int dst_linesize,
}
}
-void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
- const uint8_t *src_data[4], const int src_linesizes[4],
- enum AVPixelFormat pix_fmt, int width, int height)
+static void image_copy_plane_uc_from(uint8_t *dst, ptrdiff_t dst_linesize,
+ const uint8_t *src, ptrdiff_t src_linesize,
+ ptrdiff_t bytewidth, int height)
+{
+ int ret = -1;
+
+#if ARCH_X86
+ ret = ff_image_copy_plane_uc_from_x86(dst, dst_linesize, src, src_linesize,
+ bytewidth, height);
+#endif
+
+ if (ret < 0)
+ image_copy_plane(dst, dst_linesize, src, src_linesize, bytewidth, height);
+}
+
+void av_image_copy_plane(uint8_t *dst, int dst_linesize,
+ const uint8_t *src, int src_linesize,
+ int bytewidth, int height)
+{
+ image_copy_plane(dst, dst_linesize, src, src_linesize, bytewidth, height);
+}
+
+static void image_copy(uint8_t *dst_data[4], const ptrdiff_t dst_linesizes[4],
+ const uint8_t *src_data[4], const ptrdiff_t src_linesizes[4],
+ enum AVPixelFormat pix_fmt, int width, int height,
+ void (*copy_plane)(uint8_t *, ptrdiff_t, const uint8_t *,
+ ptrdiff_t, ptrdiff_t, int))
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
@@ -310,9 +354,9 @@ void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
if (desc->flags & AV_PIX_FMT_FLAG_PAL ||
desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL) {
- av_image_copy_plane(dst_data[0], dst_linesizes[0],
- src_data[0], src_linesizes[0],
- width, height);
+ copy_plane(dst_data[0], dst_linesizes[0],
+ src_data[0], src_linesizes[0],
+ width, height);
/* copy the palette */
memcpy(dst_data[1], src_data[1], 4*256);
} else {
@@ -323,7 +367,7 @@ void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
for (i = 0; i < planes_nb; i++) {
int h = height;
- int bwidth = av_image_get_linesize(pix_fmt, width, i);
+ ptrdiff_t bwidth = av_image_get_linesize(pix_fmt, width, i);
if (bwidth < 0) {
av_log(NULL, AV_LOG_ERROR, "av_image_get_linesize failed\n");
return;
@@ -331,13 +375,37 @@ void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
if (i == 1 || i == 2) {
h = AV_CEIL_RSHIFT(height, desc->log2_chroma_h);
}
- av_image_copy_plane(dst_data[i], dst_linesizes[i],
- src_data[i], src_linesizes[i],
- bwidth, h);
+ copy_plane(dst_data[i], dst_linesizes[i],
+ src_data[i], src_linesizes[i],
+ bwidth, h);
}
}
}
+void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
+ const uint8_t *src_data[4], const int src_linesizes[4],
+ enum AVPixelFormat pix_fmt, int width, int height)
+{
+ ptrdiff_t dst_linesizes1[4], src_linesizes1[4];
+ int i;
+
+ for (i = 0; i < 4; i++) {
+ dst_linesizes1[i] = dst_linesizes[i];
+ src_linesizes1[i] = src_linesizes[i];
+ }
+
+ image_copy(dst_data, dst_linesizes1, src_data, src_linesizes1, pix_fmt,
+ width, height, image_copy_plane);
+}
+
+void av_image_copy_uc_from(uint8_t *dst_data[4], const ptrdiff_t dst_linesizes[4],
+ const uint8_t *src_data[4], const ptrdiff_t src_linesizes[4],
+ enum AVPixelFormat pix_fmt, int width, int height)
+{
+ image_copy(dst_data, dst_linesizes, src_data, src_linesizes, pix_fmt,
+ width, height, image_copy_plane_uc_from);
+}
+
int av_image_fill_arrays(uint8_t *dst_data[4], int dst_linesize[4],
const uint8_t *src, enum AVPixelFormat pix_fmt,
int width, int height, int align)
@@ -423,3 +491,170 @@ int av_image_copy_to_buffer(uint8_t *dst, int dst_size,
return size;
}
+
+// Fill dst[0..dst_size] with the bytes in clear[0..clear_size]. The clear
+// bytes are repeated until dst_size is reached. If dst_size is unaligned (i.e.
+// dst_size%clear_size!=0), the remaining data will be filled with the beginning
+// of the clear data only.
+static void memset_bytes(uint8_t *dst, size_t dst_size, uint8_t *clear,
+ size_t clear_size)
+{
+ size_t pos = 0;
+ int same = 1;
+ int i;
+
+ if (!clear_size)
+ return;
+
+ // Reduce to memset() if possible.
+ for (i = 0; i < clear_size; i++) {
+ if (clear[i] != clear[0]) {
+ same = 0;
+ break;
+ }
+ }
+ if (same)
+ clear_size = 1;
+
+ if (clear_size == 1) {
+ memset(dst, clear[0], dst_size);
+ dst_size = 0;
+ } else if (clear_size == 2) {
+ uint16_t val = AV_RN16(clear);
+ for (; dst_size >= 2; dst_size -= 2) {
+ AV_WN16(dst, val);
+ dst += 2;
+ }
+ } else if (clear_size == 4) {
+ uint32_t val = AV_RN32(clear);
+ for (; dst_size >= 4; dst_size -= 4) {
+ AV_WN32(dst, val);
+ dst += 4;
+ }
+ } else if (clear_size == 8) {
+ uint32_t val = AV_RN64(clear);
+ for (; dst_size >= 8; dst_size -= 8) {
+ AV_WN64(dst, val);
+ dst += 8;
+ }
+ }
+
+ for (; dst_size; dst_size--)
+ *dst++ = clear[pos++ % clear_size];
+}
+
+// Maximum size in bytes of a plane element (usually a pixel, or multiple pixels
+// if it's a subsampled packed format).
+#define MAX_BLOCK_SIZE 32
+
+int av_image_fill_black(uint8_t *dst_data[4], const ptrdiff_t dst_linesize[4],
+ enum AVPixelFormat pix_fmt, enum AVColorRange range,
+ int width, int height)
+{
+ const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
+ int nb_planes = av_pix_fmt_count_planes(pix_fmt);
+ // A pixel or a group of pixels on each plane, with a value that represents black.
+ // Consider e.g. AV_PIX_FMT_UYVY422 for non-trivial cases.
+ uint8_t clear_block[4][MAX_BLOCK_SIZE] = {{0}}; // clear padding with 0
+ int clear_block_size[4] = {0};
+ ptrdiff_t plane_line_bytes[4] = {0};
+ int rgb, limited;
+ int plane, c;
+
+ if (!desc || nb_planes < 1 || nb_planes > 4 || desc->flags & AV_PIX_FMT_FLAG_HWACCEL)
+ return AVERROR(EINVAL);
+
+ rgb = !!(desc->flags & AV_PIX_FMT_FLAG_RGB);
+ limited = !rgb && range != AVCOL_RANGE_JPEG;
+
+ if (desc->flags & AV_PIX_FMT_FLAG_BITSTREAM) {
+ ptrdiff_t bytewidth = av_image_get_linesize(pix_fmt, width, 0);
+ uint8_t *data;
+ int mono = pix_fmt == AV_PIX_FMT_MONOWHITE || pix_fmt == AV_PIX_FMT_MONOBLACK;
+ int fill = pix_fmt == AV_PIX_FMT_MONOWHITE ? 0xFF : 0;
+ if (nb_planes != 1 || !(rgb || mono) || bytewidth < 1)
+ return AVERROR(EINVAL);
+
+ if (!dst_data)
+ return 0;
+
+ data = dst_data[0];
+
+ // (Bitstream + alpha will be handled incorrectly - it'll remain transparent.)
+ for (;height > 0; height--) {
+ memset(data, fill, bytewidth);
+ data += dst_linesize[0];
+ }
+ return 0;
+ }
+
+ for (c = 0; c < desc->nb_components; c++) {
+ const AVComponentDescriptor comp = desc->comp[c];
+
+ // We try to operate on entire non-subsampled pixel groups (for
+ // AV_PIX_FMT_UYVY422 this would mean two consecutive pixels).
+ clear_block_size[comp.plane] = FFMAX(clear_block_size[comp.plane], comp.step);
+
+ if (clear_block_size[comp.plane] > MAX_BLOCK_SIZE)
+ return AVERROR(EINVAL);
+ }
+
+ // Create a byte array for clearing 1 pixel (sometimes several pixels).
+ for (c = 0; c < desc->nb_components; c++) {
+ const AVComponentDescriptor comp = desc->comp[c];
+ // (Multiple pixels happen e.g. with AV_PIX_FMT_UYVY422.)
+ int w = clear_block_size[comp.plane] / comp.step;
+ uint8_t *c_data[4];
+ const int c_linesize[4] = {0};
+ uint16_t src_array[MAX_BLOCK_SIZE];
+ uint16_t src = 0;
+ int x;
+
+ if (comp.depth > 16)
+ return AVERROR(EINVAL);
+ if (!rgb && comp.depth < 8)
+ return AVERROR(EINVAL);
+ if (w < 1)
+ return AVERROR(EINVAL);
+
+ if (c == 0 && limited) {
+ src = 16 << (comp.depth - 8);
+ } else if ((c == 1 || c == 2) && !rgb) {
+ src = 128 << (comp.depth - 8);
+ } else if (c == 3) {
+ // (Assume even limited YUV uses full range alpha.)
+ src = (1 << comp.depth) - 1;
+ }
+
+ for (x = 0; x < w; x++)
+ src_array[x] = src;
+
+ for (x = 0; x < 4; x++)
+ c_data[x] = &clear_block[x][0];
+
+ av_write_image_line(src_array, c_data, c_linesize, desc, 0, 0, c, w);
+ }
+
+ for (plane = 0; plane < nb_planes; plane++) {
+ plane_line_bytes[plane] = av_image_get_linesize(pix_fmt, width, plane);
+ if (plane_line_bytes[plane] < 0)
+ return AVERROR(EINVAL);
+ }
+
+ if (!dst_data)
+ return 0;
+
+ for (plane = 0; plane < nb_planes; plane++) {
+ size_t bytewidth = plane_line_bytes[plane];
+ uint8_t *data = dst_data[plane];
+ int chroma_div = plane == 1 || plane == 2 ? desc->log2_chroma_h : 0;
+ int plane_h = ((height + ( 1 << chroma_div) - 1)) >> chroma_div;
+
+ for (; plane_h > 0; plane_h--) {
+ memset_bytes(data, bytewidth, &clear_block[plane][0], clear_block_size[plane]);
+ data += dst_linesize[plane];
+ }
+ }
+
+ return 0;
+}
diff --git a/media/ffvpx/libavutil/imgutils.h b/media/ffvpx/libavutil/imgutils.h
index 23282a38f..5b790ecf0 100644
--- a/media/ffvpx/libavutil/imgutils.h
+++ b/media/ffvpx/libavutil/imgutils.h
@@ -121,6 +121,24 @@ void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
enum AVPixelFormat pix_fmt, int width, int height);
/**
+ * Copy image data located in uncacheable (e.g. GPU mapped) memory. Where
+ * available, this function will use special functionality for reading from such
+ * memory, which may result in greatly improved performance compared to plain
+ * av_image_copy().
+ *
+ * The data pointers and the linesizes must be aligned to the maximum required
+ * by the CPU architecture.
+ *
+ * @note The linesize parameters have the type ptrdiff_t here, while they are
+ * int for av_image_copy().
+ * @note On x86, the linesizes currently need to be aligned to the cacheline
+ * size (i.e. 64) to get improved performance.
+ */
+void av_image_copy_uc_from(uint8_t *dst_data[4], const ptrdiff_t dst_linesizes[4],
+ const uint8_t *src_data[4], const ptrdiff_t src_linesizes[4],
+ enum AVPixelFormat pix_fmt, int width, int height);
+
+/**
* Setup the data pointers and linesizes based on the specified image
* parameters and the provided array.
*
@@ -137,7 +155,7 @@ void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4],
* one call, use av_image_alloc().
*
* @param dst_data data pointers to be filled in
- * @param dst_linesizes linesizes for the image in dst_data to be filled in
+ * @param dst_linesize linesizes for the image in dst_data to be filled in
* @param src buffer which will contain or contains the actual image data, can be NULL
* @param pix_fmt the pixel format of the image
* @param width the width of the image in pixels
@@ -154,7 +172,11 @@ int av_image_fill_arrays(uint8_t *dst_data[4], int dst_linesize[4],
* Return the size in bytes of the amount of data required to store an
* image with the given parameters.
*
- * @param[in] align the assumed linesize alignment
+ * @param pix_fmt the pixel format of the image
+ * @param width the width of the image in pixels
+ * @param height the height of the image in pixels
+ * @param align the assumed linesize alignment
+ * @return the buffer size in bytes, a negative error code in case of failure
*/
int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height, int align);
@@ -167,7 +189,7 @@ int av_image_get_buffer_size(enum AVPixelFormat pix_fmt, int width, int height,
* @param dst a buffer into which picture data will be copied
* @param dst_size the size in bytes of dst
* @param src_data pointers containing the source image data
- * @param src_linesizes linesizes for the image in src_data
+ * @param src_linesize linesizes for the image in src_data
* @param pix_fmt the pixel format of the source image
* @param width the width of the source image in pixels
* @param height the height of the source image in pixels
@@ -192,6 +214,21 @@ int av_image_copy_to_buffer(uint8_t *dst, int dst_size,
int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *log_ctx);
/**
+ * Check if the given dimension of an image is valid, meaning that all
+ * bytes of a plane of an image with the specified pix_fmt can be addressed
+ * with a signed int.
+ *
+ * @param w the width of the picture
+ * @param h the height of the picture
+ * @param max_pixels the maximum number of pixels the user wants to accept
+ * @param pix_fmt the pixel format, can be AV_PIX_FMT_NONE if unknown.
+ * @param log_offset the offset to sum to the log level for logging with log_ctx
+ * @param log_ctx the parent logging context, it may be NULL
+ * @return >= 0 if valid, a negative error code otherwise
+ */
+int av_image_check_size2(unsigned int w, unsigned int h, int64_t max_pixels, enum AVPixelFormat pix_fmt, int log_offset, void *log_ctx);
+
+/**
* Check if the given sample aspect ratio of an image is valid.
*
* It is considered invalid if the denominator is 0 or if applying the ratio
@@ -206,6 +243,33 @@ int av_image_check_size(unsigned int w, unsigned int h, int log_offset, void *lo
int av_image_check_sar(unsigned int w, unsigned int h, AVRational sar);
/**
+ * Overwrite the image data with black. This is suitable for filling a
+ * sub-rectangle of an image, meaning the padding between the right most pixel
+ * and the left most pixel on the next line will not be overwritten. For some
+ * formats, the image size might be rounded up due to inherent alignment.
+ *
+ * If the pixel format has alpha, the alpha is cleared to opaque.
+ *
+ * This can return an error if the pixel format is not supported. Normally, all
+ * non-hwaccel pixel formats should be supported.
+ *
+ * Passing NULL for dst_data is allowed. Then the function returns whether the
+ * operation would have succeeded. (It can return an error if the pix_fmt is
+ * not supported.)
+ *
+ * @param dst_data data pointers to destination image
+ * @param dst_linesize linesizes for the destination image
+ * @param pix_fmt the pixel format of the image
+ * @param range the color range of the image (important for colorspaces such as YUV)
+ * @param width the width of the image in pixels
+ * @param height the height of the image in pixels
+ * @return 0 if the image data was cleared, a negative AVERROR code otherwise
+ */
+int av_image_fill_black(uint8_t *dst_data[4], const ptrdiff_t dst_linesize[4],
+ enum AVPixelFormat pix_fmt, enum AVColorRange range,
+ int width, int height);
+
+/**
* @}
*/
diff --git a/media/ffvpx/libavutil/imgutils_internal.h b/media/ffvpx/libavutil/imgutils_internal.h
new file mode 100644
index 000000000..d51585841
--- /dev/null
+++ b/media/ffvpx/libavutil/imgutils_internal.h
@@ -0,0 +1,30 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_IMGUTILS_INTERNAL_H
+#define AVUTIL_IMGUTILS_INTERNAL_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+int ff_image_copy_plane_uc_from_x86(uint8_t *dst, ptrdiff_t dst_linesize,
+ const uint8_t *src, ptrdiff_t src_linesize,
+ ptrdiff_t bytewidth, int height);
+
+
+#endif /* AVUTIL_IMGUTILS_INTERNAL_H */
diff --git a/media/ffvpx/libavutil/internal.h b/media/ffvpx/libavutil/internal.h
index e995af97e..a2d73e3cc 100644
--- a/media/ffvpx/libavutil/internal.h
+++ b/media/ffvpx/libavutil/internal.h
@@ -30,6 +30,9 @@
# define NDEBUG
#endif
+// This can be enabled to allow detection of additional integer overflows with ubsan
+//#define CHECKED
+
#include <limits.h>
#include <stdint.h>
#include <stddef.h>
@@ -258,6 +261,16 @@ void avpriv_request_sample(void *avc,
# define ff_dlog(ctx, ...) do { if (0) av_log(ctx, AV_LOG_DEBUG, __VA_ARGS__); } while (0)
#endif
+// For debuging we use signed operations so overflows can be detected (by ubsan)
+// For production we use unsigned so there are no undefined operations
+#ifdef CHECKED
+#define SUINT int
+#define SUINT32 int32_t
+#else
+#define SUINT unsigned
+#define SUINT32 uint32_t
+#endif
+
/**
* Clip and convert a double value into the long long amin-amax range.
* This function is needed because conversion of floating point to integers when
@@ -340,6 +353,4 @@ void ff_check_pixfmt_descriptors(void);
*/
int avpriv_dict_set_timestamp(AVDictionary **dict, const char *key, int64_t timestamp);
-extern const uint8_t ff_reverse[256];
-
#endif /* AVUTIL_INTERNAL_H */
diff --git a/media/ffvpx/libavutil/intreadwrite.h b/media/ffvpx/libavutil/intreadwrite.h
index 51fbe30a2..d54d4b91d 100644
--- a/media/ffvpx/libavutil/intreadwrite.h
+++ b/media/ffvpx/libavutil/intreadwrite.h
@@ -229,6 +229,11 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
# define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p)))
# define AV_WN(s, p, v) (*((__unaligned uint##s##_t*)(p)) = (v))
+#elif defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_X64)) && AV_HAVE_FAST_UNALIGNED
+
+# define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p)))
+# define AV_WN(s, p, v) (*((__unaligned uint##s##_t*)(p)) = (v))
+
#elif AV_HAVE_FAST_UNALIGNED
# define AV_RN(s, p) (((const av_alias##s*)(p))->u##s)
@@ -242,8 +247,8 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
((const uint8_t*)(x))[1])
#endif
#ifndef AV_WB16
-# define AV_WB16(p, darg) do { \
- unsigned d = (darg); \
+# define AV_WB16(p, val) do { \
+ uint16_t d = (val); \
((uint8_t*)(p))[1] = (d); \
((uint8_t*)(p))[0] = (d)>>8; \
} while(0)
@@ -255,8 +260,8 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
((const uint8_t*)(x))[0])
#endif
#ifndef AV_WL16
-# define AV_WL16(p, darg) do { \
- unsigned d = (darg); \
+# define AV_WL16(p, val) do { \
+ uint16_t d = (val); \
((uint8_t*)(p))[0] = (d); \
((uint8_t*)(p))[1] = (d)>>8; \
} while(0)
@@ -270,8 +275,8 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
((const uint8_t*)(x))[3])
#endif
#ifndef AV_WB32
-# define AV_WB32(p, darg) do { \
- unsigned d = (darg); \
+# define AV_WB32(p, val) do { \
+ uint32_t d = (val); \
((uint8_t*)(p))[3] = (d); \
((uint8_t*)(p))[2] = (d)>>8; \
((uint8_t*)(p))[1] = (d)>>16; \
@@ -287,8 +292,8 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
((const uint8_t*)(x))[0])
#endif
#ifndef AV_WL32
-# define AV_WL32(p, darg) do { \
- unsigned d = (darg); \
+# define AV_WL32(p, val) do { \
+ uint32_t d = (val); \
((uint8_t*)(p))[0] = (d); \
((uint8_t*)(p))[1] = (d)>>8; \
((uint8_t*)(p))[2] = (d)>>16; \
@@ -308,8 +313,8 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
(uint64_t)((const uint8_t*)(x))[7])
#endif
#ifndef AV_WB64
-# define AV_WB64(p, darg) do { \
- uint64_t d = (darg); \
+# define AV_WB64(p, val) do { \
+ uint64_t d = (val); \
((uint8_t*)(p))[7] = (d); \
((uint8_t*)(p))[6] = (d)>>8; \
((uint8_t*)(p))[5] = (d)>>16; \
@@ -333,8 +338,8 @@ union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
(uint64_t)((const uint8_t*)(x))[0])
#endif
#ifndef AV_WL64
-# define AV_WL64(p, darg) do { \
- uint64_t d = (darg); \
+# define AV_WL64(p, val) do { \
+ uint64_t d = (val); \
((uint8_t*)(p))[0] = (d); \
((uint8_t*)(p))[1] = (d)>>8; \
((uint8_t*)(p))[2] = (d)>>16; \
diff --git a/media/ffvpx/libavutil/log.c b/media/ffvpx/libavutil/log.c
index 44c11cb09..be806202f 100644
--- a/media/ffvpx/libavutil/log.c
+++ b/media/ffvpx/libavutil/log.c
@@ -168,19 +168,19 @@ static void colored_fputs(int level, int tint, const char *str)
#else
if (local_use_color == 1) {
fprintf(stderr,
- "\033[%d;3%dm%s\033[0m",
+ "\033[%"PRIu32";3%"PRIu32"m%s\033[0m",
(color[level] >> 4) & 15,
color[level] & 15,
str);
} else if (tint && use_color == 256) {
fprintf(stderr,
- "\033[48;5;%dm\033[38;5;%dm%s\033[0m",
+ "\033[48;5;%"PRIu32"m\033[38;5;%dm%s\033[0m",
(color[level] >> 16) & 0xff,
tint,
str);
} else if (local_use_color == 256) {
fprintf(stderr,
- "\033[48;5;%dm\033[38;5;%dm%s\033[0m",
+ "\033[48;5;%"PRIu32"m\033[38;5;%"PRIu32"m%s\033[0m",
(color[level] >> 16) & 0xff,
(color[level] >> 8) & 0xff,
str);
diff --git a/media/ffvpx/libavutil/lzo.c b/media/ffvpx/libavutil/lzo.c
deleted file mode 100644
index 1ae076e33..000000000
--- a/media/ffvpx/libavutil/lzo.c
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * LZO 1x decompression
- * Copyright (c) 2006 Reimar Doeffinger
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include <string.h>
-
-#include "avutil.h"
-#include "avassert.h"
-#include "common.h"
-#include "intreadwrite.h"
-#include "lzo.h"
-
-/// Define if we may write up to 12 bytes beyond the output buffer.
-#define OUTBUF_PADDED 1
-/// Define if we may read up to 8 bytes beyond the input buffer.
-#define INBUF_PADDED 1
-
-typedef struct LZOContext {
- const uint8_t *in, *in_end;
- uint8_t *out_start, *out, *out_end;
- int error;
-} LZOContext;
-
-/**
- * @brief Reads one byte from the input buffer, avoiding an overrun.
- * @return byte read
- */
-static inline int get_byte(LZOContext *c)
-{
- if (c->in < c->in_end)
- return *c->in++;
- c->error |= AV_LZO_INPUT_DEPLETED;
- return 1;
-}
-
-#ifdef INBUF_PADDED
-#define GETB(c) (*(c).in++)
-#else
-#define GETB(c) get_byte(&(c))
-#endif
-
-/**
- * @brief Decodes a length value in the coding used by lzo.
- * @param x previous byte value
- * @param mask bits used from x
- * @return decoded length value
- */
-static inline int get_len(LZOContext *c, int x, int mask)
-{
- int cnt = x & mask;
- if (!cnt) {
- while (!(x = get_byte(c))) {
- if (cnt >= INT_MAX - 1000) {
- c->error |= AV_LZO_ERROR;
- break;
- }
- cnt += 255;
- }
- cnt += mask + x;
- }
- return cnt;
-}
-
-/**
- * @brief Copies bytes from input to output buffer with checking.
- * @param cnt number of bytes to copy, must be >= 0
- */
-static inline void copy(LZOContext *c, int cnt)
-{
- register const uint8_t *src = c->in;
- register uint8_t *dst = c->out;
- av_assert0(cnt >= 0);
- if (cnt > c->in_end - src) {
- cnt = FFMAX(c->in_end - src, 0);
- c->error |= AV_LZO_INPUT_DEPLETED;
- }
- if (cnt > c->out_end - dst) {
- cnt = FFMAX(c->out_end - dst, 0);
- c->error |= AV_LZO_OUTPUT_FULL;
- }
-#if defined(INBUF_PADDED) && defined(OUTBUF_PADDED)
- AV_COPY32U(dst, src);
- src += 4;
- dst += 4;
- cnt -= 4;
- if (cnt > 0)
-#endif
- memcpy(dst, src, cnt);
- c->in = src + cnt;
- c->out = dst + cnt;
-}
-
-/**
- * @brief Copies previously decoded bytes to current position.
- * @param back how many bytes back we start, must be > 0
- * @param cnt number of bytes to copy, must be > 0
- *
- * cnt > back is valid, this will copy the bytes we just copied,
- * thus creating a repeating pattern with a period length of back.
- */
-static inline void copy_backptr(LZOContext *c, int back, int cnt)
-{
- register uint8_t *dst = c->out;
- av_assert0(cnt > 0);
- if (dst - c->out_start < back) {
- c->error |= AV_LZO_INVALID_BACKPTR;
- return;
- }
- if (cnt > c->out_end - dst) {
- cnt = FFMAX(c->out_end - dst, 0);
- c->error |= AV_LZO_OUTPUT_FULL;
- }
- av_memcpy_backptr(dst, back, cnt);
- c->out = dst + cnt;
-}
-
-int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen)
-{
- int state = 0;
- int x;
- LZOContext c;
- if (*outlen <= 0 || *inlen <= 0) {
- int res = 0;
- if (*outlen <= 0)
- res |= AV_LZO_OUTPUT_FULL;
- if (*inlen <= 0)
- res |= AV_LZO_INPUT_DEPLETED;
- return res;
- }
- c.in = in;
- c.in_end = (const uint8_t *)in + *inlen;
- c.out = c.out_start = out;
- c.out_end = (uint8_t *)out + *outlen;
- c.error = 0;
- x = GETB(c);
- if (x > 17) {
- copy(&c, x - 17);
- x = GETB(c);
- if (x < 16)
- c.error |= AV_LZO_ERROR;
- }
- if (c.in > c.in_end)
- c.error |= AV_LZO_INPUT_DEPLETED;
- while (!c.error) {
- int cnt, back;
- if (x > 15) {
- if (x > 63) {
- cnt = (x >> 5) - 1;
- back = (GETB(c) << 3) + ((x >> 2) & 7) + 1;
- } else if (x > 31) {
- cnt = get_len(&c, x, 31);
- x = GETB(c);
- back = (GETB(c) << 6) + (x >> 2) + 1;
- } else {
- cnt = get_len(&c, x, 7);
- back = (1 << 14) + ((x & 8) << 11);
- x = GETB(c);
- back += (GETB(c) << 6) + (x >> 2);
- if (back == (1 << 14)) {
- if (cnt != 1)
- c.error |= AV_LZO_ERROR;
- break;
- }
- }
- } else if (!state) {
- cnt = get_len(&c, x, 15);
- copy(&c, cnt + 3);
- x = GETB(c);
- if (x > 15)
- continue;
- cnt = 1;
- back = (1 << 11) + (GETB(c) << 2) + (x >> 2) + 1;
- } else {
- cnt = 0;
- back = (GETB(c) << 2) + (x >> 2) + 1;
- }
- copy_backptr(&c, back, cnt + 2);
- state =
- cnt = x & 3;
- copy(&c, cnt);
- x = GETB(c);
- }
- *inlen = c.in_end - c.in;
- if (c.in > c.in_end)
- *inlen = 0;
- *outlen = c.out_end - c.out;
- return c.error;
-}
diff --git a/media/ffvpx/libavutil/lzo.h b/media/ffvpx/libavutil/lzo.h
deleted file mode 100644
index c03403992..000000000
--- a/media/ffvpx/libavutil/lzo.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * LZO 1x decompression
- * copyright (c) 2006 Reimar Doeffinger
- *
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVUTIL_LZO_H
-#define AVUTIL_LZO_H
-
-/**
- * @defgroup lavu_lzo LZO
- * @ingroup lavu_crypto
- *
- * @{
- */
-
-#include <stdint.h>
-
-/** @name Error flags returned by av_lzo1x_decode
- * @{ */
-/// end of the input buffer reached before decoding finished
-#define AV_LZO_INPUT_DEPLETED 1
-/// decoded data did not fit into output buffer
-#define AV_LZO_OUTPUT_FULL 2
-/// a reference to previously decoded data was wrong
-#define AV_LZO_INVALID_BACKPTR 4
-/// a non-specific error in the compressed bitstream
-#define AV_LZO_ERROR 8
-/** @} */
-
-#define AV_LZO_INPUT_PADDING 8
-#define AV_LZO_OUTPUT_PADDING 12
-
-/**
- * @brief Decodes LZO 1x compressed data.
- * @param out output buffer
- * @param outlen size of output buffer, number of bytes left are returned here
- * @param in input buffer
- * @param inlen size of input buffer, number of bytes left are returned here
- * @return 0 on success, otherwise a combination of the error flags above
- *
- * Make sure all buffers are appropriately padded, in must provide
- * AV_LZO_INPUT_PADDING, out must provide AV_LZO_OUTPUT_PADDING additional bytes.
- */
-int av_lzo1x_decode(void *out, int *outlen, const void *in, int *inlen);
-
-/**
- * @}
- */
-
-#endif /* AVUTIL_LZO_H */
diff --git a/media/ffvpx/libavutil/mathematics.c b/media/ffvpx/libavutil/mathematics.c
index 20ff37f5e..1bf044cdf 100644
--- a/media/ffvpx/libavutil/mathematics.c
+++ b/media/ffvpx/libavutil/mathematics.c
@@ -115,15 +115,15 @@ int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd)
if (t1 > INT64_MAX)
return INT64_MIN;
return t1;
- }
#else
+ /* reference code doing (a*b + r) / c, requires libavutil/integer.h */
AVInteger ai;
ai = av_mul_i(av_int2i(a), av_int2i(b));
ai = av_add_i(ai, av_int2i(r));
return av_i2int(av_div_i(ai, av_int2i(c)));
- }
#endif
+ }
}
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
diff --git a/media/ffvpx/libavutil/mem.c b/media/ffvpx/libavutil/mem.c
index 1a8fc21e9..36740f115 100644
--- a/media/ffvpx/libavutil/mem.c
+++ b/media/ffvpx/libavutil/mem.c
@@ -77,22 +77,12 @@ void av_max_alloc(size_t max){
void *av_malloc(size_t size)
{
void *ptr = NULL;
-#if CONFIG_MEMALIGN_HACK
- long diff;
-#endif
/* let's disallow possibly ambiguous cases */
if (size > (max_alloc_size - 32))
return NULL;
-#if CONFIG_MEMALIGN_HACK
- ptr = malloc(size + ALIGN);
- if (!ptr)
- return ptr;
- diff = ((~(long)ptr)&(ALIGN - 1)) + 1;
- ptr = (char *)ptr + diff;
- ((char *)ptr)[-1] = diff;
-#elif HAVE_POSIX_MEMALIGN
+#if HAVE_POSIX_MEMALIGN
if (size) //OS X on SDK 10.6 has a broken posix_memalign implementation
if (posix_memalign(&ptr, ALIGN, size))
ptr = NULL;
@@ -144,25 +134,11 @@ void *av_malloc(size_t size)
void *av_realloc(void *ptr, size_t size)
{
-#if CONFIG_MEMALIGN_HACK
- int diff;
-#endif
-
/* let's disallow possibly ambiguous cases */
if (size > (max_alloc_size - 32))
return NULL;
-#if CONFIG_MEMALIGN_HACK
- //FIXME this isn't aligned correctly, though it probably isn't needed
- if (!ptr)
- return av_malloc(size);
- diff = ((char *)ptr)[-1];
- av_assert0(diff>0 && diff<=ALIGN);
- ptr = realloc((char *)ptr - diff, size + diff);
- if (ptr)
- ptr = (char *)ptr + diff;
- return ptr;
-#elif HAVE_ALIGNED_MALLOC
+#if HAVE_ALIGNED_MALLOC
return _aligned_realloc(ptr, size + !size, ALIGN);
#else
return realloc(ptr, size + !size);
@@ -227,13 +203,7 @@ int av_reallocp_array(void *ptr, size_t nmemb, size_t size)
void av_free(void *ptr)
{
-#if CONFIG_MEMALIGN_HACK
- if (ptr) {
- int v= ((char *)ptr)[-1];
- av_assert0(v>0 && v<=ALIGN);
- free((char *)ptr - v);
- }
-#elif HAVE_ALIGNED_MALLOC
+#if HAVE_ALIGNED_MALLOC
_aligned_free(ptr);
#else
free(ptr);
diff --git a/media/ffvpx/libavutil/mem.h b/media/ffvpx/libavutil/mem.h
index f9d888478..527cd0319 100644
--- a/media/ffvpx/libavutil/mem.h
+++ b/media/ffvpx/libavutil/mem.h
@@ -97,7 +97,10 @@
#define DECLARE_ASM_CONST(n,t,v) \
AV_PRAGMA(DATA_ALIGN(v,n)) \
static const t __attribute__((aligned(n))) v
-#elif defined(__GNUC__)
+#elif defined(__DJGPP__)
+ #define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (FFMIN(n, 16)))) v
+ #define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (FFMIN(n, 16)))) v
+#elif defined(__GNUC__) || defined(__clang__)
#define DECLARE_ALIGNED(n,t,v) t __attribute__ ((aligned (n))) v
#define DECLARE_ASM_CONST(n,t,v) static const t av_used __attribute__ ((aligned (n))) v
#elif defined(_MSC_VER)
diff --git a/media/ffvpx/libavutil/motion_vector.h b/media/ffvpx/libavutil/motion_vector.h
deleted file mode 100644
index ec2955638..000000000
--- a/media/ffvpx/libavutil/motion_vector.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * This file is part of FFmpeg.
- *
- * FFmpeg is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * FFmpeg 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
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with FFmpeg; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#ifndef AVUTIL_MOTION_VECTOR_H
-#define AVUTIL_MOTION_VECTOR_H
-
-#include <stdint.h>
-
-typedef struct AVMotionVector {
- /**
- * Where the current macroblock comes from; negative value when it comes
- * from the past, positive value when it comes from the future.
- * XXX: set exact relative ref frame reference instead of a +/- 1 "direction".
- */
- int32_t source;
- /**
- * Width and height of the block.
- */
- uint8_t w, h;
- /**
- * Absolute source position. Can be outside the frame area.
- */
- int16_t src_x, src_y;
- /**
- * Absolute destination position. Can be outside the frame area.
- */
- int16_t dst_x, dst_y;
- /**
- * Extra flag information.
- * Currently unused.
- */
- uint64_t flags;
- /**
- * Motion vector
- * src_x = dst_x + motion_x / motion_scale
- * src_y = dst_y + motion_y / motion_scale
- */
- int32_t motion_x, motion_y;
- uint16_t motion_scale;
-} AVMotionVector;
-
-#endif /* AVUTIL_MOTION_VECTOR_H */
diff --git a/media/ffvpx/libavutil/moz.build b/media/ffvpx/libavutil/moz.build
index edc0888b1..201b62fed 100644
--- a/media/ffvpx/libavutil/moz.build
+++ b/media/ffvpx/libavutil/moz.build
@@ -22,7 +22,6 @@ SOURCES += [
'cpu.c',
'crc.c',
'dict.c',
- 'display.c',
'dummy_funcs.c',
'error.c',
'eval.c',
@@ -38,12 +37,14 @@ SOURCES += [
'log2_tab.c',
'mathematics.c',
'mem.c',
+ 'opt.c',
'parseutils.c',
'pixdesc.c',
'pixelutils.c',
'rational.c',
'reverse.c',
'samplefmt.c',
+ 'slicethread.c',
'threadmessage.c',
'time.c',
'timecode.c',
diff --git a/media/ffvpx/libavutil/opt.c b/media/ffvpx/libavutil/opt.c
new file mode 100644
index 000000000..df88663e3
--- /dev/null
+++ b/media/ffvpx/libavutil/opt.c
@@ -0,0 +1,2025 @@
+/*
+ * AVOptions
+ * Copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/**
+ * @file
+ * AVOptions
+ * @author Michael Niedermayer <michaelni@gmx.at>
+ */
+
+#include "avutil.h"
+#include "avassert.h"
+#include "avstring.h"
+#include "channel_layout.h"
+#include "common.h"
+#include "dict.h"
+#include "eval.h"
+#include "log.h"
+#include "parseutils.h"
+#include "pixdesc.h"
+#include "mathematics.h"
+#include "opt.h"
+#include "samplefmt.h"
+#include "bprint.h"
+
+#include <float.h>
+
+const AVOption *av_opt_next(const void *obj, const AVOption *last)
+{
+ const AVClass *class;
+ if (!obj)
+ return NULL;
+ class = *(const AVClass**)obj;
+ if (!last && class && class->option && class->option[0].name)
+ return class->option;
+ if (last && last[1].name)
+ return ++last;
+ return NULL;
+}
+
+static int read_number(const AVOption *o, const void *dst, double *num, int *den, int64_t *intnum)
+{
+ switch (o->type) {
+ case AV_OPT_TYPE_FLAGS:
+ *intnum = *(unsigned int*)dst;
+ return 0;
+ case AV_OPT_TYPE_PIXEL_FMT:
+ *intnum = *(enum AVPixelFormat *)dst;
+ return 0;
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ *intnum = *(enum AVSampleFormat *)dst;
+ return 0;
+ case AV_OPT_TYPE_BOOL:
+ case AV_OPT_TYPE_INT:
+ *intnum = *(int *)dst;
+ return 0;
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ case AV_OPT_TYPE_DURATION:
+ case AV_OPT_TYPE_INT64:
+ case AV_OPT_TYPE_UINT64:
+ *intnum = *(int64_t *)dst;
+ return 0;
+ case AV_OPT_TYPE_FLOAT:
+ *num = *(float *)dst;
+ return 0;
+ case AV_OPT_TYPE_DOUBLE:
+ *num = *(double *)dst;
+ return 0;
+ case AV_OPT_TYPE_RATIONAL:
+ *intnum = ((AVRational *)dst)->num;
+ *den = ((AVRational *)dst)->den;
+ return 0;
+ case AV_OPT_TYPE_CONST:
+ *num = o->default_val.dbl;
+ return 0;
+ }
+ return AVERROR(EINVAL);
+}
+
+static int write_number(void *obj, const AVOption *o, void *dst, double num, int den, int64_t intnum)
+{
+ if (o->type != AV_OPT_TYPE_FLAGS &&
+ (!den || o->max * den < num * intnum || o->min * den > num * intnum)) {
+ num = den ? num * intnum / den : (num && intnum ? INFINITY : NAN);
+ av_log(obj, AV_LOG_ERROR, "Value %f for parameter '%s' out of range [%g - %g]\n",
+ num, o->name, o->min, o->max);
+ return AVERROR(ERANGE);
+ }
+ if (o->type == AV_OPT_TYPE_FLAGS) {
+ double d = num*intnum/den;
+ if (d < -1.5 || d > 0xFFFFFFFF+0.5 || (llrint(d*256) & 255)) {
+ av_log(obj, AV_LOG_ERROR,
+ "Value %f for parameter '%s' is not a valid set of 32bit integer flags\n",
+ num*intnum/den, o->name);
+ return AVERROR(ERANGE);
+ }
+ }
+
+ switch (o->type) {
+ case AV_OPT_TYPE_PIXEL_FMT:
+ *(enum AVPixelFormat *)dst = llrint(num / den) * intnum;
+ break;
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ *(enum AVSampleFormat *)dst = llrint(num / den) * intnum;
+ break;
+ case AV_OPT_TYPE_BOOL:
+ case AV_OPT_TYPE_FLAGS:
+ case AV_OPT_TYPE_INT:
+ *(int *)dst = llrint(num / den) * intnum;
+ break;
+ case AV_OPT_TYPE_DURATION:
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ case AV_OPT_TYPE_INT64:{
+ double d = num / den;
+ if (intnum == 1 && d == (double)INT64_MAX) {
+ *(int64_t *)dst = INT64_MAX;
+ } else
+ *(int64_t *)dst = llrint(d) * intnum;
+ break;}
+ case AV_OPT_TYPE_UINT64:{
+ double d = num / den;
+ // We must special case uint64_t here as llrint() does not support values
+ // outside the int64_t range and there is no portable function which does
+ // "INT64_MAX + 1ULL" is used as it is representable exactly as IEEE double
+ // while INT64_MAX is not
+ if (intnum == 1 && d == (double)UINT64_MAX) {
+ *(uint64_t *)dst = UINT64_MAX;
+ } else if (d > INT64_MAX + 1ULL) {
+ *(uint64_t *)dst = (llrint(d - (INT64_MAX + 1ULL)) + (INT64_MAX + 1ULL))*intnum;
+ } else {
+ *(uint64_t *)dst = llrint(d) * intnum;
+ }
+ break;}
+ case AV_OPT_TYPE_FLOAT:
+ *(float *)dst = num * intnum / den;
+ break;
+ case AV_OPT_TYPE_DOUBLE:
+ *(double *)dst = num * intnum / den;
+ break;
+ case AV_OPT_TYPE_RATIONAL:
+ case AV_OPT_TYPE_VIDEO_RATE:
+ if ((int) num == num)
+ *(AVRational *)dst = (AVRational) { num *intnum, den };
+ else
+ *(AVRational *)dst = av_d2q(num * intnum / den, 1 << 24);
+ break;
+ default:
+ return AVERROR(EINVAL);
+ }
+ return 0;
+}
+
+static int hexchar2int(char c) {
+ if (c >= '0' && c <= '9')
+ return c - '0';
+ if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ if (c >= 'A' && c <= 'F')
+ return c - 'A' + 10;
+ return -1;
+}
+
+static int set_string_binary(void *obj, const AVOption *o, const char *val, uint8_t **dst)
+{
+ int *lendst = (int *)(dst + 1);
+ uint8_t *bin, *ptr;
+ int len;
+
+ av_freep(dst);
+ *lendst = 0;
+
+ if (!val || !(len = strlen(val)))
+ return 0;
+
+ if (len & 1)
+ return AVERROR(EINVAL);
+ len /= 2;
+
+ ptr = bin = av_malloc(len);
+ if (!ptr)
+ return AVERROR(ENOMEM);
+ while (*val) {
+ int a = hexchar2int(*val++);
+ int b = hexchar2int(*val++);
+ if (a < 0 || b < 0) {
+ av_free(bin);
+ return AVERROR(EINVAL);
+ }
+ *ptr++ = (a << 4) | b;
+ }
+ *dst = bin;
+ *lendst = len;
+
+ return 0;
+}
+
+static int set_string(void *obj, const AVOption *o, const char *val, uint8_t **dst)
+{
+ av_freep(dst);
+ *dst = av_strdup(val);
+ return *dst ? 0 : AVERROR(ENOMEM);
+}
+
+#define DEFAULT_NUMVAL(opt) ((opt->type == AV_OPT_TYPE_INT64 || \
+ opt->type == AV_OPT_TYPE_UINT64 || \
+ opt->type == AV_OPT_TYPE_CONST || \
+ opt->type == AV_OPT_TYPE_FLAGS || \
+ opt->type == AV_OPT_TYPE_INT) \
+ ? opt->default_val.i64 \
+ : opt->default_val.dbl)
+
+static int set_string_number(void *obj, void *target_obj, const AVOption *o, const char *val, void *dst)
+{
+ int ret = 0;
+ int num, den;
+ char c;
+
+ if (sscanf(val, "%d%*1[:/]%d%c", &num, &den, &c) == 2) {
+ if ((ret = write_number(obj, o, dst, 1, den, num)) >= 0)
+ return ret;
+ ret = 0;
+ }
+
+ for (;;) {
+ int i = 0;
+ char buf[256];
+ int cmd = 0;
+ double d;
+ int64_t intnum = 1;
+
+ if (o->type == AV_OPT_TYPE_FLAGS) {
+ if (*val == '+' || *val == '-')
+ cmd = *(val++);
+ for (; i < sizeof(buf) - 1 && val[i] && val[i] != '+' && val[i] != '-'; i++)
+ buf[i] = val[i];
+ buf[i] = 0;
+ }
+
+ {
+ const AVOption *o_named = av_opt_find(target_obj, i ? buf : val, o->unit, 0, 0);
+ int res;
+ int ci = 0;
+ double const_values[64];
+ const char * const_names[64];
+ if (o_named && o_named->type == AV_OPT_TYPE_CONST)
+ d = DEFAULT_NUMVAL(o_named);
+ else {
+ if (o->unit) {
+ for (o_named = NULL; o_named = av_opt_next(target_obj, o_named); ) {
+ if (o_named->type == AV_OPT_TYPE_CONST &&
+ o_named->unit &&
+ !strcmp(o_named->unit, o->unit)) {
+ if (ci + 6 >= FF_ARRAY_ELEMS(const_values)) {
+ av_log(obj, AV_LOG_ERROR, "const_values array too small for %s\n", o->unit);
+ return AVERROR_PATCHWELCOME;
+ }
+ const_names [ci ] = o_named->name;
+ const_values[ci++] = DEFAULT_NUMVAL(o_named);
+ }
+ }
+ }
+ const_names [ci ] = "default";
+ const_values[ci++] = DEFAULT_NUMVAL(o);
+ const_names [ci ] = "max";
+ const_values[ci++] = o->max;
+ const_names [ci ] = "min";
+ const_values[ci++] = o->min;
+ const_names [ci ] = "none";
+ const_values[ci++] = 0;
+ const_names [ci ] = "all";
+ const_values[ci++] = ~0;
+ const_names [ci] = NULL;
+ const_values[ci] = 0;
+
+ res = av_expr_parse_and_eval(&d, i ? buf : val, const_names,
+ const_values, NULL, NULL, NULL, NULL, NULL, 0, obj);
+ if (res < 0) {
+ av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\"\n", val);
+ return res;
+ }
+ }
+ }
+ if (o->type == AV_OPT_TYPE_FLAGS) {
+ read_number(o, dst, NULL, NULL, &intnum);
+ if (cmd == '+')
+ d = intnum | (int64_t)d;
+ else if (cmd == '-')
+ d = intnum &~(int64_t)d;
+ }
+
+ if ((ret = write_number(obj, o, dst, d, 1, 1)) < 0)
+ return ret;
+ val += i;
+ if (!i || !*val)
+ return 0;
+ }
+}
+
+static int set_string_image_size(void *obj, const AVOption *o, const char *val, int *dst)
+{
+ int ret;
+
+ if (!val || !strcmp(val, "none")) {
+ dst[0] =
+ dst[1] = 0;
+ return 0;
+ }
+ ret = av_parse_video_size(dst, dst + 1, val);
+ if (ret < 0)
+ av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as image size\n", val);
+ return ret;
+}
+
+static int set_string_video_rate(void *obj, const AVOption *o, const char *val, AVRational *dst)
+{
+ int ret;
+ if (!val) {
+ ret = AVERROR(EINVAL);
+ } else {
+ ret = av_parse_video_rate(dst, val);
+ }
+ if (ret < 0)
+ av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as video rate\n", val);
+ return ret;
+}
+
+static int set_string_color(void *obj, const AVOption *o, const char *val, uint8_t *dst)
+{
+ int ret;
+
+ if (!val) {
+ return 0;
+ } else {
+ ret = av_parse_color(dst, val, -1, obj);
+ if (ret < 0)
+ av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as color\n", val);
+ return ret;
+ }
+ return 0;
+}
+
+static const char *get_bool_name(int val)
+{
+ if (val < 0)
+ return "auto";
+ return val ? "true" : "false";
+}
+
+static int set_string_bool(void *obj, const AVOption *o, const char *val, int *dst)
+{
+ int n;
+
+ if (!val)
+ return 0;
+
+ if (!strcmp(val, "auto")) {
+ n = -1;
+ } else if (av_match_name(val, "true,y,yes,enable,enabled,on")) {
+ n = 1;
+ } else if (av_match_name(val, "false,n,no,disable,disabled,off")) {
+ n = 0;
+ } else {
+ char *end = NULL;
+ n = strtol(val, &end, 10);
+ if (val + strlen(val) != end)
+ goto fail;
+ }
+
+ if (n < o->min || n > o->max)
+ goto fail;
+
+ *dst = n;
+ return 0;
+
+fail:
+ av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as boolean\n", val);
+ return AVERROR(EINVAL);
+}
+
+static int set_string_fmt(void *obj, const AVOption *o, const char *val, uint8_t *dst,
+ int fmt_nb, int ((*get_fmt)(const char *)), const char *desc)
+{
+ int fmt, min, max;
+
+ if (!val || !strcmp(val, "none")) {
+ fmt = -1;
+ } else {
+ fmt = get_fmt(val);
+ if (fmt == -1) {
+ char *tail;
+ fmt = strtol(val, &tail, 0);
+ if (*tail || (unsigned)fmt >= fmt_nb) {
+ av_log(obj, AV_LOG_ERROR,
+ "Unable to parse option value \"%s\" as %s\n", val, desc);
+ return AVERROR(EINVAL);
+ }
+ }
+ }
+
+ min = FFMAX(o->min, -1);
+ max = FFMIN(o->max, fmt_nb-1);
+
+ // hack for compatibility with old ffmpeg
+ if(min == 0 && max == 0) {
+ min = -1;
+ max = fmt_nb-1;
+ }
+
+ if (fmt < min || fmt > max) {
+ av_log(obj, AV_LOG_ERROR,
+ "Value %d for parameter '%s' out of %s format range [%d - %d]\n",
+ fmt, o->name, desc, min, max);
+ return AVERROR(ERANGE);
+ }
+
+ *(int *)dst = fmt;
+ return 0;
+}
+
+static int set_string_pixel_fmt(void *obj, const AVOption *o, const char *val, uint8_t *dst)
+{
+ return set_string_fmt(obj, o, val, dst,
+ AV_PIX_FMT_NB, av_get_pix_fmt, "pixel format");
+}
+
+static int set_string_sample_fmt(void *obj, const AVOption *o, const char *val, uint8_t *dst)
+{
+ return set_string_fmt(obj, o, val, dst,
+ AV_SAMPLE_FMT_NB, av_get_sample_fmt, "sample format");
+}
+
+int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
+{
+ int ret = 0;
+ void *dst, *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (!val && (o->type != AV_OPT_TYPE_STRING &&
+ o->type != AV_OPT_TYPE_PIXEL_FMT && o->type != AV_OPT_TYPE_SAMPLE_FMT &&
+ o->type != AV_OPT_TYPE_IMAGE_SIZE && o->type != AV_OPT_TYPE_VIDEO_RATE &&
+ o->type != AV_OPT_TYPE_DURATION && o->type != AV_OPT_TYPE_COLOR &&
+ o->type != AV_OPT_TYPE_CHANNEL_LAYOUT && o->type != AV_OPT_TYPE_BOOL))
+ return AVERROR(EINVAL);
+
+ if (o->flags & AV_OPT_FLAG_READONLY)
+ return AVERROR(EINVAL);
+
+ dst = ((uint8_t *)target_obj) + o->offset;
+ switch (o->type) {
+ case AV_OPT_TYPE_BOOL:
+ return set_string_bool(obj, o, val, dst);
+ case AV_OPT_TYPE_STRING:
+ return set_string(obj, o, val, dst);
+ case AV_OPT_TYPE_BINARY:
+ return set_string_binary(obj, o, val, dst);
+ case AV_OPT_TYPE_FLAGS:
+ case AV_OPT_TYPE_INT:
+ case AV_OPT_TYPE_INT64:
+ case AV_OPT_TYPE_UINT64:
+ case AV_OPT_TYPE_FLOAT:
+ case AV_OPT_TYPE_DOUBLE:
+ case AV_OPT_TYPE_RATIONAL:
+ return set_string_number(obj, target_obj, o, val, dst);
+ case AV_OPT_TYPE_IMAGE_SIZE:
+ return set_string_image_size(obj, o, val, dst);
+ case AV_OPT_TYPE_VIDEO_RATE: {
+ AVRational tmp;
+ ret = set_string_video_rate(obj, o, val, &tmp);
+ if (ret < 0)
+ return ret;
+ return write_number(obj, o, dst, 1, tmp.den, tmp.num);
+ }
+ case AV_OPT_TYPE_PIXEL_FMT:
+ return set_string_pixel_fmt(obj, o, val, dst);
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ return set_string_sample_fmt(obj, o, val, dst);
+ case AV_OPT_TYPE_DURATION:
+ if (!val) {
+ *(int64_t *)dst = 0;
+ return 0;
+ } else {
+ if ((ret = av_parse_time(dst, val, 1)) < 0)
+ av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as duration\n", val);
+ return ret;
+ }
+ break;
+ case AV_OPT_TYPE_COLOR:
+ return set_string_color(obj, o, val, dst);
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ if (!val || !strcmp(val, "none")) {
+ *(int64_t *)dst = 0;
+ } else {
+ int64_t cl = av_get_channel_layout(val);
+ if (!cl) {
+ av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as channel layout\n", val);
+ ret = AVERROR(EINVAL);
+ }
+ *(int64_t *)dst = cl;
+ return ret;
+ }
+ break;
+ }
+
+ av_log(obj, AV_LOG_ERROR, "Invalid option type.\n");
+ return AVERROR(EINVAL);
+}
+
+#define OPT_EVAL_NUMBER(name, opttype, vartype) \
+int av_opt_eval_ ## name(void *obj, const AVOption *o, \
+ const char *val, vartype *name ## _out) \
+{ \
+ if (!o || o->type != opttype || o->flags & AV_OPT_FLAG_READONLY) \
+ return AVERROR(EINVAL); \
+ return set_string_number(obj, obj, o, val, name ## _out); \
+}
+
+OPT_EVAL_NUMBER(flags, AV_OPT_TYPE_FLAGS, int)
+OPT_EVAL_NUMBER(int, AV_OPT_TYPE_INT, int)
+OPT_EVAL_NUMBER(int64, AV_OPT_TYPE_INT64, int64_t)
+OPT_EVAL_NUMBER(float, AV_OPT_TYPE_FLOAT, float)
+OPT_EVAL_NUMBER(double, AV_OPT_TYPE_DOUBLE, double)
+OPT_EVAL_NUMBER(q, AV_OPT_TYPE_RATIONAL, AVRational)
+
+static int set_number(void *obj, const char *name, double num, int den, int64_t intnum,
+ int search_flags)
+{
+ void *dst, *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+
+ if (o->flags & AV_OPT_FLAG_READONLY)
+ return AVERROR(EINVAL);
+
+ dst = ((uint8_t *)target_obj) + o->offset;
+ return write_number(obj, o, dst, num, den, intnum);
+}
+
+int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
+{
+ return set_number(obj, name, 1, 1, val, search_flags);
+}
+
+int av_opt_set_double(void *obj, const char *name, double val, int search_flags)
+{
+ return set_number(obj, name, val, 1, 1, search_flags);
+}
+
+int av_opt_set_q(void *obj, const char *name, AVRational val, int search_flags)
+{
+ return set_number(obj, name, val.num, val.den, 1, search_flags);
+}
+
+int av_opt_set_bin(void *obj, const char *name, const uint8_t *val, int len, int search_flags)
+{
+ void *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+ uint8_t *ptr;
+ uint8_t **dst;
+ int *lendst;
+
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+
+ if (o->type != AV_OPT_TYPE_BINARY || o->flags & AV_OPT_FLAG_READONLY)
+ return AVERROR(EINVAL);
+
+ ptr = len ? av_malloc(len) : NULL;
+ if (len && !ptr)
+ return AVERROR(ENOMEM);
+
+ dst = (uint8_t **)(((uint8_t *)target_obj) + o->offset);
+ lendst = (int *)(dst + 1);
+
+ av_free(*dst);
+ *dst = ptr;
+ *lendst = len;
+ if (len)
+ memcpy(ptr, val, len);
+
+ return 0;
+}
+
+int av_opt_set_image_size(void *obj, const char *name, int w, int h, int search_flags)
+{
+ void *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->type != AV_OPT_TYPE_IMAGE_SIZE) {
+ av_log(obj, AV_LOG_ERROR,
+ "The value set by option '%s' is not an image size.\n", o->name);
+ return AVERROR(EINVAL);
+ }
+ if (w<0 || h<0) {
+ av_log(obj, AV_LOG_ERROR,
+ "Invalid negative size value %dx%d for size '%s'\n", w, h, o->name);
+ return AVERROR(EINVAL);
+ }
+ *(int *)(((uint8_t *)target_obj) + o->offset) = w;
+ *(int *)(((uint8_t *)target_obj+sizeof(int)) + o->offset) = h;
+ return 0;
+}
+
+int av_opt_set_video_rate(void *obj, const char *name, AVRational val, int search_flags)
+{
+ void *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->type != AV_OPT_TYPE_VIDEO_RATE) {
+ av_log(obj, AV_LOG_ERROR,
+ "The value set by option '%s' is not a video rate.\n", o->name);
+ return AVERROR(EINVAL);
+ }
+ if (val.num <= 0 || val.den <= 0)
+ return AVERROR(EINVAL);
+ return set_number(obj, name, val.num, val.den, 1, search_flags);
+}
+
+static int set_format(void *obj, const char *name, int fmt, int search_flags,
+ enum AVOptionType type, const char *desc, int nb_fmts)
+{
+ void *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0,
+ search_flags, &target_obj);
+ int min, max;
+
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->type != type) {
+ av_log(obj, AV_LOG_ERROR,
+ "The value set by option '%s' is not a %s format", name, desc);
+ return AVERROR(EINVAL);
+ }
+
+ min = FFMAX(o->min, -1);
+ max = FFMIN(o->max, nb_fmts-1);
+
+ if (fmt < min || fmt > max) {
+ av_log(obj, AV_LOG_ERROR,
+ "Value %d for parameter '%s' out of %s format range [%d - %d]\n",
+ fmt, name, desc, min, max);
+ return AVERROR(ERANGE);
+ }
+ *(int *)(((uint8_t *)target_obj) + o->offset) = fmt;
+ return 0;
+}
+
+int av_opt_set_pixel_fmt(void *obj, const char *name, enum AVPixelFormat fmt, int search_flags)
+{
+ return set_format(obj, name, fmt, search_flags, AV_OPT_TYPE_PIXEL_FMT, "pixel", AV_PIX_FMT_NB);
+}
+
+int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags)
+{
+ return set_format(obj, name, fmt, search_flags, AV_OPT_TYPE_SAMPLE_FMT, "sample", AV_SAMPLE_FMT_NB);
+}
+
+int av_opt_set_channel_layout(void *obj, const char *name, int64_t cl, int search_flags)
+{
+ void *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->type != AV_OPT_TYPE_CHANNEL_LAYOUT) {
+ av_log(obj, AV_LOG_ERROR,
+ "The value set by option '%s' is not a channel layout.\n", o->name);
+ return AVERROR(EINVAL);
+ }
+ *(int64_t *)(((uint8_t *)target_obj) + o->offset) = cl;
+ return 0;
+}
+
+int av_opt_set_dict_val(void *obj, const char *name, const AVDictionary *val,
+ int search_flags)
+{
+ void *target_obj;
+ AVDictionary **dst;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->flags & AV_OPT_FLAG_READONLY)
+ return AVERROR(EINVAL);
+
+ dst = (AVDictionary **)(((uint8_t *)target_obj) + o->offset);
+ av_dict_free(dst);
+ av_dict_copy(dst, val, 0);
+
+ return 0;
+}
+
+static void format_duration(char *buf, size_t size, int64_t d)
+{
+ char *e;
+
+ av_assert0(size >= 25);
+ if (d < 0 && d != INT64_MIN) {
+ *(buf++) = '-';
+ size--;
+ d = -d;
+ }
+ if (d == INT64_MAX)
+ snprintf(buf, size, "INT64_MAX");
+ else if (d == INT64_MIN)
+ snprintf(buf, size, "INT64_MIN");
+ else if (d > (int64_t)3600*1000000)
+ snprintf(buf, size, "%"PRId64":%02d:%02d.%06d", d / 3600000000,
+ (int)((d / 60000000) % 60),
+ (int)((d / 1000000) % 60),
+ (int)(d % 1000000));
+ else if (d > 60*1000000)
+ snprintf(buf, size, "%d:%02d.%06d",
+ (int)(d / 60000000),
+ (int)((d / 1000000) % 60),
+ (int)(d % 1000000));
+ else
+ snprintf(buf, size, "%d.%06d",
+ (int)(d / 1000000),
+ (int)(d % 1000000));
+ e = buf + strlen(buf);
+ while (e > buf && e[-1] == '0')
+ *(--e) = 0;
+ if (e > buf && e[-1] == '.')
+ *(--e) = 0;
+}
+
+int av_opt_get(void *obj, const char *name, int search_flags, uint8_t **out_val)
+{
+ void *dst, *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+ uint8_t *bin, buf[128];
+ int len, i, ret;
+ int64_t i64;
+
+ if (!o || !target_obj || (o->offset<=0 && o->type != AV_OPT_TYPE_CONST))
+ return AVERROR_OPTION_NOT_FOUND;
+
+ dst = (uint8_t *)target_obj + o->offset;
+
+ buf[0] = 0;
+ switch (o->type) {
+ case AV_OPT_TYPE_BOOL:
+ ret = snprintf(buf, sizeof(buf), "%s", (char *)av_x_if_null(get_bool_name(*(int *)dst), "invalid"));
+ break;
+ case AV_OPT_TYPE_FLAGS:
+ ret = snprintf(buf, sizeof(buf), "0x%08X", *(int *)dst);
+ break;
+ case AV_OPT_TYPE_INT:
+ ret = snprintf(buf, sizeof(buf), "%d", *(int *)dst);
+ break;
+ case AV_OPT_TYPE_INT64:
+ ret = snprintf(buf, sizeof(buf), "%"PRId64, *(int64_t *)dst);
+ break;
+ case AV_OPT_TYPE_UINT64:
+ ret = snprintf(buf, sizeof(buf), "%"PRIu64, *(uint64_t *)dst);
+ break;
+ case AV_OPT_TYPE_FLOAT:
+ ret = snprintf(buf, sizeof(buf), "%f", *(float *)dst);
+ break;
+ case AV_OPT_TYPE_DOUBLE:
+ ret = snprintf(buf, sizeof(buf), "%f", *(double *)dst);
+ break;
+ case AV_OPT_TYPE_VIDEO_RATE:
+ case AV_OPT_TYPE_RATIONAL:
+ ret = snprintf(buf, sizeof(buf), "%d/%d", ((AVRational *)dst)->num, ((AVRational *)dst)->den);
+ break;
+ case AV_OPT_TYPE_CONST:
+ ret = snprintf(buf, sizeof(buf), "%f", o->default_val.dbl);
+ break;
+ case AV_OPT_TYPE_STRING:
+ if (*(uint8_t **)dst) {
+ *out_val = av_strdup(*(uint8_t **)dst);
+ } else if (search_flags & AV_OPT_ALLOW_NULL) {
+ *out_val = NULL;
+ return 0;
+ } else {
+ *out_val = av_strdup("");
+ }
+ return *out_val ? 0 : AVERROR(ENOMEM);
+ case AV_OPT_TYPE_BINARY:
+ if (!*(uint8_t **)dst && (search_flags & AV_OPT_ALLOW_NULL)) {
+ *out_val = NULL;
+ return 0;
+ }
+ len = *(int *)(((uint8_t *)dst) + sizeof(uint8_t *));
+ if ((uint64_t)len * 2 + 1 > INT_MAX)
+ return AVERROR(EINVAL);
+ if (!(*out_val = av_malloc(len * 2 + 1)))
+ return AVERROR(ENOMEM);
+ if (!len) {
+ *out_val[0] = '\0';
+ return 0;
+ }
+ bin = *(uint8_t **)dst;
+ for (i = 0; i < len; i++)
+ snprintf(*out_val + i * 2, 3, "%02X", bin[i]);
+ return 0;
+ case AV_OPT_TYPE_IMAGE_SIZE:
+ ret = snprintf(buf, sizeof(buf), "%dx%d", ((int *)dst)[0], ((int *)dst)[1]);
+ break;
+ case AV_OPT_TYPE_PIXEL_FMT:
+ ret = snprintf(buf, sizeof(buf), "%s", (char *)av_x_if_null(av_get_pix_fmt_name(*(enum AVPixelFormat *)dst), "none"));
+ break;
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ ret = snprintf(buf, sizeof(buf), "%s", (char *)av_x_if_null(av_get_sample_fmt_name(*(enum AVSampleFormat *)dst), "none"));
+ break;
+ case AV_OPT_TYPE_DURATION:
+ i64 = *(int64_t *)dst;
+ format_duration(buf, sizeof(buf), i64);
+ ret = strlen(buf); // no overflow possible, checked by an assert
+ break;
+ case AV_OPT_TYPE_COLOR:
+ ret = snprintf(buf, sizeof(buf), "0x%02x%02x%02x%02x",
+ (int)((uint8_t *)dst)[0], (int)((uint8_t *)dst)[1],
+ (int)((uint8_t *)dst)[2], (int)((uint8_t *)dst)[3]);
+ break;
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ i64 = *(int64_t *)dst;
+ ret = snprintf(buf, sizeof(buf), "0x%"PRIx64, i64);
+ break;
+ default:
+ return AVERROR(EINVAL);
+ }
+
+ if (ret >= sizeof(buf))
+ return AVERROR(EINVAL);
+ *out_val = av_strdup(buf);
+ return *out_val ? 0 : AVERROR(ENOMEM);
+}
+
+static int get_number(void *obj, const char *name, const AVOption **o_out, double *num, int *den, int64_t *intnum,
+ int search_flags)
+{
+ void *dst, *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+ if (!o || !target_obj)
+ goto error;
+
+ dst = ((uint8_t *)target_obj) + o->offset;
+
+ if (o_out) *o_out= o;
+
+ return read_number(o, dst, num, den, intnum);
+
+error:
+ *den =
+ *intnum = 0;
+ return -1;
+}
+
+int av_opt_get_int(void *obj, const char *name, int search_flags, int64_t *out_val)
+{
+ int64_t intnum = 1;
+ double num = 1;
+ int ret, den = 1;
+
+ if ((ret = get_number(obj, name, NULL, &num, &den, &intnum, search_flags)) < 0)
+ return ret;
+ *out_val = num * intnum / den;
+ return 0;
+}
+
+int av_opt_get_double(void *obj, const char *name, int search_flags, double *out_val)
+{
+ int64_t intnum = 1;
+ double num = 1;
+ int ret, den = 1;
+
+ if ((ret = get_number(obj, name, NULL, &num, &den, &intnum, search_flags)) < 0)
+ return ret;
+ *out_val = num * intnum / den;
+ return 0;
+}
+
+int av_opt_get_q(void *obj, const char *name, int search_flags, AVRational *out_val)
+{
+ int64_t intnum = 1;
+ double num = 1;
+ int ret, den = 1;
+
+ if ((ret = get_number(obj, name, NULL, &num, &den, &intnum, search_flags)) < 0)
+ return ret;
+
+ if (num == 1.0 && (int)intnum == intnum)
+ *out_val = (AVRational){intnum, den};
+ else
+ *out_val = av_d2q(num*intnum/den, 1<<24);
+ return 0;
+}
+
+int av_opt_get_image_size(void *obj, const char *name, int search_flags, int *w_out, int *h_out)
+{
+ void *dst, *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->type != AV_OPT_TYPE_IMAGE_SIZE) {
+ av_log(obj, AV_LOG_ERROR,
+ "The value for option '%s' is not an image size.\n", name);
+ return AVERROR(EINVAL);
+ }
+
+ dst = ((uint8_t*)target_obj) + o->offset;
+ if (w_out) *w_out = *(int *)dst;
+ if (h_out) *h_out = *((int *)dst+1);
+ return 0;
+}
+
+int av_opt_get_video_rate(void *obj, const char *name, int search_flags, AVRational *out_val)
+{
+ int64_t intnum = 1;
+ double num = 1;
+ int ret, den = 1;
+
+ if ((ret = get_number(obj, name, NULL, &num, &den, &intnum, search_flags)) < 0)
+ return ret;
+
+ if (num == 1.0 && (int)intnum == intnum)
+ *out_val = (AVRational) { intnum, den };
+ else
+ *out_val = av_d2q(num * intnum / den, 1 << 24);
+ return 0;
+}
+
+static int get_format(void *obj, const char *name, int search_flags, int *out_fmt,
+ enum AVOptionType type, const char *desc)
+{
+ void *dst, *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->type != type) {
+ av_log(obj, AV_LOG_ERROR,
+ "The value for option '%s' is not a %s format.\n", desc, name);
+ return AVERROR(EINVAL);
+ }
+
+ dst = ((uint8_t*)target_obj) + o->offset;
+ *out_fmt = *(int *)dst;
+ return 0;
+}
+
+int av_opt_get_pixel_fmt(void *obj, const char *name, int search_flags, enum AVPixelFormat *out_fmt)
+{
+ return get_format(obj, name, search_flags, out_fmt, AV_OPT_TYPE_PIXEL_FMT, "pixel");
+}
+
+int av_opt_get_sample_fmt(void *obj, const char *name, int search_flags, enum AVSampleFormat *out_fmt)
+{
+ return get_format(obj, name, search_flags, out_fmt, AV_OPT_TYPE_SAMPLE_FMT, "sample");
+}
+
+int av_opt_get_channel_layout(void *obj, const char *name, int search_flags, int64_t *cl)
+{
+ void *dst, *target_obj;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->type != AV_OPT_TYPE_CHANNEL_LAYOUT) {
+ av_log(obj, AV_LOG_ERROR,
+ "The value for option '%s' is not a channel layout.\n", name);
+ return AVERROR(EINVAL);
+ }
+
+ dst = ((uint8_t*)target_obj) + o->offset;
+ *cl = *(int64_t *)dst;
+ return 0;
+}
+
+int av_opt_get_dict_val(void *obj, const char *name, int search_flags, AVDictionary **out_val)
+{
+ void *target_obj;
+ AVDictionary *src;
+ const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);
+
+ if (!o || !target_obj)
+ return AVERROR_OPTION_NOT_FOUND;
+ if (o->type != AV_OPT_TYPE_DICT)
+ return AVERROR(EINVAL);
+
+ src = *(AVDictionary **)(((uint8_t *)target_obj) + o->offset);
+ av_dict_copy(out_val, src, 0);
+
+ return 0;
+}
+
+int av_opt_flag_is_set(void *obj, const char *field_name, const char *flag_name)
+{
+ const AVOption *field = av_opt_find(obj, field_name, NULL, 0, 0);
+ const AVOption *flag = av_opt_find(obj, flag_name,
+ field ? field->unit : NULL, 0, 0);
+ int64_t res;
+
+ if (!field || !flag || flag->type != AV_OPT_TYPE_CONST ||
+ av_opt_get_int(obj, field_name, 0, &res) < 0)
+ return 0;
+ return res & flag->default_val.i64;
+}
+
+static void log_value(void *av_log_obj, int level, double d)
+{
+ if (d == INT_MAX) {
+ av_log(av_log_obj, level, "INT_MAX");
+ } else if (d == INT_MIN) {
+ av_log(av_log_obj, level, "INT_MIN");
+ } else if (d == UINT32_MAX) {
+ av_log(av_log_obj, level, "UINT32_MAX");
+ } else if (d == (double)INT64_MAX) {
+ av_log(av_log_obj, level, "I64_MAX");
+ } else if (d == INT64_MIN) {
+ av_log(av_log_obj, level, "I64_MIN");
+ } else if (d == FLT_MAX) {
+ av_log(av_log_obj, level, "FLT_MAX");
+ } else if (d == FLT_MIN) {
+ av_log(av_log_obj, level, "FLT_MIN");
+ } else if (d == -FLT_MAX) {
+ av_log(av_log_obj, level, "-FLT_MAX");
+ } else if (d == -FLT_MIN) {
+ av_log(av_log_obj, level, "-FLT_MIN");
+ } else if (d == DBL_MAX) {
+ av_log(av_log_obj, level, "DBL_MAX");
+ } else if (d == DBL_MIN) {
+ av_log(av_log_obj, level, "DBL_MIN");
+ } else if (d == -DBL_MAX) {
+ av_log(av_log_obj, level, "-DBL_MAX");
+ } else if (d == -DBL_MIN) {
+ av_log(av_log_obj, level, "-DBL_MIN");
+ } else {
+ av_log(av_log_obj, level, "%g", d);
+ }
+}
+
+static const char *get_opt_const_name(void *obj, const char *unit, int64_t value)
+{
+ const AVOption *opt = NULL;
+
+ if (!unit)
+ return NULL;
+ while ((opt = av_opt_next(obj, opt)))
+ if (opt->type == AV_OPT_TYPE_CONST && !strcmp(opt->unit, unit) &&
+ opt->default_val.i64 == value)
+ return opt->name;
+ return NULL;
+}
+
+static char *get_opt_flags_string(void *obj, const char *unit, int64_t value)
+{
+ const AVOption *opt = NULL;
+ char flags[512];
+
+ flags[0] = 0;
+ if (!unit)
+ return NULL;
+ while ((opt = av_opt_next(obj, opt))) {
+ if (opt->type == AV_OPT_TYPE_CONST && !strcmp(opt->unit, unit) &&
+ opt->default_val.i64 & value) {
+ if (flags[0])
+ av_strlcatf(flags, sizeof(flags), "+");
+ av_strlcatf(flags, sizeof(flags), "%s", opt->name);
+ }
+ }
+ if (flags[0])
+ return av_strdup(flags);
+ return NULL;
+}
+
+static void opt_list(void *obj, void *av_log_obj, const char *unit,
+ int req_flags, int rej_flags)
+{
+ const AVOption *opt = NULL;
+ AVOptionRanges *r;
+ int i;
+
+ while ((opt = av_opt_next(obj, opt))) {
+ if (!(opt->flags & req_flags) || (opt->flags & rej_flags))
+ continue;
+
+ /* Don't print CONST's on level one.
+ * Don't print anything but CONST's on level two.
+ * Only print items from the requested unit.
+ */
+ if (!unit && opt->type == AV_OPT_TYPE_CONST)
+ continue;
+ else if (unit && opt->type != AV_OPT_TYPE_CONST)
+ continue;
+ else if (unit && opt->type == AV_OPT_TYPE_CONST && strcmp(unit, opt->unit))
+ continue;
+ else if (unit && opt->type == AV_OPT_TYPE_CONST)
+ av_log(av_log_obj, AV_LOG_INFO, " %-15s ", opt->name);
+ else
+ av_log(av_log_obj, AV_LOG_INFO, " %s%-17s ",
+ (opt->flags & AV_OPT_FLAG_FILTERING_PARAM) ? "" : "-",
+ opt->name);
+
+ switch (opt->type) {
+ case AV_OPT_TYPE_FLAGS:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<flags>");
+ break;
+ case AV_OPT_TYPE_INT:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<int>");
+ break;
+ case AV_OPT_TYPE_INT64:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<int64>");
+ break;
+ case AV_OPT_TYPE_UINT64:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<uint64>");
+ break;
+ case AV_OPT_TYPE_DOUBLE:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<double>");
+ break;
+ case AV_OPT_TYPE_FLOAT:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<float>");
+ break;
+ case AV_OPT_TYPE_STRING:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<string>");
+ break;
+ case AV_OPT_TYPE_RATIONAL:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<rational>");
+ break;
+ case AV_OPT_TYPE_BINARY:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<binary>");
+ break;
+ case AV_OPT_TYPE_IMAGE_SIZE:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<image_size>");
+ break;
+ case AV_OPT_TYPE_VIDEO_RATE:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<video_rate>");
+ break;
+ case AV_OPT_TYPE_PIXEL_FMT:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<pix_fmt>");
+ break;
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<sample_fmt>");
+ break;
+ case AV_OPT_TYPE_DURATION:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<duration>");
+ break;
+ case AV_OPT_TYPE_COLOR:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<color>");
+ break;
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<channel_layout>");
+ break;
+ case AV_OPT_TYPE_BOOL:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "<boolean>");
+ break;
+ case AV_OPT_TYPE_CONST:
+ default:
+ av_log(av_log_obj, AV_LOG_INFO, "%-12s ", "");
+ break;
+ }
+ av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_ENCODING_PARAM) ? 'E' : '.');
+ av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_DECODING_PARAM) ? 'D' : '.');
+ av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_FILTERING_PARAM)? 'F' : '.');
+ av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_VIDEO_PARAM ) ? 'V' : '.');
+ av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_AUDIO_PARAM ) ? 'A' : '.');
+ av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_SUBTITLE_PARAM) ? 'S' : '.');
+ av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_EXPORT) ? 'X' : '.');
+ av_log(av_log_obj, AV_LOG_INFO, "%c", (opt->flags & AV_OPT_FLAG_READONLY) ? 'R' : '.');
+
+ if (opt->help)
+ av_log(av_log_obj, AV_LOG_INFO, " %s", opt->help);
+
+ if (av_opt_query_ranges(&r, obj, opt->name, AV_OPT_SEARCH_FAKE_OBJ) >= 0) {
+ switch (opt->type) {
+ case AV_OPT_TYPE_INT:
+ case AV_OPT_TYPE_INT64:
+ case AV_OPT_TYPE_UINT64:
+ case AV_OPT_TYPE_DOUBLE:
+ case AV_OPT_TYPE_FLOAT:
+ case AV_OPT_TYPE_RATIONAL:
+ for (i = 0; i < r->nb_ranges; i++) {
+ av_log(av_log_obj, AV_LOG_INFO, " (from ");
+ log_value(av_log_obj, AV_LOG_INFO, r->range[i]->value_min);
+ av_log(av_log_obj, AV_LOG_INFO, " to ");
+ log_value(av_log_obj, AV_LOG_INFO, r->range[i]->value_max);
+ av_log(av_log_obj, AV_LOG_INFO, ")");
+ }
+ break;
+ }
+ av_opt_freep_ranges(&r);
+ }
+
+ if (opt->type != AV_OPT_TYPE_CONST &&
+ opt->type != AV_OPT_TYPE_BINARY &&
+ !((opt->type == AV_OPT_TYPE_COLOR ||
+ opt->type == AV_OPT_TYPE_IMAGE_SIZE ||
+ opt->type == AV_OPT_TYPE_STRING ||
+ opt->type == AV_OPT_TYPE_VIDEO_RATE) &&
+ !opt->default_val.str)) {
+ av_log(av_log_obj, AV_LOG_INFO, " (default ");
+ switch (opt->type) {
+ case AV_OPT_TYPE_BOOL:
+ av_log(av_log_obj, AV_LOG_INFO, "%s", (char *)av_x_if_null(get_bool_name(opt->default_val.i64), "invalid"));
+ break;
+ case AV_OPT_TYPE_FLAGS: {
+ char *def_flags = get_opt_flags_string(obj, opt->unit, opt->default_val.i64);
+ if (def_flags) {
+ av_log(av_log_obj, AV_LOG_INFO, "%s", def_flags);
+ av_freep(&def_flags);
+ } else {
+ av_log(av_log_obj, AV_LOG_INFO, "%"PRIX64, opt->default_val.i64);
+ }
+ break;
+ }
+ case AV_OPT_TYPE_DURATION: {
+ char buf[25];
+ format_duration(buf, sizeof(buf), opt->default_val.i64);
+ av_log(av_log_obj, AV_LOG_INFO, "%s", buf);
+ break;
+ }
+ case AV_OPT_TYPE_INT:
+ case AV_OPT_TYPE_UINT64:
+ case AV_OPT_TYPE_INT64: {
+ const char *def_const = get_opt_const_name(obj, opt->unit, opt->default_val.i64);
+ if (def_const)
+ av_log(av_log_obj, AV_LOG_INFO, "%s", def_const);
+ else
+ log_value(av_log_obj, AV_LOG_INFO, opt->default_val.i64);
+ break;
+ }
+ case AV_OPT_TYPE_DOUBLE:
+ case AV_OPT_TYPE_FLOAT:
+ log_value(av_log_obj, AV_LOG_INFO, opt->default_val.dbl);
+ break;
+ case AV_OPT_TYPE_RATIONAL: {
+ AVRational q = av_d2q(opt->default_val.dbl, INT_MAX);
+ av_log(av_log_obj, AV_LOG_INFO, "%d/%d", q.num, q.den); }
+ break;
+ case AV_OPT_TYPE_PIXEL_FMT:
+ av_log(av_log_obj, AV_LOG_INFO, "%s", (char *)av_x_if_null(av_get_pix_fmt_name(opt->default_val.i64), "none"));
+ break;
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ av_log(av_log_obj, AV_LOG_INFO, "%s", (char *)av_x_if_null(av_get_sample_fmt_name(opt->default_val.i64), "none"));
+ break;
+ case AV_OPT_TYPE_COLOR:
+ case AV_OPT_TYPE_IMAGE_SIZE:
+ case AV_OPT_TYPE_STRING:
+ case AV_OPT_TYPE_VIDEO_RATE:
+ av_log(av_log_obj, AV_LOG_INFO, "\"%s\"", opt->default_val.str);
+ break;
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ av_log(av_log_obj, AV_LOG_INFO, "0x%"PRIx64, opt->default_val.i64);
+ break;
+ }
+ av_log(av_log_obj, AV_LOG_INFO, ")");
+ }
+
+ av_log(av_log_obj, AV_LOG_INFO, "\n");
+ if (opt->unit && opt->type != AV_OPT_TYPE_CONST)
+ opt_list(obj, av_log_obj, opt->unit, req_flags, rej_flags);
+ }
+}
+
+int av_opt_show2(void *obj, void *av_log_obj, int req_flags, int rej_flags)
+{
+ if (!obj)
+ return -1;
+
+ av_log(av_log_obj, AV_LOG_INFO, "%s AVOptions:\n", (*(AVClass **)obj)->class_name);
+
+ opt_list(obj, av_log_obj, NULL, req_flags, rej_flags);
+
+ return 0;
+}
+
+void av_opt_set_defaults(void *s)
+{
+ av_opt_set_defaults2(s, 0, 0);
+}
+
+void av_opt_set_defaults2(void *s, int mask, int flags)
+{
+ const AVOption *opt = NULL;
+ while ((opt = av_opt_next(s, opt))) {
+ void *dst = ((uint8_t*)s) + opt->offset;
+
+ if ((opt->flags & mask) != flags)
+ continue;
+
+ if (opt->flags & AV_OPT_FLAG_READONLY)
+ continue;
+
+ switch (opt->type) {
+ case AV_OPT_TYPE_CONST:
+ /* Nothing to be done here */
+ break;
+ case AV_OPT_TYPE_BOOL:
+ case AV_OPT_TYPE_FLAGS:
+ case AV_OPT_TYPE_INT:
+ case AV_OPT_TYPE_INT64:
+ case AV_OPT_TYPE_UINT64:
+ case AV_OPT_TYPE_DURATION:
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ case AV_OPT_TYPE_PIXEL_FMT:
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ write_number(s, opt, dst, 1, 1, opt->default_val.i64);
+ break;
+ case AV_OPT_TYPE_DOUBLE:
+ case AV_OPT_TYPE_FLOAT: {
+ double val;
+ val = opt->default_val.dbl;
+ write_number(s, opt, dst, val, 1, 1);
+ }
+ break;
+ case AV_OPT_TYPE_RATIONAL: {
+ AVRational val;
+ val = av_d2q(opt->default_val.dbl, INT_MAX);
+ write_number(s, opt, dst, 1, val.den, val.num);
+ }
+ break;
+ case AV_OPT_TYPE_COLOR:
+ set_string_color(s, opt, opt->default_val.str, dst);
+ break;
+ case AV_OPT_TYPE_STRING:
+ set_string(s, opt, opt->default_val.str, dst);
+ break;
+ case AV_OPT_TYPE_IMAGE_SIZE:
+ set_string_image_size(s, opt, opt->default_val.str, dst);
+ break;
+ case AV_OPT_TYPE_VIDEO_RATE:
+ set_string_video_rate(s, opt, opt->default_val.str, dst);
+ break;
+ case AV_OPT_TYPE_BINARY:
+ set_string_binary(s, opt, opt->default_val.str, dst);
+ break;
+ case AV_OPT_TYPE_DICT:
+ /* Cannot set defaults for these types */
+ break;
+ default:
+ av_log(s, AV_LOG_DEBUG, "AVOption type %d of option %s not implemented yet\n",
+ opt->type, opt->name);
+ }
+ }
+}
+
+/**
+ * Store the value in the field in ctx that is named like key.
+ * ctx must be an AVClass context, storing is done using AVOptions.
+ *
+ * @param buf the string to parse, buf will be updated to point at the
+ * separator just after the parsed key/value pair
+ * @param key_val_sep a 0-terminated list of characters used to
+ * separate key from value
+ * @param pairs_sep a 0-terminated list of characters used to separate
+ * two pairs from each other
+ * @return 0 if the key/value pair has been successfully parsed and
+ * set, or a negative value corresponding to an AVERROR code in case
+ * of error:
+ * AVERROR(EINVAL) if the key/value pair cannot be parsed,
+ * the error code issued by av_opt_set() if the key/value pair
+ * cannot be set
+ */
+static int parse_key_value_pair(void *ctx, const char **buf,
+ const char *key_val_sep, const char *pairs_sep)
+{
+ char *key = av_get_token(buf, key_val_sep);
+ char *val;
+ int ret;
+
+ if (!key)
+ return AVERROR(ENOMEM);
+
+ if (*key && strspn(*buf, key_val_sep)) {
+ (*buf)++;
+ val = av_get_token(buf, pairs_sep);
+ if (!val) {
+ av_freep(&key);
+ return AVERROR(ENOMEM);
+ }
+ } else {
+ av_log(ctx, AV_LOG_ERROR, "Missing key or no key/value separator found after key '%s'\n", key);
+ av_free(key);
+ return AVERROR(EINVAL);
+ }
+
+ av_log(ctx, AV_LOG_DEBUG, "Setting entry with key '%s' to value '%s'\n", key, val);
+
+ ret = av_opt_set(ctx, key, val, AV_OPT_SEARCH_CHILDREN);
+ if (ret == AVERROR_OPTION_NOT_FOUND)
+ av_log(ctx, AV_LOG_ERROR, "Key '%s' not found.\n", key);
+
+ av_free(key);
+ av_free(val);
+ return ret;
+}
+
+int av_set_options_string(void *ctx, const char *opts,
+ const char *key_val_sep, const char *pairs_sep)
+{
+ int ret, count = 0;
+
+ if (!opts)
+ return 0;
+
+ while (*opts) {
+ if ((ret = parse_key_value_pair(ctx, &opts, key_val_sep, pairs_sep)) < 0)
+ return ret;
+ count++;
+
+ if (*opts)
+ opts++;
+ }
+
+ return count;
+}
+
+#define WHITESPACES " \n\t\r"
+
+static int is_key_char(char c)
+{
+ return (unsigned)((c | 32) - 'a') < 26 ||
+ (unsigned)(c - '0') < 10 ||
+ c == '-' || c == '_' || c == '/' || c == '.';
+}
+
+/**
+ * Read a key from a string.
+ *
+ * The key consists of is_key_char characters and must be terminated by a
+ * character from the delim string; spaces are ignored.
+ *
+ * @return 0 for success (even with ellipsis), <0 for failure
+ */
+static int get_key(const char **ropts, const char *delim, char **rkey)
+{
+ const char *opts = *ropts;
+ const char *key_start, *key_end;
+
+ key_start = opts += strspn(opts, WHITESPACES);
+ while (is_key_char(*opts))
+ opts++;
+ key_end = opts;
+ opts += strspn(opts, WHITESPACES);
+ if (!*opts || !strchr(delim, *opts))
+ return AVERROR(EINVAL);
+ opts++;
+ if (!(*rkey = av_malloc(key_end - key_start + 1)))
+ return AVERROR(ENOMEM);
+ memcpy(*rkey, key_start, key_end - key_start);
+ (*rkey)[key_end - key_start] = 0;
+ *ropts = opts;
+ return 0;
+}
+
+int av_opt_get_key_value(const char **ropts,
+ const char *key_val_sep, const char *pairs_sep,
+ unsigned flags,
+ char **rkey, char **rval)
+{
+ int ret;
+ char *key = NULL, *val;
+ const char *opts = *ropts;
+
+ if ((ret = get_key(&opts, key_val_sep, &key)) < 0 &&
+ !(flags & AV_OPT_FLAG_IMPLICIT_KEY))
+ return AVERROR(EINVAL);
+ if (!(val = av_get_token(&opts, pairs_sep))) {
+ av_free(key);
+ return AVERROR(ENOMEM);
+ }
+ *ropts = opts;
+ *rkey = key;
+ *rval = val;
+ return 0;
+}
+
+int av_opt_set_from_string(void *ctx, const char *opts,
+ const char *const *shorthand,
+ const char *key_val_sep, const char *pairs_sep)
+{
+ int ret, count = 0;
+ const char *dummy_shorthand = NULL;
+ char *av_uninit(parsed_key), *av_uninit(value);
+ const char *key;
+
+ if (!opts)
+ return 0;
+ if (!shorthand)
+ shorthand = &dummy_shorthand;
+
+ while (*opts) {
+ ret = av_opt_get_key_value(&opts, key_val_sep, pairs_sep,
+ *shorthand ? AV_OPT_FLAG_IMPLICIT_KEY : 0,
+ &parsed_key, &value);
+ if (ret < 0) {
+ if (ret == AVERROR(EINVAL))
+ av_log(ctx, AV_LOG_ERROR, "No option name near '%s'\n", opts);
+ else
+ av_log(ctx, AV_LOG_ERROR, "Unable to parse '%s': %s\n", opts,
+ av_err2str(ret));
+ return ret;
+ }
+ if (*opts)
+ opts++;
+ if (parsed_key) {
+ key = parsed_key;
+ while (*shorthand) /* discard all remaining shorthand */
+ shorthand++;
+ } else {
+ key = *(shorthand++);
+ }
+
+ av_log(ctx, AV_LOG_DEBUG, "Setting '%s' to value '%s'\n", key, value);
+ if ((ret = av_opt_set(ctx, key, value, 0)) < 0) {
+ if (ret == AVERROR_OPTION_NOT_FOUND)
+ av_log(ctx, AV_LOG_ERROR, "Option '%s' not found\n", key);
+ av_free(value);
+ av_free(parsed_key);
+ return ret;
+ }
+
+ av_free(value);
+ av_free(parsed_key);
+ count++;
+ }
+ return count;
+}
+
+void av_opt_free(void *obj)
+{
+ const AVOption *o = NULL;
+ while ((o = av_opt_next(obj, o))) {
+ switch (o->type) {
+ case AV_OPT_TYPE_STRING:
+ case AV_OPT_TYPE_BINARY:
+ av_freep((uint8_t *)obj + o->offset);
+ break;
+
+ case AV_OPT_TYPE_DICT:
+ av_dict_free((AVDictionary **)(((uint8_t *)obj) + o->offset));
+ break;
+
+ default:
+ break;
+ }
+ }
+}
+
+int av_opt_set_dict2(void *obj, AVDictionary **options, int search_flags)
+{
+ AVDictionaryEntry *t = NULL;
+ AVDictionary *tmp = NULL;
+ int ret = 0;
+
+ if (!options)
+ return 0;
+
+ while ((t = av_dict_get(*options, "", t, AV_DICT_IGNORE_SUFFIX))) {
+ ret = av_opt_set(obj, t->key, t->value, search_flags);
+ if (ret == AVERROR_OPTION_NOT_FOUND)
+ ret = av_dict_set(&tmp, t->key, t->value, 0);
+ if (ret < 0) {
+ av_log(obj, AV_LOG_ERROR, "Error setting option %s to value %s.\n", t->key, t->value);
+ av_dict_free(&tmp);
+ return ret;
+ }
+ ret = 0;
+ }
+ av_dict_free(options);
+ *options = tmp;
+ return ret;
+}
+
+int av_opt_set_dict(void *obj, AVDictionary **options)
+{
+ return av_opt_set_dict2(obj, options, 0);
+}
+
+const AVOption *av_opt_find(void *obj, const char *name, const char *unit,
+ int opt_flags, int search_flags)
+{
+ return av_opt_find2(obj, name, unit, opt_flags, search_flags, NULL);
+}
+
+const AVOption *av_opt_find2(void *obj, const char *name, const char *unit,
+ int opt_flags, int search_flags, void **target_obj)
+{
+ const AVClass *c;
+ const AVOption *o = NULL;
+
+ if(!obj)
+ return NULL;
+
+ c= *(AVClass**)obj;
+
+ if (!c)
+ return NULL;
+
+ if (search_flags & AV_OPT_SEARCH_CHILDREN) {
+ if (search_flags & AV_OPT_SEARCH_FAKE_OBJ) {
+ const AVClass *child = NULL;
+ while (child = av_opt_child_class_next(c, child))
+ if (o = av_opt_find2(&child, name, unit, opt_flags, search_flags, NULL))
+ return o;
+ } else {
+ void *child = NULL;
+ while (child = av_opt_child_next(obj, child))
+ if (o = av_opt_find2(child, name, unit, opt_flags, search_flags, target_obj))
+ return o;
+ }
+ }
+
+ while (o = av_opt_next(obj, o)) {
+ if (!strcmp(o->name, name) && (o->flags & opt_flags) == opt_flags &&
+ ((!unit && o->type != AV_OPT_TYPE_CONST) ||
+ (unit && o->type == AV_OPT_TYPE_CONST && o->unit && !strcmp(o->unit, unit)))) {
+ if (target_obj) {
+ if (!(search_flags & AV_OPT_SEARCH_FAKE_OBJ))
+ *target_obj = obj;
+ else
+ *target_obj = NULL;
+ }
+ return o;
+ }
+ }
+ return NULL;
+}
+
+void *av_opt_child_next(void *obj, void *prev)
+{
+ const AVClass *c = *(AVClass **)obj;
+ if (c->child_next)
+ return c->child_next(obj, prev);
+ return NULL;
+}
+
+const AVClass *av_opt_child_class_next(const AVClass *parent, const AVClass *prev)
+{
+ if (parent->child_class_next)
+ return parent->child_class_next(prev);
+ return NULL;
+}
+
+void *av_opt_ptr(const AVClass *class, void *obj, const char *name)
+{
+ const AVOption *opt= av_opt_find2(&class, name, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ, NULL);
+ if(!opt)
+ return NULL;
+ return (uint8_t*)obj + opt->offset;
+}
+
+static int opt_size(enum AVOptionType type)
+{
+ switch(type) {
+ case AV_OPT_TYPE_BOOL:
+ case AV_OPT_TYPE_INT:
+ case AV_OPT_TYPE_FLAGS:
+ return sizeof(int);
+ case AV_OPT_TYPE_DURATION:
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ case AV_OPT_TYPE_INT64:
+ case AV_OPT_TYPE_UINT64:
+ return sizeof(int64_t);
+ case AV_OPT_TYPE_DOUBLE:
+ return sizeof(double);
+ case AV_OPT_TYPE_FLOAT:
+ return sizeof(float);
+ case AV_OPT_TYPE_STRING:
+ return sizeof(uint8_t*);
+ case AV_OPT_TYPE_VIDEO_RATE:
+ case AV_OPT_TYPE_RATIONAL:
+ return sizeof(AVRational);
+ case AV_OPT_TYPE_BINARY:
+ return sizeof(uint8_t*) + sizeof(int);
+ case AV_OPT_TYPE_IMAGE_SIZE:
+ return sizeof(int[2]);
+ case AV_OPT_TYPE_PIXEL_FMT:
+ return sizeof(enum AVPixelFormat);
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ return sizeof(enum AVSampleFormat);
+ case AV_OPT_TYPE_COLOR:
+ return 4;
+ }
+ return AVERROR(EINVAL);
+}
+
+int av_opt_copy(void *dst, const void *src)
+{
+ const AVOption *o = NULL;
+ const AVClass *c;
+ int ret = 0;
+
+ if (!src)
+ return AVERROR(EINVAL);
+
+ c = *(AVClass **)src;
+ if (!c || c != *(AVClass **)dst)
+ return AVERROR(EINVAL);
+
+ while ((o = av_opt_next(src, o))) {
+ void *field_dst = (uint8_t *)dst + o->offset;
+ void *field_src = (uint8_t *)src + o->offset;
+ uint8_t **field_dst8 = (uint8_t **)field_dst;
+ uint8_t **field_src8 = (uint8_t **)field_src;
+
+ if (o->type == AV_OPT_TYPE_STRING) {
+ if (*field_dst8 != *field_src8)
+ av_freep(field_dst8);
+ *field_dst8 = av_strdup(*field_src8);
+ if (*field_src8 && !*field_dst8)
+ ret = AVERROR(ENOMEM);
+ } else if (o->type == AV_OPT_TYPE_BINARY) {
+ int len = *(int *)(field_src8 + 1);
+ if (*field_dst8 != *field_src8)
+ av_freep(field_dst8);
+ *field_dst8 = av_memdup(*field_src8, len);
+ if (len && !*field_dst8) {
+ ret = AVERROR(ENOMEM);
+ len = 0;
+ }
+ *(int *)(field_dst8 + 1) = len;
+ } else if (o->type == AV_OPT_TYPE_CONST) {
+ // do nothing
+ } else if (o->type == AV_OPT_TYPE_DICT) {
+ AVDictionary **sdict = (AVDictionary **) field_src;
+ AVDictionary **ddict = (AVDictionary **) field_dst;
+ if (*sdict != *ddict)
+ av_dict_free(ddict);
+ *ddict = NULL;
+ av_dict_copy(ddict, *sdict, 0);
+ if (av_dict_count(*sdict) != av_dict_count(*ddict))
+ ret = AVERROR(ENOMEM);
+ } else {
+ int size = opt_size(o->type);
+ if (size < 0)
+ ret = size;
+ else
+ memcpy(field_dst, field_src, size);
+ }
+ }
+ return ret;
+}
+
+int av_opt_query_ranges(AVOptionRanges **ranges_arg, void *obj, const char *key, int flags)
+{
+ int ret;
+ const AVClass *c = *(AVClass**)obj;
+ int (*callback)(AVOptionRanges **, void *obj, const char *key, int flags) = NULL;
+
+ if (c->version > (52 << 16 | 11 << 8))
+ callback = c->query_ranges;
+
+ if (!callback)
+ callback = av_opt_query_ranges_default;
+
+ ret = callback(ranges_arg, obj, key, flags);
+ if (ret >= 0) {
+ if (!(flags & AV_OPT_MULTI_COMPONENT_RANGE))
+ ret = 1;
+ (*ranges_arg)->nb_components = ret;
+ }
+ return ret;
+}
+
+int av_opt_query_ranges_default(AVOptionRanges **ranges_arg, void *obj, const char *key, int flags)
+{
+ AVOptionRanges *ranges = av_mallocz(sizeof(*ranges));
+ AVOptionRange **range_array = av_mallocz(sizeof(void*));
+ AVOptionRange *range = av_mallocz(sizeof(*range));
+ const AVOption *field = av_opt_find(obj, key, NULL, 0, flags);
+ int ret;
+
+ *ranges_arg = NULL;
+
+ if (!ranges || !range || !range_array || !field) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+
+ ranges->range = range_array;
+ ranges->range[0] = range;
+ ranges->nb_ranges = 1;
+ ranges->nb_components = 1;
+ range->is_range = 1;
+ range->value_min = field->min;
+ range->value_max = field->max;
+
+ switch (field->type) {
+ case AV_OPT_TYPE_BOOL:
+ case AV_OPT_TYPE_INT:
+ case AV_OPT_TYPE_INT64:
+ case AV_OPT_TYPE_UINT64:
+ case AV_OPT_TYPE_PIXEL_FMT:
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ case AV_OPT_TYPE_FLOAT:
+ case AV_OPT_TYPE_DOUBLE:
+ case AV_OPT_TYPE_DURATION:
+ case AV_OPT_TYPE_COLOR:
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ break;
+ case AV_OPT_TYPE_STRING:
+ range->component_min = 0;
+ range->component_max = 0x10FFFF; // max unicode value
+ range->value_min = -1;
+ range->value_max = INT_MAX;
+ break;
+ case AV_OPT_TYPE_RATIONAL:
+ range->component_min = INT_MIN;
+ range->component_max = INT_MAX;
+ break;
+ case AV_OPT_TYPE_IMAGE_SIZE:
+ range->component_min = 0;
+ range->component_max = INT_MAX/128/8;
+ range->value_min = 0;
+ range->value_max = INT_MAX/8;
+ break;
+ case AV_OPT_TYPE_VIDEO_RATE:
+ range->component_min = 1;
+ range->component_max = INT_MAX;
+ range->value_min = 1;
+ range->value_max = INT_MAX;
+ break;
+ default:
+ ret = AVERROR(ENOSYS);
+ goto fail;
+ }
+
+ *ranges_arg = ranges;
+ return 1;
+fail:
+ av_free(ranges);
+ av_free(range);
+ av_free(range_array);
+ return ret;
+}
+
+void av_opt_freep_ranges(AVOptionRanges **rangesp)
+{
+ int i;
+ AVOptionRanges *ranges = *rangesp;
+
+ if (!ranges)
+ return;
+
+ for (i = 0; i < ranges->nb_ranges * ranges->nb_components; i++) {
+ AVOptionRange *range = ranges->range[i];
+ if (range) {
+ av_freep(&range->str);
+ av_freep(&ranges->range[i]);
+ }
+ }
+ av_freep(&ranges->range);
+ av_freep(rangesp);
+}
+
+int av_opt_is_set_to_default(void *obj, const AVOption *o)
+{
+ int64_t i64;
+ double d, d2;
+ float f;
+ AVRational q;
+ int ret, w, h;
+ char *str;
+ void *dst;
+
+ if (!o || !obj)
+ return AVERROR(EINVAL);
+
+ dst = ((uint8_t*)obj) + o->offset;
+
+ switch (o->type) {
+ case AV_OPT_TYPE_CONST:
+ return 1;
+ case AV_OPT_TYPE_BOOL:
+ case AV_OPT_TYPE_FLAGS:
+ case AV_OPT_TYPE_PIXEL_FMT:
+ case AV_OPT_TYPE_SAMPLE_FMT:
+ case AV_OPT_TYPE_INT:
+ case AV_OPT_TYPE_CHANNEL_LAYOUT:
+ case AV_OPT_TYPE_DURATION:
+ case AV_OPT_TYPE_INT64:
+ case AV_OPT_TYPE_UINT64:
+ read_number(o, dst, NULL, NULL, &i64);
+ return o->default_val.i64 == i64;
+ case AV_OPT_TYPE_STRING:
+ str = *(char **)dst;
+ if (str == o->default_val.str) //2 NULLs
+ return 1;
+ if (!str || !o->default_val.str) //1 NULL
+ return 0;
+ return !strcmp(str, o->default_val.str);
+ case AV_OPT_TYPE_DOUBLE:
+ read_number(o, dst, &d, NULL, NULL);
+ return o->default_val.dbl == d;
+ case AV_OPT_TYPE_FLOAT:
+ read_number(o, dst, &d, NULL, NULL);
+ f = o->default_val.dbl;
+ d2 = f;
+ return d2 == d;
+ case AV_OPT_TYPE_RATIONAL:
+ q = av_d2q(o->default_val.dbl, INT_MAX);
+ return !av_cmp_q(*(AVRational*)dst, q);
+ case AV_OPT_TYPE_BINARY: {
+ struct {
+ uint8_t *data;
+ int size;
+ } tmp = {0};
+ int opt_size = *(int *)((void **)dst + 1);
+ void *opt_ptr = *(void **)dst;
+ if (!opt_size && (!o->default_val.str || !strlen(o->default_val.str)))
+ return 1;
+ if (!opt_size || !o->default_val.str || !strlen(o->default_val.str ))
+ return 0;
+ if (opt_size != strlen(o->default_val.str) / 2)
+ return 0;
+ ret = set_string_binary(NULL, NULL, o->default_val.str, &tmp.data);
+ if (!ret)
+ ret = !memcmp(opt_ptr, tmp.data, tmp.size);
+ av_free(tmp.data);
+ return ret;
+ }
+ case AV_OPT_TYPE_DICT:
+ /* Binary and dict have not default support yet. Any pointer is not default. */
+ return !!(*(void **)dst);
+ case AV_OPT_TYPE_IMAGE_SIZE:
+ if (!o->default_val.str || !strcmp(o->default_val.str, "none"))
+ w = h = 0;
+ else if ((ret = av_parse_video_size(&w, &h, o->default_val.str)) < 0)
+ return ret;
+ return (w == *(int *)dst) && (h == *((int *)dst+1));
+ case AV_OPT_TYPE_VIDEO_RATE:
+ q = (AVRational){0, 0};
+ if (o->default_val.str) {
+ if ((ret = av_parse_video_rate(&q, o->default_val.str)) < 0)
+ return ret;
+ }
+ return !av_cmp_q(*(AVRational*)dst, q);
+ case AV_OPT_TYPE_COLOR: {
+ uint8_t color[4] = {0, 0, 0, 0};
+ if (o->default_val.str) {
+ if ((ret = av_parse_color(color, o->default_val.str, -1, NULL)) < 0)
+ return ret;
+ }
+ return !memcmp(color, dst, sizeof(color));
+ }
+ default:
+ av_log(obj, AV_LOG_WARNING, "Not supported option type: %d, option name: %s\n", o->type, o->name);
+ break;
+ }
+ return AVERROR_PATCHWELCOME;
+}
+
+int av_opt_is_set_to_default_by_name(void *obj, const char *name, int search_flags)
+{
+ const AVOption *o;
+ void *target;
+ if (!obj)
+ return AVERROR(EINVAL);
+ o = av_opt_find2(obj, name, NULL, 0, search_flags, &target);
+ if (!o)
+ return AVERROR_OPTION_NOT_FOUND;
+ return av_opt_is_set_to_default(target, o);
+}
+
+int av_opt_serialize(void *obj, int opt_flags, int flags, char **buffer,
+ const char key_val_sep, const char pairs_sep)
+{
+ const AVOption *o = NULL;
+ uint8_t *buf;
+ AVBPrint bprint;
+ int ret, cnt = 0;
+ const char special_chars[] = {pairs_sep, key_val_sep, '\0'};
+
+ if (pairs_sep == '\0' || key_val_sep == '\0' || pairs_sep == key_val_sep ||
+ pairs_sep == '\\' || key_val_sep == '\\') {
+ av_log(obj, AV_LOG_ERROR, "Invalid separator(s) found.");
+ return AVERROR(EINVAL);
+ }
+
+ if (!obj || !buffer)
+ return AVERROR(EINVAL);
+
+ *buffer = NULL;
+ av_bprint_init(&bprint, 64, AV_BPRINT_SIZE_UNLIMITED);
+
+ while (o = av_opt_next(obj, o)) {
+ if (o->type == AV_OPT_TYPE_CONST)
+ continue;
+ if ((flags & AV_OPT_SERIALIZE_OPT_FLAGS_EXACT) && o->flags != opt_flags)
+ continue;
+ else if (((o->flags & opt_flags) != opt_flags))
+ continue;
+ if (flags & AV_OPT_SERIALIZE_SKIP_DEFAULTS && av_opt_is_set_to_default(obj, o) > 0)
+ continue;
+ if ((ret = av_opt_get(obj, o->name, 0, &buf)) < 0) {
+ av_bprint_finalize(&bprint, NULL);
+ return ret;
+ }
+ if (buf) {
+ if (cnt++)
+ av_bprint_append_data(&bprint, &pairs_sep, 1);
+ av_bprint_escape(&bprint, o->name, special_chars, AV_ESCAPE_MODE_BACKSLASH, 0);
+ av_bprint_append_data(&bprint, &key_val_sep, 1);
+ av_bprint_escape(&bprint, buf, special_chars, AV_ESCAPE_MODE_BACKSLASH, 0);
+ av_freep(&buf);
+ }
+ }
+ av_bprint_finalize(&bprint, buffer);
+ return 0;
+}
diff --git a/media/ffvpx/libavutil/opt.h b/media/ffvpx/libavutil/opt.h
index 9430b989e..0d893795d 100644
--- a/media/ffvpx/libavutil/opt.h
+++ b/media/ffvpx/libavutil/opt.h
@@ -228,6 +228,7 @@ enum AVOptionType{
AV_OPT_TYPE_RATIONAL,
AV_OPT_TYPE_BINARY, ///< offset must point to a pointer immediately followed by an int for the length
AV_OPT_TYPE_DICT,
+ AV_OPT_TYPE_UINT64,
AV_OPT_TYPE_CONST = 128,
AV_OPT_TYPE_IMAGE_SIZE = MKBETAG('S','I','Z','E'), ///< offset must point to two consecutive integers
AV_OPT_TYPE_PIXEL_FMT = MKBETAG('P','F','M','T'),
diff --git a/media/ffvpx/libavutil/parseutils.c b/media/ffvpx/libavutil/parseutils.c
index a2464cfc6..be4ea1ee1 100644
--- a/media/ffvpx/libavutil/parseutils.c
+++ b/media/ffvpx/libavutil/parseutils.c
@@ -140,6 +140,11 @@ static const VideoRateAbbr video_rate_abbrs[]= {
{ "ntsc-film", { 24000, 1001 } },
};
+static const char *months[12] = {
+ "january", "february", "march", "april", "may", "june", "july", "august",
+ "september", "october", "november", "december"
+};
+
int av_parse_video_size(int *width_ptr, int *height_ptr, const char *str)
{
int i;
@@ -466,6 +471,21 @@ static int date_get_num(const char **pp,
return val;
}
+static int date_get_month(const char **pp) {
+ int i = 0;
+ for (; i < 12; i++) {
+ if (!av_strncasecmp(*pp, months[i], 3)) {
+ const char *mo_full = months[i] + 3;
+ int len = strlen(mo_full);
+ *pp += 3;
+ if (len > 0 && !av_strncasecmp(*pp, mo_full, len))
+ *pp += len;
+ return i;
+ }
+ }
+ return -1;
+}
+
char *av_small_strptime(const char *p, const char *fmt, struct tm *dt)
{
int c, val;
@@ -525,6 +545,14 @@ char *av_small_strptime(const char *p, const char *fmt, struct tm *dt)
if (!p)
return NULL;
break;
+ case 'b':
+ case 'B':
+ case 'h':
+ val = date_get_month(&p);
+ if (val == -1)
+ return NULL;
+ dt->tm_mon = val;
+ break;
case '%':
if (*p++ != '%')
return NULL;
diff --git a/media/ffvpx/libavutil/pixdesc.c b/media/ffvpx/libavutil/pixdesc.c
index b715fce15..2cfab89c0 100644
--- a/media/ffvpx/libavutil/pixdesc.c
+++ b/media/ffvpx/libavutil/pixdesc.c
@@ -560,6 +560,69 @@ static const AVPixFmtDescriptor av_pix_fmt_descriptors[AV_PIX_FMT_NB] = {
},
.flags = AV_PIX_FMT_FLAG_RGB,
},
+ [AV_PIX_FMT_GRAY9BE] = {
+ .name = "gray9be",
+ .nb_components = 1,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 0, 2, 0, 0, 9, 1, 8, 1 }, /* Y */
+ },
+ .flags = AV_PIX_FMT_FLAG_BE,
+ .alias = "y9be",
+ },
+ [AV_PIX_FMT_GRAY9LE] = {
+ .name = "gray9le",
+ .nb_components = 1,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 0, 2, 0, 0, 9, 1, 8, 1 }, /* Y */
+ },
+ .alias = "y9le",
+ },
+ [AV_PIX_FMT_GRAY10BE] = {
+ .name = "gray10be",
+ .nb_components = 1,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 0, 2, 0, 0, 10, 1, 9, 1 }, /* Y */
+ },
+ .flags = AV_PIX_FMT_FLAG_BE,
+ .alias = "y10be",
+ },
+ [AV_PIX_FMT_GRAY10LE] = {
+ .name = "gray10le",
+ .nb_components = 1,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 0, 2, 0, 0, 10, 1, 9, 1 }, /* Y */
+ },
+ .alias = "y10le",
+ },
+ [AV_PIX_FMT_GRAY12BE] = {
+ .name = "gray12be",
+ .nb_components = 1,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 0, 2, 0, 0, 12, 1, 11, 1 }, /* Y */
+ },
+ .flags = AV_PIX_FMT_FLAG_BE,
+ .alias = "y12be",
+ },
+ [AV_PIX_FMT_GRAY12LE] = {
+ .name = "gray12le",
+ .nb_components = 1,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 0, 2, 0, 0, 12, 1, 11, 1 }, /* Y */
+ },
+ .alias = "y12le",
+ },
[AV_PIX_FMT_GRAY16BE] = {
.name = "gray16be",
.nb_components = 1,
@@ -1873,62 +1936,62 @@ static const AVPixFmtDescriptor av_pix_fmt_descriptors[AV_PIX_FMT_NB] = {
[AV_PIX_FMT_BAYER_BGGR8] = {
.name = "bayer_bggr8",
BAYER8_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_BGGR16LE] = {
.name = "bayer_bggr16le",
BAYER16_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_BGGR16BE] = {
.name = "bayer_bggr16be",
BAYER16_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_RGGB8] = {
.name = "bayer_rggb8",
BAYER8_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_RGGB16LE] = {
.name = "bayer_rggb16le",
BAYER16_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_RGGB16BE] = {
.name = "bayer_rggb16be",
BAYER16_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_GBRG8] = {
.name = "bayer_gbrg8",
BAYER8_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_GBRG16LE] = {
.name = "bayer_gbrg16le",
BAYER16_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_GBRG16BE] = {
.name = "bayer_gbrg16be",
BAYER16_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_GRBG8] = {
.name = "bayer_grbg8",
BAYER8_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_GRBG16LE] = {
.name = "bayer_grbg16le",
BAYER16_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_BAYER_GRBG16BE] = {
.name = "bayer_grbg16be",
BAYER16_DESC_COMMON
- .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_RGB,
+ .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_BAYER,
},
[AV_PIX_FMT_NV16] = {
.name = "nv16",
@@ -2036,6 +2099,30 @@ static const AVPixFmtDescriptor av_pix_fmt_descriptors[AV_PIX_FMT_NB] = {
},
.flags = AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_BE,
},
+ [AV_PIX_FMT_P016LE] = {
+ .name = "p016le",
+ .nb_components = 3,
+ .log2_chroma_w = 1,
+ .log2_chroma_h = 1,
+ .comp = {
+ { 0, 2, 0, 0, 16, 1, 15, 1 }, /* Y */
+ { 1, 4, 0, 0, 16, 3, 15, 1 }, /* U */
+ { 1, 4, 2, 0, 16, 3, 15, 3 }, /* V */
+ },
+ .flags = AV_PIX_FMT_FLAG_PLANAR,
+ },
+ [AV_PIX_FMT_P016BE] = {
+ .name = "p016be",
+ .nb_components = 3,
+ .log2_chroma_w = 1,
+ .log2_chroma_h = 1,
+ .comp = {
+ { 0, 2, 0, 0, 16, 1, 15, 1 }, /* Y */
+ { 1, 4, 0, 0, 16, 3, 15, 1 }, /* U */
+ { 1, 4, 2, 0, 16, 3, 15, 3 }, /* V */
+ },
+ .flags = AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_BE,
+ },
[AV_PIX_FMT_GBRAP12LE] = {
.name = "gbrap12le",
.nb_components = 4,
@@ -2092,18 +2179,80 @@ static const AVPixFmtDescriptor av_pix_fmt_descriptors[AV_PIX_FMT_NB] = {
.flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_PLANAR |
AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_ALPHA,
},
+ [AV_PIX_FMT_D3D11] = {
+ .name = "d3d11",
+ .flags = AV_PIX_FMT_FLAG_HWACCEL,
+ },
+ [AV_PIX_FMT_GBRPF32BE] = {
+ .name = "gbrpf32be",
+ .nb_components = 3,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 2, 4, 0, 0, 32, 3, 31, 1 }, /* R */
+ { 0, 4, 0, 0, 32, 3, 31, 1 }, /* G */
+ { 1, 4, 0, 0, 32, 3, 31, 1 }, /* B */
+ },
+ .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_PLANAR |
+ AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_FLOAT,
+ },
+ [AV_PIX_FMT_GBRPF32LE] = {
+ .name = "gbrpf32le",
+ .nb_components = 3,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 2, 4, 0, 0, 32, 3, 31, 1 }, /* R */
+ { 0, 4, 0, 0, 32, 3, 31, 1 }, /* G */
+ { 1, 4, 0, 0, 32, 3, 31, 1 }, /* B */
+ },
+ .flags = AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_FLOAT | AV_PIX_FMT_FLAG_RGB,
+ },
+ [AV_PIX_FMT_GBRAPF32BE] = {
+ .name = "gbrapf32be",
+ .nb_components = 4,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 2, 4, 0, 0, 32, 3, 31, 1 }, /* R */
+ { 0, 4, 0, 0, 32, 3, 31, 1 }, /* G */
+ { 1, 4, 0, 0, 32, 3, 31, 1 }, /* B */
+ { 3, 4, 0, 0, 32, 3, 31, 1 }, /* A */
+ },
+ .flags = AV_PIX_FMT_FLAG_BE | AV_PIX_FMT_FLAG_PLANAR |
+ AV_PIX_FMT_FLAG_ALPHA | AV_PIX_FMT_FLAG_RGB |
+ AV_PIX_FMT_FLAG_FLOAT,
+ },
+ [AV_PIX_FMT_GBRAPF32LE] = {
+ .name = "gbrapf32le",
+ .nb_components = 4,
+ .log2_chroma_w = 0,
+ .log2_chroma_h = 0,
+ .comp = {
+ { 2, 4, 0, 0, 32, 3, 31, 1 }, /* R */
+ { 0, 4, 0, 0, 32, 3, 31, 1 }, /* G */
+ { 1, 4, 0, 0, 32, 3, 31, 1 }, /* B */
+ { 3, 4, 0, 0, 32, 3, 31, 1 }, /* A */
+ },
+ .flags = AV_PIX_FMT_FLAG_PLANAR | AV_PIX_FMT_FLAG_ALPHA |
+ AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_FLOAT,
+ },
+ [AV_PIX_FMT_DRM_PRIME] = {
+ .name = "drm_prime",
+ .flags = AV_PIX_FMT_FLAG_HWACCEL,
+ },
};
#if FF_API_PLUS1_MINUS1
FF_ENABLE_DEPRECATION_WARNINGS
#endif
-static const char *color_range_names[] = {
+static const char * const color_range_names[] = {
[AVCOL_RANGE_UNSPECIFIED] = "unknown",
[AVCOL_RANGE_MPEG] = "tv",
[AVCOL_RANGE_JPEG] = "pc",
};
-static const char *color_primaries_names[AVCOL_PRI_NB] = {
+static const char * const color_primaries_names[AVCOL_PRI_NB] = {
[AVCOL_PRI_RESERVED0] = "reserved",
[AVCOL_PRI_BT709] = "bt709",
[AVCOL_PRI_UNSPECIFIED] = "unknown",
@@ -2114,12 +2263,13 @@ static const char *color_primaries_names[AVCOL_PRI_NB] = {
[AVCOL_PRI_SMPTE240M] = "smpte240m",
[AVCOL_PRI_FILM] = "film",
[AVCOL_PRI_BT2020] = "bt2020",
- [AVCOL_PRI_SMPTEST428_1] = "smpte428-1",
+ [AVCOL_PRI_SMPTE428] = "smpte428",
[AVCOL_PRI_SMPTE431] = "smpte431",
[AVCOL_PRI_SMPTE432] = "smpte432",
+ [AVCOL_PRI_JEDEC_P22] = "jedec-p22",
};
-static const char *color_transfer_names[] = {
+static const char * const color_transfer_names[] = {
[AVCOL_TRC_RESERVED0] = "reserved",
[AVCOL_TRC_BT709] = "bt709",
[AVCOL_TRC_UNSPECIFIED] = "unknown",
@@ -2135,13 +2285,13 @@ static const char *color_transfer_names[] = {
[AVCOL_TRC_BT1361_ECG] = "bt1361e",
[AVCOL_TRC_IEC61966_2_1] = "iec61966-2-1",
[AVCOL_TRC_BT2020_10] = "bt2020-10",
- [AVCOL_TRC_BT2020_12] = "bt2020-20",
- [AVCOL_TRC_SMPTEST2084] = "smpte2084",
- [AVCOL_TRC_SMPTEST428_1] = "smpte428-1",
+ [AVCOL_TRC_BT2020_12] = "bt2020-12",
+ [AVCOL_TRC_SMPTE2084] = "smpte2084",
+ [AVCOL_TRC_SMPTE428] = "smpte428",
[AVCOL_TRC_ARIB_STD_B67] = "arib-std-b67",
};
-static const char *color_space_names[] = {
+static const char * const color_space_names[] = {
[AVCOL_SPC_RGB] = "gbr",
[AVCOL_SPC_BT709] = "bt709",
[AVCOL_SPC_UNSPECIFIED] = "unknown",
@@ -2150,13 +2300,16 @@ static const char *color_space_names[] = {
[AVCOL_SPC_BT470BG] = "bt470bg",
[AVCOL_SPC_SMPTE170M] = "smpte170m",
[AVCOL_SPC_SMPTE240M] = "smpte240m",
- [AVCOL_SPC_YCOCG] = "ycgco",
+ [AVCOL_SPC_YCGCO] = "ycgco",
[AVCOL_SPC_BT2020_NCL] = "bt2020nc",
[AVCOL_SPC_BT2020_CL] = "bt2020c",
[AVCOL_SPC_SMPTE2085] = "smpte2085",
+ [AVCOL_SPC_CHROMA_DERIVED_NCL] = "chroma-derived-nc",
+ [AVCOL_SPC_CHROMA_DERIVED_CL] = "chroma-derived-c",
+ [AVCOL_SPC_ICTCP] = "ictcp",
};
-static const char *chroma_location_names[] = {
+static const char * const chroma_location_names[] = {
[AVCHROMA_LOC_UNSPECIFIED] = "unspecified",
[AVCHROMA_LOC_LEFT] = "left",
[AVCHROMA_LOC_CENTER] = "center",
@@ -2349,7 +2502,7 @@ void ff_check_pixfmt_descriptors(void){
} else {
av_assert0(8*c->step >= c->depth);
}
- if (!strncmp(d->name, "bayer_", 6))
+ if (d->flags & AV_PIX_FMT_FLAG_BAYER)
continue;
av_read_image_line(tmp, (void*)data, linesize, d, 0, 0, j, 2, 0);
av_assert0(tmp[0] == 0 && tmp[1] == 0);
@@ -2440,8 +2593,16 @@ static int get_pix_fmt_score(enum AVPixelFormat dst_pix_fmt,
int ret, loss, i, nb_components;
int score = INT_MAX - 1;
- if (dst_pix_fmt >= AV_PIX_FMT_NB || dst_pix_fmt <= AV_PIX_FMT_NONE)
- return ~0;
+ if (!src_desc || !dst_desc)
+ return -4;
+
+ if ((src_desc->flags & AV_PIX_FMT_FLAG_HWACCEL) ||
+ (dst_desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) {
+ if (dst_pix_fmt == src_pix_fmt)
+ return -1;
+ else
+ return -2;
+ }
/* compute loss */
*lossp = loss = 0;
@@ -2450,9 +2611,9 @@ static int get_pix_fmt_score(enum AVPixelFormat dst_pix_fmt,
return INT_MAX;
if ((ret = get_pix_fmt_depth(&src_min_depth, &src_max_depth, src_pix_fmt)) < 0)
- return ret;
+ return -3;
if ((ret = get_pix_fmt_depth(&dst_min_depth, &dst_max_depth, dst_pix_fmt)) < 0)
- return ret;
+ return -3;
src_color = get_color_type(src_desc);
dst_color = get_color_type(dst_desc);
@@ -2554,21 +2715,27 @@ enum AVPixelFormat av_find_best_pix_fmt_of_2(enum AVPixelFormat dst_pix_fmt1, en
const AVPixFmtDescriptor *desc2 = av_pix_fmt_desc_get(dst_pix_fmt2);
int score1, score2;
- loss_mask= loss_ptr?~*loss_ptr:~0; /* use loss mask if provided */
- if(!has_alpha)
- loss_mask &= ~FF_LOSS_ALPHA;
+ if (!desc1) {
+ dst_pix_fmt = dst_pix_fmt2;
+ } else if (!desc2) {
+ dst_pix_fmt = dst_pix_fmt1;
+ } else {
+ loss_mask= loss_ptr?~*loss_ptr:~0; /* use loss mask if provided */
+ if(!has_alpha)
+ loss_mask &= ~FF_LOSS_ALPHA;
- score1 = get_pix_fmt_score(dst_pix_fmt1, src_pix_fmt, &loss1, loss_mask);
- score2 = get_pix_fmt_score(dst_pix_fmt2, src_pix_fmt, &loss2, loss_mask);
+ score1 = get_pix_fmt_score(dst_pix_fmt1, src_pix_fmt, &loss1, loss_mask);
+ score2 = get_pix_fmt_score(dst_pix_fmt2, src_pix_fmt, &loss2, loss_mask);
- if (score1 == score2) {
- if(av_get_padded_bits_per_pixel(desc2) != av_get_padded_bits_per_pixel(desc1)) {
- dst_pix_fmt = av_get_padded_bits_per_pixel(desc2) < av_get_padded_bits_per_pixel(desc1) ? dst_pix_fmt2 : dst_pix_fmt1;
+ if (score1 == score2) {
+ if(av_get_padded_bits_per_pixel(desc2) != av_get_padded_bits_per_pixel(desc1)) {
+ dst_pix_fmt = av_get_padded_bits_per_pixel(desc2) < av_get_padded_bits_per_pixel(desc1) ? dst_pix_fmt2 : dst_pix_fmt1;
+ } else {
+ dst_pix_fmt = desc2->nb_components < desc1->nb_components ? dst_pix_fmt2 : dst_pix_fmt1;
+ }
} else {
- dst_pix_fmt = desc2->nb_components < desc1->nb_components ? dst_pix_fmt2 : dst_pix_fmt1;
+ dst_pix_fmt = score1 < score2 ? dst_pix_fmt2 : dst_pix_fmt1;
}
- } else {
- dst_pix_fmt = score1 < score2 ? dst_pix_fmt2 : dst_pix_fmt1;
}
if (loss_ptr)
@@ -2582,26 +2749,91 @@ const char *av_color_range_name(enum AVColorRange range)
color_range_names[range] : NULL;
}
+int av_color_range_from_name(const char *name)
+{
+ int i;
+
+ for (i = 0; i < FF_ARRAY_ELEMS(color_range_names); i++) {
+ size_t len = strlen(color_range_names[i]);
+ if (!strncmp(color_range_names[i], name, len))
+ return i;
+ }
+
+ return AVERROR(EINVAL);
+}
+
const char *av_color_primaries_name(enum AVColorPrimaries primaries)
{
return (unsigned) primaries < AVCOL_PRI_NB ?
color_primaries_names[primaries] : NULL;
}
+int av_color_primaries_from_name(const char *name)
+{
+ int i;
+
+ for (i = 0; i < FF_ARRAY_ELEMS(color_primaries_names); i++) {
+ size_t len = strlen(color_primaries_names[i]);
+ if (!strncmp(color_primaries_names[i], name, len))
+ return i;
+ }
+
+ return AVERROR(EINVAL);
+}
+
const char *av_color_transfer_name(enum AVColorTransferCharacteristic transfer)
{
return (unsigned) transfer < AVCOL_TRC_NB ?
color_transfer_names[transfer] : NULL;
}
+int av_color_transfer_from_name(const char *name)
+{
+ int i;
+
+ for (i = 0; i < FF_ARRAY_ELEMS(color_transfer_names); i++) {
+ size_t len = strlen(color_transfer_names[i]);
+ if (!strncmp(color_transfer_names[i], name, len))
+ return i;
+ }
+
+ return AVERROR(EINVAL);
+}
+
const char *av_color_space_name(enum AVColorSpace space)
{
return (unsigned) space < AVCOL_SPC_NB ?
color_space_names[space] : NULL;
}
+int av_color_space_from_name(const char *name)
+{
+ int i;
+
+ for (i = 0; i < FF_ARRAY_ELEMS(color_space_names); i++) {
+ size_t len = strlen(color_space_names[i]);
+ if (!strncmp(color_space_names[i], name, len))
+ return i;
+ }
+
+ return AVERROR(EINVAL);
+}
+
const char *av_chroma_location_name(enum AVChromaLocation location)
{
return (unsigned) location < AVCHROMA_LOC_NB ?
chroma_location_names[location] : NULL;
}
+
+int av_chroma_location_from_name(const char *name)
+{
+ int i;
+
+ for (i = 0; i < FF_ARRAY_ELEMS(chroma_location_names); i++) {
+ size_t len = strlen(chroma_location_names[i]);
+ if (!strncmp(chroma_location_names[i], name, len))
+ return i;
+ }
+
+ return AVERROR(EINVAL);
+}
diff --git a/media/ffvpx/libavutil/pixdesc.h b/media/ffvpx/libavutil/pixdesc.h
index a8ad58891..fc3737c4a 100644
--- a/media/ffvpx/libavutil/pixdesc.h
+++ b/media/ffvpx/libavutil/pixdesc.h
@@ -173,6 +173,17 @@ typedef struct AVPixFmtDescriptor {
#define AV_PIX_FMT_FLAG_ALPHA (1 << 7)
/**
+ * The pixel format is following a Bayer pattern
+ */
+#define AV_PIX_FMT_FLAG_BAYER (1 << 8)
+
+/**
+ * The pixel format contains IEEE-754 floating point values. Precision (double,
+ * single, or half) should be determined by the pixel size (64, 32, or 16 bits).
+ */
+#define AV_PIX_FMT_FLAG_FLOAT (1 << 9)
+
+/**
* Return the number of bits per pixel used by the pixel format
* described by pixdesc. Note that this is not the same as the number
* of bits per sample.
@@ -240,26 +251,51 @@ int av_pix_fmt_count_planes(enum AVPixelFormat pix_fmt);
const char *av_color_range_name(enum AVColorRange range);
/**
+ * @return the AVColorRange value for name or an AVError if not found.
+ */
+int av_color_range_from_name(const char *name);
+
+/**
* @return the name for provided color primaries or NULL if unknown.
*/
const char *av_color_primaries_name(enum AVColorPrimaries primaries);
/**
+ * @return the AVColorPrimaries value for name or an AVError if not found.
+ */
+int av_color_primaries_from_name(const char *name);
+
+/**
* @return the name for provided color transfer or NULL if unknown.
*/
const char *av_color_transfer_name(enum AVColorTransferCharacteristic transfer);
/**
+ * @return the AVColorTransferCharacteristic value for name or an AVError if not found.
+ */
+int av_color_transfer_from_name(const char *name);
+
+/**
* @return the name for provided color space or NULL if unknown.
*/
const char *av_color_space_name(enum AVColorSpace space);
/**
+ * @return the AVColorSpace value for name or an AVError if not found.
+ */
+int av_color_space_from_name(const char *name);
+
+/**
* @return the name for provided chroma location or NULL if unknown.
*/
const char *av_chroma_location_name(enum AVChromaLocation location);
/**
+ * @return the AVChromaLocation value for name or an AVError if not found.
+ */
+int av_chroma_location_from_name(const char *name);
+
+/**
* Return the pixel format corresponding to name.
*
* If there is no pixel format with name name, then looks for a
diff --git a/media/ffvpx/libavutil/pixfmt.h b/media/ffvpx/libavutil/pixfmt.h
index 7a3f68be7..24889c8e5 100644
--- a/media/ffvpx/libavutil/pixfmt.h
+++ b/media/ffvpx/libavutil/pixfmt.h
@@ -240,7 +240,7 @@ enum AVPixelFormat {
*/
AV_PIX_FMT_MMAL,
- AV_PIX_FMT_D3D11VA_VLD, ///< HW decoding through Direct3D11, Picture.data[3] contains a ID3D11VideoDecoderOutputView pointer
+ AV_PIX_FMT_D3D11VA_VLD, ///< HW decoding through Direct3D11 via old API, Picture.data[3] contains a ID3D11VideoDecoderOutputView pointer
/**
* HW acceleration through CUDA. data[i] contain CUdeviceptr pointers
@@ -306,6 +306,41 @@ enum AVPixelFormat {
AV_PIX_FMT_MEDIACODEC, ///< hardware decoding through MediaCodec
+ AV_PIX_FMT_GRAY12BE, ///< Y , 12bpp, big-endian
+ AV_PIX_FMT_GRAY12LE, ///< Y , 12bpp, little-endian
+ AV_PIX_FMT_GRAY10BE, ///< Y , 10bpp, big-endian
+ AV_PIX_FMT_GRAY10LE, ///< Y , 10bpp, little-endian
+
+ AV_PIX_FMT_P016LE, ///< like NV12, with 16bpp per component, little-endian
+ AV_PIX_FMT_P016BE, ///< like NV12, with 16bpp per component, big-endian
+
+ /**
+ * Hardware surfaces for Direct3D11.
+ *
+ * This is preferred over the legacy AV_PIX_FMT_D3D11VA_VLD. The new D3D11
+ * hwaccel API and filtering support AV_PIX_FMT_D3D11 only.
+ *
+ * data[0] contains a ID3D11Texture2D pointer, and data[1] contains the
+ * texture array index of the frame as intptr_t if the ID3D11Texture2D is
+ * an array texture (or always 0 if it's a normal texture).
+ */
+ AV_PIX_FMT_D3D11,
+
+ AV_PIX_FMT_GRAY9BE, ///< Y , 9bpp, big-endian
+ AV_PIX_FMT_GRAY9LE, ///< Y , 9bpp, little-endian
+
+ AV_PIX_FMT_GBRPF32BE, ///< IEEE-754 single precision planar GBR 4:4:4, 96bpp, big-endian
+ AV_PIX_FMT_GBRPF32LE, ///< IEEE-754 single precision planar GBR 4:4:4, 96bpp, little-endian
+ AV_PIX_FMT_GBRAPF32BE, ///< IEEE-754 single precision planar GBRA 4:4:4:4, 128bpp, big-endian
+ AV_PIX_FMT_GBRAPF32LE, ///< IEEE-754 single precision planar GBRA 4:4:4:4, 128bpp, little-endian
+
+ /**
+ * DRM-managed buffers exposed through PRIME buffer sharing.
+ *
+ * data[0] points to an AVDRMFrameDescriptor.
+ */
+ AV_PIX_FMT_DRM_PRIME,
+
AV_PIX_FMT_NB ///< number of pixel formats, DO NOT USE THIS if you want to link with shared libav* because the number of formats might differ between versions
};
@@ -322,6 +357,9 @@ enum AVPixelFormat {
#define AV_PIX_FMT_0RGB32 AV_PIX_FMT_NE(0RGB, BGR0)
#define AV_PIX_FMT_0BGR32 AV_PIX_FMT_NE(0BGR, RGB0)
+#define AV_PIX_FMT_GRAY9 AV_PIX_FMT_NE(GRAY9BE, GRAY9LE)
+#define AV_PIX_FMT_GRAY10 AV_PIX_FMT_NE(GRAY10BE, GRAY10LE)
+#define AV_PIX_FMT_GRAY12 AV_PIX_FMT_NE(GRAY12BE, GRAY12LE)
#define AV_PIX_FMT_GRAY16 AV_PIX_FMT_NE(GRAY16BE, GRAY16LE)
#define AV_PIX_FMT_YA16 AV_PIX_FMT_NE(YA16BE, YA16LE)
#define AV_PIX_FMT_RGB48 AV_PIX_FMT_NE(RGB48BE, RGB48LE)
@@ -367,6 +405,8 @@ enum AVPixelFormat {
#define AV_PIX_FMT_BAYER_GBRG16 AV_PIX_FMT_NE(BAYER_GBRG16BE, BAYER_GBRG16LE)
#define AV_PIX_FMT_BAYER_GRBG16 AV_PIX_FMT_NE(BAYER_GRBG16BE, BAYER_GRBG16LE)
+#define AV_PIX_FMT_GBRPF32 AV_PIX_FMT_NE(GBRPF32BE, GBRPF32LE)
+#define AV_PIX_FMT_GBRAPF32 AV_PIX_FMT_NE(GBRAPF32BE, GBRAPF32LE)
#define AV_PIX_FMT_YUVA420P9 AV_PIX_FMT_NE(YUVA420P9BE , YUVA420P9LE)
#define AV_PIX_FMT_YUVA422P9 AV_PIX_FMT_NE(YUVA422P9BE , YUVA422P9LE)
@@ -382,9 +422,11 @@ enum AVPixelFormat {
#define AV_PIX_FMT_NV20 AV_PIX_FMT_NE(NV20BE, NV20LE)
#define AV_PIX_FMT_AYUV64 AV_PIX_FMT_NE(AYUV64BE, AYUV64LE)
#define AV_PIX_FMT_P010 AV_PIX_FMT_NE(P010BE, P010LE)
+#define AV_PIX_FMT_P016 AV_PIX_FMT_NE(P016BE, P016LE)
/**
* Chromaticity coordinates of the source primaries.
+ * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.1.
*/
enum AVColorPrimaries {
AVCOL_PRI_RESERVED0 = 0,
@@ -398,14 +440,17 @@ enum AVColorPrimaries {
AVCOL_PRI_SMPTE240M = 7, ///< functionally identical to above
AVCOL_PRI_FILM = 8, ///< colour filters using Illuminant C
AVCOL_PRI_BT2020 = 9, ///< ITU-R BT2020
- AVCOL_PRI_SMPTEST428_1 = 10, ///< SMPTE ST 428-1 (CIE 1931 XYZ)
- AVCOL_PRI_SMPTE431 = 11, ///< SMPTE ST 431-2 (2011)
- AVCOL_PRI_SMPTE432 = 12, ///< SMPTE ST 432-1 D65 (2010)
+ AVCOL_PRI_SMPTE428 = 10, ///< SMPTE ST 428-1 (CIE 1931 XYZ)
+ AVCOL_PRI_SMPTEST428_1 = AVCOL_PRI_SMPTE428,
+ AVCOL_PRI_SMPTE431 = 11, ///< SMPTE ST 431-2 (2011) / DCI P3
+ AVCOL_PRI_SMPTE432 = 12, ///< SMPTE ST 432-1 (2010) / P3 D65 / Display P3
+ AVCOL_PRI_JEDEC_P22 = 22, ///< JEDEC P22 phosphors
AVCOL_PRI_NB ///< Not part of ABI
};
/**
* Color Transfer Characteristic.
+ * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.2.
*/
enum AVColorTransferCharacteristic {
AVCOL_TRC_RESERVED0 = 0,
@@ -424,14 +469,17 @@ enum AVColorTransferCharacteristic {
AVCOL_TRC_IEC61966_2_1 = 13, ///< IEC 61966-2-1 (sRGB or sYCC)
AVCOL_TRC_BT2020_10 = 14, ///< ITU-R BT2020 for 10-bit system
AVCOL_TRC_BT2020_12 = 15, ///< ITU-R BT2020 for 12-bit system
- AVCOL_TRC_SMPTEST2084 = 16, ///< SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems
- AVCOL_TRC_SMPTEST428_1 = 17, ///< SMPTE ST 428-1
+ AVCOL_TRC_SMPTE2084 = 16, ///< SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems
+ AVCOL_TRC_SMPTEST2084 = AVCOL_TRC_SMPTE2084,
+ AVCOL_TRC_SMPTE428 = 17, ///< SMPTE ST 428-1
+ AVCOL_TRC_SMPTEST428_1 = AVCOL_TRC_SMPTE428,
AVCOL_TRC_ARIB_STD_B67 = 18, ///< ARIB STD-B67, known as "Hybrid log-gamma"
AVCOL_TRC_NB ///< Not part of ABI
};
/**
* YUV colorspace type.
+ * These values match the ones defined by ISO/IEC 23001-8_2013 § 7.3.
*/
enum AVColorSpace {
AVCOL_SPC_RGB = 0, ///< order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB)
@@ -442,14 +490,16 @@ enum AVColorSpace {
AVCOL_SPC_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
AVCOL_SPC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC
AVCOL_SPC_SMPTE240M = 7, ///< functionally identical to above
- AVCOL_SPC_YCOCG = 8, ///< Used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16
+ AVCOL_SPC_YCGCO = 8, ///< Used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16
+ AVCOL_SPC_YCOCG = AVCOL_SPC_YCGCO,
AVCOL_SPC_BT2020_NCL = 9, ///< ITU-R BT2020 non-constant luminance system
AVCOL_SPC_BT2020_CL = 10, ///< ITU-R BT2020 constant luminance system
AVCOL_SPC_SMPTE2085 = 11, ///< SMPTE 2085, Y'D'zD'x
+ AVCOL_SPC_CHROMA_DERIVED_NCL = 12, ///< Chromaticity-derived non-constant luminance system
+ AVCOL_SPC_CHROMA_DERIVED_CL = 13, ///< Chromaticity-derived constant luminance system
+ AVCOL_SPC_ICTCP = 14, ///< ITU-R BT.2100-0, ICtCp
AVCOL_SPC_NB ///< Not part of ABI
};
-#define AVCOL_SPC_YCGCO AVCOL_SPC_YCOCG
-
/**
* MPEG vs JPEG YUV range.
diff --git a/media/ffvpx/libavcodec/ff_options_table.h b/media/ffvpx/libavutil/reverse.h
index ee01275d3..4eb612393 100644
--- a/media/ffvpx/libavcodec/ff_options_table.h
+++ b/media/ffvpx/libavutil/reverse.h
@@ -1,5 +1,4 @@
/*
- * Copyright (c) 2001 Fabrice Bellard
* Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
@@ -19,12 +18,11 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
-#ifndef AVCODEC_OPTIONS_TABLE_H
-#define AVCODEC_OPTIONS_TABLE_H
+#ifndef AVUTIL_REVERSE_H
+#define AVUTIL_REVERSE_H
-#include "libavutil/opt.h"
-static const AVOption avcodec_options[] = {
-{NULL},
-};
+#include <stdint.h>
-#endif /* AVCODEC_OPTIONS_TABLE_H */
+extern const uint8_t ff_reverse[256];
+
+#endif /* AVUTIL_REVERSE_H */
diff --git a/media/ffvpx/libavutil/slicethread.c b/media/ffvpx/libavutil/slicethread.c
new file mode 100644
index 000000000..c43f87a2a
--- /dev/null
+++ b/media/ffvpx/libavutil/slicethread.c
@@ -0,0 +1,259 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stdatomic.h>
+#include "slicethread.h"
+#include "mem.h"
+#include "thread.h"
+#include "avassert.h"
+
+#if HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS2THREADS
+
+typedef struct WorkerContext {
+ AVSliceThread *ctx;
+ pthread_mutex_t mutex;
+ pthread_cond_t cond;
+ pthread_t thread;
+ int done;
+} WorkerContext;
+
+struct AVSliceThread {
+ WorkerContext *workers;
+ int nb_threads;
+ int nb_active_threads;
+ int nb_jobs;
+
+ atomic_uint first_job;
+ atomic_uint current_job;
+ pthread_mutex_t done_mutex;
+ pthread_cond_t done_cond;
+ int done;
+ int finished;
+
+ void *priv;
+ void (*worker_func)(void *priv, int jobnr, int threadnr, int nb_jobs, int nb_threads);
+ void (*main_func)(void *priv);
+};
+
+static int run_jobs(AVSliceThread *ctx)
+{
+ unsigned nb_jobs = ctx->nb_jobs;
+ unsigned nb_active_threads = ctx->nb_active_threads;
+ unsigned first_job = atomic_fetch_add_explicit(&ctx->first_job, 1, memory_order_acq_rel);
+ unsigned current_job = first_job;
+
+ do {
+ ctx->worker_func(ctx->priv, current_job, first_job, nb_jobs, nb_active_threads);
+ } while ((current_job = atomic_fetch_add_explicit(&ctx->current_job, 1, memory_order_acq_rel)) < nb_jobs);
+
+ return current_job == nb_jobs + nb_active_threads - 1;
+}
+
+static void *attribute_align_arg thread_worker(void *v)
+{
+ WorkerContext *w = v;
+ AVSliceThread *ctx = w->ctx;
+
+ pthread_mutex_lock(&w->mutex);
+ pthread_cond_signal(&w->cond);
+
+ while (1) {
+ w->done = 1;
+ while (w->done)
+ pthread_cond_wait(&w->cond, &w->mutex);
+
+ if (ctx->finished) {
+ pthread_mutex_unlock(&w->mutex);
+ return NULL;
+ }
+
+ if (run_jobs(ctx)) {
+ pthread_mutex_lock(&ctx->done_mutex);
+ ctx->done = 1;
+ pthread_cond_signal(&ctx->done_cond);
+ pthread_mutex_unlock(&ctx->done_mutex);
+ }
+ }
+}
+
+int avpriv_slicethread_create(AVSliceThread **pctx, void *priv,
+ void (*worker_func)(void *priv, int jobnr, int threadnr, int nb_jobs, int nb_threads),
+ void (*main_func)(void *priv),
+ int nb_threads)
+{
+ AVSliceThread *ctx;
+ int nb_workers, i;
+
+#if HAVE_W32THREADS
+ w32thread_init();
+#endif
+
+ av_assert0(nb_threads >= 0);
+ if (!nb_threads) {
+ int nb_cpus = av_cpu_count();
+ if (nb_cpus > 1)
+ nb_threads = nb_cpus + 1;
+ else
+ nb_threads = 1;
+ }
+
+ nb_workers = nb_threads;
+ if (!main_func)
+ nb_workers--;
+
+ *pctx = ctx = av_mallocz(sizeof(*ctx));
+ if (!ctx)
+ return AVERROR(ENOMEM);
+
+ if (nb_workers && !(ctx->workers = av_calloc(nb_workers, sizeof(*ctx->workers)))) {
+ av_freep(pctx);
+ return AVERROR(ENOMEM);
+ }
+
+ ctx->priv = priv;
+ ctx->worker_func = worker_func;
+ ctx->main_func = main_func;
+ ctx->nb_threads = nb_threads;
+ ctx->nb_active_threads = 0;
+ ctx->nb_jobs = 0;
+ ctx->finished = 0;
+
+ atomic_init(&ctx->first_job, 0);
+ atomic_init(&ctx->current_job, 0);
+ pthread_mutex_init(&ctx->done_mutex, NULL);
+ pthread_cond_init(&ctx->done_cond, NULL);
+ ctx->done = 0;
+
+ for (i = 0; i < nb_workers; i++) {
+ WorkerContext *w = &ctx->workers[i];
+ int ret;
+ w->ctx = ctx;
+ pthread_mutex_init(&w->mutex, NULL);
+ pthread_cond_init(&w->cond, NULL);
+ pthread_mutex_lock(&w->mutex);
+ w->done = 0;
+
+ if (ret = pthread_create(&w->thread, NULL, thread_worker, w)) {
+ ctx->nb_threads = main_func ? i : i + 1;
+ pthread_mutex_unlock(&w->mutex);
+ pthread_cond_destroy(&w->cond);
+ pthread_mutex_destroy(&w->mutex);
+ avpriv_slicethread_free(pctx);
+ return AVERROR(ret);
+ }
+
+ while (!w->done)
+ pthread_cond_wait(&w->cond, &w->mutex);
+ pthread_mutex_unlock(&w->mutex);
+ }
+
+ return nb_threads;
+}
+
+void avpriv_slicethread_execute(AVSliceThread *ctx, int nb_jobs, int execute_main)
+{
+ int nb_workers, i, is_last = 0;
+
+ av_assert0(nb_jobs > 0);
+ ctx->nb_jobs = nb_jobs;
+ ctx->nb_active_threads = FFMIN(nb_jobs, ctx->nb_threads);
+ atomic_store_explicit(&ctx->first_job, 0, memory_order_relaxed);
+ atomic_store_explicit(&ctx->current_job, ctx->nb_active_threads, memory_order_relaxed);
+ nb_workers = ctx->nb_active_threads;
+ if (!ctx->main_func || !execute_main)
+ nb_workers--;
+
+ for (i = 0; i < nb_workers; i++) {
+ WorkerContext *w = &ctx->workers[i];
+ pthread_mutex_lock(&w->mutex);
+ w->done = 0;
+ pthread_cond_signal(&w->cond);
+ pthread_mutex_unlock(&w->mutex);
+ }
+
+ if (ctx->main_func && execute_main)
+ ctx->main_func(ctx->priv);
+ else
+ is_last = run_jobs(ctx);
+
+ if (!is_last) {
+ pthread_mutex_lock(&ctx->done_mutex);
+ while (!ctx->done)
+ pthread_cond_wait(&ctx->done_cond, &ctx->done_mutex);
+ ctx->done = 0;
+ pthread_mutex_unlock(&ctx->done_mutex);
+ }
+}
+
+void avpriv_slicethread_free(AVSliceThread **pctx)
+{
+ AVSliceThread *ctx;
+ int nb_workers, i;
+
+ if (!pctx || !*pctx)
+ return;
+
+ ctx = *pctx;
+ nb_workers = ctx->nb_threads;
+ if (!ctx->main_func)
+ nb_workers--;
+
+ ctx->finished = 1;
+ for (i = 0; i < nb_workers; i++) {
+ WorkerContext *w = &ctx->workers[i];
+ pthread_mutex_lock(&w->mutex);
+ w->done = 0;
+ pthread_cond_signal(&w->cond);
+ pthread_mutex_unlock(&w->mutex);
+ }
+
+ for (i = 0; i < nb_workers; i++) {
+ WorkerContext *w = &ctx->workers[i];
+ pthread_join(w->thread, NULL);
+ pthread_cond_destroy(&w->cond);
+ pthread_mutex_destroy(&w->mutex);
+ }
+
+ pthread_cond_destroy(&ctx->done_cond);
+ pthread_mutex_destroy(&ctx->done_mutex);
+ av_freep(&ctx->workers);
+ av_freep(pctx);
+}
+
+#else /* HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS32THREADS */
+
+int avpriv_slicethread_create(AVSliceThread **pctx, void *priv,
+ void (*worker_func)(void *priv, int jobnr, int threadnr, int nb_jobs, int nb_threads),
+ void (*main_func)(void *priv),
+ int nb_threads)
+{
+ *pctx = NULL;
+ return AVERROR(EINVAL);
+}
+
+void avpriv_slicethread_execute(AVSliceThread *ctx, int nb_jobs, int execute_main)
+{
+ av_assert0(0);
+}
+
+void avpriv_slicethread_free(AVSliceThread **pctx)
+{
+ av_assert0(!pctx || !*pctx);
+}
+
+#endif /* HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS32THREADS */
diff --git a/media/ffvpx/libavutil/slicethread.h b/media/ffvpx/libavutil/slicethread.h
new file mode 100644
index 000000000..f6f6f302c
--- /dev/null
+++ b/media/ffvpx/libavutil/slicethread.h
@@ -0,0 +1,52 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef AVUTIL_SLICETHREAD_H
+#define AVUTIL_SLICETHREAD_H
+
+typedef struct AVSliceThread AVSliceThread;
+
+/**
+ * Create slice threading context.
+ * @param pctx slice threading context returned here
+ * @param priv private pointer to be passed to callback function
+ * @param worker_func callback function to be executed
+ * @param main_func special callback function, called from main thread, may be NULL
+ * @param nb_threads number of threads, 0 for automatic, must be >= 0
+ * @return return number of threads or negative AVERROR on failure
+ */
+int avpriv_slicethread_create(AVSliceThread **pctx, void *priv,
+ void (*worker_func)(void *priv, int jobnr, int threadnr, int nb_jobs, int nb_threads),
+ void (*main_func)(void *priv),
+ int nb_threads);
+
+/**
+ * Execute slice threading.
+ * @param ctx slice threading context
+ * @param nb_jobs number of jobs, must be > 0
+ * @param execute_main also execute main_func
+ */
+void avpriv_slicethread_execute(AVSliceThread *ctx, int nb_jobs, int execute_main);
+
+/**
+ * Destroy slice threading context.
+ * @param pctx pointer to context
+ */
+void avpriv_slicethread_free(AVSliceThread **pctx);
+
+#endif
diff --git a/media/ffvpx/libavutil/thread.h b/media/ffvpx/libavutil/thread.h
index 32ddf4036..f108e2005 100644
--- a/media/ffvpx/libavutil/thread.h
+++ b/media/ffvpx/libavutil/thread.h
@@ -26,8 +26,6 @@
#if HAVE_PTHREADS || HAVE_W32THREADS || HAVE_OS2THREADS
-#define USE_ATOMICS 0
-
#if HAVE_PTHREADS
#include <pthread.h>
@@ -38,8 +36,11 @@
#define ASSERT_PTHREAD_NORET(func, ...) do { \
int ret = func(__VA_ARGS__); \
if (ret) { \
+ char errbuf[AV_ERROR_MAX_STRING_SIZE] = ""; \
av_log(NULL, AV_LOG_FATAL, AV_STRINGIFY(func) \
- " failed with error: %s\n", av_err2str(AVERROR(ret))); \
+ " failed with error: %s\n", \
+ av_make_error_string(errbuf, AV_ERROR_MAX_STRING_SIZE, \
+ AVERROR(ret))); \
abort(); \
} \
} while (0)
@@ -146,8 +147,6 @@ static inline int strict_pthread_once(pthread_once_t *once_control, void (*init_
#else
-#define USE_ATOMICS 1
-
#define AVMutex char
#define ff_mutex_init(mutex, attr) (0)
diff --git a/media/ffvpx/libavutil/threadmessage.c b/media/ffvpx/libavutil/threadmessage.c
index 7c5cd2463..872e9392b 100644
--- a/media/ffvpx/libavutil/threadmessage.c
+++ b/media/ffvpx/libavutil/threadmessage.c
@@ -69,7 +69,7 @@ int av_thread_message_queue_alloc(AVThreadMessageQueue **mq,
pthread_cond_destroy(&rmq->cond_recv);
pthread_mutex_destroy(&rmq->lock);
av_free(rmq);
- return AVERROR(ret);
+ return AVERROR(ENOMEM);
}
rmq->elsize = elsize;
*mq = rmq;
diff --git a/media/ffvpx/libavutil/time.c b/media/ffvpx/libavutil/time.c
index 69419e6f3..80d1faf26 100644
--- a/media/ffvpx/libavutil/time.c
+++ b/media/ffvpx/libavutil/time.c
@@ -56,17 +56,25 @@ int64_t av_gettime(void)
int64_t av_gettime_relative(void)
{
#if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
- struct timespec ts;
- clock_gettime(CLOCK_MONOTONIC, &ts);
- return (int64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
-#else
- return av_gettime() + 42 * 60 * 60 * INT64_C(1000000);
+#ifdef __APPLE__
+ if (clock_gettime)
+#endif
+ {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (int64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
+ }
#endif
+ return av_gettime() + 42 * 60 * 60 * INT64_C(1000000);
}
int av_gettime_relative_is_monotonic(void)
{
#if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
+#ifdef __APPLE__
+ if (!clock_gettime)
+ return 0;
+#endif
return 1;
#else
return 0;
diff --git a/media/ffvpx/libavutil/timecode.c b/media/ffvpx/libavutil/timecode.c
index fa92df1ef..c0c67c847 100644
--- a/media/ffvpx/libavutil/timecode.c
+++ b/media/ffvpx/libavutil/timecode.c
@@ -129,7 +129,8 @@ char *av_timecode_make_smpte_tc_string(char *buf, uint32_t tcsmpte, int prevent_
char *av_timecode_make_mpeg_tc_string(char *buf, uint32_t tc25bit)
{
- snprintf(buf, AV_TIMECODE_STR_SIZE, "%02u:%02u:%02u%c%02u",
+ snprintf(buf, AV_TIMECODE_STR_SIZE,
+ "%02"PRIu32":%02"PRIu32":%02"PRIu32"%c%02"PRIu32,
tc25bit>>19 & 0x1f, // 5-bit hours
tc25bit>>13 & 0x3f, // 6-bit minutes
tc25bit>>6 & 0x3f, // 6-bit seconds
diff --git a/media/ffvpx/libavutil/timecode.h b/media/ffvpx/libavutil/timecode.h
index 56e3975fd..37c1361bc 100644
--- a/media/ffvpx/libavutil/timecode.h
+++ b/media/ffvpx/libavutil/timecode.h
@@ -30,7 +30,7 @@
#include <stdint.h>
#include "rational.h"
-#define AV_TIMECODE_STR_SIZE 16
+#define AV_TIMECODE_STR_SIZE 23
enum AVTimecodeFlag {
AV_TIMECODE_FLAG_DROPFRAME = 1<<0, ///< timecode is drop frame
diff --git a/media/ffvpx/libavutil/timer.h b/media/ffvpx/libavutil/timer.h
index ed3b04787..f7ab455df 100644
--- a/media/ffvpx/libavutil/timer.h
+++ b/media/ffvpx/libavutil/timer.h
@@ -26,12 +26,22 @@
#ifndef AVUTIL_TIMER_H
#define AVUTIL_TIMER_H
+#include "config.h"
+
+#if CONFIG_LINUX_PERF
+# ifndef _GNU_SOURCE
+# define _GNU_SOURCE
+# endif
+# include <unistd.h> // read(3)
+# include <sys/ioctl.h>
+# include <asm/unistd.h>
+# include <linux/perf_event.h>
+#endif
+
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
-#include "config.h"
-
#if HAVE_MACH_MACH_TIME_H
#include <mach/mach_time.h>
#endif
@@ -60,23 +70,17 @@
# define FF_TIMER_UNITS "UNITS"
#endif
-#ifdef AV_READ_TIME
-#define START_TIMER \
- uint64_t tend; \
- uint64_t tstart = AV_READ_TIME(); \
-
-#define STOP_TIMER(id) \
- tend = AV_READ_TIME(); \
+#define TIMER_REPORT(id, tdiff) \
{ \
static uint64_t tsum = 0; \
static int tcount = 0; \
static int tskip_count = 0; \
static int thistogram[32] = {0}; \
- thistogram[av_log2(tend - tstart)]++; \
- if (tcount < 2 || \
- tend - tstart < 8 * tsum / tcount || \
- tend - tstart < 2000) { \
- tsum+= tend - tstart; \
+ thistogram[av_log2(tdiff)]++; \
+ if (tcount < 2 || \
+ (tdiff) < 8 * tsum / tcount || \
+ (tdiff) < 2000) { \
+ tsum += (tdiff); \
tcount++; \
} else \
tskip_count++; \
@@ -90,6 +94,45 @@
av_log(NULL, AV_LOG_ERROR, "\n"); \
} \
}
+
+#if CONFIG_LINUX_PERF
+
+#define START_TIMER \
+ static int linux_perf_fd; \
+ uint64_t tperf; \
+ if (!linux_perf_fd) { \
+ struct perf_event_attr attr = { \
+ .type = PERF_TYPE_HARDWARE, \
+ .size = sizeof(struct perf_event_attr), \
+ .config = PERF_COUNT_HW_CPU_CYCLES, \
+ .disabled = 1, \
+ .exclude_kernel = 1, \
+ .exclude_hv = 1, \
+ }; \
+ linux_perf_fd = syscall(__NR_perf_event_open, &attr, \
+ 0, -1, -1, 0); \
+ } \
+ if (linux_perf_fd == -1) { \
+ av_log(NULL, AV_LOG_ERROR, "perf_event_open failed: %s\n", \
+ av_err2str(AVERROR(errno))); \
+ } else { \
+ ioctl(linux_perf_fd, PERF_EVENT_IOC_RESET, 0); \
+ ioctl(linux_perf_fd, PERF_EVENT_IOC_ENABLE, 0); \
+ }
+
+#define STOP_TIMER(id) \
+ ioctl(linux_perf_fd, PERF_EVENT_IOC_DISABLE, 0); \
+ read(linux_perf_fd, &tperf, sizeof(tperf)); \
+ TIMER_REPORT(id, tperf)
+
+#elif defined(AV_READ_TIME)
+#define START_TIMER \
+ uint64_t tend; \
+ uint64_t tstart = AV_READ_TIME(); \
+
+#define STOP_TIMER(id) \
+ tend = AV_READ_TIME(); \
+ TIMER_REPORT(id, tend - tstart)
#else
#define START_TIMER
#define STOP_TIMER(id) { }
diff --git a/media/ffvpx/libavutil/utils.c b/media/ffvpx/libavutil/utils.c
index 36e4dd5fd..2c170db2e 100644
--- a/media/ffvpx/libavutil/utils.c
+++ b/media/ffvpx/libavutil/utils.c
@@ -121,6 +121,29 @@ unsigned av_int_list_length_for_size(unsigned elsize,
return i;
}
+char *av_fourcc_make_string(char *buf, uint32_t fourcc)
+{
+ int i;
+ char *orig_buf = buf;
+ size_t buf_size = AV_FOURCC_MAX_STRING_SIZE;
+
+ for (i = 0; i < 4; i++) {
+ const int c = fourcc & 0xff;
+ const int print_chr = (c >= '0' && c <= '9') ||
+ (c >= 'a' && c <= 'z') ||
+ (c >= 'A' && c <= 'Z') ||
+ (c && strchr(". -_", c));
+ const int len = snprintf(buf, buf_size, print_chr ? "%c" : "[%d]", c);
+ if (len < 0)
+ break;
+ buf += len;
+ buf_size = buf_size > len ? buf_size - len : 0;
+ fourcc >>= 8;
+ }
+
+ return orig_buf;
+}
+
AVRational av_get_time_base_q(void)
{
return (AVRational){1, AV_TIME_BASE};
@@ -129,7 +152,7 @@ AVRational av_get_time_base_q(void)
void av_assert0_fpu(void) {
#if HAVE_MMX_INLINE
uint16_t state[14];
- __asm volatile (
+ __asm__ volatile (
"fstenv %0 \n\t"
: "+m" (state)
:
diff --git a/media/ffvpx/libavutil/version.h b/media/ffvpx/libavutil/version.h
index bdd310f85..f594dc069 100644
--- a/media/ffvpx/libavutil/version.h
+++ b/media/ffvpx/libavutil/version.h
@@ -78,8 +78,9 @@
* @{
*/
+
#define LIBAVUTIL_VERSION_MAJOR 55
-#define LIBAVUTIL_VERSION_MINOR 34
+#define LIBAVUTIL_VERSION_MINOR 78
#define LIBAVUTIL_VERSION_MICRO 100
#define LIBAVUTIL_VERSION_INT AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
@@ -135,6 +136,9 @@
#ifndef FF_API_PKT_PTS
#define FF_API_PKT_PTS (LIBAVUTIL_VERSION_MAJOR < 56)
#endif
+#ifndef FF_API_CRYPTO_SIZE_T
+#define FF_API_CRYPTO_SIZE_T (LIBAVUTIL_VERSION_MAJOR < 56)
+#endif
/**
diff --git a/media/ffvpx/libavutil/x86/cpu.c b/media/ffvpx/libavutil/x86/cpu.c
index f3a49c677..f33088c8c 100644
--- a/media/ffvpx/libavutil/x86/cpu.c
+++ b/media/ffvpx/libavutil/x86/cpu.c
@@ -28,7 +28,7 @@
#include "libavutil/cpu.h"
#include "libavutil/cpu_internal.h"
-#if HAVE_YASM
+#if HAVE_X86ASM
#define cpuid(index, eax, ebx, ecx, edx) \
ff_cpu_cpuid(index, &eax, &ebx, &ecx, &edx)
@@ -66,7 +66,7 @@
#define cpuid_test() 1
-#elif HAVE_YASM
+#elif HAVE_X86ASM
#define cpuid_test ff_cpu_cpuid_test
@@ -221,9 +221,42 @@ int ff_get_cpu_flags_x86(void)
* functions on the Atom. */
if (family == 6 && model == 28)
rval |= AV_CPU_FLAG_ATOM;
+
+ /* Conroe has a slow shuffle unit. Check the model number to ensure not
+ * to include crippled low-end Penryns and Nehalems that lack SSE4. */
+ if ((rval & AV_CPU_FLAG_SSSE3) && !(rval & AV_CPU_FLAG_SSE4) &&
+ family == 6 && model < 23)
+ rval |= AV_CPU_FLAG_SSSE3SLOW;
}
#endif /* cpuid */
return rval;
}
+
+size_t ff_get_cpu_max_align_x86(void)
+{
+ int flags = av_get_cpu_flags();
+
+ if (flags & (AV_CPU_FLAG_AVX2 |
+ AV_CPU_FLAG_AVX |
+ AV_CPU_FLAG_XOP |
+ AV_CPU_FLAG_FMA4 |
+ AV_CPU_FLAG_FMA3 |
+ AV_CPU_FLAG_AVXSLOW))
+ return 32;
+ if (flags & (AV_CPU_FLAG_AESNI |
+ AV_CPU_FLAG_SSE42 |
+ AV_CPU_FLAG_SSE4 |
+ AV_CPU_FLAG_SSSE3 |
+ AV_CPU_FLAG_SSE3 |
+ AV_CPU_FLAG_SSE2 |
+ AV_CPU_FLAG_SSE |
+ AV_CPU_FLAG_ATOM |
+ AV_CPU_FLAG_SSSE3SLOW |
+ AV_CPU_FLAG_SSE3SLOW |
+ AV_CPU_FLAG_SSE2SLOW))
+ return 16;
+
+ return 8;
+}
diff --git a/media/ffvpx/libavutil/x86/cpu.h b/media/ffvpx/libavutil/x86/cpu.h
index f171037f1..309b8e746 100644
--- a/media/ffvpx/libavutil/x86/cpu.h
+++ b/media/ffvpx/libavutil/x86/cpu.h
@@ -38,6 +38,8 @@
#define X86_SSE3_FAST(flags) CPUEXT_FAST(flags, SSE3)
#define X86_SSE3_SLOW(flags) CPUEXT_SLOW(flags, SSE3)
#define X86_SSSE3(flags) CPUEXT(flags, SSSE3)
+#define X86_SSSE3_FAST(flags) CPUEXT_FAST(flags, SSSE3)
+#define X86_SSSE3_SLOW(flags) CPUEXT_SLOW(flags, SSSE3)
#define X86_SSE4(flags) CPUEXT(flags, SSE4)
#define X86_SSE42(flags) CPUEXT(flags, SSE42)
#define X86_AVX(flags) CPUEXT(flags, AVX)
@@ -61,6 +63,8 @@
#define EXTERNAL_SSE3_FAST(flags) CPUEXT_SUFFIX_FAST(flags, _EXTERNAL, SSE3)
#define EXTERNAL_SSE3_SLOW(flags) CPUEXT_SUFFIX_SLOW(flags, _EXTERNAL, SSE3)
#define EXTERNAL_SSSE3(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, SSSE3)
+#define EXTERNAL_SSSE3_FAST(flags) CPUEXT_SUFFIX_FAST(flags, _EXTERNAL, SSSE3)
+#define EXTERNAL_SSSE3_SLOW(flags) CPUEXT_SUFFIX_SLOW(flags, _EXTERNAL, SSSE3)
#define EXTERNAL_SSE4(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, SSE4)
#define EXTERNAL_SSE42(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, SSE42)
#define EXTERNAL_AVX(flags) CPUEXT_SUFFIX(flags, _EXTERNAL, AVX)
@@ -88,6 +92,8 @@
#define INLINE_SSE3_FAST(flags) CPUEXT_SUFFIX_FAST(flags, _INLINE, SSE3)
#define INLINE_SSE3_SLOW(flags) CPUEXT_SUFFIX_SLOW(flags, _INLINE, SSE3)
#define INLINE_SSSE3(flags) CPUEXT_SUFFIX(flags, _INLINE, SSSE3)
+#define INLINE_SSSE3_FAST(flags) CPUEXT_SUFFIX_FAST(flags, _INLINE, SSSE3)
+#define INLINE_SSSE3_SLOW(flags) CPUEXT_SUFFIX_SLOW(flags, _INLINE, SSSE3)
#define INLINE_SSE4(flags) CPUEXT_SUFFIX(flags, _INLINE, SSE4)
#define INLINE_SSE42(flags) CPUEXT_SUFFIX(flags, _INLINE, SSE42)
#define INLINE_AVX(flags) CPUEXT_SUFFIX(flags, _INLINE, AVX)
diff --git a/media/ffvpx/libavutil/x86/emms.asm b/media/ffvpx/libavutil/x86/emms.asm
index 0aad34af3..8611762d7 100644
--- a/media/ffvpx/libavutil/x86/emms.asm
+++ b/media/ffvpx/libavutil/x86/emms.asm
@@ -23,8 +23,8 @@
SECTION .text
;-----------------------------------------------------------------------------
-; void avpriv_emms_yasm(void)
+; void avpriv_emms_asm(void)
;-----------------------------------------------------------------------------
-cvisible emms_yasm, 0, 0
+cvisible emms_asm, 0, 0
emms
RET
diff --git a/media/ffvpx/libavutil/x86/emms.h b/media/ffvpx/libavutil/x86/emms.h
index 42c18e295..c21e34b45 100644
--- a/media/ffvpx/libavutil/x86/emms.h
+++ b/media/ffvpx/libavutil/x86/emms.h
@@ -23,7 +23,7 @@
#include "libavutil/attributes.h"
#include "libavutil/cpu.h"
-void avpriv_emms_yasm(void);
+void avpriv_emms_asm(void);
#if HAVE_MMX_INLINE
# define emms_c emms_c
@@ -49,7 +49,7 @@ static av_always_inline void emms_c(void)
# include <mmintrin.h>
# define emms_c _mm_empty
#elif HAVE_MMX_EXTERNAL
-# define emms_c avpriv_emms_yasm
+# define emms_c avpriv_emms_asm
#endif /* HAVE_MMX_INLINE */
#endif /* AVUTIL_X86_EMMS_H */
diff --git a/media/ffvpx/libavutil/x86/float_dsp.asm b/media/ffvpx/libavutil/x86/float_dsp.asm
index 021ff03c8..06d2d2cfd 100644
--- a/media/ffvpx/libavutil/x86/float_dsp.asm
+++ b/media/ffvpx/libavutil/x86/float_dsp.asm
@@ -22,6 +22,9 @@
%include "x86util.asm"
+SECTION_RODATA 32
+pd_reverse: dd 7, 6, 5, 4, 3, 2, 1, 0
+
SECTION .text
;-----------------------------------------------------------------------------
@@ -149,6 +152,69 @@ INIT_XMM sse
VECTOR_FMUL_SCALAR
;------------------------------------------------------------------------------
+; void ff_vector_dmac_scalar(double *dst, const double *src, double mul,
+; int len)
+;------------------------------------------------------------------------------
+
+%macro VECTOR_DMAC_SCALAR 0
+%if ARCH_X86_32
+cglobal vector_dmac_scalar, 2,4,5, dst, src, mul, len, lenaddr
+ mov lenq, lenaddrm
+ VBROADCASTSD m0, mulm
+%else
+%if UNIX64
+cglobal vector_dmac_scalar, 3,3,5, dst, src, len
+%else
+cglobal vector_dmac_scalar, 4,4,5, dst, src, mul, len
+ SWAP 0, 2
+%endif
+ movlhps xm0, xm0
+%if cpuflag(avx)
+ vinsertf128 m0, m0, xm0, 1
+%endif
+%endif
+ lea lenq, [lend*8-mmsize*4]
+.loop:
+%if cpuflag(fma3)
+ movaps m1, [dstq+lenq]
+ movaps m2, [dstq+lenq+1*mmsize]
+ movaps m3, [dstq+lenq+2*mmsize]
+ movaps m4, [dstq+lenq+3*mmsize]
+ fmaddpd m1, m0, [srcq+lenq], m1
+ fmaddpd m2, m0, [srcq+lenq+1*mmsize], m2
+ fmaddpd m3, m0, [srcq+lenq+2*mmsize], m3
+ fmaddpd m4, m0, [srcq+lenq+3*mmsize], m4
+%else ; cpuflag
+ mulpd m1, m0, [srcq+lenq]
+ mulpd m2, m0, [srcq+lenq+1*mmsize]
+ mulpd m3, m0, [srcq+lenq+2*mmsize]
+ mulpd m4, m0, [srcq+lenq+3*mmsize]
+ addpd m1, m1, [dstq+lenq]
+ addpd m2, m2, [dstq+lenq+1*mmsize]
+ addpd m3, m3, [dstq+lenq+2*mmsize]
+ addpd m4, m4, [dstq+lenq+3*mmsize]
+%endif ; cpuflag
+ movaps [dstq+lenq], m1
+ movaps [dstq+lenq+1*mmsize], m2
+ movaps [dstq+lenq+2*mmsize], m3
+ movaps [dstq+lenq+3*mmsize], m4
+ sub lenq, mmsize*4
+ jge .loop
+ REP_RET
+%endmacro
+
+INIT_XMM sse2
+VECTOR_DMAC_SCALAR
+%if HAVE_AVX_EXTERNAL
+INIT_YMM avx
+VECTOR_DMAC_SCALAR
+%endif
+%if HAVE_FMA3_EXTERNAL
+INIT_YMM fma3
+VECTOR_DMAC_SCALAR
+%endif
+
+;------------------------------------------------------------------------------
; void ff_vector_dmul_scalar(double *dst, const double *src, double mul,
; int len)
;------------------------------------------------------------------------------
@@ -177,8 +243,8 @@ cglobal vector_dmul_scalar, 4,4,3, dst, src, mul, len
.loop:
mulpd m1, m0, [srcq+lenq ]
mulpd m2, m0, [srcq+lenq+mmsize]
- mova [dstq+lenq ], m1
- mova [dstq+lenq+mmsize], m2
+ movaps [dstq+lenq ], m1
+ movaps [dstq+lenq+mmsize], m2
sub lenq, 2*mmsize
jge .loop
REP_RET
@@ -296,10 +362,16 @@ VECTOR_FMUL_ADD
;-----------------------------------------------------------------------------
%macro VECTOR_FMUL_REVERSE 0
cglobal vector_fmul_reverse, 4,4,2, dst, src0, src1, len
+%if cpuflag(avx2)
+ movaps m2, [pd_reverse]
+%endif
lea lenq, [lend*4 - 2*mmsize]
ALIGN 16
.loop:
-%if cpuflag(avx)
+%if cpuflag(avx2)
+ vpermps m0, m2, [src1q]
+ vpermps m1, m2, [src1q+mmsize]
+%elif cpuflag(avx)
vmovaps xmm0, [src1q + 16]
vinsertf128 m0, m0, [src1q], 1
vshufps m0, m0, m0, q0123
@@ -314,8 +386,8 @@ ALIGN 16
%endif
mulps m0, m0, [src0q + lenq + mmsize]
mulps m1, m1, [src0q + lenq]
- mova [dstq + lenq + mmsize], m0
- mova [dstq + lenq], m1
+ movaps [dstq + lenq + mmsize], m0
+ movaps [dstq + lenq], m1
add src1q, 2*mmsize
sub lenq, 2*mmsize
jge .loop
@@ -328,6 +400,10 @@ VECTOR_FMUL_REVERSE
INIT_YMM avx
VECTOR_FMUL_REVERSE
%endif
+%if HAVE_AVX2_EXTERNAL
+INIT_YMM avx2
+VECTOR_FMUL_REVERSE
+%endif
; float scalarproduct_float_sse(const float *v1, const float *v2, int len)
INIT_XMM sse
diff --git a/media/ffvpx/libavutil/x86/float_dsp_init.c b/media/ffvpx/libavutil/x86/float_dsp_init.c
index c836a78e1..122087a19 100644
--- a/media/ffvpx/libavutil/x86/float_dsp_init.c
+++ b/media/ffvpx/libavutil/x86/float_dsp_init.c
@@ -39,6 +39,13 @@ void ff_vector_fmac_scalar_fma3(float *dst, const float *src, float mul,
void ff_vector_fmul_scalar_sse(float *dst, const float *src, float mul,
int len);
+void ff_vector_dmac_scalar_sse2(double *dst, const double *src, double mul,
+ int len);
+void ff_vector_dmac_scalar_avx(double *dst, const double *src, double mul,
+ int len);
+void ff_vector_dmac_scalar_fma3(double *dst, const double *src, double mul,
+ int len);
+
void ff_vector_dmul_scalar_sse2(double *dst, const double *src,
double mul, int len);
void ff_vector_dmul_scalar_avx(double *dst, const double *src,
@@ -60,10 +67,12 @@ void ff_vector_fmul_reverse_sse(float *dst, const float *src0,
const float *src1, int len);
void ff_vector_fmul_reverse_avx(float *dst, const float *src0,
const float *src1, int len);
+void ff_vector_fmul_reverse_avx2(float *dst, const float *src0,
+ const float *src1, int len);
float ff_scalarproduct_float_sse(const float *v1, const float *v2, int order);
-void ff_butterflies_float_sse(float *src0, float *src1, int len);
+void ff_butterflies_float_sse(float *av_restrict src0, float *av_restrict src1, int len);
av_cold void ff_float_dsp_init_x86(AVFloatDSPContext *fdsp)
{
@@ -83,17 +92,23 @@ av_cold void ff_float_dsp_init_x86(AVFloatDSPContext *fdsp)
fdsp->butterflies_float = ff_butterflies_float_sse;
}
if (EXTERNAL_SSE2(cpu_flags)) {
+ fdsp->vector_dmac_scalar = ff_vector_dmac_scalar_sse2;
fdsp->vector_dmul_scalar = ff_vector_dmul_scalar_sse2;
}
if (EXTERNAL_AVX_FAST(cpu_flags)) {
fdsp->vector_fmul = ff_vector_fmul_avx;
fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_avx;
fdsp->vector_dmul_scalar = ff_vector_dmul_scalar_avx;
+ fdsp->vector_dmac_scalar = ff_vector_dmac_scalar_avx;
fdsp->vector_fmul_add = ff_vector_fmul_add_avx;
fdsp->vector_fmul_reverse = ff_vector_fmul_reverse_avx;
}
+ if (EXTERNAL_AVX2_FAST(cpu_flags)) {
+ fdsp->vector_fmul_reverse = ff_vector_fmul_reverse_avx2;
+ }
if (EXTERNAL_FMA3_FAST(cpu_flags)) {
fdsp->vector_fmac_scalar = ff_vector_fmac_scalar_fma3;
fdsp->vector_fmul_add = ff_vector_fmul_add_fma3;
+ fdsp->vector_dmac_scalar = ff_vector_dmac_scalar_fma3;
}
}
diff --git a/media/ffvpx/libavutil/x86/imgutils.asm b/media/ffvpx/libavutil/x86/imgutils.asm
new file mode 100644
index 000000000..3cca56cdc
--- /dev/null
+++ b/media/ffvpx/libavutil/x86/imgutils.asm
@@ -0,0 +1,53 @@
+;*****************************************************************************
+;* Copyright 2016 Anton Khirnov
+;*
+;* This file is part of FFmpeg.
+;*
+;* FFmpeg is free software; you can redistribute it and/or
+;* modify it under the terms of the GNU Lesser General Public
+;* License as published by the Free Software Foundation; either
+;* version 2.1 of the License, or (at your option) any later version.
+;*
+;* FFmpeg 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
+;* Lesser General Public License for more details.
+;*
+;* You should have received a copy of the GNU Lesser General Public
+;* License along with FFmpeg; if not, write to the Free Software
+;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+;******************************************************************************
+
+%include "libavutil/x86/x86util.asm"
+
+SECTION .text
+
+INIT_XMM sse4
+cglobal image_copy_plane_uc_from, 6, 7, 4, dst, dst_linesize, src, src_linesize, bw, height, rowpos
+ add dstq, bwq
+ add srcq, bwq
+ neg bwq
+
+.row_start:
+ mov rowposq, bwq
+
+.loop:
+ movntdqa m0, [srcq + rowposq + 0 * mmsize]
+ movntdqa m1, [srcq + rowposq + 1 * mmsize]
+ movntdqa m2, [srcq + rowposq + 2 * mmsize]
+ movntdqa m3, [srcq + rowposq + 3 * mmsize]
+
+ mova [dstq + rowposq + 0 * mmsize], m0
+ mova [dstq + rowposq + 1 * mmsize], m1
+ mova [dstq + rowposq + 2 * mmsize], m2
+ mova [dstq + rowposq + 3 * mmsize], m3
+
+ add rowposq, 4 * mmsize
+ jnz .loop
+
+ add srcq, src_linesizeq
+ add dstq, dst_linesizeq
+ dec heightd
+ jnz .row_start
+
+ RET
diff --git a/media/ffvpx/libavutil/x86/imgutils_init.c b/media/ffvpx/libavutil/x86/imgutils_init.c
new file mode 100644
index 000000000..4ea398205
--- /dev/null
+++ b/media/ffvpx/libavutil/x86/imgutils_init.c
@@ -0,0 +1,49 @@
+/*
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "libavutil/cpu.h"
+#include "libavutil/error.h"
+#include "libavutil/imgutils.h"
+#include "libavutil/imgutils_internal.h"
+#include "libavutil/internal.h"
+
+#include "cpu.h"
+
+void ff_image_copy_plane_uc_from_sse4(uint8_t *dst, ptrdiff_t dst_linesize,
+ const uint8_t *src, ptrdiff_t src_linesize,
+ ptrdiff_t bytewidth, int height);
+
+int ff_image_copy_plane_uc_from_x86(uint8_t *dst, ptrdiff_t dst_linesize,
+ const uint8_t *src, ptrdiff_t src_linesize,
+ ptrdiff_t bytewidth, int height)
+{
+ int cpu_flags = av_get_cpu_flags();
+ ptrdiff_t bw_aligned = FFALIGN(bytewidth, 64);
+
+ if (EXTERNAL_SSE4(cpu_flags) &&
+ bw_aligned <= dst_linesize && bw_aligned <= src_linesize)
+ ff_image_copy_plane_uc_from_sse4(dst, dst_linesize, src, src_linesize,
+ bw_aligned, height);
+ else
+ return AVERROR(ENOSYS);
+
+ return 0;
+}
diff --git a/media/ffvpx/libavutil/x86/moz.build b/media/ffvpx/libavutil/x86/moz.build
index 1d1a6ca67..b56ed75ea 100644
--- a/media/ffvpx/libavutil/x86/moz.build
+++ b/media/ffvpx/libavutil/x86/moz.build
@@ -12,6 +12,8 @@ SOURCES += [
'fixed_dsp_init.c',
'float_dsp.asm',
'float_dsp_init.c',
+ 'imgutils.asm',
+ 'imgutils_init.c',
'lls.asm',
'lls_init.c'
]
diff --git a/media/ffvpx/libavutil/x86/x86inc.asm b/media/ffvpx/libavutil/x86/x86inc.asm
index b2e9c6019..6a054a3e0 100644
--- a/media/ffvpx/libavutil/x86/x86inc.asm
+++ b/media/ffvpx/libavutil/x86/x86inc.asm
@@ -1,7 +1,7 @@
;*****************************************************************************
;* x86inc.asm: x264asm abstraction layer
;*****************************************************************************
-;* Copyright (C) 2005-2016 x264 project
+;* Copyright (C) 2005-2017 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;* Anton Mitrofanov <BugMaster@narod.ru>
@@ -87,7 +87,9 @@
; keep supporting OS/2.
%macro SECTION_RODATA 0-1 16
%ifidn __OUTPUT_FORMAT__,aout
- section .text
+ SECTION .text
+ %elifidn __OUTPUT_FORMAT__,coff
+ SECTION .text
%else
SECTION .rodata align=%1
%endif
@@ -385,7 +387,14 @@ DECLARE_REG_TMP_SIZE 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14
%ifnum %1
%if %1 != 0 && required_stack_alignment > STACK_ALIGNMENT
%if %1 > 0
+ ; Reserve an additional register for storing the original stack pointer, but avoid using
+ ; eax/rax for this purpose since it can potentially get overwritten as a return value.
%assign regs_used (regs_used + 1)
+ %if ARCH_X86_64 && regs_used == 7
+ %assign regs_used 8
+ %elif ARCH_X86_64 == 0 && regs_used == 1
+ %assign regs_used 2
+ %endif
%endif
%if ARCH_X86_64 && regs_used < 5 + UNIX64 * 3
; Ensure that we don't clobber any registers containing arguments. For UNIX64 we also preserve r6 (rax)
@@ -419,10 +428,10 @@ DECLARE_REG 7, rdi, 64
DECLARE_REG 8, rsi, 72
DECLARE_REG 9, rbx, 80
DECLARE_REG 10, rbp, 88
-DECLARE_REG 11, R12, 96
-DECLARE_REG 12, R13, 104
-DECLARE_REG 13, R14, 112
-DECLARE_REG 14, R15, 120
+DECLARE_REG 11, R14, 96
+DECLARE_REG 12, R15, 104
+DECLARE_REG 13, R12, 112
+DECLARE_REG 14, R13, 120
%macro PROLOGUE 2-5+ 0 ; #args, #regs, #xmm_regs, [stack_size,] arg_names...
%assign num_args %1
@@ -468,41 +477,42 @@ DECLARE_REG 14, R15, 120
WIN64_PUSH_XMM
%endmacro
-%macro WIN64_RESTORE_XMM_INTERNAL 1
+%macro WIN64_RESTORE_XMM_INTERNAL 0
%assign %%pad_size 0
%if xmm_regs_used > 8
%assign %%i xmm_regs_used
%rep xmm_regs_used-8
%assign %%i %%i-1
- movaps xmm %+ %%i, [%1 + (%%i-8)*16 + stack_size + 32]
+ movaps xmm %+ %%i, [rsp + (%%i-8)*16 + stack_size + 32]
%endrep
%endif
%if stack_size_padded > 0
%if stack_size > 0 && required_stack_alignment > STACK_ALIGNMENT
mov rsp, rstkm
%else
- add %1, stack_size_padded
+ add rsp, stack_size_padded
%assign %%pad_size stack_size_padded
%endif
%endif
%if xmm_regs_used > 7
- movaps xmm7, [%1 + stack_offset - %%pad_size + 24]
+ movaps xmm7, [rsp + stack_offset - %%pad_size + 24]
%endif
%if xmm_regs_used > 6
- movaps xmm6, [%1 + stack_offset - %%pad_size + 8]
+ movaps xmm6, [rsp + stack_offset - %%pad_size + 8]
%endif
%endmacro
-%macro WIN64_RESTORE_XMM 1
- WIN64_RESTORE_XMM_INTERNAL %1
+%macro WIN64_RESTORE_XMM 0
+ WIN64_RESTORE_XMM_INTERNAL
%assign stack_offset (stack_offset-stack_size_padded)
+ %assign stack_size_padded 0
%assign xmm_regs_used 0
%endmacro
%define has_epilogue regs_used > 7 || xmm_regs_used > 6 || mmsize == 32 || stack_size > 0
%macro RET 0
- WIN64_RESTORE_XMM_INTERNAL rsp
+ WIN64_RESTORE_XMM_INTERNAL
POP_IF_USED 14, 13, 12, 11, 10, 9, 8, 7
%if mmsize == 32
vzeroupper
@@ -523,10 +533,10 @@ DECLARE_REG 7, R10, 16
DECLARE_REG 8, R11, 24
DECLARE_REG 9, rbx, 32
DECLARE_REG 10, rbp, 40
-DECLARE_REG 11, R12, 48
-DECLARE_REG 12, R13, 56
-DECLARE_REG 13, R14, 64
-DECLARE_REG 14, R15, 72
+DECLARE_REG 11, R14, 48
+DECLARE_REG 12, R15, 56
+DECLARE_REG 13, R12, 64
+DECLARE_REG 14, R13, 72
%macro PROLOGUE 2-5+ ; #args, #regs, #xmm_regs, [stack_size,] arg_names...
%assign num_args %1
@@ -618,7 +628,7 @@ DECLARE_ARG 7, 8, 9, 10, 11, 12, 13, 14
%if WIN64 == 0
%macro WIN64_SPILL_XMM 1
%endmacro
- %macro WIN64_RESTORE_XMM 1
+ %macro WIN64_RESTORE_XMM 0
%endmacro
%macro WIN64_PUSH_XMM 0
%endmacro
@@ -629,7 +639,7 @@ DECLARE_ARG 7, 8, 9, 10, 11, 12, 13, 14
; We can automatically detect "follows a branch", but not a branch target.
; (SSSE3 is a sufficient condition to know that your cpu doesn't have this problem.)
%macro REP_RET 0
- %if has_epilogue
+ %if has_epilogue || cpuflag(ssse3)
RET
%else
rep ret
@@ -780,25 +790,25 @@ BRANCH_INSTR jz, je, jnz, jne, jl, jle, jnl, jnle, jg, jge, jng, jnge, ja, jae,
%assign cpuflags_sse (1<<4) | cpuflags_mmx2
%assign cpuflags_sse2 (1<<5) | cpuflags_sse
%assign cpuflags_sse2slow (1<<6) | cpuflags_sse2
-%assign cpuflags_sse3 (1<<7) | cpuflags_sse2
-%assign cpuflags_ssse3 (1<<8) | cpuflags_sse3
-%assign cpuflags_sse4 (1<<9) | cpuflags_ssse3
-%assign cpuflags_sse42 (1<<10)| cpuflags_sse4
-%assign cpuflags_avx (1<<11)| cpuflags_sse42
-%assign cpuflags_xop (1<<12)| cpuflags_avx
-%assign cpuflags_fma4 (1<<13)| cpuflags_avx
-%assign cpuflags_fma3 (1<<14)| cpuflags_avx
-%assign cpuflags_avx2 (1<<15)| cpuflags_fma3
-
-%assign cpuflags_cache32 (1<<16)
-%assign cpuflags_cache64 (1<<17)
-%assign cpuflags_slowctz (1<<18)
-%assign cpuflags_lzcnt (1<<19)
-%assign cpuflags_aligned (1<<20) ; not a cpu feature, but a function variant
-%assign cpuflags_atom (1<<21)
-%assign cpuflags_bmi1 (1<<22)|cpuflags_lzcnt
-%assign cpuflags_bmi2 (1<<23)|cpuflags_bmi1
-%assign cpuflags_aesni (1<<24)|cpuflags_sse42
+%assign cpuflags_lzcnt (1<<7) | cpuflags_sse2
+%assign cpuflags_sse3 (1<<8) | cpuflags_sse2
+%assign cpuflags_ssse3 (1<<9) | cpuflags_sse3
+%assign cpuflags_sse4 (1<<10)| cpuflags_ssse3
+%assign cpuflags_sse42 (1<<11)| cpuflags_sse4
+%assign cpuflags_aesni (1<<12)| cpuflags_sse42
+%assign cpuflags_avx (1<<13)| cpuflags_sse42
+%assign cpuflags_xop (1<<14)| cpuflags_avx
+%assign cpuflags_fma4 (1<<15)| cpuflags_avx
+%assign cpuflags_fma3 (1<<16)| cpuflags_avx
+%assign cpuflags_bmi1 (1<<17)| cpuflags_avx|cpuflags_lzcnt
+%assign cpuflags_bmi2 (1<<18)| cpuflags_bmi1
+%assign cpuflags_avx2 (1<<19)| cpuflags_fma3|cpuflags_bmi2
+
+%assign cpuflags_cache32 (1<<20)
+%assign cpuflags_cache64 (1<<21)
+%assign cpuflags_slowctz (1<<22)
+%assign cpuflags_aligned (1<<23) ; not a cpu feature, but a function variant
+%assign cpuflags_atom (1<<24)
; Returns a boolean value expressing whether or not the specified cpuflag is enabled.
%define cpuflag(x) (((((cpuflags & (cpuflags_ %+ x)) ^ (cpuflags_ %+ x)) - 1) >> 31) & 1)
@@ -1030,7 +1040,11 @@ INIT_XMM
; Append cpuflags to the callee's name iff the appended name is known and the plain name isn't
%macro call 1
- call_internal %1 %+ SUFFIX, %1
+ %ifid %1
+ call_internal %1 %+ SUFFIX, %1
+ %else
+ call %1
+ %endif
%endmacro
%macro call_internal 2
%xdefine %%i %2
diff --git a/media/ffvpx/libavutil/x86/x86util.asm b/media/ffvpx/libavutil/x86/x86util.asm
index 44ed750ae..e1220dfc1 100644
--- a/media/ffvpx/libavutil/x86/x86util.asm
+++ b/media/ffvpx/libavutil/x86/x86util.asm
@@ -29,6 +29,21 @@
%include "libavutil/x86/x86inc.asm"
+; expands to [base],...,[base+7*stride]
+%define PASS8ROWS(base, base3, stride, stride3) \
+ [base], [base + stride], [base + 2*stride], [base3], \
+ [base3 + stride], [base3 + 2*stride], [base3 + stride3], [base3 + stride*4]
+
+; Interleave low src0 with low src1 and store in src0,
+; interleave high src0 with high src1 and store in src1.
+; %1 - types
+; %2 - index of the register with src0
+; %3 - index of the register with src1
+; %4 - index of the register for intermediate results
+; example for %1 - wd: input: src0: x0 x1 x2 x3 z0 z1 z2 z3
+; src1: y0 y1 y2 y3 q0 q1 q2 q3
+; output: src0: x0 y0 x1 y1 x2 y2 x3 y3
+; src1: z0 q0 z1 q1 z2 q2 z3 q3
%macro SBUTTERFLY 4
%ifidn %1, dqqq
vperm2i128 m%4, m%2, m%3, q0301
@@ -56,6 +71,12 @@
SWAP %1, %3, %2
%endmacro
+%macro SBUTTERFLYPD 3
+ movlhps m%3, m%1, m%2
+ movhlps m%2, m%2, m%1
+ SWAP %1, %3
+%endmacro
+
%macro TRANSPOSE4x4B 5
SBUTTERFLY bw, %1, %2, %5
SBUTTERFLY bw, %3, %4, %5
@@ -102,12 +123,9 @@
%macro TRANSPOSE4x4PS 5
SBUTTERFLYPS %1, %2, %5
SBUTTERFLYPS %3, %4, %5
- movlhps m%5, m%1, m%3
- movhlps m%3, m%1
- SWAP %5, %1
- movlhps m%5, m%2, m%4
- movhlps m%4, m%2
- SWAP %5, %2, %3
+ SBUTTERFLYPD %1, %3, %5
+ SBUTTERFLYPD %2, %4, %5
+ SWAP %2, %3
%endmacro
%macro TRANSPOSE8x4D 9-11
@@ -260,6 +278,21 @@
SWAP %12, %15
%endmacro
+%macro TRANSPOSE_8X8B 8
+ %if mmsize == 8
+ %error "This macro does not support mmsize == 8"
+ %endif
+ punpcklbw m%1, m%2
+ punpcklbw m%3, m%4
+ punpcklbw m%5, m%6
+ punpcklbw m%7, m%8
+ TRANSPOSE4x4W %1, %3, %5, %7, %2
+ MOVHL m%2, m%1
+ MOVHL m%4, m%3
+ MOVHL m%6, m%5
+ MOVHL m%8, m%7
+%endmacro
+
; PABSW macro assumes %1 != %2, while ABS1/2 macros work in-place
%macro PABSW 2
%if cpuflag(ssse3)
@@ -799,12 +832,25 @@
pmaxsd %1, %2
%endmacro
-%macro VBROADCASTSS 2 ; dst xmm/ymm, src m32
-%if cpuflag(avx)
- vbroadcastss %1, %2
-%else ; sse
- movss %1, %2
- shufps %1, %1, 0
+%macro VBROADCASTSS 2 ; dst xmm/ymm, src m32/xmm
+%if cpuflag(avx2)
+ vbroadcastss %1, %2
+%elif cpuflag(avx)
+ %ifnum sizeof%2 ; avx1 register
+ shufps xmm%1, xmm%2, xmm%2, q0000
+ %if sizeof%1 >= 32 ; mmsize>=32
+ vinsertf128 %1, %1, xmm%1, 1
+ %endif
+ %else ; avx1 memory
+ vbroadcastss %1, %2
+ %endif
+%else
+ %ifnum sizeof%2 ; sse register
+ shufps %1, %2, %2, q0000
+ %else ; sse memory
+ movss %1, %2
+ shufps %1, %1, 0
+ %endif
%endif
%endmacro
@@ -819,6 +865,21 @@
%endif
%endmacro
+%macro VPBROADCASTD 2 ; dst xmm/ymm, src m32/xmm
+%if cpuflag(avx2)
+ vpbroadcastd %1, %2
+%elif cpuflag(avx) && sizeof%1 >= 32
+ %error vpbroadcastd not possible with ymm on avx1. try vbroadcastss
+%else
+ %ifnum sizeof%2 ; sse2 register
+ pshufd %1, %2, q0000
+ %else ; sse memory
+ movd %1, %2
+ pshufd %1, %1, 0
+ %endif
+%endif
+%endmacro
+
%macro SHUFFLE_MASK_W 8
%rep 8
%if %1>=0x80
@@ -871,3 +932,79 @@
psrlq %1, 8*(%2)
%endif
%endmacro
+
+%macro MOVHL 2 ; dst, src
+%ifidn %1, %2
+ punpckhqdq %1, %2
+%elif cpuflag(avx)
+ punpckhqdq %1, %2, %2
+%elif cpuflag(sse4)
+ pshufd %1, %2, q3232 ; pshufd is slow on some older CPUs, so only use it on more modern ones
+%else
+ movhlps %1, %2 ; may cause an int/float domain transition and has a dependency on dst
+%endif
+%endmacro
+
+; Horizontal Sum of Packed Single precision floats
+; The resulting sum is in all elements.
+%macro HSUMPS 2 ; dst/src, tmp
+%if cpuflag(avx)
+ %if sizeof%1>=32 ; avx
+ vperm2f128 %2, %1, %1, (0)*16+(1)
+ addps %1, %2
+ %endif
+ shufps %2, %1, %1, q1032
+ addps %1, %2
+ shufps %2, %1, %1, q0321
+ addps %1, %2
+%else ; this form is a bit faster than the short avx-like emulation.
+ movaps %2, %1
+ shufps %1, %1, q1032
+ addps %1, %2
+ movaps %2, %1
+ shufps %1, %1, q0321
+ addps %1, %2
+ ; all %1 members should be equal for as long as float a+b==b+a
+%endif
+%endmacro
+
+; Emulate blendvps if not available
+;
+; src_b is destroyed when using emulation with logical operands
+; SSE41 blendv instruction is hard coded to use xmm0 as mask
+%macro BLENDVPS 3 ; dst/src_a, src_b, mask
+%if cpuflag(avx)
+ blendvps %1, %1, %2, %3
+%elif cpuflag(sse4)
+ %ifnidn %3,xmm0
+ %error sse41 blendvps uses xmm0 as default 3d operand, you used %3
+ %endif
+ blendvps %1, %2, %3
+%else
+ xorps %2, %1
+ andps %2, %3
+ xorps %1, %2
+%endif
+%endmacro
+
+; Emulate pblendvb if not available
+;
+; src_b is destroyed when using emulation with logical operands
+; SSE41 blendv instruction is hard coded to use xmm0 as mask
+%macro PBLENDVB 3 ; dst/src_a, src_b, mask
+%if cpuflag(avx)
+ %if cpuflag(avx) && notcpuflag(avx2) && sizeof%1 >= 32
+ %error pblendb not possible with ymm on avx1, try blendvps.
+ %endif
+ pblendvb %1, %1, %2, %3
+%elif cpuflag(sse4)
+ %ifnidn %3,xmm0
+ %error sse41 pblendvd uses xmm0 as default 3d operand, you used %3
+ %endif
+ pblendvb %1, %2, %3
+%else
+ pxor %2, %1
+ pand %2, %3
+ pxor %1, %2
+%endif
+%endmacro
diff --git a/media/ffvpx/libavutil_visibility.h b/media/ffvpx/libavutil_visibility.h
index a5cce0844..706aacdf3 100644
--- a/media/ffvpx/libavutil_visibility.h
+++ b/media/ffvpx/libavutil_visibility.h
@@ -9,6 +9,15 @@
#ifndef MOZILLA_AVUTIL_VISIBILITY_H
#define MOZILLA_AVUTIL_VISIBILITY_H
+// We need to preemptively include <stdlib.h> before anyone[1] has a chance
+// to include <limits.h>. We do this to avoid a Linux clang build error, in
+// -ffreestanding mode, which happens when limits.h defines MB_LEN_MAX to some
+// value that is different from what stdlib.h expects. If we include stdlib.h
+// before limits.h, then they don't get a chance to interact badly.
+//
+// [1] (e.g. libavutil/common.h, which is indirectly included by log.h below.)
+#include <stdlib.h>
+
#pragma GCC visibility push(default)
#include "libavutil/cpu.h"
diff --git a/media/libcubeb/src/cubeb_opensl.c b/media/libcubeb/src/cubeb_opensl.c
index d44a56bd7..dd5416228 100644
--- a/media/libcubeb/src/cubeb_opensl.c
+++ b/media/libcubeb/src/cubeb_opensl.c
@@ -187,10 +187,6 @@ static void opensl_destroy(cubeb * ctx);
#if defined(__ANDROID__)
-// The bionic header file on B2G contains the required
-// declarations on all releases.
-#ifndef MOZ_WIDGET_GONK
-
#if (__ANDROID_API__ >= ANDROID_VERSION_LOLLIPOP)
typedef int (system_property_get)(const char*, char*);
@@ -212,7 +208,6 @@ __system_property_get(const char* name, char* value)
return ret;
}
#endif
-#endif
static int
get_android_version(void)
diff --git a/media/libcubeb/src/moz.build b/media/libcubeb/src/moz.build
index 781214620..2ca3a2f54 100644
--- a/media/libcubeb/src/moz.build
+++ b/media/libcubeb/src/moz.build
@@ -29,8 +29,6 @@ if CONFIG['MOZ_PULSEAUDIO']:
'cubeb_pulse.c',
]
DEFINES['USE_PULSE'] = True
- if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DEFINES['DISABLE_LIBPULSE_DLOPEN'] = True
if CONFIG['MOZ_JACK']:
SOURCES += [
@@ -73,24 +71,13 @@ if CONFIG['OS_TARGET'] == 'Android':
SOURCES += ['cubeb_opensl.c']
SOURCES += ['cubeb_resampler.cpp']
DEFINES['USE_OPENSL'] = True
- if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
- SOURCES += [
- 'cubeb_audiotrack.c',
- ]
- DEFINES['USE_AUDIOTRACK'] = True
+ SOURCES += [
+ 'cubeb_audiotrack.c',
+ ]
+ DEFINES['USE_AUDIOTRACK'] = True
FINAL_LIBRARY = 'gkmedias'
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- if CONFIG['ANDROID_VERSION'] >= '17':
- LOCAL_INCLUDES += [
- '%' + '%s/frameworks/wilhelm/include' % CONFIG['ANDROID_SOURCE'],
- ]
- else:
- LOCAL_INCLUDES += [
- '%' + '%s/system/media/wilhelm/include' % CONFIG['ANDROID_SOURCE'],
- ]
-
CFLAGS += CONFIG['MOZ_ALSA_CFLAGS']
CFLAGS += CONFIG['MOZ_PULSEAUDIO_CFLAGS']
diff --git a/media/libpng/pnglibconf.h b/media/libpng/pnglibconf.h
index 3a39f86fa..662e1ce89 100644
--- a/media/libpng/pnglibconf.h
+++ b/media/libpng/pnglibconf.h
@@ -95,19 +95,6 @@
#define PNG_SEQUENTIAL_READ_SUPPORTED
#endif
-/* necessary for boot animation code (Gonk) */
-#ifdef MOZ_WIDGET_GONK
-#define PNG_bKGD_SUPPORTED
-#define PNG_UNKNOWN_CHUNKS_SUPPORTED
-#define PNG_SET_UNKNOWN_CHUNKS_SUPPORTED
-#define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
-#define PNG_EASY_ACCESS_SUPPORTED
-#define PNG_READ_bKGD_SUPPORTED
-#define PNG_READ_BGR_SUPPORTED
-#define PNG_READ_GRAY_TO_RGB_SUPPORTED
-#define PNG_READ_STRIP_ALPHA_SUPPORTED
-#endif
-
#define PNG_WRITE_SUPPORTED
#define PNG_WRITE_APNG_SUPPORTED
#define PNG_WRITE_tRNS_SUPPORTED
diff --git a/media/mtransport/common.build b/media/mtransport/common.build
index 7576ab4fc..4050af366 100644
--- a/media/mtransport/common.build
+++ b/media/mtransport/common.build
@@ -27,11 +27,6 @@ mtransport_lcppsrcs = [
'transportlayerprsock.cpp',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- mtransport_lcppsrcs += [
- 'gonk_addrs.cpp',
- ]
-
mtransport_cppsrcs = [
'/media/mtransport/%s' % s for s in sorted(mtransport_lcppsrcs)
]
diff --git a/media/mtransport/gonk_addrs.cpp b/media/mtransport/gonk_addrs.cpp
deleted file mode 100644
index 1c69b711e..000000000
--- a/media/mtransport/gonk_addrs.cpp
+++ /dev/null
@@ -1,170 +0,0 @@
-/* -*- 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/. */
-extern "C" {
-#include <arpa/inet.h>
-#include "r_types.h"
-#include "stun.h"
-#include "addrs.h"
-}
-
-#include <vector>
-#include <string>
-#include "nsINetworkInterface.h"
-#include "nsINetworkInterfaceListService.h"
-#include "runnable_utils.h"
-#include "nsCOMPtr.h"
-#include "nsMemory.h"
-#include "nsThreadUtils.h"
-#include "nsServiceManagerUtils.h"
-#include "mozilla/SyncRunnable.h"
-
-namespace {
-struct NetworkInterface {
- struct sockaddr_in addr;
- std::string name;
- // See NR_INTERFACE_TYPE_* in nICEr/src/net/local_addrs.h
- int type;
-};
-
-nsresult
-GetInterfaces(std::vector<NetworkInterface>* aInterfaces)
-{
- MOZ_ASSERT(aInterfaces);
-
- // Obtain network interfaces from network manager.
- nsresult rv;
- nsCOMPtr<nsINetworkInterfaceListService> listService =
- do_GetService("@mozilla.org/network/interface-list-service;1", &rv);
- NS_ENSURE_SUCCESS(rv, rv);
-
- int32_t flags =
- nsINetworkInterfaceListService::LIST_NOT_INCLUDE_SUPL_INTERFACES |
- nsINetworkInterfaceListService::LIST_NOT_INCLUDE_MMS_INTERFACES |
- nsINetworkInterfaceListService::LIST_NOT_INCLUDE_IMS_INTERFACES |
- nsINetworkInterfaceListService::LIST_NOT_INCLUDE_DUN_INTERFACES |
- nsINetworkInterfaceListService::LIST_NOT_INCLUDE_FOTA_INTERFACES;
- nsCOMPtr<nsINetworkInterfaceList> networkList;
- NS_ENSURE_SUCCESS(listService->GetDataInterfaceList(flags,
- getter_AddRefs(networkList)),
- NS_ERROR_FAILURE);
-
- // Translate nsINetworkInterfaceList to NetworkInterface.
- int32_t listLength;
- NS_ENSURE_SUCCESS(networkList->GetNumberOfInterface(&listLength),
- NS_ERROR_FAILURE);
- aInterfaces->clear();
-
- for (int32_t i = 0; i < listLength; i++) {
- nsCOMPtr<nsINetworkInfo> info;
- if (NS_FAILED(networkList->GetInterfaceInfo(i, getter_AddRefs(info)))) {
- continue;
- }
-
- char16_t **ips = nullptr;
- uint32_t *prefixs = nullptr;
- uint32_t count = 0;
- bool isAddressGot = false;
- NetworkInterface interface;
- memset(&(interface.addr), 0, sizeof(interface.addr));
- interface.addr.sin_family = AF_INET;
-
- if (NS_FAILED(info->GetAddresses(&ips, &prefixs, &count))) {
- continue;
- }
-
- for (uint32_t j = 0; j < count; j++) {
- nsAutoString ip;
-
- ip.Assign(ips[j]);
- if (inet_pton(AF_INET, NS_ConvertUTF16toUTF8(ip).get(),
- &(interface.addr.sin_addr.s_addr)) == 1) {
- isAddressGot = true;
- break;
- }
- }
-
- free(prefixs);
- NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(count, ips);
-
- if (!isAddressGot) {
- continue;
- }
-
- nsAutoString ifaceName;
- if (NS_FAILED(info->GetName(ifaceName))) {
- continue;
- }
- interface.name = NS_ConvertUTF16toUTF8(ifaceName).get();
-
- int32_t type;
- if (NS_FAILED(info->GetType(&type))) {
- continue;
- }
- switch (type) {
- case nsINetworkInfo::NETWORK_TYPE_WIFI:
- interface.type = NR_INTERFACE_TYPE_WIFI;
- break;
- case nsINetworkInfo::NETWORK_TYPE_MOBILE:
- interface.type = NR_INTERFACE_TYPE_MOBILE;
- break;
- }
-
- aInterfaces->push_back(interface);
- }
- return NS_OK;
-}
-} // anonymous namespace
-
-int
-nr_stun_get_addrs(nr_local_addr aAddrs[], int aMaxAddrs,
- int aDropLoopback, int aDropLinkLocal, int* aCount)
-{
- nsresult rv;
- int r;
-
- // Get network interface list.
- std::vector<NetworkInterface> interfaces;
- nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
- mozilla::SyncRunnable::DispatchToThread(
- mainThread.get(),
- mozilla::WrapRunnableNMRet(&rv, &GetInterfaces, &interfaces),
- false);
- if (NS_FAILED(rv)) {
- return R_FAILED;
- }
-
- // Translate to nr_transport_addr.
- int32_t n = 0;
- size_t num_interface = std::min(interfaces.size(), (size_t)aMaxAddrs);
- for (size_t i = 0; i < num_interface; ++i) {
- NetworkInterface &interface = interfaces[i];
- if (nr_sockaddr_to_transport_addr((sockaddr*)&(interface.addr),
- IPPROTO_UDP, 0, &(aAddrs[n].addr))) {
- r_log(NR_LOG_STUN, LOG_WARNING, "Problem transforming address");
- return R_FAILED;
- }
- strlcpy(aAddrs[n].addr.ifname, interface.name.c_str(),
- sizeof(aAddrs[n].addr.ifname));
- aAddrs[n].interface.type = interface.type;
- aAddrs[n].interface.estimated_speed = 0;
- n++;
- }
-
- *aCount = n;
- r = nr_stun_remove_duplicate_addrs(aAddrs, aDropLoopback, aDropLinkLocal, aCount);
- if (r != 0) {
- return r;
- }
-
- for (int i = 0; i < *aCount; ++i) {
- char typestr[100];
- nr_local_addr_fmt_info_string(aAddrs + i, typestr, sizeof(typestr));
- r_log(NR_LOG_STUN, LOG_DEBUG, "Address %d: %s on %s, type: %s\n",
- i, aAddrs[i].addr.as_string, aAddrs[i].addr.ifname, typestr);
- }
-
- return 0;
-}
diff --git a/media/mtransport/test/moz.build b/media/mtransport/test/moz.build
index e8f453787..d769e62f2 100644
--- a/media/mtransport/test/moz.build
+++ b/media/mtransport/test/moz.build
@@ -4,7 +4,7 @@
# License, v. 2.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['OS_TARGET'] != 'WINNT' and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
+if CONFIG['OS_TARGET'] != 'WINNT':
SOURCES += [
'buffered_stun_socket_unittest.cpp',
'ice_unittest.cpp',
diff --git a/media/omx-plugin/OmxPlugin.cpp b/media/omx-plugin/OmxPlugin.cpp
index 4b6641c46..ce132b8e2 100644
--- a/media/omx-plugin/OmxPlugin.cpp
+++ b/media/omx-plugin/OmxPlugin.cpp
@@ -10,11 +10,7 @@
#include <stagefright/MetaData.h>
#include <stagefright/OMXCodec.h>
#include <media/stagefright/MediaErrors.h>
-#ifdef MOZ_WIDGET_GONK
-#include <OMX.h>
-#else
#include <stagefright/OMXClient.h>
-#endif
#include <algorithm>
#include "mozilla/Assertions.h"
@@ -125,7 +121,6 @@ public:
bool ReadAudio(AudioFrame *aFrame, int64_t aSeekTimeUs);
};
-#if !defined(MOZ_WIDGET_GONK)
static class OmxClientInstance {
public:
OmxClientInstance()
@@ -156,7 +151,6 @@ private:
OMXClient *mClient;
status_t mStatus;
} sClientInstance;
-#endif
OmxDecoder::OmxDecoder(PluginHost *aPluginHost, Decoder *aDecoder) :
mPluginHost(aPluginHost),
@@ -210,16 +204,6 @@ public:
}
};
-#ifdef MOZ_WIDGET_GONK
-static sp<IOMX> sOMX = nullptr;
-static sp<IOMX> GetOMX() {
- if(sOMX.get() == nullptr) {
- sOMX = reinterpret_cast<IOMX*>(new OMX);
- }
- return sOMX;
-}
-#endif
-
static uint32_t
GetDefaultStagefrightFlags(PluginHost *aPluginHost)
{
@@ -246,11 +230,6 @@ GetDefaultStagefrightFlags(PluginHost *aPluginHost)
static uint32_t GetVideoCreationFlags(PluginHost* aPluginHost)
{
-#ifdef MOZ_WIDGET_GONK
- // Flag value of zero means return a hardware or software decoder
- // depending on what the device supports.
- return 0;
-#else
// Check whether the user has set a pref to override our default OMXCodec
// CreationFlags flags. This is useful for A/B testing hardware and software
// decoders for performance and bugs. The interesting flag values are:
@@ -271,7 +250,6 @@ static uint32_t GetVideoCreationFlags(PluginHost* aPluginHost)
flags |= GetDefaultStagefrightFlags(aPluginHost);
return static_cast<uint32_t>(flags);
-#endif
}
enum ColorFormatSupport {
@@ -481,11 +459,7 @@ bool OmxDecoder::Init()
int64_t totalDurationUs = 0;
-#ifdef MOZ_WIDGET_GONK
- sp<IOMX> omx = GetOMX();
-#else
sp<IOMX> omx = sClientInstance.get()->interface();
-#endif
sp<MediaSource> videoTrack;
sp<MediaSource> videoSource;
diff --git a/media/omx-plugin/lib/ics/libstagefright/moz.build b/media/omx-plugin/lib/ics/libstagefright/moz.build
index 1fe19a5fd..b156d151e 100644
--- a/media/omx-plugin/lib/ics/libstagefright/moz.build
+++ b/media/omx-plugin/lib/ics/libstagefright/moz.build
@@ -5,14 +5,13 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
DIST_INSTALL = False
-if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
- SOURCES += [
- 'libstagefright.cpp',
- ]
- # Some codec-related code uses multi-character constants; allow this.
- # XXX: could instead use the FOURCC macro to define these constants.
- if CONFIG['GNU_CC'] or CONFIG['CLANG_CL']:
- SOURCES['libstagefright.cpp'].flags += ['-Wno-error=multichar']
+SOURCES += [
+ 'libstagefright.cpp',
+]
+# Some codec-related code uses multi-character constants; allow this.
+# XXX: could instead use the FOURCC macro to define these constants.
+if CONFIG['GNU_CC'] or CONFIG['CLANG_CL']:
+ SOURCES['libstagefright.cpp'].flags += ['-Wno-error=multichar']
SharedLibrary('stagefright')
diff --git a/media/omx-plugin/lib/ics/libutils/moz.build b/media/omx-plugin/lib/ics/libutils/moz.build
index efce12194..7fa617fb3 100644
--- a/media/omx-plugin/lib/ics/libutils/moz.build
+++ b/media/omx-plugin/lib/ics/libutils/moz.build
@@ -5,10 +5,9 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
DIST_INSTALL = False
-if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
- SOURCES += [
- 'libutils.cpp',
- ]
+SOURCES += [
+ 'libutils.cpp',
+]
SharedLibrary('utils')
diff --git a/media/omx-plugin/lib/ics/libvideoeditorplayer/moz.build b/media/omx-plugin/lib/ics/libvideoeditorplayer/moz.build
index 4314b1aa2..f05f0f3c9 100644
--- a/media/omx-plugin/lib/ics/libvideoeditorplayer/moz.build
+++ b/media/omx-plugin/lib/ics/libvideoeditorplayer/moz.build
@@ -5,10 +5,9 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
DIST_INSTALL = False
-if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
- SOURCES += [
- 'libvideoeditorplayer.cpp',
- ]
+SOURCES += [
+ 'libvideoeditorplayer.cpp',
+]
SharedLibrary('videoeditorplayer')
diff --git a/media/omx-plugin/moz.build b/media/omx-plugin/moz.build
index 80b8534f2..004a8bdba 100644
--- a/media/omx-plugin/moz.build
+++ b/media/omx-plugin/moz.build
@@ -20,13 +20,10 @@ SOURCES += [
SharedLibrary('omxplugin')
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- pass
-else:
- LOCAL_INCLUDES += [
- 'include/ics',
- 'include/ics/media/stagefright/openmax',
- ]
+LOCAL_INCLUDES += [
+ 'include/ics',
+ 'include/ics/media/stagefright/openmax',
+]
if CONFIG['GNU_CXX']:
# Stagefright header files define many multichar constants.
@@ -35,23 +32,11 @@ if CONFIG['GNU_CXX']:
'-Wno-shadow',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- EXTRA_DSO_LDOPTS += [
- '-lutils',
- '-lstagefright',
- '-lmedia',
- '-lstagefright_omx',
- '-lbinder',
- '-lui',
- '-lhardware',
- '-lcutils',
- ]
-else:
- USE_LIBS += [
- '/media/omx-plugin/lib/ics/libstagefright/stagefright',
- '/media/omx-plugin/lib/ics/libutils/utils',
- 'videoeditorplayer',
- ]
+USE_LIBS += [
+ '/media/omx-plugin/lib/ics/libstagefright/stagefright',
+ '/media/omx-plugin/lib/ics/libutils/utils',
+ 'videoeditorplayer',
+]
# Don't use STL wrappers; this isn't Gecko code
DISABLE_STL_WRAPPING = True
diff --git a/media/webrtc/moz.build b/media/webrtc/moz.build
index 986655c53..4361273b4 100644
--- a/media/webrtc/moz.build
+++ b/media/webrtc/moz.build
@@ -101,22 +101,21 @@ if CONFIG['MOZ_WEBRTC_SIGNALING']:
else:
CXXFLAGS += ['-validate-charset-']
-if CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
- GYP_DIRS += ['trunk/testing']
- GYP_DIRS['trunk/testing'].input = 'trunk/testing/gtest.gyp'
- GYP_DIRS['trunk/testing'].variables = gyp_vars
- # We allow warnings for third-party code that can be updated from upstream.
- GYP_DIRS['trunk/testing'].sandbox_vars['ALLOW_COMPILER_WARNINGS'] = True
- GYP_DIRS['trunk/testing'].non_unified_sources += webrtc_non_unified_sources
+GYP_DIRS += ['trunk/testing']
+GYP_DIRS['trunk/testing'].input = 'trunk/testing/gtest.gyp'
+GYP_DIRS['trunk/testing'].variables = gyp_vars
+# We allow warnings for third-party code that can be updated from upstream.
+GYP_DIRS['trunk/testing'].sandbox_vars['ALLOW_COMPILER_WARNINGS'] = True
+GYP_DIRS['trunk/testing'].non_unified_sources += webrtc_non_unified_sources
- if CONFIG['MOZ_WEBRTC_SIGNALING']:
- GYP_DIRS += ['signalingtest']
- GYP_DIRS['signalingtest'].input = 'signaling/signaling.gyp'
- GYP_DIRS['signalingtest'].variables = gyp_vars.copy()
- GYP_DIRS['signalingtest'].variables.update(
- build_for_test=1,
- moz_webrtc_mediacodec=0,
- build_for_standalone=0
- )
- GYP_DIRS['signalingtest'].sandbox_vars['ALLOW_COMPILER_WARNINGS'] = True
- GYP_DIRS['signalingtest'].non_unified_sources += signaling_non_unified_sources
+if CONFIG['MOZ_WEBRTC_SIGNALING']:
+ GYP_DIRS += ['signalingtest']
+ GYP_DIRS['signalingtest'].input = 'signaling/signaling.gyp'
+ GYP_DIRS['signalingtest'].variables = gyp_vars.copy()
+ GYP_DIRS['signalingtest'].variables.update(
+ build_for_test=1,
+ moz_webrtc_mediacodec=0,
+ build_for_standalone=0
+ )
+ GYP_DIRS['signalingtest'].sandbox_vars['ALLOW_COMPILER_WARNINGS'] = True
+ GYP_DIRS['signalingtest'].non_unified_sources += signaling_non_unified_sources
diff --git a/media/webrtc/signaling/src/media-conduit/WebrtcOMXH264VideoCodec.cpp b/media/webrtc/signaling/src/media-conduit/WebrtcOMXH264VideoCodec.cpp
index dc052f4e0..888b87857 100644
--- a/media/webrtc/signaling/src/media-conduit/WebrtcOMXH264VideoCodec.cpp
+++ b/media/webrtc/signaling/src/media-conduit/WebrtcOMXH264VideoCodec.cpp
@@ -26,9 +26,6 @@ using namespace android;
#include "runnable_utils.h"
// Gecko
-#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 21
-#include "GonkBufferQueueProducer.h"
-#endif
#include "GonkNativeWindow.h"
#include "GrallocImages.h"
#include "mozilla/Atomics.h"
@@ -326,30 +323,16 @@ public:
mHeight = aHeight;
sp<Surface> surface = nullptr;
-#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 21
- sp<IGraphicBufferProducer> producer;
- sp<IGonkGraphicBufferConsumer> consumer;
- GonkBufferQueue::createBufferQueue(&producer, &consumer);
- mNativeWindow = new GonkNativeWindow(consumer);
-#else
mNativeWindow = new GonkNativeWindow();
-#endif
if (mNativeWindow.get()) {
// listen to buffers queued by MediaCodec::RenderOutputBufferAndRelease().
mNativeWindow->setNewFrameCallback(this);
// XXX remove buffer changes after a better solution lands - bug 1009420
-#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 21
- static_cast<GonkBufferQueueProducer*>(producer.get())->setSynchronousMode(false);
- // More spare buffers to avoid OMX decoder waiting for native window
- consumer->setMaxAcquiredBufferCount(WEBRTC_OMX_H264_MIN_DECODE_BUFFERS);
- surface = new Surface(producer);
-#else
sp<GonkBufferQueue> bq = mNativeWindow->getBufferQueue();
bq->setSynchronousMode(false);
// More spare buffers to avoid OMX decoder waiting for native window
bq->setMaxAcquiredBufferCount(WEBRTC_OMX_H264_MIN_DECODE_BUFFERS);
surface = new Surface(bq);
-#endif
}
status_t result = mCodec->configure(config, surface, nullptr, 0);
if (result == OK) {
diff --git a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp
index 586876406..d47a10312 100644
--- a/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp
+++ b/media/webrtc/signaling/src/mediapipeline/MediaPipeline.cpp
@@ -2217,11 +2217,7 @@ public:
#if defined(MOZILLA_INTERNAL_API)
if (buffer) {
// Create a video frame using |buffer|.
-#ifdef MOZ_WIDGET_GONK
- RefPtr<PlanarYCbCrImage> yuvImage = new GrallocImage();
-#else
RefPtr<PlanarYCbCrImage> yuvImage = image_container_->CreatePlanarYCbCrImage();
-#endif
uint8_t* frame = const_cast<uint8_t*>(static_cast<const uint8_t*> (buffer));
PlanarYCbCrData yuvData;
diff --git a/media/webrtc/signaling/test/moz.build b/media/webrtc/signaling/test/moz.build
index 4d8704de4..aac331b1b 100644
--- a/media/webrtc/signaling/test/moz.build
+++ b/media/webrtc/signaling/test/moz.build
@@ -5,7 +5,7 @@
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# TODO: bug 1172551 - get these tests working on iOS
-if CONFIG['OS_TARGET'] != 'WINNT' and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk' and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'uikit':
+if CONFIG['OS_TARGET'] != 'WINNT' and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'uikit':
GeckoCppUnitTests([
'jsep_session_unittest',
'jsep_track_unittest',
diff --git a/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_device_utility_android.h b/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_device_utility_android.h
index fd05a61ad..1c1ce1ca6 100644
--- a/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_device_utility_android.h
+++ b/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_device_utility_android.h
@@ -15,9 +15,7 @@
#ifndef WEBRTC_AUDIO_DEVICE_AUDIO_DEVICE_UTILITY_ANDROID_H
#define WEBRTC_AUDIO_DEVICE_AUDIO_DEVICE_UTILITY_ANDROID_H
-#if !defined(MOZ_WIDGET_GONK)
#include <jni.h>
-#endif
#include "webrtc/base/checks.h"
#include "webrtc/modules/audio_device/audio_device_utility.h"
diff --git a/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.cc b/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.cc
index d0a46afde..5424ba3de 100644
--- a/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.cc
+++ b/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.cc
@@ -9,18 +9,14 @@
*/
#include "webrtc/modules/audio_device/android/audio_manager.h"
-#if !defined(MOZ_WIDGET_GONK)
#include "AndroidJNIWrapper.h"
-#endif
#include <android/log.h>
#include "webrtc/base/arraysize.h"
#include "webrtc/base/checks.h"
#include "webrtc/modules/audio_device/android/audio_common.h"
-#if !defined(MOZ_WIDGET_GONK)
#include "webrtc/modules/utility/interface/helpers_android.h"
-#endif
#define TAG "AudioManager"
#define ALOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__)
@@ -31,14 +27,11 @@
namespace webrtc {
-#if !defined(MOZ_WIDGET_GONK)
static JavaVM* g_jvm = NULL;
static jobject g_context = NULL;
static jclass g_audio_manager_class = NULL;
-#endif
void AudioManager::SetAndroidAudioDeviceObjects(void* jvm, void* context) {
-#if !defined(MOZ_WIDGET_GONK)
ALOGD("SetAndroidAudioDeviceObjects%s", GetThreadInfo().c_str());
CHECK(jvm);
@@ -65,11 +58,9 @@ void AudioManager::SetAndroidAudioDeviceObjects(void* jvm, void* context) {
jni->RegisterNatives(g_audio_manager_class,
native_methods, arraysize(native_methods));
CHECK_EXCEPTION(jni) << "Error during RegisterNatives";
-#endif
}
void AudioManager::ClearAndroidAudioDeviceObjects() {
-#if !defined(MOZ_WIDGET_GONK)
ALOGD("ClearAndroidAudioDeviceObjects%s", GetThreadInfo().c_str());
JNIEnv* jni = GetEnv(g_jvm);
CHECK(jni) << "AttachCurrentThread must be called on this tread";
@@ -80,36 +71,28 @@ void AudioManager::ClearAndroidAudioDeviceObjects() {
DeleteGlobalRef(jni, g_context);
g_context = NULL;
g_jvm = NULL;
-#endif
}
AudioManager::AudioManager()
: initialized_(false) {
-#if !defined(MOZ_WIDGET_GONK)
j_audio_manager_ = NULL;
ALOGD("ctor%s", GetThreadInfo().c_str());
-#endif
CHECK(HasDeviceObjects());
CreateJavaInstance();
}
AudioManager::~AudioManager() {
-#if !defined(MOZ_WIDGET_GONK)
ALOGD("~dtor%s", GetThreadInfo().c_str());
-#endif
DCHECK(thread_checker_.CalledOnValidThread());
Close();
-#if !defined(MOZ_WIDGET_GONK)
AttachThreadScoped ats(g_jvm);
JNIEnv* jni = ats.env();
jni->DeleteGlobalRef(j_audio_manager_);
j_audio_manager_ = NULL;
-#endif
DCHECK(!initialized_);
}
bool AudioManager::Init() {
-#if !defined(MOZ_WIDGET_GONK)
ALOGD("Init%s", GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!initialized_);
@@ -122,13 +105,11 @@ bool AudioManager::Init() {
ALOGE("init failed!");
return false;
}
-#endif
initialized_ = true;
return true;
}
bool AudioManager::Close() {
-#if !defined(MOZ_WIDGET_GONK)
ALOGD("Close%s", GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
if (!initialized_)
@@ -139,12 +120,10 @@ bool AudioManager::Close() {
jni, g_audio_manager_class, "dispose", "()V");
jni->CallVoidMethod(j_audio_manager_, disposeID);
CHECK_EXCEPTION(jni);
-#endif
initialized_ = false;
return true;
}
-#if !defined(MOZ_WIDGET_GONK)
void JNICALL AudioManager::CacheAudioParameters(JNIEnv* env, jobject obj,
jint sample_rate, jint channels, jlong nativeAudioManager) {
webrtc::AudioManager* this_object =
@@ -162,7 +141,6 @@ void AudioManager::OnCacheAudioParameters(
playout_parameters_.reset(sample_rate, channels);
record_parameters_.reset(sample_rate, channels);
}
-#endif
AudioParameters AudioManager::GetPlayoutAudioParameters() const {
CHECK(playout_parameters_.is_valid());
@@ -175,15 +153,10 @@ AudioParameters AudioManager::GetRecordAudioParameters() const {
}
bool AudioManager::HasDeviceObjects() {
-#if !defined(MOZ_WIDGET_GONK)
return (g_jvm && g_context && g_audio_manager_class);
-#else
- return true;
-#endif
}
void AudioManager::CreateJavaInstance() {
-#if !defined(MOZ_WIDGET_GONK)
ALOGD("CreateJavaInstance");
AttachThreadScoped ats(g_jvm);
JNIEnv* jni = ats.env();
@@ -198,7 +171,6 @@ void AudioManager::CreateJavaInstance() {
j_audio_manager_ = jni->NewGlobalRef(j_audio_manager_);
CHECK_EXCEPTION(jni) << "Error during NewGlobalRef";
CHECK(j_audio_manager_);
-#endif
}
} // namespace webrtc
diff --git a/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.h b/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.h
index a85acb9bb..a6c712e11 100644
--- a/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.h
+++ b/media/webrtc/trunk/webrtc/modules/audio_device/android/audio_manager.h
@@ -11,17 +11,13 @@
#ifndef WEBRTC_MODULES_AUDIO_DEVICE_ANDROID_AUDIO_MANAGER_H_
#define WEBRTC_MODULES_AUDIO_DEVICE_ANDROID_AUDIO_MANAGER_H_
-#if !defined(MOZ_WIDGET_GONK)
#include <jni.h>
-#endif
#include "webrtc/base/thread_checker.h"
#include "webrtc/modules/audio_device/android/audio_common.h"
#include "webrtc/modules/audio_device/include/audio_device_defines.h"
#include "webrtc/modules/audio_device/audio_device_generic.h"
-#if !defined(MOZ_WIDGET_GONK)
#include "webrtc/modules/utility/interface/helpers_android.h"
-#endif
namespace webrtc {
@@ -100,14 +96,12 @@ class AudioManager {
bool initialized() const { return initialized_; }
private:
-#if !defined(MOZ_WIDGET_GONK)
// Called from Java side so we can cache the native audio parameters.
// This method will be called by the WebRtcAudioManager constructor, i.e.
// on the same thread that this object is created on.
static void JNICALL CacheAudioParameters(JNIEnv* env, jobject obj,
jint sample_rate, jint channels, jlong nativeAudioManager);
void OnCacheAudioParameters(JNIEnv* env, jint sample_rate, jint channels);
-#endif
// Returns true if SetAndroidAudioDeviceObjects() has been called
// successfully.
@@ -121,10 +115,8 @@ class AudioManager {
// other methods are called from the same thread.
rtc::ThreadChecker thread_checker_;
-#if !defined(MOZ_WIDGET_GONK)
// The Java WebRtcAudioManager instance.
jobject j_audio_manager_;
-#endif
// Set to true by Init() and false by Close().
bool initialized_;
diff --git a/media/webrtc/trunk/webrtc/video_engine/include/vie_base.h b/media/webrtc/trunk/webrtc/video_engine/include/vie_base.h
index 4e0b15355..578622411 100644
--- a/media/webrtc/trunk/webrtc/video_engine/include/vie_base.h
+++ b/media/webrtc/trunk/webrtc/video_engine/include/vie_base.h
@@ -21,7 +21,7 @@
#include "webrtc/common_types.h"
-#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD) && !defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
#include <jni.h>
#endif
@@ -156,7 +156,7 @@ class WEBRTC_DLLEXPORT VideoEngine {
// user receives callbacks for generated trace messages.
static int SetTraceCallback(TraceCallback* callback);
-#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD) && !defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID) && !defined(WEBRTC_CHROMIUM_BUILD)
// Android specific.
static int SetAndroidObjects(JavaVM* java_vm);
#endif
diff --git a/memory/build/jemalloc_config.cpp b/memory/build/jemalloc_config.cpp
index 441fd8a2b..0b734d804 100644
--- a/memory/build/jemalloc_config.cpp
+++ b/memory/build/jemalloc_config.cpp
@@ -2,161 +2,7 @@
* License, v. 2.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 MOZ_JEMALLOC4
-
-#define MOZ_JEMALLOC_IMPL
-
-/* mozmemory_wrap.h needs to be included before MFBT headers */
-#include "mozmemory_wrap.h"
-#include <mozilla/Assertions.h>
-#include "mozilla/Types.h"
-
-#if defined(MOZ_SYSTEM_JEMALLOC)
-#include MALLOC_H
-#else
-#define DLLEXPORT
-#include "jemalloc/jemalloc.h"
-#endif
-
-#ifdef XP_WIN
-#include <windows.h>
-#endif
-#ifdef XP_DARWIN
-#include <sys/mman.h>
-#endif
-
-/* Override some jemalloc defaults */
-#ifdef DEBUG
-#define MOZ_MALLOC_BUILD_OPTIONS ",junk:true"
-#else
-#define MOZ_MALLOC_BUILD_OPTIONS ",junk:free"
-#endif
-
-#define MOZ_MALLOC_OPTIONS "narenas:1,tcache:false"
-MFBT_DATA const char* je_(malloc_conf) =
- MOZ_MALLOC_OPTIONS MOZ_MALLOC_BUILD_OPTIONS;
-
-#ifdef ANDROID
-#include <android/log.h>
-
-static void
-_je_malloc_message(void* cbopaque, const char* s)
-{
- __android_log_print(ANDROID_LOG_INFO, "GeckoJemalloc", "%s", s);
-}
-
-void (*je_(malloc_message))(void*, const char* s) = _je_malloc_message;
-#endif
-
-/* Jemalloc supports hooks that are called on chunk
- * allocate/deallocate/commit/decommit/purge/etc.
- *
- * We currently only hook commit, decommit and purge. We do this to tweak
- * the way chunks are handled so that RSS stays lower than it normally
- * would with the default jemalloc uses.
- * This somewhat matches the behavior of mozjemalloc, except it doesn't
- * rely on a double purge on mac, instead purging directly. (Yes, this
- * means we can get rid of jemalloc_purge_freed_pages at some point)
- *
- * The default for jemalloc is to do the following:
- * - commit, decommit: nothing
- * - purge: MEM_RESET on Windows, MADV_FREE on Mac/BSD, MADV_DONTNEED on Linux
- *
- * The hooks we setup do the following:
- * on Windows:
- * - commit: MEM_COMMIT
- * - decommit: MEM_DECOMMIT
- * on Mac:
- * - purge: mmap new anonymous memory on top of the chunk
- *
- * We only set the above hooks, others are left with the default.
- */
-#if defined(XP_WIN) || defined(XP_DARWIN)
-class JemallocInit {
-public:
- JemallocInit()
- {
- chunk_hooks_t hooks;
- size_t hooks_len;
- unsigned narenas;
- size_t mib[3];
- size_t size;
-
- size = sizeof(narenas);
- je_(mallctl)("arenas.narenas", &narenas, &size, nullptr, 0);
-
- size = sizeof(mib) / sizeof(mib[0]);
- je_(mallctlnametomib)("arena.0.chunk_hooks", mib, &size);
-
- /* Set the hooks on all the existing arenas. */
- for (unsigned arena = 0; arena < narenas; arena++) {
- mib[1] = arena;
- hooks_len = sizeof(hooks);
- je_(mallctlbymib)(mib, size, &hooks, &hooks_len, nullptr, 0);
-
-#ifdef XP_WIN
- hooks.commit = CommitHook;
- hooks.decommit = DecommitHook;
-#endif
-#ifdef XP_DARWIN
- hooks.purge = PurgeHook;
-#endif
-
- je_(mallctlbymib)(mib, size, nullptr, nullptr, &hooks, hooks_len);
- }
- }
-
-private:
-#ifdef XP_WIN
- static bool
- CommitHook(void* chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
- {
- void* addr = reinterpret_cast<void*>(
- reinterpret_cast<uintptr_t>(chunk) + static_cast<uintptr_t>(offset));
-
- if (!VirtualAlloc(addr, length, MEM_COMMIT, PAGE_READWRITE))
- return true;
-
- return false;
- }
-
- static bool
- DecommitHook(void* chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
- {
- void* addr = reinterpret_cast<void*>(
- reinterpret_cast<uintptr_t>(chunk) + static_cast<uintptr_t>(offset));
-
- if (!VirtualFree(addr, length, MEM_DECOMMIT))
- MOZ_CRASH();
-
- return false;
- }
-#endif
-
-#ifdef XP_DARWIN
- static bool
- PurgeHook(void* chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
- {
- void* addr = reinterpret_cast<void*>(
- reinterpret_cast<uintptr_t>(chunk) + static_cast<uintptr_t>(offset));
-
- void* new_addr = mmap(addr, length, PROT_READ | PROT_WRITE,
- MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0);
- return (new_addr != addr);
- }
-#endif
-};
-
-/* For the static constructor from the class above */
-JemallocInit gJemallocInit;
-#endif
-
-#else
#include <mozilla/Assertions.h>
-#endif /* MOZ_JEMALLOC4 */
/* Provide an abort function for use in jemalloc code */
extern "C" void moz_abort() {
diff --git a/memory/build/moz.build b/memory/build/moz.build
index 8d80561b1..f4fd82878 100644
--- a/memory/build/moz.build
+++ b/memory/build/moz.build
@@ -24,16 +24,6 @@ SOURCES += [
'mozmemory_wrap.c',
]
-if CONFIG['MOZ_JEMALLOC4']:
- SOURCES += [
- 'mozjemalloc_compat.c',
- ]
- LOCAL_INCLUDES += ['!../jemalloc/src/include']
- if CONFIG['_MSC_VER']:
- LOCAL_INCLUDES += ['/memory/jemalloc/src/include/msvc_compat']
- if not CONFIG['HAVE_INTTYPES_H']:
- LOCAL_INCLUDES += ['/memory/jemalloc/src/include/msvc_compat/C99']
-
if CONFIG['MOZ_REPLACE_MALLOC']:
SOURCES += [
'replace_malloc.c',
@@ -46,10 +36,6 @@ if CONFIG['MOZ_GLUE_IN_PROGRAM']:
DIST_INSTALL = True
# Keep jemalloc separated when mozglue is statically linked
-if CONFIG['MOZ_MEMORY'] and (CONFIG['OS_TARGET'] in ('WINNT', 'Darwin', 'Android') or
- CONFIG['MOZ_SYSTEM_JEMALLOC']):
+if CONFIG['MOZ_MEMORY'] and CONFIG['OS_TARGET'] in ('WINNT', 'Darwin', 'Android'):
FINAL_LIBRARY = 'mozglue'
-if CONFIG['MOZ_REPLACE_MALLOC'] and CONFIG['OS_TARGET'] == 'Darwin':
- # The zone allocator for OSX needs some jemalloc internal functions
- LOCAL_INCLUDES += ['/memory/jemalloc/src/include']
diff --git a/memory/build/mozjemalloc_compat.c b/memory/build/mozjemalloc_compat.c
deleted file mode 100644
index 6591892c1..000000000
--- a/memory/build/mozjemalloc_compat.c
+++ /dev/null
@@ -1,182 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_JEMALLOC4
-# error Should only compile this file when building with jemalloc 3
-#endif
-
-#define MOZ_JEMALLOC_IMPL
-
-#include "mozmemory_wrap.h"
-#include "jemalloc_types.h"
-#include "mozilla/Types.h"
-
-#include <stdbool.h>
-
-#if defined(MOZ_SYSTEM_JEMALLOC)
-# include MALLOC_H
-#else
-# include "jemalloc/jemalloc.h"
-#endif
-
-/*
- * CTL_* macros are from memory/jemalloc/src/src/stats.c with changes:
- * - drop `t' argument to avoid redundancy in calculating type size
- * - require `i' argument for arena number explicitly
- */
-
-#define CTL_GET(n, v) do { \
- size_t sz = sizeof(v); \
- je_(mallctl)(n, &v, &sz, NULL, 0); \
-} while (0)
-
-#define CTL_I_GET(n, v, i) do { \
- size_t mib[6]; \
- size_t miblen = sizeof(mib) / sizeof(mib[0]); \
- size_t sz = sizeof(v); \
- je_(mallctlnametomib)(n, mib, &miblen); \
- mib[2] = i; \
- je_(mallctlbymib)(mib, miblen, &v, &sz, NULL, 0); \
-} while (0)
-
-#define CTL_IJ_GET(n, v, i, j) do { \
- size_t mib[6]; \
- size_t miblen = sizeof(mib) / sizeof(mib[0]); \
- size_t sz = sizeof(v); \
- je_(mallctlnametomib)(n, mib, &miblen); \
- mib[2] = i; \
- mib[4] = j; \
- je_(mallctlbymib)(mib, miblen, &v, &sz, NULL, 0); \
-} while (0)
-
-/*
- * VARIABLE_ARRAY is copied from
- * memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal.h.in
- */
-#if __STDC_VERSION__ < 199901L
-# ifdef _MSC_VER
-# include <malloc.h>
-# define alloca _alloca
-# else
-# ifdef HAVE_ALLOCA_H
-# include <alloca.h>
-# else
-# include <stdlib.h>
-# endif
-# endif
-# define VARIABLE_ARRAY(type, name, count) \
- type *name = alloca(sizeof(type) * (count))
-#else
-# define VARIABLE_ARRAY(type, name, count) type name[(count)]
-#endif
-
-MOZ_MEMORY_API size_t
-malloc_good_size_impl(size_t size)
-{
- /* je_nallocx crashes when given a size of 0. As
- * malloc_usable_size(malloc(0)) and malloc_usable_size(malloc(1))
- * return the same value, use a size of 1. */
- if (size == 0)
- size = 1;
- return je_(nallocx)(size, 0);
-}
-
-static void
-compute_bin_unused_and_bookkeeping(jemalloc_stats_t *stats, unsigned int narenas)
-{
- size_t bin_unused = 0;
-
- uint32_t nregs; // number of regions per run in the j-th bin
- size_t reg_size; // size of regions served by the j-th bin
- size_t curruns; // number of runs belonging to a bin
- size_t curregs; // number of allocated regions in a bin
-
- unsigned int nbins; // number of bins per arena
- unsigned int i, j;
-
- size_t stats_metadata;
- size_t stats_ametadata = 0; // total internal allocations in all arenas
-
- // narenas also counts uninitialized arenas, and initialized arenas
- // are not guaranteed to be adjacent
- VARIABLE_ARRAY(bool, initialized, narenas);
- size_t isz = sizeof(initialized) / sizeof(initialized[0]);
-
- je_(mallctl)("arenas.initialized", initialized, &isz, NULL, 0);
- CTL_GET("arenas.nbins", nbins);
-
- for (j = 0; j < nbins; j++) {
- CTL_I_GET("arenas.bin.0.nregs", nregs, j);
- CTL_I_GET("arenas.bin.0.size", reg_size, j);
-
- for (i = 0; i < narenas; i++) {
- if (!initialized[i]) {
- continue;
- }
-
- CTL_IJ_GET("stats.arenas.0.bins.0.curruns", curruns, i, j);
- CTL_IJ_GET("stats.arenas.0.bins.0.curregs", curregs, i, j);
-
- bin_unused += (nregs * curruns - curregs) * reg_size;
- }
- }
-
- CTL_GET("stats.metadata", stats_metadata);
-
- /* get the summation for all arenas, i == narenas */
- CTL_I_GET("stats.arenas.0.metadata.allocated", stats_ametadata, narenas);
-
- stats->bookkeeping = stats_metadata - stats_ametadata;
- stats->bin_unused = bin_unused;
-}
-
-MOZ_JEMALLOC_API void
-jemalloc_stats_impl(jemalloc_stats_t *stats)
-{
- unsigned narenas;
- size_t active, allocated, mapped, page, pdirty;
- size_t lg_chunk;
-
- // Refresh jemalloc's stats by updating its epoch, see ctl_refresh in
- // src/ctl.c
- uint64_t epoch = 0;
- size_t esz = sizeof(epoch);
- je_(mallctl)("epoch", &epoch, &esz, &epoch, esz);
-
- CTL_GET("arenas.narenas", narenas);
- CTL_GET("arenas.page", page);
- CTL_GET("stats.active", active);
- CTL_GET("stats.allocated", allocated);
- CTL_GET("stats.mapped", mapped);
- CTL_GET("opt.lg_chunk", lg_chunk);
-
- /* get the summation for all arenas, i == narenas */
- CTL_I_GET("stats.arenas.0.pdirty", pdirty, narenas);
-
- stats->chunksize = (size_t) 1 << lg_chunk;
- stats->mapped = mapped;
- stats->allocated = allocated;
- stats->waste = active - allocated;
- stats->page_cache = pdirty * page;
- compute_bin_unused_and_bookkeeping(stats, narenas);
- stats->waste -= stats->bin_unused;
-}
-
-MOZ_JEMALLOC_API void
-jemalloc_purge_freed_pages_impl()
-{
-}
-
-MOZ_JEMALLOC_API void
-jemalloc_free_dirty_pages_impl()
-{
- unsigned narenas;
- size_t mib[3];
- size_t miblen = sizeof(mib) / sizeof(mib[0]);
-
- CTL_GET("arenas.narenas", narenas);
- je_(mallctlnametomib)("arena.0.purge", mib, &miblen);
- mib[1] = narenas;
- je_(mallctlbymib)(mib, miblen, NULL, NULL, NULL, 0);
-}
diff --git a/memory/build/mozmemory_wrap.h b/memory/build/mozmemory_wrap.h
index 066d57782..bb1d339ba 100644
--- a/memory/build/mozmemory_wrap.h
+++ b/memory/build/mozmemory_wrap.h
@@ -36,8 +36,7 @@
* - jemalloc_stats
* - jemalloc_purge_freed_pages
* - jemalloc_free_dirty_pages
- * (these functions are native to mozjemalloc, and have compatibility
- * implementations for jemalloc3)
+ * (these functions are native to mozjemalloc)
*
* These functions are all exported as part of libmozglue (see
* $(topsrcdir)/mozglue/build/Makefile.in), with a few implementation
@@ -87,21 +86,16 @@
* char* strdup_impl(const char *)
* That implementation would call malloc by using "malloc_impl".
*
- * While mozjemalloc uses these "_impl" suffixed helpers, jemalloc3, being
- * third-party code, doesn't, but instead has an elaborate way to mangle
- * individual functions. See under "Run jemalloc configure script" in
- * $(topsrcdir)/configure.in.
- *
*
* When building with replace-malloc support, the above still holds, but
* the malloc implementation and jemalloc specific functions are the
* replace-malloc functions from replace_malloc.c.
*
- * The actual jemalloc/mozjemalloc implementation is prefixed with "je_".
+ * The actual mozjemalloc implementation is prefixed with "je_".
*
* Thus, when MOZ_REPLACE_MALLOC is defined, the "_impl" suffixed macros
- * expand to "je_" prefixed function when building mozjemalloc or
- * jemalloc3/mozjemalloc_compat, where MOZ_JEMALLOC_IMPL is defined.
+ * expand to "je_" prefixed function when building mozjemalloc, where
+ * MOZ_JEMALLOC_IMPL is defined.
*
* In other cases, the "_impl" suffixed macros follow the original scheme,
* except on Windows and MacOSX, where they would expand to "je_" prefixed
@@ -125,43 +119,31 @@
#include "mozilla/Types.h"
-#if !defined(MOZ_SYSTEM_JEMALLOC)
-# ifdef MOZ_MEMORY_IMPL
-# if defined(MOZ_JEMALLOC_IMPL) && defined(MOZ_REPLACE_MALLOC) && !defined(MOZ_REPLACE_JEMALLOC)
-# define mozmem_malloc_impl(a) je_ ## a
-# define mozmem_jemalloc_impl(a) je_ ## a
-# else
-# define MOZ_JEMALLOC_API MFBT_API
-# ifdef MOZ_REPLACE_JEMALLOC
-# define MOZ_MEMORY_API MFBT_API
-# define mozmem_malloc_impl(a) replace_ ## a
-# define mozmem_jemalloc_impl(a) replace_ ## a
-# elif (defined(XP_WIN) || defined(XP_DARWIN))
-# if defined(MOZ_REPLACE_MALLOC)
-# define mozmem_malloc_impl(a) a ## _impl
-# else
-# define mozmem_malloc_impl(a) je_ ## a
-# endif
+#ifdef MOZ_MEMORY_IMPL
+# if defined(MOZ_JEMALLOC_IMPL) && defined(MOZ_REPLACE_MALLOC)
+# define mozmem_malloc_impl(a) je_ ## a
+# define mozmem_jemalloc_impl(a) je_ ## a
+# else
+# define MOZ_JEMALLOC_API MFBT_API
+# if (defined(XP_WIN) || defined(XP_DARWIN))
+# if defined(MOZ_REPLACE_MALLOC)
+# define mozmem_malloc_impl(a) a ## _impl
# else
-# define MOZ_MEMORY_API MFBT_API
-# if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
-# define MOZ_WRAP_NEW_DELETE
-# endif
+# define mozmem_malloc_impl(a) je_ ## a
+# endif
+# else
+# define MOZ_MEMORY_API MFBT_API
+# if defined(MOZ_WIDGET_ANDROID)
+# define MOZ_WRAP_NEW_DELETE
# endif
-# endif
-# ifdef XP_WIN
-# define mozmem_dup_impl(a) wrap_ ## a
# endif
# endif
-
-/* All other jemalloc3 functions are prefixed with "je_", except when
- * building against an unprefixed system jemalloc library */
-# define je_(a) je_ ## a
-#else /* defined(MOZ_SYSTEM_JEMALLOC) */
-# define je_(a) a
+# ifdef XP_WIN
+# define mozmem_dup_impl(a) wrap_ ## a
+# endif
#endif
-#if !defined(MOZ_MEMORY_IMPL) || defined(MOZ_SYSTEM_JEMALLOC)
+#if !defined(MOZ_MEMORY_IMPL)
# define MOZ_MEMORY_API MFBT_API
# define MOZ_JEMALLOC_API MFBT_API
#endif
diff --git a/memory/build/replace_malloc.c b/memory/build/replace_malloc.c
index 26dd8c2d6..f4c7eb878 100644
--- a/memory/build/replace_malloc.c
+++ b/memory/build/replace_malloc.c
@@ -10,10 +10,6 @@
# error Should not compile this file when replace-malloc is disabled
#endif
-#ifdef MOZ_SYSTEM_JEMALLOC
-# error Should not compile this file when we want to use native jemalloc
-#endif
-
#include "mozmemory_wrap.h"
/* Declare all je_* functions */
diff --git a/memory/jemalloc/README.mozilla b/memory/jemalloc/README.mozilla
deleted file mode 100644
index 0bbbca468..000000000
--- a/memory/jemalloc/README.mozilla
+++ /dev/null
@@ -1,9 +0,0 @@
-This is a copy of the jemalloc source code. It is intended to be left pristine.
-Modifications to this code without coordinating with upstream are unacceptable,
-and will be reverted. Integration modifications should be made in memory/build
-whenever possible.
-
-The canonical repository for this source code is git://canonware.com/jemalloc.git.
-The information about the upstream repository and revision lives in upstream.info.
-In order to update the code, you can run the update.sh script located in
-the same directory.
diff --git a/memory/jemalloc/helper/git b/memory/jemalloc/helper/git
deleted file mode 100755
index 9afdb6778..000000000
--- a/memory/jemalloc/helper/git
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/bin/sh
-
-# jemalloc's configure runs git to determine the version. But when building
-# from a gecko git clone, the git commands it uses is going to pick gecko's
-# information, not jemalloc's, which is useless. So pretend we don't have git
-# at all. That will make jemalloc's configure pick the in-tree VERSION file.
-
-exit 1
diff --git a/memory/jemalloc/moz.build b/memory/jemalloc/moz.build
deleted file mode 100644
index b7e2b661f..000000000
--- a/memory/jemalloc/moz.build
+++ /dev/null
@@ -1,81 +0,0 @@
-# -*- 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/.
-
-UNIFIED_SOURCES += [
- 'src/src/arena.c',
- 'src/src/atomic.c',
- 'src/src/base.c',
- 'src/src/bitmap.c',
- 'src/src/chunk.c',
- 'src/src/chunk_dss.c',
- 'src/src/chunk_mmap.c',
- 'src/src/ckh.c',
- 'src/src/extent.c',
- 'src/src/hash.c',
- 'src/src/huge.c',
- 'src/src/jemalloc.c',
- 'src/src/mb.c',
- 'src/src/mutex.c',
- 'src/src/nstime.c',
- 'src/src/pages.c',
- 'src/src/prng.c',
- 'src/src/prof.c',
- 'src/src/quarantine.c',
- 'src/src/rtree.c',
- 'src/src/spin.c',
- 'src/src/stats.c',
- 'src/src/tcache.c',
- 'src/src/ticker.c',
- 'src/src/tsd.c',
- 'src/src/util.c',
- 'src/src/witness.c',
-]
-
-SOURCES += [
- # This file cannot be built in unified mode because of symbol clash on arena_purge.
- 'src/src/ctl.c',
-]
-
-# Only OSX needs the zone allocation implementation,
-# but only if replace-malloc is not enabled.
-if CONFIG['OS_TARGET'] == 'Darwin' and not CONFIG['MOZ_REPLACE_MALLOC']:
- UNIFIED_SOURCES += [
- 'src/src/zone.c',
- ]
-
-if CONFIG['MOZ_JEMALLOC4']:
- FINAL_LIBRARY = 'memory'
-else:
- FINAL_LIBRARY = 'replace_jemalloc'
-
-if CONFIG['MOZ_GLUE_IN_PROGRAM']:
- SDK_LIBRARY = True
- DIST_INSTALL = True
-
-if CONFIG['_MSC_VER']:
- DEFINES['DLLEXPORT'] = True
- LOCAL_INCLUDES += ['src/include/msvc_compat']
- if not CONFIG['HAVE_INTTYPES_H']:
- LOCAL_INCLUDES += ['src/include/msvc_compat/C99']
-
-if CONFIG['OS_TARGET'] == 'Linux':
- # For mremap
- DEFINES['_GNU_SOURCE'] = True
-
-if CONFIG['GNU_CC']:
- CFLAGS += ['-std=gnu99']
-
-DEFINES['abort'] = 'moz_abort'
-
-LOCAL_INCLUDES += [
- '!src/include',
- 'src/include',
-]
-
-# We allow warnings for third-party code that can be updated from upstream.
-ALLOW_COMPILER_WARNINGS = True
-
-OS_LIBS += CONFIG['REALTIME_LIBS']
diff --git a/memory/jemalloc/src/.appveyor.yml b/memory/jemalloc/src/.appveyor.yml
deleted file mode 100644
index ddd5c5711..000000000
--- a/memory/jemalloc/src/.appveyor.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-version: '{build}'
-
-environment:
- matrix:
- - MSYSTEM: MINGW64
- CPU: x86_64
- MSVC: amd64
- - MSYSTEM: MINGW32
- CPU: i686
- MSVC: x86
- - MSYSTEM: MINGW64
- CPU: x86_64
- - MSYSTEM: MINGW32
- CPU: i686
-
-install:
- - set PATH=c:\msys64\%MSYSTEM%\bin;c:\msys64\usr\bin;%PATH%
- - if defined MSVC call "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" %MSVC%
- - if defined MSVC pacman --noconfirm -Rsc mingw-w64-%CPU%-gcc gcc
- - pacman --noconfirm -Suy mingw-w64-%CPU%-make
-
-build_script:
- - bash -c "autoconf"
- - bash -c "./configure"
- - mingw32-make -j3
- - file lib/jemalloc.dll
- - mingw32-make -j3 tests
- - mingw32-make -k check
diff --git a/memory/jemalloc/src/.travis.yml b/memory/jemalloc/src/.travis.yml
deleted file mode 100644
index 1fed4f8e6..000000000
--- a/memory/jemalloc/src/.travis.yml
+++ /dev/null
@@ -1,29 +0,0 @@
-language: c
-
-matrix:
- include:
- - os: linux
- compiler: gcc
- - os: linux
- compiler: gcc
- env:
- - EXTRA_FLAGS=-m32
- addons:
- apt:
- packages:
- - gcc-multilib
- - os: osx
- compiler: clang
- - os: osx
- compiler: clang
- env:
- - EXTRA_FLAGS=-m32
-
-before_script:
- - autoconf
- - ./configure${EXTRA_FLAGS:+ CC="$CC $EXTRA_FLAGS"}
- - make -j3
- - make -j3 tests
-
-script:
- - make check
diff --git a/memory/jemalloc/src/COPYING b/memory/jemalloc/src/COPYING
deleted file mode 100644
index 104b1f8b0..000000000
--- a/memory/jemalloc/src/COPYING
+++ /dev/null
@@ -1,27 +0,0 @@
-Unless otherwise specified, files in the jemalloc source distribution are
-subject to the following license:
---------------------------------------------------------------------------------
-Copyright (C) 2002-2016 Jason Evans <jasone@canonware.com>.
-All rights reserved.
-Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
-Copyright (C) 2009-2016 Facebook, Inc. 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(s),
- this list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright notice(s),
- 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 COPYRIGHT HOLDER(S) ``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(S) 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/memory/jemalloc/src/ChangeLog b/memory/jemalloc/src/ChangeLog
deleted file mode 100644
index 587685d02..000000000
--- a/memory/jemalloc/src/ChangeLog
+++ /dev/null
@@ -1,981 +0,0 @@
-Following are change highlights associated with official releases. Important
-bug fixes are all mentioned, but some internal enhancements are omitted here for
-brevity. Much more detail can be found in the git revision history:
-
- https://github.com/jemalloc/jemalloc
-
-* 4.3.1 (November 7, 2016)
-
- Bug fixes:
- - Fix a severe virtual memory leak. This regression was first released in
- 4.3.0. (@interwq, @jasone)
- - Refactor atomic and prng APIs to restore support for 32-bit platforms that
- use pre-C11 toolchains, e.g. FreeBSD's mips. (@jasone)
-
-* 4.3.0 (November 4, 2016)
-
- This is the first release that passes the test suite for multiple Windows
- configurations, thanks in large part to @glandium setting up continuous
- integration via AppVeyor (and Travis CI for Linux and OS X).
-
- New features:
- - Add "J" (JSON) support to malloc_stats_print(). (@jasone)
- - Add Cray compiler support. (@ronawho)
-
- Optimizations:
- - Add/use adaptive spinning for bootstrapping and radix tree node
- initialization. (@jasone)
-
- Bug fixes:
- - Fix large allocation to search starting in the optimal size class heap,
- which can substantially reduce virtual memory churn and fragmentation. This
- regression was first released in 4.0.0. (@mjp41, @jasone)
- - Fix stats.arenas.<i>.nthreads accounting. (@interwq)
- - Fix and simplify decay-based purging. (@jasone)
- - Make DSS (sbrk(2)-related) operations lockless, which resolves potential
- deadlocks during thread exit. (@jasone)
- - Fix over-sized allocation of radix tree leaf nodes. (@mjp41, @ogaun,
- @jasone)
- - Fix over-sized allocation of arena_t (plus associated stats) data
- structures. (@jasone, @interwq)
- - Fix EXTRA_CFLAGS to not affect configuration. (@jasone)
- - Fix a Valgrind integration bug. (@ronawho)
- - Disallow 0x5a junk filling when running in Valgrind. (@jasone)
- - Fix a file descriptor leak on Linux. This regression was first released in
- 4.2.0. (@vsarunas, @jasone)
- - Fix static linking of jemalloc with glibc. (@djwatson)
- - Use syscall(2) rather than {open,read,close}(2) during boot on Linux. This
- works around other libraries' system call wrappers performing reentrant
- allocation. (@kspinka, @Whissi, @jasone)
- - Fix OS X default zone replacement to work with OS X 10.12. (@glandium,
- @jasone)
- - Fix cached memory management to avoid needless commit/decommit operations
- during purging, which resolves permanent virtual memory map fragmentation
- issues on Windows. (@mjp41, @jasone)
- - Fix TSD fetches to avoid (recursive) allocation. This is relevant to
- non-TLS and Windows configurations. (@jasone)
- - Fix malloc_conf overriding to work on Windows. (@jasone)
- - Forcibly disable lazy-lock on Windows (was forcibly *enabled*). (@jasone)
-
-* 4.2.1 (June 8, 2016)
-
- Bug fixes:
- - Fix bootstrapping issues for configurations that require allocation during
- tsd initialization (e.g. --disable-tls). (@cferris1000, @jasone)
- - Fix gettimeofday() version of nstime_update(). (@ronawho)
- - Fix Valgrind regressions in calloc() and chunk_alloc_wrapper(). (@ronawho)
- - Fix potential VM map fragmentation regression. (@jasone)
- - Fix opt_zero-triggered in-place huge reallocation zeroing. (@jasone)
- - Fix heap profiling context leaks in reallocation edge cases. (@jasone)
-
-* 4.2.0 (May 12, 2016)
-
- New features:
- - Add the arena.<i>.reset mallctl, which makes it possible to discard all of
- an arena's allocations in a single operation. (@jasone)
- - Add the stats.retained and stats.arenas.<i>.retained statistics. (@jasone)
- - Add the --with-version configure option. (@jasone)
- - Support --with-lg-page values larger than actual page size. (@jasone)
-
- Optimizations:
- - Use pairing heaps rather than red-black trees for various hot data
- structures. (@djwatson, @jasone)
- - Streamline fast paths of rtree operations. (@jasone)
- - Optimize the fast paths of calloc() and [m,d,sd]allocx(). (@jasone)
- - Decommit unused virtual memory if the OS does not overcommit. (@jasone)
- - Specify MAP_NORESERVE on Linux if [heuristic] overcommit is active, in order
- to avoid unfortunate interactions during fork(2). (@jasone)
-
- Bug fixes:
- - Fix chunk accounting related to triggering gdump profiles. (@jasone)
- - Link against librt for clock_gettime(2) if glibc < 2.17. (@jasone)
- - Scale leak report summary according to sampling probability. (@jasone)
-
-* 4.1.1 (May 3, 2016)
-
- This bugfix release resolves a variety of mostly minor issues, though the
- bitmap fix is critical for 64-bit Windows.
-
- Bug fixes:
- - Fix the linear scan version of bitmap_sfu() to shift by the proper amount
- even when sizeof(long) is not the same as sizeof(void *), as on 64-bit
- Windows. (@jasone)
- - Fix hashing functions to avoid unaligned memory accesses (and resulting
- crashes). This is relevant at least to some ARM-based platforms.
- (@rkmisra)
- - Fix fork()-related lock rank ordering reversals. These reversals were
- unlikely to cause deadlocks in practice except when heap profiling was
- enabled and active. (@jasone)
- - Fix various chunk leaks in OOM code paths. (@jasone)
- - Fix malloc_stats_print() to print opt.narenas correctly. (@jasone)
- - Fix MSVC-specific build/test issues. (@rustyx, @yuslepukhin)
- - Fix a variety of test failures that were due to test fragility rather than
- core bugs. (@jasone)
-
-* 4.1.0 (February 28, 2016)
-
- This release is primarily about optimizations, but it also incorporates a lot
- of portability-motivated refactoring and enhancements. Many people worked on
- this release, to an extent that even with the omission here of minor changes
- (see git revision history), and of the people who reported and diagnosed
- issues, so much of the work was contributed that starting with this release,
- changes are annotated with author credits to help reflect the collaborative
- effort involved.
-
- New features:
- - Implement decay-based unused dirty page purging, a major optimization with
- mallctl API impact. This is an alternative to the existing ratio-based
- unused dirty page purging, and is intended to eventually become the sole
- purging mechanism. New mallctls:
- + opt.purge
- + opt.decay_time
- + arena.<i>.decay
- + arena.<i>.decay_time
- + arenas.decay_time
- + stats.arenas.<i>.decay_time
- (@jasone, @cevans87)
- - Add --with-malloc-conf, which makes it possible to embed a default
- options string during configuration. This was motivated by the desire to
- specify --with-malloc-conf=purge:decay , since the default must remain
- purge:ratio until the 5.0.0 release. (@jasone)
- - Add MS Visual Studio 2015 support. (@rustyx, @yuslepukhin)
- - Make *allocx() size class overflow behavior defined. The maximum
- size class is now less than PTRDIFF_MAX to protect applications against
- numerical overflow, and all allocation functions are guaranteed to indicate
- errors rather than potentially crashing if the request size exceeds the
- maximum size class. (@jasone)
- - jeprof:
- + Add raw heap profile support. (@jasone)
- + Add --retain and --exclude for backtrace symbol filtering. (@jasone)
-
- Optimizations:
- - Optimize the fast path to combine various bootstrapping and configuration
- checks and execute more streamlined code in the common case. (@interwq)
- - Use linear scan for small bitmaps (used for small object tracking). In
- addition to speeding up bitmap operations on 64-bit systems, this reduces
- allocator metadata overhead by approximately 0.2%. (@djwatson)
- - Separate arena_avail trees, which substantially speeds up run tree
- operations. (@djwatson)
- - Use memoization (boot-time-computed table) for run quantization. Separate
- arena_avail trees reduced the importance of this optimization. (@jasone)
- - Attempt mmap-based in-place huge reallocation. This can dramatically speed
- up incremental huge reallocation. (@jasone)
-
- Incompatible changes:
- - Make opt.narenas unsigned rather than size_t. (@jasone)
-
- Bug fixes:
- - Fix stats.cactive accounting regression. (@rustyx, @jasone)
- - Handle unaligned keys in hash(). This caused problems for some ARM systems.
- (@jasone, @cferris1000)
- - Refactor arenas array. In addition to fixing a fork-related deadlock, this
- makes arena lookups faster and simpler. (@jasone)
- - Move retained memory allocation out of the default chunk allocation
- function, to a location that gets executed even if the application installs
- a custom chunk allocation function. This resolves a virtual memory leak.
- (@buchgr)
- - Fix a potential tsd cleanup leak. (@cferris1000, @jasone)
- - Fix run quantization. In practice this bug had no impact unless
- applications requested memory with alignment exceeding one page.
- (@jasone, @djwatson)
- - Fix LinuxThreads-specific bootstrapping deadlock. (Cosmin Paraschiv)
- - jeprof:
- + Don't discard curl options if timeout is not defined. (@djwatson)
- + Detect failed profile fetches. (@djwatson)
- - Fix stats.arenas.<i>.{dss,lg_dirty_mult,decay_time,pactive,pdirty} for
- --disable-stats case. (@jasone)
-
-* 4.0.4 (October 24, 2015)
-
- This bugfix release fixes another xallocx() regression. No other regressions
- have come to light in over a month, so this is likely a good starting point
- for people who prefer to wait for "dot one" releases with all the major issues
- shaken out.
-
- Bug fixes:
- - Fix xallocx(..., MALLOCX_ZERO to zero the last full trailing page of large
- allocations that have been randomly assigned an offset of 0 when
- --enable-cache-oblivious configure option is enabled.
-
-* 4.0.3 (September 24, 2015)
-
- This bugfix release continues the trend of xallocx() and heap profiling fixes.
-
- Bug fixes:
- - Fix xallocx(..., MALLOCX_ZERO) to zero all trailing bytes of large
- allocations when --enable-cache-oblivious configure option is enabled.
- - Fix xallocx(..., MALLOCX_ZERO) to zero trailing bytes of huge allocations
- when resizing from/to a size class that is not a multiple of the chunk size.
- - Fix prof_tctx_dump_iter() to filter out nodes that were created after heap
- profile dumping started.
- - Work around a potentially bad thread-specific data initialization
- interaction with NPTL (glibc's pthreads implementation).
-
-* 4.0.2 (September 21, 2015)
-
- This bugfix release addresses a few bugs specific to heap profiling.
-
- Bug fixes:
- - Fix ixallocx_prof_sample() to never modify nor create sampled small
- allocations. xallocx() is in general incapable of moving small allocations,
- so this fix removes buggy code without loss of generality.
- - Fix irallocx_prof_sample() to always allocate large regions, even when
- alignment is non-zero.
- - Fix prof_alloc_rollback() to read tdata from thread-specific data rather
- than dereferencing a potentially invalid tctx.
-
-* 4.0.1 (September 15, 2015)
-
- This is a bugfix release that is somewhat high risk due to the amount of
- refactoring required to address deep xallocx() problems. As a side effect of
- these fixes, xallocx() now tries harder to partially fulfill requests for
- optional extra space. Note that a couple of minor heap profiling
- optimizations are included, but these are better thought of as performance
- fixes that were integral to disovering most of the other bugs.
-
- Optimizations:
- - Avoid a chunk metadata read in arena_prof_tctx_set(), since it is in the
- fast path when heap profiling is enabled. Additionally, split a special
- case out into arena_prof_tctx_reset(), which also avoids chunk metadata
- reads.
- - Optimize irallocx_prof() to optimistically update the sampler state. The
- prior implementation appears to have been a holdover from when
- rallocx()/xallocx() functionality was combined as rallocm().
-
- Bug fixes:
- - Fix TLS configuration such that it is enabled by default for platforms on
- which it works correctly.
- - Fix arenas_cache_cleanup() and arena_get_hard() to handle
- allocation/deallocation within the application's thread-specific data
- cleanup functions even after arenas_cache is torn down.
- - Fix xallocx() bugs related to size+extra exceeding HUGE_MAXCLASS.
- - Fix chunk purge hook calls for in-place huge shrinking reallocation to
- specify the old chunk size rather than the new chunk size. This bug caused
- no correctness issues for the default chunk purge function, but was
- visible to custom functions set via the "arena.<i>.chunk_hooks" mallctl.
- - Fix heap profiling bugs:
- + Fix heap profiling to distinguish among otherwise identical sample sites
- with interposed resets (triggered via the "prof.reset" mallctl). This bug
- could cause data structure corruption that would most likely result in a
- segfault.
- + Fix irealloc_prof() to prof_alloc_rollback() on OOM.
- + Make one call to prof_active_get_unlocked() per allocation event, and use
- the result throughout the relevant functions that handle an allocation
- event. Also add a missing check in prof_realloc(). These fixes protect
- allocation events against concurrent prof_active changes.
- + Fix ixallocx_prof() to pass usize_max and zero to ixallocx_prof_sample()
- in the correct order.
- + Fix prof_realloc() to call prof_free_sampled_object() after calling
- prof_malloc_sample_object(). Prior to this fix, if tctx and old_tctx were
- the same, the tctx could have been prematurely destroyed.
- - Fix portability bugs:
- + Don't bitshift by negative amounts when encoding/decoding run sizes in
- chunk header maps. This affected systems with page sizes greater than 8
- KiB.
- + Rename index_t to szind_t to avoid an existing type on Solaris.
- + Add JEMALLOC_CXX_THROW to the memalign() function prototype, in order to
- match glibc and avoid compilation errors when including both
- jemalloc/jemalloc.h and malloc.h in C++ code.
- + Don't assume that /bin/sh is appropriate when running size_classes.sh
- during configuration.
- + Consider __sparcv9 a synonym for __sparc64__ when defining LG_QUANTUM.
- + Link tests to librt if it contains clock_gettime(2).
-
-* 4.0.0 (August 17, 2015)
-
- This version contains many speed and space optimizations, both minor and
- major. The major themes are generalization, unification, and simplification.
- Although many of these optimizations cause no visible behavior change, their
- cumulative effect is substantial.
-
- New features:
- - Normalize size class spacing to be consistent across the complete size
- range. By default there are four size classes per size doubling, but this
- is now configurable via the --with-lg-size-class-group option. Also add the
- --with-lg-page, --with-lg-page-sizes, --with-lg-quantum, and
- --with-lg-tiny-min options, which can be used to tweak page and size class
- settings. Impacts:
- + Worst case performance for incrementally growing/shrinking reallocation
- is improved because there are far fewer size classes, and therefore
- copying happens less often.
- + Internal fragmentation is limited to 20% for all but the smallest size
- classes (those less than four times the quantum). (1B + 4 KiB)
- and (1B + 4 MiB) previously suffered nearly 50% internal fragmentation.
- + Chunk fragmentation tends to be lower because there are fewer distinct run
- sizes to pack.
- - Add support for explicit tcaches. The "tcache.create", "tcache.flush", and
- "tcache.destroy" mallctls control tcache lifetime and flushing, and the
- MALLOCX_TCACHE(tc) and MALLOCX_TCACHE_NONE flags to the *allocx() API
- control which tcache is used for each operation.
- - Implement per thread heap profiling, as well as the ability to
- enable/disable heap profiling on a per thread basis. Add the "prof.reset",
- "prof.lg_sample", "thread.prof.name", "thread.prof.active",
- "opt.prof_thread_active_init", "prof.thread_active_init", and
- "thread.prof.active" mallctls.
- - Add support for per arena application-specified chunk allocators, configured
- via the "arena.<i>.chunk_hooks" mallctl.
- - Refactor huge allocation to be managed by arenas, so that arenas now
- function as general purpose independent allocators. This is important in
- the context of user-specified chunk allocators, aside from the scalability
- benefits. Related new statistics:
- + The "stats.arenas.<i>.huge.allocated", "stats.arenas.<i>.huge.nmalloc",
- "stats.arenas.<i>.huge.ndalloc", and "stats.arenas.<i>.huge.nrequests"
- mallctls provide high level per arena huge allocation statistics.
- + The "arenas.nhchunks", "arenas.hchunk.<i>.size",
- "stats.arenas.<i>.hchunks.<j>.nmalloc",
- "stats.arenas.<i>.hchunks.<j>.ndalloc",
- "stats.arenas.<i>.hchunks.<j>.nrequests", and
- "stats.arenas.<i>.hchunks.<j>.curhchunks" mallctls provide per size class
- statistics.
- - Add the 'util' column to malloc_stats_print() output, which reports the
- proportion of available regions that are currently in use for each small
- size class.
- - Add "alloc" and "free" modes for for junk filling (see the "opt.junk"
- mallctl), so that it is possible to separately enable junk filling for
- allocation versus deallocation.
- - Add the jemalloc-config script, which provides information about how
- jemalloc was configured, and how to integrate it into application builds.
- - Add metadata statistics, which are accessible via the "stats.metadata",
- "stats.arenas.<i>.metadata.mapped", and
- "stats.arenas.<i>.metadata.allocated" mallctls.
- - Add the "stats.resident" mallctl, which reports the upper limit of
- physically resident memory mapped by the allocator.
- - Add per arena control over unused dirty page purging, via the
- "arenas.lg_dirty_mult", "arena.<i>.lg_dirty_mult", and
- "stats.arenas.<i>.lg_dirty_mult" mallctls.
- - Add the "prof.gdump" mallctl, which makes it possible to toggle the gdump
- feature on/off during program execution.
- - Add sdallocx(), which implements sized deallocation. The primary
- optimization over dallocx() is the removal of a metadata read, which often
- suffers an L1 cache miss.
- - Add missing header includes in jemalloc/jemalloc.h, so that applications
- only have to #include <jemalloc/jemalloc.h>.
- - Add support for additional platforms:
- + Bitrig
- + Cygwin
- + DragonFlyBSD
- + iOS
- + OpenBSD
- + OpenRISC/or1k
-
- Optimizations:
- - Maintain dirty runs in per arena LRUs rather than in per arena trees of
- dirty-run-containing chunks. In practice this change significantly reduces
- dirty page purging volume.
- - Integrate whole chunks into the unused dirty page purging machinery. This
- reduces the cost of repeated huge allocation/deallocation, because it
- effectively introduces a cache of chunks.
- - Split the arena chunk map into two separate arrays, in order to increase
- cache locality for the frequently accessed bits.
- - Move small run metadata out of runs, into arena chunk headers. This reduces
- run fragmentation, smaller runs reduce external fragmentation for small size
- classes, and packed (less uniformly aligned) metadata layout improves CPU
- cache set distribution.
- - Randomly distribute large allocation base pointer alignment relative to page
- boundaries in order to more uniformly utilize CPU cache sets. This can be
- disabled via the --disable-cache-oblivious configure option, and queried via
- the "config.cache_oblivious" mallctl.
- - Micro-optimize the fast paths for the public API functions.
- - Refactor thread-specific data to reside in a single structure. This assures
- that only a single TLS read is necessary per call into the public API.
- - Implement in-place huge allocation growing and shrinking.
- - Refactor rtree (radix tree for chunk lookups) to be lock-free, and make
- additional optimizations that reduce maximum lookup depth to one or two
- levels. This resolves what was a concurrency bottleneck for per arena huge
- allocation, because a global data structure is critical for determining
- which arenas own which huge allocations.
-
- Incompatible changes:
- - Replace --enable-cc-silence with --disable-cc-silence to suppress spurious
- warnings by default.
- - Assure that the constness of malloc_usable_size()'s return type matches that
- of the system implementation.
- - Change the heap profile dump format to support per thread heap profiling,
- rename pprof to jeprof, and enhance it with the --thread=<n> option. As a
- result, the bundled jeprof must now be used rather than the upstream
- (gperftools) pprof.
- - Disable "opt.prof_final" by default, in order to avoid atexit(3), which can
- internally deadlock on some platforms.
- - Change the "arenas.nlruns" mallctl type from size_t to unsigned.
- - Replace the "stats.arenas.<i>.bins.<j>.allocated" mallctl with
- "stats.arenas.<i>.bins.<j>.curregs".
- - Ignore MALLOC_CONF in set{uid,gid,cap} binaries.
- - Ignore MALLOCX_ARENA(a) in dallocx(), in favor of using the
- MALLOCX_TCACHE(tc) and MALLOCX_TCACHE_NONE flags to control tcache usage.
-
- Removed features:
- - Remove the *allocm() API, which is superseded by the *allocx() API.
- - Remove the --enable-dss options, and make dss non-optional on all platforms
- which support sbrk(2).
- - Remove the "arenas.purge" mallctl, which was obsoleted by the
- "arena.<i>.purge" mallctl in 3.1.0.
- - Remove the unnecessary "opt.valgrind" mallctl; jemalloc automatically
- detects whether it is running inside Valgrind.
- - Remove the "stats.huge.allocated", "stats.huge.nmalloc", and
- "stats.huge.ndalloc" mallctls.
- - Remove the --enable-mremap option.
- - Remove the "stats.chunks.current", "stats.chunks.total", and
- "stats.chunks.high" mallctls.
-
- Bug fixes:
- - Fix the cactive statistic to decrease (rather than increase) when active
- memory decreases. This regression was first released in 3.5.0.
- - Fix OOM handling in memalign() and valloc(). A variant of this bug existed
- in all releases since 2.0.0, which introduced these functions.
- - Fix an OOM-related regression in arena_tcache_fill_small(), which could
- cause cache corruption on OOM. This regression was present in all releases
- from 2.2.0 through 3.6.0.
- - Fix size class overflow handling for malloc(), posix_memalign(), memalign(),
- calloc(), and realloc() when profiling is enabled.
- - Fix the "arena.<i>.dss" mallctl to return an error if "primary" or
- "secondary" precedence is specified, but sbrk(2) is not supported.
- - Fix fallback lg_floor() implementations to handle extremely large inputs.
- - Ensure the default purgeable zone is after the default zone on OS X.
- - Fix latent bugs in atomic_*().
- - Fix the "arena.<i>.dss" mallctl to handle read-only calls.
- - Fix tls_model configuration to enable the initial-exec model when possible.
- - Mark malloc_conf as a weak symbol so that the application can override it.
- - Correctly detect glibc's adaptive pthread mutexes.
- - Fix the --without-export configure option.
-
-* 3.6.0 (March 31, 2014)
-
- This version contains a critical bug fix for a regression present in 3.5.0 and
- 3.5.1.
-
- Bug fixes:
- - Fix a regression in arena_chunk_alloc() that caused crashes during
- small/large allocation if chunk allocation failed. In the absence of this
- bug, chunk allocation failure would result in allocation failure, e.g. NULL
- return from malloc(). This regression was introduced in 3.5.0.
- - Fix backtracing for gcc intrinsics-based backtracing by specifying
- -fno-omit-frame-pointer to gcc. Note that the application (and all the
- libraries it links to) must also be compiled with this option for
- backtracing to be reliable.
- - Use dss allocation precedence for huge allocations as well as small/large
- allocations.
- - Fix test assertion failure message formatting. This bug did not manifest on
- x86_64 systems because of implementation subtleties in va_list.
- - Fix inconsequential test failures for hash and SFMT code.
-
- New features:
- - Support heap profiling on FreeBSD. This feature depends on the proc
- filesystem being mounted during heap profile dumping.
-
-* 3.5.1 (February 25, 2014)
-
- This version primarily addresses minor bugs in test code.
-
- Bug fixes:
- - Configure Solaris/Illumos to use MADV_FREE.
- - Fix junk filling for mremap(2)-based huge reallocation. This is only
- relevant if configuring with the --enable-mremap option specified.
- - Avoid compilation failure if 'restrict' C99 keyword is not supported by the
- compiler.
- - Add a configure test for SSE2 rather than assuming it is usable on i686
- systems. This fixes test compilation errors, especially on 32-bit Linux
- systems.
- - Fix mallctl argument size mismatches (size_t vs. uint64_t) in the stats unit
- test.
- - Fix/remove flawed alignment-related overflow tests.
- - Prevent compiler optimizations that could change backtraces in the
- prof_accum unit test.
-
-* 3.5.0 (January 22, 2014)
-
- This version focuses on refactoring and automated testing, though it also
- includes some non-trivial heap profiling optimizations not mentioned below.
-
- New features:
- - Add the *allocx() API, which is a successor to the experimental *allocm()
- API. The *allocx() functions are slightly simpler to use because they have
- fewer parameters, they directly return the results of primary interest, and
- mallocx()/rallocx() avoid the strict aliasing pitfall that
- allocm()/rallocm() share with posix_memalign(). Note that *allocm() is
- slated for removal in the next non-bugfix release.
- - Add support for LinuxThreads.
-
- Bug fixes:
- - Unless heap profiling is enabled, disable floating point code and don't link
- with libm. This, in combination with e.g. EXTRA_CFLAGS=-mno-sse on x64
- systems, makes it possible to completely disable floating point register
- use. Some versions of glibc neglect to save/restore caller-saved floating
- point registers during dynamic lazy symbol loading, and the symbol loading
- code uses whatever malloc the application happens to have linked/loaded
- with, the result being potential floating point register corruption.
- - Report ENOMEM rather than EINVAL if an OOM occurs during heap profiling
- backtrace creation in imemalign(). This bug impacted posix_memalign() and
- aligned_alloc().
- - Fix a file descriptor leak in a prof_dump_maps() error path.
- - Fix prof_dump() to close the dump file descriptor for all relevant error
- paths.
- - Fix rallocm() to use the arena specified by the ALLOCM_ARENA(s) flag for
- allocation, not just deallocation.
- - Fix a data race for large allocation stats counters.
- - Fix a potential infinite loop during thread exit. This bug occurred on
- Solaris, and could affect other platforms with similar pthreads TSD
- implementations.
- - Don't junk-fill reallocations unless usable size changes. This fixes a
- violation of the *allocx()/*allocm() semantics.
- - Fix growing large reallocation to junk fill new space.
- - Fix huge deallocation to junk fill when munmap is disabled.
- - Change the default private namespace prefix from empty to je_, and change
- --with-private-namespace-prefix so that it prepends an additional prefix
- rather than replacing je_. This reduces the likelihood of applications
- which statically link jemalloc experiencing symbol name collisions.
- - Add missing private namespace mangling (relevant when
- --with-private-namespace is specified).
- - Add and use JEMALLOC_INLINE_C so that static inline functions are marked as
- static even for debug builds.
- - Add a missing mutex unlock in a malloc_init_hard() error path. In practice
- this error path is never executed.
- - Fix numerous bugs in malloc_strotumax() error handling/reporting. These
- bugs had no impact except for malformed inputs.
- - Fix numerous bugs in malloc_snprintf(). These bugs were not exercised by
- existing calls, so they had no impact.
-
-* 3.4.1 (October 20, 2013)
-
- Bug fixes:
- - Fix a race in the "arenas.extend" mallctl that could cause memory corruption
- of internal data structures and subsequent crashes.
- - Fix Valgrind integration flaws that caused Valgrind warnings about reads of
- uninitialized memory in:
- + arena chunk headers
- + internal zero-initialized data structures (relevant to tcache and prof
- code)
- - Preserve errno during the first allocation. A readlink(2) call during
- initialization fails unless /etc/malloc.conf exists, so errno was typically
- set during the first allocation prior to this fix.
- - Fix compilation warnings reported by gcc 4.8.1.
-
-* 3.4.0 (June 2, 2013)
-
- This version is essentially a small bugfix release, but the addition of
- aarch64 support requires that the minor version be incremented.
-
- Bug fixes:
- - Fix race-triggered deadlocks in chunk_record(). These deadlocks were
- typically triggered by multiple threads concurrently deallocating huge
- objects.
-
- New features:
- - Add support for the aarch64 architecture.
-
-* 3.3.1 (March 6, 2013)
-
- This version fixes bugs that are typically encountered only when utilizing
- custom run-time options.
-
- Bug fixes:
- - Fix a locking order bug that could cause deadlock during fork if heap
- profiling were enabled.
- - Fix a chunk recycling bug that could cause the allocator to lose track of
- whether a chunk was zeroed. On FreeBSD, NetBSD, and OS X, it could cause
- corruption if allocating via sbrk(2) (unlikely unless running with the
- "dss:primary" option specified). This was completely harmless on Linux
- unless using mlockall(2) (and unlikely even then, unless the
- --disable-munmap configure option or the "dss:primary" option was
- specified). This regression was introduced in 3.1.0 by the
- mlockall(2)/madvise(2) interaction fix.
- - Fix TLS-related memory corruption that could occur during thread exit if the
- thread never allocated memory. Only the quarantine and prof facilities were
- susceptible.
- - Fix two quarantine bugs:
- + Internal reallocation of the quarantined object array leaked the old
- array.
- + Reallocation failure for internal reallocation of the quarantined object
- array (very unlikely) resulted in memory corruption.
- - Fix Valgrind integration to annotate all internally allocated memory in a
- way that keeps Valgrind happy about internal data structure access.
- - Fix building for s390 systems.
-
-* 3.3.0 (January 23, 2013)
-
- This version includes a few minor performance improvements in addition to the
- listed new features and bug fixes.
-
- New features:
- - Add clipping support to lg_chunk option processing.
- - Add the --enable-ivsalloc option.
- - Add the --without-export option.
- - Add the --disable-zone-allocator option.
-
- Bug fixes:
- - Fix "arenas.extend" mallctl to output the number of arenas.
- - Fix chunk_recycle() to unconditionally inform Valgrind that returned memory
- is undefined.
- - Fix build break on FreeBSD related to alloca.h.
-
-* 3.2.0 (November 9, 2012)
-
- In addition to a couple of bug fixes, this version modifies page run
- allocation and dirty page purging algorithms in order to better control
- page-level virtual memory fragmentation.
-
- Incompatible changes:
- - Change the "opt.lg_dirty_mult" default from 5 to 3 (32:1 to 8:1).
-
- Bug fixes:
- - Fix dss/mmap allocation precedence code to use recyclable mmap memory only
- after primary dss allocation fails.
- - Fix deadlock in the "arenas.purge" mallctl. This regression was introduced
- in 3.1.0 by the addition of the "arena.<i>.purge" mallctl.
-
-* 3.1.0 (October 16, 2012)
-
- New features:
- - Auto-detect whether running inside Valgrind, thus removing the need to
- manually specify MALLOC_CONF=valgrind:true.
- - Add the "arenas.extend" mallctl, which allows applications to create
- manually managed arenas.
- - Add the ALLOCM_ARENA() flag for {,r,d}allocm().
- - Add the "opt.dss", "arena.<i>.dss", and "stats.arenas.<i>.dss" mallctls,
- which provide control over dss/mmap precedence.
- - Add the "arena.<i>.purge" mallctl, which obsoletes "arenas.purge".
- - Define LG_QUANTUM for hppa.
-
- Incompatible changes:
- - Disable tcache by default if running inside Valgrind, in order to avoid
- making unallocated objects appear reachable to Valgrind.
- - Drop const from malloc_usable_size() argument on Linux.
-
- Bug fixes:
- - Fix heap profiling crash if sampled object is freed via realloc(p, 0).
- - Remove const from __*_hook variable declarations, so that glibc can modify
- them during process forking.
- - Fix mlockall(2)/madvise(2) interaction.
- - Fix fork(2)-related deadlocks.
- - Fix error return value for "thread.tcache.enabled" mallctl.
-
-* 3.0.0 (May 11, 2012)
-
- Although this version adds some major new features, the primary focus is on
- internal code cleanup that facilitates maintainability and portability, most
- of which is not reflected in the ChangeLog. This is the first release to
- incorporate substantial contributions from numerous other developers, and the
- result is a more broadly useful allocator (see the git revision history for
- contribution details). Note that the license has been unified, thanks to
- Facebook granting a license under the same terms as the other copyright
- holders (see COPYING).
-
- New features:
- - Implement Valgrind support, redzones, and quarantine.
- - Add support for additional platforms:
- + FreeBSD
- + Mac OS X Lion
- + MinGW
- + Windows (no support yet for replacing the system malloc)
- - Add support for additional architectures:
- + MIPS
- + SH4
- + Tilera
- - Add support for cross compiling.
- - Add nallocm(), which rounds a request size up to the nearest size class
- without actually allocating.
- - Implement aligned_alloc() (blame C11).
- - Add the "thread.tcache.enabled" mallctl.
- - Add the "opt.prof_final" mallctl.
- - Update pprof (from gperftools 2.0).
- - Add the --with-mangling option.
- - Add the --disable-experimental option.
- - Add the --disable-munmap option, and make it the default on Linux.
- - Add the --enable-mremap option, which disables use of mremap(2) by default.
-
- Incompatible changes:
- - Enable stats by default.
- - Enable fill by default.
- - Disable lazy locking by default.
- - Rename the "tcache.flush" mallctl to "thread.tcache.flush".
- - Rename the "arenas.pagesize" mallctl to "arenas.page".
- - Change the "opt.lg_prof_sample" default from 0 to 19 (1 B to 512 KiB).
- - Change the "opt.prof_accum" default from true to false.
-
- Removed features:
- - Remove the swap feature, including the "config.swap", "swap.avail",
- "swap.prezeroed", "swap.nfds", and "swap.fds" mallctls.
- - Remove highruns statistics, including the
- "stats.arenas.<i>.bins.<j>.highruns" and
- "stats.arenas.<i>.lruns.<j>.highruns" mallctls.
- - As part of small size class refactoring, remove the "opt.lg_[qc]space_max",
- "arenas.cacheline", "arenas.subpage", "arenas.[tqcs]space_{min,max}", and
- "arenas.[tqcs]bins" mallctls.
- - Remove the "arenas.chunksize" mallctl.
- - Remove the "opt.lg_prof_tcmax" option.
- - Remove the "opt.lg_prof_bt_max" option.
- - Remove the "opt.lg_tcache_gc_sweep" option.
- - Remove the --disable-tiny option, including the "config.tiny" mallctl.
- - Remove the --enable-dynamic-page-shift configure option.
- - Remove the --enable-sysv configure option.
-
- Bug fixes:
- - Fix a statistics-related bug in the "thread.arena" mallctl that could cause
- invalid statistics and crashes.
- - Work around TLS deallocation via free() on Linux. This bug could cause
- write-after-free memory corruption.
- - Fix a potential deadlock that could occur during interval- and
- growth-triggered heap profile dumps.
- - Fix large calloc() zeroing bugs due to dropping chunk map unzeroed flags.
- - Fix chunk_alloc_dss() to stop claiming memory is zeroed. This bug could
- cause memory corruption and crashes with --enable-dss specified.
- - Fix fork-related bugs that could cause deadlock in children between fork
- and exec.
- - Fix malloc_stats_print() to honor 'b' and 'l' in the opts parameter.
- - Fix realloc(p, 0) to act like free(p).
- - Do not enforce minimum alignment in memalign().
- - Check for NULL pointer in malloc_usable_size().
- - Fix an off-by-one heap profile statistics bug that could be observed in
- interval- and growth-triggered heap profiles.
- - Fix the "epoch" mallctl to update cached stats even if the passed in epoch
- is 0.
- - Fix bin->runcur management to fix a layout policy bug. This bug did not
- affect correctness.
- - Fix a bug in choose_arena_hard() that potentially caused more arenas to be
- initialized than necessary.
- - Add missing "opt.lg_tcache_max" mallctl implementation.
- - Use glibc allocator hooks to make mixed allocator usage less likely.
- - Fix build issues for --disable-tcache.
- - Don't mangle pthread_create() when --with-private-namespace is specified.
-
-* 2.2.5 (November 14, 2011)
-
- Bug fixes:
- - Fix huge_ralloc() race when using mremap(2). This is a serious bug that
- could cause memory corruption and/or crashes.
- - Fix huge_ralloc() to maintain chunk statistics.
- - Fix malloc_stats_print(..., "a") output.
-
-* 2.2.4 (November 5, 2011)
-
- Bug fixes:
- - Initialize arenas_tsd before using it. This bug existed for 2.2.[0-3], as
- well as for --disable-tls builds in earlier releases.
- - Do not assume a 4 KiB page size in test/rallocm.c.
-
-* 2.2.3 (August 31, 2011)
-
- This version fixes numerous bugs related to heap profiling.
-
- Bug fixes:
- - Fix a prof-related race condition. This bug could cause memory corruption,
- but only occurred in non-default configurations (prof_accum:false).
- - Fix off-by-one backtracing issues (make sure that prof_alloc_prep() is
- excluded from backtraces).
- - Fix a prof-related bug in realloc() (only triggered by OOM errors).
- - Fix prof-related bugs in allocm() and rallocm().
- - Fix prof_tdata_cleanup() for --disable-tls builds.
- - Fix a relative include path, to fix objdir builds.
-
-* 2.2.2 (July 30, 2011)
-
- Bug fixes:
- - Fix a build error for --disable-tcache.
- - Fix assertions in arena_purge() (for real this time).
- - Add the --with-private-namespace option. This is a workaround for symbol
- conflicts that can inadvertently arise when using static libraries.
-
-* 2.2.1 (March 30, 2011)
-
- Bug fixes:
- - Implement atomic operations for x86/x64. This fixes compilation failures
- for versions of gcc that are still in wide use.
- - Fix an assertion in arena_purge().
-
-* 2.2.0 (March 22, 2011)
-
- This version incorporates several improvements to algorithms and data
- structures that tend to reduce fragmentation and increase speed.
-
- New features:
- - Add the "stats.cactive" mallctl.
- - Update pprof (from google-perftools 1.7).
- - Improve backtracing-related configuration logic, and add the
- --disable-prof-libgcc option.
-
- Bug fixes:
- - Change default symbol visibility from "internal", to "hidden", which
- decreases the overhead of library-internal function calls.
- - Fix symbol visibility so that it is also set on OS X.
- - Fix a build dependency regression caused by the introduction of the .pic.o
- suffix for PIC object files.
- - Add missing checks for mutex initialization failures.
- - Don't use libgcc-based backtracing except on x64, where it is known to work.
- - Fix deadlocks on OS X that were due to memory allocation in
- pthread_mutex_lock().
- - Heap profiling-specific fixes:
- + Fix memory corruption due to integer overflow in small region index
- computation, when using a small enough sample interval that profiling
- context pointers are stored in small run headers.
- + Fix a bootstrap ordering bug that only occurred with TLS disabled.
- + Fix a rallocm() rsize bug.
- + Fix error detection bugs for aligned memory allocation.
-
-* 2.1.3 (March 14, 2011)
-
- Bug fixes:
- - Fix a cpp logic regression (due to the "thread.{de,}allocatedp" mallctl fix
- for OS X in 2.1.2).
- - Fix a "thread.arena" mallctl bug.
- - Fix a thread cache stats merging bug.
-
-* 2.1.2 (March 2, 2011)
-
- Bug fixes:
- - Fix "thread.{de,}allocatedp" mallctl for OS X.
- - Add missing jemalloc.a to build system.
-
-* 2.1.1 (January 31, 2011)
-
- Bug fixes:
- - Fix aligned huge reallocation (affected allocm()).
- - Fix the ALLOCM_LG_ALIGN macro definition.
- - Fix a heap dumping deadlock.
- - Fix a "thread.arena" mallctl bug.
-
-* 2.1.0 (December 3, 2010)
-
- This version incorporates some optimizations that can't quite be considered
- bug fixes.
-
- New features:
- - Use Linux's mremap(2) for huge object reallocation when possible.
- - Avoid locking in mallctl*() when possible.
- - Add the "thread.[de]allocatedp" mallctl's.
- - Convert the manual page source from roff to DocBook, and generate both roff
- and HTML manuals.
-
- Bug fixes:
- - Fix a crash due to incorrect bootstrap ordering. This only impacted
- --enable-debug --enable-dss configurations.
- - Fix a minor statistics bug for mallctl("swap.avail", ...).
-
-* 2.0.1 (October 29, 2010)
-
- Bug fixes:
- - Fix a race condition in heap profiling that could cause undefined behavior
- if "opt.prof_accum" were disabled.
- - Add missing mutex unlocks for some OOM error paths in the heap profiling
- code.
- - Fix a compilation error for non-C99 builds.
-
-* 2.0.0 (October 24, 2010)
-
- This version focuses on the experimental *allocm() API, and on improved
- run-time configuration/introspection. Nonetheless, numerous performance
- improvements are also included.
-
- New features:
- - Implement the experimental {,r,s,d}allocm() API, which provides a superset
- of the functionality available via malloc(), calloc(), posix_memalign(),
- realloc(), malloc_usable_size(), and free(). These functions can be used to
- allocate/reallocate aligned zeroed memory, ask for optional extra memory
- during reallocation, prevent object movement during reallocation, etc.
- - Replace JEMALLOC_OPTIONS/JEMALLOC_PROF_PREFIX with MALLOC_CONF, which is
- more human-readable, and more flexible. For example:
- JEMALLOC_OPTIONS=AJP
- is now:
- MALLOC_CONF=abort:true,fill:true,stats_print:true
- - Port to Apple OS X. Sponsored by Mozilla.
- - Make it possible for the application to control thread-->arena mappings via
- the "thread.arena" mallctl.
- - Add compile-time support for all TLS-related functionality via pthreads TSD.
- This is mainly of interest for OS X, which does not support TLS, but has a
- TSD implementation with similar performance.
- - Override memalign() and valloc() if they are provided by the system.
- - Add the "arenas.purge" mallctl, which can be used to synchronously purge all
- dirty unused pages.
- - Make cumulative heap profiling data optional, so that it is possible to
- limit the amount of memory consumed by heap profiling data structures.
- - Add per thread allocation counters that can be accessed via the
- "thread.allocated" and "thread.deallocated" mallctls.
-
- Incompatible changes:
- - Remove JEMALLOC_OPTIONS and malloc_options (see MALLOC_CONF above).
- - Increase default backtrace depth from 4 to 128 for heap profiling.
- - Disable interval-based profile dumps by default.
-
- Bug fixes:
- - Remove bad assertions in fork handler functions. These assertions could
- cause aborts for some combinations of configure settings.
- - Fix strerror_r() usage to deal with non-standard semantics in GNU libc.
- - Fix leak context reporting. This bug tended to cause the number of contexts
- to be underreported (though the reported number of objects and bytes were
- correct).
- - Fix a realloc() bug for large in-place growing reallocation. This bug could
- cause memory corruption, but it was hard to trigger.
- - Fix an allocation bug for small allocations that could be triggered if
- multiple threads raced to create a new run of backing pages.
- - Enhance the heap profiler to trigger samples based on usable size, rather
- than request size.
- - Fix a heap profiling bug due to sometimes losing track of requested object
- size for sampled objects.
-
-* 1.0.3 (August 12, 2010)
-
- Bug fixes:
- - Fix the libunwind-based implementation of stack backtracing (used for heap
- profiling). This bug could cause zero-length backtraces to be reported.
- - Add a missing mutex unlock in library initialization code. If multiple
- threads raced to initialize malloc, some of them could end up permanently
- blocked.
-
-* 1.0.2 (May 11, 2010)
-
- Bug fixes:
- - Fix junk filling of large objects, which could cause memory corruption.
- - Add MAP_NORESERVE support for chunk mapping, because otherwise virtual
- memory limits could cause swap file configuration to fail. Contributed by
- Jordan DeLong.
-
-* 1.0.1 (April 14, 2010)
-
- Bug fixes:
- - Fix compilation when --enable-fill is specified.
- - Fix threads-related profiling bugs that affected accuracy and caused memory
- to be leaked during thread exit.
- - Fix dirty page purging race conditions that could cause crashes.
- - Fix crash in tcache flushing code during thread destruction.
-
-* 1.0.0 (April 11, 2010)
-
- This release focuses on speed and run-time introspection. Numerous
- algorithmic improvements make this release substantially faster than its
- predecessors.
-
- New features:
- - Implement autoconf-based configuration system.
- - Add mallctl*(), for the purposes of introspection and run-time
- configuration.
- - Make it possible for the application to manually flush a thread's cache, via
- the "tcache.flush" mallctl.
- - Base maximum dirty page count on proportion of active memory.
- - Compute various additional run-time statistics, including per size class
- statistics for large objects.
- - Expose malloc_stats_print(), which can be called repeatedly by the
- application.
- - Simplify the malloc_message() signature to only take one string argument,
- and incorporate an opaque data pointer argument for use by the application
- in combination with malloc_stats_print().
- - Add support for allocation backed by one or more swap files, and allow the
- application to disable over-commit if swap files are in use.
- - Implement allocation profiling and leak checking.
-
- Removed features:
- - Remove the dynamic arena rebalancing code, since thread-specific caching
- reduces its utility.
-
- Bug fixes:
- - Modify chunk allocation to work when address space layout randomization
- (ASLR) is in use.
- - Fix thread cleanup bugs related to TLS destruction.
- - Handle 0-size allocation requests in posix_memalign().
- - Fix a chunk leak. The leaked chunks were never touched, so this impacted
- virtual memory usage, but not physical memory usage.
-
-* linux_2008082[78]a (August 27/28, 2008)
-
- These snapshot releases are the simple result of incorporating Linux-specific
- support into the FreeBSD malloc sources.
-
---------------------------------------------------------------------------------
-vim:filetype=text:textwidth=80
diff --git a/memory/jemalloc/src/INSTALL b/memory/jemalloc/src/INSTALL
deleted file mode 100644
index 687871653..000000000
--- a/memory/jemalloc/src/INSTALL
+++ /dev/null
@@ -1,414 +0,0 @@
-Building and installing a packaged release of jemalloc can be as simple as
-typing the following while in the root directory of the source tree:
-
- ./configure
- make
- make install
-
-If building from unpackaged developer sources, the simplest command sequence
-that might work is:
-
- ./autogen.sh
- make dist
- make
- make install
-
-Note that documentation is not built by the default target because doing so
-would create a dependency on xsltproc in packaged releases, hence the
-requirement to either run 'make dist' or avoid installing docs via the various
-install_* targets documented below.
-
-=== Advanced configuration =====================================================
-
-The 'configure' script supports numerous options that allow control of which
-functionality is enabled, where jemalloc is installed, etc. Optionally, pass
-any of the following arguments (not a definitive list) to 'configure':
-
---help
- Print a definitive list of options.
-
---prefix=<install-root-dir>
- Set the base directory in which to install. For example:
-
- ./configure --prefix=/usr/local
-
- will cause files to be installed into /usr/local/include, /usr/local/lib,
- and /usr/local/man.
-
---with-version=<major>.<minor>.<bugfix>-<nrev>-g<gid>
- Use the specified version string rather than trying to generate one (if in
- a git repository) or use existing the VERSION file (if present).
-
---with-rpath=<colon-separated-rpath>
- Embed one or more library paths, so that libjemalloc can find the libraries
- it is linked to. This works only on ELF-based systems.
-
---with-mangling=<map>
- Mangle public symbols specified in <map> which is a comma-separated list of
- name:mangled pairs.
-
- For example, to use ld's --wrap option as an alternative method for
- overriding libc's malloc implementation, specify something like:
-
- --with-mangling=malloc:__wrap_malloc,free:__wrap_free[...]
-
- Note that mangling happens prior to application of the prefix specified by
- --with-jemalloc-prefix, and mangled symbols are then ignored when applying
- the prefix.
-
---with-jemalloc-prefix=<prefix>
- Prefix all public APIs with <prefix>. For example, if <prefix> is
- "prefix_", API changes like the following occur:
-
- malloc() --> prefix_malloc()
- malloc_conf --> prefix_malloc_conf
- /etc/malloc.conf --> /etc/prefix_malloc.conf
- MALLOC_CONF --> PREFIX_MALLOC_CONF
-
- This makes it possible to use jemalloc at the same time as the system
- allocator, or even to use multiple copies of jemalloc simultaneously.
-
- By default, the prefix is "", except on OS X, where it is "je_". On OS X,
- jemalloc overlays the default malloc zone, but makes no attempt to actually
- replace the "malloc", "calloc", etc. symbols.
-
---without-export
- Don't export public APIs. This can be useful when building jemalloc as a
- static library, or to avoid exporting public APIs when using the zone
- allocator on OSX.
-
---with-private-namespace=<prefix>
- Prefix all library-private APIs with <prefix>je_. For shared libraries,
- symbol visibility mechanisms prevent these symbols from being exported, but
- for static libraries, naming collisions are a real possibility. By
- default, <prefix> is empty, which results in a symbol prefix of je_ .
-
---with-install-suffix=<suffix>
- Append <suffix> to the base name of all installed files, such that multiple
- versions of jemalloc can coexist in the same installation directory. For
- example, libjemalloc.so.0 becomes libjemalloc<suffix>.so.0.
-
---with-malloc-conf=<malloc_conf>
- Embed <malloc_conf> as a run-time options string that is processed prior to
- the malloc_conf global variable, the /etc/malloc.conf symlink, and the
- MALLOC_CONF environment variable. For example, to change the default chunk
- size to 256 KiB:
-
- --with-malloc-conf=lg_chunk:18
-
---disable-cc-silence
- Disable code that silences non-useful compiler warnings. This is mainly
- useful during development when auditing the set of warnings that are being
- silenced.
-
---enable-debug
- Enable assertions and validation code. This incurs a substantial
- performance hit, but is very useful during application development.
- Implies --enable-ivsalloc.
-
---enable-code-coverage
- Enable code coverage support, for use during jemalloc test development.
- Additional testing targets are available if this option is enabled:
-
- coverage
- coverage_unit
- coverage_integration
- coverage_stress
-
- These targets do not clear code coverage results from previous runs, and
- there are interactions between the various coverage targets, so it is
- usually advisable to run 'make clean' between repeated code coverage runs.
-
---disable-stats
- Disable statistics gathering functionality. See the "opt.stats_print"
- option documentation for usage details.
-
---enable-ivsalloc
- Enable validation code, which verifies that pointers reside within
- jemalloc-owned chunks before dereferencing them. This incurs a minor
- performance hit.
-
---enable-prof
- Enable heap profiling and leak detection functionality. See the "opt.prof"
- option documentation for usage details. When enabled, there are several
- approaches to backtracing, and the configure script chooses the first one
- in the following list that appears to function correctly:
-
- + libunwind (requires --enable-prof-libunwind)
- + libgcc (unless --disable-prof-libgcc)
- + gcc intrinsics (unless --disable-prof-gcc)
-
---enable-prof-libunwind
- Use the libunwind library (http://www.nongnu.org/libunwind/) for stack
- backtracing.
-
---disable-prof-libgcc
- Disable the use of libgcc's backtracing functionality.
-
---disable-prof-gcc
- Disable the use of gcc intrinsics for backtracing.
-
---with-static-libunwind=<libunwind.a>
- Statically link against the specified libunwind.a rather than dynamically
- linking with -lunwind.
-
---disable-tcache
- Disable thread-specific caches for small objects. Objects are cached and
- released in bulk, thus reducing the total number of mutex operations. See
- the "opt.tcache" option for usage details.
-
---disable-munmap
- Disable virtual memory deallocation via munmap(2); instead keep track of
- the virtual memory for later use. munmap() is disabled by default (i.e.
- --disable-munmap is implied) on Linux, which has a quirk in its virtual
- memory allocation algorithm that causes semi-permanent VM map holes under
- normal jemalloc operation.
-
---disable-fill
- Disable support for junk/zero filling of memory, quarantine, and redzones.
- See the "opt.junk", "opt.zero", "opt.quarantine", and "opt.redzone" option
- documentation for usage details.
-
---disable-valgrind
- Disable support for Valgrind.
-
---disable-zone-allocator
- Disable zone allocator for Darwin. This means jemalloc won't be hooked as
- the default allocator on OSX/iOS.
-
---enable-utrace
- Enable utrace(2)-based allocation tracing. This feature is not broadly
- portable (FreeBSD has it, but Linux and OS X do not).
-
---enable-xmalloc
- Enable support for optional immediate termination due to out-of-memory
- errors, as is commonly implemented by "xmalloc" wrapper function for malloc.
- See the "opt.xmalloc" option documentation for usage details.
-
---enable-lazy-lock
- Enable code that wraps pthread_create() to detect when an application
- switches from single-threaded to multi-threaded mode, so that it can avoid
- mutex locking/unlocking operations while in single-threaded mode. In
- practice, this feature usually has little impact on performance unless
- thread-specific caching is disabled.
-
---disable-tls
- Disable thread-local storage (TLS), which allows for fast access to
- thread-local variables via the __thread keyword. If TLS is available,
- jemalloc uses it for several purposes.
-
---disable-cache-oblivious
- Disable cache-oblivious large allocation alignment for large allocation
- requests with no alignment constraints. If this feature is disabled, all
- large allocations are page-aligned as an implementation artifact, which can
- severely harm CPU cache utilization. However, the cache-oblivious layout
- comes at the cost of one extra page per large allocation, which in the
- most extreme case increases physical memory usage for the 16 KiB size class
- to 20 KiB.
-
---with-xslroot=<path>
- Specify where to find DocBook XSL stylesheets when building the
- documentation.
-
---with-lg-page=<lg-page>
- Specify the base 2 log of the system page size. This option is only useful
- when cross compiling, since the configure script automatically determines
- the host's page size by default.
-
---with-lg-page-sizes=<lg-page-sizes>
- Specify the comma-separated base 2 logs of the page sizes to support. This
- option may be useful when cross-compiling in combination with
- --with-lg-page, but its primary use case is for integration with FreeBSD's
- libc, wherein jemalloc is embedded.
-
---with-lg-size-class-group=<lg-size-class-group>
- Specify the base 2 log of how many size classes to use for each doubling in
- size. By default jemalloc uses <lg-size-class-group>=2, which results in
- e.g. the following size classes:
-
- [...], 64,
- 80, 96, 112, 128,
- 160, [...]
-
- <lg-size-class-group>=3 results in e.g. the following size classes:
-
- [...], 64,
- 72, 80, 88, 96, 104, 112, 120, 128,
- 144, [...]
-
- The minimal <lg-size-class-group>=0 causes jemalloc to only provide size
- classes that are powers of 2:
-
- [...],
- 64,
- 128,
- 256,
- [...]
-
- An implementation detail currently limits the total number of small size
- classes to 255, and a compilation error will result if the
- <lg-size-class-group> you specify cannot be supported. The limit is
- roughly <lg-size-class-group>=4, depending on page size.
-
---with-lg-quantum=<lg-quantum>
- Specify the base 2 log of the minimum allocation alignment. jemalloc needs
- to know the minimum alignment that meets the following C standard
- requirement (quoted from the April 12, 2011 draft of the C11 standard):
-
- The pointer returned if the allocation succeeds is suitably aligned so
- that it may be assigned to a pointer to any type of object with a
- fundamental alignment requirement and then used to access such an object
- or an array of such objects in the space allocated [...]
-
- This setting is architecture-specific, and although jemalloc includes known
- safe values for the most commonly used modern architectures, there is a
- wrinkle related to GNU libc (glibc) that may impact your choice of
- <lg-quantum>. On most modern architectures, this mandates 16-byte alignment
- (<lg-quantum>=4), but the glibc developers chose not to meet this
- requirement for performance reasons. An old discussion can be found at
- https://sourceware.org/bugzilla/show_bug.cgi?id=206 . Unlike glibc,
- jemalloc does follow the C standard by default (caveat: jemalloc
- technically cheats if --with-lg-tiny-min is smaller than
- --with-lg-quantum), but the fact that Linux systems already work around
- this allocator noncompliance means that it is generally safe in practice to
- let jemalloc's minimum alignment follow glibc's lead. If you specify
- --with-lg-quantum=3 during configuration, jemalloc will provide additional
- size classes that are not 16-byte-aligned (24, 40, and 56, assuming
- --with-lg-size-class-group=2).
-
---with-lg-tiny-min=<lg-tiny-min>
- Specify the base 2 log of the minimum tiny size class to support. Tiny
- size classes are powers of 2 less than the quantum, and are only
- incorporated if <lg-tiny-min> is less than <lg-quantum> (see
- --with-lg-quantum). Tiny size classes technically violate the C standard
- requirement for minimum alignment, and crashes could conceivably result if
- the compiler were to generate instructions that made alignment assumptions,
- both because illegal instruction traps could result, and because accesses
- could straddle page boundaries and cause segmentation faults due to
- accessing unmapped addresses.
-
- The default of <lg-tiny-min>=3 works well in practice even on architectures
- that technically require 16-byte alignment, probably for the same reason
- --with-lg-quantum=3 works. Smaller tiny size classes can, and will, cause
- crashes (see https://bugzilla.mozilla.org/show_bug.cgi?id=691003 for an
- example).
-
- This option is rarely useful, and is mainly provided as documentation of a
- subtle implementation detail. If you do use this option, specify a
- value in [3, ..., <lg-quantum>].
-
-The following environment variables (not a definitive list) impact configure's
-behavior:
-
-CFLAGS="?"
- Pass these flags to the compiler. You probably shouldn't define this unless
- you know what you are doing. (Use EXTRA_CFLAGS instead.)
-
-EXTRA_CFLAGS="?"
- Append these flags to CFLAGS. This makes it possible to add flags such as
- -Werror, while allowing the configure script to determine what other flags
- are appropriate for the specified configuration.
-
- The configure script specifically checks whether an optimization flag (-O*)
- is specified in EXTRA_CFLAGS, and refrains from specifying an optimization
- level if it finds that one has already been specified.
-
-CPPFLAGS="?"
- Pass these flags to the C preprocessor. Note that CFLAGS is not passed to
- 'cpp' when 'configure' is looking for include files, so you must use
- CPPFLAGS instead if you need to help 'configure' find header files.
-
-LD_LIBRARY_PATH="?"
- 'ld' uses this colon-separated list to find libraries.
-
-LDFLAGS="?"
- Pass these flags when linking.
-
-PATH="?"
- 'configure' uses this to find programs.
-
-=== Advanced compilation =======================================================
-
-To build only parts of jemalloc, use the following targets:
-
- build_lib_shared
- build_lib_static
- build_lib
- build_doc_html
- build_doc_man
- build_doc
-
-To install only parts of jemalloc, use the following targets:
-
- install_bin
- install_include
- install_lib_shared
- install_lib_static
- install_lib
- install_doc_html
- install_doc_man
- install_doc
-
-To clean up build results to varying degrees, use the following make targets:
-
- clean
- distclean
- relclean
-
-=== Advanced installation ======================================================
-
-Optionally, define make variables when invoking make, including (not
-exclusively):
-
-INCLUDEDIR="?"
- Use this as the installation prefix for header files.
-
-LIBDIR="?"
- Use this as the installation prefix for libraries.
-
-MANDIR="?"
- Use this as the installation prefix for man pages.
-
-DESTDIR="?"
- Prepend DESTDIR to INCLUDEDIR, LIBDIR, DATADIR, and MANDIR. This is useful
- when installing to a different path than was specified via --prefix.
-
-CC="?"
- Use this to invoke the C compiler.
-
-CFLAGS="?"
- Pass these flags to the compiler.
-
-CPPFLAGS="?"
- Pass these flags to the C preprocessor.
-
-LDFLAGS="?"
- Pass these flags when linking.
-
-PATH="?"
- Use this to search for programs used during configuration and building.
-
-=== Development ================================================================
-
-If you intend to make non-trivial changes to jemalloc, use the 'autogen.sh'
-script rather than 'configure'. This re-generates 'configure', enables
-configuration dependency rules, and enables re-generation of automatically
-generated source files.
-
-The build system supports using an object directory separate from the source
-tree. For example, you can create an 'obj' directory, and from within that
-directory, issue configuration and build commands:
-
- autoconf
- mkdir obj
- cd obj
- ../configure --enable-autogen
- make
-
-=== Documentation ==============================================================
-
-The manual page is generated in both html and roff formats. Any web browser
-can be used to view the html manual. The roff manual page can be formatted
-prior to installation via the following command:
-
- nroff -man -t doc/jemalloc.3
diff --git a/memory/jemalloc/src/Makefile.in b/memory/jemalloc/src/Makefile.in
deleted file mode 100644
index d13c7f108..000000000
--- a/memory/jemalloc/src/Makefile.in
+++ /dev/null
@@ -1,506 +0,0 @@
-# Clear out all vpaths, then set just one (default vpath) for the main build
-# directory.
-vpath
-vpath % .
-
-# Clear the default suffixes, so that built-in rules are not used.
-.SUFFIXES :
-
-SHELL := /bin/sh
-
-CC := @CC@
-
-# Configuration parameters.
-DESTDIR =
-BINDIR := $(DESTDIR)@BINDIR@
-INCLUDEDIR := $(DESTDIR)@INCLUDEDIR@
-LIBDIR := $(DESTDIR)@LIBDIR@
-DATADIR := $(DESTDIR)@DATADIR@
-MANDIR := $(DESTDIR)@MANDIR@
-srcroot := @srcroot@
-objroot := @objroot@
-abs_srcroot := @abs_srcroot@
-abs_objroot := @abs_objroot@
-
-# Build parameters.
-CPPFLAGS := @CPPFLAGS@ -I$(srcroot)include -I$(objroot)include
-EXTRA_CFLAGS := @EXTRA_CFLAGS@
-CFLAGS := @CFLAGS@ $(EXTRA_CFLAGS)
-LDFLAGS := @LDFLAGS@
-EXTRA_LDFLAGS := @EXTRA_LDFLAGS@
-LIBS := @LIBS@
-RPATH_EXTRA := @RPATH_EXTRA@
-SO := @so@
-IMPORTLIB := @importlib@
-O := @o@
-A := @a@
-EXE := @exe@
-LIBPREFIX := @libprefix@
-REV := @rev@
-install_suffix := @install_suffix@
-ABI := @abi@
-XSLTPROC := @XSLTPROC@
-AUTOCONF := @AUTOCONF@
-_RPATH = @RPATH@
-RPATH = $(if $(1),$(call _RPATH,$(1)))
-cfghdrs_in := $(addprefix $(srcroot),@cfghdrs_in@)
-cfghdrs_out := @cfghdrs_out@
-cfgoutputs_in := $(addprefix $(srcroot),@cfgoutputs_in@)
-cfgoutputs_out := @cfgoutputs_out@
-enable_autogen := @enable_autogen@
-enable_code_coverage := @enable_code_coverage@
-enable_prof := @enable_prof@
-enable_valgrind := @enable_valgrind@
-enable_zone_allocator := @enable_zone_allocator@
-MALLOC_CONF := @JEMALLOC_CPREFIX@MALLOC_CONF
-link_whole_archive := @link_whole_archive@
-DSO_LDFLAGS = @DSO_LDFLAGS@
-SOREV = @SOREV@
-PIC_CFLAGS = @PIC_CFLAGS@
-CTARGET = @CTARGET@
-LDTARGET = @LDTARGET@
-TEST_LD_MODE = @TEST_LD_MODE@
-MKLIB = @MKLIB@
-AR = @AR@
-ARFLAGS = @ARFLAGS@
-CC_MM = @CC_MM@
-LM := @LM@
-INSTALL = @INSTALL@
-
-ifeq (macho, $(ABI))
-TEST_LIBRARY_PATH := DYLD_FALLBACK_LIBRARY_PATH="$(objroot)lib"
-else
-ifeq (pecoff, $(ABI))
-TEST_LIBRARY_PATH := PATH="$(PATH):$(objroot)lib"
-else
-TEST_LIBRARY_PATH :=
-endif
-endif
-
-LIBJEMALLOC := $(LIBPREFIX)jemalloc$(install_suffix)
-
-# Lists of files.
-BINS := $(objroot)bin/jemalloc-config $(objroot)bin/jemalloc.sh $(objroot)bin/jeprof
-C_HDRS := $(objroot)include/jemalloc/jemalloc$(install_suffix).h
-C_SRCS := $(srcroot)src/jemalloc.c \
- $(srcroot)src/arena.c \
- $(srcroot)src/atomic.c \
- $(srcroot)src/base.c \
- $(srcroot)src/bitmap.c \
- $(srcroot)src/chunk.c \
- $(srcroot)src/chunk_dss.c \
- $(srcroot)src/chunk_mmap.c \
- $(srcroot)src/ckh.c \
- $(srcroot)src/ctl.c \
- $(srcroot)src/extent.c \
- $(srcroot)src/hash.c \
- $(srcroot)src/huge.c \
- $(srcroot)src/mb.c \
- $(srcroot)src/mutex.c \
- $(srcroot)src/nstime.c \
- $(srcroot)src/pages.c \
- $(srcroot)src/prng.c \
- $(srcroot)src/prof.c \
- $(srcroot)src/quarantine.c \
- $(srcroot)src/rtree.c \
- $(srcroot)src/stats.c \
- $(srcroot)src/spin.c \
- $(srcroot)src/tcache.c \
- $(srcroot)src/ticker.c \
- $(srcroot)src/tsd.c \
- $(srcroot)src/util.c \
- $(srcroot)src/witness.c
-ifeq ($(enable_valgrind), 1)
-C_SRCS += $(srcroot)src/valgrind.c
-endif
-ifeq ($(enable_zone_allocator), 1)
-C_SRCS += $(srcroot)src/zone.c
-endif
-ifeq ($(IMPORTLIB),$(SO))
-STATIC_LIBS := $(objroot)lib/$(LIBJEMALLOC).$(A)
-endif
-ifdef PIC_CFLAGS
-STATIC_LIBS += $(objroot)lib/$(LIBJEMALLOC)_pic.$(A)
-else
-STATIC_LIBS += $(objroot)lib/$(LIBJEMALLOC)_s.$(A)
-endif
-DSOS := $(objroot)lib/$(LIBJEMALLOC).$(SOREV)
-ifneq ($(SOREV),$(SO))
-DSOS += $(objroot)lib/$(LIBJEMALLOC).$(SO)
-endif
-ifeq (1, $(link_whole_archive))
-LJEMALLOC := -Wl,--whole-archive -L$(objroot)lib -l$(LIBJEMALLOC) -Wl,--no-whole-archive
-else
-LJEMALLOC := $(objroot)lib/$(LIBJEMALLOC).$(IMPORTLIB)
-endif
-PC := $(objroot)jemalloc.pc
-MAN3 := $(objroot)doc/jemalloc$(install_suffix).3
-DOCS_XML := $(objroot)doc/jemalloc$(install_suffix).xml
-DOCS_HTML := $(DOCS_XML:$(objroot)%.xml=$(objroot)%.html)
-DOCS_MAN3 := $(DOCS_XML:$(objroot)%.xml=$(objroot)%.3)
-DOCS := $(DOCS_HTML) $(DOCS_MAN3)
-C_TESTLIB_SRCS := $(srcroot)test/src/btalloc.c $(srcroot)test/src/btalloc_0.c \
- $(srcroot)test/src/btalloc_1.c $(srcroot)test/src/math.c \
- $(srcroot)test/src/mtx.c $(srcroot)test/src/mq.c \
- $(srcroot)test/src/SFMT.c $(srcroot)test/src/test.c \
- $(srcroot)test/src/thd.c $(srcroot)test/src/timer.c
-ifeq (1, $(link_whole_archive))
-C_UTIL_INTEGRATION_SRCS :=
-else
-C_UTIL_INTEGRATION_SRCS := $(srcroot)src/nstime.c $(srcroot)src/util.c
-endif
-TESTS_UNIT := \
- $(srcroot)test/unit/a0.c \
- $(srcroot)test/unit/arena_reset.c \
- $(srcroot)test/unit/atomic.c \
- $(srcroot)test/unit/bitmap.c \
- $(srcroot)test/unit/ckh.c \
- $(srcroot)test/unit/decay.c \
- $(srcroot)test/unit/fork.c \
- $(srcroot)test/unit/hash.c \
- $(srcroot)test/unit/junk.c \
- $(srcroot)test/unit/junk_alloc.c \
- $(srcroot)test/unit/junk_free.c \
- $(srcroot)test/unit/lg_chunk.c \
- $(srcroot)test/unit/mallctl.c \
- $(srcroot)test/unit/math.c \
- $(srcroot)test/unit/mq.c \
- $(srcroot)test/unit/mtx.c \
- $(srcroot)test/unit/ph.c \
- $(srcroot)test/unit/prng.c \
- $(srcroot)test/unit/prof_accum.c \
- $(srcroot)test/unit/prof_active.c \
- $(srcroot)test/unit/prof_gdump.c \
- $(srcroot)test/unit/prof_idump.c \
- $(srcroot)test/unit/prof_reset.c \
- $(srcroot)test/unit/prof_thread_name.c \
- $(srcroot)test/unit/ql.c \
- $(srcroot)test/unit/qr.c \
- $(srcroot)test/unit/quarantine.c \
- $(srcroot)test/unit/rb.c \
- $(srcroot)test/unit/rtree.c \
- $(srcroot)test/unit/run_quantize.c \
- $(srcroot)test/unit/SFMT.c \
- $(srcroot)test/unit/size_classes.c \
- $(srcroot)test/unit/smoothstep.c \
- $(srcroot)test/unit/stats.c \
- $(srcroot)test/unit/ticker.c \
- $(srcroot)test/unit/nstime.c \
- $(srcroot)test/unit/tsd.c \
- $(srcroot)test/unit/util.c \
- $(srcroot)test/unit/witness.c \
- $(srcroot)test/unit/zero.c
-TESTS_INTEGRATION := $(srcroot)test/integration/aligned_alloc.c \
- $(srcroot)test/integration/allocated.c \
- $(srcroot)test/integration/sdallocx.c \
- $(srcroot)test/integration/mallocx.c \
- $(srcroot)test/integration/MALLOCX_ARENA.c \
- $(srcroot)test/integration/overflow.c \
- $(srcroot)test/integration/posix_memalign.c \
- $(srcroot)test/integration/rallocx.c \
- $(srcroot)test/integration/thread_arena.c \
- $(srcroot)test/integration/thread_tcache_enabled.c \
- $(srcroot)test/integration/xallocx.c \
- $(srcroot)test/integration/chunk.c
-TESTS_STRESS := $(srcroot)test/stress/microbench.c
-TESTS := $(TESTS_UNIT) $(TESTS_INTEGRATION) $(TESTS_STRESS)
-
-C_OBJS := $(C_SRCS:$(srcroot)%.c=$(objroot)%.$(O))
-C_PIC_OBJS := $(C_SRCS:$(srcroot)%.c=$(objroot)%.pic.$(O))
-C_JET_OBJS := $(C_SRCS:$(srcroot)%.c=$(objroot)%.jet.$(O))
-C_TESTLIB_UNIT_OBJS := $(C_TESTLIB_SRCS:$(srcroot)%.c=$(objroot)%.unit.$(O))
-C_TESTLIB_INTEGRATION_OBJS := $(C_TESTLIB_SRCS:$(srcroot)%.c=$(objroot)%.integration.$(O))
-C_UTIL_INTEGRATION_OBJS := $(C_UTIL_INTEGRATION_SRCS:$(srcroot)%.c=$(objroot)%.integration.$(O))
-C_TESTLIB_STRESS_OBJS := $(C_TESTLIB_SRCS:$(srcroot)%.c=$(objroot)%.stress.$(O))
-C_TESTLIB_OBJS := $(C_TESTLIB_UNIT_OBJS) $(C_TESTLIB_INTEGRATION_OBJS) $(C_UTIL_INTEGRATION_OBJS) $(C_TESTLIB_STRESS_OBJS)
-
-TESTS_UNIT_OBJS := $(TESTS_UNIT:$(srcroot)%.c=$(objroot)%.$(O))
-TESTS_INTEGRATION_OBJS := $(TESTS_INTEGRATION:$(srcroot)%.c=$(objroot)%.$(O))
-TESTS_STRESS_OBJS := $(TESTS_STRESS:$(srcroot)%.c=$(objroot)%.$(O))
-TESTS_OBJS := $(TESTS_UNIT_OBJS) $(TESTS_INTEGRATION_OBJS) $(TESTS_STRESS_OBJS)
-
-.PHONY: all dist build_doc_html build_doc_man build_doc
-.PHONY: install_bin install_include install_lib
-.PHONY: install_doc_html install_doc_man install_doc install
-.PHONY: tests check clean distclean relclean
-
-.SECONDARY : $(TESTS_OBJS)
-
-# Default target.
-all: build_lib
-
-dist: build_doc
-
-$(objroot)doc/%.html : $(objroot)doc/%.xml $(srcroot)doc/stylesheet.xsl $(objroot)doc/html.xsl
- $(XSLTPROC) -o $@ $(objroot)doc/html.xsl $<
-
-$(objroot)doc/%.3 : $(objroot)doc/%.xml $(srcroot)doc/stylesheet.xsl $(objroot)doc/manpages.xsl
- $(XSLTPROC) -o $@ $(objroot)doc/manpages.xsl $<
-
-build_doc_html: $(DOCS_HTML)
-build_doc_man: $(DOCS_MAN3)
-build_doc: $(DOCS)
-
-#
-# Include generated dependency files.
-#
-ifdef CC_MM
--include $(C_OBJS:%.$(O)=%.d)
--include $(C_PIC_OBJS:%.$(O)=%.d)
--include $(C_JET_OBJS:%.$(O)=%.d)
--include $(C_TESTLIB_OBJS:%.$(O)=%.d)
--include $(TESTS_OBJS:%.$(O)=%.d)
-endif
-
-$(C_OBJS): $(objroot)src/%.$(O): $(srcroot)src/%.c
-$(C_PIC_OBJS): $(objroot)src/%.pic.$(O): $(srcroot)src/%.c
-$(C_PIC_OBJS): CFLAGS += $(PIC_CFLAGS)
-$(C_JET_OBJS): $(objroot)src/%.jet.$(O): $(srcroot)src/%.c
-$(C_JET_OBJS): CFLAGS += -DJEMALLOC_JET
-$(C_TESTLIB_UNIT_OBJS): $(objroot)test/src/%.unit.$(O): $(srcroot)test/src/%.c
-$(C_TESTLIB_UNIT_OBJS): CPPFLAGS += -DJEMALLOC_UNIT_TEST
-$(C_TESTLIB_INTEGRATION_OBJS): $(objroot)test/src/%.integration.$(O): $(srcroot)test/src/%.c
-$(C_TESTLIB_INTEGRATION_OBJS): CPPFLAGS += -DJEMALLOC_INTEGRATION_TEST
-$(C_UTIL_INTEGRATION_OBJS): $(objroot)src/%.integration.$(O): $(srcroot)src/%.c
-$(C_TESTLIB_STRESS_OBJS): $(objroot)test/src/%.stress.$(O): $(srcroot)test/src/%.c
-$(C_TESTLIB_STRESS_OBJS): CPPFLAGS += -DJEMALLOC_STRESS_TEST -DJEMALLOC_STRESS_TESTLIB
-$(C_TESTLIB_OBJS): CPPFLAGS += -I$(srcroot)test/include -I$(objroot)test/include
-$(TESTS_UNIT_OBJS): CPPFLAGS += -DJEMALLOC_UNIT_TEST
-$(TESTS_INTEGRATION_OBJS): CPPFLAGS += -DJEMALLOC_INTEGRATION_TEST
-$(TESTS_STRESS_OBJS): CPPFLAGS += -DJEMALLOC_STRESS_TEST
-$(TESTS_OBJS): $(objroot)test/%.$(O): $(srcroot)test/%.c
-$(TESTS_OBJS): CPPFLAGS += -I$(srcroot)test/include -I$(objroot)test/include
-ifneq ($(IMPORTLIB),$(SO))
-$(C_OBJS) $(C_JET_OBJS): CPPFLAGS += -DDLLEXPORT
-endif
-
-ifndef CC_MM
-# Dependencies.
-HEADER_DIRS = $(srcroot)include/jemalloc/internal \
- $(objroot)include/jemalloc $(objroot)include/jemalloc/internal
-HEADERS = $(wildcard $(foreach dir,$(HEADER_DIRS),$(dir)/*.h))
-$(C_OBJS) $(C_PIC_OBJS) $(C_JET_OBJS) $(C_TESTLIB_OBJS) $(TESTS_OBJS): $(HEADERS)
-$(TESTS_OBJS): $(objroot)test/include/test/jemalloc_test.h
-endif
-
-$(C_OBJS) $(C_PIC_OBJS) $(C_JET_OBJS) $(C_TESTLIB_OBJS) $(TESTS_OBJS): %.$(O):
- @mkdir -p $(@D)
- $(CC) $(CFLAGS) -c $(CPPFLAGS) $(CTARGET) $<
-ifdef CC_MM
- @$(CC) -MM $(CPPFLAGS) -MT $@ -o $(@:%.$(O)=%.d) $<
-endif
-
-ifneq ($(SOREV),$(SO))
-%.$(SO) : %.$(SOREV)
- @mkdir -p $(@D)
- ln -sf $(<F) $@
-endif
-
-$(objroot)lib/$(LIBJEMALLOC).$(SOREV) : $(if $(PIC_CFLAGS),$(C_PIC_OBJS),$(C_OBJS))
- @mkdir -p $(@D)
- $(CC) $(DSO_LDFLAGS) $(call RPATH,$(RPATH_EXTRA)) $(LDTARGET) $+ $(LDFLAGS) $(LIBS) $(EXTRA_LDFLAGS)
-
-$(objroot)lib/$(LIBJEMALLOC)_pic.$(A) : $(C_PIC_OBJS)
-$(objroot)lib/$(LIBJEMALLOC).$(A) : $(C_OBJS)
-$(objroot)lib/$(LIBJEMALLOC)_s.$(A) : $(C_OBJS)
-
-$(STATIC_LIBS):
- @mkdir -p $(@D)
- $(AR) $(ARFLAGS)@AROUT@ $+
-
-$(objroot)test/unit/%$(EXE): $(objroot)test/unit/%.$(O) $(TESTS_UNIT_LINK_OBJS) $(C_JET_OBJS) $(C_TESTLIB_UNIT_OBJS)
- @mkdir -p $(@D)
- $(CC) $(LDTARGET) $(filter %.$(O),$^) $(call RPATH,$(objroot)lib) $(LDFLAGS) $(filter-out -lm,$(LIBS)) $(LM) $(EXTRA_LDFLAGS)
-
-$(objroot)test/integration/%$(EXE): $(objroot)test/integration/%.$(O) $(C_TESTLIB_INTEGRATION_OBJS) $(C_UTIL_INTEGRATION_OBJS) $(objroot)lib/$(LIBJEMALLOC).$(IMPORTLIB)
- @mkdir -p $(@D)
- $(CC) $(TEST_LD_MODE) $(LDTARGET) $(filter %.$(O),$^) $(call RPATH,$(objroot)lib) $(LJEMALLOC) $(LDFLAGS) $(filter-out -lm,$(filter -lrt -lpthread,$(LIBS))) $(LM) $(EXTRA_LDFLAGS)
-
-$(objroot)test/stress/%$(EXE): $(objroot)test/stress/%.$(O) $(C_JET_OBJS) $(C_TESTLIB_STRESS_OBJS) $(objroot)lib/$(LIBJEMALLOC).$(IMPORTLIB)
- @mkdir -p $(@D)
- $(CC) $(TEST_LD_MODE) $(LDTARGET) $(filter %.$(O),$^) $(call RPATH,$(objroot)lib) $(objroot)lib/$(LIBJEMALLOC).$(IMPORTLIB) $(LDFLAGS) $(filter-out -lm,$(LIBS)) $(LM) $(EXTRA_LDFLAGS)
-
-build_lib_shared: $(DSOS)
-build_lib_static: $(STATIC_LIBS)
-build_lib: build_lib_shared build_lib_static
-
-install_bin:
- $(INSTALL) -d $(BINDIR)
- @for b in $(BINS); do \
- echo "$(INSTALL) -m 755 $$b $(BINDIR)"; \
- $(INSTALL) -m 755 $$b $(BINDIR); \
-done
-
-install_include:
- $(INSTALL) -d $(INCLUDEDIR)/jemalloc
- @for h in $(C_HDRS); do \
- echo "$(INSTALL) -m 644 $$h $(INCLUDEDIR)/jemalloc"; \
- $(INSTALL) -m 644 $$h $(INCLUDEDIR)/jemalloc; \
-done
-
-install_lib_shared: $(DSOS)
- $(INSTALL) -d $(LIBDIR)
- $(INSTALL) -m 755 $(objroot)lib/$(LIBJEMALLOC).$(SOREV) $(LIBDIR)
-ifneq ($(SOREV),$(SO))
- ln -sf $(LIBJEMALLOC).$(SOREV) $(LIBDIR)/$(LIBJEMALLOC).$(SO)
-endif
-
-install_lib_static: $(STATIC_LIBS)
- $(INSTALL) -d $(LIBDIR)
- @for l in $(STATIC_LIBS); do \
- echo "$(INSTALL) -m 755 $$l $(LIBDIR)"; \
- $(INSTALL) -m 755 $$l $(LIBDIR); \
-done
-
-install_lib_pc: $(PC)
- $(INSTALL) -d $(LIBDIR)/pkgconfig
- @for l in $(PC); do \
- echo "$(INSTALL) -m 644 $$l $(LIBDIR)/pkgconfig"; \
- $(INSTALL) -m 644 $$l $(LIBDIR)/pkgconfig; \
-done
-
-install_lib: install_lib_shared install_lib_static install_lib_pc
-
-install_doc_html:
- $(INSTALL) -d $(DATADIR)/doc/jemalloc$(install_suffix)
- @for d in $(DOCS_HTML); do \
- echo "$(INSTALL) -m 644 $$d $(DATADIR)/doc/jemalloc$(install_suffix)"; \
- $(INSTALL) -m 644 $$d $(DATADIR)/doc/jemalloc$(install_suffix); \
-done
-
-install_doc_man:
- $(INSTALL) -d $(MANDIR)/man3
- @for d in $(DOCS_MAN3); do \
- echo "$(INSTALL) -m 644 $$d $(MANDIR)/man3"; \
- $(INSTALL) -m 644 $$d $(MANDIR)/man3; \
-done
-
-install_doc: install_doc_html install_doc_man
-
-install: install_bin install_include install_lib install_doc
-
-tests_unit: $(TESTS_UNIT:$(srcroot)%.c=$(objroot)%$(EXE))
-tests_integration: $(TESTS_INTEGRATION:$(srcroot)%.c=$(objroot)%$(EXE))
-tests_stress: $(TESTS_STRESS:$(srcroot)%.c=$(objroot)%$(EXE))
-tests: tests_unit tests_integration tests_stress
-
-check_unit_dir:
- @mkdir -p $(objroot)test/unit
-check_integration_dir:
- @mkdir -p $(objroot)test/integration
-stress_dir:
- @mkdir -p $(objroot)test/stress
-check_dir: check_unit_dir check_integration_dir
-
-check_unit: tests_unit check_unit_dir
- $(MALLOC_CONF)="purge:ratio" $(SHELL) $(objroot)test/test.sh $(TESTS_UNIT:$(srcroot)%.c=$(objroot)%)
- $(MALLOC_CONF)="purge:decay" $(SHELL) $(objroot)test/test.sh $(TESTS_UNIT:$(srcroot)%.c=$(objroot)%)
-check_integration_prof: tests_integration check_integration_dir
-ifeq ($(enable_prof), 1)
- $(MALLOC_CONF)="prof:true" $(SHELL) $(objroot)test/test.sh $(TESTS_INTEGRATION:$(srcroot)%.c=$(objroot)%)
- $(MALLOC_CONF)="prof:true,prof_active:false" $(SHELL) $(objroot)test/test.sh $(TESTS_INTEGRATION:$(srcroot)%.c=$(objroot)%)
-endif
-check_integration_decay: tests_integration check_integration_dir
- $(MALLOC_CONF)="purge:decay,decay_time:-1" $(SHELL) $(objroot)test/test.sh $(TESTS_INTEGRATION:$(srcroot)%.c=$(objroot)%)
- $(MALLOC_CONF)="purge:decay,decay_time:0" $(SHELL) $(objroot)test/test.sh $(TESTS_INTEGRATION:$(srcroot)%.c=$(objroot)%)
- $(MALLOC_CONF)="purge:decay" $(SHELL) $(objroot)test/test.sh $(TESTS_INTEGRATION:$(srcroot)%.c=$(objroot)%)
-check_integration: tests_integration check_integration_dir
- $(SHELL) $(objroot)test/test.sh $(TESTS_INTEGRATION:$(srcroot)%.c=$(objroot)%)
-stress: tests_stress stress_dir
- $(SHELL) $(objroot)test/test.sh $(TESTS_STRESS:$(srcroot)%.c=$(objroot)%)
-check: check_unit check_integration check_integration_decay check_integration_prof
-
-ifeq ($(enable_code_coverage), 1)
-coverage_unit: check_unit
- $(SHELL) $(srcroot)coverage.sh $(srcroot)src jet $(C_JET_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/src unit $(C_TESTLIB_UNIT_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/unit unit $(TESTS_UNIT_OBJS)
-
-coverage_integration: check_integration
- $(SHELL) $(srcroot)coverage.sh $(srcroot)src pic $(C_PIC_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)src integration $(C_UTIL_INTEGRATION_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/src integration $(C_TESTLIB_INTEGRATION_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/integration integration $(TESTS_INTEGRATION_OBJS)
-
-coverage_stress: stress
- $(SHELL) $(srcroot)coverage.sh $(srcroot)src pic $(C_PIC_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)src jet $(C_JET_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/src stress $(C_TESTLIB_STRESS_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/stress stress $(TESTS_STRESS_OBJS)
-
-coverage: check
- $(SHELL) $(srcroot)coverage.sh $(srcroot)src pic $(C_PIC_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)src jet $(C_JET_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)src integration $(C_UTIL_INTEGRATION_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/src unit $(C_TESTLIB_UNIT_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/src integration $(C_TESTLIB_INTEGRATION_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/src stress $(C_TESTLIB_STRESS_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/unit unit $(TESTS_UNIT_OBJS) $(TESTS_UNIT_AUX_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/integration integration $(TESTS_INTEGRATION_OBJS)
- $(SHELL) $(srcroot)coverage.sh $(srcroot)test/stress integration $(TESTS_STRESS_OBJS)
-endif
-
-clean:
- rm -f $(C_OBJS)
- rm -f $(C_PIC_OBJS)
- rm -f $(C_JET_OBJS)
- rm -f $(C_TESTLIB_OBJS)
- rm -f $(C_OBJS:%.$(O)=%.d)
- rm -f $(C_OBJS:%.$(O)=%.gcda)
- rm -f $(C_OBJS:%.$(O)=%.gcno)
- rm -f $(C_PIC_OBJS:%.$(O)=%.d)
- rm -f $(C_PIC_OBJS:%.$(O)=%.gcda)
- rm -f $(C_PIC_OBJS:%.$(O)=%.gcno)
- rm -f $(C_JET_OBJS:%.$(O)=%.d)
- rm -f $(C_JET_OBJS:%.$(O)=%.gcda)
- rm -f $(C_JET_OBJS:%.$(O)=%.gcno)
- rm -f $(C_TESTLIB_OBJS:%.$(O)=%.d)
- rm -f $(C_TESTLIB_OBJS:%.$(O)=%.gcda)
- rm -f $(C_TESTLIB_OBJS:%.$(O)=%.gcno)
- rm -f $(TESTS_OBJS:%.$(O)=%$(EXE))
- rm -f $(TESTS_OBJS)
- rm -f $(TESTS_OBJS:%.$(O)=%.d)
- rm -f $(TESTS_OBJS:%.$(O)=%.gcda)
- rm -f $(TESTS_OBJS:%.$(O)=%.gcno)
- rm -f $(TESTS_OBJS:%.$(O)=%.out)
- rm -f $(DSOS) $(STATIC_LIBS)
- rm -f $(objroot)*.gcov.*
-
-distclean: clean
- rm -f $(objroot)bin/jemalloc-config
- rm -f $(objroot)bin/jemalloc.sh
- rm -f $(objroot)bin/jeprof
- rm -f $(objroot)config.log
- rm -f $(objroot)config.status
- rm -f $(objroot)config.stamp
- rm -f $(cfghdrs_out)
- rm -f $(cfgoutputs_out)
-
-relclean: distclean
- rm -f $(objroot)configure
- rm -f $(objroot)VERSION
- rm -f $(DOCS_HTML)
- rm -f $(DOCS_MAN3)
-
-#===============================================================================
-# Re-configuration rules.
-
-ifeq ($(enable_autogen), 1)
-$(srcroot)configure : $(srcroot)configure.ac
- cd ./$(srcroot) && $(AUTOCONF)
-
-$(objroot)config.status : $(srcroot)configure
- ./$(objroot)config.status --recheck
-
-$(srcroot)config.stamp.in : $(srcroot)configure.ac
- echo stamp > $(srcroot)config.stamp.in
-
-$(objroot)config.stamp : $(cfgoutputs_in) $(cfghdrs_in) $(srcroot)configure
- ./$(objroot)config.status
- @touch $@
-
-# There must be some action in order for make to re-read Makefile when it is
-# out of date.
-$(cfgoutputs_out) $(cfghdrs_out) : $(objroot)config.stamp
- @true
-endif
diff --git a/memory/jemalloc/src/README b/memory/jemalloc/src/README
deleted file mode 100644
index 5ff24a9ef..000000000
--- a/memory/jemalloc/src/README
+++ /dev/null
@@ -1,20 +0,0 @@
-jemalloc is a general purpose malloc(3) implementation that emphasizes
-fragmentation avoidance and scalable concurrency support. jemalloc first came
-into use as the FreeBSD libc allocator in 2005, and since then it has found its
-way into numerous applications that rely on its predictable behavior. In 2010
-jemalloc development efforts broadened to include developer support features
-such as heap profiling, Valgrind integration, and extensive monitoring/tuning
-hooks. Modern jemalloc releases continue to be integrated back into FreeBSD,
-and therefore versatility remains critical. Ongoing development efforts trend
-toward making jemalloc among the best allocators for a broad range of demanding
-applications, and eliminating/mitigating weaknesses that have practical
-repercussions for real world applications.
-
-The COPYING file contains copyright and licensing information.
-
-The INSTALL file contains information on how to configure, build, and install
-jemalloc.
-
-The ChangeLog file contains a brief summary of changes for each release.
-
-URL: http://jemalloc.net/
diff --git a/memory/jemalloc/src/VERSION b/memory/jemalloc/src/VERSION
deleted file mode 100644
index c108ecb84..000000000
--- a/memory/jemalloc/src/VERSION
+++ /dev/null
@@ -1 +0,0 @@
-4.3.1-0-g0110fa8451af905affd77c3bea0d545fee2251b2
diff --git a/memory/jemalloc/src/autogen.sh b/memory/jemalloc/src/autogen.sh
deleted file mode 100755
index 75f32da68..000000000
--- a/memory/jemalloc/src/autogen.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/bin/sh
-
-for i in autoconf; do
- echo "$i"
- $i
- if [ $? -ne 0 ]; then
- echo "Error $? in $i"
- exit 1
- fi
-done
-
-echo "./configure --enable-autogen $@"
-./configure --enable-autogen $@
-if [ $? -ne 0 ]; then
- echo "Error $? in ./configure"
- exit 1
-fi
diff --git a/memory/jemalloc/src/bin/jemalloc-config.in b/memory/jemalloc/src/bin/jemalloc-config.in
deleted file mode 100644
index b016c8d33..000000000
--- a/memory/jemalloc/src/bin/jemalloc-config.in
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/bin/sh
-
-usage() {
- cat <<EOF
-Usage:
- @BINDIR@/jemalloc-config <option>
-Options:
- --help | -h : Print usage.
- --version : Print jemalloc version.
- --revision : Print shared library revision number.
- --config : Print configure options used to build jemalloc.
- --prefix : Print installation directory prefix.
- --bindir : Print binary installation directory.
- --datadir : Print data installation directory.
- --includedir : Print include installation directory.
- --libdir : Print library installation directory.
- --mandir : Print manual page installation directory.
- --cc : Print compiler used to build jemalloc.
- --cflags : Print compiler flags used to build jemalloc.
- --cppflags : Print preprocessor flags used to build jemalloc.
- --ldflags : Print library flags used to build jemalloc.
- --libs : Print libraries jemalloc was linked against.
-EOF
-}
-
-prefix="@prefix@"
-exec_prefix="@exec_prefix@"
-
-case "$1" in
---help | -h)
- usage
- exit 0
- ;;
---version)
- echo "@jemalloc_version@"
- ;;
---revision)
- echo "@rev@"
- ;;
---config)
- echo "@CONFIG@"
- ;;
---prefix)
- echo "@PREFIX@"
- ;;
---bindir)
- echo "@BINDIR@"
- ;;
---datadir)
- echo "@DATADIR@"
- ;;
---includedir)
- echo "@INCLUDEDIR@"
- ;;
---libdir)
- echo "@LIBDIR@"
- ;;
---mandir)
- echo "@MANDIR@"
- ;;
---cc)
- echo "@CC@"
- ;;
---cflags)
- echo "@CFLAGS@"
- ;;
---cppflags)
- echo "@CPPFLAGS@"
- ;;
---ldflags)
- echo "@LDFLAGS@ @EXTRA_LDFLAGS@"
- ;;
---libs)
- echo "@LIBS@"
- ;;
-*)
- usage
- exit 1
-esac
diff --git a/memory/jemalloc/src/bin/jemalloc.sh.in b/memory/jemalloc/src/bin/jemalloc.sh.in
deleted file mode 100644
index cdf367375..000000000
--- a/memory/jemalloc/src/bin/jemalloc.sh.in
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/bin/sh
-
-prefix=@prefix@
-exec_prefix=@exec_prefix@
-libdir=@libdir@
-
-@LD_PRELOAD_VAR@=${libdir}/libjemalloc.@SOREV@
-export @LD_PRELOAD_VAR@
-exec "$@"
diff --git a/memory/jemalloc/src/bin/jeprof.in b/memory/jemalloc/src/bin/jeprof.in
deleted file mode 100644
index 42087fcec..000000000
--- a/memory/jemalloc/src/bin/jeprof.in
+++ /dev/null
@@ -1,5611 +0,0 @@
-#! /usr/bin/env perl
-
-# Copyright (c) 1998-2007, Google Inc.
-# 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.
-
-# ---
-# Program for printing the profile generated by common/profiler.cc,
-# or by the heap profiler (common/debugallocation.cc)
-#
-# The profile contains a sequence of entries of the form:
-# <count> <stack trace>
-# This program parses the profile, and generates user-readable
-# output.
-#
-# Examples:
-#
-# % tools/jeprof "program" "profile"
-# Enters "interactive" mode
-#
-# % tools/jeprof --text "program" "profile"
-# Generates one line per procedure
-#
-# % tools/jeprof --gv "program" "profile"
-# Generates annotated call-graph and displays via "gv"
-#
-# % tools/jeprof --gv --focus=Mutex "program" "profile"
-# Restrict to code paths that involve an entry that matches "Mutex"
-#
-# % tools/jeprof --gv --focus=Mutex --ignore=string "program" "profile"
-# Restrict to code paths that involve an entry that matches "Mutex"
-# and does not match "string"
-#
-# % tools/jeprof --list=IBF_CheckDocid "program" "profile"
-# Generates disassembly listing of all routines with at least one
-# sample that match the --list=<regexp> pattern. The listing is
-# annotated with the flat and cumulative sample counts at each line.
-#
-# % tools/jeprof --disasm=IBF_CheckDocid "program" "profile"
-# Generates disassembly listing of all routines with at least one
-# sample that match the --disasm=<regexp> pattern. The listing is
-# annotated with the flat and cumulative sample counts at each PC value.
-#
-# TODO: Use color to indicate files?
-
-use strict;
-use warnings;
-use Getopt::Long;
-
-my $JEPROF_VERSION = "@jemalloc_version@";
-my $PPROF_VERSION = "2.0";
-
-# These are the object tools we use which can come from a
-# user-specified location using --tools, from the JEPROF_TOOLS
-# environment variable, or from the environment.
-my %obj_tool_map = (
- "objdump" => "objdump",
- "nm" => "nm",
- "addr2line" => "addr2line",
- "c++filt" => "c++filt",
- ## ConfigureObjTools may add architecture-specific entries:
- #"nm_pdb" => "nm-pdb", # for reading windows (PDB-format) executables
- #"addr2line_pdb" => "addr2line-pdb", # ditto
- #"otool" => "otool", # equivalent of objdump on OS X
-);
-# NOTE: these are lists, so you can put in commandline flags if you want.
-my @DOT = ("dot"); # leave non-absolute, since it may be in /usr/local
-my @GV = ("gv");
-my @EVINCE = ("evince"); # could also be xpdf or perhaps acroread
-my @KCACHEGRIND = ("kcachegrind");
-my @PS2PDF = ("ps2pdf");
-# These are used for dynamic profiles
-my @URL_FETCHER = ("curl", "-s", "--fail");
-
-# These are the web pages that servers need to support for dynamic profiles
-my $HEAP_PAGE = "/pprof/heap";
-my $PROFILE_PAGE = "/pprof/profile"; # must support cgi-param "?seconds=#"
-my $PMUPROFILE_PAGE = "/pprof/pmuprofile(?:\\?.*)?"; # must support cgi-param
- # ?seconds=#&event=x&period=n
-my $GROWTH_PAGE = "/pprof/growth";
-my $CONTENTION_PAGE = "/pprof/contention";
-my $WALL_PAGE = "/pprof/wall(?:\\?.*)?"; # accepts options like namefilter
-my $FILTEREDPROFILE_PAGE = "/pprof/filteredprofile(?:\\?.*)?";
-my $CENSUSPROFILE_PAGE = "/pprof/censusprofile(?:\\?.*)?"; # must support cgi-param
- # "?seconds=#",
- # "?tags_regexp=#" and
- # "?type=#".
-my $SYMBOL_PAGE = "/pprof/symbol"; # must support symbol lookup via POST
-my $PROGRAM_NAME_PAGE = "/pprof/cmdline";
-
-# These are the web pages that can be named on the command line.
-# All the alternatives must begin with /.
-my $PROFILES = "($HEAP_PAGE|$PROFILE_PAGE|$PMUPROFILE_PAGE|" .
- "$GROWTH_PAGE|$CONTENTION_PAGE|$WALL_PAGE|" .
- "$FILTEREDPROFILE_PAGE|$CENSUSPROFILE_PAGE)";
-
-# default binary name
-my $UNKNOWN_BINARY = "(unknown)";
-
-# There is a pervasive dependency on the length (in hex characters,
-# i.e., nibbles) of an address, distinguishing between 32-bit and
-# 64-bit profiles. To err on the safe size, default to 64-bit here:
-my $address_length = 16;
-
-my $dev_null = "/dev/null";
-if (! -e $dev_null && $^O =~ /MSWin/) { # $^O is the OS perl was built for
- $dev_null = "nul";
-}
-
-# A list of paths to search for shared object files
-my @prefix_list = ();
-
-# Special routine name that should not have any symbols.
-# Used as separator to parse "addr2line -i" output.
-my $sep_symbol = '_fini';
-my $sep_address = undef;
-
-##### Argument parsing #####
-
-sub usage_string {
- return <<EOF;
-Usage:
-jeprof [options] <program> <profiles>
- <profiles> is a space separated list of profile names.
-jeprof [options] <symbolized-profiles>
- <symbolized-profiles> is a list of profile files where each file contains
- the necessary symbol mappings as well as profile data (likely generated
- with --raw).
-jeprof [options] <profile>
- <profile> is a remote form. Symbols are obtained from host:port$SYMBOL_PAGE
-
- Each name can be:
- /path/to/profile - a path to a profile file
- host:port[/<service>] - a location of a service to get profile from
-
- The /<service> can be $HEAP_PAGE, $PROFILE_PAGE, /pprof/pmuprofile,
- $GROWTH_PAGE, $CONTENTION_PAGE, /pprof/wall,
- $CENSUSPROFILE_PAGE, or /pprof/filteredprofile.
- For instance:
- jeprof http://myserver.com:80$HEAP_PAGE
- If /<service> is omitted, the service defaults to $PROFILE_PAGE (cpu profiling).
-jeprof --symbols <program>
- Maps addresses to symbol names. In this mode, stdin should be a
- list of library mappings, in the same format as is found in the heap-
- and cpu-profile files (this loosely matches that of /proc/self/maps
- on linux), followed by a list of hex addresses to map, one per line.
-
- For more help with querying remote servers, including how to add the
- necessary server-side support code, see this filename (or one like it):
-
- /usr/doc/gperftools-$PPROF_VERSION/pprof_remote_servers.html
-
-Options:
- --cum Sort by cumulative data
- --base=<base> Subtract <base> from <profile> before display
- --interactive Run in interactive mode (interactive "help" gives help) [default]
- --seconds=<n> Length of time for dynamic profiles [default=30 secs]
- --add_lib=<file> Read additional symbols and line info from the given library
- --lib_prefix=<dir> Comma separated list of library path prefixes
-
-Reporting Granularity:
- --addresses Report at address level
- --lines Report at source line level
- --functions Report at function level [default]
- --files Report at source file level
-
-Output type:
- --text Generate text report
- --callgrind Generate callgrind format to stdout
- --gv Generate Postscript and display
- --evince Generate PDF and display
- --web Generate SVG and display
- --list=<regexp> Generate source listing of matching routines
- --disasm=<regexp> Generate disassembly of matching routines
- --symbols Print demangled symbol names found at given addresses
- --dot Generate DOT file to stdout
- --ps Generate Postcript to stdout
- --pdf Generate PDF to stdout
- --svg Generate SVG to stdout
- --gif Generate GIF to stdout
- --raw Generate symbolized jeprof data (useful with remote fetch)
-
-Heap-Profile Options:
- --inuse_space Display in-use (mega)bytes [default]
- --inuse_objects Display in-use objects
- --alloc_space Display allocated (mega)bytes
- --alloc_objects Display allocated objects
- --show_bytes Display space in bytes
- --drop_negative Ignore negative differences
-
-Contention-profile options:
- --total_delay Display total delay at each region [default]
- --contentions Display number of delays at each region
- --mean_delay Display mean delay at each region
-
-Call-graph Options:
- --nodecount=<n> Show at most so many nodes [default=80]
- --nodefraction=<f> Hide nodes below <f>*total [default=.005]
- --edgefraction=<f> Hide edges below <f>*total [default=.001]
- --maxdegree=<n> Max incoming/outgoing edges per node [default=8]
- --focus=<regexp> Focus on backtraces with nodes matching <regexp>
- --thread=<n> Show profile for thread <n>
- --ignore=<regexp> Ignore backtraces with nodes matching <regexp>
- --scale=<n> Set GV scaling [default=0]
- --heapcheck Make nodes with non-0 object counts
- (i.e. direct leak generators) more visible
- --retain=<regexp> Retain only nodes that match <regexp>
- --exclude=<regexp> Exclude all nodes that match <regexp>
-
-Miscellaneous:
- --tools=<prefix or binary:fullpath>[,...] \$PATH for object tool pathnames
- --test Run unit tests
- --help This message
- --version Version information
-
-Environment Variables:
- JEPROF_TMPDIR Profiles directory. Defaults to \$HOME/jeprof
- JEPROF_TOOLS Prefix for object tools pathnames
-
-Examples:
-
-jeprof /bin/ls ls.prof
- Enters "interactive" mode
-jeprof --text /bin/ls ls.prof
- Outputs one line per procedure
-jeprof --web /bin/ls ls.prof
- Displays annotated call-graph in web browser
-jeprof --gv /bin/ls ls.prof
- Displays annotated call-graph via 'gv'
-jeprof --gv --focus=Mutex /bin/ls ls.prof
- Restricts to code paths including a .*Mutex.* entry
-jeprof --gv --focus=Mutex --ignore=string /bin/ls ls.prof
- Code paths including Mutex but not string
-jeprof --list=getdir /bin/ls ls.prof
- (Per-line) annotated source listing for getdir()
-jeprof --disasm=getdir /bin/ls ls.prof
- (Per-PC) annotated disassembly for getdir()
-
-jeprof http://localhost:1234/
- Enters "interactive" mode
-jeprof --text localhost:1234
- Outputs one line per procedure for localhost:1234
-jeprof --raw localhost:1234 > ./local.raw
-jeprof --text ./local.raw
- Fetches a remote profile for later analysis and then
- analyzes it in text mode.
-EOF
-}
-
-sub version_string {
- return <<EOF
-jeprof (part of jemalloc $JEPROF_VERSION)
-based on pprof (part of gperftools $PPROF_VERSION)
-
-Copyright 1998-2007 Google Inc.
-
-This is BSD licensed software; see the source for copying conditions
-and license information.
-There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
-PARTICULAR PURPOSE.
-EOF
-}
-
-sub usage {
- my $msg = shift;
- print STDERR "$msg\n\n";
- print STDERR usage_string();
- print STDERR "\nFATAL ERROR: $msg\n"; # just as a reminder
- exit(1);
-}
-
-sub Init() {
- # Setup tmp-file name and handler to clean it up.
- # We do this in the very beginning so that we can use
- # error() and cleanup() function anytime here after.
- $main::tmpfile_sym = "/tmp/jeprof$$.sym";
- $main::tmpfile_ps = "/tmp/jeprof$$";
- $main::next_tmpfile = 0;
- $SIG{'INT'} = \&sighandler;
-
- # Cache from filename/linenumber to source code
- $main::source_cache = ();
-
- $main::opt_help = 0;
- $main::opt_version = 0;
-
- $main::opt_cum = 0;
- $main::opt_base = '';
- $main::opt_addresses = 0;
- $main::opt_lines = 0;
- $main::opt_functions = 0;
- $main::opt_files = 0;
- $main::opt_lib_prefix = "";
-
- $main::opt_text = 0;
- $main::opt_callgrind = 0;
- $main::opt_list = "";
- $main::opt_disasm = "";
- $main::opt_symbols = 0;
- $main::opt_gv = 0;
- $main::opt_evince = 0;
- $main::opt_web = 0;
- $main::opt_dot = 0;
- $main::opt_ps = 0;
- $main::opt_pdf = 0;
- $main::opt_gif = 0;
- $main::opt_svg = 0;
- $main::opt_raw = 0;
-
- $main::opt_nodecount = 80;
- $main::opt_nodefraction = 0.005;
- $main::opt_edgefraction = 0.001;
- $main::opt_maxdegree = 8;
- $main::opt_focus = '';
- $main::opt_thread = undef;
- $main::opt_ignore = '';
- $main::opt_scale = 0;
- $main::opt_heapcheck = 0;
- $main::opt_retain = '';
- $main::opt_exclude = '';
- $main::opt_seconds = 30;
- $main::opt_lib = "";
-
- $main::opt_inuse_space = 0;
- $main::opt_inuse_objects = 0;
- $main::opt_alloc_space = 0;
- $main::opt_alloc_objects = 0;
- $main::opt_show_bytes = 0;
- $main::opt_drop_negative = 0;
- $main::opt_interactive = 0;
-
- $main::opt_total_delay = 0;
- $main::opt_contentions = 0;
- $main::opt_mean_delay = 0;
-
- $main::opt_tools = "";
- $main::opt_debug = 0;
- $main::opt_test = 0;
-
- # These are undocumented flags used only by unittests.
- $main::opt_test_stride = 0;
-
- # Are we using $SYMBOL_PAGE?
- $main::use_symbol_page = 0;
-
- # Files returned by TempName.
- %main::tempnames = ();
-
- # Type of profile we are dealing with
- # Supported types:
- # cpu
- # heap
- # growth
- # contention
- $main::profile_type = ''; # Empty type means "unknown"
-
- GetOptions("help!" => \$main::opt_help,
- "version!" => \$main::opt_version,
- "cum!" => \$main::opt_cum,
- "base=s" => \$main::opt_base,
- "seconds=i" => \$main::opt_seconds,
- "add_lib=s" => \$main::opt_lib,
- "lib_prefix=s" => \$main::opt_lib_prefix,
- "functions!" => \$main::opt_functions,
- "lines!" => \$main::opt_lines,
- "addresses!" => \$main::opt_addresses,
- "files!" => \$main::opt_files,
- "text!" => \$main::opt_text,
- "callgrind!" => \$main::opt_callgrind,
- "list=s" => \$main::opt_list,
- "disasm=s" => \$main::opt_disasm,
- "symbols!" => \$main::opt_symbols,
- "gv!" => \$main::opt_gv,
- "evince!" => \$main::opt_evince,
- "web!" => \$main::opt_web,
- "dot!" => \$main::opt_dot,
- "ps!" => \$main::opt_ps,
- "pdf!" => \$main::opt_pdf,
- "svg!" => \$main::opt_svg,
- "gif!" => \$main::opt_gif,
- "raw!" => \$main::opt_raw,
- "interactive!" => \$main::opt_interactive,
- "nodecount=i" => \$main::opt_nodecount,
- "nodefraction=f" => \$main::opt_nodefraction,
- "edgefraction=f" => \$main::opt_edgefraction,
- "maxdegree=i" => \$main::opt_maxdegree,
- "focus=s" => \$main::opt_focus,
- "thread=s" => \$main::opt_thread,
- "ignore=s" => \$main::opt_ignore,
- "scale=i" => \$main::opt_scale,
- "heapcheck" => \$main::opt_heapcheck,
- "retain=s" => \$main::opt_retain,
- "exclude=s" => \$main::opt_exclude,
- "inuse_space!" => \$main::opt_inuse_space,
- "inuse_objects!" => \$main::opt_inuse_objects,
- "alloc_space!" => \$main::opt_alloc_space,
- "alloc_objects!" => \$main::opt_alloc_objects,
- "show_bytes!" => \$main::opt_show_bytes,
- "drop_negative!" => \$main::opt_drop_negative,
- "total_delay!" => \$main::opt_total_delay,
- "contentions!" => \$main::opt_contentions,
- "mean_delay!" => \$main::opt_mean_delay,
- "tools=s" => \$main::opt_tools,
- "test!" => \$main::opt_test,
- "debug!" => \$main::opt_debug,
- # Undocumented flags used only by unittests:
- "test_stride=i" => \$main::opt_test_stride,
- ) || usage("Invalid option(s)");
-
- # Deal with the standard --help and --version
- if ($main::opt_help) {
- print usage_string();
- exit(0);
- }
-
- if ($main::opt_version) {
- print version_string();
- exit(0);
- }
-
- # Disassembly/listing/symbols mode requires address-level info
- if ($main::opt_disasm || $main::opt_list || $main::opt_symbols) {
- $main::opt_functions = 0;
- $main::opt_lines = 0;
- $main::opt_addresses = 1;
- $main::opt_files = 0;
- }
-
- # Check heap-profiling flags
- if ($main::opt_inuse_space +
- $main::opt_inuse_objects +
- $main::opt_alloc_space +
- $main::opt_alloc_objects > 1) {
- usage("Specify at most on of --inuse/--alloc options");
- }
-
- # Check output granularities
- my $grains =
- $main::opt_functions +
- $main::opt_lines +
- $main::opt_addresses +
- $main::opt_files +
- 0;
- if ($grains > 1) {
- usage("Only specify one output granularity option");
- }
- if ($grains == 0) {
- $main::opt_functions = 1;
- }
-
- # Check output modes
- my $modes =
- $main::opt_text +
- $main::opt_callgrind +
- ($main::opt_list eq '' ? 0 : 1) +
- ($main::opt_disasm eq '' ? 0 : 1) +
- ($main::opt_symbols == 0 ? 0 : 1) +
- $main::opt_gv +
- $main::opt_evince +
- $main::opt_web +
- $main::opt_dot +
- $main::opt_ps +
- $main::opt_pdf +
- $main::opt_svg +
- $main::opt_gif +
- $main::opt_raw +
- $main::opt_interactive +
- 0;
- if ($modes > 1) {
- usage("Only specify one output mode");
- }
- if ($modes == 0) {
- if (-t STDOUT) { # If STDOUT is a tty, activate interactive mode
- $main::opt_interactive = 1;
- } else {
- $main::opt_text = 1;
- }
- }
-
- if ($main::opt_test) {
- RunUnitTests();
- # Should not return
- exit(1);
- }
-
- # Binary name and profile arguments list
- $main::prog = "";
- @main::pfile_args = ();
-
- # Remote profiling without a binary (using $SYMBOL_PAGE instead)
- if (@ARGV > 0) {
- if (IsProfileURL($ARGV[0])) {
- $main::use_symbol_page = 1;
- } elsif (IsSymbolizedProfileFile($ARGV[0])) {
- $main::use_symbolized_profile = 1;
- $main::prog = $UNKNOWN_BINARY; # will be set later from the profile file
- }
- }
-
- if ($main::use_symbol_page || $main::use_symbolized_profile) {
- # We don't need a binary!
- my %disabled = ('--lines' => $main::opt_lines,
- '--disasm' => $main::opt_disasm);
- for my $option (keys %disabled) {
- usage("$option cannot be used without a binary") if $disabled{$option};
- }
- # Set $main::prog later...
- scalar(@ARGV) || usage("Did not specify profile file");
- } elsif ($main::opt_symbols) {
- # --symbols needs a binary-name (to run nm on, etc) but not profiles
- $main::prog = shift(@ARGV) || usage("Did not specify program");
- } else {
- $main::prog = shift(@ARGV) || usage("Did not specify program");
- scalar(@ARGV) || usage("Did not specify profile file");
- }
-
- # Parse profile file/location arguments
- foreach my $farg (@ARGV) {
- if ($farg =~ m/(.*)\@([0-9]+)(|\/.*)$/ ) {
- my $machine = $1;
- my $num_machines = $2;
- my $path = $3;
- for (my $i = 0; $i < $num_machines; $i++) {
- unshift(@main::pfile_args, "$i.$machine$path");
- }
- } else {
- unshift(@main::pfile_args, $farg);
- }
- }
-
- if ($main::use_symbol_page) {
- unless (IsProfileURL($main::pfile_args[0])) {
- error("The first profile should be a remote form to use $SYMBOL_PAGE\n");
- }
- CheckSymbolPage();
- $main::prog = FetchProgramName();
- } elsif (!$main::use_symbolized_profile) { # may not need objtools!
- ConfigureObjTools($main::prog)
- }
-
- # Break the opt_lib_prefix into the prefix_list array
- @prefix_list = split (',', $main::opt_lib_prefix);
-
- # Remove trailing / from the prefixes, in the list to prevent
- # searching things like /my/path//lib/mylib.so
- foreach (@prefix_list) {
- s|/+$||;
- }
-}
-
-sub FilterAndPrint {
- my ($profile, $symbols, $libs, $thread) = @_;
-
- # Get total data in profile
- my $total = TotalProfile($profile);
-
- # Remove uniniteresting stack items
- $profile = RemoveUninterestingFrames($symbols, $profile);
-
- # Focus?
- if ($main::opt_focus ne '') {
- $profile = FocusProfile($symbols, $profile, $main::opt_focus);
- }
-
- # Ignore?
- if ($main::opt_ignore ne '') {
- $profile = IgnoreProfile($symbols, $profile, $main::opt_ignore);
- }
-
- my $calls = ExtractCalls($symbols, $profile);
-
- # Reduce profiles to required output granularity, and also clean
- # each stack trace so a given entry exists at most once.
- my $reduced = ReduceProfile($symbols, $profile);
-
- # Get derived profiles
- my $flat = FlatProfile($reduced);
- my $cumulative = CumulativeProfile($reduced);
-
- # Print
- if (!$main::opt_interactive) {
- if ($main::opt_disasm) {
- PrintDisassembly($libs, $flat, $cumulative, $main::opt_disasm);
- } elsif ($main::opt_list) {
- PrintListing($total, $libs, $flat, $cumulative, $main::opt_list, 0);
- } elsif ($main::opt_text) {
- # Make sure the output is empty when have nothing to report
- # (only matters when --heapcheck is given but we must be
- # compatible with old branches that did not pass --heapcheck always):
- if ($total != 0) {
- printf("Total%s: %s %s\n",
- (defined($thread) ? " (t$thread)" : ""),
- Unparse($total), Units());
- }
- PrintText($symbols, $flat, $cumulative, -1);
- } elsif ($main::opt_raw) {
- PrintSymbolizedProfile($symbols, $profile, $main::prog);
- } elsif ($main::opt_callgrind) {
- PrintCallgrind($calls);
- } else {
- if (PrintDot($main::prog, $symbols, $profile, $flat, $cumulative, $total)) {
- if ($main::opt_gv) {
- RunGV(TempName($main::next_tmpfile, "ps"), "");
- } elsif ($main::opt_evince) {
- RunEvince(TempName($main::next_tmpfile, "pdf"), "");
- } elsif ($main::opt_web) {
- my $tmp = TempName($main::next_tmpfile, "svg");
- RunWeb($tmp);
- # The command we run might hand the file name off
- # to an already running browser instance and then exit.
- # Normally, we'd remove $tmp on exit (right now),
- # but fork a child to remove $tmp a little later, so that the
- # browser has time to load it first.
- delete $main::tempnames{$tmp};
- if (fork() == 0) {
- sleep 5;
- unlink($tmp);
- exit(0);
- }
- }
- } else {
- cleanup();
- exit(1);
- }
- }
- } else {
- InteractiveMode($profile, $symbols, $libs, $total);
- }
-}
-
-sub Main() {
- Init();
- $main::collected_profile = undef;
- @main::profile_files = ();
- $main::op_time = time();
-
- # Printing symbols is special and requires a lot less info that most.
- if ($main::opt_symbols) {
- PrintSymbols(*STDIN); # Get /proc/maps and symbols output from stdin
- return;
- }
-
- # Fetch all profile data
- FetchDynamicProfiles();
-
- # this will hold symbols that we read from the profile files
- my $symbol_map = {};
-
- # Read one profile, pick the last item on the list
- my $data = ReadProfile($main::prog, pop(@main::profile_files));
- my $profile = $data->{profile};
- my $pcs = $data->{pcs};
- my $libs = $data->{libs}; # Info about main program and shared libraries
- $symbol_map = MergeSymbols($symbol_map, $data->{symbols});
-
- # Add additional profiles, if available.
- if (scalar(@main::profile_files) > 0) {
- foreach my $pname (@main::profile_files) {
- my $data2 = ReadProfile($main::prog, $pname);
- $profile = AddProfile($profile, $data2->{profile});
- $pcs = AddPcs($pcs, $data2->{pcs});
- $symbol_map = MergeSymbols($symbol_map, $data2->{symbols});
- }
- }
-
- # Subtract base from profile, if specified
- if ($main::opt_base ne '') {
- my $base = ReadProfile($main::prog, $main::opt_base);
- $profile = SubtractProfile($profile, $base->{profile});
- $pcs = AddPcs($pcs, $base->{pcs});
- $symbol_map = MergeSymbols($symbol_map, $base->{symbols});
- }
-
- # Collect symbols
- my $symbols;
- if ($main::use_symbolized_profile) {
- $symbols = FetchSymbols($pcs, $symbol_map);
- } elsif ($main::use_symbol_page) {
- $symbols = FetchSymbols($pcs);
- } else {
- # TODO(csilvers): $libs uses the /proc/self/maps data from profile1,
- # which may differ from the data from subsequent profiles, especially
- # if they were run on different machines. Use appropriate libs for
- # each pc somehow.
- $symbols = ExtractSymbols($libs, $pcs);
- }
-
- if (!defined($main::opt_thread)) {
- FilterAndPrint($profile, $symbols, $libs);
- }
- if (defined($data->{threads})) {
- foreach my $thread (sort { $a <=> $b } keys(%{$data->{threads}})) {
- if (defined($main::opt_thread) &&
- ($main::opt_thread eq '*' || $main::opt_thread == $thread)) {
- my $thread_profile = $data->{threads}{$thread};
- FilterAndPrint($thread_profile, $symbols, $libs, $thread);
- }
- }
- }
-
- cleanup();
- exit(0);
-}
-
-##### Entry Point #####
-
-Main();
-
-# Temporary code to detect if we're running on a Goobuntu system.
-# These systems don't have the right stuff installed for the special
-# Readline libraries to work, so as a temporary workaround, we default
-# to using the normal stdio code, rather than the fancier readline-based
-# code
-sub ReadlineMightFail {
- if (-e '/lib/libtermcap.so.2') {
- return 0; # libtermcap exists, so readline should be okay
- } else {
- return 1;
- }
-}
-
-sub RunGV {
- my $fname = shift;
- my $bg = shift; # "" or " &" if we should run in background
- if (!system(ShellEscape(@GV, "--version") . " >$dev_null 2>&1")) {
- # Options using double dash are supported by this gv version.
- # Also, turn on noantialias to better handle bug in gv for
- # postscript files with large dimensions.
- # TODO: Maybe we should not pass the --noantialias flag
- # if the gv version is known to work properly without the flag.
- system(ShellEscape(@GV, "--scale=$main::opt_scale", "--noantialias", $fname)
- . $bg);
- } else {
- # Old gv version - only supports options that use single dash.
- print STDERR ShellEscape(@GV, "-scale", $main::opt_scale) . "\n";
- system(ShellEscape(@GV, "-scale", "$main::opt_scale", $fname) . $bg);
- }
-}
-
-sub RunEvince {
- my $fname = shift;
- my $bg = shift; # "" or " &" if we should run in background
- system(ShellEscape(@EVINCE, $fname) . $bg);
-}
-
-sub RunWeb {
- my $fname = shift;
- print STDERR "Loading web page file:///$fname\n";
-
- if (`uname` =~ /Darwin/) {
- # OS X: open will use standard preference for SVG files.
- system("/usr/bin/open", $fname);
- return;
- }
-
- # Some kind of Unix; try generic symlinks, then specific browsers.
- # (Stop once we find one.)
- # Works best if the browser is already running.
- my @alt = (
- "/etc/alternatives/gnome-www-browser",
- "/etc/alternatives/x-www-browser",
- "google-chrome",
- "firefox",
- );
- foreach my $b (@alt) {
- if (system($b, $fname) == 0) {
- return;
- }
- }
-
- print STDERR "Could not load web browser.\n";
-}
-
-sub RunKcachegrind {
- my $fname = shift;
- my $bg = shift; # "" or " &" if we should run in background
- print STDERR "Starting '@KCACHEGRIND " . $fname . $bg . "'\n";
- system(ShellEscape(@KCACHEGRIND, $fname) . $bg);
-}
-
-
-##### Interactive helper routines #####
-
-sub InteractiveMode {
- $| = 1; # Make output unbuffered for interactive mode
- my ($orig_profile, $symbols, $libs, $total) = @_;
-
- print STDERR "Welcome to jeprof! For help, type 'help'.\n";
-
- # Use ReadLine if it's installed and input comes from a console.
- if ( -t STDIN &&
- !ReadlineMightFail() &&
- defined(eval {require Term::ReadLine}) ) {
- my $term = new Term::ReadLine 'jeprof';
- while ( defined ($_ = $term->readline('(jeprof) '))) {
- $term->addhistory($_) if /\S/;
- if (!InteractiveCommand($orig_profile, $symbols, $libs, $total, $_)) {
- last; # exit when we get an interactive command to quit
- }
- }
- } else { # don't have readline
- while (1) {
- print STDERR "(jeprof) ";
- $_ = <STDIN>;
- last if ! defined $_ ;
- s/\r//g; # turn windows-looking lines into unix-looking lines
-
- # Save some flags that might be reset by InteractiveCommand()
- my $save_opt_lines = $main::opt_lines;
-
- if (!InteractiveCommand($orig_profile, $symbols, $libs, $total, $_)) {
- last; # exit when we get an interactive command to quit
- }
-
- # Restore flags
- $main::opt_lines = $save_opt_lines;
- }
- }
-}
-
-# Takes two args: orig profile, and command to run.
-# Returns 1 if we should keep going, or 0 if we were asked to quit
-sub InteractiveCommand {
- my($orig_profile, $symbols, $libs, $total, $command) = @_;
- $_ = $command; # just to make future m//'s easier
- if (!defined($_)) {
- print STDERR "\n";
- return 0;
- }
- if (m/^\s*quit/) {
- return 0;
- }
- if (m/^\s*help/) {
- InteractiveHelpMessage();
- return 1;
- }
- # Clear all the mode options -- mode is controlled by "$command"
- $main::opt_text = 0;
- $main::opt_callgrind = 0;
- $main::opt_disasm = 0;
- $main::opt_list = 0;
- $main::opt_gv = 0;
- $main::opt_evince = 0;
- $main::opt_cum = 0;
-
- if (m/^\s*(text|top)(\d*)\s*(.*)/) {
- $main::opt_text = 1;
-
- my $line_limit = ($2 ne "") ? int($2) : 10;
-
- my $routine;
- my $ignore;
- ($routine, $ignore) = ParseInteractiveArgs($3);
-
- my $profile = ProcessProfile($total, $orig_profile, $symbols, "", $ignore);
- my $reduced = ReduceProfile($symbols, $profile);
-
- # Get derived profiles
- my $flat = FlatProfile($reduced);
- my $cumulative = CumulativeProfile($reduced);
-
- PrintText($symbols, $flat, $cumulative, $line_limit);
- return 1;
- }
- if (m/^\s*callgrind\s*([^ \n]*)/) {
- $main::opt_callgrind = 1;
-
- # Get derived profiles
- my $calls = ExtractCalls($symbols, $orig_profile);
- my $filename = $1;
- if ( $1 eq '' ) {
- $filename = TempName($main::next_tmpfile, "callgrind");
- }
- PrintCallgrind($calls, $filename);
- if ( $1 eq '' ) {
- RunKcachegrind($filename, " & ");
- $main::next_tmpfile++;
- }
-
- return 1;
- }
- if (m/^\s*(web)?list\s*(.+)/) {
- my $html = (defined($1) && ($1 eq "web"));
- $main::opt_list = 1;
-
- my $routine;
- my $ignore;
- ($routine, $ignore) = ParseInteractiveArgs($2);
-
- my $profile = ProcessProfile($total, $orig_profile, $symbols, "", $ignore);
- my $reduced = ReduceProfile($symbols, $profile);
-
- # Get derived profiles
- my $flat = FlatProfile($reduced);
- my $cumulative = CumulativeProfile($reduced);
-
- PrintListing($total, $libs, $flat, $cumulative, $routine, $html);
- return 1;
- }
- if (m/^\s*disasm\s*(.+)/) {
- $main::opt_disasm = 1;
-
- my $routine;
- my $ignore;
- ($routine, $ignore) = ParseInteractiveArgs($1);
-
- # Process current profile to account for various settings
- my $profile = ProcessProfile($total, $orig_profile, $symbols, "", $ignore);
- my $reduced = ReduceProfile($symbols, $profile);
-
- # Get derived profiles
- my $flat = FlatProfile($reduced);
- my $cumulative = CumulativeProfile($reduced);
-
- PrintDisassembly($libs, $flat, $cumulative, $routine);
- return 1;
- }
- if (m/^\s*(gv|web|evince)\s*(.*)/) {
- $main::opt_gv = 0;
- $main::opt_evince = 0;
- $main::opt_web = 0;
- if ($1 eq "gv") {
- $main::opt_gv = 1;
- } elsif ($1 eq "evince") {
- $main::opt_evince = 1;
- } elsif ($1 eq "web") {
- $main::opt_web = 1;
- }
-
- my $focus;
- my $ignore;
- ($focus, $ignore) = ParseInteractiveArgs($2);
-
- # Process current profile to account for various settings
- my $profile = ProcessProfile($total, $orig_profile, $symbols,
- $focus, $ignore);
- my $reduced = ReduceProfile($symbols, $profile);
-
- # Get derived profiles
- my $flat = FlatProfile($reduced);
- my $cumulative = CumulativeProfile($reduced);
-
- if (PrintDot($main::prog, $symbols, $profile, $flat, $cumulative, $total)) {
- if ($main::opt_gv) {
- RunGV(TempName($main::next_tmpfile, "ps"), " &");
- } elsif ($main::opt_evince) {
- RunEvince(TempName($main::next_tmpfile, "pdf"), " &");
- } elsif ($main::opt_web) {
- RunWeb(TempName($main::next_tmpfile, "svg"));
- }
- $main::next_tmpfile++;
- }
- return 1;
- }
- if (m/^\s*$/) {
- return 1;
- }
- print STDERR "Unknown command: try 'help'.\n";
- return 1;
-}
-
-
-sub ProcessProfile {
- my $total_count = shift;
- my $orig_profile = shift;
- my $symbols = shift;
- my $focus = shift;
- my $ignore = shift;
-
- # Process current profile to account for various settings
- my $profile = $orig_profile;
- printf("Total: %s %s\n", Unparse($total_count), Units());
- if ($focus ne '') {
- $profile = FocusProfile($symbols, $profile, $focus);
- my $focus_count = TotalProfile($profile);
- printf("After focusing on '%s': %s %s of %s (%0.1f%%)\n",
- $focus,
- Unparse($focus_count), Units(),
- Unparse($total_count), ($focus_count*100.0) / $total_count);
- }
- if ($ignore ne '') {
- $profile = IgnoreProfile($symbols, $profile, $ignore);
- my $ignore_count = TotalProfile($profile);
- printf("After ignoring '%s': %s %s of %s (%0.1f%%)\n",
- $ignore,
- Unparse($ignore_count), Units(),
- Unparse($total_count),
- ($ignore_count*100.0) / $total_count);
- }
-
- return $profile;
-}
-
-sub InteractiveHelpMessage {
- print STDERR <<ENDOFHELP;
-Interactive jeprof mode
-
-Commands:
- gv
- gv [focus] [-ignore1] [-ignore2]
- Show graphical hierarchical display of current profile. Without
- any arguments, shows all samples in the profile. With the optional
- "focus" argument, restricts the samples shown to just those where
- the "focus" regular expression matches a routine name on the stack
- trace.
-
- web
- web [focus] [-ignore1] [-ignore2]
- Like GV, but displays profile in your web browser instead of using
- Ghostview. Works best if your web browser is already running.
- To change the browser that gets used:
- On Linux, set the /etc/alternatives/gnome-www-browser symlink.
- On OS X, change the Finder association for SVG files.
-
- list [routine_regexp] [-ignore1] [-ignore2]
- Show source listing of routines whose names match "routine_regexp"
-
- weblist [routine_regexp] [-ignore1] [-ignore2]
- Displays a source listing of routines whose names match "routine_regexp"
- in a web browser. You can click on source lines to view the
- corresponding disassembly.
-
- top [--cum] [-ignore1] [-ignore2]
- top20 [--cum] [-ignore1] [-ignore2]
- top37 [--cum] [-ignore1] [-ignore2]
- Show top lines ordered by flat profile count, or cumulative count
- if --cum is specified. If a number is present after 'top', the
- top K routines will be shown (defaults to showing the top 10)
-
- disasm [routine_regexp] [-ignore1] [-ignore2]
- Show disassembly of routines whose names match "routine_regexp",
- annotated with sample counts.
-
- callgrind
- callgrind [filename]
- Generates callgrind file. If no filename is given, kcachegrind is called.
-
- help - This listing
- quit or ^D - End jeprof
-
-For commands that accept optional -ignore tags, samples where any routine in
-the stack trace matches the regular expression in any of the -ignore
-parameters will be ignored.
-
-Further pprof details are available at this location (or one similar):
-
- /usr/doc/gperftools-$PPROF_VERSION/cpu_profiler.html
- /usr/doc/gperftools-$PPROF_VERSION/heap_profiler.html
-
-ENDOFHELP
-}
-sub ParseInteractiveArgs {
- my $args = shift;
- my $focus = "";
- my $ignore = "";
- my @x = split(/ +/, $args);
- foreach $a (@x) {
- if ($a =~ m/^(--|-)lines$/) {
- $main::opt_lines = 1;
- } elsif ($a =~ m/^(--|-)cum$/) {
- $main::opt_cum = 1;
- } elsif ($a =~ m/^-(.*)/) {
- $ignore .= (($ignore ne "") ? "|" : "" ) . $1;
- } else {
- $focus .= (($focus ne "") ? "|" : "" ) . $a;
- }
- }
- if ($ignore ne "") {
- print STDERR "Ignoring samples in call stacks that match '$ignore'\n";
- }
- return ($focus, $ignore);
-}
-
-##### Output code #####
-
-sub TempName {
- my $fnum = shift;
- my $ext = shift;
- my $file = "$main::tmpfile_ps.$fnum.$ext";
- $main::tempnames{$file} = 1;
- return $file;
-}
-
-# Print profile data in packed binary format (64-bit) to standard out
-sub PrintProfileData {
- my $profile = shift;
-
- # print header (64-bit style)
- # (zero) (header-size) (version) (sample-period) (zero)
- print pack('L*', 0, 0, 3, 0, 0, 0, 1, 0, 0, 0);
-
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @addrs = split(/\n/, $k);
- if ($#addrs >= 0) {
- my $depth = $#addrs + 1;
- # int(foo / 2**32) is the only reliable way to get rid of bottom
- # 32 bits on both 32- and 64-bit systems.
- print pack('L*', $count & 0xFFFFFFFF, int($count / 2**32));
- print pack('L*', $depth & 0xFFFFFFFF, int($depth / 2**32));
-
- foreach my $full_addr (@addrs) {
- my $addr = $full_addr;
- $addr =~ s/0x0*//; # strip off leading 0x, zeroes
- if (length($addr) > 16) {
- print STDERR "Invalid address in profile: $full_addr\n";
- next;
- }
- my $low_addr = substr($addr, -8); # get last 8 hex chars
- my $high_addr = substr($addr, -16, 8); # get up to 8 more hex chars
- print pack('L*', hex('0x' . $low_addr), hex('0x' . $high_addr));
- }
- }
- }
-}
-
-# Print symbols and profile data
-sub PrintSymbolizedProfile {
- my $symbols = shift;
- my $profile = shift;
- my $prog = shift;
-
- $SYMBOL_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- my $symbol_marker = $&;
-
- print '--- ', $symbol_marker, "\n";
- if (defined($prog)) {
- print 'binary=', $prog, "\n";
- }
- while (my ($pc, $name) = each(%{$symbols})) {
- my $sep = ' ';
- print '0x', $pc;
- # We have a list of function names, which include the inlined
- # calls. They are separated (and terminated) by --, which is
- # illegal in function names.
- for (my $j = 2; $j <= $#{$name}; $j += 3) {
- print $sep, $name->[$j];
- $sep = '--';
- }
- print "\n";
- }
- print '---', "\n";
-
- my $profile_marker;
- if ($main::profile_type eq 'heap') {
- $HEAP_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- $profile_marker = $&;
- } elsif ($main::profile_type eq 'growth') {
- $GROWTH_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- $profile_marker = $&;
- } elsif ($main::profile_type eq 'contention') {
- $CONTENTION_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- $profile_marker = $&;
- } else { # elsif ($main::profile_type eq 'cpu')
- $PROFILE_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- $profile_marker = $&;
- }
-
- print '--- ', $profile_marker, "\n";
- if (defined($main::collected_profile)) {
- # if used with remote fetch, simply dump the collected profile to output.
- open(SRC, "<$main::collected_profile");
- while (<SRC>) {
- print $_;
- }
- close(SRC);
- } else {
- # --raw/http: For everything to work correctly for non-remote profiles, we
- # would need to extend PrintProfileData() to handle all possible profile
- # types, re-enable the code that is currently disabled in ReadCPUProfile()
- # and FixCallerAddresses(), and remove the remote profile dumping code in
- # the block above.
- die "--raw/http: jeprof can only dump remote profiles for --raw\n";
- # dump a cpu-format profile to standard out
- PrintProfileData($profile);
- }
-}
-
-# Print text output
-sub PrintText {
- my $symbols = shift;
- my $flat = shift;
- my $cumulative = shift;
- my $line_limit = shift;
-
- my $total = TotalProfile($flat);
-
- # Which profile to sort by?
- my $s = $main::opt_cum ? $cumulative : $flat;
-
- my $running_sum = 0;
- my $lines = 0;
- foreach my $k (sort { GetEntry($s, $b) <=> GetEntry($s, $a) || $a cmp $b }
- keys(%{$cumulative})) {
- my $f = GetEntry($flat, $k);
- my $c = GetEntry($cumulative, $k);
- $running_sum += $f;
-
- my $sym = $k;
- if (exists($symbols->{$k})) {
- $sym = $symbols->{$k}->[0] . " " . $symbols->{$k}->[1];
- if ($main::opt_addresses) {
- $sym = $k . " " . $sym;
- }
- }
-
- if ($f != 0 || $c != 0) {
- printf("%8s %6s %6s %8s %6s %s\n",
- Unparse($f),
- Percent($f, $total),
- Percent($running_sum, $total),
- Unparse($c),
- Percent($c, $total),
- $sym);
- }
- $lines++;
- last if ($line_limit >= 0 && $lines >= $line_limit);
- }
-}
-
-# Callgrind format has a compression for repeated function and file
-# names. You show the name the first time, and just use its number
-# subsequently. This can cut down the file to about a third or a
-# quarter of its uncompressed size. $key and $val are the key/value
-# pair that would normally be printed by callgrind; $map is a map from
-# value to number.
-sub CompressedCGName {
- my($key, $val, $map) = @_;
- my $idx = $map->{$val};
- # For very short keys, providing an index hurts rather than helps.
- if (length($val) <= 3) {
- return "$key=$val\n";
- } elsif (defined($idx)) {
- return "$key=($idx)\n";
- } else {
- # scalar(keys $map) gives the number of items in the map.
- $idx = scalar(keys(%{$map})) + 1;
- $map->{$val} = $idx;
- return "$key=($idx) $val\n";
- }
-}
-
-# Print the call graph in a way that's suiteable for callgrind.
-sub PrintCallgrind {
- my $calls = shift;
- my $filename;
- my %filename_to_index_map;
- my %fnname_to_index_map;
-
- if ($main::opt_interactive) {
- $filename = shift;
- print STDERR "Writing callgrind file to '$filename'.\n"
- } else {
- $filename = "&STDOUT";
- }
- open(CG, ">$filename");
- printf CG ("events: Hits\n\n");
- foreach my $call ( map { $_->[0] }
- sort { $a->[1] cmp $b ->[1] ||
- $a->[2] <=> $b->[2] }
- map { /([^:]+):(\d+):([^ ]+)( -> ([^:]+):(\d+):(.+))?/;
- [$_, $1, $2] }
- keys %$calls ) {
- my $count = int($calls->{$call});
- $call =~ /([^:]+):(\d+):([^ ]+)( -> ([^:]+):(\d+):(.+))?/;
- my ( $caller_file, $caller_line, $caller_function,
- $callee_file, $callee_line, $callee_function ) =
- ( $1, $2, $3, $5, $6, $7 );
-
- # TODO(csilvers): for better compression, collect all the
- # caller/callee_files and functions first, before printing
- # anything, and only compress those referenced more than once.
- printf CG CompressedCGName("fl", $caller_file, \%filename_to_index_map);
- printf CG CompressedCGName("fn", $caller_function, \%fnname_to_index_map);
- if (defined $6) {
- printf CG CompressedCGName("cfl", $callee_file, \%filename_to_index_map);
- printf CG CompressedCGName("cfn", $callee_function, \%fnname_to_index_map);
- printf CG ("calls=$count $callee_line\n");
- }
- printf CG ("$caller_line $count\n\n");
- }
-}
-
-# Print disassembly for all all routines that match $main::opt_disasm
-sub PrintDisassembly {
- my $libs = shift;
- my $flat = shift;
- my $cumulative = shift;
- my $disasm_opts = shift;
-
- my $total = TotalProfile($flat);
-
- foreach my $lib (@{$libs}) {
- my $symbol_table = GetProcedureBoundaries($lib->[0], $disasm_opts);
- my $offset = AddressSub($lib->[1], $lib->[3]);
- foreach my $routine (sort ByName keys(%{$symbol_table})) {
- my $start_addr = $symbol_table->{$routine}->[0];
- my $end_addr = $symbol_table->{$routine}->[1];
- # See if there are any samples in this routine
- my $length = hex(AddressSub($end_addr, $start_addr));
- my $addr = AddressAdd($start_addr, $offset);
- for (my $i = 0; $i < $length; $i++) {
- if (defined($cumulative->{$addr})) {
- PrintDisassembledFunction($lib->[0], $offset,
- $routine, $flat, $cumulative,
- $start_addr, $end_addr, $total);
- last;
- }
- $addr = AddressInc($addr);
- }
- }
- }
-}
-
-# Return reference to array of tuples of the form:
-# [start_address, filename, linenumber, instruction, limit_address]
-# E.g.,
-# ["0x806c43d", "/foo/bar.cc", 131, "ret", "0x806c440"]
-sub Disassemble {
- my $prog = shift;
- my $offset = shift;
- my $start_addr = shift;
- my $end_addr = shift;
-
- my $objdump = $obj_tool_map{"objdump"};
- my $cmd = ShellEscape($objdump, "-C", "-d", "-l", "--no-show-raw-insn",
- "--start-address=0x$start_addr",
- "--stop-address=0x$end_addr", $prog);
- open(OBJDUMP, "$cmd |") || error("$cmd: $!\n");
- my @result = ();
- my $filename = "";
- my $linenumber = -1;
- my $last = ["", "", "", ""];
- while (<OBJDUMP>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- chop;
- if (m|\s*([^:\s]+):(\d+)\s*$|) {
- # Location line of the form:
- # <filename>:<linenumber>
- $filename = $1;
- $linenumber = $2;
- } elsif (m/^ +([0-9a-f]+):\s*(.*)/) {
- # Disassembly line -- zero-extend address to full length
- my $addr = HexExtend($1);
- my $k = AddressAdd($addr, $offset);
- $last->[4] = $k; # Store ending address for previous instruction
- $last = [$k, $filename, $linenumber, $2, $end_addr];
- push(@result, $last);
- }
- }
- close(OBJDUMP);
- return @result;
-}
-
-# The input file should contain lines of the form /proc/maps-like
-# output (same format as expected from the profiles) or that looks
-# like hex addresses (like "0xDEADBEEF"). We will parse all
-# /proc/maps output, and for all the hex addresses, we will output
-# "short" symbol names, one per line, in the same order as the input.
-sub PrintSymbols {
- my $maps_and_symbols_file = shift;
-
- # ParseLibraries expects pcs to be in a set. Fine by us...
- my @pclist = (); # pcs in sorted order
- my $pcs = {};
- my $map = "";
- foreach my $line (<$maps_and_symbols_file>) {
- $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
- if ($line =~ /\b(0x[0-9a-f]+)\b/i) {
- push(@pclist, HexExtend($1));
- $pcs->{$pclist[-1]} = 1;
- } else {
- $map .= $line;
- }
- }
-
- my $libs = ParseLibraries($main::prog, $map, $pcs);
- my $symbols = ExtractSymbols($libs, $pcs);
-
- foreach my $pc (@pclist) {
- # ->[0] is the shortname, ->[2] is the full name
- print(($symbols->{$pc}->[0] || "??") . "\n");
- }
-}
-
-
-# For sorting functions by name
-sub ByName {
- return ShortFunctionName($a) cmp ShortFunctionName($b);
-}
-
-# Print source-listing for all all routines that match $list_opts
-sub PrintListing {
- my $total = shift;
- my $libs = shift;
- my $flat = shift;
- my $cumulative = shift;
- my $list_opts = shift;
- my $html = shift;
-
- my $output = \*STDOUT;
- my $fname = "";
-
- if ($html) {
- # Arrange to write the output to a temporary file
- $fname = TempName($main::next_tmpfile, "html");
- $main::next_tmpfile++;
- if (!open(TEMP, ">$fname")) {
- print STDERR "$fname: $!\n";
- return;
- }
- $output = \*TEMP;
- print $output HtmlListingHeader();
- printf $output ("<div class=\"legend\">%s<br>Total: %s %s</div>\n",
- $main::prog, Unparse($total), Units());
- }
-
- my $listed = 0;
- foreach my $lib (@{$libs}) {
- my $symbol_table = GetProcedureBoundaries($lib->[0], $list_opts);
- my $offset = AddressSub($lib->[1], $lib->[3]);
- foreach my $routine (sort ByName keys(%{$symbol_table})) {
- # Print if there are any samples in this routine
- my $start_addr = $symbol_table->{$routine}->[0];
- my $end_addr = $symbol_table->{$routine}->[1];
- my $length = hex(AddressSub($end_addr, $start_addr));
- my $addr = AddressAdd($start_addr, $offset);
- for (my $i = 0; $i < $length; $i++) {
- if (defined($cumulative->{$addr})) {
- $listed += PrintSource(
- $lib->[0], $offset,
- $routine, $flat, $cumulative,
- $start_addr, $end_addr,
- $html,
- $output);
- last;
- }
- $addr = AddressInc($addr);
- }
- }
- }
-
- if ($html) {
- if ($listed > 0) {
- print $output HtmlListingFooter();
- close($output);
- RunWeb($fname);
- } else {
- close($output);
- unlink($fname);
- }
- }
-}
-
-sub HtmlListingHeader {
- return <<'EOF';
-<DOCTYPE html>
-<html>
-<head>
-<title>Pprof listing</title>
-<style type="text/css">
-body {
- font-family: sans-serif;
-}
-h1 {
- font-size: 1.5em;
- margin-bottom: 4px;
-}
-.legend {
- font-size: 1.25em;
-}
-.line {
- color: #aaaaaa;
-}
-.nop {
- color: #aaaaaa;
-}
-.unimportant {
- color: #cccccc;
-}
-.disasmloc {
- color: #000000;
-}
-.deadsrc {
- cursor: pointer;
-}
-.deadsrc:hover {
- background-color: #eeeeee;
-}
-.livesrc {
- color: #0000ff;
- cursor: pointer;
-}
-.livesrc:hover {
- background-color: #eeeeee;
-}
-.asm {
- color: #008800;
- display: none;
-}
-</style>
-<script type="text/javascript">
-function jeprof_toggle_asm(e) {
- var target;
- if (!e) e = window.event;
- if (e.target) target = e.target;
- else if (e.srcElement) target = e.srcElement;
-
- if (target) {
- var asm = target.nextSibling;
- if (asm && asm.className == "asm") {
- asm.style.display = (asm.style.display == "block" ? "" : "block");
- e.preventDefault();
- return false;
- }
- }
-}
-</script>
-</head>
-<body>
-EOF
-}
-
-sub HtmlListingFooter {
- return <<'EOF';
-</body>
-</html>
-EOF
-}
-
-sub HtmlEscape {
- my $text = shift;
- $text =~ s/&/&amp;/g;
- $text =~ s/</&lt;/g;
- $text =~ s/>/&gt;/g;
- return $text;
-}
-
-# Returns the indentation of the line, if it has any non-whitespace
-# characters. Otherwise, returns -1.
-sub Indentation {
- my $line = shift;
- if (m/^(\s*)\S/) {
- return length($1);
- } else {
- return -1;
- }
-}
-
-# If the symbol table contains inlining info, Disassemble() may tag an
-# instruction with a location inside an inlined function. But for
-# source listings, we prefer to use the location in the function we
-# are listing. So use MapToSymbols() to fetch full location
-# information for each instruction and then pick out the first
-# location from a location list (location list contains callers before
-# callees in case of inlining).
-#
-# After this routine has run, each entry in $instructions contains:
-# [0] start address
-# [1] filename for function we are listing
-# [2] line number for function we are listing
-# [3] disassembly
-# [4] limit address
-# [5] most specific filename (may be different from [1] due to inlining)
-# [6] most specific line number (may be different from [2] due to inlining)
-sub GetTopLevelLineNumbers {
- my ($lib, $offset, $instructions) = @_;
- my $pcs = [];
- for (my $i = 0; $i <= $#{$instructions}; $i++) {
- push(@{$pcs}, $instructions->[$i]->[0]);
- }
- my $symbols = {};
- MapToSymbols($lib, $offset, $pcs, $symbols);
- for (my $i = 0; $i <= $#{$instructions}; $i++) {
- my $e = $instructions->[$i];
- push(@{$e}, $e->[1]);
- push(@{$e}, $e->[2]);
- my $addr = $e->[0];
- my $sym = $symbols->{$addr};
- if (defined($sym)) {
- if ($#{$sym} >= 2 && $sym->[1] =~ m/^(.*):(\d+)$/) {
- $e->[1] = $1; # File name
- $e->[2] = $2; # Line number
- }
- }
- }
-}
-
-# Print source-listing for one routine
-sub PrintSource {
- my $prog = shift;
- my $offset = shift;
- my $routine = shift;
- my $flat = shift;
- my $cumulative = shift;
- my $start_addr = shift;
- my $end_addr = shift;
- my $html = shift;
- my $output = shift;
-
- # Disassemble all instructions (just to get line numbers)
- my @instructions = Disassemble($prog, $offset, $start_addr, $end_addr);
- GetTopLevelLineNumbers($prog, $offset, \@instructions);
-
- # Hack 1: assume that the first source file encountered in the
- # disassembly contains the routine
- my $filename = undef;
- for (my $i = 0; $i <= $#instructions; $i++) {
- if ($instructions[$i]->[2] >= 0) {
- $filename = $instructions[$i]->[1];
- last;
- }
- }
- if (!defined($filename)) {
- print STDERR "no filename found in $routine\n";
- return 0;
- }
-
- # Hack 2: assume that the largest line number from $filename is the
- # end of the procedure. This is typically safe since if P1 contains
- # an inlined call to P2, then P2 usually occurs earlier in the
- # source file. If this does not work, we might have to compute a
- # density profile or just print all regions we find.
- my $lastline = 0;
- for (my $i = 0; $i <= $#instructions; $i++) {
- my $f = $instructions[$i]->[1];
- my $l = $instructions[$i]->[2];
- if (($f eq $filename) && ($l > $lastline)) {
- $lastline = $l;
- }
- }
-
- # Hack 3: assume the first source location from "filename" is the start of
- # the source code.
- my $firstline = 1;
- for (my $i = 0; $i <= $#instructions; $i++) {
- if ($instructions[$i]->[1] eq $filename) {
- $firstline = $instructions[$i]->[2];
- last;
- }
- }
-
- # Hack 4: Extend last line forward until its indentation is less than
- # the indentation we saw on $firstline
- my $oldlastline = $lastline;
- {
- if (!open(FILE, "<$filename")) {
- print STDERR "$filename: $!\n";
- return 0;
- }
- my $l = 0;
- my $first_indentation = -1;
- while (<FILE>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- $l++;
- my $indent = Indentation($_);
- if ($l >= $firstline) {
- if ($first_indentation < 0 && $indent >= 0) {
- $first_indentation = $indent;
- last if ($first_indentation == 0);
- }
- }
- if ($l >= $lastline && $indent >= 0) {
- if ($indent >= $first_indentation) {
- $lastline = $l+1;
- } else {
- last;
- }
- }
- }
- close(FILE);
- }
-
- # Assign all samples to the range $firstline,$lastline,
- # Hack 4: If an instruction does not occur in the range, its samples
- # are moved to the next instruction that occurs in the range.
- my $samples1 = {}; # Map from line number to flat count
- my $samples2 = {}; # Map from line number to cumulative count
- my $running1 = 0; # Unassigned flat counts
- my $running2 = 0; # Unassigned cumulative counts
- my $total1 = 0; # Total flat counts
- my $total2 = 0; # Total cumulative counts
- my %disasm = (); # Map from line number to disassembly
- my $running_disasm = ""; # Unassigned disassembly
- my $skip_marker = "---\n";
- if ($html) {
- $skip_marker = "";
- for (my $l = $firstline; $l <= $lastline; $l++) {
- $disasm{$l} = "";
- }
- }
- my $last_dis_filename = '';
- my $last_dis_linenum = -1;
- my $last_touched_line = -1; # To detect gaps in disassembly for a line
- foreach my $e (@instructions) {
- # Add up counts for all address that fall inside this instruction
- my $c1 = 0;
- my $c2 = 0;
- for (my $a = $e->[0]; $a lt $e->[4]; $a = AddressInc($a)) {
- $c1 += GetEntry($flat, $a);
- $c2 += GetEntry($cumulative, $a);
- }
-
- if ($html) {
- my $dis = sprintf(" %6s %6s \t\t%8s: %s ",
- HtmlPrintNumber($c1),
- HtmlPrintNumber($c2),
- UnparseAddress($offset, $e->[0]),
- CleanDisassembly($e->[3]));
-
- # Append the most specific source line associated with this instruction
- if (length($dis) < 80) { $dis .= (' ' x (80 - length($dis))) };
- $dis = HtmlEscape($dis);
- my $f = $e->[5];
- my $l = $e->[6];
- if ($f ne $last_dis_filename) {
- $dis .= sprintf("<span class=disasmloc>%s:%d</span>",
- HtmlEscape(CleanFileName($f)), $l);
- } elsif ($l ne $last_dis_linenum) {
- # De-emphasize the unchanged file name portion
- $dis .= sprintf("<span class=unimportant>%s</span>" .
- "<span class=disasmloc>:%d</span>",
- HtmlEscape(CleanFileName($f)), $l);
- } else {
- # De-emphasize the entire location
- $dis .= sprintf("<span class=unimportant>%s:%d</span>",
- HtmlEscape(CleanFileName($f)), $l);
- }
- $last_dis_filename = $f;
- $last_dis_linenum = $l;
- $running_disasm .= $dis;
- $running_disasm .= "\n";
- }
-
- $running1 += $c1;
- $running2 += $c2;
- $total1 += $c1;
- $total2 += $c2;
- my $file = $e->[1];
- my $line = $e->[2];
- if (($file eq $filename) &&
- ($line >= $firstline) &&
- ($line <= $lastline)) {
- # Assign all accumulated samples to this line
- AddEntry($samples1, $line, $running1);
- AddEntry($samples2, $line, $running2);
- $running1 = 0;
- $running2 = 0;
- if ($html) {
- if ($line != $last_touched_line && $disasm{$line} ne '') {
- $disasm{$line} .= "\n";
- }
- $disasm{$line} .= $running_disasm;
- $running_disasm = '';
- $last_touched_line = $line;
- }
- }
- }
-
- # Assign any leftover samples to $lastline
- AddEntry($samples1, $lastline, $running1);
- AddEntry($samples2, $lastline, $running2);
- if ($html) {
- if ($lastline != $last_touched_line && $disasm{$lastline} ne '') {
- $disasm{$lastline} .= "\n";
- }
- $disasm{$lastline} .= $running_disasm;
- }
-
- if ($html) {
- printf $output (
- "<h1>%s</h1>%s\n<pre onClick=\"jeprof_toggle_asm()\">\n" .
- "Total:%6s %6s (flat / cumulative %s)\n",
- HtmlEscape(ShortFunctionName($routine)),
- HtmlEscape(CleanFileName($filename)),
- Unparse($total1),
- Unparse($total2),
- Units());
- } else {
- printf $output (
- "ROUTINE ====================== %s in %s\n" .
- "%6s %6s Total %s (flat / cumulative)\n",
- ShortFunctionName($routine),
- CleanFileName($filename),
- Unparse($total1),
- Unparse($total2),
- Units());
- }
- if (!open(FILE, "<$filename")) {
- print STDERR "$filename: $!\n";
- return 0;
- }
- my $l = 0;
- while (<FILE>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- $l++;
- if ($l >= $firstline - 5 &&
- (($l <= $oldlastline + 5) || ($l <= $lastline))) {
- chop;
- my $text = $_;
- if ($l == $firstline) { print $output $skip_marker; }
- my $n1 = GetEntry($samples1, $l);
- my $n2 = GetEntry($samples2, $l);
- if ($html) {
- # Emit a span that has one of the following classes:
- # livesrc -- has samples
- # deadsrc -- has disassembly, but with no samples
- # nop -- has no matching disasembly
- # Also emit an optional span containing disassembly.
- my $dis = $disasm{$l};
- my $asm = "";
- if (defined($dis) && $dis ne '') {
- $asm = "<span class=\"asm\">" . $dis . "</span>";
- }
- my $source_class = (($n1 + $n2 > 0)
- ? "livesrc"
- : (($asm ne "") ? "deadsrc" : "nop"));
- printf $output (
- "<span class=\"line\">%5d</span> " .
- "<span class=\"%s\">%6s %6s %s</span>%s\n",
- $l, $source_class,
- HtmlPrintNumber($n1),
- HtmlPrintNumber($n2),
- HtmlEscape($text),
- $asm);
- } else {
- printf $output(
- "%6s %6s %4d: %s\n",
- UnparseAlt($n1),
- UnparseAlt($n2),
- $l,
- $text);
- }
- if ($l == $lastline) { print $output $skip_marker; }
- };
- }
- close(FILE);
- if ($html) {
- print $output "</pre>\n";
- }
- return 1;
-}
-
-# Return the source line for the specified file/linenumber.
-# Returns undef if not found.
-sub SourceLine {
- my $file = shift;
- my $line = shift;
-
- # Look in cache
- if (!defined($main::source_cache{$file})) {
- if (100 < scalar keys(%main::source_cache)) {
- # Clear the cache when it gets too big
- $main::source_cache = ();
- }
-
- # Read all lines from the file
- if (!open(FILE, "<$file")) {
- print STDERR "$file: $!\n";
- $main::source_cache{$file} = []; # Cache the negative result
- return undef;
- }
- my $lines = [];
- push(@{$lines}, ""); # So we can use 1-based line numbers as indices
- while (<FILE>) {
- push(@{$lines}, $_);
- }
- close(FILE);
-
- # Save the lines in the cache
- $main::source_cache{$file} = $lines;
- }
-
- my $lines = $main::source_cache{$file};
- if (($line < 0) || ($line > $#{$lines})) {
- return undef;
- } else {
- return $lines->[$line];
- }
-}
-
-# Print disassembly for one routine with interspersed source if available
-sub PrintDisassembledFunction {
- my $prog = shift;
- my $offset = shift;
- my $routine = shift;
- my $flat = shift;
- my $cumulative = shift;
- my $start_addr = shift;
- my $end_addr = shift;
- my $total = shift;
-
- # Disassemble all instructions
- my @instructions = Disassemble($prog, $offset, $start_addr, $end_addr);
-
- # Make array of counts per instruction
- my @flat_count = ();
- my @cum_count = ();
- my $flat_total = 0;
- my $cum_total = 0;
- foreach my $e (@instructions) {
- # Add up counts for all address that fall inside this instruction
- my $c1 = 0;
- my $c2 = 0;
- for (my $a = $e->[0]; $a lt $e->[4]; $a = AddressInc($a)) {
- $c1 += GetEntry($flat, $a);
- $c2 += GetEntry($cumulative, $a);
- }
- push(@flat_count, $c1);
- push(@cum_count, $c2);
- $flat_total += $c1;
- $cum_total += $c2;
- }
-
- # Print header with total counts
- printf("ROUTINE ====================== %s\n" .
- "%6s %6s %s (flat, cumulative) %.1f%% of total\n",
- ShortFunctionName($routine),
- Unparse($flat_total),
- Unparse($cum_total),
- Units(),
- ($cum_total * 100.0) / $total);
-
- # Process instructions in order
- my $current_file = "";
- for (my $i = 0; $i <= $#instructions; ) {
- my $e = $instructions[$i];
-
- # Print the new file name whenever we switch files
- if ($e->[1] ne $current_file) {
- $current_file = $e->[1];
- my $fname = $current_file;
- $fname =~ s|^\./||; # Trim leading "./"
-
- # Shorten long file names
- if (length($fname) >= 58) {
- $fname = "..." . substr($fname, -55);
- }
- printf("-------------------- %s\n", $fname);
- }
-
- # TODO: Compute range of lines to print together to deal with
- # small reorderings.
- my $first_line = $e->[2];
- my $last_line = $first_line;
- my %flat_sum = ();
- my %cum_sum = ();
- for (my $l = $first_line; $l <= $last_line; $l++) {
- $flat_sum{$l} = 0;
- $cum_sum{$l} = 0;
- }
-
- # Find run of instructions for this range of source lines
- my $first_inst = $i;
- while (($i <= $#instructions) &&
- ($instructions[$i]->[2] >= $first_line) &&
- ($instructions[$i]->[2] <= $last_line)) {
- $e = $instructions[$i];
- $flat_sum{$e->[2]} += $flat_count[$i];
- $cum_sum{$e->[2]} += $cum_count[$i];
- $i++;
- }
- my $last_inst = $i - 1;
-
- # Print source lines
- for (my $l = $first_line; $l <= $last_line; $l++) {
- my $line = SourceLine($current_file, $l);
- if (!defined($line)) {
- $line = "?\n";
- next;
- } else {
- $line =~ s/^\s+//;
- }
- printf("%6s %6s %5d: %s",
- UnparseAlt($flat_sum{$l}),
- UnparseAlt($cum_sum{$l}),
- $l,
- $line);
- }
-
- # Print disassembly
- for (my $x = $first_inst; $x <= $last_inst; $x++) {
- my $e = $instructions[$x];
- printf("%6s %6s %8s: %6s\n",
- UnparseAlt($flat_count[$x]),
- UnparseAlt($cum_count[$x]),
- UnparseAddress($offset, $e->[0]),
- CleanDisassembly($e->[3]));
- }
- }
-}
-
-# Print DOT graph
-sub PrintDot {
- my $prog = shift;
- my $symbols = shift;
- my $raw = shift;
- my $flat = shift;
- my $cumulative = shift;
- my $overall_total = shift;
-
- # Get total
- my $local_total = TotalProfile($flat);
- my $nodelimit = int($main::opt_nodefraction * $local_total);
- my $edgelimit = int($main::opt_edgefraction * $local_total);
- my $nodecount = $main::opt_nodecount;
-
- # Find nodes to include
- my @list = (sort { abs(GetEntry($cumulative, $b)) <=>
- abs(GetEntry($cumulative, $a))
- || $a cmp $b }
- keys(%{$cumulative}));
- my $last = $nodecount - 1;
- if ($last > $#list) {
- $last = $#list;
- }
- while (($last >= 0) &&
- (abs(GetEntry($cumulative, $list[$last])) <= $nodelimit)) {
- $last--;
- }
- if ($last < 0) {
- print STDERR "No nodes to print\n";
- return 0;
- }
-
- if ($nodelimit > 0 || $edgelimit > 0) {
- printf STDERR ("Dropping nodes with <= %s %s; edges with <= %s abs(%s)\n",
- Unparse($nodelimit), Units(),
- Unparse($edgelimit), Units());
- }
-
- # Open DOT output file
- my $output;
- my $escaped_dot = ShellEscape(@DOT);
- my $escaped_ps2pdf = ShellEscape(@PS2PDF);
- if ($main::opt_gv) {
- my $escaped_outfile = ShellEscape(TempName($main::next_tmpfile, "ps"));
- $output = "| $escaped_dot -Tps2 >$escaped_outfile";
- } elsif ($main::opt_evince) {
- my $escaped_outfile = ShellEscape(TempName($main::next_tmpfile, "pdf"));
- $output = "| $escaped_dot -Tps2 | $escaped_ps2pdf - $escaped_outfile";
- } elsif ($main::opt_ps) {
- $output = "| $escaped_dot -Tps2";
- } elsif ($main::opt_pdf) {
- $output = "| $escaped_dot -Tps2 | $escaped_ps2pdf - -";
- } elsif ($main::opt_web || $main::opt_svg) {
- # We need to post-process the SVG, so write to a temporary file always.
- my $escaped_outfile = ShellEscape(TempName($main::next_tmpfile, "svg"));
- $output = "| $escaped_dot -Tsvg >$escaped_outfile";
- } elsif ($main::opt_gif) {
- $output = "| $escaped_dot -Tgif";
- } else {
- $output = ">&STDOUT";
- }
- open(DOT, $output) || error("$output: $!\n");
-
- # Title
- printf DOT ("digraph \"%s; %s %s\" {\n",
- $prog,
- Unparse($overall_total),
- Units());
- if ($main::opt_pdf) {
- # The output is more printable if we set the page size for dot.
- printf DOT ("size=\"8,11\"\n");
- }
- printf DOT ("node [width=0.375,height=0.25];\n");
-
- # Print legend
- printf DOT ("Legend [shape=box,fontsize=24,shape=plaintext," .
- "label=\"%s\\l%s\\l%s\\l%s\\l%s\\l\"];\n",
- $prog,
- sprintf("Total %s: %s", Units(), Unparse($overall_total)),
- sprintf("Focusing on: %s", Unparse($local_total)),
- sprintf("Dropped nodes with <= %s abs(%s)",
- Unparse($nodelimit), Units()),
- sprintf("Dropped edges with <= %s %s",
- Unparse($edgelimit), Units())
- );
-
- # Print nodes
- my %node = ();
- my $nextnode = 1;
- foreach my $a (@list[0..$last]) {
- # Pick font size
- my $f = GetEntry($flat, $a);
- my $c = GetEntry($cumulative, $a);
-
- my $fs = 8;
- if ($local_total > 0) {
- $fs = 8 + (50.0 * sqrt(abs($f * 1.0 / $local_total)));
- }
-
- $node{$a} = $nextnode++;
- my $sym = $a;
- $sym =~ s/\s+/\\n/g;
- $sym =~ s/::/\\n/g;
-
- # Extra cumulative info to print for non-leaves
- my $extra = "";
- if ($f != $c) {
- $extra = sprintf("\\rof %s (%s)",
- Unparse($c),
- Percent($c, $local_total));
- }
- my $style = "";
- if ($main::opt_heapcheck) {
- if ($f > 0) {
- # make leak-causing nodes more visible (add a background)
- $style = ",style=filled,fillcolor=gray"
- } elsif ($f < 0) {
- # make anti-leak-causing nodes (which almost never occur)
- # stand out as well (triple border)
- $style = ",peripheries=3"
- }
- }
-
- printf DOT ("N%d [label=\"%s\\n%s (%s)%s\\r" .
- "\",shape=box,fontsize=%.1f%s];\n",
- $node{$a},
- $sym,
- Unparse($f),
- Percent($f, $local_total),
- $extra,
- $fs,
- $style,
- );
- }
-
- # Get edges and counts per edge
- my %edge = ();
- my $n;
- my $fullname_to_shortname_map = {};
- FillFullnameToShortnameMap($symbols, $fullname_to_shortname_map);
- foreach my $k (keys(%{$raw})) {
- # TODO: omit low %age edges
- $n = $raw->{$k};
- my @translated = TranslateStack($symbols, $fullname_to_shortname_map, $k);
- for (my $i = 1; $i <= $#translated; $i++) {
- my $src = $translated[$i];
- my $dst = $translated[$i-1];
- #next if ($src eq $dst); # Avoid self-edges?
- if (exists($node{$src}) && exists($node{$dst})) {
- my $edge_label = "$src\001$dst";
- if (!exists($edge{$edge_label})) {
- $edge{$edge_label} = 0;
- }
- $edge{$edge_label} += $n;
- }
- }
- }
-
- # Print edges (process in order of decreasing counts)
- my %indegree = (); # Number of incoming edges added per node so far
- my %outdegree = (); # Number of outgoing edges added per node so far
- foreach my $e (sort { $edge{$b} <=> $edge{$a} } keys(%edge)) {
- my @x = split(/\001/, $e);
- $n = $edge{$e};
-
- # Initialize degree of kept incoming and outgoing edges if necessary
- my $src = $x[0];
- my $dst = $x[1];
- if (!exists($outdegree{$src})) { $outdegree{$src} = 0; }
- if (!exists($indegree{$dst})) { $indegree{$dst} = 0; }
-
- my $keep;
- if ($indegree{$dst} == 0) {
- # Keep edge if needed for reachability
- $keep = 1;
- } elsif (abs($n) <= $edgelimit) {
- # Drop if we are below --edgefraction
- $keep = 0;
- } elsif ($outdegree{$src} >= $main::opt_maxdegree ||
- $indegree{$dst} >= $main::opt_maxdegree) {
- # Keep limited number of in/out edges per node
- $keep = 0;
- } else {
- $keep = 1;
- }
-
- if ($keep) {
- $outdegree{$src}++;
- $indegree{$dst}++;
-
- # Compute line width based on edge count
- my $fraction = abs($local_total ? (3 * ($n / $local_total)) : 0);
- if ($fraction > 1) { $fraction = 1; }
- my $w = $fraction * 2;
- if ($w < 1 && ($main::opt_web || $main::opt_svg)) {
- # SVG output treats line widths < 1 poorly.
- $w = 1;
- }
-
- # Dot sometimes segfaults if given edge weights that are too large, so
- # we cap the weights at a large value
- my $edgeweight = abs($n) ** 0.7;
- if ($edgeweight > 100000) { $edgeweight = 100000; }
- $edgeweight = int($edgeweight);
-
- my $style = sprintf("setlinewidth(%f)", $w);
- if ($x[1] =~ m/\(inline\)/) {
- $style .= ",dashed";
- }
-
- # Use a slightly squashed function of the edge count as the weight
- printf DOT ("N%s -> N%s [label=%s, weight=%d, style=\"%s\"];\n",
- $node{$x[0]},
- $node{$x[1]},
- Unparse($n),
- $edgeweight,
- $style);
- }
- }
-
- print DOT ("}\n");
- close(DOT);
-
- if ($main::opt_web || $main::opt_svg) {
- # Rewrite SVG to be more usable inside web browser.
- RewriteSvg(TempName($main::next_tmpfile, "svg"));
- }
-
- return 1;
-}
-
-sub RewriteSvg {
- my $svgfile = shift;
-
- open(SVG, $svgfile) || die "open temp svg: $!";
- my @svg = <SVG>;
- close(SVG);
- unlink $svgfile;
- my $svg = join('', @svg);
-
- # Dot's SVG output is
- #
- # <svg width="___" height="___"
- # viewBox="___" xmlns=...>
- # <g id="graph0" transform="...">
- # ...
- # </g>
- # </svg>
- #
- # Change it to
- #
- # <svg width="100%" height="100%"
- # xmlns=...>
- # $svg_javascript
- # <g id="viewport" transform="translate(0,0)">
- # <g id="graph0" transform="...">
- # ...
- # </g>
- # </g>
- # </svg>
-
- # Fix width, height; drop viewBox.
- $svg =~ s/(?s)<svg width="[^"]+" height="[^"]+"(.*?)viewBox="[^"]+"/<svg width="100%" height="100%"$1/;
-
- # Insert script, viewport <g> above first <g>
- my $svg_javascript = SvgJavascript();
- my $viewport = "<g id=\"viewport\" transform=\"translate(0,0)\">\n";
- $svg =~ s/<g id="graph\d"/$svg_javascript$viewport$&/;
-
- # Insert final </g> above </svg>.
- $svg =~ s/(.*)(<\/svg>)/$1<\/g>$2/;
- $svg =~ s/<g id="graph\d"(.*?)/<g id="viewport"$1/;
-
- if ($main::opt_svg) {
- # --svg: write to standard output.
- print $svg;
- } else {
- # Write back to temporary file.
- open(SVG, ">$svgfile") || die "open $svgfile: $!";
- print SVG $svg;
- close(SVG);
- }
-}
-
-sub SvgJavascript {
- return <<'EOF';
-<script type="text/ecmascript"><![CDATA[
-// SVGPan
-// http://www.cyberz.org/blog/2009/12/08/svgpan-a-javascript-svg-panzoomdrag-library/
-// Local modification: if(true || ...) below to force panning, never moving.
-
-/**
- * SVGPan library 1.2
- * ====================
- *
- * Given an unique existing element with id "viewport", including the
- * the library into any SVG adds the following capabilities:
- *
- * - Mouse panning
- * - Mouse zooming (using the wheel)
- * - Object dargging
- *
- * Known issues:
- *
- * - Zooming (while panning) on Safari has still some issues
- *
- * Releases:
- *
- * 1.2, Sat Mar 20 08:42:50 GMT 2010, Zeng Xiaohui
- * Fixed a bug with browser mouse handler interaction
- *
- * 1.1, Wed Feb 3 17:39:33 GMT 2010, Zeng Xiaohui
- * Updated the zoom code to support the mouse wheel on Safari/Chrome
- *
- * 1.0, Andrea Leofreddi
- * First release
- *
- * This code is licensed under the following BSD license:
- *
- * Copyright 2009-2010 Andrea Leofreddi <a.leofreddi@itcharm.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.
- *
- * THIS SOFTWARE IS PROVIDED BY Andrea Leofreddi ``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 Andrea Leofreddi 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 views and conclusions contained in the software and documentation are those of the
- * authors and should not be interpreted as representing official policies, either expressed
- * or implied, of Andrea Leofreddi.
- */
-
-var root = document.documentElement;
-
-var state = 'none', stateTarget, stateOrigin, stateTf;
-
-setupHandlers(root);
-
-/**
- * Register handlers
- */
-function setupHandlers(root){
- setAttributes(root, {
- "onmouseup" : "add(evt)",
- "onmousedown" : "handleMouseDown(evt)",
- "onmousemove" : "handleMouseMove(evt)",
- "onmouseup" : "handleMouseUp(evt)",
- //"onmouseout" : "handleMouseUp(evt)", // Decomment this to stop the pan functionality when dragging out of the SVG element
- });
-
- if(navigator.userAgent.toLowerCase().indexOf('webkit') >= 0)
- window.addEventListener('mousewheel', handleMouseWheel, false); // Chrome/Safari
- else
- window.addEventListener('DOMMouseScroll', handleMouseWheel, false); // Others
-
- var g = svgDoc.getElementById("svg");
- g.width = "100%";
- g.height = "100%";
-}
-
-/**
- * Instance an SVGPoint object with given event coordinates.
- */
-function getEventPoint(evt) {
- var p = root.createSVGPoint();
-
- p.x = evt.clientX;
- p.y = evt.clientY;
-
- return p;
-}
-
-/**
- * Sets the current transform matrix of an element.
- */
-function setCTM(element, matrix) {
- var s = "matrix(" + matrix.a + "," + matrix.b + "," + matrix.c + "," + matrix.d + "," + matrix.e + "," + matrix.f + ")";
-
- element.setAttribute("transform", s);
-}
-
-/**
- * Dumps a matrix to a string (useful for debug).
- */
-function dumpMatrix(matrix) {
- var s = "[ " + matrix.a + ", " + matrix.c + ", " + matrix.e + "\n " + matrix.b + ", " + matrix.d + ", " + matrix.f + "\n 0, 0, 1 ]";
-
- return s;
-}
-
-/**
- * Sets attributes of an element.
- */
-function setAttributes(element, attributes){
- for (i in attributes)
- element.setAttributeNS(null, i, attributes[i]);
-}
-
-/**
- * Handle mouse move event.
- */
-function handleMouseWheel(evt) {
- if(evt.preventDefault)
- evt.preventDefault();
-
- evt.returnValue = false;
-
- var svgDoc = evt.target.ownerDocument;
-
- var delta;
-
- if(evt.wheelDelta)
- delta = evt.wheelDelta / 3600; // Chrome/Safari
- else
- delta = evt.detail / -90; // Mozilla
-
- var z = 1 + delta; // Zoom factor: 0.9/1.1
-
- var g = svgDoc.getElementById("viewport");
-
- var p = getEventPoint(evt);
-
- p = p.matrixTransform(g.getCTM().inverse());
-
- // Compute new scale matrix in current mouse position
- var k = root.createSVGMatrix().translate(p.x, p.y).scale(z).translate(-p.x, -p.y);
-
- setCTM(g, g.getCTM().multiply(k));
-
- stateTf = stateTf.multiply(k.inverse());
-}
-
-/**
- * Handle mouse move event.
- */
-function handleMouseMove(evt) {
- if(evt.preventDefault)
- evt.preventDefault();
-
- evt.returnValue = false;
-
- var svgDoc = evt.target.ownerDocument;
-
- var g = svgDoc.getElementById("viewport");
-
- if(state == 'pan') {
- // Pan mode
- var p = getEventPoint(evt).matrixTransform(stateTf);
-
- setCTM(g, stateTf.inverse().translate(p.x - stateOrigin.x, p.y - stateOrigin.y));
- } else if(state == 'move') {
- // Move mode
- var p = getEventPoint(evt).matrixTransform(g.getCTM().inverse());
-
- setCTM(stateTarget, root.createSVGMatrix().translate(p.x - stateOrigin.x, p.y - stateOrigin.y).multiply(g.getCTM().inverse()).multiply(stateTarget.getCTM()));
-
- stateOrigin = p;
- }
-}
-
-/**
- * Handle click event.
- */
-function handleMouseDown(evt) {
- if(evt.preventDefault)
- evt.preventDefault();
-
- evt.returnValue = false;
-
- var svgDoc = evt.target.ownerDocument;
-
- var g = svgDoc.getElementById("viewport");
-
- if(true || evt.target.tagName == "svg") {
- // Pan mode
- state = 'pan';
-
- stateTf = g.getCTM().inverse();
-
- stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
- } else {
- // Move mode
- state = 'move';
-
- stateTarget = evt.target;
-
- stateTf = g.getCTM().inverse();
-
- stateOrigin = getEventPoint(evt).matrixTransform(stateTf);
- }
-}
-
-/**
- * Handle mouse button release event.
- */
-function handleMouseUp(evt) {
- if(evt.preventDefault)
- evt.preventDefault();
-
- evt.returnValue = false;
-
- var svgDoc = evt.target.ownerDocument;
-
- if(state == 'pan' || state == 'move') {
- // Quit pan mode
- state = '';
- }
-}
-
-]]></script>
-EOF
-}
-
-# Provides a map from fullname to shortname for cases where the
-# shortname is ambiguous. The symlist has both the fullname and
-# shortname for all symbols, which is usually fine, but sometimes --
-# such as overloaded functions -- two different fullnames can map to
-# the same shortname. In that case, we use the address of the
-# function to disambiguate the two. This function fills in a map that
-# maps fullnames to modified shortnames in such cases. If a fullname
-# is not present in the map, the 'normal' shortname provided by the
-# symlist is the appropriate one to use.
-sub FillFullnameToShortnameMap {
- my $symbols = shift;
- my $fullname_to_shortname_map = shift;
- my $shortnames_seen_once = {};
- my $shortnames_seen_more_than_once = {};
-
- foreach my $symlist (values(%{$symbols})) {
- # TODO(csilvers): deal with inlined symbols too.
- my $shortname = $symlist->[0];
- my $fullname = $symlist->[2];
- if ($fullname !~ /<[0-9a-fA-F]+>$/) { # fullname doesn't end in an address
- next; # the only collisions we care about are when addresses differ
- }
- if (defined($shortnames_seen_once->{$shortname}) &&
- $shortnames_seen_once->{$shortname} ne $fullname) {
- $shortnames_seen_more_than_once->{$shortname} = 1;
- } else {
- $shortnames_seen_once->{$shortname} = $fullname;
- }
- }
-
- foreach my $symlist (values(%{$symbols})) {
- my $shortname = $symlist->[0];
- my $fullname = $symlist->[2];
- # TODO(csilvers): take in a list of addresses we care about, and only
- # store in the map if $symlist->[1] is in that list. Saves space.
- next if defined($fullname_to_shortname_map->{$fullname});
- if (defined($shortnames_seen_more_than_once->{$shortname})) {
- if ($fullname =~ /<0*([^>]*)>$/) { # fullname has address at end of it
- $fullname_to_shortname_map->{$fullname} = "$shortname\@$1";
- }
- }
- }
-}
-
-# Return a small number that identifies the argument.
-# Multiple calls with the same argument will return the same number.
-# Calls with different arguments will return different numbers.
-sub ShortIdFor {
- my $key = shift;
- my $id = $main::uniqueid{$key};
- if (!defined($id)) {
- $id = keys(%main::uniqueid) + 1;
- $main::uniqueid{$key} = $id;
- }
- return $id;
-}
-
-# Translate a stack of addresses into a stack of symbols
-sub TranslateStack {
- my $symbols = shift;
- my $fullname_to_shortname_map = shift;
- my $k = shift;
-
- my @addrs = split(/\n/, $k);
- my @result = ();
- for (my $i = 0; $i <= $#addrs; $i++) {
- my $a = $addrs[$i];
-
- # Skip large addresses since they sometimes show up as fake entries on RH9
- if (length($a) > 8 && $a gt "7fffffffffffffff") {
- next;
- }
-
- if ($main::opt_disasm || $main::opt_list) {
- # We want just the address for the key
- push(@result, $a);
- next;
- }
-
- my $symlist = $symbols->{$a};
- if (!defined($symlist)) {
- $symlist = [$a, "", $a];
- }
-
- # We can have a sequence of symbols for a particular entry
- # (more than one symbol in the case of inlining). Callers
- # come before callees in symlist, so walk backwards since
- # the translated stack should contain callees before callers.
- for (my $j = $#{$symlist}; $j >= 2; $j -= 3) {
- my $func = $symlist->[$j-2];
- my $fileline = $symlist->[$j-1];
- my $fullfunc = $symlist->[$j];
- if (defined($fullname_to_shortname_map->{$fullfunc})) {
- $func = $fullname_to_shortname_map->{$fullfunc};
- }
- if ($j > 2) {
- $func = "$func (inline)";
- }
-
- # Do not merge nodes corresponding to Callback::Run since that
- # causes confusing cycles in dot display. Instead, we synthesize
- # a unique name for this frame per caller.
- if ($func =~ m/Callback.*::Run$/) {
- my $caller = ($i > 0) ? $addrs[$i-1] : 0;
- $func = "Run#" . ShortIdFor($caller);
- }
-
- if ($main::opt_addresses) {
- push(@result, "$a $func $fileline");
- } elsif ($main::opt_lines) {
- if ($func eq '??' && $fileline eq '??:0') {
- push(@result, "$a");
- } else {
- push(@result, "$func $fileline");
- }
- } elsif ($main::opt_functions) {
- if ($func eq '??') {
- push(@result, "$a");
- } else {
- push(@result, $func);
- }
- } elsif ($main::opt_files) {
- if ($fileline eq '??:0' || $fileline eq '') {
- push(@result, "$a");
- } else {
- my $f = $fileline;
- $f =~ s/:\d+$//;
- push(@result, $f);
- }
- } else {
- push(@result, $a);
- last; # Do not print inlined info
- }
- }
- }
-
- # print join(",", @addrs), " => ", join(",", @result), "\n";
- return @result;
-}
-
-# Generate percent string for a number and a total
-sub Percent {
- my $num = shift;
- my $tot = shift;
- if ($tot != 0) {
- return sprintf("%.1f%%", $num * 100.0 / $tot);
- } else {
- return ($num == 0) ? "nan" : (($num > 0) ? "+inf" : "-inf");
- }
-}
-
-# Generate pretty-printed form of number
-sub Unparse {
- my $num = shift;
- if ($main::profile_type eq 'heap' || $main::profile_type eq 'growth') {
- if ($main::opt_inuse_objects || $main::opt_alloc_objects) {
- return sprintf("%d", $num);
- } else {
- if ($main::opt_show_bytes) {
- return sprintf("%d", $num);
- } else {
- return sprintf("%.1f", $num / 1048576.0);
- }
- }
- } elsif ($main::profile_type eq 'contention' && !$main::opt_contentions) {
- return sprintf("%.3f", $num / 1e9); # Convert nanoseconds to seconds
- } else {
- return sprintf("%d", $num);
- }
-}
-
-# Alternate pretty-printed form: 0 maps to "."
-sub UnparseAlt {
- my $num = shift;
- if ($num == 0) {
- return ".";
- } else {
- return Unparse($num);
- }
-}
-
-# Alternate pretty-printed form: 0 maps to ""
-sub HtmlPrintNumber {
- my $num = shift;
- if ($num == 0) {
- return "";
- } else {
- return Unparse($num);
- }
-}
-
-# Return output units
-sub Units {
- if ($main::profile_type eq 'heap' || $main::profile_type eq 'growth') {
- if ($main::opt_inuse_objects || $main::opt_alloc_objects) {
- return "objects";
- } else {
- if ($main::opt_show_bytes) {
- return "B";
- } else {
- return "MB";
- }
- }
- } elsif ($main::profile_type eq 'contention' && !$main::opt_contentions) {
- return "seconds";
- } else {
- return "samples";
- }
-}
-
-##### Profile manipulation code #####
-
-# Generate flattened profile:
-# If count is charged to stack [a,b,c,d], in generated profile,
-# it will be charged to [a]
-sub FlatProfile {
- my $profile = shift;
- my $result = {};
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @addrs = split(/\n/, $k);
- if ($#addrs >= 0) {
- AddEntry($result, $addrs[0], $count);
- }
- }
- return $result;
-}
-
-# Generate cumulative profile:
-# If count is charged to stack [a,b,c,d], in generated profile,
-# it will be charged to [a], [b], [c], [d]
-sub CumulativeProfile {
- my $profile = shift;
- my $result = {};
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @addrs = split(/\n/, $k);
- foreach my $a (@addrs) {
- AddEntry($result, $a, $count);
- }
- }
- return $result;
-}
-
-# If the second-youngest PC on the stack is always the same, returns
-# that pc. Otherwise, returns undef.
-sub IsSecondPcAlwaysTheSame {
- my $profile = shift;
-
- my $second_pc = undef;
- foreach my $k (keys(%{$profile})) {
- my @addrs = split(/\n/, $k);
- if ($#addrs < 1) {
- return undef;
- }
- if (not defined $second_pc) {
- $second_pc = $addrs[1];
- } else {
- if ($second_pc ne $addrs[1]) {
- return undef;
- }
- }
- }
- return $second_pc;
-}
-
-sub ExtractSymbolLocation {
- my $symbols = shift;
- my $address = shift;
- # 'addr2line' outputs "??:0" for unknown locations; we do the
- # same to be consistent.
- my $location = "??:0:unknown";
- if (exists $symbols->{$address}) {
- my $file = $symbols->{$address}->[1];
- if ($file eq "?") {
- $file = "??:0"
- }
- $location = $file . ":" . $symbols->{$address}->[0];
- }
- return $location;
-}
-
-# Extracts a graph of calls.
-sub ExtractCalls {
- my $symbols = shift;
- my $profile = shift;
-
- my $calls = {};
- while( my ($stack_trace, $count) = each %$profile ) {
- my @address = split(/\n/, $stack_trace);
- my $destination = ExtractSymbolLocation($symbols, $address[0]);
- AddEntry($calls, $destination, $count);
- for (my $i = 1; $i <= $#address; $i++) {
- my $source = ExtractSymbolLocation($symbols, $address[$i]);
- my $call = "$source -> $destination";
- AddEntry($calls, $call, $count);
- $destination = $source;
- }
- }
-
- return $calls;
-}
-
-sub FilterFrames {
- my $symbols = shift;
- my $profile = shift;
-
- if ($main::opt_retain eq '' && $main::opt_exclude eq '') {
- return $profile;
- }
-
- my $result = {};
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @addrs = split(/\n/, $k);
- my @path = ();
- foreach my $a (@addrs) {
- my $sym;
- if (exists($symbols->{$a})) {
- $sym = $symbols->{$a}->[0];
- } else {
- $sym = $a;
- }
- if ($main::opt_retain ne '' && $sym !~ m/$main::opt_retain/) {
- next;
- }
- if ($main::opt_exclude ne '' && $sym =~ m/$main::opt_exclude/) {
- next;
- }
- push(@path, $a);
- }
- if (scalar(@path) > 0) {
- my $reduced_path = join("\n", @path);
- AddEntry($result, $reduced_path, $count);
- }
- }
-
- return $result;
-}
-
-sub RemoveUninterestingFrames {
- my $symbols = shift;
- my $profile = shift;
-
- # List of function names to skip
- my %skip = ();
- my $skip_regexp = 'NOMATCH';
- if ($main::profile_type eq 'heap' || $main::profile_type eq 'growth') {
- foreach my $name ('calloc',
- 'cfree',
- 'malloc',
- 'free',
- 'memalign',
- 'posix_memalign',
- 'aligned_alloc',
- 'pvalloc',
- 'valloc',
- 'realloc',
- 'mallocx', # jemalloc
- 'rallocx', # jemalloc
- 'xallocx', # jemalloc
- 'dallocx', # jemalloc
- 'sdallocx', # jemalloc
- 'tc_calloc',
- 'tc_cfree',
- 'tc_malloc',
- 'tc_free',
- 'tc_memalign',
- 'tc_posix_memalign',
- 'tc_pvalloc',
- 'tc_valloc',
- 'tc_realloc',
- 'tc_new',
- 'tc_delete',
- 'tc_newarray',
- 'tc_deletearray',
- 'tc_new_nothrow',
- 'tc_newarray_nothrow',
- 'do_malloc',
- '::do_malloc', # new name -- got moved to an unnamed ns
- '::do_malloc_or_cpp_alloc',
- 'DoSampledAllocation',
- 'simple_alloc::allocate',
- '__malloc_alloc_template::allocate',
- '__builtin_delete',
- '__builtin_new',
- '__builtin_vec_delete',
- '__builtin_vec_new',
- 'operator new',
- 'operator new[]',
- # The entry to our memory-allocation routines on OS X
- 'malloc_zone_malloc',
- 'malloc_zone_calloc',
- 'malloc_zone_valloc',
- 'malloc_zone_realloc',
- 'malloc_zone_memalign',
- 'malloc_zone_free',
- # These mark the beginning/end of our custom sections
- '__start_google_malloc',
- '__stop_google_malloc',
- '__start_malloc_hook',
- '__stop_malloc_hook') {
- $skip{$name} = 1;
- $skip{"_" . $name} = 1; # Mach (OS X) adds a _ prefix to everything
- }
- # TODO: Remove TCMalloc once everything has been
- # moved into the tcmalloc:: namespace and we have flushed
- # old code out of the system.
- $skip_regexp = "TCMalloc|^tcmalloc::";
- } elsif ($main::profile_type eq 'contention') {
- foreach my $vname ('base::RecordLockProfileData',
- 'base::SubmitMutexProfileData',
- 'base::SubmitSpinLockProfileData',
- 'Mutex::Unlock',
- 'Mutex::UnlockSlow',
- 'Mutex::ReaderUnlock',
- 'MutexLock::~MutexLock',
- 'SpinLock::Unlock',
- 'SpinLock::SlowUnlock',
- 'SpinLockHolder::~SpinLockHolder') {
- $skip{$vname} = 1;
- }
- } elsif ($main::profile_type eq 'cpu') {
- # Drop signal handlers used for CPU profile collection
- # TODO(dpeng): this should not be necessary; it's taken
- # care of by the general 2nd-pc mechanism below.
- foreach my $name ('ProfileData::Add', # historical
- 'ProfileData::prof_handler', # historical
- 'CpuProfiler::prof_handler',
- '__FRAME_END__',
- '__pthread_sighandler',
- '__restore') {
- $skip{$name} = 1;
- }
- } else {
- # Nothing skipped for unknown types
- }
-
- if ($main::profile_type eq 'cpu') {
- # If all the second-youngest program counters are the same,
- # this STRONGLY suggests that it is an artifact of measurement,
- # i.e., stack frames pushed by the CPU profiler signal handler.
- # Hence, we delete them.
- # (The topmost PC is read from the signal structure, not from
- # the stack, so it does not get involved.)
- while (my $second_pc = IsSecondPcAlwaysTheSame($profile)) {
- my $result = {};
- my $func = '';
- if (exists($symbols->{$second_pc})) {
- $second_pc = $symbols->{$second_pc}->[0];
- }
- print STDERR "Removing $second_pc from all stack traces.\n";
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @addrs = split(/\n/, $k);
- splice @addrs, 1, 1;
- my $reduced_path = join("\n", @addrs);
- AddEntry($result, $reduced_path, $count);
- }
- $profile = $result;
- }
- }
-
- my $result = {};
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @addrs = split(/\n/, $k);
- my @path = ();
- foreach my $a (@addrs) {
- if (exists($symbols->{$a})) {
- my $func = $symbols->{$a}->[0];
- if ($skip{$func} || ($func =~ m/$skip_regexp/)) {
- # Throw away the portion of the backtrace seen so far, under the
- # assumption that previous frames were for functions internal to the
- # allocator.
- @path = ();
- next;
- }
- }
- push(@path, $a);
- }
- my $reduced_path = join("\n", @path);
- AddEntry($result, $reduced_path, $count);
- }
-
- $result = FilterFrames($symbols, $result);
-
- return $result;
-}
-
-# Reduce profile to granularity given by user
-sub ReduceProfile {
- my $symbols = shift;
- my $profile = shift;
- my $result = {};
- my $fullname_to_shortname_map = {};
- FillFullnameToShortnameMap($symbols, $fullname_to_shortname_map);
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @translated = TranslateStack($symbols, $fullname_to_shortname_map, $k);
- my @path = ();
- my %seen = ();
- $seen{''} = 1; # So that empty keys are skipped
- foreach my $e (@translated) {
- # To avoid double-counting due to recursion, skip a stack-trace
- # entry if it has already been seen
- if (!$seen{$e}) {
- $seen{$e} = 1;
- push(@path, $e);
- }
- }
- my $reduced_path = join("\n", @path);
- AddEntry($result, $reduced_path, $count);
- }
- return $result;
-}
-
-# Does the specified symbol array match the regexp?
-sub SymbolMatches {
- my $sym = shift;
- my $re = shift;
- if (defined($sym)) {
- for (my $i = 0; $i < $#{$sym}; $i += 3) {
- if ($sym->[$i] =~ m/$re/ || $sym->[$i+1] =~ m/$re/) {
- return 1;
- }
- }
- }
- return 0;
-}
-
-# Focus only on paths involving specified regexps
-sub FocusProfile {
- my $symbols = shift;
- my $profile = shift;
- my $focus = shift;
- my $result = {};
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @addrs = split(/\n/, $k);
- foreach my $a (@addrs) {
- # Reply if it matches either the address/shortname/fileline
- if (($a =~ m/$focus/) || SymbolMatches($symbols->{$a}, $focus)) {
- AddEntry($result, $k, $count);
- last;
- }
- }
- }
- return $result;
-}
-
-# Focus only on paths not involving specified regexps
-sub IgnoreProfile {
- my $symbols = shift;
- my $profile = shift;
- my $ignore = shift;
- my $result = {};
- foreach my $k (keys(%{$profile})) {
- my $count = $profile->{$k};
- my @addrs = split(/\n/, $k);
- my $matched = 0;
- foreach my $a (@addrs) {
- # Reply if it matches either the address/shortname/fileline
- if (($a =~ m/$ignore/) || SymbolMatches($symbols->{$a}, $ignore)) {
- $matched = 1;
- last;
- }
- }
- if (!$matched) {
- AddEntry($result, $k, $count);
- }
- }
- return $result;
-}
-
-# Get total count in profile
-sub TotalProfile {
- my $profile = shift;
- my $result = 0;
- foreach my $k (keys(%{$profile})) {
- $result += $profile->{$k};
- }
- return $result;
-}
-
-# Add A to B
-sub AddProfile {
- my $A = shift;
- my $B = shift;
-
- my $R = {};
- # add all keys in A
- foreach my $k (keys(%{$A})) {
- my $v = $A->{$k};
- AddEntry($R, $k, $v);
- }
- # add all keys in B
- foreach my $k (keys(%{$B})) {
- my $v = $B->{$k};
- AddEntry($R, $k, $v);
- }
- return $R;
-}
-
-# Merges symbol maps
-sub MergeSymbols {
- my $A = shift;
- my $B = shift;
-
- my $R = {};
- foreach my $k (keys(%{$A})) {
- $R->{$k} = $A->{$k};
- }
- if (defined($B)) {
- foreach my $k (keys(%{$B})) {
- $R->{$k} = $B->{$k};
- }
- }
- return $R;
-}
-
-
-# Add A to B
-sub AddPcs {
- my $A = shift;
- my $B = shift;
-
- my $R = {};
- # add all keys in A
- foreach my $k (keys(%{$A})) {
- $R->{$k} = 1
- }
- # add all keys in B
- foreach my $k (keys(%{$B})) {
- $R->{$k} = 1
- }
- return $R;
-}
-
-# Subtract B from A
-sub SubtractProfile {
- my $A = shift;
- my $B = shift;
-
- my $R = {};
- foreach my $k (keys(%{$A})) {
- my $v = $A->{$k} - GetEntry($B, $k);
- if ($v < 0 && $main::opt_drop_negative) {
- $v = 0;
- }
- AddEntry($R, $k, $v);
- }
- if (!$main::opt_drop_negative) {
- # Take care of when subtracted profile has more entries
- foreach my $k (keys(%{$B})) {
- if (!exists($A->{$k})) {
- AddEntry($R, $k, 0 - $B->{$k});
- }
- }
- }
- return $R;
-}
-
-# Get entry from profile; zero if not present
-sub GetEntry {
- my $profile = shift;
- my $k = shift;
- if (exists($profile->{$k})) {
- return $profile->{$k};
- } else {
- return 0;
- }
-}
-
-# Add entry to specified profile
-sub AddEntry {
- my $profile = shift;
- my $k = shift;
- my $n = shift;
- if (!exists($profile->{$k})) {
- $profile->{$k} = 0;
- }
- $profile->{$k} += $n;
-}
-
-# Add a stack of entries to specified profile, and add them to the $pcs
-# list.
-sub AddEntries {
- my $profile = shift;
- my $pcs = shift;
- my $stack = shift;
- my $count = shift;
- my @k = ();
-
- foreach my $e (split(/\s+/, $stack)) {
- my $pc = HexExtend($e);
- $pcs->{$pc} = 1;
- push @k, $pc;
- }
- AddEntry($profile, (join "\n", @k), $count);
-}
-
-##### Code to profile a server dynamically #####
-
-sub CheckSymbolPage {
- my $url = SymbolPageURL();
- my $command = ShellEscape(@URL_FETCHER, $url);
- open(SYMBOL, "$command |") or error($command);
- my $line = <SYMBOL>;
- $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
- close(SYMBOL);
- unless (defined($line)) {
- error("$url doesn't exist\n");
- }
-
- if ($line =~ /^num_symbols:\s+(\d+)$/) {
- if ($1 == 0) {
- error("Stripped binary. No symbols available.\n");
- }
- } else {
- error("Failed to get the number of symbols from $url\n");
- }
-}
-
-sub IsProfileURL {
- my $profile_name = shift;
- if (-f $profile_name) {
- printf STDERR "Using local file $profile_name.\n";
- return 0;
- }
- return 1;
-}
-
-sub ParseProfileURL {
- my $profile_name = shift;
-
- if (!defined($profile_name) || $profile_name eq "") {
- return ();
- }
-
- # Split profile URL - matches all non-empty strings, so no test.
- $profile_name =~ m,^(https?://)?([^/]+)(.*?)(/|$PROFILES)?$,;
-
- my $proto = $1 || "http://";
- my $hostport = $2;
- my $prefix = $3;
- my $profile = $4 || "/";
-
- my $host = $hostport;
- $host =~ s/:.*//;
-
- my $baseurl = "$proto$hostport$prefix";
- return ($host, $baseurl, $profile);
-}
-
-# We fetch symbols from the first profile argument.
-sub SymbolPageURL {
- my ($host, $baseURL, $path) = ParseProfileURL($main::pfile_args[0]);
- return "$baseURL$SYMBOL_PAGE";
-}
-
-sub FetchProgramName() {
- my ($host, $baseURL, $path) = ParseProfileURL($main::pfile_args[0]);
- my $url = "$baseURL$PROGRAM_NAME_PAGE";
- my $command_line = ShellEscape(@URL_FETCHER, $url);
- open(CMDLINE, "$command_line |") or error($command_line);
- my $cmdline = <CMDLINE>;
- $cmdline =~ s/\r//g; # turn windows-looking lines into unix-looking lines
- close(CMDLINE);
- error("Failed to get program name from $url\n") unless defined($cmdline);
- $cmdline =~ s/\x00.+//; # Remove argv[1] and latters.
- $cmdline =~ s!\n!!g; # Remove LFs.
- return $cmdline;
-}
-
-# Gee, curl's -L (--location) option isn't reliable at least
-# with its 7.12.3 version. Curl will forget to post data if
-# there is a redirection. This function is a workaround for
-# curl. Redirection happens on borg hosts.
-sub ResolveRedirectionForCurl {
- my $url = shift;
- my $command_line = ShellEscape(@URL_FETCHER, "--head", $url);
- open(CMDLINE, "$command_line |") or error($command_line);
- while (<CMDLINE>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- if (/^Location: (.*)/) {
- $url = $1;
- }
- }
- close(CMDLINE);
- return $url;
-}
-
-# Add a timeout flat to URL_FETCHER. Returns a new list.
-sub AddFetchTimeout {
- my $timeout = shift;
- my @fetcher = @_;
- if (defined($timeout)) {
- if (join(" ", @fetcher) =~ m/\bcurl -s/) {
- push(@fetcher, "--max-time", sprintf("%d", $timeout));
- } elsif (join(" ", @fetcher) =~ m/\brpcget\b/) {
- push(@fetcher, sprintf("--deadline=%d", $timeout));
- }
- }
- return @fetcher;
-}
-
-# Reads a symbol map from the file handle name given as $1, returning
-# the resulting symbol map. Also processes variables relating to symbols.
-# Currently, the only variable processed is 'binary=<value>' which updates
-# $main::prog to have the correct program name.
-sub ReadSymbols {
- my $in = shift;
- my $map = {};
- while (<$in>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- # Removes all the leading zeroes from the symbols, see comment below.
- if (m/^0x0*([0-9a-f]+)\s+(.+)/) {
- $map->{$1} = $2;
- } elsif (m/^---/) {
- last;
- } elsif (m/^([a-z][^=]*)=(.*)$/ ) {
- my ($variable, $value) = ($1, $2);
- for ($variable, $value) {
- s/^\s+//;
- s/\s+$//;
- }
- if ($variable eq "binary") {
- if ($main::prog ne $UNKNOWN_BINARY && $main::prog ne $value) {
- printf STDERR ("Warning: Mismatched binary name '%s', using '%s'.\n",
- $main::prog, $value);
- }
- $main::prog = $value;
- } else {
- printf STDERR ("Ignoring unknown variable in symbols list: " .
- "'%s' = '%s'\n", $variable, $value);
- }
- }
- }
- return $map;
-}
-
-sub URLEncode {
- my $str = shift;
- $str =~ s/([^A-Za-z0-9\-_.!~*'()])/ sprintf "%%%02x", ord $1 /eg;
- return $str;
-}
-
-sub AppendSymbolFilterParams {
- my $url = shift;
- my @params = ();
- if ($main::opt_retain ne '') {
- push(@params, sprintf("retain=%s", URLEncode($main::opt_retain)));
- }
- if ($main::opt_exclude ne '') {
- push(@params, sprintf("exclude=%s", URLEncode($main::opt_exclude)));
- }
- if (scalar @params > 0) {
- $url = sprintf("%s?%s", $url, join("&", @params));
- }
- return $url;
-}
-
-# Fetches and processes symbols to prepare them for use in the profile output
-# code. If the optional 'symbol_map' arg is not given, fetches symbols from
-# $SYMBOL_PAGE for all PC values found in profile. Otherwise, the raw symbols
-# are assumed to have already been fetched into 'symbol_map' and are simply
-# extracted and processed.
-sub FetchSymbols {
- my $pcset = shift;
- my $symbol_map = shift;
-
- my %seen = ();
- my @pcs = grep { !$seen{$_}++ } keys(%$pcset); # uniq
-
- if (!defined($symbol_map)) {
- my $post_data = join("+", sort((map {"0x" . "$_"} @pcs)));
-
- open(POSTFILE, ">$main::tmpfile_sym");
- print POSTFILE $post_data;
- close(POSTFILE);
-
- my $url = SymbolPageURL();
-
- my $command_line;
- if (join(" ", @URL_FETCHER) =~ m/\bcurl -s/) {
- $url = ResolveRedirectionForCurl($url);
- $url = AppendSymbolFilterParams($url);
- $command_line = ShellEscape(@URL_FETCHER, "-d", "\@$main::tmpfile_sym",
- $url);
- } else {
- $url = AppendSymbolFilterParams($url);
- $command_line = (ShellEscape(@URL_FETCHER, "--post", $url)
- . " < " . ShellEscape($main::tmpfile_sym));
- }
- # We use c++filt in case $SYMBOL_PAGE gives us mangled symbols.
- my $escaped_cppfilt = ShellEscape($obj_tool_map{"c++filt"});
- open(SYMBOL, "$command_line | $escaped_cppfilt |") or error($command_line);
- $symbol_map = ReadSymbols(*SYMBOL{IO});
- close(SYMBOL);
- }
-
- my $symbols = {};
- foreach my $pc (@pcs) {
- my $fullname;
- # For 64 bits binaries, symbols are extracted with 8 leading zeroes.
- # Then /symbol reads the long symbols in as uint64, and outputs
- # the result with a "0x%08llx" format which get rid of the zeroes.
- # By removing all the leading zeroes in both $pc and the symbols from
- # /symbol, the symbols match and are retrievable from the map.
- my $shortpc = $pc;
- $shortpc =~ s/^0*//;
- # Each line may have a list of names, which includes the function
- # and also other functions it has inlined. They are separated (in
- # PrintSymbolizedProfile), by --, which is illegal in function names.
- my $fullnames;
- if (defined($symbol_map->{$shortpc})) {
- $fullnames = $symbol_map->{$shortpc};
- } else {
- $fullnames = "0x" . $pc; # Just use addresses
- }
- my $sym = [];
- $symbols->{$pc} = $sym;
- foreach my $fullname (split("--", $fullnames)) {
- my $name = ShortFunctionName($fullname);
- push(@{$sym}, $name, "?", $fullname);
- }
- }
- return $symbols;
-}
-
-sub BaseName {
- my $file_name = shift;
- $file_name =~ s!^.*/!!; # Remove directory name
- return $file_name;
-}
-
-sub MakeProfileBaseName {
- my ($binary_name, $profile_name) = @_;
- my ($host, $baseURL, $path) = ParseProfileURL($profile_name);
- my $binary_shortname = BaseName($binary_name);
- return sprintf("%s.%s.%s",
- $binary_shortname, $main::op_time, $host);
-}
-
-sub FetchDynamicProfile {
- my $binary_name = shift;
- my $profile_name = shift;
- my $fetch_name_only = shift;
- my $encourage_patience = shift;
-
- if (!IsProfileURL($profile_name)) {
- return $profile_name;
- } else {
- my ($host, $baseURL, $path) = ParseProfileURL($profile_name);
- if ($path eq "" || $path eq "/") {
- # Missing type specifier defaults to cpu-profile
- $path = $PROFILE_PAGE;
- }
-
- my $profile_file = MakeProfileBaseName($binary_name, $profile_name);
-
- my $url = "$baseURL$path";
- my $fetch_timeout = undef;
- if ($path =~ m/$PROFILE_PAGE|$PMUPROFILE_PAGE/) {
- if ($path =~ m/[?]/) {
- $url .= "&";
- } else {
- $url .= "?";
- }
- $url .= sprintf("seconds=%d", $main::opt_seconds);
- $fetch_timeout = $main::opt_seconds * 1.01 + 60;
- # Set $profile_type for consumption by PrintSymbolizedProfile.
- $main::profile_type = 'cpu';
- } else {
- # For non-CPU profiles, we add a type-extension to
- # the target profile file name.
- my $suffix = $path;
- $suffix =~ s,/,.,g;
- $profile_file .= $suffix;
- # Set $profile_type for consumption by PrintSymbolizedProfile.
- if ($path =~ m/$HEAP_PAGE/) {
- $main::profile_type = 'heap';
- } elsif ($path =~ m/$GROWTH_PAGE/) {
- $main::profile_type = 'growth';
- } elsif ($path =~ m/$CONTENTION_PAGE/) {
- $main::profile_type = 'contention';
- }
- }
-
- my $profile_dir = $ENV{"JEPROF_TMPDIR"} || ($ENV{HOME} . "/jeprof");
- if (! -d $profile_dir) {
- mkdir($profile_dir)
- || die("Unable to create profile directory $profile_dir: $!\n");
- }
- my $tmp_profile = "$profile_dir/.tmp.$profile_file";
- my $real_profile = "$profile_dir/$profile_file";
-
- if ($fetch_name_only > 0) {
- return $real_profile;
- }
-
- my @fetcher = AddFetchTimeout($fetch_timeout, @URL_FETCHER);
- my $cmd = ShellEscape(@fetcher, $url) . " > " . ShellEscape($tmp_profile);
- if ($path =~ m/$PROFILE_PAGE|$PMUPROFILE_PAGE|$CENSUSPROFILE_PAGE/){
- print STDERR "Gathering CPU profile from $url for $main::opt_seconds seconds to\n ${real_profile}\n";
- if ($encourage_patience) {
- print STDERR "Be patient...\n";
- }
- } else {
- print STDERR "Fetching $path profile from $url to\n ${real_profile}\n";
- }
-
- (system($cmd) == 0) || error("Failed to get profile: $cmd: $!\n");
- (system("mv", $tmp_profile, $real_profile) == 0) || error("Unable to rename profile\n");
- print STDERR "Wrote profile to $real_profile\n";
- $main::collected_profile = $real_profile;
- return $main::collected_profile;
- }
-}
-
-# Collect profiles in parallel
-sub FetchDynamicProfiles {
- my $items = scalar(@main::pfile_args);
- my $levels = log($items) / log(2);
-
- if ($items == 1) {
- $main::profile_files[0] = FetchDynamicProfile($main::prog, $main::pfile_args[0], 0, 1);
- } else {
- # math rounding issues
- if ((2 ** $levels) < $items) {
- $levels++;
- }
- my $count = scalar(@main::pfile_args);
- for (my $i = 0; $i < $count; $i++) {
- $main::profile_files[$i] = FetchDynamicProfile($main::prog, $main::pfile_args[$i], 1, 0);
- }
- print STDERR "Fetching $count profiles, Be patient...\n";
- FetchDynamicProfilesRecurse($levels, 0, 0);
- $main::collected_profile = join(" \\\n ", @main::profile_files);
- }
-}
-
-# Recursively fork a process to get enough processes
-# collecting profiles
-sub FetchDynamicProfilesRecurse {
- my $maxlevel = shift;
- my $level = shift;
- my $position = shift;
-
- if (my $pid = fork()) {
- $position = 0 | ($position << 1);
- TryCollectProfile($maxlevel, $level, $position);
- wait;
- } else {
- $position = 1 | ($position << 1);
- TryCollectProfile($maxlevel, $level, $position);
- cleanup();
- exit(0);
- }
-}
-
-# Collect a single profile
-sub TryCollectProfile {
- my $maxlevel = shift;
- my $level = shift;
- my $position = shift;
-
- if ($level >= ($maxlevel - 1)) {
- if ($position < scalar(@main::pfile_args)) {
- FetchDynamicProfile($main::prog, $main::pfile_args[$position], 0, 0);
- }
- } else {
- FetchDynamicProfilesRecurse($maxlevel, $level+1, $position);
- }
-}
-
-##### Parsing code #####
-
-# Provide a small streaming-read module to handle very large
-# cpu-profile files. Stream in chunks along a sliding window.
-# Provides an interface to get one 'slot', correctly handling
-# endian-ness differences. A slot is one 32-bit or 64-bit word
-# (depending on the input profile). We tell endianness and bit-size
-# for the profile by looking at the first 8 bytes: in cpu profiles,
-# the second slot is always 3 (we'll accept anything that's not 0).
-BEGIN {
- package CpuProfileStream;
-
- sub new {
- my ($class, $file, $fname) = @_;
- my $self = { file => $file,
- base => 0,
- stride => 512 * 1024, # must be a multiple of bitsize/8
- slots => [],
- unpack_code => "", # N for big-endian, V for little
- perl_is_64bit => 1, # matters if profile is 64-bit
- };
- bless $self, $class;
- # Let unittests adjust the stride
- if ($main::opt_test_stride > 0) {
- $self->{stride} = $main::opt_test_stride;
- }
- # Read the first two slots to figure out bitsize and endianness.
- my $slots = $self->{slots};
- my $str;
- read($self->{file}, $str, 8);
- # Set the global $address_length based on what we see here.
- # 8 is 32-bit (8 hexadecimal chars); 16 is 64-bit (16 hexadecimal chars).
- $address_length = ($str eq (chr(0)x8)) ? 16 : 8;
- if ($address_length == 8) {
- if (substr($str, 6, 2) eq chr(0)x2) {
- $self->{unpack_code} = 'V'; # Little-endian.
- } elsif (substr($str, 4, 2) eq chr(0)x2) {
- $self->{unpack_code} = 'N'; # Big-endian
- } else {
- ::error("$fname: header size >= 2**16\n");
- }
- @$slots = unpack($self->{unpack_code} . "*", $str);
- } else {
- # If we're a 64-bit profile, check if we're a 64-bit-capable
- # perl. Otherwise, each slot will be represented as a float
- # instead of an int64, losing precision and making all the
- # 64-bit addresses wrong. We won't complain yet, but will
- # later if we ever see a value that doesn't fit in 32 bits.
- my $has_q = 0;
- eval { $has_q = pack("Q", "1") ? 1 : 1; };
- if (!$has_q) {
- $self->{perl_is_64bit} = 0;
- }
- read($self->{file}, $str, 8);
- if (substr($str, 4, 4) eq chr(0)x4) {
- # We'd love to use 'Q', but it's a) not universal, b) not endian-proof.
- $self->{unpack_code} = 'V'; # Little-endian.
- } elsif (substr($str, 0, 4) eq chr(0)x4) {
- $self->{unpack_code} = 'N'; # Big-endian
- } else {
- ::error("$fname: header size >= 2**32\n");
- }
- my @pair = unpack($self->{unpack_code} . "*", $str);
- # Since we know one of the pair is 0, it's fine to just add them.
- @$slots = (0, $pair[0] + $pair[1]);
- }
- return $self;
- }
-
- # Load more data when we access slots->get(X) which is not yet in memory.
- sub overflow {
- my ($self) = @_;
- my $slots = $self->{slots};
- $self->{base} += $#$slots + 1; # skip over data we're replacing
- my $str;
- read($self->{file}, $str, $self->{stride});
- if ($address_length == 8) { # the 32-bit case
- # This is the easy case: unpack provides 32-bit unpacking primitives.
- @$slots = unpack($self->{unpack_code} . "*", $str);
- } else {
- # We need to unpack 32 bits at a time and combine.
- my @b32_values = unpack($self->{unpack_code} . "*", $str);
- my @b64_values = ();
- for (my $i = 0; $i < $#b32_values; $i += 2) {
- # TODO(csilvers): if this is a 32-bit perl, the math below
- # could end up in a too-large int, which perl will promote
- # to a double, losing necessary precision. Deal with that.
- # Right now, we just die.
- my ($lo, $hi) = ($b32_values[$i], $b32_values[$i+1]);
- if ($self->{unpack_code} eq 'N') { # big-endian
- ($lo, $hi) = ($hi, $lo);
- }
- my $value = $lo + $hi * (2**32);
- if (!$self->{perl_is_64bit} && # check value is exactly represented
- (($value % (2**32)) != $lo || int($value / (2**32)) != $hi)) {
- ::error("Need a 64-bit perl to process this 64-bit profile.\n");
- }
- push(@b64_values, $value);
- }
- @$slots = @b64_values;
- }
- }
-
- # Access the i-th long in the file (logically), or -1 at EOF.
- sub get {
- my ($self, $idx) = @_;
- my $slots = $self->{slots};
- while ($#$slots >= 0) {
- if ($idx < $self->{base}) {
- # The only time we expect a reference to $slots[$i - something]
- # after referencing $slots[$i] is reading the very first header.
- # Since $stride > |header|, that shouldn't cause any lookback
- # errors. And everything after the header is sequential.
- print STDERR "Unexpected look-back reading CPU profile";
- return -1; # shrug, don't know what better to return
- } elsif ($idx > $self->{base} + $#$slots) {
- $self->overflow();
- } else {
- return $slots->[$idx - $self->{base}];
- }
- }
- # If we get here, $slots is [], which means we've reached EOF
- return -1; # unique since slots is supposed to hold unsigned numbers
- }
-}
-
-# Reads the top, 'header' section of a profile, and returns the last
-# line of the header, commonly called a 'header line'. The header
-# section of a profile consists of zero or more 'command' lines that
-# are instructions to jeprof, which jeprof executes when reading the
-# header. All 'command' lines start with a %. After the command
-# lines is the 'header line', which is a profile-specific line that
-# indicates what type of profile it is, and perhaps other global
-# information about the profile. For instance, here's a header line
-# for a heap profile:
-# heap profile: 53: 38236 [ 5525: 1284029] @ heapprofile
-# For historical reasons, the CPU profile does not contain a text-
-# readable header line. If the profile looks like a CPU profile,
-# this function returns "". If no header line could be found, this
-# function returns undef.
-#
-# The following commands are recognized:
-# %warn -- emit the rest of this line to stderr, prefixed by 'WARNING:'
-#
-# The input file should be in binmode.
-sub ReadProfileHeader {
- local *PROFILE = shift;
- my $firstchar = "";
- my $line = "";
- read(PROFILE, $firstchar, 1);
- seek(PROFILE, -1, 1); # unread the firstchar
- if ($firstchar !~ /[[:print:]]/) { # is not a text character
- return "";
- }
- while (defined($line = <PROFILE>)) {
- $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
- if ($line =~ /^%warn\s+(.*)/) { # 'warn' command
- # Note this matches both '%warn blah\n' and '%warn\n'.
- print STDERR "WARNING: $1\n"; # print the rest of the line
- } elsif ($line =~ /^%/) {
- print STDERR "Ignoring unknown command from profile header: $line";
- } else {
- # End of commands, must be the header line.
- return $line;
- }
- }
- return undef; # got to EOF without seeing a header line
-}
-
-sub IsSymbolizedProfileFile {
- my $file_name = shift;
- if (!(-e $file_name) || !(-r $file_name)) {
- return 0;
- }
- # Check if the file contains a symbol-section marker.
- open(TFILE, "<$file_name");
- binmode TFILE;
- my $firstline = ReadProfileHeader(*TFILE);
- close(TFILE);
- if (!$firstline) {
- return 0;
- }
- $SYMBOL_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- my $symbol_marker = $&;
- return $firstline =~ /^--- *$symbol_marker/;
-}
-
-# Parse profile generated by common/profiler.cc and return a reference
-# to a map:
-# $result->{version} Version number of profile file
-# $result->{period} Sampling period (in microseconds)
-# $result->{profile} Profile object
-# $result->{threads} Map of thread IDs to profile objects
-# $result->{map} Memory map info from profile
-# $result->{pcs} Hash of all PC values seen, key is hex address
-sub ReadProfile {
- my $prog = shift;
- my $fname = shift;
- my $result; # return value
-
- $CONTENTION_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- my $contention_marker = $&;
- $GROWTH_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- my $growth_marker = $&;
- $SYMBOL_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- my $symbol_marker = $&;
- $PROFILE_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- my $profile_marker = $&;
- $HEAP_PAGE =~ m,[^/]+$,; # matches everything after the last slash
- my $heap_marker = $&;
-
- # Look at first line to see if it is a heap or a CPU profile.
- # CPU profile may start with no header at all, and just binary data
- # (starting with \0\0\0\0) -- in that case, don't try to read the
- # whole firstline, since it may be gigabytes(!) of data.
- open(PROFILE, "<$fname") || error("$fname: $!\n");
- binmode PROFILE; # New perls do UTF-8 processing
- my $header = ReadProfileHeader(*PROFILE);
- if (!defined($header)) { # means "at EOF"
- error("Profile is empty.\n");
- }
-
- my $symbols;
- if ($header =~ m/^--- *$symbol_marker/o) {
- # Verify that the user asked for a symbolized profile
- if (!$main::use_symbolized_profile) {
- # we have both a binary and symbolized profiles, abort
- error("FATAL ERROR: Symbolized profile\n $fname\ncannot be used with " .
- "a binary arg. Try again without passing\n $prog\n");
- }
- # Read the symbol section of the symbolized profile file.
- $symbols = ReadSymbols(*PROFILE{IO});
- # Read the next line to get the header for the remaining profile.
- $header = ReadProfileHeader(*PROFILE) || "";
- }
-
- if ($header =~ m/^--- *($heap_marker|$growth_marker)/o) {
- # Skip "--- ..." line for profile types that have their own headers.
- $header = ReadProfileHeader(*PROFILE) || "";
- }
-
- $main::profile_type = '';
-
- if ($header =~ m/^heap profile:.*$growth_marker/o) {
- $main::profile_type = 'growth';
- $result = ReadHeapProfile($prog, *PROFILE, $header);
- } elsif ($header =~ m/^heap profile:/) {
- $main::profile_type = 'heap';
- $result = ReadHeapProfile($prog, *PROFILE, $header);
- } elsif ($header =~ m/^heap/) {
- $main::profile_type = 'heap';
- $result = ReadThreadedHeapProfile($prog, $fname, $header);
- } elsif ($header =~ m/^--- *$contention_marker/o) {
- $main::profile_type = 'contention';
- $result = ReadSynchProfile($prog, *PROFILE);
- } elsif ($header =~ m/^--- *Stacks:/) {
- print STDERR
- "Old format contention profile: mistakenly reports " .
- "condition variable signals as lock contentions.\n";
- $main::profile_type = 'contention';
- $result = ReadSynchProfile($prog, *PROFILE);
- } elsif ($header =~ m/^--- *$profile_marker/) {
- # the binary cpu profile data starts immediately after this line
- $main::profile_type = 'cpu';
- $result = ReadCPUProfile($prog, $fname, *PROFILE);
- } else {
- if (defined($symbols)) {
- # a symbolized profile contains a format we don't recognize, bail out
- error("$fname: Cannot recognize profile section after symbols.\n");
- }
- # no ascii header present -- must be a CPU profile
- $main::profile_type = 'cpu';
- $result = ReadCPUProfile($prog, $fname, *PROFILE);
- }
-
- close(PROFILE);
-
- # if we got symbols along with the profile, return those as well
- if (defined($symbols)) {
- $result->{symbols} = $symbols;
- }
-
- return $result;
-}
-
-# Subtract one from caller pc so we map back to call instr.
-# However, don't do this if we're reading a symbolized profile
-# file, in which case the subtract-one was done when the file
-# was written.
-#
-# We apply the same logic to all readers, though ReadCPUProfile uses an
-# independent implementation.
-sub FixCallerAddresses {
- my $stack = shift;
- # --raw/http: Always subtract one from pc's, because PrintSymbolizedProfile()
- # dumps unadjusted profiles.
- {
- $stack =~ /(\s)/;
- my $delimiter = $1;
- my @addrs = split(' ', $stack);
- my @fixedaddrs;
- $#fixedaddrs = $#addrs;
- if ($#addrs >= 0) {
- $fixedaddrs[0] = $addrs[0];
- }
- for (my $i = 1; $i <= $#addrs; $i++) {
- $fixedaddrs[$i] = AddressSub($addrs[$i], "0x1");
- }
- return join $delimiter, @fixedaddrs;
- }
-}
-
-# CPU profile reader
-sub ReadCPUProfile {
- my $prog = shift;
- my $fname = shift; # just used for logging
- local *PROFILE = shift;
- my $version;
- my $period;
- my $i;
- my $profile = {};
- my $pcs = {};
-
- # Parse string into array of slots.
- my $slots = CpuProfileStream->new(*PROFILE, $fname);
-
- # Read header. The current header version is a 5-element structure
- # containing:
- # 0: header count (always 0)
- # 1: header "words" (after this one: 3)
- # 2: format version (0)
- # 3: sampling period (usec)
- # 4: unused padding (always 0)
- if ($slots->get(0) != 0 ) {
- error("$fname: not a profile file, or old format profile file\n");
- }
- $i = 2 + $slots->get(1);
- $version = $slots->get(2);
- $period = $slots->get(3);
- # Do some sanity checking on these header values.
- if ($version > (2**32) || $period > (2**32) || $i > (2**32) || $i < 5) {
- error("$fname: not a profile file, or corrupted profile file\n");
- }
-
- # Parse profile
- while ($slots->get($i) != -1) {
- my $n = $slots->get($i++);
- my $d = $slots->get($i++);
- if ($d > (2**16)) { # TODO(csilvers): what's a reasonable max-stack-depth?
- my $addr = sprintf("0%o", $i * ($address_length == 8 ? 4 : 8));
- print STDERR "At index $i (address $addr):\n";
- error("$fname: stack trace depth >= 2**32\n");
- }
- if ($slots->get($i) == 0) {
- # End of profile data marker
- $i += $d;
- last;
- }
-
- # Make key out of the stack entries
- my @k = ();
- for (my $j = 0; $j < $d; $j++) {
- my $pc = $slots->get($i+$j);
- # Subtract one from caller pc so we map back to call instr.
- $pc--;
- $pc = sprintf("%0*x", $address_length, $pc);
- $pcs->{$pc} = 1;
- push @k, $pc;
- }
-
- AddEntry($profile, (join "\n", @k), $n);
- $i += $d;
- }
-
- # Parse map
- my $map = '';
- seek(PROFILE, $i * 4, 0);
- read(PROFILE, $map, (stat PROFILE)[7]);
-
- my $r = {};
- $r->{version} = $version;
- $r->{period} = $period;
- $r->{profile} = $profile;
- $r->{libs} = ParseLibraries($prog, $map, $pcs);
- $r->{pcs} = $pcs;
-
- return $r;
-}
-
-sub HeapProfileIndex {
- my $index = 1;
- if ($main::opt_inuse_space) {
- $index = 1;
- } elsif ($main::opt_inuse_objects) {
- $index = 0;
- } elsif ($main::opt_alloc_space) {
- $index = 3;
- } elsif ($main::opt_alloc_objects) {
- $index = 2;
- }
- return $index;
-}
-
-sub ReadMappedLibraries {
- my $fh = shift;
- my $map = "";
- # Read the /proc/self/maps data
- while (<$fh>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- $map .= $_;
- }
- return $map;
-}
-
-sub ReadMemoryMap {
- my $fh = shift;
- my $map = "";
- # Read /proc/self/maps data as formatted by DumpAddressMap()
- my $buildvar = "";
- while (<PROFILE>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- # Parse "build=<dir>" specification if supplied
- if (m/^\s*build=(.*)\n/) {
- $buildvar = $1;
- }
-
- # Expand "$build" variable if available
- $_ =~ s/\$build\b/$buildvar/g;
-
- $map .= $_;
- }
- return $map;
-}
-
-sub AdjustSamples {
- my ($sample_adjustment, $sampling_algorithm, $n1, $s1, $n2, $s2) = @_;
- if ($sample_adjustment) {
- if ($sampling_algorithm == 2) {
- # Remote-heap version 2
- # The sampling frequency is the rate of a Poisson process.
- # This means that the probability of sampling an allocation of
- # size X with sampling rate Y is 1 - exp(-X/Y)
- if ($n1 != 0) {
- my $ratio = (($s1*1.0)/$n1)/($sample_adjustment);
- my $scale_factor = 1/(1 - exp(-$ratio));
- $n1 *= $scale_factor;
- $s1 *= $scale_factor;
- }
- if ($n2 != 0) {
- my $ratio = (($s2*1.0)/$n2)/($sample_adjustment);
- my $scale_factor = 1/(1 - exp(-$ratio));
- $n2 *= $scale_factor;
- $s2 *= $scale_factor;
- }
- } else {
- # Remote-heap version 1
- my $ratio;
- $ratio = (($s1*1.0)/$n1)/($sample_adjustment);
- if ($ratio < 1) {
- $n1 /= $ratio;
- $s1 /= $ratio;
- }
- $ratio = (($s2*1.0)/$n2)/($sample_adjustment);
- if ($ratio < 1) {
- $n2 /= $ratio;
- $s2 /= $ratio;
- }
- }
- }
- return ($n1, $s1, $n2, $s2);
-}
-
-sub ReadHeapProfile {
- my $prog = shift;
- local *PROFILE = shift;
- my $header = shift;
-
- my $index = HeapProfileIndex();
-
- # Find the type of this profile. The header line looks like:
- # heap profile: 1246: 8800744 [ 1246: 8800744] @ <heap-url>/266053
- # There are two pairs <count: size>, the first inuse objects/space, and the
- # second allocated objects/space. This is followed optionally by a profile
- # type, and if that is present, optionally by a sampling frequency.
- # For remote heap profiles (v1):
- # The interpretation of the sampling frequency is that the profiler, for
- # each sample, calculates a uniformly distributed random integer less than
- # the given value, and records the next sample after that many bytes have
- # been allocated. Therefore, the expected sample interval is half of the
- # given frequency. By default, if not specified, the expected sample
- # interval is 128KB. Only remote-heap-page profiles are adjusted for
- # sample size.
- # For remote heap profiles (v2):
- # The sampling frequency is the rate of a Poisson process. This means that
- # the probability of sampling an allocation of size X with sampling rate Y
- # is 1 - exp(-X/Y)
- # For version 2, a typical header line might look like this:
- # heap profile: 1922: 127792360 [ 1922: 127792360] @ <heap-url>_v2/524288
- # the trailing number (524288) is the sampling rate. (Version 1 showed
- # double the 'rate' here)
- my $sampling_algorithm = 0;
- my $sample_adjustment = 0;
- chomp($header);
- my $type = "unknown";
- if ($header =~ m"^heap profile:\s*(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\](\s*@\s*([^/]*)(/(\d+))?)?") {
- if (defined($6) && ($6 ne '')) {
- $type = $6;
- my $sample_period = $8;
- # $type is "heapprofile" for profiles generated by the
- # heap-profiler, and either "heap" or "heap_v2" for profiles
- # generated by sampling directly within tcmalloc. It can also
- # be "growth" for heap-growth profiles. The first is typically
- # found for profiles generated locally, and the others for
- # remote profiles.
- if (($type eq "heapprofile") || ($type !~ /heap/) ) {
- # No need to adjust for the sampling rate with heap-profiler-derived data
- $sampling_algorithm = 0;
- } elsif ($type =~ /_v2/) {
- $sampling_algorithm = 2; # version 2 sampling
- if (defined($sample_period) && ($sample_period ne '')) {
- $sample_adjustment = int($sample_period);
- }
- } else {
- $sampling_algorithm = 1; # version 1 sampling
- if (defined($sample_period) && ($sample_period ne '')) {
- $sample_adjustment = int($sample_period)/2;
- }
- }
- } else {
- # We detect whether or not this is a remote-heap profile by checking
- # that the total-allocated stats ($n2,$s2) are exactly the
- # same as the in-use stats ($n1,$s1). It is remotely conceivable
- # that a non-remote-heap profile may pass this check, but it is hard
- # to imagine how that could happen.
- # In this case it's so old it's guaranteed to be remote-heap version 1.
- my ($n1, $s1, $n2, $s2) = ($1, $2, $3, $4);
- if (($n1 == $n2) && ($s1 == $s2)) {
- # This is likely to be a remote-heap based sample profile
- $sampling_algorithm = 1;
- }
- }
- }
-
- if ($sampling_algorithm > 0) {
- # For remote-heap generated profiles, adjust the counts and sizes to
- # account for the sample rate (we sample once every 128KB by default).
- if ($sample_adjustment == 0) {
- # Turn on profile adjustment.
- $sample_adjustment = 128*1024;
- print STDERR "Adjusting heap profiles for 1-in-128KB sampling rate\n";
- } else {
- printf STDERR ("Adjusting heap profiles for 1-in-%d sampling rate\n",
- $sample_adjustment);
- }
- if ($sampling_algorithm > 1) {
- # We don't bother printing anything for the original version (version 1)
- printf STDERR "Heap version $sampling_algorithm\n";
- }
- }
-
- my $profile = {};
- my $pcs = {};
- my $map = "";
-
- while (<PROFILE>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- if (/^MAPPED_LIBRARIES:/) {
- $map .= ReadMappedLibraries(*PROFILE);
- last;
- }
-
- if (/^--- Memory map:/) {
- $map .= ReadMemoryMap(*PROFILE);
- last;
- }
-
- # Read entry of the form:
- # <count1>: <bytes1> [<count2>: <bytes2>] @ a1 a2 a3 ... an
- s/^\s*//;
- s/\s*$//;
- if (m/^\s*(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\]\s+@\s+(.*)$/) {
- my $stack = $5;
- my ($n1, $s1, $n2, $s2) = ($1, $2, $3, $4);
- my @counts = AdjustSamples($sample_adjustment, $sampling_algorithm,
- $n1, $s1, $n2, $s2);
- AddEntries($profile, $pcs, FixCallerAddresses($stack), $counts[$index]);
- }
- }
-
- my $r = {};
- $r->{version} = "heap";
- $r->{period} = 1;
- $r->{profile} = $profile;
- $r->{libs} = ParseLibraries($prog, $map, $pcs);
- $r->{pcs} = $pcs;
- return $r;
-}
-
-sub ReadThreadedHeapProfile {
- my ($prog, $fname, $header) = @_;
-
- my $index = HeapProfileIndex();
- my $sampling_algorithm = 0;
- my $sample_adjustment = 0;
- chomp($header);
- my $type = "unknown";
- # Assuming a very specific type of header for now.
- if ($header =~ m"^heap_v2/(\d+)") {
- $type = "_v2";
- $sampling_algorithm = 2;
- $sample_adjustment = int($1);
- }
- if ($type ne "_v2" || !defined($sample_adjustment)) {
- die "Threaded heap profiles require v2 sampling with a sample rate\n";
- }
-
- my $profile = {};
- my $thread_profiles = {};
- my $pcs = {};
- my $map = "";
- my $stack = "";
-
- while (<PROFILE>) {
- s/\r//g;
- if (/^MAPPED_LIBRARIES:/) {
- $map .= ReadMappedLibraries(*PROFILE);
- last;
- }
-
- if (/^--- Memory map:/) {
- $map .= ReadMemoryMap(*PROFILE);
- last;
- }
-
- # Read entry of the form:
- # @ a1 a2 ... an
- # t*: <count1>: <bytes1> [<count2>: <bytes2>]
- # t1: <count1>: <bytes1> [<count2>: <bytes2>]
- # ...
- # tn: <count1>: <bytes1> [<count2>: <bytes2>]
- s/^\s*//;
- s/\s*$//;
- if (m/^@\s+(.*)$/) {
- $stack = $1;
- } elsif (m/^\s*(t(\*|\d+)):\s+(\d+):\s+(\d+)\s+\[\s*(\d+):\s+(\d+)\]$/) {
- if ($stack eq "") {
- # Still in the header, so this is just a per-thread summary.
- next;
- }
- my $thread = $2;
- my ($n1, $s1, $n2, $s2) = ($3, $4, $5, $6);
- my @counts = AdjustSamples($sample_adjustment, $sampling_algorithm,
- $n1, $s1, $n2, $s2);
- if ($thread eq "*") {
- AddEntries($profile, $pcs, FixCallerAddresses($stack), $counts[$index]);
- } else {
- if (!exists($thread_profiles->{$thread})) {
- $thread_profiles->{$thread} = {};
- }
- AddEntries($thread_profiles->{$thread}, $pcs,
- FixCallerAddresses($stack), $counts[$index]);
- }
- }
- }
-
- my $r = {};
- $r->{version} = "heap";
- $r->{period} = 1;
- $r->{profile} = $profile;
- $r->{threads} = $thread_profiles;
- $r->{libs} = ParseLibraries($prog, $map, $pcs);
- $r->{pcs} = $pcs;
- return $r;
-}
-
-sub ReadSynchProfile {
- my $prog = shift;
- local *PROFILE = shift;
- my $header = shift;
-
- my $map = '';
- my $profile = {};
- my $pcs = {};
- my $sampling_period = 1;
- my $cyclespernanosec = 2.8; # Default assumption for old binaries
- my $seen_clockrate = 0;
- my $line;
-
- my $index = 0;
- if ($main::opt_total_delay) {
- $index = 0;
- } elsif ($main::opt_contentions) {
- $index = 1;
- } elsif ($main::opt_mean_delay) {
- $index = 2;
- }
-
- while ( $line = <PROFILE> ) {
- $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
- if ( $line =~ /^\s*(\d+)\s+(\d+) \@\s*(.*?)\s*$/ ) {
- my ($cycles, $count, $stack) = ($1, $2, $3);
-
- # Convert cycles to nanoseconds
- $cycles /= $cyclespernanosec;
-
- # Adjust for sampling done by application
- $cycles *= $sampling_period;
- $count *= $sampling_period;
-
- my @values = ($cycles, $count, $cycles / $count);
- AddEntries($profile, $pcs, FixCallerAddresses($stack), $values[$index]);
-
- } elsif ( $line =~ /^(slow release).*thread \d+ \@\s*(.*?)\s*$/ ||
- $line =~ /^\s*(\d+) \@\s*(.*?)\s*$/ ) {
- my ($cycles, $stack) = ($1, $2);
- if ($cycles !~ /^\d+$/) {
- next;
- }
-
- # Convert cycles to nanoseconds
- $cycles /= $cyclespernanosec;
-
- # Adjust for sampling done by application
- $cycles *= $sampling_period;
-
- AddEntries($profile, $pcs, FixCallerAddresses($stack), $cycles);
-
- } elsif ( $line =~ m/^([a-z][^=]*)=(.*)$/ ) {
- my ($variable, $value) = ($1,$2);
- for ($variable, $value) {
- s/^\s+//;
- s/\s+$//;
- }
- if ($variable eq "cycles/second") {
- $cyclespernanosec = $value / 1e9;
- $seen_clockrate = 1;
- } elsif ($variable eq "sampling period") {
- $sampling_period = $value;
- } elsif ($variable eq "ms since reset") {
- # Currently nothing is done with this value in jeprof
- # So we just silently ignore it for now
- } elsif ($variable eq "discarded samples") {
- # Currently nothing is done with this value in jeprof
- # So we just silently ignore it for now
- } else {
- printf STDERR ("Ignoring unnknown variable in /contention output: " .
- "'%s' = '%s'\n",$variable,$value);
- }
- } else {
- # Memory map entry
- $map .= $line;
- }
- }
-
- if (!$seen_clockrate) {
- printf STDERR ("No cycles/second entry in profile; Guessing %.1f GHz\n",
- $cyclespernanosec);
- }
-
- my $r = {};
- $r->{version} = 0;
- $r->{period} = $sampling_period;
- $r->{profile} = $profile;
- $r->{libs} = ParseLibraries($prog, $map, $pcs);
- $r->{pcs} = $pcs;
- return $r;
-}
-
-# Given a hex value in the form "0x1abcd" or "1abcd", return either
-# "0001abcd" or "000000000001abcd", depending on the current (global)
-# address length.
-sub HexExtend {
- my $addr = shift;
-
- $addr =~ s/^(0x)?0*//;
- my $zeros_needed = $address_length - length($addr);
- if ($zeros_needed < 0) {
- printf STDERR "Warning: address $addr is longer than address length $address_length\n";
- return $addr;
- }
- return ("0" x $zeros_needed) . $addr;
-}
-
-##### Symbol extraction #####
-
-# Aggressively search the lib_prefix values for the given library
-# If all else fails, just return the name of the library unmodified.
-# If the lib_prefix is "/my/path,/other/path" and $file is "/lib/dir/mylib.so"
-# it will search the following locations in this order, until it finds a file:
-# /my/path/lib/dir/mylib.so
-# /other/path/lib/dir/mylib.so
-# /my/path/dir/mylib.so
-# /other/path/dir/mylib.so
-# /my/path/mylib.so
-# /other/path/mylib.so
-# /lib/dir/mylib.so (returned as last resort)
-sub FindLibrary {
- my $file = shift;
- my $suffix = $file;
-
- # Search for the library as described above
- do {
- foreach my $prefix (@prefix_list) {
- my $fullpath = $prefix . $suffix;
- if (-e $fullpath) {
- return $fullpath;
- }
- }
- } while ($suffix =~ s|^/[^/]+/|/|);
- return $file;
-}
-
-# Return path to library with debugging symbols.
-# For libc libraries, the copy in /usr/lib/debug contains debugging symbols
-sub DebuggingLibrary {
- my $file = shift;
- if ($file =~ m|^/|) {
- if (-f "/usr/lib/debug$file") {
- return "/usr/lib/debug$file";
- } elsif (-f "/usr/lib/debug$file.debug") {
- return "/usr/lib/debug$file.debug";
- }
- }
- return undef;
-}
-
-# Parse text section header of a library using objdump
-sub ParseTextSectionHeaderFromObjdump {
- my $lib = shift;
-
- my $size = undef;
- my $vma;
- my $file_offset;
- # Get objdump output from the library file to figure out how to
- # map between mapped addresses and addresses in the library.
- my $cmd = ShellEscape($obj_tool_map{"objdump"}, "-h", $lib);
- open(OBJDUMP, "$cmd |") || error("$cmd: $!\n");
- while (<OBJDUMP>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- # Idx Name Size VMA LMA File off Algn
- # 10 .text 00104b2c 420156f0 420156f0 000156f0 2**4
- # For 64-bit objects, VMA and LMA will be 16 hex digits, size and file
- # offset may still be 8. But AddressSub below will still handle that.
- my @x = split;
- if (($#x >= 6) && ($x[1] eq '.text')) {
- $size = $x[2];
- $vma = $x[3];
- $file_offset = $x[5];
- last;
- }
- }
- close(OBJDUMP);
-
- if (!defined($size)) {
- return undef;
- }
-
- my $r = {};
- $r->{size} = $size;
- $r->{vma} = $vma;
- $r->{file_offset} = $file_offset;
-
- return $r;
-}
-
-# Parse text section header of a library using otool (on OS X)
-sub ParseTextSectionHeaderFromOtool {
- my $lib = shift;
-
- my $size = undef;
- my $vma = undef;
- my $file_offset = undef;
- # Get otool output from the library file to figure out how to
- # map between mapped addresses and addresses in the library.
- my $command = ShellEscape($obj_tool_map{"otool"}, "-l", $lib);
- open(OTOOL, "$command |") || error("$command: $!\n");
- my $cmd = "";
- my $sectname = "";
- my $segname = "";
- foreach my $line (<OTOOL>) {
- $line =~ s/\r//g; # turn windows-looking lines into unix-looking lines
- # Load command <#>
- # cmd LC_SEGMENT
- # [...]
- # Section
- # sectname __text
- # segname __TEXT
- # addr 0x000009f8
- # size 0x00018b9e
- # offset 2552
- # align 2^2 (4)
- # We will need to strip off the leading 0x from the hex addresses,
- # and convert the offset into hex.
- if ($line =~ /Load command/) {
- $cmd = "";
- $sectname = "";
- $segname = "";
- } elsif ($line =~ /Section/) {
- $sectname = "";
- $segname = "";
- } elsif ($line =~ /cmd (\w+)/) {
- $cmd = $1;
- } elsif ($line =~ /sectname (\w+)/) {
- $sectname = $1;
- } elsif ($line =~ /segname (\w+)/) {
- $segname = $1;
- } elsif (!(($cmd eq "LC_SEGMENT" || $cmd eq "LC_SEGMENT_64") &&
- $sectname eq "__text" &&
- $segname eq "__TEXT")) {
- next;
- } elsif ($line =~ /\baddr 0x([0-9a-fA-F]+)/) {
- $vma = $1;
- } elsif ($line =~ /\bsize 0x([0-9a-fA-F]+)/) {
- $size = $1;
- } elsif ($line =~ /\boffset ([0-9]+)/) {
- $file_offset = sprintf("%016x", $1);
- }
- if (defined($vma) && defined($size) && defined($file_offset)) {
- last;
- }
- }
- close(OTOOL);
-
- if (!defined($vma) || !defined($size) || !defined($file_offset)) {
- return undef;
- }
-
- my $r = {};
- $r->{size} = $size;
- $r->{vma} = $vma;
- $r->{file_offset} = $file_offset;
-
- return $r;
-}
-
-sub ParseTextSectionHeader {
- # obj_tool_map("otool") is only defined if we're in a Mach-O environment
- if (defined($obj_tool_map{"otool"})) {
- my $r = ParseTextSectionHeaderFromOtool(@_);
- if (defined($r)){
- return $r;
- }
- }
- # If otool doesn't work, or we don't have it, fall back to objdump
- return ParseTextSectionHeaderFromObjdump(@_);
-}
-
-# Split /proc/pid/maps dump into a list of libraries
-sub ParseLibraries {
- return if $main::use_symbol_page; # We don't need libraries info.
- my $prog = shift;
- my $map = shift;
- my $pcs = shift;
-
- my $result = [];
- my $h = "[a-f0-9]+";
- my $zero_offset = HexExtend("0");
-
- my $buildvar = "";
- foreach my $l (split("\n", $map)) {
- if ($l =~ m/^\s*build=(.*)$/) {
- $buildvar = $1;
- }
-
- my $start;
- my $finish;
- my $offset;
- my $lib;
- if ($l =~ /^($h)-($h)\s+..x.\s+($h)\s+\S+:\S+\s+\d+\s+(\S+\.(so|dll|dylib|bundle)((\.\d+)+\w*(\.\d+){0,3})?)$/i) {
- # Full line from /proc/self/maps. Example:
- # 40000000-40015000 r-xp 00000000 03:01 12845071 /lib/ld-2.3.2.so
- $start = HexExtend($1);
- $finish = HexExtend($2);
- $offset = HexExtend($3);
- $lib = $4;
- $lib =~ s|\\|/|g; # turn windows-style paths into unix-style paths
- } elsif ($l =~ /^\s*($h)-($h):\s*(\S+\.so(\.\d+)*)/) {
- # Cooked line from DumpAddressMap. Example:
- # 40000000-40015000: /lib/ld-2.3.2.so
- $start = HexExtend($1);
- $finish = HexExtend($2);
- $offset = $zero_offset;
- $lib = $3;
- }
- # FreeBSD 10.0 virtual memory map /proc/curproc/map as defined in
- # function procfs_doprocmap (sys/fs/procfs/procfs_map.c)
- #
- # Example:
- # 0x800600000 0x80061a000 26 0 0xfffff800035a0000 r-x 75 33 0x1004 COW NC vnode /libexec/ld-elf.s
- # o.1 NCH -1
- elsif ($l =~ /^(0x$h)\s(0x$h)\s\d+\s\d+\s0x$h\sr-x\s\d+\s\d+\s0x\d+\s(COW|NCO)\s(NC|NNC)\svnode\s(\S+\.so(\.\d+)*)/) {
- $start = HexExtend($1);
- $finish = HexExtend($2);
- $offset = $zero_offset;
- $lib = FindLibrary($5);
-
- } else {
- next;
- }
-
- # Expand "$build" variable if available
- $lib =~ s/\$build\b/$buildvar/g;
-
- $lib = FindLibrary($lib);
-
- # Check for pre-relocated libraries, which use pre-relocated symbol tables
- # and thus require adjusting the offset that we'll use to translate
- # VM addresses into symbol table addresses.
- # Only do this if we're not going to fetch the symbol table from a
- # debugging copy of the library.
- if (!DebuggingLibrary($lib)) {
- my $text = ParseTextSectionHeader($lib);
- if (defined($text)) {
- my $vma_offset = AddressSub($text->{vma}, $text->{file_offset});
- $offset = AddressAdd($offset, $vma_offset);
- }
- }
-
- if($main::opt_debug) { printf STDERR "$start:$finish ($offset) $lib\n"; }
- push(@{$result}, [$lib, $start, $finish, $offset]);
- }
-
- # Append special entry for additional library (not relocated)
- if ($main::opt_lib ne "") {
- my $text = ParseTextSectionHeader($main::opt_lib);
- if (defined($text)) {
- my $start = $text->{vma};
- my $finish = AddressAdd($start, $text->{size});
-
- push(@{$result}, [$main::opt_lib, $start, $finish, $start]);
- }
- }
-
- # Append special entry for the main program. This covers
- # 0..max_pc_value_seen, so that we assume pc values not found in one
- # of the library ranges will be treated as coming from the main
- # program binary.
- my $min_pc = HexExtend("0");
- my $max_pc = $min_pc; # find the maximal PC value in any sample
- foreach my $pc (keys(%{$pcs})) {
- if (HexExtend($pc) gt $max_pc) { $max_pc = HexExtend($pc); }
- }
- push(@{$result}, [$prog, $min_pc, $max_pc, $zero_offset]);
-
- return $result;
-}
-
-# Add two hex addresses of length $address_length.
-# Run jeprof --test for unit test if this is changed.
-sub AddressAdd {
- my $addr1 = shift;
- my $addr2 = shift;
- my $sum;
-
- if ($address_length == 8) {
- # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
- $sum = (hex($addr1)+hex($addr2)) % (0x10000000 * 16);
- return sprintf("%08x", $sum);
-
- } else {
- # Do the addition in 7-nibble chunks to trivialize carry handling.
-
- if ($main::opt_debug and $main::opt_test) {
- print STDERR "AddressAdd $addr1 + $addr2 = ";
- }
-
- my $a1 = substr($addr1,-7);
- $addr1 = substr($addr1,0,-7);
- my $a2 = substr($addr2,-7);
- $addr2 = substr($addr2,0,-7);
- $sum = hex($a1) + hex($a2);
- my $c = 0;
- if ($sum > 0xfffffff) {
- $c = 1;
- $sum -= 0x10000000;
- }
- my $r = sprintf("%07x", $sum);
-
- $a1 = substr($addr1,-7);
- $addr1 = substr($addr1,0,-7);
- $a2 = substr($addr2,-7);
- $addr2 = substr($addr2,0,-7);
- $sum = hex($a1) + hex($a2) + $c;
- $c = 0;
- if ($sum > 0xfffffff) {
- $c = 1;
- $sum -= 0x10000000;
- }
- $r = sprintf("%07x", $sum) . $r;
-
- $sum = hex($addr1) + hex($addr2) + $c;
- if ($sum > 0xff) { $sum -= 0x100; }
- $r = sprintf("%02x", $sum) . $r;
-
- if ($main::opt_debug and $main::opt_test) { print STDERR "$r\n"; }
-
- return $r;
- }
-}
-
-
-# Subtract two hex addresses of length $address_length.
-# Run jeprof --test for unit test if this is changed.
-sub AddressSub {
- my $addr1 = shift;
- my $addr2 = shift;
- my $diff;
-
- if ($address_length == 8) {
- # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
- $diff = (hex($addr1)-hex($addr2)) % (0x10000000 * 16);
- return sprintf("%08x", $diff);
-
- } else {
- # Do the addition in 7-nibble chunks to trivialize borrow handling.
- # if ($main::opt_debug) { print STDERR "AddressSub $addr1 - $addr2 = "; }
-
- my $a1 = hex(substr($addr1,-7));
- $addr1 = substr($addr1,0,-7);
- my $a2 = hex(substr($addr2,-7));
- $addr2 = substr($addr2,0,-7);
- my $b = 0;
- if ($a2 > $a1) {
- $b = 1;
- $a1 += 0x10000000;
- }
- $diff = $a1 - $a2;
- my $r = sprintf("%07x", $diff);
-
- $a1 = hex(substr($addr1,-7));
- $addr1 = substr($addr1,0,-7);
- $a2 = hex(substr($addr2,-7)) + $b;
- $addr2 = substr($addr2,0,-7);
- $b = 0;
- if ($a2 > $a1) {
- $b = 1;
- $a1 += 0x10000000;
- }
- $diff = $a1 - $a2;
- $r = sprintf("%07x", $diff) . $r;
-
- $a1 = hex($addr1);
- $a2 = hex($addr2) + $b;
- if ($a2 > $a1) { $a1 += 0x100; }
- $diff = $a1 - $a2;
- $r = sprintf("%02x", $diff) . $r;
-
- # if ($main::opt_debug) { print STDERR "$r\n"; }
-
- return $r;
- }
-}
-
-# Increment a hex addresses of length $address_length.
-# Run jeprof --test for unit test if this is changed.
-sub AddressInc {
- my $addr = shift;
- my $sum;
-
- if ($address_length == 8) {
- # Perl doesn't cope with wraparound arithmetic, so do it explicitly:
- $sum = (hex($addr)+1) % (0x10000000 * 16);
- return sprintf("%08x", $sum);
-
- } else {
- # Do the addition in 7-nibble chunks to trivialize carry handling.
- # We are always doing this to step through the addresses in a function,
- # and will almost never overflow the first chunk, so we check for this
- # case and exit early.
-
- # if ($main::opt_debug) { print STDERR "AddressInc $addr1 = "; }
-
- my $a1 = substr($addr,-7);
- $addr = substr($addr,0,-7);
- $sum = hex($a1) + 1;
- my $r = sprintf("%07x", $sum);
- if ($sum <= 0xfffffff) {
- $r = $addr . $r;
- # if ($main::opt_debug) { print STDERR "$r\n"; }
- return HexExtend($r);
- } else {
- $r = "0000000";
- }
-
- $a1 = substr($addr,-7);
- $addr = substr($addr,0,-7);
- $sum = hex($a1) + 1;
- $r = sprintf("%07x", $sum) . $r;
- if ($sum <= 0xfffffff) {
- $r = $addr . $r;
- # if ($main::opt_debug) { print STDERR "$r\n"; }
- return HexExtend($r);
- } else {
- $r = "00000000000000";
- }
-
- $sum = hex($addr) + 1;
- if ($sum > 0xff) { $sum -= 0x100; }
- $r = sprintf("%02x", $sum) . $r;
-
- # if ($main::opt_debug) { print STDERR "$r\n"; }
- return $r;
- }
-}
-
-# Extract symbols for all PC values found in profile
-sub ExtractSymbols {
- my $libs = shift;
- my $pcset = shift;
-
- my $symbols = {};
-
- # Map each PC value to the containing library. To make this faster,
- # we sort libraries by their starting pc value (highest first), and
- # advance through the libraries as we advance the pc. Sometimes the
- # addresses of libraries may overlap with the addresses of the main
- # binary, so to make sure the libraries 'win', we iterate over the
- # libraries in reverse order (which assumes the binary doesn't start
- # in the middle of a library, which seems a fair assumption).
- my @pcs = (sort { $a cmp $b } keys(%{$pcset})); # pcset is 0-extended strings
- foreach my $lib (sort {$b->[1] cmp $a->[1]} @{$libs}) {
- my $libname = $lib->[0];
- my $start = $lib->[1];
- my $finish = $lib->[2];
- my $offset = $lib->[3];
-
- # Use debug library if it exists
- my $debug_libname = DebuggingLibrary($libname);
- if ($debug_libname) {
- $libname = $debug_libname;
- }
-
- # Get list of pcs that belong in this library.
- my $contained = [];
- my ($start_pc_index, $finish_pc_index);
- # Find smallest finish_pc_index such that $finish < $pc[$finish_pc_index].
- for ($finish_pc_index = $#pcs + 1; $finish_pc_index > 0;
- $finish_pc_index--) {
- last if $pcs[$finish_pc_index - 1] le $finish;
- }
- # Find smallest start_pc_index such that $start <= $pc[$start_pc_index].
- for ($start_pc_index = $finish_pc_index; $start_pc_index > 0;
- $start_pc_index--) {
- last if $pcs[$start_pc_index - 1] lt $start;
- }
- # This keeps PC values higher than $pc[$finish_pc_index] in @pcs,
- # in case there are overlaps in libraries and the main binary.
- @{$contained} = splice(@pcs, $start_pc_index,
- $finish_pc_index - $start_pc_index);
- # Map to symbols
- MapToSymbols($libname, AddressSub($start, $offset), $contained, $symbols);
- }
-
- return $symbols;
-}
-
-# Map list of PC values to symbols for a given image
-sub MapToSymbols {
- my $image = shift;
- my $offset = shift;
- my $pclist = shift;
- my $symbols = shift;
-
- my $debug = 0;
-
- # Ignore empty binaries
- if ($#{$pclist} < 0) { return; }
-
- # Figure out the addr2line command to use
- my $addr2line = $obj_tool_map{"addr2line"};
- my $cmd = ShellEscape($addr2line, "-f", "-C", "-e", $image);
- if (exists $obj_tool_map{"addr2line_pdb"}) {
- $addr2line = $obj_tool_map{"addr2line_pdb"};
- $cmd = ShellEscape($addr2line, "--demangle", "-f", "-C", "-e", $image);
- }
-
- # If "addr2line" isn't installed on the system at all, just use
- # nm to get what info we can (function names, but not line numbers).
- if (system(ShellEscape($addr2line, "--help") . " >$dev_null 2>&1") != 0) {
- MapSymbolsWithNM($image, $offset, $pclist, $symbols);
- return;
- }
-
- # "addr2line -i" can produce a variable number of lines per input
- # address, with no separator that allows us to tell when data for
- # the next address starts. So we find the address for a special
- # symbol (_fini) and interleave this address between all real
- # addresses passed to addr2line. The name of this special symbol
- # can then be used as a separator.
- $sep_address = undef; # May be filled in by MapSymbolsWithNM()
- my $nm_symbols = {};
- MapSymbolsWithNM($image, $offset, $pclist, $nm_symbols);
- if (defined($sep_address)) {
- # Only add " -i" to addr2line if the binary supports it.
- # addr2line --help returns 0, but not if it sees an unknown flag first.
- if (system("$cmd -i --help >$dev_null 2>&1") == 0) {
- $cmd .= " -i";
- } else {
- $sep_address = undef; # no need for sep_address if we don't support -i
- }
- }
-
- # Make file with all PC values with intervening 'sep_address' so
- # that we can reliably detect the end of inlined function list
- open(ADDRESSES, ">$main::tmpfile_sym") || error("$main::tmpfile_sym: $!\n");
- if ($debug) { print("---- $image ---\n"); }
- for (my $i = 0; $i <= $#{$pclist}; $i++) {
- # addr2line always reads hex addresses, and does not need '0x' prefix.
- if ($debug) { printf STDERR ("%s\n", $pclist->[$i]); }
- printf ADDRESSES ("%s\n", AddressSub($pclist->[$i], $offset));
- if (defined($sep_address)) {
- printf ADDRESSES ("%s\n", $sep_address);
- }
- }
- close(ADDRESSES);
- if ($debug) {
- print("----\n");
- system("cat", $main::tmpfile_sym);
- print("----\n");
- system("$cmd < " . ShellEscape($main::tmpfile_sym));
- print("----\n");
- }
-
- open(SYMBOLS, "$cmd <" . ShellEscape($main::tmpfile_sym) . " |")
- || error("$cmd: $!\n");
- my $count = 0; # Index in pclist
- while (<SYMBOLS>) {
- # Read fullfunction and filelineinfo from next pair of lines
- s/\r?\n$//g;
- my $fullfunction = $_;
- $_ = <SYMBOLS>;
- s/\r?\n$//g;
- my $filelinenum = $_;
-
- if (defined($sep_address) && $fullfunction eq $sep_symbol) {
- # Terminating marker for data for this address
- $count++;
- next;
- }
-
- $filelinenum =~ s|\\|/|g; # turn windows-style paths into unix-style paths
-
- my $pcstr = $pclist->[$count];
- my $function = ShortFunctionName($fullfunction);
- my $nms = $nm_symbols->{$pcstr};
- if (defined($nms)) {
- if ($fullfunction eq '??') {
- # nm found a symbol for us.
- $function = $nms->[0];
- $fullfunction = $nms->[2];
- } else {
- # MapSymbolsWithNM tags each routine with its starting address,
- # useful in case the image has multiple occurrences of this
- # routine. (It uses a syntax that resembles template paramters,
- # that are automatically stripped out by ShortFunctionName().)
- # addr2line does not provide the same information. So we check
- # if nm disambiguated our symbol, and if so take the annotated
- # (nm) version of the routine-name. TODO(csilvers): this won't
- # catch overloaded, inlined symbols, which nm doesn't see.
- # Better would be to do a check similar to nm's, in this fn.
- if ($nms->[2] =~ m/^\Q$function\E/) { # sanity check it's the right fn
- $function = $nms->[0];
- $fullfunction = $nms->[2];
- }
- }
- }
-
- # Prepend to accumulated symbols for pcstr
- # (so that caller comes before callee)
- my $sym = $symbols->{$pcstr};
- if (!defined($sym)) {
- $sym = [];
- $symbols->{$pcstr} = $sym;
- }
- unshift(@{$sym}, $function, $filelinenum, $fullfunction);
- if ($debug) { printf STDERR ("%s => [%s]\n", $pcstr, join(" ", @{$sym})); }
- if (!defined($sep_address)) {
- # Inlining is off, so this entry ends immediately
- $count++;
- }
- }
- close(SYMBOLS);
-}
-
-# Use nm to map the list of referenced PCs to symbols. Return true iff we
-# are able to read procedure information via nm.
-sub MapSymbolsWithNM {
- my $image = shift;
- my $offset = shift;
- my $pclist = shift;
- my $symbols = shift;
-
- # Get nm output sorted by increasing address
- my $symbol_table = GetProcedureBoundaries($image, ".");
- if (!%{$symbol_table}) {
- return 0;
- }
- # Start addresses are already the right length (8 or 16 hex digits).
- my @names = sort { $symbol_table->{$a}->[0] cmp $symbol_table->{$b}->[0] }
- keys(%{$symbol_table});
-
- if ($#names < 0) {
- # No symbols: just use addresses
- foreach my $pc (@{$pclist}) {
- my $pcstr = "0x" . $pc;
- $symbols->{$pc} = [$pcstr, "?", $pcstr];
- }
- return 0;
- }
-
- # Sort addresses so we can do a join against nm output
- my $index = 0;
- my $fullname = $names[0];
- my $name = ShortFunctionName($fullname);
- foreach my $pc (sort { $a cmp $b } @{$pclist}) {
- # Adjust for mapped offset
- my $mpc = AddressSub($pc, $offset);
- while (($index < $#names) && ($mpc ge $symbol_table->{$fullname}->[1])){
- $index++;
- $fullname = $names[$index];
- $name = ShortFunctionName($fullname);
- }
- if ($mpc lt $symbol_table->{$fullname}->[1]) {
- $symbols->{$pc} = [$name, "?", $fullname];
- } else {
- my $pcstr = "0x" . $pc;
- $symbols->{$pc} = [$pcstr, "?", $pcstr];
- }
- }
- return 1;
-}
-
-sub ShortFunctionName {
- my $function = shift;
- while ($function =~ s/\([^()]*\)(\s*const)?//g) { } # Argument types
- while ($function =~ s/<[^<>]*>//g) { } # Remove template arguments
- $function =~ s/^.*\s+(\w+::)/$1/; # Remove leading type
- return $function;
-}
-
-# Trim overly long symbols found in disassembler output
-sub CleanDisassembly {
- my $d = shift;
- while ($d =~ s/\([^()%]*\)(\s*const)?//g) { } # Argument types, not (%rax)
- while ($d =~ s/(\w+)<[^<>]*>/$1/g) { } # Remove template arguments
- return $d;
-}
-
-# Clean file name for display
-sub CleanFileName {
- my ($f) = @_;
- $f =~ s|^/proc/self/cwd/||;
- $f =~ s|^\./||;
- return $f;
-}
-
-# Make address relative to section and clean up for display
-sub UnparseAddress {
- my ($offset, $address) = @_;
- $address = AddressSub($address, $offset);
- $address =~ s/^0x//;
- $address =~ s/^0*//;
- return $address;
-}
-
-##### Miscellaneous #####
-
-# Find the right versions of the above object tools to use. The
-# argument is the program file being analyzed, and should be an ELF
-# 32-bit or ELF 64-bit executable file. The location of the tools
-# is determined by considering the following options in this order:
-# 1) --tools option, if set
-# 2) JEPROF_TOOLS environment variable, if set
-# 3) the environment
-sub ConfigureObjTools {
- my $prog_file = shift;
-
- # Check for the existence of $prog_file because /usr/bin/file does not
- # predictably return error status in prod.
- (-e $prog_file) || error("$prog_file does not exist.\n");
-
- my $file_type = undef;
- if (-e "/usr/bin/file") {
- # Follow symlinks (at least for systems where "file" supports that).
- my $escaped_prog_file = ShellEscape($prog_file);
- $file_type = `/usr/bin/file -L $escaped_prog_file 2>$dev_null ||
- /usr/bin/file $escaped_prog_file`;
- } elsif ($^O == "MSWin32") {
- $file_type = "MS Windows";
- } else {
- print STDERR "WARNING: Can't determine the file type of $prog_file";
- }
-
- if ($file_type =~ /64-bit/) {
- # Change $address_length to 16 if the program file is ELF 64-bit.
- # We can't detect this from many (most?) heap or lock contention
- # profiles, since the actual addresses referenced are generally in low
- # memory even for 64-bit programs.
- $address_length = 16;
- }
-
- if ($file_type =~ /MS Windows/) {
- # For windows, we provide a version of nm and addr2line as part of
- # the opensource release, which is capable of parsing
- # Windows-style PDB executables. It should live in the path, or
- # in the same directory as jeprof.
- $obj_tool_map{"nm_pdb"} = "nm-pdb";
- $obj_tool_map{"addr2line_pdb"} = "addr2line-pdb";
- }
-
- if ($file_type =~ /Mach-O/) {
- # OS X uses otool to examine Mach-O files, rather than objdump.
- $obj_tool_map{"otool"} = "otool";
- $obj_tool_map{"addr2line"} = "false"; # no addr2line
- $obj_tool_map{"objdump"} = "false"; # no objdump
- }
-
- # Go fill in %obj_tool_map with the pathnames to use:
- foreach my $tool (keys %obj_tool_map) {
- $obj_tool_map{$tool} = ConfigureTool($obj_tool_map{$tool});
- }
-}
-
-# Returns the path of a caller-specified object tool. If --tools or
-# JEPROF_TOOLS are specified, then returns the full path to the tool
-# with that prefix. Otherwise, returns the path unmodified (which
-# means we will look for it on PATH).
-sub ConfigureTool {
- my $tool = shift;
- my $path;
-
- # --tools (or $JEPROF_TOOLS) is a comma separated list, where each
- # item is either a) a pathname prefix, or b) a map of the form
- # <tool>:<path>. First we look for an entry of type (b) for our
- # tool. If one is found, we use it. Otherwise, we consider all the
- # pathname prefixes in turn, until one yields an existing file. If
- # none does, we use a default path.
- my $tools = $main::opt_tools || $ENV{"JEPROF_TOOLS"} || "";
- if ($tools =~ m/(,|^)\Q$tool\E:([^,]*)/) {
- $path = $2;
- # TODO(csilvers): sanity-check that $path exists? Hard if it's relative.
- } elsif ($tools ne '') {
- foreach my $prefix (split(',', $tools)) {
- next if ($prefix =~ /:/); # ignore "tool:fullpath" entries in the list
- if (-x $prefix . $tool) {
- $path = $prefix . $tool;
- last;
- }
- }
- if (!$path) {
- error("No '$tool' found with prefix specified by " .
- "--tools (or \$JEPROF_TOOLS) '$tools'\n");
- }
- } else {
- # ... otherwise use the version that exists in the same directory as
- # jeprof. If there's nothing there, use $PATH.
- $0 =~ m,[^/]*$,; # this is everything after the last slash
- my $dirname = $`; # this is everything up to and including the last slash
- if (-x "$dirname$tool") {
- $path = "$dirname$tool";
- } else {
- $path = $tool;
- }
- }
- if ($main::opt_debug) { print STDERR "Using '$path' for '$tool'.\n"; }
- return $path;
-}
-
-sub ShellEscape {
- my @escaped_words = ();
- foreach my $word (@_) {
- my $escaped_word = $word;
- if ($word =~ m![^a-zA-Z0-9/.,_=-]!) { # check for anything not in whitelist
- $escaped_word =~ s/'/'\\''/;
- $escaped_word = "'$escaped_word'";
- }
- push(@escaped_words, $escaped_word);
- }
- return join(" ", @escaped_words);
-}
-
-sub cleanup {
- unlink($main::tmpfile_sym);
- unlink(keys %main::tempnames);
-
- # We leave any collected profiles in $HOME/jeprof in case the user wants
- # to look at them later. We print a message informing them of this.
- if ((scalar(@main::profile_files) > 0) &&
- defined($main::collected_profile)) {
- if (scalar(@main::profile_files) == 1) {
- print STDERR "Dynamically gathered profile is in $main::collected_profile\n";
- }
- print STDERR "If you want to investigate this profile further, you can do:\n";
- print STDERR "\n";
- print STDERR " jeprof \\\n";
- print STDERR " $main::prog \\\n";
- print STDERR " $main::collected_profile\n";
- print STDERR "\n";
- }
-}
-
-sub sighandler {
- cleanup();
- exit(1);
-}
-
-sub error {
- my $msg = shift;
- print STDERR $msg;
- cleanup();
- exit(1);
-}
-
-
-# Run $nm_command and get all the resulting procedure boundaries whose
-# names match "$regexp" and returns them in a hashtable mapping from
-# procedure name to a two-element vector of [start address, end address]
-sub GetProcedureBoundariesViaNm {
- my $escaped_nm_command = shift; # shell-escaped
- my $regexp = shift;
-
- my $symbol_table = {};
- open(NM, "$escaped_nm_command |") || error("$escaped_nm_command: $!\n");
- my $last_start = "0";
- my $routine = "";
- while (<NM>) {
- s/\r//g; # turn windows-looking lines into unix-looking lines
- if (m/^\s*([0-9a-f]+) (.) (..*)/) {
- my $start_val = $1;
- my $type = $2;
- my $this_routine = $3;
-
- # It's possible for two symbols to share the same address, if
- # one is a zero-length variable (like __start_google_malloc) or
- # one symbol is a weak alias to another (like __libc_malloc).
- # In such cases, we want to ignore all values except for the
- # actual symbol, which in nm-speak has type "T". The logic
- # below does this, though it's a bit tricky: what happens when
- # we have a series of lines with the same address, is the first
- # one gets queued up to be processed. However, it won't
- # *actually* be processed until later, when we read a line with
- # a different address. That means that as long as we're reading
- # lines with the same address, we have a chance to replace that
- # item in the queue, which we do whenever we see a 'T' entry --
- # that is, a line with type 'T'. If we never see a 'T' entry,
- # we'll just go ahead and process the first entry (which never
- # got touched in the queue), and ignore the others.
- if ($start_val eq $last_start && $type =~ /t/i) {
- # We are the 'T' symbol at this address, replace previous symbol.
- $routine = $this_routine;
- next;
- } elsif ($start_val eq $last_start) {
- # We're not the 'T' symbol at this address, so ignore us.
- next;
- }
-
- if ($this_routine eq $sep_symbol) {
- $sep_address = HexExtend($start_val);
- }
-
- # Tag this routine with the starting address in case the image
- # has multiple occurrences of this routine. We use a syntax
- # that resembles template parameters that are automatically
- # stripped out by ShortFunctionName()
- $this_routine .= "<$start_val>";
-
- if (defined($routine) && $routine =~ m/$regexp/) {
- $symbol_table->{$routine} = [HexExtend($last_start),
- HexExtend($start_val)];
- }
- $last_start = $start_val;
- $routine = $this_routine;
- } elsif (m/^Loaded image name: (.+)/) {
- # The win32 nm workalike emits information about the binary it is using.
- if ($main::opt_debug) { print STDERR "Using Image $1\n"; }
- } elsif (m/^PDB file name: (.+)/) {
- # The win32 nm workalike emits information about the pdb it is using.
- if ($main::opt_debug) { print STDERR "Using PDB $1\n"; }
- }
- }
- close(NM);
- # Handle the last line in the nm output. Unfortunately, we don't know
- # how big this last symbol is, because we don't know how big the file
- # is. For now, we just give it a size of 0.
- # TODO(csilvers): do better here.
- if (defined($routine) && $routine =~ m/$regexp/) {
- $symbol_table->{$routine} = [HexExtend($last_start),
- HexExtend($last_start)];
- }
- return $symbol_table;
-}
-
-# Gets the procedure boundaries for all routines in "$image" whose names
-# match "$regexp" and returns them in a hashtable mapping from procedure
-# name to a two-element vector of [start address, end address].
-# Will return an empty map if nm is not installed or not working properly.
-sub GetProcedureBoundaries {
- my $image = shift;
- my $regexp = shift;
-
- # If $image doesn't start with /, then put ./ in front of it. This works
- # around an obnoxious bug in our probing of nm -f behavior.
- # "nm -f $image" is supposed to fail on GNU nm, but if:
- #
- # a. $image starts with [BbSsPp] (for example, bin/foo/bar), AND
- # b. you have a.out in your current directory (a not uncommon occurence)
- #
- # then "nm -f $image" succeeds because -f only looks at the first letter of
- # the argument, which looks valid because it's [BbSsPp], and then since
- # there's no image provided, it looks for a.out and finds it.
- #
- # This regex makes sure that $image starts with . or /, forcing the -f
- # parsing to fail since . and / are not valid formats.
- $image =~ s#^[^/]#./$&#;
-
- # For libc libraries, the copy in /usr/lib/debug contains debugging symbols
- my $debugging = DebuggingLibrary($image);
- if ($debugging) {
- $image = $debugging;
- }
-
- my $nm = $obj_tool_map{"nm"};
- my $cppfilt = $obj_tool_map{"c++filt"};
-
- # nm can fail for two reasons: 1) $image isn't a debug library; 2) nm
- # binary doesn't support --demangle. In addition, for OS X we need
- # to use the -f flag to get 'flat' nm output (otherwise we don't sort
- # properly and get incorrect results). Unfortunately, GNU nm uses -f
- # in an incompatible way. So first we test whether our nm supports
- # --demangle and -f.
- my $demangle_flag = "";
- my $cppfilt_flag = "";
- my $to_devnull = ">$dev_null 2>&1";
- if (system(ShellEscape($nm, "--demangle", "image") . $to_devnull) == 0) {
- # In this mode, we do "nm --demangle <foo>"
- $demangle_flag = "--demangle";
- $cppfilt_flag = "";
- } elsif (system(ShellEscape($cppfilt, $image) . $to_devnull) == 0) {
- # In this mode, we do "nm <foo> | c++filt"
- $cppfilt_flag = " | " . ShellEscape($cppfilt);
- };
- my $flatten_flag = "";
- if (system(ShellEscape($nm, "-f", $image) . $to_devnull) == 0) {
- $flatten_flag = "-f";
- }
-
- # Finally, in the case $imagie isn't a debug library, we try again with
- # -D to at least get *exported* symbols. If we can't use --demangle,
- # we use c++filt instead, if it exists on this system.
- my @nm_commands = (ShellEscape($nm, "-n", $flatten_flag, $demangle_flag,
- $image) . " 2>$dev_null $cppfilt_flag",
- ShellEscape($nm, "-D", "-n", $flatten_flag, $demangle_flag,
- $image) . " 2>$dev_null $cppfilt_flag",
- # 6nm is for Go binaries
- ShellEscape("6nm", "$image") . " 2>$dev_null | sort",
- );
-
- # If the executable is an MS Windows PDB-format executable, we'll
- # have set up obj_tool_map("nm_pdb"). In this case, we actually
- # want to use both unix nm and windows-specific nm_pdb, since
- # PDB-format executables can apparently include dwarf .o files.
- if (exists $obj_tool_map{"nm_pdb"}) {
- push(@nm_commands,
- ShellEscape($obj_tool_map{"nm_pdb"}, "--demangle", $image)
- . " 2>$dev_null");
- }
-
- foreach my $nm_command (@nm_commands) {
- my $symbol_table = GetProcedureBoundariesViaNm($nm_command, $regexp);
- return $symbol_table if (%{$symbol_table});
- }
- my $symbol_table = {};
- return $symbol_table;
-}
-
-
-# The test vectors for AddressAdd/Sub/Inc are 8-16-nibble hex strings.
-# To make them more readable, we add underscores at interesting places.
-# This routine removes the underscores, producing the canonical representation
-# used by jeprof to represent addresses, particularly in the tested routines.
-sub CanonicalHex {
- my $arg = shift;
- return join '', (split '_',$arg);
-}
-
-
-# Unit test for AddressAdd:
-sub AddressAddUnitTest {
- my $test_data_8 = shift;
- my $test_data_16 = shift;
- my $error_count = 0;
- my $fail_count = 0;
- my $pass_count = 0;
- # print STDERR "AddressAddUnitTest: ", 1+$#{$test_data_8}, " tests\n";
-
- # First a few 8-nibble addresses. Note that this implementation uses
- # plain old arithmetic, so a quick sanity check along with verifying what
- # happens to overflow (we want it to wrap):
- $address_length = 8;
- foreach my $row (@{$test_data_8}) {
- if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
- my $sum = AddressAdd ($row->[0], $row->[1]);
- if ($sum ne $row->[2]) {
- printf STDERR "ERROR: %s != %s + %s = %s\n", $sum,
- $row->[0], $row->[1], $row->[2];
- ++$fail_count;
- } else {
- ++$pass_count;
- }
- }
- printf STDERR "AddressAdd 32-bit tests: %d passes, %d failures\n",
- $pass_count, $fail_count;
- $error_count = $fail_count;
- $fail_count = 0;
- $pass_count = 0;
-
- # Now 16-nibble addresses.
- $address_length = 16;
- foreach my $row (@{$test_data_16}) {
- if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
- my $sum = AddressAdd (CanonicalHex($row->[0]), CanonicalHex($row->[1]));
- my $expected = join '', (split '_',$row->[2]);
- if ($sum ne CanonicalHex($row->[2])) {
- printf STDERR "ERROR: %s != %s + %s = %s\n", $sum,
- $row->[0], $row->[1], $row->[2];
- ++$fail_count;
- } else {
- ++$pass_count;
- }
- }
- printf STDERR "AddressAdd 64-bit tests: %d passes, %d failures\n",
- $pass_count, $fail_count;
- $error_count += $fail_count;
-
- return $error_count;
-}
-
-
-# Unit test for AddressSub:
-sub AddressSubUnitTest {
- my $test_data_8 = shift;
- my $test_data_16 = shift;
- my $error_count = 0;
- my $fail_count = 0;
- my $pass_count = 0;
- # print STDERR "AddressSubUnitTest: ", 1+$#{$test_data_8}, " tests\n";
-
- # First a few 8-nibble addresses. Note that this implementation uses
- # plain old arithmetic, so a quick sanity check along with verifying what
- # happens to overflow (we want it to wrap):
- $address_length = 8;
- foreach my $row (@{$test_data_8}) {
- if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
- my $sum = AddressSub ($row->[0], $row->[1]);
- if ($sum ne $row->[3]) {
- printf STDERR "ERROR: %s != %s - %s = %s\n", $sum,
- $row->[0], $row->[1], $row->[3];
- ++$fail_count;
- } else {
- ++$pass_count;
- }
- }
- printf STDERR "AddressSub 32-bit tests: %d passes, %d failures\n",
- $pass_count, $fail_count;
- $error_count = $fail_count;
- $fail_count = 0;
- $pass_count = 0;
-
- # Now 16-nibble addresses.
- $address_length = 16;
- foreach my $row (@{$test_data_16}) {
- if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
- my $sum = AddressSub (CanonicalHex($row->[0]), CanonicalHex($row->[1]));
- if ($sum ne CanonicalHex($row->[3])) {
- printf STDERR "ERROR: %s != %s - %s = %s\n", $sum,
- $row->[0], $row->[1], $row->[3];
- ++$fail_count;
- } else {
- ++$pass_count;
- }
- }
- printf STDERR "AddressSub 64-bit tests: %d passes, %d failures\n",
- $pass_count, $fail_count;
- $error_count += $fail_count;
-
- return $error_count;
-}
-
-
-# Unit test for AddressInc:
-sub AddressIncUnitTest {
- my $test_data_8 = shift;
- my $test_data_16 = shift;
- my $error_count = 0;
- my $fail_count = 0;
- my $pass_count = 0;
- # print STDERR "AddressIncUnitTest: ", 1+$#{$test_data_8}, " tests\n";
-
- # First a few 8-nibble addresses. Note that this implementation uses
- # plain old arithmetic, so a quick sanity check along with verifying what
- # happens to overflow (we want it to wrap):
- $address_length = 8;
- foreach my $row (@{$test_data_8}) {
- if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
- my $sum = AddressInc ($row->[0]);
- if ($sum ne $row->[4]) {
- printf STDERR "ERROR: %s != %s + 1 = %s\n", $sum,
- $row->[0], $row->[4];
- ++$fail_count;
- } else {
- ++$pass_count;
- }
- }
- printf STDERR "AddressInc 32-bit tests: %d passes, %d failures\n",
- $pass_count, $fail_count;
- $error_count = $fail_count;
- $fail_count = 0;
- $pass_count = 0;
-
- # Now 16-nibble addresses.
- $address_length = 16;
- foreach my $row (@{$test_data_16}) {
- if ($main::opt_debug and $main::opt_test) { print STDERR "@{$row}\n"; }
- my $sum = AddressInc (CanonicalHex($row->[0]));
- if ($sum ne CanonicalHex($row->[4])) {
- printf STDERR "ERROR: %s != %s + 1 = %s\n", $sum,
- $row->[0], $row->[4];
- ++$fail_count;
- } else {
- ++$pass_count;
- }
- }
- printf STDERR "AddressInc 64-bit tests: %d passes, %d failures\n",
- $pass_count, $fail_count;
- $error_count += $fail_count;
-
- return $error_count;
-}
-
-
-# Driver for unit tests.
-# Currently just the address add/subtract/increment routines for 64-bit.
-sub RunUnitTests {
- my $error_count = 0;
-
- # This is a list of tuples [a, b, a+b, a-b, a+1]
- my $unit_test_data_8 = [
- [qw(aaaaaaaa 50505050 fafafafa 5a5a5a5a aaaaaaab)],
- [qw(50505050 aaaaaaaa fafafafa a5a5a5a6 50505051)],
- [qw(ffffffff aaaaaaaa aaaaaaa9 55555555 00000000)],
- [qw(00000001 ffffffff 00000000 00000002 00000002)],
- [qw(00000001 fffffff0 fffffff1 00000011 00000002)],
- ];
- my $unit_test_data_16 = [
- # The implementation handles data in 7-nibble chunks, so those are the
- # interesting boundaries.
- [qw(aaaaaaaa 50505050
- 00_000000f_afafafa 00_0000005_a5a5a5a 00_000000a_aaaaaab)],
- [qw(50505050 aaaaaaaa
- 00_000000f_afafafa ff_ffffffa_5a5a5a6 00_0000005_0505051)],
- [qw(ffffffff aaaaaaaa
- 00_000001a_aaaaaa9 00_0000005_5555555 00_0000010_0000000)],
- [qw(00000001 ffffffff
- 00_0000010_0000000 ff_ffffff0_0000002 00_0000000_0000002)],
- [qw(00000001 fffffff0
- 00_000000f_ffffff1 ff_ffffff0_0000011 00_0000000_0000002)],
-
- [qw(00_a00000a_aaaaaaa 50505050
- 00_a00000f_afafafa 00_a000005_a5a5a5a 00_a00000a_aaaaaab)],
- [qw(0f_fff0005_0505050 aaaaaaaa
- 0f_fff000f_afafafa 0f_ffefffa_5a5a5a6 0f_fff0005_0505051)],
- [qw(00_000000f_fffffff 01_800000a_aaaaaaa
- 01_800001a_aaaaaa9 fe_8000005_5555555 00_0000010_0000000)],
- [qw(00_0000000_0000001 ff_fffffff_fffffff
- 00_0000000_0000000 00_0000000_0000002 00_0000000_0000002)],
- [qw(00_0000000_0000001 ff_fffffff_ffffff0
- ff_fffffff_ffffff1 00_0000000_0000011 00_0000000_0000002)],
- ];
-
- $error_count += AddressAddUnitTest($unit_test_data_8, $unit_test_data_16);
- $error_count += AddressSubUnitTest($unit_test_data_8, $unit_test_data_16);
- $error_count += AddressIncUnitTest($unit_test_data_8, $unit_test_data_16);
- if ($error_count > 0) {
- print STDERR $error_count, " errors: FAILED\n";
- } else {
- print STDERR "PASS\n";
- }
- exit ($error_count);
-}
diff --git a/memory/jemalloc/src/build-aux/config.guess b/memory/jemalloc/src/build-aux/config.guess
deleted file mode 100755
index 1f5c50c0d..000000000
--- a/memory/jemalloc/src/build-aux/config.guess
+++ /dev/null
@@ -1,1420 +0,0 @@
-#! /bin/sh
-# Attempt to guess a canonical system name.
-# Copyright 1992-2014 Free Software Foundation, Inc.
-
-timestamp='2014-03-23'
-
-# This file 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 to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that
-# program. This Exception is an additional permission under section 7
-# of the GNU General Public License, version 3 ("GPLv3").
-#
-# Originally written by Per Bothner.
-#
-# You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
-#
-# Please send patches with a ChangeLog entry to config-patches@gnu.org.
-
-
-me=`echo "$0" | sed -e 's,.*/,,'`
-
-usage="\
-Usage: $0 [OPTION]
-
-Output the configuration name of the system \`$me' is run on.
-
-Operation modes:
- -h, --help print this help, then exit
- -t, --time-stamp print date of last modification, then exit
- -v, --version print version number, then exit
-
-Report bugs and patches to <config-patches@gnu.org>."
-
-version="\
-GNU config.guess ($timestamp)
-
-Originally written by Per Bothner.
-Copyright 1992-2014 Free Software Foundation, Inc.
-
-This is free software; see the source for copying conditions. There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-
-help="
-Try \`$me --help' for more information."
-
-# Parse command line
-while test $# -gt 0 ; do
- case $1 in
- --time-stamp | --time* | -t )
- echo "$timestamp" ; exit ;;
- --version | -v )
- echo "$version" ; exit ;;
- --help | --h* | -h )
- echo "$usage"; exit ;;
- -- ) # Stop option processing
- shift; break ;;
- - ) # Use stdin as input.
- break ;;
- -* )
- echo "$me: invalid option $1$help" >&2
- exit 1 ;;
- * )
- break ;;
- esac
-done
-
-if test $# != 0; then
- echo "$me: too many arguments$help" >&2
- exit 1
-fi
-
-trap 'exit 1' 1 2 15
-
-# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
-# compiler to aid in system detection is discouraged as it requires
-# temporary files to be created and, as you can see below, it is a
-# headache to deal with in a portable fashion.
-
-# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
-# use `HOST_CC' if defined, but it is deprecated.
-
-# Portable tmp directory creation inspired by the Autoconf team.
-
-set_cc_for_build='
-trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
-trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
-: ${TMPDIR=/tmp} ;
- { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
- { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
- { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
- { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
-dummy=$tmp/dummy ;
-tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
-case $CC_FOR_BUILD,$HOST_CC,$CC in
- ,,) echo "int x;" > $dummy.c ;
- for c in cc gcc c89 c99 ; do
- if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
- CC_FOR_BUILD="$c"; break ;
- fi ;
- done ;
- if test x"$CC_FOR_BUILD" = x ; then
- CC_FOR_BUILD=no_compiler_found ;
- fi
- ;;
- ,,*) CC_FOR_BUILD=$CC ;;
- ,*,*) CC_FOR_BUILD=$HOST_CC ;;
-esac ; set_cc_for_build= ;'
-
-# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
-# (ghazi@noc.rutgers.edu 1994-08-24)
-if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
- PATH=$PATH:/.attbin ; export PATH
-fi
-
-UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
-UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
-UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown
-UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
-
-case "${UNAME_SYSTEM}" in
-Linux|GNU|GNU/*)
- # If the system lacks a compiler, then just pick glibc.
- # We could probably try harder.
- LIBC=gnu
-
- eval $set_cc_for_build
- cat <<-EOF > $dummy.c
- #include <features.h>
- #if defined(__UCLIBC__)
- LIBC=uclibc
- #elif defined(__dietlibc__)
- LIBC=dietlibc
- #else
- LIBC=gnu
- #endif
- EOF
- eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
- ;;
-esac
-
-# Note: order is significant - the case branches are not exclusive.
-
-case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
- *:NetBSD:*:*)
- # NetBSD (nbsd) targets should (where applicable) match one or
- # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,
- # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently
- # switched to ELF, *-*-netbsd* would select the old
- # object file format. This provides both forward
- # compatibility and a consistent mechanism for selecting the
- # object file format.
- #
- # Note: NetBSD doesn't particularly care about the vendor
- # portion of the name. We always set it to "unknown".
- sysctl="sysctl -n hw.machine_arch"
- UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
- /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
- case "${UNAME_MACHINE_ARCH}" in
- armeb) machine=armeb-unknown ;;
- arm*) machine=arm-unknown ;;
- sh3el) machine=shl-unknown ;;
- sh3eb) machine=sh-unknown ;;
- sh5el) machine=sh5le-unknown ;;
- *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
- esac
- # The Operating System including object format, if it has switched
- # to ELF recently, or will in the future.
- case "${UNAME_MACHINE_ARCH}" in
- arm*|i386|m68k|ns32k|sh3*|sparc|vax)
- eval $set_cc_for_build
- if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
- | grep -q __ELF__
- then
- # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
- # Return netbsd for either. FIX?
- os=netbsd
- else
- os=netbsdelf
- fi
- ;;
- *)
- os=netbsd
- ;;
- esac
- # The OS release
- # Debian GNU/NetBSD machines have a different userland, and
- # thus, need a distinct triplet. However, they do not need
- # kernel version information, so it can be replaced with a
- # suitable tag, in the style of linux-gnu.
- case "${UNAME_VERSION}" in
- Debian*)
- release='-gnu'
- ;;
- *)
- release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
- ;;
- esac
- # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
- # contains redundant information, the shorter form:
- # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
- echo "${machine}-${os}${release}"
- exit ;;
- *:Bitrig:*:*)
- UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
- echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE}
- exit ;;
- *:OpenBSD:*:*)
- UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
- echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
- exit ;;
- *:ekkoBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
- exit ;;
- *:SolidBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
- exit ;;
- macppc:MirBSD:*:*)
- echo powerpc-unknown-mirbsd${UNAME_RELEASE}
- exit ;;
- *:MirBSD:*:*)
- echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
- exit ;;
- alpha:OSF1:*:*)
- case $UNAME_RELEASE in
- *4.0)
- UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
- ;;
- *5.*)
- UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
- ;;
- esac
- # According to Compaq, /usr/sbin/psrinfo has been available on
- # OSF/1 and Tru64 systems produced since 1995. I hope that
- # covers most systems running today. This code pipes the CPU
- # types through head -n 1, so we only detect the type of CPU 0.
- ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1`
- case "$ALPHA_CPU_TYPE" in
- "EV4 (21064)")
- UNAME_MACHINE="alpha" ;;
- "EV4.5 (21064)")
- UNAME_MACHINE="alpha" ;;
- "LCA4 (21066/21068)")
- UNAME_MACHINE="alpha" ;;
- "EV5 (21164)")
- UNAME_MACHINE="alphaev5" ;;
- "EV5.6 (21164A)")
- UNAME_MACHINE="alphaev56" ;;
- "EV5.6 (21164PC)")
- UNAME_MACHINE="alphapca56" ;;
- "EV5.7 (21164PC)")
- UNAME_MACHINE="alphapca57" ;;
- "EV6 (21264)")
- UNAME_MACHINE="alphaev6" ;;
- "EV6.7 (21264A)")
- UNAME_MACHINE="alphaev67" ;;
- "EV6.8CB (21264C)")
- UNAME_MACHINE="alphaev68" ;;
- "EV6.8AL (21264B)")
- UNAME_MACHINE="alphaev68" ;;
- "EV6.8CX (21264D)")
- UNAME_MACHINE="alphaev68" ;;
- "EV6.9A (21264/EV69A)")
- UNAME_MACHINE="alphaev69" ;;
- "EV7 (21364)")
- UNAME_MACHINE="alphaev7" ;;
- "EV7.9 (21364A)")
- UNAME_MACHINE="alphaev79" ;;
- esac
- # A Pn.n version is a patched version.
- # A Vn.n version is a released version.
- # A Tn.n version is a released field test version.
- # A Xn.n version is an unreleased experimental baselevel.
- # 1.2 uses "1.2" for uname -r.
- echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
- # Reset EXIT trap before exiting to avoid spurious non-zero exit code.
- exitcode=$?
- trap '' 0
- exit $exitcode ;;
- Alpha\ *:Windows_NT*:*)
- # How do we know it's Interix rather than the generic POSIX subsystem?
- # Should we change UNAME_MACHINE based on the output of uname instead
- # of the specific Alpha model?
- echo alpha-pc-interix
- exit ;;
- 21064:Windows_NT:50:3)
- echo alpha-dec-winnt3.5
- exit ;;
- Amiga*:UNIX_System_V:4.0:*)
- echo m68k-unknown-sysv4
- exit ;;
- *:[Aa]miga[Oo][Ss]:*:*)
- echo ${UNAME_MACHINE}-unknown-amigaos
- exit ;;
- *:[Mm]orph[Oo][Ss]:*:*)
- echo ${UNAME_MACHINE}-unknown-morphos
- exit ;;
- *:OS/390:*:*)
- echo i370-ibm-openedition
- exit ;;
- *:z/VM:*:*)
- echo s390-ibm-zvmoe
- exit ;;
- *:OS400:*:*)
- echo powerpc-ibm-os400
- exit ;;
- arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
- echo arm-acorn-riscix${UNAME_RELEASE}
- exit ;;
- arm*:riscos:*:*|arm*:RISCOS:*:*)
- echo arm-unknown-riscos
- exit ;;
- SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
- echo hppa1.1-hitachi-hiuxmpp
- exit ;;
- Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
- # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
- if test "`(/bin/universe) 2>/dev/null`" = att ; then
- echo pyramid-pyramid-sysv3
- else
- echo pyramid-pyramid-bsd
- fi
- exit ;;
- NILE*:*:*:dcosx)
- echo pyramid-pyramid-svr4
- exit ;;
- DRS?6000:unix:4.0:6*)
- echo sparc-icl-nx6
- exit ;;
- DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
- case `/usr/bin/uname -p` in
- sparc) echo sparc-icl-nx7; exit ;;
- esac ;;
- s390x:SunOS:*:*)
- echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit ;;
- sun4H:SunOS:5.*:*)
- echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit ;;
- sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
- echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit ;;
- i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
- echo i386-pc-auroraux${UNAME_RELEASE}
- exit ;;
- i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
- eval $set_cc_for_build
- SUN_ARCH="i386"
- # If there is a compiler, see if it is configured for 64-bit objects.
- # Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
- # This test works for both compilers.
- if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
- if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
- (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
- grep IS_64BIT_ARCH >/dev/null
- then
- SUN_ARCH="x86_64"
- fi
- fi
- echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit ;;
- sun4*:SunOS:6*:*)
- # According to config.sub, this is the proper way to canonicalize
- # SunOS6. Hard to guess exactly what SunOS6 will be like, but
- # it's likely to be more like Solaris than SunOS4.
- echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit ;;
- sun4*:SunOS:*:*)
- case "`/usr/bin/arch -k`" in
- Series*|S4*)
- UNAME_RELEASE=`uname -v`
- ;;
- esac
- # Japanese Language versions have a version number like `4.1.3-JL'.
- echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
- exit ;;
- sun3*:SunOS:*:*)
- echo m68k-sun-sunos${UNAME_RELEASE}
- exit ;;
- sun*:*:4.2BSD:*)
- UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
- test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
- case "`/bin/arch`" in
- sun3)
- echo m68k-sun-sunos${UNAME_RELEASE}
- ;;
- sun4)
- echo sparc-sun-sunos${UNAME_RELEASE}
- ;;
- esac
- exit ;;
- aushp:SunOS:*:*)
- echo sparc-auspex-sunos${UNAME_RELEASE}
- exit ;;
- # The situation for MiNT is a little confusing. The machine name
- # can be virtually everything (everything which is not
- # "atarist" or "atariste" at least should have a processor
- # > m68000). The system name ranges from "MiNT" over "FreeMiNT"
- # to the lowercase version "mint" (or "freemint"). Finally
- # the system name "TOS" denotes a system which is actually not
- # MiNT. But MiNT is downward compatible to TOS, so this should
- # be no problem.
- atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit ;;
- atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit ;;
- *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
- echo m68k-atari-mint${UNAME_RELEASE}
- exit ;;
- milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
- echo m68k-milan-mint${UNAME_RELEASE}
- exit ;;
- hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
- echo m68k-hades-mint${UNAME_RELEASE}
- exit ;;
- *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
- echo m68k-unknown-mint${UNAME_RELEASE}
- exit ;;
- m68k:machten:*:*)
- echo m68k-apple-machten${UNAME_RELEASE}
- exit ;;
- powerpc:machten:*:*)
- echo powerpc-apple-machten${UNAME_RELEASE}
- exit ;;
- RISC*:Mach:*:*)
- echo mips-dec-mach_bsd4.3
- exit ;;
- RISC*:ULTRIX:*:*)
- echo mips-dec-ultrix${UNAME_RELEASE}
- exit ;;
- VAX*:ULTRIX*:*:*)
- echo vax-dec-ultrix${UNAME_RELEASE}
- exit ;;
- 2020:CLIX:*:* | 2430:CLIX:*:*)
- echo clipper-intergraph-clix${UNAME_RELEASE}
- exit ;;
- mips:*:*:UMIPS | mips:*:*:RISCos)
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
-#ifdef __cplusplus
-#include <stdio.h> /* for printf() prototype */
- int main (int argc, char *argv[]) {
-#else
- int main (argc, argv) int argc; char *argv[]; {
-#endif
- #if defined (host_mips) && defined (MIPSEB)
- #if defined (SYSTYPE_SYSV)
- printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
- #endif
- #if defined (SYSTYPE_SVR4)
- printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
- #endif
- #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
- printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
- #endif
- #endif
- exit (-1);
- }
-EOF
- $CC_FOR_BUILD -o $dummy $dummy.c &&
- dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
- SYSTEM_NAME=`$dummy $dummyarg` &&
- { echo "$SYSTEM_NAME"; exit; }
- echo mips-mips-riscos${UNAME_RELEASE}
- exit ;;
- Motorola:PowerMAX_OS:*:*)
- echo powerpc-motorola-powermax
- exit ;;
- Motorola:*:4.3:PL8-*)
- echo powerpc-harris-powermax
- exit ;;
- Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
- echo powerpc-harris-powermax
- exit ;;
- Night_Hawk:Power_UNIX:*:*)
- echo powerpc-harris-powerunix
- exit ;;
- m88k:CX/UX:7*:*)
- echo m88k-harris-cxux7
- exit ;;
- m88k:*:4*:R4*)
- echo m88k-motorola-sysv4
- exit ;;
- m88k:*:3*:R3*)
- echo m88k-motorola-sysv3
- exit ;;
- AViiON:dgux:*:*)
- # DG/UX returns AViiON for all architectures
- UNAME_PROCESSOR=`/usr/bin/uname -p`
- if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
- then
- if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
- [ ${TARGET_BINARY_INTERFACE}x = x ]
- then
- echo m88k-dg-dgux${UNAME_RELEASE}
- else
- echo m88k-dg-dguxbcs${UNAME_RELEASE}
- fi
- else
- echo i586-dg-dgux${UNAME_RELEASE}
- fi
- exit ;;
- M88*:DolphinOS:*:*) # DolphinOS (SVR3)
- echo m88k-dolphin-sysv3
- exit ;;
- M88*:*:R3*:*)
- # Delta 88k system running SVR3
- echo m88k-motorola-sysv3
- exit ;;
- XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
- echo m88k-tektronix-sysv3
- exit ;;
- Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
- echo m68k-tektronix-bsd
- exit ;;
- *:IRIX*:*:*)
- echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
- exit ;;
- ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
- echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id
- exit ;; # Note that: echo "'`uname -s`'" gives 'AIX '
- i*86:AIX:*:*)
- echo i386-ibm-aix
- exit ;;
- ia64:AIX:*:*)
- if [ -x /usr/bin/oslevel ] ; then
- IBM_REV=`/usr/bin/oslevel`
- else
- IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
- fi
- echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
- exit ;;
- *:AIX:2:3)
- if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
- #include <sys/systemcfg.h>
-
- main()
- {
- if (!__power_pc())
- exit(1);
- puts("powerpc-ibm-aix3.2.5");
- exit(0);
- }
-EOF
- if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
- then
- echo "$SYSTEM_NAME"
- else
- echo rs6000-ibm-aix3.2.5
- fi
- elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
- echo rs6000-ibm-aix3.2.4
- else
- echo rs6000-ibm-aix3.2
- fi
- exit ;;
- *:AIX:*:[4567])
- IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
- if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
- IBM_ARCH=rs6000
- else
- IBM_ARCH=powerpc
- fi
- if [ -x /usr/bin/oslevel ] ; then
- IBM_REV=`/usr/bin/oslevel`
- else
- IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
- fi
- echo ${IBM_ARCH}-ibm-aix${IBM_REV}
- exit ;;
- *:AIX:*:*)
- echo rs6000-ibm-aix
- exit ;;
- ibmrt:4.4BSD:*|romp-ibm:BSD:*)
- echo romp-ibm-bsd4.4
- exit ;;
- ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and
- echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to
- exit ;; # report: romp-ibm BSD 4.3
- *:BOSX:*:*)
- echo rs6000-bull-bosx
- exit ;;
- DPX/2?00:B.O.S.:*:*)
- echo m68k-bull-sysv3
- exit ;;
- 9000/[34]??:4.3bsd:1.*:*)
- echo m68k-hp-bsd
- exit ;;
- hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
- echo m68k-hp-bsd4.4
- exit ;;
- 9000/[34678]??:HP-UX:*:*)
- HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
- case "${UNAME_MACHINE}" in
- 9000/31? ) HP_ARCH=m68000 ;;
- 9000/[34]?? ) HP_ARCH=m68k ;;
- 9000/[678][0-9][0-9])
- if [ -x /usr/bin/getconf ]; then
- sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
- sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
- case "${sc_cpu_version}" in
- 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
- 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
- 532) # CPU_PA_RISC2_0
- case "${sc_kernel_bits}" in
- 32) HP_ARCH="hppa2.0n" ;;
- 64) HP_ARCH="hppa2.0w" ;;
- '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20
- esac ;;
- esac
- fi
- if [ "${HP_ARCH}" = "" ]; then
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
-
- #define _HPUX_SOURCE
- #include <stdlib.h>
- #include <unistd.h>
-
- int main ()
- {
- #if defined(_SC_KERNEL_BITS)
- long bits = sysconf(_SC_KERNEL_BITS);
- #endif
- long cpu = sysconf (_SC_CPU_VERSION);
-
- switch (cpu)
- {
- case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
- case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
- case CPU_PA_RISC2_0:
- #if defined(_SC_KERNEL_BITS)
- switch (bits)
- {
- case 64: puts ("hppa2.0w"); break;
- case 32: puts ("hppa2.0n"); break;
- default: puts ("hppa2.0"); break;
- } break;
- #else /* !defined(_SC_KERNEL_BITS) */
- puts ("hppa2.0"); break;
- #endif
- default: puts ("hppa1.0"); break;
- }
- exit (0);
- }
-EOF
- (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
- test -z "$HP_ARCH" && HP_ARCH=hppa
- fi ;;
- esac
- if [ ${HP_ARCH} = "hppa2.0w" ]
- then
- eval $set_cc_for_build
-
- # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
- # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler
- # generating 64-bit code. GNU and HP use different nomenclature:
- #
- # $ CC_FOR_BUILD=cc ./config.guess
- # => hppa2.0w-hp-hpux11.23
- # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
- # => hppa64-hp-hpux11.23
-
- if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
- grep -q __LP64__
- then
- HP_ARCH="hppa2.0w"
- else
- HP_ARCH="hppa64"
- fi
- fi
- echo ${HP_ARCH}-hp-hpux${HPUX_REV}
- exit ;;
- ia64:HP-UX:*:*)
- HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
- echo ia64-hp-hpux${HPUX_REV}
- exit ;;
- 3050*:HI-UX:*:*)
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
- #include <unistd.h>
- int
- main ()
- {
- long cpu = sysconf (_SC_CPU_VERSION);
- /* The order matters, because CPU_IS_HP_MC68K erroneously returns
- true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct
- results, however. */
- if (CPU_IS_PA_RISC (cpu))
- {
- switch (cpu)
- {
- case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
- case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
- case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
- default: puts ("hppa-hitachi-hiuxwe2"); break;
- }
- }
- else if (CPU_IS_HP_MC68K (cpu))
- puts ("m68k-hitachi-hiuxwe2");
- else puts ("unknown-hitachi-hiuxwe2");
- exit (0);
- }
-EOF
- $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
- { echo "$SYSTEM_NAME"; exit; }
- echo unknown-hitachi-hiuxwe2
- exit ;;
- 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
- echo hppa1.1-hp-bsd
- exit ;;
- 9000/8??:4.3bsd:*:*)
- echo hppa1.0-hp-bsd
- exit ;;
- *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
- echo hppa1.0-hp-mpeix
- exit ;;
- hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
- echo hppa1.1-hp-osf
- exit ;;
- hp8??:OSF1:*:*)
- echo hppa1.0-hp-osf
- exit ;;
- i*86:OSF1:*:*)
- if [ -x /usr/sbin/sysversion ] ; then
- echo ${UNAME_MACHINE}-unknown-osf1mk
- else
- echo ${UNAME_MACHINE}-unknown-osf1
- fi
- exit ;;
- parisc*:Lites*:*:*)
- echo hppa1.1-hp-lites
- exit ;;
- C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
- echo c1-convex-bsd
- exit ;;
- C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
- if getsysinfo -f scalar_acc
- then echo c32-convex-bsd
- else echo c2-convex-bsd
- fi
- exit ;;
- C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
- echo c34-convex-bsd
- exit ;;
- C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
- echo c38-convex-bsd
- exit ;;
- C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
- echo c4-convex-bsd
- exit ;;
- CRAY*Y-MP:*:*:*)
- echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit ;;
- CRAY*[A-Z]90:*:*:*)
- echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
- | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
- -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
- -e 's/\.[^.]*$/.X/'
- exit ;;
- CRAY*TS:*:*:*)
- echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit ;;
- CRAY*T3E:*:*:*)
- echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit ;;
- CRAY*SV1:*:*:*)
- echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit ;;
- *:UNICOS/mp:*:*)
- echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
- exit ;;
- F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
- FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
- FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
- FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
- echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
- exit ;;
- 5000:UNIX_System_V:4.*:*)
- FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
- FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
- echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
- exit ;;
- i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
- echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
- exit ;;
- sparc*:BSD/OS:*:*)
- echo sparc-unknown-bsdi${UNAME_RELEASE}
- exit ;;
- *:BSD/OS:*:*)
- echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
- exit ;;
- *:FreeBSD:*:*)
- UNAME_PROCESSOR=`/usr/bin/uname -p`
- case ${UNAME_PROCESSOR} in
- amd64)
- echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
- *)
- echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
- esac
- exit ;;
- i*:CYGWIN*:*)
- echo ${UNAME_MACHINE}-pc-cygwin
- exit ;;
- *:MINGW64*:*)
- echo ${UNAME_MACHINE}-pc-mingw64
- exit ;;
- *:MINGW*:*)
- echo ${UNAME_MACHINE}-pc-mingw32
- exit ;;
- *:MSYS*:*)
- echo ${UNAME_MACHINE}-pc-msys
- exit ;;
- i*:windows32*:*)
- # uname -m includes "-pc" on this system.
- echo ${UNAME_MACHINE}-mingw32
- exit ;;
- i*:PW*:*)
- echo ${UNAME_MACHINE}-pc-pw32
- exit ;;
- *:Interix*:*)
- case ${UNAME_MACHINE} in
- x86)
- echo i586-pc-interix${UNAME_RELEASE}
- exit ;;
- authenticamd | genuineintel | EM64T)
- echo x86_64-unknown-interix${UNAME_RELEASE}
- exit ;;
- IA64)
- echo ia64-unknown-interix${UNAME_RELEASE}
- exit ;;
- esac ;;
- [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
- echo i${UNAME_MACHINE}-pc-mks
- exit ;;
- 8664:Windows_NT:*)
- echo x86_64-pc-mks
- exit ;;
- i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
- # How do we know it's Interix rather than the generic POSIX subsystem?
- # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
- # UNAME_MACHINE based on the output of uname instead of i386?
- echo i586-pc-interix
- exit ;;
- i*:UWIN*:*)
- echo ${UNAME_MACHINE}-pc-uwin
- exit ;;
- amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
- echo x86_64-unknown-cygwin
- exit ;;
- p*:CYGWIN*:*)
- echo powerpcle-unknown-cygwin
- exit ;;
- prep*:SunOS:5.*:*)
- echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
- exit ;;
- *:GNU:*:*)
- # the GNU system
- echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
- exit ;;
- *:GNU/*:*:*)
- # other systems with GNU libc and userland
- echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
- exit ;;
- i*86:Minix:*:*)
- echo ${UNAME_MACHINE}-pc-minix
- exit ;;
- aarch64:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- aarch64_be:Linux:*:*)
- UNAME_MACHINE=aarch64_be
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- alpha:Linux:*:*)
- case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
- EV5) UNAME_MACHINE=alphaev5 ;;
- EV56) UNAME_MACHINE=alphaev56 ;;
- PCA56) UNAME_MACHINE=alphapca56 ;;
- PCA57) UNAME_MACHINE=alphapca56 ;;
- EV6) UNAME_MACHINE=alphaev6 ;;
- EV67) UNAME_MACHINE=alphaev67 ;;
- EV68*) UNAME_MACHINE=alphaev68 ;;
- esac
- objdump --private-headers /bin/sh | grep -q ld.so.1
- if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- arc:Linux:*:* | arceb:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- arm*:Linux:*:*)
- eval $set_cc_for_build
- if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
- | grep -q __ARM_EABI__
- then
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- else
- if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
- | grep -q __ARM_PCS_VFP
- then
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
- else
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
- fi
- fi
- exit ;;
- avr32*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- cris:Linux:*:*)
- echo ${UNAME_MACHINE}-axis-linux-${LIBC}
- exit ;;
- crisv32:Linux:*:*)
- echo ${UNAME_MACHINE}-axis-linux-${LIBC}
- exit ;;
- frv:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- hexagon:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- i*86:Linux:*:*)
- echo ${UNAME_MACHINE}-pc-linux-${LIBC}
- exit ;;
- ia64:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- m32r*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- m68*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- mips:Linux:*:* | mips64:Linux:*:*)
- eval $set_cc_for_build
- sed 's/^ //' << EOF >$dummy.c
- #undef CPU
- #undef ${UNAME_MACHINE}
- #undef ${UNAME_MACHINE}el
- #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
- CPU=${UNAME_MACHINE}el
- #else
- #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
- CPU=${UNAME_MACHINE}
- #else
- CPU=
- #endif
- #endif
-EOF
- eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
- test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
- ;;
- openrisc*:Linux:*:*)
- echo or1k-unknown-linux-${LIBC}
- exit ;;
- or32:Linux:*:* | or1k*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- padre:Linux:*:*)
- echo sparc-unknown-linux-${LIBC}
- exit ;;
- parisc64:Linux:*:* | hppa64:Linux:*:*)
- echo hppa64-unknown-linux-${LIBC}
- exit ;;
- parisc:Linux:*:* | hppa:Linux:*:*)
- # Look for CPU level
- case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
- PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
- PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
- *) echo hppa-unknown-linux-${LIBC} ;;
- esac
- exit ;;
- ppc64:Linux:*:*)
- echo powerpc64-unknown-linux-${LIBC}
- exit ;;
- ppc:Linux:*:*)
- echo powerpc-unknown-linux-${LIBC}
- exit ;;
- ppc64le:Linux:*:*)
- echo powerpc64le-unknown-linux-${LIBC}
- exit ;;
- ppcle:Linux:*:*)
- echo powerpcle-unknown-linux-${LIBC}
- exit ;;
- s390:Linux:*:* | s390x:Linux:*:*)
- echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
- exit ;;
- sh64*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- sh*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- sparc:Linux:*:* | sparc64:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- tile*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- vax:Linux:*:*)
- echo ${UNAME_MACHINE}-dec-linux-${LIBC}
- exit ;;
- x86_64:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- xtensa*:Linux:*:*)
- echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
- exit ;;
- i*86:DYNIX/ptx:4*:*)
- # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
- # earlier versions are messed up and put the nodename in both
- # sysname and nodename.
- echo i386-sequent-sysv4
- exit ;;
- i*86:UNIX_SV:4.2MP:2.*)
- # Unixware is an offshoot of SVR4, but it has its own version
- # number series starting with 2...
- # I am not positive that other SVR4 systems won't match this,
- # I just have to hope. -- rms.
- # Use sysv4.2uw... so that sysv4* matches it.
- echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
- exit ;;
- i*86:OS/2:*:*)
- # If we were able to find `uname', then EMX Unix compatibility
- # is probably installed.
- echo ${UNAME_MACHINE}-pc-os2-emx
- exit ;;
- i*86:XTS-300:*:STOP)
- echo ${UNAME_MACHINE}-unknown-stop
- exit ;;
- i*86:atheos:*:*)
- echo ${UNAME_MACHINE}-unknown-atheos
- exit ;;
- i*86:syllable:*:*)
- echo ${UNAME_MACHINE}-pc-syllable
- exit ;;
- i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
- echo i386-unknown-lynxos${UNAME_RELEASE}
- exit ;;
- i*86:*DOS:*:*)
- echo ${UNAME_MACHINE}-pc-msdosdjgpp
- exit ;;
- i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
- UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
- if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
- echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
- else
- echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
- fi
- exit ;;
- i*86:*:5:[678]*)
- # UnixWare 7.x, OpenUNIX and OpenServer 6.
- case `/bin/uname -X | grep "^Machine"` in
- *486*) UNAME_MACHINE=i486 ;;
- *Pentium) UNAME_MACHINE=i586 ;;
- *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
- esac
- echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
- exit ;;
- i*86:*:3.2:*)
- if test -f /usr/options/cb.name; then
- UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
- echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
- elif /bin/uname -X 2>/dev/null >/dev/null ; then
- UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
- (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
- (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
- && UNAME_MACHINE=i586
- (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
- && UNAME_MACHINE=i686
- (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
- && UNAME_MACHINE=i686
- echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
- else
- echo ${UNAME_MACHINE}-pc-sysv32
- fi
- exit ;;
- pc:*:*:*)
- # Left here for compatibility:
- # uname -m prints for DJGPP always 'pc', but it prints nothing about
- # the processor, so we play safe by assuming i586.
- # Note: whatever this is, it MUST be the same as what config.sub
- # prints for the "djgpp" host, or else GDB configury will decide that
- # this is a cross-build.
- echo i586-pc-msdosdjgpp
- exit ;;
- Intel:Mach:3*:*)
- echo i386-pc-mach3
- exit ;;
- paragon:*:*:*)
- echo i860-intel-osf1
- exit ;;
- i860:*:4.*:*) # i860-SVR4
- if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
- echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
- else # Add other i860-SVR4 vendors below as they are discovered.
- echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4
- fi
- exit ;;
- mini*:CTIX:SYS*5:*)
- # "miniframe"
- echo m68010-convergent-sysv
- exit ;;
- mc68k:UNIX:SYSTEM5:3.51m)
- echo m68k-convergent-sysv
- exit ;;
- M680?0:D-NIX:5.3:*)
- echo m68k-diab-dnix
- exit ;;
- M68*:*:R3V[5678]*:*)
- test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
- 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
- OS_REL=''
- test -r /etc/.relid \
- && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
- /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
- && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
- /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
- && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
- 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
- /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
- && { echo i486-ncr-sysv4; exit; } ;;
- NCR*:*:4.2:* | MPRAS*:*:4.2:*)
- OS_REL='.3'
- test -r /etc/.relid \
- && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
- /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
- && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
- /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
- && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
- /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
- && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
- m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
- echo m68k-unknown-lynxos${UNAME_RELEASE}
- exit ;;
- mc68030:UNIX_System_V:4.*:*)
- echo m68k-atari-sysv4
- exit ;;
- TSUNAMI:LynxOS:2.*:*)
- echo sparc-unknown-lynxos${UNAME_RELEASE}
- exit ;;
- rs6000:LynxOS:2.*:*)
- echo rs6000-unknown-lynxos${UNAME_RELEASE}
- exit ;;
- PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
- echo powerpc-unknown-lynxos${UNAME_RELEASE}
- exit ;;
- SM[BE]S:UNIX_SV:*:*)
- echo mips-dde-sysv${UNAME_RELEASE}
- exit ;;
- RM*:ReliantUNIX-*:*:*)
- echo mips-sni-sysv4
- exit ;;
- RM*:SINIX-*:*:*)
- echo mips-sni-sysv4
- exit ;;
- *:SINIX-*:*:*)
- if uname -p 2>/dev/null >/dev/null ; then
- UNAME_MACHINE=`(uname -p) 2>/dev/null`
- echo ${UNAME_MACHINE}-sni-sysv4
- else
- echo ns32k-sni-sysv
- fi
- exit ;;
- PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
- # says <Richard.M.Bartel@ccMail.Census.GOV>
- echo i586-unisys-sysv4
- exit ;;
- *:UNIX_System_V:4*:FTX*)
- # From Gerald Hewes <hewes@openmarket.com>.
- # How about differentiating between stratus architectures? -djm
- echo hppa1.1-stratus-sysv4
- exit ;;
- *:*:*:FTX*)
- # From seanf@swdc.stratus.com.
- echo i860-stratus-sysv4
- exit ;;
- i*86:VOS:*:*)
- # From Paul.Green@stratus.com.
- echo ${UNAME_MACHINE}-stratus-vos
- exit ;;
- *:VOS:*:*)
- # From Paul.Green@stratus.com.
- echo hppa1.1-stratus-vos
- exit ;;
- mc68*:A/UX:*:*)
- echo m68k-apple-aux${UNAME_RELEASE}
- exit ;;
- news*:NEWS-OS:6*:*)
- echo mips-sony-newsos6
- exit ;;
- R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
- if [ -d /usr/nec ]; then
- echo mips-nec-sysv${UNAME_RELEASE}
- else
- echo mips-unknown-sysv${UNAME_RELEASE}
- fi
- exit ;;
- BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only.
- echo powerpc-be-beos
- exit ;;
- BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only.
- echo powerpc-apple-beos
- exit ;;
- BePC:BeOS:*:*) # BeOS running on Intel PC compatible.
- echo i586-pc-beos
- exit ;;
- BePC:Haiku:*:*) # Haiku running on Intel PC compatible.
- echo i586-pc-haiku
- exit ;;
- x86_64:Haiku:*:*)
- echo x86_64-unknown-haiku
- exit ;;
- SX-4:SUPER-UX:*:*)
- echo sx4-nec-superux${UNAME_RELEASE}
- exit ;;
- SX-5:SUPER-UX:*:*)
- echo sx5-nec-superux${UNAME_RELEASE}
- exit ;;
- SX-6:SUPER-UX:*:*)
- echo sx6-nec-superux${UNAME_RELEASE}
- exit ;;
- SX-7:SUPER-UX:*:*)
- echo sx7-nec-superux${UNAME_RELEASE}
- exit ;;
- SX-8:SUPER-UX:*:*)
- echo sx8-nec-superux${UNAME_RELEASE}
- exit ;;
- SX-8R:SUPER-UX:*:*)
- echo sx8r-nec-superux${UNAME_RELEASE}
- exit ;;
- Power*:Rhapsody:*:*)
- echo powerpc-apple-rhapsody${UNAME_RELEASE}
- exit ;;
- *:Rhapsody:*:*)
- echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
- exit ;;
- *:Darwin:*:*)
- UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
- eval $set_cc_for_build
- if test "$UNAME_PROCESSOR" = unknown ; then
- UNAME_PROCESSOR=powerpc
- fi
- if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
- if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
- if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
- (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
- grep IS_64BIT_ARCH >/dev/null
- then
- case $UNAME_PROCESSOR in
- i386) UNAME_PROCESSOR=x86_64 ;;
- powerpc) UNAME_PROCESSOR=powerpc64 ;;
- esac
- fi
- fi
- elif test "$UNAME_PROCESSOR" = i386 ; then
- # Avoid executing cc on OS X 10.9, as it ships with a stub
- # that puts up a graphical alert prompting to install
- # developer tools. Any system running Mac OS X 10.7 or
- # later (Darwin 11 and later) is required to have a 64-bit
- # processor. This is not true of the ARM version of Darwin
- # that Apple uses in portable devices.
- UNAME_PROCESSOR=x86_64
- fi
- echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
- exit ;;
- *:procnto*:*:* | *:QNX:[0123456789]*:*)
- UNAME_PROCESSOR=`uname -p`
- if test "$UNAME_PROCESSOR" = "x86"; then
- UNAME_PROCESSOR=i386
- UNAME_MACHINE=pc
- fi
- echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
- exit ;;
- *:QNX:*:4*)
- echo i386-pc-qnx
- exit ;;
- NEO-?:NONSTOP_KERNEL:*:*)
- echo neo-tandem-nsk${UNAME_RELEASE}
- exit ;;
- NSE-*:NONSTOP_KERNEL:*:*)
- echo nse-tandem-nsk${UNAME_RELEASE}
- exit ;;
- NSR-?:NONSTOP_KERNEL:*:*)
- echo nsr-tandem-nsk${UNAME_RELEASE}
- exit ;;
- *:NonStop-UX:*:*)
- echo mips-compaq-nonstopux
- exit ;;
- BS2000:POSIX*:*:*)
- echo bs2000-siemens-sysv
- exit ;;
- DS/*:UNIX_System_V:*:*)
- echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
- exit ;;
- *:Plan9:*:*)
- # "uname -m" is not consistent, so use $cputype instead. 386
- # is converted to i386 for consistency with other x86
- # operating systems.
- if test "$cputype" = "386"; then
- UNAME_MACHINE=i386
- else
- UNAME_MACHINE="$cputype"
- fi
- echo ${UNAME_MACHINE}-unknown-plan9
- exit ;;
- *:TOPS-10:*:*)
- echo pdp10-unknown-tops10
- exit ;;
- *:TENEX:*:*)
- echo pdp10-unknown-tenex
- exit ;;
- KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
- echo pdp10-dec-tops20
- exit ;;
- XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
- echo pdp10-xkl-tops20
- exit ;;
- *:TOPS-20:*:*)
- echo pdp10-unknown-tops20
- exit ;;
- *:ITS:*:*)
- echo pdp10-unknown-its
- exit ;;
- SEI:*:*:SEIUX)
- echo mips-sei-seiux${UNAME_RELEASE}
- exit ;;
- *:DragonFly:*:*)
- echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
- exit ;;
- *:*VMS:*:*)
- UNAME_MACHINE=`(uname -p) 2>/dev/null`
- case "${UNAME_MACHINE}" in
- A*) echo alpha-dec-vms ; exit ;;
- I*) echo ia64-dec-vms ; exit ;;
- V*) echo vax-dec-vms ; exit ;;
- esac ;;
- *:XENIX:*:SysV)
- echo i386-pc-xenix
- exit ;;
- i*86:skyos:*:*)
- echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
- exit ;;
- i*86:rdos:*:*)
- echo ${UNAME_MACHINE}-pc-rdos
- exit ;;
- i*86:AROS:*:*)
- echo ${UNAME_MACHINE}-pc-aros
- exit ;;
- x86_64:VMkernel:*:*)
- echo ${UNAME_MACHINE}-unknown-esx
- exit ;;
-esac
-
-cat >&2 <<EOF
-$0: unable to guess system type
-
-This script, last modified $timestamp, has failed to recognize
-the operating system you are using. It is advised that you
-download the most up to date version of the config scripts from
-
- http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
-and
- http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
-
-If the version you run ($0) is already up to date, please
-send the following data and any information you think might be
-pertinent to <config-patches@gnu.org> in order to provide the needed
-information to handle your system.
-
-config.guess timestamp = $timestamp
-
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
-/bin/uname -X = `(/bin/uname -X) 2>/dev/null`
-
-hostinfo = `(hostinfo) 2>/dev/null`
-/bin/universe = `(/bin/universe) 2>/dev/null`
-/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null`
-/bin/arch = `(/bin/arch) 2>/dev/null`
-/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
-
-UNAME_MACHINE = ${UNAME_MACHINE}
-UNAME_RELEASE = ${UNAME_RELEASE}
-UNAME_SYSTEM = ${UNAME_SYSTEM}
-UNAME_VERSION = ${UNAME_VERSION}
-EOF
-
-exit 1
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "timestamp='"
-# time-stamp-format: "%:y-%02m-%02d"
-# time-stamp-end: "'"
-# End:
diff --git a/memory/jemalloc/src/build-aux/config.sub b/memory/jemalloc/src/build-aux/config.sub
deleted file mode 100755
index 0ccff7706..000000000
--- a/memory/jemalloc/src/build-aux/config.sub
+++ /dev/null
@@ -1,1797 +0,0 @@
-#! /bin/sh
-# Configuration validation subroutine script.
-# Copyright 1992-2014 Free Software Foundation, Inc.
-
-timestamp='2014-05-01'
-
-# This file 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 to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that
-# program. This Exception is an additional permission under section 7
-# of the GNU General Public License, version 3 ("GPLv3").
-
-
-# Please send patches with a ChangeLog entry to config-patches@gnu.org.
-#
-# Configuration subroutine to validate and canonicalize a configuration type.
-# Supply the specified configuration type as an argument.
-# If it is invalid, we print an error message on stderr and exit with code 1.
-# Otherwise, we print the canonical config type on stdout and succeed.
-
-# You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
-
-# This file is supposed to be the same for all GNU packages
-# and recognize all the CPU types, system types and aliases
-# that are meaningful with *any* GNU software.
-# Each package is responsible for reporting which valid configurations
-# it does not support. The user should be able to distinguish
-# a failure to support a valid configuration from a meaningless
-# configuration.
-
-# The goal of this file is to map all the various variations of a given
-# machine specification into a single specification in the form:
-# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
-# or in some cases, the newer four-part form:
-# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
-# It is wrong to echo any other type of specification.
-
-me=`echo "$0" | sed -e 's,.*/,,'`
-
-usage="\
-Usage: $0 [OPTION] CPU-MFR-OPSYS
- $0 [OPTION] ALIAS
-
-Canonicalize a configuration name.
-
-Operation modes:
- -h, --help print this help, then exit
- -t, --time-stamp print date of last modification, then exit
- -v, --version print version number, then exit
-
-Report bugs and patches to <config-patches@gnu.org>."
-
-version="\
-GNU config.sub ($timestamp)
-
-Copyright 1992-2014 Free Software Foundation, Inc.
-
-This is free software; see the source for copying conditions. There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
-
-help="
-Try \`$me --help' for more information."
-
-# Parse command line
-while test $# -gt 0 ; do
- case $1 in
- --time-stamp | --time* | -t )
- echo "$timestamp" ; exit ;;
- --version | -v )
- echo "$version" ; exit ;;
- --help | --h* | -h )
- echo "$usage"; exit ;;
- -- ) # Stop option processing
- shift; break ;;
- - ) # Use stdin as input.
- break ;;
- -* )
- echo "$me: invalid option $1$help"
- exit 1 ;;
-
- *local*)
- # First pass through any local machine types.
- echo $1
- exit ;;
-
- * )
- break ;;
- esac
-done
-
-case $# in
- 0) echo "$me: missing argument$help" >&2
- exit 1;;
- 1) ;;
- *) echo "$me: too many arguments$help" >&2
- exit 1;;
-esac
-
-# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
-# Here we must recognize all the valid KERNEL-OS combinations.
-maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
-case $maybe_os in
- nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
- linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
- knetbsd*-gnu* | netbsd*-gnu* | \
- kopensolaris*-gnu* | \
- storm-chaos* | os2-emx* | rtmk-nova*)
- os=-$maybe_os
- basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
- ;;
- android-linux)
- os=-linux-android
- basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
- ;;
- *)
- basic_machine=`echo $1 | sed 's/-[^-]*$//'`
- if [ $basic_machine != $1 ]
- then os=`echo $1 | sed 's/.*-/-/'`
- else os=; fi
- ;;
-esac
-
-### Let's recognize common machines as not being operating systems so
-### that things like config.sub decstation-3100 work. We also
-### recognize some manufacturers as not being operating systems, so we
-### can provide default operating systems below.
-case $os in
- -sun*os*)
- # Prevent following clause from handling this invalid input.
- ;;
- -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
- -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
- -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
- -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
- -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
- -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
- -apple | -axis | -knuth | -cray | -microblaze*)
- os=
- basic_machine=$1
- ;;
- -bluegene*)
- os=-cnk
- ;;
- -sim | -cisco | -oki | -wec | -winbond)
- os=
- basic_machine=$1
- ;;
- -scout)
- ;;
- -wrs)
- os=-vxworks
- basic_machine=$1
- ;;
- -chorusos*)
- os=-chorusos
- basic_machine=$1
- ;;
- -chorusrdb)
- os=-chorusrdb
- basic_machine=$1
- ;;
- -hiux*)
- os=-hiuxwe2
- ;;
- -sco6)
- os=-sco5v6
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco5)
- os=-sco3.2v5
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco4)
- os=-sco3.2v4
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco3.2.[4-9]*)
- os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco3.2v[4-9]*)
- # Don't forget version if it is 3.2v4 or newer.
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco5v6*)
- # Don't forget version if it is 3.2v4 or newer.
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -sco*)
- os=-sco3.2v2
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -udk*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -isc)
- os=-isc2.2
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -clix*)
- basic_machine=clipper-intergraph
- ;;
- -isc*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
- ;;
- -lynx*178)
- os=-lynxos178
- ;;
- -lynx*5)
- os=-lynxos5
- ;;
- -lynx*)
- os=-lynxos
- ;;
- -ptx*)
- basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
- ;;
- -windowsnt*)
- os=`echo $os | sed -e 's/windowsnt/winnt/'`
- ;;
- -psos*)
- os=-psos
- ;;
- -mint | -mint[0-9]*)
- basic_machine=m68k-atari
- os=-mint
- ;;
-esac
-
-# Decode aliases for certain CPU-COMPANY combinations.
-case $basic_machine in
- # Recognize the basic CPU types without company name.
- # Some are omitted here because they have special meanings below.
- 1750a | 580 \
- | a29k \
- | aarch64 | aarch64_be \
- | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
- | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
- | am33_2.0 \
- | arc | arceb \
- | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
- | avr | avr32 \
- | be32 | be64 \
- | bfin \
- | c4x | c8051 | clipper \
- | d10v | d30v | dlx | dsp16xx \
- | epiphany \
- | fido | fr30 | frv \
- | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
- | hexagon \
- | i370 | i860 | i960 | ia64 \
- | ip2k | iq2000 \
- | k1om \
- | le32 | le64 \
- | lm32 \
- | m32c | m32r | m32rle | m68000 | m68k | m88k \
- | maxq | mb | microblaze | microblazeel | mcore | mep | metag \
- | mips | mipsbe | mipseb | mipsel | mipsle \
- | mips16 \
- | mips64 | mips64el \
- | mips64octeon | mips64octeonel \
- | mips64orion | mips64orionel \
- | mips64r5900 | mips64r5900el \
- | mips64vr | mips64vrel \
- | mips64vr4100 | mips64vr4100el \
- | mips64vr4300 | mips64vr4300el \
- | mips64vr5000 | mips64vr5000el \
- | mips64vr5900 | mips64vr5900el \
- | mipsisa32 | mipsisa32el \
- | mipsisa32r2 | mipsisa32r2el \
- | mipsisa32r6 | mipsisa32r6el \
- | mipsisa64 | mipsisa64el \
- | mipsisa64r2 | mipsisa64r2el \
- | mipsisa64r6 | mipsisa64r6el \
- | mipsisa64sb1 | mipsisa64sb1el \
- | mipsisa64sr71k | mipsisa64sr71kel \
- | mipsr5900 | mipsr5900el \
- | mipstx39 | mipstx39el \
- | mn10200 | mn10300 \
- | moxie \
- | mt \
- | msp430 \
- | nds32 | nds32le | nds32be \
- | nios | nios2 | nios2eb | nios2el \
- | ns16k | ns32k \
- | open8 | or1k | or1knd | or32 \
- | pdp10 | pdp11 | pj | pjl \
- | powerpc | powerpc64 | powerpc64le | powerpcle \
- | pyramid \
- | rl78 | rx \
- | score \
- | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
- | sh64 | sh64le \
- | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
- | sparcv8 | sparcv9 | sparcv9b | sparcv9v \
- | spu \
- | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
- | ubicom32 \
- | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
- | we32k \
- | x86 | xc16x | xstormy16 | xtensa \
- | z8k | z80)
- basic_machine=$basic_machine-unknown
- ;;
- c54x)
- basic_machine=tic54x-unknown
- ;;
- c55x)
- basic_machine=tic55x-unknown
- ;;
- c6x)
- basic_machine=tic6x-unknown
- ;;
- m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
- basic_machine=$basic_machine-unknown
- os=-none
- ;;
- m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
- ;;
- ms1)
- basic_machine=mt-unknown
- ;;
-
- strongarm | thumb | xscale)
- basic_machine=arm-unknown
- ;;
- xgate)
- basic_machine=$basic_machine-unknown
- os=-none
- ;;
- xscaleeb)
- basic_machine=armeb-unknown
- ;;
-
- xscaleel)
- basic_machine=armel-unknown
- ;;
-
- # We use `pc' rather than `unknown'
- # because (1) that's what they normally are, and
- # (2) the word "unknown" tends to confuse beginning users.
- i*86 | x86_64)
- basic_machine=$basic_machine-pc
- ;;
- # Object if more than one company name word.
- *-*-*)
- echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
- exit 1
- ;;
- # Recognize the basic CPU types with company name.
- 580-* \
- | a29k-* \
- | aarch64-* | aarch64_be-* \
- | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
- | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
- | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
- | arm-* | armbe-* | armle-* | armeb-* | armv*-* \
- | avr-* | avr32-* \
- | be32-* | be64-* \
- | bfin-* | bs2000-* \
- | c[123]* | c30-* | [cjt]90-* | c4x-* \
- | c8051-* | clipper-* | craynv-* | cydra-* \
- | d10v-* | d30v-* | dlx-* \
- | elxsi-* \
- | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
- | h8300-* | h8500-* \
- | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
- | hexagon-* \
- | i*86-* | i860-* | i960-* | ia64-* \
- | ip2k-* | iq2000-* \
- | k1om-* \
- | le32-* | le64-* \
- | lm32-* \
- | m32c-* | m32r-* | m32rle-* \
- | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
- | m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
- | microblaze-* | microblazeel-* \
- | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
- | mips16-* \
- | mips64-* | mips64el-* \
- | mips64octeon-* | mips64octeonel-* \
- | mips64orion-* | mips64orionel-* \
- | mips64r5900-* | mips64r5900el-* \
- | mips64vr-* | mips64vrel-* \
- | mips64vr4100-* | mips64vr4100el-* \
- | mips64vr4300-* | mips64vr4300el-* \
- | mips64vr5000-* | mips64vr5000el-* \
- | mips64vr5900-* | mips64vr5900el-* \
- | mipsisa32-* | mipsisa32el-* \
- | mipsisa32r2-* | mipsisa32r2el-* \
- | mipsisa32r6-* | mipsisa32r6el-* \
- | mipsisa64-* | mipsisa64el-* \
- | mipsisa64r2-* | mipsisa64r2el-* \
- | mipsisa64r6-* | mipsisa64r6el-* \
- | mipsisa64sb1-* | mipsisa64sb1el-* \
- | mipsisa64sr71k-* | mipsisa64sr71kel-* \
- | mipsr5900-* | mipsr5900el-* \
- | mipstx39-* | mipstx39el-* \
- | mmix-* \
- | mt-* \
- | msp430-* \
- | nds32-* | nds32le-* | nds32be-* \
- | nios-* | nios2-* | nios2eb-* | nios2el-* \
- | none-* | np1-* | ns16k-* | ns32k-* \
- | open8-* \
- | or1k*-* \
- | orion-* \
- | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
- | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
- | pyramid-* \
- | rl78-* | romp-* | rs6000-* | rx-* \
- | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
- | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
- | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
- | sparclite-* \
- | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
- | tahoe-* \
- | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
- | tile*-* \
- | tron-* \
- | ubicom32-* \
- | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
- | vax-* \
- | we32k-* \
- | x86-* | x86_64-* | xc16x-* | xps100-* \
- | xstormy16-* | xtensa*-* \
- | ymp-* \
- | z8k-* | z80-*)
- ;;
- # Recognize the basic CPU types without company name, with glob match.
- xtensa*)
- basic_machine=$basic_machine-unknown
- ;;
- # Recognize the various machine names and aliases which stand
- # for a CPU type and a company and sometimes even an OS.
- 386bsd)
- basic_machine=i386-unknown
- os=-bsd
- ;;
- 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
- basic_machine=m68000-att
- ;;
- 3b*)
- basic_machine=we32k-att
- ;;
- a29khif)
- basic_machine=a29k-amd
- os=-udi
- ;;
- abacus)
- basic_machine=abacus-unknown
- ;;
- adobe68k)
- basic_machine=m68010-adobe
- os=-scout
- ;;
- alliant | fx80)
- basic_machine=fx80-alliant
- ;;
- altos | altos3068)
- basic_machine=m68k-altos
- ;;
- am29k)
- basic_machine=a29k-none
- os=-bsd
- ;;
- amd64)
- basic_machine=x86_64-pc
- ;;
- amd64-*)
- basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- amdahl)
- basic_machine=580-amdahl
- os=-sysv
- ;;
- amiga | amiga-*)
- basic_machine=m68k-unknown
- ;;
- amigaos | amigados)
- basic_machine=m68k-unknown
- os=-amigaos
- ;;
- amigaunix | amix)
- basic_machine=m68k-unknown
- os=-sysv4
- ;;
- apollo68)
- basic_machine=m68k-apollo
- os=-sysv
- ;;
- apollo68bsd)
- basic_machine=m68k-apollo
- os=-bsd
- ;;
- aros)
- basic_machine=i386-pc
- os=-aros
- ;;
- aux)
- basic_machine=m68k-apple
- os=-aux
- ;;
- balance)
- basic_machine=ns32k-sequent
- os=-dynix
- ;;
- blackfin)
- basic_machine=bfin-unknown
- os=-linux
- ;;
- blackfin-*)
- basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
- os=-linux
- ;;
- bluegene*)
- basic_machine=powerpc-ibm
- os=-cnk
- ;;
- c54x-*)
- basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- c55x-*)
- basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- c6x-*)
- basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- c90)
- basic_machine=c90-cray
- os=-unicos
- ;;
- cegcc)
- basic_machine=arm-unknown
- os=-cegcc
- ;;
- convex-c1)
- basic_machine=c1-convex
- os=-bsd
- ;;
- convex-c2)
- basic_machine=c2-convex
- os=-bsd
- ;;
- convex-c32)
- basic_machine=c32-convex
- os=-bsd
- ;;
- convex-c34)
- basic_machine=c34-convex
- os=-bsd
- ;;
- convex-c38)
- basic_machine=c38-convex
- os=-bsd
- ;;
- cray | j90)
- basic_machine=j90-cray
- os=-unicos
- ;;
- craynv)
- basic_machine=craynv-cray
- os=-unicosmp
- ;;
- cr16 | cr16-*)
- basic_machine=cr16-unknown
- os=-elf
- ;;
- crds | unos)
- basic_machine=m68k-crds
- ;;
- crisv32 | crisv32-* | etraxfs*)
- basic_machine=crisv32-axis
- ;;
- cris | cris-* | etrax*)
- basic_machine=cris-axis
- ;;
- crx)
- basic_machine=crx-unknown
- os=-elf
- ;;
- da30 | da30-*)
- basic_machine=m68k-da30
- ;;
- decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
- basic_machine=mips-dec
- ;;
- decsystem10* | dec10*)
- basic_machine=pdp10-dec
- os=-tops10
- ;;
- decsystem20* | dec20*)
- basic_machine=pdp10-dec
- os=-tops20
- ;;
- delta | 3300 | motorola-3300 | motorola-delta \
- | 3300-motorola | delta-motorola)
- basic_machine=m68k-motorola
- ;;
- delta88)
- basic_machine=m88k-motorola
- os=-sysv3
- ;;
- dicos)
- basic_machine=i686-pc
- os=-dicos
- ;;
- djgpp)
- basic_machine=i586-pc
- os=-msdosdjgpp
- ;;
- dpx20 | dpx20-*)
- basic_machine=rs6000-bull
- os=-bosx
- ;;
- dpx2* | dpx2*-bull)
- basic_machine=m68k-bull
- os=-sysv3
- ;;
- ebmon29k)
- basic_machine=a29k-amd
- os=-ebmon
- ;;
- elxsi)
- basic_machine=elxsi-elxsi
- os=-bsd
- ;;
- encore | umax | mmax)
- basic_machine=ns32k-encore
- ;;
- es1800 | OSE68k | ose68k | ose | OSE)
- basic_machine=m68k-ericsson
- os=-ose
- ;;
- fx2800)
- basic_machine=i860-alliant
- ;;
- genix)
- basic_machine=ns32k-ns
- ;;
- gmicro)
- basic_machine=tron-gmicro
- os=-sysv
- ;;
- go32)
- basic_machine=i386-pc
- os=-go32
- ;;
- h3050r* | hiux*)
- basic_machine=hppa1.1-hitachi
- os=-hiuxwe2
- ;;
- h8300hms)
- basic_machine=h8300-hitachi
- os=-hms
- ;;
- h8300xray)
- basic_machine=h8300-hitachi
- os=-xray
- ;;
- h8500hms)
- basic_machine=h8500-hitachi
- os=-hms
- ;;
- harris)
- basic_machine=m88k-harris
- os=-sysv3
- ;;
- hp300-*)
- basic_machine=m68k-hp
- ;;
- hp300bsd)
- basic_machine=m68k-hp
- os=-bsd
- ;;
- hp300hpux)
- basic_machine=m68k-hp
- os=-hpux
- ;;
- hp3k9[0-9][0-9] | hp9[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hp9k2[0-9][0-9] | hp9k31[0-9])
- basic_machine=m68000-hp
- ;;
- hp9k3[2-9][0-9])
- basic_machine=m68k-hp
- ;;
- hp9k6[0-9][0-9] | hp6[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hp9k7[0-79][0-9] | hp7[0-79][0-9])
- basic_machine=hppa1.1-hp
- ;;
- hp9k78[0-9] | hp78[0-9])
- # FIXME: really hppa2.0-hp
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
- # FIXME: really hppa2.0-hp
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[0-9][13679] | hp8[0-9][13679])
- basic_machine=hppa1.1-hp
- ;;
- hp9k8[0-9][0-9] | hp8[0-9][0-9])
- basic_machine=hppa1.0-hp
- ;;
- hppa-next)
- os=-nextstep3
- ;;
- hppaosf)
- basic_machine=hppa1.1-hp
- os=-osf
- ;;
- hppro)
- basic_machine=hppa1.1-hp
- os=-proelf
- ;;
- i370-ibm* | ibm*)
- basic_machine=i370-ibm
- ;;
- i*86v32)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv32
- ;;
- i*86v4*)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv4
- ;;
- i*86v)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-sysv
- ;;
- i*86sol2)
- basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
- os=-solaris2
- ;;
- i386mach)
- basic_machine=i386-mach
- os=-mach
- ;;
- i386-vsta | vsta)
- basic_machine=i386-unknown
- os=-vsta
- ;;
- iris | iris4d)
- basic_machine=mips-sgi
- case $os in
- -irix*)
- ;;
- *)
- os=-irix4
- ;;
- esac
- ;;
- isi68 | isi)
- basic_machine=m68k-isi
- os=-sysv
- ;;
- m68knommu)
- basic_machine=m68k-unknown
- os=-linux
- ;;
- m68knommu-*)
- basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
- os=-linux
- ;;
- m88k-omron*)
- basic_machine=m88k-omron
- ;;
- magnum | m3230)
- basic_machine=mips-mips
- os=-sysv
- ;;
- merlin)
- basic_machine=ns32k-utek
- os=-sysv
- ;;
- microblaze*)
- basic_machine=microblaze-xilinx
- ;;
- mingw64)
- basic_machine=x86_64-pc
- os=-mingw64
- ;;
- mingw32)
- basic_machine=i686-pc
- os=-mingw32
- ;;
- mingw32ce)
- basic_machine=arm-unknown
- os=-mingw32ce
- ;;
- miniframe)
- basic_machine=m68000-convergent
- ;;
- *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
- basic_machine=m68k-atari
- os=-mint
- ;;
- mips3*-*)
- basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
- ;;
- mips3*)
- basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
- ;;
- monitor)
- basic_machine=m68k-rom68k
- os=-coff
- ;;
- morphos)
- basic_machine=powerpc-unknown
- os=-morphos
- ;;
- msdos)
- basic_machine=i386-pc
- os=-msdos
- ;;
- ms1-*)
- basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
- ;;
- msys)
- basic_machine=i686-pc
- os=-msys
- ;;
- mvs)
- basic_machine=i370-ibm
- os=-mvs
- ;;
- nacl)
- basic_machine=le32-unknown
- os=-nacl
- ;;
- ncr3000)
- basic_machine=i486-ncr
- os=-sysv4
- ;;
- netbsd386)
- basic_machine=i386-unknown
- os=-netbsd
- ;;
- netwinder)
- basic_machine=armv4l-rebel
- os=-linux
- ;;
- news | news700 | news800 | news900)
- basic_machine=m68k-sony
- os=-newsos
- ;;
- news1000)
- basic_machine=m68030-sony
- os=-newsos
- ;;
- news-3600 | risc-news)
- basic_machine=mips-sony
- os=-newsos
- ;;
- necv70)
- basic_machine=v70-nec
- os=-sysv
- ;;
- next | m*-next )
- basic_machine=m68k-next
- case $os in
- -nextstep* )
- ;;
- -ns2*)
- os=-nextstep2
- ;;
- *)
- os=-nextstep3
- ;;
- esac
- ;;
- nh3000)
- basic_machine=m68k-harris
- os=-cxux
- ;;
- nh[45]000)
- basic_machine=m88k-harris
- os=-cxux
- ;;
- nindy960)
- basic_machine=i960-intel
- os=-nindy
- ;;
- mon960)
- basic_machine=i960-intel
- os=-mon960
- ;;
- nonstopux)
- basic_machine=mips-compaq
- os=-nonstopux
- ;;
- np1)
- basic_machine=np1-gould
- ;;
- neo-tandem)
- basic_machine=neo-tandem
- ;;
- nse-tandem)
- basic_machine=nse-tandem
- ;;
- nsr-tandem)
- basic_machine=nsr-tandem
- ;;
- op50n-* | op60c-*)
- basic_machine=hppa1.1-oki
- os=-proelf
- ;;
- openrisc | openrisc-*)
- basic_machine=or32-unknown
- ;;
- os400)
- basic_machine=powerpc-ibm
- os=-os400
- ;;
- OSE68000 | ose68000)
- basic_machine=m68000-ericsson
- os=-ose
- ;;
- os68k)
- basic_machine=m68k-none
- os=-os68k
- ;;
- pa-hitachi)
- basic_machine=hppa1.1-hitachi
- os=-hiuxwe2
- ;;
- paragon)
- basic_machine=i860-intel
- os=-osf
- ;;
- parisc)
- basic_machine=hppa-unknown
- os=-linux
- ;;
- parisc-*)
- basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
- os=-linux
- ;;
- pbd)
- basic_machine=sparc-tti
- ;;
- pbb)
- basic_machine=m68k-tti
- ;;
- pc532 | pc532-*)
- basic_machine=ns32k-pc532
- ;;
- pc98)
- basic_machine=i386-pc
- ;;
- pc98-*)
- basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentium | p5 | k5 | k6 | nexgen | viac3)
- basic_machine=i586-pc
- ;;
- pentiumpro | p6 | 6x86 | athlon | athlon_*)
- basic_machine=i686-pc
- ;;
- pentiumii | pentium2 | pentiumiii | pentium3)
- basic_machine=i686-pc
- ;;
- pentium4)
- basic_machine=i786-pc
- ;;
- pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
- basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentiumpro-* | p6-* | 6x86-* | athlon-*)
- basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
- basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pentium4-*)
- basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- pn)
- basic_machine=pn-gould
- ;;
- power) basic_machine=power-ibm
- ;;
- ppc | ppcbe) basic_machine=powerpc-unknown
- ;;
- ppc-* | ppcbe-*)
- basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ppcle | powerpclittle | ppc-le | powerpc-little)
- basic_machine=powerpcle-unknown
- ;;
- ppcle-* | powerpclittle-*)
- basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ppc64) basic_machine=powerpc64-unknown
- ;;
- ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ppc64le | powerpc64little | ppc64-le | powerpc64-little)
- basic_machine=powerpc64le-unknown
- ;;
- ppc64le-* | powerpc64little-*)
- basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- ps2)
- basic_machine=i386-ibm
- ;;
- pw32)
- basic_machine=i586-unknown
- os=-pw32
- ;;
- rdos | rdos64)
- basic_machine=x86_64-pc
- os=-rdos
- ;;
- rdos32)
- basic_machine=i386-pc
- os=-rdos
- ;;
- rom68k)
- basic_machine=m68k-rom68k
- os=-coff
- ;;
- rm[46]00)
- basic_machine=mips-siemens
- ;;
- rtpc | rtpc-*)
- basic_machine=romp-ibm
- ;;
- s390 | s390-*)
- basic_machine=s390-ibm
- ;;
- s390x | s390x-*)
- basic_machine=s390x-ibm
- ;;
- sa29200)
- basic_machine=a29k-amd
- os=-udi
- ;;
- sb1)
- basic_machine=mipsisa64sb1-unknown
- ;;
- sb1el)
- basic_machine=mipsisa64sb1el-unknown
- ;;
- sde)
- basic_machine=mipsisa32-sde
- os=-elf
- ;;
- sei)
- basic_machine=mips-sei
- os=-seiux
- ;;
- sequent)
- basic_machine=i386-sequent
- ;;
- sh)
- basic_machine=sh-hitachi
- os=-hms
- ;;
- sh5el)
- basic_machine=sh5le-unknown
- ;;
- sh64)
- basic_machine=sh64-unknown
- ;;
- sparclite-wrs | simso-wrs)
- basic_machine=sparclite-wrs
- os=-vxworks
- ;;
- sps7)
- basic_machine=m68k-bull
- os=-sysv2
- ;;
- spur)
- basic_machine=spur-unknown
- ;;
- st2000)
- basic_machine=m68k-tandem
- ;;
- stratus)
- basic_machine=i860-stratus
- os=-sysv4
- ;;
- strongarm-* | thumb-*)
- basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
- ;;
- sun2)
- basic_machine=m68000-sun
- ;;
- sun2os3)
- basic_machine=m68000-sun
- os=-sunos3
- ;;
- sun2os4)
- basic_machine=m68000-sun
- os=-sunos4
- ;;
- sun3os3)
- basic_machine=m68k-sun
- os=-sunos3
- ;;
- sun3os4)
- basic_machine=m68k-sun
- os=-sunos4
- ;;
- sun4os3)
- basic_machine=sparc-sun
- os=-sunos3
- ;;
- sun4os4)
- basic_machine=sparc-sun
- os=-sunos4
- ;;
- sun4sol2)
- basic_machine=sparc-sun
- os=-solaris2
- ;;
- sun3 | sun3-*)
- basic_machine=m68k-sun
- ;;
- sun4)
- basic_machine=sparc-sun
- ;;
- sun386 | sun386i | roadrunner)
- basic_machine=i386-sun
- ;;
- sv1)
- basic_machine=sv1-cray
- os=-unicos
- ;;
- symmetry)
- basic_machine=i386-sequent
- os=-dynix
- ;;
- t3e)
- basic_machine=alphaev5-cray
- os=-unicos
- ;;
- t90)
- basic_machine=t90-cray
- os=-unicos
- ;;
- tile*)
- basic_machine=$basic_machine-unknown
- os=-linux-gnu
- ;;
- tx39)
- basic_machine=mipstx39-unknown
- ;;
- tx39el)
- basic_machine=mipstx39el-unknown
- ;;
- toad1)
- basic_machine=pdp10-xkl
- os=-tops20
- ;;
- tower | tower-32)
- basic_machine=m68k-ncr
- ;;
- tpf)
- basic_machine=s390x-ibm
- os=-tpf
- ;;
- udi29k)
- basic_machine=a29k-amd
- os=-udi
- ;;
- ultra3)
- basic_machine=a29k-nyu
- os=-sym1
- ;;
- v810 | necv810)
- basic_machine=v810-nec
- os=-none
- ;;
- vaxv)
- basic_machine=vax-dec
- os=-sysv
- ;;
- vms)
- basic_machine=vax-dec
- os=-vms
- ;;
- vpp*|vx|vx-*)
- basic_machine=f301-fujitsu
- ;;
- vxworks960)
- basic_machine=i960-wrs
- os=-vxworks
- ;;
- vxworks68)
- basic_machine=m68k-wrs
- os=-vxworks
- ;;
- vxworks29k)
- basic_machine=a29k-wrs
- os=-vxworks
- ;;
- w65*)
- basic_machine=w65-wdc
- os=-none
- ;;
- w89k-*)
- basic_machine=hppa1.1-winbond
- os=-proelf
- ;;
- xbox)
- basic_machine=i686-pc
- os=-mingw32
- ;;
- xps | xps100)
- basic_machine=xps100-honeywell
- ;;
- xscale-* | xscalee[bl]-*)
- basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
- ;;
- ymp)
- basic_machine=ymp-cray
- os=-unicos
- ;;
- z8k-*-coff)
- basic_machine=z8k-unknown
- os=-sim
- ;;
- z80-*-coff)
- basic_machine=z80-unknown
- os=-sim
- ;;
- none)
- basic_machine=none-none
- os=-none
- ;;
-
-# Here we handle the default manufacturer of certain CPU types. It is in
-# some cases the only manufacturer, in others, it is the most popular.
- w89k)
- basic_machine=hppa1.1-winbond
- ;;
- op50n)
- basic_machine=hppa1.1-oki
- ;;
- op60c)
- basic_machine=hppa1.1-oki
- ;;
- romp)
- basic_machine=romp-ibm
- ;;
- mmix)
- basic_machine=mmix-knuth
- ;;
- rs6000)
- basic_machine=rs6000-ibm
- ;;
- vax)
- basic_machine=vax-dec
- ;;
- pdp10)
- # there are many clones, so DEC is not a safe bet
- basic_machine=pdp10-unknown
- ;;
- pdp11)
- basic_machine=pdp11-dec
- ;;
- we32k)
- basic_machine=we32k-att
- ;;
- sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
- basic_machine=sh-unknown
- ;;
- sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
- basic_machine=sparc-sun
- ;;
- cydra)
- basic_machine=cydra-cydrome
- ;;
- orion)
- basic_machine=orion-highlevel
- ;;
- orion105)
- basic_machine=clipper-highlevel
- ;;
- mac | mpw | mac-mpw)
- basic_machine=m68k-apple
- ;;
- pmac | pmac-mpw)
- basic_machine=powerpc-apple
- ;;
- *-unknown)
- # Make sure to match an already-canonicalized machine name.
- ;;
- *)
- echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
- exit 1
- ;;
-esac
-
-# Here we canonicalize certain aliases for manufacturers.
-case $basic_machine in
- *-digital*)
- basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
- ;;
- *-commodore*)
- basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
- ;;
- *)
- ;;
-esac
-
-# Decode manufacturer-specific aliases for certain operating systems.
-
-if [ x"$os" != x"" ]
-then
-case $os in
- # First match some system type aliases
- # that might get confused with valid system types.
- # -solaris* is a basic system type, with this one exception.
- -auroraux)
- os=-auroraux
- ;;
- -solaris1 | -solaris1.*)
- os=`echo $os | sed -e 's|solaris1|sunos4|'`
- ;;
- -solaris)
- os=-solaris2
- ;;
- -svr4*)
- os=-sysv4
- ;;
- -unixware*)
- os=-sysv4.2uw
- ;;
- -gnu/linux*)
- os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
- ;;
- # First accept the basic system types.
- # The portable systems comes first.
- # Each alternative MUST END IN A *, to match a version number.
- # -sysv* is not here because it comes later, after sysvr4.
- -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
- | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
- | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
- | -sym* | -kopensolaris* | -plan9* \
- | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
- | -aos* | -aros* \
- | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
- | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
- | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
- | -bitrig* | -openbsd* | -solidbsd* \
- | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
- | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
- | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
- | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
- | -chorusos* | -chorusrdb* | -cegcc* \
- | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
- | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
- | -linux-newlib* | -linux-musl* | -linux-uclibc* \
- | -uxpv* | -beos* | -mpeix* | -udk* \
- | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
- | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
- | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
- | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
- | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
- | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
- | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*)
- # Remember, each alternative MUST END IN *, to match a version number.
- ;;
- -qnx*)
- case $basic_machine in
- x86-* | i*86-*)
- ;;
- *)
- os=-nto$os
- ;;
- esac
- ;;
- -nto-qnx*)
- ;;
- -nto*)
- os=`echo $os | sed -e 's|nto|nto-qnx|'`
- ;;
- -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
- | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
- | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
- ;;
- -mac*)
- os=`echo $os | sed -e 's|mac|macos|'`
- ;;
- # Apple iOS
- -ios*)
- ;;
- -linux-dietlibc)
- os=-linux-dietlibc
- ;;
- -linux*)
- os=`echo $os | sed -e 's|linux|linux-gnu|'`
- ;;
- -sunos5*)
- os=`echo $os | sed -e 's|sunos5|solaris2|'`
- ;;
- -sunos6*)
- os=`echo $os | sed -e 's|sunos6|solaris3|'`
- ;;
- -opened*)
- os=-openedition
- ;;
- -os400*)
- os=-os400
- ;;
- -wince*)
- os=-wince
- ;;
- -osfrose*)
- os=-osfrose
- ;;
- -osf*)
- os=-osf
- ;;
- -utek*)
- os=-bsd
- ;;
- -dynix*)
- os=-bsd
- ;;
- -acis*)
- os=-aos
- ;;
- -atheos*)
- os=-atheos
- ;;
- -syllable*)
- os=-syllable
- ;;
- -386bsd)
- os=-bsd
- ;;
- -ctix* | -uts*)
- os=-sysv
- ;;
- -nova*)
- os=-rtmk-nova
- ;;
- -ns2 )
- os=-nextstep2
- ;;
- -nsk*)
- os=-nsk
- ;;
- # Preserve the version number of sinix5.
- -sinix5.*)
- os=`echo $os | sed -e 's|sinix|sysv|'`
- ;;
- -sinix*)
- os=-sysv4
- ;;
- -tpf*)
- os=-tpf
- ;;
- -triton*)
- os=-sysv3
- ;;
- -oss*)
- os=-sysv3
- ;;
- -svr4)
- os=-sysv4
- ;;
- -svr3)
- os=-sysv3
- ;;
- -sysvr4)
- os=-sysv4
- ;;
- # This must come after -sysvr4.
- -sysv*)
- ;;
- -ose*)
- os=-ose
- ;;
- -es1800*)
- os=-ose
- ;;
- -xenix)
- os=-xenix
- ;;
- -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
- os=-mint
- ;;
- -aros*)
- os=-aros
- ;;
- -zvmoe)
- os=-zvmoe
- ;;
- -dicos*)
- os=-dicos
- ;;
- -nacl*)
- ;;
- -none)
- ;;
- *)
- # Get rid of the `-' at the beginning of $os.
- os=`echo $os | sed 's/[^-]*-//'`
- echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
- exit 1
- ;;
-esac
-else
-
-# Here we handle the default operating systems that come with various machines.
-# The value should be what the vendor currently ships out the door with their
-# machine or put another way, the most popular os provided with the machine.
-
-# Note that if you're going to try to match "-MANUFACTURER" here (say,
-# "-sun"), then you have to tell the case statement up towards the top
-# that MANUFACTURER isn't an operating system. Otherwise, code above
-# will signal an error saying that MANUFACTURER isn't an operating
-# system, and we'll never get to this point.
-
-case $basic_machine in
- score-*)
- os=-elf
- ;;
- spu-*)
- os=-elf
- ;;
- *-acorn)
- os=-riscix1.2
- ;;
- arm*-rebel)
- os=-linux
- ;;
- arm*-semi)
- os=-aout
- ;;
- c4x-* | tic4x-*)
- os=-coff
- ;;
- c8051-*)
- os=-elf
- ;;
- hexagon-*)
- os=-elf
- ;;
- tic54x-*)
- os=-coff
- ;;
- tic55x-*)
- os=-coff
- ;;
- tic6x-*)
- os=-coff
- ;;
- # This must come before the *-dec entry.
- pdp10-*)
- os=-tops20
- ;;
- pdp11-*)
- os=-none
- ;;
- *-dec | vax-*)
- os=-ultrix4.2
- ;;
- m68*-apollo)
- os=-domain
- ;;
- i386-sun)
- os=-sunos4.0.2
- ;;
- m68000-sun)
- os=-sunos3
- ;;
- m68*-cisco)
- os=-aout
- ;;
- mep-*)
- os=-elf
- ;;
- mips*-cisco)
- os=-elf
- ;;
- mips*-*)
- os=-elf
- ;;
- or32-*)
- os=-coff
- ;;
- *-tti) # must be before sparc entry or we get the wrong os.
- os=-sysv3
- ;;
- sparc-* | *-sun)
- os=-sunos4.1.1
- ;;
- *-be)
- os=-beos
- ;;
- *-haiku)
- os=-haiku
- ;;
- *-ibm)
- os=-aix
- ;;
- *-knuth)
- os=-mmixware
- ;;
- *-wec)
- os=-proelf
- ;;
- *-winbond)
- os=-proelf
- ;;
- *-oki)
- os=-proelf
- ;;
- *-hp)
- os=-hpux
- ;;
- *-hitachi)
- os=-hiux
- ;;
- i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
- os=-sysv
- ;;
- *-cbm)
- os=-amigaos
- ;;
- *-dg)
- os=-dgux
- ;;
- *-dolphin)
- os=-sysv3
- ;;
- m68k-ccur)
- os=-rtu
- ;;
- m88k-omron*)
- os=-luna
- ;;
- *-next )
- os=-nextstep
- ;;
- *-sequent)
- os=-ptx
- ;;
- *-crds)
- os=-unos
- ;;
- *-ns)
- os=-genix
- ;;
- i370-*)
- os=-mvs
- ;;
- *-next)
- os=-nextstep3
- ;;
- *-gould)
- os=-sysv
- ;;
- *-highlevel)
- os=-bsd
- ;;
- *-encore)
- os=-bsd
- ;;
- *-sgi)
- os=-irix
- ;;
- *-siemens)
- os=-sysv4
- ;;
- *-masscomp)
- os=-rtu
- ;;
- f30[01]-fujitsu | f700-fujitsu)
- os=-uxpv
- ;;
- *-rom68k)
- os=-coff
- ;;
- *-*bug)
- os=-coff
- ;;
- *-apple)
- os=-macos
- ;;
- *-atari*)
- os=-mint
- ;;
- *)
- os=-none
- ;;
-esac
-fi
-
-# Here we handle the case where we know the os, and the CPU type, but not the
-# manufacturer. We pick the logical manufacturer.
-vendor=unknown
-case $basic_machine in
- *-unknown)
- case $os in
- -riscix*)
- vendor=acorn
- ;;
- -sunos*)
- vendor=sun
- ;;
- -cnk*|-aix*)
- vendor=ibm
- ;;
- -beos*)
- vendor=be
- ;;
- -hpux*)
- vendor=hp
- ;;
- -mpeix*)
- vendor=hp
- ;;
- -hiux*)
- vendor=hitachi
- ;;
- -unos*)
- vendor=crds
- ;;
- -dgux*)
- vendor=dg
- ;;
- -luna*)
- vendor=omron
- ;;
- -genix*)
- vendor=ns
- ;;
- -mvs* | -opened*)
- vendor=ibm
- ;;
- -os400*)
- vendor=ibm
- ;;
- -ptx*)
- vendor=sequent
- ;;
- -tpf*)
- vendor=ibm
- ;;
- -vxsim* | -vxworks* | -windiss*)
- vendor=wrs
- ;;
- -aux*)
- vendor=apple
- ;;
- -hms*)
- vendor=hitachi
- ;;
- -mpw* | -macos*)
- vendor=apple
- ;;
- -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
- vendor=atari
- ;;
- -vos*)
- vendor=stratus
- ;;
- esac
- basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
- ;;
-esac
-
-echo $basic_machine$os
-exit
-
-# Local variables:
-# eval: (add-hook 'write-file-hooks 'time-stamp)
-# time-stamp-start: "timestamp='"
-# time-stamp-format: "%:y-%02m-%02d"
-# time-stamp-end: "'"
-# End:
diff --git a/memory/jemalloc/src/build-aux/install-sh b/memory/jemalloc/src/build-aux/install-sh
deleted file mode 100755
index ebc66913e..000000000
--- a/memory/jemalloc/src/build-aux/install-sh
+++ /dev/null
@@ -1,250 +0,0 @@
-#! /bin/sh
-#
-# install - install a program, script, or datafile
-# This comes from X11R5 (mit/util/scripts/install.sh).
-#
-# Copyright 1991 by the Massachusetts Institute of Technology
-#
-# Permission to use, copy, modify, distribute, and sell this software and its
-# documentation for any purpose is hereby granted without fee, provided that
-# the above copyright notice appear in all copies and that both that
-# copyright notice and this permission notice appear in supporting
-# documentation, and that the name of M.I.T. not be used in advertising or
-# publicity pertaining to distribution of the software without specific,
-# written prior permission. M.I.T. makes no representations about the
-# suitability of this software for any purpose. It is provided "as is"
-# without express or implied warranty.
-#
-# Calling this script install-sh is preferred over install.sh, to prevent
-# `make' implicit rules from creating a file called install from it
-# when there is no Makefile.
-#
-# This script is compatible with the BSD install script, but was written
-# from scratch. It can only install one file at a time, a restriction
-# shared with many OS's install programs.
-
-
-# set DOITPROG to echo to test this script
-
-# Don't use :- since 4.3BSD and earlier shells don't like it.
-doit="${DOITPROG-}"
-
-
-# put in absolute paths if you don't have them in your path; or use env. vars.
-
-mvprog="${MVPROG-mv}"
-cpprog="${CPPROG-cp}"
-chmodprog="${CHMODPROG-chmod}"
-chownprog="${CHOWNPROG-chown}"
-chgrpprog="${CHGRPPROG-chgrp}"
-stripprog="${STRIPPROG-strip}"
-rmprog="${RMPROG-rm}"
-mkdirprog="${MKDIRPROG-mkdir}"
-
-transformbasename=""
-transform_arg=""
-instcmd="$mvprog"
-chmodcmd="$chmodprog 0755"
-chowncmd=""
-chgrpcmd=""
-stripcmd=""
-rmcmd="$rmprog -f"
-mvcmd="$mvprog"
-src=""
-dst=""
-dir_arg=""
-
-while [ x"$1" != x ]; do
- case $1 in
- -c) instcmd="$cpprog"
- shift
- continue;;
-
- -d) dir_arg=true
- shift
- continue;;
-
- -m) chmodcmd="$chmodprog $2"
- shift
- shift
- continue;;
-
- -o) chowncmd="$chownprog $2"
- shift
- shift
- continue;;
-
- -g) chgrpcmd="$chgrpprog $2"
- shift
- shift
- continue;;
-
- -s) stripcmd="$stripprog"
- shift
- continue;;
-
- -t=*) transformarg=`echo $1 | sed 's/-t=//'`
- shift
- continue;;
-
- -b=*) transformbasename=`echo $1 | sed 's/-b=//'`
- shift
- continue;;
-
- *) if [ x"$src" = x ]
- then
- src=$1
- else
- # this colon is to work around a 386BSD /bin/sh bug
- :
- dst=$1
- fi
- shift
- continue;;
- esac
-done
-
-if [ x"$src" = x ]
-then
- echo "install: no input file specified"
- exit 1
-else
- true
-fi
-
-if [ x"$dir_arg" != x ]; then
- dst=$src
- src=""
-
- if [ -d $dst ]; then
- instcmd=:
- else
- instcmd=mkdir
- fi
-else
-
-# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
-# might cause directories to be created, which would be especially bad
-# if $src (and thus $dsttmp) contains '*'.
-
- if [ -f $src -o -d $src ]
- then
- true
- else
- echo "install: $src does not exist"
- exit 1
- fi
-
- if [ x"$dst" = x ]
- then
- echo "install: no destination specified"
- exit 1
- else
- true
- fi
-
-# If destination is a directory, append the input filename; if your system
-# does not like double slashes in filenames, you may need to add some logic
-
- if [ -d $dst ]
- then
- dst="$dst"/`basename $src`
- else
- true
- fi
-fi
-
-## this sed command emulates the dirname command
-dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
-
-# Make sure that the destination directory exists.
-# this part is taken from Noah Friedman's mkinstalldirs script
-
-# Skip lots of stat calls in the usual case.
-if [ ! -d "$dstdir" ]; then
-defaultIFS='
-'
-IFS="${IFS-${defaultIFS}}"
-
-oIFS="${IFS}"
-# Some sh's can't handle IFS=/ for some reason.
-IFS='%'
-set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
-IFS="${oIFS}"
-
-pathcomp=''
-
-while [ $# -ne 0 ] ; do
- pathcomp="${pathcomp}${1}"
- shift
-
- if [ ! -d "${pathcomp}" ] ;
- then
- $mkdirprog "${pathcomp}"
- else
- true
- fi
-
- pathcomp="${pathcomp}/"
-done
-fi
-
-if [ x"$dir_arg" != x ]
-then
- $doit $instcmd $dst &&
-
- if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
- if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
- if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
- if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
-else
-
-# If we're going to rename the final executable, determine the name now.
-
- if [ x"$transformarg" = x ]
- then
- dstfile=`basename $dst`
- else
- dstfile=`basename $dst $transformbasename |
- sed $transformarg`$transformbasename
- fi
-
-# don't allow the sed command to completely eliminate the filename
-
- if [ x"$dstfile" = x ]
- then
- dstfile=`basename $dst`
- else
- true
- fi
-
-# Make a temp file name in the proper directory.
-
- dsttmp=$dstdir/#inst.$$#
-
-# Move or copy the file name to the temp name
-
- $doit $instcmd $src $dsttmp &&
-
- trap "rm -f ${dsttmp}" 0 &&
-
-# and set any options; do chmod last to preserve setuid bits
-
-# If any of these fail, we abort the whole thing. If we want to
-# ignore errors from any of these, just make sure not to ignore
-# errors from the above "$doit $instcmd $src $dsttmp" command.
-
- if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
- if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
- if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
- if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
-
-# Now rename the file to the real destination.
-
- $doit $rmcmd -f $dstdir/$dstfile &&
- $doit $mvcmd $dsttmp $dstdir/$dstfile
-
-fi &&
-
-
-exit 0
diff --git a/memory/jemalloc/src/config.stamp.in b/memory/jemalloc/src/config.stamp.in
deleted file mode 100644
index e69de29bb..000000000
--- a/memory/jemalloc/src/config.stamp.in
+++ /dev/null
diff --git a/memory/jemalloc/src/configure b/memory/jemalloc/src/configure
deleted file mode 100755
index 2ad9b5a87..000000000
--- a/memory/jemalloc/src/configure
+++ /dev/null
@@ -1,10773 +0,0 @@
-#! /bin/sh
-# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69.
-#
-#
-# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
-#
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
- emulate sh
- NULLCMD=:
- # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
- # is contrary to our usage. Disable this feature.
- alias -g '${1+"$@"}'='"$@"'
- setopt NO_GLOB_SUBST
-else
- case `(set -o) 2>/dev/null` in #(
- *posix*) :
- set -o posix ;; #(
- *) :
- ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
- && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
- as_echo='print -r --'
- as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
- as_echo='printf %s\n'
- as_echo_n='printf %s'
-else
- if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
- as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
- as_echo_n='/usr/ucb/echo -n'
- else
- as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
- as_echo_n_body='eval
- arg=$1;
- case $arg in #(
- *"$as_nl"*)
- expr "X$arg" : "X\\(.*\\)$as_nl";
- arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
- esac;
- expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
- '
- export as_echo_n_body
- as_echo_n='sh -c $as_echo_n_body as_echo'
- fi
- export as_echo_body
- as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
- PATH_SEPARATOR=:
- (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
- (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
- PATH_SEPARATOR=';'
- }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order. Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" "" $as_nl"
-
-# Find who we are. Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
- *[\\/]* ) as_myself=$0 ;;
- *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
- done
-IFS=$as_save_IFS
-
- ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
- as_myself=$0
-fi
-if test ! -f "$as_myself"; then
- $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
- exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there. '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
- && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-# Use a proper internal environment variable to ensure we don't fall
- # into an infinite loop, continuously re-executing ourselves.
- if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
- _as_can_reexec=no; export _as_can_reexec;
- # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
- *v*x* | *x*v* ) as_opts=-vx ;;
- *v* ) as_opts=-v ;;
- *x* ) as_opts=-x ;;
- * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-as_fn_exit 255
- fi
- # We don't want this to propagate to other subprocesses.
- { _as_can_reexec=; unset _as_can_reexec;}
-if test "x$CONFIG_SHELL" = x; then
- as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
- emulate sh
- NULLCMD=:
- # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
- # is contrary to our usage. Disable this feature.
- alias -g '\${1+\"\$@\"}'='\"\$@\"'
- setopt NO_GLOB_SUBST
-else
- case \`(set -o) 2>/dev/null\` in #(
- *posix*) :
- set -o posix ;; #(
- *) :
- ;;
-esac
-fi
-"
- as_required="as_fn_return () { (exit \$1); }
-as_fn_success () { as_fn_return 0; }
-as_fn_failure () { as_fn_return 1; }
-as_fn_ret_success () { return 0; }
-as_fn_ret_failure () { return 1; }
-
-exitcode=0
-as_fn_success || { exitcode=1; echo as_fn_success failed.; }
-as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
-as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
-as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
-if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
-
-else
- exitcode=1; echo positional parameters were not saved.
-fi
-test x\$exitcode = x0 || exit 1
-test -x / || exit 1"
- as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
- as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
- eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
- test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
-test \$(( 1 + 1 )) = 2 || exit 1"
- if (eval "$as_required") 2>/dev/null; then :
- as_have_required=yes
-else
- as_have_required=no
-fi
- if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
-
-else
- as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-as_found=false
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- as_found=:
- case $as_dir in #(
- /*)
- for as_base in sh bash ksh sh5; do
- # Try only shells that exist, to save several forks.
- as_shell=$as_dir/$as_base
- if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
- { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
- CONFIG_SHELL=$as_shell as_have_required=yes
- if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
- break 2
-fi
-fi
- done;;
- esac
- as_found=false
-done
-$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
- { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
- CONFIG_SHELL=$SHELL as_have_required=yes
-fi; }
-IFS=$as_save_IFS
-
-
- if test "x$CONFIG_SHELL" != x; then :
- export CONFIG_SHELL
- # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
- *v*x* | *x*v* ) as_opts=-vx ;;
- *v* ) as_opts=-v ;;
- *x* ) as_opts=-x ;;
- * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-exit 255
-fi
-
- if test x$as_have_required = xno; then :
- $as_echo "$0: This script requires a shell more modern than all"
- $as_echo "$0: the shells that I found on your system."
- if test x${ZSH_VERSION+set} = xset ; then
- $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
- $as_echo "$0: be upgraded to zsh 4.3.4 or later."
- else
- $as_echo "$0: Please tell bug-autoconf@gnu.org about your system,
-$0: including any error possibly output before this
-$0: message. Then install a modern shell, or manually run
-$0: the script under such a shell if you do have one."
- fi
- exit 1
-fi
-fi
-fi
-SHELL=${CONFIG_SHELL-/bin/sh}
-export SHELL
-# Unset more variables known to interfere with behavior of common tools.
-CLICOLOR_FORCE= GREP_OPTIONS=
-unset CLICOLOR_FORCE GREP_OPTIONS
-
-## --------------------- ##
-## M4sh Shell Functions. ##
-## --------------------- ##
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
- { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
- return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
- set +e
- as_fn_set_status $1
- exit $1
-} # as_fn_exit
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
- case $as_dir in #(
- -*) as_dir=./$as_dir;;
- esac
- test -d "$as_dir" || eval $as_mkdir_p || {
- as_dirs=
- while :; do
- case $as_dir in #(
- *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
- *) as_qdir=$as_dir;;
- esac
- as_dirs="'$as_qdir' $as_dirs"
- as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$as_dir" : 'X\(//\)[^/]' \| \
- X"$as_dir" : 'X\(//\)$' \| \
- X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- test -d "$as_dir" && break
- done
- test -z "$as_dirs" || eval "mkdir $as_dirs"
- } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
- test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
- eval 'as_fn_append ()
- {
- eval $1+=\$2
- }'
-else
- as_fn_append ()
- {
- eval $1=\$$1\$2
- }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
- eval 'as_fn_arith ()
- {
- as_val=$(( $* ))
- }'
-else
- as_fn_arith ()
- {
- as_val=`expr "$@" || test $? -eq 1`
- }
-fi # as_fn_arith
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
- as_status=$1; test $as_status -eq 0 && as_status=1
- if test "$4"; then
- as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
- fi
- $as_echo "$as_me: error: $2" >&2
- as_fn_exit $as_status
-} # as_fn_error
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
- test "X`expr 00001 : '.*\(...\)'`" = X001; then
- as_expr=expr
-else
- as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
- as_basename=basename
-else
- as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
- as_dirname=dirname
-else
- as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
- X"$0" : 'X\(//\)$' \| \
- X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
- sed '/^.*\/\([^/][^/]*\)\/*$/{
- s//\1/
- q
- }
- /^X\/\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\/\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-
- as_lineno_1=$LINENO as_lineno_1a=$LINENO
- as_lineno_2=$LINENO as_lineno_2a=$LINENO
- eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
- test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
- # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-)
- sed -n '
- p
- /[$]LINENO/=
- ' <$as_myself |
- sed '
- s/[$]LINENO.*/&-/
- t lineno
- b
- :lineno
- N
- :loop
- s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
- t loop
- s/-\n.*//
- ' >$as_me.lineno &&
- chmod +x "$as_me.lineno" ||
- { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
-
- # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
- # already done that, so ensure we don't try to do so again and fall
- # in an infinite loop. This has already happened in practice.
- _as_can_reexec=no; export _as_can_reexec
- # Don't try to exec as it changes $[0], causing all sort of problems
- # (the dirname of $[0] is not the place where we might find the
- # original and so on. Autoconf is especially sensitive to this).
- . "./$as_me.lineno"
- # Exit status is that of the last command.
- exit
-}
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
- case `echo 'xy\c'` in
- *c*) ECHO_T=' ';; # ECHO_T is single tab character.
- xy) ECHO_C='\c';;
- *) echo `echo ksh88 bug on AIX 6.1` > /dev/null
- ECHO_T=' ';;
- esac;;
-*)
- ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
- rm -f conf$$.dir/conf$$.file
-else
- rm -f conf$$.dir
- mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
- if ln -s conf$$.file conf$$ 2>/dev/null; then
- as_ln_s='ln -s'
- # ... but there are two gotchas:
- # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
- # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
- # In both cases, we have to default to `cp -pR'.
- ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
- as_ln_s='cp -pR'
- elif ln conf$$.file conf$$ 2>/dev/null; then
- as_ln_s=ln
- else
- as_ln_s='cp -pR'
- fi
-else
- as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-if mkdir -p . 2>/dev/null; then
- as_mkdir_p='mkdir -p "$as_dir"'
-else
- test -d ./-p && rmdir ./-p
- as_mkdir_p=false
-fi
-
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-test -n "$DJDIR" || exec 7<&0 </dev/null
-exec 6>&1
-
-# Name of the host.
-# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
-# so uname gets run too.
-ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
-
-#
-# Initializations.
-#
-ac_default_prefix=/usr/local
-ac_clean_files=
-ac_config_libobj_dir=.
-LIBOBJS=
-cross_compiling=no
-subdirs=
-MFLAGS=
-MAKEFLAGS=
-
-# Identity of this package.
-PACKAGE_NAME=
-PACKAGE_TARNAME=
-PACKAGE_VERSION=
-PACKAGE_STRING=
-PACKAGE_BUGREPORT=
-PACKAGE_URL=
-
-ac_unique_file="Makefile.in"
-# Factoring default headers for most tests.
-ac_includes_default="\
-#include <stdio.h>
-#ifdef HAVE_SYS_TYPES_H
-# include <sys/types.h>
-#endif
-#ifdef HAVE_SYS_STAT_H
-# include <sys/stat.h>
-#endif
-#ifdef STDC_HEADERS
-# include <stdlib.h>
-# include <stddef.h>
-#else
-# ifdef HAVE_STDLIB_H
-# include <stdlib.h>
-# endif
-#endif
-#ifdef HAVE_STRING_H
-# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
-# include <memory.h>
-# endif
-# include <string.h>
-#endif
-#ifdef HAVE_STRINGS_H
-# include <strings.h>
-#endif
-#ifdef HAVE_INTTYPES_H
-# include <inttypes.h>
-#endif
-#ifdef HAVE_STDINT_H
-# include <stdint.h>
-#endif
-#ifdef HAVE_UNISTD_H
-# include <unistd.h>
-#endif"
-
-ac_subst_vars='LTLIBOBJS
-LIBOBJS
-cfgoutputs_out
-cfgoutputs_in
-cfghdrs_out
-cfghdrs_in
-enable_zone_allocator
-enable_tls
-enable_lazy_lock
-jemalloc_version_gid
-jemalloc_version_nrev
-jemalloc_version_bugfix
-jemalloc_version_minor
-jemalloc_version_major
-jemalloc_version
-enable_cache_oblivious
-enable_xmalloc
-enable_valgrind
-enable_utrace
-enable_fill
-enable_munmap
-enable_tcache
-enable_prof
-enable_stats
-enable_debug
-je_
-install_suffix
-private_namespace
-JEMALLOC_CPREFIX
-enable_code_coverage
-AUTOCONF
-LD
-RANLIB
-INSTALL_DATA
-INSTALL_SCRIPT
-INSTALL_PROGRAM
-enable_autogen
-RPATH_EXTRA
-LM
-CC_MM
-AROUT
-ARFLAGS
-MKLIB
-TEST_LD_MODE
-LDTARGET
-CTARGET
-PIC_CFLAGS
-SOREV
-EXTRA_LDFLAGS
-DSO_LDFLAGS
-link_whole_archive
-libprefix
-exe
-a
-o
-importlib
-so
-LD_PRELOAD_VAR
-RPATH
-abi
-AR
-host_os
-host_vendor
-host_cpu
-host
-build_os
-build_vendor
-build_cpu
-build
-EGREP
-GREP
-CPP
-EXTRA_CFLAGS
-OBJEXT
-EXEEXT
-ac_ct_CC
-CPPFLAGS
-LDFLAGS
-CFLAGS
-CC
-XSLROOT
-XSLTPROC
-MANDIR
-DATADIR
-LIBDIR
-INCLUDEDIR
-BINDIR
-PREFIX
-abs_objroot
-objroot
-abs_srcroot
-srcroot
-rev
-CONFIG
-target_alias
-host_alias
-build_alias
-LIBS
-ECHO_T
-ECHO_N
-ECHO_C
-DEFS
-mandir
-localedir
-libdir
-psdir
-pdfdir
-dvidir
-htmldir
-infodir
-docdir
-oldincludedir
-includedir
-runstatedir
-localstatedir
-sharedstatedir
-sysconfdir
-datadir
-datarootdir
-libexecdir
-sbindir
-bindir
-program_transform_name
-prefix
-exec_prefix
-PACKAGE_URL
-PACKAGE_BUGREPORT
-PACKAGE_STRING
-PACKAGE_VERSION
-PACKAGE_TARNAME
-PACKAGE_NAME
-PATH_SEPARATOR
-SHELL'
-ac_subst_files=''
-ac_user_opts='
-enable_option_checking
-with_xslroot
-with_rpath
-enable_autogen
-enable_code_coverage
-with_mangling
-with_jemalloc_prefix
-with_export
-with_private_namespace
-with_install_suffix
-with_malloc_conf
-enable_cc_silence
-enable_debug
-enable_ivsalloc
-enable_stats
-enable_prof
-enable_prof_libunwind
-with_static_libunwind
-enable_prof_libgcc
-enable_prof_gcc
-enable_tcache
-enable_munmap
-enable_fill
-enable_utrace
-enable_valgrind
-enable_xmalloc
-enable_cache_oblivious
-with_lg_tiny_min
-with_lg_quantum
-with_lg_page
-with_lg_page_sizes
-with_lg_size_class_group
-with_version
-enable_lazy_lock
-enable_tls
-enable_zone_allocator
-'
- ac_precious_vars='build_alias
-host_alias
-target_alias
-CC
-CFLAGS
-LDFLAGS
-LIBS
-CPPFLAGS
-CPP'
-
-
-# Initialize some variables set by options.
-ac_init_help=
-ac_init_version=false
-ac_unrecognized_opts=
-ac_unrecognized_sep=
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-cache_file=/dev/null
-exec_prefix=NONE
-no_create=
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-verbose=
-x_includes=NONE
-x_libraries=NONE
-
-# Installation directory options.
-# These are left unexpanded so users can "make install exec_prefix=/foo"
-# and all the variables that are supposed to be based on exec_prefix
-# by default will actually change.
-# Use braces instead of parens because sh, perl, etc. also accept them.
-# (The list follows the same order as the GNU Coding Standards.)
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datarootdir='${prefix}/share'
-datadir='${datarootdir}'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-runstatedir='${localstatedir}/run'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-docdir='${datarootdir}/doc/${PACKAGE}'
-infodir='${datarootdir}/info'
-htmldir='${docdir}'
-dvidir='${docdir}'
-pdfdir='${docdir}'
-psdir='${docdir}'
-libdir='${exec_prefix}/lib'
-localedir='${datarootdir}/locale'
-mandir='${datarootdir}/man'
-
-ac_prev=
-ac_dashdash=
-for ac_option
-do
- # If the previous option needs an argument, assign it.
- if test -n "$ac_prev"; then
- eval $ac_prev=\$ac_option
- ac_prev=
- continue
- fi
-
- case $ac_option in
- *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
- *=) ac_optarg= ;;
- *) ac_optarg=yes ;;
- esac
-
- # Accept the important Cygnus configure options, so we can diagnose typos.
-
- case $ac_dashdash$ac_option in
- --)
- ac_dashdash=yes ;;
-
- -bindir | --bindir | --bindi | --bind | --bin | --bi)
- ac_prev=bindir ;;
- -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
- bindir=$ac_optarg ;;
-
- -build | --build | --buil | --bui | --bu)
- ac_prev=build_alias ;;
- -build=* | --build=* | --buil=* | --bui=* | --bu=*)
- build_alias=$ac_optarg ;;
-
- -cache-file | --cache-file | --cache-fil | --cache-fi \
- | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
- ac_prev=cache_file ;;
- -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
- | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
- cache_file=$ac_optarg ;;
-
- --config-cache | -C)
- cache_file=config.cache ;;
-
- -datadir | --datadir | --datadi | --datad)
- ac_prev=datadir ;;
- -datadir=* | --datadir=* | --datadi=* | --datad=*)
- datadir=$ac_optarg ;;
-
- -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
- | --dataroo | --dataro | --datar)
- ac_prev=datarootdir ;;
- -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
- | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
- datarootdir=$ac_optarg ;;
-
- -disable-* | --disable-*)
- ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
- # Reject names that are not valid shell variable names.
- expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
- as_fn_error $? "invalid feature name: $ac_useropt"
- ac_useropt_orig=$ac_useropt
- ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
- case $ac_user_opts in
- *"
-"enable_$ac_useropt"
-"*) ;;
- *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
- ac_unrecognized_sep=', ';;
- esac
- eval enable_$ac_useropt=no ;;
-
- -docdir | --docdir | --docdi | --doc | --do)
- ac_prev=docdir ;;
- -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
- docdir=$ac_optarg ;;
-
- -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
- ac_prev=dvidir ;;
- -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
- dvidir=$ac_optarg ;;
-
- -enable-* | --enable-*)
- ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
- # Reject names that are not valid shell variable names.
- expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
- as_fn_error $? "invalid feature name: $ac_useropt"
- ac_useropt_orig=$ac_useropt
- ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
- case $ac_user_opts in
- *"
-"enable_$ac_useropt"
-"*) ;;
- *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
- ac_unrecognized_sep=', ';;
- esac
- eval enable_$ac_useropt=\$ac_optarg ;;
-
- -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
- | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
- | --exec | --exe | --ex)
- ac_prev=exec_prefix ;;
- -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
- | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
- | --exec=* | --exe=* | --ex=*)
- exec_prefix=$ac_optarg ;;
-
- -gas | --gas | --ga | --g)
- # Obsolete; use --with-gas.
- with_gas=yes ;;
-
- -help | --help | --hel | --he | -h)
- ac_init_help=long ;;
- -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
- ac_init_help=recursive ;;
- -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
- ac_init_help=short ;;
-
- -host | --host | --hos | --ho)
- ac_prev=host_alias ;;
- -host=* | --host=* | --hos=* | --ho=*)
- host_alias=$ac_optarg ;;
-
- -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
- ac_prev=htmldir ;;
- -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
- | --ht=*)
- htmldir=$ac_optarg ;;
-
- -includedir | --includedir | --includedi | --included | --include \
- | --includ | --inclu | --incl | --inc)
- ac_prev=includedir ;;
- -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
- | --includ=* | --inclu=* | --incl=* | --inc=*)
- includedir=$ac_optarg ;;
-
- -infodir | --infodir | --infodi | --infod | --info | --inf)
- ac_prev=infodir ;;
- -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
- infodir=$ac_optarg ;;
-
- -libdir | --libdir | --libdi | --libd)
- ac_prev=libdir ;;
- -libdir=* | --libdir=* | --libdi=* | --libd=*)
- libdir=$ac_optarg ;;
-
- -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
- | --libexe | --libex | --libe)
- ac_prev=libexecdir ;;
- -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
- | --libexe=* | --libex=* | --libe=*)
- libexecdir=$ac_optarg ;;
-
- -localedir | --localedir | --localedi | --localed | --locale)
- ac_prev=localedir ;;
- -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
- localedir=$ac_optarg ;;
-
- -localstatedir | --localstatedir | --localstatedi | --localstated \
- | --localstate | --localstat | --localsta | --localst | --locals)
- ac_prev=localstatedir ;;
- -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
- | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
- localstatedir=$ac_optarg ;;
-
- -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
- ac_prev=mandir ;;
- -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
- mandir=$ac_optarg ;;
-
- -nfp | --nfp | --nf)
- # Obsolete; use --without-fp.
- with_fp=no ;;
-
- -no-create | --no-create | --no-creat | --no-crea | --no-cre \
- | --no-cr | --no-c | -n)
- no_create=yes ;;
-
- -no-recursion | --no-recursion | --no-recursio | --no-recursi \
- | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
- no_recursion=yes ;;
-
- -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
- | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
- | --oldin | --oldi | --old | --ol | --o)
- ac_prev=oldincludedir ;;
- -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
- | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
- | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
- oldincludedir=$ac_optarg ;;
-
- -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
- ac_prev=prefix ;;
- -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
- prefix=$ac_optarg ;;
-
- -program-prefix | --program-prefix | --program-prefi | --program-pref \
- | --program-pre | --program-pr | --program-p)
- ac_prev=program_prefix ;;
- -program-prefix=* | --program-prefix=* | --program-prefi=* \
- | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
- program_prefix=$ac_optarg ;;
-
- -program-suffix | --program-suffix | --program-suffi | --program-suff \
- | --program-suf | --program-su | --program-s)
- ac_prev=program_suffix ;;
- -program-suffix=* | --program-suffix=* | --program-suffi=* \
- | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
- program_suffix=$ac_optarg ;;
-
- -program-transform-name | --program-transform-name \
- | --program-transform-nam | --program-transform-na \
- | --program-transform-n | --program-transform- \
- | --program-transform | --program-transfor \
- | --program-transfo | --program-transf \
- | --program-trans | --program-tran \
- | --progr-tra | --program-tr | --program-t)
- ac_prev=program_transform_name ;;
- -program-transform-name=* | --program-transform-name=* \
- | --program-transform-nam=* | --program-transform-na=* \
- | --program-transform-n=* | --program-transform-=* \
- | --program-transform=* | --program-transfor=* \
- | --program-transfo=* | --program-transf=* \
- | --program-trans=* | --program-tran=* \
- | --progr-tra=* | --program-tr=* | --program-t=*)
- program_transform_name=$ac_optarg ;;
-
- -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
- ac_prev=pdfdir ;;
- -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
- pdfdir=$ac_optarg ;;
-
- -psdir | --psdir | --psdi | --psd | --ps)
- ac_prev=psdir ;;
- -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
- psdir=$ac_optarg ;;
-
- -q | -quiet | --quiet | --quie | --qui | --qu | --q \
- | -silent | --silent | --silen | --sile | --sil)
- silent=yes ;;
-
- -runstatedir | --runstatedir | --runstatedi | --runstated \
- | --runstate | --runstat | --runsta | --runst | --runs \
- | --run | --ru | --r)
- ac_prev=runstatedir ;;
- -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \
- | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \
- | --run=* | --ru=* | --r=*)
- runstatedir=$ac_optarg ;;
-
- -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
- ac_prev=sbindir ;;
- -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
- | --sbi=* | --sb=*)
- sbindir=$ac_optarg ;;
-
- -sharedstatedir | --sharedstatedir | --sharedstatedi \
- | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
- | --sharedst | --shareds | --shared | --share | --shar \
- | --sha | --sh)
- ac_prev=sharedstatedir ;;
- -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
- | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
- | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
- | --sha=* | --sh=*)
- sharedstatedir=$ac_optarg ;;
-
- -site | --site | --sit)
- ac_prev=site ;;
- -site=* | --site=* | --sit=*)
- site=$ac_optarg ;;
-
- -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
- ac_prev=srcdir ;;
- -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
- srcdir=$ac_optarg ;;
-
- -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
- | --syscon | --sysco | --sysc | --sys | --sy)
- ac_prev=sysconfdir ;;
- -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
- | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
- sysconfdir=$ac_optarg ;;
-
- -target | --target | --targe | --targ | --tar | --ta | --t)
- ac_prev=target_alias ;;
- -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
- target_alias=$ac_optarg ;;
-
- -v | -verbose | --verbose | --verbos | --verbo | --verb)
- verbose=yes ;;
-
- -version | --version | --versio | --versi | --vers | -V)
- ac_init_version=: ;;
-
- -with-* | --with-*)
- ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
- # Reject names that are not valid shell variable names.
- expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
- as_fn_error $? "invalid package name: $ac_useropt"
- ac_useropt_orig=$ac_useropt
- ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
- case $ac_user_opts in
- *"
-"with_$ac_useropt"
-"*) ;;
- *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
- ac_unrecognized_sep=', ';;
- esac
- eval with_$ac_useropt=\$ac_optarg ;;
-
- -without-* | --without-*)
- ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
- # Reject names that are not valid shell variable names.
- expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
- as_fn_error $? "invalid package name: $ac_useropt"
- ac_useropt_orig=$ac_useropt
- ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
- case $ac_user_opts in
- *"
-"with_$ac_useropt"
-"*) ;;
- *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
- ac_unrecognized_sep=', ';;
- esac
- eval with_$ac_useropt=no ;;
-
- --x)
- # Obsolete; use --with-x.
- with_x=yes ;;
-
- -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
- | --x-incl | --x-inc | --x-in | --x-i)
- ac_prev=x_includes ;;
- -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
- | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
- x_includes=$ac_optarg ;;
-
- -x-libraries | --x-libraries | --x-librarie | --x-librari \
- | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
- ac_prev=x_libraries ;;
- -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
- | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
- x_libraries=$ac_optarg ;;
-
- -*) as_fn_error $? "unrecognized option: \`$ac_option'
-Try \`$0 --help' for more information"
- ;;
-
- *=*)
- ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
- # Reject names that are not valid shell variable names.
- case $ac_envvar in #(
- '' | [0-9]* | *[!_$as_cr_alnum]* )
- as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
- esac
- eval $ac_envvar=\$ac_optarg
- export $ac_envvar ;;
-
- *)
- # FIXME: should be removed in autoconf 3.0.
- $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
- expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
- $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
- : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
- ;;
-
- esac
-done
-
-if test -n "$ac_prev"; then
- ac_option=--`echo $ac_prev | sed 's/_/-/g'`
- as_fn_error $? "missing argument to $ac_option"
-fi
-
-if test -n "$ac_unrecognized_opts"; then
- case $enable_option_checking in
- no) ;;
- fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
- *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
- esac
-fi
-
-# Check all directory arguments for consistency.
-for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \
- datadir sysconfdir sharedstatedir localstatedir includedir \
- oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
- libdir localedir mandir runstatedir
-do
- eval ac_val=\$$ac_var
- # Remove trailing slashes.
- case $ac_val in
- */ )
- ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
- eval $ac_var=\$ac_val;;
- esac
- # Be sure to have absolute directory names.
- case $ac_val in
- [\\/$]* | ?:[\\/]* ) continue;;
- NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
- esac
- as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
-done
-
-# There might be people who depend on the old broken behavior: `$host'
-# used to hold the argument of --host etc.
-# FIXME: To remove some day.
-build=$build_alias
-host=$host_alias
-target=$target_alias
-
-# FIXME: To remove some day.
-if test "x$host_alias" != x; then
- if test "x$build_alias" = x; then
- cross_compiling=maybe
- elif test "x$build_alias" != "x$host_alias"; then
- cross_compiling=yes
- fi
-fi
-
-ac_tool_prefix=
-test -n "$host_alias" && ac_tool_prefix=$host_alias-
-
-test "$silent" = yes && exec 6>/dev/null
-
-
-ac_pwd=`pwd` && test -n "$ac_pwd" &&
-ac_ls_di=`ls -di .` &&
-ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
- as_fn_error $? "working directory cannot be determined"
-test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
- as_fn_error $? "pwd does not report name of working directory"
-
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
- ac_srcdir_defaulted=yes
- # Try the directory containing this script, then the parent directory.
- ac_confdir=`$as_dirname -- "$as_myself" ||
-$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$as_myself" : 'X\(//\)[^/]' \| \
- X"$as_myself" : 'X\(//\)$' \| \
- X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_myself" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- srcdir=$ac_confdir
- if test ! -r "$srcdir/$ac_unique_file"; then
- srcdir=..
- fi
-else
- ac_srcdir_defaulted=no
-fi
-if test ! -r "$srcdir/$ac_unique_file"; then
- test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
- as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
-fi
-ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
-ac_abs_confdir=`(
- cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
- pwd)`
-# When building in place, set srcdir=.
-if test "$ac_abs_confdir" = "$ac_pwd"; then
- srcdir=.
-fi
-# Remove unnecessary trailing slashes from srcdir.
-# Double slashes in file names in object file debugging info
-# mess up M-x gdb in Emacs.
-case $srcdir in
-*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
-esac
-for ac_var in $ac_precious_vars; do
- eval ac_env_${ac_var}_set=\${${ac_var}+set}
- eval ac_env_${ac_var}_value=\$${ac_var}
- eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
- eval ac_cv_env_${ac_var}_value=\$${ac_var}
-done
-
-#
-# Report the --help message.
-#
-if test "$ac_init_help" = "long"; then
- # Omit some internal or obsolete options to make the list less imposing.
- # This message is too long to be a string in the A/UX 3.1 sh.
- cat <<_ACEOF
-\`configure' configures this package to adapt to many kinds of systems.
-
-Usage: $0 [OPTION]... [VAR=VALUE]...
-
-To assign environment variables (e.g., CC, CFLAGS...), specify them as
-VAR=VALUE. See below for descriptions of some of the useful variables.
-
-Defaults for the options are specified in brackets.
-
-Configuration:
- -h, --help display this help and exit
- --help=short display options specific to this package
- --help=recursive display the short help of all the included packages
- -V, --version display version information and exit
- -q, --quiet, --silent do not print \`checking ...' messages
- --cache-file=FILE cache test results in FILE [disabled]
- -C, --config-cache alias for \`--cache-file=config.cache'
- -n, --no-create do not create output files
- --srcdir=DIR find the sources in DIR [configure dir or \`..']
-
-Installation directories:
- --prefix=PREFIX install architecture-independent files in PREFIX
- [$ac_default_prefix]
- --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
- [PREFIX]
-
-By default, \`make install' will install all the files in
-\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify
-an installation prefix other than \`$ac_default_prefix' using \`--prefix',
-for instance \`--prefix=\$HOME'.
-
-For better control, use the options below.
-
-Fine tuning of the installation directories:
- --bindir=DIR user executables [EPREFIX/bin]
- --sbindir=DIR system admin executables [EPREFIX/sbin]
- --libexecdir=DIR program executables [EPREFIX/libexec]
- --sysconfdir=DIR read-only single-machine data [PREFIX/etc]
- --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com]
- --localstatedir=DIR modifiable single-machine data [PREFIX/var]
- --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run]
- --libdir=DIR object code libraries [EPREFIX/lib]
- --includedir=DIR C header files [PREFIX/include]
- --oldincludedir=DIR C header files for non-gcc [/usr/include]
- --datarootdir=DIR read-only arch.-independent data root [PREFIX/share]
- --datadir=DIR read-only architecture-independent data [DATAROOTDIR]
- --infodir=DIR info documentation [DATAROOTDIR/info]
- --localedir=DIR locale-dependent data [DATAROOTDIR/locale]
- --mandir=DIR man documentation [DATAROOTDIR/man]
- --docdir=DIR documentation root [DATAROOTDIR/doc/PACKAGE]
- --htmldir=DIR html documentation [DOCDIR]
- --dvidir=DIR dvi documentation [DOCDIR]
- --pdfdir=DIR pdf documentation [DOCDIR]
- --psdir=DIR ps documentation [DOCDIR]
-_ACEOF
-
- cat <<\_ACEOF
-
-System types:
- --build=BUILD configure for building on BUILD [guessed]
- --host=HOST cross-compile to build programs to run on HOST [BUILD]
-_ACEOF
-fi
-
-if test -n "$ac_init_help"; then
-
- cat <<\_ACEOF
-
-Optional Features:
- --disable-option-checking ignore unrecognized --enable/--with options
- --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no)
- --enable-FEATURE[=ARG] include FEATURE [ARG=yes]
- --enable-autogen Automatically regenerate configure output
- --enable-code-coverage Enable code coverage
- --disable-cc-silence Do not silence irrelevant compiler warnings
- --enable-debug Build debugging code (implies --enable-ivsalloc)
- --enable-ivsalloc Validate pointers passed through the public API
- --disable-stats Disable statistics calculation/reporting
- --enable-prof Enable allocation profiling
- --enable-prof-libunwind Use libunwind for backtracing
- --disable-prof-libgcc Do not use libgcc for backtracing
- --disable-prof-gcc Do not use gcc intrinsics for backtracing
- --disable-tcache Disable per thread caches
- --disable-munmap Disable VM deallocation via munmap(2)
- --disable-fill Disable support for junk/zero filling, quarantine,
- and redzones
- --enable-utrace Enable utrace(2)-based tracing
- --disable-valgrind Disable support for Valgrind
- --enable-xmalloc Support xmalloc option
- --disable-cache-oblivious
- Disable support for cache-oblivious allocation
- alignment
- --enable-lazy-lock Enable lazy locking (only lock when multi-threaded)
- --disable-tls Disable thread-local storage (__thread keyword)
- --disable-zone-allocator
- Disable zone allocator for Darwin
-
-Optional Packages:
- --with-PACKAGE[=ARG] use PACKAGE [ARG=yes]
- --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no)
- --with-xslroot=<path> XSL stylesheet root path
- --with-rpath=<rpath> Colon-separated rpath (ELF systems only)
- --with-mangling=<map> Mangle symbols in <map>
- --with-jemalloc-prefix=<prefix>
- Prefix to prepend to all public APIs
- --without-export disable exporting jemalloc public APIs
- --with-private-namespace=<prefix>
- Prefix to prepend to all library-private APIs
- --with-install-suffix=<suffix>
- Suffix to append to all installed files
- --with-malloc-conf=<malloc_conf>
- config.malloc_conf options string
- --with-static-libunwind=<libunwind.a>
- Path to static libunwind library; use rather than
- dynamically linking
- --with-lg-tiny-min=<lg-tiny-min>
- Base 2 log of minimum tiny size class to support
- --with-lg-quantum=<lg-quantum>
- Base 2 log of minimum allocation alignment
- --with-lg-page=<lg-page>
- Base 2 log of system page size
- --with-lg-page-sizes=<lg-page-sizes>
- Base 2 logs of system page sizes to support
- --with-lg-size-class-group=<lg-size-class-group>
- Base 2 log of size classes per doubling
- --with-version=<major>.<minor>.<bugfix>-<nrev>-g<gid>
- Version string
-
-Some influential environment variables:
- CC C compiler command
- CFLAGS C compiler flags
- LDFLAGS linker flags, e.g. -L<lib dir> if you have libraries in a
- nonstandard directory <lib dir>
- LIBS libraries to pass to the linker, e.g. -l<library>
- CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
- you have headers in a nonstandard directory <include dir>
- CPP C preprocessor
-
-Use these variables to override the choices made by `configure' or to help
-it to find libraries and programs with nonstandard names/locations.
-
-Report bugs to the package provider.
-_ACEOF
-ac_status=$?
-fi
-
-if test "$ac_init_help" = "recursive"; then
- # If there are subdirs, report their specific --help.
- for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
- test -d "$ac_dir" ||
- { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
- continue
- ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
- ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
- # A ".." for each directory in $ac_dir_suffix.
- ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
- case $ac_top_builddir_sub in
- "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
- *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
- esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
- .) # We are building in place.
- ac_srcdir=.
- ac_top_srcdir=$ac_top_builddir_sub
- ac_abs_top_srcdir=$ac_pwd ;;
- [\\/]* | ?:[\\/]* ) # Absolute name.
- ac_srcdir=$srcdir$ac_dir_suffix;
- ac_top_srcdir=$srcdir
- ac_abs_top_srcdir=$srcdir ;;
- *) # Relative name.
- ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
- ac_top_srcdir=$ac_top_build_prefix$srcdir
- ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
- cd "$ac_dir" || { ac_status=$?; continue; }
- # Check for guested configure.
- if test -f "$ac_srcdir/configure.gnu"; then
- echo &&
- $SHELL "$ac_srcdir/configure.gnu" --help=recursive
- elif test -f "$ac_srcdir/configure"; then
- echo &&
- $SHELL "$ac_srcdir/configure" --help=recursive
- else
- $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
- fi || ac_status=$?
- cd "$ac_pwd" || { ac_status=$?; break; }
- done
-fi
-
-test -n "$ac_init_help" && exit $ac_status
-if $ac_init_version; then
- cat <<\_ACEOF
-configure
-generated by GNU Autoconf 2.69
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This configure script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it.
-_ACEOF
- exit
-fi
-
-## ------------------------ ##
-## Autoconf initialization. ##
-## ------------------------ ##
-
-# ac_fn_c_try_compile LINENO
-# --------------------------
-# Try to compile conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_compile ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- rm -f conftest.$ac_objext
- if { { ac_try="$ac_compile"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_compile") 2>conftest.err
- ac_status=$?
- if test -s conftest.err; then
- grep -v '^ *+' conftest.err >conftest.er1
- cat conftest.er1 >&5
- mv -f conftest.er1 conftest.err
- fi
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; } && {
- test -z "$ac_c_werror_flag" ||
- test ! -s conftest.err
- } && test -s conftest.$ac_objext; then :
- ac_retval=0
-else
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
- ac_retval=1
-fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
- as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_compile
-
-# ac_fn_c_try_cpp LINENO
-# ----------------------
-# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_cpp ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- if { { ac_try="$ac_cpp conftest.$ac_ext"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
- ac_status=$?
- if test -s conftest.err; then
- grep -v '^ *+' conftest.err >conftest.er1
- cat conftest.er1 >&5
- mv -f conftest.er1 conftest.err
- fi
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; } > conftest.i && {
- test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
- test ! -s conftest.err
- }; then :
- ac_retval=0
-else
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
- ac_retval=1
-fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
- as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_cpp
-
-# ac_fn_c_try_run LINENO
-# ----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
-# that executables *can* be run.
-ac_fn_c_try_run ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- if { { ac_try="$ac_link"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
- { { case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_try") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; }; then :
- ac_retval=0
-else
- $as_echo "$as_me: program exited with status $ac_status" >&5
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
- ac_retval=$ac_status
-fi
- rm -rf conftest.dSYM conftest_ipa8_conftest.oo
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
- as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_run
-
-# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists and can be compiled using the include files in
-# INCLUDES, setting the cache variable VAR accordingly.
-ac_fn_c_check_header_compile ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- eval "$3=yes"
-else
- eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$3
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_compile
-
-# ac_fn_c_compute_int LINENO EXPR VAR INCLUDES
-# --------------------------------------------
-# Tries to find the compile-time value of EXPR in a program that includes
-# INCLUDES, setting VAR accordingly. Returns whether the value could be
-# computed
-ac_fn_c_compute_int ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- if test "$cross_compiling" = yes; then
- # Depending upon the size, compute the lo and hi bounds.
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-int
-main ()
-{
-static int test_array [1 - 2 * !(($2) >= 0)];
-test_array [0] = 0;
-return test_array [0];
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_lo=0 ac_mid=0
- while :; do
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-int
-main ()
-{
-static int test_array [1 - 2 * !(($2) <= $ac_mid)];
-test_array [0] = 0;
-return test_array [0];
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_hi=$ac_mid; break
-else
- as_fn_arith $ac_mid + 1 && ac_lo=$as_val
- if test $ac_lo -le $ac_mid; then
- ac_lo= ac_hi=
- break
- fi
- as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- done
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-int
-main ()
-{
-static int test_array [1 - 2 * !(($2) < 0)];
-test_array [0] = 0;
-return test_array [0];
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_hi=-1 ac_mid=-1
- while :; do
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-int
-main ()
-{
-static int test_array [1 - 2 * !(($2) >= $ac_mid)];
-test_array [0] = 0;
-return test_array [0];
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_lo=$ac_mid; break
-else
- as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val
- if test $ac_mid -le $ac_hi; then
- ac_lo= ac_hi=
- break
- fi
- as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- done
-else
- ac_lo= ac_hi=
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-# Binary search between lo and hi bounds.
-while test "x$ac_lo" != "x$ac_hi"; do
- as_fn_arith '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo && ac_mid=$as_val
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-int
-main ()
-{
-static int test_array [1 - 2 * !(($2) <= $ac_mid)];
-test_array [0] = 0;
-return test_array [0];
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_hi=$ac_mid
-else
- as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-done
-case $ac_lo in #((
-?*) eval "$3=\$ac_lo"; ac_retval=0 ;;
-'') ac_retval=1 ;;
-esac
- else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-static long int longval () { return $2; }
-static unsigned long int ulongval () { return $2; }
-#include <stdio.h>
-#include <stdlib.h>
-int
-main ()
-{
-
- FILE *f = fopen ("conftest.val", "w");
- if (! f)
- return 1;
- if (($2) < 0)
- {
- long int i = longval ();
- if (i != ($2))
- return 1;
- fprintf (f, "%ld", i);
- }
- else
- {
- unsigned long int i = ulongval ();
- if (i != ($2))
- return 1;
- fprintf (f, "%lu", i);
- }
- /* Do not output a trailing newline, as this causes \r\n confusion
- on some platforms. */
- return ferror (f) || fclose (f) != 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
- echo >>conftest.val; read $3 <conftest.val; ac_retval=0
-else
- ac_retval=1
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
- conftest.$ac_objext conftest.beam conftest.$ac_ext
-rm -f conftest.val
-
- fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
- as_fn_set_status $ac_retval
-
-} # ac_fn_c_compute_int
-
-# ac_fn_c_try_link LINENO
-# -----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_link ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- rm -f conftest.$ac_objext conftest$ac_exeext
- if { { ac_try="$ac_link"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link") 2>conftest.err
- ac_status=$?
- if test -s conftest.err; then
- grep -v '^ *+' conftest.err >conftest.er1
- cat conftest.er1 >&5
- mv -f conftest.er1 conftest.err
- fi
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; } && {
- test -z "$ac_c_werror_flag" ||
- test ! -s conftest.err
- } && test -s conftest$ac_exeext && {
- test "$cross_compiling" = yes ||
- test -x conftest$ac_exeext
- }; then :
- ac_retval=0
-else
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
- ac_retval=1
-fi
- # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
- # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
- # interfere with the next link command; also delete a directory that is
- # left behind by Apple's compiler. We do this before executing the actions.
- rm -rf conftest.dSYM conftest_ipa8_conftest.oo
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
- as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_link
-
-# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
-# -------------------------------------------------------
-# Tests whether HEADER exists, giving a warning if it cannot be compiled using
-# the include files in INCLUDES and setting the cache variable VAR
-# accordingly.
-ac_fn_c_check_header_mongrel ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- if eval \${$3+:} false; then :
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
- $as_echo_n "(cached) " >&6
-fi
-eval ac_res=\$$3
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-else
- # Is the header compilable?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
-$as_echo_n "checking $2 usability... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-#include <$2>
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_header_compiler=yes
-else
- ac_header_compiler=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
-$as_echo "$ac_header_compiler" >&6; }
-
-# Is the header present?
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
-$as_echo_n "checking $2 presence... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <$2>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
- ac_header_preproc=yes
-else
- ac_header_preproc=no
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
-$as_echo "$ac_header_preproc" >&6; }
-
-# So? What about this header?
-case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
- yes:no: )
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
-$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
- ;;
- no:yes:* )
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
-$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5
-$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
-$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5
-$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
-$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
- ;;
-esac
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- eval "$3=\$ac_header_compiler"
-fi
-eval ac_res=\$$3
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
-fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_header_mongrel
-
-# ac_fn_c_check_func LINENO FUNC VAR
-# ----------------------------------
-# Tests whether FUNC exists, setting the cache variable VAR accordingly
-ac_fn_c_check_func ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-/* Define $2 to an innocuous variant, in case <limits.h> declares $2.
- For example, HP-UX 11i <limits.h> declares gettimeofday. */
-#define $2 innocuous_$2
-
-/* System header to define __stub macros and hopefully few prototypes,
- which can conflict with char $2 (); below.
- Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
- <limits.h> exists even on freestanding compilers. */
-
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
-
-#undef $2
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char $2 ();
-/* The GNU C library defines this for functions which it implements
- to always fail with ENOSYS. Some functions are actually named
- something starting with __ and the normal name is an alias. */
-#if defined __stub_$2 || defined __stub___$2
-choke me
-#endif
-
-int
-main ()
-{
-return $2 ();
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- eval "$3=yes"
-else
- eval "$3=no"
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-eval ac_res=\$$3
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_func
-
-# ac_fn_c_check_type LINENO TYPE VAR INCLUDES
-# -------------------------------------------
-# Tests whether TYPE exists after having included INCLUDES, setting cache
-# variable VAR accordingly.
-ac_fn_c_check_type ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
-$as_echo_n "checking for $2... " >&6; }
-if eval \${$3+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- eval "$3=no"
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-int
-main ()
-{
-if (sizeof ($2))
- return 0;
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$4
-int
-main ()
-{
-if (sizeof (($2)))
- return 0;
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
- eval "$3=yes"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-eval ac_res=\$$3
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
-$as_echo "$ac_res" >&6; }
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
-
-} # ac_fn_c_check_type
-cat >config.log <<_ACEOF
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by $as_me, which was
-generated by GNU Autoconf 2.69. Invocation command line was
-
- $ $0 $@
-
-_ACEOF
-exec 5>>config.log
-{
-cat <<_ASUNAME
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
-/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown`
-
-/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown`
-/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown`
-/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown`
-/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown`
-/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown`
-
-_ASUNAME
-
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- $as_echo "PATH: $as_dir"
- done
-IFS=$as_save_IFS
-
-} >&5
-
-cat >&5 <<_ACEOF
-
-
-## ----------- ##
-## Core tests. ##
-## ----------- ##
-
-_ACEOF
-
-
-# Keep a trace of the command line.
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Strip out --silent because we don't want to record it for future runs.
-# Also quote any args containing shell meta-characters.
-# Make two passes to allow for proper duplicate-argument suppression.
-ac_configure_args=
-ac_configure_args0=
-ac_configure_args1=
-ac_must_keep_next=false
-for ac_pass in 1 2
-do
- for ac_arg
- do
- case $ac_arg in
- -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
- -q | -quiet | --quiet | --quie | --qui | --qu | --q \
- | -silent | --silent | --silen | --sile | --sil)
- continue ;;
- *\'*)
- ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
- esac
- case $ac_pass in
- 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
- 2)
- as_fn_append ac_configure_args1 " '$ac_arg'"
- if test $ac_must_keep_next = true; then
- ac_must_keep_next=false # Got value, back to normal.
- else
- case $ac_arg in
- *=* | --config-cache | -C | -disable-* | --disable-* \
- | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
- | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
- | -with-* | --with-* | -without-* | --without-* | --x)
- case "$ac_configure_args0 " in
- "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
- esac
- ;;
- -* ) ac_must_keep_next=true ;;
- esac
- fi
- as_fn_append ac_configure_args " '$ac_arg'"
- ;;
- esac
- done
-done
-{ ac_configure_args0=; unset ac_configure_args0;}
-{ ac_configure_args1=; unset ac_configure_args1;}
-
-# When interrupted or exit'd, cleanup temporary files, and complete
-# config.log. We remove comments because anyway the quotes in there
-# would cause problems or look ugly.
-# WARNING: Use '\'' to represent an apostrophe within the trap.
-# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
-trap 'exit_status=$?
- # Save into config.log some information that might help in debugging.
- {
- echo
-
- $as_echo "## ---------------- ##
-## Cache variables. ##
-## ---------------- ##"
- echo
- # The following way of writing the cache mishandles newlines in values,
-(
- for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
- eval ac_val=\$$ac_var
- case $ac_val in #(
- *${as_nl}*)
- case $ac_var in #(
- *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
- esac
- case $ac_var in #(
- _ | IFS | as_nl) ;; #(
- BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
- *) { eval $ac_var=; unset $ac_var;} ;;
- esac ;;
- esac
- done
- (set) 2>&1 |
- case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
- *${as_nl}ac_space=\ *)
- sed -n \
- "s/'\''/'\''\\\\'\'''\''/g;
- s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
- ;; #(
- *)
- sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
- ;;
- esac |
- sort
-)
- echo
-
- $as_echo "## ----------------- ##
-## Output variables. ##
-## ----------------- ##"
- echo
- for ac_var in $ac_subst_vars
- do
- eval ac_val=\$$ac_var
- case $ac_val in
- *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
- esac
- $as_echo "$ac_var='\''$ac_val'\''"
- done | sort
- echo
-
- if test -n "$ac_subst_files"; then
- $as_echo "## ------------------- ##
-## File substitutions. ##
-## ------------------- ##"
- echo
- for ac_var in $ac_subst_files
- do
- eval ac_val=\$$ac_var
- case $ac_val in
- *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
- esac
- $as_echo "$ac_var='\''$ac_val'\''"
- done | sort
- echo
- fi
-
- if test -s confdefs.h; then
- $as_echo "## ----------- ##
-## confdefs.h. ##
-## ----------- ##"
- echo
- cat confdefs.h
- echo
- fi
- test "$ac_signal" != 0 &&
- $as_echo "$as_me: caught signal $ac_signal"
- $as_echo "$as_me: exit $exit_status"
- } >&5
- rm -f core *.core core.conftest.* &&
- rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
- exit $exit_status
-' 0
-for ac_signal in 1 2 13 15; do
- trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
-done
-ac_signal=0
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -f -r conftest* confdefs.h
-
-$as_echo "/* confdefs.h */" > confdefs.h
-
-# Predefined preprocessor variables.
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_NAME "$PACKAGE_NAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_VERSION "$PACKAGE_VERSION"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_STRING "$PACKAGE_STRING"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_URL "$PACKAGE_URL"
-_ACEOF
-
-
-# Let the site file select an alternate cache file if it wants to.
-# Prefer an explicitly selected file to automatically selected ones.
-ac_site_file1=NONE
-ac_site_file2=NONE
-if test -n "$CONFIG_SITE"; then
- # We do not want a PATH search for config.site.
- case $CONFIG_SITE in #((
- -*) ac_site_file1=./$CONFIG_SITE;;
- */*) ac_site_file1=$CONFIG_SITE;;
- *) ac_site_file1=./$CONFIG_SITE;;
- esac
-elif test "x$prefix" != xNONE; then
- ac_site_file1=$prefix/share/config.site
- ac_site_file2=$prefix/etc/config.site
-else
- ac_site_file1=$ac_default_prefix/share/config.site
- ac_site_file2=$ac_default_prefix/etc/config.site
-fi
-for ac_site_file in "$ac_site_file1" "$ac_site_file2"
-do
- test "x$ac_site_file" = xNONE && continue
- if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
-$as_echo "$as_me: loading site script $ac_site_file" >&6;}
- sed 's/^/| /' "$ac_site_file" >&5
- . "$ac_site_file" \
- || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "failed to load site script $ac_site_file
-See \`config.log' for more details" "$LINENO" 5; }
- fi
-done
-
-if test -r "$cache_file"; then
- # Some versions of bash will fail to source /dev/null (special files
- # actually), so we avoid doing that. DJGPP emulates it as a regular file.
- if test /dev/null != "$cache_file" && test -f "$cache_file"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
-$as_echo "$as_me: loading cache $cache_file" >&6;}
- case $cache_file in
- [\\/]* | ?:[\\/]* ) . "$cache_file";;
- *) . "./$cache_file";;
- esac
- fi
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
-$as_echo "$as_me: creating cache $cache_file" >&6;}
- >$cache_file
-fi
-
-# Check that the precious variables saved in the cache have kept the same
-# value.
-ac_cache_corrupted=false
-for ac_var in $ac_precious_vars; do
- eval ac_old_set=\$ac_cv_env_${ac_var}_set
- eval ac_new_set=\$ac_env_${ac_var}_set
- eval ac_old_val=\$ac_cv_env_${ac_var}_value
- eval ac_new_val=\$ac_env_${ac_var}_value
- case $ac_old_set,$ac_new_set in
- set,)
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
- ac_cache_corrupted=: ;;
- ,set)
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
- ac_cache_corrupted=: ;;
- ,);;
- *)
- if test "x$ac_old_val" != "x$ac_new_val"; then
- # differences in whitespace do not lead to failure.
- ac_old_val_w=`echo x $ac_old_val`
- ac_new_val_w=`echo x $ac_new_val`
- if test "$ac_old_val_w" != "$ac_new_val_w"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
-$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
- ac_cache_corrupted=:
- else
- { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
-$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
- eval $ac_var=\$ac_old_val
- fi
- { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5
-$as_echo "$as_me: former value: \`$ac_old_val'" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5
-$as_echo "$as_me: current value: \`$ac_new_val'" >&2;}
- fi;;
- esac
- # Pass precious variables to config.status.
- if test "$ac_new_set" = set; then
- case $ac_new_val in
- *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
- *) ac_arg=$ac_var=$ac_new_val ;;
- esac
- case " $ac_configure_args " in
- *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy.
- *) as_fn_append ac_configure_args " '$ac_arg'" ;;
- esac
- fi
-done
-if $ac_cache_corrupted; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
-$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
- as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
-fi
-## -------------------- ##
-## Main body of script. ##
-## -------------------- ##
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-ac_aux_dir=
-for ac_dir in build-aux "$srcdir"/build-aux; do
- if test -f "$ac_dir/install-sh"; then
- ac_aux_dir=$ac_dir
- ac_install_sh="$ac_aux_dir/install-sh -c"
- break
- elif test -f "$ac_dir/install.sh"; then
- ac_aux_dir=$ac_dir
- ac_install_sh="$ac_aux_dir/install.sh -c"
- break
- elif test -f "$ac_dir/shtool"; then
- ac_aux_dir=$ac_dir
- ac_install_sh="$ac_aux_dir/shtool install -c"
- break
- fi
-done
-if test -z "$ac_aux_dir"; then
- as_fn_error $? "cannot find install-sh, install.sh, or shtool in build-aux \"$srcdir\"/build-aux" "$LINENO" 5
-fi
-
-# These three variables are undocumented and unsupported,
-# and are intended to be withdrawn in a future Autoconf release.
-# They can cause serious problems if a builder's source tree is in a directory
-# whose full name contains unusual characters.
-ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var.
-ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var.
-ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var.
-
-
-
-
-
-
-
-
-
-CONFIG=`echo ${ac_configure_args} | sed -e 's#'"'"'\([^ ]*\)'"'"'#\1#g'`
-
-
-rev=2
-
-
-srcroot=$srcdir
-if test "x${srcroot}" = "x." ; then
- srcroot=""
-else
- srcroot="${srcroot}/"
-fi
-
-abs_srcroot="`cd \"${srcdir}\"; pwd`/"
-
-
-objroot=""
-
-abs_objroot="`pwd`/"
-
-
-if test "x$prefix" = "xNONE" ; then
- prefix="/usr/local"
-fi
-if test "x$exec_prefix" = "xNONE" ; then
- exec_prefix=$prefix
-fi
-PREFIX=$prefix
-
-BINDIR=`eval echo $bindir`
-BINDIR=`eval echo $BINDIR`
-
-INCLUDEDIR=`eval echo $includedir`
-INCLUDEDIR=`eval echo $INCLUDEDIR`
-
-LIBDIR=`eval echo $libdir`
-LIBDIR=`eval echo $LIBDIR`
-
-DATADIR=`eval echo $datadir`
-DATADIR=`eval echo $DATADIR`
-
-MANDIR=`eval echo $mandir`
-MANDIR=`eval echo $MANDIR`
-
-
-# Extract the first word of "xsltproc", so it can be a program name with args.
-set dummy xsltproc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_XSLTPROC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- case $XSLTPROC in
- [\\/]* | ?:[\\/]*)
- ac_cv_path_XSLTPROC="$XSLTPROC" # Let the user override the test with a path.
- ;;
- *)
- as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_path_XSLTPROC="$as_dir/$ac_word$ac_exec_ext"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
- test -z "$ac_cv_path_XSLTPROC" && ac_cv_path_XSLTPROC="false"
- ;;
-esac
-fi
-XSLTPROC=$ac_cv_path_XSLTPROC
-if test -n "$XSLTPROC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $XSLTPROC" >&5
-$as_echo "$XSLTPROC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-if test -d "/usr/share/xml/docbook/stylesheet/docbook-xsl" ; then
- DEFAULT_XSLROOT="/usr/share/xml/docbook/stylesheet/docbook-xsl"
-elif test -d "/usr/share/sgml/docbook/xsl-stylesheets" ; then
- DEFAULT_XSLROOT="/usr/share/sgml/docbook/xsl-stylesheets"
-else
- DEFAULT_XSLROOT=""
-fi
-
-# Check whether --with-xslroot was given.
-if test "${with_xslroot+set}" = set; then :
- withval=$with_xslroot;
-if test "x$with_xslroot" = "xno" ; then
- XSLROOT="${DEFAULT_XSLROOT}"
-else
- XSLROOT="${with_xslroot}"
-fi
-
-else
- XSLROOT="${DEFAULT_XSLROOT}"
-
-fi
-
-
-
-CFLAGS=$CFLAGS
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-if test -n "$ac_tool_prefix"; then
- # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_CC="${ac_tool_prefix}gcc"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_CC"; then
- ac_ct_CC=$CC
- # Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$ac_ct_CC"; then
- ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_ac_ct_CC="gcc"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
- if test "x$ac_ct_CC" = x; then
- CC=""
- else
- case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
- CC=$ac_ct_CC
- fi
-else
- CC="$ac_cv_prog_CC"
-fi
-
-if test -z "$CC"; then
- if test -n "$ac_tool_prefix"; then
- # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_CC="${ac_tool_prefix}cc"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- fi
-fi
-if test -z "$CC"; then
- # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
- ac_prog_rejected=no
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
- ac_prog_rejected=yes
- continue
- fi
- ac_cv_prog_CC="cc"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-if test $ac_prog_rejected = yes; then
- # We found a bogon in the path, so make sure we never use it.
- set dummy $ac_cv_prog_CC
- shift
- if test $# != 0; then
- # We chose a different compiler from the bogus one.
- # However, it has the same basename, so the bogon will be chosen
- # first if we set CC to just the basename; use the full file name.
- shift
- ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
- fi
-fi
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$CC"; then
- if test -n "$ac_tool_prefix"; then
- for ac_prog in cl.exe
- do
- # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- test -n "$CC" && break
- done
-fi
-if test -z "$CC"; then
- ac_ct_CC=$CC
- for ac_prog in cl.exe
-do
- # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$ac_ct_CC"; then
- ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_ac_ct_CC="$ac_prog"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- test -n "$ac_ct_CC" && break
-done
-
- if test "x$ac_ct_CC" = x; then
- CC=""
- else
- case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
- CC=$ac_ct_CC
- fi
-fi
-
-fi
-
-
-test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "no acceptable C compiler found in \$PATH
-See \`config.log' for more details" "$LINENO" 5; }
-
-# Provide some information about the compiler.
-$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
-set X $ac_compile
-ac_compiler=$2
-for ac_option in --version -v -V -qversion; do
- { { ac_try="$ac_compiler $ac_option >&5"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_compiler $ac_option >&5") 2>conftest.err
- ac_status=$?
- if test -s conftest.err; then
- sed '10a\
-... rest of stderr output deleted ...
- 10q' conftest.err >conftest.er1
- cat conftest.er1 >&5
- fi
- rm -f conftest.er1 conftest.err
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }
-done
-
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
-# Try to create an executable without -o first, disregard a.out.
-# It will help us diagnose broken compilers, and finding out an intuition
-# of exeext.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
-$as_echo_n "checking whether the C compiler works... " >&6; }
-ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-
-# The possible output files:
-ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
-
-ac_rmfiles=
-for ac_file in $ac_files
-do
- case $ac_file in
- *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
- * ) ac_rmfiles="$ac_rmfiles $ac_file";;
- esac
-done
-rm -f $ac_rmfiles
-
-if { { ac_try="$ac_link_default"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link_default") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; then :
- # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
-# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
-# in a Makefile. We should not override ac_cv_exeext if it was cached,
-# so that the user can short-circuit this test for compilers unknown to
-# Autoconf.
-for ac_file in $ac_files ''
-do
- test -f "$ac_file" || continue
- case $ac_file in
- *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
- ;;
- [ab].out )
- # We found the default executable, but exeext='' is most
- # certainly right.
- break;;
- *.* )
- if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
- then :; else
- ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
- fi
- # We set ac_cv_exeext here because the later test for it is not
- # safe: cross compilers may not add the suffix if given an `-o'
- # argument, so we may need to know it at that point already.
- # Even if this section looks crufty: it has the advantage of
- # actually working.
- break;;
- * )
- break;;
- esac
-done
-test "$ac_cv_exeext" = no && ac_cv_exeext=
-
-else
- ac_file=''
-fi
-if test -z "$ac_file"; then :
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-$as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "C compiler cannot create executables
-See \`config.log' for more details" "$LINENO" 5; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
-$as_echo_n "checking for C compiler default output file name... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
-$as_echo "$ac_file" >&6; }
-ac_exeext=$ac_cv_exeext
-
-rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
-$as_echo_n "checking for suffix of executables... " >&6; }
-if { { ac_try="$ac_link"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; then :
- # If both `conftest.exe' and `conftest' are `present' (well, observable)
-# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will
-# work properly (i.e., refer to `conftest.exe'), while it won't with
-# `rm'.
-for ac_file in conftest.exe conftest conftest.*; do
- test -f "$ac_file" || continue
- case $ac_file in
- *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
- *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
- break;;
- * ) break;;
- esac
-done
-else
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest conftest$ac_cv_exeext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
-$as_echo "$ac_cv_exeext" >&6; }
-
-rm -f conftest.$ac_ext
-EXEEXT=$ac_cv_exeext
-ac_exeext=$EXEEXT
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <stdio.h>
-int
-main ()
-{
-FILE *f = fopen ("conftest.out", "w");
- return ferror (f) || fclose (f) != 0;
-
- ;
- return 0;
-}
-_ACEOF
-ac_clean_files="$ac_clean_files conftest.out"
-# Check that the compiler produces executables we can run. If not, either
-# the compiler is broken, or we cross compile.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
-$as_echo_n "checking whether we are cross compiling... " >&6; }
-if test "$cross_compiling" != yes; then
- { { ac_try="$ac_link"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }
- if { ac_try='./conftest$ac_cv_exeext'
- { { case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_try") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; }; then
- cross_compiling=no
- else
- if test "$cross_compiling" = maybe; then
- cross_compiling=yes
- else
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details" "$LINENO" 5; }
- fi
- fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
-$as_echo "$cross_compiling" >&6; }
-
-rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
-$as_echo_n "checking for suffix of object files... " >&6; }
-if ${ac_cv_objext+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-rm -f conftest.o conftest.obj
-if { { ac_try="$ac_compile"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_compile") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; then :
- for ac_file in conftest.o conftest.obj conftest.*; do
- test -f "$ac_file" || continue;
- case $ac_file in
- *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
- *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
- break;;
- esac
-done
-else
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of object files: cannot compile
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest.$ac_cv_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
-$as_echo "$ac_cv_objext" >&6; }
-OBJEXT=$ac_cv_objext
-ac_objext=$OBJEXT
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
-$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if ${ac_cv_c_compiler_gnu+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-#ifndef __GNUC__
- choke me
-#endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_compiler_gnu=yes
-else
- ac_compiler_gnu=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_c_compiler_gnu=$ac_compiler_gnu
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
-$as_echo "$ac_cv_c_compiler_gnu" >&6; }
-if test $ac_compiler_gnu = yes; then
- GCC=yes
-else
- GCC=
-fi
-ac_test_CFLAGS=${CFLAGS+set}
-ac_save_CFLAGS=$CFLAGS
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
-$as_echo_n "checking whether $CC accepts -g... " >&6; }
-if ${ac_cv_prog_cc_g+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_save_c_werror_flag=$ac_c_werror_flag
- ac_c_werror_flag=yes
- ac_cv_prog_cc_g=no
- CFLAGS="-g"
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_prog_cc_g=yes
-else
- CFLAGS=""
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
- ac_c_werror_flag=$ac_save_c_werror_flag
- CFLAGS="-g"
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_prog_cc_g=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- ac_c_werror_flag=$ac_save_c_werror_flag
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
-$as_echo "$ac_cv_prog_cc_g" >&6; }
-if test "$ac_test_CFLAGS" = set; then
- CFLAGS=$ac_save_CFLAGS
-elif test $ac_cv_prog_cc_g = yes; then
- if test "$GCC" = yes; then
- CFLAGS="-g -O2"
- else
- CFLAGS="-g"
- fi
-else
- if test "$GCC" = yes; then
- CFLAGS="-O2"
- else
- CFLAGS=
- fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
-$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if ${ac_cv_prog_cc_c89+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_cv_prog_cc_c89=no
-ac_save_CC=$CC
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <stdarg.h>
-#include <stdio.h>
-struct stat;
-/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */
-struct buf { int x; };
-FILE * (*rcsopen) (struct buf *, struct stat *, int);
-static char *e (p, i)
- char **p;
- int i;
-{
- return p[i];
-}
-static char *f (char * (*g) (char **, int), char **p, ...)
-{
- char *s;
- va_list v;
- va_start (v,p);
- s = g (p, va_arg (v,int));
- va_end (v);
- return s;
-}
-
-/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has
- function prototypes and stuff, but not '\xHH' hex character constants.
- These don't provoke an error unfortunately, instead are silently treated
- as 'x'. The following induces an error, until -std is added to get
- proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an
- array size at least. It's necessary to write '\x00'==0 to get something
- that's true only with -std. */
-int osf4_cc_array ['\x00' == 0 ? 1 : -1];
-
-/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
- inside strings and character constants. */
-#define FOO(x) 'x'
-int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
-
-int test (int i, double x);
-struct s1 {int (*f) (int a);};
-struct s2 {int (*f) (double a);};
-int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
-int argc;
-char **argv;
-int
-main ()
-{
-return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1];
- ;
- return 0;
-}
-_ACEOF
-for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
- -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
-do
- CC="$ac_save_CC $ac_arg"
- if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_prog_cc_c89=$ac_arg
-fi
-rm -f core conftest.err conftest.$ac_objext
- test "x$ac_cv_prog_cc_c89" != "xno" && break
-done
-rm -f conftest.$ac_ext
-CC=$ac_save_CC
-
-fi
-# AC_CACHE_VAL
-case "x$ac_cv_prog_cc_c89" in
- x)
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
-$as_echo "none needed" >&6; } ;;
- xno)
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
-$as_echo "unsupported" >&6; } ;;
- *)
- CC="$CC $ac_cv_prog_cc_c89"
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
-$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
-esac
-if test "x$ac_cv_prog_cc_c89" != xno; then :
-
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-if test "x$GCC" != "xyes" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler is MSVC" >&5
-$as_echo_n "checking whether compiler is MSVC... " >&6; }
-if ${je_cv_msvc+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
-#ifndef _MSC_VER
- int fail-1;
-#endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_msvc=yes
-else
- je_cv_msvc=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_msvc" >&5
-$as_echo "$je_cv_msvc" >&6; }
-fi
-
-je_cv_cray_prgenv_wrapper=""
-if test "x${PE_ENV}" != "x" ; then
- case "${CC}" in
- CC|cc)
- je_cv_cray_prgenv_wrapper="yes"
- ;;
- *)
- ;;
- esac
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler is cray" >&5
-$as_echo_n "checking whether compiler is cray... " >&6; }
-if ${je_cv_cray+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
-#ifndef _CRAYC
- int fail-1;
-#endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cray=yes
-else
- je_cv_cray=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_cray" >&5
-$as_echo "$je_cv_cray" >&6; }
-
-if test "x${je_cv_cray}" = "xyes" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether cray compiler version is 8.4" >&5
-$as_echo_n "checking whether cray compiler version is 8.4... " >&6; }
-if ${je_cv_cray_84+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
-#if !(_RELEASE_MAJOR == 8 && _RELEASE_MINOR == 4)
- int fail-1;
-#endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cray_84=yes
-else
- je_cv_cray_84=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_cray_84" >&5
-$as_echo "$je_cv_cray_84" >&6; }
-fi
-
-if test "x$CFLAGS" = "x" ; then
- no_CFLAGS="yes"
- if test "x$GCC" = "xyes" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -std=gnu11" >&5
-$as_echo_n "checking whether compiler supports -std=gnu11... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-std=gnu11"
-else
- CFLAGS="${CFLAGS} -std=gnu11"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-std=gnu11
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- if test "x$je_cv_cflags_appended" = "x-std=gnu11" ; then
- cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_HAS_RESTRICT 1
-_ACEOF
-
- else
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -std=gnu99" >&5
-$as_echo_n "checking whether compiler supports -std=gnu99... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-std=gnu99"
-else
- CFLAGS="${CFLAGS} -std=gnu99"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-std=gnu99
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- if test "x$je_cv_cflags_appended" = "x-std=gnu99" ; then
- cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_HAS_RESTRICT 1
-_ACEOF
-
- fi
- fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Wall" >&5
-$as_echo_n "checking whether compiler supports -Wall... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Wall"
-else
- CFLAGS="${CFLAGS} -Wall"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Wall
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Werror=declaration-after-statement" >&5
-$as_echo_n "checking whether compiler supports -Werror=declaration-after-statement... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Werror=declaration-after-statement"
-else
- CFLAGS="${CFLAGS} -Werror=declaration-after-statement"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Werror=declaration-after-statement
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Wshorten-64-to-32" >&5
-$as_echo_n "checking whether compiler supports -Wshorten-64-to-32... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Wshorten-64-to-32"
-else
- CFLAGS="${CFLAGS} -Wshorten-64-to-32"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Wshorten-64-to-32
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Wsign-compare" >&5
-$as_echo_n "checking whether compiler supports -Wsign-compare... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Wsign-compare"
-else
- CFLAGS="${CFLAGS} -Wsign-compare"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Wsign-compare
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -pipe" >&5
-$as_echo_n "checking whether compiler supports -pipe... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-pipe"
-else
- CFLAGS="${CFLAGS} -pipe"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-pipe
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -g3" >&5
-$as_echo_n "checking whether compiler supports -g3... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-g3"
-else
- CFLAGS="${CFLAGS} -g3"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-g3
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- elif test "x$je_cv_msvc" = "xyes" ; then
- CC="$CC -nologo"
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Zi" >&5
-$as_echo_n "checking whether compiler supports -Zi... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Zi"
-else
- CFLAGS="${CFLAGS} -Zi"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Zi
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -MT" >&5
-$as_echo_n "checking whether compiler supports -MT... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-MT"
-else
- CFLAGS="${CFLAGS} -MT"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-MT
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -W3" >&5
-$as_echo_n "checking whether compiler supports -W3... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-W3"
-else
- CFLAGS="${CFLAGS} -W3"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-W3
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -FS" >&5
-$as_echo_n "checking whether compiler supports -FS... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-FS"
-else
- CFLAGS="${CFLAGS} -FS"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-FS
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- CPPFLAGS="$CPPFLAGS -I${srcdir}/include/msvc_compat"
- fi
- if test "x$je_cv_cray" = "xyes" ; then
- if test "x$je_cv_cray_84" = "xyes" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -hipa2" >&5
-$as_echo_n "checking whether compiler supports -hipa2... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-hipa2"
-else
- CFLAGS="${CFLAGS} -hipa2"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-hipa2
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -hnognu" >&5
-$as_echo_n "checking whether compiler supports -hnognu... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-hnognu"
-else
- CFLAGS="${CFLAGS} -hnognu"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-hnognu
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- fi
- if test "x$enable_cc_silence" != "xno" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -hnomessage=128" >&5
-$as_echo_n "checking whether compiler supports -hnomessage=128... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-hnomessage=128"
-else
- CFLAGS="${CFLAGS} -hnomessage=128"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-hnomessage=128
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -hnomessage=1357" >&5
-$as_echo_n "checking whether compiler supports -hnomessage=1357... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-hnomessage=1357"
-else
- CFLAGS="${CFLAGS} -hnomessage=1357"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-hnomessage=1357
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- fi
- fi
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
-$as_echo_n "checking how to run the C preprocessor... " >&6; }
-# On Suns, sometimes $CPP names a directory.
-if test -n "$CPP" && test -d "$CPP"; then
- CPP=
-fi
-if test -z "$CPP"; then
- if ${ac_cv_prog_CPP+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- # Double quotes because CPP needs to be expanded
- for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
- do
- ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
- # Use a header file that comes with gcc, so configuring glibc
- # with a fresh cross-compiler works.
- # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
- # <limits.h> exists even on freestanding compilers.
- # On the NeXT, cc -E runs the code through the compiler's parser,
- # not just through cpp. "Syntax error" is here to catch this case.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
- Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
- # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
- # OK, works on sane cases. Now check whether nonexistent headers
- # can be detected and how.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
- # Broken: success on invalid input.
-continue
-else
- # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
- break
-fi
-
- done
- ac_cv_prog_CPP=$CPP
-
-fi
- CPP=$ac_cv_prog_CPP
-else
- ac_cv_prog_CPP=$CPP
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
-$as_echo "$CPP" >&6; }
-ac_preproc_ok=false
-for ac_c_preproc_warn_flag in '' yes
-do
- # Use a header file that comes with gcc, so configuring glibc
- # with a fresh cross-compiler works.
- # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
- # <limits.h> exists even on freestanding compilers.
- # On the NeXT, cc -E runs the code through the compiler's parser,
- # not just through cpp. "Syntax error" is here to catch this case.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#ifdef __STDC__
-# include <limits.h>
-#else
-# include <assert.h>
-#endif
- Syntax error
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
-
-else
- # Broken: fails on valid input.
-continue
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
- # OK, works on sane cases. Now check whether nonexistent headers
- # can be detected and how.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <ac_nonexistent.h>
-_ACEOF
-if ac_fn_c_try_cpp "$LINENO"; then :
- # Broken: success on invalid input.
-continue
-else
- # Passes both tests.
-ac_preproc_ok=:
-break
-fi
-rm -f conftest.err conftest.i conftest.$ac_ext
-
-done
-# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
-rm -f conftest.i conftest.err conftest.$ac_ext
-if $ac_preproc_ok; then :
-
-else
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
-$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
-if ${ac_cv_path_GREP+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -z "$GREP"; then
- ac_path_GREP_found=false
- # Loop through the user's path and test for each of PROGNAME-LIST
- as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_prog in grep ggrep; do
- for ac_exec_ext in '' $ac_executable_extensions; do
- ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
- as_fn_executable_p "$ac_path_GREP" || continue
-# Check for GNU ac_path_GREP and select it if it is found.
- # Check for GNU $ac_path_GREP
-case `"$ac_path_GREP" --version 2>&1` in
-*GNU*)
- ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
-*)
- ac_count=0
- $as_echo_n 0123456789 >"conftest.in"
- while :
- do
- cat "conftest.in" "conftest.in" >"conftest.tmp"
- mv "conftest.tmp" "conftest.in"
- cp "conftest.in" "conftest.nl"
- $as_echo 'GREP' >> "conftest.nl"
- "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
- diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
- as_fn_arith $ac_count + 1 && ac_count=$as_val
- if test $ac_count -gt ${ac_path_GREP_max-0}; then
- # Best one so far, save it but keep looking for a better one
- ac_cv_path_GREP="$ac_path_GREP"
- ac_path_GREP_max=$ac_count
- fi
- # 10*(2^10) chars as input seems more than enough
- test $ac_count -gt 10 && break
- done
- rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
- $ac_path_GREP_found && break 3
- done
- done
- done
-IFS=$as_save_IFS
- if test -z "$ac_cv_path_GREP"; then
- as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
- fi
-else
- ac_cv_path_GREP=$GREP
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
-$as_echo "$ac_cv_path_GREP" >&6; }
- GREP="$ac_cv_path_GREP"
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
-$as_echo_n "checking for egrep... " >&6; }
-if ${ac_cv_path_EGREP+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
- then ac_cv_path_EGREP="$GREP -E"
- else
- if test -z "$EGREP"; then
- ac_path_EGREP_found=false
- # Loop through the user's path and test for each of PROGNAME-LIST
- as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_prog in egrep; do
- for ac_exec_ext in '' $ac_executable_extensions; do
- ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
- as_fn_executable_p "$ac_path_EGREP" || continue
-# Check for GNU ac_path_EGREP and select it if it is found.
- # Check for GNU $ac_path_EGREP
-case `"$ac_path_EGREP" --version 2>&1` in
-*GNU*)
- ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
-*)
- ac_count=0
- $as_echo_n 0123456789 >"conftest.in"
- while :
- do
- cat "conftest.in" "conftest.in" >"conftest.tmp"
- mv "conftest.tmp" "conftest.in"
- cp "conftest.in" "conftest.nl"
- $as_echo 'EGREP' >> "conftest.nl"
- "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
- diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
- as_fn_arith $ac_count + 1 && ac_count=$as_val
- if test $ac_count -gt ${ac_path_EGREP_max-0}; then
- # Best one so far, save it but keep looking for a better one
- ac_cv_path_EGREP="$ac_path_EGREP"
- ac_path_EGREP_max=$ac_count
- fi
- # 10*(2^10) chars as input seems more than enough
- test $ac_count -gt 10 && break
- done
- rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
-esac
-
- $ac_path_EGREP_found && break 3
- done
- done
- done
-IFS=$as_save_IFS
- if test -z "$ac_cv_path_EGREP"; then
- as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
- fi
-else
- ac_cv_path_EGREP=$EGREP
-fi
-
- fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
-$as_echo "$ac_cv_path_EGREP" >&6; }
- EGREP="$ac_cv_path_EGREP"
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
-$as_echo_n "checking for ANSI C header files... " >&6; }
-if ${ac_cv_header_stdc+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_header_stdc=yes
-else
- ac_cv_header_stdc=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-if test $ac_cv_header_stdc = yes; then
- # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <string.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- $EGREP "memchr" >/dev/null 2>&1; then :
-
-else
- ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
- # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <stdlib.h>
-
-_ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
- $EGREP "free" >/dev/null 2>&1; then :
-
-else
- ac_cv_header_stdc=no
-fi
-rm -f conftest*
-
-fi
-
-if test $ac_cv_header_stdc = yes; then
- # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
- if test "$cross_compiling" = yes; then :
- :
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <ctype.h>
-#include <stdlib.h>
-#if ((' ' & 0x0FF) == 0x020)
-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#else
-# define ISLOWER(c) \
- (('a' <= (c) && (c) <= 'i') \
- || ('j' <= (c) && (c) <= 'r') \
- || ('s' <= (c) && (c) <= 'z'))
-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
-#endif
-
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int
-main ()
-{
- int i;
- for (i = 0; i < 256; i++)
- if (XOR (islower (i), ISLOWER (i))
- || toupper (i) != TOUPPER (i))
- return 2;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-
-else
- ac_cv_header_stdc=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
- conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
-$as_echo "$ac_cv_header_stdc" >&6; }
-if test $ac_cv_header_stdc = yes; then
-
-$as_echo "#define STDC_HEADERS 1" >>confdefs.h
-
-fi
-
-# On IRIX 5.3, sys/types and inttypes.h are conflicting.
-for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
- inttypes.h stdint.h unistd.h
-do :
- as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
-ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
-"
-if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
- cat >>confdefs.h <<_ACEOF
-#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
-_ACEOF
-
-fi
-
-done
-
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5
-$as_echo_n "checking whether byte ordering is bigendian... " >&6; }
-if ${ac_cv_c_bigendian+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_cv_c_bigendian=unknown
- # See if we're dealing with a universal compiler.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#ifndef __APPLE_CC__
- not a universal capable compiler
- #endif
- typedef int dummy;
-
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
- # Check for potential -arch flags. It is not universal unless
- # there are at least two -arch flags with different values.
- ac_arch=
- ac_prev=
- for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do
- if test -n "$ac_prev"; then
- case $ac_word in
- i?86 | x86_64 | ppc | ppc64)
- if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then
- ac_arch=$ac_word
- else
- ac_cv_c_bigendian=universal
- break
- fi
- ;;
- esac
- ac_prev=
- elif test "x$ac_word" = "x-arch"; then
- ac_prev=arch
- fi
- done
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- if test $ac_cv_c_bigendian = unknown; then
- # See if sys/param.h defines the BYTE_ORDER macro.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <sys/types.h>
- #include <sys/param.h>
-
-int
-main ()
-{
-#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \
- && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \
- && LITTLE_ENDIAN)
- bogus endian macros
- #endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- # It does; now see whether it defined to BIG_ENDIAN or not.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <sys/types.h>
- #include <sys/param.h>
-
-int
-main ()
-{
-#if BYTE_ORDER != BIG_ENDIAN
- not big endian
- #endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_c_bigendian=yes
-else
- ac_cv_c_bigendian=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- fi
- if test $ac_cv_c_bigendian = unknown; then
- # See if <limits.h> defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris).
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <limits.h>
-
-int
-main ()
-{
-#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN)
- bogus endian macros
- #endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- # It does; now see whether it defined to _BIG_ENDIAN or not.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <limits.h>
-
-int
-main ()
-{
-#ifndef _BIG_ENDIAN
- not big endian
- #endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_c_bigendian=yes
-else
- ac_cv_c_bigendian=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- fi
- if test $ac_cv_c_bigendian = unknown; then
- # Compile a test program.
- if test "$cross_compiling" = yes; then :
- # Try to guess by grepping values from an object file.
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-short int ascii_mm[] =
- { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 };
- short int ascii_ii[] =
- { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 };
- int use_ascii (int i) {
- return ascii_mm[i] + ascii_ii[i];
- }
- short int ebcdic_ii[] =
- { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 };
- short int ebcdic_mm[] =
- { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 };
- int use_ebcdic (int i) {
- return ebcdic_mm[i] + ebcdic_ii[i];
- }
- extern int foo;
-
-int
-main ()
-{
-return use_ascii (foo) == use_ebcdic (foo);
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then
- ac_cv_c_bigendian=yes
- fi
- if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then
- if test "$ac_cv_c_bigendian" = unknown; then
- ac_cv_c_bigendian=no
- else
- # finding both strings is unlikely to happen, but who knows?
- ac_cv_c_bigendian=unknown
- fi
- fi
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-$ac_includes_default
-int
-main ()
-{
-
- /* Are we little or big endian? From Harbison&Steele. */
- union
- {
- long int l;
- char c[sizeof (long int)];
- } u;
- u.l = 1;
- return u.c[sizeof (long int) - 1] == 1;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
- ac_cv_c_bigendian=no
-else
- ac_cv_c_bigendian=yes
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
- conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
- fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5
-$as_echo "$ac_cv_c_bigendian" >&6; }
- case $ac_cv_c_bigendian in #(
- yes)
- ac_cv_big_endian=1;; #(
- no)
- ac_cv_big_endian=0 ;; #(
- universal)
-
-$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h
-
- ;; #(
- *)
- as_fn_error $? "unknown endianness
- presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;;
- esac
-
-if test "x${ac_cv_big_endian}" = "x1" ; then
- cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_BIG_ENDIAN
-_ACEOF
-
-fi
-
-if test "x${je_cv_msvc}" = "xyes" -a "x${ac_cv_header_inttypes_h}" = "xno"; then
- CPPFLAGS="$CPPFLAGS -I${srcdir}/include/msvc_compat/C99"
-fi
-
-if test "x${je_cv_msvc}" = "xyes" ; then
- LG_SIZEOF_PTR=LG_SIZEOF_PTR_WIN
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: Using a predefined value for sizeof(void *): 4 for 32-bit, 8 for 64-bit" >&5
-$as_echo "Using a predefined value for sizeof(void *): 4 for 32-bit, 8 for 64-bit" >&6; }
-else
- # The cast to long int works around a bug in the HP C Compiler
-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
-# This bug is HP SR number 8606223364.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of void *" >&5
-$as_echo_n "checking size of void *... " >&6; }
-if ${ac_cv_sizeof_void_p+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (void *))" "ac_cv_sizeof_void_p" "$ac_includes_default"; then :
-
-else
- if test "$ac_cv_type_void_p" = yes; then
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "cannot compute sizeof (void *)
-See \`config.log' for more details" "$LINENO" 5; }
- else
- ac_cv_sizeof_void_p=0
- fi
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_void_p" >&5
-$as_echo "$ac_cv_sizeof_void_p" >&6; }
-
-
-
-cat >>confdefs.h <<_ACEOF
-#define SIZEOF_VOID_P $ac_cv_sizeof_void_p
-_ACEOF
-
-
- if test "x${ac_cv_sizeof_void_p}" = "x8" ; then
- LG_SIZEOF_PTR=3
- elif test "x${ac_cv_sizeof_void_p}" = "x4" ; then
- LG_SIZEOF_PTR=2
- else
- as_fn_error $? "Unsupported pointer size: ${ac_cv_sizeof_void_p}" "$LINENO" 5
- fi
-fi
-cat >>confdefs.h <<_ACEOF
-#define LG_SIZEOF_PTR $LG_SIZEOF_PTR
-_ACEOF
-
-
-# The cast to long int works around a bug in the HP C Compiler
-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
-# This bug is HP SR number 8606223364.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of int" >&5
-$as_echo_n "checking size of int... " >&6; }
-if ${ac_cv_sizeof_int+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (int))" "ac_cv_sizeof_int" "$ac_includes_default"; then :
-
-else
- if test "$ac_cv_type_int" = yes; then
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "cannot compute sizeof (int)
-See \`config.log' for more details" "$LINENO" 5; }
- else
- ac_cv_sizeof_int=0
- fi
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_int" >&5
-$as_echo "$ac_cv_sizeof_int" >&6; }
-
-
-
-cat >>confdefs.h <<_ACEOF
-#define SIZEOF_INT $ac_cv_sizeof_int
-_ACEOF
-
-
-if test "x${ac_cv_sizeof_int}" = "x8" ; then
- LG_SIZEOF_INT=3
-elif test "x${ac_cv_sizeof_int}" = "x4" ; then
- LG_SIZEOF_INT=2
-else
- as_fn_error $? "Unsupported int size: ${ac_cv_sizeof_int}" "$LINENO" 5
-fi
-cat >>confdefs.h <<_ACEOF
-#define LG_SIZEOF_INT $LG_SIZEOF_INT
-_ACEOF
-
-
-# The cast to long int works around a bug in the HP C Compiler
-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
-# This bug is HP SR number 8606223364.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long" >&5
-$as_echo_n "checking size of long... " >&6; }
-if ${ac_cv_sizeof_long+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long))" "ac_cv_sizeof_long" "$ac_includes_default"; then :
-
-else
- if test "$ac_cv_type_long" = yes; then
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "cannot compute sizeof (long)
-See \`config.log' for more details" "$LINENO" 5; }
- else
- ac_cv_sizeof_long=0
- fi
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long" >&5
-$as_echo "$ac_cv_sizeof_long" >&6; }
-
-
-
-cat >>confdefs.h <<_ACEOF
-#define SIZEOF_LONG $ac_cv_sizeof_long
-_ACEOF
-
-
-if test "x${ac_cv_sizeof_long}" = "x8" ; then
- LG_SIZEOF_LONG=3
-elif test "x${ac_cv_sizeof_long}" = "x4" ; then
- LG_SIZEOF_LONG=2
-else
- as_fn_error $? "Unsupported long size: ${ac_cv_sizeof_long}" "$LINENO" 5
-fi
-cat >>confdefs.h <<_ACEOF
-#define LG_SIZEOF_LONG $LG_SIZEOF_LONG
-_ACEOF
-
-
-# The cast to long int works around a bug in the HP C Compiler
-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
-# This bug is HP SR number 8606223364.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long long" >&5
-$as_echo_n "checking size of long long... " >&6; }
-if ${ac_cv_sizeof_long_long+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long long))" "ac_cv_sizeof_long_long" "$ac_includes_default"; then :
-
-else
- if test "$ac_cv_type_long_long" = yes; then
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "cannot compute sizeof (long long)
-See \`config.log' for more details" "$LINENO" 5; }
- else
- ac_cv_sizeof_long_long=0
- fi
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_long" >&5
-$as_echo "$ac_cv_sizeof_long_long" >&6; }
-
-
-
-cat >>confdefs.h <<_ACEOF
-#define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long
-_ACEOF
-
-
-if test "x${ac_cv_sizeof_long_long}" = "x8" ; then
- LG_SIZEOF_LONG_LONG=3
-elif test "x${ac_cv_sizeof_long_long}" = "x4" ; then
- LG_SIZEOF_LONG_LONG=2
-else
- as_fn_error $? "Unsupported long long size: ${ac_cv_sizeof_long_long}" "$LINENO" 5
-fi
-cat >>confdefs.h <<_ACEOF
-#define LG_SIZEOF_LONG_LONG $LG_SIZEOF_LONG_LONG
-_ACEOF
-
-
-# The cast to long int works around a bug in the HP C Compiler
-# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
-# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
-# This bug is HP SR number 8606223364.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking size of intmax_t" >&5
-$as_echo_n "checking size of intmax_t... " >&6; }
-if ${ac_cv_sizeof_intmax_t+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (intmax_t))" "ac_cv_sizeof_intmax_t" "$ac_includes_default"; then :
-
-else
- if test "$ac_cv_type_intmax_t" = yes; then
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "cannot compute sizeof (intmax_t)
-See \`config.log' for more details" "$LINENO" 5; }
- else
- ac_cv_sizeof_intmax_t=0
- fi
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_intmax_t" >&5
-$as_echo "$ac_cv_sizeof_intmax_t" >&6; }
-
-
-
-cat >>confdefs.h <<_ACEOF
-#define SIZEOF_INTMAX_T $ac_cv_sizeof_intmax_t
-_ACEOF
-
-
-if test "x${ac_cv_sizeof_intmax_t}" = "x16" ; then
- LG_SIZEOF_INTMAX_T=4
-elif test "x${ac_cv_sizeof_intmax_t}" = "x8" ; then
- LG_SIZEOF_INTMAX_T=3
-elif test "x${ac_cv_sizeof_intmax_t}" = "x4" ; then
- LG_SIZEOF_INTMAX_T=2
-else
- as_fn_error $? "Unsupported intmax_t size: ${ac_cv_sizeof_intmax_t}" "$LINENO" 5
-fi
-cat >>confdefs.h <<_ACEOF
-#define LG_SIZEOF_INTMAX_T $LG_SIZEOF_INTMAX_T
-_ACEOF
-
-
-# Make sure we can run config.sub.
-$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
- as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
-$as_echo_n "checking build system type... " >&6; }
-if ${ac_cv_build+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_build_alias=$build_alias
-test "x$ac_build_alias" = x &&
- ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
-test "x$ac_build_alias" = x &&
- as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5
-ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` ||
- as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5
-$as_echo "$ac_cv_build" >&6; }
-case $ac_cv_build in
-*-*-*) ;;
-*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;
-esac
-build=$ac_cv_build
-ac_save_IFS=$IFS; IFS='-'
-set x $ac_cv_build
-shift
-build_cpu=$1
-build_vendor=$2
-shift; shift
-# Remember, the first character of IFS is used to create $*,
-# except with old shells:
-build_os=$*
-IFS=$ac_save_IFS
-case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
-$as_echo_n "checking host system type... " >&6; }
-if ${ac_cv_host+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test "x$host_alias" = x; then
- ac_cv_host=$ac_cv_build
-else
- ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
- as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5
-$as_echo "$ac_cv_host" >&6; }
-case $ac_cv_host in
-*-*-*) ;;
-*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;
-esac
-host=$ac_cv_host
-ac_save_IFS=$IFS; IFS='-'
-set x $ac_cv_host
-shift
-host_cpu=$1
-host_vendor=$2
-shift; shift
-# Remember, the first character of IFS is used to create $*,
-# except with old shells:
-host_os=$*
-IFS=$ac_save_IFS
-case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
-
-
-CPU_SPINWAIT=""
-case "${host_cpu}" in
- i686|x86_64)
- if test "x${je_cv_msvc}" = "xyes" ; then
- if ${je_cv_pause_msvc+:} false; then :
- $as_echo_n "(cached) " >&6
-else
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pause instruction MSVC is compilable" >&5
-$as_echo_n "checking whether pause instruction MSVC is compilable... " >&6; }
-if ${je_cv_pause_msvc+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-_mm_pause(); return 0;
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_pause_msvc=yes
-else
- je_cv_pause_msvc=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_pause_msvc" >&5
-$as_echo "$je_cv_pause_msvc" >&6; }
-
-fi
-
- if test "x${je_cv_pause_msvc}" = "xyes" ; then
- CPU_SPINWAIT='_mm_pause()'
- fi
- else
- if ${je_cv_pause+:} false; then :
- $as_echo_n "(cached) " >&6
-else
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pause instruction is compilable" >&5
-$as_echo_n "checking whether pause instruction is compilable... " >&6; }
-if ${je_cv_pause+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-__asm__ volatile("pause"); return 0;
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_pause=yes
-else
- je_cv_pause=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_pause" >&5
-$as_echo "$je_cv_pause" >&6; }
-
-fi
-
- if test "x${je_cv_pause}" = "xyes" ; then
- CPU_SPINWAIT='__asm__ volatile("pause")'
- fi
- fi
- ;;
- powerpc)
- cat >>confdefs.h <<_ACEOF
-#define HAVE_ALTIVEC
-_ACEOF
-
- ;;
- *)
- ;;
-esac
-cat >>confdefs.h <<_ACEOF
-#define CPU_SPINWAIT $CPU_SPINWAIT
-_ACEOF
-
-
-LD_PRELOAD_VAR="LD_PRELOAD"
-so="so"
-importlib="${so}"
-o="$ac_objext"
-a="a"
-exe="$ac_exeext"
-libprefix="lib"
-link_whole_archive="0"
-DSO_LDFLAGS='-shared -Wl,-soname,$(@F)'
-RPATH='-Wl,-rpath,$(1)'
-SOREV="${so}.${rev}"
-PIC_CFLAGS='-fPIC -DPIC'
-CTARGET='-o $@'
-LDTARGET='-o $@'
-TEST_LD_MODE=
-EXTRA_LDFLAGS=
-ARFLAGS='crus'
-AROUT=' $@'
-CC_MM=1
-
-if test "x$je_cv_cray_prgenv_wrapper" = "xyes" ; then
- TEST_LD_MODE='-dynamic'
-fi
-
-if test "x${je_cv_cray}" = "xyes" ; then
- CC_MM=
-fi
-
-
-
-
-if test -n "$ac_tool_prefix"; then
- # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ar; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_AR+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$AR"; then
- ac_cv_prog_AR="$AR" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_AR="${ac_tool_prefix}ar"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-AR=$ac_cv_prog_AR
-if test -n "$AR"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5
-$as_echo "$AR" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_AR"; then
- ac_ct_AR=$AR
- # Extract the first word of "ar", so it can be a program name with args.
-set dummy ar; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_AR+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$ac_ct_AR"; then
- ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_ac_ct_AR="ar"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_AR=$ac_cv_prog_ac_ct_AR
-if test -n "$ac_ct_AR"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5
-$as_echo "$ac_ct_AR" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
- if test "x$ac_ct_AR" = x; then
- AR=":"
- else
- case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
- AR=$ac_ct_AR
- fi
-else
- AR="$ac_cv_prog_AR"
-fi
-
-
-CFLAGS="$CFLAGS"
-default_munmap="1"
-maps_coalesce="1"
-case "${host}" in
- *-*-darwin* | *-*-ios*)
- abi="macho"
- $as_echo "#define JEMALLOC_PURGE_MADVISE_FREE " >>confdefs.h
-
- RPATH=""
- LD_PRELOAD_VAR="DYLD_INSERT_LIBRARIES"
- so="dylib"
- importlib="${so}"
- force_tls="0"
- DSO_LDFLAGS='-shared -Wl,-install_name,$(LIBDIR)/$(@F)'
- SOREV="${rev}.${so}"
- sbrk_deprecated="1"
- ;;
- *-*-freebsd*)
- abi="elf"
- $as_echo "#define JEMALLOC_SYSCTL_VM_OVERCOMMIT " >>confdefs.h
-
- $as_echo "#define JEMALLOC_PURGE_MADVISE_FREE " >>confdefs.h
-
- force_lazy_lock="1"
- ;;
- *-*-dragonfly*)
- abi="elf"
- $as_echo "#define JEMALLOC_PURGE_MADVISE_FREE " >>confdefs.h
-
- ;;
- *-*-openbsd*)
- abi="elf"
- $as_echo "#define JEMALLOC_PURGE_MADVISE_FREE " >>confdefs.h
-
- force_tls="0"
- ;;
- *-*-bitrig*)
- abi="elf"
- $as_echo "#define JEMALLOC_PURGE_MADVISE_FREE " >>confdefs.h
-
- ;;
- *-*-linux*)
- CPPFLAGS="$CPPFLAGS -D_GNU_SOURCE"
- abi="elf"
- $as_echo "#define JEMALLOC_HAS_ALLOCA_H 1" >>confdefs.h
-
- $as_echo "#define JEMALLOC_PROC_SYS_VM_OVERCOMMIT_MEMORY " >>confdefs.h
-
- $as_echo "#define JEMALLOC_PURGE_MADVISE_DONTNEED " >>confdefs.h
-
- $as_echo "#define JEMALLOC_THREADED_INIT " >>confdefs.h
-
- $as_echo "#define JEMALLOC_USE_CXX_THROW " >>confdefs.h
-
- default_munmap="0"
- ;;
- *-*-netbsd*)
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking ABI" >&5
-$as_echo_n "checking ABI... " >&6; }
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#ifdef __ELF__
-/* ELF */
-#else
-#error aout
-#endif
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- abi="elf"
-else
- abi="aout"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $abi" >&5
-$as_echo "$abi" >&6; }
- $as_echo "#define JEMALLOC_PURGE_MADVISE_FREE " >>confdefs.h
-
- ;;
- *-*-solaris2*)
- abi="elf"
- $as_echo "#define JEMALLOC_PURGE_MADVISE_FREE " >>confdefs.h
-
- RPATH='-Wl,-R,$(1)'
- CPPFLAGS="$CPPFLAGS -D_POSIX_PTHREAD_SEMANTICS"
- LIBS="$LIBS -lposix4 -lsocket -lnsl"
- ;;
- *-ibm-aix*)
- if "$LG_SIZEOF_PTR" = "8"; then
- LD_PRELOAD_VAR="LDR_PRELOAD64"
- else
- LD_PRELOAD_VAR="LDR_PRELOAD"
- fi
- abi="xcoff"
- ;;
- *-*-mingw* | *-*-cygwin*)
- abi="pecoff"
- force_tls="0"
- maps_coalesce="0"
- RPATH=""
- so="dll"
- if test "x$je_cv_msvc" = "xyes" ; then
- importlib="lib"
- DSO_LDFLAGS="-LD"
- EXTRA_LDFLAGS="-link -DEBUG"
- CTARGET='-Fo$@'
- LDTARGET='-Fe$@'
- AR='lib'
- ARFLAGS='-nologo -out:'
- AROUT='$@'
- CC_MM=
- else
- importlib="${so}"
- DSO_LDFLAGS="-shared"
- link_whole_archive="1"
- fi
- a="lib"
- libprefix=""
- SOREV="${so}"
- PIC_CFLAGS=""
- ;;
- *)
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: Unsupported operating system: ${host}" >&5
-$as_echo "Unsupported operating system: ${host}" >&6; }
- abi="elf"
- ;;
-esac
-
-JEMALLOC_USABLE_SIZE_CONST=const
-for ac_header in malloc.h
-do :
- ac_fn_c_check_header_mongrel "$LINENO" "malloc.h" "ac_cv_header_malloc_h" "$ac_includes_default"
-if test "x$ac_cv_header_malloc_h" = xyes; then :
- cat >>confdefs.h <<_ACEOF
-#define HAVE_MALLOC_H 1
-_ACEOF
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether malloc_usable_size definition can use const argument" >&5
-$as_echo_n "checking whether malloc_usable_size definition can use const argument... " >&6; }
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <malloc.h>
- #include <stddef.h>
- size_t malloc_usable_size(const void *ptr);
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-
-else
-
- JEMALLOC_USABLE_SIZE_CONST=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-fi
-
-done
-
-cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_USABLE_SIZE_CONST $JEMALLOC_USABLE_SIZE_CONST
-_ACEOF
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing log" >&5
-$as_echo_n "checking for library containing log... " >&6; }
-if ${ac_cv_search_log+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char log ();
-int
-main ()
-{
-return log ();
- ;
- return 0;
-}
-_ACEOF
-for ac_lib in '' m; do
- if test -z "$ac_lib"; then
- ac_res="none required"
- else
- ac_res=-l$ac_lib
- LIBS="-l$ac_lib $ac_func_search_save_LIBS"
- fi
- if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_search_log=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext
- if ${ac_cv_search_log+:} false; then :
- break
-fi
-done
-if ${ac_cv_search_log+:} false; then :
-
-else
- ac_cv_search_log=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_log" >&5
-$as_echo "$ac_cv_search_log" >&6; }
-ac_res=$ac_cv_search_log
-if test "$ac_res" != no; then :
- test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-else
- as_fn_error $? "Missing math functions" "$LINENO" 5
-fi
-
-if test "x$ac_cv_search_log" != "xnone required" ; then
- LM="$ac_cv_search_log"
-else
- LM=
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether __attribute__ syntax is compilable" >&5
-$as_echo_n "checking whether __attribute__ syntax is compilable... " >&6; }
-if ${je_cv_attribute+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-static __attribute__((unused)) void foo(void){}
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_attribute=yes
-else
- je_cv_attribute=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_attribute" >&5
-$as_echo "$je_cv_attribute" >&6; }
-
-if test "x${je_cv_attribute}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_ATTR " >>confdefs.h
-
- if test "x${GCC}" = "xyes" -a "x${abi}" = "xelf"; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -fvisibility=hidden" >&5
-$as_echo_n "checking whether compiler supports -fvisibility=hidden... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-fvisibility=hidden"
-else
- CFLAGS="${CFLAGS} -fvisibility=hidden"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-fvisibility=hidden
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- fi
-fi
-SAVED_CFLAGS="${CFLAGS}"
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Werror" >&5
-$as_echo_n "checking whether compiler supports -Werror... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Werror"
-else
- CFLAGS="${CFLAGS} -Werror"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Werror
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -herror_on_warning" >&5
-$as_echo_n "checking whether compiler supports -herror_on_warning... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-herror_on_warning"
-else
- CFLAGS="${CFLAGS} -herror_on_warning"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-herror_on_warning
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether tls_model attribute is compilable" >&5
-$as_echo_n "checking whether tls_model attribute is compilable... " >&6; }
-if ${je_cv_tls_model+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-static __thread int
- __attribute__((tls_model("initial-exec"), unused)) foo;
- foo = 0;
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_tls_model=yes
-else
- je_cv_tls_model=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_tls_model" >&5
-$as_echo "$je_cv_tls_model" >&6; }
-
-CFLAGS="${SAVED_CFLAGS}"
-if test "x${je_cv_tls_model}" = "xyes" ; then
- $as_echo "#define JEMALLOC_TLS_MODEL __attribute__((tls_model(\"initial-exec\")))" >>confdefs.h
-
-else
- $as_echo "#define JEMALLOC_TLS_MODEL " >>confdefs.h
-
-fi
-SAVED_CFLAGS="${CFLAGS}"
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Werror" >&5
-$as_echo_n "checking whether compiler supports -Werror... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Werror"
-else
- CFLAGS="${CFLAGS} -Werror"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Werror
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -herror_on_warning" >&5
-$as_echo_n "checking whether compiler supports -herror_on_warning... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-herror_on_warning"
-else
- CFLAGS="${CFLAGS} -herror_on_warning"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-herror_on_warning
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether alloc_size attribute is compilable" >&5
-$as_echo_n "checking whether alloc_size attribute is compilable... " >&6; }
-if ${je_cv_alloc_size+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <stdlib.h>
-int
-main ()
-{
-void *foo(size_t size) __attribute__((alloc_size(1)));
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_alloc_size=yes
-else
- je_cv_alloc_size=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_alloc_size" >&5
-$as_echo "$je_cv_alloc_size" >&6; }
-
-CFLAGS="${SAVED_CFLAGS}"
-if test "x${je_cv_alloc_size}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_ATTR_ALLOC_SIZE " >>confdefs.h
-
-fi
-SAVED_CFLAGS="${CFLAGS}"
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Werror" >&5
-$as_echo_n "checking whether compiler supports -Werror... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Werror"
-else
- CFLAGS="${CFLAGS} -Werror"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Werror
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -herror_on_warning" >&5
-$as_echo_n "checking whether compiler supports -herror_on_warning... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-herror_on_warning"
-else
- CFLAGS="${CFLAGS} -herror_on_warning"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-herror_on_warning
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether format(gnu_printf, ...) attribute is compilable" >&5
-$as_echo_n "checking whether format(gnu_printf, ...) attribute is compilable... " >&6; }
-if ${je_cv_format_gnu_printf+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <stdlib.h>
-int
-main ()
-{
-void *foo(const char *format, ...) __attribute__((format(gnu_printf, 1, 2)));
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_format_gnu_printf=yes
-else
- je_cv_format_gnu_printf=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_format_gnu_printf" >&5
-$as_echo "$je_cv_format_gnu_printf" >&6; }
-
-CFLAGS="${SAVED_CFLAGS}"
-if test "x${je_cv_format_gnu_printf}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_ATTR_FORMAT_GNU_PRINTF " >>confdefs.h
-
-fi
-SAVED_CFLAGS="${CFLAGS}"
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Werror" >&5
-$as_echo_n "checking whether compiler supports -Werror... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Werror"
-else
- CFLAGS="${CFLAGS} -Werror"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Werror
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -herror_on_warning" >&5
-$as_echo_n "checking whether compiler supports -herror_on_warning... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-herror_on_warning"
-else
- CFLAGS="${CFLAGS} -herror_on_warning"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-herror_on_warning
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether format(printf, ...) attribute is compilable" >&5
-$as_echo_n "checking whether format(printf, ...) attribute is compilable... " >&6; }
-if ${je_cv_format_printf+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <stdlib.h>
-int
-main ()
-{
-void *foo(const char *format, ...) __attribute__((format(printf, 1, 2)));
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_format_printf=yes
-else
- je_cv_format_printf=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_format_printf" >&5
-$as_echo "$je_cv_format_printf" >&6; }
-
-CFLAGS="${SAVED_CFLAGS}"
-if test "x${je_cv_format_printf}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_ATTR_FORMAT_PRINTF " >>confdefs.h
-
-fi
-
-
-# Check whether --with-rpath was given.
-if test "${with_rpath+set}" = set; then :
- withval=$with_rpath; if test "x$with_rpath" = "xno" ; then
- RPATH_EXTRA=
-else
- RPATH_EXTRA="`echo $with_rpath | tr \":\" \" \"`"
-fi
-else
- RPATH_EXTRA=
-
-fi
-
-
-
-# Check whether --enable-autogen was given.
-if test "${enable_autogen+set}" = set; then :
- enableval=$enable_autogen; if test "x$enable_autogen" = "xno" ; then
- enable_autogen="0"
-else
- enable_autogen="1"
-fi
-
-else
- enable_autogen="0"
-
-fi
-
-
-
-# Find a good install program. We prefer a C program (faster),
-# so one script is as good as another. But avoid the broken or
-# incompatible versions:
-# SysV /etc/install, /usr/sbin/install
-# SunOS /usr/etc/install
-# IRIX /sbin/install
-# AIX /bin/install
-# AmigaOS /C/install, which installs bootblocks on floppy discs
-# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag
-# AFS /usr/afsws/bin/install, which mishandles nonexistent args
-# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
-# OS/2's system install, which has a completely different semantic
-# ./install, which can be erroneously created by make from ./install.sh.
-# Reject install programs that cannot install multiple files.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5
-$as_echo_n "checking for a BSD-compatible install... " >&6; }
-if test -z "$INSTALL"; then
-if ${ac_cv_path_install+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- # Account for people who put trailing slashes in PATH elements.
-case $as_dir/ in #((
- ./ | .// | /[cC]/* | \
- /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \
- ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \
- /usr/ucb/* ) ;;
- *)
- # OSF1 and SCO ODT 3.0 have their own names for install.
- # Don't use installbsd from OSF since it installs stuff as root
- # by default.
- for ac_prog in ginstall scoinst install; do
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then
- if test $ac_prog = install &&
- grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
- # AIX install. It has an incompatible calling convention.
- :
- elif test $ac_prog = install &&
- grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
- # program-specific install script used by HP pwplus--don't use.
- :
- else
- rm -rf conftest.one conftest.two conftest.dir
- echo one > conftest.one
- echo two > conftest.two
- mkdir conftest.dir
- if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" &&
- test -s conftest.one && test -s conftest.two &&
- test -s conftest.dir/conftest.one &&
- test -s conftest.dir/conftest.two
- then
- ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c"
- break 3
- fi
- fi
- fi
- done
- done
- ;;
-esac
-
- done
-IFS=$as_save_IFS
-
-rm -rf conftest.one conftest.two conftest.dir
-
-fi
- if test "${ac_cv_path_install+set}" = set; then
- INSTALL=$ac_cv_path_install
- else
- # As a last resort, use the slow shell script. Don't cache a
- # value for INSTALL within a source directory, because that will
- # break other packages using the cache if that directory is
- # removed, or if the value is a relative name.
- INSTALL=$ac_install_sh
- fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5
-$as_echo "$INSTALL" >&6; }
-
-# Use test -z because SunOS4 sh mishandles braces in ${var-val}.
-# It thinks the first close brace ends the variable substitution.
-test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}'
-
-test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}'
-
-test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
-
-if test -n "$ac_tool_prefix"; then
- # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
-set dummy ${ac_tool_prefix}ranlib; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_RANLIB+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$RANLIB"; then
- ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-RANLIB=$ac_cv_prog_RANLIB
-if test -n "$RANLIB"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5
-$as_echo "$RANLIB" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_RANLIB"; then
- ac_ct_RANLIB=$RANLIB
- # Extract the first word of "ranlib", so it can be a program name with args.
-set dummy ranlib; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$ac_ct_RANLIB"; then
- ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_ac_ct_RANLIB="ranlib"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
-if test -n "$ac_ct_RANLIB"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5
-$as_echo "$ac_ct_RANLIB" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
- if test "x$ac_ct_RANLIB" = x; then
- RANLIB=":"
- else
- case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
- RANLIB=$ac_ct_RANLIB
- fi
-else
- RANLIB="$ac_cv_prog_RANLIB"
-fi
-
-# Extract the first word of "ld", so it can be a program name with args.
-set dummy ld; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_LD+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- case $LD in
- [\\/]* | ?:[\\/]*)
- ac_cv_path_LD="$LD" # Let the user override the test with a path.
- ;;
- *)
- as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_path_LD="$as_dir/$ac_word$ac_exec_ext"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
- test -z "$ac_cv_path_LD" && ac_cv_path_LD="false"
- ;;
-esac
-fi
-LD=$ac_cv_path_LD
-if test -n "$LD"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LD" >&5
-$as_echo "$LD" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-# Extract the first word of "autoconf", so it can be a program name with args.
-set dummy autoconf; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_path_AUTOCONF+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- case $AUTOCONF in
- [\\/]* | ?:[\\/]*)
- ac_cv_path_AUTOCONF="$AUTOCONF" # Let the user override the test with a path.
- ;;
- *)
- as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_path_AUTOCONF="$as_dir/$ac_word$ac_exec_ext"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
- test -z "$ac_cv_path_AUTOCONF" && ac_cv_path_AUTOCONF="false"
- ;;
-esac
-fi
-AUTOCONF=$ac_cv_path_AUTOCONF
-if test -n "$AUTOCONF"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AUTOCONF" >&5
-$as_echo "$AUTOCONF" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-
-public_syms="malloc_conf malloc_message malloc calloc posix_memalign aligned_alloc realloc free mallocx rallocx xallocx sallocx dallocx sdallocx nallocx mallctl mallctlnametomib mallctlbymib malloc_stats_print malloc_usable_size"
-
-ac_fn_c_check_func "$LINENO" "memalign" "ac_cv_func_memalign"
-if test "x$ac_cv_func_memalign" = xyes; then :
- $as_echo "#define JEMALLOC_OVERRIDE_MEMALIGN " >>confdefs.h
-
- public_syms="${public_syms} memalign"
-fi
-
-ac_fn_c_check_func "$LINENO" "valloc" "ac_cv_func_valloc"
-if test "x$ac_cv_func_valloc" = xyes; then :
- $as_echo "#define JEMALLOC_OVERRIDE_VALLOC " >>confdefs.h
-
- public_syms="${public_syms} valloc"
-fi
-
-
-GCOV_FLAGS=
-# Check whether --enable-code-coverage was given.
-if test "${enable_code_coverage+set}" = set; then :
- enableval=$enable_code_coverage; if test "x$enable_code_coverage" = "xno" ; then
- enable_code_coverage="0"
-else
- enable_code_coverage="1"
-fi
-
-else
- enable_code_coverage="0"
-
-fi
-
-if test "x$enable_code_coverage" = "x1" ; then
- deoptimize="no"
- echo "$CFLAGS $EXTRA_CFLAGS" | grep '\-O' >/dev/null || deoptimize="yes"
- if test "x${deoptimize}" = "xyes" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -O0" >&5
-$as_echo_n "checking whether compiler supports -O0... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-O0"
-else
- CFLAGS="${CFLAGS} -O0"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-O0
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -fprofile-arcs -ftest-coverage" >&5
-$as_echo_n "checking whether compiler supports -fprofile-arcs -ftest-coverage... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-fprofile-arcs -ftest-coverage"
-else
- CFLAGS="${CFLAGS} -fprofile-arcs -ftest-coverage"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-fprofile-arcs -ftest-coverage
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- EXTRA_LDFLAGS="$EXTRA_LDFLAGS -fprofile-arcs -ftest-coverage"
- $as_echo "#define JEMALLOC_CODE_COVERAGE " >>confdefs.h
-
-fi
-
-
-
-# Check whether --with-mangling was given.
-if test "${with_mangling+set}" = set; then :
- withval=$with_mangling; mangling_map="$with_mangling"
-else
- mangling_map=""
-fi
-
-
-
-# Check whether --with-jemalloc_prefix was given.
-if test "${with_jemalloc_prefix+set}" = set; then :
- withval=$with_jemalloc_prefix; JEMALLOC_PREFIX="$with_jemalloc_prefix"
-else
- if test "x$abi" != "xmacho" -a "x$abi" != "xpecoff"; then
- JEMALLOC_PREFIX=""
-else
- JEMALLOC_PREFIX="je_"
-fi
-
-fi
-
-if test "x$JEMALLOC_PREFIX" != "x" ; then
- JEMALLOC_CPREFIX=`echo ${JEMALLOC_PREFIX} | tr "a-z" "A-Z"`
- cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_PREFIX "$JEMALLOC_PREFIX"
-_ACEOF
-
- cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_CPREFIX "$JEMALLOC_CPREFIX"
-_ACEOF
-
-fi
-
-
-
-# Check whether --with-export was given.
-if test "${with_export+set}" = set; then :
- withval=$with_export; if test "x$with_export" = "xno"; then
- $as_echo "#define JEMALLOC_EXPORT /**/" >>confdefs.h
-
-fi
-
-fi
-
-
-
-# Check whether --with-private_namespace was given.
-if test "${with_private_namespace+set}" = set; then :
- withval=$with_private_namespace; JEMALLOC_PRIVATE_NAMESPACE="${with_private_namespace}je_"
-else
- JEMALLOC_PRIVATE_NAMESPACE="je_"
-
-fi
-
-cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_PRIVATE_NAMESPACE $JEMALLOC_PRIVATE_NAMESPACE
-_ACEOF
-
-private_namespace="$JEMALLOC_PRIVATE_NAMESPACE"
-
-
-
-# Check whether --with-install_suffix was given.
-if test "${with_install_suffix+set}" = set; then :
- withval=$with_install_suffix; INSTALL_SUFFIX="$with_install_suffix"
-else
- INSTALL_SUFFIX=
-
-fi
-
-install_suffix="$INSTALL_SUFFIX"
-
-
-
-# Check whether --with-malloc_conf was given.
-if test "${with_malloc_conf+set}" = set; then :
- withval=$with_malloc_conf; JEMALLOC_CONFIG_MALLOC_CONF="$with_malloc_conf"
-else
- JEMALLOC_CONFIG_MALLOC_CONF=""
-
-fi
-
-config_malloc_conf="$JEMALLOC_CONFIG_MALLOC_CONF"
-cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_CONFIG_MALLOC_CONF "$config_malloc_conf"
-_ACEOF
-
-
-je_="je_"
-
-
-cfgoutputs_in="Makefile.in"
-cfgoutputs_in="${cfgoutputs_in} jemalloc.pc.in"
-cfgoutputs_in="${cfgoutputs_in} doc/html.xsl.in"
-cfgoutputs_in="${cfgoutputs_in} doc/manpages.xsl.in"
-cfgoutputs_in="${cfgoutputs_in} doc/jemalloc.xml.in"
-cfgoutputs_in="${cfgoutputs_in} include/jemalloc/jemalloc_macros.h.in"
-cfgoutputs_in="${cfgoutputs_in} include/jemalloc/jemalloc_protos.h.in"
-cfgoutputs_in="${cfgoutputs_in} include/jemalloc/jemalloc_typedefs.h.in"
-cfgoutputs_in="${cfgoutputs_in} include/jemalloc/internal/jemalloc_internal.h.in"
-cfgoutputs_in="${cfgoutputs_in} test/test.sh.in"
-cfgoutputs_in="${cfgoutputs_in} test/include/test/jemalloc_test.h.in"
-
-cfgoutputs_out="Makefile"
-cfgoutputs_out="${cfgoutputs_out} jemalloc.pc"
-cfgoutputs_out="${cfgoutputs_out} doc/html.xsl"
-cfgoutputs_out="${cfgoutputs_out} doc/manpages.xsl"
-cfgoutputs_out="${cfgoutputs_out} doc/jemalloc.xml"
-cfgoutputs_out="${cfgoutputs_out} include/jemalloc/jemalloc_macros.h"
-cfgoutputs_out="${cfgoutputs_out} include/jemalloc/jemalloc_protos.h"
-cfgoutputs_out="${cfgoutputs_out} include/jemalloc/jemalloc_typedefs.h"
-cfgoutputs_out="${cfgoutputs_out} include/jemalloc/internal/jemalloc_internal.h"
-cfgoutputs_out="${cfgoutputs_out} test/test.sh"
-cfgoutputs_out="${cfgoutputs_out} test/include/test/jemalloc_test.h"
-
-cfgoutputs_tup="Makefile"
-cfgoutputs_tup="${cfgoutputs_tup} jemalloc.pc:jemalloc.pc.in"
-cfgoutputs_tup="${cfgoutputs_tup} doc/html.xsl:doc/html.xsl.in"
-cfgoutputs_tup="${cfgoutputs_tup} doc/manpages.xsl:doc/manpages.xsl.in"
-cfgoutputs_tup="${cfgoutputs_tup} doc/jemalloc.xml:doc/jemalloc.xml.in"
-cfgoutputs_tup="${cfgoutputs_tup} include/jemalloc/jemalloc_macros.h:include/jemalloc/jemalloc_macros.h.in"
-cfgoutputs_tup="${cfgoutputs_tup} include/jemalloc/jemalloc_protos.h:include/jemalloc/jemalloc_protos.h.in"
-cfgoutputs_tup="${cfgoutputs_tup} include/jemalloc/jemalloc_typedefs.h:include/jemalloc/jemalloc_typedefs.h.in"
-cfgoutputs_tup="${cfgoutputs_tup} include/jemalloc/internal/jemalloc_internal.h"
-cfgoutputs_tup="${cfgoutputs_tup} test/test.sh:test/test.sh.in"
-cfgoutputs_tup="${cfgoutputs_tup} test/include/test/jemalloc_test.h:test/include/test/jemalloc_test.h.in"
-
-cfghdrs_in="include/jemalloc/jemalloc_defs.h.in"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/jemalloc_internal_defs.h.in"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/private_namespace.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/private_unnamespace.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/private_symbols.txt"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/public_namespace.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/public_unnamespace.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/size_classes.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/jemalloc_rename.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/jemalloc_mangle.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/jemalloc.sh"
-cfghdrs_in="${cfghdrs_in} test/include/test/jemalloc_test_defs.h.in"
-
-cfghdrs_out="include/jemalloc/jemalloc_defs.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc${install_suffix}.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/private_namespace.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/private_unnamespace.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/public_symbols.txt"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/public_namespace.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/public_unnamespace.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/size_classes.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc_protos_jet.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc_rename.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc_mangle.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc_mangle_jet.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/jemalloc_internal_defs.h"
-cfghdrs_out="${cfghdrs_out} test/include/test/jemalloc_test_defs.h"
-
-cfghdrs_tup="include/jemalloc/jemalloc_defs.h:include/jemalloc/jemalloc_defs.h.in"
-cfghdrs_tup="${cfghdrs_tup} include/jemalloc/internal/jemalloc_internal_defs.h:include/jemalloc/internal/jemalloc_internal_defs.h.in"
-cfghdrs_tup="${cfghdrs_tup} test/include/test/jemalloc_test_defs.h:test/include/test/jemalloc_test_defs.h.in"
-
-# Check whether --enable-cc-silence was given.
-if test "${enable_cc_silence+set}" = set; then :
- enableval=$enable_cc_silence; if test "x$enable_cc_silence" = "xno" ; then
- enable_cc_silence="0"
-else
- enable_cc_silence="1"
-fi
-
-else
- enable_cc_silence="1"
-
-fi
-
-if test "x$enable_cc_silence" = "x1" ; then
- $as_echo "#define JEMALLOC_CC_SILENCE " >>confdefs.h
-
-fi
-
-# Check whether --enable-debug was given.
-if test "${enable_debug+set}" = set; then :
- enableval=$enable_debug; if test "x$enable_debug" = "xno" ; then
- enable_debug="0"
-else
- enable_debug="1"
-fi
-
-else
- enable_debug="0"
-
-fi
-
-if test "x$enable_debug" = "x1" ; then
- $as_echo "#define JEMALLOC_DEBUG " >>confdefs.h
-
-fi
-if test "x$enable_debug" = "x1" ; then
- $as_echo "#define JEMALLOC_DEBUG " >>confdefs.h
-
- enable_ivsalloc="1"
-fi
-
-
-# Check whether --enable-ivsalloc was given.
-if test "${enable_ivsalloc+set}" = set; then :
- enableval=$enable_ivsalloc; if test "x$enable_ivsalloc" = "xno" ; then
- enable_ivsalloc="0"
-else
- enable_ivsalloc="1"
-fi
-
-else
- enable_ivsalloc="0"
-
-fi
-
-if test "x$enable_ivsalloc" = "x1" ; then
- $as_echo "#define JEMALLOC_IVSALLOC " >>confdefs.h
-
-fi
-
-if test "x$enable_debug" = "x0" -a "x$no_CFLAGS" = "xyes" ; then
- optimize="no"
- echo "$CFLAGS $EXTRA_CFLAGS" | grep '\-O' >/dev/null || optimize="yes"
- if test "x${optimize}" = "xyes" ; then
- if test "x$GCC" = "xyes" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -O3" >&5
-$as_echo_n "checking whether compiler supports -O3... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-O3"
-else
- CFLAGS="${CFLAGS} -O3"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-O3
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -funroll-loops" >&5
-$as_echo_n "checking whether compiler supports -funroll-loops... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-funroll-loops"
-else
- CFLAGS="${CFLAGS} -funroll-loops"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-funroll-loops
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- elif test "x$je_cv_msvc" = "xyes" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -O2" >&5
-$as_echo_n "checking whether compiler supports -O2... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-O2"
-else
- CFLAGS="${CFLAGS} -O2"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-O2
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- else
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -O" >&5
-$as_echo_n "checking whether compiler supports -O... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-O"
-else
- CFLAGS="${CFLAGS} -O"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-O
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- fi
- fi
-fi
-
-# Check whether --enable-stats was given.
-if test "${enable_stats+set}" = set; then :
- enableval=$enable_stats; if test "x$enable_stats" = "xno" ; then
- enable_stats="0"
-else
- enable_stats="1"
-fi
-
-else
- enable_stats="1"
-
-fi
-
-if test "x$enable_stats" = "x1" ; then
- $as_echo "#define JEMALLOC_STATS " >>confdefs.h
-
-fi
-
-
-# Check whether --enable-prof was given.
-if test "${enable_prof+set}" = set; then :
- enableval=$enable_prof; if test "x$enable_prof" = "xno" ; then
- enable_prof="0"
-else
- enable_prof="1"
-fi
-
-else
- enable_prof="0"
-
-fi
-
-if test "x$enable_prof" = "x1" ; then
- backtrace_method=""
-else
- backtrace_method="N/A"
-fi
-
-# Check whether --enable-prof-libunwind was given.
-if test "${enable_prof_libunwind+set}" = set; then :
- enableval=$enable_prof_libunwind; if test "x$enable_prof_libunwind" = "xno" ; then
- enable_prof_libunwind="0"
-else
- enable_prof_libunwind="1"
-fi
-
-else
- enable_prof_libunwind="0"
-
-fi
-
-
-# Check whether --with-static_libunwind was given.
-if test "${with_static_libunwind+set}" = set; then :
- withval=$with_static_libunwind; if test "x$with_static_libunwind" = "xno" ; then
- LUNWIND="-lunwind"
-else
- if test ! -f "$with_static_libunwind" ; then
- as_fn_error $? "Static libunwind not found: $with_static_libunwind" "$LINENO" 5
- fi
- LUNWIND="$with_static_libunwind"
-fi
-else
- LUNWIND="-lunwind"
-
-fi
-
-if test "x$backtrace_method" = "x" -a "x$enable_prof_libunwind" = "x1" ; then
- for ac_header in libunwind.h
-do :
- ac_fn_c_check_header_mongrel "$LINENO" "libunwind.h" "ac_cv_header_libunwind_h" "$ac_includes_default"
-if test "x$ac_cv_header_libunwind_h" = xyes; then :
- cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBUNWIND_H 1
-_ACEOF
-
-else
- enable_prof_libunwind="0"
-fi
-
-done
-
- if test "x$LUNWIND" = "x-lunwind" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for unw_backtrace in -lunwind" >&5
-$as_echo_n "checking for unw_backtrace in -lunwind... " >&6; }
-if ${ac_cv_lib_unwind_unw_backtrace+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_check_lib_save_LIBS=$LIBS
-LIBS="-lunwind $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char unw_backtrace ();
-int
-main ()
-{
-return unw_backtrace ();
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_lib_unwind_unw_backtrace=yes
-else
- ac_cv_lib_unwind_unw_backtrace=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_unwind_unw_backtrace" >&5
-$as_echo "$ac_cv_lib_unwind_unw_backtrace" >&6; }
-if test "x$ac_cv_lib_unwind_unw_backtrace" = xyes; then :
- LIBS="$LIBS $LUNWIND"
-else
- enable_prof_libunwind="0"
-fi
-
- else
- LIBS="$LIBS $LUNWIND"
- fi
- if test "x${enable_prof_libunwind}" = "x1" ; then
- backtrace_method="libunwind"
- $as_echo "#define JEMALLOC_PROF_LIBUNWIND " >>confdefs.h
-
- fi
-fi
-
-# Check whether --enable-prof-libgcc was given.
-if test "${enable_prof_libgcc+set}" = set; then :
- enableval=$enable_prof_libgcc; if test "x$enable_prof_libgcc" = "xno" ; then
- enable_prof_libgcc="0"
-else
- enable_prof_libgcc="1"
-fi
-
-else
- enable_prof_libgcc="1"
-
-fi
-
-if test "x$backtrace_method" = "x" -a "x$enable_prof_libgcc" = "x1" \
- -a "x$GCC" = "xyes" ; then
- for ac_header in unwind.h
-do :
- ac_fn_c_check_header_mongrel "$LINENO" "unwind.h" "ac_cv_header_unwind_h" "$ac_includes_default"
-if test "x$ac_cv_header_unwind_h" = xyes; then :
- cat >>confdefs.h <<_ACEOF
-#define HAVE_UNWIND_H 1
-_ACEOF
-
-else
- enable_prof_libgcc="0"
-fi
-
-done
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _Unwind_Backtrace in -lgcc" >&5
-$as_echo_n "checking for _Unwind_Backtrace in -lgcc... " >&6; }
-if ${ac_cv_lib_gcc__Unwind_Backtrace+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_check_lib_save_LIBS=$LIBS
-LIBS="-lgcc $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char _Unwind_Backtrace ();
-int
-main ()
-{
-return _Unwind_Backtrace ();
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_lib_gcc__Unwind_Backtrace=yes
-else
- ac_cv_lib_gcc__Unwind_Backtrace=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gcc__Unwind_Backtrace" >&5
-$as_echo "$ac_cv_lib_gcc__Unwind_Backtrace" >&6; }
-if test "x$ac_cv_lib_gcc__Unwind_Backtrace" = xyes; then :
- LIBS="$LIBS -lgcc"
-else
- enable_prof_libgcc="0"
-fi
-
- if test "x${enable_prof_libgcc}" = "x1" ; then
- backtrace_method="libgcc"
- $as_echo "#define JEMALLOC_PROF_LIBGCC " >>confdefs.h
-
- fi
-else
- enable_prof_libgcc="0"
-fi
-
-# Check whether --enable-prof-gcc was given.
-if test "${enable_prof_gcc+set}" = set; then :
- enableval=$enable_prof_gcc; if test "x$enable_prof_gcc" = "xno" ; then
- enable_prof_gcc="0"
-else
- enable_prof_gcc="1"
-fi
-
-else
- enable_prof_gcc="1"
-
-fi
-
-if test "x$backtrace_method" = "x" -a "x$enable_prof_gcc" = "x1" \
- -a "x$GCC" = "xyes" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -fno-omit-frame-pointer" >&5
-$as_echo_n "checking whether compiler supports -fno-omit-frame-pointer... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-fno-omit-frame-pointer"
-else
- CFLAGS="${CFLAGS} -fno-omit-frame-pointer"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-fno-omit-frame-pointer
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- backtrace_method="gcc intrinsics"
- $as_echo "#define JEMALLOC_PROF_GCC " >>confdefs.h
-
-else
- enable_prof_gcc="0"
-fi
-
-if test "x$backtrace_method" = "x" ; then
- backtrace_method="none (disabling profiling)"
- enable_prof="0"
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking configured backtracing method" >&5
-$as_echo_n "checking configured backtracing method... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $backtrace_method" >&5
-$as_echo "$backtrace_method" >&6; }
-if test "x$enable_prof" = "x1" ; then
- if test "x$LM" != "x" ; then
- LIBS="$LIBS $LM"
- fi
-
- $as_echo "#define JEMALLOC_PROF " >>confdefs.h
-
-fi
-
-
-# Check whether --enable-tcache was given.
-if test "${enable_tcache+set}" = set; then :
- enableval=$enable_tcache; if test "x$enable_tcache" = "xno" ; then
- enable_tcache="0"
-else
- enable_tcache="1"
-fi
-
-else
- enable_tcache="1"
-
-fi
-
-if test "x$enable_tcache" = "x1" ; then
- $as_echo "#define JEMALLOC_TCACHE " >>confdefs.h
-
-fi
-
-
-if test "x${maps_coalesce}" = "x1" ; then
- $as_echo "#define JEMALLOC_MAPS_COALESCE " >>confdefs.h
-
-fi
-
-# Check whether --enable-munmap was given.
-if test "${enable_munmap+set}" = set; then :
- enableval=$enable_munmap; if test "x$enable_munmap" = "xno" ; then
- enable_munmap="0"
-else
- enable_munmap="1"
-fi
-
-else
- enable_munmap="${default_munmap}"
-
-fi
-
-if test "x$enable_munmap" = "x1" ; then
- $as_echo "#define JEMALLOC_MUNMAP " >>confdefs.h
-
-fi
-
-
-have_dss="1"
-ac_fn_c_check_func "$LINENO" "sbrk" "ac_cv_func_sbrk"
-if test "x$ac_cv_func_sbrk" = xyes; then :
- have_sbrk="1"
-else
- have_sbrk="0"
-fi
-
-if test "x$have_sbrk" = "x1" ; then
- if test "x$sbrk_deprecated" = "x1" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: Disabling dss allocation because sbrk is deprecated" >&5
-$as_echo "Disabling dss allocation because sbrk is deprecated" >&6; }
- have_dss="0"
- fi
-else
- have_dss="0"
-fi
-
-if test "x$have_dss" = "x1" ; then
- $as_echo "#define JEMALLOC_DSS " >>confdefs.h
-
-fi
-
-# Check whether --enable-fill was given.
-if test "${enable_fill+set}" = set; then :
- enableval=$enable_fill; if test "x$enable_fill" = "xno" ; then
- enable_fill="0"
-else
- enable_fill="1"
-fi
-
-else
- enable_fill="1"
-
-fi
-
-if test "x$enable_fill" = "x1" ; then
- $as_echo "#define JEMALLOC_FILL " >>confdefs.h
-
-fi
-
-
-# Check whether --enable-utrace was given.
-if test "${enable_utrace+set}" = set; then :
- enableval=$enable_utrace; if test "x$enable_utrace" = "xno" ; then
- enable_utrace="0"
-else
- enable_utrace="1"
-fi
-
-else
- enable_utrace="0"
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether utrace(2) is compilable" >&5
-$as_echo_n "checking whether utrace(2) is compilable... " >&6; }
-if ${je_cv_utrace+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/ktrace.h>
-
-int
-main ()
-{
-
- utrace((void *)0, 0);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_utrace=yes
-else
- je_cv_utrace=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_utrace" >&5
-$as_echo "$je_cv_utrace" >&6; }
-
-if test "x${je_cv_utrace}" = "xno" ; then
- enable_utrace="0"
-fi
-if test "x$enable_utrace" = "x1" ; then
- $as_echo "#define JEMALLOC_UTRACE " >>confdefs.h
-
-fi
-
-
-# Check whether --enable-valgrind was given.
-if test "${enable_valgrind+set}" = set; then :
- enableval=$enable_valgrind; if test "x$enable_valgrind" = "xno" ; then
- enable_valgrind="0"
-else
- enable_valgrind="1"
-fi
-
-else
- enable_valgrind="1"
-
-fi
-
-if test "x$enable_valgrind" = "x1" ; then
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether valgrind is compilable" >&5
-$as_echo_n "checking whether valgrind is compilable... " >&6; }
-if ${je_cv_valgrind+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <valgrind/valgrind.h>
-#include <valgrind/memcheck.h>
-
-#if !defined(VALGRIND_RESIZEINPLACE_BLOCK)
-# error "Incompatible Valgrind version"
-#endif
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_valgrind=yes
-else
- je_cv_valgrind=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_valgrind" >&5
-$as_echo "$je_cv_valgrind" >&6; }
-
- if test "x${je_cv_valgrind}" = "xno" ; then
- enable_valgrind="0"
- fi
- if test "x$enable_valgrind" = "x1" ; then
- $as_echo "#define JEMALLOC_VALGRIND " >>confdefs.h
-
- fi
-fi
-
-
-# Check whether --enable-xmalloc was given.
-if test "${enable_xmalloc+set}" = set; then :
- enableval=$enable_xmalloc; if test "x$enable_xmalloc" = "xno" ; then
- enable_xmalloc="0"
-else
- enable_xmalloc="1"
-fi
-
-else
- enable_xmalloc="0"
-
-fi
-
-if test "x$enable_xmalloc" = "x1" ; then
- $as_echo "#define JEMALLOC_XMALLOC " >>confdefs.h
-
-fi
-
-
-# Check whether --enable-cache-oblivious was given.
-if test "${enable_cache_oblivious+set}" = set; then :
- enableval=$enable_cache_oblivious; if test "x$enable_cache_oblivious" = "xno" ; then
- enable_cache_oblivious="0"
-else
- enable_cache_oblivious="1"
-fi
-
-else
- enable_cache_oblivious="1"
-
-fi
-
-if test "x$enable_cache_oblivious" = "x1" ; then
- $as_echo "#define JEMALLOC_CACHE_OBLIVIOUS " >>confdefs.h
-
-fi
-
-
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program using __builtin_unreachable is compilable" >&5
-$as_echo_n "checking whether a program using __builtin_unreachable is compilable... " >&6; }
-if ${je_cv_gcc_builtin_unreachable+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-void foo (void) {
- __builtin_unreachable();
-}
-
-int
-main ()
-{
-
- {
- foo();
- }
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_gcc_builtin_unreachable=yes
-else
- je_cv_gcc_builtin_unreachable=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_gcc_builtin_unreachable" >&5
-$as_echo "$je_cv_gcc_builtin_unreachable" >&6; }
-
-if test "x${je_cv_gcc_builtin_unreachable}" = "xyes" ; then
- $as_echo "#define JEMALLOC_INTERNAL_UNREACHABLE __builtin_unreachable" >>confdefs.h
-
-else
- $as_echo "#define JEMALLOC_INTERNAL_UNREACHABLE abort" >>confdefs.h
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program using __builtin_ffsl is compilable" >&5
-$as_echo_n "checking whether a program using __builtin_ffsl is compilable... " >&6; }
-if ${je_cv_gcc_builtin_ffsl+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <stdio.h>
-#include <strings.h>
-#include <string.h>
-
-int
-main ()
-{
-
- {
- int rv = __builtin_ffsl(0x08);
- printf("%d\n", rv);
- }
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_gcc_builtin_ffsl=yes
-else
- je_cv_gcc_builtin_ffsl=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_gcc_builtin_ffsl" >&5
-$as_echo "$je_cv_gcc_builtin_ffsl" >&6; }
-
-if test "x${je_cv_gcc_builtin_ffsl}" = "xyes" ; then
- $as_echo "#define JEMALLOC_INTERNAL_FFSLL __builtin_ffsll" >>confdefs.h
-
- $as_echo "#define JEMALLOC_INTERNAL_FFSL __builtin_ffsl" >>confdefs.h
-
- $as_echo "#define JEMALLOC_INTERNAL_FFS __builtin_ffs" >>confdefs.h
-
-else
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program using ffsl is compilable" >&5
-$as_echo_n "checking whether a program using ffsl is compilable... " >&6; }
-if ${je_cv_function_ffsl+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
- #include <stdio.h>
- #include <strings.h>
- #include <string.h>
-
-int
-main ()
-{
-
- {
- int rv = ffsl(0x08);
- printf("%d\n", rv);
- }
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_function_ffsl=yes
-else
- je_cv_function_ffsl=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_function_ffsl" >&5
-$as_echo "$je_cv_function_ffsl" >&6; }
-
- if test "x${je_cv_function_ffsl}" = "xyes" ; then
- $as_echo "#define JEMALLOC_INTERNAL_FFSLL ffsll" >>confdefs.h
-
- $as_echo "#define JEMALLOC_INTERNAL_FFSL ffsl" >>confdefs.h
-
- $as_echo "#define JEMALLOC_INTERNAL_FFS ffs" >>confdefs.h
-
- else
- as_fn_error $? "Cannot build without ffsl(3) or __builtin_ffsl()" "$LINENO" 5
- fi
-fi
-
-
-# Check whether --with-lg_tiny_min was given.
-if test "${with_lg_tiny_min+set}" = set; then :
- withval=$with_lg_tiny_min; LG_TINY_MIN="$with_lg_tiny_min"
-else
- LG_TINY_MIN="3"
-fi
-
-cat >>confdefs.h <<_ACEOF
-#define LG_TINY_MIN $LG_TINY_MIN
-_ACEOF
-
-
-
-# Check whether --with-lg_quantum was given.
-if test "${with_lg_quantum+set}" = set; then :
- withval=$with_lg_quantum; LG_QUANTA="$with_lg_quantum"
-else
- LG_QUANTA="3 4"
-fi
-
-if test "x$with_lg_quantum" != "x" ; then
- cat >>confdefs.h <<_ACEOF
-#define LG_QUANTUM $with_lg_quantum
-_ACEOF
-
-fi
-
-
-# Check whether --with-lg_page was given.
-if test "${with_lg_page+set}" = set; then :
- withval=$with_lg_page; LG_PAGE="$with_lg_page"
-else
- LG_PAGE="detect"
-fi
-
-if test "x$LG_PAGE" = "xdetect"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking LG_PAGE" >&5
-$as_echo_n "checking LG_PAGE... " >&6; }
-if ${je_cv_lg_page+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test "$cross_compiling" = yes; then :
- je_cv_lg_page=12
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <strings.h>
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <unistd.h>
-#endif
-#include <stdio.h>
-
-int
-main ()
-{
-
- int result;
- FILE *f;
-
-#ifdef _WIN32
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- result = si.dwPageSize;
-#else
- result = sysconf(_SC_PAGESIZE);
-#endif
- if (result == -1) {
- return 1;
- }
- result = JEMALLOC_INTERNAL_FFSL(result) - 1;
-
- f = fopen("conftest.out", "w");
- if (f == NULL) {
- return 1;
- }
- fprintf(f, "%d", result);
- fclose(f);
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
- je_cv_lg_page=`cat conftest.out`
-else
- je_cv_lg_page=undefined
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
- conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_lg_page" >&5
-$as_echo "$je_cv_lg_page" >&6; }
-fi
-if test "x${je_cv_lg_page}" != "x" ; then
- LG_PAGE="${je_cv_lg_page}"
-fi
-if test "x${LG_PAGE}" != "xundefined" ; then
- cat >>confdefs.h <<_ACEOF
-#define LG_PAGE $LG_PAGE
-_ACEOF
-
-else
- as_fn_error $? "cannot determine value for LG_PAGE" "$LINENO" 5
-fi
-
-
-# Check whether --with-lg_page_sizes was given.
-if test "${with_lg_page_sizes+set}" = set; then :
- withval=$with_lg_page_sizes; LG_PAGE_SIZES="$with_lg_page_sizes"
-else
- LG_PAGE_SIZES="$LG_PAGE"
-fi
-
-
-
-# Check whether --with-lg_size_class_group was given.
-if test "${with_lg_size_class_group+set}" = set; then :
- withval=$with_lg_size_class_group; LG_SIZE_CLASS_GROUP="$with_lg_size_class_group"
-else
- LG_SIZE_CLASS_GROUP="2"
-fi
-
-
-
-
-# Check whether --with-version was given.
-if test "${with_version+set}" = set; then :
- withval=$with_version;
- echo "${with_version}" | grep '^[0-9]\+\.[0-9]\+\.[0-9]\+-[0-9]\+-g[0-9a-f]\+$' 2>&1 1>/dev/null
- if test $? -ne 0 ; then
- as_fn_error $? "${with_version} does not match <major>.<minor>.<bugfix>-<nrev>-g<gid>" "$LINENO" 5
- fi
- echo "$with_version" > "${objroot}VERSION"
-
-else
-
- if test "x`test ! \"${srcroot}\" && cd \"${srcroot}\"; git rev-parse --is-inside-work-tree 2>/dev/null`" = "xtrue" ; then
- for pattern in '[0-9].[0-9].[0-9]' '[0-9].[0-9].[0-9][0-9]' \
- '[0-9].[0-9][0-9].[0-9]' '[0-9].[0-9][0-9].[0-9][0-9]' \
- '[0-9][0-9].[0-9].[0-9]' '[0-9][0-9].[0-9].[0-9][0-9]' \
- '[0-9][0-9].[0-9][0-9].[0-9]' \
- '[0-9][0-9].[0-9][0-9].[0-9][0-9]'; do
- (test ! "${srcroot}" && cd "${srcroot}"; git describe --long --abbrev=40 --match="${pattern}") > "${objroot}VERSION.tmp" 2>/dev/null
- if test $? -eq 0 ; then
- mv "${objroot}VERSION.tmp" "${objroot}VERSION"
- break
- fi
- done
- fi
- rm -f "${objroot}VERSION.tmp"
-
-fi
-
-
-if test ! -e "${objroot}VERSION" ; then
- if test ! -e "${srcroot}VERSION" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: Missing VERSION file, and unable to generate it; creating bogus VERSION" >&5
-$as_echo "Missing VERSION file, and unable to generate it; creating bogus VERSION" >&6; }
- echo "0.0.0-0-g0000000000000000000000000000000000000000" > "${objroot}VERSION"
- else
- cp ${srcroot}VERSION ${objroot}VERSION
- fi
-fi
-jemalloc_version=`cat "${objroot}VERSION"`
-jemalloc_version_major=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print $1}'`
-jemalloc_version_minor=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print $2}'`
-jemalloc_version_bugfix=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print $3}'`
-jemalloc_version_nrev=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print $4}'`
-jemalloc_version_gid=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print $5}'`
-
-
-
-
-
-
-
-
-if test "x$abi" != "xpecoff" ; then
- for ac_header in pthread.h
-do :
- ac_fn_c_check_header_mongrel "$LINENO" "pthread.h" "ac_cv_header_pthread_h" "$ac_includes_default"
-if test "x$ac_cv_header_pthread_h" = xyes; then :
- cat >>confdefs.h <<_ACEOF
-#define HAVE_PTHREAD_H 1
-_ACEOF
-
-else
- as_fn_error $? "pthread.h is missing" "$LINENO" 5
-fi
-
-done
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pthread_create in -lpthread" >&5
-$as_echo_n "checking for pthread_create in -lpthread... " >&6; }
-if ${ac_cv_lib_pthread_pthread_create+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpthread $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char pthread_create ();
-int
-main ()
-{
-return pthread_create ();
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_lib_pthread_pthread_create=yes
-else
- ac_cv_lib_pthread_pthread_create=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pthread_pthread_create" >&5
-$as_echo "$ac_cv_lib_pthread_pthread_create" >&6; }
-if test "x$ac_cv_lib_pthread_pthread_create" = xyes; then :
- LIBS="$LIBS -lpthread"
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing pthread_create" >&5
-$as_echo_n "checking for library containing pthread_create... " >&6; }
-if ${ac_cv_search_pthread_create+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char pthread_create ();
-int
-main ()
-{
-return pthread_create ();
- ;
- return 0;
-}
-_ACEOF
-for ac_lib in '' ; do
- if test -z "$ac_lib"; then
- ac_res="none required"
- else
- ac_res=-l$ac_lib
- LIBS="-l$ac_lib $ac_func_search_save_LIBS"
- fi
- if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_search_pthread_create=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext
- if ${ac_cv_search_pthread_create+:} false; then :
- break
-fi
-done
-if ${ac_cv_search_pthread_create+:} false; then :
-
-else
- ac_cv_search_pthread_create=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_pthread_create" >&5
-$as_echo "$ac_cv_search_pthread_create" >&6; }
-ac_res=$ac_cv_search_pthread_create
-if test "$ac_res" != no; then :
- test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-else
- as_fn_error $? "libpthread is missing" "$LINENO" 5
-fi
-
-fi
-
-fi
-
-CPPFLAGS="$CPPFLAGS -D_REENTRANT"
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing clock_gettime" >&5
-$as_echo_n "checking for library containing clock_gettime... " >&6; }
-if ${ac_cv_search_clock_gettime+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char clock_gettime ();
-int
-main ()
-{
-return clock_gettime ();
- ;
- return 0;
-}
-_ACEOF
-for ac_lib in '' rt; do
- if test -z "$ac_lib"; then
- ac_res="none required"
- else
- ac_res=-l$ac_lib
- LIBS="-l$ac_lib $ac_func_search_save_LIBS"
- fi
- if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_search_clock_gettime=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext
- if ${ac_cv_search_clock_gettime+:} false; then :
- break
-fi
-done
-if ${ac_cv_search_clock_gettime+:} false; then :
-
-else
- ac_cv_search_clock_gettime=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_clock_gettime" >&5
-$as_echo "$ac_cv_search_clock_gettime" >&6; }
-ac_res=$ac_cv_search_clock_gettime
-if test "$ac_res" != no; then :
- test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-fi
-
-
-if test "x$je_cv_cray_prgenv_wrapper" = "xyes" ; then
- if test "$ac_cv_search_clock_gettime" != "-lrt"; then
- SAVED_CFLAGS="${CFLAGS}"
-
- unset ac_cv_search_clock_gettime
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -dynamic" >&5
-$as_echo_n "checking whether compiler supports -dynamic... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-dynamic"
-else
- CFLAGS="${CFLAGS} -dynamic"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-dynamic
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing clock_gettime" >&5
-$as_echo_n "checking for library containing clock_gettime... " >&6; }
-if ${ac_cv_search_clock_gettime+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_func_search_save_LIBS=$LIBS
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char clock_gettime ();
-int
-main ()
-{
-return clock_gettime ();
- ;
- return 0;
-}
-_ACEOF
-for ac_lib in '' rt; do
- if test -z "$ac_lib"; then
- ac_res="none required"
- else
- ac_res=-l$ac_lib
- LIBS="-l$ac_lib $ac_func_search_save_LIBS"
- fi
- if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_search_clock_gettime=$ac_res
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext
- if ${ac_cv_search_clock_gettime+:} false; then :
- break
-fi
-done
-if ${ac_cv_search_clock_gettime+:} false; then :
-
-else
- ac_cv_search_clock_gettime=no
-fi
-rm conftest.$ac_ext
-LIBS=$ac_func_search_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_clock_gettime" >&5
-$as_echo "$ac_cv_search_clock_gettime" >&6; }
-ac_res=$ac_cv_search_clock_gettime
-if test "$ac_res" != no; then :
- test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"
-
-fi
-
-
- CFLAGS="${SAVED_CFLAGS}"
- fi
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether clock_gettime(CLOCK_MONOTONIC_COARSE, ...) is compilable" >&5
-$as_echo_n "checking whether clock_gettime(CLOCK_MONOTONIC_COARSE, ...) is compilable... " >&6; }
-if ${je_cv_clock_monotonic_coarse+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <time.h>
-
-int
-main ()
-{
-
- struct timespec ts;
-
- clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_clock_monotonic_coarse=yes
-else
- je_cv_clock_monotonic_coarse=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_clock_monotonic_coarse" >&5
-$as_echo "$je_cv_clock_monotonic_coarse" >&6; }
-
-if test "x${je_cv_clock_monotonic_coarse}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_CLOCK_MONOTONIC_COARSE 1" >>confdefs.h
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether clock_gettime(CLOCK_MONOTONIC, ...) is compilable" >&5
-$as_echo_n "checking whether clock_gettime(CLOCK_MONOTONIC, ...) is compilable... " >&6; }
-if ${je_cv_clock_monotonic+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <unistd.h>
-#include <time.h>
-
-int
-main ()
-{
-
- struct timespec ts;
-
- clock_gettime(CLOCK_MONOTONIC, &ts);
-#if !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0
-# error _POSIX_MONOTONIC_CLOCK missing/invalid
-#endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_clock_monotonic=yes
-else
- je_cv_clock_monotonic=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_clock_monotonic" >&5
-$as_echo "$je_cv_clock_monotonic" >&6; }
-
-if test "x${je_cv_clock_monotonic}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_CLOCK_MONOTONIC 1" >>confdefs.h
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether mach_absolute_time() is compilable" >&5
-$as_echo_n "checking whether mach_absolute_time() is compilable... " >&6; }
-if ${je_cv_mach_absolute_time+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <mach/mach_time.h>
-
-int
-main ()
-{
-
- mach_absolute_time();
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_mach_absolute_time=yes
-else
- je_cv_mach_absolute_time=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_mach_absolute_time" >&5
-$as_echo "$je_cv_mach_absolute_time" >&6; }
-
-if test "x${je_cv_mach_absolute_time}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_MACH_ABSOLUTE_TIME 1" >>confdefs.h
-
-fi
-
-SAVED_CFLAGS="${CFLAGS}"
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether compiler supports -Werror" >&5
-$as_echo_n "checking whether compiler supports -Werror... " >&6; }
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="-Werror"
-else
- CFLAGS="${CFLAGS} -Werror"
-fi
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-
-int
-main ()
-{
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- je_cv_cflags_appended=-Werror
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- je_cv_cflags_appended=
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- CFLAGS="${TCFLAGS}"
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether syscall(2) is compilable" >&5
-$as_echo_n "checking whether syscall(2) is compilable... " >&6; }
-if ${je_cv_syscall+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <sys/syscall.h>
-#include <unistd.h>
-
-int
-main ()
-{
-
- syscall(SYS_write, 2, "hello", 5);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_syscall=yes
-else
- je_cv_syscall=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_syscall" >&5
-$as_echo "$je_cv_syscall" >&6; }
-
-CFLAGS="${SAVED_CFLAGS}"
-if test "x$je_cv_syscall" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_SYSCALL " >>confdefs.h
-
-fi
-
-ac_fn_c_check_func "$LINENO" "secure_getenv" "ac_cv_func_secure_getenv"
-if test "x$ac_cv_func_secure_getenv" = xyes; then :
- have_secure_getenv="1"
-else
- have_secure_getenv="0"
-
-fi
-
-if test "x$have_secure_getenv" = "x1" ; then
- $as_echo "#define JEMALLOC_HAVE_SECURE_GETENV " >>confdefs.h
-
-fi
-
-ac_fn_c_check_func "$LINENO" "issetugid" "ac_cv_func_issetugid"
-if test "x$ac_cv_func_issetugid" = xyes; then :
- have_issetugid="1"
-else
- have_issetugid="0"
-
-fi
-
-if test "x$have_issetugid" = "x1" ; then
- $as_echo "#define JEMALLOC_HAVE_ISSETUGID " >>confdefs.h
-
-fi
-
-ac_fn_c_check_func "$LINENO" "_malloc_thread_cleanup" "ac_cv_func__malloc_thread_cleanup"
-if test "x$ac_cv_func__malloc_thread_cleanup" = xyes; then :
- have__malloc_thread_cleanup="1"
-else
- have__malloc_thread_cleanup="0"
-
-fi
-
-if test "x$have__malloc_thread_cleanup" = "x1" ; then
- $as_echo "#define JEMALLOC_MALLOC_THREAD_CLEANUP " >>confdefs.h
-
- force_tls="1"
-fi
-
-ac_fn_c_check_func "$LINENO" "_pthread_mutex_init_calloc_cb" "ac_cv_func__pthread_mutex_init_calloc_cb"
-if test "x$ac_cv_func__pthread_mutex_init_calloc_cb" = xyes; then :
- have__pthread_mutex_init_calloc_cb="1"
-else
- have__pthread_mutex_init_calloc_cb="0"
-
-fi
-
-if test "x$have__pthread_mutex_init_calloc_cb" = "x1" ; then
- $as_echo "#define JEMALLOC_MUTEX_INIT_CB 1" >>confdefs.h
-
-fi
-
-# Check whether --enable-lazy_lock was given.
-if test "${enable_lazy_lock+set}" = set; then :
- enableval=$enable_lazy_lock; if test "x$enable_lazy_lock" = "xno" ; then
- enable_lazy_lock="0"
-else
- enable_lazy_lock="1"
-fi
-
-else
- enable_lazy_lock=""
-
-fi
-
-if test "x${enable_lazy_lock}" = "x" ; then
- if test "x${force_lazy_lock}" = "x1" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: Forcing lazy-lock to avoid allocator/threading bootstrap issues" >&5
-$as_echo "Forcing lazy-lock to avoid allocator/threading bootstrap issues" >&6; }
- enable_lazy_lock="1"
- else
- enable_lazy_lock="0"
- fi
-fi
-if test "x${enable_lazy_lock}" = "x1" -a "x${abi}" = "xpecoff" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: Forcing no lazy-lock because thread creation monitoring is unimplemented" >&5
-$as_echo "Forcing no lazy-lock because thread creation monitoring is unimplemented" >&6; }
- enable_lazy_lock="0"
-fi
-if test "x$enable_lazy_lock" = "x1" ; then
- if test "x$abi" != "xpecoff" ; then
- for ac_header in dlfcn.h
-do :
- ac_fn_c_check_header_mongrel "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default"
-if test "x$ac_cv_header_dlfcn_h" = xyes; then :
- cat >>confdefs.h <<_ACEOF
-#define HAVE_DLFCN_H 1
-_ACEOF
-
-else
- as_fn_error $? "dlfcn.h is missing" "$LINENO" 5
-fi
-
-done
-
- ac_fn_c_check_func "$LINENO" "dlsym" "ac_cv_func_dlsym"
-if test "x$ac_cv_func_dlsym" = xyes; then :
-
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlsym in -ldl" >&5
-$as_echo_n "checking for dlsym in -ldl... " >&6; }
-if ${ac_cv_lib_dl_dlsym+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_check_lib_save_LIBS=$LIBS
-LIBS="-ldl $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char dlsym ();
-int
-main ()
-{
-return dlsym ();
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_lib_dl_dlsym=yes
-else
- ac_cv_lib_dl_dlsym=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlsym" >&5
-$as_echo "$ac_cv_lib_dl_dlsym" >&6; }
-if test "x$ac_cv_lib_dl_dlsym" = xyes; then :
- LIBS="$LIBS -ldl"
-else
- as_fn_error $? "libdl is missing" "$LINENO" 5
-fi
-
-
-fi
-
- fi
- $as_echo "#define JEMALLOC_LAZY_LOCK " >>confdefs.h
-
-fi
-
-
-# Check whether --enable-tls was given.
-if test "${enable_tls+set}" = set; then :
- enableval=$enable_tls; if test "x$enable_tls" = "xno" ; then
- enable_tls="0"
-else
- enable_tls="1"
-fi
-
-else
- enable_tls=""
-
-fi
-
-if test "x${enable_tls}" = "x" ; then
- if test "x${force_tls}" = "x1" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: Forcing TLS to avoid allocator/threading bootstrap issues" >&5
-$as_echo "Forcing TLS to avoid allocator/threading bootstrap issues" >&6; }
- enable_tls="1"
- elif test "x${force_tls}" = "x0" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: Forcing no TLS to avoid allocator/threading bootstrap issues" >&5
-$as_echo "Forcing no TLS to avoid allocator/threading bootstrap issues" >&6; }
- enable_tls="0"
- else
- enable_tls="1"
- fi
-fi
-if test "x${enable_tls}" = "x1" ; then
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for TLS" >&5
-$as_echo_n "checking for TLS... " >&6; }
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
- __thread int x;
-
-int
-main ()
-{
-
- x = 42;
-
- return 0;
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
- enable_tls="0"
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-else
- enable_tls="0"
-fi
-
-if test "x${enable_tls}" = "x1" ; then
- if test "x${force_tls}" = "x0" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: TLS enabled despite being marked unusable on this platform" >&5
-$as_echo "$as_me: WARNING: TLS enabled despite being marked unusable on this platform" >&2;}
- fi
- cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_TLS
-_ACEOF
-
-elif test "x${force_tls}" = "x1" ; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: TLS disabled despite being marked critical on this platform" >&5
-$as_echo "$as_me: WARNING: TLS disabled despite being marked critical on this platform" >&2;}
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether C11 atomics is compilable" >&5
-$as_echo_n "checking whether C11 atomics is compilable... " >&6; }
-if ${je_cv_c11atomics+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <stdint.h>
-#if (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__)
-#include <stdatomic.h>
-#else
-#error Atomics not available
-#endif
-
-int
-main ()
-{
-
- uint64_t *p = (uint64_t *)0;
- uint64_t x = 1;
- volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
- uint64_t r = atomic_fetch_add(a, x) + x;
- return (r == 0);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_c11atomics=yes
-else
- je_cv_c11atomics=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_c11atomics" >&5
-$as_echo "$je_cv_c11atomics" >&6; }
-
-if test "x${je_cv_c11atomics}" = "xyes" ; then
- $as_echo "#define JEMALLOC_C11ATOMICS 1" >>confdefs.h
-
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether atomic(9) is compilable" >&5
-$as_echo_n "checking whether atomic(9) is compilable... " >&6; }
-if ${je_cv_atomic9+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <sys/types.h>
-#include <machine/atomic.h>
-#include <inttypes.h>
-
-int
-main ()
-{
-
- {
- uint32_t x32 = 0;
- volatile uint32_t *x32p = &x32;
- atomic_fetchadd_32(x32p, 1);
- }
- {
- unsigned long xlong = 0;
- volatile unsigned long *xlongp = &xlong;
- atomic_fetchadd_long(xlongp, 1);
- }
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_atomic9=yes
-else
- je_cv_atomic9=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_atomic9" >&5
-$as_echo "$je_cv_atomic9" >&6; }
-
-if test "x${je_cv_atomic9}" = "xyes" ; then
- $as_echo "#define JEMALLOC_ATOMIC9 1" >>confdefs.h
-
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether Darwin OSAtomic*() is compilable" >&5
-$as_echo_n "checking whether Darwin OSAtomic*() is compilable... " >&6; }
-if ${je_cv_osatomic+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <libkern/OSAtomic.h>
-#include <inttypes.h>
-
-int
-main ()
-{
-
- {
- int32_t x32 = 0;
- volatile int32_t *x32p = &x32;
- OSAtomicAdd32(1, x32p);
- }
- {
- int64_t x64 = 0;
- volatile int64_t *x64p = &x64;
- OSAtomicAdd64(1, x64p);
- }
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_osatomic=yes
-else
- je_cv_osatomic=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_osatomic" >&5
-$as_echo "$je_cv_osatomic" >&6; }
-
-if test "x${je_cv_osatomic}" = "xyes" ; then
- $as_echo "#define JEMALLOC_OSATOMIC " >>confdefs.h
-
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether madvise(2) is compilable" >&5
-$as_echo_n "checking whether madvise(2) is compilable... " >&6; }
-if ${je_cv_madvise+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <sys/mman.h>
-
-int
-main ()
-{
-
- {
- madvise((void *)0, 0, 0);
- }
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_madvise=yes
-else
- je_cv_madvise=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_madvise" >&5
-$as_echo "$je_cv_madvise" >&6; }
-
-if test "x${je_cv_madvise}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_MADVISE " >>confdefs.h
-
-fi
-
-
-
-
-if test "x${je_cv_atomic9}" != "xyes" -a "x${je_cv_osatomic}" != "xyes" ; then
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to force 32-bit __sync_{add,sub}_and_fetch()" >&5
-$as_echo_n "checking whether to force 32-bit __sync_{add,sub}_and_fetch()... " >&6; }
-if ${je_cv_sync_compare_and_swap_4+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
- #include <stdint.h>
-
-int
-main ()
-{
-
- #ifndef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
- {
- uint32_t x32 = 0;
- __sync_add_and_fetch(&x32, 42);
- __sync_sub_and_fetch(&x32, 1);
- }
- #else
- #error __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 is defined, no need to force
- #endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_sync_compare_and_swap_4=yes
-else
- je_cv_sync_compare_and_swap_4=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_sync_compare_and_swap_4" >&5
-$as_echo "$je_cv_sync_compare_and_swap_4" >&6; }
-
- if test "x${je_cv_sync_compare_and_swap_4}" = "xyes" ; then
- $as_echo "#define JE_FORCE_SYNC_COMPARE_AND_SWAP_4 " >>confdefs.h
-
- fi
-
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to force 64-bit __sync_{add,sub}_and_fetch()" >&5
-$as_echo_n "checking whether to force 64-bit __sync_{add,sub}_and_fetch()... " >&6; }
-if ${je_cv_sync_compare_and_swap_8+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
- #include <stdint.h>
-
-int
-main ()
-{
-
- #ifndef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8
- {
- uint64_t x64 = 0;
- __sync_add_and_fetch(&x64, 42);
- __sync_sub_and_fetch(&x64, 1);
- }
- #else
- #error __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 is defined, no need to force
- #endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_sync_compare_and_swap_8=yes
-else
- je_cv_sync_compare_and_swap_8=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_sync_compare_and_swap_8" >&5
-$as_echo "$je_cv_sync_compare_and_swap_8" >&6; }
-
- if test "x${je_cv_sync_compare_and_swap_8}" = "xyes" ; then
- $as_echo "#define JE_FORCE_SYNC_COMPARE_AND_SWAP_8 " >>confdefs.h
-
- fi
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for __builtin_clz" >&5
-$as_echo_n "checking for __builtin_clz... " >&6; }
-if ${je_cv_builtin_clz+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- {
- unsigned x = 0;
- int y = __builtin_clz(x);
- }
- {
- unsigned long x = 0;
- int y = __builtin_clzl(x);
- }
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_builtin_clz=yes
-else
- je_cv_builtin_clz=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_builtin_clz" >&5
-$as_echo "$je_cv_builtin_clz" >&6; }
-
-if test "x${je_cv_builtin_clz}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_BUILTIN_CLZ " >>confdefs.h
-
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether Darwin os_unfair_lock_*() is compilable" >&5
-$as_echo_n "checking whether Darwin os_unfair_lock_*() is compilable... " >&6; }
-if ${je_cv_os_unfair_lock+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <os/lock.h>
-
-int
-main ()
-{
-
- os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;
- os_unfair_lock_lock(&lock);
- os_unfair_lock_unlock(&lock);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_os_unfair_lock=yes
-else
- je_cv_os_unfair_lock=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_os_unfair_lock" >&5
-$as_echo "$je_cv_os_unfair_lock" >&6; }
-
-if test "x${je_cv_os_unfair_lock}" = "xyes" ; then
- $as_echo "#define JEMALLOC_OS_UNFAIR_LOCK " >>confdefs.h
-
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether Darwin OSSpin*() is compilable" >&5
-$as_echo_n "checking whether Darwin OSSpin*() is compilable... " >&6; }
-if ${je_cv_osspin+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <libkern/OSAtomic.h>
-#include <inttypes.h>
-
-int
-main ()
-{
-
- OSSpinLock lock = 0;
- OSSpinLockLock(&lock);
- OSSpinLockUnlock(&lock);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_osspin=yes
-else
- je_cv_osspin=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_osspin" >&5
-$as_echo "$je_cv_osspin" >&6; }
-
-if test "x${je_cv_osspin}" = "xyes" ; then
- $as_echo "#define JEMALLOC_OSSPIN " >>confdefs.h
-
-fi
-
-
-# Check whether --enable-zone-allocator was given.
-if test "${enable_zone_allocator+set}" = set; then :
- enableval=$enable_zone_allocator; if test "x$enable_zone_allocator" = "xno" ; then
- enable_zone_allocator="0"
-else
- enable_zone_allocator="1"
-fi
-
-else
- if test "x${abi}" = "xmacho"; then
- enable_zone_allocator="1"
-fi
-
-
-fi
-
-
-
-if test "x${enable_zone_allocator}" = "x1" ; then
- if test "x${abi}" != "xmacho"; then
- as_fn_error $? "--enable-zone-allocator is only supported on Darwin" "$LINENO" 5
- fi
- $as_echo "#define JEMALLOC_ZONE " >>confdefs.h
-
-
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking malloc zone version" >&5
-$as_echo_n "checking malloc zone version... " >&6; }
-
-
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <malloc/malloc.h>
-int
-main ()
-{
-static int foo[sizeof(malloc_zone_t) == sizeof(void *) * 14 ? 1 : -1]
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- JEMALLOC_ZONE_VERSION=3
-else
-
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <malloc/malloc.h>
-int
-main ()
-{
-static int foo[sizeof(malloc_zone_t) == sizeof(void *) * 15 ? 1 : -1]
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- JEMALLOC_ZONE_VERSION=5
-else
-
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <malloc/malloc.h>
-int
-main ()
-{
-static int foo[sizeof(malloc_zone_t) == sizeof(void *) * 16 ? 1 : -1]
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <malloc/malloc.h>
-int
-main ()
-{
-static int foo[sizeof(malloc_introspection_t) == sizeof(void *) * 9 ? 1 : -1]
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- JEMALLOC_ZONE_VERSION=6
-else
-
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <malloc/malloc.h>
-int
-main ()
-{
-static int foo[sizeof(malloc_introspection_t) == sizeof(void *) * 13 ? 1 : -1]
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- JEMALLOC_ZONE_VERSION=7
-else
- JEMALLOC_ZONE_VERSION=
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-else
-
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <malloc/malloc.h>
-int
-main ()
-{
-static int foo[sizeof(malloc_zone_t) == sizeof(void *) * 17 ? 1 : -1]
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- JEMALLOC_ZONE_VERSION=8
-else
-
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include <malloc/malloc.h>
-int
-main ()
-{
-static int foo[sizeof(malloc_zone_t) > sizeof(void *) * 17 ? 1 : -1]
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- JEMALLOC_ZONE_VERSION=9
-else
- JEMALLOC_ZONE_VERSION=
-
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- if test "x${JEMALLOC_ZONE_VERSION}" = "x"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
-$as_echo "unsupported" >&6; }
- as_fn_error $? "Unsupported malloc zone version" "$LINENO" 5
- fi
- if test "${JEMALLOC_ZONE_VERSION}" = 9; then
- JEMALLOC_ZONE_VERSION=8
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: > 8" >&5
-$as_echo "> 8" >&6; }
- else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $JEMALLOC_ZONE_VERSION" >&5
-$as_echo "$JEMALLOC_ZONE_VERSION" >&6; }
- fi
- cat >>confdefs.h <<_ACEOF
-#define JEMALLOC_ZONE_VERSION $JEMALLOC_ZONE_VERSION
-_ACEOF
-
-fi
-
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether glibc malloc hook is compilable" >&5
-$as_echo_n "checking whether glibc malloc hook is compilable... " >&6; }
-if ${je_cv_glibc_malloc_hook+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <stddef.h>
-
-extern void (* __free_hook)(void *ptr);
-extern void *(* __malloc_hook)(size_t size);
-extern void *(* __realloc_hook)(void *ptr, size_t size);
-
-int
-main ()
-{
-
- void *ptr = 0L;
- if (__malloc_hook) ptr = __malloc_hook(1);
- if (__realloc_hook) ptr = __realloc_hook(ptr, 2);
- if (__free_hook && ptr) __free_hook(ptr);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_glibc_malloc_hook=yes
-else
- je_cv_glibc_malloc_hook=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_glibc_malloc_hook" >&5
-$as_echo "$je_cv_glibc_malloc_hook" >&6; }
-
-if test "x${je_cv_glibc_malloc_hook}" = "xyes" ; then
- $as_echo "#define JEMALLOC_GLIBC_MALLOC_HOOK " >>confdefs.h
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether glibc memalign hook is compilable" >&5
-$as_echo_n "checking whether glibc memalign hook is compilable... " >&6; }
-if ${je_cv_glibc_memalign_hook+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <stddef.h>
-
-extern void *(* __memalign_hook)(size_t alignment, size_t size);
-
-int
-main ()
-{
-
- void *ptr = 0L;
- if (__memalign_hook) ptr = __memalign_hook(16, 7);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_glibc_memalign_hook=yes
-else
- je_cv_glibc_memalign_hook=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_glibc_memalign_hook" >&5
-$as_echo "$je_cv_glibc_memalign_hook" >&6; }
-
-if test "x${je_cv_glibc_memalign_hook}" = "xyes" ; then
- $as_echo "#define JEMALLOC_GLIBC_MEMALIGN_HOOK " >>confdefs.h
-
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether pthreads adaptive mutexes is compilable" >&5
-$as_echo_n "checking whether pthreads adaptive mutexes is compilable... " >&6; }
-if ${je_cv_pthread_mutex_adaptive_np+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-#include <pthread.h>
-
-int
-main ()
-{
-
- pthread_mutexattr_t attr;
- pthread_mutexattr_init(&attr);
- pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
- pthread_mutexattr_destroy(&attr);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- je_cv_pthread_mutex_adaptive_np=yes
-else
- je_cv_pthread_mutex_adaptive_np=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $je_cv_pthread_mutex_adaptive_np" >&5
-$as_echo "$je_cv_pthread_mutex_adaptive_np" >&6; }
-
-if test "x${je_cv_pthread_mutex_adaptive_np}" = "xyes" ; then
- $as_echo "#define JEMALLOC_HAVE_PTHREAD_MUTEX_ADAPTIVE_NP " >>confdefs.h
-
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for stdbool.h that conforms to C99" >&5
-$as_echo_n "checking for stdbool.h that conforms to C99... " >&6; }
-if ${ac_cv_header_stdbool_h+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
- #include <stdbool.h>
- #ifndef bool
- "error: bool is not defined"
- #endif
- #ifndef false
- "error: false is not defined"
- #endif
- #if false
- "error: false is not 0"
- #endif
- #ifndef true
- "error: true is not defined"
- #endif
- #if true != 1
- "error: true is not 1"
- #endif
- #ifndef __bool_true_false_are_defined
- "error: __bool_true_false_are_defined is not defined"
- #endif
-
- struct s { _Bool s: 1; _Bool t; } s;
-
- char a[true == 1 ? 1 : -1];
- char b[false == 0 ? 1 : -1];
- char c[__bool_true_false_are_defined == 1 ? 1 : -1];
- char d[(bool) 0.5 == true ? 1 : -1];
- /* See body of main program for 'e'. */
- char f[(_Bool) 0.0 == false ? 1 : -1];
- char g[true];
- char h[sizeof (_Bool)];
- char i[sizeof s.t];
- enum { j = false, k = true, l = false * true, m = true * 256 };
- /* The following fails for
- HP aC++/ANSI C B3910B A.05.55 [Dec 04 2003]. */
- _Bool n[m];
- char o[sizeof n == m * sizeof n[0] ? 1 : -1];
- char p[-1 - (_Bool) 0 < 0 && -1 - (bool) 0 < 0 ? 1 : -1];
- /* Catch a bug in an HP-UX C compiler. See
- http://gcc.gnu.org/ml/gcc-patches/2003-12/msg02303.html
- http://lists.gnu.org/archive/html/bug-coreutils/2005-11/msg00161.html
- */
- _Bool q = true;
- _Bool *pq = &q;
-
-int
-main ()
-{
-
- bool e = &s;
- *pq |= q;
- *pq |= ! q;
- /* Refer to every declared value, to avoid compiler optimizations. */
- return (!a + !b + !c + !d + !e + !f + !g + !h + !i + !!j + !k + !!l
- + !m + !n + !o + !p + !q + !pq);
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_header_stdbool_h=yes
-else
- ac_cv_header_stdbool_h=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdbool_h" >&5
-$as_echo "$ac_cv_header_stdbool_h" >&6; }
- ac_fn_c_check_type "$LINENO" "_Bool" "ac_cv_type__Bool" "$ac_includes_default"
-if test "x$ac_cv_type__Bool" = xyes; then :
-
-cat >>confdefs.h <<_ACEOF
-#define HAVE__BOOL 1
-_ACEOF
-
-
-fi
-
-
-if test $ac_cv_header_stdbool_h = yes; then
-
-$as_echo "#define HAVE_STDBOOL_H 1" >>confdefs.h
-
-fi
-
-
-
-ac_config_commands="$ac_config_commands include/jemalloc/internal/private_namespace.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/internal/private_unnamespace.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/internal/public_symbols.txt"
-
-ac_config_commands="$ac_config_commands include/jemalloc/internal/public_namespace.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/internal/public_unnamespace.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/internal/size_classes.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/jemalloc_protos_jet.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/jemalloc_rename.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/jemalloc_mangle.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/jemalloc_mangle_jet.h"
-
-ac_config_commands="$ac_config_commands include/jemalloc/jemalloc.h"
-
-
-
-
-ac_config_headers="$ac_config_headers $cfghdrs_tup"
-
-
-
-ac_config_files="$ac_config_files $cfgoutputs_tup config.stamp bin/jemalloc-config bin/jemalloc.sh bin/jeprof"
-
-
-
-cat >confcache <<\_ACEOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs, see configure's option --config-cache.
-# It is not useful on other systems. If it contains results you don't
-# want to keep, you may remove or edit it.
-#
-# config.status only pays attention to the cache file if you give it
-# the --recheck option to rerun configure.
-#
-# `ac_cv_env_foo' variables (set or unset) will be overridden when
-# loading this file, other *unset* `ac_cv_foo' will be assigned the
-# following values.
-
-_ACEOF
-
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, we kill variables containing newlines.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(
- for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
- eval ac_val=\$$ac_var
- case $ac_val in #(
- *${as_nl}*)
- case $ac_var in #(
- *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
- esac
- case $ac_var in #(
- _ | IFS | as_nl) ;; #(
- BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
- *) { eval $ac_var=; unset $ac_var;} ;;
- esac ;;
- esac
- done
-
- (set) 2>&1 |
- case $as_nl`(ac_space=' '; set) 2>&1` in #(
- *${as_nl}ac_space=\ *)
- # `set' does not quote correctly, so add quotes: double-quote
- # substitution turns \\\\ into \\, and sed turns \\ into \.
- sed -n \
- "s/'/'\\\\''/g;
- s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
- ;; #(
- *)
- # `set' quotes correctly as required by POSIX, so do not add quotes.
- sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
- ;;
- esac |
- sort
-) |
- sed '
- /^ac_cv_env_/b end
- t clear
- :clear
- s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
- t end
- s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
- :end' >>confcache
-if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
- if test -w "$cache_file"; then
- if test "x$cache_file" != "x/dev/null"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
-$as_echo "$as_me: updating cache $cache_file" >&6;}
- if test ! -f "$cache_file" || test -h "$cache_file"; then
- cat confcache >"$cache_file"
- else
- case $cache_file in #(
- */* | ?:*)
- mv -f confcache "$cache_file"$$ &&
- mv -f "$cache_file"$$ "$cache_file" ;; #(
- *)
- mv -f confcache "$cache_file" ;;
- esac
- fi
- fi
- else
- { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
-$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
- fi
-fi
-rm -f confcache
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-DEFS=-DHAVE_CONFIG_H
-
-ac_libobjs=
-ac_ltlibobjs=
-U=
-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
- # 1. Remove the extension, and $U if already installed.
- ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
- ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
- # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR
- # will be set to the directory where LIBOBJS objects are built.
- as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
- as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
-done
-LIBOBJS=$ac_libobjs
-
-LTLIBOBJS=$ac_ltlibobjs
-
-
-
-
-: "${CONFIG_STATUS=./config.status}"
-ac_write_fail=0
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
-$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
-as_write_fail=0
-cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-
-SHELL=\${CONFIG_SHELL-$SHELL}
-export SHELL
-_ASEOF
-cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
- emulate sh
- NULLCMD=:
- # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
- # is contrary to our usage. Disable this feature.
- alias -g '${1+"$@"}'='"$@"'
- setopt NO_GLOB_SUBST
-else
- case `(set -o) 2>/dev/null` in #(
- *posix*) :
- set -o posix ;; #(
- *) :
- ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
- && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
- as_echo='print -r --'
- as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
- as_echo='printf %s\n'
- as_echo_n='printf %s'
-else
- if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
- as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
- as_echo_n='/usr/ucb/echo -n'
- else
- as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
- as_echo_n_body='eval
- arg=$1;
- case $arg in #(
- *"$as_nl"*)
- expr "X$arg" : "X\\(.*\\)$as_nl";
- arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
- esac;
- expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
- '
- export as_echo_n_body
- as_echo_n='sh -c $as_echo_n_body as_echo'
- fi
- export as_echo_body
- as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
- PATH_SEPARATOR=:
- (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
- (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
- PATH_SEPARATOR=';'
- }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order. Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" "" $as_nl"
-
-# Find who we are. Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
- *[\\/]* ) as_myself=$0 ;;
- *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
- done
-IFS=$as_save_IFS
-
- ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
- as_myself=$0
-fi
-if test ! -f "$as_myself"; then
- $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
- exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there. '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
- && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
- as_status=$1; test $as_status -eq 0 && as_status=1
- if test "$4"; then
- as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
- fi
- $as_echo "$as_me: error: $2" >&2
- as_fn_exit $as_status
-} # as_fn_error
-
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
- return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
- set +e
- as_fn_set_status $1
- exit $1
-} # as_fn_exit
-
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
- { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
- eval 'as_fn_append ()
- {
- eval $1+=\$2
- }'
-else
- as_fn_append ()
- {
- eval $1=\$$1\$2
- }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
- eval 'as_fn_arith ()
- {
- as_val=$(( $* ))
- }'
-else
- as_fn_arith ()
- {
- as_val=`expr "$@" || test $? -eq 1`
- }
-fi # as_fn_arith
-
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
- test "X`expr 00001 : '.*\(...\)'`" = X001; then
- as_expr=expr
-else
- as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
- as_basename=basename
-else
- as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
- as_dirname=dirname
-else
- as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
- X"$0" : 'X\(//\)$' \| \
- X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
- sed '/^.*\/\([^/][^/]*\)\/*$/{
- s//\1/
- q
- }
- /^X\/\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\/\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
- case `echo 'xy\c'` in
- *c*) ECHO_T=' ';; # ECHO_T is single tab character.
- xy) ECHO_C='\c';;
- *) echo `echo ksh88 bug on AIX 6.1` > /dev/null
- ECHO_T=' ';;
- esac;;
-*)
- ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
- rm -f conf$$.dir/conf$$.file
-else
- rm -f conf$$.dir
- mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
- if ln -s conf$$.file conf$$ 2>/dev/null; then
- as_ln_s='ln -s'
- # ... but there are two gotchas:
- # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
- # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
- # In both cases, we have to default to `cp -pR'.
- ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
- as_ln_s='cp -pR'
- elif ln conf$$.file conf$$ 2>/dev/null; then
- as_ln_s=ln
- else
- as_ln_s='cp -pR'
- fi
-else
- as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
- case $as_dir in #(
- -*) as_dir=./$as_dir;;
- esac
- test -d "$as_dir" || eval $as_mkdir_p || {
- as_dirs=
- while :; do
- case $as_dir in #(
- *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
- *) as_qdir=$as_dir;;
- esac
- as_dirs="'$as_qdir' $as_dirs"
- as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$as_dir" : 'X\(//\)[^/]' \| \
- X"$as_dir" : 'X\(//\)$' \| \
- X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- test -d "$as_dir" && break
- done
- test -z "$as_dirs" || eval "mkdir $as_dirs"
- } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-if mkdir -p . 2>/dev/null; then
- as_mkdir_p='mkdir -p "$as_dir"'
-else
- test -d ./-p && rmdir ./-p
- as_mkdir_p=false
-fi
-
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
- test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-exec 6>&1
-## ----------------------------------- ##
-## Main body of $CONFIG_STATUS script. ##
-## ----------------------------------- ##
-_ASEOF
-test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# Save the log message, to keep $0 and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.
-ac_log="
-This file was extended by $as_me, which was
-generated by GNU Autoconf 2.69. Invocation command line was
-
- CONFIG_FILES = $CONFIG_FILES
- CONFIG_HEADERS = $CONFIG_HEADERS
- CONFIG_LINKS = $CONFIG_LINKS
- CONFIG_COMMANDS = $CONFIG_COMMANDS
- $ $0 $@
-
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
-_ACEOF
-
-case $ac_config_files in *"
-"*) set x $ac_config_files; shift; ac_config_files=$*;;
-esac
-
-case $ac_config_headers in *"
-"*) set x $ac_config_headers; shift; ac_config_headers=$*;;
-esac
-
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-# Files that config.status was made for.
-config_files="$ac_config_files"
-config_headers="$ac_config_headers"
-config_commands="$ac_config_commands"
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-ac_cs_usage="\
-\`$as_me' instantiates files and other configuration actions
-from templates according to the current configuration. Unless the files
-and actions are specified as TAGs, all are instantiated by default.
-
-Usage: $0 [OPTION]... [TAG]...
-
- -h, --help print this help, then exit
- -V, --version print version number and configuration settings, then exit
- --config print configuration, then exit
- -q, --quiet, --silent
- do not print progress messages
- -d, --debug don't remove temporary files
- --recheck update $as_me by reconfiguring in the same conditions
- --file=FILE[:TEMPLATE]
- instantiate the configuration file FILE
- --header=FILE[:TEMPLATE]
- instantiate the configuration header FILE
-
-Configuration files:
-$config_files
-
-Configuration headers:
-$config_headers
-
-Configuration commands:
-$config_commands
-
-Report bugs to the package provider."
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
-ac_cs_version="\\
-config.status
-configured by $0, generated by GNU Autoconf 2.69,
- with options \\"\$ac_cs_config\\"
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-
-ac_pwd='$ac_pwd'
-srcdir='$srcdir'
-INSTALL='$INSTALL'
-test -n "\$AWK" || AWK=awk
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# The default lists apply if the user does not specify any file.
-ac_need_defaults=:
-while test $# != 0
-do
- case $1 in
- --*=?*)
- ac_option=`expr "X$1" : 'X\([^=]*\)='`
- ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
- ac_shift=:
- ;;
- --*=)
- ac_option=`expr "X$1" : 'X\([^=]*\)='`
- ac_optarg=
- ac_shift=:
- ;;
- *)
- ac_option=$1
- ac_optarg=$2
- ac_shift=shift
- ;;
- esac
-
- case $ac_option in
- # Handling of the options.
- -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
- ac_cs_recheck=: ;;
- --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
- $as_echo "$ac_cs_version"; exit ;;
- --config | --confi | --conf | --con | --co | --c )
- $as_echo "$ac_cs_config"; exit ;;
- --debug | --debu | --deb | --de | --d | -d )
- debug=: ;;
- --file | --fil | --fi | --f )
- $ac_shift
- case $ac_optarg in
- *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
- '') as_fn_error $? "missing file argument" ;;
- esac
- as_fn_append CONFIG_FILES " '$ac_optarg'"
- ac_need_defaults=false;;
- --header | --heade | --head | --hea )
- $ac_shift
- case $ac_optarg in
- *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
- esac
- as_fn_append CONFIG_HEADERS " '$ac_optarg'"
- ac_need_defaults=false;;
- --he | --h)
- # Conflict between --help and --header
- as_fn_error $? "ambiguous option: \`$1'
-Try \`$0 --help' for more information.";;
- --help | --hel | -h )
- $as_echo "$ac_cs_usage"; exit ;;
- -q | -quiet | --quiet | --quie | --qui | --qu | --q \
- | -silent | --silent | --silen | --sile | --sil | --si | --s)
- ac_cs_silent=: ;;
-
- # This is an error.
- -*) as_fn_error $? "unrecognized option: \`$1'
-Try \`$0 --help' for more information." ;;
-
- *) as_fn_append ac_config_targets " $1"
- ac_need_defaults=false ;;
-
- esac
- shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
- exec 6>/dev/null
- ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-if \$ac_cs_recheck; then
- set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
- shift
- \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
- CONFIG_SHELL='$SHELL'
- export CONFIG_SHELL
- exec "\$@"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-exec 5>>config.log
-{
- echo
- sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
- $as_echo "$ac_log"
-} >&5
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-#
-# INIT-COMMANDS
-#
-
- srcdir="${srcdir}"
- objroot="${objroot}"
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
- mangling_map="${mangling_map}"
- public_syms="${public_syms}"
- JEMALLOC_PREFIX="${JEMALLOC_PREFIX}"
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
-
-
- SHELL="${SHELL}"
- srcdir="${srcdir}"
- objroot="${objroot}"
- LG_QUANTA="${LG_QUANTA}"
- LG_TINY_MIN=${LG_TINY_MIN}
- LG_PAGE_SIZES="${LG_PAGE_SIZES}"
- LG_SIZE_CLASS_GROUP=${LG_SIZE_CLASS_GROUP}
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
-
-
- srcdir="${srcdir}"
- objroot="${objroot}"
- install_suffix="${install_suffix}"
-
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-
-# Handling of arguments.
-for ac_config_target in $ac_config_targets
-do
- case $ac_config_target in
- "include/jemalloc/internal/private_namespace.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/internal/private_namespace.h" ;;
- "include/jemalloc/internal/private_unnamespace.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/internal/private_unnamespace.h" ;;
- "include/jemalloc/internal/public_symbols.txt") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/internal/public_symbols.txt" ;;
- "include/jemalloc/internal/public_namespace.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/internal/public_namespace.h" ;;
- "include/jemalloc/internal/public_unnamespace.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/internal/public_unnamespace.h" ;;
- "include/jemalloc/internal/size_classes.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/internal/size_classes.h" ;;
- "include/jemalloc/jemalloc_protos_jet.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/jemalloc_protos_jet.h" ;;
- "include/jemalloc/jemalloc_rename.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/jemalloc_rename.h" ;;
- "include/jemalloc/jemalloc_mangle.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/jemalloc_mangle.h" ;;
- "include/jemalloc/jemalloc_mangle_jet.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/jemalloc_mangle_jet.h" ;;
- "include/jemalloc/jemalloc.h") CONFIG_COMMANDS="$CONFIG_COMMANDS include/jemalloc/jemalloc.h" ;;
- "$cfghdrs_tup") CONFIG_HEADERS="$CONFIG_HEADERS $cfghdrs_tup" ;;
- "$cfgoutputs_tup") CONFIG_FILES="$CONFIG_FILES $cfgoutputs_tup" ;;
- "config.stamp") CONFIG_FILES="$CONFIG_FILES config.stamp" ;;
- "bin/jemalloc-config") CONFIG_FILES="$CONFIG_FILES bin/jemalloc-config" ;;
- "bin/jemalloc.sh") CONFIG_FILES="$CONFIG_FILES bin/jemalloc.sh" ;;
- "bin/jeprof") CONFIG_FILES="$CONFIG_FILES bin/jeprof" ;;
-
- *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
- esac
-done
-
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used. Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
- test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
- test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
- test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands
-fi
-
-# Have a temporary directory for convenience. Make it in the build tree
-# simply because there is no reason against having it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Hook for its removal unless debugging.
-# Note that there is a small window in which the directory will not be cleaned:
-# after its creation but before its name has been assigned to `$tmp'.
-$debug ||
-{
- tmp= ac_tmp=
- trap 'exit_status=$?
- : "${ac_tmp:=$tmp}"
- { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
-' 0
- trap 'as_fn_exit 1' 1 2 13 15
-}
-# Create a (secure) tmp directory for tmp files.
-
-{
- tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
- test -d "$tmp"
-} ||
-{
- tmp=./conf$$-$RANDOM
- (umask 077 && mkdir "$tmp")
-} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
-ac_tmp=$tmp
-
-# Set up the scripts for CONFIG_FILES section.
-# No need to generate them if there are no CONFIG_FILES.
-# This happens for instance with `./config.status config.h'.
-if test -n "$CONFIG_FILES"; then
-
-
-ac_cr=`echo X | tr X '\015'`
-# On cygwin, bash can eat \r inside `` if the user requested igncr.
-# But we know of no other shell where ac_cr would be empty at this
-# point, so we can use a bashism as a fallback.
-if test "x$ac_cr" = x; then
- eval ac_cr=\$\'\\r\'
-fi
-ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
-if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
- ac_cs_awk_cr='\\r'
-else
- ac_cs_awk_cr=$ac_cr
-fi
-
-echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
-_ACEOF
-
-
-{
- echo "cat >conf$$subs.awk <<_ACEOF" &&
- echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
- echo "_ACEOF"
-} >conf$$subs.sh ||
- as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
-ac_delim='%!_!# '
-for ac_last_try in false false false false false :; do
- . ./conf$$subs.sh ||
- as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-
- ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
- if test $ac_delim_n = $ac_delim_num; then
- break
- elif $ac_last_try; then
- as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
- else
- ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
- fi
-done
-rm -f conf$$subs.sh
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
-_ACEOF
-sed -n '
-h
-s/^/S["/; s/!.*/"]=/
-p
-g
-s/^[^!]*!//
-:repl
-t repl
-s/'"$ac_delim"'$//
-t delim
-:nl
-h
-s/\(.\{148\}\)..*/\1/
-t more1
-s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
-p
-n
-b repl
-:more1
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t nl
-:delim
-h
-s/\(.\{148\}\)..*/\1/
-t more2
-s/["\\]/\\&/g; s/^/"/; s/$/"/
-p
-b
-:more2
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t delim
-' <conf$$subs.awk | sed '
-/^[^""]/{
- N
- s/\n//
-}
-' >>$CONFIG_STATUS || ac_write_fail=1
-rm -f conf$$subs.awk
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-_ACAWK
-cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
- for (key in S) S_is_set[key] = 1
- FS = ""
-
-}
-{
- line = $ 0
- nfields = split(line, field, "@")
- substed = 0
- len = length(field[1])
- for (i = 2; i < nfields; i++) {
- key = field[i]
- keylen = length(key)
- if (S_is_set[key]) {
- value = S[key]
- line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
- len += length(value) + length(field[++i])
- substed = 1
- } else
- len += 1 + keylen
- }
-
- print line
-}
-
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
- sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
-else
- cat
-fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
- || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
-_ACEOF
-
-# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
-# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
- ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{
-h
-s///
-s/^/:/
-s/[ ]*$/:/
-s/:\$(srcdir):/:/g
-s/:\${srcdir}:/:/g
-s/:@srcdir@:/:/g
-s/^:*//
-s/:*$//
-x
-s/\(=[ ]*\).*/\1/
-G
-s/\n//
-s/^[^=]*=[ ]*$//
-}'
-fi
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-fi # test -n "$CONFIG_FILES"
-
-# Set up the scripts for CONFIG_HEADERS section.
-# No need to generate them if there are no CONFIG_HEADERS.
-# This happens for instance with `./config.status Makefile'.
-if test -n "$CONFIG_HEADERS"; then
-cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
-BEGIN {
-_ACEOF
-
-# Transform confdefs.h into an awk script `defines.awk', embedded as
-# here-document in config.status, that substitutes the proper values into
-# config.h.in to produce config.h.
-
-# Create a delimiter string that does not exist in confdefs.h, to ease
-# handling of long lines.
-ac_delim='%!_!# '
-for ac_last_try in false false :; do
- ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
- if test -z "$ac_tt"; then
- break
- elif $ac_last_try; then
- as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
- else
- ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
- fi
-done
-
-# For the awk script, D is an array of macro values keyed by name,
-# likewise P contains macro parameters if any. Preserve backslash
-# newline sequences.
-
-ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
-sed -n '
-s/.\{148\}/&'"$ac_delim"'/g
-t rset
-:rset
-s/^[ ]*#[ ]*define[ ][ ]*/ /
-t def
-d
-:def
-s/\\$//
-t bsnl
-s/["\\]/\\&/g
-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\
-D["\1"]=" \3"/p
-s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p
-d
-:bsnl
-s/["\\]/\\&/g
-s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\
-D["\1"]=" \3\\\\\\n"\\/p
-t cont
-s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p
-t cont
-d
-:cont
-n
-s/.\{148\}/&'"$ac_delim"'/g
-t clear
-:clear
-s/\\$//
-t bsnlc
-s/["\\]/\\&/g; s/^/"/; s/$/"/p
-d
-:bsnlc
-s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p
-b cont
-' <confdefs.h | sed '
-s/'"$ac_delim"'/"\\\
-"/g' >>$CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
- for (key in D) D_is_set[key] = 1
- FS = ""
-}
-/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ {
- line = \$ 0
- split(line, arg, " ")
- if (arg[1] == "#") {
- defundef = arg[2]
- mac1 = arg[3]
- } else {
- defundef = substr(arg[1], 2)
- mac1 = arg[2]
- }
- split(mac1, mac2, "(") #)
- macro = mac2[1]
- prefix = substr(line, 1, index(line, defundef) - 1)
- if (D_is_set[macro]) {
- # Preserve the white space surrounding the "#".
- print prefix "define", macro P[macro] D[macro]
- next
- } else {
- # Replace #undef with comments. This is necessary, for example,
- # in the case of _POSIX_SOURCE, which is predefined and required
- # on some systems where configure will not decide to define it.
- if (defundef == "undef") {
- print "/*", prefix defundef, macro, "*/"
- next
- }
- }
-}
-{ print }
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
- as_fn_error $? "could not setup config headers machinery" "$LINENO" 5
-fi # test -n "$CONFIG_HEADERS"
-
-
-eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS"
-shift
-for ac_tag
-do
- case $ac_tag in
- :[FHLC]) ac_mode=$ac_tag; continue;;
- esac
- case $ac_mode$ac_tag in
- :[FHL]*:*);;
- :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
- :[FH]-) ac_tag=-:-;;
- :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
- esac
- ac_save_IFS=$IFS
- IFS=:
- set x $ac_tag
- IFS=$ac_save_IFS
- shift
- ac_file=$1
- shift
-
- case $ac_mode in
- :L) ac_source=$1;;
- :[FH])
- ac_file_inputs=
- for ac_f
- do
- case $ac_f in
- -) ac_f="$ac_tmp/stdin";;
- *) # Look for the file first in the build tree, then in the source tree
- # (if the path is not absolute). The absolute path cannot be DOS-style,
- # because $ac_f cannot contain `:'.
- test -f "$ac_f" ||
- case $ac_f in
- [\\/$]*) false;;
- *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
- esac ||
- as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
- esac
- case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
- as_fn_append ac_file_inputs " '$ac_f'"
- done
-
- # Let's still pretend it is `configure' which instantiates (i.e., don't
- # use $as_me), people would be surprised to read:
- # /* config.h. Generated by config.status. */
- configure_input='Generated from '`
- $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
- `' by configure.'
- if test x"$ac_file" != x-; then
- configure_input="$ac_file. $configure_input"
- { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
-$as_echo "$as_me: creating $ac_file" >&6;}
- fi
- # Neutralize special characters interpreted by sed in replacement strings.
- case $configure_input in #(
- *\&* | *\|* | *\\* )
- ac_sed_conf_input=`$as_echo "$configure_input" |
- sed 's/[\\\\&|]/\\\\&/g'`;; #(
- *) ac_sed_conf_input=$configure_input;;
- esac
-
- case $ac_tag in
- *:-:* | *:-) cat >"$ac_tmp/stdin" \
- || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
- esac
- ;;
- esac
-
- ac_dir=`$as_dirname -- "$ac_file" ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$ac_file" : 'X\(//\)[^/]' \| \
- X"$ac_file" : 'X\(//\)$' \| \
- X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$ac_file" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- as_dir="$ac_dir"; as_fn_mkdir_p
- ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
- ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
- # A ".." for each directory in $ac_dir_suffix.
- ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
- case $ac_top_builddir_sub in
- "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
- *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
- esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
- .) # We are building in place.
- ac_srcdir=.
- ac_top_srcdir=$ac_top_builddir_sub
- ac_abs_top_srcdir=$ac_pwd ;;
- [\\/]* | ?:[\\/]* ) # Absolute name.
- ac_srcdir=$srcdir$ac_dir_suffix;
- ac_top_srcdir=$srcdir
- ac_abs_top_srcdir=$srcdir ;;
- *) # Relative name.
- ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
- ac_top_srcdir=$ac_top_build_prefix$srcdir
- ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-
- case $ac_mode in
- :F)
- #
- # CONFIG_FILE
- #
-
- case $INSTALL in
- [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
- *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
- esac
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# If the template does not know about datarootdir, expand it.
-# FIXME: This hack should be removed a few years after 2.60.
-ac_datarootdir_hack=; ac_datarootdir_seen=
-ac_sed_dataroot='
-/datarootdir/ {
- p
- q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p'
-case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
- ac_datarootdir_hack='
- s&@datadir@&$datadir&g
- s&@docdir@&$docdir&g
- s&@infodir@&$infodir&g
- s&@localedir@&$localedir&g
- s&@mandir@&$mandir&g
- s&\\\${datarootdir}&$datarootdir&g' ;;
-esac
-_ACEOF
-
-# Neutralize VPATH when `$srcdir' = `.'.
-# Shell code in configure.ac might set extrasub.
-# FIXME: do we really want to maintain this feature?
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_sed_extra="$ac_vpsub
-$extrasub
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s|@configure_input@|$ac_sed_conf_input|;t t
-s&@top_builddir@&$ac_top_builddir_sub&;t t
-s&@top_build_prefix@&$ac_top_build_prefix&;t t
-s&@srcdir@&$ac_srcdir&;t t
-s&@abs_srcdir@&$ac_abs_srcdir&;t t
-s&@top_srcdir@&$ac_top_srcdir&;t t
-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
-s&@builddir@&$ac_builddir&;t t
-s&@abs_builddir@&$ac_abs_builddir&;t t
-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
-s&@INSTALL@&$ac_INSTALL&;t t
-$ac_datarootdir_hack
-"
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
- >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-
-test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
- { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
- { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \
- "$ac_tmp/out"`; test -z "$ac_out"; } &&
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined. Please make sure it is defined" >&5
-$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined. Please make sure it is defined" >&2;}
-
- rm -f "$ac_tmp/stdin"
- case $ac_file in
- -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
- *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
- esac \
- || as_fn_error $? "could not create $ac_file" "$LINENO" 5
- ;;
- :H)
- #
- # CONFIG_HEADER
- #
- if test x"$ac_file" != x-; then
- {
- $as_echo "/* $configure_input */" \
- && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
- } >"$ac_tmp/config.h" \
- || as_fn_error $? "could not create $ac_file" "$LINENO" 5
- if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
-$as_echo "$as_me: $ac_file is unchanged" >&6;}
- else
- rm -f "$ac_file"
- mv "$ac_tmp/config.h" "$ac_file" \
- || as_fn_error $? "could not create $ac_file" "$LINENO" 5
- fi
- else
- $as_echo "/* $configure_input */" \
- && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
- || as_fn_error $? "could not create -" "$LINENO" 5
- fi
- ;;
-
- :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5
-$as_echo "$as_me: executing $ac_file commands" >&6;}
- ;;
- esac
-
-
- case $ac_file$ac_mode in
- "include/jemalloc/internal/private_namespace.h":C)
- mkdir -p "${objroot}include/jemalloc/internal"
- "${srcdir}/include/jemalloc/internal/private_namespace.sh" "${srcdir}/include/jemalloc/internal/private_symbols.txt" > "${objroot}include/jemalloc/internal/private_namespace.h"
- ;;
- "include/jemalloc/internal/private_unnamespace.h":C)
- mkdir -p "${objroot}include/jemalloc/internal"
- "${srcdir}/include/jemalloc/internal/private_unnamespace.sh" "${srcdir}/include/jemalloc/internal/private_symbols.txt" > "${objroot}include/jemalloc/internal/private_unnamespace.h"
- ;;
- "include/jemalloc/internal/public_symbols.txt":C)
- f="${objroot}include/jemalloc/internal/public_symbols.txt"
- mkdir -p "${objroot}include/jemalloc/internal"
- cp /dev/null "${f}"
- for nm in `echo ${mangling_map} |tr ',' ' '` ; do
- n=`echo ${nm} |tr ':' ' ' |awk '{print $1}'`
- m=`echo ${nm} |tr ':' ' ' |awk '{print $2}'`
- echo "${n}:${m}" >> "${f}"
- public_syms=`for sym in ${public_syms}; do echo "${sym}"; done |grep -v "^${n}\$" |tr '\n' ' '`
- done
- for sym in ${public_syms} ; do
- n="${sym}"
- m="${JEMALLOC_PREFIX}${sym}"
- echo "${n}:${m}" >> "${f}"
- done
- ;;
- "include/jemalloc/internal/public_namespace.h":C)
- mkdir -p "${objroot}include/jemalloc/internal"
- "${srcdir}/include/jemalloc/internal/public_namespace.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" > "${objroot}include/jemalloc/internal/public_namespace.h"
- ;;
- "include/jemalloc/internal/public_unnamespace.h":C)
- mkdir -p "${objroot}include/jemalloc/internal"
- "${srcdir}/include/jemalloc/internal/public_unnamespace.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" > "${objroot}include/jemalloc/internal/public_unnamespace.h"
- ;;
- "include/jemalloc/internal/size_classes.h":C)
- mkdir -p "${objroot}include/jemalloc/internal"
- "${SHELL}" "${srcdir}/include/jemalloc/internal/size_classes.sh" "${LG_QUANTA}" ${LG_TINY_MIN} "${LG_PAGE_SIZES}" ${LG_SIZE_CLASS_GROUP} > "${objroot}include/jemalloc/internal/size_classes.h"
- ;;
- "include/jemalloc/jemalloc_protos_jet.h":C)
- mkdir -p "${objroot}include/jemalloc"
- cat "${srcdir}/include/jemalloc/jemalloc_protos.h.in" | sed -e 's/@je_@/jet_/g' > "${objroot}include/jemalloc/jemalloc_protos_jet.h"
- ;;
- "include/jemalloc/jemalloc_rename.h":C)
- mkdir -p "${objroot}include/jemalloc"
- "${srcdir}/include/jemalloc/jemalloc_rename.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" > "${objroot}include/jemalloc/jemalloc_rename.h"
- ;;
- "include/jemalloc/jemalloc_mangle.h":C)
- mkdir -p "${objroot}include/jemalloc"
- "${srcdir}/include/jemalloc/jemalloc_mangle.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" je_ > "${objroot}include/jemalloc/jemalloc_mangle.h"
- ;;
- "include/jemalloc/jemalloc_mangle_jet.h":C)
- mkdir -p "${objroot}include/jemalloc"
- "${srcdir}/include/jemalloc/jemalloc_mangle.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" jet_ > "${objroot}include/jemalloc/jemalloc_mangle_jet.h"
- ;;
- "include/jemalloc/jemalloc.h":C)
- mkdir -p "${objroot}include/jemalloc"
- "${srcdir}/include/jemalloc/jemalloc.sh" "${objroot}" > "${objroot}include/jemalloc/jemalloc${install_suffix}.h"
- ;;
-
- esac
-done # for ac_tag
-
-
-as_fn_exit 0
-_ACEOF
-ac_clean_files=$ac_clean_files_save
-
-test $ac_write_fail = 0 ||
- as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
-
-
-# configure is writing to config.log, and then calls config.status.
-# config.status does its own redirection, appending to config.log.
-# Unfortunately, on DOS this fails, as config.log is still kept open
-# by configure, so config.status won't be able to write to it; its
-# output is simply discarded. So we exec the FD to /dev/null,
-# effectively closing config.log, so it can be properly (re)opened and
-# appended to by config.status. When coming back to configure, we
-# need to make the FD available again.
-if test "$no_create" != yes; then
- ac_cs_success=:
- ac_config_status_args=
- test "$silent" = yes &&
- ac_config_status_args="$ac_config_status_args --quiet"
- exec 5>/dev/null
- $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
- exec 5>>config.log
- # Use ||, not &&, to avoid exiting from the if with $? = 1, which
- # would make configure fail if this is the last instruction.
- $ac_cs_success || as_fn_exit 1
-fi
-if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
-$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
-fi
-
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: ===============================================================================" >&5
-$as_echo "===============================================================================" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: jemalloc version : ${jemalloc_version}" >&5
-$as_echo "jemalloc version : ${jemalloc_version}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: library revision : ${rev}" >&5
-$as_echo "library revision : ${rev}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: CONFIG : ${CONFIG}" >&5
-$as_echo "CONFIG : ${CONFIG}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: CC : ${CC}" >&5
-$as_echo "CC : ${CC}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: CFLAGS : ${CFLAGS}" >&5
-$as_echo "CFLAGS : ${CFLAGS}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: EXTRA_CFLAGS : ${EXTRA_CFLAGS}" >&5
-$as_echo "EXTRA_CFLAGS : ${EXTRA_CFLAGS}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: CPPFLAGS : ${CPPFLAGS}" >&5
-$as_echo "CPPFLAGS : ${CPPFLAGS}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: LDFLAGS : ${LDFLAGS}" >&5
-$as_echo "LDFLAGS : ${LDFLAGS}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: EXTRA_LDFLAGS : ${EXTRA_LDFLAGS}" >&5
-$as_echo "EXTRA_LDFLAGS : ${EXTRA_LDFLAGS}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: LIBS : ${LIBS}" >&5
-$as_echo "LIBS : ${LIBS}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: RPATH_EXTRA : ${RPATH_EXTRA}" >&5
-$as_echo "RPATH_EXTRA : ${RPATH_EXTRA}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: XSLTPROC : ${XSLTPROC}" >&5
-$as_echo "XSLTPROC : ${XSLTPROC}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: XSLROOT : ${XSLROOT}" >&5
-$as_echo "XSLROOT : ${XSLROOT}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: PREFIX : ${PREFIX}" >&5
-$as_echo "PREFIX : ${PREFIX}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: BINDIR : ${BINDIR}" >&5
-$as_echo "BINDIR : ${BINDIR}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: DATADIR : ${DATADIR}" >&5
-$as_echo "DATADIR : ${DATADIR}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: INCLUDEDIR : ${INCLUDEDIR}" >&5
-$as_echo "INCLUDEDIR : ${INCLUDEDIR}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: LIBDIR : ${LIBDIR}" >&5
-$as_echo "LIBDIR : ${LIBDIR}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: MANDIR : ${MANDIR}" >&5
-$as_echo "MANDIR : ${MANDIR}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: srcroot : ${srcroot}" >&5
-$as_echo "srcroot : ${srcroot}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: abs_srcroot : ${abs_srcroot}" >&5
-$as_echo "abs_srcroot : ${abs_srcroot}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: objroot : ${objroot}" >&5
-$as_echo "objroot : ${objroot}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: abs_objroot : ${abs_objroot}" >&5
-$as_echo "abs_objroot : ${abs_objroot}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: JEMALLOC_PREFIX : ${JEMALLOC_PREFIX}" >&5
-$as_echo "JEMALLOC_PREFIX : ${JEMALLOC_PREFIX}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: JEMALLOC_PRIVATE_NAMESPACE" >&5
-$as_echo "JEMALLOC_PRIVATE_NAMESPACE" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: : ${JEMALLOC_PRIVATE_NAMESPACE}" >&5
-$as_echo " : ${JEMALLOC_PRIVATE_NAMESPACE}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: install_suffix : ${install_suffix}" >&5
-$as_echo "install_suffix : ${install_suffix}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: malloc_conf : ${config_malloc_conf}" >&5
-$as_echo "malloc_conf : ${config_malloc_conf}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: autogen : ${enable_autogen}" >&5
-$as_echo "autogen : ${enable_autogen}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: cc-silence : ${enable_cc_silence}" >&5
-$as_echo "cc-silence : ${enable_cc_silence}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: debug : ${enable_debug}" >&5
-$as_echo "debug : ${enable_debug}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: code-coverage : ${enable_code_coverage}" >&5
-$as_echo "code-coverage : ${enable_code_coverage}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: stats : ${enable_stats}" >&5
-$as_echo "stats : ${enable_stats}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: prof : ${enable_prof}" >&5
-$as_echo "prof : ${enable_prof}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: prof-libunwind : ${enable_prof_libunwind}" >&5
-$as_echo "prof-libunwind : ${enable_prof_libunwind}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: prof-libgcc : ${enable_prof_libgcc}" >&5
-$as_echo "prof-libgcc : ${enable_prof_libgcc}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: prof-gcc : ${enable_prof_gcc}" >&5
-$as_echo "prof-gcc : ${enable_prof_gcc}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: tcache : ${enable_tcache}" >&5
-$as_echo "tcache : ${enable_tcache}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: fill : ${enable_fill}" >&5
-$as_echo "fill : ${enable_fill}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: utrace : ${enable_utrace}" >&5
-$as_echo "utrace : ${enable_utrace}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: valgrind : ${enable_valgrind}" >&5
-$as_echo "valgrind : ${enable_valgrind}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: xmalloc : ${enable_xmalloc}" >&5
-$as_echo "xmalloc : ${enable_xmalloc}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: munmap : ${enable_munmap}" >&5
-$as_echo "munmap : ${enable_munmap}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: lazy_lock : ${enable_lazy_lock}" >&5
-$as_echo "lazy_lock : ${enable_lazy_lock}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: tls : ${enable_tls}" >&5
-$as_echo "tls : ${enable_tls}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: cache-oblivious : ${enable_cache_oblivious}" >&5
-$as_echo "cache-oblivious : ${enable_cache_oblivious}" >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: ===============================================================================" >&5
-$as_echo "===============================================================================" >&6; }
diff --git a/memory/jemalloc/src/configure.ac b/memory/jemalloc/src/configure.ac
deleted file mode 100644
index 104fd994d..000000000
--- a/memory/jemalloc/src/configure.ac
+++ /dev/null
@@ -1,1970 +0,0 @@
-dnl Process this file with autoconf to produce a configure script.
-AC_INIT([Makefile.in])
-
-AC_CONFIG_AUX_DIR([build-aux])
-
-dnl ============================================================================
-dnl Custom macro definitions.
-
-dnl JE_CFLAGS_APPEND(cflag)
-AC_DEFUN([JE_CFLAGS_APPEND],
-[
-AC_MSG_CHECKING([whether compiler supports $1])
-TCFLAGS="${CFLAGS}"
-if test "x${CFLAGS}" = "x" ; then
- CFLAGS="$1"
-else
- CFLAGS="${CFLAGS} $1"
-fi
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
-[[
-]], [[
- return 0;
-]])],
- [je_cv_cflags_appended=$1]
- AC_MSG_RESULT([yes]),
- [je_cv_cflags_appended=]
- AC_MSG_RESULT([no])
- [CFLAGS="${TCFLAGS}"]
-)
-])
-
-dnl JE_COMPILABLE(label, hcode, mcode, rvar)
-dnl
-dnl Use AC_LINK_IFELSE() rather than AC_COMPILE_IFELSE() so that linker errors
-dnl cause failure.
-AC_DEFUN([JE_COMPILABLE],
-[
-AC_CACHE_CHECK([whether $1 is compilable],
- [$4],
- [AC_LINK_IFELSE([AC_LANG_PROGRAM([$2],
- [$3])],
- [$4=yes],
- [$4=no])])
-])
-
-dnl ============================================================================
-
-CONFIG=`echo ${ac_configure_args} | sed -e 's#'"'"'\([^ ]*\)'"'"'#\1#g'`
-AC_SUBST([CONFIG])
-
-dnl Library revision.
-rev=2
-AC_SUBST([rev])
-
-srcroot=$srcdir
-if test "x${srcroot}" = "x." ; then
- srcroot=""
-else
- srcroot="${srcroot}/"
-fi
-AC_SUBST([srcroot])
-abs_srcroot="`cd \"${srcdir}\"; pwd`/"
-AC_SUBST([abs_srcroot])
-
-objroot=""
-AC_SUBST([objroot])
-abs_objroot="`pwd`/"
-AC_SUBST([abs_objroot])
-
-dnl Munge install path variables.
-if test "x$prefix" = "xNONE" ; then
- prefix="/usr/local"
-fi
-if test "x$exec_prefix" = "xNONE" ; then
- exec_prefix=$prefix
-fi
-PREFIX=$prefix
-AC_SUBST([PREFIX])
-BINDIR=`eval echo $bindir`
-BINDIR=`eval echo $BINDIR`
-AC_SUBST([BINDIR])
-INCLUDEDIR=`eval echo $includedir`
-INCLUDEDIR=`eval echo $INCLUDEDIR`
-AC_SUBST([INCLUDEDIR])
-LIBDIR=`eval echo $libdir`
-LIBDIR=`eval echo $LIBDIR`
-AC_SUBST([LIBDIR])
-DATADIR=`eval echo $datadir`
-DATADIR=`eval echo $DATADIR`
-AC_SUBST([DATADIR])
-MANDIR=`eval echo $mandir`
-MANDIR=`eval echo $MANDIR`
-AC_SUBST([MANDIR])
-
-dnl Support for building documentation.
-AC_PATH_PROG([XSLTPROC], [xsltproc], [false], [$PATH])
-if test -d "/usr/share/xml/docbook/stylesheet/docbook-xsl" ; then
- DEFAULT_XSLROOT="/usr/share/xml/docbook/stylesheet/docbook-xsl"
-elif test -d "/usr/share/sgml/docbook/xsl-stylesheets" ; then
- DEFAULT_XSLROOT="/usr/share/sgml/docbook/xsl-stylesheets"
-else
- dnl Documentation building will fail if this default gets used.
- DEFAULT_XSLROOT=""
-fi
-AC_ARG_WITH([xslroot],
- [AS_HELP_STRING([--with-xslroot=<path>], [XSL stylesheet root path])], [
-if test "x$with_xslroot" = "xno" ; then
- XSLROOT="${DEFAULT_XSLROOT}"
-else
- XSLROOT="${with_xslroot}"
-fi
-],
- XSLROOT="${DEFAULT_XSLROOT}"
-)
-AC_SUBST([XSLROOT])
-
-dnl If CFLAGS isn't defined, set CFLAGS to something reasonable. Otherwise,
-dnl just prevent autoconf from molesting CFLAGS.
-CFLAGS=$CFLAGS
-AC_PROG_CC
-
-if test "x$GCC" != "xyes" ; then
- AC_CACHE_CHECK([whether compiler is MSVC],
- [je_cv_msvc],
- [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
- [
-#ifndef _MSC_VER
- int fail[-1];
-#endif
-])],
- [je_cv_msvc=yes],
- [je_cv_msvc=no])])
-fi
-
-dnl check if a cray prgenv wrapper compiler is being used
-je_cv_cray_prgenv_wrapper=""
-if test "x${PE_ENV}" != "x" ; then
- case "${CC}" in
- CC|cc)
- je_cv_cray_prgenv_wrapper="yes"
- ;;
- *)
- ;;
- esac
-fi
-
-AC_CACHE_CHECK([whether compiler is cray],
- [je_cv_cray],
- [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
- [
-#ifndef _CRAYC
- int fail[-1];
-#endif
-])],
- [je_cv_cray=yes],
- [je_cv_cray=no])])
-
-if test "x${je_cv_cray}" = "xyes" ; then
- AC_CACHE_CHECK([whether cray compiler version is 8.4],
- [je_cv_cray_84],
- [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],
- [
-#if !(_RELEASE_MAJOR == 8 && _RELEASE_MINOR == 4)
- int fail[-1];
-#endif
-])],
- [je_cv_cray_84=yes],
- [je_cv_cray_84=no])])
-fi
-
-if test "x$CFLAGS" = "x" ; then
- no_CFLAGS="yes"
- if test "x$GCC" = "xyes" ; then
-dnl JE_CFLAGS_APPEND([-std=gnu99])
- JE_CFLAGS_APPEND([-std=gnu11])
- if test "x$je_cv_cflags_appended" = "x-std=gnu11" ; then
- AC_DEFINE_UNQUOTED([JEMALLOC_HAS_RESTRICT])
- else
- JE_CFLAGS_APPEND([-std=gnu99])
- if test "x$je_cv_cflags_appended" = "x-std=gnu99" ; then
- AC_DEFINE_UNQUOTED([JEMALLOC_HAS_RESTRICT])
- fi
- fi
- JE_CFLAGS_APPEND([-Wall])
- JE_CFLAGS_APPEND([-Werror=declaration-after-statement])
- JE_CFLAGS_APPEND([-Wshorten-64-to-32])
- JE_CFLAGS_APPEND([-Wsign-compare])
- JE_CFLAGS_APPEND([-pipe])
- JE_CFLAGS_APPEND([-g3])
- elif test "x$je_cv_msvc" = "xyes" ; then
- CC="$CC -nologo"
- JE_CFLAGS_APPEND([-Zi])
- JE_CFLAGS_APPEND([-MT])
- JE_CFLAGS_APPEND([-W3])
- JE_CFLAGS_APPEND([-FS])
- CPPFLAGS="$CPPFLAGS -I${srcdir}/include/msvc_compat"
- fi
- if test "x$je_cv_cray" = "xyes" ; then
- dnl cray compiler 8.4 has an inlining bug
- if test "x$je_cv_cray_84" = "xyes" ; then
- JE_CFLAGS_APPEND([-hipa2])
- JE_CFLAGS_APPEND([-hnognu])
- fi
- if test "x$enable_cc_silence" != "xno" ; then
- dnl ignore unreachable code warning
- JE_CFLAGS_APPEND([-hnomessage=128])
- dnl ignore redefinition of "malloc", "free", etc warning
- JE_CFLAGS_APPEND([-hnomessage=1357])
- fi
- fi
-fi
-AC_SUBST([EXTRA_CFLAGS])
-AC_PROG_CPP
-
-AC_C_BIGENDIAN([ac_cv_big_endian=1], [ac_cv_big_endian=0])
-if test "x${ac_cv_big_endian}" = "x1" ; then
- AC_DEFINE_UNQUOTED([JEMALLOC_BIG_ENDIAN], [ ])
-fi
-
-if test "x${je_cv_msvc}" = "xyes" -a "x${ac_cv_header_inttypes_h}" = "xno"; then
- CPPFLAGS="$CPPFLAGS -I${srcdir}/include/msvc_compat/C99"
-fi
-
-if test "x${je_cv_msvc}" = "xyes" ; then
- LG_SIZEOF_PTR=LG_SIZEOF_PTR_WIN
- AC_MSG_RESULT([Using a predefined value for sizeof(void *): 4 for 32-bit, 8 for 64-bit])
-else
- AC_CHECK_SIZEOF([void *])
- if test "x${ac_cv_sizeof_void_p}" = "x8" ; then
- LG_SIZEOF_PTR=3
- elif test "x${ac_cv_sizeof_void_p}" = "x4" ; then
- LG_SIZEOF_PTR=2
- else
- AC_MSG_ERROR([Unsupported pointer size: ${ac_cv_sizeof_void_p}])
- fi
-fi
-AC_DEFINE_UNQUOTED([LG_SIZEOF_PTR], [$LG_SIZEOF_PTR])
-
-AC_CHECK_SIZEOF([int])
-if test "x${ac_cv_sizeof_int}" = "x8" ; then
- LG_SIZEOF_INT=3
-elif test "x${ac_cv_sizeof_int}" = "x4" ; then
- LG_SIZEOF_INT=2
-else
- AC_MSG_ERROR([Unsupported int size: ${ac_cv_sizeof_int}])
-fi
-AC_DEFINE_UNQUOTED([LG_SIZEOF_INT], [$LG_SIZEOF_INT])
-
-AC_CHECK_SIZEOF([long])
-if test "x${ac_cv_sizeof_long}" = "x8" ; then
- LG_SIZEOF_LONG=3
-elif test "x${ac_cv_sizeof_long}" = "x4" ; then
- LG_SIZEOF_LONG=2
-else
- AC_MSG_ERROR([Unsupported long size: ${ac_cv_sizeof_long}])
-fi
-AC_DEFINE_UNQUOTED([LG_SIZEOF_LONG], [$LG_SIZEOF_LONG])
-
-AC_CHECK_SIZEOF([long long])
-if test "x${ac_cv_sizeof_long_long}" = "x8" ; then
- LG_SIZEOF_LONG_LONG=3
-elif test "x${ac_cv_sizeof_long_long}" = "x4" ; then
- LG_SIZEOF_LONG_LONG=2
-else
- AC_MSG_ERROR([Unsupported long long size: ${ac_cv_sizeof_long_long}])
-fi
-AC_DEFINE_UNQUOTED([LG_SIZEOF_LONG_LONG], [$LG_SIZEOF_LONG_LONG])
-
-AC_CHECK_SIZEOF([intmax_t])
-if test "x${ac_cv_sizeof_intmax_t}" = "x16" ; then
- LG_SIZEOF_INTMAX_T=4
-elif test "x${ac_cv_sizeof_intmax_t}" = "x8" ; then
- LG_SIZEOF_INTMAX_T=3
-elif test "x${ac_cv_sizeof_intmax_t}" = "x4" ; then
- LG_SIZEOF_INTMAX_T=2
-else
- AC_MSG_ERROR([Unsupported intmax_t size: ${ac_cv_sizeof_intmax_t}])
-fi
-AC_DEFINE_UNQUOTED([LG_SIZEOF_INTMAX_T], [$LG_SIZEOF_INTMAX_T])
-
-AC_CANONICAL_HOST
-dnl CPU-specific settings.
-CPU_SPINWAIT=""
-case "${host_cpu}" in
- i686|x86_64)
- if test "x${je_cv_msvc}" = "xyes" ; then
- AC_CACHE_VAL([je_cv_pause_msvc],
- [JE_COMPILABLE([pause instruction MSVC], [],
- [[_mm_pause(); return 0;]],
- [je_cv_pause_msvc])])
- if test "x${je_cv_pause_msvc}" = "xyes" ; then
- CPU_SPINWAIT='_mm_pause()'
- fi
- else
- AC_CACHE_VAL([je_cv_pause],
- [JE_COMPILABLE([pause instruction], [],
- [[__asm__ volatile("pause"); return 0;]],
- [je_cv_pause])])
- if test "x${je_cv_pause}" = "xyes" ; then
- CPU_SPINWAIT='__asm__ volatile("pause")'
- fi
- fi
- ;;
- powerpc)
- AC_DEFINE_UNQUOTED([HAVE_ALTIVEC], [ ])
- ;;
- *)
- ;;
-esac
-AC_DEFINE_UNQUOTED([CPU_SPINWAIT], [$CPU_SPINWAIT])
-
-LD_PRELOAD_VAR="LD_PRELOAD"
-so="so"
-importlib="${so}"
-o="$ac_objext"
-a="a"
-exe="$ac_exeext"
-libprefix="lib"
-link_whole_archive="0"
-DSO_LDFLAGS='-shared -Wl,-soname,$(@F)'
-RPATH='-Wl,-rpath,$(1)'
-SOREV="${so}.${rev}"
-PIC_CFLAGS='-fPIC -DPIC'
-CTARGET='-o $@'
-LDTARGET='-o $@'
-TEST_LD_MODE=
-EXTRA_LDFLAGS=
-ARFLAGS='crus'
-AROUT=' $@'
-CC_MM=1
-
-if test "x$je_cv_cray_prgenv_wrapper" = "xyes" ; then
- TEST_LD_MODE='-dynamic'
-fi
-
-if test "x${je_cv_cray}" = "xyes" ; then
- CC_MM=
-fi
-
-AN_MAKEVAR([AR], [AC_PROG_AR])
-AN_PROGRAM([ar], [AC_PROG_AR])
-AC_DEFUN([AC_PROG_AR], [AC_CHECK_TOOL(AR, ar, :)])
-AC_PROG_AR
-
-dnl Platform-specific settings. abi and RPATH can probably be determined
-dnl programmatically, but doing so is error-prone, which makes it generally
-dnl not worth the trouble.
-dnl
-dnl Define cpp macros in CPPFLAGS, rather than doing AC_DEFINE(macro), since the
-dnl definitions need to be seen before any headers are included, which is a pain
-dnl to make happen otherwise.
-CFLAGS="$CFLAGS"
-default_munmap="1"
-maps_coalesce="1"
-case "${host}" in
- *-*-darwin* | *-*-ios*)
- abi="macho"
- AC_DEFINE([JEMALLOC_PURGE_MADVISE_FREE], [ ])
- RPATH=""
- LD_PRELOAD_VAR="DYLD_INSERT_LIBRARIES"
- so="dylib"
- importlib="${so}"
- force_tls="0"
- DSO_LDFLAGS='-shared -Wl,-install_name,$(LIBDIR)/$(@F)'
- SOREV="${rev}.${so}"
- sbrk_deprecated="1"
- ;;
- *-*-freebsd*)
- abi="elf"
- AC_DEFINE([JEMALLOC_SYSCTL_VM_OVERCOMMIT], [ ])
- AC_DEFINE([JEMALLOC_PURGE_MADVISE_FREE], [ ])
- force_lazy_lock="1"
- ;;
- *-*-dragonfly*)
- abi="elf"
- AC_DEFINE([JEMALLOC_PURGE_MADVISE_FREE], [ ])
- ;;
- *-*-openbsd*)
- abi="elf"
- AC_DEFINE([JEMALLOC_PURGE_MADVISE_FREE], [ ])
- force_tls="0"
- ;;
- *-*-bitrig*)
- abi="elf"
- AC_DEFINE([JEMALLOC_PURGE_MADVISE_FREE], [ ])
- ;;
- *-*-linux*)
- dnl syscall(2) and secure_getenv(3) are exposed by _GNU_SOURCE.
- CPPFLAGS="$CPPFLAGS -D_GNU_SOURCE"
- abi="elf"
- AC_DEFINE([JEMALLOC_HAS_ALLOCA_H])
- AC_DEFINE([JEMALLOC_PROC_SYS_VM_OVERCOMMIT_MEMORY], [ ])
- AC_DEFINE([JEMALLOC_PURGE_MADVISE_DONTNEED], [ ])
- AC_DEFINE([JEMALLOC_THREADED_INIT], [ ])
- AC_DEFINE([JEMALLOC_USE_CXX_THROW], [ ])
- default_munmap="0"
- ;;
- *-*-netbsd*)
- AC_MSG_CHECKING([ABI])
- AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
-[[#ifdef __ELF__
-/* ELF */
-#else
-#error aout
-#endif
-]])],
- [abi="elf"],
- [abi="aout"])
- AC_MSG_RESULT([$abi])
- AC_DEFINE([JEMALLOC_PURGE_MADVISE_FREE], [ ])
- ;;
- *-*-solaris2*)
- abi="elf"
- AC_DEFINE([JEMALLOC_PURGE_MADVISE_FREE], [ ])
- RPATH='-Wl,-R,$(1)'
- dnl Solaris needs this for sigwait().
- CPPFLAGS="$CPPFLAGS -D_POSIX_PTHREAD_SEMANTICS"
- LIBS="$LIBS -lposix4 -lsocket -lnsl"
- ;;
- *-ibm-aix*)
- if "$LG_SIZEOF_PTR" = "8"; then
- dnl 64bit AIX
- LD_PRELOAD_VAR="LDR_PRELOAD64"
- else
- dnl 32bit AIX
- LD_PRELOAD_VAR="LDR_PRELOAD"
- fi
- abi="xcoff"
- ;;
- *-*-mingw* | *-*-cygwin*)
- abi="pecoff"
- force_tls="0"
- maps_coalesce="0"
- RPATH=""
- so="dll"
- if test "x$je_cv_msvc" = "xyes" ; then
- importlib="lib"
- DSO_LDFLAGS="-LD"
- EXTRA_LDFLAGS="-link -DEBUG"
- CTARGET='-Fo$@'
- LDTARGET='-Fe$@'
- AR='lib'
- ARFLAGS='-nologo -out:'
- AROUT='$@'
- CC_MM=
- else
- importlib="${so}"
- DSO_LDFLAGS="-shared"
- link_whole_archive="1"
- fi
- a="lib"
- libprefix=""
- SOREV="${so}"
- PIC_CFLAGS=""
- ;;
- *)
- AC_MSG_RESULT([Unsupported operating system: ${host}])
- abi="elf"
- ;;
-esac
-
-JEMALLOC_USABLE_SIZE_CONST=const
-AC_CHECK_HEADERS([malloc.h], [
- AC_MSG_CHECKING([whether malloc_usable_size definition can use const argument])
- AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
- [#include <malloc.h>
- #include <stddef.h>
- size_t malloc_usable_size(const void *ptr);
- ],
- [])],[
- AC_MSG_RESULT([yes])
- ],[
- JEMALLOC_USABLE_SIZE_CONST=
- AC_MSG_RESULT([no])
- ])
-])
-AC_DEFINE_UNQUOTED([JEMALLOC_USABLE_SIZE_CONST], [$JEMALLOC_USABLE_SIZE_CONST])
-AC_SUBST([abi])
-AC_SUBST([RPATH])
-AC_SUBST([LD_PRELOAD_VAR])
-AC_SUBST([so])
-AC_SUBST([importlib])
-AC_SUBST([o])
-AC_SUBST([a])
-AC_SUBST([exe])
-AC_SUBST([libprefix])
-AC_SUBST([link_whole_archive])
-AC_SUBST([DSO_LDFLAGS])
-AC_SUBST([EXTRA_LDFLAGS])
-AC_SUBST([SOREV])
-AC_SUBST([PIC_CFLAGS])
-AC_SUBST([CTARGET])
-AC_SUBST([LDTARGET])
-AC_SUBST([TEST_LD_MODE])
-AC_SUBST([MKLIB])
-AC_SUBST([ARFLAGS])
-AC_SUBST([AROUT])
-AC_SUBST([CC_MM])
-
-dnl Determine whether libm must be linked to use e.g. log(3).
-AC_SEARCH_LIBS([log], [m], , [AC_MSG_ERROR([Missing math functions])])
-if test "x$ac_cv_search_log" != "xnone required" ; then
- LM="$ac_cv_search_log"
-else
- LM=
-fi
-AC_SUBST(LM)
-
-JE_COMPILABLE([__attribute__ syntax],
- [static __attribute__((unused)) void foo(void){}],
- [],
- [je_cv_attribute])
-if test "x${je_cv_attribute}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_ATTR], [ ])
- if test "x${GCC}" = "xyes" -a "x${abi}" = "xelf"; then
- JE_CFLAGS_APPEND([-fvisibility=hidden])
- fi
-fi
-dnl Check for tls_model attribute support (clang 3.0 still lacks support).
-SAVED_CFLAGS="${CFLAGS}"
-JE_CFLAGS_APPEND([-Werror])
-JE_CFLAGS_APPEND([-herror_on_warning])
-JE_COMPILABLE([tls_model attribute], [],
- [static __thread int
- __attribute__((tls_model("initial-exec"), unused)) foo;
- foo = 0;],
- [je_cv_tls_model])
-CFLAGS="${SAVED_CFLAGS}"
-if test "x${je_cv_tls_model}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_TLS_MODEL],
- [__attribute__((tls_model("initial-exec")))])
-else
- AC_DEFINE([JEMALLOC_TLS_MODEL], [ ])
-fi
-dnl Check for alloc_size attribute support.
-SAVED_CFLAGS="${CFLAGS}"
-JE_CFLAGS_APPEND([-Werror])
-JE_CFLAGS_APPEND([-herror_on_warning])
-JE_COMPILABLE([alloc_size attribute], [#include <stdlib.h>],
- [void *foo(size_t size) __attribute__((alloc_size(1)));],
- [je_cv_alloc_size])
-CFLAGS="${SAVED_CFLAGS}"
-if test "x${je_cv_alloc_size}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_ATTR_ALLOC_SIZE], [ ])
-fi
-dnl Check for format(gnu_printf, ...) attribute support.
-SAVED_CFLAGS="${CFLAGS}"
-JE_CFLAGS_APPEND([-Werror])
-JE_CFLAGS_APPEND([-herror_on_warning])
-JE_COMPILABLE([format(gnu_printf, ...) attribute], [#include <stdlib.h>],
- [void *foo(const char *format, ...) __attribute__((format(gnu_printf, 1, 2)));],
- [je_cv_format_gnu_printf])
-CFLAGS="${SAVED_CFLAGS}"
-if test "x${je_cv_format_gnu_printf}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_ATTR_FORMAT_GNU_PRINTF], [ ])
-fi
-dnl Check for format(printf, ...) attribute support.
-SAVED_CFLAGS="${CFLAGS}"
-JE_CFLAGS_APPEND([-Werror])
-JE_CFLAGS_APPEND([-herror_on_warning])
-JE_COMPILABLE([format(printf, ...) attribute], [#include <stdlib.h>],
- [void *foo(const char *format, ...) __attribute__((format(printf, 1, 2)));],
- [je_cv_format_printf])
-CFLAGS="${SAVED_CFLAGS}"
-if test "x${je_cv_format_printf}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_ATTR_FORMAT_PRINTF], [ ])
-fi
-
-dnl Support optional additions to rpath.
-AC_ARG_WITH([rpath],
- [AS_HELP_STRING([--with-rpath=<rpath>], [Colon-separated rpath (ELF systems only)])],
-if test "x$with_rpath" = "xno" ; then
- RPATH_EXTRA=
-else
- RPATH_EXTRA="`echo $with_rpath | tr \":\" \" \"`"
-fi,
- RPATH_EXTRA=
-)
-AC_SUBST([RPATH_EXTRA])
-
-dnl Disable rules that do automatic regeneration of configure output by default.
-AC_ARG_ENABLE([autogen],
- [AS_HELP_STRING([--enable-autogen], [Automatically regenerate configure output])],
-if test "x$enable_autogen" = "xno" ; then
- enable_autogen="0"
-else
- enable_autogen="1"
-fi
-,
-enable_autogen="0"
-)
-AC_SUBST([enable_autogen])
-
-AC_PROG_INSTALL
-AC_PROG_RANLIB
-AC_PATH_PROG([LD], [ld], [false], [$PATH])
-AC_PATH_PROG([AUTOCONF], [autoconf], [false], [$PATH])
-
-public_syms="malloc_conf malloc_message malloc calloc posix_memalign aligned_alloc realloc free mallocx rallocx xallocx sallocx dallocx sdallocx nallocx mallctl mallctlnametomib mallctlbymib malloc_stats_print malloc_usable_size"
-
-dnl Check for allocator-related functions that should be wrapped.
-AC_CHECK_FUNC([memalign],
- [AC_DEFINE([JEMALLOC_OVERRIDE_MEMALIGN], [ ])
- public_syms="${public_syms} memalign"])
-AC_CHECK_FUNC([valloc],
- [AC_DEFINE([JEMALLOC_OVERRIDE_VALLOC], [ ])
- public_syms="${public_syms} valloc"])
-
-dnl Do not compute test code coverage by default.
-GCOV_FLAGS=
-AC_ARG_ENABLE([code-coverage],
- [AS_HELP_STRING([--enable-code-coverage],
- [Enable code coverage])],
-[if test "x$enable_code_coverage" = "xno" ; then
- enable_code_coverage="0"
-else
- enable_code_coverage="1"
-fi
-],
-[enable_code_coverage="0"]
-)
-if test "x$enable_code_coverage" = "x1" ; then
- deoptimize="no"
- echo "$CFLAGS $EXTRA_CFLAGS" | grep '\-O' >/dev/null || deoptimize="yes"
- if test "x${deoptimize}" = "xyes" ; then
- JE_CFLAGS_APPEND([-O0])
- fi
- JE_CFLAGS_APPEND([-fprofile-arcs -ftest-coverage])
- EXTRA_LDFLAGS="$EXTRA_LDFLAGS -fprofile-arcs -ftest-coverage"
- AC_DEFINE([JEMALLOC_CODE_COVERAGE], [ ])
-fi
-AC_SUBST([enable_code_coverage])
-
-dnl Perform no name mangling by default.
-AC_ARG_WITH([mangling],
- [AS_HELP_STRING([--with-mangling=<map>], [Mangle symbols in <map>])],
- [mangling_map="$with_mangling"], [mangling_map=""])
-
-dnl Do not prefix public APIs by default.
-AC_ARG_WITH([jemalloc_prefix],
- [AS_HELP_STRING([--with-jemalloc-prefix=<prefix>], [Prefix to prepend to all public APIs])],
- [JEMALLOC_PREFIX="$with_jemalloc_prefix"],
- [if test "x$abi" != "xmacho" -a "x$abi" != "xpecoff"; then
- JEMALLOC_PREFIX=""
-else
- JEMALLOC_PREFIX="je_"
-fi]
-)
-if test "x$JEMALLOC_PREFIX" != "x" ; then
- JEMALLOC_CPREFIX=`echo ${JEMALLOC_PREFIX} | tr "a-z" "A-Z"`
- AC_DEFINE_UNQUOTED([JEMALLOC_PREFIX], ["$JEMALLOC_PREFIX"])
- AC_DEFINE_UNQUOTED([JEMALLOC_CPREFIX], ["$JEMALLOC_CPREFIX"])
-fi
-AC_SUBST([JEMALLOC_CPREFIX])
-
-AC_ARG_WITH([export],
- [AS_HELP_STRING([--without-export], [disable exporting jemalloc public APIs])],
- [if test "x$with_export" = "xno"; then
- AC_DEFINE([JEMALLOC_EXPORT],[])
-fi]
-)
-
-dnl Mangle library-private APIs.
-AC_ARG_WITH([private_namespace],
- [AS_HELP_STRING([--with-private-namespace=<prefix>], [Prefix to prepend to all library-private APIs])],
- [JEMALLOC_PRIVATE_NAMESPACE="${with_private_namespace}je_"],
- [JEMALLOC_PRIVATE_NAMESPACE="je_"]
-)
-AC_DEFINE_UNQUOTED([JEMALLOC_PRIVATE_NAMESPACE], [$JEMALLOC_PRIVATE_NAMESPACE])
-private_namespace="$JEMALLOC_PRIVATE_NAMESPACE"
-AC_SUBST([private_namespace])
-
-dnl Do not add suffix to installed files by default.
-AC_ARG_WITH([install_suffix],
- [AS_HELP_STRING([--with-install-suffix=<suffix>], [Suffix to append to all installed files])],
- [INSTALL_SUFFIX="$with_install_suffix"],
- [INSTALL_SUFFIX=]
-)
-install_suffix="$INSTALL_SUFFIX"
-AC_SUBST([install_suffix])
-
-dnl Specify default malloc_conf.
-AC_ARG_WITH([malloc_conf],
- [AS_HELP_STRING([--with-malloc-conf=<malloc_conf>], [config.malloc_conf options string])],
- [JEMALLOC_CONFIG_MALLOC_CONF="$with_malloc_conf"],
- [JEMALLOC_CONFIG_MALLOC_CONF=""]
-)
-config_malloc_conf="$JEMALLOC_CONFIG_MALLOC_CONF"
-AC_DEFINE_UNQUOTED([JEMALLOC_CONFIG_MALLOC_CONF], ["$config_malloc_conf"])
-
-dnl Substitute @je_@ in jemalloc_protos.h.in, primarily to make generation of
-dnl jemalloc_protos_jet.h easy.
-je_="je_"
-AC_SUBST([je_])
-
-cfgoutputs_in="Makefile.in"
-cfgoutputs_in="${cfgoutputs_in} jemalloc.pc.in"
-cfgoutputs_in="${cfgoutputs_in} doc/html.xsl.in"
-cfgoutputs_in="${cfgoutputs_in} doc/manpages.xsl.in"
-cfgoutputs_in="${cfgoutputs_in} doc/jemalloc.xml.in"
-cfgoutputs_in="${cfgoutputs_in} include/jemalloc/jemalloc_macros.h.in"
-cfgoutputs_in="${cfgoutputs_in} include/jemalloc/jemalloc_protos.h.in"
-cfgoutputs_in="${cfgoutputs_in} include/jemalloc/jemalloc_typedefs.h.in"
-cfgoutputs_in="${cfgoutputs_in} include/jemalloc/internal/jemalloc_internal.h.in"
-cfgoutputs_in="${cfgoutputs_in} test/test.sh.in"
-cfgoutputs_in="${cfgoutputs_in} test/include/test/jemalloc_test.h.in"
-
-cfgoutputs_out="Makefile"
-cfgoutputs_out="${cfgoutputs_out} jemalloc.pc"
-cfgoutputs_out="${cfgoutputs_out} doc/html.xsl"
-cfgoutputs_out="${cfgoutputs_out} doc/manpages.xsl"
-cfgoutputs_out="${cfgoutputs_out} doc/jemalloc.xml"
-cfgoutputs_out="${cfgoutputs_out} include/jemalloc/jemalloc_macros.h"
-cfgoutputs_out="${cfgoutputs_out} include/jemalloc/jemalloc_protos.h"
-cfgoutputs_out="${cfgoutputs_out} include/jemalloc/jemalloc_typedefs.h"
-cfgoutputs_out="${cfgoutputs_out} include/jemalloc/internal/jemalloc_internal.h"
-cfgoutputs_out="${cfgoutputs_out} test/test.sh"
-cfgoutputs_out="${cfgoutputs_out} test/include/test/jemalloc_test.h"
-
-cfgoutputs_tup="Makefile"
-cfgoutputs_tup="${cfgoutputs_tup} jemalloc.pc:jemalloc.pc.in"
-cfgoutputs_tup="${cfgoutputs_tup} doc/html.xsl:doc/html.xsl.in"
-cfgoutputs_tup="${cfgoutputs_tup} doc/manpages.xsl:doc/manpages.xsl.in"
-cfgoutputs_tup="${cfgoutputs_tup} doc/jemalloc.xml:doc/jemalloc.xml.in"
-cfgoutputs_tup="${cfgoutputs_tup} include/jemalloc/jemalloc_macros.h:include/jemalloc/jemalloc_macros.h.in"
-cfgoutputs_tup="${cfgoutputs_tup} include/jemalloc/jemalloc_protos.h:include/jemalloc/jemalloc_protos.h.in"
-cfgoutputs_tup="${cfgoutputs_tup} include/jemalloc/jemalloc_typedefs.h:include/jemalloc/jemalloc_typedefs.h.in"
-cfgoutputs_tup="${cfgoutputs_tup} include/jemalloc/internal/jemalloc_internal.h"
-cfgoutputs_tup="${cfgoutputs_tup} test/test.sh:test/test.sh.in"
-cfgoutputs_tup="${cfgoutputs_tup} test/include/test/jemalloc_test.h:test/include/test/jemalloc_test.h.in"
-
-cfghdrs_in="include/jemalloc/jemalloc_defs.h.in"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/jemalloc_internal_defs.h.in"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/private_namespace.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/private_unnamespace.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/private_symbols.txt"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/public_namespace.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/public_unnamespace.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/internal/size_classes.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/jemalloc_rename.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/jemalloc_mangle.sh"
-cfghdrs_in="${cfghdrs_in} include/jemalloc/jemalloc.sh"
-cfghdrs_in="${cfghdrs_in} test/include/test/jemalloc_test_defs.h.in"
-
-cfghdrs_out="include/jemalloc/jemalloc_defs.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc${install_suffix}.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/private_namespace.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/private_unnamespace.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/public_symbols.txt"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/public_namespace.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/public_unnamespace.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/size_classes.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc_protos_jet.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc_rename.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc_mangle.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/jemalloc_mangle_jet.h"
-cfghdrs_out="${cfghdrs_out} include/jemalloc/internal/jemalloc_internal_defs.h"
-cfghdrs_out="${cfghdrs_out} test/include/test/jemalloc_test_defs.h"
-
-cfghdrs_tup="include/jemalloc/jemalloc_defs.h:include/jemalloc/jemalloc_defs.h.in"
-cfghdrs_tup="${cfghdrs_tup} include/jemalloc/internal/jemalloc_internal_defs.h:include/jemalloc/internal/jemalloc_internal_defs.h.in"
-cfghdrs_tup="${cfghdrs_tup} test/include/test/jemalloc_test_defs.h:test/include/test/jemalloc_test_defs.h.in"
-
-dnl Silence irrelevant compiler warnings by default.
-AC_ARG_ENABLE([cc-silence],
- [AS_HELP_STRING([--disable-cc-silence],
- [Do not silence irrelevant compiler warnings])],
-[if test "x$enable_cc_silence" = "xno" ; then
- enable_cc_silence="0"
-else
- enable_cc_silence="1"
-fi
-],
-[enable_cc_silence="1"]
-)
-if test "x$enable_cc_silence" = "x1" ; then
- AC_DEFINE([JEMALLOC_CC_SILENCE], [ ])
-fi
-
-dnl Do not compile with debugging by default.
-AC_ARG_ENABLE([debug],
- [AS_HELP_STRING([--enable-debug],
- [Build debugging code (implies --enable-ivsalloc)])],
-[if test "x$enable_debug" = "xno" ; then
- enable_debug="0"
-else
- enable_debug="1"
-fi
-],
-[enable_debug="0"]
-)
-if test "x$enable_debug" = "x1" ; then
- AC_DEFINE([JEMALLOC_DEBUG], [ ])
-fi
-if test "x$enable_debug" = "x1" ; then
- AC_DEFINE([JEMALLOC_DEBUG], [ ])
- enable_ivsalloc="1"
-fi
-AC_SUBST([enable_debug])
-
-dnl Do not validate pointers by default.
-AC_ARG_ENABLE([ivsalloc],
- [AS_HELP_STRING([--enable-ivsalloc],
- [Validate pointers passed through the public API])],
-[if test "x$enable_ivsalloc" = "xno" ; then
- enable_ivsalloc="0"
-else
- enable_ivsalloc="1"
-fi
-],
-[enable_ivsalloc="0"]
-)
-if test "x$enable_ivsalloc" = "x1" ; then
- AC_DEFINE([JEMALLOC_IVSALLOC], [ ])
-fi
-
-dnl Only optimize if not debugging.
-if test "x$enable_debug" = "x0" -a "x$no_CFLAGS" = "xyes" ; then
- dnl Make sure that an optimization flag was not specified in EXTRA_CFLAGS.
- optimize="no"
- echo "$CFLAGS $EXTRA_CFLAGS" | grep '\-O' >/dev/null || optimize="yes"
- if test "x${optimize}" = "xyes" ; then
- if test "x$GCC" = "xyes" ; then
- JE_CFLAGS_APPEND([-O3])
- JE_CFLAGS_APPEND([-funroll-loops])
- elif test "x$je_cv_msvc" = "xyes" ; then
- JE_CFLAGS_APPEND([-O2])
- else
- JE_CFLAGS_APPEND([-O])
- fi
- fi
-fi
-
-dnl Enable statistics calculation by default.
-AC_ARG_ENABLE([stats],
- [AS_HELP_STRING([--disable-stats],
- [Disable statistics calculation/reporting])],
-[if test "x$enable_stats" = "xno" ; then
- enable_stats="0"
-else
- enable_stats="1"
-fi
-],
-[enable_stats="1"]
-)
-if test "x$enable_stats" = "x1" ; then
- AC_DEFINE([JEMALLOC_STATS], [ ])
-fi
-AC_SUBST([enable_stats])
-
-dnl Do not enable profiling by default.
-AC_ARG_ENABLE([prof],
- [AS_HELP_STRING([--enable-prof], [Enable allocation profiling])],
-[if test "x$enable_prof" = "xno" ; then
- enable_prof="0"
-else
- enable_prof="1"
-fi
-],
-[enable_prof="0"]
-)
-if test "x$enable_prof" = "x1" ; then
- backtrace_method=""
-else
- backtrace_method="N/A"
-fi
-
-AC_ARG_ENABLE([prof-libunwind],
- [AS_HELP_STRING([--enable-prof-libunwind], [Use libunwind for backtracing])],
-[if test "x$enable_prof_libunwind" = "xno" ; then
- enable_prof_libunwind="0"
-else
- enable_prof_libunwind="1"
-fi
-],
-[enable_prof_libunwind="0"]
-)
-AC_ARG_WITH([static_libunwind],
- [AS_HELP_STRING([--with-static-libunwind=<libunwind.a>],
- [Path to static libunwind library; use rather than dynamically linking])],
-if test "x$with_static_libunwind" = "xno" ; then
- LUNWIND="-lunwind"
-else
- if test ! -f "$with_static_libunwind" ; then
- AC_MSG_ERROR([Static libunwind not found: $with_static_libunwind])
- fi
- LUNWIND="$with_static_libunwind"
-fi,
- LUNWIND="-lunwind"
-)
-if test "x$backtrace_method" = "x" -a "x$enable_prof_libunwind" = "x1" ; then
- AC_CHECK_HEADERS([libunwind.h], , [enable_prof_libunwind="0"])
- if test "x$LUNWIND" = "x-lunwind" ; then
- AC_CHECK_LIB([unwind], [unw_backtrace], [LIBS="$LIBS $LUNWIND"],
- [enable_prof_libunwind="0"])
- else
- LIBS="$LIBS $LUNWIND"
- fi
- if test "x${enable_prof_libunwind}" = "x1" ; then
- backtrace_method="libunwind"
- AC_DEFINE([JEMALLOC_PROF_LIBUNWIND], [ ])
- fi
-fi
-
-AC_ARG_ENABLE([prof-libgcc],
- [AS_HELP_STRING([--disable-prof-libgcc],
- [Do not use libgcc for backtracing])],
-[if test "x$enable_prof_libgcc" = "xno" ; then
- enable_prof_libgcc="0"
-else
- enable_prof_libgcc="1"
-fi
-],
-[enable_prof_libgcc="1"]
-)
-if test "x$backtrace_method" = "x" -a "x$enable_prof_libgcc" = "x1" \
- -a "x$GCC" = "xyes" ; then
- AC_CHECK_HEADERS([unwind.h], , [enable_prof_libgcc="0"])
- AC_CHECK_LIB([gcc], [_Unwind_Backtrace], [LIBS="$LIBS -lgcc"], [enable_prof_libgcc="0"])
- if test "x${enable_prof_libgcc}" = "x1" ; then
- backtrace_method="libgcc"
- AC_DEFINE([JEMALLOC_PROF_LIBGCC], [ ])
- fi
-else
- enable_prof_libgcc="0"
-fi
-
-AC_ARG_ENABLE([prof-gcc],
- [AS_HELP_STRING([--disable-prof-gcc],
- [Do not use gcc intrinsics for backtracing])],
-[if test "x$enable_prof_gcc" = "xno" ; then
- enable_prof_gcc="0"
-else
- enable_prof_gcc="1"
-fi
-],
-[enable_prof_gcc="1"]
-)
-if test "x$backtrace_method" = "x" -a "x$enable_prof_gcc" = "x1" \
- -a "x$GCC" = "xyes" ; then
- JE_CFLAGS_APPEND([-fno-omit-frame-pointer])
- backtrace_method="gcc intrinsics"
- AC_DEFINE([JEMALLOC_PROF_GCC], [ ])
-else
- enable_prof_gcc="0"
-fi
-
-if test "x$backtrace_method" = "x" ; then
- backtrace_method="none (disabling profiling)"
- enable_prof="0"
-fi
-AC_MSG_CHECKING([configured backtracing method])
-AC_MSG_RESULT([$backtrace_method])
-if test "x$enable_prof" = "x1" ; then
- dnl Heap profiling uses the log(3) function.
- if test "x$LM" != "x" ; then
- LIBS="$LIBS $LM"
- fi
-
- AC_DEFINE([JEMALLOC_PROF], [ ])
-fi
-AC_SUBST([enable_prof])
-
-dnl Enable thread-specific caching by default.
-AC_ARG_ENABLE([tcache],
- [AS_HELP_STRING([--disable-tcache], [Disable per thread caches])],
-[if test "x$enable_tcache" = "xno" ; then
- enable_tcache="0"
-else
- enable_tcache="1"
-fi
-],
-[enable_tcache="1"]
-)
-if test "x$enable_tcache" = "x1" ; then
- AC_DEFINE([JEMALLOC_TCACHE], [ ])
-fi
-AC_SUBST([enable_tcache])
-
-dnl Indicate whether adjacent virtual memory mappings automatically coalesce
-dnl (and fragment on demand).
-if test "x${maps_coalesce}" = "x1" ; then
- AC_DEFINE([JEMALLOC_MAPS_COALESCE], [ ])
-fi
-
-dnl Enable VM deallocation via munmap() by default.
-AC_ARG_ENABLE([munmap],
- [AS_HELP_STRING([--disable-munmap], [Disable VM deallocation via munmap(2)])],
-[if test "x$enable_munmap" = "xno" ; then
- enable_munmap="0"
-else
- enable_munmap="1"
-fi
-],
-[enable_munmap="${default_munmap}"]
-)
-if test "x$enable_munmap" = "x1" ; then
- AC_DEFINE([JEMALLOC_MUNMAP], [ ])
-fi
-AC_SUBST([enable_munmap])
-
-dnl Enable allocation from DSS if supported by the OS.
-have_dss="1"
-dnl Check whether the BSD/SUSv1 sbrk() exists. If not, disable DSS support.
-AC_CHECK_FUNC([sbrk], [have_sbrk="1"], [have_sbrk="0"])
-if test "x$have_sbrk" = "x1" ; then
- if test "x$sbrk_deprecated" = "x1" ; then
- AC_MSG_RESULT([Disabling dss allocation because sbrk is deprecated])
- have_dss="0"
- fi
-else
- have_dss="0"
-fi
-
-if test "x$have_dss" = "x1" ; then
- AC_DEFINE([JEMALLOC_DSS], [ ])
-fi
-
-dnl Support the junk/zero filling option by default.
-AC_ARG_ENABLE([fill],
- [AS_HELP_STRING([--disable-fill],
- [Disable support for junk/zero filling, quarantine, and redzones])],
-[if test "x$enable_fill" = "xno" ; then
- enable_fill="0"
-else
- enable_fill="1"
-fi
-],
-[enable_fill="1"]
-)
-if test "x$enable_fill" = "x1" ; then
- AC_DEFINE([JEMALLOC_FILL], [ ])
-fi
-AC_SUBST([enable_fill])
-
-dnl Disable utrace(2)-based tracing by default.
-AC_ARG_ENABLE([utrace],
- [AS_HELP_STRING([--enable-utrace], [Enable utrace(2)-based tracing])],
-[if test "x$enable_utrace" = "xno" ; then
- enable_utrace="0"
-else
- enable_utrace="1"
-fi
-],
-[enable_utrace="0"]
-)
-JE_COMPILABLE([utrace(2)], [
-#include <sys/types.h>
-#include <sys/param.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/ktrace.h>
-], [
- utrace((void *)0, 0);
-], [je_cv_utrace])
-if test "x${je_cv_utrace}" = "xno" ; then
- enable_utrace="0"
-fi
-if test "x$enable_utrace" = "x1" ; then
- AC_DEFINE([JEMALLOC_UTRACE], [ ])
-fi
-AC_SUBST([enable_utrace])
-
-dnl Support Valgrind by default.
-AC_ARG_ENABLE([valgrind],
- [AS_HELP_STRING([--disable-valgrind], [Disable support for Valgrind])],
-[if test "x$enable_valgrind" = "xno" ; then
- enable_valgrind="0"
-else
- enable_valgrind="1"
-fi
-],
-[enable_valgrind="1"]
-)
-if test "x$enable_valgrind" = "x1" ; then
- JE_COMPILABLE([valgrind], [
-#include <valgrind/valgrind.h>
-#include <valgrind/memcheck.h>
-
-#if !defined(VALGRIND_RESIZEINPLACE_BLOCK)
-# error "Incompatible Valgrind version"
-#endif
-], [], [je_cv_valgrind])
- if test "x${je_cv_valgrind}" = "xno" ; then
- enable_valgrind="0"
- fi
- if test "x$enable_valgrind" = "x1" ; then
- AC_DEFINE([JEMALLOC_VALGRIND], [ ])
- fi
-fi
-AC_SUBST([enable_valgrind])
-
-dnl Do not support the xmalloc option by default.
-AC_ARG_ENABLE([xmalloc],
- [AS_HELP_STRING([--enable-xmalloc], [Support xmalloc option])],
-[if test "x$enable_xmalloc" = "xno" ; then
- enable_xmalloc="0"
-else
- enable_xmalloc="1"
-fi
-],
-[enable_xmalloc="0"]
-)
-if test "x$enable_xmalloc" = "x1" ; then
- AC_DEFINE([JEMALLOC_XMALLOC], [ ])
-fi
-AC_SUBST([enable_xmalloc])
-
-dnl Support cache-oblivious allocation alignment by default.
-AC_ARG_ENABLE([cache-oblivious],
- [AS_HELP_STRING([--disable-cache-oblivious],
- [Disable support for cache-oblivious allocation alignment])],
-[if test "x$enable_cache_oblivious" = "xno" ; then
- enable_cache_oblivious="0"
-else
- enable_cache_oblivious="1"
-fi
-],
-[enable_cache_oblivious="1"]
-)
-if test "x$enable_cache_oblivious" = "x1" ; then
- AC_DEFINE([JEMALLOC_CACHE_OBLIVIOUS], [ ])
-fi
-AC_SUBST([enable_cache_oblivious])
-
-
-
-JE_COMPILABLE([a program using __builtin_unreachable], [
-void foo (void) {
- __builtin_unreachable();
-}
-], [
- {
- foo();
- }
-], [je_cv_gcc_builtin_unreachable])
-if test "x${je_cv_gcc_builtin_unreachable}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_INTERNAL_UNREACHABLE], [__builtin_unreachable])
-else
- AC_DEFINE([JEMALLOC_INTERNAL_UNREACHABLE], [abort])
-fi
-
-dnl ============================================================================
-dnl Check for __builtin_ffsl(), then ffsl(3), and fail if neither are found.
-dnl One of those two functions should (theoretically) exist on all platforms
-dnl that jemalloc currently has a chance of functioning on without modification.
-dnl We additionally assume ffs[ll]() or __builtin_ffs[ll]() are defined if
-dnl ffsl() or __builtin_ffsl() are defined, respectively.
-JE_COMPILABLE([a program using __builtin_ffsl], [
-#include <stdio.h>
-#include <strings.h>
-#include <string.h>
-], [
- {
- int rv = __builtin_ffsl(0x08);
- printf("%d\n", rv);
- }
-], [je_cv_gcc_builtin_ffsl])
-if test "x${je_cv_gcc_builtin_ffsl}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_INTERNAL_FFSLL], [__builtin_ffsll])
- AC_DEFINE([JEMALLOC_INTERNAL_FFSL], [__builtin_ffsl])
- AC_DEFINE([JEMALLOC_INTERNAL_FFS], [__builtin_ffs])
-else
- JE_COMPILABLE([a program using ffsl], [
- #include <stdio.h>
- #include <strings.h>
- #include <string.h>
- ], [
- {
- int rv = ffsl(0x08);
- printf("%d\n", rv);
- }
- ], [je_cv_function_ffsl])
- if test "x${je_cv_function_ffsl}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_INTERNAL_FFSLL], [ffsll])
- AC_DEFINE([JEMALLOC_INTERNAL_FFSL], [ffsl])
- AC_DEFINE([JEMALLOC_INTERNAL_FFS], [ffs])
- else
- AC_MSG_ERROR([Cannot build without ffsl(3) or __builtin_ffsl()])
- fi
-fi
-
-AC_ARG_WITH([lg_tiny_min],
- [AS_HELP_STRING([--with-lg-tiny-min=<lg-tiny-min>],
- [Base 2 log of minimum tiny size class to support])],
- [LG_TINY_MIN="$with_lg_tiny_min"],
- [LG_TINY_MIN="3"])
-AC_DEFINE_UNQUOTED([LG_TINY_MIN], [$LG_TINY_MIN])
-
-AC_ARG_WITH([lg_quantum],
- [AS_HELP_STRING([--with-lg-quantum=<lg-quantum>],
- [Base 2 log of minimum allocation alignment])],
- [LG_QUANTA="$with_lg_quantum"],
- [LG_QUANTA="3 4"])
-if test "x$with_lg_quantum" != "x" ; then
- AC_DEFINE_UNQUOTED([LG_QUANTUM], [$with_lg_quantum])
-fi
-
-AC_ARG_WITH([lg_page],
- [AS_HELP_STRING([--with-lg-page=<lg-page>], [Base 2 log of system page size])],
- [LG_PAGE="$with_lg_page"], [LG_PAGE="detect"])
-if test "x$LG_PAGE" = "xdetect"; then
- AC_CACHE_CHECK([LG_PAGE],
- [je_cv_lg_page],
- AC_RUN_IFELSE([AC_LANG_PROGRAM(
-[[
-#include <strings.h>
-#ifdef _WIN32
-#include <windows.h>
-#else
-#include <unistd.h>
-#endif
-#include <stdio.h>
-]],
-[[
- int result;
- FILE *f;
-
-#ifdef _WIN32
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- result = si.dwPageSize;
-#else
- result = sysconf(_SC_PAGESIZE);
-#endif
- if (result == -1) {
- return 1;
- }
- result = JEMALLOC_INTERNAL_FFSL(result) - 1;
-
- f = fopen("conftest.out", "w");
- if (f == NULL) {
- return 1;
- }
- fprintf(f, "%d", result);
- fclose(f);
-
- return 0;
-]])],
- [je_cv_lg_page=`cat conftest.out`],
- [je_cv_lg_page=undefined],
- [je_cv_lg_page=12]))
-fi
-if test "x${je_cv_lg_page}" != "x" ; then
- LG_PAGE="${je_cv_lg_page}"
-fi
-if test "x${LG_PAGE}" != "xundefined" ; then
- AC_DEFINE_UNQUOTED([LG_PAGE], [$LG_PAGE])
-else
- AC_MSG_ERROR([cannot determine value for LG_PAGE])
-fi
-
-AC_ARG_WITH([lg_page_sizes],
- [AS_HELP_STRING([--with-lg-page-sizes=<lg-page-sizes>],
- [Base 2 logs of system page sizes to support])],
- [LG_PAGE_SIZES="$with_lg_page_sizes"], [LG_PAGE_SIZES="$LG_PAGE"])
-
-AC_ARG_WITH([lg_size_class_group],
- [AS_HELP_STRING([--with-lg-size-class-group=<lg-size-class-group>],
- [Base 2 log of size classes per doubling])],
- [LG_SIZE_CLASS_GROUP="$with_lg_size_class_group"],
- [LG_SIZE_CLASS_GROUP="2"])
-
-dnl ============================================================================
-dnl jemalloc configuration.
-dnl
-
-AC_ARG_WITH([version],
- [AS_HELP_STRING([--with-version=<major>.<minor>.<bugfix>-<nrev>-g<gid>],
- [Version string])],
- [
- echo "${with_version}" | grep ['^[0-9]\+\.[0-9]\+\.[0-9]\+-[0-9]\+-g[0-9a-f]\+$'] 2>&1 1>/dev/null
- if test $? -ne 0 ; then
- AC_MSG_ERROR([${with_version} does not match <major>.<minor>.<bugfix>-<nrev>-g<gid>])
- fi
- echo "$with_version" > "${objroot}VERSION"
- ], [
- dnl Set VERSION if source directory is inside a git repository.
- if test "x`test ! \"${srcroot}\" && cd \"${srcroot}\"; git rev-parse --is-inside-work-tree 2>/dev/null`" = "xtrue" ; then
- dnl Pattern globs aren't powerful enough to match both single- and
- dnl double-digit version numbers, so iterate over patterns to support up
- dnl to version 99.99.99 without any accidental matches.
- for pattern in ['[0-9].[0-9].[0-9]' '[0-9].[0-9].[0-9][0-9]' \
- '[0-9].[0-9][0-9].[0-9]' '[0-9].[0-9][0-9].[0-9][0-9]' \
- '[0-9][0-9].[0-9].[0-9]' '[0-9][0-9].[0-9].[0-9][0-9]' \
- '[0-9][0-9].[0-9][0-9].[0-9]' \
- '[0-9][0-9].[0-9][0-9].[0-9][0-9]']; do
- (test ! "${srcroot}" && cd "${srcroot}"; git describe --long --abbrev=40 --match="${pattern}") > "${objroot}VERSION.tmp" 2>/dev/null
- if test $? -eq 0 ; then
- mv "${objroot}VERSION.tmp" "${objroot}VERSION"
- break
- fi
- done
- fi
- rm -f "${objroot}VERSION.tmp"
- ])
-
-if test ! -e "${objroot}VERSION" ; then
- if test ! -e "${srcroot}VERSION" ; then
- AC_MSG_RESULT(
- [Missing VERSION file, and unable to generate it; creating bogus VERSION])
- echo "0.0.0-0-g0000000000000000000000000000000000000000" > "${objroot}VERSION"
- else
- cp ${srcroot}VERSION ${objroot}VERSION
- fi
-fi
-jemalloc_version=`cat "${objroot}VERSION"`
-jemalloc_version_major=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print [$]1}'`
-jemalloc_version_minor=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print [$]2}'`
-jemalloc_version_bugfix=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print [$]3}'`
-jemalloc_version_nrev=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print [$]4}'`
-jemalloc_version_gid=`echo ${jemalloc_version} | tr ".g-" " " | awk '{print [$]5}'`
-AC_SUBST([jemalloc_version])
-AC_SUBST([jemalloc_version_major])
-AC_SUBST([jemalloc_version_minor])
-AC_SUBST([jemalloc_version_bugfix])
-AC_SUBST([jemalloc_version_nrev])
-AC_SUBST([jemalloc_version_gid])
-
-dnl ============================================================================
-dnl Configure pthreads.
-
-if test "x$abi" != "xpecoff" ; then
- AC_CHECK_HEADERS([pthread.h], , [AC_MSG_ERROR([pthread.h is missing])])
- dnl Some systems may embed pthreads functionality in libc; check for libpthread
- dnl first, but try libc too before failing.
- AC_CHECK_LIB([pthread], [pthread_create], [LIBS="$LIBS -lpthread"],
- [AC_SEARCH_LIBS([pthread_create], , ,
- AC_MSG_ERROR([libpthread is missing]))])
-fi
-
-CPPFLAGS="$CPPFLAGS -D_REENTRANT"
-
-dnl Check whether clock_gettime(2) is in libc or librt.
-AC_SEARCH_LIBS([clock_gettime], [rt])
-
-dnl Cray wrapper compiler often adds `-lrt` when using `-static`. Check with
-dnl `-dynamic` as well in case a user tries to dynamically link in jemalloc
-if test "x$je_cv_cray_prgenv_wrapper" = "xyes" ; then
- if test "$ac_cv_search_clock_gettime" != "-lrt"; then
- SAVED_CFLAGS="${CFLAGS}"
-
- unset ac_cv_search_clock_gettime
- JE_CFLAGS_APPEND([-dynamic])
- AC_SEARCH_LIBS([clock_gettime], [rt])
-
- CFLAGS="${SAVED_CFLAGS}"
- fi
-fi
-
-dnl check for CLOCK_MONOTONIC_COARSE (Linux-specific).
-JE_COMPILABLE([clock_gettime(CLOCK_MONOTONIC_COARSE, ...)], [
-#include <time.h>
-], [
- struct timespec ts;
-
- clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
-], [je_cv_clock_monotonic_coarse])
-if test "x${je_cv_clock_monotonic_coarse}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_CLOCK_MONOTONIC_COARSE])
-fi
-
-dnl check for CLOCK_MONOTONIC.
-JE_COMPILABLE([clock_gettime(CLOCK_MONOTONIC, ...)], [
-#include <unistd.h>
-#include <time.h>
-], [
- struct timespec ts;
-
- clock_gettime(CLOCK_MONOTONIC, &ts);
-#if !defined(_POSIX_MONOTONIC_CLOCK) || _POSIX_MONOTONIC_CLOCK < 0
-# error _POSIX_MONOTONIC_CLOCK missing/invalid
-#endif
-], [je_cv_clock_monotonic])
-if test "x${je_cv_clock_monotonic}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_CLOCK_MONOTONIC])
-fi
-
-dnl Check for mach_absolute_time().
-JE_COMPILABLE([mach_absolute_time()], [
-#include <mach/mach_time.h>
-], [
- mach_absolute_time();
-], [je_cv_mach_absolute_time])
-if test "x${je_cv_mach_absolute_time}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_MACH_ABSOLUTE_TIME])
-fi
-
-dnl Check if syscall(2) is usable. Treat warnings as errors, so that e.g. OS X
-dnl 10.12's deprecation warning prevents use.
-SAVED_CFLAGS="${CFLAGS}"
-JE_CFLAGS_APPEND([-Werror])
-JE_COMPILABLE([syscall(2)], [
-#include <sys/syscall.h>
-#include <unistd.h>
-], [
- syscall(SYS_write, 2, "hello", 5);
-],
- [je_cv_syscall])
-CFLAGS="${SAVED_CFLAGS}"
-if test "x$je_cv_syscall" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_SYSCALL], [ ])
-fi
-
-dnl Check if the GNU-specific secure_getenv function exists.
-AC_CHECK_FUNC([secure_getenv],
- [have_secure_getenv="1"],
- [have_secure_getenv="0"]
- )
-if test "x$have_secure_getenv" = "x1" ; then
- AC_DEFINE([JEMALLOC_HAVE_SECURE_GETENV], [ ])
-fi
-
-dnl Check if the Solaris/BSD issetugid function exists.
-AC_CHECK_FUNC([issetugid],
- [have_issetugid="1"],
- [have_issetugid="0"]
- )
-if test "x$have_issetugid" = "x1" ; then
- AC_DEFINE([JEMALLOC_HAVE_ISSETUGID], [ ])
-fi
-
-dnl Check whether the BSD-specific _malloc_thread_cleanup() exists. If so, use
-dnl it rather than pthreads TSD cleanup functions to support cleanup during
-dnl thread exit, in order to avoid pthreads library recursion during
-dnl bootstrapping.
-AC_CHECK_FUNC([_malloc_thread_cleanup],
- [have__malloc_thread_cleanup="1"],
- [have__malloc_thread_cleanup="0"]
- )
-if test "x$have__malloc_thread_cleanup" = "x1" ; then
- AC_DEFINE([JEMALLOC_MALLOC_THREAD_CLEANUP], [ ])
- force_tls="1"
-fi
-
-dnl Check whether the BSD-specific _pthread_mutex_init_calloc_cb() exists. If
-dnl so, mutex initialization causes allocation, and we need to implement this
-dnl callback function in order to prevent recursive allocation.
-AC_CHECK_FUNC([_pthread_mutex_init_calloc_cb],
- [have__pthread_mutex_init_calloc_cb="1"],
- [have__pthread_mutex_init_calloc_cb="0"]
- )
-if test "x$have__pthread_mutex_init_calloc_cb" = "x1" ; then
- AC_DEFINE([JEMALLOC_MUTEX_INIT_CB])
-fi
-
-dnl Disable lazy locking by default.
-AC_ARG_ENABLE([lazy_lock],
- [AS_HELP_STRING([--enable-lazy-lock],
- [Enable lazy locking (only lock when multi-threaded)])],
-[if test "x$enable_lazy_lock" = "xno" ; then
- enable_lazy_lock="0"
-else
- enable_lazy_lock="1"
-fi
-],
-[enable_lazy_lock=""]
-)
-if test "x${enable_lazy_lock}" = "x" ; then
- if test "x${force_lazy_lock}" = "x1" ; then
- AC_MSG_RESULT([Forcing lazy-lock to avoid allocator/threading bootstrap issues])
- enable_lazy_lock="1"
- else
- enable_lazy_lock="0"
- fi
-fi
-if test "x${enable_lazy_lock}" = "x1" -a "x${abi}" = "xpecoff" ; then
- AC_MSG_RESULT([Forcing no lazy-lock because thread creation monitoring is unimplemented])
- enable_lazy_lock="0"
-fi
-if test "x$enable_lazy_lock" = "x1" ; then
- if test "x$abi" != "xpecoff" ; then
- AC_CHECK_HEADERS([dlfcn.h], , [AC_MSG_ERROR([dlfcn.h is missing])])
- AC_CHECK_FUNC([dlsym], [],
- [AC_CHECK_LIB([dl], [dlsym], [LIBS="$LIBS -ldl"],
- [AC_MSG_ERROR([libdl is missing])])
- ])
- fi
- AC_DEFINE([JEMALLOC_LAZY_LOCK], [ ])
-fi
-AC_SUBST([enable_lazy_lock])
-
-AC_ARG_ENABLE([tls],
- [AS_HELP_STRING([--disable-tls], [Disable thread-local storage (__thread keyword)])],
-if test "x$enable_tls" = "xno" ; then
- enable_tls="0"
-else
- enable_tls="1"
-fi
-,
-enable_tls=""
-)
-if test "x${enable_tls}" = "x" ; then
- if test "x${force_tls}" = "x1" ; then
- AC_MSG_RESULT([Forcing TLS to avoid allocator/threading bootstrap issues])
- enable_tls="1"
- elif test "x${force_tls}" = "x0" ; then
- AC_MSG_RESULT([Forcing no TLS to avoid allocator/threading bootstrap issues])
- enable_tls="0"
- else
- enable_tls="1"
- fi
-fi
-if test "x${enable_tls}" = "x1" ; then
-AC_MSG_CHECKING([for TLS])
-AC_COMPILE_IFELSE([AC_LANG_PROGRAM(
-[[
- __thread int x;
-]], [[
- x = 42;
-
- return 0;
-]])],
- AC_MSG_RESULT([yes]),
- AC_MSG_RESULT([no])
- enable_tls="0")
-else
- enable_tls="0"
-fi
-AC_SUBST([enable_tls])
-if test "x${enable_tls}" = "x1" ; then
- if test "x${force_tls}" = "x0" ; then
- AC_MSG_WARN([TLS enabled despite being marked unusable on this platform])
- fi
- AC_DEFINE_UNQUOTED([JEMALLOC_TLS], [ ])
-elif test "x${force_tls}" = "x1" ; then
- AC_MSG_WARN([TLS disabled despite being marked critical on this platform])
-fi
-
-dnl ============================================================================
-dnl Check for C11 atomics.
-
-JE_COMPILABLE([C11 atomics], [
-#include <stdint.h>
-#if (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__)
-#include <stdatomic.h>
-#else
-#error Atomics not available
-#endif
-], [
- uint64_t *p = (uint64_t *)0;
- uint64_t x = 1;
- volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
- uint64_t r = atomic_fetch_add(a, x) + x;
- return (r == 0);
-], [je_cv_c11atomics])
-if test "x${je_cv_c11atomics}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_C11ATOMICS])
-fi
-
-dnl ============================================================================
-dnl Check for atomic(9) operations as provided on FreeBSD.
-
-JE_COMPILABLE([atomic(9)], [
-#include <sys/types.h>
-#include <machine/atomic.h>
-#include <inttypes.h>
-], [
- {
- uint32_t x32 = 0;
- volatile uint32_t *x32p = &x32;
- atomic_fetchadd_32(x32p, 1);
- }
- {
- unsigned long xlong = 0;
- volatile unsigned long *xlongp = &xlong;
- atomic_fetchadd_long(xlongp, 1);
- }
-], [je_cv_atomic9])
-if test "x${je_cv_atomic9}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_ATOMIC9])
-fi
-
-dnl ============================================================================
-dnl Check for atomic(3) operations as provided on Darwin.
-
-JE_COMPILABLE([Darwin OSAtomic*()], [
-#include <libkern/OSAtomic.h>
-#include <inttypes.h>
-], [
- {
- int32_t x32 = 0;
- volatile int32_t *x32p = &x32;
- OSAtomicAdd32(1, x32p);
- }
- {
- int64_t x64 = 0;
- volatile int64_t *x64p = &x64;
- OSAtomicAdd64(1, x64p);
- }
-], [je_cv_osatomic])
-if test "x${je_cv_osatomic}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_OSATOMIC], [ ])
-fi
-
-dnl ============================================================================
-dnl Check for madvise(2).
-
-JE_COMPILABLE([madvise(2)], [
-#include <sys/mman.h>
-], [
- {
- madvise((void *)0, 0, 0);
- }
-], [je_cv_madvise])
-if test "x${je_cv_madvise}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_MADVISE], [ ])
-fi
-
-dnl ============================================================================
-dnl Check whether __sync_{add,sub}_and_fetch() are available despite
-dnl __GCC_HAVE_SYNC_COMPARE_AND_SWAP_n macros being undefined.
-
-AC_DEFUN([JE_SYNC_COMPARE_AND_SWAP_CHECK],[
- AC_CACHE_CHECK([whether to force $1-bit __sync_{add,sub}_and_fetch()],
- [je_cv_sync_compare_and_swap_$2],
- [AC_LINK_IFELSE([AC_LANG_PROGRAM([
- #include <stdint.h>
- ],
- [
- #ifndef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_$2
- {
- uint$1_t x$1 = 0;
- __sync_add_and_fetch(&x$1, 42);
- __sync_sub_and_fetch(&x$1, 1);
- }
- #else
- #error __GCC_HAVE_SYNC_COMPARE_AND_SWAP_$2 is defined, no need to force
- #endif
- ])],
- [je_cv_sync_compare_and_swap_$2=yes],
- [je_cv_sync_compare_and_swap_$2=no])])
-
- if test "x${je_cv_sync_compare_and_swap_$2}" = "xyes" ; then
- AC_DEFINE([JE_FORCE_SYNC_COMPARE_AND_SWAP_$2], [ ])
- fi
-])
-
-if test "x${je_cv_atomic9}" != "xyes" -a "x${je_cv_osatomic}" != "xyes" ; then
- JE_SYNC_COMPARE_AND_SWAP_CHECK(32, 4)
- JE_SYNC_COMPARE_AND_SWAP_CHECK(64, 8)
-fi
-
-dnl ============================================================================
-dnl Check for __builtin_clz() and __builtin_clzl().
-
-AC_CACHE_CHECK([for __builtin_clz],
- [je_cv_builtin_clz],
- [AC_LINK_IFELSE([AC_LANG_PROGRAM([],
- [
- {
- unsigned x = 0;
- int y = __builtin_clz(x);
- }
- {
- unsigned long x = 0;
- int y = __builtin_clzl(x);
- }
- ])],
- [je_cv_builtin_clz=yes],
- [je_cv_builtin_clz=no])])
-
-if test "x${je_cv_builtin_clz}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_BUILTIN_CLZ], [ ])
-fi
-
-dnl ============================================================================
-dnl Check for os_unfair_lock operations as provided on Darwin.
-
-JE_COMPILABLE([Darwin os_unfair_lock_*()], [
-#include <os/lock.h>
-], [
- os_unfair_lock lock = OS_UNFAIR_LOCK_INIT;
- os_unfair_lock_lock(&lock);
- os_unfair_lock_unlock(&lock);
-], [je_cv_os_unfair_lock])
-if test "x${je_cv_os_unfair_lock}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_OS_UNFAIR_LOCK], [ ])
-fi
-
-dnl ============================================================================
-dnl Check for spinlock(3) operations as provided on Darwin.
-
-JE_COMPILABLE([Darwin OSSpin*()], [
-#include <libkern/OSAtomic.h>
-#include <inttypes.h>
-], [
- OSSpinLock lock = 0;
- OSSpinLockLock(&lock);
- OSSpinLockUnlock(&lock);
-], [je_cv_osspin])
-if test "x${je_cv_osspin}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_OSSPIN], [ ])
-fi
-
-dnl ============================================================================
-dnl Darwin-related configuration.
-
-AC_ARG_ENABLE([zone-allocator],
- [AS_HELP_STRING([--disable-zone-allocator],
- [Disable zone allocator for Darwin])],
-[if test "x$enable_zone_allocator" = "xno" ; then
- enable_zone_allocator="0"
-else
- enable_zone_allocator="1"
-fi
-],
-[if test "x${abi}" = "xmacho"; then
- enable_zone_allocator="1"
-fi
-]
-)
-AC_SUBST([enable_zone_allocator])
-
-if test "x${enable_zone_allocator}" = "x1" ; then
- if test "x${abi}" != "xmacho"; then
- AC_MSG_ERROR([--enable-zone-allocator is only supported on Darwin])
- fi
- AC_DEFINE([JEMALLOC_ZONE], [ ])
-
- dnl The szone version jumped from 3 to 6 between the OS X 10.5.x and 10.6
- dnl releases. malloc_zone_t and malloc_introspection_t have new fields in
- dnl 10.6, which is the only source-level indication of the change.
- AC_MSG_CHECKING([malloc zone version])
- AC_DEFUN([JE_ZONE_PROGRAM],
- [AC_LANG_PROGRAM(
- [#include <malloc/malloc.h>],
- [static int foo[[sizeof($1) $2 sizeof(void *) * $3 ? 1 : -1]]]
- )])
-
- AC_COMPILE_IFELSE([JE_ZONE_PROGRAM(malloc_zone_t,==,14)],[JEMALLOC_ZONE_VERSION=3],[
- AC_COMPILE_IFELSE([JE_ZONE_PROGRAM(malloc_zone_t,==,15)],[JEMALLOC_ZONE_VERSION=5],[
- AC_COMPILE_IFELSE([JE_ZONE_PROGRAM(malloc_zone_t,==,16)],[
- AC_COMPILE_IFELSE([JE_ZONE_PROGRAM(malloc_introspection_t,==,9)],[JEMALLOC_ZONE_VERSION=6],[
- AC_COMPILE_IFELSE([JE_ZONE_PROGRAM(malloc_introspection_t,==,13)],[JEMALLOC_ZONE_VERSION=7],[JEMALLOC_ZONE_VERSION=]
- )])],[
- AC_COMPILE_IFELSE([JE_ZONE_PROGRAM(malloc_zone_t,==,17)],[JEMALLOC_ZONE_VERSION=8],[
- AC_COMPILE_IFELSE([JE_ZONE_PROGRAM(malloc_zone_t,>,17)],[JEMALLOC_ZONE_VERSION=9],[JEMALLOC_ZONE_VERSION=]
- )])])])])
- if test "x${JEMALLOC_ZONE_VERSION}" = "x"; then
- AC_MSG_RESULT([unsupported])
- AC_MSG_ERROR([Unsupported malloc zone version])
- fi
- if test "${JEMALLOC_ZONE_VERSION}" = 9; then
- JEMALLOC_ZONE_VERSION=8
- AC_MSG_RESULT([> 8])
- else
- AC_MSG_RESULT([$JEMALLOC_ZONE_VERSION])
- fi
- AC_DEFINE_UNQUOTED(JEMALLOC_ZONE_VERSION, [$JEMALLOC_ZONE_VERSION])
-fi
-
-dnl ============================================================================
-dnl Check for glibc malloc hooks
-
-JE_COMPILABLE([glibc malloc hook], [
-#include <stddef.h>
-
-extern void (* __free_hook)(void *ptr);
-extern void *(* __malloc_hook)(size_t size);
-extern void *(* __realloc_hook)(void *ptr, size_t size);
-], [
- void *ptr = 0L;
- if (__malloc_hook) ptr = __malloc_hook(1);
- if (__realloc_hook) ptr = __realloc_hook(ptr, 2);
- if (__free_hook && ptr) __free_hook(ptr);
-], [je_cv_glibc_malloc_hook])
-if test "x${je_cv_glibc_malloc_hook}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_GLIBC_MALLOC_HOOK], [ ])
-fi
-
-JE_COMPILABLE([glibc memalign hook], [
-#include <stddef.h>
-
-extern void *(* __memalign_hook)(size_t alignment, size_t size);
-], [
- void *ptr = 0L;
- if (__memalign_hook) ptr = __memalign_hook(16, 7);
-], [je_cv_glibc_memalign_hook])
-if test "x${je_cv_glibc_memalign_hook}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_GLIBC_MEMALIGN_HOOK], [ ])
-fi
-
-JE_COMPILABLE([pthreads adaptive mutexes], [
-#include <pthread.h>
-], [
- pthread_mutexattr_t attr;
- pthread_mutexattr_init(&attr);
- pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
- pthread_mutexattr_destroy(&attr);
-], [je_cv_pthread_mutex_adaptive_np])
-if test "x${je_cv_pthread_mutex_adaptive_np}" = "xyes" ; then
- AC_DEFINE([JEMALLOC_HAVE_PTHREAD_MUTEX_ADAPTIVE_NP], [ ])
-fi
-
-dnl ============================================================================
-dnl Check for typedefs, structures, and compiler characteristics.
-AC_HEADER_STDBOOL
-
-dnl ============================================================================
-dnl Define commands that generate output files.
-
-AC_CONFIG_COMMANDS([include/jemalloc/internal/private_namespace.h], [
- mkdir -p "${objroot}include/jemalloc/internal"
- "${srcdir}/include/jemalloc/internal/private_namespace.sh" "${srcdir}/include/jemalloc/internal/private_symbols.txt" > "${objroot}include/jemalloc/internal/private_namespace.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/internal/private_unnamespace.h], [
- mkdir -p "${objroot}include/jemalloc/internal"
- "${srcdir}/include/jemalloc/internal/private_unnamespace.sh" "${srcdir}/include/jemalloc/internal/private_symbols.txt" > "${objroot}include/jemalloc/internal/private_unnamespace.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/internal/public_symbols.txt], [
- f="${objroot}include/jemalloc/internal/public_symbols.txt"
- mkdir -p "${objroot}include/jemalloc/internal"
- cp /dev/null "${f}"
- for nm in `echo ${mangling_map} |tr ',' ' '` ; do
- n=`echo ${nm} |tr ':' ' ' |awk '{print $[]1}'`
- m=`echo ${nm} |tr ':' ' ' |awk '{print $[]2}'`
- echo "${n}:${m}" >> "${f}"
- dnl Remove name from public_syms so that it isn't redefined later.
- public_syms=`for sym in ${public_syms}; do echo "${sym}"; done |grep -v "^${n}\$" |tr '\n' ' '`
- done
- for sym in ${public_syms} ; do
- n="${sym}"
- m="${JEMALLOC_PREFIX}${sym}"
- echo "${n}:${m}" >> "${f}"
- done
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
- mangling_map="${mangling_map}"
- public_syms="${public_syms}"
- JEMALLOC_PREFIX="${JEMALLOC_PREFIX}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/internal/public_namespace.h], [
- mkdir -p "${objroot}include/jemalloc/internal"
- "${srcdir}/include/jemalloc/internal/public_namespace.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" > "${objroot}include/jemalloc/internal/public_namespace.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/internal/public_unnamespace.h], [
- mkdir -p "${objroot}include/jemalloc/internal"
- "${srcdir}/include/jemalloc/internal/public_unnamespace.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" > "${objroot}include/jemalloc/internal/public_unnamespace.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/internal/size_classes.h], [
- mkdir -p "${objroot}include/jemalloc/internal"
- "${SHELL}" "${srcdir}/include/jemalloc/internal/size_classes.sh" "${LG_QUANTA}" ${LG_TINY_MIN} "${LG_PAGE_SIZES}" ${LG_SIZE_CLASS_GROUP} > "${objroot}include/jemalloc/internal/size_classes.h"
-], [
- SHELL="${SHELL}"
- srcdir="${srcdir}"
- objroot="${objroot}"
- LG_QUANTA="${LG_QUANTA}"
- LG_TINY_MIN=${LG_TINY_MIN}
- LG_PAGE_SIZES="${LG_PAGE_SIZES}"
- LG_SIZE_CLASS_GROUP=${LG_SIZE_CLASS_GROUP}
-])
-AC_CONFIG_COMMANDS([include/jemalloc/jemalloc_protos_jet.h], [
- mkdir -p "${objroot}include/jemalloc"
- cat "${srcdir}/include/jemalloc/jemalloc_protos.h.in" | sed -e 's/@je_@/jet_/g' > "${objroot}include/jemalloc/jemalloc_protos_jet.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/jemalloc_rename.h], [
- mkdir -p "${objroot}include/jemalloc"
- "${srcdir}/include/jemalloc/jemalloc_rename.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" > "${objroot}include/jemalloc/jemalloc_rename.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/jemalloc_mangle.h], [
- mkdir -p "${objroot}include/jemalloc"
- "${srcdir}/include/jemalloc/jemalloc_mangle.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" je_ > "${objroot}include/jemalloc/jemalloc_mangle.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/jemalloc_mangle_jet.h], [
- mkdir -p "${objroot}include/jemalloc"
- "${srcdir}/include/jemalloc/jemalloc_mangle.sh" "${objroot}include/jemalloc/internal/public_symbols.txt" jet_ > "${objroot}include/jemalloc/jemalloc_mangle_jet.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
-])
-AC_CONFIG_COMMANDS([include/jemalloc/jemalloc.h], [
- mkdir -p "${objroot}include/jemalloc"
- "${srcdir}/include/jemalloc/jemalloc.sh" "${objroot}" > "${objroot}include/jemalloc/jemalloc${install_suffix}.h"
-], [
- srcdir="${srcdir}"
- objroot="${objroot}"
- install_suffix="${install_suffix}"
-])
-
-dnl Process .in files.
-AC_SUBST([cfghdrs_in])
-AC_SUBST([cfghdrs_out])
-AC_CONFIG_HEADERS([$cfghdrs_tup])
-
-dnl ============================================================================
-dnl Generate outputs.
-
-AC_CONFIG_FILES([$cfgoutputs_tup config.stamp bin/jemalloc-config bin/jemalloc.sh bin/jeprof])
-AC_SUBST([cfgoutputs_in])
-AC_SUBST([cfgoutputs_out])
-AC_OUTPUT
-
-dnl ============================================================================
-dnl Print out the results of configuration.
-AC_MSG_RESULT([===============================================================================])
-AC_MSG_RESULT([jemalloc version : ${jemalloc_version}])
-AC_MSG_RESULT([library revision : ${rev}])
-AC_MSG_RESULT([])
-AC_MSG_RESULT([CONFIG : ${CONFIG}])
-AC_MSG_RESULT([CC : ${CC}])
-AC_MSG_RESULT([CFLAGS : ${CFLAGS}])
-AC_MSG_RESULT([EXTRA_CFLAGS : ${EXTRA_CFLAGS}])
-AC_MSG_RESULT([CPPFLAGS : ${CPPFLAGS}])
-AC_MSG_RESULT([LDFLAGS : ${LDFLAGS}])
-AC_MSG_RESULT([EXTRA_LDFLAGS : ${EXTRA_LDFLAGS}])
-AC_MSG_RESULT([LIBS : ${LIBS}])
-AC_MSG_RESULT([RPATH_EXTRA : ${RPATH_EXTRA}])
-AC_MSG_RESULT([])
-AC_MSG_RESULT([XSLTPROC : ${XSLTPROC}])
-AC_MSG_RESULT([XSLROOT : ${XSLROOT}])
-AC_MSG_RESULT([])
-AC_MSG_RESULT([PREFIX : ${PREFIX}])
-AC_MSG_RESULT([BINDIR : ${BINDIR}])
-AC_MSG_RESULT([DATADIR : ${DATADIR}])
-AC_MSG_RESULT([INCLUDEDIR : ${INCLUDEDIR}])
-AC_MSG_RESULT([LIBDIR : ${LIBDIR}])
-AC_MSG_RESULT([MANDIR : ${MANDIR}])
-AC_MSG_RESULT([])
-AC_MSG_RESULT([srcroot : ${srcroot}])
-AC_MSG_RESULT([abs_srcroot : ${abs_srcroot}])
-AC_MSG_RESULT([objroot : ${objroot}])
-AC_MSG_RESULT([abs_objroot : ${abs_objroot}])
-AC_MSG_RESULT([])
-AC_MSG_RESULT([JEMALLOC_PREFIX : ${JEMALLOC_PREFIX}])
-AC_MSG_RESULT([JEMALLOC_PRIVATE_NAMESPACE])
-AC_MSG_RESULT([ : ${JEMALLOC_PRIVATE_NAMESPACE}])
-AC_MSG_RESULT([install_suffix : ${install_suffix}])
-AC_MSG_RESULT([malloc_conf : ${config_malloc_conf}])
-AC_MSG_RESULT([autogen : ${enable_autogen}])
-AC_MSG_RESULT([cc-silence : ${enable_cc_silence}])
-AC_MSG_RESULT([debug : ${enable_debug}])
-AC_MSG_RESULT([code-coverage : ${enable_code_coverage}])
-AC_MSG_RESULT([stats : ${enable_stats}])
-AC_MSG_RESULT([prof : ${enable_prof}])
-AC_MSG_RESULT([prof-libunwind : ${enable_prof_libunwind}])
-AC_MSG_RESULT([prof-libgcc : ${enable_prof_libgcc}])
-AC_MSG_RESULT([prof-gcc : ${enable_prof_gcc}])
-AC_MSG_RESULT([tcache : ${enable_tcache}])
-AC_MSG_RESULT([fill : ${enable_fill}])
-AC_MSG_RESULT([utrace : ${enable_utrace}])
-AC_MSG_RESULT([valgrind : ${enable_valgrind}])
-AC_MSG_RESULT([xmalloc : ${enable_xmalloc}])
-AC_MSG_RESULT([munmap : ${enable_munmap}])
-AC_MSG_RESULT([lazy_lock : ${enable_lazy_lock}])
-AC_MSG_RESULT([tls : ${enable_tls}])
-AC_MSG_RESULT([cache-oblivious : ${enable_cache_oblivious}])
-AC_MSG_RESULT([===============================================================================])
diff --git a/memory/jemalloc/src/coverage.sh b/memory/jemalloc/src/coverage.sh
deleted file mode 100755
index 6d1362a8c..000000000
--- a/memory/jemalloc/src/coverage.sh
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/bin/sh
-
-set -e
-
-objdir=$1
-suffix=$2
-shift 2
-objs=$@
-
-gcov -b -p -f -o "${objdir}" ${objs}
-
-# Move gcov outputs so that subsequent gcov invocations won't clobber results
-# for the same sources with different compilation flags.
-for f in `find . -maxdepth 1 -type f -name '*.gcov'` ; do
- mv "${f}" "${f}.${suffix}"
-done
diff --git a/memory/jemalloc/src/doc/html.xsl.in b/memory/jemalloc/src/doc/html.xsl.in
deleted file mode 100644
index ec4fa6552..000000000
--- a/memory/jemalloc/src/doc/html.xsl.in
+++ /dev/null
@@ -1,5 +0,0 @@
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
- <xsl:import href="@XSLROOT@/html/docbook.xsl"/>
- <xsl:import href="@abs_srcroot@doc/stylesheet.xsl"/>
- <xsl:output method="xml" encoding="utf-8"/>
-</xsl:stylesheet>
diff --git a/memory/jemalloc/src/doc/jemalloc.xml.in b/memory/jemalloc/src/doc/jemalloc.xml.in
deleted file mode 100644
index 3d2e721d3..000000000
--- a/memory/jemalloc/src/doc/jemalloc.xml.in
+++ /dev/null
@@ -1,2966 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<?xml-stylesheet type="text/xsl"
- href="http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl"?>
-<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
- "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd" [
-]>
-
-<refentry>
- <refentryinfo>
- <title>User Manual</title>
- <productname>jemalloc</productname>
- <releaseinfo role="version">@jemalloc_version@</releaseinfo>
- <authorgroup>
- <author>
- <firstname>Jason</firstname>
- <surname>Evans</surname>
- <personblurb>Author</personblurb>
- </author>
- </authorgroup>
- </refentryinfo>
- <refmeta>
- <refentrytitle>JEMALLOC</refentrytitle>
- <manvolnum>3</manvolnum>
- </refmeta>
- <refnamediv>
- <refdescriptor>jemalloc</refdescriptor>
- <refname>jemalloc</refname>
- <!-- Each refname causes a man page file to be created. Only if this were
- the system malloc(3) implementation would these files be appropriate.
- <refname>malloc</refname>
- <refname>calloc</refname>
- <refname>posix_memalign</refname>
- <refname>aligned_alloc</refname>
- <refname>realloc</refname>
- <refname>free</refname>
- <refname>mallocx</refname>
- <refname>rallocx</refname>
- <refname>xallocx</refname>
- <refname>sallocx</refname>
- <refname>dallocx</refname>
- <refname>sdallocx</refname>
- <refname>nallocx</refname>
- <refname>mallctl</refname>
- <refname>mallctlnametomib</refname>
- <refname>mallctlbymib</refname>
- <refname>malloc_stats_print</refname>
- <refname>malloc_usable_size</refname>
- -->
- <refpurpose>general purpose memory allocation functions</refpurpose>
- </refnamediv>
- <refsect1 id="library">
- <title>LIBRARY</title>
- <para>This manual describes jemalloc @jemalloc_version@. More information
- can be found at the <ulink
- url="http://jemalloc.net/">jemalloc website</ulink>.</para>
- </refsect1>
- <refsynopsisdiv>
- <title>SYNOPSIS</title>
- <funcsynopsis>
- <funcsynopsisinfo>#include &lt;<filename class="headerfile">jemalloc/jemalloc.h</filename>&gt;</funcsynopsisinfo>
- <refsect2>
- <title>Standard API</title>
- <funcprototype>
- <funcdef>void *<function>malloc</function></funcdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void *<function>calloc</function></funcdef>
- <paramdef>size_t <parameter>number</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>int <function>posix_memalign</function></funcdef>
- <paramdef>void **<parameter>ptr</parameter></paramdef>
- <paramdef>size_t <parameter>alignment</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void *<function>aligned_alloc</function></funcdef>
- <paramdef>size_t <parameter>alignment</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void *<function>realloc</function></funcdef>
- <paramdef>void *<parameter>ptr</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void <function>free</function></funcdef>
- <paramdef>void *<parameter>ptr</parameter></paramdef>
- </funcprototype>
- </refsect2>
- <refsect2>
- <title>Non-standard API</title>
- <funcprototype>
- <funcdef>void *<function>mallocx</function></funcdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>int <parameter>flags</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void *<function>rallocx</function></funcdef>
- <paramdef>void *<parameter>ptr</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>int <parameter>flags</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>size_t <function>xallocx</function></funcdef>
- <paramdef>void *<parameter>ptr</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>size_t <parameter>extra</parameter></paramdef>
- <paramdef>int <parameter>flags</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>size_t <function>sallocx</function></funcdef>
- <paramdef>void *<parameter>ptr</parameter></paramdef>
- <paramdef>int <parameter>flags</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void <function>dallocx</function></funcdef>
- <paramdef>void *<parameter>ptr</parameter></paramdef>
- <paramdef>int <parameter>flags</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void <function>sdallocx</function></funcdef>
- <paramdef>void *<parameter>ptr</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>int <parameter>flags</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>size_t <function>nallocx</function></funcdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>int <parameter>flags</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>int <function>mallctl</function></funcdef>
- <paramdef>const char *<parameter>name</parameter></paramdef>
- <paramdef>void *<parameter>oldp</parameter></paramdef>
- <paramdef>size_t *<parameter>oldlenp</parameter></paramdef>
- <paramdef>void *<parameter>newp</parameter></paramdef>
- <paramdef>size_t <parameter>newlen</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>int <function>mallctlnametomib</function></funcdef>
- <paramdef>const char *<parameter>name</parameter></paramdef>
- <paramdef>size_t *<parameter>mibp</parameter></paramdef>
- <paramdef>size_t *<parameter>miblenp</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>int <function>mallctlbymib</function></funcdef>
- <paramdef>const size_t *<parameter>mib</parameter></paramdef>
- <paramdef>size_t <parameter>miblen</parameter></paramdef>
- <paramdef>void *<parameter>oldp</parameter></paramdef>
- <paramdef>size_t *<parameter>oldlenp</parameter></paramdef>
- <paramdef>void *<parameter>newp</parameter></paramdef>
- <paramdef>size_t <parameter>newlen</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void <function>malloc_stats_print</function></funcdef>
- <paramdef>void <parameter>(*write_cb)</parameter>
- <funcparams>void *, const char *</funcparams>
- </paramdef>
- <paramdef>void *<parameter>cbopaque</parameter></paramdef>
- <paramdef>const char *<parameter>opts</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>size_t <function>malloc_usable_size</function></funcdef>
- <paramdef>const void *<parameter>ptr</parameter></paramdef>
- </funcprototype>
- <funcprototype>
- <funcdef>void <function>(*malloc_message)</function></funcdef>
- <paramdef>void *<parameter>cbopaque</parameter></paramdef>
- <paramdef>const char *<parameter>s</parameter></paramdef>
- </funcprototype>
- <para><type>const char *</type><varname>malloc_conf</varname>;</para>
- </refsect2>
- </funcsynopsis>
- </refsynopsisdiv>
- <refsect1 id="description">
- <title>DESCRIPTION</title>
- <refsect2>
- <title>Standard API</title>
-
- <para>The <function>malloc()</function> function allocates
- <parameter>size</parameter> bytes of uninitialized memory. The allocated
- space is suitably aligned (after possible pointer coercion) for storage
- of any type of object.</para>
-
- <para>The <function>calloc()</function> function allocates
- space for <parameter>number</parameter> objects, each
- <parameter>size</parameter> bytes in length. The result is identical to
- calling <function>malloc()</function> with an argument of
- <parameter>number</parameter> * <parameter>size</parameter>, with the
- exception that the allocated memory is explicitly initialized to zero
- bytes.</para>
-
- <para>The <function>posix_memalign()</function> function
- allocates <parameter>size</parameter> bytes of memory such that the
- allocation's base address is a multiple of
- <parameter>alignment</parameter>, and returns the allocation in the value
- pointed to by <parameter>ptr</parameter>. The requested
- <parameter>alignment</parameter> must be a power of 2 at least as large as
- <code language="C">sizeof(<type>void *</type>)</code>.</para>
-
- <para>The <function>aligned_alloc()</function> function
- allocates <parameter>size</parameter> bytes of memory such that the
- allocation's base address is a multiple of
- <parameter>alignment</parameter>. The requested
- <parameter>alignment</parameter> must be a power of 2. Behavior is
- undefined if <parameter>size</parameter> is not an integral multiple of
- <parameter>alignment</parameter>.</para>
-
- <para>The <function>realloc()</function> function changes the
- size of the previously allocated memory referenced by
- <parameter>ptr</parameter> to <parameter>size</parameter> bytes. The
- contents of the memory are unchanged up to the lesser of the new and old
- sizes. If the new size is larger, the contents of the newly allocated
- portion of the memory are undefined. Upon success, the memory referenced
- by <parameter>ptr</parameter> is freed and a pointer to the newly
- allocated memory is returned. Note that
- <function>realloc()</function> may move the memory allocation,
- resulting in a different return value than <parameter>ptr</parameter>.
- If <parameter>ptr</parameter> is <constant>NULL</constant>, the
- <function>realloc()</function> function behaves identically to
- <function>malloc()</function> for the specified size.</para>
-
- <para>The <function>free()</function> function causes the
- allocated memory referenced by <parameter>ptr</parameter> to be made
- available for future allocations. If <parameter>ptr</parameter> is
- <constant>NULL</constant>, no action occurs.</para>
- </refsect2>
- <refsect2>
- <title>Non-standard API</title>
- <para>The <function>mallocx()</function>,
- <function>rallocx()</function>,
- <function>xallocx()</function>,
- <function>sallocx()</function>,
- <function>dallocx()</function>,
- <function>sdallocx()</function>, and
- <function>nallocx()</function> functions all have a
- <parameter>flags</parameter> argument that can be used to specify
- options. The functions only check the options that are contextually
- relevant. Use bitwise or (<code language="C">|</code>) operations to
- specify one or more of the following:
- <variablelist>
- <varlistentry id="MALLOCX_LG_ALIGN">
- <term><constant>MALLOCX_LG_ALIGN(<parameter>la</parameter>)
- </constant></term>
-
- <listitem><para>Align the memory allocation to start at an address
- that is a multiple of <code language="C">(1 &lt;&lt;
- <parameter>la</parameter>)</code>. This macro does not validate
- that <parameter>la</parameter> is within the valid
- range.</para></listitem>
- </varlistentry>
- <varlistentry id="MALLOCX_ALIGN">
- <term><constant>MALLOCX_ALIGN(<parameter>a</parameter>)
- </constant></term>
-
- <listitem><para>Align the memory allocation to start at an address
- that is a multiple of <parameter>a</parameter>, where
- <parameter>a</parameter> is a power of two. This macro does not
- validate that <parameter>a</parameter> is a power of 2.
- </para></listitem>
- </varlistentry>
- <varlistentry id="MALLOCX_ZERO">
- <term><constant>MALLOCX_ZERO</constant></term>
-
- <listitem><para>Initialize newly allocated memory to contain zero
- bytes. In the growing reallocation case, the real size prior to
- reallocation defines the boundary between untouched bytes and those
- that are initialized to contain zero bytes. If this macro is
- absent, newly allocated memory is uninitialized.</para></listitem>
- </varlistentry>
- <varlistentry id="MALLOCX_TCACHE">
- <term><constant>MALLOCX_TCACHE(<parameter>tc</parameter>)
- </constant></term>
-
- <listitem><para>Use the thread-specific cache (tcache) specified by
- the identifier <parameter>tc</parameter>, which must have been
- acquired via the <link
- linkend="tcache.create"><mallctl>tcache.create</mallctl></link>
- mallctl. This macro does not validate that
- <parameter>tc</parameter> specifies a valid
- identifier.</para></listitem>
- </varlistentry>
- <varlistentry id="MALLOC_TCACHE_NONE">
- <term><constant>MALLOCX_TCACHE_NONE</constant></term>
-
- <listitem><para>Do not use a thread-specific cache (tcache). Unless
- <constant>MALLOCX_TCACHE(<parameter>tc</parameter>)</constant> or
- <constant>MALLOCX_TCACHE_NONE</constant> is specified, an
- automatically managed tcache will be used under many circumstances.
- This macro cannot be used in the same <parameter>flags</parameter>
- argument as
- <constant>MALLOCX_TCACHE(<parameter>tc</parameter>)</constant>.</para></listitem>
- </varlistentry>
- <varlistentry id="MALLOCX_ARENA">
- <term><constant>MALLOCX_ARENA(<parameter>a</parameter>)
- </constant></term>
-
- <listitem><para>Use the arena specified by the index
- <parameter>a</parameter>. This macro has no effect for regions that
- were allocated via an arena other than the one specified. This
- macro does not validate that <parameter>a</parameter> specifies an
- arena index in the valid range.</para></listitem>
- </varlistentry>
- </variablelist>
- </para>
-
- <para>The <function>mallocx()</function> function allocates at
- least <parameter>size</parameter> bytes of memory, and returns a pointer
- to the base address of the allocation. Behavior is undefined if
- <parameter>size</parameter> is <constant>0</constant>.</para>
-
- <para>The <function>rallocx()</function> function resizes the
- allocation at <parameter>ptr</parameter> to be at least
- <parameter>size</parameter> bytes, and returns a pointer to the base
- address of the resulting allocation, which may or may not have moved from
- its original location. Behavior is undefined if
- <parameter>size</parameter> is <constant>0</constant>.</para>
-
- <para>The <function>xallocx()</function> function resizes the
- allocation at <parameter>ptr</parameter> in place to be at least
- <parameter>size</parameter> bytes, and returns the real size of the
- allocation. If <parameter>extra</parameter> is non-zero, an attempt is
- made to resize the allocation to be at least <code
- language="C">(<parameter>size</parameter> +
- <parameter>extra</parameter>)</code> bytes, though inability to allocate
- the extra byte(s) will not by itself result in failure to resize.
- Behavior is undefined if <parameter>size</parameter> is
- <constant>0</constant>, or if <code
- language="C">(<parameter>size</parameter> + <parameter>extra</parameter>
- &gt; <constant>SIZE_T_MAX</constant>)</code>.</para>
-
- <para>The <function>sallocx()</function> function returns the
- real size of the allocation at <parameter>ptr</parameter>.</para>
-
- <para>The <function>dallocx()</function> function causes the
- memory referenced by <parameter>ptr</parameter> to be made available for
- future allocations.</para>
-
- <para>The <function>sdallocx()</function> function is an
- extension of <function>dallocx()</function> with a
- <parameter>size</parameter> parameter to allow the caller to pass in the
- allocation size as an optimization. The minimum valid input size is the
- original requested size of the allocation, and the maximum valid input
- size is the corresponding value returned by
- <function>nallocx()</function> or
- <function>sallocx()</function>.</para>
-
- <para>The <function>nallocx()</function> function allocates no
- memory, but it performs the same size computation as the
- <function>mallocx()</function> function, and returns the real
- size of the allocation that would result from the equivalent
- <function>mallocx()</function> function call, or
- <constant>0</constant> if the inputs exceed the maximum supported size
- class and/or alignment. Behavior is undefined if
- <parameter>size</parameter> is <constant>0</constant>.</para>
-
- <para>The <function>mallctl()</function> function provides a
- general interface for introspecting the memory allocator, as well as
- setting modifiable parameters and triggering actions. The
- period-separated <parameter>name</parameter> argument specifies a
- location in a tree-structured namespace; see the <xref
- linkend="mallctl_namespace" xrefstyle="template:%t"/> section for
- documentation on the tree contents. To read a value, pass a pointer via
- <parameter>oldp</parameter> to adequate space to contain the value, and a
- pointer to its length via <parameter>oldlenp</parameter>; otherwise pass
- <constant>NULL</constant> and <constant>NULL</constant>. Similarly, to
- write a value, pass a pointer to the value via
- <parameter>newp</parameter>, and its length via
- <parameter>newlen</parameter>; otherwise pass <constant>NULL</constant>
- and <constant>0</constant>.</para>
-
- <para>The <function>mallctlnametomib()</function> function
- provides a way to avoid repeated name lookups for applications that
- repeatedly query the same portion of the namespace, by translating a name
- to a <quote>Management Information Base</quote> (MIB) that can be passed
- repeatedly to <function>mallctlbymib()</function>. Upon
- successful return from <function>mallctlnametomib()</function>,
- <parameter>mibp</parameter> contains an array of
- <parameter>*miblenp</parameter> integers, where
- <parameter>*miblenp</parameter> is the lesser of the number of components
- in <parameter>name</parameter> and the input value of
- <parameter>*miblenp</parameter>. Thus it is possible to pass a
- <parameter>*miblenp</parameter> that is smaller than the number of
- period-separated name components, which results in a partial MIB that can
- be used as the basis for constructing a complete MIB. For name
- components that are integers (e.g. the 2 in
- <link
- linkend="arenas.bin.i.size"><mallctl>arenas.bin.2.size</mallctl></link>),
- the corresponding MIB component will always be that integer. Therefore,
- it is legitimate to construct code like the following: <programlisting
- language="C"><![CDATA[
-unsigned nbins, i;
-size_t mib[4];
-size_t len, miblen;
-
-len = sizeof(nbins);
-mallctl("arenas.nbins", &nbins, &len, NULL, 0);
-
-miblen = 4;
-mallctlnametomib("arenas.bin.0.size", mib, &miblen);
-for (i = 0; i < nbins; i++) {
- size_t bin_size;
-
- mib[2] = i;
- len = sizeof(bin_size);
- mallctlbymib(mib, miblen, &bin_size, &len, NULL, 0);
- /* Do something with bin_size... */
-}]]></programlisting></para>
-
- <para>The <function>malloc_stats_print()</function> function writes
- summary statistics via the <parameter>write_cb</parameter> callback
- function pointer and <parameter>cbopaque</parameter> data passed to
- <parameter>write_cb</parameter>, or <function>malloc_message()</function>
- if <parameter>write_cb</parameter> is <constant>NULL</constant>. The
- statistics are presented in human-readable form unless <quote>J</quote> is
- specified as a character within the <parameter>opts</parameter> string, in
- which case the statistics are presented in <ulink
- url="http://www.json.org/">JSON format</ulink>. This function can be
- called repeatedly. General information that never changes during
- execution can be omitted by specifying <quote>g</quote> as a character
- within the <parameter>opts</parameter> string. Note that
- <function>malloc_message()</function> uses the
- <function>mallctl*()</function> functions internally, so inconsistent
- statistics can be reported if multiple threads use these functions
- simultaneously. If <option>--enable-stats</option> is specified during
- configuration, <quote>m</quote> and <quote>a</quote> can be specified to
- omit merged arena and per arena statistics, respectively;
- <quote>b</quote>, <quote>l</quote>, and <quote>h</quote> can be specified
- to omit per size class statistics for bins, large objects, and huge
- objects, respectively. Unrecognized characters are silently ignored.
- Note that thread caching may prevent some statistics from being completely
- up to date, since extra locking would be required to merge counters that
- track thread cache operations.</para>
-
- <para>The <function>malloc_usable_size()</function> function
- returns the usable size of the allocation pointed to by
- <parameter>ptr</parameter>. The return value may be larger than the size
- that was requested during allocation. The
- <function>malloc_usable_size()</function> function is not a
- mechanism for in-place <function>realloc()</function>; rather
- it is provided solely as a tool for introspection purposes. Any
- discrepancy between the requested allocation size and the size reported
- by <function>malloc_usable_size()</function> should not be
- depended on, since such behavior is entirely implementation-dependent.
- </para>
- </refsect2>
- </refsect1>
- <refsect1 id="tuning">
- <title>TUNING</title>
- <para>Once, when the first call is made to one of the memory allocation
- routines, the allocator initializes its internals based in part on various
- options that can be specified at compile- or run-time.</para>
-
- <para>The string specified via <option>--with-malloc-conf</option>, the
- string pointed to by the global variable <varname>malloc_conf</varname>, the
- <quote>name</quote> of the file referenced by the symbolic link named
- <filename class="symlink">/etc/malloc.conf</filename>, and the value of the
- environment variable <envar>MALLOC_CONF</envar>, will be interpreted, in
- that order, from left to right as options. Note that
- <varname>malloc_conf</varname> may be read before
- <function>main()</function> is entered, so the declaration of
- <varname>malloc_conf</varname> should specify an initializer that contains
- the final value to be read by jemalloc. <option>--with-malloc-conf</option>
- and <varname>malloc_conf</varname> are compile-time mechanisms, whereas
- <filename class="symlink">/etc/malloc.conf</filename> and
- <envar>MALLOC_CONF</envar> can be safely set any time prior to program
- invocation.</para>
-
- <para>An options string is a comma-separated list of option:value pairs.
- There is one key corresponding to each <link
- linkend="opt.abort"><mallctl>opt.*</mallctl></link> mallctl (see the <xref
- linkend="mallctl_namespace" xrefstyle="template:%t"/> section for options
- documentation). For example, <literal>abort:true,narenas:1</literal> sets
- the <link linkend="opt.abort"><mallctl>opt.abort</mallctl></link> and <link
- linkend="opt.narenas"><mallctl>opt.narenas</mallctl></link> options. Some
- options have boolean values (true/false), others have integer values (base
- 8, 10, or 16, depending on prefix), and yet others have raw string
- values.</para>
- </refsect1>
- <refsect1 id="implementation_notes">
- <title>IMPLEMENTATION NOTES</title>
- <para>Traditionally, allocators have used
- <citerefentry><refentrytitle>sbrk</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> to obtain memory, which is
- suboptimal for several reasons, including race conditions, increased
- fragmentation, and artificial limitations on maximum usable memory. If
- <citerefentry><refentrytitle>sbrk</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> is supported by the operating
- system, this allocator uses both
- <citerefentry><refentrytitle>mmap</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> and
- <citerefentry><refentrytitle>sbrk</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry>, in that order of preference;
- otherwise only <citerefentry><refentrytitle>mmap</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> is used.</para>
-
- <para>This allocator uses multiple arenas in order to reduce lock
- contention for threaded programs on multi-processor systems. This works
- well with regard to threading scalability, but incurs some costs. There is
- a small fixed per-arena overhead, and additionally, arenas manage memory
- completely independently of each other, which means a small fixed increase
- in overall memory fragmentation. These overheads are not generally an
- issue, given the number of arenas normally used. Note that using
- substantially more arenas than the default is not likely to improve
- performance, mainly due to reduced cache performance. However, it may make
- sense to reduce the number of arenas if an application does not make much
- use of the allocation functions.</para>
-
- <para>In addition to multiple arenas, unless
- <option>--disable-tcache</option> is specified during configuration, this
- allocator supports thread-specific caching for small and large objects, in
- order to make it possible to completely avoid synchronization for most
- allocation requests. Such caching allows very fast allocation in the
- common case, but it increases memory usage and fragmentation, since a
- bounded number of objects can remain allocated in each thread cache.</para>
-
- <para>Memory is conceptually broken into equal-sized chunks, where the chunk
- size is a power of two that is greater than the page size. Chunks are
- always aligned to multiples of the chunk size. This alignment makes it
- possible to find metadata for user objects very quickly. User objects are
- broken into three categories according to size: small, large, and huge.
- Multiple small and large objects can reside within a single chunk, whereas
- huge objects each have one or more chunks backing them. Each chunk that
- contains small and/or large objects tracks its contents as runs of
- contiguous pages (unused, backing a set of small objects, or backing one
- large object). The combination of chunk alignment and chunk page maps makes
- it possible to determine all metadata regarding small and large allocations
- in constant time.</para>
-
- <para>Small objects are managed in groups by page runs. Each run maintains
- a bitmap to track which regions are in use. Allocation requests that are no
- more than half the quantum (8 or 16, depending on architecture) are rounded
- up to the nearest power of two that is at least <code
- language="C">sizeof(<type>double</type>)</code>. All other object size
- classes are multiples of the quantum, spaced such that there are four size
- classes for each doubling in size, which limits internal fragmentation to
- approximately 20% for all but the smallest size classes. Small size classes
- are smaller than four times the page size, large size classes are smaller
- than the chunk size (see the <link
- linkend="opt.lg_chunk"><mallctl>opt.lg_chunk</mallctl></link> option), and
- huge size classes extend from the chunk size up to the largest size class
- that does not exceed <constant>PTRDIFF_MAX</constant>.</para>
-
- <para>Allocations are packed tightly together, which can be an issue for
- multi-threaded applications. If you need to assure that allocations do not
- suffer from cacheline sharing, round your allocation requests up to the
- nearest multiple of the cacheline size, or specify cacheline alignment when
- allocating.</para>
-
- <para>The <function>realloc()</function>,
- <function>rallocx()</function>, and
- <function>xallocx()</function> functions may resize allocations
- without moving them under limited circumstances. Unlike the
- <function>*allocx()</function> API, the standard API does not
- officially round up the usable size of an allocation to the nearest size
- class, so technically it is necessary to call
- <function>realloc()</function> to grow e.g. a 9-byte allocation to
- 16 bytes, or shrink a 16-byte allocation to 9 bytes. Growth and shrinkage
- trivially succeeds in place as long as the pre-size and post-size both round
- up to the same size class. No other API guarantees are made regarding
- in-place resizing, but the current implementation also tries to resize large
- and huge allocations in place, as long as the pre-size and post-size are
- both large or both huge. In such cases shrinkage always succeeds for large
- size classes, but for huge size classes the chunk allocator must support
- splitting (see <link
- linkend="arena.i.chunk_hooks"><mallctl>arena.&lt;i&gt;.chunk_hooks</mallctl></link>).
- Growth only succeeds if the trailing memory is currently available, and
- additionally for huge size classes the chunk allocator must support
- merging.</para>
-
- <para>Assuming 2 MiB chunks, 4 KiB pages, and a 16-byte quantum on a
- 64-bit system, the size classes in each category are as shown in <xref
- linkend="size_classes" xrefstyle="template:Table %n"/>.</para>
-
- <table xml:id="size_classes" frame="all">
- <title>Size classes</title>
- <tgroup cols="3" colsep="1" rowsep="1">
- <colspec colname="c1" align="left"/>
- <colspec colname="c2" align="right"/>
- <colspec colname="c3" align="left"/>
- <thead>
- <row>
- <entry>Category</entry>
- <entry>Spacing</entry>
- <entry>Size</entry>
- </row>
- </thead>
- <tbody>
- <row>
- <entry morerows="8">Small</entry>
- <entry>lg</entry>
- <entry>[8]</entry>
- </row>
- <row>
- <entry>16</entry>
- <entry>[16, 32, 48, 64, 80, 96, 112, 128]</entry>
- </row>
- <row>
- <entry>32</entry>
- <entry>[160, 192, 224, 256]</entry>
- </row>
- <row>
- <entry>64</entry>
- <entry>[320, 384, 448, 512]</entry>
- </row>
- <row>
- <entry>128</entry>
- <entry>[640, 768, 896, 1024]</entry>
- </row>
- <row>
- <entry>256</entry>
- <entry>[1280, 1536, 1792, 2048]</entry>
- </row>
- <row>
- <entry>512</entry>
- <entry>[2560, 3072, 3584, 4096]</entry>
- </row>
- <row>
- <entry>1 KiB</entry>
- <entry>[5 KiB, 6 KiB, 7 KiB, 8 KiB]</entry>
- </row>
- <row>
- <entry>2 KiB</entry>
- <entry>[10 KiB, 12 KiB, 14 KiB]</entry>
- </row>
- <row>
- <entry morerows="7">Large</entry>
- <entry>2 KiB</entry>
- <entry>[16 KiB]</entry>
- </row>
- <row>
- <entry>4 KiB</entry>
- <entry>[20 KiB, 24 KiB, 28 KiB, 32 KiB]</entry>
- </row>
- <row>
- <entry>8 KiB</entry>
- <entry>[40 KiB, 48 KiB, 54 KiB, 64 KiB]</entry>
- </row>
- <row>
- <entry>16 KiB</entry>
- <entry>[80 KiB, 96 KiB, 112 KiB, 128 KiB]</entry>
- </row>
- <row>
- <entry>32 KiB</entry>
- <entry>[160 KiB, 192 KiB, 224 KiB, 256 KiB]</entry>
- </row>
- <row>
- <entry>64 KiB</entry>
- <entry>[320 KiB, 384 KiB, 448 KiB, 512 KiB]</entry>
- </row>
- <row>
- <entry>128 KiB</entry>
- <entry>[640 KiB, 768 KiB, 896 KiB, 1 MiB]</entry>
- </row>
- <row>
- <entry>256 KiB</entry>
- <entry>[1280 KiB, 1536 KiB, 1792 KiB]</entry>
- </row>
- <row>
- <entry morerows="8">Huge</entry>
- <entry>256 KiB</entry>
- <entry>[2 MiB]</entry>
- </row>
- <row>
- <entry>512 KiB</entry>
- <entry>[2560 KiB, 3 MiB, 3584 KiB, 4 MiB]</entry>
- </row>
- <row>
- <entry>1 MiB</entry>
- <entry>[5 MiB, 6 MiB, 7 MiB, 8 MiB]</entry>
- </row>
- <row>
- <entry>2 MiB</entry>
- <entry>[10 MiB, 12 MiB, 14 MiB, 16 MiB]</entry>
- </row>
- <row>
- <entry>4 MiB</entry>
- <entry>[20 MiB, 24 MiB, 28 MiB, 32 MiB]</entry>
- </row>
- <row>
- <entry>8 MiB</entry>
- <entry>[40 MiB, 48 MiB, 56 MiB, 64 MiB]</entry>
- </row>
- <row>
- <entry>...</entry>
- <entry>...</entry>
- </row>
- <row>
- <entry>512 PiB</entry>
- <entry>[2560 PiB, 3 EiB, 3584 PiB, 4 EiB]</entry>
- </row>
- <row>
- <entry>1 EiB</entry>
- <entry>[5 EiB, 6 EiB, 7 EiB]</entry>
- </row>
- </tbody>
- </tgroup>
- </table>
- </refsect1>
- <refsect1 id="mallctl_namespace">
- <title>MALLCTL NAMESPACE</title>
- <para>The following names are defined in the namespace accessible via the
- <function>mallctl*()</function> functions. Value types are
- specified in parentheses, their readable/writable statuses are encoded as
- <literal>rw</literal>, <literal>r-</literal>, <literal>-w</literal>, or
- <literal>--</literal>, and required build configuration flags follow, if
- any. A name element encoded as <literal>&lt;i&gt;</literal> or
- <literal>&lt;j&gt;</literal> indicates an integer component, where the
- integer varies from 0 to some upper value that must be determined via
- introspection. In the case of <mallctl>stats.arenas.&lt;i&gt;.*</mallctl>,
- <literal>&lt;i&gt;</literal> equal to <link
- linkend="arenas.narenas"><mallctl>arenas.narenas</mallctl></link> can be
- used to access the summation of statistics from all arenas. Take special
- note of the <link linkend="epoch"><mallctl>epoch</mallctl></link> mallctl,
- which controls refreshing of cached dynamic statistics.</para>
-
- <variablelist>
- <varlistentry id="version">
- <term>
- <mallctl>version</mallctl>
- (<type>const char *</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Return the jemalloc version string.</para></listitem>
- </varlistentry>
-
- <varlistentry id="epoch">
- <term>
- <mallctl>epoch</mallctl>
- (<type>uint64_t</type>)
- <literal>rw</literal>
- </term>
- <listitem><para>If a value is passed in, refresh the data from which
- the <function>mallctl*()</function> functions report values,
- and increment the epoch. Return the current epoch. This is useful for
- detecting whether another thread caused a refresh.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.cache_oblivious">
- <term>
- <mallctl>config.cache_oblivious</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-cache-oblivious</option> was specified
- during build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.debug">
- <term>
- <mallctl>config.debug</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-debug</option> was specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.fill">
- <term>
- <mallctl>config.fill</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-fill</option> was specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.lazy_lock">
- <term>
- <mallctl>config.lazy_lock</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-lazy-lock</option> was specified
- during build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.malloc_conf">
- <term>
- <mallctl>config.malloc_conf</mallctl>
- (<type>const char *</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Embedded configure-time-specified run-time options
- string, empty unless <option>--with-malloc-conf</option> was specified
- during build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.munmap">
- <term>
- <mallctl>config.munmap</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-munmap</option> was specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.prof">
- <term>
- <mallctl>config.prof</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-prof</option> was specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.prof_libgcc">
- <term>
- <mallctl>config.prof_libgcc</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--disable-prof-libgcc</option> was not
- specified during build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.prof_libunwind">
- <term>
- <mallctl>config.prof_libunwind</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-prof-libunwind</option> was specified
- during build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.stats">
- <term>
- <mallctl>config.stats</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-stats</option> was specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.tcache">
- <term>
- <mallctl>config.tcache</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--disable-tcache</option> was not specified
- during build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.tls">
- <term>
- <mallctl>config.tls</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--disable-tls</option> was not specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.utrace">
- <term>
- <mallctl>config.utrace</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-utrace</option> was specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.valgrind">
- <term>
- <mallctl>config.valgrind</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-valgrind</option> was specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="config.xmalloc">
- <term>
- <mallctl>config.xmalloc</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para><option>--enable-xmalloc</option> was specified during
- build configuration.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.abort">
- <term>
- <mallctl>opt.abort</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Abort-on-warning enabled/disabled. If true, most
- warnings are fatal. The process will call
- <citerefentry><refentrytitle>abort</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry> in these cases. This option is
- disabled by default unless <option>--enable-debug</option> is
- specified during configuration, in which case it is enabled by default.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.dss">
- <term>
- <mallctl>opt.dss</mallctl>
- (<type>const char *</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>dss (<citerefentry><refentrytitle>sbrk</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry>) allocation precedence as
- related to <citerefentry><refentrytitle>mmap</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> allocation. The following
- settings are supported if
- <citerefentry><refentrytitle>sbrk</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> is supported by the operating
- system: <quote>disabled</quote>, <quote>primary</quote>, and
- <quote>secondary</quote>; otherwise only <quote>disabled</quote> is
- supported. The default is <quote>secondary</quote> if
- <citerefentry><refentrytitle>sbrk</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> is supported by the operating
- system; <quote>disabled</quote> otherwise.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.lg_chunk">
- <term>
- <mallctl>opt.lg_chunk</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Virtual memory chunk size (log base 2). If a chunk
- size outside the supported size range is specified, the size is
- silently clipped to the minimum/maximum supported size. The default
- chunk size is 2 MiB (2^21).
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.narenas">
- <term>
- <mallctl>opt.narenas</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Maximum number of arenas to use for automatic
- multiplexing of threads and arenas. The default is four times the
- number of CPUs, or one if there is a single CPU.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.purge">
- <term>
- <mallctl>opt.purge</mallctl>
- (<type>const char *</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Purge mode is &ldquo;ratio&rdquo; (default) or
- &ldquo;decay&rdquo;. See <link
- linkend="opt.lg_dirty_mult"><mallctl>opt.lg_dirty_mult</mallctl></link>
- for details of the ratio mode. See <link
- linkend="opt.decay_time"><mallctl>opt.decay_time</mallctl></link> for
- details of the decay mode.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.lg_dirty_mult">
- <term>
- <mallctl>opt.lg_dirty_mult</mallctl>
- (<type>ssize_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Per-arena minimum ratio (log base 2) of active to dirty
- pages. Some dirty unused pages may be allowed to accumulate, within
- the limit set by the ratio (or one chunk worth of dirty pages,
- whichever is greater), before informing the kernel about some of those
- pages via <citerefentry><refentrytitle>madvise</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> or a similar system call. This
- provides the kernel with sufficient information to recycle dirty pages
- if physical memory becomes scarce and the pages remain unused. The
- default minimum ratio is 8:1 (2^3:1); an option value of -1 will
- disable dirty page purging. See <link
- linkend="arenas.lg_dirty_mult"><mallctl>arenas.lg_dirty_mult</mallctl></link>
- and <link
- linkend="arena.i.lg_dirty_mult"><mallctl>arena.&lt;i&gt;.lg_dirty_mult</mallctl></link>
- for related dynamic control options.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.decay_time">
- <term>
- <mallctl>opt.decay_time</mallctl>
- (<type>ssize_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Approximate time in seconds from the creation of a set
- of unused dirty pages until an equivalent set of unused dirty pages is
- purged and/or reused. The pages are incrementally purged according to a
- sigmoidal decay curve that starts and ends with zero purge rate. A
- decay time of 0 causes all unused dirty pages to be purged immediately
- upon creation. A decay time of -1 disables purging. The default decay
- time is 10 seconds. See <link
- linkend="arenas.decay_time"><mallctl>arenas.decay_time</mallctl></link>
- and <link
- linkend="arena.i.decay_time"><mallctl>arena.&lt;i&gt;.decay_time</mallctl></link>
- for related dynamic control options.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.stats_print">
- <term>
- <mallctl>opt.stats_print</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Enable/disable statistics printing at exit. If
- enabled, the <function>malloc_stats_print()</function>
- function is called at program exit via an
- <citerefentry><refentrytitle>atexit</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry> function. If
- <option>--enable-stats</option> is specified during configuration, this
- has the potential to cause deadlock for a multi-threaded process that
- exits while one or more threads are executing in the memory allocation
- functions. Furthermore, <function>atexit()</function> may
- allocate memory during application initialization and then deadlock
- internally when jemalloc in turn calls
- <function>atexit()</function>, so this option is not
- universally usable (though the application can register its own
- <function>atexit()</function> function with equivalent
- functionality). Therefore, this option should only be used with care;
- it is primarily intended as a performance tuning aid during application
- development. This option is disabled by default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.junk">
- <term>
- <mallctl>opt.junk</mallctl>
- (<type>const char *</type>)
- <literal>r-</literal>
- [<option>--enable-fill</option>]
- </term>
- <listitem><para>Junk filling. If set to <quote>alloc</quote>, each byte
- of uninitialized allocated memory will be initialized to
- <literal>0xa5</literal>. If set to <quote>free</quote>, all deallocated
- memory will be initialized to <literal>0x5a</literal>. If set to
- <quote>true</quote>, both allocated and deallocated memory will be
- initialized, and if set to <quote>false</quote>, junk filling be
- disabled entirely. This is intended for debugging and will impact
- performance negatively. This option is <quote>false</quote> by default
- unless <option>--enable-debug</option> is specified during
- configuration, in which case it is <quote>true</quote> by default unless
- running inside <ulink
- url="http://valgrind.org/">Valgrind</ulink>.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.quarantine">
- <term>
- <mallctl>opt.quarantine</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-fill</option>]
- </term>
- <listitem><para>Per thread quarantine size in bytes. If non-zero, each
- thread maintains a FIFO object quarantine that stores up to the
- specified number of bytes of memory. The quarantined memory is not
- freed until it is released from quarantine, though it is immediately
- junk-filled if the <link
- linkend="opt.junk"><mallctl>opt.junk</mallctl></link> option is
- enabled. This feature is of particular use in combination with <ulink
- url="http://valgrind.org/">Valgrind</ulink>, which can detect attempts
- to access quarantined objects. This is intended for debugging and will
- impact performance negatively. The default quarantine size is 0 unless
- running inside Valgrind, in which case the default is 16
- MiB.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.redzone">
- <term>
- <mallctl>opt.redzone</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-fill</option>]
- </term>
- <listitem><para>Redzones enabled/disabled. If enabled, small
- allocations have redzones before and after them. Furthermore, if the
- <link linkend="opt.junk"><mallctl>opt.junk</mallctl></link> option is
- enabled, the redzones are checked for corruption during deallocation.
- However, the primary intended purpose of this feature is to be used in
- combination with <ulink url="http://valgrind.org/">Valgrind</ulink>,
- which needs redzones in order to do effective buffer overflow/underflow
- detection. This option is intended for debugging and will impact
- performance negatively. This option is disabled by
- default unless running inside Valgrind.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.zero">
- <term>
- <mallctl>opt.zero</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-fill</option>]
- </term>
- <listitem><para>Zero filling enabled/disabled. If enabled, each byte
- of uninitialized allocated memory will be initialized to 0. Note that
- this initialization only happens once for each byte, so
- <function>realloc()</function> and
- <function>rallocx()</function> calls do not zero memory that
- was previously allocated. This is intended for debugging and will
- impact performance negatively. This option is disabled by default.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.utrace">
- <term>
- <mallctl>opt.utrace</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-utrace</option>]
- </term>
- <listitem><para>Allocation tracing based on
- <citerefentry><refentrytitle>utrace</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> enabled/disabled. This option
- is disabled by default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.xmalloc">
- <term>
- <mallctl>opt.xmalloc</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-xmalloc</option>]
- </term>
- <listitem><para>Abort-on-out-of-memory enabled/disabled. If enabled,
- rather than returning failure for any allocation function, display a
- diagnostic message on <constant>STDERR_FILENO</constant> and cause the
- program to drop core (using
- <citerefentry><refentrytitle>abort</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry>). If an application is
- designed to depend on this behavior, set the option at compile time by
- including the following in the source code:
- <programlisting language="C"><![CDATA[
-malloc_conf = "xmalloc:true";]]></programlisting>
- This option is disabled by default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.tcache">
- <term>
- <mallctl>opt.tcache</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Thread-specific caching (tcache) enabled/disabled. When
- there are multiple threads, each thread uses a tcache for objects up to
- a certain size. Thread-specific caching allows many allocations to be
- satisfied without performing any thread synchronization, at the cost of
- increased memory use. See the <link
- linkend="opt.lg_tcache_max"><mallctl>opt.lg_tcache_max</mallctl></link>
- option for related tuning information. This option is enabled by
- default unless running inside <ulink
- url="http://valgrind.org/">Valgrind</ulink>, in which case it is
- forcefully disabled.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.lg_tcache_max">
- <term>
- <mallctl>opt.lg_tcache_max</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Maximum size class (log base 2) to cache in the
- thread-specific cache (tcache). At a minimum, all small size classes
- are cached, and at a maximum all large size classes are cached. The
- default maximum is 32 KiB (2^15).</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.prof">
- <term>
- <mallctl>opt.prof</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Memory profiling enabled/disabled. If enabled, profile
- memory allocation activity. See the <link
- linkend="opt.prof_active"><mallctl>opt.prof_active</mallctl></link>
- option for on-the-fly activation/deactivation. See the <link
- linkend="opt.lg_prof_sample"><mallctl>opt.lg_prof_sample</mallctl></link>
- option for probabilistic sampling control. See the <link
- linkend="opt.prof_accum"><mallctl>opt.prof_accum</mallctl></link>
- option for control of cumulative sample reporting. See the <link
- linkend="opt.lg_prof_interval"><mallctl>opt.lg_prof_interval</mallctl></link>
- option for information on interval-triggered profile dumping, the <link
- linkend="opt.prof_gdump"><mallctl>opt.prof_gdump</mallctl></link>
- option for information on high-water-triggered profile dumping, and the
- <link linkend="opt.prof_final"><mallctl>opt.prof_final</mallctl></link>
- option for final profile dumping. Profile output is compatible with
- the <command>jeprof</command> command, which is based on the
- <command>pprof</command> that is developed as part of the <ulink
- url="http://code.google.com/p/gperftools/">gperftools
- package</ulink>. See <link linkend="heap_profile_format">HEAP PROFILE
- FORMAT</link> for heap profile format documentation.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.prof_prefix">
- <term>
- <mallctl>opt.prof_prefix</mallctl>
- (<type>const char *</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Filename prefix for profile dumps. If the prefix is
- set to the empty string, no automatic dumps will occur; this is
- primarily useful for disabling the automatic final heap dump (which
- also disables leak reporting, if enabled). The default prefix is
- <filename>jeprof</filename>.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.prof_active">
- <term>
- <mallctl>opt.prof_active</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Profiling activated/deactivated. This is a secondary
- control mechanism that makes it possible to start the application with
- profiling enabled (see the <link
- linkend="opt.prof"><mallctl>opt.prof</mallctl></link> option) but
- inactive, then toggle profiling at any time during program execution
- with the <link
- linkend="prof.active"><mallctl>prof.active</mallctl></link> mallctl.
- This option is enabled by default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.prof_thread_active_init">
- <term>
- <mallctl>opt.prof_thread_active_init</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Initial setting for <link
- linkend="thread.prof.active"><mallctl>thread.prof.active</mallctl></link>
- in newly created threads. The initial setting for newly created threads
- can also be changed during execution via the <link
- linkend="prof.thread_active_init"><mallctl>prof.thread_active_init</mallctl></link>
- mallctl. This option is enabled by default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.lg_prof_sample">
- <term>
- <mallctl>opt.lg_prof_sample</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Average interval (log base 2) between allocation
- samples, as measured in bytes of allocation activity. Increasing the
- sampling interval decreases profile fidelity, but also decreases the
- computational overhead. The default sample interval is 512 KiB (2^19
- B).</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.prof_accum">
- <term>
- <mallctl>opt.prof_accum</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Reporting of cumulative object/byte counts in profile
- dumps enabled/disabled. If this option is enabled, every unique
- backtrace must be stored for the duration of execution. Depending on
- the application, this can impose a large memory overhead, and the
- cumulative counts are not always of interest. This option is disabled
- by default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.lg_prof_interval">
- <term>
- <mallctl>opt.lg_prof_interval</mallctl>
- (<type>ssize_t</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Average interval (log base 2) between memory profile
- dumps, as measured in bytes of allocation activity. The actual
- interval between dumps may be sporadic because decentralized allocation
- counters are used to avoid synchronization bottlenecks. Profiles are
- dumped to files named according to the pattern
- <filename>&lt;prefix&gt;.&lt;pid&gt;.&lt;seq&gt;.i&lt;iseq&gt;.heap</filename>,
- where <literal>&lt;prefix&gt;</literal> is controlled by the
- <link
- linkend="opt.prof_prefix"><mallctl>opt.prof_prefix</mallctl></link>
- option. By default, interval-triggered profile dumping is disabled
- (encoded as -1).
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.prof_gdump">
- <term>
- <mallctl>opt.prof_gdump</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Set the initial state of <link
- linkend="prof.gdump"><mallctl>prof.gdump</mallctl></link>, which when
- enabled triggers a memory profile dump every time the total virtual
- memory exceeds the previous maximum. This option is disabled by
- default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.prof_final">
- <term>
- <mallctl>opt.prof_final</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Use an
- <citerefentry><refentrytitle>atexit</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry> function to dump final memory
- usage to a file named according to the pattern
- <filename>&lt;prefix&gt;.&lt;pid&gt;.&lt;seq&gt;.f.heap</filename>,
- where <literal>&lt;prefix&gt;</literal> is controlled by the <link
- linkend="opt.prof_prefix"><mallctl>opt.prof_prefix</mallctl></link>
- option. Note that <function>atexit()</function> may allocate
- memory during application initialization and then deadlock internally
- when jemalloc in turn calls <function>atexit()</function>, so
- this option is not universally usable (though the application can
- register its own <function>atexit()</function> function with
- equivalent functionality). This option is disabled by
- default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="opt.prof_leak">
- <term>
- <mallctl>opt.prof_leak</mallctl>
- (<type>bool</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Leak reporting enabled/disabled. If enabled, use an
- <citerefentry><refentrytitle>atexit</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry> function to report memory leaks
- detected by allocation sampling. See the
- <link linkend="opt.prof"><mallctl>opt.prof</mallctl></link> option for
- information on analyzing heap profile output. This option is disabled
- by default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.arena">
- <term>
- <mallctl>thread.arena</mallctl>
- (<type>unsigned</type>)
- <literal>rw</literal>
- </term>
- <listitem><para>Get or set the arena associated with the calling
- thread. If the specified arena was not initialized beforehand (see the
- <link
- linkend="arenas.initialized"><mallctl>arenas.initialized</mallctl></link>
- mallctl), it will be automatically initialized as a side effect of
- calling this interface.</para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.allocated">
- <term>
- <mallctl>thread.allocated</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Get the total number of bytes ever allocated by the
- calling thread. This counter has the potential to wrap around; it is
- up to the application to appropriately interpret the counter in such
- cases.</para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.allocatedp">
- <term>
- <mallctl>thread.allocatedp</mallctl>
- (<type>uint64_t *</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Get a pointer to the the value that is returned by the
- <link
- linkend="thread.allocated"><mallctl>thread.allocated</mallctl></link>
- mallctl. This is useful for avoiding the overhead of repeated
- <function>mallctl*()</function> calls.</para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.deallocated">
- <term>
- <mallctl>thread.deallocated</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Get the total number of bytes ever deallocated by the
- calling thread. This counter has the potential to wrap around; it is
- up to the application to appropriately interpret the counter in such
- cases.</para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.deallocatedp">
- <term>
- <mallctl>thread.deallocatedp</mallctl>
- (<type>uint64_t *</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Get a pointer to the the value that is returned by the
- <link
- linkend="thread.deallocated"><mallctl>thread.deallocated</mallctl></link>
- mallctl. This is useful for avoiding the overhead of repeated
- <function>mallctl*()</function> calls.</para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.tcache.enabled">
- <term>
- <mallctl>thread.tcache.enabled</mallctl>
- (<type>bool</type>)
- <literal>rw</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Enable/disable calling thread's tcache. The tcache is
- implicitly flushed as a side effect of becoming
- disabled (see <link
- linkend="thread.tcache.flush"><mallctl>thread.tcache.flush</mallctl></link>).
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.tcache.flush">
- <term>
- <mallctl>thread.tcache.flush</mallctl>
- (<type>void</type>)
- <literal>--</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Flush calling thread's thread-specific cache (tcache).
- This interface releases all cached objects and internal data structures
- associated with the calling thread's tcache. Ordinarily, this interface
- need not be called, since automatic periodic incremental garbage
- collection occurs, and the thread cache is automatically discarded when
- a thread exits. However, garbage collection is triggered by allocation
- activity, so it is possible for a thread that stops
- allocating/deallocating to retain its cache indefinitely, in which case
- the developer may find manual flushing useful.</para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.prof.name">
- <term>
- <mallctl>thread.prof.name</mallctl>
- (<type>const char *</type>)
- <literal>r-</literal> or
- <literal>-w</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Get/set the descriptive name associated with the calling
- thread in memory profile dumps. An internal copy of the name string is
- created, so the input string need not be maintained after this interface
- completes execution. The output string of this interface should be
- copied for non-ephemeral uses, because multiple implementation details
- can cause asynchronous string deallocation. Furthermore, each
- invocation of this interface can only read or write; simultaneous
- read/write is not supported due to string lifetime limitations. The
- name string must be nil-terminated and comprised only of characters in
- the sets recognized
- by <citerefentry><refentrytitle>isgraph</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry> and
- <citerefentry><refentrytitle>isblank</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry>.</para></listitem>
- </varlistentry>
-
- <varlistentry id="thread.prof.active">
- <term>
- <mallctl>thread.prof.active</mallctl>
- (<type>bool</type>)
- <literal>rw</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Control whether sampling is currently active for the
- calling thread. This is an activation mechanism in addition to <link
- linkend="prof.active"><mallctl>prof.active</mallctl></link>; both must
- be active for the calling thread to sample. This flag is enabled by
- default.</para></listitem>
- </varlistentry>
-
- <varlistentry id="tcache.create">
- <term>
- <mallctl>tcache.create</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Create an explicit thread-specific cache (tcache) and
- return an identifier that can be passed to the <link
- linkend="MALLOCX_TCACHE"><constant>MALLOCX_TCACHE(<parameter>tc</parameter>)</constant></link>
- macro to explicitly use the specified cache rather than the
- automatically managed one that is used by default. Each explicit cache
- can be used by only one thread at a time; the application must assure
- that this constraint holds.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="tcache.flush">
- <term>
- <mallctl>tcache.flush</mallctl>
- (<type>unsigned</type>)
- <literal>-w</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Flush the specified thread-specific cache (tcache). The
- same considerations apply to this interface as to <link
- linkend="thread.tcache.flush"><mallctl>thread.tcache.flush</mallctl></link>,
- except that the tcache will never be automatically discarded.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="tcache.destroy">
- <term>
- <mallctl>tcache.destroy</mallctl>
- (<type>unsigned</type>)
- <literal>-w</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Flush the specified thread-specific cache (tcache) and
- make the identifier available for use during a future tcache creation.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="arena.i.purge">
- <term>
- <mallctl>arena.&lt;i&gt;.purge</mallctl>
- (<type>void</type>)
- <literal>--</literal>
- </term>
- <listitem><para>Purge all unused dirty pages for arena &lt;i&gt;, or for
- all arenas if &lt;i&gt; equals <link
- linkend="arenas.narenas"><mallctl>arenas.narenas</mallctl></link>.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="arena.i.decay">
- <term>
- <mallctl>arena.&lt;i&gt;.decay</mallctl>
- (<type>void</type>)
- <literal>--</literal>
- </term>
- <listitem><para>Trigger decay-based purging of unused dirty pages for
- arena &lt;i&gt;, or for all arenas if &lt;i&gt; equals <link
- linkend="arenas.narenas"><mallctl>arenas.narenas</mallctl></link>.
- The proportion of unused dirty pages to be purged depends on the current
- time; see <link
- linkend="opt.decay_time"><mallctl>opt.decay_time</mallctl></link> for
- details.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arena.i.reset">
- <term>
- <mallctl>arena.&lt;i&gt;.reset</mallctl>
- (<type>void</type>)
- <literal>--</literal>
- </term>
- <listitem><para>Discard all of the arena's extant allocations. This
- interface can only be used with arenas created via <link
- linkend="arenas.extend"><mallctl>arenas.extend</mallctl></link>. None
- of the arena's discarded/cached allocations may accessed afterward. As
- part of this requirement, all thread caches which were used to
- allocate/deallocate in conjunction with the arena must be flushed
- beforehand. This interface cannot be used if running inside Valgrind,
- nor if the <link linkend="opt.quarantine">quarantine</link> size is
- non-zero.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arena.i.dss">
- <term>
- <mallctl>arena.&lt;i&gt;.dss</mallctl>
- (<type>const char *</type>)
- <literal>rw</literal>
- </term>
- <listitem><para>Set the precedence of dss allocation as related to mmap
- allocation for arena &lt;i&gt;, or for all arenas if &lt;i&gt; equals
- <link
- linkend="arenas.narenas"><mallctl>arenas.narenas</mallctl></link>. See
- <link linkend="opt.dss"><mallctl>opt.dss</mallctl></link> for supported
- settings.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arena.i.lg_dirty_mult">
- <term>
- <mallctl>arena.&lt;i&gt;.lg_dirty_mult</mallctl>
- (<type>ssize_t</type>)
- <literal>rw</literal>
- </term>
- <listitem><para>Current per-arena minimum ratio (log base 2) of active
- to dirty pages for arena &lt;i&gt;. Each time this interface is set and
- the ratio is increased, pages are synchronously purged as necessary to
- impose the new ratio. See <link
- linkend="opt.lg_dirty_mult"><mallctl>opt.lg_dirty_mult</mallctl></link>
- for additional information.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arena.i.decay_time">
- <term>
- <mallctl>arena.&lt;i&gt;.decay_time</mallctl>
- (<type>ssize_t</type>)
- <literal>rw</literal>
- </term>
- <listitem><para>Current per-arena approximate time in seconds from the
- creation of a set of unused dirty pages until an equivalent set of
- unused dirty pages is purged and/or reused. Each time this interface is
- set, all currently unused dirty pages are considered to have fully
- decayed, which causes immediate purging of all unused dirty pages unless
- the decay time is set to -1 (i.e. purging disabled). See <link
- linkend="opt.decay_time"><mallctl>opt.decay_time</mallctl></link> for
- additional information.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arena.i.chunk_hooks">
- <term>
- <mallctl>arena.&lt;i&gt;.chunk_hooks</mallctl>
- (<type>chunk_hooks_t</type>)
- <literal>rw</literal>
- </term>
- <listitem><para>Get or set the chunk management hook functions for arena
- &lt;i&gt;. The functions must be capable of operating on all extant
- chunks associated with arena &lt;i&gt;, usually by passing unknown
- chunks to the replaced functions. In practice, it is feasible to
- control allocation for arenas created via <link
- linkend="arenas.extend"><mallctl>arenas.extend</mallctl></link> such
- that all chunks originate from an application-supplied chunk allocator
- (by setting custom chunk hook functions just after arena creation), but
- the automatically created arenas may have already created chunks prior
- to the application having an opportunity to take over chunk
- allocation.</para>
-
- <programlisting language="C"><![CDATA[
-typedef struct {
- chunk_alloc_t *alloc;
- chunk_dalloc_t *dalloc;
- chunk_commit_t *commit;
- chunk_decommit_t *decommit;
- chunk_purge_t *purge;
- chunk_split_t *split;
- chunk_merge_t *merge;
-} chunk_hooks_t;]]></programlisting>
- <para>The <type>chunk_hooks_t</type> structure comprises function
- pointers which are described individually below. jemalloc uses these
- functions to manage chunk lifetime, which starts off with allocation of
- mapped committed memory, in the simplest case followed by deallocation.
- However, there are performance and platform reasons to retain chunks for
- later reuse. Cleanup attempts cascade from deallocation to decommit to
- purging, which gives the chunk management functions opportunities to
- reject the most permanent cleanup operations in favor of less permanent
- (and often less costly) operations. The chunk splitting and merging
- operations can also be opted out of, but this is mainly intended to
- support platforms on which virtual memory mappings provided by the
- operating system kernel do not automatically coalesce and split, e.g.
- Windows.</para>
-
- <funcsynopsis><funcprototype>
- <funcdef>typedef void *<function>(chunk_alloc_t)</function></funcdef>
- <paramdef>void *<parameter>chunk</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>size_t <parameter>alignment</parameter></paramdef>
- <paramdef>bool *<parameter>zero</parameter></paramdef>
- <paramdef>bool *<parameter>commit</parameter></paramdef>
- <paramdef>unsigned <parameter>arena_ind</parameter></paramdef>
- </funcprototype></funcsynopsis>
- <literallayout></literallayout>
- <para>A chunk allocation function conforms to the
- <type>chunk_alloc_t</type> type and upon success returns a pointer to
- <parameter>size</parameter> bytes of mapped memory on behalf of arena
- <parameter>arena_ind</parameter> such that the chunk's base address is a
- multiple of <parameter>alignment</parameter>, as well as setting
- <parameter>*zero</parameter> to indicate whether the chunk is zeroed and
- <parameter>*commit</parameter> to indicate whether the chunk is
- committed. Upon error the function returns <constant>NULL</constant>
- and leaves <parameter>*zero</parameter> and
- <parameter>*commit</parameter> unmodified. The
- <parameter>size</parameter> parameter is always a multiple of the chunk
- size. The <parameter>alignment</parameter> parameter is always a power
- of two at least as large as the chunk size. Zeroing is mandatory if
- <parameter>*zero</parameter> is true upon function entry. Committing is
- mandatory if <parameter>*commit</parameter> is true upon function entry.
- If <parameter>chunk</parameter> is not <constant>NULL</constant>, the
- returned pointer must be <parameter>chunk</parameter> on success or
- <constant>NULL</constant> on error. Committed memory may be committed
- in absolute terms as on a system that does not overcommit, or in
- implicit terms as on a system that overcommits and satisfies physical
- memory needs on demand via soft page faults. Note that replacing the
- default chunk allocation function makes the arena's <link
- linkend="arena.i.dss"><mallctl>arena.&lt;i&gt;.dss</mallctl></link>
- setting irrelevant.</para>
-
- <funcsynopsis><funcprototype>
- <funcdef>typedef bool <function>(chunk_dalloc_t)</function></funcdef>
- <paramdef>void *<parameter>chunk</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>bool <parameter>committed</parameter></paramdef>
- <paramdef>unsigned <parameter>arena_ind</parameter></paramdef>
- </funcprototype></funcsynopsis>
- <literallayout></literallayout>
- <para>
- A chunk deallocation function conforms to the
- <type>chunk_dalloc_t</type> type and deallocates a
- <parameter>chunk</parameter> of given <parameter>size</parameter> with
- <parameter>committed</parameter>/decommited memory as indicated, on
- behalf of arena <parameter>arena_ind</parameter>, returning false upon
- success. If the function returns true, this indicates opt-out from
- deallocation; the virtual memory mapping associated with the chunk
- remains mapped, in the same commit state, and available for future use,
- in which case it will be automatically retained for later reuse.</para>
-
- <funcsynopsis><funcprototype>
- <funcdef>typedef bool <function>(chunk_commit_t)</function></funcdef>
- <paramdef>void *<parameter>chunk</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>size_t <parameter>offset</parameter></paramdef>
- <paramdef>size_t <parameter>length</parameter></paramdef>
- <paramdef>unsigned <parameter>arena_ind</parameter></paramdef>
- </funcprototype></funcsynopsis>
- <literallayout></literallayout>
- <para>A chunk commit function conforms to the
- <type>chunk_commit_t</type> type and commits zeroed physical memory to
- back pages within a <parameter>chunk</parameter> of given
- <parameter>size</parameter> at <parameter>offset</parameter> bytes,
- extending for <parameter>length</parameter> on behalf of arena
- <parameter>arena_ind</parameter>, returning false upon success.
- Committed memory may be committed in absolute terms as on a system that
- does not overcommit, or in implicit terms as on a system that
- overcommits and satisfies physical memory needs on demand via soft page
- faults. If the function returns true, this indicates insufficient
- physical memory to satisfy the request.</para>
-
- <funcsynopsis><funcprototype>
- <funcdef>typedef bool <function>(chunk_decommit_t)</function></funcdef>
- <paramdef>void *<parameter>chunk</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>size_t <parameter>offset</parameter></paramdef>
- <paramdef>size_t <parameter>length</parameter></paramdef>
- <paramdef>unsigned <parameter>arena_ind</parameter></paramdef>
- </funcprototype></funcsynopsis>
- <literallayout></literallayout>
- <para>A chunk decommit function conforms to the
- <type>chunk_decommit_t</type> type and decommits any physical memory
- that is backing pages within a <parameter>chunk</parameter> of given
- <parameter>size</parameter> at <parameter>offset</parameter> bytes,
- extending for <parameter>length</parameter> on behalf of arena
- <parameter>arena_ind</parameter>, returning false upon success, in which
- case the pages will be committed via the chunk commit function before
- being reused. If the function returns true, this indicates opt-out from
- decommit; the memory remains committed and available for future use, in
- which case it will be automatically retained for later reuse.</para>
-
- <funcsynopsis><funcprototype>
- <funcdef>typedef bool <function>(chunk_purge_t)</function></funcdef>
- <paramdef>void *<parameter>chunk</parameter></paramdef>
- <paramdef>size_t<parameter>size</parameter></paramdef>
- <paramdef>size_t <parameter>offset</parameter></paramdef>
- <paramdef>size_t <parameter>length</parameter></paramdef>
- <paramdef>unsigned <parameter>arena_ind</parameter></paramdef>
- </funcprototype></funcsynopsis>
- <literallayout></literallayout>
- <para>A chunk purge function conforms to the <type>chunk_purge_t</type>
- type and optionally discards physical pages within the virtual memory
- mapping associated with <parameter>chunk</parameter> of given
- <parameter>size</parameter> at <parameter>offset</parameter> bytes,
- extending for <parameter>length</parameter> on behalf of arena
- <parameter>arena_ind</parameter>, returning false if pages within the
- purged virtual memory range will be zero-filled the next time they are
- accessed.</para>
-
- <funcsynopsis><funcprototype>
- <funcdef>typedef bool <function>(chunk_split_t)</function></funcdef>
- <paramdef>void *<parameter>chunk</parameter></paramdef>
- <paramdef>size_t <parameter>size</parameter></paramdef>
- <paramdef>size_t <parameter>size_a</parameter></paramdef>
- <paramdef>size_t <parameter>size_b</parameter></paramdef>
- <paramdef>bool <parameter>committed</parameter></paramdef>
- <paramdef>unsigned <parameter>arena_ind</parameter></paramdef>
- </funcprototype></funcsynopsis>
- <literallayout></literallayout>
- <para>A chunk split function conforms to the <type>chunk_split_t</type>
- type and optionally splits <parameter>chunk</parameter> of given
- <parameter>size</parameter> into two adjacent chunks, the first of
- <parameter>size_a</parameter> bytes, and the second of
- <parameter>size_b</parameter> bytes, operating on
- <parameter>committed</parameter>/decommitted memory as indicated, on
- behalf of arena <parameter>arena_ind</parameter>, returning false upon
- success. If the function returns true, this indicates that the chunk
- remains unsplit and therefore should continue to be operated on as a
- whole.</para>
-
- <funcsynopsis><funcprototype>
- <funcdef>typedef bool <function>(chunk_merge_t)</function></funcdef>
- <paramdef>void *<parameter>chunk_a</parameter></paramdef>
- <paramdef>size_t <parameter>size_a</parameter></paramdef>
- <paramdef>void *<parameter>chunk_b</parameter></paramdef>
- <paramdef>size_t <parameter>size_b</parameter></paramdef>
- <paramdef>bool <parameter>committed</parameter></paramdef>
- <paramdef>unsigned <parameter>arena_ind</parameter></paramdef>
- </funcprototype></funcsynopsis>
- <literallayout></literallayout>
- <para>A chunk merge function conforms to the <type>chunk_merge_t</type>
- type and optionally merges adjacent chunks,
- <parameter>chunk_a</parameter> of given <parameter>size_a</parameter>
- and <parameter>chunk_b</parameter> of given
- <parameter>size_b</parameter> into one contiguous chunk, operating on
- <parameter>committed</parameter>/decommitted memory as indicated, on
- behalf of arena <parameter>arena_ind</parameter>, returning false upon
- success. If the function returns true, this indicates that the chunks
- remain distinct mappings and therefore should continue to be operated on
- independently.</para>
- </listitem>
- </varlistentry>
-
- <varlistentry id="arenas.narenas">
- <term>
- <mallctl>arenas.narenas</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Current limit on number of arenas.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.initialized">
- <term>
- <mallctl>arenas.initialized</mallctl>
- (<type>bool *</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>An array of <link
- linkend="arenas.narenas"><mallctl>arenas.narenas</mallctl></link>
- booleans. Each boolean indicates whether the corresponding arena is
- initialized.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.lg_dirty_mult">
- <term>
- <mallctl>arenas.lg_dirty_mult</mallctl>
- (<type>ssize_t</type>)
- <literal>rw</literal>
- </term>
- <listitem><para>Current default per-arena minimum ratio (log base 2) of
- active to dirty pages, used to initialize <link
- linkend="arena.i.lg_dirty_mult"><mallctl>arena.&lt;i&gt;.lg_dirty_mult</mallctl></link>
- during arena creation. See <link
- linkend="opt.lg_dirty_mult"><mallctl>opt.lg_dirty_mult</mallctl></link>
- for additional information.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.decay_time">
- <term>
- <mallctl>arenas.decay_time</mallctl>
- (<type>ssize_t</type>)
- <literal>rw</literal>
- </term>
- <listitem><para>Current default per-arena approximate time in seconds
- from the creation of a set of unused dirty pages until an equivalent set
- of unused dirty pages is purged and/or reused, used to initialize <link
- linkend="arena.i.decay_time"><mallctl>arena.&lt;i&gt;.decay_time</mallctl></link>
- during arena creation. See <link
- linkend="opt.decay_time"><mallctl>opt.decay_time</mallctl></link> for
- additional information.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.quantum">
- <term>
- <mallctl>arenas.quantum</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Quantum size.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.page">
- <term>
- <mallctl>arenas.page</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Page size.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.tcache_max">
- <term>
- <mallctl>arenas.tcache_max</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Maximum thread-cached size class.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.nbins">
- <term>
- <mallctl>arenas.nbins</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Number of bin size classes.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.nhbins">
- <term>
- <mallctl>arenas.nhbins</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- [<option>--enable-tcache</option>]
- </term>
- <listitem><para>Total number of thread cache bin size
- classes.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.bin.i.size">
- <term>
- <mallctl>arenas.bin.&lt;i&gt;.size</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Maximum size supported by size class.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.bin.i.nregs">
- <term>
- <mallctl>arenas.bin.&lt;i&gt;.nregs</mallctl>
- (<type>uint32_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Number of regions per page run.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.bin.i.run_size">
- <term>
- <mallctl>arenas.bin.&lt;i&gt;.run_size</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Number of bytes per page run.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.nlruns">
- <term>
- <mallctl>arenas.nlruns</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Total number of large size classes.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.lrun.i.size">
- <term>
- <mallctl>arenas.lrun.&lt;i&gt;.size</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Maximum size supported by this large size
- class.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.nhchunks">
- <term>
- <mallctl>arenas.nhchunks</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Total number of huge size classes.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.hchunk.i.size">
- <term>
- <mallctl>arenas.hchunk.&lt;i&gt;.size</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Maximum size supported by this huge size
- class.</para></listitem>
- </varlistentry>
-
- <varlistentry id="arenas.extend">
- <term>
- <mallctl>arenas.extend</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Extend the array of arenas by appending a new arena,
- and returning the new arena index.</para></listitem>
- </varlistentry>
-
- <varlistentry id="prof.thread_active_init">
- <term>
- <mallctl>prof.thread_active_init</mallctl>
- (<type>bool</type>)
- <literal>rw</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Control the initial setting for <link
- linkend="thread.prof.active"><mallctl>thread.prof.active</mallctl></link>
- in newly created threads. See the <link
- linkend="opt.prof_thread_active_init"><mallctl>opt.prof_thread_active_init</mallctl></link>
- option for additional information.</para></listitem>
- </varlistentry>
-
- <varlistentry id="prof.active">
- <term>
- <mallctl>prof.active</mallctl>
- (<type>bool</type>)
- <literal>rw</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Control whether sampling is currently active. See the
- <link
- linkend="opt.prof_active"><mallctl>opt.prof_active</mallctl></link>
- option for additional information, as well as the interrelated <link
- linkend="thread.prof.active"><mallctl>thread.prof.active</mallctl></link>
- mallctl.</para></listitem>
- </varlistentry>
-
- <varlistentry id="prof.dump">
- <term>
- <mallctl>prof.dump</mallctl>
- (<type>const char *</type>)
- <literal>-w</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Dump a memory profile to the specified file, or if NULL
- is specified, to a file according to the pattern
- <filename>&lt;prefix&gt;.&lt;pid&gt;.&lt;seq&gt;.m&lt;mseq&gt;.heap</filename>,
- where <literal>&lt;prefix&gt;</literal> is controlled by the
- <link
- linkend="opt.prof_prefix"><mallctl>opt.prof_prefix</mallctl></link>
- option.</para></listitem>
- </varlistentry>
-
- <varlistentry id="prof.gdump">
- <term>
- <mallctl>prof.gdump</mallctl>
- (<type>bool</type>)
- <literal>rw</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>When enabled, trigger a memory profile dump every time
- the total virtual memory exceeds the previous maximum. Profiles are
- dumped to files named according to the pattern
- <filename>&lt;prefix&gt;.&lt;pid&gt;.&lt;seq&gt;.u&lt;useq&gt;.heap</filename>,
- where <literal>&lt;prefix&gt;</literal> is controlled by the <link
- linkend="opt.prof_prefix"><mallctl>opt.prof_prefix</mallctl></link>
- option.</para></listitem>
- </varlistentry>
-
- <varlistentry id="prof.reset">
- <term>
- <mallctl>prof.reset</mallctl>
- (<type>size_t</type>)
- <literal>-w</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Reset all memory profile statistics, and optionally
- update the sample rate (see <link
- linkend="opt.lg_prof_sample"><mallctl>opt.lg_prof_sample</mallctl></link>
- and <link
- linkend="prof.lg_sample"><mallctl>prof.lg_sample</mallctl></link>).
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="prof.lg_sample">
- <term>
- <mallctl>prof.lg_sample</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Get the current sample rate (see <link
- linkend="opt.lg_prof_sample"><mallctl>opt.lg_prof_sample</mallctl></link>).
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="prof.interval">
- <term>
- <mallctl>prof.interval</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-prof</option>]
- </term>
- <listitem><para>Average number of bytes allocated between
- interval-based profile dumps. See the
- <link
- linkend="opt.lg_prof_interval"><mallctl>opt.lg_prof_interval</mallctl></link>
- option for additional information.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.cactive">
- <term>
- <mallctl>stats.cactive</mallctl>
- (<type>size_t *</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Pointer to a counter that contains an approximate count
- of the current number of bytes in active pages. The estimate may be
- high, but never low, because each arena rounds up when computing its
- contribution to the counter. Note that the <link
- linkend="epoch"><mallctl>epoch</mallctl></link> mallctl has no bearing
- on this counter. Furthermore, counter consistency is maintained via
- atomic operations, so it is necessary to use an atomic operation in
- order to guarantee a consistent read when dereferencing the pointer.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.allocated">
- <term>
- <mallctl>stats.allocated</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Total number of bytes allocated by the
- application.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.active">
- <term>
- <mallctl>stats.active</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Total number of bytes in active pages allocated by the
- application. This is a multiple of the page size, and greater than or
- equal to <link
- linkend="stats.allocated"><mallctl>stats.allocated</mallctl></link>.
- This does not include <link linkend="stats.arenas.i.pdirty">
- <mallctl>stats.arenas.&lt;i&gt;.pdirty</mallctl></link>, nor pages
- entirely devoted to allocator metadata.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.metadata">
- <term>
- <mallctl>stats.metadata</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Total number of bytes dedicated to metadata, which
- comprise base allocations used for bootstrap-sensitive internal
- allocator data structures, arena chunk headers (see <link
- linkend="stats.arenas.i.metadata.mapped"><mallctl>stats.arenas.&lt;i&gt;.metadata.mapped</mallctl></link>),
- and internal allocations (see <link
- linkend="stats.arenas.i.metadata.allocated"><mallctl>stats.arenas.&lt;i&gt;.metadata.allocated</mallctl></link>).</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.resident">
- <term>
- <mallctl>stats.resident</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Maximum number of bytes in physically resident data
- pages mapped by the allocator, comprising all pages dedicated to
- allocator metadata, pages backing active allocations, and unused dirty
- pages. This is a maximum rather than precise because pages may not
- actually be physically resident if they correspond to demand-zeroed
- virtual memory that has not yet been touched. This is a multiple of the
- page size, and is larger than <link
- linkend="stats.active"><mallctl>stats.active</mallctl></link>.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.mapped">
- <term>
- <mallctl>stats.mapped</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Total number of bytes in active chunks mapped by the
- allocator. This is a multiple of the chunk size, and is larger than
- <link linkend="stats.active"><mallctl>stats.active</mallctl></link>.
- This does not include inactive chunks, even those that contain unused
- dirty pages, which means that there is no strict ordering between this
- and <link
- linkend="stats.resident"><mallctl>stats.resident</mallctl></link>.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.retained">
- <term>
- <mallctl>stats.retained</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Total number of bytes in virtual memory mappings that
- were retained rather than being returned to the operating system via
- e.g. <citerefentry><refentrytitle>munmap</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry>. Retained virtual memory is
- typically untouched, decommitted, or purged, so it has no strongly
- associated physical memory (see <link
- linkend="arena.i.chunk_hooks">chunk hooks</link> for details). Retained
- memory is excluded from mapped memory statistics, e.g. <link
- linkend="stats.mapped"><mallctl>stats.mapped</mallctl></link>.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.dss">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.dss</mallctl>
- (<type>const char *</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>dss (<citerefentry><refentrytitle>sbrk</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry>) allocation precedence as
- related to <citerefentry><refentrytitle>mmap</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry> allocation. See <link
- linkend="opt.dss"><mallctl>opt.dss</mallctl></link> for details.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.lg_dirty_mult">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.lg_dirty_mult</mallctl>
- (<type>ssize_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Minimum ratio (log base 2) of active to dirty pages.
- See <link
- linkend="opt.lg_dirty_mult"><mallctl>opt.lg_dirty_mult</mallctl></link>
- for details.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.decay_time">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.decay_time</mallctl>
- (<type>ssize_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Approximate time in seconds from the creation of a set
- of unused dirty pages until an equivalent set of unused dirty pages is
- purged and/or reused. See <link
- linkend="opt.decay_time"><mallctl>opt.decay_time</mallctl></link>
- for details.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.nthreads">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.nthreads</mallctl>
- (<type>unsigned</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Number of threads currently assigned to
- arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.pactive">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.pactive</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Number of pages in active runs.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.pdirty">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.pdirty</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- </term>
- <listitem><para>Number of pages within unused runs that are potentially
- dirty, and for which <function>madvise<parameter>...</parameter>
- <parameter><constant>MADV_DONTNEED</constant></parameter></function> or
- similar has not been called.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.mapped">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.mapped</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of mapped bytes.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.retained">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.retained</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of retained bytes. See <link
- linkend="stats.retained"><mallctl>stats.retained</mallctl></link> for
- details.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.metadata.mapped">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.metadata.mapped</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of mapped bytes in arena chunk headers, which
- track the states of the non-metadata pages.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.metadata.allocated">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.metadata.allocated</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of bytes dedicated to internal allocations.
- Internal allocations differ from application-originated allocations in
- that they are for internal use, and that they are omitted from heap
- profiles. This statistic is reported separately from <link
- linkend="stats.metadata"><mallctl>stats.metadata</mallctl></link> and
- <link
- linkend="stats.arenas.i.metadata.mapped"><mallctl>stats.arenas.&lt;i&gt;.metadata.mapped</mallctl></link>
- because it overlaps with e.g. the <link
- linkend="stats.allocated"><mallctl>stats.allocated</mallctl></link> and
- <link linkend="stats.active"><mallctl>stats.active</mallctl></link>
- statistics, whereas the other metadata statistics do
- not.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.npurge">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.npurge</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of dirty page purge sweeps performed.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.nmadvise">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.nmadvise</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of <function>madvise<parameter>...</parameter>
- <parameter><constant>MADV_DONTNEED</constant></parameter></function> or
- similar calls made to purge dirty pages.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.purged">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.purged</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of pages purged.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.small.allocated">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.small.allocated</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of bytes currently allocated by small objects.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.small.nmalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.small.nmalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of allocation requests served by
- small bins.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.small.ndalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.small.ndalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of small objects returned to bins.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.small.nrequests">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.small.nrequests</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of small allocation requests.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.large.allocated">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.large.allocated</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of bytes currently allocated by large objects.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.large.nmalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.large.nmalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of large allocation requests served
- directly by the arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.large.ndalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.large.ndalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of large deallocation requests served
- directly by the arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.large.nrequests">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.large.nrequests</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of large allocation requests.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.huge.allocated">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.huge.allocated</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Number of bytes currently allocated by huge objects.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.huge.nmalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.huge.nmalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of huge allocation requests served
- directly by the arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.huge.ndalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.huge.ndalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of huge deallocation requests served
- directly by the arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.huge.nrequests">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.huge.nrequests</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of huge allocation requests.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.nmalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.nmalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of allocations served by bin.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.ndalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.ndalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of allocations returned to bin.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.nrequests">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.nrequests</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of allocation
- requests.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.curregs">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.curregs</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Current number of regions for this size
- class.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.nfills">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.nfills</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option> <option>--enable-tcache</option>]
- </term>
- <listitem><para>Cumulative number of tcache fills.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.nflushes">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.nflushes</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option> <option>--enable-tcache</option>]
- </term>
- <listitem><para>Cumulative number of tcache flushes.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.nruns">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.nruns</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of runs created.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.nreruns">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.nreruns</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of times the current run from which
- to allocate changed.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.bins.j.curruns">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.bins.&lt;j&gt;.curruns</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Current number of runs.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.lruns.j.nmalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.lruns.&lt;j&gt;.nmalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of allocation requests for this size
- class served directly by the arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.lruns.j.ndalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.lruns.&lt;j&gt;.ndalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of deallocation requests for this
- size class served directly by the arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.lruns.j.nrequests">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.lruns.&lt;j&gt;.nrequests</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of allocation requests for this size
- class.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.lruns.j.curruns">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.lruns.&lt;j&gt;.curruns</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Current number of runs for this size class.
- </para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.hchunks.j.nmalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.hchunks.&lt;j&gt;.nmalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of allocation requests for this size
- class served directly by the arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.hchunks.j.ndalloc">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.hchunks.&lt;j&gt;.ndalloc</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of deallocation requests for this
- size class served directly by the arena.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.hchunks.j.nrequests">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.hchunks.&lt;j&gt;.nrequests</mallctl>
- (<type>uint64_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Cumulative number of allocation requests for this size
- class.</para></listitem>
- </varlistentry>
-
- <varlistentry id="stats.arenas.i.hchunks.j.curhchunks">
- <term>
- <mallctl>stats.arenas.&lt;i&gt;.hchunks.&lt;j&gt;.curhchunks</mallctl>
- (<type>size_t</type>)
- <literal>r-</literal>
- [<option>--enable-stats</option>]
- </term>
- <listitem><para>Current number of huge allocations for this size class.
- </para></listitem>
- </varlistentry>
- </variablelist>
- </refsect1>
- <refsect1 id="heap_profile_format">
- <title>HEAP PROFILE FORMAT</title>
- <para>Although the heap profiling functionality was originally designed to
- be compatible with the
- <command>pprof</command> command that is developed as part of the <ulink
- url="http://code.google.com/p/gperftools/">gperftools
- package</ulink>, the addition of per thread heap profiling functionality
- required a different heap profile format. The <command>jeprof</command>
- command is derived from <command>pprof</command>, with enhancements to
- support the heap profile format described here.</para>
-
- <para>In the following hypothetical heap profile, <constant>[...]</constant>
- indicates elision for the sake of compactness. <programlisting><![CDATA[
-heap_v2/524288
- t*: 28106: 56637512 [0: 0]
- [...]
- t3: 352: 16777344 [0: 0]
- [...]
- t99: 17754: 29341640 [0: 0]
- [...]
-@ 0x5f86da8 0x5f5a1dc [...] 0x29e4d4e 0xa200316 0xabb2988 [...]
- t*: 13: 6688 [0: 0]
- t3: 12: 6496 [0: ]
- t99: 1: 192 [0: 0]
-[...]
-
-MAPPED_LIBRARIES:
-[...]]]></programlisting> The following matches the above heap profile, but most
-tokens are replaced with <constant>&lt;description&gt;</constant> to indicate
-descriptions of the corresponding fields. <programlisting><![CDATA[
-<heap_profile_format_version>/<mean_sample_interval>
- <aggregate>: <curobjs>: <curbytes> [<cumobjs>: <cumbytes>]
- [...]
- <thread_3_aggregate>: <curobjs>: <curbytes>[<cumobjs>: <cumbytes>]
- [...]
- <thread_99_aggregate>: <curobjs>: <curbytes>[<cumobjs>: <cumbytes>]
- [...]
-@ <top_frame> <frame> [...] <frame> <frame> <frame> [...]
- <backtrace_aggregate>: <curobjs>: <curbytes> [<cumobjs>: <cumbytes>]
- <backtrace_thread_3>: <curobjs>: <curbytes> [<cumobjs>: <cumbytes>]
- <backtrace_thread_99>: <curobjs>: <curbytes> [<cumobjs>: <cumbytes>]
-[...]
-
-MAPPED_LIBRARIES:
-</proc/<pid>/maps>]]></programlisting></para>
- </refsect1>
-
- <refsect1 id="debugging_malloc_problems">
- <title>DEBUGGING MALLOC PROBLEMS</title>
- <para>When debugging, it is a good idea to configure/build jemalloc with
- the <option>--enable-debug</option> and <option>--enable-fill</option>
- options, and recompile the program with suitable options and symbols for
- debugger support. When so configured, jemalloc incorporates a wide variety
- of run-time assertions that catch application errors such as double-free,
- write-after-free, etc.</para>
-
- <para>Programs often accidentally depend on <quote>uninitialized</quote>
- memory actually being filled with zero bytes. Junk filling
- (see the <link linkend="opt.junk"><mallctl>opt.junk</mallctl></link>
- option) tends to expose such bugs in the form of obviously incorrect
- results and/or coredumps. Conversely, zero
- filling (see the <link
- linkend="opt.zero"><mallctl>opt.zero</mallctl></link> option) eliminates
- the symptoms of such bugs. Between these two options, it is usually
- possible to quickly detect, diagnose, and eliminate such bugs.</para>
-
- <para>This implementation does not provide much detail about the problems
- it detects, because the performance impact for storing such information
- would be prohibitive. However, jemalloc does integrate with the most
- excellent <ulink url="http://valgrind.org/">Valgrind</ulink> tool if the
- <option>--enable-valgrind</option> configuration option is enabled.</para>
- </refsect1>
- <refsect1 id="diagnostic_messages">
- <title>DIAGNOSTIC MESSAGES</title>
- <para>If any of the memory allocation/deallocation functions detect an
- error or warning condition, a message will be printed to file descriptor
- <constant>STDERR_FILENO</constant>. Errors will result in the process
- dumping core. If the <link
- linkend="opt.abort"><mallctl>opt.abort</mallctl></link> option is set, most
- warnings are treated as errors.</para>
-
- <para>The <varname>malloc_message</varname> variable allows the programmer
- to override the function which emits the text strings forming the errors
- and warnings if for some reason the <constant>STDERR_FILENO</constant> file
- descriptor is not suitable for this.
- <function>malloc_message()</function> takes the
- <parameter>cbopaque</parameter> pointer argument that is
- <constant>NULL</constant> unless overridden by the arguments in a call to
- <function>malloc_stats_print()</function>, followed by a string
- pointer. Please note that doing anything which tries to allocate memory in
- this function is likely to result in a crash or deadlock.</para>
-
- <para>All messages are prefixed by
- <quote><computeroutput>&lt;jemalloc&gt;: </computeroutput></quote>.</para>
- </refsect1>
- <refsect1 id="return_values">
- <title>RETURN VALUES</title>
- <refsect2>
- <title>Standard API</title>
- <para>The <function>malloc()</function> and
- <function>calloc()</function> functions return a pointer to the
- allocated memory if successful; otherwise a <constant>NULL</constant>
- pointer is returned and <varname>errno</varname> is set to
- <errorname>ENOMEM</errorname>.</para>
-
- <para>The <function>posix_memalign()</function> function
- returns the value 0 if successful; otherwise it returns an error value.
- The <function>posix_memalign()</function> function will fail
- if:
- <variablelist>
- <varlistentry>
- <term><errorname>EINVAL</errorname></term>
-
- <listitem><para>The <parameter>alignment</parameter> parameter is
- not a power of 2 at least as large as
- <code language="C">sizeof(<type>void *</type>)</code>.
- </para></listitem>
- </varlistentry>
- <varlistentry>
- <term><errorname>ENOMEM</errorname></term>
-
- <listitem><para>Memory allocation error.</para></listitem>
- </varlistentry>
- </variablelist>
- </para>
-
- <para>The <function>aligned_alloc()</function> function returns
- a pointer to the allocated memory if successful; otherwise a
- <constant>NULL</constant> pointer is returned and
- <varname>errno</varname> is set. The
- <function>aligned_alloc()</function> function will fail if:
- <variablelist>
- <varlistentry>
- <term><errorname>EINVAL</errorname></term>
-
- <listitem><para>The <parameter>alignment</parameter> parameter is
- not a power of 2.
- </para></listitem>
- </varlistentry>
- <varlistentry>
- <term><errorname>ENOMEM</errorname></term>
-
- <listitem><para>Memory allocation error.</para></listitem>
- </varlistentry>
- </variablelist>
- </para>
-
- <para>The <function>realloc()</function> function returns a
- pointer, possibly identical to <parameter>ptr</parameter>, to the
- allocated memory if successful; otherwise a <constant>NULL</constant>
- pointer is returned, and <varname>errno</varname> is set to
- <errorname>ENOMEM</errorname> if the error was the result of an
- allocation failure. The <function>realloc()</function>
- function always leaves the original buffer intact when an error occurs.
- </para>
-
- <para>The <function>free()</function> function returns no
- value.</para>
- </refsect2>
- <refsect2>
- <title>Non-standard API</title>
- <para>The <function>mallocx()</function> and
- <function>rallocx()</function> functions return a pointer to
- the allocated memory if successful; otherwise a <constant>NULL</constant>
- pointer is returned to indicate insufficient contiguous memory was
- available to service the allocation request. </para>
-
- <para>The <function>xallocx()</function> function returns the
- real size of the resulting resized allocation pointed to by
- <parameter>ptr</parameter>, which is a value less than
- <parameter>size</parameter> if the allocation could not be adequately
- grown in place. </para>
-
- <para>The <function>sallocx()</function> function returns the
- real size of the allocation pointed to by <parameter>ptr</parameter>.
- </para>
-
- <para>The <function>nallocx()</function> returns the real size
- that would result from a successful equivalent
- <function>mallocx()</function> function call, or zero if
- insufficient memory is available to perform the size computation. </para>
-
- <para>The <function>mallctl()</function>,
- <function>mallctlnametomib()</function>, and
- <function>mallctlbymib()</function> functions return 0 on
- success; otherwise they return an error value. The functions will fail
- if:
- <variablelist>
- <varlistentry>
- <term><errorname>EINVAL</errorname></term>
-
- <listitem><para><parameter>newp</parameter> is not
- <constant>NULL</constant>, and <parameter>newlen</parameter> is too
- large or too small. Alternatively, <parameter>*oldlenp</parameter>
- is too large or too small; in this case as much data as possible
- are read despite the error.</para></listitem>
- </varlistentry>
- <varlistentry>
- <term><errorname>ENOENT</errorname></term>
-
- <listitem><para><parameter>name</parameter> or
- <parameter>mib</parameter> specifies an unknown/invalid
- value.</para></listitem>
- </varlistentry>
- <varlistentry>
- <term><errorname>EPERM</errorname></term>
-
- <listitem><para>Attempt to read or write void value, or attempt to
- write read-only value.</para></listitem>
- </varlistentry>
- <varlistentry>
- <term><errorname>EAGAIN</errorname></term>
-
- <listitem><para>A memory allocation failure
- occurred.</para></listitem>
- </varlistentry>
- <varlistentry>
- <term><errorname>EFAULT</errorname></term>
-
- <listitem><para>An interface with side effects failed in some way
- not directly related to <function>mallctl*()</function>
- read/write processing.</para></listitem>
- </varlistentry>
- </variablelist>
- </para>
-
- <para>The <function>malloc_usable_size()</function> function
- returns the usable size of the allocation pointed to by
- <parameter>ptr</parameter>. </para>
- </refsect2>
- </refsect1>
- <refsect1 id="environment">
- <title>ENVIRONMENT</title>
- <para>The following environment variable affects the execution of the
- allocation functions:
- <variablelist>
- <varlistentry>
- <term><envar>MALLOC_CONF</envar></term>
-
- <listitem><para>If the environment variable
- <envar>MALLOC_CONF</envar> is set, the characters it contains
- will be interpreted as options.</para></listitem>
- </varlistentry>
- </variablelist>
- </para>
- </refsect1>
- <refsect1 id="examples">
- <title>EXAMPLES</title>
- <para>To dump core whenever a problem occurs:
- <screen>ln -s 'abort:true' /etc/malloc.conf</screen>
- </para>
- <para>To specify in the source a chunk size that is 16 MiB:
- <programlisting language="C"><![CDATA[
-malloc_conf = "lg_chunk:24";]]></programlisting></para>
- </refsect1>
- <refsect1 id="see_also">
- <title>SEE ALSO</title>
- <para><citerefentry><refentrytitle>madvise</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry>,
- <citerefentry><refentrytitle>mmap</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry>,
- <citerefentry><refentrytitle>sbrk</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry>,
- <citerefentry><refentrytitle>utrace</refentrytitle>
- <manvolnum>2</manvolnum></citerefentry>,
- <citerefentry><refentrytitle>alloca</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry>,
- <citerefentry><refentrytitle>atexit</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry>,
- <citerefentry><refentrytitle>getpagesize</refentrytitle>
- <manvolnum>3</manvolnum></citerefentry></para>
- </refsect1>
- <refsect1 id="standards">
- <title>STANDARDS</title>
- <para>The <function>malloc()</function>,
- <function>calloc()</function>,
- <function>realloc()</function>, and
- <function>free()</function> functions conform to ISO/IEC
- 9899:1990 (<quote>ISO C90</quote>).</para>
-
- <para>The <function>posix_memalign()</function> function conforms
- to IEEE Std 1003.1-2001 (<quote>POSIX.1</quote>).</para>
- </refsect1>
-</refentry>
diff --git a/memory/jemalloc/src/doc/manpages.xsl.in b/memory/jemalloc/src/doc/manpages.xsl.in
deleted file mode 100644
index 88b2626b9..000000000
--- a/memory/jemalloc/src/doc/manpages.xsl.in
+++ /dev/null
@@ -1,4 +0,0 @@
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
- <xsl:import href="@XSLROOT@/manpages/docbook.xsl"/>
- <xsl:import href="@abs_srcroot@doc/stylesheet.xsl"/>
-</xsl:stylesheet>
diff --git a/memory/jemalloc/src/doc/stylesheet.xsl b/memory/jemalloc/src/doc/stylesheet.xsl
deleted file mode 100644
index 619365d82..000000000
--- a/memory/jemalloc/src/doc/stylesheet.xsl
+++ /dev/null
@@ -1,10 +0,0 @@
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
- <xsl:param name="funcsynopsis.style">ansi</xsl:param>
- <xsl:param name="function.parens" select="0"/>
- <xsl:template match="function">
- <xsl:call-template name="inline.monoseq"/>
- </xsl:template>
- <xsl:template match="mallctl">
- <quote><xsl:call-template name="inline.monoseq"/></quote>
- </xsl:template>
-</xsl:stylesheet>
diff --git a/memory/jemalloc/src/include/jemalloc/internal/arena.h b/memory/jemalloc/src/include/jemalloc/internal/arena.h
deleted file mode 100644
index f39ce54b5..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/arena.h
+++ /dev/null
@@ -1,1516 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#define LARGE_MINCLASS (ZU(1) << LG_LARGE_MINCLASS)
-
-/* Maximum number of regions in one run. */
-#define LG_RUN_MAXREGS (LG_PAGE - LG_TINY_MIN)
-#define RUN_MAXREGS (1U << LG_RUN_MAXREGS)
-
-/*
- * Minimum redzone size. Redzones may be larger than this if necessary to
- * preserve region alignment.
- */
-#define REDZONE_MINSIZE 16
-
-/*
- * The minimum ratio of active:dirty pages per arena is computed as:
- *
- * (nactive >> lg_dirty_mult) >= ndirty
- *
- * So, supposing that lg_dirty_mult is 3, there can be no less than 8 times as
- * many active pages as dirty pages.
- */
-#define LG_DIRTY_MULT_DEFAULT 3
-
-typedef enum {
- purge_mode_ratio = 0,
- purge_mode_decay = 1,
-
- purge_mode_limit = 2
-} purge_mode_t;
-#define PURGE_DEFAULT purge_mode_ratio
-/* Default decay time in seconds. */
-#define DECAY_TIME_DEFAULT 10
-/* Number of event ticks between time checks. */
-#define DECAY_NTICKS_PER_UPDATE 1000
-
-typedef struct arena_runs_dirty_link_s arena_runs_dirty_link_t;
-typedef struct arena_avail_links_s arena_avail_links_t;
-typedef struct arena_run_s arena_run_t;
-typedef struct arena_chunk_map_bits_s arena_chunk_map_bits_t;
-typedef struct arena_chunk_map_misc_s arena_chunk_map_misc_t;
-typedef struct arena_chunk_s arena_chunk_t;
-typedef struct arena_bin_info_s arena_bin_info_t;
-typedef struct arena_decay_s arena_decay_t;
-typedef struct arena_bin_s arena_bin_t;
-typedef struct arena_s arena_t;
-typedef struct arena_tdata_s arena_tdata_t;
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#ifdef JEMALLOC_ARENA_STRUCTS_A
-struct arena_run_s {
- /* Index of bin this run is associated with. */
- szind_t binind;
-
- /* Number of free regions in run. */
- unsigned nfree;
-
- /* Per region allocated/deallocated bitmap. */
- bitmap_t bitmap[BITMAP_GROUPS_MAX];
-};
-
-/* Each element of the chunk map corresponds to one page within the chunk. */
-struct arena_chunk_map_bits_s {
- /*
- * Run address (or size) and various flags are stored together. The bit
- * layout looks like (assuming 32-bit system):
- *
- * ???????? ???????? ???nnnnn nnndumla
- *
- * ? : Unallocated: Run address for first/last pages, unset for internal
- * pages.
- * Small: Run page offset.
- * Large: Run page count for first page, unset for trailing pages.
- * n : binind for small size class, BININD_INVALID for large size class.
- * d : dirty?
- * u : unzeroed?
- * m : decommitted?
- * l : large?
- * a : allocated?
- *
- * Following are example bit patterns for the three types of runs.
- *
- * p : run page offset
- * s : run size
- * n : binind for size class; large objects set these to BININD_INVALID
- * x : don't care
- * - : 0
- * + : 1
- * [DUMLA] : bit set
- * [dumla] : bit unset
- *
- * Unallocated (clean):
- * ssssssss ssssssss sss+++++ +++dum-a
- * xxxxxxxx xxxxxxxx xxxxxxxx xxx-Uxxx
- * ssssssss ssssssss sss+++++ +++dUm-a
- *
- * Unallocated (dirty):
- * ssssssss ssssssss sss+++++ +++D-m-a
- * xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
- * ssssssss ssssssss sss+++++ +++D-m-a
- *
- * Small:
- * pppppppp pppppppp pppnnnnn nnnd---A
- * pppppppp pppppppp pppnnnnn nnn----A
- * pppppppp pppppppp pppnnnnn nnnd---A
- *
- * Large:
- * ssssssss ssssssss sss+++++ +++D--LA
- * xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
- * -------- -------- ---+++++ +++D--LA
- *
- * Large (sampled, size <= LARGE_MINCLASS):
- * ssssssss ssssssss sssnnnnn nnnD--LA
- * xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
- * -------- -------- ---+++++ +++D--LA
- *
- * Large (not sampled, size == LARGE_MINCLASS):
- * ssssssss ssssssss sss+++++ +++D--LA
- * xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
- * -------- -------- ---+++++ +++D--LA
- */
- size_t bits;
-#define CHUNK_MAP_ALLOCATED ((size_t)0x01U)
-#define CHUNK_MAP_LARGE ((size_t)0x02U)
-#define CHUNK_MAP_STATE_MASK ((size_t)0x3U)
-
-#define CHUNK_MAP_DECOMMITTED ((size_t)0x04U)
-#define CHUNK_MAP_UNZEROED ((size_t)0x08U)
-#define CHUNK_MAP_DIRTY ((size_t)0x10U)
-#define CHUNK_MAP_FLAGS_MASK ((size_t)0x1cU)
-
-#define CHUNK_MAP_BININD_SHIFT 5
-#define BININD_INVALID ((size_t)0xffU)
-#define CHUNK_MAP_BININD_MASK (BININD_INVALID << CHUNK_MAP_BININD_SHIFT)
-#define CHUNK_MAP_BININD_INVALID CHUNK_MAP_BININD_MASK
-
-#define CHUNK_MAP_RUNIND_SHIFT (CHUNK_MAP_BININD_SHIFT + 8)
-#define CHUNK_MAP_SIZE_SHIFT (CHUNK_MAP_RUNIND_SHIFT - LG_PAGE)
-#define CHUNK_MAP_SIZE_MASK \
- (~(CHUNK_MAP_BININD_MASK | CHUNK_MAP_FLAGS_MASK | CHUNK_MAP_STATE_MASK))
-};
-
-struct arena_runs_dirty_link_s {
- qr(arena_runs_dirty_link_t) rd_link;
-};
-
-/*
- * Each arena_chunk_map_misc_t corresponds to one page within the chunk, just
- * like arena_chunk_map_bits_t. Two separate arrays are stored within each
- * chunk header in order to improve cache locality.
- */
-struct arena_chunk_map_misc_s {
- /*
- * Linkage for run heaps. There are two disjoint uses:
- *
- * 1) arena_t's runs_avail heaps.
- * 2) arena_run_t conceptually uses this linkage for in-use non-full
- * runs, rather than directly embedding linkage.
- */
- phn(arena_chunk_map_misc_t) ph_link;
-
- union {
- /* Linkage for list of dirty runs. */
- arena_runs_dirty_link_t rd;
-
- /* Profile counters, used for large object runs. */
- union {
- void *prof_tctx_pun;
- prof_tctx_t *prof_tctx;
- };
-
- /* Small region run metadata. */
- arena_run_t run;
- };
-};
-typedef ph(arena_chunk_map_misc_t) arena_run_heap_t;
-#endif /* JEMALLOC_ARENA_STRUCTS_A */
-
-#ifdef JEMALLOC_ARENA_STRUCTS_B
-/* Arena chunk header. */
-struct arena_chunk_s {
- /*
- * A pointer to the arena that owns the chunk is stored within the node.
- * This field as a whole is used by chunks_rtree to support both
- * ivsalloc() and core-based debugging.
- */
- extent_node_t node;
-
- /*
- * Map of pages within chunk that keeps track of free/large/small. The
- * first map_bias entries are omitted, since the chunk header does not
- * need to be tracked in the map. This omission saves a header page
- * for common chunk sizes (e.g. 4 MiB).
- */
- arena_chunk_map_bits_t map_bits[1]; /* Dynamically sized. */
-};
-
-/*
- * Read-only information associated with each element of arena_t's bins array
- * is stored separately, partly to reduce memory usage (only one copy, rather
- * than one per arena), but mainly to avoid false cacheline sharing.
- *
- * Each run has the following layout:
- *
- * /--------------------\
- * | pad? |
- * |--------------------|
- * | redzone |
- * reg0_offset | region 0 |
- * | redzone |
- * |--------------------| \
- * | redzone | |
- * | region 1 | > reg_interval
- * | redzone | /
- * |--------------------|
- * | ... |
- * | ... |
- * | ... |
- * |--------------------|
- * | redzone |
- * | region nregs-1 |
- * | redzone |
- * |--------------------|
- * | alignment pad? |
- * \--------------------/
- *
- * reg_interval has at least the same minimum alignment as reg_size; this
- * preserves the alignment constraint that sa2u() depends on. Alignment pad is
- * either 0 or redzone_size; it is present only if needed to align reg0_offset.
- */
-struct arena_bin_info_s {
- /* Size of regions in a run for this bin's size class. */
- size_t reg_size;
-
- /* Redzone size. */
- size_t redzone_size;
-
- /* Interval between regions (reg_size + (redzone_size << 1)). */
- size_t reg_interval;
-
- /* Total size of a run for this bin's size class. */
- size_t run_size;
-
- /* Total number of regions in a run for this bin's size class. */
- uint32_t nregs;
-
- /*
- * Metadata used to manipulate bitmaps for runs associated with this
- * bin.
- */
- bitmap_info_t bitmap_info;
-
- /* Offset of first region in a run for this bin's size class. */
- uint32_t reg0_offset;
-};
-
-struct arena_decay_s {
- /*
- * Approximate time in seconds from the creation of a set of unused
- * dirty pages until an equivalent set of unused dirty pages is purged
- * and/or reused.
- */
- ssize_t time;
- /* time / SMOOTHSTEP_NSTEPS. */
- nstime_t interval;
- /*
- * Time at which the current decay interval logically started. We do
- * not actually advance to a new epoch until sometime after it starts
- * because of scheduling and computation delays, and it is even possible
- * to completely skip epochs. In all cases, during epoch advancement we
- * merge all relevant activity into the most recently recorded epoch.
- */
- nstime_t epoch;
- /* Deadline randomness generator. */
- uint64_t jitter_state;
- /*
- * Deadline for current epoch. This is the sum of interval and per
- * epoch jitter which is a uniform random variable in [0..interval).
- * Epochs always advance by precise multiples of interval, but we
- * randomize the deadline to reduce the likelihood of arenas purging in
- * lockstep.
- */
- nstime_t deadline;
- /*
- * Number of dirty pages at beginning of current epoch. During epoch
- * advancement we use the delta between arena->decay.ndirty and
- * arena->ndirty to determine how many dirty pages, if any, were
- * generated.
- */
- size_t ndirty;
- /*
- * Trailing log of how many unused dirty pages were generated during
- * each of the past SMOOTHSTEP_NSTEPS decay epochs, where the last
- * element is the most recent epoch. Corresponding epoch times are
- * relative to epoch.
- */
- size_t backlog[SMOOTHSTEP_NSTEPS];
-};
-
-struct arena_bin_s {
- /*
- * All operations on runcur, runs, and stats require that lock be
- * locked. Run allocation/deallocation are protected by the arena lock,
- * which may be acquired while holding one or more bin locks, but not
- * vise versa.
- */
- malloc_mutex_t lock;
-
- /*
- * Current run being used to service allocations of this bin's size
- * class.
- */
- arena_run_t *runcur;
-
- /*
- * Heap of non-full runs. This heap is used when looking for an
- * existing run when runcur is no longer usable. We choose the
- * non-full run that is lowest in memory; this policy tends to keep
- * objects packed well, and it can also help reduce the number of
- * almost-empty chunks.
- */
- arena_run_heap_t runs;
-
- /* Bin statistics. */
- malloc_bin_stats_t stats;
-};
-
-struct arena_s {
- /* This arena's index within the arenas array. */
- unsigned ind;
-
- /*
- * Number of threads currently assigned to this arena, synchronized via
- * atomic operations. Each thread has two distinct assignments, one for
- * application-serving allocation, and the other for internal metadata
- * allocation. Internal metadata must not be allocated from arenas
- * created via the arenas.extend mallctl, because the arena.<i>.reset
- * mallctl indiscriminately discards all allocations for the affected
- * arena.
- *
- * 0: Application allocation.
- * 1: Internal metadata allocation.
- */
- unsigned nthreads[2];
-
- /*
- * There are three classes of arena operations from a locking
- * perspective:
- * 1) Thread assignment (modifies nthreads) is synchronized via atomics.
- * 2) Bin-related operations are protected by bin locks.
- * 3) Chunk- and run-related operations are protected by this mutex.
- */
- malloc_mutex_t lock;
-
- arena_stats_t stats;
- /*
- * List of tcaches for extant threads associated with this arena.
- * Stats from these are merged incrementally, and at exit if
- * opt_stats_print is enabled.
- */
- ql_head(tcache_t) tcache_ql;
-
- uint64_t prof_accumbytes;
-
- /*
- * PRNG state for cache index randomization of large allocation base
- * pointers.
- */
- size_t offset_state;
-
- dss_prec_t dss_prec;
-
-
- /* Extant arena chunks. */
- ql_head(extent_node_t) achunks;
-
- /*
- * In order to avoid rapid chunk allocation/deallocation when an arena
- * oscillates right on the cusp of needing a new chunk, cache the most
- * recently freed chunk. The spare is left in the arena's chunk trees
- * until it is deleted.
- *
- * There is one spare chunk per arena, rather than one spare total, in
- * order to avoid interactions between multiple threads that could make
- * a single spare inadequate.
- */
- arena_chunk_t *spare;
-
- /* Minimum ratio (log base 2) of nactive:ndirty. */
- ssize_t lg_dirty_mult;
-
- /* True if a thread is currently executing arena_purge_to_limit(). */
- bool purging;
-
- /* Number of pages in active runs and huge regions. */
- size_t nactive;
-
- /*
- * Current count of pages within unused runs that are potentially
- * dirty, and for which madvise(... MADV_DONTNEED) has not been called.
- * By tracking this, we can institute a limit on how much dirty unused
- * memory is mapped for each arena.
- */
- size_t ndirty;
-
- /*
- * Unused dirty memory this arena manages. Dirty memory is conceptually
- * tracked as an arbitrarily interleaved LRU of dirty runs and cached
- * chunks, but the list linkage is actually semi-duplicated in order to
- * avoid extra arena_chunk_map_misc_t space overhead.
- *
- * LRU-----------------------------------------------------------MRU
- *
- * /-- arena ---\
- * | |
- * | |
- * |------------| /- chunk -\
- * ...->|chunks_cache|<--------------------------->| /----\ |<--...
- * |------------| | |node| |
- * | | | | | |
- * | | /- run -\ /- run -\ | | | |
- * | | | | | | | | | |
- * | | | | | | | | | |
- * |------------| |-------| |-------| | |----| |
- * ...->|runs_dirty |<-->|rd |<-->|rd |<---->|rd |<----...
- * |------------| |-------| |-------| | |----| |
- * | | | | | | | | | |
- * | | | | | | | \----/ |
- * | | \-------/ \-------/ | |
- * | | | |
- * | | | |
- * \------------/ \---------/
- */
- arena_runs_dirty_link_t runs_dirty;
- extent_node_t chunks_cache;
-
- /* Decay-based purging state. */
- arena_decay_t decay;
-
- /* Extant huge allocations. */
- ql_head(extent_node_t) huge;
- /* Synchronizes all huge allocation/update/deallocation. */
- malloc_mutex_t huge_mtx;
-
- /*
- * Trees of chunks that were previously allocated (trees differ only in
- * node ordering). These are used when allocating chunks, in an attempt
- * to re-use address space. Depending on function, different tree
- * orderings are needed, which is why there are two trees with the same
- * contents.
- */
- extent_tree_t chunks_szad_cached;
- extent_tree_t chunks_ad_cached;
- extent_tree_t chunks_szad_retained;
- extent_tree_t chunks_ad_retained;
-
- malloc_mutex_t chunks_mtx;
- /* Cache of nodes that were allocated via base_alloc(). */
- ql_head(extent_node_t) node_cache;
- malloc_mutex_t node_cache_mtx;
-
- /* User-configurable chunk hook functions. */
- chunk_hooks_t chunk_hooks;
-
- /* bins is used to store trees of free regions. */
- arena_bin_t bins[NBINS];
-
- /*
- * Size-segregated address-ordered heaps of this arena's available runs,
- * used for first-best-fit run allocation. Runs are quantized, i.e.
- * they reside in the last heap which corresponds to a size class less
- * than or equal to the run size.
- */
- arena_run_heap_t runs_avail[NPSIZES];
-};
-
-/* Used in conjunction with tsd for fast arena-related context lookup. */
-struct arena_tdata_s {
- ticker_t decay_ticker;
-};
-#endif /* JEMALLOC_ARENA_STRUCTS_B */
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-static const size_t large_pad =
-#ifdef JEMALLOC_CACHE_OBLIVIOUS
- PAGE
-#else
- 0
-#endif
- ;
-
-extern purge_mode_t opt_purge;
-extern const char *purge_mode_names[];
-extern ssize_t opt_lg_dirty_mult;
-extern ssize_t opt_decay_time;
-
-extern arena_bin_info_t arena_bin_info[NBINS];
-
-extern size_t map_bias; /* Number of arena chunk header pages. */
-extern size_t map_misc_offset;
-extern size_t arena_maxrun; /* Max run size for arenas. */
-extern size_t large_maxclass; /* Max large size class. */
-extern unsigned nlclasses; /* Number of large size classes. */
-extern unsigned nhclasses; /* Number of huge size classes. */
-
-#ifdef JEMALLOC_JET
-typedef size_t (run_quantize_t)(size_t);
-extern run_quantize_t *run_quantize_floor;
-extern run_quantize_t *run_quantize_ceil;
-#endif
-void arena_chunk_cache_maybe_insert(arena_t *arena, extent_node_t *node,
- bool cache);
-void arena_chunk_cache_maybe_remove(arena_t *arena, extent_node_t *node,
- bool cache);
-extent_node_t *arena_node_alloc(tsdn_t *tsdn, arena_t *arena);
-void arena_node_dalloc(tsdn_t *tsdn, arena_t *arena, extent_node_t *node);
-void *arena_chunk_alloc_huge(tsdn_t *tsdn, arena_t *arena, size_t usize,
- size_t alignment, bool *zero);
-void arena_chunk_dalloc_huge(tsdn_t *tsdn, arena_t *arena, void *chunk,
- size_t usize);
-void arena_chunk_ralloc_huge_similar(tsdn_t *tsdn, arena_t *arena,
- void *chunk, size_t oldsize, size_t usize);
-void arena_chunk_ralloc_huge_shrink(tsdn_t *tsdn, arena_t *arena,
- void *chunk, size_t oldsize, size_t usize);
-bool arena_chunk_ralloc_huge_expand(tsdn_t *tsdn, arena_t *arena,
- void *chunk, size_t oldsize, size_t usize, bool *zero);
-ssize_t arena_lg_dirty_mult_get(tsdn_t *tsdn, arena_t *arena);
-bool arena_lg_dirty_mult_set(tsdn_t *tsdn, arena_t *arena,
- ssize_t lg_dirty_mult);
-ssize_t arena_decay_time_get(tsdn_t *tsdn, arena_t *arena);
-bool arena_decay_time_set(tsdn_t *tsdn, arena_t *arena, ssize_t decay_time);
-void arena_purge(tsdn_t *tsdn, arena_t *arena, bool all);
-void arena_maybe_purge(tsdn_t *tsdn, arena_t *arena);
-void arena_reset(tsd_t *tsd, arena_t *arena);
-void arena_tcache_fill_small(tsdn_t *tsdn, arena_t *arena,
- tcache_bin_t *tbin, szind_t binind, uint64_t prof_accumbytes);
-void arena_alloc_junk_small(void *ptr, arena_bin_info_t *bin_info,
- bool zero);
-#ifdef JEMALLOC_JET
-typedef void (arena_redzone_corruption_t)(void *, size_t, bool, size_t,
- uint8_t);
-extern arena_redzone_corruption_t *arena_redzone_corruption;
-typedef void (arena_dalloc_junk_small_t)(void *, arena_bin_info_t *);
-extern arena_dalloc_junk_small_t *arena_dalloc_junk_small;
-#else
-void arena_dalloc_junk_small(void *ptr, arena_bin_info_t *bin_info);
-#endif
-void arena_quarantine_junk_small(void *ptr, size_t usize);
-void *arena_malloc_large(tsdn_t *tsdn, arena_t *arena, szind_t ind,
- bool zero);
-void *arena_malloc_hard(tsdn_t *tsdn, arena_t *arena, size_t size,
- szind_t ind, bool zero);
-void *arena_palloc(tsdn_t *tsdn, arena_t *arena, size_t usize,
- size_t alignment, bool zero, tcache_t *tcache);
-void arena_prof_promoted(tsdn_t *tsdn, const void *ptr, size_t size);
-void arena_dalloc_bin_junked_locked(tsdn_t *tsdn, arena_t *arena,
- arena_chunk_t *chunk, void *ptr, arena_chunk_map_bits_t *bitselm);
-void arena_dalloc_bin(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- void *ptr, size_t pageind, arena_chunk_map_bits_t *bitselm);
-void arena_dalloc_small(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- void *ptr, size_t pageind);
-#ifdef JEMALLOC_JET
-typedef void (arena_dalloc_junk_large_t)(void *, size_t);
-extern arena_dalloc_junk_large_t *arena_dalloc_junk_large;
-#else
-void arena_dalloc_junk_large(void *ptr, size_t usize);
-#endif
-void arena_dalloc_large_junked_locked(tsdn_t *tsdn, arena_t *arena,
- arena_chunk_t *chunk, void *ptr);
-void arena_dalloc_large(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- void *ptr);
-#ifdef JEMALLOC_JET
-typedef void (arena_ralloc_junk_large_t)(void *, size_t, size_t);
-extern arena_ralloc_junk_large_t *arena_ralloc_junk_large;
-#endif
-bool arena_ralloc_no_move(tsdn_t *tsdn, void *ptr, size_t oldsize,
- size_t size, size_t extra, bool zero);
-void *arena_ralloc(tsd_t *tsd, arena_t *arena, void *ptr, size_t oldsize,
- size_t size, size_t alignment, bool zero, tcache_t *tcache);
-dss_prec_t arena_dss_prec_get(tsdn_t *tsdn, arena_t *arena);
-bool arena_dss_prec_set(tsdn_t *tsdn, arena_t *arena, dss_prec_t dss_prec);
-ssize_t arena_lg_dirty_mult_default_get(void);
-bool arena_lg_dirty_mult_default_set(ssize_t lg_dirty_mult);
-ssize_t arena_decay_time_default_get(void);
-bool arena_decay_time_default_set(ssize_t decay_time);
-void arena_basic_stats_merge(tsdn_t *tsdn, arena_t *arena,
- unsigned *nthreads, const char **dss, ssize_t *lg_dirty_mult,
- ssize_t *decay_time, size_t *nactive, size_t *ndirty);
-void arena_stats_merge(tsdn_t *tsdn, arena_t *arena, unsigned *nthreads,
- const char **dss, ssize_t *lg_dirty_mult, ssize_t *decay_time,
- size_t *nactive, size_t *ndirty, arena_stats_t *astats,
- malloc_bin_stats_t *bstats, malloc_large_stats_t *lstats,
- malloc_huge_stats_t *hstats);
-unsigned arena_nthreads_get(arena_t *arena, bool internal);
-void arena_nthreads_inc(arena_t *arena, bool internal);
-void arena_nthreads_dec(arena_t *arena, bool internal);
-arena_t *arena_new(tsdn_t *tsdn, unsigned ind);
-void arena_boot(void);
-void arena_prefork0(tsdn_t *tsdn, arena_t *arena);
-void arena_prefork1(tsdn_t *tsdn, arena_t *arena);
-void arena_prefork2(tsdn_t *tsdn, arena_t *arena);
-void arena_prefork3(tsdn_t *tsdn, arena_t *arena);
-void arena_postfork_parent(tsdn_t *tsdn, arena_t *arena);
-void arena_postfork_child(tsdn_t *tsdn, arena_t *arena);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-arena_chunk_map_bits_t *arena_bitselm_get_mutable(arena_chunk_t *chunk,
- size_t pageind);
-const arena_chunk_map_bits_t *arena_bitselm_get_const(
- const arena_chunk_t *chunk, size_t pageind);
-arena_chunk_map_misc_t *arena_miscelm_get_mutable(arena_chunk_t *chunk,
- size_t pageind);
-const arena_chunk_map_misc_t *arena_miscelm_get_const(
- const arena_chunk_t *chunk, size_t pageind);
-size_t arena_miscelm_to_pageind(const arena_chunk_map_misc_t *miscelm);
-void *arena_miscelm_to_rpages(const arena_chunk_map_misc_t *miscelm);
-arena_chunk_map_misc_t *arena_rd_to_miscelm(arena_runs_dirty_link_t *rd);
-arena_chunk_map_misc_t *arena_run_to_miscelm(arena_run_t *run);
-size_t *arena_mapbitsp_get_mutable(arena_chunk_t *chunk, size_t pageind);
-const size_t *arena_mapbitsp_get_const(const arena_chunk_t *chunk,
- size_t pageind);
-size_t arena_mapbitsp_read(const size_t *mapbitsp);
-size_t arena_mapbits_get(const arena_chunk_t *chunk, size_t pageind);
-size_t arena_mapbits_size_decode(size_t mapbits);
-size_t arena_mapbits_unallocated_size_get(const arena_chunk_t *chunk,
- size_t pageind);
-size_t arena_mapbits_large_size_get(const arena_chunk_t *chunk,
- size_t pageind);
-size_t arena_mapbits_small_runind_get(const arena_chunk_t *chunk,
- size_t pageind);
-szind_t arena_mapbits_binind_get(const arena_chunk_t *chunk, size_t pageind);
-size_t arena_mapbits_dirty_get(const arena_chunk_t *chunk, size_t pageind);
-size_t arena_mapbits_unzeroed_get(const arena_chunk_t *chunk, size_t pageind);
-size_t arena_mapbits_decommitted_get(const arena_chunk_t *chunk,
- size_t pageind);
-size_t arena_mapbits_large_get(const arena_chunk_t *chunk, size_t pageind);
-size_t arena_mapbits_allocated_get(const arena_chunk_t *chunk, size_t pageind);
-void arena_mapbitsp_write(size_t *mapbitsp, size_t mapbits);
-size_t arena_mapbits_size_encode(size_t size);
-void arena_mapbits_unallocated_set(arena_chunk_t *chunk, size_t pageind,
- size_t size, size_t flags);
-void arena_mapbits_unallocated_size_set(arena_chunk_t *chunk, size_t pageind,
- size_t size);
-void arena_mapbits_internal_set(arena_chunk_t *chunk, size_t pageind,
- size_t flags);
-void arena_mapbits_large_set(arena_chunk_t *chunk, size_t pageind,
- size_t size, size_t flags);
-void arena_mapbits_large_binind_set(arena_chunk_t *chunk, size_t pageind,
- szind_t binind);
-void arena_mapbits_small_set(arena_chunk_t *chunk, size_t pageind,
- size_t runind, szind_t binind, size_t flags);
-void arena_metadata_allocated_add(arena_t *arena, size_t size);
-void arena_metadata_allocated_sub(arena_t *arena, size_t size);
-size_t arena_metadata_allocated_get(arena_t *arena);
-bool arena_prof_accum_impl(arena_t *arena, uint64_t accumbytes);
-bool arena_prof_accum_locked(arena_t *arena, uint64_t accumbytes);
-bool arena_prof_accum(tsdn_t *tsdn, arena_t *arena, uint64_t accumbytes);
-szind_t arena_ptr_small_binind_get(const void *ptr, size_t mapbits);
-szind_t arena_bin_index(arena_t *arena, arena_bin_t *bin);
-size_t arena_run_regind(arena_run_t *run, arena_bin_info_t *bin_info,
- const void *ptr);
-prof_tctx_t *arena_prof_tctx_get(tsdn_t *tsdn, const void *ptr);
-void arena_prof_tctx_set(tsdn_t *tsdn, const void *ptr, size_t usize,
- prof_tctx_t *tctx);
-void arena_prof_tctx_reset(tsdn_t *tsdn, const void *ptr, size_t usize,
- const void *old_ptr, prof_tctx_t *old_tctx);
-void arena_decay_ticks(tsdn_t *tsdn, arena_t *arena, unsigned nticks);
-void arena_decay_tick(tsdn_t *tsdn, arena_t *arena);
-void *arena_malloc(tsdn_t *tsdn, arena_t *arena, size_t size, szind_t ind,
- bool zero, tcache_t *tcache, bool slow_path);
-arena_t *arena_aalloc(const void *ptr);
-size_t arena_salloc(tsdn_t *tsdn, const void *ptr, bool demote);
-void arena_dalloc(tsdn_t *tsdn, void *ptr, tcache_t *tcache, bool slow_path);
-void arena_sdalloc(tsdn_t *tsdn, void *ptr, size_t size, tcache_t *tcache,
- bool slow_path);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_ARENA_C_))
-# ifdef JEMALLOC_ARENA_INLINE_A
-JEMALLOC_ALWAYS_INLINE arena_chunk_map_bits_t *
-arena_bitselm_get_mutable(arena_chunk_t *chunk, size_t pageind)
-{
-
- assert(pageind >= map_bias);
- assert(pageind < chunk_npages);
-
- return (&chunk->map_bits[pageind-map_bias]);
-}
-
-JEMALLOC_ALWAYS_INLINE const arena_chunk_map_bits_t *
-arena_bitselm_get_const(const arena_chunk_t *chunk, size_t pageind)
-{
-
- return (arena_bitselm_get_mutable((arena_chunk_t *)chunk, pageind));
-}
-
-JEMALLOC_ALWAYS_INLINE arena_chunk_map_misc_t *
-arena_miscelm_get_mutable(arena_chunk_t *chunk, size_t pageind)
-{
-
- assert(pageind >= map_bias);
- assert(pageind < chunk_npages);
-
- return ((arena_chunk_map_misc_t *)((uintptr_t)chunk +
- (uintptr_t)map_misc_offset) + pageind-map_bias);
-}
-
-JEMALLOC_ALWAYS_INLINE const arena_chunk_map_misc_t *
-arena_miscelm_get_const(const arena_chunk_t *chunk, size_t pageind)
-{
-
- return (arena_miscelm_get_mutable((arena_chunk_t *)chunk, pageind));
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_miscelm_to_pageind(const arena_chunk_map_misc_t *miscelm)
-{
- arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(miscelm);
- size_t pageind = ((uintptr_t)miscelm - ((uintptr_t)chunk +
- map_misc_offset)) / sizeof(arena_chunk_map_misc_t) + map_bias;
-
- assert(pageind >= map_bias);
- assert(pageind < chunk_npages);
-
- return (pageind);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-arena_miscelm_to_rpages(const arena_chunk_map_misc_t *miscelm)
-{
- arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(miscelm);
- size_t pageind = arena_miscelm_to_pageind(miscelm);
-
- return ((void *)((uintptr_t)chunk + (pageind << LG_PAGE)));
-}
-
-JEMALLOC_ALWAYS_INLINE arena_chunk_map_misc_t *
-arena_rd_to_miscelm(arena_runs_dirty_link_t *rd)
-{
- arena_chunk_map_misc_t *miscelm = (arena_chunk_map_misc_t
- *)((uintptr_t)rd - offsetof(arena_chunk_map_misc_t, rd));
-
- assert(arena_miscelm_to_pageind(miscelm) >= map_bias);
- assert(arena_miscelm_to_pageind(miscelm) < chunk_npages);
-
- return (miscelm);
-}
-
-JEMALLOC_ALWAYS_INLINE arena_chunk_map_misc_t *
-arena_run_to_miscelm(arena_run_t *run)
-{
- arena_chunk_map_misc_t *miscelm = (arena_chunk_map_misc_t
- *)((uintptr_t)run - offsetof(arena_chunk_map_misc_t, run));
-
- assert(arena_miscelm_to_pageind(miscelm) >= map_bias);
- assert(arena_miscelm_to_pageind(miscelm) < chunk_npages);
-
- return (miscelm);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t *
-arena_mapbitsp_get_mutable(arena_chunk_t *chunk, size_t pageind)
-{
-
- return (&arena_bitselm_get_mutable(chunk, pageind)->bits);
-}
-
-JEMALLOC_ALWAYS_INLINE const size_t *
-arena_mapbitsp_get_const(const arena_chunk_t *chunk, size_t pageind)
-{
-
- return (arena_mapbitsp_get_mutable((arena_chunk_t *)chunk, pageind));
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbitsp_read(const size_t *mapbitsp)
-{
-
- return (*mapbitsp);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_get(const arena_chunk_t *chunk, size_t pageind)
-{
-
- return (arena_mapbitsp_read(arena_mapbitsp_get_const(chunk, pageind)));
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_size_decode(size_t mapbits)
-{
- size_t size;
-
-#if CHUNK_MAP_SIZE_SHIFT > 0
- size = (mapbits & CHUNK_MAP_SIZE_MASK) >> CHUNK_MAP_SIZE_SHIFT;
-#elif CHUNK_MAP_SIZE_SHIFT == 0
- size = mapbits & CHUNK_MAP_SIZE_MASK;
-#else
- size = (mapbits & CHUNK_MAP_SIZE_MASK) << -CHUNK_MAP_SIZE_SHIFT;
-#endif
-
- return (size);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_unallocated_size_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- assert((mapbits & (CHUNK_MAP_LARGE|CHUNK_MAP_ALLOCATED)) == 0);
- return (arena_mapbits_size_decode(mapbits));
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_large_size_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- assert((mapbits & (CHUNK_MAP_LARGE|CHUNK_MAP_ALLOCATED)) ==
- (CHUNK_MAP_LARGE|CHUNK_MAP_ALLOCATED));
- return (arena_mapbits_size_decode(mapbits));
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_small_runind_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- assert((mapbits & (CHUNK_MAP_LARGE|CHUNK_MAP_ALLOCATED)) ==
- CHUNK_MAP_ALLOCATED);
- return (mapbits >> CHUNK_MAP_RUNIND_SHIFT);
-}
-
-JEMALLOC_ALWAYS_INLINE szind_t
-arena_mapbits_binind_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
- szind_t binind;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- binind = (mapbits & CHUNK_MAP_BININD_MASK) >> CHUNK_MAP_BININD_SHIFT;
- assert(binind < NBINS || binind == BININD_INVALID);
- return (binind);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_dirty_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- assert((mapbits & CHUNK_MAP_DECOMMITTED) == 0 || (mapbits &
- (CHUNK_MAP_DIRTY|CHUNK_MAP_UNZEROED)) == 0);
- return (mapbits & CHUNK_MAP_DIRTY);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_unzeroed_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- assert((mapbits & CHUNK_MAP_DECOMMITTED) == 0 || (mapbits &
- (CHUNK_MAP_DIRTY|CHUNK_MAP_UNZEROED)) == 0);
- return (mapbits & CHUNK_MAP_UNZEROED);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_decommitted_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- assert((mapbits & CHUNK_MAP_DECOMMITTED) == 0 || (mapbits &
- (CHUNK_MAP_DIRTY|CHUNK_MAP_UNZEROED)) == 0);
- return (mapbits & CHUNK_MAP_DECOMMITTED);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_large_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- return (mapbits & CHUNK_MAP_LARGE);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_allocated_get(const arena_chunk_t *chunk, size_t pageind)
-{
- size_t mapbits;
-
- mapbits = arena_mapbits_get(chunk, pageind);
- return (mapbits & CHUNK_MAP_ALLOCATED);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_mapbitsp_write(size_t *mapbitsp, size_t mapbits)
-{
-
- *mapbitsp = mapbits;
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-arena_mapbits_size_encode(size_t size)
-{
- size_t mapbits;
-
-#if CHUNK_MAP_SIZE_SHIFT > 0
- mapbits = size << CHUNK_MAP_SIZE_SHIFT;
-#elif CHUNK_MAP_SIZE_SHIFT == 0
- mapbits = size;
-#else
- mapbits = size >> -CHUNK_MAP_SIZE_SHIFT;
-#endif
-
- assert((mapbits & ~CHUNK_MAP_SIZE_MASK) == 0);
- return (mapbits);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_mapbits_unallocated_set(arena_chunk_t *chunk, size_t pageind, size_t size,
- size_t flags)
-{
- size_t *mapbitsp = arena_mapbitsp_get_mutable(chunk, pageind);
-
- assert((size & PAGE_MASK) == 0);
- assert((flags & CHUNK_MAP_FLAGS_MASK) == flags);
- assert((flags & CHUNK_MAP_DECOMMITTED) == 0 || (flags &
- (CHUNK_MAP_DIRTY|CHUNK_MAP_UNZEROED)) == 0);
- arena_mapbitsp_write(mapbitsp, arena_mapbits_size_encode(size) |
- CHUNK_MAP_BININD_INVALID | flags);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_mapbits_unallocated_size_set(arena_chunk_t *chunk, size_t pageind,
- size_t size)
-{
- size_t *mapbitsp = arena_mapbitsp_get_mutable(chunk, pageind);
- size_t mapbits = arena_mapbitsp_read(mapbitsp);
-
- assert((size & PAGE_MASK) == 0);
- assert((mapbits & (CHUNK_MAP_LARGE|CHUNK_MAP_ALLOCATED)) == 0);
- arena_mapbitsp_write(mapbitsp, arena_mapbits_size_encode(size) |
- (mapbits & ~CHUNK_MAP_SIZE_MASK));
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_mapbits_internal_set(arena_chunk_t *chunk, size_t pageind, size_t flags)
-{
- size_t *mapbitsp = arena_mapbitsp_get_mutable(chunk, pageind);
-
- assert((flags & CHUNK_MAP_UNZEROED) == flags);
- arena_mapbitsp_write(mapbitsp, flags);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_mapbits_large_set(arena_chunk_t *chunk, size_t pageind, size_t size,
- size_t flags)
-{
- size_t *mapbitsp = arena_mapbitsp_get_mutable(chunk, pageind);
-
- assert((size & PAGE_MASK) == 0);
- assert((flags & CHUNK_MAP_FLAGS_MASK) == flags);
- assert((flags & CHUNK_MAP_DECOMMITTED) == 0 || (flags &
- (CHUNK_MAP_DIRTY|CHUNK_MAP_UNZEROED)) == 0);
- arena_mapbitsp_write(mapbitsp, arena_mapbits_size_encode(size) |
- CHUNK_MAP_BININD_INVALID | flags | CHUNK_MAP_LARGE |
- CHUNK_MAP_ALLOCATED);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_mapbits_large_binind_set(arena_chunk_t *chunk, size_t pageind,
- szind_t binind)
-{
- size_t *mapbitsp = arena_mapbitsp_get_mutable(chunk, pageind);
- size_t mapbits = arena_mapbitsp_read(mapbitsp);
-
- assert(binind <= BININD_INVALID);
- assert(arena_mapbits_large_size_get(chunk, pageind) == LARGE_MINCLASS +
- large_pad);
- arena_mapbitsp_write(mapbitsp, (mapbits & ~CHUNK_MAP_BININD_MASK) |
- (binind << CHUNK_MAP_BININD_SHIFT));
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_mapbits_small_set(arena_chunk_t *chunk, size_t pageind, size_t runind,
- szind_t binind, size_t flags)
-{
- size_t *mapbitsp = arena_mapbitsp_get_mutable(chunk, pageind);
-
- assert(binind < BININD_INVALID);
- assert(pageind - runind >= map_bias);
- assert((flags & CHUNK_MAP_UNZEROED) == flags);
- arena_mapbitsp_write(mapbitsp, (runind << CHUNK_MAP_RUNIND_SHIFT) |
- (binind << CHUNK_MAP_BININD_SHIFT) | flags | CHUNK_MAP_ALLOCATED);
-}
-
-JEMALLOC_INLINE void
-arena_metadata_allocated_add(arena_t *arena, size_t size)
-{
-
- atomic_add_z(&arena->stats.metadata_allocated, size);
-}
-
-JEMALLOC_INLINE void
-arena_metadata_allocated_sub(arena_t *arena, size_t size)
-{
-
- atomic_sub_z(&arena->stats.metadata_allocated, size);
-}
-
-JEMALLOC_INLINE size_t
-arena_metadata_allocated_get(arena_t *arena)
-{
-
- return (atomic_read_z(&arena->stats.metadata_allocated));
-}
-
-JEMALLOC_INLINE bool
-arena_prof_accum_impl(arena_t *arena, uint64_t accumbytes)
-{
-
- cassert(config_prof);
- assert(prof_interval != 0);
-
- arena->prof_accumbytes += accumbytes;
- if (arena->prof_accumbytes >= prof_interval) {
- arena->prof_accumbytes -= prof_interval;
- return (true);
- }
- return (false);
-}
-
-JEMALLOC_INLINE bool
-arena_prof_accum_locked(arena_t *arena, uint64_t accumbytes)
-{
-
- cassert(config_prof);
-
- if (likely(prof_interval == 0))
- return (false);
- return (arena_prof_accum_impl(arena, accumbytes));
-}
-
-JEMALLOC_INLINE bool
-arena_prof_accum(tsdn_t *tsdn, arena_t *arena, uint64_t accumbytes)
-{
-
- cassert(config_prof);
-
- if (likely(prof_interval == 0))
- return (false);
-
- {
- bool ret;
-
- malloc_mutex_lock(tsdn, &arena->lock);
- ret = arena_prof_accum_impl(arena, accumbytes);
- malloc_mutex_unlock(tsdn, &arena->lock);
- return (ret);
- }
-}
-
-JEMALLOC_ALWAYS_INLINE szind_t
-arena_ptr_small_binind_get(const void *ptr, size_t mapbits)
-{
- szind_t binind;
-
- binind = (mapbits & CHUNK_MAP_BININD_MASK) >> CHUNK_MAP_BININD_SHIFT;
-
- if (config_debug) {
- arena_chunk_t *chunk;
- arena_t *arena;
- size_t pageind;
- size_t actual_mapbits;
- size_t rpages_ind;
- const arena_run_t *run;
- arena_bin_t *bin;
- szind_t run_binind, actual_binind;
- arena_bin_info_t *bin_info;
- const arena_chunk_map_misc_t *miscelm;
- const void *rpages;
-
- assert(binind != BININD_INVALID);
- assert(binind < NBINS);
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- arena = extent_node_arena_get(&chunk->node);
- pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- actual_mapbits = arena_mapbits_get(chunk, pageind);
- assert(mapbits == actual_mapbits);
- assert(arena_mapbits_large_get(chunk, pageind) == 0);
- assert(arena_mapbits_allocated_get(chunk, pageind) != 0);
- rpages_ind = pageind - arena_mapbits_small_runind_get(chunk,
- pageind);
- miscelm = arena_miscelm_get_const(chunk, rpages_ind);
- run = &miscelm->run;
- run_binind = run->binind;
- bin = &arena->bins[run_binind];
- actual_binind = (szind_t)(bin - arena->bins);
- assert(run_binind == actual_binind);
- bin_info = &arena_bin_info[actual_binind];
- rpages = arena_miscelm_to_rpages(miscelm);
- assert(((uintptr_t)ptr - ((uintptr_t)rpages +
- (uintptr_t)bin_info->reg0_offset)) % bin_info->reg_interval
- == 0);
- }
-
- return (binind);
-}
-# endif /* JEMALLOC_ARENA_INLINE_A */
-
-# ifdef JEMALLOC_ARENA_INLINE_B
-JEMALLOC_INLINE szind_t
-arena_bin_index(arena_t *arena, arena_bin_t *bin)
-{
- szind_t binind = (szind_t)(bin - arena->bins);
- assert(binind < NBINS);
- return (binind);
-}
-
-JEMALLOC_INLINE size_t
-arena_run_regind(arena_run_t *run, arena_bin_info_t *bin_info, const void *ptr)
-{
- size_t diff, interval, shift, regind;
- arena_chunk_map_misc_t *miscelm = arena_run_to_miscelm(run);
- void *rpages = arena_miscelm_to_rpages(miscelm);
-
- /*
- * Freeing a pointer lower than region zero can cause assertion
- * failure.
- */
- assert((uintptr_t)ptr >= (uintptr_t)rpages +
- (uintptr_t)bin_info->reg0_offset);
-
- /*
- * Avoid doing division with a variable divisor if possible. Using
- * actual division here can reduce allocator throughput by over 20%!
- */
- diff = (size_t)((uintptr_t)ptr - (uintptr_t)rpages -
- bin_info->reg0_offset);
-
- /* Rescale (factor powers of 2 out of the numerator and denominator). */
- interval = bin_info->reg_interval;
- shift = ffs_zu(interval) - 1;
- diff >>= shift;
- interval >>= shift;
-
- if (interval == 1) {
- /* The divisor was a power of 2. */
- regind = diff;
- } else {
- /*
- * To divide by a number D that is not a power of two we
- * multiply by (2^21 / D) and then right shift by 21 positions.
- *
- * X / D
- *
- * becomes
- *
- * (X * interval_invs[D - 3]) >> SIZE_INV_SHIFT
- *
- * We can omit the first three elements, because we never
- * divide by 0, and 1 and 2 are both powers of two, which are
- * handled above.
- */
-#define SIZE_INV_SHIFT ((sizeof(size_t) << 3) - LG_RUN_MAXREGS)
-#define SIZE_INV(s) (((ZU(1) << SIZE_INV_SHIFT) / (s)) + 1)
- static const size_t interval_invs[] = {
- SIZE_INV(3),
- SIZE_INV(4), SIZE_INV(5), SIZE_INV(6), SIZE_INV(7),
- SIZE_INV(8), SIZE_INV(9), SIZE_INV(10), SIZE_INV(11),
- SIZE_INV(12), SIZE_INV(13), SIZE_INV(14), SIZE_INV(15),
- SIZE_INV(16), SIZE_INV(17), SIZE_INV(18), SIZE_INV(19),
- SIZE_INV(20), SIZE_INV(21), SIZE_INV(22), SIZE_INV(23),
- SIZE_INV(24), SIZE_INV(25), SIZE_INV(26), SIZE_INV(27),
- SIZE_INV(28), SIZE_INV(29), SIZE_INV(30), SIZE_INV(31)
- };
-
- if (likely(interval <= ((sizeof(interval_invs) / sizeof(size_t))
- + 2))) {
- regind = (diff * interval_invs[interval - 3]) >>
- SIZE_INV_SHIFT;
- } else
- regind = diff / interval;
-#undef SIZE_INV
-#undef SIZE_INV_SHIFT
- }
- assert(diff == regind * interval);
- assert(regind < bin_info->nregs);
-
- return (regind);
-}
-
-JEMALLOC_INLINE prof_tctx_t *
-arena_prof_tctx_get(tsdn_t *tsdn, const void *ptr)
-{
- prof_tctx_t *ret;
- arena_chunk_t *chunk;
-
- cassert(config_prof);
- assert(ptr != NULL);
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (likely(chunk != ptr)) {
- size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- size_t mapbits = arena_mapbits_get(chunk, pageind);
- assert((mapbits & CHUNK_MAP_ALLOCATED) != 0);
- if (likely((mapbits & CHUNK_MAP_LARGE) == 0))
- ret = (prof_tctx_t *)(uintptr_t)1U;
- else {
- arena_chunk_map_misc_t *elm =
- arena_miscelm_get_mutable(chunk, pageind);
- ret = atomic_read_p(&elm->prof_tctx_pun);
- }
- } else
- ret = huge_prof_tctx_get(tsdn, ptr);
-
- return (ret);
-}
-
-JEMALLOC_INLINE void
-arena_prof_tctx_set(tsdn_t *tsdn, const void *ptr, size_t usize,
- prof_tctx_t *tctx)
-{
- arena_chunk_t *chunk;
-
- cassert(config_prof);
- assert(ptr != NULL);
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (likely(chunk != ptr)) {
- size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
-
- assert(arena_mapbits_allocated_get(chunk, pageind) != 0);
-
- if (unlikely(usize > SMALL_MAXCLASS || (uintptr_t)tctx >
- (uintptr_t)1U)) {
- arena_chunk_map_misc_t *elm;
-
- assert(arena_mapbits_large_get(chunk, pageind) != 0);
-
- elm = arena_miscelm_get_mutable(chunk, pageind);
- atomic_write_p(&elm->prof_tctx_pun, tctx);
- } else {
- /*
- * tctx must always be initialized for large runs.
- * Assert that the surrounding conditional logic is
- * equivalent to checking whether ptr refers to a large
- * run.
- */
- assert(arena_mapbits_large_get(chunk, pageind) == 0);
- }
- } else
- huge_prof_tctx_set(tsdn, ptr, tctx);
-}
-
-JEMALLOC_INLINE void
-arena_prof_tctx_reset(tsdn_t *tsdn, const void *ptr, size_t usize,
- const void *old_ptr, prof_tctx_t *old_tctx)
-{
-
- cassert(config_prof);
- assert(ptr != NULL);
-
- if (unlikely(usize > SMALL_MAXCLASS || (ptr == old_ptr &&
- (uintptr_t)old_tctx > (uintptr_t)1U))) {
- arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (likely(chunk != ptr)) {
- size_t pageind;
- arena_chunk_map_misc_t *elm;
-
- pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >>
- LG_PAGE;
- assert(arena_mapbits_allocated_get(chunk, pageind) !=
- 0);
- assert(arena_mapbits_large_get(chunk, pageind) != 0);
-
- elm = arena_miscelm_get_mutable(chunk, pageind);
- atomic_write_p(&elm->prof_tctx_pun,
- (prof_tctx_t *)(uintptr_t)1U);
- } else
- huge_prof_tctx_reset(tsdn, ptr);
- }
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_decay_ticks(tsdn_t *tsdn, arena_t *arena, unsigned nticks)
-{
- tsd_t *tsd;
- ticker_t *decay_ticker;
-
- if (unlikely(tsdn_null(tsdn)))
- return;
- tsd = tsdn_tsd(tsdn);
- decay_ticker = decay_ticker_get(tsd, arena->ind);
- if (unlikely(decay_ticker == NULL))
- return;
- if (unlikely(ticker_ticks(decay_ticker, nticks)))
- arena_purge(tsdn, arena, false);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_decay_tick(tsdn_t *tsdn, arena_t *arena)
-{
-
- arena_decay_ticks(tsdn, arena, 1);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-arena_malloc(tsdn_t *tsdn, arena_t *arena, size_t size, szind_t ind, bool zero,
- tcache_t *tcache, bool slow_path)
-{
-
- assert(!tsdn_null(tsdn) || tcache == NULL);
- assert(size != 0);
-
- if (likely(tcache != NULL)) {
- if (likely(size <= SMALL_MAXCLASS)) {
- return (tcache_alloc_small(tsdn_tsd(tsdn), arena,
- tcache, size, ind, zero, slow_path));
- }
- if (likely(size <= tcache_maxclass)) {
- return (tcache_alloc_large(tsdn_tsd(tsdn), arena,
- tcache, size, ind, zero, slow_path));
- }
- /* (size > tcache_maxclass) case falls through. */
- assert(size > tcache_maxclass);
- }
-
- return (arena_malloc_hard(tsdn, arena, size, ind, zero));
-}
-
-JEMALLOC_ALWAYS_INLINE arena_t *
-arena_aalloc(const void *ptr)
-{
- arena_chunk_t *chunk;
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (likely(chunk != ptr))
- return (extent_node_arena_get(&chunk->node));
- else
- return (huge_aalloc(ptr));
-}
-
-/* Return the size of the allocation pointed to by ptr. */
-JEMALLOC_ALWAYS_INLINE size_t
-arena_salloc(tsdn_t *tsdn, const void *ptr, bool demote)
-{
- size_t ret;
- arena_chunk_t *chunk;
- size_t pageind;
- szind_t binind;
-
- assert(ptr != NULL);
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (likely(chunk != ptr)) {
- pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- assert(arena_mapbits_allocated_get(chunk, pageind) != 0);
- binind = arena_mapbits_binind_get(chunk, pageind);
- if (unlikely(binind == BININD_INVALID || (config_prof && !demote
- && arena_mapbits_large_get(chunk, pageind) != 0))) {
- /*
- * Large allocation. In the common case (demote), and
- * as this is an inline function, most callers will only
- * end up looking at binind to determine that ptr is a
- * small allocation.
- */
- assert(config_cache_oblivious || ((uintptr_t)ptr &
- PAGE_MASK) == 0);
- ret = arena_mapbits_large_size_get(chunk, pageind) -
- large_pad;
- assert(ret != 0);
- assert(pageind + ((ret+large_pad)>>LG_PAGE) <=
- chunk_npages);
- assert(arena_mapbits_dirty_get(chunk, pageind) ==
- arena_mapbits_dirty_get(chunk,
- pageind+((ret+large_pad)>>LG_PAGE)-1));
- } else {
- /*
- * Small allocation (possibly promoted to a large
- * object).
- */
- assert(arena_mapbits_large_get(chunk, pageind) != 0 ||
- arena_ptr_small_binind_get(ptr,
- arena_mapbits_get(chunk, pageind)) == binind);
- ret = index2size(binind);
- }
- } else
- ret = huge_salloc(tsdn, ptr);
-
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_dalloc(tsdn_t *tsdn, void *ptr, tcache_t *tcache, bool slow_path)
-{
- arena_chunk_t *chunk;
- size_t pageind, mapbits;
-
- assert(!tsdn_null(tsdn) || tcache == NULL);
- assert(ptr != NULL);
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (likely(chunk != ptr)) {
- pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- mapbits = arena_mapbits_get(chunk, pageind);
- assert(arena_mapbits_allocated_get(chunk, pageind) != 0);
- if (likely((mapbits & CHUNK_MAP_LARGE) == 0)) {
- /* Small allocation. */
- if (likely(tcache != NULL)) {
- szind_t binind = arena_ptr_small_binind_get(ptr,
- mapbits);
- tcache_dalloc_small(tsdn_tsd(tsdn), tcache, ptr,
- binind, slow_path);
- } else {
- arena_dalloc_small(tsdn,
- extent_node_arena_get(&chunk->node), chunk,
- ptr, pageind);
- }
- } else {
- size_t size = arena_mapbits_large_size_get(chunk,
- pageind);
-
- assert(config_cache_oblivious || ((uintptr_t)ptr &
- PAGE_MASK) == 0);
-
- if (likely(tcache != NULL) && size - large_pad <=
- tcache_maxclass) {
- tcache_dalloc_large(tsdn_tsd(tsdn), tcache, ptr,
- size - large_pad, slow_path);
- } else {
- arena_dalloc_large(tsdn,
- extent_node_arena_get(&chunk->node), chunk,
- ptr);
- }
- }
- } else
- huge_dalloc(tsdn, ptr);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-arena_sdalloc(tsdn_t *tsdn, void *ptr, size_t size, tcache_t *tcache,
- bool slow_path)
-{
- arena_chunk_t *chunk;
-
- assert(!tsdn_null(tsdn) || tcache == NULL);
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (likely(chunk != ptr)) {
- if (config_prof && opt_prof) {
- size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >>
- LG_PAGE;
- assert(arena_mapbits_allocated_get(chunk, pageind) !=
- 0);
- if (arena_mapbits_large_get(chunk, pageind) != 0) {
- /*
- * Make sure to use promoted size, not request
- * size.
- */
- size = arena_mapbits_large_size_get(chunk,
- pageind) - large_pad;
- }
- }
- assert(s2u(size) == s2u(arena_salloc(tsdn, ptr, false)));
-
- if (likely(size <= SMALL_MAXCLASS)) {
- /* Small allocation. */
- if (likely(tcache != NULL)) {
- szind_t binind = size2index(size);
- tcache_dalloc_small(tsdn_tsd(tsdn), tcache, ptr,
- binind, slow_path);
- } else {
- size_t pageind = ((uintptr_t)ptr -
- (uintptr_t)chunk) >> LG_PAGE;
- arena_dalloc_small(tsdn,
- extent_node_arena_get(&chunk->node), chunk,
- ptr, pageind);
- }
- } else {
- assert(config_cache_oblivious || ((uintptr_t)ptr &
- PAGE_MASK) == 0);
-
- if (likely(tcache != NULL) && size <= tcache_maxclass) {
- tcache_dalloc_large(tsdn_tsd(tsdn), tcache, ptr,
- size, slow_path);
- } else {
- arena_dalloc_large(tsdn,
- extent_node_arena_get(&chunk->node), chunk,
- ptr);
- }
- }
- } else
- huge_dalloc(tsdn, ptr);
-}
-# endif /* JEMALLOC_ARENA_INLINE_B */
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/assert.h b/memory/jemalloc/src/include/jemalloc/internal/assert.h
deleted file mode 100644
index 6f8f7eb93..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/assert.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Define a custom assert() in order to reduce the chances of deadlock during
- * assertion failure.
- */
-#ifndef assert
-#define assert(e) do { \
- if (unlikely(config_debug && !(e))) { \
- malloc_printf( \
- "<jemalloc>: %s:%d: Failed assertion: \"%s\"\n", \
- __FILE__, __LINE__, #e); \
- abort(); \
- } \
-} while (0)
-#endif
-
-#ifndef not_reached
-#define not_reached() do { \
- if (config_debug) { \
- malloc_printf( \
- "<jemalloc>: %s:%d: Unreachable code reached\n", \
- __FILE__, __LINE__); \
- abort(); \
- } \
- unreachable(); \
-} while (0)
-#endif
-
-#ifndef not_implemented
-#define not_implemented() do { \
- if (config_debug) { \
- malloc_printf("<jemalloc>: %s:%d: Not implemented\n", \
- __FILE__, __LINE__); \
- abort(); \
- } \
-} while (0)
-#endif
-
-#ifndef assert_not_implemented
-#define assert_not_implemented(e) do { \
- if (unlikely(config_debug && !(e))) \
- not_implemented(); \
-} while (0)
-#endif
-
-
diff --git a/memory/jemalloc/src/include/jemalloc/internal/atomic.h b/memory/jemalloc/src/include/jemalloc/internal/atomic.h
deleted file mode 100644
index 3f15ea149..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/atomic.h
+++ /dev/null
@@ -1,651 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-#define atomic_read_uint64(p) atomic_add_uint64(p, 0)
-#define atomic_read_uint32(p) atomic_add_uint32(p, 0)
-#define atomic_read_p(p) atomic_add_p(p, NULL)
-#define atomic_read_z(p) atomic_add_z(p, 0)
-#define atomic_read_u(p) atomic_add_u(p, 0)
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-/*
- * All arithmetic functions return the arithmetic result of the atomic
- * operation. Some atomic operation APIs return the value prior to mutation, in
- * which case the following functions must redundantly compute the result so
- * that it can be returned. These functions are normally inlined, so the extra
- * operations can be optimized away if the return values aren't used by the
- * callers.
- *
- * <t> atomic_read_<t>(<t> *p) { return (*p); }
- * <t> atomic_add_<t>(<t> *p, <t> x) { return (*p += x); }
- * <t> atomic_sub_<t>(<t> *p, <t> x) { return (*p -= x); }
- * bool atomic_cas_<t>(<t> *p, <t> c, <t> s)
- * {
- * if (*p != c)
- * return (true);
- * *p = s;
- * return (false);
- * }
- * void atomic_write_<t>(<t> *p, <t> x) { *p = x; }
- */
-
-#ifndef JEMALLOC_ENABLE_INLINE
-uint64_t atomic_add_uint64(uint64_t *p, uint64_t x);
-uint64_t atomic_sub_uint64(uint64_t *p, uint64_t x);
-bool atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s);
-void atomic_write_uint64(uint64_t *p, uint64_t x);
-uint32_t atomic_add_uint32(uint32_t *p, uint32_t x);
-uint32_t atomic_sub_uint32(uint32_t *p, uint32_t x);
-bool atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s);
-void atomic_write_uint32(uint32_t *p, uint32_t x);
-void *atomic_add_p(void **p, void *x);
-void *atomic_sub_p(void **p, void *x);
-bool atomic_cas_p(void **p, void *c, void *s);
-void atomic_write_p(void **p, const void *x);
-size_t atomic_add_z(size_t *p, size_t x);
-size_t atomic_sub_z(size_t *p, size_t x);
-bool atomic_cas_z(size_t *p, size_t c, size_t s);
-void atomic_write_z(size_t *p, size_t x);
-unsigned atomic_add_u(unsigned *p, unsigned x);
-unsigned atomic_sub_u(unsigned *p, unsigned x);
-bool atomic_cas_u(unsigned *p, unsigned c, unsigned s);
-void atomic_write_u(unsigned *p, unsigned x);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_ATOMIC_C_))
-/******************************************************************************/
-/* 64-bit operations. */
-#if (LG_SIZEOF_PTR == 3 || LG_SIZEOF_INT == 3)
-# if (defined(__amd64__) || defined(__x86_64__))
-JEMALLOC_INLINE uint64_t
-atomic_add_uint64(uint64_t *p, uint64_t x)
-{
- uint64_t t = x;
-
- asm volatile (
- "lock; xaddq %0, %1;"
- : "+r" (t), "=m" (*p) /* Outputs. */
- : "m" (*p) /* Inputs. */
- );
-
- return (t + x);
-}
-
-JEMALLOC_INLINE uint64_t
-atomic_sub_uint64(uint64_t *p, uint64_t x)
-{
- uint64_t t;
-
- x = (uint64_t)(-(int64_t)x);
- t = x;
- asm volatile (
- "lock; xaddq %0, %1;"
- : "+r" (t), "=m" (*p) /* Outputs. */
- : "m" (*p) /* Inputs. */
- );
-
- return (t + x);
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
-{
- uint8_t success;
-
- asm volatile (
- "lock; cmpxchgq %4, %0;"
- "sete %1;"
- : "=m" (*p), "=a" (success) /* Outputs. */
- : "m" (*p), "a" (c), "r" (s) /* Inputs. */
- : "memory" /* Clobbers. */
- );
-
- return (!(bool)success);
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint64(uint64_t *p, uint64_t x)
-{
-
- asm volatile (
- "xchgq %1, %0;" /* Lock is implied by xchgq. */
- : "=m" (*p), "+r" (x) /* Outputs. */
- : "m" (*p) /* Inputs. */
- : "memory" /* Clobbers. */
- );
-}
-# elif (defined(JEMALLOC_C11ATOMICS))
-JEMALLOC_INLINE uint64_t
-atomic_add_uint64(uint64_t *p, uint64_t x)
-{
- volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
- return (atomic_fetch_add(a, x) + x);
-}
-
-JEMALLOC_INLINE uint64_t
-atomic_sub_uint64(uint64_t *p, uint64_t x)
-{
- volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
- return (atomic_fetch_sub(a, x) - x);
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
-{
- volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
- return (!atomic_compare_exchange_strong(a, &c, s));
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint64(uint64_t *p, uint64_t x)
-{
- volatile atomic_uint_least64_t *a = (volatile atomic_uint_least64_t *)p;
- atomic_store(a, x);
-}
-# elif (defined(JEMALLOC_ATOMIC9))
-JEMALLOC_INLINE uint64_t
-atomic_add_uint64(uint64_t *p, uint64_t x)
-{
-
- /*
- * atomic_fetchadd_64() doesn't exist, but we only ever use this
- * function on LP64 systems, so atomic_fetchadd_long() will do.
- */
- assert(sizeof(uint64_t) == sizeof(unsigned long));
-
- return (atomic_fetchadd_long(p, (unsigned long)x) + x);
-}
-
-JEMALLOC_INLINE uint64_t
-atomic_sub_uint64(uint64_t *p, uint64_t x)
-{
-
- assert(sizeof(uint64_t) == sizeof(unsigned long));
-
- return (atomic_fetchadd_long(p, (unsigned long)(-(long)x)) - x);
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
-{
-
- assert(sizeof(uint64_t) == sizeof(unsigned long));
-
- return (!atomic_cmpset_long(p, (unsigned long)c, (unsigned long)s));
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint64(uint64_t *p, uint64_t x)
-{
-
- assert(sizeof(uint64_t) == sizeof(unsigned long));
-
- atomic_store_rel_long(p, x);
-}
-# elif (defined(JEMALLOC_OSATOMIC))
-JEMALLOC_INLINE uint64_t
-atomic_add_uint64(uint64_t *p, uint64_t x)
-{
-
- return (OSAtomicAdd64((int64_t)x, (int64_t *)p));
-}
-
-JEMALLOC_INLINE uint64_t
-atomic_sub_uint64(uint64_t *p, uint64_t x)
-{
-
- return (OSAtomicAdd64(-((int64_t)x), (int64_t *)p));
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
-{
-
- return (!OSAtomicCompareAndSwap64(c, s, (int64_t *)p));
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint64(uint64_t *p, uint64_t x)
-{
- uint64_t o;
-
- /*The documented OSAtomic*() API does not expose an atomic exchange. */
- do {
- o = atomic_read_uint64(p);
- } while (atomic_cas_uint64(p, o, x));
-}
-# elif (defined(_MSC_VER))
-JEMALLOC_INLINE uint64_t
-atomic_add_uint64(uint64_t *p, uint64_t x)
-{
-
- return (InterlockedExchangeAdd64(p, x) + x);
-}
-
-JEMALLOC_INLINE uint64_t
-atomic_sub_uint64(uint64_t *p, uint64_t x)
-{
-
- return (InterlockedExchangeAdd64(p, -((int64_t)x)) - x);
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
-{
- uint64_t o;
-
- o = InterlockedCompareExchange64(p, s, c);
- return (o != c);
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint64(uint64_t *p, uint64_t x)
-{
-
- InterlockedExchange64(p, x);
-}
-# elif (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) || \
- defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_8))
-JEMALLOC_INLINE uint64_t
-atomic_add_uint64(uint64_t *p, uint64_t x)
-{
-
- return (__sync_add_and_fetch(p, x));
-}
-
-JEMALLOC_INLINE uint64_t
-atomic_sub_uint64(uint64_t *p, uint64_t x)
-{
-
- return (__sync_sub_and_fetch(p, x));
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint64(uint64_t *p, uint64_t c, uint64_t s)
-{
-
- return (!__sync_bool_compare_and_swap(p, c, s));
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint64(uint64_t *p, uint64_t x)
-{
-
- __sync_lock_test_and_set(p, x);
-}
-# else
-# error "Missing implementation for 64-bit atomic operations"
-# endif
-#endif
-
-/******************************************************************************/
-/* 32-bit operations. */
-#if (defined(__i386__) || defined(__amd64__) || defined(__x86_64__))
-JEMALLOC_INLINE uint32_t
-atomic_add_uint32(uint32_t *p, uint32_t x)
-{
- uint32_t t = x;
-
- asm volatile (
- "lock; xaddl %0, %1;"
- : "+r" (t), "=m" (*p) /* Outputs. */
- : "m" (*p) /* Inputs. */
- );
-
- return (t + x);
-}
-
-JEMALLOC_INLINE uint32_t
-atomic_sub_uint32(uint32_t *p, uint32_t x)
-{
- uint32_t t;
-
- x = (uint32_t)(-(int32_t)x);
- t = x;
- asm volatile (
- "lock; xaddl %0, %1;"
- : "+r" (t), "=m" (*p) /* Outputs. */
- : "m" (*p) /* Inputs. */
- );
-
- return (t + x);
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
-{
- uint8_t success;
-
- asm volatile (
- "lock; cmpxchgl %4, %0;"
- "sete %1;"
- : "=m" (*p), "=a" (success) /* Outputs. */
- : "m" (*p), "a" (c), "r" (s) /* Inputs. */
- : "memory"
- );
-
- return (!(bool)success);
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint32(uint32_t *p, uint32_t x)
-{
-
- asm volatile (
- "xchgl %1, %0;" /* Lock is implied by xchgl. */
- : "=m" (*p), "+r" (x) /* Outputs. */
- : "m" (*p) /* Inputs. */
- : "memory" /* Clobbers. */
- );
-}
-# elif (defined(JEMALLOC_C11ATOMICS))
-JEMALLOC_INLINE uint32_t
-atomic_add_uint32(uint32_t *p, uint32_t x)
-{
- volatile atomic_uint_least32_t *a = (volatile atomic_uint_least32_t *)p;
- return (atomic_fetch_add(a, x) + x);
-}
-
-JEMALLOC_INLINE uint32_t
-atomic_sub_uint32(uint32_t *p, uint32_t x)
-{
- volatile atomic_uint_least32_t *a = (volatile atomic_uint_least32_t *)p;
- return (atomic_fetch_sub(a, x) - x);
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
-{
- volatile atomic_uint_least32_t *a = (volatile atomic_uint_least32_t *)p;
- return (!atomic_compare_exchange_strong(a, &c, s));
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint32(uint32_t *p, uint32_t x)
-{
- volatile atomic_uint_least32_t *a = (volatile atomic_uint_least32_t *)p;
- atomic_store(a, x);
-}
-#elif (defined(JEMALLOC_ATOMIC9))
-JEMALLOC_INLINE uint32_t
-atomic_add_uint32(uint32_t *p, uint32_t x)
-{
-
- return (atomic_fetchadd_32(p, x) + x);
-}
-
-JEMALLOC_INLINE uint32_t
-atomic_sub_uint32(uint32_t *p, uint32_t x)
-{
-
- return (atomic_fetchadd_32(p, (uint32_t)(-(int32_t)x)) - x);
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
-{
-
- return (!atomic_cmpset_32(p, c, s));
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint32(uint32_t *p, uint32_t x)
-{
-
- atomic_store_rel_32(p, x);
-}
-#elif (defined(JEMALLOC_OSATOMIC))
-JEMALLOC_INLINE uint32_t
-atomic_add_uint32(uint32_t *p, uint32_t x)
-{
-
- return (OSAtomicAdd32((int32_t)x, (int32_t *)p));
-}
-
-JEMALLOC_INLINE uint32_t
-atomic_sub_uint32(uint32_t *p, uint32_t x)
-{
-
- return (OSAtomicAdd32(-((int32_t)x), (int32_t *)p));
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
-{
-
- return (!OSAtomicCompareAndSwap32(c, s, (int32_t *)p));
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint32(uint32_t *p, uint32_t x)
-{
- uint32_t o;
-
- /*The documented OSAtomic*() API does not expose an atomic exchange. */
- do {
- o = atomic_read_uint32(p);
- } while (atomic_cas_uint32(p, o, x));
-}
-#elif (defined(_MSC_VER))
-JEMALLOC_INLINE uint32_t
-atomic_add_uint32(uint32_t *p, uint32_t x)
-{
-
- return (InterlockedExchangeAdd(p, x) + x);
-}
-
-JEMALLOC_INLINE uint32_t
-atomic_sub_uint32(uint32_t *p, uint32_t x)
-{
-
- return (InterlockedExchangeAdd(p, -((int32_t)x)) - x);
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
-{
- uint32_t o;
-
- o = InterlockedCompareExchange(p, s, c);
- return (o != c);
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint32(uint32_t *p, uint32_t x)
-{
-
- InterlockedExchange(p, x);
-}
-#elif (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) || \
- defined(JE_FORCE_SYNC_COMPARE_AND_SWAP_4))
-JEMALLOC_INLINE uint32_t
-atomic_add_uint32(uint32_t *p, uint32_t x)
-{
-
- return (__sync_add_and_fetch(p, x));
-}
-
-JEMALLOC_INLINE uint32_t
-atomic_sub_uint32(uint32_t *p, uint32_t x)
-{
-
- return (__sync_sub_and_fetch(p, x));
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_uint32(uint32_t *p, uint32_t c, uint32_t s)
-{
-
- return (!__sync_bool_compare_and_swap(p, c, s));
-}
-
-JEMALLOC_INLINE void
-atomic_write_uint32(uint32_t *p, uint32_t x)
-{
-
- __sync_lock_test_and_set(p, x);
-}
-#else
-# error "Missing implementation for 32-bit atomic operations"
-#endif
-
-/******************************************************************************/
-/* Pointer operations. */
-JEMALLOC_INLINE void *
-atomic_add_p(void **p, void *x)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- return ((void *)atomic_add_uint64((uint64_t *)p, (uint64_t)x));
-#elif (LG_SIZEOF_PTR == 2)
- return ((void *)atomic_add_uint32((uint32_t *)p, (uint32_t)x));
-#endif
-}
-
-JEMALLOC_INLINE void *
-atomic_sub_p(void **p, void *x)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- return ((void *)atomic_add_uint64((uint64_t *)p,
- (uint64_t)-((int64_t)x)));
-#elif (LG_SIZEOF_PTR == 2)
- return ((void *)atomic_add_uint32((uint32_t *)p,
- (uint32_t)-((int32_t)x)));
-#endif
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_p(void **p, void *c, void *s)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- return (atomic_cas_uint64((uint64_t *)p, (uint64_t)c, (uint64_t)s));
-#elif (LG_SIZEOF_PTR == 2)
- return (atomic_cas_uint32((uint32_t *)p, (uint32_t)c, (uint32_t)s));
-#endif
-}
-
-JEMALLOC_INLINE void
-atomic_write_p(void **p, const void *x)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- atomic_write_uint64((uint64_t *)p, (uint64_t)x);
-#elif (LG_SIZEOF_PTR == 2)
- atomic_write_uint32((uint32_t *)p, (uint32_t)x);
-#endif
-}
-
-/******************************************************************************/
-/* size_t operations. */
-JEMALLOC_INLINE size_t
-atomic_add_z(size_t *p, size_t x)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- return ((size_t)atomic_add_uint64((uint64_t *)p, (uint64_t)x));
-#elif (LG_SIZEOF_PTR == 2)
- return ((size_t)atomic_add_uint32((uint32_t *)p, (uint32_t)x));
-#endif
-}
-
-JEMALLOC_INLINE size_t
-atomic_sub_z(size_t *p, size_t x)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- return ((size_t)atomic_add_uint64((uint64_t *)p,
- (uint64_t)-((int64_t)x)));
-#elif (LG_SIZEOF_PTR == 2)
- return ((size_t)atomic_add_uint32((uint32_t *)p,
- (uint32_t)-((int32_t)x)));
-#endif
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_z(size_t *p, size_t c, size_t s)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- return (atomic_cas_uint64((uint64_t *)p, (uint64_t)c, (uint64_t)s));
-#elif (LG_SIZEOF_PTR == 2)
- return (atomic_cas_uint32((uint32_t *)p, (uint32_t)c, (uint32_t)s));
-#endif
-}
-
-JEMALLOC_INLINE void
-atomic_write_z(size_t *p, size_t x)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- atomic_write_uint64((uint64_t *)p, (uint64_t)x);
-#elif (LG_SIZEOF_PTR == 2)
- atomic_write_uint32((uint32_t *)p, (uint32_t)x);
-#endif
-}
-
-/******************************************************************************/
-/* unsigned operations. */
-JEMALLOC_INLINE unsigned
-atomic_add_u(unsigned *p, unsigned x)
-{
-
-#if (LG_SIZEOF_INT == 3)
- return ((unsigned)atomic_add_uint64((uint64_t *)p, (uint64_t)x));
-#elif (LG_SIZEOF_INT == 2)
- return ((unsigned)atomic_add_uint32((uint32_t *)p, (uint32_t)x));
-#endif
-}
-
-JEMALLOC_INLINE unsigned
-atomic_sub_u(unsigned *p, unsigned x)
-{
-
-#if (LG_SIZEOF_INT == 3)
- return ((unsigned)atomic_add_uint64((uint64_t *)p,
- (uint64_t)-((int64_t)x)));
-#elif (LG_SIZEOF_INT == 2)
- return ((unsigned)atomic_add_uint32((uint32_t *)p,
- (uint32_t)-((int32_t)x)));
-#endif
-}
-
-JEMALLOC_INLINE bool
-atomic_cas_u(unsigned *p, unsigned c, unsigned s)
-{
-
-#if (LG_SIZEOF_INT == 3)
- return (atomic_cas_uint64((uint64_t *)p, (uint64_t)c, (uint64_t)s));
-#elif (LG_SIZEOF_INT == 2)
- return (atomic_cas_uint32((uint32_t *)p, (uint32_t)c, (uint32_t)s));
-#endif
-}
-
-JEMALLOC_INLINE void
-atomic_write_u(unsigned *p, unsigned x)
-{
-
-#if (LG_SIZEOF_INT == 3)
- atomic_write_uint64((uint64_t *)p, (uint64_t)x);
-#elif (LG_SIZEOF_INT == 2)
- atomic_write_uint32((uint32_t *)p, (uint32_t)x);
-#endif
-}
-
-/******************************************************************************/
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/base.h b/memory/jemalloc/src/include/jemalloc/internal/base.h
deleted file mode 100644
index d6b81e162..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/base.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void *base_alloc(tsdn_t *tsdn, size_t size);
-void base_stats_get(tsdn_t *tsdn, size_t *allocated, size_t *resident,
- size_t *mapped);
-bool base_boot(void);
-void base_prefork(tsdn_t *tsdn);
-void base_postfork_parent(tsdn_t *tsdn);
-void base_postfork_child(tsdn_t *tsdn);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/bitmap.h b/memory/jemalloc/src/include/jemalloc/internal/bitmap.h
deleted file mode 100644
index 36f38b59c..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/bitmap.h
+++ /dev/null
@@ -1,274 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-/* Maximum bitmap bit count is 2^LG_BITMAP_MAXBITS. */
-#define LG_BITMAP_MAXBITS LG_RUN_MAXREGS
-#define BITMAP_MAXBITS (ZU(1) << LG_BITMAP_MAXBITS)
-
-typedef struct bitmap_level_s bitmap_level_t;
-typedef struct bitmap_info_s bitmap_info_t;
-typedef unsigned long bitmap_t;
-#define LG_SIZEOF_BITMAP LG_SIZEOF_LONG
-
-/* Number of bits per group. */
-#define LG_BITMAP_GROUP_NBITS (LG_SIZEOF_BITMAP + 3)
-#define BITMAP_GROUP_NBITS (ZU(1) << LG_BITMAP_GROUP_NBITS)
-#define BITMAP_GROUP_NBITS_MASK (BITMAP_GROUP_NBITS-1)
-
-/*
- * Do some analysis on how big the bitmap is before we use a tree. For a brute
- * force linear search, if we would have to call ffs_lu() more than 2^3 times,
- * use a tree instead.
- */
-#if LG_BITMAP_MAXBITS - LG_BITMAP_GROUP_NBITS > 3
-# define USE_TREE
-#endif
-
-/* Number of groups required to store a given number of bits. */
-#define BITMAP_BITS2GROUPS(nbits) \
- ((nbits + BITMAP_GROUP_NBITS_MASK) >> LG_BITMAP_GROUP_NBITS)
-
-/*
- * Number of groups required at a particular level for a given number of bits.
- */
-#define BITMAP_GROUPS_L0(nbits) \
- BITMAP_BITS2GROUPS(nbits)
-#define BITMAP_GROUPS_L1(nbits) \
- BITMAP_BITS2GROUPS(BITMAP_BITS2GROUPS(nbits))
-#define BITMAP_GROUPS_L2(nbits) \
- BITMAP_BITS2GROUPS(BITMAP_BITS2GROUPS(BITMAP_BITS2GROUPS((nbits))))
-#define BITMAP_GROUPS_L3(nbits) \
- BITMAP_BITS2GROUPS(BITMAP_BITS2GROUPS(BITMAP_BITS2GROUPS( \
- BITMAP_BITS2GROUPS((nbits)))))
-
-/*
- * Assuming the number of levels, number of groups required for a given number
- * of bits.
- */
-#define BITMAP_GROUPS_1_LEVEL(nbits) \
- BITMAP_GROUPS_L0(nbits)
-#define BITMAP_GROUPS_2_LEVEL(nbits) \
- (BITMAP_GROUPS_1_LEVEL(nbits) + BITMAP_GROUPS_L1(nbits))
-#define BITMAP_GROUPS_3_LEVEL(nbits) \
- (BITMAP_GROUPS_2_LEVEL(nbits) + BITMAP_GROUPS_L2(nbits))
-#define BITMAP_GROUPS_4_LEVEL(nbits) \
- (BITMAP_GROUPS_3_LEVEL(nbits) + BITMAP_GROUPS_L3(nbits))
-
-/*
- * Maximum number of groups required to support LG_BITMAP_MAXBITS.
- */
-#ifdef USE_TREE
-
-#if LG_BITMAP_MAXBITS <= LG_BITMAP_GROUP_NBITS
-# define BITMAP_GROUPS_MAX BITMAP_GROUPS_1_LEVEL(BITMAP_MAXBITS)
-#elif LG_BITMAP_MAXBITS <= LG_BITMAP_GROUP_NBITS * 2
-# define BITMAP_GROUPS_MAX BITMAP_GROUPS_2_LEVEL(BITMAP_MAXBITS)
-#elif LG_BITMAP_MAXBITS <= LG_BITMAP_GROUP_NBITS * 3
-# define BITMAP_GROUPS_MAX BITMAP_GROUPS_3_LEVEL(BITMAP_MAXBITS)
-#elif LG_BITMAP_MAXBITS <= LG_BITMAP_GROUP_NBITS * 4
-# define BITMAP_GROUPS_MAX BITMAP_GROUPS_4_LEVEL(BITMAP_MAXBITS)
-#else
-# error "Unsupported bitmap size"
-#endif
-
-/* Maximum number of levels possible. */
-#define BITMAP_MAX_LEVELS \
- (LG_BITMAP_MAXBITS / LG_SIZEOF_BITMAP) \
- + !!(LG_BITMAP_MAXBITS % LG_SIZEOF_BITMAP)
-
-#else /* USE_TREE */
-
-#define BITMAP_GROUPS_MAX BITMAP_BITS2GROUPS(BITMAP_MAXBITS)
-
-#endif /* USE_TREE */
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct bitmap_level_s {
- /* Offset of this level's groups within the array of groups. */
- size_t group_offset;
-};
-
-struct bitmap_info_s {
- /* Logical number of bits in bitmap (stored at bottom level). */
- size_t nbits;
-
-#ifdef USE_TREE
- /* Number of levels necessary for nbits. */
- unsigned nlevels;
-
- /*
- * Only the first (nlevels+1) elements are used, and levels are ordered
- * bottom to top (e.g. the bottom level is stored in levels[0]).
- */
- bitmap_level_t levels[BITMAP_MAX_LEVELS+1];
-#else /* USE_TREE */
- /* Number of groups necessary for nbits. */
- size_t ngroups;
-#endif /* USE_TREE */
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void bitmap_info_init(bitmap_info_t *binfo, size_t nbits);
-void bitmap_init(bitmap_t *bitmap, const bitmap_info_t *binfo);
-size_t bitmap_size(const bitmap_info_t *binfo);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-bool bitmap_full(bitmap_t *bitmap, const bitmap_info_t *binfo);
-bool bitmap_get(bitmap_t *bitmap, const bitmap_info_t *binfo, size_t bit);
-void bitmap_set(bitmap_t *bitmap, const bitmap_info_t *binfo, size_t bit);
-size_t bitmap_sfu(bitmap_t *bitmap, const bitmap_info_t *binfo);
-void bitmap_unset(bitmap_t *bitmap, const bitmap_info_t *binfo, size_t bit);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_BITMAP_C_))
-JEMALLOC_INLINE bool
-bitmap_full(bitmap_t *bitmap, const bitmap_info_t *binfo)
-{
-#ifdef USE_TREE
- size_t rgoff = binfo->levels[binfo->nlevels].group_offset - 1;
- bitmap_t rg = bitmap[rgoff];
- /* The bitmap is full iff the root group is 0. */
- return (rg == 0);
-#else
- size_t i;
-
- for (i = 0; i < binfo->ngroups; i++) {
- if (bitmap[i] != 0)
- return (false);
- }
- return (true);
-#endif
-}
-
-JEMALLOC_INLINE bool
-bitmap_get(bitmap_t *bitmap, const bitmap_info_t *binfo, size_t bit)
-{
- size_t goff;
- bitmap_t g;
-
- assert(bit < binfo->nbits);
- goff = bit >> LG_BITMAP_GROUP_NBITS;
- g = bitmap[goff];
- return (!(g & (ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK))));
-}
-
-JEMALLOC_INLINE void
-bitmap_set(bitmap_t *bitmap, const bitmap_info_t *binfo, size_t bit)
-{
- size_t goff;
- bitmap_t *gp;
- bitmap_t g;
-
- assert(bit < binfo->nbits);
- assert(!bitmap_get(bitmap, binfo, bit));
- goff = bit >> LG_BITMAP_GROUP_NBITS;
- gp = &bitmap[goff];
- g = *gp;
- assert(g & (ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK)));
- g ^= ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK);
- *gp = g;
- assert(bitmap_get(bitmap, binfo, bit));
-#ifdef USE_TREE
- /* Propagate group state transitions up the tree. */
- if (g == 0) {
- unsigned i;
- for (i = 1; i < binfo->nlevels; i++) {
- bit = goff;
- goff = bit >> LG_BITMAP_GROUP_NBITS;
- gp = &bitmap[binfo->levels[i].group_offset + goff];
- g = *gp;
- assert(g & (ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK)));
- g ^= ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK);
- *gp = g;
- if (g != 0)
- break;
- }
- }
-#endif
-}
-
-/* sfu: set first unset. */
-JEMALLOC_INLINE size_t
-bitmap_sfu(bitmap_t *bitmap, const bitmap_info_t *binfo)
-{
- size_t bit;
- bitmap_t g;
- unsigned i;
-
- assert(!bitmap_full(bitmap, binfo));
-
-#ifdef USE_TREE
- i = binfo->nlevels - 1;
- g = bitmap[binfo->levels[i].group_offset];
- bit = ffs_lu(g) - 1;
- while (i > 0) {
- i--;
- g = bitmap[binfo->levels[i].group_offset + bit];
- bit = (bit << LG_BITMAP_GROUP_NBITS) + (ffs_lu(g) - 1);
- }
-#else
- i = 0;
- g = bitmap[0];
- while ((bit = ffs_lu(g)) == 0) {
- i++;
- g = bitmap[i];
- }
- bit = (i << LG_BITMAP_GROUP_NBITS) + (bit - 1);
-#endif
- bitmap_set(bitmap, binfo, bit);
- return (bit);
-}
-
-JEMALLOC_INLINE void
-bitmap_unset(bitmap_t *bitmap, const bitmap_info_t *binfo, size_t bit)
-{
- size_t goff;
- bitmap_t *gp;
- bitmap_t g;
- UNUSED bool propagate;
-
- assert(bit < binfo->nbits);
- assert(bitmap_get(bitmap, binfo, bit));
- goff = bit >> LG_BITMAP_GROUP_NBITS;
- gp = &bitmap[goff];
- g = *gp;
- propagate = (g == 0);
- assert((g & (ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK))) == 0);
- g ^= ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK);
- *gp = g;
- assert(!bitmap_get(bitmap, binfo, bit));
-#ifdef USE_TREE
- /* Propagate group state transitions up the tree. */
- if (propagate) {
- unsigned i;
- for (i = 1; i < binfo->nlevels; i++) {
- bit = goff;
- goff = bit >> LG_BITMAP_GROUP_NBITS;
- gp = &bitmap[binfo->levels[i].group_offset + goff];
- g = *gp;
- propagate = (g == 0);
- assert((g & (ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK)))
- == 0);
- g ^= ZU(1) << (bit & BITMAP_GROUP_NBITS_MASK);
- *gp = g;
- if (!propagate)
- break;
- }
- }
-#endif /* USE_TREE */
-}
-
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/chunk.h b/memory/jemalloc/src/include/jemalloc/internal/chunk.h
deleted file mode 100644
index 38c9a012d..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/chunk.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-/*
- * Size and alignment of memory chunks that are allocated by the OS's virtual
- * memory system.
- */
-#define LG_CHUNK_DEFAULT 21
-
-/* Return the chunk address for allocation address a. */
-#define CHUNK_ADDR2BASE(a) \
- ((void *)((uintptr_t)(a) & ~chunksize_mask))
-
-/* Return the chunk offset of address a. */
-#define CHUNK_ADDR2OFFSET(a) \
- ((size_t)((uintptr_t)(a) & chunksize_mask))
-
-/* Return the smallest chunk multiple that is >= s. */
-#define CHUNK_CEILING(s) \
- (((s) + chunksize_mask) & ~chunksize_mask)
-
-#define CHUNK_HOOKS_INITIALIZER { \
- NULL, \
- NULL, \
- NULL, \
- NULL, \
- NULL, \
- NULL, \
- NULL \
-}
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-extern size_t opt_lg_chunk;
-extern const char *opt_dss;
-
-extern rtree_t chunks_rtree;
-
-extern size_t chunksize;
-extern size_t chunksize_mask; /* (chunksize - 1). */
-extern size_t chunk_npages;
-
-extern const chunk_hooks_t chunk_hooks_default;
-
-chunk_hooks_t chunk_hooks_get(tsdn_t *tsdn, arena_t *arena);
-chunk_hooks_t chunk_hooks_set(tsdn_t *tsdn, arena_t *arena,
- const chunk_hooks_t *chunk_hooks);
-
-bool chunk_register(tsdn_t *tsdn, const void *chunk,
- const extent_node_t *node);
-void chunk_deregister(const void *chunk, const extent_node_t *node);
-void *chunk_alloc_base(size_t size);
-void *chunk_alloc_cache(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, void *new_addr, size_t size, size_t alignment,
- bool *zero, bool *commit, bool dalloc_node);
-void *chunk_alloc_wrapper(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, void *new_addr, size_t size, size_t alignment,
- bool *zero, bool *commit);
-void chunk_dalloc_cache(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, void *chunk, size_t size, bool committed);
-void chunk_dalloc_wrapper(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, void *chunk, size_t size, bool zeroed,
- bool committed);
-bool chunk_purge_wrapper(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, void *chunk, size_t size, size_t offset,
- size_t length);
-bool chunk_boot(void);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-extent_node_t *chunk_lookup(const void *chunk, bool dependent);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_CHUNK_C_))
-JEMALLOC_INLINE extent_node_t *
-chunk_lookup(const void *ptr, bool dependent)
-{
-
- return (rtree_get(&chunks_rtree, (uintptr_t)ptr, dependent));
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-
-#include "jemalloc/internal/chunk_dss.h"
-#include "jemalloc/internal/chunk_mmap.h"
diff --git a/memory/jemalloc/src/include/jemalloc/internal/chunk_dss.h b/memory/jemalloc/src/include/jemalloc/internal/chunk_dss.h
deleted file mode 100644
index da8511ba0..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/chunk_dss.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef enum {
- dss_prec_disabled = 0,
- dss_prec_primary = 1,
- dss_prec_secondary = 2,
-
- dss_prec_limit = 3
-} dss_prec_t;
-#define DSS_PREC_DEFAULT dss_prec_secondary
-#define DSS_DEFAULT "secondary"
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-extern const char *dss_prec_names[];
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-dss_prec_t chunk_dss_prec_get(void);
-bool chunk_dss_prec_set(dss_prec_t dss_prec);
-void *chunk_alloc_dss(tsdn_t *tsdn, arena_t *arena, void *new_addr,
- size_t size, size_t alignment, bool *zero, bool *commit);
-bool chunk_in_dss(void *chunk);
-bool chunk_dss_mergeable(void *chunk_a, void *chunk_b);
-void chunk_dss_boot(void);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/chunk_mmap.h b/memory/jemalloc/src/include/jemalloc/internal/chunk_mmap.h
deleted file mode 100644
index 6f2d0ac2e..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/chunk_mmap.h
+++ /dev/null
@@ -1,21 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void *chunk_alloc_mmap(void *new_addr, size_t size, size_t alignment,
- bool *zero, bool *commit);
-bool chunk_dalloc_mmap(void *chunk, size_t size);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/ckh.h b/memory/jemalloc/src/include/jemalloc/internal/ckh.h
deleted file mode 100644
index f75ad90b7..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/ckh.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct ckh_s ckh_t;
-typedef struct ckhc_s ckhc_t;
-
-/* Typedefs to allow easy function pointer passing. */
-typedef void ckh_hash_t (const void *, size_t[2]);
-typedef bool ckh_keycomp_t (const void *, const void *);
-
-/* Maintain counters used to get an idea of performance. */
-/* #define CKH_COUNT */
-/* Print counter values in ckh_delete() (requires CKH_COUNT). */
-/* #define CKH_VERBOSE */
-
-/*
- * There are 2^LG_CKH_BUCKET_CELLS cells in each hash table bucket. Try to fit
- * one bucket per L1 cache line.
- */
-#define LG_CKH_BUCKET_CELLS (LG_CACHELINE - LG_SIZEOF_PTR - 1)
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-/* Hash table cell. */
-struct ckhc_s {
- const void *key;
- const void *data;
-};
-
-struct ckh_s {
-#ifdef CKH_COUNT
- /* Counters used to get an idea of performance. */
- uint64_t ngrows;
- uint64_t nshrinks;
- uint64_t nshrinkfails;
- uint64_t ninserts;
- uint64_t nrelocs;
-#endif
-
- /* Used for pseudo-random number generation. */
- uint64_t prng_state;
-
- /* Total number of items. */
- size_t count;
-
- /*
- * Minimum and current number of hash table buckets. There are
- * 2^LG_CKH_BUCKET_CELLS cells per bucket.
- */
- unsigned lg_minbuckets;
- unsigned lg_curbuckets;
-
- /* Hash and comparison functions. */
- ckh_hash_t *hash;
- ckh_keycomp_t *keycomp;
-
- /* Hash table with 2^lg_curbuckets buckets. */
- ckhc_t *tab;
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-bool ckh_new(tsd_t *tsd, ckh_t *ckh, size_t minitems, ckh_hash_t *hash,
- ckh_keycomp_t *keycomp);
-void ckh_delete(tsd_t *tsd, ckh_t *ckh);
-size_t ckh_count(ckh_t *ckh);
-bool ckh_iter(ckh_t *ckh, size_t *tabind, void **key, void **data);
-bool ckh_insert(tsd_t *tsd, ckh_t *ckh, const void *key, const void *data);
-bool ckh_remove(tsd_t *tsd, ckh_t *ckh, const void *searchkey, void **key,
- void **data);
-bool ckh_search(ckh_t *ckh, const void *searchkey, void **key, void **data);
-void ckh_string_hash(const void *key, size_t r_hash[2]);
-bool ckh_string_keycomp(const void *k1, const void *k2);
-void ckh_pointer_hash(const void *key, size_t r_hash[2]);
-bool ckh_pointer_keycomp(const void *k1, const void *k2);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/ctl.h b/memory/jemalloc/src/include/jemalloc/internal/ctl.h
deleted file mode 100644
index af0f6d7c5..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/ctl.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct ctl_node_s ctl_node_t;
-typedef struct ctl_named_node_s ctl_named_node_t;
-typedef struct ctl_indexed_node_s ctl_indexed_node_t;
-typedef struct ctl_arena_stats_s ctl_arena_stats_t;
-typedef struct ctl_stats_s ctl_stats_t;
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct ctl_node_s {
- bool named;
-};
-
-struct ctl_named_node_s {
- struct ctl_node_s node;
- const char *name;
- /* If (nchildren == 0), this is a terminal node. */
- unsigned nchildren;
- const ctl_node_t *children;
- int (*ctl)(tsd_t *, const size_t *, size_t, void *,
- size_t *, void *, size_t);
-};
-
-struct ctl_indexed_node_s {
- struct ctl_node_s node;
- const ctl_named_node_t *(*index)(tsdn_t *, const size_t *, size_t,
- size_t);
-};
-
-struct ctl_arena_stats_s {
- bool initialized;
- unsigned nthreads;
- const char *dss;
- ssize_t lg_dirty_mult;
- ssize_t decay_time;
- size_t pactive;
- size_t pdirty;
-
- /* The remainder are only populated if config_stats is true. */
-
- arena_stats_t astats;
-
- /* Aggregate stats for small size classes, based on bin stats. */
- size_t allocated_small;
- uint64_t nmalloc_small;
- uint64_t ndalloc_small;
- uint64_t nrequests_small;
-
- malloc_bin_stats_t bstats[NBINS];
- malloc_large_stats_t *lstats; /* nlclasses elements. */
- malloc_huge_stats_t *hstats; /* nhclasses elements. */
-};
-
-struct ctl_stats_s {
- size_t allocated;
- size_t active;
- size_t metadata;
- size_t resident;
- size_t mapped;
- size_t retained;
- unsigned narenas;
- ctl_arena_stats_t *arenas; /* (narenas + 1) elements. */
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-int ctl_byname(tsd_t *tsd, const char *name, void *oldp, size_t *oldlenp,
- void *newp, size_t newlen);
-int ctl_nametomib(tsdn_t *tsdn, const char *name, size_t *mibp,
- size_t *miblenp);
-
-int ctl_bymib(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen);
-bool ctl_boot(void);
-void ctl_prefork(tsdn_t *tsdn);
-void ctl_postfork_parent(tsdn_t *tsdn);
-void ctl_postfork_child(tsdn_t *tsdn);
-
-#define xmallctl(name, oldp, oldlenp, newp, newlen) do { \
- if (je_mallctl(name, oldp, oldlenp, newp, newlen) \
- != 0) { \
- malloc_printf( \
- "<jemalloc>: Failure in xmallctl(\"%s\", ...)\n", \
- name); \
- abort(); \
- } \
-} while (0)
-
-#define xmallctlnametomib(name, mibp, miblenp) do { \
- if (je_mallctlnametomib(name, mibp, miblenp) != 0) { \
- malloc_printf("<jemalloc>: Failure in " \
- "xmallctlnametomib(\"%s\", ...)\n", name); \
- abort(); \
- } \
-} while (0)
-
-#define xmallctlbymib(mib, miblen, oldp, oldlenp, newp, newlen) do { \
- if (je_mallctlbymib(mib, miblen, oldp, oldlenp, newp, \
- newlen) != 0) { \
- malloc_write( \
- "<jemalloc>: Failure in xmallctlbymib()\n"); \
- abort(); \
- } \
-} while (0)
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-
diff --git a/memory/jemalloc/src/include/jemalloc/internal/extent.h b/memory/jemalloc/src/include/jemalloc/internal/extent.h
deleted file mode 100644
index 49d76a57f..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/extent.h
+++ /dev/null
@@ -1,239 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct extent_node_s extent_node_t;
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-/* Tree of extents. Use accessor functions for en_* fields. */
-struct extent_node_s {
- /* Arena from which this extent came, if any. */
- arena_t *en_arena;
-
- /* Pointer to the extent that this tree node is responsible for. */
- void *en_addr;
-
- /* Total region size. */
- size_t en_size;
-
- /*
- * The zeroed flag is used by chunk recycling code to track whether
- * memory is zero-filled.
- */
- bool en_zeroed;
-
- /*
- * True if physical memory is committed to the extent, whether
- * explicitly or implicitly as on a system that overcommits and
- * satisfies physical memory needs on demand via soft page faults.
- */
- bool en_committed;
-
- /*
- * The achunk flag is used to validate that huge allocation lookups
- * don't return arena chunks.
- */
- bool en_achunk;
-
- /* Profile counters, used for huge objects. */
- prof_tctx_t *en_prof_tctx;
-
- /* Linkage for arena's runs_dirty and chunks_cache rings. */
- arena_runs_dirty_link_t rd;
- qr(extent_node_t) cc_link;
-
- union {
- /* Linkage for the size/address-ordered tree. */
- rb_node(extent_node_t) szad_link;
-
- /* Linkage for arena's achunks, huge, and node_cache lists. */
- ql_elm(extent_node_t) ql_link;
- };
-
- /* Linkage for the address-ordered tree. */
- rb_node(extent_node_t) ad_link;
-};
-typedef rb_tree(extent_node_t) extent_tree_t;
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-rb_proto(, extent_tree_szad_, extent_tree_t, extent_node_t)
-
-rb_proto(, extent_tree_ad_, extent_tree_t, extent_node_t)
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-arena_t *extent_node_arena_get(const extent_node_t *node);
-void *extent_node_addr_get(const extent_node_t *node);
-size_t extent_node_size_get(const extent_node_t *node);
-bool extent_node_zeroed_get(const extent_node_t *node);
-bool extent_node_committed_get(const extent_node_t *node);
-bool extent_node_achunk_get(const extent_node_t *node);
-prof_tctx_t *extent_node_prof_tctx_get(const extent_node_t *node);
-void extent_node_arena_set(extent_node_t *node, arena_t *arena);
-void extent_node_addr_set(extent_node_t *node, void *addr);
-void extent_node_size_set(extent_node_t *node, size_t size);
-void extent_node_zeroed_set(extent_node_t *node, bool zeroed);
-void extent_node_committed_set(extent_node_t *node, bool committed);
-void extent_node_achunk_set(extent_node_t *node, bool achunk);
-void extent_node_prof_tctx_set(extent_node_t *node, prof_tctx_t *tctx);
-void extent_node_init(extent_node_t *node, arena_t *arena, void *addr,
- size_t size, bool zeroed, bool committed);
-void extent_node_dirty_linkage_init(extent_node_t *node);
-void extent_node_dirty_insert(extent_node_t *node,
- arena_runs_dirty_link_t *runs_dirty, extent_node_t *chunks_dirty);
-void extent_node_dirty_remove(extent_node_t *node);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_EXTENT_C_))
-JEMALLOC_INLINE arena_t *
-extent_node_arena_get(const extent_node_t *node)
-{
-
- return (node->en_arena);
-}
-
-JEMALLOC_INLINE void *
-extent_node_addr_get(const extent_node_t *node)
-{
-
- return (node->en_addr);
-}
-
-JEMALLOC_INLINE size_t
-extent_node_size_get(const extent_node_t *node)
-{
-
- return (node->en_size);
-}
-
-JEMALLOC_INLINE bool
-extent_node_zeroed_get(const extent_node_t *node)
-{
-
- return (node->en_zeroed);
-}
-
-JEMALLOC_INLINE bool
-extent_node_committed_get(const extent_node_t *node)
-{
-
- assert(!node->en_achunk);
- return (node->en_committed);
-}
-
-JEMALLOC_INLINE bool
-extent_node_achunk_get(const extent_node_t *node)
-{
-
- return (node->en_achunk);
-}
-
-JEMALLOC_INLINE prof_tctx_t *
-extent_node_prof_tctx_get(const extent_node_t *node)
-{
-
- return (node->en_prof_tctx);
-}
-
-JEMALLOC_INLINE void
-extent_node_arena_set(extent_node_t *node, arena_t *arena)
-{
-
- node->en_arena = arena;
-}
-
-JEMALLOC_INLINE void
-extent_node_addr_set(extent_node_t *node, void *addr)
-{
-
- node->en_addr = addr;
-}
-
-JEMALLOC_INLINE void
-extent_node_size_set(extent_node_t *node, size_t size)
-{
-
- node->en_size = size;
-}
-
-JEMALLOC_INLINE void
-extent_node_zeroed_set(extent_node_t *node, bool zeroed)
-{
-
- node->en_zeroed = zeroed;
-}
-
-JEMALLOC_INLINE void
-extent_node_committed_set(extent_node_t *node, bool committed)
-{
-
- node->en_committed = committed;
-}
-
-JEMALLOC_INLINE void
-extent_node_achunk_set(extent_node_t *node, bool achunk)
-{
-
- node->en_achunk = achunk;
-}
-
-JEMALLOC_INLINE void
-extent_node_prof_tctx_set(extent_node_t *node, prof_tctx_t *tctx)
-{
-
- node->en_prof_tctx = tctx;
-}
-
-JEMALLOC_INLINE void
-extent_node_init(extent_node_t *node, arena_t *arena, void *addr, size_t size,
- bool zeroed, bool committed)
-{
-
- extent_node_arena_set(node, arena);
- extent_node_addr_set(node, addr);
- extent_node_size_set(node, size);
- extent_node_zeroed_set(node, zeroed);
- extent_node_committed_set(node, committed);
- extent_node_achunk_set(node, false);
- if (config_prof)
- extent_node_prof_tctx_set(node, NULL);
-}
-
-JEMALLOC_INLINE void
-extent_node_dirty_linkage_init(extent_node_t *node)
-{
-
- qr_new(&node->rd, rd_link);
- qr_new(node, cc_link);
-}
-
-JEMALLOC_INLINE void
-extent_node_dirty_insert(extent_node_t *node,
- arena_runs_dirty_link_t *runs_dirty, extent_node_t *chunks_dirty)
-{
-
- qr_meld(runs_dirty, &node->rd, rd_link);
- qr_meld(chunks_dirty, node, cc_link);
-}
-
-JEMALLOC_INLINE void
-extent_node_dirty_remove(extent_node_t *node)
-{
-
- qr_remove(&node->rd, rd_link);
- qr_remove(node, cc_link);
-}
-
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-
diff --git a/memory/jemalloc/src/include/jemalloc/internal/hash.h b/memory/jemalloc/src/include/jemalloc/internal/hash.h
deleted file mode 100644
index 1ff2d9a05..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/hash.h
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * The following hash function is based on MurmurHash3, placed into the public
- * domain by Austin Appleby. See https://github.com/aappleby/smhasher for
- * details.
- */
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-uint32_t hash_x86_32(const void *key, int len, uint32_t seed);
-void hash_x86_128(const void *key, const int len, uint32_t seed,
- uint64_t r_out[2]);
-void hash_x64_128(const void *key, const int len, const uint32_t seed,
- uint64_t r_out[2]);
-void hash(const void *key, size_t len, const uint32_t seed,
- size_t r_hash[2]);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_HASH_C_))
-/******************************************************************************/
-/* Internal implementation. */
-JEMALLOC_INLINE uint32_t
-hash_rotl_32(uint32_t x, int8_t r)
-{
-
- return ((x << r) | (x >> (32 - r)));
-}
-
-JEMALLOC_INLINE uint64_t
-hash_rotl_64(uint64_t x, int8_t r)
-{
-
- return ((x << r) | (x >> (64 - r)));
-}
-
-JEMALLOC_INLINE uint32_t
-hash_get_block_32(const uint32_t *p, int i)
-{
-
- /* Handle unaligned read. */
- if (unlikely((uintptr_t)p & (sizeof(uint32_t)-1)) != 0) {
- uint32_t ret;
-
- memcpy(&ret, (uint8_t *)(p + i), sizeof(uint32_t));
- return (ret);
- }
-
- return (p[i]);
-}
-
-JEMALLOC_INLINE uint64_t
-hash_get_block_64(const uint64_t *p, int i)
-{
-
- /* Handle unaligned read. */
- if (unlikely((uintptr_t)p & (sizeof(uint64_t)-1)) != 0) {
- uint64_t ret;
-
- memcpy(&ret, (uint8_t *)(p + i), sizeof(uint64_t));
- return (ret);
- }
-
- return (p[i]);
-}
-
-JEMALLOC_INLINE uint32_t
-hash_fmix_32(uint32_t h)
-{
-
- h ^= h >> 16;
- h *= 0x85ebca6b;
- h ^= h >> 13;
- h *= 0xc2b2ae35;
- h ^= h >> 16;
-
- return (h);
-}
-
-JEMALLOC_INLINE uint64_t
-hash_fmix_64(uint64_t k)
-{
-
- k ^= k >> 33;
- k *= KQU(0xff51afd7ed558ccd);
- k ^= k >> 33;
- k *= KQU(0xc4ceb9fe1a85ec53);
- k ^= k >> 33;
-
- return (k);
-}
-
-JEMALLOC_INLINE uint32_t
-hash_x86_32(const void *key, int len, uint32_t seed)
-{
- const uint8_t *data = (const uint8_t *) key;
- const int nblocks = len / 4;
-
- uint32_t h1 = seed;
-
- const uint32_t c1 = 0xcc9e2d51;
- const uint32_t c2 = 0x1b873593;
-
- /* body */
- {
- const uint32_t *blocks = (const uint32_t *) (data + nblocks*4);
- int i;
-
- for (i = -nblocks; i; i++) {
- uint32_t k1 = hash_get_block_32(blocks, i);
-
- k1 *= c1;
- k1 = hash_rotl_32(k1, 15);
- k1 *= c2;
-
- h1 ^= k1;
- h1 = hash_rotl_32(h1, 13);
- h1 = h1*5 + 0xe6546b64;
- }
- }
-
- /* tail */
- {
- const uint8_t *tail = (const uint8_t *) (data + nblocks*4);
-
- uint32_t k1 = 0;
-
- switch (len & 3) {
- case 3: k1 ^= tail[2] << 16;
- case 2: k1 ^= tail[1] << 8;
- case 1: k1 ^= tail[0]; k1 *= c1; k1 = hash_rotl_32(k1, 15);
- k1 *= c2; h1 ^= k1;
- }
- }
-
- /* finalization */
- h1 ^= len;
-
- h1 = hash_fmix_32(h1);
-
- return (h1);
-}
-
-UNUSED JEMALLOC_INLINE void
-hash_x86_128(const void *key, const int len, uint32_t seed,
- uint64_t r_out[2])
-{
- const uint8_t * data = (const uint8_t *) key;
- const int nblocks = len / 16;
-
- uint32_t h1 = seed;
- uint32_t h2 = seed;
- uint32_t h3 = seed;
- uint32_t h4 = seed;
-
- const uint32_t c1 = 0x239b961b;
- const uint32_t c2 = 0xab0e9789;
- const uint32_t c3 = 0x38b34ae5;
- const uint32_t c4 = 0xa1e38b93;
-
- /* body */
- {
- const uint32_t *blocks = (const uint32_t *) (data + nblocks*16);
- int i;
-
- for (i = -nblocks; i; i++) {
- uint32_t k1 = hash_get_block_32(blocks, i*4 + 0);
- uint32_t k2 = hash_get_block_32(blocks, i*4 + 1);
- uint32_t k3 = hash_get_block_32(blocks, i*4 + 2);
- uint32_t k4 = hash_get_block_32(blocks, i*4 + 3);
-
- k1 *= c1; k1 = hash_rotl_32(k1, 15); k1 *= c2; h1 ^= k1;
-
- h1 = hash_rotl_32(h1, 19); h1 += h2;
- h1 = h1*5 + 0x561ccd1b;
-
- k2 *= c2; k2 = hash_rotl_32(k2, 16); k2 *= c3; h2 ^= k2;
-
- h2 = hash_rotl_32(h2, 17); h2 += h3;
- h2 = h2*5 + 0x0bcaa747;
-
- k3 *= c3; k3 = hash_rotl_32(k3, 17); k3 *= c4; h3 ^= k3;
-
- h3 = hash_rotl_32(h3, 15); h3 += h4;
- h3 = h3*5 + 0x96cd1c35;
-
- k4 *= c4; k4 = hash_rotl_32(k4, 18); k4 *= c1; h4 ^= k4;
-
- h4 = hash_rotl_32(h4, 13); h4 += h1;
- h4 = h4*5 + 0x32ac3b17;
- }
- }
-
- /* tail */
- {
- const uint8_t *tail = (const uint8_t *) (data + nblocks*16);
- uint32_t k1 = 0;
- uint32_t k2 = 0;
- uint32_t k3 = 0;
- uint32_t k4 = 0;
-
- switch (len & 15) {
- case 15: k4 ^= tail[14] << 16;
- case 14: k4 ^= tail[13] << 8;
- case 13: k4 ^= tail[12] << 0;
- k4 *= c4; k4 = hash_rotl_32(k4, 18); k4 *= c1; h4 ^= k4;
-
- case 12: k3 ^= tail[11] << 24;
- case 11: k3 ^= tail[10] << 16;
- case 10: k3 ^= tail[ 9] << 8;
- case 9: k3 ^= tail[ 8] << 0;
- k3 *= c3; k3 = hash_rotl_32(k3, 17); k3 *= c4; h3 ^= k3;
-
- case 8: k2 ^= tail[ 7] << 24;
- case 7: k2 ^= tail[ 6] << 16;
- case 6: k2 ^= tail[ 5] << 8;
- case 5: k2 ^= tail[ 4] << 0;
- k2 *= c2; k2 = hash_rotl_32(k2, 16); k2 *= c3; h2 ^= k2;
-
- case 4: k1 ^= tail[ 3] << 24;
- case 3: k1 ^= tail[ 2] << 16;
- case 2: k1 ^= tail[ 1] << 8;
- case 1: k1 ^= tail[ 0] << 0;
- k1 *= c1; k1 = hash_rotl_32(k1, 15); k1 *= c2; h1 ^= k1;
- }
- }
-
- /* finalization */
- h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len;
-
- h1 += h2; h1 += h3; h1 += h4;
- h2 += h1; h3 += h1; h4 += h1;
-
- h1 = hash_fmix_32(h1);
- h2 = hash_fmix_32(h2);
- h3 = hash_fmix_32(h3);
- h4 = hash_fmix_32(h4);
-
- h1 += h2; h1 += h3; h1 += h4;
- h2 += h1; h3 += h1; h4 += h1;
-
- r_out[0] = (((uint64_t) h2) << 32) | h1;
- r_out[1] = (((uint64_t) h4) << 32) | h3;
-}
-
-UNUSED JEMALLOC_INLINE void
-hash_x64_128(const void *key, const int len, const uint32_t seed,
- uint64_t r_out[2])
-{
- const uint8_t *data = (const uint8_t *) key;
- const int nblocks = len / 16;
-
- uint64_t h1 = seed;
- uint64_t h2 = seed;
-
- const uint64_t c1 = KQU(0x87c37b91114253d5);
- const uint64_t c2 = KQU(0x4cf5ad432745937f);
-
- /* body */
- {
- const uint64_t *blocks = (const uint64_t *) (data);
- int i;
-
- for (i = 0; i < nblocks; i++) {
- uint64_t k1 = hash_get_block_64(blocks, i*2 + 0);
- uint64_t k2 = hash_get_block_64(blocks, i*2 + 1);
-
- k1 *= c1; k1 = hash_rotl_64(k1, 31); k1 *= c2; h1 ^= k1;
-
- h1 = hash_rotl_64(h1, 27); h1 += h2;
- h1 = h1*5 + 0x52dce729;
-
- k2 *= c2; k2 = hash_rotl_64(k2, 33); k2 *= c1; h2 ^= k2;
-
- h2 = hash_rotl_64(h2, 31); h2 += h1;
- h2 = h2*5 + 0x38495ab5;
- }
- }
-
- /* tail */
- {
- const uint8_t *tail = (const uint8_t*)(data + nblocks*16);
- uint64_t k1 = 0;
- uint64_t k2 = 0;
-
- switch (len & 15) {
- case 15: k2 ^= ((uint64_t)(tail[14])) << 48;
- case 14: k2 ^= ((uint64_t)(tail[13])) << 40;
- case 13: k2 ^= ((uint64_t)(tail[12])) << 32;
- case 12: k2 ^= ((uint64_t)(tail[11])) << 24;
- case 11: k2 ^= ((uint64_t)(tail[10])) << 16;
- case 10: k2 ^= ((uint64_t)(tail[ 9])) << 8;
- case 9: k2 ^= ((uint64_t)(tail[ 8])) << 0;
- k2 *= c2; k2 = hash_rotl_64(k2, 33); k2 *= c1; h2 ^= k2;
-
- case 8: k1 ^= ((uint64_t)(tail[ 7])) << 56;
- case 7: k1 ^= ((uint64_t)(tail[ 6])) << 48;
- case 6: k1 ^= ((uint64_t)(tail[ 5])) << 40;
- case 5: k1 ^= ((uint64_t)(tail[ 4])) << 32;
- case 4: k1 ^= ((uint64_t)(tail[ 3])) << 24;
- case 3: k1 ^= ((uint64_t)(tail[ 2])) << 16;
- case 2: k1 ^= ((uint64_t)(tail[ 1])) << 8;
- case 1: k1 ^= ((uint64_t)(tail[ 0])) << 0;
- k1 *= c1; k1 = hash_rotl_64(k1, 31); k1 *= c2; h1 ^= k1;
- }
- }
-
- /* finalization */
- h1 ^= len; h2 ^= len;
-
- h1 += h2;
- h2 += h1;
-
- h1 = hash_fmix_64(h1);
- h2 = hash_fmix_64(h2);
-
- h1 += h2;
- h2 += h1;
-
- r_out[0] = h1;
- r_out[1] = h2;
-}
-
-/******************************************************************************/
-/* API. */
-JEMALLOC_INLINE void
-hash(const void *key, size_t len, const uint32_t seed, size_t r_hash[2])
-{
-
- assert(len <= INT_MAX); /* Unfortunate implementation limitation. */
-
-#if (LG_SIZEOF_PTR == 3 && !defined(JEMALLOC_BIG_ENDIAN))
- hash_x64_128(key, (int)len, seed, (uint64_t *)r_hash);
-#else
- {
- uint64_t hashes[2];
- hash_x86_128(key, (int)len, seed, hashes);
- r_hash[0] = (size_t)hashes[0];
- r_hash[1] = (size_t)hashes[1];
- }
-#endif
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/huge.h b/memory/jemalloc/src/include/jemalloc/internal/huge.h
deleted file mode 100644
index 22184d9bb..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/huge.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void *huge_malloc(tsdn_t *tsdn, arena_t *arena, size_t usize, bool zero);
-void *huge_palloc(tsdn_t *tsdn, arena_t *arena, size_t usize,
- size_t alignment, bool zero);
-bool huge_ralloc_no_move(tsdn_t *tsdn, void *ptr, size_t oldsize,
- size_t usize_min, size_t usize_max, bool zero);
-void *huge_ralloc(tsd_t *tsd, arena_t *arena, void *ptr, size_t oldsize,
- size_t usize, size_t alignment, bool zero, tcache_t *tcache);
-#ifdef JEMALLOC_JET
-typedef void (huge_dalloc_junk_t)(void *, size_t);
-extern huge_dalloc_junk_t *huge_dalloc_junk;
-#endif
-void huge_dalloc(tsdn_t *tsdn, void *ptr);
-arena_t *huge_aalloc(const void *ptr);
-size_t huge_salloc(tsdn_t *tsdn, const void *ptr);
-prof_tctx_t *huge_prof_tctx_get(tsdn_t *tsdn, const void *ptr);
-void huge_prof_tctx_set(tsdn_t *tsdn, const void *ptr, prof_tctx_t *tctx);
-void huge_prof_tctx_reset(tsdn_t *tsdn, const void *ptr);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal.h.in b/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal.h.in
deleted file mode 100644
index fdc8fef9d..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal.h.in
+++ /dev/null
@@ -1,1288 +0,0 @@
-#ifndef JEMALLOC_INTERNAL_H
-#define JEMALLOC_INTERNAL_H
-
-#include "jemalloc_internal_defs.h"
-#include "jemalloc/internal/jemalloc_internal_decls.h"
-
-#ifdef JEMALLOC_UTRACE
-#include <sys/ktrace.h>
-#endif
-
-#define JEMALLOC_NO_DEMANGLE
-#ifdef JEMALLOC_JET
-# define JEMALLOC_N(n) jet_##n
-# include "jemalloc/internal/public_namespace.h"
-# define JEMALLOC_NO_RENAME
-# include "../jemalloc@install_suffix@.h"
-# undef JEMALLOC_NO_RENAME
-#else
-# define JEMALLOC_N(n) @private_namespace@##n
-# include "../jemalloc@install_suffix@.h"
-#endif
-#include "jemalloc/internal/private_namespace.h"
-
-static const bool config_debug =
-#ifdef JEMALLOC_DEBUG
- true
-#else
- false
-#endif
- ;
-static const bool have_dss =
-#ifdef JEMALLOC_DSS
- true
-#else
- false
-#endif
- ;
-static const bool config_fill =
-#ifdef JEMALLOC_FILL
- true
-#else
- false
-#endif
- ;
-static const bool config_lazy_lock =
-#ifdef JEMALLOC_LAZY_LOCK
- true
-#else
- false
-#endif
- ;
-static const char * const config_malloc_conf = JEMALLOC_CONFIG_MALLOC_CONF;
-static const bool config_prof =
-#ifdef JEMALLOC_PROF
- true
-#else
- false
-#endif
- ;
-static const bool config_prof_libgcc =
-#ifdef JEMALLOC_PROF_LIBGCC
- true
-#else
- false
-#endif
- ;
-static const bool config_prof_libunwind =
-#ifdef JEMALLOC_PROF_LIBUNWIND
- true
-#else
- false
-#endif
- ;
-static const bool maps_coalesce =
-#ifdef JEMALLOC_MAPS_COALESCE
- true
-#else
- false
-#endif
- ;
-static const bool config_munmap =
-#ifdef JEMALLOC_MUNMAP
- true
-#else
- false
-#endif
- ;
-static const bool config_stats =
-#ifdef JEMALLOC_STATS
- true
-#else
- false
-#endif
- ;
-static const bool config_tcache =
-#ifdef JEMALLOC_TCACHE
- true
-#else
- false
-#endif
- ;
-static const bool config_tls =
-#ifdef JEMALLOC_TLS
- true
-#else
- false
-#endif
- ;
-static const bool config_utrace =
-#ifdef JEMALLOC_UTRACE
- true
-#else
- false
-#endif
- ;
-static const bool config_valgrind =
-#ifdef JEMALLOC_VALGRIND
- true
-#else
- false
-#endif
- ;
-static const bool config_xmalloc =
-#ifdef JEMALLOC_XMALLOC
- true
-#else
- false
-#endif
- ;
-static const bool config_ivsalloc =
-#ifdef JEMALLOC_IVSALLOC
- true
-#else
- false
-#endif
- ;
-static const bool config_cache_oblivious =
-#ifdef JEMALLOC_CACHE_OBLIVIOUS
- true
-#else
- false
-#endif
- ;
-
-#ifdef JEMALLOC_C11ATOMICS
-#include <stdatomic.h>
-#endif
-
-#ifdef JEMALLOC_ATOMIC9
-#include <machine/atomic.h>
-#endif
-
-#if (defined(JEMALLOC_OSATOMIC) || defined(JEMALLOC_OSSPIN))
-#include <libkern/OSAtomic.h>
-#endif
-
-#ifdef JEMALLOC_ZONE
-#include <mach/mach_error.h>
-#include <mach/mach_init.h>
-#include <mach/vm_map.h>
-#include <malloc/malloc.h>
-#endif
-
-#include "jemalloc/internal/ph.h"
-#ifndef __PGI
-#define RB_COMPACT
-#endif
-#include "jemalloc/internal/rb.h"
-#include "jemalloc/internal/qr.h"
-#include "jemalloc/internal/ql.h"
-
-/*
- * jemalloc can conceptually be broken into components (arena, tcache, etc.),
- * but there are circular dependencies that cannot be broken without
- * substantial performance degradation. In order to reduce the effect on
- * visual code flow, read the header files in multiple passes, with one of the
- * following cpp variables defined during each pass:
- *
- * JEMALLOC_H_TYPES : Preprocessor-defined constants and psuedo-opaque data
- * types.
- * JEMALLOC_H_STRUCTS : Data structures.
- * JEMALLOC_H_EXTERNS : Extern data declarations and function prototypes.
- * JEMALLOC_H_INLINES : Inline functions.
- */
-/******************************************************************************/
-#define JEMALLOC_H_TYPES
-
-#include "jemalloc/internal/jemalloc_internal_macros.h"
-
-/* Page size index type. */
-typedef unsigned pszind_t;
-
-/* Size class index type. */
-typedef unsigned szind_t;
-
-/*
- * Flags bits:
- *
- * a: arena
- * t: tcache
- * 0: unused
- * z: zero
- * n: alignment
- *
- * aaaaaaaa aaaatttt tttttttt 0znnnnnn
- */
-#define MALLOCX_ARENA_MASK ((int)~0xfffff)
-#define MALLOCX_ARENA_MAX 0xffe
-#define MALLOCX_TCACHE_MASK ((int)~0xfff000ffU)
-#define MALLOCX_TCACHE_MAX 0xffd
-#define MALLOCX_LG_ALIGN_MASK ((int)0x3f)
-/* Use MALLOCX_ALIGN_GET() if alignment may not be specified in flags. */
-#define MALLOCX_ALIGN_GET_SPECIFIED(flags) \
- (ZU(1) << (flags & MALLOCX_LG_ALIGN_MASK))
-#define MALLOCX_ALIGN_GET(flags) \
- (MALLOCX_ALIGN_GET_SPECIFIED(flags) & (SIZE_T_MAX-1))
-#define MALLOCX_ZERO_GET(flags) \
- ((bool)(flags & MALLOCX_ZERO))
-
-#define MALLOCX_TCACHE_GET(flags) \
- (((unsigned)((flags & MALLOCX_TCACHE_MASK) >> 8)) - 2)
-#define MALLOCX_ARENA_GET(flags) \
- (((unsigned)(((unsigned)flags) >> 20)) - 1)
-
-/* Smallest size class to support. */
-#define TINY_MIN (1U << LG_TINY_MIN)
-
-/*
- * Minimum allocation alignment is 2^LG_QUANTUM bytes (ignoring tiny size
- * classes).
- */
-#ifndef LG_QUANTUM
-# if (defined(__i386__) || defined(_M_IX86))
-# define LG_QUANTUM 4
-# endif
-# ifdef __ia64__
-# define LG_QUANTUM 4
-# endif
-# ifdef __alpha__
-# define LG_QUANTUM 4
-# endif
-# if (defined(__sparc64__) || defined(__sparcv9) || defined(__sparc_v9__))
-# define LG_QUANTUM 4
-# endif
-# if (defined(__amd64__) || defined(__x86_64__) || defined(_M_X64))
-# define LG_QUANTUM 4
-# endif
-# ifdef __arm__
-# define LG_QUANTUM 3
-# endif
-# ifdef __aarch64__
-# define LG_QUANTUM 4
-# endif
-# ifdef __hppa__
-# define LG_QUANTUM 4
-# endif
-# ifdef __mips__
-# define LG_QUANTUM 3
-# endif
-# ifdef __or1k__
-# define LG_QUANTUM 3
-# endif
-# ifdef __powerpc__
-# define LG_QUANTUM 4
-# endif
-# ifdef __riscv__
-# define LG_QUANTUM 4
-# endif
-# ifdef __s390__
-# define LG_QUANTUM 4
-# endif
-# ifdef __SH4__
-# define LG_QUANTUM 4
-# endif
-# ifdef __tile__
-# define LG_QUANTUM 4
-# endif
-# ifdef __le32__
-# define LG_QUANTUM 4
-# endif
-# ifndef LG_QUANTUM
-# error "Unknown minimum alignment for architecture; specify via "
- "--with-lg-quantum"
-# endif
-#endif
-
-#define QUANTUM ((size_t)(1U << LG_QUANTUM))
-#define QUANTUM_MASK (QUANTUM - 1)
-
-/* Return the smallest quantum multiple that is >= a. */
-#define QUANTUM_CEILING(a) \
- (((a) + QUANTUM_MASK) & ~QUANTUM_MASK)
-
-#define LONG ((size_t)(1U << LG_SIZEOF_LONG))
-#define LONG_MASK (LONG - 1)
-
-/* Return the smallest long multiple that is >= a. */
-#define LONG_CEILING(a) \
- (((a) + LONG_MASK) & ~LONG_MASK)
-
-#define SIZEOF_PTR (1U << LG_SIZEOF_PTR)
-#define PTR_MASK (SIZEOF_PTR - 1)
-
-/* Return the smallest (void *) multiple that is >= a. */
-#define PTR_CEILING(a) \
- (((a) + PTR_MASK) & ~PTR_MASK)
-
-/*
- * Maximum size of L1 cache line. This is used to avoid cache line aliasing.
- * In addition, this controls the spacing of cacheline-spaced size classes.
- *
- * CACHELINE cannot be based on LG_CACHELINE because __declspec(align()) can
- * only handle raw constants.
- */
-#define LG_CACHELINE 6
-#define CACHELINE 64
-#define CACHELINE_MASK (CACHELINE - 1)
-
-/* Return the smallest cacheline multiple that is >= s. */
-#define CACHELINE_CEILING(s) \
- (((s) + CACHELINE_MASK) & ~CACHELINE_MASK)
-
-/* Page size. LG_PAGE is determined by the configure script. */
-#ifdef PAGE_MASK
-# undef PAGE_MASK
-#endif
-#define PAGE ((size_t)(1U << LG_PAGE))
-#define PAGE_MASK ((size_t)(PAGE - 1))
-
-/* Return the page base address for the page containing address a. */
-#define PAGE_ADDR2BASE(a) \
- ((void *)((uintptr_t)(a) & ~PAGE_MASK))
-
-/* Return the smallest pagesize multiple that is >= s. */
-#define PAGE_CEILING(s) \
- (((s) + PAGE_MASK) & ~PAGE_MASK)
-
-/* Return the nearest aligned address at or below a. */
-#define ALIGNMENT_ADDR2BASE(a, alignment) \
- ((void *)((uintptr_t)(a) & (-(alignment))))
-
-/* Return the offset between a and the nearest aligned address at or below a. */
-#define ALIGNMENT_ADDR2OFFSET(a, alignment) \
- ((size_t)((uintptr_t)(a) & (alignment - 1)))
-
-/* Return the smallest alignment multiple that is >= s. */
-#define ALIGNMENT_CEILING(s, alignment) \
- (((s) + (alignment - 1)) & (-(alignment)))
-
-/* Declare a variable-length array. */
-#if __STDC_VERSION__ < 199901L
-# ifdef _MSC_VER
-# include <malloc.h>
-# define alloca _alloca
-# else
-# ifdef JEMALLOC_HAS_ALLOCA_H
-# include <alloca.h>
-# else
-# include <stdlib.h>
-# endif
-# endif
-# define VARIABLE_ARRAY(type, name, count) \
- type *name = alloca(sizeof(type) * (count))
-#else
-# define VARIABLE_ARRAY(type, name, count) type name[(count)]
-#endif
-
-#include "jemalloc/internal/nstime.h"
-#include "jemalloc/internal/valgrind.h"
-#include "jemalloc/internal/util.h"
-#include "jemalloc/internal/atomic.h"
-#include "jemalloc/internal/spin.h"
-#include "jemalloc/internal/prng.h"
-#include "jemalloc/internal/ticker.h"
-#include "jemalloc/internal/ckh.h"
-#include "jemalloc/internal/size_classes.h"
-#include "jemalloc/internal/smoothstep.h"
-#include "jemalloc/internal/stats.h"
-#include "jemalloc/internal/ctl.h"
-#include "jemalloc/internal/witness.h"
-#include "jemalloc/internal/mutex.h"
-#include "jemalloc/internal/tsd.h"
-#include "jemalloc/internal/mb.h"
-#include "jemalloc/internal/extent.h"
-#include "jemalloc/internal/arena.h"
-#include "jemalloc/internal/bitmap.h"
-#include "jemalloc/internal/base.h"
-#include "jemalloc/internal/rtree.h"
-#include "jemalloc/internal/pages.h"
-#include "jemalloc/internal/chunk.h"
-#include "jemalloc/internal/huge.h"
-#include "jemalloc/internal/tcache.h"
-#include "jemalloc/internal/hash.h"
-#include "jemalloc/internal/quarantine.h"
-#include "jemalloc/internal/prof.h"
-
-#undef JEMALLOC_H_TYPES
-/******************************************************************************/
-#define JEMALLOC_H_STRUCTS
-
-#include "jemalloc/internal/nstime.h"
-#include "jemalloc/internal/valgrind.h"
-#include "jemalloc/internal/util.h"
-#include "jemalloc/internal/atomic.h"
-#include "jemalloc/internal/spin.h"
-#include "jemalloc/internal/prng.h"
-#include "jemalloc/internal/ticker.h"
-#include "jemalloc/internal/ckh.h"
-#include "jemalloc/internal/size_classes.h"
-#include "jemalloc/internal/smoothstep.h"
-#include "jemalloc/internal/stats.h"
-#include "jemalloc/internal/ctl.h"
-#include "jemalloc/internal/witness.h"
-#include "jemalloc/internal/mutex.h"
-#include "jemalloc/internal/mb.h"
-#include "jemalloc/internal/bitmap.h"
-#define JEMALLOC_ARENA_STRUCTS_A
-#include "jemalloc/internal/arena.h"
-#undef JEMALLOC_ARENA_STRUCTS_A
-#include "jemalloc/internal/extent.h"
-#define JEMALLOC_ARENA_STRUCTS_B
-#include "jemalloc/internal/arena.h"
-#undef JEMALLOC_ARENA_STRUCTS_B
-#include "jemalloc/internal/base.h"
-#include "jemalloc/internal/rtree.h"
-#include "jemalloc/internal/pages.h"
-#include "jemalloc/internal/chunk.h"
-#include "jemalloc/internal/huge.h"
-#include "jemalloc/internal/tcache.h"
-#include "jemalloc/internal/hash.h"
-#include "jemalloc/internal/quarantine.h"
-#include "jemalloc/internal/prof.h"
-
-#include "jemalloc/internal/tsd.h"
-
-#undef JEMALLOC_H_STRUCTS
-/******************************************************************************/
-#define JEMALLOC_H_EXTERNS
-
-extern bool opt_abort;
-extern const char *opt_junk;
-extern bool opt_junk_alloc;
-extern bool opt_junk_free;
-extern size_t opt_quarantine;
-extern bool opt_redzone;
-extern bool opt_utrace;
-extern bool opt_xmalloc;
-extern bool opt_zero;
-extern unsigned opt_narenas;
-
-extern bool in_valgrind;
-
-/* Number of CPUs. */
-extern unsigned ncpus;
-
-/* Number of arenas used for automatic multiplexing of threads and arenas. */
-extern unsigned narenas_auto;
-
-/*
- * Arenas that are used to service external requests. Not all elements of the
- * arenas array are necessarily used; arenas are created lazily as needed.
- */
-extern arena_t **arenas;
-
-/*
- * pind2sz_tab encodes the same information as could be computed by
- * pind2sz_compute().
- */
-extern size_t const pind2sz_tab[NPSIZES];
-/*
- * index2size_tab encodes the same information as could be computed (at
- * unacceptable cost in some code paths) by index2size_compute().
- */
-extern size_t const index2size_tab[NSIZES];
-/*
- * size2index_tab is a compact lookup table that rounds request sizes up to
- * size classes. In order to reduce cache footprint, the table is compressed,
- * and all accesses are via size2index().
- */
-extern uint8_t const size2index_tab[];
-
-arena_t *a0get(void);
-void *a0malloc(size_t size);
-void a0dalloc(void *ptr);
-void *bootstrap_malloc(size_t size);
-void *bootstrap_calloc(size_t num, size_t size);
-void bootstrap_free(void *ptr);
-unsigned narenas_total_get(void);
-arena_t *arena_init(tsdn_t *tsdn, unsigned ind);
-arena_tdata_t *arena_tdata_get_hard(tsd_t *tsd, unsigned ind);
-arena_t *arena_choose_hard(tsd_t *tsd, bool internal);
-void arena_migrate(tsd_t *tsd, unsigned oldind, unsigned newind);
-void thread_allocated_cleanup(tsd_t *tsd);
-void thread_deallocated_cleanup(tsd_t *tsd);
-void iarena_cleanup(tsd_t *tsd);
-void arena_cleanup(tsd_t *tsd);
-void arenas_tdata_cleanup(tsd_t *tsd);
-void narenas_tdata_cleanup(tsd_t *tsd);
-void arenas_tdata_bypass_cleanup(tsd_t *tsd);
-void jemalloc_prefork(void);
-void jemalloc_postfork_parent(void);
-void jemalloc_postfork_child(void);
-
-#include "jemalloc/internal/nstime.h"
-#include "jemalloc/internal/valgrind.h"
-#include "jemalloc/internal/util.h"
-#include "jemalloc/internal/atomic.h"
-#include "jemalloc/internal/spin.h"
-#include "jemalloc/internal/prng.h"
-#include "jemalloc/internal/ticker.h"
-#include "jemalloc/internal/ckh.h"
-#include "jemalloc/internal/size_classes.h"
-#include "jemalloc/internal/smoothstep.h"
-#include "jemalloc/internal/stats.h"
-#include "jemalloc/internal/ctl.h"
-#include "jemalloc/internal/witness.h"
-#include "jemalloc/internal/mutex.h"
-#include "jemalloc/internal/mb.h"
-#include "jemalloc/internal/bitmap.h"
-#include "jemalloc/internal/extent.h"
-#include "jemalloc/internal/arena.h"
-#include "jemalloc/internal/base.h"
-#include "jemalloc/internal/rtree.h"
-#include "jemalloc/internal/pages.h"
-#include "jemalloc/internal/chunk.h"
-#include "jemalloc/internal/huge.h"
-#include "jemalloc/internal/tcache.h"
-#include "jemalloc/internal/hash.h"
-#include "jemalloc/internal/quarantine.h"
-#include "jemalloc/internal/prof.h"
-#include "jemalloc/internal/tsd.h"
-
-#undef JEMALLOC_H_EXTERNS
-/******************************************************************************/
-#define JEMALLOC_H_INLINES
-
-#include "jemalloc/internal/nstime.h"
-#include "jemalloc/internal/valgrind.h"
-#include "jemalloc/internal/util.h"
-#include "jemalloc/internal/atomic.h"
-#include "jemalloc/internal/spin.h"
-#include "jemalloc/internal/prng.h"
-#include "jemalloc/internal/ticker.h"
-#include "jemalloc/internal/ckh.h"
-#include "jemalloc/internal/size_classes.h"
-#include "jemalloc/internal/smoothstep.h"
-#include "jemalloc/internal/stats.h"
-#include "jemalloc/internal/ctl.h"
-#include "jemalloc/internal/tsd.h"
-#include "jemalloc/internal/witness.h"
-#include "jemalloc/internal/mutex.h"
-#include "jemalloc/internal/mb.h"
-#include "jemalloc/internal/extent.h"
-#include "jemalloc/internal/base.h"
-#include "jemalloc/internal/rtree.h"
-#include "jemalloc/internal/pages.h"
-#include "jemalloc/internal/chunk.h"
-#include "jemalloc/internal/huge.h"
-
-#ifndef JEMALLOC_ENABLE_INLINE
-pszind_t psz2ind(size_t psz);
-size_t pind2sz_compute(pszind_t pind);
-size_t pind2sz_lookup(pszind_t pind);
-size_t pind2sz(pszind_t pind);
-size_t psz2u(size_t psz);
-szind_t size2index_compute(size_t size);
-szind_t size2index_lookup(size_t size);
-szind_t size2index(size_t size);
-size_t index2size_compute(szind_t index);
-size_t index2size_lookup(szind_t index);
-size_t index2size(szind_t index);
-size_t s2u_compute(size_t size);
-size_t s2u_lookup(size_t size);
-size_t s2u(size_t size);
-size_t sa2u(size_t size, size_t alignment);
-arena_t *arena_choose_impl(tsd_t *tsd, arena_t *arena, bool internal);
-arena_t *arena_choose(tsd_t *tsd, arena_t *arena);
-arena_t *arena_ichoose(tsd_t *tsd, arena_t *arena);
-arena_tdata_t *arena_tdata_get(tsd_t *tsd, unsigned ind,
- bool refresh_if_missing);
-arena_t *arena_get(tsdn_t *tsdn, unsigned ind, bool init_if_missing);
-ticker_t *decay_ticker_get(tsd_t *tsd, unsigned ind);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_))
-JEMALLOC_INLINE pszind_t
-psz2ind(size_t psz)
-{
-
- if (unlikely(psz > HUGE_MAXCLASS))
- return (NPSIZES);
- {
- pszind_t x = lg_floor((psz<<1)-1);
- pszind_t shift = (x < LG_SIZE_CLASS_GROUP + LG_PAGE) ? 0 : x -
- (LG_SIZE_CLASS_GROUP + LG_PAGE);
- pszind_t grp = shift << LG_SIZE_CLASS_GROUP;
-
- pszind_t lg_delta = (x < LG_SIZE_CLASS_GROUP + LG_PAGE + 1) ?
- LG_PAGE : x - LG_SIZE_CLASS_GROUP - 1;
-
- size_t delta_inverse_mask = ZI(-1) << lg_delta;
- pszind_t mod = ((((psz-1) & delta_inverse_mask) >> lg_delta)) &
- ((ZU(1) << LG_SIZE_CLASS_GROUP) - 1);
-
- pszind_t ind = grp + mod;
- return (ind);
- }
-}
-
-JEMALLOC_INLINE size_t
-pind2sz_compute(pszind_t pind)
-{
-
- {
- size_t grp = pind >> LG_SIZE_CLASS_GROUP;
- size_t mod = pind & ((ZU(1) << LG_SIZE_CLASS_GROUP) - 1);
-
- size_t grp_size_mask = ~((!!grp)-1);
- size_t grp_size = ((ZU(1) << (LG_PAGE +
- (LG_SIZE_CLASS_GROUP-1))) << grp) & grp_size_mask;
-
- size_t shift = (grp == 0) ? 1 : grp;
- size_t lg_delta = shift + (LG_PAGE-1);
- size_t mod_size = (mod+1) << lg_delta;
-
- size_t sz = grp_size + mod_size;
- return (sz);
- }
-}
-
-JEMALLOC_INLINE size_t
-pind2sz_lookup(pszind_t pind)
-{
- size_t ret = (size_t)pind2sz_tab[pind];
- assert(ret == pind2sz_compute(pind));
- return (ret);
-}
-
-JEMALLOC_INLINE size_t
-pind2sz(pszind_t pind)
-{
-
- assert(pind < NPSIZES);
- return (pind2sz_lookup(pind));
-}
-
-JEMALLOC_INLINE size_t
-psz2u(size_t psz)
-{
-
- if (unlikely(psz > HUGE_MAXCLASS))
- return (0);
- {
- size_t x = lg_floor((psz<<1)-1);
- size_t lg_delta = (x < LG_SIZE_CLASS_GROUP + LG_PAGE + 1) ?
- LG_PAGE : x - LG_SIZE_CLASS_GROUP - 1;
- size_t delta = ZU(1) << lg_delta;
- size_t delta_mask = delta - 1;
- size_t usize = (psz + delta_mask) & ~delta_mask;
- return (usize);
- }
-}
-
-JEMALLOC_INLINE szind_t
-size2index_compute(size_t size)
-{
-
- if (unlikely(size > HUGE_MAXCLASS))
- return (NSIZES);
-#if (NTBINS != 0)
- if (size <= (ZU(1) << LG_TINY_MAXCLASS)) {
- szind_t lg_tmin = LG_TINY_MAXCLASS - NTBINS + 1;
- szind_t lg_ceil = lg_floor(pow2_ceil_zu(size));
- return (lg_ceil < lg_tmin ? 0 : lg_ceil - lg_tmin);
- }
-#endif
- {
- szind_t x = lg_floor((size<<1)-1);
- szind_t shift = (x < LG_SIZE_CLASS_GROUP + LG_QUANTUM) ? 0 :
- x - (LG_SIZE_CLASS_GROUP + LG_QUANTUM);
- szind_t grp = shift << LG_SIZE_CLASS_GROUP;
-
- szind_t lg_delta = (x < LG_SIZE_CLASS_GROUP + LG_QUANTUM + 1)
- ? LG_QUANTUM : x - LG_SIZE_CLASS_GROUP - 1;
-
- size_t delta_inverse_mask = ZI(-1) << lg_delta;
- szind_t mod = ((((size-1) & delta_inverse_mask) >> lg_delta)) &
- ((ZU(1) << LG_SIZE_CLASS_GROUP) - 1);
-
- szind_t index = NTBINS + grp + mod;
- return (index);
- }
-}
-
-JEMALLOC_ALWAYS_INLINE szind_t
-size2index_lookup(size_t size)
-{
-
- assert(size <= LOOKUP_MAXCLASS);
- {
- szind_t ret = (size2index_tab[(size-1) >> LG_TINY_MIN]);
- assert(ret == size2index_compute(size));
- return (ret);
- }
-}
-
-JEMALLOC_ALWAYS_INLINE szind_t
-size2index(size_t size)
-{
-
- assert(size > 0);
- if (likely(size <= LOOKUP_MAXCLASS))
- return (size2index_lookup(size));
- return (size2index_compute(size));
-}
-
-JEMALLOC_INLINE size_t
-index2size_compute(szind_t index)
-{
-
-#if (NTBINS > 0)
- if (index < NTBINS)
- return (ZU(1) << (LG_TINY_MAXCLASS - NTBINS + 1 + index));
-#endif
- {
- size_t reduced_index = index - NTBINS;
- size_t grp = reduced_index >> LG_SIZE_CLASS_GROUP;
- size_t mod = reduced_index & ((ZU(1) << LG_SIZE_CLASS_GROUP) -
- 1);
-
- size_t grp_size_mask = ~((!!grp)-1);
- size_t grp_size = ((ZU(1) << (LG_QUANTUM +
- (LG_SIZE_CLASS_GROUP-1))) << grp) & grp_size_mask;
-
- size_t shift = (grp == 0) ? 1 : grp;
- size_t lg_delta = shift + (LG_QUANTUM-1);
- size_t mod_size = (mod+1) << lg_delta;
-
- size_t usize = grp_size + mod_size;
- return (usize);
- }
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-index2size_lookup(szind_t index)
-{
- size_t ret = (size_t)index2size_tab[index];
- assert(ret == index2size_compute(index));
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-index2size(szind_t index)
-{
-
- assert(index < NSIZES);
- return (index2size_lookup(index));
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-s2u_compute(size_t size)
-{
-
- if (unlikely(size > HUGE_MAXCLASS))
- return (0);
-#if (NTBINS > 0)
- if (size <= (ZU(1) << LG_TINY_MAXCLASS)) {
- size_t lg_tmin = LG_TINY_MAXCLASS - NTBINS + 1;
- size_t lg_ceil = lg_floor(pow2_ceil_zu(size));
- return (lg_ceil < lg_tmin ? (ZU(1) << lg_tmin) :
- (ZU(1) << lg_ceil));
- }
-#endif
- {
- size_t x = lg_floor((size<<1)-1);
- size_t lg_delta = (x < LG_SIZE_CLASS_GROUP + LG_QUANTUM + 1)
- ? LG_QUANTUM : x - LG_SIZE_CLASS_GROUP - 1;
- size_t delta = ZU(1) << lg_delta;
- size_t delta_mask = delta - 1;
- size_t usize = (size + delta_mask) & ~delta_mask;
- return (usize);
- }
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-s2u_lookup(size_t size)
-{
- size_t ret = index2size_lookup(size2index_lookup(size));
-
- assert(ret == s2u_compute(size));
- return (ret);
-}
-
-/*
- * Compute usable size that would result from allocating an object with the
- * specified size.
- */
-JEMALLOC_ALWAYS_INLINE size_t
-s2u(size_t size)
-{
-
- assert(size > 0);
- if (likely(size <= LOOKUP_MAXCLASS))
- return (s2u_lookup(size));
- return (s2u_compute(size));
-}
-
-/*
- * Compute usable size that would result from allocating an object with the
- * specified size and alignment.
- */
-JEMALLOC_ALWAYS_INLINE size_t
-sa2u(size_t size, size_t alignment)
-{
- size_t usize;
-
- assert(alignment != 0 && ((alignment - 1) & alignment) == 0);
-
- /* Try for a small size class. */
- if (size <= SMALL_MAXCLASS && alignment < PAGE) {
- /*
- * Round size up to the nearest multiple of alignment.
- *
- * This done, we can take advantage of the fact that for each
- * small size class, every object is aligned at the smallest
- * power of two that is non-zero in the base two representation
- * of the size. For example:
- *
- * Size | Base 2 | Minimum alignment
- * -----+----------+------------------
- * 96 | 1100000 | 32
- * 144 | 10100000 | 32
- * 192 | 11000000 | 64
- */
- usize = s2u(ALIGNMENT_CEILING(size, alignment));
- if (usize < LARGE_MINCLASS)
- return (usize);
- }
-
- /* Try for a large size class. */
- if (likely(size <= large_maxclass) && likely(alignment < chunksize)) {
- /*
- * We can't achieve subpage alignment, so round up alignment
- * to the minimum that can actually be supported.
- */
- alignment = PAGE_CEILING(alignment);
-
- /* Make sure result is a large size class. */
- usize = (size <= LARGE_MINCLASS) ? LARGE_MINCLASS : s2u(size);
-
- /*
- * Calculate the size of the over-size run that arena_palloc()
- * would need to allocate in order to guarantee the alignment.
- */
- if (usize + large_pad + alignment - PAGE <= arena_maxrun)
- return (usize);
- }
-
- /* Huge size class. Beware of overflow. */
-
- if (unlikely(alignment > HUGE_MAXCLASS))
- return (0);
-
- /*
- * We can't achieve subchunk alignment, so round up alignment to the
- * minimum that can actually be supported.
- */
- alignment = CHUNK_CEILING(alignment);
-
- /* Make sure result is a huge size class. */
- if (size <= chunksize)
- usize = chunksize;
- else {
- usize = s2u(size);
- if (usize < size) {
- /* size_t overflow. */
- return (0);
- }
- }
-
- /*
- * Calculate the multi-chunk mapping that huge_palloc() would need in
- * order to guarantee the alignment.
- */
- if (usize + alignment - PAGE < usize) {
- /* size_t overflow. */
- return (0);
- }
- return (usize);
-}
-
-/* Choose an arena based on a per-thread value. */
-JEMALLOC_INLINE arena_t *
-arena_choose_impl(tsd_t *tsd, arena_t *arena, bool internal)
-{
- arena_t *ret;
-
- if (arena != NULL)
- return (arena);
-
- ret = internal ? tsd_iarena_get(tsd) : tsd_arena_get(tsd);
- if (unlikely(ret == NULL))
- ret = arena_choose_hard(tsd, internal);
-
- return (ret);
-}
-
-JEMALLOC_INLINE arena_t *
-arena_choose(tsd_t *tsd, arena_t *arena)
-{
-
- return (arena_choose_impl(tsd, arena, false));
-}
-
-JEMALLOC_INLINE arena_t *
-arena_ichoose(tsd_t *tsd, arena_t *arena)
-{
-
- return (arena_choose_impl(tsd, arena, true));
-}
-
-JEMALLOC_INLINE arena_tdata_t *
-arena_tdata_get(tsd_t *tsd, unsigned ind, bool refresh_if_missing)
-{
- arena_tdata_t *tdata;
- arena_tdata_t *arenas_tdata = tsd_arenas_tdata_get(tsd);
-
- if (unlikely(arenas_tdata == NULL)) {
- /* arenas_tdata hasn't been initialized yet. */
- return (arena_tdata_get_hard(tsd, ind));
- }
- if (unlikely(ind >= tsd_narenas_tdata_get(tsd))) {
- /*
- * ind is invalid, cache is old (too small), or tdata to be
- * initialized.
- */
- return (refresh_if_missing ? arena_tdata_get_hard(tsd, ind) :
- NULL);
- }
-
- tdata = &arenas_tdata[ind];
- if (likely(tdata != NULL) || !refresh_if_missing)
- return (tdata);
- return (arena_tdata_get_hard(tsd, ind));
-}
-
-JEMALLOC_INLINE arena_t *
-arena_get(tsdn_t *tsdn, unsigned ind, bool init_if_missing)
-{
- arena_t *ret;
-
- assert(ind <= MALLOCX_ARENA_MAX);
-
- ret = arenas[ind];
- if (unlikely(ret == NULL)) {
- ret = atomic_read_p((void *)&arenas[ind]);
- if (init_if_missing && unlikely(ret == NULL))
- ret = arena_init(tsdn, ind);
- }
- return (ret);
-}
-
-JEMALLOC_INLINE ticker_t *
-decay_ticker_get(tsd_t *tsd, unsigned ind)
-{
- arena_tdata_t *tdata;
-
- tdata = arena_tdata_get(tsd, ind, true);
- if (unlikely(tdata == NULL))
- return (NULL);
- return (&tdata->decay_ticker);
-}
-#endif
-
-#include "jemalloc/internal/bitmap.h"
-/*
- * Include portions of arena.h interleaved with tcache.h in order to resolve
- * circular dependencies.
- */
-#define JEMALLOC_ARENA_INLINE_A
-#include "jemalloc/internal/arena.h"
-#undef JEMALLOC_ARENA_INLINE_A
-#include "jemalloc/internal/tcache.h"
-#define JEMALLOC_ARENA_INLINE_B
-#include "jemalloc/internal/arena.h"
-#undef JEMALLOC_ARENA_INLINE_B
-#include "jemalloc/internal/hash.h"
-#include "jemalloc/internal/quarantine.h"
-
-#ifndef JEMALLOC_ENABLE_INLINE
-arena_t *iaalloc(const void *ptr);
-size_t isalloc(tsdn_t *tsdn, const void *ptr, bool demote);
-void *iallocztm(tsdn_t *tsdn, size_t size, szind_t ind, bool zero,
- tcache_t *tcache, bool is_metadata, arena_t *arena, bool slow_path);
-void *ialloc(tsd_t *tsd, size_t size, szind_t ind, bool zero,
- bool slow_path);
-void *ipallocztm(tsdn_t *tsdn, size_t usize, size_t alignment, bool zero,
- tcache_t *tcache, bool is_metadata, arena_t *arena);
-void *ipalloct(tsdn_t *tsdn, size_t usize, size_t alignment, bool zero,
- tcache_t *tcache, arena_t *arena);
-void *ipalloc(tsd_t *tsd, size_t usize, size_t alignment, bool zero);
-size_t ivsalloc(tsdn_t *tsdn, const void *ptr, bool demote);
-size_t u2rz(size_t usize);
-size_t p2rz(tsdn_t *tsdn, const void *ptr);
-void idalloctm(tsdn_t *tsdn, void *ptr, tcache_t *tcache, bool is_metadata,
- bool slow_path);
-void idalloc(tsd_t *tsd, void *ptr);
-void iqalloc(tsd_t *tsd, void *ptr, tcache_t *tcache, bool slow_path);
-void isdalloct(tsdn_t *tsdn, void *ptr, size_t size, tcache_t *tcache,
- bool slow_path);
-void isqalloc(tsd_t *tsd, void *ptr, size_t size, tcache_t *tcache,
- bool slow_path);
-void *iralloct_realign(tsd_t *tsd, void *ptr, size_t oldsize, size_t size,
- size_t extra, size_t alignment, bool zero, tcache_t *tcache,
- arena_t *arena);
-void *iralloct(tsd_t *tsd, void *ptr, size_t oldsize, size_t size,
- size_t alignment, bool zero, tcache_t *tcache, arena_t *arena);
-void *iralloc(tsd_t *tsd, void *ptr, size_t oldsize, size_t size,
- size_t alignment, bool zero);
-bool ixalloc(tsdn_t *tsdn, void *ptr, size_t oldsize, size_t size,
- size_t extra, size_t alignment, bool zero);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_C_))
-JEMALLOC_ALWAYS_INLINE arena_t *
-iaalloc(const void *ptr)
-{
-
- assert(ptr != NULL);
-
- return (arena_aalloc(ptr));
-}
-
-/*
- * Typical usage:
- * tsdn_t *tsdn = [...]
- * void *ptr = [...]
- * size_t sz = isalloc(tsdn, ptr, config_prof);
- */
-JEMALLOC_ALWAYS_INLINE size_t
-isalloc(tsdn_t *tsdn, const void *ptr, bool demote)
-{
-
- assert(ptr != NULL);
- /* Demotion only makes sense if config_prof is true. */
- assert(config_prof || !demote);
-
- return (arena_salloc(tsdn, ptr, demote));
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-iallocztm(tsdn_t *tsdn, size_t size, szind_t ind, bool zero, tcache_t *tcache,
- bool is_metadata, arena_t *arena, bool slow_path)
-{
- void *ret;
-
- assert(size != 0);
- assert(!is_metadata || tcache == NULL);
- assert(!is_metadata || arena == NULL || arena->ind < narenas_auto);
-
- ret = arena_malloc(tsdn, arena, size, ind, zero, tcache, slow_path);
- if (config_stats && is_metadata && likely(ret != NULL)) {
- arena_metadata_allocated_add(iaalloc(ret),
- isalloc(tsdn, ret, config_prof));
- }
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-ialloc(tsd_t *tsd, size_t size, szind_t ind, bool zero, bool slow_path)
-{
-
- return (iallocztm(tsd_tsdn(tsd), size, ind, zero, tcache_get(tsd, true),
- false, NULL, slow_path));
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-ipallocztm(tsdn_t *tsdn, size_t usize, size_t alignment, bool zero,
- tcache_t *tcache, bool is_metadata, arena_t *arena)
-{
- void *ret;
-
- assert(usize != 0);
- assert(usize == sa2u(usize, alignment));
- assert(!is_metadata || tcache == NULL);
- assert(!is_metadata || arena == NULL || arena->ind < narenas_auto);
-
- ret = arena_palloc(tsdn, arena, usize, alignment, zero, tcache);
- assert(ALIGNMENT_ADDR2BASE(ret, alignment) == ret);
- if (config_stats && is_metadata && likely(ret != NULL)) {
- arena_metadata_allocated_add(iaalloc(ret), isalloc(tsdn, ret,
- config_prof));
- }
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-ipalloct(tsdn_t *tsdn, size_t usize, size_t alignment, bool zero,
- tcache_t *tcache, arena_t *arena)
-{
-
- return (ipallocztm(tsdn, usize, alignment, zero, tcache, false, arena));
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-ipalloc(tsd_t *tsd, size_t usize, size_t alignment, bool zero)
-{
-
- return (ipallocztm(tsd_tsdn(tsd), usize, alignment, zero,
- tcache_get(tsd, true), false, NULL));
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-ivsalloc(tsdn_t *tsdn, const void *ptr, bool demote)
-{
- extent_node_t *node;
-
- /* Return 0 if ptr is not within a chunk managed by jemalloc. */
- node = chunk_lookup(ptr, false);
- if (node == NULL)
- return (0);
- /* Only arena chunks should be looked up via interior pointers. */
- assert(extent_node_addr_get(node) == ptr ||
- extent_node_achunk_get(node));
-
- return (isalloc(tsdn, ptr, demote));
-}
-
-JEMALLOC_INLINE size_t
-u2rz(size_t usize)
-{
- size_t ret;
-
- if (usize <= SMALL_MAXCLASS) {
- szind_t binind = size2index(usize);
- ret = arena_bin_info[binind].redzone_size;
- } else
- ret = 0;
-
- return (ret);
-}
-
-JEMALLOC_INLINE size_t
-p2rz(tsdn_t *tsdn, const void *ptr)
-{
- size_t usize = isalloc(tsdn, ptr, false);
-
- return (u2rz(usize));
-}
-
-JEMALLOC_ALWAYS_INLINE void
-idalloctm(tsdn_t *tsdn, void *ptr, tcache_t *tcache, bool is_metadata,
- bool slow_path)
-{
-
- assert(ptr != NULL);
- assert(!is_metadata || tcache == NULL);
- assert(!is_metadata || iaalloc(ptr)->ind < narenas_auto);
- if (config_stats && is_metadata) {
- arena_metadata_allocated_sub(iaalloc(ptr), isalloc(tsdn, ptr,
- config_prof));
- }
-
- arena_dalloc(tsdn, ptr, tcache, slow_path);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-idalloc(tsd_t *tsd, void *ptr)
-{
-
- idalloctm(tsd_tsdn(tsd), ptr, tcache_get(tsd, false), false, true);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-iqalloc(tsd_t *tsd, void *ptr, tcache_t *tcache, bool slow_path)
-{
-
- if (slow_path && config_fill && unlikely(opt_quarantine))
- quarantine(tsd, ptr);
- else
- idalloctm(tsd_tsdn(tsd), ptr, tcache, false, slow_path);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-isdalloct(tsdn_t *tsdn, void *ptr, size_t size, tcache_t *tcache,
- bool slow_path)
-{
-
- arena_sdalloc(tsdn, ptr, size, tcache, slow_path);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-isqalloc(tsd_t *tsd, void *ptr, size_t size, tcache_t *tcache, bool slow_path)
-{
-
- if (slow_path && config_fill && unlikely(opt_quarantine))
- quarantine(tsd, ptr);
- else
- isdalloct(tsd_tsdn(tsd), ptr, size, tcache, slow_path);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-iralloct_realign(tsd_t *tsd, void *ptr, size_t oldsize, size_t size,
- size_t extra, size_t alignment, bool zero, tcache_t *tcache, arena_t *arena)
-{
- void *p;
- size_t usize, copysize;
-
- usize = sa2u(size + extra, alignment);
- if (unlikely(usize == 0 || usize > HUGE_MAXCLASS))
- return (NULL);
- p = ipalloct(tsd_tsdn(tsd), usize, alignment, zero, tcache, arena);
- if (p == NULL) {
- if (extra == 0)
- return (NULL);
- /* Try again, without extra this time. */
- usize = sa2u(size, alignment);
- if (unlikely(usize == 0 || usize > HUGE_MAXCLASS))
- return (NULL);
- p = ipalloct(tsd_tsdn(tsd), usize, alignment, zero, tcache,
- arena);
- if (p == NULL)
- return (NULL);
- }
- /*
- * Copy at most size bytes (not size+extra), since the caller has no
- * expectation that the extra bytes will be reliably preserved.
- */
- copysize = (size < oldsize) ? size : oldsize;
- memcpy(p, ptr, copysize);
- isqalloc(tsd, ptr, oldsize, tcache, true);
- return (p);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-iralloct(tsd_t *tsd, void *ptr, size_t oldsize, size_t size, size_t alignment,
- bool zero, tcache_t *tcache, arena_t *arena)
-{
-
- assert(ptr != NULL);
- assert(size != 0);
-
- if (alignment != 0 && ((uintptr_t)ptr & ((uintptr_t)alignment-1))
- != 0) {
- /*
- * Existing object alignment is inadequate; allocate new space
- * and copy.
- */
- return (iralloct_realign(tsd, ptr, oldsize, size, 0, alignment,
- zero, tcache, arena));
- }
-
- return (arena_ralloc(tsd, arena, ptr, oldsize, size, alignment, zero,
- tcache));
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-iralloc(tsd_t *tsd, void *ptr, size_t oldsize, size_t size, size_t alignment,
- bool zero)
-{
-
- return (iralloct(tsd, ptr, oldsize, size, alignment, zero,
- tcache_get(tsd, true), NULL));
-}
-
-JEMALLOC_ALWAYS_INLINE bool
-ixalloc(tsdn_t *tsdn, void *ptr, size_t oldsize, size_t size, size_t extra,
- size_t alignment, bool zero)
-{
-
- assert(ptr != NULL);
- assert(size != 0);
-
- if (alignment != 0 && ((uintptr_t)ptr & ((uintptr_t)alignment-1))
- != 0) {
- /* Existing object alignment is inadequate. */
- return (true);
- }
-
- return (arena_ralloc_no_move(tsdn, ptr, oldsize, size, extra, zero));
-}
-#endif
-
-#include "jemalloc/internal/prof.h"
-
-#undef JEMALLOC_H_INLINES
-/******************************************************************************/
-#endif /* JEMALLOC_INTERNAL_H */
diff --git a/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_decls.h b/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_decls.h
deleted file mode 100644
index c907d9109..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_decls.h
+++ /dev/null
@@ -1,75 +0,0 @@
-#ifndef JEMALLOC_INTERNAL_DECLS_H
-#define JEMALLOC_INTERNAL_DECLS_H
-
-#include <math.h>
-#ifdef _WIN32
-# include <windows.h>
-# include "msvc_compat/windows_extra.h"
-
-#else
-# include <sys/param.h>
-# include <sys/mman.h>
-# if !defined(__pnacl__) && !defined(__native_client__)
-# include <sys/syscall.h>
-# if !defined(SYS_write) && defined(__NR_write)
-# define SYS_write __NR_write
-# endif
-# include <sys/uio.h>
-# endif
-# include <pthread.h>
-# ifdef JEMALLOC_OS_UNFAIR_LOCK
-# include <os/lock.h>
-# endif
-# ifdef JEMALLOC_GLIBC_MALLOC_HOOK
-# include <sched.h>
-# endif
-# include <errno.h>
-# include <sys/time.h>
-# include <time.h>
-# ifdef JEMALLOC_HAVE_MACH_ABSOLUTE_TIME
-# include <mach/mach_time.h>
-# endif
-#endif
-#include <sys/types.h>
-
-#include <limits.h>
-#ifndef SIZE_T_MAX
-# define SIZE_T_MAX SIZE_MAX
-#endif
-#include <stdarg.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stddef.h>
-#ifndef offsetof
-# define offsetof(type, member) ((size_t)&(((type *)NULL)->member))
-#endif
-#include <string.h>
-#include <strings.h>
-#include <ctype.h>
-#ifdef _MSC_VER
-# include <io.h>
-typedef intptr_t ssize_t;
-# define PATH_MAX 1024
-# define STDERR_FILENO 2
-# define __func__ __FUNCTION__
-# ifdef JEMALLOC_HAS_RESTRICT
-# define restrict __restrict
-# endif
-/* Disable warnings about deprecated system functions. */
-# pragma warning(disable: 4996)
-#if _MSC_VER < 1800
-static int
-isblank(int c)
-{
-
- return (c == '\t' || c == ' ');
-}
-#endif
-#else
-# include <unistd.h>
-#endif
-#include <fcntl.h>
-
-#endif /* JEMALLOC_INTERNAL_H */
diff --git a/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_defs.h.in b/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_defs.h.in
deleted file mode 100644
index 9b3dca504..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_defs.h.in
+++ /dev/null
@@ -1,307 +0,0 @@
-#ifndef JEMALLOC_INTERNAL_DEFS_H_
-#define JEMALLOC_INTERNAL_DEFS_H_
-/*
- * If JEMALLOC_PREFIX is defined via --with-jemalloc-prefix, it will cause all
- * public APIs to be prefixed. This makes it possible, with some care, to use
- * multiple allocators simultaneously.
- */
-#undef JEMALLOC_PREFIX
-#undef JEMALLOC_CPREFIX
-
-/*
- * JEMALLOC_PRIVATE_NAMESPACE is used as a prefix for all library-private APIs.
- * For shared libraries, symbol visibility mechanisms prevent these symbols
- * from being exported, but for static libraries, naming collisions are a real
- * possibility.
- */
-#undef JEMALLOC_PRIVATE_NAMESPACE
-
-/*
- * Hyper-threaded CPUs may need a special instruction inside spin loops in
- * order to yield to another virtual CPU.
- */
-#undef CPU_SPINWAIT
-
-/* Defined if C11 atomics are available. */
-#undef JEMALLOC_C11ATOMICS
-
-/* Defined if the equivalent of FreeBSD's atomic(9) functions are available. */
-#undef JEMALLOC_ATOMIC9
-
-/*
- * Defined if OSAtomic*() functions are available, as provided by Darwin, and
- * documented in the atomic(3) manual page.
- */
-#undef JEMALLOC_OSATOMIC
-
-/*
- * Defined if __sync_add_and_fetch(uint32_t *, uint32_t) and
- * __sync_sub_and_fetch(uint32_t *, uint32_t) are available, despite
- * __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 not being defined (which means the
- * functions are defined in libgcc instead of being inlines).
- */
-#undef JE_FORCE_SYNC_COMPARE_AND_SWAP_4
-
-/*
- * Defined if __sync_add_and_fetch(uint64_t *, uint64_t) and
- * __sync_sub_and_fetch(uint64_t *, uint64_t) are available, despite
- * __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 not being defined (which means the
- * functions are defined in libgcc instead of being inlines).
- */
-#undef JE_FORCE_SYNC_COMPARE_AND_SWAP_8
-
-/*
- * Defined if __builtin_clz() and __builtin_clzl() are available.
- */
-#undef JEMALLOC_HAVE_BUILTIN_CLZ
-
-/*
- * Defined if madvise(2) is available.
- */
-#undef JEMALLOC_HAVE_MADVISE
-
-/*
- * Defined if os_unfair_lock_*() functions are available, as provided by Darwin.
- */
-#undef JEMALLOC_OS_UNFAIR_LOCK
-
-/*
- * Defined if OSSpin*() functions are available, as provided by Darwin, and
- * documented in the spinlock(3) manual page.
- */
-#undef JEMALLOC_OSSPIN
-
-/* Defined if syscall(2) is available. */
-#undef JEMALLOC_HAVE_SYSCALL
-
-/*
- * Defined if secure_getenv(3) is available.
- */
-#undef JEMALLOC_HAVE_SECURE_GETENV
-
-/*
- * Defined if issetugid(2) is available.
- */
-#undef JEMALLOC_HAVE_ISSETUGID
-
-/*
- * Defined if clock_gettime(CLOCK_MONOTONIC_COARSE, ...) is available.
- */
-#undef JEMALLOC_HAVE_CLOCK_MONOTONIC_COARSE
-
-/*
- * Defined if clock_gettime(CLOCK_MONOTONIC, ...) is available.
- */
-#undef JEMALLOC_HAVE_CLOCK_MONOTONIC
-
-/*
- * Defined if mach_absolute_time() is available.
- */
-#undef JEMALLOC_HAVE_MACH_ABSOLUTE_TIME
-
-/*
- * Defined if _malloc_thread_cleanup() exists. At least in the case of
- * FreeBSD, pthread_key_create() allocates, which if used during malloc
- * bootstrapping will cause recursion into the pthreads library. Therefore, if
- * _malloc_thread_cleanup() exists, use it as the basis for thread cleanup in
- * malloc_tsd.
- */
-#undef JEMALLOC_MALLOC_THREAD_CLEANUP
-
-/*
- * Defined if threaded initialization is known to be safe on this platform.
- * Among other things, it must be possible to initialize a mutex without
- * triggering allocation in order for threaded allocation to be safe.
- */
-#undef JEMALLOC_THREADED_INIT
-
-/*
- * Defined if the pthreads implementation defines
- * _pthread_mutex_init_calloc_cb(), in which case the function is used in order
- * to avoid recursive allocation during mutex initialization.
- */
-#undef JEMALLOC_MUTEX_INIT_CB
-
-/* Non-empty if the tls_model attribute is supported. */
-#undef JEMALLOC_TLS_MODEL
-
-/* JEMALLOC_CC_SILENCE enables code that silences unuseful compiler warnings. */
-#undef JEMALLOC_CC_SILENCE
-
-/* JEMALLOC_CODE_COVERAGE enables test code coverage analysis. */
-#undef JEMALLOC_CODE_COVERAGE
-
-/*
- * JEMALLOC_DEBUG enables assertions and other sanity checks, and disables
- * inline functions.
- */
-#undef JEMALLOC_DEBUG
-
-/* JEMALLOC_STATS enables statistics calculation. */
-#undef JEMALLOC_STATS
-
-/* JEMALLOC_PROF enables allocation profiling. */
-#undef JEMALLOC_PROF
-
-/* Use libunwind for profile backtracing if defined. */
-#undef JEMALLOC_PROF_LIBUNWIND
-
-/* Use libgcc for profile backtracing if defined. */
-#undef JEMALLOC_PROF_LIBGCC
-
-/* Use gcc intrinsics for profile backtracing if defined. */
-#undef JEMALLOC_PROF_GCC
-
-/*
- * JEMALLOC_TCACHE enables a thread-specific caching layer for small objects.
- * This makes it possible to allocate/deallocate objects without any locking
- * when the cache is in the steady state.
- */
-#undef JEMALLOC_TCACHE
-
-/*
- * JEMALLOC_DSS enables use of sbrk(2) to allocate chunks from the data storage
- * segment (DSS).
- */
-#undef JEMALLOC_DSS
-
-/* Support memory filling (junk/zero/quarantine/redzone). */
-#undef JEMALLOC_FILL
-
-/* Support utrace(2)-based tracing. */
-#undef JEMALLOC_UTRACE
-
-/* Support Valgrind. */
-#undef JEMALLOC_VALGRIND
-
-/* Support optional abort() on OOM. */
-#undef JEMALLOC_XMALLOC
-
-/* Support lazy locking (avoid locking unless a second thread is launched). */
-#undef JEMALLOC_LAZY_LOCK
-
-/* Minimum size class to support is 2^LG_TINY_MIN bytes. */
-#undef LG_TINY_MIN
-
-/*
- * Minimum allocation alignment is 2^LG_QUANTUM bytes (ignoring tiny size
- * classes).
- */
-#undef LG_QUANTUM
-
-/* One page is 2^LG_PAGE bytes. */
-#undef LG_PAGE
-
-/*
- * If defined, adjacent virtual memory mappings with identical attributes
- * automatically coalesce, and they fragment when changes are made to subranges.
- * This is the normal order of things for mmap()/munmap(), but on Windows
- * VirtualAlloc()/VirtualFree() operations must be precisely matched, i.e.
- * mappings do *not* coalesce/fragment.
- */
-#undef JEMALLOC_MAPS_COALESCE
-
-/*
- * If defined, use munmap() to unmap freed chunks, rather than storing them for
- * later reuse. This is disabled by default on Linux because common sequences
- * of mmap()/munmap() calls will cause virtual memory map holes.
- */
-#undef JEMALLOC_MUNMAP
-
-/* TLS is used to map arenas and magazine caches to threads. */
-#undef JEMALLOC_TLS
-
-/*
- * Used to mark unreachable code to quiet "end of non-void" compiler warnings.
- * Don't use this directly; instead use unreachable() from util.h
- */
-#undef JEMALLOC_INTERNAL_UNREACHABLE
-
-/*
- * ffs*() functions to use for bitmapping. Don't use these directly; instead,
- * use ffs_*() from util.h.
- */
-#undef JEMALLOC_INTERNAL_FFSLL
-#undef JEMALLOC_INTERNAL_FFSL
-#undef JEMALLOC_INTERNAL_FFS
-
-/*
- * JEMALLOC_IVSALLOC enables ivsalloc(), which verifies that pointers reside
- * within jemalloc-owned chunks before dereferencing them.
- */
-#undef JEMALLOC_IVSALLOC
-
-/*
- * If defined, explicitly attempt to more uniformly distribute large allocation
- * pointer alignments across all cache indices.
- */
-#undef JEMALLOC_CACHE_OBLIVIOUS
-
-/*
- * Darwin (OS X) uses zones to work around Mach-O symbol override shortcomings.
- */
-#undef JEMALLOC_ZONE
-#undef JEMALLOC_ZONE_VERSION
-
-/*
- * Methods for determining whether the OS overcommits.
- * JEMALLOC_PROC_SYS_VM_OVERCOMMIT_MEMORY: Linux's
- * /proc/sys/vm.overcommit_memory file.
- * JEMALLOC_SYSCTL_VM_OVERCOMMIT: FreeBSD's vm.overcommit sysctl.
- */
-#undef JEMALLOC_SYSCTL_VM_OVERCOMMIT
-#undef JEMALLOC_PROC_SYS_VM_OVERCOMMIT_MEMORY
-
-/*
- * Methods for purging unused pages differ between operating systems.
- *
- * madvise(..., MADV_DONTNEED) : On Linux, this immediately discards pages,
- * such that new pages will be demand-zeroed if
- * the address region is later touched.
- * madvise(..., MADV_FREE) : On FreeBSD and Darwin, this marks pages as being
- * unused, such that they will be discarded rather
- * than swapped out.
- */
-#undef JEMALLOC_PURGE_MADVISE_DONTNEED
-#undef JEMALLOC_PURGE_MADVISE_FREE
-
-/* Define if operating system has alloca.h header. */
-#undef JEMALLOC_HAS_ALLOCA_H
-
-/* C99 restrict keyword supported. */
-#undef JEMALLOC_HAS_RESTRICT
-
-/* For use by hash code. */
-#undef JEMALLOC_BIG_ENDIAN
-
-/* sizeof(int) == 2^LG_SIZEOF_INT. */
-#undef LG_SIZEOF_INT
-
-/* sizeof(long) == 2^LG_SIZEOF_LONG. */
-#undef LG_SIZEOF_LONG
-
-/* sizeof(long long) == 2^LG_SIZEOF_LONG_LONG. */
-#undef LG_SIZEOF_LONG_LONG
-
-/* sizeof(intmax_t) == 2^LG_SIZEOF_INTMAX_T. */
-#undef LG_SIZEOF_INTMAX_T
-
-/* glibc malloc hooks (__malloc_hook, __realloc_hook, __free_hook). */
-#undef JEMALLOC_GLIBC_MALLOC_HOOK
-
-/* glibc memalign hook. */
-#undef JEMALLOC_GLIBC_MEMALIGN_HOOK
-
-/* Adaptive mutex support in pthreads. */
-#undef JEMALLOC_HAVE_PTHREAD_MUTEX_ADAPTIVE_NP
-
-/*
- * If defined, jemalloc symbols are not exported (doesn't work when
- * JEMALLOC_PREFIX is not defined).
- */
-#undef JEMALLOC_EXPORT
-
-/* config.malloc_conf options string. */
-#undef JEMALLOC_CONFIG_MALLOC_CONF
-
-#endif /* JEMALLOC_INTERNAL_DEFS_H_ */
diff --git a/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_macros.h b/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_macros.h
deleted file mode 100644
index a08ba772e..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/jemalloc_internal_macros.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * JEMALLOC_ALWAYS_INLINE and JEMALLOC_INLINE are used within header files for
- * functions that are static inline functions if inlining is enabled, and
- * single-definition library-private functions if inlining is disabled.
- *
- * JEMALLOC_ALWAYS_INLINE_C and JEMALLOC_INLINE_C are for use in .c files, in
- * which case the denoted functions are always static, regardless of whether
- * inlining is enabled.
- */
-#if defined(JEMALLOC_DEBUG) || defined(JEMALLOC_CODE_COVERAGE)
- /* Disable inlining to make debugging/profiling easier. */
-# define JEMALLOC_ALWAYS_INLINE
-# define JEMALLOC_ALWAYS_INLINE_C static
-# define JEMALLOC_INLINE
-# define JEMALLOC_INLINE_C static
-# define inline
-#else
-# define JEMALLOC_ENABLE_INLINE
-# ifdef JEMALLOC_HAVE_ATTR
-# define JEMALLOC_ALWAYS_INLINE \
- static inline JEMALLOC_ATTR(unused) JEMALLOC_ATTR(always_inline)
-# define JEMALLOC_ALWAYS_INLINE_C \
- static inline JEMALLOC_ATTR(always_inline)
-# else
-# define JEMALLOC_ALWAYS_INLINE static inline
-# define JEMALLOC_ALWAYS_INLINE_C static inline
-# endif
-# define JEMALLOC_INLINE static inline
-# define JEMALLOC_INLINE_C static inline
-# ifdef _MSC_VER
-# define inline _inline
-# endif
-#endif
-
-#ifdef JEMALLOC_CC_SILENCE
-# define UNUSED JEMALLOC_ATTR(unused)
-#else
-# define UNUSED
-#endif
-
-#define ZU(z) ((size_t)z)
-#define ZI(z) ((ssize_t)z)
-#define QU(q) ((uint64_t)q)
-#define QI(q) ((int64_t)q)
-
-#define KZU(z) ZU(z##ULL)
-#define KZI(z) ZI(z##LL)
-#define KQU(q) QU(q##ULL)
-#define KQI(q) QI(q##LL)
-
-#ifndef __DECONST
-# define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var))
-#endif
-
-#ifndef JEMALLOC_HAS_RESTRICT
-# define restrict
-#endif
diff --git a/memory/jemalloc/src/include/jemalloc/internal/mb.h b/memory/jemalloc/src/include/jemalloc/internal/mb.h
deleted file mode 100644
index 5384728fd..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/mb.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-void mb_write(void);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_MB_C_))
-#ifdef __i386__
-/*
- * According to the Intel Architecture Software Developer's Manual, current
- * processors execute instructions in order from the perspective of other
- * processors in a multiprocessor system, but 1) Intel reserves the right to
- * change that, and 2) the compiler's optimizer could re-order instructions if
- * there weren't some form of barrier. Therefore, even if running on an
- * architecture that does not need memory barriers (everything through at least
- * i686), an "optimizer barrier" is necessary.
- */
-JEMALLOC_INLINE void
-mb_write(void)
-{
-
-# if 0
- /* This is a true memory barrier. */
- asm volatile ("pusha;"
- "xor %%eax,%%eax;"
- "cpuid;"
- "popa;"
- : /* Outputs. */
- : /* Inputs. */
- : "memory" /* Clobbers. */
- );
-# else
- /*
- * This is hopefully enough to keep the compiler from reordering
- * instructions around this one.
- */
- asm volatile ("nop;"
- : /* Outputs. */
- : /* Inputs. */
- : "memory" /* Clobbers. */
- );
-# endif
-}
-#elif (defined(__amd64__) || defined(__x86_64__))
-JEMALLOC_INLINE void
-mb_write(void)
-{
-
- asm volatile ("sfence"
- : /* Outputs. */
- : /* Inputs. */
- : "memory" /* Clobbers. */
- );
-}
-#elif defined(__powerpc__)
-JEMALLOC_INLINE void
-mb_write(void)
-{
-
- asm volatile ("eieio"
- : /* Outputs. */
- : /* Inputs. */
- : "memory" /* Clobbers. */
- );
-}
-#elif defined(__sparc64__)
-JEMALLOC_INLINE void
-mb_write(void)
-{
-
- asm volatile ("membar #StoreStore"
- : /* Outputs. */
- : /* Inputs. */
- : "memory" /* Clobbers. */
- );
-}
-#elif defined(__tile__)
-JEMALLOC_INLINE void
-mb_write(void)
-{
-
- __sync_synchronize();
-}
-#else
-/*
- * This is much slower than a simple memory barrier, but the semantics of mutex
- * unlock make this work.
- */
-JEMALLOC_INLINE void
-mb_write(void)
-{
- malloc_mutex_t mtx;
-
- malloc_mutex_init(&mtx, "mb", WITNESS_RANK_OMIT);
- malloc_mutex_lock(TSDN_NULL, &mtx);
- malloc_mutex_unlock(TSDN_NULL, &mtx);
-}
-#endif
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/mutex.h b/memory/jemalloc/src/include/jemalloc/internal/mutex.h
deleted file mode 100644
index b442d2d4e..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/mutex.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct malloc_mutex_s malloc_mutex_t;
-
-#ifdef _WIN32
-# define MALLOC_MUTEX_INITIALIZER
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
-# define MALLOC_MUTEX_INITIALIZER \
- {OS_UNFAIR_LOCK_INIT, WITNESS_INITIALIZER(WITNESS_RANK_OMIT)}
-#elif (defined(JEMALLOC_OSSPIN))
-# define MALLOC_MUTEX_INITIALIZER {0, WITNESS_INITIALIZER(WITNESS_RANK_OMIT)}
-#elif (defined(JEMALLOC_MUTEX_INIT_CB))
-# define MALLOC_MUTEX_INITIALIZER \
- {PTHREAD_MUTEX_INITIALIZER, NULL, WITNESS_INITIALIZER(WITNESS_RANK_OMIT)}
-#else
-# if (defined(JEMALLOC_HAVE_PTHREAD_MUTEX_ADAPTIVE_NP) && \
- defined(PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP))
-# define MALLOC_MUTEX_TYPE PTHREAD_MUTEX_ADAPTIVE_NP
-# define MALLOC_MUTEX_INITIALIZER \
- {PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP, \
- WITNESS_INITIALIZER(WITNESS_RANK_OMIT)}
-# else
-# define MALLOC_MUTEX_TYPE PTHREAD_MUTEX_DEFAULT
-# define MALLOC_MUTEX_INITIALIZER \
- {PTHREAD_MUTEX_INITIALIZER, WITNESS_INITIALIZER(WITNESS_RANK_OMIT)}
-# endif
-#endif
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct malloc_mutex_s {
-#ifdef _WIN32
-# if _WIN32_WINNT >= 0x0600
- SRWLOCK lock;
-# else
- CRITICAL_SECTION lock;
-# endif
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
- os_unfair_lock lock;
-#elif (defined(JEMALLOC_OSSPIN))
- OSSpinLock lock;
-#elif (defined(JEMALLOC_MUTEX_INIT_CB))
- pthread_mutex_t lock;
- malloc_mutex_t *postponed_next;
-#else
- pthread_mutex_t lock;
-#endif
- witness_t witness;
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-#ifdef JEMALLOC_LAZY_LOCK
-extern bool isthreaded;
-#else
-# undef isthreaded /* Undo private_namespace.h definition. */
-# define isthreaded true
-#endif
-
-bool malloc_mutex_init(malloc_mutex_t *mutex, const char *name,
- witness_rank_t rank);
-void malloc_mutex_prefork(tsdn_t *tsdn, malloc_mutex_t *mutex);
-void malloc_mutex_postfork_parent(tsdn_t *tsdn, malloc_mutex_t *mutex);
-void malloc_mutex_postfork_child(tsdn_t *tsdn, malloc_mutex_t *mutex);
-bool malloc_mutex_boot(void);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-void malloc_mutex_lock(tsdn_t *tsdn, malloc_mutex_t *mutex);
-void malloc_mutex_unlock(tsdn_t *tsdn, malloc_mutex_t *mutex);
-void malloc_mutex_assert_owner(tsdn_t *tsdn, malloc_mutex_t *mutex);
-void malloc_mutex_assert_not_owner(tsdn_t *tsdn, malloc_mutex_t *mutex);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_MUTEX_C_))
-JEMALLOC_INLINE void
-malloc_mutex_lock(tsdn_t *tsdn, malloc_mutex_t *mutex)
-{
-
- if (isthreaded) {
- witness_assert_not_owner(tsdn, &mutex->witness);
-#ifdef _WIN32
-# if _WIN32_WINNT >= 0x0600
- AcquireSRWLockExclusive(&mutex->lock);
-# else
- EnterCriticalSection(&mutex->lock);
-# endif
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
- os_unfair_lock_lock(&mutex->lock);
-#elif (defined(JEMALLOC_OSSPIN))
- OSSpinLockLock(&mutex->lock);
-#else
- pthread_mutex_lock(&mutex->lock);
-#endif
- witness_lock(tsdn, &mutex->witness);
- }
-}
-
-JEMALLOC_INLINE void
-malloc_mutex_unlock(tsdn_t *tsdn, malloc_mutex_t *mutex)
-{
-
- if (isthreaded) {
- witness_unlock(tsdn, &mutex->witness);
-#ifdef _WIN32
-# if _WIN32_WINNT >= 0x0600
- ReleaseSRWLockExclusive(&mutex->lock);
-# else
- LeaveCriticalSection(&mutex->lock);
-# endif
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
- os_unfair_lock_unlock(&mutex->lock);
-#elif (defined(JEMALLOC_OSSPIN))
- OSSpinLockUnlock(&mutex->lock);
-#else
- pthread_mutex_unlock(&mutex->lock);
-#endif
- }
-}
-
-JEMALLOC_INLINE void
-malloc_mutex_assert_owner(tsdn_t *tsdn, malloc_mutex_t *mutex)
-{
-
- if (isthreaded)
- witness_assert_owner(tsdn, &mutex->witness);
-}
-
-JEMALLOC_INLINE void
-malloc_mutex_assert_not_owner(tsdn_t *tsdn, malloc_mutex_t *mutex)
-{
-
- if (isthreaded)
- witness_assert_not_owner(tsdn, &mutex->witness);
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/nstime.h b/memory/jemalloc/src/include/jemalloc/internal/nstime.h
deleted file mode 100644
index 93b27dc80..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/nstime.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct nstime_s nstime_t;
-
-/* Maximum supported number of seconds (~584 years). */
-#define NSTIME_SEC_MAX KQU(18446744072)
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct nstime_s {
- uint64_t ns;
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void nstime_init(nstime_t *time, uint64_t ns);
-void nstime_init2(nstime_t *time, uint64_t sec, uint64_t nsec);
-uint64_t nstime_ns(const nstime_t *time);
-uint64_t nstime_sec(const nstime_t *time);
-uint64_t nstime_nsec(const nstime_t *time);
-void nstime_copy(nstime_t *time, const nstime_t *source);
-int nstime_compare(const nstime_t *a, const nstime_t *b);
-void nstime_add(nstime_t *time, const nstime_t *addend);
-void nstime_subtract(nstime_t *time, const nstime_t *subtrahend);
-void nstime_imultiply(nstime_t *time, uint64_t multiplier);
-void nstime_idivide(nstime_t *time, uint64_t divisor);
-uint64_t nstime_divide(const nstime_t *time, const nstime_t *divisor);
-#ifdef JEMALLOC_JET
-typedef bool (nstime_monotonic_t)(void);
-extern nstime_monotonic_t *nstime_monotonic;
-typedef bool (nstime_update_t)(nstime_t *);
-extern nstime_update_t *nstime_update;
-#else
-bool nstime_monotonic(void);
-bool nstime_update(nstime_t *time);
-#endif
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/pages.h b/memory/jemalloc/src/include/jemalloc/internal/pages.h
deleted file mode 100644
index e21effd14..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/pages.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void *pages_map(void *addr, size_t size, bool *commit);
-void pages_unmap(void *addr, size_t size);
-void *pages_trim(void *addr, size_t alloc_size, size_t leadsize,
- size_t size, bool *commit);
-bool pages_commit(void *addr, size_t size);
-bool pages_decommit(void *addr, size_t size);
-bool pages_purge(void *addr, size_t size);
-void pages_boot(void);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-
diff --git a/memory/jemalloc/src/include/jemalloc/internal/ph.h b/memory/jemalloc/src/include/jemalloc/internal/ph.h
deleted file mode 100644
index 4f91c333f..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/ph.h
+++ /dev/null
@@ -1,345 +0,0 @@
-/*
- * A Pairing Heap implementation.
- *
- * "The Pairing Heap: A New Form of Self-Adjusting Heap"
- * https://www.cs.cmu.edu/~sleator/papers/pairing-heaps.pdf
- *
- * With auxiliary twopass list, described in a follow on paper.
- *
- * "Pairing Heaps: Experiments and Analysis"
- * http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.106.2988&rep=rep1&type=pdf
- *
- *******************************************************************************
- */
-
-#ifndef PH_H_
-#define PH_H_
-
-/* Node structure. */
-#define phn(a_type) \
-struct { \
- a_type *phn_prev; \
- a_type *phn_next; \
- a_type *phn_lchild; \
-}
-
-/* Root structure. */
-#define ph(a_type) \
-struct { \
- a_type *ph_root; \
-}
-
-/* Internal utility macros. */
-#define phn_lchild_get(a_type, a_field, a_phn) \
- (a_phn->a_field.phn_lchild)
-#define phn_lchild_set(a_type, a_field, a_phn, a_lchild) do { \
- a_phn->a_field.phn_lchild = a_lchild; \
-} while (0)
-
-#define phn_next_get(a_type, a_field, a_phn) \
- (a_phn->a_field.phn_next)
-#define phn_prev_set(a_type, a_field, a_phn, a_prev) do { \
- a_phn->a_field.phn_prev = a_prev; \
-} while (0)
-
-#define phn_prev_get(a_type, a_field, a_phn) \
- (a_phn->a_field.phn_prev)
-#define phn_next_set(a_type, a_field, a_phn, a_next) do { \
- a_phn->a_field.phn_next = a_next; \
-} while (0)
-
-#define phn_merge_ordered(a_type, a_field, a_phn0, a_phn1, a_cmp) do { \
- a_type *phn0child; \
- \
- assert(a_phn0 != NULL); \
- assert(a_phn1 != NULL); \
- assert(a_cmp(a_phn0, a_phn1) <= 0); \
- \
- phn_prev_set(a_type, a_field, a_phn1, a_phn0); \
- phn0child = phn_lchild_get(a_type, a_field, a_phn0); \
- phn_next_set(a_type, a_field, a_phn1, phn0child); \
- if (phn0child != NULL) \
- phn_prev_set(a_type, a_field, phn0child, a_phn1); \
- phn_lchild_set(a_type, a_field, a_phn0, a_phn1); \
-} while (0)
-
-#define phn_merge(a_type, a_field, a_phn0, a_phn1, a_cmp, r_phn) do { \
- if (a_phn0 == NULL) \
- r_phn = a_phn1; \
- else if (a_phn1 == NULL) \
- r_phn = a_phn0; \
- else if (a_cmp(a_phn0, a_phn1) < 0) { \
- phn_merge_ordered(a_type, a_field, a_phn0, a_phn1, \
- a_cmp); \
- r_phn = a_phn0; \
- } else { \
- phn_merge_ordered(a_type, a_field, a_phn1, a_phn0, \
- a_cmp); \
- r_phn = a_phn1; \
- } \
-} while (0)
-
-#define ph_merge_siblings(a_type, a_field, a_phn, a_cmp, r_phn) do { \
- a_type *head = NULL; \
- a_type *tail = NULL; \
- a_type *phn0 = a_phn; \
- a_type *phn1 = phn_next_get(a_type, a_field, phn0); \
- \
- /* \
- * Multipass merge, wherein the first two elements of a FIFO \
- * are repeatedly merged, and each result is appended to the \
- * singly linked FIFO, until the FIFO contains only a single \
- * element. We start with a sibling list but no reference to \
- * its tail, so we do a single pass over the sibling list to \
- * populate the FIFO. \
- */ \
- if (phn1 != NULL) { \
- a_type *phnrest = phn_next_get(a_type, a_field, phn1); \
- if (phnrest != NULL) \
- phn_prev_set(a_type, a_field, phnrest, NULL); \
- phn_prev_set(a_type, a_field, phn0, NULL); \
- phn_next_set(a_type, a_field, phn0, NULL); \
- phn_prev_set(a_type, a_field, phn1, NULL); \
- phn_next_set(a_type, a_field, phn1, NULL); \
- phn_merge(a_type, a_field, phn0, phn1, a_cmp, phn0); \
- head = tail = phn0; \
- phn0 = phnrest; \
- while (phn0 != NULL) { \
- phn1 = phn_next_get(a_type, a_field, phn0); \
- if (phn1 != NULL) { \
- phnrest = phn_next_get(a_type, a_field, \
- phn1); \
- if (phnrest != NULL) { \
- phn_prev_set(a_type, a_field, \
- phnrest, NULL); \
- } \
- phn_prev_set(a_type, a_field, phn0, \
- NULL); \
- phn_next_set(a_type, a_field, phn0, \
- NULL); \
- phn_prev_set(a_type, a_field, phn1, \
- NULL); \
- phn_next_set(a_type, a_field, phn1, \
- NULL); \
- phn_merge(a_type, a_field, phn0, phn1, \
- a_cmp, phn0); \
- phn_next_set(a_type, a_field, tail, \
- phn0); \
- tail = phn0; \
- phn0 = phnrest; \
- } else { \
- phn_next_set(a_type, a_field, tail, \
- phn0); \
- tail = phn0; \
- phn0 = NULL; \
- } \
- } \
- phn0 = head; \
- phn1 = phn_next_get(a_type, a_field, phn0); \
- if (phn1 != NULL) { \
- while (true) { \
- head = phn_next_get(a_type, a_field, \
- phn1); \
- assert(phn_prev_get(a_type, a_field, \
- phn0) == NULL); \
- phn_next_set(a_type, a_field, phn0, \
- NULL); \
- assert(phn_prev_get(a_type, a_field, \
- phn1) == NULL); \
- phn_next_set(a_type, a_field, phn1, \
- NULL); \
- phn_merge(a_type, a_field, phn0, phn1, \
- a_cmp, phn0); \
- if (head == NULL) \
- break; \
- phn_next_set(a_type, a_field, tail, \
- phn0); \
- tail = phn0; \
- phn0 = head; \
- phn1 = phn_next_get(a_type, a_field, \
- phn0); \
- } \
- } \
- } \
- r_phn = phn0; \
-} while (0)
-
-#define ph_merge_aux(a_type, a_field, a_ph, a_cmp) do { \
- a_type *phn = phn_next_get(a_type, a_field, a_ph->ph_root); \
- if (phn != NULL) { \
- phn_prev_set(a_type, a_field, a_ph->ph_root, NULL); \
- phn_next_set(a_type, a_field, a_ph->ph_root, NULL); \
- phn_prev_set(a_type, a_field, phn, NULL); \
- ph_merge_siblings(a_type, a_field, phn, a_cmp, phn); \
- assert(phn_next_get(a_type, a_field, phn) == NULL); \
- phn_merge(a_type, a_field, a_ph->ph_root, phn, a_cmp, \
- a_ph->ph_root); \
- } \
-} while (0)
-
-#define ph_merge_children(a_type, a_field, a_phn, a_cmp, r_phn) do { \
- a_type *lchild = phn_lchild_get(a_type, a_field, a_phn); \
- if (lchild == NULL) \
- r_phn = NULL; \
- else { \
- ph_merge_siblings(a_type, a_field, lchild, a_cmp, \
- r_phn); \
- } \
-} while (0)
-
-/*
- * The ph_proto() macro generates function prototypes that correspond to the
- * functions generated by an equivalently parameterized call to ph_gen().
- */
-#define ph_proto(a_attr, a_prefix, a_ph_type, a_type) \
-a_attr void a_prefix##new(a_ph_type *ph); \
-a_attr bool a_prefix##empty(a_ph_type *ph); \
-a_attr a_type *a_prefix##first(a_ph_type *ph); \
-a_attr void a_prefix##insert(a_ph_type *ph, a_type *phn); \
-a_attr a_type *a_prefix##remove_first(a_ph_type *ph); \
-a_attr void a_prefix##remove(a_ph_type *ph, a_type *phn);
-
-/*
- * The ph_gen() macro generates a type-specific pairing heap implementation,
- * based on the above cpp macros.
- */
-#define ph_gen(a_attr, a_prefix, a_ph_type, a_type, a_field, a_cmp) \
-a_attr void \
-a_prefix##new(a_ph_type *ph) \
-{ \
- \
- memset(ph, 0, sizeof(ph(a_type))); \
-} \
-a_attr bool \
-a_prefix##empty(a_ph_type *ph) \
-{ \
- \
- return (ph->ph_root == NULL); \
-} \
-a_attr a_type * \
-a_prefix##first(a_ph_type *ph) \
-{ \
- \
- if (ph->ph_root == NULL) \
- return (NULL); \
- ph_merge_aux(a_type, a_field, ph, a_cmp); \
- return (ph->ph_root); \
-} \
-a_attr void \
-a_prefix##insert(a_ph_type *ph, a_type *phn) \
-{ \
- \
- memset(&phn->a_field, 0, sizeof(phn(a_type))); \
- \
- /* \
- * Treat the root as an aux list during insertion, and lazily \
- * merge during a_prefix##remove_first(). For elements that \
- * are inserted, then removed via a_prefix##remove() before the \
- * aux list is ever processed, this makes insert/remove \
- * constant-time, whereas eager merging would make insert \
- * O(log n). \
- */ \
- if (ph->ph_root == NULL) \
- ph->ph_root = phn; \
- else { \
- phn_next_set(a_type, a_field, phn, phn_next_get(a_type, \
- a_field, ph->ph_root)); \
- if (phn_next_get(a_type, a_field, ph->ph_root) != \
- NULL) { \
- phn_prev_set(a_type, a_field, \
- phn_next_get(a_type, a_field, ph->ph_root), \
- phn); \
- } \
- phn_prev_set(a_type, a_field, phn, ph->ph_root); \
- phn_next_set(a_type, a_field, ph->ph_root, phn); \
- } \
-} \
-a_attr a_type * \
-a_prefix##remove_first(a_ph_type *ph) \
-{ \
- a_type *ret; \
- \
- if (ph->ph_root == NULL) \
- return (NULL); \
- ph_merge_aux(a_type, a_field, ph, a_cmp); \
- \
- ret = ph->ph_root; \
- \
- ph_merge_children(a_type, a_field, ph->ph_root, a_cmp, \
- ph->ph_root); \
- \
- return (ret); \
-} \
-a_attr void \
-a_prefix##remove(a_ph_type *ph, a_type *phn) \
-{ \
- a_type *replace, *parent; \
- \
- /* \
- * We can delete from aux list without merging it, but we need \
- * to merge if we are dealing with the root node. \
- */ \
- if (ph->ph_root == phn) { \
- ph_merge_aux(a_type, a_field, ph, a_cmp); \
- if (ph->ph_root == phn) { \
- ph_merge_children(a_type, a_field, ph->ph_root, \
- a_cmp, ph->ph_root); \
- return; \
- } \
- } \
- \
- /* Get parent (if phn is leftmost child) before mutating. */ \
- if ((parent = phn_prev_get(a_type, a_field, phn)) != NULL) { \
- if (phn_lchild_get(a_type, a_field, parent) != phn) \
- parent = NULL; \
- } \
- /* Find a possible replacement node, and link to parent. */ \
- ph_merge_children(a_type, a_field, phn, a_cmp, replace); \
- /* Set next/prev for sibling linked list. */ \
- if (replace != NULL) { \
- if (parent != NULL) { \
- phn_prev_set(a_type, a_field, replace, parent); \
- phn_lchild_set(a_type, a_field, parent, \
- replace); \
- } else { \
- phn_prev_set(a_type, a_field, replace, \
- phn_prev_get(a_type, a_field, phn)); \
- if (phn_prev_get(a_type, a_field, phn) != \
- NULL) { \
- phn_next_set(a_type, a_field, \
- phn_prev_get(a_type, a_field, phn), \
- replace); \
- } \
- } \
- phn_next_set(a_type, a_field, replace, \
- phn_next_get(a_type, a_field, phn)); \
- if (phn_next_get(a_type, a_field, phn) != NULL) { \
- phn_prev_set(a_type, a_field, \
- phn_next_get(a_type, a_field, phn), \
- replace); \
- } \
- } else { \
- if (parent != NULL) { \
- a_type *next = phn_next_get(a_type, a_field, \
- phn); \
- phn_lchild_set(a_type, a_field, parent, next); \
- if (next != NULL) { \
- phn_prev_set(a_type, a_field, next, \
- parent); \
- } \
- } else { \
- assert(phn_prev_get(a_type, a_field, phn) != \
- NULL); \
- phn_next_set(a_type, a_field, \
- phn_prev_get(a_type, a_field, phn), \
- phn_next_get(a_type, a_field, phn)); \
- } \
- if (phn_next_get(a_type, a_field, phn) != NULL) { \
- phn_prev_set(a_type, a_field, \
- phn_next_get(a_type, a_field, phn), \
- phn_prev_get(a_type, a_field, phn)); \
- } \
- } \
-}
-
-#endif /* PH_H_ */
diff --git a/memory/jemalloc/src/include/jemalloc/internal/private_namespace.sh b/memory/jemalloc/src/include/jemalloc/internal/private_namespace.sh
deleted file mode 100755
index cd25eb306..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/private_namespace.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/sh
-
-for symbol in `cat $1` ; do
- echo "#define ${symbol} JEMALLOC_N(${symbol})"
-done
diff --git a/memory/jemalloc/src/include/jemalloc/internal/private_symbols.txt b/memory/jemalloc/src/include/jemalloc/internal/private_symbols.txt
deleted file mode 100644
index 87c8c9b71..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/private_symbols.txt
+++ /dev/null
@@ -1,626 +0,0 @@
-a0dalloc
-a0get
-a0malloc
-arena_aalloc
-arena_alloc_junk_small
-arena_basic_stats_merge
-arena_bin_index
-arena_bin_info
-arena_bitselm_get_const
-arena_bitselm_get_mutable
-arena_boot
-arena_choose
-arena_choose_hard
-arena_choose_impl
-arena_chunk_alloc_huge
-arena_chunk_cache_maybe_insert
-arena_chunk_cache_maybe_remove
-arena_chunk_dalloc_huge
-arena_chunk_ralloc_huge_expand
-arena_chunk_ralloc_huge_shrink
-arena_chunk_ralloc_huge_similar
-arena_cleanup
-arena_dalloc
-arena_dalloc_bin
-arena_dalloc_bin_junked_locked
-arena_dalloc_junk_large
-arena_dalloc_junk_small
-arena_dalloc_large
-arena_dalloc_large_junked_locked
-arena_dalloc_small
-arena_decay_tick
-arena_decay_ticks
-arena_decay_time_default_get
-arena_decay_time_default_set
-arena_decay_time_get
-arena_decay_time_set
-arena_dss_prec_get
-arena_dss_prec_set
-arena_get
-arena_ichoose
-arena_init
-arena_lg_dirty_mult_default_get
-arena_lg_dirty_mult_default_set
-arena_lg_dirty_mult_get
-arena_lg_dirty_mult_set
-arena_malloc
-arena_malloc_hard
-arena_malloc_large
-arena_mapbits_allocated_get
-arena_mapbits_binind_get
-arena_mapbits_decommitted_get
-arena_mapbits_dirty_get
-arena_mapbits_get
-arena_mapbits_internal_set
-arena_mapbits_large_binind_set
-arena_mapbits_large_get
-arena_mapbits_large_set
-arena_mapbits_large_size_get
-arena_mapbits_size_decode
-arena_mapbits_size_encode
-arena_mapbits_small_runind_get
-arena_mapbits_small_set
-arena_mapbits_unallocated_set
-arena_mapbits_unallocated_size_get
-arena_mapbits_unallocated_size_set
-arena_mapbits_unzeroed_get
-arena_mapbitsp_get_const
-arena_mapbitsp_get_mutable
-arena_mapbitsp_read
-arena_mapbitsp_write
-arena_maxrun
-arena_maybe_purge
-arena_metadata_allocated_add
-arena_metadata_allocated_get
-arena_metadata_allocated_sub
-arena_migrate
-arena_miscelm_get_const
-arena_miscelm_get_mutable
-arena_miscelm_to_pageind
-arena_miscelm_to_rpages
-arena_new
-arena_node_alloc
-arena_node_dalloc
-arena_nthreads_dec
-arena_nthreads_get
-arena_nthreads_inc
-arena_palloc
-arena_postfork_child
-arena_postfork_parent
-arena_prefork0
-arena_prefork1
-arena_prefork2
-arena_prefork3
-arena_prof_accum
-arena_prof_accum_impl
-arena_prof_accum_locked
-arena_prof_promoted
-arena_prof_tctx_get
-arena_prof_tctx_reset
-arena_prof_tctx_set
-arena_ptr_small_binind_get
-arena_purge
-arena_quarantine_junk_small
-arena_ralloc
-arena_ralloc_junk_large
-arena_ralloc_no_move
-arena_rd_to_miscelm
-arena_redzone_corruption
-arena_reset
-arena_run_regind
-arena_run_to_miscelm
-arena_salloc
-arena_sdalloc
-arena_stats_merge
-arena_tcache_fill_small
-arena_tdata_get
-arena_tdata_get_hard
-arenas
-arenas_tdata_bypass_cleanup
-arenas_tdata_cleanup
-atomic_add_p
-atomic_add_u
-atomic_add_uint32
-atomic_add_uint64
-atomic_add_z
-atomic_cas_p
-atomic_cas_u
-atomic_cas_uint32
-atomic_cas_uint64
-atomic_cas_z
-atomic_sub_p
-atomic_sub_u
-atomic_sub_uint32
-atomic_sub_uint64
-atomic_sub_z
-atomic_write_p
-atomic_write_u
-atomic_write_uint32
-atomic_write_uint64
-atomic_write_z
-base_alloc
-base_boot
-base_postfork_child
-base_postfork_parent
-base_prefork
-base_stats_get
-bitmap_full
-bitmap_get
-bitmap_info_init
-bitmap_init
-bitmap_set
-bitmap_sfu
-bitmap_size
-bitmap_unset
-bootstrap_calloc
-bootstrap_free
-bootstrap_malloc
-bt_init
-buferror
-chunk_alloc_base
-chunk_alloc_cache
-chunk_alloc_dss
-chunk_alloc_mmap
-chunk_alloc_wrapper
-chunk_boot
-chunk_dalloc_cache
-chunk_dalloc_mmap
-chunk_dalloc_wrapper
-chunk_deregister
-chunk_dss_boot
-chunk_dss_mergeable
-chunk_dss_prec_get
-chunk_dss_prec_set
-chunk_hooks_default
-chunk_hooks_get
-chunk_hooks_set
-chunk_in_dss
-chunk_lookup
-chunk_npages
-chunk_purge_wrapper
-chunk_register
-chunks_rtree
-chunksize
-chunksize_mask
-ckh_count
-ckh_delete
-ckh_insert
-ckh_iter
-ckh_new
-ckh_pointer_hash
-ckh_pointer_keycomp
-ckh_remove
-ckh_search
-ckh_string_hash
-ckh_string_keycomp
-ctl_boot
-ctl_bymib
-ctl_byname
-ctl_nametomib
-ctl_postfork_child
-ctl_postfork_parent
-ctl_prefork
-decay_ticker_get
-dss_prec_names
-extent_node_achunk_get
-extent_node_achunk_set
-extent_node_addr_get
-extent_node_addr_set
-extent_node_arena_get
-extent_node_arena_set
-extent_node_committed_get
-extent_node_committed_set
-extent_node_dirty_insert
-extent_node_dirty_linkage_init
-extent_node_dirty_remove
-extent_node_init
-extent_node_prof_tctx_get
-extent_node_prof_tctx_set
-extent_node_size_get
-extent_node_size_set
-extent_node_zeroed_get
-extent_node_zeroed_set
-extent_tree_ad_destroy
-extent_tree_ad_destroy_recurse
-extent_tree_ad_empty
-extent_tree_ad_first
-extent_tree_ad_insert
-extent_tree_ad_iter
-extent_tree_ad_iter_recurse
-extent_tree_ad_iter_start
-extent_tree_ad_last
-extent_tree_ad_new
-extent_tree_ad_next
-extent_tree_ad_nsearch
-extent_tree_ad_prev
-extent_tree_ad_psearch
-extent_tree_ad_remove
-extent_tree_ad_reverse_iter
-extent_tree_ad_reverse_iter_recurse
-extent_tree_ad_reverse_iter_start
-extent_tree_ad_search
-extent_tree_szad_destroy
-extent_tree_szad_destroy_recurse
-extent_tree_szad_empty
-extent_tree_szad_first
-extent_tree_szad_insert
-extent_tree_szad_iter
-extent_tree_szad_iter_recurse
-extent_tree_szad_iter_start
-extent_tree_szad_last
-extent_tree_szad_new
-extent_tree_szad_next
-extent_tree_szad_nsearch
-extent_tree_szad_prev
-extent_tree_szad_psearch
-extent_tree_szad_remove
-extent_tree_szad_reverse_iter
-extent_tree_szad_reverse_iter_recurse
-extent_tree_szad_reverse_iter_start
-extent_tree_szad_search
-ffs_llu
-ffs_lu
-ffs_u
-ffs_u32
-ffs_u64
-ffs_zu
-get_errno
-hash
-hash_fmix_32
-hash_fmix_64
-hash_get_block_32
-hash_get_block_64
-hash_rotl_32
-hash_rotl_64
-hash_x64_128
-hash_x86_128
-hash_x86_32
-huge_aalloc
-huge_dalloc
-huge_dalloc_junk
-huge_malloc
-huge_palloc
-huge_prof_tctx_get
-huge_prof_tctx_reset
-huge_prof_tctx_set
-huge_ralloc
-huge_ralloc_no_move
-huge_salloc
-iaalloc
-ialloc
-iallocztm
-iarena_cleanup
-idalloc
-idalloctm
-in_valgrind
-index2size
-index2size_compute
-index2size_lookup
-index2size_tab
-ipalloc
-ipalloct
-ipallocztm
-iqalloc
-iralloc
-iralloct
-iralloct_realign
-isalloc
-isdalloct
-isqalloc
-isthreaded
-ivsalloc
-ixalloc
-jemalloc_postfork_child
-jemalloc_postfork_parent
-jemalloc_prefork
-large_maxclass
-lg_floor
-lg_prof_sample
-malloc_cprintf
-malloc_mutex_assert_not_owner
-malloc_mutex_assert_owner
-malloc_mutex_boot
-malloc_mutex_init
-malloc_mutex_lock
-malloc_mutex_postfork_child
-malloc_mutex_postfork_parent
-malloc_mutex_prefork
-malloc_mutex_unlock
-malloc_printf
-malloc_snprintf
-malloc_strtoumax
-malloc_tsd_boot0
-malloc_tsd_boot1
-malloc_tsd_cleanup_register
-malloc_tsd_dalloc
-malloc_tsd_malloc
-malloc_tsd_no_cleanup
-malloc_vcprintf
-malloc_vsnprintf
-malloc_write
-map_bias
-map_misc_offset
-mb_write
-narenas_auto
-narenas_tdata_cleanup
-narenas_total_get
-ncpus
-nhbins
-nhclasses
-nlclasses
-nstime_add
-nstime_compare
-nstime_copy
-nstime_divide
-nstime_idivide
-nstime_imultiply
-nstime_init
-nstime_init2
-nstime_monotonic
-nstime_ns
-nstime_nsec
-nstime_sec
-nstime_subtract
-nstime_update
-opt_abort
-opt_decay_time
-opt_dss
-opt_junk
-opt_junk_alloc
-opt_junk_free
-opt_lg_chunk
-opt_lg_dirty_mult
-opt_lg_prof_interval
-opt_lg_prof_sample
-opt_lg_tcache_max
-opt_narenas
-opt_prof
-opt_prof_accum
-opt_prof_active
-opt_prof_final
-opt_prof_gdump
-opt_prof_leak
-opt_prof_prefix
-opt_prof_thread_active_init
-opt_purge
-opt_quarantine
-opt_redzone
-opt_stats_print
-opt_tcache
-opt_utrace
-opt_xmalloc
-opt_zero
-p2rz
-pages_boot
-pages_commit
-pages_decommit
-pages_map
-pages_purge
-pages_trim
-pages_unmap
-pind2sz
-pind2sz_compute
-pind2sz_lookup
-pind2sz_tab
-pow2_ceil_u32
-pow2_ceil_u64
-pow2_ceil_zu
-prng_lg_range_u32
-prng_lg_range_u64
-prng_lg_range_zu
-prng_range_u32
-prng_range_u64
-prng_range_zu
-prng_state_next_u32
-prng_state_next_u64
-prng_state_next_zu
-prof_active
-prof_active_get
-prof_active_get_unlocked
-prof_active_set
-prof_alloc_prep
-prof_alloc_rollback
-prof_backtrace
-prof_boot0
-prof_boot1
-prof_boot2
-prof_bt_count
-prof_dump_header
-prof_dump_open
-prof_free
-prof_free_sampled_object
-prof_gdump
-prof_gdump_get
-prof_gdump_get_unlocked
-prof_gdump_set
-prof_gdump_val
-prof_idump
-prof_interval
-prof_lookup
-prof_malloc
-prof_malloc_sample_object
-prof_mdump
-prof_postfork_child
-prof_postfork_parent
-prof_prefork0
-prof_prefork1
-prof_realloc
-prof_reset
-prof_sample_accum_update
-prof_sample_threshold_update
-prof_tctx_get
-prof_tctx_reset
-prof_tctx_set
-prof_tdata_cleanup
-prof_tdata_count
-prof_tdata_get
-prof_tdata_init
-prof_tdata_reinit
-prof_thread_active_get
-prof_thread_active_init_get
-prof_thread_active_init_set
-prof_thread_active_set
-prof_thread_name_get
-prof_thread_name_set
-psz2ind
-psz2u
-purge_mode_names
-quarantine
-quarantine_alloc_hook
-quarantine_alloc_hook_work
-quarantine_cleanup
-rtree_child_read
-rtree_child_read_hard
-rtree_child_tryread
-rtree_delete
-rtree_get
-rtree_new
-rtree_node_valid
-rtree_set
-rtree_start_level
-rtree_subkey
-rtree_subtree_read
-rtree_subtree_read_hard
-rtree_subtree_tryread
-rtree_val_read
-rtree_val_write
-run_quantize_ceil
-run_quantize_floor
-s2u
-s2u_compute
-s2u_lookup
-sa2u
-set_errno
-size2index
-size2index_compute
-size2index_lookup
-size2index_tab
-spin_adaptive
-spin_init
-stats_cactive
-stats_cactive_add
-stats_cactive_get
-stats_cactive_sub
-stats_print
-tcache_alloc_easy
-tcache_alloc_large
-tcache_alloc_small
-tcache_alloc_small_hard
-tcache_arena_reassociate
-tcache_bin_flush_large
-tcache_bin_flush_small
-tcache_bin_info
-tcache_boot
-tcache_cleanup
-tcache_create
-tcache_dalloc_large
-tcache_dalloc_small
-tcache_enabled_cleanup
-tcache_enabled_get
-tcache_enabled_set
-tcache_event
-tcache_event_hard
-tcache_flush
-tcache_get
-tcache_get_hard
-tcache_maxclass
-tcache_salloc
-tcache_stats_merge
-tcaches
-tcaches_create
-tcaches_destroy
-tcaches_flush
-tcaches_get
-thread_allocated_cleanup
-thread_deallocated_cleanup
-ticker_copy
-ticker_init
-ticker_read
-ticker_tick
-ticker_ticks
-tsd_arena_get
-tsd_arena_set
-tsd_arenap_get
-tsd_arenas_tdata_bypass_get
-tsd_arenas_tdata_bypass_set
-tsd_arenas_tdata_bypassp_get
-tsd_arenas_tdata_get
-tsd_arenas_tdata_set
-tsd_arenas_tdatap_get
-tsd_boot
-tsd_boot0
-tsd_boot1
-tsd_booted
-tsd_booted_get
-tsd_cleanup
-tsd_cleanup_wrapper
-tsd_fetch
-tsd_fetch_impl
-tsd_get
-tsd_get_allocates
-tsd_iarena_get
-tsd_iarena_set
-tsd_iarenap_get
-tsd_initialized
-tsd_init_check_recursion
-tsd_init_finish
-tsd_init_head
-tsd_narenas_tdata_get
-tsd_narenas_tdata_set
-tsd_narenas_tdatap_get
-tsd_wrapper_get
-tsd_wrapper_set
-tsd_nominal
-tsd_prof_tdata_get
-tsd_prof_tdata_set
-tsd_prof_tdatap_get
-tsd_quarantine_get
-tsd_quarantine_set
-tsd_quarantinep_get
-tsd_set
-tsd_tcache_enabled_get
-tsd_tcache_enabled_set
-tsd_tcache_enabledp_get
-tsd_tcache_get
-tsd_tcache_set
-tsd_tcachep_get
-tsd_thread_allocated_get
-tsd_thread_allocated_set
-tsd_thread_allocatedp_get
-tsd_thread_deallocated_get
-tsd_thread_deallocated_set
-tsd_thread_deallocatedp_get
-tsd_tls
-tsd_tsd
-tsd_tsdn
-tsd_witness_fork_get
-tsd_witness_fork_set
-tsd_witness_forkp_get
-tsd_witnesses_get
-tsd_witnesses_set
-tsd_witnessesp_get
-tsdn_fetch
-tsdn_null
-tsdn_tsd
-u2rz
-valgrind_freelike_block
-valgrind_make_mem_defined
-valgrind_make_mem_noaccess
-valgrind_make_mem_undefined
-witness_assert_lockless
-witness_assert_not_owner
-witness_assert_owner
-witness_fork_cleanup
-witness_init
-witness_lock
-witness_lock_error
-witness_lockless_error
-witness_not_owner_error
-witness_owner
-witness_owner_error
-witness_postfork_child
-witness_postfork_parent
-witness_prefork
-witness_unlock
-witnesses_cleanup
-zone_register
diff --git a/memory/jemalloc/src/include/jemalloc/internal/private_unnamespace.sh b/memory/jemalloc/src/include/jemalloc/internal/private_unnamespace.sh
deleted file mode 100755
index 23fed8e80..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/private_unnamespace.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/sh
-
-for symbol in `cat $1` ; do
- echo "#undef ${symbol}"
-done
diff --git a/memory/jemalloc/src/include/jemalloc/internal/prng.h b/memory/jemalloc/src/include/jemalloc/internal/prng.h
deleted file mode 100644
index c2bda19c6..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/prng.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-/*
- * Simple linear congruential pseudo-random number generator:
- *
- * prng(y) = (a*x + c) % m
- *
- * where the following constants ensure maximal period:
- *
- * a == Odd number (relatively prime to 2^n), and (a-1) is a multiple of 4.
- * c == Odd number (relatively prime to 2^n).
- * m == 2^32
- *
- * See Knuth's TAOCP 3rd Ed., Vol. 2, pg. 17 for details on these constraints.
- *
- * This choice of m has the disadvantage that the quality of the bits is
- * proportional to bit position. For example, the lowest bit has a cycle of 2,
- * the next has a cycle of 4, etc. For this reason, we prefer to use the upper
- * bits.
- */
-
-#define PRNG_A_32 UINT32_C(1103515241)
-#define PRNG_C_32 UINT32_C(12347)
-
-#define PRNG_A_64 UINT64_C(6364136223846793005)
-#define PRNG_C_64 UINT64_C(1442695040888963407)
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-uint32_t prng_state_next_u32(uint32_t state);
-uint64_t prng_state_next_u64(uint64_t state);
-size_t prng_state_next_zu(size_t state);
-
-uint32_t prng_lg_range_u32(uint32_t *state, unsigned lg_range,
- bool atomic);
-uint64_t prng_lg_range_u64(uint64_t *state, unsigned lg_range);
-size_t prng_lg_range_zu(size_t *state, unsigned lg_range, bool atomic);
-
-uint32_t prng_range_u32(uint32_t *state, uint32_t range, bool atomic);
-uint64_t prng_range_u64(uint64_t *state, uint64_t range);
-size_t prng_range_zu(size_t *state, size_t range, bool atomic);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_PRNG_C_))
-JEMALLOC_ALWAYS_INLINE uint32_t
-prng_state_next_u32(uint32_t state)
-{
-
- return ((state * PRNG_A_32) + PRNG_C_32);
-}
-
-JEMALLOC_ALWAYS_INLINE uint64_t
-prng_state_next_u64(uint64_t state)
-{
-
- return ((state * PRNG_A_64) + PRNG_C_64);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-prng_state_next_zu(size_t state)
-{
-
-#if LG_SIZEOF_PTR == 2
- return ((state * PRNG_A_32) + PRNG_C_32);
-#elif LG_SIZEOF_PTR == 3
- return ((state * PRNG_A_64) + PRNG_C_64);
-#else
-#error Unsupported pointer size
-#endif
-}
-
-JEMALLOC_ALWAYS_INLINE uint32_t
-prng_lg_range_u32(uint32_t *state, unsigned lg_range, bool atomic)
-{
- uint32_t ret, state1;
-
- assert(lg_range > 0);
- assert(lg_range <= 32);
-
- if (atomic) {
- uint32_t state0;
-
- do {
- state0 = atomic_read_uint32(state);
- state1 = prng_state_next_u32(state0);
- } while (atomic_cas_uint32(state, state0, state1));
- } else {
- state1 = prng_state_next_u32(*state);
- *state = state1;
- }
- ret = state1 >> (32 - lg_range);
-
- return (ret);
-}
-
-/* 64-bit atomic operations cannot be supported on all relevant platforms. */
-JEMALLOC_ALWAYS_INLINE uint64_t
-prng_lg_range_u64(uint64_t *state, unsigned lg_range)
-{
- uint64_t ret, state1;
-
- assert(lg_range > 0);
- assert(lg_range <= 64);
-
- state1 = prng_state_next_u64(*state);
- *state = state1;
- ret = state1 >> (64 - lg_range);
-
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-prng_lg_range_zu(size_t *state, unsigned lg_range, bool atomic)
-{
- size_t ret, state1;
-
- assert(lg_range > 0);
- assert(lg_range <= ZU(1) << (3 + LG_SIZEOF_PTR));
-
- if (atomic) {
- size_t state0;
-
- do {
- state0 = atomic_read_z(state);
- state1 = prng_state_next_zu(state0);
- } while (atomic_cas_z(state, state0, state1));
- } else {
- state1 = prng_state_next_zu(*state);
- *state = state1;
- }
- ret = state1 >> ((ZU(1) << (3 + LG_SIZEOF_PTR)) - lg_range);
-
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE uint32_t
-prng_range_u32(uint32_t *state, uint32_t range, bool atomic)
-{
- uint32_t ret;
- unsigned lg_range;
-
- assert(range > 1);
-
- /* Compute the ceiling of lg(range). */
- lg_range = ffs_u32(pow2_ceil_u32(range)) - 1;
-
- /* Generate a result in [0..range) via repeated trial. */
- do {
- ret = prng_lg_range_u32(state, lg_range, atomic);
- } while (ret >= range);
-
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE uint64_t
-prng_range_u64(uint64_t *state, uint64_t range)
-{
- uint64_t ret;
- unsigned lg_range;
-
- assert(range > 1);
-
- /* Compute the ceiling of lg(range). */
- lg_range = ffs_u64(pow2_ceil_u64(range)) - 1;
-
- /* Generate a result in [0..range) via repeated trial. */
- do {
- ret = prng_lg_range_u64(state, lg_range);
- } while (ret >= range);
-
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE size_t
-prng_range_zu(size_t *state, size_t range, bool atomic)
-{
- size_t ret;
- unsigned lg_range;
-
- assert(range > 1);
-
- /* Compute the ceiling of lg(range). */
- lg_range = ffs_u64(pow2_ceil_u64(range)) - 1;
-
- /* Generate a result in [0..range) via repeated trial. */
- do {
- ret = prng_lg_range_zu(state, lg_range, atomic);
- } while (ret >= range);
-
- return (ret);
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/prof.h b/memory/jemalloc/src/include/jemalloc/internal/prof.h
deleted file mode 100644
index 8293b71ed..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/prof.h
+++ /dev/null
@@ -1,547 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct prof_bt_s prof_bt_t;
-typedef struct prof_cnt_s prof_cnt_t;
-typedef struct prof_tctx_s prof_tctx_t;
-typedef struct prof_gctx_s prof_gctx_t;
-typedef struct prof_tdata_s prof_tdata_t;
-
-/* Option defaults. */
-#ifdef JEMALLOC_PROF
-# define PROF_PREFIX_DEFAULT "jeprof"
-#else
-# define PROF_PREFIX_DEFAULT ""
-#endif
-#define LG_PROF_SAMPLE_DEFAULT 19
-#define LG_PROF_INTERVAL_DEFAULT -1
-
-/*
- * Hard limit on stack backtrace depth. The version of prof_backtrace() that
- * is based on __builtin_return_address() necessarily has a hard-coded number
- * of backtrace frame handlers, and should be kept in sync with this setting.
- */
-#define PROF_BT_MAX 128
-
-/* Initial hash table size. */
-#define PROF_CKH_MINITEMS 64
-
-/* Size of memory buffer to use when writing dump files. */
-#define PROF_DUMP_BUFSIZE 65536
-
-/* Size of stack-allocated buffer used by prof_printf(). */
-#define PROF_PRINTF_BUFSIZE 128
-
-/*
- * Number of mutexes shared among all gctx's. No space is allocated for these
- * unless profiling is enabled, so it's okay to over-provision.
- */
-#define PROF_NCTX_LOCKS 1024
-
-/*
- * Number of mutexes shared among all tdata's. No space is allocated for these
- * unless profiling is enabled, so it's okay to over-provision.
- */
-#define PROF_NTDATA_LOCKS 256
-
-/*
- * prof_tdata pointers close to NULL are used to encode state information that
- * is used for cleaning up during thread shutdown.
- */
-#define PROF_TDATA_STATE_REINCARNATED ((prof_tdata_t *)(uintptr_t)1)
-#define PROF_TDATA_STATE_PURGATORY ((prof_tdata_t *)(uintptr_t)2)
-#define PROF_TDATA_STATE_MAX PROF_TDATA_STATE_PURGATORY
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct prof_bt_s {
- /* Backtrace, stored as len program counters. */
- void **vec;
- unsigned len;
-};
-
-#ifdef JEMALLOC_PROF_LIBGCC
-/* Data structure passed to libgcc _Unwind_Backtrace() callback functions. */
-typedef struct {
- prof_bt_t *bt;
- unsigned max;
-} prof_unwind_data_t;
-#endif
-
-struct prof_cnt_s {
- /* Profiling counters. */
- uint64_t curobjs;
- uint64_t curbytes;
- uint64_t accumobjs;
- uint64_t accumbytes;
-};
-
-typedef enum {
- prof_tctx_state_initializing,
- prof_tctx_state_nominal,
- prof_tctx_state_dumping,
- prof_tctx_state_purgatory /* Dumper must finish destroying. */
-} prof_tctx_state_t;
-
-struct prof_tctx_s {
- /* Thread data for thread that performed the allocation. */
- prof_tdata_t *tdata;
-
- /*
- * Copy of tdata->thr_{uid,discrim}, necessary because tdata may be
- * defunct during teardown.
- */
- uint64_t thr_uid;
- uint64_t thr_discrim;
-
- /* Profiling counters, protected by tdata->lock. */
- prof_cnt_t cnts;
-
- /* Associated global context. */
- prof_gctx_t *gctx;
-
- /*
- * UID that distinguishes multiple tctx's created by the same thread,
- * but coexisting in gctx->tctxs. There are two ways that such
- * coexistence can occur:
- * - A dumper thread can cause a tctx to be retained in the purgatory
- * state.
- * - Although a single "producer" thread must create all tctx's which
- * share the same thr_uid, multiple "consumers" can each concurrently
- * execute portions of prof_tctx_destroy(). prof_tctx_destroy() only
- * gets called once each time cnts.cur{objs,bytes} drop to 0, but this
- * threshold can be hit again before the first consumer finishes
- * executing prof_tctx_destroy().
- */
- uint64_t tctx_uid;
-
- /* Linkage into gctx's tctxs. */
- rb_node(prof_tctx_t) tctx_link;
-
- /*
- * True during prof_alloc_prep()..prof_malloc_sample_object(), prevents
- * sample vs destroy race.
- */
- bool prepared;
-
- /* Current dump-related state, protected by gctx->lock. */
- prof_tctx_state_t state;
-
- /*
- * Copy of cnts snapshotted during early dump phase, protected by
- * dump_mtx.
- */
- prof_cnt_t dump_cnts;
-};
-typedef rb_tree(prof_tctx_t) prof_tctx_tree_t;
-
-struct prof_gctx_s {
- /* Protects nlimbo, cnt_summed, and tctxs. */
- malloc_mutex_t *lock;
-
- /*
- * Number of threads that currently cause this gctx to be in a state of
- * limbo due to one of:
- * - Initializing this gctx.
- * - Initializing per thread counters associated with this gctx.
- * - Preparing to destroy this gctx.
- * - Dumping a heap profile that includes this gctx.
- * nlimbo must be 1 (single destroyer) in order to safely destroy the
- * gctx.
- */
- unsigned nlimbo;
-
- /*
- * Tree of profile counters, one for each thread that has allocated in
- * this context.
- */
- prof_tctx_tree_t tctxs;
-
- /* Linkage for tree of contexts to be dumped. */
- rb_node(prof_gctx_t) dump_link;
-
- /* Temporary storage for summation during dump. */
- prof_cnt_t cnt_summed;
-
- /* Associated backtrace. */
- prof_bt_t bt;
-
- /* Backtrace vector, variable size, referred to by bt. */
- void *vec[1];
-};
-typedef rb_tree(prof_gctx_t) prof_gctx_tree_t;
-
-struct prof_tdata_s {
- malloc_mutex_t *lock;
-
- /* Monotonically increasing unique thread identifier. */
- uint64_t thr_uid;
-
- /*
- * Monotonically increasing discriminator among tdata structures
- * associated with the same thr_uid.
- */
- uint64_t thr_discrim;
-
- /* Included in heap profile dumps if non-NULL. */
- char *thread_name;
-
- bool attached;
- bool expired;
-
- rb_node(prof_tdata_t) tdata_link;
-
- /*
- * Counter used to initialize prof_tctx_t's tctx_uid. No locking is
- * necessary when incrementing this field, because only one thread ever
- * does so.
- */
- uint64_t tctx_uid_next;
-
- /*
- * Hash of (prof_bt_t *)-->(prof_tctx_t *). Each thread tracks
- * backtraces for which it has non-zero allocation/deallocation counters
- * associated with thread-specific prof_tctx_t objects. Other threads
- * may write to prof_tctx_t contents when freeing associated objects.
- */
- ckh_t bt2tctx;
-
- /* Sampling state. */
- uint64_t prng_state;
- uint64_t bytes_until_sample;
-
- /* State used to avoid dumping while operating on prof internals. */
- bool enq;
- bool enq_idump;
- bool enq_gdump;
-
- /*
- * Set to true during an early dump phase for tdata's which are
- * currently being dumped. New threads' tdata's have this initialized
- * to false so that they aren't accidentally included in later dump
- * phases.
- */
- bool dumping;
-
- /*
- * True if profiling is active for this tdata's thread
- * (thread.prof.active mallctl).
- */
- bool active;
-
- /* Temporary storage for summation during dump. */
- prof_cnt_t cnt_summed;
-
- /* Backtrace vector, used for calls to prof_backtrace(). */
- void *vec[PROF_BT_MAX];
-};
-typedef rb_tree(prof_tdata_t) prof_tdata_tree_t;
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-extern bool opt_prof;
-extern bool opt_prof_active;
-extern bool opt_prof_thread_active_init;
-extern size_t opt_lg_prof_sample; /* Mean bytes between samples. */
-extern ssize_t opt_lg_prof_interval; /* lg(prof_interval). */
-extern bool opt_prof_gdump; /* High-water memory dumping. */
-extern bool opt_prof_final; /* Final profile dumping. */
-extern bool opt_prof_leak; /* Dump leak summary at exit. */
-extern bool opt_prof_accum; /* Report cumulative bytes. */
-extern char opt_prof_prefix[
- /* Minimize memory bloat for non-prof builds. */
-#ifdef JEMALLOC_PROF
- PATH_MAX +
-#endif
- 1];
-
-/* Accessed via prof_active_[gs]et{_unlocked,}(). */
-extern bool prof_active;
-
-/* Accessed via prof_gdump_[gs]et{_unlocked,}(). */
-extern bool prof_gdump_val;
-
-/*
- * Profile dump interval, measured in bytes allocated. Each arena triggers a
- * profile dump when it reaches this threshold. The effect is that the
- * interval between profile dumps averages prof_interval, though the actual
- * interval between dumps will tend to be sporadic, and the interval will be a
- * maximum of approximately (prof_interval * narenas).
- */
-extern uint64_t prof_interval;
-
-/*
- * Initialized as opt_lg_prof_sample, and potentially modified during profiling
- * resets.
- */
-extern size_t lg_prof_sample;
-
-void prof_alloc_rollback(tsd_t *tsd, prof_tctx_t *tctx, bool updated);
-void prof_malloc_sample_object(tsdn_t *tsdn, const void *ptr, size_t usize,
- prof_tctx_t *tctx);
-void prof_free_sampled_object(tsd_t *tsd, size_t usize, prof_tctx_t *tctx);
-void bt_init(prof_bt_t *bt, void **vec);
-void prof_backtrace(prof_bt_t *bt);
-prof_tctx_t *prof_lookup(tsd_t *tsd, prof_bt_t *bt);
-#ifdef JEMALLOC_JET
-size_t prof_tdata_count(void);
-size_t prof_bt_count(void);
-const prof_cnt_t *prof_cnt_all(void);
-typedef int (prof_dump_open_t)(bool, const char *);
-extern prof_dump_open_t *prof_dump_open;
-typedef bool (prof_dump_header_t)(tsdn_t *, bool, const prof_cnt_t *);
-extern prof_dump_header_t *prof_dump_header;
-#endif
-void prof_idump(tsdn_t *tsdn);
-bool prof_mdump(tsd_t *tsd, const char *filename);
-void prof_gdump(tsdn_t *tsdn);
-prof_tdata_t *prof_tdata_init(tsd_t *tsd);
-prof_tdata_t *prof_tdata_reinit(tsd_t *tsd, prof_tdata_t *tdata);
-void prof_reset(tsd_t *tsd, size_t lg_sample);
-void prof_tdata_cleanup(tsd_t *tsd);
-bool prof_active_get(tsdn_t *tsdn);
-bool prof_active_set(tsdn_t *tsdn, bool active);
-const char *prof_thread_name_get(tsd_t *tsd);
-int prof_thread_name_set(tsd_t *tsd, const char *thread_name);
-bool prof_thread_active_get(tsd_t *tsd);
-bool prof_thread_active_set(tsd_t *tsd, bool active);
-bool prof_thread_active_init_get(tsdn_t *tsdn);
-bool prof_thread_active_init_set(tsdn_t *tsdn, bool active_init);
-bool prof_gdump_get(tsdn_t *tsdn);
-bool prof_gdump_set(tsdn_t *tsdn, bool active);
-void prof_boot0(void);
-void prof_boot1(void);
-bool prof_boot2(tsd_t *tsd);
-void prof_prefork0(tsdn_t *tsdn);
-void prof_prefork1(tsdn_t *tsdn);
-void prof_postfork_parent(tsdn_t *tsdn);
-void prof_postfork_child(tsdn_t *tsdn);
-void prof_sample_threshold_update(prof_tdata_t *tdata);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-bool prof_active_get_unlocked(void);
-bool prof_gdump_get_unlocked(void);
-prof_tdata_t *prof_tdata_get(tsd_t *tsd, bool create);
-prof_tctx_t *prof_tctx_get(tsdn_t *tsdn, const void *ptr);
-void prof_tctx_set(tsdn_t *tsdn, const void *ptr, size_t usize,
- prof_tctx_t *tctx);
-void prof_tctx_reset(tsdn_t *tsdn, const void *ptr, size_t usize,
- const void *old_ptr, prof_tctx_t *tctx);
-bool prof_sample_accum_update(tsd_t *tsd, size_t usize, bool commit,
- prof_tdata_t **tdata_out);
-prof_tctx_t *prof_alloc_prep(tsd_t *tsd, size_t usize, bool prof_active,
- bool update);
-void prof_malloc(tsdn_t *tsdn, const void *ptr, size_t usize,
- prof_tctx_t *tctx);
-void prof_realloc(tsd_t *tsd, const void *ptr, size_t usize,
- prof_tctx_t *tctx, bool prof_active, bool updated, const void *old_ptr,
- size_t old_usize, prof_tctx_t *old_tctx);
-void prof_free(tsd_t *tsd, const void *ptr, size_t usize);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_PROF_C_))
-JEMALLOC_ALWAYS_INLINE bool
-prof_active_get_unlocked(void)
-{
-
- /*
- * Even if opt_prof is true, sampling can be temporarily disabled by
- * setting prof_active to false. No locking is used when reading
- * prof_active in the fast path, so there are no guarantees regarding
- * how long it will take for all threads to notice state changes.
- */
- return (prof_active);
-}
-
-JEMALLOC_ALWAYS_INLINE bool
-prof_gdump_get_unlocked(void)
-{
-
- /*
- * No locking is used when reading prof_gdump_val in the fast path, so
- * there are no guarantees regarding how long it will take for all
- * threads to notice state changes.
- */
- return (prof_gdump_val);
-}
-
-JEMALLOC_ALWAYS_INLINE prof_tdata_t *
-prof_tdata_get(tsd_t *tsd, bool create)
-{
- prof_tdata_t *tdata;
-
- cassert(config_prof);
-
- tdata = tsd_prof_tdata_get(tsd);
- if (create) {
- if (unlikely(tdata == NULL)) {
- if (tsd_nominal(tsd)) {
- tdata = prof_tdata_init(tsd);
- tsd_prof_tdata_set(tsd, tdata);
- }
- } else if (unlikely(tdata->expired)) {
- tdata = prof_tdata_reinit(tsd, tdata);
- tsd_prof_tdata_set(tsd, tdata);
- }
- assert(tdata == NULL || tdata->attached);
- }
-
- return (tdata);
-}
-
-JEMALLOC_ALWAYS_INLINE prof_tctx_t *
-prof_tctx_get(tsdn_t *tsdn, const void *ptr)
-{
-
- cassert(config_prof);
- assert(ptr != NULL);
-
- return (arena_prof_tctx_get(tsdn, ptr));
-}
-
-JEMALLOC_ALWAYS_INLINE void
-prof_tctx_set(tsdn_t *tsdn, const void *ptr, size_t usize, prof_tctx_t *tctx)
-{
-
- cassert(config_prof);
- assert(ptr != NULL);
-
- arena_prof_tctx_set(tsdn, ptr, usize, tctx);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-prof_tctx_reset(tsdn_t *tsdn, const void *ptr, size_t usize, const void *old_ptr,
- prof_tctx_t *old_tctx)
-{
-
- cassert(config_prof);
- assert(ptr != NULL);
-
- arena_prof_tctx_reset(tsdn, ptr, usize, old_ptr, old_tctx);
-}
-
-JEMALLOC_ALWAYS_INLINE bool
-prof_sample_accum_update(tsd_t *tsd, size_t usize, bool update,
- prof_tdata_t **tdata_out)
-{
- prof_tdata_t *tdata;
-
- cassert(config_prof);
-
- tdata = prof_tdata_get(tsd, true);
- if (unlikely((uintptr_t)tdata <= (uintptr_t)PROF_TDATA_STATE_MAX))
- tdata = NULL;
-
- if (tdata_out != NULL)
- *tdata_out = tdata;
-
- if (unlikely(tdata == NULL))
- return (true);
-
- if (likely(tdata->bytes_until_sample >= usize)) {
- if (update)
- tdata->bytes_until_sample -= usize;
- return (true);
- } else {
- /* Compute new sample threshold. */
- if (update)
- prof_sample_threshold_update(tdata);
- return (!tdata->active);
- }
-}
-
-JEMALLOC_ALWAYS_INLINE prof_tctx_t *
-prof_alloc_prep(tsd_t *tsd, size_t usize, bool prof_active, bool update)
-{
- prof_tctx_t *ret;
- prof_tdata_t *tdata;
- prof_bt_t bt;
-
- assert(usize == s2u(usize));
-
- if (!prof_active || likely(prof_sample_accum_update(tsd, usize, update,
- &tdata)))
- ret = (prof_tctx_t *)(uintptr_t)1U;
- else {
- bt_init(&bt, tdata->vec);
- prof_backtrace(&bt);
- ret = prof_lookup(tsd, &bt);
- }
-
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-prof_malloc(tsdn_t *tsdn, const void *ptr, size_t usize, prof_tctx_t *tctx)
-{
-
- cassert(config_prof);
- assert(ptr != NULL);
- assert(usize == isalloc(tsdn, ptr, true));
-
- if (unlikely((uintptr_t)tctx > (uintptr_t)1U))
- prof_malloc_sample_object(tsdn, ptr, usize, tctx);
- else
- prof_tctx_set(tsdn, ptr, usize, (prof_tctx_t *)(uintptr_t)1U);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-prof_realloc(tsd_t *tsd, const void *ptr, size_t usize, prof_tctx_t *tctx,
- bool prof_active, bool updated, const void *old_ptr, size_t old_usize,
- prof_tctx_t *old_tctx)
-{
- bool sampled, old_sampled;
-
- cassert(config_prof);
- assert(ptr != NULL || (uintptr_t)tctx <= (uintptr_t)1U);
-
- if (prof_active && !updated && ptr != NULL) {
- assert(usize == isalloc(tsd_tsdn(tsd), ptr, true));
- if (prof_sample_accum_update(tsd, usize, true, NULL)) {
- /*
- * Don't sample. The usize passed to prof_alloc_prep()
- * was larger than what actually got allocated, so a
- * backtrace was captured for this allocation, even
- * though its actual usize was insufficient to cross the
- * sample threshold.
- */
- prof_alloc_rollback(tsd, tctx, true);
- tctx = (prof_tctx_t *)(uintptr_t)1U;
- }
- }
-
- sampled = ((uintptr_t)tctx > (uintptr_t)1U);
- old_sampled = ((uintptr_t)old_tctx > (uintptr_t)1U);
-
- if (unlikely(sampled))
- prof_malloc_sample_object(tsd_tsdn(tsd), ptr, usize, tctx);
- else
- prof_tctx_reset(tsd_tsdn(tsd), ptr, usize, old_ptr, old_tctx);
-
- if (unlikely(old_sampled))
- prof_free_sampled_object(tsd, old_usize, old_tctx);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-prof_free(tsd_t *tsd, const void *ptr, size_t usize)
-{
- prof_tctx_t *tctx = prof_tctx_get(tsd_tsdn(tsd), ptr);
-
- cassert(config_prof);
- assert(usize == isalloc(tsd_tsdn(tsd), ptr, true));
-
- if (unlikely((uintptr_t)tctx > (uintptr_t)1U))
- prof_free_sampled_object(tsd, usize, tctx);
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/public_namespace.sh b/memory/jemalloc/src/include/jemalloc/internal/public_namespace.sh
deleted file mode 100755
index 362109f71..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/public_namespace.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/sh
-
-for nm in `cat $1` ; do
- n=`echo ${nm} |tr ':' ' ' |awk '{print $1}'`
- echo "#define je_${n} JEMALLOC_N(${n})"
-done
diff --git a/memory/jemalloc/src/include/jemalloc/internal/public_unnamespace.sh b/memory/jemalloc/src/include/jemalloc/internal/public_unnamespace.sh
deleted file mode 100755
index 4239d1775..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/public_unnamespace.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/sh
-
-for nm in `cat $1` ; do
- n=`echo ${nm} |tr ':' ' ' |awk '{print $1}'`
- echo "#undef je_${n}"
-done
diff --git a/memory/jemalloc/src/include/jemalloc/internal/ql.h b/memory/jemalloc/src/include/jemalloc/internal/ql.h
deleted file mode 100644
index 1834bb855..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/ql.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/* List definitions. */
-#define ql_head(a_type) \
-struct { \
- a_type *qlh_first; \
-}
-
-#define ql_head_initializer(a_head) {NULL}
-
-#define ql_elm(a_type) qr(a_type)
-
-/* List functions. */
-#define ql_new(a_head) do { \
- (a_head)->qlh_first = NULL; \
-} while (0)
-
-#define ql_elm_new(a_elm, a_field) qr_new((a_elm), a_field)
-
-#define ql_first(a_head) ((a_head)->qlh_first)
-
-#define ql_last(a_head, a_field) \
- ((ql_first(a_head) != NULL) \
- ? qr_prev(ql_first(a_head), a_field) : NULL)
-
-#define ql_next(a_head, a_elm, a_field) \
- ((ql_last(a_head, a_field) != (a_elm)) \
- ? qr_next((a_elm), a_field) : NULL)
-
-#define ql_prev(a_head, a_elm, a_field) \
- ((ql_first(a_head) != (a_elm)) ? qr_prev((a_elm), a_field) \
- : NULL)
-
-#define ql_before_insert(a_head, a_qlelm, a_elm, a_field) do { \
- qr_before_insert((a_qlelm), (a_elm), a_field); \
- if (ql_first(a_head) == (a_qlelm)) { \
- ql_first(a_head) = (a_elm); \
- } \
-} while (0)
-
-#define ql_after_insert(a_qlelm, a_elm, a_field) \
- qr_after_insert((a_qlelm), (a_elm), a_field)
-
-#define ql_head_insert(a_head, a_elm, a_field) do { \
- if (ql_first(a_head) != NULL) { \
- qr_before_insert(ql_first(a_head), (a_elm), a_field); \
- } \
- ql_first(a_head) = (a_elm); \
-} while (0)
-
-#define ql_tail_insert(a_head, a_elm, a_field) do { \
- if (ql_first(a_head) != NULL) { \
- qr_before_insert(ql_first(a_head), (a_elm), a_field); \
- } \
- ql_first(a_head) = qr_next((a_elm), a_field); \
-} while (0)
-
-#define ql_remove(a_head, a_elm, a_field) do { \
- if (ql_first(a_head) == (a_elm)) { \
- ql_first(a_head) = qr_next(ql_first(a_head), a_field); \
- } \
- if (ql_first(a_head) != (a_elm)) { \
- qr_remove((a_elm), a_field); \
- } else { \
- ql_first(a_head) = NULL; \
- } \
-} while (0)
-
-#define ql_head_remove(a_head, a_type, a_field) do { \
- a_type *t = ql_first(a_head); \
- ql_remove((a_head), t, a_field); \
-} while (0)
-
-#define ql_tail_remove(a_head, a_type, a_field) do { \
- a_type *t = ql_last(a_head, a_field); \
- ql_remove((a_head), t, a_field); \
-} while (0)
-
-#define ql_foreach(a_var, a_head, a_field) \
- qr_foreach((a_var), ql_first(a_head), a_field)
-
-#define ql_reverse_foreach(a_var, a_head, a_field) \
- qr_reverse_foreach((a_var), ql_first(a_head), a_field)
diff --git a/memory/jemalloc/src/include/jemalloc/internal/qr.h b/memory/jemalloc/src/include/jemalloc/internal/qr.h
deleted file mode 100644
index 0fbaec25e..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/qr.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* Ring definitions. */
-#define qr(a_type) \
-struct { \
- a_type *qre_next; \
- a_type *qre_prev; \
-}
-
-/* Ring functions. */
-#define qr_new(a_qr, a_field) do { \
- (a_qr)->a_field.qre_next = (a_qr); \
- (a_qr)->a_field.qre_prev = (a_qr); \
-} while (0)
-
-#define qr_next(a_qr, a_field) ((a_qr)->a_field.qre_next)
-
-#define qr_prev(a_qr, a_field) ((a_qr)->a_field.qre_prev)
-
-#define qr_before_insert(a_qrelm, a_qr, a_field) do { \
- (a_qr)->a_field.qre_prev = (a_qrelm)->a_field.qre_prev; \
- (a_qr)->a_field.qre_next = (a_qrelm); \
- (a_qr)->a_field.qre_prev->a_field.qre_next = (a_qr); \
- (a_qrelm)->a_field.qre_prev = (a_qr); \
-} while (0)
-
-#define qr_after_insert(a_qrelm, a_qr, a_field) \
- do \
- { \
- (a_qr)->a_field.qre_next = (a_qrelm)->a_field.qre_next; \
- (a_qr)->a_field.qre_prev = (a_qrelm); \
- (a_qr)->a_field.qre_next->a_field.qre_prev = (a_qr); \
- (a_qrelm)->a_field.qre_next = (a_qr); \
- } while (0)
-
-#define qr_meld(a_qr_a, a_qr_b, a_field) do { \
- void *t; \
- (a_qr_a)->a_field.qre_prev->a_field.qre_next = (a_qr_b); \
- (a_qr_b)->a_field.qre_prev->a_field.qre_next = (a_qr_a); \
- t = (a_qr_a)->a_field.qre_prev; \
- (a_qr_a)->a_field.qre_prev = (a_qr_b)->a_field.qre_prev; \
- (a_qr_b)->a_field.qre_prev = t; \
-} while (0)
-
-/*
- * qr_meld() and qr_split() are functionally equivalent, so there's no need to
- * have two copies of the code.
- */
-#define qr_split(a_qr_a, a_qr_b, a_field) \
- qr_meld((a_qr_a), (a_qr_b), a_field)
-
-#define qr_remove(a_qr, a_field) do { \
- (a_qr)->a_field.qre_prev->a_field.qre_next \
- = (a_qr)->a_field.qre_next; \
- (a_qr)->a_field.qre_next->a_field.qre_prev \
- = (a_qr)->a_field.qre_prev; \
- (a_qr)->a_field.qre_next = (a_qr); \
- (a_qr)->a_field.qre_prev = (a_qr); \
-} while (0)
-
-#define qr_foreach(var, a_qr, a_field) \
- for ((var) = (a_qr); \
- (var) != NULL; \
- (var) = (((var)->a_field.qre_next != (a_qr)) \
- ? (var)->a_field.qre_next : NULL))
-
-#define qr_reverse_foreach(var, a_qr, a_field) \
- for ((var) = ((a_qr) != NULL) ? qr_prev(a_qr, a_field) : NULL; \
- (var) != NULL; \
- (var) = (((var) != (a_qr)) \
- ? (var)->a_field.qre_prev : NULL))
diff --git a/memory/jemalloc/src/include/jemalloc/internal/quarantine.h b/memory/jemalloc/src/include/jemalloc/internal/quarantine.h
deleted file mode 100644
index ae607399f..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/quarantine.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct quarantine_obj_s quarantine_obj_t;
-typedef struct quarantine_s quarantine_t;
-
-/* Default per thread quarantine size if valgrind is enabled. */
-#define JEMALLOC_VALGRIND_QUARANTINE_DEFAULT (ZU(1) << 24)
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct quarantine_obj_s {
- void *ptr;
- size_t usize;
-};
-
-struct quarantine_s {
- size_t curbytes;
- size_t curobjs;
- size_t first;
-#define LG_MAXOBJS_INIT 10
- size_t lg_maxobjs;
- quarantine_obj_t objs[1]; /* Dynamically sized ring buffer. */
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void quarantine_alloc_hook_work(tsd_t *tsd);
-void quarantine(tsd_t *tsd, void *ptr);
-void quarantine_cleanup(tsd_t *tsd);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-void quarantine_alloc_hook(void);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_QUARANTINE_C_))
-JEMALLOC_ALWAYS_INLINE void
-quarantine_alloc_hook(void)
-{
- tsd_t *tsd;
-
- assert(config_fill && opt_quarantine);
-
- tsd = tsd_fetch();
- if (tsd_quarantine_get(tsd) == NULL)
- quarantine_alloc_hook_work(tsd);
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-
diff --git a/memory/jemalloc/src/include/jemalloc/internal/rb.h b/memory/jemalloc/src/include/jemalloc/internal/rb.h
deleted file mode 100644
index 3770342f8..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/rb.h
+++ /dev/null
@@ -1,1003 +0,0 @@
-/*-
- *******************************************************************************
- *
- * cpp macro implementation of left-leaning 2-3 red-black trees. Parent
- * pointers are not used, and color bits are stored in the least significant
- * bit of right-child pointers (if RB_COMPACT is defined), thus making node
- * linkage as compact as is possible for red-black trees.
- *
- * Usage:
- *
- * #include <stdint.h>
- * #include <stdbool.h>
- * #define NDEBUG // (Optional, see assert(3).)
- * #include <assert.h>
- * #define RB_COMPACT // (Optional, embed color bits in right-child pointers.)
- * #include <rb.h>
- * ...
- *
- *******************************************************************************
- */
-
-#ifndef RB_H_
-#define RB_H_
-
-#ifdef RB_COMPACT
-/* Node structure. */
-#define rb_node(a_type) \
-struct { \
- a_type *rbn_left; \
- a_type *rbn_right_red; \
-}
-#else
-#define rb_node(a_type) \
-struct { \
- a_type *rbn_left; \
- a_type *rbn_right; \
- bool rbn_red; \
-}
-#endif
-
-/* Root structure. */
-#define rb_tree(a_type) \
-struct { \
- a_type *rbt_root; \
-}
-
-/* Left accessors. */
-#define rbtn_left_get(a_type, a_field, a_node) \
- ((a_node)->a_field.rbn_left)
-#define rbtn_left_set(a_type, a_field, a_node, a_left) do { \
- (a_node)->a_field.rbn_left = a_left; \
-} while (0)
-
-#ifdef RB_COMPACT
-/* Right accessors. */
-#define rbtn_right_get(a_type, a_field, a_node) \
- ((a_type *) (((intptr_t) (a_node)->a_field.rbn_right_red) \
- & ((ssize_t)-2)))
-#define rbtn_right_set(a_type, a_field, a_node, a_right) do { \
- (a_node)->a_field.rbn_right_red = (a_type *) (((uintptr_t) a_right) \
- | (((uintptr_t) (a_node)->a_field.rbn_right_red) & ((size_t)1))); \
-} while (0)
-
-/* Color accessors. */
-#define rbtn_red_get(a_type, a_field, a_node) \
- ((bool) (((uintptr_t) (a_node)->a_field.rbn_right_red) \
- & ((size_t)1)))
-#define rbtn_color_set(a_type, a_field, a_node, a_red) do { \
- (a_node)->a_field.rbn_right_red = (a_type *) ((((intptr_t) \
- (a_node)->a_field.rbn_right_red) & ((ssize_t)-2)) \
- | ((ssize_t)a_red)); \
-} while (0)
-#define rbtn_red_set(a_type, a_field, a_node) do { \
- (a_node)->a_field.rbn_right_red = (a_type *) (((uintptr_t) \
- (a_node)->a_field.rbn_right_red) | ((size_t)1)); \
-} while (0)
-#define rbtn_black_set(a_type, a_field, a_node) do { \
- (a_node)->a_field.rbn_right_red = (a_type *) (((intptr_t) \
- (a_node)->a_field.rbn_right_red) & ((ssize_t)-2)); \
-} while (0)
-
-/* Node initializer. */
-#define rbt_node_new(a_type, a_field, a_rbt, a_node) do { \
- /* Bookkeeping bit cannot be used by node pointer. */ \
- assert(((uintptr_t)(a_node) & 0x1) == 0); \
- rbtn_left_set(a_type, a_field, (a_node), NULL); \
- rbtn_right_set(a_type, a_field, (a_node), NULL); \
- rbtn_red_set(a_type, a_field, (a_node)); \
-} while (0)
-#else
-/* Right accessors. */
-#define rbtn_right_get(a_type, a_field, a_node) \
- ((a_node)->a_field.rbn_right)
-#define rbtn_right_set(a_type, a_field, a_node, a_right) do { \
- (a_node)->a_field.rbn_right = a_right; \
-} while (0)
-
-/* Color accessors. */
-#define rbtn_red_get(a_type, a_field, a_node) \
- ((a_node)->a_field.rbn_red)
-#define rbtn_color_set(a_type, a_field, a_node, a_red) do { \
- (a_node)->a_field.rbn_red = (a_red); \
-} while (0)
-#define rbtn_red_set(a_type, a_field, a_node) do { \
- (a_node)->a_field.rbn_red = true; \
-} while (0)
-#define rbtn_black_set(a_type, a_field, a_node) do { \
- (a_node)->a_field.rbn_red = false; \
-} while (0)
-
-/* Node initializer. */
-#define rbt_node_new(a_type, a_field, a_rbt, a_node) do { \
- rbtn_left_set(a_type, a_field, (a_node), NULL); \
- rbtn_right_set(a_type, a_field, (a_node), NULL); \
- rbtn_red_set(a_type, a_field, (a_node)); \
-} while (0)
-#endif
-
-/* Tree initializer. */
-#define rb_new(a_type, a_field, a_rbt) do { \
- (a_rbt)->rbt_root = NULL; \
-} while (0)
-
-/* Internal utility macros. */
-#define rbtn_first(a_type, a_field, a_rbt, a_root, r_node) do { \
- (r_node) = (a_root); \
- if ((r_node) != NULL) { \
- for (; \
- rbtn_left_get(a_type, a_field, (r_node)) != NULL; \
- (r_node) = rbtn_left_get(a_type, a_field, (r_node))) { \
- } \
- } \
-} while (0)
-
-#define rbtn_last(a_type, a_field, a_rbt, a_root, r_node) do { \
- (r_node) = (a_root); \
- if ((r_node) != NULL) { \
- for (; rbtn_right_get(a_type, a_field, (r_node)) != NULL; \
- (r_node) = rbtn_right_get(a_type, a_field, (r_node))) { \
- } \
- } \
-} while (0)
-
-#define rbtn_rotate_left(a_type, a_field, a_node, r_node) do { \
- (r_node) = rbtn_right_get(a_type, a_field, (a_node)); \
- rbtn_right_set(a_type, a_field, (a_node), \
- rbtn_left_get(a_type, a_field, (r_node))); \
- rbtn_left_set(a_type, a_field, (r_node), (a_node)); \
-} while (0)
-
-#define rbtn_rotate_right(a_type, a_field, a_node, r_node) do { \
- (r_node) = rbtn_left_get(a_type, a_field, (a_node)); \
- rbtn_left_set(a_type, a_field, (a_node), \
- rbtn_right_get(a_type, a_field, (r_node))); \
- rbtn_right_set(a_type, a_field, (r_node), (a_node)); \
-} while (0)
-
-/*
- * The rb_proto() macro generates function prototypes that correspond to the
- * functions generated by an equivalently parameterized call to rb_gen().
- */
-
-#define rb_proto(a_attr, a_prefix, a_rbt_type, a_type) \
-a_attr void \
-a_prefix##new(a_rbt_type *rbtree); \
-a_attr bool \
-a_prefix##empty(a_rbt_type *rbtree); \
-a_attr a_type * \
-a_prefix##first(a_rbt_type *rbtree); \
-a_attr a_type * \
-a_prefix##last(a_rbt_type *rbtree); \
-a_attr a_type * \
-a_prefix##next(a_rbt_type *rbtree, a_type *node); \
-a_attr a_type * \
-a_prefix##prev(a_rbt_type *rbtree, a_type *node); \
-a_attr a_type * \
-a_prefix##search(a_rbt_type *rbtree, const a_type *key); \
-a_attr a_type * \
-a_prefix##nsearch(a_rbt_type *rbtree, const a_type *key); \
-a_attr a_type * \
-a_prefix##psearch(a_rbt_type *rbtree, const a_type *key); \
-a_attr void \
-a_prefix##insert(a_rbt_type *rbtree, a_type *node); \
-a_attr void \
-a_prefix##remove(a_rbt_type *rbtree, a_type *node); \
-a_attr a_type * \
-a_prefix##iter(a_rbt_type *rbtree, a_type *start, a_type *(*cb)( \
- a_rbt_type *, a_type *, void *), void *arg); \
-a_attr a_type * \
-a_prefix##reverse_iter(a_rbt_type *rbtree, a_type *start, \
- a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg); \
-a_attr void \
-a_prefix##destroy(a_rbt_type *rbtree, void (*cb)(a_type *, void *), \
- void *arg);
-
-/*
- * The rb_gen() macro generates a type-specific red-black tree implementation,
- * based on the above cpp macros.
- *
- * Arguments:
- *
- * a_attr : Function attribute for generated functions (ex: static).
- * a_prefix : Prefix for generated functions (ex: ex_).
- * a_rb_type : Type for red-black tree data structure (ex: ex_t).
- * a_type : Type for red-black tree node data structure (ex: ex_node_t).
- * a_field : Name of red-black tree node linkage (ex: ex_link).
- * a_cmp : Node comparison function name, with the following prototype:
- * int (a_cmp *)(a_type *a_node, a_type *a_other);
- * ^^^^^^
- * or a_key
- * Interpretation of comparison function return values:
- * -1 : a_node < a_other
- * 0 : a_node == a_other
- * 1 : a_node > a_other
- * In all cases, the a_node or a_key macro argument is the first
- * argument to the comparison function, which makes it possible
- * to write comparison functions that treat the first argument
- * specially.
- *
- * Assuming the following setup:
- *
- * typedef struct ex_node_s ex_node_t;
- * struct ex_node_s {
- * rb_node(ex_node_t) ex_link;
- * };
- * typedef rb_tree(ex_node_t) ex_t;
- * rb_gen(static, ex_, ex_t, ex_node_t, ex_link, ex_cmp)
- *
- * The following API is generated:
- *
- * static void
- * ex_new(ex_t *tree);
- * Description: Initialize a red-black tree structure.
- * Args:
- * tree: Pointer to an uninitialized red-black tree object.
- *
- * static bool
- * ex_empty(ex_t *tree);
- * Description: Determine whether tree is empty.
- * Args:
- * tree: Pointer to an initialized red-black tree object.
- * Ret: True if tree is empty, false otherwise.
- *
- * static ex_node_t *
- * ex_first(ex_t *tree);
- * static ex_node_t *
- * ex_last(ex_t *tree);
- * Description: Get the first/last node in tree.
- * Args:
- * tree: Pointer to an initialized red-black tree object.
- * Ret: First/last node in tree, or NULL if tree is empty.
- *
- * static ex_node_t *
- * ex_next(ex_t *tree, ex_node_t *node);
- * static ex_node_t *
- * ex_prev(ex_t *tree, ex_node_t *node);
- * Description: Get node's successor/predecessor.
- * Args:
- * tree: Pointer to an initialized red-black tree object.
- * node: A node in tree.
- * Ret: node's successor/predecessor in tree, or NULL if node is
- * last/first.
- *
- * static ex_node_t *
- * ex_search(ex_t *tree, const ex_node_t *key);
- * Description: Search for node that matches key.
- * Args:
- * tree: Pointer to an initialized red-black tree object.
- * key : Search key.
- * Ret: Node in tree that matches key, or NULL if no match.
- *
- * static ex_node_t *
- * ex_nsearch(ex_t *tree, const ex_node_t *key);
- * static ex_node_t *
- * ex_psearch(ex_t *tree, const ex_node_t *key);
- * Description: Search for node that matches key. If no match is found,
- * return what would be key's successor/predecessor, were
- * key in tree.
- * Args:
- * tree: Pointer to an initialized red-black tree object.
- * key : Search key.
- * Ret: Node in tree that matches key, or if no match, hypothetical node's
- * successor/predecessor (NULL if no successor/predecessor).
- *
- * static void
- * ex_insert(ex_t *tree, ex_node_t *node);
- * Description: Insert node into tree.
- * Args:
- * tree: Pointer to an initialized red-black tree object.
- * node: Node to be inserted into tree.
- *
- * static void
- * ex_remove(ex_t *tree, ex_node_t *node);
- * Description: Remove node from tree.
- * Args:
- * tree: Pointer to an initialized red-black tree object.
- * node: Node in tree to be removed.
- *
- * static ex_node_t *
- * ex_iter(ex_t *tree, ex_node_t *start, ex_node_t *(*cb)(ex_t *,
- * ex_node_t *, void *), void *arg);
- * static ex_node_t *
- * ex_reverse_iter(ex_t *tree, ex_node_t *start, ex_node *(*cb)(ex_t *,
- * ex_node_t *, void *), void *arg);
- * Description: Iterate forward/backward over tree, starting at node. If
- * tree is modified, iteration must be immediately
- * terminated by the callback function that causes the
- * modification.
- * Args:
- * tree : Pointer to an initialized red-black tree object.
- * start: Node at which to start iteration, or NULL to start at
- * first/last node.
- * cb : Callback function, which is called for each node during
- * iteration. Under normal circumstances the callback function
- * should return NULL, which causes iteration to continue. If a
- * callback function returns non-NULL, iteration is immediately
- * terminated and the non-NULL return value is returned by the
- * iterator. This is useful for re-starting iteration after
- * modifying tree.
- * arg : Opaque pointer passed to cb().
- * Ret: NULL if iteration completed, or the non-NULL callback return value
- * that caused termination of the iteration.
- *
- * static void
- * ex_destroy(ex_t *tree, void (*cb)(ex_node_t *, void *), void *arg);
- * Description: Iterate over the tree with post-order traversal, remove
- * each node, and run the callback if non-null. This is
- * used for destroying a tree without paying the cost to
- * rebalance it. The tree must not be otherwise altered
- * during traversal.
- * Args:
- * tree: Pointer to an initialized red-black tree object.
- * cb : Callback function, which, if non-null, is called for each node
- * during iteration. There is no way to stop iteration once it
- * has begun.
- * arg : Opaque pointer passed to cb().
- */
-#define rb_gen(a_attr, a_prefix, a_rbt_type, a_type, a_field, a_cmp) \
-a_attr void \
-a_prefix##new(a_rbt_type *rbtree) { \
- rb_new(a_type, a_field, rbtree); \
-} \
-a_attr bool \
-a_prefix##empty(a_rbt_type *rbtree) { \
- return (rbtree->rbt_root == NULL); \
-} \
-a_attr a_type * \
-a_prefix##first(a_rbt_type *rbtree) { \
- a_type *ret; \
- rbtn_first(a_type, a_field, rbtree, rbtree->rbt_root, ret); \
- return (ret); \
-} \
-a_attr a_type * \
-a_prefix##last(a_rbt_type *rbtree) { \
- a_type *ret; \
- rbtn_last(a_type, a_field, rbtree, rbtree->rbt_root, ret); \
- return (ret); \
-} \
-a_attr a_type * \
-a_prefix##next(a_rbt_type *rbtree, a_type *node) { \
- a_type *ret; \
- if (rbtn_right_get(a_type, a_field, node) != NULL) { \
- rbtn_first(a_type, a_field, rbtree, rbtn_right_get(a_type, \
- a_field, node), ret); \
- } else { \
- a_type *tnode = rbtree->rbt_root; \
- assert(tnode != NULL); \
- ret = NULL; \
- while (true) { \
- int cmp = (a_cmp)(node, tnode); \
- if (cmp < 0) { \
- ret = tnode; \
- tnode = rbtn_left_get(a_type, a_field, tnode); \
- } else if (cmp > 0) { \
- tnode = rbtn_right_get(a_type, a_field, tnode); \
- } else { \
- break; \
- } \
- assert(tnode != NULL); \
- } \
- } \
- return (ret); \
-} \
-a_attr a_type * \
-a_prefix##prev(a_rbt_type *rbtree, a_type *node) { \
- a_type *ret; \
- if (rbtn_left_get(a_type, a_field, node) != NULL) { \
- rbtn_last(a_type, a_field, rbtree, rbtn_left_get(a_type, \
- a_field, node), ret); \
- } else { \
- a_type *tnode = rbtree->rbt_root; \
- assert(tnode != NULL); \
- ret = NULL; \
- while (true) { \
- int cmp = (a_cmp)(node, tnode); \
- if (cmp < 0) { \
- tnode = rbtn_left_get(a_type, a_field, tnode); \
- } else if (cmp > 0) { \
- ret = tnode; \
- tnode = rbtn_right_get(a_type, a_field, tnode); \
- } else { \
- break; \
- } \
- assert(tnode != NULL); \
- } \
- } \
- return (ret); \
-} \
-a_attr a_type * \
-a_prefix##search(a_rbt_type *rbtree, const a_type *key) { \
- a_type *ret; \
- int cmp; \
- ret = rbtree->rbt_root; \
- while (ret != NULL \
- && (cmp = (a_cmp)(key, ret)) != 0) { \
- if (cmp < 0) { \
- ret = rbtn_left_get(a_type, a_field, ret); \
- } else { \
- ret = rbtn_right_get(a_type, a_field, ret); \
- } \
- } \
- return (ret); \
-} \
-a_attr a_type * \
-a_prefix##nsearch(a_rbt_type *rbtree, const a_type *key) { \
- a_type *ret; \
- a_type *tnode = rbtree->rbt_root; \
- ret = NULL; \
- while (tnode != NULL) { \
- int cmp = (a_cmp)(key, tnode); \
- if (cmp < 0) { \
- ret = tnode; \
- tnode = rbtn_left_get(a_type, a_field, tnode); \
- } else if (cmp > 0) { \
- tnode = rbtn_right_get(a_type, a_field, tnode); \
- } else { \
- ret = tnode; \
- break; \
- } \
- } \
- return (ret); \
-} \
-a_attr a_type * \
-a_prefix##psearch(a_rbt_type *rbtree, const a_type *key) { \
- a_type *ret; \
- a_type *tnode = rbtree->rbt_root; \
- ret = NULL; \
- while (tnode != NULL) { \
- int cmp = (a_cmp)(key, tnode); \
- if (cmp < 0) { \
- tnode = rbtn_left_get(a_type, a_field, tnode); \
- } else if (cmp > 0) { \
- ret = tnode; \
- tnode = rbtn_right_get(a_type, a_field, tnode); \
- } else { \
- ret = tnode; \
- break; \
- } \
- } \
- return (ret); \
-} \
-a_attr void \
-a_prefix##insert(a_rbt_type *rbtree, a_type *node) { \
- struct { \
- a_type *node; \
- int cmp; \
- } path[sizeof(void *) << 4], *pathp; \
- rbt_node_new(a_type, a_field, rbtree, node); \
- /* Wind. */ \
- path->node = rbtree->rbt_root; \
- for (pathp = path; pathp->node != NULL; pathp++) { \
- int cmp = pathp->cmp = a_cmp(node, pathp->node); \
- assert(cmp != 0); \
- if (cmp < 0) { \
- pathp[1].node = rbtn_left_get(a_type, a_field, \
- pathp->node); \
- } else { \
- pathp[1].node = rbtn_right_get(a_type, a_field, \
- pathp->node); \
- } \
- } \
- pathp->node = node; \
- /* Unwind. */ \
- for (pathp--; (uintptr_t)pathp >= (uintptr_t)path; pathp--) { \
- a_type *cnode = pathp->node; \
- if (pathp->cmp < 0) { \
- a_type *left = pathp[1].node; \
- rbtn_left_set(a_type, a_field, cnode, left); \
- if (rbtn_red_get(a_type, a_field, left)) { \
- a_type *leftleft = rbtn_left_get(a_type, a_field, left);\
- if (leftleft != NULL && rbtn_red_get(a_type, a_field, \
- leftleft)) { \
- /* Fix up 4-node. */ \
- a_type *tnode; \
- rbtn_black_set(a_type, a_field, leftleft); \
- rbtn_rotate_right(a_type, a_field, cnode, tnode); \
- cnode = tnode; \
- } \
- } else { \
- return; \
- } \
- } else { \
- a_type *right = pathp[1].node; \
- rbtn_right_set(a_type, a_field, cnode, right); \
- if (rbtn_red_get(a_type, a_field, right)) { \
- a_type *left = rbtn_left_get(a_type, a_field, cnode); \
- if (left != NULL && rbtn_red_get(a_type, a_field, \
- left)) { \
- /* Split 4-node. */ \
- rbtn_black_set(a_type, a_field, left); \
- rbtn_black_set(a_type, a_field, right); \
- rbtn_red_set(a_type, a_field, cnode); \
- } else { \
- /* Lean left. */ \
- a_type *tnode; \
- bool tred = rbtn_red_get(a_type, a_field, cnode); \
- rbtn_rotate_left(a_type, a_field, cnode, tnode); \
- rbtn_color_set(a_type, a_field, tnode, tred); \
- rbtn_red_set(a_type, a_field, cnode); \
- cnode = tnode; \
- } \
- } else { \
- return; \
- } \
- } \
- pathp->node = cnode; \
- } \
- /* Set root, and make it black. */ \
- rbtree->rbt_root = path->node; \
- rbtn_black_set(a_type, a_field, rbtree->rbt_root); \
-} \
-a_attr void \
-a_prefix##remove(a_rbt_type *rbtree, a_type *node) { \
- struct { \
- a_type *node; \
- int cmp; \
- } *pathp, *nodep, path[sizeof(void *) << 4]; \
- /* Wind. */ \
- nodep = NULL; /* Silence compiler warning. */ \
- path->node = rbtree->rbt_root; \
- for (pathp = path; pathp->node != NULL; pathp++) { \
- int cmp = pathp->cmp = a_cmp(node, pathp->node); \
- if (cmp < 0) { \
- pathp[1].node = rbtn_left_get(a_type, a_field, \
- pathp->node); \
- } else { \
- pathp[1].node = rbtn_right_get(a_type, a_field, \
- pathp->node); \
- if (cmp == 0) { \
- /* Find node's successor, in preparation for swap. */ \
- pathp->cmp = 1; \
- nodep = pathp; \
- for (pathp++; pathp->node != NULL; \
- pathp++) { \
- pathp->cmp = -1; \
- pathp[1].node = rbtn_left_get(a_type, a_field, \
- pathp->node); \
- } \
- break; \
- } \
- } \
- } \
- assert(nodep->node == node); \
- pathp--; \
- if (pathp->node != node) { \
- /* Swap node with its successor. */ \
- bool tred = rbtn_red_get(a_type, a_field, pathp->node); \
- rbtn_color_set(a_type, a_field, pathp->node, \
- rbtn_red_get(a_type, a_field, node)); \
- rbtn_left_set(a_type, a_field, pathp->node, \
- rbtn_left_get(a_type, a_field, node)); \
- /* If node's successor is its right child, the following code */\
- /* will do the wrong thing for the right child pointer. */\
- /* However, it doesn't matter, because the pointer will be */\
- /* properly set when the successor is pruned. */\
- rbtn_right_set(a_type, a_field, pathp->node, \
- rbtn_right_get(a_type, a_field, node)); \
- rbtn_color_set(a_type, a_field, node, tred); \
- /* The pruned leaf node's child pointers are never accessed */\
- /* again, so don't bother setting them to nil. */\
- nodep->node = pathp->node; \
- pathp->node = node; \
- if (nodep == path) { \
- rbtree->rbt_root = nodep->node; \
- } else { \
- if (nodep[-1].cmp < 0) { \
- rbtn_left_set(a_type, a_field, nodep[-1].node, \
- nodep->node); \
- } else { \
- rbtn_right_set(a_type, a_field, nodep[-1].node, \
- nodep->node); \
- } \
- } \
- } else { \
- a_type *left = rbtn_left_get(a_type, a_field, node); \
- if (left != NULL) { \
- /* node has no successor, but it has a left child. */\
- /* Splice node out, without losing the left child. */\
- assert(!rbtn_red_get(a_type, a_field, node)); \
- assert(rbtn_red_get(a_type, a_field, left)); \
- rbtn_black_set(a_type, a_field, left); \
- if (pathp == path) { \
- rbtree->rbt_root = left; \
- } else { \
- if (pathp[-1].cmp < 0) { \
- rbtn_left_set(a_type, a_field, pathp[-1].node, \
- left); \
- } else { \
- rbtn_right_set(a_type, a_field, pathp[-1].node, \
- left); \
- } \
- } \
- return; \
- } else if (pathp == path) { \
- /* The tree only contained one node. */ \
- rbtree->rbt_root = NULL; \
- return; \
- } \
- } \
- if (rbtn_red_get(a_type, a_field, pathp->node)) { \
- /* Prune red node, which requires no fixup. */ \
- assert(pathp[-1].cmp < 0); \
- rbtn_left_set(a_type, a_field, pathp[-1].node, NULL); \
- return; \
- } \
- /* The node to be pruned is black, so unwind until balance is */\
- /* restored. */\
- pathp->node = NULL; \
- for (pathp--; (uintptr_t)pathp >= (uintptr_t)path; pathp--) { \
- assert(pathp->cmp != 0); \
- if (pathp->cmp < 0) { \
- rbtn_left_set(a_type, a_field, pathp->node, \
- pathp[1].node); \
- if (rbtn_red_get(a_type, a_field, pathp->node)) { \
- a_type *right = rbtn_right_get(a_type, a_field, \
- pathp->node); \
- a_type *rightleft = rbtn_left_get(a_type, a_field, \
- right); \
- a_type *tnode; \
- if (rightleft != NULL && rbtn_red_get(a_type, a_field, \
- rightleft)) { \
- /* In the following diagrams, ||, //, and \\ */\
- /* indicate the path to the removed node. */\
- /* */\
- /* || */\
- /* pathp(r) */\
- /* // \ */\
- /* (b) (b) */\
- /* / */\
- /* (r) */\
- /* */\
- rbtn_black_set(a_type, a_field, pathp->node); \
- rbtn_rotate_right(a_type, a_field, right, tnode); \
- rbtn_right_set(a_type, a_field, pathp->node, tnode);\
- rbtn_rotate_left(a_type, a_field, pathp->node, \
- tnode); \
- } else { \
- /* || */\
- /* pathp(r) */\
- /* // \ */\
- /* (b) (b) */\
- /* / */\
- /* (b) */\
- /* */\
- rbtn_rotate_left(a_type, a_field, pathp->node, \
- tnode); \
- } \
- /* Balance restored, but rotation modified subtree */\
- /* root. */\
- assert((uintptr_t)pathp > (uintptr_t)path); \
- if (pathp[-1].cmp < 0) { \
- rbtn_left_set(a_type, a_field, pathp[-1].node, \
- tnode); \
- } else { \
- rbtn_right_set(a_type, a_field, pathp[-1].node, \
- tnode); \
- } \
- return; \
- } else { \
- a_type *right = rbtn_right_get(a_type, a_field, \
- pathp->node); \
- a_type *rightleft = rbtn_left_get(a_type, a_field, \
- right); \
- if (rightleft != NULL && rbtn_red_get(a_type, a_field, \
- rightleft)) { \
- /* || */\
- /* pathp(b) */\
- /* // \ */\
- /* (b) (b) */\
- /* / */\
- /* (r) */\
- a_type *tnode; \
- rbtn_black_set(a_type, a_field, rightleft); \
- rbtn_rotate_right(a_type, a_field, right, tnode); \
- rbtn_right_set(a_type, a_field, pathp->node, tnode);\
- rbtn_rotate_left(a_type, a_field, pathp->node, \
- tnode); \
- /* Balance restored, but rotation modified */\
- /* subtree root, which may actually be the tree */\
- /* root. */\
- if (pathp == path) { \
- /* Set root. */ \
- rbtree->rbt_root = tnode; \
- } else { \
- if (pathp[-1].cmp < 0) { \
- rbtn_left_set(a_type, a_field, \
- pathp[-1].node, tnode); \
- } else { \
- rbtn_right_set(a_type, a_field, \
- pathp[-1].node, tnode); \
- } \
- } \
- return; \
- } else { \
- /* || */\
- /* pathp(b) */\
- /* // \ */\
- /* (b) (b) */\
- /* / */\
- /* (b) */\
- a_type *tnode; \
- rbtn_red_set(a_type, a_field, pathp->node); \
- rbtn_rotate_left(a_type, a_field, pathp->node, \
- tnode); \
- pathp->node = tnode; \
- } \
- } \
- } else { \
- a_type *left; \
- rbtn_right_set(a_type, a_field, pathp->node, \
- pathp[1].node); \
- left = rbtn_left_get(a_type, a_field, pathp->node); \
- if (rbtn_red_get(a_type, a_field, left)) { \
- a_type *tnode; \
- a_type *leftright = rbtn_right_get(a_type, a_field, \
- left); \
- a_type *leftrightleft = rbtn_left_get(a_type, a_field, \
- leftright); \
- if (leftrightleft != NULL && rbtn_red_get(a_type, \
- a_field, leftrightleft)) { \
- /* || */\
- /* pathp(b) */\
- /* / \\ */\
- /* (r) (b) */\
- /* \ */\
- /* (b) */\
- /* / */\
- /* (r) */\
- a_type *unode; \
- rbtn_black_set(a_type, a_field, leftrightleft); \
- rbtn_rotate_right(a_type, a_field, pathp->node, \
- unode); \
- rbtn_rotate_right(a_type, a_field, pathp->node, \
- tnode); \
- rbtn_right_set(a_type, a_field, unode, tnode); \
- rbtn_rotate_left(a_type, a_field, unode, tnode); \
- } else { \
- /* || */\
- /* pathp(b) */\
- /* / \\ */\
- /* (r) (b) */\
- /* \ */\
- /* (b) */\
- /* / */\
- /* (b) */\
- assert(leftright != NULL); \
- rbtn_red_set(a_type, a_field, leftright); \
- rbtn_rotate_right(a_type, a_field, pathp->node, \
- tnode); \
- rbtn_black_set(a_type, a_field, tnode); \
- } \
- /* Balance restored, but rotation modified subtree */\
- /* root, which may actually be the tree root. */\
- if (pathp == path) { \
- /* Set root. */ \
- rbtree->rbt_root = tnode; \
- } else { \
- if (pathp[-1].cmp < 0) { \
- rbtn_left_set(a_type, a_field, pathp[-1].node, \
- tnode); \
- } else { \
- rbtn_right_set(a_type, a_field, pathp[-1].node, \
- tnode); \
- } \
- } \
- return; \
- } else if (rbtn_red_get(a_type, a_field, pathp->node)) { \
- a_type *leftleft = rbtn_left_get(a_type, a_field, left);\
- if (leftleft != NULL && rbtn_red_get(a_type, a_field, \
- leftleft)) { \
- /* || */\
- /* pathp(r) */\
- /* / \\ */\
- /* (b) (b) */\
- /* / */\
- /* (r) */\
- a_type *tnode; \
- rbtn_black_set(a_type, a_field, pathp->node); \
- rbtn_red_set(a_type, a_field, left); \
- rbtn_black_set(a_type, a_field, leftleft); \
- rbtn_rotate_right(a_type, a_field, pathp->node, \
- tnode); \
- /* Balance restored, but rotation modified */\
- /* subtree root. */\
- assert((uintptr_t)pathp > (uintptr_t)path); \
- if (pathp[-1].cmp < 0) { \
- rbtn_left_set(a_type, a_field, pathp[-1].node, \
- tnode); \
- } else { \
- rbtn_right_set(a_type, a_field, pathp[-1].node, \
- tnode); \
- } \
- return; \
- } else { \
- /* || */\
- /* pathp(r) */\
- /* / \\ */\
- /* (b) (b) */\
- /* / */\
- /* (b) */\
- rbtn_red_set(a_type, a_field, left); \
- rbtn_black_set(a_type, a_field, pathp->node); \
- /* Balance restored. */ \
- return; \
- } \
- } else { \
- a_type *leftleft = rbtn_left_get(a_type, a_field, left);\
- if (leftleft != NULL && rbtn_red_get(a_type, a_field, \
- leftleft)) { \
- /* || */\
- /* pathp(b) */\
- /* / \\ */\
- /* (b) (b) */\
- /* / */\
- /* (r) */\
- a_type *tnode; \
- rbtn_black_set(a_type, a_field, leftleft); \
- rbtn_rotate_right(a_type, a_field, pathp->node, \
- tnode); \
- /* Balance restored, but rotation modified */\
- /* subtree root, which may actually be the tree */\
- /* root. */\
- if (pathp == path) { \
- /* Set root. */ \
- rbtree->rbt_root = tnode; \
- } else { \
- if (pathp[-1].cmp < 0) { \
- rbtn_left_set(a_type, a_field, \
- pathp[-1].node, tnode); \
- } else { \
- rbtn_right_set(a_type, a_field, \
- pathp[-1].node, tnode); \
- } \
- } \
- return; \
- } else { \
- /* || */\
- /* pathp(b) */\
- /* / \\ */\
- /* (b) (b) */\
- /* / */\
- /* (b) */\
- rbtn_red_set(a_type, a_field, left); \
- } \
- } \
- } \
- } \
- /* Set root. */ \
- rbtree->rbt_root = path->node; \
- assert(!rbtn_red_get(a_type, a_field, rbtree->rbt_root)); \
-} \
-a_attr a_type * \
-a_prefix##iter_recurse(a_rbt_type *rbtree, a_type *node, \
- a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \
- if (node == NULL) { \
- return (NULL); \
- } else { \
- a_type *ret; \
- if ((ret = a_prefix##iter_recurse(rbtree, rbtn_left_get(a_type, \
- a_field, node), cb, arg)) != NULL || (ret = cb(rbtree, node, \
- arg)) != NULL) { \
- return (ret); \
- } \
- return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \
- a_field, node), cb, arg)); \
- } \
-} \
-a_attr a_type * \
-a_prefix##iter_start(a_rbt_type *rbtree, a_type *start, a_type *node, \
- a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \
- int cmp = a_cmp(start, node); \
- if (cmp < 0) { \
- a_type *ret; \
- if ((ret = a_prefix##iter_start(rbtree, start, \
- rbtn_left_get(a_type, a_field, node), cb, arg)) != NULL || \
- (ret = cb(rbtree, node, arg)) != NULL) { \
- return (ret); \
- } \
- return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \
- a_field, node), cb, arg)); \
- } else if (cmp > 0) { \
- return (a_prefix##iter_start(rbtree, start, \
- rbtn_right_get(a_type, a_field, node), cb, arg)); \
- } else { \
- a_type *ret; \
- if ((ret = cb(rbtree, node, arg)) != NULL) { \
- return (ret); \
- } \
- return (a_prefix##iter_recurse(rbtree, rbtn_right_get(a_type, \
- a_field, node), cb, arg)); \
- } \
-} \
-a_attr a_type * \
-a_prefix##iter(a_rbt_type *rbtree, a_type *start, a_type *(*cb)( \
- a_rbt_type *, a_type *, void *), void *arg) { \
- a_type *ret; \
- if (start != NULL) { \
- ret = a_prefix##iter_start(rbtree, start, rbtree->rbt_root, \
- cb, arg); \
- } else { \
- ret = a_prefix##iter_recurse(rbtree, rbtree->rbt_root, cb, arg);\
- } \
- return (ret); \
-} \
-a_attr a_type * \
-a_prefix##reverse_iter_recurse(a_rbt_type *rbtree, a_type *node, \
- a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \
- if (node == NULL) { \
- return (NULL); \
- } else { \
- a_type *ret; \
- if ((ret = a_prefix##reverse_iter_recurse(rbtree, \
- rbtn_right_get(a_type, a_field, node), cb, arg)) != NULL || \
- (ret = cb(rbtree, node, arg)) != NULL) { \
- return (ret); \
- } \
- return (a_prefix##reverse_iter_recurse(rbtree, \
- rbtn_left_get(a_type, a_field, node), cb, arg)); \
- } \
-} \
-a_attr a_type * \
-a_prefix##reverse_iter_start(a_rbt_type *rbtree, a_type *start, \
- a_type *node, a_type *(*cb)(a_rbt_type *, a_type *, void *), \
- void *arg) { \
- int cmp = a_cmp(start, node); \
- if (cmp > 0) { \
- a_type *ret; \
- if ((ret = a_prefix##reverse_iter_start(rbtree, start, \
- rbtn_right_get(a_type, a_field, node), cb, arg)) != NULL || \
- (ret = cb(rbtree, node, arg)) != NULL) { \
- return (ret); \
- } \
- return (a_prefix##reverse_iter_recurse(rbtree, \
- rbtn_left_get(a_type, a_field, node), cb, arg)); \
- } else if (cmp < 0) { \
- return (a_prefix##reverse_iter_start(rbtree, start, \
- rbtn_left_get(a_type, a_field, node), cb, arg)); \
- } else { \
- a_type *ret; \
- if ((ret = cb(rbtree, node, arg)) != NULL) { \
- return (ret); \
- } \
- return (a_prefix##reverse_iter_recurse(rbtree, \
- rbtn_left_get(a_type, a_field, node), cb, arg)); \
- } \
-} \
-a_attr a_type * \
-a_prefix##reverse_iter(a_rbt_type *rbtree, a_type *start, \
- a_type *(*cb)(a_rbt_type *, a_type *, void *), void *arg) { \
- a_type *ret; \
- if (start != NULL) { \
- ret = a_prefix##reverse_iter_start(rbtree, start, \
- rbtree->rbt_root, cb, arg); \
- } else { \
- ret = a_prefix##reverse_iter_recurse(rbtree, rbtree->rbt_root, \
- cb, arg); \
- } \
- return (ret); \
-} \
-a_attr void \
-a_prefix##destroy_recurse(a_rbt_type *rbtree, a_type *node, void (*cb)( \
- a_type *, void *), void *arg) { \
- if (node == NULL) { \
- return; \
- } \
- a_prefix##destroy_recurse(rbtree, rbtn_left_get(a_type, a_field, \
- node), cb, arg); \
- rbtn_left_set(a_type, a_field, (node), NULL); \
- a_prefix##destroy_recurse(rbtree, rbtn_right_get(a_type, a_field, \
- node), cb, arg); \
- rbtn_right_set(a_type, a_field, (node), NULL); \
- if (cb) { \
- cb(node, arg); \
- } \
-} \
-a_attr void \
-a_prefix##destroy(a_rbt_type *rbtree, void (*cb)(a_type *, void *), \
- void *arg) { \
- a_prefix##destroy_recurse(rbtree, rbtree->rbt_root, cb, arg); \
- rbtree->rbt_root = NULL; \
-}
-
-#endif /* RB_H_ */
diff --git a/memory/jemalloc/src/include/jemalloc/internal/rtree.h b/memory/jemalloc/src/include/jemalloc/internal/rtree.h
deleted file mode 100644
index 8d0c584da..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/rtree.h
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * This radix tree implementation is tailored to the singular purpose of
- * associating metadata with chunks that are currently owned by jemalloc.
- *
- *******************************************************************************
- */
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct rtree_node_elm_s rtree_node_elm_t;
-typedef struct rtree_level_s rtree_level_t;
-typedef struct rtree_s rtree_t;
-
-/*
- * RTREE_BITS_PER_LEVEL must be a power of two that is no larger than the
- * machine address width.
- */
-#define LG_RTREE_BITS_PER_LEVEL 4
-#define RTREE_BITS_PER_LEVEL (1U << LG_RTREE_BITS_PER_LEVEL)
-/* Maximum rtree height. */
-#define RTREE_HEIGHT_MAX \
- ((1U << (LG_SIZEOF_PTR+3)) / RTREE_BITS_PER_LEVEL)
-
-/* Used for two-stage lock-free node initialization. */
-#define RTREE_NODE_INITIALIZING ((rtree_node_elm_t *)0x1)
-
-/*
- * The node allocation callback function's argument is the number of contiguous
- * rtree_node_elm_t structures to allocate, and the resulting memory must be
- * zeroed.
- */
-typedef rtree_node_elm_t *(rtree_node_alloc_t)(size_t);
-typedef void (rtree_node_dalloc_t)(rtree_node_elm_t *);
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct rtree_node_elm_s {
- union {
- void *pun;
- rtree_node_elm_t *child;
- extent_node_t *val;
- };
-};
-
-struct rtree_level_s {
- /*
- * A non-NULL subtree points to a subtree rooted along the hypothetical
- * path to the leaf node corresponding to key 0. Depending on what keys
- * have been used to store to the tree, an arbitrary combination of
- * subtree pointers may remain NULL.
- *
- * Suppose keys comprise 48 bits, and LG_RTREE_BITS_PER_LEVEL is 4.
- * This results in a 3-level tree, and the leftmost leaf can be directly
- * accessed via subtrees[2], the subtree prefixed by 0x0000 (excluding
- * 0x00000000) can be accessed via subtrees[1], and the remainder of the
- * tree can be accessed via subtrees[0].
- *
- * levels[0] : [<unused> | 0x0001******** | 0x0002******** | ...]
- *
- * levels[1] : [<unused> | 0x00000001**** | 0x00000002**** | ... ]
- *
- * levels[2] : [val(0x000000000000) | val(0x000000000001) | ...]
- *
- * This has practical implications on x64, which currently uses only the
- * lower 47 bits of virtual address space in userland, thus leaving
- * subtrees[0] unused and avoiding a level of tree traversal.
- */
- union {
- void *subtree_pun;
- rtree_node_elm_t *subtree;
- };
- /* Number of key bits distinguished by this level. */
- unsigned bits;
- /*
- * Cumulative number of key bits distinguished by traversing to
- * corresponding tree level.
- */
- unsigned cumbits;
-};
-
-struct rtree_s {
- rtree_node_alloc_t *alloc;
- rtree_node_dalloc_t *dalloc;
- unsigned height;
- /*
- * Precomputed table used to convert from the number of leading 0 key
- * bits to which subtree level to start at.
- */
- unsigned start_level[RTREE_HEIGHT_MAX];
- rtree_level_t levels[RTREE_HEIGHT_MAX];
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-bool rtree_new(rtree_t *rtree, unsigned bits, rtree_node_alloc_t *alloc,
- rtree_node_dalloc_t *dalloc);
-void rtree_delete(rtree_t *rtree);
-rtree_node_elm_t *rtree_subtree_read_hard(rtree_t *rtree,
- unsigned level);
-rtree_node_elm_t *rtree_child_read_hard(rtree_t *rtree,
- rtree_node_elm_t *elm, unsigned level);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-unsigned rtree_start_level(rtree_t *rtree, uintptr_t key);
-uintptr_t rtree_subkey(rtree_t *rtree, uintptr_t key, unsigned level);
-
-bool rtree_node_valid(rtree_node_elm_t *node);
-rtree_node_elm_t *rtree_child_tryread(rtree_node_elm_t *elm,
- bool dependent);
-rtree_node_elm_t *rtree_child_read(rtree_t *rtree, rtree_node_elm_t *elm,
- unsigned level, bool dependent);
-extent_node_t *rtree_val_read(rtree_t *rtree, rtree_node_elm_t *elm,
- bool dependent);
-void rtree_val_write(rtree_t *rtree, rtree_node_elm_t *elm,
- const extent_node_t *val);
-rtree_node_elm_t *rtree_subtree_tryread(rtree_t *rtree, unsigned level,
- bool dependent);
-rtree_node_elm_t *rtree_subtree_read(rtree_t *rtree, unsigned level,
- bool dependent);
-
-extent_node_t *rtree_get(rtree_t *rtree, uintptr_t key, bool dependent);
-bool rtree_set(rtree_t *rtree, uintptr_t key, const extent_node_t *val);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_RTREE_C_))
-JEMALLOC_ALWAYS_INLINE unsigned
-rtree_start_level(rtree_t *rtree, uintptr_t key)
-{
- unsigned start_level;
-
- if (unlikely(key == 0))
- return (rtree->height - 1);
-
- start_level = rtree->start_level[lg_floor(key) >>
- LG_RTREE_BITS_PER_LEVEL];
- assert(start_level < rtree->height);
- return (start_level);
-}
-
-JEMALLOC_ALWAYS_INLINE uintptr_t
-rtree_subkey(rtree_t *rtree, uintptr_t key, unsigned level)
-{
-
- return ((key >> ((ZU(1) << (LG_SIZEOF_PTR+3)) -
- rtree->levels[level].cumbits)) & ((ZU(1) <<
- rtree->levels[level].bits) - 1));
-}
-
-JEMALLOC_ALWAYS_INLINE bool
-rtree_node_valid(rtree_node_elm_t *node)
-{
-
- return ((uintptr_t)node > (uintptr_t)RTREE_NODE_INITIALIZING);
-}
-
-JEMALLOC_ALWAYS_INLINE rtree_node_elm_t *
-rtree_child_tryread(rtree_node_elm_t *elm, bool dependent)
-{
- rtree_node_elm_t *child;
-
- /* Double-checked read (first read may be stale. */
- child = elm->child;
- if (!dependent && !rtree_node_valid(child))
- child = atomic_read_p(&elm->pun);
- assert(!dependent || child != NULL);
- return (child);
-}
-
-JEMALLOC_ALWAYS_INLINE rtree_node_elm_t *
-rtree_child_read(rtree_t *rtree, rtree_node_elm_t *elm, unsigned level,
- bool dependent)
-{
- rtree_node_elm_t *child;
-
- child = rtree_child_tryread(elm, dependent);
- if (!dependent && unlikely(!rtree_node_valid(child)))
- child = rtree_child_read_hard(rtree, elm, level);
- assert(!dependent || child != NULL);
- return (child);
-}
-
-JEMALLOC_ALWAYS_INLINE extent_node_t *
-rtree_val_read(rtree_t *rtree, rtree_node_elm_t *elm, bool dependent)
-{
-
- if (dependent) {
- /*
- * Reading a val on behalf of a pointer to a valid allocation is
- * guaranteed to be a clean read even without synchronization,
- * because the rtree update became visible in memory before the
- * pointer came into existence.
- */
- return (elm->val);
- } else {
- /*
- * An arbitrary read, e.g. on behalf of ivsalloc(), may not be
- * dependent on a previous rtree write, which means a stale read
- * could result if synchronization were omitted here.
- */
- return (atomic_read_p(&elm->pun));
- }
-}
-
-JEMALLOC_INLINE void
-rtree_val_write(rtree_t *rtree, rtree_node_elm_t *elm, const extent_node_t *val)
-{
-
- atomic_write_p(&elm->pun, val);
-}
-
-JEMALLOC_ALWAYS_INLINE rtree_node_elm_t *
-rtree_subtree_tryread(rtree_t *rtree, unsigned level, bool dependent)
-{
- rtree_node_elm_t *subtree;
-
- /* Double-checked read (first read may be stale. */
- subtree = rtree->levels[level].subtree;
- if (!dependent && unlikely(!rtree_node_valid(subtree)))
- subtree = atomic_read_p(&rtree->levels[level].subtree_pun);
- assert(!dependent || subtree != NULL);
- return (subtree);
-}
-
-JEMALLOC_ALWAYS_INLINE rtree_node_elm_t *
-rtree_subtree_read(rtree_t *rtree, unsigned level, bool dependent)
-{
- rtree_node_elm_t *subtree;
-
- subtree = rtree_subtree_tryread(rtree, level, dependent);
- if (!dependent && unlikely(!rtree_node_valid(subtree)))
- subtree = rtree_subtree_read_hard(rtree, level);
- assert(!dependent || subtree != NULL);
- return (subtree);
-}
-
-JEMALLOC_ALWAYS_INLINE extent_node_t *
-rtree_get(rtree_t *rtree, uintptr_t key, bool dependent)
-{
- uintptr_t subkey;
- unsigned start_level;
- rtree_node_elm_t *node;
-
- start_level = rtree_start_level(rtree, key);
-
- node = rtree_subtree_tryread(rtree, start_level, dependent);
-#define RTREE_GET_BIAS (RTREE_HEIGHT_MAX - rtree->height)
- switch (start_level + RTREE_GET_BIAS) {
-#define RTREE_GET_SUBTREE(level) \
- case level: \
- assert(level < (RTREE_HEIGHT_MAX-1)); \
- if (!dependent && unlikely(!rtree_node_valid(node))) \
- return (NULL); \
- subkey = rtree_subkey(rtree, key, level - \
- RTREE_GET_BIAS); \
- node = rtree_child_tryread(&node[subkey], dependent); \
- /* Fall through. */
-#define RTREE_GET_LEAF(level) \
- case level: \
- assert(level == (RTREE_HEIGHT_MAX-1)); \
- if (!dependent && unlikely(!rtree_node_valid(node))) \
- return (NULL); \
- subkey = rtree_subkey(rtree, key, level - \
- RTREE_GET_BIAS); \
- /* \
- * node is a leaf, so it contains values rather than \
- * child pointers. \
- */ \
- return (rtree_val_read(rtree, &node[subkey], \
- dependent));
-#if RTREE_HEIGHT_MAX > 1
- RTREE_GET_SUBTREE(0)
-#endif
-#if RTREE_HEIGHT_MAX > 2
- RTREE_GET_SUBTREE(1)
-#endif
-#if RTREE_HEIGHT_MAX > 3
- RTREE_GET_SUBTREE(2)
-#endif
-#if RTREE_HEIGHT_MAX > 4
- RTREE_GET_SUBTREE(3)
-#endif
-#if RTREE_HEIGHT_MAX > 5
- RTREE_GET_SUBTREE(4)
-#endif
-#if RTREE_HEIGHT_MAX > 6
- RTREE_GET_SUBTREE(5)
-#endif
-#if RTREE_HEIGHT_MAX > 7
- RTREE_GET_SUBTREE(6)
-#endif
-#if RTREE_HEIGHT_MAX > 8
- RTREE_GET_SUBTREE(7)
-#endif
-#if RTREE_HEIGHT_MAX > 9
- RTREE_GET_SUBTREE(8)
-#endif
-#if RTREE_HEIGHT_MAX > 10
- RTREE_GET_SUBTREE(9)
-#endif
-#if RTREE_HEIGHT_MAX > 11
- RTREE_GET_SUBTREE(10)
-#endif
-#if RTREE_HEIGHT_MAX > 12
- RTREE_GET_SUBTREE(11)
-#endif
-#if RTREE_HEIGHT_MAX > 13
- RTREE_GET_SUBTREE(12)
-#endif
-#if RTREE_HEIGHT_MAX > 14
- RTREE_GET_SUBTREE(13)
-#endif
-#if RTREE_HEIGHT_MAX > 15
- RTREE_GET_SUBTREE(14)
-#endif
-#if RTREE_HEIGHT_MAX > 16
-# error Unsupported RTREE_HEIGHT_MAX
-#endif
- RTREE_GET_LEAF(RTREE_HEIGHT_MAX-1)
-#undef RTREE_GET_SUBTREE
-#undef RTREE_GET_LEAF
- default: not_reached();
- }
-#undef RTREE_GET_BIAS
- not_reached();
-}
-
-JEMALLOC_INLINE bool
-rtree_set(rtree_t *rtree, uintptr_t key, const extent_node_t *val)
-{
- uintptr_t subkey;
- unsigned i, start_level;
- rtree_node_elm_t *node, *child;
-
- start_level = rtree_start_level(rtree, key);
-
- node = rtree_subtree_read(rtree, start_level, false);
- if (node == NULL)
- return (true);
- for (i = start_level; /**/; i++, node = child) {
- subkey = rtree_subkey(rtree, key, i);
- if (i == rtree->height - 1) {
- /*
- * node is a leaf, so it contains values rather than
- * child pointers.
- */
- rtree_val_write(rtree, &node[subkey], val);
- return (false);
- }
- assert(i + 1 < rtree->height);
- child = rtree_child_read(rtree, &node[subkey], i, false);
- if (child == NULL)
- return (true);
- }
- not_reached();
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/size_classes.sh b/memory/jemalloc/src/include/jemalloc/internal/size_classes.sh
deleted file mode 100755
index f6fbce4ef..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/size_classes.sh
+++ /dev/null
@@ -1,318 +0,0 @@
-#!/bin/sh
-#
-# Usage: size_classes.sh <lg_qarr> <lg_tmin> <lg_parr> <lg_g>
-
-# The following limits are chosen such that they cover all supported platforms.
-
-# Pointer sizes.
-lg_zarr="2 3"
-
-# Quanta.
-lg_qarr=$1
-
-# The range of tiny size classes is [2^lg_tmin..2^(lg_q-1)].
-lg_tmin=$2
-
-# Maximum lookup size.
-lg_kmax=12
-
-# Page sizes.
-lg_parr=`echo $3 | tr ',' ' '`
-
-# Size class group size (number of size classes for each size doubling).
-lg_g=$4
-
-pow2() {
- e=$1
- pow2_result=1
- while [ ${e} -gt 0 ] ; do
- pow2_result=$((${pow2_result} + ${pow2_result}))
- e=$((${e} - 1))
- done
-}
-
-lg() {
- x=$1
- lg_result=0
- while [ ${x} -gt 1 ] ; do
- lg_result=$((${lg_result} + 1))
- x=$((${x} / 2))
- done
-}
-
-size_class() {
- index=$1
- lg_grp=$2
- lg_delta=$3
- ndelta=$4
- lg_p=$5
- lg_kmax=$6
-
- if [ ${lg_delta} -ge ${lg_p} ] ; then
- psz="yes"
- else
- pow2 ${lg_p}; p=${pow2_result}
- pow2 ${lg_grp}; grp=${pow2_result}
- pow2 ${lg_delta}; delta=${pow2_result}
- sz=$((${grp} + ${delta} * ${ndelta}))
- npgs=$((${sz} / ${p}))
- if [ ${sz} -eq $((${npgs} * ${p})) ] ; then
- psz="yes"
- else
- psz="no"
- fi
- fi
-
- lg ${ndelta}; lg_ndelta=${lg_result}; pow2 ${lg_ndelta}
- if [ ${pow2_result} -lt ${ndelta} ] ; then
- rem="yes"
- else
- rem="no"
- fi
-
- lg_size=${lg_grp}
- if [ $((${lg_delta} + ${lg_ndelta})) -eq ${lg_grp} ] ; then
- lg_size=$((${lg_grp} + 1))
- else
- lg_size=${lg_grp}
- rem="yes"
- fi
-
- if [ ${lg_size} -lt $((${lg_p} + ${lg_g})) ] ; then
- bin="yes"
- else
- bin="no"
- fi
- if [ ${lg_size} -lt ${lg_kmax} \
- -o ${lg_size} -eq ${lg_kmax} -a ${rem} = "no" ] ; then
- lg_delta_lookup=${lg_delta}
- else
- lg_delta_lookup="no"
- fi
- printf ' SC(%3d, %6d, %8d, %6d, %3s, %3s, %2s) \\\n' ${index} ${lg_grp} ${lg_delta} ${ndelta} ${psz} ${bin} ${lg_delta_lookup}
- # Defined upon return:
- # - psz ("yes" or "no")
- # - bin ("yes" or "no")
- # - lg_delta_lookup (${lg_delta} or "no")
-}
-
-sep_line() {
- echo " \\"
-}
-
-size_classes() {
- lg_z=$1
- lg_q=$2
- lg_t=$3
- lg_p=$4
- lg_g=$5
-
- pow2 $((${lg_z} + 3)); ptr_bits=${pow2_result}
- pow2 ${lg_g}; g=${pow2_result}
-
- echo "#define SIZE_CLASSES \\"
- echo " /* index, lg_grp, lg_delta, ndelta, psz, bin, lg_delta_lookup */ \\"
-
- ntbins=0
- nlbins=0
- lg_tiny_maxclass='"NA"'
- nbins=0
- npsizes=0
-
- # Tiny size classes.
- ndelta=0
- index=0
- lg_grp=${lg_t}
- lg_delta=${lg_grp}
- while [ ${lg_grp} -lt ${lg_q} ] ; do
- size_class ${index} ${lg_grp} ${lg_delta} ${ndelta} ${lg_p} ${lg_kmax}
- if [ ${lg_delta_lookup} != "no" ] ; then
- nlbins=$((${index} + 1))
- fi
- if [ ${psz} = "yes" ] ; then
- npsizes=$((${npsizes} + 1))
- fi
- if [ ${bin} != "no" ] ; then
- nbins=$((${index} + 1))
- fi
- ntbins=$((${ntbins} + 1))
- lg_tiny_maxclass=${lg_grp} # Final written value is correct.
- index=$((${index} + 1))
- lg_delta=${lg_grp}
- lg_grp=$((${lg_grp} + 1))
- done
-
- # First non-tiny group.
- if [ ${ntbins} -gt 0 ] ; then
- sep_line
- # The first size class has an unusual encoding, because the size has to be
- # split between grp and delta*ndelta.
- lg_grp=$((${lg_grp} - 1))
- ndelta=1
- size_class ${index} ${lg_grp} ${lg_delta} ${ndelta} ${lg_p} ${lg_kmax}
- index=$((${index} + 1))
- lg_grp=$((${lg_grp} + 1))
- lg_delta=$((${lg_delta} + 1))
- if [ ${psz} = "yes" ] ; then
- npsizes=$((${npsizes} + 1))
- fi
- fi
- while [ ${ndelta} -lt ${g} ] ; do
- size_class ${index} ${lg_grp} ${lg_delta} ${ndelta} ${lg_p} ${lg_kmax}
- index=$((${index} + 1))
- ndelta=$((${ndelta} + 1))
- if [ ${psz} = "yes" ] ; then
- npsizes=$((${npsizes} + 1))
- fi
- done
-
- # All remaining groups.
- lg_grp=$((${lg_grp} + ${lg_g}))
- while [ ${lg_grp} -lt $((${ptr_bits} - 1)) ] ; do
- sep_line
- ndelta=1
- if [ ${lg_grp} -eq $((${ptr_bits} - 2)) ] ; then
- ndelta_limit=$((${g} - 1))
- else
- ndelta_limit=${g}
- fi
- while [ ${ndelta} -le ${ndelta_limit} ] ; do
- size_class ${index} ${lg_grp} ${lg_delta} ${ndelta} ${lg_p} ${lg_kmax}
- if [ ${lg_delta_lookup} != "no" ] ; then
- nlbins=$((${index} + 1))
- # Final written value is correct:
- lookup_maxclass="((((size_t)1) << ${lg_grp}) + (((size_t)${ndelta}) << ${lg_delta}))"
- fi
- if [ ${psz} = "yes" ] ; then
- npsizes=$((${npsizes} + 1))
- fi
- if [ ${bin} != "no" ] ; then
- nbins=$((${index} + 1))
- # Final written value is correct:
- small_maxclass="((((size_t)1) << ${lg_grp}) + (((size_t)${ndelta}) << ${lg_delta}))"
- if [ ${lg_g} -gt 0 ] ; then
- lg_large_minclass=$((${lg_grp} + 1))
- else
- lg_large_minclass=$((${lg_grp} + 2))
- fi
- fi
- # Final written value is correct:
- huge_maxclass="((((size_t)1) << ${lg_grp}) + (((size_t)${ndelta}) << ${lg_delta}))"
- index=$((${index} + 1))
- ndelta=$((${ndelta} + 1))
- done
- lg_grp=$((${lg_grp} + 1))
- lg_delta=$((${lg_delta} + 1))
- done
- echo
- nsizes=${index}
-
- # Defined upon completion:
- # - ntbins
- # - nlbins
- # - nbins
- # - nsizes
- # - npsizes
- # - lg_tiny_maxclass
- # - lookup_maxclass
- # - small_maxclass
- # - lg_large_minclass
- # - huge_maxclass
-}
-
-cat <<EOF
-/* This file was automatically generated by size_classes.sh. */
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-/*
- * This header requires LG_SIZEOF_PTR, LG_TINY_MIN, LG_QUANTUM, and LG_PAGE to
- * be defined prior to inclusion, and it in turn defines:
- *
- * LG_SIZE_CLASS_GROUP: Lg of size class count for each size doubling.
- * SIZE_CLASSES: Complete table of SC(index, lg_grp, lg_delta, ndelta, psz,
- * bin, lg_delta_lookup) tuples.
- * index: Size class index.
- * lg_grp: Lg group base size (no deltas added).
- * lg_delta: Lg delta to previous size class.
- * ndelta: Delta multiplier. size == 1<<lg_grp + ndelta<<lg_delta
- * psz: 'yes' if a multiple of the page size, 'no' otherwise.
- * bin: 'yes' if a small bin size class, 'no' otherwise.
- * lg_delta_lookup: Same as lg_delta if a lookup table size class, 'no'
- * otherwise.
- * NTBINS: Number of tiny bins.
- * NLBINS: Number of bins supported by the lookup table.
- * NBINS: Number of small size class bins.
- * NSIZES: Number of size classes.
- * NPSIZES: Number of size classes that are a multiple of (1U << LG_PAGE).
- * LG_TINY_MAXCLASS: Lg of maximum tiny size class.
- * LOOKUP_MAXCLASS: Maximum size class included in lookup table.
- * SMALL_MAXCLASS: Maximum small size class.
- * LG_LARGE_MINCLASS: Lg of minimum large size class.
- * HUGE_MAXCLASS: Maximum (huge) size class.
- */
-
-#define LG_SIZE_CLASS_GROUP ${lg_g}
-
-EOF
-
-for lg_z in ${lg_zarr} ; do
- for lg_q in ${lg_qarr} ; do
- lg_t=${lg_tmin}
- while [ ${lg_t} -le ${lg_q} ] ; do
- # Iterate through page sizes and compute how many bins there are.
- for lg_p in ${lg_parr} ; do
- echo "#if (LG_SIZEOF_PTR == ${lg_z} && LG_TINY_MIN == ${lg_t} && LG_QUANTUM == ${lg_q} && LG_PAGE == ${lg_p})"
- size_classes ${lg_z} ${lg_q} ${lg_t} ${lg_p} ${lg_g}
- echo "#define SIZE_CLASSES_DEFINED"
- echo "#define NTBINS ${ntbins}"
- echo "#define NLBINS ${nlbins}"
- echo "#define NBINS ${nbins}"
- echo "#define NSIZES ${nsizes}"
- echo "#define NPSIZES ${npsizes}"
- echo "#define LG_TINY_MAXCLASS ${lg_tiny_maxclass}"
- echo "#define LOOKUP_MAXCLASS ${lookup_maxclass}"
- echo "#define SMALL_MAXCLASS ${small_maxclass}"
- echo "#define LG_LARGE_MINCLASS ${lg_large_minclass}"
- echo "#define HUGE_MAXCLASS ${huge_maxclass}"
- echo "#endif"
- echo
- done
- lg_t=$((${lg_t} + 1))
- done
- done
-done
-
-cat <<EOF
-#ifndef SIZE_CLASSES_DEFINED
-# error "No size class definitions match configuration"
-#endif
-#undef SIZE_CLASSES_DEFINED
-/*
- * The size2index_tab lookup table uses uint8_t to encode each bin index, so we
- * cannot support more than 256 small size classes. Further constrain NBINS to
- * 255 since all small size classes, plus a "not small" size class must be
- * stored in 8 bits of arena_chunk_map_bits_t's bits field.
- */
-#if (NBINS > 255)
-# error "Too many small size classes"
-#endif
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-EOF
diff --git a/memory/jemalloc/src/include/jemalloc/internal/smoothstep.h b/memory/jemalloc/src/include/jemalloc/internal/smoothstep.h
deleted file mode 100644
index c5333ccad..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/smoothstep.h
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * This file was generated by the following command:
- * sh smoothstep.sh smoother 200 24 3 15
- */
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-/*
- * This header defines a precomputed table based on the smoothstep family of
- * sigmoidal curves (https://en.wikipedia.org/wiki/Smoothstep) that grow from 0
- * to 1 in 0 <= x <= 1. The table is stored as integer fixed point values so
- * that floating point math can be avoided.
- *
- * 3 2
- * smoothstep(x) = -2x + 3x
- *
- * 5 4 3
- * smootherstep(x) = 6x - 15x + 10x
- *
- * 7 6 5 4
- * smootheststep(x) = -20x + 70x - 84x + 35x
- */
-
-#define SMOOTHSTEP_VARIANT "smoother"
-#define SMOOTHSTEP_NSTEPS 200
-#define SMOOTHSTEP_BFP 24
-#define SMOOTHSTEP \
- /* STEP(step, h, x, y) */ \
- STEP( 1, UINT64_C(0x0000000000000014), 0.005, 0.000001240643750) \
- STEP( 2, UINT64_C(0x00000000000000a5), 0.010, 0.000009850600000) \
- STEP( 3, UINT64_C(0x0000000000000229), 0.015, 0.000032995181250) \
- STEP( 4, UINT64_C(0x0000000000000516), 0.020, 0.000077619200000) \
- STEP( 5, UINT64_C(0x00000000000009dc), 0.025, 0.000150449218750) \
- STEP( 6, UINT64_C(0x00000000000010e8), 0.030, 0.000257995800000) \
- STEP( 7, UINT64_C(0x0000000000001aa4), 0.035, 0.000406555756250) \
- STEP( 8, UINT64_C(0x0000000000002777), 0.040, 0.000602214400000) \
- STEP( 9, UINT64_C(0x00000000000037c2), 0.045, 0.000850847793750) \
- STEP( 10, UINT64_C(0x0000000000004be6), 0.050, 0.001158125000000) \
- STEP( 11, UINT64_C(0x000000000000643c), 0.055, 0.001529510331250) \
- STEP( 12, UINT64_C(0x000000000000811f), 0.060, 0.001970265600000) \
- STEP( 13, UINT64_C(0x000000000000a2e2), 0.065, 0.002485452368750) \
- STEP( 14, UINT64_C(0x000000000000c9d8), 0.070, 0.003079934200000) \
- STEP( 15, UINT64_C(0x000000000000f64f), 0.075, 0.003758378906250) \
- STEP( 16, UINT64_C(0x0000000000012891), 0.080, 0.004525260800000) \
- STEP( 17, UINT64_C(0x00000000000160e7), 0.085, 0.005384862943750) \
- STEP( 18, UINT64_C(0x0000000000019f95), 0.090, 0.006341279400000) \
- STEP( 19, UINT64_C(0x000000000001e4dc), 0.095, 0.007398417481250) \
- STEP( 20, UINT64_C(0x00000000000230fc), 0.100, 0.008560000000000) \
- STEP( 21, UINT64_C(0x0000000000028430), 0.105, 0.009829567518750) \
- STEP( 22, UINT64_C(0x000000000002deb0), 0.110, 0.011210480600000) \
- STEP( 23, UINT64_C(0x00000000000340b1), 0.115, 0.012705922056250) \
- STEP( 24, UINT64_C(0x000000000003aa67), 0.120, 0.014318899200000) \
- STEP( 25, UINT64_C(0x0000000000041c00), 0.125, 0.016052246093750) \
- STEP( 26, UINT64_C(0x00000000000495a8), 0.130, 0.017908625800000) \
- STEP( 27, UINT64_C(0x000000000005178b), 0.135, 0.019890532631250) \
- STEP( 28, UINT64_C(0x000000000005a1cf), 0.140, 0.022000294400000) \
- STEP( 29, UINT64_C(0x0000000000063498), 0.145, 0.024240074668750) \
- STEP( 30, UINT64_C(0x000000000006d009), 0.150, 0.026611875000000) \
- STEP( 31, UINT64_C(0x000000000007743f), 0.155, 0.029117537206250) \
- STEP( 32, UINT64_C(0x0000000000082157), 0.160, 0.031758745600000) \
- STEP( 33, UINT64_C(0x000000000008d76b), 0.165, 0.034537029243750) \
- STEP( 34, UINT64_C(0x0000000000099691), 0.170, 0.037453764200000) \
- STEP( 35, UINT64_C(0x00000000000a5edf), 0.175, 0.040510175781250) \
- STEP( 36, UINT64_C(0x00000000000b3067), 0.180, 0.043707340800000) \
- STEP( 37, UINT64_C(0x00000000000c0b38), 0.185, 0.047046189818750) \
- STEP( 38, UINT64_C(0x00000000000cef5e), 0.190, 0.050527509400000) \
- STEP( 39, UINT64_C(0x00000000000ddce6), 0.195, 0.054151944356250) \
- STEP( 40, UINT64_C(0x00000000000ed3d8), 0.200, 0.057920000000000) \
- STEP( 41, UINT64_C(0x00000000000fd439), 0.205, 0.061832044393750) \
- STEP( 42, UINT64_C(0x000000000010de0e), 0.210, 0.065888310600000) \
- STEP( 43, UINT64_C(0x000000000011f158), 0.215, 0.070088898931250) \
- STEP( 44, UINT64_C(0x0000000000130e17), 0.220, 0.074433779200000) \
- STEP( 45, UINT64_C(0x0000000000143448), 0.225, 0.078922792968750) \
- STEP( 46, UINT64_C(0x00000000001563e7), 0.230, 0.083555655800000) \
- STEP( 47, UINT64_C(0x0000000000169cec), 0.235, 0.088331959506250) \
- STEP( 48, UINT64_C(0x000000000017df4f), 0.240, 0.093251174400000) \
- STEP( 49, UINT64_C(0x0000000000192b04), 0.245, 0.098312651543750) \
- STEP( 50, UINT64_C(0x00000000001a8000), 0.250, 0.103515625000000) \
- STEP( 51, UINT64_C(0x00000000001bde32), 0.255, 0.108859214081250) \
- STEP( 52, UINT64_C(0x00000000001d458b), 0.260, 0.114342425600000) \
- STEP( 53, UINT64_C(0x00000000001eb5f8), 0.265, 0.119964156118750) \
- STEP( 54, UINT64_C(0x0000000000202f65), 0.270, 0.125723194200000) \
- STEP( 55, UINT64_C(0x000000000021b1bb), 0.275, 0.131618222656250) \
- STEP( 56, UINT64_C(0x0000000000233ce3), 0.280, 0.137647820800000) \
- STEP( 57, UINT64_C(0x000000000024d0c3), 0.285, 0.143810466693750) \
- STEP( 58, UINT64_C(0x0000000000266d40), 0.290, 0.150104539400000) \
- STEP( 59, UINT64_C(0x000000000028123d), 0.295, 0.156528321231250) \
- STEP( 60, UINT64_C(0x000000000029bf9c), 0.300, 0.163080000000000) \
- STEP( 61, UINT64_C(0x00000000002b753d), 0.305, 0.169757671268750) \
- STEP( 62, UINT64_C(0x00000000002d32fe), 0.310, 0.176559340600000) \
- STEP( 63, UINT64_C(0x00000000002ef8bc), 0.315, 0.183482925806250) \
- STEP( 64, UINT64_C(0x000000000030c654), 0.320, 0.190526259200000) \
- STEP( 65, UINT64_C(0x0000000000329b9f), 0.325, 0.197687089843750) \
- STEP( 66, UINT64_C(0x0000000000347875), 0.330, 0.204963085800000) \
- STEP( 67, UINT64_C(0x0000000000365cb0), 0.335, 0.212351836381250) \
- STEP( 68, UINT64_C(0x0000000000384825), 0.340, 0.219850854400000) \
- STEP( 69, UINT64_C(0x00000000003a3aa8), 0.345, 0.227457578418750) \
- STEP( 70, UINT64_C(0x00000000003c340f), 0.350, 0.235169375000000) \
- STEP( 71, UINT64_C(0x00000000003e342b), 0.355, 0.242983540956250) \
- STEP( 72, UINT64_C(0x0000000000403ace), 0.360, 0.250897305600000) \
- STEP( 73, UINT64_C(0x00000000004247c8), 0.365, 0.258907832993750) \
- STEP( 74, UINT64_C(0x0000000000445ae9), 0.370, 0.267012224200000) \
- STEP( 75, UINT64_C(0x0000000000467400), 0.375, 0.275207519531250) \
- STEP( 76, UINT64_C(0x00000000004892d8), 0.380, 0.283490700800000) \
- STEP( 77, UINT64_C(0x00000000004ab740), 0.385, 0.291858693568750) \
- STEP( 78, UINT64_C(0x00000000004ce102), 0.390, 0.300308369400000) \
- STEP( 79, UINT64_C(0x00000000004f0fe9), 0.395, 0.308836548106250) \
- STEP( 80, UINT64_C(0x00000000005143bf), 0.400, 0.317440000000000) \
- STEP( 81, UINT64_C(0x0000000000537c4d), 0.405, 0.326115448143750) \
- STEP( 82, UINT64_C(0x000000000055b95b), 0.410, 0.334859570600000) \
- STEP( 83, UINT64_C(0x000000000057fab1), 0.415, 0.343669002681250) \
- STEP( 84, UINT64_C(0x00000000005a4015), 0.420, 0.352540339200000) \
- STEP( 85, UINT64_C(0x00000000005c894e), 0.425, 0.361470136718750) \
- STEP( 86, UINT64_C(0x00000000005ed622), 0.430, 0.370454915800000) \
- STEP( 87, UINT64_C(0x0000000000612655), 0.435, 0.379491163256250) \
- STEP( 88, UINT64_C(0x00000000006379ac), 0.440, 0.388575334400000) \
- STEP( 89, UINT64_C(0x000000000065cfeb), 0.445, 0.397703855293750) \
- STEP( 90, UINT64_C(0x00000000006828d6), 0.450, 0.406873125000000) \
- STEP( 91, UINT64_C(0x00000000006a842f), 0.455, 0.416079517831250) \
- STEP( 92, UINT64_C(0x00000000006ce1bb), 0.460, 0.425319385600000) \
- STEP( 93, UINT64_C(0x00000000006f413a), 0.465, 0.434589059868750) \
- STEP( 94, UINT64_C(0x000000000071a270), 0.470, 0.443884854200000) \
- STEP( 95, UINT64_C(0x000000000074051d), 0.475, 0.453203066406250) \
- STEP( 96, UINT64_C(0x0000000000766905), 0.480, 0.462539980800000) \
- STEP( 97, UINT64_C(0x000000000078cde7), 0.485, 0.471891870443750) \
- STEP( 98, UINT64_C(0x00000000007b3387), 0.490, 0.481254999400000) \
- STEP( 99, UINT64_C(0x00000000007d99a4), 0.495, 0.490625624981250) \
- STEP( 100, UINT64_C(0x0000000000800000), 0.500, 0.500000000000000) \
- STEP( 101, UINT64_C(0x000000000082665b), 0.505, 0.509374375018750) \
- STEP( 102, UINT64_C(0x000000000084cc78), 0.510, 0.518745000600000) \
- STEP( 103, UINT64_C(0x0000000000873218), 0.515, 0.528108129556250) \
- STEP( 104, UINT64_C(0x00000000008996fa), 0.520, 0.537460019200000) \
- STEP( 105, UINT64_C(0x00000000008bfae2), 0.525, 0.546796933593750) \
- STEP( 106, UINT64_C(0x00000000008e5d8f), 0.530, 0.556115145800000) \
- STEP( 107, UINT64_C(0x000000000090bec5), 0.535, 0.565410940131250) \
- STEP( 108, UINT64_C(0x0000000000931e44), 0.540, 0.574680614400000) \
- STEP( 109, UINT64_C(0x0000000000957bd0), 0.545, 0.583920482168750) \
- STEP( 110, UINT64_C(0x000000000097d729), 0.550, 0.593126875000000) \
- STEP( 111, UINT64_C(0x00000000009a3014), 0.555, 0.602296144706250) \
- STEP( 112, UINT64_C(0x00000000009c8653), 0.560, 0.611424665600000) \
- STEP( 113, UINT64_C(0x00000000009ed9aa), 0.565, 0.620508836743750) \
- STEP( 114, UINT64_C(0x0000000000a129dd), 0.570, 0.629545084200000) \
- STEP( 115, UINT64_C(0x0000000000a376b1), 0.575, 0.638529863281250) \
- STEP( 116, UINT64_C(0x0000000000a5bfea), 0.580, 0.647459660800000) \
- STEP( 117, UINT64_C(0x0000000000a8054e), 0.585, 0.656330997318750) \
- STEP( 118, UINT64_C(0x0000000000aa46a4), 0.590, 0.665140429400000) \
- STEP( 119, UINT64_C(0x0000000000ac83b2), 0.595, 0.673884551856250) \
- STEP( 120, UINT64_C(0x0000000000aebc40), 0.600, 0.682560000000000) \
- STEP( 121, UINT64_C(0x0000000000b0f016), 0.605, 0.691163451893750) \
- STEP( 122, UINT64_C(0x0000000000b31efd), 0.610, 0.699691630600000) \
- STEP( 123, UINT64_C(0x0000000000b548bf), 0.615, 0.708141306431250) \
- STEP( 124, UINT64_C(0x0000000000b76d27), 0.620, 0.716509299200000) \
- STEP( 125, UINT64_C(0x0000000000b98c00), 0.625, 0.724792480468750) \
- STEP( 126, UINT64_C(0x0000000000bba516), 0.630, 0.732987775800000) \
- STEP( 127, UINT64_C(0x0000000000bdb837), 0.635, 0.741092167006250) \
- STEP( 128, UINT64_C(0x0000000000bfc531), 0.640, 0.749102694400000) \
- STEP( 129, UINT64_C(0x0000000000c1cbd4), 0.645, 0.757016459043750) \
- STEP( 130, UINT64_C(0x0000000000c3cbf0), 0.650, 0.764830625000000) \
- STEP( 131, UINT64_C(0x0000000000c5c557), 0.655, 0.772542421581250) \
- STEP( 132, UINT64_C(0x0000000000c7b7da), 0.660, 0.780149145600000) \
- STEP( 133, UINT64_C(0x0000000000c9a34f), 0.665, 0.787648163618750) \
- STEP( 134, UINT64_C(0x0000000000cb878a), 0.670, 0.795036914200000) \
- STEP( 135, UINT64_C(0x0000000000cd6460), 0.675, 0.802312910156250) \
- STEP( 136, UINT64_C(0x0000000000cf39ab), 0.680, 0.809473740800000) \
- STEP( 137, UINT64_C(0x0000000000d10743), 0.685, 0.816517074193750) \
- STEP( 138, UINT64_C(0x0000000000d2cd01), 0.690, 0.823440659400000) \
- STEP( 139, UINT64_C(0x0000000000d48ac2), 0.695, 0.830242328731250) \
- STEP( 140, UINT64_C(0x0000000000d64063), 0.700, 0.836920000000000) \
- STEP( 141, UINT64_C(0x0000000000d7edc2), 0.705, 0.843471678768750) \
- STEP( 142, UINT64_C(0x0000000000d992bf), 0.710, 0.849895460600000) \
- STEP( 143, UINT64_C(0x0000000000db2f3c), 0.715, 0.856189533306250) \
- STEP( 144, UINT64_C(0x0000000000dcc31c), 0.720, 0.862352179200000) \
- STEP( 145, UINT64_C(0x0000000000de4e44), 0.725, 0.868381777343750) \
- STEP( 146, UINT64_C(0x0000000000dfd09a), 0.730, 0.874276805800000) \
- STEP( 147, UINT64_C(0x0000000000e14a07), 0.735, 0.880035843881250) \
- STEP( 148, UINT64_C(0x0000000000e2ba74), 0.740, 0.885657574400000) \
- STEP( 149, UINT64_C(0x0000000000e421cd), 0.745, 0.891140785918750) \
- STEP( 150, UINT64_C(0x0000000000e58000), 0.750, 0.896484375000000) \
- STEP( 151, UINT64_C(0x0000000000e6d4fb), 0.755, 0.901687348456250) \
- STEP( 152, UINT64_C(0x0000000000e820b0), 0.760, 0.906748825600000) \
- STEP( 153, UINT64_C(0x0000000000e96313), 0.765, 0.911668040493750) \
- STEP( 154, UINT64_C(0x0000000000ea9c18), 0.770, 0.916444344200000) \
- STEP( 155, UINT64_C(0x0000000000ebcbb7), 0.775, 0.921077207031250) \
- STEP( 156, UINT64_C(0x0000000000ecf1e8), 0.780, 0.925566220800000) \
- STEP( 157, UINT64_C(0x0000000000ee0ea7), 0.785, 0.929911101068750) \
- STEP( 158, UINT64_C(0x0000000000ef21f1), 0.790, 0.934111689400000) \
- STEP( 159, UINT64_C(0x0000000000f02bc6), 0.795, 0.938167955606250) \
- STEP( 160, UINT64_C(0x0000000000f12c27), 0.800, 0.942080000000000) \
- STEP( 161, UINT64_C(0x0000000000f22319), 0.805, 0.945848055643750) \
- STEP( 162, UINT64_C(0x0000000000f310a1), 0.810, 0.949472490600000) \
- STEP( 163, UINT64_C(0x0000000000f3f4c7), 0.815, 0.952953810181250) \
- STEP( 164, UINT64_C(0x0000000000f4cf98), 0.820, 0.956292659200000) \
- STEP( 165, UINT64_C(0x0000000000f5a120), 0.825, 0.959489824218750) \
- STEP( 166, UINT64_C(0x0000000000f6696e), 0.830, 0.962546235800000) \
- STEP( 167, UINT64_C(0x0000000000f72894), 0.835, 0.965462970756250) \
- STEP( 168, UINT64_C(0x0000000000f7dea8), 0.840, 0.968241254400000) \
- STEP( 169, UINT64_C(0x0000000000f88bc0), 0.845, 0.970882462793750) \
- STEP( 170, UINT64_C(0x0000000000f92ff6), 0.850, 0.973388125000000) \
- STEP( 171, UINT64_C(0x0000000000f9cb67), 0.855, 0.975759925331250) \
- STEP( 172, UINT64_C(0x0000000000fa5e30), 0.860, 0.977999705600000) \
- STEP( 173, UINT64_C(0x0000000000fae874), 0.865, 0.980109467368750) \
- STEP( 174, UINT64_C(0x0000000000fb6a57), 0.870, 0.982091374200000) \
- STEP( 175, UINT64_C(0x0000000000fbe400), 0.875, 0.983947753906250) \
- STEP( 176, UINT64_C(0x0000000000fc5598), 0.880, 0.985681100800000) \
- STEP( 177, UINT64_C(0x0000000000fcbf4e), 0.885, 0.987294077943750) \
- STEP( 178, UINT64_C(0x0000000000fd214f), 0.890, 0.988789519400000) \
- STEP( 179, UINT64_C(0x0000000000fd7bcf), 0.895, 0.990170432481250) \
- STEP( 180, UINT64_C(0x0000000000fdcf03), 0.900, 0.991440000000000) \
- STEP( 181, UINT64_C(0x0000000000fe1b23), 0.905, 0.992601582518750) \
- STEP( 182, UINT64_C(0x0000000000fe606a), 0.910, 0.993658720600000) \
- STEP( 183, UINT64_C(0x0000000000fe9f18), 0.915, 0.994615137056250) \
- STEP( 184, UINT64_C(0x0000000000fed76e), 0.920, 0.995474739200000) \
- STEP( 185, UINT64_C(0x0000000000ff09b0), 0.925, 0.996241621093750) \
- STEP( 186, UINT64_C(0x0000000000ff3627), 0.930, 0.996920065800000) \
- STEP( 187, UINT64_C(0x0000000000ff5d1d), 0.935, 0.997514547631250) \
- STEP( 188, UINT64_C(0x0000000000ff7ee0), 0.940, 0.998029734400000) \
- STEP( 189, UINT64_C(0x0000000000ff9bc3), 0.945, 0.998470489668750) \
- STEP( 190, UINT64_C(0x0000000000ffb419), 0.950, 0.998841875000000) \
- STEP( 191, UINT64_C(0x0000000000ffc83d), 0.955, 0.999149152206250) \
- STEP( 192, UINT64_C(0x0000000000ffd888), 0.960, 0.999397785600000) \
- STEP( 193, UINT64_C(0x0000000000ffe55b), 0.965, 0.999593444243750) \
- STEP( 194, UINT64_C(0x0000000000ffef17), 0.970, 0.999742004200000) \
- STEP( 195, UINT64_C(0x0000000000fff623), 0.975, 0.999849550781250) \
- STEP( 196, UINT64_C(0x0000000000fffae9), 0.980, 0.999922380800000) \
- STEP( 197, UINT64_C(0x0000000000fffdd6), 0.985, 0.999967004818750) \
- STEP( 198, UINT64_C(0x0000000000ffff5a), 0.990, 0.999990149400000) \
- STEP( 199, UINT64_C(0x0000000000ffffeb), 0.995, 0.999998759356250) \
- STEP( 200, UINT64_C(0x0000000001000000), 1.000, 1.000000000000000) \
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/smoothstep.sh b/memory/jemalloc/src/include/jemalloc/internal/smoothstep.sh
deleted file mode 100755
index 8124693f7..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/smoothstep.sh
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/bin/sh
-#
-# Generate a discrete lookup table for a sigmoid function in the smoothstep
-# family (https://en.wikipedia.org/wiki/Smoothstep), where the lookup table
-# entries correspond to x in [1/nsteps, 2/nsteps, ..., nsteps/nsteps]. Encode
-# the entries using a binary fixed point representation.
-#
-# Usage: smoothstep.sh <variant> <nsteps> <bfp> <xprec> <yprec>
-#
-# <variant> is in {smooth, smoother, smoothest}.
-# <nsteps> must be greater than zero.
-# <bfp> must be in [0..62]; reasonable values are roughly [10..30].
-# <xprec> is x decimal precision.
-# <yprec> is y decimal precision.
-
-#set -x
-
-cmd="sh smoothstep.sh $*"
-variant=$1
-nsteps=$2
-bfp=$3
-xprec=$4
-yprec=$5
-
-case "${variant}" in
- smooth)
- ;;
- smoother)
- ;;
- smoothest)
- ;;
- *)
- echo "Unsupported variant"
- exit 1
- ;;
-esac
-
-smooth() {
- step=$1
- y=`echo ${yprec} k ${step} ${nsteps} / sx _2 lx 3 ^ '*' 3 lx 2 ^ '*' + p | dc | tr -d '\\\\\n' | sed -e 's#^\.#0.#g'`
- h=`echo ${yprec} k 2 ${bfp} ^ ${y} '*' p | dc | tr -d '\\\\\n' | sed -e 's#^\.#0.#g' | tr '.' ' ' | awk '{print $1}' `
-}
-
-smoother() {
- step=$1
- y=`echo ${yprec} k ${step} ${nsteps} / sx 6 lx 5 ^ '*' _15 lx 4 ^ '*' + 10 lx 3 ^ '*' + p | dc | tr -d '\\\\\n' | sed -e 's#^\.#0.#g'`
- h=`echo ${yprec} k 2 ${bfp} ^ ${y} '*' p | dc | tr -d '\\\\\n' | sed -e 's#^\.#0.#g' | tr '.' ' ' | awk '{print $1}' `
-}
-
-smoothest() {
- step=$1
- y=`echo ${yprec} k ${step} ${nsteps} / sx _20 lx 7 ^ '*' 70 lx 6 ^ '*' + _84 lx 5 ^ '*' + 35 lx 4 ^ '*' + p | dc | tr -d '\\\\\n' | sed -e 's#^\.#0.#g'`
- h=`echo ${yprec} k 2 ${bfp} ^ ${y} '*' p | dc | tr -d '\\\\\n' | sed -e 's#^\.#0.#g' | tr '.' ' ' | awk '{print $1}' `
-}
-
-cat <<EOF
-/*
- * This file was generated by the following command:
- * $cmd
- */
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-/*
- * This header defines a precomputed table based on the smoothstep family of
- * sigmoidal curves (https://en.wikipedia.org/wiki/Smoothstep) that grow from 0
- * to 1 in 0 <= x <= 1. The table is stored as integer fixed point values so
- * that floating point math can be avoided.
- *
- * 3 2
- * smoothstep(x) = -2x + 3x
- *
- * 5 4 3
- * smootherstep(x) = 6x - 15x + 10x
- *
- * 7 6 5 4
- * smootheststep(x) = -20x + 70x - 84x + 35x
- */
-
-#define SMOOTHSTEP_VARIANT "${variant}"
-#define SMOOTHSTEP_NSTEPS ${nsteps}
-#define SMOOTHSTEP_BFP ${bfp}
-#define SMOOTHSTEP \\
- /* STEP(step, h, x, y) */ \\
-EOF
-
-s=1
-while [ $s -le $nsteps ] ; do
- $variant ${s}
- x=`echo ${xprec} k ${s} ${nsteps} / p | dc | tr -d '\\\\\n' | sed -e 's#^\.#0.#g'`
- printf ' STEP(%4d, UINT64_C(0x%016x), %s, %s) \\\n' ${s} ${h} ${x} ${y}
-
- s=$((s+1))
-done
-echo
-
-cat <<EOF
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-EOF
diff --git a/memory/jemalloc/src/include/jemalloc/internal/spin.h b/memory/jemalloc/src/include/jemalloc/internal/spin.h
deleted file mode 100644
index 9ef5ceb92..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/spin.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct spin_s spin_t;
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct spin_s {
- unsigned iteration;
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-void spin_init(spin_t *spin);
-void spin_adaptive(spin_t *spin);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_SPIN_C_))
-JEMALLOC_INLINE void
-spin_init(spin_t *spin)
-{
-
- spin->iteration = 0;
-}
-
-JEMALLOC_INLINE void
-spin_adaptive(spin_t *spin)
-{
- volatile uint64_t i;
-
- for (i = 0; i < (KQU(1) << spin->iteration); i++)
- CPU_SPINWAIT;
-
- if (spin->iteration < 63)
- spin->iteration++;
-}
-
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-
diff --git a/memory/jemalloc/src/include/jemalloc/internal/stats.h b/memory/jemalloc/src/include/jemalloc/internal/stats.h
deleted file mode 100644
index b62181783..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/stats.h
+++ /dev/null
@@ -1,201 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct tcache_bin_stats_s tcache_bin_stats_t;
-typedef struct malloc_bin_stats_s malloc_bin_stats_t;
-typedef struct malloc_large_stats_s malloc_large_stats_t;
-typedef struct malloc_huge_stats_s malloc_huge_stats_t;
-typedef struct arena_stats_s arena_stats_t;
-typedef struct chunk_stats_s chunk_stats_t;
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct tcache_bin_stats_s {
- /*
- * Number of allocation requests that corresponded to the size of this
- * bin.
- */
- uint64_t nrequests;
-};
-
-struct malloc_bin_stats_s {
- /*
- * Total number of allocation/deallocation requests served directly by
- * the bin. Note that tcache may allocate an object, then recycle it
- * many times, resulting many increments to nrequests, but only one
- * each to nmalloc and ndalloc.
- */
- uint64_t nmalloc;
- uint64_t ndalloc;
-
- /*
- * Number of allocation requests that correspond to the size of this
- * bin. This includes requests served by tcache, though tcache only
- * periodically merges into this counter.
- */
- uint64_t nrequests;
-
- /*
- * Current number of regions of this size class, including regions
- * currently cached by tcache.
- */
- size_t curregs;
-
- /* Number of tcache fills from this bin. */
- uint64_t nfills;
-
- /* Number of tcache flushes to this bin. */
- uint64_t nflushes;
-
- /* Total number of runs created for this bin's size class. */
- uint64_t nruns;
-
- /*
- * Total number of runs reused by extracting them from the runs tree for
- * this bin's size class.
- */
- uint64_t reruns;
-
- /* Current number of runs in this bin. */
- size_t curruns;
-};
-
-struct malloc_large_stats_s {
- /*
- * Total number of allocation/deallocation requests served directly by
- * the arena. Note that tcache may allocate an object, then recycle it
- * many times, resulting many increments to nrequests, but only one
- * each to nmalloc and ndalloc.
- */
- uint64_t nmalloc;
- uint64_t ndalloc;
-
- /*
- * Number of allocation requests that correspond to this size class.
- * This includes requests served by tcache, though tcache only
- * periodically merges into this counter.
- */
- uint64_t nrequests;
-
- /*
- * Current number of runs of this size class, including runs currently
- * cached by tcache.
- */
- size_t curruns;
-};
-
-struct malloc_huge_stats_s {
- /*
- * Total number of allocation/deallocation requests served directly by
- * the arena.
- */
- uint64_t nmalloc;
- uint64_t ndalloc;
-
- /* Current number of (multi-)chunk allocations of this size class. */
- size_t curhchunks;
-};
-
-struct arena_stats_s {
- /* Number of bytes currently mapped. */
- size_t mapped;
-
- /*
- * Number of bytes currently retained as a side effect of munmap() being
- * disabled/bypassed. Retained bytes are technically mapped (though
- * always decommitted or purged), but they are excluded from the mapped
- * statistic (above).
- */
- size_t retained;
-
- /*
- * Total number of purge sweeps, total number of madvise calls made,
- * and total pages purged in order to keep dirty unused memory under
- * control.
- */
- uint64_t npurge;
- uint64_t nmadvise;
- uint64_t purged;
-
- /*
- * Number of bytes currently mapped purely for metadata purposes, and
- * number of bytes currently allocated for internal metadata.
- */
- size_t metadata_mapped;
- size_t metadata_allocated; /* Protected via atomic_*_z(). */
-
- /* Per-size-category statistics. */
- size_t allocated_large;
- uint64_t nmalloc_large;
- uint64_t ndalloc_large;
- uint64_t nrequests_large;
-
- size_t allocated_huge;
- uint64_t nmalloc_huge;
- uint64_t ndalloc_huge;
-
- /* One element for each large size class. */
- malloc_large_stats_t *lstats;
-
- /* One element for each huge size class. */
- malloc_huge_stats_t *hstats;
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-extern bool opt_stats_print;
-
-extern size_t stats_cactive;
-
-void stats_print(void (*write)(void *, const char *), void *cbopaque,
- const char *opts);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-size_t stats_cactive_get(void);
-void stats_cactive_add(size_t size);
-void stats_cactive_sub(size_t size);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_STATS_C_))
-JEMALLOC_INLINE size_t
-stats_cactive_get(void)
-{
-
- return (atomic_read_z(&stats_cactive));
-}
-
-JEMALLOC_INLINE void
-stats_cactive_add(size_t size)
-{
- UNUSED size_t cactive;
-
- assert(size > 0);
- assert((size & chunksize_mask) == 0);
-
- cactive = atomic_add_z(&stats_cactive, size);
- assert(cactive - size < cactive);
-}
-
-JEMALLOC_INLINE void
-stats_cactive_sub(size_t size)
-{
- UNUSED size_t cactive;
-
- assert(size > 0);
- assert((size & chunksize_mask) == 0);
-
- cactive = atomic_sub_z(&stats_cactive, size);
- assert(cactive + size > cactive);
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/tcache.h b/memory/jemalloc/src/include/jemalloc/internal/tcache.h
deleted file mode 100644
index 01ba062de..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/tcache.h
+++ /dev/null
@@ -1,469 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct tcache_bin_info_s tcache_bin_info_t;
-typedef struct tcache_bin_s tcache_bin_t;
-typedef struct tcache_s tcache_t;
-typedef struct tcaches_s tcaches_t;
-
-/*
- * tcache pointers close to NULL are used to encode state information that is
- * used for two purposes: preventing thread caching on a per thread basis and
- * cleaning up during thread shutdown.
- */
-#define TCACHE_STATE_DISABLED ((tcache_t *)(uintptr_t)1)
-#define TCACHE_STATE_REINCARNATED ((tcache_t *)(uintptr_t)2)
-#define TCACHE_STATE_PURGATORY ((tcache_t *)(uintptr_t)3)
-#define TCACHE_STATE_MAX TCACHE_STATE_PURGATORY
-
-/*
- * Absolute minimum number of cache slots for each small bin.
- */
-#define TCACHE_NSLOTS_SMALL_MIN 20
-
-/*
- * Absolute maximum number of cache slots for each small bin in the thread
- * cache. This is an additional constraint beyond that imposed as: twice the
- * number of regions per run for this size class.
- *
- * This constant must be an even number.
- */
-#define TCACHE_NSLOTS_SMALL_MAX 200
-
-/* Number of cache slots for large size classes. */
-#define TCACHE_NSLOTS_LARGE 20
-
-/* (1U << opt_lg_tcache_max) is used to compute tcache_maxclass. */
-#define LG_TCACHE_MAXCLASS_DEFAULT 15
-
-/*
- * TCACHE_GC_SWEEP is the approximate number of allocation events between
- * full GC sweeps. Integer rounding may cause the actual number to be
- * slightly higher, since GC is performed incrementally.
- */
-#define TCACHE_GC_SWEEP 8192
-
-/* Number of tcache allocation/deallocation events between incremental GCs. */
-#define TCACHE_GC_INCR \
- ((TCACHE_GC_SWEEP / NBINS) + ((TCACHE_GC_SWEEP / NBINS == 0) ? 0 : 1))
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-typedef enum {
- tcache_enabled_false = 0, /* Enable cast to/from bool. */
- tcache_enabled_true = 1,
- tcache_enabled_default = 2
-} tcache_enabled_t;
-
-/*
- * Read-only information associated with each element of tcache_t's tbins array
- * is stored separately, mainly to reduce memory usage.
- */
-struct tcache_bin_info_s {
- unsigned ncached_max; /* Upper limit on ncached. */
-};
-
-struct tcache_bin_s {
- tcache_bin_stats_t tstats;
- int low_water; /* Min # cached since last GC. */
- unsigned lg_fill_div; /* Fill (ncached_max >> lg_fill_div). */
- unsigned ncached; /* # of cached objects. */
- /*
- * To make use of adjacent cacheline prefetch, the items in the avail
- * stack goes to higher address for newer allocations. avail points
- * just above the available space, which means that
- * avail[-ncached, ... -1] are available items and the lowest item will
- * be allocated first.
- */
- void **avail; /* Stack of available objects. */
-};
-
-struct tcache_s {
- ql_elm(tcache_t) link; /* Used for aggregating stats. */
- uint64_t prof_accumbytes;/* Cleared after arena_prof_accum(). */
- ticker_t gc_ticker; /* Drives incremental GC. */
- szind_t next_gc_bin; /* Next bin to GC. */
- tcache_bin_t tbins[1]; /* Dynamically sized. */
- /*
- * The pointer stacks associated with tbins follow as a contiguous
- * array. During tcache initialization, the avail pointer in each
- * element of tbins is initialized to point to the proper offset within
- * this array.
- */
-};
-
-/* Linkage for list of available (previously used) explicit tcache IDs. */
-struct tcaches_s {
- union {
- tcache_t *tcache;
- tcaches_t *next;
- };
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-extern bool opt_tcache;
-extern ssize_t opt_lg_tcache_max;
-
-extern tcache_bin_info_t *tcache_bin_info;
-
-/*
- * Number of tcache bins. There are NBINS small-object bins, plus 0 or more
- * large-object bins.
- */
-extern unsigned nhbins;
-
-/* Maximum cached size class. */
-extern size_t tcache_maxclass;
-
-/*
- * Explicit tcaches, managed via the tcache.{create,flush,destroy} mallctls and
- * usable via the MALLOCX_TCACHE() flag. The automatic per thread tcaches are
- * completely disjoint from this data structure. tcaches starts off as a sparse
- * array, so it has no physical memory footprint until individual pages are
- * touched. This allows the entire array to be allocated the first time an
- * explicit tcache is created without a disproportionate impact on memory usage.
- */
-extern tcaches_t *tcaches;
-
-size_t tcache_salloc(tsdn_t *tsdn, const void *ptr);
-void tcache_event_hard(tsd_t *tsd, tcache_t *tcache);
-void *tcache_alloc_small_hard(tsdn_t *tsdn, arena_t *arena, tcache_t *tcache,
- tcache_bin_t *tbin, szind_t binind, bool *tcache_success);
-void tcache_bin_flush_small(tsd_t *tsd, tcache_t *tcache, tcache_bin_t *tbin,
- szind_t binind, unsigned rem);
-void tcache_bin_flush_large(tsd_t *tsd, tcache_bin_t *tbin, szind_t binind,
- unsigned rem, tcache_t *tcache);
-void tcache_arena_reassociate(tsdn_t *tsdn, tcache_t *tcache,
- arena_t *oldarena, arena_t *newarena);
-tcache_t *tcache_get_hard(tsd_t *tsd);
-tcache_t *tcache_create(tsdn_t *tsdn, arena_t *arena);
-void tcache_cleanup(tsd_t *tsd);
-void tcache_enabled_cleanup(tsd_t *tsd);
-void tcache_stats_merge(tsdn_t *tsdn, tcache_t *tcache, arena_t *arena);
-bool tcaches_create(tsd_t *tsd, unsigned *r_ind);
-void tcaches_flush(tsd_t *tsd, unsigned ind);
-void tcaches_destroy(tsd_t *tsd, unsigned ind);
-bool tcache_boot(tsdn_t *tsdn);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-void tcache_event(tsd_t *tsd, tcache_t *tcache);
-void tcache_flush(void);
-bool tcache_enabled_get(void);
-tcache_t *tcache_get(tsd_t *tsd, bool create);
-void tcache_enabled_set(bool enabled);
-void *tcache_alloc_easy(tcache_bin_t *tbin, bool *tcache_success);
-void *tcache_alloc_small(tsd_t *tsd, arena_t *arena, tcache_t *tcache,
- size_t size, szind_t ind, bool zero, bool slow_path);
-void *tcache_alloc_large(tsd_t *tsd, arena_t *arena, tcache_t *tcache,
- size_t size, szind_t ind, bool zero, bool slow_path);
-void tcache_dalloc_small(tsd_t *tsd, tcache_t *tcache, void *ptr,
- szind_t binind, bool slow_path);
-void tcache_dalloc_large(tsd_t *tsd, tcache_t *tcache, void *ptr,
- size_t size, bool slow_path);
-tcache_t *tcaches_get(tsd_t *tsd, unsigned ind);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_TCACHE_C_))
-JEMALLOC_INLINE void
-tcache_flush(void)
-{
- tsd_t *tsd;
-
- cassert(config_tcache);
-
- tsd = tsd_fetch();
- tcache_cleanup(tsd);
-}
-
-JEMALLOC_INLINE bool
-tcache_enabled_get(void)
-{
- tsd_t *tsd;
- tcache_enabled_t tcache_enabled;
-
- cassert(config_tcache);
-
- tsd = tsd_fetch();
- tcache_enabled = tsd_tcache_enabled_get(tsd);
- if (tcache_enabled == tcache_enabled_default) {
- tcache_enabled = (tcache_enabled_t)opt_tcache;
- tsd_tcache_enabled_set(tsd, tcache_enabled);
- }
-
- return ((bool)tcache_enabled);
-}
-
-JEMALLOC_INLINE void
-tcache_enabled_set(bool enabled)
-{
- tsd_t *tsd;
- tcache_enabled_t tcache_enabled;
-
- cassert(config_tcache);
-
- tsd = tsd_fetch();
-
- tcache_enabled = (tcache_enabled_t)enabled;
- tsd_tcache_enabled_set(tsd, tcache_enabled);
-
- if (!enabled)
- tcache_cleanup(tsd);
-}
-
-JEMALLOC_ALWAYS_INLINE tcache_t *
-tcache_get(tsd_t *tsd, bool create)
-{
- tcache_t *tcache;
-
- if (!config_tcache)
- return (NULL);
-
- tcache = tsd_tcache_get(tsd);
- if (!create)
- return (tcache);
- if (unlikely(tcache == NULL) && tsd_nominal(tsd)) {
- tcache = tcache_get_hard(tsd);
- tsd_tcache_set(tsd, tcache);
- }
-
- return (tcache);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-tcache_event(tsd_t *tsd, tcache_t *tcache)
-{
-
- if (TCACHE_GC_INCR == 0)
- return;
-
- if (unlikely(ticker_tick(&tcache->gc_ticker)))
- tcache_event_hard(tsd, tcache);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-tcache_alloc_easy(tcache_bin_t *tbin, bool *tcache_success)
-{
- void *ret;
-
- if (unlikely(tbin->ncached == 0)) {
- tbin->low_water = -1;
- *tcache_success = false;
- return (NULL);
- }
- /*
- * tcache_success (instead of ret) should be checked upon the return of
- * this function. We avoid checking (ret == NULL) because there is
- * never a null stored on the avail stack (which is unknown to the
- * compiler), and eagerly checking ret would cause pipeline stall
- * (waiting for the cacheline).
- */
- *tcache_success = true;
- ret = *(tbin->avail - tbin->ncached);
- tbin->ncached--;
-
- if (unlikely((int)tbin->ncached < tbin->low_water))
- tbin->low_water = tbin->ncached;
-
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-tcache_alloc_small(tsd_t *tsd, arena_t *arena, tcache_t *tcache, size_t size,
- szind_t binind, bool zero, bool slow_path)
-{
- void *ret;
- tcache_bin_t *tbin;
- bool tcache_success;
- size_t usize JEMALLOC_CC_SILENCE_INIT(0);
-
- assert(binind < NBINS);
- tbin = &tcache->tbins[binind];
- ret = tcache_alloc_easy(tbin, &tcache_success);
- assert(tcache_success == (ret != NULL));
- if (unlikely(!tcache_success)) {
- bool tcache_hard_success;
- arena = arena_choose(tsd, arena);
- if (unlikely(arena == NULL))
- return (NULL);
-
- ret = tcache_alloc_small_hard(tsd_tsdn(tsd), arena, tcache,
- tbin, binind, &tcache_hard_success);
- if (tcache_hard_success == false)
- return (NULL);
- }
-
- assert(ret);
- /*
- * Only compute usize if required. The checks in the following if
- * statement are all static.
- */
- if (config_prof || (slow_path && config_fill) || unlikely(zero)) {
- usize = index2size(binind);
- assert(tcache_salloc(tsd_tsdn(tsd), ret) == usize);
- }
-
- if (likely(!zero)) {
- if (slow_path && config_fill) {
- if (unlikely(opt_junk_alloc)) {
- arena_alloc_junk_small(ret,
- &arena_bin_info[binind], false);
- } else if (unlikely(opt_zero))
- memset(ret, 0, usize);
- }
- } else {
- if (slow_path && config_fill && unlikely(opt_junk_alloc)) {
- arena_alloc_junk_small(ret, &arena_bin_info[binind],
- true);
- }
- memset(ret, 0, usize);
- }
-
- if (config_stats)
- tbin->tstats.nrequests++;
- if (config_prof)
- tcache->prof_accumbytes += usize;
- tcache_event(tsd, tcache);
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE void *
-tcache_alloc_large(tsd_t *tsd, arena_t *arena, tcache_t *tcache, size_t size,
- szind_t binind, bool zero, bool slow_path)
-{
- void *ret;
- tcache_bin_t *tbin;
- bool tcache_success;
-
- assert(binind < nhbins);
- tbin = &tcache->tbins[binind];
- ret = tcache_alloc_easy(tbin, &tcache_success);
- assert(tcache_success == (ret != NULL));
- if (unlikely(!tcache_success)) {
- /*
- * Only allocate one large object at a time, because it's quite
- * expensive to create one and not use it.
- */
- arena = arena_choose(tsd, arena);
- if (unlikely(arena == NULL))
- return (NULL);
-
- ret = arena_malloc_large(tsd_tsdn(tsd), arena, binind, zero);
- if (ret == NULL)
- return (NULL);
- } else {
- size_t usize JEMALLOC_CC_SILENCE_INIT(0);
-
- /* Only compute usize on demand */
- if (config_prof || (slow_path && config_fill) ||
- unlikely(zero)) {
- usize = index2size(binind);
- assert(usize <= tcache_maxclass);
- }
-
- if (config_prof && usize == LARGE_MINCLASS) {
- arena_chunk_t *chunk =
- (arena_chunk_t *)CHUNK_ADDR2BASE(ret);
- size_t pageind = (((uintptr_t)ret - (uintptr_t)chunk) >>
- LG_PAGE);
- arena_mapbits_large_binind_set(chunk, pageind,
- BININD_INVALID);
- }
- if (likely(!zero)) {
- if (slow_path && config_fill) {
- if (unlikely(opt_junk_alloc)) {
- memset(ret, JEMALLOC_ALLOC_JUNK,
- usize);
- } else if (unlikely(opt_zero))
- memset(ret, 0, usize);
- }
- } else
- memset(ret, 0, usize);
-
- if (config_stats)
- tbin->tstats.nrequests++;
- if (config_prof)
- tcache->prof_accumbytes += usize;
- }
-
- tcache_event(tsd, tcache);
- return (ret);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-tcache_dalloc_small(tsd_t *tsd, tcache_t *tcache, void *ptr, szind_t binind,
- bool slow_path)
-{
- tcache_bin_t *tbin;
- tcache_bin_info_t *tbin_info;
-
- assert(tcache_salloc(tsd_tsdn(tsd), ptr) <= SMALL_MAXCLASS);
-
- if (slow_path && config_fill && unlikely(opt_junk_free))
- arena_dalloc_junk_small(ptr, &arena_bin_info[binind]);
-
- tbin = &tcache->tbins[binind];
- tbin_info = &tcache_bin_info[binind];
- if (unlikely(tbin->ncached == tbin_info->ncached_max)) {
- tcache_bin_flush_small(tsd, tcache, tbin, binind,
- (tbin_info->ncached_max >> 1));
- }
- assert(tbin->ncached < tbin_info->ncached_max);
- tbin->ncached++;
- *(tbin->avail - tbin->ncached) = ptr;
-
- tcache_event(tsd, tcache);
-}
-
-JEMALLOC_ALWAYS_INLINE void
-tcache_dalloc_large(tsd_t *tsd, tcache_t *tcache, void *ptr, size_t size,
- bool slow_path)
-{
- szind_t binind;
- tcache_bin_t *tbin;
- tcache_bin_info_t *tbin_info;
-
- assert((size & PAGE_MASK) == 0);
- assert(tcache_salloc(tsd_tsdn(tsd), ptr) > SMALL_MAXCLASS);
- assert(tcache_salloc(tsd_tsdn(tsd), ptr) <= tcache_maxclass);
-
- binind = size2index(size);
-
- if (slow_path && config_fill && unlikely(opt_junk_free))
- arena_dalloc_junk_large(ptr, size);
-
- tbin = &tcache->tbins[binind];
- tbin_info = &tcache_bin_info[binind];
- if (unlikely(tbin->ncached == tbin_info->ncached_max)) {
- tcache_bin_flush_large(tsd, tbin, binind,
- (tbin_info->ncached_max >> 1), tcache);
- }
- assert(tbin->ncached < tbin_info->ncached_max);
- tbin->ncached++;
- *(tbin->avail - tbin->ncached) = ptr;
-
- tcache_event(tsd, tcache);
-}
-
-JEMALLOC_ALWAYS_INLINE tcache_t *
-tcaches_get(tsd_t *tsd, unsigned ind)
-{
- tcaches_t *elm = &tcaches[ind];
- if (unlikely(elm->tcache == NULL)) {
- elm->tcache = tcache_create(tsd_tsdn(tsd), arena_choose(tsd,
- NULL));
- }
- return (elm->tcache);
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/ticker.h b/memory/jemalloc/src/include/jemalloc/internal/ticker.h
deleted file mode 100644
index 4696e56d2..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/ticker.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct ticker_s ticker_t;
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct ticker_s {
- int32_t tick;
- int32_t nticks;
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-void ticker_init(ticker_t *ticker, int32_t nticks);
-void ticker_copy(ticker_t *ticker, const ticker_t *other);
-int32_t ticker_read(const ticker_t *ticker);
-bool ticker_ticks(ticker_t *ticker, int32_t nticks);
-bool ticker_tick(ticker_t *ticker);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_TICKER_C_))
-JEMALLOC_INLINE void
-ticker_init(ticker_t *ticker, int32_t nticks)
-{
-
- ticker->tick = nticks;
- ticker->nticks = nticks;
-}
-
-JEMALLOC_INLINE void
-ticker_copy(ticker_t *ticker, const ticker_t *other)
-{
-
- *ticker = *other;
-}
-
-JEMALLOC_INLINE int32_t
-ticker_read(const ticker_t *ticker)
-{
-
- return (ticker->tick);
-}
-
-JEMALLOC_INLINE bool
-ticker_ticks(ticker_t *ticker, int32_t nticks)
-{
-
- if (unlikely(ticker->tick < nticks)) {
- ticker->tick = ticker->nticks;
- return (true);
- }
- ticker->tick -= nticks;
- return(false);
-}
-
-JEMALLOC_INLINE bool
-ticker_tick(ticker_t *ticker)
-{
-
- return (ticker_ticks(ticker, 1));
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/tsd.h b/memory/jemalloc/src/include/jemalloc/internal/tsd.h
deleted file mode 100644
index 9055acafd..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/tsd.h
+++ /dev/null
@@ -1,787 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-/* Maximum number of malloc_tsd users with cleanup functions. */
-#define MALLOC_TSD_CLEANUPS_MAX 2
-
-typedef bool (*malloc_tsd_cleanup_t)(void);
-
-#if (!defined(JEMALLOC_MALLOC_THREAD_CLEANUP) && !defined(JEMALLOC_TLS) && \
- !defined(_WIN32))
-typedef struct tsd_init_block_s tsd_init_block_t;
-typedef struct tsd_init_head_s tsd_init_head_t;
-#endif
-
-typedef struct tsd_s tsd_t;
-typedef struct tsdn_s tsdn_t;
-
-#define TSDN_NULL ((tsdn_t *)0)
-
-typedef enum {
- tsd_state_uninitialized,
- tsd_state_nominal,
- tsd_state_purgatory,
- tsd_state_reincarnated
-} tsd_state_t;
-
-/*
- * TLS/TSD-agnostic macro-based implementation of thread-specific data. There
- * are five macros that support (at least) three use cases: file-private,
- * library-private, and library-private inlined. Following is an example
- * library-private tsd variable:
- *
- * In example.h:
- * typedef struct {
- * int x;
- * int y;
- * } example_t;
- * #define EX_INITIALIZER JEMALLOC_CONCAT({0, 0})
- * malloc_tsd_types(example_, example_t)
- * malloc_tsd_protos(, example_, example_t)
- * malloc_tsd_externs(example_, example_t)
- * In example.c:
- * malloc_tsd_data(, example_, example_t, EX_INITIALIZER)
- * malloc_tsd_funcs(, example_, example_t, EX_INITIALIZER,
- * example_tsd_cleanup)
- *
- * The result is a set of generated functions, e.g.:
- *
- * bool example_tsd_boot(void) {...}
- * bool example_tsd_booted_get(void) {...}
- * example_t *example_tsd_get(bool init) {...}
- * void example_tsd_set(example_t *val) {...}
- *
- * Note that all of the functions deal in terms of (a_type *) rather than
- * (a_type) so that it is possible to support non-pointer types (unlike
- * pthreads TSD). example_tsd_cleanup() is passed an (a_type *) pointer that is
- * cast to (void *). This means that the cleanup function needs to cast the
- * function argument to (a_type *), then dereference the resulting pointer to
- * access fields, e.g.
- *
- * void
- * example_tsd_cleanup(void *arg)
- * {
- * example_t *example = (example_t *)arg;
- *
- * example->x = 42;
- * [...]
- * if ([want the cleanup function to be called again])
- * example_tsd_set(example);
- * }
- *
- * If example_tsd_set() is called within example_tsd_cleanup(), it will be
- * called again. This is similar to how pthreads TSD destruction works, except
- * that pthreads only calls the cleanup function again if the value was set to
- * non-NULL.
- */
-
-/* malloc_tsd_types(). */
-#ifdef JEMALLOC_MALLOC_THREAD_CLEANUP
-#define malloc_tsd_types(a_name, a_type)
-#elif (defined(JEMALLOC_TLS))
-#define malloc_tsd_types(a_name, a_type)
-#elif (defined(_WIN32))
-#define malloc_tsd_types(a_name, a_type) \
-typedef struct { \
- bool initialized; \
- a_type val; \
-} a_name##tsd_wrapper_t;
-#else
-#define malloc_tsd_types(a_name, a_type) \
-typedef struct { \
- bool initialized; \
- a_type val; \
-} a_name##tsd_wrapper_t;
-#endif
-
-/* malloc_tsd_protos(). */
-#define malloc_tsd_protos(a_attr, a_name, a_type) \
-a_attr bool \
-a_name##tsd_boot0(void); \
-a_attr void \
-a_name##tsd_boot1(void); \
-a_attr bool \
-a_name##tsd_boot(void); \
-a_attr bool \
-a_name##tsd_booted_get(void); \
-a_attr a_type * \
-a_name##tsd_get(bool init); \
-a_attr void \
-a_name##tsd_set(a_type *val);
-
-/* malloc_tsd_externs(). */
-#ifdef JEMALLOC_MALLOC_THREAD_CLEANUP
-#define malloc_tsd_externs(a_name, a_type) \
-extern __thread a_type a_name##tsd_tls; \
-extern __thread bool a_name##tsd_initialized; \
-extern bool a_name##tsd_booted;
-#elif (defined(JEMALLOC_TLS))
-#define malloc_tsd_externs(a_name, a_type) \
-extern __thread a_type a_name##tsd_tls; \
-extern pthread_key_t a_name##tsd_tsd; \
-extern bool a_name##tsd_booted;
-#elif (defined(_WIN32))
-#define malloc_tsd_externs(a_name, a_type) \
-extern DWORD a_name##tsd_tsd; \
-extern a_name##tsd_wrapper_t a_name##tsd_boot_wrapper; \
-extern bool a_name##tsd_booted;
-#else
-#define malloc_tsd_externs(a_name, a_type) \
-extern pthread_key_t a_name##tsd_tsd; \
-extern tsd_init_head_t a_name##tsd_init_head; \
-extern a_name##tsd_wrapper_t a_name##tsd_boot_wrapper; \
-extern bool a_name##tsd_booted;
-#endif
-
-/* malloc_tsd_data(). */
-#ifdef JEMALLOC_MALLOC_THREAD_CLEANUP
-#define malloc_tsd_data(a_attr, a_name, a_type, a_initializer) \
-a_attr __thread a_type JEMALLOC_TLS_MODEL \
- a_name##tsd_tls = a_initializer; \
-a_attr __thread bool JEMALLOC_TLS_MODEL \
- a_name##tsd_initialized = false; \
-a_attr bool a_name##tsd_booted = false;
-#elif (defined(JEMALLOC_TLS))
-#define malloc_tsd_data(a_attr, a_name, a_type, a_initializer) \
-a_attr __thread a_type JEMALLOC_TLS_MODEL \
- a_name##tsd_tls = a_initializer; \
-a_attr pthread_key_t a_name##tsd_tsd; \
-a_attr bool a_name##tsd_booted = false;
-#elif (defined(_WIN32))
-#define malloc_tsd_data(a_attr, a_name, a_type, a_initializer) \
-a_attr DWORD a_name##tsd_tsd; \
-a_attr a_name##tsd_wrapper_t a_name##tsd_boot_wrapper = { \
- false, \
- a_initializer \
-}; \
-a_attr bool a_name##tsd_booted = false;
-#else
-#define malloc_tsd_data(a_attr, a_name, a_type, a_initializer) \
-a_attr pthread_key_t a_name##tsd_tsd; \
-a_attr tsd_init_head_t a_name##tsd_init_head = { \
- ql_head_initializer(blocks), \
- MALLOC_MUTEX_INITIALIZER \
-}; \
-a_attr a_name##tsd_wrapper_t a_name##tsd_boot_wrapper = { \
- false, \
- a_initializer \
-}; \
-a_attr bool a_name##tsd_booted = false;
-#endif
-
-/* malloc_tsd_funcs(). */
-#ifdef JEMALLOC_MALLOC_THREAD_CLEANUP
-#define malloc_tsd_funcs(a_attr, a_name, a_type, a_initializer, \
- a_cleanup) \
-/* Initialization/cleanup. */ \
-a_attr bool \
-a_name##tsd_cleanup_wrapper(void) \
-{ \
- \
- if (a_name##tsd_initialized) { \
- a_name##tsd_initialized = false; \
- a_cleanup(&a_name##tsd_tls); \
- } \
- return (a_name##tsd_initialized); \
-} \
-a_attr bool \
-a_name##tsd_boot0(void) \
-{ \
- \
- if (a_cleanup != malloc_tsd_no_cleanup) { \
- malloc_tsd_cleanup_register( \
- &a_name##tsd_cleanup_wrapper); \
- } \
- a_name##tsd_booted = true; \
- return (false); \
-} \
-a_attr void \
-a_name##tsd_boot1(void) \
-{ \
- \
- /* Do nothing. */ \
-} \
-a_attr bool \
-a_name##tsd_boot(void) \
-{ \
- \
- return (a_name##tsd_boot0()); \
-} \
-a_attr bool \
-a_name##tsd_booted_get(void) \
-{ \
- \
- return (a_name##tsd_booted); \
-} \
-a_attr bool \
-a_name##tsd_get_allocates(void) \
-{ \
- \
- return (false); \
-} \
-/* Get/set. */ \
-a_attr a_type * \
-a_name##tsd_get(bool init) \
-{ \
- \
- assert(a_name##tsd_booted); \
- return (&a_name##tsd_tls); \
-} \
-a_attr void \
-a_name##tsd_set(a_type *val) \
-{ \
- \
- assert(a_name##tsd_booted); \
- a_name##tsd_tls = (*val); \
- if (a_cleanup != malloc_tsd_no_cleanup) \
- a_name##tsd_initialized = true; \
-}
-#elif (defined(JEMALLOC_TLS))
-#define malloc_tsd_funcs(a_attr, a_name, a_type, a_initializer, \
- a_cleanup) \
-/* Initialization/cleanup. */ \
-a_attr bool \
-a_name##tsd_boot0(void) \
-{ \
- \
- if (a_cleanup != malloc_tsd_no_cleanup) { \
- if (pthread_key_create(&a_name##tsd_tsd, a_cleanup) != \
- 0) \
- return (true); \
- } \
- a_name##tsd_booted = true; \
- return (false); \
-} \
-a_attr void \
-a_name##tsd_boot1(void) \
-{ \
- \
- /* Do nothing. */ \
-} \
-a_attr bool \
-a_name##tsd_boot(void) \
-{ \
- \
- return (a_name##tsd_boot0()); \
-} \
-a_attr bool \
-a_name##tsd_booted_get(void) \
-{ \
- \
- return (a_name##tsd_booted); \
-} \
-a_attr bool \
-a_name##tsd_get_allocates(void) \
-{ \
- \
- return (false); \
-} \
-/* Get/set. */ \
-a_attr a_type * \
-a_name##tsd_get(bool init) \
-{ \
- \
- assert(a_name##tsd_booted); \
- return (&a_name##tsd_tls); \
-} \
-a_attr void \
-a_name##tsd_set(a_type *val) \
-{ \
- \
- assert(a_name##tsd_booted); \
- a_name##tsd_tls = (*val); \
- if (a_cleanup != malloc_tsd_no_cleanup) { \
- if (pthread_setspecific(a_name##tsd_tsd, \
- (void *)(&a_name##tsd_tls))) { \
- malloc_write("<jemalloc>: Error" \
- " setting TSD for "#a_name"\n"); \
- if (opt_abort) \
- abort(); \
- } \
- } \
-}
-#elif (defined(_WIN32))
-#define malloc_tsd_funcs(a_attr, a_name, a_type, a_initializer, \
- a_cleanup) \
-/* Initialization/cleanup. */ \
-a_attr bool \
-a_name##tsd_cleanup_wrapper(void) \
-{ \
- DWORD error = GetLastError(); \
- a_name##tsd_wrapper_t *wrapper = (a_name##tsd_wrapper_t *) \
- TlsGetValue(a_name##tsd_tsd); \
- SetLastError(error); \
- \
- if (wrapper == NULL) \
- return (false); \
- if (a_cleanup != malloc_tsd_no_cleanup && \
- wrapper->initialized) { \
- wrapper->initialized = false; \
- a_cleanup(&wrapper->val); \
- if (wrapper->initialized) { \
- /* Trigger another cleanup round. */ \
- return (true); \
- } \
- } \
- malloc_tsd_dalloc(wrapper); \
- return (false); \
-} \
-a_attr void \
-a_name##tsd_wrapper_set(a_name##tsd_wrapper_t *wrapper) \
-{ \
- \
- if (!TlsSetValue(a_name##tsd_tsd, (void *)wrapper)) { \
- malloc_write("<jemalloc>: Error setting" \
- " TSD for "#a_name"\n"); \
- abort(); \
- } \
-} \
-a_attr a_name##tsd_wrapper_t * \
-a_name##tsd_wrapper_get(bool init) \
-{ \
- DWORD error = GetLastError(); \
- a_name##tsd_wrapper_t *wrapper = (a_name##tsd_wrapper_t *) \
- TlsGetValue(a_name##tsd_tsd); \
- SetLastError(error); \
- \
- if (init && unlikely(wrapper == NULL)) { \
- wrapper = (a_name##tsd_wrapper_t *) \
- malloc_tsd_malloc(sizeof(a_name##tsd_wrapper_t)); \
- if (wrapper == NULL) { \
- malloc_write("<jemalloc>: Error allocating" \
- " TSD for "#a_name"\n"); \
- abort(); \
- } else { \
- wrapper->initialized = false; \
- wrapper->val = a_initializer; \
- } \
- a_name##tsd_wrapper_set(wrapper); \
- } \
- return (wrapper); \
-} \
-a_attr bool \
-a_name##tsd_boot0(void) \
-{ \
- \
- a_name##tsd_tsd = TlsAlloc(); \
- if (a_name##tsd_tsd == TLS_OUT_OF_INDEXES) \
- return (true); \
- if (a_cleanup != malloc_tsd_no_cleanup) { \
- malloc_tsd_cleanup_register( \
- &a_name##tsd_cleanup_wrapper); \
- } \
- a_name##tsd_wrapper_set(&a_name##tsd_boot_wrapper); \
- a_name##tsd_booted = true; \
- return (false); \
-} \
-a_attr void \
-a_name##tsd_boot1(void) \
-{ \
- a_name##tsd_wrapper_t *wrapper; \
- wrapper = (a_name##tsd_wrapper_t *) \
- malloc_tsd_malloc(sizeof(a_name##tsd_wrapper_t)); \
- if (wrapper == NULL) { \
- malloc_write("<jemalloc>: Error allocating" \
- " TSD for "#a_name"\n"); \
- abort(); \
- } \
- memcpy(wrapper, &a_name##tsd_boot_wrapper, \
- sizeof(a_name##tsd_wrapper_t)); \
- a_name##tsd_wrapper_set(wrapper); \
-} \
-a_attr bool \
-a_name##tsd_boot(void) \
-{ \
- \
- if (a_name##tsd_boot0()) \
- return (true); \
- a_name##tsd_boot1(); \
- return (false); \
-} \
-a_attr bool \
-a_name##tsd_booted_get(void) \
-{ \
- \
- return (a_name##tsd_booted); \
-} \
-a_attr bool \
-a_name##tsd_get_allocates(void) \
-{ \
- \
- return (true); \
-} \
-/* Get/set. */ \
-a_attr a_type * \
-a_name##tsd_get(bool init) \
-{ \
- a_name##tsd_wrapper_t *wrapper; \
- \
- assert(a_name##tsd_booted); \
- wrapper = a_name##tsd_wrapper_get(init); \
- if (a_name##tsd_get_allocates() && !init && wrapper == NULL) \
- return (NULL); \
- return (&wrapper->val); \
-} \
-a_attr void \
-a_name##tsd_set(a_type *val) \
-{ \
- a_name##tsd_wrapper_t *wrapper; \
- \
- assert(a_name##tsd_booted); \
- wrapper = a_name##tsd_wrapper_get(true); \
- wrapper->val = *(val); \
- if (a_cleanup != malloc_tsd_no_cleanup) \
- wrapper->initialized = true; \
-}
-#else
-#define malloc_tsd_funcs(a_attr, a_name, a_type, a_initializer, \
- a_cleanup) \
-/* Initialization/cleanup. */ \
-a_attr void \
-a_name##tsd_cleanup_wrapper(void *arg) \
-{ \
- a_name##tsd_wrapper_t *wrapper = (a_name##tsd_wrapper_t *)arg; \
- \
- if (a_cleanup != malloc_tsd_no_cleanup && \
- wrapper->initialized) { \
- wrapper->initialized = false; \
- a_cleanup(&wrapper->val); \
- if (wrapper->initialized) { \
- /* Trigger another cleanup round. */ \
- if (pthread_setspecific(a_name##tsd_tsd, \
- (void *)wrapper)) { \
- malloc_write("<jemalloc>: Error" \
- " setting TSD for "#a_name"\n"); \
- if (opt_abort) \
- abort(); \
- } \
- return; \
- } \
- } \
- malloc_tsd_dalloc(wrapper); \
-} \
-a_attr void \
-a_name##tsd_wrapper_set(a_name##tsd_wrapper_t *wrapper) \
-{ \
- \
- if (pthread_setspecific(a_name##tsd_tsd, \
- (void *)wrapper)) { \
- malloc_write("<jemalloc>: Error setting" \
- " TSD for "#a_name"\n"); \
- abort(); \
- } \
-} \
-a_attr a_name##tsd_wrapper_t * \
-a_name##tsd_wrapper_get(bool init) \
-{ \
- a_name##tsd_wrapper_t *wrapper = (a_name##tsd_wrapper_t *) \
- pthread_getspecific(a_name##tsd_tsd); \
- \
- if (init && unlikely(wrapper == NULL)) { \
- tsd_init_block_t block; \
- wrapper = tsd_init_check_recursion( \
- &a_name##tsd_init_head, &block); \
- if (wrapper) \
- return (wrapper); \
- wrapper = (a_name##tsd_wrapper_t *) \
- malloc_tsd_malloc(sizeof(a_name##tsd_wrapper_t)); \
- block.data = wrapper; \
- if (wrapper == NULL) { \
- malloc_write("<jemalloc>: Error allocating" \
- " TSD for "#a_name"\n"); \
- abort(); \
- } else { \
- wrapper->initialized = false; \
- wrapper->val = a_initializer; \
- } \
- a_name##tsd_wrapper_set(wrapper); \
- tsd_init_finish(&a_name##tsd_init_head, &block); \
- } \
- return (wrapper); \
-} \
-a_attr bool \
-a_name##tsd_boot0(void) \
-{ \
- \
- if (pthread_key_create(&a_name##tsd_tsd, \
- a_name##tsd_cleanup_wrapper) != 0) \
- return (true); \
- a_name##tsd_wrapper_set(&a_name##tsd_boot_wrapper); \
- a_name##tsd_booted = true; \
- return (false); \
-} \
-a_attr void \
-a_name##tsd_boot1(void) \
-{ \
- a_name##tsd_wrapper_t *wrapper; \
- wrapper = (a_name##tsd_wrapper_t *) \
- malloc_tsd_malloc(sizeof(a_name##tsd_wrapper_t)); \
- if (wrapper == NULL) { \
- malloc_write("<jemalloc>: Error allocating" \
- " TSD for "#a_name"\n"); \
- abort(); \
- } \
- memcpy(wrapper, &a_name##tsd_boot_wrapper, \
- sizeof(a_name##tsd_wrapper_t)); \
- a_name##tsd_wrapper_set(wrapper); \
-} \
-a_attr bool \
-a_name##tsd_boot(void) \
-{ \
- \
- if (a_name##tsd_boot0()) \
- return (true); \
- a_name##tsd_boot1(); \
- return (false); \
-} \
-a_attr bool \
-a_name##tsd_booted_get(void) \
-{ \
- \
- return (a_name##tsd_booted); \
-} \
-a_attr bool \
-a_name##tsd_get_allocates(void) \
-{ \
- \
- return (true); \
-} \
-/* Get/set. */ \
-a_attr a_type * \
-a_name##tsd_get(bool init) \
-{ \
- a_name##tsd_wrapper_t *wrapper; \
- \
- assert(a_name##tsd_booted); \
- wrapper = a_name##tsd_wrapper_get(init); \
- if (a_name##tsd_get_allocates() && !init && wrapper == NULL) \
- return (NULL); \
- return (&wrapper->val); \
-} \
-a_attr void \
-a_name##tsd_set(a_type *val) \
-{ \
- a_name##tsd_wrapper_t *wrapper; \
- \
- assert(a_name##tsd_booted); \
- wrapper = a_name##tsd_wrapper_get(true); \
- wrapper->val = *(val); \
- if (a_cleanup != malloc_tsd_no_cleanup) \
- wrapper->initialized = true; \
-}
-#endif
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#if (!defined(JEMALLOC_MALLOC_THREAD_CLEANUP) && !defined(JEMALLOC_TLS) && \
- !defined(_WIN32))
-struct tsd_init_block_s {
- ql_elm(tsd_init_block_t) link;
- pthread_t thread;
- void *data;
-};
-struct tsd_init_head_s {
- ql_head(tsd_init_block_t) blocks;
- malloc_mutex_t lock;
-};
-#endif
-
-#define MALLOC_TSD \
-/* O(name, type) */ \
- O(tcache, tcache_t *) \
- O(thread_allocated, uint64_t) \
- O(thread_deallocated, uint64_t) \
- O(prof_tdata, prof_tdata_t *) \
- O(iarena, arena_t *) \
- O(arena, arena_t *) \
- O(arenas_tdata, arena_tdata_t *) \
- O(narenas_tdata, unsigned) \
- O(arenas_tdata_bypass, bool) \
- O(tcache_enabled, tcache_enabled_t) \
- O(quarantine, quarantine_t *) \
- O(witnesses, witness_list_t) \
- O(witness_fork, bool) \
-
-#define TSD_INITIALIZER { \
- tsd_state_uninitialized, \
- NULL, \
- 0, \
- 0, \
- NULL, \
- NULL, \
- NULL, \
- NULL, \
- 0, \
- false, \
- tcache_enabled_default, \
- NULL, \
- ql_head_initializer(witnesses), \
- false \
-}
-
-struct tsd_s {
- tsd_state_t state;
-#define O(n, t) \
- t n;
-MALLOC_TSD
-#undef O
-};
-
-/*
- * Wrapper around tsd_t that makes it possible to avoid implicit conversion
- * between tsd_t and tsdn_t, where tsdn_t is "nullable" and has to be
- * explicitly converted to tsd_t, which is non-nullable.
- */
-struct tsdn_s {
- tsd_t tsd;
-};
-
-static const tsd_t tsd_initializer = TSD_INITIALIZER;
-
-malloc_tsd_types(, tsd_t)
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void *malloc_tsd_malloc(size_t size);
-void malloc_tsd_dalloc(void *wrapper);
-void malloc_tsd_no_cleanup(void *arg);
-void malloc_tsd_cleanup_register(bool (*f)(void));
-tsd_t *malloc_tsd_boot0(void);
-void malloc_tsd_boot1(void);
-#if (!defined(JEMALLOC_MALLOC_THREAD_CLEANUP) && !defined(JEMALLOC_TLS) && \
- !defined(_WIN32))
-void *tsd_init_check_recursion(tsd_init_head_t *head,
- tsd_init_block_t *block);
-void tsd_init_finish(tsd_init_head_t *head, tsd_init_block_t *block);
-#endif
-void tsd_cleanup(void *arg);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-malloc_tsd_protos(JEMALLOC_ATTR(unused), , tsd_t)
-
-tsd_t *tsd_fetch_impl(bool init);
-tsd_t *tsd_fetch(void);
-tsdn_t *tsd_tsdn(tsd_t *tsd);
-bool tsd_nominal(tsd_t *tsd);
-#define O(n, t) \
-t *tsd_##n##p_get(tsd_t *tsd); \
-t tsd_##n##_get(tsd_t *tsd); \
-void tsd_##n##_set(tsd_t *tsd, t n);
-MALLOC_TSD
-#undef O
-tsdn_t *tsdn_fetch(void);
-bool tsdn_null(const tsdn_t *tsdn);
-tsd_t *tsdn_tsd(tsdn_t *tsdn);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_TSD_C_))
-malloc_tsd_externs(, tsd_t)
-malloc_tsd_funcs(JEMALLOC_ALWAYS_INLINE, , tsd_t, tsd_initializer, tsd_cleanup)
-
-JEMALLOC_ALWAYS_INLINE tsd_t *
-tsd_fetch_impl(bool init)
-{
- tsd_t *tsd = tsd_get(init);
-
- if (!init && tsd_get_allocates() && tsd == NULL)
- return (NULL);
- assert(tsd != NULL);
-
- if (unlikely(tsd->state != tsd_state_nominal)) {
- if (tsd->state == tsd_state_uninitialized) {
- tsd->state = tsd_state_nominal;
- /* Trigger cleanup handler registration. */
- tsd_set(tsd);
- } else if (tsd->state == tsd_state_purgatory) {
- tsd->state = tsd_state_reincarnated;
- tsd_set(tsd);
- } else
- assert(tsd->state == tsd_state_reincarnated);
- }
-
- return (tsd);
-}
-
-JEMALLOC_ALWAYS_INLINE tsd_t *
-tsd_fetch(void)
-{
-
- return (tsd_fetch_impl(true));
-}
-
-JEMALLOC_ALWAYS_INLINE tsdn_t *
-tsd_tsdn(tsd_t *tsd)
-{
-
- return ((tsdn_t *)tsd);
-}
-
-JEMALLOC_INLINE bool
-tsd_nominal(tsd_t *tsd)
-{
-
- return (tsd->state == tsd_state_nominal);
-}
-
-#define O(n, t) \
-JEMALLOC_ALWAYS_INLINE t * \
-tsd_##n##p_get(tsd_t *tsd) \
-{ \
- \
- return (&tsd->n); \
-} \
- \
-JEMALLOC_ALWAYS_INLINE t \
-tsd_##n##_get(tsd_t *tsd) \
-{ \
- \
- return (*tsd_##n##p_get(tsd)); \
-} \
- \
-JEMALLOC_ALWAYS_INLINE void \
-tsd_##n##_set(tsd_t *tsd, t n) \
-{ \
- \
- assert(tsd->state == tsd_state_nominal); \
- tsd->n = n; \
-}
-MALLOC_TSD
-#undef O
-
-JEMALLOC_ALWAYS_INLINE tsdn_t *
-tsdn_fetch(void)
-{
-
- if (!tsd_booted_get())
- return (NULL);
-
- return (tsd_tsdn(tsd_fetch_impl(false)));
-}
-
-JEMALLOC_ALWAYS_INLINE bool
-tsdn_null(const tsdn_t *tsdn)
-{
-
- return (tsdn == NULL);
-}
-
-JEMALLOC_ALWAYS_INLINE tsd_t *
-tsdn_tsd(tsdn_t *tsdn)
-{
-
- assert(!tsdn_null(tsdn));
-
- return (&tsdn->tsd);
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/util.h b/memory/jemalloc/src/include/jemalloc/internal/util.h
deleted file mode 100644
index aee00d6d9..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/util.h
+++ /dev/null
@@ -1,338 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#ifdef _WIN32
-# ifdef _WIN64
-# define FMT64_PREFIX "ll"
-# define FMTPTR_PREFIX "ll"
-# else
-# define FMT64_PREFIX "ll"
-# define FMTPTR_PREFIX ""
-# endif
-# define FMTd32 "d"
-# define FMTu32 "u"
-# define FMTx32 "x"
-# define FMTd64 FMT64_PREFIX "d"
-# define FMTu64 FMT64_PREFIX "u"
-# define FMTx64 FMT64_PREFIX "x"
-# define FMTdPTR FMTPTR_PREFIX "d"
-# define FMTuPTR FMTPTR_PREFIX "u"
-# define FMTxPTR FMTPTR_PREFIX "x"
-#else
-# include <inttypes.h>
-# define FMTd32 PRId32
-# define FMTu32 PRIu32
-# define FMTx32 PRIx32
-# define FMTd64 PRId64
-# define FMTu64 PRIu64
-# define FMTx64 PRIx64
-# define FMTdPTR PRIdPTR
-# define FMTuPTR PRIuPTR
-# define FMTxPTR PRIxPTR
-#endif
-
-/* Size of stack-allocated buffer passed to buferror(). */
-#define BUFERROR_BUF 64
-
-/*
- * Size of stack-allocated buffer used by malloc_{,v,vc}printf(). This must be
- * large enough for all possible uses within jemalloc.
- */
-#define MALLOC_PRINTF_BUFSIZE 4096
-
-/* Junk fill patterns. */
-#define JEMALLOC_ALLOC_JUNK ((uint8_t)0xa5)
-#define JEMALLOC_FREE_JUNK ((uint8_t)0x5a)
-
-/*
- * Wrap a cpp argument that contains commas such that it isn't broken up into
- * multiple arguments.
- */
-#define JEMALLOC_ARG_CONCAT(...) __VA_ARGS__
-
-/*
- * Silence compiler warnings due to uninitialized values. This is used
- * wherever the compiler fails to recognize that the variable is never used
- * uninitialized.
- */
-#ifdef JEMALLOC_CC_SILENCE
-# define JEMALLOC_CC_SILENCE_INIT(v) = v
-#else
-# define JEMALLOC_CC_SILENCE_INIT(v)
-#endif
-
-#ifdef __GNUC__
-# define likely(x) __builtin_expect(!!(x), 1)
-# define unlikely(x) __builtin_expect(!!(x), 0)
-#else
-# define likely(x) !!(x)
-# define unlikely(x) !!(x)
-#endif
-
-#if !defined(JEMALLOC_INTERNAL_UNREACHABLE)
-# error JEMALLOC_INTERNAL_UNREACHABLE should have been defined by configure
-#endif
-
-#define unreachable() JEMALLOC_INTERNAL_UNREACHABLE()
-
-#include "jemalloc/internal/assert.h"
-
-/* Use to assert a particular configuration, e.g., cassert(config_debug). */
-#define cassert(c) do { \
- if (unlikely(!(c))) \
- not_reached(); \
-} while (0)
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-int buferror(int err, char *buf, size_t buflen);
-uintmax_t malloc_strtoumax(const char *restrict nptr,
- char **restrict endptr, int base);
-void malloc_write(const char *s);
-
-/*
- * malloc_vsnprintf() supports a subset of snprintf(3) that avoids floating
- * point math.
- */
-size_t malloc_vsnprintf(char *str, size_t size, const char *format,
- va_list ap);
-size_t malloc_snprintf(char *str, size_t size, const char *format, ...)
- JEMALLOC_FORMAT_PRINTF(3, 4);
-void malloc_vcprintf(void (*write_cb)(void *, const char *), void *cbopaque,
- const char *format, va_list ap);
-void malloc_cprintf(void (*write)(void *, const char *), void *cbopaque,
- const char *format, ...) JEMALLOC_FORMAT_PRINTF(3, 4);
-void malloc_printf(const char *format, ...) JEMALLOC_FORMAT_PRINTF(1, 2);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-unsigned ffs_llu(unsigned long long bitmap);
-unsigned ffs_lu(unsigned long bitmap);
-unsigned ffs_u(unsigned bitmap);
-unsigned ffs_zu(size_t bitmap);
-unsigned ffs_u64(uint64_t bitmap);
-unsigned ffs_u32(uint32_t bitmap);
-uint64_t pow2_ceil_u64(uint64_t x);
-uint32_t pow2_ceil_u32(uint32_t x);
-size_t pow2_ceil_zu(size_t x);
-unsigned lg_floor(size_t x);
-void set_errno(int errnum);
-int get_errno(void);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_UTIL_C_))
-
-/* Sanity check. */
-#if !defined(JEMALLOC_INTERNAL_FFSLL) || !defined(JEMALLOC_INTERNAL_FFSL) \
- || !defined(JEMALLOC_INTERNAL_FFS)
-# error JEMALLOC_INTERNAL_FFS{,L,LL} should have been defined by configure
-#endif
-
-JEMALLOC_ALWAYS_INLINE unsigned
-ffs_llu(unsigned long long bitmap)
-{
-
- return (JEMALLOC_INTERNAL_FFSLL(bitmap));
-}
-
-JEMALLOC_ALWAYS_INLINE unsigned
-ffs_lu(unsigned long bitmap)
-{
-
- return (JEMALLOC_INTERNAL_FFSL(bitmap));
-}
-
-JEMALLOC_ALWAYS_INLINE unsigned
-ffs_u(unsigned bitmap)
-{
-
- return (JEMALLOC_INTERNAL_FFS(bitmap));
-}
-
-JEMALLOC_ALWAYS_INLINE unsigned
-ffs_zu(size_t bitmap)
-{
-
-#if LG_SIZEOF_PTR == LG_SIZEOF_INT
- return (ffs_u(bitmap));
-#elif LG_SIZEOF_PTR == LG_SIZEOF_LONG
- return (ffs_lu(bitmap));
-#elif LG_SIZEOF_PTR == LG_SIZEOF_LONG_LONG
- return (ffs_llu(bitmap));
-#else
-#error No implementation for size_t ffs()
-#endif
-}
-
-JEMALLOC_ALWAYS_INLINE unsigned
-ffs_u64(uint64_t bitmap)
-{
-
-#if LG_SIZEOF_LONG == 3
- return (ffs_lu(bitmap));
-#elif LG_SIZEOF_LONG_LONG == 3
- return (ffs_llu(bitmap));
-#else
-#error No implementation for 64-bit ffs()
-#endif
-}
-
-JEMALLOC_ALWAYS_INLINE unsigned
-ffs_u32(uint32_t bitmap)
-{
-
-#if LG_SIZEOF_INT == 2
- return (ffs_u(bitmap));
-#else
-#error No implementation for 32-bit ffs()
-#endif
- return (ffs_u(bitmap));
-}
-
-JEMALLOC_INLINE uint64_t
-pow2_ceil_u64(uint64_t x)
-{
-
- x--;
- x |= x >> 1;
- x |= x >> 2;
- x |= x >> 4;
- x |= x >> 8;
- x |= x >> 16;
- x |= x >> 32;
- x++;
- return (x);
-}
-
-JEMALLOC_INLINE uint32_t
-pow2_ceil_u32(uint32_t x)
-{
-
- x--;
- x |= x >> 1;
- x |= x >> 2;
- x |= x >> 4;
- x |= x >> 8;
- x |= x >> 16;
- x++;
- return (x);
-}
-
-/* Compute the smallest power of 2 that is >= x. */
-JEMALLOC_INLINE size_t
-pow2_ceil_zu(size_t x)
-{
-
-#if (LG_SIZEOF_PTR == 3)
- return (pow2_ceil_u64(x));
-#else
- return (pow2_ceil_u32(x));
-#endif
-}
-
-#if (defined(__i386__) || defined(__amd64__) || defined(__x86_64__))
-JEMALLOC_INLINE unsigned
-lg_floor(size_t x)
-{
- size_t ret;
-
- assert(x != 0);
-
- asm ("bsr %1, %0"
- : "=r"(ret) // Outputs.
- : "r"(x) // Inputs.
- );
- assert(ret < UINT_MAX);
- return ((unsigned)ret);
-}
-#elif (defined(_MSC_VER))
-JEMALLOC_INLINE unsigned
-lg_floor(size_t x)
-{
- unsigned long ret;
-
- assert(x != 0);
-
-#if (LG_SIZEOF_PTR == 3)
- _BitScanReverse64(&ret, x);
-#elif (LG_SIZEOF_PTR == 2)
- _BitScanReverse(&ret, x);
-#else
-# error "Unsupported type size for lg_floor()"
-#endif
- assert(ret < UINT_MAX);
- return ((unsigned)ret);
-}
-#elif (defined(JEMALLOC_HAVE_BUILTIN_CLZ))
-JEMALLOC_INLINE unsigned
-lg_floor(size_t x)
-{
-
- assert(x != 0);
-
-#if (LG_SIZEOF_PTR == LG_SIZEOF_INT)
- return (((8 << LG_SIZEOF_PTR) - 1) - __builtin_clz(x));
-#elif (LG_SIZEOF_PTR == LG_SIZEOF_LONG)
- return (((8 << LG_SIZEOF_PTR) - 1) - __builtin_clzl(x));
-#else
-# error "Unsupported type size for lg_floor()"
-#endif
-}
-#else
-JEMALLOC_INLINE unsigned
-lg_floor(size_t x)
-{
-
- assert(x != 0);
-
- x |= (x >> 1);
- x |= (x >> 2);
- x |= (x >> 4);
- x |= (x >> 8);
- x |= (x >> 16);
-#if (LG_SIZEOF_PTR == 3)
- x |= (x >> 32);
-#endif
- if (x == SIZE_T_MAX)
- return ((8 << LG_SIZEOF_PTR) - 1);
- x++;
- return (ffs_zu(x) - 2);
-}
-#endif
-
-/* Set error code. */
-JEMALLOC_INLINE void
-set_errno(int errnum)
-{
-
-#ifdef _WIN32
- SetLastError(errnum);
-#else
- errno = errnum;
-#endif
-}
-
-/* Get last error code. */
-JEMALLOC_INLINE int
-get_errno(void)
-{
-
-#ifdef _WIN32
- return (GetLastError());
-#else
- return (errno);
-#endif
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/internal/valgrind.h b/memory/jemalloc/src/include/jemalloc/internal/valgrind.h
deleted file mode 100644
index 1a8680828..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/valgrind.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-#ifdef JEMALLOC_VALGRIND
-#include <valgrind/valgrind.h>
-
-/*
- * The size that is reported to Valgrind must be consistent through a chain of
- * malloc..realloc..realloc calls. Request size isn't recorded anywhere in
- * jemalloc, so it is critical that all callers of these macros provide usize
- * rather than request size. As a result, buffer overflow detection is
- * technically weakened for the standard API, though it is generally accepted
- * practice to consider any extra bytes reported by malloc_usable_size() as
- * usable space.
- */
-#define JEMALLOC_VALGRIND_MAKE_MEM_NOACCESS(ptr, usize) do { \
- if (unlikely(in_valgrind)) \
- valgrind_make_mem_noaccess(ptr, usize); \
-} while (0)
-#define JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ptr, usize) do { \
- if (unlikely(in_valgrind)) \
- valgrind_make_mem_undefined(ptr, usize); \
-} while (0)
-#define JEMALLOC_VALGRIND_MAKE_MEM_DEFINED(ptr, usize) do { \
- if (unlikely(in_valgrind)) \
- valgrind_make_mem_defined(ptr, usize); \
-} while (0)
-/*
- * The VALGRIND_MALLOCLIKE_BLOCK() and VALGRIND_RESIZEINPLACE_BLOCK() macro
- * calls must be embedded in macros rather than in functions so that when
- * Valgrind reports errors, there are no extra stack frames in the backtraces.
- */
-#define JEMALLOC_VALGRIND_MALLOC(cond, tsdn, ptr, usize, zero) do { \
- if (unlikely(in_valgrind && cond)) { \
- VALGRIND_MALLOCLIKE_BLOCK(ptr, usize, p2rz(tsdn, ptr), \
- zero); \
- } \
-} while (0)
-#define JEMALLOC_VALGRIND_REALLOC(maybe_moved, tsdn, ptr, usize, \
- ptr_maybe_null, old_ptr, old_usize, old_rzsize, old_ptr_maybe_null, \
- zero) do { \
- if (unlikely(in_valgrind)) { \
- size_t rzsize = p2rz(tsdn, ptr); \
- \
- if (!maybe_moved || ptr == old_ptr) { \
- VALGRIND_RESIZEINPLACE_BLOCK(ptr, old_usize, \
- usize, rzsize); \
- if (zero && old_usize < usize) { \
- valgrind_make_mem_defined( \
- (void *)((uintptr_t)ptr + \
- old_usize), usize - old_usize); \
- } \
- } else { \
- if (!old_ptr_maybe_null || old_ptr != NULL) { \
- valgrind_freelike_block(old_ptr, \
- old_rzsize); \
- } \
- if (!ptr_maybe_null || ptr != NULL) { \
- size_t copy_size = (old_usize < usize) \
- ? old_usize : usize; \
- size_t tail_size = usize - copy_size; \
- VALGRIND_MALLOCLIKE_BLOCK(ptr, usize, \
- rzsize, false); \
- if (copy_size > 0) { \
- valgrind_make_mem_defined(ptr, \
- copy_size); \
- } \
- if (zero && tail_size > 0) { \
- valgrind_make_mem_defined( \
- (void *)((uintptr_t)ptr + \
- copy_size), tail_size); \
- } \
- } \
- } \
- } \
-} while (0)
-#define JEMALLOC_VALGRIND_FREE(ptr, rzsize) do { \
- if (unlikely(in_valgrind)) \
- valgrind_freelike_block(ptr, rzsize); \
-} while (0)
-#else
-#define RUNNING_ON_VALGRIND ((unsigned)0)
-#define JEMALLOC_VALGRIND_MAKE_MEM_NOACCESS(ptr, usize) do {} while (0)
-#define JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ptr, usize) do {} while (0)
-#define JEMALLOC_VALGRIND_MAKE_MEM_DEFINED(ptr, usize) do {} while (0)
-#define JEMALLOC_VALGRIND_MALLOC(cond, tsdn, ptr, usize, zero) do {} while (0)
-#define JEMALLOC_VALGRIND_REALLOC(maybe_moved, tsdn, ptr, usize, \
- ptr_maybe_null, old_ptr, old_usize, old_rzsize, old_ptr_maybe_null, \
- zero) do {} while (0)
-#define JEMALLOC_VALGRIND_FREE(ptr, rzsize) do {} while (0)
-#endif
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-#ifdef JEMALLOC_VALGRIND
-void valgrind_make_mem_noaccess(void *ptr, size_t usize);
-void valgrind_make_mem_undefined(void *ptr, size_t usize);
-void valgrind_make_mem_defined(void *ptr, size_t usize);
-void valgrind_freelike_block(void *ptr, size_t usize);
-#endif
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
-
diff --git a/memory/jemalloc/src/include/jemalloc/internal/witness.h b/memory/jemalloc/src/include/jemalloc/internal/witness.h
deleted file mode 100644
index cdf15d797..000000000
--- a/memory/jemalloc/src/include/jemalloc/internal/witness.h
+++ /dev/null
@@ -1,266 +0,0 @@
-/******************************************************************************/
-#ifdef JEMALLOC_H_TYPES
-
-typedef struct witness_s witness_t;
-typedef unsigned witness_rank_t;
-typedef ql_head(witness_t) witness_list_t;
-typedef int witness_comp_t (const witness_t *, const witness_t *);
-
-/*
- * Lock ranks. Witnesses with rank WITNESS_RANK_OMIT are completely ignored by
- * the witness machinery.
- */
-#define WITNESS_RANK_OMIT 0U
-
-#define WITNESS_RANK_INIT 1U
-#define WITNESS_RANK_CTL 1U
-#define WITNESS_RANK_ARENAS 2U
-
-#define WITNESS_RANK_PROF_DUMP 3U
-#define WITNESS_RANK_PROF_BT2GCTX 4U
-#define WITNESS_RANK_PROF_TDATAS 5U
-#define WITNESS_RANK_PROF_TDATA 6U
-#define WITNESS_RANK_PROF_GCTX 7U
-
-#define WITNESS_RANK_ARENA 8U
-#define WITNESS_RANK_ARENA_CHUNKS 9U
-#define WITNESS_RANK_ARENA_NODE_CACHE 10
-
-#define WITNESS_RANK_BASE 11U
-
-#define WITNESS_RANK_LEAF 0xffffffffU
-#define WITNESS_RANK_ARENA_BIN WITNESS_RANK_LEAF
-#define WITNESS_RANK_ARENA_HUGE WITNESS_RANK_LEAF
-#define WITNESS_RANK_DSS WITNESS_RANK_LEAF
-#define WITNESS_RANK_PROF_ACTIVE WITNESS_RANK_LEAF
-#define WITNESS_RANK_PROF_DUMP_SEQ WITNESS_RANK_LEAF
-#define WITNESS_RANK_PROF_GDUMP WITNESS_RANK_LEAF
-#define WITNESS_RANK_PROF_NEXT_THR_UID WITNESS_RANK_LEAF
-#define WITNESS_RANK_PROF_THREAD_ACTIVE_INIT WITNESS_RANK_LEAF
-
-#define WITNESS_INITIALIZER(rank) {"initializer", rank, NULL, {NULL, NULL}}
-
-#endif /* JEMALLOC_H_TYPES */
-/******************************************************************************/
-#ifdef JEMALLOC_H_STRUCTS
-
-struct witness_s {
- /* Name, used for printing lock order reversal messages. */
- const char *name;
-
- /*
- * Witness rank, where 0 is lowest and UINT_MAX is highest. Witnesses
- * must be acquired in order of increasing rank.
- */
- witness_rank_t rank;
-
- /*
- * If two witnesses are of equal rank and they have the samp comp
- * function pointer, it is called as a last attempt to differentiate
- * between witnesses of equal rank.
- */
- witness_comp_t *comp;
-
- /* Linkage for thread's currently owned locks. */
- ql_elm(witness_t) link;
-};
-
-#endif /* JEMALLOC_H_STRUCTS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_EXTERNS
-
-void witness_init(witness_t *witness, const char *name, witness_rank_t rank,
- witness_comp_t *comp);
-#ifdef JEMALLOC_JET
-typedef void (witness_lock_error_t)(const witness_list_t *, const witness_t *);
-extern witness_lock_error_t *witness_lock_error;
-#else
-void witness_lock_error(const witness_list_t *witnesses,
- const witness_t *witness);
-#endif
-#ifdef JEMALLOC_JET
-typedef void (witness_owner_error_t)(const witness_t *);
-extern witness_owner_error_t *witness_owner_error;
-#else
-void witness_owner_error(const witness_t *witness);
-#endif
-#ifdef JEMALLOC_JET
-typedef void (witness_not_owner_error_t)(const witness_t *);
-extern witness_not_owner_error_t *witness_not_owner_error;
-#else
-void witness_not_owner_error(const witness_t *witness);
-#endif
-#ifdef JEMALLOC_JET
-typedef void (witness_lockless_error_t)(const witness_list_t *);
-extern witness_lockless_error_t *witness_lockless_error;
-#else
-void witness_lockless_error(const witness_list_t *witnesses);
-#endif
-
-void witnesses_cleanup(tsd_t *tsd);
-void witness_fork_cleanup(tsd_t *tsd);
-void witness_prefork(tsd_t *tsd);
-void witness_postfork_parent(tsd_t *tsd);
-void witness_postfork_child(tsd_t *tsd);
-
-#endif /* JEMALLOC_H_EXTERNS */
-/******************************************************************************/
-#ifdef JEMALLOC_H_INLINES
-
-#ifndef JEMALLOC_ENABLE_INLINE
-bool witness_owner(tsd_t *tsd, const witness_t *witness);
-void witness_assert_owner(tsdn_t *tsdn, const witness_t *witness);
-void witness_assert_not_owner(tsdn_t *tsdn, const witness_t *witness);
-void witness_assert_lockless(tsdn_t *tsdn);
-void witness_lock(tsdn_t *tsdn, witness_t *witness);
-void witness_unlock(tsdn_t *tsdn, witness_t *witness);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(JEMALLOC_MUTEX_C_))
-JEMALLOC_INLINE bool
-witness_owner(tsd_t *tsd, const witness_t *witness)
-{
- witness_list_t *witnesses;
- witness_t *w;
-
- witnesses = tsd_witnessesp_get(tsd);
- ql_foreach(w, witnesses, link) {
- if (w == witness)
- return (true);
- }
-
- return (false);
-}
-
-JEMALLOC_INLINE void
-witness_assert_owner(tsdn_t *tsdn, const witness_t *witness)
-{
- tsd_t *tsd;
-
- if (!config_debug)
- return;
-
- if (tsdn_null(tsdn))
- return;
- tsd = tsdn_tsd(tsdn);
- if (witness->rank == WITNESS_RANK_OMIT)
- return;
-
- if (witness_owner(tsd, witness))
- return;
- witness_owner_error(witness);
-}
-
-JEMALLOC_INLINE void
-witness_assert_not_owner(tsdn_t *tsdn, const witness_t *witness)
-{
- tsd_t *tsd;
- witness_list_t *witnesses;
- witness_t *w;
-
- if (!config_debug)
- return;
-
- if (tsdn_null(tsdn))
- return;
- tsd = tsdn_tsd(tsdn);
- if (witness->rank == WITNESS_RANK_OMIT)
- return;
-
- witnesses = tsd_witnessesp_get(tsd);
- ql_foreach(w, witnesses, link) {
- if (w == witness)
- witness_not_owner_error(witness);
- }
-}
-
-JEMALLOC_INLINE void
-witness_assert_lockless(tsdn_t *tsdn)
-{
- tsd_t *tsd;
- witness_list_t *witnesses;
- witness_t *w;
-
- if (!config_debug)
- return;
-
- if (tsdn_null(tsdn))
- return;
- tsd = tsdn_tsd(tsdn);
-
- witnesses = tsd_witnessesp_get(tsd);
- w = ql_last(witnesses, link);
- if (w != NULL)
- witness_lockless_error(witnesses);
-}
-
-JEMALLOC_INLINE void
-witness_lock(tsdn_t *tsdn, witness_t *witness)
-{
- tsd_t *tsd;
- witness_list_t *witnesses;
- witness_t *w;
-
- if (!config_debug)
- return;
-
- if (tsdn_null(tsdn))
- return;
- tsd = tsdn_tsd(tsdn);
- if (witness->rank == WITNESS_RANK_OMIT)
- return;
-
- witness_assert_not_owner(tsdn, witness);
-
- witnesses = tsd_witnessesp_get(tsd);
- w = ql_last(witnesses, link);
- if (w == NULL) {
- /* No other locks; do nothing. */
- } else if (tsd_witness_fork_get(tsd) && w->rank <= witness->rank) {
- /* Forking, and relaxed ranking satisfied. */
- } else if (w->rank > witness->rank) {
- /* Not forking, rank order reversal. */
- witness_lock_error(witnesses, witness);
- } else if (w->rank == witness->rank && (w->comp == NULL || w->comp !=
- witness->comp || w->comp(w, witness) > 0)) {
- /*
- * Missing/incompatible comparison function, or comparison
- * function indicates rank order reversal.
- */
- witness_lock_error(witnesses, witness);
- }
-
- ql_elm_new(witness, link);
- ql_tail_insert(witnesses, witness, link);
-}
-
-JEMALLOC_INLINE void
-witness_unlock(tsdn_t *tsdn, witness_t *witness)
-{
- tsd_t *tsd;
- witness_list_t *witnesses;
-
- if (!config_debug)
- return;
-
- if (tsdn_null(tsdn))
- return;
- tsd = tsdn_tsd(tsdn);
- if (witness->rank == WITNESS_RANK_OMIT)
- return;
-
- /*
- * Check whether owner before removal, rather than relying on
- * witness_assert_owner() to abort, so that unit tests can test this
- * function's failure mode without causing undefined behavior.
- */
- if (witness_owner(tsd, witness)) {
- witnesses = tsd_witnessesp_get(tsd);
- ql_remove(witnesses, witness, link);
- } else
- witness_assert_owner(tsdn, witness);
-}
-#endif
-
-#endif /* JEMALLOC_H_INLINES */
-/******************************************************************************/
diff --git a/memory/jemalloc/src/include/jemalloc/jemalloc.sh b/memory/jemalloc/src/include/jemalloc/jemalloc.sh
deleted file mode 100755
index c085814f2..000000000
--- a/memory/jemalloc/src/include/jemalloc/jemalloc.sh
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/bin/sh
-
-objroot=$1
-
-cat <<EOF
-#ifndef JEMALLOC_H_
-#define JEMALLOC_H_
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-EOF
-
-for hdr in jemalloc_defs.h jemalloc_rename.h jemalloc_macros.h \
- jemalloc_protos.h jemalloc_typedefs.h jemalloc_mangle.h ; do
- cat "${objroot}include/jemalloc/${hdr}" \
- | grep -v 'Generated from .* by configure\.' \
- | sed -e 's/^#define /#define /g' \
- | sed -e 's/ $//g'
- echo
-done
-
-cat <<EOF
-#ifdef __cplusplus
-}
-#endif
-#endif /* JEMALLOC_H_ */
-EOF
diff --git a/memory/jemalloc/src/include/jemalloc/jemalloc_defs.h.in b/memory/jemalloc/src/include/jemalloc/jemalloc_defs.h.in
deleted file mode 100644
index 6d89435c2..000000000
--- a/memory/jemalloc/src/include/jemalloc/jemalloc_defs.h.in
+++ /dev/null
@@ -1,45 +0,0 @@
-/* Defined if __attribute__((...)) syntax is supported. */
-#undef JEMALLOC_HAVE_ATTR
-
-/* Defined if alloc_size attribute is supported. */
-#undef JEMALLOC_HAVE_ATTR_ALLOC_SIZE
-
-/* Defined if format(gnu_printf, ...) attribute is supported. */
-#undef JEMALLOC_HAVE_ATTR_FORMAT_GNU_PRINTF
-
-/* Defined if format(printf, ...) attribute is supported. */
-#undef JEMALLOC_HAVE_ATTR_FORMAT_PRINTF
-
-/*
- * Define overrides for non-standard allocator-related functions if they are
- * present on the system.
- */
-#undef JEMALLOC_OVERRIDE_MEMALIGN
-#undef JEMALLOC_OVERRIDE_VALLOC
-
-/*
- * At least Linux omits the "const" in:
- *
- * size_t malloc_usable_size(const void *ptr);
- *
- * Match the operating system's prototype.
- */
-#undef JEMALLOC_USABLE_SIZE_CONST
-
-/*
- * If defined, specify throw() for the public function prototypes when compiling
- * with C++. The only justification for this is to match the prototypes that
- * glibc defines.
- */
-#undef JEMALLOC_USE_CXX_THROW
-
-#ifdef _MSC_VER
-# ifdef _WIN64
-# define LG_SIZEOF_PTR_WIN 3
-# else
-# define LG_SIZEOF_PTR_WIN 2
-# endif
-#endif
-
-/* sizeof(void *) == 2^LG_SIZEOF_PTR. */
-#undef LG_SIZEOF_PTR
diff --git a/memory/jemalloc/src/include/jemalloc/jemalloc_macros.h.in b/memory/jemalloc/src/include/jemalloc/jemalloc_macros.h.in
deleted file mode 100644
index 129240ed9..000000000
--- a/memory/jemalloc/src/include/jemalloc/jemalloc_macros.h.in
+++ /dev/null
@@ -1,103 +0,0 @@
-#include <stdlib.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <limits.h>
-#include <strings.h>
-
-#define JEMALLOC_VERSION "@jemalloc_version@"
-#define JEMALLOC_VERSION_MAJOR @jemalloc_version_major@
-#define JEMALLOC_VERSION_MINOR @jemalloc_version_minor@
-#define JEMALLOC_VERSION_BUGFIX @jemalloc_version_bugfix@
-#define JEMALLOC_VERSION_NREV @jemalloc_version_nrev@
-#define JEMALLOC_VERSION_GID "@jemalloc_version_gid@"
-
-# define MALLOCX_LG_ALIGN(la) ((int)(la))
-# if LG_SIZEOF_PTR == 2
-# define MALLOCX_ALIGN(a) ((int)(ffs((int)(a))-1))
-# else
-# define MALLOCX_ALIGN(a) \
- ((int)(((size_t)(a) < (size_t)INT_MAX) ? ffs((int)(a))-1 : \
- ffs((int)(((size_t)(a))>>32))+31))
-# endif
-# define MALLOCX_ZERO ((int)0x40)
-/*
- * Bias tcache index bits so that 0 encodes "automatic tcache management", and 1
- * encodes MALLOCX_TCACHE_NONE.
- */
-# define MALLOCX_TCACHE(tc) ((int)(((tc)+2) << 8))
-# define MALLOCX_TCACHE_NONE MALLOCX_TCACHE(-1)
-/*
- * Bias arena index bits so that 0 encodes "use an automatically chosen arena".
- */
-# define MALLOCX_ARENA(a) ((((int)(a))+1) << 20)
-
-#if defined(__cplusplus) && defined(JEMALLOC_USE_CXX_THROW)
-# define JEMALLOC_CXX_THROW throw()
-#else
-# define JEMALLOC_CXX_THROW
-#endif
-
-#if _MSC_VER
-# define JEMALLOC_ATTR(s)
-# define JEMALLOC_ALIGNED(s) __declspec(align(s))
-# define JEMALLOC_ALLOC_SIZE(s)
-# define JEMALLOC_ALLOC_SIZE2(s1, s2)
-# ifndef JEMALLOC_EXPORT
-# ifdef DLLEXPORT
-# define JEMALLOC_EXPORT __declspec(dllexport)
-# else
-# define JEMALLOC_EXPORT __declspec(dllimport)
-# endif
-# endif
-# define JEMALLOC_FORMAT_PRINTF(s, i)
-# define JEMALLOC_NOINLINE __declspec(noinline)
-# ifdef __cplusplus
-# define JEMALLOC_NOTHROW __declspec(nothrow)
-# else
-# define JEMALLOC_NOTHROW
-# endif
-# define JEMALLOC_SECTION(s) __declspec(allocate(s))
-# define JEMALLOC_RESTRICT_RETURN __declspec(restrict)
-# if _MSC_VER >= 1900 && !defined(__EDG__)
-# define JEMALLOC_ALLOCATOR __declspec(allocator)
-# else
-# define JEMALLOC_ALLOCATOR
-# endif
-#elif defined(JEMALLOC_HAVE_ATTR)
-# define JEMALLOC_ATTR(s) __attribute__((s))
-# define JEMALLOC_ALIGNED(s) JEMALLOC_ATTR(aligned(s))
-# ifdef JEMALLOC_HAVE_ATTR_ALLOC_SIZE
-# define JEMALLOC_ALLOC_SIZE(s) JEMALLOC_ATTR(alloc_size(s))
-# define JEMALLOC_ALLOC_SIZE2(s1, s2) JEMALLOC_ATTR(alloc_size(s1, s2))
-# else
-# define JEMALLOC_ALLOC_SIZE(s)
-# define JEMALLOC_ALLOC_SIZE2(s1, s2)
-# endif
-# ifndef JEMALLOC_EXPORT
-# define JEMALLOC_EXPORT JEMALLOC_ATTR(visibility("default"))
-# endif
-# ifdef JEMALLOC_HAVE_ATTR_FORMAT_GNU_PRINTF
-# define JEMALLOC_FORMAT_PRINTF(s, i) JEMALLOC_ATTR(format(gnu_printf, s, i))
-# elif defined(JEMALLOC_HAVE_ATTR_FORMAT_PRINTF)
-# define JEMALLOC_FORMAT_PRINTF(s, i) JEMALLOC_ATTR(format(printf, s, i))
-# else
-# define JEMALLOC_FORMAT_PRINTF(s, i)
-# endif
-# define JEMALLOC_NOINLINE JEMALLOC_ATTR(noinline)
-# define JEMALLOC_NOTHROW JEMALLOC_ATTR(nothrow)
-# define JEMALLOC_SECTION(s) JEMALLOC_ATTR(section(s))
-# define JEMALLOC_RESTRICT_RETURN
-# define JEMALLOC_ALLOCATOR
-#else
-# define JEMALLOC_ATTR(s)
-# define JEMALLOC_ALIGNED(s)
-# define JEMALLOC_ALLOC_SIZE(s)
-# define JEMALLOC_ALLOC_SIZE2(s1, s2)
-# define JEMALLOC_EXPORT
-# define JEMALLOC_FORMAT_PRINTF(s, i)
-# define JEMALLOC_NOINLINE
-# define JEMALLOC_NOTHROW
-# define JEMALLOC_SECTION(s)
-# define JEMALLOC_RESTRICT_RETURN
-# define JEMALLOC_ALLOCATOR
-#endif
diff --git a/memory/jemalloc/src/include/jemalloc/jemalloc_mangle.sh b/memory/jemalloc/src/include/jemalloc/jemalloc_mangle.sh
deleted file mode 100755
index df328b78d..000000000
--- a/memory/jemalloc/src/include/jemalloc/jemalloc_mangle.sh
+++ /dev/null
@@ -1,45 +0,0 @@
-#!/bin/sh
-
-public_symbols_txt=$1
-symbol_prefix=$2
-
-cat <<EOF
-/*
- * By default application code must explicitly refer to mangled symbol names,
- * so that it is possible to use jemalloc in conjunction with another allocator
- * in the same application. Define JEMALLOC_MANGLE in order to cause automatic
- * name mangling that matches the API prefixing that happened as a result of
- * --with-mangling and/or --with-jemalloc-prefix configuration settings.
- */
-#ifdef JEMALLOC_MANGLE
-# ifndef JEMALLOC_NO_DEMANGLE
-# define JEMALLOC_NO_DEMANGLE
-# endif
-EOF
-
-for nm in `cat ${public_symbols_txt}` ; do
- n=`echo ${nm} |tr ':' ' ' |awk '{print $1}'`
- echo "# define ${n} ${symbol_prefix}${n}"
-done
-
-cat <<EOF
-#endif
-
-/*
- * The ${symbol_prefix}* macros can be used as stable alternative names for the
- * public jemalloc API if JEMALLOC_NO_DEMANGLE is defined. This is primarily
- * meant for use in jemalloc itself, but it can be used by application code to
- * provide isolation from the name mangling specified via --with-mangling
- * and/or --with-jemalloc-prefix.
- */
-#ifndef JEMALLOC_NO_DEMANGLE
-EOF
-
-for nm in `cat ${public_symbols_txt}` ; do
- n=`echo ${nm} |tr ':' ' ' |awk '{print $1}'`
- echo "# undef ${symbol_prefix}${n}"
-done
-
-cat <<EOF
-#endif
-EOF
diff --git a/memory/jemalloc/src/include/jemalloc/jemalloc_protos.h.in b/memory/jemalloc/src/include/jemalloc/jemalloc_protos.h.in
deleted file mode 100644
index a78414b19..000000000
--- a/memory/jemalloc/src/include/jemalloc/jemalloc_protos.h.in
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * The @je_@ prefix on the following public symbol declarations is an artifact
- * of namespace management, and should be omitted in application code unless
- * JEMALLOC_NO_DEMANGLE is defined (see jemalloc_mangle@install_suffix@.h).
- */
-extern JEMALLOC_EXPORT const char *@je_@malloc_conf;
-extern JEMALLOC_EXPORT void (*@je_@malloc_message)(void *cbopaque,
- const char *s);
-
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
- void JEMALLOC_NOTHROW *@je_@malloc(size_t size)
- JEMALLOC_CXX_THROW JEMALLOC_ATTR(malloc) JEMALLOC_ALLOC_SIZE(1);
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
- void JEMALLOC_NOTHROW *@je_@calloc(size_t num, size_t size)
- JEMALLOC_CXX_THROW JEMALLOC_ATTR(malloc) JEMALLOC_ALLOC_SIZE2(1, 2);
-JEMALLOC_EXPORT int JEMALLOC_NOTHROW @je_@posix_memalign(void **memptr,
- size_t alignment, size_t size) JEMALLOC_CXX_THROW JEMALLOC_ATTR(nonnull(1));
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
- void JEMALLOC_NOTHROW *@je_@aligned_alloc(size_t alignment,
- size_t size) JEMALLOC_CXX_THROW JEMALLOC_ATTR(malloc)
- JEMALLOC_ALLOC_SIZE(2);
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
- void JEMALLOC_NOTHROW *@je_@realloc(void *ptr, size_t size)
- JEMALLOC_CXX_THROW JEMALLOC_ALLOC_SIZE(2);
-JEMALLOC_EXPORT void JEMALLOC_NOTHROW @je_@free(void *ptr)
- JEMALLOC_CXX_THROW;
-
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
- void JEMALLOC_NOTHROW *@je_@mallocx(size_t size, int flags)
- JEMALLOC_ATTR(malloc) JEMALLOC_ALLOC_SIZE(1);
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
- void JEMALLOC_NOTHROW *@je_@rallocx(void *ptr, size_t size,
- int flags) JEMALLOC_ALLOC_SIZE(2);
-JEMALLOC_EXPORT size_t JEMALLOC_NOTHROW @je_@xallocx(void *ptr, size_t size,
- size_t extra, int flags);
-JEMALLOC_EXPORT size_t JEMALLOC_NOTHROW @je_@sallocx(const void *ptr,
- int flags) JEMALLOC_ATTR(pure);
-JEMALLOC_EXPORT void JEMALLOC_NOTHROW @je_@dallocx(void *ptr, int flags);
-JEMALLOC_EXPORT void JEMALLOC_NOTHROW @je_@sdallocx(void *ptr, size_t size,
- int flags);
-JEMALLOC_EXPORT size_t JEMALLOC_NOTHROW @je_@nallocx(size_t size, int flags)
- JEMALLOC_ATTR(pure);
-
-JEMALLOC_EXPORT int JEMALLOC_NOTHROW @je_@mallctl(const char *name,
- void *oldp, size_t *oldlenp, void *newp, size_t newlen);
-JEMALLOC_EXPORT int JEMALLOC_NOTHROW @je_@mallctlnametomib(const char *name,
- size_t *mibp, size_t *miblenp);
-JEMALLOC_EXPORT int JEMALLOC_NOTHROW @je_@mallctlbymib(const size_t *mib,
- size_t miblen, void *oldp, size_t *oldlenp, void *newp, size_t newlen);
-JEMALLOC_EXPORT void JEMALLOC_NOTHROW @je_@malloc_stats_print(
- void (*write_cb)(void *, const char *), void *@je_@cbopaque,
- const char *opts);
-JEMALLOC_EXPORT size_t JEMALLOC_NOTHROW @je_@malloc_usable_size(
- JEMALLOC_USABLE_SIZE_CONST void *ptr) JEMALLOC_CXX_THROW;
-
-#ifdef JEMALLOC_OVERRIDE_MEMALIGN
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
- void JEMALLOC_NOTHROW *@je_@memalign(size_t alignment, size_t size)
- JEMALLOC_CXX_THROW JEMALLOC_ATTR(malloc);
-#endif
-
-#ifdef JEMALLOC_OVERRIDE_VALLOC
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
- void JEMALLOC_NOTHROW *@je_@valloc(size_t size) JEMALLOC_CXX_THROW
- JEMALLOC_ATTR(malloc);
-#endif
diff --git a/memory/jemalloc/src/include/jemalloc/jemalloc_rename.sh b/memory/jemalloc/src/include/jemalloc/jemalloc_rename.sh
deleted file mode 100755
index f94389120..000000000
--- a/memory/jemalloc/src/include/jemalloc/jemalloc_rename.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/bin/sh
-
-public_symbols_txt=$1
-
-cat <<EOF
-/*
- * Name mangling for public symbols is controlled by --with-mangling and
- * --with-jemalloc-prefix. With default settings the je_ prefix is stripped by
- * these macro definitions.
- */
-#ifndef JEMALLOC_NO_RENAME
-EOF
-
-for nm in `cat ${public_symbols_txt}` ; do
- n=`echo ${nm} |tr ':' ' ' |awk '{print $1}'`
- m=`echo ${nm} |tr ':' ' ' |awk '{print $2}'`
- echo "# define je_${n} ${m}"
-done
-
-cat <<EOF
-#endif
-EOF
diff --git a/memory/jemalloc/src/include/jemalloc/jemalloc_typedefs.h.in b/memory/jemalloc/src/include/jemalloc/jemalloc_typedefs.h.in
deleted file mode 100644
index fa7b350ad..000000000
--- a/memory/jemalloc/src/include/jemalloc/jemalloc_typedefs.h.in
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * void *
- * chunk_alloc(void *new_addr, size_t size, size_t alignment, bool *zero,
- * bool *commit, unsigned arena_ind);
- */
-typedef void *(chunk_alloc_t)(void *, size_t, size_t, bool *, bool *, unsigned);
-
-/*
- * bool
- * chunk_dalloc(void *chunk, size_t size, bool committed, unsigned arena_ind);
- */
-typedef bool (chunk_dalloc_t)(void *, size_t, bool, unsigned);
-
-/*
- * bool
- * chunk_commit(void *chunk, size_t size, size_t offset, size_t length,
- * unsigned arena_ind);
- */
-typedef bool (chunk_commit_t)(void *, size_t, size_t, size_t, unsigned);
-
-/*
- * bool
- * chunk_decommit(void *chunk, size_t size, size_t offset, size_t length,
- * unsigned arena_ind);
- */
-typedef bool (chunk_decommit_t)(void *, size_t, size_t, size_t, unsigned);
-
-/*
- * bool
- * chunk_purge(void *chunk, size_t size, size_t offset, size_t length,
- * unsigned arena_ind);
- */
-typedef bool (chunk_purge_t)(void *, size_t, size_t, size_t, unsigned);
-
-/*
- * bool
- * chunk_split(void *chunk, size_t size, size_t size_a, size_t size_b,
- * bool committed, unsigned arena_ind);
- */
-typedef bool (chunk_split_t)(void *, size_t, size_t, size_t, bool, unsigned);
-
-/*
- * bool
- * chunk_merge(void *chunk_a, size_t size_a, void *chunk_b, size_t size_b,
- * bool committed, unsigned arena_ind);
- */
-typedef bool (chunk_merge_t)(void *, size_t, void *, size_t, bool, unsigned);
-
-typedef struct {
- chunk_alloc_t *alloc;
- chunk_dalloc_t *dalloc;
- chunk_commit_t *commit;
- chunk_decommit_t *decommit;
- chunk_purge_t *purge;
- chunk_split_t *split;
- chunk_merge_t *merge;
-} chunk_hooks_t;
diff --git a/memory/jemalloc/src/include/msvc_compat/C99/stdbool.h b/memory/jemalloc/src/include/msvc_compat/C99/stdbool.h
deleted file mode 100644
index d92160ebc..000000000
--- a/memory/jemalloc/src/include/msvc_compat/C99/stdbool.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef stdbool_h
-#define stdbool_h
-
-#include <wtypes.h>
-
-/* MSVC doesn't define _Bool or bool in C, but does have BOOL */
-/* Note this doesn't pass autoconf's test because (bool) 0.5 != true */
-/* Clang-cl uses MSVC headers, so needs msvc_compat, but has _Bool as
- * a built-in type. */
-#ifndef __clang__
-typedef BOOL _Bool;
-#endif
-
-#define bool _Bool
-#define true 1
-#define false 0
-
-#define __bool_true_false_are_defined 1
-
-#endif /* stdbool_h */
diff --git a/memory/jemalloc/src/include/msvc_compat/C99/stdint.h b/memory/jemalloc/src/include/msvc_compat/C99/stdint.h
deleted file mode 100644
index d02608a59..000000000
--- a/memory/jemalloc/src/include/msvc_compat/C99/stdint.h
+++ /dev/null
@@ -1,247 +0,0 @@
-// ISO C9x compliant stdint.h for Microsoft Visual Studio
-// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
-//
-// Copyright (c) 2006-2008 Alexander Chemeris
-//
-// 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 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 _MSC_VER // [
-#error "Use this header only with Microsoft Visual C++ compilers!"
-#endif // _MSC_VER ]
-
-#ifndef _MSC_STDINT_H_ // [
-#define _MSC_STDINT_H_
-
-#if _MSC_VER > 1000
-#pragma once
-#endif
-
-#include <limits.h>
-
-// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
-// compiling for ARM we should wrap <wchar.h> include with 'extern "C++" {}'
-// or compiler give many errors like this:
-// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
-#ifdef __cplusplus
-extern "C" {
-#endif
-# include <wchar.h>
-#ifdef __cplusplus
-}
-#endif
-
-// Define _W64 macros to mark types changing their size, like intptr_t.
-#ifndef _W64
-# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
-# define _W64 __w64
-# else
-# define _W64
-# endif
-#endif
-
-
-// 7.18.1 Integer types
-
-// 7.18.1.1 Exact-width integer types
-
-// Visual Studio 6 and Embedded Visual C++ 4 doesn't
-// realize that, e.g. char has the same size as __int8
-// so we give up on __intX for them.
-#if (_MSC_VER < 1300)
- typedef signed char int8_t;
- typedef signed short int16_t;
- typedef signed int int32_t;
- typedef unsigned char uint8_t;
- typedef unsigned short uint16_t;
- typedef unsigned int uint32_t;
-#else
- typedef signed __int8 int8_t;
- typedef signed __int16 int16_t;
- typedef signed __int32 int32_t;
- typedef unsigned __int8 uint8_t;
- typedef unsigned __int16 uint16_t;
- typedef unsigned __int32 uint32_t;
-#endif
-typedef signed __int64 int64_t;
-typedef unsigned __int64 uint64_t;
-
-
-// 7.18.1.2 Minimum-width integer types
-typedef int8_t int_least8_t;
-typedef int16_t int_least16_t;
-typedef int32_t int_least32_t;
-typedef int64_t int_least64_t;
-typedef uint8_t uint_least8_t;
-typedef uint16_t uint_least16_t;
-typedef uint32_t uint_least32_t;
-typedef uint64_t uint_least64_t;
-
-// 7.18.1.3 Fastest minimum-width integer types
-typedef int8_t int_fast8_t;
-typedef int16_t int_fast16_t;
-typedef int32_t int_fast32_t;
-typedef int64_t int_fast64_t;
-typedef uint8_t uint_fast8_t;
-typedef uint16_t uint_fast16_t;
-typedef uint32_t uint_fast32_t;
-typedef uint64_t uint_fast64_t;
-
-// 7.18.1.4 Integer types capable of holding object pointers
-#ifdef _WIN64 // [
- typedef signed __int64 intptr_t;
- typedef unsigned __int64 uintptr_t;
-#else // _WIN64 ][
- typedef _W64 signed int intptr_t;
- typedef _W64 unsigned int uintptr_t;
-#endif // _WIN64 ]
-
-// 7.18.1.5 Greatest-width integer types
-typedef int64_t intmax_t;
-typedef uint64_t uintmax_t;
-
-
-// 7.18.2 Limits of specified-width integer types
-
-#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
-
-// 7.18.2.1 Limits of exact-width integer types
-#define INT8_MIN ((int8_t)_I8_MIN)
-#define INT8_MAX _I8_MAX
-#define INT16_MIN ((int16_t)_I16_MIN)
-#define INT16_MAX _I16_MAX
-#define INT32_MIN ((int32_t)_I32_MIN)
-#define INT32_MAX _I32_MAX
-#define INT64_MIN ((int64_t)_I64_MIN)
-#define INT64_MAX _I64_MAX
-#define UINT8_MAX _UI8_MAX
-#define UINT16_MAX _UI16_MAX
-#define UINT32_MAX _UI32_MAX
-#define UINT64_MAX _UI64_MAX
-
-// 7.18.2.2 Limits of minimum-width integer types
-#define INT_LEAST8_MIN INT8_MIN
-#define INT_LEAST8_MAX INT8_MAX
-#define INT_LEAST16_MIN INT16_MIN
-#define INT_LEAST16_MAX INT16_MAX
-#define INT_LEAST32_MIN INT32_MIN
-#define INT_LEAST32_MAX INT32_MAX
-#define INT_LEAST64_MIN INT64_MIN
-#define INT_LEAST64_MAX INT64_MAX
-#define UINT_LEAST8_MAX UINT8_MAX
-#define UINT_LEAST16_MAX UINT16_MAX
-#define UINT_LEAST32_MAX UINT32_MAX
-#define UINT_LEAST64_MAX UINT64_MAX
-
-// 7.18.2.3 Limits of fastest minimum-width integer types
-#define INT_FAST8_MIN INT8_MIN
-#define INT_FAST8_MAX INT8_MAX
-#define INT_FAST16_MIN INT16_MIN
-#define INT_FAST16_MAX INT16_MAX
-#define INT_FAST32_MIN INT32_MIN
-#define INT_FAST32_MAX INT32_MAX
-#define INT_FAST64_MIN INT64_MIN
-#define INT_FAST64_MAX INT64_MAX
-#define UINT_FAST8_MAX UINT8_MAX
-#define UINT_FAST16_MAX UINT16_MAX
-#define UINT_FAST32_MAX UINT32_MAX
-#define UINT_FAST64_MAX UINT64_MAX
-
-// 7.18.2.4 Limits of integer types capable of holding object pointers
-#ifdef _WIN64 // [
-# define INTPTR_MIN INT64_MIN
-# define INTPTR_MAX INT64_MAX
-# define UINTPTR_MAX UINT64_MAX
-#else // _WIN64 ][
-# define INTPTR_MIN INT32_MIN
-# define INTPTR_MAX INT32_MAX
-# define UINTPTR_MAX UINT32_MAX
-#endif // _WIN64 ]
-
-// 7.18.2.5 Limits of greatest-width integer types
-#define INTMAX_MIN INT64_MIN
-#define INTMAX_MAX INT64_MAX
-#define UINTMAX_MAX UINT64_MAX
-
-// 7.18.3 Limits of other integer types
-
-#ifdef _WIN64 // [
-# define PTRDIFF_MIN _I64_MIN
-# define PTRDIFF_MAX _I64_MAX
-#else // _WIN64 ][
-# define PTRDIFF_MIN _I32_MIN
-# define PTRDIFF_MAX _I32_MAX
-#endif // _WIN64 ]
-
-#define SIG_ATOMIC_MIN INT_MIN
-#define SIG_ATOMIC_MAX INT_MAX
-
-#ifndef SIZE_MAX // [
-# ifdef _WIN64 // [
-# define SIZE_MAX _UI64_MAX
-# else // _WIN64 ][
-# define SIZE_MAX _UI32_MAX
-# endif // _WIN64 ]
-#endif // SIZE_MAX ]
-
-// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
-#ifndef WCHAR_MIN // [
-# define WCHAR_MIN 0
-#endif // WCHAR_MIN ]
-#ifndef WCHAR_MAX // [
-# define WCHAR_MAX _UI16_MAX
-#endif // WCHAR_MAX ]
-
-#define WINT_MIN 0
-#define WINT_MAX _UI16_MAX
-
-#endif // __STDC_LIMIT_MACROS ]
-
-
-// 7.18.4 Limits of other integer types
-
-#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
-
-// 7.18.4.1 Macros for minimum-width integer constants
-
-#define INT8_C(val) val##i8
-#define INT16_C(val) val##i16
-#define INT32_C(val) val##i32
-#define INT64_C(val) val##i64
-
-#define UINT8_C(val) val##ui8
-#define UINT16_C(val) val##ui16
-#define UINT32_C(val) val##ui32
-#define UINT64_C(val) val##ui64
-
-// 7.18.4.2 Macros for greatest-width integer constants
-#define INTMAX_C INT64_C
-#define UINTMAX_C UINT64_C
-
-#endif // __STDC_CONSTANT_MACROS ]
-
-
-#endif // _MSC_STDINT_H_ ]
diff --git a/memory/jemalloc/src/include/msvc_compat/strings.h b/memory/jemalloc/src/include/msvc_compat/strings.h
deleted file mode 100644
index a3ee25063..000000000
--- a/memory/jemalloc/src/include/msvc_compat/strings.h
+++ /dev/null
@@ -1,59 +0,0 @@
-#ifndef strings_h
-#define strings_h
-
-/* MSVC doesn't define ffs/ffsl. This dummy strings.h header is provided
- * for both */
-#ifdef _MSC_VER
-# include <intrin.h>
-# pragma intrinsic(_BitScanForward)
-static __forceinline int ffsl(long x)
-{
- unsigned long i;
-
- if (_BitScanForward(&i, x))
- return (i + 1);
- return (0);
-}
-
-static __forceinline int ffs(int x)
-{
-
- return (ffsl(x));
-}
-
-# ifdef _M_X64
-# pragma intrinsic(_BitScanForward64)
-# endif
-
-static __forceinline int ffsll(unsigned __int64 x)
-{
- unsigned long i;
-#ifdef _M_X64
- if (_BitScanForward64(&i, x))
- return (i + 1);
- return (0);
-#else
-// Fallback for 32-bit build where 64-bit version not available
-// assuming little endian
- union {
- unsigned __int64 ll;
- unsigned long l[2];
- } s;
-
- s.ll = x;
-
- if (_BitScanForward(&i, s.l[0]))
- return (i + 1);
- else if(_BitScanForward(&i, s.l[1]))
- return (i + 33);
- return (0);
-#endif
-}
-
-#else
-# define ffsll(x) __builtin_ffsll(x)
-# define ffsl(x) __builtin_ffsl(x)
-# define ffs(x) __builtin_ffs(x)
-#endif
-
-#endif /* strings_h */
diff --git a/memory/jemalloc/src/include/msvc_compat/windows_extra.h b/memory/jemalloc/src/include/msvc_compat/windows_extra.h
deleted file mode 100644
index 3008faa37..000000000
--- a/memory/jemalloc/src/include/msvc_compat/windows_extra.h
+++ /dev/null
@@ -1,6 +0,0 @@
-#ifndef MSVC_COMPAT_WINDOWS_EXTRA_H
-#define MSVC_COMPAT_WINDOWS_EXTRA_H
-
-#include <errno.h>
-
-#endif /* MSVC_COMPAT_WINDOWS_EXTRA_H */
diff --git a/memory/jemalloc/src/jemalloc.pc.in b/memory/jemalloc/src/jemalloc.pc.in
deleted file mode 100644
index a318e8dd3..000000000
--- a/memory/jemalloc/src/jemalloc.pc.in
+++ /dev/null
@@ -1,12 +0,0 @@
-prefix=@prefix@
-exec_prefix=@exec_prefix@
-libdir=@libdir@
-includedir=@includedir@
-install_suffix=@install_suffix@
-
-Name: jemalloc
-Description: A general purpose malloc(3) implementation that emphasizes fragmentation avoidance and scalable concurrency support.
-URL: http://jemalloc.net/
-Version: @jemalloc_version@
-Cflags: -I${includedir}
-Libs: -L${libdir} -ljemalloc${install_suffix}
diff --git a/memory/jemalloc/src/msvc/ReadMe.txt b/memory/jemalloc/src/msvc/ReadMe.txt
deleted file mode 100644
index 77d567da0..000000000
--- a/memory/jemalloc/src/msvc/ReadMe.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-
-How to build jemalloc for Windows
-=================================
-
-1. Install Cygwin with at least the following packages:
- * autoconf
- * autogen
- * gawk
- * grep
- * sed
-
-2. Install Visual Studio 2015 with Visual C++
-
-3. Add Cygwin\bin to the PATH environment variable
-
-4. Open "VS2015 x86 Native Tools Command Prompt"
- (note: x86/x64 doesn't matter at this point)
-
-5. Generate header files:
- sh -c "CC=cl ./autogen.sh"
-
-6. Now the project can be opened and built in Visual Studio:
- msvc\jemalloc_vc2015.sln
-
diff --git a/memory/jemalloc/src/msvc/jemalloc_vc2015.sln b/memory/jemalloc/src/msvc/jemalloc_vc2015.sln
deleted file mode 100644
index aedd5e5ea..000000000
--- a/memory/jemalloc/src/msvc/jemalloc_vc2015.sln
+++ /dev/null
@@ -1,63 +0,0 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.24720.0
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{70A99006-6DE9-472B-8F83-4CEE6C616DF3}"
- ProjectSection(SolutionItems) = preProject
- ReadMe.txt = ReadMe.txt
- EndProjectSection
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jemalloc", "projects\vc2015\jemalloc\jemalloc.vcxproj", "{8D6BB292-9E1C-413D-9F98-4864BDC1514A}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "test_threads", "projects\vc2015\test_threads\test_threads.vcxproj", "{09028CFD-4EB7-491D-869C-0708DB97ED44}"
-EndProject
-Global
- GlobalSection(SolutionConfigurationPlatforms) = preSolution
- Debug|x64 = Debug|x64
- Debug|x86 = Debug|x86
- Debug-static|x64 = Debug-static|x64
- Debug-static|x86 = Debug-static|x86
- Release|x64 = Release|x64
- Release|x86 = Release|x86
- Release-static|x64 = Release-static|x64
- Release-static|x86 = Release-static|x86
- EndGlobalSection
- GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Debug|x64.ActiveCfg = Debug|x64
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Debug|x64.Build.0 = Debug|x64
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Debug|x86.ActiveCfg = Debug|Win32
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Debug|x86.Build.0 = Debug|Win32
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Debug-static|x64.ActiveCfg = Debug-static|x64
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Debug-static|x64.Build.0 = Debug-static|x64
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Debug-static|x86.ActiveCfg = Debug-static|Win32
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Debug-static|x86.Build.0 = Debug-static|Win32
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Release|x64.ActiveCfg = Release|x64
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Release|x64.Build.0 = Release|x64
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Release|x86.ActiveCfg = Release|Win32
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Release|x86.Build.0 = Release|Win32
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Release-static|x64.ActiveCfg = Release-static|x64
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Release-static|x64.Build.0 = Release-static|x64
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Release-static|x86.ActiveCfg = Release-static|Win32
- {8D6BB292-9E1C-413D-9F98-4864BDC1514A}.Release-static|x86.Build.0 = Release-static|Win32
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Debug|x64.ActiveCfg = Debug|x64
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Debug|x64.Build.0 = Debug|x64
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Debug|x86.ActiveCfg = Debug|Win32
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Debug|x86.Build.0 = Debug|Win32
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Debug-static|x64.ActiveCfg = Debug-static|x64
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Debug-static|x64.Build.0 = Debug-static|x64
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Debug-static|x86.ActiveCfg = Debug-static|Win32
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Debug-static|x86.Build.0 = Debug-static|Win32
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Release|x64.ActiveCfg = Release|x64
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Release|x64.Build.0 = Release|x64
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Release|x86.ActiveCfg = Release|Win32
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Release|x86.Build.0 = Release|Win32
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Release-static|x64.ActiveCfg = Release-static|x64
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Release-static|x64.Build.0 = Release-static|x64
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Release-static|x86.ActiveCfg = Release-static|Win32
- {09028CFD-4EB7-491D-869C-0708DB97ED44}.Release-static|x86.Build.0 = Release-static|Win32
- EndGlobalSection
- GlobalSection(SolutionProperties) = preSolution
- HideSolutionNode = FALSE
- EndGlobalSection
-EndGlobal
diff --git a/memory/jemalloc/src/msvc/projects/vc2015/jemalloc/jemalloc.vcxproj b/memory/jemalloc/src/msvc/projects/vc2015/jemalloc/jemalloc.vcxproj
deleted file mode 100644
index 8342ab3ab..000000000
--- a/memory/jemalloc/src/msvc/projects/vc2015/jemalloc/jemalloc.vcxproj
+++ /dev/null
@@ -1,402 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <ItemGroup Label="ProjectConfigurations">
- <ProjectConfiguration Include="Debug-static|Win32">
- <Configuration>Debug-static</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug-static|x64">
- <Configuration>Debug-static</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug|Win32">
- <Configuration>Debug</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release-static|Win32">
- <Configuration>Release-static</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release-static|x64">
- <Configuration>Release-static</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|Win32">
- <Configuration>Release</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug|x64">
- <Configuration>Debug</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|x64">
- <Configuration>Release</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- </ItemGroup>
- <ItemGroup>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\arena.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\assert.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\atomic.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\base.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\bitmap.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\chunk.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\chunk_dss.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\chunk_mmap.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ckh.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ctl.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\extent.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\hash.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\huge.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\jemalloc_internal.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\jemalloc_internal_decls.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\jemalloc_internal_defs.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\jemalloc_internal_macros.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\mb.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\mutex.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\nstime.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\pages.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ph.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\private_namespace.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\private_unnamespace.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\prng.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\prof.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\public_namespace.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\public_unnamespace.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ql.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\qr.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\quarantine.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\rb.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\rtree.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\size_classes.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\smoothstep.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\spin.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\stats.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\tcache.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ticker.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\tsd.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\util.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\witness.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_defs.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_macros.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_mangle.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_protos.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_protos_jet.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_rename.h" />
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_typedefs.h" />
- <ClInclude Include="..\..\..\..\include\msvc_compat\C99\stdbool.h" />
- <ClInclude Include="..\..\..\..\include\msvc_compat\C99\stdint.h" />
- <ClInclude Include="..\..\..\..\include\msvc_compat\strings.h" />
- <ClInclude Include="..\..\..\..\include\msvc_compat\windows_extra.h" />
- </ItemGroup>
- <ItemGroup>
- <ClCompile Include="..\..\..\..\src\arena.c" />
- <ClCompile Include="..\..\..\..\src\atomic.c" />
- <ClCompile Include="..\..\..\..\src\base.c" />
- <ClCompile Include="..\..\..\..\src\bitmap.c" />
- <ClCompile Include="..\..\..\..\src\chunk.c" />
- <ClCompile Include="..\..\..\..\src\chunk_dss.c" />
- <ClCompile Include="..\..\..\..\src\chunk_mmap.c" />
- <ClCompile Include="..\..\..\..\src\ckh.c" />
- <ClCompile Include="..\..\..\..\src\ctl.c" />
- <ClCompile Include="..\..\..\..\src\extent.c" />
- <ClCompile Include="..\..\..\..\src\hash.c" />
- <ClCompile Include="..\..\..\..\src\huge.c" />
- <ClCompile Include="..\..\..\..\src\jemalloc.c" />
- <ClCompile Include="..\..\..\..\src\mb.c" />
- <ClCompile Include="..\..\..\..\src\mutex.c" />
- <ClCompile Include="..\..\..\..\src\nstime.c" />
- <ClCompile Include="..\..\..\..\src\pages.c" />
- <ClCompile Include="..\..\..\..\src\prng.c" />
- <ClCompile Include="..\..\..\..\src\prof.c" />
- <ClCompile Include="..\..\..\..\src\quarantine.c" />
- <ClCompile Include="..\..\..\..\src\rtree.c" />
- <ClCompile Include="..\..\..\..\src\spin.c" />
- <ClCompile Include="..\..\..\..\src\stats.c" />
- <ClCompile Include="..\..\..\..\src\tcache.c" />
- <ClCompile Include="..\..\..\..\src\ticker.c" />
- <ClCompile Include="..\..\..\..\src\tsd.c" />
- <ClCompile Include="..\..\..\..\src\util.c" />
- <ClCompile Include="..\..\..\..\src\witness.c" />
- </ItemGroup>
- <PropertyGroup Label="Globals">
- <ProjectGuid>{8D6BB292-9E1C-413D-9F98-4864BDC1514A}</ProjectGuid>
- <Keyword>Win32Proj</Keyword>
- <RootNamespace>jemalloc</RootNamespace>
- <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
- </PropertyGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
- <ConfigurationType>DynamicLibrary</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'" Label="Configuration">
- <ConfigurationType>StaticLibrary</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
- <ConfigurationType>DynamicLibrary</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'" Label="Configuration">
- <ConfigurationType>StaticLibrary</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
- <ConfigurationType>DynamicLibrary</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'" Label="Configuration">
- <ConfigurationType>StaticLibrary</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
- <ConfigurationType>DynamicLibrary</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'" Label="Configuration">
- <ConfigurationType>StaticLibrary</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
- <ImportGroup Label="ExtensionSettings">
- </ImportGroup>
- <ImportGroup Label="Shared">
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <PropertyGroup Label="UserMacros" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <TargetName>$(ProjectName)d</TargetName>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <TargetName>$(ProjectName)-$(PlatformToolset)-$(Configuration)</TargetName>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <TargetName>$(ProjectName)-$(PlatformToolset)-$(Configuration)</TargetName>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <TargetName>$(ProjectName)d</TargetName>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <TargetName>$(ProjectName)-vc$(PlatformToolsetVersion)-$(Configuration)</TargetName>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <TargetName>$(ProjectName)-vc$(PlatformToolsetVersion)-$(Configuration)</TargetName>
- </PropertyGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>_REENTRANT;_WINDLL;DLLEXPORT;JEMALLOC_DEBUG;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
- <ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
- </ClCompile>
- <Link>
- <SubSystem>Windows</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>JEMALLOC_DEBUG;_REENTRANT;JEMALLOC_EXPORT=;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
- <DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
- <ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
- </ClCompile>
- <Link>
- <SubSystem>Windows</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>_REENTRANT;_WINDLL;DLLEXPORT;JEMALLOC_DEBUG;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
- <ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
- </ClCompile>
- <Link>
- <SubSystem>Windows</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>JEMALLOC_DEBUG;_REENTRANT;JEMALLOC_EXPORT=;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
- <DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
- <DebugInformationFormat>OldStyle</DebugInformationFormat>
- <MinimalRebuild>false</MinimalRebuild>
- </ClCompile>
- <Link>
- <SubSystem>Windows</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>_REENTRANT;_WINDLL;DLLEXPORT;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
- <ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
- </ClCompile>
- <Link>
- <SubSystem>Windows</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>_REENTRANT;JEMALLOC_EXPORT=;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
- <DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
- <ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
- </ClCompile>
- <Link>
- <SubSystem>Windows</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <PreprocessorDefinitions>_REENTRANT;_WINDLL;DLLEXPORT;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
- <ProgramDataBaseFileName>$(OutputPath)$(TargetName).pdb</ProgramDataBaseFileName>
- </ClCompile>
- <Link>
- <SubSystem>Windows</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>_REENTRANT;JEMALLOC_EXPORT=;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
- <DisableSpecificWarnings>4090;4146;4267;4334</DisableSpecificWarnings>
- <DebugInformationFormat>OldStyle</DebugInformationFormat>
- </ClCompile>
- <Link>
- <SubSystem>Windows</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- </Link>
- </ItemDefinitionGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
- <ImportGroup Label="ExtensionTargets">
- </ImportGroup>
-</Project> \ No newline at end of file
diff --git a/memory/jemalloc/src/msvc/projects/vc2015/jemalloc/jemalloc.vcxproj.filters b/memory/jemalloc/src/msvc/projects/vc2015/jemalloc/jemalloc.vcxproj.filters
deleted file mode 100644
index 37f0f02ae..000000000
--- a/memory/jemalloc/src/msvc/projects/vc2015/jemalloc/jemalloc.vcxproj.filters
+++ /dev/null
@@ -1,272 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <ItemGroup>
- <Filter Include="Source Files">
- <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
- <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
- </Filter>
- <Filter Include="Header Files">
- <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
- <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
- </Filter>
- <Filter Include="Header Files\internal">
- <UniqueIdentifier>{5697dfa3-16cf-4932-b428-6e0ec6e9f98e}</UniqueIdentifier>
- </Filter>
- <Filter Include="Header Files\msvc_compat">
- <UniqueIdentifier>{0cbd2ca6-42a7-4f82-8517-d7e7a14fd986}</UniqueIdentifier>
- </Filter>
- <Filter Include="Header Files\msvc_compat\C99">
- <UniqueIdentifier>{0abe6f30-49b5-46dd-8aca-6e33363fa52c}</UniqueIdentifier>
- </Filter>
- </ItemGroup>
- <ItemGroup>
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_defs.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_macros.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_mangle.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_protos.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_protos_jet.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_rename.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\jemalloc_typedefs.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\arena.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\assert.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\atomic.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\base.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\bitmap.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\chunk.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\chunk_dss.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\chunk_mmap.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ckh.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ctl.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\extent.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\hash.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\huge.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\jemalloc_internal.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\jemalloc_internal_decls.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\jemalloc_internal_defs.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\jemalloc_internal_macros.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\mb.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\mutex.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\nstime.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\pages.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ph.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\private_namespace.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\private_unnamespace.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\prng.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\prof.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\public_namespace.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\public_unnamespace.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ql.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\qr.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\quarantine.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\rb.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\rtree.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\size_classes.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\smoothstep.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\spin.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\stats.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\tcache.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\ticker.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\tsd.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\util.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\jemalloc\internal\witness.h">
- <Filter>Header Files\internal</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\msvc_compat\strings.h">
- <Filter>Header Files\msvc_compat</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\msvc_compat\windows_extra.h">
- <Filter>Header Files\msvc_compat</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\msvc_compat\C99\stdbool.h">
- <Filter>Header Files\msvc_compat\C99</Filter>
- </ClInclude>
- <ClInclude Include="..\..\..\..\include\msvc_compat\C99\stdint.h">
- <Filter>Header Files\msvc_compat\C99</Filter>
- </ClInclude>
- </ItemGroup>
- <ItemGroup>
- <ClCompile Include="..\..\..\..\src\arena.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\atomic.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\base.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\bitmap.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\chunk.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\chunk_dss.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\chunk_mmap.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\ckh.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\ctl.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\extent.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\hash.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\huge.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\jemalloc.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\mb.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\mutex.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\nstime.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\pages.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\prng.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\prof.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\quarantine.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\rtree.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\spin.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\stats.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\tcache.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\ticker.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\tsd.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\util.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="..\..\..\..\src\witness.c">
- <Filter>Source Files</Filter>
- </ClCompile>
- </ItemGroup>
-</Project>
diff --git a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.cpp b/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.cpp
deleted file mode 100644
index c8cb7d66a..000000000
--- a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-// jemalloc C++ threaded test
-// Author: Rustam Abdullaev
-// Public Domain
-
-#include <atomic>
-#include <functional>
-#include <future>
-#include <random>
-#include <thread>
-#include <vector>
-#include <stdio.h>
-#include <jemalloc/jemalloc.h>
-
-using std::vector;
-using std::thread;
-using std::uniform_int_distribution;
-using std::minstd_rand;
-
-int test_threads()
-{
- je_malloc_conf = "narenas:3";
- int narenas = 0;
- size_t sz = sizeof(narenas);
- je_mallctl("opt.narenas", &narenas, &sz, NULL, 0);
- if (narenas != 3) {
- printf("Error: unexpected number of arenas: %d\n", narenas);
- return 1;
- }
- static const int sizes[] = { 7, 16, 32, 60, 91, 100, 120, 144, 169, 199, 255, 400, 670, 900, 917, 1025, 3333, 5190, 13131, 49192, 99999, 123123, 255265, 2333111 };
- static const int numSizes = (int)(sizeof(sizes) / sizeof(sizes[0]));
- vector<thread> workers;
- static const int numThreads = narenas + 1, numAllocsMax = 25, numIter1 = 50, numIter2 = 50;
- je_malloc_stats_print(NULL, NULL, NULL);
- size_t allocated1;
- size_t sz1 = sizeof(allocated1);
- je_mallctl("stats.active", &allocated1, &sz1, NULL, 0);
- printf("\nPress Enter to start threads...\n");
- getchar();
- printf("Starting %d threads x %d x %d iterations...\n", numThreads, numIter1, numIter2);
- for (int i = 0; i < numThreads; i++) {
- workers.emplace_back([tid=i]() {
- uniform_int_distribution<int> sizeDist(0, numSizes - 1);
- minstd_rand rnd(tid * 17);
- uint8_t* ptrs[numAllocsMax];
- int ptrsz[numAllocsMax];
- for (int i = 0; i < numIter1; ++i) {
- thread t([&]() {
- for (int i = 0; i < numIter2; ++i) {
- const int numAllocs = numAllocsMax - sizeDist(rnd);
- for (int j = 0; j < numAllocs; j += 64) {
- const int x = sizeDist(rnd);
- const int sz = sizes[x];
- ptrsz[j] = sz;
- ptrs[j] = (uint8_t*)je_malloc(sz);
- if (!ptrs[j]) {
- printf("Unable to allocate %d bytes in thread %d, iter %d, alloc %d. %d\n", sz, tid, i, j, x);
- exit(1);
- }
- for (int k = 0; k < sz; k++)
- ptrs[j][k] = tid + k;
- }
- for (int j = 0; j < numAllocs; j += 64) {
- for (int k = 0, sz = ptrsz[j]; k < sz; k++)
- if (ptrs[j][k] != (uint8_t)(tid + k)) {
- printf("Memory error in thread %d, iter %d, alloc %d @ %d : %02X!=%02X\n", tid, i, j, k, ptrs[j][k], (uint8_t)(tid + k));
- exit(1);
- }
- je_free(ptrs[j]);
- }
- }
- });
- t.join();
- }
- });
- }
- for (thread& t : workers) {
- t.join();
- }
- je_malloc_stats_print(NULL, NULL, NULL);
- size_t allocated2;
- je_mallctl("stats.active", &allocated2, &sz1, NULL, 0);
- size_t leaked = allocated2 - allocated1;
- printf("\nDone. Leaked: %zd bytes\n", leaked);
- bool failed = leaked > 65536; // in case C++ runtime allocated something (e.g. iostream locale or facet)
- printf("\nTest %s!\n", (failed ? "FAILED" : "successful"));
- printf("\nPress Enter to continue...\n");
- getchar();
- return failed ? 1 : 0;
-}
diff --git a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.h b/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.h
deleted file mode 100644
index 64d0cdb33..000000000
--- a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.h
+++ /dev/null
@@ -1,3 +0,0 @@
-#pragma once
-
-int test_threads();
diff --git a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.vcxproj b/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.vcxproj
deleted file mode 100644
index f5e9898f2..000000000
--- a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.vcxproj
+++ /dev/null
@@ -1,327 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <ItemGroup Label="ProjectConfigurations">
- <ProjectConfiguration Include="Debug-static|Win32">
- <Configuration>Debug-static</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug-static|x64">
- <Configuration>Debug-static</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug|Win32">
- <Configuration>Debug</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release-static|Win32">
- <Configuration>Release-static</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release-static|x64">
- <Configuration>Release-static</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|Win32">
- <Configuration>Release</Configuration>
- <Platform>Win32</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Debug|x64">
- <Configuration>Debug</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- <ProjectConfiguration Include="Release|x64">
- <Configuration>Release</Configuration>
- <Platform>x64</Platform>
- </ProjectConfiguration>
- </ItemGroup>
- <PropertyGroup Label="Globals">
- <ProjectGuid>{09028CFD-4EB7-491D-869C-0708DB97ED44}</ProjectGuid>
- <Keyword>Win32Proj</Keyword>
- <RootNamespace>test_threads</RootNamespace>
- <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
- </PropertyGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>true</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'" Label="Configuration">
- <ConfigurationType>Application</ConfigurationType>
- <UseDebugLibraries>false</UseDebugLibraries>
- <PlatformToolset>v140</PlatformToolset>
- <WholeProgramOptimization>true</WholeProgramOptimization>
- <CharacterSet>MultiByte</CharacterSet>
- </PropertyGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
- <ImportGroup Label="ExtensionSettings">
- </ImportGroup>
- <ImportGroup Label="Shared">
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'" Label="PropertySheets">
- <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
- </ImportGroup>
- <PropertyGroup Label="UserMacros" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <LinkIncremental>true</LinkIncremental>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <LinkIncremental>true</LinkIncremental>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <LinkIncremental>true</LinkIncremental>
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'">
- <LinkIncremental>true</LinkIncremental>
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <LinkIncremental>false</LinkIncremental>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <LinkIncremental>false</LinkIncremental>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <LinkIncremental>false</LinkIncremental>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'">
- <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
- <IntDir>$(Platform)\$(Configuration)\</IntDir>
- <LinkIncremental>false</LinkIncremental>
- </PropertyGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\test\include;..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <AdditionalLibraryDirectories>$(SolutionDir)$(Platform)\$(Configuration)</AdditionalLibraryDirectories>
- <AdditionalDependencies>jemallocd.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|Win32'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>JEMALLOC_EXPORT=;JEMALLOC_STATIC;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\test\include;..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <AdditionalLibraryDirectories>$(SolutionDir)$(Platform)\$(Configuration)</AdditionalLibraryDirectories>
- <AdditionalDependencies>jemalloc-$(PlatformToolset)-$(Configuration).lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\test\include;..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <AdditionalDependencies>jemallocd.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- <AdditionalLibraryDirectories>$(SolutionDir)$(Platform)\$(Configuration)</AdditionalLibraryDirectories>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug-static|x64'">
- <ClCompile>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <WarningLevel>Level3</WarningLevel>
- <Optimization>Disabled</Optimization>
- <PreprocessorDefinitions>JEMALLOC_EXPORT=;JEMALLOC_STATIC;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\test\include;..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <AdditionalDependencies>jemalloc-vc$(PlatformToolsetVersion)-$(Configuration).lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- <AdditionalLibraryDirectories>$(SolutionDir)$(Platform)\$(Configuration)</AdditionalLibraryDirectories>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\test\include;..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- <AdditionalLibraryDirectories>$(SolutionDir)$(Platform)\$(Configuration)</AdditionalLibraryDirectories>
- <AdditionalDependencies>jemalloc.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|Win32'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>JEMALLOC_EXPORT=;JEMALLOC_STATIC;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\test\include;..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- <AdditionalLibraryDirectories>$(SolutionDir)$(Platform)\$(Configuration)</AdditionalLibraryDirectories>
- <AdditionalDependencies>jemalloc-$(PlatformToolset)-$(Configuration).lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\test\include;..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- <AdditionalLibraryDirectories>$(SolutionDir)$(Platform)\$(Configuration)</AdditionalLibraryDirectories>
- <AdditionalDependencies>jemalloc.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release-static|x64'">
- <ClCompile>
- <WarningLevel>Level3</WarningLevel>
- <PrecompiledHeader>
- </PrecompiledHeader>
- <Optimization>MaxSpeed</Optimization>
- <FunctionLevelLinking>true</FunctionLevelLinking>
- <IntrinsicFunctions>true</IntrinsicFunctions>
- <PreprocessorDefinitions>JEMALLOC_EXPORT=;JEMALLOC_STATIC;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
- <AdditionalIncludeDirectories>..\..\..\..\test\include;..\..\..\..\include;..\..\..\..\include\msvc_compat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
- <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
- </ClCompile>
- <Link>
- <SubSystem>Console</SubSystem>
- <GenerateDebugInformation>true</GenerateDebugInformation>
- <EnableCOMDATFolding>true</EnableCOMDATFolding>
- <OptimizeReferences>true</OptimizeReferences>
- <AdditionalLibraryDirectories>$(SolutionDir)$(Platform)\$(Configuration)</AdditionalLibraryDirectories>
- <AdditionalDependencies>jemalloc-vc$(PlatformToolsetVersion)-$(Configuration).lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)</AdditionalDependencies>
- </Link>
- </ItemDefinitionGroup>
- <ItemGroup>
- <ClCompile Include="test_threads.cpp" />
- <ClCompile Include="test_threads_main.cpp" />
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\jemalloc\jemalloc.vcxproj">
- <Project>{8d6bb292-9e1c-413d-9f98-4864bdc1514a}</Project>
- </ProjectReference>
- </ItemGroup>
- <ItemGroup>
- <ClInclude Include="test_threads.h" />
- </ItemGroup>
- <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
- <ImportGroup Label="ExtensionTargets">
- </ImportGroup>
-</Project> \ No newline at end of file
diff --git a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.vcxproj.filters b/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.vcxproj.filters
deleted file mode 100644
index 4c2334073..000000000
--- a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads.vcxproj.filters
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <ItemGroup>
- <Filter Include="Source Files">
- <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
- <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
- </Filter>
- <Filter Include="Header Files">
- <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
- <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
- </Filter>
- </ItemGroup>
- <ItemGroup>
- <ClCompile Include="test_threads.cpp">
- <Filter>Source Files</Filter>
- </ClCompile>
- <ClCompile Include="test_threads_main.cpp">
- <Filter>Source Files</Filter>
- </ClCompile>
- </ItemGroup>
- <ItemGroup>
- <ClInclude Include="test_threads.h">
- <Filter>Header Files</Filter>
- </ClInclude>
- </ItemGroup>
-</Project> \ No newline at end of file
diff --git a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads_main.cpp b/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads_main.cpp
deleted file mode 100644
index ffd96e6ab..000000000
--- a/memory/jemalloc/src/msvc/projects/vc2015/test_threads/test_threads_main.cpp
+++ /dev/null
@@ -1,12 +0,0 @@
-#include "test_threads.h"
-#include <future>
-#include <functional>
-#include <chrono>
-
-using namespace std::chrono_literals;
-
-int main(int argc, char** argv)
-{
- int rc = test_threads();
- return rc;
-}
diff --git a/memory/jemalloc/src/src/arena.c b/memory/jemalloc/src/src/arena.c
deleted file mode 100644
index e196b1337..000000000
--- a/memory/jemalloc/src/src/arena.c
+++ /dev/null
@@ -1,3781 +0,0 @@
-#define JEMALLOC_ARENA_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Data. */
-
-purge_mode_t opt_purge = PURGE_DEFAULT;
-const char *purge_mode_names[] = {
- "ratio",
- "decay",
- "N/A"
-};
-ssize_t opt_lg_dirty_mult = LG_DIRTY_MULT_DEFAULT;
-static ssize_t lg_dirty_mult_default;
-ssize_t opt_decay_time = DECAY_TIME_DEFAULT;
-static ssize_t decay_time_default;
-
-arena_bin_info_t arena_bin_info[NBINS];
-
-size_t map_bias;
-size_t map_misc_offset;
-size_t arena_maxrun; /* Max run size for arenas. */
-size_t large_maxclass; /* Max large size class. */
-unsigned nlclasses; /* Number of large size classes. */
-unsigned nhclasses; /* Number of huge size classes. */
-
-/******************************************************************************/
-/*
- * Function prototypes for static functions that are referenced prior to
- * definition.
- */
-
-static void arena_chunk_dalloc(tsdn_t *tsdn, arena_t *arena,
- arena_chunk_t *chunk);
-static void arena_purge_to_limit(tsdn_t *tsdn, arena_t *arena,
- size_t ndirty_limit);
-static void arena_run_dalloc(tsdn_t *tsdn, arena_t *arena, arena_run_t *run,
- bool dirty, bool cleaned, bool decommitted);
-static void arena_dalloc_bin_run(tsdn_t *tsdn, arena_t *arena,
- arena_chunk_t *chunk, arena_run_t *run, arena_bin_t *bin);
-static void arena_bin_lower_run(arena_t *arena, arena_chunk_t *chunk,
- arena_run_t *run, arena_bin_t *bin);
-
-/******************************************************************************/
-
-JEMALLOC_INLINE_C size_t
-arena_miscelm_size_get(const arena_chunk_map_misc_t *miscelm)
-{
- arena_chunk_t *chunk;
- size_t pageind, mapbits;
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(miscelm);
- pageind = arena_miscelm_to_pageind(miscelm);
- mapbits = arena_mapbits_get(chunk, pageind);
- return (arena_mapbits_size_decode(mapbits));
-}
-
-JEMALLOC_INLINE_C int
-arena_run_addr_comp(const arena_chunk_map_misc_t *a,
- const arena_chunk_map_misc_t *b)
-{
- uintptr_t a_miscelm = (uintptr_t)a;
- uintptr_t b_miscelm = (uintptr_t)b;
-
- assert(a != NULL);
- assert(b != NULL);
-
- return ((a_miscelm > b_miscelm) - (a_miscelm < b_miscelm));
-}
-
-/* Generate pairing heap functions. */
-ph_gen(static UNUSED, arena_run_heap_, arena_run_heap_t, arena_chunk_map_misc_t,
- ph_link, arena_run_addr_comp)
-
-#ifdef JEMALLOC_JET
-#undef run_quantize_floor
-#define run_quantize_floor JEMALLOC_N(n_run_quantize_floor)
-#endif
-static size_t
-run_quantize_floor(size_t size)
-{
- size_t ret;
- pszind_t pind;
-
- assert(size > 0);
- assert(size <= HUGE_MAXCLASS);
- assert((size & PAGE_MASK) == 0);
-
- assert(size != 0);
- assert(size == PAGE_CEILING(size));
-
- pind = psz2ind(size - large_pad + 1);
- if (pind == 0) {
- /*
- * Avoid underflow. This short-circuit would also do the right
- * thing for all sizes in the range for which there are
- * PAGE-spaced size classes, but it's simplest to just handle
- * the one case that would cause erroneous results.
- */
- return (size);
- }
- ret = pind2sz(pind - 1) + large_pad;
- assert(ret <= size);
- return (ret);
-}
-#ifdef JEMALLOC_JET
-#undef run_quantize_floor
-#define run_quantize_floor JEMALLOC_N(run_quantize_floor)
-run_quantize_t *run_quantize_floor = JEMALLOC_N(n_run_quantize_floor);
-#endif
-
-#ifdef JEMALLOC_JET
-#undef run_quantize_ceil
-#define run_quantize_ceil JEMALLOC_N(n_run_quantize_ceil)
-#endif
-static size_t
-run_quantize_ceil(size_t size)
-{
- size_t ret;
-
- assert(size > 0);
- assert(size <= HUGE_MAXCLASS);
- assert((size & PAGE_MASK) == 0);
-
- ret = run_quantize_floor(size);
- if (ret < size) {
- /*
- * Skip a quantization that may have an adequately large run,
- * because under-sized runs may be mixed in. This only happens
- * when an unusual size is requested, i.e. for aligned
- * allocation, and is just one of several places where linear
- * search would potentially find sufficiently aligned available
- * memory somewhere lower.
- */
- ret = pind2sz(psz2ind(ret - large_pad + 1)) + large_pad;
- }
- return (ret);
-}
-#ifdef JEMALLOC_JET
-#undef run_quantize_ceil
-#define run_quantize_ceil JEMALLOC_N(run_quantize_ceil)
-run_quantize_t *run_quantize_ceil = JEMALLOC_N(n_run_quantize_ceil);
-#endif
-
-static void
-arena_avail_insert(arena_t *arena, arena_chunk_t *chunk, size_t pageind,
- size_t npages)
-{
- pszind_t pind = psz2ind(run_quantize_floor(arena_miscelm_size_get(
- arena_miscelm_get_const(chunk, pageind))));
- assert(npages == (arena_mapbits_unallocated_size_get(chunk, pageind) >>
- LG_PAGE));
- assert((npages << LG_PAGE) < chunksize);
- assert(pind2sz(pind) <= chunksize);
- arena_run_heap_insert(&arena->runs_avail[pind],
- arena_miscelm_get_mutable(chunk, pageind));
-}
-
-static void
-arena_avail_remove(arena_t *arena, arena_chunk_t *chunk, size_t pageind,
- size_t npages)
-{
- pszind_t pind = psz2ind(run_quantize_floor(arena_miscelm_size_get(
- arena_miscelm_get_const(chunk, pageind))));
- assert(npages == (arena_mapbits_unallocated_size_get(chunk, pageind) >>
- LG_PAGE));
- assert((npages << LG_PAGE) < chunksize);
- assert(pind2sz(pind) <= chunksize);
- arena_run_heap_remove(&arena->runs_avail[pind],
- arena_miscelm_get_mutable(chunk, pageind));
-}
-
-static void
-arena_run_dirty_insert(arena_t *arena, arena_chunk_t *chunk, size_t pageind,
- size_t npages)
-{
- arena_chunk_map_misc_t *miscelm = arena_miscelm_get_mutable(chunk,
- pageind);
-
- assert(npages == (arena_mapbits_unallocated_size_get(chunk, pageind) >>
- LG_PAGE));
- assert(arena_mapbits_dirty_get(chunk, pageind) == CHUNK_MAP_DIRTY);
- assert(arena_mapbits_dirty_get(chunk, pageind+npages-1) ==
- CHUNK_MAP_DIRTY);
-
- qr_new(&miscelm->rd, rd_link);
- qr_meld(&arena->runs_dirty, &miscelm->rd, rd_link);
- arena->ndirty += npages;
-}
-
-static void
-arena_run_dirty_remove(arena_t *arena, arena_chunk_t *chunk, size_t pageind,
- size_t npages)
-{
- arena_chunk_map_misc_t *miscelm = arena_miscelm_get_mutable(chunk,
- pageind);
-
- assert(npages == (arena_mapbits_unallocated_size_get(chunk, pageind) >>
- LG_PAGE));
- assert(arena_mapbits_dirty_get(chunk, pageind) == CHUNK_MAP_DIRTY);
- assert(arena_mapbits_dirty_get(chunk, pageind+npages-1) ==
- CHUNK_MAP_DIRTY);
-
- qr_remove(&miscelm->rd, rd_link);
- assert(arena->ndirty >= npages);
- arena->ndirty -= npages;
-}
-
-static size_t
-arena_chunk_dirty_npages(const extent_node_t *node)
-{
-
- return (extent_node_size_get(node) >> LG_PAGE);
-}
-
-void
-arena_chunk_cache_maybe_insert(arena_t *arena, extent_node_t *node, bool cache)
-{
-
- if (cache) {
- extent_node_dirty_linkage_init(node);
- extent_node_dirty_insert(node, &arena->runs_dirty,
- &arena->chunks_cache);
- arena->ndirty += arena_chunk_dirty_npages(node);
- }
-}
-
-void
-arena_chunk_cache_maybe_remove(arena_t *arena, extent_node_t *node, bool dirty)
-{
-
- if (dirty) {
- extent_node_dirty_remove(node);
- assert(arena->ndirty >= arena_chunk_dirty_npages(node));
- arena->ndirty -= arena_chunk_dirty_npages(node);
- }
-}
-
-JEMALLOC_INLINE_C void *
-arena_run_reg_alloc(arena_run_t *run, arena_bin_info_t *bin_info)
-{
- void *ret;
- size_t regind;
- arena_chunk_map_misc_t *miscelm;
- void *rpages;
-
- assert(run->nfree > 0);
- assert(!bitmap_full(run->bitmap, &bin_info->bitmap_info));
-
- regind = (unsigned)bitmap_sfu(run->bitmap, &bin_info->bitmap_info);
- miscelm = arena_run_to_miscelm(run);
- rpages = arena_miscelm_to_rpages(miscelm);
- ret = (void *)((uintptr_t)rpages + (uintptr_t)bin_info->reg0_offset +
- (uintptr_t)(bin_info->reg_interval * regind));
- run->nfree--;
- return (ret);
-}
-
-JEMALLOC_INLINE_C void
-arena_run_reg_dalloc(arena_run_t *run, void *ptr)
-{
- arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
- size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- size_t mapbits = arena_mapbits_get(chunk, pageind);
- szind_t binind = arena_ptr_small_binind_get(ptr, mapbits);
- arena_bin_info_t *bin_info = &arena_bin_info[binind];
- size_t regind = arena_run_regind(run, bin_info, ptr);
-
- assert(run->nfree < bin_info->nregs);
- /* Freeing an interior pointer can cause assertion failure. */
- assert(((uintptr_t)ptr -
- ((uintptr_t)arena_miscelm_to_rpages(arena_run_to_miscelm(run)) +
- (uintptr_t)bin_info->reg0_offset)) %
- (uintptr_t)bin_info->reg_interval == 0);
- assert((uintptr_t)ptr >=
- (uintptr_t)arena_miscelm_to_rpages(arena_run_to_miscelm(run)) +
- (uintptr_t)bin_info->reg0_offset);
- /* Freeing an unallocated pointer can cause assertion failure. */
- assert(bitmap_get(run->bitmap, &bin_info->bitmap_info, regind));
-
- bitmap_unset(run->bitmap, &bin_info->bitmap_info, regind);
- run->nfree++;
-}
-
-JEMALLOC_INLINE_C void
-arena_run_zero(arena_chunk_t *chunk, size_t run_ind, size_t npages)
-{
-
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED((void *)((uintptr_t)chunk +
- (run_ind << LG_PAGE)), (npages << LG_PAGE));
- memset((void *)((uintptr_t)chunk + (run_ind << LG_PAGE)), 0,
- (npages << LG_PAGE));
-}
-
-JEMALLOC_INLINE_C void
-arena_run_page_mark_zeroed(arena_chunk_t *chunk, size_t run_ind)
-{
-
- JEMALLOC_VALGRIND_MAKE_MEM_DEFINED((void *)((uintptr_t)chunk + (run_ind
- << LG_PAGE)), PAGE);
-}
-
-JEMALLOC_INLINE_C void
-arena_run_page_validate_zeroed(arena_chunk_t *chunk, size_t run_ind)
-{
- size_t i;
- UNUSED size_t *p = (size_t *)((uintptr_t)chunk + (run_ind << LG_PAGE));
-
- arena_run_page_mark_zeroed(chunk, run_ind);
- for (i = 0; i < PAGE / sizeof(size_t); i++)
- assert(p[i] == 0);
-}
-
-static void
-arena_nactive_add(arena_t *arena, size_t add_pages)
-{
-
- if (config_stats) {
- size_t cactive_add = CHUNK_CEILING((arena->nactive +
- add_pages) << LG_PAGE) - CHUNK_CEILING(arena->nactive <<
- LG_PAGE);
- if (cactive_add != 0)
- stats_cactive_add(cactive_add);
- }
- arena->nactive += add_pages;
-}
-
-static void
-arena_nactive_sub(arena_t *arena, size_t sub_pages)
-{
-
- if (config_stats) {
- size_t cactive_sub = CHUNK_CEILING(arena->nactive << LG_PAGE) -
- CHUNK_CEILING((arena->nactive - sub_pages) << LG_PAGE);
- if (cactive_sub != 0)
- stats_cactive_sub(cactive_sub);
- }
- arena->nactive -= sub_pages;
-}
-
-static void
-arena_run_split_remove(arena_t *arena, arena_chunk_t *chunk, size_t run_ind,
- size_t flag_dirty, size_t flag_decommitted, size_t need_pages)
-{
- size_t total_pages, rem_pages;
-
- assert(flag_dirty == 0 || flag_decommitted == 0);
-
- total_pages = arena_mapbits_unallocated_size_get(chunk, run_ind) >>
- LG_PAGE;
- assert(arena_mapbits_dirty_get(chunk, run_ind+total_pages-1) ==
- flag_dirty);
- assert(need_pages <= total_pages);
- rem_pages = total_pages - need_pages;
-
- arena_avail_remove(arena, chunk, run_ind, total_pages);
- if (flag_dirty != 0)
- arena_run_dirty_remove(arena, chunk, run_ind, total_pages);
- arena_nactive_add(arena, need_pages);
-
- /* Keep track of trailing unused pages for later use. */
- if (rem_pages > 0) {
- size_t flags = flag_dirty | flag_decommitted;
- size_t flag_unzeroed_mask = (flags == 0) ? CHUNK_MAP_UNZEROED :
- 0;
-
- arena_mapbits_unallocated_set(chunk, run_ind+need_pages,
- (rem_pages << LG_PAGE), flags |
- (arena_mapbits_unzeroed_get(chunk, run_ind+need_pages) &
- flag_unzeroed_mask));
- arena_mapbits_unallocated_set(chunk, run_ind+total_pages-1,
- (rem_pages << LG_PAGE), flags |
- (arena_mapbits_unzeroed_get(chunk, run_ind+total_pages-1) &
- flag_unzeroed_mask));
- if (flag_dirty != 0) {
- arena_run_dirty_insert(arena, chunk, run_ind+need_pages,
- rem_pages);
- }
- arena_avail_insert(arena, chunk, run_ind+need_pages, rem_pages);
- }
-}
-
-static bool
-arena_run_split_large_helper(arena_t *arena, arena_run_t *run, size_t size,
- bool remove, bool zero)
-{
- arena_chunk_t *chunk;
- arena_chunk_map_misc_t *miscelm;
- size_t flag_dirty, flag_decommitted, run_ind, need_pages;
- size_t flag_unzeroed_mask;
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
- miscelm = arena_run_to_miscelm(run);
- run_ind = arena_miscelm_to_pageind(miscelm);
- flag_dirty = arena_mapbits_dirty_get(chunk, run_ind);
- flag_decommitted = arena_mapbits_decommitted_get(chunk, run_ind);
- need_pages = (size >> LG_PAGE);
- assert(need_pages > 0);
-
- if (flag_decommitted != 0 && arena->chunk_hooks.commit(chunk, chunksize,
- run_ind << LG_PAGE, size, arena->ind))
- return (true);
-
- if (remove) {
- arena_run_split_remove(arena, chunk, run_ind, flag_dirty,
- flag_decommitted, need_pages);
- }
-
- if (zero) {
- if (flag_decommitted != 0) {
- /* The run is untouched, and therefore zeroed. */
- JEMALLOC_VALGRIND_MAKE_MEM_DEFINED((void
- *)((uintptr_t)chunk + (run_ind << LG_PAGE)),
- (need_pages << LG_PAGE));
- } else if (flag_dirty != 0) {
- /* The run is dirty, so all pages must be zeroed. */
- arena_run_zero(chunk, run_ind, need_pages);
- } else {
- /*
- * The run is clean, so some pages may be zeroed (i.e.
- * never before touched).
- */
- size_t i;
- for (i = 0; i < need_pages; i++) {
- if (arena_mapbits_unzeroed_get(chunk, run_ind+i)
- != 0)
- arena_run_zero(chunk, run_ind+i, 1);
- else if (config_debug) {
- arena_run_page_validate_zeroed(chunk,
- run_ind+i);
- } else {
- arena_run_page_mark_zeroed(chunk,
- run_ind+i);
- }
- }
- }
- } else {
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED((void *)((uintptr_t)chunk +
- (run_ind << LG_PAGE)), (need_pages << LG_PAGE));
- }
-
- /*
- * Set the last element first, in case the run only contains one page
- * (i.e. both statements set the same element).
- */
- flag_unzeroed_mask = (flag_dirty | flag_decommitted) == 0 ?
- CHUNK_MAP_UNZEROED : 0;
- arena_mapbits_large_set(chunk, run_ind+need_pages-1, 0, flag_dirty |
- (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk,
- run_ind+need_pages-1)));
- arena_mapbits_large_set(chunk, run_ind, size, flag_dirty |
- (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk, run_ind)));
- return (false);
-}
-
-static bool
-arena_run_split_large(arena_t *arena, arena_run_t *run, size_t size, bool zero)
-{
-
- return (arena_run_split_large_helper(arena, run, size, true, zero));
-}
-
-static bool
-arena_run_init_large(arena_t *arena, arena_run_t *run, size_t size, bool zero)
-{
-
- return (arena_run_split_large_helper(arena, run, size, false, zero));
-}
-
-static bool
-arena_run_split_small(arena_t *arena, arena_run_t *run, size_t size,
- szind_t binind)
-{
- arena_chunk_t *chunk;
- arena_chunk_map_misc_t *miscelm;
- size_t flag_dirty, flag_decommitted, run_ind, need_pages, i;
-
- assert(binind != BININD_INVALID);
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
- miscelm = arena_run_to_miscelm(run);
- run_ind = arena_miscelm_to_pageind(miscelm);
- flag_dirty = arena_mapbits_dirty_get(chunk, run_ind);
- flag_decommitted = arena_mapbits_decommitted_get(chunk, run_ind);
- need_pages = (size >> LG_PAGE);
- assert(need_pages > 0);
-
- if (flag_decommitted != 0 && arena->chunk_hooks.commit(chunk, chunksize,
- run_ind << LG_PAGE, size, arena->ind))
- return (true);
-
- arena_run_split_remove(arena, chunk, run_ind, flag_dirty,
- flag_decommitted, need_pages);
-
- for (i = 0; i < need_pages; i++) {
- size_t flag_unzeroed = arena_mapbits_unzeroed_get(chunk,
- run_ind+i);
- arena_mapbits_small_set(chunk, run_ind+i, i, binind,
- flag_unzeroed);
- if (config_debug && flag_dirty == 0 && flag_unzeroed == 0)
- arena_run_page_validate_zeroed(chunk, run_ind+i);
- }
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED((void *)((uintptr_t)chunk +
- (run_ind << LG_PAGE)), (need_pages << LG_PAGE));
- return (false);
-}
-
-static arena_chunk_t *
-arena_chunk_init_spare(arena_t *arena)
-{
- arena_chunk_t *chunk;
-
- assert(arena->spare != NULL);
-
- chunk = arena->spare;
- arena->spare = NULL;
-
- assert(arena_mapbits_allocated_get(chunk, map_bias) == 0);
- assert(arena_mapbits_allocated_get(chunk, chunk_npages-1) == 0);
- assert(arena_mapbits_unallocated_size_get(chunk, map_bias) ==
- arena_maxrun);
- assert(arena_mapbits_unallocated_size_get(chunk, chunk_npages-1) ==
- arena_maxrun);
- assert(arena_mapbits_dirty_get(chunk, map_bias) ==
- arena_mapbits_dirty_get(chunk, chunk_npages-1));
-
- return (chunk);
-}
-
-static bool
-arena_chunk_register(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- bool zero)
-{
-
- /*
- * The extent node notion of "committed" doesn't directly apply to
- * arena chunks. Arbitrarily mark them as committed. The commit state
- * of runs is tracked individually, and upon chunk deallocation the
- * entire chunk is in a consistent commit state.
- */
- extent_node_init(&chunk->node, arena, chunk, chunksize, zero, true);
- extent_node_achunk_set(&chunk->node, true);
- return (chunk_register(tsdn, chunk, &chunk->node));
-}
-
-static arena_chunk_t *
-arena_chunk_alloc_internal_hard(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, bool *zero, bool *commit)
-{
- arena_chunk_t *chunk;
-
- malloc_mutex_unlock(tsdn, &arena->lock);
-
- chunk = (arena_chunk_t *)chunk_alloc_wrapper(tsdn, arena, chunk_hooks,
- NULL, chunksize, chunksize, zero, commit);
- if (chunk != NULL && !*commit) {
- /* Commit header. */
- if (chunk_hooks->commit(chunk, chunksize, 0, map_bias <<
- LG_PAGE, arena->ind)) {
- chunk_dalloc_wrapper(tsdn, arena, chunk_hooks,
- (void *)chunk, chunksize, *zero, *commit);
- chunk = NULL;
- }
- }
- if (chunk != NULL && arena_chunk_register(tsdn, arena, chunk, *zero)) {
- if (!*commit) {
- /* Undo commit of header. */
- chunk_hooks->decommit(chunk, chunksize, 0, map_bias <<
- LG_PAGE, arena->ind);
- }
- chunk_dalloc_wrapper(tsdn, arena, chunk_hooks, (void *)chunk,
- chunksize, *zero, *commit);
- chunk = NULL;
- }
-
- malloc_mutex_lock(tsdn, &arena->lock);
- return (chunk);
-}
-
-static arena_chunk_t *
-arena_chunk_alloc_internal(tsdn_t *tsdn, arena_t *arena, bool *zero,
- bool *commit)
-{
- arena_chunk_t *chunk;
- chunk_hooks_t chunk_hooks = CHUNK_HOOKS_INITIALIZER;
-
- chunk = chunk_alloc_cache(tsdn, arena, &chunk_hooks, NULL, chunksize,
- chunksize, zero, commit, true);
- if (chunk != NULL) {
- if (arena_chunk_register(tsdn, arena, chunk, *zero)) {
- chunk_dalloc_cache(tsdn, arena, &chunk_hooks, chunk,
- chunksize, true);
- return (NULL);
- }
- }
- if (chunk == NULL) {
- chunk = arena_chunk_alloc_internal_hard(tsdn, arena,
- &chunk_hooks, zero, commit);
- }
-
- if (config_stats && chunk != NULL) {
- arena->stats.mapped += chunksize;
- arena->stats.metadata_mapped += (map_bias << LG_PAGE);
- }
-
- return (chunk);
-}
-
-static arena_chunk_t *
-arena_chunk_init_hard(tsdn_t *tsdn, arena_t *arena)
-{
- arena_chunk_t *chunk;
- bool zero, commit;
- size_t flag_unzeroed, flag_decommitted, i;
-
- assert(arena->spare == NULL);
-
- zero = false;
- commit = false;
- chunk = arena_chunk_alloc_internal(tsdn, arena, &zero, &commit);
- if (chunk == NULL)
- return (NULL);
-
- /*
- * Initialize the map to contain one maximal free untouched run. Mark
- * the pages as zeroed if arena_chunk_alloc_internal() returned a zeroed
- * or decommitted chunk.
- */
- flag_unzeroed = (zero || !commit) ? 0 : CHUNK_MAP_UNZEROED;
- flag_decommitted = commit ? 0 : CHUNK_MAP_DECOMMITTED;
- arena_mapbits_unallocated_set(chunk, map_bias, arena_maxrun,
- flag_unzeroed | flag_decommitted);
- /*
- * There is no need to initialize the internal page map entries unless
- * the chunk is not zeroed.
- */
- if (!zero) {
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(
- (void *)arena_bitselm_get_const(chunk, map_bias+1),
- (size_t)((uintptr_t)arena_bitselm_get_const(chunk,
- chunk_npages-1) -
- (uintptr_t)arena_bitselm_get_const(chunk, map_bias+1)));
- for (i = map_bias+1; i < chunk_npages-1; i++)
- arena_mapbits_internal_set(chunk, i, flag_unzeroed);
- } else {
- JEMALLOC_VALGRIND_MAKE_MEM_DEFINED((void
- *)arena_bitselm_get_const(chunk, map_bias+1),
- (size_t)((uintptr_t)arena_bitselm_get_const(chunk,
- chunk_npages-1) -
- (uintptr_t)arena_bitselm_get_const(chunk, map_bias+1)));
- if (config_debug) {
- for (i = map_bias+1; i < chunk_npages-1; i++) {
- assert(arena_mapbits_unzeroed_get(chunk, i) ==
- flag_unzeroed);
- }
- }
- }
- arena_mapbits_unallocated_set(chunk, chunk_npages-1, arena_maxrun,
- flag_unzeroed);
-
- return (chunk);
-}
-
-static arena_chunk_t *
-arena_chunk_alloc(tsdn_t *tsdn, arena_t *arena)
-{
- arena_chunk_t *chunk;
-
- if (arena->spare != NULL)
- chunk = arena_chunk_init_spare(arena);
- else {
- chunk = arena_chunk_init_hard(tsdn, arena);
- if (chunk == NULL)
- return (NULL);
- }
-
- ql_elm_new(&chunk->node, ql_link);
- ql_tail_insert(&arena->achunks, &chunk->node, ql_link);
- arena_avail_insert(arena, chunk, map_bias, chunk_npages-map_bias);
-
- return (chunk);
-}
-
-static void
-arena_chunk_discard(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk)
-{
- bool committed;
- chunk_hooks_t chunk_hooks = CHUNK_HOOKS_INITIALIZER;
-
- chunk_deregister(chunk, &chunk->node);
-
- committed = (arena_mapbits_decommitted_get(chunk, map_bias) == 0);
- if (!committed) {
- /*
- * Decommit the header. Mark the chunk as decommitted even if
- * header decommit fails, since treating a partially committed
- * chunk as committed has a high potential for causing later
- * access of decommitted memory.
- */
- chunk_hooks = chunk_hooks_get(tsdn, arena);
- chunk_hooks.decommit(chunk, chunksize, 0, map_bias << LG_PAGE,
- arena->ind);
- }
-
- chunk_dalloc_cache(tsdn, arena, &chunk_hooks, (void *)chunk, chunksize,
- committed);
-
- if (config_stats) {
- arena->stats.mapped -= chunksize;
- arena->stats.metadata_mapped -= (map_bias << LG_PAGE);
- }
-}
-
-static void
-arena_spare_discard(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *spare)
-{
-
- assert(arena->spare != spare);
-
- if (arena_mapbits_dirty_get(spare, map_bias) != 0) {
- arena_run_dirty_remove(arena, spare, map_bias,
- chunk_npages-map_bias);
- }
-
- arena_chunk_discard(tsdn, arena, spare);
-}
-
-static void
-arena_chunk_dalloc(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk)
-{
- arena_chunk_t *spare;
-
- assert(arena_mapbits_allocated_get(chunk, map_bias) == 0);
- assert(arena_mapbits_allocated_get(chunk, chunk_npages-1) == 0);
- assert(arena_mapbits_unallocated_size_get(chunk, map_bias) ==
- arena_maxrun);
- assert(arena_mapbits_unallocated_size_get(chunk, chunk_npages-1) ==
- arena_maxrun);
- assert(arena_mapbits_dirty_get(chunk, map_bias) ==
- arena_mapbits_dirty_get(chunk, chunk_npages-1));
- assert(arena_mapbits_decommitted_get(chunk, map_bias) ==
- arena_mapbits_decommitted_get(chunk, chunk_npages-1));
-
- /* Remove run from runs_avail, so that the arena does not use it. */
- arena_avail_remove(arena, chunk, map_bias, chunk_npages-map_bias);
-
- ql_remove(&arena->achunks, &chunk->node, ql_link);
- spare = arena->spare;
- arena->spare = chunk;
- if (spare != NULL)
- arena_spare_discard(tsdn, arena, spare);
-}
-
-static void
-arena_huge_malloc_stats_update(arena_t *arena, size_t usize)
-{
- szind_t index = size2index(usize) - nlclasses - NBINS;
-
- cassert(config_stats);
-
- arena->stats.nmalloc_huge++;
- arena->stats.allocated_huge += usize;
- arena->stats.hstats[index].nmalloc++;
- arena->stats.hstats[index].curhchunks++;
-}
-
-static void
-arena_huge_malloc_stats_update_undo(arena_t *arena, size_t usize)
-{
- szind_t index = size2index(usize) - nlclasses - NBINS;
-
- cassert(config_stats);
-
- arena->stats.nmalloc_huge--;
- arena->stats.allocated_huge -= usize;
- arena->stats.hstats[index].nmalloc--;
- arena->stats.hstats[index].curhchunks--;
-}
-
-static void
-arena_huge_dalloc_stats_update(arena_t *arena, size_t usize)
-{
- szind_t index = size2index(usize) - nlclasses - NBINS;
-
- cassert(config_stats);
-
- arena->stats.ndalloc_huge++;
- arena->stats.allocated_huge -= usize;
- arena->stats.hstats[index].ndalloc++;
- arena->stats.hstats[index].curhchunks--;
-}
-
-static void
-arena_huge_reset_stats_cancel(arena_t *arena, size_t usize)
-{
- szind_t index = size2index(usize) - nlclasses - NBINS;
-
- cassert(config_stats);
-
- arena->stats.ndalloc_huge++;
- arena->stats.hstats[index].ndalloc--;
-}
-
-static void
-arena_huge_dalloc_stats_update_undo(arena_t *arena, size_t usize)
-{
- szind_t index = size2index(usize) - nlclasses - NBINS;
-
- cassert(config_stats);
-
- arena->stats.ndalloc_huge--;
- arena->stats.allocated_huge += usize;
- arena->stats.hstats[index].ndalloc--;
- arena->stats.hstats[index].curhchunks++;
-}
-
-static void
-arena_huge_ralloc_stats_update(arena_t *arena, size_t oldsize, size_t usize)
-{
-
- arena_huge_dalloc_stats_update(arena, oldsize);
- arena_huge_malloc_stats_update(arena, usize);
-}
-
-static void
-arena_huge_ralloc_stats_update_undo(arena_t *arena, size_t oldsize,
- size_t usize)
-{
-
- arena_huge_dalloc_stats_update_undo(arena, oldsize);
- arena_huge_malloc_stats_update_undo(arena, usize);
-}
-
-extent_node_t *
-arena_node_alloc(tsdn_t *tsdn, arena_t *arena)
-{
- extent_node_t *node;
-
- malloc_mutex_lock(tsdn, &arena->node_cache_mtx);
- node = ql_last(&arena->node_cache, ql_link);
- if (node == NULL) {
- malloc_mutex_unlock(tsdn, &arena->node_cache_mtx);
- return (base_alloc(tsdn, sizeof(extent_node_t)));
- }
- ql_tail_remove(&arena->node_cache, extent_node_t, ql_link);
- malloc_mutex_unlock(tsdn, &arena->node_cache_mtx);
- return (node);
-}
-
-void
-arena_node_dalloc(tsdn_t *tsdn, arena_t *arena, extent_node_t *node)
-{
-
- malloc_mutex_lock(tsdn, &arena->node_cache_mtx);
- ql_elm_new(node, ql_link);
- ql_tail_insert(&arena->node_cache, node, ql_link);
- malloc_mutex_unlock(tsdn, &arena->node_cache_mtx);
-}
-
-static void *
-arena_chunk_alloc_huge_hard(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, size_t usize, size_t alignment, bool *zero,
- size_t csize)
-{
- void *ret;
- bool commit = true;
-
- ret = chunk_alloc_wrapper(tsdn, arena, chunk_hooks, NULL, csize,
- alignment, zero, &commit);
- if (ret == NULL) {
- /* Revert optimistic stats updates. */
- malloc_mutex_lock(tsdn, &arena->lock);
- if (config_stats) {
- arena_huge_malloc_stats_update_undo(arena, usize);
- arena->stats.mapped -= usize;
- }
- arena_nactive_sub(arena, usize >> LG_PAGE);
- malloc_mutex_unlock(tsdn, &arena->lock);
- }
-
- return (ret);
-}
-
-void *
-arena_chunk_alloc_huge(tsdn_t *tsdn, arena_t *arena, size_t usize,
- size_t alignment, bool *zero)
-{
- void *ret;
- chunk_hooks_t chunk_hooks = CHUNK_HOOKS_INITIALIZER;
- size_t csize = CHUNK_CEILING(usize);
- bool commit = true;
-
- malloc_mutex_lock(tsdn, &arena->lock);
-
- /* Optimistically update stats. */
- if (config_stats) {
- arena_huge_malloc_stats_update(arena, usize);
- arena->stats.mapped += usize;
- }
- arena_nactive_add(arena, usize >> LG_PAGE);
-
- ret = chunk_alloc_cache(tsdn, arena, &chunk_hooks, NULL, csize,
- alignment, zero, &commit, true);
- malloc_mutex_unlock(tsdn, &arena->lock);
- if (ret == NULL) {
- ret = arena_chunk_alloc_huge_hard(tsdn, arena, &chunk_hooks,
- usize, alignment, zero, csize);
- }
-
- return (ret);
-}
-
-void
-arena_chunk_dalloc_huge(tsdn_t *tsdn, arena_t *arena, void *chunk, size_t usize)
-{
- chunk_hooks_t chunk_hooks = CHUNK_HOOKS_INITIALIZER;
- size_t csize;
-
- csize = CHUNK_CEILING(usize);
- malloc_mutex_lock(tsdn, &arena->lock);
- if (config_stats) {
- arena_huge_dalloc_stats_update(arena, usize);
- arena->stats.mapped -= usize;
- }
- arena_nactive_sub(arena, usize >> LG_PAGE);
-
- chunk_dalloc_cache(tsdn, arena, &chunk_hooks, chunk, csize, true);
- malloc_mutex_unlock(tsdn, &arena->lock);
-}
-
-void
-arena_chunk_ralloc_huge_similar(tsdn_t *tsdn, arena_t *arena, void *chunk,
- size_t oldsize, size_t usize)
-{
-
- assert(CHUNK_CEILING(oldsize) == CHUNK_CEILING(usize));
- assert(oldsize != usize);
-
- malloc_mutex_lock(tsdn, &arena->lock);
- if (config_stats)
- arena_huge_ralloc_stats_update(arena, oldsize, usize);
- if (oldsize < usize)
- arena_nactive_add(arena, (usize - oldsize) >> LG_PAGE);
- else
- arena_nactive_sub(arena, (oldsize - usize) >> LG_PAGE);
- malloc_mutex_unlock(tsdn, &arena->lock);
-}
-
-void
-arena_chunk_ralloc_huge_shrink(tsdn_t *tsdn, arena_t *arena, void *chunk,
- size_t oldsize, size_t usize)
-{
- size_t udiff = oldsize - usize;
- size_t cdiff = CHUNK_CEILING(oldsize) - CHUNK_CEILING(usize);
-
- malloc_mutex_lock(tsdn, &arena->lock);
- if (config_stats) {
- arena_huge_ralloc_stats_update(arena, oldsize, usize);
- if (cdiff != 0)
- arena->stats.mapped -= cdiff;
- }
- arena_nactive_sub(arena, udiff >> LG_PAGE);
-
- if (cdiff != 0) {
- chunk_hooks_t chunk_hooks = CHUNK_HOOKS_INITIALIZER;
- void *nchunk = (void *)((uintptr_t)chunk +
- CHUNK_CEILING(usize));
-
- chunk_dalloc_cache(tsdn, arena, &chunk_hooks, nchunk, cdiff,
- true);
- }
- malloc_mutex_unlock(tsdn, &arena->lock);
-}
-
-static bool
-arena_chunk_ralloc_huge_expand_hard(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, void *chunk, size_t oldsize, size_t usize,
- bool *zero, void *nchunk, size_t udiff, size_t cdiff)
-{
- bool err;
- bool commit = true;
-
- err = (chunk_alloc_wrapper(tsdn, arena, chunk_hooks, nchunk, cdiff,
- chunksize, zero, &commit) == NULL);
- if (err) {
- /* Revert optimistic stats updates. */
- malloc_mutex_lock(tsdn, &arena->lock);
- if (config_stats) {
- arena_huge_ralloc_stats_update_undo(arena, oldsize,
- usize);
- arena->stats.mapped -= cdiff;
- }
- arena_nactive_sub(arena, udiff >> LG_PAGE);
- malloc_mutex_unlock(tsdn, &arena->lock);
- } else if (chunk_hooks->merge(chunk, CHUNK_CEILING(oldsize), nchunk,
- cdiff, true, arena->ind)) {
- chunk_dalloc_wrapper(tsdn, arena, chunk_hooks, nchunk, cdiff,
- *zero, true);
- err = true;
- }
- return (err);
-}
-
-bool
-arena_chunk_ralloc_huge_expand(tsdn_t *tsdn, arena_t *arena, void *chunk,
- size_t oldsize, size_t usize, bool *zero)
-{
- bool err;
- chunk_hooks_t chunk_hooks = chunk_hooks_get(tsdn, arena);
- void *nchunk = (void *)((uintptr_t)chunk + CHUNK_CEILING(oldsize));
- size_t udiff = usize - oldsize;
- size_t cdiff = CHUNK_CEILING(usize) - CHUNK_CEILING(oldsize);
- bool commit = true;
-
- malloc_mutex_lock(tsdn, &arena->lock);
-
- /* Optimistically update stats. */
- if (config_stats) {
- arena_huge_ralloc_stats_update(arena, oldsize, usize);
- arena->stats.mapped += cdiff;
- }
- arena_nactive_add(arena, udiff >> LG_PAGE);
-
- err = (chunk_alloc_cache(tsdn, arena, &chunk_hooks, nchunk, cdiff,
- chunksize, zero, &commit, true) == NULL);
- malloc_mutex_unlock(tsdn, &arena->lock);
- if (err) {
- err = arena_chunk_ralloc_huge_expand_hard(tsdn, arena,
- &chunk_hooks, chunk, oldsize, usize, zero, nchunk, udiff,
- cdiff);
- } else if (chunk_hooks.merge(chunk, CHUNK_CEILING(oldsize), nchunk,
- cdiff, true, arena->ind)) {
- chunk_dalloc_wrapper(tsdn, arena, &chunk_hooks, nchunk, cdiff,
- *zero, true);
- err = true;
- }
-
- return (err);
-}
-
-/*
- * Do first-best-fit run selection, i.e. select the lowest run that best fits.
- * Run sizes are indexed, so not all candidate runs are necessarily exactly the
- * same size.
- */
-static arena_run_t *
-arena_run_first_best_fit(arena_t *arena, size_t size)
-{
- pszind_t pind, i;
-
- pind = psz2ind(run_quantize_ceil(size));
-
- for (i = pind; pind2sz(i) <= chunksize; i++) {
- arena_chunk_map_misc_t *miscelm = arena_run_heap_first(
- &arena->runs_avail[i]);
- if (miscelm != NULL)
- return (&miscelm->run);
- }
-
- return (NULL);
-}
-
-static arena_run_t *
-arena_run_alloc_large_helper(arena_t *arena, size_t size, bool zero)
-{
- arena_run_t *run = arena_run_first_best_fit(arena, size);
- if (run != NULL) {
- if (arena_run_split_large(arena, run, size, zero))
- run = NULL;
- }
- return (run);
-}
-
-static arena_run_t *
-arena_run_alloc_large(tsdn_t *tsdn, arena_t *arena, size_t size, bool zero)
-{
- arena_chunk_t *chunk;
- arena_run_t *run;
-
- assert(size <= arena_maxrun);
- assert(size == PAGE_CEILING(size));
-
- /* Search the arena's chunks for the lowest best fit. */
- run = arena_run_alloc_large_helper(arena, size, zero);
- if (run != NULL)
- return (run);
-
- /*
- * No usable runs. Create a new chunk from which to allocate the run.
- */
- chunk = arena_chunk_alloc(tsdn, arena);
- if (chunk != NULL) {
- run = &arena_miscelm_get_mutable(chunk, map_bias)->run;
- if (arena_run_split_large(arena, run, size, zero))
- run = NULL;
- return (run);
- }
-
- /*
- * arena_chunk_alloc() failed, but another thread may have made
- * sufficient memory available while this one dropped arena->lock in
- * arena_chunk_alloc(), so search one more time.
- */
- return (arena_run_alloc_large_helper(arena, size, zero));
-}
-
-static arena_run_t *
-arena_run_alloc_small_helper(arena_t *arena, size_t size, szind_t binind)
-{
- arena_run_t *run = arena_run_first_best_fit(arena, size);
- if (run != NULL) {
- if (arena_run_split_small(arena, run, size, binind))
- run = NULL;
- }
- return (run);
-}
-
-static arena_run_t *
-arena_run_alloc_small(tsdn_t *tsdn, arena_t *arena, size_t size, szind_t binind)
-{
- arena_chunk_t *chunk;
- arena_run_t *run;
-
- assert(size <= arena_maxrun);
- assert(size == PAGE_CEILING(size));
- assert(binind != BININD_INVALID);
-
- /* Search the arena's chunks for the lowest best fit. */
- run = arena_run_alloc_small_helper(arena, size, binind);
- if (run != NULL)
- return (run);
-
- /*
- * No usable runs. Create a new chunk from which to allocate the run.
- */
- chunk = arena_chunk_alloc(tsdn, arena);
- if (chunk != NULL) {
- run = &arena_miscelm_get_mutable(chunk, map_bias)->run;
- if (arena_run_split_small(arena, run, size, binind))
- run = NULL;
- return (run);
- }
-
- /*
- * arena_chunk_alloc() failed, but another thread may have made
- * sufficient memory available while this one dropped arena->lock in
- * arena_chunk_alloc(), so search one more time.
- */
- return (arena_run_alloc_small_helper(arena, size, binind));
-}
-
-static bool
-arena_lg_dirty_mult_valid(ssize_t lg_dirty_mult)
-{
-
- return (lg_dirty_mult >= -1 && lg_dirty_mult < (ssize_t)(sizeof(size_t)
- << 3));
-}
-
-ssize_t
-arena_lg_dirty_mult_get(tsdn_t *tsdn, arena_t *arena)
-{
- ssize_t lg_dirty_mult;
-
- malloc_mutex_lock(tsdn, &arena->lock);
- lg_dirty_mult = arena->lg_dirty_mult;
- malloc_mutex_unlock(tsdn, &arena->lock);
-
- return (lg_dirty_mult);
-}
-
-bool
-arena_lg_dirty_mult_set(tsdn_t *tsdn, arena_t *arena, ssize_t lg_dirty_mult)
-{
-
- if (!arena_lg_dirty_mult_valid(lg_dirty_mult))
- return (true);
-
- malloc_mutex_lock(tsdn, &arena->lock);
- arena->lg_dirty_mult = lg_dirty_mult;
- arena_maybe_purge(tsdn, arena);
- malloc_mutex_unlock(tsdn, &arena->lock);
-
- return (false);
-}
-
-static void
-arena_decay_deadline_init(arena_t *arena)
-{
-
- assert(opt_purge == purge_mode_decay);
-
- /*
- * Generate a new deadline that is uniformly random within the next
- * epoch after the current one.
- */
- nstime_copy(&arena->decay.deadline, &arena->decay.epoch);
- nstime_add(&arena->decay.deadline, &arena->decay.interval);
- if (arena->decay.time > 0) {
- nstime_t jitter;
-
- nstime_init(&jitter, prng_range_u64(&arena->decay.jitter_state,
- nstime_ns(&arena->decay.interval)));
- nstime_add(&arena->decay.deadline, &jitter);
- }
-}
-
-static bool
-arena_decay_deadline_reached(const arena_t *arena, const nstime_t *time)
-{
-
- assert(opt_purge == purge_mode_decay);
-
- return (nstime_compare(&arena->decay.deadline, time) <= 0);
-}
-
-static size_t
-arena_decay_backlog_npages_limit(const arena_t *arena)
-{
- static const uint64_t h_steps[] = {
-#define STEP(step, h, x, y) \
- h,
- SMOOTHSTEP
-#undef STEP
- };
- uint64_t sum;
- size_t npages_limit_backlog;
- unsigned i;
-
- assert(opt_purge == purge_mode_decay);
-
- /*
- * For each element of decay_backlog, multiply by the corresponding
- * fixed-point smoothstep decay factor. Sum the products, then divide
- * to round down to the nearest whole number of pages.
- */
- sum = 0;
- for (i = 0; i < SMOOTHSTEP_NSTEPS; i++)
- sum += arena->decay.backlog[i] * h_steps[i];
- npages_limit_backlog = (size_t)(sum >> SMOOTHSTEP_BFP);
-
- return (npages_limit_backlog);
-}
-
-static void
-arena_decay_backlog_update_last(arena_t *arena)
-{
- size_t ndirty_delta = (arena->ndirty > arena->decay.ndirty) ?
- arena->ndirty - arena->decay.ndirty : 0;
- arena->decay.backlog[SMOOTHSTEP_NSTEPS-1] = ndirty_delta;
-}
-
-static void
-arena_decay_backlog_update(arena_t *arena, uint64_t nadvance_u64)
-{
-
- if (nadvance_u64 >= SMOOTHSTEP_NSTEPS) {
- memset(arena->decay.backlog, 0, (SMOOTHSTEP_NSTEPS-1) *
- sizeof(size_t));
- } else {
- size_t nadvance_z = (size_t)nadvance_u64;
-
- assert((uint64_t)nadvance_z == nadvance_u64);
-
- memmove(arena->decay.backlog, &arena->decay.backlog[nadvance_z],
- (SMOOTHSTEP_NSTEPS - nadvance_z) * sizeof(size_t));
- if (nadvance_z > 1) {
- memset(&arena->decay.backlog[SMOOTHSTEP_NSTEPS -
- nadvance_z], 0, (nadvance_z-1) * sizeof(size_t));
- }
- }
-
- arena_decay_backlog_update_last(arena);
-}
-
-static void
-arena_decay_epoch_advance_helper(arena_t *arena, const nstime_t *time)
-{
- uint64_t nadvance_u64;
- nstime_t delta;
-
- assert(opt_purge == purge_mode_decay);
- assert(arena_decay_deadline_reached(arena, time));
-
- nstime_copy(&delta, time);
- nstime_subtract(&delta, &arena->decay.epoch);
- nadvance_u64 = nstime_divide(&delta, &arena->decay.interval);
- assert(nadvance_u64 > 0);
-
- /* Add nadvance_u64 decay intervals to epoch. */
- nstime_copy(&delta, &arena->decay.interval);
- nstime_imultiply(&delta, nadvance_u64);
- nstime_add(&arena->decay.epoch, &delta);
-
- /* Set a new deadline. */
- arena_decay_deadline_init(arena);
-
- /* Update the backlog. */
- arena_decay_backlog_update(arena, nadvance_u64);
-}
-
-static void
-arena_decay_epoch_advance_purge(tsdn_t *tsdn, arena_t *arena)
-{
- size_t ndirty_limit = arena_decay_backlog_npages_limit(arena);
-
- if (arena->ndirty > ndirty_limit)
- arena_purge_to_limit(tsdn, arena, ndirty_limit);
- arena->decay.ndirty = arena->ndirty;
-}
-
-static void
-arena_decay_epoch_advance(tsdn_t *tsdn, arena_t *arena, const nstime_t *time)
-{
-
- arena_decay_epoch_advance_helper(arena, time);
- arena_decay_epoch_advance_purge(tsdn, arena);
-}
-
-static void
-arena_decay_init(arena_t *arena, ssize_t decay_time)
-{
-
- arena->decay.time = decay_time;
- if (decay_time > 0) {
- nstime_init2(&arena->decay.interval, decay_time, 0);
- nstime_idivide(&arena->decay.interval, SMOOTHSTEP_NSTEPS);
- }
-
- nstime_init(&arena->decay.epoch, 0);
- nstime_update(&arena->decay.epoch);
- arena->decay.jitter_state = (uint64_t)(uintptr_t)arena;
- arena_decay_deadline_init(arena);
- arena->decay.ndirty = arena->ndirty;
- memset(arena->decay.backlog, 0, SMOOTHSTEP_NSTEPS * sizeof(size_t));
-}
-
-static bool
-arena_decay_time_valid(ssize_t decay_time)
-{
-
- if (decay_time < -1)
- return (false);
- if (decay_time == -1 || (uint64_t)decay_time <= NSTIME_SEC_MAX)
- return (true);
- return (false);
-}
-
-ssize_t
-arena_decay_time_get(tsdn_t *tsdn, arena_t *arena)
-{
- ssize_t decay_time;
-
- malloc_mutex_lock(tsdn, &arena->lock);
- decay_time = arena->decay.time;
- malloc_mutex_unlock(tsdn, &arena->lock);
-
- return (decay_time);
-}
-
-bool
-arena_decay_time_set(tsdn_t *tsdn, arena_t *arena, ssize_t decay_time)
-{
-
- if (!arena_decay_time_valid(decay_time))
- return (true);
-
- malloc_mutex_lock(tsdn, &arena->lock);
- /*
- * Restart decay backlog from scratch, which may cause many dirty pages
- * to be immediately purged. It would conceptually be possible to map
- * the old backlog onto the new backlog, but there is no justification
- * for such complexity since decay_time changes are intended to be
- * infrequent, either between the {-1, 0, >0} states, or a one-time
- * arbitrary change during initial arena configuration.
- */
- arena_decay_init(arena, decay_time);
- arena_maybe_purge(tsdn, arena);
- malloc_mutex_unlock(tsdn, &arena->lock);
-
- return (false);
-}
-
-static void
-arena_maybe_purge_ratio(tsdn_t *tsdn, arena_t *arena)
-{
-
- assert(opt_purge == purge_mode_ratio);
-
- /* Don't purge if the option is disabled. */
- if (arena->lg_dirty_mult < 0)
- return;
-
- /*
- * Iterate, since preventing recursive purging could otherwise leave too
- * many dirty pages.
- */
- while (true) {
- size_t threshold = (arena->nactive >> arena->lg_dirty_mult);
- if (threshold < chunk_npages)
- threshold = chunk_npages;
- /*
- * Don't purge unless the number of purgeable pages exceeds the
- * threshold.
- */
- if (arena->ndirty <= threshold)
- return;
- arena_purge_to_limit(tsdn, arena, threshold);
- }
-}
-
-static void
-arena_maybe_purge_decay(tsdn_t *tsdn, arena_t *arena)
-{
- nstime_t time;
-
- assert(opt_purge == purge_mode_decay);
-
- /* Purge all or nothing if the option is disabled. */
- if (arena->decay.time <= 0) {
- if (arena->decay.time == 0)
- arena_purge_to_limit(tsdn, arena, 0);
- return;
- }
-
- nstime_init(&time, 0);
- nstime_update(&time);
- if (unlikely(!nstime_monotonic() && nstime_compare(&arena->decay.epoch,
- &time) > 0)) {
- /*
- * Time went backwards. Move the epoch back in time and
- * generate a new deadline, with the expectation that time
- * typically flows forward for long enough periods of time that
- * epochs complete. Unfortunately, this strategy is susceptible
- * to clock jitter triggering premature epoch advances, but
- * clock jitter estimation and compensation isn't feasible here
- * because calls into this code are event-driven.
- */
- nstime_copy(&arena->decay.epoch, &time);
- arena_decay_deadline_init(arena);
- } else {
- /* Verify that time does not go backwards. */
- assert(nstime_compare(&arena->decay.epoch, &time) <= 0);
- }
-
- /*
- * If the deadline has been reached, advance to the current epoch and
- * purge to the new limit if necessary. Note that dirty pages created
- * during the current epoch are not subject to purge until a future
- * epoch, so as a result purging only happens during epoch advances.
- */
- if (arena_decay_deadline_reached(arena, &time))
- arena_decay_epoch_advance(tsdn, arena, &time);
-}
-
-void
-arena_maybe_purge(tsdn_t *tsdn, arena_t *arena)
-{
-
- /* Don't recursively purge. */
- if (arena->purging)
- return;
-
- if (opt_purge == purge_mode_ratio)
- arena_maybe_purge_ratio(tsdn, arena);
- else
- arena_maybe_purge_decay(tsdn, arena);
-}
-
-static size_t
-arena_dirty_count(arena_t *arena)
-{
- size_t ndirty = 0;
- arena_runs_dirty_link_t *rdelm;
- extent_node_t *chunkselm;
-
- for (rdelm = qr_next(&arena->runs_dirty, rd_link),
- chunkselm = qr_next(&arena->chunks_cache, cc_link);
- rdelm != &arena->runs_dirty; rdelm = qr_next(rdelm, rd_link)) {
- size_t npages;
-
- if (rdelm == &chunkselm->rd) {
- npages = extent_node_size_get(chunkselm) >> LG_PAGE;
- chunkselm = qr_next(chunkselm, cc_link);
- } else {
- arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(
- rdelm);
- arena_chunk_map_misc_t *miscelm =
- arena_rd_to_miscelm(rdelm);
- size_t pageind = arena_miscelm_to_pageind(miscelm);
- assert(arena_mapbits_allocated_get(chunk, pageind) ==
- 0);
- assert(arena_mapbits_large_get(chunk, pageind) == 0);
- assert(arena_mapbits_dirty_get(chunk, pageind) != 0);
- npages = arena_mapbits_unallocated_size_get(chunk,
- pageind) >> LG_PAGE;
- }
- ndirty += npages;
- }
-
- return (ndirty);
-}
-
-static size_t
-arena_stash_dirty(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- size_t ndirty_limit, arena_runs_dirty_link_t *purge_runs_sentinel,
- extent_node_t *purge_chunks_sentinel)
-{
- arena_runs_dirty_link_t *rdelm, *rdelm_next;
- extent_node_t *chunkselm;
- size_t nstashed = 0;
-
- /* Stash runs/chunks according to ndirty_limit. */
- for (rdelm = qr_next(&arena->runs_dirty, rd_link),
- chunkselm = qr_next(&arena->chunks_cache, cc_link);
- rdelm != &arena->runs_dirty; rdelm = rdelm_next) {
- size_t npages;
- rdelm_next = qr_next(rdelm, rd_link);
-
- if (rdelm == &chunkselm->rd) {
- extent_node_t *chunkselm_next;
- bool zero, commit;
- UNUSED void *chunk;
-
- npages = extent_node_size_get(chunkselm) >> LG_PAGE;
- if (opt_purge == purge_mode_decay && arena->ndirty -
- (nstashed + npages) < ndirty_limit)
- break;
-
- chunkselm_next = qr_next(chunkselm, cc_link);
- /*
- * Allocate. chunkselm remains valid due to the
- * dalloc_node=false argument to chunk_alloc_cache().
- */
- zero = false;
- commit = false;
- chunk = chunk_alloc_cache(tsdn, arena, chunk_hooks,
- extent_node_addr_get(chunkselm),
- extent_node_size_get(chunkselm), chunksize, &zero,
- &commit, false);
- assert(chunk == extent_node_addr_get(chunkselm));
- assert(zero == extent_node_zeroed_get(chunkselm));
- extent_node_dirty_insert(chunkselm, purge_runs_sentinel,
- purge_chunks_sentinel);
- assert(npages == (extent_node_size_get(chunkselm) >>
- LG_PAGE));
- chunkselm = chunkselm_next;
- } else {
- arena_chunk_t *chunk =
- (arena_chunk_t *)CHUNK_ADDR2BASE(rdelm);
- arena_chunk_map_misc_t *miscelm =
- arena_rd_to_miscelm(rdelm);
- size_t pageind = arena_miscelm_to_pageind(miscelm);
- arena_run_t *run = &miscelm->run;
- size_t run_size =
- arena_mapbits_unallocated_size_get(chunk, pageind);
-
- npages = run_size >> LG_PAGE;
- if (opt_purge == purge_mode_decay && arena->ndirty -
- (nstashed + npages) < ndirty_limit)
- break;
-
- assert(pageind + npages <= chunk_npages);
- assert(arena_mapbits_dirty_get(chunk, pageind) ==
- arena_mapbits_dirty_get(chunk, pageind+npages-1));
-
- /*
- * If purging the spare chunk's run, make it available
- * prior to allocation.
- */
- if (chunk == arena->spare)
- arena_chunk_alloc(tsdn, arena);
-
- /* Temporarily allocate the free dirty run. */
- arena_run_split_large(arena, run, run_size, false);
- /* Stash. */
- if (false)
- qr_new(rdelm, rd_link); /* Redundant. */
- else {
- assert(qr_next(rdelm, rd_link) == rdelm);
- assert(qr_prev(rdelm, rd_link) == rdelm);
- }
- qr_meld(purge_runs_sentinel, rdelm, rd_link);
- }
-
- nstashed += npages;
- if (opt_purge == purge_mode_ratio && arena->ndirty - nstashed <=
- ndirty_limit)
- break;
- }
-
- return (nstashed);
-}
-
-static size_t
-arena_purge_stashed(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- arena_runs_dirty_link_t *purge_runs_sentinel,
- extent_node_t *purge_chunks_sentinel)
-{
- size_t npurged, nmadvise;
- arena_runs_dirty_link_t *rdelm;
- extent_node_t *chunkselm;
-
- if (config_stats)
- nmadvise = 0;
- npurged = 0;
-
- malloc_mutex_unlock(tsdn, &arena->lock);
- for (rdelm = qr_next(purge_runs_sentinel, rd_link),
- chunkselm = qr_next(purge_chunks_sentinel, cc_link);
- rdelm != purge_runs_sentinel; rdelm = qr_next(rdelm, rd_link)) {
- size_t npages;
-
- if (rdelm == &chunkselm->rd) {
- /*
- * Don't actually purge the chunk here because 1)
- * chunkselm is embedded in the chunk and must remain
- * valid, and 2) we deallocate the chunk in
- * arena_unstash_purged(), where it is destroyed,
- * decommitted, or purged, depending on chunk
- * deallocation policy.
- */
- size_t size = extent_node_size_get(chunkselm);
- npages = size >> LG_PAGE;
- chunkselm = qr_next(chunkselm, cc_link);
- } else {
- size_t pageind, run_size, flag_unzeroed, flags, i;
- bool decommitted;
- arena_chunk_t *chunk =
- (arena_chunk_t *)CHUNK_ADDR2BASE(rdelm);
- arena_chunk_map_misc_t *miscelm =
- arena_rd_to_miscelm(rdelm);
- pageind = arena_miscelm_to_pageind(miscelm);
- run_size = arena_mapbits_large_size_get(chunk, pageind);
- npages = run_size >> LG_PAGE;
-
- assert(pageind + npages <= chunk_npages);
- assert(!arena_mapbits_decommitted_get(chunk, pageind));
- assert(!arena_mapbits_decommitted_get(chunk,
- pageind+npages-1));
- decommitted = !chunk_hooks->decommit(chunk, chunksize,
- pageind << LG_PAGE, npages << LG_PAGE, arena->ind);
- if (decommitted) {
- flag_unzeroed = 0;
- flags = CHUNK_MAP_DECOMMITTED;
- } else {
- flag_unzeroed = chunk_purge_wrapper(tsdn, arena,
- chunk_hooks, chunk, chunksize, pageind <<
- LG_PAGE, run_size) ? CHUNK_MAP_UNZEROED : 0;
- flags = flag_unzeroed;
- }
- arena_mapbits_large_set(chunk, pageind+npages-1, 0,
- flags);
- arena_mapbits_large_set(chunk, pageind, run_size,
- flags);
-
- /*
- * Set the unzeroed flag for internal pages, now that
- * chunk_purge_wrapper() has returned whether the pages
- * were zeroed as a side effect of purging. This chunk
- * map modification is safe even though the arena mutex
- * isn't currently owned by this thread, because the run
- * is marked as allocated, thus protecting it from being
- * modified by any other thread. As long as these
- * writes don't perturb the first and last elements'
- * CHUNK_MAP_ALLOCATED bits, behavior is well defined.
- */
- for (i = 1; i < npages-1; i++) {
- arena_mapbits_internal_set(chunk, pageind+i,
- flag_unzeroed);
- }
- }
-
- npurged += npages;
- if (config_stats)
- nmadvise++;
- }
- malloc_mutex_lock(tsdn, &arena->lock);
-
- if (config_stats) {
- arena->stats.nmadvise += nmadvise;
- arena->stats.purged += npurged;
- }
-
- return (npurged);
-}
-
-static void
-arena_unstash_purged(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- arena_runs_dirty_link_t *purge_runs_sentinel,
- extent_node_t *purge_chunks_sentinel)
-{
- arena_runs_dirty_link_t *rdelm, *rdelm_next;
- extent_node_t *chunkselm;
-
- /* Deallocate chunks/runs. */
- for (rdelm = qr_next(purge_runs_sentinel, rd_link),
- chunkselm = qr_next(purge_chunks_sentinel, cc_link);
- rdelm != purge_runs_sentinel; rdelm = rdelm_next) {
- rdelm_next = qr_next(rdelm, rd_link);
- if (rdelm == &chunkselm->rd) {
- extent_node_t *chunkselm_next = qr_next(chunkselm,
- cc_link);
- void *addr = extent_node_addr_get(chunkselm);
- size_t size = extent_node_size_get(chunkselm);
- bool zeroed = extent_node_zeroed_get(chunkselm);
- bool committed = extent_node_committed_get(chunkselm);
- extent_node_dirty_remove(chunkselm);
- arena_node_dalloc(tsdn, arena, chunkselm);
- chunkselm = chunkselm_next;
- chunk_dalloc_wrapper(tsdn, arena, chunk_hooks, addr,
- size, zeroed, committed);
- } else {
- arena_chunk_t *chunk =
- (arena_chunk_t *)CHUNK_ADDR2BASE(rdelm);
- arena_chunk_map_misc_t *miscelm =
- arena_rd_to_miscelm(rdelm);
- size_t pageind = arena_miscelm_to_pageind(miscelm);
- bool decommitted = (arena_mapbits_decommitted_get(chunk,
- pageind) != 0);
- arena_run_t *run = &miscelm->run;
- qr_remove(rdelm, rd_link);
- arena_run_dalloc(tsdn, arena, run, false, true,
- decommitted);
- }
- }
-}
-
-/*
- * NB: ndirty_limit is interpreted differently depending on opt_purge:
- * - purge_mode_ratio: Purge as few dirty run/chunks as possible to reach the
- * desired state:
- * (arena->ndirty <= ndirty_limit)
- * - purge_mode_decay: Purge as many dirty runs/chunks as possible without
- * violating the invariant:
- * (arena->ndirty >= ndirty_limit)
- */
-static void
-arena_purge_to_limit(tsdn_t *tsdn, arena_t *arena, size_t ndirty_limit)
-{
- chunk_hooks_t chunk_hooks = chunk_hooks_get(tsdn, arena);
- size_t npurge, npurged;
- arena_runs_dirty_link_t purge_runs_sentinel;
- extent_node_t purge_chunks_sentinel;
-
- arena->purging = true;
-
- /*
- * Calls to arena_dirty_count() are disabled even for debug builds
- * because overhead grows nonlinearly as memory usage increases.
- */
- if (false && config_debug) {
- size_t ndirty = arena_dirty_count(arena);
- assert(ndirty == arena->ndirty);
- }
- assert(opt_purge != purge_mode_ratio || (arena->nactive >>
- arena->lg_dirty_mult) < arena->ndirty || ndirty_limit == 0);
-
- qr_new(&purge_runs_sentinel, rd_link);
- extent_node_dirty_linkage_init(&purge_chunks_sentinel);
-
- npurge = arena_stash_dirty(tsdn, arena, &chunk_hooks, ndirty_limit,
- &purge_runs_sentinel, &purge_chunks_sentinel);
- if (npurge == 0)
- goto label_return;
- npurged = arena_purge_stashed(tsdn, arena, &chunk_hooks,
- &purge_runs_sentinel, &purge_chunks_sentinel);
- assert(npurged == npurge);
- arena_unstash_purged(tsdn, arena, &chunk_hooks, &purge_runs_sentinel,
- &purge_chunks_sentinel);
-
- if (config_stats)
- arena->stats.npurge++;
-
-label_return:
- arena->purging = false;
-}
-
-void
-arena_purge(tsdn_t *tsdn, arena_t *arena, bool all)
-{
-
- malloc_mutex_lock(tsdn, &arena->lock);
- if (all)
- arena_purge_to_limit(tsdn, arena, 0);
- else
- arena_maybe_purge(tsdn, arena);
- malloc_mutex_unlock(tsdn, &arena->lock);
-}
-
-static void
-arena_achunk_prof_reset(tsd_t *tsd, arena_t *arena, arena_chunk_t *chunk)
-{
- size_t pageind, npages;
-
- cassert(config_prof);
- assert(opt_prof);
-
- /*
- * Iterate over the allocated runs and remove profiled allocations from
- * the sample set.
- */
- for (pageind = map_bias; pageind < chunk_npages; pageind += npages) {
- if (arena_mapbits_allocated_get(chunk, pageind) != 0) {
- if (arena_mapbits_large_get(chunk, pageind) != 0) {
- void *ptr = (void *)((uintptr_t)chunk + (pageind
- << LG_PAGE));
- size_t usize = isalloc(tsd_tsdn(tsd), ptr,
- config_prof);
-
- prof_free(tsd, ptr, usize);
- npages = arena_mapbits_large_size_get(chunk,
- pageind) >> LG_PAGE;
- } else {
- /* Skip small run. */
- size_t binind = arena_mapbits_binind_get(chunk,
- pageind);
- arena_bin_info_t *bin_info =
- &arena_bin_info[binind];
- npages = bin_info->run_size >> LG_PAGE;
- }
- } else {
- /* Skip unallocated run. */
- npages = arena_mapbits_unallocated_size_get(chunk,
- pageind) >> LG_PAGE;
- }
- assert(pageind + npages <= chunk_npages);
- }
-}
-
-void
-arena_reset(tsd_t *tsd, arena_t *arena)
-{
- unsigned i;
- extent_node_t *node;
-
- /*
- * Locking in this function is unintuitive. The caller guarantees that
- * no concurrent operations are happening in this arena, but there are
- * still reasons that some locking is necessary:
- *
- * - Some of the functions in the transitive closure of calls assume
- * appropriate locks are held, and in some cases these locks are
- * temporarily dropped to avoid lock order reversal or deadlock due to
- * reentry.
- * - mallctl("epoch", ...) may concurrently refresh stats. While
- * strictly speaking this is a "concurrent operation", disallowing
- * stats refreshes would impose an inconvenient burden.
- */
-
- /* Remove large allocations from prof sample set. */
- if (config_prof && opt_prof) {
- ql_foreach(node, &arena->achunks, ql_link) {
- arena_achunk_prof_reset(tsd, arena,
- extent_node_addr_get(node));
- }
- }
-
- /* Reset curruns for large size classes. */
- if (config_stats) {
- for (i = 0; i < nlclasses; i++)
- arena->stats.lstats[i].curruns = 0;
- }
-
- /* Huge allocations. */
- malloc_mutex_lock(tsd_tsdn(tsd), &arena->huge_mtx);
- for (node = ql_last(&arena->huge, ql_link); node != NULL; node =
- ql_last(&arena->huge, ql_link)) {
- void *ptr = extent_node_addr_get(node);
- size_t usize;
-
- malloc_mutex_unlock(tsd_tsdn(tsd), &arena->huge_mtx);
- if (config_stats || (config_prof && opt_prof))
- usize = isalloc(tsd_tsdn(tsd), ptr, config_prof);
- /* Remove huge allocation from prof sample set. */
- if (config_prof && opt_prof)
- prof_free(tsd, ptr, usize);
- huge_dalloc(tsd_tsdn(tsd), ptr);
- malloc_mutex_lock(tsd_tsdn(tsd), &arena->huge_mtx);
- /* Cancel out unwanted effects on stats. */
- if (config_stats)
- arena_huge_reset_stats_cancel(arena, usize);
- }
- malloc_mutex_unlock(tsd_tsdn(tsd), &arena->huge_mtx);
-
- malloc_mutex_lock(tsd_tsdn(tsd), &arena->lock);
-
- /* Bins. */
- for (i = 0; i < NBINS; i++) {
- arena_bin_t *bin = &arena->bins[i];
- malloc_mutex_lock(tsd_tsdn(tsd), &bin->lock);
- bin->runcur = NULL;
- arena_run_heap_new(&bin->runs);
- if (config_stats) {
- bin->stats.curregs = 0;
- bin->stats.curruns = 0;
- }
- malloc_mutex_unlock(tsd_tsdn(tsd), &bin->lock);
- }
-
- /*
- * Re-initialize runs_dirty such that the chunks_cache and runs_dirty
- * chains directly correspond.
- */
- qr_new(&arena->runs_dirty, rd_link);
- for (node = qr_next(&arena->chunks_cache, cc_link);
- node != &arena->chunks_cache; node = qr_next(node, cc_link)) {
- qr_new(&node->rd, rd_link);
- qr_meld(&arena->runs_dirty, &node->rd, rd_link);
- }
-
- /* Arena chunks. */
- for (node = ql_last(&arena->achunks, ql_link); node != NULL; node =
- ql_last(&arena->achunks, ql_link)) {
- ql_remove(&arena->achunks, node, ql_link);
- arena_chunk_discard(tsd_tsdn(tsd), arena,
- extent_node_addr_get(node));
- }
-
- /* Spare. */
- if (arena->spare != NULL) {
- arena_chunk_discard(tsd_tsdn(tsd), arena, arena->spare);
- arena->spare = NULL;
- }
-
- assert(!arena->purging);
- arena->nactive = 0;
-
- for (i = 0; i < NPSIZES; i++)
- arena_run_heap_new(&arena->runs_avail[i]);
-
- malloc_mutex_unlock(tsd_tsdn(tsd), &arena->lock);
-}
-
-static void
-arena_run_coalesce(arena_t *arena, arena_chunk_t *chunk, size_t *p_size,
- size_t *p_run_ind, size_t *p_run_pages, size_t flag_dirty,
- size_t flag_decommitted)
-{
- size_t size = *p_size;
- size_t run_ind = *p_run_ind;
- size_t run_pages = *p_run_pages;
-
- /* Try to coalesce forward. */
- if (run_ind + run_pages < chunk_npages &&
- arena_mapbits_allocated_get(chunk, run_ind+run_pages) == 0 &&
- arena_mapbits_dirty_get(chunk, run_ind+run_pages) == flag_dirty &&
- arena_mapbits_decommitted_get(chunk, run_ind+run_pages) ==
- flag_decommitted) {
- size_t nrun_size = arena_mapbits_unallocated_size_get(chunk,
- run_ind+run_pages);
- size_t nrun_pages = nrun_size >> LG_PAGE;
-
- /*
- * Remove successor from runs_avail; the coalesced run is
- * inserted later.
- */
- assert(arena_mapbits_unallocated_size_get(chunk,
- run_ind+run_pages+nrun_pages-1) == nrun_size);
- assert(arena_mapbits_dirty_get(chunk,
- run_ind+run_pages+nrun_pages-1) == flag_dirty);
- assert(arena_mapbits_decommitted_get(chunk,
- run_ind+run_pages+nrun_pages-1) == flag_decommitted);
- arena_avail_remove(arena, chunk, run_ind+run_pages, nrun_pages);
-
- /*
- * If the successor is dirty, remove it from the set of dirty
- * pages.
- */
- if (flag_dirty != 0) {
- arena_run_dirty_remove(arena, chunk, run_ind+run_pages,
- nrun_pages);
- }
-
- size += nrun_size;
- run_pages += nrun_pages;
-
- arena_mapbits_unallocated_size_set(chunk, run_ind, size);
- arena_mapbits_unallocated_size_set(chunk, run_ind+run_pages-1,
- size);
- }
-
- /* Try to coalesce backward. */
- if (run_ind > map_bias && arena_mapbits_allocated_get(chunk,
- run_ind-1) == 0 && arena_mapbits_dirty_get(chunk, run_ind-1) ==
- flag_dirty && arena_mapbits_decommitted_get(chunk, run_ind-1) ==
- flag_decommitted) {
- size_t prun_size = arena_mapbits_unallocated_size_get(chunk,
- run_ind-1);
- size_t prun_pages = prun_size >> LG_PAGE;
-
- run_ind -= prun_pages;
-
- /*
- * Remove predecessor from runs_avail; the coalesced run is
- * inserted later.
- */
- assert(arena_mapbits_unallocated_size_get(chunk, run_ind) ==
- prun_size);
- assert(arena_mapbits_dirty_get(chunk, run_ind) == flag_dirty);
- assert(arena_mapbits_decommitted_get(chunk, run_ind) ==
- flag_decommitted);
- arena_avail_remove(arena, chunk, run_ind, prun_pages);
-
- /*
- * If the predecessor is dirty, remove it from the set of dirty
- * pages.
- */
- if (flag_dirty != 0) {
- arena_run_dirty_remove(arena, chunk, run_ind,
- prun_pages);
- }
-
- size += prun_size;
- run_pages += prun_pages;
-
- arena_mapbits_unallocated_size_set(chunk, run_ind, size);
- arena_mapbits_unallocated_size_set(chunk, run_ind+run_pages-1,
- size);
- }
-
- *p_size = size;
- *p_run_ind = run_ind;
- *p_run_pages = run_pages;
-}
-
-static size_t
-arena_run_size_get(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run,
- size_t run_ind)
-{
- size_t size;
-
- assert(run_ind >= map_bias);
- assert(run_ind < chunk_npages);
-
- if (arena_mapbits_large_get(chunk, run_ind) != 0) {
- size = arena_mapbits_large_size_get(chunk, run_ind);
- assert(size == PAGE || arena_mapbits_large_size_get(chunk,
- run_ind+(size>>LG_PAGE)-1) == 0);
- } else {
- arena_bin_info_t *bin_info = &arena_bin_info[run->binind];
- size = bin_info->run_size;
- }
-
- return (size);
-}
-
-static void
-arena_run_dalloc(tsdn_t *tsdn, arena_t *arena, arena_run_t *run, bool dirty,
- bool cleaned, bool decommitted)
-{
- arena_chunk_t *chunk;
- arena_chunk_map_misc_t *miscelm;
- size_t size, run_ind, run_pages, flag_dirty, flag_decommitted;
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
- miscelm = arena_run_to_miscelm(run);
- run_ind = arena_miscelm_to_pageind(miscelm);
- assert(run_ind >= map_bias);
- assert(run_ind < chunk_npages);
- size = arena_run_size_get(arena, chunk, run, run_ind);
- run_pages = (size >> LG_PAGE);
- arena_nactive_sub(arena, run_pages);
-
- /*
- * The run is dirty if the caller claims to have dirtied it, as well as
- * if it was already dirty before being allocated and the caller
- * doesn't claim to have cleaned it.
- */
- assert(arena_mapbits_dirty_get(chunk, run_ind) ==
- arena_mapbits_dirty_get(chunk, run_ind+run_pages-1));
- if (!cleaned && !decommitted && arena_mapbits_dirty_get(chunk, run_ind)
- != 0)
- dirty = true;
- flag_dirty = dirty ? CHUNK_MAP_DIRTY : 0;
- flag_decommitted = decommitted ? CHUNK_MAP_DECOMMITTED : 0;
-
- /* Mark pages as unallocated in the chunk map. */
- if (dirty || decommitted) {
- size_t flags = flag_dirty | flag_decommitted;
- arena_mapbits_unallocated_set(chunk, run_ind, size, flags);
- arena_mapbits_unallocated_set(chunk, run_ind+run_pages-1, size,
- flags);
- } else {
- arena_mapbits_unallocated_set(chunk, run_ind, size,
- arena_mapbits_unzeroed_get(chunk, run_ind));
- arena_mapbits_unallocated_set(chunk, run_ind+run_pages-1, size,
- arena_mapbits_unzeroed_get(chunk, run_ind+run_pages-1));
- }
-
- arena_run_coalesce(arena, chunk, &size, &run_ind, &run_pages,
- flag_dirty, flag_decommitted);
-
- /* Insert into runs_avail, now that coalescing is complete. */
- assert(arena_mapbits_unallocated_size_get(chunk, run_ind) ==
- arena_mapbits_unallocated_size_get(chunk, run_ind+run_pages-1));
- assert(arena_mapbits_dirty_get(chunk, run_ind) ==
- arena_mapbits_dirty_get(chunk, run_ind+run_pages-1));
- assert(arena_mapbits_decommitted_get(chunk, run_ind) ==
- arena_mapbits_decommitted_get(chunk, run_ind+run_pages-1));
- arena_avail_insert(arena, chunk, run_ind, run_pages);
-
- if (dirty)
- arena_run_dirty_insert(arena, chunk, run_ind, run_pages);
-
- /* Deallocate chunk if it is now completely unused. */
- if (size == arena_maxrun) {
- assert(run_ind == map_bias);
- assert(run_pages == (arena_maxrun >> LG_PAGE));
- arena_chunk_dalloc(tsdn, arena, chunk);
- }
-
- /*
- * It is okay to do dirty page processing here even if the chunk was
- * deallocated above, since in that case it is the spare. Waiting
- * until after possible chunk deallocation to do dirty processing
- * allows for an old spare to be fully deallocated, thus decreasing the
- * chances of spuriously crossing the dirty page purging threshold.
- */
- if (dirty)
- arena_maybe_purge(tsdn, arena);
-}
-
-static void
-arena_run_trim_head(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- arena_run_t *run, size_t oldsize, size_t newsize)
-{
- arena_chunk_map_misc_t *miscelm = arena_run_to_miscelm(run);
- size_t pageind = arena_miscelm_to_pageind(miscelm);
- size_t head_npages = (oldsize - newsize) >> LG_PAGE;
- size_t flag_dirty = arena_mapbits_dirty_get(chunk, pageind);
- size_t flag_decommitted = arena_mapbits_decommitted_get(chunk, pageind);
- size_t flag_unzeroed_mask = (flag_dirty | flag_decommitted) == 0 ?
- CHUNK_MAP_UNZEROED : 0;
-
- assert(oldsize > newsize);
-
- /*
- * Update the chunk map so that arena_run_dalloc() can treat the
- * leading run as separately allocated. Set the last element of each
- * run first, in case of single-page runs.
- */
- assert(arena_mapbits_large_size_get(chunk, pageind) == oldsize);
- arena_mapbits_large_set(chunk, pageind+head_npages-1, 0, flag_dirty |
- (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk,
- pageind+head_npages-1)));
- arena_mapbits_large_set(chunk, pageind, oldsize-newsize, flag_dirty |
- (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk, pageind)));
-
- if (config_debug) {
- UNUSED size_t tail_npages = newsize >> LG_PAGE;
- assert(arena_mapbits_large_size_get(chunk,
- pageind+head_npages+tail_npages-1) == 0);
- assert(arena_mapbits_dirty_get(chunk,
- pageind+head_npages+tail_npages-1) == flag_dirty);
- }
- arena_mapbits_large_set(chunk, pageind+head_npages, newsize,
- flag_dirty | (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk,
- pageind+head_npages)));
-
- arena_run_dalloc(tsdn, arena, run, false, false, (flag_decommitted !=
- 0));
-}
-
-static void
-arena_run_trim_tail(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- arena_run_t *run, size_t oldsize, size_t newsize, bool dirty)
-{
- arena_chunk_map_misc_t *miscelm = arena_run_to_miscelm(run);
- size_t pageind = arena_miscelm_to_pageind(miscelm);
- size_t head_npages = newsize >> LG_PAGE;
- size_t flag_dirty = arena_mapbits_dirty_get(chunk, pageind);
- size_t flag_decommitted = arena_mapbits_decommitted_get(chunk, pageind);
- size_t flag_unzeroed_mask = (flag_dirty | flag_decommitted) == 0 ?
- CHUNK_MAP_UNZEROED : 0;
- arena_chunk_map_misc_t *tail_miscelm;
- arena_run_t *tail_run;
-
- assert(oldsize > newsize);
-
- /*
- * Update the chunk map so that arena_run_dalloc() can treat the
- * trailing run as separately allocated. Set the last element of each
- * run first, in case of single-page runs.
- */
- assert(arena_mapbits_large_size_get(chunk, pageind) == oldsize);
- arena_mapbits_large_set(chunk, pageind+head_npages-1, 0, flag_dirty |
- (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk,
- pageind+head_npages-1)));
- arena_mapbits_large_set(chunk, pageind, newsize, flag_dirty |
- (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk, pageind)));
-
- if (config_debug) {
- UNUSED size_t tail_npages = (oldsize - newsize) >> LG_PAGE;
- assert(arena_mapbits_large_size_get(chunk,
- pageind+head_npages+tail_npages-1) == 0);
- assert(arena_mapbits_dirty_get(chunk,
- pageind+head_npages+tail_npages-1) == flag_dirty);
- }
- arena_mapbits_large_set(chunk, pageind+head_npages, oldsize-newsize,
- flag_dirty | (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk,
- pageind+head_npages)));
-
- tail_miscelm = arena_miscelm_get_mutable(chunk, pageind + head_npages);
- tail_run = &tail_miscelm->run;
- arena_run_dalloc(tsdn, arena, tail_run, dirty, false, (flag_decommitted
- != 0));
-}
-
-static void
-arena_bin_runs_insert(arena_bin_t *bin, arena_run_t *run)
-{
- arena_chunk_map_misc_t *miscelm = arena_run_to_miscelm(run);
-
- arena_run_heap_insert(&bin->runs, miscelm);
-}
-
-static arena_run_t *
-arena_bin_nonfull_run_tryget(arena_bin_t *bin)
-{
- arena_chunk_map_misc_t *miscelm;
-
- miscelm = arena_run_heap_remove_first(&bin->runs);
- if (miscelm == NULL)
- return (NULL);
- if (config_stats)
- bin->stats.reruns++;
-
- return (&miscelm->run);
-}
-
-static arena_run_t *
-arena_bin_nonfull_run_get(tsdn_t *tsdn, arena_t *arena, arena_bin_t *bin)
-{
- arena_run_t *run;
- szind_t binind;
- arena_bin_info_t *bin_info;
-
- /* Look for a usable run. */
- run = arena_bin_nonfull_run_tryget(bin);
- if (run != NULL)
- return (run);
- /* No existing runs have any space available. */
-
- binind = arena_bin_index(arena, bin);
- bin_info = &arena_bin_info[binind];
-
- /* Allocate a new run. */
- malloc_mutex_unlock(tsdn, &bin->lock);
- /******************************/
- malloc_mutex_lock(tsdn, &arena->lock);
- run = arena_run_alloc_small(tsdn, arena, bin_info->run_size, binind);
- if (run != NULL) {
- /* Initialize run internals. */
- run->binind = binind;
- run->nfree = bin_info->nregs;
- bitmap_init(run->bitmap, &bin_info->bitmap_info);
- }
- malloc_mutex_unlock(tsdn, &arena->lock);
- /********************************/
- malloc_mutex_lock(tsdn, &bin->lock);
- if (run != NULL) {
- if (config_stats) {
- bin->stats.nruns++;
- bin->stats.curruns++;
- }
- return (run);
- }
-
- /*
- * arena_run_alloc_small() failed, but another thread may have made
- * sufficient memory available while this one dropped bin->lock above,
- * so search one more time.
- */
- run = arena_bin_nonfull_run_tryget(bin);
- if (run != NULL)
- return (run);
-
- return (NULL);
-}
-
-/* Re-fill bin->runcur, then call arena_run_reg_alloc(). */
-static void *
-arena_bin_malloc_hard(tsdn_t *tsdn, arena_t *arena, arena_bin_t *bin)
-{
- szind_t binind;
- arena_bin_info_t *bin_info;
- arena_run_t *run;
-
- binind = arena_bin_index(arena, bin);
- bin_info = &arena_bin_info[binind];
- bin->runcur = NULL;
- run = arena_bin_nonfull_run_get(tsdn, arena, bin);
- if (bin->runcur != NULL && bin->runcur->nfree > 0) {
- /*
- * Another thread updated runcur while this one ran without the
- * bin lock in arena_bin_nonfull_run_get().
- */
- void *ret;
- assert(bin->runcur->nfree > 0);
- ret = arena_run_reg_alloc(bin->runcur, bin_info);
- if (run != NULL) {
- arena_chunk_t *chunk;
-
- /*
- * arena_run_alloc_small() may have allocated run, or
- * it may have pulled run from the bin's run tree.
- * Therefore it is unsafe to make any assumptions about
- * how run has previously been used, and
- * arena_bin_lower_run() must be called, as if a region
- * were just deallocated from the run.
- */
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
- if (run->nfree == bin_info->nregs) {
- arena_dalloc_bin_run(tsdn, arena, chunk, run,
- bin);
- } else
- arena_bin_lower_run(arena, chunk, run, bin);
- }
- return (ret);
- }
-
- if (run == NULL)
- return (NULL);
-
- bin->runcur = run;
-
- assert(bin->runcur->nfree > 0);
-
- return (arena_run_reg_alloc(bin->runcur, bin_info));
-}
-
-void
-arena_tcache_fill_small(tsdn_t *tsdn, arena_t *arena, tcache_bin_t *tbin,
- szind_t binind, uint64_t prof_accumbytes)
-{
- unsigned i, nfill;
- arena_bin_t *bin;
-
- assert(tbin->ncached == 0);
-
- if (config_prof && arena_prof_accum(tsdn, arena, prof_accumbytes))
- prof_idump(tsdn);
- bin = &arena->bins[binind];
- malloc_mutex_lock(tsdn, &bin->lock);
- for (i = 0, nfill = (tcache_bin_info[binind].ncached_max >>
- tbin->lg_fill_div); i < nfill; i++) {
- arena_run_t *run;
- void *ptr;
- if ((run = bin->runcur) != NULL && run->nfree > 0)
- ptr = arena_run_reg_alloc(run, &arena_bin_info[binind]);
- else
- ptr = arena_bin_malloc_hard(tsdn, arena, bin);
- if (ptr == NULL) {
- /*
- * OOM. tbin->avail isn't yet filled down to its first
- * element, so the successful allocations (if any) must
- * be moved just before tbin->avail before bailing out.
- */
- if (i > 0) {
- memmove(tbin->avail - i, tbin->avail - nfill,
- i * sizeof(void *));
- }
- break;
- }
- if (config_fill && unlikely(opt_junk_alloc)) {
- arena_alloc_junk_small(ptr, &arena_bin_info[binind],
- true);
- }
- /* Insert such that low regions get used first. */
- *(tbin->avail - nfill + i) = ptr;
- }
- if (config_stats) {
- bin->stats.nmalloc += i;
- bin->stats.nrequests += tbin->tstats.nrequests;
- bin->stats.curregs += i;
- bin->stats.nfills++;
- tbin->tstats.nrequests = 0;
- }
- malloc_mutex_unlock(tsdn, &bin->lock);
- tbin->ncached = i;
- arena_decay_tick(tsdn, arena);
-}
-
-void
-arena_alloc_junk_small(void *ptr, arena_bin_info_t *bin_info, bool zero)
-{
-
- size_t redzone_size = bin_info->redzone_size;
-
- if (zero) {
- memset((void *)((uintptr_t)ptr - redzone_size),
- JEMALLOC_ALLOC_JUNK, redzone_size);
- memset((void *)((uintptr_t)ptr + bin_info->reg_size),
- JEMALLOC_ALLOC_JUNK, redzone_size);
- } else {
- memset((void *)((uintptr_t)ptr - redzone_size),
- JEMALLOC_ALLOC_JUNK, bin_info->reg_interval);
- }
-}
-
-#ifdef JEMALLOC_JET
-#undef arena_redzone_corruption
-#define arena_redzone_corruption JEMALLOC_N(n_arena_redzone_corruption)
-#endif
-static void
-arena_redzone_corruption(void *ptr, size_t usize, bool after,
- size_t offset, uint8_t byte)
-{
-
- malloc_printf("<jemalloc>: Corrupt redzone %zu byte%s %s %p "
- "(size %zu), byte=%#x\n", offset, (offset == 1) ? "" : "s",
- after ? "after" : "before", ptr, usize, byte);
-}
-#ifdef JEMALLOC_JET
-#undef arena_redzone_corruption
-#define arena_redzone_corruption JEMALLOC_N(arena_redzone_corruption)
-arena_redzone_corruption_t *arena_redzone_corruption =
- JEMALLOC_N(n_arena_redzone_corruption);
-#endif
-
-static void
-arena_redzones_validate(void *ptr, arena_bin_info_t *bin_info, bool reset)
-{
- bool error = false;
-
- if (opt_junk_alloc) {
- size_t size = bin_info->reg_size;
- size_t redzone_size = bin_info->redzone_size;
- size_t i;
-
- for (i = 1; i <= redzone_size; i++) {
- uint8_t *byte = (uint8_t *)((uintptr_t)ptr - i);
- if (*byte != JEMALLOC_ALLOC_JUNK) {
- error = true;
- arena_redzone_corruption(ptr, size, false, i,
- *byte);
- if (reset)
- *byte = JEMALLOC_ALLOC_JUNK;
- }
- }
- for (i = 0; i < redzone_size; i++) {
- uint8_t *byte = (uint8_t *)((uintptr_t)ptr + size + i);
- if (*byte != JEMALLOC_ALLOC_JUNK) {
- error = true;
- arena_redzone_corruption(ptr, size, true, i,
- *byte);
- if (reset)
- *byte = JEMALLOC_ALLOC_JUNK;
- }
- }
- }
-
- if (opt_abort && error)
- abort();
-}
-
-#ifdef JEMALLOC_JET
-#undef arena_dalloc_junk_small
-#define arena_dalloc_junk_small JEMALLOC_N(n_arena_dalloc_junk_small)
-#endif
-void
-arena_dalloc_junk_small(void *ptr, arena_bin_info_t *bin_info)
-{
- size_t redzone_size = bin_info->redzone_size;
-
- arena_redzones_validate(ptr, bin_info, false);
- memset((void *)((uintptr_t)ptr - redzone_size), JEMALLOC_FREE_JUNK,
- bin_info->reg_interval);
-}
-#ifdef JEMALLOC_JET
-#undef arena_dalloc_junk_small
-#define arena_dalloc_junk_small JEMALLOC_N(arena_dalloc_junk_small)
-arena_dalloc_junk_small_t *arena_dalloc_junk_small =
- JEMALLOC_N(n_arena_dalloc_junk_small);
-#endif
-
-void
-arena_quarantine_junk_small(void *ptr, size_t usize)
-{
- szind_t binind;
- arena_bin_info_t *bin_info;
- cassert(config_fill);
- assert(opt_junk_free);
- assert(opt_quarantine);
- assert(usize <= SMALL_MAXCLASS);
-
- binind = size2index(usize);
- bin_info = &arena_bin_info[binind];
- arena_redzones_validate(ptr, bin_info, true);
-}
-
-static void *
-arena_malloc_small(tsdn_t *tsdn, arena_t *arena, szind_t binind, bool zero)
-{
- void *ret;
- arena_bin_t *bin;
- size_t usize;
- arena_run_t *run;
-
- assert(binind < NBINS);
- bin = &arena->bins[binind];
- usize = index2size(binind);
-
- malloc_mutex_lock(tsdn, &bin->lock);
- if ((run = bin->runcur) != NULL && run->nfree > 0)
- ret = arena_run_reg_alloc(run, &arena_bin_info[binind]);
- else
- ret = arena_bin_malloc_hard(tsdn, arena, bin);
-
- if (ret == NULL) {
- malloc_mutex_unlock(tsdn, &bin->lock);
- return (NULL);
- }
-
- if (config_stats) {
- bin->stats.nmalloc++;
- bin->stats.nrequests++;
- bin->stats.curregs++;
- }
- malloc_mutex_unlock(tsdn, &bin->lock);
- if (config_prof && !isthreaded && arena_prof_accum(tsdn, arena, usize))
- prof_idump(tsdn);
-
- if (!zero) {
- if (config_fill) {
- if (unlikely(opt_junk_alloc)) {
- arena_alloc_junk_small(ret,
- &arena_bin_info[binind], false);
- } else if (unlikely(opt_zero))
- memset(ret, 0, usize);
- }
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ret, usize);
- } else {
- if (config_fill && unlikely(opt_junk_alloc)) {
- arena_alloc_junk_small(ret, &arena_bin_info[binind],
- true);
- }
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ret, usize);
- memset(ret, 0, usize);
- }
-
- arena_decay_tick(tsdn, arena);
- return (ret);
-}
-
-void *
-arena_malloc_large(tsdn_t *tsdn, arena_t *arena, szind_t binind, bool zero)
-{
- void *ret;
- size_t usize;
- uintptr_t random_offset;
- arena_run_t *run;
- arena_chunk_map_misc_t *miscelm;
- UNUSED bool idump JEMALLOC_CC_SILENCE_INIT(false);
-
- /* Large allocation. */
- usize = index2size(binind);
- malloc_mutex_lock(tsdn, &arena->lock);
- if (config_cache_oblivious) {
- uint64_t r;
-
- /*
- * Compute a uniformly distributed offset within the first page
- * that is a multiple of the cacheline size, e.g. [0 .. 63) * 64
- * for 4 KiB pages and 64-byte cachelines.
- */
- r = prng_lg_range_zu(&arena->offset_state, LG_PAGE -
- LG_CACHELINE, false);
- random_offset = ((uintptr_t)r) << LG_CACHELINE;
- } else
- random_offset = 0;
- run = arena_run_alloc_large(tsdn, arena, usize + large_pad, zero);
- if (run == NULL) {
- malloc_mutex_unlock(tsdn, &arena->lock);
- return (NULL);
- }
- miscelm = arena_run_to_miscelm(run);
- ret = (void *)((uintptr_t)arena_miscelm_to_rpages(miscelm) +
- random_offset);
- if (config_stats) {
- szind_t index = binind - NBINS;
-
- arena->stats.nmalloc_large++;
- arena->stats.nrequests_large++;
- arena->stats.allocated_large += usize;
- arena->stats.lstats[index].nmalloc++;
- arena->stats.lstats[index].nrequests++;
- arena->stats.lstats[index].curruns++;
- }
- if (config_prof)
- idump = arena_prof_accum_locked(arena, usize);
- malloc_mutex_unlock(tsdn, &arena->lock);
- if (config_prof && idump)
- prof_idump(tsdn);
-
- if (!zero) {
- if (config_fill) {
- if (unlikely(opt_junk_alloc))
- memset(ret, JEMALLOC_ALLOC_JUNK, usize);
- else if (unlikely(opt_zero))
- memset(ret, 0, usize);
- }
- }
-
- arena_decay_tick(tsdn, arena);
- return (ret);
-}
-
-void *
-arena_malloc_hard(tsdn_t *tsdn, arena_t *arena, size_t size, szind_t ind,
- bool zero)
-{
-
- assert(!tsdn_null(tsdn) || arena != NULL);
-
- if (likely(!tsdn_null(tsdn)))
- arena = arena_choose(tsdn_tsd(tsdn), arena);
- if (unlikely(arena == NULL))
- return (NULL);
-
- if (likely(size <= SMALL_MAXCLASS))
- return (arena_malloc_small(tsdn, arena, ind, zero));
- if (likely(size <= large_maxclass))
- return (arena_malloc_large(tsdn, arena, ind, zero));
- return (huge_malloc(tsdn, arena, index2size(ind), zero));
-}
-
-/* Only handles large allocations that require more than page alignment. */
-static void *
-arena_palloc_large(tsdn_t *tsdn, arena_t *arena, size_t usize, size_t alignment,
- bool zero)
-{
- void *ret;
- size_t alloc_size, leadsize, trailsize;
- arena_run_t *run;
- arena_chunk_t *chunk;
- arena_chunk_map_misc_t *miscelm;
- void *rpages;
-
- assert(!tsdn_null(tsdn) || arena != NULL);
- assert(usize == PAGE_CEILING(usize));
-
- if (likely(!tsdn_null(tsdn)))
- arena = arena_choose(tsdn_tsd(tsdn), arena);
- if (unlikely(arena == NULL))
- return (NULL);
-
- alignment = PAGE_CEILING(alignment);
- alloc_size = usize + large_pad + alignment - PAGE;
-
- malloc_mutex_lock(tsdn, &arena->lock);
- run = arena_run_alloc_large(tsdn, arena, alloc_size, false);
- if (run == NULL) {
- malloc_mutex_unlock(tsdn, &arena->lock);
- return (NULL);
- }
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(run);
- miscelm = arena_run_to_miscelm(run);
- rpages = arena_miscelm_to_rpages(miscelm);
-
- leadsize = ALIGNMENT_CEILING((uintptr_t)rpages, alignment) -
- (uintptr_t)rpages;
- assert(alloc_size >= leadsize + usize);
- trailsize = alloc_size - leadsize - usize - large_pad;
- if (leadsize != 0) {
- arena_chunk_map_misc_t *head_miscelm = miscelm;
- arena_run_t *head_run = run;
-
- miscelm = arena_miscelm_get_mutable(chunk,
- arena_miscelm_to_pageind(head_miscelm) + (leadsize >>
- LG_PAGE));
- run = &miscelm->run;
-
- arena_run_trim_head(tsdn, arena, chunk, head_run, alloc_size,
- alloc_size - leadsize);
- }
- if (trailsize != 0) {
- arena_run_trim_tail(tsdn, arena, chunk, run, usize + large_pad +
- trailsize, usize + large_pad, false);
- }
- if (arena_run_init_large(arena, run, usize + large_pad, zero)) {
- size_t run_ind =
- arena_miscelm_to_pageind(arena_run_to_miscelm(run));
- bool dirty = (arena_mapbits_dirty_get(chunk, run_ind) != 0);
- bool decommitted = (arena_mapbits_decommitted_get(chunk,
- run_ind) != 0);
-
- assert(decommitted); /* Cause of OOM. */
- arena_run_dalloc(tsdn, arena, run, dirty, false, decommitted);
- malloc_mutex_unlock(tsdn, &arena->lock);
- return (NULL);
- }
- ret = arena_miscelm_to_rpages(miscelm);
-
- if (config_stats) {
- szind_t index = size2index(usize) - NBINS;
-
- arena->stats.nmalloc_large++;
- arena->stats.nrequests_large++;
- arena->stats.allocated_large += usize;
- arena->stats.lstats[index].nmalloc++;
- arena->stats.lstats[index].nrequests++;
- arena->stats.lstats[index].curruns++;
- }
- malloc_mutex_unlock(tsdn, &arena->lock);
-
- if (config_fill && !zero) {
- if (unlikely(opt_junk_alloc))
- memset(ret, JEMALLOC_ALLOC_JUNK, usize);
- else if (unlikely(opt_zero))
- memset(ret, 0, usize);
- }
- arena_decay_tick(tsdn, arena);
- return (ret);
-}
-
-void *
-arena_palloc(tsdn_t *tsdn, arena_t *arena, size_t usize, size_t alignment,
- bool zero, tcache_t *tcache)
-{
- void *ret;
-
- if (usize <= SMALL_MAXCLASS && (alignment < PAGE || (alignment == PAGE
- && (usize & PAGE_MASK) == 0))) {
- /* Small; alignment doesn't require special run placement. */
- ret = arena_malloc(tsdn, arena, usize, size2index(usize), zero,
- tcache, true);
- } else if (usize <= large_maxclass && alignment <= PAGE) {
- /*
- * Large; alignment doesn't require special run placement.
- * However, the cached pointer may be at a random offset from
- * the base of the run, so do some bit manipulation to retrieve
- * the base.
- */
- ret = arena_malloc(tsdn, arena, usize, size2index(usize), zero,
- tcache, true);
- if (config_cache_oblivious)
- ret = (void *)((uintptr_t)ret & ~PAGE_MASK);
- } else {
- if (likely(usize <= large_maxclass)) {
- ret = arena_palloc_large(tsdn, arena, usize, alignment,
- zero);
- } else if (likely(alignment <= chunksize))
- ret = huge_malloc(tsdn, arena, usize, zero);
- else {
- ret = huge_palloc(tsdn, arena, usize, alignment, zero);
- }
- }
- return (ret);
-}
-
-void
-arena_prof_promoted(tsdn_t *tsdn, const void *ptr, size_t size)
-{
- arena_chunk_t *chunk;
- size_t pageind;
- szind_t binind;
-
- cassert(config_prof);
- assert(ptr != NULL);
- assert(CHUNK_ADDR2BASE(ptr) != ptr);
- assert(isalloc(tsdn, ptr, false) == LARGE_MINCLASS);
- assert(isalloc(tsdn, ptr, true) == LARGE_MINCLASS);
- assert(size <= SMALL_MAXCLASS);
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- binind = size2index(size);
- assert(binind < NBINS);
- arena_mapbits_large_binind_set(chunk, pageind, binind);
-
- assert(isalloc(tsdn, ptr, false) == LARGE_MINCLASS);
- assert(isalloc(tsdn, ptr, true) == size);
-}
-
-static void
-arena_dissociate_bin_run(arena_chunk_t *chunk, arena_run_t *run,
- arena_bin_t *bin)
-{
-
- /* Dissociate run from bin. */
- if (run == bin->runcur)
- bin->runcur = NULL;
- else {
- szind_t binind = arena_bin_index(extent_node_arena_get(
- &chunk->node), bin);
- arena_bin_info_t *bin_info = &arena_bin_info[binind];
-
- /*
- * The following block's conditional is necessary because if the
- * run only contains one region, then it never gets inserted
- * into the non-full runs tree.
- */
- if (bin_info->nregs != 1) {
- arena_chunk_map_misc_t *miscelm =
- arena_run_to_miscelm(run);
-
- arena_run_heap_remove(&bin->runs, miscelm);
- }
- }
-}
-
-static void
-arena_dalloc_bin_run(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- arena_run_t *run, arena_bin_t *bin)
-{
-
- assert(run != bin->runcur);
-
- malloc_mutex_unlock(tsdn, &bin->lock);
- /******************************/
- malloc_mutex_lock(tsdn, &arena->lock);
- arena_run_dalloc(tsdn, arena, run, true, false, false);
- malloc_mutex_unlock(tsdn, &arena->lock);
- /****************************/
- malloc_mutex_lock(tsdn, &bin->lock);
- if (config_stats)
- bin->stats.curruns--;
-}
-
-static void
-arena_bin_lower_run(arena_t *arena, arena_chunk_t *chunk, arena_run_t *run,
- arena_bin_t *bin)
-{
-
- /*
- * Make sure that if bin->runcur is non-NULL, it refers to the lowest
- * non-full run. It is okay to NULL runcur out rather than proactively
- * keeping it pointing at the lowest non-full run.
- */
- if ((uintptr_t)run < (uintptr_t)bin->runcur) {
- /* Switch runcur. */
- if (bin->runcur->nfree > 0)
- arena_bin_runs_insert(bin, bin->runcur);
- bin->runcur = run;
- if (config_stats)
- bin->stats.reruns++;
- } else
- arena_bin_runs_insert(bin, run);
-}
-
-static void
-arena_dalloc_bin_locked_impl(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- void *ptr, arena_chunk_map_bits_t *bitselm, bool junked)
-{
- size_t pageind, rpages_ind;
- arena_run_t *run;
- arena_bin_t *bin;
- arena_bin_info_t *bin_info;
- szind_t binind;
-
- pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- rpages_ind = pageind - arena_mapbits_small_runind_get(chunk, pageind);
- run = &arena_miscelm_get_mutable(chunk, rpages_ind)->run;
- binind = run->binind;
- bin = &arena->bins[binind];
- bin_info = &arena_bin_info[binind];
-
- if (!junked && config_fill && unlikely(opt_junk_free))
- arena_dalloc_junk_small(ptr, bin_info);
-
- arena_run_reg_dalloc(run, ptr);
- if (run->nfree == bin_info->nregs) {
- arena_dissociate_bin_run(chunk, run, bin);
- arena_dalloc_bin_run(tsdn, arena, chunk, run, bin);
- } else if (run->nfree == 1 && run != bin->runcur)
- arena_bin_lower_run(arena, chunk, run, bin);
-
- if (config_stats) {
- bin->stats.ndalloc++;
- bin->stats.curregs--;
- }
-}
-
-void
-arena_dalloc_bin_junked_locked(tsdn_t *tsdn, arena_t *arena,
- arena_chunk_t *chunk, void *ptr, arena_chunk_map_bits_t *bitselm)
-{
-
- arena_dalloc_bin_locked_impl(tsdn, arena, chunk, ptr, bitselm, true);
-}
-
-void
-arena_dalloc_bin(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk, void *ptr,
- size_t pageind, arena_chunk_map_bits_t *bitselm)
-{
- arena_run_t *run;
- arena_bin_t *bin;
- size_t rpages_ind;
-
- rpages_ind = pageind - arena_mapbits_small_runind_get(chunk, pageind);
- run = &arena_miscelm_get_mutable(chunk, rpages_ind)->run;
- bin = &arena->bins[run->binind];
- malloc_mutex_lock(tsdn, &bin->lock);
- arena_dalloc_bin_locked_impl(tsdn, arena, chunk, ptr, bitselm, false);
- malloc_mutex_unlock(tsdn, &bin->lock);
-}
-
-void
-arena_dalloc_small(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- void *ptr, size_t pageind)
-{
- arena_chunk_map_bits_t *bitselm;
-
- if (config_debug) {
- /* arena_ptr_small_binind_get() does extra sanity checking. */
- assert(arena_ptr_small_binind_get(ptr, arena_mapbits_get(chunk,
- pageind)) != BININD_INVALID);
- }
- bitselm = arena_bitselm_get_mutable(chunk, pageind);
- arena_dalloc_bin(tsdn, arena, chunk, ptr, pageind, bitselm);
- arena_decay_tick(tsdn, arena);
-}
-
-#ifdef JEMALLOC_JET
-#undef arena_dalloc_junk_large
-#define arena_dalloc_junk_large JEMALLOC_N(n_arena_dalloc_junk_large)
-#endif
-void
-arena_dalloc_junk_large(void *ptr, size_t usize)
-{
-
- if (config_fill && unlikely(opt_junk_free))
- memset(ptr, JEMALLOC_FREE_JUNK, usize);
-}
-#ifdef JEMALLOC_JET
-#undef arena_dalloc_junk_large
-#define arena_dalloc_junk_large JEMALLOC_N(arena_dalloc_junk_large)
-arena_dalloc_junk_large_t *arena_dalloc_junk_large =
- JEMALLOC_N(n_arena_dalloc_junk_large);
-#endif
-
-static void
-arena_dalloc_large_locked_impl(tsdn_t *tsdn, arena_t *arena,
- arena_chunk_t *chunk, void *ptr, bool junked)
-{
- size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- arena_chunk_map_misc_t *miscelm = arena_miscelm_get_mutable(chunk,
- pageind);
- arena_run_t *run = &miscelm->run;
-
- if (config_fill || config_stats) {
- size_t usize = arena_mapbits_large_size_get(chunk, pageind) -
- large_pad;
-
- if (!junked)
- arena_dalloc_junk_large(ptr, usize);
- if (config_stats) {
- szind_t index = size2index(usize) - NBINS;
-
- arena->stats.ndalloc_large++;
- arena->stats.allocated_large -= usize;
- arena->stats.lstats[index].ndalloc++;
- arena->stats.lstats[index].curruns--;
- }
- }
-
- arena_run_dalloc(tsdn, arena, run, true, false, false);
-}
-
-void
-arena_dalloc_large_junked_locked(tsdn_t *tsdn, arena_t *arena,
- arena_chunk_t *chunk, void *ptr)
-{
-
- arena_dalloc_large_locked_impl(tsdn, arena, chunk, ptr, true);
-}
-
-void
-arena_dalloc_large(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- void *ptr)
-{
-
- malloc_mutex_lock(tsdn, &arena->lock);
- arena_dalloc_large_locked_impl(tsdn, arena, chunk, ptr, false);
- malloc_mutex_unlock(tsdn, &arena->lock);
- arena_decay_tick(tsdn, arena);
-}
-
-static void
-arena_ralloc_large_shrink(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- void *ptr, size_t oldsize, size_t size)
-{
- size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- arena_chunk_map_misc_t *miscelm = arena_miscelm_get_mutable(chunk,
- pageind);
- arena_run_t *run = &miscelm->run;
-
- assert(size < oldsize);
-
- /*
- * Shrink the run, and make trailing pages available for other
- * allocations.
- */
- malloc_mutex_lock(tsdn, &arena->lock);
- arena_run_trim_tail(tsdn, arena, chunk, run, oldsize + large_pad, size +
- large_pad, true);
- if (config_stats) {
- szind_t oldindex = size2index(oldsize) - NBINS;
- szind_t index = size2index(size) - NBINS;
-
- arena->stats.ndalloc_large++;
- arena->stats.allocated_large -= oldsize;
- arena->stats.lstats[oldindex].ndalloc++;
- arena->stats.lstats[oldindex].curruns--;
-
- arena->stats.nmalloc_large++;
- arena->stats.nrequests_large++;
- arena->stats.allocated_large += size;
- arena->stats.lstats[index].nmalloc++;
- arena->stats.lstats[index].nrequests++;
- arena->stats.lstats[index].curruns++;
- }
- malloc_mutex_unlock(tsdn, &arena->lock);
-}
-
-static bool
-arena_ralloc_large_grow(tsdn_t *tsdn, arena_t *arena, arena_chunk_t *chunk,
- void *ptr, size_t oldsize, size_t usize_min, size_t usize_max, bool zero)
-{
- size_t pageind = ((uintptr_t)ptr - (uintptr_t)chunk) >> LG_PAGE;
- size_t npages = (oldsize + large_pad) >> LG_PAGE;
- size_t followsize;
-
- assert(oldsize == arena_mapbits_large_size_get(chunk, pageind) -
- large_pad);
-
- /* Try to extend the run. */
- malloc_mutex_lock(tsdn, &arena->lock);
- if (pageind+npages >= chunk_npages || arena_mapbits_allocated_get(chunk,
- pageind+npages) != 0)
- goto label_fail;
- followsize = arena_mapbits_unallocated_size_get(chunk, pageind+npages);
- if (oldsize + followsize >= usize_min) {
- /*
- * The next run is available and sufficiently large. Split the
- * following run, then merge the first part with the existing
- * allocation.
- */
- arena_run_t *run;
- size_t usize, splitsize, size, flag_dirty, flag_unzeroed_mask;
-
- usize = usize_max;
- while (oldsize + followsize < usize)
- usize = index2size(size2index(usize)-1);
- assert(usize >= usize_min);
- assert(usize >= oldsize);
- splitsize = usize - oldsize;
- if (splitsize == 0)
- goto label_fail;
-
- run = &arena_miscelm_get_mutable(chunk, pageind+npages)->run;
- if (arena_run_split_large(arena, run, splitsize, zero))
- goto label_fail;
-
- if (config_cache_oblivious && zero) {
- /*
- * Zero the trailing bytes of the original allocation's
- * last page, since they are in an indeterminate state.
- * There will always be trailing bytes, because ptr's
- * offset from the beginning of the run is a multiple of
- * CACHELINE in [0 .. PAGE).
- */
- void *zbase = (void *)((uintptr_t)ptr + oldsize);
- void *zpast = PAGE_ADDR2BASE((void *)((uintptr_t)zbase +
- PAGE));
- size_t nzero = (uintptr_t)zpast - (uintptr_t)zbase;
- assert(nzero > 0);
- memset(zbase, 0, nzero);
- }
-
- size = oldsize + splitsize;
- npages = (size + large_pad) >> LG_PAGE;
-
- /*
- * Mark the extended run as dirty if either portion of the run
- * was dirty before allocation. This is rather pedantic,
- * because there's not actually any sequence of events that
- * could cause the resulting run to be passed to
- * arena_run_dalloc() with the dirty argument set to false
- * (which is when dirty flag consistency would really matter).
- */
- flag_dirty = arena_mapbits_dirty_get(chunk, pageind) |
- arena_mapbits_dirty_get(chunk, pageind+npages-1);
- flag_unzeroed_mask = flag_dirty == 0 ? CHUNK_MAP_UNZEROED : 0;
- arena_mapbits_large_set(chunk, pageind, size + large_pad,
- flag_dirty | (flag_unzeroed_mask &
- arena_mapbits_unzeroed_get(chunk, pageind)));
- arena_mapbits_large_set(chunk, pageind+npages-1, 0, flag_dirty |
- (flag_unzeroed_mask & arena_mapbits_unzeroed_get(chunk,
- pageind+npages-1)));
-
- if (config_stats) {
- szind_t oldindex = size2index(oldsize) - NBINS;
- szind_t index = size2index(size) - NBINS;
-
- arena->stats.ndalloc_large++;
- arena->stats.allocated_large -= oldsize;
- arena->stats.lstats[oldindex].ndalloc++;
- arena->stats.lstats[oldindex].curruns--;
-
- arena->stats.nmalloc_large++;
- arena->stats.nrequests_large++;
- arena->stats.allocated_large += size;
- arena->stats.lstats[index].nmalloc++;
- arena->stats.lstats[index].nrequests++;
- arena->stats.lstats[index].curruns++;
- }
- malloc_mutex_unlock(tsdn, &arena->lock);
- return (false);
- }
-label_fail:
- malloc_mutex_unlock(tsdn, &arena->lock);
- return (true);
-}
-
-#ifdef JEMALLOC_JET
-#undef arena_ralloc_junk_large
-#define arena_ralloc_junk_large JEMALLOC_N(n_arena_ralloc_junk_large)
-#endif
-static void
-arena_ralloc_junk_large(void *ptr, size_t old_usize, size_t usize)
-{
-
- if (config_fill && unlikely(opt_junk_free)) {
- memset((void *)((uintptr_t)ptr + usize), JEMALLOC_FREE_JUNK,
- old_usize - usize);
- }
-}
-#ifdef JEMALLOC_JET
-#undef arena_ralloc_junk_large
-#define arena_ralloc_junk_large JEMALLOC_N(arena_ralloc_junk_large)
-arena_ralloc_junk_large_t *arena_ralloc_junk_large =
- JEMALLOC_N(n_arena_ralloc_junk_large);
-#endif
-
-/*
- * Try to resize a large allocation, in order to avoid copying. This will
- * always fail if growing an object, and the following run is already in use.
- */
-static bool
-arena_ralloc_large(tsdn_t *tsdn, void *ptr, size_t oldsize, size_t usize_min,
- size_t usize_max, bool zero)
-{
- arena_chunk_t *chunk;
- arena_t *arena;
-
- if (oldsize == usize_max) {
- /* Current size class is compatible and maximal. */
- return (false);
- }
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- arena = extent_node_arena_get(&chunk->node);
-
- if (oldsize < usize_max) {
- bool ret = arena_ralloc_large_grow(tsdn, arena, chunk, ptr,
- oldsize, usize_min, usize_max, zero);
- if (config_fill && !ret && !zero) {
- if (unlikely(opt_junk_alloc)) {
- memset((void *)((uintptr_t)ptr + oldsize),
- JEMALLOC_ALLOC_JUNK,
- isalloc(tsdn, ptr, config_prof) - oldsize);
- } else if (unlikely(opt_zero)) {
- memset((void *)((uintptr_t)ptr + oldsize), 0,
- isalloc(tsdn, ptr, config_prof) - oldsize);
- }
- }
- return (ret);
- }
-
- assert(oldsize > usize_max);
- /* Fill before shrinking in order avoid a race. */
- arena_ralloc_junk_large(ptr, oldsize, usize_max);
- arena_ralloc_large_shrink(tsdn, arena, chunk, ptr, oldsize, usize_max);
- return (false);
-}
-
-bool
-arena_ralloc_no_move(tsdn_t *tsdn, void *ptr, size_t oldsize, size_t size,
- size_t extra, bool zero)
-{
- size_t usize_min, usize_max;
-
- /* Calls with non-zero extra had to clamp extra. */
- assert(extra == 0 || size + extra <= HUGE_MAXCLASS);
-
- if (unlikely(size > HUGE_MAXCLASS))
- return (true);
-
- usize_min = s2u(size);
- usize_max = s2u(size + extra);
- if (likely(oldsize <= large_maxclass && usize_min <= large_maxclass)) {
- arena_chunk_t *chunk;
-
- /*
- * Avoid moving the allocation if the size class can be left the
- * same.
- */
- if (oldsize <= SMALL_MAXCLASS) {
- assert(arena_bin_info[size2index(oldsize)].reg_size ==
- oldsize);
- if ((usize_max > SMALL_MAXCLASS ||
- size2index(usize_max) != size2index(oldsize)) &&
- (size > oldsize || usize_max < oldsize))
- return (true);
- } else {
- if (usize_max <= SMALL_MAXCLASS)
- return (true);
- if (arena_ralloc_large(tsdn, ptr, oldsize, usize_min,
- usize_max, zero))
- return (true);
- }
-
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- arena_decay_tick(tsdn, extent_node_arena_get(&chunk->node));
- return (false);
- } else {
- return (huge_ralloc_no_move(tsdn, ptr, oldsize, usize_min,
- usize_max, zero));
- }
-}
-
-static void *
-arena_ralloc_move_helper(tsdn_t *tsdn, arena_t *arena, size_t usize,
- size_t alignment, bool zero, tcache_t *tcache)
-{
-
- if (alignment == 0)
- return (arena_malloc(tsdn, arena, usize, size2index(usize),
- zero, tcache, true));
- usize = sa2u(usize, alignment);
- if (unlikely(usize == 0 || usize > HUGE_MAXCLASS))
- return (NULL);
- return (ipalloct(tsdn, usize, alignment, zero, tcache, arena));
-}
-
-void *
-arena_ralloc(tsd_t *tsd, arena_t *arena, void *ptr, size_t oldsize, size_t size,
- size_t alignment, bool zero, tcache_t *tcache)
-{
- void *ret;
- size_t usize;
-
- usize = s2u(size);
- if (unlikely(usize == 0 || size > HUGE_MAXCLASS))
- return (NULL);
-
- if (likely(usize <= large_maxclass)) {
- size_t copysize;
-
- /* Try to avoid moving the allocation. */
- if (!arena_ralloc_no_move(tsd_tsdn(tsd), ptr, oldsize, usize, 0,
- zero))
- return (ptr);
-
- /*
- * size and oldsize are different enough that we need to move
- * the object. In that case, fall back to allocating new space
- * and copying.
- */
- ret = arena_ralloc_move_helper(tsd_tsdn(tsd), arena, usize,
- alignment, zero, tcache);
- if (ret == NULL)
- return (NULL);
-
- /*
- * Junk/zero-filling were already done by
- * ipalloc()/arena_malloc().
- */
-
- copysize = (usize < oldsize) ? usize : oldsize;
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ret, copysize);
- memcpy(ret, ptr, copysize);
- isqalloc(tsd, ptr, oldsize, tcache, true);
- } else {
- ret = huge_ralloc(tsd, arena, ptr, oldsize, usize, alignment,
- zero, tcache);
- }
- return (ret);
-}
-
-dss_prec_t
-arena_dss_prec_get(tsdn_t *tsdn, arena_t *arena)
-{
- dss_prec_t ret;
-
- malloc_mutex_lock(tsdn, &arena->lock);
- ret = arena->dss_prec;
- malloc_mutex_unlock(tsdn, &arena->lock);
- return (ret);
-}
-
-bool
-arena_dss_prec_set(tsdn_t *tsdn, arena_t *arena, dss_prec_t dss_prec)
-{
-
- if (!have_dss)
- return (dss_prec != dss_prec_disabled);
- malloc_mutex_lock(tsdn, &arena->lock);
- arena->dss_prec = dss_prec;
- malloc_mutex_unlock(tsdn, &arena->lock);
- return (false);
-}
-
-ssize_t
-arena_lg_dirty_mult_default_get(void)
-{
-
- return ((ssize_t)atomic_read_z((size_t *)&lg_dirty_mult_default));
-}
-
-bool
-arena_lg_dirty_mult_default_set(ssize_t lg_dirty_mult)
-{
-
- if (opt_purge != purge_mode_ratio)
- return (true);
- if (!arena_lg_dirty_mult_valid(lg_dirty_mult))
- return (true);
- atomic_write_z((size_t *)&lg_dirty_mult_default, (size_t)lg_dirty_mult);
- return (false);
-}
-
-ssize_t
-arena_decay_time_default_get(void)
-{
-
- return ((ssize_t)atomic_read_z((size_t *)&decay_time_default));
-}
-
-bool
-arena_decay_time_default_set(ssize_t decay_time)
-{
-
- if (opt_purge != purge_mode_decay)
- return (true);
- if (!arena_decay_time_valid(decay_time))
- return (true);
- atomic_write_z((size_t *)&decay_time_default, (size_t)decay_time);
- return (false);
-}
-
-static void
-arena_basic_stats_merge_locked(arena_t *arena, unsigned *nthreads,
- const char **dss, ssize_t *lg_dirty_mult, ssize_t *decay_time,
- size_t *nactive, size_t *ndirty)
-{
-
- *nthreads += arena_nthreads_get(arena, false);
- *dss = dss_prec_names[arena->dss_prec];
- *lg_dirty_mult = arena->lg_dirty_mult;
- *decay_time = arena->decay.time;
- *nactive += arena->nactive;
- *ndirty += arena->ndirty;
-}
-
-void
-arena_basic_stats_merge(tsdn_t *tsdn, arena_t *arena, unsigned *nthreads,
- const char **dss, ssize_t *lg_dirty_mult, ssize_t *decay_time,
- size_t *nactive, size_t *ndirty)
-{
-
- malloc_mutex_lock(tsdn, &arena->lock);
- arena_basic_stats_merge_locked(arena, nthreads, dss, lg_dirty_mult,
- decay_time, nactive, ndirty);
- malloc_mutex_unlock(tsdn, &arena->lock);
-}
-
-void
-arena_stats_merge(tsdn_t *tsdn, arena_t *arena, unsigned *nthreads,
- const char **dss, ssize_t *lg_dirty_mult, ssize_t *decay_time,
- size_t *nactive, size_t *ndirty, arena_stats_t *astats,
- malloc_bin_stats_t *bstats, malloc_large_stats_t *lstats,
- malloc_huge_stats_t *hstats)
-{
- unsigned i;
-
- cassert(config_stats);
-
- malloc_mutex_lock(tsdn, &arena->lock);
- arena_basic_stats_merge_locked(arena, nthreads, dss, lg_dirty_mult,
- decay_time, nactive, ndirty);
-
- astats->mapped += arena->stats.mapped;
- astats->retained += arena->stats.retained;
- astats->npurge += arena->stats.npurge;
- astats->nmadvise += arena->stats.nmadvise;
- astats->purged += arena->stats.purged;
- astats->metadata_mapped += arena->stats.metadata_mapped;
- astats->metadata_allocated += arena_metadata_allocated_get(arena);
- astats->allocated_large += arena->stats.allocated_large;
- astats->nmalloc_large += arena->stats.nmalloc_large;
- astats->ndalloc_large += arena->stats.ndalloc_large;
- astats->nrequests_large += arena->stats.nrequests_large;
- astats->allocated_huge += arena->stats.allocated_huge;
- astats->nmalloc_huge += arena->stats.nmalloc_huge;
- astats->ndalloc_huge += arena->stats.ndalloc_huge;
-
- for (i = 0; i < nlclasses; i++) {
- lstats[i].nmalloc += arena->stats.lstats[i].nmalloc;
- lstats[i].ndalloc += arena->stats.lstats[i].ndalloc;
- lstats[i].nrequests += arena->stats.lstats[i].nrequests;
- lstats[i].curruns += arena->stats.lstats[i].curruns;
- }
-
- for (i = 0; i < nhclasses; i++) {
- hstats[i].nmalloc += arena->stats.hstats[i].nmalloc;
- hstats[i].ndalloc += arena->stats.hstats[i].ndalloc;
- hstats[i].curhchunks += arena->stats.hstats[i].curhchunks;
- }
- malloc_mutex_unlock(tsdn, &arena->lock);
-
- for (i = 0; i < NBINS; i++) {
- arena_bin_t *bin = &arena->bins[i];
-
- malloc_mutex_lock(tsdn, &bin->lock);
- bstats[i].nmalloc += bin->stats.nmalloc;
- bstats[i].ndalloc += bin->stats.ndalloc;
- bstats[i].nrequests += bin->stats.nrequests;
- bstats[i].curregs += bin->stats.curregs;
- if (config_tcache) {
- bstats[i].nfills += bin->stats.nfills;
- bstats[i].nflushes += bin->stats.nflushes;
- }
- bstats[i].nruns += bin->stats.nruns;
- bstats[i].reruns += bin->stats.reruns;
- bstats[i].curruns += bin->stats.curruns;
- malloc_mutex_unlock(tsdn, &bin->lock);
- }
-}
-
-unsigned
-arena_nthreads_get(arena_t *arena, bool internal)
-{
-
- return (atomic_read_u(&arena->nthreads[internal]));
-}
-
-void
-arena_nthreads_inc(arena_t *arena, bool internal)
-{
-
- atomic_add_u(&arena->nthreads[internal], 1);
-}
-
-void
-arena_nthreads_dec(arena_t *arena, bool internal)
-{
-
- atomic_sub_u(&arena->nthreads[internal], 1);
-}
-
-arena_t *
-arena_new(tsdn_t *tsdn, unsigned ind)
-{
- arena_t *arena;
- unsigned i;
-
- /*
- * Allocate arena, arena->lstats, and arena->hstats contiguously, mainly
- * because there is no way to clean up if base_alloc() OOMs.
- */
- if (config_stats) {
- arena = (arena_t *)base_alloc(tsdn,
- CACHELINE_CEILING(sizeof(arena_t)) +
- QUANTUM_CEILING((nlclasses * sizeof(malloc_large_stats_t)))
- + (nhclasses * sizeof(malloc_huge_stats_t)));
- } else
- arena = (arena_t *)base_alloc(tsdn, sizeof(arena_t));
- if (arena == NULL)
- return (NULL);
-
- arena->ind = ind;
- arena->nthreads[0] = arena->nthreads[1] = 0;
- if (malloc_mutex_init(&arena->lock, "arena", WITNESS_RANK_ARENA))
- return (NULL);
-
- if (config_stats) {
- memset(&arena->stats, 0, sizeof(arena_stats_t));
- arena->stats.lstats = (malloc_large_stats_t *)((uintptr_t)arena
- + CACHELINE_CEILING(sizeof(arena_t)));
- memset(arena->stats.lstats, 0, nlclasses *
- sizeof(malloc_large_stats_t));
- arena->stats.hstats = (malloc_huge_stats_t *)((uintptr_t)arena
- + CACHELINE_CEILING(sizeof(arena_t)) +
- QUANTUM_CEILING(nlclasses * sizeof(malloc_large_stats_t)));
- memset(arena->stats.hstats, 0, nhclasses *
- sizeof(malloc_huge_stats_t));
- if (config_tcache)
- ql_new(&arena->tcache_ql);
- }
-
- if (config_prof)
- arena->prof_accumbytes = 0;
-
- if (config_cache_oblivious) {
- /*
- * A nondeterministic seed based on the address of arena reduces
- * the likelihood of lockstep non-uniform cache index
- * utilization among identical concurrent processes, but at the
- * cost of test repeatability. For debug builds, instead use a
- * deterministic seed.
- */
- arena->offset_state = config_debug ? ind :
- (size_t)(uintptr_t)arena;
- }
-
- arena->dss_prec = chunk_dss_prec_get();
-
- ql_new(&arena->achunks);
-
- arena->spare = NULL;
-
- arena->lg_dirty_mult = arena_lg_dirty_mult_default_get();
- arena->purging = false;
- arena->nactive = 0;
- arena->ndirty = 0;
-
- for (i = 0; i < NPSIZES; i++)
- arena_run_heap_new(&arena->runs_avail[i]);
-
- qr_new(&arena->runs_dirty, rd_link);
- qr_new(&arena->chunks_cache, cc_link);
-
- if (opt_purge == purge_mode_decay)
- arena_decay_init(arena, arena_decay_time_default_get());
-
- ql_new(&arena->huge);
- if (malloc_mutex_init(&arena->huge_mtx, "arena_huge",
- WITNESS_RANK_ARENA_HUGE))
- return (NULL);
-
- extent_tree_szad_new(&arena->chunks_szad_cached);
- extent_tree_ad_new(&arena->chunks_ad_cached);
- extent_tree_szad_new(&arena->chunks_szad_retained);
- extent_tree_ad_new(&arena->chunks_ad_retained);
- if (malloc_mutex_init(&arena->chunks_mtx, "arena_chunks",
- WITNESS_RANK_ARENA_CHUNKS))
- return (NULL);
- ql_new(&arena->node_cache);
- if (malloc_mutex_init(&arena->node_cache_mtx, "arena_node_cache",
- WITNESS_RANK_ARENA_NODE_CACHE))
- return (NULL);
-
- arena->chunk_hooks = chunk_hooks_default;
-
- /* Initialize bins. */
- for (i = 0; i < NBINS; i++) {
- arena_bin_t *bin = &arena->bins[i];
- if (malloc_mutex_init(&bin->lock, "arena_bin",
- WITNESS_RANK_ARENA_BIN))
- return (NULL);
- bin->runcur = NULL;
- arena_run_heap_new(&bin->runs);
- if (config_stats)
- memset(&bin->stats, 0, sizeof(malloc_bin_stats_t));
- }
-
- return (arena);
-}
-
-/*
- * Calculate bin_info->run_size such that it meets the following constraints:
- *
- * *) bin_info->run_size <= arena_maxrun
- * *) bin_info->nregs <= RUN_MAXREGS
- *
- * bin_info->nregs and bin_info->reg0_offset are also calculated here, since
- * these settings are all interdependent.
- */
-static void
-bin_info_run_size_calc(arena_bin_info_t *bin_info)
-{
- size_t pad_size;
- size_t try_run_size, perfect_run_size, actual_run_size;
- uint32_t try_nregs, perfect_nregs, actual_nregs;
-
- /*
- * Determine redzone size based on minimum alignment and minimum
- * redzone size. Add padding to the end of the run if it is needed to
- * align the regions. The padding allows each redzone to be half the
- * minimum alignment; without the padding, each redzone would have to
- * be twice as large in order to maintain alignment.
- */
- if (config_fill && unlikely(opt_redzone)) {
- size_t align_min = ZU(1) << (ffs_zu(bin_info->reg_size) - 1);
- if (align_min <= REDZONE_MINSIZE) {
- bin_info->redzone_size = REDZONE_MINSIZE;
- pad_size = 0;
- } else {
- bin_info->redzone_size = align_min >> 1;
- pad_size = bin_info->redzone_size;
- }
- } else {
- bin_info->redzone_size = 0;
- pad_size = 0;
- }
- bin_info->reg_interval = bin_info->reg_size +
- (bin_info->redzone_size << 1);
-
- /*
- * Compute run size under ideal conditions (no redzones, no limit on run
- * size).
- */
- try_run_size = PAGE;
- try_nregs = (uint32_t)(try_run_size / bin_info->reg_size);
- do {
- perfect_run_size = try_run_size;
- perfect_nregs = try_nregs;
-
- try_run_size += PAGE;
- try_nregs = (uint32_t)(try_run_size / bin_info->reg_size);
- } while (perfect_run_size != perfect_nregs * bin_info->reg_size);
- assert(perfect_nregs <= RUN_MAXREGS);
-
- actual_run_size = perfect_run_size;
- actual_nregs = (uint32_t)((actual_run_size - pad_size) /
- bin_info->reg_interval);
-
- /*
- * Redzones can require enough padding that not even a single region can
- * fit within the number of pages that would normally be dedicated to a
- * run for this size class. Increase the run size until at least one
- * region fits.
- */
- while (actual_nregs == 0) {
- assert(config_fill && unlikely(opt_redzone));
-
- actual_run_size += PAGE;
- actual_nregs = (uint32_t)((actual_run_size - pad_size) /
- bin_info->reg_interval);
- }
-
- /*
- * Make sure that the run will fit within an arena chunk.
- */
- while (actual_run_size > arena_maxrun) {
- actual_run_size -= PAGE;
- actual_nregs = (uint32_t)((actual_run_size - pad_size) /
- bin_info->reg_interval);
- }
- assert(actual_nregs > 0);
- assert(actual_run_size == s2u(actual_run_size));
-
- /* Copy final settings. */
- bin_info->run_size = actual_run_size;
- bin_info->nregs = actual_nregs;
- bin_info->reg0_offset = (uint32_t)(actual_run_size - (actual_nregs *
- bin_info->reg_interval) - pad_size + bin_info->redzone_size);
-
- assert(bin_info->reg0_offset - bin_info->redzone_size + (bin_info->nregs
- * bin_info->reg_interval) + pad_size == bin_info->run_size);
-}
-
-static void
-bin_info_init(void)
-{
- arena_bin_info_t *bin_info;
-
-#define BIN_INFO_INIT_bin_yes(index, size) \
- bin_info = &arena_bin_info[index]; \
- bin_info->reg_size = size; \
- bin_info_run_size_calc(bin_info); \
- bitmap_info_init(&bin_info->bitmap_info, bin_info->nregs);
-#define BIN_INFO_INIT_bin_no(index, size)
-#define SC(index, lg_grp, lg_delta, ndelta, psz, bin, lg_delta_lookup) \
- BIN_INFO_INIT_bin_##bin(index, (ZU(1)<<lg_grp) + (ZU(ndelta)<<lg_delta))
- SIZE_CLASSES
-#undef BIN_INFO_INIT_bin_yes
-#undef BIN_INFO_INIT_bin_no
-#undef SC
-}
-
-void
-arena_boot(void)
-{
- unsigned i;
-
- arena_lg_dirty_mult_default_set(opt_lg_dirty_mult);
- arena_decay_time_default_set(opt_decay_time);
-
- /*
- * Compute the header size such that it is large enough to contain the
- * page map. The page map is biased to omit entries for the header
- * itself, so some iteration is necessary to compute the map bias.
- *
- * 1) Compute safe header_size and map_bias values that include enough
- * space for an unbiased page map.
- * 2) Refine map_bias based on (1) to omit the header pages in the page
- * map. The resulting map_bias may be one too small.
- * 3) Refine map_bias based on (2). The result will be >= the result
- * from (2), and will always be correct.
- */
- map_bias = 0;
- for (i = 0; i < 3; i++) {
- size_t header_size = offsetof(arena_chunk_t, map_bits) +
- ((sizeof(arena_chunk_map_bits_t) +
- sizeof(arena_chunk_map_misc_t)) * (chunk_npages-map_bias));
- map_bias = (header_size + PAGE_MASK) >> LG_PAGE;
- }
- assert(map_bias > 0);
-
- map_misc_offset = offsetof(arena_chunk_t, map_bits) +
- sizeof(arena_chunk_map_bits_t) * (chunk_npages-map_bias);
-
- arena_maxrun = chunksize - (map_bias << LG_PAGE);
- assert(arena_maxrun > 0);
- large_maxclass = index2size(size2index(chunksize)-1);
- if (large_maxclass > arena_maxrun) {
- /*
- * For small chunk sizes it's possible for there to be fewer
- * non-header pages available than are necessary to serve the
- * size classes just below chunksize.
- */
- large_maxclass = arena_maxrun;
- }
- assert(large_maxclass > 0);
- nlclasses = size2index(large_maxclass) - size2index(SMALL_MAXCLASS);
- nhclasses = NSIZES - nlclasses - NBINS;
-
- bin_info_init();
-}
-
-void
-arena_prefork0(tsdn_t *tsdn, arena_t *arena)
-{
-
- malloc_mutex_prefork(tsdn, &arena->lock);
-}
-
-void
-arena_prefork1(tsdn_t *tsdn, arena_t *arena)
-{
-
- malloc_mutex_prefork(tsdn, &arena->chunks_mtx);
-}
-
-void
-arena_prefork2(tsdn_t *tsdn, arena_t *arena)
-{
-
- malloc_mutex_prefork(tsdn, &arena->node_cache_mtx);
-}
-
-void
-arena_prefork3(tsdn_t *tsdn, arena_t *arena)
-{
- unsigned i;
-
- for (i = 0; i < NBINS; i++)
- malloc_mutex_prefork(tsdn, &arena->bins[i].lock);
- malloc_mutex_prefork(tsdn, &arena->huge_mtx);
-}
-
-void
-arena_postfork_parent(tsdn_t *tsdn, arena_t *arena)
-{
- unsigned i;
-
- malloc_mutex_postfork_parent(tsdn, &arena->huge_mtx);
- for (i = 0; i < NBINS; i++)
- malloc_mutex_postfork_parent(tsdn, &arena->bins[i].lock);
- malloc_mutex_postfork_parent(tsdn, &arena->node_cache_mtx);
- malloc_mutex_postfork_parent(tsdn, &arena->chunks_mtx);
- malloc_mutex_postfork_parent(tsdn, &arena->lock);
-}
-
-void
-arena_postfork_child(tsdn_t *tsdn, arena_t *arena)
-{
- unsigned i;
-
- malloc_mutex_postfork_child(tsdn, &arena->huge_mtx);
- for (i = 0; i < NBINS; i++)
- malloc_mutex_postfork_child(tsdn, &arena->bins[i].lock);
- malloc_mutex_postfork_child(tsdn, &arena->node_cache_mtx);
- malloc_mutex_postfork_child(tsdn, &arena->chunks_mtx);
- malloc_mutex_postfork_child(tsdn, &arena->lock);
-}
diff --git a/memory/jemalloc/src/src/atomic.c b/memory/jemalloc/src/src/atomic.c
deleted file mode 100644
index 77ee31311..000000000
--- a/memory/jemalloc/src/src/atomic.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#define JEMALLOC_ATOMIC_C_
-#include "jemalloc/internal/jemalloc_internal.h"
diff --git a/memory/jemalloc/src/src/base.c b/memory/jemalloc/src/src/base.c
deleted file mode 100644
index 81b0801fd..000000000
--- a/memory/jemalloc/src/src/base.c
+++ /dev/null
@@ -1,177 +0,0 @@
-#define JEMALLOC_BASE_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Data. */
-
-static malloc_mutex_t base_mtx;
-static extent_tree_t base_avail_szad;
-static extent_node_t *base_nodes;
-static size_t base_allocated;
-static size_t base_resident;
-static size_t base_mapped;
-
-/******************************************************************************/
-
-static extent_node_t *
-base_node_try_alloc(tsdn_t *tsdn)
-{
- extent_node_t *node;
-
- malloc_mutex_assert_owner(tsdn, &base_mtx);
-
- if (base_nodes == NULL)
- return (NULL);
- node = base_nodes;
- base_nodes = *(extent_node_t **)node;
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(node, sizeof(extent_node_t));
- return (node);
-}
-
-static void
-base_node_dalloc(tsdn_t *tsdn, extent_node_t *node)
-{
-
- malloc_mutex_assert_owner(tsdn, &base_mtx);
-
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(node, sizeof(extent_node_t));
- *(extent_node_t **)node = base_nodes;
- base_nodes = node;
-}
-
-static extent_node_t *
-base_chunk_alloc(tsdn_t *tsdn, size_t minsize)
-{
- extent_node_t *node;
- size_t csize, nsize;
- void *addr;
-
- malloc_mutex_assert_owner(tsdn, &base_mtx);
- assert(minsize != 0);
- node = base_node_try_alloc(tsdn);
- /* Allocate enough space to also carve a node out if necessary. */
- nsize = (node == NULL) ? CACHELINE_CEILING(sizeof(extent_node_t)) : 0;
- csize = CHUNK_CEILING(minsize + nsize);
- addr = chunk_alloc_base(csize);
- if (addr == NULL) {
- if (node != NULL)
- base_node_dalloc(tsdn, node);
- return (NULL);
- }
- base_mapped += csize;
- if (node == NULL) {
- node = (extent_node_t *)addr;
- addr = (void *)((uintptr_t)addr + nsize);
- csize -= nsize;
- if (config_stats) {
- base_allocated += nsize;
- base_resident += PAGE_CEILING(nsize);
- }
- }
- extent_node_init(node, NULL, addr, csize, true, true);
- return (node);
-}
-
-/*
- * base_alloc() guarantees demand-zeroed memory, in order to make multi-page
- * sparse data structures such as radix tree nodes efficient with respect to
- * physical memory usage.
- */
-void *
-base_alloc(tsdn_t *tsdn, size_t size)
-{
- void *ret;
- size_t csize, usize;
- extent_node_t *node;
- extent_node_t key;
-
- /*
- * Round size up to nearest multiple of the cacheline size, so that
- * there is no chance of false cache line sharing.
- */
- csize = CACHELINE_CEILING(size);
-
- usize = s2u(csize);
- extent_node_init(&key, NULL, NULL, usize, false, false);
- malloc_mutex_lock(tsdn, &base_mtx);
- node = extent_tree_szad_nsearch(&base_avail_szad, &key);
- if (node != NULL) {
- /* Use existing space. */
- extent_tree_szad_remove(&base_avail_szad, node);
- } else {
- /* Try to allocate more space. */
- node = base_chunk_alloc(tsdn, csize);
- }
- if (node == NULL) {
- ret = NULL;
- goto label_return;
- }
-
- ret = extent_node_addr_get(node);
- if (extent_node_size_get(node) > csize) {
- extent_node_addr_set(node, (void *)((uintptr_t)ret + csize));
- extent_node_size_set(node, extent_node_size_get(node) - csize);
- extent_tree_szad_insert(&base_avail_szad, node);
- } else
- base_node_dalloc(tsdn, node);
- if (config_stats) {
- base_allocated += csize;
- /*
- * Add one PAGE to base_resident for every page boundary that is
- * crossed by the new allocation.
- */
- base_resident += PAGE_CEILING((uintptr_t)ret + csize) -
- PAGE_CEILING((uintptr_t)ret);
- }
- JEMALLOC_VALGRIND_MAKE_MEM_DEFINED(ret, csize);
-label_return:
- malloc_mutex_unlock(tsdn, &base_mtx);
- return (ret);
-}
-
-void
-base_stats_get(tsdn_t *tsdn, size_t *allocated, size_t *resident,
- size_t *mapped)
-{
-
- malloc_mutex_lock(tsdn, &base_mtx);
- assert(base_allocated <= base_resident);
- assert(base_resident <= base_mapped);
- *allocated = base_allocated;
- *resident = base_resident;
- *mapped = base_mapped;
- malloc_mutex_unlock(tsdn, &base_mtx);
-}
-
-bool
-base_boot(void)
-{
-
- if (malloc_mutex_init(&base_mtx, "base", WITNESS_RANK_BASE))
- return (true);
- extent_tree_szad_new(&base_avail_szad);
- base_nodes = NULL;
-
- return (false);
-}
-
-void
-base_prefork(tsdn_t *tsdn)
-{
-
- malloc_mutex_prefork(tsdn, &base_mtx);
-}
-
-void
-base_postfork_parent(tsdn_t *tsdn)
-{
-
- malloc_mutex_postfork_parent(tsdn, &base_mtx);
-}
-
-void
-base_postfork_child(tsdn_t *tsdn)
-{
-
- malloc_mutex_postfork_child(tsdn, &base_mtx);
-}
diff --git a/memory/jemalloc/src/src/bitmap.c b/memory/jemalloc/src/src/bitmap.c
deleted file mode 100644
index ac0f3b381..000000000
--- a/memory/jemalloc/src/src/bitmap.c
+++ /dev/null
@@ -1,111 +0,0 @@
-#define JEMALLOC_BITMAP_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-
-#ifdef USE_TREE
-
-void
-bitmap_info_init(bitmap_info_t *binfo, size_t nbits)
-{
- unsigned i;
- size_t group_count;
-
- assert(nbits > 0);
- assert(nbits <= (ZU(1) << LG_BITMAP_MAXBITS));
-
- /*
- * Compute the number of groups necessary to store nbits bits, and
- * progressively work upward through the levels until reaching a level
- * that requires only one group.
- */
- binfo->levels[0].group_offset = 0;
- group_count = BITMAP_BITS2GROUPS(nbits);
- for (i = 1; group_count > 1; i++) {
- assert(i < BITMAP_MAX_LEVELS);
- binfo->levels[i].group_offset = binfo->levels[i-1].group_offset
- + group_count;
- group_count = BITMAP_BITS2GROUPS(group_count);
- }
- binfo->levels[i].group_offset = binfo->levels[i-1].group_offset
- + group_count;
- assert(binfo->levels[i].group_offset <= BITMAP_GROUPS_MAX);
- binfo->nlevels = i;
- binfo->nbits = nbits;
-}
-
-static size_t
-bitmap_info_ngroups(const bitmap_info_t *binfo)
-{
-
- return (binfo->levels[binfo->nlevels].group_offset);
-}
-
-void
-bitmap_init(bitmap_t *bitmap, const bitmap_info_t *binfo)
-{
- size_t extra;
- unsigned i;
-
- /*
- * Bits are actually inverted with regard to the external bitmap
- * interface, so the bitmap starts out with all 1 bits, except for
- * trailing unused bits (if any). Note that each group uses bit 0 to
- * correspond to the first logical bit in the group, so extra bits
- * are the most significant bits of the last group.
- */
- memset(bitmap, 0xffU, bitmap_size(binfo));
- extra = (BITMAP_GROUP_NBITS - (binfo->nbits & BITMAP_GROUP_NBITS_MASK))
- & BITMAP_GROUP_NBITS_MASK;
- if (extra != 0)
- bitmap[binfo->levels[1].group_offset - 1] >>= extra;
- for (i = 1; i < binfo->nlevels; i++) {
- size_t group_count = binfo->levels[i].group_offset -
- binfo->levels[i-1].group_offset;
- extra = (BITMAP_GROUP_NBITS - (group_count &
- BITMAP_GROUP_NBITS_MASK)) & BITMAP_GROUP_NBITS_MASK;
- if (extra != 0)
- bitmap[binfo->levels[i+1].group_offset - 1] >>= extra;
- }
-}
-
-#else /* USE_TREE */
-
-void
-bitmap_info_init(bitmap_info_t *binfo, size_t nbits)
-{
-
- assert(nbits > 0);
- assert(nbits <= (ZU(1) << LG_BITMAP_MAXBITS));
-
- binfo->ngroups = BITMAP_BITS2GROUPS(nbits);
- binfo->nbits = nbits;
-}
-
-static size_t
-bitmap_info_ngroups(const bitmap_info_t *binfo)
-{
-
- return (binfo->ngroups);
-}
-
-void
-bitmap_init(bitmap_t *bitmap, const bitmap_info_t *binfo)
-{
- size_t extra;
-
- memset(bitmap, 0xffU, bitmap_size(binfo));
- extra = (BITMAP_GROUP_NBITS - (binfo->nbits & BITMAP_GROUP_NBITS_MASK))
- & BITMAP_GROUP_NBITS_MASK;
- if (extra != 0)
- bitmap[binfo->ngroups - 1] >>= extra;
-}
-
-#endif /* USE_TREE */
-
-size_t
-bitmap_size(const bitmap_info_t *binfo)
-{
-
- return (bitmap_info_ngroups(binfo) << LG_SIZEOF_BITMAP);
-}
diff --git a/memory/jemalloc/src/src/chunk.c b/memory/jemalloc/src/src/chunk.c
deleted file mode 100644
index 07e26f77c..000000000
--- a/memory/jemalloc/src/src/chunk.c
+++ /dev/null
@@ -1,783 +0,0 @@
-#define JEMALLOC_CHUNK_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Data. */
-
-const char *opt_dss = DSS_DEFAULT;
-size_t opt_lg_chunk = 0;
-
-/* Used exclusively for gdump triggering. */
-static size_t curchunks;
-static size_t highchunks;
-
-rtree_t chunks_rtree;
-
-/* Various chunk-related settings. */
-size_t chunksize;
-size_t chunksize_mask; /* (chunksize - 1). */
-size_t chunk_npages;
-
-static void *chunk_alloc_default(void *new_addr, size_t size,
- size_t alignment, bool *zero, bool *commit, unsigned arena_ind);
-static bool chunk_dalloc_default(void *chunk, size_t size, bool committed,
- unsigned arena_ind);
-static bool chunk_commit_default(void *chunk, size_t size, size_t offset,
- size_t length, unsigned arena_ind);
-static bool chunk_decommit_default(void *chunk, size_t size, size_t offset,
- size_t length, unsigned arena_ind);
-static bool chunk_purge_default(void *chunk, size_t size, size_t offset,
- size_t length, unsigned arena_ind);
-static bool chunk_split_default(void *chunk, size_t size, size_t size_a,
- size_t size_b, bool committed, unsigned arena_ind);
-static bool chunk_merge_default(void *chunk_a, size_t size_a, void *chunk_b,
- size_t size_b, bool committed, unsigned arena_ind);
-
-const chunk_hooks_t chunk_hooks_default = {
- chunk_alloc_default,
- chunk_dalloc_default,
- chunk_commit_default,
- chunk_decommit_default,
- chunk_purge_default,
- chunk_split_default,
- chunk_merge_default
-};
-
-/******************************************************************************/
-/*
- * Function prototypes for static functions that are referenced prior to
- * definition.
- */
-
-static void chunk_record(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, extent_tree_t *chunks_szad,
- extent_tree_t *chunks_ad, bool cache, void *chunk, size_t size, bool zeroed,
- bool committed);
-
-/******************************************************************************/
-
-static chunk_hooks_t
-chunk_hooks_get_locked(arena_t *arena)
-{
-
- return (arena->chunk_hooks);
-}
-
-chunk_hooks_t
-chunk_hooks_get(tsdn_t *tsdn, arena_t *arena)
-{
- chunk_hooks_t chunk_hooks;
-
- malloc_mutex_lock(tsdn, &arena->chunks_mtx);
- chunk_hooks = chunk_hooks_get_locked(arena);
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
-
- return (chunk_hooks);
-}
-
-chunk_hooks_t
-chunk_hooks_set(tsdn_t *tsdn, arena_t *arena, const chunk_hooks_t *chunk_hooks)
-{
- chunk_hooks_t old_chunk_hooks;
-
- malloc_mutex_lock(tsdn, &arena->chunks_mtx);
- old_chunk_hooks = arena->chunk_hooks;
- /*
- * Copy each field atomically so that it is impossible for readers to
- * see partially updated pointers. There are places where readers only
- * need one hook function pointer (therefore no need to copy the
- * entirety of arena->chunk_hooks), and stale reads do not affect
- * correctness, so they perform unlocked reads.
- */
-#define ATOMIC_COPY_HOOK(n) do { \
- union { \
- chunk_##n##_t **n; \
- void **v; \
- } u; \
- u.n = &arena->chunk_hooks.n; \
- atomic_write_p(u.v, chunk_hooks->n); \
-} while (0)
- ATOMIC_COPY_HOOK(alloc);
- ATOMIC_COPY_HOOK(dalloc);
- ATOMIC_COPY_HOOK(commit);
- ATOMIC_COPY_HOOK(decommit);
- ATOMIC_COPY_HOOK(purge);
- ATOMIC_COPY_HOOK(split);
- ATOMIC_COPY_HOOK(merge);
-#undef ATOMIC_COPY_HOOK
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
-
- return (old_chunk_hooks);
-}
-
-static void
-chunk_hooks_assure_initialized_impl(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks, bool locked)
-{
- static const chunk_hooks_t uninitialized_hooks =
- CHUNK_HOOKS_INITIALIZER;
-
- if (memcmp(chunk_hooks, &uninitialized_hooks, sizeof(chunk_hooks_t)) ==
- 0) {
- *chunk_hooks = locked ? chunk_hooks_get_locked(arena) :
- chunk_hooks_get(tsdn, arena);
- }
-}
-
-static void
-chunk_hooks_assure_initialized_locked(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks)
-{
-
- chunk_hooks_assure_initialized_impl(tsdn, arena, chunk_hooks, true);
-}
-
-static void
-chunk_hooks_assure_initialized(tsdn_t *tsdn, arena_t *arena,
- chunk_hooks_t *chunk_hooks)
-{
-
- chunk_hooks_assure_initialized_impl(tsdn, arena, chunk_hooks, false);
-}
-
-bool
-chunk_register(tsdn_t *tsdn, const void *chunk, const extent_node_t *node)
-{
-
- assert(extent_node_addr_get(node) == chunk);
-
- if (rtree_set(&chunks_rtree, (uintptr_t)chunk, node))
- return (true);
- if (config_prof && opt_prof) {
- size_t size = extent_node_size_get(node);
- size_t nadd = (size == 0) ? 1 : size / chunksize;
- size_t cur = atomic_add_z(&curchunks, nadd);
- size_t high = atomic_read_z(&highchunks);
- while (cur > high && atomic_cas_z(&highchunks, high, cur)) {
- /*
- * Don't refresh cur, because it may have decreased
- * since this thread lost the highchunks update race.
- */
- high = atomic_read_z(&highchunks);
- }
- if (cur > high && prof_gdump_get_unlocked())
- prof_gdump(tsdn);
- }
-
- return (false);
-}
-
-void
-chunk_deregister(const void *chunk, const extent_node_t *node)
-{
- bool err;
-
- err = rtree_set(&chunks_rtree, (uintptr_t)chunk, NULL);
- assert(!err);
- if (config_prof && opt_prof) {
- size_t size = extent_node_size_get(node);
- size_t nsub = (size == 0) ? 1 : size / chunksize;
- assert(atomic_read_z(&curchunks) >= nsub);
- atomic_sub_z(&curchunks, nsub);
- }
-}
-
-/*
- * Do first-best-fit chunk selection, i.e. select the lowest chunk that best
- * fits.
- */
-static extent_node_t *
-chunk_first_best_fit(arena_t *arena, extent_tree_t *chunks_szad,
- extent_tree_t *chunks_ad, size_t size)
-{
- extent_node_t key;
-
- assert(size == CHUNK_CEILING(size));
-
- extent_node_init(&key, arena, NULL, size, false, false);
- return (extent_tree_szad_nsearch(chunks_szad, &key));
-}
-
-static void *
-chunk_recycle(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- extent_tree_t *chunks_szad, extent_tree_t *chunks_ad, bool cache,
- void *new_addr, size_t size, size_t alignment, bool *zero, bool *commit,
- bool dalloc_node)
-{
- void *ret;
- extent_node_t *node;
- size_t alloc_size, leadsize, trailsize;
- bool zeroed, committed;
-
- assert(new_addr == NULL || alignment == chunksize);
- /*
- * Cached chunks use the node linkage embedded in their headers, in
- * which case dalloc_node is true, and new_addr is non-NULL because
- * we're operating on a specific chunk.
- */
- assert(dalloc_node || new_addr != NULL);
-
- alloc_size = CHUNK_CEILING(s2u(size + alignment - chunksize));
- /* Beware size_t wrap-around. */
- if (alloc_size < size)
- return (NULL);
- malloc_mutex_lock(tsdn, &arena->chunks_mtx);
- chunk_hooks_assure_initialized_locked(tsdn, arena, chunk_hooks);
- if (new_addr != NULL) {
- extent_node_t key;
- extent_node_init(&key, arena, new_addr, alloc_size, false,
- false);
- node = extent_tree_ad_search(chunks_ad, &key);
- } else {
- node = chunk_first_best_fit(arena, chunks_szad, chunks_ad,
- alloc_size);
- }
- if (node == NULL || (new_addr != NULL && extent_node_size_get(node) <
- size)) {
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
- return (NULL);
- }
- leadsize = ALIGNMENT_CEILING((uintptr_t)extent_node_addr_get(node),
- alignment) - (uintptr_t)extent_node_addr_get(node);
- assert(new_addr == NULL || leadsize == 0);
- assert(extent_node_size_get(node) >= leadsize + size);
- trailsize = extent_node_size_get(node) - leadsize - size;
- ret = (void *)((uintptr_t)extent_node_addr_get(node) + leadsize);
- zeroed = extent_node_zeroed_get(node);
- if (zeroed)
- *zero = true;
- committed = extent_node_committed_get(node);
- if (committed)
- *commit = true;
- /* Split the lead. */
- if (leadsize != 0 &&
- chunk_hooks->split(extent_node_addr_get(node),
- extent_node_size_get(node), leadsize, size, false, arena->ind)) {
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
- return (NULL);
- }
- /* Remove node from the tree. */
- extent_tree_szad_remove(chunks_szad, node);
- extent_tree_ad_remove(chunks_ad, node);
- arena_chunk_cache_maybe_remove(arena, node, cache);
- if (leadsize != 0) {
- /* Insert the leading space as a smaller chunk. */
- extent_node_size_set(node, leadsize);
- extent_tree_szad_insert(chunks_szad, node);
- extent_tree_ad_insert(chunks_ad, node);
- arena_chunk_cache_maybe_insert(arena, node, cache);
- node = NULL;
- }
- if (trailsize != 0) {
- /* Split the trail. */
- if (chunk_hooks->split(ret, size + trailsize, size,
- trailsize, false, arena->ind)) {
- if (dalloc_node && node != NULL)
- arena_node_dalloc(tsdn, arena, node);
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
- chunk_record(tsdn, arena, chunk_hooks, chunks_szad,
- chunks_ad, cache, ret, size + trailsize, zeroed,
- committed);
- return (NULL);
- }
- /* Insert the trailing space as a smaller chunk. */
- if (node == NULL) {
- node = arena_node_alloc(tsdn, arena);
- if (node == NULL) {
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
- chunk_record(tsdn, arena, chunk_hooks,
- chunks_szad, chunks_ad, cache, ret, size +
- trailsize, zeroed, committed);
- return (NULL);
- }
- }
- extent_node_init(node, arena, (void *)((uintptr_t)(ret) + size),
- trailsize, zeroed, committed);
- extent_tree_szad_insert(chunks_szad, node);
- extent_tree_ad_insert(chunks_ad, node);
- arena_chunk_cache_maybe_insert(arena, node, cache);
- node = NULL;
- }
- if (!committed && chunk_hooks->commit(ret, size, 0, size, arena->ind)) {
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
- chunk_record(tsdn, arena, chunk_hooks, chunks_szad, chunks_ad,
- cache, ret, size, zeroed, committed);
- return (NULL);
- }
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
-
- assert(dalloc_node || node != NULL);
- if (dalloc_node && node != NULL)
- arena_node_dalloc(tsdn, arena, node);
- if (*zero) {
- if (!zeroed)
- memset(ret, 0, size);
- else if (config_debug) {
- size_t i;
- size_t *p = (size_t *)(uintptr_t)ret;
-
- for (i = 0; i < size / sizeof(size_t); i++)
- assert(p[i] == 0);
- }
- if (config_valgrind)
- JEMALLOC_VALGRIND_MAKE_MEM_DEFINED(ret, size);
- }
- return (ret);
-}
-
-/*
- * If the caller specifies (!*zero), it is still possible to receive zeroed
- * memory, in which case *zero is toggled to true. arena_chunk_alloc() takes
- * advantage of this to avoid demanding zeroed chunks, but taking advantage of
- * them if they are returned.
- */
-static void *
-chunk_alloc_core(tsdn_t *tsdn, arena_t *arena, void *new_addr, size_t size,
- size_t alignment, bool *zero, bool *commit, dss_prec_t dss_prec)
-{
- void *ret;
-
- assert(size != 0);
- assert((size & chunksize_mask) == 0);
- assert(alignment != 0);
- assert((alignment & chunksize_mask) == 0);
-
- /* "primary" dss. */
- if (have_dss && dss_prec == dss_prec_primary && (ret =
- chunk_alloc_dss(tsdn, arena, new_addr, size, alignment, zero,
- commit)) != NULL)
- return (ret);
- /* mmap. */
- if ((ret = chunk_alloc_mmap(new_addr, size, alignment, zero, commit)) !=
- NULL)
- return (ret);
- /* "secondary" dss. */
- if (have_dss && dss_prec == dss_prec_secondary && (ret =
- chunk_alloc_dss(tsdn, arena, new_addr, size, alignment, zero,
- commit)) != NULL)
- return (ret);
-
- /* All strategies for allocation failed. */
- return (NULL);
-}
-
-void *
-chunk_alloc_base(size_t size)
-{
- void *ret;
- bool zero, commit;
-
- /*
- * Directly call chunk_alloc_mmap() rather than chunk_alloc_core()
- * because it's critical that chunk_alloc_base() return untouched
- * demand-zeroed virtual memory.
- */
- zero = true;
- commit = true;
- ret = chunk_alloc_mmap(NULL, size, chunksize, &zero, &commit);
- if (ret == NULL)
- return (NULL);
- if (config_valgrind)
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ret, size);
-
- return (ret);
-}
-
-void *
-chunk_alloc_cache(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- void *new_addr, size_t size, size_t alignment, bool *zero, bool *commit,
- bool dalloc_node)
-{
- void *ret;
-
- assert(size != 0);
- assert((size & chunksize_mask) == 0);
- assert(alignment != 0);
- assert((alignment & chunksize_mask) == 0);
-
- ret = chunk_recycle(tsdn, arena, chunk_hooks,
- &arena->chunks_szad_cached, &arena->chunks_ad_cached, true,
- new_addr, size, alignment, zero, commit, dalloc_node);
- if (ret == NULL)
- return (NULL);
- if (config_valgrind)
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ret, size);
- return (ret);
-}
-
-static arena_t *
-chunk_arena_get(tsdn_t *tsdn, unsigned arena_ind)
-{
- arena_t *arena;
-
- arena = arena_get(tsdn, arena_ind, false);
- /*
- * The arena we're allocating on behalf of must have been initialized
- * already.
- */
- assert(arena != NULL);
- return (arena);
-}
-
-static void *
-chunk_alloc_default_impl(tsdn_t *tsdn, arena_t *arena, void *new_addr,
- size_t size, size_t alignment, bool *zero, bool *commit)
-{
- void *ret;
-
- ret = chunk_alloc_core(tsdn, arena, new_addr, size, alignment, zero,
- commit, arena->dss_prec);
- if (ret == NULL)
- return (NULL);
- if (config_valgrind)
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ret, size);
-
- return (ret);
-}
-
-static void *
-chunk_alloc_default(void *new_addr, size_t size, size_t alignment, bool *zero,
- bool *commit, unsigned arena_ind)
-{
- tsdn_t *tsdn;
- arena_t *arena;
-
- tsdn = tsdn_fetch();
- arena = chunk_arena_get(tsdn, arena_ind);
-
- return (chunk_alloc_default_impl(tsdn, arena, new_addr, size, alignment,
- zero, commit));
-}
-
-static void *
-chunk_alloc_retained(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- void *new_addr, size_t size, size_t alignment, bool *zero, bool *commit)
-{
- void *ret;
-
- assert(size != 0);
- assert((size & chunksize_mask) == 0);
- assert(alignment != 0);
- assert((alignment & chunksize_mask) == 0);
-
- ret = chunk_recycle(tsdn, arena, chunk_hooks,
- &arena->chunks_szad_retained, &arena->chunks_ad_retained, false,
- new_addr, size, alignment, zero, commit, true);
-
- if (config_stats && ret != NULL)
- arena->stats.retained -= size;
-
- return (ret);
-}
-
-void *
-chunk_alloc_wrapper(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- void *new_addr, size_t size, size_t alignment, bool *zero, bool *commit)
-{
- void *ret;
-
- chunk_hooks_assure_initialized(tsdn, arena, chunk_hooks);
-
- ret = chunk_alloc_retained(tsdn, arena, chunk_hooks, new_addr, size,
- alignment, zero, commit);
- if (ret == NULL) {
- if (chunk_hooks->alloc == chunk_alloc_default) {
- /* Call directly to propagate tsdn. */
- ret = chunk_alloc_default_impl(tsdn, arena, new_addr,
- size, alignment, zero, commit);
- } else {
- ret = chunk_hooks->alloc(new_addr, size, alignment,
- zero, commit, arena->ind);
- }
-
- if (ret == NULL)
- return (NULL);
-
- if (config_valgrind && chunk_hooks->alloc !=
- chunk_alloc_default)
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(ret, chunksize);
- }
-
- return (ret);
-}
-
-static void
-chunk_record(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- extent_tree_t *chunks_szad, extent_tree_t *chunks_ad, bool cache,
- void *chunk, size_t size, bool zeroed, bool committed)
-{
- bool unzeroed;
- extent_node_t *node, *prev;
- extent_node_t key;
-
- assert(!cache || !zeroed);
- unzeroed = cache || !zeroed;
- JEMALLOC_VALGRIND_MAKE_MEM_NOACCESS(chunk, size);
-
- malloc_mutex_lock(tsdn, &arena->chunks_mtx);
- chunk_hooks_assure_initialized_locked(tsdn, arena, chunk_hooks);
- extent_node_init(&key, arena, (void *)((uintptr_t)chunk + size), 0,
- false, false);
- node = extent_tree_ad_nsearch(chunks_ad, &key);
- /* Try to coalesce forward. */
- if (node != NULL && extent_node_addr_get(node) ==
- extent_node_addr_get(&key) && extent_node_committed_get(node) ==
- committed && !chunk_hooks->merge(chunk, size,
- extent_node_addr_get(node), extent_node_size_get(node), false,
- arena->ind)) {
- /*
- * Coalesce chunk with the following address range. This does
- * not change the position within chunks_ad, so only
- * remove/insert from/into chunks_szad.
- */
- extent_tree_szad_remove(chunks_szad, node);
- arena_chunk_cache_maybe_remove(arena, node, cache);
- extent_node_addr_set(node, chunk);
- extent_node_size_set(node, size + extent_node_size_get(node));
- extent_node_zeroed_set(node, extent_node_zeroed_get(node) &&
- !unzeroed);
- extent_tree_szad_insert(chunks_szad, node);
- arena_chunk_cache_maybe_insert(arena, node, cache);
- } else {
- /* Coalescing forward failed, so insert a new node. */
- node = arena_node_alloc(tsdn, arena);
- if (node == NULL) {
- /*
- * Node allocation failed, which is an exceedingly
- * unlikely failure. Leak chunk after making sure its
- * pages have already been purged, so that this is only
- * a virtual memory leak.
- */
- if (cache) {
- chunk_purge_wrapper(tsdn, arena, chunk_hooks,
- chunk, size, 0, size);
- }
- goto label_return;
- }
- extent_node_init(node, arena, chunk, size, !unzeroed,
- committed);
- extent_tree_ad_insert(chunks_ad, node);
- extent_tree_szad_insert(chunks_szad, node);
- arena_chunk_cache_maybe_insert(arena, node, cache);
- }
-
- /* Try to coalesce backward. */
- prev = extent_tree_ad_prev(chunks_ad, node);
- if (prev != NULL && (void *)((uintptr_t)extent_node_addr_get(prev) +
- extent_node_size_get(prev)) == chunk &&
- extent_node_committed_get(prev) == committed &&
- !chunk_hooks->merge(extent_node_addr_get(prev),
- extent_node_size_get(prev), chunk, size, false, arena->ind)) {
- /*
- * Coalesce chunk with the previous address range. This does
- * not change the position within chunks_ad, so only
- * remove/insert node from/into chunks_szad.
- */
- extent_tree_szad_remove(chunks_szad, prev);
- extent_tree_ad_remove(chunks_ad, prev);
- arena_chunk_cache_maybe_remove(arena, prev, cache);
- extent_tree_szad_remove(chunks_szad, node);
- arena_chunk_cache_maybe_remove(arena, node, cache);
- extent_node_addr_set(node, extent_node_addr_get(prev));
- extent_node_size_set(node, extent_node_size_get(prev) +
- extent_node_size_get(node));
- extent_node_zeroed_set(node, extent_node_zeroed_get(prev) &&
- extent_node_zeroed_get(node));
- extent_tree_szad_insert(chunks_szad, node);
- arena_chunk_cache_maybe_insert(arena, node, cache);
-
- arena_node_dalloc(tsdn, arena, prev);
- }
-
-label_return:
- malloc_mutex_unlock(tsdn, &arena->chunks_mtx);
-}
-
-void
-chunk_dalloc_cache(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- void *chunk, size_t size, bool committed)
-{
-
- assert(chunk != NULL);
- assert(CHUNK_ADDR2BASE(chunk) == chunk);
- assert(size != 0);
- assert((size & chunksize_mask) == 0);
-
- chunk_record(tsdn, arena, chunk_hooks, &arena->chunks_szad_cached,
- &arena->chunks_ad_cached, true, chunk, size, false, committed);
- arena_maybe_purge(tsdn, arena);
-}
-
-static bool
-chunk_dalloc_default_impl(void *chunk, size_t size)
-{
-
- if (!have_dss || !chunk_in_dss(chunk))
- return (chunk_dalloc_mmap(chunk, size));
- return (true);
-}
-
-static bool
-chunk_dalloc_default(void *chunk, size_t size, bool committed,
- unsigned arena_ind)
-{
-
- return (chunk_dalloc_default_impl(chunk, size));
-}
-
-void
-chunk_dalloc_wrapper(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- void *chunk, size_t size, bool zeroed, bool committed)
-{
- bool err;
-
- assert(chunk != NULL);
- assert(CHUNK_ADDR2BASE(chunk) == chunk);
- assert(size != 0);
- assert((size & chunksize_mask) == 0);
-
- chunk_hooks_assure_initialized(tsdn, arena, chunk_hooks);
- /* Try to deallocate. */
- if (chunk_hooks->dalloc == chunk_dalloc_default) {
- /* Call directly to propagate tsdn. */
- err = chunk_dalloc_default_impl(chunk, size);
- } else
- err = chunk_hooks->dalloc(chunk, size, committed, arena->ind);
-
- if (!err)
- return;
- /* Try to decommit; purge if that fails. */
- if (committed) {
- committed = chunk_hooks->decommit(chunk, size, 0, size,
- arena->ind);
- }
- zeroed = !committed || !chunk_hooks->purge(chunk, size, 0, size,
- arena->ind);
- chunk_record(tsdn, arena, chunk_hooks, &arena->chunks_szad_retained,
- &arena->chunks_ad_retained, false, chunk, size, zeroed, committed);
-
- if (config_stats)
- arena->stats.retained += size;
-}
-
-static bool
-chunk_commit_default(void *chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
-{
-
- return (pages_commit((void *)((uintptr_t)chunk + (uintptr_t)offset),
- length));
-}
-
-static bool
-chunk_decommit_default(void *chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
-{
-
- return (pages_decommit((void *)((uintptr_t)chunk + (uintptr_t)offset),
- length));
-}
-
-static bool
-chunk_purge_default(void *chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
-{
-
- assert(chunk != NULL);
- assert(CHUNK_ADDR2BASE(chunk) == chunk);
- assert((offset & PAGE_MASK) == 0);
- assert(length != 0);
- assert((length & PAGE_MASK) == 0);
-
- return (pages_purge((void *)((uintptr_t)chunk + (uintptr_t)offset),
- length));
-}
-
-bool
-chunk_purge_wrapper(tsdn_t *tsdn, arena_t *arena, chunk_hooks_t *chunk_hooks,
- void *chunk, size_t size, size_t offset, size_t length)
-{
-
- chunk_hooks_assure_initialized(tsdn, arena, chunk_hooks);
- return (chunk_hooks->purge(chunk, size, offset, length, arena->ind));
-}
-
-static bool
-chunk_split_default(void *chunk, size_t size, size_t size_a, size_t size_b,
- bool committed, unsigned arena_ind)
-{
-
- if (!maps_coalesce)
- return (true);
- return (false);
-}
-
-static bool
-chunk_merge_default_impl(void *chunk_a, void *chunk_b)
-{
-
- if (!maps_coalesce)
- return (true);
- if (have_dss && !chunk_dss_mergeable(chunk_a, chunk_b))
- return (true);
-
- return (false);
-}
-
-static bool
-chunk_merge_default(void *chunk_a, size_t size_a, void *chunk_b, size_t size_b,
- bool committed, unsigned arena_ind)
-{
-
- return (chunk_merge_default_impl(chunk_a, chunk_b));
-}
-
-static rtree_node_elm_t *
-chunks_rtree_node_alloc(size_t nelms)
-{
-
- return ((rtree_node_elm_t *)base_alloc(TSDN_NULL, nelms *
- sizeof(rtree_node_elm_t)));
-}
-
-bool
-chunk_boot(void)
-{
-#ifdef _WIN32
- SYSTEM_INFO info;
- GetSystemInfo(&info);
-
- /*
- * Verify actual page size is equal to or an integral multiple of
- * configured page size.
- */
- if (info.dwPageSize & ((1U << LG_PAGE) - 1))
- return (true);
-
- /*
- * Configure chunksize (if not set) to match granularity (usually 64K),
- * so pages_map will always take fast path.
- */
- if (!opt_lg_chunk) {
- opt_lg_chunk = ffs_u((unsigned)info.dwAllocationGranularity)
- - 1;
- }
-#else
- if (!opt_lg_chunk)
- opt_lg_chunk = LG_CHUNK_DEFAULT;
-#endif
-
- /* Set variables according to the value of opt_lg_chunk. */
- chunksize = (ZU(1) << opt_lg_chunk);
- assert(chunksize >= PAGE);
- chunksize_mask = chunksize - 1;
- chunk_npages = (chunksize >> LG_PAGE);
-
- if (have_dss)
- chunk_dss_boot();
- if (rtree_new(&chunks_rtree, (unsigned)((ZU(1) << (LG_SIZEOF_PTR+3)) -
- opt_lg_chunk), chunks_rtree_node_alloc, NULL))
- return (true);
-
- return (false);
-}
diff --git a/memory/jemalloc/src/src/chunk_dss.c b/memory/jemalloc/src/src/chunk_dss.c
deleted file mode 100644
index 85a13548f..000000000
--- a/memory/jemalloc/src/src/chunk_dss.c
+++ /dev/null
@@ -1,237 +0,0 @@
-#define JEMALLOC_CHUNK_DSS_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-/******************************************************************************/
-/* Data. */
-
-const char *dss_prec_names[] = {
- "disabled",
- "primary",
- "secondary",
- "N/A"
-};
-
-/*
- * Current dss precedence default, used when creating new arenas. NB: This is
- * stored as unsigned rather than dss_prec_t because in principle there's no
- * guarantee that sizeof(dss_prec_t) is the same as sizeof(unsigned), and we use
- * atomic operations to synchronize the setting.
- */
-static unsigned dss_prec_default = (unsigned)DSS_PREC_DEFAULT;
-
-/* Base address of the DSS. */
-static void *dss_base;
-/* Atomic boolean indicating whether the DSS is exhausted. */
-static unsigned dss_exhausted;
-/* Atomic current upper limit on DSS addresses. */
-static void *dss_max;
-
-/******************************************************************************/
-
-static void *
-chunk_dss_sbrk(intptr_t increment)
-{
-
-#ifdef JEMALLOC_DSS
- return (sbrk(increment));
-#else
- not_implemented();
- return (NULL);
-#endif
-}
-
-dss_prec_t
-chunk_dss_prec_get(void)
-{
- dss_prec_t ret;
-
- if (!have_dss)
- return (dss_prec_disabled);
- ret = (dss_prec_t)atomic_read_u(&dss_prec_default);
- return (ret);
-}
-
-bool
-chunk_dss_prec_set(dss_prec_t dss_prec)
-{
-
- if (!have_dss)
- return (dss_prec != dss_prec_disabled);
- atomic_write_u(&dss_prec_default, (unsigned)dss_prec);
- return (false);
-}
-
-static void *
-chunk_dss_max_update(void *new_addr)
-{
- void *max_cur;
- spin_t spinner;
-
- /*
- * Get the current end of the DSS as max_cur and assure that dss_max is
- * up to date.
- */
- spin_init(&spinner);
- while (true) {
- void *max_prev = atomic_read_p(&dss_max);
-
- max_cur = chunk_dss_sbrk(0);
- if ((uintptr_t)max_prev > (uintptr_t)max_cur) {
- /*
- * Another thread optimistically updated dss_max. Wait
- * for it to finish.
- */
- spin_adaptive(&spinner);
- continue;
- }
- if (!atomic_cas_p(&dss_max, max_prev, max_cur))
- break;
- }
- /* Fixed new_addr can only be supported if it is at the edge of DSS. */
- if (new_addr != NULL && max_cur != new_addr)
- return (NULL);
-
- return (max_cur);
-}
-
-void *
-chunk_alloc_dss(tsdn_t *tsdn, arena_t *arena, void *new_addr, size_t size,
- size_t alignment, bool *zero, bool *commit)
-{
- cassert(have_dss);
- assert(size > 0 && (size & chunksize_mask) == 0);
- assert(alignment > 0 && (alignment & chunksize_mask) == 0);
-
- /*
- * sbrk() uses a signed increment argument, so take care not to
- * interpret a huge allocation request as a negative increment.
- */
- if ((intptr_t)size < 0)
- return (NULL);
-
- if (!atomic_read_u(&dss_exhausted)) {
- /*
- * The loop is necessary to recover from races with other
- * threads that are using the DSS for something other than
- * malloc.
- */
- while (true) {
- void *ret, *cpad, *max_cur, *dss_next, *dss_prev;
- size_t gap_size, cpad_size;
- intptr_t incr;
-
- max_cur = chunk_dss_max_update(new_addr);
- if (max_cur == NULL)
- goto label_oom;
-
- /*
- * Calculate how much padding is necessary to
- * chunk-align the end of the DSS.
- */
- gap_size = (chunksize - CHUNK_ADDR2OFFSET(dss_max)) &
- chunksize_mask;
- /*
- * Compute how much chunk-aligned pad space (if any) is
- * necessary to satisfy alignment. This space can be
- * recycled for later use.
- */
- cpad = (void *)((uintptr_t)dss_max + gap_size);
- ret = (void *)ALIGNMENT_CEILING((uintptr_t)dss_max,
- alignment);
- cpad_size = (uintptr_t)ret - (uintptr_t)cpad;
- dss_next = (void *)((uintptr_t)ret + size);
- if ((uintptr_t)ret < (uintptr_t)dss_max ||
- (uintptr_t)dss_next < (uintptr_t)dss_max)
- goto label_oom; /* Wrap-around. */
- incr = gap_size + cpad_size + size;
-
- /*
- * Optimistically update dss_max, and roll back below if
- * sbrk() fails. No other thread will try to extend the
- * DSS while dss_max is greater than the current DSS
- * max reported by sbrk(0).
- */
- if (atomic_cas_p(&dss_max, max_cur, dss_next))
- continue;
-
- /* Try to allocate. */
- dss_prev = chunk_dss_sbrk(incr);
- if (dss_prev == max_cur) {
- /* Success. */
- if (cpad_size != 0) {
- chunk_hooks_t chunk_hooks =
- CHUNK_HOOKS_INITIALIZER;
- chunk_dalloc_wrapper(tsdn, arena,
- &chunk_hooks, cpad, cpad_size,
- false, true);
- }
- if (*zero) {
- JEMALLOC_VALGRIND_MAKE_MEM_UNDEFINED(
- ret, size);
- memset(ret, 0, size);
- }
- if (!*commit)
- *commit = pages_decommit(ret, size);
- return (ret);
- }
-
- /*
- * Failure, whether due to OOM or a race with a raw
- * sbrk() call from outside the allocator. Try to roll
- * back optimistic dss_max update; if rollback fails,
- * it's due to another caller of this function having
- * succeeded since this invocation started, in which
- * case rollback is not necessary.
- */
- atomic_cas_p(&dss_max, dss_next, max_cur);
- if (dss_prev == (void *)-1) {
- /* OOM. */
- atomic_write_u(&dss_exhausted, (unsigned)true);
- goto label_oom;
- }
- }
- }
-label_oom:
- return (NULL);
-}
-
-static bool
-chunk_in_dss_helper(void *chunk, void *max)
-{
-
- return ((uintptr_t)chunk >= (uintptr_t)dss_base && (uintptr_t)chunk <
- (uintptr_t)max);
-}
-
-bool
-chunk_in_dss(void *chunk)
-{
-
- cassert(have_dss);
-
- return (chunk_in_dss_helper(chunk, atomic_read_p(&dss_max)));
-}
-
-bool
-chunk_dss_mergeable(void *chunk_a, void *chunk_b)
-{
- void *max;
-
- cassert(have_dss);
-
- max = atomic_read_p(&dss_max);
- return (chunk_in_dss_helper(chunk_a, max) ==
- chunk_in_dss_helper(chunk_b, max));
-}
-
-void
-chunk_dss_boot(void)
-{
-
- cassert(have_dss);
-
- dss_base = chunk_dss_sbrk(0);
- dss_exhausted = (unsigned)(dss_base == (void *)-1);
- dss_max = dss_base;
-}
-
-/******************************************************************************/
diff --git a/memory/jemalloc/src/src/chunk_mmap.c b/memory/jemalloc/src/src/chunk_mmap.c
deleted file mode 100644
index 73fc497af..000000000
--- a/memory/jemalloc/src/src/chunk_mmap.c
+++ /dev/null
@@ -1,78 +0,0 @@
-#define JEMALLOC_CHUNK_MMAP_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-
-static void *
-chunk_alloc_mmap_slow(size_t size, size_t alignment, bool *zero, bool *commit)
-{
- void *ret;
- size_t alloc_size;
-
- alloc_size = size + alignment - PAGE;
- /* Beware size_t wrap-around. */
- if (alloc_size < size)
- return (NULL);
- do {
- void *pages;
- size_t leadsize;
- pages = pages_map(NULL, alloc_size, commit);
- if (pages == NULL)
- return (NULL);
- leadsize = ALIGNMENT_CEILING((uintptr_t)pages, alignment) -
- (uintptr_t)pages;
- ret = pages_trim(pages, alloc_size, leadsize, size, commit);
- } while (ret == NULL);
-
- assert(ret != NULL);
- *zero = true;
- return (ret);
-}
-
-void *
-chunk_alloc_mmap(void *new_addr, size_t size, size_t alignment, bool *zero,
- bool *commit)
-{
- void *ret;
- size_t offset;
-
- /*
- * Ideally, there would be a way to specify alignment to mmap() (like
- * NetBSD has), but in the absence of such a feature, we have to work
- * hard to efficiently create aligned mappings. The reliable, but
- * slow method is to create a mapping that is over-sized, then trim the
- * excess. However, that always results in one or two calls to
- * pages_unmap().
- *
- * Optimistically try mapping precisely the right amount before falling
- * back to the slow method, with the expectation that the optimistic
- * approach works most of the time.
- */
-
- assert(alignment != 0);
- assert((alignment & chunksize_mask) == 0);
-
- ret = pages_map(new_addr, size, commit);
- if (ret == NULL || ret == new_addr)
- return (ret);
- assert(new_addr == NULL);
- offset = ALIGNMENT_ADDR2OFFSET(ret, alignment);
- if (offset != 0) {
- pages_unmap(ret, size);
- return (chunk_alloc_mmap_slow(size, alignment, zero, commit));
- }
-
- assert(ret != NULL);
- *zero = true;
- return (ret);
-}
-
-bool
-chunk_dalloc_mmap(void *chunk, size_t size)
-{
-
- if (config_munmap)
- pages_unmap(chunk, size);
-
- return (!config_munmap);
-}
diff --git a/memory/jemalloc/src/src/ckh.c b/memory/jemalloc/src/src/ckh.c
deleted file mode 100644
index 159bd8ae1..000000000
--- a/memory/jemalloc/src/src/ckh.c
+++ /dev/null
@@ -1,569 +0,0 @@
-/*
- *******************************************************************************
- * Implementation of (2^1+,2) cuckoo hashing, where 2^1+ indicates that each
- * hash bucket contains 2^n cells, for n >= 1, and 2 indicates that two hash
- * functions are employed. The original cuckoo hashing algorithm was described
- * in:
- *
- * Pagh, R., F.F. Rodler (2004) Cuckoo Hashing. Journal of Algorithms
- * 51(2):122-144.
- *
- * Generalization of cuckoo hashing was discussed in:
- *
- * Erlingsson, U., M. Manasse, F. McSherry (2006) A cool and practical
- * alternative to traditional hash tables. In Proceedings of the 7th
- * Workshop on Distributed Data and Structures (WDAS'06), Santa Clara, CA,
- * January 2006.
- *
- * This implementation uses precisely two hash functions because that is the
- * fewest that can work, and supporting multiple hashes is an implementation
- * burden. Here is a reproduction of Figure 1 from Erlingsson et al. (2006)
- * that shows approximate expected maximum load factors for various
- * configurations:
- *
- * | #cells/bucket |
- * #hashes | 1 | 2 | 4 | 8 |
- * --------+-------+-------+-------+-------+
- * 1 | 0.006 | 0.006 | 0.03 | 0.12 |
- * 2 | 0.49 | 0.86 |>0.93< |>0.96< |
- * 3 | 0.91 | 0.97 | 0.98 | 0.999 |
- * 4 | 0.97 | 0.99 | 0.999 | |
- *
- * The number of cells per bucket is chosen such that a bucket fits in one cache
- * line. So, on 32- and 64-bit systems, we use (8,2) and (4,2) cuckoo hashing,
- * respectively.
- *
- ******************************************************************************/
-#define JEMALLOC_CKH_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Function prototypes for non-inline static functions. */
-
-static bool ckh_grow(tsd_t *tsd, ckh_t *ckh);
-static void ckh_shrink(tsd_t *tsd, ckh_t *ckh);
-
-/******************************************************************************/
-
-/*
- * Search bucket for key and return the cell number if found; SIZE_T_MAX
- * otherwise.
- */
-JEMALLOC_INLINE_C size_t
-ckh_bucket_search(ckh_t *ckh, size_t bucket, const void *key)
-{
- ckhc_t *cell;
- unsigned i;
-
- for (i = 0; i < (ZU(1) << LG_CKH_BUCKET_CELLS); i++) {
- cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) + i];
- if (cell->key != NULL && ckh->keycomp(key, cell->key))
- return ((bucket << LG_CKH_BUCKET_CELLS) + i);
- }
-
- return (SIZE_T_MAX);
-}
-
-/*
- * Search table for key and return cell number if found; SIZE_T_MAX otherwise.
- */
-JEMALLOC_INLINE_C size_t
-ckh_isearch(ckh_t *ckh, const void *key)
-{
- size_t hashes[2], bucket, cell;
-
- assert(ckh != NULL);
-
- ckh->hash(key, hashes);
-
- /* Search primary bucket. */
- bucket = hashes[0] & ((ZU(1) << ckh->lg_curbuckets) - 1);
- cell = ckh_bucket_search(ckh, bucket, key);
- if (cell != SIZE_T_MAX)
- return (cell);
-
- /* Search secondary bucket. */
- bucket = hashes[1] & ((ZU(1) << ckh->lg_curbuckets) - 1);
- cell = ckh_bucket_search(ckh, bucket, key);
- return (cell);
-}
-
-JEMALLOC_INLINE_C bool
-ckh_try_bucket_insert(ckh_t *ckh, size_t bucket, const void *key,
- const void *data)
-{
- ckhc_t *cell;
- unsigned offset, i;
-
- /*
- * Cycle through the cells in the bucket, starting at a random position.
- * The randomness avoids worst-case search overhead as buckets fill up.
- */
- offset = (unsigned)prng_lg_range_u64(&ckh->prng_state,
- LG_CKH_BUCKET_CELLS);
- for (i = 0; i < (ZU(1) << LG_CKH_BUCKET_CELLS); i++) {
- cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) +
- ((i + offset) & ((ZU(1) << LG_CKH_BUCKET_CELLS) - 1))];
- if (cell->key == NULL) {
- cell->key = key;
- cell->data = data;
- ckh->count++;
- return (false);
- }
- }
-
- return (true);
-}
-
-/*
- * No space is available in bucket. Randomly evict an item, then try to find an
- * alternate location for that item. Iteratively repeat this
- * eviction/relocation procedure until either success or detection of an
- * eviction/relocation bucket cycle.
- */
-JEMALLOC_INLINE_C bool
-ckh_evict_reloc_insert(ckh_t *ckh, size_t argbucket, void const **argkey,
- void const **argdata)
-{
- const void *key, *data, *tkey, *tdata;
- ckhc_t *cell;
- size_t hashes[2], bucket, tbucket;
- unsigned i;
-
- bucket = argbucket;
- key = *argkey;
- data = *argdata;
- while (true) {
- /*
- * Choose a random item within the bucket to evict. This is
- * critical to correct function, because without (eventually)
- * evicting all items within a bucket during iteration, it
- * would be possible to get stuck in an infinite loop if there
- * were an item for which both hashes indicated the same
- * bucket.
- */
- i = (unsigned)prng_lg_range_u64(&ckh->prng_state,
- LG_CKH_BUCKET_CELLS);
- cell = &ckh->tab[(bucket << LG_CKH_BUCKET_CELLS) + i];
- assert(cell->key != NULL);
-
- /* Swap cell->{key,data} and {key,data} (evict). */
- tkey = cell->key; tdata = cell->data;
- cell->key = key; cell->data = data;
- key = tkey; data = tdata;
-
-#ifdef CKH_COUNT
- ckh->nrelocs++;
-#endif
-
- /* Find the alternate bucket for the evicted item. */
- ckh->hash(key, hashes);
- tbucket = hashes[1] & ((ZU(1) << ckh->lg_curbuckets) - 1);
- if (tbucket == bucket) {
- tbucket = hashes[0] & ((ZU(1) << ckh->lg_curbuckets)
- - 1);
- /*
- * It may be that (tbucket == bucket) still, if the
- * item's hashes both indicate this bucket. However,
- * we are guaranteed to eventually escape this bucket
- * during iteration, assuming pseudo-random item
- * selection (true randomness would make infinite
- * looping a remote possibility). The reason we can
- * never get trapped forever is that there are two
- * cases:
- *
- * 1) This bucket == argbucket, so we will quickly
- * detect an eviction cycle and terminate.
- * 2) An item was evicted to this bucket from another,
- * which means that at least one item in this bucket
- * has hashes that indicate distinct buckets.
- */
- }
- /* Check for a cycle. */
- if (tbucket == argbucket) {
- *argkey = key;
- *argdata = data;
- return (true);
- }
-
- bucket = tbucket;
- if (!ckh_try_bucket_insert(ckh, bucket, key, data))
- return (false);
- }
-}
-
-JEMALLOC_INLINE_C bool
-ckh_try_insert(ckh_t *ckh, void const**argkey, void const**argdata)
-{
- size_t hashes[2], bucket;
- const void *key = *argkey;
- const void *data = *argdata;
-
- ckh->hash(key, hashes);
-
- /* Try to insert in primary bucket. */
- bucket = hashes[0] & ((ZU(1) << ckh->lg_curbuckets) - 1);
- if (!ckh_try_bucket_insert(ckh, bucket, key, data))
- return (false);
-
- /* Try to insert in secondary bucket. */
- bucket = hashes[1] & ((ZU(1) << ckh->lg_curbuckets) - 1);
- if (!ckh_try_bucket_insert(ckh, bucket, key, data))
- return (false);
-
- /*
- * Try to find a place for this item via iterative eviction/relocation.
- */
- return (ckh_evict_reloc_insert(ckh, bucket, argkey, argdata));
-}
-
-/*
- * Try to rebuild the hash table from scratch by inserting all items from the
- * old table into the new.
- */
-JEMALLOC_INLINE_C bool
-ckh_rebuild(ckh_t *ckh, ckhc_t *aTab)
-{
- size_t count, i, nins;
- const void *key, *data;
-
- count = ckh->count;
- ckh->count = 0;
- for (i = nins = 0; nins < count; i++) {
- if (aTab[i].key != NULL) {
- key = aTab[i].key;
- data = aTab[i].data;
- if (ckh_try_insert(ckh, &key, &data)) {
- ckh->count = count;
- return (true);
- }
- nins++;
- }
- }
-
- return (false);
-}
-
-static bool
-ckh_grow(tsd_t *tsd, ckh_t *ckh)
-{
- bool ret;
- ckhc_t *tab, *ttab;
- unsigned lg_prevbuckets, lg_curcells;
-
-#ifdef CKH_COUNT
- ckh->ngrows++;
-#endif
-
- /*
- * It is possible (though unlikely, given well behaved hashes) that the
- * table will have to be doubled more than once in order to create a
- * usable table.
- */
- lg_prevbuckets = ckh->lg_curbuckets;
- lg_curcells = ckh->lg_curbuckets + LG_CKH_BUCKET_CELLS;
- while (true) {
- size_t usize;
-
- lg_curcells++;
- usize = sa2u(sizeof(ckhc_t) << lg_curcells, CACHELINE);
- if (unlikely(usize == 0 || usize > HUGE_MAXCLASS)) {
- ret = true;
- goto label_return;
- }
- tab = (ckhc_t *)ipallocztm(tsd_tsdn(tsd), usize, CACHELINE,
- true, NULL, true, arena_ichoose(tsd, NULL));
- if (tab == NULL) {
- ret = true;
- goto label_return;
- }
- /* Swap in new table. */
- ttab = ckh->tab;
- ckh->tab = tab;
- tab = ttab;
- ckh->lg_curbuckets = lg_curcells - LG_CKH_BUCKET_CELLS;
-
- if (!ckh_rebuild(ckh, tab)) {
- idalloctm(tsd_tsdn(tsd), tab, NULL, true, true);
- break;
- }
-
- /* Rebuilding failed, so back out partially rebuilt table. */
- idalloctm(tsd_tsdn(tsd), ckh->tab, NULL, true, true);
- ckh->tab = tab;
- ckh->lg_curbuckets = lg_prevbuckets;
- }
-
- ret = false;
-label_return:
- return (ret);
-}
-
-static void
-ckh_shrink(tsd_t *tsd, ckh_t *ckh)
-{
- ckhc_t *tab, *ttab;
- size_t usize;
- unsigned lg_prevbuckets, lg_curcells;
-
- /*
- * It is possible (though unlikely, given well behaved hashes) that the
- * table rebuild will fail.
- */
- lg_prevbuckets = ckh->lg_curbuckets;
- lg_curcells = ckh->lg_curbuckets + LG_CKH_BUCKET_CELLS - 1;
- usize = sa2u(sizeof(ckhc_t) << lg_curcells, CACHELINE);
- if (unlikely(usize == 0 || usize > HUGE_MAXCLASS))
- return;
- tab = (ckhc_t *)ipallocztm(tsd_tsdn(tsd), usize, CACHELINE, true, NULL,
- true, arena_ichoose(tsd, NULL));
- if (tab == NULL) {
- /*
- * An OOM error isn't worth propagating, since it doesn't
- * prevent this or future operations from proceeding.
- */
- return;
- }
- /* Swap in new table. */
- ttab = ckh->tab;
- ckh->tab = tab;
- tab = ttab;
- ckh->lg_curbuckets = lg_curcells - LG_CKH_BUCKET_CELLS;
-
- if (!ckh_rebuild(ckh, tab)) {
- idalloctm(tsd_tsdn(tsd), tab, NULL, true, true);
-#ifdef CKH_COUNT
- ckh->nshrinks++;
-#endif
- return;
- }
-
- /* Rebuilding failed, so back out partially rebuilt table. */
- idalloctm(tsd_tsdn(tsd), ckh->tab, NULL, true, true);
- ckh->tab = tab;
- ckh->lg_curbuckets = lg_prevbuckets;
-#ifdef CKH_COUNT
- ckh->nshrinkfails++;
-#endif
-}
-
-bool
-ckh_new(tsd_t *tsd, ckh_t *ckh, size_t minitems, ckh_hash_t *hash,
- ckh_keycomp_t *keycomp)
-{
- bool ret;
- size_t mincells, usize;
- unsigned lg_mincells;
-
- assert(minitems > 0);
- assert(hash != NULL);
- assert(keycomp != NULL);
-
-#ifdef CKH_COUNT
- ckh->ngrows = 0;
- ckh->nshrinks = 0;
- ckh->nshrinkfails = 0;
- ckh->ninserts = 0;
- ckh->nrelocs = 0;
-#endif
- ckh->prng_state = 42; /* Value doesn't really matter. */
- ckh->count = 0;
-
- /*
- * Find the minimum power of 2 that is large enough to fit minitems
- * entries. We are using (2+,2) cuckoo hashing, which has an expected
- * maximum load factor of at least ~0.86, so 0.75 is a conservative load
- * factor that will typically allow mincells items to fit without ever
- * growing the table.
- */
- assert(LG_CKH_BUCKET_CELLS > 0);
- mincells = ((minitems + (3 - (minitems % 3))) / 3) << 2;
- for (lg_mincells = LG_CKH_BUCKET_CELLS;
- (ZU(1) << lg_mincells) < mincells;
- lg_mincells++)
- ; /* Do nothing. */
- ckh->lg_minbuckets = lg_mincells - LG_CKH_BUCKET_CELLS;
- ckh->lg_curbuckets = lg_mincells - LG_CKH_BUCKET_CELLS;
- ckh->hash = hash;
- ckh->keycomp = keycomp;
-
- usize = sa2u(sizeof(ckhc_t) << lg_mincells, CACHELINE);
- if (unlikely(usize == 0 || usize > HUGE_MAXCLASS)) {
- ret = true;
- goto label_return;
- }
- ckh->tab = (ckhc_t *)ipallocztm(tsd_tsdn(tsd), usize, CACHELINE, true,
- NULL, true, arena_ichoose(tsd, NULL));
- if (ckh->tab == NULL) {
- ret = true;
- goto label_return;
- }
-
- ret = false;
-label_return:
- return (ret);
-}
-
-void
-ckh_delete(tsd_t *tsd, ckh_t *ckh)
-{
-
- assert(ckh != NULL);
-
-#ifdef CKH_VERBOSE
- malloc_printf(
- "%s(%p): ngrows: %"FMTu64", nshrinks: %"FMTu64","
- " nshrinkfails: %"FMTu64", ninserts: %"FMTu64","
- " nrelocs: %"FMTu64"\n", __func__, ckh,
- (unsigned long long)ckh->ngrows,
- (unsigned long long)ckh->nshrinks,
- (unsigned long long)ckh->nshrinkfails,
- (unsigned long long)ckh->ninserts,
- (unsigned long long)ckh->nrelocs);
-#endif
-
- idalloctm(tsd_tsdn(tsd), ckh->tab, NULL, true, true);
- if (config_debug)
- memset(ckh, JEMALLOC_FREE_JUNK, sizeof(ckh_t));
-}
-
-size_t
-ckh_count(ckh_t *ckh)
-{
-
- assert(ckh != NULL);
-
- return (ckh->count);
-}
-
-bool
-ckh_iter(ckh_t *ckh, size_t *tabind, void **key, void **data)
-{
- size_t i, ncells;
-
- for (i = *tabind, ncells = (ZU(1) << (ckh->lg_curbuckets +
- LG_CKH_BUCKET_CELLS)); i < ncells; i++) {
- if (ckh->tab[i].key != NULL) {
- if (key != NULL)
- *key = (void *)ckh->tab[i].key;
- if (data != NULL)
- *data = (void *)ckh->tab[i].data;
- *tabind = i + 1;
- return (false);
- }
- }
-
- return (true);
-}
-
-bool
-ckh_insert(tsd_t *tsd, ckh_t *ckh, const void *key, const void *data)
-{
- bool ret;
-
- assert(ckh != NULL);
- assert(ckh_search(ckh, key, NULL, NULL));
-
-#ifdef CKH_COUNT
- ckh->ninserts++;
-#endif
-
- while (ckh_try_insert(ckh, &key, &data)) {
- if (ckh_grow(tsd, ckh)) {
- ret = true;
- goto label_return;
- }
- }
-
- ret = false;
-label_return:
- return (ret);
-}
-
-bool
-ckh_remove(tsd_t *tsd, ckh_t *ckh, const void *searchkey, void **key,
- void **data)
-{
- size_t cell;
-
- assert(ckh != NULL);
-
- cell = ckh_isearch(ckh, searchkey);
- if (cell != SIZE_T_MAX) {
- if (key != NULL)
- *key = (void *)ckh->tab[cell].key;
- if (data != NULL)
- *data = (void *)ckh->tab[cell].data;
- ckh->tab[cell].key = NULL;
- ckh->tab[cell].data = NULL; /* Not necessary. */
-
- ckh->count--;
- /* Try to halve the table if it is less than 1/4 full. */
- if (ckh->count < (ZU(1) << (ckh->lg_curbuckets
- + LG_CKH_BUCKET_CELLS - 2)) && ckh->lg_curbuckets
- > ckh->lg_minbuckets) {
- /* Ignore error due to OOM. */
- ckh_shrink(tsd, ckh);
- }
-
- return (false);
- }
-
- return (true);
-}
-
-bool
-ckh_search(ckh_t *ckh, const void *searchkey, void **key, void **data)
-{
- size_t cell;
-
- assert(ckh != NULL);
-
- cell = ckh_isearch(ckh, searchkey);
- if (cell != SIZE_T_MAX) {
- if (key != NULL)
- *key = (void *)ckh->tab[cell].key;
- if (data != NULL)
- *data = (void *)ckh->tab[cell].data;
- return (false);
- }
-
- return (true);
-}
-
-void
-ckh_string_hash(const void *key, size_t r_hash[2])
-{
-
- hash(key, strlen((const char *)key), 0x94122f33U, r_hash);
-}
-
-bool
-ckh_string_keycomp(const void *k1, const void *k2)
-{
-
- assert(k1 != NULL);
- assert(k2 != NULL);
-
- return (strcmp((char *)k1, (char *)k2) ? false : true);
-}
-
-void
-ckh_pointer_hash(const void *key, size_t r_hash[2])
-{
- union {
- const void *v;
- size_t i;
- } u;
-
- assert(sizeof(u.v) == sizeof(u.i));
- u.v = key;
- hash(&u.i, sizeof(u.i), 0xd983396eU, r_hash);
-}
-
-bool
-ckh_pointer_keycomp(const void *k1, const void *k2)
-{
-
- return ((k1 == k2) ? true : false);
-}
diff --git a/memory/jemalloc/src/src/ctl.c b/memory/jemalloc/src/src/ctl.c
deleted file mode 100644
index bc78b2055..000000000
--- a/memory/jemalloc/src/src/ctl.c
+++ /dev/null
@@ -1,2254 +0,0 @@
-#define JEMALLOC_CTL_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Data. */
-
-/*
- * ctl_mtx protects the following:
- * - ctl_stats.*
- */
-static malloc_mutex_t ctl_mtx;
-static bool ctl_initialized;
-static uint64_t ctl_epoch;
-static ctl_stats_t ctl_stats;
-
-/******************************************************************************/
-/* Helpers for named and indexed nodes. */
-
-JEMALLOC_INLINE_C const ctl_named_node_t *
-ctl_named_node(const ctl_node_t *node)
-{
-
- return ((node->named) ? (const ctl_named_node_t *)node : NULL);
-}
-
-JEMALLOC_INLINE_C const ctl_named_node_t *
-ctl_named_children(const ctl_named_node_t *node, size_t index)
-{
- const ctl_named_node_t *children = ctl_named_node(node->children);
-
- return (children ? &children[index] : NULL);
-}
-
-JEMALLOC_INLINE_C const ctl_indexed_node_t *
-ctl_indexed_node(const ctl_node_t *node)
-{
-
- return (!node->named ? (const ctl_indexed_node_t *)node : NULL);
-}
-
-/******************************************************************************/
-/* Function prototypes for non-inline static functions. */
-
-#define CTL_PROTO(n) \
-static int n##_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, \
- void *oldp, size_t *oldlenp, void *newp, size_t newlen);
-
-#define INDEX_PROTO(n) \
-static const ctl_named_node_t *n##_index(tsdn_t *tsdn, \
- const size_t *mib, size_t miblen, size_t i);
-
-static bool ctl_arena_init(ctl_arena_stats_t *astats);
-static void ctl_arena_clear(ctl_arena_stats_t *astats);
-static void ctl_arena_stats_amerge(tsdn_t *tsdn, ctl_arena_stats_t *cstats,
- arena_t *arena);
-static void ctl_arena_stats_smerge(ctl_arena_stats_t *sstats,
- ctl_arena_stats_t *astats);
-static void ctl_arena_refresh(tsdn_t *tsdn, arena_t *arena, unsigned i);
-static bool ctl_grow(tsdn_t *tsdn);
-static void ctl_refresh(tsdn_t *tsdn);
-static bool ctl_init(tsdn_t *tsdn);
-static int ctl_lookup(tsdn_t *tsdn, const char *name,
- ctl_node_t const **nodesp, size_t *mibp, size_t *depthp);
-
-CTL_PROTO(version)
-CTL_PROTO(epoch)
-CTL_PROTO(thread_tcache_enabled)
-CTL_PROTO(thread_tcache_flush)
-CTL_PROTO(thread_prof_name)
-CTL_PROTO(thread_prof_active)
-CTL_PROTO(thread_arena)
-CTL_PROTO(thread_allocated)
-CTL_PROTO(thread_allocatedp)
-CTL_PROTO(thread_deallocated)
-CTL_PROTO(thread_deallocatedp)
-CTL_PROTO(config_cache_oblivious)
-CTL_PROTO(config_debug)
-CTL_PROTO(config_fill)
-CTL_PROTO(config_lazy_lock)
-CTL_PROTO(config_malloc_conf)
-CTL_PROTO(config_munmap)
-CTL_PROTO(config_prof)
-CTL_PROTO(config_prof_libgcc)
-CTL_PROTO(config_prof_libunwind)
-CTL_PROTO(config_stats)
-CTL_PROTO(config_tcache)
-CTL_PROTO(config_tls)
-CTL_PROTO(config_utrace)
-CTL_PROTO(config_valgrind)
-CTL_PROTO(config_xmalloc)
-CTL_PROTO(opt_abort)
-CTL_PROTO(opt_dss)
-CTL_PROTO(opt_lg_chunk)
-CTL_PROTO(opt_narenas)
-CTL_PROTO(opt_purge)
-CTL_PROTO(opt_lg_dirty_mult)
-CTL_PROTO(opt_decay_time)
-CTL_PROTO(opt_stats_print)
-CTL_PROTO(opt_junk)
-CTL_PROTO(opt_zero)
-CTL_PROTO(opt_quarantine)
-CTL_PROTO(opt_redzone)
-CTL_PROTO(opt_utrace)
-CTL_PROTO(opt_xmalloc)
-CTL_PROTO(opt_tcache)
-CTL_PROTO(opt_lg_tcache_max)
-CTL_PROTO(opt_prof)
-CTL_PROTO(opt_prof_prefix)
-CTL_PROTO(opt_prof_active)
-CTL_PROTO(opt_prof_thread_active_init)
-CTL_PROTO(opt_lg_prof_sample)
-CTL_PROTO(opt_lg_prof_interval)
-CTL_PROTO(opt_prof_gdump)
-CTL_PROTO(opt_prof_final)
-CTL_PROTO(opt_prof_leak)
-CTL_PROTO(opt_prof_accum)
-CTL_PROTO(tcache_create)
-CTL_PROTO(tcache_flush)
-CTL_PROTO(tcache_destroy)
-static void arena_i_purge(tsdn_t *tsdn, unsigned arena_ind, bool all);
-CTL_PROTO(arena_i_purge)
-CTL_PROTO(arena_i_decay)
-CTL_PROTO(arena_i_reset)
-CTL_PROTO(arena_i_dss)
-CTL_PROTO(arena_i_lg_dirty_mult)
-CTL_PROTO(arena_i_decay_time)
-CTL_PROTO(arena_i_chunk_hooks)
-INDEX_PROTO(arena_i)
-CTL_PROTO(arenas_bin_i_size)
-CTL_PROTO(arenas_bin_i_nregs)
-CTL_PROTO(arenas_bin_i_run_size)
-INDEX_PROTO(arenas_bin_i)
-CTL_PROTO(arenas_lrun_i_size)
-INDEX_PROTO(arenas_lrun_i)
-CTL_PROTO(arenas_hchunk_i_size)
-INDEX_PROTO(arenas_hchunk_i)
-CTL_PROTO(arenas_narenas)
-CTL_PROTO(arenas_initialized)
-CTL_PROTO(arenas_lg_dirty_mult)
-CTL_PROTO(arenas_decay_time)
-CTL_PROTO(arenas_quantum)
-CTL_PROTO(arenas_page)
-CTL_PROTO(arenas_tcache_max)
-CTL_PROTO(arenas_nbins)
-CTL_PROTO(arenas_nhbins)
-CTL_PROTO(arenas_nlruns)
-CTL_PROTO(arenas_nhchunks)
-CTL_PROTO(arenas_extend)
-CTL_PROTO(prof_thread_active_init)
-CTL_PROTO(prof_active)
-CTL_PROTO(prof_dump)
-CTL_PROTO(prof_gdump)
-CTL_PROTO(prof_reset)
-CTL_PROTO(prof_interval)
-CTL_PROTO(lg_prof_sample)
-CTL_PROTO(stats_arenas_i_small_allocated)
-CTL_PROTO(stats_arenas_i_small_nmalloc)
-CTL_PROTO(stats_arenas_i_small_ndalloc)
-CTL_PROTO(stats_arenas_i_small_nrequests)
-CTL_PROTO(stats_arenas_i_large_allocated)
-CTL_PROTO(stats_arenas_i_large_nmalloc)
-CTL_PROTO(stats_arenas_i_large_ndalloc)
-CTL_PROTO(stats_arenas_i_large_nrequests)
-CTL_PROTO(stats_arenas_i_huge_allocated)
-CTL_PROTO(stats_arenas_i_huge_nmalloc)
-CTL_PROTO(stats_arenas_i_huge_ndalloc)
-CTL_PROTO(stats_arenas_i_huge_nrequests)
-CTL_PROTO(stats_arenas_i_bins_j_nmalloc)
-CTL_PROTO(stats_arenas_i_bins_j_ndalloc)
-CTL_PROTO(stats_arenas_i_bins_j_nrequests)
-CTL_PROTO(stats_arenas_i_bins_j_curregs)
-CTL_PROTO(stats_arenas_i_bins_j_nfills)
-CTL_PROTO(stats_arenas_i_bins_j_nflushes)
-CTL_PROTO(stats_arenas_i_bins_j_nruns)
-CTL_PROTO(stats_arenas_i_bins_j_nreruns)
-CTL_PROTO(stats_arenas_i_bins_j_curruns)
-INDEX_PROTO(stats_arenas_i_bins_j)
-CTL_PROTO(stats_arenas_i_lruns_j_nmalloc)
-CTL_PROTO(stats_arenas_i_lruns_j_ndalloc)
-CTL_PROTO(stats_arenas_i_lruns_j_nrequests)
-CTL_PROTO(stats_arenas_i_lruns_j_curruns)
-INDEX_PROTO(stats_arenas_i_lruns_j)
-CTL_PROTO(stats_arenas_i_hchunks_j_nmalloc)
-CTL_PROTO(stats_arenas_i_hchunks_j_ndalloc)
-CTL_PROTO(stats_arenas_i_hchunks_j_nrequests)
-CTL_PROTO(stats_arenas_i_hchunks_j_curhchunks)
-INDEX_PROTO(stats_arenas_i_hchunks_j)
-CTL_PROTO(stats_arenas_i_nthreads)
-CTL_PROTO(stats_arenas_i_dss)
-CTL_PROTO(stats_arenas_i_lg_dirty_mult)
-CTL_PROTO(stats_arenas_i_decay_time)
-CTL_PROTO(stats_arenas_i_pactive)
-CTL_PROTO(stats_arenas_i_pdirty)
-CTL_PROTO(stats_arenas_i_mapped)
-CTL_PROTO(stats_arenas_i_retained)
-CTL_PROTO(stats_arenas_i_npurge)
-CTL_PROTO(stats_arenas_i_nmadvise)
-CTL_PROTO(stats_arenas_i_purged)
-CTL_PROTO(stats_arenas_i_metadata_mapped)
-CTL_PROTO(stats_arenas_i_metadata_allocated)
-INDEX_PROTO(stats_arenas_i)
-CTL_PROTO(stats_cactive)
-CTL_PROTO(stats_allocated)
-CTL_PROTO(stats_active)
-CTL_PROTO(stats_metadata)
-CTL_PROTO(stats_resident)
-CTL_PROTO(stats_mapped)
-CTL_PROTO(stats_retained)
-
-/******************************************************************************/
-/* mallctl tree. */
-
-/* Maximum tree depth. */
-#define CTL_MAX_DEPTH 6
-
-#define NAME(n) {true}, n
-#define CHILD(t, c) \
- sizeof(c##_node) / sizeof(ctl_##t##_node_t), \
- (ctl_node_t *)c##_node, \
- NULL
-#define CTL(c) 0, NULL, c##_ctl
-
-/*
- * Only handles internal indexed nodes, since there are currently no external
- * ones.
- */
-#define INDEX(i) {false}, i##_index
-
-static const ctl_named_node_t thread_tcache_node[] = {
- {NAME("enabled"), CTL(thread_tcache_enabled)},
- {NAME("flush"), CTL(thread_tcache_flush)}
-};
-
-static const ctl_named_node_t thread_prof_node[] = {
- {NAME("name"), CTL(thread_prof_name)},
- {NAME("active"), CTL(thread_prof_active)}
-};
-
-static const ctl_named_node_t thread_node[] = {
- {NAME("arena"), CTL(thread_arena)},
- {NAME("allocated"), CTL(thread_allocated)},
- {NAME("allocatedp"), CTL(thread_allocatedp)},
- {NAME("deallocated"), CTL(thread_deallocated)},
- {NAME("deallocatedp"), CTL(thread_deallocatedp)},
- {NAME("tcache"), CHILD(named, thread_tcache)},
- {NAME("prof"), CHILD(named, thread_prof)}
-};
-
-static const ctl_named_node_t config_node[] = {
- {NAME("cache_oblivious"), CTL(config_cache_oblivious)},
- {NAME("debug"), CTL(config_debug)},
- {NAME("fill"), CTL(config_fill)},
- {NAME("lazy_lock"), CTL(config_lazy_lock)},
- {NAME("malloc_conf"), CTL(config_malloc_conf)},
- {NAME("munmap"), CTL(config_munmap)},
- {NAME("prof"), CTL(config_prof)},
- {NAME("prof_libgcc"), CTL(config_prof_libgcc)},
- {NAME("prof_libunwind"), CTL(config_prof_libunwind)},
- {NAME("stats"), CTL(config_stats)},
- {NAME("tcache"), CTL(config_tcache)},
- {NAME("tls"), CTL(config_tls)},
- {NAME("utrace"), CTL(config_utrace)},
- {NAME("valgrind"), CTL(config_valgrind)},
- {NAME("xmalloc"), CTL(config_xmalloc)}
-};
-
-static const ctl_named_node_t opt_node[] = {
- {NAME("abort"), CTL(opt_abort)},
- {NAME("dss"), CTL(opt_dss)},
- {NAME("lg_chunk"), CTL(opt_lg_chunk)},
- {NAME("narenas"), CTL(opt_narenas)},
- {NAME("purge"), CTL(opt_purge)},
- {NAME("lg_dirty_mult"), CTL(opt_lg_dirty_mult)},
- {NAME("decay_time"), CTL(opt_decay_time)},
- {NAME("stats_print"), CTL(opt_stats_print)},
- {NAME("junk"), CTL(opt_junk)},
- {NAME("zero"), CTL(opt_zero)},
- {NAME("quarantine"), CTL(opt_quarantine)},
- {NAME("redzone"), CTL(opt_redzone)},
- {NAME("utrace"), CTL(opt_utrace)},
- {NAME("xmalloc"), CTL(opt_xmalloc)},
- {NAME("tcache"), CTL(opt_tcache)},
- {NAME("lg_tcache_max"), CTL(opt_lg_tcache_max)},
- {NAME("prof"), CTL(opt_prof)},
- {NAME("prof_prefix"), CTL(opt_prof_prefix)},
- {NAME("prof_active"), CTL(opt_prof_active)},
- {NAME("prof_thread_active_init"), CTL(opt_prof_thread_active_init)},
- {NAME("lg_prof_sample"), CTL(opt_lg_prof_sample)},
- {NAME("lg_prof_interval"), CTL(opt_lg_prof_interval)},
- {NAME("prof_gdump"), CTL(opt_prof_gdump)},
- {NAME("prof_final"), CTL(opt_prof_final)},
- {NAME("prof_leak"), CTL(opt_prof_leak)},
- {NAME("prof_accum"), CTL(opt_prof_accum)}
-};
-
-static const ctl_named_node_t tcache_node[] = {
- {NAME("create"), CTL(tcache_create)},
- {NAME("flush"), CTL(tcache_flush)},
- {NAME("destroy"), CTL(tcache_destroy)}
-};
-
-static const ctl_named_node_t arena_i_node[] = {
- {NAME("purge"), CTL(arena_i_purge)},
- {NAME("decay"), CTL(arena_i_decay)},
- {NAME("reset"), CTL(arena_i_reset)},
- {NAME("dss"), CTL(arena_i_dss)},
- {NAME("lg_dirty_mult"), CTL(arena_i_lg_dirty_mult)},
- {NAME("decay_time"), CTL(arena_i_decay_time)},
- {NAME("chunk_hooks"), CTL(arena_i_chunk_hooks)}
-};
-static const ctl_named_node_t super_arena_i_node[] = {
- {NAME(""), CHILD(named, arena_i)}
-};
-
-static const ctl_indexed_node_t arena_node[] = {
- {INDEX(arena_i)}
-};
-
-static const ctl_named_node_t arenas_bin_i_node[] = {
- {NAME("size"), CTL(arenas_bin_i_size)},
- {NAME("nregs"), CTL(arenas_bin_i_nregs)},
- {NAME("run_size"), CTL(arenas_bin_i_run_size)}
-};
-static const ctl_named_node_t super_arenas_bin_i_node[] = {
- {NAME(""), CHILD(named, arenas_bin_i)}
-};
-
-static const ctl_indexed_node_t arenas_bin_node[] = {
- {INDEX(arenas_bin_i)}
-};
-
-static const ctl_named_node_t arenas_lrun_i_node[] = {
- {NAME("size"), CTL(arenas_lrun_i_size)}
-};
-static const ctl_named_node_t super_arenas_lrun_i_node[] = {
- {NAME(""), CHILD(named, arenas_lrun_i)}
-};
-
-static const ctl_indexed_node_t arenas_lrun_node[] = {
- {INDEX(arenas_lrun_i)}
-};
-
-static const ctl_named_node_t arenas_hchunk_i_node[] = {
- {NAME("size"), CTL(arenas_hchunk_i_size)}
-};
-static const ctl_named_node_t super_arenas_hchunk_i_node[] = {
- {NAME(""), CHILD(named, arenas_hchunk_i)}
-};
-
-static const ctl_indexed_node_t arenas_hchunk_node[] = {
- {INDEX(arenas_hchunk_i)}
-};
-
-static const ctl_named_node_t arenas_node[] = {
- {NAME("narenas"), CTL(arenas_narenas)},
- {NAME("initialized"), CTL(arenas_initialized)},
- {NAME("lg_dirty_mult"), CTL(arenas_lg_dirty_mult)},
- {NAME("decay_time"), CTL(arenas_decay_time)},
- {NAME("quantum"), CTL(arenas_quantum)},
- {NAME("page"), CTL(arenas_page)},
- {NAME("tcache_max"), CTL(arenas_tcache_max)},
- {NAME("nbins"), CTL(arenas_nbins)},
- {NAME("nhbins"), CTL(arenas_nhbins)},
- {NAME("bin"), CHILD(indexed, arenas_bin)},
- {NAME("nlruns"), CTL(arenas_nlruns)},
- {NAME("lrun"), CHILD(indexed, arenas_lrun)},
- {NAME("nhchunks"), CTL(arenas_nhchunks)},
- {NAME("hchunk"), CHILD(indexed, arenas_hchunk)},
- {NAME("extend"), CTL(arenas_extend)}
-};
-
-static const ctl_named_node_t prof_node[] = {
- {NAME("thread_active_init"), CTL(prof_thread_active_init)},
- {NAME("active"), CTL(prof_active)},
- {NAME("dump"), CTL(prof_dump)},
- {NAME("gdump"), CTL(prof_gdump)},
- {NAME("reset"), CTL(prof_reset)},
- {NAME("interval"), CTL(prof_interval)},
- {NAME("lg_sample"), CTL(lg_prof_sample)}
-};
-
-static const ctl_named_node_t stats_arenas_i_metadata_node[] = {
- {NAME("mapped"), CTL(stats_arenas_i_metadata_mapped)},
- {NAME("allocated"), CTL(stats_arenas_i_metadata_allocated)}
-};
-
-static const ctl_named_node_t stats_arenas_i_small_node[] = {
- {NAME("allocated"), CTL(stats_arenas_i_small_allocated)},
- {NAME("nmalloc"), CTL(stats_arenas_i_small_nmalloc)},
- {NAME("ndalloc"), CTL(stats_arenas_i_small_ndalloc)},
- {NAME("nrequests"), CTL(stats_arenas_i_small_nrequests)}
-};
-
-static const ctl_named_node_t stats_arenas_i_large_node[] = {
- {NAME("allocated"), CTL(stats_arenas_i_large_allocated)},
- {NAME("nmalloc"), CTL(stats_arenas_i_large_nmalloc)},
- {NAME("ndalloc"), CTL(stats_arenas_i_large_ndalloc)},
- {NAME("nrequests"), CTL(stats_arenas_i_large_nrequests)}
-};
-
-static const ctl_named_node_t stats_arenas_i_huge_node[] = {
- {NAME("allocated"), CTL(stats_arenas_i_huge_allocated)},
- {NAME("nmalloc"), CTL(stats_arenas_i_huge_nmalloc)},
- {NAME("ndalloc"), CTL(stats_arenas_i_huge_ndalloc)},
- {NAME("nrequests"), CTL(stats_arenas_i_huge_nrequests)}
-};
-
-static const ctl_named_node_t stats_arenas_i_bins_j_node[] = {
- {NAME("nmalloc"), CTL(stats_arenas_i_bins_j_nmalloc)},
- {NAME("ndalloc"), CTL(stats_arenas_i_bins_j_ndalloc)},
- {NAME("nrequests"), CTL(stats_arenas_i_bins_j_nrequests)},
- {NAME("curregs"), CTL(stats_arenas_i_bins_j_curregs)},
- {NAME("nfills"), CTL(stats_arenas_i_bins_j_nfills)},
- {NAME("nflushes"), CTL(stats_arenas_i_bins_j_nflushes)},
- {NAME("nruns"), CTL(stats_arenas_i_bins_j_nruns)},
- {NAME("nreruns"), CTL(stats_arenas_i_bins_j_nreruns)},
- {NAME("curruns"), CTL(stats_arenas_i_bins_j_curruns)}
-};
-static const ctl_named_node_t super_stats_arenas_i_bins_j_node[] = {
- {NAME(""), CHILD(named, stats_arenas_i_bins_j)}
-};
-
-static const ctl_indexed_node_t stats_arenas_i_bins_node[] = {
- {INDEX(stats_arenas_i_bins_j)}
-};
-
-static const ctl_named_node_t stats_arenas_i_lruns_j_node[] = {
- {NAME("nmalloc"), CTL(stats_arenas_i_lruns_j_nmalloc)},
- {NAME("ndalloc"), CTL(stats_arenas_i_lruns_j_ndalloc)},
- {NAME("nrequests"), CTL(stats_arenas_i_lruns_j_nrequests)},
- {NAME("curruns"), CTL(stats_arenas_i_lruns_j_curruns)}
-};
-static const ctl_named_node_t super_stats_arenas_i_lruns_j_node[] = {
- {NAME(""), CHILD(named, stats_arenas_i_lruns_j)}
-};
-
-static const ctl_indexed_node_t stats_arenas_i_lruns_node[] = {
- {INDEX(stats_arenas_i_lruns_j)}
-};
-
-static const ctl_named_node_t stats_arenas_i_hchunks_j_node[] = {
- {NAME("nmalloc"), CTL(stats_arenas_i_hchunks_j_nmalloc)},
- {NAME("ndalloc"), CTL(stats_arenas_i_hchunks_j_ndalloc)},
- {NAME("nrequests"), CTL(stats_arenas_i_hchunks_j_nrequests)},
- {NAME("curhchunks"), CTL(stats_arenas_i_hchunks_j_curhchunks)}
-};
-static const ctl_named_node_t super_stats_arenas_i_hchunks_j_node[] = {
- {NAME(""), CHILD(named, stats_arenas_i_hchunks_j)}
-};
-
-static const ctl_indexed_node_t stats_arenas_i_hchunks_node[] = {
- {INDEX(stats_arenas_i_hchunks_j)}
-};
-
-static const ctl_named_node_t stats_arenas_i_node[] = {
- {NAME("nthreads"), CTL(stats_arenas_i_nthreads)},
- {NAME("dss"), CTL(stats_arenas_i_dss)},
- {NAME("lg_dirty_mult"), CTL(stats_arenas_i_lg_dirty_mult)},
- {NAME("decay_time"), CTL(stats_arenas_i_decay_time)},
- {NAME("pactive"), CTL(stats_arenas_i_pactive)},
- {NAME("pdirty"), CTL(stats_arenas_i_pdirty)},
- {NAME("mapped"), CTL(stats_arenas_i_mapped)},
- {NAME("retained"), CTL(stats_arenas_i_retained)},
- {NAME("npurge"), CTL(stats_arenas_i_npurge)},
- {NAME("nmadvise"), CTL(stats_arenas_i_nmadvise)},
- {NAME("purged"), CTL(stats_arenas_i_purged)},
- {NAME("metadata"), CHILD(named, stats_arenas_i_metadata)},
- {NAME("small"), CHILD(named, stats_arenas_i_small)},
- {NAME("large"), CHILD(named, stats_arenas_i_large)},
- {NAME("huge"), CHILD(named, stats_arenas_i_huge)},
- {NAME("bins"), CHILD(indexed, stats_arenas_i_bins)},
- {NAME("lruns"), CHILD(indexed, stats_arenas_i_lruns)},
- {NAME("hchunks"), CHILD(indexed, stats_arenas_i_hchunks)}
-};
-static const ctl_named_node_t super_stats_arenas_i_node[] = {
- {NAME(""), CHILD(named, stats_arenas_i)}
-};
-
-static const ctl_indexed_node_t stats_arenas_node[] = {
- {INDEX(stats_arenas_i)}
-};
-
-static const ctl_named_node_t stats_node[] = {
- {NAME("cactive"), CTL(stats_cactive)},
- {NAME("allocated"), CTL(stats_allocated)},
- {NAME("active"), CTL(stats_active)},
- {NAME("metadata"), CTL(stats_metadata)},
- {NAME("resident"), CTL(stats_resident)},
- {NAME("mapped"), CTL(stats_mapped)},
- {NAME("retained"), CTL(stats_retained)},
- {NAME("arenas"), CHILD(indexed, stats_arenas)}
-};
-
-static const ctl_named_node_t root_node[] = {
- {NAME("version"), CTL(version)},
- {NAME("epoch"), CTL(epoch)},
- {NAME("thread"), CHILD(named, thread)},
- {NAME("config"), CHILD(named, config)},
- {NAME("opt"), CHILD(named, opt)},
- {NAME("tcache"), CHILD(named, tcache)},
- {NAME("arena"), CHILD(indexed, arena)},
- {NAME("arenas"), CHILD(named, arenas)},
- {NAME("prof"), CHILD(named, prof)},
- {NAME("stats"), CHILD(named, stats)}
-};
-static const ctl_named_node_t super_root_node[] = {
- {NAME(""), CHILD(named, root)}
-};
-
-#undef NAME
-#undef CHILD
-#undef CTL
-#undef INDEX
-
-/******************************************************************************/
-
-static bool
-ctl_arena_init(ctl_arena_stats_t *astats)
-{
-
- if (astats->lstats == NULL) {
- astats->lstats = (malloc_large_stats_t *)a0malloc(nlclasses *
- sizeof(malloc_large_stats_t));
- if (astats->lstats == NULL)
- return (true);
- }
-
- if (astats->hstats == NULL) {
- astats->hstats = (malloc_huge_stats_t *)a0malloc(nhclasses *
- sizeof(malloc_huge_stats_t));
- if (astats->hstats == NULL)
- return (true);
- }
-
- return (false);
-}
-
-static void
-ctl_arena_clear(ctl_arena_stats_t *astats)
-{
-
- astats->nthreads = 0;
- astats->dss = dss_prec_names[dss_prec_limit];
- astats->lg_dirty_mult = -1;
- astats->decay_time = -1;
- astats->pactive = 0;
- astats->pdirty = 0;
- if (config_stats) {
- memset(&astats->astats, 0, sizeof(arena_stats_t));
- astats->allocated_small = 0;
- astats->nmalloc_small = 0;
- astats->ndalloc_small = 0;
- astats->nrequests_small = 0;
- memset(astats->bstats, 0, NBINS * sizeof(malloc_bin_stats_t));
- memset(astats->lstats, 0, nlclasses *
- sizeof(malloc_large_stats_t));
- memset(astats->hstats, 0, nhclasses *
- sizeof(malloc_huge_stats_t));
- }
-}
-
-static void
-ctl_arena_stats_amerge(tsdn_t *tsdn, ctl_arena_stats_t *cstats, arena_t *arena)
-{
- unsigned i;
-
- if (config_stats) {
- arena_stats_merge(tsdn, arena, &cstats->nthreads, &cstats->dss,
- &cstats->lg_dirty_mult, &cstats->decay_time,
- &cstats->pactive, &cstats->pdirty, &cstats->astats,
- cstats->bstats, cstats->lstats, cstats->hstats);
-
- for (i = 0; i < NBINS; i++) {
- cstats->allocated_small += cstats->bstats[i].curregs *
- index2size(i);
- cstats->nmalloc_small += cstats->bstats[i].nmalloc;
- cstats->ndalloc_small += cstats->bstats[i].ndalloc;
- cstats->nrequests_small += cstats->bstats[i].nrequests;
- }
- } else {
- arena_basic_stats_merge(tsdn, arena, &cstats->nthreads,
- &cstats->dss, &cstats->lg_dirty_mult, &cstats->decay_time,
- &cstats->pactive, &cstats->pdirty);
- }
-}
-
-static void
-ctl_arena_stats_smerge(ctl_arena_stats_t *sstats, ctl_arena_stats_t *astats)
-{
- unsigned i;
-
- sstats->nthreads += astats->nthreads;
- sstats->pactive += astats->pactive;
- sstats->pdirty += astats->pdirty;
-
- if (config_stats) {
- sstats->astats.mapped += astats->astats.mapped;
- sstats->astats.retained += astats->astats.retained;
- sstats->astats.npurge += astats->astats.npurge;
- sstats->astats.nmadvise += astats->astats.nmadvise;
- sstats->astats.purged += astats->astats.purged;
-
- sstats->astats.metadata_mapped +=
- astats->astats.metadata_mapped;
- sstats->astats.metadata_allocated +=
- astats->astats.metadata_allocated;
-
- sstats->allocated_small += astats->allocated_small;
- sstats->nmalloc_small += astats->nmalloc_small;
- sstats->ndalloc_small += astats->ndalloc_small;
- sstats->nrequests_small += astats->nrequests_small;
-
- sstats->astats.allocated_large +=
- astats->astats.allocated_large;
- sstats->astats.nmalloc_large += astats->astats.nmalloc_large;
- sstats->astats.ndalloc_large += astats->astats.ndalloc_large;
- sstats->astats.nrequests_large +=
- astats->astats.nrequests_large;
-
- sstats->astats.allocated_huge += astats->astats.allocated_huge;
- sstats->astats.nmalloc_huge += astats->astats.nmalloc_huge;
- sstats->astats.ndalloc_huge += astats->astats.ndalloc_huge;
-
- for (i = 0; i < NBINS; i++) {
- sstats->bstats[i].nmalloc += astats->bstats[i].nmalloc;
- sstats->bstats[i].ndalloc += astats->bstats[i].ndalloc;
- sstats->bstats[i].nrequests +=
- astats->bstats[i].nrequests;
- sstats->bstats[i].curregs += astats->bstats[i].curregs;
- if (config_tcache) {
- sstats->bstats[i].nfills +=
- astats->bstats[i].nfills;
- sstats->bstats[i].nflushes +=
- astats->bstats[i].nflushes;
- }
- sstats->bstats[i].nruns += astats->bstats[i].nruns;
- sstats->bstats[i].reruns += astats->bstats[i].reruns;
- sstats->bstats[i].curruns += astats->bstats[i].curruns;
- }
-
- for (i = 0; i < nlclasses; i++) {
- sstats->lstats[i].nmalloc += astats->lstats[i].nmalloc;
- sstats->lstats[i].ndalloc += astats->lstats[i].ndalloc;
- sstats->lstats[i].nrequests +=
- astats->lstats[i].nrequests;
- sstats->lstats[i].curruns += astats->lstats[i].curruns;
- }
-
- for (i = 0; i < nhclasses; i++) {
- sstats->hstats[i].nmalloc += astats->hstats[i].nmalloc;
- sstats->hstats[i].ndalloc += astats->hstats[i].ndalloc;
- sstats->hstats[i].curhchunks +=
- astats->hstats[i].curhchunks;
- }
- }
-}
-
-static void
-ctl_arena_refresh(tsdn_t *tsdn, arena_t *arena, unsigned i)
-{
- ctl_arena_stats_t *astats = &ctl_stats.arenas[i];
- ctl_arena_stats_t *sstats = &ctl_stats.arenas[ctl_stats.narenas];
-
- ctl_arena_clear(astats);
- ctl_arena_stats_amerge(tsdn, astats, arena);
- /* Merge into sum stats as well. */
- ctl_arena_stats_smerge(sstats, astats);
-}
-
-static bool
-ctl_grow(tsdn_t *tsdn)
-{
- ctl_arena_stats_t *astats;
-
- /* Initialize new arena. */
- if (arena_init(tsdn, ctl_stats.narenas) == NULL)
- return (true);
-
- /* Allocate extended arena stats. */
- astats = (ctl_arena_stats_t *)a0malloc((ctl_stats.narenas + 2) *
- sizeof(ctl_arena_stats_t));
- if (astats == NULL)
- return (true);
-
- /* Initialize the new astats element. */
- memcpy(astats, ctl_stats.arenas, (ctl_stats.narenas + 1) *
- sizeof(ctl_arena_stats_t));
- memset(&astats[ctl_stats.narenas + 1], 0, sizeof(ctl_arena_stats_t));
- if (ctl_arena_init(&astats[ctl_stats.narenas + 1])) {
- a0dalloc(astats);
- return (true);
- }
- /* Swap merged stats to their new location. */
- {
- ctl_arena_stats_t tstats;
- memcpy(&tstats, &astats[ctl_stats.narenas],
- sizeof(ctl_arena_stats_t));
- memcpy(&astats[ctl_stats.narenas],
- &astats[ctl_stats.narenas + 1], sizeof(ctl_arena_stats_t));
- memcpy(&astats[ctl_stats.narenas + 1], &tstats,
- sizeof(ctl_arena_stats_t));
- }
- a0dalloc(ctl_stats.arenas);
- ctl_stats.arenas = astats;
- ctl_stats.narenas++;
-
- return (false);
-}
-
-static void
-ctl_refresh(tsdn_t *tsdn)
-{
- unsigned i;
- VARIABLE_ARRAY(arena_t *, tarenas, ctl_stats.narenas);
-
- /*
- * Clear sum stats, since they will be merged into by
- * ctl_arena_refresh().
- */
- ctl_arena_clear(&ctl_stats.arenas[ctl_stats.narenas]);
-
- for (i = 0; i < ctl_stats.narenas; i++)
- tarenas[i] = arena_get(tsdn, i, false);
-
- for (i = 0; i < ctl_stats.narenas; i++) {
- bool initialized = (tarenas[i] != NULL);
-
- ctl_stats.arenas[i].initialized = initialized;
- if (initialized)
- ctl_arena_refresh(tsdn, tarenas[i], i);
- }
-
- if (config_stats) {
- size_t base_allocated, base_resident, base_mapped;
- base_stats_get(tsdn, &base_allocated, &base_resident,
- &base_mapped);
- ctl_stats.allocated =
- ctl_stats.arenas[ctl_stats.narenas].allocated_small +
- ctl_stats.arenas[ctl_stats.narenas].astats.allocated_large +
- ctl_stats.arenas[ctl_stats.narenas].astats.allocated_huge;
- ctl_stats.active =
- (ctl_stats.arenas[ctl_stats.narenas].pactive << LG_PAGE);
- ctl_stats.metadata = base_allocated +
- ctl_stats.arenas[ctl_stats.narenas].astats.metadata_mapped +
- ctl_stats.arenas[ctl_stats.narenas].astats
- .metadata_allocated;
- ctl_stats.resident = base_resident +
- ctl_stats.arenas[ctl_stats.narenas].astats.metadata_mapped +
- ((ctl_stats.arenas[ctl_stats.narenas].pactive +
- ctl_stats.arenas[ctl_stats.narenas].pdirty) << LG_PAGE);
- ctl_stats.mapped = base_mapped +
- ctl_stats.arenas[ctl_stats.narenas].astats.mapped;
- ctl_stats.retained =
- ctl_stats.arenas[ctl_stats.narenas].astats.retained;
- }
-
- ctl_epoch++;
-}
-
-static bool
-ctl_init(tsdn_t *tsdn)
-{
- bool ret;
-
- malloc_mutex_lock(tsdn, &ctl_mtx);
- if (!ctl_initialized) {
- /*
- * Allocate space for one extra arena stats element, which
- * contains summed stats across all arenas.
- */
- ctl_stats.narenas = narenas_total_get();
- ctl_stats.arenas = (ctl_arena_stats_t *)a0malloc(
- (ctl_stats.narenas + 1) * sizeof(ctl_arena_stats_t));
- if (ctl_stats.arenas == NULL) {
- ret = true;
- goto label_return;
- }
- memset(ctl_stats.arenas, 0, (ctl_stats.narenas + 1) *
- sizeof(ctl_arena_stats_t));
-
- /*
- * Initialize all stats structures, regardless of whether they
- * ever get used. Lazy initialization would allow errors to
- * cause inconsistent state to be viewable by the application.
- */
- if (config_stats) {
- unsigned i;
- for (i = 0; i <= ctl_stats.narenas; i++) {
- if (ctl_arena_init(&ctl_stats.arenas[i])) {
- unsigned j;
- for (j = 0; j < i; j++) {
- a0dalloc(
- ctl_stats.arenas[j].lstats);
- a0dalloc(
- ctl_stats.arenas[j].hstats);
- }
- a0dalloc(ctl_stats.arenas);
- ctl_stats.arenas = NULL;
- ret = true;
- goto label_return;
- }
- }
- }
- ctl_stats.arenas[ctl_stats.narenas].initialized = true;
-
- ctl_epoch = 0;
- ctl_refresh(tsdn);
- ctl_initialized = true;
- }
-
- ret = false;
-label_return:
- malloc_mutex_unlock(tsdn, &ctl_mtx);
- return (ret);
-}
-
-static int
-ctl_lookup(tsdn_t *tsdn, const char *name, ctl_node_t const **nodesp,
- size_t *mibp, size_t *depthp)
-{
- int ret;
- const char *elm, *tdot, *dot;
- size_t elen, i, j;
- const ctl_named_node_t *node;
-
- elm = name;
- /* Equivalent to strchrnul(). */
- dot = ((tdot = strchr(elm, '.')) != NULL) ? tdot : strchr(elm, '\0');
- elen = (size_t)((uintptr_t)dot - (uintptr_t)elm);
- if (elen == 0) {
- ret = ENOENT;
- goto label_return;
- }
- node = super_root_node;
- for (i = 0; i < *depthp; i++) {
- assert(node);
- assert(node->nchildren > 0);
- if (ctl_named_node(node->children) != NULL) {
- const ctl_named_node_t *pnode = node;
-
- /* Children are named. */
- for (j = 0; j < node->nchildren; j++) {
- const ctl_named_node_t *child =
- ctl_named_children(node, j);
- if (strlen(child->name) == elen &&
- strncmp(elm, child->name, elen) == 0) {
- node = child;
- if (nodesp != NULL)
- nodesp[i] =
- (const ctl_node_t *)node;
- mibp[i] = j;
- break;
- }
- }
- if (node == pnode) {
- ret = ENOENT;
- goto label_return;
- }
- } else {
- uintmax_t index;
- const ctl_indexed_node_t *inode;
-
- /* Children are indexed. */
- index = malloc_strtoumax(elm, NULL, 10);
- if (index == UINTMAX_MAX || index > SIZE_T_MAX) {
- ret = ENOENT;
- goto label_return;
- }
-
- inode = ctl_indexed_node(node->children);
- node = inode->index(tsdn, mibp, *depthp, (size_t)index);
- if (node == NULL) {
- ret = ENOENT;
- goto label_return;
- }
-
- if (nodesp != NULL)
- nodesp[i] = (const ctl_node_t *)node;
- mibp[i] = (size_t)index;
- }
-
- if (node->ctl != NULL) {
- /* Terminal node. */
- if (*dot != '\0') {
- /*
- * The name contains more elements than are
- * in this path through the tree.
- */
- ret = ENOENT;
- goto label_return;
- }
- /* Complete lookup successful. */
- *depthp = i + 1;
- break;
- }
-
- /* Update elm. */
- if (*dot == '\0') {
- /* No more elements. */
- ret = ENOENT;
- goto label_return;
- }
- elm = &dot[1];
- dot = ((tdot = strchr(elm, '.')) != NULL) ? tdot :
- strchr(elm, '\0');
- elen = (size_t)((uintptr_t)dot - (uintptr_t)elm);
- }
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-int
-ctl_byname(tsd_t *tsd, const char *name, void *oldp, size_t *oldlenp,
- void *newp, size_t newlen)
-{
- int ret;
- size_t depth;
- ctl_node_t const *nodes[CTL_MAX_DEPTH];
- size_t mib[CTL_MAX_DEPTH];
- const ctl_named_node_t *node;
-
- if (!ctl_initialized && ctl_init(tsd_tsdn(tsd))) {
- ret = EAGAIN;
- goto label_return;
- }
-
- depth = CTL_MAX_DEPTH;
- ret = ctl_lookup(tsd_tsdn(tsd), name, nodes, mib, &depth);
- if (ret != 0)
- goto label_return;
-
- node = ctl_named_node(nodes[depth-1]);
- if (node != NULL && node->ctl)
- ret = node->ctl(tsd, mib, depth, oldp, oldlenp, newp, newlen);
- else {
- /* The name refers to a partial path through the ctl tree. */
- ret = ENOENT;
- }
-
-label_return:
- return(ret);
-}
-
-int
-ctl_nametomib(tsdn_t *tsdn, const char *name, size_t *mibp, size_t *miblenp)
-{
- int ret;
-
- if (!ctl_initialized && ctl_init(tsdn)) {
- ret = EAGAIN;
- goto label_return;
- }
-
- ret = ctl_lookup(tsdn, name, NULL, mibp, miblenp);
-label_return:
- return(ret);
-}
-
-int
-ctl_bymib(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- const ctl_named_node_t *node;
- size_t i;
-
- if (!ctl_initialized && ctl_init(tsd_tsdn(tsd))) {
- ret = EAGAIN;
- goto label_return;
- }
-
- /* Iterate down the tree. */
- node = super_root_node;
- for (i = 0; i < miblen; i++) {
- assert(node);
- assert(node->nchildren > 0);
- if (ctl_named_node(node->children) != NULL) {
- /* Children are named. */
- if (node->nchildren <= (unsigned)mib[i]) {
- ret = ENOENT;
- goto label_return;
- }
- node = ctl_named_children(node, mib[i]);
- } else {
- const ctl_indexed_node_t *inode;
-
- /* Indexed element. */
- inode = ctl_indexed_node(node->children);
- node = inode->index(tsd_tsdn(tsd), mib, miblen, mib[i]);
- if (node == NULL) {
- ret = ENOENT;
- goto label_return;
- }
- }
- }
-
- /* Call the ctl function. */
- if (node && node->ctl)
- ret = node->ctl(tsd, mib, miblen, oldp, oldlenp, newp, newlen);
- else {
- /* Partial MIB. */
- ret = ENOENT;
- }
-
-label_return:
- return(ret);
-}
-
-bool
-ctl_boot(void)
-{
-
- if (malloc_mutex_init(&ctl_mtx, "ctl", WITNESS_RANK_CTL))
- return (true);
-
- ctl_initialized = false;
-
- return (false);
-}
-
-void
-ctl_prefork(tsdn_t *tsdn)
-{
-
- malloc_mutex_prefork(tsdn, &ctl_mtx);
-}
-
-void
-ctl_postfork_parent(tsdn_t *tsdn)
-{
-
- malloc_mutex_postfork_parent(tsdn, &ctl_mtx);
-}
-
-void
-ctl_postfork_child(tsdn_t *tsdn)
-{
-
- malloc_mutex_postfork_child(tsdn, &ctl_mtx);
-}
-
-/******************************************************************************/
-/* *_ctl() functions. */
-
-#define READONLY() do { \
- if (newp != NULL || newlen != 0) { \
- ret = EPERM; \
- goto label_return; \
- } \
-} while (0)
-
-#define WRITEONLY() do { \
- if (oldp != NULL || oldlenp != NULL) { \
- ret = EPERM; \
- goto label_return; \
- } \
-} while (0)
-
-#define READ_XOR_WRITE() do { \
- if ((oldp != NULL && oldlenp != NULL) && (newp != NULL || \
- newlen != 0)) { \
- ret = EPERM; \
- goto label_return; \
- } \
-} while (0)
-
-#define READ(v, t) do { \
- if (oldp != NULL && oldlenp != NULL) { \
- if (*oldlenp != sizeof(t)) { \
- size_t copylen = (sizeof(t) <= *oldlenp) \
- ? sizeof(t) : *oldlenp; \
- memcpy(oldp, (void *)&(v), copylen); \
- ret = EINVAL; \
- goto label_return; \
- } \
- *(t *)oldp = (v); \
- } \
-} while (0)
-
-#define WRITE(v, t) do { \
- if (newp != NULL) { \
- if (newlen != sizeof(t)) { \
- ret = EINVAL; \
- goto label_return; \
- } \
- (v) = *(t *)newp; \
- } \
-} while (0)
-
-/*
- * There's a lot of code duplication in the following macros due to limitations
- * in how nested cpp macros are expanded.
- */
-#define CTL_RO_CLGEN(c, l, n, v, t) \
-static int \
-n##_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp, \
- size_t *oldlenp, void *newp, size_t newlen) \
-{ \
- int ret; \
- t oldval; \
- \
- if (!(c)) \
- return (ENOENT); \
- if (l) \
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx); \
- READONLY(); \
- oldval = (v); \
- READ(oldval, t); \
- \
- ret = 0; \
-label_return: \
- if (l) \
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx); \
- return (ret); \
-}
-
-#define CTL_RO_CGEN(c, n, v, t) \
-static int \
-n##_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp, \
- size_t *oldlenp, void *newp, size_t newlen) \
-{ \
- int ret; \
- t oldval; \
- \
- if (!(c)) \
- return (ENOENT); \
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx); \
- READONLY(); \
- oldval = (v); \
- READ(oldval, t); \
- \
- ret = 0; \
-label_return: \
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx); \
- return (ret); \
-}
-
-#define CTL_RO_GEN(n, v, t) \
-static int \
-n##_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp, \
- size_t *oldlenp, void *newp, size_t newlen) \
-{ \
- int ret; \
- t oldval; \
- \
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx); \
- READONLY(); \
- oldval = (v); \
- READ(oldval, t); \
- \
- ret = 0; \
-label_return: \
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx); \
- return (ret); \
-}
-
-/*
- * ctl_mtx is not acquired, under the assumption that no pertinent data will
- * mutate during the call.
- */
-#define CTL_RO_NL_CGEN(c, n, v, t) \
-static int \
-n##_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp, \
- size_t *oldlenp, void *newp, size_t newlen) \
-{ \
- int ret; \
- t oldval; \
- \
- if (!(c)) \
- return (ENOENT); \
- READONLY(); \
- oldval = (v); \
- READ(oldval, t); \
- \
- ret = 0; \
-label_return: \
- return (ret); \
-}
-
-#define CTL_RO_NL_GEN(n, v, t) \
-static int \
-n##_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp, \
- size_t *oldlenp, void *newp, size_t newlen) \
-{ \
- int ret; \
- t oldval; \
- \
- READONLY(); \
- oldval = (v); \
- READ(oldval, t); \
- \
- ret = 0; \
-label_return: \
- return (ret); \
-}
-
-#define CTL_TSD_RO_NL_CGEN(c, n, m, t) \
-static int \
-n##_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp, \
- size_t *oldlenp, void *newp, size_t newlen) \
-{ \
- int ret; \
- t oldval; \
- \
- if (!(c)) \
- return (ENOENT); \
- READONLY(); \
- oldval = (m(tsd)); \
- READ(oldval, t); \
- \
- ret = 0; \
-label_return: \
- return (ret); \
-}
-
-#define CTL_RO_CONFIG_GEN(n, t) \
-static int \
-n##_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp, \
- size_t *oldlenp, void *newp, size_t newlen) \
-{ \
- int ret; \
- t oldval; \
- \
- READONLY(); \
- oldval = n; \
- READ(oldval, t); \
- \
- ret = 0; \
-label_return: \
- return (ret); \
-}
-
-/******************************************************************************/
-
-CTL_RO_NL_GEN(version, JEMALLOC_VERSION, const char *)
-
-static int
-epoch_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- UNUSED uint64_t newval;
-
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- WRITE(newval, uint64_t);
- if (newp != NULL)
- ctl_refresh(tsd_tsdn(tsd));
- READ(ctl_epoch, uint64_t);
-
- ret = 0;
-label_return:
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- return (ret);
-}
-
-/******************************************************************************/
-
-CTL_RO_CONFIG_GEN(config_cache_oblivious, bool)
-CTL_RO_CONFIG_GEN(config_debug, bool)
-CTL_RO_CONFIG_GEN(config_fill, bool)
-CTL_RO_CONFIG_GEN(config_lazy_lock, bool)
-CTL_RO_CONFIG_GEN(config_malloc_conf, const char *)
-CTL_RO_CONFIG_GEN(config_munmap, bool)
-CTL_RO_CONFIG_GEN(config_prof, bool)
-CTL_RO_CONFIG_GEN(config_prof_libgcc, bool)
-CTL_RO_CONFIG_GEN(config_prof_libunwind, bool)
-CTL_RO_CONFIG_GEN(config_stats, bool)
-CTL_RO_CONFIG_GEN(config_tcache, bool)
-CTL_RO_CONFIG_GEN(config_tls, bool)
-CTL_RO_CONFIG_GEN(config_utrace, bool)
-CTL_RO_CONFIG_GEN(config_valgrind, bool)
-CTL_RO_CONFIG_GEN(config_xmalloc, bool)
-
-/******************************************************************************/
-
-CTL_RO_NL_GEN(opt_abort, opt_abort, bool)
-CTL_RO_NL_GEN(opt_dss, opt_dss, const char *)
-CTL_RO_NL_GEN(opt_lg_chunk, opt_lg_chunk, size_t)
-CTL_RO_NL_GEN(opt_narenas, opt_narenas, unsigned)
-CTL_RO_NL_GEN(opt_purge, purge_mode_names[opt_purge], const char *)
-CTL_RO_NL_GEN(opt_lg_dirty_mult, opt_lg_dirty_mult, ssize_t)
-CTL_RO_NL_GEN(opt_decay_time, opt_decay_time, ssize_t)
-CTL_RO_NL_GEN(opt_stats_print, opt_stats_print, bool)
-CTL_RO_NL_CGEN(config_fill, opt_junk, opt_junk, const char *)
-CTL_RO_NL_CGEN(config_fill, opt_quarantine, opt_quarantine, size_t)
-CTL_RO_NL_CGEN(config_fill, opt_redzone, opt_redzone, bool)
-CTL_RO_NL_CGEN(config_fill, opt_zero, opt_zero, bool)
-CTL_RO_NL_CGEN(config_utrace, opt_utrace, opt_utrace, bool)
-CTL_RO_NL_CGEN(config_xmalloc, opt_xmalloc, opt_xmalloc, bool)
-CTL_RO_NL_CGEN(config_tcache, opt_tcache, opt_tcache, bool)
-CTL_RO_NL_CGEN(config_tcache, opt_lg_tcache_max, opt_lg_tcache_max, ssize_t)
-CTL_RO_NL_CGEN(config_prof, opt_prof, opt_prof, bool)
-CTL_RO_NL_CGEN(config_prof, opt_prof_prefix, opt_prof_prefix, const char *)
-CTL_RO_NL_CGEN(config_prof, opt_prof_active, opt_prof_active, bool)
-CTL_RO_NL_CGEN(config_prof, opt_prof_thread_active_init,
- opt_prof_thread_active_init, bool)
-CTL_RO_NL_CGEN(config_prof, opt_lg_prof_sample, opt_lg_prof_sample, size_t)
-CTL_RO_NL_CGEN(config_prof, opt_prof_accum, opt_prof_accum, bool)
-CTL_RO_NL_CGEN(config_prof, opt_lg_prof_interval, opt_lg_prof_interval, ssize_t)
-CTL_RO_NL_CGEN(config_prof, opt_prof_gdump, opt_prof_gdump, bool)
-CTL_RO_NL_CGEN(config_prof, opt_prof_final, opt_prof_final, bool)
-CTL_RO_NL_CGEN(config_prof, opt_prof_leak, opt_prof_leak, bool)
-
-/******************************************************************************/
-
-static int
-thread_arena_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- arena_t *oldarena;
- unsigned newind, oldind;
-
- oldarena = arena_choose(tsd, NULL);
- if (oldarena == NULL)
- return (EAGAIN);
-
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- newind = oldind = oldarena->ind;
- WRITE(newind, unsigned);
- READ(oldind, unsigned);
- if (newind != oldind) {
- arena_t *newarena;
-
- if (newind >= ctl_stats.narenas) {
- /* New arena index is out of range. */
- ret = EFAULT;
- goto label_return;
- }
-
- /* Initialize arena if necessary. */
- newarena = arena_get(tsd_tsdn(tsd), newind, true);
- if (newarena == NULL) {
- ret = EAGAIN;
- goto label_return;
- }
- /* Set new arena/tcache associations. */
- arena_migrate(tsd, oldind, newind);
- if (config_tcache) {
- tcache_t *tcache = tsd_tcache_get(tsd);
- if (tcache != NULL) {
- tcache_arena_reassociate(tsd_tsdn(tsd), tcache,
- oldarena, newarena);
- }
- }
- }
-
- ret = 0;
-label_return:
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- return (ret);
-}
-
-CTL_TSD_RO_NL_CGEN(config_stats, thread_allocated, tsd_thread_allocated_get,
- uint64_t)
-CTL_TSD_RO_NL_CGEN(config_stats, thread_allocatedp, tsd_thread_allocatedp_get,
- uint64_t *)
-CTL_TSD_RO_NL_CGEN(config_stats, thread_deallocated, tsd_thread_deallocated_get,
- uint64_t)
-CTL_TSD_RO_NL_CGEN(config_stats, thread_deallocatedp,
- tsd_thread_deallocatedp_get, uint64_t *)
-
-static int
-thread_tcache_enabled_ctl(tsd_t *tsd, const size_t *mib, size_t miblen,
- void *oldp, size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- bool oldval;
-
- if (!config_tcache)
- return (ENOENT);
-
- oldval = tcache_enabled_get();
- if (newp != NULL) {
- if (newlen != sizeof(bool)) {
- ret = EINVAL;
- goto label_return;
- }
- tcache_enabled_set(*(bool *)newp);
- }
- READ(oldval, bool);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-thread_tcache_flush_ctl(tsd_t *tsd, const size_t *mib, size_t miblen,
- void *oldp, size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
-
- if (!config_tcache)
- return (ENOENT);
-
- READONLY();
- WRITEONLY();
-
- tcache_flush();
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-thread_prof_name_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
-
- if (!config_prof)
- return (ENOENT);
-
- READ_XOR_WRITE();
-
- if (newp != NULL) {
- if (newlen != sizeof(const char *)) {
- ret = EINVAL;
- goto label_return;
- }
-
- if ((ret = prof_thread_name_set(tsd, *(const char **)newp)) !=
- 0)
- goto label_return;
- } else {
- const char *oldname = prof_thread_name_get(tsd);
- READ(oldname, const char *);
- }
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-thread_prof_active_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- bool oldval;
-
- if (!config_prof)
- return (ENOENT);
-
- oldval = prof_thread_active_get(tsd);
- if (newp != NULL) {
- if (newlen != sizeof(bool)) {
- ret = EINVAL;
- goto label_return;
- }
- if (prof_thread_active_set(tsd, *(bool *)newp)) {
- ret = EAGAIN;
- goto label_return;
- }
- }
- READ(oldval, bool);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-/******************************************************************************/
-
-static int
-tcache_create_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned tcache_ind;
-
- if (!config_tcache)
- return (ENOENT);
-
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- READONLY();
- if (tcaches_create(tsd, &tcache_ind)) {
- ret = EFAULT;
- goto label_return;
- }
- READ(tcache_ind, unsigned);
-
- ret = 0;
-label_return:
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- return (ret);
-}
-
-static int
-tcache_flush_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned tcache_ind;
-
- if (!config_tcache)
- return (ENOENT);
-
- WRITEONLY();
- tcache_ind = UINT_MAX;
- WRITE(tcache_ind, unsigned);
- if (tcache_ind == UINT_MAX) {
- ret = EFAULT;
- goto label_return;
- }
- tcaches_flush(tsd, tcache_ind);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-tcache_destroy_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned tcache_ind;
-
- if (!config_tcache)
- return (ENOENT);
-
- WRITEONLY();
- tcache_ind = UINT_MAX;
- WRITE(tcache_ind, unsigned);
- if (tcache_ind == UINT_MAX) {
- ret = EFAULT;
- goto label_return;
- }
- tcaches_destroy(tsd, tcache_ind);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-/******************************************************************************/
-
-static void
-arena_i_purge(tsdn_t *tsdn, unsigned arena_ind, bool all)
-{
-
- malloc_mutex_lock(tsdn, &ctl_mtx);
- {
- unsigned narenas = ctl_stats.narenas;
-
- if (arena_ind == narenas) {
- unsigned i;
- VARIABLE_ARRAY(arena_t *, tarenas, narenas);
-
- for (i = 0; i < narenas; i++)
- tarenas[i] = arena_get(tsdn, i, false);
-
- /*
- * No further need to hold ctl_mtx, since narenas and
- * tarenas contain everything needed below.
- */
- malloc_mutex_unlock(tsdn, &ctl_mtx);
-
- for (i = 0; i < narenas; i++) {
- if (tarenas[i] != NULL)
- arena_purge(tsdn, tarenas[i], all);
- }
- } else {
- arena_t *tarena;
-
- assert(arena_ind < narenas);
-
- tarena = arena_get(tsdn, arena_ind, false);
-
- /* No further need to hold ctl_mtx. */
- malloc_mutex_unlock(tsdn, &ctl_mtx);
-
- if (tarena != NULL)
- arena_purge(tsdn, tarena, all);
- }
- }
-}
-
-static int
-arena_i_purge_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
-
- READONLY();
- WRITEONLY();
- arena_i_purge(tsd_tsdn(tsd), (unsigned)mib[1], true);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-arena_i_decay_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
-
- READONLY();
- WRITEONLY();
- arena_i_purge(tsd_tsdn(tsd), (unsigned)mib[1], false);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-arena_i_reset_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned arena_ind;
- arena_t *arena;
-
- READONLY();
- WRITEONLY();
-
- if ((config_valgrind && unlikely(in_valgrind)) || (config_fill &&
- unlikely(opt_quarantine))) {
- ret = EFAULT;
- goto label_return;
- }
-
- arena_ind = (unsigned)mib[1];
- if (config_debug) {
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- assert(arena_ind < ctl_stats.narenas);
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- }
- assert(arena_ind >= opt_narenas);
-
- arena = arena_get(tsd_tsdn(tsd), arena_ind, false);
-
- arena_reset(tsd, arena);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-arena_i_dss_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- const char *dss = NULL;
- unsigned arena_ind = (unsigned)mib[1];
- dss_prec_t dss_prec_old = dss_prec_limit;
- dss_prec_t dss_prec = dss_prec_limit;
-
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- WRITE(dss, const char *);
- if (dss != NULL) {
- int i;
- bool match = false;
-
- for (i = 0; i < dss_prec_limit; i++) {
- if (strcmp(dss_prec_names[i], dss) == 0) {
- dss_prec = i;
- match = true;
- break;
- }
- }
-
- if (!match) {
- ret = EINVAL;
- goto label_return;
- }
- }
-
- if (arena_ind < ctl_stats.narenas) {
- arena_t *arena = arena_get(tsd_tsdn(tsd), arena_ind, false);
- if (arena == NULL || (dss_prec != dss_prec_limit &&
- arena_dss_prec_set(tsd_tsdn(tsd), arena, dss_prec))) {
- ret = EFAULT;
- goto label_return;
- }
- dss_prec_old = arena_dss_prec_get(tsd_tsdn(tsd), arena);
- } else {
- if (dss_prec != dss_prec_limit &&
- chunk_dss_prec_set(dss_prec)) {
- ret = EFAULT;
- goto label_return;
- }
- dss_prec_old = chunk_dss_prec_get();
- }
-
- dss = dss_prec_names[dss_prec_old];
- READ(dss, const char *);
-
- ret = 0;
-label_return:
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- return (ret);
-}
-
-static int
-arena_i_lg_dirty_mult_ctl(tsd_t *tsd, const size_t *mib, size_t miblen,
- void *oldp, size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned arena_ind = (unsigned)mib[1];
- arena_t *arena;
-
- arena = arena_get(tsd_tsdn(tsd), arena_ind, false);
- if (arena == NULL) {
- ret = EFAULT;
- goto label_return;
- }
-
- if (oldp != NULL && oldlenp != NULL) {
- size_t oldval = arena_lg_dirty_mult_get(tsd_tsdn(tsd), arena);
- READ(oldval, ssize_t);
- }
- if (newp != NULL) {
- if (newlen != sizeof(ssize_t)) {
- ret = EINVAL;
- goto label_return;
- }
- if (arena_lg_dirty_mult_set(tsd_tsdn(tsd), arena,
- *(ssize_t *)newp)) {
- ret = EFAULT;
- goto label_return;
- }
- }
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-arena_i_decay_time_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned arena_ind = (unsigned)mib[1];
- arena_t *arena;
-
- arena = arena_get(tsd_tsdn(tsd), arena_ind, false);
- if (arena == NULL) {
- ret = EFAULT;
- goto label_return;
- }
-
- if (oldp != NULL && oldlenp != NULL) {
- size_t oldval = arena_decay_time_get(tsd_tsdn(tsd), arena);
- READ(oldval, ssize_t);
- }
- if (newp != NULL) {
- if (newlen != sizeof(ssize_t)) {
- ret = EINVAL;
- goto label_return;
- }
- if (arena_decay_time_set(tsd_tsdn(tsd), arena,
- *(ssize_t *)newp)) {
- ret = EFAULT;
- goto label_return;
- }
- }
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-arena_i_chunk_hooks_ctl(tsd_t *tsd, const size_t *mib, size_t miblen,
- void *oldp, size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned arena_ind = (unsigned)mib[1];
- arena_t *arena;
-
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- if (arena_ind < narenas_total_get() && (arena =
- arena_get(tsd_tsdn(tsd), arena_ind, false)) != NULL) {
- if (newp != NULL) {
- chunk_hooks_t old_chunk_hooks, new_chunk_hooks;
- WRITE(new_chunk_hooks, chunk_hooks_t);
- old_chunk_hooks = chunk_hooks_set(tsd_tsdn(tsd), arena,
- &new_chunk_hooks);
- READ(old_chunk_hooks, chunk_hooks_t);
- } else {
- chunk_hooks_t old_chunk_hooks =
- chunk_hooks_get(tsd_tsdn(tsd), arena);
- READ(old_chunk_hooks, chunk_hooks_t);
- }
- } else {
- ret = EFAULT;
- goto label_return;
- }
- ret = 0;
-label_return:
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- return (ret);
-}
-
-static const ctl_named_node_t *
-arena_i_index(tsdn_t *tsdn, const size_t *mib, size_t miblen, size_t i)
-{
- const ctl_named_node_t *ret;
-
- malloc_mutex_lock(tsdn, &ctl_mtx);
- if (i > ctl_stats.narenas) {
- ret = NULL;
- goto label_return;
- }
-
- ret = super_arena_i_node;
-label_return:
- malloc_mutex_unlock(tsdn, &ctl_mtx);
- return (ret);
-}
-
-/******************************************************************************/
-
-static int
-arenas_narenas_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned narenas;
-
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- READONLY();
- if (*oldlenp != sizeof(unsigned)) {
- ret = EINVAL;
- goto label_return;
- }
- narenas = ctl_stats.narenas;
- READ(narenas, unsigned);
-
- ret = 0;
-label_return:
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- return (ret);
-}
-
-static int
-arenas_initialized_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned nread, i;
-
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- READONLY();
- if (*oldlenp != ctl_stats.narenas * sizeof(bool)) {
- ret = EINVAL;
- nread = (*oldlenp < ctl_stats.narenas * sizeof(bool))
- ? (unsigned)(*oldlenp / sizeof(bool)) : ctl_stats.narenas;
- } else {
- ret = 0;
- nread = ctl_stats.narenas;
- }
-
- for (i = 0; i < nread; i++)
- ((bool *)oldp)[i] = ctl_stats.arenas[i].initialized;
-
-label_return:
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- return (ret);
-}
-
-static int
-arenas_lg_dirty_mult_ctl(tsd_t *tsd, const size_t *mib, size_t miblen,
- void *oldp, size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
-
- if (oldp != NULL && oldlenp != NULL) {
- size_t oldval = arena_lg_dirty_mult_default_get();
- READ(oldval, ssize_t);
- }
- if (newp != NULL) {
- if (newlen != sizeof(ssize_t)) {
- ret = EINVAL;
- goto label_return;
- }
- if (arena_lg_dirty_mult_default_set(*(ssize_t *)newp)) {
- ret = EFAULT;
- goto label_return;
- }
- }
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-arenas_decay_time_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
-
- if (oldp != NULL && oldlenp != NULL) {
- size_t oldval = arena_decay_time_default_get();
- READ(oldval, ssize_t);
- }
- if (newp != NULL) {
- if (newlen != sizeof(ssize_t)) {
- ret = EINVAL;
- goto label_return;
- }
- if (arena_decay_time_default_set(*(ssize_t *)newp)) {
- ret = EFAULT;
- goto label_return;
- }
- }
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-CTL_RO_NL_GEN(arenas_quantum, QUANTUM, size_t)
-CTL_RO_NL_GEN(arenas_page, PAGE, size_t)
-CTL_RO_NL_CGEN(config_tcache, arenas_tcache_max, tcache_maxclass, size_t)
-CTL_RO_NL_GEN(arenas_nbins, NBINS, unsigned)
-CTL_RO_NL_CGEN(config_tcache, arenas_nhbins, nhbins, unsigned)
-CTL_RO_NL_GEN(arenas_bin_i_size, arena_bin_info[mib[2]].reg_size, size_t)
-CTL_RO_NL_GEN(arenas_bin_i_nregs, arena_bin_info[mib[2]].nregs, uint32_t)
-CTL_RO_NL_GEN(arenas_bin_i_run_size, arena_bin_info[mib[2]].run_size, size_t)
-static const ctl_named_node_t *
-arenas_bin_i_index(tsdn_t *tsdn, const size_t *mib, size_t miblen, size_t i)
-{
-
- if (i > NBINS)
- return (NULL);
- return (super_arenas_bin_i_node);
-}
-
-CTL_RO_NL_GEN(arenas_nlruns, nlclasses, unsigned)
-CTL_RO_NL_GEN(arenas_lrun_i_size, index2size(NBINS+(szind_t)mib[2]), size_t)
-static const ctl_named_node_t *
-arenas_lrun_i_index(tsdn_t *tsdn, const size_t *mib, size_t miblen, size_t i)
-{
-
- if (i > nlclasses)
- return (NULL);
- return (super_arenas_lrun_i_node);
-}
-
-CTL_RO_NL_GEN(arenas_nhchunks, nhclasses, unsigned)
-CTL_RO_NL_GEN(arenas_hchunk_i_size, index2size(NBINS+nlclasses+(szind_t)mib[2]),
- size_t)
-static const ctl_named_node_t *
-arenas_hchunk_i_index(tsdn_t *tsdn, const size_t *mib, size_t miblen, size_t i)
-{
-
- if (i > nhclasses)
- return (NULL);
- return (super_arenas_hchunk_i_node);
-}
-
-static int
-arenas_extend_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- unsigned narenas;
-
- malloc_mutex_lock(tsd_tsdn(tsd), &ctl_mtx);
- READONLY();
- if (ctl_grow(tsd_tsdn(tsd))) {
- ret = EAGAIN;
- goto label_return;
- }
- narenas = ctl_stats.narenas - 1;
- READ(narenas, unsigned);
-
- ret = 0;
-label_return:
- malloc_mutex_unlock(tsd_tsdn(tsd), &ctl_mtx);
- return (ret);
-}
-
-/******************************************************************************/
-
-static int
-prof_thread_active_init_ctl(tsd_t *tsd, const size_t *mib, size_t miblen,
- void *oldp, size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- bool oldval;
-
- if (!config_prof)
- return (ENOENT);
-
- if (newp != NULL) {
- if (newlen != sizeof(bool)) {
- ret = EINVAL;
- goto label_return;
- }
- oldval = prof_thread_active_init_set(tsd_tsdn(tsd),
- *(bool *)newp);
- } else
- oldval = prof_thread_active_init_get(tsd_tsdn(tsd));
- READ(oldval, bool);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-prof_active_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- bool oldval;
-
- if (!config_prof)
- return (ENOENT);
-
- if (newp != NULL) {
- if (newlen != sizeof(bool)) {
- ret = EINVAL;
- goto label_return;
- }
- oldval = prof_active_set(tsd_tsdn(tsd), *(bool *)newp);
- } else
- oldval = prof_active_get(tsd_tsdn(tsd));
- READ(oldval, bool);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-prof_dump_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- const char *filename = NULL;
-
- if (!config_prof)
- return (ENOENT);
-
- WRITEONLY();
- WRITE(filename, const char *);
-
- if (prof_mdump(tsd, filename)) {
- ret = EFAULT;
- goto label_return;
- }
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-prof_gdump_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- bool oldval;
-
- if (!config_prof)
- return (ENOENT);
-
- if (newp != NULL) {
- if (newlen != sizeof(bool)) {
- ret = EINVAL;
- goto label_return;
- }
- oldval = prof_gdump_set(tsd_tsdn(tsd), *(bool *)newp);
- } else
- oldval = prof_gdump_get(tsd_tsdn(tsd));
- READ(oldval, bool);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-static int
-prof_reset_ctl(tsd_t *tsd, const size_t *mib, size_t miblen, void *oldp,
- size_t *oldlenp, void *newp, size_t newlen)
-{
- int ret;
- size_t lg_sample = lg_prof_sample;
-
- if (!config_prof)
- return (ENOENT);
-
- WRITEONLY();
- WRITE(lg_sample, size_t);
- if (lg_sample >= (sizeof(uint64_t) << 3))
- lg_sample = (sizeof(uint64_t) << 3) - 1;
-
- prof_reset(tsd, lg_sample);
-
- ret = 0;
-label_return:
- return (ret);
-}
-
-CTL_RO_NL_CGEN(config_prof, prof_interval, prof_interval, uint64_t)
-CTL_RO_NL_CGEN(config_prof, lg_prof_sample, lg_prof_sample, size_t)
-
-/******************************************************************************/
-
-CTL_RO_CGEN(config_stats, stats_cactive, &stats_cactive, size_t *)
-CTL_RO_CGEN(config_stats, stats_allocated, ctl_stats.allocated, size_t)
-CTL_RO_CGEN(config_stats, stats_active, ctl_stats.active, size_t)
-CTL_RO_CGEN(config_stats, stats_metadata, ctl_stats.metadata, size_t)
-CTL_RO_CGEN(config_stats, stats_resident, ctl_stats.resident, size_t)
-CTL_RO_CGEN(config_stats, stats_mapped, ctl_stats.mapped, size_t)
-CTL_RO_CGEN(config_stats, stats_retained, ctl_stats.retained, size_t)
-
-CTL_RO_GEN(stats_arenas_i_dss, ctl_stats.arenas[mib[2]].dss, const char *)
-CTL_RO_GEN(stats_arenas_i_lg_dirty_mult, ctl_stats.arenas[mib[2]].lg_dirty_mult,
- ssize_t)
-CTL_RO_GEN(stats_arenas_i_decay_time, ctl_stats.arenas[mib[2]].decay_time,
- ssize_t)
-CTL_RO_GEN(stats_arenas_i_nthreads, ctl_stats.arenas[mib[2]].nthreads, unsigned)
-CTL_RO_GEN(stats_arenas_i_pactive, ctl_stats.arenas[mib[2]].pactive, size_t)
-CTL_RO_GEN(stats_arenas_i_pdirty, ctl_stats.arenas[mib[2]].pdirty, size_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_mapped,
- ctl_stats.arenas[mib[2]].astats.mapped, size_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_retained,
- ctl_stats.arenas[mib[2]].astats.retained, size_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_npurge,
- ctl_stats.arenas[mib[2]].astats.npurge, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_nmadvise,
- ctl_stats.arenas[mib[2]].astats.nmadvise, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_purged,
- ctl_stats.arenas[mib[2]].astats.purged, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_metadata_mapped,
- ctl_stats.arenas[mib[2]].astats.metadata_mapped, size_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_metadata_allocated,
- ctl_stats.arenas[mib[2]].astats.metadata_allocated, size_t)
-
-CTL_RO_CGEN(config_stats, stats_arenas_i_small_allocated,
- ctl_stats.arenas[mib[2]].allocated_small, size_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_small_nmalloc,
- ctl_stats.arenas[mib[2]].nmalloc_small, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_small_ndalloc,
- ctl_stats.arenas[mib[2]].ndalloc_small, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_small_nrequests,
- ctl_stats.arenas[mib[2]].nrequests_small, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_large_allocated,
- ctl_stats.arenas[mib[2]].astats.allocated_large, size_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_large_nmalloc,
- ctl_stats.arenas[mib[2]].astats.nmalloc_large, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_large_ndalloc,
- ctl_stats.arenas[mib[2]].astats.ndalloc_large, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_large_nrequests,
- ctl_stats.arenas[mib[2]].astats.nrequests_large, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_huge_allocated,
- ctl_stats.arenas[mib[2]].astats.allocated_huge, size_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_huge_nmalloc,
- ctl_stats.arenas[mib[2]].astats.nmalloc_huge, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_huge_ndalloc,
- ctl_stats.arenas[mib[2]].astats.ndalloc_huge, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_huge_nrequests,
- ctl_stats.arenas[mib[2]].astats.nmalloc_huge, uint64_t) /* Intentional. */
-
-CTL_RO_CGEN(config_stats, stats_arenas_i_bins_j_nmalloc,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].nmalloc, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_bins_j_ndalloc,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].ndalloc, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_bins_j_nrequests,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].nrequests, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_bins_j_curregs,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].curregs, size_t)
-CTL_RO_CGEN(config_stats && config_tcache, stats_arenas_i_bins_j_nfills,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].nfills, uint64_t)
-CTL_RO_CGEN(config_stats && config_tcache, stats_arenas_i_bins_j_nflushes,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].nflushes, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_bins_j_nruns,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].nruns, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_bins_j_nreruns,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].reruns, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_bins_j_curruns,
- ctl_stats.arenas[mib[2]].bstats[mib[4]].curruns, size_t)
-
-static const ctl_named_node_t *
-stats_arenas_i_bins_j_index(tsdn_t *tsdn, const size_t *mib, size_t miblen,
- size_t j)
-{
-
- if (j > NBINS)
- return (NULL);
- return (super_stats_arenas_i_bins_j_node);
-}
-
-CTL_RO_CGEN(config_stats, stats_arenas_i_lruns_j_nmalloc,
- ctl_stats.arenas[mib[2]].lstats[mib[4]].nmalloc, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_lruns_j_ndalloc,
- ctl_stats.arenas[mib[2]].lstats[mib[4]].ndalloc, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_lruns_j_nrequests,
- ctl_stats.arenas[mib[2]].lstats[mib[4]].nrequests, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_lruns_j_curruns,
- ctl_stats.arenas[mib[2]].lstats[mib[4]].curruns, size_t)
-
-static const ctl_named_node_t *
-stats_arenas_i_lruns_j_index(tsdn_t *tsdn, const size_t *mib, size_t miblen,
- size_t j)
-{
-
- if (j > nlclasses)
- return (NULL);
- return (super_stats_arenas_i_lruns_j_node);
-}
-
-CTL_RO_CGEN(config_stats, stats_arenas_i_hchunks_j_nmalloc,
- ctl_stats.arenas[mib[2]].hstats[mib[4]].nmalloc, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_hchunks_j_ndalloc,
- ctl_stats.arenas[mib[2]].hstats[mib[4]].ndalloc, uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_hchunks_j_nrequests,
- ctl_stats.arenas[mib[2]].hstats[mib[4]].nmalloc, /* Intentional. */
- uint64_t)
-CTL_RO_CGEN(config_stats, stats_arenas_i_hchunks_j_curhchunks,
- ctl_stats.arenas[mib[2]].hstats[mib[4]].curhchunks, size_t)
-
-static const ctl_named_node_t *
-stats_arenas_i_hchunks_j_index(tsdn_t *tsdn, const size_t *mib, size_t miblen,
- size_t j)
-{
-
- if (j > nhclasses)
- return (NULL);
- return (super_stats_arenas_i_hchunks_j_node);
-}
-
-static const ctl_named_node_t *
-stats_arenas_i_index(tsdn_t *tsdn, const size_t *mib, size_t miblen, size_t i)
-{
- const ctl_named_node_t * ret;
-
- malloc_mutex_lock(tsdn, &ctl_mtx);
- if (i > ctl_stats.narenas || !ctl_stats.arenas[i].initialized) {
- ret = NULL;
- goto label_return;
- }
-
- ret = super_stats_arenas_i_node;
-label_return:
- malloc_mutex_unlock(tsdn, &ctl_mtx);
- return (ret);
-}
diff --git a/memory/jemalloc/src/src/extent.c b/memory/jemalloc/src/src/extent.c
deleted file mode 100644
index 9f5146e5f..000000000
--- a/memory/jemalloc/src/src/extent.c
+++ /dev/null
@@ -1,53 +0,0 @@
-#define JEMALLOC_EXTENT_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-
-JEMALLOC_INLINE_C size_t
-extent_quantize(size_t size)
-{
-
- /*
- * Round down to the nearest chunk size that can actually be requested
- * during normal huge allocation.
- */
- return (index2size(size2index(size + 1) - 1));
-}
-
-JEMALLOC_INLINE_C int
-extent_szad_comp(const extent_node_t *a, const extent_node_t *b)
-{
- int ret;
- size_t a_qsize = extent_quantize(extent_node_size_get(a));
- size_t b_qsize = extent_quantize(extent_node_size_get(b));
-
- /*
- * Compare based on quantized size rather than size, in order to sort
- * equally useful extents only by address.
- */
- ret = (a_qsize > b_qsize) - (a_qsize < b_qsize);
- if (ret == 0) {
- uintptr_t a_addr = (uintptr_t)extent_node_addr_get(a);
- uintptr_t b_addr = (uintptr_t)extent_node_addr_get(b);
-
- ret = (a_addr > b_addr) - (a_addr < b_addr);
- }
-
- return (ret);
-}
-
-/* Generate red-black tree functions. */
-rb_gen(, extent_tree_szad_, extent_tree_t, extent_node_t, szad_link,
- extent_szad_comp)
-
-JEMALLOC_INLINE_C int
-extent_ad_comp(const extent_node_t *a, const extent_node_t *b)
-{
- uintptr_t a_addr = (uintptr_t)extent_node_addr_get(a);
- uintptr_t b_addr = (uintptr_t)extent_node_addr_get(b);
-
- return ((a_addr > b_addr) - (a_addr < b_addr));
-}
-
-/* Generate red-black tree functions. */
-rb_gen(, extent_tree_ad_, extent_tree_t, extent_node_t, ad_link, extent_ad_comp)
diff --git a/memory/jemalloc/src/src/hash.c b/memory/jemalloc/src/src/hash.c
deleted file mode 100644
index cfa4da027..000000000
--- a/memory/jemalloc/src/src/hash.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#define JEMALLOC_HASH_C_
-#include "jemalloc/internal/jemalloc_internal.h"
diff --git a/memory/jemalloc/src/src/huge.c b/memory/jemalloc/src/src/huge.c
deleted file mode 100644
index 62e6932b7..000000000
--- a/memory/jemalloc/src/src/huge.c
+++ /dev/null
@@ -1,473 +0,0 @@
-#define JEMALLOC_HUGE_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-
-static extent_node_t *
-huge_node_get(const void *ptr)
-{
- extent_node_t *node;
-
- node = chunk_lookup(ptr, true);
- assert(!extent_node_achunk_get(node));
-
- return (node);
-}
-
-static bool
-huge_node_set(tsdn_t *tsdn, const void *ptr, extent_node_t *node)
-{
-
- assert(extent_node_addr_get(node) == ptr);
- assert(!extent_node_achunk_get(node));
- return (chunk_register(tsdn, ptr, node));
-}
-
-static void
-huge_node_reset(tsdn_t *tsdn, const void *ptr, extent_node_t *node)
-{
- bool err;
-
- err = huge_node_set(tsdn, ptr, node);
- assert(!err);
-}
-
-static void
-huge_node_unset(const void *ptr, const extent_node_t *node)
-{
-
- chunk_deregister(ptr, node);
-}
-
-void *
-huge_malloc(tsdn_t *tsdn, arena_t *arena, size_t usize, bool zero)
-{
-
- assert(usize == s2u(usize));
-
- return (huge_palloc(tsdn, arena, usize, chunksize, zero));
-}
-
-void *
-huge_palloc(tsdn_t *tsdn, arena_t *arena, size_t usize, size_t alignment,
- bool zero)
-{
- void *ret;
- size_t ausize;
- arena_t *iarena;
- extent_node_t *node;
- bool is_zeroed;
-
- /* Allocate one or more contiguous chunks for this request. */
-
- assert(!tsdn_null(tsdn) || arena != NULL);
-
- ausize = sa2u(usize, alignment);
- if (unlikely(ausize == 0 || ausize > HUGE_MAXCLASS))
- return (NULL);
- assert(ausize >= chunksize);
-
- /* Allocate an extent node with which to track the chunk. */
- iarena = (!tsdn_null(tsdn)) ? arena_ichoose(tsdn_tsd(tsdn), NULL) : a0get();
- node = ipallocztm(tsdn, CACHELINE_CEILING(sizeof(extent_node_t)),
- CACHELINE, false, NULL, true, iarena);
- if (node == NULL)
- return (NULL);
-
- /*
- * Copy zero into is_zeroed and pass the copy to chunk_alloc(), so that
- * it is possible to make correct junk/zero fill decisions below.
- */
- is_zeroed = zero;
- if (likely(!tsdn_null(tsdn)))
- arena = arena_choose(tsdn_tsd(tsdn), arena);
- if (unlikely(arena == NULL) || (ret = arena_chunk_alloc_huge(tsdn,
- arena, usize, alignment, &is_zeroed)) == NULL) {
- idalloctm(tsdn, node, NULL, true, true);
- return (NULL);
- }
-
- extent_node_init(node, arena, ret, usize, is_zeroed, true);
-
- if (huge_node_set(tsdn, ret, node)) {
- arena_chunk_dalloc_huge(tsdn, arena, ret, usize);
- idalloctm(tsdn, node, NULL, true, true);
- return (NULL);
- }
-
- /* Insert node into huge. */
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- ql_elm_new(node, ql_link);
- ql_tail_insert(&arena->huge, node, ql_link);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-
- if (zero || (config_fill && unlikely(opt_zero))) {
- if (!is_zeroed)
- memset(ret, 0, usize);
- } else if (config_fill && unlikely(opt_junk_alloc))
- memset(ret, JEMALLOC_ALLOC_JUNK, usize);
-
- arena_decay_tick(tsdn, arena);
- return (ret);
-}
-
-#ifdef JEMALLOC_JET
-#undef huge_dalloc_junk
-#define huge_dalloc_junk JEMALLOC_N(huge_dalloc_junk_impl)
-#endif
-static void
-huge_dalloc_junk(void *ptr, size_t usize)
-{
-
- if (config_fill && have_dss && unlikely(opt_junk_free)) {
- /*
- * Only bother junk filling if the chunk isn't about to be
- * unmapped.
- */
- if (!config_munmap || (have_dss && chunk_in_dss(ptr)))
- memset(ptr, JEMALLOC_FREE_JUNK, usize);
- }
-}
-#ifdef JEMALLOC_JET
-#undef huge_dalloc_junk
-#define huge_dalloc_junk JEMALLOC_N(huge_dalloc_junk)
-huge_dalloc_junk_t *huge_dalloc_junk = JEMALLOC_N(huge_dalloc_junk_impl);
-#endif
-
-static void
-huge_ralloc_no_move_similar(tsdn_t *tsdn, void *ptr, size_t oldsize,
- size_t usize_min, size_t usize_max, bool zero)
-{
- size_t usize, usize_next;
- extent_node_t *node;
- arena_t *arena;
- chunk_hooks_t chunk_hooks = CHUNK_HOOKS_INITIALIZER;
- bool pre_zeroed, post_zeroed;
-
- /* Increase usize to incorporate extra. */
- for (usize = usize_min; usize < usize_max && (usize_next = s2u(usize+1))
- <= oldsize; usize = usize_next)
- ; /* Do nothing. */
-
- if (oldsize == usize)
- return;
-
- node = huge_node_get(ptr);
- arena = extent_node_arena_get(node);
- pre_zeroed = extent_node_zeroed_get(node);
-
- /* Fill if necessary (shrinking). */
- if (oldsize > usize) {
- size_t sdiff = oldsize - usize;
- if (config_fill && unlikely(opt_junk_free)) {
- memset((void *)((uintptr_t)ptr + usize),
- JEMALLOC_FREE_JUNK, sdiff);
- post_zeroed = false;
- } else {
- post_zeroed = !chunk_purge_wrapper(tsdn, arena,
- &chunk_hooks, ptr, CHUNK_CEILING(oldsize), usize,
- sdiff);
- }
- } else
- post_zeroed = pre_zeroed;
-
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- /* Update the size of the huge allocation. */
- huge_node_unset(ptr, node);
- assert(extent_node_size_get(node) != usize);
- extent_node_size_set(node, usize);
- huge_node_reset(tsdn, ptr, node);
- /* Update zeroed. */
- extent_node_zeroed_set(node, post_zeroed);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-
- arena_chunk_ralloc_huge_similar(tsdn, arena, ptr, oldsize, usize);
-
- /* Fill if necessary (growing). */
- if (oldsize < usize) {
- if (zero || (config_fill && unlikely(opt_zero))) {
- if (!pre_zeroed) {
- memset((void *)((uintptr_t)ptr + oldsize), 0,
- usize - oldsize);
- }
- } else if (config_fill && unlikely(opt_junk_alloc)) {
- memset((void *)((uintptr_t)ptr + oldsize),
- JEMALLOC_ALLOC_JUNK, usize - oldsize);
- }
- }
-}
-
-static bool
-huge_ralloc_no_move_shrink(tsdn_t *tsdn, void *ptr, size_t oldsize,
- size_t usize)
-{
- extent_node_t *node;
- arena_t *arena;
- chunk_hooks_t chunk_hooks;
- size_t cdiff;
- bool pre_zeroed, post_zeroed;
-
- node = huge_node_get(ptr);
- arena = extent_node_arena_get(node);
- pre_zeroed = extent_node_zeroed_get(node);
- chunk_hooks = chunk_hooks_get(tsdn, arena);
-
- assert(oldsize > usize);
-
- /* Split excess chunks. */
- cdiff = CHUNK_CEILING(oldsize) - CHUNK_CEILING(usize);
- if (cdiff != 0 && chunk_hooks.split(ptr, CHUNK_CEILING(oldsize),
- CHUNK_CEILING(usize), cdiff, true, arena->ind))
- return (true);
-
- if (oldsize > usize) {
- size_t sdiff = oldsize - usize;
- if (config_fill && unlikely(opt_junk_free)) {
- huge_dalloc_junk((void *)((uintptr_t)ptr + usize),
- sdiff);
- post_zeroed = false;
- } else {
- post_zeroed = !chunk_purge_wrapper(tsdn, arena,
- &chunk_hooks, CHUNK_ADDR2BASE((uintptr_t)ptr +
- usize), CHUNK_CEILING(oldsize),
- CHUNK_ADDR2OFFSET((uintptr_t)ptr + usize), sdiff);
- }
- } else
- post_zeroed = pre_zeroed;
-
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- /* Update the size of the huge allocation. */
- huge_node_unset(ptr, node);
- extent_node_size_set(node, usize);
- huge_node_reset(tsdn, ptr, node);
- /* Update zeroed. */
- extent_node_zeroed_set(node, post_zeroed);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-
- /* Zap the excess chunks. */
- arena_chunk_ralloc_huge_shrink(tsdn, arena, ptr, oldsize, usize);
-
- return (false);
-}
-
-static bool
-huge_ralloc_no_move_expand(tsdn_t *tsdn, void *ptr, size_t oldsize,
- size_t usize, bool zero) {
- extent_node_t *node;
- arena_t *arena;
- bool is_zeroed_subchunk, is_zeroed_chunk;
-
- node = huge_node_get(ptr);
- arena = extent_node_arena_get(node);
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- is_zeroed_subchunk = extent_node_zeroed_get(node);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-
- /*
- * Use is_zeroed_chunk to detect whether the trailing memory is zeroed,
- * update extent's zeroed field, and zero as necessary.
- */
- is_zeroed_chunk = false;
- if (arena_chunk_ralloc_huge_expand(tsdn, arena, ptr, oldsize, usize,
- &is_zeroed_chunk))
- return (true);
-
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- huge_node_unset(ptr, node);
- extent_node_size_set(node, usize);
- extent_node_zeroed_set(node, extent_node_zeroed_get(node) &&
- is_zeroed_chunk);
- huge_node_reset(tsdn, ptr, node);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-
- if (zero || (config_fill && unlikely(opt_zero))) {
- if (!is_zeroed_subchunk) {
- memset((void *)((uintptr_t)ptr + oldsize), 0,
- CHUNK_CEILING(oldsize) - oldsize);
- }
- if (!is_zeroed_chunk) {
- memset((void *)((uintptr_t)ptr +
- CHUNK_CEILING(oldsize)), 0, usize -
- CHUNK_CEILING(oldsize));
- }
- } else if (config_fill && unlikely(opt_junk_alloc)) {
- memset((void *)((uintptr_t)ptr + oldsize), JEMALLOC_ALLOC_JUNK,
- usize - oldsize);
- }
-
- return (false);
-}
-
-bool
-huge_ralloc_no_move(tsdn_t *tsdn, void *ptr, size_t oldsize, size_t usize_min,
- size_t usize_max, bool zero)
-{
-
- assert(s2u(oldsize) == oldsize);
- /* The following should have been caught by callers. */
- assert(usize_min > 0 && usize_max <= HUGE_MAXCLASS);
-
- /* Both allocations must be huge to avoid a move. */
- if (oldsize < chunksize || usize_max < chunksize)
- return (true);
-
- if (CHUNK_CEILING(usize_max) > CHUNK_CEILING(oldsize)) {
- /* Attempt to expand the allocation in-place. */
- if (!huge_ralloc_no_move_expand(tsdn, ptr, oldsize, usize_max,
- zero)) {
- arena_decay_tick(tsdn, huge_aalloc(ptr));
- return (false);
- }
- /* Try again, this time with usize_min. */
- if (usize_min < usize_max && CHUNK_CEILING(usize_min) >
- CHUNK_CEILING(oldsize) && huge_ralloc_no_move_expand(tsdn,
- ptr, oldsize, usize_min, zero)) {
- arena_decay_tick(tsdn, huge_aalloc(ptr));
- return (false);
- }
- }
-
- /*
- * Avoid moving the allocation if the existing chunk size accommodates
- * the new size.
- */
- if (CHUNK_CEILING(oldsize) >= CHUNK_CEILING(usize_min)
- && CHUNK_CEILING(oldsize) <= CHUNK_CEILING(usize_max)) {
- huge_ralloc_no_move_similar(tsdn, ptr, oldsize, usize_min,
- usize_max, zero);
- arena_decay_tick(tsdn, huge_aalloc(ptr));
- return (false);
- }
-
- /* Attempt to shrink the allocation in-place. */
- if (CHUNK_CEILING(oldsize) > CHUNK_CEILING(usize_max)) {
- if (!huge_ralloc_no_move_shrink(tsdn, ptr, oldsize,
- usize_max)) {
- arena_decay_tick(tsdn, huge_aalloc(ptr));
- return (false);
- }
- }
- return (true);
-}
-
-static void *
-huge_ralloc_move_helper(tsdn_t *tsdn, arena_t *arena, size_t usize,
- size_t alignment, bool zero)
-{
-
- if (alignment <= chunksize)
- return (huge_malloc(tsdn, arena, usize, zero));
- return (huge_palloc(tsdn, arena, usize, alignment, zero));
-}
-
-void *
-huge_ralloc(tsd_t *tsd, arena_t *arena, void *ptr, size_t oldsize,
- size_t usize, size_t alignment, bool zero, tcache_t *tcache)
-{
- void *ret;
- size_t copysize;
-
- /* The following should have been caught by callers. */
- assert(usize > 0 && usize <= HUGE_MAXCLASS);
-
- /* Try to avoid moving the allocation. */
- if (!huge_ralloc_no_move(tsd_tsdn(tsd), ptr, oldsize, usize, usize,
- zero))
- return (ptr);
-
- /*
- * usize and oldsize are different enough that we need to use a
- * different size class. In that case, fall back to allocating new
- * space and copying.
- */
- ret = huge_ralloc_move_helper(tsd_tsdn(tsd), arena, usize, alignment,
- zero);
- if (ret == NULL)
- return (NULL);
-
- copysize = (usize < oldsize) ? usize : oldsize;
- memcpy(ret, ptr, copysize);
- isqalloc(tsd, ptr, oldsize, tcache, true);
- return (ret);
-}
-
-void
-huge_dalloc(tsdn_t *tsdn, void *ptr)
-{
- extent_node_t *node;
- arena_t *arena;
-
- node = huge_node_get(ptr);
- arena = extent_node_arena_get(node);
- huge_node_unset(ptr, node);
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- ql_remove(&arena->huge, node, ql_link);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-
- huge_dalloc_junk(extent_node_addr_get(node),
- extent_node_size_get(node));
- arena_chunk_dalloc_huge(tsdn, extent_node_arena_get(node),
- extent_node_addr_get(node), extent_node_size_get(node));
- idalloctm(tsdn, node, NULL, true, true);
-
- arena_decay_tick(tsdn, arena);
-}
-
-arena_t *
-huge_aalloc(const void *ptr)
-{
-
- return (extent_node_arena_get(huge_node_get(ptr)));
-}
-
-size_t
-huge_salloc(tsdn_t *tsdn, const void *ptr)
-{
- size_t size;
- extent_node_t *node;
- arena_t *arena;
-
- node = huge_node_get(ptr);
- arena = extent_node_arena_get(node);
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- size = extent_node_size_get(node);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-
- return (size);
-}
-
-prof_tctx_t *
-huge_prof_tctx_get(tsdn_t *tsdn, const void *ptr)
-{
- prof_tctx_t *tctx;
- extent_node_t *node;
- arena_t *arena;
-
- node = huge_node_get(ptr);
- arena = extent_node_arena_get(node);
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- tctx = extent_node_prof_tctx_get(node);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-
- return (tctx);
-}
-
-void
-huge_prof_tctx_set(tsdn_t *tsdn, const void *ptr, prof_tctx_t *tctx)
-{
- extent_node_t *node;
- arena_t *arena;
-
- node = huge_node_get(ptr);
- arena = extent_node_arena_get(node);
- malloc_mutex_lock(tsdn, &arena->huge_mtx);
- extent_node_prof_tctx_set(node, tctx);
- malloc_mutex_unlock(tsdn, &arena->huge_mtx);
-}
-
-void
-huge_prof_tctx_reset(tsdn_t *tsdn, const void *ptr)
-{
-
- huge_prof_tctx_set(tsdn, ptr, (prof_tctx_t *)(uintptr_t)1U);
-}
diff --git a/memory/jemalloc/src/src/jemalloc.c b/memory/jemalloc/src/src/jemalloc.c
deleted file mode 100644
index 38650ff06..000000000
--- a/memory/jemalloc/src/src/jemalloc.c
+++ /dev/null
@@ -1,2897 +0,0 @@
-#define JEMALLOC_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Data. */
-
-/* Runtime configuration options. */
-const char *je_malloc_conf
-#ifndef _WIN32
- JEMALLOC_ATTR(weak)
-#endif
- ;
-bool opt_abort =
-#ifdef JEMALLOC_DEBUG
- true
-#else
- false
-#endif
- ;
-const char *opt_junk =
-#if (defined(JEMALLOC_DEBUG) && defined(JEMALLOC_FILL))
- "true"
-#else
- "false"
-#endif
- ;
-bool opt_junk_alloc =
-#if (defined(JEMALLOC_DEBUG) && defined(JEMALLOC_FILL))
- true
-#else
- false
-#endif
- ;
-bool opt_junk_free =
-#if (defined(JEMALLOC_DEBUG) && defined(JEMALLOC_FILL))
- true
-#else
- false
-#endif
- ;
-
-size_t opt_quarantine = ZU(0);
-bool opt_redzone = false;
-bool opt_utrace = false;
-bool opt_xmalloc = false;
-bool opt_zero = false;
-unsigned opt_narenas = 0;
-
-/* Initialized to true if the process is running inside Valgrind. */
-bool in_valgrind;
-
-unsigned ncpus;
-
-/* Protects arenas initialization. */
-static malloc_mutex_t arenas_lock;
-/*
- * Arenas that are used to service external requests. Not all elements of the
- * arenas array are necessarily used; arenas are created lazily as needed.
- *
- * arenas[0..narenas_auto) are used for automatic multiplexing of threads and
- * arenas. arenas[narenas_auto..narenas_total) are only used if the application
- * takes some action to create them and allocate from them.
- */
-arena_t **arenas;
-static unsigned narenas_total; /* Use narenas_total_*(). */
-static arena_t *a0; /* arenas[0]; read-only after initialization. */
-unsigned narenas_auto; /* Read-only after initialization. */
-
-typedef enum {
- malloc_init_uninitialized = 3,
- malloc_init_a0_initialized = 2,
- malloc_init_recursible = 1,
- malloc_init_initialized = 0 /* Common case --> jnz. */
-} malloc_init_t;
-static malloc_init_t malloc_init_state = malloc_init_uninitialized;
-
-/* False should be the common case. Set to true to trigger initialization. */
-static bool malloc_slow = true;
-
-/* When malloc_slow is true, set the corresponding bits for sanity check. */
-enum {
- flag_opt_junk_alloc = (1U),
- flag_opt_junk_free = (1U << 1),
- flag_opt_quarantine = (1U << 2),
- flag_opt_zero = (1U << 3),
- flag_opt_utrace = (1U << 4),
- flag_in_valgrind = (1U << 5),
- flag_opt_xmalloc = (1U << 6)
-};
-static uint8_t malloc_slow_flags;
-
-JEMALLOC_ALIGNED(CACHELINE)
-const size_t pind2sz_tab[NPSIZES] = {
-#define PSZ_yes(lg_grp, ndelta, lg_delta) \
- (((ZU(1)<<lg_grp) + (ZU(ndelta)<<lg_delta))),
-#define PSZ_no(lg_grp, ndelta, lg_delta)
-#define SC(index, lg_grp, lg_delta, ndelta, psz, bin, lg_delta_lookup) \
- PSZ_##psz(lg_grp, ndelta, lg_delta)
- SIZE_CLASSES
-#undef PSZ_yes
-#undef PSZ_no
-#undef SC
-};
-
-JEMALLOC_ALIGNED(CACHELINE)
-const size_t index2size_tab[NSIZES] = {
-#define SC(index, lg_grp, lg_delta, ndelta, psz, bin, lg_delta_lookup) \
- ((ZU(1)<<lg_grp) + (ZU(ndelta)<<lg_delta)),
- SIZE_CLASSES
-#undef SC
-};
-
-JEMALLOC_ALIGNED(CACHELINE)
-const uint8_t size2index_tab[] = {
-#if LG_TINY_MIN == 0
-#warning "Dangerous LG_TINY_MIN"
-#define S2B_0(i) i,
-#elif LG_TINY_MIN == 1
-#warning "Dangerous LG_TINY_MIN"
-#define S2B_1(i) i,
-#elif LG_TINY_MIN == 2
-#warning "Dangerous LG_TINY_MIN"
-#define S2B_2(i) i,
-#elif LG_TINY_MIN == 3
-#define S2B_3(i) i,
-#elif LG_TINY_MIN == 4
-#define S2B_4(i) i,
-#elif LG_TINY_MIN == 5
-#define S2B_5(i) i,
-#elif LG_TINY_MIN == 6
-#define S2B_6(i) i,
-#elif LG_TINY_MIN == 7
-#define S2B_7(i) i,
-#elif LG_TINY_MIN == 8
-#define S2B_8(i) i,
-#elif LG_TINY_MIN == 9
-#define S2B_9(i) i,
-#elif LG_TINY_MIN == 10
-#define S2B_10(i) i,
-#elif LG_TINY_MIN == 11
-#define S2B_11(i) i,
-#else
-#error "Unsupported LG_TINY_MIN"
-#endif
-#if LG_TINY_MIN < 1
-#define S2B_1(i) S2B_0(i) S2B_0(i)
-#endif
-#if LG_TINY_MIN < 2
-#define S2B_2(i) S2B_1(i) S2B_1(i)
-#endif
-#if LG_TINY_MIN < 3
-#define S2B_3(i) S2B_2(i) S2B_2(i)
-#endif
-#if LG_TINY_MIN < 4
-#define S2B_4(i) S2B_3(i) S2B_3(i)
-#endif
-#if LG_TINY_MIN < 5
-#define S2B_5(i) S2B_4(i) S2B_4(i)
-#endif
-#if LG_TINY_MIN < 6
-#define S2B_6(i) S2B_5(i) S2B_5(i)
-#endif
-#if LG_TINY_MIN < 7
-#define S2B_7(i) S2B_6(i) S2B_6(i)
-#endif
-#if LG_TINY_MIN < 8
-#define S2B_8(i) S2B_7(i) S2B_7(i)
-#endif
-#if LG_TINY_MIN < 9
-#define S2B_9(i) S2B_8(i) S2B_8(i)
-#endif
-#if LG_TINY_MIN < 10
-#define S2B_10(i) S2B_9(i) S2B_9(i)
-#endif
-#if LG_TINY_MIN < 11
-#define S2B_11(i) S2B_10(i) S2B_10(i)
-#endif
-#define S2B_no(i)
-#define SC(index, lg_grp, lg_delta, ndelta, psz, bin, lg_delta_lookup) \
- S2B_##lg_delta_lookup(index)
- SIZE_CLASSES
-#undef S2B_3
-#undef S2B_4
-#undef S2B_5
-#undef S2B_6
-#undef S2B_7
-#undef S2B_8
-#undef S2B_9
-#undef S2B_10
-#undef S2B_11
-#undef S2B_no
-#undef SC
-};
-
-#ifdef JEMALLOC_THREADED_INIT
-/* Used to let the initializing thread recursively allocate. */
-# define NO_INITIALIZER ((unsigned long)0)
-# define INITIALIZER pthread_self()
-# define IS_INITIALIZER (malloc_initializer == pthread_self())
-static pthread_t malloc_initializer = NO_INITIALIZER;
-#else
-# define NO_INITIALIZER false
-# define INITIALIZER true
-# define IS_INITIALIZER malloc_initializer
-static bool malloc_initializer = NO_INITIALIZER;
-#endif
-
-/* Used to avoid initialization races. */
-#ifdef _WIN32
-#if _WIN32_WINNT >= 0x0600
-static malloc_mutex_t init_lock = SRWLOCK_INIT;
-#else
-static malloc_mutex_t init_lock;
-static bool init_lock_initialized = false;
-
-JEMALLOC_ATTR(constructor)
-static void WINAPI
-_init_init_lock(void)
-{
-
- /* If another constructor in the same binary is using mallctl to
- * e.g. setup chunk hooks, it may end up running before this one,
- * and malloc_init_hard will crash trying to lock the uninitialized
- * lock. So we force an initialization of the lock in
- * malloc_init_hard as well. We don't try to care about atomicity
- * of the accessed to the init_lock_initialized boolean, since it
- * really only matters early in the process creation, before any
- * separate thread normally starts doing anything. */
- if (!init_lock_initialized)
- malloc_mutex_init(&init_lock, "init", WITNESS_RANK_INIT);
- init_lock_initialized = true;
-}
-
-#ifdef _MSC_VER
-# pragma section(".CRT$XCU", read)
-JEMALLOC_SECTION(".CRT$XCU") JEMALLOC_ATTR(used)
-static const void (WINAPI *init_init_lock)(void) = _init_init_lock;
-#endif
-#endif
-#else
-static malloc_mutex_t init_lock = MALLOC_MUTEX_INITIALIZER;
-#endif
-
-typedef struct {
- void *p; /* Input pointer (as in realloc(p, s)). */
- size_t s; /* Request size. */
- void *r; /* Result pointer. */
-} malloc_utrace_t;
-
-#ifdef JEMALLOC_UTRACE
-# define UTRACE(a, b, c) do { \
- if (unlikely(opt_utrace)) { \
- int utrace_serrno = errno; \
- malloc_utrace_t ut; \
- ut.p = (a); \
- ut.s = (b); \
- ut.r = (c); \
- utrace(&ut, sizeof(ut)); \
- errno = utrace_serrno; \
- } \
-} while (0)
-#else
-# define UTRACE(a, b, c)
-#endif
-
-/******************************************************************************/
-/*
- * Function prototypes for static functions that are referenced prior to
- * definition.
- */
-
-static bool malloc_init_hard_a0(void);
-static bool malloc_init_hard(void);
-
-/******************************************************************************/
-/*
- * Begin miscellaneous support functions.
- */
-
-JEMALLOC_ALWAYS_INLINE_C bool
-malloc_initialized(void)
-{
-
- return (malloc_init_state == malloc_init_initialized);
-}
-
-JEMALLOC_ALWAYS_INLINE_C void
-malloc_thread_init(void)
-{
-
- /*
- * TSD initialization can't be safely done as a side effect of
- * deallocation, because it is possible for a thread to do nothing but
- * deallocate its TLS data via free(), in which case writing to TLS
- * would cause write-after-free memory corruption. The quarantine
- * facility *only* gets used as a side effect of deallocation, so make
- * a best effort attempt at initializing its TSD by hooking all
- * allocation events.
- */
- if (config_fill && unlikely(opt_quarantine))
- quarantine_alloc_hook();
-}
-
-JEMALLOC_ALWAYS_INLINE_C bool
-malloc_init_a0(void)
-{
-
- if (unlikely(malloc_init_state == malloc_init_uninitialized))
- return (malloc_init_hard_a0());
- return (false);
-}
-
-JEMALLOC_ALWAYS_INLINE_C bool
-malloc_init(void)
-{
-
- if (unlikely(!malloc_initialized()) && malloc_init_hard())
- return (true);
- malloc_thread_init();
-
- return (false);
-}
-
-/*
- * The a0*() functions are used instead of i{d,}alloc() in situations that
- * cannot tolerate TLS variable access.
- */
-
-static void *
-a0ialloc(size_t size, bool zero, bool is_metadata)
-{
-
- if (unlikely(malloc_init_a0()))
- return (NULL);
-
- return (iallocztm(TSDN_NULL, size, size2index(size), zero, NULL,
- is_metadata, arena_get(TSDN_NULL, 0, true), true));
-}
-
-static void
-a0idalloc(void *ptr, bool is_metadata)
-{
-
- idalloctm(TSDN_NULL, ptr, false, is_metadata, true);
-}
-
-arena_t *
-a0get(void)
-{
-
- return (a0);
-}
-
-void *
-a0malloc(size_t size)
-{
-
- return (a0ialloc(size, false, true));
-}
-
-void
-a0dalloc(void *ptr)
-{
-
- a0idalloc(ptr, true);
-}
-
-/*
- * FreeBSD's libc uses the bootstrap_*() functions in bootstrap-senstive
- * situations that cannot tolerate TLS variable access (TLS allocation and very
- * early internal data structure initialization).
- */
-
-void *
-bootstrap_malloc(size_t size)
-{
-
- if (unlikely(size == 0))
- size = 1;
-
- return (a0ialloc(size, false, false));
-}
-
-void *
-bootstrap_calloc(size_t num, size_t size)
-{
- size_t num_size;
-
- num_size = num * size;
- if (unlikely(num_size == 0)) {
- assert(num == 0 || size == 0);
- num_size = 1;
- }
-
- return (a0ialloc(num_size, true, false));
-}
-
-void
-bootstrap_free(void *ptr)
-{
-
- if (unlikely(ptr == NULL))
- return;
-
- a0idalloc(ptr, false);
-}
-
-static void
-arena_set(unsigned ind, arena_t *arena)
-{
-
- atomic_write_p((void **)&arenas[ind], arena);
-}
-
-static void
-narenas_total_set(unsigned narenas)
-{
-
- atomic_write_u(&narenas_total, narenas);
-}
-
-static void
-narenas_total_inc(void)
-{
-
- atomic_add_u(&narenas_total, 1);
-}
-
-unsigned
-narenas_total_get(void)
-{
-
- return (atomic_read_u(&narenas_total));
-}
-
-/* Create a new arena and insert it into the arenas array at index ind. */
-static arena_t *
-arena_init_locked(tsdn_t *tsdn, unsigned ind)
-{
- arena_t *arena;
-
- assert(ind <= narenas_total_get());
- if (ind > MALLOCX_ARENA_MAX)
- return (NULL);
- if (ind == narenas_total_get())
- narenas_total_inc();
-
- /*
- * Another thread may have already initialized arenas[ind] if it's an
- * auto arena.
- */
- arena = arena_get(tsdn, ind, false);
- if (arena != NULL) {
- assert(ind < narenas_auto);
- return (arena);
- }
-
- /* Actually initialize the arena. */
- arena = arena_new(tsdn, ind);
- arena_set(ind, arena);
- return (arena);
-}
-
-arena_t *
-arena_init(tsdn_t *tsdn, unsigned ind)
-{
- arena_t *arena;
-
- malloc_mutex_lock(tsdn, &arenas_lock);
- arena = arena_init_locked(tsdn, ind);
- malloc_mutex_unlock(tsdn, &arenas_lock);
- return (arena);
-}
-
-static void
-arena_bind(tsd_t *tsd, unsigned ind, bool internal)
-{
- arena_t *arena;
-
- if (!tsd_nominal(tsd))
- return;
-
- arena = arena_get(tsd_tsdn(tsd), ind, false);
- arena_nthreads_inc(arena, internal);
-
- if (internal)
- tsd_iarena_set(tsd, arena);
- else
- tsd_arena_set(tsd, arena);
-}
-
-void
-arena_migrate(tsd_t *tsd, unsigned oldind, unsigned newind)
-{
- arena_t *oldarena, *newarena;
-
- oldarena = arena_get(tsd_tsdn(tsd), oldind, false);
- newarena = arena_get(tsd_tsdn(tsd), newind, false);
- arena_nthreads_dec(oldarena, false);
- arena_nthreads_inc(newarena, false);
- tsd_arena_set(tsd, newarena);
-}
-
-static void
-arena_unbind(tsd_t *tsd, unsigned ind, bool internal)
-{
- arena_t *arena;
-
- arena = arena_get(tsd_tsdn(tsd), ind, false);
- arena_nthreads_dec(arena, internal);
- if (internal)
- tsd_iarena_set(tsd, NULL);
- else
- tsd_arena_set(tsd, NULL);
-}
-
-arena_tdata_t *
-arena_tdata_get_hard(tsd_t *tsd, unsigned ind)
-{
- arena_tdata_t *tdata, *arenas_tdata_old;
- arena_tdata_t *arenas_tdata = tsd_arenas_tdata_get(tsd);
- unsigned narenas_tdata_old, i;
- unsigned narenas_tdata = tsd_narenas_tdata_get(tsd);
- unsigned narenas_actual = narenas_total_get();
-
- /*
- * Dissociate old tdata array (and set up for deallocation upon return)
- * if it's too small.
- */
- if (arenas_tdata != NULL && narenas_tdata < narenas_actual) {
- arenas_tdata_old = arenas_tdata;
- narenas_tdata_old = narenas_tdata;
- arenas_tdata = NULL;
- narenas_tdata = 0;
- tsd_arenas_tdata_set(tsd, arenas_tdata);
- tsd_narenas_tdata_set(tsd, narenas_tdata);
- } else {
- arenas_tdata_old = NULL;
- narenas_tdata_old = 0;
- }
-
- /* Allocate tdata array if it's missing. */
- if (arenas_tdata == NULL) {
- bool *arenas_tdata_bypassp = tsd_arenas_tdata_bypassp_get(tsd);
- narenas_tdata = (ind < narenas_actual) ? narenas_actual : ind+1;
-
- if (tsd_nominal(tsd) && !*arenas_tdata_bypassp) {
- *arenas_tdata_bypassp = true;
- arenas_tdata = (arena_tdata_t *)a0malloc(
- sizeof(arena_tdata_t) * narenas_tdata);
- *arenas_tdata_bypassp = false;
- }
- if (arenas_tdata == NULL) {
- tdata = NULL;
- goto label_return;
- }
- assert(tsd_nominal(tsd) && !*arenas_tdata_bypassp);
- tsd_arenas_tdata_set(tsd, arenas_tdata);
- tsd_narenas_tdata_set(tsd, narenas_tdata);
- }
-
- /*
- * Copy to tdata array. It's possible that the actual number of arenas
- * has increased since narenas_total_get() was called above, but that
- * causes no correctness issues unless two threads concurrently execute
- * the arenas.extend mallctl, which we trust mallctl synchronization to
- * prevent.
- */
-
- /* Copy/initialize tickers. */
- for (i = 0; i < narenas_actual; i++) {
- if (i < narenas_tdata_old) {
- ticker_copy(&arenas_tdata[i].decay_ticker,
- &arenas_tdata_old[i].decay_ticker);
- } else {
- ticker_init(&arenas_tdata[i].decay_ticker,
- DECAY_NTICKS_PER_UPDATE);
- }
- }
- if (narenas_tdata > narenas_actual) {
- memset(&arenas_tdata[narenas_actual], 0, sizeof(arena_tdata_t)
- * (narenas_tdata - narenas_actual));
- }
-
- /* Read the refreshed tdata array. */
- tdata = &arenas_tdata[ind];
-label_return:
- if (arenas_tdata_old != NULL)
- a0dalloc(arenas_tdata_old);
- return (tdata);
-}
-
-/* Slow path, called only by arena_choose(). */
-arena_t *
-arena_choose_hard(tsd_t *tsd, bool internal)
-{
- arena_t *ret JEMALLOC_CC_SILENCE_INIT(NULL);
-
- if (narenas_auto > 1) {
- unsigned i, j, choose[2], first_null;
-
- /*
- * Determine binding for both non-internal and internal
- * allocation.
- *
- * choose[0]: For application allocation.
- * choose[1]: For internal metadata allocation.
- */
-
- for (j = 0; j < 2; j++)
- choose[j] = 0;
-
- first_null = narenas_auto;
- malloc_mutex_lock(tsd_tsdn(tsd), &arenas_lock);
- assert(arena_get(tsd_tsdn(tsd), 0, false) != NULL);
- for (i = 1; i < narenas_auto; i++) {
- if (arena_get(tsd_tsdn(tsd), i, false) != NULL) {
- /*
- * Choose the first arena that has the lowest
- * number of threads assigned to it.
- */
- for (j = 0; j < 2; j++) {
- if (arena_nthreads_get(arena_get(
- tsd_tsdn(tsd), i, false), !!j) <
- arena_nthreads_get(arena_get(
- tsd_tsdn(tsd), choose[j], false),
- !!j))
- choose[j] = i;
- }
- } else if (first_null == narenas_auto) {
- /*
- * Record the index of the first uninitialized
- * arena, in case all extant arenas are in use.
- *
- * NB: It is possible for there to be
- * discontinuities in terms of initialized
- * versus uninitialized arenas, due to the
- * "thread.arena" mallctl.
- */
- first_null = i;
- }
- }
-
- for (j = 0; j < 2; j++) {
- if (arena_nthreads_get(arena_get(tsd_tsdn(tsd),
- choose[j], false), !!j) == 0 || first_null ==
- narenas_auto) {
- /*
- * Use an unloaded arena, or the least loaded
- * arena if all arenas are already initialized.
- */
- if (!!j == internal) {
- ret = arena_get(tsd_tsdn(tsd),
- choose[j], false);
- }
- } else {
- arena_t *arena;
-
- /* Initialize a new arena. */
- choose[j] = first_null;
- arena = arena_init_locked(tsd_tsdn(tsd),
- choose[j]);
- if (arena == NULL) {
- malloc_mutex_unlock(tsd_tsdn(tsd),
- &arenas_lock);
- return (NULL);
- }
- if (!!j == internal)
- ret = arena;
- }
- arena_bind(tsd, choose[j], !!j);
- }
- malloc_mutex_unlock(tsd_tsdn(tsd), &arenas_lock);
- } else {
- ret = arena_get(tsd_tsdn(tsd), 0, false);
- arena_bind(tsd, 0, false);
- arena_bind(tsd, 0, true);
- }
-
- return (ret);
-}
-
-void
-thread_allocated_cleanup(tsd_t *tsd)
-{
-
- /* Do nothing. */
-}
-
-void
-thread_deallocated_cleanup(tsd_t *tsd)
-{
-
- /* Do nothing. */
-}
-
-void
-iarena_cleanup(tsd_t *tsd)
-{
- arena_t *iarena;
-
- iarena = tsd_iarena_get(tsd);
- if (iarena != NULL)
- arena_unbind(tsd, iarena->ind, true);
-}
-
-void
-arena_cleanup(tsd_t *tsd)
-{
- arena_t *arena;
-
- arena = tsd_arena_get(tsd);
- if (arena != NULL)
- arena_unbind(tsd, arena->ind, false);
-}
-
-void
-arenas_tdata_cleanup(tsd_t *tsd)
-{
- arena_tdata_t *arenas_tdata;
-
- /* Prevent tsd->arenas_tdata from being (re)created. */
- *tsd_arenas_tdata_bypassp_get(tsd) = true;
-
- arenas_tdata = tsd_arenas_tdata_get(tsd);
- if (arenas_tdata != NULL) {
- tsd_arenas_tdata_set(tsd, NULL);
- a0dalloc(arenas_tdata);
- }
-}
-
-void
-narenas_tdata_cleanup(tsd_t *tsd)
-{
-
- /* Do nothing. */
-}
-
-void
-arenas_tdata_bypass_cleanup(tsd_t *tsd)
-{
-
- /* Do nothing. */
-}
-
-static void
-stats_print_atexit(void)
-{
-
- if (config_tcache && config_stats) {
- tsdn_t *tsdn;
- unsigned narenas, i;
-
- tsdn = tsdn_fetch();
-
- /*
- * Merge stats from extant threads. This is racy, since
- * individual threads do not lock when recording tcache stats
- * events. As a consequence, the final stats may be slightly
- * out of date by the time they are reported, if other threads
- * continue to allocate.
- */
- for (i = 0, narenas = narenas_total_get(); i < narenas; i++) {
- arena_t *arena = arena_get(tsdn, i, false);
- if (arena != NULL) {
- tcache_t *tcache;
-
- /*
- * tcache_stats_merge() locks bins, so if any
- * code is introduced that acquires both arena
- * and bin locks in the opposite order,
- * deadlocks may result.
- */
- malloc_mutex_lock(tsdn, &arena->lock);
- ql_foreach(tcache, &arena->tcache_ql, link) {
- tcache_stats_merge(tsdn, tcache, arena);
- }
- malloc_mutex_unlock(tsdn, &arena->lock);
- }
- }
- }
- je_malloc_stats_print(NULL, NULL, NULL);
-}
-
-/*
- * End miscellaneous support functions.
- */
-/******************************************************************************/
-/*
- * Begin initialization functions.
- */
-
-#ifndef JEMALLOC_HAVE_SECURE_GETENV
-static char *
-secure_getenv(const char *name)
-{
-
-# ifdef JEMALLOC_HAVE_ISSETUGID
- if (issetugid() != 0)
- return (NULL);
-# endif
- return (getenv(name));
-}
-#endif
-
-static unsigned
-malloc_ncpus(void)
-{
- long result;
-
-#ifdef _WIN32
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- result = si.dwNumberOfProcessors;
-#elif defined(JEMALLOC_GLIBC_MALLOC_HOOK) && defined(CPU_COUNT)
- /*
- * glibc >= 2.6 has the CPU_COUNT macro.
- *
- * glibc's sysconf() uses isspace(). glibc allocates for the first time
- * *before* setting up the isspace tables. Therefore we need a
- * different method to get the number of CPUs.
- */
- {
- cpu_set_t set;
-
- pthread_getaffinity_np(pthread_self(), sizeof(set), &set);
- result = CPU_COUNT(&set);
- }
-#else
- result = sysconf(_SC_NPROCESSORS_ONLN);
-#endif
- return ((result == -1) ? 1 : (unsigned)result);
-}
-
-static bool
-malloc_conf_next(char const **opts_p, char const **k_p, size_t *klen_p,
- char const **v_p, size_t *vlen_p)
-{
- bool accept;
- const char *opts = *opts_p;
-
- *k_p = opts;
-
- for (accept = false; !accept;) {
- switch (*opts) {
- case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
- case 'G': case 'H': case 'I': case 'J': case 'K': case 'L':
- case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R':
- case 'S': case 'T': case 'U': case 'V': case 'W': case 'X':
- case 'Y': case 'Z':
- case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
- case 'g': case 'h': case 'i': case 'j': case 'k': case 'l':
- case 'm': case 'n': case 'o': case 'p': case 'q': case 'r':
- case 's': case 't': case 'u': case 'v': case 'w': case 'x':
- case 'y': case 'z':
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7': case '8': case '9':
- case '_':
- opts++;
- break;
- case ':':
- opts++;
- *klen_p = (uintptr_t)opts - 1 - (uintptr_t)*k_p;
- *v_p = opts;
- accept = true;
- break;
- case '\0':
- if (opts != *opts_p) {
- malloc_write("<jemalloc>: Conf string ends "
- "with key\n");
- }
- return (true);
- default:
- malloc_write("<jemalloc>: Malformed conf string\n");
- return (true);
- }
- }
-
- for (accept = false; !accept;) {
- switch (*opts) {
- case ',':
- opts++;
- /*
- * Look ahead one character here, because the next time
- * this function is called, it will assume that end of
- * input has been cleanly reached if no input remains,
- * but we have optimistically already consumed the
- * comma if one exists.
- */
- if (*opts == '\0') {
- malloc_write("<jemalloc>: Conf string ends "
- "with comma\n");
- }
- *vlen_p = (uintptr_t)opts - 1 - (uintptr_t)*v_p;
- accept = true;
- break;
- case '\0':
- *vlen_p = (uintptr_t)opts - (uintptr_t)*v_p;
- accept = true;
- break;
- default:
- opts++;
- break;
- }
- }
-
- *opts_p = opts;
- return (false);
-}
-
-static void
-malloc_conf_error(const char *msg, const char *k, size_t klen, const char *v,
- size_t vlen)
-{
-
- malloc_printf("<jemalloc>: %s: %.*s:%.*s\n", msg, (int)klen, k,
- (int)vlen, v);
-}
-
-static void
-malloc_slow_flag_init(void)
-{
- /*
- * Combine the runtime options into malloc_slow for fast path. Called
- * after processing all the options.
- */
- malloc_slow_flags |= (opt_junk_alloc ? flag_opt_junk_alloc : 0)
- | (opt_junk_free ? flag_opt_junk_free : 0)
- | (opt_quarantine ? flag_opt_quarantine : 0)
- | (opt_zero ? flag_opt_zero : 0)
- | (opt_utrace ? flag_opt_utrace : 0)
- | (opt_xmalloc ? flag_opt_xmalloc : 0);
-
- if (config_valgrind)
- malloc_slow_flags |= (in_valgrind ? flag_in_valgrind : 0);
-
- malloc_slow = (malloc_slow_flags != 0);
-}
-
-static void
-malloc_conf_init(void)
-{
- unsigned i;
- char buf[PATH_MAX + 1];
- const char *opts, *k, *v;
- size_t klen, vlen;
-
- /*
- * Automatically configure valgrind before processing options. The
- * valgrind option remains in jemalloc 3.x for compatibility reasons.
- */
- if (config_valgrind) {
- in_valgrind = (RUNNING_ON_VALGRIND != 0) ? true : false;
- if (config_fill && unlikely(in_valgrind)) {
- opt_junk = "false";
- opt_junk_alloc = false;
- opt_junk_free = false;
- assert(!opt_zero);
- opt_quarantine = JEMALLOC_VALGRIND_QUARANTINE_DEFAULT;
- opt_redzone = true;
- }
- if (config_tcache && unlikely(in_valgrind))
- opt_tcache = false;
- }
-
- for (i = 0; i < 4; i++) {
- /* Get runtime configuration. */
- switch (i) {
- case 0:
- opts = config_malloc_conf;
- break;
- case 1:
- if (je_malloc_conf != NULL) {
- /*
- * Use options that were compiled into the
- * program.
- */
- opts = je_malloc_conf;
- } else {
- /* No configuration specified. */
- buf[0] = '\0';
- opts = buf;
- }
- break;
- case 2: {
- ssize_t linklen = 0;
-#ifndef _WIN32
- int saved_errno = errno;
- const char *linkname =
-# ifdef JEMALLOC_PREFIX
- "/etc/"JEMALLOC_PREFIX"malloc.conf"
-# else
- "/etc/malloc.conf"
-# endif
- ;
-
- /*
- * Try to use the contents of the "/etc/malloc.conf"
- * symbolic link's name.
- */
- linklen = readlink(linkname, buf, sizeof(buf) - 1);
- if (linklen == -1) {
- /* No configuration specified. */
- linklen = 0;
- /* Restore errno. */
- set_errno(saved_errno);
- }
-#endif
- buf[linklen] = '\0';
- opts = buf;
- break;
- } case 3: {
- const char *envname =
-#ifdef JEMALLOC_PREFIX
- JEMALLOC_CPREFIX"MALLOC_CONF"
-#else
- "MALLOC_CONF"
-#endif
- ;
-
- if ((opts = secure_getenv(envname)) != NULL) {
- /*
- * Do nothing; opts is already initialized to
- * the value of the MALLOC_CONF environment
- * variable.
- */
- } else {
- /* No configuration specified. */
- buf[0] = '\0';
- opts = buf;
- }
- break;
- } default:
- not_reached();
- buf[0] = '\0';
- opts = buf;
- }
-
- while (*opts != '\0' && !malloc_conf_next(&opts, &k, &klen, &v,
- &vlen)) {
-#define CONF_MATCH(n) \
- (sizeof(n)-1 == klen && strncmp(n, k, klen) == 0)
-#define CONF_MATCH_VALUE(n) \
- (sizeof(n)-1 == vlen && strncmp(n, v, vlen) == 0)
-#define CONF_HANDLE_BOOL(o, n, cont) \
- if (CONF_MATCH(n)) { \
- if (CONF_MATCH_VALUE("true")) \
- o = true; \
- else if (CONF_MATCH_VALUE("false")) \
- o = false; \
- else { \
- malloc_conf_error( \
- "Invalid conf value", \
- k, klen, v, vlen); \
- } \
- if (cont) \
- continue; \
- }
-#define CONF_HANDLE_T_U(t, o, n, min, max, clip) \
- if (CONF_MATCH(n)) { \
- uintmax_t um; \
- char *end; \
- \
- set_errno(0); \
- um = malloc_strtoumax(v, &end, 0); \
- if (get_errno() != 0 || (uintptr_t)end -\
- (uintptr_t)v != vlen) { \
- malloc_conf_error( \
- "Invalid conf value", \
- k, klen, v, vlen); \
- } else if (clip) { \
- if ((min) != 0 && um < (min)) \
- o = (t)(min); \
- else if (um > (max)) \
- o = (t)(max); \
- else \
- o = (t)um; \
- } else { \
- if (((min) != 0 && um < (min)) \
- || um > (max)) { \
- malloc_conf_error( \
- "Out-of-range " \
- "conf value", \
- k, klen, v, vlen); \
- } else \
- o = (t)um; \
- } \
- continue; \
- }
-#define CONF_HANDLE_UNSIGNED(o, n, min, max, clip) \
- CONF_HANDLE_T_U(unsigned, o, n, min, max, clip)
-#define CONF_HANDLE_SIZE_T(o, n, min, max, clip) \
- CONF_HANDLE_T_U(size_t, o, n, min, max, clip)
-#define CONF_HANDLE_SSIZE_T(o, n, min, max) \
- if (CONF_MATCH(n)) { \
- long l; \
- char *end; \
- \
- set_errno(0); \
- l = strtol(v, &end, 0); \
- if (get_errno() != 0 || (uintptr_t)end -\
- (uintptr_t)v != vlen) { \
- malloc_conf_error( \
- "Invalid conf value", \
- k, klen, v, vlen); \
- } else if (l < (ssize_t)(min) || l > \
- (ssize_t)(max)) { \
- malloc_conf_error( \
- "Out-of-range conf value", \
- k, klen, v, vlen); \
- } else \
- o = l; \
- continue; \
- }
-#define CONF_HANDLE_CHAR_P(o, n, d) \
- if (CONF_MATCH(n)) { \
- size_t cpylen = (vlen <= \
- sizeof(o)-1) ? vlen : \
- sizeof(o)-1; \
- strncpy(o, v, cpylen); \
- o[cpylen] = '\0'; \
- continue; \
- }
-
- CONF_HANDLE_BOOL(opt_abort, "abort", true)
- /*
- * Chunks always require at least one header page,
- * as many as 2^(LG_SIZE_CLASS_GROUP+1) data pages, and
- * possibly an additional page in the presence of
- * redzones. In order to simplify options processing,
- * use a conservative bound that accommodates all these
- * constraints.
- */
- CONF_HANDLE_SIZE_T(opt_lg_chunk, "lg_chunk", LG_PAGE +
- LG_SIZE_CLASS_GROUP + (config_fill ? 2 : 1),
- (sizeof(size_t) << 3) - 1, true)
- if (strncmp("dss", k, klen) == 0) {
- int i;
- bool match = false;
- for (i = 0; i < dss_prec_limit; i++) {
- if (strncmp(dss_prec_names[i], v, vlen)
- == 0) {
- if (chunk_dss_prec_set(i)) {
- malloc_conf_error(
- "Error setting dss",
- k, klen, v, vlen);
- } else {
- opt_dss =
- dss_prec_names[i];
- match = true;
- break;
- }
- }
- }
- if (!match) {
- malloc_conf_error("Invalid conf value",
- k, klen, v, vlen);
- }
- continue;
- }
- CONF_HANDLE_UNSIGNED(opt_narenas, "narenas", 1,
- UINT_MAX, false)
- if (strncmp("purge", k, klen) == 0) {
- int i;
- bool match = false;
- for (i = 0; i < purge_mode_limit; i++) {
- if (strncmp(purge_mode_names[i], v,
- vlen) == 0) {
- opt_purge = (purge_mode_t)i;
- match = true;
- break;
- }
- }
- if (!match) {
- malloc_conf_error("Invalid conf value",
- k, klen, v, vlen);
- }
- continue;
- }
- CONF_HANDLE_SSIZE_T(opt_lg_dirty_mult, "lg_dirty_mult",
- -1, (sizeof(size_t) << 3) - 1)
- CONF_HANDLE_SSIZE_T(opt_decay_time, "decay_time", -1,
- NSTIME_SEC_MAX);
- CONF_HANDLE_BOOL(opt_stats_print, "stats_print", true)
- if (config_fill) {
- if (CONF_MATCH("junk")) {
- if (CONF_MATCH_VALUE("true")) {
- if (config_valgrind &&
- unlikely(in_valgrind)) {
- malloc_conf_error(
- "Deallocation-time "
- "junk filling cannot "
- "be enabled while "
- "running inside "
- "Valgrind", k, klen, v,
- vlen);
- } else {
- opt_junk = "true";
- opt_junk_alloc = true;
- opt_junk_free = true;
- }
- } else if (CONF_MATCH_VALUE("false")) {
- opt_junk = "false";
- opt_junk_alloc = opt_junk_free =
- false;
- } else if (CONF_MATCH_VALUE("alloc")) {
- opt_junk = "alloc";
- opt_junk_alloc = true;
- opt_junk_free = false;
- } else if (CONF_MATCH_VALUE("free")) {
- if (config_valgrind &&
- unlikely(in_valgrind)) {
- malloc_conf_error(
- "Deallocation-time "
- "junk filling cannot "
- "be enabled while "
- "running inside "
- "Valgrind", k, klen, v,
- vlen);
- } else {
- opt_junk = "free";
- opt_junk_alloc = false;
- opt_junk_free = true;
- }
- } else {
- malloc_conf_error(
- "Invalid conf value", k,
- klen, v, vlen);
- }
- continue;
- }
- CONF_HANDLE_SIZE_T(opt_quarantine, "quarantine",
- 0, SIZE_T_MAX, false)
- CONF_HANDLE_BOOL(opt_redzone, "redzone", true)
- CONF_HANDLE_BOOL(opt_zero, "zero", true)
- }
- if (config_utrace) {
- CONF_HANDLE_BOOL(opt_utrace, "utrace", true)
- }
- if (config_xmalloc) {
- CONF_HANDLE_BOOL(opt_xmalloc, "xmalloc", true)
- }
- if (config_tcache) {
- CONF_HANDLE_BOOL(opt_tcache, "tcache",
- !config_valgrind || !in_valgrind)
- if (CONF_MATCH("tcache")) {
- assert(config_valgrind && in_valgrind);
- if (opt_tcache) {
- opt_tcache = false;
- malloc_conf_error(
- "tcache cannot be enabled "
- "while running inside Valgrind",
- k, klen, v, vlen);
- }
- continue;
- }
- CONF_HANDLE_SSIZE_T(opt_lg_tcache_max,
- "lg_tcache_max", -1,
- (sizeof(size_t) << 3) - 1)
- }
- if (config_prof) {
- CONF_HANDLE_BOOL(opt_prof, "prof", true)
- CONF_HANDLE_CHAR_P(opt_prof_prefix,
- "prof_prefix", "jeprof")
- CONF_HANDLE_BOOL(opt_prof_active, "prof_active",
- true)
- CONF_HANDLE_BOOL(opt_prof_thread_active_init,
- "prof_thread_active_init", true)
- CONF_HANDLE_SIZE_T(opt_lg_prof_sample,
- "lg_prof_sample", 0,
- (sizeof(uint64_t) << 3) - 1, true)
- CONF_HANDLE_BOOL(opt_prof_accum, "prof_accum",
- true)
- CONF_HANDLE_SSIZE_T(opt_lg_prof_interval,
- "lg_prof_interval", -1,
- (sizeof(uint64_t) << 3) - 1)
- CONF_HANDLE_BOOL(opt_prof_gdump, "prof_gdump",
- true)
- CONF_HANDLE_BOOL(opt_prof_final, "prof_final",
- true)
- CONF_HANDLE_BOOL(opt_prof_leak, "prof_leak",
- true)
- }
- malloc_conf_error("Invalid conf pair", k, klen, v,
- vlen);
-#undef CONF_MATCH
-#undef CONF_HANDLE_BOOL
-#undef CONF_HANDLE_SIZE_T
-#undef CONF_HANDLE_SSIZE_T
-#undef CONF_HANDLE_CHAR_P
- }
- }
-}
-
-static bool
-malloc_init_hard_needed(void)
-{
-
- if (malloc_initialized() || (IS_INITIALIZER && malloc_init_state ==
- malloc_init_recursible)) {
- /*
- * Another thread initialized the allocator before this one
- * acquired init_lock, or this thread is the initializing
- * thread, and it is recursively allocating.
- */
- return (false);
- }
-#ifdef JEMALLOC_THREADED_INIT
- if (malloc_initializer != NO_INITIALIZER && !IS_INITIALIZER) {
- spin_t spinner;
-
- /* Busy-wait until the initializing thread completes. */
- spin_init(&spinner);
- do {
- malloc_mutex_unlock(TSDN_NULL, &init_lock);
- spin_adaptive(&spinner);
- malloc_mutex_lock(TSDN_NULL, &init_lock);
- } while (!malloc_initialized());
- return (false);
- }
-#endif
- return (true);
-}
-
-static bool
-malloc_init_hard_a0_locked()
-{
-
- malloc_initializer = INITIALIZER;
-
- if (config_prof)
- prof_boot0();
- malloc_conf_init();
- if (opt_stats_print) {
- /* Print statistics at exit. */
- if (atexit(stats_print_atexit) != 0) {
- malloc_write("<jemalloc>: Error in atexit()\n");
- if (opt_abort)
- abort();
- }
- }
- pages_boot();
- if (base_boot())
- return (true);
- if (chunk_boot())
- return (true);
- if (ctl_boot())
- return (true);
- if (config_prof)
- prof_boot1();
- arena_boot();
- if (config_tcache && tcache_boot(TSDN_NULL))
- return (true);
- if (malloc_mutex_init(&arenas_lock, "arenas", WITNESS_RANK_ARENAS))
- return (true);
- /*
- * Create enough scaffolding to allow recursive allocation in
- * malloc_ncpus().
- */
- narenas_auto = 1;
- narenas_total_set(narenas_auto);
- arenas = &a0;
- memset(arenas, 0, sizeof(arena_t *) * narenas_auto);
- /*
- * Initialize one arena here. The rest are lazily created in
- * arena_choose_hard().
- */
- if (arena_init(TSDN_NULL, 0) == NULL)
- return (true);
-
- malloc_init_state = malloc_init_a0_initialized;
-
- return (false);
-}
-
-static bool
-malloc_init_hard_a0(void)
-{
- bool ret;
-
- malloc_mutex_lock(TSDN_NULL, &init_lock);
- ret = malloc_init_hard_a0_locked();
- malloc_mutex_unlock(TSDN_NULL, &init_lock);
- return (ret);
-}
-
-/* Initialize data structures which may trigger recursive allocation. */
-static bool
-malloc_init_hard_recursible(void)
-{
-
- malloc_init_state = malloc_init_recursible;
-
- ncpus = malloc_ncpus();
-
-#if (!defined(JEMALLOC_MUTEX_INIT_CB) && !defined(JEMALLOC_ZONE) \
- && !defined(_WIN32) && !defined(__native_client__))
- /* LinuxThreads' pthread_atfork() allocates. */
- if (pthread_atfork(jemalloc_prefork, jemalloc_postfork_parent,
- jemalloc_postfork_child) != 0) {
- malloc_write("<jemalloc>: Error in pthread_atfork()\n");
- if (opt_abort)
- abort();
- return (true);
- }
-#endif
-
- return (false);
-}
-
-static bool
-malloc_init_hard_finish(tsdn_t *tsdn)
-{
-
- if (malloc_mutex_boot())
- return (true);
-
- if (opt_narenas == 0) {
- /*
- * For SMP systems, create more than one arena per CPU by
- * default.
- */
- if (ncpus > 1)
- opt_narenas = ncpus << 2;
- else
- opt_narenas = 1;
- }
- narenas_auto = opt_narenas;
- /*
- * Limit the number of arenas to the indexing range of MALLOCX_ARENA().
- */
- if (narenas_auto > MALLOCX_ARENA_MAX) {
- narenas_auto = MALLOCX_ARENA_MAX;
- malloc_printf("<jemalloc>: Reducing narenas to limit (%d)\n",
- narenas_auto);
- }
- narenas_total_set(narenas_auto);
-
- /* Allocate and initialize arenas. */
- arenas = (arena_t **)base_alloc(tsdn, sizeof(arena_t *) *
- (MALLOCX_ARENA_MAX+1));
- if (arenas == NULL)
- return (true);
- /* Copy the pointer to the one arena that was already initialized. */
- arena_set(0, a0);
-
- malloc_init_state = malloc_init_initialized;
- malloc_slow_flag_init();
-
- return (false);
-}
-
-static bool
-malloc_init_hard(void)
-{
- tsd_t *tsd;
-
-#if defined(_WIN32) && _WIN32_WINNT < 0x0600
- _init_init_lock();
-#endif
- malloc_mutex_lock(TSDN_NULL, &init_lock);
- if (!malloc_init_hard_needed()) {
- malloc_mutex_unlock(TSDN_NULL, &init_lock);
- return (false);
- }
-
- if (malloc_init_state != malloc_init_a0_initialized &&
- malloc_init_hard_a0_locked()) {
- malloc_mutex_unlock(TSDN_NULL, &init_lock);
- return (true);
- }
-
- malloc_mutex_unlock(TSDN_NULL, &init_lock);
- /* Recursive allocation relies on functional tsd. */
- tsd = malloc_tsd_boot0();
- if (tsd == NULL)
- return (true);
- if (malloc_init_hard_recursible())
- return (true);
- malloc_mutex_lock(tsd_tsdn(tsd), &init_lock);
-
- if (config_prof && prof_boot2(tsd)) {
- malloc_mutex_unlock(tsd_tsdn(tsd), &init_lock);
- return (true);
- }
-
- if (malloc_init_hard_finish(tsd_tsdn(tsd))) {
- malloc_mutex_unlock(tsd_tsdn(tsd), &init_lock);
- return (true);
- }
-
- malloc_mutex_unlock(tsd_tsdn(tsd), &init_lock);
- malloc_tsd_boot1();
- return (false);
-}
-
-/*
- * End initialization functions.
- */
-/******************************************************************************/
-/*
- * Begin malloc(3)-compatible functions.
- */
-
-static void *
-ialloc_prof_sample(tsd_t *tsd, size_t usize, szind_t ind, bool zero,
- prof_tctx_t *tctx, bool slow_path)
-{
- void *p;
-
- if (tctx == NULL)
- return (NULL);
- if (usize <= SMALL_MAXCLASS) {
- szind_t ind_large = size2index(LARGE_MINCLASS);
- p = ialloc(tsd, LARGE_MINCLASS, ind_large, zero, slow_path);
- if (p == NULL)
- return (NULL);
- arena_prof_promoted(tsd_tsdn(tsd), p, usize);
- } else
- p = ialloc(tsd, usize, ind, zero, slow_path);
-
- return (p);
-}
-
-JEMALLOC_ALWAYS_INLINE_C void *
-ialloc_prof(tsd_t *tsd, size_t usize, szind_t ind, bool zero, bool slow_path)
-{
- void *p;
- prof_tctx_t *tctx;
-
- tctx = prof_alloc_prep(tsd, usize, prof_active_get_unlocked(), true);
- if (unlikely((uintptr_t)tctx != (uintptr_t)1U))
- p = ialloc_prof_sample(tsd, usize, ind, zero, tctx, slow_path);
- else
- p = ialloc(tsd, usize, ind, zero, slow_path);
- if (unlikely(p == NULL)) {
- prof_alloc_rollback(tsd, tctx, true);
- return (NULL);
- }
- prof_malloc(tsd_tsdn(tsd), p, usize, tctx);
-
- return (p);
-}
-
-/*
- * ialloc_body() is inlined so that fast and slow paths are generated separately
- * with statically known slow_path.
- *
- * This function guarantees that *tsdn is non-NULL on success.
- */
-JEMALLOC_ALWAYS_INLINE_C void *
-ialloc_body(size_t size, bool zero, tsdn_t **tsdn, size_t *usize,
- bool slow_path)
-{
- tsd_t *tsd;
- szind_t ind;
-
- if (slow_path && unlikely(malloc_init())) {
- *tsdn = NULL;
- return (NULL);
- }
-
- tsd = tsd_fetch();
- *tsdn = tsd_tsdn(tsd);
- witness_assert_lockless(tsd_tsdn(tsd));
-
- ind = size2index(size);
- if (unlikely(ind >= NSIZES))
- return (NULL);
-
- if (config_stats || (config_prof && opt_prof) || (slow_path &&
- config_valgrind && unlikely(in_valgrind))) {
- *usize = index2size(ind);
- assert(*usize > 0 && *usize <= HUGE_MAXCLASS);
- }
-
- if (config_prof && opt_prof)
- return (ialloc_prof(tsd, *usize, ind, zero, slow_path));
-
- return (ialloc(tsd, size, ind, zero, slow_path));
-}
-
-JEMALLOC_ALWAYS_INLINE_C void
-ialloc_post_check(void *ret, tsdn_t *tsdn, size_t usize, const char *func,
- bool update_errno, bool slow_path)
-{
-
- assert(!tsdn_null(tsdn) || ret == NULL);
-
- if (unlikely(ret == NULL)) {
- if (slow_path && config_xmalloc && unlikely(opt_xmalloc)) {
- malloc_printf("<jemalloc>: Error in %s(): out of "
- "memory\n", func);
- abort();
- }
- if (update_errno)
- set_errno(ENOMEM);
- }
- if (config_stats && likely(ret != NULL)) {
- assert(usize == isalloc(tsdn, ret, config_prof));
- *tsd_thread_allocatedp_get(tsdn_tsd(tsdn)) += usize;
- }
- witness_assert_lockless(tsdn);
-}
-
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
-void JEMALLOC_NOTHROW *
-JEMALLOC_ATTR(malloc) JEMALLOC_ALLOC_SIZE(1)
-je_malloc(size_t size)
-{
- void *ret;
- tsdn_t *tsdn;
- size_t usize JEMALLOC_CC_SILENCE_INIT(0);
-
- if (size == 0)
- size = 1;
-
- if (likely(!malloc_slow)) {
- ret = ialloc_body(size, false, &tsdn, &usize, false);
- ialloc_post_check(ret, tsdn, usize, "malloc", true, false);
- } else {
- ret = ialloc_body(size, false, &tsdn, &usize, true);
- ialloc_post_check(ret, tsdn, usize, "malloc", true, true);
- UTRACE(0, size, ret);
- JEMALLOC_VALGRIND_MALLOC(ret != NULL, tsdn, ret, usize, false);
- }
-
- return (ret);
-}
-
-static void *
-imemalign_prof_sample(tsd_t *tsd, size_t alignment, size_t usize,
- prof_tctx_t *tctx)
-{
- void *p;
-
- if (tctx == NULL)
- return (NULL);
- if (usize <= SMALL_MAXCLASS) {
- assert(sa2u(LARGE_MINCLASS, alignment) == LARGE_MINCLASS);
- p = ipalloc(tsd, LARGE_MINCLASS, alignment, false);
- if (p == NULL)
- return (NULL);
- arena_prof_promoted(tsd_tsdn(tsd), p, usize);
- } else
- p = ipalloc(tsd, usize, alignment, false);
-
- return (p);
-}
-
-JEMALLOC_ALWAYS_INLINE_C void *
-imemalign_prof(tsd_t *tsd, size_t alignment, size_t usize)
-{
- void *p;
- prof_tctx_t *tctx;
-
- tctx = prof_alloc_prep(tsd, usize, prof_active_get_unlocked(), true);
- if (unlikely((uintptr_t)tctx != (uintptr_t)1U))
- p = imemalign_prof_sample(tsd, alignment, usize, tctx);
- else
- p = ipalloc(tsd, usize, alignment, false);
- if (unlikely(p == NULL)) {
- prof_alloc_rollback(tsd, tctx, true);
- return (NULL);
- }
- prof_malloc(tsd_tsdn(tsd), p, usize, tctx);
-
- return (p);
-}
-
-JEMALLOC_ATTR(nonnull(1))
-static int
-imemalign(void **memptr, size_t alignment, size_t size, size_t min_alignment)
-{
- int ret;
- tsd_t *tsd;
- size_t usize;
- void *result;
-
- assert(min_alignment != 0);
-
- if (unlikely(malloc_init())) {
- tsd = NULL;
- result = NULL;
- goto label_oom;
- }
- tsd = tsd_fetch();
- witness_assert_lockless(tsd_tsdn(tsd));
- if (size == 0)
- size = 1;
-
- /* Make sure that alignment is a large enough power of 2. */
- if (unlikely(((alignment - 1) & alignment) != 0
- || (alignment < min_alignment))) {
- if (config_xmalloc && unlikely(opt_xmalloc)) {
- malloc_write("<jemalloc>: Error allocating "
- "aligned memory: invalid alignment\n");
- abort();
- }
- result = NULL;
- ret = EINVAL;
- goto label_return;
- }
-
- usize = sa2u(size, alignment);
- if (unlikely(usize == 0 || usize > HUGE_MAXCLASS)) {
- result = NULL;
- goto label_oom;
- }
-
- if (config_prof && opt_prof)
- result = imemalign_prof(tsd, alignment, usize);
- else
- result = ipalloc(tsd, usize, alignment, false);
- if (unlikely(result == NULL))
- goto label_oom;
- assert(((uintptr_t)result & (alignment - 1)) == ZU(0));
-
- *memptr = result;
- ret = 0;
-label_return:
- if (config_stats && likely(result != NULL)) {
- assert(usize == isalloc(tsd_tsdn(tsd), result, config_prof));
- *tsd_thread_allocatedp_get(tsd) += usize;
- }
- UTRACE(0, size, result);
- JEMALLOC_VALGRIND_MALLOC(result != NULL, tsd_tsdn(tsd), result, usize,
- false);
- witness_assert_lockless(tsd_tsdn(tsd));
- return (ret);
-label_oom:
- assert(result == NULL);
- if (config_xmalloc && unlikely(opt_xmalloc)) {
- malloc_write("<jemalloc>: Error allocating aligned memory: "
- "out of memory\n");
- abort();
- }
- ret = ENOMEM;
- witness_assert_lockless(tsd_tsdn(tsd));
- goto label_return;
-}
-
-JEMALLOC_EXPORT int JEMALLOC_NOTHROW
-JEMALLOC_ATTR(nonnull(1))
-je_posix_memalign(void **memptr, size_t alignment, size_t size)
-{
- int ret;
-
- ret = imemalign(memptr, alignment, size, sizeof(void *));
-
- return (ret);
-}
-
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
-void JEMALLOC_NOTHROW *
-JEMALLOC_ATTR(malloc) JEMALLOC_ALLOC_SIZE(2)
-je_aligned_alloc(size_t alignment, size_t size)
-{
- void *ret;
- int err;
-
- if (unlikely((err = imemalign(&ret, alignment, size, 1)) != 0)) {
- ret = NULL;
- set_errno(err);
- }
-
- return (ret);
-}
-
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
-void JEMALLOC_NOTHROW *
-JEMALLOC_ATTR(malloc) JEMALLOC_ALLOC_SIZE2(1, 2)
-je_calloc(size_t num, size_t size)
-{
- void *ret;
- tsdn_t *tsdn;
- size_t num_size;
- size_t usize JEMALLOC_CC_SILENCE_INIT(0);
-
- num_size = num * size;
- if (unlikely(num_size == 0)) {
- if (num == 0 || size == 0)
- num_size = 1;
- else
- num_size = HUGE_MAXCLASS + 1; /* Trigger OOM. */
- /*
- * Try to avoid division here. We know that it isn't possible to
- * overflow during multiplication if neither operand uses any of the
- * most significant half of the bits in a size_t.
- */
- } else if (unlikely(((num | size) & (SIZE_T_MAX << (sizeof(size_t) <<
- 2))) && (num_size / size != num)))
- num_size = HUGE_MAXCLASS + 1; /* size_t overflow. */
-
- if (likely(!malloc_slow)) {
- ret = ialloc_body(num_size, true, &tsdn, &usize, false);
- ialloc_post_check(ret, tsdn, usize, "calloc", true, false);
- } else {
- ret = ialloc_body(num_size, true, &tsdn, &usize, true);
- ialloc_post_check(ret, tsdn, usize, "calloc", true, true);
- UTRACE(0, num_size, ret);
- JEMALLOC_VALGRIND_MALLOC(ret != NULL, tsdn, ret, usize, true);
- }
-
- return (ret);
-}
-
-static void *
-irealloc_prof_sample(tsd_t *tsd, void *old_ptr, size_t old_usize, size_t usize,
- prof_tctx_t *tctx)
-{
- void *p;
-
- if (tctx == NULL)
- return (NULL);
- if (usize <= SMALL_MAXCLASS) {
- p = iralloc(tsd, old_ptr, old_usize, LARGE_MINCLASS, 0, false);
- if (p == NULL)
- return (NULL);
- arena_prof_promoted(tsd_tsdn(tsd), p, usize);
- } else
- p = iralloc(tsd, old_ptr, old_usize, usize, 0, false);
-
- return (p);
-}
-
-JEMALLOC_ALWAYS_INLINE_C void *
-irealloc_prof(tsd_t *tsd, void *old_ptr, size_t old_usize, size_t usize)
-{
- void *p;
- bool prof_active;
- prof_tctx_t *old_tctx, *tctx;
-
- prof_active = prof_active_get_unlocked();
- old_tctx = prof_tctx_get(tsd_tsdn(tsd), old_ptr);
- tctx = prof_alloc_prep(tsd, usize, prof_active, true);
- if (unlikely((uintptr_t)tctx != (uintptr_t)1U))
- p = irealloc_prof_sample(tsd, old_ptr, old_usize, usize, tctx);
- else
- p = iralloc(tsd, old_ptr, old_usize, usize, 0, false);
- if (unlikely(p == NULL)) {
- prof_alloc_rollback(tsd, tctx, true);
- return (NULL);
- }
- prof_realloc(tsd, p, usize, tctx, prof_active, true, old_ptr, old_usize,
- old_tctx);
-
- return (p);
-}
-
-JEMALLOC_INLINE_C void
-ifree(tsd_t *tsd, void *ptr, tcache_t *tcache, bool slow_path)
-{
- size_t usize;
- UNUSED size_t rzsize JEMALLOC_CC_SILENCE_INIT(0);
-
- witness_assert_lockless(tsd_tsdn(tsd));
-
- assert(ptr != NULL);
- assert(malloc_initialized() || IS_INITIALIZER);
-
- if (config_prof && opt_prof) {
- usize = isalloc(tsd_tsdn(tsd), ptr, config_prof);
- prof_free(tsd, ptr, usize);
- } else if (config_stats || config_valgrind)
- usize = isalloc(tsd_tsdn(tsd), ptr, config_prof);
- if (config_stats)
- *tsd_thread_deallocatedp_get(tsd) += usize;
-
- if (likely(!slow_path))
- iqalloc(tsd, ptr, tcache, false);
- else {
- if (config_valgrind && unlikely(in_valgrind))
- rzsize = p2rz(tsd_tsdn(tsd), ptr);
- iqalloc(tsd, ptr, tcache, true);
- JEMALLOC_VALGRIND_FREE(ptr, rzsize);
- }
-}
-
-JEMALLOC_INLINE_C void
-isfree(tsd_t *tsd, void *ptr, size_t usize, tcache_t *tcache, bool slow_path)
-{
- UNUSED size_t rzsize JEMALLOC_CC_SILENCE_INIT(0);
-
- witness_assert_lockless(tsd_tsdn(tsd));
-
- assert(ptr != NULL);
- assert(malloc_initialized() || IS_INITIALIZER);
-
- if (config_prof && opt_prof)
- prof_free(tsd, ptr, usize);
- if (config_stats)
- *tsd_thread_deallocatedp_get(tsd) += usize;
- if (config_valgrind && unlikely(in_valgrind))
- rzsize = p2rz(tsd_tsdn(tsd), ptr);
- isqalloc(tsd, ptr, usize, tcache, slow_path);
- JEMALLOC_VALGRIND_FREE(ptr, rzsize);
-}
-
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
-void JEMALLOC_NOTHROW *
-JEMALLOC_ALLOC_SIZE(2)
-je_realloc(void *ptr, size_t size)
-{
- void *ret;
- tsdn_t *tsdn JEMALLOC_CC_SILENCE_INIT(NULL);
- size_t usize JEMALLOC_CC_SILENCE_INIT(0);
- size_t old_usize = 0;
- UNUSED size_t old_rzsize JEMALLOC_CC_SILENCE_INIT(0);
-
- if (unlikely(size == 0)) {
- if (ptr != NULL) {
- tsd_t *tsd;
-
- /* realloc(ptr, 0) is equivalent to free(ptr). */
- UTRACE(ptr, 0, 0);
- tsd = tsd_fetch();
- ifree(tsd, ptr, tcache_get(tsd, false), true);
- return (NULL);
- }
- size = 1;
- }
-
- if (likely(ptr != NULL)) {
- tsd_t *tsd;
-
- assert(malloc_initialized() || IS_INITIALIZER);
- malloc_thread_init();
- tsd = tsd_fetch();
-
- witness_assert_lockless(tsd_tsdn(tsd));
-
- old_usize = isalloc(tsd_tsdn(tsd), ptr, config_prof);
- if (config_valgrind && unlikely(in_valgrind)) {
- old_rzsize = config_prof ? p2rz(tsd_tsdn(tsd), ptr) :
- u2rz(old_usize);
- }
-
- if (config_prof && opt_prof) {
- usize = s2u(size);
- ret = unlikely(usize == 0 || usize > HUGE_MAXCLASS) ?
- NULL : irealloc_prof(tsd, ptr, old_usize, usize);
- } else {
- if (config_stats || (config_valgrind &&
- unlikely(in_valgrind)))
- usize = s2u(size);
- ret = iralloc(tsd, ptr, old_usize, size, 0, false);
- }
- tsdn = tsd_tsdn(tsd);
- } else {
- /* realloc(NULL, size) is equivalent to malloc(size). */
- if (likely(!malloc_slow))
- ret = ialloc_body(size, false, &tsdn, &usize, false);
- else
- ret = ialloc_body(size, false, &tsdn, &usize, true);
- assert(!tsdn_null(tsdn) || ret == NULL);
- }
-
- if (unlikely(ret == NULL)) {
- if (config_xmalloc && unlikely(opt_xmalloc)) {
- malloc_write("<jemalloc>: Error in realloc(): "
- "out of memory\n");
- abort();
- }
- set_errno(ENOMEM);
- }
- if (config_stats && likely(ret != NULL)) {
- tsd_t *tsd;
-
- assert(usize == isalloc(tsdn, ret, config_prof));
- tsd = tsdn_tsd(tsdn);
- *tsd_thread_allocatedp_get(tsd) += usize;
- *tsd_thread_deallocatedp_get(tsd) += old_usize;
- }
- UTRACE(ptr, size, ret);
- JEMALLOC_VALGRIND_REALLOC(true, tsdn, ret, usize, true, ptr, old_usize,
- old_rzsize, true, false);
- witness_assert_lockless(tsdn);
- return (ret);
-}
-
-JEMALLOC_EXPORT void JEMALLOC_NOTHROW
-je_free(void *ptr)
-{
-
- UTRACE(ptr, 0, 0);
- if (likely(ptr != NULL)) {
- tsd_t *tsd = tsd_fetch();
- witness_assert_lockless(tsd_tsdn(tsd));
- if (likely(!malloc_slow))
- ifree(tsd, ptr, tcache_get(tsd, false), false);
- else
- ifree(tsd, ptr, tcache_get(tsd, false), true);
- witness_assert_lockless(tsd_tsdn(tsd));
- }
-}
-
-/*
- * End malloc(3)-compatible functions.
- */
-/******************************************************************************/
-/*
- * Begin non-standard override functions.
- */
-
-#ifdef JEMALLOC_OVERRIDE_MEMALIGN
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
-void JEMALLOC_NOTHROW *
-JEMALLOC_ATTR(malloc)
-je_memalign(size_t alignment, size_t size)
-{
- void *ret JEMALLOC_CC_SILENCE_INIT(NULL);
- if (unlikely(imemalign(&ret, alignment, size, 1) != 0))
- ret = NULL;
- return (ret);
-}
-#endif
-
-#ifdef JEMALLOC_OVERRIDE_VALLOC
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
-void JEMALLOC_NOTHROW *
-JEMALLOC_ATTR(malloc)
-je_valloc(size_t size)
-{
- void *ret JEMALLOC_CC_SILENCE_INIT(NULL);
- if (unlikely(imemalign(&ret, PAGE, size, 1) != 0))
- ret = NULL;
- return (ret);
-}
-#endif
-
-/*
- * is_malloc(je_malloc) is some macro magic to detect if jemalloc_defs.h has
- * #define je_malloc malloc
- */
-#define malloc_is_malloc 1
-#define is_malloc_(a) malloc_is_ ## a
-#define is_malloc(a) is_malloc_(a)
-
-#if ((is_malloc(je_malloc) == 1) && defined(JEMALLOC_GLIBC_MALLOC_HOOK))
-/*
- * glibc provides the RTLD_DEEPBIND flag for dlopen which can make it possible
- * to inconsistently reference libc's malloc(3)-compatible functions
- * (https://bugzilla.mozilla.org/show_bug.cgi?id=493541).
- *
- * These definitions interpose hooks in glibc. The functions are actually
- * passed an extra argument for the caller return address, which will be
- * ignored.
- */
-JEMALLOC_EXPORT void (*__free_hook)(void *ptr) = je_free;
-JEMALLOC_EXPORT void *(*__malloc_hook)(size_t size) = je_malloc;
-JEMALLOC_EXPORT void *(*__realloc_hook)(void *ptr, size_t size) = je_realloc;
-# ifdef JEMALLOC_GLIBC_MEMALIGN_HOOK
-JEMALLOC_EXPORT void *(*__memalign_hook)(size_t alignment, size_t size) =
- je_memalign;
-# endif
-
-#ifdef CPU_COUNT
-/*
- * To enable static linking with glibc, the libc specific malloc interface must
- * be implemented also, so none of glibc's malloc.o functions are added to the
- * link.
- */
-#define ALIAS(je_fn) __attribute__((alias (#je_fn), used))
-/* To force macro expansion of je_ prefix before stringification. */
-#define PREALIAS(je_fn) ALIAS(je_fn)
-void *__libc_malloc(size_t size) PREALIAS(je_malloc);
-void __libc_free(void* ptr) PREALIAS(je_free);
-void *__libc_realloc(void* ptr, size_t size) PREALIAS(je_realloc);
-void *__libc_calloc(size_t n, size_t size) PREALIAS(je_calloc);
-void *__libc_memalign(size_t align, size_t s) PREALIAS(je_memalign);
-void *__libc_valloc(size_t size) PREALIAS(je_valloc);
-int __posix_memalign(void** r, size_t a, size_t s)
- PREALIAS(je_posix_memalign);
-#undef PREALIAS
-#undef ALIAS
-
-#endif
-
-#endif
-
-/*
- * End non-standard override functions.
- */
-/******************************************************************************/
-/*
- * Begin non-standard functions.
- */
-
-JEMALLOC_ALWAYS_INLINE_C bool
-imallocx_flags_decode(tsd_t *tsd, size_t size, int flags, size_t *usize,
- size_t *alignment, bool *zero, tcache_t **tcache, arena_t **arena)
-{
-
- if ((flags & MALLOCX_LG_ALIGN_MASK) == 0) {
- *alignment = 0;
- *usize = s2u(size);
- } else {
- *alignment = MALLOCX_ALIGN_GET_SPECIFIED(flags);
- *usize = sa2u(size, *alignment);
- }
- if (unlikely(*usize == 0 || *usize > HUGE_MAXCLASS))
- return (true);
- *zero = MALLOCX_ZERO_GET(flags);
- if ((flags & MALLOCX_TCACHE_MASK) != 0) {
- if ((flags & MALLOCX_TCACHE_MASK) == MALLOCX_TCACHE_NONE)
- *tcache = NULL;
- else
- *tcache = tcaches_get(tsd, MALLOCX_TCACHE_GET(flags));
- } else
- *tcache = tcache_get(tsd, true);
- if ((flags & MALLOCX_ARENA_MASK) != 0) {
- unsigned arena_ind = MALLOCX_ARENA_GET(flags);
- *arena = arena_get(tsd_tsdn(tsd), arena_ind, true);
- if (unlikely(*arena == NULL))
- return (true);
- } else
- *arena = NULL;
- return (false);
-}
-
-JEMALLOC_ALWAYS_INLINE_C void *
-imallocx_flags(tsdn_t *tsdn, size_t usize, size_t alignment, bool zero,
- tcache_t *tcache, arena_t *arena, bool slow_path)
-{
- szind_t ind;
-
- if (unlikely(alignment != 0))
- return (ipalloct(tsdn, usize, alignment, zero, tcache, arena));
- ind = size2index(usize);
- assert(ind < NSIZES);
- return (iallocztm(tsdn, usize, ind, zero, tcache, false, arena,
- slow_path));
-}
-
-static void *
-imallocx_prof_sample(tsdn_t *tsdn, size_t usize, size_t alignment, bool zero,
- tcache_t *tcache, arena_t *arena, bool slow_path)
-{
- void *p;
-
- if (usize <= SMALL_MAXCLASS) {
- assert(((alignment == 0) ? s2u(LARGE_MINCLASS) :
- sa2u(LARGE_MINCLASS, alignment)) == LARGE_MINCLASS);
- p = imallocx_flags(tsdn, LARGE_MINCLASS, alignment, zero,
- tcache, arena, slow_path);
- if (p == NULL)
- return (NULL);
- arena_prof_promoted(tsdn, p, usize);
- } else {
- p = imallocx_flags(tsdn, usize, alignment, zero, tcache, arena,
- slow_path);
- }
-
- return (p);
-}
-
-JEMALLOC_ALWAYS_INLINE_C void *
-imallocx_prof(tsd_t *tsd, size_t size, int flags, size_t *usize, bool slow_path)
-{
- void *p;
- size_t alignment;
- bool zero;
- tcache_t *tcache;
- arena_t *arena;
- prof_tctx_t *tctx;
-
- if (unlikely(imallocx_flags_decode(tsd, size, flags, usize, &alignment,
- &zero, &tcache, &arena)))
- return (NULL);
- tctx = prof_alloc_prep(tsd, *usize, prof_active_get_unlocked(), true);
- if (likely((uintptr_t)tctx == (uintptr_t)1U)) {
- p = imallocx_flags(tsd_tsdn(tsd), *usize, alignment, zero,
- tcache, arena, slow_path);
- } else if ((uintptr_t)tctx > (uintptr_t)1U) {
- p = imallocx_prof_sample(tsd_tsdn(tsd), *usize, alignment, zero,
- tcache, arena, slow_path);
- } else
- p = NULL;
- if (unlikely(p == NULL)) {
- prof_alloc_rollback(tsd, tctx, true);
- return (NULL);
- }
- prof_malloc(tsd_tsdn(tsd), p, *usize, tctx);
-
- assert(alignment == 0 || ((uintptr_t)p & (alignment - 1)) == ZU(0));
- return (p);
-}
-
-JEMALLOC_ALWAYS_INLINE_C void *
-imallocx_no_prof(tsd_t *tsd, size_t size, int flags, size_t *usize,
- bool slow_path)
-{
- void *p;
- size_t alignment;
- bool zero;
- tcache_t *tcache;
- arena_t *arena;
-
- if (unlikely(imallocx_flags_decode(tsd, size, flags, usize, &alignment,
- &zero, &tcache, &arena)))
- return (NULL);
- p = imallocx_flags(tsd_tsdn(tsd), *usize, alignment, zero, tcache,
- arena, slow_path);
- assert(alignment == 0 || ((uintptr_t)p & (alignment - 1)) == ZU(0));
- return (p);
-}
-
-/* This function guarantees that *tsdn is non-NULL on success. */
-JEMALLOC_ALWAYS_INLINE_C void *
-imallocx_body(size_t size, int flags, tsdn_t **tsdn, size_t *usize,
- bool slow_path)
-{
- tsd_t *tsd;
-
- if (slow_path && unlikely(malloc_init())) {
- *tsdn = NULL;
- return (NULL);
- }
-
- tsd = tsd_fetch();
- *tsdn = tsd_tsdn(tsd);
- witness_assert_lockless(tsd_tsdn(tsd));
-
- if (likely(flags == 0)) {
- szind_t ind = size2index(size);
- if (unlikely(ind >= NSIZES))
- return (NULL);
- if (config_stats || (config_prof && opt_prof) || (slow_path &&
- config_valgrind && unlikely(in_valgrind))) {
- *usize = index2size(ind);
- assert(*usize > 0 && *usize <= HUGE_MAXCLASS);
- }
-
- if (config_prof && opt_prof) {
- return (ialloc_prof(tsd, *usize, ind, false,
- slow_path));
- }
-
- return (ialloc(tsd, size, ind, false, slow_path));
- }
-
- if (config_prof && opt_prof)
- return (imallocx_prof(tsd, size, flags, usize, slow_path));
-
- return (imallocx_no_prof(tsd, size, flags, usize, slow_path));
-}
-
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
-void JEMALLOC_NOTHROW *
-JEMALLOC_ATTR(malloc) JEMALLOC_ALLOC_SIZE(1)
-je_mallocx(size_t size, int flags)
-{
- tsdn_t *tsdn;
- void *p;
- size_t usize;
-
- assert(size != 0);
-
- if (likely(!malloc_slow)) {
- p = imallocx_body(size, flags, &tsdn, &usize, false);
- ialloc_post_check(p, tsdn, usize, "mallocx", false, false);
- } else {
- p = imallocx_body(size, flags, &tsdn, &usize, true);
- ialloc_post_check(p, tsdn, usize, "mallocx", false, true);
- UTRACE(0, size, p);
- JEMALLOC_VALGRIND_MALLOC(p != NULL, tsdn, p, usize,
- MALLOCX_ZERO_GET(flags));
- }
-
- return (p);
-}
-
-static void *
-irallocx_prof_sample(tsd_t *tsd, void *old_ptr, size_t old_usize,
- size_t usize, size_t alignment, bool zero, tcache_t *tcache, arena_t *arena,
- prof_tctx_t *tctx)
-{
- void *p;
-
- if (tctx == NULL)
- return (NULL);
- if (usize <= SMALL_MAXCLASS) {
- p = iralloct(tsd, old_ptr, old_usize, LARGE_MINCLASS, alignment,
- zero, tcache, arena);
- if (p == NULL)
- return (NULL);
- arena_prof_promoted(tsd_tsdn(tsd), p, usize);
- } else {
- p = iralloct(tsd, old_ptr, old_usize, usize, alignment, zero,
- tcache, arena);
- }
-
- return (p);
-}
-
-JEMALLOC_ALWAYS_INLINE_C void *
-irallocx_prof(tsd_t *tsd, void *old_ptr, size_t old_usize, size_t size,
- size_t alignment, size_t *usize, bool zero, tcache_t *tcache,
- arena_t *arena)
-{
- void *p;
- bool prof_active;
- prof_tctx_t *old_tctx, *tctx;
-
- prof_active = prof_active_get_unlocked();
- old_tctx = prof_tctx_get(tsd_tsdn(tsd), old_ptr);
- tctx = prof_alloc_prep(tsd, *usize, prof_active, false);
- if (unlikely((uintptr_t)tctx != (uintptr_t)1U)) {
- p = irallocx_prof_sample(tsd, old_ptr, old_usize, *usize,
- alignment, zero, tcache, arena, tctx);
- } else {
- p = iralloct(tsd, old_ptr, old_usize, size, alignment, zero,
- tcache, arena);
- }
- if (unlikely(p == NULL)) {
- prof_alloc_rollback(tsd, tctx, false);
- return (NULL);
- }
-
- if (p == old_ptr && alignment != 0) {
- /*
- * The allocation did not move, so it is possible that the size
- * class is smaller than would guarantee the requested
- * alignment, and that the alignment constraint was
- * serendipitously satisfied. Additionally, old_usize may not
- * be the same as the current usize because of in-place large
- * reallocation. Therefore, query the actual value of usize.
- */
- *usize = isalloc(tsd_tsdn(tsd), p, config_prof);
- }
- prof_realloc(tsd, p, *usize, tctx, prof_active, false, old_ptr,
- old_usize, old_tctx);
-
- return (p);
-}
-
-JEMALLOC_EXPORT JEMALLOC_ALLOCATOR JEMALLOC_RESTRICT_RETURN
-void JEMALLOC_NOTHROW *
-JEMALLOC_ALLOC_SIZE(2)
-je_rallocx(void *ptr, size_t size, int flags)
-{
- void *p;
- tsd_t *tsd;
- size_t usize;
- size_t old_usize;
- UNUSED size_t old_rzsize JEMALLOC_CC_SILENCE_INIT(0);
- size_t alignment = MALLOCX_ALIGN_GET(flags);
- bool zero = flags & MALLOCX_ZERO;
- arena_t *arena;
- tcache_t *tcache;
-
- assert(ptr != NULL);
- assert(size != 0);
- assert(malloc_initialized() || IS_INITIALIZER);
- malloc_thread_init();
- tsd = tsd_fetch();
- witness_assert_lockless(tsd_tsdn(tsd));
-
- if (unlikely((flags & MALLOCX_ARENA_MASK) != 0)) {
- unsigned arena_ind = MALLOCX_ARENA_GET(flags);
- arena = arena_get(tsd_tsdn(tsd), arena_ind, true);
- if (unlikely(arena == NULL))
- goto label_oom;
- } else
- arena = NULL;
-
- if (unlikely((flags & MALLOCX_TCACHE_MASK) != 0)) {
- if ((flags & MALLOCX_TCACHE_MASK) == MALLOCX_TCACHE_NONE)
- tcache = NULL;
- else
- tcache = tcaches_get(tsd, MALLOCX_TCACHE_GET(flags));
- } else
- tcache = tcache_get(tsd, true);
-
- old_usize = isalloc(tsd_tsdn(tsd), ptr, config_prof);
- if (config_valgrind && unlikely(in_valgrind))
- old_rzsize = u2rz(old_usize);
-
- if (config_prof && opt_prof) {
- usize = (alignment == 0) ? s2u(size) : sa2u(size, alignment);
- if (unlikely(usize == 0 || usize > HUGE_MAXCLASS))
- goto label_oom;
- p = irallocx_prof(tsd, ptr, old_usize, size, alignment, &usize,
- zero, tcache, arena);
- if (unlikely(p == NULL))
- goto label_oom;
- } else {
- p = iralloct(tsd, ptr, old_usize, size, alignment, zero,
- tcache, arena);
- if (unlikely(p == NULL))
- goto label_oom;
- if (config_stats || (config_valgrind && unlikely(in_valgrind)))
- usize = isalloc(tsd_tsdn(tsd), p, config_prof);
- }
- assert(alignment == 0 || ((uintptr_t)p & (alignment - 1)) == ZU(0));
-
- if (config_stats) {
- *tsd_thread_allocatedp_get(tsd) += usize;
- *tsd_thread_deallocatedp_get(tsd) += old_usize;
- }
- UTRACE(ptr, size, p);
- JEMALLOC_VALGRIND_REALLOC(true, tsd_tsdn(tsd), p, usize, false, ptr,
- old_usize, old_rzsize, false, zero);
- witness_assert_lockless(tsd_tsdn(tsd));
- return (p);
-label_oom:
- if (config_xmalloc && unlikely(opt_xmalloc)) {
- malloc_write("<jemalloc>: Error in rallocx(): out of memory\n");
- abort();
- }
- UTRACE(ptr, size, 0);
- witness_assert_lockless(tsd_tsdn(tsd));
- return (NULL);
-}
-
-JEMALLOC_ALWAYS_INLINE_C size_t
-ixallocx_helper(tsdn_t *tsdn, void *ptr, size_t old_usize, size_t size,
- size_t extra, size_t alignment, bool zero)
-{
- size_t usize;
-
- if (ixalloc(tsdn, ptr, old_usize, size, extra, alignment, zero))
- return (old_usize);
- usize = isalloc(tsdn, ptr, config_prof);
-
- return (usize);
-}
-
-static size_t
-ixallocx_prof_sample(tsdn_t *tsdn, void *ptr, size_t old_usize, size_t size,
- size_t extra, size_t alignment, bool zero, prof_tctx_t *tctx)
-{
- size_t usize;
-
- if (tctx == NULL)
- return (old_usize);
- usize = ixallocx_helper(tsdn, ptr, old_usize, size, extra, alignment,
- zero);
-
- return (usize);
-}
-
-JEMALLOC_ALWAYS_INLINE_C size_t
-ixallocx_prof(tsd_t *tsd, void *ptr, size_t old_usize, size_t size,
- size_t extra, size_t alignment, bool zero)
-{
- size_t usize_max, usize;
- bool prof_active;
- prof_tctx_t *old_tctx, *tctx;
-
- prof_active = prof_active_get_unlocked();
- old_tctx = prof_tctx_get(tsd_tsdn(tsd), ptr);
- /*
- * usize isn't knowable before ixalloc() returns when extra is non-zero.
- * Therefore, compute its maximum possible value and use that in
- * prof_alloc_prep() to decide whether to capture a backtrace.
- * prof_realloc() will use the actual usize to decide whether to sample.
- */
- if (alignment == 0) {
- usize_max = s2u(size+extra);
- assert(usize_max > 0 && usize_max <= HUGE_MAXCLASS);
- } else {
- usize_max = sa2u(size+extra, alignment);
- if (unlikely(usize_max == 0 || usize_max > HUGE_MAXCLASS)) {
- /*
- * usize_max is out of range, and chances are that
- * allocation will fail, but use the maximum possible
- * value and carry on with prof_alloc_prep(), just in
- * case allocation succeeds.
- */
- usize_max = HUGE_MAXCLASS;
- }
- }
- tctx = prof_alloc_prep(tsd, usize_max, prof_active, false);
-
- if (unlikely((uintptr_t)tctx != (uintptr_t)1U)) {
- usize = ixallocx_prof_sample(tsd_tsdn(tsd), ptr, old_usize,
- size, extra, alignment, zero, tctx);
- } else {
- usize = ixallocx_helper(tsd_tsdn(tsd), ptr, old_usize, size,
- extra, alignment, zero);
- }
- if (usize == old_usize) {
- prof_alloc_rollback(tsd, tctx, false);
- return (usize);
- }
- prof_realloc(tsd, ptr, usize, tctx, prof_active, false, ptr, old_usize,
- old_tctx);
-
- return (usize);
-}
-
-JEMALLOC_EXPORT size_t JEMALLOC_NOTHROW
-je_xallocx(void *ptr, size_t size, size_t extra, int flags)
-{
- tsd_t *tsd;
- size_t usize, old_usize;
- UNUSED size_t old_rzsize JEMALLOC_CC_SILENCE_INIT(0);
- size_t alignment = MALLOCX_ALIGN_GET(flags);
- bool zero = flags & MALLOCX_ZERO;
-
- assert(ptr != NULL);
- assert(size != 0);
- assert(SIZE_T_MAX - size >= extra);
- assert(malloc_initialized() || IS_INITIALIZER);
- malloc_thread_init();
- tsd = tsd_fetch();
- witness_assert_lockless(tsd_tsdn(tsd));
-
- old_usize = isalloc(tsd_tsdn(tsd), ptr, config_prof);
-
- /*
- * The API explicitly absolves itself of protecting against (size +
- * extra) numerical overflow, but we may need to clamp extra to avoid
- * exceeding HUGE_MAXCLASS.
- *
- * Ordinarily, size limit checking is handled deeper down, but here we
- * have to check as part of (size + extra) clamping, since we need the
- * clamped value in the above helper functions.
- */
- if (unlikely(size > HUGE_MAXCLASS)) {
- usize = old_usize;
- goto label_not_resized;
- }
- if (unlikely(HUGE_MAXCLASS - size < extra))
- extra = HUGE_MAXCLASS - size;
-
- if (config_valgrind && unlikely(in_valgrind))
- old_rzsize = u2rz(old_usize);
-
- if (config_prof && opt_prof) {
- usize = ixallocx_prof(tsd, ptr, old_usize, size, extra,
- alignment, zero);
- } else {
- usize = ixallocx_helper(tsd_tsdn(tsd), ptr, old_usize, size,
- extra, alignment, zero);
- }
- if (unlikely(usize == old_usize))
- goto label_not_resized;
-
- if (config_stats) {
- *tsd_thread_allocatedp_get(tsd) += usize;
- *tsd_thread_deallocatedp_get(tsd) += old_usize;
- }
- JEMALLOC_VALGRIND_REALLOC(false, tsd_tsdn(tsd), ptr, usize, false, ptr,
- old_usize, old_rzsize, false, zero);
-label_not_resized:
- UTRACE(ptr, size, ptr);
- witness_assert_lockless(tsd_tsdn(tsd));
- return (usize);
-}
-
-JEMALLOC_EXPORT size_t JEMALLOC_NOTHROW
-JEMALLOC_ATTR(pure)
-je_sallocx(const void *ptr, int flags)
-{
- size_t usize;
- tsdn_t *tsdn;
-
- assert(malloc_initialized() || IS_INITIALIZER);
- malloc_thread_init();
-
- tsdn = tsdn_fetch();
- witness_assert_lockless(tsdn);
-
- if (config_ivsalloc)
- usize = ivsalloc(tsdn, ptr, config_prof);
- else
- usize = isalloc(tsdn, ptr, config_prof);
-
- witness_assert_lockless(tsdn);
- return (usize);
-}
-
-JEMALLOC_EXPORT void JEMALLOC_NOTHROW
-je_dallocx(void *ptr, int flags)
-{
- tsd_t *tsd;
- tcache_t *tcache;
-
- assert(ptr != NULL);
- assert(malloc_initialized() || IS_INITIALIZER);
-
- tsd = tsd_fetch();
- witness_assert_lockless(tsd_tsdn(tsd));
- if (unlikely((flags & MALLOCX_TCACHE_MASK) != 0)) {
- if ((flags & MALLOCX_TCACHE_MASK) == MALLOCX_TCACHE_NONE)
- tcache = NULL;
- else
- tcache = tcaches_get(tsd, MALLOCX_TCACHE_GET(flags));
- } else
- tcache = tcache_get(tsd, false);
-
- UTRACE(ptr, 0, 0);
- if (likely(!malloc_slow))
- ifree(tsd, ptr, tcache, false);
- else
- ifree(tsd, ptr, tcache, true);
- witness_assert_lockless(tsd_tsdn(tsd));
-}
-
-JEMALLOC_ALWAYS_INLINE_C size_t
-inallocx(tsdn_t *tsdn, size_t size, int flags)
-{
- size_t usize;
-
- witness_assert_lockless(tsdn);
-
- if (likely((flags & MALLOCX_LG_ALIGN_MASK) == 0))
- usize = s2u(size);
- else
- usize = sa2u(size, MALLOCX_ALIGN_GET_SPECIFIED(flags));
- witness_assert_lockless(tsdn);
- return (usize);
-}
-
-JEMALLOC_EXPORT void JEMALLOC_NOTHROW
-je_sdallocx(void *ptr, size_t size, int flags)
-{
- tsd_t *tsd;
- tcache_t *tcache;
- size_t usize;
-
- assert(ptr != NULL);
- assert(malloc_initialized() || IS_INITIALIZER);
- tsd = tsd_fetch();
- usize = inallocx(tsd_tsdn(tsd), size, flags);
- assert(usize == isalloc(tsd_tsdn(tsd), ptr, config_prof));
-
- witness_assert_lockless(tsd_tsdn(tsd));
- if (unlikely((flags & MALLOCX_TCACHE_MASK) != 0)) {
- if ((flags & MALLOCX_TCACHE_MASK) == MALLOCX_TCACHE_NONE)
- tcache = NULL;
- else
- tcache = tcaches_get(tsd, MALLOCX_TCACHE_GET(flags));
- } else
- tcache = tcache_get(tsd, false);
-
- UTRACE(ptr, 0, 0);
- if (likely(!malloc_slow))
- isfree(tsd, ptr, usize, tcache, false);
- else
- isfree(tsd, ptr, usize, tcache, true);
- witness_assert_lockless(tsd_tsdn(tsd));
-}
-
-JEMALLOC_EXPORT size_t JEMALLOC_NOTHROW
-JEMALLOC_ATTR(pure)
-je_nallocx(size_t size, int flags)
-{
- size_t usize;
- tsdn_t *tsdn;
-
- assert(size != 0);
-
- if (unlikely(malloc_init()))
- return (0);
-
- tsdn = tsdn_fetch();
- witness_assert_lockless(tsdn);
-
- usize = inallocx(tsdn, size, flags);
- if (unlikely(usize > HUGE_MAXCLASS))
- return (0);
-
- witness_assert_lockless(tsdn);
- return (usize);
-}
-
-JEMALLOC_EXPORT int JEMALLOC_NOTHROW
-je_mallctl(const char *name, void *oldp, size_t *oldlenp, void *newp,
- size_t newlen)
-{
- int ret;
- tsd_t *tsd;
-
- if (unlikely(malloc_init()))
- return (EAGAIN);
-
- tsd = tsd_fetch();
- witness_assert_lockless(tsd_tsdn(tsd));
- ret = ctl_byname(tsd, name, oldp, oldlenp, newp, newlen);
- witness_assert_lockless(tsd_tsdn(tsd));
- return (ret);
-}
-
-JEMALLOC_EXPORT int JEMALLOC_NOTHROW
-je_mallctlnametomib(const char *name, size_t *mibp, size_t *miblenp)
-{
- int ret;
- tsdn_t *tsdn;
-
- if (unlikely(malloc_init()))
- return (EAGAIN);
-
- tsdn = tsdn_fetch();
- witness_assert_lockless(tsdn);
- ret = ctl_nametomib(tsdn, name, mibp, miblenp);
- witness_assert_lockless(tsdn);
- return (ret);
-}
-
-JEMALLOC_EXPORT int JEMALLOC_NOTHROW
-je_mallctlbymib(const size_t *mib, size_t miblen, void *oldp, size_t *oldlenp,
- void *newp, size_t newlen)
-{
- int ret;
- tsd_t *tsd;
-
- if (unlikely(malloc_init()))
- return (EAGAIN);
-
- tsd = tsd_fetch();
- witness_assert_lockless(tsd_tsdn(tsd));
- ret = ctl_bymib(tsd, mib, miblen, oldp, oldlenp, newp, newlen);
- witness_assert_lockless(tsd_tsdn(tsd));
- return (ret);
-}
-
-JEMALLOC_EXPORT void JEMALLOC_NOTHROW
-je_malloc_stats_print(void (*write_cb)(void *, const char *), void *cbopaque,
- const char *opts)
-{
- tsdn_t *tsdn;
-
- tsdn = tsdn_fetch();
- witness_assert_lockless(tsdn);
- stats_print(write_cb, cbopaque, opts);
- witness_assert_lockless(tsdn);
-}
-
-JEMALLOC_EXPORT size_t JEMALLOC_NOTHROW
-je_malloc_usable_size(JEMALLOC_USABLE_SIZE_CONST void *ptr)
-{
- size_t ret;
- tsdn_t *tsdn;
-
- assert(malloc_initialized() || IS_INITIALIZER);
- malloc_thread_init();
-
- tsdn = tsdn_fetch();
- witness_assert_lockless(tsdn);
-
- if (config_ivsalloc)
- ret = ivsalloc(tsdn, ptr, config_prof);
- else
- ret = (ptr == NULL) ? 0 : isalloc(tsdn, ptr, config_prof);
-
- witness_assert_lockless(tsdn);
- return (ret);
-}
-
-/*
- * End non-standard functions.
- */
-/******************************************************************************/
-/*
- * The following functions are used by threading libraries for protection of
- * malloc during fork().
- */
-
-/*
- * If an application creates a thread before doing any allocation in the main
- * thread, then calls fork(2) in the main thread followed by memory allocation
- * in the child process, a race can occur that results in deadlock within the
- * child: the main thread may have forked while the created thread had
- * partially initialized the allocator. Ordinarily jemalloc prevents
- * fork/malloc races via the following functions it registers during
- * initialization using pthread_atfork(), but of course that does no good if
- * the allocator isn't fully initialized at fork time. The following library
- * constructor is a partial solution to this problem. It may still be possible
- * to trigger the deadlock described above, but doing so would involve forking
- * via a library constructor that runs before jemalloc's runs.
- */
-#ifndef JEMALLOC_JET
-JEMALLOC_ATTR(constructor)
-static void
-jemalloc_constructor(void)
-{
-
- malloc_init();
-}
-#endif
-
-#ifndef JEMALLOC_MUTEX_INIT_CB
-void
-jemalloc_prefork(void)
-#else
-JEMALLOC_EXPORT void
-_malloc_prefork(void)
-#endif
-{
- tsd_t *tsd;
- unsigned i, j, narenas;
- arena_t *arena;
-
-#ifdef JEMALLOC_MUTEX_INIT_CB
- if (!malloc_initialized())
- return;
-#endif
- assert(malloc_initialized());
-
- tsd = tsd_fetch();
-
- narenas = narenas_total_get();
-
- witness_prefork(tsd);
- /* Acquire all mutexes in a safe order. */
- ctl_prefork(tsd_tsdn(tsd));
- malloc_mutex_prefork(tsd_tsdn(tsd), &arenas_lock);
- prof_prefork0(tsd_tsdn(tsd));
- for (i = 0; i < 3; i++) {
- for (j = 0; j < narenas; j++) {
- if ((arena = arena_get(tsd_tsdn(tsd), j, false)) !=
- NULL) {
- switch (i) {
- case 0:
- arena_prefork0(tsd_tsdn(tsd), arena);
- break;
- case 1:
- arena_prefork1(tsd_tsdn(tsd), arena);
- break;
- case 2:
- arena_prefork2(tsd_tsdn(tsd), arena);
- break;
- default: not_reached();
- }
- }
- }
- }
- base_prefork(tsd_tsdn(tsd));
- for (i = 0; i < narenas; i++) {
- if ((arena = arena_get(tsd_tsdn(tsd), i, false)) != NULL)
- arena_prefork3(tsd_tsdn(tsd), arena);
- }
- prof_prefork1(tsd_tsdn(tsd));
-}
-
-#ifndef JEMALLOC_MUTEX_INIT_CB
-void
-jemalloc_postfork_parent(void)
-#else
-JEMALLOC_EXPORT void
-_malloc_postfork(void)
-#endif
-{
- tsd_t *tsd;
- unsigned i, narenas;
-
-#ifdef JEMALLOC_MUTEX_INIT_CB
- if (!malloc_initialized())
- return;
-#endif
- assert(malloc_initialized());
-
- tsd = tsd_fetch();
-
- witness_postfork_parent(tsd);
- /* Release all mutexes, now that fork() has completed. */
- base_postfork_parent(tsd_tsdn(tsd));
- for (i = 0, narenas = narenas_total_get(); i < narenas; i++) {
- arena_t *arena;
-
- if ((arena = arena_get(tsd_tsdn(tsd), i, false)) != NULL)
- arena_postfork_parent(tsd_tsdn(tsd), arena);
- }
- prof_postfork_parent(tsd_tsdn(tsd));
- malloc_mutex_postfork_parent(tsd_tsdn(tsd), &arenas_lock);
- ctl_postfork_parent(tsd_tsdn(tsd));
-}
-
-void
-jemalloc_postfork_child(void)
-{
- tsd_t *tsd;
- unsigned i, narenas;
-
- assert(malloc_initialized());
-
- tsd = tsd_fetch();
-
- witness_postfork_child(tsd);
- /* Release all mutexes, now that fork() has completed. */
- base_postfork_child(tsd_tsdn(tsd));
- for (i = 0, narenas = narenas_total_get(); i < narenas; i++) {
- arena_t *arena;
-
- if ((arena = arena_get(tsd_tsdn(tsd), i, false)) != NULL)
- arena_postfork_child(tsd_tsdn(tsd), arena);
- }
- prof_postfork_child(tsd_tsdn(tsd));
- malloc_mutex_postfork_child(tsd_tsdn(tsd), &arenas_lock);
- ctl_postfork_child(tsd_tsdn(tsd));
-}
-
-/******************************************************************************/
diff --git a/memory/jemalloc/src/src/mb.c b/memory/jemalloc/src/src/mb.c
deleted file mode 100644
index dc2c0a256..000000000
--- a/memory/jemalloc/src/src/mb.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#define JEMALLOC_MB_C_
-#include "jemalloc/internal/jemalloc_internal.h"
diff --git a/memory/jemalloc/src/src/mutex.c b/memory/jemalloc/src/src/mutex.c
deleted file mode 100644
index 6333e73d6..000000000
--- a/memory/jemalloc/src/src/mutex.c
+++ /dev/null
@@ -1,158 +0,0 @@
-#define JEMALLOC_MUTEX_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-#if defined(JEMALLOC_LAZY_LOCK) && !defined(_WIN32)
-#include <dlfcn.h>
-#endif
-
-#ifndef _CRT_SPINCOUNT
-#define _CRT_SPINCOUNT 4000
-#endif
-
-/******************************************************************************/
-/* Data. */
-
-#ifdef JEMALLOC_LAZY_LOCK
-bool isthreaded = false;
-#endif
-#ifdef JEMALLOC_MUTEX_INIT_CB
-static bool postpone_init = true;
-static malloc_mutex_t *postponed_mutexes = NULL;
-#endif
-
-#if defined(JEMALLOC_LAZY_LOCK) && !defined(_WIN32)
-static void pthread_create_once(void);
-#endif
-
-/******************************************************************************/
-/*
- * We intercept pthread_create() calls in order to toggle isthreaded if the
- * process goes multi-threaded.
- */
-
-#if defined(JEMALLOC_LAZY_LOCK) && !defined(_WIN32)
-static int (*pthread_create_fptr)(pthread_t *__restrict, const pthread_attr_t *,
- void *(*)(void *), void *__restrict);
-
-static void
-pthread_create_once(void)
-{
-
- pthread_create_fptr = dlsym(RTLD_NEXT, "pthread_create");
- if (pthread_create_fptr == NULL) {
- malloc_write("<jemalloc>: Error in dlsym(RTLD_NEXT, "
- "\"pthread_create\")\n");
- abort();
- }
-
- isthreaded = true;
-}
-
-JEMALLOC_EXPORT int
-pthread_create(pthread_t *__restrict thread,
- const pthread_attr_t *__restrict attr, void *(*start_routine)(void *),
- void *__restrict arg)
-{
- static pthread_once_t once_control = PTHREAD_ONCE_INIT;
-
- pthread_once(&once_control, pthread_create_once);
-
- return (pthread_create_fptr(thread, attr, start_routine, arg));
-}
-#endif
-
-/******************************************************************************/
-
-#ifdef JEMALLOC_MUTEX_INIT_CB
-JEMALLOC_EXPORT int _pthread_mutex_init_calloc_cb(pthread_mutex_t *mutex,
- void *(calloc_cb)(size_t, size_t));
-#endif
-
-bool
-malloc_mutex_init(malloc_mutex_t *mutex, const char *name, witness_rank_t rank)
-{
-
-#ifdef _WIN32
-# if _WIN32_WINNT >= 0x0600
- InitializeSRWLock(&mutex->lock);
-# else
- if (!InitializeCriticalSectionAndSpinCount(&mutex->lock,
- _CRT_SPINCOUNT))
- return (true);
-# endif
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
- mutex->lock = OS_UNFAIR_LOCK_INIT;
-#elif (defined(JEMALLOC_OSSPIN))
- mutex->lock = 0;
-#elif (defined(JEMALLOC_MUTEX_INIT_CB))
- if (postpone_init) {
- mutex->postponed_next = postponed_mutexes;
- postponed_mutexes = mutex;
- } else {
- if (_pthread_mutex_init_calloc_cb(&mutex->lock,
- bootstrap_calloc) != 0)
- return (true);
- }
-#else
- pthread_mutexattr_t attr;
-
- if (pthread_mutexattr_init(&attr) != 0)
- return (true);
- pthread_mutexattr_settype(&attr, MALLOC_MUTEX_TYPE);
- if (pthread_mutex_init(&mutex->lock, &attr) != 0) {
- pthread_mutexattr_destroy(&attr);
- return (true);
- }
- pthread_mutexattr_destroy(&attr);
-#endif
- if (config_debug)
- witness_init(&mutex->witness, name, rank, NULL);
- return (false);
-}
-
-void
-malloc_mutex_prefork(tsdn_t *tsdn, malloc_mutex_t *mutex)
-{
-
- malloc_mutex_lock(tsdn, mutex);
-}
-
-void
-malloc_mutex_postfork_parent(tsdn_t *tsdn, malloc_mutex_t *mutex)
-{
-
- malloc_mutex_unlock(tsdn, mutex);
-}
-
-void
-malloc_mutex_postfork_child(tsdn_t *tsdn, malloc_mutex_t *mutex)
-{
-
-#ifdef JEMALLOC_MUTEX_INIT_CB
- malloc_mutex_unlock(tsdn, mutex);
-#else
- if (malloc_mutex_init(mutex, mutex->witness.name,
- mutex->witness.rank)) {
- malloc_printf("<jemalloc>: Error re-initializing mutex in "
- "child\n");
- if (opt_abort)
- abort();
- }
-#endif
-}
-
-bool
-malloc_mutex_boot(void)
-{
-
-#ifdef JEMALLOC_MUTEX_INIT_CB
- postpone_init = false;
- while (postponed_mutexes != NULL) {
- if (_pthread_mutex_init_calloc_cb(&postponed_mutexes->lock,
- bootstrap_calloc) != 0)
- return (true);
- postponed_mutexes = postponed_mutexes->postponed_next;
- }
-#endif
- return (false);
-}
diff --git a/memory/jemalloc/src/src/nstime.c b/memory/jemalloc/src/src/nstime.c
deleted file mode 100644
index 0948e29fa..000000000
--- a/memory/jemalloc/src/src/nstime.c
+++ /dev/null
@@ -1,194 +0,0 @@
-#include "jemalloc/internal/jemalloc_internal.h"
-
-#define BILLION UINT64_C(1000000000)
-
-void
-nstime_init(nstime_t *time, uint64_t ns)
-{
-
- time->ns = ns;
-}
-
-void
-nstime_init2(nstime_t *time, uint64_t sec, uint64_t nsec)
-{
-
- time->ns = sec * BILLION + nsec;
-}
-
-uint64_t
-nstime_ns(const nstime_t *time)
-{
-
- return (time->ns);
-}
-
-uint64_t
-nstime_sec(const nstime_t *time)
-{
-
- return (time->ns / BILLION);
-}
-
-uint64_t
-nstime_nsec(const nstime_t *time)
-{
-
- return (time->ns % BILLION);
-}
-
-void
-nstime_copy(nstime_t *time, const nstime_t *source)
-{
-
- *time = *source;
-}
-
-int
-nstime_compare(const nstime_t *a, const nstime_t *b)
-{
-
- return ((a->ns > b->ns) - (a->ns < b->ns));
-}
-
-void
-nstime_add(nstime_t *time, const nstime_t *addend)
-{
-
- assert(UINT64_MAX - time->ns >= addend->ns);
-
- time->ns += addend->ns;
-}
-
-void
-nstime_subtract(nstime_t *time, const nstime_t *subtrahend)
-{
-
- assert(nstime_compare(time, subtrahend) >= 0);
-
- time->ns -= subtrahend->ns;
-}
-
-void
-nstime_imultiply(nstime_t *time, uint64_t multiplier)
-{
-
- assert((((time->ns | multiplier) & (UINT64_MAX << (sizeof(uint64_t) <<
- 2))) == 0) || ((time->ns * multiplier) / multiplier == time->ns));
-
- time->ns *= multiplier;
-}
-
-void
-nstime_idivide(nstime_t *time, uint64_t divisor)
-{
-
- assert(divisor != 0);
-
- time->ns /= divisor;
-}
-
-uint64_t
-nstime_divide(const nstime_t *time, const nstime_t *divisor)
-{
-
- assert(divisor->ns != 0);
-
- return (time->ns / divisor->ns);
-}
-
-#ifdef _WIN32
-# define NSTIME_MONOTONIC true
-static void
-nstime_get(nstime_t *time)
-{
- FILETIME ft;
- uint64_t ticks_100ns;
-
- GetSystemTimeAsFileTime(&ft);
- ticks_100ns = (((uint64_t)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
-
- nstime_init(time, ticks_100ns * 100);
-}
-#elif JEMALLOC_HAVE_CLOCK_MONOTONIC_COARSE
-# define NSTIME_MONOTONIC true
-static void
-nstime_get(nstime_t *time)
-{
- struct timespec ts;
-
- clock_gettime(CLOCK_MONOTONIC_COARSE, &ts);
- nstime_init2(time, ts.tv_sec, ts.tv_nsec);
-}
-#elif JEMALLOC_HAVE_CLOCK_MONOTONIC
-# define NSTIME_MONOTONIC true
-static void
-nstime_get(nstime_t *time)
-{
- struct timespec ts;
-
- clock_gettime(CLOCK_MONOTONIC, &ts);
- nstime_init2(time, ts.tv_sec, ts.tv_nsec);
-}
-#elif JEMALLOC_HAVE_MACH_ABSOLUTE_TIME
-# define NSTIME_MONOTONIC true
-static void
-nstime_get(nstime_t *time)
-{
-
- nstime_init(time, mach_absolute_time());
-}
-#else
-# define NSTIME_MONOTONIC false
-static void
-nstime_get(nstime_t *time)
-{
- struct timeval tv;
-
- gettimeofday(&tv, NULL);
- nstime_init2(time, tv.tv_sec, tv.tv_usec * 1000);
-}
-#endif
-
-#ifdef JEMALLOC_JET
-#undef nstime_monotonic
-#define nstime_monotonic JEMALLOC_N(n_nstime_monotonic)
-#endif
-bool
-nstime_monotonic(void)
-{
-
- return (NSTIME_MONOTONIC);
-#undef NSTIME_MONOTONIC
-}
-#ifdef JEMALLOC_JET
-#undef nstime_monotonic
-#define nstime_monotonic JEMALLOC_N(nstime_monotonic)
-nstime_monotonic_t *nstime_monotonic = JEMALLOC_N(n_nstime_monotonic);
-#endif
-
-#ifdef JEMALLOC_JET
-#undef nstime_update
-#define nstime_update JEMALLOC_N(n_nstime_update)
-#endif
-bool
-nstime_update(nstime_t *time)
-{
- nstime_t old_time;
-
- nstime_copy(&old_time, time);
- nstime_get(time);
-
- /* Handle non-monotonic clocks. */
- if (unlikely(nstime_compare(&old_time, time) > 0)) {
- nstime_copy(time, &old_time);
- return (true);
- }
-
- return (false);
-}
-#ifdef JEMALLOC_JET
-#undef nstime_update
-#define nstime_update JEMALLOC_N(nstime_update)
-nstime_update_t *nstime_update = JEMALLOC_N(n_nstime_update);
-#endif
diff --git a/memory/jemalloc/src/src/pages.c b/memory/jemalloc/src/src/pages.c
deleted file mode 100644
index 647952ac3..000000000
--- a/memory/jemalloc/src/src/pages.c
+++ /dev/null
@@ -1,273 +0,0 @@
-#define JEMALLOC_PAGES_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-#ifdef JEMALLOC_SYSCTL_VM_OVERCOMMIT
-#include <sys/sysctl.h>
-#endif
-
-/******************************************************************************/
-/* Data. */
-
-#ifndef _WIN32
-# define PAGES_PROT_COMMIT (PROT_READ | PROT_WRITE)
-# define PAGES_PROT_DECOMMIT (PROT_NONE)
-static int mmap_flags;
-#endif
-static bool os_overcommits;
-
-/******************************************************************************/
-
-void *
-pages_map(void *addr, size_t size, bool *commit)
-{
- void *ret;
-
- assert(size != 0);
-
- if (os_overcommits)
- *commit = true;
-
-#ifdef _WIN32
- /*
- * If VirtualAlloc can't allocate at the given address when one is
- * given, it fails and returns NULL.
- */
- ret = VirtualAlloc(addr, size, MEM_RESERVE | (*commit ? MEM_COMMIT : 0),
- PAGE_READWRITE);
-#else
- /*
- * We don't use MAP_FIXED here, because it can cause the *replacement*
- * of existing mappings, and we only want to create new mappings.
- */
- {
- int prot = *commit ? PAGES_PROT_COMMIT : PAGES_PROT_DECOMMIT;
-
- ret = mmap(addr, size, prot, mmap_flags, -1, 0);
- }
- assert(ret != NULL);
-
- if (ret == MAP_FAILED)
- ret = NULL;
- else if (addr != NULL && ret != addr) {
- /*
- * We succeeded in mapping memory, but not in the right place.
- */
- pages_unmap(ret, size);
- ret = NULL;
- }
-#endif
- assert(ret == NULL || (addr == NULL && ret != addr)
- || (addr != NULL && ret == addr));
- return (ret);
-}
-
-void
-pages_unmap(void *addr, size_t size)
-{
-
-#ifdef _WIN32
- if (VirtualFree(addr, 0, MEM_RELEASE) == 0)
-#else
- if (munmap(addr, size) == -1)
-#endif
- {
- char buf[BUFERROR_BUF];
-
- buferror(get_errno(), buf, sizeof(buf));
- malloc_printf("<jemalloc>: Error in "
-#ifdef _WIN32
- "VirtualFree"
-#else
- "munmap"
-#endif
- "(): %s\n", buf);
- if (opt_abort)
- abort();
- }
-}
-
-void *
-pages_trim(void *addr, size_t alloc_size, size_t leadsize, size_t size,
- bool *commit)
-{
- void *ret = (void *)((uintptr_t)addr + leadsize);
-
- assert(alloc_size >= leadsize + size);
-#ifdef _WIN32
- {
- void *new_addr;
-
- pages_unmap(addr, alloc_size);
- new_addr = pages_map(ret, size, commit);
- if (new_addr == ret)
- return (ret);
- if (new_addr)
- pages_unmap(new_addr, size);
- return (NULL);
- }
-#else
- {
- size_t trailsize = alloc_size - leadsize - size;
-
- if (leadsize != 0)
- pages_unmap(addr, leadsize);
- if (trailsize != 0)
- pages_unmap((void *)((uintptr_t)ret + size), trailsize);
- return (ret);
- }
-#endif
-}
-
-static bool
-pages_commit_impl(void *addr, size_t size, bool commit)
-{
-
- if (os_overcommits)
- return (true);
-
-#ifdef _WIN32
- return (commit ? (addr != VirtualAlloc(addr, size, MEM_COMMIT,
- PAGE_READWRITE)) : (!VirtualFree(addr, size, MEM_DECOMMIT)));
-#else
- {
- int prot = commit ? PAGES_PROT_COMMIT : PAGES_PROT_DECOMMIT;
- void *result = mmap(addr, size, prot, mmap_flags | MAP_FIXED,
- -1, 0);
- if (result == MAP_FAILED)
- return (true);
- if (result != addr) {
- /*
- * We succeeded in mapping memory, but not in the right
- * place.
- */
- pages_unmap(result, size);
- return (true);
- }
- return (false);
- }
-#endif
-}
-
-bool
-pages_commit(void *addr, size_t size)
-{
-
- return (pages_commit_impl(addr, size, true));
-}
-
-bool
-pages_decommit(void *addr, size_t size)
-{
-
- return (pages_commit_impl(addr, size, false));
-}
-
-bool
-pages_purge(void *addr, size_t size)
-{
- bool unzeroed;
-
-#ifdef _WIN32
- VirtualAlloc(addr, size, MEM_RESET, PAGE_READWRITE);
- unzeroed = true;
-#elif defined(JEMALLOC_HAVE_MADVISE)
-# ifdef JEMALLOC_PURGE_MADVISE_DONTNEED
-# define JEMALLOC_MADV_PURGE MADV_DONTNEED
-# define JEMALLOC_MADV_ZEROS true
-# elif defined(JEMALLOC_PURGE_MADVISE_FREE)
-# define JEMALLOC_MADV_PURGE MADV_FREE
-# define JEMALLOC_MADV_ZEROS false
-# else
-# error "No madvise(2) flag defined for purging unused dirty pages."
-# endif
- int err = madvise(addr, size, JEMALLOC_MADV_PURGE);
- unzeroed = (!JEMALLOC_MADV_ZEROS || err != 0);
-# undef JEMALLOC_MADV_PURGE
-# undef JEMALLOC_MADV_ZEROS
-#else
- /* Last resort no-op. */
- unzeroed = true;
-#endif
- return (unzeroed);
-}
-
-#ifdef JEMALLOC_SYSCTL_VM_OVERCOMMIT
-static bool
-os_overcommits_sysctl(void)
-{
- int vm_overcommit;
- size_t sz;
-
- sz = sizeof(vm_overcommit);
- if (sysctlbyname("vm.overcommit", &vm_overcommit, &sz, NULL, 0) != 0)
- return (false); /* Error. */
-
- return ((vm_overcommit & 0x3) == 0);
-}
-#endif
-
-#ifdef JEMALLOC_PROC_SYS_VM_OVERCOMMIT_MEMORY
-/*
- * Use syscall(2) rather than {open,read,close}(2) when possible to avoid
- * reentry during bootstrapping if another library has interposed system call
- * wrappers.
- */
-static bool
-os_overcommits_proc(void)
-{
- int fd;
- char buf[1];
- ssize_t nread;
-
-#if defined(JEMALLOC_HAVE_SYSCALL) && defined(SYS_open)
- fd = (int)syscall(SYS_open, "/proc/sys/vm/overcommit_memory", O_RDONLY);
-#else
- fd = open("/proc/sys/vm/overcommit_memory", O_RDONLY);
-#endif
- if (fd == -1)
- return (false); /* Error. */
-
-#if defined(JEMALLOC_HAVE_SYSCALL) && defined(SYS_read)
- nread = (ssize_t)syscall(SYS_read, fd, &buf, sizeof(buf));
-#else
- nread = read(fd, &buf, sizeof(buf));
-#endif
-
-#if defined(JEMALLOC_HAVE_SYSCALL) && defined(SYS_close)
- syscall(SYS_close, fd);
-#else
- close(fd);
-#endif
-
- if (nread < 1)
- return (false); /* Error. */
- /*
- * /proc/sys/vm/overcommit_memory meanings:
- * 0: Heuristic overcommit.
- * 1: Always overcommit.
- * 2: Never overcommit.
- */
- return (buf[0] == '0' || buf[0] == '1');
-}
-#endif
-
-void
-pages_boot(void)
-{
-
-#ifndef _WIN32
- mmap_flags = MAP_PRIVATE | MAP_ANON;
-#endif
-
-#ifdef JEMALLOC_SYSCTL_VM_OVERCOMMIT
- os_overcommits = os_overcommits_sysctl();
-#elif defined(JEMALLOC_PROC_SYS_VM_OVERCOMMIT_MEMORY)
- os_overcommits = os_overcommits_proc();
-# ifdef MAP_NORESERVE
- if (os_overcommits)
- mmap_flags |= MAP_NORESERVE;
-# endif
-#else
- os_overcommits = false;
-#endif
-}
diff --git a/memory/jemalloc/src/src/prng.c b/memory/jemalloc/src/src/prng.c
deleted file mode 100644
index 76646a2a4..000000000
--- a/memory/jemalloc/src/src/prng.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#define JEMALLOC_PRNG_C_
-#include "jemalloc/internal/jemalloc_internal.h"
diff --git a/memory/jemalloc/src/src/prof.c b/memory/jemalloc/src/src/prof.c
deleted file mode 100644
index c89dade1f..000000000
--- a/memory/jemalloc/src/src/prof.c
+++ /dev/null
@@ -1,2355 +0,0 @@
-#define JEMALLOC_PROF_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-/******************************************************************************/
-
-#ifdef JEMALLOC_PROF_LIBUNWIND
-#define UNW_LOCAL_ONLY
-#include <libunwind.h>
-#endif
-
-#ifdef JEMALLOC_PROF_LIBGCC
-#include <unwind.h>
-#endif
-
-/******************************************************************************/
-/* Data. */
-
-bool opt_prof = false;
-bool opt_prof_active = true;
-bool opt_prof_thread_active_init = true;
-size_t opt_lg_prof_sample = LG_PROF_SAMPLE_DEFAULT;
-ssize_t opt_lg_prof_interval = LG_PROF_INTERVAL_DEFAULT;
-bool opt_prof_gdump = false;
-bool opt_prof_final = false;
-bool opt_prof_leak = false;
-bool opt_prof_accum = false;
-char opt_prof_prefix[
- /* Minimize memory bloat for non-prof builds. */
-#ifdef JEMALLOC_PROF
- PATH_MAX +
-#endif
- 1];
-
-/*
- * Initialized as opt_prof_active, and accessed via
- * prof_active_[gs]et{_unlocked,}().
- */
-bool prof_active;
-static malloc_mutex_t prof_active_mtx;
-
-/*
- * Initialized as opt_prof_thread_active_init, and accessed via
- * prof_thread_active_init_[gs]et().
- */
-static bool prof_thread_active_init;
-static malloc_mutex_t prof_thread_active_init_mtx;
-
-/*
- * Initialized as opt_prof_gdump, and accessed via
- * prof_gdump_[gs]et{_unlocked,}().
- */
-bool prof_gdump_val;
-static malloc_mutex_t prof_gdump_mtx;
-
-uint64_t prof_interval = 0;
-
-size_t lg_prof_sample;
-
-/*
- * Table of mutexes that are shared among gctx's. These are leaf locks, so
- * there is no problem with using them for more than one gctx at the same time.
- * The primary motivation for this sharing though is that gctx's are ephemeral,
- * and destroying mutexes causes complications for systems that allocate when
- * creating/destroying mutexes.
- */
-static malloc_mutex_t *gctx_locks;
-static unsigned cum_gctxs; /* Atomic counter. */
-
-/*
- * Table of mutexes that are shared among tdata's. No operations require
- * holding multiple tdata locks, so there is no problem with using them for more
- * than one tdata at the same time, even though a gctx lock may be acquired
- * while holding a tdata lock.
- */
-static malloc_mutex_t *tdata_locks;
-
-/*
- * Global hash of (prof_bt_t *)-->(prof_gctx_t *). This is the master data
- * structure that knows about all backtraces currently captured.
- */
-static ckh_t bt2gctx;
-static malloc_mutex_t bt2gctx_mtx;
-
-/*
- * Tree of all extant prof_tdata_t structures, regardless of state,
- * {attached,detached,expired}.
- */
-static prof_tdata_tree_t tdatas;
-static malloc_mutex_t tdatas_mtx;
-
-static uint64_t next_thr_uid;
-static malloc_mutex_t next_thr_uid_mtx;
-
-static malloc_mutex_t prof_dump_seq_mtx;
-static uint64_t prof_dump_seq;
-static uint64_t prof_dump_iseq;
-static uint64_t prof_dump_mseq;
-static uint64_t prof_dump_useq;
-
-/*
- * This buffer is rather large for stack allocation, so use a single buffer for
- * all profile dumps.
- */
-static malloc_mutex_t prof_dump_mtx;
-static char prof_dump_buf[
- /* Minimize memory bloat for non-prof builds. */
-#ifdef JEMALLOC_PROF
- PROF_DUMP_BUFSIZE
-#else
- 1
-#endif
-];
-static size_t prof_dump_buf_end;
-static int prof_dump_fd;
-
-/* Do not dump any profiles until bootstrapping is complete. */
-static bool prof_booted = false;
-
-/******************************************************************************/
-/*
- * Function prototypes for static functions that are referenced prior to
- * definition.
- */
-
-static bool prof_tctx_should_destroy(tsdn_t *tsdn, prof_tctx_t *tctx);
-static void prof_tctx_destroy(tsd_t *tsd, prof_tctx_t *tctx);
-static bool prof_tdata_should_destroy(tsdn_t *tsdn, prof_tdata_t *tdata,
- bool even_if_attached);
-static void prof_tdata_destroy(tsd_t *tsd, prof_tdata_t *tdata,
- bool even_if_attached);
-static char *prof_thread_name_alloc(tsdn_t *tsdn, const char *thread_name);
-
-/******************************************************************************/
-/* Red-black trees. */
-
-JEMALLOC_INLINE_C int
-prof_tctx_comp(const prof_tctx_t *a, const prof_tctx_t *b)
-{
- uint64_t a_thr_uid = a->thr_uid;
- uint64_t b_thr_uid = b->thr_uid;
- int ret = (a_thr_uid > b_thr_uid) - (a_thr_uid < b_thr_uid);
- if (ret == 0) {
- uint64_t a_thr_discrim = a->thr_discrim;
- uint64_t b_thr_discrim = b->thr_discrim;
- ret = (a_thr_discrim > b_thr_discrim) - (a_thr_discrim <
- b_thr_discrim);
- if (ret == 0) {
- uint64_t a_tctx_uid = a->tctx_uid;
- uint64_t b_tctx_uid = b->tctx_uid;
- ret = (a_tctx_uid > b_tctx_uid) - (a_tctx_uid <
- b_tctx_uid);
- }
- }
- return (ret);
-}
-
-rb_gen(static UNUSED, tctx_tree_, prof_tctx_tree_t, prof_tctx_t,
- tctx_link, prof_tctx_comp)
-
-JEMALLOC_INLINE_C int
-prof_gctx_comp(const prof_gctx_t *a, const prof_gctx_t *b)
-{
- unsigned a_len = a->bt.len;
- unsigned b_len = b->bt.len;
- unsigned comp_len = (a_len < b_len) ? a_len : b_len;
- int ret = memcmp(a->bt.vec, b->bt.vec, comp_len * sizeof(void *));
- if (ret == 0)
- ret = (a_len > b_len) - (a_len < b_len);
- return (ret);
-}
-
-rb_gen(static UNUSED, gctx_tree_, prof_gctx_tree_t, prof_gctx_t, dump_link,
- prof_gctx_comp)
-
-JEMALLOC_INLINE_C int
-prof_tdata_comp(const prof_tdata_t *a, const prof_tdata_t *b)
-{
- int ret;
- uint64_t a_uid = a->thr_uid;
- uint64_t b_uid = b->thr_uid;
-
- ret = ((a_uid > b_uid) - (a_uid < b_uid));
- if (ret == 0) {
- uint64_t a_discrim = a->thr_discrim;
- uint64_t b_discrim = b->thr_discrim;
-
- ret = ((a_discrim > b_discrim) - (a_discrim < b_discrim));
- }
- return (ret);
-}
-
-rb_gen(static UNUSED, tdata_tree_, prof_tdata_tree_t, prof_tdata_t, tdata_link,
- prof_tdata_comp)
-
-/******************************************************************************/
-
-void
-prof_alloc_rollback(tsd_t *tsd, prof_tctx_t *tctx, bool updated)
-{
- prof_tdata_t *tdata;
-
- cassert(config_prof);
-
- if (updated) {
- /*
- * Compute a new sample threshold. This isn't very important in
- * practice, because this function is rarely executed, so the
- * potential for sample bias is minimal except in contrived
- * programs.
- */
- tdata = prof_tdata_get(tsd, true);
- if (tdata != NULL)
- prof_sample_threshold_update(tdata);
- }
-
- if ((uintptr_t)tctx > (uintptr_t)1U) {
- malloc_mutex_lock(tsd_tsdn(tsd), tctx->tdata->lock);
- tctx->prepared = false;
- if (prof_tctx_should_destroy(tsd_tsdn(tsd), tctx))
- prof_tctx_destroy(tsd, tctx);
- else
- malloc_mutex_unlock(tsd_tsdn(tsd), tctx->tdata->lock);
- }
-}
-
-void
-prof_malloc_sample_object(tsdn_t *tsdn, const void *ptr, size_t usize,
- prof_tctx_t *tctx)
-{
-
- prof_tctx_set(tsdn, ptr, usize, tctx);
-
- malloc_mutex_lock(tsdn, tctx->tdata->lock);
- tctx->cnts.curobjs++;
- tctx->cnts.curbytes += usize;
- if (opt_prof_accum) {
- tctx->cnts.accumobjs++;
- tctx->cnts.accumbytes += usize;
- }
- tctx->prepared = false;
- malloc_mutex_unlock(tsdn, tctx->tdata->lock);
-}
-
-void
-prof_free_sampled_object(tsd_t *tsd, size_t usize, prof_tctx_t *tctx)
-{
-
- malloc_mutex_lock(tsd_tsdn(tsd), tctx->tdata->lock);
- assert(tctx->cnts.curobjs > 0);
- assert(tctx->cnts.curbytes >= usize);
- tctx->cnts.curobjs--;
- tctx->cnts.curbytes -= usize;
-
- if (prof_tctx_should_destroy(tsd_tsdn(tsd), tctx))
- prof_tctx_destroy(tsd, tctx);
- else
- malloc_mutex_unlock(tsd_tsdn(tsd), tctx->tdata->lock);
-}
-
-void
-bt_init(prof_bt_t *bt, void **vec)
-{
-
- cassert(config_prof);
-
- bt->vec = vec;
- bt->len = 0;
-}
-
-JEMALLOC_INLINE_C void
-prof_enter(tsd_t *tsd, prof_tdata_t *tdata)
-{
-
- cassert(config_prof);
- assert(tdata == prof_tdata_get(tsd, false));
-
- if (tdata != NULL) {
- assert(!tdata->enq);
- tdata->enq = true;
- }
-
- malloc_mutex_lock(tsd_tsdn(tsd), &bt2gctx_mtx);
-}
-
-JEMALLOC_INLINE_C void
-prof_leave(tsd_t *tsd, prof_tdata_t *tdata)
-{
-
- cassert(config_prof);
- assert(tdata == prof_tdata_get(tsd, false));
-
- malloc_mutex_unlock(tsd_tsdn(tsd), &bt2gctx_mtx);
-
- if (tdata != NULL) {
- bool idump, gdump;
-
- assert(tdata->enq);
- tdata->enq = false;
- idump = tdata->enq_idump;
- tdata->enq_idump = false;
- gdump = tdata->enq_gdump;
- tdata->enq_gdump = false;
-
- if (idump)
- prof_idump(tsd_tsdn(tsd));
- if (gdump)
- prof_gdump(tsd_tsdn(tsd));
- }
-}
-
-#ifdef JEMALLOC_PROF_LIBUNWIND
-void
-prof_backtrace(prof_bt_t *bt)
-{
- int nframes;
-
- cassert(config_prof);
- assert(bt->len == 0);
- assert(bt->vec != NULL);
-
- nframes = unw_backtrace(bt->vec, PROF_BT_MAX);
- if (nframes <= 0)
- return;
- bt->len = nframes;
-}
-#elif (defined(JEMALLOC_PROF_LIBGCC))
-static _Unwind_Reason_Code
-prof_unwind_init_callback(struct _Unwind_Context *context, void *arg)
-{
-
- cassert(config_prof);
-
- return (_URC_NO_REASON);
-}
-
-static _Unwind_Reason_Code
-prof_unwind_callback(struct _Unwind_Context *context, void *arg)
-{
- prof_unwind_data_t *data = (prof_unwind_data_t *)arg;
- void *ip;
-
- cassert(config_prof);
-
- ip = (void *)_Unwind_GetIP(context);
- if (ip == NULL)
- return (_URC_END_OF_STACK);
- data->bt->vec[data->bt->len] = ip;
- data->bt->len++;
- if (data->bt->len == data->max)
- return (_URC_END_OF_STACK);
-
- return (_URC_NO_REASON);
-}
-
-void
-prof_backtrace(prof_bt_t *bt)
-{
- prof_unwind_data_t data = {bt, PROF_BT_MAX};
-
- cassert(config_prof);
-
- _Unwind_Backtrace(prof_unwind_callback, &data);
-}
-#elif (defined(JEMALLOC_PROF_GCC))
-void
-prof_backtrace(prof_bt_t *bt)
-{
-#define BT_FRAME(i) \
- if ((i) < PROF_BT_MAX) { \
- void *p; \
- if (__builtin_frame_address(i) == 0) \
- return; \
- p = __builtin_return_address(i); \
- if (p == NULL) \
- return; \
- bt->vec[(i)] = p; \
- bt->len = (i) + 1; \
- } else \
- return;
-
- cassert(config_prof);
-
- BT_FRAME(0)
- BT_FRAME(1)
- BT_FRAME(2)
- BT_FRAME(3)
- BT_FRAME(4)
- BT_FRAME(5)
- BT_FRAME(6)
- BT_FRAME(7)
- BT_FRAME(8)
- BT_FRAME(9)
-
- BT_FRAME(10)
- BT_FRAME(11)
- BT_FRAME(12)
- BT_FRAME(13)
- BT_FRAME(14)
- BT_FRAME(15)
- BT_FRAME(16)
- BT_FRAME(17)
- BT_FRAME(18)
- BT_FRAME(19)
-
- BT_FRAME(20)
- BT_FRAME(21)
- BT_FRAME(22)
- BT_FRAME(23)
- BT_FRAME(24)
- BT_FRAME(25)
- BT_FRAME(26)
- BT_FRAME(27)
- BT_FRAME(28)
- BT_FRAME(29)
-
- BT_FRAME(30)
- BT_FRAME(31)
- BT_FRAME(32)
- BT_FRAME(33)
- BT_FRAME(34)
- BT_FRAME(35)
- BT_FRAME(36)
- BT_FRAME(37)
- BT_FRAME(38)
- BT_FRAME(39)
-
- BT_FRAME(40)
- BT_FRAME(41)
- BT_FRAME(42)
- BT_FRAME(43)
- BT_FRAME(44)
- BT_FRAME(45)
- BT_FRAME(46)
- BT_FRAME(47)
- BT_FRAME(48)
- BT_FRAME(49)
-
- BT_FRAME(50)
- BT_FRAME(51)
- BT_FRAME(52)
- BT_FRAME(53)
- BT_FRAME(54)
- BT_FRAME(55)
- BT_FRAME(56)
- BT_FRAME(57)
- BT_FRAME(58)
- BT_FRAME(59)
-
- BT_FRAME(60)
- BT_FRAME(61)
- BT_FRAME(62)
- BT_FRAME(63)
- BT_FRAME(64)
- BT_FRAME(65)
- BT_FRAME(66)
- BT_FRAME(67)
- BT_FRAME(68)
- BT_FRAME(69)
-
- BT_FRAME(70)
- BT_FRAME(71)
- BT_FRAME(72)
- BT_FRAME(73)
- BT_FRAME(74)
- BT_FRAME(75)
- BT_FRAME(76)
- BT_FRAME(77)
- BT_FRAME(78)
- BT_FRAME(79)
-
- BT_FRAME(80)
- BT_FRAME(81)
- BT_FRAME(82)
- BT_FRAME(83)
- BT_FRAME(84)
- BT_FRAME(85)
- BT_FRAME(86)
- BT_FRAME(87)
- BT_FRAME(88)
- BT_FRAME(89)
-
- BT_FRAME(90)
- BT_FRAME(91)
- BT_FRAME(92)
- BT_FRAME(93)
- BT_FRAME(94)
- BT_FRAME(95)
- BT_FRAME(96)
- BT_FRAME(97)
- BT_FRAME(98)
- BT_FRAME(99)
-
- BT_FRAME(100)
- BT_FRAME(101)
- BT_FRAME(102)
- BT_FRAME(103)
- BT_FRAME(104)
- BT_FRAME(105)
- BT_FRAME(106)
- BT_FRAME(107)
- BT_FRAME(108)
- BT_FRAME(109)
-
- BT_FRAME(110)
- BT_FRAME(111)
- BT_FRAME(112)
- BT_FRAME(113)
- BT_FRAME(114)
- BT_FRAME(115)
- BT_FRAME(116)
- BT_FRAME(117)
- BT_FRAME(118)
- BT_FRAME(119)
-
- BT_FRAME(120)
- BT_FRAME(121)
- BT_FRAME(122)
- BT_FRAME(123)
- BT_FRAME(124)
- BT_FRAME(125)
- BT_FRAME(126)
- BT_FRAME(127)
-#undef BT_FRAME
-}
-#else
-void
-prof_backtrace(prof_bt_t *bt)
-{
-
- cassert(config_prof);
- not_reached();
-}
-#endif
-
-static malloc_mutex_t *
-prof_gctx_mutex_choose(void)
-{
- unsigned ngctxs = atomic_add_u(&cum_gctxs, 1);
-
- return (&gctx_locks[(ngctxs - 1) % PROF_NCTX_LOCKS]);
-}
-
-static malloc_mutex_t *
-prof_tdata_mutex_choose(uint64_t thr_uid)
-{
-
- return (&tdata_locks[thr_uid % PROF_NTDATA_LOCKS]);
-}
-
-static prof_gctx_t *
-prof_gctx_create(tsdn_t *tsdn, prof_bt_t *bt)
-{
- /*
- * Create a single allocation that has space for vec of length bt->len.
- */
- size_t size = offsetof(prof_gctx_t, vec) + (bt->len * sizeof(void *));
- prof_gctx_t *gctx = (prof_gctx_t *)iallocztm(tsdn, size,
- size2index(size), false, NULL, true, arena_get(TSDN_NULL, 0, true),
- true);
- if (gctx == NULL)
- return (NULL);
- gctx->lock = prof_gctx_mutex_choose();
- /*
- * Set nlimbo to 1, in order to avoid a race condition with
- * prof_tctx_destroy()/prof_gctx_try_destroy().
- */
- gctx->nlimbo = 1;
- tctx_tree_new(&gctx->tctxs);
- /* Duplicate bt. */
- memcpy(gctx->vec, bt->vec, bt->len * sizeof(void *));
- gctx->bt.vec = gctx->vec;
- gctx->bt.len = bt->len;
- return (gctx);
-}
-
-static void
-prof_gctx_try_destroy(tsd_t *tsd, prof_tdata_t *tdata_self, prof_gctx_t *gctx,
- prof_tdata_t *tdata)
-{
-
- cassert(config_prof);
-
- /*
- * Check that gctx is still unused by any thread cache before destroying
- * it. prof_lookup() increments gctx->nlimbo in order to avoid a race
- * condition with this function, as does prof_tctx_destroy() in order to
- * avoid a race between the main body of prof_tctx_destroy() and entry
- * into this function.
- */
- prof_enter(tsd, tdata_self);
- malloc_mutex_lock(tsd_tsdn(tsd), gctx->lock);
- assert(gctx->nlimbo != 0);
- if (tctx_tree_empty(&gctx->tctxs) && gctx->nlimbo == 1) {
- /* Remove gctx from bt2gctx. */
- if (ckh_remove(tsd, &bt2gctx, &gctx->bt, NULL, NULL))
- not_reached();
- prof_leave(tsd, tdata_self);
- /* Destroy gctx. */
- malloc_mutex_unlock(tsd_tsdn(tsd), gctx->lock);
- idalloctm(tsd_tsdn(tsd), gctx, NULL, true, true);
- } else {
- /*
- * Compensate for increment in prof_tctx_destroy() or
- * prof_lookup().
- */
- gctx->nlimbo--;
- malloc_mutex_unlock(tsd_tsdn(tsd), gctx->lock);
- prof_leave(tsd, tdata_self);
- }
-}
-
-static bool
-prof_tctx_should_destroy(tsdn_t *tsdn, prof_tctx_t *tctx)
-{
-
- malloc_mutex_assert_owner(tsdn, tctx->tdata->lock);
-
- if (opt_prof_accum)
- return (false);
- if (tctx->cnts.curobjs != 0)
- return (false);
- if (tctx->prepared)
- return (false);
- return (true);
-}
-
-static bool
-prof_gctx_should_destroy(prof_gctx_t *gctx)
-{
-
- if (opt_prof_accum)
- return (false);
- if (!tctx_tree_empty(&gctx->tctxs))
- return (false);
- if (gctx->nlimbo != 0)
- return (false);
- return (true);
-}
-
-static void
-prof_tctx_destroy(tsd_t *tsd, prof_tctx_t *tctx)
-{
- prof_tdata_t *tdata = tctx->tdata;
- prof_gctx_t *gctx = tctx->gctx;
- bool destroy_tdata, destroy_tctx, destroy_gctx;
-
- malloc_mutex_assert_owner(tsd_tsdn(tsd), tctx->tdata->lock);
-
- assert(tctx->cnts.curobjs == 0);
- assert(tctx->cnts.curbytes == 0);
- assert(!opt_prof_accum);
- assert(tctx->cnts.accumobjs == 0);
- assert(tctx->cnts.accumbytes == 0);
-
- ckh_remove(tsd, &tdata->bt2tctx, &gctx->bt, NULL, NULL);
- destroy_tdata = prof_tdata_should_destroy(tsd_tsdn(tsd), tdata, false);
- malloc_mutex_unlock(tsd_tsdn(tsd), tdata->lock);
-
- malloc_mutex_lock(tsd_tsdn(tsd), gctx->lock);
- switch (tctx->state) {
- case prof_tctx_state_nominal:
- tctx_tree_remove(&gctx->tctxs, tctx);
- destroy_tctx = true;
- if (prof_gctx_should_destroy(gctx)) {
- /*
- * Increment gctx->nlimbo in order to keep another
- * thread from winning the race to destroy gctx while
- * this one has gctx->lock dropped. Without this, it
- * would be possible for another thread to:
- *
- * 1) Sample an allocation associated with gctx.
- * 2) Deallocate the sampled object.
- * 3) Successfully prof_gctx_try_destroy(gctx).
- *
- * The result would be that gctx no longer exists by the
- * time this thread accesses it in
- * prof_gctx_try_destroy().
- */
- gctx->nlimbo++;
- destroy_gctx = true;
- } else
- destroy_gctx = false;
- break;
- case prof_tctx_state_dumping:
- /*
- * A dumping thread needs tctx to remain valid until dumping
- * has finished. Change state such that the dumping thread will
- * complete destruction during a late dump iteration phase.
- */
- tctx->state = prof_tctx_state_purgatory;
- destroy_tctx = false;
- destroy_gctx = false;
- break;
- default:
- not_reached();
- destroy_tctx = false;
- destroy_gctx = false;
- }
- malloc_mutex_unlock(tsd_tsdn(tsd), gctx->lock);
- if (destroy_gctx) {
- prof_gctx_try_destroy(tsd, prof_tdata_get(tsd, false), gctx,
- tdata);
- }
-
- malloc_mutex_assert_not_owner(tsd_tsdn(tsd), tctx->tdata->lock);
-
- if (destroy_tdata)
- prof_tdata_destroy(tsd, tdata, false);
-
- if (destroy_tctx)
- idalloctm(tsd_tsdn(tsd), tctx, NULL, true, true);
-}
-
-static bool
-prof_lookup_global(tsd_t *tsd, prof_bt_t *bt, prof_tdata_t *tdata,
- void **p_btkey, prof_gctx_t **p_gctx, bool *p_new_gctx)
-{
- union {
- prof_gctx_t *p;
- void *v;
- } gctx;
- union {
- prof_bt_t *p;
- void *v;
- } btkey;
- bool new_gctx;
-
- prof_enter(tsd, tdata);
- if (ckh_search(&bt2gctx, bt, &btkey.v, &gctx.v)) {
- /* bt has never been seen before. Insert it. */
- gctx.p = prof_gctx_create(tsd_tsdn(tsd), bt);
- if (gctx.v == NULL) {
- prof_leave(tsd, tdata);
- return (true);
- }
- btkey.p = &gctx.p->bt;
- if (ckh_insert(tsd, &bt2gctx, btkey.v, gctx.v)) {
- /* OOM. */
- prof_leave(tsd, tdata);
- idalloctm(tsd_tsdn(tsd), gctx.v, NULL, true, true);
- return (true);
- }
- new_gctx = true;
- } else {
- /*
- * Increment nlimbo, in order to avoid a race condition with
- * prof_tctx_destroy()/prof_gctx_try_destroy().
- */
- malloc_mutex_lock(tsd_tsdn(tsd), gctx.p->lock);
- gctx.p->nlimbo++;
- malloc_mutex_unlock(tsd_tsdn(tsd), gctx.p->lock);
- new_gctx = false;
- }
- prof_leave(tsd, tdata);
-
- *p_btkey = btkey.v;
- *p_gctx = gctx.p;
- *p_new_gctx = new_gctx;
- return (false);
-}
-
-prof_tctx_t *
-prof_lookup(tsd_t *tsd, prof_bt_t *bt)
-{
- union {
- prof_tctx_t *p;
- void *v;
- } ret;
- prof_tdata_t *tdata;
- bool not_found;
-
- cassert(config_prof);
-
- tdata = prof_tdata_get(tsd, false);
- if (tdata == NULL)
- return (NULL);
-
- malloc_mutex_lock(tsd_tsdn(tsd), tdata->lock);
- not_found = ckh_search(&tdata->bt2tctx, bt, NULL, &ret.v);
- if (!not_found) /* Note double negative! */
- ret.p->prepared = true;
- malloc_mutex_unlock(tsd_tsdn(tsd), tdata->lock);
- if (not_found) {
- void *btkey;
- prof_gctx_t *gctx;
- bool new_gctx, error;
-
- /*
- * This thread's cache lacks bt. Look for it in the global
- * cache.
- */
- if (prof_lookup_global(tsd, bt, tdata, &btkey, &gctx,
- &new_gctx))
- return (NULL);
-
- /* Link a prof_tctx_t into gctx for this thread. */
- ret.v = iallocztm(tsd_tsdn(tsd), sizeof(prof_tctx_t),
- size2index(sizeof(prof_tctx_t)), false, NULL, true,
- arena_ichoose(tsd, NULL), true);
- if (ret.p == NULL) {
- if (new_gctx)
- prof_gctx_try_destroy(tsd, tdata, gctx, tdata);
- return (NULL);
- }
- ret.p->tdata = tdata;
- ret.p->thr_uid = tdata->thr_uid;
- ret.p->thr_discrim = tdata->thr_discrim;
- memset(&ret.p->cnts, 0, sizeof(prof_cnt_t));
- ret.p->gctx = gctx;
- ret.p->tctx_uid = tdata->tctx_uid_next++;
- ret.p->prepared = true;
- ret.p->state = prof_tctx_state_initializing;
- malloc_mutex_lock(tsd_tsdn(tsd), tdata->lock);
- error = ckh_insert(tsd, &tdata->bt2tctx, btkey, ret.v);
- malloc_mutex_unlock(tsd_tsdn(tsd), tdata->lock);
- if (error) {
- if (new_gctx)
- prof_gctx_try_destroy(tsd, tdata, gctx, tdata);
- idalloctm(tsd_tsdn(tsd), ret.v, NULL, true, true);
- return (NULL);
- }
- malloc_mutex_lock(tsd_tsdn(tsd), gctx->lock);
- ret.p->state = prof_tctx_state_nominal;
- tctx_tree_insert(&gctx->tctxs, ret.p);
- gctx->nlimbo--;
- malloc_mutex_unlock(tsd_tsdn(tsd), gctx->lock);
- }
-
- return (ret.p);
-}
-
-/*
- * The bodies of this function and prof_leakcheck() are compiled out unless heap
- * profiling is enabled, so that it is possible to compile jemalloc with
- * floating point support completely disabled. Avoiding floating point code is
- * important on memory-constrained systems, but it also enables a workaround for
- * versions of glibc that don't properly save/restore floating point registers
- * during dynamic lazy symbol loading (which internally calls into whatever
- * malloc implementation happens to be integrated into the application). Note
- * that some compilers (e.g. gcc 4.8) may use floating point registers for fast
- * memory moves, so jemalloc must be compiled with such optimizations disabled
- * (e.g.
- * -mno-sse) in order for the workaround to be complete.
- */
-void
-prof_sample_threshold_update(prof_tdata_t *tdata)
-{
-#ifdef JEMALLOC_PROF
- uint64_t r;
- double u;
-
- if (!config_prof)
- return;
-
- if (lg_prof_sample == 0) {
- tdata->bytes_until_sample = 0;
- return;
- }
-
- /*
- * Compute sample interval as a geometrically distributed random
- * variable with mean (2^lg_prof_sample).
- *
- * __ __
- * | log(u) | 1
- * tdata->bytes_until_sample = | -------- |, where p = ---------------
- * | log(1-p) | lg_prof_sample
- * 2
- *
- * For more information on the math, see:
- *
- * Non-Uniform Random Variate Generation
- * Luc Devroye
- * Springer-Verlag, New York, 1986
- * pp 500
- * (http://luc.devroye.org/rnbookindex.html)
- */
- r = prng_lg_range_u64(&tdata->prng_state, 53);
- u = (double)r * (1.0/9007199254740992.0L);
- tdata->bytes_until_sample = (uint64_t)(log(u) /
- log(1.0 - (1.0 / (double)((uint64_t)1U << lg_prof_sample))))
- + (uint64_t)1U;
-#endif
-}
-
-#ifdef JEMALLOC_JET
-static prof_tdata_t *
-prof_tdata_count_iter(prof_tdata_tree_t *tdatas, prof_tdata_t *tdata, void *arg)
-{
- size_t *tdata_count = (size_t *)arg;
-
- (*tdata_count)++;
-
- return (NULL);
-}
-
-size_t
-prof_tdata_count(void)
-{
- size_t tdata_count = 0;
- tsdn_t *tsdn;
-
- tsdn = tsdn_fetch();
- malloc_mutex_lock(tsdn, &tdatas_mtx);
- tdata_tree_iter(&tdatas, NULL, prof_tdata_count_iter,
- (void *)&tdata_count);
- malloc_mutex_unlock(tsdn, &tdatas_mtx);
-
- return (tdata_count);
-}
-#endif
-
-#ifdef JEMALLOC_JET
-size_t
-prof_bt_count(void)
-{
- size_t bt_count;
- tsd_t *tsd;
- prof_tdata_t *tdata;
-
- tsd = tsd_fetch();
- tdata = prof_tdata_get(tsd, false);
- if (tdata == NULL)
- return (0);
-
- malloc_mutex_lock(tsd_tsdn(tsd), &bt2gctx_mtx);
- bt_count = ckh_count(&bt2gctx);
- malloc_mutex_unlock(tsd_tsdn(tsd), &bt2gctx_mtx);
-
- return (bt_count);
-}
-#endif
-
-#ifdef JEMALLOC_JET
-#undef prof_dump_open
-#define prof_dump_open JEMALLOC_N(prof_dump_open_impl)
-#endif
-static int
-prof_dump_open(bool propagate_err, const char *filename)
-{
- int fd;
-
- fd = creat(filename, 0644);
- if (fd == -1 && !propagate_err) {
- malloc_printf("<jemalloc>: creat(\"%s\"), 0644) failed\n",
- filename);
- if (opt_abort)
- abort();
- }
-
- return (fd);
-}
-#ifdef JEMALLOC_JET
-#undef prof_dump_open
-#define prof_dump_open JEMALLOC_N(prof_dump_open)
-prof_dump_open_t *prof_dump_open = JEMALLOC_N(prof_dump_open_impl);
-#endif
-
-static bool
-prof_dump_flush(bool propagate_err)
-{
- bool ret = false;
- ssize_t err;
-
- cassert(config_prof);
-
- err = write(prof_dump_fd, prof_dump_buf, prof_dump_buf_end);
- if (err == -1) {
- if (!propagate_err) {
- malloc_write("<jemalloc>: write() failed during heap "
- "profile flush\n");
- if (opt_abort)
- abort();
- }
- ret = true;
- }
- prof_dump_buf_end = 0;
-
- return (ret);
-}
-
-static bool
-prof_dump_close(bool propagate_err)
-{
- bool ret;
-
- assert(prof_dump_fd != -1);
- ret = prof_dump_flush(propagate_err);
- close(prof_dump_fd);
- prof_dump_fd = -1;
-
- return (ret);
-}
-
-static bool
-prof_dump_write(bool propagate_err, const char *s)
-{
- size_t i, slen, n;
-
- cassert(config_prof);
-
- i = 0;
- slen = strlen(s);
- while (i < slen) {
- /* Flush the buffer if it is full. */
- if (prof_dump_buf_end == PROF_DUMP_BUFSIZE)
- if (prof_dump_flush(propagate_err) && propagate_err)
- return (true);
-
- if (prof_dump_buf_end + slen <= PROF_DUMP_BUFSIZE) {
- /* Finish writing. */
- n = slen - i;
- } else {
- /* Write as much of s as will fit. */
- n = PROF_DUMP_BUFSIZE - prof_dump_buf_end;
- }
- memcpy(&prof_dump_buf[prof_dump_buf_end], &s[i], n);
- prof_dump_buf_end += n;
- i += n;
- }
-
- return (false);
-}
-
-JEMALLOC_FORMAT_PRINTF(2, 3)
-static bool
-prof_dump_printf(bool propagate_err, const char *format, ...)
-{
- bool ret;
- va_list ap;
- char buf[PROF_PRINTF_BUFSIZE];
-
- va_start(ap, format);
- malloc_vsnprintf(buf, sizeof(buf), format, ap);
- va_end(ap);
- ret = prof_dump_write(propagate_err, buf);
-
- return (ret);
-}
-
-static void
-prof_tctx_merge_tdata(tsdn_t *tsdn, prof_tctx_t *tctx, prof_tdata_t *tdata)
-{
-
- malloc_mutex_assert_owner(tsdn, tctx->tdata->lock);
-
- malloc_mutex_lock(tsdn, tctx->gctx->lock);
-
- switch (tctx->state) {
- case prof_tctx_state_initializing:
- malloc_mutex_unlock(tsdn, tctx->gctx->lock);
- return;
- case prof_tctx_state_nominal:
- tctx->state = prof_tctx_state_dumping;
- malloc_mutex_unlock(tsdn, tctx->gctx->lock);
-
- memcpy(&tctx->dump_cnts, &tctx->cnts, sizeof(prof_cnt_t));
-
- tdata->cnt_summed.curobjs += tctx->dump_cnts.curobjs;
- tdata->cnt_summed.curbytes += tctx->dump_cnts.curbytes;
- if (opt_prof_accum) {
- tdata->cnt_summed.accumobjs +=
- tctx->dump_cnts.accumobjs;
- tdata->cnt_summed.accumbytes +=
- tctx->dump_cnts.accumbytes;
- }
- break;
- case prof_tctx_state_dumping:
- case prof_tctx_state_purgatory:
- not_reached();
- }
-}
-
-static void
-prof_tctx_merge_gctx(tsdn_t *tsdn, prof_tctx_t *tctx, prof_gctx_t *gctx)
-{
-
- malloc_mutex_assert_owner(tsdn, gctx->lock);
-
- gctx->cnt_summed.curobjs += tctx->dump_cnts.curobjs;
- gctx->cnt_summed.curbytes += tctx->dump_cnts.curbytes;
- if (opt_prof_accum) {
- gctx->cnt_summed.accumobjs += tctx->dump_cnts.accumobjs;
- gctx->cnt_summed.accumbytes += tctx->dump_cnts.accumbytes;
- }
-}
-
-static prof_tctx_t *
-prof_tctx_merge_iter(prof_tctx_tree_t *tctxs, prof_tctx_t *tctx, void *arg)
-{
- tsdn_t *tsdn = (tsdn_t *)arg;
-
- malloc_mutex_assert_owner(tsdn, tctx->gctx->lock);
-
- switch (tctx->state) {
- case prof_tctx_state_nominal:
- /* New since dumping started; ignore. */
- break;
- case prof_tctx_state_dumping:
- case prof_tctx_state_purgatory:
- prof_tctx_merge_gctx(tsdn, tctx, tctx->gctx);
- break;
- default:
- not_reached();
- }
-
- return (NULL);
-}
-
-struct prof_tctx_dump_iter_arg_s {
- tsdn_t *tsdn;
- bool propagate_err;
-};
-
-static prof_tctx_t *
-prof_tctx_dump_iter(prof_tctx_tree_t *tctxs, prof_tctx_t *tctx, void *opaque)
-{
- struct prof_tctx_dump_iter_arg_s *arg =
- (struct prof_tctx_dump_iter_arg_s *)opaque;
-
- malloc_mutex_assert_owner(arg->tsdn, tctx->gctx->lock);
-
- switch (tctx->state) {
- case prof_tctx_state_initializing:
- case prof_tctx_state_nominal:
- /* Not captured by this dump. */
- break;
- case prof_tctx_state_dumping:
- case prof_tctx_state_purgatory:
- if (prof_dump_printf(arg->propagate_err,
- " t%"FMTu64": %"FMTu64": %"FMTu64" [%"FMTu64": "
- "%"FMTu64"]\n", tctx->thr_uid, tctx->dump_cnts.curobjs,
- tctx->dump_cnts.curbytes, tctx->dump_cnts.accumobjs,
- tctx->dump_cnts.accumbytes))
- return (tctx);
- break;
- default:
- not_reached();
- }
- return (NULL);
-}
-
-static prof_tctx_t *
-prof_tctx_finish_iter(prof_tctx_tree_t *tctxs, prof_tctx_t *tctx, void *arg)
-{
- tsdn_t *tsdn = (tsdn_t *)arg;
- prof_tctx_t *ret;
-
- malloc_mutex_assert_owner(tsdn, tctx->gctx->lock);
-
- switch (tctx->state) {
- case prof_tctx_state_nominal:
- /* New since dumping started; ignore. */
- break;
- case prof_tctx_state_dumping:
- tctx->state = prof_tctx_state_nominal;
- break;
- case prof_tctx_state_purgatory:
- ret = tctx;
- goto label_return;
- default:
- not_reached();
- }
-
- ret = NULL;
-label_return:
- return (ret);
-}
-
-static void
-prof_dump_gctx_prep(tsdn_t *tsdn, prof_gctx_t *gctx, prof_gctx_tree_t *gctxs)
-{
-
- cassert(config_prof);
-
- malloc_mutex_lock(tsdn, gctx->lock);
-
- /*
- * Increment nlimbo so that gctx won't go away before dump.
- * Additionally, link gctx into the dump list so that it is included in
- * prof_dump()'s second pass.
- */
- gctx->nlimbo++;
- gctx_tree_insert(gctxs, gctx);
-
- memset(&gctx->cnt_summed, 0, sizeof(prof_cnt_t));
-
- malloc_mutex_unlock(tsdn, gctx->lock);
-}
-
-struct prof_gctx_merge_iter_arg_s {
- tsdn_t *tsdn;
- size_t leak_ngctx;
-};
-
-static prof_gctx_t *
-prof_gctx_merge_iter(prof_gctx_tree_t *gctxs, prof_gctx_t *gctx, void *opaque)
-{
- struct prof_gctx_merge_iter_arg_s *arg =
- (struct prof_gctx_merge_iter_arg_s *)opaque;
-
- malloc_mutex_lock(arg->tsdn, gctx->lock);
- tctx_tree_iter(&gctx->tctxs, NULL, prof_tctx_merge_iter,
- (void *)arg->tsdn);
- if (gctx->cnt_summed.curobjs != 0)
- arg->leak_ngctx++;
- malloc_mutex_unlock(arg->tsdn, gctx->lock);
-
- return (NULL);
-}
-
-static void
-prof_gctx_finish(tsd_t *tsd, prof_gctx_tree_t *gctxs)
-{
- prof_tdata_t *tdata = prof_tdata_get(tsd, false);
- prof_gctx_t *gctx;
-
- /*
- * Standard tree iteration won't work here, because as soon as we
- * decrement gctx->nlimbo and unlock gctx, another thread can
- * concurrently destroy it, which will corrupt the tree. Therefore,
- * tear down the tree one node at a time during iteration.
- */
- while ((gctx = gctx_tree_first(gctxs)) != NULL) {
- gctx_tree_remove(gctxs, gctx);
- malloc_mutex_lock(tsd_tsdn(tsd), gctx->lock);
- {
- prof_tctx_t *next;
-
- next = NULL;
- do {
- prof_tctx_t *to_destroy =
- tctx_tree_iter(&gctx->tctxs, next,
- prof_tctx_finish_iter,
- (void *)tsd_tsdn(tsd));
- if (to_destroy != NULL) {
- next = tctx_tree_next(&gctx->tctxs,
- to_destroy);
- tctx_tree_remove(&gctx->tctxs,
- to_destroy);
- idalloctm(tsd_tsdn(tsd), to_destroy,
- NULL, true, true);
- } else
- next = NULL;
- } while (next != NULL);
- }
- gctx->nlimbo--;
- if (prof_gctx_should_destroy(gctx)) {
- gctx->nlimbo++;
- malloc_mutex_unlock(tsd_tsdn(tsd), gctx->lock);
- prof_gctx_try_destroy(tsd, tdata, gctx, tdata);
- } else
- malloc_mutex_unlock(tsd_tsdn(tsd), gctx->lock);
- }
-}
-
-struct prof_tdata_merge_iter_arg_s {
- tsdn_t *tsdn;
- prof_cnt_t cnt_all;
-};
-
-static prof_tdata_t *
-prof_tdata_merge_iter(prof_tdata_tree_t *tdatas, prof_tdata_t *tdata,
- void *opaque)
-{
- struct prof_tdata_merge_iter_arg_s *arg =
- (struct prof_tdata_merge_iter_arg_s *)opaque;
-
- malloc_mutex_lock(arg->tsdn, tdata->lock);
- if (!tdata->expired) {
- size_t tabind;
- union {
- prof_tctx_t *p;
- void *v;
- } tctx;
-
- tdata->dumping = true;
- memset(&tdata->cnt_summed, 0, sizeof(prof_cnt_t));
- for (tabind = 0; !ckh_iter(&tdata->bt2tctx, &tabind, NULL,
- &tctx.v);)
- prof_tctx_merge_tdata(arg->tsdn, tctx.p, tdata);
-
- arg->cnt_all.curobjs += tdata->cnt_summed.curobjs;
- arg->cnt_all.curbytes += tdata->cnt_summed.curbytes;
- if (opt_prof_accum) {
- arg->cnt_all.accumobjs += tdata->cnt_summed.accumobjs;
- arg->cnt_all.accumbytes += tdata->cnt_summed.accumbytes;
- }
- } else
- tdata->dumping = false;
- malloc_mutex_unlock(arg->tsdn, tdata->lock);
-
- return (NULL);
-}
-
-static prof_tdata_t *
-prof_tdata_dump_iter(prof_tdata_tree_t *tdatas, prof_tdata_t *tdata, void *arg)
-{
- bool propagate_err = *(bool *)arg;
-
- if (!tdata->dumping)
- return (NULL);
-
- if (prof_dump_printf(propagate_err,
- " t%"FMTu64": %"FMTu64": %"FMTu64" [%"FMTu64": %"FMTu64"]%s%s\n",
- tdata->thr_uid, tdata->cnt_summed.curobjs,
- tdata->cnt_summed.curbytes, tdata->cnt_summed.accumobjs,
- tdata->cnt_summed.accumbytes,
- (tdata->thread_name != NULL) ? " " : "",
- (tdata->thread_name != NULL) ? tdata->thread_name : ""))
- return (tdata);
- return (NULL);
-}
-
-#ifdef JEMALLOC_JET
-#undef prof_dump_header
-#define prof_dump_header JEMALLOC_N(prof_dump_header_impl)
-#endif
-static bool
-prof_dump_header(tsdn_t *tsdn, bool propagate_err, const prof_cnt_t *cnt_all)
-{
- bool ret;
-
- if (prof_dump_printf(propagate_err,
- "heap_v2/%"FMTu64"\n"
- " t*: %"FMTu64": %"FMTu64" [%"FMTu64": %"FMTu64"]\n",
- ((uint64_t)1U << lg_prof_sample), cnt_all->curobjs,
- cnt_all->curbytes, cnt_all->accumobjs, cnt_all->accumbytes))
- return (true);
-
- malloc_mutex_lock(tsdn, &tdatas_mtx);
- ret = (tdata_tree_iter(&tdatas, NULL, prof_tdata_dump_iter,
- (void *)&propagate_err) != NULL);
- malloc_mutex_unlock(tsdn, &tdatas_mtx);
- return (ret);
-}
-#ifdef JEMALLOC_JET
-#undef prof_dump_header
-#define prof_dump_header JEMALLOC_N(prof_dump_header)
-prof_dump_header_t *prof_dump_header = JEMALLOC_N(prof_dump_header_impl);
-#endif
-
-static bool
-prof_dump_gctx(tsdn_t *tsdn, bool propagate_err, prof_gctx_t *gctx,
- const prof_bt_t *bt, prof_gctx_tree_t *gctxs)
-{
- bool ret;
- unsigned i;
- struct prof_tctx_dump_iter_arg_s prof_tctx_dump_iter_arg;
-
- cassert(config_prof);
- malloc_mutex_assert_owner(tsdn, gctx->lock);
-
- /* Avoid dumping such gctx's that have no useful data. */
- if ((!opt_prof_accum && gctx->cnt_summed.curobjs == 0) ||
- (opt_prof_accum && gctx->cnt_summed.accumobjs == 0)) {
- assert(gctx->cnt_summed.curobjs == 0);
- assert(gctx->cnt_summed.curbytes == 0);
- assert(gctx->cnt_summed.accumobjs == 0);
- assert(gctx->cnt_summed.accumbytes == 0);
- ret = false;
- goto label_return;
- }
-
- if (prof_dump_printf(propagate_err, "@")) {
- ret = true;
- goto label_return;
- }
- for (i = 0; i < bt->len; i++) {
- if (prof_dump_printf(propagate_err, " %#"FMTxPTR,
- (uintptr_t)bt->vec[i])) {
- ret = true;
- goto label_return;
- }
- }
-
- if (prof_dump_printf(propagate_err,
- "\n"
- " t*: %"FMTu64": %"FMTu64" [%"FMTu64": %"FMTu64"]\n",
- gctx->cnt_summed.curobjs, gctx->cnt_summed.curbytes,
- gctx->cnt_summed.accumobjs, gctx->cnt_summed.accumbytes)) {
- ret = true;
- goto label_return;
- }
-
- prof_tctx_dump_iter_arg.tsdn = tsdn;
- prof_tctx_dump_iter_arg.propagate_err = propagate_err;
- if (tctx_tree_iter(&gctx->tctxs, NULL, prof_tctx_dump_iter,
- (void *)&prof_tctx_dump_iter_arg) != NULL) {
- ret = true;
- goto label_return;
- }
-
- ret = false;
-label_return:
- return (ret);
-}
-
-#ifndef _WIN32
-JEMALLOC_FORMAT_PRINTF(1, 2)
-static int
-prof_open_maps(const char *format, ...)
-{
- int mfd;
- va_list ap;
- char filename[PATH_MAX + 1];
-
- va_start(ap, format);
- malloc_vsnprintf(filename, sizeof(filename), format, ap);
- va_end(ap);
- mfd = open(filename, O_RDONLY);
-
- return (mfd);
-}
-#endif
-
-static int
-prof_getpid(void)
-{
-
-#ifdef _WIN32
- return (GetCurrentProcessId());
-#else
- return (getpid());
-#endif
-}
-
-static bool
-prof_dump_maps(bool propagate_err)
-{
- bool ret;
- int mfd;
-
- cassert(config_prof);
-#ifdef __FreeBSD__
- mfd = prof_open_maps("/proc/curproc/map");
-#elif defined(_WIN32)
- mfd = -1; // Not implemented
-#else
- {
- int pid = prof_getpid();
-
- mfd = prof_open_maps("/proc/%d/task/%d/maps", pid, pid);
- if (mfd == -1)
- mfd = prof_open_maps("/proc/%d/maps", pid);
- }
-#endif
- if (mfd != -1) {
- ssize_t nread;
-
- if (prof_dump_write(propagate_err, "\nMAPPED_LIBRARIES:\n") &&
- propagate_err) {
- ret = true;
- goto label_return;
- }
- nread = 0;
- do {
- prof_dump_buf_end += nread;
- if (prof_dump_buf_end == PROF_DUMP_BUFSIZE) {
- /* Make space in prof_dump_buf before read(). */
- if (prof_dump_flush(propagate_err) &&
- propagate_err) {
- ret = true;
- goto label_return;
- }
- }
- nread = read(mfd, &prof_dump_buf[prof_dump_buf_end],
- PROF_DUMP_BUFSIZE - prof_dump_buf_end);
- } while (nread > 0);
- } else {
- ret = true;
- goto label_return;
- }
-
- ret = false;
-label_return:
- if (mfd != -1)
- close(mfd);
- return (ret);
-}
-
-/*
- * See prof_sample_threshold_update() comment for why the body of this function
- * is conditionally compiled.
- */
-static void
-prof_leakcheck(const prof_cnt_t *cnt_all, size_t leak_ngctx,
- const char *filename)
-{
-
-#ifdef JEMALLOC_PROF
- /*
- * Scaling is equivalent AdjustSamples() in jeprof, but the result may
- * differ slightly from what jeprof reports, because here we scale the
- * summary values, whereas jeprof scales each context individually and
- * reports the sums of the scaled values.
- */
- if (cnt_all->curbytes != 0) {
- double sample_period = (double)((uint64_t)1 << lg_prof_sample);
- double ratio = (((double)cnt_all->curbytes) /
- (double)cnt_all->curobjs) / sample_period;
- double scale_factor = 1.0 / (1.0 - exp(-ratio));
- uint64_t curbytes = (uint64_t)round(((double)cnt_all->curbytes)
- * scale_factor);
- uint64_t curobjs = (uint64_t)round(((double)cnt_all->curobjs) *
- scale_factor);
-
- malloc_printf("<jemalloc>: Leak approximation summary: ~%"FMTu64
- " byte%s, ~%"FMTu64" object%s, >= %zu context%s\n",
- curbytes, (curbytes != 1) ? "s" : "", curobjs, (curobjs !=
- 1) ? "s" : "", leak_ngctx, (leak_ngctx != 1) ? "s" : "");
- malloc_printf(
- "<jemalloc>: Run jeprof on \"%s\" for leak detail\n",
- filename);
- }
-#endif
-}
-
-struct prof_gctx_dump_iter_arg_s {
- tsdn_t *tsdn;
- bool propagate_err;
-};
-
-static prof_gctx_t *
-prof_gctx_dump_iter(prof_gctx_tree_t *gctxs, prof_gctx_t *gctx, void *opaque)
-{
- prof_gctx_t *ret;
- struct prof_gctx_dump_iter_arg_s *arg =
- (struct prof_gctx_dump_iter_arg_s *)opaque;
-
- malloc_mutex_lock(arg->tsdn, gctx->lock);
-
- if (prof_dump_gctx(arg->tsdn, arg->propagate_err, gctx, &gctx->bt,
- gctxs)) {
- ret = gctx;
- goto label_return;
- }
-
- ret = NULL;
-label_return:
- malloc_mutex_unlock(arg->tsdn, gctx->lock);
- return (ret);
-}
-
-static bool
-prof_dump(tsd_t *tsd, bool propagate_err, const char *filename, bool leakcheck)
-{
- prof_tdata_t *tdata;
- struct prof_tdata_merge_iter_arg_s prof_tdata_merge_iter_arg;
- size_t tabind;
- union {
- prof_gctx_t *p;
- void *v;
- } gctx;
- struct prof_gctx_merge_iter_arg_s prof_gctx_merge_iter_arg;
- struct prof_gctx_dump_iter_arg_s prof_gctx_dump_iter_arg;
- prof_gctx_tree_t gctxs;
-
- cassert(config_prof);
-
- tdata = prof_tdata_get(tsd, true);
- if (tdata == NULL)
- return (true);
-
- malloc_mutex_lock(tsd_tsdn(tsd), &prof_dump_mtx);
- prof_enter(tsd, tdata);
-
- /*
- * Put gctx's in limbo and clear their counters in preparation for
- * summing.
- */
- gctx_tree_new(&gctxs);
- for (tabind = 0; !ckh_iter(&bt2gctx, &tabind, NULL, &gctx.v);)
- prof_dump_gctx_prep(tsd_tsdn(tsd), gctx.p, &gctxs);
-
- /*
- * Iterate over tdatas, and for the non-expired ones snapshot their tctx
- * stats and merge them into the associated gctx's.
- */
- prof_tdata_merge_iter_arg.tsdn = tsd_tsdn(tsd);
- memset(&prof_tdata_merge_iter_arg.cnt_all, 0, sizeof(prof_cnt_t));
- malloc_mutex_lock(tsd_tsdn(tsd), &tdatas_mtx);
- tdata_tree_iter(&tdatas, NULL, prof_tdata_merge_iter,
- (void *)&prof_tdata_merge_iter_arg);
- malloc_mutex_unlock(tsd_tsdn(tsd), &tdatas_mtx);
-
- /* Merge tctx stats into gctx's. */
- prof_gctx_merge_iter_arg.tsdn = tsd_tsdn(tsd);
- prof_gctx_merge_iter_arg.leak_ngctx = 0;
- gctx_tree_iter(&gctxs, NULL, prof_gctx_merge_iter,
- (void *)&prof_gctx_merge_iter_arg);
-
- prof_leave(tsd, tdata);
-
- /* Create dump file. */
- if ((prof_dump_fd = prof_dump_open(propagate_err, filename)) == -1)
- goto label_open_close_error;
-
- /* Dump profile header. */
- if (prof_dump_header(tsd_tsdn(tsd), propagate_err,
- &prof_tdata_merge_iter_arg.cnt_all))
- goto label_write_error;
-
- /* Dump per gctx profile stats. */
- prof_gctx_dump_iter_arg.tsdn = tsd_tsdn(tsd);
- prof_gctx_dump_iter_arg.propagate_err = propagate_err;
- if (gctx_tree_iter(&gctxs, NULL, prof_gctx_dump_iter,
- (void *)&prof_gctx_dump_iter_arg) != NULL)
- goto label_write_error;
-
- /* Dump /proc/<pid>/maps if possible. */
- if (prof_dump_maps(propagate_err))
- goto label_write_error;
-
- if (prof_dump_close(propagate_err))
- goto label_open_close_error;
-
- prof_gctx_finish(tsd, &gctxs);
- malloc_mutex_unlock(tsd_tsdn(tsd), &prof_dump_mtx);
-
- if (leakcheck) {
- prof_leakcheck(&prof_tdata_merge_iter_arg.cnt_all,
- prof_gctx_merge_iter_arg.leak_ngctx, filename);
- }
- return (false);
-label_write_error:
- prof_dump_close(propagate_err);
-label_open_close_error:
- prof_gctx_finish(tsd, &gctxs);
- malloc_mutex_unlock(tsd_tsdn(tsd), &prof_dump_mtx);
- return (true);
-}
-
-#define DUMP_FILENAME_BUFSIZE (PATH_MAX + 1)
-#define VSEQ_INVALID UINT64_C(0xffffffffffffffff)
-static void
-prof_dump_filename(char *filename, char v, uint64_t vseq)
-{
-
- cassert(config_prof);
-
- if (vseq != VSEQ_INVALID) {
- /* "<prefix>.<pid>.<seq>.v<vseq>.heap" */
- malloc_snprintf(filename, DUMP_FILENAME_BUFSIZE,
- "%s.%d.%"FMTu64".%c%"FMTu64".heap",
- opt_prof_prefix, prof_getpid(), prof_dump_seq, v, vseq);
- } else {
- /* "<prefix>.<pid>.<seq>.<v>.heap" */
- malloc_snprintf(filename, DUMP_FILENAME_BUFSIZE,
- "%s.%d.%"FMTu64".%c.heap",
- opt_prof_prefix, prof_getpid(), prof_dump_seq, v);
- }
- prof_dump_seq++;
-}
-
-static void
-prof_fdump(void)
-{
- tsd_t *tsd;
- char filename[DUMP_FILENAME_BUFSIZE];
-
- cassert(config_prof);
- assert(opt_prof_final);
- assert(opt_prof_prefix[0] != '\0');
-
- if (!prof_booted)
- return;
- tsd = tsd_fetch();
-
- malloc_mutex_lock(tsd_tsdn(tsd), &prof_dump_seq_mtx);
- prof_dump_filename(filename, 'f', VSEQ_INVALID);
- malloc_mutex_unlock(tsd_tsdn(tsd), &prof_dump_seq_mtx);
- prof_dump(tsd, false, filename, opt_prof_leak);
-}
-
-void
-prof_idump(tsdn_t *tsdn)
-{
- tsd_t *tsd;
- prof_tdata_t *tdata;
-
- cassert(config_prof);
-
- if (!prof_booted || tsdn_null(tsdn))
- return;
- tsd = tsdn_tsd(tsdn);
- tdata = prof_tdata_get(tsd, false);
- if (tdata == NULL)
- return;
- if (tdata->enq) {
- tdata->enq_idump = true;
- return;
- }
-
- if (opt_prof_prefix[0] != '\0') {
- char filename[PATH_MAX + 1];
- malloc_mutex_lock(tsd_tsdn(tsd), &prof_dump_seq_mtx);
- prof_dump_filename(filename, 'i', prof_dump_iseq);
- prof_dump_iseq++;
- malloc_mutex_unlock(tsd_tsdn(tsd), &prof_dump_seq_mtx);
- prof_dump(tsd, false, filename, false);
- }
-}
-
-bool
-prof_mdump(tsd_t *tsd, const char *filename)
-{
- char filename_buf[DUMP_FILENAME_BUFSIZE];
-
- cassert(config_prof);
-
- if (!opt_prof || !prof_booted)
- return (true);
-
- if (filename == NULL) {
- /* No filename specified, so automatically generate one. */
- if (opt_prof_prefix[0] == '\0')
- return (true);
- malloc_mutex_lock(tsd_tsdn(tsd), &prof_dump_seq_mtx);
- prof_dump_filename(filename_buf, 'm', prof_dump_mseq);
- prof_dump_mseq++;
- malloc_mutex_unlock(tsd_tsdn(tsd), &prof_dump_seq_mtx);
- filename = filename_buf;
- }
- return (prof_dump(tsd, true, filename, false));
-}
-
-void
-prof_gdump(tsdn_t *tsdn)
-{
- tsd_t *tsd;
- prof_tdata_t *tdata;
-
- cassert(config_prof);
-
- if (!prof_booted || tsdn_null(tsdn))
- return;
- tsd = tsdn_tsd(tsdn);
- tdata = prof_tdata_get(tsd, false);
- if (tdata == NULL)
- return;
- if (tdata->enq) {
- tdata->enq_gdump = true;
- return;
- }
-
- if (opt_prof_prefix[0] != '\0') {
- char filename[DUMP_FILENAME_BUFSIZE];
- malloc_mutex_lock(tsdn, &prof_dump_seq_mtx);
- prof_dump_filename(filename, 'u', prof_dump_useq);
- prof_dump_useq++;
- malloc_mutex_unlock(tsdn, &prof_dump_seq_mtx);
- prof_dump(tsd, false, filename, false);
- }
-}
-
-static void
-prof_bt_hash(const void *key, size_t r_hash[2])
-{
- prof_bt_t *bt = (prof_bt_t *)key;
-
- cassert(config_prof);
-
- hash(bt->vec, bt->len * sizeof(void *), 0x94122f33U, r_hash);
-}
-
-static bool
-prof_bt_keycomp(const void *k1, const void *k2)
-{
- const prof_bt_t *bt1 = (prof_bt_t *)k1;
- const prof_bt_t *bt2 = (prof_bt_t *)k2;
-
- cassert(config_prof);
-
- if (bt1->len != bt2->len)
- return (false);
- return (memcmp(bt1->vec, bt2->vec, bt1->len * sizeof(void *)) == 0);
-}
-
-JEMALLOC_INLINE_C uint64_t
-prof_thr_uid_alloc(tsdn_t *tsdn)
-{
- uint64_t thr_uid;
-
- malloc_mutex_lock(tsdn, &next_thr_uid_mtx);
- thr_uid = next_thr_uid;
- next_thr_uid++;
- malloc_mutex_unlock(tsdn, &next_thr_uid_mtx);
-
- return (thr_uid);
-}
-
-static prof_tdata_t *
-prof_tdata_init_impl(tsd_t *tsd, uint64_t thr_uid, uint64_t thr_discrim,
- char *thread_name, bool active)
-{
- prof_tdata_t *tdata;
-
- cassert(config_prof);
-
- /* Initialize an empty cache for this thread. */
- tdata = (prof_tdata_t *)iallocztm(tsd_tsdn(tsd), sizeof(prof_tdata_t),
- size2index(sizeof(prof_tdata_t)), false, NULL, true,
- arena_get(TSDN_NULL, 0, true), true);
- if (tdata == NULL)
- return (NULL);
-
- tdata->lock = prof_tdata_mutex_choose(thr_uid);
- tdata->thr_uid = thr_uid;
- tdata->thr_discrim = thr_discrim;
- tdata->thread_name = thread_name;
- tdata->attached = true;
- tdata->expired = false;
- tdata->tctx_uid_next = 0;
-
- if (ckh_new(tsd, &tdata->bt2tctx, PROF_CKH_MINITEMS, prof_bt_hash,
- prof_bt_keycomp)) {
- idalloctm(tsd_tsdn(tsd), tdata, NULL, true, true);
- return (NULL);
- }
-
- tdata->prng_state = (uint64_t)(uintptr_t)tdata;
- prof_sample_threshold_update(tdata);
-
- tdata->enq = false;
- tdata->enq_idump = false;
- tdata->enq_gdump = false;
-
- tdata->dumping = false;
- tdata->active = active;
-
- malloc_mutex_lock(tsd_tsdn(tsd), &tdatas_mtx);
- tdata_tree_insert(&tdatas, tdata);
- malloc_mutex_unlock(tsd_tsdn(tsd), &tdatas_mtx);
-
- return (tdata);
-}
-
-prof_tdata_t *
-prof_tdata_init(tsd_t *tsd)
-{
-
- return (prof_tdata_init_impl(tsd, prof_thr_uid_alloc(tsd_tsdn(tsd)), 0,
- NULL, prof_thread_active_init_get(tsd_tsdn(tsd))));
-}
-
-static bool
-prof_tdata_should_destroy_unlocked(prof_tdata_t *tdata, bool even_if_attached)
-{
-
- if (tdata->attached && !even_if_attached)
- return (false);
- if (ckh_count(&tdata->bt2tctx) != 0)
- return (false);
- return (true);
-}
-
-static bool
-prof_tdata_should_destroy(tsdn_t *tsdn, prof_tdata_t *tdata,
- bool even_if_attached)
-{
-
- malloc_mutex_assert_owner(tsdn, tdata->lock);
-
- return (prof_tdata_should_destroy_unlocked(tdata, even_if_attached));
-}
-
-static void
-prof_tdata_destroy_locked(tsd_t *tsd, prof_tdata_t *tdata,
- bool even_if_attached)
-{
-
- malloc_mutex_assert_owner(tsd_tsdn(tsd), &tdatas_mtx);
-
- tdata_tree_remove(&tdatas, tdata);
-
- assert(prof_tdata_should_destroy_unlocked(tdata, even_if_attached));
-
- if (tdata->thread_name != NULL)
- idalloctm(tsd_tsdn(tsd), tdata->thread_name, NULL, true, true);
- ckh_delete(tsd, &tdata->bt2tctx);
- idalloctm(tsd_tsdn(tsd), tdata, NULL, true, true);
-}
-
-static void
-prof_tdata_destroy(tsd_t *tsd, prof_tdata_t *tdata, bool even_if_attached)
-{
-
- malloc_mutex_lock(tsd_tsdn(tsd), &tdatas_mtx);
- prof_tdata_destroy_locked(tsd, tdata, even_if_attached);
- malloc_mutex_unlock(tsd_tsdn(tsd), &tdatas_mtx);
-}
-
-static void
-prof_tdata_detach(tsd_t *tsd, prof_tdata_t *tdata)
-{
- bool destroy_tdata;
-
- malloc_mutex_lock(tsd_tsdn(tsd), tdata->lock);
- if (tdata->attached) {
- destroy_tdata = prof_tdata_should_destroy(tsd_tsdn(tsd), tdata,
- true);
- /*
- * Only detach if !destroy_tdata, because detaching would allow
- * another thread to win the race to destroy tdata.
- */
- if (!destroy_tdata)
- tdata->attached = false;
- tsd_prof_tdata_set(tsd, NULL);
- } else
- destroy_tdata = false;
- malloc_mutex_unlock(tsd_tsdn(tsd), tdata->lock);
- if (destroy_tdata)
- prof_tdata_destroy(tsd, tdata, true);
-}
-
-prof_tdata_t *
-prof_tdata_reinit(tsd_t *tsd, prof_tdata_t *tdata)
-{
- uint64_t thr_uid = tdata->thr_uid;
- uint64_t thr_discrim = tdata->thr_discrim + 1;
- char *thread_name = (tdata->thread_name != NULL) ?
- prof_thread_name_alloc(tsd_tsdn(tsd), tdata->thread_name) : NULL;
- bool active = tdata->active;
-
- prof_tdata_detach(tsd, tdata);
- return (prof_tdata_init_impl(tsd, thr_uid, thr_discrim, thread_name,
- active));
-}
-
-static bool
-prof_tdata_expire(tsdn_t *tsdn, prof_tdata_t *tdata)
-{
- bool destroy_tdata;
-
- malloc_mutex_lock(tsdn, tdata->lock);
- if (!tdata->expired) {
- tdata->expired = true;
- destroy_tdata = tdata->attached ? false :
- prof_tdata_should_destroy(tsdn, tdata, false);
- } else
- destroy_tdata = false;
- malloc_mutex_unlock(tsdn, tdata->lock);
-
- return (destroy_tdata);
-}
-
-static prof_tdata_t *
-prof_tdata_reset_iter(prof_tdata_tree_t *tdatas, prof_tdata_t *tdata, void *arg)
-{
- tsdn_t *tsdn = (tsdn_t *)arg;
-
- return (prof_tdata_expire(tsdn, tdata) ? tdata : NULL);
-}
-
-void
-prof_reset(tsd_t *tsd, size_t lg_sample)
-{
- prof_tdata_t *next;
-
- assert(lg_sample < (sizeof(uint64_t) << 3));
-
- malloc_mutex_lock(tsd_tsdn(tsd), &prof_dump_mtx);
- malloc_mutex_lock(tsd_tsdn(tsd), &tdatas_mtx);
-
- lg_prof_sample = lg_sample;
-
- next = NULL;
- do {
- prof_tdata_t *to_destroy = tdata_tree_iter(&tdatas, next,
- prof_tdata_reset_iter, (void *)tsd);
- if (to_destroy != NULL) {
- next = tdata_tree_next(&tdatas, to_destroy);
- prof_tdata_destroy_locked(tsd, to_destroy, false);
- } else
- next = NULL;
- } while (next != NULL);
-
- malloc_mutex_unlock(tsd_tsdn(tsd), &tdatas_mtx);
- malloc_mutex_unlock(tsd_tsdn(tsd), &prof_dump_mtx);
-}
-
-void
-prof_tdata_cleanup(tsd_t *tsd)
-{
- prof_tdata_t *tdata;
-
- if (!config_prof)
- return;
-
- tdata = tsd_prof_tdata_get(tsd);
- if (tdata != NULL)
- prof_tdata_detach(tsd, tdata);
-}
-
-bool
-prof_active_get(tsdn_t *tsdn)
-{
- bool prof_active_current;
-
- malloc_mutex_lock(tsdn, &prof_active_mtx);
- prof_active_current = prof_active;
- malloc_mutex_unlock(tsdn, &prof_active_mtx);
- return (prof_active_current);
-}
-
-bool
-prof_active_set(tsdn_t *tsdn, bool active)
-{
- bool prof_active_old;
-
- malloc_mutex_lock(tsdn, &prof_active_mtx);
- prof_active_old = prof_active;
- prof_active = active;
- malloc_mutex_unlock(tsdn, &prof_active_mtx);
- return (prof_active_old);
-}
-
-const char *
-prof_thread_name_get(tsd_t *tsd)
-{
- prof_tdata_t *tdata;
-
- tdata = prof_tdata_get(tsd, true);
- if (tdata == NULL)
- return ("");
- return (tdata->thread_name != NULL ? tdata->thread_name : "");
-}
-
-static char *
-prof_thread_name_alloc(tsdn_t *tsdn, const char *thread_name)
-{
- char *ret;
- size_t size;
-
- if (thread_name == NULL)
- return (NULL);
-
- size = strlen(thread_name) + 1;
- if (size == 1)
- return ("");
-
- ret = iallocztm(tsdn, size, size2index(size), false, NULL, true,
- arena_get(TSDN_NULL, 0, true), true);
- if (ret == NULL)
- return (NULL);
- memcpy(ret, thread_name, size);
- return (ret);
-}
-
-int
-prof_thread_name_set(tsd_t *tsd, const char *thread_name)
-{
- prof_tdata_t *tdata;
- unsigned i;
- char *s;
-
- tdata = prof_tdata_get(tsd, true);
- if (tdata == NULL)
- return (EAGAIN);
-
- /* Validate input. */
- if (thread_name == NULL)
- return (EFAULT);
- for (i = 0; thread_name[i] != '\0'; i++) {
- char c = thread_name[i];
- if (!isgraph(c) && !isblank(c))
- return (EFAULT);
- }
-
- s = prof_thread_name_alloc(tsd_tsdn(tsd), thread_name);
- if (s == NULL)
- return (EAGAIN);
-
- if (tdata->thread_name != NULL) {
- idalloctm(tsd_tsdn(tsd), tdata->thread_name, NULL, true, true);
- tdata->thread_name = NULL;
- }
- if (strlen(s) > 0)
- tdata->thread_name = s;
- return (0);
-}
-
-bool
-prof_thread_active_get(tsd_t *tsd)
-{
- prof_tdata_t *tdata;
-
- tdata = prof_tdata_get(tsd, true);
- if (tdata == NULL)
- return (false);
- return (tdata->active);
-}
-
-bool
-prof_thread_active_set(tsd_t *tsd, bool active)
-{
- prof_tdata_t *tdata;
-
- tdata = prof_tdata_get(tsd, true);
- if (tdata == NULL)
- return (true);
- tdata->active = active;
- return (false);
-}
-
-bool
-prof_thread_active_init_get(tsdn_t *tsdn)
-{
- bool active_init;
-
- malloc_mutex_lock(tsdn, &prof_thread_active_init_mtx);
- active_init = prof_thread_active_init;
- malloc_mutex_unlock(tsdn, &prof_thread_active_init_mtx);
- return (active_init);
-}
-
-bool
-prof_thread_active_init_set(tsdn_t *tsdn, bool active_init)
-{
- bool active_init_old;
-
- malloc_mutex_lock(tsdn, &prof_thread_active_init_mtx);
- active_init_old = prof_thread_active_init;
- prof_thread_active_init = active_init;
- malloc_mutex_unlock(tsdn, &prof_thread_active_init_mtx);
- return (active_init_old);
-}
-
-bool
-prof_gdump_get(tsdn_t *tsdn)
-{
- bool prof_gdump_current;
-
- malloc_mutex_lock(tsdn, &prof_gdump_mtx);
- prof_gdump_current = prof_gdump_val;
- malloc_mutex_unlock(tsdn, &prof_gdump_mtx);
- return (prof_gdump_current);
-}
-
-bool
-prof_gdump_set(tsdn_t *tsdn, bool gdump)
-{
- bool prof_gdump_old;
-
- malloc_mutex_lock(tsdn, &prof_gdump_mtx);
- prof_gdump_old = prof_gdump_val;
- prof_gdump_val = gdump;
- malloc_mutex_unlock(tsdn, &prof_gdump_mtx);
- return (prof_gdump_old);
-}
-
-void
-prof_boot0(void)
-{
-
- cassert(config_prof);
-
- memcpy(opt_prof_prefix, PROF_PREFIX_DEFAULT,
- sizeof(PROF_PREFIX_DEFAULT));
-}
-
-void
-prof_boot1(void)
-{
-
- cassert(config_prof);
-
- /*
- * opt_prof must be in its final state before any arenas are
- * initialized, so this function must be executed early.
- */
-
- if (opt_prof_leak && !opt_prof) {
- /*
- * Enable opt_prof, but in such a way that profiles are never
- * automatically dumped.
- */
- opt_prof = true;
- opt_prof_gdump = false;
- } else if (opt_prof) {
- if (opt_lg_prof_interval >= 0) {
- prof_interval = (((uint64_t)1U) <<
- opt_lg_prof_interval);
- }
- }
-}
-
-bool
-prof_boot2(tsd_t *tsd)
-{
-
- cassert(config_prof);
-
- if (opt_prof) {
- unsigned i;
-
- lg_prof_sample = opt_lg_prof_sample;
-
- prof_active = opt_prof_active;
- if (malloc_mutex_init(&prof_active_mtx, "prof_active",
- WITNESS_RANK_PROF_ACTIVE))
- return (true);
-
- prof_gdump_val = opt_prof_gdump;
- if (malloc_mutex_init(&prof_gdump_mtx, "prof_gdump",
- WITNESS_RANK_PROF_GDUMP))
- return (true);
-
- prof_thread_active_init = opt_prof_thread_active_init;
- if (malloc_mutex_init(&prof_thread_active_init_mtx,
- "prof_thread_active_init",
- WITNESS_RANK_PROF_THREAD_ACTIVE_INIT))
- return (true);
-
- if (ckh_new(tsd, &bt2gctx, PROF_CKH_MINITEMS, prof_bt_hash,
- prof_bt_keycomp))
- return (true);
- if (malloc_mutex_init(&bt2gctx_mtx, "prof_bt2gctx",
- WITNESS_RANK_PROF_BT2GCTX))
- return (true);
-
- tdata_tree_new(&tdatas);
- if (malloc_mutex_init(&tdatas_mtx, "prof_tdatas",
- WITNESS_RANK_PROF_TDATAS))
- return (true);
-
- next_thr_uid = 0;
- if (malloc_mutex_init(&next_thr_uid_mtx, "prof_next_thr_uid",
- WITNESS_RANK_PROF_NEXT_THR_UID))
- return (true);
-
- if (malloc_mutex_init(&prof_dump_seq_mtx, "prof_dump_seq",
- WITNESS_RANK_PROF_DUMP_SEQ))
- return (true);
- if (malloc_mutex_init(&prof_dump_mtx, "prof_dump",
- WITNESS_RANK_PROF_DUMP))
- return (true);
-
- if (opt_prof_final && opt_prof_prefix[0] != '\0' &&
- atexit(prof_fdump) != 0) {
- malloc_write("<jemalloc>: Error in atexit()\n");
- if (opt_abort)
- abort();
- }
-
- gctx_locks = (malloc_mutex_t *)base_alloc(tsd_tsdn(tsd),
- PROF_NCTX_LOCKS * sizeof(malloc_mutex_t));
- if (gctx_locks == NULL)
- return (true);
- for (i = 0; i < PROF_NCTX_LOCKS; i++) {
- if (malloc_mutex_init(&gctx_locks[i], "prof_gctx",
- WITNESS_RANK_PROF_GCTX))
- return (true);
- }
-
- tdata_locks = (malloc_mutex_t *)base_alloc(tsd_tsdn(tsd),
- PROF_NTDATA_LOCKS * sizeof(malloc_mutex_t));
- if (tdata_locks == NULL)
- return (true);
- for (i = 0; i < PROF_NTDATA_LOCKS; i++) {
- if (malloc_mutex_init(&tdata_locks[i], "prof_tdata",
- WITNESS_RANK_PROF_TDATA))
- return (true);
- }
- }
-
-#ifdef JEMALLOC_PROF_LIBGCC
- /*
- * Cause the backtracing machinery to allocate its internal state
- * before enabling profiling.
- */
- _Unwind_Backtrace(prof_unwind_init_callback, NULL);
-#endif
-
- prof_booted = true;
-
- return (false);
-}
-
-void
-prof_prefork0(tsdn_t *tsdn)
-{
-
- if (opt_prof) {
- unsigned i;
-
- malloc_mutex_prefork(tsdn, &prof_dump_mtx);
- malloc_mutex_prefork(tsdn, &bt2gctx_mtx);
- malloc_mutex_prefork(tsdn, &tdatas_mtx);
- for (i = 0; i < PROF_NTDATA_LOCKS; i++)
- malloc_mutex_prefork(tsdn, &tdata_locks[i]);
- for (i = 0; i < PROF_NCTX_LOCKS; i++)
- malloc_mutex_prefork(tsdn, &gctx_locks[i]);
- }
-}
-
-void
-prof_prefork1(tsdn_t *tsdn)
-{
-
- if (opt_prof) {
- malloc_mutex_prefork(tsdn, &prof_active_mtx);
- malloc_mutex_prefork(tsdn, &prof_dump_seq_mtx);
- malloc_mutex_prefork(tsdn, &prof_gdump_mtx);
- malloc_mutex_prefork(tsdn, &next_thr_uid_mtx);
- malloc_mutex_prefork(tsdn, &prof_thread_active_init_mtx);
- }
-}
-
-void
-prof_postfork_parent(tsdn_t *tsdn)
-{
-
- if (opt_prof) {
- unsigned i;
-
- malloc_mutex_postfork_parent(tsdn,
- &prof_thread_active_init_mtx);
- malloc_mutex_postfork_parent(tsdn, &next_thr_uid_mtx);
- malloc_mutex_postfork_parent(tsdn, &prof_gdump_mtx);
- malloc_mutex_postfork_parent(tsdn, &prof_dump_seq_mtx);
- malloc_mutex_postfork_parent(tsdn, &prof_active_mtx);
- for (i = 0; i < PROF_NCTX_LOCKS; i++)
- malloc_mutex_postfork_parent(tsdn, &gctx_locks[i]);
- for (i = 0; i < PROF_NTDATA_LOCKS; i++)
- malloc_mutex_postfork_parent(tsdn, &tdata_locks[i]);
- malloc_mutex_postfork_parent(tsdn, &tdatas_mtx);
- malloc_mutex_postfork_parent(tsdn, &bt2gctx_mtx);
- malloc_mutex_postfork_parent(tsdn, &prof_dump_mtx);
- }
-}
-
-void
-prof_postfork_child(tsdn_t *tsdn)
-{
-
- if (opt_prof) {
- unsigned i;
-
- malloc_mutex_postfork_child(tsdn, &prof_thread_active_init_mtx);
- malloc_mutex_postfork_child(tsdn, &next_thr_uid_mtx);
- malloc_mutex_postfork_child(tsdn, &prof_gdump_mtx);
- malloc_mutex_postfork_child(tsdn, &prof_dump_seq_mtx);
- malloc_mutex_postfork_child(tsdn, &prof_active_mtx);
- for (i = 0; i < PROF_NCTX_LOCKS; i++)
- malloc_mutex_postfork_child(tsdn, &gctx_locks[i]);
- for (i = 0; i < PROF_NTDATA_LOCKS; i++)
- malloc_mutex_postfork_child(tsdn, &tdata_locks[i]);
- malloc_mutex_postfork_child(tsdn, &tdatas_mtx);
- malloc_mutex_postfork_child(tsdn, &bt2gctx_mtx);
- malloc_mutex_postfork_child(tsdn, &prof_dump_mtx);
- }
-}
-
-/******************************************************************************/
diff --git a/memory/jemalloc/src/src/quarantine.c b/memory/jemalloc/src/src/quarantine.c
deleted file mode 100644
index 18903fb5c..000000000
--- a/memory/jemalloc/src/src/quarantine.c
+++ /dev/null
@@ -1,183 +0,0 @@
-#define JEMALLOC_QUARANTINE_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/*
- * Quarantine pointers close to NULL are used to encode state information that
- * is used for cleaning up during thread shutdown.
- */
-#define QUARANTINE_STATE_REINCARNATED ((quarantine_t *)(uintptr_t)1)
-#define QUARANTINE_STATE_PURGATORY ((quarantine_t *)(uintptr_t)2)
-#define QUARANTINE_STATE_MAX QUARANTINE_STATE_PURGATORY
-
-/******************************************************************************/
-/* Function prototypes for non-inline static functions. */
-
-static quarantine_t *quarantine_grow(tsd_t *tsd, quarantine_t *quarantine);
-static void quarantine_drain_one(tsdn_t *tsdn, quarantine_t *quarantine);
-static void quarantine_drain(tsdn_t *tsdn, quarantine_t *quarantine,
- size_t upper_bound);
-
-/******************************************************************************/
-
-static quarantine_t *
-quarantine_init(tsdn_t *tsdn, size_t lg_maxobjs)
-{
- quarantine_t *quarantine;
- size_t size;
-
- size = offsetof(quarantine_t, objs) + ((ZU(1) << lg_maxobjs) *
- sizeof(quarantine_obj_t));
- quarantine = (quarantine_t *)iallocztm(tsdn, size, size2index(size),
- false, NULL, true, arena_get(TSDN_NULL, 0, true), true);
- if (quarantine == NULL)
- return (NULL);
- quarantine->curbytes = 0;
- quarantine->curobjs = 0;
- quarantine->first = 0;
- quarantine->lg_maxobjs = lg_maxobjs;
-
- return (quarantine);
-}
-
-void
-quarantine_alloc_hook_work(tsd_t *tsd)
-{
- quarantine_t *quarantine;
-
- if (!tsd_nominal(tsd))
- return;
-
- quarantine = quarantine_init(tsd_tsdn(tsd), LG_MAXOBJS_INIT);
- /*
- * Check again whether quarantine has been initialized, because
- * quarantine_init() may have triggered recursive initialization.
- */
- if (tsd_quarantine_get(tsd) == NULL)
- tsd_quarantine_set(tsd, quarantine);
- else
- idalloctm(tsd_tsdn(tsd), quarantine, NULL, true, true);
-}
-
-static quarantine_t *
-quarantine_grow(tsd_t *tsd, quarantine_t *quarantine)
-{
- quarantine_t *ret;
-
- ret = quarantine_init(tsd_tsdn(tsd), quarantine->lg_maxobjs + 1);
- if (ret == NULL) {
- quarantine_drain_one(tsd_tsdn(tsd), quarantine);
- return (quarantine);
- }
-
- ret->curbytes = quarantine->curbytes;
- ret->curobjs = quarantine->curobjs;
- if (quarantine->first + quarantine->curobjs <= (ZU(1) <<
- quarantine->lg_maxobjs)) {
- /* objs ring buffer data are contiguous. */
- memcpy(ret->objs, &quarantine->objs[quarantine->first],
- quarantine->curobjs * sizeof(quarantine_obj_t));
- } else {
- /* objs ring buffer data wrap around. */
- size_t ncopy_a = (ZU(1) << quarantine->lg_maxobjs) -
- quarantine->first;
- size_t ncopy_b = quarantine->curobjs - ncopy_a;
-
- memcpy(ret->objs, &quarantine->objs[quarantine->first], ncopy_a
- * sizeof(quarantine_obj_t));
- memcpy(&ret->objs[ncopy_a], quarantine->objs, ncopy_b *
- sizeof(quarantine_obj_t));
- }
- idalloctm(tsd_tsdn(tsd), quarantine, NULL, true, true);
-
- tsd_quarantine_set(tsd, ret);
- return (ret);
-}
-
-static void
-quarantine_drain_one(tsdn_t *tsdn, quarantine_t *quarantine)
-{
- quarantine_obj_t *obj = &quarantine->objs[quarantine->first];
- assert(obj->usize == isalloc(tsdn, obj->ptr, config_prof));
- idalloctm(tsdn, obj->ptr, NULL, false, true);
- quarantine->curbytes -= obj->usize;
- quarantine->curobjs--;
- quarantine->first = (quarantine->first + 1) & ((ZU(1) <<
- quarantine->lg_maxobjs) - 1);
-}
-
-static void
-quarantine_drain(tsdn_t *tsdn, quarantine_t *quarantine, size_t upper_bound)
-{
-
- while (quarantine->curbytes > upper_bound && quarantine->curobjs > 0)
- quarantine_drain_one(tsdn, quarantine);
-}
-
-void
-quarantine(tsd_t *tsd, void *ptr)
-{
- quarantine_t *quarantine;
- size_t usize = isalloc(tsd_tsdn(tsd), ptr, config_prof);
-
- cassert(config_fill);
- assert(opt_quarantine);
-
- if ((quarantine = tsd_quarantine_get(tsd)) == NULL) {
- idalloctm(tsd_tsdn(tsd), ptr, NULL, false, true);
- return;
- }
- /*
- * Drain one or more objects if the quarantine size limit would be
- * exceeded by appending ptr.
- */
- if (quarantine->curbytes + usize > opt_quarantine) {
- size_t upper_bound = (opt_quarantine >= usize) ? opt_quarantine
- - usize : 0;
- quarantine_drain(tsd_tsdn(tsd), quarantine, upper_bound);
- }
- /* Grow the quarantine ring buffer if it's full. */
- if (quarantine->curobjs == (ZU(1) << quarantine->lg_maxobjs))
- quarantine = quarantine_grow(tsd, quarantine);
- /* quarantine_grow() must free a slot if it fails to grow. */
- assert(quarantine->curobjs < (ZU(1) << quarantine->lg_maxobjs));
- /* Append ptr if its size doesn't exceed the quarantine size. */
- if (quarantine->curbytes + usize <= opt_quarantine) {
- size_t offset = (quarantine->first + quarantine->curobjs) &
- ((ZU(1) << quarantine->lg_maxobjs) - 1);
- quarantine_obj_t *obj = &quarantine->objs[offset];
- obj->ptr = ptr;
- obj->usize = usize;
- quarantine->curbytes += usize;
- quarantine->curobjs++;
- if (config_fill && unlikely(opt_junk_free)) {
- /*
- * Only do redzone validation if Valgrind isn't in
- * operation.
- */
- if ((!config_valgrind || likely(!in_valgrind))
- && usize <= SMALL_MAXCLASS)
- arena_quarantine_junk_small(ptr, usize);
- else
- memset(ptr, JEMALLOC_FREE_JUNK, usize);
- }
- } else {
- assert(quarantine->curbytes == 0);
- idalloctm(tsd_tsdn(tsd), ptr, NULL, false, true);
- }
-}
-
-void
-quarantine_cleanup(tsd_t *tsd)
-{
- quarantine_t *quarantine;
-
- if (!config_fill)
- return;
-
- quarantine = tsd_quarantine_get(tsd);
- if (quarantine != NULL) {
- quarantine_drain(tsd_tsdn(tsd), quarantine, 0);
- idalloctm(tsd_tsdn(tsd), quarantine, NULL, true, true);
- tsd_quarantine_set(tsd, NULL);
- }
-}
diff --git a/memory/jemalloc/src/src/rtree.c b/memory/jemalloc/src/src/rtree.c
deleted file mode 100644
index f2e2997d5..000000000
--- a/memory/jemalloc/src/src/rtree.c
+++ /dev/null
@@ -1,132 +0,0 @@
-#define JEMALLOC_RTREE_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-static unsigned
-hmin(unsigned ha, unsigned hb)
-{
-
- return (ha < hb ? ha : hb);
-}
-
-/* Only the most significant bits of keys passed to rtree_[gs]et() are used. */
-bool
-rtree_new(rtree_t *rtree, unsigned bits, rtree_node_alloc_t *alloc,
- rtree_node_dalloc_t *dalloc)
-{
- unsigned bits_in_leaf, height, i;
-
- assert(RTREE_HEIGHT_MAX == ((ZU(1) << (LG_SIZEOF_PTR+3)) /
- RTREE_BITS_PER_LEVEL));
- assert(bits > 0 && bits <= (sizeof(uintptr_t) << 3));
-
- bits_in_leaf = (bits % RTREE_BITS_PER_LEVEL) == 0 ? RTREE_BITS_PER_LEVEL
- : (bits % RTREE_BITS_PER_LEVEL);
- if (bits > bits_in_leaf) {
- height = 1 + (bits - bits_in_leaf) / RTREE_BITS_PER_LEVEL;
- if ((height-1) * RTREE_BITS_PER_LEVEL + bits_in_leaf != bits)
- height++;
- } else
- height = 1;
- assert((height-1) * RTREE_BITS_PER_LEVEL + bits_in_leaf == bits);
-
- rtree->alloc = alloc;
- rtree->dalloc = dalloc;
- rtree->height = height;
-
- /* Root level. */
- rtree->levels[0].subtree = NULL;
- rtree->levels[0].bits = (height > 1) ? RTREE_BITS_PER_LEVEL :
- bits_in_leaf;
- rtree->levels[0].cumbits = rtree->levels[0].bits;
- /* Interior levels. */
- for (i = 1; i < height-1; i++) {
- rtree->levels[i].subtree = NULL;
- rtree->levels[i].bits = RTREE_BITS_PER_LEVEL;
- rtree->levels[i].cumbits = rtree->levels[i-1].cumbits +
- RTREE_BITS_PER_LEVEL;
- }
- /* Leaf level. */
- if (height > 1) {
- rtree->levels[height-1].subtree = NULL;
- rtree->levels[height-1].bits = bits_in_leaf;
- rtree->levels[height-1].cumbits = bits;
- }
-
- /* Compute lookup table to be used by rtree_start_level(). */
- for (i = 0; i < RTREE_HEIGHT_MAX; i++) {
- rtree->start_level[i] = hmin(RTREE_HEIGHT_MAX - 1 - i, height -
- 1);
- }
-
- return (false);
-}
-
-static void
-rtree_delete_subtree(rtree_t *rtree, rtree_node_elm_t *node, unsigned level)
-{
-
- if (level + 1 < rtree->height) {
- size_t nchildren, i;
-
- nchildren = ZU(1) << rtree->levels[level].bits;
- for (i = 0; i < nchildren; i++) {
- rtree_node_elm_t *child = node[i].child;
- if (child != NULL)
- rtree_delete_subtree(rtree, child, level + 1);
- }
- }
- rtree->dalloc(node);
-}
-
-void
-rtree_delete(rtree_t *rtree)
-{
- unsigned i;
-
- for (i = 0; i < rtree->height; i++) {
- rtree_node_elm_t *subtree = rtree->levels[i].subtree;
- if (subtree != NULL)
- rtree_delete_subtree(rtree, subtree, i);
- }
-}
-
-static rtree_node_elm_t *
-rtree_node_init(rtree_t *rtree, unsigned level, rtree_node_elm_t **elmp)
-{
- rtree_node_elm_t *node;
-
- if (atomic_cas_p((void **)elmp, NULL, RTREE_NODE_INITIALIZING)) {
- spin_t spinner;
-
- /*
- * Another thread is already in the process of initializing.
- * Spin-wait until initialization is complete.
- */
- spin_init(&spinner);
- do {
- spin_adaptive(&spinner);
- node = atomic_read_p((void **)elmp);
- } while (node == RTREE_NODE_INITIALIZING);
- } else {
- node = rtree->alloc(ZU(1) << rtree->levels[level].bits);
- if (node == NULL)
- return (NULL);
- atomic_write_p((void **)elmp, node);
- }
-
- return (node);
-}
-
-rtree_node_elm_t *
-rtree_subtree_read_hard(rtree_t *rtree, unsigned level)
-{
-
- return (rtree_node_init(rtree, level, &rtree->levels[level].subtree));
-}
-
-rtree_node_elm_t *
-rtree_child_read_hard(rtree_t *rtree, rtree_node_elm_t *elm, unsigned level)
-{
-
- return (rtree_node_init(rtree, level+1, &elm->child));
-}
diff --git a/memory/jemalloc/src/src/spin.c b/memory/jemalloc/src/src/spin.c
deleted file mode 100644
index 5242d95aa..000000000
--- a/memory/jemalloc/src/src/spin.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#define JEMALLOC_SPIN_C_
-#include "jemalloc/internal/jemalloc_internal.h"
diff --git a/memory/jemalloc/src/src/stats.c b/memory/jemalloc/src/src/stats.c
deleted file mode 100644
index bd8af3999..000000000
--- a/memory/jemalloc/src/src/stats.c
+++ /dev/null
@@ -1,1153 +0,0 @@
-#define JEMALLOC_STATS_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-#define CTL_GET(n, v, t) do { \
- size_t sz = sizeof(t); \
- xmallctl(n, v, &sz, NULL, 0); \
-} while (0)
-
-#define CTL_M2_GET(n, i, v, t) do { \
- size_t mib[6]; \
- size_t miblen = sizeof(mib) / sizeof(size_t); \
- size_t sz = sizeof(t); \
- xmallctlnametomib(n, mib, &miblen); \
- mib[2] = (i); \
- xmallctlbymib(mib, miblen, v, &sz, NULL, 0); \
-} while (0)
-
-#define CTL_M2_M4_GET(n, i, j, v, t) do { \
- size_t mib[6]; \
- size_t miblen = sizeof(mib) / sizeof(size_t); \
- size_t sz = sizeof(t); \
- xmallctlnametomib(n, mib, &miblen); \
- mib[2] = (i); \
- mib[4] = (j); \
- xmallctlbymib(mib, miblen, v, &sz, NULL, 0); \
-} while (0)
-
-/******************************************************************************/
-/* Data. */
-
-bool opt_stats_print = false;
-
-size_t stats_cactive = 0;
-
-/******************************************************************************/
-
-static void
-stats_arena_bins_print(void (*write_cb)(void *, const char *), void *cbopaque,
- bool json, bool large, bool huge, unsigned i)
-{
- size_t page;
- bool config_tcache, in_gap, in_gap_prev;
- unsigned nbins, j;
-
- CTL_GET("arenas.page", &page, size_t);
-
- CTL_GET("arenas.nbins", &nbins, unsigned);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"bins\": [\n");
- } else {
- CTL_GET("config.tcache", &config_tcache, bool);
- if (config_tcache) {
- malloc_cprintf(write_cb, cbopaque,
- "bins: size ind allocated nmalloc"
- " ndalloc nrequests curregs"
- " curruns regs pgs util nfills"
- " nflushes newruns reruns\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "bins: size ind allocated nmalloc"
- " ndalloc nrequests curregs"
- " curruns regs pgs util newruns"
- " reruns\n");
- }
- }
- for (j = 0, in_gap = false; j < nbins; j++) {
- uint64_t nruns;
- size_t reg_size, run_size, curregs;
- size_t curruns;
- uint32_t nregs;
- uint64_t nmalloc, ndalloc, nrequests, nfills, nflushes;
- uint64_t nreruns;
-
- CTL_M2_M4_GET("stats.arenas.0.bins.0.nruns", i, j, &nruns,
- uint64_t);
- in_gap_prev = in_gap;
- in_gap = (nruns == 0);
-
- if (!json && in_gap_prev && !in_gap) {
- malloc_cprintf(write_cb, cbopaque,
- " ---\n");
- }
-
- CTL_M2_GET("arenas.bin.0.size", j, &reg_size, size_t);
- CTL_M2_GET("arenas.bin.0.nregs", j, &nregs, uint32_t);
- CTL_M2_GET("arenas.bin.0.run_size", j, &run_size, size_t);
-
- CTL_M2_M4_GET("stats.arenas.0.bins.0.nmalloc", i, j, &nmalloc,
- uint64_t);
- CTL_M2_M4_GET("stats.arenas.0.bins.0.ndalloc", i, j, &ndalloc,
- uint64_t);
- CTL_M2_M4_GET("stats.arenas.0.bins.0.curregs", i, j, &curregs,
- size_t);
- CTL_M2_M4_GET("stats.arenas.0.bins.0.nrequests", i, j,
- &nrequests, uint64_t);
- if (config_tcache) {
- CTL_M2_M4_GET("stats.arenas.0.bins.0.nfills", i, j,
- &nfills, uint64_t);
- CTL_M2_M4_GET("stats.arenas.0.bins.0.nflushes", i, j,
- &nflushes, uint64_t);
- }
- CTL_M2_M4_GET("stats.arenas.0.bins.0.nreruns", i, j, &nreruns,
- uint64_t);
- CTL_M2_M4_GET("stats.arenas.0.bins.0.curruns", i, j, &curruns,
- size_t);
-
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t{\n"
- "\t\t\t\t\t\t\"nmalloc\": %"FMTu64",\n"
- "\t\t\t\t\t\t\"ndalloc\": %"FMTu64",\n"
- "\t\t\t\t\t\t\"curregs\": %zu,\n"
- "\t\t\t\t\t\t\"nrequests\": %"FMTu64",\n",
- nmalloc,
- ndalloc,
- curregs,
- nrequests);
- if (config_tcache) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\t\"nfills\": %"FMTu64",\n"
- "\t\t\t\t\t\t\"nflushes\": %"FMTu64",\n",
- nfills,
- nflushes);
- }
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\t\"nreruns\": %"FMTu64",\n"
- "\t\t\t\t\t\t\"curruns\": %zu\n"
- "\t\t\t\t\t}%s\n",
- nreruns,
- curruns,
- (j + 1 < nbins) ? "," : "");
- } else if (!in_gap) {
- size_t availregs, milli;
- char util[6]; /* "x.yyy". */
-
- availregs = nregs * curruns;
- milli = (availregs != 0) ? (1000 * curregs) / availregs
- : 1000;
- assert(milli <= 1000);
- if (milli < 10) {
- malloc_snprintf(util, sizeof(util),
- "0.00%zu", milli);
- } else if (milli < 100) {
- malloc_snprintf(util, sizeof(util), "0.0%zu",
- milli);
- } else if (milli < 1000) {
- malloc_snprintf(util, sizeof(util), "0.%zu",
- milli);
- } else
- malloc_snprintf(util, sizeof(util), "1");
-
- if (config_tcache) {
- malloc_cprintf(write_cb, cbopaque,
- "%20zu %3u %12zu %12"FMTu64
- " %12"FMTu64" %12"FMTu64" %12zu"
- " %12zu %4u %3zu %-5s %12"FMTu64
- " %12"FMTu64" %12"FMTu64" %12"FMTu64"\n",
- reg_size, j, curregs * reg_size, nmalloc,
- ndalloc, nrequests, curregs, curruns, nregs,
- run_size / page, util, nfills, nflushes,
- nruns, nreruns);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "%20zu %3u %12zu %12"FMTu64
- " %12"FMTu64" %12"FMTu64" %12zu"
- " %12zu %4u %3zu %-5s %12"FMTu64
- " %12"FMTu64"\n",
- reg_size, j, curregs * reg_size, nmalloc,
- ndalloc, nrequests, curregs, curruns, nregs,
- run_size / page, util, nruns, nreruns);
- }
- }
- }
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t]%s\n", (large || huge) ? "," : "");
- } else {
- if (in_gap) {
- malloc_cprintf(write_cb, cbopaque,
- " ---\n");
- }
- }
-}
-
-static void
-stats_arena_lruns_print(void (*write_cb)(void *, const char *), void *cbopaque,
- bool json, bool huge, unsigned i)
-{
- unsigned nbins, nlruns, j;
- bool in_gap, in_gap_prev;
-
- CTL_GET("arenas.nbins", &nbins, unsigned);
- CTL_GET("arenas.nlruns", &nlruns, unsigned);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"lruns\": [\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "large: size ind allocated nmalloc"
- " ndalloc nrequests curruns\n");
- }
- for (j = 0, in_gap = false; j < nlruns; j++) {
- uint64_t nmalloc, ndalloc, nrequests;
- size_t run_size, curruns;
-
- CTL_M2_M4_GET("stats.arenas.0.lruns.0.nmalloc", i, j, &nmalloc,
- uint64_t);
- CTL_M2_M4_GET("stats.arenas.0.lruns.0.ndalloc", i, j, &ndalloc,
- uint64_t);
- CTL_M2_M4_GET("stats.arenas.0.lruns.0.nrequests", i, j,
- &nrequests, uint64_t);
- in_gap_prev = in_gap;
- in_gap = (nrequests == 0);
-
- if (!json && in_gap_prev && !in_gap) {
- malloc_cprintf(write_cb, cbopaque,
- " ---\n");
- }
-
- CTL_M2_GET("arenas.lrun.0.size", j, &run_size, size_t);
- CTL_M2_M4_GET("stats.arenas.0.lruns.0.curruns", i, j, &curruns,
- size_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t{\n"
- "\t\t\t\t\t\t\"curruns\": %zu\n"
- "\t\t\t\t\t}%s\n",
- curruns,
- (j + 1 < nlruns) ? "," : "");
- } else if (!in_gap) {
- malloc_cprintf(write_cb, cbopaque,
- "%20zu %3u %12zu %12"FMTu64" %12"FMTu64
- " %12"FMTu64" %12zu\n",
- run_size, nbins + j, curruns * run_size, nmalloc,
- ndalloc, nrequests, curruns);
- }
- }
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t]%s\n", huge ? "," : "");
- } else {
- if (in_gap) {
- malloc_cprintf(write_cb, cbopaque,
- " ---\n");
- }
- }
-}
-
-static void
-stats_arena_hchunks_print(void (*write_cb)(void *, const char *),
- void *cbopaque, bool json, unsigned i)
-{
- unsigned nbins, nlruns, nhchunks, j;
- bool in_gap, in_gap_prev;
-
- CTL_GET("arenas.nbins", &nbins, unsigned);
- CTL_GET("arenas.nlruns", &nlruns, unsigned);
- CTL_GET("arenas.nhchunks", &nhchunks, unsigned);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"hchunks\": [\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "huge: size ind allocated nmalloc"
- " ndalloc nrequests curhchunks\n");
- }
- for (j = 0, in_gap = false; j < nhchunks; j++) {
- uint64_t nmalloc, ndalloc, nrequests;
- size_t hchunk_size, curhchunks;
-
- CTL_M2_M4_GET("stats.arenas.0.hchunks.0.nmalloc", i, j,
- &nmalloc, uint64_t);
- CTL_M2_M4_GET("stats.arenas.0.hchunks.0.ndalloc", i, j,
- &ndalloc, uint64_t);
- CTL_M2_M4_GET("stats.arenas.0.hchunks.0.nrequests", i, j,
- &nrequests, uint64_t);
- in_gap_prev = in_gap;
- in_gap = (nrequests == 0);
-
- if (!json && in_gap_prev && !in_gap) {
- malloc_cprintf(write_cb, cbopaque,
- " ---\n");
- }
-
- CTL_M2_GET("arenas.hchunk.0.size", j, &hchunk_size, size_t);
- CTL_M2_M4_GET("stats.arenas.0.hchunks.0.curhchunks", i, j,
- &curhchunks, size_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t{\n"
- "\t\t\t\t\t\t\"curhchunks\": %zu\n"
- "\t\t\t\t\t}%s\n",
- curhchunks,
- (j + 1 < nhchunks) ? "," : "");
- } else if (!in_gap) {
- malloc_cprintf(write_cb, cbopaque,
- "%20zu %3u %12zu %12"FMTu64" %12"FMTu64
- " %12"FMTu64" %12zu\n",
- hchunk_size, nbins + nlruns + j,
- curhchunks * hchunk_size, nmalloc, ndalloc,
- nrequests, curhchunks);
- }
- }
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t]\n");
- } else {
- if (in_gap) {
- malloc_cprintf(write_cb, cbopaque,
- " ---\n");
- }
- }
-}
-
-static void
-stats_arena_print(void (*write_cb)(void *, const char *), void *cbopaque,
- bool json, unsigned i, bool bins, bool large, bool huge)
-{
- unsigned nthreads;
- const char *dss;
- ssize_t lg_dirty_mult, decay_time;
- size_t page, pactive, pdirty, mapped, retained;
- size_t metadata_mapped, metadata_allocated;
- uint64_t npurge, nmadvise, purged;
- size_t small_allocated;
- uint64_t small_nmalloc, small_ndalloc, small_nrequests;
- size_t large_allocated;
- uint64_t large_nmalloc, large_ndalloc, large_nrequests;
- size_t huge_allocated;
- uint64_t huge_nmalloc, huge_ndalloc, huge_nrequests;
-
- CTL_GET("arenas.page", &page, size_t);
-
- CTL_M2_GET("stats.arenas.0.nthreads", i, &nthreads, unsigned);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"nthreads\": %u,\n", nthreads);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "assigned threads: %u\n", nthreads);
- }
-
- CTL_M2_GET("stats.arenas.0.dss", i, &dss, const char *);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"dss\": \"%s\",\n", dss);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "dss allocation precedence: %s\n", dss);
- }
-
- CTL_M2_GET("stats.arenas.0.lg_dirty_mult", i, &lg_dirty_mult, ssize_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"lg_dirty_mult\": %zd,\n", lg_dirty_mult);
- } else {
- if (opt_purge == purge_mode_ratio) {
- if (lg_dirty_mult >= 0) {
- malloc_cprintf(write_cb, cbopaque,
- "min active:dirty page ratio: %u:1\n",
- (1U << lg_dirty_mult));
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "min active:dirty page ratio: N/A\n");
- }
- }
- }
-
- CTL_M2_GET("stats.arenas.0.decay_time", i, &decay_time, ssize_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"decay_time\": %zd,\n", decay_time);
- } else {
- if (opt_purge == purge_mode_decay) {
- if (decay_time >= 0) {
- malloc_cprintf(write_cb, cbopaque,
- "decay time: %zd\n", decay_time);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "decay time: N/A\n");
- }
- }
- }
-
- CTL_M2_GET("stats.arenas.0.pactive", i, &pactive, size_t);
- CTL_M2_GET("stats.arenas.0.pdirty", i, &pdirty, size_t);
- CTL_M2_GET("stats.arenas.0.npurge", i, &npurge, uint64_t);
- CTL_M2_GET("stats.arenas.0.nmadvise", i, &nmadvise, uint64_t);
- CTL_M2_GET("stats.arenas.0.purged", i, &purged, uint64_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"pactive\": %zu,\n", pactive);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"pdirty\": %zu,\n", pdirty);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"npurge\": %"FMTu64",\n", npurge);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"nmadvise\": %"FMTu64",\n", nmadvise);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"purged\": %"FMTu64",\n", purged);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "purging: dirty: %zu, sweeps: %"FMTu64", madvises: %"FMTu64
- ", purged: %"FMTu64"\n", pdirty, npurge, nmadvise, purged);
- }
-
- CTL_M2_GET("stats.arenas.0.small.allocated", i, &small_allocated,
- size_t);
- CTL_M2_GET("stats.arenas.0.small.nmalloc", i, &small_nmalloc, uint64_t);
- CTL_M2_GET("stats.arenas.0.small.ndalloc", i, &small_ndalloc, uint64_t);
- CTL_M2_GET("stats.arenas.0.small.nrequests", i, &small_nrequests,
- uint64_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"small\": {\n");
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"allocated\": %zu,\n", small_allocated);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"nmalloc\": %"FMTu64",\n", small_nmalloc);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"ndalloc\": %"FMTu64",\n", small_ndalloc);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"nrequests\": %"FMTu64"\n", small_nrequests);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t},\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- " allocated nmalloc"
- " ndalloc nrequests\n");
- malloc_cprintf(write_cb, cbopaque,
- "small: %12zu %12"FMTu64" %12"FMTu64
- " %12"FMTu64"\n",
- small_allocated, small_nmalloc, small_ndalloc,
- small_nrequests);
- }
-
- CTL_M2_GET("stats.arenas.0.large.allocated", i, &large_allocated,
- size_t);
- CTL_M2_GET("stats.arenas.0.large.nmalloc", i, &large_nmalloc, uint64_t);
- CTL_M2_GET("stats.arenas.0.large.ndalloc", i, &large_ndalloc, uint64_t);
- CTL_M2_GET("stats.arenas.0.large.nrequests", i, &large_nrequests,
- uint64_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"large\": {\n");
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"allocated\": %zu,\n", large_allocated);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"nmalloc\": %"FMTu64",\n", large_nmalloc);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"ndalloc\": %"FMTu64",\n", large_ndalloc);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"nrequests\": %"FMTu64"\n", large_nrequests);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t},\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "large: %12zu %12"FMTu64" %12"FMTu64
- " %12"FMTu64"\n",
- large_allocated, large_nmalloc, large_ndalloc,
- large_nrequests);
- }
-
- CTL_M2_GET("stats.arenas.0.huge.allocated", i, &huge_allocated, size_t);
- CTL_M2_GET("stats.arenas.0.huge.nmalloc", i, &huge_nmalloc, uint64_t);
- CTL_M2_GET("stats.arenas.0.huge.ndalloc", i, &huge_ndalloc, uint64_t);
- CTL_M2_GET("stats.arenas.0.huge.nrequests", i, &huge_nrequests,
- uint64_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"huge\": {\n");
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"allocated\": %zu,\n", huge_allocated);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"nmalloc\": %"FMTu64",\n", huge_nmalloc);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"ndalloc\": %"FMTu64",\n", huge_ndalloc);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"nrequests\": %"FMTu64"\n", huge_nrequests);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t},\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "huge: %12zu %12"FMTu64" %12"FMTu64
- " %12"FMTu64"\n",
- huge_allocated, huge_nmalloc, huge_ndalloc, huge_nrequests);
- malloc_cprintf(write_cb, cbopaque,
- "total: %12zu %12"FMTu64" %12"FMTu64
- " %12"FMTu64"\n",
- small_allocated + large_allocated + huge_allocated,
- small_nmalloc + large_nmalloc + huge_nmalloc,
- small_ndalloc + large_ndalloc + huge_ndalloc,
- small_nrequests + large_nrequests + huge_nrequests);
- }
- if (!json) {
- malloc_cprintf(write_cb, cbopaque,
- "active: %12zu\n", pactive * page);
- }
-
- CTL_M2_GET("stats.arenas.0.mapped", i, &mapped, size_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"mapped\": %zu,\n", mapped);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "mapped: %12zu\n", mapped);
- }
-
- CTL_M2_GET("stats.arenas.0.retained", i, &retained, size_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"retained\": %zu,\n", retained);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "retained: %12zu\n", retained);
- }
-
- CTL_M2_GET("stats.arenas.0.metadata.mapped", i, &metadata_mapped,
- size_t);
- CTL_M2_GET("stats.arenas.0.metadata.allocated", i, &metadata_allocated,
- size_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\"metadata\": {\n");
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"mapped\": %zu,\n", metadata_mapped);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"allocated\": %zu\n", metadata_allocated);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t},\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "metadata: mapped: %zu, allocated: %zu\n",
- metadata_mapped, metadata_allocated);
- }
-
- if (bins) {
- stats_arena_bins_print(write_cb, cbopaque, json, large, huge,
- i);
- }
- if (large)
- stats_arena_lruns_print(write_cb, cbopaque, json, huge, i);
- if (huge)
- stats_arena_hchunks_print(write_cb, cbopaque, json, i);
-}
-
-static void
-stats_general_print(void (*write_cb)(void *, const char *), void *cbopaque,
- bool json, bool merged, bool unmerged)
-{
- const char *cpv;
- bool bv;
- unsigned uv;
- uint32_t u32v;
- uint64_t u64v;
- ssize_t ssv;
- size_t sv, bsz, usz, ssz, sssz, cpsz;
-
- bsz = sizeof(bool);
- usz = sizeof(unsigned);
- ssz = sizeof(size_t);
- sssz = sizeof(ssize_t);
- cpsz = sizeof(const char *);
-
- CTL_GET("version", &cpv, const char *);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\"version\": \"%s\",\n", cpv);
- } else
- malloc_cprintf(write_cb, cbopaque, "Version: %s\n", cpv);
-
- /* config. */
-#define CONFIG_WRITE_BOOL_JSON(n, c) \
- if (json) { \
- CTL_GET("config."#n, &bv, bool); \
- malloc_cprintf(write_cb, cbopaque, \
- "\t\t\t\""#n"\": %s%s\n", bv ? "true" : "false", \
- (c)); \
- }
-
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\"config\": {\n");
- }
-
- CONFIG_WRITE_BOOL_JSON(cache_oblivious, ",")
-
- CTL_GET("config.debug", &bv, bool);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"debug\": %s,\n", bv ? "true" : "false");
- } else {
- malloc_cprintf(write_cb, cbopaque, "Assertions %s\n",
- bv ? "enabled" : "disabled");
- }
-
- CONFIG_WRITE_BOOL_JSON(fill, ",")
- CONFIG_WRITE_BOOL_JSON(lazy_lock, ",")
-
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"malloc_conf\": \"%s\",\n",
- config_malloc_conf);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "config.malloc_conf: \"%s\"\n", config_malloc_conf);
- }
-
- CONFIG_WRITE_BOOL_JSON(munmap, ",")
- CONFIG_WRITE_BOOL_JSON(prof, ",")
- CONFIG_WRITE_BOOL_JSON(prof_libgcc, ",")
- CONFIG_WRITE_BOOL_JSON(prof_libunwind, ",")
- CONFIG_WRITE_BOOL_JSON(stats, ",")
- CONFIG_WRITE_BOOL_JSON(tcache, ",")
- CONFIG_WRITE_BOOL_JSON(tls, ",")
- CONFIG_WRITE_BOOL_JSON(utrace, ",")
- CONFIG_WRITE_BOOL_JSON(valgrind, ",")
- CONFIG_WRITE_BOOL_JSON(xmalloc, "")
-
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t},\n");
- }
-#undef CONFIG_WRITE_BOOL_JSON
-
- /* opt. */
-#define OPT_WRITE_BOOL(n, c) \
- if (je_mallctl("opt."#n, (void *)&bv, &bsz, NULL, 0) == 0) { \
- if (json) { \
- malloc_cprintf(write_cb, cbopaque, \
- "\t\t\t\""#n"\": %s%s\n", bv ? "true" : \
- "false", (c)); \
- } else { \
- malloc_cprintf(write_cb, cbopaque, \
- " opt."#n": %s\n", bv ? "true" : "false"); \
- } \
- }
-#define OPT_WRITE_BOOL_MUTABLE(n, m, c) { \
- bool bv2; \
- if (je_mallctl("opt."#n, (void *)&bv, &bsz, NULL, 0) == 0 && \
- je_mallctl(#m, &bv2, &bsz, NULL, 0) == 0) { \
- if (json) { \
- malloc_cprintf(write_cb, cbopaque, \
- "\t\t\t\""#n"\": %s%s\n", bv ? "true" : \
- "false", (c)); \
- } else { \
- malloc_cprintf(write_cb, cbopaque, \
- " opt."#n": %s ("#m": %s)\n", bv ? "true" \
- : "false", bv2 ? "true" : "false"); \
- } \
- } \
-}
-#define OPT_WRITE_UNSIGNED(n, c) \
- if (je_mallctl("opt."#n, (void *)&uv, &usz, NULL, 0) == 0) { \
- if (json) { \
- malloc_cprintf(write_cb, cbopaque, \
- "\t\t\t\""#n"\": %u%s\n", uv, (c)); \
- } else { \
- malloc_cprintf(write_cb, cbopaque, \
- " opt."#n": %u\n", uv); \
- } \
- }
-#define OPT_WRITE_SIZE_T(n, c) \
- if (je_mallctl("opt."#n, (void *)&sv, &ssz, NULL, 0) == 0) { \
- if (json) { \
- malloc_cprintf(write_cb, cbopaque, \
- "\t\t\t\""#n"\": %zu%s\n", sv, (c)); \
- } else { \
- malloc_cprintf(write_cb, cbopaque, \
- " opt."#n": %zu\n", sv); \
- } \
- }
-#define OPT_WRITE_SSIZE_T(n, c) \
- if (je_mallctl("opt."#n, (void *)&ssv, &sssz, NULL, 0) == 0) { \
- if (json) { \
- malloc_cprintf(write_cb, cbopaque, \
- "\t\t\t\""#n"\": %zd%s\n", ssv, (c)); \
- } else { \
- malloc_cprintf(write_cb, cbopaque, \
- " opt."#n": %zd\n", ssv); \
- } \
- }
-#define OPT_WRITE_SSIZE_T_MUTABLE(n, m, c) { \
- ssize_t ssv2; \
- if (je_mallctl("opt."#n, (void *)&ssv, &sssz, NULL, 0) == 0 && \
- je_mallctl(#m, &ssv2, &sssz, NULL, 0) == 0) { \
- if (json) { \
- malloc_cprintf(write_cb, cbopaque, \
- "\t\t\t\""#n"\": %zd%s\n", ssv, (c)); \
- } else { \
- malloc_cprintf(write_cb, cbopaque, \
- " opt."#n": %zd ("#m": %zd)\n", \
- ssv, ssv2); \
- } \
- } \
-}
-#define OPT_WRITE_CHAR_P(n, c) \
- if (je_mallctl("opt."#n, (void *)&cpv, &cpsz, NULL, 0) == 0) { \
- if (json) { \
- malloc_cprintf(write_cb, cbopaque, \
- "\t\t\t\""#n"\": \"%s\"%s\n", cpv, (c)); \
- } else { \
- malloc_cprintf(write_cb, cbopaque, \
- " opt."#n": \"%s\"\n", cpv); \
- } \
- }
-
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\"opt\": {\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "Run-time option settings:\n");
- }
- OPT_WRITE_BOOL(abort, ",")
- OPT_WRITE_SIZE_T(lg_chunk, ",")
- OPT_WRITE_CHAR_P(dss, ",")
- OPT_WRITE_UNSIGNED(narenas, ",")
- OPT_WRITE_CHAR_P(purge, ",")
- if (json || opt_purge == purge_mode_ratio) {
- OPT_WRITE_SSIZE_T_MUTABLE(lg_dirty_mult,
- arenas.lg_dirty_mult, ",")
- }
- if (json || opt_purge == purge_mode_decay) {
- OPT_WRITE_SSIZE_T_MUTABLE(decay_time, arenas.decay_time, ",")
- }
- OPT_WRITE_CHAR_P(junk, ",")
- OPT_WRITE_SIZE_T(quarantine, ",")
- OPT_WRITE_BOOL(redzone, ",")
- OPT_WRITE_BOOL(zero, ",")
- OPT_WRITE_BOOL(utrace, ",")
- OPT_WRITE_BOOL(xmalloc, ",")
- OPT_WRITE_BOOL(tcache, ",")
- OPT_WRITE_SSIZE_T(lg_tcache_max, ",")
- OPT_WRITE_BOOL(prof, ",")
- OPT_WRITE_CHAR_P(prof_prefix, ",")
- OPT_WRITE_BOOL_MUTABLE(prof_active, prof.active, ",")
- OPT_WRITE_BOOL_MUTABLE(prof_thread_active_init, prof.thread_active_init,
- ",")
- OPT_WRITE_SSIZE_T_MUTABLE(lg_prof_sample, prof.lg_sample, ",")
- OPT_WRITE_BOOL(prof_accum, ",")
- OPT_WRITE_SSIZE_T(lg_prof_interval, ",")
- OPT_WRITE_BOOL(prof_gdump, ",")
- OPT_WRITE_BOOL(prof_final, ",")
- OPT_WRITE_BOOL(prof_leak, ",")
- /*
- * stats_print is always emitted, so as long as stats_print comes last
- * it's safe to unconditionally omit the comma here (rather than having
- * to conditionally omit it elsewhere depending on configuration).
- */
- OPT_WRITE_BOOL(stats_print, "")
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t},\n");
- }
-
-#undef OPT_WRITE_BOOL
-#undef OPT_WRITE_BOOL_MUTABLE
-#undef OPT_WRITE_SIZE_T
-#undef OPT_WRITE_SSIZE_T
-#undef OPT_WRITE_CHAR_P
-
- /* arenas. */
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\"arenas\": {\n");
- }
-
- CTL_GET("arenas.narenas", &uv, unsigned);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"narenas\": %u,\n", uv);
- } else
- malloc_cprintf(write_cb, cbopaque, "Arenas: %u\n", uv);
-
- CTL_GET("arenas.lg_dirty_mult", &ssv, ssize_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"lg_dirty_mult\": %zd,\n", ssv);
- } else if (opt_purge == purge_mode_ratio) {
- if (ssv >= 0) {
- malloc_cprintf(write_cb, cbopaque,
- "Min active:dirty page ratio per arena: "
- "%u:1\n", (1U << ssv));
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "Min active:dirty page ratio per arena: "
- "N/A\n");
- }
- }
- CTL_GET("arenas.decay_time", &ssv, ssize_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"decay_time\": %zd,\n", ssv);
- } else if (opt_purge == purge_mode_decay) {
- malloc_cprintf(write_cb, cbopaque,
- "Unused dirty page decay time: %zd%s\n",
- ssv, (ssv < 0) ? " (no decay)" : "");
- }
-
- CTL_GET("arenas.quantum", &sv, size_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"quantum\": %zu,\n", sv);
- } else
- malloc_cprintf(write_cb, cbopaque, "Quantum size: %zu\n", sv);
-
- CTL_GET("arenas.page", &sv, size_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"page\": %zu,\n", sv);
- } else
- malloc_cprintf(write_cb, cbopaque, "Page size: %zu\n", sv);
-
- if (je_mallctl("arenas.tcache_max", (void *)&sv, &ssz, NULL, 0) == 0) {
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"tcache_max\": %zu,\n", sv);
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "Maximum thread-cached size class: %zu\n", sv);
- }
- }
-
- if (json) {
- unsigned nbins, nlruns, nhchunks, i;
-
- CTL_GET("arenas.nbins", &nbins, unsigned);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"nbins\": %u,\n", nbins);
-
- CTL_GET("arenas.nhbins", &uv, unsigned);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"nhbins\": %u,\n", uv);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"bin\": [\n");
- for (i = 0; i < nbins; i++) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t{\n");
-
- CTL_M2_GET("arenas.bin.0.size", i, &sv, size_t);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"size\": %zu,\n", sv);
-
- CTL_M2_GET("arenas.bin.0.nregs", i, &u32v, uint32_t);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"nregs\": %"FMTu32",\n", u32v);
-
- CTL_M2_GET("arenas.bin.0.run_size", i, &sv, size_t);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"run_size\": %zu\n", sv);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t}%s\n", (i + 1 < nbins) ? "," : "");
- }
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t],\n");
-
- CTL_GET("arenas.nlruns", &nlruns, unsigned);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"nlruns\": %u,\n", nlruns);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"lrun\": [\n");
- for (i = 0; i < nlruns; i++) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t{\n");
-
- CTL_M2_GET("arenas.lrun.0.size", i, &sv, size_t);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"size\": %zu\n", sv);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t}%s\n", (i + 1 < nlruns) ? "," : "");
- }
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t],\n");
-
- CTL_GET("arenas.nhchunks", &nhchunks, unsigned);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"nhchunks\": %u,\n", nhchunks);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"hchunk\": [\n");
- for (i = 0; i < nhchunks; i++) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t{\n");
-
- CTL_M2_GET("arenas.hchunk.0.size", i, &sv, size_t);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t\t\"size\": %zu\n", sv);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\t}%s\n", (i + 1 < nhchunks) ? "," : "");
- }
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t]\n");
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t},\n");
- }
-
- /* prof. */
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\"prof\": {\n");
-
- CTL_GET("prof.thread_active_init", &bv, bool);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"thread_active_init\": %s,\n", bv ? "true" :
- "false");
-
- CTL_GET("prof.active", &bv, bool);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"active\": %s,\n", bv ? "true" : "false");
-
- CTL_GET("prof.gdump", &bv, bool);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"gdump\": %s,\n", bv ? "true" : "false");
-
- CTL_GET("prof.interval", &u64v, uint64_t);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"interval\": %"FMTu64",\n", u64v);
-
- CTL_GET("prof.lg_sample", &ssv, ssize_t);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"lg_sample\": %zd\n", ssv);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t}%s\n", (config_stats || merged || unmerged) ? "," :
- "");
- }
-}
-
-static void
-stats_print_helper(void (*write_cb)(void *, const char *), void *cbopaque,
- bool json, bool merged, bool unmerged, bool bins, bool large, bool huge)
-{
- size_t *cactive;
- size_t allocated, active, metadata, resident, mapped, retained;
-
- CTL_GET("stats.cactive", &cactive, size_t *);
- CTL_GET("stats.allocated", &allocated, size_t);
- CTL_GET("stats.active", &active, size_t);
- CTL_GET("stats.metadata", &metadata, size_t);
- CTL_GET("stats.resident", &resident, size_t);
- CTL_GET("stats.mapped", &mapped, size_t);
- CTL_GET("stats.retained", &retained, size_t);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\"stats\": {\n");
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"cactive\": %zu,\n", atomic_read_z(cactive));
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"allocated\": %zu,\n", allocated);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"active\": %zu,\n", active);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"metadata\": %zu,\n", metadata);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"resident\": %zu,\n", resident);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"mapped\": %zu,\n", mapped);
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"retained\": %zu\n", retained);
-
- malloc_cprintf(write_cb, cbopaque,
- "\t\t}%s\n", (merged || unmerged) ? "," : "");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "Allocated: %zu, active: %zu, metadata: %zu,"
- " resident: %zu, mapped: %zu, retained: %zu\n",
- allocated, active, metadata, resident, mapped, retained);
- malloc_cprintf(write_cb, cbopaque,
- "Current active ceiling: %zu\n",
- atomic_read_z(cactive));
- }
-
- if (merged || unmerged) {
- unsigned narenas;
-
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\"stats.arenas\": {\n");
- }
-
- CTL_GET("arenas.narenas", &narenas, unsigned);
- {
- VARIABLE_ARRAY(bool, initialized, narenas);
- size_t isz;
- unsigned i, j, ninitialized;
-
- isz = sizeof(bool) * narenas;
- xmallctl("arenas.initialized", (void *)initialized,
- &isz, NULL, 0);
- for (i = ninitialized = 0; i < narenas; i++) {
- if (initialized[i])
- ninitialized++;
- }
-
- /* Merged stats. */
- if (merged && (ninitialized > 1 || !unmerged)) {
- /* Print merged arena stats. */
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t\"merged\": {\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "\nMerged arenas stats:\n");
- }
- stats_arena_print(write_cb, cbopaque, json,
- narenas, bins, large, huge);
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t\t}%s\n", (ninitialized > 1) ?
- "," : "");
- }
- }
-
- /* Unmerged stats. */
- for (i = j = 0; i < narenas; i++) {
- if (initialized[i]) {
- if (json) {
- j++;
- malloc_cprintf(write_cb,
- cbopaque,
- "\t\t\t\"%u\": {\n", i);
- } else {
- malloc_cprintf(write_cb,
- cbopaque, "\narenas[%u]:\n",
- i);
- }
- stats_arena_print(write_cb, cbopaque,
- json, i, bins, large, huge);
- if (json) {
- malloc_cprintf(write_cb,
- cbopaque,
- "\t\t\t}%s\n", (j <
- ninitialized) ? "," : "");
- }
- }
- }
- }
-
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t\t}\n");
- }
- }
-}
-
-void
-stats_print(void (*write_cb)(void *, const char *), void *cbopaque,
- const char *opts)
-{
- int err;
- uint64_t epoch;
- size_t u64sz;
- bool json = false;
- bool general = true;
- bool merged = true;
- bool unmerged = true;
- bool bins = true;
- bool large = true;
- bool huge = true;
-
- /*
- * Refresh stats, in case mallctl() was called by the application.
- *
- * Check for OOM here, since refreshing the ctl cache can trigger
- * allocation. In practice, none of the subsequent mallctl()-related
- * calls in this function will cause OOM if this one succeeds.
- * */
- epoch = 1;
- u64sz = sizeof(uint64_t);
- err = je_mallctl("epoch", &epoch, &u64sz, &epoch, sizeof(uint64_t));
- if (err != 0) {
- if (err == EAGAIN) {
- malloc_write("<jemalloc>: Memory allocation failure in "
- "mallctl(\"epoch\", ...)\n");
- return;
- }
- malloc_write("<jemalloc>: Failure in mallctl(\"epoch\", "
- "...)\n");
- abort();
- }
-
- if (opts != NULL) {
- unsigned i;
-
- for (i = 0; opts[i] != '\0'; i++) {
- switch (opts[i]) {
- case 'J':
- json = true;
- break;
- case 'g':
- general = false;
- break;
- case 'm':
- merged = false;
- break;
- case 'a':
- unmerged = false;
- break;
- case 'b':
- bins = false;
- break;
- case 'l':
- large = false;
- break;
- case 'h':
- huge = false;
- break;
- default:;
- }
- }
- }
-
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "{\n"
- "\t\"jemalloc\": {\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "___ Begin jemalloc statistics ___\n");
- }
-
- if (general)
- stats_general_print(write_cb, cbopaque, json, merged, unmerged);
- if (config_stats) {
- stats_print_helper(write_cb, cbopaque, json, merged, unmerged,
- bins, large, huge);
- }
- if (json) {
- malloc_cprintf(write_cb, cbopaque,
- "\t}\n"
- "}\n");
- } else {
- malloc_cprintf(write_cb, cbopaque,
- "--- End jemalloc statistics ---\n");
- }
-}
diff --git a/memory/jemalloc/src/src/tcache.c b/memory/jemalloc/src/src/tcache.c
deleted file mode 100644
index f97aa420c..000000000
--- a/memory/jemalloc/src/src/tcache.c
+++ /dev/null
@@ -1,555 +0,0 @@
-#define JEMALLOC_TCACHE_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Data. */
-
-bool opt_tcache = true;
-ssize_t opt_lg_tcache_max = LG_TCACHE_MAXCLASS_DEFAULT;
-
-tcache_bin_info_t *tcache_bin_info;
-static unsigned stack_nelms; /* Total stack elms per tcache. */
-
-unsigned nhbins;
-size_t tcache_maxclass;
-
-tcaches_t *tcaches;
-
-/* Index of first element within tcaches that has never been used. */
-static unsigned tcaches_past;
-
-/* Head of singly linked list tracking available tcaches elements. */
-static tcaches_t *tcaches_avail;
-
-/******************************************************************************/
-
-size_t
-tcache_salloc(tsdn_t *tsdn, const void *ptr)
-{
-
- return (arena_salloc(tsdn, ptr, false));
-}
-
-void
-tcache_event_hard(tsd_t *tsd, tcache_t *tcache)
-{
- szind_t binind = tcache->next_gc_bin;
- tcache_bin_t *tbin = &tcache->tbins[binind];
- tcache_bin_info_t *tbin_info = &tcache_bin_info[binind];
-
- if (tbin->low_water > 0) {
- /*
- * Flush (ceiling) 3/4 of the objects below the low water mark.
- */
- if (binind < NBINS) {
- tcache_bin_flush_small(tsd, tcache, tbin, binind,
- tbin->ncached - tbin->low_water + (tbin->low_water
- >> 2));
- } else {
- tcache_bin_flush_large(tsd, tbin, binind, tbin->ncached
- - tbin->low_water + (tbin->low_water >> 2), tcache);
- }
- /*
- * Reduce fill count by 2X. Limit lg_fill_div such that the
- * fill count is always at least 1.
- */
- if ((tbin_info->ncached_max >> (tbin->lg_fill_div+1)) >= 1)
- tbin->lg_fill_div++;
- } else if (tbin->low_water < 0) {
- /*
- * Increase fill count by 2X. Make sure lg_fill_div stays
- * greater than 0.
- */
- if (tbin->lg_fill_div > 1)
- tbin->lg_fill_div--;
- }
- tbin->low_water = tbin->ncached;
-
- tcache->next_gc_bin++;
- if (tcache->next_gc_bin == nhbins)
- tcache->next_gc_bin = 0;
-}
-
-void *
-tcache_alloc_small_hard(tsdn_t *tsdn, arena_t *arena, tcache_t *tcache,
- tcache_bin_t *tbin, szind_t binind, bool *tcache_success)
-{
- void *ret;
-
- arena_tcache_fill_small(tsdn, arena, tbin, binind, config_prof ?
- tcache->prof_accumbytes : 0);
- if (config_prof)
- tcache->prof_accumbytes = 0;
- ret = tcache_alloc_easy(tbin, tcache_success);
-
- return (ret);
-}
-
-void
-tcache_bin_flush_small(tsd_t *tsd, tcache_t *tcache, tcache_bin_t *tbin,
- szind_t binind, unsigned rem)
-{
- arena_t *arena;
- void *ptr;
- unsigned i, nflush, ndeferred;
- bool merged_stats = false;
-
- assert(binind < NBINS);
- assert(rem <= tbin->ncached);
-
- arena = arena_choose(tsd, NULL);
- assert(arena != NULL);
- for (nflush = tbin->ncached - rem; nflush > 0; nflush = ndeferred) {
- /* Lock the arena bin associated with the first object. */
- arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(
- *(tbin->avail - 1));
- arena_t *bin_arena = extent_node_arena_get(&chunk->node);
- arena_bin_t *bin = &bin_arena->bins[binind];
-
- if (config_prof && bin_arena == arena) {
- if (arena_prof_accum(tsd_tsdn(tsd), arena,
- tcache->prof_accumbytes))
- prof_idump(tsd_tsdn(tsd));
- tcache->prof_accumbytes = 0;
- }
-
- malloc_mutex_lock(tsd_tsdn(tsd), &bin->lock);
- if (config_stats && bin_arena == arena) {
- assert(!merged_stats);
- merged_stats = true;
- bin->stats.nflushes++;
- bin->stats.nrequests += tbin->tstats.nrequests;
- tbin->tstats.nrequests = 0;
- }
- ndeferred = 0;
- for (i = 0; i < nflush; i++) {
- ptr = *(tbin->avail - 1 - i);
- assert(ptr != NULL);
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (extent_node_arena_get(&chunk->node) == bin_arena) {
- size_t pageind = ((uintptr_t)ptr -
- (uintptr_t)chunk) >> LG_PAGE;
- arena_chunk_map_bits_t *bitselm =
- arena_bitselm_get_mutable(chunk, pageind);
- arena_dalloc_bin_junked_locked(tsd_tsdn(tsd),
- bin_arena, chunk, ptr, bitselm);
- } else {
- /*
- * This object was allocated via a different
- * arena bin than the one that is currently
- * locked. Stash the object, so that it can be
- * handled in a future pass.
- */
- *(tbin->avail - 1 - ndeferred) = ptr;
- ndeferred++;
- }
- }
- malloc_mutex_unlock(tsd_tsdn(tsd), &bin->lock);
- arena_decay_ticks(tsd_tsdn(tsd), bin_arena, nflush - ndeferred);
- }
- if (config_stats && !merged_stats) {
- /*
- * The flush loop didn't happen to flush to this thread's
- * arena, so the stats didn't get merged. Manually do so now.
- */
- arena_bin_t *bin = &arena->bins[binind];
- malloc_mutex_lock(tsd_tsdn(tsd), &bin->lock);
- bin->stats.nflushes++;
- bin->stats.nrequests += tbin->tstats.nrequests;
- tbin->tstats.nrequests = 0;
- malloc_mutex_unlock(tsd_tsdn(tsd), &bin->lock);
- }
-
- memmove(tbin->avail - rem, tbin->avail - tbin->ncached, rem *
- sizeof(void *));
- tbin->ncached = rem;
- if ((int)tbin->ncached < tbin->low_water)
- tbin->low_water = tbin->ncached;
-}
-
-void
-tcache_bin_flush_large(tsd_t *tsd, tcache_bin_t *tbin, szind_t binind,
- unsigned rem, tcache_t *tcache)
-{
- arena_t *arena;
- void *ptr;
- unsigned i, nflush, ndeferred;
- bool merged_stats = false;
-
- assert(binind < nhbins);
- assert(rem <= tbin->ncached);
-
- arena = arena_choose(tsd, NULL);
- assert(arena != NULL);
- for (nflush = tbin->ncached - rem; nflush > 0; nflush = ndeferred) {
- /* Lock the arena associated with the first object. */
- arena_chunk_t *chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(
- *(tbin->avail - 1));
- arena_t *locked_arena = extent_node_arena_get(&chunk->node);
- UNUSED bool idump;
-
- if (config_prof)
- idump = false;
- malloc_mutex_lock(tsd_tsdn(tsd), &locked_arena->lock);
- if ((config_prof || config_stats) && locked_arena == arena) {
- if (config_prof) {
- idump = arena_prof_accum_locked(arena,
- tcache->prof_accumbytes);
- tcache->prof_accumbytes = 0;
- }
- if (config_stats) {
- merged_stats = true;
- arena->stats.nrequests_large +=
- tbin->tstats.nrequests;
- arena->stats.lstats[binind - NBINS].nrequests +=
- tbin->tstats.nrequests;
- tbin->tstats.nrequests = 0;
- }
- }
- ndeferred = 0;
- for (i = 0; i < nflush; i++) {
- ptr = *(tbin->avail - 1 - i);
- assert(ptr != NULL);
- chunk = (arena_chunk_t *)CHUNK_ADDR2BASE(ptr);
- if (extent_node_arena_get(&chunk->node) ==
- locked_arena) {
- arena_dalloc_large_junked_locked(tsd_tsdn(tsd),
- locked_arena, chunk, ptr);
- } else {
- /*
- * This object was allocated via a different
- * arena than the one that is currently locked.
- * Stash the object, so that it can be handled
- * in a future pass.
- */
- *(tbin->avail - 1 - ndeferred) = ptr;
- ndeferred++;
- }
- }
- malloc_mutex_unlock(tsd_tsdn(tsd), &locked_arena->lock);
- if (config_prof && idump)
- prof_idump(tsd_tsdn(tsd));
- arena_decay_ticks(tsd_tsdn(tsd), locked_arena, nflush -
- ndeferred);
- }
- if (config_stats && !merged_stats) {
- /*
- * The flush loop didn't happen to flush to this thread's
- * arena, so the stats didn't get merged. Manually do so now.
- */
- malloc_mutex_lock(tsd_tsdn(tsd), &arena->lock);
- arena->stats.nrequests_large += tbin->tstats.nrequests;
- arena->stats.lstats[binind - NBINS].nrequests +=
- tbin->tstats.nrequests;
- tbin->tstats.nrequests = 0;
- malloc_mutex_unlock(tsd_tsdn(tsd), &arena->lock);
- }
-
- memmove(tbin->avail - rem, tbin->avail - tbin->ncached, rem *
- sizeof(void *));
- tbin->ncached = rem;
- if ((int)tbin->ncached < tbin->low_water)
- tbin->low_water = tbin->ncached;
-}
-
-static void
-tcache_arena_associate(tsdn_t *tsdn, tcache_t *tcache, arena_t *arena)
-{
-
- if (config_stats) {
- /* Link into list of extant tcaches. */
- malloc_mutex_lock(tsdn, &arena->lock);
- ql_elm_new(tcache, link);
- ql_tail_insert(&arena->tcache_ql, tcache, link);
- malloc_mutex_unlock(tsdn, &arena->lock);
- }
-}
-
-static void
-tcache_arena_dissociate(tsdn_t *tsdn, tcache_t *tcache, arena_t *arena)
-{
-
- if (config_stats) {
- /* Unlink from list of extant tcaches. */
- malloc_mutex_lock(tsdn, &arena->lock);
- if (config_debug) {
- bool in_ql = false;
- tcache_t *iter;
- ql_foreach(iter, &arena->tcache_ql, link) {
- if (iter == tcache) {
- in_ql = true;
- break;
- }
- }
- assert(in_ql);
- }
- ql_remove(&arena->tcache_ql, tcache, link);
- tcache_stats_merge(tsdn, tcache, arena);
- malloc_mutex_unlock(tsdn, &arena->lock);
- }
-}
-
-void
-tcache_arena_reassociate(tsdn_t *tsdn, tcache_t *tcache, arena_t *oldarena,
- arena_t *newarena)
-{
-
- tcache_arena_dissociate(tsdn, tcache, oldarena);
- tcache_arena_associate(tsdn, tcache, newarena);
-}
-
-tcache_t *
-tcache_get_hard(tsd_t *tsd)
-{
- arena_t *arena;
-
- if (!tcache_enabled_get()) {
- if (tsd_nominal(tsd))
- tcache_enabled_set(false); /* Memoize. */
- return (NULL);
- }
- arena = arena_choose(tsd, NULL);
- if (unlikely(arena == NULL))
- return (NULL);
- return (tcache_create(tsd_tsdn(tsd), arena));
-}
-
-tcache_t *
-tcache_create(tsdn_t *tsdn, arena_t *arena)
-{
- tcache_t *tcache;
- size_t size, stack_offset;
- unsigned i;
-
- size = offsetof(tcache_t, tbins) + (sizeof(tcache_bin_t) * nhbins);
- /* Naturally align the pointer stacks. */
- size = PTR_CEILING(size);
- stack_offset = size;
- size += stack_nelms * sizeof(void *);
- /* Avoid false cacheline sharing. */
- size = sa2u(size, CACHELINE);
-
- tcache = ipallocztm(tsdn, size, CACHELINE, true, NULL, true,
- arena_get(TSDN_NULL, 0, true));
- if (tcache == NULL)
- return (NULL);
-
- tcache_arena_associate(tsdn, tcache, arena);
-
- ticker_init(&tcache->gc_ticker, TCACHE_GC_INCR);
-
- assert((TCACHE_NSLOTS_SMALL_MAX & 1U) == 0);
- for (i = 0; i < nhbins; i++) {
- tcache->tbins[i].lg_fill_div = 1;
- stack_offset += tcache_bin_info[i].ncached_max * sizeof(void *);
- /*
- * avail points past the available space. Allocations will
- * access the slots toward higher addresses (for the benefit of
- * prefetch).
- */
- tcache->tbins[i].avail = (void **)((uintptr_t)tcache +
- (uintptr_t)stack_offset);
- }
-
- return (tcache);
-}
-
-static void
-tcache_destroy(tsd_t *tsd, tcache_t *tcache)
-{
- arena_t *arena;
- unsigned i;
-
- arena = arena_choose(tsd, NULL);
- tcache_arena_dissociate(tsd_tsdn(tsd), tcache, arena);
-
- for (i = 0; i < NBINS; i++) {
- tcache_bin_t *tbin = &tcache->tbins[i];
- tcache_bin_flush_small(tsd, tcache, tbin, i, 0);
-
- if (config_stats && tbin->tstats.nrequests != 0) {
- arena_bin_t *bin = &arena->bins[i];
- malloc_mutex_lock(tsd_tsdn(tsd), &bin->lock);
- bin->stats.nrequests += tbin->tstats.nrequests;
- malloc_mutex_unlock(tsd_tsdn(tsd), &bin->lock);
- }
- }
-
- for (; i < nhbins; i++) {
- tcache_bin_t *tbin = &tcache->tbins[i];
- tcache_bin_flush_large(tsd, tbin, i, 0, tcache);
-
- if (config_stats && tbin->tstats.nrequests != 0) {
- malloc_mutex_lock(tsd_tsdn(tsd), &arena->lock);
- arena->stats.nrequests_large += tbin->tstats.nrequests;
- arena->stats.lstats[i - NBINS].nrequests +=
- tbin->tstats.nrequests;
- malloc_mutex_unlock(tsd_tsdn(tsd), &arena->lock);
- }
- }
-
- if (config_prof && tcache->prof_accumbytes > 0 &&
- arena_prof_accum(tsd_tsdn(tsd), arena, tcache->prof_accumbytes))
- prof_idump(tsd_tsdn(tsd));
-
- idalloctm(tsd_tsdn(tsd), tcache, NULL, true, true);
-}
-
-void
-tcache_cleanup(tsd_t *tsd)
-{
- tcache_t *tcache;
-
- if (!config_tcache)
- return;
-
- if ((tcache = tsd_tcache_get(tsd)) != NULL) {
- tcache_destroy(tsd, tcache);
- tsd_tcache_set(tsd, NULL);
- }
-}
-
-void
-tcache_enabled_cleanup(tsd_t *tsd)
-{
-
- /* Do nothing. */
-}
-
-void
-tcache_stats_merge(tsdn_t *tsdn, tcache_t *tcache, arena_t *arena)
-{
- unsigned i;
-
- cassert(config_stats);
-
- malloc_mutex_assert_owner(tsdn, &arena->lock);
-
- /* Merge and reset tcache stats. */
- for (i = 0; i < NBINS; i++) {
- arena_bin_t *bin = &arena->bins[i];
- tcache_bin_t *tbin = &tcache->tbins[i];
- malloc_mutex_lock(tsdn, &bin->lock);
- bin->stats.nrequests += tbin->tstats.nrequests;
- malloc_mutex_unlock(tsdn, &bin->lock);
- tbin->tstats.nrequests = 0;
- }
-
- for (; i < nhbins; i++) {
- malloc_large_stats_t *lstats = &arena->stats.lstats[i - NBINS];
- tcache_bin_t *tbin = &tcache->tbins[i];
- arena->stats.nrequests_large += tbin->tstats.nrequests;
- lstats->nrequests += tbin->tstats.nrequests;
- tbin->tstats.nrequests = 0;
- }
-}
-
-bool
-tcaches_create(tsd_t *tsd, unsigned *r_ind)
-{
- arena_t *arena;
- tcache_t *tcache;
- tcaches_t *elm;
-
- if (tcaches == NULL) {
- tcaches = base_alloc(tsd_tsdn(tsd), sizeof(tcache_t *) *
- (MALLOCX_TCACHE_MAX+1));
- if (tcaches == NULL)
- return (true);
- }
-
- if (tcaches_avail == NULL && tcaches_past > MALLOCX_TCACHE_MAX)
- return (true);
- arena = arena_ichoose(tsd, NULL);
- if (unlikely(arena == NULL))
- return (true);
- tcache = tcache_create(tsd_tsdn(tsd), arena);
- if (tcache == NULL)
- return (true);
-
- if (tcaches_avail != NULL) {
- elm = tcaches_avail;
- tcaches_avail = tcaches_avail->next;
- elm->tcache = tcache;
- *r_ind = (unsigned)(elm - tcaches);
- } else {
- elm = &tcaches[tcaches_past];
- elm->tcache = tcache;
- *r_ind = tcaches_past;
- tcaches_past++;
- }
-
- return (false);
-}
-
-static void
-tcaches_elm_flush(tsd_t *tsd, tcaches_t *elm)
-{
-
- if (elm->tcache == NULL)
- return;
- tcache_destroy(tsd, elm->tcache);
- elm->tcache = NULL;
-}
-
-void
-tcaches_flush(tsd_t *tsd, unsigned ind)
-{
-
- tcaches_elm_flush(tsd, &tcaches[ind]);
-}
-
-void
-tcaches_destroy(tsd_t *tsd, unsigned ind)
-{
- tcaches_t *elm = &tcaches[ind];
- tcaches_elm_flush(tsd, elm);
- elm->next = tcaches_avail;
- tcaches_avail = elm;
-}
-
-bool
-tcache_boot(tsdn_t *tsdn)
-{
- unsigned i;
-
- /*
- * If necessary, clamp opt_lg_tcache_max, now that large_maxclass is
- * known.
- */
- if (opt_lg_tcache_max < 0 || (1U << opt_lg_tcache_max) < SMALL_MAXCLASS)
- tcache_maxclass = SMALL_MAXCLASS;
- else if ((1U << opt_lg_tcache_max) > large_maxclass)
- tcache_maxclass = large_maxclass;
- else
- tcache_maxclass = (1U << opt_lg_tcache_max);
-
- nhbins = size2index(tcache_maxclass) + 1;
-
- /* Initialize tcache_bin_info. */
- tcache_bin_info = (tcache_bin_info_t *)base_alloc(tsdn, nhbins *
- sizeof(tcache_bin_info_t));
- if (tcache_bin_info == NULL)
- return (true);
- stack_nelms = 0;
- for (i = 0; i < NBINS; i++) {
- if ((arena_bin_info[i].nregs << 1) <= TCACHE_NSLOTS_SMALL_MIN) {
- tcache_bin_info[i].ncached_max =
- TCACHE_NSLOTS_SMALL_MIN;
- } else if ((arena_bin_info[i].nregs << 1) <=
- TCACHE_NSLOTS_SMALL_MAX) {
- tcache_bin_info[i].ncached_max =
- (arena_bin_info[i].nregs << 1);
- } else {
- tcache_bin_info[i].ncached_max =
- TCACHE_NSLOTS_SMALL_MAX;
- }
- stack_nelms += tcache_bin_info[i].ncached_max;
- }
- for (; i < nhbins; i++) {
- tcache_bin_info[i].ncached_max = TCACHE_NSLOTS_LARGE;
- stack_nelms += tcache_bin_info[i].ncached_max;
- }
-
- return (false);
-}
diff --git a/memory/jemalloc/src/src/ticker.c b/memory/jemalloc/src/src/ticker.c
deleted file mode 100644
index db0902404..000000000
--- a/memory/jemalloc/src/src/ticker.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#define JEMALLOC_TICKER_C_
-#include "jemalloc/internal/jemalloc_internal.h"
diff --git a/memory/jemalloc/src/src/tsd.c b/memory/jemalloc/src/src/tsd.c
deleted file mode 100644
index ec69a51c3..000000000
--- a/memory/jemalloc/src/src/tsd.c
+++ /dev/null
@@ -1,197 +0,0 @@
-#define JEMALLOC_TSD_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Data. */
-
-static unsigned ncleanups;
-static malloc_tsd_cleanup_t cleanups[MALLOC_TSD_CLEANUPS_MAX];
-
-malloc_tsd_data(, , tsd_t, TSD_INITIALIZER)
-
-/******************************************************************************/
-
-void *
-malloc_tsd_malloc(size_t size)
-{
-
- return (a0malloc(CACHELINE_CEILING(size)));
-}
-
-void
-malloc_tsd_dalloc(void *wrapper)
-{
-
- a0dalloc(wrapper);
-}
-
-void
-malloc_tsd_no_cleanup(void *arg)
-{
-
- not_reached();
-}
-
-#if defined(JEMALLOC_MALLOC_THREAD_CLEANUP) || defined(_WIN32)
-#ifndef _WIN32
-JEMALLOC_EXPORT
-#endif
-void
-_malloc_thread_cleanup(void)
-{
- bool pending[MALLOC_TSD_CLEANUPS_MAX], again;
- unsigned i;
-
- for (i = 0; i < ncleanups; i++)
- pending[i] = true;
-
- do {
- again = false;
- for (i = 0; i < ncleanups; i++) {
- if (pending[i]) {
- pending[i] = cleanups[i]();
- if (pending[i])
- again = true;
- }
- }
- } while (again);
-}
-#endif
-
-void
-malloc_tsd_cleanup_register(bool (*f)(void))
-{
-
- assert(ncleanups < MALLOC_TSD_CLEANUPS_MAX);
- cleanups[ncleanups] = f;
- ncleanups++;
-}
-
-void
-tsd_cleanup(void *arg)
-{
- tsd_t *tsd = (tsd_t *)arg;
-
- switch (tsd->state) {
- case tsd_state_uninitialized:
- /* Do nothing. */
- break;
- case tsd_state_nominal:
-#define O(n, t) \
- n##_cleanup(tsd);
-MALLOC_TSD
-#undef O
- tsd->state = tsd_state_purgatory;
- tsd_set(tsd);
- break;
- case tsd_state_purgatory:
- /*
- * The previous time this destructor was called, we set the
- * state to tsd_state_purgatory so that other destructors
- * wouldn't cause re-creation of the tsd. This time, do
- * nothing, and do not request another callback.
- */
- break;
- case tsd_state_reincarnated:
- /*
- * Another destructor deallocated memory after this destructor
- * was called. Reset state to tsd_state_purgatory and request
- * another callback.
- */
- tsd->state = tsd_state_purgatory;
- tsd_set(tsd);
- break;
- default:
- not_reached();
- }
-}
-
-tsd_t *
-malloc_tsd_boot0(void)
-{
- tsd_t *tsd;
-
- ncleanups = 0;
- if (tsd_boot0())
- return (NULL);
- tsd = tsd_fetch();
- *tsd_arenas_tdata_bypassp_get(tsd) = true;
- return (tsd);
-}
-
-void
-malloc_tsd_boot1(void)
-{
-
- tsd_boot1();
- *tsd_arenas_tdata_bypassp_get(tsd_fetch()) = false;
-}
-
-#ifdef _WIN32
-static BOOL WINAPI
-_tls_callback(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
-{
-
- switch (fdwReason) {
-#ifdef JEMALLOC_LAZY_LOCK
- case DLL_THREAD_ATTACH:
- isthreaded = true;
- break;
-#endif
- case DLL_THREAD_DETACH:
- _malloc_thread_cleanup();
- break;
- default:
- break;
- }
- return (true);
-}
-
-#ifdef _MSC_VER
-# ifdef _M_IX86
-# pragma comment(linker, "/INCLUDE:__tls_used")
-# pragma comment(linker, "/INCLUDE:_tls_callback")
-# else
-# pragma comment(linker, "/INCLUDE:_tls_used")
-# pragma comment(linker, "/INCLUDE:tls_callback")
-# endif
-# pragma section(".CRT$XLY",long,read)
-#endif
-JEMALLOC_SECTION(".CRT$XLY") JEMALLOC_ATTR(used)
-BOOL (WINAPI *const tls_callback)(HINSTANCE hinstDLL,
- DWORD fdwReason, LPVOID lpvReserved) = _tls_callback;
-#endif
-
-#if (!defined(JEMALLOC_MALLOC_THREAD_CLEANUP) && !defined(JEMALLOC_TLS) && \
- !defined(_WIN32))
-void *
-tsd_init_check_recursion(tsd_init_head_t *head, tsd_init_block_t *block)
-{
- pthread_t self = pthread_self();
- tsd_init_block_t *iter;
-
- /* Check whether this thread has already inserted into the list. */
- malloc_mutex_lock(TSDN_NULL, &head->lock);
- ql_foreach(iter, &head->blocks, link) {
- if (iter->thread == self) {
- malloc_mutex_unlock(TSDN_NULL, &head->lock);
- return (iter->data);
- }
- }
- /* Insert block into list. */
- ql_elm_new(block, link);
- block->thread = self;
- ql_tail_insert(&head->blocks, block, link);
- malloc_mutex_unlock(TSDN_NULL, &head->lock);
- return (NULL);
-}
-
-void
-tsd_init_finish(tsd_init_head_t *head, tsd_init_block_t *block)
-{
-
- malloc_mutex_lock(TSDN_NULL, &head->lock);
- ql_remove(&head->blocks, block, link);
- malloc_mutex_unlock(TSDN_NULL, &head->lock);
-}
-#endif
diff --git a/memory/jemalloc/src/src/util.c b/memory/jemalloc/src/src/util.c
deleted file mode 100644
index 79052674f..000000000
--- a/memory/jemalloc/src/src/util.c
+++ /dev/null
@@ -1,666 +0,0 @@
-/*
- * Define simple versions of assertion macros that won't recurse in case
- * of assertion failures in malloc_*printf().
- */
-#define assert(e) do { \
- if (config_debug && !(e)) { \
- malloc_write("<jemalloc>: Failed assertion\n"); \
- abort(); \
- } \
-} while (0)
-
-#define not_reached() do { \
- if (config_debug) { \
- malloc_write("<jemalloc>: Unreachable code reached\n"); \
- abort(); \
- } \
- unreachable(); \
-} while (0)
-
-#define not_implemented() do { \
- if (config_debug) { \
- malloc_write("<jemalloc>: Not implemented\n"); \
- abort(); \
- } \
-} while (0)
-
-#define JEMALLOC_UTIL_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/* Function prototypes for non-inline static functions. */
-
-static void wrtmessage(void *cbopaque, const char *s);
-#define U2S_BUFSIZE ((1U << (LG_SIZEOF_INTMAX_T + 3)) + 1)
-static char *u2s(uintmax_t x, unsigned base, bool uppercase, char *s,
- size_t *slen_p);
-#define D2S_BUFSIZE (1 + U2S_BUFSIZE)
-static char *d2s(intmax_t x, char sign, char *s, size_t *slen_p);
-#define O2S_BUFSIZE (1 + U2S_BUFSIZE)
-static char *o2s(uintmax_t x, bool alt_form, char *s, size_t *slen_p);
-#define X2S_BUFSIZE (2 + U2S_BUFSIZE)
-static char *x2s(uintmax_t x, bool alt_form, bool uppercase, char *s,
- size_t *slen_p);
-
-/******************************************************************************/
-
-/* malloc_message() setup. */
-static void
-wrtmessage(void *cbopaque, const char *s)
-{
-
-#if defined(JEMALLOC_HAVE_SYSCALL) && defined(SYS_write)
- /*
- * Use syscall(2) rather than write(2) when possible in order to avoid
- * the possibility of memory allocation within libc. This is necessary
- * on FreeBSD; most operating systems do not have this problem though.
- *
- * syscall() returns long or int, depending on platform, so capture the
- * unused result in the widest plausible type to avoid compiler
- * warnings.
- */
- UNUSED long result = syscall(SYS_write, STDERR_FILENO, s, strlen(s));
-#else
- UNUSED ssize_t result = write(STDERR_FILENO, s, strlen(s));
-#endif
-}
-
-JEMALLOC_EXPORT void (*je_malloc_message)(void *, const char *s);
-
-/*
- * Wrapper around malloc_message() that avoids the need for
- * je_malloc_message(...) throughout the code.
- */
-void
-malloc_write(const char *s)
-{
-
- if (je_malloc_message != NULL)
- je_malloc_message(NULL, s);
- else
- wrtmessage(NULL, s);
-}
-
-/*
- * glibc provides a non-standard strerror_r() when _GNU_SOURCE is defined, so
- * provide a wrapper.
- */
-int
-buferror(int err, char *buf, size_t buflen)
-{
-
-#ifdef _WIN32
- FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
- (LPSTR)buf, (DWORD)buflen, NULL);
- return (0);
-#elif defined(__GLIBC__) && defined(_GNU_SOURCE)
- char *b = strerror_r(err, buf, buflen);
- if (b != buf) {
- strncpy(buf, b, buflen);
- buf[buflen-1] = '\0';
- }
- return (0);
-#else
- return (strerror_r(err, buf, buflen));
-#endif
-}
-
-uintmax_t
-malloc_strtoumax(const char *restrict nptr, char **restrict endptr, int base)
-{
- uintmax_t ret, digit;
- unsigned b;
- bool neg;
- const char *p, *ns;
-
- p = nptr;
- if (base < 0 || base == 1 || base > 36) {
- ns = p;
- set_errno(EINVAL);
- ret = UINTMAX_MAX;
- goto label_return;
- }
- b = base;
-
- /* Swallow leading whitespace and get sign, if any. */
- neg = false;
- while (true) {
- switch (*p) {
- case '\t': case '\n': case '\v': case '\f': case '\r': case ' ':
- p++;
- break;
- case '-':
- neg = true;
- /* Fall through. */
- case '+':
- p++;
- /* Fall through. */
- default:
- goto label_prefix;
- }
- }
-
- /* Get prefix, if any. */
- label_prefix:
- /*
- * Note where the first non-whitespace/sign character is so that it is
- * possible to tell whether any digits are consumed (e.g., " 0" vs.
- * " -x").
- */
- ns = p;
- if (*p == '0') {
- switch (p[1]) {
- case '0': case '1': case '2': case '3': case '4': case '5':
- case '6': case '7':
- if (b == 0)
- b = 8;
- if (b == 8)
- p++;
- break;
- case 'X': case 'x':
- switch (p[2]) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- case 'A': case 'B': case 'C': case 'D': case 'E':
- case 'F':
- case 'a': case 'b': case 'c': case 'd': case 'e':
- case 'f':
- if (b == 0)
- b = 16;
- if (b == 16)
- p += 2;
- break;
- default:
- break;
- }
- break;
- default:
- p++;
- ret = 0;
- goto label_return;
- }
- }
- if (b == 0)
- b = 10;
-
- /* Convert. */
- ret = 0;
- while ((*p >= '0' && *p <= '9' && (digit = *p - '0') < b)
- || (*p >= 'A' && *p <= 'Z' && (digit = 10 + *p - 'A') < b)
- || (*p >= 'a' && *p <= 'z' && (digit = 10 + *p - 'a') < b)) {
- uintmax_t pret = ret;
- ret *= b;
- ret += digit;
- if (ret < pret) {
- /* Overflow. */
- set_errno(ERANGE);
- ret = UINTMAX_MAX;
- goto label_return;
- }
- p++;
- }
- if (neg)
- ret = -ret;
-
- if (p == ns) {
- /* No conversion performed. */
- set_errno(EINVAL);
- ret = UINTMAX_MAX;
- goto label_return;
- }
-
-label_return:
- if (endptr != NULL) {
- if (p == ns) {
- /* No characters were converted. */
- *endptr = (char *)nptr;
- } else
- *endptr = (char *)p;
- }
- return (ret);
-}
-
-static char *
-u2s(uintmax_t x, unsigned base, bool uppercase, char *s, size_t *slen_p)
-{
- unsigned i;
-
- i = U2S_BUFSIZE - 1;
- s[i] = '\0';
- switch (base) {
- case 10:
- do {
- i--;
- s[i] = "0123456789"[x % (uint64_t)10];
- x /= (uint64_t)10;
- } while (x > 0);
- break;
- case 16: {
- const char *digits = (uppercase)
- ? "0123456789ABCDEF"
- : "0123456789abcdef";
-
- do {
- i--;
- s[i] = digits[x & 0xf];
- x >>= 4;
- } while (x > 0);
- break;
- } default: {
- const char *digits = (uppercase)
- ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- : "0123456789abcdefghijklmnopqrstuvwxyz";
-
- assert(base >= 2 && base <= 36);
- do {
- i--;
- s[i] = digits[x % (uint64_t)base];
- x /= (uint64_t)base;
- } while (x > 0);
- }}
-
- *slen_p = U2S_BUFSIZE - 1 - i;
- return (&s[i]);
-}
-
-static char *
-d2s(intmax_t x, char sign, char *s, size_t *slen_p)
-{
- bool neg;
-
- if ((neg = (x < 0)))
- x = -x;
- s = u2s(x, 10, false, s, slen_p);
- if (neg)
- sign = '-';
- switch (sign) {
- case '-':
- if (!neg)
- break;
- /* Fall through. */
- case ' ':
- case '+':
- s--;
- (*slen_p)++;
- *s = sign;
- break;
- default: not_reached();
- }
- return (s);
-}
-
-static char *
-o2s(uintmax_t x, bool alt_form, char *s, size_t *slen_p)
-{
-
- s = u2s(x, 8, false, s, slen_p);
- if (alt_form && *s != '0') {
- s--;
- (*slen_p)++;
- *s = '0';
- }
- return (s);
-}
-
-static char *
-x2s(uintmax_t x, bool alt_form, bool uppercase, char *s, size_t *slen_p)
-{
-
- s = u2s(x, 16, uppercase, s, slen_p);
- if (alt_form) {
- s -= 2;
- (*slen_p) += 2;
- memcpy(s, uppercase ? "0X" : "0x", 2);
- }
- return (s);
-}
-
-size_t
-malloc_vsnprintf(char *str, size_t size, const char *format, va_list ap)
-{
- size_t i;
- const char *f;
-
-#define APPEND_C(c) do { \
- if (i < size) \
- str[i] = (c); \
- i++; \
-} while (0)
-#define APPEND_S(s, slen) do { \
- if (i < size) { \
- size_t cpylen = (slen <= size - i) ? slen : size - i; \
- memcpy(&str[i], s, cpylen); \
- } \
- i += slen; \
-} while (0)
-#define APPEND_PADDED_S(s, slen, width, left_justify) do { \
- /* Left padding. */ \
- size_t pad_len = (width == -1) ? 0 : ((slen < (size_t)width) ? \
- (size_t)width - slen : 0); \
- if (!left_justify && pad_len != 0) { \
- size_t j; \
- for (j = 0; j < pad_len; j++) \
- APPEND_C(' '); \
- } \
- /* Value. */ \
- APPEND_S(s, slen); \
- /* Right padding. */ \
- if (left_justify && pad_len != 0) { \
- size_t j; \
- for (j = 0; j < pad_len; j++) \
- APPEND_C(' '); \
- } \
-} while (0)
-#define GET_ARG_NUMERIC(val, len) do { \
- switch (len) { \
- case '?': \
- val = va_arg(ap, int); \
- break; \
- case '?' | 0x80: \
- val = va_arg(ap, unsigned int); \
- break; \
- case 'l': \
- val = va_arg(ap, long); \
- break; \
- case 'l' | 0x80: \
- val = va_arg(ap, unsigned long); \
- break; \
- case 'q': \
- val = va_arg(ap, long long); \
- break; \
- case 'q' | 0x80: \
- val = va_arg(ap, unsigned long long); \
- break; \
- case 'j': \
- val = va_arg(ap, intmax_t); \
- break; \
- case 'j' | 0x80: \
- val = va_arg(ap, uintmax_t); \
- break; \
- case 't': \
- val = va_arg(ap, ptrdiff_t); \
- break; \
- case 'z': \
- val = va_arg(ap, ssize_t); \
- break; \
- case 'z' | 0x80: \
- val = va_arg(ap, size_t); \
- break; \
- case 'p': /* Synthetic; used for %p. */ \
- val = va_arg(ap, uintptr_t); \
- break; \
- default: \
- not_reached(); \
- val = 0; \
- } \
-} while (0)
-
- i = 0;
- f = format;
- while (true) {
- switch (*f) {
- case '\0': goto label_out;
- case '%': {
- bool alt_form = false;
- bool left_justify = false;
- bool plus_space = false;
- bool plus_plus = false;
- int prec = -1;
- int width = -1;
- unsigned char len = '?';
- char *s;
- size_t slen;
-
- f++;
- /* Flags. */
- while (true) {
- switch (*f) {
- case '#':
- assert(!alt_form);
- alt_form = true;
- break;
- case '-':
- assert(!left_justify);
- left_justify = true;
- break;
- case ' ':
- assert(!plus_space);
- plus_space = true;
- break;
- case '+':
- assert(!plus_plus);
- plus_plus = true;
- break;
- default: goto label_width;
- }
- f++;
- }
- /* Width. */
- label_width:
- switch (*f) {
- case '*':
- width = va_arg(ap, int);
- f++;
- if (width < 0) {
- left_justify = true;
- width = -width;
- }
- break;
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9': {
- uintmax_t uwidth;
- set_errno(0);
- uwidth = malloc_strtoumax(f, (char **)&f, 10);
- assert(uwidth != UINTMAX_MAX || get_errno() !=
- ERANGE);
- width = (int)uwidth;
- break;
- } default:
- break;
- }
- /* Width/precision separator. */
- if (*f == '.')
- f++;
- else
- goto label_length;
- /* Precision. */
- switch (*f) {
- case '*':
- prec = va_arg(ap, int);
- f++;
- break;
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9': {
- uintmax_t uprec;
- set_errno(0);
- uprec = malloc_strtoumax(f, (char **)&f, 10);
- assert(uprec != UINTMAX_MAX || get_errno() !=
- ERANGE);
- prec = (int)uprec;
- break;
- }
- default: break;
- }
- /* Length. */
- label_length:
- switch (*f) {
- case 'l':
- f++;
- if (*f == 'l') {
- len = 'q';
- f++;
- } else
- len = 'l';
- break;
- case 'q': case 'j': case 't': case 'z':
- len = *f;
- f++;
- break;
- default: break;
- }
- /* Conversion specifier. */
- switch (*f) {
- case '%':
- /* %% */
- APPEND_C(*f);
- f++;
- break;
- case 'd': case 'i': {
- intmax_t val JEMALLOC_CC_SILENCE_INIT(0);
- char buf[D2S_BUFSIZE];
-
- GET_ARG_NUMERIC(val, len);
- s = d2s(val, (plus_plus ? '+' : (plus_space ?
- ' ' : '-')), buf, &slen);
- APPEND_PADDED_S(s, slen, width, left_justify);
- f++;
- break;
- } case 'o': {
- uintmax_t val JEMALLOC_CC_SILENCE_INIT(0);
- char buf[O2S_BUFSIZE];
-
- GET_ARG_NUMERIC(val, len | 0x80);
- s = o2s(val, alt_form, buf, &slen);
- APPEND_PADDED_S(s, slen, width, left_justify);
- f++;
- break;
- } case 'u': {
- uintmax_t val JEMALLOC_CC_SILENCE_INIT(0);
- char buf[U2S_BUFSIZE];
-
- GET_ARG_NUMERIC(val, len | 0x80);
- s = u2s(val, 10, false, buf, &slen);
- APPEND_PADDED_S(s, slen, width, left_justify);
- f++;
- break;
- } case 'x': case 'X': {
- uintmax_t val JEMALLOC_CC_SILENCE_INIT(0);
- char buf[X2S_BUFSIZE];
-
- GET_ARG_NUMERIC(val, len | 0x80);
- s = x2s(val, alt_form, *f == 'X', buf, &slen);
- APPEND_PADDED_S(s, slen, width, left_justify);
- f++;
- break;
- } case 'c': {
- unsigned char val;
- char buf[2];
-
- assert(len == '?' || len == 'l');
- assert_not_implemented(len != 'l');
- val = va_arg(ap, int);
- buf[0] = val;
- buf[1] = '\0';
- APPEND_PADDED_S(buf, 1, width, left_justify);
- f++;
- break;
- } case 's':
- assert(len == '?' || len == 'l');
- assert_not_implemented(len != 'l');
- s = va_arg(ap, char *);
- slen = (prec < 0) ? strlen(s) : (size_t)prec;
- APPEND_PADDED_S(s, slen, width, left_justify);
- f++;
- break;
- case 'p': {
- uintmax_t val;
- char buf[X2S_BUFSIZE];
-
- GET_ARG_NUMERIC(val, 'p');
- s = x2s(val, true, false, buf, &slen);
- APPEND_PADDED_S(s, slen, width, left_justify);
- f++;
- break;
- } default: not_reached();
- }
- break;
- } default: {
- APPEND_C(*f);
- f++;
- break;
- }}
- }
- label_out:
- if (i < size)
- str[i] = '\0';
- else
- str[size - 1] = '\0';
-
-#undef APPEND_C
-#undef APPEND_S
-#undef APPEND_PADDED_S
-#undef GET_ARG_NUMERIC
- return (i);
-}
-
-JEMALLOC_FORMAT_PRINTF(3, 4)
-size_t
-malloc_snprintf(char *str, size_t size, const char *format, ...)
-{
- size_t ret;
- va_list ap;
-
- va_start(ap, format);
- ret = malloc_vsnprintf(str, size, format, ap);
- va_end(ap);
-
- return (ret);
-}
-
-void
-malloc_vcprintf(void (*write_cb)(void *, const char *), void *cbopaque,
- const char *format, va_list ap)
-{
- char buf[MALLOC_PRINTF_BUFSIZE];
-
- if (write_cb == NULL) {
- /*
- * The caller did not provide an alternate write_cb callback
- * function, so use the default one. malloc_write() is an
- * inline function, so use malloc_message() directly here.
- */
- write_cb = (je_malloc_message != NULL) ? je_malloc_message :
- wrtmessage;
- cbopaque = NULL;
- }
-
- malloc_vsnprintf(buf, sizeof(buf), format, ap);
- write_cb(cbopaque, buf);
-}
-
-/*
- * Print to a callback function in such a way as to (hopefully) avoid memory
- * allocation.
- */
-JEMALLOC_FORMAT_PRINTF(3, 4)
-void
-malloc_cprintf(void (*write_cb)(void *, const char *), void *cbopaque,
- const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- malloc_vcprintf(write_cb, cbopaque, format, ap);
- va_end(ap);
-}
-
-/* Print to stderr in such a way as to avoid memory allocation. */
-JEMALLOC_FORMAT_PRINTF(1, 2)
-void
-malloc_printf(const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- malloc_vcprintf(NULL, NULL, format, ap);
- va_end(ap);
-}
-
-/*
- * Restore normal assertion macros, in order to make it possible to compile all
- * C files as a single concatenation.
- */
-#undef assert
-#undef not_reached
-#undef not_implemented
-#include "jemalloc/internal/assert.h"
diff --git a/memory/jemalloc/src/src/valgrind.c b/memory/jemalloc/src/src/valgrind.c
deleted file mode 100644
index 8e7ef3a2e..000000000
--- a/memory/jemalloc/src/src/valgrind.c
+++ /dev/null
@@ -1,34 +0,0 @@
-#include "jemalloc/internal/jemalloc_internal.h"
-#ifndef JEMALLOC_VALGRIND
-# error "This source file is for Valgrind integration."
-#endif
-
-#include <valgrind/memcheck.h>
-
-void
-valgrind_make_mem_noaccess(void *ptr, size_t usize)
-{
-
- VALGRIND_MAKE_MEM_NOACCESS(ptr, usize);
-}
-
-void
-valgrind_make_mem_undefined(void *ptr, size_t usize)
-{
-
- VALGRIND_MAKE_MEM_UNDEFINED(ptr, usize);
-}
-
-void
-valgrind_make_mem_defined(void *ptr, size_t usize)
-{
-
- VALGRIND_MAKE_MEM_DEFINED(ptr, usize);
-}
-
-void
-valgrind_freelike_block(void *ptr, size_t usize)
-{
-
- VALGRIND_FREELIKE_BLOCK(ptr, usize);
-}
diff --git a/memory/jemalloc/src/src/witness.c b/memory/jemalloc/src/src/witness.c
deleted file mode 100644
index 23753f246..000000000
--- a/memory/jemalloc/src/src/witness.c
+++ /dev/null
@@ -1,136 +0,0 @@
-#define JEMALLOC_WITNESS_C_
-#include "jemalloc/internal/jemalloc_internal.h"
-
-void
-witness_init(witness_t *witness, const char *name, witness_rank_t rank,
- witness_comp_t *comp)
-{
-
- witness->name = name;
- witness->rank = rank;
- witness->comp = comp;
-}
-
-#ifdef JEMALLOC_JET
-#undef witness_lock_error
-#define witness_lock_error JEMALLOC_N(n_witness_lock_error)
-#endif
-void
-witness_lock_error(const witness_list_t *witnesses, const witness_t *witness)
-{
- witness_t *w;
-
- malloc_printf("<jemalloc>: Lock rank order reversal:");
- ql_foreach(w, witnesses, link) {
- malloc_printf(" %s(%u)", w->name, w->rank);
- }
- malloc_printf(" %s(%u)\n", witness->name, witness->rank);
- abort();
-}
-#ifdef JEMALLOC_JET
-#undef witness_lock_error
-#define witness_lock_error JEMALLOC_N(witness_lock_error)
-witness_lock_error_t *witness_lock_error = JEMALLOC_N(n_witness_lock_error);
-#endif
-
-#ifdef JEMALLOC_JET
-#undef witness_owner_error
-#define witness_owner_error JEMALLOC_N(n_witness_owner_error)
-#endif
-void
-witness_owner_error(const witness_t *witness)
-{
-
- malloc_printf("<jemalloc>: Should own %s(%u)\n", witness->name,
- witness->rank);
- abort();
-}
-#ifdef JEMALLOC_JET
-#undef witness_owner_error
-#define witness_owner_error JEMALLOC_N(witness_owner_error)
-witness_owner_error_t *witness_owner_error = JEMALLOC_N(n_witness_owner_error);
-#endif
-
-#ifdef JEMALLOC_JET
-#undef witness_not_owner_error
-#define witness_not_owner_error JEMALLOC_N(n_witness_not_owner_error)
-#endif
-void
-witness_not_owner_error(const witness_t *witness)
-{
-
- malloc_printf("<jemalloc>: Should not own %s(%u)\n", witness->name,
- witness->rank);
- abort();
-}
-#ifdef JEMALLOC_JET
-#undef witness_not_owner_error
-#define witness_not_owner_error JEMALLOC_N(witness_not_owner_error)
-witness_not_owner_error_t *witness_not_owner_error =
- JEMALLOC_N(n_witness_not_owner_error);
-#endif
-
-#ifdef JEMALLOC_JET
-#undef witness_lockless_error
-#define witness_lockless_error JEMALLOC_N(n_witness_lockless_error)
-#endif
-void
-witness_lockless_error(const witness_list_t *witnesses)
-{
- witness_t *w;
-
- malloc_printf("<jemalloc>: Should not own any locks:");
- ql_foreach(w, witnesses, link) {
- malloc_printf(" %s(%u)", w->name, w->rank);
- }
- malloc_printf("\n");
- abort();
-}
-#ifdef JEMALLOC_JET
-#undef witness_lockless_error
-#define witness_lockless_error JEMALLOC_N(witness_lockless_error)
-witness_lockless_error_t *witness_lockless_error =
- JEMALLOC_N(n_witness_lockless_error);
-#endif
-
-void
-witnesses_cleanup(tsd_t *tsd)
-{
-
- witness_assert_lockless(tsd_tsdn(tsd));
-
- /* Do nothing. */
-}
-
-void
-witness_fork_cleanup(tsd_t *tsd)
-{
-
- /* Do nothing. */
-}
-
-void
-witness_prefork(tsd_t *tsd)
-{
-
- tsd_witness_fork_set(tsd, true);
-}
-
-void
-witness_postfork_parent(tsd_t *tsd)
-{
-
- tsd_witness_fork_set(tsd, false);
-}
-
-void
-witness_postfork_child(tsd_t *tsd)
-{
-#ifndef JEMALLOC_MUTEX_INIT_CB
- witness_list_t *witnesses;
-
- witnesses = tsd_witnessesp_get(tsd);
- ql_new(witnesses);
-#endif
- tsd_witness_fork_set(tsd, false);
-}
diff --git a/memory/jemalloc/src/src/zone.c b/memory/jemalloc/src/src/zone.c
deleted file mode 100644
index 0571920e4..000000000
--- a/memory/jemalloc/src/src/zone.c
+++ /dev/null
@@ -1,330 +0,0 @@
-#include "jemalloc/internal/jemalloc_internal.h"
-#ifndef JEMALLOC_ZONE
-# error "This source file is for zones on Darwin (OS X)."
-#endif
-
-/*
- * The malloc_default_purgeable_zone() function is only available on >= 10.6.
- * We need to check whether it is present at runtime, thus the weak_import.
- */
-extern malloc_zone_t *malloc_default_purgeable_zone(void)
-JEMALLOC_ATTR(weak_import);
-
-/******************************************************************************/
-/* Data. */
-
-static malloc_zone_t *default_zone, *purgeable_zone;
-static malloc_zone_t jemalloc_zone;
-static struct malloc_introspection_t jemalloc_zone_introspect;
-
-/******************************************************************************/
-/* Function prototypes for non-inline static functions. */
-
-static size_t zone_size(malloc_zone_t *zone, void *ptr);
-static void *zone_malloc(malloc_zone_t *zone, size_t size);
-static void *zone_calloc(malloc_zone_t *zone, size_t num, size_t size);
-static void *zone_valloc(malloc_zone_t *zone, size_t size);
-static void zone_free(malloc_zone_t *zone, void *ptr);
-static void *zone_realloc(malloc_zone_t *zone, void *ptr, size_t size);
-#if (JEMALLOC_ZONE_VERSION >= 5)
-static void *zone_memalign(malloc_zone_t *zone, size_t alignment,
-#endif
-#if (JEMALLOC_ZONE_VERSION >= 6)
- size_t size);
-static void zone_free_definite_size(malloc_zone_t *zone, void *ptr,
- size_t size);
-#endif
-static void *zone_destroy(malloc_zone_t *zone);
-static size_t zone_good_size(malloc_zone_t *zone, size_t size);
-static void zone_force_lock(malloc_zone_t *zone);
-static void zone_force_unlock(malloc_zone_t *zone);
-
-/******************************************************************************/
-/*
- * Functions.
- */
-
-static size_t
-zone_size(malloc_zone_t *zone, void *ptr)
-{
-
- /*
- * There appear to be places within Darwin (such as setenv(3)) that
- * cause calls to this function with pointers that *no* zone owns. If
- * we knew that all pointers were owned by *some* zone, we could split
- * our zone into two parts, and use one as the default allocator and
- * the other as the default deallocator/reallocator. Since that will
- * not work in practice, we must check all pointers to assure that they
- * reside within a mapped chunk before determining size.
- */
- return (ivsalloc(tsdn_fetch(), ptr, config_prof));
-}
-
-static void *
-zone_malloc(malloc_zone_t *zone, size_t size)
-{
-
- return (je_malloc(size));
-}
-
-static void *
-zone_calloc(malloc_zone_t *zone, size_t num, size_t size)
-{
-
- return (je_calloc(num, size));
-}
-
-static void *
-zone_valloc(malloc_zone_t *zone, size_t size)
-{
- void *ret = NULL; /* Assignment avoids useless compiler warning. */
-
- je_posix_memalign(&ret, PAGE, size);
-
- return (ret);
-}
-
-static void
-zone_free(malloc_zone_t *zone, void *ptr)
-{
-
- if (ivsalloc(tsdn_fetch(), ptr, config_prof) != 0) {
- je_free(ptr);
- return;
- }
-
- free(ptr);
-}
-
-static void *
-zone_realloc(malloc_zone_t *zone, void *ptr, size_t size)
-{
-
- if (ivsalloc(tsdn_fetch(), ptr, config_prof) != 0)
- return (je_realloc(ptr, size));
-
- return (realloc(ptr, size));
-}
-
-#if (JEMALLOC_ZONE_VERSION >= 5)
-static void *
-zone_memalign(malloc_zone_t *zone, size_t alignment, size_t size)
-{
- void *ret = NULL; /* Assignment avoids useless compiler warning. */
-
- je_posix_memalign(&ret, alignment, size);
-
- return (ret);
-}
-#endif
-
-#if (JEMALLOC_ZONE_VERSION >= 6)
-static void
-zone_free_definite_size(malloc_zone_t *zone, void *ptr, size_t size)
-{
- size_t alloc_size;
-
- alloc_size = ivsalloc(tsdn_fetch(), ptr, config_prof);
- if (alloc_size != 0) {
- assert(alloc_size == size);
- je_free(ptr);
- return;
- }
-
- free(ptr);
-}
-#endif
-
-static void *
-zone_destroy(malloc_zone_t *zone)
-{
-
- /* This function should never be called. */
- not_reached();
- return (NULL);
-}
-
-static size_t
-zone_good_size(malloc_zone_t *zone, size_t size)
-{
-
- if (size == 0)
- size = 1;
- return (s2u(size));
-}
-
-static void
-zone_force_lock(malloc_zone_t *zone)
-{
-
- if (isthreaded)
- jemalloc_prefork();
-}
-
-static void
-zone_force_unlock(malloc_zone_t *zone)
-{
-
- /*
- * Call jemalloc_postfork_child() rather than
- * jemalloc_postfork_parent(), because this function is executed by both
- * parent and child. The parent can tolerate having state
- * reinitialized, but the child cannot unlock mutexes that were locked
- * by the parent.
- */
- if (isthreaded)
- jemalloc_postfork_child();
-}
-
-static void
-zone_init(void)
-{
-
- jemalloc_zone.size = (void *)zone_size;
- jemalloc_zone.malloc = (void *)zone_malloc;
- jemalloc_zone.calloc = (void *)zone_calloc;
- jemalloc_zone.valloc = (void *)zone_valloc;
- jemalloc_zone.free = (void *)zone_free;
- jemalloc_zone.realloc = (void *)zone_realloc;
- jemalloc_zone.destroy = (void *)zone_destroy;
- jemalloc_zone.zone_name = "jemalloc_zone";
- jemalloc_zone.batch_malloc = NULL;
- jemalloc_zone.batch_free = NULL;
- jemalloc_zone.introspect = &jemalloc_zone_introspect;
- jemalloc_zone.version = JEMALLOC_ZONE_VERSION;
-#if (JEMALLOC_ZONE_VERSION >= 5)
- jemalloc_zone.memalign = zone_memalign;
-#endif
-#if (JEMALLOC_ZONE_VERSION >= 6)
- jemalloc_zone.free_definite_size = zone_free_definite_size;
-#endif
-#if (JEMALLOC_ZONE_VERSION >= 8)
- jemalloc_zone.pressure_relief = NULL;
-#endif
-
- jemalloc_zone_introspect.enumerator = NULL;
- jemalloc_zone_introspect.good_size = (void *)zone_good_size;
- jemalloc_zone_introspect.check = NULL;
- jemalloc_zone_introspect.print = NULL;
- jemalloc_zone_introspect.log = NULL;
- jemalloc_zone_introspect.force_lock = (void *)zone_force_lock;
- jemalloc_zone_introspect.force_unlock = (void *)zone_force_unlock;
- jemalloc_zone_introspect.statistics = NULL;
-#if (JEMALLOC_ZONE_VERSION >= 6)
- jemalloc_zone_introspect.zone_locked = NULL;
-#endif
-#if (JEMALLOC_ZONE_VERSION >= 7)
- jemalloc_zone_introspect.enable_discharge_checking = NULL;
- jemalloc_zone_introspect.disable_discharge_checking = NULL;
- jemalloc_zone_introspect.discharge = NULL;
-# ifdef __BLOCKS__
- jemalloc_zone_introspect.enumerate_discharged_pointers = NULL;
-# else
- jemalloc_zone_introspect.enumerate_unavailable_without_blocks = NULL;
-# endif
-#endif
-}
-
-static malloc_zone_t *
-zone_default_get(void)
-{
- malloc_zone_t **zones = NULL;
- unsigned int num_zones = 0;
-
- /*
- * On OSX 10.12, malloc_default_zone returns a special zone that is not
- * present in the list of registered zones. That zone uses a "lite zone"
- * if one is present (apparently enabled when malloc stack logging is
- * enabled), or the first registered zone otherwise. In practice this
- * means unless malloc stack logging is enabled, the first registered
- * zone is the default. So get the list of zones to get the first one,
- * instead of relying on malloc_default_zone.
- */
- if (KERN_SUCCESS != malloc_get_all_zones(0, NULL,
- (vm_address_t**)&zones, &num_zones)) {
- /*
- * Reset the value in case the failure happened after it was
- * set.
- */
- num_zones = 0;
- }
-
- if (num_zones)
- return (zones[0]);
-
- return (malloc_default_zone());
-}
-
-/* As written, this function can only promote jemalloc_zone. */
-static void
-zone_promote(void)
-{
- malloc_zone_t *zone;
-
- do {
- /*
- * Unregister and reregister the default zone. On OSX >= 10.6,
- * unregistering takes the last registered zone and places it
- * at the location of the specified zone. Unregistering the
- * default zone thus makes the last registered one the default.
- * On OSX < 10.6, unregistering shifts all registered zones.
- * The first registered zone then becomes the default.
- */
- malloc_zone_unregister(default_zone);
- malloc_zone_register(default_zone);
-
- /*
- * On OSX 10.6, having the default purgeable zone appear before
- * the default zone makes some things crash because it thinks it
- * owns the default zone allocated pointers. We thus
- * unregister/re-register it in order to ensure it's always
- * after the default zone. On OSX < 10.6, there is no purgeable
- * zone, so this does nothing. On OSX >= 10.6, unregistering
- * replaces the purgeable zone with the last registered zone
- * above, i.e. the default zone. Registering it again then puts
- * it at the end, obviously after the default zone.
- */
- if (purgeable_zone != NULL) {
- malloc_zone_unregister(purgeable_zone);
- malloc_zone_register(purgeable_zone);
- }
-
- zone = zone_default_get();
- } while (zone != &jemalloc_zone);
-}
-
-JEMALLOC_ATTR(constructor)
-void
-zone_register(void)
-{
-
- /*
- * If something else replaced the system default zone allocator, don't
- * register jemalloc's.
- */
- default_zone = zone_default_get();
- if (!default_zone->zone_name || strcmp(default_zone->zone_name,
- "DefaultMallocZone") != 0)
- return;
-
- /*
- * The default purgeable zone is created lazily by OSX's libc. It uses
- * the default zone when it is created for "small" allocations
- * (< 15 KiB), but assumes the default zone is a scalable_zone. This
- * obviously fails when the default zone is the jemalloc zone, so
- * malloc_default_purgeable_zone() is called beforehand so that the
- * default purgeable zone is created when the default zone is still
- * a scalable_zone. As purgeable zones only exist on >= 10.6, we need
- * to check for the existence of malloc_default_purgeable_zone() at
- * run time.
- */
- purgeable_zone = (malloc_default_purgeable_zone == NULL) ? NULL :
- malloc_default_purgeable_zone();
-
- /* Register the custom zone. At this point it won't be the default. */
- zone_init();
- malloc_zone_register(&jemalloc_zone);
-
- /* Promote the custom zone to be default. */
- zone_promote();
-}
diff --git a/memory/jemalloc/src/test/include/test/SFMT-alti.h b/memory/jemalloc/src/test/include/test/SFMT-alti.h
deleted file mode 100644
index 0005df6b4..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-alti.h
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-/**
- * @file SFMT-alti.h
- *
- * @brief SIMD oriented Fast Mersenne Twister(SFMT)
- * pseudorandom number generator
- *
- * @author Mutsuo Saito (Hiroshima University)
- * @author Makoto Matsumoto (Hiroshima University)
- *
- * Copyright (C) 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. All rights reserved.
- *
- * The new BSD License is applied to this software.
- * see LICENSE.txt
- */
-
-#ifndef SFMT_ALTI_H
-#define SFMT_ALTI_H
-
-/**
- * This function represents the recursion formula in AltiVec and BIG ENDIAN.
- * @param a a 128-bit part of the interal state array
- * @param b a 128-bit part of the interal state array
- * @param c a 128-bit part of the interal state array
- * @param d a 128-bit part of the interal state array
- * @return output
- */
-JEMALLOC_ALWAYS_INLINE
-vector unsigned int vec_recursion(vector unsigned int a,
- vector unsigned int b,
- vector unsigned int c,
- vector unsigned int d) {
-
- const vector unsigned int sl1 = ALTI_SL1;
- const vector unsigned int sr1 = ALTI_SR1;
-#ifdef ONLY64
- const vector unsigned int mask = ALTI_MSK64;
- const vector unsigned char perm_sl = ALTI_SL2_PERM64;
- const vector unsigned char perm_sr = ALTI_SR2_PERM64;
-#else
- const vector unsigned int mask = ALTI_MSK;
- const vector unsigned char perm_sl = ALTI_SL2_PERM;
- const vector unsigned char perm_sr = ALTI_SR2_PERM;
-#endif
- vector unsigned int v, w, x, y, z;
- x = vec_perm(a, (vector unsigned int)perm_sl, perm_sl);
- v = a;
- y = vec_sr(b, sr1);
- z = vec_perm(c, (vector unsigned int)perm_sr, perm_sr);
- w = vec_sl(d, sl1);
- z = vec_xor(z, w);
- y = vec_and(y, mask);
- v = vec_xor(v, x);
- z = vec_xor(z, y);
- z = vec_xor(z, v);
- return z;
-}
-
-/**
- * This function fills the internal state array with pseudorandom
- * integers.
- */
-JEMALLOC_INLINE void gen_rand_all(sfmt_t *ctx) {
- int i;
- vector unsigned int r, r1, r2;
-
- r1 = ctx->sfmt[N - 2].s;
- r2 = ctx->sfmt[N - 1].s;
- for (i = 0; i < N - POS1; i++) {
- r = vec_recursion(ctx->sfmt[i].s, ctx->sfmt[i + POS1].s, r1, r2);
- ctx->sfmt[i].s = r;
- r1 = r2;
- r2 = r;
- }
- for (; i < N; i++) {
- r = vec_recursion(ctx->sfmt[i].s, ctx->sfmt[i + POS1 - N].s, r1, r2);
- ctx->sfmt[i].s = r;
- r1 = r2;
- r2 = r;
- }
-}
-
-/**
- * This function fills the user-specified array with pseudorandom
- * integers.
- *
- * @param array an 128-bit array to be filled by pseudorandom numbers.
- * @param size number of 128-bit pesudorandom numbers to be generated.
- */
-JEMALLOC_INLINE void gen_rand_array(sfmt_t *ctx, w128_t *array, int size) {
- int i, j;
- vector unsigned int r, r1, r2;
-
- r1 = ctx->sfmt[N - 2].s;
- r2 = ctx->sfmt[N - 1].s;
- for (i = 0; i < N - POS1; i++) {
- r = vec_recursion(ctx->sfmt[i].s, ctx->sfmt[i + POS1].s, r1, r2);
- array[i].s = r;
- r1 = r2;
- r2 = r;
- }
- for (; i < N; i++) {
- r = vec_recursion(ctx->sfmt[i].s, array[i + POS1 - N].s, r1, r2);
- array[i].s = r;
- r1 = r2;
- r2 = r;
- }
- /* main loop */
- for (; i < size - N; i++) {
- r = vec_recursion(array[i - N].s, array[i + POS1 - N].s, r1, r2);
- array[i].s = r;
- r1 = r2;
- r2 = r;
- }
- for (j = 0; j < 2 * N - size; j++) {
- ctx->sfmt[j].s = array[j + size - N].s;
- }
- for (; i < size; i++) {
- r = vec_recursion(array[i - N].s, array[i + POS1 - N].s, r1, r2);
- array[i].s = r;
- ctx->sfmt[j++].s = r;
- r1 = r2;
- r2 = r;
- }
-}
-
-#ifndef ONLY64
-#if defined(__APPLE__)
-#define ALTI_SWAP (vector unsigned char) \
- (4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11)
-#else
-#define ALTI_SWAP {4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11}
-#endif
-/**
- * This function swaps high and low 32-bit of 64-bit integers in user
- * specified array.
- *
- * @param array an 128-bit array to be swaped.
- * @param size size of 128-bit array.
- */
-JEMALLOC_INLINE void swap(w128_t *array, int size) {
- int i;
- const vector unsigned char perm = ALTI_SWAP;
-
- for (i = 0; i < size; i++) {
- array[i].s = vec_perm(array[i].s, (vector unsigned int)perm, perm);
- }
-}
-#endif
-
-#endif
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params.h b/memory/jemalloc/src/test/include/test/SFMT-params.h
deleted file mode 100644
index ade662220..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS_H
-#define SFMT_PARAMS_H
-
-#if !defined(MEXP)
-#ifdef __GNUC__
- #warning "MEXP is not defined. I assume MEXP is 19937."
-#endif
- #define MEXP 19937
-#endif
-/*-----------------
- BASIC DEFINITIONS
- -----------------*/
-/** Mersenne Exponent. The period of the sequence
- * is a multiple of 2^MEXP-1.
- * #define MEXP 19937 */
-/** SFMT generator has an internal state array of 128-bit integers,
- * and N is its size. */
-#define N (MEXP / 128 + 1)
-/** N32 is the size of internal state array when regarded as an array
- * of 32-bit integers.*/
-#define N32 (N * 4)
-/** N64 is the size of internal state array when regarded as an array
- * of 64-bit integers.*/
-#define N64 (N * 2)
-
-/*----------------------
- the parameters of SFMT
- following definitions are in paramsXXXX.h file.
- ----------------------*/
-/** the pick up position of the array.
-#define POS1 122
-*/
-
-/** the parameter of shift left as four 32-bit registers.
-#define SL1 18
- */
-
-/** the parameter of shift left as one 128-bit register.
- * The 128-bit integer is shifted by (SL2 * 8) bits.
-#define SL2 1
-*/
-
-/** the parameter of shift right as four 32-bit registers.
-#define SR1 11
-*/
-
-/** the parameter of shift right as one 128-bit register.
- * The 128-bit integer is shifted by (SL2 * 8) bits.
-#define SR2 1
-*/
-
-/** A bitmask, used in the recursion. These parameters are introduced
- * to break symmetry of SIMD.
-#define MSK1 0xdfffffefU
-#define MSK2 0xddfecb7fU
-#define MSK3 0xbffaffffU
-#define MSK4 0xbffffff6U
-*/
-
-/** These definitions are part of a 128-bit period certification vector.
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0x00000000U
-#define PARITY4 0xc98e126aU
-*/
-
-#if MEXP == 607
- #include "test/SFMT-params607.h"
-#elif MEXP == 1279
- #include "test/SFMT-params1279.h"
-#elif MEXP == 2281
- #include "test/SFMT-params2281.h"
-#elif MEXP == 4253
- #include "test/SFMT-params4253.h"
-#elif MEXP == 11213
- #include "test/SFMT-params11213.h"
-#elif MEXP == 19937
- #include "test/SFMT-params19937.h"
-#elif MEXP == 44497
- #include "test/SFMT-params44497.h"
-#elif MEXP == 86243
- #include "test/SFMT-params86243.h"
-#elif MEXP == 132049
- #include "test/SFMT-params132049.h"
-#elif MEXP == 216091
- #include "test/SFMT-params216091.h"
-#else
-#ifdef __GNUC__
- #error "MEXP is not valid."
- #undef MEXP
-#else
- #undef MEXP
-#endif
-
-#endif
-
-#endif /* SFMT_PARAMS_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params11213.h b/memory/jemalloc/src/test/include/test/SFMT-params11213.h
deleted file mode 100644
index 2994bd21d..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params11213.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS11213_H
-#define SFMT_PARAMS11213_H
-
-#define POS1 68
-#define SL1 14
-#define SL2 3
-#define SR1 7
-#define SR2 3
-#define MSK1 0xeffff7fbU
-#define MSK2 0xffffffefU
-#define MSK3 0xdfdfbfffU
-#define MSK4 0x7fffdbfdU
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0xe8148000U
-#define PARITY4 0xd0c7afa3U
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10}
- #define ALTI_SL2_PERM64 {3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2}
- #define ALTI_SR2_PERM {5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12}
- #define ALTI_SR2_PERM64 {13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12}
-#endif /* For OSX */
-#define IDSTR "SFMT-11213:68-14-3-7-3:effff7fb-ffffffef-dfdfbfff-7fffdbfd"
-
-#endif /* SFMT_PARAMS11213_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params1279.h b/memory/jemalloc/src/test/include/test/SFMT-params1279.h
deleted file mode 100644
index d7959f980..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params1279.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS1279_H
-#define SFMT_PARAMS1279_H
-
-#define POS1 7
-#define SL1 14
-#define SL2 3
-#define SR1 5
-#define SR2 1
-#define MSK1 0xf7fefffdU
-#define MSK2 0x7fefcfffU
-#define MSK3 0xaff3ef3fU
-#define MSK4 0xb5ffff7fU
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0x00000000U
-#define PARITY4 0x20000000U
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10}
- #define ALTI_SL2_PERM64 {3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2}
- #define ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14}
- #define ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14}
-#endif /* For OSX */
-#define IDSTR "SFMT-1279:7-14-3-5-1:f7fefffd-7fefcfff-aff3ef3f-b5ffff7f"
-
-#endif /* SFMT_PARAMS1279_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params132049.h b/memory/jemalloc/src/test/include/test/SFMT-params132049.h
deleted file mode 100644
index a1dcec392..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params132049.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS132049_H
-#define SFMT_PARAMS132049_H
-
-#define POS1 110
-#define SL1 19
-#define SL2 1
-#define SR1 21
-#define SR2 1
-#define MSK1 0xffffbb5fU
-#define MSK2 0xfb6ebf95U
-#define MSK3 0xfffefffaU
-#define MSK4 0xcff77fffU
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0xcb520000U
-#define PARITY4 0xc7e91c7dU
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8}
- #define ALTI_SL2_PERM64 {1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0}
- #define ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14}
- #define ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14}
-#endif /* For OSX */
-#define IDSTR "SFMT-132049:110-19-1-21-1:ffffbb5f-fb6ebf95-fffefffa-cff77fff"
-
-#endif /* SFMT_PARAMS132049_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params19937.h b/memory/jemalloc/src/test/include/test/SFMT-params19937.h
deleted file mode 100644
index fb92b4c9b..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params19937.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS19937_H
-#define SFMT_PARAMS19937_H
-
-#define POS1 122
-#define SL1 18
-#define SL2 1
-#define SR1 11
-#define SR2 1
-#define MSK1 0xdfffffefU
-#define MSK2 0xddfecb7fU
-#define MSK3 0xbffaffffU
-#define MSK4 0xbffffff6U
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0x00000000U
-#define PARITY4 0x13c9e684U
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8}
- #define ALTI_SL2_PERM64 {1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0}
- #define ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14}
- #define ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14}
-#endif /* For OSX */
-#define IDSTR "SFMT-19937:122-18-1-11-1:dfffffef-ddfecb7f-bffaffff-bffffff6"
-
-#endif /* SFMT_PARAMS19937_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params216091.h b/memory/jemalloc/src/test/include/test/SFMT-params216091.h
deleted file mode 100644
index 125ce2820..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params216091.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS216091_H
-#define SFMT_PARAMS216091_H
-
-#define POS1 627
-#define SL1 11
-#define SL2 3
-#define SR1 10
-#define SR2 1
-#define MSK1 0xbff7bff7U
-#define MSK2 0xbfffffffU
-#define MSK3 0xbffffa7fU
-#define MSK4 0xffddfbfbU
-#define PARITY1 0xf8000001U
-#define PARITY2 0x89e80709U
-#define PARITY3 0x3bd2b64bU
-#define PARITY4 0x0c64b1e4U
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10}
- #define ALTI_SL2_PERM64 {3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2}
- #define ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14}
- #define ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14}
-#endif /* For OSX */
-#define IDSTR "SFMT-216091:627-11-3-10-1:bff7bff7-bfffffff-bffffa7f-ffddfbfb"
-
-#endif /* SFMT_PARAMS216091_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params2281.h b/memory/jemalloc/src/test/include/test/SFMT-params2281.h
deleted file mode 100644
index 0ef85c407..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params2281.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS2281_H
-#define SFMT_PARAMS2281_H
-
-#define POS1 12
-#define SL1 19
-#define SL2 1
-#define SR1 5
-#define SR2 1
-#define MSK1 0xbff7ffbfU
-#define MSK2 0xfdfffffeU
-#define MSK3 0xf7ffef7fU
-#define MSK4 0xf2f7cbbfU
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0x00000000U
-#define PARITY4 0x41dfa600U
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8}
- #define ALTI_SL2_PERM64 {1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0}
- #define ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14}
- #define ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14}
-#endif /* For OSX */
-#define IDSTR "SFMT-2281:12-19-1-5-1:bff7ffbf-fdfffffe-f7ffef7f-f2f7cbbf"
-
-#endif /* SFMT_PARAMS2281_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params4253.h b/memory/jemalloc/src/test/include/test/SFMT-params4253.h
deleted file mode 100644
index 9f07bc67e..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params4253.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS4253_H
-#define SFMT_PARAMS4253_H
-
-#define POS1 17
-#define SL1 20
-#define SL2 1
-#define SR1 7
-#define SR2 1
-#define MSK1 0x9f7bffffU
-#define MSK2 0x9fffff5fU
-#define MSK3 0x3efffffbU
-#define MSK4 0xfffff7bbU
-#define PARITY1 0xa8000001U
-#define PARITY2 0xaf5390a3U
-#define PARITY3 0xb740b3f8U
-#define PARITY4 0x6c11486dU
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {1,2,3,23,5,6,7,0,9,10,11,4,13,14,15,8}
- #define ALTI_SL2_PERM64 {1,2,3,4,5,6,7,31,9,10,11,12,13,14,15,0}
- #define ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14}
- #define ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14}
-#endif /* For OSX */
-#define IDSTR "SFMT-4253:17-20-1-7-1:9f7bffff-9fffff5f-3efffffb-fffff7bb"
-
-#endif /* SFMT_PARAMS4253_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params44497.h b/memory/jemalloc/src/test/include/test/SFMT-params44497.h
deleted file mode 100644
index 85598fed5..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params44497.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS44497_H
-#define SFMT_PARAMS44497_H
-
-#define POS1 330
-#define SL1 5
-#define SL2 3
-#define SR1 9
-#define SR2 3
-#define MSK1 0xeffffffbU
-#define MSK2 0xdfbebfffU
-#define MSK3 0xbfbf7befU
-#define MSK4 0x9ffd7bffU
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0xa3ac4000U
-#define PARITY4 0xecc1327aU
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10}
- #define ALTI_SL2_PERM64 {3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2}
- #define ALTI_SR2_PERM {5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12}
- #define ALTI_SR2_PERM64 {13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12}
-#endif /* For OSX */
-#define IDSTR "SFMT-44497:330-5-3-9-3:effffffb-dfbebfff-bfbf7bef-9ffd7bff"
-
-#endif /* SFMT_PARAMS44497_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params607.h b/memory/jemalloc/src/test/include/test/SFMT-params607.h
deleted file mode 100644
index bc76485f8..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params607.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS607_H
-#define SFMT_PARAMS607_H
-
-#define POS1 2
-#define SL1 15
-#define SL2 3
-#define SR1 13
-#define SR2 3
-#define MSK1 0xfdff37ffU
-#define MSK2 0xef7f3f7dU
-#define MSK3 0xff777b7dU
-#define MSK4 0x7ff7fb2fU
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0x00000000U
-#define PARITY4 0x5986f054U
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {3,21,21,21,7,0,1,2,11,4,5,6,15,8,9,10}
- #define ALTI_SL2_PERM64 {3,4,5,6,7,29,29,29,11,12,13,14,15,0,1,2}
- #define ALTI_SR2_PERM {5,6,7,0,9,10,11,4,13,14,15,8,19,19,19,12}
- #define ALTI_SR2_PERM64 {13,14,15,0,1,2,3,4,19,19,19,8,9,10,11,12}
-#endif /* For OSX */
-#define IDSTR "SFMT-607:2-15-3-13-3:fdff37ff-ef7f3f7d-ff777b7d-7ff7fb2f"
-
-#endif /* SFMT_PARAMS607_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-params86243.h b/memory/jemalloc/src/test/include/test/SFMT-params86243.h
deleted file mode 100644
index 5e4d783c5..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-params86243.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#ifndef SFMT_PARAMS86243_H
-#define SFMT_PARAMS86243_H
-
-#define POS1 366
-#define SL1 6
-#define SL2 7
-#define SR1 19
-#define SR2 1
-#define MSK1 0xfdbffbffU
-#define MSK2 0xbff7ff3fU
-#define MSK3 0xfd77efffU
-#define MSK4 0xbf9ff3ffU
-#define PARITY1 0x00000001U
-#define PARITY2 0x00000000U
-#define PARITY3 0x00000000U
-#define PARITY4 0xe9528d85U
-
-
-/* PARAMETERS FOR ALTIVEC */
-#if defined(__APPLE__) /* For OSX */
- #define ALTI_SL1 (vector unsigned int)(SL1, SL1, SL1, SL1)
- #define ALTI_SR1 (vector unsigned int)(SR1, SR1, SR1, SR1)
- #define ALTI_MSK (vector unsigned int)(MSK1, MSK2, MSK3, MSK4)
- #define ALTI_MSK64 \
- (vector unsigned int)(MSK2, MSK1, MSK4, MSK3)
- #define ALTI_SL2_PERM \
- (vector unsigned char)(25,25,25,25,3,25,25,25,7,0,1,2,11,4,5,6)
- #define ALTI_SL2_PERM64 \
- (vector unsigned char)(7,25,25,25,25,25,25,25,15,0,1,2,3,4,5,6)
- #define ALTI_SR2_PERM \
- (vector unsigned char)(7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14)
- #define ALTI_SR2_PERM64 \
- (vector unsigned char)(15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14)
-#else /* For OTHER OSs(Linux?) */
- #define ALTI_SL1 {SL1, SL1, SL1, SL1}
- #define ALTI_SR1 {SR1, SR1, SR1, SR1}
- #define ALTI_MSK {MSK1, MSK2, MSK3, MSK4}
- #define ALTI_MSK64 {MSK2, MSK1, MSK4, MSK3}
- #define ALTI_SL2_PERM {25,25,25,25,3,25,25,25,7,0,1,2,11,4,5,6}
- #define ALTI_SL2_PERM64 {7,25,25,25,25,25,25,25,15,0,1,2,3,4,5,6}
- #define ALTI_SR2_PERM {7,0,1,2,11,4,5,6,15,8,9,10,17,12,13,14}
- #define ALTI_SR2_PERM64 {15,0,1,2,3,4,5,6,17,8,9,10,11,12,13,14}
-#endif /* For OSX */
-#define IDSTR "SFMT-86243:366-6-7-19-1:fdbffbff-bff7ff3f-fd77efff-bf9ff3ff"
-
-#endif /* SFMT_PARAMS86243_H */
diff --git a/memory/jemalloc/src/test/include/test/SFMT-sse2.h b/memory/jemalloc/src/test/include/test/SFMT-sse2.h
deleted file mode 100644
index 0314a163d..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT-sse2.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-/**
- * @file SFMT-sse2.h
- * @brief SIMD oriented Fast Mersenne Twister(SFMT) for Intel SSE2
- *
- * @author Mutsuo Saito (Hiroshima University)
- * @author Makoto Matsumoto (Hiroshima University)
- *
- * @note We assume LITTLE ENDIAN in this file
- *
- * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. All rights reserved.
- *
- * The new BSD License is applied to this software, see LICENSE.txt
- */
-
-#ifndef SFMT_SSE2_H
-#define SFMT_SSE2_H
-
-/**
- * This function represents the recursion formula.
- * @param a a 128-bit part of the interal state array
- * @param b a 128-bit part of the interal state array
- * @param c a 128-bit part of the interal state array
- * @param d a 128-bit part of the interal state array
- * @param mask 128-bit mask
- * @return output
- */
-JEMALLOC_ALWAYS_INLINE __m128i mm_recursion(__m128i *a, __m128i *b,
- __m128i c, __m128i d, __m128i mask) {
- __m128i v, x, y, z;
-
- x = _mm_load_si128(a);
- y = _mm_srli_epi32(*b, SR1);
- z = _mm_srli_si128(c, SR2);
- v = _mm_slli_epi32(d, SL1);
- z = _mm_xor_si128(z, x);
- z = _mm_xor_si128(z, v);
- x = _mm_slli_si128(x, SL2);
- y = _mm_and_si128(y, mask);
- z = _mm_xor_si128(z, x);
- z = _mm_xor_si128(z, y);
- return z;
-}
-
-/**
- * This function fills the internal state array with pseudorandom
- * integers.
- */
-JEMALLOC_INLINE void gen_rand_all(sfmt_t *ctx) {
- int i;
- __m128i r, r1, r2, mask;
- mask = _mm_set_epi32(MSK4, MSK3, MSK2, MSK1);
-
- r1 = _mm_load_si128(&ctx->sfmt[N - 2].si);
- r2 = _mm_load_si128(&ctx->sfmt[N - 1].si);
- for (i = 0; i < N - POS1; i++) {
- r = mm_recursion(&ctx->sfmt[i].si, &ctx->sfmt[i + POS1].si, r1, r2,
- mask);
- _mm_store_si128(&ctx->sfmt[i].si, r);
- r1 = r2;
- r2 = r;
- }
- for (; i < N; i++) {
- r = mm_recursion(&ctx->sfmt[i].si, &ctx->sfmt[i + POS1 - N].si, r1, r2,
- mask);
- _mm_store_si128(&ctx->sfmt[i].si, r);
- r1 = r2;
- r2 = r;
- }
-}
-
-/**
- * This function fills the user-specified array with pseudorandom
- * integers.
- *
- * @param array an 128-bit array to be filled by pseudorandom numbers.
- * @param size number of 128-bit pesudorandom numbers to be generated.
- */
-JEMALLOC_INLINE void gen_rand_array(sfmt_t *ctx, w128_t *array, int size) {
- int i, j;
- __m128i r, r1, r2, mask;
- mask = _mm_set_epi32(MSK4, MSK3, MSK2, MSK1);
-
- r1 = _mm_load_si128(&ctx->sfmt[N - 2].si);
- r2 = _mm_load_si128(&ctx->sfmt[N - 1].si);
- for (i = 0; i < N - POS1; i++) {
- r = mm_recursion(&ctx->sfmt[i].si, &ctx->sfmt[i + POS1].si, r1, r2,
- mask);
- _mm_store_si128(&array[i].si, r);
- r1 = r2;
- r2 = r;
- }
- for (; i < N; i++) {
- r = mm_recursion(&ctx->sfmt[i].si, &array[i + POS1 - N].si, r1, r2,
- mask);
- _mm_store_si128(&array[i].si, r);
- r1 = r2;
- r2 = r;
- }
- /* main loop */
- for (; i < size - N; i++) {
- r = mm_recursion(&array[i - N].si, &array[i + POS1 - N].si, r1, r2,
- mask);
- _mm_store_si128(&array[i].si, r);
- r1 = r2;
- r2 = r;
- }
- for (j = 0; j < 2 * N - size; j++) {
- r = _mm_load_si128(&array[j + size - N].si);
- _mm_store_si128(&ctx->sfmt[j].si, r);
- }
- for (; i < size; i++) {
- r = mm_recursion(&array[i - N].si, &array[i + POS1 - N].si, r1, r2,
- mask);
- _mm_store_si128(&array[i].si, r);
- _mm_store_si128(&ctx->sfmt[j++].si, r);
- r1 = r2;
- r2 = r;
- }
-}
-
-#endif
diff --git a/memory/jemalloc/src/test/include/test/SFMT.h b/memory/jemalloc/src/test/include/test/SFMT.h
deleted file mode 100644
index 09c1607dd..000000000
--- a/memory/jemalloc/src/test/include/test/SFMT.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-/**
- * @file SFMT.h
- *
- * @brief SIMD oriented Fast Mersenne Twister(SFMT) pseudorandom
- * number generator
- *
- * @author Mutsuo Saito (Hiroshima University)
- * @author Makoto Matsumoto (Hiroshima University)
- *
- * Copyright (C) 2006, 2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. All rights reserved.
- *
- * The new BSD License is applied to this software.
- * see LICENSE.txt
- *
- * @note We assume that your system has inttypes.h. If your system
- * doesn't have inttypes.h, you have to typedef uint32_t and uint64_t,
- * and you have to define PRIu64 and PRIx64 in this file as follows:
- * @verbatim
- typedef unsigned int uint32_t
- typedef unsigned long long uint64_t
- #define PRIu64 "llu"
- #define PRIx64 "llx"
-@endverbatim
- * uint32_t must be exactly 32-bit unsigned integer type (no more, no
- * less), and uint64_t must be exactly 64-bit unsigned integer type.
- * PRIu64 and PRIx64 are used for printf function to print 64-bit
- * unsigned int and 64-bit unsigned int in hexadecimal format.
- */
-
-#ifndef SFMT_H
-#define SFMT_H
-
-typedef struct sfmt_s sfmt_t;
-
-uint32_t gen_rand32(sfmt_t *ctx);
-uint32_t gen_rand32_range(sfmt_t *ctx, uint32_t limit);
-uint64_t gen_rand64(sfmt_t *ctx);
-uint64_t gen_rand64_range(sfmt_t *ctx, uint64_t limit);
-void fill_array32(sfmt_t *ctx, uint32_t *array, int size);
-void fill_array64(sfmt_t *ctx, uint64_t *array, int size);
-sfmt_t *init_gen_rand(uint32_t seed);
-sfmt_t *init_by_array(uint32_t *init_key, int key_length);
-void fini_gen_rand(sfmt_t *ctx);
-const char *get_idstring(void);
-int get_min_array_size32(void);
-int get_min_array_size64(void);
-
-#ifndef JEMALLOC_ENABLE_INLINE
-double to_real1(uint32_t v);
-double genrand_real1(sfmt_t *ctx);
-double to_real2(uint32_t v);
-double genrand_real2(sfmt_t *ctx);
-double to_real3(uint32_t v);
-double genrand_real3(sfmt_t *ctx);
-double to_res53(uint64_t v);
-double to_res53_mix(uint32_t x, uint32_t y);
-double genrand_res53(sfmt_t *ctx);
-double genrand_res53_mix(sfmt_t *ctx);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(SFMT_C_))
-/* These real versions are due to Isaku Wada */
-/** generates a random number on [0,1]-real-interval */
-JEMALLOC_INLINE double to_real1(uint32_t v)
-{
- return v * (1.0/4294967295.0);
- /* divided by 2^32-1 */
-}
-
-/** generates a random number on [0,1]-real-interval */
-JEMALLOC_INLINE double genrand_real1(sfmt_t *ctx)
-{
- return to_real1(gen_rand32(ctx));
-}
-
-/** generates a random number on [0,1)-real-interval */
-JEMALLOC_INLINE double to_real2(uint32_t v)
-{
- return v * (1.0/4294967296.0);
- /* divided by 2^32 */
-}
-
-/** generates a random number on [0,1)-real-interval */
-JEMALLOC_INLINE double genrand_real2(sfmt_t *ctx)
-{
- return to_real2(gen_rand32(ctx));
-}
-
-/** generates a random number on (0,1)-real-interval */
-JEMALLOC_INLINE double to_real3(uint32_t v)
-{
- return (((double)v) + 0.5)*(1.0/4294967296.0);
- /* divided by 2^32 */
-}
-
-/** generates a random number on (0,1)-real-interval */
-JEMALLOC_INLINE double genrand_real3(sfmt_t *ctx)
-{
- return to_real3(gen_rand32(ctx));
-}
-/** These real versions are due to Isaku Wada */
-
-/** generates a random number on [0,1) with 53-bit resolution*/
-JEMALLOC_INLINE double to_res53(uint64_t v)
-{
- return v * (1.0/18446744073709551616.0L);
-}
-
-/** generates a random number on [0,1) with 53-bit resolution from two
- * 32 bit integers */
-JEMALLOC_INLINE double to_res53_mix(uint32_t x, uint32_t y)
-{
- return to_res53(x | ((uint64_t)y << 32));
-}
-
-/** generates a random number on [0,1) with 53-bit resolution
- */
-JEMALLOC_INLINE double genrand_res53(sfmt_t *ctx)
-{
- return to_res53(gen_rand64(ctx));
-}
-
-/** generates a random number on [0,1) with 53-bit resolution
- using 32bit integer.
- */
-JEMALLOC_INLINE double genrand_res53_mix(sfmt_t *ctx)
-{
- uint32_t x, y;
-
- x = gen_rand32(ctx);
- y = gen_rand32(ctx);
- return to_res53_mix(x, y);
-}
-#endif
-#endif
diff --git a/memory/jemalloc/src/test/include/test/btalloc.h b/memory/jemalloc/src/test/include/test/btalloc.h
deleted file mode 100644
index c3f9d4df7..000000000
--- a/memory/jemalloc/src/test/include/test/btalloc.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* btalloc() provides a mechanism for allocating via permuted backtraces. */
-void *btalloc(size_t size, unsigned bits);
-
-#define btalloc_n_proto(n) \
-void *btalloc_##n(size_t size, unsigned bits);
-btalloc_n_proto(0)
-btalloc_n_proto(1)
-
-#define btalloc_n_gen(n) \
-void * \
-btalloc_##n(size_t size, unsigned bits) \
-{ \
- void *p; \
- \
- if (bits == 0) \
- p = mallocx(size, 0); \
- else { \
- switch (bits & 0x1U) { \
- case 0: \
- p = (btalloc_0(size, bits >> 1)); \
- break; \
- case 1: \
- p = (btalloc_1(size, bits >> 1)); \
- break; \
- default: not_reached(); \
- } \
- } \
- /* Intentionally sabotage tail call optimization. */ \
- assert_ptr_not_null(p, "Unexpected mallocx() failure"); \
- return (p); \
-}
diff --git a/memory/jemalloc/src/test/include/test/jemalloc_test.h.in b/memory/jemalloc/src/test/include/test/jemalloc_test.h.in
deleted file mode 100644
index 1f36e4695..000000000
--- a/memory/jemalloc/src/test/include/test/jemalloc_test.h.in
+++ /dev/null
@@ -1,163 +0,0 @@
-#include <limits.h>
-#ifndef SIZE_T_MAX
-# define SIZE_T_MAX SIZE_MAX
-#endif
-#include <stdlib.h>
-#include <stdarg.h>
-#include <stdbool.h>
-#include <errno.h>
-#include <math.h>
-#include <string.h>
-#ifdef _WIN32
-# include "msvc_compat/strings.h"
-#endif
-
-#ifdef _WIN32
-# include <windows.h>
-# include "msvc_compat/windows_extra.h"
-#else
-# include <pthread.h>
-#endif
-
-#include "test/jemalloc_test_defs.h"
-
-#ifdef JEMALLOC_OSSPIN
-# include <libkern/OSAtomic.h>
-#endif
-
-#if defined(HAVE_ALTIVEC) && !defined(__APPLE__)
-# include <altivec.h>
-#endif
-#ifdef HAVE_SSE2
-# include <emmintrin.h>
-#endif
-
-/******************************************************************************/
-/*
- * For unit tests, expose all public and private interfaces.
- */
-#ifdef JEMALLOC_UNIT_TEST
-# define JEMALLOC_JET
-# define JEMALLOC_MANGLE
-# include "jemalloc/internal/jemalloc_internal.h"
-
-/******************************************************************************/
-/*
- * For integration tests, expose the public jemalloc interfaces, but only
- * expose the minimum necessary internal utility code (to avoid re-implementing
- * essentially identical code within the test infrastructure).
- */
-#elif defined(JEMALLOC_INTEGRATION_TEST)
-# define JEMALLOC_MANGLE
-# include "jemalloc/jemalloc@install_suffix@.h"
-# include "jemalloc/internal/jemalloc_internal_defs.h"
-# include "jemalloc/internal/jemalloc_internal_macros.h"
-
-static const bool config_debug =
-#ifdef JEMALLOC_DEBUG
- true
-#else
- false
-#endif
- ;
-
-# define JEMALLOC_N(n) @private_namespace@##n
-# include "jemalloc/internal/private_namespace.h"
-
-# define JEMALLOC_H_TYPES
-# define JEMALLOC_H_STRUCTS
-# define JEMALLOC_H_EXTERNS
-# define JEMALLOC_H_INLINES
-# include "jemalloc/internal/nstime.h"
-# include "jemalloc/internal/util.h"
-# include "jemalloc/internal/qr.h"
-# include "jemalloc/internal/ql.h"
-# undef JEMALLOC_H_TYPES
-# undef JEMALLOC_H_STRUCTS
-# undef JEMALLOC_H_EXTERNS
-# undef JEMALLOC_H_INLINES
-
-/******************************************************************************/
-/*
- * For stress tests, expose the public jemalloc interfaces with name mangling
- * so that they can be tested as e.g. malloc() and free(). Also expose the
- * public jemalloc interfaces with jet_ prefixes, so that stress tests can use
- * a separate allocator for their internal data structures.
- */
-#elif defined(JEMALLOC_STRESS_TEST)
-# include "jemalloc/jemalloc@install_suffix@.h"
-
-# include "jemalloc/jemalloc_protos_jet.h"
-
-# define JEMALLOC_JET
-# include "jemalloc/internal/jemalloc_internal.h"
-# include "jemalloc/internal/public_unnamespace.h"
-# undef JEMALLOC_JET
-
-# include "jemalloc/jemalloc_rename.h"
-# define JEMALLOC_MANGLE
-# ifdef JEMALLOC_STRESS_TESTLIB
-# include "jemalloc/jemalloc_mangle_jet.h"
-# else
-# include "jemalloc/jemalloc_mangle.h"
-# endif
-
-/******************************************************************************/
-/*
- * This header does dangerous things, the effects of which only test code
- * should be subject to.
- */
-#else
-# error "This header cannot be included outside a testing context"
-#endif
-
-/******************************************************************************/
-/*
- * Common test utilities.
- */
-#include "test/btalloc.h"
-#include "test/math.h"
-#include "test/mtx.h"
-#include "test/mq.h"
-#include "test/test.h"
-#include "test/timer.h"
-#include "test/thd.h"
-#define MEXP 19937
-#include "test/SFMT.h"
-
-/******************************************************************************/
-/*
- * Define always-enabled assertion macros, so that test assertions execute even
- * if assertions are disabled in the library code.
- */
-#undef assert
-#undef not_reached
-#undef not_implemented
-#undef assert_not_implemented
-
-#define assert(e) do { \
- if (!(e)) { \
- malloc_printf( \
- "<jemalloc>: %s:%d: Failed assertion: \"%s\"\n", \
- __FILE__, __LINE__, #e); \
- abort(); \
- } \
-} while (0)
-
-#define not_reached() do { \
- malloc_printf( \
- "<jemalloc>: %s:%d: Unreachable code reached\n", \
- __FILE__, __LINE__); \
- abort(); \
-} while (0)
-
-#define not_implemented() do { \
- malloc_printf("<jemalloc>: %s:%d: Not implemented\n", \
- __FILE__, __LINE__); \
- abort(); \
-} while (0)
-
-#define assert_not_implemented(e) do { \
- if (!(e)) \
- not_implemented(); \
-} while (0)
diff --git a/memory/jemalloc/src/test/include/test/jemalloc_test_defs.h.in b/memory/jemalloc/src/test/include/test/jemalloc_test_defs.h.in
deleted file mode 100644
index 5cc8532a3..000000000
--- a/memory/jemalloc/src/test/include/test/jemalloc_test_defs.h.in
+++ /dev/null
@@ -1,9 +0,0 @@
-#include "jemalloc/internal/jemalloc_internal_defs.h"
-#include "jemalloc/internal/jemalloc_internal_decls.h"
-
-/*
- * For use by SFMT. configure.ac doesn't actually define HAVE_SSE2 because its
- * dependencies are notoriously unportable in practice.
- */
-#undef HAVE_SSE2
-#undef HAVE_ALTIVEC
diff --git a/memory/jemalloc/src/test/include/test/math.h b/memory/jemalloc/src/test/include/test/math.h
deleted file mode 100644
index b057b29a1..000000000
--- a/memory/jemalloc/src/test/include/test/math.h
+++ /dev/null
@@ -1,311 +0,0 @@
-#ifndef JEMALLOC_ENABLE_INLINE
-double ln_gamma(double x);
-double i_gamma(double x, double p, double ln_gamma_p);
-double pt_norm(double p);
-double pt_chi2(double p, double df, double ln_gamma_df_2);
-double pt_gamma(double p, double shape, double scale, double ln_gamma_shape);
-#endif
-
-#if (defined(JEMALLOC_ENABLE_INLINE) || defined(MATH_C_))
-/*
- * Compute the natural log of Gamma(x), accurate to 10 decimal places.
- *
- * This implementation is based on:
- *
- * Pike, M.C., I.D. Hill (1966) Algorithm 291: Logarithm of Gamma function
- * [S14]. Communications of the ACM 9(9):684.
- */
-JEMALLOC_INLINE double
-ln_gamma(double x)
-{
- double f, z;
-
- assert(x > 0.0);
-
- if (x < 7.0) {
- f = 1.0;
- z = x;
- while (z < 7.0) {
- f *= z;
- z += 1.0;
- }
- x = z;
- f = -log(f);
- } else
- f = 0.0;
-
- z = 1.0 / (x * x);
-
- return (f + (x-0.5) * log(x) - x + 0.918938533204673 +
- (((-0.000595238095238 * z + 0.000793650793651) * z -
- 0.002777777777778) * z + 0.083333333333333) / x);
-}
-
-/*
- * Compute the incomplete Gamma ratio for [0..x], where p is the shape
- * parameter, and ln_gamma_p is ln_gamma(p).
- *
- * This implementation is based on:
- *
- * Bhattacharjee, G.P. (1970) Algorithm AS 32: The incomplete Gamma integral.
- * Applied Statistics 19:285-287.
- */
-JEMALLOC_INLINE double
-i_gamma(double x, double p, double ln_gamma_p)
-{
- double acu, factor, oflo, gin, term, rn, a, b, an, dif;
- double pn[6];
- unsigned i;
-
- assert(p > 0.0);
- assert(x >= 0.0);
-
- if (x == 0.0)
- return (0.0);
-
- acu = 1.0e-10;
- oflo = 1.0e30;
- gin = 0.0;
- factor = exp(p * log(x) - x - ln_gamma_p);
-
- if (x <= 1.0 || x < p) {
- /* Calculation by series expansion. */
- gin = 1.0;
- term = 1.0;
- rn = p;
-
- while (true) {
- rn += 1.0;
- term *= x / rn;
- gin += term;
- if (term <= acu) {
- gin *= factor / p;
- return (gin);
- }
- }
- } else {
- /* Calculation by continued fraction. */
- a = 1.0 - p;
- b = a + x + 1.0;
- term = 0.0;
- pn[0] = 1.0;
- pn[1] = x;
- pn[2] = x + 1.0;
- pn[3] = x * b;
- gin = pn[2] / pn[3];
-
- while (true) {
- a += 1.0;
- b += 2.0;
- term += 1.0;
- an = a * term;
- for (i = 0; i < 2; i++)
- pn[i+4] = b * pn[i+2] - an * pn[i];
- if (pn[5] != 0.0) {
- rn = pn[4] / pn[5];
- dif = fabs(gin - rn);
- if (dif <= acu && dif <= acu * rn) {
- gin = 1.0 - factor * gin;
- return (gin);
- }
- gin = rn;
- }
- for (i = 0; i < 4; i++)
- pn[i] = pn[i+2];
-
- if (fabs(pn[4]) >= oflo) {
- for (i = 0; i < 4; i++)
- pn[i] /= oflo;
- }
- }
- }
-}
-
-/*
- * Given a value p in [0..1] of the lower tail area of the normal distribution,
- * compute the limit on the definite integral from [-inf..z] that satisfies p,
- * accurate to 16 decimal places.
- *
- * This implementation is based on:
- *
- * Wichura, M.J. (1988) Algorithm AS 241: The percentage points of the normal
- * distribution. Applied Statistics 37(3):477-484.
- */
-JEMALLOC_INLINE double
-pt_norm(double p)
-{
- double q, r, ret;
-
- assert(p > 0.0 && p < 1.0);
-
- q = p - 0.5;
- if (fabs(q) <= 0.425) {
- /* p close to 1/2. */
- r = 0.180625 - q * q;
- return (q * (((((((2.5090809287301226727e3 * r +
- 3.3430575583588128105e4) * r + 6.7265770927008700853e4) * r
- + 4.5921953931549871457e4) * r + 1.3731693765509461125e4) *
- r + 1.9715909503065514427e3) * r + 1.3314166789178437745e2)
- * r + 3.3871328727963666080e0) /
- (((((((5.2264952788528545610e3 * r +
- 2.8729085735721942674e4) * r + 3.9307895800092710610e4) * r
- + 2.1213794301586595867e4) * r + 5.3941960214247511077e3) *
- r + 6.8718700749205790830e2) * r + 4.2313330701600911252e1)
- * r + 1.0));
- } else {
- if (q < 0.0)
- r = p;
- else
- r = 1.0 - p;
- assert(r > 0.0);
-
- r = sqrt(-log(r));
- if (r <= 5.0) {
- /* p neither close to 1/2 nor 0 or 1. */
- r -= 1.6;
- ret = ((((((((7.74545014278341407640e-4 * r +
- 2.27238449892691845833e-2) * r +
- 2.41780725177450611770e-1) * r +
- 1.27045825245236838258e0) * r +
- 3.64784832476320460504e0) * r +
- 5.76949722146069140550e0) * r +
- 4.63033784615654529590e0) * r +
- 1.42343711074968357734e0) /
- (((((((1.05075007164441684324e-9 * r +
- 5.47593808499534494600e-4) * r +
- 1.51986665636164571966e-2)
- * r + 1.48103976427480074590e-1) * r +
- 6.89767334985100004550e-1) * r +
- 1.67638483018380384940e0) * r +
- 2.05319162663775882187e0) * r + 1.0));
- } else {
- /* p near 0 or 1. */
- r -= 5.0;
- ret = ((((((((2.01033439929228813265e-7 * r +
- 2.71155556874348757815e-5) * r +
- 1.24266094738807843860e-3) * r +
- 2.65321895265761230930e-2) * r +
- 2.96560571828504891230e-1) * r +
- 1.78482653991729133580e0) * r +
- 5.46378491116411436990e0) * r +
- 6.65790464350110377720e0) /
- (((((((2.04426310338993978564e-15 * r +
- 1.42151175831644588870e-7) * r +
- 1.84631831751005468180e-5) * r +
- 7.86869131145613259100e-4) * r +
- 1.48753612908506148525e-2) * r +
- 1.36929880922735805310e-1) * r +
- 5.99832206555887937690e-1)
- * r + 1.0));
- }
- if (q < 0.0)
- ret = -ret;
- return (ret);
- }
-}
-
-/*
- * Given a value p in [0..1] of the lower tail area of the Chi^2 distribution
- * with df degrees of freedom, where ln_gamma_df_2 is ln_gamma(df/2.0), compute
- * the upper limit on the definite integral from [0..z] that satisfies p,
- * accurate to 12 decimal places.
- *
- * This implementation is based on:
- *
- * Best, D.J., D.E. Roberts (1975) Algorithm AS 91: The percentage points of
- * the Chi^2 distribution. Applied Statistics 24(3):385-388.
- *
- * Shea, B.L. (1991) Algorithm AS R85: A remark on AS 91: The percentage
- * points of the Chi^2 distribution. Applied Statistics 40(1):233-235.
- */
-JEMALLOC_INLINE double
-pt_chi2(double p, double df, double ln_gamma_df_2)
-{
- double e, aa, xx, c, ch, a, q, p1, p2, t, x, b, s1, s2, s3, s4, s5, s6;
- unsigned i;
-
- assert(p >= 0.0 && p < 1.0);
- assert(df > 0.0);
-
- e = 5.0e-7;
- aa = 0.6931471805;
-
- xx = 0.5 * df;
- c = xx - 1.0;
-
- if (df < -1.24 * log(p)) {
- /* Starting approximation for small Chi^2. */
- ch = pow(p * xx * exp(ln_gamma_df_2 + xx * aa), 1.0 / xx);
- if (ch - e < 0.0)
- return (ch);
- } else {
- if (df > 0.32) {
- x = pt_norm(p);
- /*
- * Starting approximation using Wilson and Hilferty
- * estimate.
- */
- p1 = 0.222222 / df;
- ch = df * pow(x * sqrt(p1) + 1.0 - p1, 3.0);
- /* Starting approximation for p tending to 1. */
- if (ch > 2.2 * df + 6.0) {
- ch = -2.0 * (log(1.0 - p) - c * log(0.5 * ch) +
- ln_gamma_df_2);
- }
- } else {
- ch = 0.4;
- a = log(1.0 - p);
- while (true) {
- q = ch;
- p1 = 1.0 + ch * (4.67 + ch);
- p2 = ch * (6.73 + ch * (6.66 + ch));
- t = -0.5 + (4.67 + 2.0 * ch) / p1 - (6.73 + ch
- * (13.32 + 3.0 * ch)) / p2;
- ch -= (1.0 - exp(a + ln_gamma_df_2 + 0.5 * ch +
- c * aa) * p2 / p1) / t;
- if (fabs(q / ch - 1.0) - 0.01 <= 0.0)
- break;
- }
- }
- }
-
- for (i = 0; i < 20; i++) {
- /* Calculation of seven-term Taylor series. */
- q = ch;
- p1 = 0.5 * ch;
- if (p1 < 0.0)
- return (-1.0);
- p2 = p - i_gamma(p1, xx, ln_gamma_df_2);
- t = p2 * exp(xx * aa + ln_gamma_df_2 + p1 - c * log(ch));
- b = t / ch;
- a = 0.5 * t - b * c;
- s1 = (210.0 + a * (140.0 + a * (105.0 + a * (84.0 + a * (70.0 +
- 60.0 * a))))) / 420.0;
- s2 = (420.0 + a * (735.0 + a * (966.0 + a * (1141.0 + 1278.0 *
- a)))) / 2520.0;
- s3 = (210.0 + a * (462.0 + a * (707.0 + 932.0 * a))) / 2520.0;
- s4 = (252.0 + a * (672.0 + 1182.0 * a) + c * (294.0 + a *
- (889.0 + 1740.0 * a))) / 5040.0;
- s5 = (84.0 + 264.0 * a + c * (175.0 + 606.0 * a)) / 2520.0;
- s6 = (120.0 + c * (346.0 + 127.0 * c)) / 5040.0;
- ch += t * (1.0 + 0.5 * t * s1 - b * c * (s1 - b * (s2 - b * (s3
- - b * (s4 - b * (s5 - b * s6))))));
- if (fabs(q / ch - 1.0) <= e)
- break;
- }
-
- return (ch);
-}
-
-/*
- * Given a value p in [0..1] and Gamma distribution shape and scale parameters,
- * compute the upper limit on the definite integral from [0..z] that satisfies
- * p.
- */
-JEMALLOC_INLINE double
-pt_gamma(double p, double shape, double scale, double ln_gamma_shape)
-{
-
- return (pt_chi2(p, shape * 2.0, ln_gamma_shape) * 0.5 * scale);
-}
-#endif
diff --git a/memory/jemalloc/src/test/include/test/mq.h b/memory/jemalloc/src/test/include/test/mq.h
deleted file mode 100644
index 7c4df4931..000000000
--- a/memory/jemalloc/src/test/include/test/mq.h
+++ /dev/null
@@ -1,109 +0,0 @@
-void mq_nanosleep(unsigned ns);
-
-/*
- * Simple templated message queue implementation that relies on only mutexes for
- * synchronization (which reduces portability issues). Given the following
- * setup:
- *
- * typedef struct mq_msg_s mq_msg_t;
- * struct mq_msg_s {
- * mq_msg(mq_msg_t) link;
- * [message data]
- * };
- * mq_gen(, mq_, mq_t, mq_msg_t, link)
- *
- * The API is as follows:
- *
- * bool mq_init(mq_t *mq);
- * void mq_fini(mq_t *mq);
- * unsigned mq_count(mq_t *mq);
- * mq_msg_t *mq_tryget(mq_t *mq);
- * mq_msg_t *mq_get(mq_t *mq);
- * void mq_put(mq_t *mq, mq_msg_t *msg);
- *
- * The message queue linkage embedded in each message is to be treated as
- * externally opaque (no need to initialize or clean up externally). mq_fini()
- * does not perform any cleanup of messages, since it knows nothing of their
- * payloads.
- */
-#define mq_msg(a_mq_msg_type) ql_elm(a_mq_msg_type)
-
-#define mq_gen(a_attr, a_prefix, a_mq_type, a_mq_msg_type, a_field) \
-typedef struct { \
- mtx_t lock; \
- ql_head(a_mq_msg_type) msgs; \
- unsigned count; \
-} a_mq_type; \
-a_attr bool \
-a_prefix##init(a_mq_type *mq) { \
- \
- if (mtx_init(&mq->lock)) \
- return (true); \
- ql_new(&mq->msgs); \
- mq->count = 0; \
- return (false); \
-} \
-a_attr void \
-a_prefix##fini(a_mq_type *mq) \
-{ \
- \
- mtx_fini(&mq->lock); \
-} \
-a_attr unsigned \
-a_prefix##count(a_mq_type *mq) \
-{ \
- unsigned count; \
- \
- mtx_lock(&mq->lock); \
- count = mq->count; \
- mtx_unlock(&mq->lock); \
- return (count); \
-} \
-a_attr a_mq_msg_type * \
-a_prefix##tryget(a_mq_type *mq) \
-{ \
- a_mq_msg_type *msg; \
- \
- mtx_lock(&mq->lock); \
- msg = ql_first(&mq->msgs); \
- if (msg != NULL) { \
- ql_head_remove(&mq->msgs, a_mq_msg_type, a_field); \
- mq->count--; \
- } \
- mtx_unlock(&mq->lock); \
- return (msg); \
-} \
-a_attr a_mq_msg_type * \
-a_prefix##get(a_mq_type *mq) \
-{ \
- a_mq_msg_type *msg; \
- unsigned ns; \
- \
- msg = a_prefix##tryget(mq); \
- if (msg != NULL) \
- return (msg); \
- \
- ns = 1; \
- while (true) { \
- mq_nanosleep(ns); \
- msg = a_prefix##tryget(mq); \
- if (msg != NULL) \
- return (msg); \
- if (ns < 1000*1000*1000) { \
- /* Double sleep time, up to max 1 second. */ \
- ns <<= 1; \
- if (ns > 1000*1000*1000) \
- ns = 1000*1000*1000; \
- } \
- } \
-} \
-a_attr void \
-a_prefix##put(a_mq_type *mq, a_mq_msg_type *msg) \
-{ \
- \
- mtx_lock(&mq->lock); \
- ql_elm_new(msg, a_field); \
- ql_tail_insert(&mq->msgs, msg, a_field); \
- mq->count++; \
- mtx_unlock(&mq->lock); \
-}
diff --git a/memory/jemalloc/src/test/include/test/mtx.h b/memory/jemalloc/src/test/include/test/mtx.h
deleted file mode 100644
index 58afbc3d1..000000000
--- a/memory/jemalloc/src/test/include/test/mtx.h
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * mtx is a slightly simplified version of malloc_mutex. This code duplication
- * is unfortunate, but there are allocator bootstrapping considerations that
- * would leak into the test infrastructure if malloc_mutex were used directly
- * in tests.
- */
-
-typedef struct {
-#ifdef _WIN32
- CRITICAL_SECTION lock;
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
- os_unfair_lock lock;
-#elif (defined(JEMALLOC_OSSPIN))
- OSSpinLock lock;
-#else
- pthread_mutex_t lock;
-#endif
-} mtx_t;
-
-bool mtx_init(mtx_t *mtx);
-void mtx_fini(mtx_t *mtx);
-void mtx_lock(mtx_t *mtx);
-void mtx_unlock(mtx_t *mtx);
diff --git a/memory/jemalloc/src/test/include/test/test.h b/memory/jemalloc/src/test/include/test/test.h
deleted file mode 100644
index c8112eb8b..000000000
--- a/memory/jemalloc/src/test/include/test/test.h
+++ /dev/null
@@ -1,333 +0,0 @@
-#define ASSERT_BUFSIZE 256
-
-#define assert_cmp(t, a, b, cmp, neg_cmp, pri, ...) do { \
- t a_ = (a); \
- t b_ = (b); \
- if (!(a_ cmp b_)) { \
- char prefix[ASSERT_BUFSIZE]; \
- char message[ASSERT_BUFSIZE]; \
- malloc_snprintf(prefix, sizeof(prefix), \
- "%s:%s:%d: Failed assertion: " \
- "(%s) "#cmp" (%s) --> " \
- "%"pri" "#neg_cmp" %"pri": ", \
- __func__, __FILE__, __LINE__, \
- #a, #b, a_, b_); \
- malloc_snprintf(message, sizeof(message), __VA_ARGS__); \
- p_test_fail(prefix, message); \
- } \
-} while (0)
-
-#define assert_ptr_eq(a, b, ...) assert_cmp(void *, a, b, ==, \
- !=, "p", __VA_ARGS__)
-#define assert_ptr_ne(a, b, ...) assert_cmp(void *, a, b, !=, \
- ==, "p", __VA_ARGS__)
-#define assert_ptr_null(a, ...) assert_cmp(void *, a, NULL, ==, \
- !=, "p", __VA_ARGS__)
-#define assert_ptr_not_null(a, ...) assert_cmp(void *, a, NULL, !=, \
- ==, "p", __VA_ARGS__)
-
-#define assert_c_eq(a, b, ...) assert_cmp(char, a, b, ==, !=, "c", __VA_ARGS__)
-#define assert_c_ne(a, b, ...) assert_cmp(char, a, b, !=, ==, "c", __VA_ARGS__)
-#define assert_c_lt(a, b, ...) assert_cmp(char, a, b, <, >=, "c", __VA_ARGS__)
-#define assert_c_le(a, b, ...) assert_cmp(char, a, b, <=, >, "c", __VA_ARGS__)
-#define assert_c_ge(a, b, ...) assert_cmp(char, a, b, >=, <, "c", __VA_ARGS__)
-#define assert_c_gt(a, b, ...) assert_cmp(char, a, b, >, <=, "c", __VA_ARGS__)
-
-#define assert_x_eq(a, b, ...) assert_cmp(int, a, b, ==, !=, "#x", __VA_ARGS__)
-#define assert_x_ne(a, b, ...) assert_cmp(int, a, b, !=, ==, "#x", __VA_ARGS__)
-#define assert_x_lt(a, b, ...) assert_cmp(int, a, b, <, >=, "#x", __VA_ARGS__)
-#define assert_x_le(a, b, ...) assert_cmp(int, a, b, <=, >, "#x", __VA_ARGS__)
-#define assert_x_ge(a, b, ...) assert_cmp(int, a, b, >=, <, "#x", __VA_ARGS__)
-#define assert_x_gt(a, b, ...) assert_cmp(int, a, b, >, <=, "#x", __VA_ARGS__)
-
-#define assert_d_eq(a, b, ...) assert_cmp(int, a, b, ==, !=, "d", __VA_ARGS__)
-#define assert_d_ne(a, b, ...) assert_cmp(int, a, b, !=, ==, "d", __VA_ARGS__)
-#define assert_d_lt(a, b, ...) assert_cmp(int, a, b, <, >=, "d", __VA_ARGS__)
-#define assert_d_le(a, b, ...) assert_cmp(int, a, b, <=, >, "d", __VA_ARGS__)
-#define assert_d_ge(a, b, ...) assert_cmp(int, a, b, >=, <, "d", __VA_ARGS__)
-#define assert_d_gt(a, b, ...) assert_cmp(int, a, b, >, <=, "d", __VA_ARGS__)
-
-#define assert_u_eq(a, b, ...) assert_cmp(int, a, b, ==, !=, "u", __VA_ARGS__)
-#define assert_u_ne(a, b, ...) assert_cmp(int, a, b, !=, ==, "u", __VA_ARGS__)
-#define assert_u_lt(a, b, ...) assert_cmp(int, a, b, <, >=, "u", __VA_ARGS__)
-#define assert_u_le(a, b, ...) assert_cmp(int, a, b, <=, >, "u", __VA_ARGS__)
-#define assert_u_ge(a, b, ...) assert_cmp(int, a, b, >=, <, "u", __VA_ARGS__)
-#define assert_u_gt(a, b, ...) assert_cmp(int, a, b, >, <=, "u", __VA_ARGS__)
-
-#define assert_ld_eq(a, b, ...) assert_cmp(long, a, b, ==, \
- !=, "ld", __VA_ARGS__)
-#define assert_ld_ne(a, b, ...) assert_cmp(long, a, b, !=, \
- ==, "ld", __VA_ARGS__)
-#define assert_ld_lt(a, b, ...) assert_cmp(long, a, b, <, \
- >=, "ld", __VA_ARGS__)
-#define assert_ld_le(a, b, ...) assert_cmp(long, a, b, <=, \
- >, "ld", __VA_ARGS__)
-#define assert_ld_ge(a, b, ...) assert_cmp(long, a, b, >=, \
- <, "ld", __VA_ARGS__)
-#define assert_ld_gt(a, b, ...) assert_cmp(long, a, b, >, \
- <=, "ld", __VA_ARGS__)
-
-#define assert_lu_eq(a, b, ...) assert_cmp(unsigned long, \
- a, b, ==, !=, "lu", __VA_ARGS__)
-#define assert_lu_ne(a, b, ...) assert_cmp(unsigned long, \
- a, b, !=, ==, "lu", __VA_ARGS__)
-#define assert_lu_lt(a, b, ...) assert_cmp(unsigned long, \
- a, b, <, >=, "lu", __VA_ARGS__)
-#define assert_lu_le(a, b, ...) assert_cmp(unsigned long, \
- a, b, <=, >, "lu", __VA_ARGS__)
-#define assert_lu_ge(a, b, ...) assert_cmp(unsigned long, \
- a, b, >=, <, "lu", __VA_ARGS__)
-#define assert_lu_gt(a, b, ...) assert_cmp(unsigned long, \
- a, b, >, <=, "lu", __VA_ARGS__)
-
-#define assert_qd_eq(a, b, ...) assert_cmp(long long, a, b, ==, \
- !=, "qd", __VA_ARGS__)
-#define assert_qd_ne(a, b, ...) assert_cmp(long long, a, b, !=, \
- ==, "qd", __VA_ARGS__)
-#define assert_qd_lt(a, b, ...) assert_cmp(long long, a, b, <, \
- >=, "qd", __VA_ARGS__)
-#define assert_qd_le(a, b, ...) assert_cmp(long long, a, b, <=, \
- >, "qd", __VA_ARGS__)
-#define assert_qd_ge(a, b, ...) assert_cmp(long long, a, b, >=, \
- <, "qd", __VA_ARGS__)
-#define assert_qd_gt(a, b, ...) assert_cmp(long long, a, b, >, \
- <=, "qd", __VA_ARGS__)
-
-#define assert_qu_eq(a, b, ...) assert_cmp(unsigned long long, \
- a, b, ==, !=, "qu", __VA_ARGS__)
-#define assert_qu_ne(a, b, ...) assert_cmp(unsigned long long, \
- a, b, !=, ==, "qu", __VA_ARGS__)
-#define assert_qu_lt(a, b, ...) assert_cmp(unsigned long long, \
- a, b, <, >=, "qu", __VA_ARGS__)
-#define assert_qu_le(a, b, ...) assert_cmp(unsigned long long, \
- a, b, <=, >, "qu", __VA_ARGS__)
-#define assert_qu_ge(a, b, ...) assert_cmp(unsigned long long, \
- a, b, >=, <, "qu", __VA_ARGS__)
-#define assert_qu_gt(a, b, ...) assert_cmp(unsigned long long, \
- a, b, >, <=, "qu", __VA_ARGS__)
-
-#define assert_jd_eq(a, b, ...) assert_cmp(intmax_t, a, b, ==, \
- !=, "jd", __VA_ARGS__)
-#define assert_jd_ne(a, b, ...) assert_cmp(intmax_t, a, b, !=, \
- ==, "jd", __VA_ARGS__)
-#define assert_jd_lt(a, b, ...) assert_cmp(intmax_t, a, b, <, \
- >=, "jd", __VA_ARGS__)
-#define assert_jd_le(a, b, ...) assert_cmp(intmax_t, a, b, <=, \
- >, "jd", __VA_ARGS__)
-#define assert_jd_ge(a, b, ...) assert_cmp(intmax_t, a, b, >=, \
- <, "jd", __VA_ARGS__)
-#define assert_jd_gt(a, b, ...) assert_cmp(intmax_t, a, b, >, \
- <=, "jd", __VA_ARGS__)
-
-#define assert_ju_eq(a, b, ...) assert_cmp(uintmax_t, a, b, ==, \
- !=, "ju", __VA_ARGS__)
-#define assert_ju_ne(a, b, ...) assert_cmp(uintmax_t, a, b, !=, \
- ==, "ju", __VA_ARGS__)
-#define assert_ju_lt(a, b, ...) assert_cmp(uintmax_t, a, b, <, \
- >=, "ju", __VA_ARGS__)
-#define assert_ju_le(a, b, ...) assert_cmp(uintmax_t, a, b, <=, \
- >, "ju", __VA_ARGS__)
-#define assert_ju_ge(a, b, ...) assert_cmp(uintmax_t, a, b, >=, \
- <, "ju", __VA_ARGS__)
-#define assert_ju_gt(a, b, ...) assert_cmp(uintmax_t, a, b, >, \
- <=, "ju", __VA_ARGS__)
-
-#define assert_zd_eq(a, b, ...) assert_cmp(ssize_t, a, b, ==, \
- !=, "zd", __VA_ARGS__)
-#define assert_zd_ne(a, b, ...) assert_cmp(ssize_t, a, b, !=, \
- ==, "zd", __VA_ARGS__)
-#define assert_zd_lt(a, b, ...) assert_cmp(ssize_t, a, b, <, \
- >=, "zd", __VA_ARGS__)
-#define assert_zd_le(a, b, ...) assert_cmp(ssize_t, a, b, <=, \
- >, "zd", __VA_ARGS__)
-#define assert_zd_ge(a, b, ...) assert_cmp(ssize_t, a, b, >=, \
- <, "zd", __VA_ARGS__)
-#define assert_zd_gt(a, b, ...) assert_cmp(ssize_t, a, b, >, \
- <=, "zd", __VA_ARGS__)
-
-#define assert_zu_eq(a, b, ...) assert_cmp(size_t, a, b, ==, \
- !=, "zu", __VA_ARGS__)
-#define assert_zu_ne(a, b, ...) assert_cmp(size_t, a, b, !=, \
- ==, "zu", __VA_ARGS__)
-#define assert_zu_lt(a, b, ...) assert_cmp(size_t, a, b, <, \
- >=, "zu", __VA_ARGS__)
-#define assert_zu_le(a, b, ...) assert_cmp(size_t, a, b, <=, \
- >, "zu", __VA_ARGS__)
-#define assert_zu_ge(a, b, ...) assert_cmp(size_t, a, b, >=, \
- <, "zu", __VA_ARGS__)
-#define assert_zu_gt(a, b, ...) assert_cmp(size_t, a, b, >, \
- <=, "zu", __VA_ARGS__)
-
-#define assert_d32_eq(a, b, ...) assert_cmp(int32_t, a, b, ==, \
- !=, FMTd32, __VA_ARGS__)
-#define assert_d32_ne(a, b, ...) assert_cmp(int32_t, a, b, !=, \
- ==, FMTd32, __VA_ARGS__)
-#define assert_d32_lt(a, b, ...) assert_cmp(int32_t, a, b, <, \
- >=, FMTd32, __VA_ARGS__)
-#define assert_d32_le(a, b, ...) assert_cmp(int32_t, a, b, <=, \
- >, FMTd32, __VA_ARGS__)
-#define assert_d32_ge(a, b, ...) assert_cmp(int32_t, a, b, >=, \
- <, FMTd32, __VA_ARGS__)
-#define assert_d32_gt(a, b, ...) assert_cmp(int32_t, a, b, >, \
- <=, FMTd32, __VA_ARGS__)
-
-#define assert_u32_eq(a, b, ...) assert_cmp(uint32_t, a, b, ==, \
- !=, FMTu32, __VA_ARGS__)
-#define assert_u32_ne(a, b, ...) assert_cmp(uint32_t, a, b, !=, \
- ==, FMTu32, __VA_ARGS__)
-#define assert_u32_lt(a, b, ...) assert_cmp(uint32_t, a, b, <, \
- >=, FMTu32, __VA_ARGS__)
-#define assert_u32_le(a, b, ...) assert_cmp(uint32_t, a, b, <=, \
- >, FMTu32, __VA_ARGS__)
-#define assert_u32_ge(a, b, ...) assert_cmp(uint32_t, a, b, >=, \
- <, FMTu32, __VA_ARGS__)
-#define assert_u32_gt(a, b, ...) assert_cmp(uint32_t, a, b, >, \
- <=, FMTu32, __VA_ARGS__)
-
-#define assert_d64_eq(a, b, ...) assert_cmp(int64_t, a, b, ==, \
- !=, FMTd64, __VA_ARGS__)
-#define assert_d64_ne(a, b, ...) assert_cmp(int64_t, a, b, !=, \
- ==, FMTd64, __VA_ARGS__)
-#define assert_d64_lt(a, b, ...) assert_cmp(int64_t, a, b, <, \
- >=, FMTd64, __VA_ARGS__)
-#define assert_d64_le(a, b, ...) assert_cmp(int64_t, a, b, <=, \
- >, FMTd64, __VA_ARGS__)
-#define assert_d64_ge(a, b, ...) assert_cmp(int64_t, a, b, >=, \
- <, FMTd64, __VA_ARGS__)
-#define assert_d64_gt(a, b, ...) assert_cmp(int64_t, a, b, >, \
- <=, FMTd64, __VA_ARGS__)
-
-#define assert_u64_eq(a, b, ...) assert_cmp(uint64_t, a, b, ==, \
- !=, FMTu64, __VA_ARGS__)
-#define assert_u64_ne(a, b, ...) assert_cmp(uint64_t, a, b, !=, \
- ==, FMTu64, __VA_ARGS__)
-#define assert_u64_lt(a, b, ...) assert_cmp(uint64_t, a, b, <, \
- >=, FMTu64, __VA_ARGS__)
-#define assert_u64_le(a, b, ...) assert_cmp(uint64_t, a, b, <=, \
- >, FMTu64, __VA_ARGS__)
-#define assert_u64_ge(a, b, ...) assert_cmp(uint64_t, a, b, >=, \
- <, FMTu64, __VA_ARGS__)
-#define assert_u64_gt(a, b, ...) assert_cmp(uint64_t, a, b, >, \
- <=, FMTu64, __VA_ARGS__)
-
-#define assert_b_eq(a, b, ...) do { \
- bool a_ = (a); \
- bool b_ = (b); \
- if (!(a_ == b_)) { \
- char prefix[ASSERT_BUFSIZE]; \
- char message[ASSERT_BUFSIZE]; \
- malloc_snprintf(prefix, sizeof(prefix), \
- "%s:%s:%d: Failed assertion: " \
- "(%s) == (%s) --> %s != %s: ", \
- __func__, __FILE__, __LINE__, \
- #a, #b, a_ ? "true" : "false", \
- b_ ? "true" : "false"); \
- malloc_snprintf(message, sizeof(message), __VA_ARGS__); \
- p_test_fail(prefix, message); \
- } \
-} while (0)
-#define assert_b_ne(a, b, ...) do { \
- bool a_ = (a); \
- bool b_ = (b); \
- if (!(a_ != b_)) { \
- char prefix[ASSERT_BUFSIZE]; \
- char message[ASSERT_BUFSIZE]; \
- malloc_snprintf(prefix, sizeof(prefix), \
- "%s:%s:%d: Failed assertion: " \
- "(%s) != (%s) --> %s == %s: ", \
- __func__, __FILE__, __LINE__, \
- #a, #b, a_ ? "true" : "false", \
- b_ ? "true" : "false"); \
- malloc_snprintf(message, sizeof(message), __VA_ARGS__); \
- p_test_fail(prefix, message); \
- } \
-} while (0)
-#define assert_true(a, ...) assert_b_eq(a, true, __VA_ARGS__)
-#define assert_false(a, ...) assert_b_eq(a, false, __VA_ARGS__)
-
-#define assert_str_eq(a, b, ...) do { \
- if (strcmp((a), (b))) { \
- char prefix[ASSERT_BUFSIZE]; \
- char message[ASSERT_BUFSIZE]; \
- malloc_snprintf(prefix, sizeof(prefix), \
- "%s:%s:%d: Failed assertion: " \
- "(%s) same as (%s) --> " \
- "\"%s\" differs from \"%s\": ", \
- __func__, __FILE__, __LINE__, #a, #b, a, b); \
- malloc_snprintf(message, sizeof(message), __VA_ARGS__); \
- p_test_fail(prefix, message); \
- } \
-} while (0)
-#define assert_str_ne(a, b, ...) do { \
- if (!strcmp((a), (b))) { \
- char prefix[ASSERT_BUFSIZE]; \
- char message[ASSERT_BUFSIZE]; \
- malloc_snprintf(prefix, sizeof(prefix), \
- "%s:%s:%d: Failed assertion: " \
- "(%s) differs from (%s) --> " \
- "\"%s\" same as \"%s\": ", \
- __func__, __FILE__, __LINE__, #a, #b, a, b); \
- malloc_snprintf(message, sizeof(message), __VA_ARGS__); \
- p_test_fail(prefix, message); \
- } \
-} while (0)
-
-#define assert_not_reached(...) do { \
- char prefix[ASSERT_BUFSIZE]; \
- char message[ASSERT_BUFSIZE]; \
- malloc_snprintf(prefix, sizeof(prefix), \
- "%s:%s:%d: Unreachable code reached: ", \
- __func__, __FILE__, __LINE__); \
- malloc_snprintf(message, sizeof(message), __VA_ARGS__); \
- p_test_fail(prefix, message); \
-} while (0)
-
-/*
- * If this enum changes, corresponding changes in test/test.sh.in are also
- * necessary.
- */
-typedef enum {
- test_status_pass = 0,
- test_status_skip = 1,
- test_status_fail = 2,
-
- test_status_count = 3
-} test_status_t;
-
-typedef void (test_t)(void);
-
-#define TEST_BEGIN(f) \
-static void \
-f(void) \
-{ \
- p_test_init(#f);
-
-#define TEST_END \
- goto label_test_end; \
-label_test_end: \
- p_test_fini(); \
-}
-
-#define test(...) \
- p_test(__VA_ARGS__, NULL)
-
-#define test_no_malloc_init(...) \
- p_test_no_malloc_init(__VA_ARGS__, NULL)
-
-#define test_skip_if(e) do { \
- if (e) { \
- test_skip("%s:%s:%d: Test skipped: (%s)", \
- __func__, __FILE__, __LINE__, #e); \
- goto label_test_end; \
- } \
-} while (0)
-
-void test_skip(const char *format, ...) JEMALLOC_FORMAT_PRINTF(1, 2);
-void test_fail(const char *format, ...) JEMALLOC_FORMAT_PRINTF(1, 2);
-
-/* For private use by macros. */
-test_status_t p_test(test_t *t, ...);
-test_status_t p_test_no_malloc_init(test_t *t, ...);
-void p_test_init(const char *name);
-void p_test_fini(void);
-void p_test_fail(const char *prefix, const char *message);
diff --git a/memory/jemalloc/src/test/include/test/thd.h b/memory/jemalloc/src/test/include/test/thd.h
deleted file mode 100644
index 47a51262e..000000000
--- a/memory/jemalloc/src/test/include/test/thd.h
+++ /dev/null
@@ -1,9 +0,0 @@
-/* Abstraction layer for threading in tests. */
-#ifdef _WIN32
-typedef HANDLE thd_t;
-#else
-typedef pthread_t thd_t;
-#endif
-
-void thd_create(thd_t *thd, void *(*proc)(void *), void *arg);
-void thd_join(thd_t thd, void **ret);
diff --git a/memory/jemalloc/src/test/include/test/timer.h b/memory/jemalloc/src/test/include/test/timer.h
deleted file mode 100644
index ace6191b8..000000000
--- a/memory/jemalloc/src/test/include/test/timer.h
+++ /dev/null
@@ -1,11 +0,0 @@
-/* Simple timer, for use in benchmark reporting. */
-
-typedef struct {
- nstime_t t0;
- nstime_t t1;
-} timedelta_t;
-
-void timer_start(timedelta_t *timer);
-void timer_stop(timedelta_t *timer);
-uint64_t timer_usec(const timedelta_t *timer);
-void timer_ratio(timedelta_t *a, timedelta_t *b, char *buf, size_t buflen);
diff --git a/memory/jemalloc/src/test/integration/MALLOCX_ARENA.c b/memory/jemalloc/src/test/integration/MALLOCX_ARENA.c
deleted file mode 100644
index 30c203ae6..000000000
--- a/memory/jemalloc/src/test/integration/MALLOCX_ARENA.c
+++ /dev/null
@@ -1,69 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define NTHREADS 10
-
-static bool have_dss =
-#ifdef JEMALLOC_DSS
- true
-#else
- false
-#endif
- ;
-
-void *
-thd_start(void *arg)
-{
- unsigned thread_ind = (unsigned)(uintptr_t)arg;
- unsigned arena_ind;
- void *p;
- size_t sz;
-
- sz = sizeof(arena_ind);
- assert_d_eq(mallctl("arenas.extend", &arena_ind, &sz, NULL, 0), 0,
- "Error in arenas.extend");
-
- if (thread_ind % 4 != 3) {
- size_t mib[3];
- size_t miblen = sizeof(mib) / sizeof(size_t);
- const char *dss_precs[] = {"disabled", "primary", "secondary"};
- unsigned prec_ind = thread_ind %
- (sizeof(dss_precs)/sizeof(char*));
- const char *dss = dss_precs[prec_ind];
- int expected_err = (have_dss || prec_ind == 0) ? 0 : EFAULT;
- assert_d_eq(mallctlnametomib("arena.0.dss", mib, &miblen), 0,
- "Error in mallctlnametomib()");
- mib[1] = arena_ind;
- assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, (void *)&dss,
- sizeof(const char *)), expected_err,
- "Error in mallctlbymib()");
- }
-
- p = mallocx(1, MALLOCX_ARENA(arena_ind));
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- dallocx(p, 0);
-
- return (NULL);
-}
-
-TEST_BEGIN(test_MALLOCX_ARENA)
-{
- thd_t thds[NTHREADS];
- unsigned i;
-
- for (i = 0; i < NTHREADS; i++) {
- thd_create(&thds[i], thd_start,
- (void *)(uintptr_t)i);
- }
-
- for (i = 0; i < NTHREADS; i++)
- thd_join(thds[i], NULL);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_MALLOCX_ARENA));
-}
diff --git a/memory/jemalloc/src/test/integration/aligned_alloc.c b/memory/jemalloc/src/test/integration/aligned_alloc.c
deleted file mode 100644
index 58438421d..000000000
--- a/memory/jemalloc/src/test/integration/aligned_alloc.c
+++ /dev/null
@@ -1,139 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define CHUNK 0x400000
-#define MAXALIGN (((size_t)1) << 23)
-
-/*
- * On systems which can't merge extents, tests that call this function generate
- * a lot of dirty memory very quickly. Purging between cycles mitigates
- * potential OOM on e.g. 32-bit Windows.
- */
-static void
-purge(void)
-{
-
- assert_d_eq(mallctl("arena.0.purge", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl error");
-}
-
-TEST_BEGIN(test_alignment_errors)
-{
- size_t alignment;
- void *p;
-
- alignment = 0;
- set_errno(0);
- p = aligned_alloc(alignment, 1);
- assert_false(p != NULL || get_errno() != EINVAL,
- "Expected error for invalid alignment %zu", alignment);
-
- for (alignment = sizeof(size_t); alignment < MAXALIGN;
- alignment <<= 1) {
- set_errno(0);
- p = aligned_alloc(alignment + 1, 1);
- assert_false(p != NULL || get_errno() != EINVAL,
- "Expected error for invalid alignment %zu",
- alignment + 1);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_oom_errors)
-{
- size_t alignment, size;
- void *p;
-
-#if LG_SIZEOF_PTR == 3
- alignment = UINT64_C(0x8000000000000000);
- size = UINT64_C(0x8000000000000000);
-#else
- alignment = 0x80000000LU;
- size = 0x80000000LU;
-#endif
- set_errno(0);
- p = aligned_alloc(alignment, size);
- assert_false(p != NULL || get_errno() != ENOMEM,
- "Expected error for aligned_alloc(%zu, %zu)",
- alignment, size);
-
-#if LG_SIZEOF_PTR == 3
- alignment = UINT64_C(0x4000000000000000);
- size = UINT64_C(0xc000000000000001);
-#else
- alignment = 0x40000000LU;
- size = 0xc0000001LU;
-#endif
- set_errno(0);
- p = aligned_alloc(alignment, size);
- assert_false(p != NULL || get_errno() != ENOMEM,
- "Expected error for aligned_alloc(%zu, %zu)",
- alignment, size);
-
- alignment = 0x10LU;
-#if LG_SIZEOF_PTR == 3
- size = UINT64_C(0xfffffffffffffff0);
-#else
- size = 0xfffffff0LU;
-#endif
- set_errno(0);
- p = aligned_alloc(alignment, size);
- assert_false(p != NULL || get_errno() != ENOMEM,
- "Expected error for aligned_alloc(&p, %zu, %zu)",
- alignment, size);
-}
-TEST_END
-
-TEST_BEGIN(test_alignment_and_size)
-{
-#define NITER 4
- size_t alignment, size, total;
- unsigned i;
- void *ps[NITER];
-
- for (i = 0; i < NITER; i++)
- ps[i] = NULL;
-
- for (alignment = 8;
- alignment <= MAXALIGN;
- alignment <<= 1) {
- total = 0;
- for (size = 1;
- size < 3 * alignment && size < (1U << 31);
- size += (alignment >> (LG_SIZEOF_PTR-1)) - 1) {
- for (i = 0; i < NITER; i++) {
- ps[i] = aligned_alloc(alignment, size);
- if (ps[i] == NULL) {
- char buf[BUFERROR_BUF];
-
- buferror(get_errno(), buf, sizeof(buf));
- test_fail(
- "Error for alignment=%zu, "
- "size=%zu (%#zx): %s",
- alignment, size, size, buf);
- }
- total += malloc_usable_size(ps[i]);
- if (total >= (MAXALIGN << 1))
- break;
- }
- for (i = 0; i < NITER; i++) {
- if (ps[i] != NULL) {
- free(ps[i]);
- ps[i] = NULL;
- }
- }
- }
- purge();
- }
-#undef NITER
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_alignment_errors,
- test_oom_errors,
- test_alignment_and_size));
-}
diff --git a/memory/jemalloc/src/test/integration/allocated.c b/memory/jemalloc/src/test/integration/allocated.c
deleted file mode 100644
index 3630e80ce..000000000
--- a/memory/jemalloc/src/test/integration/allocated.c
+++ /dev/null
@@ -1,125 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static const bool config_stats =
-#ifdef JEMALLOC_STATS
- true
-#else
- false
-#endif
- ;
-
-void *
-thd_start(void *arg)
-{
- int err;
- void *p;
- uint64_t a0, a1, d0, d1;
- uint64_t *ap0, *ap1, *dp0, *dp1;
- size_t sz, usize;
-
- sz = sizeof(a0);
- if ((err = mallctl("thread.allocated", &a0, &sz, NULL, 0))) {
- if (err == ENOENT)
- goto label_ENOENT;
- test_fail("%s(): Error in mallctl(): %s", __func__,
- strerror(err));
- }
- sz = sizeof(ap0);
- if ((err = mallctl("thread.allocatedp", &ap0, &sz, NULL, 0))) {
- if (err == ENOENT)
- goto label_ENOENT;
- test_fail("%s(): Error in mallctl(): %s", __func__,
- strerror(err));
- }
- assert_u64_eq(*ap0, a0,
- "\"thread.allocatedp\" should provide a pointer to internal "
- "storage");
-
- sz = sizeof(d0);
- if ((err = mallctl("thread.deallocated", &d0, &sz, NULL, 0))) {
- if (err == ENOENT)
- goto label_ENOENT;
- test_fail("%s(): Error in mallctl(): %s", __func__,
- strerror(err));
- }
- sz = sizeof(dp0);
- if ((err = mallctl("thread.deallocatedp", &dp0, &sz, NULL, 0))) {
- if (err == ENOENT)
- goto label_ENOENT;
- test_fail("%s(): Error in mallctl(): %s", __func__,
- strerror(err));
- }
- assert_u64_eq(*dp0, d0,
- "\"thread.deallocatedp\" should provide a pointer to internal "
- "storage");
-
- p = malloc(1);
- assert_ptr_not_null(p, "Unexpected malloc() error");
-
- sz = sizeof(a1);
- mallctl("thread.allocated", &a1, &sz, NULL, 0);
- sz = sizeof(ap1);
- mallctl("thread.allocatedp", &ap1, &sz, NULL, 0);
- assert_u64_eq(*ap1, a1,
- "Dereferenced \"thread.allocatedp\" value should equal "
- "\"thread.allocated\" value");
- assert_ptr_eq(ap0, ap1,
- "Pointer returned by \"thread.allocatedp\" should not change");
-
- usize = malloc_usable_size(p);
- assert_u64_le(a0 + usize, a1,
- "Allocated memory counter should increase by at least the amount "
- "explicitly allocated");
-
- free(p);
-
- sz = sizeof(d1);
- mallctl("thread.deallocated", &d1, &sz, NULL, 0);
- sz = sizeof(dp1);
- mallctl("thread.deallocatedp", &dp1, &sz, NULL, 0);
- assert_u64_eq(*dp1, d1,
- "Dereferenced \"thread.deallocatedp\" value should equal "
- "\"thread.deallocated\" value");
- assert_ptr_eq(dp0, dp1,
- "Pointer returned by \"thread.deallocatedp\" should not change");
-
- assert_u64_le(d0 + usize, d1,
- "Deallocated memory counter should increase by at least the amount "
- "explicitly deallocated");
-
- return (NULL);
-label_ENOENT:
- assert_false(config_stats,
- "ENOENT should only be returned if stats are disabled");
- test_skip("\"thread.allocated\" mallctl not available");
- return (NULL);
-}
-
-TEST_BEGIN(test_main_thread)
-{
-
- thd_start(NULL);
-}
-TEST_END
-
-TEST_BEGIN(test_subthread)
-{
- thd_t thd;
-
- thd_create(&thd, thd_start, NULL);
- thd_join(thd, NULL);
-}
-TEST_END
-
-int
-main(void)
-{
-
- /* Run tests multiple times to check for bad interactions. */
- return (test(
- test_main_thread,
- test_subthread,
- test_main_thread,
- test_subthread,
- test_main_thread));
-}
diff --git a/memory/jemalloc/src/test/integration/chunk.c b/memory/jemalloc/src/test/integration/chunk.c
deleted file mode 100644
index ff9bf967a..000000000
--- a/memory/jemalloc/src/test/integration/chunk.c
+++ /dev/null
@@ -1,293 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_FILL
-const char *malloc_conf = "junk:false";
-#endif
-
-static chunk_hooks_t orig_hooks;
-static chunk_hooks_t old_hooks;
-
-static bool do_dalloc = true;
-static bool do_decommit;
-
-static bool did_alloc;
-static bool did_dalloc;
-static bool did_commit;
-static bool did_decommit;
-static bool did_purge;
-static bool did_split;
-static bool did_merge;
-
-#if 0
-# define TRACE_HOOK(fmt, ...) malloc_printf(fmt, __VA_ARGS__)
-#else
-# define TRACE_HOOK(fmt, ...)
-#endif
-
-void *
-chunk_alloc(void *new_addr, size_t size, size_t alignment, bool *zero,
- bool *commit, unsigned arena_ind)
-{
-
- TRACE_HOOK("%s(new_addr=%p, size=%zu, alignment=%zu, *zero=%s, "
- "*commit=%s, arena_ind=%u)\n", __func__, new_addr, size, alignment,
- *zero ? "true" : "false", *commit ? "true" : "false", arena_ind);
- did_alloc = true;
- return (old_hooks.alloc(new_addr, size, alignment, zero, commit,
- arena_ind));
-}
-
-bool
-chunk_dalloc(void *chunk, size_t size, bool committed, unsigned arena_ind)
-{
-
- TRACE_HOOK("%s(chunk=%p, size=%zu, committed=%s, arena_ind=%u)\n",
- __func__, chunk, size, committed ? "true" : "false", arena_ind);
- did_dalloc = true;
- if (!do_dalloc)
- return (true);
- return (old_hooks.dalloc(chunk, size, committed, arena_ind));
-}
-
-bool
-chunk_commit(void *chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
-{
- bool err;
-
- TRACE_HOOK("%s(chunk=%p, size=%zu, offset=%zu, length=%zu, "
- "arena_ind=%u)\n", __func__, chunk, size, offset, length,
- arena_ind);
- err = old_hooks.commit(chunk, size, offset, length, arena_ind);
- did_commit = !err;
- return (err);
-}
-
-bool
-chunk_decommit(void *chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
-{
- bool err;
-
- TRACE_HOOK("%s(chunk=%p, size=%zu, offset=%zu, length=%zu, "
- "arena_ind=%u)\n", __func__, chunk, size, offset, length,
- arena_ind);
- if (!do_decommit)
- return (true);
- err = old_hooks.decommit(chunk, size, offset, length, arena_ind);
- did_decommit = !err;
- return (err);
-}
-
-bool
-chunk_purge(void *chunk, size_t size, size_t offset, size_t length,
- unsigned arena_ind)
-{
-
- TRACE_HOOK("%s(chunk=%p, size=%zu, offset=%zu, length=%zu "
- "arena_ind=%u)\n", __func__, chunk, size, offset, length,
- arena_ind);
- did_purge = true;
- return (old_hooks.purge(chunk, size, offset, length, arena_ind));
-}
-
-bool
-chunk_split(void *chunk, size_t size, size_t size_a, size_t size_b,
- bool committed, unsigned arena_ind)
-{
-
- TRACE_HOOK("%s(chunk=%p, size=%zu, size_a=%zu, size_b=%zu, "
- "committed=%s, arena_ind=%u)\n", __func__, chunk, size, size_a,
- size_b, committed ? "true" : "false", arena_ind);
- did_split = true;
- return (old_hooks.split(chunk, size, size_a, size_b, committed,
- arena_ind));
-}
-
-bool
-chunk_merge(void *chunk_a, size_t size_a, void *chunk_b, size_t size_b,
- bool committed, unsigned arena_ind)
-{
-
- TRACE_HOOK("%s(chunk_a=%p, size_a=%zu, chunk_b=%p size_b=%zu, "
- "committed=%s, arena_ind=%u)\n", __func__, chunk_a, size_a, chunk_b,
- size_b, committed ? "true" : "false", arena_ind);
- did_merge = true;
- return (old_hooks.merge(chunk_a, size_a, chunk_b, size_b,
- committed, arena_ind));
-}
-
-TEST_BEGIN(test_chunk)
-{
- void *p;
- size_t old_size, new_size, large0, large1, huge0, huge1, huge2, sz;
- unsigned arena_ind;
- int flags;
- size_t hooks_mib[3], purge_mib[3];
- size_t hooks_miblen, purge_miblen;
- chunk_hooks_t new_hooks = {
- chunk_alloc,
- chunk_dalloc,
- chunk_commit,
- chunk_decommit,
- chunk_purge,
- chunk_split,
- chunk_merge
- };
- bool xallocx_success_a, xallocx_success_b, xallocx_success_c;
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("arenas.extend", &arena_ind, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- flags = MALLOCX_ARENA(arena_ind) | MALLOCX_TCACHE_NONE;
-
- /* Install custom chunk hooks. */
- hooks_miblen = sizeof(hooks_mib)/sizeof(size_t);
- assert_d_eq(mallctlnametomib("arena.0.chunk_hooks", hooks_mib,
- &hooks_miblen), 0, "Unexpected mallctlnametomib() failure");
- hooks_mib[1] = (size_t)arena_ind;
- old_size = sizeof(chunk_hooks_t);
- new_size = sizeof(chunk_hooks_t);
- assert_d_eq(mallctlbymib(hooks_mib, hooks_miblen, &old_hooks, &old_size,
- &new_hooks, new_size), 0, "Unexpected chunk_hooks error");
- orig_hooks = old_hooks;
- assert_ptr_ne(old_hooks.alloc, chunk_alloc, "Unexpected alloc error");
- assert_ptr_ne(old_hooks.dalloc, chunk_dalloc,
- "Unexpected dalloc error");
- assert_ptr_ne(old_hooks.commit, chunk_commit,
- "Unexpected commit error");
- assert_ptr_ne(old_hooks.decommit, chunk_decommit,
- "Unexpected decommit error");
- assert_ptr_ne(old_hooks.purge, chunk_purge, "Unexpected purge error");
- assert_ptr_ne(old_hooks.split, chunk_split, "Unexpected split error");
- assert_ptr_ne(old_hooks.merge, chunk_merge, "Unexpected merge error");
-
- /* Get large size classes. */
- sz = sizeof(size_t);
- assert_d_eq(mallctl("arenas.lrun.0.size", &large0, &sz, NULL, 0), 0,
- "Unexpected arenas.lrun.0.size failure");
- assert_d_eq(mallctl("arenas.lrun.1.size", &large1, &sz, NULL, 0), 0,
- "Unexpected arenas.lrun.1.size failure");
-
- /* Get huge size classes. */
- assert_d_eq(mallctl("arenas.hchunk.0.size", &huge0, &sz, NULL, 0), 0,
- "Unexpected arenas.hchunk.0.size failure");
- assert_d_eq(mallctl("arenas.hchunk.1.size", &huge1, &sz, NULL, 0), 0,
- "Unexpected arenas.hchunk.1.size failure");
- assert_d_eq(mallctl("arenas.hchunk.2.size", &huge2, &sz, NULL, 0), 0,
- "Unexpected arenas.hchunk.2.size failure");
-
- /* Test dalloc/decommit/purge cascade. */
- purge_miblen = sizeof(purge_mib)/sizeof(size_t);
- assert_d_eq(mallctlnametomib("arena.0.purge", purge_mib, &purge_miblen),
- 0, "Unexpected mallctlnametomib() failure");
- purge_mib[1] = (size_t)arena_ind;
- do_dalloc = false;
- do_decommit = false;
- p = mallocx(huge0 * 2, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- did_dalloc = false;
- did_decommit = false;
- did_purge = false;
- did_split = false;
- xallocx_success_a = (xallocx(p, huge0, 0, flags) == huge0);
- assert_d_eq(mallctlbymib(purge_mib, purge_miblen, NULL, NULL, NULL, 0),
- 0, "Unexpected arena.%u.purge error", arena_ind);
- if (xallocx_success_a) {
- assert_true(did_dalloc, "Expected dalloc");
- assert_false(did_decommit, "Unexpected decommit");
- assert_true(did_purge, "Expected purge");
- }
- assert_true(did_split, "Expected split");
- dallocx(p, flags);
- do_dalloc = true;
-
- /* Test decommit/commit and observe split/merge. */
- do_dalloc = false;
- do_decommit = true;
- p = mallocx(huge0 * 2, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- did_decommit = false;
- did_commit = false;
- did_split = false;
- did_merge = false;
- xallocx_success_b = (xallocx(p, huge0, 0, flags) == huge0);
- assert_d_eq(mallctlbymib(purge_mib, purge_miblen, NULL, NULL, NULL, 0),
- 0, "Unexpected arena.%u.purge error", arena_ind);
- if (xallocx_success_b)
- assert_true(did_split, "Expected split");
- xallocx_success_c = (xallocx(p, huge0 * 2, 0, flags) == huge0 * 2);
- assert_b_eq(did_decommit, did_commit, "Expected decommit/commit match");
- if (xallocx_success_b && xallocx_success_c)
- assert_true(did_merge, "Expected merge");
- dallocx(p, flags);
- do_dalloc = true;
- do_decommit = false;
-
- /* Test purge for partial-chunk huge allocations. */
- if (huge0 * 2 > huge2) {
- /*
- * There are at least four size classes per doubling, so a
- * successful xallocx() from size=huge2 to size=huge1 is
- * guaranteed to leave trailing purgeable memory.
- */
- p = mallocx(huge2, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- did_purge = false;
- assert_zu_eq(xallocx(p, huge1, 0, flags), huge1,
- "Unexpected xallocx() failure");
- assert_true(did_purge, "Expected purge");
- dallocx(p, flags);
- }
-
- /* Test decommit for large allocations. */
- do_decommit = true;
- p = mallocx(large1, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- assert_d_eq(mallctlbymib(purge_mib, purge_miblen, NULL, NULL, NULL, 0),
- 0, "Unexpected arena.%u.purge error", arena_ind);
- did_decommit = false;
- assert_zu_eq(xallocx(p, large0, 0, flags), large0,
- "Unexpected xallocx() failure");
- assert_d_eq(mallctlbymib(purge_mib, purge_miblen, NULL, NULL, NULL, 0),
- 0, "Unexpected arena.%u.purge error", arena_ind);
- did_commit = false;
- assert_zu_eq(xallocx(p, large1, 0, flags), large1,
- "Unexpected xallocx() failure");
- assert_b_eq(did_decommit, did_commit, "Expected decommit/commit match");
- dallocx(p, flags);
- do_decommit = false;
-
- /* Make sure non-huge allocation succeeds. */
- p = mallocx(42, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- dallocx(p, flags);
-
- /* Restore chunk hooks. */
- assert_d_eq(mallctlbymib(hooks_mib, hooks_miblen, NULL, NULL,
- &old_hooks, new_size), 0, "Unexpected chunk_hooks error");
- assert_d_eq(mallctlbymib(hooks_mib, hooks_miblen, &old_hooks, &old_size,
- NULL, 0), 0, "Unexpected chunk_hooks error");
- assert_ptr_eq(old_hooks.alloc, orig_hooks.alloc,
- "Unexpected alloc error");
- assert_ptr_eq(old_hooks.dalloc, orig_hooks.dalloc,
- "Unexpected dalloc error");
- assert_ptr_eq(old_hooks.commit, orig_hooks.commit,
- "Unexpected commit error");
- assert_ptr_eq(old_hooks.decommit, orig_hooks.decommit,
- "Unexpected decommit error");
- assert_ptr_eq(old_hooks.purge, orig_hooks.purge,
- "Unexpected purge error");
- assert_ptr_eq(old_hooks.split, orig_hooks.split,
- "Unexpected split error");
- assert_ptr_eq(old_hooks.merge, orig_hooks.merge,
- "Unexpected merge error");
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(test_chunk));
-}
diff --git a/memory/jemalloc/src/test/integration/mallocx.c b/memory/jemalloc/src/test/integration/mallocx.c
deleted file mode 100644
index 43b76ebac..000000000
--- a/memory/jemalloc/src/test/integration/mallocx.c
+++ /dev/null
@@ -1,234 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_FILL
-const char *malloc_conf = "junk:false";
-#endif
-
-static unsigned
-get_nsizes_impl(const char *cmd)
-{
- unsigned ret;
- size_t z;
-
- z = sizeof(unsigned);
- assert_d_eq(mallctl(cmd, &ret, &z, NULL, 0), 0,
- "Unexpected mallctl(\"%s\", ...) failure", cmd);
-
- return (ret);
-}
-
-static unsigned
-get_nhuge(void)
-{
-
- return (get_nsizes_impl("arenas.nhchunks"));
-}
-
-static size_t
-get_size_impl(const char *cmd, size_t ind)
-{
- size_t ret;
- size_t z;
- size_t mib[4];
- size_t miblen = 4;
-
- z = sizeof(size_t);
- assert_d_eq(mallctlnametomib(cmd, mib, &miblen),
- 0, "Unexpected mallctlnametomib(\"%s\", ...) failure", cmd);
- mib[2] = ind;
- z = sizeof(size_t);
- assert_d_eq(mallctlbymib(mib, miblen, &ret, &z, NULL, 0),
- 0, "Unexpected mallctlbymib([\"%s\", %zu], ...) failure", cmd, ind);
-
- return (ret);
-}
-
-static size_t
-get_huge_size(size_t ind)
-{
-
- return (get_size_impl("arenas.hchunk.0.size", ind));
-}
-
-/*
- * On systems which can't merge extents, tests that call this function generate
- * a lot of dirty memory very quickly. Purging between cycles mitigates
- * potential OOM on e.g. 32-bit Windows.
- */
-static void
-purge(void)
-{
-
- assert_d_eq(mallctl("arena.0.purge", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl error");
-}
-
-TEST_BEGIN(test_overflow)
-{
- size_t hugemax;
-
- hugemax = get_huge_size(get_nhuge()-1);
-
- assert_ptr_null(mallocx(hugemax+1, 0),
- "Expected OOM for mallocx(size=%#zx, 0)", hugemax+1);
-
- assert_ptr_null(mallocx(ZU(PTRDIFF_MAX)+1, 0),
- "Expected OOM for mallocx(size=%#zx, 0)", ZU(PTRDIFF_MAX)+1);
-
- assert_ptr_null(mallocx(SIZE_T_MAX, 0),
- "Expected OOM for mallocx(size=%#zx, 0)", SIZE_T_MAX);
-
- assert_ptr_null(mallocx(1, MALLOCX_ALIGN(ZU(PTRDIFF_MAX)+1)),
- "Expected OOM for mallocx(size=1, MALLOCX_ALIGN(%#zx))",
- ZU(PTRDIFF_MAX)+1);
-}
-TEST_END
-
-TEST_BEGIN(test_oom)
-{
- size_t hugemax;
- bool oom;
- void *ptrs[3];
- unsigned i;
-
- /*
- * It should be impossible to allocate three objects that each consume
- * nearly half the virtual address space.
- */
- hugemax = get_huge_size(get_nhuge()-1);
- oom = false;
- for (i = 0; i < sizeof(ptrs) / sizeof(void *); i++) {
- ptrs[i] = mallocx(hugemax, 0);
- if (ptrs[i] == NULL)
- oom = true;
- }
- assert_true(oom,
- "Expected OOM during series of calls to mallocx(size=%zu, 0)",
- hugemax);
- for (i = 0; i < sizeof(ptrs) / sizeof(void *); i++) {
- if (ptrs[i] != NULL)
- dallocx(ptrs[i], 0);
- }
- purge();
-
-#if LG_SIZEOF_PTR == 3
- assert_ptr_null(mallocx(0x8000000000000000ULL,
- MALLOCX_ALIGN(0x8000000000000000ULL)),
- "Expected OOM for mallocx()");
- assert_ptr_null(mallocx(0x8000000000000000ULL,
- MALLOCX_ALIGN(0x80000000)),
- "Expected OOM for mallocx()");
-#else
- assert_ptr_null(mallocx(0x80000000UL, MALLOCX_ALIGN(0x80000000UL)),
- "Expected OOM for mallocx()");
-#endif
-}
-TEST_END
-
-TEST_BEGIN(test_basic)
-{
-#define MAXSZ (((size_t)1) << 23)
- size_t sz;
-
- for (sz = 1; sz < MAXSZ; sz = nallocx(sz, 0) + 1) {
- size_t nsz, rsz;
- void *p;
- nsz = nallocx(sz, 0);
- assert_zu_ne(nsz, 0, "Unexpected nallocx() error");
- p = mallocx(sz, 0);
- assert_ptr_not_null(p,
- "Unexpected mallocx(size=%zx, flags=0) error", sz);
- rsz = sallocx(p, 0);
- assert_zu_ge(rsz, sz, "Real size smaller than expected");
- assert_zu_eq(nsz, rsz, "nallocx()/sallocx() size mismatch");
- dallocx(p, 0);
-
- p = mallocx(sz, 0);
- assert_ptr_not_null(p,
- "Unexpected mallocx(size=%zx, flags=0) error", sz);
- dallocx(p, 0);
-
- nsz = nallocx(sz, MALLOCX_ZERO);
- assert_zu_ne(nsz, 0, "Unexpected nallocx() error");
- p = mallocx(sz, MALLOCX_ZERO);
- assert_ptr_not_null(p,
- "Unexpected mallocx(size=%zx, flags=MALLOCX_ZERO) error",
- nsz);
- rsz = sallocx(p, 0);
- assert_zu_eq(nsz, rsz, "nallocx()/sallocx() rsize mismatch");
- dallocx(p, 0);
- purge();
- }
-#undef MAXSZ
-}
-TEST_END
-
-TEST_BEGIN(test_alignment_and_size)
-{
-#define MAXALIGN (((size_t)1) << 23)
-#define NITER 4
- size_t nsz, rsz, sz, alignment, total;
- unsigned i;
- void *ps[NITER];
-
- for (i = 0; i < NITER; i++)
- ps[i] = NULL;
-
- for (alignment = 8;
- alignment <= MAXALIGN;
- alignment <<= 1) {
- total = 0;
- for (sz = 1;
- sz < 3 * alignment && sz < (1U << 31);
- sz += (alignment >> (LG_SIZEOF_PTR-1)) - 1) {
- for (i = 0; i < NITER; i++) {
- nsz = nallocx(sz, MALLOCX_ALIGN(alignment) |
- MALLOCX_ZERO);
- assert_zu_ne(nsz, 0,
- "nallocx() error for alignment=%zu, "
- "size=%zu (%#zx)", alignment, sz, sz);
- ps[i] = mallocx(sz, MALLOCX_ALIGN(alignment) |
- MALLOCX_ZERO);
- assert_ptr_not_null(ps[i],
- "mallocx() error for alignment=%zu, "
- "size=%zu (%#zx)", alignment, sz, sz);
- rsz = sallocx(ps[i], 0);
- assert_zu_ge(rsz, sz,
- "Real size smaller than expected for "
- "alignment=%zu, size=%zu", alignment, sz);
- assert_zu_eq(nsz, rsz,
- "nallocx()/sallocx() size mismatch for "
- "alignment=%zu, size=%zu", alignment, sz);
- assert_ptr_null(
- (void *)((uintptr_t)ps[i] & (alignment-1)),
- "%p inadequately aligned for"
- " alignment=%zu, size=%zu", ps[i],
- alignment, sz);
- total += rsz;
- if (total >= (MAXALIGN << 1))
- break;
- }
- for (i = 0; i < NITER; i++) {
- if (ps[i] != NULL) {
- dallocx(ps[i], 0);
- ps[i] = NULL;
- }
- }
- }
- purge();
- }
-#undef MAXALIGN
-#undef NITER
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_overflow,
- test_oom,
- test_basic,
- test_alignment_and_size));
-}
diff --git a/memory/jemalloc/src/test/integration/overflow.c b/memory/jemalloc/src/test/integration/overflow.c
deleted file mode 100644
index 303d9b2d3..000000000
--- a/memory/jemalloc/src/test/integration/overflow.c
+++ /dev/null
@@ -1,49 +0,0 @@
-#include "test/jemalloc_test.h"
-
-TEST_BEGIN(test_overflow)
-{
- unsigned nhchunks;
- size_t mib[4];
- size_t sz, miblen, max_size_class;
- void *p;
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("arenas.nhchunks", &nhchunks, &sz, NULL, 0), 0,
- "Unexpected mallctl() error");
-
- miblen = sizeof(mib) / sizeof(size_t);
- assert_d_eq(mallctlnametomib("arenas.hchunk.0.size", mib, &miblen), 0,
- "Unexpected mallctlnametomib() error");
- mib[2] = nhchunks - 1;
-
- sz = sizeof(size_t);
- assert_d_eq(mallctlbymib(mib, miblen, &max_size_class, &sz, NULL, 0), 0,
- "Unexpected mallctlbymib() error");
-
- assert_ptr_null(malloc(max_size_class + 1),
- "Expected OOM due to over-sized allocation request");
- assert_ptr_null(malloc(SIZE_T_MAX),
- "Expected OOM due to over-sized allocation request");
-
- assert_ptr_null(calloc(1, max_size_class + 1),
- "Expected OOM due to over-sized allocation request");
- assert_ptr_null(calloc(1, SIZE_T_MAX),
- "Expected OOM due to over-sized allocation request");
-
- p = malloc(1);
- assert_ptr_not_null(p, "Unexpected malloc() OOM");
- assert_ptr_null(realloc(p, max_size_class + 1),
- "Expected OOM due to over-sized allocation request");
- assert_ptr_null(realloc(p, SIZE_T_MAX),
- "Expected OOM due to over-sized allocation request");
- free(p);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_overflow));
-}
diff --git a/memory/jemalloc/src/test/integration/posix_memalign.c b/memory/jemalloc/src/test/integration/posix_memalign.c
deleted file mode 100644
index e22e10200..000000000
--- a/memory/jemalloc/src/test/integration/posix_memalign.c
+++ /dev/null
@@ -1,133 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define CHUNK 0x400000
-#define MAXALIGN (((size_t)1) << 23)
-
-/*
- * On systems which can't merge extents, tests that call this function generate
- * a lot of dirty memory very quickly. Purging between cycles mitigates
- * potential OOM on e.g. 32-bit Windows.
- */
-static void
-purge(void)
-{
-
- assert_d_eq(mallctl("arena.0.purge", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl error");
-}
-
-TEST_BEGIN(test_alignment_errors)
-{
- size_t alignment;
- void *p;
-
- for (alignment = 0; alignment < sizeof(void *); alignment++) {
- assert_d_eq(posix_memalign(&p, alignment, 1), EINVAL,
- "Expected error for invalid alignment %zu",
- alignment);
- }
-
- for (alignment = sizeof(size_t); alignment < MAXALIGN;
- alignment <<= 1) {
- assert_d_ne(posix_memalign(&p, alignment + 1, 1), 0,
- "Expected error for invalid alignment %zu",
- alignment + 1);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_oom_errors)
-{
- size_t alignment, size;
- void *p;
-
-#if LG_SIZEOF_PTR == 3
- alignment = UINT64_C(0x8000000000000000);
- size = UINT64_C(0x8000000000000000);
-#else
- alignment = 0x80000000LU;
- size = 0x80000000LU;
-#endif
- assert_d_ne(posix_memalign(&p, alignment, size), 0,
- "Expected error for posix_memalign(&p, %zu, %zu)",
- alignment, size);
-
-#if LG_SIZEOF_PTR == 3
- alignment = UINT64_C(0x4000000000000000);
- size = UINT64_C(0xc000000000000001);
-#else
- alignment = 0x40000000LU;
- size = 0xc0000001LU;
-#endif
- assert_d_ne(posix_memalign(&p, alignment, size), 0,
- "Expected error for posix_memalign(&p, %zu, %zu)",
- alignment, size);
-
- alignment = 0x10LU;
-#if LG_SIZEOF_PTR == 3
- size = UINT64_C(0xfffffffffffffff0);
-#else
- size = 0xfffffff0LU;
-#endif
- assert_d_ne(posix_memalign(&p, alignment, size), 0,
- "Expected error for posix_memalign(&p, %zu, %zu)",
- alignment, size);
-}
-TEST_END
-
-TEST_BEGIN(test_alignment_and_size)
-{
-#define NITER 4
- size_t alignment, size, total;
- unsigned i;
- int err;
- void *ps[NITER];
-
- for (i = 0; i < NITER; i++)
- ps[i] = NULL;
-
- for (alignment = 8;
- alignment <= MAXALIGN;
- alignment <<= 1) {
- total = 0;
- for (size = 1;
- size < 3 * alignment && size < (1U << 31);
- size += (alignment >> (LG_SIZEOF_PTR-1)) - 1) {
- for (i = 0; i < NITER; i++) {
- err = posix_memalign(&ps[i],
- alignment, size);
- if (err) {
- char buf[BUFERROR_BUF];
-
- buferror(get_errno(), buf, sizeof(buf));
- test_fail(
- "Error for alignment=%zu, "
- "size=%zu (%#zx): %s",
- alignment, size, size, buf);
- }
- total += malloc_usable_size(ps[i]);
- if (total >= (MAXALIGN << 1))
- break;
- }
- for (i = 0; i < NITER; i++) {
- if (ps[i] != NULL) {
- free(ps[i]);
- ps[i] = NULL;
- }
- }
- }
- purge();
- }
-#undef NITER
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_alignment_errors,
- test_oom_errors,
- test_alignment_and_size));
-}
diff --git a/memory/jemalloc/src/test/integration/rallocx.c b/memory/jemalloc/src/test/integration/rallocx.c
deleted file mode 100644
index 66ad8660a..000000000
--- a/memory/jemalloc/src/test/integration/rallocx.c
+++ /dev/null
@@ -1,259 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static unsigned
-get_nsizes_impl(const char *cmd)
-{
- unsigned ret;
- size_t z;
-
- z = sizeof(unsigned);
- assert_d_eq(mallctl(cmd, &ret, &z, NULL, 0), 0,
- "Unexpected mallctl(\"%s\", ...) failure", cmd);
-
- return (ret);
-}
-
-static unsigned
-get_nhuge(void)
-{
-
- return (get_nsizes_impl("arenas.nhchunks"));
-}
-
-static size_t
-get_size_impl(const char *cmd, size_t ind)
-{
- size_t ret;
- size_t z;
- size_t mib[4];
- size_t miblen = 4;
-
- z = sizeof(size_t);
- assert_d_eq(mallctlnametomib(cmd, mib, &miblen),
- 0, "Unexpected mallctlnametomib(\"%s\", ...) failure", cmd);
- mib[2] = ind;
- z = sizeof(size_t);
- assert_d_eq(mallctlbymib(mib, miblen, &ret, &z, NULL, 0),
- 0, "Unexpected mallctlbymib([\"%s\", %zu], ...) failure", cmd, ind);
-
- return (ret);
-}
-
-static size_t
-get_huge_size(size_t ind)
-{
-
- return (get_size_impl("arenas.hchunk.0.size", ind));
-}
-
-TEST_BEGIN(test_grow_and_shrink)
-{
- void *p, *q;
- size_t tsz;
-#define NCYCLES 3
- unsigned i, j;
-#define NSZS 2500
- size_t szs[NSZS];
-#define MAXSZ ZU(12 * 1024 * 1024)
-
- p = mallocx(1, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- szs[0] = sallocx(p, 0);
-
- for (i = 0; i < NCYCLES; i++) {
- for (j = 1; j < NSZS && szs[j-1] < MAXSZ; j++) {
- q = rallocx(p, szs[j-1]+1, 0);
- assert_ptr_not_null(q,
- "Unexpected rallocx() error for size=%zu-->%zu",
- szs[j-1], szs[j-1]+1);
- szs[j] = sallocx(q, 0);
- assert_zu_ne(szs[j], szs[j-1]+1,
- "Expected size to be at least: %zu", szs[j-1]+1);
- p = q;
- }
-
- for (j--; j > 0; j--) {
- q = rallocx(p, szs[j-1], 0);
- assert_ptr_not_null(q,
- "Unexpected rallocx() error for size=%zu-->%zu",
- szs[j], szs[j-1]);
- tsz = sallocx(q, 0);
- assert_zu_eq(tsz, szs[j-1],
- "Expected size=%zu, got size=%zu", szs[j-1], tsz);
- p = q;
- }
- }
-
- dallocx(p, 0);
-#undef MAXSZ
-#undef NSZS
-#undef NCYCLES
-}
-TEST_END
-
-static bool
-validate_fill(const void *p, uint8_t c, size_t offset, size_t len)
-{
- bool ret = false;
- const uint8_t *buf = (const uint8_t *)p;
- size_t i;
-
- for (i = 0; i < len; i++) {
- uint8_t b = buf[offset+i];
- if (b != c) {
- test_fail("Allocation at %p (len=%zu) contains %#x "
- "rather than %#x at offset %zu", p, len, b, c,
- offset+i);
- ret = true;
- }
- }
-
- return (ret);
-}
-
-TEST_BEGIN(test_zero)
-{
- void *p, *q;
- size_t psz, qsz, i, j;
- size_t start_sizes[] = {1, 3*1024, 63*1024, 4095*1024};
-#define FILL_BYTE 0xaaU
-#define RANGE 2048
-
- for (i = 0; i < sizeof(start_sizes)/sizeof(size_t); i++) {
- size_t start_size = start_sizes[i];
- p = mallocx(start_size, MALLOCX_ZERO);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- psz = sallocx(p, 0);
-
- assert_false(validate_fill(p, 0, 0, psz),
- "Expected zeroed memory");
- memset(p, FILL_BYTE, psz);
- assert_false(validate_fill(p, FILL_BYTE, 0, psz),
- "Expected filled memory");
-
- for (j = 1; j < RANGE; j++) {
- q = rallocx(p, start_size+j, MALLOCX_ZERO);
- assert_ptr_not_null(q, "Unexpected rallocx() error");
- qsz = sallocx(q, 0);
- if (q != p || qsz != psz) {
- assert_false(validate_fill(q, FILL_BYTE, 0,
- psz), "Expected filled memory");
- assert_false(validate_fill(q, 0, psz, qsz-psz),
- "Expected zeroed memory");
- }
- if (psz != qsz) {
- memset((void *)((uintptr_t)q+psz), FILL_BYTE,
- qsz-psz);
- psz = qsz;
- }
- p = q;
- }
- assert_false(validate_fill(p, FILL_BYTE, 0, psz),
- "Expected filled memory");
- dallocx(p, 0);
- }
-#undef FILL_BYTE
-}
-TEST_END
-
-TEST_BEGIN(test_align)
-{
- void *p, *q;
- size_t align;
-#define MAX_ALIGN (ZU(1) << 25)
-
- align = ZU(1);
- p = mallocx(1, MALLOCX_ALIGN(align));
- assert_ptr_not_null(p, "Unexpected mallocx() error");
-
- for (align <<= 1; align <= MAX_ALIGN; align <<= 1) {
- q = rallocx(p, 1, MALLOCX_ALIGN(align));
- assert_ptr_not_null(q,
- "Unexpected rallocx() error for align=%zu", align);
- assert_ptr_null(
- (void *)((uintptr_t)q & (align-1)),
- "%p inadequately aligned for align=%zu",
- q, align);
- p = q;
- }
- dallocx(p, 0);
-#undef MAX_ALIGN
-}
-TEST_END
-
-TEST_BEGIN(test_lg_align_and_zero)
-{
- void *p, *q;
- unsigned lg_align;
- size_t sz;
-#define MAX_LG_ALIGN 25
-#define MAX_VALIDATE (ZU(1) << 22)
-
- lg_align = 0;
- p = mallocx(1, MALLOCX_LG_ALIGN(lg_align)|MALLOCX_ZERO);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
-
- for (lg_align++; lg_align <= MAX_LG_ALIGN; lg_align++) {
- q = rallocx(p, 1, MALLOCX_LG_ALIGN(lg_align)|MALLOCX_ZERO);
- assert_ptr_not_null(q,
- "Unexpected rallocx() error for lg_align=%u", lg_align);
- assert_ptr_null(
- (void *)((uintptr_t)q & ((ZU(1) << lg_align)-1)),
- "%p inadequately aligned for lg_align=%u", q, lg_align);
- sz = sallocx(q, 0);
- if ((sz << 1) <= MAX_VALIDATE) {
- assert_false(validate_fill(q, 0, 0, sz),
- "Expected zeroed memory");
- } else {
- assert_false(validate_fill(q, 0, 0, MAX_VALIDATE),
- "Expected zeroed memory");
- assert_false(validate_fill(
- (void *)((uintptr_t)q+sz-MAX_VALIDATE),
- 0, 0, MAX_VALIDATE), "Expected zeroed memory");
- }
- p = q;
- }
- dallocx(p, 0);
-#undef MAX_VALIDATE
-#undef MAX_LG_ALIGN
-}
-TEST_END
-
-TEST_BEGIN(test_overflow)
-{
- size_t hugemax;
- void *p;
-
- hugemax = get_huge_size(get_nhuge()-1);
-
- p = mallocx(1, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- assert_ptr_null(rallocx(p, hugemax+1, 0),
- "Expected OOM for rallocx(p, size=%#zx, 0)", hugemax+1);
-
- assert_ptr_null(rallocx(p, ZU(PTRDIFF_MAX)+1, 0),
- "Expected OOM for rallocx(p, size=%#zx, 0)", ZU(PTRDIFF_MAX)+1);
-
- assert_ptr_null(rallocx(p, SIZE_T_MAX, 0),
- "Expected OOM for rallocx(p, size=%#zx, 0)", SIZE_T_MAX);
-
- assert_ptr_null(rallocx(p, 1, MALLOCX_ALIGN(ZU(PTRDIFF_MAX)+1)),
- "Expected OOM for rallocx(p, size=1, MALLOCX_ALIGN(%#zx))",
- ZU(PTRDIFF_MAX)+1);
-
- dallocx(p, 0);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_grow_and_shrink,
- test_zero,
- test_align,
- test_lg_align_and_zero,
- test_overflow));
-}
diff --git a/memory/jemalloc/src/test/integration/sdallocx.c b/memory/jemalloc/src/test/integration/sdallocx.c
deleted file mode 100644
index b84817d76..000000000
--- a/memory/jemalloc/src/test/integration/sdallocx.c
+++ /dev/null
@@ -1,57 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define MAXALIGN (((size_t)1) << 25)
-#define NITER 4
-
-TEST_BEGIN(test_basic)
-{
- void *ptr = mallocx(64, 0);
- sdallocx(ptr, 64, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_alignment_and_size)
-{
- size_t nsz, sz, alignment, total;
- unsigned i;
- void *ps[NITER];
-
- for (i = 0; i < NITER; i++)
- ps[i] = NULL;
-
- for (alignment = 8;
- alignment <= MAXALIGN;
- alignment <<= 1) {
- total = 0;
- for (sz = 1;
- sz < 3 * alignment && sz < (1U << 31);
- sz += (alignment >> (LG_SIZEOF_PTR-1)) - 1) {
- for (i = 0; i < NITER; i++) {
- nsz = nallocx(sz, MALLOCX_ALIGN(alignment) |
- MALLOCX_ZERO);
- ps[i] = mallocx(sz, MALLOCX_ALIGN(alignment) |
- MALLOCX_ZERO);
- total += nsz;
- if (total >= (MAXALIGN << 1))
- break;
- }
- for (i = 0; i < NITER; i++) {
- if (ps[i] != NULL) {
- sdallocx(ps[i], sz,
- MALLOCX_ALIGN(alignment));
- ps[i] = NULL;
- }
- }
- }
- }
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_basic,
- test_alignment_and_size));
-}
diff --git a/memory/jemalloc/src/test/integration/thread_arena.c b/memory/jemalloc/src/test/integration/thread_arena.c
deleted file mode 100644
index 67be53513..000000000
--- a/memory/jemalloc/src/test/integration/thread_arena.c
+++ /dev/null
@@ -1,79 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define NTHREADS 10
-
-void *
-thd_start(void *arg)
-{
- unsigned main_arena_ind = *(unsigned *)arg;
- void *p;
- unsigned arena_ind;
- size_t size;
- int err;
-
- p = malloc(1);
- assert_ptr_not_null(p, "Error in malloc()");
- free(p);
-
- size = sizeof(arena_ind);
- if ((err = mallctl("thread.arena", &arena_ind, &size, &main_arena_ind,
- sizeof(main_arena_ind)))) {
- char buf[BUFERROR_BUF];
-
- buferror(err, buf, sizeof(buf));
- test_fail("Error in mallctl(): %s", buf);
- }
-
- size = sizeof(arena_ind);
- if ((err = mallctl("thread.arena", &arena_ind, &size, NULL, 0))) {
- char buf[BUFERROR_BUF];
-
- buferror(err, buf, sizeof(buf));
- test_fail("Error in mallctl(): %s", buf);
- }
- assert_u_eq(arena_ind, main_arena_ind,
- "Arena index should be same as for main thread");
-
- return (NULL);
-}
-
-TEST_BEGIN(test_thread_arena)
-{
- void *p;
- unsigned arena_ind;
- size_t size;
- int err;
- thd_t thds[NTHREADS];
- unsigned i;
-
- p = malloc(1);
- assert_ptr_not_null(p, "Error in malloc()");
-
- size = sizeof(arena_ind);
- if ((err = mallctl("thread.arena", &arena_ind, &size, NULL, 0))) {
- char buf[BUFERROR_BUF];
-
- buferror(err, buf, sizeof(buf));
- test_fail("Error in mallctl(): %s", buf);
- }
-
- for (i = 0; i < NTHREADS; i++) {
- thd_create(&thds[i], thd_start,
- (void *)&arena_ind);
- }
-
- for (i = 0; i < NTHREADS; i++) {
- intptr_t join_ret;
- thd_join(thds[i], (void *)&join_ret);
- assert_zd_eq(join_ret, 0, "Unexpected thread join error");
- }
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_thread_arena));
-}
diff --git a/memory/jemalloc/src/test/integration/thread_tcache_enabled.c b/memory/jemalloc/src/test/integration/thread_tcache_enabled.c
deleted file mode 100644
index f4e89c682..000000000
--- a/memory/jemalloc/src/test/integration/thread_tcache_enabled.c
+++ /dev/null
@@ -1,113 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static const bool config_tcache =
-#ifdef JEMALLOC_TCACHE
- true
-#else
- false
-#endif
- ;
-
-void *
-thd_start(void *arg)
-{
- int err;
- size_t sz;
- bool e0, e1;
-
- sz = sizeof(bool);
- if ((err = mallctl("thread.tcache.enabled", &e0, &sz, NULL, 0))) {
- if (err == ENOENT) {
- assert_false(config_tcache,
- "ENOENT should only be returned if tcache is "
- "disabled");
- }
- goto label_ENOENT;
- }
-
- if (e0) {
- e1 = false;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz),
- 0, "Unexpected mallctl() error");
- assert_true(e0, "tcache should be enabled");
- }
-
- e1 = true;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz), 0,
- "Unexpected mallctl() error");
- assert_false(e0, "tcache should be disabled");
-
- e1 = true;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz), 0,
- "Unexpected mallctl() error");
- assert_true(e0, "tcache should be enabled");
-
- e1 = false;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz), 0,
- "Unexpected mallctl() error");
- assert_true(e0, "tcache should be enabled");
-
- e1 = false;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz), 0,
- "Unexpected mallctl() error");
- assert_false(e0, "tcache should be disabled");
-
- free(malloc(1));
- e1 = true;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz), 0,
- "Unexpected mallctl() error");
- assert_false(e0, "tcache should be disabled");
-
- free(malloc(1));
- e1 = true;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz), 0,
- "Unexpected mallctl() error");
- assert_true(e0, "tcache should be enabled");
-
- free(malloc(1));
- e1 = false;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz), 0,
- "Unexpected mallctl() error");
- assert_true(e0, "tcache should be enabled");
-
- free(malloc(1));
- e1 = false;
- assert_d_eq(mallctl("thread.tcache.enabled", &e0, &sz, &e1, sz), 0,
- "Unexpected mallctl() error");
- assert_false(e0, "tcache should be disabled");
-
- free(malloc(1));
- return (NULL);
-label_ENOENT:
- test_skip("\"thread.tcache.enabled\" mallctl not available");
- return (NULL);
-}
-
-TEST_BEGIN(test_main_thread)
-{
-
- thd_start(NULL);
-}
-TEST_END
-
-TEST_BEGIN(test_subthread)
-{
- thd_t thd;
-
- thd_create(&thd, thd_start, NULL);
- thd_join(thd, NULL);
-}
-TEST_END
-
-int
-main(void)
-{
-
- /* Run tests multiple times to check for bad interactions. */
- return (test(
- test_main_thread,
- test_subthread,
- test_main_thread,
- test_subthread,
- test_main_thread));
-}
diff --git a/memory/jemalloc/src/test/integration/xallocx.c b/memory/jemalloc/src/test/integration/xallocx.c
deleted file mode 100644
index ad292bb56..000000000
--- a/memory/jemalloc/src/test/integration/xallocx.c
+++ /dev/null
@@ -1,497 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_FILL
-const char *malloc_conf = "junk:false";
-#endif
-
-/*
- * Use a separate arena for xallocx() extension/contraction tests so that
- * internal allocation e.g. by heap profiling can't interpose allocations where
- * xallocx() would ordinarily be able to extend.
- */
-static unsigned
-arena_ind(void)
-{
- static unsigned ind = 0;
-
- if (ind == 0) {
- size_t sz = sizeof(ind);
- assert_d_eq(mallctl("arenas.extend", &ind, &sz, NULL, 0), 0,
- "Unexpected mallctl failure creating arena");
- }
-
- return (ind);
-}
-
-TEST_BEGIN(test_same_size)
-{
- void *p;
- size_t sz, tsz;
-
- p = mallocx(42, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- sz = sallocx(p, 0);
-
- tsz = xallocx(p, sz, 0, 0);
- assert_zu_eq(tsz, sz, "Unexpected size change: %zu --> %zu", sz, tsz);
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_extra_no_move)
-{
- void *p;
- size_t sz, tsz;
-
- p = mallocx(42, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- sz = sallocx(p, 0);
-
- tsz = xallocx(p, sz, sz-42, 0);
- assert_zu_eq(tsz, sz, "Unexpected size change: %zu --> %zu", sz, tsz);
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_no_move_fail)
-{
- void *p;
- size_t sz, tsz;
-
- p = mallocx(42, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- sz = sallocx(p, 0);
-
- tsz = xallocx(p, sz + 5, 0, 0);
- assert_zu_eq(tsz, sz, "Unexpected size change: %zu --> %zu", sz, tsz);
-
- dallocx(p, 0);
-}
-TEST_END
-
-static unsigned
-get_nsizes_impl(const char *cmd)
-{
- unsigned ret;
- size_t z;
-
- z = sizeof(unsigned);
- assert_d_eq(mallctl(cmd, &ret, &z, NULL, 0), 0,
- "Unexpected mallctl(\"%s\", ...) failure", cmd);
-
- return (ret);
-}
-
-static unsigned
-get_nsmall(void)
-{
-
- return (get_nsizes_impl("arenas.nbins"));
-}
-
-static unsigned
-get_nlarge(void)
-{
-
- return (get_nsizes_impl("arenas.nlruns"));
-}
-
-static unsigned
-get_nhuge(void)
-{
-
- return (get_nsizes_impl("arenas.nhchunks"));
-}
-
-static size_t
-get_size_impl(const char *cmd, size_t ind)
-{
- size_t ret;
- size_t z;
- size_t mib[4];
- size_t miblen = 4;
-
- z = sizeof(size_t);
- assert_d_eq(mallctlnametomib(cmd, mib, &miblen),
- 0, "Unexpected mallctlnametomib(\"%s\", ...) failure", cmd);
- mib[2] = ind;
- z = sizeof(size_t);
- assert_d_eq(mallctlbymib(mib, miblen, &ret, &z, NULL, 0),
- 0, "Unexpected mallctlbymib([\"%s\", %zu], ...) failure", cmd, ind);
-
- return (ret);
-}
-
-static size_t
-get_small_size(size_t ind)
-{
-
- return (get_size_impl("arenas.bin.0.size", ind));
-}
-
-static size_t
-get_large_size(size_t ind)
-{
-
- return (get_size_impl("arenas.lrun.0.size", ind));
-}
-
-static size_t
-get_huge_size(size_t ind)
-{
-
- return (get_size_impl("arenas.hchunk.0.size", ind));
-}
-
-TEST_BEGIN(test_size)
-{
- size_t small0, hugemax;
- void *p;
-
- /* Get size classes. */
- small0 = get_small_size(0);
- hugemax = get_huge_size(get_nhuge()-1);
-
- p = mallocx(small0, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
-
- /* Test smallest supported size. */
- assert_zu_eq(xallocx(p, 1, 0, 0), small0,
- "Unexpected xallocx() behavior");
-
- /* Test largest supported size. */
- assert_zu_le(xallocx(p, hugemax, 0, 0), hugemax,
- "Unexpected xallocx() behavior");
-
- /* Test size overflow. */
- assert_zu_le(xallocx(p, hugemax+1, 0, 0), hugemax,
- "Unexpected xallocx() behavior");
- assert_zu_le(xallocx(p, SIZE_T_MAX, 0, 0), hugemax,
- "Unexpected xallocx() behavior");
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_size_extra_overflow)
-{
- size_t small0, hugemax;
- void *p;
-
- /* Get size classes. */
- small0 = get_small_size(0);
- hugemax = get_huge_size(get_nhuge()-1);
-
- p = mallocx(small0, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
-
- /* Test overflows that can be resolved by clamping extra. */
- assert_zu_le(xallocx(p, hugemax-1, 2, 0), hugemax,
- "Unexpected xallocx() behavior");
- assert_zu_le(xallocx(p, hugemax, 1, 0), hugemax,
- "Unexpected xallocx() behavior");
-
- /* Test overflow such that hugemax-size underflows. */
- assert_zu_le(xallocx(p, hugemax+1, 2, 0), hugemax,
- "Unexpected xallocx() behavior");
- assert_zu_le(xallocx(p, hugemax+2, 3, 0), hugemax,
- "Unexpected xallocx() behavior");
- assert_zu_le(xallocx(p, SIZE_T_MAX-2, 2, 0), hugemax,
- "Unexpected xallocx() behavior");
- assert_zu_le(xallocx(p, SIZE_T_MAX-1, 1, 0), hugemax,
- "Unexpected xallocx() behavior");
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_extra_small)
-{
- size_t small0, small1, hugemax;
- void *p;
-
- /* Get size classes. */
- small0 = get_small_size(0);
- small1 = get_small_size(1);
- hugemax = get_huge_size(get_nhuge()-1);
-
- p = mallocx(small0, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
-
- assert_zu_eq(xallocx(p, small1, 0, 0), small0,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, small1, 0, 0), small0,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, small0, small1 - small0, 0), small0,
- "Unexpected xallocx() behavior");
-
- /* Test size+extra overflow. */
- assert_zu_eq(xallocx(p, small0, hugemax - small0 + 1, 0), small0,
- "Unexpected xallocx() behavior");
- assert_zu_eq(xallocx(p, small0, SIZE_T_MAX - small0, 0), small0,
- "Unexpected xallocx() behavior");
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_extra_large)
-{
- int flags = MALLOCX_ARENA(arena_ind());
- size_t smallmax, large0, large1, large2, huge0, hugemax;
- void *p;
-
- /* Get size classes. */
- smallmax = get_small_size(get_nsmall()-1);
- large0 = get_large_size(0);
- large1 = get_large_size(1);
- large2 = get_large_size(2);
- huge0 = get_huge_size(0);
- hugemax = get_huge_size(get_nhuge()-1);
-
- p = mallocx(large2, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
-
- assert_zu_eq(xallocx(p, large2, 0, flags), large2,
- "Unexpected xallocx() behavior");
- /* Test size decrease with zero extra. */
- assert_zu_eq(xallocx(p, large0, 0, flags), large0,
- "Unexpected xallocx() behavior");
- assert_zu_eq(xallocx(p, smallmax, 0, flags), large0,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, large2, 0, flags), large2,
- "Unexpected xallocx() behavior");
- /* Test size decrease with non-zero extra. */
- assert_zu_eq(xallocx(p, large0, large2 - large0, flags), large2,
- "Unexpected xallocx() behavior");
- assert_zu_eq(xallocx(p, large1, large2 - large1, flags), large2,
- "Unexpected xallocx() behavior");
- assert_zu_eq(xallocx(p, large0, large1 - large0, flags), large1,
- "Unexpected xallocx() behavior");
- assert_zu_eq(xallocx(p, smallmax, large0 - smallmax, flags), large0,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, large0, 0, flags), large0,
- "Unexpected xallocx() behavior");
- /* Test size increase with zero extra. */
- assert_zu_eq(xallocx(p, large2, 0, flags), large2,
- "Unexpected xallocx() behavior");
- assert_zu_eq(xallocx(p, huge0, 0, flags), large2,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, large0, 0, flags), large0,
- "Unexpected xallocx() behavior");
- /* Test size increase with non-zero extra. */
- assert_zu_lt(xallocx(p, large0, huge0 - large0, flags), huge0,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, large0, 0, flags), large0,
- "Unexpected xallocx() behavior");
- /* Test size increase with non-zero extra. */
- assert_zu_eq(xallocx(p, large0, large2 - large0, flags), large2,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, large2, 0, flags), large2,
- "Unexpected xallocx() behavior");
- /* Test size+extra overflow. */
- assert_zu_lt(xallocx(p, large2, hugemax - large2 + 1, flags), huge0,
- "Unexpected xallocx() behavior");
-
- dallocx(p, flags);
-}
-TEST_END
-
-TEST_BEGIN(test_extra_huge)
-{
- int flags = MALLOCX_ARENA(arena_ind());
- size_t largemax, huge1, huge2, huge3, hugemax;
- void *p;
-
- /* Get size classes. */
- largemax = get_large_size(get_nlarge()-1);
- huge1 = get_huge_size(1);
- huge2 = get_huge_size(2);
- huge3 = get_huge_size(3);
- hugemax = get_huge_size(get_nhuge()-1);
-
- p = mallocx(huge3, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
-
- assert_zu_eq(xallocx(p, huge3, 0, flags), huge3,
- "Unexpected xallocx() behavior");
- /* Test size decrease with zero extra. */
- assert_zu_ge(xallocx(p, huge1, 0, flags), huge1,
- "Unexpected xallocx() behavior");
- assert_zu_ge(xallocx(p, largemax, 0, flags), huge1,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, huge3, 0, flags), huge3,
- "Unexpected xallocx() behavior");
- /* Test size decrease with non-zero extra. */
- assert_zu_eq(xallocx(p, huge1, huge3 - huge1, flags), huge3,
- "Unexpected xallocx() behavior");
- assert_zu_eq(xallocx(p, huge2, huge3 - huge2, flags), huge3,
- "Unexpected xallocx() behavior");
- assert_zu_eq(xallocx(p, huge1, huge2 - huge1, flags), huge2,
- "Unexpected xallocx() behavior");
- assert_zu_ge(xallocx(p, largemax, huge1 - largemax, flags), huge1,
- "Unexpected xallocx() behavior");
-
- assert_zu_ge(xallocx(p, huge1, 0, flags), huge1,
- "Unexpected xallocx() behavior");
- /* Test size increase with zero extra. */
- assert_zu_le(xallocx(p, huge3, 0, flags), huge3,
- "Unexpected xallocx() behavior");
- assert_zu_le(xallocx(p, hugemax+1, 0, flags), huge3,
- "Unexpected xallocx() behavior");
-
- assert_zu_ge(xallocx(p, huge1, 0, flags), huge1,
- "Unexpected xallocx() behavior");
- /* Test size increase with non-zero extra. */
- assert_zu_le(xallocx(p, huge1, SIZE_T_MAX - huge1, flags), hugemax,
- "Unexpected xallocx() behavior");
-
- assert_zu_ge(xallocx(p, huge1, 0, flags), huge1,
- "Unexpected xallocx() behavior");
- /* Test size increase with non-zero extra. */
- assert_zu_le(xallocx(p, huge1, huge3 - huge1, flags), huge3,
- "Unexpected xallocx() behavior");
-
- assert_zu_eq(xallocx(p, huge3, 0, flags), huge3,
- "Unexpected xallocx() behavior");
- /* Test size+extra overflow. */
- assert_zu_le(xallocx(p, huge3, hugemax - huge3 + 1, flags), hugemax,
- "Unexpected xallocx() behavior");
-
- dallocx(p, flags);
-}
-TEST_END
-
-static void
-print_filled_extents(const void *p, uint8_t c, size_t len)
-{
- const uint8_t *pc = (const uint8_t *)p;
- size_t i, range0;
- uint8_t c0;
-
- malloc_printf(" p=%p, c=%#x, len=%zu:", p, c, len);
- range0 = 0;
- c0 = pc[0];
- for (i = 0; i < len; i++) {
- if (pc[i] != c0) {
- malloc_printf(" %#x[%zu..%zu)", c0, range0, i);
- range0 = i;
- c0 = pc[i];
- }
- }
- malloc_printf(" %#x[%zu..%zu)\n", c0, range0, i);
-}
-
-static bool
-validate_fill(const void *p, uint8_t c, size_t offset, size_t len)
-{
- const uint8_t *pc = (const uint8_t *)p;
- bool err;
- size_t i;
-
- for (i = offset, err = false; i < offset+len; i++) {
- if (pc[i] != c)
- err = true;
- }
-
- if (err)
- print_filled_extents(p, c, offset + len);
-
- return (err);
-}
-
-static void
-test_zero(size_t szmin, size_t szmax)
-{
- int flags = MALLOCX_ARENA(arena_ind()) | MALLOCX_ZERO;
- size_t sz, nsz;
- void *p;
-#define FILL_BYTE 0x7aU
-
- sz = szmax;
- p = mallocx(sz, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() error");
- assert_false(validate_fill(p, 0x00, 0, sz), "Memory not filled: sz=%zu",
- sz);
-
- /*
- * Fill with non-zero so that non-debug builds are more likely to detect
- * errors.
- */
- memset(p, FILL_BYTE, sz);
- assert_false(validate_fill(p, FILL_BYTE, 0, sz),
- "Memory not filled: sz=%zu", sz);
-
- /* Shrink in place so that we can expect growing in place to succeed. */
- sz = szmin;
- assert_zu_eq(xallocx(p, sz, 0, flags), sz,
- "Unexpected xallocx() error");
- assert_false(validate_fill(p, FILL_BYTE, 0, sz),
- "Memory not filled: sz=%zu", sz);
-
- for (sz = szmin; sz < szmax; sz = nsz) {
- nsz = nallocx(sz+1, flags);
- assert_zu_eq(xallocx(p, sz+1, 0, flags), nsz,
- "Unexpected xallocx() failure");
- assert_false(validate_fill(p, FILL_BYTE, 0, sz),
- "Memory not filled: sz=%zu", sz);
- assert_false(validate_fill(p, 0x00, sz, nsz-sz),
- "Memory not filled: sz=%zu, nsz-sz=%zu", sz, nsz-sz);
- memset((void *)((uintptr_t)p + sz), FILL_BYTE, nsz-sz);
- assert_false(validate_fill(p, FILL_BYTE, 0, nsz),
- "Memory not filled: nsz=%zu", nsz);
- }
-
- dallocx(p, flags);
-}
-
-TEST_BEGIN(test_zero_large)
-{
- size_t large0, largemax;
-
- /* Get size classes. */
- large0 = get_large_size(0);
- largemax = get_large_size(get_nlarge()-1);
-
- test_zero(large0, largemax);
-}
-TEST_END
-
-TEST_BEGIN(test_zero_huge)
-{
- size_t huge0, huge1;
-
- /* Get size classes. */
- huge0 = get_huge_size(0);
- huge1 = get_huge_size(1);
-
- test_zero(huge1, huge0 * 2);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_same_size,
- test_extra_no_move,
- test_no_move_fail,
- test_size,
- test_size_extra_overflow,
- test_extra_small,
- test_extra_large,
- test_extra_huge,
- test_zero_large,
- test_zero_huge));
-}
diff --git a/memory/jemalloc/src/test/src/SFMT.c b/memory/jemalloc/src/test/src/SFMT.c
deleted file mode 100644
index 80cabe05e..000000000
--- a/memory/jemalloc/src/test/src/SFMT.c
+++ /dev/null
@@ -1,719 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-/**
- * @file SFMT.c
- * @brief SIMD oriented Fast Mersenne Twister(SFMT)
- *
- * @author Mutsuo Saito (Hiroshima University)
- * @author Makoto Matsumoto (Hiroshima University)
- *
- * Copyright (C) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. All rights reserved.
- *
- * The new BSD License is applied to this software, see LICENSE.txt
- */
-#define SFMT_C_
-#include "test/jemalloc_test.h"
-#include "test/SFMT-params.h"
-
-#if defined(JEMALLOC_BIG_ENDIAN) && !defined(BIG_ENDIAN64)
-#define BIG_ENDIAN64 1
-#endif
-#if defined(__BIG_ENDIAN__) && !defined(__amd64) && !defined(BIG_ENDIAN64)
-#define BIG_ENDIAN64 1
-#endif
-#if defined(HAVE_ALTIVEC) && !defined(BIG_ENDIAN64)
-#define BIG_ENDIAN64 1
-#endif
-#if defined(ONLY64) && !defined(BIG_ENDIAN64)
- #if defined(__GNUC__)
- #error "-DONLY64 must be specified with -DBIG_ENDIAN64"
- #endif
-#undef ONLY64
-#endif
-/*------------------------------------------------------
- 128-bit SIMD data type for Altivec, SSE2 or standard C
- ------------------------------------------------------*/
-#if defined(HAVE_ALTIVEC)
-/** 128-bit data structure */
-union W128_T {
- vector unsigned int s;
- uint32_t u[4];
-};
-/** 128-bit data type */
-typedef union W128_T w128_t;
-
-#elif defined(HAVE_SSE2)
-/** 128-bit data structure */
-union W128_T {
- __m128i si;
- uint32_t u[4];
-};
-/** 128-bit data type */
-typedef union W128_T w128_t;
-
-#else
-
-/** 128-bit data structure */
-struct W128_T {
- uint32_t u[4];
-};
-/** 128-bit data type */
-typedef struct W128_T w128_t;
-
-#endif
-
-struct sfmt_s {
- /** the 128-bit internal state array */
- w128_t sfmt[N];
- /** index counter to the 32-bit internal state array */
- int idx;
- /** a flag: it is 0 if and only if the internal state is not yet
- * initialized. */
- int initialized;
-};
-
-/*--------------------------------------
- FILE GLOBAL VARIABLES
- internal state, index counter and flag
- --------------------------------------*/
-
-/** a parity check vector which certificate the period of 2^{MEXP} */
-static uint32_t parity[4] = {PARITY1, PARITY2, PARITY3, PARITY4};
-
-/*----------------
- STATIC FUNCTIONS
- ----------------*/
-JEMALLOC_INLINE_C int idxof(int i);
-#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2))
-JEMALLOC_INLINE_C void rshift128(w128_t *out, w128_t const *in, int shift);
-JEMALLOC_INLINE_C void lshift128(w128_t *out, w128_t const *in, int shift);
-#endif
-JEMALLOC_INLINE_C void gen_rand_all(sfmt_t *ctx);
-JEMALLOC_INLINE_C void gen_rand_array(sfmt_t *ctx, w128_t *array, int size);
-JEMALLOC_INLINE_C uint32_t func1(uint32_t x);
-JEMALLOC_INLINE_C uint32_t func2(uint32_t x);
-static void period_certification(sfmt_t *ctx);
-#if defined(BIG_ENDIAN64) && !defined(ONLY64)
-JEMALLOC_INLINE_C void swap(w128_t *array, int size);
-#endif
-
-#if defined(HAVE_ALTIVEC)
- #include "test/SFMT-alti.h"
-#elif defined(HAVE_SSE2)
- #include "test/SFMT-sse2.h"
-#endif
-
-/**
- * This function simulate a 64-bit index of LITTLE ENDIAN
- * in BIG ENDIAN machine.
- */
-#ifdef ONLY64
-JEMALLOC_INLINE_C int idxof(int i) {
- return i ^ 1;
-}
-#else
-JEMALLOC_INLINE_C int idxof(int i) {
- return i;
-}
-#endif
-/**
- * This function simulates SIMD 128-bit right shift by the standard C.
- * The 128-bit integer given in in is shifted by (shift * 8) bits.
- * This function simulates the LITTLE ENDIAN SIMD.
- * @param out the output of this function
- * @param in the 128-bit data to be shifted
- * @param shift the shift value
- */
-#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2))
-#ifdef ONLY64
-JEMALLOC_INLINE_C void rshift128(w128_t *out, w128_t const *in, int shift) {
- uint64_t th, tl, oh, ol;
-
- th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]);
- tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]);
-
- oh = th >> (shift * 8);
- ol = tl >> (shift * 8);
- ol |= th << (64 - shift * 8);
- out->u[0] = (uint32_t)(ol >> 32);
- out->u[1] = (uint32_t)ol;
- out->u[2] = (uint32_t)(oh >> 32);
- out->u[3] = (uint32_t)oh;
-}
-#else
-JEMALLOC_INLINE_C void rshift128(w128_t *out, w128_t const *in, int shift) {
- uint64_t th, tl, oh, ol;
-
- th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]);
- tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]);
-
- oh = th >> (shift * 8);
- ol = tl >> (shift * 8);
- ol |= th << (64 - shift * 8);
- out->u[1] = (uint32_t)(ol >> 32);
- out->u[0] = (uint32_t)ol;
- out->u[3] = (uint32_t)(oh >> 32);
- out->u[2] = (uint32_t)oh;
-}
-#endif
-/**
- * This function simulates SIMD 128-bit left shift by the standard C.
- * The 128-bit integer given in in is shifted by (shift * 8) bits.
- * This function simulates the LITTLE ENDIAN SIMD.
- * @param out the output of this function
- * @param in the 128-bit data to be shifted
- * @param shift the shift value
- */
-#ifdef ONLY64
-JEMALLOC_INLINE_C void lshift128(w128_t *out, w128_t const *in, int shift) {
- uint64_t th, tl, oh, ol;
-
- th = ((uint64_t)in->u[2] << 32) | ((uint64_t)in->u[3]);
- tl = ((uint64_t)in->u[0] << 32) | ((uint64_t)in->u[1]);
-
- oh = th << (shift * 8);
- ol = tl << (shift * 8);
- oh |= tl >> (64 - shift * 8);
- out->u[0] = (uint32_t)(ol >> 32);
- out->u[1] = (uint32_t)ol;
- out->u[2] = (uint32_t)(oh >> 32);
- out->u[3] = (uint32_t)oh;
-}
-#else
-JEMALLOC_INLINE_C void lshift128(w128_t *out, w128_t const *in, int shift) {
- uint64_t th, tl, oh, ol;
-
- th = ((uint64_t)in->u[3] << 32) | ((uint64_t)in->u[2]);
- tl = ((uint64_t)in->u[1] << 32) | ((uint64_t)in->u[0]);
-
- oh = th << (shift * 8);
- ol = tl << (shift * 8);
- oh |= tl >> (64 - shift * 8);
- out->u[1] = (uint32_t)(ol >> 32);
- out->u[0] = (uint32_t)ol;
- out->u[3] = (uint32_t)(oh >> 32);
- out->u[2] = (uint32_t)oh;
-}
-#endif
-#endif
-
-/**
- * This function represents the recursion formula.
- * @param r output
- * @param a a 128-bit part of the internal state array
- * @param b a 128-bit part of the internal state array
- * @param c a 128-bit part of the internal state array
- * @param d a 128-bit part of the internal state array
- */
-#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2))
-#ifdef ONLY64
-JEMALLOC_INLINE_C void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c,
- w128_t *d) {
- w128_t x;
- w128_t y;
-
- lshift128(&x, a, SL2);
- rshift128(&y, c, SR2);
- r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SR1) & MSK2) ^ y.u[0]
- ^ (d->u[0] << SL1);
- r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SR1) & MSK1) ^ y.u[1]
- ^ (d->u[1] << SL1);
- r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SR1) & MSK4) ^ y.u[2]
- ^ (d->u[2] << SL1);
- r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SR1) & MSK3) ^ y.u[3]
- ^ (d->u[3] << SL1);
-}
-#else
-JEMALLOC_INLINE_C void do_recursion(w128_t *r, w128_t *a, w128_t *b, w128_t *c,
- w128_t *d) {
- w128_t x;
- w128_t y;
-
- lshift128(&x, a, SL2);
- rshift128(&y, c, SR2);
- r->u[0] = a->u[0] ^ x.u[0] ^ ((b->u[0] >> SR1) & MSK1) ^ y.u[0]
- ^ (d->u[0] << SL1);
- r->u[1] = a->u[1] ^ x.u[1] ^ ((b->u[1] >> SR1) & MSK2) ^ y.u[1]
- ^ (d->u[1] << SL1);
- r->u[2] = a->u[2] ^ x.u[2] ^ ((b->u[2] >> SR1) & MSK3) ^ y.u[2]
- ^ (d->u[2] << SL1);
- r->u[3] = a->u[3] ^ x.u[3] ^ ((b->u[3] >> SR1) & MSK4) ^ y.u[3]
- ^ (d->u[3] << SL1);
-}
-#endif
-#endif
-
-#if (!defined(HAVE_ALTIVEC)) && (!defined(HAVE_SSE2))
-/**
- * This function fills the internal state array with pseudorandom
- * integers.
- */
-JEMALLOC_INLINE_C void gen_rand_all(sfmt_t *ctx) {
- int i;
- w128_t *r1, *r2;
-
- r1 = &ctx->sfmt[N - 2];
- r2 = &ctx->sfmt[N - 1];
- for (i = 0; i < N - POS1; i++) {
- do_recursion(&ctx->sfmt[i], &ctx->sfmt[i], &ctx->sfmt[i + POS1], r1,
- r2);
- r1 = r2;
- r2 = &ctx->sfmt[i];
- }
- for (; i < N; i++) {
- do_recursion(&ctx->sfmt[i], &ctx->sfmt[i], &ctx->sfmt[i + POS1 - N], r1,
- r2);
- r1 = r2;
- r2 = &ctx->sfmt[i];
- }
-}
-
-/**
- * This function fills the user-specified array with pseudorandom
- * integers.
- *
- * @param array an 128-bit array to be filled by pseudorandom numbers.
- * @param size number of 128-bit pseudorandom numbers to be generated.
- */
-JEMALLOC_INLINE_C void gen_rand_array(sfmt_t *ctx, w128_t *array, int size) {
- int i, j;
- w128_t *r1, *r2;
-
- r1 = &ctx->sfmt[N - 2];
- r2 = &ctx->sfmt[N - 1];
- for (i = 0; i < N - POS1; i++) {
- do_recursion(&array[i], &ctx->sfmt[i], &ctx->sfmt[i + POS1], r1, r2);
- r1 = r2;
- r2 = &array[i];
- }
- for (; i < N; i++) {
- do_recursion(&array[i], &ctx->sfmt[i], &array[i + POS1 - N], r1, r2);
- r1 = r2;
- r2 = &array[i];
- }
- for (; i < size - N; i++) {
- do_recursion(&array[i], &array[i - N], &array[i + POS1 - N], r1, r2);
- r1 = r2;
- r2 = &array[i];
- }
- for (j = 0; j < 2 * N - size; j++) {
- ctx->sfmt[j] = array[j + size - N];
- }
- for (; i < size; i++, j++) {
- do_recursion(&array[i], &array[i - N], &array[i + POS1 - N], r1, r2);
- r1 = r2;
- r2 = &array[i];
- ctx->sfmt[j] = array[i];
- }
-}
-#endif
-
-#if defined(BIG_ENDIAN64) && !defined(ONLY64) && !defined(HAVE_ALTIVEC)
-JEMALLOC_INLINE_C void swap(w128_t *array, int size) {
- int i;
- uint32_t x, y;
-
- for (i = 0; i < size; i++) {
- x = array[i].u[0];
- y = array[i].u[2];
- array[i].u[0] = array[i].u[1];
- array[i].u[2] = array[i].u[3];
- array[i].u[1] = x;
- array[i].u[3] = y;
- }
-}
-#endif
-/**
- * This function represents a function used in the initialization
- * by init_by_array
- * @param x 32-bit integer
- * @return 32-bit integer
- */
-static uint32_t func1(uint32_t x) {
- return (x ^ (x >> 27)) * (uint32_t)1664525UL;
-}
-
-/**
- * This function represents a function used in the initialization
- * by init_by_array
- * @param x 32-bit integer
- * @return 32-bit integer
- */
-static uint32_t func2(uint32_t x) {
- return (x ^ (x >> 27)) * (uint32_t)1566083941UL;
-}
-
-/**
- * This function certificate the period of 2^{MEXP}
- */
-static void period_certification(sfmt_t *ctx) {
- int inner = 0;
- int i, j;
- uint32_t work;
- uint32_t *psfmt32 = &ctx->sfmt[0].u[0];
-
- for (i = 0; i < 4; i++)
- inner ^= psfmt32[idxof(i)] & parity[i];
- for (i = 16; i > 0; i >>= 1)
- inner ^= inner >> i;
- inner &= 1;
- /* check OK */
- if (inner == 1) {
- return;
- }
- /* check NG, and modification */
- for (i = 0; i < 4; i++) {
- work = 1;
- for (j = 0; j < 32; j++) {
- if ((work & parity[i]) != 0) {
- psfmt32[idxof(i)] ^= work;
- return;
- }
- work = work << 1;
- }
- }
-}
-
-/*----------------
- PUBLIC FUNCTIONS
- ----------------*/
-/**
- * This function returns the identification string.
- * The string shows the word size, the Mersenne exponent,
- * and all parameters of this generator.
- */
-const char *get_idstring(void) {
- return IDSTR;
-}
-
-/**
- * This function returns the minimum size of array used for \b
- * fill_array32() function.
- * @return minimum size of array used for fill_array32() function.
- */
-int get_min_array_size32(void) {
- return N32;
-}
-
-/**
- * This function returns the minimum size of array used for \b
- * fill_array64() function.
- * @return minimum size of array used for fill_array64() function.
- */
-int get_min_array_size64(void) {
- return N64;
-}
-
-#ifndef ONLY64
-/**
- * This function generates and returns 32-bit pseudorandom number.
- * init_gen_rand or init_by_array must be called before this function.
- * @return 32-bit pseudorandom number
- */
-uint32_t gen_rand32(sfmt_t *ctx) {
- uint32_t r;
- uint32_t *psfmt32 = &ctx->sfmt[0].u[0];
-
- assert(ctx->initialized);
- if (ctx->idx >= N32) {
- gen_rand_all(ctx);
- ctx->idx = 0;
- }
- r = psfmt32[ctx->idx++];
- return r;
-}
-
-/* Generate a random integer in [0..limit). */
-uint32_t gen_rand32_range(sfmt_t *ctx, uint32_t limit) {
- uint32_t ret, above;
-
- above = 0xffffffffU - (0xffffffffU % limit);
- while (1) {
- ret = gen_rand32(ctx);
- if (ret < above) {
- ret %= limit;
- break;
- }
- }
- return ret;
-}
-#endif
-/**
- * This function generates and returns 64-bit pseudorandom number.
- * init_gen_rand or init_by_array must be called before this function.
- * The function gen_rand64 should not be called after gen_rand32,
- * unless an initialization is again executed.
- * @return 64-bit pseudorandom number
- */
-uint64_t gen_rand64(sfmt_t *ctx) {
-#if defined(BIG_ENDIAN64) && !defined(ONLY64)
- uint32_t r1, r2;
- uint32_t *psfmt32 = &ctx->sfmt[0].u[0];
-#else
- uint64_t r;
- uint64_t *psfmt64 = (uint64_t *)&ctx->sfmt[0].u[0];
-#endif
-
- assert(ctx->initialized);
- assert(ctx->idx % 2 == 0);
-
- if (ctx->idx >= N32) {
- gen_rand_all(ctx);
- ctx->idx = 0;
- }
-#if defined(BIG_ENDIAN64) && !defined(ONLY64)
- r1 = psfmt32[ctx->idx];
- r2 = psfmt32[ctx->idx + 1];
- ctx->idx += 2;
- return ((uint64_t)r2 << 32) | r1;
-#else
- r = psfmt64[ctx->idx / 2];
- ctx->idx += 2;
- return r;
-#endif
-}
-
-/* Generate a random integer in [0..limit). */
-uint64_t gen_rand64_range(sfmt_t *ctx, uint64_t limit) {
- uint64_t ret, above;
-
- above = KQU(0xffffffffffffffff) - (KQU(0xffffffffffffffff) % limit);
- while (1) {
- ret = gen_rand64(ctx);
- if (ret < above) {
- ret %= limit;
- break;
- }
- }
- return ret;
-}
-
-#ifndef ONLY64
-/**
- * This function generates pseudorandom 32-bit integers in the
- * specified array[] by one call. The number of pseudorandom integers
- * is specified by the argument size, which must be at least 624 and a
- * multiple of four. The generation by this function is much faster
- * than the following gen_rand function.
- *
- * For initialization, init_gen_rand or init_by_array must be called
- * before the first call of this function. This function can not be
- * used after calling gen_rand function, without initialization.
- *
- * @param array an array where pseudorandom 32-bit integers are filled
- * by this function. The pointer to the array must be \b "aligned"
- * (namely, must be a multiple of 16) in the SIMD version, since it
- * refers to the address of a 128-bit integer. In the standard C
- * version, the pointer is arbitrary.
- *
- * @param size the number of 32-bit pseudorandom integers to be
- * generated. size must be a multiple of 4, and greater than or equal
- * to (MEXP / 128 + 1) * 4.
- *
- * @note \b memalign or \b posix_memalign is available to get aligned
- * memory. Mac OSX doesn't have these functions, but \b malloc of OSX
- * returns the pointer to the aligned memory block.
- */
-void fill_array32(sfmt_t *ctx, uint32_t *array, int size) {
- assert(ctx->initialized);
- assert(ctx->idx == N32);
- assert(size % 4 == 0);
- assert(size >= N32);
-
- gen_rand_array(ctx, (w128_t *)array, size / 4);
- ctx->idx = N32;
-}
-#endif
-
-/**
- * This function generates pseudorandom 64-bit integers in the
- * specified array[] by one call. The number of pseudorandom integers
- * is specified by the argument size, which must be at least 312 and a
- * multiple of two. The generation by this function is much faster
- * than the following gen_rand function.
- *
- * For initialization, init_gen_rand or init_by_array must be called
- * before the first call of this function. This function can not be
- * used after calling gen_rand function, without initialization.
- *
- * @param array an array where pseudorandom 64-bit integers are filled
- * by this function. The pointer to the array must be "aligned"
- * (namely, must be a multiple of 16) in the SIMD version, since it
- * refers to the address of a 128-bit integer. In the standard C
- * version, the pointer is arbitrary.
- *
- * @param size the number of 64-bit pseudorandom integers to be
- * generated. size must be a multiple of 2, and greater than or equal
- * to (MEXP / 128 + 1) * 2
- *
- * @note \b memalign or \b posix_memalign is available to get aligned
- * memory. Mac OSX doesn't have these functions, but \b malloc of OSX
- * returns the pointer to the aligned memory block.
- */
-void fill_array64(sfmt_t *ctx, uint64_t *array, int size) {
- assert(ctx->initialized);
- assert(ctx->idx == N32);
- assert(size % 2 == 0);
- assert(size >= N64);
-
- gen_rand_array(ctx, (w128_t *)array, size / 2);
- ctx->idx = N32;
-
-#if defined(BIG_ENDIAN64) && !defined(ONLY64)
- swap((w128_t *)array, size /2);
-#endif
-}
-
-/**
- * This function initializes the internal state array with a 32-bit
- * integer seed.
- *
- * @param seed a 32-bit integer used as the seed.
- */
-sfmt_t *init_gen_rand(uint32_t seed) {
- void *p;
- sfmt_t *ctx;
- int i;
- uint32_t *psfmt32;
-
- if (posix_memalign(&p, sizeof(w128_t), sizeof(sfmt_t)) != 0) {
- return NULL;
- }
- ctx = (sfmt_t *)p;
- psfmt32 = &ctx->sfmt[0].u[0];
-
- psfmt32[idxof(0)] = seed;
- for (i = 1; i < N32; i++) {
- psfmt32[idxof(i)] = 1812433253UL * (psfmt32[idxof(i - 1)]
- ^ (psfmt32[idxof(i - 1)] >> 30))
- + i;
- }
- ctx->idx = N32;
- period_certification(ctx);
- ctx->initialized = 1;
-
- return ctx;
-}
-
-/**
- * This function initializes the internal state array,
- * with an array of 32-bit integers used as the seeds
- * @param init_key the array of 32-bit integers, used as a seed.
- * @param key_length the length of init_key.
- */
-sfmt_t *init_by_array(uint32_t *init_key, int key_length) {
- void *p;
- sfmt_t *ctx;
- int i, j, count;
- uint32_t r;
- int lag;
- int mid;
- int size = N * 4;
- uint32_t *psfmt32;
-
- if (posix_memalign(&p, sizeof(w128_t), sizeof(sfmt_t)) != 0) {
- return NULL;
- }
- ctx = (sfmt_t *)p;
- psfmt32 = &ctx->sfmt[0].u[0];
-
- if (size >= 623) {
- lag = 11;
- } else if (size >= 68) {
- lag = 7;
- } else if (size >= 39) {
- lag = 5;
- } else {
- lag = 3;
- }
- mid = (size - lag) / 2;
-
- memset(ctx->sfmt, 0x8b, sizeof(ctx->sfmt));
- if (key_length + 1 > N32) {
- count = key_length + 1;
- } else {
- count = N32;
- }
- r = func1(psfmt32[idxof(0)] ^ psfmt32[idxof(mid)]
- ^ psfmt32[idxof(N32 - 1)]);
- psfmt32[idxof(mid)] += r;
- r += key_length;
- psfmt32[idxof(mid + lag)] += r;
- psfmt32[idxof(0)] = r;
-
- count--;
- for (i = 1, j = 0; (j < count) && (j < key_length); j++) {
- r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % N32)]
- ^ psfmt32[idxof((i + N32 - 1) % N32)]);
- psfmt32[idxof((i + mid) % N32)] += r;
- r += init_key[j] + i;
- psfmt32[idxof((i + mid + lag) % N32)] += r;
- psfmt32[idxof(i)] = r;
- i = (i + 1) % N32;
- }
- for (; j < count; j++) {
- r = func1(psfmt32[idxof(i)] ^ psfmt32[idxof((i + mid) % N32)]
- ^ psfmt32[idxof((i + N32 - 1) % N32)]);
- psfmt32[idxof((i + mid) % N32)] += r;
- r += i;
- psfmt32[idxof((i + mid + lag) % N32)] += r;
- psfmt32[idxof(i)] = r;
- i = (i + 1) % N32;
- }
- for (j = 0; j < N32; j++) {
- r = func2(psfmt32[idxof(i)] + psfmt32[idxof((i + mid) % N32)]
- + psfmt32[idxof((i + N32 - 1) % N32)]);
- psfmt32[idxof((i + mid) % N32)] ^= r;
- r -= i;
- psfmt32[idxof((i + mid + lag) % N32)] ^= r;
- psfmt32[idxof(i)] = r;
- i = (i + 1) % N32;
- }
-
- ctx->idx = N32;
- period_certification(ctx);
- ctx->initialized = 1;
-
- return ctx;
-}
-
-void fini_gen_rand(sfmt_t *ctx) {
- assert(ctx != NULL);
-
- ctx->initialized = 0;
- free(ctx);
-}
diff --git a/memory/jemalloc/src/test/src/btalloc.c b/memory/jemalloc/src/test/src/btalloc.c
deleted file mode 100644
index 9a253d978..000000000
--- a/memory/jemalloc/src/test/src/btalloc.c
+++ /dev/null
@@ -1,8 +0,0 @@
-#include "test/jemalloc_test.h"
-
-void *
-btalloc(size_t size, unsigned bits)
-{
-
- return (btalloc_0(size, bits));
-}
diff --git a/memory/jemalloc/src/test/src/btalloc_0.c b/memory/jemalloc/src/test/src/btalloc_0.c
deleted file mode 100644
index 77d8904ea..000000000
--- a/memory/jemalloc/src/test/src/btalloc_0.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#include "test/jemalloc_test.h"
-
-btalloc_n_gen(0)
diff --git a/memory/jemalloc/src/test/src/btalloc_1.c b/memory/jemalloc/src/test/src/btalloc_1.c
deleted file mode 100644
index 4c126c309..000000000
--- a/memory/jemalloc/src/test/src/btalloc_1.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#include "test/jemalloc_test.h"
-
-btalloc_n_gen(1)
diff --git a/memory/jemalloc/src/test/src/math.c b/memory/jemalloc/src/test/src/math.c
deleted file mode 100644
index 887a36390..000000000
--- a/memory/jemalloc/src/test/src/math.c
+++ /dev/null
@@ -1,2 +0,0 @@
-#define MATH_C_
-#include "test/jemalloc_test.h"
diff --git a/memory/jemalloc/src/test/src/mq.c b/memory/jemalloc/src/test/src/mq.c
deleted file mode 100644
index 40b31c15c..000000000
--- a/memory/jemalloc/src/test/src/mq.c
+++ /dev/null
@@ -1,29 +0,0 @@
-#include "test/jemalloc_test.h"
-
-/*
- * Sleep for approximately ns nanoseconds. No lower *nor* upper bound on sleep
- * time is guaranteed.
- */
-void
-mq_nanosleep(unsigned ns)
-{
-
- assert(ns <= 1000*1000*1000);
-
-#ifdef _WIN32
- Sleep(ns / 1000);
-#else
- {
- struct timespec timeout;
-
- if (ns < 1000*1000*1000) {
- timeout.tv_sec = 0;
- timeout.tv_nsec = ns;
- } else {
- timeout.tv_sec = 1;
- timeout.tv_nsec = 0;
- }
- nanosleep(&timeout, NULL);
- }
-#endif
-}
diff --git a/memory/jemalloc/src/test/src/mtx.c b/memory/jemalloc/src/test/src/mtx.c
deleted file mode 100644
index 8a5dfdd99..000000000
--- a/memory/jemalloc/src/test/src/mtx.c
+++ /dev/null
@@ -1,73 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifndef _CRT_SPINCOUNT
-#define _CRT_SPINCOUNT 4000
-#endif
-
-bool
-mtx_init(mtx_t *mtx)
-{
-
-#ifdef _WIN32
- if (!InitializeCriticalSectionAndSpinCount(&mtx->lock, _CRT_SPINCOUNT))
- return (true);
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
- mtx->lock = OS_UNFAIR_LOCK_INIT;
-#elif (defined(JEMALLOC_OSSPIN))
- mtx->lock = 0;
-#else
- pthread_mutexattr_t attr;
-
- if (pthread_mutexattr_init(&attr) != 0)
- return (true);
- pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_DEFAULT);
- if (pthread_mutex_init(&mtx->lock, &attr) != 0) {
- pthread_mutexattr_destroy(&attr);
- return (true);
- }
- pthread_mutexattr_destroy(&attr);
-#endif
- return (false);
-}
-
-void
-mtx_fini(mtx_t *mtx)
-{
-
-#ifdef _WIN32
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
-#elif (defined(JEMALLOC_OSSPIN))
-#else
- pthread_mutex_destroy(&mtx->lock);
-#endif
-}
-
-void
-mtx_lock(mtx_t *mtx)
-{
-
-#ifdef _WIN32
- EnterCriticalSection(&mtx->lock);
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
- os_unfair_lock_lock(&mtx->lock);
-#elif (defined(JEMALLOC_OSSPIN))
- OSSpinLockLock(&mtx->lock);
-#else
- pthread_mutex_lock(&mtx->lock);
-#endif
-}
-
-void
-mtx_unlock(mtx_t *mtx)
-{
-
-#ifdef _WIN32
- LeaveCriticalSection(&mtx->lock);
-#elif (defined(JEMALLOC_OS_UNFAIR_LOCK))
- os_unfair_lock_unlock(&mtx->lock);
-#elif (defined(JEMALLOC_OSSPIN))
- OSSpinLockUnlock(&mtx->lock);
-#else
- pthread_mutex_unlock(&mtx->lock);
-#endif
-}
diff --git a/memory/jemalloc/src/test/src/test.c b/memory/jemalloc/src/test/src/test.c
deleted file mode 100644
index d70cc7501..000000000
--- a/memory/jemalloc/src/test/src/test.c
+++ /dev/null
@@ -1,133 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static unsigned test_count = 0;
-static test_status_t test_counts[test_status_count] = {0, 0, 0};
-static test_status_t test_status = test_status_pass;
-static const char * test_name = "";
-
-JEMALLOC_FORMAT_PRINTF(1, 2)
-void
-test_skip(const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- malloc_vcprintf(NULL, NULL, format, ap);
- va_end(ap);
- malloc_printf("\n");
- test_status = test_status_skip;
-}
-
-JEMALLOC_FORMAT_PRINTF(1, 2)
-void
-test_fail(const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- malloc_vcprintf(NULL, NULL, format, ap);
- va_end(ap);
- malloc_printf("\n");
- test_status = test_status_fail;
-}
-
-static const char *
-test_status_string(test_status_t test_status)
-{
-
- switch (test_status) {
- case test_status_pass: return "pass";
- case test_status_skip: return "skip";
- case test_status_fail: return "fail";
- default: not_reached();
- }
-}
-
-void
-p_test_init(const char *name)
-{
-
- test_count++;
- test_status = test_status_pass;
- test_name = name;
-}
-
-void
-p_test_fini(void)
-{
-
- test_counts[test_status]++;
- malloc_printf("%s: %s\n", test_name, test_status_string(test_status));
-}
-
-static test_status_t
-p_test_impl(bool do_malloc_init, test_t *t, va_list ap)
-{
- test_status_t ret;
-
- if (do_malloc_init) {
- /*
- * Make sure initialization occurs prior to running tests.
- * Tests are special because they may use internal facilities
- * prior to triggering initialization as a side effect of
- * calling into the public API.
- */
- if (nallocx(1, 0) == 0) {
- malloc_printf("Initialization error");
- return (test_status_fail);
- }
- }
-
- ret = test_status_pass;
- for (; t != NULL; t = va_arg(ap, test_t *)) {
- t();
- if (test_status > ret)
- ret = test_status;
- }
-
- malloc_printf("--- %s: %u/%u, %s: %u/%u, %s: %u/%u ---\n",
- test_status_string(test_status_pass),
- test_counts[test_status_pass], test_count,
- test_status_string(test_status_skip),
- test_counts[test_status_skip], test_count,
- test_status_string(test_status_fail),
- test_counts[test_status_fail], test_count);
-
- return (ret);
-}
-
-test_status_t
-p_test(test_t *t, ...)
-{
- test_status_t ret;
- va_list ap;
-
- ret = test_status_pass;
- va_start(ap, t);
- ret = p_test_impl(true, t, ap);
- va_end(ap);
-
- return (ret);
-}
-
-test_status_t
-p_test_no_malloc_init(test_t *t, ...)
-{
- test_status_t ret;
- va_list ap;
-
- ret = test_status_pass;
- va_start(ap, t);
- ret = p_test_impl(false, t, ap);
- va_end(ap);
-
- return (ret);
-}
-
-void
-p_test_fail(const char *prefix, const char *message)
-{
-
- malloc_cprintf(NULL, NULL, "%s%s\n", prefix, message);
- test_status = test_status_fail;
-}
diff --git a/memory/jemalloc/src/test/src/thd.c b/memory/jemalloc/src/test/src/thd.c
deleted file mode 100644
index c9d006586..000000000
--- a/memory/jemalloc/src/test/src/thd.c
+++ /dev/null
@@ -1,39 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef _WIN32
-void
-thd_create(thd_t *thd, void *(*proc)(void *), void *arg)
-{
- LPTHREAD_START_ROUTINE routine = (LPTHREAD_START_ROUTINE)proc;
- *thd = CreateThread(NULL, 0, routine, arg, 0, NULL);
- if (*thd == NULL)
- test_fail("Error in CreateThread()\n");
-}
-
-void
-thd_join(thd_t thd, void **ret)
-{
-
- if (WaitForSingleObject(thd, INFINITE) == WAIT_OBJECT_0 && ret) {
- DWORD exit_code;
- GetExitCodeThread(thd, (LPDWORD) &exit_code);
- *ret = (void *)(uintptr_t)exit_code;
- }
-}
-
-#else
-void
-thd_create(thd_t *thd, void *(*proc)(void *), void *arg)
-{
-
- if (pthread_create(thd, NULL, proc, arg) != 0)
- test_fail("Error in pthread_create()\n");
-}
-
-void
-thd_join(thd_t thd, void **ret)
-{
-
- pthread_join(thd, ret);
-}
-#endif
diff --git a/memory/jemalloc/src/test/src/timer.c b/memory/jemalloc/src/test/src/timer.c
deleted file mode 100644
index 3c7e63a26..000000000
--- a/memory/jemalloc/src/test/src/timer.c
+++ /dev/null
@@ -1,60 +0,0 @@
-#include "test/jemalloc_test.h"
-
-void
-timer_start(timedelta_t *timer)
-{
-
- nstime_init(&timer->t0, 0);
- nstime_update(&timer->t0);
-}
-
-void
-timer_stop(timedelta_t *timer)
-{
-
- nstime_copy(&timer->t1, &timer->t0);
- nstime_update(&timer->t1);
-}
-
-uint64_t
-timer_usec(const timedelta_t *timer)
-{
- nstime_t delta;
-
- nstime_copy(&delta, &timer->t1);
- nstime_subtract(&delta, &timer->t0);
- return (nstime_ns(&delta) / 1000);
-}
-
-void
-timer_ratio(timedelta_t *a, timedelta_t *b, char *buf, size_t buflen)
-{
- uint64_t t0 = timer_usec(a);
- uint64_t t1 = timer_usec(b);
- uint64_t mult;
- size_t i = 0;
- size_t j, n;
-
- /* Whole. */
- n = malloc_snprintf(&buf[i], buflen-i, "%"FMTu64, t0 / t1);
- i += n;
- if (i >= buflen)
- return;
- mult = 1;
- for (j = 0; j < n; j++)
- mult *= 10;
-
- /* Decimal. */
- n = malloc_snprintf(&buf[i], buflen-i, ".");
- i += n;
-
- /* Fraction. */
- while (i < buflen-1) {
- uint64_t round = (i+1 == buflen-1 && ((t0 * mult * 10 / t1) % 10
- >= 5)) ? 1 : 0;
- n = malloc_snprintf(&buf[i], buflen-i,
- "%"FMTu64, (t0 * mult / t1) % 10 + round);
- i += n;
- mult *= 10;
- }
-}
diff --git a/memory/jemalloc/src/test/stress/microbench.c b/memory/jemalloc/src/test/stress/microbench.c
deleted file mode 100644
index 7dc45f89c..000000000
--- a/memory/jemalloc/src/test/stress/microbench.c
+++ /dev/null
@@ -1,182 +0,0 @@
-#include "test/jemalloc_test.h"
-
-JEMALLOC_INLINE_C void
-time_func(timedelta_t *timer, uint64_t nwarmup, uint64_t niter,
- void (*func)(void))
-{
- uint64_t i;
-
- for (i = 0; i < nwarmup; i++)
- func();
- timer_start(timer);
- for (i = 0; i < niter; i++)
- func();
- timer_stop(timer);
-}
-
-void
-compare_funcs(uint64_t nwarmup, uint64_t niter, const char *name_a,
- void (*func_a), const char *name_b, void (*func_b))
-{
- timedelta_t timer_a, timer_b;
- char ratio_buf[6];
- void *p;
-
- p = mallocx(1, 0);
- if (p == NULL) {
- test_fail("Unexpected mallocx() failure");
- return;
- }
-
- time_func(&timer_a, nwarmup, niter, func_a);
- time_func(&timer_b, nwarmup, niter, func_b);
-
- timer_ratio(&timer_a, &timer_b, ratio_buf, sizeof(ratio_buf));
- malloc_printf("%"FMTu64" iterations, %s=%"FMTu64"us, "
- "%s=%"FMTu64"us, ratio=1:%s\n",
- niter, name_a, timer_usec(&timer_a), name_b, timer_usec(&timer_b),
- ratio_buf);
-
- dallocx(p, 0);
-}
-
-static void
-malloc_free(void)
-{
- /* The compiler can optimize away free(malloc(1))! */
- void *p = malloc(1);
- if (p == NULL) {
- test_fail("Unexpected malloc() failure");
- return;
- }
- free(p);
-}
-
-static void
-mallocx_free(void)
-{
- void *p = mallocx(1, 0);
- if (p == NULL) {
- test_fail("Unexpected mallocx() failure");
- return;
- }
- free(p);
-}
-
-TEST_BEGIN(test_malloc_vs_mallocx)
-{
-
- compare_funcs(10*1000*1000, 100*1000*1000, "malloc",
- malloc_free, "mallocx", mallocx_free);
-}
-TEST_END
-
-static void
-malloc_dallocx(void)
-{
- void *p = malloc(1);
- if (p == NULL) {
- test_fail("Unexpected malloc() failure");
- return;
- }
- dallocx(p, 0);
-}
-
-static void
-malloc_sdallocx(void)
-{
- void *p = malloc(1);
- if (p == NULL) {
- test_fail("Unexpected malloc() failure");
- return;
- }
- sdallocx(p, 1, 0);
-}
-
-TEST_BEGIN(test_free_vs_dallocx)
-{
-
- compare_funcs(10*1000*1000, 100*1000*1000, "free", malloc_free,
- "dallocx", malloc_dallocx);
-}
-TEST_END
-
-TEST_BEGIN(test_dallocx_vs_sdallocx)
-{
-
- compare_funcs(10*1000*1000, 100*1000*1000, "dallocx", malloc_dallocx,
- "sdallocx", malloc_sdallocx);
-}
-TEST_END
-
-static void
-malloc_mus_free(void)
-{
- void *p;
-
- p = malloc(1);
- if (p == NULL) {
- test_fail("Unexpected malloc() failure");
- return;
- }
- malloc_usable_size(p);
- free(p);
-}
-
-static void
-malloc_sallocx_free(void)
-{
- void *p;
-
- p = malloc(1);
- if (p == NULL) {
- test_fail("Unexpected malloc() failure");
- return;
- }
- if (sallocx(p, 0) < 1)
- test_fail("Unexpected sallocx() failure");
- free(p);
-}
-
-TEST_BEGIN(test_mus_vs_sallocx)
-{
-
- compare_funcs(10*1000*1000, 100*1000*1000, "malloc_usable_size",
- malloc_mus_free, "sallocx", malloc_sallocx_free);
-}
-TEST_END
-
-static void
-malloc_nallocx_free(void)
-{
- void *p;
-
- p = malloc(1);
- if (p == NULL) {
- test_fail("Unexpected malloc() failure");
- return;
- }
- if (nallocx(1, 0) < 1)
- test_fail("Unexpected nallocx() failure");
- free(p);
-}
-
-TEST_BEGIN(test_sallocx_vs_nallocx)
-{
-
- compare_funcs(10*1000*1000, 100*1000*1000, "sallocx",
- malloc_sallocx_free, "nallocx", malloc_nallocx_free);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_malloc_vs_mallocx,
- test_free_vs_dallocx,
- test_dallocx_vs_sdallocx,
- test_mus_vs_sallocx,
- test_sallocx_vs_nallocx));
-}
diff --git a/memory/jemalloc/src/test/test.sh.in b/memory/jemalloc/src/test/test.sh.in
deleted file mode 100644
index a39f99f6b..000000000
--- a/memory/jemalloc/src/test/test.sh.in
+++ /dev/null
@@ -1,53 +0,0 @@
-#!/bin/sh
-
-case @abi@ in
- macho)
- export DYLD_FALLBACK_LIBRARY_PATH="@objroot@lib"
- ;;
- pecoff)
- export PATH="${PATH}:@objroot@lib"
- ;;
- *)
- ;;
-esac
-
-# Corresponds to test_status_t.
-pass_code=0
-skip_code=1
-fail_code=2
-
-pass_count=0
-skip_count=0
-fail_count=0
-for t in $@; do
- if [ $pass_count -ne 0 -o $skip_count -ne 0 -o $fail_count != 0 ] ; then
- echo
- fi
- echo "=== ${t} ==="
- ${t}@exe@ @abs_srcroot@ @abs_objroot@
- result_code=$?
- case ${result_code} in
- ${pass_code})
- pass_count=$((pass_count+1))
- ;;
- ${skip_code})
- skip_count=$((skip_count+1))
- ;;
- ${fail_code})
- fail_count=$((fail_count+1))
- ;;
- *)
- echo "Test harness error" 1>&2
- exit 1
- esac
-done
-
-total_count=`expr ${pass_count} + ${skip_count} + ${fail_count}`
-echo
-echo "Test suite summary: pass: ${pass_count}/${total_count}, skip: ${skip_count}/${total_count}, fail: ${fail_count}/${total_count}"
-
-if [ ${fail_count} -eq 0 ] ; then
- exit 0
-else
- exit 1
-fi
diff --git a/memory/jemalloc/src/test/unit/SFMT.c b/memory/jemalloc/src/test/unit/SFMT.c
deleted file mode 100644
index ba4be8702..000000000
--- a/memory/jemalloc/src/test/unit/SFMT.c
+++ /dev/null
@@ -1,1605 +0,0 @@
-/*
- * This file derives from SFMT 1.3.3
- * (http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html), which was
- * released under the terms of the following license:
- *
- * Copyright (c) 2006,2007 Mutsuo Saito, Makoto Matsumoto and Hiroshima
- * University. 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 Hiroshima 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 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.
- */
-#include "test/jemalloc_test.h"
-
-#define BLOCK_SIZE 10000
-#define BLOCK_SIZE64 (BLOCK_SIZE / 2)
-#define COUNT_1 1000
-#define COUNT_2 700
-
-static const uint32_t init_gen_rand_32_expected[] = {
- 3440181298U, 1564997079U, 1510669302U, 2930277156U, 1452439940U,
- 3796268453U, 423124208U, 2143818589U, 3827219408U, 2987036003U,
- 2674978610U, 1536842514U, 2027035537U, 2534897563U, 1686527725U,
- 545368292U, 1489013321U, 1370534252U, 4231012796U, 3994803019U,
- 1764869045U, 824597505U, 862581900U, 2469764249U, 812862514U,
- 359318673U, 116957936U, 3367389672U, 2327178354U, 1898245200U,
- 3206507879U, 2378925033U, 1040214787U, 2524778605U, 3088428700U,
- 1417665896U, 964324147U, 2282797708U, 2456269299U, 313400376U,
- 2245093271U, 1015729427U, 2694465011U, 3246975184U, 1992793635U,
- 463679346U, 3721104591U, 3475064196U, 856141236U, 1499559719U,
- 3522818941U, 3721533109U, 1954826617U, 1282044024U, 1543279136U,
- 1301863085U, 2669145051U, 4221477354U, 3896016841U, 3392740262U,
- 462466863U, 1037679449U, 1228140306U, 922298197U, 1205109853U,
- 1872938061U, 3102547608U, 2742766808U, 1888626088U, 4028039414U,
- 157593879U, 1136901695U, 4038377686U, 3572517236U, 4231706728U,
- 2997311961U, 1189931652U, 3981543765U, 2826166703U, 87159245U,
- 1721379072U, 3897926942U, 1790395498U, 2569178939U, 1047368729U,
- 2340259131U, 3144212906U, 2301169789U, 2442885464U, 3034046771U,
- 3667880593U, 3935928400U, 2372805237U, 1666397115U, 2460584504U,
- 513866770U, 3810869743U, 2147400037U, 2792078025U, 2941761810U,
- 3212265810U, 984692259U, 346590253U, 1804179199U, 3298543443U,
- 750108141U, 2880257022U, 243310542U, 1869036465U, 1588062513U,
- 2983949551U, 1931450364U, 4034505847U, 2735030199U, 1628461061U,
- 2539522841U, 127965585U, 3992448871U, 913388237U, 559130076U,
- 1202933193U, 4087643167U, 2590021067U, 2256240196U, 1746697293U,
- 1013913783U, 1155864921U, 2715773730U, 915061862U, 1948766573U,
- 2322882854U, 3761119102U, 1343405684U, 3078711943U, 3067431651U,
- 3245156316U, 3588354584U, 3484623306U, 3899621563U, 4156689741U,
- 3237090058U, 3880063844U, 862416318U, 4039923869U, 2303788317U,
- 3073590536U, 701653667U, 2131530884U, 3169309950U, 2028486980U,
- 747196777U, 3620218225U, 432016035U, 1449580595U, 2772266392U,
- 444224948U, 1662832057U, 3184055582U, 3028331792U, 1861686254U,
- 1104864179U, 342430307U, 1350510923U, 3024656237U, 1028417492U,
- 2870772950U, 290847558U, 3675663500U, 508431529U, 4264340390U,
- 2263569913U, 1669302976U, 519511383U, 2706411211U, 3764615828U,
- 3883162495U, 4051445305U, 2412729798U, 3299405164U, 3991911166U,
- 2348767304U, 2664054906U, 3763609282U, 593943581U, 3757090046U,
- 2075338894U, 2020550814U, 4287452920U, 4290140003U, 1422957317U,
- 2512716667U, 2003485045U, 2307520103U, 2288472169U, 3940751663U,
- 4204638664U, 2892583423U, 1710068300U, 3904755993U, 2363243951U,
- 3038334120U, 547099465U, 771105860U, 3199983734U, 4282046461U,
- 2298388363U, 934810218U, 2837827901U, 3952500708U, 2095130248U,
- 3083335297U, 26885281U, 3932155283U, 1531751116U, 1425227133U,
- 495654159U, 3279634176U, 3855562207U, 3957195338U, 4159985527U,
- 893375062U, 1875515536U, 1327247422U, 3754140693U, 1028923197U,
- 1729880440U, 805571298U, 448971099U, 2726757106U, 2749436461U,
- 2485987104U, 175337042U, 3235477922U, 3882114302U, 2020970972U,
- 943926109U, 2762587195U, 1904195558U, 3452650564U, 108432281U,
- 3893463573U, 3977583081U, 2636504348U, 1110673525U, 3548479841U,
- 4258854744U, 980047703U, 4057175418U, 3890008292U, 145653646U,
- 3141868989U, 3293216228U, 1194331837U, 1254570642U, 3049934521U,
- 2868313360U, 2886032750U, 1110873820U, 279553524U, 3007258565U,
- 1104807822U, 3186961098U, 315764646U, 2163680838U, 3574508994U,
- 3099755655U, 191957684U, 3642656737U, 3317946149U, 3522087636U,
- 444526410U, 779157624U, 1088229627U, 1092460223U, 1856013765U,
- 3659877367U, 368270451U, 503570716U, 3000984671U, 2742789647U,
- 928097709U, 2914109539U, 308843566U, 2816161253U, 3667192079U,
- 2762679057U, 3395240989U, 2928925038U, 1491465914U, 3458702834U,
- 3787782576U, 2894104823U, 1296880455U, 1253636503U, 989959407U,
- 2291560361U, 2776790436U, 1913178042U, 1584677829U, 689637520U,
- 1898406878U, 688391508U, 3385234998U, 845493284U, 1943591856U,
- 2720472050U, 222695101U, 1653320868U, 2904632120U, 4084936008U,
- 1080720688U, 3938032556U, 387896427U, 2650839632U, 99042991U,
- 1720913794U, 1047186003U, 1877048040U, 2090457659U, 517087501U,
- 4172014665U, 2129713163U, 2413533132U, 2760285054U, 4129272496U,
- 1317737175U, 2309566414U, 2228873332U, 3889671280U, 1110864630U,
- 3576797776U, 2074552772U, 832002644U, 3097122623U, 2464859298U,
- 2679603822U, 1667489885U, 3237652716U, 1478413938U, 1719340335U,
- 2306631119U, 639727358U, 3369698270U, 226902796U, 2099920751U,
- 1892289957U, 2201594097U, 3508197013U, 3495811856U, 3900381493U,
- 841660320U, 3974501451U, 3360949056U, 1676829340U, 728899254U,
- 2047809627U, 2390948962U, 670165943U, 3412951831U, 4189320049U,
- 1911595255U, 2055363086U, 507170575U, 418219594U, 4141495280U,
- 2692088692U, 4203630654U, 3540093932U, 791986533U, 2237921051U,
- 2526864324U, 2956616642U, 1394958700U, 1983768223U, 1893373266U,
- 591653646U, 228432437U, 1611046598U, 3007736357U, 1040040725U,
- 2726180733U, 2789804360U, 4263568405U, 829098158U, 3847722805U,
- 1123578029U, 1804276347U, 997971319U, 4203797076U, 4185199713U,
- 2811733626U, 2343642194U, 2985262313U, 1417930827U, 3759587724U,
- 1967077982U, 1585223204U, 1097475516U, 1903944948U, 740382444U,
- 1114142065U, 1541796065U, 1718384172U, 1544076191U, 1134682254U,
- 3519754455U, 2866243923U, 341865437U, 645498576U, 2690735853U,
- 1046963033U, 2493178460U, 1187604696U, 1619577821U, 488503634U,
- 3255768161U, 2306666149U, 1630514044U, 2377698367U, 2751503746U,
- 3794467088U, 1796415981U, 3657173746U, 409136296U, 1387122342U,
- 1297726519U, 219544855U, 4270285558U, 437578827U, 1444698679U,
- 2258519491U, 963109892U, 3982244073U, 3351535275U, 385328496U,
- 1804784013U, 698059346U, 3920535147U, 708331212U, 784338163U,
- 785678147U, 1238376158U, 1557298846U, 2037809321U, 271576218U,
- 4145155269U, 1913481602U, 2763691931U, 588981080U, 1201098051U,
- 3717640232U, 1509206239U, 662536967U, 3180523616U, 1133105435U,
- 2963500837U, 2253971215U, 3153642623U, 1066925709U, 2582781958U,
- 3034720222U, 1090798544U, 2942170004U, 4036187520U, 686972531U,
- 2610990302U, 2641437026U, 1837562420U, 722096247U, 1315333033U,
- 2102231203U, 3402389208U, 3403698140U, 1312402831U, 2898426558U,
- 814384596U, 385649582U, 1916643285U, 1924625106U, 2512905582U,
- 2501170304U, 4275223366U, 2841225246U, 1467663688U, 3563567847U,
- 2969208552U, 884750901U, 102992576U, 227844301U, 3681442994U,
- 3502881894U, 4034693299U, 1166727018U, 1697460687U, 1737778332U,
- 1787161139U, 1053003655U, 1215024478U, 2791616766U, 2525841204U,
- 1629323443U, 3233815U, 2003823032U, 3083834263U, 2379264872U,
- 3752392312U, 1287475550U, 3770904171U, 3004244617U, 1502117784U,
- 918698423U, 2419857538U, 3864502062U, 1751322107U, 2188775056U,
- 4018728324U, 983712955U, 440071928U, 3710838677U, 2001027698U,
- 3994702151U, 22493119U, 3584400918U, 3446253670U, 4254789085U,
- 1405447860U, 1240245579U, 1800644159U, 1661363424U, 3278326132U,
- 3403623451U, 67092802U, 2609352193U, 3914150340U, 1814842761U,
- 3610830847U, 591531412U, 3880232807U, 1673505890U, 2585326991U,
- 1678544474U, 3148435887U, 3457217359U, 1193226330U, 2816576908U,
- 154025329U, 121678860U, 1164915738U, 973873761U, 269116100U,
- 52087970U, 744015362U, 498556057U, 94298882U, 1563271621U,
- 2383059628U, 4197367290U, 3958472990U, 2592083636U, 2906408439U,
- 1097742433U, 3924840517U, 264557272U, 2292287003U, 3203307984U,
- 4047038857U, 3820609705U, 2333416067U, 1839206046U, 3600944252U,
- 3412254904U, 583538222U, 2390557166U, 4140459427U, 2810357445U,
- 226777499U, 2496151295U, 2207301712U, 3283683112U, 611630281U,
- 1933218215U, 3315610954U, 3889441987U, 3719454256U, 3957190521U,
- 1313998161U, 2365383016U, 3146941060U, 1801206260U, 796124080U,
- 2076248581U, 1747472464U, 3254365145U, 595543130U, 3573909503U,
- 3758250204U, 2020768540U, 2439254210U, 93368951U, 3155792250U,
- 2600232980U, 3709198295U, 3894900440U, 2971850836U, 1578909644U,
- 1443493395U, 2581621665U, 3086506297U, 2443465861U, 558107211U,
- 1519367835U, 249149686U, 908102264U, 2588765675U, 1232743965U,
- 1001330373U, 3561331654U, 2259301289U, 1564977624U, 3835077093U,
- 727244906U, 4255738067U, 1214133513U, 2570786021U, 3899704621U,
- 1633861986U, 1636979509U, 1438500431U, 58463278U, 2823485629U,
- 2297430187U, 2926781924U, 3371352948U, 1864009023U, 2722267973U,
- 1444292075U, 437703973U, 1060414512U, 189705863U, 910018135U,
- 4077357964U, 884213423U, 2644986052U, 3973488374U, 1187906116U,
- 2331207875U, 780463700U, 3713351662U, 3854611290U, 412805574U,
- 2978462572U, 2176222820U, 829424696U, 2790788332U, 2750819108U,
- 1594611657U, 3899878394U, 3032870364U, 1702887682U, 1948167778U,
- 14130042U, 192292500U, 947227076U, 90719497U, 3854230320U,
- 784028434U, 2142399787U, 1563449646U, 2844400217U, 819143172U,
- 2883302356U, 2328055304U, 1328532246U, 2603885363U, 3375188924U,
- 933941291U, 3627039714U, 2129697284U, 2167253953U, 2506905438U,
- 1412424497U, 2981395985U, 1418359660U, 2925902456U, 52752784U,
- 3713667988U, 3924669405U, 648975707U, 1145520213U, 4018650664U,
- 3805915440U, 2380542088U, 2013260958U, 3262572197U, 2465078101U,
- 1114540067U, 3728768081U, 2396958768U, 590672271U, 904818725U,
- 4263660715U, 700754408U, 1042601829U, 4094111823U, 4274838909U,
- 2512692617U, 2774300207U, 2057306915U, 3470942453U, 99333088U,
- 1142661026U, 2889931380U, 14316674U, 2201179167U, 415289459U,
- 448265759U, 3515142743U, 3254903683U, 246633281U, 1184307224U,
- 2418347830U, 2092967314U, 2682072314U, 2558750234U, 2000352263U,
- 1544150531U, 399010405U, 1513946097U, 499682937U, 461167460U,
- 3045570638U, 1633669705U, 851492362U, 4052801922U, 2055266765U,
- 635556996U, 368266356U, 2385737383U, 3218202352U, 2603772408U,
- 349178792U, 226482567U, 3102426060U, 3575998268U, 2103001871U,
- 3243137071U, 225500688U, 1634718593U, 4283311431U, 4292122923U,
- 3842802787U, 811735523U, 105712518U, 663434053U, 1855889273U,
- 2847972595U, 1196355421U, 2552150115U, 4254510614U, 3752181265U,
- 3430721819U, 3828705396U, 3436287905U, 3441964937U, 4123670631U,
- 353001539U, 459496439U, 3799690868U, 1293777660U, 2761079737U,
- 498096339U, 3398433374U, 4080378380U, 2304691596U, 2995729055U,
- 4134660419U, 3903444024U, 3576494993U, 203682175U, 3321164857U,
- 2747963611U, 79749085U, 2992890370U, 1240278549U, 1772175713U,
- 2111331972U, 2655023449U, 1683896345U, 2836027212U, 3482868021U,
- 2489884874U, 756853961U, 2298874501U, 4013448667U, 4143996022U,
- 2948306858U, 4132920035U, 1283299272U, 995592228U, 3450508595U,
- 1027845759U, 1766942720U, 3861411826U, 1446861231U, 95974993U,
- 3502263554U, 1487532194U, 601502472U, 4129619129U, 250131773U,
- 2050079547U, 3198903947U, 3105589778U, 4066481316U, 3026383978U,
- 2276901713U, 365637751U, 2260718426U, 1394775634U, 1791172338U,
- 2690503163U, 2952737846U, 1568710462U, 732623190U, 2980358000U,
- 1053631832U, 1432426951U, 3229149635U, 1854113985U, 3719733532U,
- 3204031934U, 735775531U, 107468620U, 3734611984U, 631009402U,
- 3083622457U, 4109580626U, 159373458U, 1301970201U, 4132389302U,
- 1293255004U, 847182752U, 4170022737U, 96712900U, 2641406755U,
- 1381727755U, 405608287U, 4287919625U, 1703554290U, 3589580244U,
- 2911403488U, 2166565U, 2647306451U, 2330535117U, 1200815358U,
- 1165916754U, 245060911U, 4040679071U, 3684908771U, 2452834126U,
- 2486872773U, 2318678365U, 2940627908U, 1837837240U, 3447897409U,
- 4270484676U, 1495388728U, 3754288477U, 4204167884U, 1386977705U,
- 2692224733U, 3076249689U, 4109568048U, 4170955115U, 4167531356U,
- 4020189950U, 4261855038U, 3036907575U, 3410399885U, 3076395737U,
- 1046178638U, 144496770U, 230725846U, 3349637149U, 17065717U,
- 2809932048U, 2054581785U, 3608424964U, 3259628808U, 134897388U,
- 3743067463U, 257685904U, 3795656590U, 1562468719U, 3589103904U,
- 3120404710U, 254684547U, 2653661580U, 3663904795U, 2631942758U,
- 1063234347U, 2609732900U, 2332080715U, 3521125233U, 1180599599U,
- 1935868586U, 4110970440U, 296706371U, 2128666368U, 1319875791U,
- 1570900197U, 3096025483U, 1799882517U, 1928302007U, 1163707758U,
- 1244491489U, 3533770203U, 567496053U, 2757924305U, 2781639343U,
- 2818420107U, 560404889U, 2619609724U, 4176035430U, 2511289753U,
- 2521842019U, 3910553502U, 2926149387U, 3302078172U, 4237118867U,
- 330725126U, 367400677U, 888239854U, 545570454U, 4259590525U,
- 134343617U, 1102169784U, 1647463719U, 3260979784U, 1518840883U,
- 3631537963U, 3342671457U, 1301549147U, 2083739356U, 146593792U,
- 3217959080U, 652755743U, 2032187193U, 3898758414U, 1021358093U,
- 4037409230U, 2176407931U, 3427391950U, 2883553603U, 985613827U,
- 3105265092U, 3423168427U, 3387507672U, 467170288U, 2141266163U,
- 3723870208U, 916410914U, 1293987799U, 2652584950U, 769160137U,
- 3205292896U, 1561287359U, 1684510084U, 3136055621U, 3765171391U,
- 639683232U, 2639569327U, 1218546948U, 4263586685U, 3058215773U,
- 2352279820U, 401870217U, 2625822463U, 1529125296U, 2981801895U,
- 1191285226U, 4027725437U, 3432700217U, 4098835661U, 971182783U,
- 2443861173U, 3881457123U, 3874386651U, 457276199U, 2638294160U,
- 4002809368U, 421169044U, 1112642589U, 3076213779U, 3387033971U,
- 2499610950U, 3057240914U, 1662679783U, 461224431U, 1168395933U
-};
-static const uint32_t init_by_array_32_expected[] = {
- 2920711183U, 3885745737U, 3501893680U, 856470934U, 1421864068U,
- 277361036U, 1518638004U, 2328404353U, 3355513634U, 64329189U,
- 1624587673U, 3508467182U, 2481792141U, 3706480799U, 1925859037U,
- 2913275699U, 882658412U, 384641219U, 422202002U, 1873384891U,
- 2006084383U, 3924929912U, 1636718106U, 3108838742U, 1245465724U,
- 4195470535U, 779207191U, 1577721373U, 1390469554U, 2928648150U,
- 121399709U, 3170839019U, 4044347501U, 953953814U, 3821710850U,
- 3085591323U, 3666535579U, 3577837737U, 2012008410U, 3565417471U,
- 4044408017U, 433600965U, 1637785608U, 1798509764U, 860770589U,
- 3081466273U, 3982393409U, 2451928325U, 3437124742U, 4093828739U,
- 3357389386U, 2154596123U, 496568176U, 2650035164U, 2472361850U,
- 3438299U, 2150366101U, 1577256676U, 3802546413U, 1787774626U,
- 4078331588U, 3706103141U, 170391138U, 3806085154U, 1680970100U,
- 1961637521U, 3316029766U, 890610272U, 1453751581U, 1430283664U,
- 3051057411U, 3597003186U, 542563954U, 3796490244U, 1690016688U,
- 3448752238U, 440702173U, 347290497U, 1121336647U, 2540588620U,
- 280881896U, 2495136428U, 213707396U, 15104824U, 2946180358U,
- 659000016U, 566379385U, 2614030979U, 2855760170U, 334526548U,
- 2315569495U, 2729518615U, 564745877U, 1263517638U, 3157185798U,
- 1604852056U, 1011639885U, 2950579535U, 2524219188U, 312951012U,
- 1528896652U, 1327861054U, 2846910138U, 3966855905U, 2536721582U,
- 855353911U, 1685434729U, 3303978929U, 1624872055U, 4020329649U,
- 3164802143U, 1642802700U, 1957727869U, 1792352426U, 3334618929U,
- 2631577923U, 3027156164U, 842334259U, 3353446843U, 1226432104U,
- 1742801369U, 3552852535U, 3471698828U, 1653910186U, 3380330939U,
- 2313782701U, 3351007196U, 2129839995U, 1800682418U, 4085884420U,
- 1625156629U, 3669701987U, 615211810U, 3294791649U, 4131143784U,
- 2590843588U, 3207422808U, 3275066464U, 561592872U, 3957205738U,
- 3396578098U, 48410678U, 3505556445U, 1005764855U, 3920606528U,
- 2936980473U, 2378918600U, 2404449845U, 1649515163U, 701203563U,
- 3705256349U, 83714199U, 3586854132U, 922978446U, 2863406304U,
- 3523398907U, 2606864832U, 2385399361U, 3171757816U, 4262841009U,
- 3645837721U, 1169579486U, 3666433897U, 3174689479U, 1457866976U,
- 3803895110U, 3346639145U, 1907224409U, 1978473712U, 1036712794U,
- 980754888U, 1302782359U, 1765252468U, 459245755U, 3728923860U,
- 1512894209U, 2046491914U, 207860527U, 514188684U, 2288713615U,
- 1597354672U, 3349636117U, 2357291114U, 3995796221U, 945364213U,
- 1893326518U, 3770814016U, 1691552714U, 2397527410U, 967486361U,
- 776416472U, 4197661421U, 951150819U, 1852770983U, 4044624181U,
- 1399439738U, 4194455275U, 2284037669U, 1550734958U, 3321078108U,
- 1865235926U, 2912129961U, 2664980877U, 1357572033U, 2600196436U,
- 2486728200U, 2372668724U, 1567316966U, 2374111491U, 1839843570U,
- 20815612U, 3727008608U, 3871996229U, 824061249U, 1932503978U,
- 3404541726U, 758428924U, 2609331364U, 1223966026U, 1299179808U,
- 648499352U, 2180134401U, 880821170U, 3781130950U, 113491270U,
- 1032413764U, 4185884695U, 2490396037U, 1201932817U, 4060951446U,
- 4165586898U, 1629813212U, 2887821158U, 415045333U, 628926856U,
- 2193466079U, 3391843445U, 2227540681U, 1907099846U, 2848448395U,
- 1717828221U, 1372704537U, 1707549841U, 2294058813U, 2101214437U,
- 2052479531U, 1695809164U, 3176587306U, 2632770465U, 81634404U,
- 1603220563U, 644238487U, 302857763U, 897352968U, 2613146653U,
- 1391730149U, 4245717312U, 4191828749U, 1948492526U, 2618174230U,
- 3992984522U, 2178852787U, 3596044509U, 3445573503U, 2026614616U,
- 915763564U, 3415689334U, 2532153403U, 3879661562U, 2215027417U,
- 3111154986U, 2929478371U, 668346391U, 1152241381U, 2632029711U,
- 3004150659U, 2135025926U, 948690501U, 2799119116U, 4228829406U,
- 1981197489U, 4209064138U, 684318751U, 3459397845U, 201790843U,
- 4022541136U, 3043635877U, 492509624U, 3263466772U, 1509148086U,
- 921459029U, 3198857146U, 705479721U, 3835966910U, 3603356465U,
- 576159741U, 1742849431U, 594214882U, 2055294343U, 3634861861U,
- 449571793U, 3246390646U, 3868232151U, 1479156585U, 2900125656U,
- 2464815318U, 3960178104U, 1784261920U, 18311476U, 3627135050U,
- 644609697U, 424968996U, 919890700U, 2986824110U, 816423214U,
- 4003562844U, 1392714305U, 1757384428U, 2569030598U, 995949559U,
- 3875659880U, 2933807823U, 2752536860U, 2993858466U, 4030558899U,
- 2770783427U, 2775406005U, 2777781742U, 1931292655U, 472147933U,
- 3865853827U, 2726470545U, 2668412860U, 2887008249U, 408979190U,
- 3578063323U, 3242082049U, 1778193530U, 27981909U, 2362826515U,
- 389875677U, 1043878156U, 581653903U, 3830568952U, 389535942U,
- 3713523185U, 2768373359U, 2526101582U, 1998618197U, 1160859704U,
- 3951172488U, 1098005003U, 906275699U, 3446228002U, 2220677963U,
- 2059306445U, 132199571U, 476838790U, 1868039399U, 3097344807U,
- 857300945U, 396345050U, 2835919916U, 1782168828U, 1419519470U,
- 4288137521U, 819087232U, 596301494U, 872823172U, 1526888217U,
- 805161465U, 1116186205U, 2829002754U, 2352620120U, 620121516U,
- 354159268U, 3601949785U, 209568138U, 1352371732U, 2145977349U,
- 4236871834U, 1539414078U, 3558126206U, 3224857093U, 4164166682U,
- 3817553440U, 3301780278U, 2682696837U, 3734994768U, 1370950260U,
- 1477421202U, 2521315749U, 1330148125U, 1261554731U, 2769143688U,
- 3554756293U, 4235882678U, 3254686059U, 3530579953U, 1215452615U,
- 3574970923U, 4057131421U, 589224178U, 1000098193U, 171190718U,
- 2521852045U, 2351447494U, 2284441580U, 2646685513U, 3486933563U,
- 3789864960U, 1190528160U, 1702536782U, 1534105589U, 4262946827U,
- 2726686826U, 3584544841U, 2348270128U, 2145092281U, 2502718509U,
- 1027832411U, 3571171153U, 1287361161U, 4011474411U, 3241215351U,
- 2419700818U, 971242709U, 1361975763U, 1096842482U, 3271045537U,
- 81165449U, 612438025U, 3912966678U, 1356929810U, 733545735U,
- 537003843U, 1282953084U, 884458241U, 588930090U, 3930269801U,
- 2961472450U, 1219535534U, 3632251943U, 268183903U, 1441240533U,
- 3653903360U, 3854473319U, 2259087390U, 2548293048U, 2022641195U,
- 2105543911U, 1764085217U, 3246183186U, 482438805U, 888317895U,
- 2628314765U, 2466219854U, 717546004U, 2322237039U, 416725234U,
- 1544049923U, 1797944973U, 3398652364U, 3111909456U, 485742908U,
- 2277491072U, 1056355088U, 3181001278U, 129695079U, 2693624550U,
- 1764438564U, 3797785470U, 195503713U, 3266519725U, 2053389444U,
- 1961527818U, 3400226523U, 3777903038U, 2597274307U, 4235851091U,
- 4094406648U, 2171410785U, 1781151386U, 1378577117U, 654643266U,
- 3424024173U, 3385813322U, 679385799U, 479380913U, 681715441U,
- 3096225905U, 276813409U, 3854398070U, 2721105350U, 831263315U,
- 3276280337U, 2628301522U, 3984868494U, 1466099834U, 2104922114U,
- 1412672743U, 820330404U, 3491501010U, 942735832U, 710652807U,
- 3972652090U, 679881088U, 40577009U, 3705286397U, 2815423480U,
- 3566262429U, 663396513U, 3777887429U, 4016670678U, 404539370U,
- 1142712925U, 1140173408U, 2913248352U, 2872321286U, 263751841U,
- 3175196073U, 3162557581U, 2878996619U, 75498548U, 3836833140U,
- 3284664959U, 1157523805U, 112847376U, 207855609U, 1337979698U,
- 1222578451U, 157107174U, 901174378U, 3883717063U, 1618632639U,
- 1767889440U, 4264698824U, 1582999313U, 884471997U, 2508825098U,
- 3756370771U, 2457213553U, 3565776881U, 3709583214U, 915609601U,
- 460833524U, 1091049576U, 85522880U, 2553251U, 132102809U,
- 2429882442U, 2562084610U, 1386507633U, 4112471229U, 21965213U,
- 1981516006U, 2418435617U, 3054872091U, 4251511224U, 2025783543U,
- 1916911512U, 2454491136U, 3938440891U, 3825869115U, 1121698605U,
- 3463052265U, 802340101U, 1912886800U, 4031997367U, 3550640406U,
- 1596096923U, 610150600U, 431464457U, 2541325046U, 486478003U,
- 739704936U, 2862696430U, 3037903166U, 1129749694U, 2611481261U,
- 1228993498U, 510075548U, 3424962587U, 2458689681U, 818934833U,
- 4233309125U, 1608196251U, 3419476016U, 1858543939U, 2682166524U,
- 3317854285U, 631986188U, 3008214764U, 613826412U, 3567358221U,
- 3512343882U, 1552467474U, 3316162670U, 1275841024U, 4142173454U,
- 565267881U, 768644821U, 198310105U, 2396688616U, 1837659011U,
- 203429334U, 854539004U, 4235811518U, 3338304926U, 3730418692U,
- 3852254981U, 3032046452U, 2329811860U, 2303590566U, 2696092212U,
- 3894665932U, 145835667U, 249563655U, 1932210840U, 2431696407U,
- 3312636759U, 214962629U, 2092026914U, 3020145527U, 4073039873U,
- 2739105705U, 1308336752U, 855104522U, 2391715321U, 67448785U,
- 547989482U, 854411802U, 3608633740U, 431731530U, 537375589U,
- 3888005760U, 696099141U, 397343236U, 1864511780U, 44029739U,
- 1729526891U, 1993398655U, 2010173426U, 2591546756U, 275223291U,
- 1503900299U, 4217765081U, 2185635252U, 1122436015U, 3550155364U,
- 681707194U, 3260479338U, 933579397U, 2983029282U, 2505504587U,
- 2667410393U, 2962684490U, 4139721708U, 2658172284U, 2452602383U,
- 2607631612U, 1344296217U, 3075398709U, 2949785295U, 1049956168U,
- 3917185129U, 2155660174U, 3280524475U, 1503827867U, 674380765U,
- 1918468193U, 3843983676U, 634358221U, 2538335643U, 1873351298U,
- 3368723763U, 2129144130U, 3203528633U, 3087174986U, 2691698871U,
- 2516284287U, 24437745U, 1118381474U, 2816314867U, 2448576035U,
- 4281989654U, 217287825U, 165872888U, 2628995722U, 3533525116U,
- 2721669106U, 872340568U, 3429930655U, 3309047304U, 3916704967U,
- 3270160355U, 1348884255U, 1634797670U, 881214967U, 4259633554U,
- 174613027U, 1103974314U, 1625224232U, 2678368291U, 1133866707U,
- 3853082619U, 4073196549U, 1189620777U, 637238656U, 930241537U,
- 4042750792U, 3842136042U, 2417007212U, 2524907510U, 1243036827U,
- 1282059441U, 3764588774U, 1394459615U, 2323620015U, 1166152231U,
- 3307479609U, 3849322257U, 3507445699U, 4247696636U, 758393720U,
- 967665141U, 1095244571U, 1319812152U, 407678762U, 2640605208U,
- 2170766134U, 3663594275U, 4039329364U, 2512175520U, 725523154U,
- 2249807004U, 3312617979U, 2414634172U, 1278482215U, 349206484U,
- 1573063308U, 1196429124U, 3873264116U, 2400067801U, 268795167U,
- 226175489U, 2961367263U, 1968719665U, 42656370U, 1010790699U,
- 561600615U, 2422453992U, 3082197735U, 1636700484U, 3977715296U,
- 3125350482U, 3478021514U, 2227819446U, 1540868045U, 3061908980U,
- 1087362407U, 3625200291U, 361937537U, 580441897U, 1520043666U,
- 2270875402U, 1009161260U, 2502355842U, 4278769785U, 473902412U,
- 1057239083U, 1905829039U, 1483781177U, 2080011417U, 1207494246U,
- 1806991954U, 2194674403U, 3455972205U, 807207678U, 3655655687U,
- 674112918U, 195425752U, 3917890095U, 1874364234U, 1837892715U,
- 3663478166U, 1548892014U, 2570748714U, 2049929836U, 2167029704U,
- 697543767U, 3499545023U, 3342496315U, 1725251190U, 3561387469U,
- 2905606616U, 1580182447U, 3934525927U, 4103172792U, 1365672522U,
- 1534795737U, 3308667416U, 2841911405U, 3943182730U, 4072020313U,
- 3494770452U, 3332626671U, 55327267U, 478030603U, 411080625U,
- 3419529010U, 1604767823U, 3513468014U, 570668510U, 913790824U,
- 2283967995U, 695159462U, 3825542932U, 4150698144U, 1829758699U,
- 202895590U, 1609122645U, 1267651008U, 2910315509U, 2511475445U,
- 2477423819U, 3932081579U, 900879979U, 2145588390U, 2670007504U,
- 580819444U, 1864996828U, 2526325979U, 1019124258U, 815508628U,
- 2765933989U, 1277301341U, 3006021786U, 855540956U, 288025710U,
- 1919594237U, 2331223864U, 177452412U, 2475870369U, 2689291749U,
- 865194284U, 253432152U, 2628531804U, 2861208555U, 2361597573U,
- 1653952120U, 1039661024U, 2159959078U, 3709040440U, 3564718533U,
- 2596878672U, 2041442161U, 31164696U, 2662962485U, 3665637339U,
- 1678115244U, 2699839832U, 3651968520U, 3521595541U, 458433303U,
- 2423096824U, 21831741U, 380011703U, 2498168716U, 861806087U,
- 1673574843U, 4188794405U, 2520563651U, 2632279153U, 2170465525U,
- 4171949898U, 3886039621U, 1661344005U, 3424285243U, 992588372U,
- 2500984144U, 2993248497U, 3590193895U, 1535327365U, 515645636U,
- 131633450U, 3729760261U, 1613045101U, 3254194278U, 15889678U,
- 1493590689U, 244148718U, 2991472662U, 1401629333U, 777349878U,
- 2501401703U, 4285518317U, 3794656178U, 955526526U, 3442142820U,
- 3970298374U, 736025417U, 2737370764U, 1271509744U, 440570731U,
- 136141826U, 1596189518U, 923399175U, 257541519U, 3505774281U,
- 2194358432U, 2518162991U, 1379893637U, 2667767062U, 3748146247U,
- 1821712620U, 3923161384U, 1947811444U, 2392527197U, 4127419685U,
- 1423694998U, 4156576871U, 1382885582U, 3420127279U, 3617499534U,
- 2994377493U, 4038063986U, 1918458672U, 2983166794U, 4200449033U,
- 353294540U, 1609232588U, 243926648U, 2332803291U, 507996832U,
- 2392838793U, 4075145196U, 2060984340U, 4287475136U, 88232602U,
- 2491531140U, 4159725633U, 2272075455U, 759298618U, 201384554U,
- 838356250U, 1416268324U, 674476934U, 90795364U, 141672229U,
- 3660399588U, 4196417251U, 3249270244U, 3774530247U, 59587265U,
- 3683164208U, 19392575U, 1463123697U, 1882205379U, 293780489U,
- 2553160622U, 2933904694U, 675638239U, 2851336944U, 1435238743U,
- 2448730183U, 804436302U, 2119845972U, 322560608U, 4097732704U,
- 2987802540U, 641492617U, 2575442710U, 4217822703U, 3271835300U,
- 2836418300U, 3739921620U, 2138378768U, 2879771855U, 4294903423U,
- 3121097946U, 2603440486U, 2560820391U, 1012930944U, 2313499967U,
- 584489368U, 3431165766U, 897384869U, 2062537737U, 2847889234U,
- 3742362450U, 2951174585U, 4204621084U, 1109373893U, 3668075775U,
- 2750138839U, 3518055702U, 733072558U, 4169325400U, 788493625U
-};
-static const uint64_t init_gen_rand_64_expected[] = {
- KQU(16924766246869039260), KQU( 8201438687333352714),
- KQU( 2265290287015001750), KQU(18397264611805473832),
- KQU( 3375255223302384358), KQU( 6345559975416828796),
- KQU(18229739242790328073), KQU( 7596792742098800905),
- KQU( 255338647169685981), KQU( 2052747240048610300),
- KQU(18328151576097299343), KQU(12472905421133796567),
- KQU(11315245349717600863), KQU(16594110197775871209),
- KQU(15708751964632456450), KQU(10452031272054632535),
- KQU(11097646720811454386), KQU( 4556090668445745441),
- KQU(17116187693090663106), KQU(14931526836144510645),
- KQU( 9190752218020552591), KQU( 9625800285771901401),
- KQU(13995141077659972832), KQU( 5194209094927829625),
- KQU( 4156788379151063303), KQU( 8523452593770139494),
- KQU(14082382103049296727), KQU( 2462601863986088483),
- KQU( 3030583461592840678), KQU( 5221622077872827681),
- KQU( 3084210671228981236), KQU(13956758381389953823),
- KQU(13503889856213423831), KQU(15696904024189836170),
- KQU( 4612584152877036206), KQU( 6231135538447867881),
- KQU(10172457294158869468), KQU( 6452258628466708150),
- KQU(14044432824917330221), KQU( 370168364480044279),
- KQU(10102144686427193359), KQU( 667870489994776076),
- KQU( 2732271956925885858), KQU(18027788905977284151),
- KQU(15009842788582923859), KQU( 7136357960180199542),
- KQU(15901736243475578127), KQU(16951293785352615701),
- KQU(10551492125243691632), KQU(17668869969146434804),
- KQU(13646002971174390445), KQU( 9804471050759613248),
- KQU( 5511670439655935493), KQU(18103342091070400926),
- KQU(17224512747665137533), KQU(15534627482992618168),
- KQU( 1423813266186582647), KQU(15821176807932930024),
- KQU( 30323369733607156), KQU(11599382494723479403),
- KQU( 653856076586810062), KQU( 3176437395144899659),
- KQU(14028076268147963917), KQU(16156398271809666195),
- KQU( 3166955484848201676), KQU( 5746805620136919390),
- KQU(17297845208891256593), KQU(11691653183226428483),
- KQU(17900026146506981577), KQU(15387382115755971042),
- KQU(16923567681040845943), KQU( 8039057517199388606),
- KQU(11748409241468629263), KQU( 794358245539076095),
- KQU(13438501964693401242), KQU(14036803236515618962),
- KQU( 5252311215205424721), KQU(17806589612915509081),
- KQU( 6802767092397596006), KQU(14212120431184557140),
- KQU( 1072951366761385712), KQU(13098491780722836296),
- KQU( 9466676828710797353), KQU(12673056849042830081),
- KQU(12763726623645357580), KQU(16468961652999309493),
- KQU(15305979875636438926), KQU(17444713151223449734),
- KQU( 5692214267627883674), KQU(13049589139196151505),
- KQU( 880115207831670745), KQU( 1776529075789695498),
- KQU(16695225897801466485), KQU(10666901778795346845),
- KQU( 6164389346722833869), KQU( 2863817793264300475),
- KQU( 9464049921886304754), KQU( 3993566636740015468),
- KQU( 9983749692528514136), KQU(16375286075057755211),
- KQU(16042643417005440820), KQU(11445419662923489877),
- KQU( 7999038846885158836), KQU( 6721913661721511535),
- KQU( 5363052654139357320), KQU( 1817788761173584205),
- KQU(13290974386445856444), KQU( 4650350818937984680),
- KQU( 8219183528102484836), KQU( 1569862923500819899),
- KQU( 4189359732136641860), KQU(14202822961683148583),
- KQU( 4457498315309429058), KQU(13089067387019074834),
- KQU(11075517153328927293), KQU(10277016248336668389),
- KQU( 7070509725324401122), KQU(17808892017780289380),
- KQU(13143367339909287349), KQU( 1377743745360085151),
- KQU( 5749341807421286485), KQU(14832814616770931325),
- KQU( 7688820635324359492), KQU(10960474011539770045),
- KQU( 81970066653179790), KQU(12619476072607878022),
- KQU( 4419566616271201744), KQU(15147917311750568503),
- KQU( 5549739182852706345), KQU( 7308198397975204770),
- KQU(13580425496671289278), KQU(17070764785210130301),
- KQU( 8202832846285604405), KQU( 6873046287640887249),
- KQU( 6927424434308206114), KQU( 6139014645937224874),
- KQU(10290373645978487639), KQU(15904261291701523804),
- KQU( 9628743442057826883), KQU(18383429096255546714),
- KQU( 4977413265753686967), KQU( 7714317492425012869),
- KQU( 9025232586309926193), KQU(14627338359776709107),
- KQU(14759849896467790763), KQU(10931129435864423252),
- KQU( 4588456988775014359), KQU(10699388531797056724),
- KQU( 468652268869238792), KQU( 5755943035328078086),
- KQU( 2102437379988580216), KQU( 9986312786506674028),
- KQU( 2654207180040945604), KQU( 8726634790559960062),
- KQU( 100497234871808137), KQU( 2800137176951425819),
- KQU( 6076627612918553487), KQU( 5780186919186152796),
- KQU( 8179183595769929098), KQU( 6009426283716221169),
- KQU( 2796662551397449358), KQU( 1756961367041986764),
- KQU( 6972897917355606205), KQU(14524774345368968243),
- KQU( 2773529684745706940), KQU( 4853632376213075959),
- KQU( 4198177923731358102), KQU( 8271224913084139776),
- KQU( 2741753121611092226), KQU(16782366145996731181),
- KQU(15426125238972640790), KQU(13595497100671260342),
- KQU( 3173531022836259898), KQU( 6573264560319511662),
- KQU(18041111951511157441), KQU( 2351433581833135952),
- KQU( 3113255578908173487), KQU( 1739371330877858784),
- KQU(16046126562789165480), KQU( 8072101652214192925),
- KQU(15267091584090664910), KQU( 9309579200403648940),
- KQU( 5218892439752408722), KQU(14492477246004337115),
- KQU(17431037586679770619), KQU( 7385248135963250480),
- KQU( 9580144956565560660), KQU( 4919546228040008720),
- KQU(15261542469145035584), KQU(18233297270822253102),
- KQU( 5453248417992302857), KQU( 9309519155931460285),
- KQU(10342813012345291756), KQU(15676085186784762381),
- KQU(15912092950691300645), KQU( 9371053121499003195),
- KQU( 9897186478226866746), KQU(14061858287188196327),
- KQU( 122575971620788119), KQU(12146750969116317754),
- KQU( 4438317272813245201), KQU( 8332576791009527119),
- KQU(13907785691786542057), KQU(10374194887283287467),
- KQU( 2098798755649059566), KQU( 3416235197748288894),
- KQU( 8688269957320773484), KQU( 7503964602397371571),
- KQU(16724977015147478236), KQU( 9461512855439858184),
- KQU(13259049744534534727), KQU( 3583094952542899294),
- KQU( 8764245731305528292), KQU(13240823595462088985),
- KQU(13716141617617910448), KQU(18114969519935960955),
- KQU( 2297553615798302206), KQU( 4585521442944663362),
- KQU(17776858680630198686), KQU( 4685873229192163363),
- KQU( 152558080671135627), KQU(15424900540842670088),
- KQU(13229630297130024108), KQU(17530268788245718717),
- KQU(16675633913065714144), KQU( 3158912717897568068),
- KQU(15399132185380087288), KQU( 7401418744515677872),
- KQU(13135412922344398535), KQU( 6385314346100509511),
- KQU(13962867001134161139), KQU(10272780155442671999),
- KQU(12894856086597769142), KQU(13340877795287554994),
- KQU(12913630602094607396), KQU(12543167911119793857),
- KQU(17343570372251873096), KQU(10959487764494150545),
- KQU( 6966737953093821128), KQU(13780699135496988601),
- KQU( 4405070719380142046), KQU(14923788365607284982),
- KQU( 2869487678905148380), KQU( 6416272754197188403),
- KQU(15017380475943612591), KQU( 1995636220918429487),
- KQU( 3402016804620122716), KQU(15800188663407057080),
- KQU(11362369990390932882), KQU(15262183501637986147),
- KQU(10239175385387371494), KQU( 9352042420365748334),
- KQU( 1682457034285119875), KQU( 1724710651376289644),
- KQU( 2038157098893817966), KQU( 9897825558324608773),
- KQU( 1477666236519164736), KQU(16835397314511233640),
- KQU(10370866327005346508), KQU(10157504370660621982),
- KQU(12113904045335882069), KQU(13326444439742783008),
- KQU(11302769043000765804), KQU(13594979923955228484),
- KQU(11779351762613475968), KQU( 3786101619539298383),
- KQU( 8021122969180846063), KQU(15745904401162500495),
- KQU(10762168465993897267), KQU(13552058957896319026),
- KQU(11200228655252462013), KQU( 5035370357337441226),
- KQU( 7593918984545500013), KQU( 5418554918361528700),
- KQU( 4858270799405446371), KQU( 9974659566876282544),
- KQU(18227595922273957859), KQU( 2772778443635656220),
- KQU(14285143053182085385), KQU( 9939700992429600469),
- KQU(12756185904545598068), KQU( 2020783375367345262),
- KQU( 57026775058331227), KQU( 950827867930065454),
- KQU( 6602279670145371217), KQU( 2291171535443566929),
- KQU( 5832380724425010313), KQU( 1220343904715982285),
- KQU(17045542598598037633), KQU(15460481779702820971),
- KQU(13948388779949365130), KQU(13975040175430829518),
- KQU(17477538238425541763), KQU(11104663041851745725),
- KQU(15860992957141157587), KQU(14529434633012950138),
- KQU( 2504838019075394203), KQU( 7512113882611121886),
- KQU( 4859973559980886617), KQU( 1258601555703250219),
- KQU(15594548157514316394), KQU( 4516730171963773048),
- KQU(11380103193905031983), KQU( 6809282239982353344),
- KQU(18045256930420065002), KQU( 2453702683108791859),
- KQU( 977214582986981460), KQU( 2006410402232713466),
- KQU( 6192236267216378358), KQU( 3429468402195675253),
- KQU(18146933153017348921), KQU(17369978576367231139),
- KQU( 1246940717230386603), KQU(11335758870083327110),
- KQU(14166488801730353682), KQU( 9008573127269635732),
- KQU(10776025389820643815), KQU(15087605441903942962),
- KQU( 1359542462712147922), KQU(13898874411226454206),
- KQU(17911176066536804411), KQU( 9435590428600085274),
- KQU( 294488509967864007), KQU( 8890111397567922046),
- KQU( 7987823476034328778), KQU(13263827582440967651),
- KQU( 7503774813106751573), KQU(14974747296185646837),
- KQU( 8504765037032103375), KQU(17340303357444536213),
- KQU( 7704610912964485743), KQU( 8107533670327205061),
- KQU( 9062969835083315985), KQU(16968963142126734184),
- KQU(12958041214190810180), KQU( 2720170147759570200),
- KQU( 2986358963942189566), KQU(14884226322219356580),
- KQU( 286224325144368520), KQU(11313800433154279797),
- KQU(18366849528439673248), KQU(17899725929482368789),
- KQU( 3730004284609106799), KQU( 1654474302052767205),
- KQU( 5006698007047077032), KQU( 8196893913601182838),
- KQU(15214541774425211640), KQU(17391346045606626073),
- KQU( 8369003584076969089), KQU( 3939046733368550293),
- KQU(10178639720308707785), KQU( 2180248669304388697),
- KQU( 62894391300126322), KQU( 9205708961736223191),
- KQU( 6837431058165360438), KQU( 3150743890848308214),
- KQU(17849330658111464583), KQU(12214815643135450865),
- KQU(13410713840519603402), KQU( 3200778126692046802),
- KQU(13354780043041779313), KQU( 800850022756886036),
- KQU(15660052933953067433), KQU( 6572823544154375676),
- KQU(11030281857015819266), KQU(12682241941471433835),
- KQU(11654136407300274693), KQU( 4517795492388641109),
- KQU( 9757017371504524244), KQU(17833043400781889277),
- KQU(12685085201747792227), KQU(10408057728835019573),
- KQU( 98370418513455221), KQU( 6732663555696848598),
- KQU(13248530959948529780), KQU( 3530441401230622826),
- KQU(18188251992895660615), KQU( 1847918354186383756),
- KQU( 1127392190402660921), KQU(11293734643143819463),
- KQU( 3015506344578682982), KQU(13852645444071153329),
- KQU( 2121359659091349142), KQU( 1294604376116677694),
- KQU( 5616576231286352318), KQU( 7112502442954235625),
- KQU(11676228199551561689), KQU(12925182803007305359),
- KQU( 7852375518160493082), KQU( 1136513130539296154),
- KQU( 5636923900916593195), KQU( 3221077517612607747),
- KQU(17784790465798152513), KQU( 3554210049056995938),
- KQU(17476839685878225874), KQU( 3206836372585575732),
- KQU( 2765333945644823430), KQU(10080070903718799528),
- KQU( 5412370818878286353), KQU( 9689685887726257728),
- KQU( 8236117509123533998), KQU( 1951139137165040214),
- KQU( 4492205209227980349), KQU(16541291230861602967),
- KQU( 1424371548301437940), KQU( 9117562079669206794),
- KQU(14374681563251691625), KQU(13873164030199921303),
- KQU( 6680317946770936731), KQU(15586334026918276214),
- KQU(10896213950976109802), KQU( 9506261949596413689),
- KQU( 9903949574308040616), KQU( 6038397344557204470),
- KQU( 174601465422373648), KQU(15946141191338238030),
- KQU(17142225620992044937), KQU( 7552030283784477064),
- KQU( 2947372384532947997), KQU( 510797021688197711),
- KQU( 4962499439249363461), KQU( 23770320158385357),
- KQU( 959774499105138124), KQU( 1468396011518788276),
- KQU( 2015698006852312308), KQU( 4149400718489980136),
- KQU( 5992916099522371188), KQU(10819182935265531076),
- KQU(16189787999192351131), KQU( 342833961790261950),
- KQU(12470830319550495336), KQU(18128495041912812501),
- KQU( 1193600899723524337), KQU( 9056793666590079770),
- KQU( 2154021227041669041), KQU( 4963570213951235735),
- KQU( 4865075960209211409), KQU( 2097724599039942963),
- KQU( 2024080278583179845), KQU(11527054549196576736),
- KQU(10650256084182390252), KQU( 4808408648695766755),
- KQU( 1642839215013788844), KQU(10607187948250398390),
- KQU( 7076868166085913508), KQU( 730522571106887032),
- KQU(12500579240208524895), KQU( 4484390097311355324),
- KQU(15145801330700623870), KQU( 8055827661392944028),
- KQU( 5865092976832712268), KQU(15159212508053625143),
- KQU( 3560964582876483341), KQU( 4070052741344438280),
- KQU( 6032585709886855634), KQU(15643262320904604873),
- KQU( 2565119772293371111), KQU( 318314293065348260),
- KQU(15047458749141511872), KQU( 7772788389811528730),
- KQU( 7081187494343801976), KQU( 6465136009467253947),
- KQU(10425940692543362069), KQU( 554608190318339115),
- KQU(14796699860302125214), KQU( 1638153134431111443),
- KQU(10336967447052276248), KQU( 8412308070396592958),
- KQU( 4004557277152051226), KQU( 8143598997278774834),
- KQU(16413323996508783221), KQU(13139418758033994949),
- KQU( 9772709138335006667), KQU( 2818167159287157659),
- KQU(17091740573832523669), KQU(14629199013130751608),
- KQU(18268322711500338185), KQU( 8290963415675493063),
- KQU( 8830864907452542588), KQU( 1614839084637494849),
- KQU(14855358500870422231), KQU( 3472996748392519937),
- KQU(15317151166268877716), KQU( 5825895018698400362),
- KQU(16730208429367544129), KQU(10481156578141202800),
- KQU( 4746166512382823750), KQU(12720876014472464998),
- KQU( 8825177124486735972), KQU(13733447296837467838),
- KQU( 6412293741681359625), KQU( 8313213138756135033),
- KQU(11421481194803712517), KQU( 7997007691544174032),
- KQU( 6812963847917605930), KQU( 9683091901227558641),
- KQU(14703594165860324713), KQU( 1775476144519618309),
- KQU( 2724283288516469519), KQU( 717642555185856868),
- KQU( 8736402192215092346), KQU(11878800336431381021),
- KQU( 4348816066017061293), KQU( 6115112756583631307),
- KQU( 9176597239667142976), KQU(12615622714894259204),
- KQU(10283406711301385987), KQU( 5111762509485379420),
- KQU( 3118290051198688449), KQU( 7345123071632232145),
- KQU( 9176423451688682359), KQU( 4843865456157868971),
- KQU(12008036363752566088), KQU(12058837181919397720),
- KQU( 2145073958457347366), KQU( 1526504881672818067),
- KQU( 3488830105567134848), KQU(13208362960674805143),
- KQU( 4077549672899572192), KQU( 7770995684693818365),
- KQU( 1398532341546313593), KQU(12711859908703927840),
- KQU( 1417561172594446813), KQU(17045191024194170604),
- KQU( 4101933177604931713), KQU(14708428834203480320),
- KQU(17447509264469407724), KQU(14314821973983434255),
- KQU(17990472271061617265), KQU( 5087756685841673942),
- KQU(12797820586893859939), KQU( 1778128952671092879),
- KQU( 3535918530508665898), KQU( 9035729701042481301),
- KQU(14808661568277079962), KQU(14587345077537747914),
- KQU(11920080002323122708), KQU( 6426515805197278753),
- KQU( 3295612216725984831), KQU(11040722532100876120),
- KQU(12305952936387598754), KQU(16097391899742004253),
- KQU( 4908537335606182208), KQU(12446674552196795504),
- KQU(16010497855816895177), KQU( 9194378874788615551),
- KQU( 3382957529567613384), KQU( 5154647600754974077),
- KQU( 9801822865328396141), KQU( 9023662173919288143),
- KQU(17623115353825147868), KQU( 8238115767443015816),
- KQU(15811444159859002560), KQU( 9085612528904059661),
- KQU( 6888601089398614254), KQU( 258252992894160189),
- KQU( 6704363880792428622), KQU( 6114966032147235763),
- KQU(11075393882690261875), KQU( 8797664238933620407),
- KQU( 5901892006476726920), KQU( 5309780159285518958),
- KQU(14940808387240817367), KQU(14642032021449656698),
- KQU( 9808256672068504139), KQU( 3670135111380607658),
- KQU(11211211097845960152), KQU( 1474304506716695808),
- KQU(15843166204506876239), KQU( 7661051252471780561),
- KQU(10170905502249418476), KQU( 7801416045582028589),
- KQU( 2763981484737053050), KQU( 9491377905499253054),
- KQU(16201395896336915095), KQU( 9256513756442782198),
- KQU( 5411283157972456034), KQU( 5059433122288321676),
- KQU( 4327408006721123357), KQU( 9278544078834433377),
- KQU( 7601527110882281612), KQU(11848295896975505251),
- KQU(12096998801094735560), KQU(14773480339823506413),
- KQU(15586227433895802149), KQU(12786541257830242872),
- KQU( 6904692985140503067), KQU( 5309011515263103959),
- KQU(12105257191179371066), KQU(14654380212442225037),
- KQU( 2556774974190695009), KQU( 4461297399927600261),
- KQU(14888225660915118646), KQU(14915459341148291824),
- KQU( 2738802166252327631), KQU( 6047155789239131512),
- KQU(12920545353217010338), KQU(10697617257007840205),
- KQU( 2751585253158203504), KQU(13252729159780047496),
- KQU(14700326134672815469), KQU(14082527904374600529),
- KQU(16852962273496542070), KQU(17446675504235853907),
- KQU(15019600398527572311), KQU(12312781346344081551),
- KQU(14524667935039810450), KQU( 5634005663377195738),
- KQU(11375574739525000569), KQU( 2423665396433260040),
- KQU( 5222836914796015410), KQU( 4397666386492647387),
- KQU( 4619294441691707638), KQU( 665088602354770716),
- KQU(13246495665281593610), KQU( 6564144270549729409),
- KQU(10223216188145661688), KQU( 3961556907299230585),
- KQU(11543262515492439914), KQU(16118031437285993790),
- KQU( 7143417964520166465), KQU(13295053515909486772),
- KQU( 40434666004899675), KQU(17127804194038347164),
- KQU( 8599165966560586269), KQU( 8214016749011284903),
- KQU(13725130352140465239), KQU( 5467254474431726291),
- KQU( 7748584297438219877), KQU(16933551114829772472),
- KQU( 2169618439506799400), KQU( 2169787627665113463),
- KQU(17314493571267943764), KQU(18053575102911354912),
- KQU(11928303275378476973), KQU(11593850925061715550),
- KQU(17782269923473589362), KQU( 3280235307704747039),
- KQU( 6145343578598685149), KQU(17080117031114086090),
- KQU(18066839902983594755), KQU( 6517508430331020706),
- KQU( 8092908893950411541), KQU(12558378233386153732),
- KQU( 4476532167973132976), KQU(16081642430367025016),
- KQU( 4233154094369139361), KQU( 8693630486693161027),
- KQU(11244959343027742285), KQU(12273503967768513508),
- KQU(14108978636385284876), KQU( 7242414665378826984),
- KQU( 6561316938846562432), KQU( 8601038474994665795),
- KQU(17532942353612365904), KQU(17940076637020912186),
- KQU( 7340260368823171304), KQU( 7061807613916067905),
- KQU(10561734935039519326), KQU(17990796503724650862),
- KQU( 6208732943911827159), KQU( 359077562804090617),
- KQU(14177751537784403113), KQU(10659599444915362902),
- KQU(15081727220615085833), KQU(13417573895659757486),
- KQU(15513842342017811524), KQU(11814141516204288231),
- KQU( 1827312513875101814), KQU( 2804611699894603103),
- KQU(17116500469975602763), KQU(12270191815211952087),
- KQU(12256358467786024988), KQU(18435021722453971267),
- KQU( 671330264390865618), KQU( 476504300460286050),
- KQU(16465470901027093441), KQU( 4047724406247136402),
- KQU( 1322305451411883346), KQU( 1388308688834322280),
- KQU( 7303989085269758176), KQU( 9323792664765233642),
- KQU( 4542762575316368936), KQU(17342696132794337618),
- KQU( 4588025054768498379), KQU(13415475057390330804),
- KQU(17880279491733405570), KQU(10610553400618620353),
- KQU( 3180842072658960139), KQU(13002966655454270120),
- KQU( 1665301181064982826), KQU( 7083673946791258979),
- KQU( 190522247122496820), KQU(17388280237250677740),
- KQU( 8430770379923642945), KQU(12987180971921668584),
- KQU( 2311086108365390642), KQU( 2870984383579822345),
- KQU(14014682609164653318), KQU(14467187293062251484),
- KQU( 192186361147413298), KQU(15171951713531796524),
- KQU( 9900305495015948728), KQU(17958004775615466344),
- KQU(14346380954498606514), KQU(18040047357617407096),
- KQU( 5035237584833424532), KQU(15089555460613972287),
- KQU( 4131411873749729831), KQU( 1329013581168250330),
- KQU(10095353333051193949), KQU(10749518561022462716),
- KQU( 9050611429810755847), KQU(15022028840236655649),
- KQU( 8775554279239748298), KQU(13105754025489230502),
- KQU(15471300118574167585), KQU( 89864764002355628),
- KQU( 8776416323420466637), KQU( 5280258630612040891),
- KQU( 2719174488591862912), KQU( 7599309137399661994),
- KQU(15012887256778039979), KQU(14062981725630928925),
- KQU(12038536286991689603), KQU( 7089756544681775245),
- KQU(10376661532744718039), KQU( 1265198725901533130),
- KQU(13807996727081142408), KQU( 2935019626765036403),
- KQU( 7651672460680700141), KQU( 3644093016200370795),
- KQU( 2840982578090080674), KQU(17956262740157449201),
- KQU(18267979450492880548), KQU(11799503659796848070),
- KQU( 9942537025669672388), KQU(11886606816406990297),
- KQU( 5488594946437447576), KQU( 7226714353282744302),
- KQU( 3784851653123877043), KQU( 878018453244803041),
- KQU(12110022586268616085), KQU( 734072179404675123),
- KQU(11869573627998248542), KQU( 469150421297783998),
- KQU( 260151124912803804), KQU(11639179410120968649),
- KQU( 9318165193840846253), KQU(12795671722734758075),
- KQU(15318410297267253933), KQU( 691524703570062620),
- KQU( 5837129010576994601), KQU(15045963859726941052),
- KQU( 5850056944932238169), KQU(12017434144750943807),
- KQU( 7447139064928956574), KQU( 3101711812658245019),
- KQU(16052940704474982954), KQU(18195745945986994042),
- KQU( 8932252132785575659), KQU(13390817488106794834),
- KQU(11582771836502517453), KQU( 4964411326683611686),
- KQU( 2195093981702694011), KQU(14145229538389675669),
- KQU(16459605532062271798), KQU( 866316924816482864),
- KQU( 4593041209937286377), KQU( 8415491391910972138),
- KQU( 4171236715600528969), KQU(16637569303336782889),
- KQU( 2002011073439212680), KQU(17695124661097601411),
- KQU( 4627687053598611702), KQU( 7895831936020190403),
- KQU( 8455951300917267802), KQU( 2923861649108534854),
- KQU( 8344557563927786255), KQU( 6408671940373352556),
- KQU(12210227354536675772), KQU(14294804157294222295),
- KQU(10103022425071085127), KQU(10092959489504123771),
- KQU( 6554774405376736268), KQU(12629917718410641774),
- KQU( 6260933257596067126), KQU( 2460827021439369673),
- KQU( 2541962996717103668), KQU( 597377203127351475),
- KQU( 5316984203117315309), KQU( 4811211393563241961),
- KQU(13119698597255811641), KQU( 8048691512862388981),
- KQU(10216818971194073842), KQU( 4612229970165291764),
- KQU(10000980798419974770), KQU( 6877640812402540687),
- KQU( 1488727563290436992), KQU( 2227774069895697318),
- KQU(11237754507523316593), KQU(13478948605382290972),
- KQU( 1963583846976858124), KQU( 5512309205269276457),
- KQU( 3972770164717652347), KQU( 3841751276198975037),
- KQU(10283343042181903117), KQU( 8564001259792872199),
- KQU(16472187244722489221), KQU( 8953493499268945921),
- KQU( 3518747340357279580), KQU( 4003157546223963073),
- KQU( 3270305958289814590), KQU( 3966704458129482496),
- KQU( 8122141865926661939), KQU(14627734748099506653),
- KQU(13064426990862560568), KQU( 2414079187889870829),
- KQU( 5378461209354225306), KQU(10841985740128255566),
- KQU( 538582442885401738), KQU( 7535089183482905946),
- KQU(16117559957598879095), KQU( 8477890721414539741),
- KQU( 1459127491209533386), KQU(17035126360733620462),
- KQU( 8517668552872379126), KQU(10292151468337355014),
- KQU(17081267732745344157), KQU(13751455337946087178),
- KQU(14026945459523832966), KQU( 6653278775061723516),
- KQU(10619085543856390441), KQU( 2196343631481122885),
- KQU(10045966074702826136), KQU(10082317330452718282),
- KQU( 5920859259504831242), KQU( 9951879073426540617),
- KQU( 7074696649151414158), KQU(15808193543879464318),
- KQU( 7385247772746953374), KQU( 3192003544283864292),
- KQU(18153684490917593847), KQU(12423498260668568905),
- KQU(10957758099756378169), KQU(11488762179911016040),
- KQU( 2099931186465333782), KQU(11180979581250294432),
- KQU( 8098916250668367933), KQU( 3529200436790763465),
- KQU(12988418908674681745), KQU( 6147567275954808580),
- KQU( 3207503344604030989), KQU(10761592604898615360),
- KQU( 229854861031893504), KQU( 8809853962667144291),
- KQU(13957364469005693860), KQU( 7634287665224495886),
- KQU(12353487366976556874), KQU( 1134423796317152034),
- KQU( 2088992471334107068), KQU( 7393372127190799698),
- KQU( 1845367839871058391), KQU( 207922563987322884),
- KQU(11960870813159944976), KQU(12182120053317317363),
- KQU(17307358132571709283), KQU(13871081155552824936),
- KQU(18304446751741566262), KQU( 7178705220184302849),
- KQU(10929605677758824425), KQU(16446976977835806844),
- KQU(13723874412159769044), KQU( 6942854352100915216),
- KQU( 1726308474365729390), KQU( 2150078766445323155),
- KQU(15345558947919656626), KQU(12145453828874527201),
- KQU( 2054448620739726849), KQU( 2740102003352628137),
- KQU(11294462163577610655), KQU( 756164283387413743),
- KQU(17841144758438810880), KQU(10802406021185415861),
- KQU( 8716455530476737846), KQU( 6321788834517649606),
- KQU(14681322910577468426), KQU(17330043563884336387),
- KQU(12701802180050071614), KQU(14695105111079727151),
- KQU( 5112098511654172830), KQU( 4957505496794139973),
- KQU( 8270979451952045982), KQU(12307685939199120969),
- KQU(12425799408953443032), KQU( 8376410143634796588),
- KQU(16621778679680060464), KQU( 3580497854566660073),
- KQU( 1122515747803382416), KQU( 857664980960597599),
- KQU( 6343640119895925918), KQU(12878473260854462891),
- KQU(10036813920765722626), KQU(14451335468363173812),
- KQU( 5476809692401102807), KQU(16442255173514366342),
- KQU(13060203194757167104), KQU(14354124071243177715),
- KQU(15961249405696125227), KQU(13703893649690872584),
- KQU( 363907326340340064), KQU( 6247455540491754842),
- KQU(12242249332757832361), KQU( 156065475679796717),
- KQU( 9351116235749732355), KQU( 4590350628677701405),
- KQU( 1671195940982350389), KQU(13501398458898451905),
- KQU( 6526341991225002255), KQU( 1689782913778157592),
- KQU( 7439222350869010334), KQU(13975150263226478308),
- KQU(11411961169932682710), KQU(17204271834833847277),
- KQU( 541534742544435367), KQU( 6591191931218949684),
- KQU( 2645454775478232486), KQU( 4322857481256485321),
- KQU( 8477416487553065110), KQU(12902505428548435048),
- KQU( 971445777981341415), KQU(14995104682744976712),
- KQU( 4243341648807158063), KQU( 8695061252721927661),
- KQU( 5028202003270177222), KQU( 2289257340915567840),
- KQU(13870416345121866007), KQU(13994481698072092233),
- KQU( 6912785400753196481), KQU( 2278309315841980139),
- KQU( 4329765449648304839), KQU( 5963108095785485298),
- KQU( 4880024847478722478), KQU(16015608779890240947),
- KQU( 1866679034261393544), KQU( 914821179919731519),
- KQU( 9643404035648760131), KQU( 2418114953615593915),
- KQU( 944756836073702374), KQU(15186388048737296834),
- KQU( 7723355336128442206), KQU( 7500747479679599691),
- KQU(18013961306453293634), KQU( 2315274808095756456),
- KQU(13655308255424029566), KQU(17203800273561677098),
- KQU( 1382158694422087756), KQU( 5090390250309588976),
- KQU( 517170818384213989), KQU( 1612709252627729621),
- KQU( 1330118955572449606), KQU( 300922478056709885),
- KQU(18115693291289091987), KQU(13491407109725238321),
- KQU(15293714633593827320), KQU( 5151539373053314504),
- KQU( 5951523243743139207), KQU(14459112015249527975),
- KQU( 5456113959000700739), KQU( 3877918438464873016),
- KQU(12534071654260163555), KQU(15871678376893555041),
- KQU(11005484805712025549), KQU(16353066973143374252),
- KQU( 4358331472063256685), KQU( 8268349332210859288),
- KQU(12485161590939658075), KQU(13955993592854471343),
- KQU( 5911446886848367039), KQU(14925834086813706974),
- KQU( 6590362597857994805), KQU( 1280544923533661875),
- KQU( 1637756018947988164), KQU( 4734090064512686329),
- KQU(16693705263131485912), KQU( 6834882340494360958),
- KQU( 8120732176159658505), KQU( 2244371958905329346),
- KQU(10447499707729734021), KQU( 7318742361446942194),
- KQU( 8032857516355555296), KQU(14023605983059313116),
- KQU( 1032336061815461376), KQU( 9840995337876562612),
- KQU( 9869256223029203587), KQU(12227975697177267636),
- KQU(12728115115844186033), KQU( 7752058479783205470),
- KQU( 729733219713393087), KQU(12954017801239007622)
-};
-static const uint64_t init_by_array_64_expected[] = {
- KQU( 2100341266307895239), KQU( 8344256300489757943),
- KQU(15687933285484243894), KQU( 8268620370277076319),
- KQU(12371852309826545459), KQU( 8800491541730110238),
- KQU(18113268950100835773), KQU( 2886823658884438119),
- KQU( 3293667307248180724), KQU( 9307928143300172731),
- KQU( 7688082017574293629), KQU( 900986224735166665),
- KQU( 9977972710722265039), KQU( 6008205004994830552),
- KQU( 546909104521689292), KQU( 7428471521869107594),
- KQU(14777563419314721179), KQU(16116143076567350053),
- KQU( 5322685342003142329), KQU( 4200427048445863473),
- KQU( 4693092150132559146), KQU(13671425863759338582),
- KQU( 6747117460737639916), KQU( 4732666080236551150),
- KQU( 5912839950611941263), KQU( 3903717554504704909),
- KQU( 2615667650256786818), KQU(10844129913887006352),
- KQU(13786467861810997820), KQU(14267853002994021570),
- KQU(13767807302847237439), KQU(16407963253707224617),
- KQU( 4802498363698583497), KQU( 2523802839317209764),
- KQU( 3822579397797475589), KQU( 8950320572212130610),
- KQU( 3745623504978342534), KQU(16092609066068482806),
- KQU( 9817016950274642398), KQU(10591660660323829098),
- KQU(11751606650792815920), KQU( 5122873818577122211),
- KQU(17209553764913936624), KQU( 6249057709284380343),
- KQU(15088791264695071830), KQU(15344673071709851930),
- KQU( 4345751415293646084), KQU( 2542865750703067928),
- KQU(13520525127852368784), KQU(18294188662880997241),
- KQU( 3871781938044881523), KQU( 2873487268122812184),
- KQU(15099676759482679005), KQU(15442599127239350490),
- KQU( 6311893274367710888), KQU( 3286118760484672933),
- KQU( 4146067961333542189), KQU(13303942567897208770),
- KQU( 8196013722255630418), KQU( 4437815439340979989),
- KQU(15433791533450605135), KQU( 4254828956815687049),
- KQU( 1310903207708286015), KQU(10529182764462398549),
- KQU(14900231311660638810), KQU( 9727017277104609793),
- KQU( 1821308310948199033), KQU(11628861435066772084),
- KQU( 9469019138491546924), KQU( 3145812670532604988),
- KQU( 9938468915045491919), KQU( 1562447430672662142),
- KQU(13963995266697989134), KQU( 3356884357625028695),
- KQU( 4499850304584309747), KQU( 8456825817023658122),
- KQU(10859039922814285279), KQU( 8099512337972526555),
- KQU( 348006375109672149), KQU(11919893998241688603),
- KQU( 1104199577402948826), KQU(16689191854356060289),
- KQU(10992552041730168078), KQU( 7243733172705465836),
- KQU( 5668075606180319560), KQU(18182847037333286970),
- KQU( 4290215357664631322), KQU( 4061414220791828613),
- KQU(13006291061652989604), KQU( 7140491178917128798),
- KQU(12703446217663283481), KQU( 5500220597564558267),
- KQU(10330551509971296358), KQU(15958554768648714492),
- KQU( 5174555954515360045), KQU( 1731318837687577735),
- KQU( 3557700801048354857), KQU(13764012341928616198),
- KQU(13115166194379119043), KQU( 7989321021560255519),
- KQU( 2103584280905877040), KQU( 9230788662155228488),
- KQU(16396629323325547654), KQU( 657926409811318051),
- KQU(15046700264391400727), KQU( 5120132858771880830),
- KQU( 7934160097989028561), KQU( 6963121488531976245),
- KQU(17412329602621742089), KQU(15144843053931774092),
- KQU(17204176651763054532), KQU(13166595387554065870),
- KQU( 8590377810513960213), KQU( 5834365135373991938),
- KQU( 7640913007182226243), KQU( 3479394703859418425),
- KQU(16402784452644521040), KQU( 4993979809687083980),
- KQU(13254522168097688865), KQU(15643659095244365219),
- KQU( 5881437660538424982), KQU(11174892200618987379),
- KQU( 254409966159711077), KQU(17158413043140549909),
- KQU( 3638048789290376272), KQU( 1376816930299489190),
- KQU( 4622462095217761923), KQU(15086407973010263515),
- KQU(13253971772784692238), KQU( 5270549043541649236),
- KQU(11182714186805411604), KQU(12283846437495577140),
- KQU( 5297647149908953219), KQU(10047451738316836654),
- KQU( 4938228100367874746), KQU(12328523025304077923),
- KQU( 3601049438595312361), KQU( 9313624118352733770),
- KQU(13322966086117661798), KQU(16660005705644029394),
- KQU(11337677526988872373), KQU(13869299102574417795),
- KQU(15642043183045645437), KQU( 3021755569085880019),
- KQU( 4979741767761188161), KQU(13679979092079279587),
- KQU( 3344685842861071743), KQU(13947960059899588104),
- KQU( 305806934293368007), KQU( 5749173929201650029),
- KQU(11123724852118844098), KQU(15128987688788879802),
- KQU(15251651211024665009), KQU( 7689925933816577776),
- KQU(16732804392695859449), KQU(17087345401014078468),
- KQU(14315108589159048871), KQU( 4820700266619778917),
- KQU(16709637539357958441), KQU( 4936227875177351374),
- KQU( 2137907697912987247), KQU(11628565601408395420),
- KQU( 2333250549241556786), KQU( 5711200379577778637),
- KQU( 5170680131529031729), KQU(12620392043061335164),
- KQU( 95363390101096078), KQU( 5487981914081709462),
- KQU( 1763109823981838620), KQU( 3395861271473224396),
- KQU( 1300496844282213595), KQU( 6894316212820232902),
- KQU(10673859651135576674), KQU( 5911839658857903252),
- KQU(17407110743387299102), KQU( 8257427154623140385),
- KQU(11389003026741800267), KQU( 4070043211095013717),
- KQU(11663806997145259025), KQU(15265598950648798210),
- KQU( 630585789434030934), KQU( 3524446529213587334),
- KQU( 7186424168495184211), KQU(10806585451386379021),
- KQU(11120017753500499273), KQU( 1586837651387701301),
- KQU(17530454400954415544), KQU( 9991670045077880430),
- KQU( 7550997268990730180), KQU( 8640249196597379304),
- KQU( 3522203892786893823), KQU(10401116549878854788),
- KQU(13690285544733124852), KQU( 8295785675455774586),
- KQU(15535716172155117603), KQU( 3112108583723722511),
- KQU(17633179955339271113), KQU(18154208056063759375),
- KQU( 1866409236285815666), KQU(13326075895396412882),
- KQU( 8756261842948020025), KQU( 6281852999868439131),
- KQU(15087653361275292858), KQU(10333923911152949397),
- KQU( 5265567645757408500), KQU(12728041843210352184),
- KQU( 6347959327507828759), KQU( 154112802625564758),
- KQU(18235228308679780218), KQU( 3253805274673352418),
- KQU( 4849171610689031197), KQU(17948529398340432518),
- KQU(13803510475637409167), KQU(13506570190409883095),
- KQU(15870801273282960805), KQU( 8451286481299170773),
- KQU( 9562190620034457541), KQU( 8518905387449138364),
- KQU(12681306401363385655), KQU( 3788073690559762558),
- KQU( 5256820289573487769), KQU( 2752021372314875467),
- KQU( 6354035166862520716), KQU( 4328956378309739069),
- KQU( 449087441228269600), KQU( 5533508742653090868),
- KQU( 1260389420404746988), KQU(18175394473289055097),
- KQU( 1535467109660399420), KQU( 8818894282874061442),
- KQU(12140873243824811213), KQU(15031386653823014946),
- KQU( 1286028221456149232), KQU( 6329608889367858784),
- KQU( 9419654354945132725), KQU( 6094576547061672379),
- KQU(17706217251847450255), KQU( 1733495073065878126),
- KQU(16918923754607552663), KQU( 8881949849954945044),
- KQU(12938977706896313891), KQU(14043628638299793407),
- KQU(18393874581723718233), KQU( 6886318534846892044),
- KQU(14577870878038334081), KQU(13541558383439414119),
- KQU(13570472158807588273), KQU(18300760537910283361),
- KQU( 818368572800609205), KQU( 1417000585112573219),
- KQU(12337533143867683655), KQU(12433180994702314480),
- KQU( 778190005829189083), KQU(13667356216206524711),
- KQU( 9866149895295225230), KQU(11043240490417111999),
- KQU( 1123933826541378598), KQU( 6469631933605123610),
- KQU(14508554074431980040), KQU(13918931242962026714),
- KQU( 2870785929342348285), KQU(14786362626740736974),
- KQU(13176680060902695786), KQU( 9591778613541679456),
- KQU( 9097662885117436706), KQU( 749262234240924947),
- KQU( 1944844067793307093), KQU( 4339214904577487742),
- KQU( 8009584152961946551), KQU(16073159501225501777),
- KQU( 3335870590499306217), KQU(17088312653151202847),
- KQU( 3108893142681931848), KQU(16636841767202792021),
- KQU(10423316431118400637), KQU( 8008357368674443506),
- KQU(11340015231914677875), KQU(17687896501594936090),
- KQU(15173627921763199958), KQU( 542569482243721959),
- KQU(15071714982769812975), KQU( 4466624872151386956),
- KQU( 1901780715602332461), KQU( 9822227742154351098),
- KQU( 1479332892928648780), KQU( 6981611948382474400),
- KQU( 7620824924456077376), KQU(14095973329429406782),
- KQU( 7902744005696185404), KQU(15830577219375036920),
- KQU(10287076667317764416), KQU(12334872764071724025),
- KQU( 4419302088133544331), KQU(14455842851266090520),
- KQU(12488077416504654222), KQU( 7953892017701886766),
- KQU( 6331484925529519007), KQU( 4902145853785030022),
- KQU(17010159216096443073), KQU(11945354668653886087),
- KQU(15112022728645230829), KQU(17363484484522986742),
- KQU( 4423497825896692887), KQU( 8155489510809067471),
- KQU( 258966605622576285), KQU( 5462958075742020534),
- KQU( 6763710214913276228), KQU( 2368935183451109054),
- KQU(14209506165246453811), KQU( 2646257040978514881),
- KQU( 3776001911922207672), KQU( 1419304601390147631),
- KQU(14987366598022458284), KQU( 3977770701065815721),
- KQU( 730820417451838898), KQU( 3982991703612885327),
- KQU( 2803544519671388477), KQU(17067667221114424649),
- KQU( 2922555119737867166), KQU( 1989477584121460932),
- KQU(15020387605892337354), KQU( 9293277796427533547),
- KQU(10722181424063557247), KQU(16704542332047511651),
- KQU( 5008286236142089514), KQU(16174732308747382540),
- KQU(17597019485798338402), KQU(13081745199110622093),
- KQU( 8850305883842258115), KQU(12723629125624589005),
- KQU( 8140566453402805978), KQU(15356684607680935061),
- KQU(14222190387342648650), KQU(11134610460665975178),
- KQU( 1259799058620984266), KQU(13281656268025610041),
- KQU( 298262561068153992), KQU(12277871700239212922),
- KQU(13911297774719779438), KQU(16556727962761474934),
- KQU(17903010316654728010), KQU( 9682617699648434744),
- KQU(14757681836838592850), KQU( 1327242446558524473),
- KQU(11126645098780572792), KQU( 1883602329313221774),
- KQU( 2543897783922776873), KQU(15029168513767772842),
- KQU(12710270651039129878), KQU(16118202956069604504),
- KQU(15010759372168680524), KQU( 2296827082251923948),
- KQU(10793729742623518101), KQU(13829764151845413046),
- KQU(17769301223184451213), KQU( 3118268169210783372),
- KQU(17626204544105123127), KQU( 7416718488974352644),
- KQU(10450751996212925994), KQU( 9352529519128770586),
- KQU( 259347569641110140), KQU( 8048588892269692697),
- KQU( 1774414152306494058), KQU(10669548347214355622),
- KQU(13061992253816795081), KQU(18432677803063861659),
- KQU( 8879191055593984333), KQU(12433753195199268041),
- KQU(14919392415439730602), KQU( 6612848378595332963),
- KQU( 6320986812036143628), KQU(10465592420226092859),
- KQU( 4196009278962570808), KQU( 3747816564473572224),
- KQU(17941203486133732898), KQU( 2350310037040505198),
- KQU( 5811779859134370113), KQU(10492109599506195126),
- KQU( 7699650690179541274), KQU( 1954338494306022961),
- KQU(14095816969027231152), KQU( 5841346919964852061),
- KQU(14945969510148214735), KQU( 3680200305887550992),
- KQU( 6218047466131695792), KQU( 8242165745175775096),
- KQU(11021371934053307357), KQU( 1265099502753169797),
- KQU( 4644347436111321718), KQU( 3609296916782832859),
- KQU( 8109807992218521571), KQU(18387884215648662020),
- KQU(14656324896296392902), KQU(17386819091238216751),
- KQU(17788300878582317152), KQU( 7919446259742399591),
- KQU( 4466613134576358004), KQU(12928181023667938509),
- KQU(13147446154454932030), KQU(16552129038252734620),
- KQU( 8395299403738822450), KQU(11313817655275361164),
- KQU( 434258809499511718), KQU( 2074882104954788676),
- KQU( 7929892178759395518), KQU( 9006461629105745388),
- KQU( 5176475650000323086), KQU(11128357033468341069),
- KQU(12026158851559118955), KQU(14699716249471156500),
- KQU( 448982497120206757), KQU( 4156475356685519900),
- KQU( 6063816103417215727), KQU(10073289387954971479),
- KQU( 8174466846138590962), KQU( 2675777452363449006),
- KQU( 9090685420572474281), KQU( 6659652652765562060),
- KQU(12923120304018106621), KQU(11117480560334526775),
- KQU( 937910473424587511), KQU( 1838692113502346645),
- KQU(11133914074648726180), KQU( 7922600945143884053),
- KQU(13435287702700959550), KQU( 5287964921251123332),
- KQU(11354875374575318947), KQU(17955724760748238133),
- KQU(13728617396297106512), KQU( 4107449660118101255),
- KQU( 1210269794886589623), KQU(11408687205733456282),
- KQU( 4538354710392677887), KQU(13566803319341319267),
- KQU(17870798107734050771), KQU( 3354318982568089135),
- KQU( 9034450839405133651), KQU(13087431795753424314),
- KQU( 950333102820688239), KQU( 1968360654535604116),
- KQU(16840551645563314995), KQU( 8867501803892924995),
- KQU(11395388644490626845), KQU( 1529815836300732204),
- KQU(13330848522996608842), KQU( 1813432878817504265),
- KQU( 2336867432693429560), KQU(15192805445973385902),
- KQU( 2528593071076407877), KQU( 128459777936689248),
- KQU( 9976345382867214866), KQU( 6208885766767996043),
- KQU(14982349522273141706), KQU( 3099654362410737822),
- KQU(13776700761947297661), KQU( 8806185470684925550),
- KQU( 8151717890410585321), KQU( 640860591588072925),
- KQU(14592096303937307465), KQU( 9056472419613564846),
- KQU(14861544647742266352), KQU(12703771500398470216),
- KQU( 3142372800384138465), KQU( 6201105606917248196),
- KQU(18337516409359270184), KQU(15042268695665115339),
- KQU(15188246541383283846), KQU(12800028693090114519),
- KQU( 5992859621101493472), KQU(18278043971816803521),
- KQU( 9002773075219424560), KQU( 7325707116943598353),
- KQU( 7930571931248040822), KQU( 5645275869617023448),
- KQU( 7266107455295958487), KQU( 4363664528273524411),
- KQU(14313875763787479809), KQU(17059695613553486802),
- KQU( 9247761425889940932), KQU(13704726459237593128),
- KQU( 2701312427328909832), KQU(17235532008287243115),
- KQU(14093147761491729538), KQU( 6247352273768386516),
- KQU( 8268710048153268415), KQU( 7985295214477182083),
- KQU(15624495190888896807), KQU( 3772753430045262788),
- KQU( 9133991620474991698), KQU( 5665791943316256028),
- KQU( 7551996832462193473), KQU(13163729206798953877),
- KQU( 9263532074153846374), KQU( 1015460703698618353),
- KQU(17929874696989519390), KQU(18257884721466153847),
- KQU(16271867543011222991), KQU( 3905971519021791941),
- KQU(16814488397137052085), KQU( 1321197685504621613),
- KQU( 2870359191894002181), KQU(14317282970323395450),
- KQU(13663920845511074366), KQU( 2052463995796539594),
- KQU(14126345686431444337), KQU( 1727572121947022534),
- KQU(17793552254485594241), KQU( 6738857418849205750),
- KQU( 1282987123157442952), KQU(16655480021581159251),
- KQU( 6784587032080183866), KQU(14726758805359965162),
- KQU( 7577995933961987349), KQU(12539609320311114036),
- KQU(10789773033385439494), KQU( 8517001497411158227),
- KQU(10075543932136339710), KQU(14838152340938811081),
- KQU( 9560840631794044194), KQU(17445736541454117475),
- KQU(10633026464336393186), KQU(15705729708242246293),
- KQU( 1117517596891411098), KQU( 4305657943415886942),
- KQU( 4948856840533979263), KQU(16071681989041789593),
- KQU(13723031429272486527), KQU( 7639567622306509462),
- KQU(12670424537483090390), KQU( 9715223453097197134),
- KQU( 5457173389992686394), KQU( 289857129276135145),
- KQU(17048610270521972512), KQU( 692768013309835485),
- KQU(14823232360546632057), KQU(18218002361317895936),
- KQU( 3281724260212650204), KQU(16453957266549513795),
- KQU( 8592711109774511881), KQU( 929825123473369579),
- KQU(15966784769764367791), KQU( 9627344291450607588),
- KQU(10849555504977813287), KQU( 9234566913936339275),
- KQU( 6413807690366911210), KQU(10862389016184219267),
- KQU(13842504799335374048), KQU( 1531994113376881174),
- KQU( 2081314867544364459), KQU(16430628791616959932),
- KQU( 8314714038654394368), KQU( 9155473892098431813),
- KQU(12577843786670475704), KQU( 4399161106452401017),
- KQU( 1668083091682623186), KQU( 1741383777203714216),
- KQU( 2162597285417794374), KQU(15841980159165218736),
- KQU( 1971354603551467079), KQU( 1206714764913205968),
- KQU( 4790860439591272330), KQU(14699375615594055799),
- KQU( 8374423871657449988), KQU(10950685736472937738),
- KQU( 697344331343267176), KQU(10084998763118059810),
- KQU(12897369539795983124), KQU(12351260292144383605),
- KQU( 1268810970176811234), KQU( 7406287800414582768),
- KQU( 516169557043807831), KQU( 5077568278710520380),
- KQU( 3828791738309039304), KQU( 7721974069946943610),
- KQU( 3534670260981096460), KQU( 4865792189600584891),
- KQU(16892578493734337298), KQU( 9161499464278042590),
- KQU(11976149624067055931), KQU(13219479887277343990),
- KQU(14161556738111500680), KQU(14670715255011223056),
- KQU( 4671205678403576558), KQU(12633022931454259781),
- KQU(14821376219869187646), KQU( 751181776484317028),
- KQU( 2192211308839047070), KQU(11787306362361245189),
- KQU(10672375120744095707), KQU( 4601972328345244467),
- KQU(15457217788831125879), KQU( 8464345256775460809),
- KQU(10191938789487159478), KQU( 6184348739615197613),
- KQU(11425436778806882100), KQU( 2739227089124319793),
- KQU( 461464518456000551), KQU( 4689850170029177442),
- KQU( 6120307814374078625), KQU(11153579230681708671),
- KQU( 7891721473905347926), KQU(10281646937824872400),
- KQU( 3026099648191332248), KQU( 8666750296953273818),
- KQU(14978499698844363232), KQU(13303395102890132065),
- KQU( 8182358205292864080), KQU(10560547713972971291),
- KQU(11981635489418959093), KQU( 3134621354935288409),
- KQU(11580681977404383968), KQU(14205530317404088650),
- KQU( 5997789011854923157), KQU(13659151593432238041),
- KQU(11664332114338865086), KQU( 7490351383220929386),
- KQU( 7189290499881530378), KQU(15039262734271020220),
- KQU( 2057217285976980055), KQU( 555570804905355739),
- KQU(11235311968348555110), KQU(13824557146269603217),
- KQU(16906788840653099693), KQU( 7222878245455661677),
- KQU( 5245139444332423756), KQU( 4723748462805674292),
- KQU(12216509815698568612), KQU(17402362976648951187),
- KQU(17389614836810366768), KQU( 4880936484146667711),
- KQU( 9085007839292639880), KQU(13837353458498535449),
- KQU(11914419854360366677), KQU(16595890135313864103),
- KQU( 6313969847197627222), KQU(18296909792163910431),
- KQU(10041780113382084042), KQU( 2499478551172884794),
- KQU(11057894246241189489), KQU( 9742243032389068555),
- KQU(12838934582673196228), KQU(13437023235248490367),
- KQU(13372420669446163240), KQU( 6752564244716909224),
- KQU( 7157333073400313737), KQU(12230281516370654308),
- KQU( 1182884552219419117), KQU( 2955125381312499218),
- KQU(10308827097079443249), KQU( 1337648572986534958),
- KQU(16378788590020343939), KQU( 108619126514420935),
- KQU( 3990981009621629188), KQU( 5460953070230946410),
- KQU( 9703328329366531883), KQU(13166631489188077236),
- KQU( 1104768831213675170), KQU( 3447930458553877908),
- KQU( 8067172487769945676), KQU( 5445802098190775347),
- KQU( 3244840981648973873), KQU(17314668322981950060),
- KQU( 5006812527827763807), KQU(18158695070225526260),
- KQU( 2824536478852417853), KQU(13974775809127519886),
- KQU( 9814362769074067392), KQU(17276205156374862128),
- KQU(11361680725379306967), KQU( 3422581970382012542),
- KQU(11003189603753241266), KQU(11194292945277862261),
- KQU( 6839623313908521348), KQU(11935326462707324634),
- KQU( 1611456788685878444), KQU(13112620989475558907),
- KQU( 517659108904450427), KQU(13558114318574407624),
- KQU(15699089742731633077), KQU( 4988979278862685458),
- KQU( 8111373583056521297), KQU( 3891258746615399627),
- KQU( 8137298251469718086), KQU(12748663295624701649),
- KQU( 4389835683495292062), KQU( 5775217872128831729),
- KQU( 9462091896405534927), KQU( 8498124108820263989),
- KQU( 8059131278842839525), KQU(10503167994254090892),
- KQU(11613153541070396656), KQU(18069248738504647790),
- KQU( 570657419109768508), KQU( 3950574167771159665),
- KQU( 5514655599604313077), KQU( 2908460854428484165),
- KQU(10777722615935663114), KQU(12007363304839279486),
- KQU( 9800646187569484767), KQU( 8795423564889864287),
- KQU(14257396680131028419), KQU( 6405465117315096498),
- KQU( 7939411072208774878), KQU(17577572378528990006),
- KQU(14785873806715994850), KQU(16770572680854747390),
- KQU(18127549474419396481), KQU(11637013449455757750),
- KQU(14371851933996761086), KQU( 3601181063650110280),
- KQU( 4126442845019316144), KQU(10198287239244320669),
- KQU(18000169628555379659), KQU(18392482400739978269),
- KQU( 6219919037686919957), KQU( 3610085377719446052),
- KQU( 2513925039981776336), KQU(16679413537926716955),
- KQU(12903302131714909434), KQU( 5581145789762985009),
- KQU(12325955044293303233), KQU(17216111180742141204),
- KQU( 6321919595276545740), KQU( 3507521147216174501),
- KQU( 9659194593319481840), KQU(11473976005975358326),
- KQU(14742730101435987026), KQU( 492845897709954780),
- KQU(16976371186162599676), KQU(17712703422837648655),
- KQU( 9881254778587061697), KQU( 8413223156302299551),
- KQU( 1563841828254089168), KQU( 9996032758786671975),
- KQU( 138877700583772667), KQU(13003043368574995989),
- KQU( 4390573668650456587), KQU( 8610287390568126755),
- KQU(15126904974266642199), KQU( 6703637238986057662),
- KQU( 2873075592956810157), KQU( 6035080933946049418),
- KQU(13382846581202353014), KQU( 7303971031814642463),
- KQU(18418024405307444267), KQU( 5847096731675404647),
- KQU( 4035880699639842500), KQU(11525348625112218478),
- KQU( 3041162365459574102), KQU( 2604734487727986558),
- KQU(15526341771636983145), KQU(14556052310697370254),
- KQU(12997787077930808155), KQU( 9601806501755554499),
- KQU(11349677952521423389), KQU(14956777807644899350),
- KQU(16559736957742852721), KQU(12360828274778140726),
- KQU( 6685373272009662513), KQU(16932258748055324130),
- KQU(15918051131954158508), KQU( 1692312913140790144),
- KQU( 546653826801637367), KQU( 5341587076045986652),
- KQU(14975057236342585662), KQU(12374976357340622412),
- KQU(10328833995181940552), KQU(12831807101710443149),
- KQU(10548514914382545716), KQU( 2217806727199715993),
- KQU(12627067369242845138), KQU( 4598965364035438158),
- KQU( 150923352751318171), KQU(14274109544442257283),
- KQU( 4696661475093863031), KQU( 1505764114384654516),
- KQU(10699185831891495147), KQU( 2392353847713620519),
- KQU( 3652870166711788383), KQU( 8640653276221911108),
- KQU( 3894077592275889704), KQU( 4918592872135964845),
- KQU(16379121273281400789), KQU(12058465483591683656),
- KQU(11250106829302924945), KQU( 1147537556296983005),
- KQU( 6376342756004613268), KQU(14967128191709280506),
- KQU(18007449949790627628), KQU( 9497178279316537841),
- KQU( 7920174844809394893), KQU(10037752595255719907),
- KQU(15875342784985217697), KQU(15311615921712850696),
- KQU( 9552902652110992950), KQU(14054979450099721140),
- KQU( 5998709773566417349), KQU(18027910339276320187),
- KQU( 8223099053868585554), KQU( 7842270354824999767),
- KQU( 4896315688770080292), KQU(12969320296569787895),
- KQU( 2674321489185759961), KQU( 4053615936864718439),
- KQU(11349775270588617578), KQU( 4743019256284553975),
- KQU( 5602100217469723769), KQU(14398995691411527813),
- KQU( 7412170493796825470), KQU( 836262406131744846),
- KQU( 8231086633845153022), KQU( 5161377920438552287),
- KQU( 8828731196169924949), KQU(16211142246465502680),
- KQU( 3307990879253687818), KQU( 5193405406899782022),
- KQU( 8510842117467566693), KQU( 6070955181022405365),
- KQU(14482950231361409799), KQU(12585159371331138077),
- KQU( 3511537678933588148), KQU( 2041849474531116417),
- KQU(10944936685095345792), KQU(18303116923079107729),
- KQU( 2720566371239725320), KQU( 4958672473562397622),
- KQU( 3032326668253243412), KQU(13689418691726908338),
- KQU( 1895205511728843996), KQU( 8146303515271990527),
- KQU(16507343500056113480), KQU( 473996939105902919),
- KQU( 9897686885246881481), KQU(14606433762712790575),
- KQU( 6732796251605566368), KQU( 1399778120855368916),
- KQU( 935023885182833777), KQU(16066282816186753477),
- KQU( 7291270991820612055), KQU(17530230393129853844),
- KQU(10223493623477451366), KQU(15841725630495676683),
- KQU(17379567246435515824), KQU( 8588251429375561971),
- KQU(18339511210887206423), KQU(17349587430725976100),
- KQU(12244876521394838088), KQU( 6382187714147161259),
- KQU(12335807181848950831), KQU(16948885622305460665),
- KQU(13755097796371520506), KQU(14806740373324947801),
- KQU( 4828699633859287703), KQU( 8209879281452301604),
- KQU(12435716669553736437), KQU(13970976859588452131),
- KQU( 6233960842566773148), KQU(12507096267900505759),
- KQU( 1198713114381279421), KQU(14989862731124149015),
- KQU(15932189508707978949), KQU( 2526406641432708722),
- KQU( 29187427817271982), KQU( 1499802773054556353),
- KQU(10816638187021897173), KQU( 5436139270839738132),
- KQU( 6659882287036010082), KQU( 2154048955317173697),
- KQU(10887317019333757642), KQU(16281091802634424955),
- KQU(10754549879915384901), KQU(10760611745769249815),
- KQU( 2161505946972504002), KQU( 5243132808986265107),
- KQU(10129852179873415416), KQU( 710339480008649081),
- KQU( 7802129453068808528), KQU(17967213567178907213),
- KQU(15730859124668605599), KQU(13058356168962376502),
- KQU( 3701224985413645909), KQU(14464065869149109264),
- KQU( 9959272418844311646), KQU(10157426099515958752),
- KQU(14013736814538268528), KQU(17797456992065653951),
- KQU(17418878140257344806), KQU(15457429073540561521),
- KQU( 2184426881360949378), KQU( 2062193041154712416),
- KQU( 8553463347406931661), KQU( 4913057625202871854),
- KQU( 2668943682126618425), KQU(17064444737891172288),
- KQU( 4997115903913298637), KQU(12019402608892327416),
- KQU(17603584559765897352), KQU(11367529582073647975),
- KQU( 8211476043518436050), KQU( 8676849804070323674),
- KQU(18431829230394475730), KQU(10490177861361247904),
- KQU( 9508720602025651349), KQU( 7409627448555722700),
- KQU( 5804047018862729008), KQU(11943858176893142594),
- KQU(11908095418933847092), KQU( 5415449345715887652),
- KQU( 1554022699166156407), KQU( 9073322106406017161),
- KQU( 7080630967969047082), KQU(18049736940860732943),
- KQU(12748714242594196794), KQU( 1226992415735156741),
- KQU(17900981019609531193), KQU(11720739744008710999),
- KQU( 3006400683394775434), KQU(11347974011751996028),
- KQU( 3316999628257954608), KQU( 8384484563557639101),
- KQU(18117794685961729767), KQU( 1900145025596618194),
- KQU(17459527840632892676), KQU( 5634784101865710994),
- KQU( 7918619300292897158), KQU( 3146577625026301350),
- KQU( 9955212856499068767), KQU( 1873995843681746975),
- KQU( 1561487759967972194), KQU( 8322718804375878474),
- KQU(11300284215327028366), KQU( 4667391032508998982),
- KQU( 9820104494306625580), KQU(17922397968599970610),
- KQU( 1784690461886786712), KQU(14940365084341346821),
- KQU( 5348719575594186181), KQU(10720419084507855261),
- KQU(14210394354145143274), KQU( 2426468692164000131),
- KQU(16271062114607059202), KQU(14851904092357070247),
- KQU( 6524493015693121897), KQU( 9825473835127138531),
- KQU(14222500616268569578), KQU(15521484052007487468),
- KQU(14462579404124614699), KQU(11012375590820665520),
- KQU(11625327350536084927), KQU(14452017765243785417),
- KQU( 9989342263518766305), KQU( 3640105471101803790),
- KQU( 4749866455897513242), KQU(13963064946736312044),
- KQU(10007416591973223791), KQU(18314132234717431115),
- KQU( 3286596588617483450), KQU( 7726163455370818765),
- KQU( 7575454721115379328), KQU( 5308331576437663422),
- KQU(18288821894903530934), KQU( 8028405805410554106),
- KQU(15744019832103296628), KQU( 149765559630932100),
- KQU( 6137705557200071977), KQU(14513416315434803615),
- KQU(11665702820128984473), KQU( 218926670505601386),
- KQU( 6868675028717769519), KQU(15282016569441512302),
- KQU( 5707000497782960236), KQU( 6671120586555079567),
- KQU( 2194098052618985448), KQU(16849577895477330978),
- KQU(12957148471017466283), KQU( 1997805535404859393),
- KQU( 1180721060263860490), KQU(13206391310193756958),
- KQU(12980208674461861797), KQU( 3825967775058875366),
- KQU(17543433670782042631), KQU( 1518339070120322730),
- KQU(16344584340890991669), KQU( 2611327165318529819),
- KQU(11265022723283422529), KQU( 4001552800373196817),
- KQU(14509595890079346161), KQU( 3528717165416234562),
- KQU(18153222571501914072), KQU( 9387182977209744425),
- KQU(10064342315985580021), KQU(11373678413215253977),
- KQU( 2308457853228798099), KQU( 9729042942839545302),
- KQU( 7833785471140127746), KQU( 6351049900319844436),
- KQU(14454610627133496067), KQU(12533175683634819111),
- KQU(15570163926716513029), KQU(13356980519185762498)
-};
-
-TEST_BEGIN(test_gen_rand_32)
-{
- uint32_t array32[BLOCK_SIZE] JEMALLOC_ATTR(aligned(16));
- uint32_t array32_2[BLOCK_SIZE] JEMALLOC_ATTR(aligned(16));
- int i;
- uint32_t r32;
- sfmt_t *ctx;
-
- assert_d_le(get_min_array_size32(), BLOCK_SIZE,
- "Array size too small");
- ctx = init_gen_rand(1234);
- fill_array32(ctx, array32, BLOCK_SIZE);
- fill_array32(ctx, array32_2, BLOCK_SIZE);
- fini_gen_rand(ctx);
-
- ctx = init_gen_rand(1234);
- for (i = 0; i < BLOCK_SIZE; i++) {
- if (i < COUNT_1) {
- assert_u32_eq(array32[i], init_gen_rand_32_expected[i],
- "Output mismatch for i=%d", i);
- }
- r32 = gen_rand32(ctx);
- assert_u32_eq(r32, array32[i],
- "Mismatch at array32[%d]=%x, gen=%x", i, array32[i], r32);
- }
- for (i = 0; i < COUNT_2; i++) {
- r32 = gen_rand32(ctx);
- assert_u32_eq(r32, array32_2[i],
- "Mismatch at array32_2[%d]=%x, gen=%x", i, array32_2[i],
- r32);
- }
- fini_gen_rand(ctx);
-}
-TEST_END
-
-TEST_BEGIN(test_by_array_32)
-{
- uint32_t array32[BLOCK_SIZE] JEMALLOC_ATTR(aligned(16));
- uint32_t array32_2[BLOCK_SIZE] JEMALLOC_ATTR(aligned(16));
- int i;
- uint32_t ini[4] = {0x1234, 0x5678, 0x9abc, 0xdef0};
- uint32_t r32;
- sfmt_t *ctx;
-
- assert_d_le(get_min_array_size32(), BLOCK_SIZE,
- "Array size too small");
- ctx = init_by_array(ini, 4);
- fill_array32(ctx, array32, BLOCK_SIZE);
- fill_array32(ctx, array32_2, BLOCK_SIZE);
- fini_gen_rand(ctx);
-
- ctx = init_by_array(ini, 4);
- for (i = 0; i < BLOCK_SIZE; i++) {
- if (i < COUNT_1) {
- assert_u32_eq(array32[i], init_by_array_32_expected[i],
- "Output mismatch for i=%d", i);
- }
- r32 = gen_rand32(ctx);
- assert_u32_eq(r32, array32[i],
- "Mismatch at array32[%d]=%x, gen=%x", i, array32[i], r32);
- }
- for (i = 0; i < COUNT_2; i++) {
- r32 = gen_rand32(ctx);
- assert_u32_eq(r32, array32_2[i],
- "Mismatch at array32_2[%d]=%x, gen=%x", i, array32_2[i],
- r32);
- }
- fini_gen_rand(ctx);
-}
-TEST_END
-
-TEST_BEGIN(test_gen_rand_64)
-{
- uint64_t array64[BLOCK_SIZE64] JEMALLOC_ATTR(aligned(16));
- uint64_t array64_2[BLOCK_SIZE64] JEMALLOC_ATTR(aligned(16));
- int i;
- uint64_t r;
- sfmt_t *ctx;
-
- assert_d_le(get_min_array_size64(), BLOCK_SIZE64,
- "Array size too small");
- ctx = init_gen_rand(4321);
- fill_array64(ctx, array64, BLOCK_SIZE64);
- fill_array64(ctx, array64_2, BLOCK_SIZE64);
- fini_gen_rand(ctx);
-
- ctx = init_gen_rand(4321);
- for (i = 0; i < BLOCK_SIZE64; i++) {
- if (i < COUNT_1) {
- assert_u64_eq(array64[i], init_gen_rand_64_expected[i],
- "Output mismatch for i=%d", i);
- }
- r = gen_rand64(ctx);
- assert_u64_eq(r, array64[i],
- "Mismatch at array64[%d]=%"FMTx64", gen=%"FMTx64, i,
- array64[i], r);
- }
- for (i = 0; i < COUNT_2; i++) {
- r = gen_rand64(ctx);
- assert_u64_eq(r, array64_2[i],
- "Mismatch at array64_2[%d]=%"FMTx64" gen=%"FMTx64"", i,
- array64_2[i], r);
- }
- fini_gen_rand(ctx);
-}
-TEST_END
-
-TEST_BEGIN(test_by_array_64)
-{
- uint64_t array64[BLOCK_SIZE64] JEMALLOC_ATTR(aligned(16));
- uint64_t array64_2[BLOCK_SIZE64] JEMALLOC_ATTR(aligned(16));
- int i;
- uint64_t r;
- uint32_t ini[] = {5, 4, 3, 2, 1};
- sfmt_t *ctx;
-
- assert_d_le(get_min_array_size64(), BLOCK_SIZE64,
- "Array size too small");
- ctx = init_by_array(ini, 5);
- fill_array64(ctx, array64, BLOCK_SIZE64);
- fill_array64(ctx, array64_2, BLOCK_SIZE64);
- fini_gen_rand(ctx);
-
- ctx = init_by_array(ini, 5);
- for (i = 0; i < BLOCK_SIZE64; i++) {
- if (i < COUNT_1) {
- assert_u64_eq(array64[i], init_by_array_64_expected[i],
- "Output mismatch for i=%d", i);
- }
- r = gen_rand64(ctx);
- assert_u64_eq(r, array64[i],
- "Mismatch at array64[%d]=%"FMTx64" gen=%"FMTx64, i,
- array64[i], r);
- }
- for (i = 0; i < COUNT_2; i++) {
- r = gen_rand64(ctx);
- assert_u64_eq(r, array64_2[i],
- "Mismatch at array64_2[%d]=%"FMTx64" gen=%"FMTx64, i,
- array64_2[i], r);
- }
- fini_gen_rand(ctx);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_gen_rand_32,
- test_by_array_32,
- test_gen_rand_64,
- test_by_array_64));
-}
diff --git a/memory/jemalloc/src/test/unit/a0.c b/memory/jemalloc/src/test/unit/a0.c
deleted file mode 100644
index b9ba45a3d..000000000
--- a/memory/jemalloc/src/test/unit/a0.c
+++ /dev/null
@@ -1,19 +0,0 @@
-#include "test/jemalloc_test.h"
-
-TEST_BEGIN(test_a0)
-{
- void *p;
-
- p = a0malloc(1);
- assert_ptr_not_null(p, "Unexpected a0malloc() error");
- a0dalloc(p);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test_no_malloc_init(
- test_a0));
-}
diff --git a/memory/jemalloc/src/test/unit/arena_reset.c b/memory/jemalloc/src/test/unit/arena_reset.c
deleted file mode 100644
index 8ba36c21f..000000000
--- a/memory/jemalloc/src/test/unit/arena_reset.c
+++ /dev/null
@@ -1,159 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_PROF
-const char *malloc_conf = "prof:true,lg_prof_sample:0";
-#endif
-
-static unsigned
-get_nsizes_impl(const char *cmd)
-{
- unsigned ret;
- size_t z;
-
- z = sizeof(unsigned);
- assert_d_eq(mallctl(cmd, &ret, &z, NULL, 0), 0,
- "Unexpected mallctl(\"%s\", ...) failure", cmd);
-
- return (ret);
-}
-
-static unsigned
-get_nsmall(void)
-{
-
- return (get_nsizes_impl("arenas.nbins"));
-}
-
-static unsigned
-get_nlarge(void)
-{
-
- return (get_nsizes_impl("arenas.nlruns"));
-}
-
-static unsigned
-get_nhuge(void)
-{
-
- return (get_nsizes_impl("arenas.nhchunks"));
-}
-
-static size_t
-get_size_impl(const char *cmd, size_t ind)
-{
- size_t ret;
- size_t z;
- size_t mib[4];
- size_t miblen = 4;
-
- z = sizeof(size_t);
- assert_d_eq(mallctlnametomib(cmd, mib, &miblen),
- 0, "Unexpected mallctlnametomib(\"%s\", ...) failure", cmd);
- mib[2] = ind;
- z = sizeof(size_t);
- assert_d_eq(mallctlbymib(mib, miblen, &ret, &z, NULL, 0),
- 0, "Unexpected mallctlbymib([\"%s\", %zu], ...) failure", cmd, ind);
-
- return (ret);
-}
-
-static size_t
-get_small_size(size_t ind)
-{
-
- return (get_size_impl("arenas.bin.0.size", ind));
-}
-
-static size_t
-get_large_size(size_t ind)
-{
-
- return (get_size_impl("arenas.lrun.0.size", ind));
-}
-
-static size_t
-get_huge_size(size_t ind)
-{
-
- return (get_size_impl("arenas.hchunk.0.size", ind));
-}
-
-TEST_BEGIN(test_arena_reset)
-{
-#define NHUGE 4
- unsigned arena_ind, nsmall, nlarge, nhuge, nptrs, i;
- size_t sz, miblen;
- void **ptrs;
- int flags;
- size_t mib[3];
- tsdn_t *tsdn;
-
- test_skip_if((config_valgrind && unlikely(in_valgrind)) || (config_fill
- && unlikely(opt_quarantine)));
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("arenas.extend", &arena_ind, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
-
- flags = MALLOCX_ARENA(arena_ind) | MALLOCX_TCACHE_NONE;
-
- nsmall = get_nsmall();
- nlarge = get_nlarge();
- nhuge = get_nhuge() > NHUGE ? NHUGE : get_nhuge();
- nptrs = nsmall + nlarge + nhuge;
- ptrs = (void **)malloc(nptrs * sizeof(void *));
- assert_ptr_not_null(ptrs, "Unexpected malloc() failure");
-
- /* Allocate objects with a wide range of sizes. */
- for (i = 0; i < nsmall; i++) {
- sz = get_small_size(i);
- ptrs[i] = mallocx(sz, flags);
- assert_ptr_not_null(ptrs[i],
- "Unexpected mallocx(%zu, %#x) failure", sz, flags);
- }
- for (i = 0; i < nlarge; i++) {
- sz = get_large_size(i);
- ptrs[nsmall + i] = mallocx(sz, flags);
- assert_ptr_not_null(ptrs[i],
- "Unexpected mallocx(%zu, %#x) failure", sz, flags);
- }
- for (i = 0; i < nhuge; i++) {
- sz = get_huge_size(i);
- ptrs[nsmall + nlarge + i] = mallocx(sz, flags);
- assert_ptr_not_null(ptrs[i],
- "Unexpected mallocx(%zu, %#x) failure", sz, flags);
- }
-
- tsdn = tsdn_fetch();
-
- /* Verify allocations. */
- for (i = 0; i < nptrs; i++) {
- assert_zu_gt(ivsalloc(tsdn, ptrs[i], false), 0,
- "Allocation should have queryable size");
- }
-
- /* Reset. */
- miblen = sizeof(mib)/sizeof(size_t);
- assert_d_eq(mallctlnametomib("arena.0.reset", mib, &miblen), 0,
- "Unexpected mallctlnametomib() failure");
- mib[1] = (size_t)arena_ind;
- assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, NULL, 0), 0,
- "Unexpected mallctlbymib() failure");
-
- /* Verify allocations no longer exist. */
- for (i = 0; i < nptrs; i++) {
- assert_zu_eq(ivsalloc(tsdn, ptrs[i], false), 0,
- "Allocation should no longer exist");
- }
-
- free(ptrs);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_arena_reset));
-}
diff --git a/memory/jemalloc/src/test/unit/atomic.c b/memory/jemalloc/src/test/unit/atomic.c
deleted file mode 100644
index bdd74f659..000000000
--- a/memory/jemalloc/src/test/unit/atomic.c
+++ /dev/null
@@ -1,122 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define TEST_STRUCT(p, t) \
-struct p##_test_s { \
- t accum0; \
- t x; \
- t s; \
-}; \
-typedef struct p##_test_s p##_test_t;
-
-#define TEST_BODY(p, t, tc, ta, FMT) do { \
- const p##_test_t tests[] = { \
- {(t)-1, (t)-1, (t)-2}, \
- {(t)-1, (t) 0, (t)-2}, \
- {(t)-1, (t) 1, (t)-2}, \
- \
- {(t) 0, (t)-1, (t)-2}, \
- {(t) 0, (t) 0, (t)-2}, \
- {(t) 0, (t) 1, (t)-2}, \
- \
- {(t) 1, (t)-1, (t)-2}, \
- {(t) 1, (t) 0, (t)-2}, \
- {(t) 1, (t) 1, (t)-2}, \
- \
- {(t)0, (t)-(1 << 22), (t)-2}, \
- {(t)0, (t)(1 << 22), (t)-2}, \
- {(t)(1 << 22), (t)-(1 << 22), (t)-2}, \
- {(t)(1 << 22), (t)(1 << 22), (t)-2} \
- }; \
- unsigned i; \
- \
- for (i = 0; i < sizeof(tests)/sizeof(p##_test_t); i++) { \
- bool err; \
- t accum = tests[i].accum0; \
- assert_##ta##_eq(atomic_read_##p(&accum), \
- tests[i].accum0, \
- "Erroneous read, i=%u", i); \
- \
- assert_##ta##_eq(atomic_add_##p(&accum, tests[i].x), \
- (t)((tc)tests[i].accum0 + (tc)tests[i].x), \
- "i=%u, accum=%"FMT", x=%"FMT, \
- i, tests[i].accum0, tests[i].x); \
- assert_##ta##_eq(atomic_read_##p(&accum), accum, \
- "Erroneous add, i=%u", i); \
- \
- accum = tests[i].accum0; \
- assert_##ta##_eq(atomic_sub_##p(&accum, tests[i].x), \
- (t)((tc)tests[i].accum0 - (tc)tests[i].x), \
- "i=%u, accum=%"FMT", x=%"FMT, \
- i, tests[i].accum0, tests[i].x); \
- assert_##ta##_eq(atomic_read_##p(&accum), accum, \
- "Erroneous sub, i=%u", i); \
- \
- accum = tests[i].accum0; \
- err = atomic_cas_##p(&accum, tests[i].x, tests[i].s); \
- assert_b_eq(err, tests[i].accum0 != tests[i].x, \
- "Erroneous cas success/failure result"); \
- assert_##ta##_eq(accum, err ? tests[i].accum0 : \
- tests[i].s, "Erroneous cas effect, i=%u", i); \
- \
- accum = tests[i].accum0; \
- atomic_write_##p(&accum, tests[i].s); \
- assert_##ta##_eq(accum, tests[i].s, \
- "Erroneous write, i=%u", i); \
- } \
-} while (0)
-
-TEST_STRUCT(uint64, uint64_t)
-TEST_BEGIN(test_atomic_uint64)
-{
-
-#if !(LG_SIZEOF_PTR == 3 || LG_SIZEOF_INT == 3)
- test_skip("64-bit atomic operations not supported");
-#else
- TEST_BODY(uint64, uint64_t, uint64_t, u64, FMTx64);
-#endif
-}
-TEST_END
-
-TEST_STRUCT(uint32, uint32_t)
-TEST_BEGIN(test_atomic_uint32)
-{
-
- TEST_BODY(uint32, uint32_t, uint32_t, u32, "#"FMTx32);
-}
-TEST_END
-
-TEST_STRUCT(p, void *)
-TEST_BEGIN(test_atomic_p)
-{
-
- TEST_BODY(p, void *, uintptr_t, ptr, "p");
-}
-TEST_END
-
-TEST_STRUCT(z, size_t)
-TEST_BEGIN(test_atomic_z)
-{
-
- TEST_BODY(z, size_t, size_t, zu, "#zx");
-}
-TEST_END
-
-TEST_STRUCT(u, unsigned)
-TEST_BEGIN(test_atomic_u)
-{
-
- TEST_BODY(u, unsigned, unsigned, u, "#x");
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_atomic_uint64,
- test_atomic_uint32,
- test_atomic_p,
- test_atomic_z,
- test_atomic_u));
-}
diff --git a/memory/jemalloc/src/test/unit/bitmap.c b/memory/jemalloc/src/test/unit/bitmap.c
deleted file mode 100644
index a2dd54630..000000000
--- a/memory/jemalloc/src/test/unit/bitmap.c
+++ /dev/null
@@ -1,163 +0,0 @@
-#include "test/jemalloc_test.h"
-
-TEST_BEGIN(test_bitmap_size)
-{
- size_t i, prev_size;
-
- prev_size = 0;
- for (i = 1; i <= BITMAP_MAXBITS; i++) {
- bitmap_info_t binfo;
- size_t size;
-
- bitmap_info_init(&binfo, i);
- size = bitmap_size(&binfo);
- assert_true(size >= prev_size,
- "Bitmap size is smaller than expected");
- prev_size = size;
- }
-}
-TEST_END
-
-TEST_BEGIN(test_bitmap_init)
-{
- size_t i;
-
- for (i = 1; i <= BITMAP_MAXBITS; i++) {
- bitmap_info_t binfo;
- bitmap_info_init(&binfo, i);
- {
- size_t j;
- bitmap_t *bitmap = (bitmap_t *)malloc(
- bitmap_size(&binfo));
- bitmap_init(bitmap, &binfo);
-
- for (j = 0; j < i; j++) {
- assert_false(bitmap_get(bitmap, &binfo, j),
- "Bit should be unset");
- }
- free(bitmap);
- }
- }
-}
-TEST_END
-
-TEST_BEGIN(test_bitmap_set)
-{
- size_t i;
-
- for (i = 1; i <= BITMAP_MAXBITS; i++) {
- bitmap_info_t binfo;
- bitmap_info_init(&binfo, i);
- {
- size_t j;
- bitmap_t *bitmap = (bitmap_t *)malloc(
- bitmap_size(&binfo));
- bitmap_init(bitmap, &binfo);
-
- for (j = 0; j < i; j++)
- bitmap_set(bitmap, &binfo, j);
- assert_true(bitmap_full(bitmap, &binfo),
- "All bits should be set");
- free(bitmap);
- }
- }
-}
-TEST_END
-
-TEST_BEGIN(test_bitmap_unset)
-{
- size_t i;
-
- for (i = 1; i <= BITMAP_MAXBITS; i++) {
- bitmap_info_t binfo;
- bitmap_info_init(&binfo, i);
- {
- size_t j;
- bitmap_t *bitmap = (bitmap_t *)malloc(
- bitmap_size(&binfo));
- bitmap_init(bitmap, &binfo);
-
- for (j = 0; j < i; j++)
- bitmap_set(bitmap, &binfo, j);
- assert_true(bitmap_full(bitmap, &binfo),
- "All bits should be set");
- for (j = 0; j < i; j++)
- bitmap_unset(bitmap, &binfo, j);
- for (j = 0; j < i; j++)
- bitmap_set(bitmap, &binfo, j);
- assert_true(bitmap_full(bitmap, &binfo),
- "All bits should be set");
- free(bitmap);
- }
- }
-}
-TEST_END
-
-TEST_BEGIN(test_bitmap_sfu)
-{
- size_t i;
-
- for (i = 1; i <= BITMAP_MAXBITS; i++) {
- bitmap_info_t binfo;
- bitmap_info_init(&binfo, i);
- {
- size_t j;
- bitmap_t *bitmap = (bitmap_t *)malloc(
- bitmap_size(&binfo));
- bitmap_init(bitmap, &binfo);
-
- /* Iteratively set bits starting at the beginning. */
- for (j = 0; j < i; j++) {
- assert_zd_eq(bitmap_sfu(bitmap, &binfo), j,
- "First unset bit should be just after "
- "previous first unset bit");
- }
- assert_true(bitmap_full(bitmap, &binfo),
- "All bits should be set");
-
- /*
- * Iteratively unset bits starting at the end, and
- * verify that bitmap_sfu() reaches the unset bits.
- */
- for (j = i - 1; j < i; j--) { /* (i..0] */
- bitmap_unset(bitmap, &binfo, j);
- assert_zd_eq(bitmap_sfu(bitmap, &binfo), j,
- "First unset bit should the bit previously "
- "unset");
- bitmap_unset(bitmap, &binfo, j);
- }
- assert_false(bitmap_get(bitmap, &binfo, 0),
- "Bit should be unset");
-
- /*
- * Iteratively set bits starting at the beginning, and
- * verify that bitmap_sfu() looks past them.
- */
- for (j = 1; j < i; j++) {
- bitmap_set(bitmap, &binfo, j - 1);
- assert_zd_eq(bitmap_sfu(bitmap, &binfo), j,
- "First unset bit should be just after the "
- "bit previously set");
- bitmap_unset(bitmap, &binfo, j);
- }
- assert_zd_eq(bitmap_sfu(bitmap, &binfo), i - 1,
- "First unset bit should be the last bit");
- assert_true(bitmap_full(bitmap, &binfo),
- "All bits should be set");
- free(bitmap);
- }
- }
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_bitmap_size,
- test_bitmap_init,
- test_bitmap_set,
- test_bitmap_unset,
- test_bitmap_sfu));
-}
diff --git a/memory/jemalloc/src/test/unit/ckh.c b/memory/jemalloc/src/test/unit/ckh.c
deleted file mode 100644
index 2cbc22688..000000000
--- a/memory/jemalloc/src/test/unit/ckh.c
+++ /dev/null
@@ -1,214 +0,0 @@
-#include "test/jemalloc_test.h"
-
-TEST_BEGIN(test_new_delete)
-{
- tsd_t *tsd;
- ckh_t ckh;
-
- tsd = tsd_fetch();
-
- assert_false(ckh_new(tsd, &ckh, 2, ckh_string_hash,
- ckh_string_keycomp), "Unexpected ckh_new() error");
- ckh_delete(tsd, &ckh);
-
- assert_false(ckh_new(tsd, &ckh, 3, ckh_pointer_hash,
- ckh_pointer_keycomp), "Unexpected ckh_new() error");
- ckh_delete(tsd, &ckh);
-}
-TEST_END
-
-TEST_BEGIN(test_count_insert_search_remove)
-{
- tsd_t *tsd;
- ckh_t ckh;
- const char *strs[] = {
- "a string",
- "A string",
- "a string.",
- "A string."
- };
- const char *missing = "A string not in the hash table.";
- size_t i;
-
- tsd = tsd_fetch();
-
- assert_false(ckh_new(tsd, &ckh, 2, ckh_string_hash,
- ckh_string_keycomp), "Unexpected ckh_new() error");
- assert_zu_eq(ckh_count(&ckh), 0,
- "ckh_count() should return %zu, but it returned %zu", ZU(0),
- ckh_count(&ckh));
-
- /* Insert. */
- for (i = 0; i < sizeof(strs)/sizeof(const char *); i++) {
- ckh_insert(tsd, &ckh, strs[i], strs[i]);
- assert_zu_eq(ckh_count(&ckh), i+1,
- "ckh_count() should return %zu, but it returned %zu", i+1,
- ckh_count(&ckh));
- }
-
- /* Search. */
- for (i = 0; i < sizeof(strs)/sizeof(const char *); i++) {
- union {
- void *p;
- const char *s;
- } k, v;
- void **kp, **vp;
- const char *ks, *vs;
-
- kp = (i & 1) ? &k.p : NULL;
- vp = (i & 2) ? &v.p : NULL;
- k.p = NULL;
- v.p = NULL;
- assert_false(ckh_search(&ckh, strs[i], kp, vp),
- "Unexpected ckh_search() error");
-
- ks = (i & 1) ? strs[i] : (const char *)NULL;
- vs = (i & 2) ? strs[i] : (const char *)NULL;
- assert_ptr_eq((void *)ks, (void *)k.s, "Key mismatch, i=%zu",
- i);
- assert_ptr_eq((void *)vs, (void *)v.s, "Value mismatch, i=%zu",
- i);
- }
- assert_true(ckh_search(&ckh, missing, NULL, NULL),
- "Unexpected ckh_search() success");
-
- /* Remove. */
- for (i = 0; i < sizeof(strs)/sizeof(const char *); i++) {
- union {
- void *p;
- const char *s;
- } k, v;
- void **kp, **vp;
- const char *ks, *vs;
-
- kp = (i & 1) ? &k.p : NULL;
- vp = (i & 2) ? &v.p : NULL;
- k.p = NULL;
- v.p = NULL;
- assert_false(ckh_remove(tsd, &ckh, strs[i], kp, vp),
- "Unexpected ckh_remove() error");
-
- ks = (i & 1) ? strs[i] : (const char *)NULL;
- vs = (i & 2) ? strs[i] : (const char *)NULL;
- assert_ptr_eq((void *)ks, (void *)k.s, "Key mismatch, i=%zu",
- i);
- assert_ptr_eq((void *)vs, (void *)v.s, "Value mismatch, i=%zu",
- i);
- assert_zu_eq(ckh_count(&ckh),
- sizeof(strs)/sizeof(const char *) - i - 1,
- "ckh_count() should return %zu, but it returned %zu",
- sizeof(strs)/sizeof(const char *) - i - 1,
- ckh_count(&ckh));
- }
-
- ckh_delete(tsd, &ckh);
-}
-TEST_END
-
-TEST_BEGIN(test_insert_iter_remove)
-{
-#define NITEMS ZU(1000)
- tsd_t *tsd;
- ckh_t ckh;
- void **p[NITEMS];
- void *q, *r;
- size_t i;
-
- tsd = tsd_fetch();
-
- assert_false(ckh_new(tsd, &ckh, 2, ckh_pointer_hash,
- ckh_pointer_keycomp), "Unexpected ckh_new() error");
-
- for (i = 0; i < NITEMS; i++) {
- p[i] = mallocx(i+1, 0);
- assert_ptr_not_null(p[i], "Unexpected mallocx() failure");
- }
-
- for (i = 0; i < NITEMS; i++) {
- size_t j;
-
- for (j = i; j < NITEMS; j++) {
- assert_false(ckh_insert(tsd, &ckh, p[j], p[j]),
- "Unexpected ckh_insert() failure");
- assert_false(ckh_search(&ckh, p[j], &q, &r),
- "Unexpected ckh_search() failure");
- assert_ptr_eq(p[j], q, "Key pointer mismatch");
- assert_ptr_eq(p[j], r, "Value pointer mismatch");
- }
-
- assert_zu_eq(ckh_count(&ckh), NITEMS,
- "ckh_count() should return %zu, but it returned %zu",
- NITEMS, ckh_count(&ckh));
-
- for (j = i + 1; j < NITEMS; j++) {
- assert_false(ckh_search(&ckh, p[j], NULL, NULL),
- "Unexpected ckh_search() failure");
- assert_false(ckh_remove(tsd, &ckh, p[j], &q, &r),
- "Unexpected ckh_remove() failure");
- assert_ptr_eq(p[j], q, "Key pointer mismatch");
- assert_ptr_eq(p[j], r, "Value pointer mismatch");
- assert_true(ckh_search(&ckh, p[j], NULL, NULL),
- "Unexpected ckh_search() success");
- assert_true(ckh_remove(tsd, &ckh, p[j], &q, &r),
- "Unexpected ckh_remove() success");
- }
-
- {
- bool seen[NITEMS];
- size_t tabind;
-
- memset(seen, 0, sizeof(seen));
-
- for (tabind = 0; !ckh_iter(&ckh, &tabind, &q, &r);) {
- size_t k;
-
- assert_ptr_eq(q, r, "Key and val not equal");
-
- for (k = 0; k < NITEMS; k++) {
- if (p[k] == q) {
- assert_false(seen[k],
- "Item %zu already seen", k);
- seen[k] = true;
- break;
- }
- }
- }
-
- for (j = 0; j < i + 1; j++)
- assert_true(seen[j], "Item %zu not seen", j);
- for (; j < NITEMS; j++)
- assert_false(seen[j], "Item %zu seen", j);
- }
- }
-
- for (i = 0; i < NITEMS; i++) {
- assert_false(ckh_search(&ckh, p[i], NULL, NULL),
- "Unexpected ckh_search() failure");
- assert_false(ckh_remove(tsd, &ckh, p[i], &q, &r),
- "Unexpected ckh_remove() failure");
- assert_ptr_eq(p[i], q, "Key pointer mismatch");
- assert_ptr_eq(p[i], r, "Value pointer mismatch");
- assert_true(ckh_search(&ckh, p[i], NULL, NULL),
- "Unexpected ckh_search() success");
- assert_true(ckh_remove(tsd, &ckh, p[i], &q, &r),
- "Unexpected ckh_remove() success");
- dallocx(p[i], 0);
- }
-
- assert_zu_eq(ckh_count(&ckh), 0,
- "ckh_count() should return %zu, but it returned %zu",
- ZU(0), ckh_count(&ckh));
- ckh_delete(tsd, &ckh);
-#undef NITEMS
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_new_delete,
- test_count_insert_search_remove,
- test_insert_iter_remove));
-}
diff --git a/memory/jemalloc/src/test/unit/decay.c b/memory/jemalloc/src/test/unit/decay.c
deleted file mode 100644
index e169ae24e..000000000
--- a/memory/jemalloc/src/test/unit/decay.c
+++ /dev/null
@@ -1,374 +0,0 @@
-#include "test/jemalloc_test.h"
-
-const char *malloc_conf = "purge:decay,decay_time:1";
-
-static nstime_monotonic_t *nstime_monotonic_orig;
-static nstime_update_t *nstime_update_orig;
-
-static unsigned nupdates_mock;
-static nstime_t time_mock;
-static bool monotonic_mock;
-
-static bool
-nstime_monotonic_mock(void)
-{
-
- return (monotonic_mock);
-}
-
-static bool
-nstime_update_mock(nstime_t *time)
-{
-
- nupdates_mock++;
- if (monotonic_mock)
- nstime_copy(time, &time_mock);
- return (!monotonic_mock);
-}
-
-TEST_BEGIN(test_decay_ticks)
-{
- ticker_t *decay_ticker;
- unsigned tick0, tick1;
- size_t sz, huge0, large0;
- void *p;
-
- test_skip_if(opt_purge != purge_mode_decay);
-
- decay_ticker = decay_ticker_get(tsd_fetch(), 0);
- assert_ptr_not_null(decay_ticker,
- "Unexpected failure getting decay ticker");
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("arenas.hchunk.0.size", &huge0, &sz, NULL, 0), 0,
- "Unexpected mallctl failure");
- assert_d_eq(mallctl("arenas.lrun.0.size", &large0, &sz, NULL, 0), 0,
- "Unexpected mallctl failure");
-
- /*
- * Test the standard APIs using a huge size class, since we can't
- * control tcache interactions (except by completely disabling tcache
- * for the entire test program).
- */
-
- /* malloc(). */
- tick0 = ticker_read(decay_ticker);
- p = malloc(huge0);
- assert_ptr_not_null(p, "Unexpected malloc() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0, "Expected ticker to tick during malloc()");
- /* free(). */
- tick0 = ticker_read(decay_ticker);
- free(p);
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0, "Expected ticker to tick during free()");
-
- /* calloc(). */
- tick0 = ticker_read(decay_ticker);
- p = calloc(1, huge0);
- assert_ptr_not_null(p, "Unexpected calloc() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0, "Expected ticker to tick during calloc()");
- free(p);
-
- /* posix_memalign(). */
- tick0 = ticker_read(decay_ticker);
- assert_d_eq(posix_memalign(&p, sizeof(size_t), huge0), 0,
- "Unexpected posix_memalign() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during posix_memalign()");
- free(p);
-
- /* aligned_alloc(). */
- tick0 = ticker_read(decay_ticker);
- p = aligned_alloc(sizeof(size_t), huge0);
- assert_ptr_not_null(p, "Unexpected aligned_alloc() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during aligned_alloc()");
- free(p);
-
- /* realloc(). */
- /* Allocate. */
- tick0 = ticker_read(decay_ticker);
- p = realloc(NULL, huge0);
- assert_ptr_not_null(p, "Unexpected realloc() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0, "Expected ticker to tick during realloc()");
- /* Reallocate. */
- tick0 = ticker_read(decay_ticker);
- p = realloc(p, huge0);
- assert_ptr_not_null(p, "Unexpected realloc() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0, "Expected ticker to tick during realloc()");
- /* Deallocate. */
- tick0 = ticker_read(decay_ticker);
- realloc(p, 0);
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0, "Expected ticker to tick during realloc()");
-
- /*
- * Test the *allocx() APIs using huge, large, and small size classes,
- * with tcache explicitly disabled.
- */
- {
- unsigned i;
- size_t allocx_sizes[3];
- allocx_sizes[0] = huge0;
- allocx_sizes[1] = large0;
- allocx_sizes[2] = 1;
-
- for (i = 0; i < sizeof(allocx_sizes) / sizeof(size_t); i++) {
- sz = allocx_sizes[i];
-
- /* mallocx(). */
- tick0 = ticker_read(decay_ticker);
- p = mallocx(sz, MALLOCX_TCACHE_NONE);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during mallocx() (sz=%zu)",
- sz);
- /* rallocx(). */
- tick0 = ticker_read(decay_ticker);
- p = rallocx(p, sz, MALLOCX_TCACHE_NONE);
- assert_ptr_not_null(p, "Unexpected rallocx() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during rallocx() (sz=%zu)",
- sz);
- /* xallocx(). */
- tick0 = ticker_read(decay_ticker);
- xallocx(p, sz, 0, MALLOCX_TCACHE_NONE);
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during xallocx() (sz=%zu)",
- sz);
- /* dallocx(). */
- tick0 = ticker_read(decay_ticker);
- dallocx(p, MALLOCX_TCACHE_NONE);
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during dallocx() (sz=%zu)",
- sz);
- /* sdallocx(). */
- p = mallocx(sz, MALLOCX_TCACHE_NONE);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- tick0 = ticker_read(decay_ticker);
- sdallocx(p, sz, MALLOCX_TCACHE_NONE);
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during sdallocx() "
- "(sz=%zu)", sz);
- }
- }
-
- /*
- * Test tcache fill/flush interactions for large and small size classes,
- * using an explicit tcache.
- */
- if (config_tcache) {
- unsigned tcache_ind, i;
- size_t tcache_sizes[2];
- tcache_sizes[0] = large0;
- tcache_sizes[1] = 1;
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("tcache.create", &tcache_ind, &sz, NULL, 0),
- 0, "Unexpected mallctl failure");
-
- for (i = 0; i < sizeof(tcache_sizes) / sizeof(size_t); i++) {
- sz = tcache_sizes[i];
-
- /* tcache fill. */
- tick0 = ticker_read(decay_ticker);
- p = mallocx(sz, MALLOCX_TCACHE(tcache_ind));
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during tcache fill "
- "(sz=%zu)", sz);
- /* tcache flush. */
- dallocx(p, MALLOCX_TCACHE(tcache_ind));
- tick0 = ticker_read(decay_ticker);
- assert_d_eq(mallctl("tcache.flush", NULL, NULL,
- &tcache_ind, sizeof(unsigned)), 0,
- "Unexpected mallctl failure");
- tick1 = ticker_read(decay_ticker);
- assert_u32_ne(tick1, tick0,
- "Expected ticker to tick during tcache flush "
- "(sz=%zu)", sz);
- }
- }
-}
-TEST_END
-
-TEST_BEGIN(test_decay_ticker)
-{
-#define NPS 1024
- int flags = (MALLOCX_ARENA(0) | MALLOCX_TCACHE_NONE);
- void *ps[NPS];
- uint64_t epoch;
- uint64_t npurge0 = 0;
- uint64_t npurge1 = 0;
- size_t sz, large;
- unsigned i, nupdates0;
- nstime_t time, decay_time, deadline;
-
- test_skip_if(opt_purge != purge_mode_decay);
-
- /*
- * Allocate a bunch of large objects, pause the clock, deallocate the
- * objects, restore the clock, then [md]allocx() in a tight loop to
- * verify the ticker triggers purging.
- */
-
- if (config_tcache) {
- size_t tcache_max;
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("arenas.tcache_max", &tcache_max, &sz, NULL,
- 0), 0, "Unexpected mallctl failure");
- large = nallocx(tcache_max + 1, flags);
- } else {
- sz = sizeof(size_t);
- assert_d_eq(mallctl("arenas.lrun.0.size", &large, &sz, NULL, 0),
- 0, "Unexpected mallctl failure");
- }
-
- assert_d_eq(mallctl("arena.0.purge", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl failure");
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(uint64_t)), 0,
- "Unexpected mallctl failure");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.npurge", &npurge0, &sz, NULL, 0),
- config_stats ? 0 : ENOENT, "Unexpected mallctl result");
-
- for (i = 0; i < NPS; i++) {
- ps[i] = mallocx(large, flags);
- assert_ptr_not_null(ps[i], "Unexpected mallocx() failure");
- }
-
- nupdates_mock = 0;
- nstime_init(&time_mock, 0);
- nstime_update(&time_mock);
- monotonic_mock = true;
-
- nstime_monotonic_orig = nstime_monotonic;
- nstime_update_orig = nstime_update;
- nstime_monotonic = nstime_monotonic_mock;
- nstime_update = nstime_update_mock;
-
- for (i = 0; i < NPS; i++) {
- dallocx(ps[i], flags);
- nupdates0 = nupdates_mock;
- assert_d_eq(mallctl("arena.0.decay", NULL, NULL, NULL, 0), 0,
- "Unexpected arena.0.decay failure");
- assert_u_gt(nupdates_mock, nupdates0,
- "Expected nstime_update() to be called");
- }
-
- nstime_monotonic = nstime_monotonic_orig;
- nstime_update = nstime_update_orig;
-
- nstime_init(&time, 0);
- nstime_update(&time);
- nstime_init2(&decay_time, opt_decay_time, 0);
- nstime_copy(&deadline, &time);
- nstime_add(&deadline, &decay_time);
- do {
- for (i = 0; i < DECAY_NTICKS_PER_UPDATE / 2; i++) {
- void *p = mallocx(1, flags);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- dallocx(p, flags);
- }
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch,
- sizeof(uint64_t)), 0, "Unexpected mallctl failure");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.npurge", &npurge1, &sz,
- NULL, 0), config_stats ? 0 : ENOENT,
- "Unexpected mallctl result");
-
- nstime_update(&time);
- } while (nstime_compare(&time, &deadline) <= 0 && npurge1 == npurge0);
-
- if (config_stats)
- assert_u64_gt(npurge1, npurge0, "Expected purging to occur");
-#undef NPS
-}
-TEST_END
-
-TEST_BEGIN(test_decay_nonmonotonic)
-{
-#define NPS (SMOOTHSTEP_NSTEPS + 1)
- int flags = (MALLOCX_ARENA(0) | MALLOCX_TCACHE_NONE);
- void *ps[NPS];
- uint64_t epoch;
- uint64_t npurge0 = 0;
- uint64_t npurge1 = 0;
- size_t sz, large0;
- unsigned i, nupdates0;
-
- test_skip_if(opt_purge != purge_mode_decay);
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("arenas.lrun.0.size", &large0, &sz, NULL, 0), 0,
- "Unexpected mallctl failure");
-
- assert_d_eq(mallctl("arena.0.purge", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl failure");
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(uint64_t)), 0,
- "Unexpected mallctl failure");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.npurge", &npurge0, &sz, NULL, 0),
- config_stats ? 0 : ENOENT, "Unexpected mallctl result");
-
- nupdates_mock = 0;
- nstime_init(&time_mock, 0);
- nstime_update(&time_mock);
- monotonic_mock = false;
-
- nstime_monotonic_orig = nstime_monotonic;
- nstime_update_orig = nstime_update;
- nstime_monotonic = nstime_monotonic_mock;
- nstime_update = nstime_update_mock;
-
- for (i = 0; i < NPS; i++) {
- ps[i] = mallocx(large0, flags);
- assert_ptr_not_null(ps[i], "Unexpected mallocx() failure");
- }
-
- for (i = 0; i < NPS; i++) {
- dallocx(ps[i], flags);
- nupdates0 = nupdates_mock;
- assert_d_eq(mallctl("arena.0.decay", NULL, NULL, NULL, 0), 0,
- "Unexpected arena.0.decay failure");
- assert_u_gt(nupdates_mock, nupdates0,
- "Expected nstime_update() to be called");
- }
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(uint64_t)), 0,
- "Unexpected mallctl failure");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.npurge", &npurge1, &sz, NULL, 0),
- config_stats ? 0 : ENOENT, "Unexpected mallctl result");
-
- if (config_stats)
- assert_u64_eq(npurge0, npurge1, "Unexpected purging occurred");
-
- nstime_monotonic = nstime_monotonic_orig;
- nstime_update = nstime_update_orig;
-#undef NPS
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_decay_ticks,
- test_decay_ticker,
- test_decay_nonmonotonic));
-}
diff --git a/memory/jemalloc/src/test/unit/fork.c b/memory/jemalloc/src/test/unit/fork.c
deleted file mode 100644
index c530797c4..000000000
--- a/memory/jemalloc/src/test/unit/fork.c
+++ /dev/null
@@ -1,64 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifndef _WIN32
-#include <sys/wait.h>
-#endif
-
-TEST_BEGIN(test_fork)
-{
-#ifndef _WIN32
- void *p;
- pid_t pid;
-
- p = malloc(1);
- assert_ptr_not_null(p, "Unexpected malloc() failure");
-
- pid = fork();
-
- free(p);
-
- p = malloc(64);
- assert_ptr_not_null(p, "Unexpected malloc() failure");
- free(p);
-
- if (pid == -1) {
- /* Error. */
- test_fail("Unexpected fork() failure");
- } else if (pid == 0) {
- /* Child. */
- _exit(0);
- } else {
- int status;
-
- /* Parent. */
- while (true) {
- if (waitpid(pid, &status, 0) == -1)
- test_fail("Unexpected waitpid() failure");
- if (WIFSIGNALED(status)) {
- test_fail("Unexpected child termination due to "
- "signal %d", WTERMSIG(status));
- break;
- }
- if (WIFEXITED(status)) {
- if (WEXITSTATUS(status) != 0) {
- test_fail(
- "Unexpected child exit value %d",
- WEXITSTATUS(status));
- }
- break;
- }
- }
- }
-#else
- test_skip("fork(2) is irrelevant to Windows");
-#endif
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_fork));
-}
diff --git a/memory/jemalloc/src/test/unit/hash.c b/memory/jemalloc/src/test/unit/hash.c
deleted file mode 100644
index 010c9d76f..000000000
--- a/memory/jemalloc/src/test/unit/hash.c
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * This file is based on code that is part of SMHasher
- * (https://code.google.com/p/smhasher/), and is subject to the MIT license
- * (http://www.opensource.org/licenses/mit-license.php). Both email addresses
- * associated with the source code's revision history belong to Austin Appleby,
- * and the revision history ranges from 2010 to 2012. Therefore the copyright
- * and license are here taken to be:
- *
- * Copyright (c) 2010-2012 Austin Appleby
- *
- * 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.
- */
-
-#include "test/jemalloc_test.h"
-
-typedef enum {
- hash_variant_x86_32,
- hash_variant_x86_128,
- hash_variant_x64_128
-} hash_variant_t;
-
-static int
-hash_variant_bits(hash_variant_t variant)
-{
-
- switch (variant) {
- case hash_variant_x86_32: return (32);
- case hash_variant_x86_128: return (128);
- case hash_variant_x64_128: return (128);
- default: not_reached();
- }
-}
-
-static const char *
-hash_variant_string(hash_variant_t variant)
-{
-
- switch (variant) {
- case hash_variant_x86_32: return ("hash_x86_32");
- case hash_variant_x86_128: return ("hash_x86_128");
- case hash_variant_x64_128: return ("hash_x64_128");
- default: not_reached();
- }
-}
-
-#define KEY_SIZE 256
-static void
-hash_variant_verify_key(hash_variant_t variant, uint8_t *key)
-{
- const int hashbytes = hash_variant_bits(variant) / 8;
- const int hashes_size = hashbytes * 256;
- VARIABLE_ARRAY(uint8_t, hashes, hashes_size);
- VARIABLE_ARRAY(uint8_t, final, hashbytes);
- unsigned i;
- uint32_t computed, expected;
-
- memset(key, 0, KEY_SIZE);
- memset(hashes, 0, hashes_size);
- memset(final, 0, hashbytes);
-
- /*
- * Hash keys of the form {0}, {0,1}, {0,1,2}, ..., {0,1,...,255} as the
- * seed.
- */
- for (i = 0; i < 256; i++) {
- key[i] = (uint8_t)i;
- switch (variant) {
- case hash_variant_x86_32: {
- uint32_t out;
- out = hash_x86_32(key, i, 256-i);
- memcpy(&hashes[i*hashbytes], &out, hashbytes);
- break;
- } case hash_variant_x86_128: {
- uint64_t out[2];
- hash_x86_128(key, i, 256-i, out);
- memcpy(&hashes[i*hashbytes], out, hashbytes);
- break;
- } case hash_variant_x64_128: {
- uint64_t out[2];
- hash_x64_128(key, i, 256-i, out);
- memcpy(&hashes[i*hashbytes], out, hashbytes);
- break;
- } default: not_reached();
- }
- }
-
- /* Hash the result array. */
- switch (variant) {
- case hash_variant_x86_32: {
- uint32_t out = hash_x86_32(hashes, hashes_size, 0);
- memcpy(final, &out, sizeof(out));
- break;
- } case hash_variant_x86_128: {
- uint64_t out[2];
- hash_x86_128(hashes, hashes_size, 0, out);
- memcpy(final, out, sizeof(out));
- break;
- } case hash_variant_x64_128: {
- uint64_t out[2];
- hash_x64_128(hashes, hashes_size, 0, out);
- memcpy(final, out, sizeof(out));
- break;
- } default: not_reached();
- }
-
- computed = (final[0] << 0) | (final[1] << 8) | (final[2] << 16) |
- (final[3] << 24);
-
- switch (variant) {
-#ifdef JEMALLOC_BIG_ENDIAN
- case hash_variant_x86_32: expected = 0x6213303eU; break;
- case hash_variant_x86_128: expected = 0x266820caU; break;
- case hash_variant_x64_128: expected = 0xcc622b6fU; break;
-#else
- case hash_variant_x86_32: expected = 0xb0f57ee3U; break;
- case hash_variant_x86_128: expected = 0xb3ece62aU; break;
- case hash_variant_x64_128: expected = 0x6384ba69U; break;
-#endif
- default: not_reached();
- }
-
- assert_u32_eq(computed, expected,
- "Hash mismatch for %s(): expected %#x but got %#x",
- hash_variant_string(variant), expected, computed);
-}
-
-static void
-hash_variant_verify(hash_variant_t variant)
-{
-#define MAX_ALIGN 16
- uint8_t key[KEY_SIZE + (MAX_ALIGN - 1)];
- unsigned i;
-
- for (i = 0; i < MAX_ALIGN; i++)
- hash_variant_verify_key(variant, &key[i]);
-#undef MAX_ALIGN
-}
-#undef KEY_SIZE
-
-TEST_BEGIN(test_hash_x86_32)
-{
-
- hash_variant_verify(hash_variant_x86_32);
-}
-TEST_END
-
-TEST_BEGIN(test_hash_x86_128)
-{
-
- hash_variant_verify(hash_variant_x86_128);
-}
-TEST_END
-
-TEST_BEGIN(test_hash_x64_128)
-{
-
- hash_variant_verify(hash_variant_x64_128);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_hash_x86_32,
- test_hash_x86_128,
- test_hash_x64_128));
-}
diff --git a/memory/jemalloc/src/test/unit/junk.c b/memory/jemalloc/src/test/unit/junk.c
deleted file mode 100644
index 460bd524d..000000000
--- a/memory/jemalloc/src/test/unit/junk.c
+++ /dev/null
@@ -1,253 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_FILL
-# ifndef JEMALLOC_TEST_JUNK_OPT
-# define JEMALLOC_TEST_JUNK_OPT "junk:true"
-# endif
-const char *malloc_conf =
- "abort:false,zero:false,redzone:true,quarantine:0," JEMALLOC_TEST_JUNK_OPT;
-#endif
-
-static arena_dalloc_junk_small_t *arena_dalloc_junk_small_orig;
-static arena_dalloc_junk_large_t *arena_dalloc_junk_large_orig;
-static huge_dalloc_junk_t *huge_dalloc_junk_orig;
-static void *watch_for_junking;
-static bool saw_junking;
-
-static void
-watch_junking(void *p)
-{
-
- watch_for_junking = p;
- saw_junking = false;
-}
-
-static void
-arena_dalloc_junk_small_intercept(void *ptr, arena_bin_info_t *bin_info)
-{
- size_t i;
-
- arena_dalloc_junk_small_orig(ptr, bin_info);
- for (i = 0; i < bin_info->reg_size; i++) {
- assert_u_eq(((uint8_t *)ptr)[i], JEMALLOC_FREE_JUNK,
- "Missing junk fill for byte %zu/%zu of deallocated region",
- i, bin_info->reg_size);
- }
- if (ptr == watch_for_junking)
- saw_junking = true;
-}
-
-static void
-arena_dalloc_junk_large_intercept(void *ptr, size_t usize)
-{
- size_t i;
-
- arena_dalloc_junk_large_orig(ptr, usize);
- for (i = 0; i < usize; i++) {
- assert_u_eq(((uint8_t *)ptr)[i], JEMALLOC_FREE_JUNK,
- "Missing junk fill for byte %zu/%zu of deallocated region",
- i, usize);
- }
- if (ptr == watch_for_junking)
- saw_junking = true;
-}
-
-static void
-huge_dalloc_junk_intercept(void *ptr, size_t usize)
-{
-
- huge_dalloc_junk_orig(ptr, usize);
- /*
- * The conditions under which junk filling actually occurs are nuanced
- * enough that it doesn't make sense to duplicate the decision logic in
- * test code, so don't actually check that the region is junk-filled.
- */
- if (ptr == watch_for_junking)
- saw_junking = true;
-}
-
-static void
-test_junk(size_t sz_min, size_t sz_max)
-{
- uint8_t *s;
- size_t sz_prev, sz, i;
-
- if (opt_junk_free) {
- arena_dalloc_junk_small_orig = arena_dalloc_junk_small;
- arena_dalloc_junk_small = arena_dalloc_junk_small_intercept;
- arena_dalloc_junk_large_orig = arena_dalloc_junk_large;
- arena_dalloc_junk_large = arena_dalloc_junk_large_intercept;
- huge_dalloc_junk_orig = huge_dalloc_junk;
- huge_dalloc_junk = huge_dalloc_junk_intercept;
- }
-
- sz_prev = 0;
- s = (uint8_t *)mallocx(sz_min, 0);
- assert_ptr_not_null((void *)s, "Unexpected mallocx() failure");
-
- for (sz = sallocx(s, 0); sz <= sz_max;
- sz_prev = sz, sz = sallocx(s, 0)) {
- if (sz_prev > 0) {
- assert_u_eq(s[0], 'a',
- "Previously allocated byte %zu/%zu is corrupted",
- ZU(0), sz_prev);
- assert_u_eq(s[sz_prev-1], 'a',
- "Previously allocated byte %zu/%zu is corrupted",
- sz_prev-1, sz_prev);
- }
-
- for (i = sz_prev; i < sz; i++) {
- if (opt_junk_alloc) {
- assert_u_eq(s[i], JEMALLOC_ALLOC_JUNK,
- "Newly allocated byte %zu/%zu isn't "
- "junk-filled", i, sz);
- }
- s[i] = 'a';
- }
-
- if (xallocx(s, sz+1, 0, 0) == sz) {
- watch_junking(s);
- s = (uint8_t *)rallocx(s, sz+1, 0);
- assert_ptr_not_null((void *)s,
- "Unexpected rallocx() failure");
- assert_true(!opt_junk_free || saw_junking,
- "Expected region of size %zu to be junk-filled",
- sz);
- }
- }
-
- watch_junking(s);
- dallocx(s, 0);
- assert_true(!opt_junk_free || saw_junking,
- "Expected region of size %zu to be junk-filled", sz);
-
- if (opt_junk_free) {
- arena_dalloc_junk_small = arena_dalloc_junk_small_orig;
- arena_dalloc_junk_large = arena_dalloc_junk_large_orig;
- huge_dalloc_junk = huge_dalloc_junk_orig;
- }
-}
-
-TEST_BEGIN(test_junk_small)
-{
-
- test_skip_if(!config_fill);
- test_junk(1, SMALL_MAXCLASS-1);
-}
-TEST_END
-
-TEST_BEGIN(test_junk_large)
-{
-
- test_skip_if(!config_fill);
- test_junk(SMALL_MAXCLASS+1, large_maxclass);
-}
-TEST_END
-
-TEST_BEGIN(test_junk_huge)
-{
-
- test_skip_if(!config_fill);
- test_junk(large_maxclass+1, chunksize*2);
-}
-TEST_END
-
-arena_ralloc_junk_large_t *arena_ralloc_junk_large_orig;
-static void *most_recently_trimmed;
-
-static size_t
-shrink_size(size_t size)
-{
- size_t shrink_size;
-
- for (shrink_size = size - 1; nallocx(shrink_size, 0) == size;
- shrink_size--)
- ; /* Do nothing. */
-
- return (shrink_size);
-}
-
-static void
-arena_ralloc_junk_large_intercept(void *ptr, size_t old_usize, size_t usize)
-{
-
- arena_ralloc_junk_large_orig(ptr, old_usize, usize);
- assert_zu_eq(old_usize, large_maxclass, "Unexpected old_usize");
- assert_zu_eq(usize, shrink_size(large_maxclass), "Unexpected usize");
- most_recently_trimmed = ptr;
-}
-
-TEST_BEGIN(test_junk_large_ralloc_shrink)
-{
- void *p1, *p2;
-
- p1 = mallocx(large_maxclass, 0);
- assert_ptr_not_null(p1, "Unexpected mallocx() failure");
-
- arena_ralloc_junk_large_orig = arena_ralloc_junk_large;
- arena_ralloc_junk_large = arena_ralloc_junk_large_intercept;
-
- p2 = rallocx(p1, shrink_size(large_maxclass), 0);
- assert_ptr_eq(p1, p2, "Unexpected move during shrink");
-
- arena_ralloc_junk_large = arena_ralloc_junk_large_orig;
-
- assert_ptr_eq(most_recently_trimmed, p1,
- "Expected trimmed portion of region to be junk-filled");
-}
-TEST_END
-
-static bool detected_redzone_corruption;
-
-static void
-arena_redzone_corruption_replacement(void *ptr, size_t usize, bool after,
- size_t offset, uint8_t byte)
-{
-
- detected_redzone_corruption = true;
-}
-
-TEST_BEGIN(test_junk_redzone)
-{
- char *s;
- arena_redzone_corruption_t *arena_redzone_corruption_orig;
-
- test_skip_if(!config_fill);
- test_skip_if(!opt_junk_alloc || !opt_junk_free);
-
- arena_redzone_corruption_orig = arena_redzone_corruption;
- arena_redzone_corruption = arena_redzone_corruption_replacement;
-
- /* Test underflow. */
- detected_redzone_corruption = false;
- s = (char *)mallocx(1, 0);
- assert_ptr_not_null((void *)s, "Unexpected mallocx() failure");
- s[-1] = 0xbb;
- dallocx(s, 0);
- assert_true(detected_redzone_corruption,
- "Did not detect redzone corruption");
-
- /* Test overflow. */
- detected_redzone_corruption = false;
- s = (char *)mallocx(1, 0);
- assert_ptr_not_null((void *)s, "Unexpected mallocx() failure");
- s[sallocx(s, 0)] = 0xbb;
- dallocx(s, 0);
- assert_true(detected_redzone_corruption,
- "Did not detect redzone corruption");
-
- arena_redzone_corruption = arena_redzone_corruption_orig;
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_junk_small,
- test_junk_large,
- test_junk_huge,
- test_junk_large_ralloc_shrink,
- test_junk_redzone));
-}
diff --git a/memory/jemalloc/src/test/unit/junk_alloc.c b/memory/jemalloc/src/test/unit/junk_alloc.c
deleted file mode 100644
index a5895b5c0..000000000
--- a/memory/jemalloc/src/test/unit/junk_alloc.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define JEMALLOC_TEST_JUNK_OPT "junk:alloc"
-#include "junk.c"
-#undef JEMALLOC_TEST_JUNK_OPT
diff --git a/memory/jemalloc/src/test/unit/junk_free.c b/memory/jemalloc/src/test/unit/junk_free.c
deleted file mode 100644
index bb5183c90..000000000
--- a/memory/jemalloc/src/test/unit/junk_free.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define JEMALLOC_TEST_JUNK_OPT "junk:free"
-#include "junk.c"
-#undef JEMALLOC_TEST_JUNK_OPT
diff --git a/memory/jemalloc/src/test/unit/lg_chunk.c b/memory/jemalloc/src/test/unit/lg_chunk.c
deleted file mode 100644
index 7e5df3814..000000000
--- a/memory/jemalloc/src/test/unit/lg_chunk.c
+++ /dev/null
@@ -1,26 +0,0 @@
-#include "test/jemalloc_test.h"
-
-/*
- * Make sure that opt.lg_chunk clamping is sufficient. In practice, this test
- * program will fail a debug assertion during initialization and abort (rather
- * than the test soft-failing) if clamping is insufficient.
- */
-const char *malloc_conf = "lg_chunk:0";
-
-TEST_BEGIN(test_lg_chunk_clamp)
-{
- void *p;
-
- p = mallocx(1, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- dallocx(p, 0);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_lg_chunk_clamp));
-}
diff --git a/memory/jemalloc/src/test/unit/mallctl.c b/memory/jemalloc/src/test/unit/mallctl.c
deleted file mode 100644
index 69f8c20c1..000000000
--- a/memory/jemalloc/src/test/unit/mallctl.c
+++ /dev/null
@@ -1,731 +0,0 @@
-#include "test/jemalloc_test.h"
-
-TEST_BEGIN(test_mallctl_errors)
-{
- uint64_t epoch;
- size_t sz;
-
- assert_d_eq(mallctl("no_such_name", NULL, NULL, NULL, 0), ENOENT,
- "mallctl() should return ENOENT for non-existent names");
-
- assert_d_eq(mallctl("version", NULL, NULL, "0.0.0", strlen("0.0.0")),
- EPERM, "mallctl() should return EPERM on attempt to write "
- "read-only value");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)-1),
- EINVAL, "mallctl() should return EINVAL for input size mismatch");
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)+1),
- EINVAL, "mallctl() should return EINVAL for input size mismatch");
-
- sz = sizeof(epoch)-1;
- assert_d_eq(mallctl("epoch", &epoch, &sz, NULL, 0), EINVAL,
- "mallctl() should return EINVAL for output size mismatch");
- sz = sizeof(epoch)+1;
- assert_d_eq(mallctl("epoch", &epoch, &sz, NULL, 0), EINVAL,
- "mallctl() should return EINVAL for output size mismatch");
-}
-TEST_END
-
-TEST_BEGIN(test_mallctlnametomib_errors)
-{
- size_t mib[1];
- size_t miblen;
-
- miblen = sizeof(mib)/sizeof(size_t);
- assert_d_eq(mallctlnametomib("no_such_name", mib, &miblen), ENOENT,
- "mallctlnametomib() should return ENOENT for non-existent names");
-}
-TEST_END
-
-TEST_BEGIN(test_mallctlbymib_errors)
-{
- uint64_t epoch;
- size_t sz;
- size_t mib[1];
- size_t miblen;
-
- miblen = sizeof(mib)/sizeof(size_t);
- assert_d_eq(mallctlnametomib("version", mib, &miblen), 0,
- "Unexpected mallctlnametomib() failure");
-
- assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, "0.0.0",
- strlen("0.0.0")), EPERM, "mallctl() should return EPERM on "
- "attempt to write read-only value");
-
- miblen = sizeof(mib)/sizeof(size_t);
- assert_d_eq(mallctlnametomib("epoch", mib, &miblen), 0,
- "Unexpected mallctlnametomib() failure");
-
- assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, &epoch,
- sizeof(epoch)-1), EINVAL,
- "mallctlbymib() should return EINVAL for input size mismatch");
- assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, &epoch,
- sizeof(epoch)+1), EINVAL,
- "mallctlbymib() should return EINVAL for input size mismatch");
-
- sz = sizeof(epoch)-1;
- assert_d_eq(mallctlbymib(mib, miblen, &epoch, &sz, NULL, 0), EINVAL,
- "mallctlbymib() should return EINVAL for output size mismatch");
- sz = sizeof(epoch)+1;
- assert_d_eq(mallctlbymib(mib, miblen, &epoch, &sz, NULL, 0), EINVAL,
- "mallctlbymib() should return EINVAL for output size mismatch");
-}
-TEST_END
-
-TEST_BEGIN(test_mallctl_read_write)
-{
- uint64_t old_epoch, new_epoch;
- size_t sz = sizeof(old_epoch);
-
- /* Blind. */
- assert_d_eq(mallctl("epoch", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_zu_eq(sz, sizeof(old_epoch), "Unexpected output size");
-
- /* Read. */
- assert_d_eq(mallctl("epoch", &old_epoch, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_zu_eq(sz, sizeof(old_epoch), "Unexpected output size");
-
- /* Write. */
- assert_d_eq(mallctl("epoch", NULL, NULL, &new_epoch, sizeof(new_epoch)),
- 0, "Unexpected mallctl() failure");
- assert_zu_eq(sz, sizeof(old_epoch), "Unexpected output size");
-
- /* Read+write. */
- assert_d_eq(mallctl("epoch", &old_epoch, &sz, &new_epoch,
- sizeof(new_epoch)), 0, "Unexpected mallctl() failure");
- assert_zu_eq(sz, sizeof(old_epoch), "Unexpected output size");
-}
-TEST_END
-
-TEST_BEGIN(test_mallctlnametomib_short_mib)
-{
- size_t mib[4];
- size_t miblen;
-
- miblen = 3;
- mib[3] = 42;
- assert_d_eq(mallctlnametomib("arenas.bin.0.nregs", mib, &miblen), 0,
- "Unexpected mallctlnametomib() failure");
- assert_zu_eq(miblen, 3, "Unexpected mib output length");
- assert_zu_eq(mib[3], 42,
- "mallctlnametomib() wrote past the end of the input mib");
-}
-TEST_END
-
-TEST_BEGIN(test_mallctl_config)
-{
-
-#define TEST_MALLCTL_CONFIG(config, t) do { \
- t oldval; \
- size_t sz = sizeof(oldval); \
- assert_d_eq(mallctl("config."#config, &oldval, &sz, NULL, 0), \
- 0, "Unexpected mallctl() failure"); \
- assert_b_eq(oldval, config_##config, "Incorrect config value"); \
- assert_zu_eq(sz, sizeof(oldval), "Unexpected output size"); \
-} while (0)
-
- TEST_MALLCTL_CONFIG(cache_oblivious, bool);
- TEST_MALLCTL_CONFIG(debug, bool);
- TEST_MALLCTL_CONFIG(fill, bool);
- TEST_MALLCTL_CONFIG(lazy_lock, bool);
- TEST_MALLCTL_CONFIG(malloc_conf, const char *);
- TEST_MALLCTL_CONFIG(munmap, bool);
- TEST_MALLCTL_CONFIG(prof, bool);
- TEST_MALLCTL_CONFIG(prof_libgcc, bool);
- TEST_MALLCTL_CONFIG(prof_libunwind, bool);
- TEST_MALLCTL_CONFIG(stats, bool);
- TEST_MALLCTL_CONFIG(tcache, bool);
- TEST_MALLCTL_CONFIG(tls, bool);
- TEST_MALLCTL_CONFIG(utrace, bool);
- TEST_MALLCTL_CONFIG(valgrind, bool);
- TEST_MALLCTL_CONFIG(xmalloc, bool);
-
-#undef TEST_MALLCTL_CONFIG
-}
-TEST_END
-
-TEST_BEGIN(test_mallctl_opt)
-{
- bool config_always = true;
-
-#define TEST_MALLCTL_OPT(t, opt, config) do { \
- t oldval; \
- size_t sz = sizeof(oldval); \
- int expected = config_##config ? 0 : ENOENT; \
- int result = mallctl("opt."#opt, &oldval, &sz, NULL, 0); \
- assert_d_eq(result, expected, \
- "Unexpected mallctl() result for opt."#opt); \
- assert_zu_eq(sz, sizeof(oldval), "Unexpected output size"); \
-} while (0)
-
- TEST_MALLCTL_OPT(bool, abort, always);
- TEST_MALLCTL_OPT(size_t, lg_chunk, always);
- TEST_MALLCTL_OPT(const char *, dss, always);
- TEST_MALLCTL_OPT(unsigned, narenas, always);
- TEST_MALLCTL_OPT(const char *, purge, always);
- TEST_MALLCTL_OPT(ssize_t, lg_dirty_mult, always);
- TEST_MALLCTL_OPT(ssize_t, decay_time, always);
- TEST_MALLCTL_OPT(bool, stats_print, always);
- TEST_MALLCTL_OPT(const char *, junk, fill);
- TEST_MALLCTL_OPT(size_t, quarantine, fill);
- TEST_MALLCTL_OPT(bool, redzone, fill);
- TEST_MALLCTL_OPT(bool, zero, fill);
- TEST_MALLCTL_OPT(bool, utrace, utrace);
- TEST_MALLCTL_OPT(bool, xmalloc, xmalloc);
- TEST_MALLCTL_OPT(bool, tcache, tcache);
- TEST_MALLCTL_OPT(size_t, lg_tcache_max, tcache);
- TEST_MALLCTL_OPT(bool, prof, prof);
- TEST_MALLCTL_OPT(const char *, prof_prefix, prof);
- TEST_MALLCTL_OPT(bool, prof_active, prof);
- TEST_MALLCTL_OPT(ssize_t, lg_prof_sample, prof);
- TEST_MALLCTL_OPT(bool, prof_accum, prof);
- TEST_MALLCTL_OPT(ssize_t, lg_prof_interval, prof);
- TEST_MALLCTL_OPT(bool, prof_gdump, prof);
- TEST_MALLCTL_OPT(bool, prof_final, prof);
- TEST_MALLCTL_OPT(bool, prof_leak, prof);
-
-#undef TEST_MALLCTL_OPT
-}
-TEST_END
-
-TEST_BEGIN(test_manpage_example)
-{
- unsigned nbins, i;
- size_t mib[4];
- size_t len, miblen;
-
- len = sizeof(nbins);
- assert_d_eq(mallctl("arenas.nbins", &nbins, &len, NULL, 0), 0,
- "Unexpected mallctl() failure");
-
- miblen = 4;
- assert_d_eq(mallctlnametomib("arenas.bin.0.size", mib, &miblen), 0,
- "Unexpected mallctlnametomib() failure");
- for (i = 0; i < nbins; i++) {
- size_t bin_size;
-
- mib[2] = i;
- len = sizeof(bin_size);
- assert_d_eq(mallctlbymib(mib, miblen, &bin_size, &len, NULL, 0),
- 0, "Unexpected mallctlbymib() failure");
- /* Do something with bin_size... */
- }
-}
-TEST_END
-
-TEST_BEGIN(test_tcache_none)
-{
- void *p0, *q, *p1;
-
- test_skip_if(!config_tcache);
-
- /* Allocate p and q. */
- p0 = mallocx(42, 0);
- assert_ptr_not_null(p0, "Unexpected mallocx() failure");
- q = mallocx(42, 0);
- assert_ptr_not_null(q, "Unexpected mallocx() failure");
-
- /* Deallocate p and q, but bypass the tcache for q. */
- dallocx(p0, 0);
- dallocx(q, MALLOCX_TCACHE_NONE);
-
- /* Make sure that tcache-based allocation returns p, not q. */
- p1 = mallocx(42, 0);
- assert_ptr_not_null(p1, "Unexpected mallocx() failure");
- assert_ptr_eq(p0, p1, "Expected tcache to allocate cached region");
-
- /* Clean up. */
- dallocx(p1, MALLOCX_TCACHE_NONE);
-}
-TEST_END
-
-TEST_BEGIN(test_tcache)
-{
-#define NTCACHES 10
- unsigned tis[NTCACHES];
- void *ps[NTCACHES];
- void *qs[NTCACHES];
- unsigned i;
- size_t sz, psz, qsz;
-
- test_skip_if(!config_tcache);
-
- psz = 42;
- qsz = nallocx(psz, 0) + 1;
-
- /* Create tcaches. */
- for (i = 0; i < NTCACHES; i++) {
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("tcache.create", &tis[i], &sz, NULL, 0), 0,
- "Unexpected mallctl() failure, i=%u", i);
- }
-
- /* Exercise tcache ID recycling. */
- for (i = 0; i < NTCACHES; i++) {
- assert_d_eq(mallctl("tcache.destroy", NULL, NULL, &tis[i],
- sizeof(unsigned)), 0, "Unexpected mallctl() failure, i=%u",
- i);
- }
- for (i = 0; i < NTCACHES; i++) {
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("tcache.create", &tis[i], &sz, NULL, 0), 0,
- "Unexpected mallctl() failure, i=%u", i);
- }
-
- /* Flush empty tcaches. */
- for (i = 0; i < NTCACHES; i++) {
- assert_d_eq(mallctl("tcache.flush", NULL, NULL, &tis[i],
- sizeof(unsigned)), 0, "Unexpected mallctl() failure, i=%u",
- i);
- }
-
- /* Cache some allocations. */
- for (i = 0; i < NTCACHES; i++) {
- ps[i] = mallocx(psz, MALLOCX_TCACHE(tis[i]));
- assert_ptr_not_null(ps[i], "Unexpected mallocx() failure, i=%u",
- i);
- dallocx(ps[i], MALLOCX_TCACHE(tis[i]));
-
- qs[i] = mallocx(qsz, MALLOCX_TCACHE(tis[i]));
- assert_ptr_not_null(qs[i], "Unexpected mallocx() failure, i=%u",
- i);
- dallocx(qs[i], MALLOCX_TCACHE(tis[i]));
- }
-
- /* Verify that tcaches allocate cached regions. */
- for (i = 0; i < NTCACHES; i++) {
- void *p0 = ps[i];
- ps[i] = mallocx(psz, MALLOCX_TCACHE(tis[i]));
- assert_ptr_not_null(ps[i], "Unexpected mallocx() failure, i=%u",
- i);
- assert_ptr_eq(ps[i], p0,
- "Expected mallocx() to allocate cached region, i=%u", i);
- }
-
- /* Verify that reallocation uses cached regions. */
- for (i = 0; i < NTCACHES; i++) {
- void *q0 = qs[i];
- qs[i] = rallocx(ps[i], qsz, MALLOCX_TCACHE(tis[i]));
- assert_ptr_not_null(qs[i], "Unexpected rallocx() failure, i=%u",
- i);
- assert_ptr_eq(qs[i], q0,
- "Expected rallocx() to allocate cached region, i=%u", i);
- /* Avoid undefined behavior in case of test failure. */
- if (qs[i] == NULL)
- qs[i] = ps[i];
- }
- for (i = 0; i < NTCACHES; i++)
- dallocx(qs[i], MALLOCX_TCACHE(tis[i]));
-
- /* Flush some non-empty tcaches. */
- for (i = 0; i < NTCACHES/2; i++) {
- assert_d_eq(mallctl("tcache.flush", NULL, NULL, &tis[i],
- sizeof(unsigned)), 0, "Unexpected mallctl() failure, i=%u",
- i);
- }
-
- /* Destroy tcaches. */
- for (i = 0; i < NTCACHES; i++) {
- assert_d_eq(mallctl("tcache.destroy", NULL, NULL, &tis[i],
- sizeof(unsigned)), 0, "Unexpected mallctl() failure, i=%u",
- i);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_thread_arena)
-{
- unsigned arena_old, arena_new, narenas;
- size_t sz = sizeof(unsigned);
-
- assert_d_eq(mallctl("arenas.narenas", &narenas, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_u_eq(narenas, opt_narenas, "Number of arenas incorrect");
- arena_new = narenas - 1;
- assert_d_eq(mallctl("thread.arena", &arena_old, &sz, &arena_new,
- sizeof(unsigned)), 0, "Unexpected mallctl() failure");
- arena_new = 0;
- assert_d_eq(mallctl("thread.arena", &arena_old, &sz, &arena_new,
- sizeof(unsigned)), 0, "Unexpected mallctl() failure");
-}
-TEST_END
-
-TEST_BEGIN(test_arena_i_lg_dirty_mult)
-{
- ssize_t lg_dirty_mult, orig_lg_dirty_mult, prev_lg_dirty_mult;
- size_t sz = sizeof(ssize_t);
-
- test_skip_if(opt_purge != purge_mode_ratio);
-
- assert_d_eq(mallctl("arena.0.lg_dirty_mult", &orig_lg_dirty_mult, &sz,
- NULL, 0), 0, "Unexpected mallctl() failure");
-
- lg_dirty_mult = -2;
- assert_d_eq(mallctl("arena.0.lg_dirty_mult", NULL, NULL,
- &lg_dirty_mult, sizeof(ssize_t)), EFAULT,
- "Unexpected mallctl() success");
-
- lg_dirty_mult = (sizeof(size_t) << 3);
- assert_d_eq(mallctl("arena.0.lg_dirty_mult", NULL, NULL,
- &lg_dirty_mult, sizeof(ssize_t)), EFAULT,
- "Unexpected mallctl() success");
-
- for (prev_lg_dirty_mult = orig_lg_dirty_mult, lg_dirty_mult = -1;
- lg_dirty_mult < (ssize_t)(sizeof(size_t) << 3); prev_lg_dirty_mult
- = lg_dirty_mult, lg_dirty_mult++) {
- ssize_t old_lg_dirty_mult;
-
- assert_d_eq(mallctl("arena.0.lg_dirty_mult", &old_lg_dirty_mult,
- &sz, &lg_dirty_mult, sizeof(ssize_t)), 0,
- "Unexpected mallctl() failure");
- assert_zd_eq(old_lg_dirty_mult, prev_lg_dirty_mult,
- "Unexpected old arena.0.lg_dirty_mult");
- }
-}
-TEST_END
-
-TEST_BEGIN(test_arena_i_decay_time)
-{
- ssize_t decay_time, orig_decay_time, prev_decay_time;
- size_t sz = sizeof(ssize_t);
-
- test_skip_if(opt_purge != purge_mode_decay);
-
- assert_d_eq(mallctl("arena.0.decay_time", &orig_decay_time, &sz,
- NULL, 0), 0, "Unexpected mallctl() failure");
-
- decay_time = -2;
- assert_d_eq(mallctl("arena.0.decay_time", NULL, NULL,
- &decay_time, sizeof(ssize_t)), EFAULT,
- "Unexpected mallctl() success");
-
- decay_time = 0x7fffffff;
- assert_d_eq(mallctl("arena.0.decay_time", NULL, NULL,
- &decay_time, sizeof(ssize_t)), 0,
- "Unexpected mallctl() failure");
-
- for (prev_decay_time = decay_time, decay_time = -1;
- decay_time < 20; prev_decay_time = decay_time, decay_time++) {
- ssize_t old_decay_time;
-
- assert_d_eq(mallctl("arena.0.decay_time", &old_decay_time,
- &sz, &decay_time, sizeof(ssize_t)), 0,
- "Unexpected mallctl() failure");
- assert_zd_eq(old_decay_time, prev_decay_time,
- "Unexpected old arena.0.decay_time");
- }
-}
-TEST_END
-
-TEST_BEGIN(test_arena_i_purge)
-{
- unsigned narenas;
- size_t sz = sizeof(unsigned);
- size_t mib[3];
- size_t miblen = 3;
-
- assert_d_eq(mallctl("arena.0.purge", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl() failure");
-
- assert_d_eq(mallctl("arenas.narenas", &narenas, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_d_eq(mallctlnametomib("arena.0.purge", mib, &miblen), 0,
- "Unexpected mallctlnametomib() failure");
- mib[1] = narenas;
- assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, NULL, 0), 0,
- "Unexpected mallctlbymib() failure");
-}
-TEST_END
-
-TEST_BEGIN(test_arena_i_decay)
-{
- unsigned narenas;
- size_t sz = sizeof(unsigned);
- size_t mib[3];
- size_t miblen = 3;
-
- assert_d_eq(mallctl("arena.0.decay", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl() failure");
-
- assert_d_eq(mallctl("arenas.narenas", &narenas, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_d_eq(mallctlnametomib("arena.0.decay", mib, &miblen), 0,
- "Unexpected mallctlnametomib() failure");
- mib[1] = narenas;
- assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, NULL, 0), 0,
- "Unexpected mallctlbymib() failure");
-}
-TEST_END
-
-TEST_BEGIN(test_arena_i_dss)
-{
- const char *dss_prec_old, *dss_prec_new;
- size_t sz = sizeof(dss_prec_old);
- size_t mib[3];
- size_t miblen;
-
- miblen = sizeof(mib)/sizeof(size_t);
- assert_d_eq(mallctlnametomib("arena.0.dss", mib, &miblen), 0,
- "Unexpected mallctlnametomib() error");
-
- dss_prec_new = "disabled";
- assert_d_eq(mallctlbymib(mib, miblen, &dss_prec_old, &sz, &dss_prec_new,
- sizeof(dss_prec_new)), 0, "Unexpected mallctl() failure");
- assert_str_ne(dss_prec_old, "primary",
- "Unexpected default for dss precedence");
-
- assert_d_eq(mallctlbymib(mib, miblen, &dss_prec_new, &sz, &dss_prec_old,
- sizeof(dss_prec_old)), 0, "Unexpected mallctl() failure");
-
- assert_d_eq(mallctlbymib(mib, miblen, &dss_prec_old, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_str_ne(dss_prec_old, "primary",
- "Unexpected value for dss precedence");
-
- mib[1] = narenas_total_get();
- dss_prec_new = "disabled";
- assert_d_eq(mallctlbymib(mib, miblen, &dss_prec_old, &sz, &dss_prec_new,
- sizeof(dss_prec_new)), 0, "Unexpected mallctl() failure");
- assert_str_ne(dss_prec_old, "primary",
- "Unexpected default for dss precedence");
-
- assert_d_eq(mallctlbymib(mib, miblen, &dss_prec_new, &sz, &dss_prec_old,
- sizeof(dss_prec_new)), 0, "Unexpected mallctl() failure");
-
- assert_d_eq(mallctlbymib(mib, miblen, &dss_prec_old, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_str_ne(dss_prec_old, "primary",
- "Unexpected value for dss precedence");
-}
-TEST_END
-
-TEST_BEGIN(test_arenas_initialized)
-{
- unsigned narenas;
- size_t sz = sizeof(narenas);
-
- assert_d_eq(mallctl("arenas.narenas", &narenas, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- {
- VARIABLE_ARRAY(bool, initialized, narenas);
-
- sz = narenas * sizeof(bool);
- assert_d_eq(mallctl("arenas.initialized", initialized, &sz,
- NULL, 0), 0, "Unexpected mallctl() failure");
- }
-}
-TEST_END
-
-TEST_BEGIN(test_arenas_lg_dirty_mult)
-{
- ssize_t lg_dirty_mult, orig_lg_dirty_mult, prev_lg_dirty_mult;
- size_t sz = sizeof(ssize_t);
-
- test_skip_if(opt_purge != purge_mode_ratio);
-
- assert_d_eq(mallctl("arenas.lg_dirty_mult", &orig_lg_dirty_mult, &sz,
- NULL, 0), 0, "Unexpected mallctl() failure");
-
- lg_dirty_mult = -2;
- assert_d_eq(mallctl("arenas.lg_dirty_mult", NULL, NULL,
- &lg_dirty_mult, sizeof(ssize_t)), EFAULT,
- "Unexpected mallctl() success");
-
- lg_dirty_mult = (sizeof(size_t) << 3);
- assert_d_eq(mallctl("arenas.lg_dirty_mult", NULL, NULL,
- &lg_dirty_mult, sizeof(ssize_t)), EFAULT,
- "Unexpected mallctl() success");
-
- for (prev_lg_dirty_mult = orig_lg_dirty_mult, lg_dirty_mult = -1;
- lg_dirty_mult < (ssize_t)(sizeof(size_t) << 3); prev_lg_dirty_mult =
- lg_dirty_mult, lg_dirty_mult++) {
- ssize_t old_lg_dirty_mult;
-
- assert_d_eq(mallctl("arenas.lg_dirty_mult", &old_lg_dirty_mult,
- &sz, &lg_dirty_mult, sizeof(ssize_t)), 0,
- "Unexpected mallctl() failure");
- assert_zd_eq(old_lg_dirty_mult, prev_lg_dirty_mult,
- "Unexpected old arenas.lg_dirty_mult");
- }
-}
-TEST_END
-
-TEST_BEGIN(test_arenas_decay_time)
-{
- ssize_t decay_time, orig_decay_time, prev_decay_time;
- size_t sz = sizeof(ssize_t);
-
- test_skip_if(opt_purge != purge_mode_decay);
-
- assert_d_eq(mallctl("arenas.decay_time", &orig_decay_time, &sz,
- NULL, 0), 0, "Unexpected mallctl() failure");
-
- decay_time = -2;
- assert_d_eq(mallctl("arenas.decay_time", NULL, NULL,
- &decay_time, sizeof(ssize_t)), EFAULT,
- "Unexpected mallctl() success");
-
- decay_time = 0x7fffffff;
- assert_d_eq(mallctl("arenas.decay_time", NULL, NULL,
- &decay_time, sizeof(ssize_t)), 0,
- "Expected mallctl() failure");
-
- for (prev_decay_time = decay_time, decay_time = -1;
- decay_time < 20; prev_decay_time = decay_time, decay_time++) {
- ssize_t old_decay_time;
-
- assert_d_eq(mallctl("arenas.decay_time", &old_decay_time,
- &sz, &decay_time, sizeof(ssize_t)), 0,
- "Unexpected mallctl() failure");
- assert_zd_eq(old_decay_time, prev_decay_time,
- "Unexpected old arenas.decay_time");
- }
-}
-TEST_END
-
-TEST_BEGIN(test_arenas_constants)
-{
-
-#define TEST_ARENAS_CONSTANT(t, name, expected) do { \
- t name; \
- size_t sz = sizeof(t); \
- assert_d_eq(mallctl("arenas."#name, &name, &sz, NULL, 0), 0, \
- "Unexpected mallctl() failure"); \
- assert_zu_eq(name, expected, "Incorrect "#name" size"); \
-} while (0)
-
- TEST_ARENAS_CONSTANT(size_t, quantum, QUANTUM);
- TEST_ARENAS_CONSTANT(size_t, page, PAGE);
- TEST_ARENAS_CONSTANT(unsigned, nbins, NBINS);
- TEST_ARENAS_CONSTANT(unsigned, nlruns, nlclasses);
- TEST_ARENAS_CONSTANT(unsigned, nhchunks, nhclasses);
-
-#undef TEST_ARENAS_CONSTANT
-}
-TEST_END
-
-TEST_BEGIN(test_arenas_bin_constants)
-{
-
-#define TEST_ARENAS_BIN_CONSTANT(t, name, expected) do { \
- t name; \
- size_t sz = sizeof(t); \
- assert_d_eq(mallctl("arenas.bin.0."#name, &name, &sz, NULL, 0), \
- 0, "Unexpected mallctl() failure"); \
- assert_zu_eq(name, expected, "Incorrect "#name" size"); \
-} while (0)
-
- TEST_ARENAS_BIN_CONSTANT(size_t, size, arena_bin_info[0].reg_size);
- TEST_ARENAS_BIN_CONSTANT(uint32_t, nregs, arena_bin_info[0].nregs);
- TEST_ARENAS_BIN_CONSTANT(size_t, run_size, arena_bin_info[0].run_size);
-
-#undef TEST_ARENAS_BIN_CONSTANT
-}
-TEST_END
-
-TEST_BEGIN(test_arenas_lrun_constants)
-{
-
-#define TEST_ARENAS_LRUN_CONSTANT(t, name, expected) do { \
- t name; \
- size_t sz = sizeof(t); \
- assert_d_eq(mallctl("arenas.lrun.0."#name, &name, &sz, NULL, \
- 0), 0, "Unexpected mallctl() failure"); \
- assert_zu_eq(name, expected, "Incorrect "#name" size"); \
-} while (0)
-
- TEST_ARENAS_LRUN_CONSTANT(size_t, size, LARGE_MINCLASS);
-
-#undef TEST_ARENAS_LRUN_CONSTANT
-}
-TEST_END
-
-TEST_BEGIN(test_arenas_hchunk_constants)
-{
-
-#define TEST_ARENAS_HCHUNK_CONSTANT(t, name, expected) do { \
- t name; \
- size_t sz = sizeof(t); \
- assert_d_eq(mallctl("arenas.hchunk.0."#name, &name, &sz, NULL, \
- 0), 0, "Unexpected mallctl() failure"); \
- assert_zu_eq(name, expected, "Incorrect "#name" size"); \
-} while (0)
-
- TEST_ARENAS_HCHUNK_CONSTANT(size_t, size, chunksize);
-
-#undef TEST_ARENAS_HCHUNK_CONSTANT
-}
-TEST_END
-
-TEST_BEGIN(test_arenas_extend)
-{
- unsigned narenas_before, arena, narenas_after;
- size_t sz = sizeof(unsigned);
-
- assert_d_eq(mallctl("arenas.narenas", &narenas_before, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_d_eq(mallctl("arenas.extend", &arena, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
- assert_d_eq(mallctl("arenas.narenas", &narenas_after, &sz, NULL, 0), 0,
- "Unexpected mallctl() failure");
-
- assert_u_eq(narenas_before+1, narenas_after,
- "Unexpected number of arenas before versus after extension");
- assert_u_eq(arena, narenas_after-1, "Unexpected arena index");
-}
-TEST_END
-
-TEST_BEGIN(test_stats_arenas)
-{
-
-#define TEST_STATS_ARENAS(t, name) do { \
- t name; \
- size_t sz = sizeof(t); \
- assert_d_eq(mallctl("stats.arenas.0."#name, &name, &sz, NULL, \
- 0), 0, "Unexpected mallctl() failure"); \
-} while (0)
-
- TEST_STATS_ARENAS(unsigned, nthreads);
- TEST_STATS_ARENAS(const char *, dss);
- TEST_STATS_ARENAS(ssize_t, lg_dirty_mult);
- TEST_STATS_ARENAS(ssize_t, decay_time);
- TEST_STATS_ARENAS(size_t, pactive);
- TEST_STATS_ARENAS(size_t, pdirty);
-
-#undef TEST_STATS_ARENAS
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_mallctl_errors,
- test_mallctlnametomib_errors,
- test_mallctlbymib_errors,
- test_mallctl_read_write,
- test_mallctlnametomib_short_mib,
- test_mallctl_config,
- test_mallctl_opt,
- test_manpage_example,
- test_tcache_none,
- test_tcache,
- test_thread_arena,
- test_arena_i_lg_dirty_mult,
- test_arena_i_decay_time,
- test_arena_i_purge,
- test_arena_i_decay,
- test_arena_i_dss,
- test_arenas_initialized,
- test_arenas_lg_dirty_mult,
- test_arenas_decay_time,
- test_arenas_constants,
- test_arenas_bin_constants,
- test_arenas_lrun_constants,
- test_arenas_hchunk_constants,
- test_arenas_extend,
- test_stats_arenas));
-}
diff --git a/memory/jemalloc/src/test/unit/math.c b/memory/jemalloc/src/test/unit/math.c
deleted file mode 100644
index adb72bed9..000000000
--- a/memory/jemalloc/src/test/unit/math.c
+++ /dev/null
@@ -1,398 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define MAX_REL_ERR 1.0e-9
-#define MAX_ABS_ERR 1.0e-9
-
-#include <float.h>
-
-#ifdef __PGI
-#undef INFINITY
-#endif
-
-#ifndef INFINITY
-#define INFINITY (DBL_MAX + DBL_MAX)
-#endif
-
-static bool
-double_eq_rel(double a, double b, double max_rel_err, double max_abs_err)
-{
- double rel_err;
-
- if (fabs(a - b) < max_abs_err)
- return (true);
- rel_err = (fabs(b) > fabs(a)) ? fabs((a-b)/b) : fabs((a-b)/a);
- return (rel_err < max_rel_err);
-}
-
-static uint64_t
-factorial(unsigned x)
-{
- uint64_t ret = 1;
- unsigned i;
-
- for (i = 2; i <= x; i++)
- ret *= (uint64_t)i;
-
- return (ret);
-}
-
-TEST_BEGIN(test_ln_gamma_factorial)
-{
- unsigned x;
-
- /* exp(ln_gamma(x)) == (x-1)! for integer x. */
- for (x = 1; x <= 21; x++) {
- assert_true(double_eq_rel(exp(ln_gamma(x)),
- (double)factorial(x-1), MAX_REL_ERR, MAX_ABS_ERR),
- "Incorrect factorial result for x=%u", x);
- }
-}
-TEST_END
-
-/* Expected ln_gamma([0.0..100.0] increment=0.25). */
-static const double ln_gamma_misc_expected[] = {
- INFINITY,
- 1.28802252469807743, 0.57236494292470008, 0.20328095143129538,
- 0.00000000000000000, -0.09827183642181320, -0.12078223763524518,
- -0.08440112102048555, 0.00000000000000000, 0.12487171489239651,
- 0.28468287047291918, 0.47521466691493719, 0.69314718055994529,
- 0.93580193110872523, 1.20097360234707429, 1.48681557859341718,
- 1.79175946922805496, 2.11445692745037128, 2.45373657084244234,
- 2.80857141857573644, 3.17805383034794575, 3.56137591038669710,
- 3.95781396761871651, 4.36671603662228680, 4.78749174278204581,
- 5.21960398699022932, 5.66256205985714178, 6.11591589143154568,
- 6.57925121201010121, 7.05218545073853953, 7.53436423675873268,
- 8.02545839631598312, 8.52516136106541467, 9.03318691960512332,
- 9.54926725730099690, 10.07315123968123949, 10.60460290274525086,
- 11.14340011995171231, 11.68933342079726856, 12.24220494005076176,
- 12.80182748008146909, 13.36802367147604720, 13.94062521940376342,
- 14.51947222506051816, 15.10441257307551943, 15.69530137706046524,
- 16.29200047656724237, 16.89437797963419285, 17.50230784587389010,
- 18.11566950571089407, 18.73434751193644843, 19.35823122022435427,
- 19.98721449566188468, 20.62119544270163018, 21.26007615624470048,
- 21.90376249182879320, 22.55216385312342098, 23.20519299513386002,
- 23.86276584168908954, 24.52480131594137802, 25.19122118273868338,
- 25.86194990184851861, 26.53691449111561340, 27.21604439872720604,
- 27.89927138384089389, 28.58652940490193828, 29.27775451504081516,
- 29.97288476399884871, 30.67186010608067548, 31.37462231367769050,
- 32.08111489594735843, 32.79128302226991565, 33.50507345013689076,
- 34.22243445715505317, 34.94331577687681545, 35.66766853819134298,
- 36.39544520803305261, 37.12659953718355865, 37.86108650896109395,
- 38.59886229060776230, 39.33988418719949465, 40.08411059791735198,
- 40.83150097453079752, 41.58201578195490100, 42.33561646075348506,
- 43.09226539146988699, 43.85192586067515208, 44.61456202863158893,
- 45.38013889847690052, 46.14862228684032885, 46.91997879580877395,
- 47.69417578616628361, 48.47118135183522014, 49.25096429545256882,
- 50.03349410501914463, 50.81874093156324790, 51.60667556776436982,
- 52.39726942748592364, 53.19049452616926743, 53.98632346204390586,
- 54.78472939811231157, 55.58568604486942633, 56.38916764371992940,
- 57.19514895105859864, 58.00360522298051080, 58.81451220059079787,
- 59.62784609588432261, 60.44358357816834371, 61.26170176100199427,
- 62.08217818962842927, 62.90499082887649962, 63.73011805151035958,
- 64.55753862700632340, 65.38723171073768015, 66.21917683354901385,
- 67.05335389170279825, 67.88974313718154008, 68.72832516833013017,
- 69.56908092082363737, 70.41199165894616385, 71.25703896716800045,
- 72.10420474200799390, 72.95347118416940191, 73.80482079093779646,
- 74.65823634883015814, 75.51370092648485866, 76.37119786778275454,
- 77.23071078519033961, 78.09222355331530707, 78.95572030266725960,
- 79.82118541361435859, 80.68860351052903468, 81.55795945611502873,
- 82.42923834590904164, 83.30242550295004378, 84.17750647261028973,
- 85.05446701758152983, 85.93329311301090456, 86.81397094178107920,
- 87.69648688992882057, 88.58082754219766741, 89.46697967771913795,
- 90.35493026581838194, 91.24466646193963015, 92.13617560368709292,
- 93.02944520697742803, 93.92446296229978486, 94.82121673107967297,
- 95.71969454214321615, 96.61988458827809723, 97.52177522288820910,
- 98.42535495673848800, 99.33061245478741341, 100.23753653310367895,
- 101.14611615586458981, 102.05634043243354370, 102.96819861451382394,
- 103.88168009337621811, 104.79677439715833032, 105.71347118823287303,
- 106.63176026064346047, 107.55163153760463501, 108.47307506906540198,
- 109.39608102933323153, 110.32063971475740516, 111.24674154146920557,
- 112.17437704317786995, 113.10353686902013237, 114.03421178146170689,
- 114.96639265424990128, 115.90007047041454769, 116.83523632031698014,
- 117.77188139974506953, 118.70999700805310795, 119.64957454634490830,
- 120.59060551569974962, 121.53308151543865279, 122.47699424143097247,
- 123.42233548443955726, 124.36909712850338394, 125.31727114935689826,
- 126.26684961288492559, 127.21782467361175861, 128.17018857322420899,
- 129.12393363912724453, 130.07905228303084755, 131.03553699956862033,
- 131.99338036494577864, 132.95257503561629164, 133.91311374698926784,
- 134.87498931216194364, 135.83819462068046846, 136.80272263732638294,
- 137.76856640092901785, 138.73571902320256299, 139.70417368760718091,
- 140.67392364823425055, 141.64496222871400732, 142.61728282114600574,
- 143.59087888505104047, 144.56574394634486680, 145.54187159633210058,
- 146.51925549072063859, 147.49788934865566148, 148.47776695177302031,
- 149.45888214327129617, 150.44122882700193600, 151.42480096657754984,
- 152.40959258449737490, 153.39559776128982094, 154.38281063467164245,
- 155.37122539872302696, 156.36083630307879844, 157.35163765213474107,
- 158.34362380426921391, 159.33678917107920370, 160.33112821663092973,
- 161.32663545672428995, 162.32330545817117695, 163.32113283808695314,
- 164.32011226319519892, 165.32023844914485267, 166.32150615984036790,
- 167.32391020678358018, 168.32744544842768164, 169.33210678954270634,
- 170.33788918059275375, 171.34478761712384198, 172.35279713916281707,
- 173.36191283062726143, 174.37212981874515094, 175.38344327348534080,
- 176.39584840699734514, 177.40934047306160437, 178.42391476654847793,
- 179.43956662288721304, 180.45629141754378111, 181.47408456550741107,
- 182.49294152078630304, 183.51285777591152737, 184.53382886144947861,
- 185.55585034552262869, 186.57891783333786861, 187.60302696672312095,
- 188.62817342367162610, 189.65435291789341932, 190.68156119837468054,
- 191.70979404894376330, 192.73904728784492590, 193.76931676731820176,
- 194.80059837318714244, 195.83288802445184729, 196.86618167288995096,
- 197.90047530266301123, 198.93576492992946214, 199.97204660246373464,
- 201.00931639928148797, 202.04757043027063901, 203.08680483582807597,
- 204.12701578650228385, 205.16819948264117102, 206.21035215404597807,
- 207.25347005962987623, 208.29754948708190909, 209.34258675253678916,
- 210.38857820024875878, 211.43552020227099320, 212.48340915813977858,
- 213.53224149456323744, 214.58201366511514152, 215.63272214993284592,
- 216.68436345542014010, 217.73693411395422004, 218.79043068359703739,
- 219.84484974781133815, 220.90018791517996988, 221.95644181913033322,
- 223.01360811766215875, 224.07168349307951871, 225.13066465172661879,
- 226.19054832372759734, 227.25133126272962159, 228.31301024565024704,
- 229.37558207242807384, 230.43904356577689896, 231.50339157094342113,
- 232.56862295546847008, 233.63473460895144740, 234.70172344281823484,
- 235.76958639009222907, 236.83832040516844586, 237.90792246359117712,
- 238.97838956183431947, 240.04971871708477238, 241.12190696702904802,
- 242.19495136964280846, 243.26884900298270509, 244.34359696498191283,
- 245.41919237324782443, 246.49563236486270057, 247.57291409618682110,
- 248.65103474266476269, 249.72999149863338175, 250.80978157713354904,
- 251.89040220972316320, 252.97185064629374551, 254.05412415488834199,
- 255.13722002152300661, 256.22113555000953511, 257.30586806178126835,
- 258.39141489572085675, 259.47777340799029844, 260.56494097186322279,
- 261.65291497755913497, 262.74169283208021852, 263.83127195904967266,
- 264.92164979855277807, 266.01282380697938379, 267.10479145686849733,
- 268.19755023675537586, 269.29109765101975427, 270.38543121973674488,
- 271.48054847852881721, 272.57644697842033565, 273.67312428569374561,
- 274.77057798174683967, 275.86880566295326389, 276.96780494052313770,
- 278.06757344036617496, 279.16810880295668085, 280.26940868320008349,
- 281.37147075030043197, 282.47429268763045229, 283.57787219260217171,
- 284.68220697654078322, 285.78729476455760050, 286.89313329542699194,
- 287.99972032146268930, 289.10705360839756395, 290.21513093526289140,
- 291.32395009427028754, 292.43350889069523646, 293.54380514276073200,
- 294.65483668152336350, 295.76660135076059532, 296.87909700685889902,
- 297.99232151870342022, 299.10627276756946458, 300.22094864701409733,
- 301.33634706277030091, 302.45246593264130297, 303.56930318639643929,
- 304.68685676566872189, 305.80512462385280514, 306.92410472600477078,
- 308.04379504874236773, 309.16419358014690033, 310.28529831966631036,
- 311.40710727801865687, 312.52961847709792664, 313.65282994987899201,
- 314.77673974032603610, 315.90134590329950015, 317.02664650446632777,
- 318.15263962020929966, 319.27932333753892635, 320.40669575400545455,
- 321.53475497761127144, 322.66349912672620803, 323.79292633000159185,
- 324.92303472628691452, 326.05382246454587403, 327.18528770377525916,
- 328.31742861292224234, 329.45024337080525356, 330.58373016603343331,
- 331.71788719692847280, 332.85271267144611329, 333.98820480709991898,
- 335.12436183088397001, 336.26118197919845443, 337.39866349777429377,
- 338.53680464159958774, 339.67560367484657036, 340.81505887079896411,
- 341.95516851178109619, 343.09593088908627578, 344.23734430290727460,
- 345.37940706226686416, 346.52211748494903532, 347.66547389743118401,
- 348.80947463481720661, 349.95411804077025408, 351.09940246744753267,
- 352.24532627543504759, 353.39188783368263103, 354.53908551944078908,
- 355.68691771819692349, 356.83538282361303118, 357.98447923746385868,
- 359.13420536957539753
-};
-
-TEST_BEGIN(test_ln_gamma_misc)
-{
- unsigned i;
-
- for (i = 1; i < sizeof(ln_gamma_misc_expected)/sizeof(double); i++) {
- double x = (double)i * 0.25;
- assert_true(double_eq_rel(ln_gamma(x),
- ln_gamma_misc_expected[i], MAX_REL_ERR, MAX_ABS_ERR),
- "Incorrect ln_gamma result for i=%u", i);
- }
-}
-TEST_END
-
-/* Expected pt_norm([0.01..0.99] increment=0.01). */
-static const double pt_norm_expected[] = {
- -INFINITY,
- -2.32634787404084076, -2.05374891063182252, -1.88079360815125085,
- -1.75068607125216946, -1.64485362695147264, -1.55477359459685305,
- -1.47579102817917063, -1.40507156030963221, -1.34075503369021654,
- -1.28155156554460081, -1.22652812003661049, -1.17498679206608991,
- -1.12639112903880045, -1.08031934081495606, -1.03643338949378938,
- -0.99445788320975281, -0.95416525314619416, -0.91536508784281390,
- -0.87789629505122846, -0.84162123357291418, -0.80642124701824025,
- -0.77219321418868492, -0.73884684918521371, -0.70630256284008752,
- -0.67448975019608171, -0.64334540539291685, -0.61281299101662701,
- -0.58284150727121620, -0.55338471955567281, -0.52440051270804067,
- -0.49585034734745320, -0.46769879911450812, -0.43991316567323380,
- -0.41246312944140462, -0.38532046640756751, -0.35845879325119373,
- -0.33185334643681652, -0.30548078809939738, -0.27931903444745404,
- -0.25334710313579978, -0.22754497664114931, -0.20189347914185077,
- -0.17637416478086135, -0.15096921549677725, -0.12566134685507399,
- -0.10043372051146975, -0.07526986209982976, -0.05015358346473352,
- -0.02506890825871106, 0.00000000000000000, 0.02506890825871106,
- 0.05015358346473366, 0.07526986209982990, 0.10043372051146990,
- 0.12566134685507413, 0.15096921549677739, 0.17637416478086146,
- 0.20189347914185105, 0.22754497664114931, 0.25334710313579978,
- 0.27931903444745404, 0.30548078809939738, 0.33185334643681652,
- 0.35845879325119373, 0.38532046640756762, 0.41246312944140484,
- 0.43991316567323391, 0.46769879911450835, 0.49585034734745348,
- 0.52440051270804111, 0.55338471955567303, 0.58284150727121620,
- 0.61281299101662701, 0.64334540539291685, 0.67448975019608171,
- 0.70630256284008752, 0.73884684918521371, 0.77219321418868492,
- 0.80642124701824036, 0.84162123357291441, 0.87789629505122879,
- 0.91536508784281423, 0.95416525314619460, 0.99445788320975348,
- 1.03643338949378938, 1.08031934081495606, 1.12639112903880045,
- 1.17498679206608991, 1.22652812003661049, 1.28155156554460081,
- 1.34075503369021654, 1.40507156030963265, 1.47579102817917085,
- 1.55477359459685394, 1.64485362695147308, 1.75068607125217102,
- 1.88079360815125041, 2.05374891063182208, 2.32634787404084076
-};
-
-TEST_BEGIN(test_pt_norm)
-{
- unsigned i;
-
- for (i = 1; i < sizeof(pt_norm_expected)/sizeof(double); i++) {
- double p = (double)i * 0.01;
- assert_true(double_eq_rel(pt_norm(p), pt_norm_expected[i],
- MAX_REL_ERR, MAX_ABS_ERR),
- "Incorrect pt_norm result for i=%u", i);
- }
-}
-TEST_END
-
-/*
- * Expected pt_chi2(p=[0.01..0.99] increment=0.07,
- * df={0.1, 1.1, 10.1, 100.1, 1000.1}).
- */
-static const double pt_chi2_df[] = {0.1, 1.1, 10.1, 100.1, 1000.1};
-static const double pt_chi2_expected[] = {
- 1.168926411457320e-40, 1.347680397072034e-22, 3.886980416666260e-17,
- 8.245951724356564e-14, 2.068936347497604e-11, 1.562561743309233e-09,
- 5.459543043426564e-08, 1.114775688149252e-06, 1.532101202364371e-05,
- 1.553884683726585e-04, 1.239396954915939e-03, 8.153872320255721e-03,
- 4.631183739647523e-02, 2.473187311701327e-01, 2.175254800183617e+00,
-
- 0.0003729887888876379, 0.0164409238228929513, 0.0521523015190650113,
- 0.1064701372271216612, 0.1800913735793082115, 0.2748704281195626931,
- 0.3939246282787986497, 0.5420727552260817816, 0.7267265822221973259,
- 0.9596554296000253670, 1.2607440376386165326, 1.6671185084541604304,
- 2.2604828984738705167, 3.2868613342148607082, 6.9298574921692139839,
-
- 2.606673548632508, 4.602913725294877, 5.646152813924212,
- 6.488971315540869, 7.249823275816285, 7.977314231410841,
- 8.700354939944047, 9.441728024225892, 10.224338321374127,
- 11.076435368801061, 12.039320937038386, 13.183878752697167,
- 14.657791935084575, 16.885728216339373, 23.361991680031817,
-
- 70.14844087392152, 80.92379498849355, 85.53325420085891,
- 88.94433120715347, 91.83732712857017, 94.46719943606301,
- 96.96896479994635, 99.43412843510363, 101.94074719829733,
- 104.57228644307247, 107.43900093448734, 110.71844673417287,
- 114.76616819871325, 120.57422505959563, 135.92318818757556,
-
- 899.0072447849649, 937.9271278858220, 953.8117189560207,
- 965.3079371501154, 974.8974061207954, 983.4936235182347,
- 991.5691170518946, 999.4334123954690, 1007.3391826856553,
- 1015.5445154999951, 1024.3777075619569, 1034.3538789836223,
- 1046.4872561869577, 1063.5717461999654, 1107.0741966053859
-};
-
-TEST_BEGIN(test_pt_chi2)
-{
- unsigned i, j;
- unsigned e = 0;
-
- for (i = 0; i < sizeof(pt_chi2_df)/sizeof(double); i++) {
- double df = pt_chi2_df[i];
- double ln_gamma_df = ln_gamma(df * 0.5);
- for (j = 1; j < 100; j += 7) {
- double p = (double)j * 0.01;
- assert_true(double_eq_rel(pt_chi2(p, df, ln_gamma_df),
- pt_chi2_expected[e], MAX_REL_ERR, MAX_ABS_ERR),
- "Incorrect pt_chi2 result for i=%u, j=%u", i, j);
- e++;
- }
- }
-}
-TEST_END
-
-/*
- * Expected pt_gamma(p=[0.1..0.99] increment=0.07,
- * shape=[0.5..3.0] increment=0.5).
- */
-static const double pt_gamma_shape[] = {0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
-static const double pt_gamma_expected[] = {
- 7.854392895485103e-05, 5.043466107888016e-03, 1.788288957794883e-02,
- 3.900956150232906e-02, 6.913847560638034e-02, 1.093710833465766e-01,
- 1.613412523825817e-01, 2.274682115597864e-01, 3.114117323127083e-01,
- 4.189466220207417e-01, 5.598106789059246e-01, 7.521856146202706e-01,
- 1.036125427911119e+00, 1.532450860038180e+00, 3.317448300510606e+00,
-
- 0.01005033585350144, 0.08338160893905107, 0.16251892949777497,
- 0.24846135929849966, 0.34249030894677596, 0.44628710262841947,
- 0.56211891815354142, 0.69314718055994529, 0.84397007029452920,
- 1.02165124753198167, 1.23787435600161766, 1.51412773262977574,
- 1.89711998488588196, 2.52572864430825783, 4.60517018598809091,
-
- 0.05741590094955853, 0.24747378084860744, 0.39888572212236084,
- 0.54394139997444901, 0.69048812513915159, 0.84311389861296104,
- 1.00580622221479898, 1.18298694218766931, 1.38038096305861213,
- 1.60627736383027453, 1.87396970522337947, 2.20749220408081070,
- 2.65852391865854942, 3.37934630984842244, 5.67243336507218476,
-
- 0.1485547402532659, 0.4657458011640391, 0.6832386130709406,
- 0.8794297834672100, 1.0700752852474524, 1.2629614217350744,
- 1.4638400448580779, 1.6783469900166610, 1.9132338090606940,
- 2.1778589228618777, 2.4868823970010991, 2.8664695666264195,
- 3.3724415436062114, 4.1682658512758071, 6.6383520679938108,
-
- 0.2771490383641385, 0.7195001279643727, 0.9969081732265243,
- 1.2383497880608061, 1.4675206597269927, 1.6953064251816552,
- 1.9291243435606809, 2.1757300955477641, 2.4428032131216391,
- 2.7406534569230616, 3.0851445039665513, 3.5043101122033367,
- 4.0575997065264637, 4.9182956424675286, 7.5431362346944937,
-
- 0.4360451650782932, 0.9983600902486267, 1.3306365880734528,
- 1.6129750834753802, 1.8767241606994294, 2.1357032436097660,
- 2.3988853336865565, 2.6740603137235603, 2.9697561737517959,
- 3.2971457713883265, 3.6731795898504660, 4.1275751617770631,
- 4.7230515633946677, 5.6417477865306020, 8.4059469148854635
-};
-
-TEST_BEGIN(test_pt_gamma_shape)
-{
- unsigned i, j;
- unsigned e = 0;
-
- for (i = 0; i < sizeof(pt_gamma_shape)/sizeof(double); i++) {
- double shape = pt_gamma_shape[i];
- double ln_gamma_shape = ln_gamma(shape);
- for (j = 1; j < 100; j += 7) {
- double p = (double)j * 0.01;
- assert_true(double_eq_rel(pt_gamma(p, shape, 1.0,
- ln_gamma_shape), pt_gamma_expected[e], MAX_REL_ERR,
- MAX_ABS_ERR),
- "Incorrect pt_gamma result for i=%u, j=%u", i, j);
- e++;
- }
- }
-}
-TEST_END
-
-TEST_BEGIN(test_pt_gamma_scale)
-{
- double shape = 1.0;
- double ln_gamma_shape = ln_gamma(shape);
-
- assert_true(double_eq_rel(
- pt_gamma(0.5, shape, 1.0, ln_gamma_shape) * 10.0,
- pt_gamma(0.5, shape, 10.0, ln_gamma_shape), MAX_REL_ERR,
- MAX_ABS_ERR),
- "Scale should be trivially equivalent to external multiplication");
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_ln_gamma_factorial,
- test_ln_gamma_misc,
- test_pt_norm,
- test_pt_chi2,
- test_pt_gamma_shape,
- test_pt_gamma_scale));
-}
diff --git a/memory/jemalloc/src/test/unit/mq.c b/memory/jemalloc/src/test/unit/mq.c
deleted file mode 100644
index bde2a480b..000000000
--- a/memory/jemalloc/src/test/unit/mq.c
+++ /dev/null
@@ -1,93 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define NSENDERS 3
-#define NMSGS 100000
-
-typedef struct mq_msg_s mq_msg_t;
-struct mq_msg_s {
- mq_msg(mq_msg_t) link;
-};
-mq_gen(static, mq_, mq_t, mq_msg_t, link)
-
-TEST_BEGIN(test_mq_basic)
-{
- mq_t mq;
- mq_msg_t msg;
-
- assert_false(mq_init(&mq), "Unexpected mq_init() failure");
- assert_u_eq(mq_count(&mq), 0, "mq should be empty");
- assert_ptr_null(mq_tryget(&mq),
- "mq_tryget() should fail when the queue is empty");
-
- mq_put(&mq, &msg);
- assert_u_eq(mq_count(&mq), 1, "mq should contain one message");
- assert_ptr_eq(mq_tryget(&mq), &msg, "mq_tryget() should return msg");
-
- mq_put(&mq, &msg);
- assert_ptr_eq(mq_get(&mq), &msg, "mq_get() should return msg");
-
- mq_fini(&mq);
-}
-TEST_END
-
-static void *
-thd_receiver_start(void *arg)
-{
- mq_t *mq = (mq_t *)arg;
- unsigned i;
-
- for (i = 0; i < (NSENDERS * NMSGS); i++) {
- mq_msg_t *msg = mq_get(mq);
- assert_ptr_not_null(msg, "mq_get() should never return NULL");
- dallocx(msg, 0);
- }
- return (NULL);
-}
-
-static void *
-thd_sender_start(void *arg)
-{
- mq_t *mq = (mq_t *)arg;
- unsigned i;
-
- for (i = 0; i < NMSGS; i++) {
- mq_msg_t *msg;
- void *p;
- p = mallocx(sizeof(mq_msg_t), 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- msg = (mq_msg_t *)p;
- mq_put(mq, msg);
- }
- return (NULL);
-}
-
-TEST_BEGIN(test_mq_threaded)
-{
- mq_t mq;
- thd_t receiver;
- thd_t senders[NSENDERS];
- unsigned i;
-
- assert_false(mq_init(&mq), "Unexpected mq_init() failure");
-
- thd_create(&receiver, thd_receiver_start, (void *)&mq);
- for (i = 0; i < NSENDERS; i++)
- thd_create(&senders[i], thd_sender_start, (void *)&mq);
-
- thd_join(receiver, NULL);
- for (i = 0; i < NSENDERS; i++)
- thd_join(senders[i], NULL);
-
- mq_fini(&mq);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_mq_basic,
- test_mq_threaded));
-}
-
diff --git a/memory/jemalloc/src/test/unit/mtx.c b/memory/jemalloc/src/test/unit/mtx.c
deleted file mode 100644
index 96ff69486..000000000
--- a/memory/jemalloc/src/test/unit/mtx.c
+++ /dev/null
@@ -1,60 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define NTHREADS 2
-#define NINCRS 2000000
-
-TEST_BEGIN(test_mtx_basic)
-{
- mtx_t mtx;
-
- assert_false(mtx_init(&mtx), "Unexpected mtx_init() failure");
- mtx_lock(&mtx);
- mtx_unlock(&mtx);
- mtx_fini(&mtx);
-}
-TEST_END
-
-typedef struct {
- mtx_t mtx;
- unsigned x;
-} thd_start_arg_t;
-
-static void *
-thd_start(void *varg)
-{
- thd_start_arg_t *arg = (thd_start_arg_t *)varg;
- unsigned i;
-
- for (i = 0; i < NINCRS; i++) {
- mtx_lock(&arg->mtx);
- arg->x++;
- mtx_unlock(&arg->mtx);
- }
- return (NULL);
-}
-
-TEST_BEGIN(test_mtx_race)
-{
- thd_start_arg_t arg;
- thd_t thds[NTHREADS];
- unsigned i;
-
- assert_false(mtx_init(&arg.mtx), "Unexpected mtx_init() failure");
- arg.x = 0;
- for (i = 0; i < NTHREADS; i++)
- thd_create(&thds[i], thd_start, (void *)&arg);
- for (i = 0; i < NTHREADS; i++)
- thd_join(thds[i], NULL);
- assert_u_eq(arg.x, NTHREADS * NINCRS,
- "Race-related counter corruption");
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_mtx_basic,
- test_mtx_race));
-}
diff --git a/memory/jemalloc/src/test/unit/nstime.c b/memory/jemalloc/src/test/unit/nstime.c
deleted file mode 100644
index 0368bc26e..000000000
--- a/memory/jemalloc/src/test/unit/nstime.c
+++ /dev/null
@@ -1,227 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define BILLION UINT64_C(1000000000)
-
-TEST_BEGIN(test_nstime_init)
-{
- nstime_t nst;
-
- nstime_init(&nst, 42000000043);
- assert_u64_eq(nstime_ns(&nst), 42000000043, "ns incorrectly read");
- assert_u64_eq(nstime_sec(&nst), 42, "sec incorrectly read");
- assert_u64_eq(nstime_nsec(&nst), 43, "nsec incorrectly read");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_init2)
-{
- nstime_t nst;
-
- nstime_init2(&nst, 42, 43);
- assert_u64_eq(nstime_sec(&nst), 42, "sec incorrectly read");
- assert_u64_eq(nstime_nsec(&nst), 43, "nsec incorrectly read");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_copy)
-{
- nstime_t nsta, nstb;
-
- nstime_init2(&nsta, 42, 43);
- nstime_init(&nstb, 0);
- nstime_copy(&nstb, &nsta);
- assert_u64_eq(nstime_sec(&nstb), 42, "sec incorrectly copied");
- assert_u64_eq(nstime_nsec(&nstb), 43, "nsec incorrectly copied");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_compare)
-{
- nstime_t nsta, nstb;
-
- nstime_init2(&nsta, 42, 43);
- nstime_copy(&nstb, &nsta);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0, "Times should be equal");
- assert_d_eq(nstime_compare(&nstb, &nsta), 0, "Times should be equal");
-
- nstime_init2(&nstb, 42, 42);
- assert_d_eq(nstime_compare(&nsta, &nstb), 1,
- "nsta should be greater than nstb");
- assert_d_eq(nstime_compare(&nstb, &nsta), -1,
- "nstb should be less than nsta");
-
- nstime_init2(&nstb, 42, 44);
- assert_d_eq(nstime_compare(&nsta, &nstb), -1,
- "nsta should be less than nstb");
- assert_d_eq(nstime_compare(&nstb, &nsta), 1,
- "nstb should be greater than nsta");
-
- nstime_init2(&nstb, 41, BILLION - 1);
- assert_d_eq(nstime_compare(&nsta, &nstb), 1,
- "nsta should be greater than nstb");
- assert_d_eq(nstime_compare(&nstb, &nsta), -1,
- "nstb should be less than nsta");
-
- nstime_init2(&nstb, 43, 0);
- assert_d_eq(nstime_compare(&nsta, &nstb), -1,
- "nsta should be less than nstb");
- assert_d_eq(nstime_compare(&nstb, &nsta), 1,
- "nstb should be greater than nsta");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_add)
-{
- nstime_t nsta, nstb;
-
- nstime_init2(&nsta, 42, 43);
- nstime_copy(&nstb, &nsta);
- nstime_add(&nsta, &nstb);
- nstime_init2(&nstb, 84, 86);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0,
- "Incorrect addition result");
-
- nstime_init2(&nsta, 42, BILLION - 1);
- nstime_copy(&nstb, &nsta);
- nstime_add(&nsta, &nstb);
- nstime_init2(&nstb, 85, BILLION - 2);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0,
- "Incorrect addition result");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_subtract)
-{
- nstime_t nsta, nstb;
-
- nstime_init2(&nsta, 42, 43);
- nstime_copy(&nstb, &nsta);
- nstime_subtract(&nsta, &nstb);
- nstime_init(&nstb, 0);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0,
- "Incorrect subtraction result");
-
- nstime_init2(&nsta, 42, 43);
- nstime_init2(&nstb, 41, 44);
- nstime_subtract(&nsta, &nstb);
- nstime_init2(&nstb, 0, BILLION - 1);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0,
- "Incorrect subtraction result");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_imultiply)
-{
- nstime_t nsta, nstb;
-
- nstime_init2(&nsta, 42, 43);
- nstime_imultiply(&nsta, 10);
- nstime_init2(&nstb, 420, 430);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0,
- "Incorrect multiplication result");
-
- nstime_init2(&nsta, 42, 666666666);
- nstime_imultiply(&nsta, 3);
- nstime_init2(&nstb, 127, 999999998);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0,
- "Incorrect multiplication result");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_idivide)
-{
- nstime_t nsta, nstb;
-
- nstime_init2(&nsta, 42, 43);
- nstime_copy(&nstb, &nsta);
- nstime_imultiply(&nsta, 10);
- nstime_idivide(&nsta, 10);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0,
- "Incorrect division result");
-
- nstime_init2(&nsta, 42, 666666666);
- nstime_copy(&nstb, &nsta);
- nstime_imultiply(&nsta, 3);
- nstime_idivide(&nsta, 3);
- assert_d_eq(nstime_compare(&nsta, &nstb), 0,
- "Incorrect division result");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_divide)
-{
- nstime_t nsta, nstb, nstc;
-
- nstime_init2(&nsta, 42, 43);
- nstime_copy(&nstb, &nsta);
- nstime_imultiply(&nsta, 10);
- assert_u64_eq(nstime_divide(&nsta, &nstb), 10,
- "Incorrect division result");
-
- nstime_init2(&nsta, 42, 43);
- nstime_copy(&nstb, &nsta);
- nstime_imultiply(&nsta, 10);
- nstime_init(&nstc, 1);
- nstime_add(&nsta, &nstc);
- assert_u64_eq(nstime_divide(&nsta, &nstb), 10,
- "Incorrect division result");
-
- nstime_init2(&nsta, 42, 43);
- nstime_copy(&nstb, &nsta);
- nstime_imultiply(&nsta, 10);
- nstime_init(&nstc, 1);
- nstime_subtract(&nsta, &nstc);
- assert_u64_eq(nstime_divide(&nsta, &nstb), 9,
- "Incorrect division result");
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_monotonic)
-{
-
- nstime_monotonic();
-}
-TEST_END
-
-TEST_BEGIN(test_nstime_update)
-{
- nstime_t nst;
-
- nstime_init(&nst, 0);
-
- assert_false(nstime_update(&nst), "Basic time update failed.");
-
- /* Only Rip Van Winkle sleeps this long. */
- {
- nstime_t addend;
- nstime_init2(&addend, 631152000, 0);
- nstime_add(&nst, &addend);
- }
- {
- nstime_t nst0;
- nstime_copy(&nst0, &nst);
- assert_true(nstime_update(&nst),
- "Update should detect time roll-back.");
- assert_d_eq(nstime_compare(&nst, &nst0), 0,
- "Time should not have been modified");
- }
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_nstime_init,
- test_nstime_init2,
- test_nstime_copy,
- test_nstime_compare,
- test_nstime_add,
- test_nstime_subtract,
- test_nstime_imultiply,
- test_nstime_idivide,
- test_nstime_divide,
- test_nstime_monotonic,
- test_nstime_update));
-}
diff --git a/memory/jemalloc/src/test/unit/ph.c b/memory/jemalloc/src/test/unit/ph.c
deleted file mode 100644
index da442f07e..000000000
--- a/memory/jemalloc/src/test/unit/ph.c
+++ /dev/null
@@ -1,290 +0,0 @@
-#include "test/jemalloc_test.h"
-
-typedef struct node_s node_t;
-
-struct node_s {
-#define NODE_MAGIC 0x9823af7e
- uint32_t magic;
- phn(node_t) link;
- uint64_t key;
-};
-
-static int
-node_cmp(const node_t *a, const node_t *b)
-{
- int ret;
-
- ret = (a->key > b->key) - (a->key < b->key);
- if (ret == 0) {
- /*
- * Duplicates are not allowed in the heap, so force an
- * arbitrary ordering for non-identical items with equal keys.
- */
- ret = (((uintptr_t)a) > ((uintptr_t)b))
- - (((uintptr_t)a) < ((uintptr_t)b));
- }
- return (ret);
-}
-
-static int
-node_cmp_magic(const node_t *a, const node_t *b) {
-
- assert_u32_eq(a->magic, NODE_MAGIC, "Bad magic");
- assert_u32_eq(b->magic, NODE_MAGIC, "Bad magic");
-
- return (node_cmp(a, b));
-}
-
-typedef ph(node_t) heap_t;
-ph_gen(static, heap_, heap_t, node_t, link, node_cmp_magic);
-
-static void
-node_print(const node_t *node, unsigned depth)
-{
- unsigned i;
- node_t *leftmost_child, *sibling;
-
- for (i = 0; i < depth; i++)
- malloc_printf("\t");
- malloc_printf("%2"FMTu64"\n", node->key);
-
- leftmost_child = phn_lchild_get(node_t, link, node);
- if (leftmost_child == NULL)
- return;
- node_print(leftmost_child, depth + 1);
-
- for (sibling = phn_next_get(node_t, link, leftmost_child); sibling !=
- NULL; sibling = phn_next_get(node_t, link, sibling)) {
- node_print(sibling, depth + 1);
- }
-}
-
-static void
-heap_print(const heap_t *heap)
-{
- node_t *auxelm;
-
- malloc_printf("vvv heap %p vvv\n", heap);
- if (heap->ph_root == NULL)
- goto label_return;
-
- node_print(heap->ph_root, 0);
-
- for (auxelm = phn_next_get(node_t, link, heap->ph_root); auxelm != NULL;
- auxelm = phn_next_get(node_t, link, auxelm)) {
- assert_ptr_eq(phn_next_get(node_t, link, phn_prev_get(node_t,
- link, auxelm)), auxelm,
- "auxelm's prev doesn't link to auxelm");
- node_print(auxelm, 0);
- }
-
-label_return:
- malloc_printf("^^^ heap %p ^^^\n", heap);
-}
-
-static unsigned
-node_validate(const node_t *node, const node_t *parent)
-{
- unsigned nnodes = 1;
- node_t *leftmost_child, *sibling;
-
- if (parent != NULL) {
- assert_d_ge(node_cmp_magic(node, parent), 0,
- "Child is less than parent");
- }
-
- leftmost_child = phn_lchild_get(node_t, link, node);
- if (leftmost_child == NULL)
- return (nnodes);
- assert_ptr_eq((void *)phn_prev_get(node_t, link, leftmost_child),
- (void *)node, "Leftmost child does not link to node");
- nnodes += node_validate(leftmost_child, node);
-
- for (sibling = phn_next_get(node_t, link, leftmost_child); sibling !=
- NULL; sibling = phn_next_get(node_t, link, sibling)) {
- assert_ptr_eq(phn_next_get(node_t, link, phn_prev_get(node_t,
- link, sibling)), sibling,
- "sibling's prev doesn't link to sibling");
- nnodes += node_validate(sibling, node);
- }
- return (nnodes);
-}
-
-static unsigned
-heap_validate(const heap_t *heap)
-{
- unsigned nnodes = 0;
- node_t *auxelm;
-
- if (heap->ph_root == NULL)
- goto label_return;
-
- nnodes += node_validate(heap->ph_root, NULL);
-
- for (auxelm = phn_next_get(node_t, link, heap->ph_root); auxelm != NULL;
- auxelm = phn_next_get(node_t, link, auxelm)) {
- assert_ptr_eq(phn_next_get(node_t, link, phn_prev_get(node_t,
- link, auxelm)), auxelm,
- "auxelm's prev doesn't link to auxelm");
- nnodes += node_validate(auxelm, NULL);
- }
-
-label_return:
- if (false)
- heap_print(heap);
- return (nnodes);
-}
-
-TEST_BEGIN(test_ph_empty)
-{
- heap_t heap;
-
- heap_new(&heap);
- assert_true(heap_empty(&heap), "Heap should be empty");
- assert_ptr_null(heap_first(&heap), "Unexpected node");
-}
-TEST_END
-
-static void
-node_remove(heap_t *heap, node_t *node)
-{
-
- heap_remove(heap, node);
-
- node->magic = 0;
-}
-
-static node_t *
-node_remove_first(heap_t *heap)
-{
- node_t *node = heap_remove_first(heap);
- node->magic = 0;
- return (node);
-}
-
-TEST_BEGIN(test_ph_random)
-{
-#define NNODES 25
-#define NBAGS 250
-#define SEED 42
- sfmt_t *sfmt;
- uint64_t bag[NNODES];
- heap_t heap;
- node_t nodes[NNODES];
- unsigned i, j, k;
-
- sfmt = init_gen_rand(SEED);
- for (i = 0; i < NBAGS; i++) {
- switch (i) {
- case 0:
- /* Insert in order. */
- for (j = 0; j < NNODES; j++)
- bag[j] = j;
- break;
- case 1:
- /* Insert in reverse order. */
- for (j = 0; j < NNODES; j++)
- bag[j] = NNODES - j - 1;
- break;
- default:
- for (j = 0; j < NNODES; j++)
- bag[j] = gen_rand64_range(sfmt, NNODES);
- }
-
- for (j = 1; j <= NNODES; j++) {
- /* Initialize heap and nodes. */
- heap_new(&heap);
- assert_u_eq(heap_validate(&heap), 0,
- "Incorrect node count");
- for (k = 0; k < j; k++) {
- nodes[k].magic = NODE_MAGIC;
- nodes[k].key = bag[k];
- }
-
- /* Insert nodes. */
- for (k = 0; k < j; k++) {
- heap_insert(&heap, &nodes[k]);
- if (i % 13 == 12) {
- /* Trigger merging. */
- assert_ptr_not_null(heap_first(&heap),
- "Heap should not be empty");
- }
- assert_u_eq(heap_validate(&heap), k + 1,
- "Incorrect node count");
- }
-
- assert_false(heap_empty(&heap),
- "Heap should not be empty");
-
- /* Remove nodes. */
- switch (i % 4) {
- case 0:
- for (k = 0; k < j; k++) {
- assert_u_eq(heap_validate(&heap), j - k,
- "Incorrect node count");
- node_remove(&heap, &nodes[k]);
- assert_u_eq(heap_validate(&heap), j - k
- - 1, "Incorrect node count");
- }
- break;
- case 1:
- for (k = j; k > 0; k--) {
- node_remove(&heap, &nodes[k-1]);
- assert_u_eq(heap_validate(&heap), k - 1,
- "Incorrect node count");
- }
- break;
- case 2: {
- node_t *prev = NULL;
- for (k = 0; k < j; k++) {
- node_t *node = node_remove_first(&heap);
- assert_u_eq(heap_validate(&heap), j - k
- - 1, "Incorrect node count");
- if (prev != NULL) {
- assert_d_ge(node_cmp(node,
- prev), 0,
- "Bad removal order");
- }
- prev = node;
- }
- break;
- } case 3: {
- node_t *prev = NULL;
- for (k = 0; k < j; k++) {
- node_t *node = heap_first(&heap);
- assert_u_eq(heap_validate(&heap), j - k,
- "Incorrect node count");
- if (prev != NULL) {
- assert_d_ge(node_cmp(node,
- prev), 0,
- "Bad removal order");
- }
- node_remove(&heap, node);
- assert_u_eq(heap_validate(&heap), j - k
- - 1, "Incorrect node count");
- prev = node;
- }
- break;
- } default:
- not_reached();
- }
-
- assert_ptr_null(heap_first(&heap),
- "Heap should be empty");
- assert_true(heap_empty(&heap), "Heap should be empty");
- }
- }
- fini_gen_rand(sfmt);
-#undef NNODES
-#undef SEED
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_ph_empty,
- test_ph_random));
-}
diff --git a/memory/jemalloc/src/test/unit/prng.c b/memory/jemalloc/src/test/unit/prng.c
deleted file mode 100644
index 80c9d733f..000000000
--- a/memory/jemalloc/src/test/unit/prng.c
+++ /dev/null
@@ -1,263 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static void
-test_prng_lg_range_u32(bool atomic)
-{
- uint32_t sa, sb, ra, rb;
- unsigned lg_range;
-
- sa = 42;
- ra = prng_lg_range_u32(&sa, 32, atomic);
- sa = 42;
- rb = prng_lg_range_u32(&sa, 32, atomic);
- assert_u32_eq(ra, rb,
- "Repeated generation should produce repeated results");
-
- sb = 42;
- rb = prng_lg_range_u32(&sb, 32, atomic);
- assert_u32_eq(ra, rb,
- "Equivalent generation should produce equivalent results");
-
- sa = 42;
- ra = prng_lg_range_u32(&sa, 32, atomic);
- rb = prng_lg_range_u32(&sa, 32, atomic);
- assert_u32_ne(ra, rb,
- "Full-width results must not immediately repeat");
-
- sa = 42;
- ra = prng_lg_range_u32(&sa, 32, atomic);
- for (lg_range = 31; lg_range > 0; lg_range--) {
- sb = 42;
- rb = prng_lg_range_u32(&sb, lg_range, atomic);
- assert_u32_eq((rb & (UINT32_C(0xffffffff) << lg_range)),
- 0, "High order bits should be 0, lg_range=%u", lg_range);
- assert_u32_eq(rb, (ra >> (32 - lg_range)),
- "Expected high order bits of full-width result, "
- "lg_range=%u", lg_range);
- }
-}
-
-static void
-test_prng_lg_range_u64(void)
-{
- uint64_t sa, sb, ra, rb;
- unsigned lg_range;
-
- sa = 42;
- ra = prng_lg_range_u64(&sa, 64);
- sa = 42;
- rb = prng_lg_range_u64(&sa, 64);
- assert_u64_eq(ra, rb,
- "Repeated generation should produce repeated results");
-
- sb = 42;
- rb = prng_lg_range_u64(&sb, 64);
- assert_u64_eq(ra, rb,
- "Equivalent generation should produce equivalent results");
-
- sa = 42;
- ra = prng_lg_range_u64(&sa, 64);
- rb = prng_lg_range_u64(&sa, 64);
- assert_u64_ne(ra, rb,
- "Full-width results must not immediately repeat");
-
- sa = 42;
- ra = prng_lg_range_u64(&sa, 64);
- for (lg_range = 63; lg_range > 0; lg_range--) {
- sb = 42;
- rb = prng_lg_range_u64(&sb, lg_range);
- assert_u64_eq((rb & (UINT64_C(0xffffffffffffffff) << lg_range)),
- 0, "High order bits should be 0, lg_range=%u", lg_range);
- assert_u64_eq(rb, (ra >> (64 - lg_range)),
- "Expected high order bits of full-width result, "
- "lg_range=%u", lg_range);
- }
-}
-
-static void
-test_prng_lg_range_zu(bool atomic)
-{
- size_t sa, sb, ra, rb;
- unsigned lg_range;
-
- sa = 42;
- ra = prng_lg_range_zu(&sa, ZU(1) << (3 + LG_SIZEOF_PTR), atomic);
- sa = 42;
- rb = prng_lg_range_zu(&sa, ZU(1) << (3 + LG_SIZEOF_PTR), atomic);
- assert_zu_eq(ra, rb,
- "Repeated generation should produce repeated results");
-
- sb = 42;
- rb = prng_lg_range_zu(&sb, ZU(1) << (3 + LG_SIZEOF_PTR), atomic);
- assert_zu_eq(ra, rb,
- "Equivalent generation should produce equivalent results");
-
- sa = 42;
- ra = prng_lg_range_zu(&sa, ZU(1) << (3 + LG_SIZEOF_PTR), atomic);
- rb = prng_lg_range_zu(&sa, ZU(1) << (3 + LG_SIZEOF_PTR), atomic);
- assert_zu_ne(ra, rb,
- "Full-width results must not immediately repeat");
-
- sa = 42;
- ra = prng_lg_range_zu(&sa, ZU(1) << (3 + LG_SIZEOF_PTR), atomic);
- for (lg_range = (ZU(1) << (3 + LG_SIZEOF_PTR)) - 1; lg_range > 0;
- lg_range--) {
- sb = 42;
- rb = prng_lg_range_zu(&sb, lg_range, atomic);
- assert_zu_eq((rb & (SIZE_T_MAX << lg_range)),
- 0, "High order bits should be 0, lg_range=%u", lg_range);
- assert_zu_eq(rb, (ra >> ((ZU(1) << (3 + LG_SIZEOF_PTR)) -
- lg_range)), "Expected high order bits of full-width "
- "result, lg_range=%u", lg_range);
- }
-}
-
-TEST_BEGIN(test_prng_lg_range_u32_nonatomic)
-{
-
- test_prng_lg_range_u32(false);
-}
-TEST_END
-
-TEST_BEGIN(test_prng_lg_range_u32_atomic)
-{
-
- test_prng_lg_range_u32(true);
-}
-TEST_END
-
-TEST_BEGIN(test_prng_lg_range_u64_nonatomic)
-{
-
- test_prng_lg_range_u64();
-}
-TEST_END
-
-TEST_BEGIN(test_prng_lg_range_zu_nonatomic)
-{
-
- test_prng_lg_range_zu(false);
-}
-TEST_END
-
-TEST_BEGIN(test_prng_lg_range_zu_atomic)
-{
-
- test_prng_lg_range_zu(true);
-}
-TEST_END
-
-static void
-test_prng_range_u32(bool atomic)
-{
- uint32_t range;
-#define MAX_RANGE 10000000
-#define RANGE_STEP 97
-#define NREPS 10
-
- for (range = 2; range < MAX_RANGE; range += RANGE_STEP) {
- uint32_t s;
- unsigned rep;
-
- s = range;
- for (rep = 0; rep < NREPS; rep++) {
- uint32_t r = prng_range_u32(&s, range, atomic);
-
- assert_u32_lt(r, range, "Out of range");
- }
- }
-}
-
-static void
-test_prng_range_u64(void)
-{
- uint64_t range;
-#define MAX_RANGE 10000000
-#define RANGE_STEP 97
-#define NREPS 10
-
- for (range = 2; range < MAX_RANGE; range += RANGE_STEP) {
- uint64_t s;
- unsigned rep;
-
- s = range;
- for (rep = 0; rep < NREPS; rep++) {
- uint64_t r = prng_range_u64(&s, range);
-
- assert_u64_lt(r, range, "Out of range");
- }
- }
-}
-
-static void
-test_prng_range_zu(bool atomic)
-{
- size_t range;
-#define MAX_RANGE 10000000
-#define RANGE_STEP 97
-#define NREPS 10
-
- for (range = 2; range < MAX_RANGE; range += RANGE_STEP) {
- size_t s;
- unsigned rep;
-
- s = range;
- for (rep = 0; rep < NREPS; rep++) {
- size_t r = prng_range_zu(&s, range, atomic);
-
- assert_zu_lt(r, range, "Out of range");
- }
- }
-}
-
-TEST_BEGIN(test_prng_range_u32_nonatomic)
-{
-
- test_prng_range_u32(false);
-}
-TEST_END
-
-TEST_BEGIN(test_prng_range_u32_atomic)
-{
-
- test_prng_range_u32(true);
-}
-TEST_END
-
-TEST_BEGIN(test_prng_range_u64_nonatomic)
-{
-
- test_prng_range_u64();
-}
-TEST_END
-
-TEST_BEGIN(test_prng_range_zu_nonatomic)
-{
-
- test_prng_range_zu(false);
-}
-TEST_END
-
-TEST_BEGIN(test_prng_range_zu_atomic)
-{
-
- test_prng_range_zu(true);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_prng_lg_range_u32_nonatomic,
- test_prng_lg_range_u32_atomic,
- test_prng_lg_range_u64_nonatomic,
- test_prng_lg_range_zu_nonatomic,
- test_prng_lg_range_zu_atomic,
- test_prng_range_u32_nonatomic,
- test_prng_range_u32_atomic,
- test_prng_range_u64_nonatomic,
- test_prng_range_zu_nonatomic,
- test_prng_range_zu_atomic));
-}
diff --git a/memory/jemalloc/src/test/unit/prof_accum.c b/memory/jemalloc/src/test/unit/prof_accum.c
deleted file mode 100644
index fd229e0fd..000000000
--- a/memory/jemalloc/src/test/unit/prof_accum.c
+++ /dev/null
@@ -1,91 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define NTHREADS 4
-#define NALLOCS_PER_THREAD 50
-#define DUMP_INTERVAL 1
-#define BT_COUNT_CHECK_INTERVAL 5
-
-#ifdef JEMALLOC_PROF
-const char *malloc_conf =
- "prof:true,prof_accum:true,prof_active:false,lg_prof_sample:0";
-#endif
-
-static int
-prof_dump_open_intercept(bool propagate_err, const char *filename)
-{
- int fd;
-
- fd = open("/dev/null", O_WRONLY);
- assert_d_ne(fd, -1, "Unexpected open() failure");
-
- return (fd);
-}
-
-static void *
-alloc_from_permuted_backtrace(unsigned thd_ind, unsigned iteration)
-{
-
- return (btalloc(1, thd_ind*NALLOCS_PER_THREAD + iteration));
-}
-
-static void *
-thd_start(void *varg)
-{
- unsigned thd_ind = *(unsigned *)varg;
- size_t bt_count_prev, bt_count;
- unsigned i_prev, i;
-
- i_prev = 0;
- bt_count_prev = 0;
- for (i = 0; i < NALLOCS_PER_THREAD; i++) {
- void *p = alloc_from_permuted_backtrace(thd_ind, i);
- dallocx(p, 0);
- if (i % DUMP_INTERVAL == 0) {
- assert_d_eq(mallctl("prof.dump", NULL, NULL, NULL, 0),
- 0, "Unexpected error while dumping heap profile");
- }
-
- if (i % BT_COUNT_CHECK_INTERVAL == 0 ||
- i+1 == NALLOCS_PER_THREAD) {
- bt_count = prof_bt_count();
- assert_zu_le(bt_count_prev+(i-i_prev), bt_count,
- "Expected larger backtrace count increase");
- i_prev = i;
- bt_count_prev = bt_count;
- }
- }
-
- return (NULL);
-}
-
-TEST_BEGIN(test_idump)
-{
- bool active;
- thd_t thds[NTHREADS];
- unsigned thd_args[NTHREADS];
- unsigned i;
-
- test_skip_if(!config_prof);
-
- active = true;
- assert_d_eq(mallctl("prof.active", NULL, NULL, &active, sizeof(active)),
- 0, "Unexpected mallctl failure while activating profiling");
-
- prof_dump_open = prof_dump_open_intercept;
-
- for (i = 0; i < NTHREADS; i++) {
- thd_args[i] = i;
- thd_create(&thds[i], thd_start, (void *)&thd_args[i]);
- }
- for (i = 0; i < NTHREADS; i++)
- thd_join(thds[i], NULL);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_idump));
-}
diff --git a/memory/jemalloc/src/test/unit/prof_active.c b/memory/jemalloc/src/test/unit/prof_active.c
deleted file mode 100644
index 814909572..000000000
--- a/memory/jemalloc/src/test/unit/prof_active.c
+++ /dev/null
@@ -1,136 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_PROF
-const char *malloc_conf =
- "prof:true,prof_thread_active_init:false,lg_prof_sample:0";
-#endif
-
-static void
-mallctl_bool_get(const char *name, bool expected, const char *func, int line)
-{
- bool old;
- size_t sz;
-
- sz = sizeof(old);
- assert_d_eq(mallctl(name, &old, &sz, NULL, 0), 0,
- "%s():%d: Unexpected mallctl failure reading %s", func, line, name);
- assert_b_eq(old, expected, "%s():%d: Unexpected %s value", func, line,
- name);
-}
-
-static void
-mallctl_bool_set(const char *name, bool old_expected, bool val_new,
- const char *func, int line)
-{
- bool old;
- size_t sz;
-
- sz = sizeof(old);
- assert_d_eq(mallctl(name, &old, &sz, &val_new, sizeof(val_new)), 0,
- "%s():%d: Unexpected mallctl failure reading/writing %s", func,
- line, name);
- assert_b_eq(old, old_expected, "%s():%d: Unexpected %s value", func,
- line, name);
-}
-
-static void
-mallctl_prof_active_get_impl(bool prof_active_old_expected, const char *func,
- int line)
-{
-
- mallctl_bool_get("prof.active", prof_active_old_expected, func, line);
-}
-#define mallctl_prof_active_get(a) \
- mallctl_prof_active_get_impl(a, __func__, __LINE__)
-
-static void
-mallctl_prof_active_set_impl(bool prof_active_old_expected,
- bool prof_active_new, const char *func, int line)
-{
-
- mallctl_bool_set("prof.active", prof_active_old_expected,
- prof_active_new, func, line);
-}
-#define mallctl_prof_active_set(a, b) \
- mallctl_prof_active_set_impl(a, b, __func__, __LINE__)
-
-static void
-mallctl_thread_prof_active_get_impl(bool thread_prof_active_old_expected,
- const char *func, int line)
-{
-
- mallctl_bool_get("thread.prof.active", thread_prof_active_old_expected,
- func, line);
-}
-#define mallctl_thread_prof_active_get(a) \
- mallctl_thread_prof_active_get_impl(a, __func__, __LINE__)
-
-static void
-mallctl_thread_prof_active_set_impl(bool thread_prof_active_old_expected,
- bool thread_prof_active_new, const char *func, int line)
-{
-
- mallctl_bool_set("thread.prof.active", thread_prof_active_old_expected,
- thread_prof_active_new, func, line);
-}
-#define mallctl_thread_prof_active_set(a, b) \
- mallctl_thread_prof_active_set_impl(a, b, __func__, __LINE__)
-
-static void
-prof_sampling_probe_impl(bool expect_sample, const char *func, int line)
-{
- void *p;
- size_t expected_backtraces = expect_sample ? 1 : 0;
-
- assert_zu_eq(prof_bt_count(), 0, "%s():%d: Expected 0 backtraces", func,
- line);
- p = mallocx(1, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- assert_zu_eq(prof_bt_count(), expected_backtraces,
- "%s():%d: Unexpected backtrace count", func, line);
- dallocx(p, 0);
-}
-#define prof_sampling_probe(a) \
- prof_sampling_probe_impl(a, __func__, __LINE__)
-
-TEST_BEGIN(test_prof_active)
-{
-
- test_skip_if(!config_prof);
-
- mallctl_prof_active_get(true);
- mallctl_thread_prof_active_get(false);
-
- mallctl_prof_active_set(true, true);
- mallctl_thread_prof_active_set(false, false);
- /* prof.active, !thread.prof.active. */
- prof_sampling_probe(false);
-
- mallctl_prof_active_set(true, false);
- mallctl_thread_prof_active_set(false, false);
- /* !prof.active, !thread.prof.active. */
- prof_sampling_probe(false);
-
- mallctl_prof_active_set(false, false);
- mallctl_thread_prof_active_set(false, true);
- /* !prof.active, thread.prof.active. */
- prof_sampling_probe(false);
-
- mallctl_prof_active_set(false, true);
- mallctl_thread_prof_active_set(true, true);
- /* prof.active, thread.prof.active. */
- prof_sampling_probe(true);
-
- /* Restore settings. */
- mallctl_prof_active_set(true, true);
- mallctl_thread_prof_active_set(true, false);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_prof_active));
-}
diff --git a/memory/jemalloc/src/test/unit/prof_gdump.c b/memory/jemalloc/src/test/unit/prof_gdump.c
deleted file mode 100644
index a0e6ee921..000000000
--- a/memory/jemalloc/src/test/unit/prof_gdump.c
+++ /dev/null
@@ -1,81 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_PROF
-const char *malloc_conf = "prof:true,prof_active:false,prof_gdump:true";
-#endif
-
-static bool did_prof_dump_open;
-
-static int
-prof_dump_open_intercept(bool propagate_err, const char *filename)
-{
- int fd;
-
- did_prof_dump_open = true;
-
- fd = open("/dev/null", O_WRONLY);
- assert_d_ne(fd, -1, "Unexpected open() failure");
-
- return (fd);
-}
-
-TEST_BEGIN(test_gdump)
-{
- bool active, gdump, gdump_old;
- void *p, *q, *r, *s;
- size_t sz;
-
- test_skip_if(!config_prof);
-
- active = true;
- assert_d_eq(mallctl("prof.active", NULL, NULL, &active, sizeof(active)),
- 0, "Unexpected mallctl failure while activating profiling");
-
- prof_dump_open = prof_dump_open_intercept;
-
- did_prof_dump_open = false;
- p = mallocx(chunksize, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- assert_true(did_prof_dump_open, "Expected a profile dump");
-
- did_prof_dump_open = false;
- q = mallocx(chunksize, 0);
- assert_ptr_not_null(q, "Unexpected mallocx() failure");
- assert_true(did_prof_dump_open, "Expected a profile dump");
-
- gdump = false;
- sz = sizeof(gdump_old);
- assert_d_eq(mallctl("prof.gdump", &gdump_old, &sz, &gdump,
- sizeof(gdump)), 0,
- "Unexpected mallctl failure while disabling prof.gdump");
- assert(gdump_old);
- did_prof_dump_open = false;
- r = mallocx(chunksize, 0);
- assert_ptr_not_null(q, "Unexpected mallocx() failure");
- assert_false(did_prof_dump_open, "Unexpected profile dump");
-
- gdump = true;
- sz = sizeof(gdump_old);
- assert_d_eq(mallctl("prof.gdump", &gdump_old, &sz, &gdump,
- sizeof(gdump)), 0,
- "Unexpected mallctl failure while enabling prof.gdump");
- assert(!gdump_old);
- did_prof_dump_open = false;
- s = mallocx(chunksize, 0);
- assert_ptr_not_null(q, "Unexpected mallocx() failure");
- assert_true(did_prof_dump_open, "Expected a profile dump");
-
- dallocx(p, 0);
- dallocx(q, 0);
- dallocx(r, 0);
- dallocx(s, 0);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_gdump));
-}
diff --git a/memory/jemalloc/src/test/unit/prof_idump.c b/memory/jemalloc/src/test/unit/prof_idump.c
deleted file mode 100644
index bdea53ecd..000000000
--- a/memory/jemalloc/src/test/unit/prof_idump.c
+++ /dev/null
@@ -1,51 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_PROF
-const char *malloc_conf =
- "prof:true,prof_accum:true,prof_active:false,lg_prof_sample:0,"
- "lg_prof_interval:0";
-#endif
-
-static bool did_prof_dump_open;
-
-static int
-prof_dump_open_intercept(bool propagate_err, const char *filename)
-{
- int fd;
-
- did_prof_dump_open = true;
-
- fd = open("/dev/null", O_WRONLY);
- assert_d_ne(fd, -1, "Unexpected open() failure");
-
- return (fd);
-}
-
-TEST_BEGIN(test_idump)
-{
- bool active;
- void *p;
-
- test_skip_if(!config_prof);
-
- active = true;
- assert_d_eq(mallctl("prof.active", NULL, NULL, &active, sizeof(active)),
- 0, "Unexpected mallctl failure while activating profiling");
-
- prof_dump_open = prof_dump_open_intercept;
-
- did_prof_dump_open = false;
- p = mallocx(1, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- dallocx(p, 0);
- assert_true(did_prof_dump_open, "Expected a profile dump");
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_idump));
-}
diff --git a/memory/jemalloc/src/test/unit/prof_reset.c b/memory/jemalloc/src/test/unit/prof_reset.c
deleted file mode 100644
index 5ae45fd2c..000000000
--- a/memory/jemalloc/src/test/unit/prof_reset.c
+++ /dev/null
@@ -1,303 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_PROF
-const char *malloc_conf =
- "prof:true,prof_active:false,lg_prof_sample:0";
-#endif
-
-static int
-prof_dump_open_intercept(bool propagate_err, const char *filename)
-{
- int fd;
-
- fd = open("/dev/null", O_WRONLY);
- assert_d_ne(fd, -1, "Unexpected open() failure");
-
- return (fd);
-}
-
-static void
-set_prof_active(bool active)
-{
-
- assert_d_eq(mallctl("prof.active", NULL, NULL, &active, sizeof(active)),
- 0, "Unexpected mallctl failure");
-}
-
-static size_t
-get_lg_prof_sample(void)
-{
- size_t lg_prof_sample;
- size_t sz = sizeof(size_t);
-
- assert_d_eq(mallctl("prof.lg_sample", &lg_prof_sample, &sz, NULL, 0), 0,
- "Unexpected mallctl failure while reading profiling sample rate");
- return (lg_prof_sample);
-}
-
-static void
-do_prof_reset(size_t lg_prof_sample)
-{
- assert_d_eq(mallctl("prof.reset", NULL, NULL,
- &lg_prof_sample, sizeof(size_t)), 0,
- "Unexpected mallctl failure while resetting profile data");
- assert_zu_eq(lg_prof_sample, get_lg_prof_sample(),
- "Expected profile sample rate change");
-}
-
-TEST_BEGIN(test_prof_reset_basic)
-{
- size_t lg_prof_sample_orig, lg_prof_sample, lg_prof_sample_next;
- size_t sz;
- unsigned i;
-
- test_skip_if(!config_prof);
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("opt.lg_prof_sample", &lg_prof_sample_orig, &sz,
- NULL, 0), 0,
- "Unexpected mallctl failure while reading profiling sample rate");
- assert_zu_eq(lg_prof_sample_orig, 0,
- "Unexpected profiling sample rate");
- lg_prof_sample = get_lg_prof_sample();
- assert_zu_eq(lg_prof_sample_orig, lg_prof_sample,
- "Unexpected disagreement between \"opt.lg_prof_sample\" and "
- "\"prof.lg_sample\"");
-
- /* Test simple resets. */
- for (i = 0; i < 2; i++) {
- assert_d_eq(mallctl("prof.reset", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl failure while resetting profile data");
- lg_prof_sample = get_lg_prof_sample();
- assert_zu_eq(lg_prof_sample_orig, lg_prof_sample,
- "Unexpected profile sample rate change");
- }
-
- /* Test resets with prof.lg_sample changes. */
- lg_prof_sample_next = 1;
- for (i = 0; i < 2; i++) {
- do_prof_reset(lg_prof_sample_next);
- lg_prof_sample = get_lg_prof_sample();
- assert_zu_eq(lg_prof_sample, lg_prof_sample_next,
- "Expected profile sample rate change");
- lg_prof_sample_next = lg_prof_sample_orig;
- }
-
- /* Make sure the test code restored prof.lg_sample. */
- lg_prof_sample = get_lg_prof_sample();
- assert_zu_eq(lg_prof_sample_orig, lg_prof_sample,
- "Unexpected disagreement between \"opt.lg_prof_sample\" and "
- "\"prof.lg_sample\"");
-}
-TEST_END
-
-bool prof_dump_header_intercepted = false;
-prof_cnt_t cnt_all_copy = {0, 0, 0, 0};
-static bool
-prof_dump_header_intercept(tsdn_t *tsdn, bool propagate_err,
- const prof_cnt_t *cnt_all)
-{
-
- prof_dump_header_intercepted = true;
- memcpy(&cnt_all_copy, cnt_all, sizeof(prof_cnt_t));
-
- return (false);
-}
-
-TEST_BEGIN(test_prof_reset_cleanup)
-{
- void *p;
- prof_dump_header_t *prof_dump_header_orig;
-
- test_skip_if(!config_prof);
-
- set_prof_active(true);
-
- assert_zu_eq(prof_bt_count(), 0, "Expected 0 backtraces");
- p = mallocx(1, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- assert_zu_eq(prof_bt_count(), 1, "Expected 1 backtrace");
-
- prof_dump_header_orig = prof_dump_header;
- prof_dump_header = prof_dump_header_intercept;
- assert_false(prof_dump_header_intercepted, "Unexpected intercept");
-
- assert_d_eq(mallctl("prof.dump", NULL, NULL, NULL, 0),
- 0, "Unexpected error while dumping heap profile");
- assert_true(prof_dump_header_intercepted, "Expected intercept");
- assert_u64_eq(cnt_all_copy.curobjs, 1, "Expected 1 allocation");
-
- assert_d_eq(mallctl("prof.reset", NULL, NULL, NULL, 0), 0,
- "Unexpected error while resetting heap profile data");
- assert_d_eq(mallctl("prof.dump", NULL, NULL, NULL, 0),
- 0, "Unexpected error while dumping heap profile");
- assert_u64_eq(cnt_all_copy.curobjs, 0, "Expected 0 allocations");
- assert_zu_eq(prof_bt_count(), 1, "Expected 1 backtrace");
-
- prof_dump_header = prof_dump_header_orig;
-
- dallocx(p, 0);
- assert_zu_eq(prof_bt_count(), 0, "Expected 0 backtraces");
-
- set_prof_active(false);
-}
-TEST_END
-
-#define NTHREADS 4
-#define NALLOCS_PER_THREAD (1U << 13)
-#define OBJ_RING_BUF_COUNT 1531
-#define RESET_INTERVAL (1U << 10)
-#define DUMP_INTERVAL 3677
-static void *
-thd_start(void *varg)
-{
- unsigned thd_ind = *(unsigned *)varg;
- unsigned i;
- void *objs[OBJ_RING_BUF_COUNT];
-
- memset(objs, 0, sizeof(objs));
-
- for (i = 0; i < NALLOCS_PER_THREAD; i++) {
- if (i % RESET_INTERVAL == 0) {
- assert_d_eq(mallctl("prof.reset", NULL, NULL, NULL, 0),
- 0, "Unexpected error while resetting heap profile "
- "data");
- }
-
- if (i % DUMP_INTERVAL == 0) {
- assert_d_eq(mallctl("prof.dump", NULL, NULL, NULL, 0),
- 0, "Unexpected error while dumping heap profile");
- }
-
- {
- void **pp = &objs[i % OBJ_RING_BUF_COUNT];
- if (*pp != NULL) {
- dallocx(*pp, 0);
- *pp = NULL;
- }
- *pp = btalloc(1, thd_ind*NALLOCS_PER_THREAD + i);
- assert_ptr_not_null(*pp,
- "Unexpected btalloc() failure");
- }
- }
-
- /* Clean up any remaining objects. */
- for (i = 0; i < OBJ_RING_BUF_COUNT; i++) {
- void **pp = &objs[i % OBJ_RING_BUF_COUNT];
- if (*pp != NULL) {
- dallocx(*pp, 0);
- *pp = NULL;
- }
- }
-
- return (NULL);
-}
-
-TEST_BEGIN(test_prof_reset)
-{
- size_t lg_prof_sample_orig;
- thd_t thds[NTHREADS];
- unsigned thd_args[NTHREADS];
- unsigned i;
- size_t bt_count, tdata_count;
-
- test_skip_if(!config_prof);
-
- bt_count = prof_bt_count();
- assert_zu_eq(bt_count, 0,
- "Unexpected pre-existing tdata structures");
- tdata_count = prof_tdata_count();
-
- lg_prof_sample_orig = get_lg_prof_sample();
- do_prof_reset(5);
-
- set_prof_active(true);
-
- for (i = 0; i < NTHREADS; i++) {
- thd_args[i] = i;
- thd_create(&thds[i], thd_start, (void *)&thd_args[i]);
- }
- for (i = 0; i < NTHREADS; i++)
- thd_join(thds[i], NULL);
-
- assert_zu_eq(prof_bt_count(), bt_count,
- "Unexpected bactrace count change");
- assert_zu_eq(prof_tdata_count(), tdata_count,
- "Unexpected remaining tdata structures");
-
- set_prof_active(false);
-
- do_prof_reset(lg_prof_sample_orig);
-}
-TEST_END
-#undef NTHREADS
-#undef NALLOCS_PER_THREAD
-#undef OBJ_RING_BUF_COUNT
-#undef RESET_INTERVAL
-#undef DUMP_INTERVAL
-
-/* Test sampling at the same allocation site across resets. */
-#define NITER 10
-TEST_BEGIN(test_xallocx)
-{
- size_t lg_prof_sample_orig;
- unsigned i;
- void *ptrs[NITER];
-
- test_skip_if(!config_prof);
-
- lg_prof_sample_orig = get_lg_prof_sample();
- set_prof_active(true);
-
- /* Reset profiling. */
- do_prof_reset(0);
-
- for (i = 0; i < NITER; i++) {
- void *p;
- size_t sz, nsz;
-
- /* Reset profiling. */
- do_prof_reset(0);
-
- /* Allocate small object (which will be promoted). */
- p = ptrs[i] = mallocx(1, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- /* Reset profiling. */
- do_prof_reset(0);
-
- /* Perform successful xallocx(). */
- sz = sallocx(p, 0);
- assert_zu_eq(xallocx(p, sz, 0, 0), sz,
- "Unexpected xallocx() failure");
-
- /* Perform unsuccessful xallocx(). */
- nsz = nallocx(sz+1, 0);
- assert_zu_eq(xallocx(p, nsz, 0, 0), sz,
- "Unexpected xallocx() success");
- }
-
- for (i = 0; i < NITER; i++) {
- /* dallocx. */
- dallocx(ptrs[i], 0);
- }
-
- set_prof_active(false);
- do_prof_reset(lg_prof_sample_orig);
-}
-TEST_END
-#undef NITER
-
-int
-main(void)
-{
-
- /* Intercept dumping prior to running any tests. */
- prof_dump_open = prof_dump_open_intercept;
-
- return (test(
- test_prof_reset_basic,
- test_prof_reset_cleanup,
- test_prof_reset,
- test_xallocx));
-}
diff --git a/memory/jemalloc/src/test/unit/prof_thread_name.c b/memory/jemalloc/src/test/unit/prof_thread_name.c
deleted file mode 100644
index f501158d7..000000000
--- a/memory/jemalloc/src/test/unit/prof_thread_name.c
+++ /dev/null
@@ -1,129 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_PROF
-const char *malloc_conf = "prof:true,prof_active:false";
-#endif
-
-static void
-mallctl_thread_name_get_impl(const char *thread_name_expected, const char *func,
- int line)
-{
- const char *thread_name_old;
- size_t sz;
-
- sz = sizeof(thread_name_old);
- assert_d_eq(mallctl("thread.prof.name", &thread_name_old, &sz, NULL, 0),
- 0, "%s():%d: Unexpected mallctl failure reading thread.prof.name",
- func, line);
- assert_str_eq(thread_name_old, thread_name_expected,
- "%s():%d: Unexpected thread.prof.name value", func, line);
-}
-#define mallctl_thread_name_get(a) \
- mallctl_thread_name_get_impl(a, __func__, __LINE__)
-
-static void
-mallctl_thread_name_set_impl(const char *thread_name, const char *func,
- int line)
-{
-
- assert_d_eq(mallctl("thread.prof.name", NULL, NULL, &thread_name,
- sizeof(thread_name)), 0,
- "%s():%d: Unexpected mallctl failure reading thread.prof.name",
- func, line);
- mallctl_thread_name_get_impl(thread_name, func, line);
-}
-#define mallctl_thread_name_set(a) \
- mallctl_thread_name_set_impl(a, __func__, __LINE__)
-
-TEST_BEGIN(test_prof_thread_name_validation)
-{
- const char *thread_name;
-
- test_skip_if(!config_prof);
-
- mallctl_thread_name_get("");
- mallctl_thread_name_set("hi there");
-
- /* NULL input shouldn't be allowed. */
- thread_name = NULL;
- assert_d_eq(mallctl("thread.prof.name", NULL, NULL, &thread_name,
- sizeof(thread_name)), EFAULT,
- "Unexpected mallctl result writing \"%s\" to thread.prof.name",
- thread_name);
-
- /* '\n' shouldn't be allowed. */
- thread_name = "hi\nthere";
- assert_d_eq(mallctl("thread.prof.name", NULL, NULL, &thread_name,
- sizeof(thread_name)), EFAULT,
- "Unexpected mallctl result writing \"%s\" to thread.prof.name",
- thread_name);
-
- /* Simultaneous read/write shouldn't be allowed. */
- {
- const char *thread_name_old;
- size_t sz;
-
- sz = sizeof(thread_name_old);
- assert_d_eq(mallctl("thread.prof.name", &thread_name_old, &sz,
- &thread_name, sizeof(thread_name)), EPERM,
- "Unexpected mallctl result writing \"%s\" to "
- "thread.prof.name", thread_name);
- }
-
- mallctl_thread_name_set("");
-}
-TEST_END
-
-#define NTHREADS 4
-#define NRESET 25
-static void *
-thd_start(void *varg)
-{
- unsigned thd_ind = *(unsigned *)varg;
- char thread_name[16] = "";
- unsigned i;
-
- malloc_snprintf(thread_name, sizeof(thread_name), "thread %u", thd_ind);
-
- mallctl_thread_name_get("");
- mallctl_thread_name_set(thread_name);
-
- for (i = 0; i < NRESET; i++) {
- assert_d_eq(mallctl("prof.reset", NULL, NULL, NULL, 0), 0,
- "Unexpected error while resetting heap profile data");
- mallctl_thread_name_get(thread_name);
- }
-
- mallctl_thread_name_set(thread_name);
- mallctl_thread_name_set("");
-
- return (NULL);
-}
-
-TEST_BEGIN(test_prof_thread_name_threaded)
-{
- thd_t thds[NTHREADS];
- unsigned thd_args[NTHREADS];
- unsigned i;
-
- test_skip_if(!config_prof);
-
- for (i = 0; i < NTHREADS; i++) {
- thd_args[i] = i;
- thd_create(&thds[i], thd_start, (void *)&thd_args[i]);
- }
- for (i = 0; i < NTHREADS; i++)
- thd_join(thds[i], NULL);
-}
-TEST_END
-#undef NTHREADS
-#undef NRESET
-
-int
-main(void)
-{
-
- return (test(
- test_prof_thread_name_validation,
- test_prof_thread_name_threaded));
-}
diff --git a/memory/jemalloc/src/test/unit/ql.c b/memory/jemalloc/src/test/unit/ql.c
deleted file mode 100644
index 05fad450f..000000000
--- a/memory/jemalloc/src/test/unit/ql.c
+++ /dev/null
@@ -1,209 +0,0 @@
-#include "test/jemalloc_test.h"
-
-/* Number of ring entries, in [2..26]. */
-#define NENTRIES 9
-
-typedef struct list_s list_t;
-typedef ql_head(list_t) list_head_t;
-
-struct list_s {
- ql_elm(list_t) link;
- char id;
-};
-
-static void
-test_empty_list(list_head_t *head)
-{
- list_t *t;
- unsigned i;
-
- assert_ptr_null(ql_first(head), "Unexpected element for empty list");
- assert_ptr_null(ql_last(head, link),
- "Unexpected element for empty list");
-
- i = 0;
- ql_foreach(t, head, link) {
- i++;
- }
- assert_u_eq(i, 0, "Unexpected element for empty list");
-
- i = 0;
- ql_reverse_foreach(t, head, link) {
- i++;
- }
- assert_u_eq(i, 0, "Unexpected element for empty list");
-}
-
-TEST_BEGIN(test_ql_empty)
-{
- list_head_t head;
-
- ql_new(&head);
- test_empty_list(&head);
-}
-TEST_END
-
-static void
-init_entries(list_t *entries, unsigned nentries)
-{
- unsigned i;
-
- for (i = 0; i < nentries; i++) {
- entries[i].id = 'a' + i;
- ql_elm_new(&entries[i], link);
- }
-}
-
-static void
-test_entries_list(list_head_t *head, list_t *entries, unsigned nentries)
-{
- list_t *t;
- unsigned i;
-
- assert_c_eq(ql_first(head)->id, entries[0].id, "Element id mismatch");
- assert_c_eq(ql_last(head, link)->id, entries[nentries-1].id,
- "Element id mismatch");
-
- i = 0;
- ql_foreach(t, head, link) {
- assert_c_eq(t->id, entries[i].id, "Element id mismatch");
- i++;
- }
-
- i = 0;
- ql_reverse_foreach(t, head, link) {
- assert_c_eq(t->id, entries[nentries-i-1].id,
- "Element id mismatch");
- i++;
- }
-
- for (i = 0; i < nentries-1; i++) {
- t = ql_next(head, &entries[i], link);
- assert_c_eq(t->id, entries[i+1].id, "Element id mismatch");
- }
- assert_ptr_null(ql_next(head, &entries[nentries-1], link),
- "Unexpected element");
-
- assert_ptr_null(ql_prev(head, &entries[0], link), "Unexpected element");
- for (i = 1; i < nentries; i++) {
- t = ql_prev(head, &entries[i], link);
- assert_c_eq(t->id, entries[i-1].id, "Element id mismatch");
- }
-}
-
-TEST_BEGIN(test_ql_tail_insert)
-{
- list_head_t head;
- list_t entries[NENTRIES];
- unsigned i;
-
- ql_new(&head);
- init_entries(entries, sizeof(entries)/sizeof(list_t));
- for (i = 0; i < NENTRIES; i++)
- ql_tail_insert(&head, &entries[i], link);
-
- test_entries_list(&head, entries, NENTRIES);
-}
-TEST_END
-
-TEST_BEGIN(test_ql_tail_remove)
-{
- list_head_t head;
- list_t entries[NENTRIES];
- unsigned i;
-
- ql_new(&head);
- init_entries(entries, sizeof(entries)/sizeof(list_t));
- for (i = 0; i < NENTRIES; i++)
- ql_tail_insert(&head, &entries[i], link);
-
- for (i = 0; i < NENTRIES; i++) {
- test_entries_list(&head, entries, NENTRIES-i);
- ql_tail_remove(&head, list_t, link);
- }
- test_empty_list(&head);
-}
-TEST_END
-
-TEST_BEGIN(test_ql_head_insert)
-{
- list_head_t head;
- list_t entries[NENTRIES];
- unsigned i;
-
- ql_new(&head);
- init_entries(entries, sizeof(entries)/sizeof(list_t));
- for (i = 0; i < NENTRIES; i++)
- ql_head_insert(&head, &entries[NENTRIES-i-1], link);
-
- test_entries_list(&head, entries, NENTRIES);
-}
-TEST_END
-
-TEST_BEGIN(test_ql_head_remove)
-{
- list_head_t head;
- list_t entries[NENTRIES];
- unsigned i;
-
- ql_new(&head);
- init_entries(entries, sizeof(entries)/sizeof(list_t));
- for (i = 0; i < NENTRIES; i++)
- ql_head_insert(&head, &entries[NENTRIES-i-1], link);
-
- for (i = 0; i < NENTRIES; i++) {
- test_entries_list(&head, &entries[i], NENTRIES-i);
- ql_head_remove(&head, list_t, link);
- }
- test_empty_list(&head);
-}
-TEST_END
-
-TEST_BEGIN(test_ql_insert)
-{
- list_head_t head;
- list_t entries[8];
- list_t *a, *b, *c, *d, *e, *f, *g, *h;
-
- ql_new(&head);
- init_entries(entries, sizeof(entries)/sizeof(list_t));
- a = &entries[0];
- b = &entries[1];
- c = &entries[2];
- d = &entries[3];
- e = &entries[4];
- f = &entries[5];
- g = &entries[6];
- h = &entries[7];
-
- /*
- * ql_remove(), ql_before_insert(), and ql_after_insert() are used
- * internally by other macros that are already tested, so there's no
- * need to test them completely. However, insertion/deletion from the
- * middle of lists is not otherwise tested; do so here.
- */
- ql_tail_insert(&head, f, link);
- ql_before_insert(&head, f, b, link);
- ql_before_insert(&head, f, c, link);
- ql_after_insert(f, h, link);
- ql_after_insert(f, g, link);
- ql_before_insert(&head, b, a, link);
- ql_after_insert(c, d, link);
- ql_before_insert(&head, f, e, link);
-
- test_entries_list(&head, entries, sizeof(entries)/sizeof(list_t));
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_ql_empty,
- test_ql_tail_insert,
- test_ql_tail_remove,
- test_ql_head_insert,
- test_ql_head_remove,
- test_ql_insert));
-}
diff --git a/memory/jemalloc/src/test/unit/qr.c b/memory/jemalloc/src/test/unit/qr.c
deleted file mode 100644
index a2a2d902b..000000000
--- a/memory/jemalloc/src/test/unit/qr.c
+++ /dev/null
@@ -1,248 +0,0 @@
-#include "test/jemalloc_test.h"
-
-/* Number of ring entries, in [2..26]. */
-#define NENTRIES 9
-/* Split index, in [1..NENTRIES). */
-#define SPLIT_INDEX 5
-
-typedef struct ring_s ring_t;
-
-struct ring_s {
- qr(ring_t) link;
- char id;
-};
-
-static void
-init_entries(ring_t *entries)
-{
- unsigned i;
-
- for (i = 0; i < NENTRIES; i++) {
- qr_new(&entries[i], link);
- entries[i].id = 'a' + i;
- }
-}
-
-static void
-test_independent_entries(ring_t *entries)
-{
- ring_t *t;
- unsigned i, j;
-
- for (i = 0; i < NENTRIES; i++) {
- j = 0;
- qr_foreach(t, &entries[i], link) {
- j++;
- }
- assert_u_eq(j, 1,
- "Iteration over single-element ring should visit precisely "
- "one element");
- }
- for (i = 0; i < NENTRIES; i++) {
- j = 0;
- qr_reverse_foreach(t, &entries[i], link) {
- j++;
- }
- assert_u_eq(j, 1,
- "Iteration over single-element ring should visit precisely "
- "one element");
- }
- for (i = 0; i < NENTRIES; i++) {
- t = qr_next(&entries[i], link);
- assert_ptr_eq(t, &entries[i],
- "Next element in single-element ring should be same as "
- "current element");
- }
- for (i = 0; i < NENTRIES; i++) {
- t = qr_prev(&entries[i], link);
- assert_ptr_eq(t, &entries[i],
- "Previous element in single-element ring should be same as "
- "current element");
- }
-}
-
-TEST_BEGIN(test_qr_one)
-{
- ring_t entries[NENTRIES];
-
- init_entries(entries);
- test_independent_entries(entries);
-}
-TEST_END
-
-static void
-test_entries_ring(ring_t *entries)
-{
- ring_t *t;
- unsigned i, j;
-
- for (i = 0; i < NENTRIES; i++) {
- j = 0;
- qr_foreach(t, &entries[i], link) {
- assert_c_eq(t->id, entries[(i+j) % NENTRIES].id,
- "Element id mismatch");
- j++;
- }
- }
- for (i = 0; i < NENTRIES; i++) {
- j = 0;
- qr_reverse_foreach(t, &entries[i], link) {
- assert_c_eq(t->id, entries[(NENTRIES+i-j-1) %
- NENTRIES].id, "Element id mismatch");
- j++;
- }
- }
- for (i = 0; i < NENTRIES; i++) {
- t = qr_next(&entries[i], link);
- assert_c_eq(t->id, entries[(i+1) % NENTRIES].id,
- "Element id mismatch");
- }
- for (i = 0; i < NENTRIES; i++) {
- t = qr_prev(&entries[i], link);
- assert_c_eq(t->id, entries[(NENTRIES+i-1) % NENTRIES].id,
- "Element id mismatch");
- }
-}
-
-TEST_BEGIN(test_qr_after_insert)
-{
- ring_t entries[NENTRIES];
- unsigned i;
-
- init_entries(entries);
- for (i = 1; i < NENTRIES; i++)
- qr_after_insert(&entries[i - 1], &entries[i], link);
- test_entries_ring(entries);
-}
-TEST_END
-
-TEST_BEGIN(test_qr_remove)
-{
- ring_t entries[NENTRIES];
- ring_t *t;
- unsigned i, j;
-
- init_entries(entries);
- for (i = 1; i < NENTRIES; i++)
- qr_after_insert(&entries[i - 1], &entries[i], link);
-
- for (i = 0; i < NENTRIES; i++) {
- j = 0;
- qr_foreach(t, &entries[i], link) {
- assert_c_eq(t->id, entries[i+j].id,
- "Element id mismatch");
- j++;
- }
- j = 0;
- qr_reverse_foreach(t, &entries[i], link) {
- assert_c_eq(t->id, entries[NENTRIES - 1 - j].id,
- "Element id mismatch");
- j++;
- }
- qr_remove(&entries[i], link);
- }
- test_independent_entries(entries);
-}
-TEST_END
-
-TEST_BEGIN(test_qr_before_insert)
-{
- ring_t entries[NENTRIES];
- ring_t *t;
- unsigned i, j;
-
- init_entries(entries);
- for (i = 1; i < NENTRIES; i++)
- qr_before_insert(&entries[i - 1], &entries[i], link);
- for (i = 0; i < NENTRIES; i++) {
- j = 0;
- qr_foreach(t, &entries[i], link) {
- assert_c_eq(t->id, entries[(NENTRIES+i-j) %
- NENTRIES].id, "Element id mismatch");
- j++;
- }
- }
- for (i = 0; i < NENTRIES; i++) {
- j = 0;
- qr_reverse_foreach(t, &entries[i], link) {
- assert_c_eq(t->id, entries[(i+j+1) % NENTRIES].id,
- "Element id mismatch");
- j++;
- }
- }
- for (i = 0; i < NENTRIES; i++) {
- t = qr_next(&entries[i], link);
- assert_c_eq(t->id, entries[(NENTRIES+i-1) % NENTRIES].id,
- "Element id mismatch");
- }
- for (i = 0; i < NENTRIES; i++) {
- t = qr_prev(&entries[i], link);
- assert_c_eq(t->id, entries[(i+1) % NENTRIES].id,
- "Element id mismatch");
- }
-}
-TEST_END
-
-static void
-test_split_entries(ring_t *entries)
-{
- ring_t *t;
- unsigned i, j;
-
- for (i = 0; i < NENTRIES; i++) {
- j = 0;
- qr_foreach(t, &entries[i], link) {
- if (i < SPLIT_INDEX) {
- assert_c_eq(t->id,
- entries[(i+j) % SPLIT_INDEX].id,
- "Element id mismatch");
- } else {
- assert_c_eq(t->id, entries[(i+j-SPLIT_INDEX) %
- (NENTRIES-SPLIT_INDEX) + SPLIT_INDEX].id,
- "Element id mismatch");
- }
- j++;
- }
- }
-}
-
-TEST_BEGIN(test_qr_meld_split)
-{
- ring_t entries[NENTRIES];
- unsigned i;
-
- init_entries(entries);
- for (i = 1; i < NENTRIES; i++)
- qr_after_insert(&entries[i - 1], &entries[i], link);
-
- qr_split(&entries[0], &entries[SPLIT_INDEX], link);
- test_split_entries(entries);
-
- qr_meld(&entries[0], &entries[SPLIT_INDEX], link);
- test_entries_ring(entries);
-
- qr_meld(&entries[0], &entries[SPLIT_INDEX], link);
- test_split_entries(entries);
-
- qr_split(&entries[0], &entries[SPLIT_INDEX], link);
- test_entries_ring(entries);
-
- qr_split(&entries[0], &entries[0], link);
- test_entries_ring(entries);
-
- qr_meld(&entries[0], &entries[0], link);
- test_entries_ring(entries);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_qr_one,
- test_qr_after_insert,
- test_qr_remove,
- test_qr_before_insert,
- test_qr_meld_split));
-}
diff --git a/memory/jemalloc/src/test/unit/quarantine.c b/memory/jemalloc/src/test/unit/quarantine.c
deleted file mode 100644
index bbd48a51d..000000000
--- a/memory/jemalloc/src/test/unit/quarantine.c
+++ /dev/null
@@ -1,108 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define QUARANTINE_SIZE 8192
-#define STRINGIFY_HELPER(x) #x
-#define STRINGIFY(x) STRINGIFY_HELPER(x)
-
-#ifdef JEMALLOC_FILL
-const char *malloc_conf = "abort:false,junk:true,redzone:true,quarantine:"
- STRINGIFY(QUARANTINE_SIZE);
-#endif
-
-void
-quarantine_clear(void)
-{
- void *p;
-
- p = mallocx(QUARANTINE_SIZE*2, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- dallocx(p, 0);
-}
-
-TEST_BEGIN(test_quarantine)
-{
-#define SZ ZU(256)
-#define NQUARANTINED (QUARANTINE_SIZE/SZ)
- void *quarantined[NQUARANTINED+1];
- size_t i, j;
-
- test_skip_if(!config_fill);
-
- assert_zu_eq(nallocx(SZ, 0), SZ,
- "SZ=%zu does not precisely equal a size class", SZ);
-
- quarantine_clear();
-
- /*
- * Allocate enough regions to completely fill the quarantine, plus one
- * more. The last iteration occurs with a completely full quarantine,
- * but no regions should be drained from the quarantine until the last
- * deallocation occurs. Therefore no region recycling should occur
- * until after this loop completes.
- */
- for (i = 0; i < NQUARANTINED+1; i++) {
- void *p = mallocx(SZ, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
- quarantined[i] = p;
- dallocx(p, 0);
- for (j = 0; j < i; j++) {
- assert_ptr_ne(p, quarantined[j],
- "Quarantined region recycled too early; "
- "i=%zu, j=%zu", i, j);
- }
- }
-#undef NQUARANTINED
-#undef SZ
-}
-TEST_END
-
-static bool detected_redzone_corruption;
-
-static void
-arena_redzone_corruption_replacement(void *ptr, size_t usize, bool after,
- size_t offset, uint8_t byte)
-{
-
- detected_redzone_corruption = true;
-}
-
-TEST_BEGIN(test_quarantine_redzone)
-{
- char *s;
- arena_redzone_corruption_t *arena_redzone_corruption_orig;
-
- test_skip_if(!config_fill);
-
- arena_redzone_corruption_orig = arena_redzone_corruption;
- arena_redzone_corruption = arena_redzone_corruption_replacement;
-
- /* Test underflow. */
- detected_redzone_corruption = false;
- s = (char *)mallocx(1, 0);
- assert_ptr_not_null((void *)s, "Unexpected mallocx() failure");
- s[-1] = 0xbb;
- dallocx(s, 0);
- assert_true(detected_redzone_corruption,
- "Did not detect redzone corruption");
-
- /* Test overflow. */
- detected_redzone_corruption = false;
- s = (char *)mallocx(1, 0);
- assert_ptr_not_null((void *)s, "Unexpected mallocx() failure");
- s[sallocx(s, 0)] = 0xbb;
- dallocx(s, 0);
- assert_true(detected_redzone_corruption,
- "Did not detect redzone corruption");
-
- arena_redzone_corruption = arena_redzone_corruption_orig;
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_quarantine,
- test_quarantine_redzone));
-}
diff --git a/memory/jemalloc/src/test/unit/rb.c b/memory/jemalloc/src/test/unit/rb.c
deleted file mode 100644
index cf3d3a783..000000000
--- a/memory/jemalloc/src/test/unit/rb.c
+++ /dev/null
@@ -1,354 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define rbtn_black_height(a_type, a_field, a_rbt, r_height) do { \
- a_type *rbp_bh_t; \
- for (rbp_bh_t = (a_rbt)->rbt_root, (r_height) = 0; \
- rbp_bh_t != NULL; \
- rbp_bh_t = rbtn_left_get(a_type, a_field, rbp_bh_t)) { \
- if (!rbtn_red_get(a_type, a_field, rbp_bh_t)) { \
- (r_height)++; \
- } \
- } \
-} while (0)
-
-typedef struct node_s node_t;
-
-struct node_s {
-#define NODE_MAGIC 0x9823af7e
- uint32_t magic;
- rb_node(node_t) link;
- uint64_t key;
-};
-
-static int
-node_cmp(const node_t *a, const node_t *b) {
- int ret;
-
- assert_u32_eq(a->magic, NODE_MAGIC, "Bad magic");
- assert_u32_eq(b->magic, NODE_MAGIC, "Bad magic");
-
- ret = (a->key > b->key) - (a->key < b->key);
- if (ret == 0) {
- /*
- * Duplicates are not allowed in the tree, so force an
- * arbitrary ordering for non-identical items with equal keys.
- */
- ret = (((uintptr_t)a) > ((uintptr_t)b))
- - (((uintptr_t)a) < ((uintptr_t)b));
- }
- return (ret);
-}
-
-typedef rb_tree(node_t) tree_t;
-rb_gen(static, tree_, tree_t, node_t, link, node_cmp);
-
-TEST_BEGIN(test_rb_empty)
-{
- tree_t tree;
- node_t key;
-
- tree_new(&tree);
-
- assert_true(tree_empty(&tree), "Tree should be empty");
- assert_ptr_null(tree_first(&tree), "Unexpected node");
- assert_ptr_null(tree_last(&tree), "Unexpected node");
-
- key.key = 0;
- key.magic = NODE_MAGIC;
- assert_ptr_null(tree_search(&tree, &key), "Unexpected node");
-
- key.key = 0;
- key.magic = NODE_MAGIC;
- assert_ptr_null(tree_nsearch(&tree, &key), "Unexpected node");
-
- key.key = 0;
- key.magic = NODE_MAGIC;
- assert_ptr_null(tree_psearch(&tree, &key), "Unexpected node");
-}
-TEST_END
-
-static unsigned
-tree_recurse(node_t *node, unsigned black_height, unsigned black_depth)
-{
- unsigned ret = 0;
- node_t *left_node;
- node_t *right_node;
-
- if (node == NULL)
- return (ret);
-
- left_node = rbtn_left_get(node_t, link, node);
- right_node = rbtn_right_get(node_t, link, node);
-
- if (!rbtn_red_get(node_t, link, node))
- black_depth++;
-
- /* Red nodes must be interleaved with black nodes. */
- if (rbtn_red_get(node_t, link, node)) {
- if (left_node != NULL)
- assert_false(rbtn_red_get(node_t, link, left_node),
- "Node should be black");
- if (right_node != NULL)
- assert_false(rbtn_red_get(node_t, link, right_node),
- "Node should be black");
- }
-
- /* Self. */
- assert_u32_eq(node->magic, NODE_MAGIC, "Bad magic");
-
- /* Left subtree. */
- if (left_node != NULL)
- ret += tree_recurse(left_node, black_height, black_depth);
- else
- ret += (black_depth != black_height);
-
- /* Right subtree. */
- if (right_node != NULL)
- ret += tree_recurse(right_node, black_height, black_depth);
- else
- ret += (black_depth != black_height);
-
- return (ret);
-}
-
-static node_t *
-tree_iterate_cb(tree_t *tree, node_t *node, void *data)
-{
- unsigned *i = (unsigned *)data;
- node_t *search_node;
-
- assert_u32_eq(node->magic, NODE_MAGIC, "Bad magic");
-
- /* Test rb_search(). */
- search_node = tree_search(tree, node);
- assert_ptr_eq(search_node, node,
- "tree_search() returned unexpected node");
-
- /* Test rb_nsearch(). */
- search_node = tree_nsearch(tree, node);
- assert_ptr_eq(search_node, node,
- "tree_nsearch() returned unexpected node");
-
- /* Test rb_psearch(). */
- search_node = tree_psearch(tree, node);
- assert_ptr_eq(search_node, node,
- "tree_psearch() returned unexpected node");
-
- (*i)++;
-
- return (NULL);
-}
-
-static unsigned
-tree_iterate(tree_t *tree)
-{
- unsigned i;
-
- i = 0;
- tree_iter(tree, NULL, tree_iterate_cb, (void *)&i);
-
- return (i);
-}
-
-static unsigned
-tree_iterate_reverse(tree_t *tree)
-{
- unsigned i;
-
- i = 0;
- tree_reverse_iter(tree, NULL, tree_iterate_cb, (void *)&i);
-
- return (i);
-}
-
-static void
-node_remove(tree_t *tree, node_t *node, unsigned nnodes)
-{
- node_t *search_node;
- unsigned black_height, imbalances;
-
- tree_remove(tree, node);
-
- /* Test rb_nsearch(). */
- search_node = tree_nsearch(tree, node);
- if (search_node != NULL) {
- assert_u64_ge(search_node->key, node->key,
- "Key ordering error");
- }
-
- /* Test rb_psearch(). */
- search_node = tree_psearch(tree, node);
- if (search_node != NULL) {
- assert_u64_le(search_node->key, node->key,
- "Key ordering error");
- }
-
- node->magic = 0;
-
- rbtn_black_height(node_t, link, tree, black_height);
- imbalances = tree_recurse(tree->rbt_root, black_height, 0);
- assert_u_eq(imbalances, 0, "Tree is unbalanced");
- assert_u_eq(tree_iterate(tree), nnodes-1,
- "Unexpected node iteration count");
- assert_u_eq(tree_iterate_reverse(tree), nnodes-1,
- "Unexpected node iteration count");
-}
-
-static node_t *
-remove_iterate_cb(tree_t *tree, node_t *node, void *data)
-{
- unsigned *nnodes = (unsigned *)data;
- node_t *ret = tree_next(tree, node);
-
- node_remove(tree, node, *nnodes);
-
- return (ret);
-}
-
-static node_t *
-remove_reverse_iterate_cb(tree_t *tree, node_t *node, void *data)
-{
- unsigned *nnodes = (unsigned *)data;
- node_t *ret = tree_prev(tree, node);
-
- node_remove(tree, node, *nnodes);
-
- return (ret);
-}
-
-static void
-destroy_cb(node_t *node, void *data)
-{
- unsigned *nnodes = (unsigned *)data;
-
- assert_u_gt(*nnodes, 0, "Destruction removed too many nodes");
- (*nnodes)--;
-}
-
-TEST_BEGIN(test_rb_random)
-{
-#define NNODES 25
-#define NBAGS 250
-#define SEED 42
- sfmt_t *sfmt;
- uint64_t bag[NNODES];
- tree_t tree;
- node_t nodes[NNODES];
- unsigned i, j, k, black_height, imbalances;
-
- sfmt = init_gen_rand(SEED);
- for (i = 0; i < NBAGS; i++) {
- switch (i) {
- case 0:
- /* Insert in order. */
- for (j = 0; j < NNODES; j++)
- bag[j] = j;
- break;
- case 1:
- /* Insert in reverse order. */
- for (j = 0; j < NNODES; j++)
- bag[j] = NNODES - j - 1;
- break;
- default:
- for (j = 0; j < NNODES; j++)
- bag[j] = gen_rand64_range(sfmt, NNODES);
- }
-
- for (j = 1; j <= NNODES; j++) {
- /* Initialize tree and nodes. */
- tree_new(&tree);
- for (k = 0; k < j; k++) {
- nodes[k].magic = NODE_MAGIC;
- nodes[k].key = bag[k];
- }
-
- /* Insert nodes. */
- for (k = 0; k < j; k++) {
- tree_insert(&tree, &nodes[k]);
-
- rbtn_black_height(node_t, link, &tree,
- black_height);
- imbalances = tree_recurse(tree.rbt_root,
- black_height, 0);
- assert_u_eq(imbalances, 0,
- "Tree is unbalanced");
-
- assert_u_eq(tree_iterate(&tree), k+1,
- "Unexpected node iteration count");
- assert_u_eq(tree_iterate_reverse(&tree), k+1,
- "Unexpected node iteration count");
-
- assert_false(tree_empty(&tree),
- "Tree should not be empty");
- assert_ptr_not_null(tree_first(&tree),
- "Tree should not be empty");
- assert_ptr_not_null(tree_last(&tree),
- "Tree should not be empty");
-
- tree_next(&tree, &nodes[k]);
- tree_prev(&tree, &nodes[k]);
- }
-
- /* Remove nodes. */
- switch (i % 5) {
- case 0:
- for (k = 0; k < j; k++)
- node_remove(&tree, &nodes[k], j - k);
- break;
- case 1:
- for (k = j; k > 0; k--)
- node_remove(&tree, &nodes[k-1], k);
- break;
- case 2: {
- node_t *start;
- unsigned nnodes = j;
-
- start = NULL;
- do {
- start = tree_iter(&tree, start,
- remove_iterate_cb, (void *)&nnodes);
- nnodes--;
- } while (start != NULL);
- assert_u_eq(nnodes, 0,
- "Removal terminated early");
- break;
- } case 3: {
- node_t *start;
- unsigned nnodes = j;
-
- start = NULL;
- do {
- start = tree_reverse_iter(&tree, start,
- remove_reverse_iterate_cb,
- (void *)&nnodes);
- nnodes--;
- } while (start != NULL);
- assert_u_eq(nnodes, 0,
- "Removal terminated early");
- break;
- } case 4: {
- unsigned nnodes = j;
- tree_destroy(&tree, destroy_cb, &nnodes);
- assert_u_eq(nnodes, 0,
- "Destruction terminated early");
- break;
- } default:
- not_reached();
- }
- }
- }
- fini_gen_rand(sfmt);
-#undef NNODES
-#undef NBAGS
-#undef SEED
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_rb_empty,
- test_rb_random));
-}
diff --git a/memory/jemalloc/src/test/unit/rtree.c b/memory/jemalloc/src/test/unit/rtree.c
deleted file mode 100644
index b54b3e86f..000000000
--- a/memory/jemalloc/src/test/unit/rtree.c
+++ /dev/null
@@ -1,151 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static rtree_node_elm_t *
-node_alloc(size_t nelms)
-{
-
- return ((rtree_node_elm_t *)calloc(nelms, sizeof(rtree_node_elm_t)));
-}
-
-static void
-node_dalloc(rtree_node_elm_t *node)
-{
-
- free(node);
-}
-
-TEST_BEGIN(test_rtree_get_empty)
-{
- unsigned i;
-
- for (i = 1; i <= (sizeof(uintptr_t) << 3); i++) {
- rtree_t rtree;
- assert_false(rtree_new(&rtree, i, node_alloc, node_dalloc),
- "Unexpected rtree_new() failure");
- assert_ptr_null(rtree_get(&rtree, 0, false),
- "rtree_get() should return NULL for empty tree");
- rtree_delete(&rtree);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_rtree_extrema)
-{
- unsigned i;
- extent_node_t node_a, node_b;
-
- for (i = 1; i <= (sizeof(uintptr_t) << 3); i++) {
- rtree_t rtree;
- assert_false(rtree_new(&rtree, i, node_alloc, node_dalloc),
- "Unexpected rtree_new() failure");
-
- assert_false(rtree_set(&rtree, 0, &node_a),
- "Unexpected rtree_set() failure");
- assert_ptr_eq(rtree_get(&rtree, 0, true), &node_a,
- "rtree_get() should return previously set value");
-
- assert_false(rtree_set(&rtree, ~((uintptr_t)0), &node_b),
- "Unexpected rtree_set() failure");
- assert_ptr_eq(rtree_get(&rtree, ~((uintptr_t)0), true), &node_b,
- "rtree_get() should return previously set value");
-
- rtree_delete(&rtree);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_rtree_bits)
-{
- unsigned i, j, k;
-
- for (i = 1; i < (sizeof(uintptr_t) << 3); i++) {
- uintptr_t keys[] = {0, 1,
- (((uintptr_t)1) << (sizeof(uintptr_t)*8-i)) - 1};
- extent_node_t node;
- rtree_t rtree;
-
- assert_false(rtree_new(&rtree, i, node_alloc, node_dalloc),
- "Unexpected rtree_new() failure");
-
- for (j = 0; j < sizeof(keys)/sizeof(uintptr_t); j++) {
- assert_false(rtree_set(&rtree, keys[j], &node),
- "Unexpected rtree_set() failure");
- for (k = 0; k < sizeof(keys)/sizeof(uintptr_t); k++) {
- assert_ptr_eq(rtree_get(&rtree, keys[k], true),
- &node, "rtree_get() should return "
- "previously set value and ignore "
- "insignificant key bits; i=%u, j=%u, k=%u, "
- "set key=%#"FMTxPTR", get key=%#"FMTxPTR, i,
- j, k, keys[j], keys[k]);
- }
- assert_ptr_null(rtree_get(&rtree,
- (((uintptr_t)1) << (sizeof(uintptr_t)*8-i)), false),
- "Only leftmost rtree leaf should be set; "
- "i=%u, j=%u", i, j);
- assert_false(rtree_set(&rtree, keys[j], NULL),
- "Unexpected rtree_set() failure");
- }
-
- rtree_delete(&rtree);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_rtree_random)
-{
- unsigned i;
- sfmt_t *sfmt;
-#define NSET 16
-#define SEED 42
-
- sfmt = init_gen_rand(SEED);
- for (i = 1; i <= (sizeof(uintptr_t) << 3); i++) {
- uintptr_t keys[NSET];
- extent_node_t node;
- unsigned j;
- rtree_t rtree;
-
- assert_false(rtree_new(&rtree, i, node_alloc, node_dalloc),
- "Unexpected rtree_new() failure");
-
- for (j = 0; j < NSET; j++) {
- keys[j] = (uintptr_t)gen_rand64(sfmt);
- assert_false(rtree_set(&rtree, keys[j], &node),
- "Unexpected rtree_set() failure");
- assert_ptr_eq(rtree_get(&rtree, keys[j], true), &node,
- "rtree_get() should return previously set value");
- }
- for (j = 0; j < NSET; j++) {
- assert_ptr_eq(rtree_get(&rtree, keys[j], true), &node,
- "rtree_get() should return previously set value");
- }
-
- for (j = 0; j < NSET; j++) {
- assert_false(rtree_set(&rtree, keys[j], NULL),
- "Unexpected rtree_set() failure");
- assert_ptr_null(rtree_get(&rtree, keys[j], true),
- "rtree_get() should return previously set value");
- }
- for (j = 0; j < NSET; j++) {
- assert_ptr_null(rtree_get(&rtree, keys[j], true),
- "rtree_get() should return previously set value");
- }
-
- rtree_delete(&rtree);
- }
- fini_gen_rand(sfmt);
-#undef NSET
-#undef SEED
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_rtree_get_empty,
- test_rtree_extrema,
- test_rtree_bits,
- test_rtree_random));
-}
diff --git a/memory/jemalloc/src/test/unit/run_quantize.c b/memory/jemalloc/src/test/unit/run_quantize.c
deleted file mode 100644
index b1ca6356d..000000000
--- a/memory/jemalloc/src/test/unit/run_quantize.c
+++ /dev/null
@@ -1,149 +0,0 @@
-#include "test/jemalloc_test.h"
-
-TEST_BEGIN(test_small_run_size)
-{
- unsigned nbins, i;
- size_t sz, run_size;
- size_t mib[4];
- size_t miblen = sizeof(mib) / sizeof(size_t);
-
- /*
- * Iterate over all small size classes, get their run sizes, and verify
- * that the quantized size is the same as the run size.
- */
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("arenas.nbins", &nbins, &sz, NULL, 0), 0,
- "Unexpected mallctl failure");
-
- assert_d_eq(mallctlnametomib("arenas.bin.0.run_size", mib, &miblen), 0,
- "Unexpected mallctlnametomib failure");
- for (i = 0; i < nbins; i++) {
- mib[2] = i;
- sz = sizeof(size_t);
- assert_d_eq(mallctlbymib(mib, miblen, &run_size, &sz, NULL, 0),
- 0, "Unexpected mallctlbymib failure");
- assert_zu_eq(run_size, run_quantize_floor(run_size),
- "Small run quantization should be a no-op (run_size=%zu)",
- run_size);
- assert_zu_eq(run_size, run_quantize_ceil(run_size),
- "Small run quantization should be a no-op (run_size=%zu)",
- run_size);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_large_run_size)
-{
- bool cache_oblivious;
- unsigned nlruns, i;
- size_t sz, run_size_prev, ceil_prev;
- size_t mib[4];
- size_t miblen = sizeof(mib) / sizeof(size_t);
-
- /*
- * Iterate over all large size classes, get their run sizes, and verify
- * that the quantized size is the same as the run size.
- */
-
- sz = sizeof(bool);
- assert_d_eq(mallctl("config.cache_oblivious", &cache_oblivious, &sz,
- NULL, 0), 0, "Unexpected mallctl failure");
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("arenas.nlruns", &nlruns, &sz, NULL, 0), 0,
- "Unexpected mallctl failure");
-
- assert_d_eq(mallctlnametomib("arenas.lrun.0.size", mib, &miblen), 0,
- "Unexpected mallctlnametomib failure");
- for (i = 0; i < nlruns; i++) {
- size_t lrun_size, run_size, floor, ceil;
-
- mib[2] = i;
- sz = sizeof(size_t);
- assert_d_eq(mallctlbymib(mib, miblen, &lrun_size, &sz, NULL, 0),
- 0, "Unexpected mallctlbymib failure");
- run_size = cache_oblivious ? lrun_size + PAGE : lrun_size;
- floor = run_quantize_floor(run_size);
- ceil = run_quantize_ceil(run_size);
-
- assert_zu_eq(run_size, floor,
- "Large run quantization should be a no-op for precise "
- "size (lrun_size=%zu, run_size=%zu)", lrun_size, run_size);
- assert_zu_eq(run_size, ceil,
- "Large run quantization should be a no-op for precise "
- "size (lrun_size=%zu, run_size=%zu)", lrun_size, run_size);
-
- if (i > 0) {
- assert_zu_eq(run_size_prev, run_quantize_floor(run_size
- - PAGE), "Floor should be a precise size");
- if (run_size_prev < ceil_prev) {
- assert_zu_eq(ceil_prev, run_size,
- "Ceiling should be a precise size "
- "(run_size_prev=%zu, ceil_prev=%zu, "
- "run_size=%zu)", run_size_prev, ceil_prev,
- run_size);
- }
- }
- run_size_prev = floor;
- ceil_prev = run_quantize_ceil(run_size + PAGE);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_monotonic)
-{
- unsigned nbins, nlruns, i;
- size_t sz, floor_prev, ceil_prev;
-
- /*
- * Iterate over all run sizes and verify that
- * run_quantize_{floor,ceil}() are monotonic.
- */
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("arenas.nbins", &nbins, &sz, NULL, 0), 0,
- "Unexpected mallctl failure");
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("arenas.nlruns", &nlruns, &sz, NULL, 0), 0,
- "Unexpected mallctl failure");
-
- floor_prev = 0;
- ceil_prev = 0;
- for (i = 1; i <= chunksize >> LG_PAGE; i++) {
- size_t run_size, floor, ceil;
-
- run_size = i << LG_PAGE;
- floor = run_quantize_floor(run_size);
- ceil = run_quantize_ceil(run_size);
-
- assert_zu_le(floor, run_size,
- "Floor should be <= (floor=%zu, run_size=%zu, ceil=%zu)",
- floor, run_size, ceil);
- assert_zu_ge(ceil, run_size,
- "Ceiling should be >= (floor=%zu, run_size=%zu, ceil=%zu)",
- floor, run_size, ceil);
-
- assert_zu_le(floor_prev, floor, "Floor should be monotonic "
- "(floor_prev=%zu, floor=%zu, run_size=%zu, ceil=%zu)",
- floor_prev, floor, run_size, ceil);
- assert_zu_le(ceil_prev, ceil, "Ceiling should be monotonic "
- "(floor=%zu, run_size=%zu, ceil_prev=%zu, ceil=%zu)",
- floor, run_size, ceil_prev, ceil);
-
- floor_prev = floor;
- ceil_prev = ceil;
- }
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_small_run_size,
- test_large_run_size,
- test_monotonic));
-}
diff --git a/memory/jemalloc/src/test/unit/size_classes.c b/memory/jemalloc/src/test/unit/size_classes.c
deleted file mode 100644
index 4e1e0ce4f..000000000
--- a/memory/jemalloc/src/test/unit/size_classes.c
+++ /dev/null
@@ -1,184 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static size_t
-get_max_size_class(void)
-{
- unsigned nhchunks;
- size_t mib[4];
- size_t sz, miblen, max_size_class;
-
- sz = sizeof(unsigned);
- assert_d_eq(mallctl("arenas.nhchunks", &nhchunks, &sz, NULL, 0), 0,
- "Unexpected mallctl() error");
-
- miblen = sizeof(mib) / sizeof(size_t);
- assert_d_eq(mallctlnametomib("arenas.hchunk.0.size", mib, &miblen), 0,
- "Unexpected mallctlnametomib() error");
- mib[2] = nhchunks - 1;
-
- sz = sizeof(size_t);
- assert_d_eq(mallctlbymib(mib, miblen, &max_size_class, &sz, NULL, 0), 0,
- "Unexpected mallctlbymib() error");
-
- return (max_size_class);
-}
-
-TEST_BEGIN(test_size_classes)
-{
- size_t size_class, max_size_class;
- szind_t index, max_index;
-
- max_size_class = get_max_size_class();
- max_index = size2index(max_size_class);
-
- for (index = 0, size_class = index2size(index); index < max_index ||
- size_class < max_size_class; index++, size_class =
- index2size(index)) {
- assert_true(index < max_index,
- "Loop conditionals should be equivalent; index=%u, "
- "size_class=%zu (%#zx)", index, size_class, size_class);
- assert_true(size_class < max_size_class,
- "Loop conditionals should be equivalent; index=%u, "
- "size_class=%zu (%#zx)", index, size_class, size_class);
-
- assert_u_eq(index, size2index(size_class),
- "size2index() does not reverse index2size(): index=%u -->"
- " size_class=%zu --> index=%u --> size_class=%zu", index,
- size_class, size2index(size_class),
- index2size(size2index(size_class)));
- assert_zu_eq(size_class, index2size(size2index(size_class)),
- "index2size() does not reverse size2index(): index=%u -->"
- " size_class=%zu --> index=%u --> size_class=%zu", index,
- size_class, size2index(size_class),
- index2size(size2index(size_class)));
-
- assert_u_eq(index+1, size2index(size_class+1),
- "Next size_class does not round up properly");
-
- assert_zu_eq(size_class, (index > 0) ?
- s2u(index2size(index-1)+1) : s2u(1),
- "s2u() does not round up to size class");
- assert_zu_eq(size_class, s2u(size_class-1),
- "s2u() does not round up to size class");
- assert_zu_eq(size_class, s2u(size_class),
- "s2u() does not compute same size class");
- assert_zu_eq(s2u(size_class+1), index2size(index+1),
- "s2u() does not round up to next size class");
- }
-
- assert_u_eq(index, size2index(index2size(index)),
- "size2index() does not reverse index2size()");
- assert_zu_eq(max_size_class, index2size(size2index(max_size_class)),
- "index2size() does not reverse size2index()");
-
- assert_zu_eq(size_class, s2u(index2size(index-1)+1),
- "s2u() does not round up to size class");
- assert_zu_eq(size_class, s2u(size_class-1),
- "s2u() does not round up to size class");
- assert_zu_eq(size_class, s2u(size_class),
- "s2u() does not compute same size class");
-}
-TEST_END
-
-TEST_BEGIN(test_psize_classes)
-{
- size_t size_class, max_size_class;
- pszind_t pind, max_pind;
-
- max_size_class = get_max_size_class();
- max_pind = psz2ind(max_size_class);
-
- for (pind = 0, size_class = pind2sz(pind); pind < max_pind ||
- size_class < max_size_class; pind++, size_class =
- pind2sz(pind)) {
- assert_true(pind < max_pind,
- "Loop conditionals should be equivalent; pind=%u, "
- "size_class=%zu (%#zx)", pind, size_class, size_class);
- assert_true(size_class < max_size_class,
- "Loop conditionals should be equivalent; pind=%u, "
- "size_class=%zu (%#zx)", pind, size_class, size_class);
-
- assert_u_eq(pind, psz2ind(size_class),
- "psz2ind() does not reverse pind2sz(): pind=%u -->"
- " size_class=%zu --> pind=%u --> size_class=%zu", pind,
- size_class, psz2ind(size_class),
- pind2sz(psz2ind(size_class)));
- assert_zu_eq(size_class, pind2sz(psz2ind(size_class)),
- "pind2sz() does not reverse psz2ind(): pind=%u -->"
- " size_class=%zu --> pind=%u --> size_class=%zu", pind,
- size_class, psz2ind(size_class),
- pind2sz(psz2ind(size_class)));
-
- assert_u_eq(pind+1, psz2ind(size_class+1),
- "Next size_class does not round up properly");
-
- assert_zu_eq(size_class, (pind > 0) ?
- psz2u(pind2sz(pind-1)+1) : psz2u(1),
- "psz2u() does not round up to size class");
- assert_zu_eq(size_class, psz2u(size_class-1),
- "psz2u() does not round up to size class");
- assert_zu_eq(size_class, psz2u(size_class),
- "psz2u() does not compute same size class");
- assert_zu_eq(psz2u(size_class+1), pind2sz(pind+1),
- "psz2u() does not round up to next size class");
- }
-
- assert_u_eq(pind, psz2ind(pind2sz(pind)),
- "psz2ind() does not reverse pind2sz()");
- assert_zu_eq(max_size_class, pind2sz(psz2ind(max_size_class)),
- "pind2sz() does not reverse psz2ind()");
-
- assert_zu_eq(size_class, psz2u(pind2sz(pind-1)+1),
- "psz2u() does not round up to size class");
- assert_zu_eq(size_class, psz2u(size_class-1),
- "psz2u() does not round up to size class");
- assert_zu_eq(size_class, psz2u(size_class),
- "psz2u() does not compute same size class");
-}
-TEST_END
-
-TEST_BEGIN(test_overflow)
-{
- size_t max_size_class;
-
- max_size_class = get_max_size_class();
-
- assert_u_eq(size2index(max_size_class+1), NSIZES,
- "size2index() should return NSIZES on overflow");
- assert_u_eq(size2index(ZU(PTRDIFF_MAX)+1), NSIZES,
- "size2index() should return NSIZES on overflow");
- assert_u_eq(size2index(SIZE_T_MAX), NSIZES,
- "size2index() should return NSIZES on overflow");
-
- assert_zu_eq(s2u(max_size_class+1), 0,
- "s2u() should return 0 for unsupported size");
- assert_zu_eq(s2u(ZU(PTRDIFF_MAX)+1), 0,
- "s2u() should return 0 for unsupported size");
- assert_zu_eq(s2u(SIZE_T_MAX), 0,
- "s2u() should return 0 on overflow");
-
- assert_u_eq(psz2ind(max_size_class+1), NPSIZES,
- "psz2ind() should return NPSIZES on overflow");
- assert_u_eq(psz2ind(ZU(PTRDIFF_MAX)+1), NPSIZES,
- "psz2ind() should return NPSIZES on overflow");
- assert_u_eq(psz2ind(SIZE_T_MAX), NPSIZES,
- "psz2ind() should return NPSIZES on overflow");
-
- assert_zu_eq(psz2u(max_size_class+1), 0,
- "psz2u() should return 0 for unsupported size");
- assert_zu_eq(psz2u(ZU(PTRDIFF_MAX)+1), 0,
- "psz2u() should return 0 for unsupported size");
- assert_zu_eq(psz2u(SIZE_T_MAX), 0,
- "psz2u() should return 0 on overflow");
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_size_classes,
- test_psize_classes,
- test_overflow));
-}
diff --git a/memory/jemalloc/src/test/unit/smoothstep.c b/memory/jemalloc/src/test/unit/smoothstep.c
deleted file mode 100644
index 4cfb21343..000000000
--- a/memory/jemalloc/src/test/unit/smoothstep.c
+++ /dev/null
@@ -1,106 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static const uint64_t smoothstep_tab[] = {
-#define STEP(step, h, x, y) \
- h,
- SMOOTHSTEP
-#undef STEP
-};
-
-TEST_BEGIN(test_smoothstep_integral)
-{
- uint64_t sum, min, max;
- unsigned i;
-
- /*
- * The integral of smoothstep in the [0..1] range equals 1/2. Verify
- * that the fixed point representation's integral is no more than
- * rounding error distant from 1/2. Regarding rounding, each table
- * element is rounded down to the nearest fixed point value, so the
- * integral may be off by as much as SMOOTHSTEP_NSTEPS ulps.
- */
- sum = 0;
- for (i = 0; i < SMOOTHSTEP_NSTEPS; i++)
- sum += smoothstep_tab[i];
-
- max = (KQU(1) << (SMOOTHSTEP_BFP-1)) * (SMOOTHSTEP_NSTEPS+1);
- min = max - SMOOTHSTEP_NSTEPS;
-
- assert_u64_ge(sum, min,
- "Integral too small, even accounting for truncation");
- assert_u64_le(sum, max, "Integral exceeds 1/2");
- if (false) {
- malloc_printf("%"FMTu64" ulps under 1/2 (limit %d)\n",
- max - sum, SMOOTHSTEP_NSTEPS);
- }
-}
-TEST_END
-
-TEST_BEGIN(test_smoothstep_monotonic)
-{
- uint64_t prev_h;
- unsigned i;
-
- /*
- * The smoothstep function is monotonic in [0..1], i.e. its slope is
- * non-negative. In practice we want to parametrize table generation
- * such that piecewise slope is greater than zero, but do not require
- * that here.
- */
- prev_h = 0;
- for (i = 0; i < SMOOTHSTEP_NSTEPS; i++) {
- uint64_t h = smoothstep_tab[i];
- assert_u64_ge(h, prev_h, "Piecewise non-monotonic, i=%u", i);
- prev_h = h;
- }
- assert_u64_eq(smoothstep_tab[SMOOTHSTEP_NSTEPS-1],
- (KQU(1) << SMOOTHSTEP_BFP), "Last step must equal 1");
-}
-TEST_END
-
-TEST_BEGIN(test_smoothstep_slope)
-{
- uint64_t prev_h, prev_delta;
- unsigned i;
-
- /*
- * The smoothstep slope strictly increases until x=0.5, and then
- * strictly decreases until x=1.0. Verify the slightly weaker
- * requirement of monotonicity, so that inadequate table precision does
- * not cause false test failures.
- */
- prev_h = 0;
- prev_delta = 0;
- for (i = 0; i < SMOOTHSTEP_NSTEPS / 2 + SMOOTHSTEP_NSTEPS % 2; i++) {
- uint64_t h = smoothstep_tab[i];
- uint64_t delta = h - prev_h;
- assert_u64_ge(delta, prev_delta,
- "Slope must monotonically increase in 0.0 <= x <= 0.5, "
- "i=%u", i);
- prev_h = h;
- prev_delta = delta;
- }
-
- prev_h = KQU(1) << SMOOTHSTEP_BFP;
- prev_delta = 0;
- for (i = SMOOTHSTEP_NSTEPS-1; i >= SMOOTHSTEP_NSTEPS / 2; i--) {
- uint64_t h = smoothstep_tab[i];
- uint64_t delta = prev_h - h;
- assert_u64_ge(delta, prev_delta,
- "Slope must monotonically decrease in 0.5 <= x <= 1.0, "
- "i=%u", i);
- prev_h = h;
- prev_delta = delta;
- }
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_smoothstep_integral,
- test_smoothstep_monotonic,
- test_smoothstep_slope));
-}
diff --git a/memory/jemalloc/src/test/unit/stats.c b/memory/jemalloc/src/test/unit/stats.c
deleted file mode 100644
index a9a3981fb..000000000
--- a/memory/jemalloc/src/test/unit/stats.c
+++ /dev/null
@@ -1,447 +0,0 @@
-#include "test/jemalloc_test.h"
-
-TEST_BEGIN(test_stats_summary)
-{
- size_t *cactive;
- size_t sz, allocated, active, resident, mapped;
- int expected = config_stats ? 0 : ENOENT;
-
- sz = sizeof(cactive);
- assert_d_eq(mallctl("stats.cactive", &cactive, &sz, NULL, 0), expected,
- "Unexpected mallctl() result");
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.allocated", &allocated, &sz, NULL, 0),
- expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.active", &active, &sz, NULL, 0), expected,
- "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.resident", &resident, &sz, NULL, 0),
- expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.mapped", &mapped, &sz, NULL, 0), expected,
- "Unexpected mallctl() result");
-
- if (config_stats) {
- assert_zu_le(active, *cactive,
- "active should be no larger than cactive");
- assert_zu_le(allocated, active,
- "allocated should be no larger than active");
- assert_zu_lt(active, resident,
- "active should be less than resident");
- assert_zu_lt(active, mapped,
- "active should be less than mapped");
- }
-}
-TEST_END
-
-TEST_BEGIN(test_stats_huge)
-{
- void *p;
- uint64_t epoch;
- size_t allocated;
- uint64_t nmalloc, ndalloc, nrequests;
- size_t sz;
- int expected = config_stats ? 0 : ENOENT;
-
- p = mallocx(large_maxclass+1, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)), 0,
- "Unexpected mallctl() failure");
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.huge.allocated", &allocated, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.huge.nmalloc", &nmalloc, &sz, NULL,
- 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.huge.ndalloc", &ndalloc, &sz, NULL,
- 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.huge.nrequests", &nrequests, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
-
- if (config_stats) {
- assert_zu_gt(allocated, 0,
- "allocated should be greater than zero");
- assert_u64_ge(nmalloc, ndalloc,
- "nmalloc should be at least as large as ndalloc");
- assert_u64_le(nmalloc, nrequests,
- "nmalloc should no larger than nrequests");
- }
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_stats_arenas_summary)
-{
- unsigned arena;
- void *little, *large, *huge;
- uint64_t epoch;
- size_t sz;
- int expected = config_stats ? 0 : ENOENT;
- size_t mapped;
- uint64_t npurge, nmadvise, purged;
-
- arena = 0;
- assert_d_eq(mallctl("thread.arena", NULL, NULL, &arena, sizeof(arena)),
- 0, "Unexpected mallctl() failure");
-
- little = mallocx(SMALL_MAXCLASS, 0);
- assert_ptr_not_null(little, "Unexpected mallocx() failure");
- large = mallocx(large_maxclass, 0);
- assert_ptr_not_null(large, "Unexpected mallocx() failure");
- huge = mallocx(chunksize, 0);
- assert_ptr_not_null(huge, "Unexpected mallocx() failure");
-
- dallocx(little, 0);
- dallocx(large, 0);
- dallocx(huge, 0);
-
- assert_d_eq(mallctl("arena.0.purge", NULL, NULL, NULL, 0), 0,
- "Unexpected mallctl() failure");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)), 0,
- "Unexpected mallctl() failure");
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.mapped", &mapped, &sz, NULL, 0),
- expected, "Unexepected mallctl() result");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.npurge", &npurge, &sz, NULL, 0),
- expected, "Unexepected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.nmadvise", &nmadvise, &sz, NULL, 0),
- expected, "Unexepected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.purged", &purged, &sz, NULL, 0),
- expected, "Unexepected mallctl() result");
-
- if (config_stats) {
- assert_u64_gt(npurge, 0,
- "At least one purge should have occurred");
- assert_u64_le(nmadvise, purged,
- "nmadvise should be no greater than purged");
- }
-}
-TEST_END
-
-void *
-thd_start(void *arg)
-{
-
- return (NULL);
-}
-
-static void
-no_lazy_lock(void)
-{
- thd_t thd;
-
- thd_create(&thd, thd_start, NULL);
- thd_join(thd, NULL);
-}
-
-TEST_BEGIN(test_stats_arenas_small)
-{
- unsigned arena;
- void *p;
- size_t sz, allocated;
- uint64_t epoch, nmalloc, ndalloc, nrequests;
- int expected = config_stats ? 0 : ENOENT;
-
- no_lazy_lock(); /* Lazy locking would dodge tcache testing. */
-
- arena = 0;
- assert_d_eq(mallctl("thread.arena", NULL, NULL, &arena, sizeof(arena)),
- 0, "Unexpected mallctl() failure");
-
- p = mallocx(SMALL_MAXCLASS, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- assert_d_eq(mallctl("thread.tcache.flush", NULL, NULL, NULL, 0),
- config_tcache ? 0 : ENOENT, "Unexpected mallctl() result");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)), 0,
- "Unexpected mallctl() failure");
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.small.allocated", &allocated, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.small.nmalloc", &nmalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.small.ndalloc", &ndalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.small.nrequests", &nrequests, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
-
- if (config_stats) {
- assert_zu_gt(allocated, 0,
- "allocated should be greater than zero");
- assert_u64_gt(nmalloc, 0,
- "nmalloc should be no greater than zero");
- assert_u64_ge(nmalloc, ndalloc,
- "nmalloc should be at least as large as ndalloc");
- assert_u64_gt(nrequests, 0,
- "nrequests should be greater than zero");
- }
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_stats_arenas_large)
-{
- unsigned arena;
- void *p;
- size_t sz, allocated;
- uint64_t epoch, nmalloc, ndalloc, nrequests;
- int expected = config_stats ? 0 : ENOENT;
-
- arena = 0;
- assert_d_eq(mallctl("thread.arena", NULL, NULL, &arena, sizeof(arena)),
- 0, "Unexpected mallctl() failure");
-
- p = mallocx(large_maxclass, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)), 0,
- "Unexpected mallctl() failure");
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.large.allocated", &allocated, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.large.nmalloc", &nmalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.large.ndalloc", &ndalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.large.nrequests", &nrequests, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
-
- if (config_stats) {
- assert_zu_gt(allocated, 0,
- "allocated should be greater than zero");
- assert_u64_gt(nmalloc, 0,
- "nmalloc should be greater than zero");
- assert_u64_ge(nmalloc, ndalloc,
- "nmalloc should be at least as large as ndalloc");
- assert_u64_gt(nrequests, 0,
- "nrequests should be greater than zero");
- }
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_stats_arenas_huge)
-{
- unsigned arena;
- void *p;
- size_t sz, allocated;
- uint64_t epoch, nmalloc, ndalloc;
- int expected = config_stats ? 0 : ENOENT;
-
- arena = 0;
- assert_d_eq(mallctl("thread.arena", NULL, NULL, &arena, sizeof(arena)),
- 0, "Unexpected mallctl() failure");
-
- p = mallocx(chunksize, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)), 0,
- "Unexpected mallctl() failure");
-
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.huge.allocated", &allocated, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.huge.nmalloc", &nmalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.huge.ndalloc", &ndalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
-
- if (config_stats) {
- assert_zu_gt(allocated, 0,
- "allocated should be greater than zero");
- assert_u64_gt(nmalloc, 0,
- "nmalloc should be greater than zero");
- assert_u64_ge(nmalloc, ndalloc,
- "nmalloc should be at least as large as ndalloc");
- }
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_stats_arenas_bins)
-{
- unsigned arena;
- void *p;
- size_t sz, curruns, curregs;
- uint64_t epoch, nmalloc, ndalloc, nrequests, nfills, nflushes;
- uint64_t nruns, nreruns;
- int expected = config_stats ? 0 : ENOENT;
-
- arena = 0;
- assert_d_eq(mallctl("thread.arena", NULL, NULL, &arena, sizeof(arena)),
- 0, "Unexpected mallctl() failure");
-
- p = mallocx(arena_bin_info[0].reg_size, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- assert_d_eq(mallctl("thread.tcache.flush", NULL, NULL, NULL, 0),
- config_tcache ? 0 : ENOENT, "Unexpected mallctl() result");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)), 0,
- "Unexpected mallctl() failure");
-
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.bins.0.nmalloc", &nmalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.bins.0.ndalloc", &ndalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.bins.0.nrequests", &nrequests, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.bins.0.curregs", &curregs, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
-
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.bins.0.nfills", &nfills, &sz,
- NULL, 0), config_tcache ? expected : ENOENT,
- "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.bins.0.nflushes", &nflushes, &sz,
- NULL, 0), config_tcache ? expected : ENOENT,
- "Unexpected mallctl() result");
-
- assert_d_eq(mallctl("stats.arenas.0.bins.0.nruns", &nruns, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.bins.0.nreruns", &nreruns, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.bins.0.curruns", &curruns, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
-
- if (config_stats) {
- assert_u64_gt(nmalloc, 0,
- "nmalloc should be greater than zero");
- assert_u64_ge(nmalloc, ndalloc,
- "nmalloc should be at least as large as ndalloc");
- assert_u64_gt(nrequests, 0,
- "nrequests should be greater than zero");
- assert_zu_gt(curregs, 0,
- "allocated should be greater than zero");
- if (config_tcache) {
- assert_u64_gt(nfills, 0,
- "At least one fill should have occurred");
- assert_u64_gt(nflushes, 0,
- "At least one flush should have occurred");
- }
- assert_u64_gt(nruns, 0,
- "At least one run should have been allocated");
- assert_zu_gt(curruns, 0,
- "At least one run should be currently allocated");
- }
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_stats_arenas_lruns)
-{
- unsigned arena;
- void *p;
- uint64_t epoch, nmalloc, ndalloc, nrequests;
- size_t curruns, sz;
- int expected = config_stats ? 0 : ENOENT;
-
- arena = 0;
- assert_d_eq(mallctl("thread.arena", NULL, NULL, &arena, sizeof(arena)),
- 0, "Unexpected mallctl() failure");
-
- p = mallocx(LARGE_MINCLASS, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)), 0,
- "Unexpected mallctl() failure");
-
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.lruns.0.nmalloc", &nmalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.lruns.0.ndalloc", &ndalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.lruns.0.nrequests", &nrequests, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.lruns.0.curruns", &curruns, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
-
- if (config_stats) {
- assert_u64_gt(nmalloc, 0,
- "nmalloc should be greater than zero");
- assert_u64_ge(nmalloc, ndalloc,
- "nmalloc should be at least as large as ndalloc");
- assert_u64_gt(nrequests, 0,
- "nrequests should be greater than zero");
- assert_u64_gt(curruns, 0,
- "At least one run should be currently allocated");
- }
-
- dallocx(p, 0);
-}
-TEST_END
-
-TEST_BEGIN(test_stats_arenas_hchunks)
-{
- unsigned arena;
- void *p;
- uint64_t epoch, nmalloc, ndalloc;
- size_t curhchunks, sz;
- int expected = config_stats ? 0 : ENOENT;
-
- arena = 0;
- assert_d_eq(mallctl("thread.arena", NULL, NULL, &arena, sizeof(arena)),
- 0, "Unexpected mallctl() failure");
-
- p = mallocx(chunksize, 0);
- assert_ptr_not_null(p, "Unexpected mallocx() failure");
-
- assert_d_eq(mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)), 0,
- "Unexpected mallctl() failure");
-
- sz = sizeof(uint64_t);
- assert_d_eq(mallctl("stats.arenas.0.hchunks.0.nmalloc", &nmalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- assert_d_eq(mallctl("stats.arenas.0.hchunks.0.ndalloc", &ndalloc, &sz,
- NULL, 0), expected, "Unexpected mallctl() result");
- sz = sizeof(size_t);
- assert_d_eq(mallctl("stats.arenas.0.hchunks.0.curhchunks", &curhchunks,
- &sz, NULL, 0), expected, "Unexpected mallctl() result");
-
- if (config_stats) {
- assert_u64_gt(nmalloc, 0,
- "nmalloc should be greater than zero");
- assert_u64_ge(nmalloc, ndalloc,
- "nmalloc should be at least as large as ndalloc");
- assert_u64_gt(curhchunks, 0,
- "At least one chunk should be currently allocated");
- }
-
- dallocx(p, 0);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_stats_summary,
- test_stats_huge,
- test_stats_arenas_summary,
- test_stats_arenas_small,
- test_stats_arenas_large,
- test_stats_arenas_huge,
- test_stats_arenas_bins,
- test_stats_arenas_lruns,
- test_stats_arenas_hchunks));
-}
diff --git a/memory/jemalloc/src/test/unit/ticker.c b/memory/jemalloc/src/test/unit/ticker.c
deleted file mode 100644
index e737020ab..000000000
--- a/memory/jemalloc/src/test/unit/ticker.c
+++ /dev/null
@@ -1,76 +0,0 @@
-#include "test/jemalloc_test.h"
-
-TEST_BEGIN(test_ticker_tick)
-{
-#define NREPS 2
-#define NTICKS 3
- ticker_t ticker;
- int32_t i, j;
-
- ticker_init(&ticker, NTICKS);
- for (i = 0; i < NREPS; i++) {
- for (j = 0; j < NTICKS; j++) {
- assert_u_eq(ticker_read(&ticker), NTICKS - j,
- "Unexpected ticker value (i=%d, j=%d)", i, j);
- assert_false(ticker_tick(&ticker),
- "Unexpected ticker fire (i=%d, j=%d)", i, j);
- }
- assert_u32_eq(ticker_read(&ticker), 0,
- "Expected ticker depletion");
- assert_true(ticker_tick(&ticker),
- "Expected ticker fire (i=%d)", i);
- assert_u32_eq(ticker_read(&ticker), NTICKS,
- "Expected ticker reset");
- }
-#undef NTICKS
-}
-TEST_END
-
-TEST_BEGIN(test_ticker_ticks)
-{
-#define NTICKS 3
- ticker_t ticker;
-
- ticker_init(&ticker, NTICKS);
-
- assert_u_eq(ticker_read(&ticker), NTICKS, "Unexpected ticker value");
- assert_false(ticker_ticks(&ticker, NTICKS), "Unexpected ticker fire");
- assert_u_eq(ticker_read(&ticker), 0, "Unexpected ticker value");
- assert_true(ticker_ticks(&ticker, NTICKS), "Expected ticker fire");
- assert_u_eq(ticker_read(&ticker), NTICKS, "Unexpected ticker value");
-
- assert_true(ticker_ticks(&ticker, NTICKS + 1), "Expected ticker fire");
- assert_u_eq(ticker_read(&ticker), NTICKS, "Unexpected ticker value");
-#undef NTICKS
-}
-TEST_END
-
-TEST_BEGIN(test_ticker_copy)
-{
-#define NTICKS 3
- ticker_t ta, tb;
-
- ticker_init(&ta, NTICKS);
- ticker_copy(&tb, &ta);
- assert_u_eq(ticker_read(&tb), NTICKS, "Unexpected ticker value");
- assert_true(ticker_ticks(&tb, NTICKS + 1), "Expected ticker fire");
- assert_u_eq(ticker_read(&tb), NTICKS, "Unexpected ticker value");
-
- ticker_tick(&ta);
- ticker_copy(&tb, &ta);
- assert_u_eq(ticker_read(&tb), NTICKS - 1, "Unexpected ticker value");
- assert_true(ticker_ticks(&tb, NTICKS), "Expected ticker fire");
- assert_u_eq(ticker_read(&tb), NTICKS, "Unexpected ticker value");
-#undef NTICKS
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_ticker_tick,
- test_ticker_ticks,
- test_ticker_copy));
-}
diff --git a/memory/jemalloc/src/test/unit/tsd.c b/memory/jemalloc/src/test/unit/tsd.c
deleted file mode 100644
index 4e2622a34..000000000
--- a/memory/jemalloc/src/test/unit/tsd.c
+++ /dev/null
@@ -1,112 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define THREAD_DATA 0x72b65c10
-
-typedef unsigned int data_t;
-
-static bool data_cleanup_executed;
-
-malloc_tsd_types(data_, data_t)
-malloc_tsd_protos(, data_, data_t)
-
-void
-data_cleanup(void *arg)
-{
- data_t *data = (data_t *)arg;
-
- if (!data_cleanup_executed) {
- assert_x_eq(*data, THREAD_DATA,
- "Argument passed into cleanup function should match tsd "
- "value");
- }
- data_cleanup_executed = true;
-
- /*
- * Allocate during cleanup for two rounds, in order to assure that
- * jemalloc's internal tsd reinitialization happens.
- */
- switch (*data) {
- case THREAD_DATA:
- *data = 1;
- data_tsd_set(data);
- break;
- case 1:
- *data = 2;
- data_tsd_set(data);
- break;
- case 2:
- return;
- default:
- not_reached();
- }
-
- {
- void *p = mallocx(1, 0);
- assert_ptr_not_null(p, "Unexpeced mallocx() failure");
- dallocx(p, 0);
- }
-}
-
-malloc_tsd_externs(data_, data_t)
-#define DATA_INIT 0x12345678
-malloc_tsd_data(, data_, data_t, DATA_INIT)
-malloc_tsd_funcs(, data_, data_t, DATA_INIT, data_cleanup)
-
-static void *
-thd_start(void *arg)
-{
- data_t d = (data_t)(uintptr_t)arg;
- void *p;
-
- assert_x_eq(*data_tsd_get(true), DATA_INIT,
- "Initial tsd get should return initialization value");
-
- p = malloc(1);
- assert_ptr_not_null(p, "Unexpected malloc() failure");
-
- data_tsd_set(&d);
- assert_x_eq(*data_tsd_get(true), d,
- "After tsd set, tsd get should return value that was set");
-
- d = 0;
- assert_x_eq(*data_tsd_get(true), (data_t)(uintptr_t)arg,
- "Resetting local data should have no effect on tsd");
-
- free(p);
- return (NULL);
-}
-
-TEST_BEGIN(test_tsd_main_thread)
-{
-
- thd_start((void *) 0xa5f3e329);
-}
-TEST_END
-
-TEST_BEGIN(test_tsd_sub_thread)
-{
- thd_t thd;
-
- data_cleanup_executed = false;
- thd_create(&thd, thd_start, (void *)THREAD_DATA);
- thd_join(thd, NULL);
- assert_true(data_cleanup_executed,
- "Cleanup function should have executed");
-}
-TEST_END
-
-int
-main(void)
-{
-
- /* Core tsd bootstrapping must happen prior to data_tsd_boot(). */
- if (nallocx(1, 0) == 0) {
- malloc_printf("Initialization error");
- return (test_status_fail);
- }
- data_tsd_boot();
-
- return (test(
- test_tsd_main_thread,
- test_tsd_sub_thread));
-}
diff --git a/memory/jemalloc/src/test/unit/util.c b/memory/jemalloc/src/test/unit/util.c
deleted file mode 100644
index c958dc0fb..000000000
--- a/memory/jemalloc/src/test/unit/util.c
+++ /dev/null
@@ -1,317 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#define TEST_POW2_CEIL(t, suf, pri) do { \
- unsigned i, pow2; \
- t x; \
- \
- assert_##suf##_eq(pow2_ceil_##suf(0), 0, "Unexpected result"); \
- \
- for (i = 0; i < sizeof(t) * 8; i++) { \
- assert_##suf##_eq(pow2_ceil_##suf(((t)1) << i), ((t)1) \
- << i, "Unexpected result"); \
- } \
- \
- for (i = 2; i < sizeof(t) * 8; i++) { \
- assert_##suf##_eq(pow2_ceil_##suf((((t)1) << i) - 1), \
- ((t)1) << i, "Unexpected result"); \
- } \
- \
- for (i = 0; i < sizeof(t) * 8 - 1; i++) { \
- assert_##suf##_eq(pow2_ceil_##suf((((t)1) << i) + 1), \
- ((t)1) << (i+1), "Unexpected result"); \
- } \
- \
- for (pow2 = 1; pow2 < 25; pow2++) { \
- for (x = (((t)1) << (pow2-1)) + 1; x <= ((t)1) << pow2; \
- x++) { \
- assert_##suf##_eq(pow2_ceil_##suf(x), \
- ((t)1) << pow2, \
- "Unexpected result, x=%"pri, x); \
- } \
- } \
-} while (0)
-
-TEST_BEGIN(test_pow2_ceil_u64)
-{
-
- TEST_POW2_CEIL(uint64_t, u64, FMTu64);
-}
-TEST_END
-
-TEST_BEGIN(test_pow2_ceil_u32)
-{
-
- TEST_POW2_CEIL(uint32_t, u32, FMTu32);
-}
-TEST_END
-
-TEST_BEGIN(test_pow2_ceil_zu)
-{
-
- TEST_POW2_CEIL(size_t, zu, "zu");
-}
-TEST_END
-
-TEST_BEGIN(test_malloc_strtoumax_no_endptr)
-{
- int err;
-
- set_errno(0);
- assert_ju_eq(malloc_strtoumax("0", NULL, 0), 0, "Unexpected result");
- err = get_errno();
- assert_d_eq(err, 0, "Unexpected failure");
-}
-TEST_END
-
-TEST_BEGIN(test_malloc_strtoumax)
-{
- struct test_s {
- const char *input;
- const char *expected_remainder;
- int base;
- int expected_errno;
- const char *expected_errno_name;
- uintmax_t expected_x;
- };
-#define ERR(e) e, #e
-#define KUMAX(x) ((uintmax_t)x##ULL)
- struct test_s tests[] = {
- {"0", "0", -1, ERR(EINVAL), UINTMAX_MAX},
- {"0", "0", 1, ERR(EINVAL), UINTMAX_MAX},
- {"0", "0", 37, ERR(EINVAL), UINTMAX_MAX},
-
- {"", "", 0, ERR(EINVAL), UINTMAX_MAX},
- {"+", "+", 0, ERR(EINVAL), UINTMAX_MAX},
- {"++3", "++3", 0, ERR(EINVAL), UINTMAX_MAX},
- {"-", "-", 0, ERR(EINVAL), UINTMAX_MAX},
-
- {"42", "", 0, ERR(0), KUMAX(42)},
- {"+42", "", 0, ERR(0), KUMAX(42)},
- {"-42", "", 0, ERR(0), KUMAX(-42)},
- {"042", "", 0, ERR(0), KUMAX(042)},
- {"+042", "", 0, ERR(0), KUMAX(042)},
- {"-042", "", 0, ERR(0), KUMAX(-042)},
- {"0x42", "", 0, ERR(0), KUMAX(0x42)},
- {"+0x42", "", 0, ERR(0), KUMAX(0x42)},
- {"-0x42", "", 0, ERR(0), KUMAX(-0x42)},
-
- {"0", "", 0, ERR(0), KUMAX(0)},
- {"1", "", 0, ERR(0), KUMAX(1)},
-
- {"42", "", 0, ERR(0), KUMAX(42)},
- {" 42", "", 0, ERR(0), KUMAX(42)},
- {"42 ", " ", 0, ERR(0), KUMAX(42)},
- {"0x", "x", 0, ERR(0), KUMAX(0)},
- {"42x", "x", 0, ERR(0), KUMAX(42)},
-
- {"07", "", 0, ERR(0), KUMAX(7)},
- {"010", "", 0, ERR(0), KUMAX(8)},
- {"08", "8", 0, ERR(0), KUMAX(0)},
- {"0_", "_", 0, ERR(0), KUMAX(0)},
-
- {"0x", "x", 0, ERR(0), KUMAX(0)},
- {"0X", "X", 0, ERR(0), KUMAX(0)},
- {"0xg", "xg", 0, ERR(0), KUMAX(0)},
- {"0XA", "", 0, ERR(0), KUMAX(10)},
-
- {"010", "", 10, ERR(0), KUMAX(10)},
- {"0x3", "x3", 10, ERR(0), KUMAX(0)},
-
- {"12", "2", 2, ERR(0), KUMAX(1)},
- {"78", "8", 8, ERR(0), KUMAX(7)},
- {"9a", "a", 10, ERR(0), KUMAX(9)},
- {"9A", "A", 10, ERR(0), KUMAX(9)},
- {"fg", "g", 16, ERR(0), KUMAX(15)},
- {"FG", "G", 16, ERR(0), KUMAX(15)},
- {"0xfg", "g", 16, ERR(0), KUMAX(15)},
- {"0XFG", "G", 16, ERR(0), KUMAX(15)},
- {"z_", "_", 36, ERR(0), KUMAX(35)},
- {"Z_", "_", 36, ERR(0), KUMAX(35)}
- };
-#undef ERR
-#undef KUMAX
- unsigned i;
-
- for (i = 0; i < sizeof(tests)/sizeof(struct test_s); i++) {
- struct test_s *test = &tests[i];
- int err;
- uintmax_t result;
- char *remainder;
-
- set_errno(0);
- result = malloc_strtoumax(test->input, &remainder, test->base);
- err = get_errno();
- assert_d_eq(err, test->expected_errno,
- "Expected errno %s for \"%s\", base %d",
- test->expected_errno_name, test->input, test->base);
- assert_str_eq(remainder, test->expected_remainder,
- "Unexpected remainder for \"%s\", base %d",
- test->input, test->base);
- if (err == 0) {
- assert_ju_eq(result, test->expected_x,
- "Unexpected result for \"%s\", base %d",
- test->input, test->base);
- }
- }
-}
-TEST_END
-
-TEST_BEGIN(test_malloc_snprintf_truncated)
-{
-#define BUFLEN 15
- char buf[BUFLEN];
- size_t result;
- size_t len;
-#define TEST(expected_str_untruncated, ...) do { \
- result = malloc_snprintf(buf, len, __VA_ARGS__); \
- assert_d_eq(strncmp(buf, expected_str_untruncated, len-1), 0, \
- "Unexpected string inequality (\"%s\" vs \"%s\")", \
- buf, expected_str_untruncated); \
- assert_zu_eq(result, strlen(expected_str_untruncated), \
- "Unexpected result"); \
-} while (0)
-
- for (len = 1; len < BUFLEN; len++) {
- TEST("012346789", "012346789");
- TEST("a0123b", "a%sb", "0123");
- TEST("a01234567", "a%s%s", "0123", "4567");
- TEST("a0123 ", "a%-6s", "0123");
- TEST("a 0123", "a%6s", "0123");
- TEST("a 012", "a%6.3s", "0123");
- TEST("a 012", "a%*.*s", 6, 3, "0123");
- TEST("a 123b", "a% db", 123);
- TEST("a123b", "a%-db", 123);
- TEST("a-123b", "a%-db", -123);
- TEST("a+123b", "a%+db", 123);
- }
-#undef BUFLEN
-#undef TEST
-}
-TEST_END
-
-TEST_BEGIN(test_malloc_snprintf)
-{
-#define BUFLEN 128
- char buf[BUFLEN];
- size_t result;
-#define TEST(expected_str, ...) do { \
- result = malloc_snprintf(buf, sizeof(buf), __VA_ARGS__); \
- assert_str_eq(buf, expected_str, "Unexpected output"); \
- assert_zu_eq(result, strlen(expected_str), "Unexpected result");\
-} while (0)
-
- TEST("hello", "hello");
-
- TEST("50%, 100%", "50%%, %d%%", 100);
-
- TEST("a0123b", "a%sb", "0123");
-
- TEST("a 0123b", "a%5sb", "0123");
- TEST("a 0123b", "a%*sb", 5, "0123");
-
- TEST("a0123 b", "a%-5sb", "0123");
- TEST("a0123b", "a%*sb", -1, "0123");
- TEST("a0123 b", "a%*sb", -5, "0123");
- TEST("a0123 b", "a%-*sb", -5, "0123");
-
- TEST("a012b", "a%.3sb", "0123");
- TEST("a012b", "a%.*sb", 3, "0123");
- TEST("a0123b", "a%.*sb", -3, "0123");
-
- TEST("a 012b", "a%5.3sb", "0123");
- TEST("a 012b", "a%5.*sb", 3, "0123");
- TEST("a 012b", "a%*.3sb", 5, "0123");
- TEST("a 012b", "a%*.*sb", 5, 3, "0123");
- TEST("a 0123b", "a%*.*sb", 5, -3, "0123");
-
- TEST("_abcd_", "_%x_", 0xabcd);
- TEST("_0xabcd_", "_%#x_", 0xabcd);
- TEST("_1234_", "_%o_", 01234);
- TEST("_01234_", "_%#o_", 01234);
- TEST("_1234_", "_%u_", 1234);
-
- TEST("_1234_", "_%d_", 1234);
- TEST("_ 1234_", "_% d_", 1234);
- TEST("_+1234_", "_%+d_", 1234);
- TEST("_-1234_", "_%d_", -1234);
- TEST("_-1234_", "_% d_", -1234);
- TEST("_-1234_", "_%+d_", -1234);
-
- TEST("_-1234_", "_%d_", -1234);
- TEST("_1234_", "_%d_", 1234);
- TEST("_-1234_", "_%i_", -1234);
- TEST("_1234_", "_%i_", 1234);
- TEST("_01234_", "_%#o_", 01234);
- TEST("_1234_", "_%u_", 1234);
- TEST("_0x1234abc_", "_%#x_", 0x1234abc);
- TEST("_0X1234ABC_", "_%#X_", 0x1234abc);
- TEST("_c_", "_%c_", 'c');
- TEST("_string_", "_%s_", "string");
- TEST("_0x42_", "_%p_", ((void *)0x42));
-
- TEST("_-1234_", "_%ld_", ((long)-1234));
- TEST("_1234_", "_%ld_", ((long)1234));
- TEST("_-1234_", "_%li_", ((long)-1234));
- TEST("_1234_", "_%li_", ((long)1234));
- TEST("_01234_", "_%#lo_", ((long)01234));
- TEST("_1234_", "_%lu_", ((long)1234));
- TEST("_0x1234abc_", "_%#lx_", ((long)0x1234abc));
- TEST("_0X1234ABC_", "_%#lX_", ((long)0x1234ABC));
-
- TEST("_-1234_", "_%lld_", ((long long)-1234));
- TEST("_1234_", "_%lld_", ((long long)1234));
- TEST("_-1234_", "_%lli_", ((long long)-1234));
- TEST("_1234_", "_%lli_", ((long long)1234));
- TEST("_01234_", "_%#llo_", ((long long)01234));
- TEST("_1234_", "_%llu_", ((long long)1234));
- TEST("_0x1234abc_", "_%#llx_", ((long long)0x1234abc));
- TEST("_0X1234ABC_", "_%#llX_", ((long long)0x1234ABC));
-
- TEST("_-1234_", "_%qd_", ((long long)-1234));
- TEST("_1234_", "_%qd_", ((long long)1234));
- TEST("_-1234_", "_%qi_", ((long long)-1234));
- TEST("_1234_", "_%qi_", ((long long)1234));
- TEST("_01234_", "_%#qo_", ((long long)01234));
- TEST("_1234_", "_%qu_", ((long long)1234));
- TEST("_0x1234abc_", "_%#qx_", ((long long)0x1234abc));
- TEST("_0X1234ABC_", "_%#qX_", ((long long)0x1234ABC));
-
- TEST("_-1234_", "_%jd_", ((intmax_t)-1234));
- TEST("_1234_", "_%jd_", ((intmax_t)1234));
- TEST("_-1234_", "_%ji_", ((intmax_t)-1234));
- TEST("_1234_", "_%ji_", ((intmax_t)1234));
- TEST("_01234_", "_%#jo_", ((intmax_t)01234));
- TEST("_1234_", "_%ju_", ((intmax_t)1234));
- TEST("_0x1234abc_", "_%#jx_", ((intmax_t)0x1234abc));
- TEST("_0X1234ABC_", "_%#jX_", ((intmax_t)0x1234ABC));
-
- TEST("_1234_", "_%td_", ((ptrdiff_t)1234));
- TEST("_-1234_", "_%td_", ((ptrdiff_t)-1234));
- TEST("_1234_", "_%ti_", ((ptrdiff_t)1234));
- TEST("_-1234_", "_%ti_", ((ptrdiff_t)-1234));
-
- TEST("_-1234_", "_%zd_", ((ssize_t)-1234));
- TEST("_1234_", "_%zd_", ((ssize_t)1234));
- TEST("_-1234_", "_%zi_", ((ssize_t)-1234));
- TEST("_1234_", "_%zi_", ((ssize_t)1234));
- TEST("_01234_", "_%#zo_", ((ssize_t)01234));
- TEST("_1234_", "_%zu_", ((ssize_t)1234));
- TEST("_0x1234abc_", "_%#zx_", ((ssize_t)0x1234abc));
- TEST("_0X1234ABC_", "_%#zX_", ((ssize_t)0x1234ABC));
-#undef BUFLEN
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_pow2_ceil_u64,
- test_pow2_ceil_u32,
- test_pow2_ceil_zu,
- test_malloc_strtoumax_no_endptr,
- test_malloc_strtoumax,
- test_malloc_snprintf_truncated,
- test_malloc_snprintf));
-}
diff --git a/memory/jemalloc/src/test/unit/witness.c b/memory/jemalloc/src/test/unit/witness.c
deleted file mode 100644
index ed172753c..000000000
--- a/memory/jemalloc/src/test/unit/witness.c
+++ /dev/null
@@ -1,278 +0,0 @@
-#include "test/jemalloc_test.h"
-
-static witness_lock_error_t *witness_lock_error_orig;
-static witness_owner_error_t *witness_owner_error_orig;
-static witness_not_owner_error_t *witness_not_owner_error_orig;
-static witness_lockless_error_t *witness_lockless_error_orig;
-
-static bool saw_lock_error;
-static bool saw_owner_error;
-static bool saw_not_owner_error;
-static bool saw_lockless_error;
-
-static void
-witness_lock_error_intercept(const witness_list_t *witnesses,
- const witness_t *witness)
-{
-
- saw_lock_error = true;
-}
-
-static void
-witness_owner_error_intercept(const witness_t *witness)
-{
-
- saw_owner_error = true;
-}
-
-static void
-witness_not_owner_error_intercept(const witness_t *witness)
-{
-
- saw_not_owner_error = true;
-}
-
-static void
-witness_lockless_error_intercept(const witness_list_t *witnesses)
-{
-
- saw_lockless_error = true;
-}
-
-static int
-witness_comp(const witness_t *a, const witness_t *b)
-{
-
- assert_u_eq(a->rank, b->rank, "Witnesses should have equal rank");
-
- return (strcmp(a->name, b->name));
-}
-
-static int
-witness_comp_reverse(const witness_t *a, const witness_t *b)
-{
-
- assert_u_eq(a->rank, b->rank, "Witnesses should have equal rank");
-
- return (-strcmp(a->name, b->name));
-}
-
-TEST_BEGIN(test_witness)
-{
- witness_t a, b;
- tsdn_t *tsdn;
-
- test_skip_if(!config_debug);
-
- tsdn = tsdn_fetch();
-
- witness_assert_lockless(tsdn);
-
- witness_init(&a, "a", 1, NULL);
- witness_assert_not_owner(tsdn, &a);
- witness_lock(tsdn, &a);
- witness_assert_owner(tsdn, &a);
-
- witness_init(&b, "b", 2, NULL);
- witness_assert_not_owner(tsdn, &b);
- witness_lock(tsdn, &b);
- witness_assert_owner(tsdn, &b);
-
- witness_unlock(tsdn, &a);
- witness_unlock(tsdn, &b);
-
- witness_assert_lockless(tsdn);
-}
-TEST_END
-
-TEST_BEGIN(test_witness_comp)
-{
- witness_t a, b, c, d;
- tsdn_t *tsdn;
-
- test_skip_if(!config_debug);
-
- tsdn = tsdn_fetch();
-
- witness_assert_lockless(tsdn);
-
- witness_init(&a, "a", 1, witness_comp);
- witness_assert_not_owner(tsdn, &a);
- witness_lock(tsdn, &a);
- witness_assert_owner(tsdn, &a);
-
- witness_init(&b, "b", 1, witness_comp);
- witness_assert_not_owner(tsdn, &b);
- witness_lock(tsdn, &b);
- witness_assert_owner(tsdn, &b);
- witness_unlock(tsdn, &b);
-
- witness_lock_error_orig = witness_lock_error;
- witness_lock_error = witness_lock_error_intercept;
- saw_lock_error = false;
-
- witness_init(&c, "c", 1, witness_comp_reverse);
- witness_assert_not_owner(tsdn, &c);
- assert_false(saw_lock_error, "Unexpected witness lock error");
- witness_lock(tsdn, &c);
- assert_true(saw_lock_error, "Expected witness lock error");
- witness_unlock(tsdn, &c);
-
- saw_lock_error = false;
-
- witness_init(&d, "d", 1, NULL);
- witness_assert_not_owner(tsdn, &d);
- assert_false(saw_lock_error, "Unexpected witness lock error");
- witness_lock(tsdn, &d);
- assert_true(saw_lock_error, "Expected witness lock error");
- witness_unlock(tsdn, &d);
-
- witness_unlock(tsdn, &a);
-
- witness_assert_lockless(tsdn);
-
- witness_lock_error = witness_lock_error_orig;
-}
-TEST_END
-
-TEST_BEGIN(test_witness_reversal)
-{
- witness_t a, b;
- tsdn_t *tsdn;
-
- test_skip_if(!config_debug);
-
- witness_lock_error_orig = witness_lock_error;
- witness_lock_error = witness_lock_error_intercept;
- saw_lock_error = false;
-
- tsdn = tsdn_fetch();
-
- witness_assert_lockless(tsdn);
-
- witness_init(&a, "a", 1, NULL);
- witness_init(&b, "b", 2, NULL);
-
- witness_lock(tsdn, &b);
- assert_false(saw_lock_error, "Unexpected witness lock error");
- witness_lock(tsdn, &a);
- assert_true(saw_lock_error, "Expected witness lock error");
-
- witness_unlock(tsdn, &a);
- witness_unlock(tsdn, &b);
-
- witness_assert_lockless(tsdn);
-
- witness_lock_error = witness_lock_error_orig;
-}
-TEST_END
-
-TEST_BEGIN(test_witness_recursive)
-{
- witness_t a;
- tsdn_t *tsdn;
-
- test_skip_if(!config_debug);
-
- witness_not_owner_error_orig = witness_not_owner_error;
- witness_not_owner_error = witness_not_owner_error_intercept;
- saw_not_owner_error = false;
-
- witness_lock_error_orig = witness_lock_error;
- witness_lock_error = witness_lock_error_intercept;
- saw_lock_error = false;
-
- tsdn = tsdn_fetch();
-
- witness_assert_lockless(tsdn);
-
- witness_init(&a, "a", 1, NULL);
-
- witness_lock(tsdn, &a);
- assert_false(saw_lock_error, "Unexpected witness lock error");
- assert_false(saw_not_owner_error, "Unexpected witness not owner error");
- witness_lock(tsdn, &a);
- assert_true(saw_lock_error, "Expected witness lock error");
- assert_true(saw_not_owner_error, "Expected witness not owner error");
-
- witness_unlock(tsdn, &a);
-
- witness_assert_lockless(tsdn);
-
- witness_owner_error = witness_owner_error_orig;
- witness_lock_error = witness_lock_error_orig;
-
-}
-TEST_END
-
-TEST_BEGIN(test_witness_unlock_not_owned)
-{
- witness_t a;
- tsdn_t *tsdn;
-
- test_skip_if(!config_debug);
-
- witness_owner_error_orig = witness_owner_error;
- witness_owner_error = witness_owner_error_intercept;
- saw_owner_error = false;
-
- tsdn = tsdn_fetch();
-
- witness_assert_lockless(tsdn);
-
- witness_init(&a, "a", 1, NULL);
-
- assert_false(saw_owner_error, "Unexpected owner error");
- witness_unlock(tsdn, &a);
- assert_true(saw_owner_error, "Expected owner error");
-
- witness_assert_lockless(tsdn);
-
- witness_owner_error = witness_owner_error_orig;
-}
-TEST_END
-
-TEST_BEGIN(test_witness_lockful)
-{
- witness_t a;
- tsdn_t *tsdn;
-
- test_skip_if(!config_debug);
-
- witness_lockless_error_orig = witness_lockless_error;
- witness_lockless_error = witness_lockless_error_intercept;
- saw_lockless_error = false;
-
- tsdn = tsdn_fetch();
-
- witness_assert_lockless(tsdn);
-
- witness_init(&a, "a", 1, NULL);
-
- assert_false(saw_lockless_error, "Unexpected lockless error");
- witness_assert_lockless(tsdn);
-
- witness_lock(tsdn, &a);
- witness_assert_lockless(tsdn);
- assert_true(saw_lockless_error, "Expected lockless error");
-
- witness_unlock(tsdn, &a);
-
- witness_assert_lockless(tsdn);
-
- witness_lockless_error = witness_lockless_error_orig;
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_witness,
- test_witness_comp,
- test_witness_reversal,
- test_witness_recursive,
- test_witness_unlock_not_owned,
- test_witness_lockful));
-}
diff --git a/memory/jemalloc/src/test/unit/zero.c b/memory/jemalloc/src/test/unit/zero.c
deleted file mode 100644
index 30ebe37a4..000000000
--- a/memory/jemalloc/src/test/unit/zero.c
+++ /dev/null
@@ -1,80 +0,0 @@
-#include "test/jemalloc_test.h"
-
-#ifdef JEMALLOC_FILL
-const char *malloc_conf =
- "abort:false,junk:false,zero:true,redzone:false,quarantine:0";
-#endif
-
-static void
-test_zero(size_t sz_min, size_t sz_max)
-{
- uint8_t *s;
- size_t sz_prev, sz, i;
-#define MAGIC ((uint8_t)0x61)
-
- sz_prev = 0;
- s = (uint8_t *)mallocx(sz_min, 0);
- assert_ptr_not_null((void *)s, "Unexpected mallocx() failure");
-
- for (sz = sallocx(s, 0); sz <= sz_max;
- sz_prev = sz, sz = sallocx(s, 0)) {
- if (sz_prev > 0) {
- assert_u_eq(s[0], MAGIC,
- "Previously allocated byte %zu/%zu is corrupted",
- ZU(0), sz_prev);
- assert_u_eq(s[sz_prev-1], MAGIC,
- "Previously allocated byte %zu/%zu is corrupted",
- sz_prev-1, sz_prev);
- }
-
- for (i = sz_prev; i < sz; i++) {
- assert_u_eq(s[i], 0x0,
- "Newly allocated byte %zu/%zu isn't zero-filled",
- i, sz);
- s[i] = MAGIC;
- }
-
- if (xallocx(s, sz+1, 0, 0) == sz) {
- s = (uint8_t *)rallocx(s, sz+1, 0);
- assert_ptr_not_null((void *)s,
- "Unexpected rallocx() failure");
- }
- }
-
- dallocx(s, 0);
-#undef MAGIC
-}
-
-TEST_BEGIN(test_zero_small)
-{
-
- test_skip_if(!config_fill);
- test_zero(1, SMALL_MAXCLASS-1);
-}
-TEST_END
-
-TEST_BEGIN(test_zero_large)
-{
-
- test_skip_if(!config_fill);
- test_zero(SMALL_MAXCLASS+1, large_maxclass);
-}
-TEST_END
-
-TEST_BEGIN(test_zero_huge)
-{
-
- test_skip_if(!config_fill);
- test_zero(large_maxclass+1, chunksize*2);
-}
-TEST_END
-
-int
-main(void)
-{
-
- return (test(
- test_zero_small,
- test_zero_large,
- test_zero_huge));
-}
diff --git a/memory/jemalloc/update.sh b/memory/jemalloc/update.sh
deleted file mode 100755
index bd126ec8a..000000000
--- a/memory/jemalloc/update.sh
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/bin/bash
-
-set -e
-
-cd `dirname $0`
-
-source upstream.info
-
-rm -rf src
-git clone "$UPSTREAM_REPO" src
-cd src
-git checkout "$UPSTREAM_COMMIT"
-autoconf
-git describe --long --abbrev=40 > VERSION
-rm -rf .git .gitignore .gitattributes autom4te.cache .autom4te.cfg
-
-cd ..
-hg addremove -q src
-
-echo "jemalloc has now been updated. Don't forget to run hg commit!"
diff --git a/memory/jemalloc/upstream.info b/memory/jemalloc/upstream.info
deleted file mode 100644
index ba561cc54..000000000
--- a/memory/jemalloc/upstream.info
+++ /dev/null
@@ -1,2 +0,0 @@
-UPSTREAM_REPO=https://github.com/jemalloc/jemalloc
-UPSTREAM_COMMIT=4.3.1
diff --git a/memory/moz.build b/memory/moz.build
index cf8bbc0f3..acbcfaec9 100644
--- a/memory/moz.build
+++ b/memory/moz.build
@@ -20,9 +20,5 @@ if CONFIG['MOZ_MEMORY']:
'mozjemalloc',
]
- if CONFIG['MOZ_JEMALLOC4'] or CONFIG['MOZ_REPLACE_MALLOC']:
- if not CONFIG['MOZ_SYSTEM_JEMALLOC']:
- DIRS += ['jemalloc']
-
if CONFIG['MOZ_REPLACE_MALLOC']:
DIRS += ['replace']
diff --git a/memory/mozjemalloc/Makefile.in b/memory/mozjemalloc/Makefile.in
index 6c47e1fa2..f02b315ec 100644
--- a/memory/mozjemalloc/Makefile.in
+++ b/memory/mozjemalloc/Makefile.in
@@ -3,11 +3,9 @@
# License, v. 2.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_JEMALLOC4
# Force optimize mozjemalloc on --disable-optimize builds.
# This works around the issue that the Android NDK's definition of ffs is
# broken when compiling without optimization, while avoiding to add yet another
# configure test.
MOZ_OPTIMIZE = 1
-endif
diff --git a/memory/mozjemalloc/jemalloc.c b/memory/mozjemalloc/jemalloc.c
index 5d4d83a24..c0c189abf 100644
--- a/memory/mozjemalloc/jemalloc.c
+++ b/memory/mozjemalloc/jemalloc.c
@@ -2,7 +2,7 @@
/* vim:set softtabstop=8 shiftwidth=8 noet: */
/*-
* Copyright (C) 2006-2008 Jason Evans <jasone@FreeBSD.org>.
- * All rights reserved.
+ * Copyright (C) 2015-2018 Mark Straver <moonchild@palemoon.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -140,29 +140,16 @@
#endif
/*
- * Use only one arena by default. Mozilla does not currently make extensive
- * use of concurrent allocation, so the increased fragmentation associated with
- * multiple arenas is not warranted.
- *
- * When using the Servo style system, we do indeed make use of significant
- * concurrent allocation, and the overhead matters. Bug 1291355 tracks
- * investigating the fragmentation overhead of turning this on for users.
+ * Uncomment this to use only one arena by default.
*/
-#ifndef MOZ_STYLO
-#define MOZ_MEMORY_NARENAS_DEFAULT_ONE
-#endif
+// #define MOZ_MEMORY_NARENAS_DEFAULT_ONE
/*
* Pass this set of options to jemalloc as its default. It does not override
* the options passed via the MALLOC_OPTIONS environment variable but is
* applied in addition to them.
*/
-#ifdef MOZ_WIDGET_GONK
- /* Reduce the amount of unused dirty pages to 1MiB on B2G */
-# define MOZ_MALLOC_OPTIONS "ff"
-#else
# define MOZ_MALLOC_OPTIONS ""
-#endif
/*
* MALLOC_STATS enables statistics calculation, and is required for
@@ -199,13 +186,6 @@
*/
#define MALLOC_VALIDATE
-/*
- * MALLOC_BALANCE enables monitoring of arena lock contention and dynamically
- * re-balances arena load if exponentially averaged contention exceeds a
- * certain threshold.
- */
-/* #define MALLOC_BALANCE */
-
#if defined(MOZ_MEMORY_LINUX) && !defined(MOZ_MEMORY_ANDROID)
#define _GNU_SOURCE /* For mremap(2). */
#if 0 /* Enable in order to test decommit code on Linux. */
@@ -224,9 +204,6 @@
#ifdef MOZ_MEMORY_WINDOWS
-/* Some defines from the CRT internal headers that we need here. */
-#define _CRT_SPINCOUNT 5000
-#define __crtInitCritSecAndSpinCount InitializeCriticalSectionAndSpinCount
#include <io.h>
#include <windows.h>
#include <intrin.h>
@@ -433,10 +410,6 @@ void *_mmap(void *addr, size_t length, int prot, int flags,
#endif
#endif
-#ifdef MOZ_MEMORY_DARWIN
-static const bool isthreaded = true;
-#endif
-
#if defined(MOZ_MEMORY_SOLARIS) && defined(MAP_ALIGN) && !defined(JEMALLOC_NEVER_USES_MAP_ALIGN)
#define JEMALLOC_USES_MAP_ALIGN /* Required on Solaris 10. Might improve performance elsewhere. */
#endif
@@ -471,9 +444,7 @@ static const bool isthreaded = true;
# define SIZEOF_PTR_2POW 2
#endif
#define PIC
-#ifndef MOZ_MEMORY_DARWIN
-static const bool isthreaded = true;
-#else
+#ifdef MOZ_MEMORY_DARWIN
# define NO_TLS
#endif
#if 0
@@ -529,13 +500,6 @@ static const bool isthreaded = true;
# define NO_TLS
#endif
-#ifdef NO_TLS
- /* MALLOC_BALANCE requires TLS. */
-# ifdef MALLOC_BALANCE
-# undef MALLOC_BALANCE
-# endif
-#endif
-
/*
* Size and alignment of memory chunks that are allocated by the OS's virtual
* memory system.
@@ -615,24 +579,6 @@ static const bool isthreaded = true;
*/
#define BLOCK_COST_2POW 4
-#ifdef MALLOC_BALANCE
- /*
- * We use an exponential moving average to track recent lock contention,
- * where the size of the history window is N, and alpha=2/(N+1).
- *
- * Due to integer math rounding, very small values here can cause
- * substantial degradation in accuracy, thus making the moving average decay
- * faster than it would with precise calculation.
- */
-# define BALANCE_ALPHA_INV_2POW 9
-
- /*
- * Threshold value for the exponential moving contention average at which to
- * re-assign a thread.
- */
-# define BALANCE_THRESHOLD_DEFAULT (1U << (SPIN_LIMIT_2POW-4))
-#endif
-
/******************************************************************************/
/* MALLOC_DECOMMIT and MALLOC_DOUBLE_PURGE are mutually exclusive. */
@@ -646,8 +592,8 @@ static const bool isthreaded = true;
* issues in some cases.
*/
#if defined(MOZ_MEMORY_WINDOWS)
-#define malloc_mutex_t CRITICAL_SECTION
-#define malloc_spinlock_t CRITICAL_SECTION
+#define malloc_mutex_t SRWLOCK
+#define malloc_spinlock_t SRWLOCK
#elif defined(MOZ_MEMORY_DARWIN)
typedef struct {
OSSpinLock lock;
@@ -746,11 +692,6 @@ struct arena_stats_s {
size_t allocated_large;
uint64_t nmalloc_large;
uint64_t ndalloc_large;
-
-#ifdef MALLOC_BALANCE
- /* Number of times this arena reassigned a thread due to contention. */
- uint64_t nbalance;
-#endif
};
#endif /* #ifdef MALLOC_STATS */
@@ -1035,14 +976,6 @@ struct arena_s {
*/
arena_avail_tree_t runs_avail;
-#ifdef MALLOC_BALANCE
- /*
- * The arena load balancing machinery needs to keep track of how much
- * lock contention there is. This value is exponentially averaged.
- */
- uint32_t contention;
-#endif
-
/*
* bins is used to store rings of free regions of the following sizes,
* assuming a 16-byte quantum, 4kB pagesize, and default MALLOC_OPTIONS.
@@ -1281,11 +1214,7 @@ static size_t base_committed;
static arena_t **arenas;
static unsigned narenas;
#ifndef NO_TLS
-# ifdef MALLOC_BALANCE
-static unsigned narenas_2pow;
-# else
static unsigned next_arena;
-# endif
#endif
#ifdef MOZ_MEMORY
static malloc_spinlock_t arenas_lock; /* Protects arenas initialization. */
@@ -1327,9 +1256,6 @@ static const bool opt_zero = false;
#endif
static size_t opt_dirty_max = DIRTY_MAX_DEFAULT;
-#ifdef MALLOC_BALANCE
-static uint64_t opt_balance_threshold = BALANCE_THRESHOLD_DEFAULT;
-#endif
static bool opt_print_stats = false;
#ifdef MALLOC_STATIC_SIZES
#define opt_quantum_2pow QUANTUM_2POW_MIN
@@ -1424,9 +1350,6 @@ static void arena_run_trim_tail(arena_t *arena, arena_chunk_t *chunk,
static arena_run_t *arena_bin_nonfull_run_get(arena_t *arena, arena_bin_t *bin);
static void *arena_bin_malloc_hard(arena_t *arena, arena_bin_t *bin);
static size_t arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size);
-#ifdef MALLOC_BALANCE
-static void arena_lock_balance_hard(arena_t *arena);
-#endif
static void *arena_malloc_large(arena_t *arena, size_t size, bool zero);
static void *arena_palloc(arena_t *arena, size_t alignment, size_t size,
size_t alloc_size);
@@ -1635,9 +1558,7 @@ static bool
malloc_mutex_init(malloc_mutex_t *mutex)
{
#if defined(MOZ_MEMORY_WINDOWS)
- if (isthreaded)
- if (! __crtInitCritSecAndSpinCount(mutex, _CRT_SPINCOUNT))
- return (true);
+ InitializeSRWLock(mutex);
#elif defined(MOZ_MEMORY_DARWIN)
mutex->lock = OS_SPINLOCK_INIT;
#elif defined(MOZ_MEMORY_LINUX) && !defined(MOZ_MEMORY_ANDROID)
@@ -1666,14 +1587,13 @@ malloc_mutex_lock(malloc_mutex_t *mutex)
{
#if defined(MOZ_MEMORY_WINDOWS)
- EnterCriticalSection(mutex);
+ AcquireSRWLockExclusive(mutex);
#elif defined(MOZ_MEMORY_DARWIN)
OSSpinLockLock(&mutex->lock);
#elif defined(MOZ_MEMORY)
pthread_mutex_lock(mutex);
#else
- if (isthreaded)
- _SPINLOCK(&mutex->lock);
+ _SPINLOCK(&mutex->lock);
#endif
}
@@ -1682,14 +1602,13 @@ malloc_mutex_unlock(malloc_mutex_t *mutex)
{
#if defined(MOZ_MEMORY_WINDOWS)
- LeaveCriticalSection(mutex);
+ ReleaseSRWLockExclusive(mutex);
#elif defined(MOZ_MEMORY_DARWIN)
OSSpinLockUnlock(&mutex->lock);
#elif defined(MOZ_MEMORY)
pthread_mutex_unlock(mutex);
#else
- if (isthreaded)
- _SPINUNLOCK(&mutex->lock);
+ _SPINUNLOCK(&mutex->lock);
#endif
}
@@ -1700,9 +1619,7 @@ static bool
malloc_spin_init(malloc_spinlock_t *lock)
{
#if defined(MOZ_MEMORY_WINDOWS)
- if (isthreaded)
- if (! __crtInitCritSecAndSpinCount(lock, _CRT_SPINCOUNT))
- return (true);
+ InitializeSRWLock(lock);
#elif defined(MOZ_MEMORY_DARWIN)
lock->lock = OS_SPINLOCK_INIT;
#elif defined(MOZ_MEMORY_LINUX) && !defined(MOZ_MEMORY_ANDROID)
@@ -1729,14 +1646,13 @@ malloc_spin_lock(malloc_spinlock_t *lock)
{
#if defined(MOZ_MEMORY_WINDOWS)
- EnterCriticalSection(lock);
+ AcquireSRWLockExclusive(lock);
#elif defined(MOZ_MEMORY_DARWIN)
OSSpinLockLock(&lock->lock);
#elif defined(MOZ_MEMORY)
pthread_mutex_lock(lock);
#else
- if (isthreaded)
- _SPINLOCK(&lock->lock);
+ _SPINLOCK(&lock->lock);
#endif
}
@@ -1744,14 +1660,13 @@ static inline void
malloc_spin_unlock(malloc_spinlock_t *lock)
{
#if defined(MOZ_MEMORY_WINDOWS)
- LeaveCriticalSection(lock);
+ ReleaseSRWLockExclusive(lock);
#elif defined(MOZ_MEMORY_DARWIN)
OSSpinLockUnlock(&lock->lock);
#elif defined(MOZ_MEMORY)
pthread_mutex_unlock(lock);
#else
- if (isthreaded)
- _SPINUNLOCK(&lock->lock);
+ _SPINUNLOCK(&lock->lock);
#endif
}
@@ -1805,30 +1720,28 @@ malloc_spin_lock(pthread_mutex_t *lock)
{
unsigned ret = 0;
- if (isthreaded) {
- if (_pthread_mutex_trylock(lock) != 0) {
- unsigned i;
- volatile unsigned j;
+ if (_pthread_mutex_trylock(lock) != 0) {
+ unsigned i;
+ volatile unsigned j;
- /* Exponentially back off. */
- for (i = 1; i <= SPIN_LIMIT_2POW; i++) {
- for (j = 0; j < (1U << i); j++)
- ret++;
+ /* Exponentially back off. */
+ for (i = 1; i <= SPIN_LIMIT_2POW; i++) {
+ for (j = 0; j < (1U << i); j++)
+ ret++;
- CPU_SPINWAIT;
- if (_pthread_mutex_trylock(lock) == 0)
- return (ret);
- }
-
- /*
- * Spinning failed. Block until the lock becomes
- * available, in order to avoid indefinite priority
- * inversion.
- */
- _pthread_mutex_lock(lock);
- assert((ret << BLOCK_COST_2POW) != 0);
- return (ret << BLOCK_COST_2POW);
+ CPU_SPINWAIT;
+ if (_pthread_mutex_trylock(lock) == 0)
+ return (ret);
}
+
+ /*
+ * Spinning failed. Block until the lock becomes
+ * available, in order to avoid indefinite priority
+ * inversion.
+ */
+ _pthread_mutex_lock(lock);
+ assert((ret << BLOCK_COST_2POW) != 0);
+ return (ret << BLOCK_COST_2POW);
}
return (ret);
@@ -1837,9 +1750,7 @@ malloc_spin_lock(pthread_mutex_t *lock)
static inline void
malloc_spin_unlock(pthread_mutex_t *lock)
{
-
- if (isthreaded)
- _pthread_mutex_unlock(lock);
+ _pthread_mutex_unlock(lock);
}
#endif
@@ -1893,56 +1804,6 @@ pow2_ceil(size_t x)
return (x);
}
-#ifdef MALLOC_BALANCE
-/*
- * Use a simple linear congruential pseudo-random number generator:
- *
- * prn(y) = (a*x + c) % m
- *
- * where the following constants ensure maximal period:
- *
- * a == Odd number (relatively prime to 2^n), and (a-1) is a multiple of 4.
- * c == Odd number (relatively prime to 2^n).
- * m == 2^32
- *
- * See Knuth's TAOCP 3rd Ed., Vol. 2, pg. 17 for details on these constraints.
- *
- * This choice of m has the disadvantage that the quality of the bits is
- * proportional to bit position. For example. the lowest bit has a cycle of 2,
- * the next has a cycle of 4, etc. For this reason, we prefer to use the upper
- * bits.
- */
-# define PRN_DEFINE(suffix, var, a, c) \
-static inline void \
-sprn_##suffix(uint32_t seed) \
-{ \
- var = seed; \
-} \
- \
-static inline uint32_t \
-prn_##suffix(uint32_t lg_range) \
-{ \
- uint32_t ret, x; \
- \
- assert(lg_range > 0); \
- assert(lg_range <= 32); \
- \
- x = (var * (a)) + (c); \
- var = x; \
- ret = x >> (32 - lg_range); \
- \
- return (ret); \
-}
-# define SPRN(suffix, seed) sprn_##suffix(seed)
-# define PRN(suffix, lg_range) prn_##suffix(lg_range)
-#endif
-
-#ifdef MALLOC_BALANCE
-/* Define the PRNG used for arena assignment. */
-static __thread uint32_t balance_x;
-PRN_DEFINE(balance, balance_x, 1297, 1301)
-#endif
-
#ifdef MALLOC_UTRACE
static int
utrace(const void *addr, size_t len)
@@ -3089,10 +2950,6 @@ choose_arena(void)
* introduces a bootstrapping issue.
*/
#ifndef NO_TLS
- if (isthreaded == false) {
- /* Avoid the overhead of TLS for single-threaded operation. */
- return (arenas[0]);
- }
# ifdef MOZ_MEMORY_WINDOWS
ret = (arena_t*)TlsGetValue(tlsIndex);
@@ -3105,7 +2962,7 @@ choose_arena(void)
RELEASE_ASSERT(ret != NULL);
}
#else
- if (isthreaded && narenas > 1) {
+ if (narenas > 1) {
unsigned long ind;
/*
@@ -3162,31 +3019,12 @@ choose_arena_hard(void)
{
arena_t *ret;
- assert(isthreaded);
-
-#ifdef MALLOC_BALANCE
- /* Seed the PRNG used for arena load balancing. */
- SPRN(balance, (uint32_t)(uintptr_t)(_pthread_self()));
-#endif
-
if (narenas > 1) {
-#ifdef MALLOC_BALANCE
- unsigned ind;
-
- ind = PRN(balance, narenas_2pow);
- if ((ret = arenas[ind]) == NULL) {
- malloc_spin_lock(&arenas_lock);
- if ((ret = arenas[ind]) == NULL)
- ret = arenas_extend(ind);
- malloc_spin_unlock(&arenas_lock);
- }
-#else
malloc_spin_lock(&arenas_lock);
if ((ret = arenas[next_arena]) == NULL)
ret = arenas_extend(next_arena);
next_arena = (next_arena + 1) % narenas;
malloc_spin_unlock(&arenas_lock);
-#endif
} else
ret = arenas[0];
@@ -4120,63 +3958,6 @@ arena_bin_run_size_calc(arena_bin_t *bin, size_t min_run_size)
return (good_run_size);
}
-#ifdef MALLOC_BALANCE
-static inline void
-arena_lock_balance(arena_t *arena)
-{
- unsigned contention;
-
- contention = malloc_spin_lock(&arena->lock);
- if (narenas > 1) {
- /*
- * Calculate the exponentially averaged contention for this
- * arena. Due to integer math always rounding down, this value
- * decays somewhat faster then normal.
- */
- arena->contention = (((uint64_t)arena->contention
- * (uint64_t)((1U << BALANCE_ALPHA_INV_2POW)-1))
- + (uint64_t)contention) >> BALANCE_ALPHA_INV_2POW;
- if (arena->contention >= opt_balance_threshold)
- arena_lock_balance_hard(arena);
- }
-}
-
-static void
-arena_lock_balance_hard(arena_t *arena)
-{
- uint32_t ind;
-
- arena->contention = 0;
-#ifdef MALLOC_STATS
- arena->stats.nbalance++;
-#endif
- ind = PRN(balance, narenas_2pow);
- if (arenas[ind] != NULL) {
-#ifdef MOZ_MEMORY_WINDOWS
- TlsSetValue(tlsIndex, arenas[ind]);
-#else
- arenas_map = arenas[ind];
-#endif
- } else {
- malloc_spin_lock(&arenas_lock);
- if (arenas[ind] != NULL) {
-#ifdef MOZ_MEMORY_WINDOWS
- TlsSetValue(tlsIndex, arenas[ind]);
-#else
- arenas_map = arenas[ind];
-#endif
- } else {
-#ifdef MOZ_MEMORY_WINDOWS
- TlsSetValue(tlsIndex, arenas_extend(ind));
-#else
- arenas_map = arenas_extend(ind);
-#endif
- }
- malloc_spin_unlock(&arenas_lock);
- }
-}
-#endif
-
static inline void *
arena_malloc_small(arena_t *arena, size_t size, bool zero)
{
@@ -4211,11 +3992,8 @@ arena_malloc_small(arena_t *arena, size_t size, bool zero)
}
RELEASE_ASSERT(size == bin->reg_size);
-#ifdef MALLOC_BALANCE
- arena_lock_balance(arena);
-#else
malloc_spin_lock(&arena->lock);
-#endif
+
if ((run = bin->runcur) != NULL && run->nfree > 0)
ret = arena_bin_malloc_easy(arena, bin, run);
else
@@ -4253,11 +4031,7 @@ arena_malloc_large(arena_t *arena, size_t size, bool zero)
/* Large allocation. */
size = PAGE_CEILING(size);
-#ifdef MALLOC_BALANCE
- arena_lock_balance(arena);
-#else
malloc_spin_lock(&arena->lock);
-#endif
ret = (void *)arena_run_alloc(arena, NULL, size, true, zero);
if (ret == NULL) {
malloc_spin_unlock(&arena->lock);
@@ -4329,11 +4103,8 @@ arena_palloc(arena_t *arena, size_t alignment, size_t size, size_t alloc_size)
assert((size & pagesize_mask) == 0);
assert((alignment & pagesize_mask) == 0);
-#ifdef MALLOC_BALANCE
- arena_lock_balance(arena);
-#else
malloc_spin_lock(&arena->lock);
-#endif
+
ret = (void *)arena_run_alloc(arena, NULL, alloc_size, true, false);
if (ret == NULL) {
malloc_spin_unlock(&arena->lock);
@@ -4756,11 +4527,7 @@ arena_ralloc_large_shrink(arena_t *arena, arena_chunk_t *chunk, void *ptr,
* Shrink the run, and make trailing pages available for other
* allocations.
*/
-#ifdef MALLOC_BALANCE
- arena_lock_balance(arena);
-#else
malloc_spin_lock(&arena->lock);
-#endif
arena_run_trim_tail(arena, chunk, (arena_run_t *)ptr, oldsize, size,
true);
#ifdef MALLOC_STATS
@@ -4780,11 +4547,7 @@ arena_ralloc_large_grow(arena_t *arena, arena_chunk_t *chunk, void *ptr,
/* Try to extend the run. */
assert(size > oldsize);
-#ifdef MALLOC_BALANCE
- arena_lock_balance(arena);
-#else
malloc_spin_lock(&arena->lock);
-#endif
if (pageind + npages < chunk_npages && (chunk->map[pageind+npages].bits
& CHUNK_MAP_ALLOCATED) == 0 && (chunk->map[pageind+npages].bits &
~pagesize_mask) >= size - oldsize) {
@@ -4962,10 +4725,6 @@ arena_new(arena_t *arena)
arena_avail_tree_new(&arena->runs_avail);
-#ifdef MALLOC_BALANCE
- arena->contention = 0;
-#endif
-
/* Initialize bins. */
prev_run_size = pagesize;
@@ -5273,7 +5032,10 @@ huge_dalloc(void *ptr)
base_node_dealloc(node);
}
-#ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE
+/*
+ * Platform-specific methods to determine the number of CPUs in a system.
+ * This will be used to determine the desired number of arenas.
+ */
#ifdef MOZ_MEMORY_BSD
static inline unsigned
malloc_ncpus(void)
@@ -5371,11 +5133,19 @@ malloc_ncpus(void)
{
return sysconf(_SC_NPROCESSORS_ONLN);
}
+#elif (defined(MOZ_MEMORY_WINDOWS))
+static inline unsigned
+malloc_ncpus(void)
+{
+ SYSTEM_INFO info;
+
+ GetSystemInfo(&info);
+ return (info.dwNumberOfProcessors);
+}
#else
static inline unsigned
malloc_ncpus(void)
{
-
/*
* We lack a way to determine the number of CPUs on this platform, so
* assume 1 CPU.
@@ -5383,7 +5153,6 @@ malloc_ncpus(void)
return (1);
}
#endif
-#endif
static void
malloc_print_stats(void)
@@ -5426,10 +5195,6 @@ malloc_print_stats(void)
#endif
_malloc_message("Max arenas: ", umax2s(narenas, 10, s), "\n",
"");
-#ifdef MALLOC_BALANCE
- _malloc_message("Arena balance threshold: ",
- umax2s(opt_balance_threshold, 10, s), "\n", "");
-#endif
_malloc_message("Pointer size: ", umax2s(sizeof(void *), 10, s),
"\n", "");
_malloc_message("Quantum size: ", umax2s(quantum, 10, s), "\n",
@@ -5447,9 +5212,6 @@ malloc_print_stats(void)
#ifdef MALLOC_STATS
{
size_t allocated, mapped = 0;
-#ifdef MALLOC_BALANCE
- uint64_t nbalance = 0;
-#endif
unsigned i;
arena_t *arena;
@@ -5464,9 +5226,6 @@ malloc_print_stats(void)
allocated +=
arenas[i]->stats.allocated_large;
mapped += arenas[i]->stats.mapped;
-#ifdef MALLOC_BALANCE
- nbalance += arenas[i]->stats.nbalance;
-#endif
malloc_spin_unlock(&arenas[i]->lock);
}
}
@@ -5489,11 +5248,6 @@ malloc_print_stats(void)
allocated, mapped);
#endif
-#ifdef MALLOC_BALANCE
- malloc_printf("Arena balance reassignments: %llu\n",
- nbalance);
-#endif
-
/* Print chunk stats. */
malloc_printf(
"huge: nmalloc ndalloc allocated\n");
@@ -5584,20 +5338,16 @@ malloc_init_hard(void)
GetSystemInfo(&info);
result = info.dwPageSize;
-
-#ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE
- ncpus = info.dwNumberOfProcessors;
-#endif
}
#else
-#ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE
- ncpus = malloc_ncpus();
-#endif
-
result = sysconf(_SC_PAGESIZE);
assert(result != -1);
#endif
+#ifndef MOZ_MEMORY_NARENAS_DEFAULT_ONE
+ ncpus = malloc_ncpus();
+#endif
+
/* We assume that the page size is a power of 2. */
assert(((result - 1) & result) == 0);
#ifdef MALLOC_STATIC_SIZES
@@ -5699,18 +5449,8 @@ MALLOC_OUT:
opt_abort = true;
break;
case 'b':
-#ifdef MALLOC_BALANCE
- opt_balance_threshold >>= 1;
-#endif
- break;
case 'B':
-#ifdef MALLOC_BALANCE
- if (opt_balance_threshold == 0)
- opt_balance_threshold = 1;
- else if ((opt_balance_threshold << 1)
- > opt_balance_threshold)
- opt_balance_threshold <<= 1;
-#endif
+ // Balancing option is ignored
break;
#ifdef MALLOC_FILL
#ifndef MALLOC_PRODUCTION
@@ -5953,12 +5693,6 @@ MALLOC_OUT:
if (narenas == 0)
narenas = 1;
}
-#ifdef MALLOC_BALANCE
- assert(narenas != 0);
- for (narenas_2pow = 0;
- (narenas >> (narenas_2pow + 1)) != 0;
- narenas_2pow++);
-#endif
#ifdef NO_TLS
if (narenas > 1) {
@@ -5988,9 +5722,7 @@ MALLOC_OUT:
#endif
#ifndef NO_TLS
-# ifndef MALLOC_BALANCE
next_arena = 0;
-# endif
#endif
/* Allocate and initialize arenas. */
@@ -6031,14 +5763,6 @@ MALLOC_OUT:
#endif
#endif
- /*
- * Seed here for the initial thread, since choose_arena_hard() is only
- * called for other threads. The seed value doesn't really matter.
- */
-#ifdef MALLOC_BALANCE
- SPRN(balance, 42);
-#endif
-
malloc_spin_init(&arenas_lock);
#ifdef MALLOC_VALIDATE
@@ -6579,13 +6303,7 @@ jemalloc_stats_impl(jemalloc_stats_t *stats)
#endif
false;
stats->narenas = narenas;
- stats->balance_threshold =
-#ifdef MALLOC_BALANCE
- opt_balance_threshold
-#else
- SIZE_T_MAX
-#endif
- ;
+ stats->balance_threshold = SIZE_T_MAX;
stats->quantum = quantum;
stats->small_max = small_max;
stats->large_max = arena_maxclass;
diff --git a/memory/mozjemalloc/jemalloc_types.h b/memory/mozjemalloc/jemalloc_types.h
index ae8dc4414..96165ae4d 100644
--- a/memory/mozjemalloc/jemalloc_types.h
+++ b/memory/mozjemalloc/jemalloc_types.h
@@ -2,7 +2,7 @@
/* vim:set softtabstop=8 shiftwidth=8: */
/*-
* Copyright (C) 2006-2008 Jason Evans <jasone@FreeBSD.org>.
- * All rights reserved.
+ * Copyright (C) 2015-2018 Mark Straver <moonchild@palemoon.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
diff --git a/memory/mozjemalloc/linkedlist.h b/memory/mozjemalloc/linkedlist.h
index d75531410..acb10e56d 100644
--- a/memory/mozjemalloc/linkedlist.h
+++ b/memory/mozjemalloc/linkedlist.h
@@ -2,7 +2,7 @@
/* vim:set softtabstop=8 shiftwidth=8 noet: */
/*-
* Copyright (C) the Mozilla Foundation.
- * All rights reserved.
+ * Copyright (C) 2015-2018 Mark Straver <moonchild@palemoon.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
diff --git a/memory/mozjemalloc/moz.build b/memory/mozjemalloc/moz.build
index 0660d1300..feeb4fb07 100644
--- a/memory/mozjemalloc/moz.build
+++ b/memory/mozjemalloc/moz.build
@@ -8,16 +8,15 @@ EXPORTS += [
'jemalloc_types.h',
]
-if not CONFIG['MOZ_JEMALLOC4']:
- SOURCES += [
- 'jemalloc.c',
- ]
- FINAL_LIBRARY = 'memory'
-
- # See bug 422055.
- if CONFIG['OS_ARCH'] == 'SunOS' and not CONFIG['GNU_CC'] \
- and CONFIG['MOZ_OPTIMIZE']:
- CFLAGS += ['-xO5']
+SOURCES += [
+ 'jemalloc.c',
+]
+FINAL_LIBRARY = 'memory'
+
+# See bug 422055.
+if CONFIG['OS_ARCH'] == 'SunOS' and not CONFIG['GNU_CC'] \
+ and CONFIG['MOZ_OPTIMIZE']:
+ CFLAGS += ['-xO5']
# For non release/esr builds, enable (some) fatal jemalloc assertions. This
# helps us catch memory errors.
diff --git a/memory/mozjemalloc/osx_zone_types.h b/memory/mozjemalloc/osx_zone_types.h
index 097953590..603649dbc 100644
--- a/memory/mozjemalloc/osx_zone_types.h
+++ b/memory/mozjemalloc/osx_zone_types.h
@@ -2,7 +2,7 @@
/* vim:set softtabstop=8 shiftwidth=8: */
/*-
* Copyright (C) 2006-2008 Jason Evans <jasone@FreeBSD.org>.
- * All rights reserved.
+ * Copyright (C) 2015-2018 Mark Straver <moonchild@palemoon.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
diff --git a/memory/mozjemalloc/ql.h b/memory/mozjemalloc/ql.h
index 000cd2380..2fdb2d40c 100644
--- a/memory/mozjemalloc/ql.h
+++ b/memory/mozjemalloc/ql.h
@@ -1,7 +1,7 @@
/******************************************************************************
*
* Copyright (C) 2002 Jason Evans <jasone@canonware.com>.
- * All rights reserved.
+ * Copyright (C) 2015-2018 Mark Straver <moonchild@palemoon.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
diff --git a/memory/mozjemalloc/qr.h b/memory/mozjemalloc/qr.h
index ee60491d7..03891664b 100644
--- a/memory/mozjemalloc/qr.h
+++ b/memory/mozjemalloc/qr.h
@@ -1,7 +1,7 @@
/******************************************************************************
*
* Copyright (C) 2002 Jason Evans <jasone@canonware.com>.
- * All rights reserved.
+ * Copyright (C) 2015-2018 Mark Straver <moonchild@palemoon.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
diff --git a/memory/mozjemalloc/rb.h b/memory/mozjemalloc/rb.h
index 43d8569d0..53a926d46 100644
--- a/memory/mozjemalloc/rb.h
+++ b/memory/mozjemalloc/rb.h
@@ -1,7 +1,7 @@
/******************************************************************************
*
* Copyright (C) 2008 Jason Evans <jasone@FreeBSD.org>.
- * All rights reserved.
+ * Copyright (C) 2015-2018 Mark Straver <moonchild@palemoon.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
diff --git a/memory/replace/jemalloc/moz.build b/memory/replace/jemalloc/moz.build
deleted file mode 100644
index 5e907af55..000000000
--- a/memory/replace/jemalloc/moz.build
+++ /dev/null
@@ -1,31 +0,0 @@
-# -*- 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/.
-
-SOURCES += [
- '../../build/jemalloc_config.cpp',
- '../../build/mozjemalloc_compat.c',
-]
-
-# Android doesn't have pthread_atfork, so just implement a dummy function.
-# It shouldn't make much problem, as the use of fork is pretty limited on
-# Android.
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
- SOURCES += [
- 'pthread_atfork.c',
- ]
-
-SharedLibrary('replace_jemalloc')
-
-DEFINES['MOZ_JEMALLOC4'] = True
-DEFINES['MOZ_REPLACE_JEMALLOC'] = True
-
-LOCAL_INCLUDES += ['!../../jemalloc/src/include']
-if CONFIG['_MSC_VER']:
- LOCAL_INCLUDES += ['/memory/jemalloc/src/include/msvc_compat']
- if not CONFIG['HAVE_INTTYPES_H']:
- LOCAL_INCLUDES += ['/memory/jemalloc/src/include/msvc_compat/C99']
-
-DISABLE_STL_WRAPPING = True
diff --git a/memory/replace/jemalloc/pthread_atfork.c b/memory/replace/jemalloc/pthread_atfork.c
deleted file mode 100644
index 6e737f072..000000000
--- a/memory/replace/jemalloc/pthread_atfork.c
+++ /dev/null
@@ -1,10 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-int pthread_atfork(void (*prefork)(void),
- void (*postfork_parent)(void),
- void (*postfork_child)(void))
-{
- return 0;
-}
diff --git a/memory/replace/logalloc/replay/Replay.cpp b/memory/replace/logalloc/replay/Replay.cpp
index 30fcd21e5..0ae20de2c 100644
--- a/memory/replace/logalloc/replay/Replay.cpp
+++ b/memory/replace/logalloc/replay/Replay.cpp
@@ -286,7 +286,7 @@ MOZ_BEGIN_EXTERN_C
/* mozjemalloc relies on DllMain to initialize, but DllMain is not invoked
* for executables, so manually invoke mozjemalloc initialization. */
-#if defined(_WIN32) && !defined(MOZ_JEMALLOC4)
+#if defined(_WIN32)
void malloc_init_hard(void);
#endif
@@ -475,7 +475,7 @@ main()
FdReader reader(0);
Replay replay;
-#if defined(_WIN32) && !defined(MOZ_JEMALLOC4)
+#if defined(_WIN32)
malloc_init_hard();
#endif
diff --git a/memory/replace/moz.build b/memory/replace/moz.build
index 111b8456b..e850637cb 100644
--- a/memory/replace/moz.build
+++ b/memory/replace/moz.build
@@ -9,10 +9,6 @@ DIRS += [
'replace',
]
-# Build jemalloc3 as a replace-malloc lib when building with mozjemalloc
-if not CONFIG['MOZ_JEMALLOC4']:
- DIRS += ['jemalloc']
-
if CONFIG['MOZ_REPLACE_MALLOC_LINKAGE'] == 'dummy library':
DIRS += ['dummy']
diff --git a/memory/volatile/tests/TestVolatileBuffer.cpp b/memory/volatile/tests/TestVolatileBuffer.cpp
index 9a4a8781d..dff8e794a 100644
--- a/memory/volatile/tests/TestVolatileBuffer.cpp
+++ b/memory/volatile/tests/TestVolatileBuffer.cpp
@@ -68,14 +68,7 @@ TEST(VolatileBufferTest, RealVolatileBuffersWork)
}
// Test purging if we know how to
-#if defined(MOZ_WIDGET_GONK)
- // This also works on Android, but we need root.
- int fd = open("/" ASHMEM_NAME_DEF, O_RDWR);
-
- ASSERT_GE(fd, 0) << "Failed to open ashmem device";
- ASSERT_GE(ioctl(fd, ASHMEM_PURGE_ALL_CACHES, NULL), 0)
- << "Failed to purge ashmem caches";
-#elif defined(XP_DARWIN)
+#if defined(XP_DARWIN)
int state;
vm_purgable_control(mach_task_self(), (vm_address_t)NULL,
VM_PURGABLE_PURGE_ALL, &state);
diff --git a/mfbt/TextUtils.h b/mfbt/TextUtils.h
new file mode 100644
index 000000000..9494296ce
--- /dev/null
+++ b/mfbt/TextUtils.h
@@ -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/. */
+
+/* Character/text operations. */
+
+#ifndef mozilla_TextUtils_h
+#define mozilla_TextUtils_h
+
+#include "mozilla/TypeTraits.h"
+
+namespace mozilla {
+
+namespace detail {
+
+template<typename Char>
+class MakeUnsignedChar
+ : public MakeUnsigned<Char>
+{};
+
+template<>
+class MakeUnsignedChar<char16_t>
+{
+public:
+ using Type = char16_t;
+};
+
+template<>
+class MakeUnsignedChar<char32_t>
+{
+public:
+ using Type = char32_t;
+};
+
+} // namespace detail
+
+/**
+ * Returns true iff |aChar| matches [a-zA-Z].
+ *
+ * This function is basically what you thought isalpha was, except its behavior
+ * doesn't depend on the user's current locale.
+ */
+template<typename Char>
+constexpr bool
+IsAsciiAlpha(Char aChar)
+{
+ using UnsignedChar = typename detail::MakeUnsignedChar<Char>::Type;
+ return ('a' <= static_cast<UnsignedChar>(aChar) &&
+ static_cast<UnsignedChar>(aChar) <= 'z') ||
+ ('A' <= static_cast<UnsignedChar>(aChar) &&
+ static_cast<UnsignedChar>(aChar) <= 'Z');
+}
+
+} // namespace mozilla
+
+#endif /* mozilla_TextUtils_h */
diff --git a/mfbt/moz.build b/mfbt/moz.build
index f23a3b6f5..897a686f4 100644
--- a/mfbt/moz.build
+++ b/mfbt/moz.build
@@ -87,6 +87,7 @@ EXPORTS.mozilla = [
'StaticAnalysisFunctions.h',
'TaggedAnonymousMemory.h',
'TemplateLib.h',
+ 'TextUtils.h',
'ThreadLocal.h',
'ToString.h',
'Tuple.h',
diff --git a/mfbt/tests/TestTextUtils.cpp b/mfbt/tests/TestTextUtils.cpp
new file mode 100644
index 000000000..db481c138
--- /dev/null
+++ b/mfbt/tests/TestTextUtils.cpp
@@ -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/. */
+
+#include "mozilla/Assertions.h"
+#include "mozilla/TextUtils.h"
+
+using mozilla::IsAsciiAlpha;
+
+// char
+
+static_assert(!IsAsciiAlpha('@'), "'@' isn't ASCII alpha");
+static_assert('@' == 0x40, "'@' has value 0x40");
+
+static_assert('A' == 0x41, "'A' has value 0x41");
+static_assert(IsAsciiAlpha('A'), "'A' is ASCII alpha");
+static_assert(IsAsciiAlpha('B'), "'B' is ASCII alpha");
+static_assert(IsAsciiAlpha('M'), "'M' is ASCII alpha");
+static_assert(IsAsciiAlpha('Y'), "'Y' is ASCII alpha");
+static_assert(IsAsciiAlpha('Z'), "'Z' is ASCII alpha");
+
+static_assert('Z' == 0x5A, "'Z' has value 0x5A");
+static_assert('[' == 0x5B, "'[' has value 0x5B");
+static_assert(!IsAsciiAlpha('['), "'[' isn't ASCII alpha");
+
+static_assert(!IsAsciiAlpha('`'), "'`' isn't ASCII alpha");
+static_assert('`' == 0x60, "'`' has value 0x60");
+
+static_assert('a' == 0x61, "'a' has value 0x61");
+static_assert(IsAsciiAlpha('a'), "'a' is ASCII alpha");
+static_assert(IsAsciiAlpha('b'), "'b' is ASCII alpha");
+static_assert(IsAsciiAlpha('m'), "'m' is ASCII alpha");
+static_assert(IsAsciiAlpha('y'), "'y' is ASCII alpha");
+static_assert(IsAsciiAlpha('z'), "'z' is ASCII alpha");
+
+static_assert('z' == 0x7A, "'z' has value 0x7A");
+static_assert('{' == 0x7B, "'{' has value 0x7B");
+static_assert(!IsAsciiAlpha('{'), "'{' isn't ASCII alpha");
+
+// char16_t
+
+static_assert(!IsAsciiAlpha(u'@'), "u'@' isn't ASCII alpha");
+static_assert(u'@' == 0x40, "u'@' has value 0x40");
+
+static_assert(u'A' == 0x41, "u'A' has value 0x41");
+static_assert(IsAsciiAlpha(u'A'), "u'A' is ASCII alpha");
+static_assert(IsAsciiAlpha(u'B'), "u'B' is ASCII alpha");
+static_assert(IsAsciiAlpha(u'M'), "u'M' is ASCII alpha");
+static_assert(IsAsciiAlpha(u'Y'), "u'Y' is ASCII alpha");
+static_assert(IsAsciiAlpha(u'Z'), "u'Z' is ASCII alpha");
+
+static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A");
+static_assert(u'[' == 0x5B, "u'[' has value 0x5B");
+static_assert(!IsAsciiAlpha(u'['), "u'[' isn't ASCII alpha");
+
+static_assert(!IsAsciiAlpha(u'`'), "u'`' isn't ASCII alpha");
+static_assert(u'`' == 0x60, "u'`' has value 0x60");
+
+static_assert(u'a' == 0x61, "u'a' has value 0x61");
+static_assert(IsAsciiAlpha(u'a'), "u'a' is ASCII alpha");
+static_assert(IsAsciiAlpha(u'b'), "u'b' is ASCII alpha");
+static_assert(IsAsciiAlpha(u'm'), "u'm' is ASCII alpha");
+static_assert(IsAsciiAlpha(u'y'), "u'y' is ASCII alpha");
+static_assert(IsAsciiAlpha(u'z'), "u'z' is ASCII alpha");
+
+static_assert(u'z' == 0x7A, "u'z' has value 0x7A");
+static_assert(u'{' == 0x7B, "u'{' has value 0x7B");
+static_assert(!IsAsciiAlpha(u'{'), "u'{' isn't ASCII alpha");
+
+// char32_t
+
+static_assert(!IsAsciiAlpha(U'@'), "U'@' isn't ASCII alpha");
+static_assert(U'@' == 0x40, "U'@' has value 0x40");
+
+static_assert(U'A' == 0x41, "U'A' has value 0x41");
+static_assert(IsAsciiAlpha(U'A'), "U'A' is ASCII alpha");
+static_assert(IsAsciiAlpha(U'B'), "U'B' is ASCII alpha");
+static_assert(IsAsciiAlpha(U'M'), "U'M' is ASCII alpha");
+static_assert(IsAsciiAlpha(U'Y'), "U'Y' is ASCII alpha");
+static_assert(IsAsciiAlpha(U'Z'), "U'Z' is ASCII alpha");
+
+static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A");
+static_assert(U'[' == 0x5B, "U'[' has value 0x5B");
+static_assert(!IsAsciiAlpha(U'['), "U'[' isn't ASCII alpha");
+
+static_assert(!IsAsciiAlpha(U'`'), "U'`' isn't ASCII alpha");
+static_assert(U'`' == 0x60, "U'`' has value 0x60");
+
+static_assert(U'a' == 0x61, "U'a' has value 0x61");
+static_assert(IsAsciiAlpha(U'a'), "U'a' is ASCII alpha");
+static_assert(IsAsciiAlpha(U'b'), "U'b' is ASCII alpha");
+static_assert(IsAsciiAlpha(U'm'), "U'm' is ASCII alpha");
+static_assert(IsAsciiAlpha(U'y'), "U'y' is ASCII alpha");
+static_assert(IsAsciiAlpha(U'z'), "U'z' is ASCII alpha");
+
+static_assert(U'z' == 0x7A, "U'z' has value 0x7A");
+static_assert(U'{' == 0x7B, "U'{' has value 0x7B");
+static_assert(!IsAsciiAlpha(U'{'), "U'{' isn't ASCII alpha");
+
+int
+main()
+{
+ return 0;
+}
diff --git a/mfbt/tests/moz.build b/mfbt/tests/moz.build
index f96117e03..bd25ab1d0 100644
--- a/mfbt/tests/moz.build
+++ b/mfbt/tests/moz.build
@@ -42,6 +42,7 @@ CppUnitTests([
'TestSHA1',
'TestSplayTree',
'TestTemplateLib',
+ 'TestTextUtils',
'TestTuple',
'TestTypedEnum',
'TestTypeTraits',
diff --git a/mobile/android/chrome/content/InputWidgetHelper.js b/mobile/android/chrome/content/InputWidgetHelper.js
index 9c753bd7b..cf66a263e 100644
--- a/mobile/android/chrome/content/InputWidgetHelper.js
+++ b/mobile/android/chrome/content/InputWidgetHelper.js
@@ -63,7 +63,7 @@ var InputWidgetHelper = {
},
hasInputWidget: function(aElement) {
- if (!aElement instanceof HTMLInputElement)
+ if (!(aElement instanceof HTMLInputElement))
return false;
let type = aElement.getAttribute('type');
diff --git a/mobile/android/installer/package-manifest.in b/mobile/android/installer/package-manifest.in
index 086138d47..067f9dde1 100644
--- a/mobile/android/installer/package-manifest.in
+++ b/mobile/android/installer/package-manifest.in
@@ -502,11 +502,6 @@
;
@BINPATH@/components/pipnss.xpt
-; For process sandboxing
-#if defined(MOZ_SANDBOX)
-@BINPATH@/@DLL_PREFIX@mozsandbox@DLL_SUFFIX@
-#endif
-
[mobile]
@BINPATH@/chrome/chrome@JAREXT@
@BINPATH@/chrome/chrome.manifest
diff --git a/modules/libpref/Preferences.cpp b/modules/libpref/Preferences.cpp
index f36819236..31867ca0a 100644
--- a/modules/libpref/Preferences.cpp
+++ b/modules/libpref/Preferences.cpp
@@ -466,9 +466,7 @@ Preferences::IsServiceAvailable()
bool
Preferences::InitStaticMembers()
{
-#ifndef MOZ_B2G
MOZ_ASSERT(NS_IsMainThread());
-#endif
if (!sShutdown && !sPreferences) {
nsCOMPtr<nsIPrefService> prefService =
diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js
index 903665ff8..a1016a820 100644
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -183,6 +183,9 @@ pref("dom.enable_resource_timing", true);
// Enable high-resolution timing markers for users
pref("dom.enable_user_timing", true);
+// Whether performance.GetEntries* will contain an entry for the active document
+pref("dom.enable_performance_navigation_timing", true);
+
// Enable printing performance marks/measures to log
pref("dom.performance.enable_user_timing_logging", false);
@@ -192,6 +195,9 @@ pref("dom.performance.enable_notify_performance_timing", false);
// Enable Permission API's .revoke() method
pref("dom.permissions.revoke.enable", false);
+// Enable exposing timeToNonBlankPaint
+pref("dom.performance.time_to_non_blank_paint.enabled", false);
+
// Enable Performance Observer API
#ifdef NIGHTLY_BUILD
pref("dom.enable_performance_observer", true);
@@ -445,20 +451,6 @@ pref("media.webrtc.debug.aec_log_dir", "");
pref("media.webrtc.debug.log_file", "");
pref("media.webrtc.debug.aec_dump_max_size", 4194304); // 4MB
-#ifdef MOZ_WIDGET_GONK
-pref("media.navigator.video.default_width", 320);
-pref("media.navigator.video.default_height", 240);
-pref("media.peerconnection.enabled", true);
-pref("media.peerconnection.video.enabled", true);
-pref("media.navigator.video.max_fs", 1200); // 640x480 == 1200mb
-pref("media.navigator.video.max_fr", 30);
-pref("media.navigator.video.h264.level", 12); // 0x42E00C - level 1.2
-pref("media.navigator.video.h264.max_br", 700); // 8x10
-pref("media.navigator.video.h264.max_mbps", 11880); // CIF@30fps
-pref("media.peerconnection.video.h264_enabled", false);
-pref("media.peerconnection.video.vp9_enabled", false);
-pref("media.getusermedia.aec", 4);
-#else
pref("media.navigator.video.default_width",0); // adaptive default
pref("media.navigator.video.default_height",0); // adaptive default
pref("media.peerconnection.enabled", true);
@@ -472,9 +464,7 @@ pref("media.peerconnection.video.h264_enabled", false);
pref("media.peerconnection.video.vp9_enabled", true);
pref("media.getusermedia.aec", 1);
pref("media.getusermedia.browser.enabled", true);
-#endif
-// Gonk typically captures at QVGA, and so min resolution is QQVGA or
-// 160x120; 100Kbps is plenty for that.
+
// Desktop is typically VGA capture or more; and qm_select will not drop resolution
// below 1/2 in each dimension (or so), so QVGA (320x200) is the lowest here usually.
pref("media.peerconnection.video.min_bitrate", 0);
@@ -574,7 +564,7 @@ pref("media.mediasource.enabled", true);
pref("media.mediasource.mp4.enabled", true);
-#if defined(XP_WIN) || defined(XP_MACOSX) || defined(MOZ_WIDGET_GONK) || defined(MOZ_WIDGET_ANDROID)
+#if defined(XP_WIN) || defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID)
pref("media.mediasource.webm.enabled", false);
#else
pref("media.mediasource.webm.enabled", true);
@@ -694,7 +684,7 @@ pref("apz.y_stationary_size_multiplier", "3.5");
pref("apz.zoom_animation_duration_ms", 250);
pref("apz.scale_repaint_delay_ms", 500);
-#if defined(MOZ_WIDGET_GONK) || defined(MOZ_WIDGET_ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
// Mobile prefs
pref("apz.allow_zooming", true);
pref("apz.enlarge_displayport_when_clipped", true);
@@ -710,7 +700,7 @@ pref("apz.y_stationary_size_multiplier", "1.5");
pref("gfx.hidpi.enabled", 2);
#endif
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
// Use containerless scrolling for now on desktop.
pref("layout.scroll.root-frame-containers", false);
#endif
@@ -1254,7 +1244,7 @@ pref("javascript.options.wasm", false);
pref("javascript.options.wasm_baselinejit", false);
pref("javascript.options.native_regexp", true);
pref("javascript.options.parallel_parsing", true);
-#if !defined(RELEASE_OR_BETA) && !defined(ANDROID) && !defined(MOZ_B2G) && !defined(XP_IOS)
+#if !defined(RELEASE_OR_BETA) && !defined(ANDROID) && !defined(XP_IOS)
pref("javascript.options.asyncstack", true);
#else
pref("javascript.options.asyncstack", false);
@@ -2040,7 +2030,7 @@ pref("intl.accept_languages", "chrome://global/locale/intl.propert
pref("intl.menuitems.alwaysappendaccesskeys","chrome://global/locale/intl.properties");
pref("intl.menuitems.insertseparatorbeforeaccesskeys","chrome://global/locale/intl.properties");
pref("intl.charset.detector", "chrome://global/locale/intl.properties");
-pref("intl.charset.fallback.override", "");
+pref("intl.charset.fallback.override", "*"); // '*' to make sure the UI selects the proper entry for 'auto'
pref("intl.charset.fallback.tld", true);
pref("intl.ellipsis", "chrome://global-platform/locale/intl.properties");
pref("intl.locale.matchOS", false);
@@ -2138,14 +2128,6 @@ pref("font.name.monospace.x-math", "monospace");
// These fonts are ignored the underline offset, instead of it, the underline is lowered to bottom of its em descent.
pref("font.blacklist.underline_offset", "FangSong,Gulim,GulimChe,MingLiU,MingLiU-ExtB,MingLiU_HKSCS,MingLiU-HKSCS-ExtB,MS Gothic,MS Mincho,MS PGothic,MS PMincho,MS UI Gothic,PMingLiU,PMingLiU-ExtB,SimHei,SimSun,SimSun-ExtB,Hei,Kai,Apple LiGothic,Apple LiSung,Osaka");
-#ifdef MOZ_B2G
-// Whitelist of fonts that ship with B2G that do not include space lookups in
-// default features. This allows us to skip analyzing the GSUB/GPOS tables
-// unless features are explicitly enabled.
-// Use NSPR_LOG_MODULES=fontinit:5 to dump out details of space lookups
-pref("font.whitelist.skip_default_features_space_check", "Fira Sans,Fira Mono");
-#endif
-
pref("images.dither", "auto");
pref("security.directory", "");
@@ -2510,9 +2492,12 @@ pref("layout.css.convertFromNode.enabled", true);
// Is support for CSS "text-align: unsafe X" enabled?
pref("layout.css.text-align-unsafe-value.enabled", false);
+// Is support for CSS text-justify property enabled?
+pref("layout.css.text-justify.enabled", true);
+
// Is support for CSS "float: inline-{start,end}" and
// "clear: inline-{start,end}" enabled?
-#if defined(MOZ_B2G) || !defined(RELEASE_OR_BETA)
+#if !defined(RELEASE_OR_BETA)
pref("layout.css.float-logical-values.enabled", true);
#else
pref("layout.css.float-logical-values.enabled", false);
@@ -3162,6 +3147,10 @@ pref("ui.mouse.radius.inputSource.touchOnly", true);
#ifdef XP_WIN
+// Be as uniform as possible, use Twemoji everywhere.
+// Optional: prefix with `Segoe UI Emoji` to use Win8+ Segoe UI font emoji where available.
+pref("font.name-list.emoji", "Twemoji Mozilla");
+
pref("font.name.serif.ar", "Times New Roman");
pref("font.name.sans-serif.ar", "Segoe UI");
pref("font.name-list.sans-serif.ar", "Segoe UI, Tahoma, Arial");
@@ -3587,6 +3576,8 @@ pref("ui.osk.debug.keyboardDisplayReason", "");
pref("browser.drag_out_of_frame_style", 1);
pref("ui.key.saveLink.shift", false); // true = shift, false = meta
+pref("font.name-list.emoji", "Apple Color Emoji");
+
// default fonts (in UTF8 and using canonical names)
// to determine canonical font names, use a debug build and
// enable NSPR logging for module fontInfoLog:5
@@ -4009,6 +4000,10 @@ pref("print.print_extra_margin", 0); // twips
// font names
+// fontconfig doesn't support emoji yet
+// https://lists.freedesktop.org/archives/fontconfig/2016-October/005842.html
+pref("font.name-list.emoji", "Twemoji Mozilla");
+
pref("font.name.serif.ar", "serif");
pref("font.name.sans-serif.ar", "sans-serif");
pref("font.name.monospace.ar", "monospace");
@@ -4166,7 +4161,7 @@ pref("gfx.font_rendering.fontconfig.max_generic_substitutions", 3);
#endif
#endif
-#if defined(ANDROID) || defined(MOZ_B2G)
+#if defined(ANDROID)
pref("font.size.fixed.ar", 12);
@@ -4184,75 +4179,14 @@ pref("font.size.fixed.x-unicode", 12);
pref("font.default.x-western", "sans-serif");
pref("font.size.fixed.x-western", 12);
-# ANDROID || MOZ_B2G
+# ANDROID
#endif
-#if defined(MOZ_B2G)
-// Gonk, FxOS Simulator, B2G Desktop and Mulet.
-
-// TODO: some entries could probably be cleaned up.
-
-// ar
-
-pref("font.name.serif.el", "Droid Serif"); // not Charis SIL Compact, only has a few Greek chars
-pref("font.name.sans-serif.el", "Fira Sans");
-pref("font.name.monospace.el", "Fira Mono");
-
-pref("font.name.serif.he", "Charis SIL Compact");
-pref("font.name.sans-serif.he", "Fira Sans");
-pref("font.name.monospace.he", "Fira Mono");
-pref("font.name-list.sans-serif.he", "Droid Sans Hebrew, Fira Sans");
-
-pref("font.name.serif.ja", "Charis SIL Compact");
-pref("font.name.sans-serif.ja", "Fira Sans");
-pref("font.name.monospace.ja", "MotoyaLMaru");
-pref("font.name-list.sans-serif.ja", "Fira Sans, MotoyaLMaru, MotoyaLCedar, Droid Sans Japanese");
-pref("font.name-list.monospace.ja", "MotoyaLMaru, MotoyaLCedar, Fira Mono");
-
-pref("font.name.serif.ko", "Charis SIL Compact");
-pref("font.name.sans-serif.ko", "Fira Sans");
-pref("font.name.monospace.ko", "Fira Mono");
-
-pref("font.name.serif.th", "Charis SIL Compact");
-pref("font.name.sans-serif.th", "Fira Sans");
-pref("font.name.monospace.th", "Fira Mono");
-pref("font.name-list.sans-serif.th", "Fira Sans, Noto Sans Thai, Droid Sans Thai");
-
-pref("font.name.serif.x-cyrillic", "Charis SIL Compact");
-pref("font.name.sans-serif.x-cyrillic", "Fira Sans");
-pref("font.name.monospace.x-cyrillic", "Fira Mono");
-
-pref("font.name.serif.x-unicode", "Charis SIL Compact");
-pref("font.name.sans-serif.x-unicode", "Fira Sans");
-pref("font.name.monospace.x-unicode", "Fira Mono");
-
-pref("font.name.serif.x-western", "Charis SIL Compact");
-pref("font.name.sans-serif.x-western", "Fira Sans");
-pref("font.name.monospace.x-western", "Fira Mono");
-
-pref("font.name.serif.zh-CN", "Charis SIL Compact");
-pref("font.name.sans-serif.zh-CN", "Fira Sans");
-pref("font.name.monospace.zh-CN", "Fira Mono");
-pref("font.name-list.sans-serif.zh-CN", "Fira Sans,Droid Sans Fallback");
-
-pref("font.name.serif.zh-HK", "Charis SIL Compact");
-pref("font.name.sans-serif.zh-HK", "Fira Sans");
-pref("font.name.monospace.zh-HK", "Fira Mono");
-pref("font.name-list.sans-serif.zh-HK", "Fira Sans,Droid Sans Fallback");
-
-pref("font.name.serif.zh-TW", "Charis SIL Compact");
-pref("font.name.sans-serif.zh-TW", "Fira Sans");
-pref("font.name.monospace.zh-TW", "Fira Mono");
-pref("font.name-list.sans-serif.zh-TW", "Fira Sans,Droid Sans Fallback");
-
-pref("font.name.serif.x-math", "Latin Modern Math");
-pref("font.name-list.serif.x-math", "Latin Modern Math, XITS Math, Cambria Math, Libertinus Math, DejaVu Math TeX Gyre, TeX Gyre Bonum Math, TeX Gyre Pagella Math, TeX Gyre Schola, TeX Gyre Termes Math, STIX Math, Asana Math, STIXGeneral, DejaVu Serif, DejaVu Sans, Charis SIL Compact");
-pref("font.name.sans-serif.x-math", "Fira Sans");
-pref("font.name.monospace.x-math", "Fira Mono");
-
-#elif defined(ANDROID)
+#if defined(ANDROID)
// We use the bundled fonts for Firefox for Android
+pref("font.name-list.emoji", "Noto Color Emoji");
+
// ar
pref("font.name.serif.el", "Droid Serif"); // not Charis SIL Compact, only has a few Greek chars
@@ -4519,10 +4453,6 @@ pref("webgl.dxgl.needs-finish", false);
pref("gfx.offscreencanvas.enabled", false);
-#ifdef MOZ_WIDGET_GONK
-pref("gfx.gralloc.fence-with-readpixels", false);
-#endif
-
// Stagefright prefs
pref("stagefright.force-enabled", false);
pref("stagefright.disabled", false);
@@ -4574,7 +4504,7 @@ pref("layers.acceleration.force-enabled", false);
pref("layers.acceleration.draw-fps", false);
// Enable DEAA antialiasing for transformed layers in the compositor
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
// Desktop prefs
pref("layers.deaa.enabled", true);
#else
@@ -4650,7 +4580,7 @@ pref("gfx.apitrace.enabled",false);
#ifdef MOZ_X11
pref("gfx.content.use-native-pushlayer", true);
#ifdef MOZ_WIDGET_GTK
-pref("gfx.xrender.enabled",false);
+pref("gfx.xrender.enabled", true);
#endif
#endif
@@ -4878,7 +4808,7 @@ pref("layout.css.expensive-style-struct-assertions.enabled", false);
// enable JS dump() function.
pref("browser.dom.window.dump.enabled", false);
-#if defined(MOZ_WIDGET_GONK) || defined(MOZ_WIDGET_ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
// Network Information API
pref("dom.netinfo.enabled", true);
#else
@@ -5242,15 +5172,6 @@ pref("camera.control.face_detection.enabled", true);
// SW Cache API
pref("dom.caches.enabled", true);
-#ifdef MOZ_WIDGET_GONK
-// Empirically, this is the value returned by hal::GetTotalSystemMemory()
-// when Flame's memory is limited to 512MiB. If the camera stack determines
-// it is running on a low memory platform, features that can be reliably
-// supported will be disabled. This threshold can be adjusted to suit other
-// platforms; and set to 0 to disable the low-memory check altogether.
-pref("camera.control.low_memory_thresholdMB", 404);
-#endif
-
// SystemUpdate API
pref("dom.system_update.enabled", false);
pref("dom.system_update.debug", false);
@@ -5330,7 +5251,6 @@ pref("browser.search.geoip.timeout", 3000);
pref("browser.search.official", true);
#endif
-#ifndef MOZ_WIDGET_GONK
// GMPInstallManager prefs
// User-settable override to media.gmp-manager.url for testing purposes.
@@ -5366,7 +5286,6 @@ pref("media.gmp-manager.certs.1.issuerName", "CN=DigiCert SHA2 Secure Server CA,
pref("media.gmp-manager.certs.1.commonName", "aus5.mozilla.org");
pref("media.gmp-manager.certs.2.issuerName", "CN=thawte SSL CA - G2,O=\"thawte, Inc.\",C=US");
pref("media.gmp-manager.certs.2.commonName", "aus5.mozilla.org");
-#endif
// Whether or not to perform reader mode article parsing on page load.
// If this pref is disabled, we will never show a reader mode icon in the toolbar.
@@ -5423,13 +5342,6 @@ pref("narrate.voice", " { \"default\": \"automatic\" }");
// Only make voices that match content language available.
pref("narrate.filter-voices", true);
-#if defined(XP_LINUX) && defined(MOZ_GMP_SANDBOX)
-// Whether to allow, on a Linux system that doesn't support the necessary sandboxing
-// features, loading Gecko Media Plugins unsandboxed. However, EME CDMs will not be
-// loaded without sandboxing even if this pref is changed.
-pref("media.gmp.insecure.allow", false);
-#endif
-
pref("dom.audiochannel.mutedByDefault", false);
// Enable <details> and <summary> tags.
@@ -5447,15 +5359,8 @@ pref("dom.secureelement.enabled", false);
// and compositionend events.
pref("dom.compositionevent.allow_control_characters", false);
-#ifdef MOZ_WIDGET_GONK
-// Bug 1154053: Serialize B2G memory reports; smaller devices are
-// usually overcommitted on memory by using zRAM, so memory reporting
-// causes memory pressure from uncompressing cold heap memory.
-pref("memory.report_concurrency", 1);
-#else
-// Desktop probably doesn't have swapped-out children like that.
+// Desktop probably doesn't have swapped-out children.
pref("memory.report_concurrency", 10);
-#endif
// Add Mozilla AudioChannel APIs.
pref("media.useAudioChannelAPI", false);
@@ -5524,7 +5429,7 @@ pref("dom.maxHardwareConcurrency", 16);
pref("osfile.reset_worker_delay", 30000);
#endif
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
pref("dom.webkitBlink.dirPicker.enabled", true);
pref("dom.webkitBlink.filesystem.enabled", true);
#endif
diff --git a/modules/libpref/prefapi.cpp b/modules/libpref/prefapi.cpp
index 046a69419..8aaf4077b 100644
--- a/modules/libpref/prefapi.cpp
+++ b/modules/libpref/prefapi.cpp
@@ -573,9 +573,7 @@ nsresult PREF_GetBoolPref(const char *pref_name, bool * return_value, bool get_d
nsresult
PREF_DeleteBranch(const char *branch_name)
{
-#ifndef MOZ_B2G
MOZ_ASSERT(NS_IsMainThread());
-#endif
int len = (int)strlen(branch_name);
@@ -636,9 +634,7 @@ PREF_ClearUserPref(const char *pref_name)
nsresult
PREF_ClearAllUserPrefs()
{
-#ifndef MOZ_B2G
MOZ_ASSERT(NS_IsMainThread());
-#endif
if (!gHashTable)
return NS_ERROR_NOT_INITIALIZED;
@@ -739,18 +735,14 @@ static PrefTypeFlags pref_SetValue(PrefValue* existingValue, PrefTypeFlags flags
PrefHashEntry* pref_HashTableLookup(const char *key)
{
-#ifndef MOZ_B2G
MOZ_ASSERT(NS_IsMainThread());
-#endif
return static_cast<PrefHashEntry*>(gHashTable->Search(key));
}
nsresult pref_HashPref(const char *key, PrefValue value, PrefType type, uint32_t flags)
{
-#ifndef MOZ_B2G
MOZ_ASSERT(NS_IsMainThread());
-#endif
if (!gHashTable)
return NS_ERROR_OUT_OF_MEMORY;
diff --git a/moz.configure b/moz.configure
index cecc1335e..64cdc8ac6 100644
--- a/moz.configure
+++ b/moz.configure
@@ -52,38 +52,6 @@ def compile_environment(compile_env):
set_config('COMPILE_ENVIRONMENT', compile_environment)
add_old_configure_assignment('COMPILE_ENVIRONMENT', compile_environment)
-js_option('--disable-tests',
- help='Do not build test libraries & programs')
-
-@depends('--disable-tests')
-def enable_tests(value):
- if value:
- return True
-
-set_config('ENABLE_TESTS', enable_tests)
-set_define('ENABLE_TESTS', enable_tests)
-
-@depends(enable_tests)
-def gtest_has_rtti(value):
- if value:
- return '0'
-
-set_define('GTEST_HAS_RTTI', gtest_has_rtti)
-
-@depends(target, enable_tests)
-def linux_gtest_defines(target, enable_tests):
- if enable_tests and target.os == 'Android':
- return namespace(os_linux_android=True,
- use_own_tr1_tuple=True,
- has_clone='0')
-
-set_define('GTEST_OS_LINUX_ANDROID',
- delayed_getattr(linux_gtest_defines, 'os_linux_android'))
-set_define('GTEST_USE_OWN_TR1_TUPLE',
- delayed_getattr(linux_gtest_defines, 'use_own_tr1_tuple'))
-set_define('GTEST_HAS_CLONE',
- delayed_getattr(linux_gtest_defines, 'has_clone'))
-
js_option('--enable-debug',
nargs='?',
help='Enable building with developer debug info '
diff --git a/mozglue/build/BionicGlue.cpp b/mozglue/build/BionicGlue.cpp
index 208fcce68..9277f1e76 100644
--- a/mozglue/build/BionicGlue.cpp
+++ b/mozglue/build/BionicGlue.cpp
@@ -64,22 +64,7 @@ private:
static std::vector<AtForkFuncs, SpecialAllocator<AtForkFuncs> > atfork;
#endif
-#ifdef MOZ_WIDGET_GONK
-#include "cpuacct.h"
-
-#if ANDROID_VERSION < 17 || defined(MOZ_WIDGET_ANDROID)
-extern "C" NS_EXPORT int
-timer_create(clockid_t, struct sigevent*, timer_t*)
-{
- __android_log_print(ANDROID_LOG_ERROR, "BionicGlue", "timer_create not supported!");
- abort();
- return -1;
-}
-#endif
-
-#else
#define cpuacct_add(x)
-#endif
#if ANDROID_VERSION < 17 || defined(MOZ_WIDGET_ANDROID)
extern "C" NS_EXPORT int
@@ -140,7 +125,6 @@ raise(int sig)
}
/* Flash plugin uses symbols that are not present in Android >= 4.4 */
-#ifndef MOZ_WIDGET_GONK
namespace android {
namespace VectorImpl {
NS_EXPORT void reservedVectorImpl1(void) { }
@@ -153,5 +137,4 @@ namespace android {
NS_EXPORT void reservedVectorImpl8(void) { }
}
}
-#endif
diff --git a/mozglue/build/cpuacct.c b/mozglue/build/cpuacct.c
deleted file mode 100644
index ce7d98eda..000000000
--- a/mozglue/build/cpuacct.c
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- * 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.
- *
- * 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.
- */
-#include <unistd.h>
-#include <errno.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include "cpuacct.h"
-
-int cpuacct_add(uid_t uid)
-{
- int count;
- int fd;
- char buf[80];
-
- count = snprintf(buf, sizeof(buf), "/acct/uid/%d/tasks", uid);
- fd = open(buf, O_RDWR|O_CREAT|O_TRUNC|O_SYNC);
- if (fd < 0) {
- /* Note: sizeof("tasks") returns 6, which includes the NULL char */
- buf[count - sizeof("tasks")] = 0;
- if (mkdir(buf, 0775) < 0)
- return -errno;
-
- /* Note: sizeof("tasks") returns 6, which includes the NULL char */
- buf[count - sizeof("tasks")] = '/';
- fd = open(buf, O_RDWR|O_CREAT|O_TRUNC|O_SYNC);
- }
- if (fd < 0)
- return -errno;
-
- write(fd, "0", 2);
- if (close(fd))
- return -errno;
-
- return 0;
-}
diff --git a/mozglue/build/cpuacct.h b/mozglue/build/cpuacct.h
deleted file mode 100644
index 8e24c8cc8..000000000
--- a/mozglue/build/cpuacct.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- * 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.
- *
- * 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.
- */
-
-#ifndef _BIONIC_CPUACCT_H
-#define _BIONIC_CPUACCT_H
-
-#include <sys/cdefs.h>
-#include <sys/types.h>
-
-__BEGIN_DECLS
-
-extern int cpuacct_add(uid_t uid);
-
-__END_DECLS
-
-#endif /* _BIONIC_CPUACCT_H */
diff --git a/mozglue/build/moz.build b/mozglue/build/moz.build
index d28974778..b97bddcdc 100644
--- a/mozglue/build/moz.build
+++ b/mozglue/build/moz.build
@@ -32,7 +32,7 @@ if CONFIG['OS_TARGET'] == 'WINNT':
if not CONFIG['JS_STANDALONE']:
- if CONFIG['MOZ_MEMORY'] and (CONFIG['MOZ_SYSTEM_JEMALLOC'] or FORCE_SHARED_LIB):
+ if CONFIG['MOZ_MEMORY'] and FORCE_SHARED_LIB:
pass
# TODO: SHARED_LIBRARY_LIBS go here
else:
@@ -81,11 +81,6 @@ if not CONFIG['JS_STANDALONE']:
'zlib',
]
- if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- SOURCES += [
- 'cpuacct.c',
- ]
-
USE_LIBS += [
'mfbt',
]
diff --git a/mozglue/misc/TimeStamp.h b/mozglue/misc/TimeStamp.h
index a1a0eb360..6a4f0b810 100644
--- a/mozglue/misc/TimeStamp.h
+++ b/mozglue/misc/TimeStamp.h
@@ -216,10 +216,7 @@ public:
}
double operator/(const BaseTimeDuration& aOther) const
{
-#ifndef MOZ_B2G
- // Bug 1066388 - This fails on B2G ICS Emulator
MOZ_ASSERT(aOther.mValue != 0, "Division by zero");
-#endif
return ValueCalculator::DivideDouble(mValue, aOther.mValue);
}
BaseTimeDuration operator%(const BaseTimeDuration& aOther) const
@@ -403,11 +400,11 @@ public:
* retrieved by mozilla::TimeStamp. Since we need this for
* vsync timestamps, we enable the creation of mozilla::TimeStamps
* on platforms that support vsync aligned refresh drivers / compositors
- * Verified true as of Jan 31, 2015: B2G and OS X
+ * Verified true as of Jan 31, 2015: OS X
* False on Windows 7
* UNTESTED ON OTHER PLATFORMS
*/
-#if defined(MOZ_WIDGET_GONK) || defined(XP_DARWIN)
+#if defined(XP_DARWIN)
static TimeStamp FromSystemTime(int64_t aSystemTime)
{
static_assert(sizeof(aSystemTime) == sizeof(TimeStampValue),
diff --git a/netwerk/base/Tickler.h b/netwerk/base/Tickler.h
index 573fe6e76..63353a924 100644
--- a/netwerk/base/Tickler.h
+++ b/netwerk/base/Tickler.h
@@ -27,7 +27,7 @@
// The tickler only applies to wifi on mobile right now. Hopefully it
// can also be restricted to particular handset models in the future.
-#if defined(ANDROID) && !defined(MOZ_B2G)
+#if defined(ANDROID)
#define MOZ_USE_WIFI_TICKLER
#endif
diff --git a/netwerk/base/moz.build b/netwerk/base/moz.build
index 5de1eea81..3198d746c 100644
--- a/netwerk/base/moz.build
+++ b/netwerk/base/moz.build
@@ -182,11 +182,6 @@ EXPORTS.mozilla.net += [
'ReferrerPolicy.h',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- EXPORTS += [
- 'NetStatistics.h',
- ]
-
UNIFIED_SOURCES += [
'ArrayBufferInputStream.cpp',
'BackgroundFileSaver.cpp',
diff --git a/netwerk/base/nsINetworkInterceptController.idl b/netwerk/base/nsINetworkInterceptController.idl
index 17d27de42..721b7a334 100644
--- a/netwerk/base/nsINetworkInterceptController.idl
+++ b/netwerk/base/nsINetworkInterceptController.idl
@@ -14,12 +14,16 @@ interface nsIURI;
%{C++
#include "nsIConsoleReportCollector.h"
namespace mozilla {
+class TimeStamp;
+
namespace dom {
class ChannelInfo;
}
}
%}
+native TimeStamp(mozilla::TimeStamp);
+
[ptr] native ChannelInfo(mozilla::dom::ChannelInfo);
/**
@@ -97,6 +101,30 @@ interface nsIInterceptedChannel : nsISupports
[noscript]
readonly attribute nsIConsoleReportCollector consoleReportCollector;
+ /**
+ * Save the timestamps of various service worker interception phases.
+ */
+ [noscript]
+ void SetLaunchServiceWorkerStart(in TimeStamp aTimeStamp);
+
+ [noscript]
+ void SetLaunchServiceWorkerEnd(in TimeStamp aTimeStamp);
+
+ [noscript]
+ void SetDispatchFetchEventStart(in TimeStamp aTimeStamp);
+
+ [noscript]
+ void SetDispatchFetchEventEnd(in TimeStamp aTimeStamp);
+
+ [noscript]
+ void SetHandleFetchEventStart(in TimeStamp aTimeStamp);
+
+ [noscript]
+ void SetHandleFetchEventEnd(in TimeStamp aTimeStamp);
+
+ [noscript]
+ void SaveTimeStampsToUnderlyingChannel();
+
%{C++
already_AddRefed<nsIConsoleReportCollector>
GetConsoleReportCollector()
diff --git a/netwerk/base/nsIOService.cpp b/netwerk/base/nsIOService.cpp
index 8b7f31f99..e13541acf 100644
--- a/netwerk/base/nsIOService.cpp
+++ b/netwerk/base/nsIOService.cpp
@@ -59,11 +59,6 @@
#include "nsContentUtils.h"
#include "xpcpublic.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsINetworkManager.h"
-#include "nsINetworkInterface.h"
-#endif
-
namespace mozilla {
namespace net {
diff --git a/netwerk/base/nsITimedChannel.idl b/netwerk/base/nsITimedChannel.idl
index 13b65e7b8..83670a11e 100644
--- a/netwerk/base/nsITimedChannel.idl
+++ b/netwerk/base/nsITimedChannel.idl
@@ -21,7 +21,8 @@ interface nsITimedChannel : nsISupports {
attribute boolean timingEnabled;
// The number of redirects
- attribute uint16_t redirectCount;
+ attribute uint8_t redirectCount;
+ attribute uint8_t internalRedirectCount;
[noscript] readonly attribute TimeStamp channelCreation;
[noscript] readonly attribute TimeStamp asyncOpen;
@@ -37,6 +38,15 @@ interface nsITimedChannel : nsISupports {
[noscript] readonly attribute TimeStamp responseStart;
[noscript] readonly attribute TimeStamp responseEnd;
+ // The following are only set when the request is intercepted by a service
+ // worker no matter the response is synthesized.
+ [noscript] attribute TimeStamp launchServiceWorkerStart;
+ [noscript] attribute TimeStamp launchServiceWorkerEnd;
+ [noscript] attribute TimeStamp dispatchFetchEventStart;
+ [noscript] attribute TimeStamp dispatchFetchEventEnd;
+ [noscript] attribute TimeStamp handleFetchEventStart;
+ [noscript] attribute TimeStamp handleFetchEventEnd;
+
// The redirect attributes timings must be writeble, se we can transfer
// the data from one channel to the redirected channel.
[noscript] attribute TimeStamp redirectStart;
@@ -67,6 +77,12 @@ interface nsITimedChannel : nsISupports {
// All following are PRTime versions of the above.
readonly attribute PRTime channelCreationTime;
readonly attribute PRTime asyncOpenTime;
+ readonly attribute PRTime launchServiceWorkerStartTime;
+ readonly attribute PRTime launchServiceWorkerEndTime;
+ readonly attribute PRTime dispatchFetchEventStartTime;
+ readonly attribute PRTime dispatchFetchEventEndTime;
+ readonly attribute PRTime handleFetchEventStartTime;
+ readonly attribute PRTime handleFetchEventEndTime;
readonly attribute PRTime domainLookupStartTime;
readonly attribute PRTime domainLookupEndTime;
readonly attribute PRTime connectStartTime;
diff --git a/netwerk/base/nsIncrementalDownload.cpp b/netwerk/base/nsIncrementalDownload.cpp
index 42cd6faa5..47f7cb98b 100644
--- a/netwerk/base/nsIncrementalDownload.cpp
+++ b/netwerk/base/nsIncrementalDownload.cpp
@@ -49,27 +49,6 @@ WriteToFile(nsIFile *lf, const char *data, uint32_t len, int32_t flags)
PRFileDesc *fd;
int32_t mode = 0600;
nsresult rv;
-#if defined(MOZ_WIDGET_GONK)
- // The sdcard on a B2G phone looks like:
- // d---rwx--- system sdcard_rw 1970-01-01 01:00:00 sdcard
- // On the emulator, xpcshell fails when using 0600 mode to open the file,
- // and 0660 works.
- nsCOMPtr<nsIFile> parent;
- rv = lf->GetParent(getter_AddRefs(parent));
- if (NS_FAILED(rv)) {
- return rv;
- }
- uint32_t parentPerm;
- rv = parent->GetPermissions(&parentPerm);
- if (NS_FAILED(rv)) {
- return rv;
- }
- if ((parentPerm & 0700) == 0) {
- // Parent directory has no owner-write, so try to use group permissions
- // instead of owner permissions.
- mode = 0660;
- }
-#endif
rv = lf->OpenNSPRFileDesc(flags, mode, &fd);
if (NS_FAILED(rv))
return rv;
diff --git a/netwerk/base/nsNetUtil.cpp b/netwerk/base/nsNetUtil.cpp
index 8ff3e788f..d60c909c5 100644
--- a/netwerk/base/nsNetUtil.cpp
+++ b/netwerk/base/nsNetUtil.cpp
@@ -71,11 +71,6 @@
#include "nsHttpHandler.h"
#include "nsNSSComponent.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsINetworkManager.h"
-#include "nsThreadUtils.h" // for NS_IsMainThread
-#endif
-
#include <limits>
using namespace mozilla;
@@ -1285,16 +1280,10 @@ NS_HasBeenCrossOrigin(nsIChannel* aChannel, bool aReport)
nsCOMPtr<nsILoadInfo> loadInfo = aChannel->GetLoadInfo();
MOZ_RELEASE_ASSERT(loadInfo, "Origin tracking only works for channels created with a loadinfo");
-#ifdef DEBUG
- // Don't enforce TYPE_DOCUMENT assertions for loads
- // initiated by javascript tests.
- bool skipContentTypeCheck = false;
- skipContentTypeCheck = Preferences::GetBool("network.loadinfo.skip_type_assertion");
-#endif
-
- MOZ_ASSERT(skipContentTypeCheck ||
- loadInfo->GetExternalContentPolicyType() != nsIContentPolicy::TYPE_DOCUMENT,
- "calling NS_HasBeenCrossOrigin on a top level load");
+ // TYPE_DOCUMENT loads have a null LoadingPrincipal and can not be cross origin.
+ if (!loadInfo->LoadingPrincipal()) {
+ return false;
+ }
// Always treat tainted channels as cross-origin.
if (loadInfo->GetTainting() != LoadTainting::Basic) {
diff --git a/netwerk/base/nsUDPSocket.cpp b/netwerk/base/nsUDPSocket.cpp
index 84f6b8ea5..5973a205d 100644
--- a/netwerk/base/nsUDPSocket.cpp
+++ b/netwerk/base/nsUDPSocket.cpp
@@ -31,10 +31,6 @@
#include "nsIDNSService.h"
#include "nsICancelable.h"
-#ifdef MOZ_WIDGET_GONK
-#include "NetStatistics.h"
-#endif
-
namespace mozilla {
namespace net {
@@ -626,15 +622,6 @@ nsUDPSocket::InitWithAddress(const NetAddr *aAddr, nsIPrincipal *aPrincipal,
aPrincipal->GetIsInIsolatedMozBrowserElement();
}
-#ifdef MOZ_WIDGET_GONK
- if (mAppId != NECKO_UNKNOWN_APP_ID) {
- nsCOMPtr<nsINetworkInfo> activeNetworkInfo;
- GetActiveNetworkInfo(activeNetworkInfo);
- mActiveNetworkInfo =
- new nsMainThreadPtrHolder<nsINetworkInfo>(activeNetworkInfo);
- }
-#endif
-
uint16_t port;
if (NS_FAILED(net::GetPort(aAddr, &port))) {
NS_WARNING("invalid bind address");
@@ -770,29 +757,7 @@ nsUDPSocket::GetLocalAddr(nsINetAddr * *aResult)
void
nsUDPSocket::SaveNetworkStats(bool aEnforce)
{
-#ifdef MOZ_WIDGET_GONK
- if (!mActiveNetworkInfo || mAppId == NECKO_UNKNOWN_APP_ID) {
- return;
- }
-
- if (mByteReadCount == 0 && mByteWriteCount == 0) {
- return;
- }
-
- uint64_t total = mByteReadCount + mByteWriteCount;
- if (aEnforce || total > NETWORK_STATS_THRESHOLD) {
- // Create the event to save the network statistics.
- // the event is then dispathed to the main thread.
- RefPtr<Runnable> event =
- new SaveNetworkStatsEvent(mAppId, mIsInIsolatedMozBrowserElement, mActiveNetworkInfo,
- mByteReadCount, mByteWriteCount, false);
- NS_DispatchToMainThread(event);
-
- // Reset the counters after saving.
- mByteReadCount = 0;
- mByteWriteCount = 0;
- }
-#endif
+ /*** STUB ***/
}
void
diff --git a/netwerk/base/nsUDPSocket.h b/netwerk/base/nsUDPSocket.h
index 4ddff4248..f8ae87cee 100644
--- a/netwerk/base/nsUDPSocket.h
+++ b/netwerk/base/nsUDPSocket.h
@@ -12,11 +12,6 @@
#include "nsAutoPtr.h"
#include "nsCycleCollectionParticipant.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsINetworkInterface.h"
-#include "nsProxyRelease.h"
-#endif
-
//-----------------------------------------------------------------------------
namespace mozilla {
@@ -76,9 +71,6 @@ private:
uint64_t mByteReadCount;
uint64_t mByteWriteCount;
-#ifdef MOZ_WIDGET_GONK
- nsMainThreadPtrHandle<nsINetworkInfo> mActiveNetworkInfo;
-#endif
};
//-----------------------------------------------------------------------------
diff --git a/netwerk/dns/mdns/libmdns/moz.build b/netwerk/dns/mdns/libmdns/moz.build
index d2dca4955..efad64d64 100644
--- a/netwerk/dns/mdns/libmdns/moz.build
+++ b/netwerk/dns/mdns/libmdns/moz.build
@@ -4,8 +4,7 @@
# License, v. 2.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'] == 'cocoa' or \
- (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and CONFIG['ANDROID_VERSION'] >= '16'):
+if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
UNIFIED_SOURCES += [
'MDNSResponderOperator.cpp',
'MDNSResponderReply.cpp',
@@ -16,13 +15,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa' or \
'/netwerk/base',
]
- if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- LOCAL_INCLUDES += [
- '%' + '%s/%s' % (CONFIG['ANDROID_SOURCE'], d) for d in [
- 'external/mdnsresponder/mDNSShared',
- ]
- ]
-
else:
EXTRA_COMPONENTS += [
'nsDNSServiceDiscovery.js',
diff --git a/netwerk/dns/mdns/libmdns/nsDNSServiceDiscovery.cpp b/netwerk/dns/mdns/libmdns/nsDNSServiceDiscovery.cpp
index 8ffa74b71..cec8033d1 100644
--- a/netwerk/dns/mdns/libmdns/nsDNSServiceDiscovery.cpp
+++ b/netwerk/dns/mdns/libmdns/nsDNSServiceDiscovery.cpp
@@ -9,10 +9,6 @@
#include "nsXULAppAPI.h"
#include "private/pprio.h"
-#ifdef MOZ_WIDGET_GONK
-#include <cutils/properties.h>
-#endif // MOZ_WIDGET_GONK
-
namespace mozilla {
namespace net {
@@ -21,29 +17,13 @@ namespace {
inline void
StartService()
{
-#ifdef MOZ_WIDGET_GONK
- char value[PROPERTY_VALUE_MAX] = { '\0' };
- property_get("init.svc.mdnsd", value, "");
-
- if (strcmp(value, "running") == 0) {
- return;
- }
- property_set("ctl.start", "mdnsd");
-#endif // MOZ_WIDGET_GONK
+ /*** STUB ***/
}
inline void
StopService()
{
-#ifdef MOZ_WIDGET_GONK
- char value[PROPERTY_VALUE_MAX] = { '\0' };
- property_get("init.svc.mdnsd", value, "");
-
- if (strcmp(value, "stopped") == 0) {
- return;
- }
- property_set("ctl.stop", "mdnsd");
-#endif // MOZ_WIDGET_GONK
+ /*** STUB ***/
}
class ServiceCounter
@@ -157,9 +137,6 @@ NS_IMPL_ISUPPORTS(nsDNSServiceDiscovery, nsIDNSServiceDiscovery)
nsDNSServiceDiscovery::~nsDNSServiceDiscovery()
{
-#ifdef MOZ_WIDGET_GONK
- StopService();
-#endif
}
nsresult
diff --git a/netwerk/dns/mdns/libmdns/nsMulticastDNSModule.cpp b/netwerk/dns/mdns/libmdns/nsMulticastDNSModule.cpp
index 22bad3bc7..aa1c973b5 100644
--- a/netwerk/dns/mdns/libmdns/nsMulticastDNSModule.cpp
+++ b/netwerk/dns/mdns/libmdns/nsMulticastDNSModule.cpp
@@ -3,7 +3,7 @@
* License, v. 2.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(MOZ_WIDGET_COCOA) || (defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 16)
+#if defined(MOZ_WIDGET_COCOA)
#define ENABLE_DNS_SERVICE_DISCOVERY
#endif
diff --git a/netwerk/dns/moz.build b/netwerk/dns/moz.build
index f788d9a33..c3b84df2f 100644
--- a/netwerk/dns/moz.build
+++ b/netwerk/dns/moz.build
@@ -66,13 +66,7 @@ LOCAL_INCLUDES += [
'/netwerk/base',
]
-if CONFIG['ENABLE_INTL_API']:
- DEFINES['IDNA2008'] = True
- USE_LIBS += ['icu']
-else:
- UNIFIED_SOURCES += [
- 'nameprep.c',
- ]
+USE_LIBS += ['icu']
if CONFIG['GNU_CXX']:
CXXFLAGS += ['-Wno-error=shadow']
diff --git a/netwerk/dns/nameprep.c b/netwerk/dns/nameprep.c
deleted file mode 100644
index 039797885..000000000
--- a/netwerk/dns/nameprep.c
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * Copyright (c) 2001,2002 Japan Network Information Center.
- * All rights reserved.
- *
- * By using this file, you agree to the terms and conditions set forth bellow.
- *
- * LICENSE TERMS AND CONDITIONS
- *
- * The following License Terms and Conditions apply, unless a different
- * license is obtained from Japan Network Information Center ("JPNIC"),
- * a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda,
- * Chiyoda-ku, Tokyo 101-0047, Japan.
- *
- * 1. Use, Modification and Redistribution (including distribution of any
- * modified or derived work) in source and/or binary forms is permitted
- * under this License Terms and Conditions.
- *
- * 2. Redistribution of source code must retain the copyright notices as they
- * appear in each source code file, this License Terms and Conditions.
- *
- * 3. Redistribution in binary form must reproduce the Copyright Notice,
- * this License Terms and Conditions, in the documentation and/or other
- * materials provided with the distribution. For the purposes of binary
- * distribution the "Copyright Notice" refers to the following language:
- * "Copyright (c) 2000-2002 Japan Network Information Center. All rights reserved."
- *
- * 4. The name of JPNIC may not be used to endorse or promote products
- * derived from this Software without specific prior written approval of
- * JPNIC.
- *
- * 5. Disclaimer/Limitation of Liability: THIS SOFTWARE IS PROVIDED BY JPNIC
- * "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 JPNIC 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 DAMAGES.
- */
-
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "nsIDNKitInterface.h"
-
-#define UCS_MAX 0x7fffffff
-#define UNICODE_MAX 0x10ffff
-
-
-/*
- * Load NAMEPREP compiled tables.
- */
-#include "nameprepdata.c"
-
-/*
- * Define mapping/checking functions for each version of the draft.
- */
-
-#define VERSION id11
-#include "nameprep_template.c"
-#undef VERSION
-
-typedef const char *(*nameprep_mapproc)(uint32_t v);
-typedef int (*nameprep_checkproc)(uint32_t v);
-typedef idn_biditype_t (*nameprep_biditypeproc)(uint32_t v);
-
-static struct idn_nameprep {
- char *version;
- nameprep_mapproc map_proc;
- nameprep_checkproc prohibited_proc;
- nameprep_checkproc unassigned_proc;
- nameprep_biditypeproc biditype_proc;
-} nameprep_versions[] = {
-#define MAKE_NAMEPREP_HANDLE(version, id) \
- { version, \
- compose_sym2(nameprep_map_, id), \
- compose_sym2(nameprep_prohibited_, id), \
- compose_sym2(nameprep_unassigned_, id), \
- compose_sym2(nameprep_biditype_, id), }
- MAKE_NAMEPREP_HANDLE("nameprep-11", id11),
- { NULL, NULL, NULL, NULL, NULL },
-};
-
-static idn_result_t idn_nameprep_check(nameprep_checkproc proc,
- const uint32_t *str,
- const uint32_t **found);
-
-idn_result_t
-idn_nameprep_create(const char *version, idn_nameprep_t *handlep) {
- idn_nameprep_t handle;
-
- assert(handlep != NULL);
-
- TRACE(("idn_nameprep_create(version=%-.50s)\n",
- version == NULL ? "<NULL>" : version));
-
- if (version == NULL)
- version = IDN_NAMEPREP_CURRENT;
-
- /*
- * Lookup table for the specified version. Since the number of
- * versions won't be large (I don't want see draft-23 or such :-),
- * simple linear search is OK.
- */
- for (handle = nameprep_versions; handle->version != NULL; handle++) {
- if (strcmp(handle->version, version) == 0) {
- *handlep = handle;
- return (idn_success);
- }
- }
- return (idn_notfound);
-}
-
-void
-idn_nameprep_destroy(idn_nameprep_t handle) {
- assert(handle != NULL);
-
- TRACE(("idn_nameprep_destroy()\n"));
-
- /* Nothing to do. */
-}
-
-idn_result_t
-idn_nameprep_map(idn_nameprep_t handle, const uint32_t *from,
- uint32_t *to, size_t tolen) {
- assert(handle != NULL && from != NULL && to != NULL);
-
- TRACE(("idn_nameprep_map(ctx=%s, from=\"%s\")\n",
- handle->version, idn__debug_ucs4xstring(from, 50)));
-
- while (*from != '\0') {
- uint32_t v = *from;
- const char *mapped;
-
- if (v > UCS_MAX) {
- /* This cannot happen, but just in case.. */
- return (idn_invalid_codepoint);
- } else if (v > UNICODE_MAX) {
- /* No mapping is possible. */
- mapped = NULL;
- } else {
- /* Try mapping. */
- mapped = (*handle->map_proc)(v);
- }
-
- if (mapped == NULL) {
- /* No mapping. Just copy verbatim. */
- if (tolen < 1)
- return (idn_buffer_overflow);
- *to++ = v;
- tolen--;
- } else {
- const unsigned char *mappeddata;
- size_t mappedlen;
-
- mappeddata = (const unsigned char *)mapped + 1;
- mappedlen = *mapped;
-
- if (tolen < (mappedlen + 3) / 4)
- return (idn_buffer_overflow);
- tolen -= (mappedlen + 3) / 4;
- while (mappedlen >= 4) {
- *to = *mappeddata++;
- *to |= *mappeddata++ << 8;
- *to |= *mappeddata++ << 16;
- *to |= *mappeddata++ << 24;
- mappedlen -= 4;
- to++;
- }
- if (mappedlen > 0) {
- *to = *mappeddata++;
- *to |= (mappedlen >= 2) ?
- *mappeddata++ << 8: 0;
- *to |= (mappedlen >= 3) ?
- *mappeddata++ << 16: 0;
- to++;
- }
- }
- from++;
- }
- if (tolen == 0)
- return (idn_buffer_overflow);
- *to = '\0';
- return (idn_success);
-}
-
-idn_result_t
-idn_nameprep_isprohibited(idn_nameprep_t handle, const uint32_t *str,
- const uint32_t **found) {
- assert(handle != NULL && str != NULL && found != NULL);
-
- TRACE(("idn_nameprep_isprohibited(ctx=%s, str=\"%s\")\n",
- handle->version, idn__debug_ucs4xstring(str, 50)));
-
- return (idn_nameprep_check(handle->prohibited_proc, str, found));
-}
-
-idn_result_t
-idn_nameprep_isunassigned(idn_nameprep_t handle, const uint32_t *str,
- const uint32_t **found) {
- assert(handle != NULL && str != NULL && found != NULL);
-
- TRACE(("idn_nameprep_isunassigned(handle->version, str=\"%s\")\n",
- handle->version, idn__debug_ucs4xstring(str, 50)));
-
- return (idn_nameprep_check(handle->unassigned_proc, str, found));
-}
-
-static idn_result_t
-idn_nameprep_check(nameprep_checkproc proc, const uint32_t *str,
- const uint32_t **found) {
- uint32_t v;
-
- while (*str != '\0') {
- v = *str;
-
- if (v > UCS_MAX) {
- /* This cannot happen, but just in case.. */
- return (idn_invalid_codepoint);
- } else if (v > UNICODE_MAX) {
- /* It is invalid.. */
- *found = str;
- return (idn_success);
- } else if ((*proc)(v)) {
- *found = str;
- return (idn_success);
- }
- str++;
- }
- *found = NULL;
- return (idn_success);
-}
-
-idn_result_t
-idn_nameprep_isvalidbidi(idn_nameprep_t handle, const uint32_t *str,
- const uint32_t **found) {
- uint32_t v;
- idn_biditype_t first_char;
- idn_biditype_t last_char;
- int found_r_al;
-
- assert(handle != NULL && str != NULL && found != NULL);
-
- TRACE(("idn_nameprep_isvalidbidi(ctx=%s, str=\"%s\")\n",
- handle->version, idn__debug_ucs4xstring(str, 50)));
-
- if (*str == '\0') {
- *found = NULL;
- return (idn_success);
- }
-
- /*
- * check first character's type and initialize variables.
- */
- found_r_al = 0;
- if (*str > UCS_MAX) {
- /* This cannot happen, but just in case.. */
- return (idn_invalid_codepoint);
- } else if (*str > UNICODE_MAX) {
- /* It is invalid.. */
- *found = str;
- return (idn_success);
- }
- first_char = last_char = (*(handle->biditype_proc))(*str);
- if (first_char == idn_biditype_r_al) {
- found_r_al = 1;
- }
- str++;
-
- /*
- * see whether string is valid or not.
- */
- while (*str != '\0') {
- v = *str;
-
- if (v > UCS_MAX) {
- /* This cannot happen, but just in case.. */
- return (idn_invalid_codepoint);
- } else if (v > UNICODE_MAX) {
- /* It is invalid.. */
- *found = str;
- return (idn_success);
- } else {
- last_char = (*(handle->biditype_proc))(v);
- if (found_r_al && last_char == idn_biditype_l) {
- *found = str;
- return (idn_success);
- }
- if (first_char != idn_biditype_r_al && last_char == idn_biditype_r_al) {
- *found = str;
- return (idn_success);
- }
- if (last_char == idn_biditype_r_al) {
- found_r_al = 1;
- }
- }
- str++;
- }
-
- if (found_r_al) {
- if (last_char != idn_biditype_r_al) {
- *found = str - 1;
- return (idn_success);
- }
- }
-
- *found = NULL;
- return (idn_success);
-}
-
-idn_result_t
-idn_nameprep_createproc(const char *parameter, void **handlep) {
- return idn_nameprep_create(parameter, (idn_nameprep_t *)handlep);
-}
-
-void
-idn_nameprep_destroyproc(void *handle) {
- idn_nameprep_destroy((idn_nameprep_t)handle);
-}
-
-idn_result_t
-idn_nameprep_mapproc(void *handle, const uint32_t *from,
- uint32_t *to, size_t tolen) {
- return idn_nameprep_map((idn_nameprep_t)handle, from, to, tolen);
-}
-
-idn_result_t
-idn_nameprep_prohibitproc(void *handle, const uint32_t *str,
- const uint32_t **found) {
- return idn_nameprep_isprohibited((idn_nameprep_t)handle, str, found);
-}
-
-idn_result_t
-idn_nameprep_unassignedproc(void *handle, const uint32_t *str,
- const uint32_t **found) {
- return idn_nameprep_isunassigned((idn_nameprep_t)handle, str, found);
-}
-
-idn_result_t
-idn_nameprep_bidiproc(void *handle, const uint32_t *str,
- const uint32_t **found) {
- return idn_nameprep_isvalidbidi((idn_nameprep_t)handle, str, found);
-}
diff --git a/netwerk/dns/nameprep_template.c b/netwerk/dns/nameprep_template.c
deleted file mode 100644
index 7fe36518a..000000000
--- a/netwerk/dns/nameprep_template.c
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (c) 2001 Japan Network Information Center. All rights reserved.
- *
- * By using this file, you agree to the terms and conditions set forth bellow.
- *
- * LICENSE TERMS AND CONDITIONS
- *
- * The following License Terms and Conditions apply, unless a different
- * license is obtained from Japan Network Information Center ("JPNIC"),
- * a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda,
- * Chiyoda-ku, Tokyo 101-0047, Japan.
- *
- * 1. Use, Modification and Redistribution (including distribution of any
- * modified or derived work) in source and/or binary forms is permitted
- * under this License Terms and Conditions.
- *
- * 2. Redistribution of source code must retain the copyright notices as they
- * appear in each source code file, this License Terms and Conditions.
- *
- * 3. Redistribution in binary form must reproduce the Copyright Notice,
- * this License Terms and Conditions, in the documentation and/or other
- * materials provided with the distribution. For the purposes of binary
- * distribution the "Copyright Notice" refers to the following language:
- * "Copyright (c) 2000-2002 Japan Network Information Center. All rights reserved."
- *
- * 4. The name of JPNIC may not be used to endorse or promote products
- * derived from this Software without specific prior written approval of
- * JPNIC.
- *
- * 5. Disclaimer/Limitation of Liability: THIS SOFTWARE IS PROVIDED BY JPNIC
- * "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 JPNIC 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 DAMAGES.
- */
-
-/*
- * Include this file once for each version of NAMEPREP.
- * VERSION should be defined to appropriate value before inclusion.
- */
-
-#ifndef NAMEPREP_TEMPLATE_INIT
-#define NAMEPREP_TEMPLATE_INIT
-
-/* Symbol composition. */
-#define compose_sym2(a, b) compose_sym2X(a, b)
-#define compose_sym2X(a, b) a ## b
-#define compose_sym3(a, b, c) compose_sym3X(a, b, c)
-#define compose_sym3X(a, b, c) a ## b ## c
-
-/* The table is based on "Optimized Two-Stage Table" mentioned in
- * Unicode 3.0 page 106, extended to handle 21bit data instead of 16 bit.
- */
-
-/* Index calculation for multi-level index tables. */
-#define IDX0(type, v) IDX_0(v, BITS1(type), BITS2(type))
-#define IDX1(type, v) IDX_1(v, BITS1(type), BITS2(type))
-#define IDX2(type, v) IDX_2(v, BITS1(type), BITS2(type))
-
-#define IDX_0(v, bits1, bits2) ((v) >> ((bits1) + (bits2)))
-#define IDX_1(v, bits1, bits2) (((v) >> (bits2)) & ((1 << (bits1)) - 1))
-#define IDX_2(v, bits1, bits2) ((v) & ((1 << (bits2)) - 1))
-
-#define BITS1(type) type ## _BITS_1
-#define BITS2(type) type ## _BITS_2
-
-#endif /* NAMEPREP_TEMPLATE_INIT */
-
-static const char *
-compose_sym2(nameprep_map_, VERSION) (uint32_t v) {
- int idx0 = IDX0(MAP, v);
- int idx1 = IDX1(MAP, v);
- int idx2 = IDX2(MAP, v);
- int offset;
-
-#define IMAP compose_sym3(nameprep_, VERSION, _map_imap)
-#define TABLE compose_sym3(nameprep_, VERSION, _map_table)
-#define DATA compose_sym3(nameprep_, VERSION, _map_data)
- offset = TABLE[IMAP[IMAP[idx0] + idx1]].tbl[idx2];
- if (offset == 0)
- return (NULL); /* no mapping */
- return (const char *)(DATA + offset);
-#undef IMAP
-#undef TABLE
-#undef DATA
-}
-
-static int
-compose_sym2(nameprep_prohibited_, VERSION) (uint32_t v) {
- int idx0 = IDX0(PROH, v);
- int idx1 = IDX1(PROH, v);
- int idx2 = IDX2(PROH, v);
- const unsigned char *bm;
-
-#define IMAP compose_sym3(nameprep_, VERSION, _prohibited_imap)
-#define BITMAP compose_sym3(nameprep_, VERSION, _prohibited_bitmap)
- bm = BITMAP[IMAP[IMAP[idx0] + idx1]].bm;
- return (bm[idx2 / 8] & (1 << (idx2 % 8)));
-#undef IMAP
-#undef BITMAP
-}
-
-static int
-compose_sym2(nameprep_unassigned_, VERSION) (uint32_t v) {
- int idx0 = IDX0(UNAS, v);
- int idx1 = IDX1(UNAS, v);
- int idx2 = IDX2(UNAS, v);
- const unsigned char *bm;
-
-#define IMAP compose_sym3(nameprep_, VERSION, _unassigned_imap)
-#define BITMAP compose_sym3(nameprep_, VERSION, _unassigned_bitmap)
- bm = BITMAP[IMAP[IMAP[idx0] + idx1]].bm;
- return (bm[idx2 / 8] & (1 << (idx2 % 8)));
-#undef IMAP
-#undef BITMAP
-}
-
-static idn_biditype_t
-compose_sym2(nameprep_biditype_, VERSION) (uint32_t v) {
- int idx0 = IDX0(BIDI, v);
- int idx1 = IDX1(BIDI, v);
- int idx2 = IDX2(BIDI, v);
- int offset;
-
-#define IMAP compose_sym3(nameprep_, VERSION, _bidi_imap)
-#define TABLE compose_sym3(nameprep_, VERSION, _bidi_table)
-#define DATA compose_sym3(nameprep_, VERSION, _bidi_data)
- offset = TABLE[IMAP[IMAP[idx0] + idx1]].tbl[idx2];
- return DATA[offset];
-#undef IMAP
-#undef TABLE
-#undef DATA
-}
diff --git a/netwerk/dns/nameprepdata.c b/netwerk/dns/nameprepdata.c
deleted file mode 100644
index cd7e2db0e..000000000
--- a/netwerk/dns/nameprepdata.c
+++ /dev/null
@@ -1,2588 +0,0 @@
-/*
- * Copyright (c) 2001,2002 Japan Network Information Center.
- * All rights reserved.
- *
- * By using this file, you agree to the terms and conditions set forth bellow.
- *
- * LICENSE TERMS AND CONDITIONS
- *
- * The following License Terms and Conditions apply, unless a different
- * license is obtained from Japan Network Information Center ("JPNIC"),
- * a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda,
- * Chiyoda-ku, Tokyo 101-0047, Japan.
- *
- * 1. Use, Modification and Redistribution (including distribution of any
- * modified or derived work) in source and/or binary forms is permitted
- * under this License Terms and Conditions.
- *
- * 2. Redistribution of source code must retain the copyright notices as they
- * appear in each source code file, this License Terms and Conditions.
- *
- * 3. Redistribution in binary form must reproduce the Copyright Notice,
- * this License Terms and Conditions, in the documentation and/or other
- * materials provided with the distribution. For the purposes of binary
- * distribution the "Copyright Notice" refers to the following language:
- * "Copyright (c) 2000-2002 Japan Network Information Center. All rights reserved."
- *
- * 4. The name of JPNIC may not be used to endorse or promote products
- * derived from this Software without specific prior written approval of
- * JPNIC.
- *
- * 5. Disclaimer/Limitation of Liability: THIS SOFTWARE IS PROVIDED BY JPNIC
- * "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 JPNIC 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 DAMAGES.
- */
-
- /*
- * Do not edit this file!
- * This file is generated from NAMEPREP specification.
- */
-
-#define MAP_BITS_0 9
-#define MAP_BITS_1 7
-#define MAP_BITS_2 5
-
-#define PROH_BITS_0 7
-#define PROH_BITS_1 7
-#define PROH_BITS_2 7
-
-#define UNAS_BITS_0 7
-#define UNAS_BITS_1 7
-#define UNAS_BITS_2 7
-
-#define BIDI_BITS_0 9
-#define BIDI_BITS_1 7
-#define BIDI_BITS_2 5
-
-
-static const unsigned short nameprep_id11_map_imap[] = {
- 272, 400, 528, 656, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 912,
- 1040, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 1168, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 784, 784, 784, 784, 784, 784, 784, 784,
- 0, 0, 1, 0, 0, 2, 3, 0,
- 4, 5, 6, 7, 8, 9, 10, 11,
- 12, 13, 0, 0, 0, 0, 0, 0,
- 0, 0, 14, 15, 16, 17, 18, 19,
- 20, 21, 0, 22, 23, 24, 25, 26,
- 27, 28, 29, 0, 30, 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, 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, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 31, 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,
- 32, 33, 34, 35, 36, 37, 38, 39,
- 40, 41, 42, 43, 44, 45, 46, 47,
- 48, 0, 0, 49, 0, 50, 0, 0,
- 51, 52, 53, 54, 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, 55, 56, 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, 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, 57, 58, 59, 60, 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, 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, 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, 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, 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,
- 61, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 62, 0, 0, 0, 0, 0, 0, 63,
- 0, 64, 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,
- 65, 66, 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, 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,
- 67, 68, 69, 70, 71, 72, 73, 74,
- 75, 76, 77, 78, 79, 67, 68, 69,
- 70, 80, 81, 73, 74, 82, 83, 84,
- 85, 86, 87, 88, 89, 90, 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, 0, 0,
-};
-
-static const struct {
- unsigned short tbl[32];
-} nameprep_id11_map_table[] = {
- {{
- 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, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
- 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42,
- 44, 46, 48, 50, 52, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 54,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77,
- 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99,
- 101, 0, 103, 105, 107, 109, 111, 113, 115, 117,
- }},
- {{
- 123, 0, 126, 0, 129, 0, 132, 0, 135, 0, 138,
- 0, 141, 0, 144, 0, 147, 0, 150, 0, 153, 0,
- 156, 0, 159, 0, 162, 0, 165, 0, 168, 0,
- }},
- {{
- 171, 0, 174, 0, 177, 0, 180, 0, 183, 0, 186,
- 0, 189, 0, 192, 0, 195, 0, 202, 0, 205, 0,
- 208, 0, 0, 211, 0, 214, 0, 217, 0, 220,
- }},
- {{
- 0, 223, 0, 226, 0, 229, 0, 232, 0, 235, 241,
- 0, 244, 0, 247, 0, 250, 0, 253, 0, 256, 0,
- 259, 0, 262, 0, 265, 0, 268, 0, 271, 0,
- }},
- {{
- 274, 0, 277, 0, 280, 0, 283, 0, 286, 0, 289,
- 0, 292, 0, 295, 0, 298, 0, 301, 0, 304, 0,
- 307, 0, 310, 312, 0, 315, 0, 318, 0, 38,
- }},
- {{
- 0, 321, 324, 0, 327, 0, 330, 333, 0, 336, 339,
- 342, 0, 0, 345, 348, 351, 354, 0, 357, 360, 0,
- 363, 366, 369, 0, 0, 0, 372, 375, 0, 378,
- }},
- {{
- 381, 0, 384, 0, 387, 0, 390, 393, 0, 396, 0,
- 0, 399, 0, 402, 405, 0, 408, 411, 414, 0, 417,
- 0, 420, 423, 0, 0, 0, 426, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 429, 429, 0, 432, 432, 0, 435,
- 435, 0, 438, 0, 441, 0, 444, 0, 447, 0, 450,
- 0, 453, 0, 456, 0, 459, 0, 0, 462, 0,
- }},
- {{
- 465, 0, 468, 0, 471, 0, 474, 0, 477, 0, 480,
- 0, 483, 0, 486, 0, 489, 496, 496, 0, 499, 0,
- 502, 505, 508, 0, 511, 0, 514, 0, 517, 0,
- }},
- {{
- 520, 0, 523, 0, 526, 0, 529, 0, 532, 0, 535,
- 0, 538, 0, 541, 0, 544, 0, 547, 0, 550, 0,
- 553, 0, 556, 0, 559, 0, 562, 0, 565, 0,
- }},
- {{
- 568, 0, 571, 0, 574, 0, 577, 0, 580, 0, 583,
- 0, 586, 0, 589, 0, 592, 0, 595, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 598, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 1, 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, 601, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 608, 0, 611, 614, 617,
- 0, 620, 0, 623, 626, 629, 640, 643, 646, 649, 652,
- 655, 658, 661, 598, 664, 667, 54, 670, 673, 676,
- }},
- {{
- 679, 682, 0, 685, 688, 691, 694, 697, 700, 703, 706,
- 709, 0, 0, 0, 0, 712, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 685, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 643, 661, 691, 623, 709, 694,
- 679, 0, 723, 0, 726, 0, 729, 0, 732, 0,
- }},
- {{
- 735, 0, 738, 0, 741, 0, 744, 0, 747, 0, 750,
- 0, 753, 0, 756, 0, 664, 682, 685, 0, 661, 652,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 759, 762, 765, 768, 771, 774, 777, 780, 783, 786, 789,
- 792, 795, 798, 801, 804, 807, 810, 813, 816, 819, 822,
- 825, 828, 831, 834, 837, 840, 843, 846, 849, 852,
- }},
- {{
- 855, 858, 861, 864, 867, 870, 873, 876, 879, 882, 885,
- 888, 891, 894, 897, 900, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 903, 0, 906, 0, 909, 0, 912, 0, 915, 0, 918,
- 0, 921, 0, 924, 0, 927, 0, 930, 0, 933, 0,
- 936, 0, 939, 0, 942, 0, 945, 0, 948, 0,
- }},
- {{
- 951, 0, 0, 0, 0, 0, 0, 0, 0, 0, 954,
- 0, 957, 0, 960, 0, 963, 0, 966, 0, 969, 0,
- 972, 0, 975, 0, 978, 0, 981, 0, 984, 0,
- }},
- {{
- 987, 0, 990, 0, 993, 0, 996, 0, 999, 0, 1002,
- 0, 1005, 0, 1008, 0, 1011, 0, 1014, 0, 1017, 0,
- 1020, 0, 1023, 0, 1026, 0, 1029, 0, 1032, 0,
- }},
- {{
- 0, 1035, 0, 1038, 0, 1041, 0, 1044, 0, 1047, 0,
- 1050, 0, 1053, 0, 0, 1056, 0, 1059, 0, 1062, 0,
- 1065, 0, 1068, 0, 1071, 0, 1074, 0, 1077, 0,
- }},
- {{
- 1080, 0, 1083, 0, 1086, 0, 1089, 0, 1092, 0, 1095,
- 0, 1098, 0, 1101, 0, 1104, 0, 1107, 0, 1110, 0,
- 0, 0, 1113, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 1116, 0, 1119, 0, 1122, 0, 1125, 0, 1128, 0, 1131,
- 0, 1134, 0, 1137, 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, 1140, 1143, 1146, 1149, 1152,
- 1155, 1158, 1161, 1164, 1167, 1170, 1173, 1176, 1179, 1182,
- }},
- {{
- 1185, 1188, 1191, 1194, 1197, 1200, 1203, 1206, 1209, 1212, 1215,
- 1218, 1221, 1224, 1227, 1230, 1233, 1236, 1239, 1242, 1245, 1248,
- 1251, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 1254, 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, 0, 0, 0, 0,
- 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 1261, 0, 1264, 0, 1267, 0, 1270, 0, 1273, 0, 1276,
- 0, 1279, 0, 1282, 0, 1285, 0, 1288, 0, 1291, 0,
- 1294, 0, 1297, 0, 1300, 0, 1303, 0, 1306, 0,
- }},
- {{
- 1309, 0, 1312, 0, 1315, 0, 1318, 0, 1321, 0, 1324,
- 0, 1327, 0, 1330, 0, 1333, 0, 1336, 0, 1339, 0,
- 1342, 0, 1345, 0, 1348, 0, 1351, 0, 1354, 0,
- }},
- {{
- 1357, 0, 1360, 0, 1363, 0, 1366, 0, 1369, 0, 1372,
- 0, 1375, 0, 1378, 0, 1381, 0, 1384, 0, 1387, 0,
- 1390, 0, 1393, 0, 1396, 0, 1399, 0, 1402, 0,
- }},
- {{
- 1405, 0, 1408, 0, 1411, 0, 1414, 0, 1417, 0, 1420,
- 0, 1423, 0, 1426, 0, 1429, 0, 1432, 0, 1435, 0,
- 1438, 0, 1441, 0, 1444, 0, 1447, 0, 1450, 0,
- }},
- {{
- 1453, 0, 1456, 0, 1459, 0, 1462, 0, 1465, 0, 1468,
- 0, 1471, 0, 1474, 0, 1477, 0, 1480, 0, 1483, 0,
- 1486, 1493, 1500, 1507, 1514, 1405, 0, 0, 0, 0,
- }},
- {{
- 1521, 0, 1524, 0, 1527, 0, 1530, 0, 1533, 0, 1536,
- 0, 1539, 0, 1542, 0, 1545, 0, 1548, 0, 1551, 0,
- 1554, 0, 1557, 0, 1560, 0, 1563, 0, 1566, 0,
- }},
- {{
- 1569, 0, 1572, 0, 1575, 0, 1578, 0, 1581, 0, 1584,
- 0, 1587, 0, 1590, 0, 1593, 0, 1596, 0, 1599, 0,
- 1602, 0, 1605, 0, 1608, 0, 1611, 0, 1614, 0,
- }},
- {{
- 1617, 0, 1620, 0, 1623, 0, 1626, 0, 1629, 0, 1632,
- 0, 1635, 0, 1638, 0, 1641, 0, 1644, 0, 1647, 0,
- 1650, 0, 1653, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 1656, 1659, 1662,
- 1665, 1668, 1671, 1674, 1677, 0, 0, 0, 0, 0, 0,
- 0, 0, 1680, 1683, 1686, 1689, 1692, 1695, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 1698, 1701, 1704,
- 1707, 1710, 1713, 1716, 1719, 0, 0, 0, 0, 0, 0,
- 0, 0, 1722, 1725, 1728, 1731, 1734, 1737, 1740, 1743,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 1746, 1749, 1752,
- 1755, 1758, 1761, 0, 0, 1764, 0, 1771, 0, 1782, 0,
- 1793, 0, 0, 1804, 0, 1807, 0, 1810, 0, 1813,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 1816, 1819, 1822,
- 1825, 1828, 1831, 1834, 1837, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 1840, 1847, 1854, 1861, 1868, 1875, 1882, 1889, 1840, 1847, 1854,
- 1861, 1868, 1875, 1882, 1889, 1896, 1903, 1910, 1917, 1924, 1931,
- 1938, 1945, 1896, 1903, 1910, 1917, 1924, 1931, 1938, 1945,
- }},
- {{
- 1952, 1959, 1966, 1973, 1980, 1987, 1994, 2001, 1952, 1959, 1966,
- 1973, 1980, 1987, 1994, 2001, 0, 0, 2008, 2015, 2022, 0,
- 2029, 2036, 2047, 2050, 2053, 2056, 2015, 0, 598, 0,
- }},
- {{
- 0, 0, 2059, 2066, 2073, 0, 2080, 2087, 2098, 2101, 2104,
- 2107, 2066, 0, 0, 0, 0, 0, 2110, 629, 0, 0,
- 2121, 2128, 2139, 2142, 2145, 2148, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 2151, 712, 2162, 0, 2169, 2176, 2187, 2190, 2193,
- 2196, 2199, 0, 0, 0, 0, 0, 2202, 2209, 2216, 0,
- 2223, 2230, 2241, 2244, 2247, 2250, 2209, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 1, 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, 2253, 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, 6, 2259, 0, 0, 0, 351, 0, 2265, 0,
- 16, 16, 16, 0, 0, 18, 18, 24, 0, 0, 28,
- 2271, 0, 0, 32, 34, 36, 36, 36, 0, 0,
- }},
- {{
- 2277, 2283, 2293, 0, 52, 0, 703, 0, 52, 0, 22,
- 67, 4, 6, 0, 0, 10, 12, 0, 26, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 646, 679,
- }},
- {{
- 0, 0, 0, 0, 0, 8, 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,
- }},
- {{
- 2299, 2302, 2305, 2308, 2311, 2314, 2317, 2320, 2323, 2326, 2329,
- 2332, 2335, 2338, 2341, 2344, 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,
- 2347, 2350, 2353, 2356, 2359, 2362, 2365, 2368, 2371, 2374,
- }},
- {{
- 2377, 2380, 2383, 2386, 2389, 2392, 2395, 2398, 2401, 2404, 2407,
- 2410, 2413, 2416, 2419, 2422, 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, 2425, 0, 2435, 0, 2441,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2447, 2453, 2459, 2465, 2471, 2477, 2483, 2489, 0, 0, 2495,
- 2501, 2507, 0, 0, 0, 2513, 2519, 2529, 2539, 2549, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 2447, 2559,
- 2569, 2579, 0, 0, 0, 0, 0, 0, 0, 2589, 2595,
- 2601, 2607, 2613, 2607, 2619, 2625, 2631, 2637, 2643, 2637,
- }},
- {{
- 2649, 2656, 0, 2663, 0, 0, 2669, 2683, 2693, 2699, 0,
- 2705, 0, 2711, 2717, 0, 0, 0, 0, 0, 0, 0,
- 0, 2723, 0, 2729, 2739, 0, 2745, 2751, 0, 0,
- }},
- {{
- 2757, 2763, 2769, 2775, 2785, 2795, 2795, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 2801, 2808, 2815,
- 2822, 2829, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 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, 1,
- }},
- {{
- 0, 2836, 2839, 2842, 2845, 2848, 2851, 2854, 2857, 2860, 2863,
- 2866, 2869, 2872, 2875, 2878, 2881, 2884, 2887, 2890, 2893, 2896,
- 2899, 2902, 2905, 2908, 2911, 0, 0, 0, 0, 0,
- }},
- {{
- 2914, 2918, 2922, 2926, 2930, 2934, 2938, 2942, 2946, 2950, 2954,
- 2958, 2962, 2966, 2970, 2974, 2978, 2982, 2986, 2990, 2994, 2998,
- 3002, 3006, 3010, 3014, 3018, 3022, 3026, 3030, 3034, 3038,
- }},
- {{
- 3042, 3046, 3050, 3054, 3058, 3062, 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,
- }},
- {{
- 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22,
- 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44,
- 46, 48, 50, 52, 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, 2, 4,
- 6, 8, 10, 12, 14, 16, 18, 20, 22, 24,
- }},
- {{
- 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46,
- 48, 50, 52, 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, 2, 4, 6,
- 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28,
- 30, 32, 34, 36, 38, 40, 42, 44, 46, 48,
- }},
- {{
- 50, 52, 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, 2, 0, 6, 8,
- }},
- {{
- 0, 0, 14, 0, 0, 20, 22, 0, 0, 28, 30,
- 32, 34, 0, 38, 40, 42, 44, 46, 48, 50, 52,
- 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, 2, 4, 6, 8, 10, 12,
- 14, 16, 18, 20, 22, 24, 26, 28, 30, 32,
- }},
- {{
- 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 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, 2, 4, 0, 8, 10, 12, 14,
- 0, 0, 20, 22, 24, 26, 28, 30, 32, 34, 0,
- 38, 40, 42, 44, 46, 48, 50, 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, 2, 4, 0, 8, 10, 12, 14, 0,
- }},
- {{
- 18, 20, 22, 24, 26, 0, 30, 0, 0, 0, 38,
- 40, 42, 44, 46, 48, 50, 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, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
- 22, 24, 26, 28, 30, 32, 34, 36, 38, 40,
- }},
- {{
- 42, 44, 46, 48, 50, 52, 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,
- }},
- {{
- 50, 52, 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, 2, 4, 6, 8,
- }},
- {{
- 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30,
- 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 640, 643, 646,
- 649, 652, 655, 658, 661, 598, 664, 667, 54, 670, 673,
- 676, 679, 682, 661, 685, 688, 691, 694, 697, 700,
- }},
- {{
- 703, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 685, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 640, 643, 646, 649, 652, 655, 658, 661, 598,
- 664, 667, 54, 670, 673, 676, 679, 682, 661, 685, 688,
- 691, 694, 697, 700, 703, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 685, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 640, 643, 646, 649,
- }},
- {{
- 652, 655, 658, 661, 598, 664, 667, 54, 670, 673, 676,
- 679, 682, 661, 685, 688, 691, 694, 697, 700, 703, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 685, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 640, 643, 646, 649, 652, 655, 658, 661, 598, 664,
- }},
- {{
- 667, 54, 670, 673, 676, 679, 682, 661, 685, 688, 691,
- 694, 697, 700, 703, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 685, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 640, 643, 646, 649, 652, 655,
- 658, 661, 598, 664, 667, 54, 670, 673, 676, 679,
- }},
- {{
- 682, 661, 685, 688, 691, 694, 697, 700, 703, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 685, 0, 0, 0, 0,
- }},
-};
-
-static const unsigned char nameprep_id11_map_data[] = {
- 0, 0, 1, 97, 1, 98, 1, 99, 1, 100, 1, 101,
- 1, 102, 1, 103, 1, 104, 1, 105, 1, 106, 1, 107,
- 1, 108, 1, 109, 1, 110, 1, 111, 1, 112, 1, 113,
- 1, 114, 1, 115, 1, 116, 1, 117, 1, 118, 1, 119,
- 1, 120, 1, 121, 1, 122, 2, 188, 3, 1, 224, 1,
- 225, 1, 226, 1, 227, 1, 228, 1, 229, 1, 230, 1,
- 231, 1, 232, 1, 233, 1, 234, 1, 235, 1, 236, 1,
- 237, 1, 238, 1, 239, 1, 240, 1, 241, 1, 242, 1,
- 243, 1, 244, 1, 245, 1, 246, 1, 248, 1, 249, 1,
- 250, 1, 251, 1, 252, 1, 253, 1, 254, 5, 115, 0,
- 0, 0, 115, 2, 1, 1, 2, 3, 1, 2, 5, 1,
- 2, 7, 1, 2, 9, 1, 2, 11, 1, 2, 13, 1,
- 2, 15, 1, 2, 17, 1, 2, 19, 1, 2, 21, 1,
- 2, 23, 1, 2, 25, 1, 2, 27, 1, 2, 29, 1,
- 2, 31, 1, 2, 33, 1, 2, 35, 1, 2, 37, 1,
- 2, 39, 1, 2, 41, 1, 2, 43, 1, 2, 45, 1,
- 2, 47, 1, 6, 105, 0, 0, 0, 7, 3, 2, 51,
- 1, 2, 53, 1, 2, 55, 1, 2, 58, 1, 2, 60,
- 1, 2, 62, 1, 2, 64, 1, 2, 66, 1, 2, 68,
- 1, 2, 70, 1, 2, 72, 1, 5, 188, 2, 0, 0,
- 110, 2, 75, 1, 2, 77, 1, 2, 79, 1, 2, 81,
- 1, 2, 83, 1, 2, 85, 1, 2, 87, 1, 2, 89,
- 1, 2, 91, 1, 2, 93, 1, 2, 95, 1, 2, 97,
- 1, 2, 99, 1, 2, 101, 1, 2, 103, 1, 2, 105,
- 1, 2, 107, 1, 2, 109, 1, 2, 111, 1, 2, 113,
- 1, 2, 115, 1, 2, 117, 1, 2, 119, 1, 1, 255,
- 2, 122, 1, 2, 124, 1, 2, 126, 1, 2, 83, 2,
- 2, 131, 1, 2, 133, 1, 2, 84, 2, 2, 136, 1,
- 2, 86, 2, 2, 87, 2, 2, 140, 1, 2, 221, 1,
- 2, 89, 2, 2, 91, 2, 2, 146, 1, 2, 96, 2,
- 2, 99, 2, 2, 105, 2, 2, 104, 2, 2, 153, 1,
- 2, 111, 2, 2, 114, 2, 2, 117, 2, 2, 161, 1,
- 2, 163, 1, 2, 165, 1, 2, 128, 2, 2, 168, 1,
- 2, 131, 2, 2, 173, 1, 2, 136, 2, 2, 176, 1,
- 2, 138, 2, 2, 139, 2, 2, 180, 1, 2, 182, 1,
- 2, 146, 2, 2, 185, 1, 2, 189, 1, 2, 198, 1,
- 2, 201, 1, 2, 204, 1, 2, 206, 1, 2, 208, 1,
- 2, 210, 1, 2, 212, 1, 2, 214, 1, 2, 216, 1,
- 2, 218, 1, 2, 220, 1, 2, 223, 1, 2, 225, 1,
- 2, 227, 1, 2, 229, 1, 2, 231, 1, 2, 233, 1,
- 2, 235, 1, 2, 237, 1, 2, 239, 1, 6, 106, 0,
- 0, 0, 12, 3, 2, 243, 1, 2, 245, 1, 2, 149,
- 1, 2, 191, 1, 2, 249, 1, 2, 251, 1, 2, 253,
- 1, 2, 255, 1, 2, 1, 2, 2, 3, 2, 2, 5,
- 2, 2, 7, 2, 2, 9, 2, 2, 11, 2, 2, 13,
- 2, 2, 15, 2, 2, 17, 2, 2, 19, 2, 2, 21,
- 2, 2, 23, 2, 2, 25, 2, 2, 27, 2, 2, 29,
- 2, 2, 31, 2, 2, 158, 1, 2, 35, 2, 2, 37,
- 2, 2, 39, 2, 2, 41, 2, 2, 43, 2, 2, 45,
- 2, 2, 47, 2, 2, 49, 2, 2, 51, 2, 2, 185,
- 3, 6, 32, 0, 0, 0, 185, 3, 2, 172, 3, 2,
- 173, 3, 2, 174, 3, 2, 175, 3, 2, 204, 3, 2,
- 205, 3, 2, 206, 3, 10, 185, 3, 0, 0, 8, 3,
- 0, 0, 1, 3, 2, 177, 3, 2, 178, 3, 2, 179,
- 3, 2, 180, 3, 2, 181, 3, 2, 182, 3, 2, 183,
- 3, 2, 184, 3, 2, 186, 3, 2, 187, 3, 2, 189,
- 3, 2, 190, 3, 2, 191, 3, 2, 192, 3, 2, 193,
- 3, 2, 195, 3, 2, 196, 3, 2, 197, 3, 2, 198,
- 3, 2, 199, 3, 2, 200, 3, 2, 201, 3, 2, 202,
- 3, 2, 203, 3, 10, 197, 3, 0, 0, 8, 3, 0,
- 0, 1, 3, 2, 217, 3, 2, 219, 3, 2, 221, 3,
- 2, 223, 3, 2, 225, 3, 2, 227, 3, 2, 229, 3,
- 2, 231, 3, 2, 233, 3, 2, 235, 3, 2, 237, 3,
- 2, 239, 3, 2, 80, 4, 2, 81, 4, 2, 82, 4,
- 2, 83, 4, 2, 84, 4, 2, 85, 4, 2, 86, 4,
- 2, 87, 4, 2, 88, 4, 2, 89, 4, 2, 90, 4,
- 2, 91, 4, 2, 92, 4, 2, 93, 4, 2, 94, 4,
- 2, 95, 4, 2, 48, 4, 2, 49, 4, 2, 50, 4,
- 2, 51, 4, 2, 52, 4, 2, 53, 4, 2, 54, 4,
- 2, 55, 4, 2, 56, 4, 2, 57, 4, 2, 58, 4,
- 2, 59, 4, 2, 60, 4, 2, 61, 4, 2, 62, 4,
- 2, 63, 4, 2, 64, 4, 2, 65, 4, 2, 66, 4,
- 2, 67, 4, 2, 68, 4, 2, 69, 4, 2, 70, 4,
- 2, 71, 4, 2, 72, 4, 2, 73, 4, 2, 74, 4,
- 2, 75, 4, 2, 76, 4, 2, 77, 4, 2, 78, 4,
- 2, 79, 4, 2, 97, 4, 2, 99, 4, 2, 101, 4,
- 2, 103, 4, 2, 105, 4, 2, 107, 4, 2, 109, 4,
- 2, 111, 4, 2, 113, 4, 2, 115, 4, 2, 117, 4,
- 2, 119, 4, 2, 121, 4, 2, 123, 4, 2, 125, 4,
- 2, 127, 4, 2, 129, 4, 2, 139, 4, 2, 141, 4,
- 2, 143, 4, 2, 145, 4, 2, 147, 4, 2, 149, 4,
- 2, 151, 4, 2, 153, 4, 2, 155, 4, 2, 157, 4,
- 2, 159, 4, 2, 161, 4, 2, 163, 4, 2, 165, 4,
- 2, 167, 4, 2, 169, 4, 2, 171, 4, 2, 173, 4,
- 2, 175, 4, 2, 177, 4, 2, 179, 4, 2, 181, 4,
- 2, 183, 4, 2, 185, 4, 2, 187, 4, 2, 189, 4,
- 2, 191, 4, 2, 194, 4, 2, 196, 4, 2, 198, 4,
- 2, 200, 4, 2, 202, 4, 2, 204, 4, 2, 206, 4,
- 2, 209, 4, 2, 211, 4, 2, 213, 4, 2, 215, 4,
- 2, 217, 4, 2, 219, 4, 2, 221, 4, 2, 223, 4,
- 2, 225, 4, 2, 227, 4, 2, 229, 4, 2, 231, 4,
- 2, 233, 4, 2, 235, 4, 2, 237, 4, 2, 239, 4,
- 2, 241, 4, 2, 243, 4, 2, 245, 4, 2, 249, 4,
- 2, 1, 5, 2, 3, 5, 2, 5, 5, 2, 7, 5,
- 2, 9, 5, 2, 11, 5, 2, 13, 5, 2, 15, 5,
- 2, 97, 5, 2, 98, 5, 2, 99, 5, 2, 100, 5,
- 2, 101, 5, 2, 102, 5, 2, 103, 5, 2, 104, 5,
- 2, 105, 5, 2, 106, 5, 2, 107, 5, 2, 108, 5,
- 2, 109, 5, 2, 110, 5, 2, 111, 5, 2, 112, 5,
- 2, 113, 5, 2, 114, 5, 2, 115, 5, 2, 116, 5,
- 2, 117, 5, 2, 118, 5, 2, 119, 5, 2, 120, 5,
- 2, 121, 5, 2, 122, 5, 2, 123, 5, 2, 124, 5,
- 2, 125, 5, 2, 126, 5, 2, 127, 5, 2, 128, 5,
- 2, 129, 5, 2, 130, 5, 2, 131, 5, 2, 132, 5,
- 2, 133, 5, 2, 134, 5, 6, 101, 5, 0, 0, 130,
- 5, 2, 1, 30, 2, 3, 30, 2, 5, 30, 2, 7,
- 30, 2, 9, 30, 2, 11, 30, 2, 13, 30, 2, 15,
- 30, 2, 17, 30, 2, 19, 30, 2, 21, 30, 2, 23,
- 30, 2, 25, 30, 2, 27, 30, 2, 29, 30, 2, 31,
- 30, 2, 33, 30, 2, 35, 30, 2, 37, 30, 2, 39,
- 30, 2, 41, 30, 2, 43, 30, 2, 45, 30, 2, 47,
- 30, 2, 49, 30, 2, 51, 30, 2, 53, 30, 2, 55,
- 30, 2, 57, 30, 2, 59, 30, 2, 61, 30, 2, 63,
- 30, 2, 65, 30, 2, 67, 30, 2, 69, 30, 2, 71,
- 30, 2, 73, 30, 2, 75, 30, 2, 77, 30, 2, 79,
- 30, 2, 81, 30, 2, 83, 30, 2, 85, 30, 2, 87,
- 30, 2, 89, 30, 2, 91, 30, 2, 93, 30, 2, 95,
- 30, 2, 97, 30, 2, 99, 30, 2, 101, 30, 2, 103,
- 30, 2, 105, 30, 2, 107, 30, 2, 109, 30, 2, 111,
- 30, 2, 113, 30, 2, 115, 30, 2, 117, 30, 2, 119,
- 30, 2, 121, 30, 2, 123, 30, 2, 125, 30, 2, 127,
- 30, 2, 129, 30, 2, 131, 30, 2, 133, 30, 2, 135,
- 30, 2, 137, 30, 2, 139, 30, 2, 141, 30, 2, 143,
- 30, 2, 145, 30, 2, 147, 30, 2, 149, 30, 6, 104,
- 0, 0, 0, 49, 3, 6, 116, 0, 0, 0, 8, 3,
- 6, 119, 0, 0, 0, 10, 3, 6, 121, 0, 0, 0,
- 10, 3, 6, 97, 0, 0, 0, 190, 2, 2, 161, 30,
- 2, 163, 30, 2, 165, 30, 2, 167, 30, 2, 169, 30,
- 2, 171, 30, 2, 173, 30, 2, 175, 30, 2, 177, 30,
- 2, 179, 30, 2, 181, 30, 2, 183, 30, 2, 185, 30,
- 2, 187, 30, 2, 189, 30, 2, 191, 30, 2, 193, 30,
- 2, 195, 30, 2, 197, 30, 2, 199, 30, 2, 201, 30,
- 2, 203, 30, 2, 205, 30, 2, 207, 30, 2, 209, 30,
- 2, 211, 30, 2, 213, 30, 2, 215, 30, 2, 217, 30,
- 2, 219, 30, 2, 221, 30, 2, 223, 30, 2, 225, 30,
- 2, 227, 30, 2, 229, 30, 2, 231, 30, 2, 233, 30,
- 2, 235, 30, 2, 237, 30, 2, 239, 30, 2, 241, 30,
- 2, 243, 30, 2, 245, 30, 2, 247, 30, 2, 249, 30,
- 2, 0, 31, 2, 1, 31, 2, 2, 31, 2, 3, 31,
- 2, 4, 31, 2, 5, 31, 2, 6, 31, 2, 7, 31,
- 2, 16, 31, 2, 17, 31, 2, 18, 31, 2, 19, 31,
- 2, 20, 31, 2, 21, 31, 2, 32, 31, 2, 33, 31,
- 2, 34, 31, 2, 35, 31, 2, 36, 31, 2, 37, 31,
- 2, 38, 31, 2, 39, 31, 2, 48, 31, 2, 49, 31,
- 2, 50, 31, 2, 51, 31, 2, 52, 31, 2, 53, 31,
- 2, 54, 31, 2, 55, 31, 2, 64, 31, 2, 65, 31,
- 2, 66, 31, 2, 67, 31, 2, 68, 31, 2, 69, 31,
- 6, 197, 3, 0, 0, 19, 3, 10, 197, 3, 0, 0,
- 19, 3, 0, 0, 0, 3, 10, 197, 3, 0, 0, 19,
- 3, 0, 0, 1, 3, 10, 197, 3, 0, 0, 19, 3,
- 0, 0, 66, 3, 2, 81, 31, 2, 83, 31, 2, 85,
- 31, 2, 87, 31, 2, 96, 31, 2, 97, 31, 2, 98,
- 31, 2, 99, 31, 2, 100, 31, 2, 101, 31, 2, 102,
- 31, 2, 103, 31, 6, 0, 31, 0, 0, 185, 3, 6,
- 1, 31, 0, 0, 185, 3, 6, 2, 31, 0, 0, 185,
- 3, 6, 3, 31, 0, 0, 185, 3, 6, 4, 31, 0,
- 0, 185, 3, 6, 5, 31, 0, 0, 185, 3, 6, 6,
- 31, 0, 0, 185, 3, 6, 7, 31, 0, 0, 185, 3,
- 6, 32, 31, 0, 0, 185, 3, 6, 33, 31, 0, 0,
- 185, 3, 6, 34, 31, 0, 0, 185, 3, 6, 35, 31,
- 0, 0, 185, 3, 6, 36, 31, 0, 0, 185, 3, 6,
- 37, 31, 0, 0, 185, 3, 6, 38, 31, 0, 0, 185,
- 3, 6, 39, 31, 0, 0, 185, 3, 6, 96, 31, 0,
- 0, 185, 3, 6, 97, 31, 0, 0, 185, 3, 6, 98,
- 31, 0, 0, 185, 3, 6, 99, 31, 0, 0, 185, 3,
- 6, 100, 31, 0, 0, 185, 3, 6, 101, 31, 0, 0,
- 185, 3, 6, 102, 31, 0, 0, 185, 3, 6, 103, 31,
- 0, 0, 185, 3, 6, 112, 31, 0, 0, 185, 3, 6,
- 177, 3, 0, 0, 185, 3, 6, 172, 3, 0, 0, 185,
- 3, 6, 177, 3, 0, 0, 66, 3, 10, 177, 3, 0,
- 0, 66, 3, 0, 0, 185, 3, 2, 176, 31, 2, 177,
- 31, 2, 112, 31, 2, 113, 31, 6, 116, 31, 0, 0,
- 185, 3, 6, 183, 3, 0, 0, 185, 3, 6, 174, 3,
- 0, 0, 185, 3, 6, 183, 3, 0, 0, 66, 3, 10,
- 183, 3, 0, 0, 66, 3, 0, 0, 185, 3, 2, 114,
- 31, 2, 115, 31, 2, 116, 31, 2, 117, 31, 10, 185,
- 3, 0, 0, 8, 3, 0, 0, 0, 3, 6, 185, 3,
- 0, 0, 66, 3, 10, 185, 3, 0, 0, 8, 3, 0,
- 0, 66, 3, 2, 208, 31, 2, 209, 31, 2, 118, 31,
- 2, 119, 31, 10, 197, 3, 0, 0, 8, 3, 0, 0,
- 0, 3, 6, 193, 3, 0, 0, 19, 3, 6, 197, 3,
- 0, 0, 66, 3, 10, 197, 3, 0, 0, 8, 3, 0,
- 0, 66, 3, 2, 224, 31, 2, 225, 31, 2, 122, 31,
- 2, 123, 31, 2, 229, 31, 6, 124, 31, 0, 0, 185,
- 3, 6, 201, 3, 0, 0, 185, 3, 6, 206, 3, 0,
- 0, 185, 3, 6, 201, 3, 0, 0, 66, 3, 10, 201,
- 3, 0, 0, 66, 3, 0, 0, 185, 3, 2, 120, 31,
- 2, 121, 31, 2, 124, 31, 2, 125, 31, 5, 114, 0,
- 0, 0, 115, 5, 176, 0, 0, 0, 99, 5, 176, 0,
- 0, 0, 102, 5, 110, 0, 0, 0, 111, 5, 115, 0,
- 0, 0, 109, 9, 116, 0, 0, 0, 101, 0, 0, 0,
- 108, 5, 116, 0, 0, 0, 109, 2, 112, 33, 2, 113,
- 33, 2, 114, 33, 2, 115, 33, 2, 116, 33, 2, 117,
- 33, 2, 118, 33, 2, 119, 33, 2, 120, 33, 2, 121,
- 33, 2, 122, 33, 2, 123, 33, 2, 124, 33, 2, 125,
- 33, 2, 126, 33, 2, 127, 33, 2, 208, 36, 2, 209,
- 36, 2, 210, 36, 2, 211, 36, 2, 212, 36, 2, 213,
- 36, 2, 214, 36, 2, 215, 36, 2, 216, 36, 2, 217,
- 36, 2, 218, 36, 2, 219, 36, 2, 220, 36, 2, 221,
- 36, 2, 222, 36, 2, 223, 36, 2, 224, 36, 2, 225,
- 36, 2, 226, 36, 2, 227, 36, 2, 228, 36, 2, 229,
- 36, 2, 230, 36, 2, 231, 36, 2, 232, 36, 2, 233,
- 36, 9, 104, 0, 0, 0, 112, 0, 0, 0, 97, 5,
- 97, 0, 0, 0, 117, 5, 111, 0, 0, 0, 118, 5,
- 112, 0, 0, 0, 97, 5, 110, 0, 0, 0, 97, 5,
- 188, 3, 0, 0, 97, 5, 109, 0, 0, 0, 97, 5,
- 107, 0, 0, 0, 97, 5, 107, 0, 0, 0, 98, 5,
- 109, 0, 0, 0, 98, 5, 103, 0, 0, 0, 98, 5,
- 112, 0, 0, 0, 102, 5, 110, 0, 0, 0, 102, 5,
- 188, 3, 0, 0, 102, 5, 104, 0, 0, 0, 122, 9,
- 107, 0, 0, 0, 104, 0, 0, 0, 122, 9, 109, 0,
- 0, 0, 104, 0, 0, 0, 122, 9, 103, 0, 0, 0,
- 104, 0, 0, 0, 122, 9, 116, 0, 0, 0, 104, 0,
- 0, 0, 122, 9, 107, 0, 0, 0, 112, 0, 0, 0,
- 97, 9, 109, 0, 0, 0, 112, 0, 0, 0, 97, 9,
- 103, 0, 0, 0, 112, 0, 0, 0, 97, 5, 112, 0,
- 0, 0, 118, 5, 110, 0, 0, 0, 118, 5, 188, 3,
- 0, 0, 118, 5, 109, 0, 0, 0, 118, 5, 107, 0,
- 0, 0, 118, 5, 112, 0, 0, 0, 119, 5, 110, 0,
- 0, 0, 119, 5, 188, 3, 0, 0, 119, 5, 109, 0,
- 0, 0, 119, 5, 107, 0, 0, 0, 119, 6, 107, 0,
- 0, 0, 201, 3, 6, 109, 0, 0, 0, 201, 3, 5,
- 98, 0, 0, 0, 113, 13, 99, 0, 0, 0, 21, 34,
- 0, 0, 107, 0, 0, 0, 103, 9, 99, 0, 0, 0,
- 111, 0, 0, 0, 46, 5, 100, 0, 0, 0, 98, 5,
- 103, 0, 0, 0, 121, 5, 104, 0, 0, 0, 112, 5,
- 107, 0, 0, 0, 107, 5, 107, 0, 0, 0, 109, 5,
- 112, 0, 0, 0, 104, 9, 112, 0, 0, 0, 112, 0,
- 0, 0, 109, 5, 112, 0, 0, 0, 114, 5, 115, 0,
- 0, 0, 118, 5, 119, 0, 0, 0, 98, 5, 102, 0,
- 0, 0, 102, 5, 102, 0, 0, 0, 105, 5, 102, 0,
- 0, 0, 108, 9, 102, 0, 0, 0, 102, 0, 0, 0,
- 105, 9, 102, 0, 0, 0, 102, 0, 0, 0, 108, 5,
- 115, 0, 0, 0, 116, 6, 116, 5, 0, 0, 118, 5,
- 6, 116, 5, 0, 0, 101, 5, 6, 116, 5, 0, 0,
- 107, 5, 6, 126, 5, 0, 0, 118, 5, 6, 116, 5,
- 0, 0, 109, 5, 2, 65, 255, 2, 66, 255, 2, 67,
- 255, 2, 68, 255, 2, 69, 255, 2, 70, 255, 2, 71,
- 255, 2, 72, 255, 2, 73, 255, 2, 74, 255, 2, 75,
- 255, 2, 76, 255, 2, 77, 255, 2, 78, 255, 2, 79,
- 255, 2, 80, 255, 2, 81, 255, 2, 82, 255, 2, 83,
- 255, 2, 84, 255, 2, 85, 255, 2, 86, 255, 2, 87,
- 255, 2, 88, 255, 2, 89, 255, 2, 90, 255, 3, 40,
- 4, 1, 3, 41, 4, 1, 3, 42, 4, 1, 3, 43,
- 4, 1, 3, 44, 4, 1, 3, 45, 4, 1, 3, 46,
- 4, 1, 3, 47, 4, 1, 3, 48, 4, 1, 3, 49,
- 4, 1, 3, 50, 4, 1, 3, 51, 4, 1, 3, 52,
- 4, 1, 3, 53, 4, 1, 3, 54, 4, 1, 3, 55,
- 4, 1, 3, 56, 4, 1, 3, 57, 4, 1, 3, 58,
- 4, 1, 3, 59, 4, 1, 3, 60, 4, 1, 3, 61,
- 4, 1, 3, 62, 4, 1, 3, 63, 4, 1, 3, 64,
- 4, 1, 3, 65, 4, 1, 3, 66, 4, 1, 3, 67,
- 4, 1, 3, 68, 4, 1, 3, 69, 4, 1, 3, 70,
- 4, 1, 3, 71, 4, 1, 3, 72, 4, 1, 3, 73,
- 4, 1, 3, 74, 4, 1, 3, 75, 4, 1, 3, 76,
- 4, 1, 3, 77, 4, 1,
-};
-
-static const unsigned short nameprep_id11_prohibited_imap[] = {
- 68, 196, 196, 324, 196, 196, 196, 452,
- 196, 196, 196, 580, 196, 196, 196, 580,
- 196, 196, 196, 580, 196, 196, 196, 580,
- 196, 196, 196, 580, 196, 196, 196, 580,
- 196, 196, 196, 580, 196, 196, 196, 580,
- 196, 196, 196, 580, 196, 196, 196, 580,
- 196, 196, 196, 580, 196, 196, 196, 580,
- 708, 196, 196, 580, 836, 836, 836, 836,
- 836, 836, 836, 836, 0, 1, 0, 0,
- 0, 0, 2, 0, 0, 0, 0, 0,
- 0, 3, 4, 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, 5, 0, 0, 6, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 7, 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, 8, 5, 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, 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, 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, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 10,
- 0, 0, 0, 11, 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, 12, 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, 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, 13, 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, 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, 13, 14, 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, 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, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9, 9, 9, 9, 9,
- 9, 9, 9, 9,
-};
-
-static const struct {
- unsigned char bm[16];
-} nameprep_id11_prohibited_bitmap[] = {
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 255,255,255,255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0,
- }},
- {{
- 0,128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 255,199, 0, 0, 0,255, 0, 0, 0, 0, 0,128, 14,252, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,255, 15,
- }},
- {{
- 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,255,255,255,255, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,254,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,248, 7,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,192,
- }},
- {{
- 2, 0, 0, 0,255,255,255,255,255,255,255,255,255,255,255,255,
- }},
-};
-
-static const unsigned short nameprep_id11_unassigned_imap[] = {
- 68, 196, 324, 452, 580, 708, 708, 836,
- 964, 964, 1092, 1220, 708, 708, 708, 1348,
- 708, 708, 708, 1348, 708, 708, 708, 1348,
- 708, 708, 708, 1348, 708, 708, 708, 1348,
- 708, 708, 708, 1348, 708, 708, 708, 1348,
- 708, 708, 708, 1348, 708, 708, 708, 1348,
- 708, 708, 708, 1348, 708, 708, 708, 1348,
- 1476, 708, 708, 1348, 964, 964, 964, 964,
- 964, 964, 964, 964, 0, 0, 0, 0,
- 1, 2, 3, 4, 0, 5, 6, 7,
- 8, 9, 10, 11, 12, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22,
- 23, 24, 25, 26, 27, 28, 29, 30,
- 31, 32, 33, 34, 35, 0, 0, 0,
- 36, 37, 38, 39, 40, 41, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 0, 42, 43, 44, 45, 46, 47, 48,
- 0, 0, 0, 49, 50, 51, 0, 0,
- 52, 53, 54, 55, 0, 0, 0, 0,
- 0, 0, 12, 12, 12, 12, 12, 12,
- 12, 56, 0, 57, 58, 59, 60, 61,
- 62, 63, 64, 65, 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, 66,
- 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,
- 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,
- 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, 67, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 68, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 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, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 69, 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, 0, 0, 0, 0,
- 70, 12, 71, 72, 0, 0, 73, 74,
- 75, 76, 35, 77, 12, 12, 12, 12,
- 12, 12, 78, 12, 79, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 0, 80, 81, 82,
- 12, 12, 12, 12, 83, 84, 85, 0,
- 0, 86, 0, 87, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 88, 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, 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, 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, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 89, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 0, 0, 0, 0,
- 90, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 88, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 88, 91, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12, 12, 12, 12, 12,
- 12, 12, 12, 12,
-};
-
-static const struct {
- unsigned char bm[16];
-} nameprep_id11_unassigned_bitmap[] = {
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 2, 0,240,255,255,255, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0,192, 0, 0, 0, 0, 0, 0, 0,128,255,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,255,255, 0, 0,207,187,
- }},
- {{
- 15, 40, 0, 0, 4, 0, 0, 0, 0,128, 0, 0, 0, 0,128,255,
- }},
- {{
- 128, 0, 0, 0, 0, 0, 0, 0, 0,128, 0, 0, 0, 0,192,252,
- }},
- {{
- 0, 0,255,255,255,255, 1, 0, 0, 0,128, 1, 1, 0, 0, 0,
- }},
- {{
- 0,249, 1, 0, 4, 0, 0, 4,224,255, 0, 0, 0,248,224,255,
- }},
- {{
- 255,239,255,119, 1, 0, 0,248, 0, 0,192,255, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,192, 0,128,
- }},
- {{
- 0, 64, 0, 0, 0,224, 0, 0, 0,248,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0,252,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 17, 0, 0, 0, 0, 0, 0, 12, 0,192,224, 0, 0, 0,254,255,
- }},
- {{
- 17, 96, 6, 0, 0, 2, 58, 44, 96,198,127, 79, 48, 0, 0,248,
- }},
- {{
- 27,120, 6, 0, 0, 2,146, 44,120,198,255,161, 63, 0,224,255,
- }},
- {{
- 17, 80, 4, 0, 0, 2, 18, 12, 64,196,254,255, 62, 0,255,255,
- }},
- {{
- 17, 96, 6, 0, 0, 2, 50, 12,112,198, 63, 79, 60, 0,254,255,
- }},
- {{
- 19, 56,194, 41,231, 56, 64, 60, 56,194,127,255,127, 0,248,255,
- }},
- {{
- 17, 32, 2, 0, 0, 2, 16, 60, 32,194,159,255, 60, 0,255,255,
- }},
- {{
- 19, 32, 2, 0, 0, 2, 16, 60, 32,194,159,191, 60, 0,255,255,
- }},
- {{
- 19, 32, 2, 0, 0, 2, 0, 60, 48,194,127,255, 60, 0,255,255,
- }},
- {{
- 19, 0,128, 3, 0, 0, 4,208,128,123,160, 0,255,255,227,255,
- }},
- {{
- 1, 0, 0, 0, 0, 0, 0,120, 0, 0, 0,240,255,255,255,255,
- }},
- {{
- 105,218, 15, 1, 81, 19, 0,196,160,192, 0,204,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,248, 1, 0,
- }},
- {{
- 0,240, 0, 1, 0, 0, 0, 32, 0, 96,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0, 4, 9, 56,252, 0, 0, 0,252,255,255,255,255,
- }},
- {{
- 255,255,255,255, 0, 0, 0, 0,192,255, 0, 0, 0, 0, 0,246,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,124, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0,248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,252,
- }},
- {{
- 128, 0, 0, 0, 0, 0, 0, 0,128,194,128,194, 0, 0, 0, 0,
- }},
- {{
- 128,194, 0, 0, 0,128,194,128,194,128,128, 0, 0,128, 0, 0,
- }},
- {{
- 0,128,194,128, 0, 0, 0, 0,128, 0, 0,248, 1, 0, 0,224,
- }},
- {{
- 255,255,255,255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,224,255,
- }},
- {{
- 1, 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,128,255,
- }},
- {{
- 0, 0, 0,224, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,254,255,
- }},
- {{
- 0, 32,224,255, 0, 0,128,255, 0, 0,240,255, 0, 32,242,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,224, 0,252,255,255,
- }},
- {{
- 0,128, 0,252, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,255,
- }},
- {{
- 0, 0, 0, 0, 0,252,255,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0,240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,252,
- }},
- {{
- 0, 0,192,192, 0, 0, 0, 0,192,192, 0, 85, 0, 0, 0,192,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 32, 0, 32, 0, 48, 16, 0, 0, 35,128,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,120,127,240, 3, 12, 0,
- }},
- {{
- 0,128,255,255, 0, 0,252,255,255,255, 0, 0, 0,248,255,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 24, 0,240, 7, 0, 0, 0, 0, 0,
- }},
- {{
- 240,255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0,128,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0,128,255,255,255, 0,248,255,255, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,128,
- }},
- {{
- 0, 0, 48, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,192,
- }},
- {{
- 0,252,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 33, 12, 0, 0, 0, 1, 0, 0, 0, 80,184,128, 1, 0, 0, 0,
- }},
- {{
- 0, 0,224, 0, 0, 0, 1,128,255,255, 0, 0, 0,240, 0, 0,
- }},
- {{
- 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,240,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,192,255,255,255, 0,240,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0,128, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 31, 0, 0, 0, 0,224, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0,128, 0, 0, 0, 0, 0,255,255,255,255,255,255,255, 0, 0,
- }},
- {{
- 0, 0, 0,224, 0, 0, 0, 0,240,255, 1, 0, 0, 0, 0,112,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0,240, 0, 0, 0, 0, 0,128,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,128, 7,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,192, 0, 0, 0,128,
- }},
- {{
- 0, 0, 0, 0, 0, 0,192,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0,192,255,255,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 0,224, 0, 0, 0, 0, 0, 0,128,255,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0,240,255,255,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0, 0,192, 0, 0, 0, 0, 0, 0, 0,248,255,255,
- }},
- {{
- 128,255, 7, 31, 0, 0,128,160, 36, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0,252,255,255,255, 7, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0,255,255, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 3, 0, 0, 0, 0, 0, 0,255, 0, 0, 0, 0, 0,224,
- }},
- {{
- 0, 0,255,255,240,255, 0, 0,128, 1, 8, 0,128,240, 32, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0,128, 3, 3, 3,227,128,128,255, 1,
- }},
- {{
- 0, 0, 0,128,240,255, 0, 0, 0,248,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0,192, 0, 0, 0, 0,192,255,255,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,192,255,
- }},
- {{
- 0, 0, 0, 0,128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,192,255,255,255,255,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 32,155, 33, 0, 20, 18, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 64, 24, 32, 32, 0, 0, 0,132,160, 3, 2, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0,240, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 63,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,128,255,255,255,255,255,
- }},
- {{
- 0, 0, 0,192,255,255,255,255,255,255,255,255,255,255,255,255,
- }},
- {{
- 253,255,255,255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
-};
-
-static const unsigned short nameprep_id11_bidi_imap[] = {
- 272, 400, 528, 656, 784, 912, 912, 912,
- 912, 1040, 1168, 912, 912, 1296, 912, 1424,
- 1552, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1808, 1680, 1680,
- 912, 912, 912, 912, 912, 912, 912, 912,
- 912, 912, 1936, 1680, 1680, 1680, 1680, 2064,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 1680, 1680, 1680, 1680, 1680, 1680, 1680, 1680,
- 912, 912, 912, 912, 912, 912, 912, 912,
- 912, 912, 912, 912, 912, 912, 912, 2192,
- 912, 912, 912, 912, 912, 912, 912, 912,
- 912, 912, 912, 912, 912, 912, 912, 2192,
- 0, 0, 1, 1, 0, 2, 3, 3,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 5, 6, 4, 4, 7, 8, 9,
- 0, 0, 0, 10, 11, 12, 13, 14,
- 4, 4, 4, 4, 15, 4, 13, 16,
- 17, 18, 19, 20, 21, 22, 23, 24,
- 25, 26, 27, 28, 29, 29, 30, 31,
- 32, 33, 0, 0, 29, 34, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 35, 36, 37, 38, 39, 40, 41, 42,
- 43, 44, 45, 46, 47, 48, 49, 50,
- 39, 51, 41, 52, 53, 54, 55, 56,
- 57, 58, 59, 60, 61, 62, 63, 60,
- 61, 64, 65, 60, 66, 67, 68, 69,
- 20, 70, 71, 0, 72, 73, 74, 0,
- 75, 76, 77, 78, 79, 80, 81, 0,
- 4, 82, 83, 0, 0, 4, 84, 85,
- 4, 4, 86, 4, 4, 87, 4, 88,
- 89, 4, 90, 4, 91, 92, 93, 13,
- 92, 4, 94, 95, 0, 4, 4, 96,
- 20, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 97, 1, 4, 4, 98,
- 99, 100, 101, 102, 4, 103, 104, 105,
- 106, 4, 4, 83, 4, 107, 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,
- 4, 4, 4, 4, 108, 4, 4, 88,
- 109, 4, 110, 111, 4, 112, 113, 114,
- 115, 0, 0, 116, 0, 0, 0, 0,
- 117, 118, 119, 4, 120, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 121, 4, 122, 123, 0, 0, 0,
- 0, 0, 0, 0, 124, 4, 4, 105,
- 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,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 125, 126, 20, 4, 127, 20, 4, 128,
- 129, 130, 4, 4, 13, 83, 0, 6,
- 131, 4, 120, 132, 4, 98, 133, 134,
- 4, 4, 4, 135, 4, 4, 111, 134,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 14, 0, 0,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 136, 0, 0,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 137, 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,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 120, 0, 0,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 138, 4, 139, 0, 0, 0, 0,
- 140, 141, 142, 29, 29, 143, 144, 29,
- 29, 29, 29, 29, 29, 29, 29, 29,
- 29, 145, 146, 29, 147, 29, 148, 149,
- 0, 0, 0, 150, 29, 29, 29, 151,
- 0, 1, 1, 152, 4, 134, 153, 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,
- 134, 154, 139, 0, 0, 0, 0, 0,
- 4, 155, 156, 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, 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, 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, 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,
- 4, 4, 4, 4, 4, 4, 4, 14,
- 4, 157, 4, 158, 159, 160, 111, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 4, 4, 161, 4, 162, 163, 164, 4,
- 165, 166, 167, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 168, 4, 4,
- 4, 4, 4, 4, 4, 4, 105, 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, 0,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 97, 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, 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, 0,
- 0, 0, 0, 0, 0, 0, 0, 0,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 111, 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,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 4,
- 4, 4, 4, 4, 4, 4, 4, 111,
-};
-
-static const struct {
- unsigned char tbl[32];
-} nameprep_id11_bidi_table[] = {
- {{
- 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, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 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, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
- 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 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, 2, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 2, 0, 2, 2, 2, 0, 2, 0, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 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,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 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, 1, 0,
- }},
- {{
- 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 0, 1,
- 1, 1, 1, 1, 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, 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, 0, 0,
- }},
- {{
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0,
- }},
- {{
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2,
- }},
- {{
- 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 2,
- 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2,
- 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
- 0, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2,
- }},
- {{
- 2, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 2, 0, 2,
- }},
- {{
- 2, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2,
- 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
- 0, 2, 2, 0, 2, 2, 0, 2, 2, 0, 0, 0, 0, 2, 2,
- }},
- {{
- 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0,
- 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2,
- 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
- 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2,
- }},
- {{
- 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
- 0, 2, 2, 0, 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 0,
- }},
- {{
- 2, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 2, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2,
- 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 0, 2, 0, 2, 2,
- }},
- {{
- 0, 0, 0, 2, 2, 0, 0, 0, 2, 2, 2, 0, 0, 0, 2, 2, 2,
- 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 2, 2,
- }},
- {{
- 0, 2, 2, 0, 0, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2,
- 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 2, 2, 2, 2, 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,
- }},
- {{
- 2, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2,
- 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 0, 0, 2, 2, 0, 2, 2, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2,
- }},
- {{
- 2, 0, 0, 0, 0, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2,
- 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0,
- }},
- {{
- 0, 2, 2, 0, 2, 0, 0, 2, 2, 0, 2, 0, 0, 2, 0, 0, 0,
- 0, 0, 0, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 0, 2, 2, 2, 0, 2, 0, 2, 0, 0, 2, 2, 0, 2, 2, 2, 2,
- 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
- }},
- {{
- 0, 0, 0, 0, 0, 2, 0, 0, 2, 2, 2, 2, 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, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 0, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 0, 0, 0, 0,
- 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 2,
- }},
- {{
- 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2,
- 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0,
- }},
- {{
- 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2,
- 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2,
- 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 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, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 0, 2, 0, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0,
- }},
- {{
- 0, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2,
- 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0,
- 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 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,
- 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
- }},
- {{
- 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 2, 0, 2, 0, 2, 0, 2, 2, 2, 2, 0, 2, 2,
- 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2,
- }},
- {{
- 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 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, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 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, 2, 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, 2, 2, 2, 2,
- }},
- {{
- 0, 0, 0, 0, 0, 2, 2, 2, 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, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0,
- 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2,
- }},
- {{
- 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 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,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0, 1,
- }},
- {{
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0,
- }},
- {{
- 1, 1, 0, 1, 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,
- }},
- {{
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 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, 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, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 0,
- 0, 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, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
- 1, 1, 1, 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, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0,
- 0, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- }},
- {{
- 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2,
- }},
- {{
- 0, 0, 2, 0, 0, 2, 2, 0, 0, 2, 2, 2, 2, 0, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2,
- }},
- {{
- 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2,
- 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0,
- }},
- {{
- 2, 2, 2, 2, 2, 0, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2,
- 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
- {{
- 2, 2, 2, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- }},
-};
-
-static const unsigned char nameprep_id11_bidi_data[] = {
- idn_biditype_others,
- idn_biditype_r_al,
- idn_biditype_l,
-};
-
diff --git a/netwerk/dns/nsIDNService.cpp b/netwerk/dns/nsIDNService.cpp
index 49beecbb3..31ba12b4c 100644
--- a/netwerk/dns/nsIDNService.cpp
+++ b/netwerk/dns/nsIDNService.cpp
@@ -17,7 +17,6 @@
#include "nsISupportsPrimitives.h"
#include "punycode.h"
-#ifdef IDNA2008
// Currently we use the non-transitional processing option -- see
// http://unicode.org/reports/tr46/
// To switch to transitional processing, change the value of this flag
@@ -27,7 +26,6 @@ const bool kIDNA2008_TransitionalProcessing = false;
#include "ICUUtils.h"
#include "unicode/uscript.h"
-#endif
using namespace mozilla::unicode;
@@ -136,32 +134,19 @@ nsIDNService::nsIDNService()
: mShowPunycode(false)
, mIDNUseWhitelist(false)
{
-#ifdef IDNA2008
uint32_t IDNAOptions = UIDNA_CHECK_BIDI | UIDNA_CHECK_CONTEXTJ;
if (!kIDNA2008_TransitionalProcessing) {
IDNAOptions |= UIDNA_NONTRANSITIONAL_TO_UNICODE;
}
UErrorCode errorCode = U_ZERO_ERROR;
mIDNA = uidna_openUTS46(IDNAOptions, &errorCode);
-#else
- if (idn_success != idn_nameprep_create(nullptr, &mNamePrepHandle))
- mNamePrepHandle = nullptr;
-
- mNormalizer = do_GetService(NS_UNICODE_NORMALIZER_CONTRACTID);
- /* member initializers and constructor code */
-#endif
}
nsIDNService::~nsIDNService()
{
-#ifdef IDNA2008
uidna_close(mIDNA);
-#else
- idn_nameprep_destroy(mNamePrepHandle);
-#endif
}
-#ifdef IDNA2008
nsresult
nsIDNService::IDNA2008ToUnicode(const nsACString& input, nsAString& output)
{
@@ -226,7 +211,6 @@ nsIDNService::IDNA2008StringPrep(const nsAString& input,
return rv;
}
-#endif
NS_IMETHODIMP nsIDNService::ConvertUTF8toACE(const nsACString & input, nsACString & ace)
{
@@ -486,21 +470,6 @@ static nsresult utf16ToUcs4(const nsAString& in,
return NS_OK;
}
-#ifndef IDNA2008
-static void ucs4toUtf16(const uint32_t *in, nsAString& out)
-{
- while (*in) {
- if (!IS_IN_BMP(*in)) {
- out.Append((char16_t) H_SURROGATE(*in));
- out.Append((char16_t) L_SURROGATE(*in));
- }
- else
- out.Append((char16_t) *in);
- in++;
- }
-}
-#endif
-
static nsresult punycode(const nsAString& in, nsACString& out)
{
uint32_t ucs4Buf[kMaxDNSNodeLen + 1];
@@ -551,74 +520,12 @@ static nsresult punycode(const nsAString& in, nsACString& out)
// any unassigned Unicode points and if any are found return an error.
// This is described in section 7.
//
+// => All this is handled by ICU's StringPrep().
+//
nsresult nsIDNService::stringPrep(const nsAString& in, nsAString& out,
stringPrepFlag flag)
{
-#ifdef IDNA2008
return IDNA2008StringPrep(in, out, flag);
-#else
- if (!mNamePrepHandle || !mNormalizer)
- return NS_ERROR_FAILURE;
-
- uint32_t ucs4Buf[kMaxDNSNodeLen + 1];
- uint32_t ucs4Len;
- nsresult rv = utf16ToUcs4(in, ucs4Buf, kMaxDNSNodeLen, &ucs4Len);
- NS_ENSURE_SUCCESS(rv, rv);
-
- // map
- idn_result_t idn_err;
-
- uint32_t namePrepBuf[kMaxDNSNodeLen * 3]; // map up to three characters
- idn_err = idn_nameprep_map(mNamePrepHandle, (const uint32_t *) ucs4Buf,
- (uint32_t *) namePrepBuf, kMaxDNSNodeLen * 3);
- NS_ENSURE_TRUE(idn_err == idn_success, NS_ERROR_MALFORMED_URI);
-
- nsAutoString namePrepStr;
- ucs4toUtf16(namePrepBuf, namePrepStr);
- if (namePrepStr.Length() >= kMaxDNSNodeLen)
- return NS_ERROR_MALFORMED_URI;
-
- // normalize
- nsAutoString normlizedStr;
- rv = mNormalizer->NormalizeUnicodeNFKC(namePrepStr, normlizedStr);
- if (normlizedStr.Length() >= kMaxDNSNodeLen)
- return NS_ERROR_MALFORMED_URI;
-
- // set the result string
- out.Assign(normlizedStr);
-
- if (flag == eStringPrepIgnoreErrors) {
- return NS_OK;
- }
-
- // prohibit
- const uint32_t *found = nullptr;
- idn_err = idn_nameprep_isprohibited(mNamePrepHandle,
- (const uint32_t *) ucs4Buf, &found);
- if (idn_err != idn_success || found) {
- rv = NS_ERROR_MALFORMED_URI;
- } else {
- // check bidi
- idn_err = idn_nameprep_isvalidbidi(mNamePrepHandle,
- (const uint32_t *) ucs4Buf, &found);
- if (idn_err != idn_success || found) {
- rv = NS_ERROR_MALFORMED_URI;
- } else if (flag == eStringPrepForUI) {
- // check unassigned code points
- idn_err = idn_nameprep_isunassigned(mNamePrepHandle,
- (const uint32_t *) ucs4Buf, &found);
- if (idn_err != idn_success || found) {
- rv = NS_ERROR_MALFORMED_URI;
- }
- }
- }
-
- if (flag == eStringPrepForDNS && NS_FAILED(rv)) {
- out.Truncate();
- }
-
- return rv;
-#endif
}
nsresult nsIDNService::stringPrepAndACE(const nsAString& in, nsACString& out,
@@ -709,31 +616,8 @@ nsresult nsIDNService::decodeACE(const nsACString& in, nsACString& out,
}
nsAutoString utf16;
-#ifdef IDNA2008
nsresult result = IDNA2008ToUnicode(in, utf16);
NS_ENSURE_SUCCESS(result, result);
-#else
- // RFC 3490 - 4.2 ToUnicode
- // The ToUnicode output never contains more code points than its input.
- punycode_uint output_length = in.Length() - kACEPrefixLen + 1;
- auto *output = new punycode_uint[output_length];
- NS_ENSURE_TRUE(output, NS_ERROR_OUT_OF_MEMORY);
-
- enum punycode_status status = punycode_decode(in.Length() - kACEPrefixLen,
- PromiseFlatCString(in).get() + kACEPrefixLen,
- &output_length,
- output,
- nullptr);
- if (status != punycode_success) {
- delete [] output;
- return NS_ERROR_MALFORMED_URI;
- }
-
- // UCS4 -> UTF8
- output[output_length] = 0;
- ucs4toUtf16(output, utf16);
- delete [] output;
-#endif
if (flag != eStringPrepForUI || isLabelSafe(utf16)) {
CopyUTF16toUTF8(utf16, out);
} else {
diff --git a/netwerk/dns/nsIDNService.h b/netwerk/dns/nsIDNService.h
index 19aa94da0..82a05021d 100644
--- a/netwerk/dns/nsIDNService.h
+++ b/netwerk/dns/nsIDNService.h
@@ -12,12 +12,7 @@
#include "nsUnicodeScriptCodes.h"
#include "nsWeakReference.h"
-#ifdef IDNA2008
#include "unicode/uidna.h"
-#else
-#include "nsIUnicodeNormalizer.h"
-#include "nsIDNKitInterface.h"
-#endif
#include "nsString.h"
@@ -151,7 +146,6 @@ private:
bool illegalScriptCombo(mozilla::unicode::Script script,
int32_t& savedScript);
-#ifdef IDNA2008
/**
* Convert a DNS label from ASCII to Unicode using IDNA2008
*/
@@ -164,10 +158,6 @@ private:
stringPrepFlag flag);
UIDNA* mIDNA;
-#else
- idn_nameprep_t mNamePrepHandle;
- nsCOMPtr<nsIUnicodeNormalizer> mNormalizer;
-#endif
nsXPIDLString mIDNBlacklist;
/**
diff --git a/netwerk/ipc/NeckoChannelParams.ipdlh b/netwerk/ipc/NeckoChannelParams.ipdlh
index 4f4dcf6a9..bb7562c64 100644
--- a/netwerk/ipc/NeckoChannelParams.ipdlh
+++ b/netwerk/ipc/NeckoChannelParams.ipdlh
@@ -20,6 +20,7 @@ using struct mozilla::void_t from "ipc/IPCMessageUtils.h";
using RequestHeaderTuples from "mozilla/net/PHttpChannelParams.h";
using struct nsHttpAtom from "nsHttp.h";
using class nsHttpResponseHead from "nsHttpResponseHead.h";
+using class mozilla::TimeStamp from "mozilla/TimeStamp.h";
namespace mozilla {
namespace net {
@@ -134,6 +135,12 @@ struct HttpChannelOpenArgs
nsCString channelId;
uint64_t contentWindowId;
nsCString preferredAlternativeType;
+ TimeStamp launchServiceWorkerStart;
+ TimeStamp launchServiceWorkerEnd;
+ TimeStamp dispatchFetchEventStart;
+ TimeStamp dispatchFetchEventEnd;
+ TimeStamp handleFetchEventStart;
+ TimeStamp handleFetchEventEnd;
};
struct HttpChannelConnectArgs
diff --git a/netwerk/protocol/ftp/nsFtpConnectionThread.cpp b/netwerk/protocol/ftp/nsFtpConnectionThread.cpp
index 1119fcff5..2ae12846a 100644
--- a/netwerk/protocol/ftp/nsFtpConnectionThread.cpp
+++ b/netwerk/protocol/ftp/nsFtpConnectionThread.cpp
@@ -45,10 +45,6 @@
#include "nsIAuthPrompt2.h"
#include "nsIFTPChannelParentInternal.h"
-#ifdef MOZ_WIDGET_GONK
-#include "NetStatistics.h"
-#endif
-
using namespace mozilla;
using namespace mozilla::net;
@@ -1619,13 +1615,6 @@ nsFtpState::Init(nsFtpChannel *channel)
// initialize counter for network metering
mCountRecv = 0;
-#ifdef MOZ_WIDGET_GONK
- nsCOMPtr<nsINetworkInfo> activeNetworkInfo;
- GetActiveNetworkInfo(activeNetworkInfo);
- mActiveNetworkInfo =
- new nsMainThreadPtrHolder<nsINetworkInfo>(activeNetworkInfo);
-#endif
-
mKeepRunning = true;
mSuppliedEntityID = channel->EntityID();
@@ -2104,43 +2093,7 @@ nsFtpState::ReadSegments(nsWriteSegmentFun writer, void *closure,
nsresult
nsFtpState::SaveNetworkStats(bool enforce)
{
-#ifdef MOZ_WIDGET_GONK
- // Obtain app id
- uint32_t appId;
- bool isInBrowser;
- NS_GetAppInfo(mChannel, &appId, &isInBrowser);
-
- // Check if active network and appid are valid.
- if (!mActiveNetworkInfo || appId == NECKO_NO_APP_ID) {
- return NS_OK;
- }
-
- if (mCountRecv <= 0) {
- // There is no traffic, no need to save.
- return NS_OK;
- }
-
- // If |enforce| is false, the traffic amount is saved
- // only when the total amount exceeds the predefined
- // threshold.
- if (!enforce && mCountRecv < NETWORK_STATS_THRESHOLD) {
- return NS_OK;
- }
-
- // Create the event to save the network statistics.
- // the event is then dispathed to the main thread.
- RefPtr<Runnable> event =
- new SaveNetworkStatsEvent(appId, isInBrowser, mActiveNetworkInfo,
- mCountRecv, 0, false);
- NS_DispatchToMainThread(event);
-
- // Reset the counters after saving.
- mCountRecv = 0;
-
- return NS_OK;
-#else
return NS_ERROR_NOT_IMPLEMENTED;
-#endif
}
NS_IMETHODIMP
diff --git a/netwerk/protocol/ftp/nsFtpConnectionThread.h b/netwerk/protocol/ftp/nsFtpConnectionThread.h
index dd48da562..b4e71bd10 100644
--- a/netwerk/protocol/ftp/nsFtpConnectionThread.h
+++ b/netwerk/protocol/ftp/nsFtpConnectionThread.h
@@ -17,11 +17,6 @@
#include "nsFtpControlConnection.h"
#include "nsIProtocolProxyCallback.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsINetworkInterface.h"
-#include "nsProxyRelease.h"
-#endif
-
// ftp server types
#define FTP_GENERIC_TYPE 0
#define FTP_UNIX_TYPE 1
@@ -215,11 +210,7 @@ private:
bool mDeferredCallbackPending;
// These members are used for network per-app metering (bug 855948)
-// Currently, they are only available on gonk.
uint64_t mCountRecv;
-#ifdef MOZ_WIDGET_GONK
- nsMainThreadPtrHandle<nsINetworkInfo> mActiveNetworkInfo;
-#endif
nsresult SaveNetworkStats(bool);
void CountRecvBytes(uint64_t recvBytes)
{
diff --git a/netwerk/protocol/http/HttpBaseChannel.cpp b/netwerk/protocol/http/HttpBaseChannel.cpp
index 278c94db0..d161f9a43 100644
--- a/netwerk/protocol/http/HttpBaseChannel.cpp
+++ b/netwerk/protocol/http/HttpBaseChannel.cpp
@@ -105,6 +105,7 @@ HttpBaseChannel::HttpBaseChannel()
, mHttpHandler(gHttpHandler)
, mReferrerPolicy(REFERRER_POLICY_NO_REFERRER_WHEN_DOWNGRADE)
, mRedirectCount(0)
+ , mInternalRedirectCount(0)
, mForcePending(false)
, mCorsIncludeCredentials(false)
, mCorsMode(nsIHttpChannelInternal::CORS_MODE_NO_CORS)
@@ -3128,12 +3129,6 @@ HttpBaseChannel::SetupReplacementChannel(nsIURI *newURI,
// convey the mAllowPipelining and mAllowSTS flags
httpChannel->SetAllowPipelining(mAllowPipelining);
httpChannel->SetAllowSTS(mAllowSTS);
- // convey the new redirection limit
- // make sure we don't underflow
- uint32_t redirectionLimit = mRedirectionLimit
- ? mRedirectionLimit - 1
- : 0;
- httpChannel->SetRedirectionLimit(redirectionLimit);
// convey the Accept header value
{
@@ -3215,23 +3210,40 @@ HttpBaseChannel::SetupReplacementChannel(nsIURI *newURI,
do_QueryInterface(static_cast<nsIHttpChannel*>(this)));
if (oldTimedChannel && newTimedChannel) {
newTimedChannel->SetTimingEnabled(mTimingEnabled);
- newTimedChannel->SetRedirectCount(mRedirectCount + 1);
+
+ if (redirectFlags & nsIChannelEventSink::REDIRECT_INTERNAL) {
+ int8_t newCount = mInternalRedirectCount + 1;
+ newTimedChannel->SetInternalRedirectCount(
+ std::max(newCount, mInternalRedirectCount));
+ } else {
+ int8_t newCount = mRedirectCount + 1;
+ newTimedChannel->SetRedirectCount(
+ std::max(newCount, mRedirectCount));
+ }
// If the RedirectStart is null, we will use the AsyncOpen value of the
// previous channel (this is the first redirect in the redirects chain).
if (mRedirectStartTimeStamp.IsNull()) {
- TimeStamp asyncOpen;
- oldTimedChannel->GetAsyncOpen(&asyncOpen);
- newTimedChannel->SetRedirectStart(asyncOpen);
- }
- else {
+ // Only do this for real redirects. Internal redirects should be hidden.
+ if (!(redirectFlags & nsIChannelEventSink::REDIRECT_INTERNAL)) {
+ TimeStamp asyncOpen;
+ oldTimedChannel->GetAsyncOpen(&asyncOpen);
+ newTimedChannel->SetRedirectStart(asyncOpen);
+ }
+ } else {
newTimedChannel->SetRedirectStart(mRedirectStartTimeStamp);
}
- // The RedirectEnd timestamp is equal to the previous channel response end.
- TimeStamp prevResponseEnd;
- oldTimedChannel->GetResponseEnd(&prevResponseEnd);
- newTimedChannel->SetRedirectEnd(prevResponseEnd);
+ // For internal redirects just propagate the last redirect end time
+ // forward. Otherwise the new redirect end time is the last response
+ // end time.
+ TimeStamp newRedirectEnd;
+ if (redirectFlags & nsIChannelEventSink::REDIRECT_INTERNAL) {
+ oldTimedChannel->GetRedirectEnd(&newRedirectEnd);
+ } else {
+ oldTimedChannel->GetResponseEnd(&newRedirectEnd);
+ }
+ newTimedChannel->SetRedirectEnd(newRedirectEnd);
nsAutoString initiatorType;
oldTimedChannel->GetInitiatorType(initiatorType);
@@ -3253,6 +3265,16 @@ HttpBaseChannel::SetupReplacementChannel(nsIURI *newURI,
mAllRedirectsPassTimingAllowCheck &&
oldTimedChannel->TimingAllowCheck(principal));
}
+
+ // Propagate service worker measurements across redirects. The
+ // PeformanceResourceTiming.workerStart API expects to see the
+ // worker start time after a redirect.
+ newTimedChannel->SetLaunchServiceWorkerStart(mLaunchServiceWorkerStart);
+ newTimedChannel->SetLaunchServiceWorkerEnd(mLaunchServiceWorkerEnd);
+ newTimedChannel->SetDispatchFetchEventStart(mDispatchFetchEventStart);
+ newTimedChannel->SetDispatchFetchEventEnd(mDispatchFetchEventEnd);
+ newTimedChannel->SetHandleFetchEventStart(mHandleFetchEventStart);
+ newTimedChannel->SetHandleFetchEventEnd(mHandleFetchEventEnd);
}
// Pass the preferred alt-data type on to the new channel.
@@ -3318,20 +3340,34 @@ HttpBaseChannel::GetAsyncOpen(TimeStamp* _retval) {
* redirects. This check must be done by the consumers.
*/
NS_IMETHODIMP
-HttpBaseChannel::GetRedirectCount(uint16_t *aRedirectCount)
+HttpBaseChannel::GetRedirectCount(uint8_t *aRedirectCount)
{
*aRedirectCount = mRedirectCount;
return NS_OK;
}
NS_IMETHODIMP
-HttpBaseChannel::SetRedirectCount(uint16_t aRedirectCount)
+HttpBaseChannel::SetRedirectCount(uint8_t aRedirectCount)
{
mRedirectCount = aRedirectCount;
return NS_OK;
}
NS_IMETHODIMP
+HttpBaseChannel::GetInternalRedirectCount(uint8_t *aRedirectCount)
+{
+ *aRedirectCount = mInternalRedirectCount;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::SetInternalRedirectCount(uint8_t aRedirectCount)
+{
+ mInternalRedirectCount = aRedirectCount;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
HttpBaseChannel::GetRedirectStart(TimeStamp* _retval)
{
*_retval = mRedirectStartTimeStamp;
@@ -3431,6 +3467,84 @@ HttpBaseChannel::TimingAllowCheck(nsIPrincipal *aOrigin, bool *_retval)
}
NS_IMETHODIMP
+HttpBaseChannel::GetLaunchServiceWorkerStart(TimeStamp* _retval) {
+ MOZ_ASSERT(_retval);
+ *_retval = mLaunchServiceWorkerStart;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::SetLaunchServiceWorkerStart(TimeStamp aTimeStamp) {
+ mLaunchServiceWorkerStart = aTimeStamp;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::GetLaunchServiceWorkerEnd(TimeStamp* _retval) {
+ MOZ_ASSERT(_retval);
+ *_retval = mLaunchServiceWorkerEnd;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::SetLaunchServiceWorkerEnd(TimeStamp aTimeStamp) {
+ mLaunchServiceWorkerEnd = aTimeStamp;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::GetDispatchFetchEventStart(TimeStamp* _retval) {
+ MOZ_ASSERT(_retval);
+ *_retval = mDispatchFetchEventStart;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::SetDispatchFetchEventStart(TimeStamp aTimeStamp) {
+ mDispatchFetchEventStart = aTimeStamp;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::GetDispatchFetchEventEnd(TimeStamp* _retval) {
+ MOZ_ASSERT(_retval);
+ *_retval = mDispatchFetchEventEnd;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::SetDispatchFetchEventEnd(TimeStamp aTimeStamp) {
+ mDispatchFetchEventEnd = aTimeStamp;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::GetHandleFetchEventStart(TimeStamp* _retval) {
+ MOZ_ASSERT(_retval);
+ *_retval = mHandleFetchEventStart;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::SetHandleFetchEventStart(TimeStamp aTimeStamp) {
+ mHandleFetchEventStart = aTimeStamp;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::GetHandleFetchEventEnd(TimeStamp* _retval) {
+ MOZ_ASSERT(_retval);
+ *_retval = mHandleFetchEventEnd;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+HttpBaseChannel::SetHandleFetchEventEnd(TimeStamp aTimeStamp) {
+ mHandleFetchEventEnd = aTimeStamp;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
HttpBaseChannel::GetDomainLookupStart(TimeStamp* _retval) {
*_retval = mTransactionTimings.domainLookupStart;
return NS_OK;
@@ -3520,6 +3634,12 @@ HttpBaseChannel::Get##name##Time(PRTime* _retval) { \
IMPL_TIMING_ATTR(ChannelCreation)
IMPL_TIMING_ATTR(AsyncOpen)
+IMPL_TIMING_ATTR(LaunchServiceWorkerStart)
+IMPL_TIMING_ATTR(LaunchServiceWorkerEnd)
+IMPL_TIMING_ATTR(DispatchFetchEventStart)
+IMPL_TIMING_ATTR(DispatchFetchEventEnd)
+IMPL_TIMING_ATTR(HandleFetchEventStart)
+IMPL_TIMING_ATTR(HandleFetchEventEnd)
IMPL_TIMING_ATTR(DomainLookupStart)
IMPL_TIMING_ATTR(DomainLookupEnd)
IMPL_TIMING_ATTR(ConnectStart)
diff --git a/netwerk/protocol/http/HttpBaseChannel.h b/netwerk/protocol/http/HttpBaseChannel.h
index c8184a601..9aa696a70 100644
--- a/netwerk/protocol/http/HttpBaseChannel.h
+++ b/netwerk/protocol/http/HttpBaseChannel.h
@@ -506,7 +506,9 @@ protected:
// the HTML file.
nsString mInitiatorType;
// Number of redirects that has occurred.
- int16_t mRedirectCount;
+ int8_t mRedirectCount;
+ // Number of internal redirects that has occurred.
+ int8_t mInternalRedirectCount;
// A time value equal to the starting time of the fetch that initiates the
// redirect.
mozilla::TimeStamp mRedirectStartTimeStamp;
@@ -519,6 +521,12 @@ protected:
TimeStamp mAsyncOpenTime;
TimeStamp mCacheReadStart;
TimeStamp mCacheReadEnd;
+ TimeStamp mLaunchServiceWorkerStart;
+ TimeStamp mLaunchServiceWorkerEnd;
+ TimeStamp mDispatchFetchEventStart;
+ TimeStamp mDispatchFetchEventEnd;
+ TimeStamp mHandleFetchEventStart;
+ TimeStamp mHandleFetchEventEnd;
// copied from the transaction before we null out mTransaction
// so that the timing can still be queried from OnStopRequest
TimingStruct mTransactionTimings;
diff --git a/netwerk/protocol/http/HttpChannelChild.cpp b/netwerk/protocol/http/HttpChannelChild.cpp
index f0b9e2136..6d09135c4 100644
--- a/netwerk/protocol/http/HttpChannelChild.cpp
+++ b/netwerk/protocol/http/HttpChannelChild.cpp
@@ -2132,6 +2132,13 @@ HttpChannelChild::ContinueAsyncOpen()
return NS_ERROR_FAILURE;
}
+ openArgs.launchServiceWorkerStart() = mLaunchServiceWorkerStart;
+ openArgs.launchServiceWorkerEnd() = mLaunchServiceWorkerEnd;
+ openArgs.dispatchFetchEventStart() = mDispatchFetchEventStart;
+ openArgs.dispatchFetchEventEnd() = mDispatchFetchEventEnd;
+ openArgs.handleFetchEventStart() = mHandleFetchEventStart;
+ openArgs.handleFetchEventEnd() = mHandleFetchEventEnd;
+
// The socket transport in the chrome process now holds a logical ref to us
// until OnStopRequest, or we do a redirect, or we hit an IPDL error.
AddIPDLReference();
diff --git a/netwerk/protocol/http/HttpChannelParent.cpp b/netwerk/protocol/http/HttpChannelParent.cpp
index 5f0859f28..90ed597a6 100644
--- a/netwerk/protocol/http/HttpChannelParent.cpp
+++ b/netwerk/protocol/http/HttpChannelParent.cpp
@@ -130,7 +130,13 @@ HttpChannelParent::Init(const HttpChannelCreationArgs& aArgs)
a.initialRwin(), a.blockAuthPrompt(),
a.suspendAfterSynthesizeResponse(),
a.allowStaleCacheContent(), a.contentTypeHint(),
- a.channelId(), a.contentWindowId(), a.preferredAlternativeType());
+ a.channelId(), a.contentWindowId(), a.preferredAlternativeType(),
+ a.launchServiceWorkerStart(),
+ a.launchServiceWorkerEnd(),
+ a.dispatchFetchEventStart(),
+ a.dispatchFetchEventEnd(),
+ a.handleFetchEventStart(),
+ a.handleFetchEventEnd());
}
case HttpChannelCreationArgs::THttpChannelConnectArgs:
{
@@ -329,7 +335,13 @@ HttpChannelParent::DoAsyncOpen( const URIParams& aURI,
const nsCString& aContentTypeHint,
const nsCString& aChannelId,
const uint64_t& aContentWindowId,
- const nsCString& aPreferredAlternativeType)
+ const nsCString& aPreferredAlternativeType,
+ const TimeStamp& aLaunchServiceWorkerStart,
+ const TimeStamp& aLaunchServiceWorkerEnd,
+ const TimeStamp& aDispatchFetchEventStart,
+ const TimeStamp& aDispatchFetchEventEnd,
+ const TimeStamp& aHandleFetchEventStart,
+ const TimeStamp& aHandleFetchEventEnd)
{
nsCOMPtr<nsIURI> uri = DeserializeURI(aURI);
if (!uri) {
@@ -534,6 +546,13 @@ HttpChannelParent::DoAsyncOpen( const URIParams& aURI,
mChannel->SetInitialRwin(aInitialRwin);
mChannel->SetBlockAuthPrompt(aBlockAuthPrompt);
+ mChannel->SetLaunchServiceWorkerStart(aLaunchServiceWorkerStart);
+ mChannel->SetLaunchServiceWorkerEnd(aLaunchServiceWorkerEnd);
+ mChannel->SetDispatchFetchEventStart(aDispatchFetchEventStart);
+ mChannel->SetDispatchFetchEventEnd(aDispatchFetchEventEnd);
+ mChannel->SetHandleFetchEventStart(aHandleFetchEventStart);
+ mChannel->SetHandleFetchEventEnd(aHandleFetchEventEnd);
+
nsCOMPtr<nsIApplicationCacheChannel> appCacheChan =
do_QueryObject(mChannel);
nsCOMPtr<nsIApplicationCacheService> appCacheService =
@@ -1159,7 +1178,7 @@ HttpChannelParent::OnStartRequest(nsIRequest *aRequest, nsISupports *aContext)
nsCString secInfoSerialization;
UpdateAndSerializeSecurityInfo(secInfoSerialization);
- uint16_t redirectCount = 0;
+ uint8_t redirectCount = 0;
chan->GetRedirectCount(&redirectCount);
nsCOMPtr<nsISupports> cacheKey;
diff --git a/netwerk/protocol/http/HttpChannelParent.h b/netwerk/protocol/http/HttpChannelParent.h
index a3b377d49..56854bb55 100644
--- a/netwerk/protocol/http/HttpChannelParent.h
+++ b/netwerk/protocol/http/HttpChannelParent.h
@@ -143,7 +143,13 @@ protected:
const nsCString& aContentTypeHint,
const nsCString& aChannelId,
const uint64_t& aContentWindowId,
- const nsCString& aPreferredAlternativeType);
+ const nsCString& aPreferredAlternativeType,
+ const TimeStamp& aLaunchServiceWorkerStart,
+ const TimeStamp& aLaunchServiceWorkerEnd,
+ const TimeStamp& aDispatchFetchEventStart,
+ const TimeStamp& aDispatchFetchEventEnd,
+ const TimeStamp& aHandleFetchEventStart,
+ const TimeStamp& aHandleFetchEventEnd);
virtual bool RecvSetPriority(const uint16_t& priority) override;
virtual bool RecvSetClassOfService(const uint32_t& cos) override;
diff --git a/netwerk/protocol/http/InterceptedChannel.cpp b/netwerk/protocol/http/InterceptedChannel.cpp
index 9e38e2734..2dadbe760 100644
--- a/netwerk/protocol/http/InterceptedChannel.cpp
+++ b/netwerk/protocol/http/InterceptedChannel.cpp
@@ -10,6 +10,7 @@
#include "nsInputStreamPump.h"
#include "nsIPipe.h"
#include "nsIStreamListener.h"
+#include "nsITimedChannel.h"
#include "nsHttpChannel.h"
#include "HttpChannelChild.h"
#include "nsHttpResponseHead.h"
@@ -134,6 +135,40 @@ InterceptedChannelBase::SetReleaseHandle(nsISupports* aHandle)
return NS_OK;
}
+NS_IMETHODIMP
+InterceptedChannelBase::SaveTimeStampsToUnderlyingChannel()
+{
+ MOZ_ASSERT(NS_IsMainThread());
+
+ nsCOMPtr<nsIChannel> underlyingChannel;
+ nsresult rv = GetChannel(getter_AddRefs(underlyingChannel));
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+
+ nsCOMPtr<nsITimedChannel> timedChannel =
+ do_QueryInterface(underlyingChannel);
+ MOZ_ASSERT(timedChannel);
+
+ rv = timedChannel->SetLaunchServiceWorkerStart(mLaunchServiceWorkerStart);
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+
+ rv = timedChannel->SetLaunchServiceWorkerEnd(mLaunchServiceWorkerEnd);
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+
+ rv = timedChannel->SetDispatchFetchEventStart(mDispatchFetchEventStart);
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+
+ rv = timedChannel->SetDispatchFetchEventEnd(mDispatchFetchEventEnd);
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+
+ rv = timedChannel->SetHandleFetchEventStart(mHandleFetchEventStart);
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+
+ rv = timedChannel->SetHandleFetchEventEnd(mHandleFetchEventEnd);
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+
+ return rv;
+}
+
/* static */
already_AddRefed<nsIURI>
InterceptedChannelBase::SecureUpgradeChannelURI(nsIChannel* aChannel)
diff --git a/netwerk/protocol/http/InterceptedChannel.h b/netwerk/protocol/http/InterceptedChannel.h
index 688f211de..efab7abca 100644
--- a/netwerk/protocol/http/InterceptedChannel.h
+++ b/netwerk/protocol/http/InterceptedChannel.h
@@ -46,6 +46,13 @@ protected:
nsresult DoSynthesizeStatus(uint16_t aStatus, const nsACString& aReason);
nsresult DoSynthesizeHeader(const nsACString& aName, const nsACString& aValue);
+ TimeStamp mLaunchServiceWorkerStart;
+ TimeStamp mLaunchServiceWorkerEnd;
+ TimeStamp mDispatchFetchEventStart;
+ TimeStamp mDispatchFetchEventEnd;
+ TimeStamp mHandleFetchEventStart;
+ TimeStamp mHandleFetchEventEnd;
+
virtual ~InterceptedChannelBase();
public:
explicit InterceptedChannelBase(nsINetworkInterceptController* aController);
@@ -60,6 +67,50 @@ public:
NS_IMETHOD GetConsoleReportCollector(nsIConsoleReportCollector** aCollectorOut) override;
NS_IMETHOD SetReleaseHandle(nsISupports* aHandle) override;
+ NS_IMETHODIMP
+ SetLaunchServiceWorkerStart(TimeStamp aTimeStamp) override
+ {
+ mLaunchServiceWorkerStart = aTimeStamp;
+ return NS_OK;
+ }
+
+ NS_IMETHODIMP
+ SetLaunchServiceWorkerEnd(TimeStamp aTimeStamp) override
+ {
+ mLaunchServiceWorkerEnd = aTimeStamp;
+ return NS_OK;
+ }
+
+ NS_IMETHODIMP
+ SetDispatchFetchEventStart(TimeStamp aTimeStamp) override
+ {
+ mDispatchFetchEventStart = aTimeStamp;
+ return NS_OK;
+ }
+
+ NS_IMETHODIMP
+ SetDispatchFetchEventEnd(TimeStamp aTimeStamp) override
+ {
+ mDispatchFetchEventEnd = aTimeStamp;
+ return NS_OK;
+ }
+
+ NS_IMETHODIMP
+ SetHandleFetchEventStart(TimeStamp aTimeStamp) override
+ {
+ mHandleFetchEventStart = aTimeStamp;
+ return NS_OK;
+ }
+
+ NS_IMETHODIMP
+ SetHandleFetchEventEnd(TimeStamp aTimeStamp) override
+ {
+ mHandleFetchEventEnd = aTimeStamp;
+ return NS_OK;
+ }
+
+ NS_IMETHODIMP SaveTimeStampsToUnderlyingChannel() override;
+
static already_AddRefed<nsIURI>
SecureUpgradeChannelURI(nsIChannel* aChannel);
};
diff --git a/netwerk/protocol/http/NullHttpChannel.cpp b/netwerk/protocol/http/NullHttpChannel.cpp
index 61efe3956..2954006ad 100644
--- a/netwerk/protocol/http/NullHttpChannel.cpp
+++ b/netwerk/protocol/http/NullHttpChannel.cpp
@@ -539,13 +539,25 @@ NullHttpChannel::SetTimingEnabled(bool aTimingEnabled)
}
NS_IMETHODIMP
-NullHttpChannel::GetRedirectCount(uint16_t *aRedirectCount)
+NullHttpChannel::GetRedirectCount(uint8_t *aRedirectCount)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP
-NullHttpChannel::SetRedirectCount(uint16_t aRedirectCount)
+NullHttpChannel::SetRedirectCount(uint8_t aRedirectCount)
+{
+ return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::GetInternalRedirectCount(uint8_t *aRedirectCount)
+{
+ return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::SetInternalRedirectCount(uint8_t aRedirectCount)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
@@ -565,6 +577,90 @@ NullHttpChannel::GetAsyncOpen(mozilla::TimeStamp *aAsyncOpen)
}
NS_IMETHODIMP
+NullHttpChannel::GetLaunchServiceWorkerStart(mozilla::TimeStamp *_retval)
+{
+ MOZ_ASSERT(_retval);
+ *_retval = mAsyncOpenTime;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::SetLaunchServiceWorkerStart(mozilla::TimeStamp aTimeStamp)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::GetLaunchServiceWorkerEnd(mozilla::TimeStamp *_retval)
+{
+ MOZ_ASSERT(_retval);
+ *_retval = mAsyncOpenTime;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::SetLaunchServiceWorkerEnd(mozilla::TimeStamp aTimeStamp)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::GetDispatchFetchEventStart(mozilla::TimeStamp *_retval)
+{
+ MOZ_ASSERT(_retval);
+ *_retval = mAsyncOpenTime;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::SetDispatchFetchEventStart(mozilla::TimeStamp aTimeStamp)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::GetDispatchFetchEventEnd(mozilla::TimeStamp *_retval)
+{
+ MOZ_ASSERT(_retval);
+ *_retval = mAsyncOpenTime;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::SetDispatchFetchEventEnd(mozilla::TimeStamp aTimeStamp)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::GetHandleFetchEventStart(mozilla::TimeStamp *_retval)
+{
+ MOZ_ASSERT(_retval);
+ *_retval = mAsyncOpenTime;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::SetHandleFetchEventStart(mozilla::TimeStamp aTimeStamp)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::GetHandleFetchEventEnd(mozilla::TimeStamp *_retval)
+{
+ MOZ_ASSERT(_retval);
+ *_retval = mAsyncOpenTime;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+NullHttpChannel::SetHandleFetchEventEnd(mozilla::TimeStamp aTimeStamp)
+{
+ return NS_OK;
+}
+
+NS_IMETHODIMP
NullHttpChannel::GetDomainLookupStart(mozilla::TimeStamp *aDomainLookupStart)
{
*aDomainLookupStart = mAsyncOpenTime;
@@ -761,6 +857,12 @@ NullHttpChannel::Get##name##Time(PRTime* _retval) { \
IMPL_TIMING_ATTR(ChannelCreation)
IMPL_TIMING_ATTR(AsyncOpen)
+IMPL_TIMING_ATTR(LaunchServiceWorkerStart)
+IMPL_TIMING_ATTR(LaunchServiceWorkerEnd)
+IMPL_TIMING_ATTR(DispatchFetchEventStart)
+IMPL_TIMING_ATTR(DispatchFetchEventEnd)
+IMPL_TIMING_ATTR(HandleFetchEventStart)
+IMPL_TIMING_ATTR(HandleFetchEventEnd)
IMPL_TIMING_ATTR(DomainLookupStart)
IMPL_TIMING_ATTR(DomainLookupEnd)
IMPL_TIMING_ATTR(ConnectStart)
diff --git a/netwerk/protocol/http/nsHttpChannel.cpp b/netwerk/protocol/http/nsHttpChannel.cpp
index 94b0d9bf9..05699df62 100644
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -5402,7 +5402,7 @@ nsHttpChannel::AsyncProcessRedirection(uint32_t redirectType)
if (NS_EscapeURL(location.get(), -1, esc_OnlyNonASCII, locationBuf))
location = locationBuf;
- if (mRedirectionLimit == 0) {
+ if (mRedirectCount >= mRedirectionLimit || mInternalRedirectCount >= mRedirectionLimit) {
LOG(("redirection limit reached!\n"));
return NS_ERROR_REDIRECT_LOOP;
}
diff --git a/netwerk/protocol/http/nsHttpHandler.cpp b/netwerk/protocol/http/nsHttpHandler.cpp
index 67e29a029..f9bcc391d 100644
--- a/netwerk/protocol/http/nsHttpHandler.cpp
+++ b/netwerk/protocol/http/nsHttpHandler.cpp
@@ -848,31 +848,6 @@ nsHttpHandler::InitUserAgentComponents()
}
#endif // MOZ_MULET
-#if defined(MOZ_WIDGET_GONK)
- // Device model identifier should be a simple token, which can be composed
- // of letters, numbers, hyphen ("-") and dot (".").
- // Any other characters means the identifier is invalid and ignored.
- nsCString deviceId;
- rv = Preferences::GetCString("general.useragent.device_id", &deviceId);
- if (NS_SUCCEEDED(rv)) {
- bool valid = true;
- deviceId.Trim(" ", true, true);
- for (size_t i = 0; i < deviceId.Length(); i++) {
- char c = deviceId.CharAt(i);
- if (!(isalnum(c) || c == '-' || c == '.')) {
- valid = false;
- break;
- }
- }
- if (valid) {
- mDeviceModelId = deviceId;
- } else {
- LOG(("nsHttpHandler: Ignore invalid device ID: [%s]\n",
- deviceId.get()));
- }
- }
-#endif
-
#ifndef MOZ_UA_OS_AGNOSTIC
// Gather OS/CPU.
#if defined(XP_WIN)
diff --git a/netwerk/protocol/http/nsHttpTransaction.cpp b/netwerk/protocol/http/nsHttpTransaction.cpp
index 706710d89..8d837d172 100644
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -43,10 +43,6 @@
#include "sslerr.h"
#include <algorithm>
-#ifdef MOZ_WIDGET_GONK
-#include "NetStatistics.h"
-#endif
-
//-----------------------------------------------------------------------------
static NS_DEFINE_CID(kMultiplexInputStream, NS_MULTIPLEXINPUTSTREAM_CID);
@@ -266,15 +262,6 @@ nsHttpTransaction::Init(uint32_t caps,
NS_GetAppInfo(channel, &mAppId, &mIsInIsolatedMozBrowser);
}
-#ifdef MOZ_WIDGET_GONK
- if (mAppId != NECKO_NO_APP_ID) {
- nsCOMPtr<nsINetworkInfo> activeNetworkInfo;
- GetActiveNetworkInfo(activeNetworkInfo);
- mActiveNetworkInfo =
- new nsMainThreadPtrHolder<nsINetworkInfo>(activeNetworkInfo);
- }
-#endif
-
nsCOMPtr<nsIHttpChannelInternal> httpChannelInternal =
do_QueryInterface(eventsink);
if (httpChannelInternal) {
@@ -937,40 +924,7 @@ nsHttpTransaction::WriteSegments(nsAHttpSegmentWriter *writer,
nsresult
nsHttpTransaction::SaveNetworkStats(bool enforce)
{
-#ifdef MOZ_WIDGET_GONK
- // Check if active network and appid are valid.
- if (!mActiveNetworkInfo || mAppId == NECKO_NO_APP_ID) {
- return NS_OK;
- }
-
- if (mCountRecv <= 0 && mCountSent <= 0) {
- // There is no traffic, no need to save.
- return NS_OK;
- }
-
- // If |enforce| is false, the traffic amount is saved
- // only when the total amount exceeds the predefined
- // threshold.
- uint64_t totalBytes = mCountRecv + mCountSent;
- if (!enforce && totalBytes < NETWORK_STATS_THRESHOLD) {
- return NS_OK;
- }
-
- // Create the event to save the network statistics.
- // the event is then dispatched to the main thread.
- RefPtr<Runnable> event =
- new SaveNetworkStatsEvent(mAppId, mIsInIsolatedMozBrowser, mActiveNetworkInfo,
- mCountRecv, mCountSent, false);
- NS_DispatchToMainThread(event);
-
- // Reset the counters after saving.
- mCountSent = 0;
- mCountRecv = 0;
-
- return NS_OK;
-#else
return NS_ERROR_NOT_IMPLEMENTED;
-#endif
}
void
diff --git a/netwerk/protocol/http/nsHttpTransaction.h b/netwerk/protocol/http/nsHttpTransaction.h
index 5bf97d41e..262796d71 100644
--- a/netwerk/protocol/http/nsHttpTransaction.h
+++ b/netwerk/protocol/http/nsHttpTransaction.h
@@ -19,11 +19,6 @@
#include "ARefBase.h"
#include "AlternateServices.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsINetworkInterface.h"
-#include "nsProxyRelease.h"
-#endif
-
//-----------------------------------------------------------------------------
class nsIHttpActivityObserver;
@@ -435,9 +430,6 @@ private:
uint64_t mCountSent;
uint32_t mAppId;
bool mIsInIsolatedMozBrowser;
-#ifdef MOZ_WIDGET_GONK
- nsMainThreadPtrHandle<nsINetworkInfo> mActiveNetworkInfo;
-#endif
nsresult SaveNetworkStats(bool);
void CountRecvBytes(uint64_t recvBytes)
{
diff --git a/netwerk/protocol/websocket/WebSocketChannel.cpp b/netwerk/protocol/websocket/WebSocketChannel.cpp
index a6254a088..c6dc8d328 100644
--- a/netwerk/protocol/websocket/WebSocketChannel.cpp
+++ b/netwerk/protocol/websocket/WebSocketChannel.cpp
@@ -65,10 +65,6 @@
#include "zlib.h"
#include <algorithm>
-#ifdef MOZ_WIDGET_GONK
-#include "NetStatistics.h"
-#endif
-
// rather than slurp up all of nsIWebSocket.idl, which lives outside necko, just
// dupe one constant we need from it
#define CLOSE_GOING_AWAY 1001
@@ -1396,15 +1392,6 @@ WebSocketChannel::BeginOpenInternal()
NS_GetAppInfo(localChannel, &mAppId, &mIsInIsolatedMozBrowser);
}
-#ifdef MOZ_WIDGET_GONK
- if (mAppId != NECKO_NO_APP_ID) {
- nsCOMPtr<nsINetworkInfo> activeNetworkInfo;
- GetActiveNetworkInfo(activeNetworkInfo);
- mActiveNetworkInfo =
- new nsMainThreadPtrHolder<nsINetworkInfo>(activeNetworkInfo);
- }
-#endif
-
rv = NS_MaybeOpenChannelUsingAsyncOpen2(localChannel, this);
if (NS_FAILED(rv)) {
@@ -4063,42 +4050,7 @@ WebSocketChannel::OnDataAvailable(nsIRequest *aRequest,
nsresult
WebSocketChannel::SaveNetworkStats(bool enforce)
{
-#ifdef MOZ_WIDGET_GONK
- // Check if the active network and app id are valid.
- if(!mActiveNetworkInfo || mAppId == NECKO_NO_APP_ID) {
- return NS_OK;
- }
-
- uint64_t countRecv = 0;
- uint64_t countSent = 0;
-
- mCountRecv.exchange(countRecv);
- mCountSent.exchange(countSent);
-
- if (countRecv == 0 && countSent == 0) {
- // There is no traffic, no need to save.
- return NS_OK;
- }
-
- // If |enforce| is false, the traffic amount is saved
- // only when the total amount exceeds the predefined
- // threshold.
- uint64_t totalBytes = countRecv + countSent;
- if (!enforce && totalBytes < NETWORK_STATS_THRESHOLD) {
- return NS_OK;
- }
-
- // Create the event to save the network statistics.
- // the event is then dispatched to the main thread.
- RefPtr<Runnable> event =
- new SaveNetworkStatsEvent(mAppId, mIsInIsolatedMozBrowser, mActiveNetworkInfo,
- countRecv, countSent, false);
- NS_DispatchToMainThread(event);
-
- return NS_OK;
-#else
return NS_ERROR_NOT_IMPLEMENTED;
-#endif
}
} // namespace net
diff --git a/netwerk/protocol/websocket/WebSocketChannel.h b/netwerk/protocol/websocket/WebSocketChannel.h
index e2f332dab..341a357a0 100644
--- a/netwerk/protocol/websocket/WebSocketChannel.h
+++ b/netwerk/protocol/websocket/WebSocketChannel.h
@@ -21,11 +21,6 @@
#include "nsIStringStream.h"
#include "BaseWebSocketChannel.h"
-#ifdef MOZ_WIDGET_GONK
-#include "nsINetworkInterface.h"
-#include "nsProxyRelease.h"
-#endif
-
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsDeque.h"
@@ -307,9 +302,6 @@ private:
Atomic<uint64_t, Relaxed> mCountSent;
uint32_t mAppId;
bool mIsInIsolatedMozBrowser;
-#ifdef MOZ_WIDGET_GONK
- nsMainThreadPtrHandle<nsINetworkInfo> mActiveNetworkInfo;
-#endif
nsresult SaveNetworkStats(bool);
void CountRecvBytes(uint64_t recvBytes)
{
diff --git a/netwerk/standalone/moz.build b/netwerk/standalone/moz.build
index 4c7366e3b..b5651da76 100644
--- a/netwerk/standalone/moz.build
+++ b/netwerk/standalone/moz.build
@@ -4,7 +4,7 @@
# License, v. 2.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['OS_TARGET'] != 'WINNT' and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'gonk':
+if CONFIG['OS_TARGET'] != 'WINNT':
Library('necko_standalone')
src_list = [
@@ -27,7 +27,6 @@ netwerk_dns_src = [
'DNS.cpp',
'DNSListenerProxy.cpp',
'GetAddrInfo.cpp',
- 'nameprep.c',
'nsDNSService2.cpp',
'nsIDNService.cpp',
'punycode.c',
diff --git a/netwerk/system/linux/nsNotifyAddrListener_Linux.cpp b/netwerk/system/linux/nsNotifyAddrListener_Linux.cpp
index c0ec9d90e..4fc36928a 100644
--- a/netwerk/system/linux/nsNotifyAddrListener_Linux.cpp
+++ b/netwerk/system/linux/nsNotifyAddrListener_Linux.cpp
@@ -8,10 +8,8 @@
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
-#ifndef MOZ_WIDGET_GONK
#include <ifaddrs.h>
#include <net/if.h>
-#endif
#include "nsThreadUtils.h"
#include "nsIObserverService.h"
@@ -28,10 +26,6 @@
#include "mozilla/Sprintf.h"
#include "mozilla/Telemetry.h"
-#ifdef MOZ_WIDGET_GONK
-#include <cutils/properties.h>
-#endif
-
/* a shorter name that better explains what it does */
#define EINTR_RETRY(x) MOZ_TEMP_FAILURE_RETRY(x)
@@ -210,9 +204,6 @@ void nsNotifyAddrListener::calculateNetworkId(void)
//
void nsNotifyAddrListener::checkLink(void)
{
-#ifdef MOZ_WIDGET_GONK
- // b2g instead has NetworkManager.js which handles UP/DOWN
-#else
struct ifaddrs *list;
struct ifaddrs *ifa;
bool link = false;
@@ -247,7 +238,6 @@ void nsNotifyAddrListener::checkLink(void)
SendEvent(mLinkUp ?
NS_NETWORK_LINK_DATA_UP : NS_NETWORK_LINK_DATA_DOWN);
}
-#endif
}
void nsNotifyAddrListener::OnNetlinkMessage(int aNetlinkSocket)
diff --git a/netwerk/test/moz.build b/netwerk/test/moz.build
index 3df865c3a..c83cca0eb 100644
--- a/netwerk/test/moz.build
+++ b/netwerk/test/moz.build
@@ -57,7 +57,7 @@ RESOURCE_FILES += [
USE_LIBS += ['static:js']
-if CONFIG['ENABLE_INTL_API'] and CONFIG['MOZ_ICU_DATA_ARCHIVE']:
+if CONFIG['MOZ_ICU_DATA_ARCHIVE']:
# The ICU libraries linked into libmozjs will not include the ICU data,
# so link it directly.
USE_LIBS += ['icudata']
diff --git a/netwerk/wifi/moz.build b/netwerk/wifi/moz.build
index e3edb0842..28149cb78 100644
--- a/netwerk/wifi/moz.build
+++ b/netwerk/wifi/moz.build
@@ -16,14 +16,9 @@ UNIFIED_SOURCES += [
'nsWifiAccessPoint.cpp',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- UNIFIED_SOURCES += [
- 'nsWifiMonitorGonk.cpp',
- ]
-else:
- UNIFIED_SOURCES += [
- 'nsWifiMonitor.cpp',
- ]
+UNIFIED_SOURCES += [
+ 'nsWifiMonitor.cpp',
+]
if CONFIG['OS_ARCH'] == 'Darwin':
UNIFIED_SOURCES += [
diff --git a/netwerk/wifi/nsWifiMonitor.h b/netwerk/wifi/nsWifiMonitor.h
index 665798efc..c44f6804b 100644
--- a/netwerk/wifi/nsWifiMonitor.h
+++ b/netwerk/wifi/nsWifiMonitor.h
@@ -48,7 +48,6 @@ class nsWifiListener
bool mHasSentData;
};
-#ifndef MOZ_WIDGET_GONK
class nsWifiMonitor final : nsIRunnable, nsIWifiMonitor, nsIObserver
{
public:
@@ -79,32 +78,5 @@ class nsWifiMonitor final : nsIRunnable, nsIWifiMonitor, nsIObserver
nsAutoPtr<WinWifiScanner> mWinWifiScanner;
#endif
};
-#else
-#include "nsIWifi.h"
-class nsWifiMonitor final : nsIWifiMonitor, nsIWifiScanResultsReady, nsIObserver
-{
- public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSIWIFIMONITOR
- NS_DECL_NSIOBSERVER
- NS_DECL_NSIWIFISCANRESULTSREADY
- nsWifiMonitor();
-
- private:
- ~nsWifiMonitor();
-
- void ClearTimer() {
- if (mTimer) {
- mTimer->Cancel();
- mTimer = nullptr;
- }
- }
- void StartScan();
- nsCOMArray<nsWifiAccessPoint> mLastAccessPoints;
- nsTArray<nsWifiListener> mListeners;
- nsCOMPtr<nsITimer> mTimer;
-};
-#endif
-
-#endif
+#endif // __nsWifiMonitor__
diff --git a/netwerk/wifi/nsWifiMonitorGonk.cpp b/netwerk/wifi/nsWifiMonitorGonk.cpp
deleted file mode 100644
index 017750549..000000000
--- a/netwerk/wifi/nsWifiMonitorGonk.cpp
+++ /dev/null
@@ -1,181 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsCOMPtr.h"
-#include "nsComponentManagerUtils.h"
-#include "nsServiceManagerUtils.h"
-#include "nsThreadUtils.h"
-#include "nsXPCOM.h"
-#include "nsXPCOMCID.h"
-#include "nsIObserver.h"
-#include "nsIObserverService.h"
-#include "nsWifiMonitor.h"
-#include "nsWifiAccessPoint.h"
-
-#include "nsServiceManagerUtils.h"
-#include "nsComponentManagerUtils.h"
-#include "mozilla/Services.h"
-
-#include "nsIInterfaceRequestor.h"
-#include "nsIInterfaceRequestorUtils.h"
-
-using namespace mozilla;
-
-LazyLogModule gWifiMonitorLog("WifiMonitor");
-
-NS_IMPL_ISUPPORTS(nsWifiMonitor,
- nsIWifiMonitor,
- nsIObserver,
- nsIWifiScanResultsReady)
-
-nsWifiMonitor::nsWifiMonitor()
-{
- nsCOMPtr<nsIObserverService> obsSvc = mozilla::services::GetObserverService();
- if (obsSvc) {
- obsSvc->AddObserver(this, "xpcom-shutdown", false);
- }
- LOG(("@@@@@ wifimonitor created\n"));
-}
-
-nsWifiMonitor::~nsWifiMonitor()
-{
-}
-
-NS_IMETHODIMP
-nsWifiMonitor::StartWatching(nsIWifiListener *aListener)
-{
- LOG(("@@@@@ nsWifiMonitor::StartWatching\n"));
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
- if (!aListener) {
- return NS_ERROR_NULL_POINTER;
- }
-
- mListeners.AppendElement(nsWifiListener(new nsMainThreadPtrHolder<nsIWifiListener>(aListener)));
-
- if (!mTimer) {
- mTimer = do_CreateInstance("@mozilla.org/timer;1");
- mTimer->Init(this, 5000, nsITimer::TYPE_REPEATING_SLACK);
- }
- StartScan();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWifiMonitor::StopWatching(nsIWifiListener *aListener)
-{
- LOG(("@@@@@ nsWifiMonitor::StopWatching\n"));
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
- if (!aListener) {
- return NS_ERROR_NULL_POINTER;
- }
-
- for (uint32_t i = 0; i < mListeners.Length(); i++) {
- if (mListeners[i].mListener == aListener) {
- mListeners.RemoveElementAt(i);
- break;
- }
- }
-
- if (mListeners.Length() == 0) {
- ClearTimer();
- }
- return NS_OK;
-}
-
-void
-nsWifiMonitor::StartScan()
-{
- nsCOMPtr<nsIInterfaceRequestor> ir = do_GetService("@mozilla.org/telephony/system-worker-manager;1");
- nsCOMPtr<nsIWifi> wifi = do_GetInterface(ir);
- if (!wifi) {
- return;
- }
- wifi->GetWifiScanResults(this);
-}
-
-NS_IMETHODIMP
-nsWifiMonitor::Observe(nsISupports *subject, const char *topic,
- const char16_t *data)
-{
- if (!strcmp(topic, "timer-callback")) {
- LOG(("timer callback\n"));
- StartScan();
- return NS_OK;
- }
-
- if (!strcmp(topic, "xpcom-shutdown")) {
- LOG(("Shutting down\n"));
- ClearTimer();
- return NS_OK;
- }
-
- return NS_ERROR_UNEXPECTED;
-}
-
-NS_IMETHODIMP
-nsWifiMonitor::Onready(uint32_t count, nsIWifiScanResult **results)
-{
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
- LOG(("@@@@@ About to send data to the wifi listeners\n"));
-
- nsCOMArray<nsWifiAccessPoint> accessPoints;
-
- for (uint32_t i = 0; i < count; i++) {
- RefPtr<nsWifiAccessPoint> ap = new nsWifiAccessPoint();
-
- nsString temp;
- results[i]->GetBssid(temp);
- // 00:00:00:00:00:00 --> 00-00-00-00-00-00
- for (int32_t x=0; x<6; x++) {
- temp.ReplaceSubstring(NS_LITERAL_STRING(":"), NS_LITERAL_STRING("-")); // would it be too much to ask for a ReplaceAll()?
- }
-
- nsCString mac;
- mac.AssignWithConversion(temp);
-
- results[i]->GetSsid(temp);
-
- nsCString ssid;
- ssid.AssignWithConversion(temp);
-
- uint32_t signal;
- results[i]->GetSignalStrength(&signal);
-
- ap->setSignal(signal);
- ap->setMacRaw(mac.get());
- ap->setSSIDRaw(ssid.get(), ssid.Length());
-
- accessPoints.AppendObject(ap);
- }
-
- bool accessPointsChanged = !AccessPointsEqual(accessPoints, mLastAccessPoints);
- ReplaceArray(mLastAccessPoints, accessPoints);
-
- nsTArray<nsIWifiAccessPoint*> ac;
- uint32_t resultCount = mLastAccessPoints.Count();
- for (uint32_t i = 0; i < resultCount; i++) {
- ac.AppendElement(mLastAccessPoints[i]);
- }
-
- for (uint32_t i = 0; i < mListeners.Length(); i++) {
- if (!mListeners[i].mHasSentData || accessPointsChanged) {
- mListeners[i].mHasSentData = true;
- mListeners[i].mListener->OnChange(ac.Elements(), ac.Length());
- }
- }
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWifiMonitor::Onfailure()
-{
- NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
- LOG(("@@@@@ About to send error to the wifi listeners\n"));
- for (uint32_t i = 0; i < mListeners.Length(); i++) {
- mListeners[i].mListener->OnError(NS_ERROR_UNEXPECTED);
- }
-
- ClearTimer();
- return NS_OK;
-}
diff --git a/old-configure.in b/old-configure.in
index dabd37e6d..1670a90b6 100644
--- a/old-configure.in
+++ b/old-configure.in
@@ -94,66 +94,15 @@ if test "$COMPILE_ENVIRONMENT"; then
MOZ_ANDROID_NDK
fi # COMPILE_ENVIRONMENT
-if test -n "$gonkdir"; then
- dnl export for js/src/configure. We can't pass the option down normally,
- dnl because it's a `--enable-project=b2g`-only option.
- export gonkdir
- kernel_name=`uname -s | tr "[[:upper:]]" "[[:lower:]]"`
- android_source="$gonkdir"
- ANDROID_SOURCE="$android_source"
-
- case "$android_version" in
- 15)
- CPPFLAGS="-I$gonkdir/frameworks/base/opengl/include -I$gonkdir/frameworks/base/native/include -I$gonkdir/frameworks/base/include -I$gonkdir/frameworks/base/services/camera -I$gonkdir/frameworks/base/include/media/ -I$gonkdir/frameworks/base/include/media/stagefright -I$gonkdir/frameworks/base/include/media/stagefright/openmax -I$gonkdir/frameworks/base/media/libstagefright/rtsp -I$gonkdir/frameworks/base/media/libstagefright/include -I$gonkdir/external/dbus -I$gonkdir/dalvik/libnativehelper/include/nativehelper $CPPFLAGS"
- MOZ_SECUREELEMENT=1
- ;;
- 17|18)
- CPPFLAGS="-I$gonkdir/frameworks/native/include -I$gonkdir/frameworks/av/include -I$gonkdir/frameworks/av/include/media -I$gonkdir/frameworks/av/include/camera -I$gonkdir/frameworks/native/include/media/openmax -I$gonkdir/frameworks/av/media/libstagefright/include $CPPFLAGS"
- MOZ_SECUREELEMENT=1
- ;;
- 19)
- CPPFLAGS="-I$gonkdir/frameworks/native/include -I$gonkdir/frameworks/av/include -I$gonkdir/frameworks/av/include/media -I$gonkdir/frameworks/av/include/camera -I$gonkdir/frameworks/native/include/media/openmax -I$gonkdir/frameworks/av/media/libstagefright/include $CPPFLAGS"
- MOZ_AUDIO_OFFLOAD=1
- MOZ_SECUREELEMENT=1
- AC_SUBST(MOZ_AUDIO_OFFLOAD)
- AC_DEFINE(MOZ_AUDIO_OFFLOAD)
- ;;
- 21|22)
- CPPFLAGS="-I$gonkdir/frameworks/native/include -I$gonkdir/frameworks/av/include -I$gonkdir/frameworks/av/include/media -I$gonkdir/frameworks/av/include/camera -I$gonkdir/frameworks/native/include/media/openmax -I$gonkdir/frameworks/av/media/libstagefright/include $CPPFLAGS"
- MOZ_AUDIO_OFFLOAD=1
- AC_SUBST(MOZ_AUDIO_OFFLOAD)
- AC_DEFINE(MOZ_AUDIO_OFFLOAD)
- ;;
- *)
- AC_MSG_ERROR([Unsupported platform version: $android_version])
- ;;
- esac
-
- CPPFLAGS="-I$gonkdir/system -I$gonkdir/system/core/include -I$gonkdir/hardware/libhardware/include -I$gonkdir/external/valgrind/fxos-include $CPPFLAGS"
- LDFLAGS="-L$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib -Wl,-rpath-link=$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib $LDFLAGS"
-
+case "$target" in
+*-android*|*-linuxandroid*)
+ ZLIB_DIR=yes
AC_DEFINE(ANDROID)
- AC_DEFINE_UNQUOTED(ANDROID_VERSION, $android_version)
- AC_DEFINE(HAVE_SYS_UIO_H)
- AC_DEFINE(HAVE_PTHREADS)
-
- dnl ANDROID_VERSION is only required for the AC_SUBST below
- ANDROID_VERSION=$android_version
- AC_SUBST(ANDROID_VERSION)
-
- direct_nspr_config=1
-
-else
- case "$target" in
- *-android*|*-linuxandroid*)
- ZLIB_DIR=yes
- AC_DEFINE(ANDROID)
- ;;
- *-linux*)
- AC_PATH_PROG(OBJCOPY,objcopy)
- ;;
- esac
-fi
+ ;;
+*-linux*)
+ AC_PATH_PROG(OBJCOPY,objcopy)
+ ;;
+esac
case "$target" in
*-apple-darwin*)
@@ -563,7 +512,7 @@ dnl ==============================================================
if test "$COMPILE_ENVIRONMENT"; then
MOZ_ARCH_OPTS
else
- if test "$OS_TARGET" = Android -a x"$MOZ_WIDGET_TOOLKIT" != x"gonk"; then
+ if test "$OS_TARGET" = "Android"; then
dnl Default Android builds to ARMv7.
MOZ_ARCH=armv7-a
fi
@@ -926,13 +875,8 @@ case "$target" in
*-android*|*-linuxandroid*)
AC_DEFINE(NO_PW_GECOS)
- if test -n "$gonkdir"; then
- _PLATFORM_HAVE_RIL=1
- MOZ_SYNTH_PICO=1
- else
- if test "$COMPILE_ENVIRONMENT"; then
- MOZ_LINKER=1
- fi
+ if test "$COMPILE_ENVIRONMENT"; then
+ MOZ_LINKER=1
fi
MOZ_GFX_OPTIMIZE_MOBILE=1
@@ -1030,12 +974,14 @@ case "$target" in
dnl VS2012+ defaults to -arch:SSE2. We want to target nothing
dnl more recent, so set that explicitly here unless another
dnl target arch has already been set.
+ changequote(,)
if test -z `echo $CFLAGS | grep -i [-/]arch:`; then
CFLAGS="$CFLAGS -arch:SSE2"
fi
if test -z `echo $CXXFLAGS | grep -i [-/]arch:`; then
CXXFLAGS="$CXXFLAGS -arch:SSE2"
fi
+ changequote([,])
SSE_FLAGS="-arch:SSE"
SSE2_FLAGS="-arch:SSE2"
dnl MSVC allows the use of intrinsics without any flags
@@ -2256,6 +2202,7 @@ dnl ========================================================
MOZ_ARG_HEADER(Application)
+ENABLE_TESTS=
ENABLE_SYSTEM_EXTENSION_DIRS=1
MOZ_BRANDING_DIRECTORY=
MOZ_OFFICIAL_BRANDING=
@@ -2305,9 +2252,6 @@ MOZ_INSTALL_TRACKING=
ACCESSIBILITY=1
MOZ_TIME_MANAGER=
MOZ_AUDIO_CHANNEL_MANAGER=
-MOZ_CONTENT_SANDBOX=
-MOZ_GMP_SANDBOX=
-MOZ_SANDBOX=
MOZ_BINARY_EXTENSIONS=
MOZ_JETPACK=1
MOZ_DEVTOOLS_SERVER=1
@@ -2411,30 +2355,21 @@ if test -n "$WITH_APP_BASENAME" ; then
MOZ_APP_BASENAME="$WITH_APP_BASENAME"
fi
-if test -n "$MOZ_B2G"; then
- AC_DEFINE(MOZ_B2G)
-fi
-
# Graphene is a desktop runtime for running applications with a HTML UI.
if test -n "$MOZ_GRAPHENE"; then
AC_DEFINE(MOZ_GRAPHENE)
fi
-AC_SUBST(MOZ_B2G)
-AC_SUBST(MOZ_B2G_VERSION)
-
dnl ========================================================
dnl Ensure Android SDK and build-tools versions depending on
dnl mobile target.
dnl ========================================================
-if test -z "$gonkdir" ; then
- case "$MOZ_BUILD_APP" in
- mobile/android)
- MOZ_ANDROID_SDK(23, 23.0.3 23.0.1)
- ;;
- esac
-fi
+case "$MOZ_BUILD_APP" in
+mobile/android)
+ MOZ_ANDROID_SDK(23, 23.0.3 23.0.1)
+ ;;
+esac
dnl ========================================================
dnl =
@@ -2927,7 +2862,7 @@ AC_SUBST(MOZ_SCTP)
AC_SUBST(MOZ_SRTP)
AC_SUBST_LIST(MOZ_WEBRTC_X11_LIBS)
-dnl Use integers over floats for audio on B2G and Android
+dnl Use integers over floats for audio on Android
dnl (regarless of the CPU architecture, because audio
dnl backends for those platforms don't support floats. We also
dnl use integers on ARM with other OS, because it's more efficient.
@@ -2987,18 +2922,6 @@ if test -n "$MOZ_DIRECTSHOW"; then
fi;
dnl ========================================================
-dnl = Built-in fragmented MP4 support.
-dnl ========================================================
-
-if test x"$MOZ_WIDGET_TOOLKIT" = x"gonk" -a -n "$MOZ_FMP4" -a -n "$android_version"; then
- # we now know for sure that $android_version is not an empty string!
- if test "$android_version" -ge "18"; then
- MOZ_GONK_MEDIACODEC=1
- AC_SUBST(MOZ_GONK_MEDIACODEC)
- fi
-fi
-
-dnl ========================================================
dnl = EME support
dnl ========================================================
@@ -3031,7 +2954,7 @@ fi
dnl ========================================================
dnl = Enable media plugin support
dnl ========================================================
-if test "$OS_TARGET" = Android -a x"$MOZ_WIDGET_TOOLKIT" != x"gonk"; then
+if test "$OS_TARGET" = "Android"; then
dnl Enable support on android by default
MOZ_ANDROID_OMX=1
fi
@@ -3048,7 +2971,7 @@ fi
dnl ========================================================
dnl = Enable building OMX media plugin (B2G or Android)
dnl ========================================================
-if test "$OS_TARGET" = Android -a x"$MOZ_WIDGET_TOOLKIT" != x"gonk"; then
+if test "$OS_TARGET" = "Android"; then
dnl Enable support on android by default
MOZ_OMX_PLUGIN=1
fi
@@ -3060,11 +2983,11 @@ MOZ_ARG_ENABLE_BOOL(omx-plugin,
if test -n "$MOZ_OMX_PLUGIN"; then
if test "$OS_TARGET" = "Android"; then
- dnl Only allow building OMX plugin on Gonk (B2G) or Android
+ dnl Only allow building OMX plugin on Android
AC_DEFINE(MOZ_OMX_PLUGIN)
else
- dnl fail if we're not building on Gonk or Android
- AC_MSG_ERROR([OMX media plugin can only be built on B2G or Android])
+ dnl fail if we're not building on Android
+ AC_MSG_ERROR([OMX media plugin can only be built on Android])
fi
fi
@@ -3273,13 +3196,9 @@ MOZ_ARG_DISABLE_BOOL(pulseaudio,
if test -n "$MOZ_PULSEAUDIO"; then
AC_DEFINE(MOZ_PULSEAUDIO)
- if test -z "$gonkdir"; then
- PKG_CHECK_MODULES(MOZ_PULSEAUDIO, libpulse, ,
- [echo "$MOZ_PULSEAUDIO_PKG_ERRORS"
- AC_MSG_ERROR([Building pulseaudio audio backend requires libpulse development package])])
- else
- MOZ_PULSEAUDIO_CFLAGS="-I$gonkdir/external/pulseaudio/pulseaudio/src"
- fi
+ PKG_CHECK_MODULES(MOZ_PULSEAUDIO, libpulse, ,
+ [echo "$MOZ_PULSEAUDIO_PKG_ERRORS"
+ AC_MSG_ERROR([Building pulseaudio audio backend requires libpulse development package])])
fi
AC_SUBST(MOZ_PULSEAUDIO)
@@ -3794,6 +3713,32 @@ if test -n "$MOZ_UPDATER"; then
fi
dnl ========================================================
+dnl Build the tests?
+dnl ========================================================
+MOZ_ARG_ENABLE_BOOL(tests,
+[ --enable-tests Build test libraries & programs],
+ ENABLE_TESTS=1,
+ ENABLE_TESTS= )
+
+if test -n "$ENABLE_TESTS"; then
+ GTEST_HAS_RTTI=0
+ AC_DEFINE(ENABLE_TESTS)
+ AC_DEFINE_UNQUOTED(GTEST_HAS_RTTI, 0)
+ AC_SUBST(GTEST_HAS_RTTI)
+ if test -n "$_WIN32_MSVC"; then
+ AC_DEFINE_UNQUOTED(_VARIADIC_MAX, 10)
+ fi
+ if test "${OS_TARGET}" = "Android"; then
+ AC_DEFINE(GTEST_OS_LINUX_ANDROID)
+ AC_DEFINE(GTEST_USE_OWN_TR1_TUPLE)
+ AC_DEFINE_UNQUOTED(GTEST_HAS_CLONE, 0)
+ AC_SUBST(GTEST_OS_LINUX_ANDROID)
+ AC_SUBST(GTEST_USE_OWN_TR1_TUPLE)
+ AC_SUBST(GTEST_HAS_CLONE)
+ fi
+fi
+
+dnl ========================================================
dnl parental controls (for Windows Vista)
dnl ========================================================
MOZ_ARG_DISABLE_BOOL(parental-controls,
@@ -3816,99 +3761,6 @@ fi
AC_SUBST(MOZ_NO_SMART_CARDS)
dnl ========================================================
-dnl = Sandboxing support
-dnl ========================================================
-MOZ_ARG_ENABLE_BOOL(sandbox,
-[ --enable-sandbox Enable sandboxing support],
- MOZ_SANDBOX=1,
- MOZ_SANDBOX=)
-
-if test -n "$MOZ_TSAN" -o -n "$MOZ_ASAN"; then
- # Bug 1182565: TSan conflicts with sandboxing on Linux.
- # Bug 1287971: LSan also conflicts with sandboxing on Linux.
- case $OS_TARGET in
- Linux|Android)
- MOZ_SANDBOX=
- ;;
- esac
-fi
-
-dnl ========================================================
-dnl = Content process sandboxing
-dnl ========================================================
-if test -n "$gonkdir"; then
- MOZ_CONTENT_SANDBOX=$MOZ_SANDBOX
-fi
-
-case "$OS_TARGET:$NIGHTLY_BUILD" in
-WINNT:*)
- MOZ_CONTENT_SANDBOX=$MOZ_SANDBOX
- ;;
-Darwin:*)
- MOZ_CONTENT_SANDBOX=$MOZ_SANDBOX
- ;;
-Linux:1)
- case $CPU_ARCH in
- x86_64|x86)
- MOZ_CONTENT_SANDBOX=$MOZ_SANDBOX
- ;;
- esac
- ;;
-esac
-
-MOZ_ARG_ENABLE_BOOL(content-sandbox,
-[ --enable-content-sandbox Enable sandboxing support for content-processes
- --disable-content-sandbox Disable sandboxing support for content-processes],
- MOZ_CONTENT_SANDBOX=1,
- MOZ_CONTENT_SANDBOX=)
-
-if test -n "$MOZ_CONTENT_SANDBOX" -a -z "$MOZ_SANDBOX"; then
- AC_MSG_ERROR([--enable-content-sandbox and --disable-sandbox are conflicting options])
-fi
-
-if test -n "$MOZ_CONTENT_SANDBOX"; then
- AC_DEFINE(MOZ_CONTENT_SANDBOX)
-fi
-
-AC_SUBST(MOZ_CONTENT_SANDBOX)
-
-dnl ========================================================
-dnl = Gecko Media Plugin sandboxing
-dnl ========================================================
-case $OS_TARGET in
-WINNT)
- MOZ_GMP_SANDBOX=$MOZ_SANDBOX
- ;;
-Linux)
- case $CPU_ARCH in
- x86_64|x86)
- MOZ_GMP_SANDBOX=$MOZ_SANDBOX
- ;;
- esac
- ;;
-Darwin)
- MOZ_GMP_SANDBOX=$MOZ_SANDBOX
- ;;
-esac
-
-if test -n "$MOZ_GMP_SANDBOX"; then
- AC_DEFINE(MOZ_GMP_SANDBOX)
-fi
-
-AC_SUBST(MOZ_GMP_SANDBOX)
-
-if test -z "$MOZ_CONTENT_SANDBOX" -a -z "$MOZ_GMP_SANDBOX"; then
- MOZ_SANDBOX=
-fi
-
-if test -n "$MOZ_SANDBOX"; then
- AC_DEFINE(MOZ_SANDBOX)
-fi
-
-AC_SUBST(MOZ_SANDBOX)
-
-
-dnl ========================================================
dnl =
dnl = Module specific options
dnl =
@@ -4262,8 +4114,6 @@ Android|WINNT|Darwin)
esac
if test -n "$MOZ_REPLACE_MALLOC"; then
- MOZ_SYSTEM_JEMALLOC=
-
dnl Replace-malloc Mac linkage quirks
if test -n "$MACOSX_DEPLOYMENT_TARGET"; then
AC_CACHE_CHECK([how to do weak dynamic linking],
@@ -4330,15 +4180,6 @@ if test -z "$MOZ_MEMORY"; then
;;
esac
else
- if test -n "$MOZ_JEMALLOC4" -a -z "$MOZ_REPLACE_MALLOC"; then
- MOZ_SYSTEM_JEMALLOC=1
- AC_CHECK_FUNCS(mallctl nallocx,,
- [MOZ_SYSTEM_JEMALLOC=
- break])
- if test -n "$MOZ_SYSTEM_JEMALLOC"; then
- AC_DEFINE(MOZ_SYSTEM_JEMALLOC)
- fi
- fi
if test "x$MOZ_DEBUG" = "x1"; then
AC_DEFINE(MOZ_MEMORY_DEBUG)
fi
@@ -4351,7 +4192,6 @@ else
;;
esac
fi # MOZ_MEMORY
-AC_SUBST(MOZ_SYSTEM_JEMALLOC)
AC_SUBST(MOZ_GLUE_IN_PROGRAM)
# Allow the application to provide a subconfigure script.
@@ -4545,10 +4385,6 @@ MOZ_ARG_DISABLE_BOOL(startupcache,
MOZ_DISABLE_STARTUPCACHE=1,
MOZ_DISABLE_STARTUPCACHE=)
-dnl bug 988880: disable startup cache on b2g
-if test -n "$MOZ_B2G"; then
- MOZ_DISABLE_STARTUPCACHE=1
-fi
if test -n "$MOZ_DISABLE_STARTUPCACHE"; then
AC_DEFINE(MOZ_DISABLE_STARTUPCACHE)
fi
@@ -4557,28 +4393,26 @@ AC_SUBST(MOZ_DISABLE_STARTUPCACHE)
dnl =========================================
dnl = Enable packaging Gaia with B2G desktop
dnl =========================================
-if test x"$MOZ_WIDGET_TOOLKIT" != x"gonk"; then
- if test -n "$GAIADIR" -a ! -d "$GAIADIR" ; then
- AC_MSG_ERROR([GAIADIR '$GAIADIR' isn't a valid directory])
- fi
+if test -n "$GAIADIR" -a ! -d "$GAIADIR" ; then
+ AC_MSG_ERROR([GAIADIR '$GAIADIR' isn't a valid directory])
+fi
- AC_SUBST(GAIADIR)
- if test -n "$GAIADIR" ; then
- AC_DEFINE(PACKAGE_GAIA)
- fi
+AC_SUBST(GAIADIR)
+if test -n "$GAIADIR" ; then
+ AC_DEFINE(PACKAGE_GAIA)
+fi
- if test -n "$FXOS_SIMULATOR" -a -z "$GAIADIR" ; then
- AC_MSG_ERROR([FXOS_SIMULATOR=1 requires GAIADIR to be defined])
- fi
+if test -n "$FXOS_SIMULATOR" -a -z "$GAIADIR" ; then
+ AC_MSG_ERROR([FXOS_SIMULATOR=1 requires GAIADIR to be defined])
+fi
- if test -n "$FXOS_SIMULATOR" ; then
- AC_DEFINE(FXOS_SIMULATOR)
- AC_SUBST(FXOS_SIMULATOR)
- fi
+if test -n "$FXOS_SIMULATOR" ; then
+ AC_DEFINE(FXOS_SIMULATOR)
+ AC_SUBST(FXOS_SIMULATOR)
fi
dnl ========================================================
-dnl = Enable Pico Speech Synthesis (Gonk usually)
+dnl = Enable Pico Speech Synthesis
dnl ========================================================
MOZ_ARG_ENABLE_BOOL(synth-pico,
[ --enable-synth-pico Set compile flags necessary for compiling Pico Web Speech API ],
@@ -5092,7 +4926,7 @@ else
fi
case "$MOZ_WIDGET_TOOLKIT" in
-android|gonk)
+android)
TK_CFLAGS="$MOZ_CAIRO_CFLAGS $MOZ_PIXMAN_CFLAGS"
TK_LIBS="$MOZ_CAIRO_LIBS $MOZ_PIXMAN_LIBS"
;;
@@ -5129,9 +4963,6 @@ dnl
case "$OS_TARGET" in
Android)
- if test -n "$gonkdir"; then
- NECKO_WIFI=1
- fi
;;
Darwin)
if test -z "$MOZ_IOS"; then
@@ -5178,7 +5009,7 @@ fi
dnl
dnl Always build Marionette if not Android or B2G
dnl
-if test "$OS_TARGET" != Android -a x"$MOZ_WIDGET_TOOLKIT" != x"gonk"; then
+if test "$OS_TARGET" != "Android"; then
AC_DEFINE(ENABLE_MARIONETTE)
fi
AC_SUBST(ENABLE_MARIONETTE)
@@ -5257,6 +5088,8 @@ AC_SUBST(LIBICONV)
AC_SUBST(MOZ_TOOLKIT_SEARCH)
AC_SUBST(MOZ_FEEDS)
+AC_SUBST(ENABLE_TESTS)
+
AC_SUBST(MOZ_UNIVERSALCHARDET)
AC_SUBST(ACCESSIBILITY)
AC_SUBST(MOZ_SPELLCHECK)
@@ -5432,10 +5265,6 @@ else
MOZ_APP_MAXVERSION=$MOZ_APP_VERSION
fi
-MOZ_B2G_VERSION=${MOZ_B2G_VERSION:-"1.0.0"}
-AC_DEFINE_UNQUOTED(MOZ_B2G_VERSION,"$MOZ_B2G_VERSION")
-AC_DEFINE_UNQUOTED(MOZ_B2G_OS_NAME,"$MOZ_B2G_OS_NAME")
-
AC_SUBST(MOZ_APP_NAME)
AC_SUBST(MOZ_APP_REMOTINGNAME)
AC_SUBST(MOZ_APP_DISPLAYNAME)
@@ -5507,15 +5336,6 @@ dnl ========================================================
dnl ICU Support
dnl ========================================================
-# Internationalization is not built or exposed on Fennec.
-# See Bug 1215256
-
-if test "$MOZ_BUILD_APP" = "mobile/android"; then
- _INTL_API=no
-else
- _INTL_API=yes
-fi
-
if test "$MOZ_WIDGET_TOOLKIT" = "cocoa"; then
USE_ICU=1
fi
@@ -5745,7 +5565,6 @@ MOZ_OFFICIAL_BRANDING=$MOZ_OFFICIAL_BRANDING
MOZ_BRANDING_DIRECTORY=$MOZ_BRANDING_DIRECTORY
MC_BASILISK=$MC_BASILISK
MC_PALEMOON=$MC_PALEMOON
-MOZ_SANDBOX=$MOZ_SANDBOX
MOZ_EME=$MOZ_EME
MOZ_WEBRTC=$MOZ_WEBRTC
MOZ_SYSTEM_LIBEVENT=$MOZ_SYSTEM_LIBEVENT
@@ -5832,10 +5651,6 @@ AC_SUBST(NSS_DISABLE_LIBPKIX)
MOZ_CREATE_CONFIG_STATUS()
-if test "$COMPILE_ENVIRONMENT"; then
- MOZ_SUBCONFIGURE_JEMALLOC()
-fi
-
# Run freetype configure script
if test "$MOZ_TREE_FREETYPE"; then
diff --git a/python/mozbuild/mozbuild/backend/cpp_eclipse.py b/python/mozbuild/mozbuild/backend/cpp_eclipse.py
index cbdbdde8c..ae89df5b2 100644
--- a/python/mozbuild/mozbuild/backend/cpp_eclipse.py
+++ b/python/mozbuild/mozbuild/backend/cpp_eclipse.py
@@ -183,25 +183,12 @@ class CppEclipseBackend(CommonBackend):
exe_path = os.path.join(exe_path, self._appname + self._bin_suffix)
- if self.environment.substs['MOZ_WIDGET_TOOLKIT'] != 'gonk':
- main_gecko_launch = os.path.join(launch_dir, 'gecko.launch')
- with open(main_gecko_launch, 'wb') as fh:
- launch = GECKO_LAUNCH_CONFIG_TEMPLATE
- launch = launch.replace('@LAUNCH_PROGRAM@', exe_path)
- launch = launch.replace('@LAUNCH_ARGS@', '-P -no-remote')
- fh.write(launch)
-
- if self.environment.substs['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- b2g_flash = os.path.join(launch_dir, 'b2g-flash.launch')
- with open(b2g_flash, 'wb') as fh:
- # We assume that the srcdir is inside the b2g tree.
- # If that's not the case the user can always adjust the path
- # from the eclipse IDE.
- fastxul_path = os.path.join(self.environment.topsrcdir, '..', 'scripts', 'fastxul.sh')
- launch = B2GFLASH_LAUNCH_CONFIG_TEMPLATE
- launch = launch.replace('@LAUNCH_PROGRAM@', fastxul_path)
- launch = launch.replace('@OBJDIR@', self.environment.topobjdir)
- fh.write(launch)
+ main_gecko_launch = os.path.join(launch_dir, 'gecko.launch')
+ with open(main_gecko_launch, 'wb') as fh:
+ launch = GECKO_LAUNCH_CONFIG_TEMPLATE
+ launch = launch.replace('@LAUNCH_PROGRAM@', exe_path)
+ launch = launch.replace('@LAUNCH_ARGS@', '-P -no-remote')
+ fh.write(launch)
#TODO Add more launch configs (and delegate calls to mach)
diff --git a/python/mozbuild/mozbuild/base.py b/python/mozbuild/mozbuild/base.py
index 9ca689009..9d5897a34 100644
--- a/python/mozbuild/mozbuild/base.py
+++ b/python/mozbuild/mozbuild/base.py
@@ -753,16 +753,11 @@ class MachCommandConditions(object):
@staticmethod
def is_b2g(cls):
"""Must have a B2G build."""
- if hasattr(cls, 'substs'):
- return cls.substs.get('MOZ_WIDGET_TOOLKIT') == 'gonk'
return False
@staticmethod
def is_b2g_desktop(cls):
"""Must have a B2G desktop build."""
- if hasattr(cls, 'substs'):
- return cls.substs.get('MOZ_BUILD_APP') == 'b2g' and \
- cls.substs.get('MOZ_WIDGET_TOOLKIT') != 'gonk'
return False
@staticmethod
diff --git a/python/mozbuild/mozbuild/mozinfo.py b/python/mozbuild/mozbuild/mozinfo.py
index 3e1d0a760..db46d7c7d 100755
--- a/python/mozbuild/mozbuild/mozinfo.py
+++ b/python/mozbuild/mozbuild/mozinfo.py
@@ -37,7 +37,7 @@ def build_dict(config, env=os.environ):
known_os = {"Linux": "linux",
"WINNT": "win",
"Darwin": "mac",
- "Android": "b2g" if substs.get("MOZ_WIDGET_TOOLKIT") == "gonk" else "android"}
+ "Android": "android"}
if o in known_os:
d["os"] = known_os[o]
else:
@@ -111,14 +111,6 @@ def build_dict(config, env=os.environ):
return p
- if d['buildapp'] == 'b2g':
- if d['toolkit'] == 'gonk':
- return 'emulator'
-
- if d['bits'] == 64:
- return 'linux64_gecko'
- return 'linux32_gecko'
-
if d['buildapp'] == 'mobile/android':
if d['processor'] == 'x86':
return 'android-x86'
diff --git a/python/mozbuild/mozbuild/test/test_testing.py b/python/mozbuild/mozbuild/test/test_testing.py
index e71892e24..8610edd09 100644
--- a/python/mozbuild/mozbuild/test/test_testing.py
+++ b/python/mozbuild/mozbuild/test/test_testing.py
@@ -80,7 +80,7 @@ ALL_TESTS = {
"reason": "bug 820380",
"relpath": "test_0201_app_launch_apply_update.js",
"run-sequentially": "Launches application.",
- "skip-if": "toolkit == 'gonk' || os == 'android'",
+ "skip-if": os == 'android'",
"tail": ""
},
{
@@ -96,7 +96,7 @@ ALL_TESTS = {
"reason": "bug 820380",
"relpath": "test_0201_app_launch_apply_update.js",
"run-sequentially": "Launches application.",
- "skip-if": "toolkit == 'gonk' || os == 'android'",
+ "skip-if": os == 'android'",
"tail": ""
}
],
diff --git a/security/manager/.eslintrc.js b/security/manager/.eslintrc.js
index dc9d688aa..6b292f366 100644
--- a/security/manager/.eslintrc.js
+++ b/security/manager/.eslintrc.js
@@ -131,9 +131,6 @@ module.exports = { // eslint-disable-line no-undef
// No reassigning native JS objects
"no-native-reassign": "error",
- // No (!foo in bar)
- "no-negated-in-lhs": "error",
-
// Nested ternary statements are confusing
"no-nested-ternary": "error",
diff --git a/security/manager/pki/nsNSSDialogHelper.cpp b/security/manager/pki/nsNSSDialogHelper.cpp
index 1ec161b81..95d02a981 100644
--- a/security/manager/pki/nsNSSDialogHelper.cpp
+++ b/security/manager/pki/nsNSSDialogHelper.cpp
@@ -19,12 +19,6 @@ nsresult
nsNSSDialogHelper::openDialog(mozIDOMWindowProxy* window, const char* url,
nsISupports* params, bool modal)
{
-#ifdef MOZ_WIDGET_GONK
- // On b2g devices, we need to proxy the dialog creation & management
- // to Gaia.
- return NS_ERROR_NOT_IMPLEMENTED;
-#endif
-
nsresult rv;
nsCOMPtr<nsIWindowWatcher> windowWatcher =
do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
diff --git a/security/sandbox/chromium-shim/base/MissingBasicTypes.h b/security/sandbox/chromium-shim/base/MissingBasicTypes.h
deleted file mode 100644
index 20eef00ab..000000000
--- a/security/sandbox/chromium-shim/base/MissingBasicTypes.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef security_sandbox_MissingBasicTypes_h__
-#define security_sandbox_MissingBasicTypes_h__
-
-#include <stdint.h>
-
-// These types are still used by the Chromium sandbox code. When referencing
-// Chromium sandbox code from Gecko we can't use the normal base/basictypes.h as
-// it clashes with the one from ipc/chromium/src/base/. These types have been
-// removed from the one in ipc/chromium/src/base/.
-typedef int8_t int8;
-typedef uint8_t uint8;
-typedef int16_t int16;
-typedef uint16_t uint16;
-typedef int32_t int32;
-typedef uint32_t uint32;
-typedef int64_t int64;
-typedef uint64_t uint64;
-
-#endif // security_sandbox_MissingBasicTypes_h__
diff --git a/security/sandbox/chromium-shim/base/debug/debugging_flags.h b/security/sandbox/chromium-shim/base/debug/debugging_flags.h
deleted file mode 100644
index ebb96dfca..000000000
--- a/security/sandbox/chromium-shim/base/debug/debugging_flags.h
+++ /dev/null
@@ -1,19 +0,0 @@
-/* -*- 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/. */
-
-// This is a copy of a file that is generated by the chromium build.
-
-// Generated by build/write_buildflag_header.py
-// From "//base:debugging_flags"
-
-#ifndef BASE_DEBUG_DEBUGGING_FLAGS_H_
-#define BASE_DEBUG_DEBUGGING_FLAGS_H_
-
-#include "build/buildflag.h"
-
-#define BUILDFLAG_INTERNAL_ENABLE_PROFILING() (0)
-
-#endif // BASE_DEBUG_DEBUGGING_FLAGS_H_
diff --git a/security/sandbox/chromium-shim/base/file_version_info_win.h b/security/sandbox/chromium-shim/base/file_version_info_win.h
deleted file mode 100644
index 8276900bd..000000000
--- a/security/sandbox/chromium-shim/base/file_version_info_win.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-// This is a dummy version of Chromium source file base/file_version_info_win.h
-// Within our copy of Chromium files FileVersionInfoWin is only used in
-// base/win/windows_version.cc in GetVersionFromKernel32, which we don't use.
-
-#ifndef BASE_FILE_VERSION_INFO_WIN_H_
-#define BASE_FILE_VERSION_INFO_WIN_H_
-
-struct tagVS_FIXEDFILEINFO;
-typedef tagVS_FIXEDFILEINFO VS_FIXEDFILEINFO;
-
-namespace base {
-class FilePath;
-}
-
-class FileVersionInfoWin {
- public:
- static FileVersionInfoWin*
- CreateFileVersionInfo(const base::FilePath& file_path) { return nullptr; }
-
- VS_FIXEDFILEINFO* fixed_file_info() { return nullptr; }
-};
-
-#endif // BASE_FILE_VERSION_INFO_WIN_H_
diff --git a/security/sandbox/chromium-shim/base/files/file_path.cpp b/security/sandbox/chromium-shim/base/files/file_path.cpp
deleted file mode 100644
index 245118f9e..000000000
--- a/security/sandbox/chromium-shim/base/files/file_path.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-// 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 is a dummy version of Chromium source file base/file/file_path.cc.
-// To provide the functions required in base/win/windows_version.cc
-// GetVersionFromKernel32, which we don't use.
-
-#include "base/files/file_path.h"
-
-namespace base {
-
-FilePath::FilePath(FilePath::StringPieceType path) {
-}
-
-FilePath::~FilePath() {
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium-shim/base/gtest_prod_util.h b/security/sandbox/chromium-shim/base/gtest_prod_util.h
deleted file mode 100644
index 3eb93fa2a..000000000
--- a/security/sandbox/chromium-shim/base/gtest_prod_util.h
+++ /dev/null
@@ -1,17 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef FRIEND_TEST
-#define FRIEND_TEST(A, B)
-#endif
-
-#ifndef FRIEND_TEST_ALL_PREFIXES
-#define FRIEND_TEST_ALL_PREFIXES(test_case_name, test_name)
-#endif
-
-#ifndef FORWARD_DECLARE_TEST
-#define FORWARD_DECLARE_TEST(test_case_name, test_name)
-#endif
diff --git a/security/sandbox/chromium-shim/base/logging.cpp b/security/sandbox/chromium-shim/base/logging.cpp
deleted file mode 100644
index 9c2113dcb..000000000
--- a/security/sandbox/chromium-shim/base/logging.cpp
+++ /dev/null
@@ -1,156 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-// This is a stripped down version of the Chromium source file base/logging.cc
-// This prevents dependency on the Chromium logging and dependency creep in
-// general.
-// At some point we should find a way to hook this into our own logging see
-// bug 1013988.
-// The formatting in this file matches the original Chromium file to aid future
-// merging.
-
-#include "base/logging.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#endif
-
-#if defined(OS_POSIX)
-#include <errno.h>
-#endif
-
-#if defined(OS_WIN)
-#include "base/strings/utf_string_conversions.h"
-#endif
-
-#include <algorithm>
-
-namespace logging {
-
-namespace {
-
-int g_min_log_level = 0;
-
-LoggingDestination g_logging_destination = LOG_DEFAULT;
-
-// For LOG_ERROR and above, always print to stderr.
-const int kAlwaysPrintErrorLevel = LOG_ERROR;
-
-// A log message handler that gets notified of every log message we process.
-LogMessageHandlerFunction log_message_handler = nullptr;
-
-} // namespace
-
-void SetMinLogLevel(int level) {
- g_min_log_level = std::min(LOG_FATAL, level);
-}
-
-int GetMinLogLevel() {
- return g_min_log_level;
-}
-
-bool ShouldCreateLogMessage(int severity) {
- if (severity < g_min_log_level)
- return false;
-
- // Return true here unless we know ~LogMessage won't do anything. Note that
- // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
- // when g_logging_destination is LOG_NONE.
- return g_logging_destination != LOG_NONE || log_message_handler ||
- severity >= kAlwaysPrintErrorLevel;
-}
-
-int GetVlogLevelHelper(const char* file, size_t N) {
- return 0;
-}
-
-// Explicit instantiations for commonly used comparisons.
-template std::string* MakeCheckOpString<int, int>(
- const int&, const int&, const char* names);
-template std::string* MakeCheckOpString<unsigned long, unsigned long>(
- const unsigned long&, const unsigned long&, const char* names);
-template std::string* MakeCheckOpString<unsigned long, unsigned int>(
- const unsigned long&, const unsigned int&, const char* names);
-template std::string* MakeCheckOpString<unsigned int, unsigned long>(
- const unsigned int&, const unsigned long&, const char* names);
-template std::string* MakeCheckOpString<std::string, std::string>(
- const std::string&, const std::string&, const char* name);
-
-#if defined(OS_WIN)
-LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
-}
-
-LogMessage::SaveLastError::~SaveLastError() {
- ::SetLastError(last_error_);
-}
-#endif // defined(OS_WIN)
-
-LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
- : severity_(severity), file_(file), line_(line) {
-}
-
-LogMessage::LogMessage(const char* file, int line, const char* condition)
- : severity_(LOG_FATAL), file_(file), line_(line) {
-}
-
-LogMessage::LogMessage(const char* file, int line, std::string* result)
- : severity_(LOG_FATAL), file_(file), line_(line) {
- delete result;
-}
-
-LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
- std::string* result)
- : severity_(severity), file_(file), line_(line) {
- delete result;
-}
-
-LogMessage::~LogMessage() {
-}
-
-SystemErrorCode GetLastSystemErrorCode() {
-#if defined(OS_WIN)
- return ::GetLastError();
-#elif defined(OS_POSIX)
- return errno;
-#else
-#error Not implemented
-#endif
-}
-
-#if defined(OS_WIN)
-Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
- int line,
- LogSeverity severity,
- SystemErrorCode err)
- : err_(err),
- log_message_(file, line, severity) {
-}
-
-Win32ErrorLogMessage::~Win32ErrorLogMessage() {
-}
-#elif defined(OS_POSIX)
-ErrnoLogMessage::ErrnoLogMessage(const char* file,
- int line,
- LogSeverity severity,
- SystemErrorCode err)
- : err_(err),
- log_message_(file, line, severity) {
-}
-
-ErrnoLogMessage::~ErrnoLogMessage() {
-}
-#endif // OS_WIN
-
-void RawLog(int level, const char* message) {
-}
-
-} // namespace logging
-
-#if defined(OS_WIN)
-std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
- return out << base::WideToUTF8(std::wstring(wstr));
-}
-#endif
diff --git a/security/sandbox/chromium-shim/base/third_party/nspr/prtime.h b/security/sandbox/chromium-shim/base/third_party/nspr/prtime.h
deleted file mode 100644
index 9a18a3637..000000000
--- a/security/sandbox/chromium-shim/base/third_party/nspr/prtime.h
+++ /dev/null
@@ -1,8 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-// Grab the copy from in our tree
-#include "pr/include/prtime.h"
diff --git a/security/sandbox/chromium-shim/base/third_party/nspr/prtypes.h b/security/sandbox/chromium-shim/base/third_party/nspr/prtypes.h
deleted file mode 100644
index 6aec5e08f..000000000
--- a/security/sandbox/chromium-shim/base/third_party/nspr/prtypes.h
+++ /dev/null
@@ -1,8 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-// Grab the copy from in our tree
-#include "pr/include/prtypes.h"
diff --git a/security/sandbox/chromium-shim/base/tracked_objects.h b/security/sandbox/chromium-shim/base/tracked_objects.h
deleted file mode 100644
index 837705ee9..000000000
--- a/security/sandbox/chromium-shim/base/tracked_objects.h
+++ /dev/null
@@ -1,19 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef _SECURITY_SANDBOX_TRACKED_OBJECTS_H_
-#define _SECURITY_SANDBOX_TRACKED_OBJECTS_H_
-namespace tracked_objects
-{
- class ThreadData
- {
- public:
- static void InitializeThreadContext(const std::string& name)
- {
- }
- };
-}
-#endif
diff --git a/security/sandbox/chromium-shim/base/win/registry.h b/security/sandbox/chromium-shim/base/win/registry.h
deleted file mode 100644
index 9fba57277..000000000
--- a/security/sandbox/chromium-shim/base/win/registry.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-// This is a stripped down version of Chromium source file base/win/registry.h
-// Within our copy of Chromium files this is only used in base/win/windows_version.cc
-// in OSInfo::processor_model_name, which we don't use.
-
-#ifndef BASE_WIN_REGISTRY_H_
-#define BASE_WIN_REGISTRY_H_
-
-namespace base {
-namespace win {
-
-class BASE_EXPORT RegKey {
- public:
- RegKey(HKEY rootkey, const wchar_t* subkey, REGSAM access) {}
- ~RegKey() {}
-
- LONG ReadValue(const wchar_t* name, std::wstring* out_value) const
- {
- return 0;
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(RegKey);
-};
-
-} // namespace win
-} // namespace base
-
-#endif // BASE_WIN_REGISTRY_H_
diff --git a/security/sandbox/chromium-shim/base/win/sdkdecls.h b/security/sandbox/chromium-shim/base/win/sdkdecls.h
deleted file mode 100644
index e999ab967..000000000
--- a/security/sandbox/chromium-shim/base/win/sdkdecls.h
+++ /dev/null
@@ -1,191 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef _SECURITY_SANDBOX_BASE_SHIM_SDKDECLS_H_
-#define _SECURITY_SANDBOX_BASE_SHIM_SDKDECLS_H_
-
-#include <windows.h>
-
-// This file contains definitions required for things dynamically loaded
-// while building or targetting lower platform versions or lower SDKs.
-
-#if (_WIN32_WINNT < 0x0600)
-typedef struct _STARTUPINFOEXA {
- STARTUPINFOA StartupInfo;
- LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
-} STARTUPINFOEXA, *LPSTARTUPINFOEXA;
-typedef struct _STARTUPINFOEXW {
- STARTUPINFOW StartupInfo;
- LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
-} STARTUPINFOEXW, *LPSTARTUPINFOEXW;
-#ifdef UNICODE
-typedef STARTUPINFOEXW STARTUPINFOEX;
-typedef LPSTARTUPINFOEXW LPSTARTUPINFOEX;
-#else
-typedef STARTUPINFOEXA STARTUPINFOEX;
-typedef LPSTARTUPINFOEXA LPSTARTUPINFOEX;
-#endif // UNICODE
-
-#define PROC_THREAD_ATTRIBUTE_NUMBER 0x0000FFFF
-#define PROC_THREAD_ATTRIBUTE_THREAD 0x00010000 // Attribute may be used with thread creation
-#define PROC_THREAD_ATTRIBUTE_INPUT 0x00020000 // Attribute is input only
-#define PROC_THREAD_ATTRIBUTE_ADDITIVE 0x00040000 // Attribute may be "accumulated," e.g. bitmasks, counters, etc.
-
-#define ProcThreadAttributeValue(Number, Thread, Input, Additive) \
- (((Number) & PROC_THREAD_ATTRIBUTE_NUMBER) | \
- ((Thread != FALSE) ? PROC_THREAD_ATTRIBUTE_THREAD : 0) | \
- ((Input != FALSE) ? PROC_THREAD_ATTRIBUTE_INPUT : 0) | \
- ((Additive != FALSE) ? PROC_THREAD_ATTRIBUTE_ADDITIVE : 0))
-
-#define ProcThreadAttributeHandleList 2
-
-#define PROC_THREAD_ATTRIBUTE_HANDLE_LIST \
- ProcThreadAttributeValue (ProcThreadAttributeHandleList, FALSE, TRUE, FALSE)
-
-#define PROCESS_DEP_ENABLE 0x00000001
-#define PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION 0x00000002
-
-// They dynamically load these, but they still use the functions to describe the
-// function pointers!
-WINBASEAPI
-int
-WINAPI
-GetUserDefaultLocaleName(
- _Out_writes_(cchLocaleName) LPWSTR lpLocaleName,
- _In_ int cchLocaleName
-);
-
-WINBASEAPI
-BOOL
-WINAPI
-QueryThreadCycleTime(
- _In_ HANDLE ThreadHandle,
- _Out_ PULONG64 CycleTime
- );
-
-#endif // (_WIN32_WINNT >= 0x0600)
-
-#if (_WIN32_WINNT < 0x0601)
-#define ProcThreadAttributeMitigationPolicy 7
-#define PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY \
- ProcThreadAttributeValue (ProcThreadAttributeMitigationPolicy, FALSE, TRUE, FALSE)
-
-#define PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE 0x01
-#define PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE 0x02
-#define PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE 0x04
-#endif // (_WIN32_WINNT >= 0x0601)
-
-#if (_WIN32_WINNT < 0x0602)
-#define ProcThreadAttributeSecurityCapabilities 9
-#define PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES \
- ProcThreadAttributeValue (ProcThreadAttributeSecurityCapabilities, FALSE, TRUE, FALSE)
-
-#define PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_MASK (0x00000003 << 8)
-#define PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_DEFER (0x00000000 << 8)
-#define PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON (0x00000001 << 8)
-#define PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_OFF (0x00000002 << 8)
-#define PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS (0x00000003 << 8)
-#define PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_MASK (0x00000003 << 12)
-#define PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_DEFER (0x00000000 << 12)
-#define PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON (0x00000001 << 12)
-#define PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_OFF (0x00000002 << 12)
-#define PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_RESERVED (0x00000003 << 12)
-#define PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_MASK (0x00000003 << 16)
-#define PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_DEFER (0x00000000 << 16)
-#define PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON (0x00000001 << 16)
-#define PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_OFF (0x00000002 << 16)
-#define PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_RESERVED (0x00000003 << 16)
-#define PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_MASK (0x00000003 << 20)
-#define PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_DEFER (0x00000000 << 20)
-#define PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON (0x00000001 << 20)
-#define PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_OFF (0x00000002 << 20)
-#define PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_RESERVED (0x00000003 << 20)
-#define PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_MASK (0x00000003 << 24)
-#define PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_DEFER (0x00000000 << 24)
-#define PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON (0x00000001 << 24)
-#define PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_OFF (0x00000002 << 24)
-#define PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_RESERVED (0x00000003 << 24)
-#define PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_MASK (0x00000003 << 28)
-#define PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_DEFER (0x00000000 << 28)
-#define PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON (0x00000001 << 28)
-#define PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_OFF (0x00000002 << 28)
-#define PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_RESERVED (0x00000003 << 28)
-#define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_MASK (0x00000003ui64 << 32)
-#define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_DEFER (0x00000000ui64 << 32)
-#define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON (0x00000001ui64 << 32)
-#define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_OFF (0x00000002ui64 << 32)
-#define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_RESERVED (0x00000003ui64 << 32)
-
-// Check if we're including >= win8 winnt.h
-#ifndef NTDDI_WIN8
-
-typedef struct _SECURITY_CAPABILITIES {
- PSID AppContainerSid;
- PSID_AND_ATTRIBUTES Capabilities;
- DWORD CapabilityCount;
- DWORD Reserved;
-} SECURITY_CAPABILITIES, *PSECURITY_CAPABILITIES, *LPSECURITY_CAPABILITIES;
-
-typedef enum _PROCESS_MITIGATION_POLICY {
- ProcessDEPPolicy,
- ProcessASLRPolicy,
- ProcessReserved1MitigationPolicy,
- ProcessStrictHandleCheckPolicy,
- ProcessSystemCallDisablePolicy,
- ProcessMitigationOptionsMask,
- ProcessExtensionPointDisablePolicy,
- MaxProcessMitigationPolicy
-} PROCESS_MITIGATION_POLICY, *PPROCESS_MITIGATION_POLICY;
-
-#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
-
-typedef struct _PROCESS_MITIGATION_ASLR_POLICY {
- union {
- DWORD Flags;
- struct {
- DWORD EnableBottomUpRandomization : 1;
- DWORD EnableForceRelocateImages : 1;
- DWORD EnableHighEntropy : 1;
- DWORD DisallowStrippedImages : 1;
- DWORD ReservedFlags : 28;
- };
- };
-} PROCESS_MITIGATION_ASLR_POLICY, *PPROCESS_MITIGATION_ASLR_POLICY;
-
-typedef struct _PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY {
- union {
- DWORD Flags;
- struct {
- DWORD RaiseExceptionOnInvalidHandleReference : 1;
- DWORD HandleExceptionsPermanentlyEnabled : 1;
- DWORD ReservedFlags : 30;
- };
- };
-} PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY, *PPROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY;
-
-typedef struct _PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY {
- union {
- DWORD Flags;
- struct {
- DWORD DisallowWin32kSystemCalls : 1;
- DWORD ReservedFlags : 31;
- };
- };
-} PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY, *PPROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY;
-
-typedef struct _PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY {
- union {
- DWORD Flags;
- struct {
- DWORD DisableExtensionPoints : 1;
- DWORD ReservedFlags : 31;
- };
- };
-} PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY, *PPROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY;
-
-#endif // NTDDI_WIN8
-#endif // (_WIN32_WINNT < 0x0602)
-#endif // _SECURITY_SANDBOX_BASE_SHIM_SDKDECLS_H_
diff --git a/security/sandbox/chromium-shim/sandbox/win/loggingCallbacks.h b/security/sandbox/chromium-shim/sandbox/win/loggingCallbacks.h
deleted file mode 100644
index f9402c527..000000000
--- a/security/sandbox/chromium-shim/sandbox/win/loggingCallbacks.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef security_sandbox_loggingCallbacks_h__
-#define security_sandbox_loggingCallbacks_h__
-
-#include <sstream>
-#include <iostream>
-
-#include "mozilla/Logging.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/sandboxing/loggingTypes.h"
-#include "nsContentUtils.h"
-
-#include "mozilla/StackWalk.h"
-
-namespace mozilla {
-
-static LazyLogModule sSandboxTargetLog("SandboxTarget");
-
-#define LOG_D(...) MOZ_LOG(sSandboxTargetLog, LogLevel::Debug, (__VA_ARGS__))
-
-namespace sandboxing {
-
-static uint32_t sStackTraceDepth = 0;
-
-// NS_WalkStackCallback to write a formatted stack frame to an ostringstream.
-static void
-StackFrameToOStringStream(uint32_t aFrameNumber, void* aPC, void* aSP,
- void* aClosure)
-{
- std::ostringstream* stream = static_cast<std::ostringstream*>(aClosure);
- MozCodeAddressDetails details;
- char buf[1024];
- MozDescribeCodeAddress(aPC, &details);
- MozFormatCodeAddressDetails(buf, sizeof(buf), aFrameNumber, aPC, &details);
- *stream << std::endl << "--" << buf;
- stream->flush();
-}
-
-// Log to the browser console and, if DEBUG build, stderr.
-static void
-Log(const char* aMessageType,
- const char* aFunctionName,
- const char* aContext,
- const bool aShouldLogStackTrace = false,
- uint32_t aFramesToSkip = 0)
-{
- std::ostringstream msgStream;
- msgStream << "Process Sandbox " << aMessageType << ": " << aFunctionName;
- if (aContext) {
- msgStream << " for : " << aContext;
- }
-
- if (aShouldLogStackTrace) {
- if (sStackTraceDepth) {
- msgStream << std::endl << "Stack Trace:";
- MozStackWalk(StackFrameToOStringStream, aFramesToSkip, sStackTraceDepth,
- &msgStream, 0, nullptr);
- }
- }
-
- std::string msg = msgStream.str();
-#if defined(DEBUG)
- // Use NS_DebugBreak directly as we want child process prefix, but not source
- // file or line number.
- NS_DebugBreak(NS_DEBUG_WARNING, nullptr, msg.c_str(), nullptr, -1);
-#endif
-
- if (nsContentUtils::IsInitialized()) {
- nsContentUtils::LogMessageToConsole(msg.c_str());
- }
-
- // As we don't always have the facility to log to console use MOZ_LOG as well.
- LOG_D("%s", msg.c_str());
-}
-
-// Initialize sandbox logging if required.
-static void
-InitLoggingIfRequired(ProvideLogFunctionCb aProvideLogFunctionCb)
-{
- if (!aProvideLogFunctionCb) {
- return;
- }
-
- if (Preferences::GetBool("security.sandbox.windows.log") ||
- PR_GetEnv("MOZ_WIN_SANDBOX_LOGGING")) {
- aProvideLogFunctionCb(Log);
-
-#if defined(MOZ_CONTENT_SANDBOX)
- // We can only log the stack trace on process types where we know that the
- // sandbox won't prevent it.
- if (XRE_IsContentProcess()) {
- Preferences::AddUintVarCache(&sStackTraceDepth,
- "security.sandbox.windows.log.stackTraceDepth");
- }
-#endif
- }
-}
-
-} // sandboxing
-} // mozilla
-
-#endif // security_sandbox_loggingCallbacks_h__
diff --git a/security/sandbox/chromium-shim/sandbox/win/loggingTypes.h b/security/sandbox/chromium-shim/sandbox/win/loggingTypes.h
deleted file mode 100644
index c9b74c14e..000000000
--- a/security/sandbox/chromium-shim/sandbox/win/loggingTypes.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef security_sandbox_loggingTypes_h__
-#define security_sandbox_loggingTypes_h__
-
-#include <stdint.h>
-
-namespace mozilla {
-namespace sandboxing {
-
-// We are using callbacks here that are passed in from the core code to prevent
-// a circular dependency in the linking during the build.
-typedef void (*LogFunction) (const char* aMessageType,
- const char* aFunctionName,
- const char* aContext,
- const bool aShouldLogStackTrace,
- uint32_t aFramesToSkip);
-typedef void (*ProvideLogFunctionCb) (LogFunction aLogFunction);
-
-} // sandboxing
-} // mozilla
-
-#endif // security_sandbox_loggingTypes_h__
diff --git a/security/sandbox/chromium-shim/sandbox/win/sandboxLogging.cpp b/security/sandbox/chromium-shim/sandbox/win/sandboxLogging.cpp
deleted file mode 100644
index fa2314f69..000000000
--- a/security/sandbox/chromium-shim/sandbox/win/sandboxLogging.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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 "sandboxLogging.h"
-
-#include "base/strings/utf_string_conversions.h"
-#include "sandbox/win/src/sandbox_policy.h"
-
-namespace mozilla {
-namespace sandboxing {
-
-static LogFunction sLogFunction = nullptr;
-
-void
-ProvideLogFunction(LogFunction aLogFunction)
-{
- sLogFunction = aLogFunction;
-}
-
-void
-LogBlocked(const char* aFunctionName, const char* aContext, uint32_t aFramesToSkip)
-{
- if (sLogFunction) {
- sLogFunction("BLOCKED", aFunctionName, aContext,
- /* aShouldLogStackTrace */ true, aFramesToSkip);
- }
-}
-
-void
-LogBlocked(const char* aFunctionName, const wchar_t* aContext)
-{
- if (sLogFunction) {
- // Skip an extra frame to allow for this function.
- LogBlocked(aFunctionName, base::WideToUTF8(aContext).c_str(),
- /* aFramesToSkip */ 3);
- }
-}
-
-void
-LogBlocked(const char* aFunctionName, const wchar_t* aContext,
- uint16_t aLengthInBytes)
-{
- if (sLogFunction) {
- // Skip an extra frame to allow for this function.
- LogBlocked(aFunctionName,
- base::WideToUTF8(std::wstring(aContext, aLengthInBytes / sizeof(wchar_t))).c_str(),
- /* aFramesToSkip */ 3);
- }
-}
-
-void
-LogAllowed(const char* aFunctionName, const char* aContext)
-{
- if (sLogFunction) {
- sLogFunction("Broker ALLOWED", aFunctionName, aContext,
- /* aShouldLogStackTrace */ false, /* aFramesToSkip */ 0);
- }
-}
-
-void
-LogAllowed(const char* aFunctionName, const wchar_t* aContext)
-{
- if (sLogFunction) {
- LogAllowed(aFunctionName, base::WideToUTF8(aContext).c_str());
- }
-}
-
-void
-LogAllowed(const char* aFunctionName, const wchar_t* aContext,
- uint16_t aLengthInBytes)
-{
- if (sLogFunction) {
- LogAllowed(aFunctionName,
- base::WideToUTF8(std::wstring(aContext, aLengthInBytes / sizeof(wchar_t))).c_str());
- }
-}
-
-} // sandboxing
-} // mozilla
diff --git a/security/sandbox/chromium-shim/sandbox/win/sandboxLogging.h b/security/sandbox/chromium-shim/sandbox/win/sandboxLogging.h
deleted file mode 100644
index 365afa574..000000000
--- a/security/sandbox/chromium-shim/sandbox/win/sandboxLogging.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-/*
- * Set of helper methods to implement logging for Windows sandbox.
- */
-
-#ifndef security_sandbox_sandboxLogging_h__
-#define security_sandbox_sandboxLogging_h__
-
-#include "loggingTypes.h"
-
-namespace sandbox {
-class TargetPolicy;
-}
-
-namespace mozilla {
-namespace sandboxing {
-
-// This is used to pass a LogCallback to the sandboxing code, as the logging
-// requires code to which we cannot link directly.
-void ProvideLogFunction(LogFunction aLogFunction);
-
-// Log a "BLOCKED" msg to the browser console and, if DEBUG build, stderr.
-// If the logging of a stack trace is enabled then the default aFramesToSkip
-// will start from our caller's caller, which should normally be the function
-// that triggered the interception.
-void LogBlocked(const char* aFunctionName, const char* aContext = nullptr,
- uint32_t aFramesToSkip = 2);
-
-// Convenience functions to convert to char*.
-void LogBlocked(const char* aFunctionName, const wchar_t* aContext);
-void LogBlocked(const char* aFunctionName, const wchar_t* aContext,
- uint16_t aLengthInBytes);
-
-// Log a "ALLOWED" msg to the browser console and, if DEBUG build, stderr.
-void LogAllowed(const char* aFunctionName, const char* aContext = nullptr);
-
-// Convenience functions to convert to char*.
-void LogAllowed(const char* aFunctionName, const wchar_t* aContext);
-void LogAllowed(const char* aFunctionName, const wchar_t* aContext,
- uint16_t aLengthInBytes);
-
-
-} // sandboxing
-} // mozilla
-
-#endif // security_sandbox_sandboxLogging_h__
diff --git a/security/sandbox/chromium/LICENSE b/security/sandbox/chromium/LICENSE
deleted file mode 100644
index a32e00ce6..000000000
--- a/security/sandbox/chromium/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-// Copyright 2015 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/security/sandbox/chromium/base/at_exit.cc b/security/sandbox/chromium/base/at_exit.cc
deleted file mode 100644
index 0fba35569..000000000
--- a/security/sandbox/chromium/base/at_exit.cc
+++ /dev/null
@@ -1,82 +0,0 @@
-// 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/at_exit.h"
-
-#include <stddef.h>
-#include <ostream>
-
-#include "base/bind.h"
-#include "base/callback.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 (for a
-// statically linked version of this library). Testing may use the shadow
-// version of the constructor, and if we are building a dynamic library we may
-// end up with multiple AtExitManagers on the same process. 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() : next_manager_(g_top_manager) {
-// If multiple modules instantiate AtExitManagers they'll end up living in this
-// module... they have to coexist.
-#if !defined(COMPONENT_BUILD)
- DCHECK(!g_top_manager);
-#endif
- g_top_manager = this;
-}
-
-AtExitManager::~AtExitManager() {
- if (!g_top_manager) {
- NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
- return;
- }
- DCHECK_EQ(this, g_top_manager);
-
- ProcessCallbacksNow();
- g_top_manager = next_manager_;
-}
-
-// static
-void AtExitManager::RegisterCallback(AtExitCallbackType func, void* param) {
- DCHECK(func);
- RegisterTask(base::Bind(func, param));
-}
-
-// static
-void AtExitManager::RegisterTask(base::Closure task) {
- if (!g_top_manager) {
- NOTREACHED() << "Tried to RegisterCallback without an AtExitManager";
- return;
- }
-
- AutoLock lock(g_top_manager->lock_);
- g_top_manager->stack_.push(task);
-}
-
-// static
-void AtExitManager::ProcessCallbacksNow() {
- if (!g_top_manager) {
- NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
- return;
- }
-
- AutoLock lock(g_top_manager->lock_);
-
- while (!g_top_manager->stack_.empty()) {
- base::Closure task = g_top_manager->stack_.top();
- task.Run();
- g_top_manager->stack_.pop();
- }
-}
-
-AtExitManager::AtExitManager(bool shadow) : next_manager_(g_top_manager) {
- DCHECK(shadow || !g_top_manager);
- g_top_manager = this;
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/at_exit.h b/security/sandbox/chromium/base/at_exit.h
deleted file mode 100644
index 04e3f7642..000000000
--- a/security/sandbox/chromium/base/at_exit.h
+++ /dev/null
@@ -1,76 +0,0 @@
-// 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_AT_EXIT_H_
-#define BASE_AT_EXIT_H_
-
-#include <stack>
-
-#include "base/base_export.h"
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.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 BASE_EXPORT AtExitManager {
- 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(void*).
- static void RegisterCallback(AtExitCallbackType func, void* param);
-
- // Registers the specified task to be called at exit.
- static void RegisterTask(base::Closure task);
-
- // Calls the functions registered with RegisterCallback in LIFO order. It
- // is possible to register new callbacks after calling this function.
- static void ProcessCallbacksNow();
-
- 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);
-
- private:
- base::Lock lock_;
- std::stack<base::Closure> stack_;
- AtExitManager* next_manager_; // Stack of managers to allow shadowing.
-
- DISALLOW_COPY_AND_ASSIGN(AtExitManager);
-};
-
-#if defined(UNIT_TEST)
-class ShadowingAtExitManager : public AtExitManager {
- public:
- ShadowingAtExitManager() : AtExitManager(true) {}
-};
-#endif // defined(UNIT_TEST)
-
-} // namespace base
-
-#endif // BASE_AT_EXIT_H_
diff --git a/security/sandbox/chromium/base/atomic_ref_count.h b/security/sandbox/chromium/base/atomic_ref_count.h
deleted file mode 100644
index 2ab724200..000000000
--- a/security/sandbox/chromium/base/atomic_ref_count.h
+++ /dev/null
@@ -1,66 +0,0 @@
-// 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.
-
-// This is a low level implementation of atomic semantics for reference
-// counting. Please use base/memory/ref_counted.h directly instead.
-
-#ifndef BASE_ATOMIC_REF_COUNT_H_
-#define BASE_ATOMIC_REF_COUNT_H_
-
-#include "base/atomicops.h"
-
-namespace base {
-
-typedef subtle::Atomic32 AtomicRefCount;
-
-// Increment a reference count by "increment", which must exceed 0.
-inline void AtomicRefCountIncN(volatile AtomicRefCount *ptr,
- AtomicRefCount increment) {
- subtle::NoBarrier_AtomicIncrement(ptr, increment);
-}
-
-// Decrement a reference count by "decrement", which must exceed 0,
-// and return whether the result is non-zero.
-// Insert barriers to ensure that state written before the reference count
-// became zero will be visible to a thread that has just made the count zero.
-inline bool AtomicRefCountDecN(volatile AtomicRefCount *ptr,
- AtomicRefCount decrement) {
- bool res = (subtle::Barrier_AtomicIncrement(ptr, -decrement) != 0);
- return res;
-}
-
-// Increment a reference count by 1.
-inline void AtomicRefCountInc(volatile AtomicRefCount *ptr) {
- base::AtomicRefCountIncN(ptr, 1);
-}
-
-// Decrement a reference count by 1 and return whether the result is non-zero.
-// Insert barriers to ensure that state written before the reference count
-// became zero will be visible to a thread that has just made the count zero.
-inline bool AtomicRefCountDec(volatile AtomicRefCount *ptr) {
- return base::AtomicRefCountDecN(ptr, 1);
-}
-
-// Return whether the reference count is one. If the reference count is used
-// in the conventional way, a refrerence count of 1 implies that the current
-// thread owns the reference and no other thread shares it. This call performs
-// the test for a reference count of one, and performs the memory barrier
-// needed for the owning thread to act on the object, knowing that it has
-// exclusive access to the object.
-inline bool AtomicRefCountIsOne(volatile AtomicRefCount *ptr) {
- bool res = (subtle::Acquire_Load(ptr) == 1);
- return res;
-}
-
-// Return whether the reference count is zero. With conventional object
-// referencing counting, the object will be destroyed, so the reference count
-// should never be zero. Hence this is generally used for a debug check.
-inline bool AtomicRefCountIsZero(volatile AtomicRefCount *ptr) {
- bool res = (subtle::Acquire_Load(ptr) == 0);
- return res;
-}
-
-} // namespace base
-
-#endif // BASE_ATOMIC_REF_COUNT_H_
diff --git a/security/sandbox/chromium/base/atomic_sequence_num.h b/security/sandbox/chromium/base/atomic_sequence_num.h
deleted file mode 100644
index 59b0d2551..000000000
--- a/security/sandbox/chromium/base/atomic_sequence_num.h
+++ /dev/null
@@ -1,60 +0,0 @@
-// 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.
-
-#ifndef BASE_ATOMIC_SEQUENCE_NUM_H_
-#define BASE_ATOMIC_SEQUENCE_NUM_H_
-
-#include "base/atomicops.h"
-#include "base/macros.h"
-
-namespace base {
-
-class AtomicSequenceNumber;
-
-// Static (POD) AtomicSequenceNumber that MUST be used in global scope (or
-// non-function scope) ONLY. This implementation does not generate any static
-// initializer. Note that it does not implement any constructor which means
-// that its fields are not initialized except when it is stored in the global
-// data section (.data in ELF). If you want to allocate an atomic sequence
-// number on the stack (or heap), please use the AtomicSequenceNumber class
-// declared below.
-class StaticAtomicSequenceNumber {
- public:
- inline int GetNext() {
- return static_cast<int>(
- base::subtle::NoBarrier_AtomicIncrement(&seq_, 1) - 1);
- }
-
- private:
- friend class AtomicSequenceNumber;
-
- inline void Reset() {
- base::subtle::Release_Store(&seq_, 0);
- }
-
- base::subtle::Atomic32 seq_;
-};
-
-// AtomicSequenceNumber that can be stored and used safely (i.e. its fields are
-// always initialized as opposed to StaticAtomicSequenceNumber declared above).
-// Please use StaticAtomicSequenceNumber if you want to declare an atomic
-// sequence number in the global scope.
-class AtomicSequenceNumber {
- public:
- AtomicSequenceNumber() {
- seq_.Reset();
- }
-
- inline int GetNext() {
- return seq_.GetNext();
- }
-
- private:
- StaticAtomicSequenceNumber seq_;
- DISALLOW_COPY_AND_ASSIGN(AtomicSequenceNumber);
-};
-
-} // namespace base
-
-#endif // BASE_ATOMIC_SEQUENCE_NUM_H_
diff --git a/security/sandbox/chromium/base/atomicops.h b/security/sandbox/chromium/base/atomicops.h
deleted file mode 100644
index 3428fe87a..000000000
--- a/security/sandbox/chromium/base/atomicops.h
+++ /dev/null
@@ -1,161 +0,0 @@
-// 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.
-
-// For atomic operations on reference counts, see atomic_refcount.h.
-// For atomic operations on sequence numbers, see atomic_sequence_num.h.
-
-// The routines exported by this module are subtle. If you use them, even if
-// you get the code right, it will depend on careful reasoning about atomicity
-// and memory ordering; it will be less readable, and harder to maintain. If
-// you plan to use these routines, you should have a good reason, such as solid
-// evidence that performance would otherwise suffer, or there being no
-// alternative. You should assume only properties explicitly guaranteed by the
-// specifications in this file. You are almost certainly _not_ writing code
-// just for the x86; if you assume x86 semantics, x86 hardware bugs and
-// implementations on other archtectures will cause your code to break. If you
-// do not know what you are doing, avoid these routines, and use a Mutex.
-//
-// It is incorrect to make direct assignments to/from an atomic variable.
-// You should use one of the Load or Store routines. The NoBarrier
-// versions are provided when no barriers are needed:
-// NoBarrier_Store()
-// NoBarrier_Load()
-// Although there are currently no compiler enforcement, you are encouraged
-// to use these.
-//
-
-#ifndef BASE_ATOMICOPS_H_
-#define BASE_ATOMICOPS_H_
-
-#include <stdint.h>
-
-// Small C++ header which defines implementation specific macros used to
-// identify the STL implementation.
-// - libc++: captures __config for _LIBCPP_VERSION
-// - libstdc++: captures bits/c++config.h for __GLIBCXX__
-#include <cstddef>
-
-#include "base/base_export.h"
-#include "build/build_config.h"
-
-#if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
-// windows.h #defines this (only on x64). This causes problems because the
-// public API also uses MemoryBarrier at the public name for this fence. So, on
-// X64, undef it, and call its documented
-// (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx)
-// implementation directly.
-#undef MemoryBarrier
-#endif
-
-namespace base {
-namespace subtle {
-
-typedef int32_t Atomic32;
-#ifdef ARCH_CPU_64_BITS
-// We need to be able to go between Atomic64 and AtomicWord implicitly. This
-// means Atomic64 and AtomicWord should be the same type on 64-bit.
-#if defined(__ILP32__) || defined(OS_NACL)
-// NaCl's intptr_t is not actually 64-bits on 64-bit!
-// http://code.google.com/p/nativeclient/issues/detail?id=1162
-typedef int64_t Atomic64;
-#else
-typedef intptr_t Atomic64;
-#endif
-#endif
-
-// Use AtomicWord for a machine-sized pointer. It will use the Atomic32 or
-// Atomic64 routines below, depending on your architecture.
-typedef intptr_t AtomicWord;
-
-// Atomically execute:
-// result = *ptr;
-// if (*ptr == old_value)
-// *ptr = new_value;
-// return result;
-//
-// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value".
-// Always return the old value of "*ptr"
-//
-// This routine implies no memory barriers.
-Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value);
-
-// Atomically store new_value into *ptr, returning the previous value held in
-// *ptr. This routine implies no memory barriers.
-Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value);
-
-// Atomically increment *ptr by "increment". Returns the new value of
-// *ptr with the increment applied. This routine implies no memory barriers.
-Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment);
-
-Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment);
-
-// These following lower-level operations are typically useful only to people
-// implementing higher-level synchronization operations like spinlocks,
-// mutexes, and condition-variables. They combine CompareAndSwap(), a load, or
-// a store with appropriate memory-ordering instructions. "Acquire" operations
-// ensure that no later memory access can be reordered ahead of the operation.
-// "Release" operations ensure that no previous memory access can be reordered
-// after the operation. "Barrier" operations have both "Acquire" and "Release"
-// semantics. A MemoryBarrier() has "Barrier" semantics, but does no memory
-// access.
-Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value);
-Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value);
-
-void MemoryBarrier();
-void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value);
-void Acquire_Store(volatile Atomic32* ptr, Atomic32 value);
-void Release_Store(volatile Atomic32* ptr, Atomic32 value);
-
-Atomic32 NoBarrier_Load(volatile const Atomic32* ptr);
-Atomic32 Acquire_Load(volatile const Atomic32* ptr);
-Atomic32 Release_Load(volatile const Atomic32* ptr);
-
-// 64-bit atomic operations (only available on 64-bit processors).
-#ifdef ARCH_CPU_64_BITS
-Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value);
-Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value);
-Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment);
-Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment);
-
-Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value);
-Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value);
-void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value);
-void Acquire_Store(volatile Atomic64* ptr, Atomic64 value);
-void Release_Store(volatile Atomic64* ptr, Atomic64 value);
-Atomic64 NoBarrier_Load(volatile const Atomic64* ptr);
-Atomic64 Acquire_Load(volatile const Atomic64* ptr);
-Atomic64 Release_Load(volatile const Atomic64* ptr);
-#endif // ARCH_CPU_64_BITS
-
-} // namespace subtle
-} // namespace base
-
-#if defined(OS_WIN)
-// TODO(jfb): The MSVC header includes windows.h, which other files end up
-// relying on. Fix this as part of crbug.com/559247.
-# include "base/atomicops_internals_x86_msvc.h"
-#else
-# include "base/atomicops_internals_portable.h"
-#endif
-
-// On some platforms we need additional declarations to make
-// AtomicWord compatible with our other Atomic* types.
-#if defined(OS_MACOSX) || defined(OS_OPENBSD)
-#include "base/atomicops_internals_atomicword_compat.h"
-#endif
-
-#endif // BASE_ATOMICOPS_H_
diff --git a/security/sandbox/chromium/base/atomicops_internals_portable.h b/security/sandbox/chromium/base/atomicops_internals_portable.h
deleted file mode 100644
index ee034dee1..000000000
--- a/security/sandbox/chromium/base/atomicops_internals_portable.h
+++ /dev/null
@@ -1,229 +0,0 @@
-// Copyright (c) 2014 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 is an internal atomic implementation, use atomicops.h instead.
-//
-// This implementation uses C++11 atomics' member functions. The code base is
-// currently written assuming atomicity revolves around accesses instead of
-// C++11's memory locations. The burden is on the programmer to ensure that all
-// memory locations accessed atomically are never accessed non-atomically (tsan
-// should help with this).
-//
-// TODO(jfb) Modify the atomicops.h API and user code to declare atomic
-// locations as truly atomic. See the static_assert below.
-//
-// Of note in this implementation:
-// * All NoBarrier variants are implemented as relaxed.
-// * All Barrier variants are implemented as sequentially-consistent.
-// * Compare exchange's failure ordering is always the same as the success one
-// (except for release, which fails as relaxed): using a weaker ordering is
-// only valid under certain uses of compare exchange.
-// * Acquire store doesn't exist in the C11 memory model, it is instead
-// implemented as a relaxed store followed by a sequentially consistent
-// fence.
-// * Release load doesn't exist in the C11 memory model, it is instead
-// implemented as sequentially consistent fence followed by a relaxed load.
-// * Atomic increment is expected to return the post-incremented value, whereas
-// C11 fetch add returns the previous value. The implementation therefore
-// needs to increment twice (which the compiler should be able to detect and
-// optimize).
-
-#ifndef BASE_ATOMICOPS_INTERNALS_PORTABLE_H_
-#define BASE_ATOMICOPS_INTERNALS_PORTABLE_H_
-
-#include <atomic>
-
-#include "build/build_config.h"
-
-namespace base {
-namespace subtle {
-
-// This implementation is transitional and maintains the original API for
-// atomicops.h. This requires casting memory locations to the atomic types, and
-// assumes that the API and the C++11 implementation are layout-compatible,
-// which isn't true for all implementations or hardware platforms. The static
-// assertion should detect this issue, were it to fire then this header
-// shouldn't be used.
-//
-// TODO(jfb) If this header manages to stay committed then the API should be
-// modified, and all call sites updated.
-typedef volatile std::atomic<Atomic32>* AtomicLocation32;
-static_assert(sizeof(*(AtomicLocation32) nullptr) == sizeof(Atomic32),
- "incompatible 32-bit atomic layout");
-
-inline void MemoryBarrier() {
-#if defined(__GLIBCXX__)
- // Work around libstdc++ bug 51038 where atomic_thread_fence was declared but
- // not defined, leading to the linker complaining about undefined references.
- __atomic_thread_fence(std::memory_order_seq_cst);
-#else
- std::atomic_thread_fence(std::memory_order_seq_cst);
-#endif
-}
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- ((AtomicLocation32)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_relaxed,
- std::memory_order_relaxed);
- return old_value;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- return ((AtomicLocation32)ptr)
- ->exchange(new_value, std::memory_order_relaxed);
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return increment +
- ((AtomicLocation32)ptr)
- ->fetch_add(increment, std::memory_order_relaxed);
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return increment + ((AtomicLocation32)ptr)->fetch_add(increment);
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- ((AtomicLocation32)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_acquire,
- std::memory_order_acquire);
- return old_value;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- ((AtomicLocation32)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_release,
- std::memory_order_relaxed);
- return old_value;
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- ((AtomicLocation32)ptr)->store(value, std::memory_order_relaxed);
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- ((AtomicLocation32)ptr)->store(value, std::memory_order_relaxed);
- MemoryBarrier();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- ((AtomicLocation32)ptr)->store(value, std::memory_order_release);
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return ((AtomicLocation32)ptr)->load(std::memory_order_relaxed);
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- return ((AtomicLocation32)ptr)->load(std::memory_order_acquire);
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrier();
- return ((AtomicLocation32)ptr)->load(std::memory_order_relaxed);
-}
-
-#if defined(ARCH_CPU_64_BITS)
-
-typedef volatile std::atomic<Atomic64>* AtomicLocation64;
-static_assert(sizeof(*(AtomicLocation64) nullptr) == sizeof(Atomic64),
- "incompatible 64-bit atomic layout");
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- ((AtomicLocation64)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_relaxed,
- std::memory_order_relaxed);
- return old_value;
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- return ((AtomicLocation64)ptr)
- ->exchange(new_value, std::memory_order_relaxed);
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return increment +
- ((AtomicLocation64)ptr)
- ->fetch_add(increment, std::memory_order_relaxed);
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return increment + ((AtomicLocation64)ptr)->fetch_add(increment);
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- ((AtomicLocation64)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_acquire,
- std::memory_order_acquire);
- return old_value;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- ((AtomicLocation64)ptr)
- ->compare_exchange_strong(old_value,
- new_value,
- std::memory_order_release,
- std::memory_order_relaxed);
- return old_value;
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- ((AtomicLocation64)ptr)->store(value, std::memory_order_relaxed);
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- ((AtomicLocation64)ptr)->store(value, std::memory_order_relaxed);
- MemoryBarrier();
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- ((AtomicLocation64)ptr)->store(value, std::memory_order_release);
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed);
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- return ((AtomicLocation64)ptr)->load(std::memory_order_acquire);
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- MemoryBarrier();
- return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed);
-}
-
-#endif // defined(ARCH_CPU_64_BITS)
-} // namespace subtle
-} // namespace base
-
-#endif // BASE_ATOMICOPS_INTERNALS_PORTABLE_H_
diff --git a/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h b/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
deleted file mode 100644
index 9f05b7e78..000000000
--- a/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
+++ /dev/null
@@ -1,196 +0,0 @@
-// 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 is an internal atomic implementation, use base/atomicops.h instead.
-
-#ifndef BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
-#define BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
-
-#include <windows.h>
-
-#include <intrin.h>
-
-#include "base/macros.h"
-#include "build/build_config.h"
-
-#if defined(ARCH_CPU_64_BITS)
-// windows.h #defines this (only on x64). This causes problems because the
-// public API also uses MemoryBarrier at the public name for this fence. So, on
-// X64, undef it, and call its documented
-// (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx)
-// implementation directly.
-#undef MemoryBarrier
-#endif
-
-namespace base {
-namespace subtle {
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- LONG result = _InterlockedCompareExchange(
- reinterpret_cast<volatile LONG*>(ptr),
- static_cast<LONG>(new_value),
- static_cast<LONG>(old_value));
- return static_cast<Atomic32>(result);
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
- Atomic32 new_value) {
- LONG result = _InterlockedExchange(
- reinterpret_cast<volatile LONG*>(ptr),
- static_cast<LONG>(new_value));
- return static_cast<Atomic32>(result);
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return _InterlockedExchangeAdd(
- reinterpret_cast<volatile LONG*>(ptr),
- static_cast<LONG>(increment)) + increment;
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
- Atomic32 increment) {
- return Barrier_AtomicIncrement(ptr, increment);
-}
-
-inline void MemoryBarrier() {
-#if defined(ARCH_CPU_64_BITS)
- // See #undef and note at the top of this file.
- __faststorefence();
-#else
- // We use MemoryBarrier from WinNT.h
- ::MemoryBarrier();
-#endif
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
- Atomic32 old_value,
- Atomic32 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
- NoBarrier_AtomicExchange(ptr, value);
- // acts as a barrier in this implementation
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
- *ptr = value; // works w/o barrier for current Intel chips as of June 2005
- // See comments in Atomic64 version of Release_Store() below.
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
- return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
- Atomic32 value = *ptr;
- return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
- MemoryBarrier();
- return *ptr;
-}
-
-#if defined(_WIN64)
-
-// 64-bit low-level operations on 64-bit platform.
-
-static_assert(sizeof(Atomic64) == sizeof(PVOID), "atomic word is atomic");
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- PVOID result = InterlockedCompareExchangePointer(
- reinterpret_cast<volatile PVOID*>(ptr),
- reinterpret_cast<PVOID>(new_value), reinterpret_cast<PVOID>(old_value));
- return reinterpret_cast<Atomic64>(result);
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
- Atomic64 new_value) {
- PVOID result = InterlockedExchangePointer(
- reinterpret_cast<volatile PVOID*>(ptr),
- reinterpret_cast<PVOID>(new_value));
- return reinterpret_cast<Atomic64>(result);
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return InterlockedExchangeAdd64(
- reinterpret_cast<volatile LONGLONG*>(ptr),
- static_cast<LONGLONG>(increment)) + increment;
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
- Atomic64 increment) {
- return Barrier_AtomicIncrement(ptr, increment);
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
- NoBarrier_AtomicExchange(ptr, value);
- // acts as a barrier in this implementation
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
- *ptr = value; // works w/o barrier for current Intel chips as of June 2005
-
- // When new chips come out, check:
- // IA-32 Intel Architecture Software Developer's Manual, Volume 3:
- // System Programming Guide, Chatper 7: Multiple-processor management,
- // Section 7.2, Memory Ordering.
- // Last seen at:
- // http://developer.intel.com/design/pentium4/manuals/index_new.htm
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
- return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
- Atomic64 value = *ptr;
- return value;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
- MemoryBarrier();
- return *ptr;
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
- Atomic64 old_value,
- Atomic64 new_value) {
- return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-
-#endif // defined(_WIN64)
-
-} // namespace subtle
-} // namespace base
-
-#endif // BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
diff --git a/security/sandbox/chromium/base/base_export.h b/security/sandbox/chromium/base/base_export.h
deleted file mode 100644
index cf7ebd781..000000000
--- a/security/sandbox/chromium/base/base_export.h
+++ /dev/null
@@ -1,29 +0,0 @@
-// 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.
-
-#ifndef BASE_BASE_EXPORT_H_
-#define BASE_BASE_EXPORT_H_
-
-#if defined(COMPONENT_BUILD)
-#if defined(WIN32)
-
-#if defined(BASE_IMPLEMENTATION)
-#define BASE_EXPORT __declspec(dllexport)
-#else
-#define BASE_EXPORT __declspec(dllimport)
-#endif // defined(BASE_IMPLEMENTATION)
-
-#else // defined(WIN32)
-#if defined(BASE_IMPLEMENTATION)
-#define BASE_EXPORT __attribute__((visibility("default")))
-#else
-#define BASE_EXPORT
-#endif // defined(BASE_IMPLEMENTATION)
-#endif
-
-#else // defined(COMPONENT_BUILD)
-#define BASE_EXPORT
-#endif
-
-#endif // BASE_BASE_EXPORT_H_
diff --git a/security/sandbox/chromium/base/base_paths.h b/security/sandbox/chromium/base/base_paths.h
deleted file mode 100644
index 26b2fd4c9..000000000
--- a/security/sandbox/chromium/base/base_paths.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// 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.
-
-#ifndef BASE_BASE_PATHS_H_
-#define BASE_BASE_PATHS_H_
-
-// This file declares path keys for the base module. These can be used with
-// the PathService to access various special directories and files.
-
-#include "build/build_config.h"
-
-#if defined(OS_WIN)
-#include "base/base_paths_win.h"
-#elif defined(OS_MACOSX)
-#include "base/base_paths_mac.h"
-#elif defined(OS_ANDROID)
-#include "base/base_paths_android.h"
-#endif
-
-#if defined(OS_POSIX)
-#include "base/base_paths_posix.h"
-#endif
-
-namespace base {
-
-enum BasePathKey {
- PATH_START = 0,
-
- DIR_CURRENT, // Current directory.
- DIR_EXE, // Directory containing FILE_EXE.
- DIR_MODULE, // Directory containing FILE_MODULE.
- DIR_TEMP, // Temporary directory.
- DIR_HOME, // User's root home directory. On Windows this will look
- // like "C:\Users\you" (or on XP
- // "C:\Document and Settings\you") which isn't necessarily
- // a great place to put files.
- FILE_EXE, // Path and filename of the current executable.
- FILE_MODULE, // Path and filename of the module containing the code for
- // the PathService (which could differ from FILE_EXE if the
- // PathService were compiled into a shared object, for
- // example).
- DIR_SOURCE_ROOT, // Returns the root of the source tree. This key is useful
- // for tests that need to locate various resources. It
- // should not be used outside of test code.
- DIR_USER_DESKTOP, // The current user's Desktop.
-
- DIR_TEST_DATA, // Used only for testing.
-
- PATH_END
-};
-
-} // namespace base
-
-#endif // BASE_BASE_PATHS_H_
diff --git a/security/sandbox/chromium/base/base_paths_win.h b/security/sandbox/chromium/base/base_paths_win.h
deleted file mode 100644
index d9dbc39f9..000000000
--- a/security/sandbox/chromium/base/base_paths_win.h
+++ /dev/null
@@ -1,54 +0,0 @@
-// 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.
-
-#ifndef BASE_BASE_PATHS_WIN_H_
-#define BASE_BASE_PATHS_WIN_H_
-
-// This file declares windows-specific path keys for the base module.
-// These can be used with the PathService to access various special
-// directories and files.
-
-namespace base {
-
-enum {
- PATH_WIN_START = 100,
-
- DIR_WINDOWS, // Windows directory, usually "c:\windows"
- DIR_SYSTEM, // Usually c:\windows\system32"
- // 32-bit 32-bit on 64-bit 64-bit on 64-bit
- // DIR_PROGRAM_FILES 1 2 1
- // DIR_PROGRAM_FILESX86 1 2 2
- // DIR_PROGRAM_FILES6432 1 1 1
- // 1 - C:\Program Files 2 - C:\Program Files (x86)
- DIR_PROGRAM_FILES, // See table above.
- DIR_PROGRAM_FILESX86, // See table above.
- DIR_PROGRAM_FILES6432, // See table above.
-
- DIR_IE_INTERNET_CACHE, // Temporary Internet Files directory.
- DIR_COMMON_START_MENU, // Usually "C:\Documents and Settings\All Users\
- // Start Menu\Programs"
- DIR_START_MENU, // Usually "C:\Documents and Settings\<user>\
- // Start Menu\Programs"
- DIR_APP_DATA, // Application Data directory under the user profile.
- DIR_LOCAL_APP_DATA, // "Local Settings\Application Data" directory under
- // the user profile.
- DIR_COMMON_APP_DATA, // W2K, XP, W2K3: "C:\Documents and Settings\
- // All Users\Application Data".
- // Vista, W2K8 and above: "C:\ProgramData".
- DIR_APP_SHORTCUTS, // Where tiles on the start screen are stored, only
- // for Windows 8. Maps to "Local\AppData\Microsoft\
- // Windows\Application Shortcuts\".
- DIR_COMMON_DESKTOP, // Directory for the common desktop (visible
- // on all user's Desktop).
- DIR_USER_QUICK_LAUNCH, // Directory for the quick launch shortcuts.
- DIR_TASKBAR_PINS, // Directory for the shortcuts pinned to taskbar
- // (Win7-8) via base::win::PinShortcutToTaskbar().
- DIR_WINDOWS_FONTS, // Usually C:\Windows\Fonts.
-
- PATH_WIN_END
-};
-
-} // namespace base
-
-#endif // BASE_BASE_PATHS_WIN_H_
diff --git a/security/sandbox/chromium/base/base_switches.cc b/security/sandbox/chromium/base/base_switches.cc
deleted file mode 100644
index 02b222988..000000000
--- a/security/sandbox/chromium/base/base_switches.cc
+++ /dev/null
@@ -1,95 +0,0 @@
-// 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.
-
-#include "base/base_switches.h"
-#include "build/build_config.h"
-
-namespace switches {
-
-// Disables the crash reporting.
-const char kDisableBreakpad[] = "disable-breakpad";
-
-// Indicates that crash reporting should be enabled. On platforms where helper
-// processes cannot access to files needed to make this decision, this flag is
-// generated internally.
-const char kEnableCrashReporter[] = "enable-crash-reporter";
-
-// Makes memory allocators keep track of their allocations and context, so a
-// detailed breakdown of memory usage can be presented in chrome://tracing when
-// the memory-infra category is enabled.
-const char kEnableHeapProfiling[] = "enable-heap-profiling";
-
-// Generates full memory crash dump.
-const char kFullMemoryCrashReport[] = "full-memory-crash-report";
-
-// Force low-end device mode when set.
-const char kEnableLowEndDeviceMode[] = "enable-low-end-device-mode";
-
-// Force disabling of low-end device mode when set.
-const char kDisableLowEndDeviceMode[] = "disable-low-end-device-mode";
-
-// This option can be used to force field trials when testing changes locally.
-// The argument is a list of name and value pairs, separated by slashes. If a
-// trial name is prefixed with an asterisk, that trial will start activated.
-// For example, the following argument defines two trials, with the second one
-// activated: "GoogleNow/Enable/*MaterialDesignNTP/Default/" This option can
-// also be used by the browser process to send the list of trials to a
-// non-browser process, using the same format. See
-// FieldTrialList::CreateTrialsFromString() in field_trial.h for details.
-const char kForceFieldTrials[] = "force-fieldtrials";
-
-// Suppresses all error dialogs when present.
-const char kNoErrorDialogs[] = "noerrdialogs";
-
-// When running certain tests that spawn child processes, this switch indicates
-// to the test framework that the current process is a child process.
-const char kTestChildProcess[] = "test-child-process";
-
-// Gives the default maximal active V-logging level; 0 is the default.
-// Normally positive values are used for V-logging levels.
-const char kV[] = "v";
-
-// Gives the per-module maximal V-logging levels to override the value
-// given by --v. E.g. "my_module=2,foo*=3" would change the logging
-// level for all code in source files "my_module.*" and "foo*.*"
-// ("-inl" suffixes are also disregarded for this matching).
-//
-// Any pattern containing a forward or backward slash will be tested
-// against the whole pathname and not just the module. E.g.,
-// "*/foo/bar/*=2" would change the logging level for all code in
-// source files under a "foo/bar" directory.
-const char kVModule[] = "vmodule";
-
-// Will wait for 60 seconds for a debugger to come to attach to the process.
-const char kWaitForDebugger[] = "wait-for-debugger";
-
-// Sends trace events from these categories to a file.
-// --trace-to-file on its own sends to default categories.
-const char kTraceToFile[] = "trace-to-file";
-
-// Specifies the file name for --trace-to-file. If unspecified, it will
-// go to a default file name.
-const char kTraceToFileName[] = "trace-to-file-name";
-
-// Configure whether chrome://profiler will contain timing information. This
-// option is enabled by default. A value of "0" will disable profiler timing,
-// while all other values will enable it.
-const char kProfilerTiming[] = "profiler-timing";
-// Value of the --profiler-timing flag that will disable timing information for
-// chrome://profiler.
-const char kProfilerTimingDisabledValue[] = "0";
-
-#if defined(OS_WIN)
-// Disables the USB keyboard detection for blocking the OSK on Win8+.
-const char kDisableUsbKeyboardDetect[] = "disable-usb-keyboard-detect";
-#endif
-
-#if defined(OS_POSIX)
-// Used for turning on Breakpad crash reporting in a debug environment where
-// crash reporting is typically compiled but disabled.
-const char kEnableCrashReporterForTesting[] =
- "enable-crash-reporter-for-testing";
-#endif
-
-} // namespace switches
diff --git a/security/sandbox/chromium/base/base_switches.h b/security/sandbox/chromium/base/base_switches.h
deleted file mode 100644
index c97a629d9..000000000
--- a/security/sandbox/chromium/base/base_switches.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// 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.
-
-// Defines all the "base" command-line switches.
-
-#ifndef BASE_BASE_SWITCHES_H_
-#define BASE_BASE_SWITCHES_H_
-
-#include "build/build_config.h"
-
-namespace switches {
-
-extern const char kDisableBreakpad[];
-extern const char kDisableLowEndDeviceMode[];
-extern const char kEnableCrashReporter[];
-extern const char kEnableHeapProfiling[];
-extern const char kEnableLowEndDeviceMode[];
-extern const char kForceFieldTrials[];
-extern const char kFullMemoryCrashReport[];
-extern const char kNoErrorDialogs[];
-extern const char kProfilerTiming[];
-extern const char kProfilerTimingDisabledValue[];
-extern const char kTestChildProcess[];
-extern const char kTraceToFile[];
-extern const char kTraceToFileName[];
-extern const char kV[];
-extern const char kVModule[];
-extern const char kWaitForDebugger[];
-
-#if defined(OS_WIN)
-extern const char kDisableUsbKeyboardDetect[];
-#endif
-
-#if defined(OS_POSIX)
-extern const char kEnableCrashReporterForTesting[];
-#endif
-
-} // namespace switches
-
-#endif // BASE_BASE_SWITCHES_H_
diff --git a/security/sandbox/chromium/base/bind.h b/security/sandbox/chromium/base/bind.h
deleted file mode 100644
index 770e45706..000000000
--- a/security/sandbox/chromium/base/bind.h
+++ /dev/null
@@ -1,101 +0,0 @@
-// 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_BIND_H_
-#define BASE_BIND_H_
-
-#include "base/bind_internal.h"
-#include "base/callback_internal.h"
-
-// -----------------------------------------------------------------------------
-// Usage documentation
-// -----------------------------------------------------------------------------
-//
-// See base/callback.h for documentation.
-//
-//
-// -----------------------------------------------------------------------------
-// Implementation notes
-// -----------------------------------------------------------------------------
-//
-// If you're reading the implementation, before proceeding further, you should
-// read the top comment of base/bind_internal.h for a definition of common
-// terms and concepts.
-//
-// RETURN TYPES
-//
-// Though Bind()'s result is meant to be stored in a Callback<> type, it
-// cannot actually return the exact type without requiring a large amount
-// of extra template specializations. The problem is that in order to
-// discern the correct specialization of Callback<>, Bind would need to
-// unwrap the function signature to determine the signature's arity, and
-// whether or not it is a method.
-//
-// Each unique combination of (arity, function_type, num_prebound) where
-// function_type is one of {function, method, const_method} would require
-// one specialization. We eventually have to do a similar number of
-// specializations anyways in the implementation (see the Invoker<>,
-// classes). However, it is avoidable in Bind if we return the result
-// via an indirection like we do below.
-//
-// TODO(ajwong): We might be able to avoid this now, but need to test.
-//
-// It is possible to move most of the static_assert into BindState<>, but it
-// feels a little nicer to have the asserts here so people do not need to crack
-// open bind_internal.h. On the other hand, it makes Bind() harder to read.
-
-namespace base {
-
-template <typename Functor, typename... Args>
-base::Callback<
- typename internal::BindState<
- typename internal::FunctorTraits<Functor>::RunnableType,
- typename internal::FunctorTraits<Functor>::RunType,
- typename internal::CallbackParamTraits<Args>::StorageType...>
- ::UnboundRunType>
-Bind(Functor functor, const Args&... args) {
- // Type aliases for how to store and run the functor.
- using RunnableType = typename internal::FunctorTraits<Functor>::RunnableType;
- using RunType = typename internal::FunctorTraits<Functor>::RunType;
-
- // Use RunnableType::RunType instead of RunType above because our
- // checks below for bound references need to know what the actual
- // functor is going to interpret the argument as.
- using BoundRunType = typename RunnableType::RunType;
-
- using BoundArgs =
- internal::TakeTypeListItem<sizeof...(Args),
- internal::ExtractArgs<BoundRunType>>;
-
- // Do not allow binding a non-const reference parameter. Non-const reference
- // parameters are disallowed by the Google style guide. Also, binding a
- // non-const reference parameter can make for subtle bugs because the
- // invoked function will receive a reference to the stored copy of the
- // argument and not the original.
- static_assert(!internal::HasNonConstReferenceItem<BoundArgs>::value,
- "do not bind functions with nonconst ref");
-
- const bool is_method = internal::HasIsMethodTag<RunnableType>::value;
-
- // For methods, we need to be careful for parameter 1. We do not require
- // a scoped_refptr because BindState<> itself takes care of AddRef() for
- // methods. We also disallow binding of an array as the method's target
- // object.
- static_assert(!internal::BindsArrayToFirstArg<is_method, Args...>::value,
- "first bound argument to method cannot be array");
- static_assert(
- !internal::HasRefCountedParamAsRawPtr<is_method, Args...>::value,
- "a parameter is a refcounted type and needs scoped_refptr");
-
- using BindState = internal::BindState<
- RunnableType, RunType,
- typename internal::CallbackParamTraits<Args>::StorageType...>;
-
- return Callback<typename BindState::UnboundRunType>(
- new BindState(internal::MakeRunnable(functor), args...));
-}
-
-} // namespace base
-
-#endif // BASE_BIND_H_
diff --git a/security/sandbox/chromium/base/bind_helpers.h b/security/sandbox/chromium/base/bind_helpers.h
deleted file mode 100644
index 2add755b4..000000000
--- a/security/sandbox/chromium/base/bind_helpers.h
+++ /dev/null
@@ -1,658 +0,0 @@
-// 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.
-
-// This defines a set of argument wrappers and related factory methods that
-// can be used specify the refcounting and reference semantics of arguments
-// that are bound by the Bind() function in base/bind.h.
-//
-// It also defines a set of simple functions and utilities that people want
-// when using Callback<> and Bind().
-//
-//
-// ARGUMENT BINDING WRAPPERS
-//
-// The wrapper functions are base::Unretained(), base::Owned(), base::Passed(),
-// base::ConstRef(), and base::IgnoreResult().
-//
-// Unretained() allows Bind() to bind a non-refcounted class, and to disable
-// refcounting on arguments that are refcounted objects.
-//
-// Owned() transfers ownership of an object to the Callback resulting from
-// bind; the object will be deleted when the Callback is deleted.
-//
-// Passed() is for transferring movable-but-not-copyable types (eg. scoped_ptr)
-// through a Callback. Logically, this signifies a destructive transfer of
-// the state of the argument into the target function. Invoking
-// Callback::Run() twice on a Callback that was created with a Passed()
-// argument will CHECK() because the first invocation would have already
-// transferred ownership to the target function.
-//
-// ConstRef() allows binding a constant reference to an argument rather
-// than a copy.
-//
-// IgnoreResult() is used to adapt a function or Callback with a return type to
-// one with a void return. This is most useful if you have a function with,
-// say, a pesky ignorable bool return that you want to use with PostTask or
-// something else that expect a Callback with a void return.
-//
-// EXAMPLE OF Unretained():
-//
-// class Foo {
-// public:
-// void func() { cout << "Foo:f" << endl; }
-// };
-//
-// // In some function somewhere.
-// Foo foo;
-// Closure foo_callback =
-// Bind(&Foo::func, Unretained(&foo));
-// foo_callback.Run(); // Prints "Foo:f".
-//
-// Without the Unretained() wrapper on |&foo|, the above call would fail
-// to compile because Foo does not support the AddRef() and Release() methods.
-//
-//
-// EXAMPLE OF Owned():
-//
-// void foo(int* arg) { cout << *arg << endl }
-//
-// int* pn = new int(1);
-// Closure foo_callback = Bind(&foo, Owned(pn));
-//
-// foo_callback.Run(); // Prints "1"
-// foo_callback.Run(); // Prints "1"
-// *n = 2;
-// foo_callback.Run(); // Prints "2"
-//
-// foo_callback.Reset(); // |pn| is deleted. Also will happen when
-// // |foo_callback| goes out of scope.
-//
-// Without Owned(), someone would have to know to delete |pn| when the last
-// reference to the Callback is deleted.
-//
-//
-// EXAMPLE OF ConstRef():
-//
-// void foo(int arg) { cout << arg << endl }
-//
-// int n = 1;
-// Closure no_ref = Bind(&foo, n);
-// Closure has_ref = Bind(&foo, ConstRef(n));
-//
-// no_ref.Run(); // Prints "1"
-// has_ref.Run(); // Prints "1"
-//
-// n = 2;
-// no_ref.Run(); // Prints "1"
-// has_ref.Run(); // Prints "2"
-//
-// Note that because ConstRef() takes a reference on |n|, |n| must outlive all
-// its bound callbacks.
-//
-//
-// EXAMPLE OF IgnoreResult():
-//
-// int DoSomething(int arg) { cout << arg << endl; }
-//
-// // Assign to a Callback with a void return type.
-// Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething));
-// cb->Run(1); // Prints "1".
-//
-// // Prints "1" on |ml|.
-// ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1);
-//
-//
-// EXAMPLE OF Passed():
-//
-// void TakesOwnership(scoped_ptr<Foo> arg) { }
-// scoped_ptr<Foo> CreateFoo() { return scoped_ptr<Foo>(new Foo()); }
-//
-// scoped_ptr<Foo> f(new Foo());
-//
-// // |cb| is given ownership of Foo(). |f| is now NULL.
-// // You can use std::move(f) in place of &f, but it's more verbose.
-// Closure cb = Bind(&TakesOwnership, Passed(&f));
-//
-// // Run was never called so |cb| still owns Foo() and deletes
-// // it on Reset().
-// cb.Reset();
-//
-// // |cb| is given a new Foo created by CreateFoo().
-// cb = Bind(&TakesOwnership, Passed(CreateFoo()));
-//
-// // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
-// // no longer owns Foo() and, if reset, would not delete Foo().
-// cb.Run(); // Foo() is now transferred to |arg| and deleted.
-// cb.Run(); // This CHECK()s since Foo() already been used once.
-//
-// Passed() is particularly useful with PostTask() when you are transferring
-// ownership of an argument into a task, but don't necessarily know if the
-// task will always be executed. This can happen if the task is cancellable
-// or if it is posted to a TaskRunner.
-//
-//
-// SIMPLE FUNCTIONS AND UTILITIES.
-//
-// DoNothing() - Useful for creating a Closure that does nothing when called.
-// DeletePointer<T>() - Useful for creating a Closure that will delete a
-// pointer when invoked. Only use this when necessary.
-// In most cases MessageLoop::DeleteSoon() is a better
-// fit.
-
-#ifndef BASE_BIND_HELPERS_H_
-#define BASE_BIND_HELPERS_H_
-
-#include <stddef.h>
-
-#include <type_traits>
-#include <utility>
-
-#include "base/callback.h"
-#include "base/memory/weak_ptr.h"
-#include "base/template_util.h"
-#include "build/build_config.h"
-
-namespace base {
-namespace internal {
-
-// Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T
-// for the existence of AddRef() and Release() functions of the correct
-// signature.
-//
-// http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error
-// http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence
-// http://stackoverflow.com/questions/4358584/sfinae-approach-comparison
-// http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions
-//
-// The last link in particular show the method used below.
-//
-// For SFINAE to work with inherited methods, we need to pull some extra tricks
-// with multiple inheritance. In the more standard formulation, the overloads
-// of Check would be:
-//
-// template <typename C>
-// Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*);
-//
-// template <typename C>
-// No NotTheCheckWeWant(...);
-//
-// static const bool value = sizeof(NotTheCheckWeWant<T>(0)) == sizeof(Yes);
-//
-// The problem here is that template resolution will not match
-// C::TargetFunc if TargetFunc does not exist directly in C. That is, if
-// TargetFunc in inherited from an ancestor, &C::TargetFunc will not match,
-// |value| will be false. This formulation only checks for whether or
-// not TargetFunc exist directly in the class being introspected.
-//
-// To get around this, we play a dirty trick with multiple inheritance.
-// First, We create a class BaseMixin that declares each function that we
-// want to probe for. Then we create a class Base that inherits from both T
-// (the class we wish to probe) and BaseMixin. Note that the function
-// signature in BaseMixin does not need to match the signature of the function
-// we are probing for; thus it's easiest to just use void().
-//
-// Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an
-// ambiguous resolution between BaseMixin and T. This lets us write the
-// following:
-//
-// template <typename C>
-// No GoodCheck(Helper<&C::TargetFunc>*);
-//
-// template <typename C>
-// Yes GoodCheck(...);
-//
-// static const bool value = sizeof(GoodCheck<Base>(0)) == sizeof(Yes);
-//
-// Notice here that the variadic version of GoodCheck() returns Yes here
-// instead of No like the previous one. Also notice that we calculate |value|
-// by specializing GoodCheck() on Base instead of T.
-//
-// We've reversed the roles of the variadic, and Helper overloads.
-// GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid
-// substitution if T::TargetFunc exists. Thus GoodCheck<Base>(0) will resolve
-// to the variadic version if T has TargetFunc. If T::TargetFunc does not
-// exist, then &C::TargetFunc is not ambiguous, and the overload resolution
-// will prefer GoodCheck(Helper<&C::TargetFunc>*).
-//
-// This method of SFINAE will correctly probe for inherited names, but it cannot
-// typecheck those names. It's still a good enough sanity check though.
-//
-// Works on gcc-4.2, gcc-4.4, and Visual Studio 2008.
-//
-// TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted
-// this works well.
-//
-// TODO(ajwong): Make this check for Release() as well.
-// See http://crbug.com/82038.
-template <typename T>
-class SupportsAddRefAndRelease {
- using Yes = char[1];
- using No = char[2];
-
- struct BaseMixin {
- void AddRef();
- };
-
-// MSVC warns when you try to use Base if T has a private destructor, the
-// common pattern for refcounted types. It does this even though no attempt to
-// instantiate Base is made. We disable the warning for this definition.
-#if defined(OS_WIN)
-#pragma warning(push)
-#pragma warning(disable:4624)
-#endif
- struct Base : public T, public BaseMixin {
- };
-#if defined(OS_WIN)
-#pragma warning(pop)
-#endif
-
- template <void(BaseMixin::*)()> struct Helper {};
-
- template <typename C>
- static No& Check(Helper<&C::AddRef>*);
-
- template <typename >
- static Yes& Check(...);
-
- public:
- enum { value = sizeof(Check<Base>(0)) == sizeof(Yes) };
-};
-
-// Helpers to assert that arguments of a recounted type are bound with a
-// scoped_refptr.
-template <bool IsClasstype, typename T>
-struct UnsafeBindtoRefCountedArgHelper : false_type {
-};
-
-template <typename T>
-struct UnsafeBindtoRefCountedArgHelper<true, T>
- : integral_constant<bool, SupportsAddRefAndRelease<T>::value> {
-};
-
-template <typename T>
-struct UnsafeBindtoRefCountedArg : false_type {
-};
-
-template <typename T>
-struct UnsafeBindtoRefCountedArg<T*>
- : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> {
-};
-
-template <typename T>
-class HasIsMethodTag {
- using Yes = char[1];
- using No = char[2];
-
- template <typename U>
- static Yes& Check(typename U::IsMethod*);
-
- template <typename U>
- static No& Check(...);
-
- public:
- enum { value = sizeof(Check<T>(0)) == sizeof(Yes) };
-};
-
-template <typename T>
-class UnretainedWrapper {
- public:
- explicit UnretainedWrapper(T* o) : ptr_(o) {}
- T* get() const { return ptr_; }
- private:
- T* ptr_;
-};
-
-template <typename T>
-class ConstRefWrapper {
- public:
- explicit ConstRefWrapper(const T& o) : ptr_(&o) {}
- const T& get() const { return *ptr_; }
- private:
- const T* ptr_;
-};
-
-template <typename T>
-struct IgnoreResultHelper {
- explicit IgnoreResultHelper(T functor) : functor_(functor) {}
-
- T functor_;
-};
-
-template <typename T>
-struct IgnoreResultHelper<Callback<T> > {
- explicit IgnoreResultHelper(const Callback<T>& functor) : functor_(functor) {}
-
- const Callback<T>& functor_;
-};
-
-// An alternate implementation is to avoid the destructive copy, and instead
-// specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to
-// a class that is essentially a scoped_ptr<>.
-//
-// The current implementation has the benefit though of leaving ParamTraits<>
-// fully in callback_internal.h as well as avoiding type conversions during
-// storage.
-template <typename T>
-class OwnedWrapper {
- public:
- explicit OwnedWrapper(T* o) : ptr_(o) {}
- ~OwnedWrapper() { delete ptr_; }
- T* get() const { return ptr_; }
- OwnedWrapper(const OwnedWrapper& other) {
- ptr_ = other.ptr_;
- other.ptr_ = NULL;
- }
-
- private:
- mutable T* ptr_;
-};
-
-// PassedWrapper is a copyable adapter for a scoper that ignores const.
-//
-// It is needed to get around the fact that Bind() takes a const reference to
-// all its arguments. Because Bind() takes a const reference to avoid
-// unnecessary copies, it is incompatible with movable-but-not-copyable
-// types; doing a destructive "move" of the type into Bind() would violate
-// the const correctness.
-//
-// This conundrum cannot be solved without either C++11 rvalue references or
-// a O(2^n) blowup of Bind() templates to handle each combination of regular
-// types and movable-but-not-copyable types. Thus we introduce a wrapper type
-// that is copyable to transmit the correct type information down into
-// BindState<>. Ignoring const in this type makes sense because it is only
-// created when we are explicitly trying to do a destructive move.
-//
-// Two notes:
-// 1) PassedWrapper supports any type that has a move constructor, however
-// the type will need to be specifically whitelisted in order for it to be
-// bound to a Callback. We guard this explicitly at the call of Passed()
-// to make for clear errors. Things not given to Passed() will be forwarded
-// and stored by value which will not work for general move-only types.
-// 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
-// scoper to a Callback and allow the Callback to execute once.
-template <typename T>
-class PassedWrapper {
- public:
- explicit PassedWrapper(T&& scoper)
- : is_valid_(true), scoper_(std::move(scoper)) {}
- PassedWrapper(const PassedWrapper& other)
- : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
- T Pass() const {
- CHECK(is_valid_);
- is_valid_ = false;
- return std::move(scoper_);
- }
-
- private:
- mutable bool is_valid_;
- mutable T scoper_;
-};
-
-// Unwrap the stored parameters for the wrappers above.
-template <typename T>
-struct UnwrapTraits {
- using ForwardType = const T&;
- static ForwardType Unwrap(const T& o) { return o; }
-};
-
-template <typename T>
-struct UnwrapTraits<UnretainedWrapper<T> > {
- using ForwardType = T*;
- static ForwardType Unwrap(UnretainedWrapper<T> unretained) {
- return unretained.get();
- }
-};
-
-template <typename T>
-struct UnwrapTraits<ConstRefWrapper<T> > {
- using ForwardType = const T&;
- static ForwardType Unwrap(ConstRefWrapper<T> const_ref) {
- return const_ref.get();
- }
-};
-
-template <typename T>
-struct UnwrapTraits<scoped_refptr<T> > {
- using ForwardType = T*;
- static ForwardType Unwrap(const scoped_refptr<T>& o) { return o.get(); }
-};
-
-template <typename T>
-struct UnwrapTraits<WeakPtr<T> > {
- using ForwardType = const WeakPtr<T>&;
- static ForwardType Unwrap(const WeakPtr<T>& o) { return o; }
-};
-
-template <typename T>
-struct UnwrapTraits<OwnedWrapper<T> > {
- using ForwardType = T*;
- static ForwardType Unwrap(const OwnedWrapper<T>& o) {
- return o.get();
- }
-};
-
-template <typename T>
-struct UnwrapTraits<PassedWrapper<T> > {
- using ForwardType = T;
- static T Unwrap(PassedWrapper<T>& o) {
- return o.Pass();
- }
-};
-
-// Utility for handling different refcounting semantics in the Bind()
-// function.
-template <bool is_method, typename... T>
-struct MaybeScopedRefPtr;
-
-template <bool is_method>
-struct MaybeScopedRefPtr<is_method> {
- MaybeScopedRefPtr() {}
-};
-
-template <typename T, typename... Rest>
-struct MaybeScopedRefPtr<false, T, Rest...> {
- MaybeScopedRefPtr(const T&, const Rest&...) {}
-};
-
-template <typename T, size_t n, typename... Rest>
-struct MaybeScopedRefPtr<false, T[n], Rest...> {
- MaybeScopedRefPtr(const T*, const Rest&...) {}
-};
-
-template <typename T, typename... Rest>
-struct MaybeScopedRefPtr<true, T, Rest...> {
- MaybeScopedRefPtr(const T& o, const Rest&...) {}
-};
-
-template <typename T, typename... Rest>
-struct MaybeScopedRefPtr<true, T*, Rest...> {
- MaybeScopedRefPtr(T* o, const Rest&...) : ref_(o) {}
- scoped_refptr<T> ref_;
-};
-
-// No need to additionally AddRef() and Release() since we are storing a
-// scoped_refptr<> inside the storage object already.
-template <typename T, typename... Rest>
-struct MaybeScopedRefPtr<true, scoped_refptr<T>, Rest...> {
- MaybeScopedRefPtr(const scoped_refptr<T>&, const Rest&...) {}
-};
-
-template <typename T, typename... Rest>
-struct MaybeScopedRefPtr<true, const T*, Rest...> {
- MaybeScopedRefPtr(const T* o, const Rest&...) : ref_(o) {}
- scoped_refptr<const T> ref_;
-};
-
-// IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
-// method. It is used internally by Bind() to select the correct
-// InvokeHelper that will no-op itself in the event the WeakPtr<> for
-// the target object is invalidated.
-//
-// The first argument should be the type of the object that will be received by
-// the method.
-template <bool IsMethod, typename... Args>
-struct IsWeakMethod : public false_type {};
-
-template <typename T, typename... Args>
-struct IsWeakMethod<true, WeakPtr<T>, Args...> : public true_type {};
-
-template <typename T, typename... Args>
-struct IsWeakMethod<true, ConstRefWrapper<WeakPtr<T>>, Args...>
- : public true_type {};
-
-
-// Packs a list of types to hold them in a single type.
-template <typename... Types>
-struct TypeList {};
-
-// Used for DropTypeListItem implementation.
-template <size_t n, typename List>
-struct DropTypeListItemImpl;
-
-// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
-template <size_t n, typename T, typename... List>
-struct DropTypeListItemImpl<n, TypeList<T, List...>>
- : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
-
-template <typename T, typename... List>
-struct DropTypeListItemImpl<0, TypeList<T, List...>> {
- using Type = TypeList<T, List...>;
-};
-
-template <>
-struct DropTypeListItemImpl<0, TypeList<>> {
- using Type = TypeList<>;
-};
-
-// A type-level function that drops |n| list item from given TypeList.
-template <size_t n, typename List>
-using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
-
-// Used for TakeTypeListItem implementation.
-template <size_t n, typename List, typename... Accum>
-struct TakeTypeListItemImpl;
-
-// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
-template <size_t n, typename T, typename... List, typename... Accum>
-struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
- : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
-
-template <typename T, typename... List, typename... Accum>
-struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
- using Type = TypeList<Accum...>;
-};
-
-template <typename... Accum>
-struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
- using Type = TypeList<Accum...>;
-};
-
-// A type-level function that takes first |n| list item from given TypeList.
-// E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
-// TypeList<A, B, C>.
-template <size_t n, typename List>
-using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
-
-// Used for ConcatTypeLists implementation.
-template <typename List1, typename List2>
-struct ConcatTypeListsImpl;
-
-template <typename... Types1, typename... Types2>
-struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
- using Type = TypeList<Types1..., Types2...>;
-};
-
-// A type-level function that concats two TypeLists.
-template <typename List1, typename List2>
-using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
-
-// Used for MakeFunctionType implementation.
-template <typename R, typename ArgList>
-struct MakeFunctionTypeImpl;
-
-template <typename R, typename... Args>
-struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
- // MSVC 2013 doesn't support Type Alias of function types.
- // Revisit this after we update it to newer version.
- typedef R Type(Args...);
-};
-
-// A type-level function that constructs a function type that has |R| as its
-// return type and has TypeLists items as its arguments.
-template <typename R, typename ArgList>
-using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
-
-// Used for ExtractArgs.
-template <typename Signature>
-struct ExtractArgsImpl;
-
-template <typename R, typename... Args>
-struct ExtractArgsImpl<R(Args...)> {
- using Type = TypeList<Args...>;
-};
-
-// A type-level function that extracts function arguments into a TypeList.
-// E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
-template <typename Signature>
-using ExtractArgs = typename ExtractArgsImpl<Signature>::Type;
-
-} // namespace internal
-
-template <typename T>
-static inline internal::UnretainedWrapper<T> Unretained(T* o) {
- return internal::UnretainedWrapper<T>(o);
-}
-
-template <typename T>
-static inline internal::ConstRefWrapper<T> ConstRef(const T& o) {
- return internal::ConstRefWrapper<T>(o);
-}
-
-template <typename T>
-static inline internal::OwnedWrapper<T> Owned(T* o) {
- return internal::OwnedWrapper<T>(o);
-}
-
-// We offer 2 syntaxes for calling Passed(). The first takes an rvalue and
-// is best suited for use with the return value of a function or other temporary
-// rvalues. The second takes a pointer to the scoper and is just syntactic sugar
-// to avoid having to write Passed(std::move(scoper)).
-//
-// Both versions of Passed() prevent T from being an lvalue reference. The first
-// via use of enable_if, and the second takes a T* which will not bind to T&.
-template <typename T,
- typename std::enable_if<internal::IsMoveOnlyType<T>::value &&
- !std::is_lvalue_reference<T>::value>::type* =
- nullptr>
-static inline internal::PassedWrapper<T> Passed(T&& scoper) {
- return internal::PassedWrapper<T>(std::move(scoper));
-}
-template <typename T,
- typename std::enable_if<internal::IsMoveOnlyType<T>::value>::type* =
- nullptr>
-static inline internal::PassedWrapper<T> Passed(T* scoper) {
- return internal::PassedWrapper<T>(std::move(*scoper));
-}
-
-template <typename T>
-static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
- return internal::IgnoreResultHelper<T>(data);
-}
-
-template <typename T>
-static inline internal::IgnoreResultHelper<Callback<T> >
-IgnoreResult(const Callback<T>& data) {
- return internal::IgnoreResultHelper<Callback<T> >(data);
-}
-
-BASE_EXPORT void DoNothing();
-
-template<typename T>
-void DeletePointer(T* obj) {
- delete obj;
-}
-
-} // namespace base
-
-#endif // BASE_BIND_HELPERS_H_
diff --git a/security/sandbox/chromium/base/bind_internal.h b/security/sandbox/chromium/base/bind_internal.h
deleted file mode 100644
index ac7cd0098..000000000
--- a/security/sandbox/chromium/base/bind_internal.h
+++ /dev/null
@@ -1,425 +0,0 @@
-// 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_BIND_INTERNAL_H_
-#define BASE_BIND_INTERNAL_H_
-
-#include <stddef.h>
-
-#include <type_traits>
-
-#include "base/bind_helpers.h"
-#include "base/callback_internal.h"
-#include "base/memory/raw_scoped_refptr_mismatch_checker.h"
-#include "base/memory/weak_ptr.h"
-#include "base/template_util.h"
-#include "base/tuple.h"
-#include "build/build_config.h"
-
-#if defined(OS_WIN)
-#include "base/bind_internal_win.h"
-#endif
-
-namespace base {
-namespace internal {
-
-// See base/callback.h for user documentation.
-//
-//
-// CONCEPTS:
-// Runnable -- A type (really a type class) that has a single Run() method
-// and a RunType typedef that corresponds to the type of Run().
-// A Runnable can declare that it should treated like a method
-// call by including a typedef named IsMethod. The value of
-// this typedef is NOT inspected, only the existence. When a
-// Runnable declares itself a method, Bind() will enforce special
-// refcounting + WeakPtr handling semantics for the first
-// parameter which is expected to be an object.
-// Functor -- A copyable type representing something that should be called.
-// All function pointers, Callback<>, and Runnables are functors
-// even if the invocation syntax differs.
-// RunType -- A function type (as opposed to function _pointer_ type) for
-// a Run() function. Usually just a convenience typedef.
-// (Bound)Args -- A set of types that stores the arguments.
-//
-// Types:
-// RunnableAdapter<> -- Wraps the various "function" pointer types into an
-// object that adheres to the Runnable interface.
-// ForceVoidReturn<> -- Helper class for translating function signatures to
-// equivalent forms with a "void" return type.
-// FunctorTraits<> -- Type traits used determine the correct RunType and
-// RunnableType for a Functor. This is where function
-// signature adapters are applied.
-// MakeRunnable<> -- Takes a Functor and returns an object in the Runnable
-// type class that represents the underlying Functor.
-// InvokeHelper<> -- Take a Runnable + arguments and actully invokes it.
-// Handle the differing syntaxes needed for WeakPtr<>
-// support, and for ignoring return values. This is separate
-// from Invoker to avoid creating multiple version of
-// Invoker<>.
-// Invoker<> -- Unwraps the curried parameters and executes the Runnable.
-// BindState<> -- Stores the curried parameters, and is the main entry point
-// into the Bind() system, doing most of the type resolution.
-// There are ARITY BindState types.
-
-// HasNonConstReferenceParam selects true_type when any of the parameters in
-// |Sig| is a non-const reference.
-// Implementation note: This non-specialized case handles zero-arity case only.
-// Non-zero-arity cases should be handled by the specialization below.
-template <typename List>
-struct HasNonConstReferenceItem : false_type {};
-
-// Implementation note: Select true_type if the first parameter is a non-const
-// reference. Otherwise, skip the first parameter and check rest of parameters
-// recursively.
-template <typename T, typename... Args>
-struct HasNonConstReferenceItem<TypeList<T, Args...>>
- : std::conditional<is_non_const_reference<T>::value,
- true_type,
- HasNonConstReferenceItem<TypeList<Args...>>>::type {};
-
-// HasRefCountedTypeAsRawPtr selects true_type when any of the |Args| is a raw
-// pointer to a RefCounted type.
-// Implementation note: This non-specialized case handles zero-arity case only.
-// Non-zero-arity cases should be handled by the specialization below.
-template <typename... Args>
-struct HasRefCountedTypeAsRawPtr : false_type {};
-
-// Implementation note: Select true_type if the first parameter is a raw pointer
-// to a RefCounted type. Otherwise, skip the first parameter and check rest of
-// parameters recursively.
-template <typename T, typename... Args>
-struct HasRefCountedTypeAsRawPtr<T, Args...>
- : std::conditional<NeedsScopedRefptrButGetsRawPtr<T>::value,
- true_type,
- HasRefCountedTypeAsRawPtr<Args...>>::type {};
-
-// BindsArrayToFirstArg selects true_type when |is_method| is true and the first
-// item of |Args| is an array type.
-// Implementation note: This non-specialized case handles !is_method case and
-// zero-arity case only. Other cases should be handled by the specialization
-// below.
-template <bool is_method, typename... Args>
-struct BindsArrayToFirstArg : false_type {};
-
-template <typename T, typename... Args>
-struct BindsArrayToFirstArg<true, T, Args...> : is_array<T> {};
-
-// HasRefCountedParamAsRawPtr is the same to HasRefCountedTypeAsRawPtr except
-// when |is_method| is true HasRefCountedParamAsRawPtr skips the first argument.
-// Implementation note: This non-specialized case handles !is_method case and
-// zero-arity case only. Other cases should be handled by the specialization
-// below.
-template <bool is_method, typename... Args>
-struct HasRefCountedParamAsRawPtr : HasRefCountedTypeAsRawPtr<Args...> {};
-
-template <typename T, typename... Args>
-struct HasRefCountedParamAsRawPtr<true, T, Args...>
- : HasRefCountedTypeAsRawPtr<Args...> {};
-
-// RunnableAdapter<>
-//
-// The RunnableAdapter<> templates provide a uniform interface for invoking
-// a function pointer, method pointer, or const method pointer. The adapter
-// exposes a Run() method with an appropriate signature. Using this wrapper
-// allows for writing code that supports all three pointer types without
-// undue repetition. Without it, a lot of code would need to be repeated 3
-// times.
-//
-// For method pointers and const method pointers the first argument to Run()
-// is considered to be the received of the method. This is similar to STL's
-// mem_fun().
-//
-// This class also exposes a RunType typedef that is the function type of the
-// Run() function.
-//
-// If and only if the wrapper contains a method or const method pointer, an
-// IsMethod typedef is exposed. The existence of this typedef (NOT the value)
-// marks that the wrapper should be considered a method wrapper.
-
-template <typename Functor>
-class RunnableAdapter;
-
-// Function.
-template <typename R, typename... Args>
-class RunnableAdapter<R(*)(Args...)> {
- public:
- // MSVC 2013 doesn't support Type Alias of function types.
- // Revisit this after we update it to newer version.
- typedef R RunType(Args...);
-
- explicit RunnableAdapter(R(*function)(Args...))
- : function_(function) {
- }
-
- R Run(typename CallbackParamTraits<Args>::ForwardType... args) {
- return function_(CallbackForward(args)...);
- }
-
- private:
- R (*function_)(Args...);
-};
-
-// Method.
-template <typename R, typename T, typename... Args>
-class RunnableAdapter<R(T::*)(Args...)> {
- public:
- // MSVC 2013 doesn't support Type Alias of function types.
- // Revisit this after we update it to newer version.
- typedef R RunType(T*, Args...);
- using IsMethod = true_type;
-
- explicit RunnableAdapter(R(T::*method)(Args...))
- : method_(method) {
- }
-
- R Run(T* object, typename CallbackParamTraits<Args>::ForwardType... args) {
- return (object->*method_)(CallbackForward(args)...);
- }
-
- private:
- R (T::*method_)(Args...);
-};
-
-// Const Method.
-template <typename R, typename T, typename... Args>
-class RunnableAdapter<R(T::*)(Args...) const> {
- public:
- using RunType = R(const T*, Args...);
- using IsMethod = true_type;
-
- explicit RunnableAdapter(R(T::*method)(Args...) const)
- : method_(method) {
- }
-
- R Run(const T* object,
- typename CallbackParamTraits<Args>::ForwardType... args) {
- return (object->*method_)(CallbackForward(args)...);
- }
-
- private:
- R (T::*method_)(Args...) const;
-};
-
-
-// ForceVoidReturn<>
-//
-// Set of templates that support forcing the function return type to void.
-template <typename Sig>
-struct ForceVoidReturn;
-
-template <typename R, typename... Args>
-struct ForceVoidReturn<R(Args...)> {
- // MSVC 2013 doesn't support Type Alias of function types.
- // Revisit this after we update it to newer version.
- typedef void RunType(Args...);
-};
-
-
-// FunctorTraits<>
-//
-// See description at top of file.
-template <typename T>
-struct FunctorTraits {
- using RunnableType = RunnableAdapter<T>;
- using RunType = typename RunnableType::RunType;
-};
-
-template <typename T>
-struct FunctorTraits<IgnoreResultHelper<T>> {
- using RunnableType = typename FunctorTraits<T>::RunnableType;
- using RunType =
- typename ForceVoidReturn<typename RunnableType::RunType>::RunType;
-};
-
-template <typename T>
-struct FunctorTraits<Callback<T>> {
- using RunnableType = Callback<T> ;
- using RunType = typename Callback<T>::RunType;
-};
-
-
-// MakeRunnable<>
-//
-// Converts a passed in functor to a RunnableType using type inference.
-
-template <typename T>
-typename FunctorTraits<T>::RunnableType MakeRunnable(const T& t) {
- return RunnableAdapter<T>(t);
-}
-
-template <typename T>
-typename FunctorTraits<T>::RunnableType
-MakeRunnable(const IgnoreResultHelper<T>& t) {
- return MakeRunnable(t.functor_);
-}
-
-template <typename T>
-const typename FunctorTraits<Callback<T>>::RunnableType&
-MakeRunnable(const Callback<T>& t) {
- DCHECK(!t.is_null());
- return t;
-}
-
-
-// InvokeHelper<>
-//
-// There are 3 logical InvokeHelper<> specializations: normal, void-return,
-// WeakCalls.
-//
-// The normal type just calls the underlying runnable.
-//
-// We need a InvokeHelper to handle void return types in order to support
-// IgnoreResult(). Normally, if the Runnable's RunType had a void return,
-// the template system would just accept "return functor.Run()" ignoring
-// the fact that a void function is being used with return. This piece of
-// sugar breaks though when the Runnable's RunType is not void. Thus, we
-// need a partial specialization to change the syntax to drop the "return"
-// from the invocation call.
-//
-// WeakCalls similarly need special syntax that is applied to the first
-// argument to check if they should no-op themselves.
-template <bool IsWeakCall, typename ReturnType, typename Runnable,
- typename ArgsType>
-struct InvokeHelper;
-
-template <typename ReturnType, typename Runnable, typename... Args>
-struct InvokeHelper<false, ReturnType, Runnable, TypeList<Args...>> {
- static ReturnType MakeItSo(Runnable runnable, Args... args) {
- return runnable.Run(CallbackForward(args)...);
- }
-};
-
-template <typename Runnable, typename... Args>
-struct InvokeHelper<false, void, Runnable, TypeList<Args...>> {
- static void MakeItSo(Runnable runnable, Args... args) {
- runnable.Run(CallbackForward(args)...);
- }
-};
-
-template <typename Runnable, typename BoundWeakPtr, typename... Args>
-struct InvokeHelper<true, void, Runnable, TypeList<BoundWeakPtr, Args...>> {
- static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, Args... args) {
- if (!weak_ptr.get()) {
- return;
- }
- runnable.Run(weak_ptr.get(), CallbackForward(args)...);
- }
-};
-
-#if !defined(_MSC_VER)
-
-template <typename ReturnType, typename Runnable, typename ArgsType>
-struct InvokeHelper<true, ReturnType, Runnable, ArgsType> {
- // WeakCalls are only supported for functions with a void return type.
- // Otherwise, the function result would be undefined if the the WeakPtr<>
- // is invalidated.
- static_assert(is_void<ReturnType>::value,
- "weak_ptrs can only bind to methods without return values");
-};
-
-#endif
-
-// Invoker<>
-//
-// See description at the top of the file.
-template <typename BoundIndices,
- typename StorageType, typename Unwrappers,
- typename InvokeHelperType, typename UnboundForwardRunType>
-struct Invoker;
-
-template <size_t... bound_indices,
- typename StorageType,
- typename... Unwrappers,
- typename InvokeHelperType,
- typename R,
- typename... UnboundForwardArgs>
-struct Invoker<IndexSequence<bound_indices...>,
- StorageType, TypeList<Unwrappers...>,
- InvokeHelperType, R(UnboundForwardArgs...)> {
- static R Run(BindStateBase* base,
- UnboundForwardArgs... unbound_args) {
- StorageType* storage = static_cast<StorageType*>(base);
- // Local references to make debugger stepping easier. If in a debugger,
- // you really want to warp ahead and step through the
- // InvokeHelper<>::MakeItSo() call below.
- return InvokeHelperType::MakeItSo(
- storage->runnable_,
- Unwrappers::Unwrap(get<bound_indices>(storage->bound_args_))...,
- CallbackForward(unbound_args)...);
- }
-};
-
-
-// BindState<>
-//
-// This stores all the state passed into Bind() and is also where most
-// of the template resolution magic occurs.
-//
-// Runnable is the functor we are binding arguments to.
-// RunType is type of the Run() function that the Invoker<> should use.
-// Normally, this is the same as the RunType of the Runnable, but it can
-// be different if an adapter like IgnoreResult() has been used.
-//
-// BoundArgs contains the storage type for all the bound arguments.
-template <typename Runnable, typename RunType, typename... BoundArgs>
-struct BindState;
-
-template <typename Runnable,
- typename R,
- typename... Args,
- typename... BoundArgs>
-struct BindState<Runnable, R(Args...), BoundArgs...> final
- : public BindStateBase {
- private:
- using StorageType = BindState<Runnable, R(Args...), BoundArgs...>;
- using RunnableType = Runnable;
-
- // true_type if Runnable is a method invocation and the first bound argument
- // is a WeakPtr.
- using IsWeakCall =
- IsWeakMethod<HasIsMethodTag<Runnable>::value, BoundArgs...>;
-
- using BoundIndices = MakeIndexSequence<sizeof...(BoundArgs)>;
- using Unwrappers = TypeList<UnwrapTraits<BoundArgs>...>;
- using UnboundForwardArgs = DropTypeListItem<
- sizeof...(BoundArgs),
- TypeList<typename CallbackParamTraits<Args>::ForwardType...>>;
- using UnboundForwardRunType = MakeFunctionType<R, UnboundForwardArgs>;
-
- using InvokeHelperArgs = ConcatTypeLists<
- TypeList<typename UnwrapTraits<BoundArgs>::ForwardType...>,
- UnboundForwardArgs>;
- using InvokeHelperType =
- InvokeHelper<IsWeakCall::value, R, Runnable, InvokeHelperArgs>;
-
- using UnboundArgs = DropTypeListItem<sizeof...(BoundArgs), TypeList<Args...>>;
-
- public:
- using InvokerType = Invoker<BoundIndices, StorageType, Unwrappers,
- InvokeHelperType, UnboundForwardRunType>;
- using UnboundRunType = MakeFunctionType<R, UnboundArgs>;
-
- BindState(const Runnable& runnable, const BoundArgs&... bound_args)
- : BindStateBase(&Destroy),
- runnable_(runnable),
- ref_(bound_args...),
- bound_args_(bound_args...) {}
-
- RunnableType runnable_;
- MaybeScopedRefPtr<HasIsMethodTag<Runnable>::value, BoundArgs...> ref_;
- Tuple<BoundArgs...> bound_args_;
-
- private:
- ~BindState() {}
-
- static void Destroy(BindStateBase* self) {
- delete static_cast<BindState*>(self);
- }
-};
-
-} // namespace internal
-} // namespace base
-
-#endif // BASE_BIND_INTERNAL_H_
diff --git a/security/sandbox/chromium/base/bind_internal_win.h b/security/sandbox/chromium/base/bind_internal_win.h
deleted file mode 100644
index 2ee12ef21..000000000
--- a/security/sandbox/chromium/base/bind_internal_win.h
+++ /dev/null
@@ -1,69 +0,0 @@
-// 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.
-
-// Specializations of RunnableAdapter<> for Windows specific calling
-// conventions. Please see base/bind_internal.h for more info.
-
-#ifndef BASE_BIND_INTERNAL_WIN_H_
-#define BASE_BIND_INTERNAL_WIN_H_
-
-#include "build/build_config.h"
-
-// In the x64 architecture in Windows, __fastcall, __stdcall, etc, are all
-// the same as __cdecl which would turn the following specializations into
-// multiple definitions.
-#if !defined(ARCH_CPU_X86_64)
-
-namespace base {
-namespace internal {
-
-template <typename Functor>
-class RunnableAdapter;
-
-// __stdcall Function.
-template <typename R, typename... Args>
-class RunnableAdapter<R(__stdcall *)(Args...)> {
- public:
- // MSVC 2013 doesn't support Type Alias of function types.
- // Revisit this after we update it to newer version.
- typedef R RunType(Args...);
-
- explicit RunnableAdapter(R(__stdcall *function)(Args...))
- : function_(function) {
- }
-
- R Run(typename CallbackParamTraits<Args>::ForwardType... args) {
- return function_(args...);
- }
-
- private:
- R (__stdcall *function_)(Args...);
-};
-
-// __fastcall Function.
-template <typename R, typename... Args>
-class RunnableAdapter<R(__fastcall *)(Args...)> {
- public:
- // MSVC 2013 doesn't support Type Alias of function types.
- // Revisit this after we update it to newer version.
- typedef R RunType(Args...);
-
- explicit RunnableAdapter(R(__fastcall *function)(Args...))
- : function_(function) {
- }
-
- R Run(typename CallbackParamTraits<Args>::ForwardType... args) {
- return function_(args...);
- }
-
- private:
- R (__fastcall *function_)(Args...);
-};
-
-} // namespace internal
-} // namespace base
-
-#endif // !defined(ARCH_CPU_X86_64)
-
-#endif // BASE_BIND_INTERNAL_WIN_H_
diff --git a/security/sandbox/chromium/base/bit_cast.h b/security/sandbox/chromium/base/bit_cast.h
deleted file mode 100644
index b548467e7..000000000
--- a/security/sandbox/chromium/base/bit_cast.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// 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 BASE_BIT_CAST_H_
-#define BASE_BIT_CAST_H_
-
-#include <string.h>
-
-// bit_cast<Dest,Source> is a template function that implements the equivalent
-// of "*reinterpret_cast<Dest*>(&source)". We need this in very low-level
-// functions like the protobuf library and fast math support.
-//
-// float f = 3.14159265358979;
-// int i = bit_cast<int32_t>(f);
-// // i = 0x40490fdb
-//
-// The classical address-casting method is:
-//
-// // WRONG
-// float f = 3.14159265358979; // WRONG
-// int i = * reinterpret_cast<int*>(&f); // WRONG
-//
-// The address-casting method actually produces undefined behavior according to
-// the ISO C++98 specification, section 3.10 ("basic.lval"), paragraph 15.
-// (This did not substantially change in C++11.) Roughly, this section says: if
-// an object in memory has one type, and a program accesses it with a different
-// type, then the result is undefined behavior for most values of "different
-// type".
-//
-// This is true for any cast syntax, either *(int*)&f or
-// *reinterpret_cast<int*>(&f). And it is particularly true for conversions
-// between integral lvalues and floating-point lvalues.
-//
-// The purpose of this paragraph is to allow optimizing compilers to assume that
-// expressions with different types refer to different memory. Compilers are
-// known to take advantage of this. So a non-conforming program quietly
-// produces wildly incorrect output.
-//
-// The problem is not the use of reinterpret_cast. The problem is type punning:
-// holding an object in memory of one type and reading its bits back using a
-// different type.
-//
-// The C++ standard is more subtle and complex than this, but that is the basic
-// idea.
-//
-// Anyways ...
-//
-// bit_cast<> calls memcpy() which is blessed by the standard, especially by the
-// example in section 3.9 . Also, of course, bit_cast<> wraps up the nasty
-// logic in one place.
-//
-// Fortunately memcpy() is very fast. In optimized mode, compilers replace
-// calls to memcpy() with inline object code when the size argument is a
-// compile-time constant. On a 32-bit system, memcpy(d,s,4) compiles to one
-// load and one store, and memcpy(d,s,8) compiles to two loads and two stores.
-//
-// WARNING: if Dest or Source is a non-POD type, the result of the memcpy
-// is likely to surprise you.
-
-template <class Dest, class Source>
-inline Dest bit_cast(const Source& source) {
- static_assert(sizeof(Dest) == sizeof(Source),
- "bit_cast requires source and destination to be the same size");
-
- Dest dest;
- memcpy(&dest, &source, sizeof(dest));
- return dest;
-}
-
-#endif // BASE_BIT_CAST_H_
diff --git a/security/sandbox/chromium/base/callback.h b/security/sandbox/chromium/base/callback.h
deleted file mode 100644
index 3bf0008b6..000000000
--- a/security/sandbox/chromium/base/callback.h
+++ /dev/null
@@ -1,405 +0,0 @@
-// 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.
-
-#ifndef BASE_CALLBACK_H_
-#define BASE_CALLBACK_H_
-
-#include "base/callback_forward.h"
-#include "base/callback_internal.h"
-#include "base/template_util.h"
-
-// NOTE: Header files that do not require the full definition of Callback or
-// Closure should #include "base/callback_forward.h" instead of this file.
-
-// -----------------------------------------------------------------------------
-// Introduction
-// -----------------------------------------------------------------------------
-//
-// The templated Callback class is a generalized function object. Together
-// with the Bind() function in bind.h, they provide a type-safe method for
-// performing partial application of functions.
-//
-// Partial application (or "currying") is the process of binding a subset of
-// a function's arguments to produce another function that takes fewer
-// arguments. This can be used to pass around a unit of delayed execution,
-// much like lexical closures are used in other languages. For example, it
-// is used in Chromium code to schedule tasks on different MessageLoops.
-//
-// A callback with no unbound input parameters (base::Callback<void()>)
-// is called a base::Closure. Note that this is NOT the same as what other
-// languages refer to as a closure -- it does not retain a reference to its
-// enclosing environment.
-//
-// MEMORY MANAGEMENT AND PASSING
-//
-// The Callback objects themselves should be passed by const-reference, and
-// stored by copy. They internally store their state via a refcounted class
-// and thus do not need to be deleted.
-//
-// The reason to pass via a const-reference is to avoid unnecessary
-// AddRef/Release pairs to the internal state.
-//
-//
-// -----------------------------------------------------------------------------
-// Quick reference for basic stuff
-// -----------------------------------------------------------------------------
-//
-// BINDING A BARE FUNCTION
-//
-// int Return5() { return 5; }
-// base::Callback<int()> func_cb = base::Bind(&Return5);
-// LOG(INFO) << func_cb.Run(); // Prints 5.
-//
-// BINDING A CLASS METHOD
-//
-// The first argument to bind is the member function to call, the second is
-// the object on which to call it.
-//
-// class Ref : public base::RefCountedThreadSafe<Ref> {
-// public:
-// int Foo() { return 3; }
-// void PrintBye() { LOG(INFO) << "bye."; }
-// };
-// scoped_refptr<Ref> ref = new Ref();
-// base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref);
-// LOG(INFO) << ref_cb.Run(); // Prints out 3.
-//
-// By default the object must support RefCounted or you will get a compiler
-// error. If you're passing between threads, be sure it's
-// RefCountedThreadSafe! See "Advanced binding of member functions" below if
-// you don't want to use reference counting.
-//
-// RUNNING A CALLBACK
-//
-// Callbacks can be run with their "Run" method, which has the same
-// signature as the template argument to the callback.
-//
-// void DoSomething(const base::Callback<void(int, std::string)>& callback) {
-// callback.Run(5, "hello");
-// }
-//
-// Callbacks can be run more than once (they don't get deleted or marked when
-// run). However, this precludes using base::Passed (see below).
-//
-// void DoSomething(const base::Callback<double(double)>& callback) {
-// double myresult = callback.Run(3.14159);
-// myresult += callback.Run(2.71828);
-// }
-//
-// PASSING UNBOUND INPUT PARAMETERS
-//
-// Unbound parameters are specified at the time a callback is Run(). They are
-// specified in the Callback template type:
-//
-// void MyFunc(int i, const std::string& str) {}
-// base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
-// cb.Run(23, "hello, world");
-//
-// PASSING BOUND INPUT PARAMETERS
-//
-// Bound parameters are specified when you create thee callback as arguments
-// to Bind(). They will be passed to the function and the Run()ner of the
-// callback doesn't see those values or even know that the function it's
-// calling.
-//
-// void MyFunc(int i, const std::string& str) {}
-// base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world");
-// cb.Run();
-//
-// A callback with no unbound input parameters (base::Callback<void()>)
-// is called a base::Closure. So we could have also written:
-//
-// base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
-//
-// When calling member functions, bound parameters just go after the object
-// pointer.
-//
-// base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
-//
-// PARTIAL BINDING OF PARAMETERS
-//
-// You can specify some parameters when you create the callback, and specify
-// the rest when you execute the callback.
-//
-// void MyFunc(int i, const std::string& str) {}
-// base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23);
-// cb.Run("hello world");
-//
-// When calling a function bound parameters are first, followed by unbound
-// parameters.
-//
-//
-// -----------------------------------------------------------------------------
-// Quick reference for advanced binding
-// -----------------------------------------------------------------------------
-//
-// BINDING A CLASS METHOD WITH WEAK POINTERS
-//
-// base::Bind(&MyClass::Foo, GetWeakPtr());
-//
-// The callback will not be run if the object has already been destroyed.
-// DANGER: weak pointers are not threadsafe, so don't use this
-// when passing between threads!
-//
-// BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT
-//
-// base::Bind(&MyClass::Foo, base::Unretained(this));
-//
-// This disables all lifetime management on the object. You're responsible
-// for making sure the object is alive at the time of the call. You break it,
-// you own it!
-//
-// BINDING A CLASS METHOD AND HAVING THE CALLBACK OWN THE CLASS
-//
-// MyClass* myclass = new MyClass;
-// base::Bind(&MyClass::Foo, base::Owned(myclass));
-//
-// The object will be deleted when the callback is destroyed, even if it's
-// not run (like if you post a task during shutdown). Potentially useful for
-// "fire and forget" cases.
-//
-// IGNORING RETURN VALUES
-//
-// Sometimes you want to call a function that returns a value in a callback
-// that doesn't expect a return value.
-//
-// int DoSomething(int arg) { cout << arg << endl; }
-// base::Callback<void(int)> cb =
-// base::Bind(base::IgnoreResult(&DoSomething));
-//
-//
-// -----------------------------------------------------------------------------
-// Quick reference for binding parameters to Bind()
-// -----------------------------------------------------------------------------
-//
-// Bound parameters are specified as arguments to Bind() and are passed to the
-// function. A callback with no parameters or no unbound parameters is called a
-// Closure (base::Callback<void()> and base::Closure are the same thing).
-//
-// PASSING PARAMETERS OWNED BY THE CALLBACK
-//
-// void Foo(int* arg) { cout << *arg << endl; }
-// int* pn = new int(1);
-// base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));
-//
-// The parameter will be deleted when the callback is destroyed, even if it's
-// not run (like if you post a task during shutdown).
-//
-// PASSING PARAMETERS AS A scoped_ptr
-//
-// void TakesOwnership(scoped_ptr<Foo> arg) {}
-// scoped_ptr<Foo> f(new Foo);
-// // f becomes null during the following call.
-// base::Closure cb = base::Bind(&TakesOwnership, base::Passed(&f));
-//
-// Ownership of the parameter will be with the callback until the it is run,
-// when ownership is passed to the callback function. This means the callback
-// can only be run once. If the callback is never run, it will delete the
-// object when it's destroyed.
-//
-// PASSING PARAMETERS AS A scoped_refptr
-//
-// void TakesOneRef(scoped_refptr<Foo> arg) {}
-// scoped_refptr<Foo> f(new Foo)
-// base::Closure cb = base::Bind(&TakesOneRef, f);
-//
-// This should "just work." The closure will take a reference as long as it
-// is alive, and another reference will be taken for the called function.
-//
-// PASSING PARAMETERS BY REFERENCE
-//
-// Const references are *copied* unless ConstRef is used. Example:
-//
-// void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
-// int n = 1;
-// base::Closure has_copy = base::Bind(&foo, n);
-// base::Closure has_ref = base::Bind(&foo, base::ConstRef(n));
-// n = 2;
-// foo(n); // Prints "2 0xaaaaaaaaaaaa"
-// has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb"
-// has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa"
-//
-// Normally parameters are copied in the closure. DANGER: ConstRef stores a
-// const reference instead, referencing the original parameter. This means
-// that you must ensure the object outlives the callback!
-//
-//
-// -----------------------------------------------------------------------------
-// Implementation notes
-// -----------------------------------------------------------------------------
-//
-// WHERE IS THIS DESIGN FROM:
-//
-// The design Callback and Bind is heavily influenced by C++'s
-// tr1::function/tr1::bind, and by the "Google Callback" system used inside
-// Google.
-//
-//
-// HOW THE IMPLEMENTATION WORKS:
-//
-// There are three main components to the system:
-// 1) The Callback classes.
-// 2) The Bind() functions.
-// 3) The arguments wrappers (e.g., Unretained() and ConstRef()).
-//
-// The Callback classes represent a generic function pointer. Internally,
-// it stores a refcounted piece of state that represents the target function
-// and all its bound parameters. Each Callback specialization has a templated
-// constructor that takes an BindState<>*. In the context of the constructor,
-// the static type of this BindState<> pointer uniquely identifies the
-// function it is representing, all its bound parameters, and a Run() method
-// that is capable of invoking the target.
-//
-// Callback's constructor takes the BindState<>* that has the full static type
-// and erases the target function type as well as the types of the bound
-// parameters. It does this by storing a pointer to the specific Run()
-// function, and upcasting the state of BindState<>* to a
-// BindStateBase*. This is safe as long as this BindStateBase pointer
-// is only used with the stored Run() pointer.
-//
-// To BindState<> objects are created inside the Bind() functions.
-// These functions, along with a set of internal templates, are responsible for
-//
-// - Unwrapping the function signature into return type, and parameters
-// - Determining the number of parameters that are bound
-// - Creating the BindState storing the bound parameters
-// - Performing compile-time asserts to avoid error-prone behavior
-// - Returning an Callback<> with an arity matching the number of unbound
-// parameters and that knows the correct refcounting semantics for the
-// target object if we are binding a method.
-//
-// The Bind functions do the above using type-inference, and template
-// specializations.
-//
-// By default Bind() will store copies of all bound parameters, and attempt
-// to refcount a target object if the function being bound is a class method.
-// These copies are created even if the function takes parameters as const
-// references. (Binding to non-const references is forbidden, see bind.h.)
-//
-// To change this behavior, we introduce a set of argument wrappers
-// (e.g., Unretained(), and ConstRef()). These are simple container templates
-// that are passed by value, and wrap a pointer to argument. See the
-// file-level comment in base/bind_helpers.h for more info.
-//
-// These types are passed to the Unwrap() functions, and the MaybeRefcount()
-// functions respectively to modify the behavior of Bind(). The Unwrap()
-// and MaybeRefcount() functions change behavior by doing partial
-// specialization based on whether or not a parameter is a wrapper type.
-//
-// ConstRef() is similar to tr1::cref. Unretained() is specific to Chromium.
-//
-//
-// WHY NOT TR1 FUNCTION/BIND?
-//
-// Direct use of tr1::function and tr1::bind was considered, but ultimately
-// rejected because of the number of copy constructors invocations involved
-// in the binding of arguments during construction, and the forwarding of
-// arguments during invocation. These copies will no longer be an issue in
-// C++0x because C++0x will support rvalue reference allowing for the compiler
-// to avoid these copies. However, waiting for C++0x is not an option.
-//
-// Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the
-// tr1::bind call itself will invoke a non-trivial copy constructor three times
-// for each bound parameter. Also, each when passing a tr1::function, each
-// bound argument will be copied again.
-//
-// In addition to the copies taken at binding and invocation, copying a
-// tr1::function causes a copy to be made of all the bound parameters and
-// state.
-//
-// Furthermore, in Chromium, it is desirable for the Callback to take a
-// reference on a target object when representing a class method call. This
-// is not supported by tr1.
-//
-// Lastly, tr1::function and tr1::bind has a more general and flexible API.
-// This includes things like argument reordering by use of
-// tr1::bind::placeholder, support for non-const reference parameters, and some
-// limited amount of subtyping of the tr1::function object (e.g.,
-// tr1::function<int(int)> is convertible to tr1::function<void(int)>).
-//
-// These are not features that are required in Chromium. Some of them, such as
-// allowing for reference parameters, and subtyping of functions, may actually
-// become a source of errors. Removing support for these features actually
-// allows for a simpler implementation, and a terser Currying API.
-//
-//
-// WHY NOT GOOGLE CALLBACKS?
-//
-// The Google callback system also does not support refcounting. Furthermore,
-// its implementation has a number of strange edge cases with respect to type
-// conversion of its arguments. In particular, the argument's constness must
-// at times match exactly the function signature, or the type-inference might
-// break. Given the above, writing a custom solution was easier.
-//
-//
-// MISSING FUNCTIONALITY
-// - Invoking the return of Bind. Bind(&foo).Run() does not work;
-// - Binding arrays to functions that take a non-const pointer.
-// Example:
-// void Foo(const char* ptr);
-// void Bar(char* ptr);
-// Bind(&Foo, "test");
-// Bind(&Bar, "test"); // This fails because ptr is not const.
-
-namespace base {
-
-// First, we forward declare the Callback class template. This informs the
-// compiler that the template only has 1 type parameter which is the function
-// signature that the Callback is representing.
-//
-// After this, create template specializations for 0-7 parameters. Note that
-// even though the template typelist grows, the specialization still
-// only has one type: the function signature.
-//
-// If you are thinking of forward declaring Callback in your own header file,
-// please include "base/callback_forward.h" instead.
-
-namespace internal {
-template <typename Runnable, typename RunType, typename... BoundArgsType>
-struct BindState;
-} // namespace internal
-
-template <typename R, typename... Args>
-class Callback<R(Args...)> : public internal::CallbackBase {
- public:
- // MSVC 2013 doesn't support Type Alias of function types.
- // Revisit this after we update it to newer version.
- typedef R RunType(Args...);
-
- Callback() : CallbackBase(nullptr) { }
-
- template <typename Runnable, typename BindRunType, typename... BoundArgsType>
- explicit Callback(
- internal::BindState<Runnable, BindRunType, BoundArgsType...>* bind_state)
- : CallbackBase(bind_state) {
- // Force the assignment to a local variable of PolymorphicInvoke
- // so the compiler will typecheck that the passed in Run() method has
- // the correct type.
- PolymorphicInvoke invoke_func =
- &internal::BindState<Runnable, BindRunType, BoundArgsType...>
- ::InvokerType::Run;
- polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
- }
-
- bool Equals(const Callback& other) const {
- return CallbackBase::Equals(other);
- }
-
- R Run(typename internal::CallbackParamTraits<Args>::ForwardType... args)
- const {
- PolymorphicInvoke f =
- reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
-
- return f(bind_state_.get(), internal::CallbackForward(args)...);
- }
-
- private:
- using PolymorphicInvoke =
- R(*)(internal::BindStateBase*,
- typename internal::CallbackParamTraits<Args>::ForwardType...);
-};
-
-} // namespace base
-
-#endif // BASE_CALLBACK_H_
diff --git a/security/sandbox/chromium/base/callback_forward.h b/security/sandbox/chromium/base/callback_forward.h
deleted file mode 100644
index a9a263a50..000000000
--- a/security/sandbox/chromium/base/callback_forward.h
+++ /dev/null
@@ -1,19 +0,0 @@
-// 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_CALLBACK_FORWARD_H_
-#define BASE_CALLBACK_FORWARD_H_
-
-namespace base {
-
-template <typename Sig>
-class Callback;
-
-// Syntactic sugar to make Callback<void()> easier to declare since it
-// will be used in a lot of APIs with delayed execution.
-using Closure = Callback<void()>;
-
-} // namespace base
-
-#endif // BASE_CALLBACK_FORWARD_H_
diff --git a/security/sandbox/chromium/base/callback_internal.cc b/security/sandbox/chromium/base/callback_internal.cc
deleted file mode 100644
index 2553fe7e1..000000000
--- a/security/sandbox/chromium/base/callback_internal.cc
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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.
-
-#include "base/callback_internal.h"
-
-#include "base/logging.h"
-
-namespace base {
-namespace internal {
-
-void BindStateBase::AddRef() {
- AtomicRefCountInc(&ref_count_);
-}
-
-void BindStateBase::Release() {
- if (!AtomicRefCountDec(&ref_count_))
- destructor_(this);
-}
-
-CallbackBase::CallbackBase(const CallbackBase& c) = default;
-CallbackBase& CallbackBase::operator=(const CallbackBase& c) = default;
-
-void CallbackBase::Reset() {
- polymorphic_invoke_ = NULL;
- // NULL the bind_state_ last, since it may be holding the last ref to whatever
- // object owns us, and we may be deleted after that.
- bind_state_ = NULL;
-}
-
-bool CallbackBase::Equals(const CallbackBase& other) const {
- return bind_state_.get() == other.bind_state_.get() &&
- polymorphic_invoke_ == other.polymorphic_invoke_;
-}
-
-CallbackBase::CallbackBase(BindStateBase* bind_state)
- : bind_state_(bind_state),
- polymorphic_invoke_(NULL) {
- DCHECK(!bind_state_.get() || bind_state_->ref_count_ == 1);
-}
-
-CallbackBase::~CallbackBase() {
-}
-
-} // namespace internal
-} // namespace base
diff --git a/security/sandbox/chromium/base/callback_internal.h b/security/sandbox/chromium/base/callback_internal.h
deleted file mode 100644
index d1d8ab8ec..000000000
--- a/security/sandbox/chromium/base/callback_internal.h
+++ /dev/null
@@ -1,234 +0,0 @@
-// 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 file contains utility functions and classes that help the
-// implementation, and management of the Callback objects.
-
-#ifndef BASE_CALLBACK_INTERNAL_H_
-#define BASE_CALLBACK_INTERNAL_H_
-
-#include <stddef.h>
-#include <memory>
-#include <type_traits>
-
-#include "base/atomic_ref_count.h"
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/template_util.h"
-
-namespace base {
-namespace internal {
-class CallbackBase;
-
-// BindStateBase is used to provide an opaque handle that the Callback
-// class can use to represent a function object with bound arguments. It
-// behaves as an existential type that is used by a corresponding
-// DoInvoke function to perform the function execution. This allows
-// us to shield the Callback class from the types of the bound argument via
-// "type erasure."
-// At the base level, the only task is to add reference counting data. Don't use
-// RefCountedThreadSafe since it requires the destructor to be a virtual method.
-// Creating a vtable for every BindState template instantiation results in a lot
-// of bloat. Its only task is to call the destructor which can be done with a
-// function pointer.
-class BindStateBase {
- protected:
- explicit BindStateBase(void (*destructor)(BindStateBase*))
- : ref_count_(0), destructor_(destructor) {}
- ~BindStateBase() = default;
-
- private:
- friend class scoped_refptr<BindStateBase>;
- friend class CallbackBase;
-
- void AddRef();
- void Release();
-
- AtomicRefCount ref_count_;
-
- // Pointer to a function that will properly destroy |this|.
- void (*destructor_)(BindStateBase*);
-
- DISALLOW_COPY_AND_ASSIGN(BindStateBase);
-};
-
-// Holds the Callback methods that don't require specialization to reduce
-// template bloat.
-class BASE_EXPORT CallbackBase {
- public:
- CallbackBase(const CallbackBase& c);
- CallbackBase& operator=(const CallbackBase& c);
-
- // Returns true if Callback is null (doesn't refer to anything).
- bool is_null() const { return bind_state_.get() == NULL; }
-
- // Returns the Callback into an uninitialized state.
- void Reset();
-
- protected:
- // In C++, it is safe to cast function pointers to function pointers of
- // another type. It is not okay to use void*. We create a InvokeFuncStorage
- // that that can store our function pointer, and then cast it back to
- // the original type on usage.
- using InvokeFuncStorage = void(*)();
-
- // Returns true if this callback equals |other|. |other| may be null.
- bool Equals(const CallbackBase& other) const;
-
- // Allow initializing of |bind_state_| via the constructor to avoid default
- // initialization of the scoped_refptr. We do not also initialize
- // |polymorphic_invoke_| here because doing a normal assignment in the
- // derived Callback templates makes for much nicer compiler errors.
- explicit CallbackBase(BindStateBase* bind_state);
-
- // Force the destructor to be instantiated inside this translation unit so
- // that our subclasses will not get inlined versions. Avoids more template
- // bloat.
- ~CallbackBase();
-
- scoped_refptr<BindStateBase> bind_state_;
- InvokeFuncStorage polymorphic_invoke_;
-};
-
-// A helper template to determine if given type is non-const move-only-type,
-// i.e. if a value of the given type should be passed via std::move() in a
-// destructive way. Types are considered to be move-only if they have a
-// sentinel MoveOnlyTypeForCPP03 member: a class typically gets this from using
-// the DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND macro.
-// It would be easy to generalize this trait to all move-only types... but this
-// confuses template deduction in VS2013 with certain types such as
-// std::unique_ptr.
-// TODO(dcheng): Revisit this when Windows switches to VS2015 by default.
-template <typename T> struct IsMoveOnlyType {
- template <typename U>
- static YesType Test(const typename U::MoveOnlyTypeForCPP03*);
-
- template <typename U>
- static NoType Test(...);
-
- static const bool value = sizeof((Test<T>(0))) == sizeof(YesType) &&
- !is_const<T>::value;
-};
-
-// Specialization of IsMoveOnlyType so that std::unique_ptr is still considered
-// move-only, even without the sentinel member.
-template <typename T>
-struct IsMoveOnlyType<std::unique_ptr<T>> : std::true_type {};
-
-template <typename>
-struct CallbackParamTraitsForMoveOnlyType;
-
-template <typename>
-struct CallbackParamTraitsForNonMoveOnlyType;
-
-// TODO(tzik): Use a default parameter once MSVS supports variadic templates
-// with default values.
-// http://connect.microsoft.com/VisualStudio/feedbackdetail/view/957801/compilation-error-with-variadic-templates
-//
-// This is a typetraits object that's used to take an argument type, and
-// extract a suitable type for storing and forwarding arguments.
-//
-// In particular, it strips off references, and converts arrays to
-// pointers for storage; and it avoids accidentally trying to create a
-// "reference of a reference" if the argument is a reference type.
-//
-// This array type becomes an issue for storage because we are passing bound
-// parameters by const reference. In this case, we end up passing an actual
-// array type in the initializer list which C++ does not allow. This will
-// break passing of C-string literals.
-template <typename T>
-struct CallbackParamTraits
- : std::conditional<IsMoveOnlyType<T>::value,
- CallbackParamTraitsForMoveOnlyType<T>,
- CallbackParamTraitsForNonMoveOnlyType<T>>::type {
-};
-
-template <typename T>
-struct CallbackParamTraitsForNonMoveOnlyType {
- using ForwardType = const T&;
- using StorageType = T;
-};
-
-// The Storage should almost be impossible to trigger unless someone manually
-// specifies type of the bind parameters. However, in case they do,
-// this will guard against us accidentally storing a reference parameter.
-//
-// The ForwardType should only be used for unbound arguments.
-template <typename T>
-struct CallbackParamTraitsForNonMoveOnlyType<T&> {
- using ForwardType = T&;
- using StorageType = T;
-};
-
-// Note that for array types, we implicitly add a const in the conversion. This
-// means that it is not possible to bind array arguments to functions that take
-// a non-const pointer. Trying to specialize the template based on a "const
-// T[n]" does not seem to match correctly, so we are stuck with this
-// restriction.
-template <typename T, size_t n>
-struct CallbackParamTraitsForNonMoveOnlyType<T[n]> {
- using ForwardType = const T*;
- using StorageType = const T*;
-};
-
-// See comment for CallbackParamTraits<T[n]>.
-template <typename T>
-struct CallbackParamTraitsForNonMoveOnlyType<T[]> {
- using ForwardType = const T*;
- using StorageType = const T*;
-};
-
-// Parameter traits for movable-but-not-copyable scopers.
-//
-// Callback<>/Bind() understands movable-but-not-copyable semantics where
-// the type cannot be copied but can still have its state destructively
-// transferred (aka. moved) to another instance of the same type by calling a
-// helper function. When used with Bind(), this signifies transferal of the
-// object's state to the target function.
-//
-// For these types, the ForwardType must not be a const reference, or a
-// reference. A const reference is inappropriate, and would break const
-// correctness, because we are implementing a destructive move. A non-const
-// reference cannot be used with temporaries which means the result of a
-// function or a cast would not be usable with Callback<> or Bind().
-template <typename T>
-struct CallbackParamTraitsForMoveOnlyType {
- using ForwardType = T;
- using StorageType = T;
-};
-
-// CallbackForward() is a very limited simulation of C++11's std::forward()
-// used by the Callback/Bind system for a set of movable-but-not-copyable
-// types. It is needed because forwarding a movable-but-not-copyable
-// argument to another function requires us to invoke the proper move
-// operator to create a rvalue version of the type. The supported types are
-// whitelisted below as overloads of the CallbackForward() function. The
-// default template compiles out to be a no-op.
-//
-// In C++11, std::forward would replace all uses of this function. However, it
-// is impossible to implement a general std::forward without C++11 due to a lack
-// of rvalue references.
-//
-// In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to
-// simulate std::forward() and forward the result of one Callback as a
-// parameter to another callback. This is to support Callbacks that return
-// the movable-but-not-copyable types whitelisted above.
-template <typename T>
-typename std::enable_if<!IsMoveOnlyType<T>::value, T>::type& CallbackForward(
- T& t) {
- return t;
-}
-
-template <typename T>
-typename std::enable_if<IsMoveOnlyType<T>::value, T>::type CallbackForward(
- T& t) {
- return std::move(t);
-}
-
-} // namespace internal
-} // namespace base
-
-#endif // BASE_CALLBACK_INTERNAL_H_
diff --git a/security/sandbox/chromium/base/compiler_specific.h b/security/sandbox/chromium/base/compiler_specific.h
deleted file mode 100644
index 339e9b74e..000000000
--- a/security/sandbox/chromium/base/compiler_specific.h
+++ /dev/null
@@ -1,190 +0,0 @@
-// 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.
-
-#ifndef BASE_COMPILER_SPECIFIC_H_
-#define BASE_COMPILER_SPECIFIC_H_
-
-#include "build/build_config.h"
-
-#if defined(COMPILER_MSVC)
-
-// For _Printf_format_string_.
-#include <sal.h>
-
-// 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 exporting a class that inherits from a non-exported base class.
-// This uses suppress instead of push/pop because the delimiter after the
-// declaration (either "," or "{") has to be placed before the pop macro.
-//
-// Example usage:
-// class EXPORT_API Foo : NON_EXPORTED_BASE(public Bar) {
-//
-// MSVC Compiler warning C4275:
-// non dll-interface class 'Bar' used as base for dll-interface class 'Foo'.
-// Note that this is intended to be used only when no access to the base class'
-// static data is done through derived classes or inline methods. For more info,
-// see http://msdn.microsoft.com/en-us/library/3tdb471s(VS.80).aspx
-#define NON_EXPORTED_BASE(code) MSVC_SUPPRESS_WARNING(4275) \
- code
-
-#else // Not MSVC
-
-#define _Printf_format_string_
-#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 NON_EXPORTED_BASE(code) code
-
-#endif // COMPILER_MSVC
-
-
-// Annotate a variable indicating it's ok if the variable is not used.
-// (Typically used to silence a compiler warning when the assignment
-// is important for some other reason.)
-// Use like:
-// int x = ...;
-// ALLOW_UNUSED_LOCAL(x);
-#define ALLOW_UNUSED_LOCAL(x) false ? (void)x : (void)0
-
-// Annotate a typedef or function indicating it's ok if it's not used.
-// Use like:
-// typedef Foo Bar ALLOW_UNUSED_TYPE;
-#if defined(COMPILER_GCC) || defined(__clang__)
-#define ALLOW_UNUSED_TYPE __attribute__((unused))
-#else
-#define ALLOW_UNUSED_TYPE
-#endif
-
-// Annotate a function indicating it should not be inlined.
-// Use like:
-// NOINLINE void DoStuff() { ... }
-#if defined(COMPILER_GCC)
-#define NOINLINE __attribute__((noinline))
-#elif defined(COMPILER_MSVC)
-#define NOINLINE __declspec(noinline)
-#else
-#define NOINLINE
-#endif
-
-// Specify memory alignment for structs, classes, etc.
-// Use like:
-// class ALIGNAS(16) MyClass { ... }
-// ALIGNAS(16) int array[4];
-#if defined(COMPILER_MSVC)
-#define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
-#elif defined(COMPILER_GCC)
-#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
-#endif
-
-// Return the byte alignment of the given type (available at compile time).
-// Use like:
-// ALIGNOF(int32_t) // this would be 4
-#if defined(COMPILER_MSVC)
-#define ALIGNOF(type) __alignof(type)
-#elif defined(COMPILER_GCC)
-#define ALIGNOF(type) __alignof__(type)
-#endif
-
-// 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(COMPILER_GCC) || defined(__clang__)
-#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
-#else
-#define WARN_UNUSED_RESULT
-#endif
-
-// Tell the compiler a function is using a printf-style format string.
-// |format_param| is the one-based index of the format string parameter;
-// |dots_param| is the one-based index of the "..." parameter.
-// For v*printf functions (which take a va_list), pass 0 for dots_param.
-// (This is undocumented but matches what the system C headers do.)
-#if defined(COMPILER_GCC)
-#define PRINTF_FORMAT(format_param, dots_param) \
- __attribute__((format(printf, format_param, dots_param)))
-#else
-#define PRINTF_FORMAT(format_param, dots_param)
-#endif
-
-// WPRINTF_FORMAT is the same, but for wide format strings.
-// This doesn't appear to yet be implemented in any compiler.
-// See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38308 .
-#define WPRINTF_FORMAT(format_param, dots_param)
-// If available, it would look like:
-// __attribute__((format(wprintf, format_param, dots_param)))
-
-// MemorySanitizer annotations.
-#if defined(MEMORY_SANITIZER) && !defined(OS_NACL)
-#include <sanitizer/msan_interface.h>
-
-// Mark a memory region fully initialized.
-// Use this to annotate code that deliberately reads uninitialized data, for
-// example a GC scavenging root set pointers from the stack.
-#define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
-
-// Check a memory region for initializedness, as if it was being used here.
-// If any bits are uninitialized, crash with an MSan report.
-// Use this to sanitize data which MSan won't be able to track, e.g. before
-// passing data to another process via shared memory.
-#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
- __msan_check_mem_is_initialized(p, size)
-#else // MEMORY_SANITIZER
-#define MSAN_UNPOISON(p, size)
-#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
-#endif // MEMORY_SANITIZER
-
-// Macro useful for writing cross-platform function pointers.
-#if !defined(CDECL)
-#if defined(OS_WIN)
-#define CDECL __cdecl
-#else // defined(OS_WIN)
-#define CDECL
-#endif // defined(OS_WIN)
-#endif // !defined(CDECL)
-
-// Macro for hinting that an expression is likely to be false.
-#if !defined(UNLIKELY)
-#if defined(COMPILER_GCC)
-#define UNLIKELY(x) __builtin_expect(!!(x), 0)
-#else
-#define UNLIKELY(x) (x)
-#endif // defined(COMPILER_GCC)
-#endif // !defined(UNLIKELY)
-
-#endif // BASE_COMPILER_SPECIFIC_H_
diff --git a/security/sandbox/chromium/base/containers/hash_tables.h b/security/sandbox/chromium/base/containers/hash_tables.h
deleted file mode 100644
index c421dddf3..000000000
--- a/security/sandbox/chromium/base/containers/hash_tables.h
+++ /dev/null
@@ -1,281 +0,0 @@
-// 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.
-//
-
-//
-// Deal with the differences between Microsoft and GNU implemenations
-// of hash_map. Allows all platforms to use |base::hash_map| and
-// |base::hash_set|.
-// eg:
-// base::hash_map<int> my_map;
-// base::hash_set<int> my_set;
-//
-// NOTE: It is an explicit non-goal of this class to provide a generic hash
-// function for pointers. If you want to hash a pointers to a particular class,
-// please define the template specialization elsewhere (for example, in its
-// header file) and keep it specific to just pointers to that class. This is
-// because identity hashes are not desirable for all types that might show up
-// in containers as pointers.
-
-#ifndef BASE_CONTAINERS_HASH_TABLES_H_
-#define BASE_CONTAINERS_HASH_TABLES_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <utility>
-
-#include "base/strings/string16.h"
-#include "build/build_config.h"
-
-#if defined(COMPILER_MSVC)
-#include <unordered_map>
-#include <unordered_set>
-
-#define BASE_HASH_NAMESPACE std
-
-#elif defined(COMPILER_GCC)
-
-#define BASE_HASH_NAMESPACE base_hash
-
-// This is a hack to disable the gcc 4.4 warning about hash_map and hash_set
-// being deprecated. We can get rid of this when we upgrade to VS2008 and we
-// can use <tr1/unordered_map> and <tr1/unordered_set>.
-#ifdef __DEPRECATED
-#define CHROME_OLD__DEPRECATED __DEPRECATED
-#undef __DEPRECATED
-#endif
-
-#include <ext/hash_map>
-#include <ext/hash_set>
-#define BASE_HASH_IMPL_NAMESPACE __gnu_cxx
-
-#include <string>
-
-#ifdef CHROME_OLD__DEPRECATED
-#define __DEPRECATED CHROME_OLD__DEPRECATED
-#undef CHROME_OLD__DEPRECATED
-#endif
-
-namespace BASE_HASH_NAMESPACE {
-
-// The pre-standard hash behaves like C++11's std::hash, except around pointers.
-// const char* is specialized to hash the C string and hash functions for
-// general T* are missing. Define a BASE_HASH_NAMESPACE::hash which aligns with
-// the C++11 behavior.
-
-template<typename T>
-struct hash {
- std::size_t operator()(const T& value) const {
- return BASE_HASH_IMPL_NAMESPACE::hash<T>()(value);
- }
-};
-
-template<typename T>
-struct hash<T*> {
- std::size_t operator()(T* value) const {
- return BASE_HASH_IMPL_NAMESPACE::hash<uintptr_t>()(
- reinterpret_cast<uintptr_t>(value));
- }
-};
-
-// The GNU C++ library provides identity hash functions for many integral types,
-// but not for |long long|. This hash function will truncate if |size_t| is
-// narrower than |long long|. This is probably good enough for what we will
-// use it for.
-
-#define DEFINE_TRIVIAL_HASH(integral_type) \
- template<> \
- struct hash<integral_type> { \
- std::size_t operator()(integral_type value) const { \
- return static_cast<std::size_t>(value); \
- } \
- }
-
-DEFINE_TRIVIAL_HASH(long long);
-DEFINE_TRIVIAL_HASH(unsigned long long);
-
-#undef DEFINE_TRIVIAL_HASH
-
-// Implement string hash functions so that strings of various flavors can
-// be used as keys in STL maps and sets. The hash algorithm comes from the
-// GNU C++ library, in <tr1/functional>. It is duplicated here because GCC
-// versions prior to 4.3.2 are unable to compile <tr1/functional> when RTTI
-// is disabled, as it is in our build.
-
-#define DEFINE_STRING_HASH(string_type) \
- template<> \
- struct hash<string_type> { \
- std::size_t operator()(const string_type& s) const { \
- std::size_t result = 0; \
- for (string_type::const_iterator i = s.begin(); i != s.end(); ++i) \
- result = (result * 131) + *i; \
- return result; \
- } \
- }
-
-DEFINE_STRING_HASH(std::string);
-DEFINE_STRING_HASH(base::string16);
-
-#undef DEFINE_STRING_HASH
-
-} // namespace BASE_HASH_NAMESPACE
-
-#else // COMPILER
-#error define BASE_HASH_NAMESPACE for your compiler
-#endif // COMPILER
-
-namespace base {
-
-// On MSVC, use the C++11 containers.
-#if defined(COMPILER_MSVC)
-
-template<class Key, class T,
- class Hash = std::hash<Key>,
- class Pred = std::equal_to<Key>,
- class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_map = std::unordered_map<Key, T, Hash, Pred, Alloc>;
-
-template<class Key, class T,
- class Hash = std::hash<Key>,
- class Pred = std::equal_to<Key>,
- class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_multimap = std::unordered_multimap<Key, T, Hash, Pred, Alloc>;
-
-template<class Key,
- class Hash = std::hash<Key>,
- class Pred = std::equal_to<Key>,
- class Alloc = std::allocator<Key>>
-using hash_multiset = std::unordered_multiset<Key, Hash, Pred, Alloc>;
-
-template<class Key,
- class Hash = std::hash<Key>,
- class Pred = std::equal_to<Key>,
- class Alloc = std::allocator<Key>>
-using hash_set = std::unordered_set<Key, Hash, Pred, Alloc>;
-
-#else // !COMPILER_MSVC
-
-// Otherwise, use the pre-standard ones, but override the default hash to match
-// C++11.
-template<class Key, class T,
- class Hash = BASE_HASH_NAMESPACE::hash<Key>,
- class Pred = std::equal_to<Key>,
- class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_map = BASE_HASH_IMPL_NAMESPACE::hash_map<Key, T, Hash, Pred, Alloc>;
-
-template<class Key, class T,
- class Hash = BASE_HASH_NAMESPACE::hash<Key>,
- class Pred = std::equal_to<Key>,
- class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_multimap =
- BASE_HASH_IMPL_NAMESPACE::hash_multimap<Key, T, Hash, Pred, Alloc>;
-
-template<class Key,
- class Hash = BASE_HASH_NAMESPACE::hash<Key>,
- class Pred = std::equal_to<Key>,
- class Alloc = std::allocator<Key>>
-using hash_multiset =
- BASE_HASH_IMPL_NAMESPACE::hash_multiset<Key, Hash, Pred, Alloc>;
-
-template<class Key,
- class Hash = BASE_HASH_NAMESPACE::hash<Key>,
- class Pred = std::equal_to<Key>,
- class Alloc = std::allocator<Key>>
-using hash_set = BASE_HASH_IMPL_NAMESPACE::hash_set<Key, Hash, Pred, Alloc>;
-
-#undef BASE_HASH_IMPL_NAMESPACE
-
-#endif // COMPILER_MSVC
-
-// Implement hashing for pairs of at-most 32 bit integer values.
-// When size_t is 32 bits, we turn the 64-bit hash code into 32 bits by using
-// multiply-add hashing. This algorithm, as described in
-// Theorem 4.3.3 of the thesis "Über die Komplexität der Multiplikation in
-// eingeschränkten Branchingprogrammmodellen" by Woelfel, is:
-//
-// h32(x32, y32) = (h64(x32, y32) * rand_odd64 + rand16 * 2^16) % 2^64 / 2^32
-//
-// Contact danakj@chromium.org for any questions.
-inline std::size_t HashInts32(uint32_t value1, uint32_t value2) {
- uint64_t value1_64 = value1;
- uint64_t hash64 = (value1_64 << 32) | value2;
-
- if (sizeof(std::size_t) >= sizeof(uint64_t))
- return static_cast<std::size_t>(hash64);
-
- uint64_t odd_random = 481046412LL << 32 | 1025306955LL;
- uint32_t shift_random = 10121U << 16;
-
- hash64 = hash64 * odd_random + shift_random;
- std::size_t high_bits = static_cast<std::size_t>(
- hash64 >> (8 * (sizeof(uint64_t) - sizeof(std::size_t))));
- return high_bits;
-}
-
-// Implement hashing for pairs of up-to 64-bit integer values.
-// We use the compound integer hash method to produce a 64-bit hash code, by
-// breaking the two 64-bit inputs into 4 32-bit values:
-// http://opendatastructures.org/versions/edition-0.1d/ods-java/node33.html#SECTION00832000000000000000
-// Then we reduce our result to 32 bits if required, similar to above.
-inline std::size_t HashInts64(uint64_t value1, uint64_t value2) {
- uint32_t short_random1 = 842304669U;
- uint32_t short_random2 = 619063811U;
- uint32_t short_random3 = 937041849U;
- uint32_t short_random4 = 3309708029U;
-
- uint32_t value1a = static_cast<uint32_t>(value1 & 0xffffffff);
- uint32_t value1b = static_cast<uint32_t>((value1 >> 32) & 0xffffffff);
- uint32_t value2a = static_cast<uint32_t>(value2 & 0xffffffff);
- uint32_t value2b = static_cast<uint32_t>((value2 >> 32) & 0xffffffff);
-
- uint64_t product1 = static_cast<uint64_t>(value1a) * short_random1;
- uint64_t product2 = static_cast<uint64_t>(value1b) * short_random2;
- uint64_t product3 = static_cast<uint64_t>(value2a) * short_random3;
- uint64_t product4 = static_cast<uint64_t>(value2b) * short_random4;
-
- uint64_t hash64 = product1 + product2 + product3 + product4;
-
- if (sizeof(std::size_t) >= sizeof(uint64_t))
- return static_cast<std::size_t>(hash64);
-
- uint64_t odd_random = 1578233944LL << 32 | 194370989LL;
- uint32_t shift_random = 20591U << 16;
-
- hash64 = hash64 * odd_random + shift_random;
- std::size_t high_bits = static_cast<std::size_t>(
- hash64 >> (8 * (sizeof(uint64_t) - sizeof(std::size_t))));
- return high_bits;
-}
-
-template<typename T1, typename T2>
-inline std::size_t HashPair(T1 value1, T2 value2) {
- // This condition is expected to be compile-time evaluated and optimised away
- // in release builds.
- if (sizeof(T1) > sizeof(uint32_t) || (sizeof(T2) > sizeof(uint32_t)))
- return HashInts64(value1, value2);
-
- return HashInts32(value1, value2);
-}
-
-} // namespace base
-
-namespace BASE_HASH_NAMESPACE {
-
-// Implement methods for hashing a pair of integers, so they can be used as
-// keys in STL containers.
-
-template<typename Type1, typename Type2>
-struct hash<std::pair<Type1, Type2> > {
- std::size_t operator()(std::pair<Type1, Type2> value) const {
- return base::HashPair(value.first, value.second);
- }
-};
-
-} // namespace BASE_HASH_NAMESPACE
-
-#undef DEFINE_PAIR_HASH_FUNCTION_START
-#undef DEFINE_PAIR_HASH_FUNCTION_END
-
-#endif // BASE_CONTAINERS_HASH_TABLES_H_
diff --git a/security/sandbox/chromium/base/cpu.cc b/security/sandbox/chromium/base/cpu.cc
deleted file mode 100644
index 713544566..000000000
--- a/security/sandbox/chromium/base/cpu.cc
+++ /dev/null
@@ -1,296 +0,0 @@
-// 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.
-
-#include "base/cpu.h"
-
-#include <limits.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <algorithm>
-
-#include "base/macros.h"
-#include "base/strings/string_piece.h"
-#include "build/build_config.h"
-
-#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
-#include "base/files/file_util.h"
-#include "base/lazy_instance.h"
-#endif
-
-#if defined(ARCH_CPU_X86_FAMILY)
-#if defined(_MSC_VER)
-#include <intrin.h>
-#include <immintrin.h> // For _xgetbv()
-#endif
-#endif
-
-namespace base {
-
-CPU::CPU()
- : signature_(0),
- type_(0),
- family_(0),
- model_(0),
- stepping_(0),
- ext_model_(0),
- ext_family_(0),
- has_mmx_(false),
- has_sse_(false),
- has_sse2_(false),
- has_sse3_(false),
- has_ssse3_(false),
- has_sse41_(false),
- has_sse42_(false),
- has_avx_(false),
- has_avx2_(false),
- has_aesni_(false),
- has_non_stop_time_stamp_counter_(false),
- has_broken_neon_(false),
- cpu_vendor_("unknown") {
- Initialize();
-}
-
-namespace {
-
-#if defined(ARCH_CPU_X86_FAMILY)
-#ifndef _MSC_VER
-
-#if defined(__pic__) && defined(__i386__)
-
-void __cpuid(int cpu_info[4], int info_type) {
- __asm__ volatile (
- "mov %%ebx, %%edi\n"
- "cpuid\n"
- "xchg %%edi, %%ebx\n"
- : "=a"(cpu_info[0]), "=D"(cpu_info[1]), "=c"(cpu_info[2]), "=d"(cpu_info[3])
- : "a"(info_type)
- );
-}
-
-#else
-
-void __cpuid(int cpu_info[4], int info_type) {
- __asm__ volatile (
- "cpuid\n"
- : "=a"(cpu_info[0]), "=b"(cpu_info[1]), "=c"(cpu_info[2]), "=d"(cpu_info[3])
- : "a"(info_type)
- );
-}
-
-#endif
-
-// _xgetbv returns the value of an Intel Extended Control Register (XCR).
-// Currently only XCR0 is defined by Intel so |xcr| should always be zero.
-uint64_t _xgetbv(uint32_t xcr) {
- uint32_t eax, edx;
-
- __asm__ volatile (
- "xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
- return (static_cast<uint64_t>(edx) << 32) | eax;
-}
-
-#endif // !_MSC_VER
-#endif // ARCH_CPU_X86_FAMILY
-
-#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
-class LazyCpuInfoValue {
- public:
- LazyCpuInfoValue() : has_broken_neon_(false) {
- // This function finds the value from /proc/cpuinfo under the key "model
- // name" or "Processor". "model name" is used in Linux 3.8 and later (3.7
- // and later for arm64) and is shown once per CPU. "Processor" is used in
- // earler versions and is shown only once at the top of /proc/cpuinfo
- // regardless of the number CPUs.
- const char kModelNamePrefix[] = "model name\t: ";
- const char kProcessorPrefix[] = "Processor\t: ";
-
- // This function also calculates whether we believe that this CPU has a
- // broken NEON unit based on these fields from cpuinfo:
- unsigned implementer = 0, architecture = 0, variant = 0, part = 0,
- revision = 0;
- const struct {
- const char key[17];
- unsigned int* result;
- } kUnsignedValues[] = {
- {"CPU implementer", &implementer},
- {"CPU architecture", &architecture},
- {"CPU variant", &variant},
- {"CPU part", &part},
- {"CPU revision", &revision},
- };
-
- std::string contents;
- ReadFileToString(FilePath("/proc/cpuinfo"), &contents);
- DCHECK(!contents.empty());
- if (contents.empty()) {
- return;
- }
-
- std::istringstream iss(contents);
- std::string line;
- while (std::getline(iss, line)) {
- if (brand_.empty() &&
- (line.compare(0, strlen(kModelNamePrefix), kModelNamePrefix) == 0 ||
- line.compare(0, strlen(kProcessorPrefix), kProcessorPrefix) == 0)) {
- brand_.assign(line.substr(strlen(kModelNamePrefix)));
- }
-
- for (size_t i = 0; i < arraysize(kUnsignedValues); i++) {
- const char *key = kUnsignedValues[i].key;
- const size_t len = strlen(key);
-
- if (line.compare(0, len, key) == 0 &&
- line.size() >= len + 1 &&
- (line[len] == '\t' || line[len] == ' ' || line[len] == ':')) {
- size_t colon_pos = line.find(':', len);
- if (colon_pos == std::string::npos) {
- continue;
- }
-
- const StringPiece line_sp(line);
- StringPiece value_sp = line_sp.substr(colon_pos + 1);
- while (!value_sp.empty() &&
- (value_sp[0] == ' ' || value_sp[0] == '\t')) {
- value_sp = value_sp.substr(1);
- }
-
- // The string may have leading "0x" or not, so we use strtoul to
- // handle that.
- char* endptr;
- std::string value(value_sp.as_string());
- unsigned long int result = strtoul(value.c_str(), &endptr, 0);
- if (*endptr == 0 && result <= UINT_MAX) {
- *kUnsignedValues[i].result = result;
- }
- }
- }
- }
-
- has_broken_neon_ =
- implementer == 0x51 &&
- architecture == 7 &&
- variant == 1 &&
- part == 0x4d &&
- revision == 0;
- }
-
- const std::string& brand() const { return brand_; }
- bool has_broken_neon() const { return has_broken_neon_; }
-
- private:
- std::string brand_;
- bool has_broken_neon_;
- DISALLOW_COPY_AND_ASSIGN(LazyCpuInfoValue);
-};
-
-base::LazyInstance<LazyCpuInfoValue>::Leaky g_lazy_cpuinfo =
- LAZY_INSTANCE_INITIALIZER;
-
-#endif // defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) ||
- // defined(OS_LINUX))
-
-} // anonymous namespace
-
-void CPU::Initialize() {
-#if defined(ARCH_CPU_X86_FAMILY)
- int cpu_info[4] = {-1};
- char cpu_string[48];
-
- // __cpuid with an InfoType argument of 0 returns the number of
- // valid Ids in CPUInfo[0] and the CPU identification string in
- // the other three array elements. The CPU identification string is
- // not in linear order. The code below arranges the information
- // in a human readable form. The human readable order is CPUInfo[1] |
- // CPUInfo[3] | CPUInfo[2]. CPUInfo[2] and CPUInfo[3] are swapped
- // before using memcpy to copy these three array elements to cpu_string.
- __cpuid(cpu_info, 0);
- int num_ids = cpu_info[0];
- std::swap(cpu_info[2], cpu_info[3]);
- memcpy(cpu_string, &cpu_info[1], 3 * sizeof(cpu_info[1]));
- cpu_vendor_.assign(cpu_string, 3 * sizeof(cpu_info[1]));
-
- // Interpret CPU feature information.
- if (num_ids > 0) {
- int cpu_info7[4] = {0};
- __cpuid(cpu_info, 1);
- if (num_ids >= 7) {
- __cpuid(cpu_info7, 7);
- }
- signature_ = cpu_info[0];
- stepping_ = cpu_info[0] & 0xf;
- model_ = ((cpu_info[0] >> 4) & 0xf) + ((cpu_info[0] >> 12) & 0xf0);
- family_ = (cpu_info[0] >> 8) & 0xf;
- type_ = (cpu_info[0] >> 12) & 0x3;
- ext_model_ = (cpu_info[0] >> 16) & 0xf;
- ext_family_ = (cpu_info[0] >> 20) & 0xff;
- has_mmx_ = (cpu_info[3] & 0x00800000) != 0;
- has_sse_ = (cpu_info[3] & 0x02000000) != 0;
- has_sse2_ = (cpu_info[3] & 0x04000000) != 0;
- has_sse3_ = (cpu_info[2] & 0x00000001) != 0;
- has_ssse3_ = (cpu_info[2] & 0x00000200) != 0;
- has_sse41_ = (cpu_info[2] & 0x00080000) != 0;
- has_sse42_ = (cpu_info[2] & 0x00100000) != 0;
- // AVX instructions will generate an illegal instruction exception unless
- // a) they are supported by the CPU,
- // b) XSAVE is supported by the CPU and
- // c) XSAVE is enabled by the kernel.
- // See http://software.intel.com/en-us/blogs/2011/04/14/is-avx-enabled
- //
- // In addition, we have observed some crashes with the xgetbv instruction
- // even after following Intel's example code. (See crbug.com/375968.)
- // Because of that, we also test the XSAVE bit because its description in
- // the CPUID documentation suggests that it signals xgetbv support.
- has_avx_ =
- (cpu_info[2] & 0x10000000) != 0 &&
- (cpu_info[2] & 0x04000000) != 0 /* XSAVE */ &&
- (cpu_info[2] & 0x08000000) != 0 /* OSXSAVE */ &&
- (_xgetbv(0) & 6) == 6 /* XSAVE enabled by kernel */;
- has_aesni_ = (cpu_info[2] & 0x02000000) != 0;
- has_avx2_ = has_avx_ && (cpu_info7[1] & 0x00000020) != 0;
- }
-
- // Get the brand string of the cpu.
- __cpuid(cpu_info, 0x80000000);
- const int parameter_end = 0x80000004;
- int max_parameter = cpu_info[0];
-
- if (cpu_info[0] >= parameter_end) {
- char* cpu_string_ptr = cpu_string;
-
- for (int parameter = 0x80000002; parameter <= parameter_end &&
- cpu_string_ptr < &cpu_string[sizeof(cpu_string)]; parameter++) {
- __cpuid(cpu_info, parameter);
- memcpy(cpu_string_ptr, cpu_info, sizeof(cpu_info));
- cpu_string_ptr += sizeof(cpu_info);
- }
- cpu_brand_.assign(cpu_string, cpu_string_ptr - cpu_string);
- }
-
- const int parameter_containing_non_stop_time_stamp_counter = 0x80000007;
- if (max_parameter >= parameter_containing_non_stop_time_stamp_counter) {
- __cpuid(cpu_info, parameter_containing_non_stop_time_stamp_counter);
- has_non_stop_time_stamp_counter_ = (cpu_info[3] & (1 << 8)) != 0;
- }
-#elif defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
- cpu_brand_.assign(g_lazy_cpuinfo.Get().brand());
- has_broken_neon_ = g_lazy_cpuinfo.Get().has_broken_neon();
-#endif
-}
-
-CPU::IntelMicroArchitecture CPU::GetIntelMicroArchitecture() const {
- if (has_avx2()) return AVX2;
- if (has_avx()) return AVX;
- if (has_sse42()) return SSE42;
- if (has_sse41()) return SSE41;
- if (has_ssse3()) return SSSE3;
- if (has_sse3()) return SSE3;
- if (has_sse2()) return SSE2;
- if (has_sse()) return SSE;
- return PENTIUM;
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/cpu.h b/security/sandbox/chromium/base/cpu.h
deleted file mode 100644
index 8c3c06c04..000000000
--- a/security/sandbox/chromium/base/cpu.h
+++ /dev/null
@@ -1,92 +0,0 @@
-// 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.
-
-#ifndef BASE_CPU_H_
-#define BASE_CPU_H_
-
-#include <string>
-
-#include "base/base_export.h"
-
-namespace base {
-
-// Query information about the processor.
-class BASE_EXPORT CPU {
- public:
- // Constructor
- CPU();
-
- enum IntelMicroArchitecture {
- PENTIUM,
- SSE,
- SSE2,
- SSE3,
- SSSE3,
- SSE41,
- SSE42,
- AVX,
- AVX2,
- MAX_INTEL_MICRO_ARCHITECTURE
- };
-
- // Accessors for CPU information.
- const std::string& vendor_name() const { return cpu_vendor_; }
- int signature() const { return signature_; }
- int stepping() const { return stepping_; }
- int model() const { return model_; }
- int family() const { return family_; }
- int type() const { return type_; }
- int extended_model() const { return ext_model_; }
- int extended_family() const { return ext_family_; }
- bool has_mmx() const { return has_mmx_; }
- bool has_sse() const { return has_sse_; }
- bool has_sse2() const { return has_sse2_; }
- bool has_sse3() const { return has_sse3_; }
- bool has_ssse3() const { return has_ssse3_; }
- bool has_sse41() const { return has_sse41_; }
- bool has_sse42() const { return has_sse42_; }
- bool has_avx() const { return has_avx_; }
- bool has_avx2() const { return has_avx2_; }
- bool has_aesni() const { return has_aesni_; }
- bool has_non_stop_time_stamp_counter() const {
- return has_non_stop_time_stamp_counter_;
- }
- // has_broken_neon is only valid on ARM chips. If true, it indicates that we
- // believe that the NEON unit on the current CPU is flawed and cannot execute
- // some code. See https://code.google.com/p/chromium/issues/detail?id=341598
- bool has_broken_neon() const { return has_broken_neon_; }
-
- IntelMicroArchitecture GetIntelMicroArchitecture() const;
- const std::string& cpu_brand() const { return cpu_brand_; }
-
- private:
- // Query the processor for CPUID information.
- void Initialize();
-
- int signature_; // raw form of type, family, model, and stepping
- int type_; // process type
- int family_; // family of the processor
- int model_; // model of processor
- int stepping_; // processor revision number
- int ext_model_;
- int ext_family_;
- bool has_mmx_;
- bool has_sse_;
- bool has_sse2_;
- bool has_sse3_;
- bool has_ssse3_;
- bool has_sse41_;
- bool has_sse42_;
- bool has_avx_;
- bool has_avx2_;
- bool has_aesni_;
- bool has_non_stop_time_stamp_counter_;
- bool has_broken_neon_;
- std::string cpu_vendor_;
- std::string cpu_brand_;
-};
-
-} // namespace base
-
-#endif // BASE_CPU_H_
diff --git a/security/sandbox/chromium/base/debug/alias.cc b/security/sandbox/chromium/base/debug/alias.cc
deleted file mode 100644
index 6b0caaa6d..000000000
--- a/security/sandbox/chromium/base/debug/alias.cc
+++ /dev/null
@@ -1,23 +0,0 @@
-// 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/debug/alias.h"
-#include "build/build_config.h"
-
-namespace base {
-namespace debug {
-
-#if defined(COMPILER_MSVC)
-#pragma optimize("", off)
-#endif
-
-void Alias(const void* var) {
-}
-
-#if defined(COMPILER_MSVC)
-#pragma optimize("", on)
-#endif
-
-} // namespace debug
-} // namespace base
diff --git a/security/sandbox/chromium/base/debug/alias.h b/security/sandbox/chromium/base/debug/alias.h
deleted file mode 100644
index 3b2ab64f3..000000000
--- a/security/sandbox/chromium/base/debug/alias.h
+++ /dev/null
@@ -1,21 +0,0 @@
-// 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_DEBUG_ALIAS_H_
-#define BASE_DEBUG_ALIAS_H_
-
-#include "base/base_export.h"
-
-namespace base {
-namespace debug {
-
-// Make the optimizer think that var is aliased. This is to prevent it from
-// optimizing out variables that that would not otherwise be live at the point
-// of a potential crash.
-void BASE_EXPORT Alias(const void* var);
-
-} // namespace debug
-} // namespace base
-
-#endif // BASE_DEBUG_ALIAS_H_
diff --git a/security/sandbox/chromium/base/debug/debugger.h b/security/sandbox/chromium/base/debug/debugger.h
deleted file mode 100644
index 8680e281e..000000000
--- a/security/sandbox/chromium/base/debug/debugger.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// 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.
-
-// This is a cross platform interface for helper functions related to
-// debuggers. You should use this to test if you're running under a debugger,
-// and if you would like to yield (breakpoint) into the debugger.
-
-#ifndef BASE_DEBUG_DEBUGGER_H_
-#define BASE_DEBUG_DEBUGGER_H_
-
-#include "base/base_export.h"
-
-namespace base {
-namespace debug {
-
-// Waits wait_seconds seconds for a debugger to attach to the current process.
-// When silent is false, an exception is thrown when a debugger is detected.
-BASE_EXPORT bool WaitForDebugger(int wait_seconds, bool silent);
-
-// Returns true if the given process is being run under a debugger.
-//
-// On OS X, the underlying mechanism doesn't work when the sandbox is enabled.
-// To get around this, this function caches its value.
-//
-// WARNING: Because of this, on OS X, a call MUST be made to this function
-// BEFORE the sandbox is enabled.
-BASE_EXPORT bool BeingDebugged();
-
-// Break into the debugger, assumes a debugger is present.
-BASE_EXPORT void BreakDebugger();
-
-// Used in test code, this controls whether showing dialogs and breaking into
-// the debugger is suppressed for debug errors, even in debug mode (normally
-// release mode doesn't do this stuff -- this is controlled separately).
-// Normally UI is not suppressed. This is normally used when running automated
-// tests where we want a crash rather than a dialog or a debugger.
-BASE_EXPORT void SetSuppressDebugUI(bool suppress);
-BASE_EXPORT bool IsDebugUISuppressed();
-
-} // namespace debug
-} // namespace base
-
-#endif // BASE_DEBUG_DEBUGGER_H_
diff --git a/security/sandbox/chromium/base/debug/leak_annotations.h b/security/sandbox/chromium/base/debug/leak_annotations.h
deleted file mode 100644
index dc502461d..000000000
--- a/security/sandbox/chromium/base/debug/leak_annotations.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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_DEBUG_LEAK_ANNOTATIONS_H_
-#define BASE_DEBUG_LEAK_ANNOTATIONS_H_
-
-#include "base/macros.h"
-#include "build/build_config.h"
-
-// This file defines macros which can be used to annotate intentional memory
-// leaks. Support for annotations is implemented in LeakSanitizer. Annotated
-// objects will be treated as a source of live pointers, i.e. any heap objects
-// reachable by following pointers from an annotated object will not be
-// reported as leaks.
-//
-// ANNOTATE_SCOPED_MEMORY_LEAK: all allocations made in the current scope
-// will be annotated as leaks.
-// ANNOTATE_LEAKING_OBJECT_PTR(X): the heap object referenced by pointer X will
-// be annotated as a leak.
-
-#if defined(LEAK_SANITIZER) && !defined(OS_NACL)
-
-#include <sanitizer/lsan_interface.h>
-
-class ScopedLeakSanitizerDisabler {
- public:
- ScopedLeakSanitizerDisabler() { __lsan_disable(); }
- ~ScopedLeakSanitizerDisabler() { __lsan_enable(); }
- private:
- DISALLOW_COPY_AND_ASSIGN(ScopedLeakSanitizerDisabler);
-};
-
-#define ANNOTATE_SCOPED_MEMORY_LEAK \
- ScopedLeakSanitizerDisabler leak_sanitizer_disabler; static_cast<void>(0)
-
-#define ANNOTATE_LEAKING_OBJECT_PTR(X) __lsan_ignore_object(X);
-
-#else
-
-#define ANNOTATE_SCOPED_MEMORY_LEAK ((void)0)
-#define ANNOTATE_LEAKING_OBJECT_PTR(X) ((void)0)
-
-#endif
-
-#endif // BASE_DEBUG_LEAK_ANNOTATIONS_H_
diff --git a/security/sandbox/chromium/base/debug/profiler.cc b/security/sandbox/chromium/base/debug/profiler.cc
deleted file mode 100644
index 75e9aac0c..000000000
--- a/security/sandbox/chromium/base/debug/profiler.cc
+++ /dev/null
@@ -1,221 +0,0 @@
-// 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.
-
-#include "base/debug/profiler.h"
-
-#include <string>
-
-#include "base/debug/debugging_flags.h"
-#include "base/process/process_handle.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_util.h"
-#include "build/build_config.h"
-
-#if defined(OS_WIN)
-#include "base/win/pe_image.h"
-#endif // defined(OS_WIN)
-
-// TODO(peria): Enable profiling on Windows.
-#if BUILDFLAG(ENABLE_PROFILING) && !defined(NO_TCMALLOC) && !defined(OS_WIN)
-#include "third_party/tcmalloc/chromium/src/gperftools/profiler.h"
-#endif
-
-namespace base {
-namespace debug {
-
-// TODO(peria): Enable profiling on Windows.
-#if BUILDFLAG(ENABLE_PROFILING) && !defined(NO_TCMALLOC) && !defined(OS_WIN)
-
-static int profile_count = 0;
-
-void StartProfiling(const std::string& name) {
- ++profile_count;
- std::string full_name(name);
- std::string pid = IntToString(GetCurrentProcId());
- std::string count = IntToString(profile_count);
- ReplaceSubstringsAfterOffset(&full_name, 0, "{pid}", pid);
- ReplaceSubstringsAfterOffset(&full_name, 0, "{count}", count);
- ProfilerStart(full_name.c_str());
-}
-
-void StopProfiling() {
- ProfilerFlush();
- ProfilerStop();
-}
-
-void FlushProfiling() {
- ProfilerFlush();
-}
-
-bool BeingProfiled() {
- return ProfilingIsEnabledForAllThreads();
-}
-
-void RestartProfilingAfterFork() {
- ProfilerRegisterThread();
-}
-
-#else
-
-void StartProfiling(const std::string& name) {
-}
-
-void StopProfiling() {
-}
-
-void FlushProfiling() {
-}
-
-bool BeingProfiled() {
- return false;
-}
-
-void RestartProfilingAfterFork() {
-}
-
-#endif
-
-#if !defined(OS_WIN)
-
-bool IsBinaryInstrumented() {
- return false;
-}
-
-ReturnAddressLocationResolver GetProfilerReturnAddrResolutionFunc() {
- return NULL;
-}
-
-DynamicFunctionEntryHook GetProfilerDynamicFunctionEntryHookFunc() {
- return NULL;
-}
-
-AddDynamicSymbol GetProfilerAddDynamicSymbolFunc() {
- return NULL;
-}
-
-MoveDynamicSymbol GetProfilerMoveDynamicSymbolFunc() {
- return NULL;
-}
-
-#else // defined(OS_WIN)
-
-// http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
-extern "C" IMAGE_DOS_HEADER __ImageBase;
-
-bool IsBinaryInstrumented() {
- enum InstrumentationCheckState {
- UNINITIALIZED,
- INSTRUMENTED_IMAGE,
- NON_INSTRUMENTED_IMAGE,
- };
-
- static InstrumentationCheckState state = UNINITIALIZED;
-
- if (state == UNINITIALIZED) {
- HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase);
- base::win::PEImage image(this_module);
-
- // Check to be sure our image is structured as we'd expect.
- DCHECK(image.VerifyMagic());
-
- // Syzygy-instrumented binaries contain a PE image section named ".thunks",
- // and all Syzygy-modified binaries contain the ".syzygy" image section.
- // This is a very fast check, as it only looks at the image header.
- if ((image.GetImageSectionHeaderByName(".thunks") != NULL) &&
- (image.GetImageSectionHeaderByName(".syzygy") != NULL)) {
- state = INSTRUMENTED_IMAGE;
- } else {
- state = NON_INSTRUMENTED_IMAGE;
- }
- }
- DCHECK(state != UNINITIALIZED);
-
- return state == INSTRUMENTED_IMAGE;
-}
-
-namespace {
-
-struct FunctionSearchContext {
- const char* name;
- FARPROC function;
-};
-
-// Callback function to PEImage::EnumImportChunks.
-bool FindResolutionFunctionInImports(
- const base::win::PEImage &image, const char* module_name,
- PIMAGE_THUNK_DATA unused_name_table, PIMAGE_THUNK_DATA import_address_table,
- PVOID cookie) {
- FunctionSearchContext* context =
- reinterpret_cast<FunctionSearchContext*>(cookie);
-
- DCHECK_NE(static_cast<FunctionSearchContext*>(NULL), context);
- DCHECK_EQ(static_cast<FARPROC>(NULL), context->function);
-
- // Our import address table contains pointers to the functions we import
- // at this point. Let's retrieve the first such function and use it to
- // find the module this import was resolved to by the loader.
- const wchar_t* function_in_module =
- reinterpret_cast<const wchar_t*>(import_address_table->u1.Function);
-
- // Retrieve the module by a function in the module.
- const DWORD kFlags = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
- GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
- HMODULE module = NULL;
- if (!::GetModuleHandleEx(kFlags, function_in_module, &module)) {
- // This can happen if someone IAT patches us to a thunk.
- return true;
- }
-
- // See whether this module exports the function we're looking for.
- FARPROC exported_func = ::GetProcAddress(module, context->name);
- if (exported_func != NULL) {
- // We found it, return the function and terminate the enumeration.
- context->function = exported_func;
- return false;
- }
-
- // Keep going.
- return true;
-}
-
-template <typename FunctionType>
-FunctionType FindFunctionInImports(const char* function_name) {
- if (!IsBinaryInstrumented())
- return NULL;
-
- HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase);
- base::win::PEImage image(this_module);
-
- FunctionSearchContext ctx = { function_name, NULL };
- image.EnumImportChunks(FindResolutionFunctionInImports, &ctx);
-
- return reinterpret_cast<FunctionType>(ctx.function);
-}
-
-} // namespace
-
-ReturnAddressLocationResolver GetProfilerReturnAddrResolutionFunc() {
- return FindFunctionInImports<ReturnAddressLocationResolver>(
- "ResolveReturnAddressLocation");
-}
-
-DynamicFunctionEntryHook GetProfilerDynamicFunctionEntryHookFunc() {
- return FindFunctionInImports<DynamicFunctionEntryHook>(
- "OnDynamicFunctionEntry");
-}
-
-AddDynamicSymbol GetProfilerAddDynamicSymbolFunc() {
- return FindFunctionInImports<AddDynamicSymbol>(
- "AddDynamicSymbol");
-}
-
-MoveDynamicSymbol GetProfilerMoveDynamicSymbolFunc() {
- return FindFunctionInImports<MoveDynamicSymbol>(
- "MoveDynamicSymbol");
-}
-
-#endif // defined(OS_WIN)
-
-} // namespace debug
-} // namespace base
diff --git a/security/sandbox/chromium/base/debug/profiler.h b/security/sandbox/chromium/base/debug/profiler.h
deleted file mode 100644
index 7cce7b08f..000000000
--- a/security/sandbox/chromium/base/debug/profiler.h
+++ /dev/null
@@ -1,91 +0,0 @@
-// 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.
-
-#ifndef BASE_DEBUG_PROFILER_H_
-#define BASE_DEBUG_PROFILER_H_
-
-#include <stddef.h>
-
-#include <string>
-
-#include "base/base_export.h"
-
-// The Profiler functions allow usage of the underlying sampling based
-// profiler. If the application has not been built with the necessary
-// flags (-DENABLE_PROFILING and not -DNO_TCMALLOC) then these functions
-// are noops.
-namespace base {
-namespace debug {
-
-// Start profiling with the supplied name.
-// {pid} will be replaced by the process' pid and {count} will be replaced
-// by the count of the profile run (starts at 1 with each process).
-BASE_EXPORT void StartProfiling(const std::string& name);
-
-// Stop profiling and write out data.
-BASE_EXPORT void StopProfiling();
-
-// Force data to be written to file.
-BASE_EXPORT void FlushProfiling();
-
-// Returns true if process is being profiled.
-BASE_EXPORT bool BeingProfiled();
-
-// Reset profiling after a fork, which disables timers.
-BASE_EXPORT void RestartProfilingAfterFork();
-
-// Returns true iff this executable is instrumented with the Syzygy profiler.
-BASE_EXPORT bool IsBinaryInstrumented();
-
-// There's a class of profilers that use "return address swizzling" to get a
-// hook on function exits. This class of profilers uses some form of entry hook,
-// like e.g. binary instrumentation, or a compiler flag, that calls a hook each
-// time a function is invoked. The hook then switches the return address on the
-// stack for the address of an exit hook function, and pushes the original
-// return address to a shadow stack of some type. When in due course the CPU
-// executes a return to the exit hook, the exit hook will do whatever work it
-// does on function exit, then arrange to return to the original return address.
-// This class of profiler does not play well with programs that look at the
-// return address, as does e.g. V8. V8 uses the return address to certain
-// runtime functions to find the JIT code that called it, and from there finds
-// the V8 data structures associated to the JS function involved.
-// A return address resolution function is used to fix this. It allows such
-// programs to resolve a location on stack where a return address originally
-// resided, to the shadow stack location where the profiler stashed it.
-typedef uintptr_t (*ReturnAddressLocationResolver)(
- uintptr_t return_addr_location);
-
-// This type declaration must match V8's FunctionEntryHook.
-typedef void (*DynamicFunctionEntryHook)(uintptr_t function,
- uintptr_t return_addr_location);
-
-// The functions below here are to support profiling V8-generated code.
-// V8 has provisions for generating a call to an entry hook for newly generated
-// JIT code, and it can push symbol information on code generation and advise
-// when the garbage collector moves code. The functions declarations below here
-// make glue between V8's facilities and a profiler.
-
-// This type declaration must match V8's FunctionEntryHook.
-typedef void (*DynamicFunctionEntryHook)(uintptr_t function,
- uintptr_t return_addr_location);
-
-typedef void (*AddDynamicSymbol)(const void* address,
- size_t length,
- const char* name,
- size_t name_len);
-typedef void (*MoveDynamicSymbol)(const void* address, const void* new_address);
-
-
-// If this binary is instrumented and the instrumentation supplies a function
-// for each of those purposes, find and return the function in question.
-// Otherwise returns NULL.
-BASE_EXPORT ReturnAddressLocationResolver GetProfilerReturnAddrResolutionFunc();
-BASE_EXPORT DynamicFunctionEntryHook GetProfilerDynamicFunctionEntryHookFunc();
-BASE_EXPORT AddDynamicSymbol GetProfilerAddDynamicSymbolFunc();
-BASE_EXPORT MoveDynamicSymbol GetProfilerMoveDynamicSymbolFunc();
-
-} // namespace debug
-} // namespace base
-
-#endif // BASE_DEBUG_PROFILER_H_
diff --git a/security/sandbox/chromium/base/file_descriptor_posix.h b/security/sandbox/chromium/base/file_descriptor_posix.h
deleted file mode 100644
index 2a366116a..000000000
--- a/security/sandbox/chromium/base/file_descriptor_posix.h
+++ /dev/null
@@ -1,59 +0,0 @@
-// 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_FILE_DESCRIPTOR_POSIX_H_
-#define BASE_FILE_DESCRIPTOR_POSIX_H_
-
-#include "base/files/file.h"
-#include "base/files/scoped_file.h"
-
-namespace base {
-
-// -----------------------------------------------------------------------------
-// We introduct a special structure for file descriptors in order that we are
-// able to use template specialisation to special-case their handling.
-//
-// IMPORTANT: This is primarily intended for use when sending file descriptors
-// over IPC. Even if |auto_close| is true, base::FileDescriptor does NOT close()
-// |fd| when going out of scope. Instead, a consumer of a base::FileDescriptor
-// must invoke close() on |fd| if |auto_close| is true.
-//
-// In the case of IPC, the the IPC subsystem knows to close() |fd| after sending
-// a message that contains a base::FileDescriptor if auto_close == true. On the
-// other end, the receiver must make sure to close() |fd| after it has finished
-// processing the IPC message. See the IPC::ParamTraits<> specialization in
-// ipc/ipc_message_utils.h for all the details.
-// -----------------------------------------------------------------------------
-struct FileDescriptor {
- FileDescriptor() : fd(-1), auto_close(false) {}
-
- FileDescriptor(int ifd, bool iauto_close) : fd(ifd), auto_close(iauto_close) {
- }
-
- FileDescriptor(File file) : fd(file.TakePlatformFile()), auto_close(true) {}
- explicit FileDescriptor(ScopedFD fd) : fd(fd.release()), auto_close(true) {}
-
- bool operator==(const FileDescriptor& other) const {
- return (fd == other.fd && auto_close == other.auto_close);
- }
-
- bool operator!=(const FileDescriptor& other) const {
- return !operator==(other);
- }
-
- // A comparison operator so that we can use these as keys in a std::map.
- bool operator<(const FileDescriptor& other) const {
- return other.fd < fd;
- }
-
- int fd;
- // If true, this file descriptor should be closed after it has been used. For
- // example an IPC system might interpret this flag as indicating that the
- // file descriptor it has been given should be closed after use.
- bool auto_close;
-};
-
-} // namespace base
-
-#endif // BASE_FILE_DESCRIPTOR_POSIX_H_
diff --git a/security/sandbox/chromium/base/files/file_path.h b/security/sandbox/chromium/base/files/file_path.h
deleted file mode 100644
index 89e9cbfb1..000000000
--- a/security/sandbox/chromium/base/files/file_path.h
+++ /dev/null
@@ -1,477 +0,0 @@
-// 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.
-
-// 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.
-// Chrome OS also uses UTF-8.
-// Linux does not specify an encoding, but in practice, the locale's
-// character set may be used.
-//
-// For more arcane bits of path trivia, see below.
-//
-// 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.
-//
-// As a precaution against premature truncation, paths can't contain NULs.
-//
-// 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);
-// | [...]
-// | }
-//
-// WARNING: FilePaths should ALWAYS be displayed with LTR directionality, even
-// when the UI language is RTL. This means you always need to pass filepaths
-// through base::i18n::WrapPathWithLTRFormatting() before displaying it in the
-// RTL UI.
-//
-// This is a very common source of bugs, please try to keep this in mind.
-//
-// ARCANE BITS OF PATH TRIVIA
-//
-// - A double leading slash is actually part of the POSIX standard. Systems
-// are allowed to treat // as an alternate root, as Windows does for UNC
-// (network share) paths. Most POSIX systems don't do anything special
-// with two leading slashes, but FilePath handles this case properly
-// in case it ever comes across such a system. FilePath needs this support
-// for Windows UNC paths, anyway.
-// References:
-// The Open Group Base Specifications Issue 7, sections 3.267 ("Pathname")
-// and 4.12 ("Pathname Resolution"), available at:
-// http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267
-// http://www.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_12
-//
-// - Windows treats c:\\ the same way it treats \\. This was intended to
-// allow older applications that require drive letters to support UNC paths
-// like \\server\share\path, by permitting c:\\server\share\path as an
-// equivalent. Since the OS treats these paths specially, FilePath needs
-// to do the same. Since Windows can use either / or \ as the separator,
-// FilePath treats c://, c:\\, //, and \\ all equivalently.
-// Reference:
-// The Old New Thing, "Why is a drive letter permitted in front of UNC
-// paths (sometimes)?", available at:
-// http://blogs.msdn.com/oldnewthing/archive/2005/11/22/495740.aspx
-
-#ifndef BASE_FILES_FILE_PATH_H_
-#define BASE_FILES_FILE_PATH_H_
-
-#include <stddef.h>
-
-#include <iosfwd>
-#include <string>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/containers/hash_tables.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_piece.h"
-#include "build/build_config.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(OS_WIN)
-#define FILE_PATH_USES_DRIVE_LETTERS
-#define FILE_PATH_USES_WIN_SEPARATORS
-#endif // OS_WIN
-
-// To print path names portably use PRIsFP (based on PRIuS and friends from
-// C99 and format_macros.h) like this:
-// base::StringPrintf("Path is %" PRIsFP ".\n", path.value().c_str());
-#if defined(OS_POSIX)
-#define PRIsFP "s"
-#elif defined(OS_WIN)
-#define PRIsFP "ls"
-#endif // OS_WIN
-
-namespace base {
-
-class Pickle;
-class PickleIterator;
-
-// An abstraction to isolate users from the differences between native
-// pathnames on different platforms.
-class BASE_EXPORT FilePath {
- public:
-#if defined(OS_POSIX)
- // 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;
-#elif defined(OS_WIN)
- // On Windows, for Unicode-aware applications, native pathnames are wchar_t
- // arrays encoded in UTF-16.
- typedef std::wstring StringType;
-#endif // OS_WIN
-
- typedef BasicStringPiece<StringType> StringPieceType;
- 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[];
-
- // arraysize(kSeparators).
- static const size_t kSeparatorsLength;
-
- // 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);
- explicit FilePath(StringPieceType path);
- ~FilePath();
- FilePath& operator=(const FilePath& that);
-
- bool operator==(const FilePath& that) const;
-
- bool operator!=(const FilePath& that) const;
-
- // 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(); }
-
- void clear() { path_.clear(); }
-
- // Returns true if |character| is in kSeparators.
- static bool IsSeparator(CharType character);
-
- // Returns a vector of all of the components of the provided path. It is
- // equivalent to calling DirName().value() on the path's root component,
- // and BaseName().value() on each child component.
- //
- // To make sure this is lossless so we can differentiate absolute and
- // relative paths, the root slash will be included even though no other
- // slashes will be. The precise behavior is:
- //
- // Posix: "/foo/bar" -> [ "/", "foo", "bar" ]
- // Windows: "C:\foo\bar" -> [ "C:", "\\", "foo", "bar" ]
- void GetComponents(std::vector<FilePath::StringType>* components) const;
-
- // Returns true if this FilePath is a strict parent of the |child|. Absolute
- // and relative paths are accepted i.e. is /foo parent to /foo/bar and
- // is foo parent to foo/bar. Does not convert paths to absolute, follow
- // symlinks or directory navigation (e.g. ".."). A path is *NOT* its own
- // parent.
- bool IsParent(const FilePath& child) const;
-
- // If IsParent(child) holds, appends to path (if non-NULL) the
- // relative path to child and returns true. For example, if parent
- // holds "/Users/johndoe/Library/Application Support", child holds
- // "/Users/johndoe/Library/Application Support/Google/Chrome/Default", and
- // *path holds "/Users/johndoe/Library/Caches", then after
- // parent.AppendRelativePath(child, path) is called *path will hold
- // "/Users/johndoe/Library/Caches/Google/Chrome/Default". Otherwise,
- // returns false.
- bool AppendRelativePath(const FilePath& child, FilePath* path) const;
-
- // 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 WARN_UNUSED_RESULT;
-
- // 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 WARN_UNUSED_RESULT;
-
- // 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. For common double-extensions like .tar.gz and
- // .user.js, this method returns the combined extension. For a single
- // component, use FinalExtension().
- // 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 WARN_UNUSED_RESULT;
-
- // Returns the path's file extension, as in Extension(), but will
- // never return a double extension.
- //
- // TODO(davidben): Check all our extension-sensitive code to see if
- // we can rename this to Extension() and the other to something like
- // LongExtension(), defaulting to short extensions and leaving the
- // long "extensions" to logic like base::GetUniquePathNumber().
- StringType FinalExtension() const WARN_UNUSED_RESULT;
-
- // 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 WARN_UNUSED_RESULT;
-
- // Removes the path's file extension, as in RemoveExtension(), but
- // ignores double extensions.
- FilePath RemoveFinalExtension() const WARN_UNUSED_RESULT;
-
- // 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(
- StringPieceType suffix) const WARN_UNUSED_RESULT;
- FilePath InsertBeforeExtensionASCII(
- StringPiece suffix) const WARN_UNUSED_RESULT;
-
- // Adds |extension| to |file_name|. Returns the current FilePath if
- // |extension| is empty. Returns "" if BaseName() == "." or "..".
- FilePath AddExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
-
- // Replaces the extension of |file_name| with |extension|. If |file_name|
- // does not have an extension, then |extension| is added. If |extension| is
- // empty, then the extension is removed from |file_name|.
- // Returns "" if BaseName() == "." or "..".
- FilePath ReplaceExtension(StringPieceType extension) const WARN_UNUSED_RESULT;
-
- // Returns true if the file path matches the specified extension. The test is
- // case insensitive. Don't forget the leading period if appropriate.
- bool MatchesExtension(StringPieceType 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(StringPieceType 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(StringPiece 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 true if the patch ends with a path separator character.
- bool EndsWithSeparator() const WARN_UNUSED_RESULT;
-
- // Returns a copy of this FilePath that ends with a trailing separator. If
- // the input path is empty, an empty FilePath will be returned.
- FilePath AsEndingWithSeparator() const WARN_UNUSED_RESULT;
-
- // Returns a copy of this FilePath that does not end with a trailing
- // separator.
- FilePath StripTrailingSeparators() const WARN_UNUSED_RESULT;
-
- // Returns true if this FilePath contains an attempt to reference a parent
- // directory (e.g. has a path component that is "..").
- bool ReferencesParent() const;
-
- // Return a Unicode human-readable version of this path.
- // Warning: you can *not*, in general, go from a display name back to a real
- // path. Only use this when displaying paths to users, not just when you
- // want to stuff a string16 into some other API.
- string16 LossyDisplayName() const;
-
- // Return the path as ASCII, or the empty string if the path is not ASCII.
- // This should only be used for cases where the FilePath is representing a
- // known-ASCII filename.
- std::string MaybeAsASCII() const;
-
- // Return the path as UTF-8.
- //
- // This function is *unsafe* as there is no way to tell what encoding is
- // used in file names on POSIX systems other than Mac and Chrome OS,
- // although UTF-8 is practically used everywhere these days. To mitigate
- // the encoding issue, this function internally calls
- // SysNativeMBToWide() on POSIX systems other than Mac and Chrome OS,
- // per assumption that the current locale's encoding is used in file
- // names, but this isn't a perfect solution.
- //
- // Once it becomes safe to to stop caring about non-UTF-8 file names,
- // the SysNativeMBToWide() hack will be removed from the code, along
- // with "Unsafe" in the function name.
- std::string AsUTF8Unsafe() const;
-
- // Similar to AsUTF8Unsafe, but returns UTF-16 instead.
- string16 AsUTF16Unsafe() const;
-
- // Returns a FilePath object from a path name in UTF-8. This function
- // should only be used for cases where you are sure that the input
- // string is UTF-8.
- //
- // Like AsUTF8Unsafe(), this function is unsafe. This function
- // internally calls SysWideToNativeMB() on POSIX systems other than Mac
- // and Chrome OS, to mitigate the encoding issue. See the comment at
- // AsUTF8Unsafe() for details.
- static FilePath FromUTF8Unsafe(const std::string& utf8);
-
- // Similar to FromUTF8Unsafe, but accepts UTF-16 instead.
- static FilePath FromUTF16Unsafe(const string16& utf16);
-
- void WriteToPickle(Pickle* pickle) const;
- bool ReadFromPickle(PickleIterator* iter);
-
- // Normalize all path separators to backslash on Windows
- // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
- FilePath NormalizePathSeparators() const;
-
- // Normalize all path separattors to given type on Windows
- // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
- FilePath NormalizePathSeparatorsTo(CharType separator) const;
-
- // Compare two strings in the same way the file system does.
- // Note that these always ignore case, even on file systems that are case-
- // sensitive. If case-sensitive comparison is ever needed, add corresponding
- // methods here.
- // The methods are written as a static method so that they can also be used
- // on parts of a file path, e.g., just the extension.
- // CompareIgnoreCase() returns -1, 0 or 1 for less-than, equal-to and
- // greater-than respectively.
- static int CompareIgnoreCase(StringPieceType string1,
- StringPieceType string2);
- static bool CompareEqualIgnoreCase(StringPieceType string1,
- StringPieceType string2) {
- return CompareIgnoreCase(string1, string2) == 0;
- }
- static bool CompareLessIgnoreCase(StringPieceType string1,
- StringPieceType string2) {
- return CompareIgnoreCase(string1, string2) < 0;
- }
-
-#if defined(OS_MACOSX)
- // Returns the string in the special canonical decomposed form as defined for
- // HFS, which is close to, but not quite, decomposition form D. See
- // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#UnicodeSubtleties
- // for further comments.
- // Returns the epmty string if the conversion failed.
- static StringType GetHFSDecomposedForm(StringPieceType string);
-
- // Special UTF-8 version of FastUnicodeCompare. Cf:
- // http://developer.apple.com/mac/library/technotes/tn/tn1150.html#StringComparisonAlgorithm
- // IMPORTANT: The input strings must be in the special HFS decomposed form!
- // (cf. above GetHFSDecomposedForm method)
- static int HFSFastUnicodeCompare(StringPieceType string1,
- StringPieceType string2);
-#endif
-
-#if defined(OS_ANDROID)
- // On android, file selection dialog can return a file with content uri
- // scheme(starting with content://). Content uri needs to be opened with
- // ContentResolver to guarantee that the app has appropriate permissions
- // to access it.
- // Returns true if the path is a content uri, or false otherwise.
- bool IsContentUri() const;
-#endif
-
- 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_;
-};
-
-// This is required by googletest to print a readable output on test failures.
-// This is declared here for use in gtest-based unit tests but is defined in
-// the test_support_base target. Depend on that to use this in your unit test.
-// This should not be used in production code - call ToString() instead.
-void PrintTo(const FilePath& path, std::ostream* out);
-
-} // namespace base
-
-// Macros for string literal initialization of FilePath::CharType[], and for
-// using a FilePath::CharType[] in a printf-style format string.
-#if defined(OS_POSIX)
-#define FILE_PATH_LITERAL(x) x
-#define PRFilePath "s"
-#elif defined(OS_WIN)
-#define FILE_PATH_LITERAL(x) L ## x
-#define PRFilePath "ls"
-#endif // OS_WIN
-
-// Provide a hash function so that hash_sets and maps can contain FilePath
-// objects.
-namespace BASE_HASH_NAMESPACE {
-
-template<>
-struct hash<base::FilePath> {
- size_t operator()(const base::FilePath& f) const {
- return hash<base::FilePath::StringType>()(f.value());
- }
-};
-
-} // namespace BASE_HASH_NAMESPACE
-
-#endif // BASE_FILES_FILE_PATH_H_
diff --git a/security/sandbox/chromium/base/guid.h b/security/sandbox/chromium/base/guid.h
deleted file mode 100644
index c0a06f885..000000000
--- a/security/sandbox/chromium/base/guid.h
+++ /dev/null
@@ -1,33 +0,0 @@
-// 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.
-
-#ifndef BASE_GUID_H_
-#define BASE_GUID_H_
-
-#include <stdint.h>
-
-#include <string>
-
-#include "base/base_export.h"
-#include "build/build_config.h"
-
-namespace base {
-
-// Generate a 128-bit random GUID of the form: "%08X-%04X-%04X-%04X-%012llX".
-// If GUID generation fails an empty string is returned.
-// The POSIX implementation uses pseudo random number generation to create
-// the GUID. The Windows implementation uses system services.
-BASE_EXPORT std::string GenerateGUID();
-
-// Returns true if the input string conforms to the GUID format.
-BASE_EXPORT bool IsValidGUID(const std::string& guid);
-
-#if defined(OS_POSIX)
-// For unit testing purposes only. Do not use outside of tests.
-BASE_EXPORT std::string RandomDataToGUIDString(const uint64_t bytes[2]);
-#endif
-
-} // namespace base
-
-#endif // BASE_GUID_H_
diff --git a/security/sandbox/chromium/base/hash.cc b/security/sandbox/chromium/base/hash.cc
deleted file mode 100644
index d3206f6a6..000000000
--- a/security/sandbox/chromium/base/hash.cc
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2014 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/hash.h"
-
-// Definition in base/third_party/superfasthash/superfasthash.c. (Third-party
-// code did not come with its own header file, so declaring the function here.)
-// Note: This algorithm is also in Blink under Source/wtf/StringHasher.h.
-extern "C" uint32_t SuperFastHash(const char* data, int len);
-
-namespace base {
-
-uint32_t SuperFastHash(const char* data, int len) {
- return ::SuperFastHash(data, len);
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/hash.h b/security/sandbox/chromium/base/hash.h
deleted file mode 100644
index ed8d9fd4c..000000000
--- a/security/sandbox/chromium/base/hash.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// 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_HASH_H_
-#define BASE_HASH_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <limits>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/logging.h"
-
-namespace base {
-
-// WARNING: This hash function should not be used for any cryptographic purpose.
-BASE_EXPORT uint32_t SuperFastHash(const char* data, int len);
-
-// Computes a hash of a memory buffer |data| of a given |length|.
-// WARNING: This hash function should not be used for any cryptographic purpose.
-inline uint32_t Hash(const char* data, size_t length) {
- if (length > static_cast<size_t>(std::numeric_limits<int>::max())) {
- NOTREACHED();
- return 0;
- }
- return SuperFastHash(data, static_cast<int>(length));
-}
-
-// Computes a hash of a string |str|.
-// WARNING: This hash function should not be used for any cryptographic purpose.
-inline uint32_t Hash(const std::string& str) {
- return Hash(str.data(), str.size());
-}
-
-} // namespace base
-
-#endif // BASE_HASH_H_
diff --git a/security/sandbox/chromium/base/lazy_instance.cc b/security/sandbox/chromium/base/lazy_instance.cc
deleted file mode 100644
index 54680655a..000000000
--- a/security/sandbox/chromium/base/lazy_instance.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-// 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/lazy_instance.h"
-
-#include "base/at_exit.h"
-#include "base/atomicops.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-namespace internal {
-
-// TODO(joth): This function could be shared with Singleton, in place of its
-// WaitForInstance() call.
-bool NeedsLazyInstance(subtle::AtomicWord* state) {
- // Try to create the instance, if we're the first, will go from 0 to
- // kLazyInstanceStateCreating, otherwise we've already been beaten here.
- // The memory access has no memory ordering as state 0 and
- // kLazyInstanceStateCreating have no associated data (memory barriers are
- // all about ordering of memory accesses to *associated* data).
- if (subtle::NoBarrier_CompareAndSwap(state, 0,
- kLazyInstanceStateCreating) == 0)
- // Caller must create instance
- return true;
-
- // It's either in the process of being created, or already created. Spin.
- // The load has acquire memory ordering as a thread which sees
- // state_ == STATE_CREATED needs to acquire visibility over
- // the associated data (buf_). Pairing Release_Store is in
- // CompleteLazyInstance().
- while (subtle::Acquire_Load(state) == kLazyInstanceStateCreating) {
- PlatformThread::YieldCurrentThread();
- }
- // Someone else created the instance.
- return false;
-}
-
-void CompleteLazyInstance(subtle::AtomicWord* state,
- subtle::AtomicWord new_instance,
- void* lazy_instance,
- void (*dtor)(void*)) {
- // Instance is created, go from CREATING to CREATED.
- // Releases visibility over private_buf_ to readers. Pairing Acquire_Load's
- // are in NeedsInstance() and Pointer().
- subtle::Release_Store(state, new_instance);
-
- // Make sure that the lazily instantiated object will get destroyed at exit.
- if (dtor)
- AtExitManager::RegisterCallback(dtor, lazy_instance);
-}
-
-} // namespace internal
-} // namespace base
diff --git a/security/sandbox/chromium/base/lazy_instance.h b/security/sandbox/chromium/base/lazy_instance.h
deleted file mode 100644
index fd0321017..000000000
--- a/security/sandbox/chromium/base/lazy_instance.h
+++ /dev/null
@@ -1,207 +0,0 @@
-// 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.
-
-// The LazyInstance<Type, Traits> class manages a single instance of Type,
-// which will be lazily created on the first time it's accessed. This class is
-// useful for places you would normally use a function-level static, but you
-// need to have guaranteed thread-safety. The Type constructor will only ever
-// be called once, even if two threads are racing to create the object. Get()
-// and Pointer() will always return the same, completely initialized instance.
-// When the instance is constructed it is registered with AtExitManager. The
-// destructor will be called on program exit.
-//
-// LazyInstance is completely thread safe, assuming that you create it safely.
-// The class was designed to be POD initialized, so it shouldn't require a
-// static constructor. It really only makes sense to declare a LazyInstance as
-// a global variable using the LAZY_INSTANCE_INITIALIZER initializer.
-//
-// LazyInstance is similar to Singleton, except it does not have the singleton
-// property. You can have multiple LazyInstance's of the same type, and each
-// will manage a unique instance. It also preallocates the space for Type, as
-// to avoid allocating the Type instance on the heap. This may help with the
-// performance of creating the instance, and reducing heap fragmentation. This
-// requires that Type be a complete type so we can determine the size.
-//
-// Example usage:
-// static LazyInstance<MyClass> my_instance = LAZY_INSTANCE_INITIALIZER;
-// void SomeMethod() {
-// my_instance.Get().SomeMethod(); // MyClass::SomeMethod()
-//
-// MyClass* ptr = my_instance.Pointer();
-// ptr->DoDoDo(); // MyClass::DoDoDo
-// }
-
-#ifndef BASE_LAZY_INSTANCE_H_
-#define BASE_LAZY_INSTANCE_H_
-
-#include <new> // For placement new.
-
-#include "base/atomicops.h"
-#include "base/base_export.h"
-#include "base/debug/leak_annotations.h"
-#include "base/logging.h"
-#include "base/memory/aligned_memory.h"
-#include "base/threading/thread_restrictions.h"
-
-// LazyInstance uses its own struct initializer-list style static
-// initialization, as base's LINKER_INITIALIZED requires a constructor and on
-// some compilers (notably gcc 4.4) this still ends up needing runtime
-// initialization.
-#define LAZY_INSTANCE_INITIALIZER {0}
-
-namespace base {
-
-template <typename Type>
-struct DefaultLazyInstanceTraits {
- static const bool kRegisterOnExit = true;
-#ifndef NDEBUG
- static const bool kAllowedToAccessOnNonjoinableThread = false;
-#endif
-
- static Type* New(void* instance) {
- DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u)
- << ": Bad boy, the buffer passed to placement new is not aligned!\n"
- "This may break some stuff like SSE-based optimizations assuming the "
- "<Type> objects are word aligned.";
- // Use placement new to initialize our instance in our preallocated space.
- // The parenthesis is very important here to force POD type initialization.
- return new (instance) Type();
- }
- static void Delete(Type* instance) {
- // Explicitly call the destructor.
- instance->~Type();
- }
-};
-
-// We pull out some of the functionality into non-templated functions, so we
-// can implement the more complicated pieces out of line in the .cc file.
-namespace internal {
-
-// Use LazyInstance<T>::Leaky for a less-verbose call-site typedef; e.g.:
-// base::LazyInstance<T>::Leaky my_leaky_lazy_instance;
-// instead of:
-// base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
-// my_leaky_lazy_instance;
-// (especially when T is MyLongTypeNameImplClientHolderFactory).
-// Only use this internal::-qualified verbose form to extend this traits class
-// (depending on its implementation details).
-template <typename Type>
-struct LeakyLazyInstanceTraits {
- static const bool kRegisterOnExit = false;
-#ifndef NDEBUG
- static const bool kAllowedToAccessOnNonjoinableThread = true;
-#endif
-
- static Type* New(void* instance) {
- ANNOTATE_SCOPED_MEMORY_LEAK;
- return DefaultLazyInstanceTraits<Type>::New(instance);
- }
- static void Delete(Type* instance) {
- }
-};
-
-// Our AtomicWord doubles as a spinlock, where a value of
-// kBeingCreatedMarker means the spinlock is being held for creation.
-static const subtle::AtomicWord kLazyInstanceStateCreating = 1;
-
-// Check if instance needs to be created. If so return true otherwise
-// if another thread has beat us, wait for instance to be created and
-// return false.
-BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
-
-// After creating an instance, call this to register the dtor to be called
-// at program exit and to update the atomic state to hold the |new_instance|
-BASE_EXPORT void CompleteLazyInstance(subtle::AtomicWord* state,
- subtle::AtomicWord new_instance,
- void* lazy_instance,
- void (*dtor)(void*));
-
-} // namespace internal
-
-template <typename Type, typename Traits = DefaultLazyInstanceTraits<Type> >
-class LazyInstance {
- public:
- // Do not define a destructor, as doing so makes LazyInstance a
- // non-POD-struct. We don't want that because then a static initializer will
- // be created to register the (empty) destructor with atexit() under MSVC, for
- // example. We handle destruction of the contained Type class explicitly via
- // the OnExit member function, where needed.
- // ~LazyInstance() {}
-
- // Convenience typedef to avoid having to repeat Type for leaky lazy
- // instances.
- typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type> > Leaky;
-
- Type& Get() {
- return *Pointer();
- }
-
- Type* Pointer() {
-#ifndef NDEBUG
- // Avoid making TLS lookup on release builds.
- if (!Traits::kAllowedToAccessOnNonjoinableThread)
- ThreadRestrictions::AssertSingletonAllowed();
-#endif
- // If any bit in the created mask is true, the instance has already been
- // fully constructed.
- static const subtle::AtomicWord kLazyInstanceCreatedMask =
- ~internal::kLazyInstanceStateCreating;
-
- // We will hopefully have fast access when the instance is already created.
- // Since a thread sees private_instance_ == 0 or kLazyInstanceStateCreating
- // at most once, the load is taken out of NeedsInstance() as a fast-path.
- // The load has acquire memory ordering as a thread which sees
- // private_instance_ > creating needs to acquire visibility over
- // the associated data (private_buf_). Pairing Release_Store is in
- // CompleteLazyInstance().
- subtle::AtomicWord value = subtle::Acquire_Load(&private_instance_);
- if (!(value & kLazyInstanceCreatedMask) &&
- internal::NeedsLazyInstance(&private_instance_)) {
- // Create the instance in the space provided by |private_buf_|.
- value = reinterpret_cast<subtle::AtomicWord>(
- Traits::New(private_buf_.void_data()));
- internal::CompleteLazyInstance(&private_instance_, value, this,
- Traits::kRegisterOnExit ? OnExit : NULL);
- }
- return instance();
- }
-
- bool operator==(Type* p) {
- switch (subtle::NoBarrier_Load(&private_instance_)) {
- case 0:
- return p == NULL;
- case internal::kLazyInstanceStateCreating:
- return static_cast<void*>(p) == private_buf_.void_data();
- default:
- return p == instance();
- }
- }
-
- // Effectively private: member data is only public to allow the linker to
- // statically initialize it and to maintain a POD class. DO NOT USE FROM
- // OUTSIDE THIS CLASS.
-
- subtle::AtomicWord private_instance_;
- // Preallocated space for the Type instance.
- base::AlignedMemory<sizeof(Type), ALIGNOF(Type)> private_buf_;
-
- private:
- Type* instance() {
- return reinterpret_cast<Type*>(subtle::NoBarrier_Load(&private_instance_));
- }
-
- // Adapter function for use with AtExit. This should be called single
- // threaded, so don't synchronize across threads.
- // Calling OnExit while the instance is in use by other threads is a mistake.
- static void OnExit(void* lazy_instance) {
- LazyInstance<Type, Traits>* me =
- reinterpret_cast<LazyInstance<Type, Traits>*>(lazy_instance);
- Traits::Delete(me->instance());
- subtle::NoBarrier_Store(&me->private_instance_, 0);
- }
-};
-
-} // namespace base
-
-#endif // BASE_LAZY_INSTANCE_H_
diff --git a/security/sandbox/chromium/base/location.cc b/security/sandbox/chromium/base/location.cc
deleted file mode 100644
index 1333e6ec4..000000000
--- a/security/sandbox/chromium/base/location.cc
+++ /dev/null
@@ -1,106 +0,0 @@
-// 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.
-
-#include "build/build_config.h"
-
-#if defined(COMPILER_MSVC)
-#include <intrin.h>
-#endif
-
-#include "base/location.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/stringprintf.h"
-
-namespace tracked_objects {
-
-Location::Location(const char* function_name,
- const char* file_name,
- int line_number,
- const void* program_counter)
- : function_name_(function_name),
- file_name_(file_name),
- line_number_(line_number),
- program_counter_(program_counter) {
-}
-
-Location::Location()
- : function_name_("Unknown"),
- file_name_("Unknown"),
- line_number_(-1),
- program_counter_(NULL) {
-}
-
-Location::Location(const Location& other)
- : function_name_(other.function_name_),
- file_name_(other.file_name_),
- line_number_(other.line_number_),
- program_counter_(other.program_counter_) {
-}
-
-std::string Location::ToString() const {
- return std::string(function_name_) + "@" + file_name_ + ":" +
- base::IntToString(line_number_);
-}
-
-void Location::Write(bool display_filename, bool display_function_name,
- std::string* output) const {
- base::StringAppendF(output, "%s[%d] ",
- display_filename ? file_name_ : "line",
- line_number_);
-
- if (display_function_name) {
- WriteFunctionName(output);
- output->push_back(' ');
- }
-}
-
-void Location::WriteFunctionName(std::string* output) const {
- // Translate "<" to "&lt;" for HTML safety.
- // TODO(jar): Support ASCII or html for logging in ASCII.
- for (const char *p = function_name_; *p; p++) {
- switch (*p) {
- case '<':
- output->append("&lt;");
- break;
-
- case '>':
- output->append("&gt;");
- break;
-
- default:
- output->push_back(*p);
- break;
- }
- }
-}
-
-//------------------------------------------------------------------------------
-LocationSnapshot::LocationSnapshot() : line_number(-1) {
-}
-
-LocationSnapshot::LocationSnapshot(
- const tracked_objects::Location& location)
- : file_name(location.file_name()),
- function_name(location.function_name()),
- line_number(location.line_number()) {
-}
-
-LocationSnapshot::~LocationSnapshot() {
-}
-
-//------------------------------------------------------------------------------
-#if defined(COMPILER_MSVC)
-__declspec(noinline)
-#endif
-BASE_EXPORT const void* GetProgramCounter() {
-#if defined(COMPILER_MSVC)
- return _ReturnAddress();
-#elif defined(COMPILER_GCC) && !defined(OS_NACL)
- return __builtin_extract_return_addr(__builtin_return_address(0));
-#else
- return NULL;
-#endif
-}
-
-} // namespace tracked_objects
diff --git a/security/sandbox/chromium/base/location.h b/security/sandbox/chromium/base/location.h
deleted file mode 100644
index d3bb23c63..000000000
--- a/security/sandbox/chromium/base/location.h
+++ /dev/null
@@ -1,110 +0,0 @@
-// 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.
-
-#ifndef BASE_LOCATION_H_
-#define BASE_LOCATION_H_
-
-#include <stddef.h>
-
-#include <cassert>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/containers/hash_tables.h"
-
-namespace tracked_objects {
-
-// Location provides basic info where of an object was constructed, or was
-// significantly brought to life.
-class BASE_EXPORT Location {
- public:
- // Constructor should be called with a long-lived char*, such as __FILE__.
- // It assumes the provided value will persist as a global constant, and it
- // will not make a copy of it.
- Location(const char* function_name,
- const char* file_name,
- int line_number,
- const void* program_counter);
-
- // Provide a default constructor for easy of debugging.
- Location();
-
- // Copy constructor.
- Location(const Location& other);
-
- // Comparator for hash map insertion.
- // No need to use |function_name_| since the other two fields uniquely
- // identify this location.
- bool operator==(const Location& other) const {
- return line_number_ == other.line_number_ &&
- file_name_ == other.file_name_;
- }
-
- const char* function_name() const { return function_name_; }
- const char* file_name() const { return file_name_; }
- int line_number() const { return line_number_; }
- const void* program_counter() const { return program_counter_; }
-
- std::string ToString() const;
-
- // Hash operator for hash maps.
- struct Hash {
- size_t operator()(const Location& location) const {
- // Compute the hash value using file name pointer and line number.
- // No need to use |function_name_| since the other two fields uniquely
- // identify this location.
-
- // The file name will always be uniquely identified by its pointer since
- // it comes from __FILE__, so no need to check the contents of the string.
- // See the definition of FROM_HERE in location.h, and how it is used
- // elsewhere.
- return base::HashPair(reinterpret_cast<uintptr_t>(location.file_name()),
- location.line_number());
- }
- };
-
- // Translate the some of the state in this instance into a human readable
- // string with HTML characters in the function names escaped, and append that
- // string to |output|. Inclusion of the file_name_ and function_name_ are
- // optional, and controlled by the boolean arguments.
- void Write(bool display_filename, bool display_function_name,
- std::string* output) const;
-
- // Write function_name_ in HTML with '<' and '>' properly encoded.
- void WriteFunctionName(std::string* output) const;
-
- private:
- const char* function_name_;
- const char* file_name_;
- int line_number_;
- const void* program_counter_;
-};
-
-// A "snapshotted" representation of the Location class that can safely be
-// passed across process boundaries.
-struct BASE_EXPORT LocationSnapshot {
- // The default constructor is exposed to support the IPC serialization macros.
- LocationSnapshot();
- explicit LocationSnapshot(const tracked_objects::Location& location);
- ~LocationSnapshot();
-
- std::string file_name;
- std::string function_name;
- int line_number;
-};
-
-BASE_EXPORT const void* GetProgramCounter();
-
-// Define a macro to record the current source location.
-#define FROM_HERE FROM_HERE_WITH_EXPLICIT_FUNCTION(__FUNCTION__)
-
-#define FROM_HERE_WITH_EXPLICIT_FUNCTION(function_name) \
- ::tracked_objects::Location(function_name, \
- __FILE__, \
- __LINE__, \
- ::tracked_objects::GetProgramCounter())
-
-} // namespace tracked_objects
-
-#endif // BASE_LOCATION_H_
diff --git a/security/sandbox/chromium/base/logging.h b/security/sandbox/chromium/base/logging.h
deleted file mode 100644
index 300c9b526..000000000
--- a/security/sandbox/chromium/base/logging.h
+++ /dev/null
@@ -1,976 +0,0 @@
-// 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.
-
-#ifndef BASE_LOGGING_H_
-#define BASE_LOGGING_H_
-
-#include <stddef.h>
-
-#include <cassert>
-#include <cstring>
-#include <sstream>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/debug/debugger.h"
-#include "base/macros.h"
-#include "build/build_config.h"
-
-//
-// Optional message capabilities
-// -----------------------------
-// Assertion failed messages and fatal errors are displayed in a dialog box
-// before the application exits. However, running this UI creates a message
-// loop, which causes application messages to be processed and potentially
-// dispatched to existing application windows. Since the application is in a
-// bad state when this assertion dialog is displayed, these messages may not
-// get processed and hang the dialog, or the application might go crazy.
-//
-// Therefore, it can be beneficial to display the error dialog in a separate
-// process from the main application. When the logging system needs to display
-// a fatal error dialog box, it will look for a program called
-// "DebugMessage.exe" in the same directory as the application executable. It
-// will run this application with the message as the command line, and will
-// not include the name of the application as is traditional for easier
-// parsing.
-//
-// The code for DebugMessage.exe is only one line. In WinMain, do:
-// MessageBox(NULL, GetCommandLineW(), L"Fatal Error", 0);
-//
-// If DebugMessage.exe is not found, the logging code will use a normal
-// MessageBox, potentially causing the problems discussed above.
-
-
-// Instructions
-// ------------
-//
-// Make a bunch of macros for logging. The way to log things is to stream
-// things to LOG(<a particular severity level>). E.g.,
-//
-// LOG(INFO) << "Found " << num_cookies << " cookies";
-//
-// You can also do conditional logging:
-//
-// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
-//
-// The CHECK(condition) macro is active in both debug and release builds and
-// effectively performs a LOG(FATAL) which terminates the process and
-// generates a crashdump unless a debugger is attached.
-//
-// There are also "debug mode" logging macros like the ones above:
-//
-// DLOG(INFO) << "Found cookies";
-//
-// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
-//
-// All "debug mode" logging is compiled away to nothing for non-debug mode
-// compiles. LOG_IF and development flags also work well together
-// because the code can be compiled away sometimes.
-//
-// We also have
-//
-// LOG_ASSERT(assertion);
-// DLOG_ASSERT(assertion);
-//
-// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
-//
-// There are "verbose level" logging macros. They look like
-//
-// VLOG(1) << "I'm printed when you run the program with --v=1 or more";
-// VLOG(2) << "I'm printed when you run the program with --v=2 or more";
-//
-// These always log at the INFO log level (when they log at all).
-// The verbose logging can also be turned on module-by-module. For instance,
-// --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0
-// will cause:
-// a. VLOG(2) and lower messages to be printed from profile.{h,cc}
-// b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc}
-// c. VLOG(3) and lower messages to be printed from files prefixed with
-// "browser"
-// d. VLOG(4) and lower messages to be printed from files under a
-// "chromeos" directory.
-// e. VLOG(0) and lower messages to be printed from elsewhere
-//
-// The wildcarding functionality shown by (c) supports both '*' (match
-// 0 or more characters) and '?' (match any single character)
-// wildcards. Any pattern containing a forward or backward slash will
-// be tested against the whole pathname and not just the module.
-// E.g., "*/foo/bar/*=2" would change the logging level for all code
-// in source files under a "foo/bar" directory.
-//
-// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
-//
-// if (VLOG_IS_ON(2)) {
-// // do some logging preparation and logging
-// // that can't be accomplished with just VLOG(2) << ...;
-// }
-//
-// There is also a VLOG_IF "verbose level" condition macro for sample
-// cases, when some extra computation and preparation for logs is not
-// needed.
-//
-// VLOG_IF(1, (size > 1024))
-// << "I'm printed when size is more than 1024 and when you run the "
-// "program with --v=1 or more";
-//
-// We also override the standard 'assert' to use 'DLOG_ASSERT'.
-//
-// Lastly, there is:
-//
-// PLOG(ERROR) << "Couldn't do foo";
-// DPLOG(ERROR) << "Couldn't do foo";
-// PLOG_IF(ERROR, cond) << "Couldn't do foo";
-// DPLOG_IF(ERROR, cond) << "Couldn't do foo";
-// PCHECK(condition) << "Couldn't do foo";
-// DPCHECK(condition) << "Couldn't do foo";
-//
-// which append the last system error to the message in string form (taken from
-// GetLastError() on Windows and errno on POSIX).
-//
-// The supported severity levels for macros that allow you to specify one
-// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
-//
-// Very important: logging a message at the FATAL severity level causes
-// the program to terminate (after the message is logged).
-//
-// There is the special severity of DFATAL, which logs FATAL in debug mode,
-// ERROR in normal mode.
-
-namespace logging {
-
-// TODO(avi): do we want to do a unification of character types here?
-#if defined(OS_WIN)
-typedef wchar_t PathChar;
-#else
-typedef char PathChar;
-#endif
-
-// Where to record logging output? A flat file and/or system debug log
-// via OutputDebugString.
-enum LoggingDestination {
- LOG_NONE = 0,
- LOG_TO_FILE = 1 << 0,
- LOG_TO_SYSTEM_DEBUG_LOG = 1 << 1,
-
- LOG_TO_ALL = LOG_TO_FILE | LOG_TO_SYSTEM_DEBUG_LOG,
-
- // On Windows, use a file next to the exe; on POSIX platforms, where
- // it may not even be possible to locate the executable on disk, use
- // stderr.
-#if defined(OS_WIN)
- LOG_DEFAULT = LOG_TO_FILE,
-#elif defined(OS_POSIX)
- LOG_DEFAULT = LOG_TO_SYSTEM_DEBUG_LOG,
-#endif
-};
-
-// Indicates that the log file should be locked when being written to.
-// Unless there is only one single-threaded process that is logging to
-// the log file, the file should be locked during writes to make each
-// log output atomic. Other writers will block.
-//
-// All processes writing to the log file must have their locking set for it to
-// work properly. Defaults to LOCK_LOG_FILE.
-enum LogLockingState { LOCK_LOG_FILE, DONT_LOCK_LOG_FILE };
-
-// On startup, should we delete or append to an existing log file (if any)?
-// Defaults to APPEND_TO_OLD_LOG_FILE.
-enum OldFileDeletionState { DELETE_OLD_LOG_FILE, APPEND_TO_OLD_LOG_FILE };
-
-struct BASE_EXPORT LoggingSettings {
- // The defaults values are:
- //
- // logging_dest: LOG_DEFAULT
- // log_file: NULL
- // lock_log: LOCK_LOG_FILE
- // delete_old: APPEND_TO_OLD_LOG_FILE
- LoggingSettings();
-
- LoggingDestination logging_dest;
-
- // The three settings below have an effect only when LOG_TO_FILE is
- // set in |logging_dest|.
- const PathChar* log_file;
- LogLockingState lock_log;
- OldFileDeletionState delete_old;
-};
-
-// Define different names for the BaseInitLoggingImpl() function depending on
-// whether NDEBUG is defined or not so that we'll fail to link if someone tries
-// to compile logging.cc with NDEBUG but includes logging.h without defining it,
-// or vice versa.
-#if NDEBUG
-#define BaseInitLoggingImpl BaseInitLoggingImpl_built_with_NDEBUG
-#else
-#define BaseInitLoggingImpl BaseInitLoggingImpl_built_without_NDEBUG
-#endif
-
-// Implementation of the InitLogging() method declared below. We use a
-// more-specific name so we can #define it above without affecting other code
-// that has named stuff "InitLogging".
-BASE_EXPORT bool BaseInitLoggingImpl(const LoggingSettings& settings);
-
-// Sets the log file name and other global logging state. Calling this function
-// is recommended, and is normally done at the beginning of application init.
-// If you don't call it, all the flags will be initialized to their default
-// values, and there is a race condition that may leak a critical section
-// object if two threads try to do the first log at the same time.
-// See the definition of the enums above for descriptions and default values.
-//
-// The default log file is initialized to "debug.log" in the application
-// directory. You probably don't want this, especially since the program
-// directory may not be writable on an enduser's system.
-//
-// This function may be called a second time to re-direct logging (e.g after
-// loging in to a user partition), however it should never be called more than
-// twice.
-inline bool InitLogging(const LoggingSettings& settings) {
- return BaseInitLoggingImpl(settings);
-}
-
-// Sets the log level. Anything at or above this level will be written to the
-// log file/displayed to the user (if applicable). Anything below this level
-// will be silently ignored. The log level defaults to 0 (everything is logged
-// up to level INFO) if this function is not called.
-// Note that log messages for VLOG(x) are logged at level -x, so setting
-// the min log level to negative values enables verbose logging.
-BASE_EXPORT void SetMinLogLevel(int level);
-
-// Gets the current log level.
-BASE_EXPORT int GetMinLogLevel();
-
-// Used by LOG_IS_ON to lazy-evaluate stream arguments.
-BASE_EXPORT bool ShouldCreateLogMessage(int severity);
-
-// Gets the VLOG default verbosity level.
-BASE_EXPORT int GetVlogVerbosity();
-
-// Gets the current vlog level for the given file (usually taken from
-// __FILE__).
-
-// Note that |N| is the size *with* the null terminator.
-BASE_EXPORT int GetVlogLevelHelper(const char* file_start, size_t N);
-
-template <size_t N>
-int GetVlogLevel(const char (&file)[N]) {
- return GetVlogLevelHelper(file, N);
-}
-
-// Sets the common items you want to be prepended to each log message.
-// process and thread IDs default to off, the timestamp defaults to on.
-// If this function is not called, logging defaults to writing the timestamp
-// only.
-BASE_EXPORT void SetLogItems(bool enable_process_id, bool enable_thread_id,
- bool enable_timestamp, bool enable_tickcount);
-
-// Sets whether or not you'd like to see fatal debug messages popped up in
-// a dialog box or not.
-// Dialogs are not shown by default.
-BASE_EXPORT void SetShowErrorDialogs(bool enable_dialogs);
-
-// Sets the Log Assert Handler that will be used to notify of check failures.
-// The default handler shows a dialog box and then terminate the process,
-// however clients can use this function to override with their own handling
-// (e.g. a silent one for Unit Tests)
-typedef void (*LogAssertHandlerFunction)(const std::string& str);
-BASE_EXPORT void SetLogAssertHandler(LogAssertHandlerFunction handler);
-
-// Sets the Log Message Handler that gets passed every log message before
-// it's sent to other log destinations (if any).
-// Returns true to signal that it handled the message and the message
-// should not be sent to other log destinations.
-typedef bool (*LogMessageHandlerFunction)(int severity,
- const char* file, int line, size_t message_start, const std::string& str);
-BASE_EXPORT void SetLogMessageHandler(LogMessageHandlerFunction handler);
-BASE_EXPORT LogMessageHandlerFunction GetLogMessageHandler();
-
-typedef int LogSeverity;
-const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity
-// Note: the log severities are used to index into the array of names,
-// see log_severity_names.
-const LogSeverity LOG_INFO = 0;
-const LogSeverity LOG_WARNING = 1;
-const LogSeverity LOG_ERROR = 2;
-const LogSeverity LOG_FATAL = 3;
-const LogSeverity LOG_NUM_SEVERITIES = 4;
-
-// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode
-#ifdef NDEBUG
-const LogSeverity LOG_DFATAL = LOG_ERROR;
-#else
-const LogSeverity LOG_DFATAL = LOG_FATAL;
-#endif
-
-// A few definitions of macros that don't generate much code. These are used
-// by LOG() and LOG_IF, etc. Since these are used all over our code, it's
-// better to have compact code for these operations.
-#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
- logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
-#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
- logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
-#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
- logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
-#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
- logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
-#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
- logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
-
-#define COMPACT_GOOGLE_LOG_INFO \
- COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
-#define COMPACT_GOOGLE_LOG_WARNING \
- COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
-#define COMPACT_GOOGLE_LOG_ERROR \
- COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
-#define COMPACT_GOOGLE_LOG_FATAL \
- COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage)
-#define COMPACT_GOOGLE_LOG_DFATAL \
- COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage)
-
-#if defined(OS_WIN)
-// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets
-// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us
-// to keep using this syntax, we define this macro to do the same thing
-// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that
-// the Windows SDK does for consistency.
-#define ERROR 0
-#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \
- COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__)
-#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR
-// Needed for LOG_IS_ON(ERROR).
-const LogSeverity LOG_0 = LOG_ERROR;
-#endif
-
-// As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also,
-// LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will
-// always fire if they fail.
-#define LOG_IS_ON(severity) \
- (::logging::ShouldCreateLogMessage(::logging::LOG_##severity))
-
-// We can't do any caching tricks with VLOG_IS_ON() like the
-// google-glog version since it requires GCC extensions. This means
-// that using the v-logging functions in conjunction with --vmodule
-// may be slow.
-#define VLOG_IS_ON(verboselevel) \
- ((verboselevel) <= ::logging::GetVlogLevel(__FILE__))
-
-// Helper macro which avoids evaluating the arguments to a stream if
-// the condition doesn't hold. Condition is evaluated once and only once.
-#define LAZY_STREAM(stream, condition) \
- !(condition) ? (void) 0 : ::logging::LogMessageVoidify() & (stream)
-
-// We use the preprocessor's merging operator, "##", so that, e.g.,
-// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny
-// subtle difference between ostream member streaming functions (e.g.,
-// ostream::operator<<(int) and ostream non-member streaming functions
-// (e.g., ::operator<<(ostream&, string&): it turns out that it's
-// impossible to stream something like a string directly to an unnamed
-// ostream. We employ a neat hack by calling the stream() member
-// function of LogMessage which seems to avoid the problem.
-#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
-
-#define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
-#define LOG_IF(severity, condition) \
- LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
-
-#define SYSLOG(severity) LOG(severity)
-#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
-
-// The VLOG macros log with negative verbosities.
-#define VLOG_STREAM(verbose_level) \
- logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
-
-#define VLOG(verbose_level) \
- LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
-
-#define VLOG_IF(verbose_level, condition) \
- LAZY_STREAM(VLOG_STREAM(verbose_level), \
- VLOG_IS_ON(verbose_level) && (condition))
-
-#if defined (OS_WIN)
-#define VPLOG_STREAM(verbose_level) \
- logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
- ::logging::GetLastSystemErrorCode()).stream()
-#elif defined(OS_POSIX)
-#define VPLOG_STREAM(verbose_level) \
- logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
- ::logging::GetLastSystemErrorCode()).stream()
-#endif
-
-#define VPLOG(verbose_level) \
- LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
-
-#define VPLOG_IF(verbose_level, condition) \
- LAZY_STREAM(VPLOG_STREAM(verbose_level), \
- VLOG_IS_ON(verbose_level) && (condition))
-
-// TODO(akalin): Add more VLOG variants, e.g. VPLOG.
-
-#define LOG_ASSERT(condition) \
- LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
-#define SYSLOG_ASSERT(condition) \
- SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
-
-#if defined(OS_WIN)
-#define PLOG_STREAM(severity) \
- COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
- ::logging::GetLastSystemErrorCode()).stream()
-#elif defined(OS_POSIX)
-#define PLOG_STREAM(severity) \
- COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
- ::logging::GetLastSystemErrorCode()).stream()
-#endif
-
-#define PLOG(severity) \
- LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity))
-
-#define PLOG_IF(severity, condition) \
- LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
-
-// The actual stream used isn't important.
-#define EAT_STREAM_PARAMETERS \
- true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
-
-// Captures the result of a CHECK_EQ (for example) and facilitates testing as a
-// boolean.
-class CheckOpResult {
- public:
- // |message| must be null if and only if the check failed.
- CheckOpResult(std::string* message) : message_(message) {}
- // Returns true if the check succeeded.
- operator bool() const { return !message_; }
- // Returns the message.
- std::string* message() { return message_; }
-
- private:
- std::string* message_;
-};
-
-// CHECK dies with a fatal error if condition is not true. It is *not*
-// controlled by NDEBUG, so the check will be executed regardless of
-// compilation mode.
-//
-// We make sure CHECK et al. always evaluates their arguments, as
-// doing CHECK(FunctionWithSideEffect()) is a common idiom.
-
-#if defined(OFFICIAL_BUILD) && defined(NDEBUG) && !defined(OS_ANDROID)
-
-// Make all CHECK functions discard their log strings to reduce code
-// bloat for official release builds (except Android).
-
-// TODO(akalin): This would be more valuable if there were some way to
-// remove BreakDebugger() from the backtrace, perhaps by turning it
-// into a macro (like __debugbreak() on Windows).
-#define CHECK(condition) \
- !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
-
-#define PCHECK(condition) CHECK(condition)
-
-#define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
-
-#else
-
-#if defined(_PREFAST_) && defined(OS_WIN)
-// Use __analysis_assume to tell the VC++ static analysis engine that
-// assert conditions are true, to suppress warnings. The LAZY_STREAM
-// parameter doesn't reference 'condition' in /analyze builds because
-// this evaluation confuses /analyze. The !! before condition is because
-// __analysis_assume gets confused on some conditions:
-// http://randomascii.wordpress.com/2011/09/13/analyze-for-visual-studio-the-ugly-part-5/
-
-#define CHECK(condition) \
- __analysis_assume(!!(condition)), \
- LAZY_STREAM(LOG_STREAM(FATAL), false) \
- << "Check failed: " #condition ". "
-
-#define PCHECK(condition) \
- __analysis_assume(!!(condition)), \
- LAZY_STREAM(PLOG_STREAM(FATAL), false) \
- << "Check failed: " #condition ". "
-
-#else // _PREFAST_
-
-// Do as much work as possible out of line to reduce inline code size.
-#define CHECK(condition) \
- LAZY_STREAM(logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
- !(condition))
-
-#define PCHECK(condition) \
- LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
- << "Check failed: " #condition ". "
-
-#endif // _PREFAST_
-
-// Helper macro for binary operators.
-// Don't use this macro directly in your code, use CHECK_EQ et al below.
-// The 'switch' is used to prevent the 'else' from being ambiguous when the
-// macro is used in an 'if' clause such as:
-// if (a == 1)
-// CHECK_EQ(2, a);
-#define CHECK_OP(name, op, val1, val2) \
- switch (0) case 0: default: \
- if (logging::CheckOpResult true_if_passed = \
- logging::Check##name##Impl((val1), (val2), \
- #val1 " " #op " " #val2)) \
- ; \
- else \
- logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
-
-#endif
-
-// Build the error message string. This is separate from the "Impl"
-// function template because it is not performance critical and so can
-// be out of line, while the "Impl" code should be inline. Caller
-// takes ownership of the returned string.
-template<class t1, class t2>
-std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
- std::ostringstream ss;
- ss << names << " (" << v1 << " vs. " << v2 << ")";
- std::string* msg = new std::string(ss.str());
- return msg;
-}
-
-// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
-// in logging.cc.
-extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
- const int&, const int&, const char* names);
-extern template BASE_EXPORT
-std::string* MakeCheckOpString<unsigned long, unsigned long>(
- const unsigned long&, const unsigned long&, const char* names);
-extern template BASE_EXPORT
-std::string* MakeCheckOpString<unsigned long, unsigned int>(
- const unsigned long&, const unsigned int&, const char* names);
-extern template BASE_EXPORT
-std::string* MakeCheckOpString<unsigned int, unsigned long>(
- const unsigned int&, const unsigned long&, const char* names);
-extern template BASE_EXPORT
-std::string* MakeCheckOpString<std::string, std::string>(
- const std::string&, const std::string&, const char* name);
-
-// Helper functions for CHECK_OP macro.
-// The (int, int) specialization works around the issue that the compiler
-// will not instantiate the template version of the function on values of
-// unnamed enum type - see comment below.
-#define DEFINE_CHECK_OP_IMPL(name, op) \
- template <class t1, class t2> \
- inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
- const char* names) { \
- if (v1 op v2) return NULL; \
- else return MakeCheckOpString(v1, v2, names); \
- } \
- inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
- if (v1 op v2) return NULL; \
- else return MakeCheckOpString(v1, v2, names); \
- }
-DEFINE_CHECK_OP_IMPL(EQ, ==)
-DEFINE_CHECK_OP_IMPL(NE, !=)
-DEFINE_CHECK_OP_IMPL(LE, <=)
-DEFINE_CHECK_OP_IMPL(LT, < )
-DEFINE_CHECK_OP_IMPL(GE, >=)
-DEFINE_CHECK_OP_IMPL(GT, > )
-#undef DEFINE_CHECK_OP_IMPL
-
-#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
-#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
-#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
-#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
-#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
-#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
-
-#if defined(NDEBUG)
-#define ENABLE_DLOG 0
-#else
-#define ENABLE_DLOG 1
-#endif
-
-#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
-#define DCHECK_IS_ON() 0
-#else
-#define DCHECK_IS_ON() 1
-#endif
-
-// Definitions for DLOG et al.
-
-#if ENABLE_DLOG
-
-#define DLOG_IS_ON(severity) LOG_IS_ON(severity)
-#define DLOG_IF(severity, condition) LOG_IF(severity, condition)
-#define DLOG_ASSERT(condition) LOG_ASSERT(condition)
-#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
-#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
-#define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
-
-#else // ENABLE_DLOG
-
-// If ENABLE_DLOG is off, we want to avoid emitting any references to
-// |condition| (which may reference a variable defined only if NDEBUG
-// is not defined). Contrast this with DCHECK et al., which has
-// different behavior.
-
-#define DLOG_IS_ON(severity) false
-#define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
-#define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
-#define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
-#define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
-#define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
-
-#endif // ENABLE_DLOG
-
-// DEBUG_MODE is for uses like
-// if (DEBUG_MODE) foo.CheckThatFoo();
-// instead of
-// #ifndef NDEBUG
-// foo.CheckThatFoo();
-// #endif
-//
-// We tie its state to ENABLE_DLOG.
-enum { DEBUG_MODE = ENABLE_DLOG };
-
-#undef ENABLE_DLOG
-
-#define DLOG(severity) \
- LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
-
-#define DPLOG(severity) \
- LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
-
-#define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
-
-#define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
-
-// Definitions for DCHECK et al.
-
-#if DCHECK_IS_ON()
-
-#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
- COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__)
-#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL
-const LogSeverity LOG_DCHECK = LOG_FATAL;
-
-#else // DCHECK_IS_ON()
-
-// These are just dummy values.
-#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \
- COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__)
-#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO
-const LogSeverity LOG_DCHECK = LOG_INFO;
-
-#endif // DCHECK_IS_ON()
-
-// DCHECK et al. make sure to reference |condition| regardless of
-// whether DCHECKs are enabled; this is so that we don't get unused
-// variable warnings if the only use of a variable is in a DCHECK.
-// This behavior is different from DLOG_IF et al.
-
-#if defined(_PREFAST_) && defined(OS_WIN)
-// See comments on the previous use of __analysis_assume.
-
-#define DCHECK(condition) \
- __analysis_assume(!!(condition)), \
- LAZY_STREAM(LOG_STREAM(DCHECK), false) \
- << "Check failed: " #condition ". "
-
-#define DPCHECK(condition) \
- __analysis_assume(!!(condition)), \
- LAZY_STREAM(PLOG_STREAM(DCHECK), false) \
- << "Check failed: " #condition ". "
-
-#else // _PREFAST_
-
-#define DCHECK(condition) \
- LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON() ? !(condition) : false) \
- << "Check failed: " #condition ". "
-
-#define DPCHECK(condition) \
- LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON() ? !(condition) : false) \
- << "Check failed: " #condition ". "
-
-#endif // _PREFAST_
-
-// Helper macro for binary operators.
-// Don't use this macro directly in your code, use DCHECK_EQ et al below.
-// The 'switch' is used to prevent the 'else' from being ambiguous when the
-// macro is used in an 'if' clause such as:
-// if (a == 1)
-// DCHECK_EQ(2, a);
-#define DCHECK_OP(name, op, val1, val2) \
- switch (0) case 0: default: \
- if (logging::CheckOpResult true_if_passed = \
- DCHECK_IS_ON() ? \
- logging::Check##name##Impl((val1), (val2), \
- #val1 " " #op " " #val2) : nullptr) \
- ; \
- else \
- logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK, \
- true_if_passed.message()).stream()
-
-// Equality/Inequality checks - compare two values, and log a
-// LOG_DCHECK message including the two values when the result is not
-// as expected. The values must have operator<<(ostream, ...)
-// defined.
-//
-// You may append to the error message like so:
-// DCHECK_NE(1, 2) << ": The world must be ending!";
-//
-// We are very careful to ensure that each argument is evaluated exactly
-// once, and that anything which is legal to pass as a function argument is
-// legal here. In particular, the arguments may be temporary expressions
-// which will end up being destroyed at the end of the apparent statement,
-// for example:
-// DCHECK_EQ(string("abc")[1], 'b');
-//
-// WARNING: These may not compile correctly if one of the arguments is a pointer
-// and the other is NULL. To work around this, simply static_cast NULL to the
-// type of the desired pointer.
-
-#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
-#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
-#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
-#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
-#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
-#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
-
-#if !DCHECK_IS_ON() && defined(OS_CHROMEOS)
-// Implement logging of NOTREACHED() as a dedicated function to get function
-// call overhead down to a minimum.
-void LogErrorNotReached(const char* file, int line);
-#define NOTREACHED() \
- true ? ::logging::LogErrorNotReached(__FILE__, __LINE__) \
- : EAT_STREAM_PARAMETERS
-#else
-#define NOTREACHED() DCHECK(false)
-#endif
-
-// Redefine the standard assert to use our nice log files
-#undef assert
-#define assert(x) DLOG_ASSERT(x)
-
-// This class more or less represents a particular log message. You
-// create an instance of LogMessage and then stream stuff to it.
-// When you finish streaming to it, ~LogMessage is called and the
-// full message gets streamed to the appropriate destination.
-//
-// You shouldn't actually use LogMessage's constructor to log things,
-// though. You should use the LOG() macro (and variants thereof)
-// above.
-class BASE_EXPORT LogMessage {
- public:
- // Used for LOG(severity).
- LogMessage(const char* file, int line, LogSeverity severity);
-
- // Used for CHECK(). Implied severity = LOG_FATAL.
- LogMessage(const char* file, int line, const char* condition);
-
- // Used for CHECK_EQ(), etc. Takes ownership of the given string.
- // Implied severity = LOG_FATAL.
- LogMessage(const char* file, int line, std::string* result);
-
- // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
- LogMessage(const char* file, int line, LogSeverity severity,
- std::string* result);
-
- ~LogMessage();
-
- std::ostream& stream() { return stream_; }
-
- private:
- void Init(const char* file, int line);
-
- LogSeverity severity_;
- std::ostringstream stream_;
- size_t message_start_; // Offset of the start of the message (past prefix
- // info).
- // The file and line information passed in to the constructor.
- const char* file_;
- const int line_;
-
-#if defined(OS_WIN)
- // Stores the current value of GetLastError in the constructor and restores
- // it in the destructor by calling SetLastError.
- // This is useful since the LogMessage class uses a lot of Win32 calls
- // that will lose the value of GLE and the code that called the log function
- // will have lost the thread error value when the log call returns.
- class SaveLastError {
- public:
- SaveLastError();
- ~SaveLastError();
-
- unsigned long get_error() const { return last_error_; }
-
- protected:
- unsigned long last_error_;
- };
-
- SaveLastError last_error_;
-#endif
-
- DISALLOW_COPY_AND_ASSIGN(LogMessage);
-};
-
-// A non-macro interface to the log facility; (useful
-// when the logging level is not a compile-time constant).
-inline void LogAtLevel(int log_level, const std::string& msg) {
- LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
-}
-
-// This class is used to explicitly ignore values in the conditional
-// logging macros. This avoids compiler warnings like "value computed
-// is not used" and "statement has no effect".
-class LogMessageVoidify {
- public:
- LogMessageVoidify() { }
- // This has to be an operator with a precedence lower than << but
- // higher than ?:
- void operator&(std::ostream&) { }
-};
-
-#if defined(OS_WIN)
-typedef unsigned long SystemErrorCode;
-#elif defined(OS_POSIX)
-typedef int SystemErrorCode;
-#endif
-
-// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to
-// pull in windows.h just for GetLastError() and DWORD.
-BASE_EXPORT SystemErrorCode GetLastSystemErrorCode();
-BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code);
-
-#if defined(OS_WIN)
-// Appends a formatted system message of the GetLastError() type.
-class BASE_EXPORT Win32ErrorLogMessage {
- public:
- Win32ErrorLogMessage(const char* file,
- int line,
- LogSeverity severity,
- SystemErrorCode err);
-
- // Appends the error message before destructing the encapsulated class.
- ~Win32ErrorLogMessage();
-
- std::ostream& stream() { return log_message_.stream(); }
-
- private:
- SystemErrorCode err_;
- LogMessage log_message_;
-
- DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage);
-};
-#elif defined(OS_POSIX)
-// Appends a formatted system message of the errno type
-class BASE_EXPORT ErrnoLogMessage {
- public:
- ErrnoLogMessage(const char* file,
- int line,
- LogSeverity severity,
- SystemErrorCode err);
-
- // Appends the error message before destructing the encapsulated class.
- ~ErrnoLogMessage();
-
- std::ostream& stream() { return log_message_.stream(); }
-
- private:
- SystemErrorCode err_;
- LogMessage log_message_;
-
- DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage);
-};
-#endif // OS_WIN
-
-// Closes the log file explicitly if open.
-// NOTE: Since the log file is opened as necessary by the action of logging
-// statements, there's no guarantee that it will stay closed
-// after this call.
-BASE_EXPORT void CloseLogFile();
-
-// Async signal safe logging mechanism.
-BASE_EXPORT void RawLog(int level, const char* message);
-
-#define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
-
-#define RAW_CHECK(condition) \
- do { \
- if (!(condition)) \
- logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n"); \
- } while (0)
-
-#if defined(OS_WIN)
-// Returns true if logging to file is enabled.
-BASE_EXPORT bool IsLoggingToFileEnabled();
-
-// Returns the default log file path.
-BASE_EXPORT std::wstring GetLogFileFullPath();
-#endif
-
-} // namespace logging
-
-// Note that "The behavior of a C++ program is undefined if it adds declarations
-// or definitions to namespace std or to a namespace within namespace std unless
-// otherwise specified." --C++11[namespace.std]
-//
-// We've checked that this particular definition has the intended behavior on
-// our implementations, but it's prone to breaking in the future, and please
-// don't imitate this in your own definitions without checking with some
-// standard library experts.
-namespace std {
-// These functions are provided as a convenience for logging, which is where we
-// use streams (it is against Google style to use streams in other places). It
-// is designed to allow you to emit non-ASCII Unicode strings to the log file,
-// which is normally ASCII. It is relatively slow, so try not to use it for
-// common cases. Non-ASCII characters will be converted to UTF-8 by these
-// operators.
-BASE_EXPORT std::ostream& operator<<(std::ostream& out, const wchar_t* wstr);
-inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) {
- return out << wstr.c_str();
-}
-} // namespace std
-
-// The NOTIMPLEMENTED() macro annotates codepaths which have
-// not been implemented yet.
-//
-// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY:
-// 0 -- Do nothing (stripped by compiler)
-// 1 -- Warn at compile time
-// 2 -- Fail at compile time
-// 3 -- Fail at runtime (DCHECK)
-// 4 -- [default] LOG(ERROR) at runtime
-// 5 -- LOG(ERROR) at runtime, only once per call-site
-
-#ifndef NOTIMPLEMENTED_POLICY
-#if defined(OS_ANDROID) && defined(OFFICIAL_BUILD)
-#define NOTIMPLEMENTED_POLICY 0
-#else
-// Select default policy: LOG(ERROR)
-#define NOTIMPLEMENTED_POLICY 4
-#endif
-#endif
-
-#if defined(COMPILER_GCC)
-// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name
-// of the current function in the NOTIMPLEMENTED message.
-#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__
-#else
-#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED"
-#endif
-
-#if NOTIMPLEMENTED_POLICY == 0
-#define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS
-#elif NOTIMPLEMENTED_POLICY == 1
-// TODO, figure out how to generate a warning
-#define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
-#elif NOTIMPLEMENTED_POLICY == 2
-#define NOTIMPLEMENTED() static_assert(false, "NOT_IMPLEMENTED")
-#elif NOTIMPLEMENTED_POLICY == 3
-#define NOTIMPLEMENTED() NOTREACHED()
-#elif NOTIMPLEMENTED_POLICY == 4
-#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG
-#elif NOTIMPLEMENTED_POLICY == 5
-#define NOTIMPLEMENTED() do {\
- static bool logged_once = false;\
- LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\
- logged_once = true;\
-} while(0);\
-EAT_STREAM_PARAMETERS
-#endif
-
-#endif // BASE_LOGGING_H_
diff --git a/security/sandbox/chromium/base/macros.h b/security/sandbox/chromium/base/macros.h
deleted file mode 100644
index 46ee1dadb..000000000
--- a/security/sandbox/chromium/base/macros.h
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2014 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 contains macros and macro-like constructs (e.g., templates) that
-// are commonly used throughout Chromium source. (It may also contain things
-// that are closely related to things that are commonly used that belong in this
-// file.)
-
-#ifndef BASE_MACROS_H_
-#define BASE_MACROS_H_
-
-#include <stddef.h> // For size_t.
-
-// Put this in the declarations for a class to be uncopyable.
-#define DISALLOW_COPY(TypeName) \
- TypeName(const TypeName&) = delete
-
-// Put this in the declarations for a class to be unassignable.
-#define DISALLOW_ASSIGN(TypeName) \
- void operator=(const TypeName&) = delete
-
-// A macro to disallow the copy constructor and operator= functions
-// This should be used in the private: declarations for a class
-#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
- TypeName(const TypeName&); \
- void operator=(const 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.
-#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
- TypeName() = delete; \
- 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. For the technical details, refer to
-// http://blogs.msdn.com/b/the1/archive/2004/05/07/128242.aspx.
-
-// 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];
-#define arraysize(array) (sizeof(ArraySizeHelper(array)))
-
-// Used to explicitly mark the return value of a function as unused. If you are
-// really sure you don't want to do anything with the return value of a function
-// that has been marked WARN_UNUSED_RESULT, wrap it with this. Example:
-//
-// scoped_ptr<MyType> my_var = ...;
-// if (TakeOwnership(my_var.get()) == SUCCESS)
-// ignore_result(my_var.release());
-//
-template<typename T>
-inline void ignore_result(const T&) {
-}
-
-// 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 };
-
-// Use these to declare and define a static local variable (static T;) so that
-// it is leaked so that its destructors are not called at exit. If you need
-// thread-safe initialization, use base/lazy_instance.h instead.
-#define CR_DEFINE_STATIC_LOCAL(type, name, arguments) \
- static type& name = *new type arguments
-
-} // base
-
-#endif // BASE_MACROS_H_
diff --git a/security/sandbox/chromium/base/memory/aligned_memory.h b/security/sandbox/chromium/base/memory/aligned_memory.h
deleted file mode 100644
index bb7bd872c..000000000
--- a/security/sandbox/chromium/base/memory/aligned_memory.h
+++ /dev/null
@@ -1,117 +0,0 @@
-// 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.
-
-// AlignedMemory is a POD type that gives you a portable way to specify static
-// or local stack data of a given alignment and size. For example, if you need
-// static storage for a class, but you want manual control over when the object
-// is constructed and destructed (you don't want static initialization and
-// destruction), use AlignedMemory:
-//
-// static AlignedMemory<sizeof(MyClass), ALIGNOF(MyClass)> my_class;
-//
-// // ... at runtime:
-// new(my_class.void_data()) MyClass();
-//
-// // ... use it:
-// MyClass* mc = my_class.data_as<MyClass>();
-//
-// // ... later, to destruct my_class:
-// my_class.data_as<MyClass>()->MyClass::~MyClass();
-//
-// Alternatively, a runtime sized aligned allocation can be created:
-//
-// float* my_array = static_cast<float*>(AlignedAlloc(size, alignment));
-//
-// // ... later, to release the memory:
-// AlignedFree(my_array);
-//
-// Or using scoped_ptr:
-//
-// scoped_ptr<float, AlignedFreeDeleter> my_array(
-// static_cast<float*>(AlignedAlloc(size, alignment)));
-
-#ifndef BASE_MEMORY_ALIGNED_MEMORY_H_
-#define BASE_MEMORY_ALIGNED_MEMORY_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-
-#if defined(COMPILER_MSVC)
-#include <malloc.h>
-#else
-#include <stdlib.h>
-#endif
-
-namespace base {
-
-// AlignedMemory is specialized for all supported alignments.
-// Make sure we get a compiler error if someone uses an unsupported alignment.
-template <size_t Size, size_t ByteAlignment>
-struct AlignedMemory {};
-
-#define BASE_DECL_ALIGNED_MEMORY(byte_alignment) \
- template <size_t Size> \
- class AlignedMemory<Size, byte_alignment> { \
- public: \
- ALIGNAS(byte_alignment) uint8_t data_[Size]; \
- void* void_data() { return static_cast<void*>(data_); } \
- const void* void_data() const { return static_cast<const void*>(data_); } \
- template <typename Type> \
- Type* data_as() { \
- return static_cast<Type*>(void_data()); \
- } \
- template <typename Type> \
- const Type* data_as() const { \
- return static_cast<const Type*>(void_data()); \
- } \
- \
- private: \
- void* operator new(size_t); \
- void operator delete(void*); \
- }
-
-// Specialization for all alignments is required because MSVC (as of VS 2008)
-// does not understand ALIGNAS(ALIGNOF(Type)) or ALIGNAS(template_param).
-// Greater than 4096 alignment is not supported by some compilers, so 4096 is
-// the maximum specified here.
-BASE_DECL_ALIGNED_MEMORY(1);
-BASE_DECL_ALIGNED_MEMORY(2);
-BASE_DECL_ALIGNED_MEMORY(4);
-BASE_DECL_ALIGNED_MEMORY(8);
-BASE_DECL_ALIGNED_MEMORY(16);
-BASE_DECL_ALIGNED_MEMORY(32);
-BASE_DECL_ALIGNED_MEMORY(64);
-BASE_DECL_ALIGNED_MEMORY(128);
-BASE_DECL_ALIGNED_MEMORY(256);
-BASE_DECL_ALIGNED_MEMORY(512);
-BASE_DECL_ALIGNED_MEMORY(1024);
-BASE_DECL_ALIGNED_MEMORY(2048);
-BASE_DECL_ALIGNED_MEMORY(4096);
-
-#undef BASE_DECL_ALIGNED_MEMORY
-
-BASE_EXPORT void* AlignedAlloc(size_t size, size_t alignment);
-
-inline void AlignedFree(void* ptr) {
-#if defined(COMPILER_MSVC)
- _aligned_free(ptr);
-#else
- free(ptr);
-#endif
-}
-
-// Deleter for use with scoped_ptr. E.g., use as
-// scoped_ptr<Foo, base::AlignedFreeDeleter> foo;
-struct AlignedFreeDeleter {
- inline void operator()(void* ptr) const {
- AlignedFree(ptr);
- }
-};
-
-} // namespace base
-
-#endif // BASE_MEMORY_ALIGNED_MEMORY_H_
diff --git a/security/sandbox/chromium/base/memory/raw_scoped_refptr_mismatch_checker.h b/security/sandbox/chromium/base/memory/raw_scoped_refptr_mismatch_checker.h
deleted file mode 100644
index 09f982b12..000000000
--- a/security/sandbox/chromium/base/memory/raw_scoped_refptr_mismatch_checker.h
+++ /dev/null
@@ -1,64 +0,0 @@
-// 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_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_
-#define BASE_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_
-
-#include "base/memory/ref_counted.h"
-#include "base/template_util.h"
-#include "base/tuple.h"
-#include "build/build_config.h"
-
-// It is dangerous to post a task with a T* argument where T is a subtype of
-// RefCounted(Base|ThreadSafeBase), since by the time the parameter is used, the
-// object may already have been deleted since it was not held with a
-// scoped_refptr. Example: http://crbug.com/27191
-// The following set of traits are designed to generate a compile error
-// whenever this antipattern is attempted.
-
-namespace base {
-
-// This is a base internal implementation file used by task.h and callback.h.
-// Not for public consumption, so we wrap it in namespace internal.
-namespace internal {
-
-template <typename T>
-struct NeedsScopedRefptrButGetsRawPtr {
-#if defined(OS_WIN)
- enum {
- value = base::false_type::value
- };
-#else
- enum {
- // Human readable translation: you needed to be a scoped_refptr if you are a
- // raw pointer type and are convertible to a RefCounted(Base|ThreadSafeBase)
- // type.
- value = (is_pointer<T>::value &&
- (is_convertible<T, subtle::RefCountedBase*>::value ||
- is_convertible<T, subtle::RefCountedThreadSafeBase*>::value))
- };
-#endif
-};
-
-template <typename Params>
-struct ParamsUseScopedRefptrCorrectly {
- enum { value = 0 };
-};
-
-template <>
-struct ParamsUseScopedRefptrCorrectly<Tuple<>> {
- enum { value = 1 };
-};
-
-template <typename Head, typename... Tail>
-struct ParamsUseScopedRefptrCorrectly<Tuple<Head, Tail...>> {
- enum { value = !NeedsScopedRefptrButGetsRawPtr<Head>::value &&
- ParamsUseScopedRefptrCorrectly<Tuple<Tail...>>::value };
-};
-
-} // namespace internal
-
-} // namespace base
-
-#endif // BASE_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_
diff --git a/security/sandbox/chromium/base/memory/ref_counted.cc b/security/sandbox/chromium/base/memory/ref_counted.cc
deleted file mode 100644
index f5924d0fe..000000000
--- a/security/sandbox/chromium/base/memory/ref_counted.cc
+++ /dev/null
@@ -1,53 +0,0 @@
-// 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/memory/ref_counted.h"
-#include "base/threading/thread_collision_warner.h"
-
-namespace base {
-
-namespace subtle {
-
-bool RefCountedThreadSafeBase::HasOneRef() const {
- return AtomicRefCountIsOne(
- &const_cast<RefCountedThreadSafeBase*>(this)->ref_count_);
-}
-
-RefCountedThreadSafeBase::RefCountedThreadSafeBase() : ref_count_(0) {
-#ifndef NDEBUG
- in_dtor_ = false;
-#endif
-}
-
-RefCountedThreadSafeBase::~RefCountedThreadSafeBase() {
-#ifndef NDEBUG
- DCHECK(in_dtor_) << "RefCountedThreadSafe object deleted without "
- "calling Release()";
-#endif
-}
-
-void RefCountedThreadSafeBase::AddRef() const {
-#ifndef NDEBUG
- DCHECK(!in_dtor_);
-#endif
- AtomicRefCountInc(&ref_count_);
-}
-
-bool RefCountedThreadSafeBase::Release() const {
-#ifndef NDEBUG
- DCHECK(!in_dtor_);
- DCHECK(!AtomicRefCountIsZero(&ref_count_));
-#endif
- if (!AtomicRefCountDec(&ref_count_)) {
-#ifndef NDEBUG
- in_dtor_ = true;
-#endif
- return true;
- }
- return false;
-}
-
-} // namespace subtle
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/memory/ref_counted.h b/security/sandbox/chromium/base/memory/ref_counted.h
deleted file mode 100644
index a1c126969..000000000
--- a/security/sandbox/chromium/base/memory/ref_counted.h
+++ /dev/null
@@ -1,446 +0,0 @@
-// 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.
-
-#ifndef BASE_MEMORY_REF_COUNTED_H_
-#define BASE_MEMORY_REF_COUNTED_H_
-
-#include <cassert>
-#include <iosfwd>
-
-#include "base/atomic_ref_count.h"
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#ifndef NDEBUG
-#include "base/logging.h"
-#endif
-#include "base/threading/thread_collision_warner.h"
-#include "build/build_config.h"
-
-namespace base {
-
-namespace subtle {
-
-class BASE_EXPORT RefCountedBase {
- public:
- bool HasOneRef() const { return ref_count_ == 1; }
-
- protected:
- RefCountedBase()
- : ref_count_(0)
- #ifndef NDEBUG
- , in_dtor_(false)
- #endif
- {
- }
-
- ~RefCountedBase() {
- #ifndef NDEBUG
- DCHECK(in_dtor_) << "RefCounted object deleted without calling Release()";
- #endif
- }
-
-
- void AddRef() const {
- // TODO(maruel): Add back once it doesn't assert 500 times/sec.
- // Current thread books the critical section "AddRelease"
- // without release it.
- // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_);
- #ifndef NDEBUG
- DCHECK(!in_dtor_);
- #endif
- ++ref_count_;
- }
-
- // Returns true if the object should self-delete.
- bool Release() const {
- // TODO(maruel): Add back once it doesn't assert 500 times/sec.
- // Current thread books the critical section "AddRelease"
- // without release it.
- // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_);
- #ifndef NDEBUG
- DCHECK(!in_dtor_);
- #endif
- if (--ref_count_ == 0) {
- #ifndef NDEBUG
- in_dtor_ = true;
- #endif
- return true;
- }
- return false;
- }
-
- private:
- mutable int ref_count_;
-#ifndef NDEBUG
- mutable bool in_dtor_;
-#endif
-
- DFAKE_MUTEX(add_release_);
-
- DISALLOW_COPY_AND_ASSIGN(RefCountedBase);
-};
-
-class BASE_EXPORT RefCountedThreadSafeBase {
- public:
- bool HasOneRef() const;
-
- protected:
- RefCountedThreadSafeBase();
- ~RefCountedThreadSafeBase();
-
- void AddRef() const;
-
- // Returns true if the object should self-delete.
- bool Release() const;
-
- private:
- mutable AtomicRefCount ref_count_;
-#ifndef NDEBUG
- mutable bool in_dtor_;
-#endif
-
- DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase);
-};
-
-} // namespace subtle
-
-//
-// A base class for reference counted classes. Otherwise, known as a cheap
-// knock-off of WebKit's RefCounted<T> class. To use this guy just extend your
-// class from it like so:
-//
-// class MyFoo : public base::RefCounted<MyFoo> {
-// ...
-// private:
-// friend class base::RefCounted<MyFoo>;
-// ~MyFoo();
-// };
-//
-// You should always make your destructor non-public, to avoid any code deleting
-// the object accidently while there are references to it.
-template <class T>
-class RefCounted : public subtle::RefCountedBase {
- public:
- RefCounted() {}
-
- void AddRef() const {
- subtle::RefCountedBase::AddRef();
- }
-
- void Release() const {
- if (subtle::RefCountedBase::Release()) {
- delete static_cast<const T*>(this);
- }
- }
-
- protected:
- ~RefCounted() {}
-
- private:
- DISALLOW_COPY_AND_ASSIGN(RefCounted<T>);
-};
-
-// Forward declaration.
-template <class T, typename Traits> class RefCountedThreadSafe;
-
-// Default traits for RefCountedThreadSafe<T>. Deletes the object when its ref
-// count reaches 0. Overload to delete it on a different thread etc.
-template<typename T>
-struct DefaultRefCountedThreadSafeTraits {
- static void Destruct(const T* x) {
- // Delete through RefCountedThreadSafe to make child classes only need to be
- // friend with RefCountedThreadSafe instead of this struct, which is an
- // implementation detail.
- RefCountedThreadSafe<T,
- DefaultRefCountedThreadSafeTraits>::DeleteInternal(x);
- }
-};
-
-//
-// A thread-safe variant of RefCounted<T>
-//
-// class MyFoo : public base::RefCountedThreadSafe<MyFoo> {
-// ...
-// };
-//
-// If you're using the default trait, then you should add compile time
-// asserts that no one else is deleting your object. i.e.
-// private:
-// friend class base::RefCountedThreadSafe<MyFoo>;
-// ~MyFoo();
-template <class T, typename Traits = DefaultRefCountedThreadSafeTraits<T> >
-class RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase {
- public:
- RefCountedThreadSafe() {}
-
- void AddRef() const {
- subtle::RefCountedThreadSafeBase::AddRef();
- }
-
- void Release() const {
- if (subtle::RefCountedThreadSafeBase::Release()) {
- Traits::Destruct(static_cast<const T*>(this));
- }
- }
-
- protected:
- ~RefCountedThreadSafe() {}
-
- private:
- friend struct DefaultRefCountedThreadSafeTraits<T>;
- static void DeleteInternal(const T* x) { delete x; }
-
- DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe);
-};
-
-//
-// A thread-safe wrapper for some piece of data so we can place other
-// things in scoped_refptrs<>.
-//
-template<typename T>
-class RefCountedData
- : public base::RefCountedThreadSafe< base::RefCountedData<T> > {
- public:
- RefCountedData() : data() {}
- RefCountedData(const T& in_value) : data(in_value) {}
-
- T data;
-
- private:
- friend class base::RefCountedThreadSafe<base::RefCountedData<T> >;
- ~RefCountedData() {}
-};
-
-} // namespace base
-
-//
-// A smart pointer class for reference counted objects. Use this class instead
-// of calling AddRef and Release manually on a reference counted object to
-// avoid common memory leaks caused by forgetting to Release an object
-// reference. Sample usage:
-//
-// class MyFoo : public RefCounted<MyFoo> {
-// ...
-// };
-//
-// void some_function() {
-// scoped_refptr<MyFoo> foo = new MyFoo();
-// foo->Method(param);
-// // |foo| is released when this function returns
-// }
-//
-// void some_other_function() {
-// scoped_refptr<MyFoo> foo = new MyFoo();
-// ...
-// foo = NULL; // explicitly releases |foo|
-// ...
-// if (foo)
-// foo->Method(param);
-// }
-//
-// The above examples show how scoped_refptr<T> acts like a pointer to T.
-// Given two scoped_refptr<T> classes, it is also possible to exchange
-// references between the two objects, like so:
-//
-// {
-// scoped_refptr<MyFoo> a = new MyFoo();
-// scoped_refptr<MyFoo> b;
-//
-// b.swap(a);
-// // now, |b| references the MyFoo object, and |a| references NULL.
-// }
-//
-// To make both |a| and |b| in the above example reference the same MyFoo
-// object, simply use the assignment operator:
-//
-// {
-// scoped_refptr<MyFoo> a = new MyFoo();
-// scoped_refptr<MyFoo> b;
-//
-// b = a;
-// // now, |a| and |b| each own a reference to the same MyFoo object.
-// }
-//
-template <class T>
-class scoped_refptr {
- public:
- typedef T element_type;
-
- scoped_refptr() : ptr_(NULL) {
- }
-
- scoped_refptr(T* p) : ptr_(p) {
- if (ptr_)
- AddRef(ptr_);
- }
-
- // Copy constructor.
- scoped_refptr(const scoped_refptr<T>& r) : ptr_(r.ptr_) {
- if (ptr_)
- AddRef(ptr_);
- }
-
- // Copy conversion constructor.
- template <typename U>
- scoped_refptr(const scoped_refptr<U>& r) : ptr_(r.get()) {
- if (ptr_)
- AddRef(ptr_);
- }
-
- // Move constructor. This is required in addition to the conversion
- // constructor below in order for clang to warn about pessimizing moves.
- scoped_refptr(scoped_refptr&& r) : ptr_(r.get()) { r.ptr_ = nullptr; }
-
- // Move conversion constructor.
- template <typename U>
- scoped_refptr(scoped_refptr<U>&& r) : ptr_(r.get()) {
- r.ptr_ = nullptr;
- }
-
- ~scoped_refptr() {
- if (ptr_)
- Release(ptr_);
- }
-
- T* get() const { return ptr_; }
-
- T& operator*() const {
- assert(ptr_ != NULL);
- return *ptr_;
- }
-
- T* operator->() const {
- assert(ptr_ != NULL);
- return ptr_;
- }
-
- scoped_refptr<T>& operator=(T* p) {
- // AddRef first so that self assignment should work
- if (p)
- AddRef(p);
- T* old_ptr = ptr_;
- ptr_ = p;
- if (old_ptr)
- Release(old_ptr);
- return *this;
- }
-
- scoped_refptr<T>& operator=(const scoped_refptr<T>& r) {
- return *this = r.ptr_;
- }
-
- template <typename U>
- scoped_refptr<T>& operator=(const scoped_refptr<U>& r) {
- return *this = r.get();
- }
-
- scoped_refptr<T>& operator=(scoped_refptr<T>&& r) {
- scoped_refptr<T>(std::move(r)).swap(*this);
- return *this;
- }
-
- template <typename U>
- scoped_refptr<T>& operator=(scoped_refptr<U>&& r) {
- scoped_refptr<T>(std::move(r)).swap(*this);
- return *this;
- }
-
- void swap(T** pp) {
- T* p = ptr_;
- ptr_ = *pp;
- *pp = p;
- }
-
- void swap(scoped_refptr<T>& r) {
- swap(&r.ptr_);
- }
-
- private:
- template <typename U> friend class scoped_refptr;
-
- // Allow scoped_refptr<T> to be used in boolean expressions, but not
- // implicitly convertible to a real bool (which is dangerous).
- //
- // Note that this trick is only safe when the == and != operators
- // are declared explicitly, as otherwise "refptr1 == refptr2"
- // will compile but do the wrong thing (i.e., convert to Testable
- // and then do the comparison).
- typedef T* scoped_refptr::*Testable;
-
- public:
- operator Testable() const { return ptr_ ? &scoped_refptr::ptr_ : nullptr; }
-
- template <typename U>
- bool operator==(const scoped_refptr<U>& rhs) const {
- return ptr_ == rhs.get();
- }
-
- template <typename U>
- bool operator!=(const scoped_refptr<U>& rhs) const {
- return !operator==(rhs);
- }
-
- template <typename U>
- bool operator<(const scoped_refptr<U>& rhs) const {
- return ptr_ < rhs.get();
- }
-
- protected:
- T* ptr_;
-
- private:
- // Non-inline helpers to allow:
- // class Opaque;
- // extern template class scoped_refptr<Opaque>;
- // Otherwise the compiler will complain that Opaque is an incomplete type.
- static void AddRef(T* ptr);
- static void Release(T* ptr);
-};
-
-template <typename T>
-void scoped_refptr<T>::AddRef(T* ptr) {
- ptr->AddRef();
-}
-
-template <typename T>
-void scoped_refptr<T>::Release(T* ptr) {
- ptr->Release();
-}
-
-// Handy utility for creating a scoped_refptr<T> out of a T* explicitly without
-// having to retype all the template arguments
-template <typename T>
-scoped_refptr<T> make_scoped_refptr(T* t) {
- return scoped_refptr<T>(t);
-}
-
-// Temporary operator overloads to facilitate the transition. See
-// https://crbug.com/110610.
-template <typename T, typename U>
-bool operator==(const scoped_refptr<T>& lhs, const U* rhs) {
- return lhs.get() == rhs;
-}
-
-template <typename T, typename U>
-bool operator==(const T* lhs, const scoped_refptr<U>& rhs) {
- return lhs == rhs.get();
-}
-
-template <typename T, typename U>
-bool operator!=(const scoped_refptr<T>& lhs, const U* rhs) {
- return !operator==(lhs, rhs);
-}
-
-template <typename T, typename U>
-bool operator!=(const T* lhs, const scoped_refptr<U>& rhs) {
- return !operator==(lhs, rhs);
-}
-
-template <typename T>
-std::ostream& operator<<(std::ostream& out, const scoped_refptr<T>& p) {
- return out << p.get();
-}
-
-#endif // BASE_MEMORY_REF_COUNTED_H_
diff --git a/security/sandbox/chromium/base/memory/scoped_ptr.h b/security/sandbox/chromium/base/memory/scoped_ptr.h
deleted file mode 100644
index 282a01486..000000000
--- a/security/sandbox/chromium/base/memory/scoped_ptr.h
+++ /dev/null
@@ -1,607 +0,0 @@
-// 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.
-
-// Scopers help you manage ownership of a pointer, helping you easily manage a
-// pointer within a scope, and automatically destroying the pointer at the end
-// of a scope. There are two main classes you will use, which correspond to the
-// operators new/delete and new[]/delete[].
-//
-// Example usage (scoped_ptr<T>):
-// {
-// scoped_ptr<Foo> foo(new Foo("wee"));
-// } // foo goes out of scope, releasing the pointer with it.
-//
-// {
-// scoped_ptr<Foo> foo; // No pointer managed.
-// foo.reset(new Foo("wee")); // Now a pointer is managed.
-// foo.reset(new Foo("wee2")); // Foo("wee") was destroyed.
-// foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed.
-// foo->Method(); // Foo::Method() called.
-// foo.get()->Method(); // Foo::Method() called.
-// SomeFunc(foo.release()); // SomeFunc takes ownership, foo no longer
-// // manages a pointer.
-// foo.reset(new Foo("wee4")); // foo manages a pointer again.
-// foo.reset(); // Foo("wee4") destroyed, foo no longer
-// // manages a pointer.
-// } // foo wasn't managing a pointer, so nothing was destroyed.
-//
-// Example usage (scoped_ptr<T[]>):
-// {
-// scoped_ptr<Foo[]> foo(new Foo[100]);
-// foo.get()->Method(); // Foo::Method on the 0th element.
-// foo[10].Method(); // Foo::Method on the 10th element.
-// }
-//
-// These scopers also implement part of the functionality of C++11 unique_ptr
-// in that they are "movable but not copyable." You can use the scopers in
-// the parameter and return types of functions to signify ownership transfer
-// in to and out of a function. When calling a function that has a scoper
-// as the argument type, it must be called with an rvalue of a scoper, which
-// can be created by using std::move(), or the result of another function that
-// generates a temporary; passing by copy will NOT work. Here is an example
-// using scoped_ptr:
-//
-// void TakesOwnership(scoped_ptr<Foo> arg) {
-// // Do something with arg.
-// }
-// scoped_ptr<Foo> CreateFoo() {
-// // No need for calling std::move() for returning a move-only value, or
-// // when you already have an rvalue as we do here.
-// return scoped_ptr<Foo>(new Foo("new"));
-// }
-// scoped_ptr<Foo> PassThru(scoped_ptr<Foo> arg) {
-// return arg;
-// }
-//
-// {
-// scoped_ptr<Foo> ptr(new Foo("yay")); // ptr manages Foo("yay").
-// TakesOwnership(std::move(ptr)); // ptr no longer owns Foo("yay").
-// scoped_ptr<Foo> ptr2 = CreateFoo(); // ptr2 owns the return Foo.
-// scoped_ptr<Foo> ptr3 = // ptr3 now owns what was in ptr2.
-// PassThru(std::move(ptr2)); // ptr2 is correspondingly nullptr.
-// }
-//
-// Notice that if you do not call std::move() when returning from PassThru(), or
-// when invoking TakesOwnership(), the code will not compile because scopers
-// are not copyable; they only implement move semantics which require calling
-// the std::move() function to signify a destructive transfer of state.
-// CreateFoo() is different though because we are constructing a temporary on
-// the return line and thus can avoid needing to call std::move().
-//
-// The conversion move-constructor properly handles upcast in initialization,
-// i.e. you can use a scoped_ptr<Child> to initialize a scoped_ptr<Parent>:
-//
-// scoped_ptr<Foo> foo(new Foo());
-// scoped_ptr<FooParent> parent(std::move(foo));
-
-#ifndef BASE_MEMORY_SCOPED_PTR_H_
-#define BASE_MEMORY_SCOPED_PTR_H_
-
-// This is an implementation designed to match the anticipated future TR2
-// implementation of the scoped_ptr class.
-
-#include <assert.h>
-#include <stddef.h>
-#include <stdlib.h>
-
-#include <iosfwd>
-#include <memory>
-#include <type_traits>
-#include <utility>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/move.h"
-#include "base/template_util.h"
-
-namespace base {
-
-namespace subtle {
-class RefCountedBase;
-class RefCountedThreadSafeBase;
-} // namespace subtle
-
-// Function object which invokes 'free' on its parameter, which must be
-// a pointer. Can be used to store malloc-allocated pointers in scoped_ptr:
-//
-// scoped_ptr<int, base::FreeDeleter> foo_ptr(
-// static_cast<int*>(malloc(sizeof(int))));
-struct FreeDeleter {
- inline void operator()(void* ptr) const {
- free(ptr);
- }
-};
-
-namespace internal {
-
-template <typename T> struct IsNotRefCounted {
- enum {
- value = !base::is_convertible<T*, base::subtle::RefCountedBase*>::value &&
- !base::is_convertible<T*, base::subtle::RefCountedThreadSafeBase*>::
- value
- };
-};
-
-// Minimal implementation of the core logic of scoped_ptr, suitable for
-// reuse in both scoped_ptr and its specializations.
-template <class T, class D>
-class scoped_ptr_impl {
- public:
- explicit scoped_ptr_impl(T* p) : data_(p) {}
-
- // Initializer for deleters that have data parameters.
- scoped_ptr_impl(T* p, const D& d) : data_(p, d) {}
-
- // Templated constructor that destructively takes the value from another
- // scoped_ptr_impl.
- template <typename U, typename V>
- scoped_ptr_impl(scoped_ptr_impl<U, V>* other)
- : data_(other->release(), other->get_deleter()) {
- // We do not support move-only deleters. We could modify our move
- // emulation to have base::subtle::move() and base::subtle::forward()
- // functions that are imperfect emulations of their C++11 equivalents,
- // but until there's a requirement, just assume deleters are copyable.
- }
-
- template <typename U, typename V>
- void TakeState(scoped_ptr_impl<U, V>* other) {
- // See comment in templated constructor above regarding lack of support
- // for move-only deleters.
- reset(other->release());
- get_deleter() = other->get_deleter();
- }
-
- ~scoped_ptr_impl() {
- // Match libc++, which calls reset() in its destructor.
- // Use nullptr as the new value for three reasons:
- // 1. libc++ does it.
- // 2. Avoids infinitely recursing into destructors if two classes are owned
- // in a reference cycle (see ScopedPtrTest.ReferenceCycle).
- // 3. If |this| is accessed in the future, in a use-after-free bug, attempts
- // to dereference |this|'s pointer should cause either a failure or a
- // segfault closer to the problem. If |this| wasn't reset to nullptr,
- // the access would cause the deleted memory to be read or written
- // leading to other more subtle issues.
- reset(nullptr);
- }
-
- void reset(T* p) {
- // Match C++11's definition of unique_ptr::reset(), which requires changing
- // the pointer before invoking the deleter on the old pointer. This prevents
- // |this| from being accessed after the deleter is run, which may destroy
- // |this|.
- T* old = data_.ptr;
- data_.ptr = p;
- if (old != nullptr)
- static_cast<D&>(data_)(old);
- }
-
- T* get() const { return data_.ptr; }
-
- D& get_deleter() { return data_; }
- const D& get_deleter() const { return data_; }
-
- void swap(scoped_ptr_impl& p2) {
- // Standard swap idiom: 'using std::swap' ensures that std::swap is
- // present in the overload set, but we call swap unqualified so that
- // any more-specific overloads can be used, if available.
- using std::swap;
- swap(static_cast<D&>(data_), static_cast<D&>(p2.data_));
- swap(data_.ptr, p2.data_.ptr);
- }
-
- T* release() {
- T* old_ptr = data_.ptr;
- data_.ptr = nullptr;
- return old_ptr;
- }
-
- private:
- // Needed to allow type-converting constructor.
- template <typename U, typename V> friend class scoped_ptr_impl;
-
- // Use the empty base class optimization to allow us to have a D
- // member, while avoiding any space overhead for it when D is an
- // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good
- // discussion of this technique.
- struct Data : public D {
- explicit Data(T* ptr_in) : ptr(ptr_in) {}
- Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {}
- T* ptr;
- };
-
- Data data_;
-
- DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl);
-};
-
-} // namespace internal
-
-} // namespace base
-
-// A scoped_ptr<T> is like a T*, except that the destructor of scoped_ptr<T>
-// automatically deletes the pointer it holds (if any).
-// That is, scoped_ptr<T> owns the T object that it points to.
-// Like a T*, a scoped_ptr<T> may hold either nullptr or a pointer to a T
-// object. Also like T*, scoped_ptr<T> is thread-compatible, and once you
-// dereference it, you get the thread safety guarantees of T.
-//
-// The size of scoped_ptr is small. On most compilers, when using the
-// std::default_delete, sizeof(scoped_ptr<T>) == sizeof(T*). Custom deleters
-// will increase the size proportional to whatever state they need to have. See
-// comments inside scoped_ptr_impl<> for details.
-//
-// Current implementation targets having a strict subset of C++11's
-// unique_ptr<> features. Known deficiencies include not supporting move-only
-// deleteres, function pointers as deleters, and deleters with reference
-// types.
-template <class T, class D = std::default_delete<T>>
-class scoped_ptr {
- DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND(scoped_ptr)
-
- static_assert(!std::is_array<T>::value,
- "scoped_ptr doesn't support array with size");
- static_assert(base::internal::IsNotRefCounted<T>::value,
- "T is a refcounted type and needs a scoped_refptr");
-
- public:
- // The element and deleter types.
- using element_type = T;
- using deleter_type = D;
-
- // Constructor. Defaults to initializing with nullptr.
- scoped_ptr() : impl_(nullptr) {}
-
- // Constructor. Takes ownership of p.
- explicit scoped_ptr(element_type* p) : impl_(p) {}
-
- // Constructor. Allows initialization of a stateful deleter.
- scoped_ptr(element_type* p, const D& d) : impl_(p, d) {}
-
- // Constructor. Allows construction from a nullptr.
- scoped_ptr(std::nullptr_t) : impl_(nullptr) {}
-
- // Move constructor.
- //
- // IMPLEMENTATION NOTE: Clang requires a move constructor to be defined (and
- // not just the conversion constructor) in order to warn on pessimizing moves.
- // The requirements for the move constructor are specified in C++11
- // 20.7.1.2.1.15-17, which has some subtleties around reference deleters. As
- // we don't support reference (or move-only) deleters, the post conditions are
- // trivially true: we always copy construct the deleter from other's deleter.
- scoped_ptr(scoped_ptr&& other) : impl_(&other.impl_) {}
-
- // Conversion constructor. Allows construction from a scoped_ptr rvalue for a
- // convertible type and deleter.
- //
- // IMPLEMENTATION NOTE: C++ 20.7.1.2.1.19 requires this constructor to only
- // participate in overload resolution if all the following are true:
- // - U is implicitly convertible to T: this is important for 2 reasons:
- // 1. So type traits don't incorrectly return true, e.g.
- // std::is_convertible<scoped_ptr<Base>, scoped_ptr<Derived>>::value
- // should be false.
- // 2. To make sure code like this compiles:
- // void F(scoped_ptr<int>);
- // void F(scoped_ptr<Base>);
- // // Ambiguous since both conversion constructors match.
- // F(scoped_ptr<Derived>());
- // - U is not an array type: to prevent conversions from scoped_ptr<T[]> to
- // scoped_ptr<T>.
- // - D is a reference type and E is the same type, or D is not a reference
- // type and E is implicitly convertible to D: again, we don't support
- // reference deleters, so we only worry about the latter requirement.
- template <typename U,
- typename E,
- typename std::enable_if<!std::is_array<U>::value &&
- std::is_convertible<U*, T*>::value &&
- std::is_convertible<E, D>::value>::type* =
- nullptr>
- scoped_ptr(scoped_ptr<U, E>&& other)
- : impl_(&other.impl_) {}
-
- // operator=.
- //
- // IMPLEMENTATION NOTE: Unlike the move constructor, Clang does not appear to
- // require a move assignment operator to trigger the pessimizing move warning:
- // in this case, the warning triggers when moving a temporary. For consistency
- // with the move constructor, we define it anyway. C++11 20.7.1.2.3.1-3
- // defines several requirements around this: like the move constructor, the
- // requirements are simplified by the fact that we don't support move-only or
- // reference deleters.
- scoped_ptr& operator=(scoped_ptr&& rhs) {
- impl_.TakeState(&rhs.impl_);
- return *this;
- }
-
- // operator=. Allows assignment from a scoped_ptr rvalue for a convertible
- // type and deleter.
- //
- // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from
- // the normal move assignment operator. C++11 20.7.1.2.3.4-7 contains the
- // requirement for this operator, but like the conversion constructor, the
- // requirements are greatly simplified by not supporting move-only or
- // reference deleters.
- template <typename U,
- typename E,
- typename std::enable_if<!std::is_array<U>::value &&
- std::is_convertible<U*, T*>::value &&
- // Note that this really should be
- // std::is_assignable, but <type_traits>
- // appears to be missing this on some
- // platforms. This is close enough (though
- // it's not the same).
- std::is_convertible<D, E>::value>::type* =
- nullptr>
- scoped_ptr& operator=(scoped_ptr<U, E>&& rhs) {
- impl_.TakeState(&rhs.impl_);
- return *this;
- }
-
- // operator=. Allows assignment from a nullptr. Deletes the currently owned
- // object, if any.
- scoped_ptr& operator=(std::nullptr_t) {
- reset();
- return *this;
- }
-
- // Reset. Deletes the currently owned object, if any.
- // Then takes ownership of a new object, if given.
- void reset(element_type* p = nullptr) { impl_.reset(p); }
-
- // Accessors to get the owned object.
- // operator* and operator-> will assert() if there is no current object.
- element_type& operator*() const {
- assert(impl_.get() != nullptr);
- return *impl_.get();
- }
- element_type* operator->() const {
- assert(impl_.get() != nullptr);
- return impl_.get();
- }
- element_type* get() const { return impl_.get(); }
-
- // Access to the deleter.
- deleter_type& get_deleter() { return impl_.get_deleter(); }
- const deleter_type& get_deleter() const { return impl_.get_deleter(); }
-
- // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
- // implicitly convertible to a real bool (which is dangerous).
- //
- // Note that this trick is only safe when the == and != operators
- // are declared explicitly, as otherwise "scoped_ptr1 ==
- // scoped_ptr2" will compile but do the wrong thing (i.e., convert
- // to Testable and then do the comparison).
- private:
- typedef base::internal::scoped_ptr_impl<element_type, deleter_type>
- scoped_ptr::*Testable;
-
- public:
- operator Testable() const {
- return impl_.get() ? &scoped_ptr::impl_ : nullptr;
- }
-
- // Swap two scoped pointers.
- void swap(scoped_ptr& p2) {
- impl_.swap(p2.impl_);
- }
-
- // Release a pointer.
- // The return value is the current pointer held by this object. If this object
- // holds a nullptr, the return value is nullptr. After this operation, this
- // object will hold a nullptr, and will not own the object any more.
- element_type* release() WARN_UNUSED_RESULT {
- return impl_.release();
- }
-
- private:
- // Needed to reach into |impl_| in the constructor.
- template <typename U, typename V> friend class scoped_ptr;
- base::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
-
- // Forbidden for API compatibility with std::unique_ptr.
- explicit scoped_ptr(int disallow_construction_from_null);
-};
-
-template <class T, class D>
-class scoped_ptr<T[], D> {
- DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND(scoped_ptr)
-
- public:
- // The element and deleter types.
- using element_type = T;
- using deleter_type = D;
-
- // Constructor. Defaults to initializing with nullptr.
- scoped_ptr() : impl_(nullptr) {}
-
- // Constructor. Stores the given array. Note that the argument's type
- // must exactly match T*. In particular:
- // - it cannot be a pointer to a type derived from T, because it is
- // inherently unsafe in the general case to access an array through a
- // pointer whose dynamic type does not match its static type (eg., if
- // T and the derived types had different sizes access would be
- // incorrectly calculated). Deletion is also always undefined
- // (C++98 [expr.delete]p3). If you're doing this, fix your code.
- // - it cannot be const-qualified differently from T per unique_ptr spec
- // (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting
- // to work around this may use const_cast<const T*>().
- explicit scoped_ptr(element_type* array) : impl_(array) {}
-
- // Constructor. Allows construction from a nullptr.
- scoped_ptr(std::nullptr_t) : impl_(nullptr) {}
-
- // Constructor. Allows construction from a scoped_ptr rvalue.
- scoped_ptr(scoped_ptr&& other) : impl_(&other.impl_) {}
-
- // operator=. Allows assignment from a scoped_ptr rvalue.
- scoped_ptr& operator=(scoped_ptr&& rhs) {
- impl_.TakeState(&rhs.impl_);
- return *this;
- }
-
- // operator=. Allows assignment from a nullptr. Deletes the currently owned
- // array, if any.
- scoped_ptr& operator=(std::nullptr_t) {
- reset();
- return *this;
- }
-
- // Reset. Deletes the currently owned array, if any.
- // Then takes ownership of a new object, if given.
- void reset(element_type* array = nullptr) { impl_.reset(array); }
-
- // Accessors to get the owned array.
- element_type& operator[](size_t i) const {
- assert(impl_.get() != nullptr);
- return impl_.get()[i];
- }
- element_type* get() const { return impl_.get(); }
-
- // Access to the deleter.
- deleter_type& get_deleter() { return impl_.get_deleter(); }
- const deleter_type& get_deleter() const { return impl_.get_deleter(); }
-
- // Allow scoped_ptr<element_type> to be used in boolean expressions, but not
- // implicitly convertible to a real bool (which is dangerous).
- private:
- typedef base::internal::scoped_ptr_impl<element_type, deleter_type>
- scoped_ptr::*Testable;
-
- public:
- operator Testable() const {
- return impl_.get() ? &scoped_ptr::impl_ : nullptr;
- }
-
- // Swap two scoped pointers.
- void swap(scoped_ptr& p2) {
- impl_.swap(p2.impl_);
- }
-
- // Release a pointer.
- // The return value is the current pointer held by this object. If this object
- // holds a nullptr, the return value is nullptr. After this operation, this
- // object will hold a nullptr, and will not own the object any more.
- element_type* release() WARN_UNUSED_RESULT {
- return impl_.release();
- }
-
- private:
- // Force element_type to be a complete type.
- enum { type_must_be_complete = sizeof(element_type) };
-
- // Actually hold the data.
- base::internal::scoped_ptr_impl<element_type, deleter_type> impl_;
-
- // Disable initialization from any type other than element_type*, by
- // providing a constructor that matches such an initialization, but is
- // private and has no definition. This is disabled because it is not safe to
- // call delete[] on an array whose static type does not match its dynamic
- // type.
- template <typename U> explicit scoped_ptr(U* array);
- explicit scoped_ptr(int disallow_construction_from_null);
-
- // Disable reset() from any type other than element_type*, for the same
- // reasons as the constructor above.
- template <typename U> void reset(U* array);
- void reset(int disallow_reset_from_null);
-};
-
-// Free functions
-template <class T, class D>
-void swap(scoped_ptr<T, D>& p1, scoped_ptr<T, D>& p2) {
- p1.swap(p2);
-}
-
-template <class T1, class D1, class T2, class D2>
-bool operator==(const scoped_ptr<T1, D1>& p1, const scoped_ptr<T2, D2>& p2) {
- return p1.get() == p2.get();
-}
-template <class T, class D>
-bool operator==(const scoped_ptr<T, D>& p, std::nullptr_t) {
- return p.get() == nullptr;
-}
-template <class T, class D>
-bool operator==(std::nullptr_t, const scoped_ptr<T, D>& p) {
- return p.get() == nullptr;
-}
-
-template <class T1, class D1, class T2, class D2>
-bool operator!=(const scoped_ptr<T1, D1>& p1, const scoped_ptr<T2, D2>& p2) {
- return !(p1 == p2);
-}
-template <class T, class D>
-bool operator!=(const scoped_ptr<T, D>& p, std::nullptr_t) {
- return !(p == nullptr);
-}
-template <class T, class D>
-bool operator!=(std::nullptr_t, const scoped_ptr<T, D>& p) {
- return !(p == nullptr);
-}
-
-template <class T1, class D1, class T2, class D2>
-bool operator<(const scoped_ptr<T1, D1>& p1, const scoped_ptr<T2, D2>& p2) {
- return p1.get() < p2.get();
-}
-template <class T, class D>
-bool operator<(const scoped_ptr<T, D>& p, std::nullptr_t) {
- return p.get() < nullptr;
-}
-template <class T, class D>
-bool operator<(std::nullptr_t, const scoped_ptr<T, D>& p) {
- return nullptr < p.get();
-}
-
-template <class T1, class D1, class T2, class D2>
-bool operator>(const scoped_ptr<T1, D1>& p1, const scoped_ptr<T2, D2>& p2) {
- return p2 < p1;
-}
-template <class T, class D>
-bool operator>(const scoped_ptr<T, D>& p, std::nullptr_t) {
- return nullptr < p;
-}
-template <class T, class D>
-bool operator>(std::nullptr_t, const scoped_ptr<T, D>& p) {
- return p < nullptr;
-}
-
-template <class T1, class D1, class T2, class D2>
-bool operator<=(const scoped_ptr<T1, D1>& p1, const scoped_ptr<T2, D2>& p2) {
- return !(p1 > p2);
-}
-template <class T, class D>
-bool operator<=(const scoped_ptr<T, D>& p, std::nullptr_t) {
- return !(p > nullptr);
-}
-template <class T, class D>
-bool operator<=(std::nullptr_t, const scoped_ptr<T, D>& p) {
- return !(nullptr > p);
-}
-
-template <class T1, class D1, class T2, class D2>
-bool operator>=(const scoped_ptr<T1, D1>& p1, const scoped_ptr<T2, D2>& p2) {
- return !(p1 < p2);
-}
-template <class T, class D>
-bool operator>=(const scoped_ptr<T, D>& p, std::nullptr_t) {
- return !(p < nullptr);
-}
-template <class T, class D>
-bool operator>=(std::nullptr_t, const scoped_ptr<T, D>& p) {
- return !(nullptr < p);
-}
-
-// A function to convert T* into scoped_ptr<T>
-// Doing e.g. make_scoped_ptr(new FooBarBaz<type>(arg)) is a shorter notation
-// for scoped_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
-template <typename T>
-scoped_ptr<T> make_scoped_ptr(T* ptr) {
- return scoped_ptr<T>(ptr);
-}
-
-template <typename T>
-std::ostream& operator<<(std::ostream& out, const scoped_ptr<T>& p) {
- return out << p.get();
-}
-
-#endif // BASE_MEMORY_SCOPED_PTR_H_
diff --git a/security/sandbox/chromium/base/memory/singleton.cc b/security/sandbox/chromium/base/memory/singleton.cc
deleted file mode 100644
index f68ecaa8d..000000000
--- a/security/sandbox/chromium/base/memory/singleton.cc
+++ /dev/null
@@ -1,34 +0,0 @@
-// 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/memory/singleton.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-namespace internal {
-
-subtle::AtomicWord WaitForInstance(subtle::AtomicWord* instance) {
- // Handle the race. Another thread beat us and either:
- // - Has the object in BeingCreated state
- // - Already has the object created...
- // We know value != NULL. It could be kBeingCreatedMarker, or a valid ptr.
- // Unless your constructor can be very time consuming, it is very unlikely
- // to hit this race. When it does, we just spin and yield the thread until
- // the object has been created.
- subtle::AtomicWord value;
- while (true) {
- // The load has acquire memory ordering as the thread which reads the
- // instance pointer must acquire visibility over the associated data.
- // The pairing Release_Store operation is in Singleton::get().
- value = subtle::Acquire_Load(instance);
- if (value != kBeingCreatedMarker)
- break;
- PlatformThread::YieldCurrentThread();
- }
- return value;
-}
-
-} // namespace internal
-} // namespace base
-
diff --git a/security/sandbox/chromium/base/memory/singleton.h b/security/sandbox/chromium/base/memory/singleton.h
deleted file mode 100644
index 79e4441a8..000000000
--- a/security/sandbox/chromium/base/memory/singleton.h
+++ /dev/null
@@ -1,284 +0,0 @@
-// 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.
-
-// PLEASE READ: Do you really need a singleton?
-//
-// Singletons make it hard to determine the lifetime of an object, which can
-// lead to buggy code and spurious crashes.
-//
-// Instead of adding another singleton into the mix, try to identify either:
-// a) An existing singleton that can manage your object's lifetime
-// b) Locations where you can deterministically create the object and pass
-// into other objects
-//
-// If you absolutely need a singleton, please keep them as trivial as possible
-// and ideally a leaf dependency. Singletons get problematic when they attempt
-// to do too much in their destructor or have circular dependencies.
-
-#ifndef BASE_MEMORY_SINGLETON_H_
-#define BASE_MEMORY_SINGLETON_H_
-
-#include "base/at_exit.h"
-#include "base/atomicops.h"
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/memory/aligned_memory.h"
-#include "base/threading/thread_restrictions.h"
-
-namespace base {
-namespace internal {
-
-// Our AtomicWord doubles as a spinlock, where a value of
-// kBeingCreatedMarker means the spinlock is being held for creation.
-static const subtle::AtomicWord kBeingCreatedMarker = 1;
-
-// We pull out some of the functionality into a non-templated function, so that
-// we can implement the more complicated pieces out of line in the .cc file.
-BASE_EXPORT subtle::AtomicWord WaitForInstance(subtle::AtomicWord* instance);
-
-class DeleteTraceLogForTesting;
-
-} // namespace internal
-
-
-// Default traits for Singleton<Type>. Calls operator new and operator delete on
-// the object. Registers automatic deletion at process exit.
-// Overload if you need arguments or another memory allocation function.
-template<typename Type>
-struct DefaultSingletonTraits {
- // Allocates the object.
- static Type* New() {
- // The parenthesis is very important here; it forces POD type
- // initialization.
- return new Type();
- }
-
- // Destroys the object.
- static void Delete(Type* x) {
- delete x;
- }
-
- // Set to true to automatically register deletion of the object on process
- // exit. See below for the required call that makes this happen.
- static const bool kRegisterAtExit = true;
-
-#ifndef NDEBUG
- // Set to false to disallow access on a non-joinable thread. This is
- // different from kRegisterAtExit because StaticMemorySingletonTraits allows
- // access on non-joinable threads, and gracefully handles this.
- static const bool kAllowedToAccessOnNonjoinableThread = false;
-#endif
-};
-
-
-// Alternate traits for use with the Singleton<Type>. Identical to
-// DefaultSingletonTraits except that the Singleton will not be cleaned up
-// at exit.
-template<typename Type>
-struct LeakySingletonTraits : public DefaultSingletonTraits<Type> {
- static const bool kRegisterAtExit = false;
-#ifndef NDEBUG
- static const bool kAllowedToAccessOnNonjoinableThread = true;
-#endif
-};
-
-
-// Alternate traits for use with the Singleton<Type>. Allocates memory
-// for the singleton instance from a static buffer. The singleton will
-// be cleaned up at exit, but can't be revived after destruction unless
-// the Resurrect() method is called.
-//
-// This is useful for a certain category of things, notably logging and
-// tracing, where the singleton instance is of a type carefully constructed to
-// be safe to access post-destruction.
-// In logging and tracing you'll typically get stray calls at odd times, like
-// during static destruction, thread teardown and the like, and there's a
-// termination race on the heap-based singleton - e.g. if one thread calls
-// get(), but then another thread initiates AtExit processing, the first thread
-// may call into an object residing in unallocated memory. If the instance is
-// allocated from the data segment, then this is survivable.
-//
-// The destructor is to deallocate system resources, in this case to unregister
-// a callback the system will invoke when logging levels change. Note that
-// this is also used in e.g. Chrome Frame, where you have to allow for the
-// possibility of loading briefly into someone else's process space, and
-// so leaking is not an option, as that would sabotage the state of your host
-// process once you've unloaded.
-template <typename Type>
-struct StaticMemorySingletonTraits {
- // WARNING: User has to deal with get() in the singleton class
- // this is traits for returning NULL.
- static Type* New() {
- // Only constructs once and returns pointer; otherwise returns NULL.
- if (subtle::NoBarrier_AtomicExchange(&dead_, 1))
- return NULL;
-
- return new(buffer_.void_data()) Type();
- }
-
- static void Delete(Type* p) {
- if (p != NULL)
- p->Type::~Type();
- }
-
- static const bool kRegisterAtExit = true;
- static const bool kAllowedToAccessOnNonjoinableThread = true;
-
- // Exposed for unittesting.
- static void Resurrect() { subtle::NoBarrier_Store(&dead_, 0); }
-
- private:
- static AlignedMemory<sizeof(Type), ALIGNOF(Type)> buffer_;
- // Signal the object was already deleted, so it is not revived.
- static subtle::Atomic32 dead_;
-};
-
-template <typename Type>
-AlignedMemory<sizeof(Type), ALIGNOF(Type)>
- StaticMemorySingletonTraits<Type>::buffer_;
-template <typename Type>
-subtle::Atomic32 StaticMemorySingletonTraits<Type>::dead_ = 0;
-
-// The Singleton<Type, Traits, DifferentiatingType> class manages a single
-// instance of Type which will be created on first use and will be destroyed at
-// normal process exit). The Trait::Delete function will not be called on
-// abnormal process exit.
-//
-// DifferentiatingType is used as a key to differentiate two different
-// singletons having the same memory allocation functions but serving a
-// different purpose. This is mainly used for Locks serving different purposes.
-//
-// Example usage:
-//
-// In your header:
-// template <typename T> struct DefaultSingletonTraits;
-// class FooClass {
-// public:
-// static FooClass* GetInstance(); <-- See comment below on this.
-// void Bar() { ... }
-// private:
-// FooClass() { ... }
-// friend struct DefaultSingletonTraits<FooClass>;
-//
-// DISALLOW_COPY_AND_ASSIGN(FooClass);
-// };
-//
-// In your source file:
-// #include "base/memory/singleton.h"
-// FooClass* FooClass::GetInstance() {
-// return Singleton<FooClass>::get();
-// }
-//
-// And to call methods on FooClass:
-// FooClass::GetInstance()->Bar();
-//
-// NOTE: The method accessing Singleton<T>::get() has to be named as GetInstance
-// and it is important that FooClass::GetInstance() is not inlined in the
-// header. This makes sure that when source files from multiple targets include
-// this header they don't end up with different copies of the inlined code
-// creating multiple copies of the singleton.
-//
-// Singleton<> has no non-static members and doesn't need to actually be
-// instantiated.
-//
-// This class is itself thread-safe. The underlying Type must of course be
-// thread-safe if you want to use it concurrently. Two parameters may be tuned
-// depending on the user's requirements.
-//
-// Glossary:
-// RAE = kRegisterAtExit
-//
-// On every platform, if Traits::RAE is true, the singleton will be destroyed at
-// process exit. More precisely it uses AtExitManager which requires an
-// object of this type to be instantiated. AtExitManager mimics the semantics
-// of atexit() such as LIFO order but under Windows is safer to call. For more
-// information see at_exit.h.
-//
-// If Traits::RAE is false, the singleton will not be freed at process exit,
-// thus the singleton will be leaked if it is ever accessed. Traits::RAE
-// shouldn't be false unless absolutely necessary. Remember that the heap where
-// the object is allocated may be destroyed by the CRT anyway.
-//
-// Caveats:
-// (a) Every call to get(), operator->() and operator*() incurs some overhead
-// (16ns on my P4/2.8GHz) to check whether the object has already been
-// initialized. You may wish to cache the result of get(); it will not
-// change.
-//
-// (b) Your factory function must never throw an exception. This class is not
-// exception-safe.
-//
-
-template <typename Type,
- typename Traits = DefaultSingletonTraits<Type>,
- typename DifferentiatingType = Type>
-class Singleton {
- private:
- // Classes using the Singleton<T> pattern should declare a GetInstance()
- // method and call Singleton::get() from within that.
- friend Type* Type::GetInstance();
-
- // Allow TraceLog tests to test tracing after OnExit.
- friend class internal::DeleteTraceLogForTesting;
-
- // This class is safe to be constructed and copy-constructed since it has no
- // member.
-
- // Return a pointer to the one true instance of the class.
- static Type* get() {
-#ifndef NDEBUG
- // Avoid making TLS lookup on release builds.
- if (!Traits::kAllowedToAccessOnNonjoinableThread)
- ThreadRestrictions::AssertSingletonAllowed();
-#endif
-
- // The load has acquire memory ordering as the thread which reads the
- // instance_ pointer must acquire visibility over the singleton data.
- subtle::AtomicWord value = subtle::Acquire_Load(&instance_);
- if (value != 0 && value != internal::kBeingCreatedMarker) {
- return reinterpret_cast<Type*>(value);
- }
-
- // Object isn't created yet, maybe we will get to create it, let's try...
- if (subtle::Acquire_CompareAndSwap(&instance_, 0,
- internal::kBeingCreatedMarker) == 0) {
- // instance_ was NULL and is now kBeingCreatedMarker. Only one thread
- // will ever get here. Threads might be spinning on us, and they will
- // stop right after we do this store.
- Type* newval = Traits::New();
-
- // Releases the visibility over instance_ to the readers.
- subtle::Release_Store(&instance_,
- reinterpret_cast<subtle::AtomicWord>(newval));
-
- if (newval != NULL && Traits::kRegisterAtExit)
- AtExitManager::RegisterCallback(OnExit, NULL);
-
- return newval;
- }
-
- // We hit a race. Wait for the other thread to complete it.
- value = internal::WaitForInstance(&instance_);
-
- return reinterpret_cast<Type*>(value);
- }
-
- // Adapter function for use with AtExit(). This should be called single
- // threaded, so don't use atomic operations.
- // Calling OnExit while singleton is in use by other threads is a mistake.
- static void OnExit(void* /*unused*/) {
- // AtExit should only ever be register after the singleton instance was
- // created. We should only ever get here with a valid instance_ pointer.
- Traits::Delete(reinterpret_cast<Type*>(subtle::NoBarrier_Load(&instance_)));
- instance_ = 0;
- }
- static subtle::AtomicWord instance_;
-};
-
-template <typename Type, typename Traits, typename DifferentiatingType>
-subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::instance_ = 0;
-
-} // namespace base
-
-#endif // BASE_MEMORY_SINGLETON_H_
diff --git a/security/sandbox/chromium/base/memory/weak_ptr.h b/security/sandbox/chromium/base/memory/weak_ptr.h
deleted file mode 100644
index 33d1e4736..000000000
--- a/security/sandbox/chromium/base/memory/weak_ptr.h
+++ /dev/null
@@ -1,345 +0,0 @@
-// 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.
-
-// Weak pointers are pointers to an object that do not affect its lifetime,
-// and which may be invalidated (i.e. reset to NULL) by the object, or its
-// owner, at any time, most commonly when the object is about to be deleted.
-
-// Weak pointers are useful when an object needs to be accessed safely by one
-// or more objects other than its owner, and those callers can cope with the
-// object vanishing and e.g. tasks posted to it being silently dropped.
-// Reference-counting such an object would complicate the ownership graph and
-// make it harder to reason about the object's lifetime.
-
-// EXAMPLE:
-//
-// class Controller {
-// public:
-// Controller() : weak_factory_(this) {}
-// void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); }
-// void WorkComplete(const Result& result) { ... }
-// private:
-// // Member variables should appear before the WeakPtrFactory, to ensure
-// // that any WeakPtrs to Controller are invalidated before its members
-// // variable's destructors are executed, rendering them invalid.
-// WeakPtrFactory<Controller> weak_factory_;
-// };
-//
-// class Worker {
-// public:
-// static void StartNew(const WeakPtr<Controller>& controller) {
-// Worker* worker = new Worker(controller);
-// // Kick off asynchronous processing...
-// }
-// private:
-// Worker(const WeakPtr<Controller>& controller)
-// : controller_(controller) {}
-// void DidCompleteAsynchronousProcessing(const Result& result) {
-// if (controller_)
-// controller_->WorkComplete(result);
-// }
-// WeakPtr<Controller> controller_;
-// };
-//
-// With this implementation a caller may use SpawnWorker() to dispatch multiple
-// Workers and subsequently delete the Controller, without waiting for all
-// Workers to have completed.
-
-// ------------------------- IMPORTANT: Thread-safety -------------------------
-
-// Weak pointers may be passed safely between threads, but must always be
-// dereferenced and invalidated on the same SequencedTaskRunner otherwise
-// checking the pointer would be racey.
-//
-// To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory
-// is dereferenced, the factory and its WeakPtrs become bound to the calling
-// thread or current SequencedWorkerPool token, and cannot be dereferenced or
-// invalidated on any other task runner. Bound WeakPtrs can still be handed
-// off to other task runners, e.g. to use to post tasks back to object on the
-// bound sequence.
-//
-// If all WeakPtr objects are destroyed or invalidated then the factory is
-// unbound from the SequencedTaskRunner/Thread. The WeakPtrFactory may then be
-// destroyed, or new WeakPtr objects may be used, from a different sequence.
-//
-// Thus, at least one WeakPtr object must exist and have been dereferenced on
-// the correct thread to enforce that other WeakPtr objects will enforce they
-// are used on the desired thread.
-
-#ifndef BASE_MEMORY_WEAK_PTR_H_
-#define BASE_MEMORY_WEAK_PTR_H_
-
-#include "base/base_export.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/sequence_checker.h"
-#include "base/template_util.h"
-
-namespace base {
-
-template <typename T> class SupportsWeakPtr;
-template <typename T> class WeakPtr;
-
-namespace internal {
-// These classes are part of the WeakPtr implementation.
-// DO NOT USE THESE CLASSES DIRECTLY YOURSELF.
-
-class BASE_EXPORT WeakReference {
- public:
- // Although Flag is bound to a specific SequencedTaskRunner, it may be
- // deleted from another via base::WeakPtr::~WeakPtr().
- class BASE_EXPORT Flag : public RefCountedThreadSafe<Flag> {
- public:
- Flag();
-
- void Invalidate();
- bool IsValid() const;
-
- private:
- friend class base::RefCountedThreadSafe<Flag>;
-
- ~Flag();
-
- SequenceChecker sequence_checker_;
- bool is_valid_;
- };
-
- WeakReference();
- explicit WeakReference(const Flag* flag);
- ~WeakReference();
-
- bool is_valid() const;
-
- private:
- scoped_refptr<const Flag> flag_;
-};
-
-class BASE_EXPORT WeakReferenceOwner {
- public:
- WeakReferenceOwner();
- ~WeakReferenceOwner();
-
- WeakReference GetRef() const;
-
- bool HasRefs() const {
- return flag_.get() && !flag_->HasOneRef();
- }
-
- void Invalidate();
-
- private:
- mutable scoped_refptr<WeakReference::Flag> flag_;
-};
-
-// This class simplifies the implementation of WeakPtr's type conversion
-// constructor by avoiding the need for a public accessor for ref_. A
-// WeakPtr<T> cannot access the private members of WeakPtr<U>, so this
-// base class gives us a way to access ref_ in a protected fashion.
-class BASE_EXPORT WeakPtrBase {
- public:
- WeakPtrBase();
- ~WeakPtrBase();
-
- protected:
- explicit WeakPtrBase(const WeakReference& ref);
-
- WeakReference ref_;
-};
-
-// This class provides a common implementation of common functions that would
-// otherwise get instantiated separately for each distinct instantiation of
-// SupportsWeakPtr<>.
-class SupportsWeakPtrBase {
- public:
- // A safe static downcast of a WeakPtr<Base> to WeakPtr<Derived>. This
- // conversion will only compile if there is exists a Base which inherits
- // from SupportsWeakPtr<Base>. See base::AsWeakPtr() below for a helper
- // function that makes calling this easier.
- template<typename Derived>
- static WeakPtr<Derived> StaticAsWeakPtr(Derived* t) {
- typedef
- is_convertible<Derived, internal::SupportsWeakPtrBase&> convertible;
- static_assert(convertible::value,
- "AsWeakPtr argument must inherit from SupportsWeakPtr");
- return AsWeakPtrImpl<Derived>(t, *t);
- }
-
- private:
- // This template function uses type inference to find a Base of Derived
- // which is an instance of SupportsWeakPtr<Base>. We can then safely
- // static_cast the Base* to a Derived*.
- template <typename Derived, typename Base>
- static WeakPtr<Derived> AsWeakPtrImpl(
- Derived* t, const SupportsWeakPtr<Base>&) {
- WeakPtr<Base> ptr = t->Base::AsWeakPtr();
- return WeakPtr<Derived>(ptr.ref_, static_cast<Derived*>(ptr.ptr_));
- }
-};
-
-} // namespace internal
-
-template <typename T> class WeakPtrFactory;
-
-// The WeakPtr class holds a weak reference to |T*|.
-//
-// This class is designed to be used like a normal pointer. You should always
-// null-test an object of this class before using it or invoking a method that
-// may result in the underlying object being destroyed.
-//
-// EXAMPLE:
-//
-// class Foo { ... };
-// WeakPtr<Foo> foo;
-// if (foo)
-// foo->method();
-//
-template <typename T>
-class WeakPtr : public internal::WeakPtrBase {
- public:
- WeakPtr() : ptr_(NULL) {
- }
-
- // Allow conversion from U to T provided U "is a" T. Note that this
- // is separate from the (implicit) copy constructor.
- template <typename U>
- WeakPtr(const WeakPtr<U>& other) : WeakPtrBase(other), ptr_(other.ptr_) {
- }
-
- T* get() const { return ref_.is_valid() ? ptr_ : NULL; }
-
- T& operator*() const {
- DCHECK(get() != NULL);
- return *get();
- }
- T* operator->() const {
- DCHECK(get() != NULL);
- return get();
- }
-
- // Allow WeakPtr<element_type> to be used in boolean expressions, but not
- // implicitly convertible to a real bool (which is dangerous).
- //
- // Note that this trick is only safe when the == and != operators
- // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2"
- // will compile but do the wrong thing (i.e., convert to Testable
- // and then do the comparison).
- private:
- typedef T* WeakPtr::*Testable;
-
- public:
- operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; }
-
- void reset() {
- ref_ = internal::WeakReference();
- ptr_ = NULL;
- }
-
- private:
- // Explicitly declare comparison operators as required by the bool
- // trick, but keep them private.
- template <class U> bool operator==(WeakPtr<U> const&) const;
- template <class U> bool operator!=(WeakPtr<U> const&) const;
-
- friend class internal::SupportsWeakPtrBase;
- template <typename U> friend class WeakPtr;
- friend class SupportsWeakPtr<T>;
- friend class WeakPtrFactory<T>;
-
- WeakPtr(const internal::WeakReference& ref, T* ptr)
- : WeakPtrBase(ref),
- ptr_(ptr) {
- }
-
- // This pointer is only valid when ref_.is_valid() is true. Otherwise, its
- // value is undefined (as opposed to NULL).
- T* ptr_;
-};
-
-// A class may be composed of a WeakPtrFactory and thereby
-// control how it exposes weak pointers to itself. This is helpful if you only
-// need weak pointers within the implementation of a class. This class is also
-// useful when working with primitive types. For example, you could have a
-// WeakPtrFactory<bool> that is used to pass around a weak reference to a bool.
-template <class T>
-class WeakPtrFactory {
- public:
- explicit WeakPtrFactory(T* ptr) : ptr_(ptr) {
- }
-
- ~WeakPtrFactory() {
- ptr_ = NULL;
- }
-
- WeakPtr<T> GetWeakPtr() {
- DCHECK(ptr_);
- return WeakPtr<T>(weak_reference_owner_.GetRef(), ptr_);
- }
-
- // Call this method to invalidate all existing weak pointers.
- void InvalidateWeakPtrs() {
- DCHECK(ptr_);
- weak_reference_owner_.Invalidate();
- }
-
- // Call this method to determine if any weak pointers exist.
- bool HasWeakPtrs() const {
- DCHECK(ptr_);
- return weak_reference_owner_.HasRefs();
- }
-
- private:
- internal::WeakReferenceOwner weak_reference_owner_;
- T* ptr_;
- DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory);
-};
-
-// A class may extend from SupportsWeakPtr to let others take weak pointers to
-// it. This avoids the class itself implementing boilerplate to dispense weak
-// pointers. However, since SupportsWeakPtr's destructor won't invalidate
-// weak pointers to the class until after the derived class' members have been
-// destroyed, its use can lead to subtle use-after-destroy issues.
-template <class T>
-class SupportsWeakPtr : public internal::SupportsWeakPtrBase {
- public:
- SupportsWeakPtr() {}
-
- WeakPtr<T> AsWeakPtr() {
- return WeakPtr<T>(weak_reference_owner_.GetRef(), static_cast<T*>(this));
- }
-
- protected:
- ~SupportsWeakPtr() {}
-
- private:
- internal::WeakReferenceOwner weak_reference_owner_;
- DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr);
-};
-
-// Helper function that uses type deduction to safely return a WeakPtr<Derived>
-// when Derived doesn't directly extend SupportsWeakPtr<Derived>, instead it
-// extends a Base that extends SupportsWeakPtr<Base>.
-//
-// EXAMPLE:
-// class Base : public base::SupportsWeakPtr<Producer> {};
-// class Derived : public Base {};
-//
-// Derived derived;
-// base::WeakPtr<Derived> ptr = base::AsWeakPtr(&derived);
-//
-// Note that the following doesn't work (invalid type conversion) since
-// Derived::AsWeakPtr() is WeakPtr<Base> SupportsWeakPtr<Base>::AsWeakPtr(),
-// and there's no way to safely cast WeakPtr<Base> to WeakPtr<Derived> at
-// the caller.
-//
-// base::WeakPtr<Derived> ptr = derived.AsWeakPtr(); // Fails.
-
-template <typename Derived>
-WeakPtr<Derived> AsWeakPtr(Derived* t) {
- return internal::SupportsWeakPtrBase::StaticAsWeakPtr<Derived>(t);
-}
-
-} // namespace base
-
-#endif // BASE_MEMORY_WEAK_PTR_H_
diff --git a/security/sandbox/chromium/base/move.h b/security/sandbox/chromium/base/move.h
deleted file mode 100644
index 0af416e00..000000000
--- a/security/sandbox/chromium/base/move.h
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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.
-
-#ifndef BASE_MOVE_H_
-#define BASE_MOVE_H_
-
-#include <utility>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "build/build_config.h"
-
-// TODO(crbug.com/566182): DEPRECATED!
-// Use DISALLOW_COPY_AND_ASSIGN instead, or if your type will be used in
-// Callbacks, use DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND instead.
-#define MOVE_ONLY_TYPE_FOR_CPP_03(type) \
- DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND(type)
-
-// A macro to disallow the copy constructor and copy assignment functions.
-// This should be used in the private: declarations for a class.
-//
-// Use this macro instead of DISALLOW_COPY_AND_ASSIGN if you want to pass
-// ownership of the type through a base::Callback without heap-allocating it
-// into a scoped_ptr. The class must define a move constructor and move
-// assignment operator to make this work.
-//
-// This version of the macro adds a Pass() function and a cryptic
-// MoveOnlyTypeForCPP03 typedef for the base::Callback implementation to use.
-// See IsMoveOnlyType template and its usage in base/callback_internal.h
-// for more details.
-// TODO(crbug.com/566182): Remove this macro and use DISALLOW_COPY_AND_ASSIGN
-// everywhere instead.
-#if defined(OS_ANDROID) || defined(OS_LINUX) || defined(OS_MACOSX)
-#define DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND(type) \
- private: \
- type(const type&) = delete; \
- void operator=(const type&) = delete; \
- \
- public: \
- typedef void MoveOnlyTypeForCPP03; \
- \
- private:
-#else
-#define DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND(type) \
- private: \
- type(const type&) = delete; \
- void operator=(const type&) = delete; \
- \
- public: \
- type&& Pass() WARN_UNUSED_RESULT { return std::move(*this); } \
- typedef void MoveOnlyTypeForCPP03; \
- \
- private:
-#endif
-
-#endif // BASE_MOVE_H_
diff --git a/security/sandbox/chromium/base/numerics/safe_conversions.h b/security/sandbox/chromium/base/numerics/safe_conversions.h
deleted file mode 100644
index baac188fd..000000000
--- a/security/sandbox/chromium/base/numerics/safe_conversions.h
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright 2014 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_NUMERICS_SAFE_CONVERSIONS_H_
-#define BASE_NUMERICS_SAFE_CONVERSIONS_H_
-
-#include <stddef.h>
-
-#include <limits>
-#include <type_traits>
-
-#include "base/logging.h"
-#include "base/numerics/safe_conversions_impl.h"
-
-namespace base {
-
-// Convenience function that returns true if the supplied value is in range
-// for the destination type.
-template <typename Dst, typename Src>
-inline bool IsValueInRangeForNumericType(Src value) {
- return internal::DstRangeRelationToSrcRange<Dst>(value) ==
- internal::RANGE_VALID;
-}
-
-// Convenience function for determining if a numeric value is negative without
-// throwing compiler warnings on: unsigned(value) < 0.
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
-IsValueNegative(T value) {
- static_assert(std::numeric_limits<T>::is_specialized,
- "Argument must be numeric.");
- return value < 0;
-}
-
-template <typename T>
-typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
- IsValueNegative(T) {
- static_assert(std::numeric_limits<T>::is_specialized,
- "Argument must be numeric.");
- return false;
-}
-
-// checked_cast<> is analogous to static_cast<> for numeric types,
-// except that it CHECKs that the specified numeric conversion will not
-// overflow or underflow. NaN source will always trigger a CHECK.
-template <typename Dst, typename Src>
-inline Dst checked_cast(Src value) {
- CHECK(IsValueInRangeForNumericType<Dst>(value));
- return static_cast<Dst>(value);
-}
-
-// HandleNaN will cause this class to CHECK(false).
-struct SaturatedCastNaNBehaviorCheck {
- template <typename T>
- static T HandleNaN() {
- CHECK(false);
- return T();
- }
-};
-
-// HandleNaN will return 0 in this case.
-struct SaturatedCastNaNBehaviorReturnZero {
- template <typename T>
- static T HandleNaN() {
- return T();
- }
-};
-
-// saturated_cast<> is analogous to static_cast<> for numeric types, except
-// that the specified numeric conversion will saturate rather than overflow or
-// underflow. NaN assignment to an integral will defer the behavior to a
-// specified class. By default, it will return 0.
-template <typename Dst,
- class NaNHandler = SaturatedCastNaNBehaviorReturnZero,
- typename Src>
-inline Dst saturated_cast(Src value) {
- // Optimization for floating point values, which already saturate.
- if (std::numeric_limits<Dst>::is_iec559)
- return static_cast<Dst>(value);
-
- switch (internal::DstRangeRelationToSrcRange<Dst>(value)) {
- case internal::RANGE_VALID:
- return static_cast<Dst>(value);
-
- case internal::RANGE_UNDERFLOW:
- return std::numeric_limits<Dst>::min();
-
- case internal::RANGE_OVERFLOW:
- return std::numeric_limits<Dst>::max();
-
- // Should fail only on attempting to assign NaN to a saturated integer.
- case internal::RANGE_INVALID:
- return NaNHandler::template HandleNaN<Dst>();
- }
-
- NOTREACHED();
- return static_cast<Dst>(value);
-}
-
-// strict_cast<> is analogous to static_cast<> for numeric types, except that
-// it will cause a compile failure if the destination type is not large enough
-// to contain any value in the source type. It performs no runtime checking.
-template <typename Dst, typename Src>
-inline Dst strict_cast(Src value) {
- static_assert(std::numeric_limits<Src>::is_specialized,
- "Argument must be numeric.");
- static_assert(std::numeric_limits<Dst>::is_specialized,
- "Result must be numeric.");
- static_assert((internal::StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
- internal::NUMERIC_RANGE_CONTAINED),
- "The numeric conversion is out of range for this type. You "
- "should probably use one of the following conversion "
- "mechanisms on the value you want to pass:\n"
- "- base::checked_cast\n"
- "- base::saturated_cast\n"
- "- base::CheckedNumeric");
-
- return static_cast<Dst>(value);
-}
-
-// StrictNumeric implements compile time range checking between numeric types by
-// wrapping assignment operations in a strict_cast. This class is intended to be
-// used for function arguments and return types, to ensure the destination type
-// can always contain the source type. This is essentially the same as enforcing
-// -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
-// incrementally at API boundaries, making it easier to convert code so that it
-// compiles cleanly with truncation warnings enabled.
-// This template should introduce no runtime overhead, but it also provides no
-// runtime checking of any of the associated mathematical operations. Use
-// CheckedNumeric for runtime range checks of tha actual value being assigned.
-template <typename T>
-class StrictNumeric {
- public:
- typedef T type;
-
- StrictNumeric() : value_(0) {}
-
- // Copy constructor.
- template <typename Src>
- StrictNumeric(const StrictNumeric<Src>& rhs)
- : value_(strict_cast<T>(rhs.value_)) {}
-
- // This is not an explicit constructor because we implicitly upgrade regular
- // numerics to StrictNumerics to make them easier to use.
- template <typename Src>
- StrictNumeric(Src value)
- : value_(strict_cast<T>(value)) {}
-
- // The numeric cast operator basically handles all the magic.
- template <typename Dst>
- operator Dst() const {
- return strict_cast<Dst>(value_);
- }
-
- private:
- T value_;
-};
-
-// Explicitly make a shorter size_t typedef for convenience.
-typedef StrictNumeric<size_t> SizeT;
-
-} // namespace base
-
-#endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_
diff --git a/security/sandbox/chromium/base/numerics/safe_conversions_impl.h b/security/sandbox/chromium/base/numerics/safe_conversions_impl.h
deleted file mode 100644
index 02e68e25d..000000000
--- a/security/sandbox/chromium/base/numerics/safe_conversions_impl.h
+++ /dev/null
@@ -1,264 +0,0 @@
-// Copyright 2014 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_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
-#define BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
-
-#include <limits.h>
-#include <stdint.h>
-
-#include <limits>
-
-#include "base/template_util.h"
-
-namespace base {
-namespace internal {
-
-// The std library doesn't provide a binary max_exponent for integers, however
-// we can compute one by adding one to the number of non-sign bits. This allows
-// for accurate range comparisons between floating point and integer types.
-template <typename NumericType>
-struct MaxExponent {
- static const int value = std::numeric_limits<NumericType>::is_iec559
- ? std::numeric_limits<NumericType>::max_exponent
- : (sizeof(NumericType) * 8 + 1 -
- std::numeric_limits<NumericType>::is_signed);
-};
-
-enum IntegerRepresentation {
- INTEGER_REPRESENTATION_UNSIGNED,
- INTEGER_REPRESENTATION_SIGNED
-};
-
-// A range for a given nunmeric Src type is contained for a given numeric Dst
-// type if both numeric_limits<Src>::max() <= numeric_limits<Dst>::max() and
-// numeric_limits<Src>::min() >= numeric_limits<Dst>::min() are true.
-// We implement this as template specializations rather than simple static
-// comparisons to ensure type correctness in our comparisons.
-enum NumericRangeRepresentation {
- NUMERIC_RANGE_NOT_CONTAINED,
- NUMERIC_RANGE_CONTAINED
-};
-
-// Helper templates to statically determine if our destination type can contain
-// maximum and minimum values represented by the source type.
-
-template <
- typename Dst,
- typename Src,
- IntegerRepresentation DstSign = std::numeric_limits<Dst>::is_signed
- ? INTEGER_REPRESENTATION_SIGNED
- : INTEGER_REPRESENTATION_UNSIGNED,
- IntegerRepresentation SrcSign =
- std::numeric_limits<Src>::is_signed
- ? INTEGER_REPRESENTATION_SIGNED
- : INTEGER_REPRESENTATION_UNSIGNED >
-struct StaticDstRangeRelationToSrcRange;
-
-// Same sign: Dst is guaranteed to contain Src only if its range is equal or
-// larger.
-template <typename Dst, typename Src, IntegerRepresentation Sign>
-struct StaticDstRangeRelationToSrcRange<Dst, Src, Sign, Sign> {
- static const NumericRangeRepresentation value =
- MaxExponent<Dst>::value >= MaxExponent<Src>::value
- ? NUMERIC_RANGE_CONTAINED
- : NUMERIC_RANGE_NOT_CONTAINED;
-};
-
-// Unsigned to signed: Dst is guaranteed to contain source only if its range is
-// larger.
-template <typename Dst, typename Src>
-struct StaticDstRangeRelationToSrcRange<Dst,
- Src,
- INTEGER_REPRESENTATION_SIGNED,
- INTEGER_REPRESENTATION_UNSIGNED> {
- static const NumericRangeRepresentation value =
- MaxExponent<Dst>::value > MaxExponent<Src>::value
- ? NUMERIC_RANGE_CONTAINED
- : NUMERIC_RANGE_NOT_CONTAINED;
-};
-
-// Signed to unsigned: Dst cannot be statically determined to contain Src.
-template <typename Dst, typename Src>
-struct StaticDstRangeRelationToSrcRange<Dst,
- Src,
- INTEGER_REPRESENTATION_UNSIGNED,
- INTEGER_REPRESENTATION_SIGNED> {
- static const NumericRangeRepresentation value = NUMERIC_RANGE_NOT_CONTAINED;
-};
-
-enum RangeConstraint {
- RANGE_VALID = 0x0, // Value can be represented by the destination type.
- RANGE_UNDERFLOW = 0x1, // Value would overflow.
- RANGE_OVERFLOW = 0x2, // Value would underflow.
- RANGE_INVALID = RANGE_UNDERFLOW | RANGE_OVERFLOW // Invalid (i.e. NaN).
-};
-
-// Helper function for coercing an int back to a RangeContraint.
-inline RangeConstraint GetRangeConstraint(int integer_range_constraint) {
- DCHECK(integer_range_constraint >= RANGE_VALID &&
- integer_range_constraint <= RANGE_INVALID);
- return static_cast<RangeConstraint>(integer_range_constraint);
-}
-
-// This function creates a RangeConstraint from an upper and lower bound
-// check by taking advantage of the fact that only NaN can be out of range in
-// both directions at once.
-inline RangeConstraint GetRangeConstraint(bool is_in_upper_bound,
- bool is_in_lower_bound) {
- return GetRangeConstraint((is_in_upper_bound ? 0 : RANGE_OVERFLOW) |
- (is_in_lower_bound ? 0 : RANGE_UNDERFLOW));
-}
-
-// The following helper template addresses a corner case in range checks for
-// conversion from a floating-point type to an integral type of smaller range
-// but larger precision (e.g. float -> unsigned). The problem is as follows:
-// 1. Integral maximum is always one less than a power of two, so it must be
-// truncated to fit the mantissa of the floating point. The direction of
-// rounding is implementation defined, but by default it's always IEEE
-// floats, which round to nearest and thus result in a value of larger
-// magnitude than the integral value.
-// Example: float f = UINT_MAX; // f is 4294967296f but UINT_MAX
-// // is 4294967295u.
-// 2. If the floating point value is equal to the promoted integral maximum
-// value, a range check will erroneously pass.
-// Example: (4294967296f <= 4294967295u) // This is true due to a precision
-// // loss in rounding up to float.
-// 3. When the floating point value is then converted to an integral, the
-// resulting value is out of range for the target integral type and
-// thus is implementation defined.
-// Example: unsigned u = (float)INT_MAX; // u will typically overflow to 0.
-// To fix this bug we manually truncate the maximum value when the destination
-// type is an integral of larger precision than the source floating-point type,
-// such that the resulting maximum is represented exactly as a floating point.
-template <typename Dst, typename Src>
-struct NarrowingRange {
- typedef typename std::numeric_limits<Src> SrcLimits;
- typedef typename std::numeric_limits<Dst> DstLimits;
-
- static Dst max() {
- // The following logic avoids warnings where the max function is
- // instantiated with invalid values for a bit shift (even though
- // such a function can never be called).
- static const int shift =
- (MaxExponent<Src>::value > MaxExponent<Dst>::value &&
- SrcLimits::digits < DstLimits::digits && SrcLimits::is_iec559 &&
- DstLimits::is_integer)
- ? (DstLimits::digits - SrcLimits::digits)
- : 0;
-
- // We use UINTMAX_C below to avoid compiler warnings about shifting floating
- // points. Since it's a compile time calculation, it shouldn't have any
- // performance impact.
- return DstLimits::max() - static_cast<Dst>((UINTMAX_C(1) << shift) - 1);
- }
-
- static Dst min() {
- return std::numeric_limits<Dst>::is_iec559 ? -DstLimits::max()
- : DstLimits::min();
- }
-};
-
-template <
- typename Dst,
- typename Src,
- IntegerRepresentation DstSign = std::numeric_limits<Dst>::is_signed
- ? INTEGER_REPRESENTATION_SIGNED
- : INTEGER_REPRESENTATION_UNSIGNED,
- IntegerRepresentation SrcSign = std::numeric_limits<Src>::is_signed
- ? INTEGER_REPRESENTATION_SIGNED
- : INTEGER_REPRESENTATION_UNSIGNED,
- NumericRangeRepresentation DstRange =
- StaticDstRangeRelationToSrcRange<Dst, Src>::value >
-struct DstRangeRelationToSrcRangeImpl;
-
-// The following templates are for ranges that must be verified at runtime. We
-// split it into checks based on signedness to avoid confusing casts and
-// compiler warnings on signed an unsigned comparisons.
-
-// Dst range is statically determined to contain Src: Nothing to check.
-template <typename Dst,
- typename Src,
- IntegerRepresentation DstSign,
- IntegerRepresentation SrcSign>
-struct DstRangeRelationToSrcRangeImpl<Dst,
- Src,
- DstSign,
- SrcSign,
- NUMERIC_RANGE_CONTAINED> {
- static RangeConstraint Check(Src value) { return RANGE_VALID; }
-};
-
-// Signed to signed narrowing: Both the upper and lower boundaries may be
-// exceeded.
-template <typename Dst, typename Src>
-struct DstRangeRelationToSrcRangeImpl<Dst,
- Src,
- INTEGER_REPRESENTATION_SIGNED,
- INTEGER_REPRESENTATION_SIGNED,
- NUMERIC_RANGE_NOT_CONTAINED> {
- static RangeConstraint Check(Src value) {
- return GetRangeConstraint((value <= NarrowingRange<Dst, Src>::max()),
- (value >= NarrowingRange<Dst, Src>::min()));
- }
-};
-
-// Unsigned to unsigned narrowing: Only the upper boundary can be exceeded.
-template <typename Dst, typename Src>
-struct DstRangeRelationToSrcRangeImpl<Dst,
- Src,
- INTEGER_REPRESENTATION_UNSIGNED,
- INTEGER_REPRESENTATION_UNSIGNED,
- NUMERIC_RANGE_NOT_CONTAINED> {
- static RangeConstraint Check(Src value) {
- return GetRangeConstraint(value <= NarrowingRange<Dst, Src>::max(), true);
- }
-};
-
-// Unsigned to signed: The upper boundary may be exceeded.
-template <typename Dst, typename Src>
-struct DstRangeRelationToSrcRangeImpl<Dst,
- Src,
- INTEGER_REPRESENTATION_SIGNED,
- INTEGER_REPRESENTATION_UNSIGNED,
- NUMERIC_RANGE_NOT_CONTAINED> {
- static RangeConstraint Check(Src value) {
- return sizeof(Dst) > sizeof(Src)
- ? RANGE_VALID
- : GetRangeConstraint(
- value <= static_cast<Src>(NarrowingRange<Dst, Src>::max()),
- true);
- }
-};
-
-// Signed to unsigned: The upper boundary may be exceeded for a narrower Dst,
-// and any negative value exceeds the lower boundary.
-template <typename Dst, typename Src>
-struct DstRangeRelationToSrcRangeImpl<Dst,
- Src,
- INTEGER_REPRESENTATION_UNSIGNED,
- INTEGER_REPRESENTATION_SIGNED,
- NUMERIC_RANGE_NOT_CONTAINED> {
- static RangeConstraint Check(Src value) {
- return (MaxExponent<Dst>::value >= MaxExponent<Src>::value)
- ? GetRangeConstraint(true, value >= static_cast<Src>(0))
- : GetRangeConstraint(
- value <= static_cast<Src>(NarrowingRange<Dst, Src>::max()),
- value >= static_cast<Src>(0));
- }
-};
-
-template <typename Dst, typename Src>
-inline RangeConstraint DstRangeRelationToSrcRange(Src value) {
- static_assert(std::numeric_limits<Src>::is_specialized,
- "Argument must be numeric.");
- static_assert(std::numeric_limits<Dst>::is_specialized,
- "Result must be numeric.");
- return DstRangeRelationToSrcRangeImpl<Dst, Src>::Check(value);
-}
-
-} // namespace internal
-} // namespace base
-
-#endif // BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
diff --git a/security/sandbox/chromium/base/numerics/safe_math.h b/security/sandbox/chromium/base/numerics/safe_math.h
deleted file mode 100644
index d169690a8..000000000
--- a/security/sandbox/chromium/base/numerics/safe_math.h
+++ /dev/null
@@ -1,299 +0,0 @@
-// Copyright 2014 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_NUMERICS_SAFE_MATH_H_
-#define BASE_NUMERICS_SAFE_MATH_H_
-
-#include <stddef.h>
-
-#include "base/numerics/safe_math_impl.h"
-
-namespace base {
-
-namespace internal {
-
-// CheckedNumeric implements all the logic and operators for detecting integer
-// boundary conditions such as overflow, underflow, and invalid conversions.
-// The CheckedNumeric type implicitly converts from floating point and integer
-// data types, and contains overloads for basic arithmetic operations (i.e.: +,
-// -, *, /, %).
-//
-// The following methods convert from CheckedNumeric to standard numeric values:
-// IsValid() - Returns true if the underlying numeric value is valid (i.e. has
-// has not wrapped and is not the result of an invalid conversion).
-// ValueOrDie() - Returns the underlying value. If the state is not valid this
-// call will crash on a CHECK.
-// ValueOrDefault() - Returns the current value, or the supplied default if the
-// state is not valid.
-// ValueFloating() - Returns the underlying floating point value (valid only
-// only for floating point CheckedNumeric types).
-//
-// Bitwise operations are explicitly not supported, because correct
-// handling of some cases (e.g. sign manipulation) is ambiguous. Comparison
-// operations are explicitly not supported because they could result in a crash
-// on a CHECK condition. You should use patterns like the following for these
-// operations:
-// Bitwise operation:
-// CheckedNumeric<int> checked_int = untrusted_input_value;
-// int x = checked_int.ValueOrDefault(0) | kFlagValues;
-// Comparison:
-// CheckedNumeric<size_t> checked_size = untrusted_input_value;
-// checked_size += HEADER LENGTH;
-// if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size)
-// Do stuff...
-template <typename T>
-class CheckedNumeric {
- public:
- typedef T type;
-
- CheckedNumeric() {}
-
- // Copy constructor.
- template <typename Src>
- CheckedNumeric(const CheckedNumeric<Src>& rhs)
- : state_(rhs.ValueUnsafe(), rhs.validity()) {}
-
- template <typename Src>
- CheckedNumeric(Src value, RangeConstraint validity)
- : state_(value, validity) {}
-
- // This is not an explicit constructor because we implicitly upgrade regular
- // numerics to CheckedNumerics to make them easier to use.
- template <typename Src>
- CheckedNumeric(Src value)
- : state_(value) {
- static_assert(std::numeric_limits<Src>::is_specialized,
- "Argument must be numeric.");
- }
-
- // This is not an explicit constructor because we want a seamless conversion
- // from StrictNumeric types.
- template <typename Src>
- CheckedNumeric(StrictNumeric<Src> value)
- : state_(static_cast<Src>(value)) {
- }
-
- // IsValid() is the public API to test if a CheckedNumeric is currently valid.
- bool IsValid() const { return validity() == RANGE_VALID; }
-
- // ValueOrDie() The primary accessor for the underlying value. If the current
- // state is not valid it will CHECK and crash.
- T ValueOrDie() const {
- CHECK(IsValid());
- return state_.value();
- }
-
- // ValueOrDefault(T default_value) A convenience method that returns the
- // current value if the state is valid, and the supplied default_value for
- // any other state.
- T ValueOrDefault(T default_value) const {
- return IsValid() ? state_.value() : default_value;
- }
-
- // ValueFloating() - Since floating point values include their validity state,
- // we provide an easy method for extracting them directly, without a risk of
- // crashing on a CHECK.
- T ValueFloating() const {
- static_assert(std::numeric_limits<T>::is_iec559, "Argument must be float.");
- return CheckedNumeric<T>::cast(*this).ValueUnsafe();
- }
-
- // validity() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now for
- // tests and to avoid a big matrix of friend operator overloads. But the
- // values it returns are likely to change in the future.
- // Returns: current validity state (i.e. valid, overflow, underflow, nan).
- // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
- // saturation/wrapping so we can expose this state consistently and implement
- // saturated arithmetic.
- RangeConstraint validity() const { return state_.validity(); }
-
- // ValueUnsafe() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now
- // for tests and to avoid a big matrix of friend operator overloads. But the
- // values it returns are likely to change in the future.
- // Returns: the raw numeric value, regardless of the current state.
- // TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
- // saturation/wrapping so we can expose this state consistently and implement
- // saturated arithmetic.
- T ValueUnsafe() const { return state_.value(); }
-
- // Prototypes for the supported arithmetic operator overloads.
- template <typename Src> CheckedNumeric& operator+=(Src rhs);
- template <typename Src> CheckedNumeric& operator-=(Src rhs);
- template <typename Src> CheckedNumeric& operator*=(Src rhs);
- template <typename Src> CheckedNumeric& operator/=(Src rhs);
- template <typename Src> CheckedNumeric& operator%=(Src rhs);
-
- CheckedNumeric operator-() const {
- RangeConstraint validity;
- T value = CheckedNeg(state_.value(), &validity);
- // Negation is always valid for floating point.
- if (std::numeric_limits<T>::is_iec559)
- return CheckedNumeric<T>(value);
-
- validity = GetRangeConstraint(state_.validity() | validity);
- return CheckedNumeric<T>(value, validity);
- }
-
- CheckedNumeric Abs() const {
- RangeConstraint validity;
- T value = CheckedAbs(state_.value(), &validity);
- // Absolute value is always valid for floating point.
- if (std::numeric_limits<T>::is_iec559)
- return CheckedNumeric<T>(value);
-
- validity = GetRangeConstraint(state_.validity() | validity);
- return CheckedNumeric<T>(value, validity);
- }
-
- // This function is available only for integral types. It returns an unsigned
- // integer of the same width as the source type, containing the absolute value
- // of the source, and properly handling signed min.
- CheckedNumeric<typename UnsignedOrFloatForSize<T>::type> UnsignedAbs() const {
- return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>(
- CheckedUnsignedAbs(state_.value()), state_.validity());
- }
-
- CheckedNumeric& operator++() {
- *this += 1;
- return *this;
- }
-
- CheckedNumeric operator++(int) {
- CheckedNumeric value = *this;
- *this += 1;
- return value;
- }
-
- CheckedNumeric& operator--() {
- *this -= 1;
- return *this;
- }
-
- CheckedNumeric operator--(int) {
- CheckedNumeric value = *this;
- *this -= 1;
- return value;
- }
-
- // These static methods behave like a convenience cast operator targeting
- // the desired CheckedNumeric type. As an optimization, a reference is
- // returned when Src is the same type as T.
- template <typename Src>
- static CheckedNumeric<T> cast(
- Src u,
- typename std::enable_if<std::numeric_limits<Src>::is_specialized,
- int>::type = 0) {
- return u;
- }
-
- template <typename Src>
- static CheckedNumeric<T> cast(
- const CheckedNumeric<Src>& u,
- typename std::enable_if<!is_same<Src, T>::value, int>::type = 0) {
- return u;
- }
-
- static const CheckedNumeric<T>& cast(const CheckedNumeric<T>& u) { return u; }
-
- private:
- template <typename NumericType>
- struct UnderlyingType {
- using type = NumericType;
- };
-
- template <typename NumericType>
- struct UnderlyingType<CheckedNumeric<NumericType>> {
- using type = NumericType;
- };
-
- CheckedNumericState<T> state_;
-};
-
-// This is the boilerplate for the standard arithmetic operator overloads. A
-// macro isn't the prettiest solution, but it beats rewriting these five times.
-// Some details worth noting are:
-// * We apply the standard arithmetic promotions.
-// * We skip range checks for floating points.
-// * We skip range checks for destination integers with sufficient range.
-// TODO(jschuh): extract these out into templates.
-#define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP) \
- /* Binary arithmetic operator for CheckedNumerics of the same type. */ \
- template <typename T> \
- CheckedNumeric<typename ArithmeticPromotion<T>::type> operator OP( \
- const CheckedNumeric<T>& lhs, const CheckedNumeric<T>& rhs) { \
- typedef typename ArithmeticPromotion<T>::type Promotion; \
- /* Floating point always takes the fast path */ \
- if (std::numeric_limits<T>::is_iec559) \
- return CheckedNumeric<T>(lhs.ValueUnsafe() OP rhs.ValueUnsafe()); \
- if (IsIntegerArithmeticSafe<Promotion, T, T>::value) \
- return CheckedNumeric<Promotion>( \
- lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
- GetRangeConstraint(rhs.validity() | lhs.validity())); \
- RangeConstraint validity = RANGE_VALID; \
- T result = static_cast<T>(Checked##NAME( \
- static_cast<Promotion>(lhs.ValueUnsafe()), \
- static_cast<Promotion>(rhs.ValueUnsafe()), \
- &validity)); \
- return CheckedNumeric<Promotion>( \
- result, \
- GetRangeConstraint(validity | lhs.validity() | rhs.validity())); \
- } \
- /* Assignment arithmetic operator implementation from CheckedNumeric. */ \
- template <typename T> \
- template <typename Src> \
- CheckedNumeric<T>& CheckedNumeric<T>::operator COMPOUND_OP(Src rhs) { \
- *this = CheckedNumeric<T>::cast(*this) \
- OP CheckedNumeric<typename UnderlyingType<Src>::type>::cast(rhs); \
- return *this; \
- } \
- /* Binary arithmetic operator for CheckedNumeric of different type. */ \
- template <typename T, typename Src> \
- CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
- const CheckedNumeric<Src>& lhs, const CheckedNumeric<T>& rhs) { \
- typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
- if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
- return CheckedNumeric<Promotion>( \
- lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
- GetRangeConstraint(rhs.validity() | lhs.validity())); \
- return CheckedNumeric<Promotion>::cast(lhs) \
- OP CheckedNumeric<Promotion>::cast(rhs); \
- } \
- /* Binary arithmetic operator for left CheckedNumeric and right numeric. */ \
- template <typename T, typename Src> \
- CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
- const CheckedNumeric<T>& lhs, Src rhs) { \
- typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
- if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
- return CheckedNumeric<Promotion>(lhs.ValueUnsafe() OP rhs, \
- lhs.validity()); \
- return CheckedNumeric<Promotion>::cast(lhs) \
- OP CheckedNumeric<Promotion>::cast(rhs); \
- } \
- /* Binary arithmetic operator for right numeric and left CheckedNumeric. */ \
- template <typename T, typename Src> \
- CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
- Src lhs, const CheckedNumeric<T>& rhs) { \
- typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
- if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
- return CheckedNumeric<Promotion>(lhs OP rhs.ValueUnsafe(), \
- rhs.validity()); \
- return CheckedNumeric<Promotion>::cast(lhs) \
- OP CheckedNumeric<Promotion>::cast(rhs); \
- }
-
-BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, += )
-BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -= )
-BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *= )
-BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /= )
-BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %= )
-
-#undef BASE_NUMERIC_ARITHMETIC_OPERATORS
-
-} // namespace internal
-
-using internal::CheckedNumeric;
-
-} // namespace base
-
-#endif // BASE_NUMERICS_SAFE_MATH_H_
diff --git a/security/sandbox/chromium/base/numerics/safe_math_impl.h b/security/sandbox/chromium/base/numerics/safe_math_impl.h
deleted file mode 100644
index 4fbcc045b..000000000
--- a/security/sandbox/chromium/base/numerics/safe_math_impl.h
+++ /dev/null
@@ -1,545 +0,0 @@
-// Copyright 2014 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_NUMERICS_SAFE_MATH_IMPL_H_
-#define BASE_NUMERICS_SAFE_MATH_IMPL_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <cmath>
-#include <cstdlib>
-#include <limits>
-#include <type_traits>
-
-#include "base/numerics/safe_conversions.h"
-#include "base/template_util.h"
-
-namespace base {
-namespace internal {
-
-// Everything from here up to the floating point operations is portable C++,
-// but it may not be fast. This code could be split based on
-// platform/architecture and replaced with potentially faster implementations.
-
-// Integer promotion templates used by the portable checked integer arithmetic.
-template <size_t Size, bool IsSigned>
-struct IntegerForSizeAndSign;
-template <>
-struct IntegerForSizeAndSign<1, true> {
- typedef int8_t type;
-};
-template <>
-struct IntegerForSizeAndSign<1, false> {
- typedef uint8_t type;
-};
-template <>
-struct IntegerForSizeAndSign<2, true> {
- typedef int16_t type;
-};
-template <>
-struct IntegerForSizeAndSign<2, false> {
- typedef uint16_t type;
-};
-template <>
-struct IntegerForSizeAndSign<4, true> {
- typedef int32_t type;
-};
-template <>
-struct IntegerForSizeAndSign<4, false> {
- typedef uint32_t type;
-};
-template <>
-struct IntegerForSizeAndSign<8, true> {
- typedef int64_t type;
-};
-template <>
-struct IntegerForSizeAndSign<8, false> {
- typedef uint64_t type;
-};
-
-// WARNING: We have no IntegerForSizeAndSign<16, *>. If we ever add one to
-// support 128-bit math, then the ArithmeticPromotion template below will need
-// to be updated (or more likely replaced with a decltype expression).
-
-template <typename Integer>
-struct UnsignedIntegerForSize {
- typedef typename std::enable_if<
- std::numeric_limits<Integer>::is_integer,
- typename IntegerForSizeAndSign<sizeof(Integer), false>::type>::type type;
-};
-
-template <typename Integer>
-struct SignedIntegerForSize {
- typedef typename std::enable_if<
- std::numeric_limits<Integer>::is_integer,
- typename IntegerForSizeAndSign<sizeof(Integer), true>::type>::type type;
-};
-
-template <typename Integer>
-struct TwiceWiderInteger {
- typedef typename std::enable_if<
- std::numeric_limits<Integer>::is_integer,
- typename IntegerForSizeAndSign<
- sizeof(Integer) * 2,
- std::numeric_limits<Integer>::is_signed>::type>::type type;
-};
-
-template <typename Integer>
-struct PositionOfSignBit {
- static const typename std::enable_if<std::numeric_limits<Integer>::is_integer,
- size_t>::type value =
- 8 * sizeof(Integer) - 1;
-};
-
-// This is used for UnsignedAbs, where we need to support floating-point
-// template instantiations even though we don't actually support the operations.
-// However, there is no corresponding implementation of e.g. CheckedUnsignedAbs,
-// so the float versions will not compile.
-template <typename Numeric,
- bool IsInteger = std::numeric_limits<Numeric>::is_integer,
- bool IsFloat = std::numeric_limits<Numeric>::is_iec559>
-struct UnsignedOrFloatForSize;
-
-template <typename Numeric>
-struct UnsignedOrFloatForSize<Numeric, true, false> {
- typedef typename UnsignedIntegerForSize<Numeric>::type type;
-};
-
-template <typename Numeric>
-struct UnsignedOrFloatForSize<Numeric, false, true> {
- typedef Numeric type;
-};
-
-// Helper templates for integer manipulations.
-
-template <typename T>
-bool HasSignBit(T x) {
- // Cast to unsigned since right shift on signed is undefined.
- return !!(static_cast<typename UnsignedIntegerForSize<T>::type>(x) >>
- PositionOfSignBit<T>::value);
-}
-
-// This wrapper undoes the standard integer promotions.
-template <typename T>
-T BinaryComplement(T x) {
- return ~x;
-}
-
-// Here are the actual portable checked integer math implementations.
-// TODO(jschuh): Break this code out from the enable_if pattern and find a clean
-// way to coalesce things into the CheckedNumericState specializations below.
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer, T>::type
-CheckedAdd(T x, T y, RangeConstraint* validity) {
- // Since the value of x+y is undefined if we have a signed type, we compute
- // it using the unsigned type of the same size.
- typedef typename UnsignedIntegerForSize<T>::type UnsignedDst;
- UnsignedDst ux = static_cast<UnsignedDst>(x);
- UnsignedDst uy = static_cast<UnsignedDst>(y);
- UnsignedDst uresult = ux + uy;
- // Addition is valid if the sign of (x + y) is equal to either that of x or
- // that of y.
- if (std::numeric_limits<T>::is_signed) {
- if (HasSignBit(BinaryComplement((uresult ^ ux) & (uresult ^ uy))))
- *validity = RANGE_VALID;
- else // Direction of wrap is inverse of result sign.
- *validity = HasSignBit(uresult) ? RANGE_OVERFLOW : RANGE_UNDERFLOW;
-
- } else { // Unsigned is either valid or overflow.
- *validity = BinaryComplement(x) >= y ? RANGE_VALID : RANGE_OVERFLOW;
- }
- return static_cast<T>(uresult);
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer, T>::type
-CheckedSub(T x, T y, RangeConstraint* validity) {
- // Since the value of x+y is undefined if we have a signed type, we compute
- // it using the unsigned type of the same size.
- typedef typename UnsignedIntegerForSize<T>::type UnsignedDst;
- UnsignedDst ux = static_cast<UnsignedDst>(x);
- UnsignedDst uy = static_cast<UnsignedDst>(y);
- UnsignedDst uresult = ux - uy;
- // Subtraction is valid if either x and y have same sign, or (x-y) and x have
- // the same sign.
- if (std::numeric_limits<T>::is_signed) {
- if (HasSignBit(BinaryComplement((uresult ^ ux) & (ux ^ uy))))
- *validity = RANGE_VALID;
- else // Direction of wrap is inverse of result sign.
- *validity = HasSignBit(uresult) ? RANGE_OVERFLOW : RANGE_UNDERFLOW;
-
- } else { // Unsigned is either valid or underflow.
- *validity = x >= y ? RANGE_VALID : RANGE_UNDERFLOW;
- }
- return static_cast<T>(uresult);
-}
-
-// Integer multiplication is a bit complicated. In the fast case we just
-// we just promote to a twice wider type, and range check the result. In the
-// slow case we need to manually check that the result won't be truncated by
-// checking with division against the appropriate bound.
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- sizeof(T) * 2 <= sizeof(uintmax_t),
- T>::type
-CheckedMul(T x, T y, RangeConstraint* validity) {
- typedef typename TwiceWiderInteger<T>::type IntermediateType;
- IntermediateType tmp =
- static_cast<IntermediateType>(x) * static_cast<IntermediateType>(y);
- *validity = DstRangeRelationToSrcRange<T>(tmp);
- return static_cast<T>(tmp);
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- std::numeric_limits<T>::is_signed &&
- (sizeof(T) * 2 > sizeof(uintmax_t)),
- T>::type
-CheckedMul(T x, T y, RangeConstraint* validity) {
- // If either side is zero then the result will be zero.
- if (!x || !y) {
- return RANGE_VALID;
-
- } else if (x > 0) {
- if (y > 0)
- *validity =
- x <= std::numeric_limits<T>::max() / y ? RANGE_VALID : RANGE_OVERFLOW;
- else
- *validity = y >= std::numeric_limits<T>::min() / x ? RANGE_VALID
- : RANGE_UNDERFLOW;
-
- } else {
- if (y > 0)
- *validity = x >= std::numeric_limits<T>::min() / y ? RANGE_VALID
- : RANGE_UNDERFLOW;
- else
- *validity =
- y >= std::numeric_limits<T>::max() / x ? RANGE_VALID : RANGE_OVERFLOW;
- }
-
- return x * y;
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- !std::numeric_limits<T>::is_signed &&
- (sizeof(T) * 2 > sizeof(uintmax_t)),
- T>::type
-CheckedMul(T x, T y, RangeConstraint* validity) {
- *validity = (y == 0 || x <= std::numeric_limits<T>::max() / y)
- ? RANGE_VALID
- : RANGE_OVERFLOW;
- return x * y;
-}
-
-// Division just requires a check for an invalid negation on signed min/-1.
-template <typename T>
-T CheckedDiv(T x,
- T y,
- RangeConstraint* validity,
- typename std::enable_if<std::numeric_limits<T>::is_integer,
- int>::type = 0) {
- if (std::numeric_limits<T>::is_signed && x == std::numeric_limits<T>::min() &&
- y == static_cast<T>(-1)) {
- *validity = RANGE_OVERFLOW;
- return std::numeric_limits<T>::min();
- }
-
- *validity = RANGE_VALID;
- return x / y;
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- std::numeric_limits<T>::is_signed,
- T>::type
-CheckedMod(T x, T y, RangeConstraint* validity) {
- *validity = y > 0 ? RANGE_VALID : RANGE_INVALID;
- return x % y;
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- !std::numeric_limits<T>::is_signed,
- T>::type
-CheckedMod(T x, T y, RangeConstraint* validity) {
- *validity = RANGE_VALID;
- return x % y;
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- std::numeric_limits<T>::is_signed,
- T>::type
-CheckedNeg(T value, RangeConstraint* validity) {
- *validity =
- value != std::numeric_limits<T>::min() ? RANGE_VALID : RANGE_OVERFLOW;
- // The negation of signed min is min, so catch that one.
- return -value;
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- !std::numeric_limits<T>::is_signed,
- T>::type
-CheckedNeg(T value, RangeConstraint* validity) {
- // The only legal unsigned negation is zero.
- *validity = value ? RANGE_UNDERFLOW : RANGE_VALID;
- return static_cast<T>(
- -static_cast<typename SignedIntegerForSize<T>::type>(value));
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- std::numeric_limits<T>::is_signed,
- T>::type
-CheckedAbs(T value, RangeConstraint* validity) {
- *validity =
- value != std::numeric_limits<T>::min() ? RANGE_VALID : RANGE_OVERFLOW;
- return static_cast<T>(std::abs(value));
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- !std::numeric_limits<T>::is_signed,
- T>::type
-CheckedAbs(T value, RangeConstraint* validity) {
- // T is unsigned, so |value| must already be positive.
- *validity = RANGE_VALID;
- return value;
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- std::numeric_limits<T>::is_signed,
- typename UnsignedIntegerForSize<T>::type>::type
-CheckedUnsignedAbs(T value) {
- typedef typename UnsignedIntegerForSize<T>::type UnsignedT;
- return value == std::numeric_limits<T>::min()
- ? static_cast<UnsignedT>(std::numeric_limits<T>::max()) + 1
- : static_cast<UnsignedT>(std::abs(value));
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_integer &&
- !std::numeric_limits<T>::is_signed,
- T>::type
-CheckedUnsignedAbs(T value) {
- // T is unsigned, so |value| must already be positive.
- return value;
-}
-
-// These are the floating point stubs that the compiler needs to see. Only the
-// negation operation is ever called.
-#define BASE_FLOAT_ARITHMETIC_STUBS(NAME) \
- template <typename T> \
- typename std::enable_if<std::numeric_limits<T>::is_iec559, T>::type \
- Checked##NAME(T, T, RangeConstraint*) { \
- NOTREACHED(); \
- return 0; \
- }
-
-BASE_FLOAT_ARITHMETIC_STUBS(Add)
-BASE_FLOAT_ARITHMETIC_STUBS(Sub)
-BASE_FLOAT_ARITHMETIC_STUBS(Mul)
-BASE_FLOAT_ARITHMETIC_STUBS(Div)
-BASE_FLOAT_ARITHMETIC_STUBS(Mod)
-
-#undef BASE_FLOAT_ARITHMETIC_STUBS
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_iec559, T>::type CheckedNeg(
- T value,
- RangeConstraint*) {
- return -value;
-}
-
-template <typename T>
-typename std::enable_if<std::numeric_limits<T>::is_iec559, T>::type CheckedAbs(
- T value,
- RangeConstraint*) {
- return std::abs(value);
-}
-
-// Floats carry around their validity state with them, but integers do not. So,
-// we wrap the underlying value in a specialization in order to hide that detail
-// and expose an interface via accessors.
-enum NumericRepresentation {
- NUMERIC_INTEGER,
- NUMERIC_FLOATING,
- NUMERIC_UNKNOWN
-};
-
-template <typename NumericType>
-struct GetNumericRepresentation {
- static const NumericRepresentation value =
- std::numeric_limits<NumericType>::is_integer
- ? NUMERIC_INTEGER
- : (std::numeric_limits<NumericType>::is_iec559 ? NUMERIC_FLOATING
- : NUMERIC_UNKNOWN);
-};
-
-template <typename T, NumericRepresentation type =
- GetNumericRepresentation<T>::value>
-class CheckedNumericState {};
-
-// Integrals require quite a bit of additional housekeeping to manage state.
-template <typename T>
-class CheckedNumericState<T, NUMERIC_INTEGER> {
- private:
- T value_;
- RangeConstraint validity_;
-
- public:
- template <typename Src, NumericRepresentation type>
- friend class CheckedNumericState;
-
- CheckedNumericState() : value_(0), validity_(RANGE_VALID) {}
-
- template <typename Src>
- CheckedNumericState(Src value, RangeConstraint validity)
- : value_(static_cast<T>(value)),
- validity_(GetRangeConstraint(validity |
- DstRangeRelationToSrcRange<T>(value))) {
- static_assert(std::numeric_limits<Src>::is_specialized,
- "Argument must be numeric.");
- }
-
- // Copy constructor.
- template <typename Src>
- CheckedNumericState(const CheckedNumericState<Src>& rhs)
- : value_(static_cast<T>(rhs.value())),
- validity_(GetRangeConstraint(
- rhs.validity() | DstRangeRelationToSrcRange<T>(rhs.value()))) {}
-
- template <typename Src>
- explicit CheckedNumericState(
- Src value,
- typename std::enable_if<std::numeric_limits<Src>::is_specialized,
- int>::type = 0)
- : value_(static_cast<T>(value)),
- validity_(DstRangeRelationToSrcRange<T>(value)) {}
-
- RangeConstraint validity() const { return validity_; }
- T value() const { return value_; }
-};
-
-// Floating points maintain their own validity, but need translation wrappers.
-template <typename T>
-class CheckedNumericState<T, NUMERIC_FLOATING> {
- private:
- T value_;
-
- public:
- template <typename Src, NumericRepresentation type>
- friend class CheckedNumericState;
-
- CheckedNumericState() : value_(0.0) {}
-
- template <typename Src>
- CheckedNumericState(
- Src value,
- RangeConstraint validity,
- typename std::enable_if<std::numeric_limits<Src>::is_integer, int>::type =
- 0) {
- switch (DstRangeRelationToSrcRange<T>(value)) {
- case RANGE_VALID:
- value_ = static_cast<T>(value);
- break;
-
- case RANGE_UNDERFLOW:
- value_ = -std::numeric_limits<T>::infinity();
- break;
-
- case RANGE_OVERFLOW:
- value_ = std::numeric_limits<T>::infinity();
- break;
-
- case RANGE_INVALID:
- value_ = std::numeric_limits<T>::quiet_NaN();
- break;
-
- default:
- NOTREACHED();
- }
- }
-
- template <typename Src>
- explicit CheckedNumericState(
- Src value,
- typename std::enable_if<std::numeric_limits<Src>::is_specialized,
- int>::type = 0)
- : value_(static_cast<T>(value)) {}
-
- // Copy constructor.
- template <typename Src>
- CheckedNumericState(const CheckedNumericState<Src>& rhs)
- : value_(static_cast<T>(rhs.value())) {}
-
- RangeConstraint validity() const {
- return GetRangeConstraint(value_ <= std::numeric_limits<T>::max(),
- value_ >= -std::numeric_limits<T>::max());
- }
- T value() const { return value_; }
-};
-
-// For integers less than 128-bit and floats 32-bit or larger, we can distil
-// C/C++ arithmetic promotions down to two simple rules:
-// 1. The type with the larger maximum exponent always takes precedence.
-// 2. The resulting type must be promoted to at least an int.
-// The following template specializations implement that promotion logic.
-enum ArithmeticPromotionCategory {
- LEFT_PROMOTION,
- RIGHT_PROMOTION,
- DEFAULT_PROMOTION
-};
-
-template <typename Lhs,
- typename Rhs = Lhs,
- ArithmeticPromotionCategory Promotion =
- (MaxExponent<Lhs>::value > MaxExponent<Rhs>::value)
- ? (MaxExponent<Lhs>::value > MaxExponent<int>::value
- ? LEFT_PROMOTION
- : DEFAULT_PROMOTION)
- : (MaxExponent<Rhs>::value > MaxExponent<int>::value
- ? RIGHT_PROMOTION
- : DEFAULT_PROMOTION) >
-struct ArithmeticPromotion;
-
-template <typename Lhs, typename Rhs>
-struct ArithmeticPromotion<Lhs, Rhs, LEFT_PROMOTION> {
- typedef Lhs type;
-};
-
-template <typename Lhs, typename Rhs>
-struct ArithmeticPromotion<Lhs, Rhs, RIGHT_PROMOTION> {
- typedef Rhs type;
-};
-
-template <typename Lhs, typename Rhs>
-struct ArithmeticPromotion<Lhs, Rhs, DEFAULT_PROMOTION> {
- typedef int type;
-};
-
-// We can statically check if operations on the provided types can wrap, so we
-// can skip the checked operations if they're not needed. So, for an integer we
-// care if the destination type preserves the sign and is twice the width of
-// the source.
-template <typename T, typename Lhs, typename Rhs>
-struct IsIntegerArithmeticSafe {
- static const bool value = !std::numeric_limits<T>::is_iec559 &&
- StaticDstRangeRelationToSrcRange<T, Lhs>::value ==
- NUMERIC_RANGE_CONTAINED &&
- sizeof(T) >= (2 * sizeof(Lhs)) &&
- StaticDstRangeRelationToSrcRange<T, Rhs>::value !=
- NUMERIC_RANGE_CONTAINED &&
- sizeof(T) >= (2 * sizeof(Rhs));
-};
-
-} // namespace internal
-} // namespace base
-
-#endif // BASE_NUMERICS_SAFE_MATH_IMPL_H_
diff --git a/security/sandbox/chromium/base/os_compat_android.h b/security/sandbox/chromium/base/os_compat_android.h
deleted file mode 100644
index 0f2544496..000000000
--- a/security/sandbox/chromium/base/os_compat_android.h
+++ /dev/null
@@ -1,28 +0,0 @@
-// 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.
-
-#ifndef BASE_OS_COMPAT_ANDROID_H_
-#define BASE_OS_COMPAT_ANDROID_H_
-
-#include <fcntl.h>
-#include <sys/types.h>
-#include <utime.h>
-
-// Not implemented in Bionic.
-extern "C" int futimes(int fd, const struct timeval tv[2]);
-
-// Not exposed or implemented in Bionic.
-extern "C" char* mkdtemp(char* path);
-
-// Android has no timegm().
-extern "C" time_t timegm(struct tm* const t);
-
-// The lockf() function is not available on Android; we translate to flock().
-#define F_LOCK LOCK_EX
-#define F_ULOCK LOCK_UN
-inline int lockf(int fd, int cmd, off_t ignored_len) {
- return flock(fd, cmd);
-}
-
-#endif // BASE_OS_COMPAT_ANDROID_H_
diff --git a/security/sandbox/chromium/base/path_service.h b/security/sandbox/chromium/base/path_service.h
deleted file mode 100644
index c7f1abe71..000000000
--- a/security/sandbox/chromium/base/path_service.h
+++ /dev/null
@@ -1,97 +0,0 @@
-// 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.
-
-#ifndef BASE_PATH_SERVICE_H_
-#define BASE_PATH_SERVICE_H_
-
-#include <string>
-
-#include "base/base_export.h"
-#include "base/base_paths.h"
-#include "base/gtest_prod_util.h"
-#include "build/build_config.h"
-
-namespace base {
-
-class FilePath;
-class ScopedPathOverride;
-
-// The path service is a global table mapping keys to file system paths. It is
-// OK to use this service from multiple threads.
-//
-class BASE_EXPORT PathService {
- public:
- // Retrieves a path to a special directory or file and places it into the
- // string pointed to by 'path'. If you ask for a directory it is guaranteed
- // to NOT have a path separator at the end. For example, "c:\windows\temp"
- // Directories are also guaranteed to exist when this function succeeds.
- //
- // Returns true if the directory or file was successfully retrieved. On
- // failure, 'path' will not be changed.
- static bool Get(int key, FilePath* path);
-
- // Overrides the path to a special directory or file. This cannot be used to
- // change the value of DIR_CURRENT, but that should be obvious. Also, if the
- // path specifies a directory that does not exist, the directory will be
- // created by this method. This method returns true if successful.
- //
- // If the given path is relative, then it will be resolved against
- // DIR_CURRENT.
- //
- // WARNING: Consumers of PathService::Get may expect paths to be constant
- // over the lifetime of the app, so this method should be used with caution.
- //
- // Unit tests generally should use ScopedPathOverride instead. Overrides from
- // one test should not carry over to another.
- static bool Override(int key, const FilePath& path);
-
- // This function does the same as PathService::Override but it takes extra
- // parameters:
- // - |is_absolute| indicates that |path| has already been expanded into an
- // absolute path, otherwise MakeAbsoluteFilePath() will be used. This is
- // useful to override paths that may not exist yet, since MakeAbsoluteFilePath
- // fails for those. Note that MakeAbsoluteFilePath also expands symbolic
- // links, even if path.IsAbsolute() is already true.
- // - |create| guides whether the directory to be overriden must
- // be created in case it doesn't exist already.
- static bool OverrideAndCreateIfNeeded(int key,
- const FilePath& path,
- bool is_absolute,
- bool create);
-
- // To extend the set of supported keys, you can register a path provider,
- // which is just a function mirroring PathService::Get. The ProviderFunc
- // returns false if it cannot provide a non-empty path for the given key.
- // Otherwise, true is returned.
- //
- // WARNING: This function could be called on any thread from which the
- // PathService is used, so a the ProviderFunc MUST BE THREADSAFE.
- //
- typedef bool (*ProviderFunc)(int, FilePath*);
-
- // Call to register a path provider. You must specify the range "[key_start,
- // key_end)" of supported path keys.
- static void RegisterProvider(ProviderFunc provider,
- int key_start,
- int key_end);
-
- // Disable internal cache.
- static void DisableCache();
-
- private:
- friend class ScopedPathOverride;
- FRIEND_TEST_ALL_PREFIXES(PathServiceTest, RemoveOverride);
-
- // Removes an override for a special directory or file. Returns true if there
- // was an override to remove or false if none was present.
- // NOTE: This function is intended to be used by tests only!
- static bool RemoveOverride(int key);
-};
-
-} // namespace base
-
-// TODO(brettw) Convert all callers to using the base namespace and remove this.
-using base::PathService;
-
-#endif // BASE_PATH_SERVICE_H_
diff --git a/security/sandbox/chromium/base/posix/eintr_wrapper.h b/security/sandbox/chromium/base/posix/eintr_wrapper.h
deleted file mode 100644
index 5a5dc758a..000000000
--- a/security/sandbox/chromium/base/posix/eintr_wrapper.h
+++ /dev/null
@@ -1,67 +0,0 @@
-// 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.
-// To prevent long-lasting loops (which would likely be a bug, such as a signal
-// that should be masked) to go unnoticed, there is a limit after which the
-// caller will nonetheless see an EINTR in Debug builds.
-//
-// On Windows, this wrapper macro does nothing.
-//
-// 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_POSIX_EINTR_WRAPPER_H_
-#define BASE_POSIX_EINTR_WRAPPER_H_
-
-#include "build/build_config.h"
-
-#if defined(OS_POSIX)
-
-#include <errno.h>
-
-#if defined(NDEBUG)
-
-#define HANDLE_EINTR(x) ({ \
- decltype(x) eintr_wrapper_result; \
- do { \
- eintr_wrapper_result = (x); \
- } while (eintr_wrapper_result == -1 && errno == EINTR); \
- eintr_wrapper_result; \
-})
-
-#else
-
-#define HANDLE_EINTR(x) ({ \
- int eintr_wrapper_counter = 0; \
- decltype(x) eintr_wrapper_result; \
- do { \
- eintr_wrapper_result = (x); \
- } while (eintr_wrapper_result == -1 && errno == EINTR && \
- eintr_wrapper_counter++ < 100); \
- eintr_wrapper_result; \
-})
-
-#endif // NDEBUG
-
-#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; \
-})
-
-#else
-
-#define HANDLE_EINTR(x) (x)
-#define IGNORE_EINTR(x) (x)
-
-#endif // OS_POSIX
-
-#endif // BASE_POSIX_EINTR_WRAPPER_H_
diff --git a/security/sandbox/chromium/base/process/process_handle.h b/security/sandbox/chromium/base/process/process_handle.h
deleted file mode 100644
index ef7a60255..000000000
--- a/security/sandbox/chromium/base/process/process_handle.h
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright (c) 2013 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_PROCESS_HANDLE_H_
-#define BASE_PROCESS_PROCESS_HANDLE_H_
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include "base/base_export.h"
-#include "base/files/file_path.h"
-#include "build/build_config.h"
-
-#if defined(OS_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(OS_WIN)
-typedef HANDLE ProcessHandle;
-typedef DWORD ProcessId;
-typedef HANDLE UserTokenHandle;
-const ProcessHandle kNullProcessHandle = NULL;
-const ProcessId kNullProcessId = 0;
-#elif defined(OS_POSIX)
-// On POSIX, our ProcessHandle will just be the PID.
-typedef pid_t ProcessHandle;
-typedef pid_t ProcessId;
-const ProcessHandle kNullProcessHandle = 0;
-const ProcessId kNullProcessId = 0;
-#endif // defined(OS_WIN)
-
-// Returns the id of the current process.
-// Note that on some platforms, this is not guaranteed to be unique across
-// processes (use GetUniqueIdForProcess if uniqueness is required).
-BASE_EXPORT ProcessId GetCurrentProcId();
-
-// Returns a unique ID for the current process. The ID will be unique across all
-// currently running processes within the chrome session, but IDs of terminated
-// processes may be reused. This returns an opaque value that is different from
-// a process's PID.
-BASE_EXPORT uint32_t GetUniqueIdForProcess();
-
-#if defined(OS_LINUX)
-// When a process is started in a different PID namespace from the browser
-// process, this function must be called with the process's PID in the browser's
-// PID namespace in order to initialize its unique ID. Not thread safe.
-// WARNING: To avoid inconsistent results from GetUniqueIdForProcess, this
-// should only be called very early after process startup - ideally as soon
-// after process creation as possible.
-BASE_EXPORT void InitUniqueIdForProcessInPidNamespace(
- ProcessId pid_outside_of_namespace);
-#endif
-
-// Returns the ProcessHandle of the current process.
-BASE_EXPORT ProcessHandle GetCurrentProcessHandle();
-
-// Returns the process 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.
-// DEPRECATED. New code should be using Process::Pid() instead.
-// Note that on some platforms, this is not guaranteed to be unique across
-// processes.
-BASE_EXPORT ProcessId GetProcId(ProcessHandle process);
-
-// Returns the ID for the parent of the given process.
-BASE_EXPORT ProcessId GetParentProcessId(ProcessHandle process);
-
-#if defined(OS_POSIX)
-// Returns the path to the executable of the given process.
-BASE_EXPORT FilePath GetProcessExecutablePath(ProcessHandle process);
-#endif
-
-} // namespace base
-
-#endif // BASE_PROCESS_PROCESS_HANDLE_H_
diff --git a/security/sandbox/chromium/base/rand_util.h b/security/sandbox/chromium/base/rand_util.h
deleted file mode 100644
index 881dbd50b..000000000
--- a/security/sandbox/chromium/base/rand_util.h
+++ /dev/null
@@ -1,62 +0,0 @@
-// 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.
-
-#ifndef BASE_RAND_UTIL_H_
-#define BASE_RAND_UTIL_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <string>
-
-#include "base/base_export.h"
-#include "build/build_config.h"
-
-namespace base {
-
-// Returns a random number in range [0, UINT64_MAX]. Thread-safe.
-BASE_EXPORT uint64_t RandUint64();
-
-// Returns a random number between min and max (inclusive). Thread-safe.
-BASE_EXPORT int RandInt(int min, int max);
-
-// Returns a random number in range [0, range). Thread-safe.
-//
-// Note that this can be used as an adapter for std::random_shuffle():
-// Given a pre-populated |std::vector<int> myvector|, shuffle it as
-// std::random_shuffle(myvector.begin(), myvector.end(), base::RandGenerator);
-BASE_EXPORT uint64_t RandGenerator(uint64_t range);
-
-// Returns a random double in range [0, 1). Thread-safe.
-BASE_EXPORT double RandDouble();
-
-// Given input |bits|, convert with maximum precision to a double in
-// the range [0, 1). Thread-safe.
-BASE_EXPORT double BitsToOpenEndedUnitInterval(uint64_t bits);
-
-// Fills |output_length| bytes of |output| with random data.
-//
-// WARNING:
-// Do not use for security-sensitive purposes.
-// See crypto/ for cryptographically secure random number generation APIs.
-BASE_EXPORT void RandBytes(void* output, size_t output_length);
-
-// Fills a string of length |length| with random data and returns it.
-// |length| should be nonzero.
-//
-// Note that this is a variation of |RandBytes| with a different return type.
-// The returned string is likely not ASCII/UTF-8. Use with care.
-//
-// WARNING:
-// Do not use for security-sensitive purposes.
-// See crypto/ for cryptographically secure random number generation APIs.
-BASE_EXPORT std::string RandBytesAsString(size_t length);
-
-#if defined(OS_POSIX)
-BASE_EXPORT int GetUrandomFD();
-#endif
-
-} // namespace base
-
-#endif // BASE_RAND_UTIL_H_
diff --git a/security/sandbox/chromium/base/scoped_clear_errno.h b/security/sandbox/chromium/base/scoped_clear_errno.h
deleted file mode 100644
index 585f6f768..000000000
--- a/security/sandbox/chromium/base/scoped_clear_errno.h
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2013 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_CLEAR_ERRNO_H_
-#define BASE_SCOPED_CLEAR_ERRNO_H_
-
-#include <errno.h>
-
-#include "base/macros.h"
-
-namespace base {
-
-// Simple scoper that saves the current value of errno, resets it to 0, and on
-// destruction puts the old value back.
-class ScopedClearErrno {
- public:
- ScopedClearErrno() : old_errno_(errno) {
- errno = 0;
- }
- ~ScopedClearErrno() {
- if (errno == 0)
- errno = old_errno_;
- }
-
- private:
- const int old_errno_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedClearErrno);
-};
-
-} // namespace base
-
-#endif // BASE_SCOPED_CLEAR_ERRNO_H_
diff --git a/security/sandbox/chromium/base/sequence_checker.h b/security/sandbox/chromium/base/sequence_checker.h
deleted file mode 100644
index ad0182825..000000000
--- a/security/sandbox/chromium/base/sequence_checker.h
+++ /dev/null
@@ -1,62 +0,0 @@
-// 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.
-
-#ifndef BASE_SEQUENCE_CHECKER_H_
-#define BASE_SEQUENCE_CHECKER_H_
-
-// See comments for the similar block in thread_checker.h.
-#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
-#define ENABLE_SEQUENCE_CHECKER 1
-#else
-#define ENABLE_SEQUENCE_CHECKER 0
-#endif
-
-#include "base/sequence_checker_impl.h"
-
-namespace base {
-
-// Do nothing implementation, for use in release mode.
-//
-// Note: You should almost always use the SequenceChecker class to get
-// the right version for your build configuration.
-class SequenceCheckerDoNothing {
- public:
- bool CalledOnValidSequencedThread() const {
- return true;
- }
-
- void DetachFromSequence() {}
-};
-
-// SequenceChecker is a helper class used to help verify that some
-// methods of a class are called in sequence -- that is, called from
-// the same SequencedTaskRunner. It is a generalization of
-// ThreadChecker; see comments in sequence_checker_impl.h for details.
-//
-// Example:
-// class MyClass {
-// public:
-// void Foo() {
-// DCHECK(sequence_checker_.CalledOnValidSequencedThread());
-// ... (do stuff) ...
-// }
-//
-// private:
-// SequenceChecker sequence_checker_;
-// }
-//
-// In Release mode, CalledOnValidSequencedThread() will always return true.
-#if ENABLE_SEQUENCE_CHECKER
-class SequenceChecker : public SequenceCheckerImpl {
-};
-#else
-class SequenceChecker : public SequenceCheckerDoNothing {
-};
-#endif // ENABLE_SEQUENCE_CHECKER
-
-#undef ENABLE_SEQUENCE_CHECKER
-
-} // namespace base
-
-#endif // BASE_SEQUENCE_CHECKER_H_
diff --git a/security/sandbox/chromium/base/sequence_checker_impl.h b/security/sandbox/chromium/base/sequence_checker_impl.h
deleted file mode 100644
index e3c5fed50..000000000
--- a/security/sandbox/chromium/base/sequence_checker_impl.h
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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.
-
-#ifndef BASE_SEQUENCE_CHECKER_IMPL_H_
-#define BASE_SEQUENCE_CHECKER_IMPL_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/sequenced_worker_pool.h"
-#include "base/threading/thread_checker_impl.h"
-
-namespace base {
-
-// SequenceCheckerImpl is used to help verify that some methods of a
-// class are called in sequence -- that is, called from the same
-// SequencedTaskRunner. It is a generalization of ThreadChecker; in
-// particular, it behaves exactly like ThreadChecker if constructed
-// on a thread that is not part of a SequencedWorkerPool.
-class BASE_EXPORT SequenceCheckerImpl {
- public:
- SequenceCheckerImpl();
- ~SequenceCheckerImpl();
-
- // Returns whether the we are being called on the same sequence token
- // as previous calls. If there is no associated sequence, then returns
- // whether we are being called on the underlying ThreadChecker's thread.
- bool CalledOnValidSequencedThread() const;
-
- // Unbinds the checker from the currently associated sequence. The
- // checker will be re-bound on the next call to CalledOnValidSequence().
- void DetachFromSequence();
-
- private:
- void EnsureSequenceTokenAssigned() const;
-
- // Guards all variables below.
- mutable Lock lock_;
-
- // Used if |sequence_token_| is not valid.
- ThreadCheckerImpl thread_checker_;
- mutable bool sequence_token_assigned_;
-
- mutable SequencedWorkerPool::SequenceToken sequence_token_;
-
- DISALLOW_COPY_AND_ASSIGN(SequenceCheckerImpl);
-};
-
-} // namespace base
-
-#endif // BASE_SEQUENCE_CHECKER_IMPL_H_
diff --git a/security/sandbox/chromium/base/sequenced_task_runner.h b/security/sandbox/chromium/base/sequenced_task_runner.h
deleted file mode 100644
index 6bb3f2b87..000000000
--- a/security/sandbox/chromium/base/sequenced_task_runner.h
+++ /dev/null
@@ -1,159 +0,0 @@
-// 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.
-
-#ifndef BASE_SEQUENCED_TASK_RUNNER_H_
-#define BASE_SEQUENCED_TASK_RUNNER_H_
-
-#include "base/base_export.h"
-#include "base/sequenced_task_runner_helpers.h"
-#include "base/task_runner.h"
-
-namespace base {
-
-// A SequencedTaskRunner is a subclass of TaskRunner that provides
-// additional guarantees on the order that tasks are started, as well
-// as guarantees on when tasks are in sequence, i.e. one task finishes
-// before the other one starts.
-//
-// Summary
-// -------
-// Non-nested tasks with the same delay will run one by one in FIFO
-// order.
-//
-// Detailed guarantees
-// -------------------
-//
-// SequencedTaskRunner also adds additional methods for posting
-// non-nestable tasks. In general, an implementation of TaskRunner
-// may expose task-running methods which are themselves callable from
-// within tasks. A non-nestable task is one that is guaranteed to not
-// be run from within an already-running task. Conversely, a nestable
-// task (the default) is a task that can be run from within an
-// already-running task.
-//
-// The guarantees of SequencedTaskRunner are as follows:
-//
-// - Given two tasks T2 and T1, T2 will start after T1 starts if:
-//
-// * T2 is posted after T1; and
-// * T2 has equal or higher delay than T1; and
-// * T2 is non-nestable or T1 is nestable.
-//
-// - If T2 will start after T1 starts by the above guarantee, then
-// T2 will start after T1 finishes and is destroyed if:
-//
-// * T2 is non-nestable, or
-// * T1 doesn't call any task-running methods.
-//
-// - If T2 will start after T1 finishes by the above guarantee, then
-// all memory changes in T1 and T1's destruction will be visible
-// to T2.
-//
-// - If T2 runs nested within T1 via a call to the task-running
-// method M, then all memory changes in T1 up to the call to M
-// will be visible to T2, and all memory changes in T2 will be
-// visible to T1 from the return from M.
-//
-// Note that SequencedTaskRunner does not guarantee that tasks are run
-// on a single dedicated thread, although the above guarantees provide
-// most (but not all) of the same guarantees. If you do need to
-// guarantee that tasks are run on a single dedicated thread, see
-// SingleThreadTaskRunner (in single_thread_task_runner.h).
-//
-// Some corollaries to the above guarantees, assuming the tasks in
-// question don't call any task-running methods:
-//
-// - Tasks posted via PostTask are run in FIFO order.
-//
-// - Tasks posted via PostNonNestableTask are run in FIFO order.
-//
-// - Tasks posted with the same delay and the same nestable state
-// are run in FIFO order.
-//
-// - A list of tasks with the same nestable state posted in order of
-// non-decreasing delay is run in FIFO order.
-//
-// - A list of tasks posted in order of non-decreasing delay with at
-// most a single change in nestable state from nestable to
-// non-nestable is run in FIFO order. (This is equivalent to the
-// statement of the first guarantee above.)
-//
-// Some theoretical implementations of SequencedTaskRunner:
-//
-// - A SequencedTaskRunner that wraps a regular TaskRunner but makes
-// sure that only one task at a time is posted to the TaskRunner,
-// with appropriate memory barriers in between tasks.
-//
-// - A SequencedTaskRunner that, for each task, spawns a joinable
-// thread to run that task and immediately quit, and then
-// immediately joins that thread.
-//
-// - A SequencedTaskRunner that stores the list of posted tasks and
-// has a method Run() that runs each runnable task in FIFO order
-// that can be called from any thread, but only if another
-// (non-nested) Run() call isn't already happening.
-class BASE_EXPORT SequencedTaskRunner : public TaskRunner {
- public:
- // The two PostNonNestable*Task methods below are like their
- // nestable equivalents in TaskRunner, but they guarantee that the
- // posted task will not run nested within an already-running task.
- //
- // A simple corollary is that posting a task as non-nestable can
- // only delay when the task gets run. That is, posting a task as
- // non-nestable may not affect when the task gets run, or it could
- // make it run later than it normally would, but it won't make it
- // run earlier than it normally would.
-
- // TODO(akalin): Get rid of the boolean return value for the methods
- // below.
-
- bool PostNonNestableTask(const tracked_objects::Location& from_here,
- const Closure& task);
-
- virtual bool PostNonNestableDelayedTask(
- const tracked_objects::Location& from_here,
- const Closure& task,
- base::TimeDelta delay) = 0;
-
- // Submits a non-nestable task to delete the given object. Returns
- // true if the object may be deleted at some point in the future,
- // and false if the object definitely will not be deleted.
- template <class T>
- bool DeleteSoon(const tracked_objects::Location& from_here,
- const T* object) {
- return
- subtle::DeleteHelperInternal<T, bool>::DeleteViaSequencedTaskRunner(
- this, from_here, object);
- }
-
- // Submits a non-nestable task to release the given object. Returns
- // true if the object may be released at some point in the future,
- // and false if the object definitely will not be released.
- template <class T>
- bool ReleaseSoon(const tracked_objects::Location& from_here,
- T* object) {
- return
- subtle::ReleaseHelperInternal<T, bool>::ReleaseViaSequencedTaskRunner(
- this, from_here, object);
- }
-
- protected:
- ~SequencedTaskRunner() override {}
-
- private:
- template <class T, class R> friend class subtle::DeleteHelperInternal;
- template <class T, class R> friend class subtle::ReleaseHelperInternal;
-
- bool DeleteSoonInternal(const tracked_objects::Location& from_here,
- void(*deleter)(const void*),
- const void* object);
-
- bool ReleaseSoonInternal(const tracked_objects::Location& from_here,
- void(*releaser)(const void*),
- const void* object);
-};
-
-} // namespace base
-
-#endif // BASE_SEQUENCED_TASK_RUNNER_H_
diff --git a/security/sandbox/chromium/base/sequenced_task_runner_helpers.h b/security/sandbox/chromium/base/sequenced_task_runner_helpers.h
deleted file mode 100644
index 7980b46b6..000000000
--- a/security/sandbox/chromium/base/sequenced_task_runner_helpers.h
+++ /dev/null
@@ -1,113 +0,0 @@
-// 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.
-
-#ifndef BASE_SEQUENCED_TASK_RUNNER_HELPERS_H_
-#define BASE_SEQUENCED_TASK_RUNNER_HELPERS_H_
-
-#include "base/debug/alias.h"
-#include "base/macros.h"
-
-// TODO(akalin): Investigate whether it's possible to just have
-// SequencedTaskRunner use these helpers (instead of MessageLoop).
-// Then we can just move these to sequenced_task_runner.h.
-
-namespace tracked_objects {
-class Location;
-}
-
-namespace base {
-
-namespace subtle {
-template <class T, class R> class DeleteHelperInternal;
-template <class T, class R> class ReleaseHelperInternal;
-}
-
-// Template helpers which use function indirection to erase T from the
-// function signature while still remembering it so we can call the
-// correct destructor/release function.
-//
-// We use this trick so we don't need to include bind.h in a header
-// file like sequenced_task_runner.h. We also wrap the helpers in a
-// templated class to make it easier for users of DeleteSoon to
-// declare the helper as a friend.
-template <class T>
-class DeleteHelper {
- private:
- template <class T2, class R> friend class subtle::DeleteHelperInternal;
-
- static void DoDelete(const void* object) {
- delete reinterpret_cast<const T*>(object);
- }
-
- DISALLOW_COPY_AND_ASSIGN(DeleteHelper);
-};
-
-template <class T>
-class ReleaseHelper {
- private:
- template <class T2, class R> friend class subtle::ReleaseHelperInternal;
-
- static void DoRelease(const void* object) {
- reinterpret_cast<const T*>(object)->Release();
- }
-
- DISALLOW_COPY_AND_ASSIGN(ReleaseHelper);
-};
-
-namespace subtle {
-
-// An internal SequencedTaskRunner-like class helper for DeleteHelper
-// and ReleaseHelper. We don't want to expose the Do*() functions
-// directly directly since the void* argument makes it possible to
-// pass/ an object of the wrong type to delete. Instead, we force
-// callers to go through these internal helpers for type
-// safety. SequencedTaskRunner-like classes which expose DeleteSoon or
-// ReleaseSoon methods should friend the appropriate helper and
-// implement a corresponding *Internal method with the following
-// signature:
-//
-// bool(const tracked_objects::Location&,
-// void(*function)(const void*),
-// void* object)
-//
-// An implementation of this function should simply create a
-// base::Closure from (function, object) and return the result of
-// posting the task.
-template <class T, class ReturnType>
-class DeleteHelperInternal {
- public:
- template <class SequencedTaskRunnerType>
- static ReturnType DeleteViaSequencedTaskRunner(
- SequencedTaskRunnerType* sequenced_task_runner,
- const tracked_objects::Location& from_here,
- const T* object) {
- return sequenced_task_runner->DeleteSoonInternal(
- from_here, &DeleteHelper<T>::DoDelete, object);
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(DeleteHelperInternal);
-};
-
-template <class T, class ReturnType>
-class ReleaseHelperInternal {
- public:
- template <class SequencedTaskRunnerType>
- static ReturnType ReleaseViaSequencedTaskRunner(
- SequencedTaskRunnerType* sequenced_task_runner,
- const tracked_objects::Location& from_here,
- const T* object) {
- return sequenced_task_runner->ReleaseSoonInternal(
- from_here, &ReleaseHelper<T>::DoRelease, object);
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(ReleaseHelperInternal);
-};
-
-} // namespace subtle
-
-} // namespace base
-
-#endif // BASE_SEQUENCED_TASK_RUNNER_HELPERS_H_
diff --git a/security/sandbox/chromium/base/single_thread_task_runner.h b/security/sandbox/chromium/base/single_thread_task_runner.h
deleted file mode 100644
index 6e9319314..000000000
--- a/security/sandbox/chromium/base/single_thread_task_runner.h
+++ /dev/null
@@ -1,38 +0,0 @@
-// 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.
-
-#ifndef BASE_SINGLE_THREAD_TASK_RUNNER_H_
-#define BASE_SINGLE_THREAD_TASK_RUNNER_H_
-
-#include "base/base_export.h"
-#include "base/sequenced_task_runner.h"
-
-namespace base {
-
-// A SingleThreadTaskRunner is a SequencedTaskRunner with one more
-// guarantee; namely, that all tasks are run on a single dedicated
-// thread. Most use cases require only a SequencedTaskRunner, unless
-// there is a specific need to run tasks on only a single thread.
-//
-// SingleThreadTaskRunner implementations might:
-// - Post tasks to an existing thread's MessageLoop (see
-// MessageLoop::task_runner()).
-// - Create their own worker thread and MessageLoop to post tasks to.
-// - Add tasks to a FIFO and signal to a non-MessageLoop thread for them to
-// be processed. This allows TaskRunner-oriented code run on threads
-// running other kinds of message loop, e.g. Jingle threads.
-class BASE_EXPORT SingleThreadTaskRunner : public SequencedTaskRunner {
- public:
- // A more explicit alias to RunsTasksOnCurrentThread().
- bool BelongsToCurrentThread() const {
- return RunsTasksOnCurrentThread();
- }
-
- protected:
- ~SingleThreadTaskRunner() override {}
-};
-
-} // namespace base
-
-#endif // BASE_SINGLE_THREAD_TASK_RUNNER_H_
diff --git a/security/sandbox/chromium/base/stl_util.h b/security/sandbox/chromium/base/stl_util.h
deleted file mode 100644
index 12e226a9d..000000000
--- a/security/sandbox/chromium/base/stl_util.h
+++ /dev/null
@@ -1,262 +0,0 @@
-// 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.
-
-// Derived from google3/util/gtl/stl_util.h
-
-#ifndef BASE_STL_UTIL_H_
-#define BASE_STL_UTIL_H_
-
-#include <algorithm>
-#include <functional>
-#include <iterator>
-#include <string>
-#include <vector>
-
-#include "base/logging.h"
-
-// Clears 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);
- // Sometimes "T tmp" allocates objects with memory (arena implementation?).
- // Hence using additional reserve(0) even if it doesn't always work.
- obj->reserve(0);
-}
-
-// 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;
- }
-}
-
-// 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;
- }
-}
-
-// 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;
- }
-}
-
-// For a range within a container of pairs, calls delete.
-// NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
-// Deleting the value does not always invalidate the iterator, but it may
-// do so if the key is a pointer into the value object.
-template <class ForwardIterator>
-void STLDeleteContainerPairSecondPointers(ForwardIterator begin,
- ForwardIterator end) {
- while (begin != end) {
- ForwardIterator temp = begin;
- ++begin;
- delete temp->second;
- }
-}
-
-// Counts the number of instances of val in a container.
-template <typename Container, typename T>
-typename std::iterator_traits<
- typename Container::const_iterator>::difference_type
-STLCount(const Container& container, const T& val) {
- return std::count(container.begin(), container.end(), val);
-}
-
-// 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())
- return str->empty() ? NULL : &*str->begin();
-}
-
-// 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* container) {
- if (!container)
- return;
- STLDeleteContainerPairSecondPointers(container->begin(), container->end());
- container->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 T>
-class STLElementDeleter {
- public:
- STLElementDeleter<T>(T* container) : container_(container) {}
- ~STLElementDeleter<T>() { STLDeleteElements(container_); }
-
- private:
- T* container_;
-};
-
-// Given a pointer to an STL container this class will delete all the value
-// pointers when it goes out of scope.
-template<class T>
-class STLValueDeleter {
- public:
- STLValueDeleter<T>(T* container) : container_(container) {}
- ~STLValueDeleter<T>() { STLDeleteValues(container_); }
-
- private:
- T* container_;
-};
-
-// Test to see if a set, map, hash_set or hash_map contains a particular key.
-// Returns true if the key is in the collection.
-template <typename Collection, typename Key>
-bool ContainsKey(const Collection& collection, const Key& key) {
- return collection.find(key) != collection.end();
-}
-
-// Test to see if a collection like a vector contains a particular value.
-// Returns true if the value is in the collection.
-template <typename Collection, typename Value>
-bool ContainsValue(const Collection& collection, const Value& value) {
- return std::find(collection.begin(), collection.end(), value) !=
- collection.end();
-}
-
-namespace base {
-
-// Returns true if the container is sorted.
-template <typename Container>
-bool STLIsSorted(const Container& cont) {
- // Note: Use reverse iterator on container to ensure we only require
- // value_type to implement operator<.
- return std::adjacent_find(cont.rbegin(), cont.rend(),
- std::less<typename Container::value_type>())
- == cont.rend();
-}
-
-// Returns a new ResultType containing the difference of two sorted containers.
-template <typename ResultType, typename Arg1, typename Arg2>
-ResultType STLSetDifference(const Arg1& a1, const Arg2& a2) {
- DCHECK(STLIsSorted(a1));
- DCHECK(STLIsSorted(a2));
- ResultType difference;
- std::set_difference(a1.begin(), a1.end(),
- a2.begin(), a2.end(),
- std::inserter(difference, difference.end()));
- return difference;
-}
-
-// Returns a new ResultType containing the union of two sorted containers.
-template <typename ResultType, typename Arg1, typename Arg2>
-ResultType STLSetUnion(const Arg1& a1, const Arg2& a2) {
- DCHECK(STLIsSorted(a1));
- DCHECK(STLIsSorted(a2));
- ResultType result;
- std::set_union(a1.begin(), a1.end(),
- a2.begin(), a2.end(),
- std::inserter(result, result.end()));
- return result;
-}
-
-// Returns a new ResultType containing the intersection of two sorted
-// containers.
-template <typename ResultType, typename Arg1, typename Arg2>
-ResultType STLSetIntersection(const Arg1& a1, const Arg2& a2) {
- DCHECK(STLIsSorted(a1));
- DCHECK(STLIsSorted(a2));
- ResultType result;
- std::set_intersection(a1.begin(), a1.end(),
- a2.begin(), a2.end(),
- std::inserter(result, result.end()));
- return result;
-}
-
-// Returns true if the sorted container |a1| contains all elements of the sorted
-// container |a2|.
-template <typename Arg1, typename Arg2>
-bool STLIncludes(const Arg1& a1, const Arg2& a2) {
- DCHECK(STLIsSorted(a1));
- DCHECK(STLIsSorted(a2));
- return std::includes(a1.begin(), a1.end(),
- a2.begin(), a2.end());
-}
-
-} // namespace base
-
-#endif // BASE_STL_UTIL_H_
diff --git a/security/sandbox/chromium/base/strings/nullable_string16.cc b/security/sandbox/chromium/base/strings/nullable_string16.cc
deleted file mode 100644
index 07f81d433..000000000
--- a/security/sandbox/chromium/base/strings/nullable_string16.cc
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) 2013 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/strings/nullable_string16.h"
-
-#include <ostream>
-
-#include "base/strings/utf_string_conversions.h"
-
-namespace base {
-
-std::ostream& operator<<(std::ostream& out, const NullableString16& value) {
- return value.is_null() ? out << "(null)" : out << UTF16ToUTF8(value.string());
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/nullable_string16.h b/security/sandbox/chromium/base/strings/nullable_string16.h
deleted file mode 100644
index 016c25c25..000000000
--- a/security/sandbox/chromium/base/strings/nullable_string16.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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_STRINGS_NULLABLE_STRING16_H_
-#define BASE_STRINGS_NULLABLE_STRING16_H_
-
-#include <iosfwd>
-
-#include "base/base_export.h"
-#include "base/strings/string16.h"
-
-namespace base {
-
-// This class is a simple wrapper for string16 which also contains a null
-// state. This should be used only where the difference between null and
-// empty is meaningful.
-class NullableString16 {
- public:
- NullableString16() : is_null_(true) { }
- NullableString16(const string16& string, bool is_null)
- : string_(string), is_null_(is_null) {
- }
-
- const string16& string() const { return string_; }
- bool is_null() const { return is_null_; }
-
- private:
- string16 string_;
- bool is_null_;
-};
-
-inline bool operator==(const NullableString16& a, const NullableString16& b) {
- return a.is_null() == b.is_null() && a.string() == b.string();
-}
-
-inline bool operator!=(const NullableString16& a, const NullableString16& b) {
- return !(a == b);
-}
-
-BASE_EXPORT std::ostream& operator<<(std::ostream& out,
- const NullableString16& value);
-
-} // namespace base
-
-#endif // BASE_STRINGS_NULLABLE_STRING16_H_
diff --git a/security/sandbox/chromium/base/strings/safe_sprintf.cc b/security/sandbox/chromium/base/strings/safe_sprintf.cc
deleted file mode 100644
index a51c77827..000000000
--- a/security/sandbox/chromium/base/strings/safe_sprintf.cc
+++ /dev/null
@@ -1,686 +0,0 @@
-// Copyright 2013 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/strings/safe_sprintf.h"
-
-#include <errno.h>
-#include <string.h>
-
-#include <limits>
-
-#include "base/macros.h"
-#include "build/build_config.h"
-
-#if !defined(NDEBUG)
-// In debug builds, we use RAW_CHECK() to print useful error messages, if
-// SafeSPrintf() is called with broken arguments.
-// As our contract promises that SafeSPrintf() can be called from any
-// restricted run-time context, it is not actually safe to call logging
-// functions from it; and we only ever do so for debug builds and hope for the
-// best. We should _never_ call any logging function other than RAW_CHECK(),
-// and we should _never_ include any logging code that is active in production
-// builds. Most notably, we should not include these logging functions in
-// unofficial release builds, even though those builds would otherwise have
-// DCHECKS() enabled.
-// In other words; please do not remove the #ifdef around this #include.
-// Instead, in production builds we opt for returning a degraded result,
-// whenever an error is encountered.
-// E.g. The broken function call
-// SafeSPrintf("errno = %d (%x)", errno, strerror(errno))
-// will print something like
-// errno = 13, (%x)
-// instead of
-// errno = 13 (Access denied)
-// In most of the anticipated use cases, that's probably the preferred
-// behavior.
-#include "base/logging.h"
-#define DEBUG_CHECK RAW_CHECK
-#else
-#define DEBUG_CHECK(x) do { if (x) { } } while (0)
-#endif
-
-namespace base {
-namespace strings {
-
-// The code in this file is extremely careful to be async-signal-safe.
-//
-// Most obviously, we avoid calling any code that could dynamically allocate
-// memory. Doing so would almost certainly result in bugs and dead-locks.
-// We also avoid calling any other STL functions that could have unintended
-// side-effects involving memory allocation or access to other shared
-// resources.
-//
-// But on top of that, we also avoid calling other library functions, as many
-// of them have the side-effect of calling getenv() (in order to deal with
-// localization) or accessing errno. The latter sounds benign, but there are
-// several execution contexts where it isn't even possible to safely read let
-// alone write errno.
-//
-// The stated design goal of the SafeSPrintf() function is that it can be
-// called from any context that can safely call C or C++ code (i.e. anything
-// that doesn't require assembly code).
-//
-// For a brief overview of some but not all of the issues with async-signal-
-// safety, refer to:
-// http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html
-
-namespace {
-const size_t kSSizeMaxConst = ((size_t)(ssize_t)-1) >> 1;
-
-const char kUpCaseHexDigits[] = "0123456789ABCDEF";
-const char kDownCaseHexDigits[] = "0123456789abcdef";
-}
-
-#if defined(NDEBUG)
-// We would like to define kSSizeMax as std::numeric_limits<ssize_t>::max(),
-// but C++ doesn't allow us to do that for constants. Instead, we have to
-// use careful casting and shifting. We later use a static_assert to
-// verify that this worked correctly.
-namespace {
-const size_t kSSizeMax = kSSizeMaxConst;
-}
-#else // defined(NDEBUG)
-// For efficiency, we really need kSSizeMax to be a constant. But for unit
-// tests, it should be adjustable. This allows us to verify edge cases without
-// having to fill the entire available address space. As a compromise, we make
-// kSSizeMax adjustable in debug builds, and then only compile that particular
-// part of the unit test in debug builds.
-namespace {
-static size_t kSSizeMax = kSSizeMaxConst;
-}
-
-namespace internal {
-void SetSafeSPrintfSSizeMaxForTest(size_t max) {
- kSSizeMax = max;
-}
-
-size_t GetSafeSPrintfSSizeMaxForTest() {
- return kSSizeMax;
-}
-}
-#endif // defined(NDEBUG)
-
-namespace {
-class Buffer {
- public:
- // |buffer| is caller-allocated storage that SafeSPrintf() writes to. It
- // has |size| bytes of writable storage. It is the caller's responsibility
- // to ensure that the buffer is at least one byte in size, so that it fits
- // the trailing NUL that will be added by the destructor. The buffer also
- // must be smaller or equal to kSSizeMax in size.
- Buffer(char* buffer, size_t size)
- : buffer_(buffer),
- size_(size - 1), // Account for trailing NUL byte
- count_(0) {
-// MSVS2013's standard library doesn't mark max() as constexpr yet. cl.exe
-// supports static_cast but doesn't really implement constexpr yet so it doesn't
-// complain, but clang does.
-#if __cplusplus >= 201103 && !(defined(__clang__) && defined(OS_WIN))
- static_assert(kSSizeMaxConst ==
- static_cast<size_t>(std::numeric_limits<ssize_t>::max()),
- "kSSizeMaxConst should be the max value of an ssize_t");
-#endif
- DEBUG_CHECK(size > 0);
- DEBUG_CHECK(size <= kSSizeMax);
- }
-
- ~Buffer() {
- // The code calling the constructor guaranteed that there was enough space
- // to store a trailing NUL -- and in debug builds, we are actually
- // verifying this with DEBUG_CHECK()s in the constructor. So, we can
- // always unconditionally write the NUL byte in the destructor. We do not
- // need to adjust the count_, as SafeSPrintf() copies snprintf() in not
- // including the NUL byte in its return code.
- *GetInsertionPoint() = '\000';
- }
-
- // Returns true, iff the buffer is filled all the way to |kSSizeMax-1|. The
- // caller can now stop adding more data, as GetCount() has reached its
- // maximum possible value.
- inline bool OutOfAddressableSpace() const {
- return count_ == static_cast<size_t>(kSSizeMax - 1);
- }
-
- // Returns the number of bytes that would have been emitted to |buffer_|
- // if it was sized sufficiently large. This number can be larger than
- // |size_|, if the caller provided an insufficiently large output buffer.
- // But it will never be bigger than |kSSizeMax-1|.
- inline ssize_t GetCount() const {
- DEBUG_CHECK(count_ < kSSizeMax);
- return static_cast<ssize_t>(count_);
- }
-
- // Emits one |ch| character into the |buffer_| and updates the |count_| of
- // characters that are currently supposed to be in the buffer.
- // Returns "false", iff the buffer was already full.
- // N.B. |count_| increases even if no characters have been written. This is
- // needed so that GetCount() can return the number of bytes that should
- // have been allocated for the |buffer_|.
- inline bool Out(char ch) {
- if (size_ >= 1 && count_ < size_) {
- buffer_[count_] = ch;
- return IncrementCountByOne();
- }
- // |count_| still needs to be updated, even if the buffer has been
- // filled completely. This allows SafeSPrintf() to return the number of
- // bytes that should have been emitted.
- IncrementCountByOne();
- return false;
- }
-
- // Inserts |padding|-|len| bytes worth of padding into the |buffer_|.
- // |count_| will also be incremented by the number of bytes that were meant
- // to be emitted. The |pad| character is typically either a ' ' space
- // or a '0' zero, but other non-NUL values are legal.
- // Returns "false", iff the the |buffer_| filled up (i.e. |count_|
- // overflowed |size_|) at any time during padding.
- inline bool Pad(char pad, size_t padding, size_t len) {
- DEBUG_CHECK(pad);
- DEBUG_CHECK(padding <= kSSizeMax);
- for (; padding > len; --padding) {
- if (!Out(pad)) {
- if (--padding) {
- IncrementCount(padding-len);
- }
- return false;
- }
- }
- return true;
- }
-
- // POSIX doesn't define any async-signal-safe function for converting
- // an integer to ASCII. Define our own version.
- //
- // This also gives us the ability to make the function a little more
- // powerful and have it deal with |padding|, with truncation, and with
- // predicting the length of the untruncated output.
- //
- // IToASCII() converts an integer |i| to ASCII.
- //
- // Unlike similar functions in the standard C library, it never appends a
- // NUL character. This is left for the caller to do.
- //
- // While the function signature takes a signed int64_t, the code decides at
- // run-time whether to treat the argument as signed (int64_t) or as unsigned
- // (uint64_t) based on the value of |sign|.
- //
- // It supports |base|s 2 through 16. Only a |base| of 10 is allowed to have
- // a |sign|. Otherwise, |i| is treated as unsigned.
- //
- // For bases larger than 10, |upcase| decides whether lower-case or upper-
- // case letters should be used to designate digits greater than 10.
- //
- // Padding can be done with either '0' zeros or ' ' spaces. Padding has to
- // be positive and will always be applied to the left of the output.
- //
- // Prepends a |prefix| to the number (e.g. "0x"). This prefix goes to
- // the left of |padding|, if |pad| is '0'; and to the right of |padding|
- // if |pad| is ' '.
- //
- // Returns "false", if the |buffer_| overflowed at any time.
- bool IToASCII(bool sign, bool upcase, int64_t i, int base,
- char pad, size_t padding, const char* prefix);
-
- private:
- // Increments |count_| by |inc| unless this would cause |count_| to
- // overflow |kSSizeMax-1|. Returns "false", iff an overflow was detected;
- // it then clamps |count_| to |kSSizeMax-1|.
- inline bool IncrementCount(size_t inc) {
- // "inc" is either 1 or a "padding" value. Padding is clamped at
- // run-time to at most kSSizeMax-1. So, we know that "inc" is always in
- // the range 1..kSSizeMax-1.
- // This allows us to compute "kSSizeMax - 1 - inc" without incurring any
- // integer overflows.
- DEBUG_CHECK(inc <= kSSizeMax - 1);
- if (count_ > kSSizeMax - 1 - inc) {
- count_ = kSSizeMax - 1;
- return false;
- } else {
- count_ += inc;
- return true;
- }
- }
-
- // Convenience method for the common case of incrementing |count_| by one.
- inline bool IncrementCountByOne() {
- return IncrementCount(1);
- }
-
- // Return the current insertion point into the buffer. This is typically
- // at |buffer_| + |count_|, but could be before that if truncation
- // happened. It always points to one byte past the last byte that was
- // successfully placed into the |buffer_|.
- inline char* GetInsertionPoint() const {
- size_t idx = count_;
- if (idx > size_) {
- idx = size_;
- }
- return buffer_ + idx;
- }
-
- // User-provided buffer that will receive the fully formatted output string.
- char* buffer_;
-
- // Number of bytes that are available in the buffer excluding the trailing
- // NUL byte that will be added by the destructor.
- const size_t size_;
-
- // Number of bytes that would have been emitted to the buffer, if the buffer
- // was sufficiently big. This number always excludes the trailing NUL byte
- // and it is guaranteed to never grow bigger than kSSizeMax-1.
- size_t count_;
-
- DISALLOW_COPY_AND_ASSIGN(Buffer);
-};
-
-
-bool Buffer::IToASCII(bool sign, bool upcase, int64_t i, int base,
- char pad, size_t padding, const char* prefix) {
- // Sanity check for parameters. None of these should ever fail, but see
- // above for the rationale why we can't call CHECK().
- DEBUG_CHECK(base >= 2);
- DEBUG_CHECK(base <= 16);
- DEBUG_CHECK(!sign || base == 10);
- DEBUG_CHECK(pad == '0' || pad == ' ');
- DEBUG_CHECK(padding <= kSSizeMax);
- DEBUG_CHECK(!(sign && prefix && *prefix));
-
- // Handle negative numbers, if the caller indicated that |i| should be
- // treated as a signed number; otherwise treat |i| as unsigned (even if the
- // MSB is set!)
- // Details are tricky, because of limited data-types, but equivalent pseudo-
- // code would look like:
- // if (sign && i < 0)
- // prefix = "-";
- // num = abs(i);
- int minint = 0;
- uint64_t num;
- if (sign && i < 0) {
- prefix = "-";
-
- // Turn our number positive.
- if (i == std::numeric_limits<int64_t>::min()) {
- // The most negative integer needs special treatment.
- minint = 1;
- num = static_cast<uint64_t>(-(i + 1));
- } else {
- // "Normal" negative numbers are easy.
- num = static_cast<uint64_t>(-i);
- }
- } else {
- num = static_cast<uint64_t>(i);
- }
-
- // If padding with '0' zero, emit the prefix or '-' character now. Otherwise,
- // make the prefix accessible in reverse order, so that we can later output
- // it right between padding and the number.
- // We cannot choose the easier approach of just reversing the number, as that
- // fails in situations where we need to truncate numbers that have padding
- // and/or prefixes.
- const char* reverse_prefix = NULL;
- if (prefix && *prefix) {
- if (pad == '0') {
- while (*prefix) {
- if (padding) {
- --padding;
- }
- Out(*prefix++);
- }
- prefix = NULL;
- } else {
- for (reverse_prefix = prefix; *reverse_prefix; ++reverse_prefix) {
- }
- }
- } else
- prefix = NULL;
- const size_t prefix_length = reverse_prefix - prefix;
-
- // Loop until we have converted the entire number. Output at least one
- // character (i.e. '0').
- size_t start = count_;
- size_t discarded = 0;
- bool started = false;
- do {
- // Make sure there is still enough space left in our output buffer.
- if (count_ >= size_) {
- if (start < size_) {
- // It is rare that we need to output a partial number. But if asked
- // to do so, we will still make sure we output the correct number of
- // leading digits.
- // Since we are generating the digits in reverse order, we actually
- // have to discard digits in the order that we have already emitted
- // them. This is essentially equivalent to:
- // memmove(buffer_ + start, buffer_ + start + 1, size_ - start - 1)
- for (char* move = buffer_ + start, *end = buffer_ + size_ - 1;
- move < end;
- ++move) {
- *move = move[1];
- }
- ++discarded;
- --count_;
- } else if (count_ - size_ > 1) {
- // Need to increment either |count_| or |discarded| to make progress.
- // The latter is more efficient, as it eventually triggers fast
- // handling of padding. But we have to ensure we don't accidentally
- // change the overall state (i.e. switch the state-machine from
- // discarding to non-discarding). |count_| needs to always stay
- // bigger than |size_|.
- --count_;
- ++discarded;
- }
- }
-
- // Output the next digit and (if necessary) compensate for the most
- // negative integer needing special treatment. This works because,
- // no matter the bit width of the integer, the lowest-most decimal
- // integer always ends in 2, 4, 6, or 8.
- if (!num && started) {
- if (reverse_prefix > prefix) {
- Out(*--reverse_prefix);
- } else {
- Out(pad);
- }
- } else {
- started = true;
- Out((upcase ? kUpCaseHexDigits : kDownCaseHexDigits)[num%base + minint]);
- }
-
- minint = 0;
- num /= base;
-
- // Add padding, if requested.
- if (padding > 0) {
- --padding;
-
- // Performance optimization for when we are asked to output excessive
- // padding, but our output buffer is limited in size. Even if we output
- // a 64bit number in binary, we would never write more than 64 plus
- // prefix non-padding characters. So, once this limit has been passed,
- // any further state change can be computed arithmetically; we know that
- // by this time, our entire final output consists of padding characters
- // that have all already been output.
- if (discarded > 8*sizeof(num) + prefix_length) {
- IncrementCount(padding);
- padding = 0;
- }
- }
- } while (num || padding || (reverse_prefix > prefix));
-
- // Conversion to ASCII actually resulted in the digits being in reverse
- // order. We can't easily generate them in forward order, as we can't tell
- // the number of characters needed until we are done converting.
- // So, now, we reverse the string (except for the possible '-' sign).
- char* front = buffer_ + start;
- char* back = GetInsertionPoint();
- while (--back > front) {
- char ch = *back;
- *back = *front;
- *front++ = ch;
- }
-
- IncrementCount(discarded);
- return !discarded;
-}
-
-} // anonymous namespace
-
-namespace internal {
-
-ssize_t SafeSNPrintf(char* buf, size_t sz, const char* fmt, const Arg* args,
- const size_t max_args) {
- // Make sure that at least one NUL byte can be written, and that the buffer
- // never overflows kSSizeMax. Not only does that use up most or all of the
- // address space, it also would result in a return code that cannot be
- // represented.
- if (static_cast<ssize_t>(sz) < 1) {
- return -1;
- } else if (sz > kSSizeMax) {
- sz = kSSizeMax;
- }
-
- // Iterate over format string and interpret '%' arguments as they are
- // encountered.
- Buffer buffer(buf, sz);
- size_t padding;
- char pad;
- for (unsigned int cur_arg = 0; *fmt && !buffer.OutOfAddressableSpace(); ) {
- if (*fmt++ == '%') {
- padding = 0;
- pad = ' ';
- char ch = *fmt++;
- format_character_found:
- switch (ch) {
- case '0': case '1': case '2': case '3': case '4':
- case '5': case '6': case '7': case '8': case '9':
- // Found a width parameter. Convert to an integer value and store in
- // "padding". If the leading digit is a zero, change the padding
- // character from a space ' ' to a zero '0'.
- pad = ch == '0' ? '0' : ' ';
- for (;;) {
- // The maximum allowed padding fills all the available address
- // space and leaves just enough space to insert the trailing NUL.
- const size_t max_padding = kSSizeMax - 1;
- if (padding > max_padding/10 ||
- 10*padding > max_padding - (ch - '0')) {
- DEBUG_CHECK(padding <= max_padding/10 &&
- 10*padding <= max_padding - (ch - '0'));
- // Integer overflow detected. Skip the rest of the width until
- // we find the format character, then do the normal error handling.
- padding_overflow:
- padding = max_padding;
- while ((ch = *fmt++) >= '0' && ch <= '9') {
- }
- if (cur_arg < max_args) {
- ++cur_arg;
- }
- goto fail_to_expand;
- }
- padding = 10*padding + ch - '0';
- if (padding > max_padding) {
- // This doesn't happen for "sane" values of kSSizeMax. But once
- // kSSizeMax gets smaller than about 10, our earlier range checks
- // are incomplete. Unittests do trigger this artificial corner
- // case.
- DEBUG_CHECK(padding <= max_padding);
- goto padding_overflow;
- }
- ch = *fmt++;
- if (ch < '0' || ch > '9') {
- // Reached the end of the width parameter. This is where the format
- // character is found.
- goto format_character_found;
- }
- }
- break;
- case 'c': { // Output an ASCII character.
- // Check that there are arguments left to be inserted.
- if (cur_arg >= max_args) {
- DEBUG_CHECK(cur_arg < max_args);
- goto fail_to_expand;
- }
-
- // Check that the argument has the expected type.
- const Arg& arg = args[cur_arg++];
- if (arg.type != Arg::INT && arg.type != Arg::UINT) {
- DEBUG_CHECK(arg.type == Arg::INT || arg.type == Arg::UINT);
- goto fail_to_expand;
- }
-
- // Apply padding, if needed.
- buffer.Pad(' ', padding, 1);
-
- // Convert the argument to an ASCII character and output it.
- char as_char = static_cast<char>(arg.integer.i);
- if (!as_char) {
- goto end_of_output_buffer;
- }
- buffer.Out(as_char);
- break; }
- case 'd': // Output a possibly signed decimal value.
- case 'o': // Output an unsigned octal value.
- case 'x': // Output an unsigned hexadecimal value.
- case 'X':
- case 'p': { // Output a pointer value.
- // Check that there are arguments left to be inserted.
- if (cur_arg >= max_args) {
- DEBUG_CHECK(cur_arg < max_args);
- goto fail_to_expand;
- }
-
- const Arg& arg = args[cur_arg++];
- int64_t i;
- const char* prefix = NULL;
- if (ch != 'p') {
- // Check that the argument has the expected type.
- if (arg.type != Arg::INT && arg.type != Arg::UINT) {
- DEBUG_CHECK(arg.type == Arg::INT || arg.type == Arg::UINT);
- goto fail_to_expand;
- }
- i = arg.integer.i;
-
- if (ch != 'd') {
- // The Arg() constructor automatically performed sign expansion on
- // signed parameters. This is great when outputting a %d decimal
- // number, but can result in unexpected leading 0xFF bytes when
- // outputting a %x hexadecimal number. Mask bits, if necessary.
- // We have to do this here, instead of in the Arg() constructor, as
- // the Arg() constructor cannot tell whether we will output a %d
- // or a %x. Only the latter should experience masking.
- if (arg.integer.width < sizeof(int64_t)) {
- i &= (1LL << (8*arg.integer.width)) - 1;
- }
- }
- } else {
- // Pointer values require an actual pointer or a string.
- if (arg.type == Arg::POINTER) {
- i = reinterpret_cast<uintptr_t>(arg.ptr);
- } else if (arg.type == Arg::STRING) {
- i = reinterpret_cast<uintptr_t>(arg.str);
- } else if (arg.type == Arg::INT &&
- arg.integer.width == sizeof(NULL) &&
- arg.integer.i == 0) { // Allow C++'s version of NULL
- i = 0;
- } else {
- DEBUG_CHECK(arg.type == Arg::POINTER || arg.type == Arg::STRING);
- goto fail_to_expand;
- }
-
- // Pointers always include the "0x" prefix.
- prefix = "0x";
- }
-
- // Use IToASCII() to convert to ASCII representation. For decimal
- // numbers, optionally print a sign. For hexadecimal numbers,
- // distinguish between upper and lower case. %p addresses are always
- // printed as upcase. Supports base 8, 10, and 16. Prints padding
- // and/or prefixes, if so requested.
- buffer.IToASCII(ch == 'd' && arg.type == Arg::INT,
- ch != 'x', i,
- ch == 'o' ? 8 : ch == 'd' ? 10 : 16,
- pad, padding, prefix);
- break; }
- case 's': {
- // Check that there are arguments left to be inserted.
- if (cur_arg >= max_args) {
- DEBUG_CHECK(cur_arg < max_args);
- goto fail_to_expand;
- }
-
- // Check that the argument has the expected type.
- const Arg& arg = args[cur_arg++];
- const char *s;
- if (arg.type == Arg::STRING) {
- s = arg.str ? arg.str : "<NULL>";
- } else if (arg.type == Arg::INT && arg.integer.width == sizeof(NULL) &&
- arg.integer.i == 0) { // Allow C++'s version of NULL
- s = "<NULL>";
- } else {
- DEBUG_CHECK(arg.type == Arg::STRING);
- goto fail_to_expand;
- }
-
- // Apply padding, if needed. This requires us to first check the
- // length of the string that we are outputting.
- if (padding) {
- size_t len = 0;
- for (const char* src = s; *src++; ) {
- ++len;
- }
- buffer.Pad(' ', padding, len);
- }
-
- // Printing a string involves nothing more than copying it into the
- // output buffer and making sure we don't output more bytes than
- // available space; Out() takes care of doing that.
- for (const char* src = s; *src; ) {
- buffer.Out(*src++);
- }
- break; }
- case '%':
- // Quoted percent '%' character.
- goto copy_verbatim;
- fail_to_expand:
- // C++ gives us tools to do type checking -- something that snprintf()
- // could never really do. So, whenever we see arguments that don't
- // match up with the format string, we refuse to output them. But
- // since we have to be extremely conservative about being async-
- // signal-safe, we are limited in the type of error handling that we
- // can do in production builds (in debug builds we can use
- // DEBUG_CHECK() and hope for the best). So, all we do is pass the
- // format string unchanged. That should eventually get the user's
- // attention; and in the meantime, it hopefully doesn't lose too much
- // data.
- default:
- // Unknown or unsupported format character. Just copy verbatim to
- // output.
- buffer.Out('%');
- DEBUG_CHECK(ch);
- if (!ch) {
- goto end_of_format_string;
- }
- buffer.Out(ch);
- break;
- }
- } else {
- copy_verbatim:
- buffer.Out(fmt[-1]);
- }
- }
- end_of_format_string:
- end_of_output_buffer:
- return buffer.GetCount();
-}
-
-} // namespace internal
-
-ssize_t SafeSNPrintf(char* buf, size_t sz, const char* fmt) {
- // Make sure that at least one NUL byte can be written, and that the buffer
- // never overflows kSSizeMax. Not only does that use up most or all of the
- // address space, it also would result in a return code that cannot be
- // represented.
- if (static_cast<ssize_t>(sz) < 1) {
- return -1;
- } else if (sz > kSSizeMax) {
- sz = kSSizeMax;
- }
-
- Buffer buffer(buf, sz);
-
- // In the slow-path, we deal with errors by copying the contents of
- // "fmt" unexpanded. This means, if there are no arguments passed, the
- // SafeSPrintf() function always degenerates to a version of strncpy() that
- // de-duplicates '%' characters.
- const char* src = fmt;
- for (; *src; ++src) {
- buffer.Out(*src);
- DEBUG_CHECK(src[0] != '%' || src[1] == '%');
- if (src[0] == '%' && src[1] == '%') {
- ++src;
- }
- }
- return buffer.GetCount();
-}
-
-} // namespace strings
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/safe_sprintf.h b/security/sandbox/chromium/base/strings/safe_sprintf.h
deleted file mode 100644
index 65524a50c..000000000
--- a/security/sandbox/chromium/base/strings/safe_sprintf.h
+++ /dev/null
@@ -1,246 +0,0 @@
-// Copyright 2013 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_STRINGS_SAFE_SPRINTF_H_
-#define BASE_STRINGS_SAFE_SPRINTF_H_
-
-#include "build/build_config.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <stdlib.h>
-
-#if defined(OS_POSIX)
-// For ssize_t
-#include <unistd.h>
-#endif
-
-#include "base/base_export.h"
-
-namespace base {
-namespace strings {
-
-#if defined(_MSC_VER)
-// Define ssize_t inside of our namespace.
-#if defined(_WIN64)
-typedef __int64 ssize_t;
-#else
-typedef long ssize_t;
-#endif
-#endif
-
-// SafeSPrintf() is a type-safe and completely self-contained version of
-// snprintf().
-//
-// SafeSNPrintf() is an alternative function signature that can be used when
-// not dealing with fixed-sized buffers. When possible, SafeSPrintf() should
-// always be used instead of SafeSNPrintf()
-//
-// These functions allow for formatting complicated messages from contexts that
-// require strict async-signal-safety. In fact, it is safe to call them from
-// any low-level execution context, as they are guaranteed to make no library
-// or system calls. It deliberately never touches "errno", either.
-//
-// The only exception to this rule is that in debug builds the code calls
-// RAW_CHECK() to help diagnose problems when the format string does not
-// match the rest of the arguments. In release builds, no CHECK()s are used,
-// and SafeSPrintf() instead returns an output string that expands only
-// those arguments that match their format characters. Mismatched arguments
-// are ignored.
-//
-// The code currently only supports a subset of format characters:
-// %c, %o, %d, %x, %X, %p, and %s.
-//
-// SafeSPrintf() aims to be as liberal as reasonably possible. Integer-like
-// values of arbitrary width can be passed to all of the format characters
-// that expect integers. Thus, it is explicitly legal to pass an "int" to
-// "%c", and output will automatically look at the LSB only. It is also
-// explicitly legal to pass either signed or unsigned values, and the format
-// characters will automatically interpret the arguments accordingly.
-//
-// It is still not legal to mix-and-match integer-like values with pointer
-// values. For instance, you cannot pass a pointer to %x, nor can you pass an
-// integer to %p.
-//
-// The one exception is "0" zero being accepted by "%p". This works-around
-// the problem of C++ defining NULL as an integer-like value.
-//
-// All format characters take an optional width parameter. This must be a
-// positive integer. For %d, %o, %x, %X and %p, if the width starts with
-// a leading '0', padding is done with '0' instead of ' ' characters.
-//
-// There are a few features of snprintf()-style format strings, that
-// SafeSPrintf() does not support at this time.
-//
-// If an actual user showed up, there is no particularly strong reason they
-// couldn't be added. But that assumes that the trade-offs between complexity
-// and utility are favorable.
-//
-// For example, adding support for negative padding widths, and for %n are all
-// likely to be viewed positively. They are all clearly useful, low-risk, easy
-// to test, don't jeopardize the async-signal-safety of the code, and overall
-// have little impact on other parts of SafeSPrintf() function.
-//
-// On the other hands, adding support for alternate forms, positional
-// arguments, grouping, wide characters, localization or floating point numbers
-// are all unlikely to ever be added.
-//
-// SafeSPrintf() and SafeSNPrintf() mimic the behavior of snprintf() and they
-// return the number of bytes needed to store the untruncated output. This
-// does *not* include the terminating NUL byte.
-//
-// They return -1, iff a fatal error happened. This typically can only happen,
-// if the buffer size is a) negative, or b) zero (i.e. not even the NUL byte
-// can be written). The return value can never be larger than SSIZE_MAX-1.
-// This ensures that the caller can always add one to the signed return code
-// in order to determine the amount of storage that needs to be allocated.
-//
-// While the code supports type checking and while it is generally very careful
-// to avoid printing incorrect values, it tends to be conservative in printing
-// as much as possible, even when given incorrect parameters. Typically, in
-// case of an error, the format string will not be expanded. (i.e. something
-// like SafeSPrintf(buf, "%p %d", 1, 2) results in "%p 2"). See above for
-// the use of RAW_CHECK() in debug builds, though.
-//
-// Basic example:
-// char buf[20];
-// base::strings::SafeSPrintf(buf, "The answer: %2d", 42);
-//
-// Example with dynamically sized buffer (async-signal-safe). This code won't
-// work on Visual studio, as it requires dynamically allocating arrays on the
-// stack. Consider picking a smaller value for |kMaxSize| if stack size is
-// limited and known. On the other hand, if the parameters to SafeSNPrintf()
-// are trusted and not controllable by the user, you can consider eliminating
-// the check for |kMaxSize| altogether. The current value of SSIZE_MAX is
-// essentially a no-op that just illustrates how to implement an upper bound:
-// const size_t kInitialSize = 128;
-// const size_t kMaxSize = std::numeric_limits<ssize_t>::max();
-// size_t size = kInitialSize;
-// for (;;) {
-// char buf[size];
-// size = SafeSNPrintf(buf, size, "Error message \"%s\"\n", err) + 1;
-// if (sizeof(buf) < kMaxSize && size > kMaxSize) {
-// size = kMaxSize;
-// continue;
-// } else if (size > sizeof(buf))
-// continue;
-// write(2, buf, size-1);
-// break;
-// }
-
-namespace internal {
-// Helpers that use C++ overloading, templates, and specializations to deduce
-// and record type information from function arguments. This allows us to
-// later write a type-safe version of snprintf().
-
-struct Arg {
- enum Type { INT, UINT, STRING, POINTER };
-
- // Any integer-like value.
- Arg(signed char c) : type(INT) {
- integer.i = c;
- integer.width = sizeof(char);
- }
- Arg(unsigned char c) : type(UINT) {
- integer.i = c;
- integer.width = sizeof(char);
- }
- Arg(signed short j) : type(INT) {
- integer.i = j;
- integer.width = sizeof(short);
- }
- Arg(unsigned short j) : type(UINT) {
- integer.i = j;
- integer.width = sizeof(short);
- }
- Arg(signed int j) : type(INT) {
- integer.i = j;
- integer.width = sizeof(int);
- }
- Arg(unsigned int j) : type(UINT) {
- integer.i = j;
- integer.width = sizeof(int);
- }
- Arg(signed long j) : type(INT) {
- integer.i = j;
- integer.width = sizeof(long);
- }
- Arg(unsigned long j) : type(UINT) {
- integer.i = j;
- integer.width = sizeof(long);
- }
- Arg(signed long long j) : type(INT) {
- integer.i = j;
- integer.width = sizeof(long long);
- }
- Arg(unsigned long long j) : type(UINT) {
- integer.i = j;
- integer.width = sizeof(long long);
- }
-
- // A C-style text string.
- Arg(const char* s) : str(s), type(STRING) { }
- Arg(char* s) : str(s), type(STRING) { }
-
- // Any pointer value that can be cast to a "void*".
- template<class T> Arg(T* p) : ptr((void*)p), type(POINTER) { }
-
- union {
- // An integer-like value.
- struct {
- int64_t i;
- unsigned char width;
- } integer;
-
- // A C-style text string.
- const char* str;
-
- // A pointer to an arbitrary object.
- const void* ptr;
- };
- const enum Type type;
-};
-
-// This is the internal function that performs the actual formatting of
-// an snprintf()-style format string.
-BASE_EXPORT ssize_t SafeSNPrintf(char* buf, size_t sz, const char* fmt,
- const Arg* args, size_t max_args);
-
-#if !defined(NDEBUG)
-// In debug builds, allow unit tests to artificially lower the kSSizeMax
-// constant that is used as a hard upper-bound for all buffers. In normal
-// use, this constant should always be std::numeric_limits<ssize_t>::max().
-BASE_EXPORT void SetSafeSPrintfSSizeMaxForTest(size_t max);
-BASE_EXPORT size_t GetSafeSPrintfSSizeMaxForTest();
-#endif
-
-} // namespace internal
-
-template<typename... Args>
-ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt, Args... args) {
- // Use Arg() object to record type information and then copy arguments to an
- // array to make it easier to iterate over them.
- const internal::Arg arg_array[] = { args... };
- return internal::SafeSNPrintf(buf, N, fmt, arg_array, sizeof...(args));
-}
-
-template<size_t N, typename... Args>
-ssize_t SafeSPrintf(char (&buf)[N], const char* fmt, Args... args) {
- // Use Arg() object to record type information and then copy arguments to an
- // array to make it easier to iterate over them.
- const internal::Arg arg_array[] = { args... };
- return internal::SafeSNPrintf(buf, N, fmt, arg_array, sizeof...(args));
-}
-
-// Fast-path when we don't actually need to substitute any arguments.
-BASE_EXPORT ssize_t SafeSNPrintf(char* buf, size_t N, const char* fmt);
-template<size_t N>
-inline ssize_t SafeSPrintf(char (&buf)[N], const char* fmt) {
- return SafeSNPrintf(buf, N, fmt);
-}
-
-} // namespace strings
-} // namespace base
-
-#endif // BASE_STRINGS_SAFE_SPRINTF_H_
diff --git a/security/sandbox/chromium/base/strings/safe_sprintf_unittest.cc b/security/sandbox/chromium/base/strings/safe_sprintf_unittest.cc
deleted file mode 100644
index 931ace8b1..000000000
--- a/security/sandbox/chromium/base/strings/safe_sprintf_unittest.cc
+++ /dev/null
@@ -1,763 +0,0 @@
-// Copyright 2013 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/strings/safe_sprintf.h"
-
-#include <stddef.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-
-#include <limits>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "build/build_config.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-// Death tests on Android are currently very flaky. No need to add more flaky
-// tests, as they just make it hard to spot real problems.
-// TODO(markus): See if the restrictions on Android can eventually be lifted.
-#if defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID)
-#define ALLOW_DEATH_TEST
-#endif
-
-namespace base {
-namespace strings {
-
-TEST(SafeSPrintfTest, Empty) {
- char buf[2] = { 'X', 'X' };
-
- // Negative buffer size should always result in an error.
- EXPECT_EQ(-1, SafeSNPrintf(buf, static_cast<size_t>(-1), ""));
- EXPECT_EQ('X', buf[0]);
- EXPECT_EQ('X', buf[1]);
-
- // Zero buffer size should always result in an error.
- EXPECT_EQ(-1, SafeSNPrintf(buf, 0, ""));
- EXPECT_EQ('X', buf[0]);
- EXPECT_EQ('X', buf[1]);
-
- // A one-byte buffer should always print a single NUL byte.
- EXPECT_EQ(0, SafeSNPrintf(buf, 1, ""));
- EXPECT_EQ(0, buf[0]);
- EXPECT_EQ('X', buf[1]);
- buf[0] = 'X';
-
- // A larger buffer should leave the trailing bytes unchanged.
- EXPECT_EQ(0, SafeSNPrintf(buf, 2, ""));
- EXPECT_EQ(0, buf[0]);
- EXPECT_EQ('X', buf[1]);
- buf[0] = 'X';
-
- // The same test using SafeSPrintf() instead of SafeSNPrintf().
- EXPECT_EQ(0, SafeSPrintf(buf, ""));
- EXPECT_EQ(0, buf[0]);
- EXPECT_EQ('X', buf[1]);
- buf[0] = 'X';
-}
-
-TEST(SafeSPrintfTest, NoArguments) {
- // Output a text message that doesn't require any substitutions. This
- // is roughly equivalent to calling strncpy() (but unlike strncpy(), it does
- // always add a trailing NUL; it always deduplicates '%' characters).
- static const char text[] = "hello world";
- char ref[20], buf[20];
- memset(ref, 'X', sizeof(ref));
- memcpy(buf, ref, sizeof(buf));
-
- // A negative buffer size should always result in an error.
- EXPECT_EQ(-1, SafeSNPrintf(buf, static_cast<size_t>(-1), text));
- EXPECT_TRUE(!memcmp(buf, ref, sizeof(buf)));
-
- // Zero buffer size should always result in an error.
- EXPECT_EQ(-1, SafeSNPrintf(buf, 0, text));
- EXPECT_TRUE(!memcmp(buf, ref, sizeof(buf)));
-
- // A one-byte buffer should always print a single NUL byte.
- EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1, SafeSNPrintf(buf, 1, text));
- EXPECT_EQ(0, buf[0]);
- EXPECT_TRUE(!memcmp(buf+1, ref+1, sizeof(buf)-1));
- memcpy(buf, ref, sizeof(buf));
-
- // A larger (but limited) buffer should always leave the trailing bytes
- // unchanged.
- EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1, SafeSNPrintf(buf, 2, text));
- EXPECT_EQ(text[0], buf[0]);
- EXPECT_EQ(0, buf[1]);
- EXPECT_TRUE(!memcmp(buf+2, ref+2, sizeof(buf)-2));
- memcpy(buf, ref, sizeof(buf));
-
- // A unrestricted buffer length should always leave the trailing bytes
- // unchanged.
- EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1,
- SafeSNPrintf(buf, sizeof(buf), text));
- EXPECT_EQ(std::string(text), std::string(buf));
- EXPECT_TRUE(!memcmp(buf + sizeof(text), ref + sizeof(text),
- sizeof(buf) - sizeof(text)));
- memcpy(buf, ref, sizeof(buf));
-
- // The same test using SafeSPrintf() instead of SafeSNPrintf().
- EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1, SafeSPrintf(buf, text));
- EXPECT_EQ(std::string(text), std::string(buf));
- EXPECT_TRUE(!memcmp(buf + sizeof(text), ref + sizeof(text),
- sizeof(buf) - sizeof(text)));
- memcpy(buf, ref, sizeof(buf));
-
- // Check for deduplication of '%' percent characters.
- EXPECT_EQ(1, SafeSPrintf(buf, "%%"));
- EXPECT_EQ(2, SafeSPrintf(buf, "%%%%"));
- EXPECT_EQ(2, SafeSPrintf(buf, "%%X"));
- EXPECT_EQ(3, SafeSPrintf(buf, "%%%%X"));
-#if defined(NDEBUG)
- EXPECT_EQ(1, SafeSPrintf(buf, "%"));
- EXPECT_EQ(2, SafeSPrintf(buf, "%%%"));
- EXPECT_EQ(2, SafeSPrintf(buf, "%X"));
- EXPECT_EQ(3, SafeSPrintf(buf, "%%%X"));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, "%"), "src.1. == '%'");
- EXPECT_DEATH(SafeSPrintf(buf, "%%%"), "src.1. == '%'");
- EXPECT_DEATH(SafeSPrintf(buf, "%X"), "src.1. == '%'");
- EXPECT_DEATH(SafeSPrintf(buf, "%%%X"), "src.1. == '%'");
-#endif
-}
-
-TEST(SafeSPrintfTest, OneArgument) {
- // Test basic single-argument single-character substitution.
- const char text[] = "hello world";
- const char fmt[] = "hello%cworld";
- char ref[20], buf[20];
- memset(ref, 'X', sizeof(buf));
- memcpy(buf, ref, sizeof(buf));
-
- // A negative buffer size should always result in an error.
- EXPECT_EQ(-1, SafeSNPrintf(buf, static_cast<size_t>(-1), fmt, ' '));
- EXPECT_TRUE(!memcmp(buf, ref, sizeof(buf)));
-
- // Zero buffer size should always result in an error.
- EXPECT_EQ(-1, SafeSNPrintf(buf, 0, fmt, ' '));
- EXPECT_TRUE(!memcmp(buf, ref, sizeof(buf)));
-
- // A one-byte buffer should always print a single NUL byte.
- EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1,
- SafeSNPrintf(buf, 1, fmt, ' '));
- EXPECT_EQ(0, buf[0]);
- EXPECT_TRUE(!memcmp(buf+1, ref+1, sizeof(buf)-1));
- memcpy(buf, ref, sizeof(buf));
-
- // A larger (but limited) buffer should always leave the trailing bytes
- // unchanged.
- EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1,
- SafeSNPrintf(buf, 2, fmt, ' '));
- EXPECT_EQ(text[0], buf[0]);
- EXPECT_EQ(0, buf[1]);
- EXPECT_TRUE(!memcmp(buf+2, ref+2, sizeof(buf)-2));
- memcpy(buf, ref, sizeof(buf));
-
- // A unrestricted buffer length should always leave the trailing bytes
- // unchanged.
- EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1,
- SafeSNPrintf(buf, sizeof(buf), fmt, ' '));
- EXPECT_EQ(std::string(text), std::string(buf));
- EXPECT_TRUE(!memcmp(buf + sizeof(text), ref + sizeof(text),
- sizeof(buf) - sizeof(text)));
- memcpy(buf, ref, sizeof(buf));
-
- // The same test using SafeSPrintf() instead of SafeSNPrintf().
- EXPECT_EQ(static_cast<ssize_t>(sizeof(text))-1, SafeSPrintf(buf, fmt, ' '));
- EXPECT_EQ(std::string(text), std::string(buf));
- EXPECT_TRUE(!memcmp(buf + sizeof(text), ref + sizeof(text),
- sizeof(buf) - sizeof(text)));
- memcpy(buf, ref, sizeof(buf));
-
- // Check for deduplication of '%' percent characters.
- EXPECT_EQ(1, SafeSPrintf(buf, "%%", 0));
- EXPECT_EQ(2, SafeSPrintf(buf, "%%%%", 0));
- EXPECT_EQ(2, SafeSPrintf(buf, "%Y", 0));
- EXPECT_EQ(2, SafeSPrintf(buf, "%%Y", 0));
- EXPECT_EQ(3, SafeSPrintf(buf, "%%%Y", 0));
- EXPECT_EQ(3, SafeSPrintf(buf, "%%%%Y", 0));
-#if defined(NDEBUG)
- EXPECT_EQ(1, SafeSPrintf(buf, "%", 0));
- EXPECT_EQ(2, SafeSPrintf(buf, "%%%", 0));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, "%", 0), "ch");
- EXPECT_DEATH(SafeSPrintf(buf, "%%%", 0), "ch");
-#endif
-}
-
-TEST(SafeSPrintfTest, MissingArg) {
-#if defined(NDEBUG)
- char buf[20];
- EXPECT_EQ(3, SafeSPrintf(buf, "%c%c", 'A'));
- EXPECT_EQ("A%c", std::string(buf));
-#elif defined(ALLOW_DEATH_TEST)
- char buf[20];
- EXPECT_DEATH(SafeSPrintf(buf, "%c%c", 'A'), "cur_arg < max_args");
-#endif
-}
-
-TEST(SafeSPrintfTest, ASANFriendlyBufferTest) {
- // Print into a buffer that is sized exactly to size. ASAN can verify that
- // nobody attempts to write past the end of the buffer.
- // There is a more complicated test in PrintLongString() that covers a lot
- // more edge case, but it is also harder to debug in case of a failure.
- const char kTestString[] = "This is a test";
- scoped_ptr<char[]> buf(new char[sizeof(kTestString)]);
- EXPECT_EQ(static_cast<ssize_t>(sizeof(kTestString) - 1),
- SafeSNPrintf(buf.get(), sizeof(kTestString), kTestString));
- EXPECT_EQ(std::string(kTestString), std::string(buf.get()));
- EXPECT_EQ(static_cast<ssize_t>(sizeof(kTestString) - 1),
- SafeSNPrintf(buf.get(), sizeof(kTestString), "%s", kTestString));
- EXPECT_EQ(std::string(kTestString), std::string(buf.get()));
-}
-
-TEST(SafeSPrintfTest, NArgs) {
- // Pre-C++11 compilers have a different code path, that can only print
- // up to ten distinct arguments.
- // We test both SafeSPrintf() and SafeSNPrintf(). This makes sure we don't
- // have typos in the copy-n-pasted code that is needed to deal with various
- // numbers of arguments.
- char buf[12];
- EXPECT_EQ(1, SafeSPrintf(buf, "%c", 1));
- EXPECT_EQ("\1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%c%c", 1, 2));
- EXPECT_EQ("\1\2", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%c%c%c", 1, 2, 3));
- EXPECT_EQ("\1\2\3", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%c%c%c%c", 1, 2, 3, 4));
- EXPECT_EQ("\1\2\3\4", std::string(buf));
- EXPECT_EQ(5, SafeSPrintf(buf, "%c%c%c%c%c", 1, 2, 3, 4, 5));
- EXPECT_EQ("\1\2\3\4\5", std::string(buf));
- EXPECT_EQ(6, SafeSPrintf(buf, "%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6));
- EXPECT_EQ("\1\2\3\4\5\6", std::string(buf));
- EXPECT_EQ(7, SafeSPrintf(buf, "%c%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6, 7));
- EXPECT_EQ("\1\2\3\4\5\6\7", std::string(buf));
- EXPECT_EQ(8, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6, 7, 8));
- EXPECT_EQ("\1\2\3\4\5\6\7\10", std::string(buf));
- EXPECT_EQ(9, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c%c",
- 1, 2, 3, 4, 5, 6, 7, 8, 9));
- EXPECT_EQ("\1\2\3\4\5\6\7\10\11", std::string(buf));
- EXPECT_EQ(10, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c%c%c",
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
-
- // Repeat all the tests with SafeSNPrintf() instead of SafeSPrintf().
- EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12", std::string(buf));
- EXPECT_EQ(1, SafeSNPrintf(buf, 11, "%c", 1));
- EXPECT_EQ("\1", std::string(buf));
- EXPECT_EQ(2, SafeSNPrintf(buf, 11, "%c%c", 1, 2));
- EXPECT_EQ("\1\2", std::string(buf));
- EXPECT_EQ(3, SafeSNPrintf(buf, 11, "%c%c%c", 1, 2, 3));
- EXPECT_EQ("\1\2\3", std::string(buf));
- EXPECT_EQ(4, SafeSNPrintf(buf, 11, "%c%c%c%c", 1, 2, 3, 4));
- EXPECT_EQ("\1\2\3\4", std::string(buf));
- EXPECT_EQ(5, SafeSNPrintf(buf, 11, "%c%c%c%c%c", 1, 2, 3, 4, 5));
- EXPECT_EQ("\1\2\3\4\5", std::string(buf));
- EXPECT_EQ(6, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6));
- EXPECT_EQ("\1\2\3\4\5\6", std::string(buf));
- EXPECT_EQ(7, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c", 1, 2, 3, 4, 5, 6, 7));
- EXPECT_EQ("\1\2\3\4\5\6\7", std::string(buf));
- EXPECT_EQ(8, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c%c",
- 1, 2, 3, 4, 5, 6, 7, 8));
- EXPECT_EQ("\1\2\3\4\5\6\7\10", std::string(buf));
- EXPECT_EQ(9, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c%c%c",
- 1, 2, 3, 4, 5, 6, 7, 8, 9));
- EXPECT_EQ("\1\2\3\4\5\6\7\10\11", std::string(buf));
- EXPECT_EQ(10, SafeSNPrintf(buf, 11, "%c%c%c%c%c%c%c%c%c%c",
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
- EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12", std::string(buf));
-
- EXPECT_EQ(11, SafeSPrintf(buf, "%c%c%c%c%c%c%c%c%c%c%c",
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
- EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12\13", std::string(buf));
- EXPECT_EQ(11, SafeSNPrintf(buf, 12, "%c%c%c%c%c%c%c%c%c%c%c",
- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11));
- EXPECT_EQ("\1\2\3\4\5\6\7\10\11\12\13", std::string(buf));
-}
-
-TEST(SafeSPrintfTest, DataTypes) {
- char buf[40];
-
- // Bytes
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", (uint8_t)1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%d", (uint8_t)-1));
- EXPECT_EQ("255", std::string(buf));
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", (int8_t)1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%d", (int8_t)-1));
- EXPECT_EQ("-1", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%d", (int8_t)-128));
- EXPECT_EQ("-128", std::string(buf));
-
- // Half-words
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", (uint16_t)1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(5, SafeSPrintf(buf, "%d", (uint16_t)-1));
- EXPECT_EQ("65535", std::string(buf));
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", (int16_t)1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%d", (int16_t)-1));
- EXPECT_EQ("-1", std::string(buf));
- EXPECT_EQ(6, SafeSPrintf(buf, "%d", (int16_t)-32768));
- EXPECT_EQ("-32768", std::string(buf));
-
- // Words
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", (uint32_t)1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(10, SafeSPrintf(buf, "%d", (uint32_t)-1));
- EXPECT_EQ("4294967295", std::string(buf));
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", (int32_t)1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%d", (int32_t)-1));
- EXPECT_EQ("-1", std::string(buf));
- // Work-around for an limitation of C90
- EXPECT_EQ(11, SafeSPrintf(buf, "%d", (int32_t)-2147483647-1));
- EXPECT_EQ("-2147483648", std::string(buf));
-
- // Quads
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", (uint64_t)1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(20, SafeSPrintf(buf, "%d", (uint64_t)-1));
- EXPECT_EQ("18446744073709551615", std::string(buf));
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", (int64_t)1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%d", (int64_t)-1));
- EXPECT_EQ("-1", std::string(buf));
- // Work-around for an limitation of C90
- EXPECT_EQ(20, SafeSPrintf(buf, "%d", (int64_t)-9223372036854775807LL-1));
- EXPECT_EQ("-9223372036854775808", std::string(buf));
-
- // Strings (both const and mutable).
- EXPECT_EQ(4, SafeSPrintf(buf, "test"));
- EXPECT_EQ("test", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, buf));
- EXPECT_EQ("test", std::string(buf));
-
- // Pointer
- char addr[20];
- sprintf(addr, "0x%llX", (unsigned long long)(uintptr_t)buf);
- SafeSPrintf(buf, "%p", buf);
- EXPECT_EQ(std::string(addr), std::string(buf));
- SafeSPrintf(buf, "%p", (const char *)buf);
- EXPECT_EQ(std::string(addr), std::string(buf));
- sprintf(addr, "0x%llX", (unsigned long long)(uintptr_t)sprintf);
- SafeSPrintf(buf, "%p", sprintf);
- EXPECT_EQ(std::string(addr), std::string(buf));
-
- // Padding for pointers is a little more complicated because of the "0x"
- // prefix. Padding with '0' zeros is relatively straight-forward, but
- // padding with ' ' spaces requires more effort.
- sprintf(addr, "0x%017llX", (unsigned long long)(uintptr_t)buf);
- SafeSPrintf(buf, "%019p", buf);
- EXPECT_EQ(std::string(addr), std::string(buf));
- sprintf(addr, "0x%llX", (unsigned long long)(uintptr_t)buf);
- memset(addr, ' ',
- (char*)memmove(addr + sizeof(addr) - strlen(addr) - 1,
- addr, strlen(addr)+1) - addr);
- SafeSPrintf(buf, "%19p", buf);
- EXPECT_EQ(std::string(addr), std::string(buf));
-}
-
-namespace {
-void PrintLongString(char* buf, size_t sz) {
- // Output a reasonably complex expression into a limited-size buffer.
- // At least one byte is available for writing the NUL character.
- CHECK_GT(sz, static_cast<size_t>(0));
-
- // Allocate slightly more space, so that we can verify that SafeSPrintf()
- // never writes past the end of the buffer.
- scoped_ptr<char[]> tmp(new char[sz+2]);
- memset(tmp.get(), 'X', sz+2);
-
- // Use SafeSPrintf() to output a complex list of arguments:
- // - test padding and truncating %c single characters.
- // - test truncating %s simple strings.
- // - test mismatching arguments and truncating (for %d != %s).
- // - test zero-padding and truncating %x hexadecimal numbers.
- // - test outputting and truncating %d MININT.
- // - test outputting and truncating %p arbitrary pointer values.
- // - test outputting, padding and truncating NULL-pointer %s strings.
- char* out = tmp.get();
- size_t out_sz = sz;
- size_t len;
- for (scoped_ptr<char[]> perfect_buf;;) {
- size_t needed = SafeSNPrintf(out, out_sz,
-#if defined(NDEBUG)
- "A%2cong %s: %d %010X %d %p%7s", 'l', "string", "",
-#else
- "A%2cong %s: %%d %010X %d %p%7s", 'l', "string",
-#endif
- 0xDEADBEEF, std::numeric_limits<intptr_t>::min(),
- PrintLongString, static_cast<char*>(NULL)) + 1;
-
- // Various sanity checks:
- // The numbered of characters needed to print the full string should always
- // be bigger or equal to the bytes that have actually been output.
- len = strlen(tmp.get());
- CHECK_GE(needed, len+1);
-
- // The number of characters output should always fit into the buffer that
- // was passed into SafeSPrintf().
- CHECK_LT(len, out_sz);
-
- // The output is always terminated with a NUL byte (actually, this test is
- // always going to pass, as strlen() already verified this)
- EXPECT_FALSE(tmp[len]);
-
- // ASAN can check that we are not overwriting buffers, iff we make sure the
- // buffer is exactly the size that we are expecting to be written. After
- // running SafeSNPrintf() the first time, it is possible to compute the
- // correct buffer size for this test. So, allocate a second buffer and run
- // the exact same SafeSNPrintf() command again.
- if (!perfect_buf.get()) {
- out_sz = std::min(needed, sz);
- out = new char[out_sz];
- perfect_buf.reset(out);
- } else {
- break;
- }
- }
-
- // All trailing bytes are unchanged.
- for (size_t i = len+1; i < sz+2; ++i)
- EXPECT_EQ('X', tmp[i]);
-
- // The text that was generated by SafeSPrintf() should always match the
- // equivalent text generated by sprintf(). Please note that the format
- // string for sprintf() is not complicated, as it does not have the
- // benefit of getting type information from the C++ compiler.
- //
- // N.B.: It would be so much cleaner to use snprintf(). But unfortunately,
- // Visual Studio doesn't support this function, and the work-arounds
- // are all really awkward.
- char ref[256];
- CHECK_LE(sz, sizeof(ref));
- sprintf(ref, "A long string: %%d 00DEADBEEF %lld 0x%llX <NULL>",
- static_cast<long long>(std::numeric_limits<intptr_t>::min()),
- static_cast<unsigned long long>(
- reinterpret_cast<uintptr_t>(PrintLongString)));
- ref[sz-1] = '\000';
-
-#if defined(NDEBUG)
- const size_t kSSizeMax = std::numeric_limits<ssize_t>::max();
-#else
- const size_t kSSizeMax = internal::GetSafeSPrintfSSizeMaxForTest();
-#endif
-
- // Compare the output from SafeSPrintf() to the one from sprintf().
- EXPECT_EQ(std::string(ref).substr(0, kSSizeMax-1), std::string(tmp.get()));
-
- // We allocated a slightly larger buffer, so that we could perform some
- // extra sanity checks. Now that the tests have all passed, we copy the
- // data to the output buffer that the caller provided.
- memcpy(buf, tmp.get(), len+1);
-}
-
-#if !defined(NDEBUG)
-class ScopedSafeSPrintfSSizeMaxSetter {
- public:
- ScopedSafeSPrintfSSizeMaxSetter(size_t sz) {
- old_ssize_max_ = internal::GetSafeSPrintfSSizeMaxForTest();
- internal::SetSafeSPrintfSSizeMaxForTest(sz);
- }
-
- ~ScopedSafeSPrintfSSizeMaxSetter() {
- internal::SetSafeSPrintfSSizeMaxForTest(old_ssize_max_);
- }
-
- private:
- size_t old_ssize_max_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedSafeSPrintfSSizeMaxSetter);
-};
-#endif
-
-} // anonymous namespace
-
-TEST(SafeSPrintfTest, Truncation) {
- // We use PrintLongString() to print a complex long string and then
- // truncate to all possible lengths. This ends up exercising a lot of
- // different code paths in SafeSPrintf() and IToASCII(), as truncation can
- // happen in a lot of different states.
- char ref[256];
- PrintLongString(ref, sizeof(ref));
- for (size_t i = strlen(ref)+1; i; --i) {
- char buf[sizeof(ref)];
- PrintLongString(buf, i);
- EXPECT_EQ(std::string(ref, i - 1), std::string(buf));
- }
-
- // When compiling in debug mode, we have the ability to fake a small
- // upper limit for the maximum value that can be stored in an ssize_t.
- // SafeSPrintf() uses this upper limit to determine how many bytes it will
- // write to the buffer, even if the caller claimed a bigger buffer size.
- // Repeat the truncation test and verify that this other code path in
- // SafeSPrintf() works correctly, too.
-#if !defined(NDEBUG)
- for (size_t i = strlen(ref)+1; i > 1; --i) {
- ScopedSafeSPrintfSSizeMaxSetter ssize_max_setter(i);
- char buf[sizeof(ref)];
- PrintLongString(buf, sizeof(buf));
- EXPECT_EQ(std::string(ref, i - 1), std::string(buf));
- }
-
- // kSSizeMax is also used to constrain the maximum amount of padding, before
- // SafeSPrintf() detects an error in the format string.
- ScopedSafeSPrintfSSizeMaxSetter ssize_max_setter(100);
- char buf[256];
- EXPECT_EQ(99, SafeSPrintf(buf, "%99c", ' '));
- EXPECT_EQ(std::string(99, ' '), std::string(buf));
- *buf = '\000';
-#if defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, "%100c", ' '), "padding <= max_padding");
-#endif
- EXPECT_EQ(0, *buf);
-#endif
-}
-
-TEST(SafeSPrintfTest, Padding) {
- char buf[40], fmt[40];
-
- // Chars %c
- EXPECT_EQ(1, SafeSPrintf(buf, "%c", 'A'));
- EXPECT_EQ("A", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%2c", 'A'));
- EXPECT_EQ(" A", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%02c", 'A'));
- EXPECT_EQ(" A", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%-2c", 'A'));
- EXPECT_EQ("%-2c", std::string(buf));
- SafeSPrintf(fmt, "%%%dc", std::numeric_limits<ssize_t>::max() - 1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1, SafeSPrintf(buf, fmt, 'A'));
- SafeSPrintf(fmt, "%%%dc",
- static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
- EXPECT_EQ(2, SafeSPrintf(buf, fmt, 'A'));
- EXPECT_EQ("%c", std::string(buf));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, fmt, 'A'), "padding <= max_padding");
-#endif
-
- // Octal %o
- EXPECT_EQ(1, SafeSPrintf(buf, "%o", 1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%2o", 1));
- EXPECT_EQ(" 1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%02o", 1));
- EXPECT_EQ("01", std::string(buf));
- EXPECT_EQ(12, SafeSPrintf(buf, "%12o", -1));
- EXPECT_EQ(" 37777777777", std::string(buf));
- EXPECT_EQ(12, SafeSPrintf(buf, "%012o", -1));
- EXPECT_EQ("037777777777", std::string(buf));
- EXPECT_EQ(23, SafeSPrintf(buf, "%23o", -1LL));
- EXPECT_EQ(" 1777777777777777777777", std::string(buf));
- EXPECT_EQ(23, SafeSPrintf(buf, "%023o", -1LL));
- EXPECT_EQ("01777777777777777777777", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%2o", 0111));
- EXPECT_EQ("111", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%-2o", 1));
- EXPECT_EQ("%-2o", std::string(buf));
- SafeSPrintf(fmt, "%%%do", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, 1));
- EXPECT_EQ(" ", std::string(buf));
- SafeSPrintf(fmt, "%%0%do", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, 1));
- EXPECT_EQ("000", std::string(buf));
- SafeSPrintf(fmt, "%%%do",
- static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
- EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
- EXPECT_EQ("%o", std::string(buf));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, fmt, 1), "padding <= max_padding");
-#endif
-
- // Decimals %d
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", 1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%2d", 1));
- EXPECT_EQ(" 1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%02d", 1));
- EXPECT_EQ("01", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%3d", -1));
- EXPECT_EQ(" -1", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%03d", -1));
- EXPECT_EQ("-01", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%2d", 111));
- EXPECT_EQ("111", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%2d", -111));
- EXPECT_EQ("-111", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%-2d", 1));
- EXPECT_EQ("%-2d", std::string(buf));
- SafeSPrintf(fmt, "%%%dd", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, 1));
- EXPECT_EQ(" ", std::string(buf));
- SafeSPrintf(fmt, "%%0%dd", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, 1));
- EXPECT_EQ("000", std::string(buf));
- SafeSPrintf(fmt, "%%%dd",
- static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
- EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
- EXPECT_EQ("%d", std::string(buf));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, fmt, 1), "padding <= max_padding");
-#endif
-
- // Hex %X
- EXPECT_EQ(1, SafeSPrintf(buf, "%X", 1));
- EXPECT_EQ("1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%2X", 1));
- EXPECT_EQ(" 1", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%02X", 1));
- EXPECT_EQ("01", std::string(buf));
- EXPECT_EQ(9, SafeSPrintf(buf, "%9X", -1));
- EXPECT_EQ(" FFFFFFFF", std::string(buf));
- EXPECT_EQ(9, SafeSPrintf(buf, "%09X", -1));
- EXPECT_EQ("0FFFFFFFF", std::string(buf));
- EXPECT_EQ(17, SafeSPrintf(buf, "%17X", -1LL));
- EXPECT_EQ(" FFFFFFFFFFFFFFFF", std::string(buf));
- EXPECT_EQ(17, SafeSPrintf(buf, "%017X", -1LL));
- EXPECT_EQ("0FFFFFFFFFFFFFFFF", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%2X", 0x111));
- EXPECT_EQ("111", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%-2X", 1));
- EXPECT_EQ("%-2X", std::string(buf));
- SafeSPrintf(fmt, "%%%dX", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, 1));
- EXPECT_EQ(" ", std::string(buf));
- SafeSPrintf(fmt, "%%0%dX", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, 1));
- EXPECT_EQ("000", std::string(buf));
- SafeSPrintf(fmt, "%%%dX",
- static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
- EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
- EXPECT_EQ("%X", std::string(buf));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, fmt, 1), "padding <= max_padding");
-#endif
-
- // Pointer %p
- EXPECT_EQ(3, SafeSPrintf(buf, "%p", (void*)1));
- EXPECT_EQ("0x1", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%4p", (void*)1));
- EXPECT_EQ(" 0x1", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%04p", (void*)1));
- EXPECT_EQ("0x01", std::string(buf));
- EXPECT_EQ(5, SafeSPrintf(buf, "%4p", (void*)0x111));
- EXPECT_EQ("0x111", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%-2p", (void*)1));
- EXPECT_EQ("%-2p", std::string(buf));
- SafeSPrintf(fmt, "%%%dp", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, (void*)1));
- EXPECT_EQ(" ", std::string(buf));
- SafeSPrintf(fmt, "%%0%dp", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, (void*)1));
- EXPECT_EQ("0x0", std::string(buf));
- SafeSPrintf(fmt, "%%%dp",
- static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
- EXPECT_EQ(2, SafeSPrintf(buf, fmt, 1));
- EXPECT_EQ("%p", std::string(buf));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, fmt, 1), "padding <= max_padding");
-#endif
-
- // String
- EXPECT_EQ(1, SafeSPrintf(buf, "%s", "A"));
- EXPECT_EQ("A", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%2s", "A"));
- EXPECT_EQ(" A", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%02s", "A"));
- EXPECT_EQ(" A", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%2s", "AAA"));
- EXPECT_EQ("AAA", std::string(buf));
- EXPECT_EQ(4, SafeSPrintf(buf, "%-2s", "A"));
- EXPECT_EQ("%-2s", std::string(buf));
- SafeSPrintf(fmt, "%%%ds", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, "A"));
- EXPECT_EQ(" ", std::string(buf));
- SafeSPrintf(fmt, "%%0%ds", std::numeric_limits<ssize_t>::max()-1);
- EXPECT_EQ(std::numeric_limits<ssize_t>::max()-1,
- SafeSNPrintf(buf, 4, fmt, "A"));
- EXPECT_EQ(" ", std::string(buf));
- SafeSPrintf(fmt, "%%%ds",
- static_cast<size_t>(std::numeric_limits<ssize_t>::max()));
-#if defined(NDEBUG)
- EXPECT_EQ(2, SafeSPrintf(buf, fmt, "A"));
- EXPECT_EQ("%s", std::string(buf));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, fmt, "A"), "padding <= max_padding");
-#endif
-}
-
-TEST(SafeSPrintfTest, EmbeddedNul) {
- char buf[] = { 'X', 'X', 'X', 'X' };
- EXPECT_EQ(2, SafeSPrintf(buf, "%3c", 0));
- EXPECT_EQ(' ', buf[0]);
- EXPECT_EQ(' ', buf[1]);
- EXPECT_EQ(0, buf[2]);
- EXPECT_EQ('X', buf[3]);
-
- // Check handling of a NUL format character. N.B. this takes two different
- // code paths depending on whether we are actually passing arguments. If
- // we don't have any arguments, we are running in the fast-path code, that
- // looks (almost) like a strncpy().
-#if defined(NDEBUG)
- EXPECT_EQ(2, SafeSPrintf(buf, "%%%"));
- EXPECT_EQ("%%", std::string(buf));
- EXPECT_EQ(2, SafeSPrintf(buf, "%%%", 0));
- EXPECT_EQ("%%", std::string(buf));
-#elif defined(ALLOW_DEATH_TEST)
- EXPECT_DEATH(SafeSPrintf(buf, "%%%"), "src.1. == '%'");
- EXPECT_DEATH(SafeSPrintf(buf, "%%%", 0), "ch");
-#endif
-}
-
-TEST(SafeSPrintfTest, EmitNULL) {
- char buf[40];
-#if defined(__GNUC__)
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wconversion-null"
-#endif
- EXPECT_EQ(1, SafeSPrintf(buf, "%d", NULL));
- EXPECT_EQ("0", std::string(buf));
- EXPECT_EQ(3, SafeSPrintf(buf, "%p", NULL));
- EXPECT_EQ("0x0", std::string(buf));
- EXPECT_EQ(6, SafeSPrintf(buf, "%s", NULL));
- EXPECT_EQ("<NULL>", std::string(buf));
-#if defined(__GCC__)
-#pragma GCC diagnostic pop
-#endif
-}
-
-TEST(SafeSPrintfTest, PointerSize) {
- // The internal data representation is a 64bit value, independent of the
- // native word size. We want to perform sign-extension for signed integers,
- // but we want to avoid doing so for pointer types. This could be a
- // problem on systems, where pointers are only 32bit. This tests verifies
- // that there is no such problem.
- char *str = reinterpret_cast<char *>(0x80000000u);
- void *ptr = str;
- char buf[40];
- EXPECT_EQ(10, SafeSPrintf(buf, "%p", str));
- EXPECT_EQ("0x80000000", std::string(buf));
- EXPECT_EQ(10, SafeSPrintf(buf, "%p", ptr));
- EXPECT_EQ("0x80000000", std::string(buf));
-}
-
-} // namespace strings
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/string16.cc b/security/sandbox/chromium/base/strings/string16.cc
deleted file mode 100644
index f4c8cf746..000000000
--- a/security/sandbox/chromium/base/strings/string16.cc
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright 2013 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/strings/string16.h"
-
-#if defined(WCHAR_T_IS_UTF16)
-
-#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.
-
-#elif defined(WCHAR_T_IS_UTF32)
-
-#include <ostream>
-
-#include "base/strings/utf_string_conversions.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 static_cast<char16*>(memmove(s1, s2, n * sizeof(char16)));
-}
-
-char16* c16memcpy(char16* s1, const char16* s2, size_t n) {
- return static_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;
-}
-
-std::ostream& operator<<(std::ostream& out, const string16& str) {
- return out << UTF16ToUTF8(str);
-}
-
-void PrintTo(const string16& str, std::ostream* out) {
- *out << str;
-}
-
-} // namespace base
-
-template class std::basic_string<base::char16, base::string16_char_traits>;
-
-#endif // WCHAR_T_IS_UTF32
diff --git a/security/sandbox/chromium/base/strings/string16.h b/security/sandbox/chromium/base/strings/string16.h
deleted file mode 100644
index e47669c1b..000000000
--- a/security/sandbox/chromium/base/strings/string16.h
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 2013 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_STRINGS_STRING16_H_
-#define BASE_STRINGS_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 <stddef.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string>
-
-#include "base/base_export.h"
-#include "build/build_config.h"
-
-#if defined(WCHAR_T_IS_UTF16)
-
-namespace base {
-
-typedef wchar_t char16;
-typedef std::wstring string16;
-typedef std::char_traits<wchar_t> string16_char_traits;
-
-} // namespace base
-
-#elif defined(WCHAR_T_IS_UTF32)
-
-namespace base {
-
-typedef uint16_t char16;
-
-// 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").
-BASE_EXPORT int c16memcmp(const char16* s1, const char16* s2, size_t n);
-BASE_EXPORT size_t c16len(const char16* s);
-BASE_EXPORT const char16* c16memchr(const char16* s, char16 c, size_t n);
-BASE_EXPORT char16* c16memmove(char16* s1, const char16* s2, size_t n);
-BASE_EXPORT char16* c16memcpy(char16* s1, const char16* s2, size_t n);
-BASE_EXPORT 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().
- static_assert(sizeof(int_type) > sizeof(char_type),
- "int must be larger than 16 bits wide");
-
- 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, size_t 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);
- }
-};
-
-typedef std::basic_string<char16, base::string16_char_traits> string16;
-
-BASE_EXPORT extern std::ostream& operator<<(std::ostream& out,
- const string16& str);
-
-// This is required by googletest to print a readable output on test failures.
-BASE_EXPORT extern void PrintTo(const string16& str, std::ostream* out);
-
-} // 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 BASE_EXPORT std::basic_string<base::char16, base::string16_char_traits>;
-
-#endif // WCHAR_T_IS_UTF32
-
-#endif // BASE_STRINGS_STRING16_H_
diff --git a/security/sandbox/chromium/base/strings/string_number_conversions.cc b/security/sandbox/chromium/base/strings/string_number_conversions.cc
deleted file mode 100644
index 07248501e..000000000
--- a/security/sandbox/chromium/base/strings/string_number_conversions.cc
+++ /dev/null
@@ -1,485 +0,0 @@
-// 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.
-
-#include "base/strings/string_number_conversions.h"
-
-#include <ctype.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <wctype.h>
-
-#include <limits>
-
-#include "base/logging.h"
-#include "base/numerics/safe_conversions.h"
-#include "base/numerics/safe_math.h"
-#include "base/scoped_clear_errno.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/third_party/dmg_fp/dmg_fp.h"
-
-namespace base {
-
-namespace {
-
-template <typename STR, typename INT>
-struct IntToStringT {
- 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 size_t kOutputBufSize =
- 3 * sizeof(INT) + std::numeric_limits<INT>::is_signed;
-
- // Create the string in a temporary buffer, write it back to front, and
- // then return the substr of what we ended up using.
- using CHR = typename STR::value_type;
- CHR outbuf[kOutputBufSize];
-
- // The ValueOrDie call below can never fail, because UnsignedAbs is valid
- // for all valid inputs.
- auto res = CheckedNumeric<INT>(value).UnsignedAbs().ValueOrDie();
-
- CHR* end = outbuf + kOutputBufSize;
- CHR* i = end;
- do {
- --i;
- DCHECK(i != outbuf);
- *i = static_cast<CHR>((res % 10) + '0');
- res /= 10;
- } while (res != 0);
- if (IsValueNegative(value)) {
- --i;
- DCHECK(i != outbuf);
- *i = static_cast<CHR>('-');
- }
- return STR(i, end);
- }
-};
-
-// Utility to convert a character to a digit in a given base
-template<typename CHAR, int BASE, bool BASE_LTE_10> class BaseCharToDigit {
-};
-
-// Faster specialization for bases <= 10
-template<typename CHAR, int BASE> class BaseCharToDigit<CHAR, BASE, true> {
- public:
- static bool Convert(CHAR c, uint8_t* digit) {
- if (c >= '0' && c < '0' + BASE) {
- *digit = static_cast<uint8_t>(c - '0');
- return true;
- }
- return false;
- }
-};
-
-// Specialization for bases where 10 < base <= 36
-template<typename CHAR, int BASE> class BaseCharToDigit<CHAR, BASE, false> {
- public:
- static bool Convert(CHAR c, uint8_t* digit) {
- if (c >= '0' && c <= '9') {
- *digit = c - '0';
- } else if (c >= 'a' && c < 'a' + BASE - 10) {
- *digit = c - 'a' + 10;
- } else if (c >= 'A' && c < 'A' + BASE - 10) {
- *digit = c - 'A' + 10;
- } else {
- return false;
- }
- return true;
- }
-};
-
-template <int BASE, typename CHAR>
-bool CharToDigit(CHAR c, uint8_t* digit) {
- return BaseCharToDigit<CHAR, BASE, BASE <= 10>::Convert(c, digit);
-}
-
-// There is an IsUnicodeWhitespace for wchars defined in string_util.h, but it
-// is locale independent, whereas the functions we are replacing were
-// locale-dependent. TBD what is desired, but for the moment let's not
-// introduce a change in behaviour.
-template<typename CHAR> class WhitespaceHelper {
-};
-
-template<> class WhitespaceHelper<char> {
- public:
- static bool Invoke(char c) {
- return 0 != isspace(static_cast<unsigned char>(c));
- }
-};
-
-template<> class WhitespaceHelper<char16> {
- public:
- static bool Invoke(char16 c) {
- return 0 != iswspace(c);
- }
-};
-
-template<typename CHAR> bool LocalIsWhitespace(CHAR c) {
- return WhitespaceHelper<CHAR>::Invoke(c);
-}
-
-// IteratorRangeToNumberTraits should provide:
-// - a typedef for iterator_type, the iterator type used as input.
-// - a typedef for value_type, the target numeric type.
-// - static functions min, max (returning the minimum and maximum permitted
-// values)
-// - constant kBase, the base in which to interpret the input
-template<typename IteratorRangeToNumberTraits>
-class IteratorRangeToNumber {
- public:
- typedef IteratorRangeToNumberTraits traits;
- typedef typename traits::iterator_type const_iterator;
- typedef typename traits::value_type value_type;
-
- // Generalized iterator-range-to-number conversion.
- //
- static bool Invoke(const_iterator begin,
- const_iterator end,
- value_type* output) {
- bool valid = true;
-
- while (begin != end && LocalIsWhitespace(*begin)) {
- valid = false;
- ++begin;
- }
-
- if (begin != end && *begin == '-') {
- if (!std::numeric_limits<value_type>::is_signed) {
- valid = false;
- } else if (!Negative::Invoke(begin + 1, end, output)) {
- valid = false;
- }
- } else {
- if (begin != end && *begin == '+') {
- ++begin;
- }
- if (!Positive::Invoke(begin, end, output)) {
- valid = false;
- }
- }
-
- return valid;
- }
-
- private:
- // Sign provides:
- // - a static function, CheckBounds, that determines whether the next digit
- // causes an overflow/underflow
- // - a static function, Increment, that appends the next digit appropriately
- // according to the sign of the number being parsed.
- template<typename Sign>
- class Base {
- public:
- static bool Invoke(const_iterator begin, const_iterator end,
- typename traits::value_type* output) {
- *output = 0;
-
- if (begin == end) {
- return false;
- }
-
- // Note: no performance difference was found when using template
- // specialization to remove this check in bases other than 16
- if (traits::kBase == 16 && end - begin > 2 && *begin == '0' &&
- (*(begin + 1) == 'x' || *(begin + 1) == 'X')) {
- begin += 2;
- }
-
- for (const_iterator current = begin; current != end; ++current) {
- uint8_t new_digit = 0;
-
- if (!CharToDigit<traits::kBase>(*current, &new_digit)) {
- return false;
- }
-
- if (current != begin) {
- if (!Sign::CheckBounds(output, new_digit)) {
- return false;
- }
- *output *= traits::kBase;
- }
-
- Sign::Increment(new_digit, output);
- }
- return true;
- }
- };
-
- class Positive : public Base<Positive> {
- public:
- static bool CheckBounds(value_type* output, uint8_t new_digit) {
- if (*output > static_cast<value_type>(traits::max() / traits::kBase) ||
- (*output == static_cast<value_type>(traits::max() / traits::kBase) &&
- new_digit > traits::max() % traits::kBase)) {
- *output = traits::max();
- return false;
- }
- return true;
- }
- static void Increment(uint8_t increment, value_type* output) {
- *output += increment;
- }
- };
-
- class Negative : public Base<Negative> {
- public:
- static bool CheckBounds(value_type* output, uint8_t new_digit) {
- if (*output < traits::min() / traits::kBase ||
- (*output == traits::min() / traits::kBase &&
- new_digit > 0 - traits::min() % traits::kBase)) {
- *output = traits::min();
- return false;
- }
- return true;
- }
- static void Increment(uint8_t increment, value_type* output) {
- *output -= increment;
- }
- };
-};
-
-template<typename ITERATOR, typename VALUE, int BASE>
-class BaseIteratorRangeToNumberTraits {
- public:
- typedef ITERATOR iterator_type;
- typedef VALUE value_type;
- static value_type min() {
- return std::numeric_limits<value_type>::min();
- }
- static value_type max() {
- return std::numeric_limits<value_type>::max();
- }
- static const int kBase = BASE;
-};
-
-template<typename ITERATOR>
-class BaseHexIteratorRangeToIntTraits
- : public BaseIteratorRangeToNumberTraits<ITERATOR, int, 16> {
-};
-
-template <typename ITERATOR>
-class BaseHexIteratorRangeToUIntTraits
- : public BaseIteratorRangeToNumberTraits<ITERATOR, uint32_t, 16> {};
-
-template <typename ITERATOR>
-class BaseHexIteratorRangeToInt64Traits
- : public BaseIteratorRangeToNumberTraits<ITERATOR, int64_t, 16> {};
-
-template <typename ITERATOR>
-class BaseHexIteratorRangeToUInt64Traits
- : public BaseIteratorRangeToNumberTraits<ITERATOR, uint64_t, 16> {};
-
-typedef BaseHexIteratorRangeToIntTraits<StringPiece::const_iterator>
- HexIteratorRangeToIntTraits;
-
-typedef BaseHexIteratorRangeToUIntTraits<StringPiece::const_iterator>
- HexIteratorRangeToUIntTraits;
-
-typedef BaseHexIteratorRangeToInt64Traits<StringPiece::const_iterator>
- HexIteratorRangeToInt64Traits;
-
-typedef BaseHexIteratorRangeToUInt64Traits<StringPiece::const_iterator>
- HexIteratorRangeToUInt64Traits;
-
-template <typename STR>
-bool HexStringToBytesT(const STR& input, std::vector<uint8_t>* output) {
- DCHECK_EQ(output->size(), 0u);
- size_t count = input.size();
- if (count == 0 || (count % 2) != 0)
- return false;
- for (uintptr_t i = 0; i < count / 2; ++i) {
- uint8_t msb = 0; // most significant 4 bits
- uint8_t lsb = 0; // least significant 4 bits
- if (!CharToDigit<16>(input[i * 2], &msb) ||
- !CharToDigit<16>(input[i * 2 + 1], &lsb))
- return false;
- output->push_back((msb << 4) | lsb);
- }
- return true;
-}
-
-template <typename VALUE, int BASE>
-class StringPieceToNumberTraits
- : public BaseIteratorRangeToNumberTraits<StringPiece::const_iterator,
- VALUE,
- BASE> {
-};
-
-template <typename VALUE>
-bool StringToIntImpl(const StringPiece& input, VALUE* output) {
- return IteratorRangeToNumber<StringPieceToNumberTraits<VALUE, 10> >::Invoke(
- input.begin(), input.end(), output);
-}
-
-template <typename VALUE, int BASE>
-class StringPiece16ToNumberTraits
- : public BaseIteratorRangeToNumberTraits<StringPiece16::const_iterator,
- VALUE,
- BASE> {
-};
-
-template <typename VALUE>
-bool String16ToIntImpl(const StringPiece16& input, VALUE* output) {
- return IteratorRangeToNumber<StringPiece16ToNumberTraits<VALUE, 10> >::Invoke(
- input.begin(), input.end(), output);
-}
-
-} // namespace
-
-std::string IntToString(int value) {
- return IntToStringT<std::string, int>::IntToString(value);
-}
-
-string16 IntToString16(int value) {
- return IntToStringT<string16, int>::IntToString(value);
-}
-
-std::string UintToString(unsigned int value) {
- return IntToStringT<std::string, unsigned int>::IntToString(value);
-}
-
-string16 UintToString16(unsigned int value) {
- return IntToStringT<string16, unsigned int>::IntToString(value);
-}
-
-std::string Int64ToString(int64_t value) {
- return IntToStringT<std::string, int64_t>::IntToString(value);
-}
-
-string16 Int64ToString16(int64_t value) {
- return IntToStringT<string16, int64_t>::IntToString(value);
-}
-
-std::string Uint64ToString(uint64_t value) {
- return IntToStringT<std::string, uint64_t>::IntToString(value);
-}
-
-string16 Uint64ToString16(uint64_t value) {
- return IntToStringT<string16, uint64_t>::IntToString(value);
-}
-
-std::string SizeTToString(size_t value) {
- return IntToStringT<std::string, size_t>::IntToString(value);
-}
-
-string16 SizeTToString16(size_t value) {
- return IntToStringT<string16, size_t>::IntToString(value);
-}
-
-std::string DoubleToString(double value) {
- // According to g_fmt.cc, it is sufficient to declare a buffer of size 32.
- char buffer[32];
- dmg_fp::g_fmt(buffer, value);
- return std::string(buffer);
-}
-
-bool StringToInt(const StringPiece& input, int* output) {
- return StringToIntImpl(input, output);
-}
-
-bool StringToInt(const StringPiece16& input, int* output) {
- return String16ToIntImpl(input, output);
-}
-
-bool StringToUint(const StringPiece& input, unsigned* output) {
- return StringToIntImpl(input, output);
-}
-
-bool StringToUint(const StringPiece16& input, unsigned* output) {
- return String16ToIntImpl(input, output);
-}
-
-bool StringToInt64(const StringPiece& input, int64_t* output) {
- return StringToIntImpl(input, output);
-}
-
-bool StringToInt64(const StringPiece16& input, int64_t* output) {
- return String16ToIntImpl(input, output);
-}
-
-bool StringToUint64(const StringPiece& input, uint64_t* output) {
- return StringToIntImpl(input, output);
-}
-
-bool StringToUint64(const StringPiece16& input, uint64_t* output) {
- return String16ToIntImpl(input, output);
-}
-
-bool StringToSizeT(const StringPiece& input, size_t* output) {
- return StringToIntImpl(input, output);
-}
-
-bool StringToSizeT(const StringPiece16& input, size_t* output) {
- return String16ToIntImpl(input, output);
-}
-
-bool StringToDouble(const std::string& input, double* output) {
- // Thread-safe? It is on at least Mac, Linux, and Windows.
- ScopedClearErrno clear_errno;
-
- char* endptr = NULL;
- *output = dmg_fp::strtod(input.c_str(), &endptr);
-
- // 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.
- // - If the first character is a space, there was leading whitespace
- return errno == 0 &&
- !input.empty() &&
- input.c_str() + input.length() == endptr &&
- !isspace(input[0]);
-}
-
-// Note: if you need to add String16ToDouble, first ask yourself if it's
-// really necessary. If it is, probably the best implementation here is to
-// convert to 8-bit and then use the 8-bit version.
-
-// Note: if you need to add an iterator range version of StringToDouble, first
-// ask yourself if it's really necessary. If it is, probably the best
-// implementation here is to instantiate a string and use the string version.
-
-std::string HexEncode(const void* bytes, size_t size) {
- static const char kHexChars[] = "0123456789ABCDEF";
-
- // Each input byte creates two output hex characters.
- std::string ret(size * 2, '\0');
-
- for (size_t i = 0; i < size; ++i) {
- char b = reinterpret_cast<const char*>(bytes)[i];
- ret[(i * 2)] = kHexChars[(b >> 4) & 0xf];
- ret[(i * 2) + 1] = kHexChars[b & 0xf];
- }
- return ret;
-}
-
-bool HexStringToInt(const StringPiece& input, int* output) {
- return IteratorRangeToNumber<HexIteratorRangeToIntTraits>::Invoke(
- input.begin(), input.end(), output);
-}
-
-bool HexStringToUInt(const StringPiece& input, uint32_t* output) {
- return IteratorRangeToNumber<HexIteratorRangeToUIntTraits>::Invoke(
- input.begin(), input.end(), output);
-}
-
-bool HexStringToInt64(const StringPiece& input, int64_t* output) {
- return IteratorRangeToNumber<HexIteratorRangeToInt64Traits>::Invoke(
- input.begin(), input.end(), output);
-}
-
-bool HexStringToUInt64(const StringPiece& input, uint64_t* output) {
- return IteratorRangeToNumber<HexIteratorRangeToUInt64Traits>::Invoke(
- input.begin(), input.end(), output);
-}
-
-bool HexStringToBytes(const std::string& input, std::vector<uint8_t>* output) {
- return HexStringToBytesT(input, output);
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/string_number_conversions.h b/security/sandbox/chromium/base/strings/string_number_conversions.h
deleted file mode 100644
index 1265f0dcb..000000000
--- a/security/sandbox/chromium/base/strings/string_number_conversions.h
+++ /dev/null
@@ -1,137 +0,0 @@
-// 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.
-
-#ifndef BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_
-#define BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <string>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_piece.h"
-
-// ----------------------------------------------------------------------------
-// IMPORTANT MESSAGE FROM YOUR SPONSOR
-//
-// This file contains no "wstring" variants. New code should use string16. If
-// you need to make old code work, use the UTF8 version and convert. Please do
-// not add wstring variants.
-//
-// Please do not add "convenience" functions for converting strings to integers
-// that return the value and ignore success/failure. That encourages people to
-// write code that doesn't properly handle the error conditions.
-// ----------------------------------------------------------------------------
-
-namespace base {
-
-// Number -> string conversions ------------------------------------------------
-
-BASE_EXPORT std::string IntToString(int value);
-BASE_EXPORT string16 IntToString16(int value);
-
-BASE_EXPORT std::string UintToString(unsigned value);
-BASE_EXPORT string16 UintToString16(unsigned value);
-
-BASE_EXPORT std::string Int64ToString(int64_t value);
-BASE_EXPORT string16 Int64ToString16(int64_t value);
-
-BASE_EXPORT std::string Uint64ToString(uint64_t value);
-BASE_EXPORT string16 Uint64ToString16(uint64_t value);
-
-BASE_EXPORT std::string SizeTToString(size_t value);
-BASE_EXPORT string16 SizeTToString16(size_t value);
-
-// DoubleToString converts the double to a string format that ignores the
-// locale. If you want to use locale specific formatting, use ICU.
-BASE_EXPORT std::string DoubleToString(double value);
-
-// String -> number conversions ------------------------------------------------
-
-// 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. |*output| will be set to the maximum value supported
-// by the data type.
-// - Underflow. |*output| will be set to the minimum 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.
-// - Leading whitespace in the string before 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.
-// WARNING: Will write to |output| even when returning false.
-// Read the comments above carefully.
-BASE_EXPORT bool StringToInt(const StringPiece& input, int* output);
-BASE_EXPORT bool StringToInt(const StringPiece16& input, int* output);
-
-BASE_EXPORT bool StringToUint(const StringPiece& input, unsigned* output);
-BASE_EXPORT bool StringToUint(const StringPiece16& input, unsigned* output);
-
-BASE_EXPORT bool StringToInt64(const StringPiece& input, int64_t* output);
-BASE_EXPORT bool StringToInt64(const StringPiece16& input, int64_t* output);
-
-BASE_EXPORT bool StringToUint64(const StringPiece& input, uint64_t* output);
-BASE_EXPORT bool StringToUint64(const StringPiece16& input, uint64_t* output);
-
-BASE_EXPORT bool StringToSizeT(const StringPiece& input, size_t* output);
-BASE_EXPORT bool StringToSizeT(const StringPiece16& input, size_t* output);
-
-// For floating-point conversions, only conversions of input strings in decimal
-// form are defined to work. Behavior with strings representing floating-point
-// numbers in hexadecimal, and strings representing non-finite values (such as
-// NaN and inf) is undefined. Otherwise, these behave the same as the integral
-// variants. This expects the input string to NOT be specific to the locale.
-// If your input is locale specific, use ICU to read the number.
-// WARNING: Will write to |output| even when returning false.
-// Read the comments here and above StringToInt() carefully.
-BASE_EXPORT bool StringToDouble(const std::string& input, double* output);
-
-// Hex encoding ----------------------------------------------------------------
-
-// Returns a hex string representation of a binary buffer. The returned hex
-// string will be in upper case. This function does not check if |size| is
-// within reasonable limits since it's written with trusted data in mind. If
-// you suspect that the data you want to format might be large, the absolute
-// max size for |size| should be is
-// std::numeric_limits<size_t>::max() / 2
-BASE_EXPORT std::string HexEncode(const void* bytes, size_t size);
-
-// Best effort conversion, see StringToInt above for restrictions.
-// Will only successful parse hex values that will fit into |output|, i.e.
-// -0x80000000 < |input| < 0x7FFFFFFF.
-BASE_EXPORT bool HexStringToInt(const StringPiece& input, int* output);
-
-// Best effort conversion, see StringToInt above for restrictions.
-// Will only successful parse hex values that will fit into |output|, i.e.
-// 0x00000000 < |input| < 0xFFFFFFFF.
-// The string is not required to start with 0x.
-BASE_EXPORT bool HexStringToUInt(const StringPiece& input, uint32_t* output);
-
-// Best effort conversion, see StringToInt above for restrictions.
-// Will only successful parse hex values that will fit into |output|, i.e.
-// -0x8000000000000000 < |input| < 0x7FFFFFFFFFFFFFFF.
-BASE_EXPORT bool HexStringToInt64(const StringPiece& input, int64_t* output);
-
-// Best effort conversion, see StringToInt above for restrictions.
-// Will only successful parse hex values that will fit into |output|, i.e.
-// 0x0000000000000000 < |input| < 0xFFFFFFFFFFFFFFFF.
-// The string is not required to start with 0x.
-BASE_EXPORT bool HexStringToUInt64(const StringPiece& input, uint64_t* output);
-
-// Similar to the previous functions, except that output is a vector of bytes.
-// |*output| will contain as many bytes as were successfully parsed prior to the
-// error. There is no overflow, but input.size() must be evenly divisible by 2.
-// Leading 0x or +/- are not allowed.
-BASE_EXPORT bool HexStringToBytes(const std::string& input,
- std::vector<uint8_t>* output);
-
-} // namespace base
-
-#endif // BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_
diff --git a/security/sandbox/chromium/base/strings/string_piece.cc b/security/sandbox/chromium/base/strings/string_piece.cc
deleted file mode 100644
index c26bb3652..000000000
--- a/security/sandbox/chromium/base/strings/string_piece.cc
+++ /dev/null
@@ -1,452 +0,0 @@
-// 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.
-// Copied from strings/stringpiece.cc with modifications
-
-#include "base/strings/string_piece.h"
-
-#include <limits.h>
-
-#include <algorithm>
-#include <ostream>
-
-#include "base/logging.h"
-
-namespace base {
-namespace {
-
-// 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]
-inline void BuildLookupTable(const StringPiece& characters_wanted,
- bool* table) {
- const size_t length = characters_wanted.length();
- const char* const data = characters_wanted.data();
- for (size_t i = 0; i < length; ++i) {
- table[static_cast<unsigned char>(data[i])] = true;
- }
-}
-
-} // namespace
-
-// MSVC doesn't like complex extern templates and DLLs.
-#if !defined(COMPILER_MSVC)
-template class BasicStringPiece<std::string>;
-template class BasicStringPiece<string16>;
-#endif
-
-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;
-}
-
-std::ostream& operator<<(std::ostream& o, const StringPiece& piece) {
- o.write(piece.data(), static_cast<std::streamsize>(piece.size()));
- return o;
-}
-
-namespace internal {
-
-template<typename STR>
-void CopyToStringT(const BasicStringPiece<STR>& self, STR* target) {
- if (self.empty())
- target->clear();
- else
- target->assign(self.data(), self.size());
-}
-
-void CopyToString(const StringPiece& self, std::string* target) {
- CopyToStringT(self, target);
-}
-
-void CopyToString(const StringPiece16& self, string16* target) {
- CopyToStringT(self, target);
-}
-
-template<typename STR>
-void AppendToStringT(const BasicStringPiece<STR>& self, STR* target) {
- if (!self.empty())
- target->append(self.data(), self.size());
-}
-
-void AppendToString(const StringPiece& self, std::string* target) {
- AppendToStringT(self, target);
-}
-
-void AppendToString(const StringPiece16& self, string16* target) {
- AppendToStringT(self, target);
-}
-
-template<typename STR>
-size_t copyT(const BasicStringPiece<STR>& self,
- typename STR::value_type* buf,
- size_t n,
- size_t pos) {
- size_t ret = std::min(self.size() - pos, n);
- memcpy(buf, self.data() + pos, ret * sizeof(typename STR::value_type));
- return ret;
-}
-
-size_t copy(const StringPiece& self, char* buf, size_t n, size_t pos) {
- return copyT(self, buf, n, pos);
-}
-
-size_t copy(const StringPiece16& self, char16* buf, size_t n, size_t pos) {
- return copyT(self, buf, n, pos);
-}
-
-template<typename STR>
-size_t findT(const BasicStringPiece<STR>& self,
- const BasicStringPiece<STR>& s,
- size_t pos) {
- if (pos > self.size())
- return BasicStringPiece<STR>::npos;
-
- typename BasicStringPiece<STR>::const_iterator result =
- std::search(self.begin() + pos, self.end(), s.begin(), s.end());
- const size_t xpos =
- static_cast<size_t>(result - self.begin());
- return xpos + s.size() <= self.size() ? xpos : BasicStringPiece<STR>::npos;
-}
-
-size_t find(const StringPiece& self, const StringPiece& s, size_t pos) {
- return findT(self, s, pos);
-}
-
-size_t find(const StringPiece16& self, const StringPiece16& s, size_t pos) {
- return findT(self, s, pos);
-}
-
-template<typename STR>
-size_t findT(const BasicStringPiece<STR>& self,
- typename STR::value_type c,
- size_t pos) {
- if (pos >= self.size())
- return BasicStringPiece<STR>::npos;
-
- typename BasicStringPiece<STR>::const_iterator result =
- std::find(self.begin() + pos, self.end(), c);
- return result != self.end() ?
- static_cast<size_t>(result - self.begin()) : BasicStringPiece<STR>::npos;
-}
-
-size_t find(const StringPiece& self, char c, size_t pos) {
- return findT(self, c, pos);
-}
-
-size_t find(const StringPiece16& self, char16 c, size_t pos) {
- return findT(self, c, pos);
-}
-
-template<typename STR>
-size_t rfindT(const BasicStringPiece<STR>& self,
- const BasicStringPiece<STR>& s,
- size_t pos) {
- if (self.size() < s.size())
- return BasicStringPiece<STR>::npos;
-
- if (s.empty())
- return std::min(self.size(), pos);
-
- typename BasicStringPiece<STR>::const_iterator last =
- self.begin() + std::min(self.size() - s.size(), pos) + s.size();
- typename BasicStringPiece<STR>::const_iterator result =
- std::find_end(self.begin(), last, s.begin(), s.end());
- return result != last ?
- static_cast<size_t>(result - self.begin()) : BasicStringPiece<STR>::npos;
-}
-
-size_t rfind(const StringPiece& self, const StringPiece& s, size_t pos) {
- return rfindT(self, s, pos);
-}
-
-size_t rfind(const StringPiece16& self, const StringPiece16& s, size_t pos) {
- return rfindT(self, s, pos);
-}
-
-template<typename STR>
-size_t rfindT(const BasicStringPiece<STR>& self,
- typename STR::value_type c,
- size_t pos) {
- if (self.size() == 0)
- return BasicStringPiece<STR>::npos;
-
- for (size_t i = std::min(pos, self.size() - 1); ;
- --i) {
- if (self.data()[i] == c)
- return i;
- if (i == 0)
- break;
- }
- return BasicStringPiece<STR>::npos;
-}
-
-size_t rfind(const StringPiece& self, char c, size_t pos) {
- return rfindT(self, c, pos);
-}
-
-size_t rfind(const StringPiece16& self, char16 c, size_t pos) {
- return rfindT(self, c, pos);
-}
-
-// 8-bit version using lookup table.
-size_t find_first_of(const StringPiece& self,
- const StringPiece& s,
- size_t pos) {
- if (self.size() == 0 || s.size() == 0)
- return StringPiece::npos;
-
- // Avoid the cost of BuildLookupTable() for a single-character search.
- if (s.size() == 1)
- return find(self, s.data()[0], pos);
-
- bool lookup[UCHAR_MAX + 1] = { false };
- BuildLookupTable(s, lookup);
- for (size_t i = pos; i < self.size(); ++i) {
- if (lookup[static_cast<unsigned char>(self.data()[i])]) {
- return i;
- }
- }
- return StringPiece::npos;
-}
-
-// 16-bit brute force version.
-size_t find_first_of(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos) {
- StringPiece16::const_iterator found =
- std::find_first_of(self.begin() + pos, self.end(), s.begin(), s.end());
- if (found == self.end())
- return StringPiece16::npos;
- return found - self.begin();
-}
-
-// 8-bit version using lookup table.
-size_t find_first_not_of(const StringPiece& self,
- const StringPiece& s,
- size_t pos) {
- if (self.size() == 0)
- return StringPiece::npos;
-
- if (s.size() == 0)
- return 0;
-
- // Avoid the cost of BuildLookupTable() for a single-character search.
- if (s.size() == 1)
- return find_first_not_of(self, s.data()[0], pos);
-
- bool lookup[UCHAR_MAX + 1] = { false };
- BuildLookupTable(s, lookup);
- for (size_t i = pos; i < self.size(); ++i) {
- if (!lookup[static_cast<unsigned char>(self.data()[i])]) {
- return i;
- }
- }
- return StringPiece::npos;
-}
-
-// 16-bit brute-force version.
-BASE_EXPORT size_t find_first_not_of(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos) {
- if (self.size() == 0)
- return StringPiece16::npos;
-
- for (size_t self_i = pos; self_i < self.size(); ++self_i) {
- bool found = false;
- for (size_t s_i = 0; s_i < s.size(); ++s_i) {
- if (self[self_i] == s[s_i]) {
- found = true;
- break;
- }
- }
- if (!found)
- return self_i;
- }
- return StringPiece16::npos;
-}
-
-template<typename STR>
-size_t find_first_not_ofT(const BasicStringPiece<STR>& self,
- typename STR::value_type c,
- size_t pos) {
- if (self.size() == 0)
- return BasicStringPiece<STR>::npos;
-
- for (; pos < self.size(); ++pos) {
- if (self.data()[pos] != c) {
- return pos;
- }
- }
- return BasicStringPiece<STR>::npos;
-}
-
-size_t find_first_not_of(const StringPiece& self,
- char c,
- size_t pos) {
- return find_first_not_ofT(self, c, pos);
-}
-
-size_t find_first_not_of(const StringPiece16& self,
- char16 c,
- size_t pos) {
- return find_first_not_ofT(self, c, pos);
-}
-
-// 8-bit version using lookup table.
-size_t find_last_of(const StringPiece& self, const StringPiece& s, size_t pos) {
- if (self.size() == 0 || s.size() == 0)
- return StringPiece::npos;
-
- // Avoid the cost of BuildLookupTable() for a single-character search.
- if (s.size() == 1)
- return rfind(self, s.data()[0], pos);
-
- bool lookup[UCHAR_MAX + 1] = { false };
- BuildLookupTable(s, lookup);
- for (size_t i = std::min(pos, self.size() - 1); ; --i) {
- if (lookup[static_cast<unsigned char>(self.data()[i])])
- return i;
- if (i == 0)
- break;
- }
- return StringPiece::npos;
-}
-
-// 16-bit brute-force version.
-size_t find_last_of(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos) {
- if (self.size() == 0)
- return StringPiece16::npos;
-
- for (size_t self_i = std::min(pos, self.size() - 1); ;
- --self_i) {
- for (size_t s_i = 0; s_i < s.size(); s_i++) {
- if (self.data()[self_i] == s[s_i])
- return self_i;
- }
- if (self_i == 0)
- break;
- }
- return StringPiece16::npos;
-}
-
-// 8-bit version using lookup table.
-size_t find_last_not_of(const StringPiece& self,
- const StringPiece& s,
- size_t pos) {
- if (self.size() == 0)
- return StringPiece::npos;
-
- size_t i = std::min(pos, self.size() - 1);
- if (s.size() == 0)
- return i;
-
- // Avoid the cost of BuildLookupTable() for a single-character search.
- if (s.size() == 1)
- return find_last_not_of(self, s.data()[0], pos);
-
- bool lookup[UCHAR_MAX + 1] = { false };
- BuildLookupTable(s, lookup);
- for (; ; --i) {
- if (!lookup[static_cast<unsigned char>(self.data()[i])])
- return i;
- if (i == 0)
- break;
- }
- return StringPiece::npos;
-}
-
-// 16-bit brute-force version.
-size_t find_last_not_of(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos) {
- if (self.size() == 0)
- return StringPiece::npos;
-
- for (size_t self_i = std::min(pos, self.size() - 1); ; --self_i) {
- bool found = false;
- for (size_t s_i = 0; s_i < s.size(); s_i++) {
- if (self.data()[self_i] == s[s_i]) {
- found = true;
- break;
- }
- }
- if (!found)
- return self_i;
- if (self_i == 0)
- break;
- }
- return StringPiece16::npos;
-}
-
-template<typename STR>
-size_t find_last_not_ofT(const BasicStringPiece<STR>& self,
- typename STR::value_type c,
- size_t pos) {
- if (self.size() == 0)
- return BasicStringPiece<STR>::npos;
-
- for (size_t i = std::min(pos, self.size() - 1); ; --i) {
- if (self.data()[i] != c)
- return i;
- if (i == 0)
- break;
- }
- return BasicStringPiece<STR>::npos;
-}
-
-size_t find_last_not_of(const StringPiece& self,
- char c,
- size_t pos) {
- return find_last_not_ofT(self, c, pos);
-}
-
-size_t find_last_not_of(const StringPiece16& self,
- char16 c,
- size_t pos) {
- return find_last_not_ofT(self, c, pos);
-}
-
-template<typename STR>
-BasicStringPiece<STR> substrT(const BasicStringPiece<STR>& self,
- size_t pos,
- size_t n) {
- if (pos > self.size()) pos = self.size();
- if (n > self.size() - pos) n = self.size() - pos;
- return BasicStringPiece<STR>(self.data() + pos, n);
-}
-
-StringPiece substr(const StringPiece& self,
- size_t pos,
- size_t n) {
- return substrT(self, pos, n);
-}
-
-StringPiece16 substr(const StringPiece16& self,
- size_t pos,
- size_t n) {
- return substrT(self, pos, n);
-}
-
-#if DCHECK_IS_ON()
-void AssertIteratorsInOrder(std::string::const_iterator begin,
- std::string::const_iterator end) {
- DCHECK(begin <= end) << "StringPiece iterators swapped or invalid.";
-}
-void AssertIteratorsInOrder(string16::const_iterator begin,
- string16::const_iterator end) {
- DCHECK(begin <= end) << "StringPiece iterators swapped or invalid.";
-}
-#endif
-
-} // namespace internal
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/string_piece.h b/security/sandbox/chromium/base/strings/string_piece.h
deleted file mode 100644
index 31e7596d1..000000000
--- a/security/sandbox/chromium/base/strings/string_piece.h
+++ /dev/null
@@ -1,469 +0,0 @@
-// 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.
-// Copied from strings/stringpiece.h with modifications
-//
-// A string-like object that points to a sized piece of memory.
-//
-// You can use StringPiece as a function or method parameter. A StringPiece
-// parameter can receive a double-quoted string literal argument, a "const
-// char*" argument, a string argument, or a StringPiece argument with no data
-// copying. Systematic use of StringPiece for arguments reduces data
-// copies and strlen() calls.
-//
-// Prefer passing StringPieces by value:
-// void MyFunction(StringPiece arg);
-// If circumstances require, you may also pass by const reference:
-// void MyFunction(const StringPiece& arg); // not preferred
-// Both of these have the same lifetime semantics. Passing by value
-// generates slightly smaller code. For more discussion, Googlers can see
-// the thread go/stringpiecebyvalue on c-users.
-
-#ifndef BASE_STRINGS_STRING_PIECE_H_
-#define BASE_STRINGS_STRING_PIECE_H_
-
-#include <stddef.h>
-
-#include <iosfwd>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/containers/hash_tables.h"
-#include "base/logging.h"
-#include "base/strings/string16.h"
-
-namespace base {
-
-template <typename STRING_TYPE> class BasicStringPiece;
-typedef BasicStringPiece<std::string> StringPiece;
-typedef BasicStringPiece<string16> StringPiece16;
-
-// internal --------------------------------------------------------------------
-
-// Many of the StringPiece functions use different implementations for the
-// 8-bit and 16-bit versions, and we don't want lots of template expansions in
-// this (very common) header that will slow down compilation.
-//
-// So here we define overloaded functions called by the StringPiece template.
-// For those that share an implementation, the two versions will expand to a
-// template internal to the .cc file.
-namespace internal {
-
-BASE_EXPORT void CopyToString(const StringPiece& self, std::string* target);
-BASE_EXPORT void CopyToString(const StringPiece16& self, string16* target);
-
-BASE_EXPORT void AppendToString(const StringPiece& self, std::string* target);
-BASE_EXPORT void AppendToString(const StringPiece16& self, string16* target);
-
-BASE_EXPORT size_t copy(const StringPiece& self,
- char* buf,
- size_t n,
- size_t pos);
-BASE_EXPORT size_t copy(const StringPiece16& self,
- char16* buf,
- size_t n,
- size_t pos);
-
-BASE_EXPORT size_t find(const StringPiece& self,
- const StringPiece& s,
- size_t pos);
-BASE_EXPORT size_t find(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos);
-BASE_EXPORT size_t find(const StringPiece& self,
- char c,
- size_t pos);
-BASE_EXPORT size_t find(const StringPiece16& self,
- char16 c,
- size_t pos);
-
-BASE_EXPORT size_t rfind(const StringPiece& self,
- const StringPiece& s,
- size_t pos);
-BASE_EXPORT size_t rfind(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos);
-BASE_EXPORT size_t rfind(const StringPiece& self,
- char c,
- size_t pos);
-BASE_EXPORT size_t rfind(const StringPiece16& self,
- char16 c,
- size_t pos);
-
-BASE_EXPORT size_t find_first_of(const StringPiece& self,
- const StringPiece& s,
- size_t pos);
-BASE_EXPORT size_t find_first_of(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos);
-
-BASE_EXPORT size_t find_first_not_of(const StringPiece& self,
- const StringPiece& s,
- size_t pos);
-BASE_EXPORT size_t find_first_not_of(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos);
-BASE_EXPORT size_t find_first_not_of(const StringPiece& self,
- char c,
- size_t pos);
-BASE_EXPORT size_t find_first_not_of(const StringPiece16& self,
- char16 c,
- size_t pos);
-
-BASE_EXPORT size_t find_last_of(const StringPiece& self,
- const StringPiece& s,
- size_t pos);
-BASE_EXPORT size_t find_last_of(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos);
-BASE_EXPORT size_t find_last_of(const StringPiece& self,
- char c,
- size_t pos);
-BASE_EXPORT size_t find_last_of(const StringPiece16& self,
- char16 c,
- size_t pos);
-
-BASE_EXPORT size_t find_last_not_of(const StringPiece& self,
- const StringPiece& s,
- size_t pos);
-BASE_EXPORT size_t find_last_not_of(const StringPiece16& self,
- const StringPiece16& s,
- size_t pos);
-BASE_EXPORT size_t find_last_not_of(const StringPiece16& self,
- char16 c,
- size_t pos);
-BASE_EXPORT size_t find_last_not_of(const StringPiece& self,
- char c,
- size_t pos);
-
-BASE_EXPORT StringPiece substr(const StringPiece& self,
- size_t pos,
- size_t n);
-BASE_EXPORT StringPiece16 substr(const StringPiece16& self,
- size_t pos,
- size_t n);
-
-#if DCHECK_IS_ON()
-// Asserts that begin <= end to catch some errors with iterator usage.
-BASE_EXPORT void AssertIteratorsInOrder(std::string::const_iterator begin,
- std::string::const_iterator end);
-BASE_EXPORT void AssertIteratorsInOrder(string16::const_iterator begin,
- string16::const_iterator end);
-#endif
-
-} // namespace internal
-
-// BasicStringPiece ------------------------------------------------------------
-
-// Defines the types, methods, operators, and data members common to both
-// StringPiece and StringPiece16. Do not refer to this class directly, but
-// rather to BasicStringPiece, StringPiece, or StringPiece16.
-//
-// This is templatized by string class type rather than character type, so
-// BasicStringPiece<std::string> or BasicStringPiece<base::string16>.
-template <typename STRING_TYPE> class BasicStringPiece {
- public:
- // Standard STL container boilerplate.
- typedef size_t size_type;
- typedef typename STRING_TYPE::value_type value_type;
- typedef const value_type* pointer;
- typedef const value_type& reference;
- typedef const value_type& const_reference;
- typedef ptrdiff_t difference_type;
- typedef const value_type* const_iterator;
- typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
-
- static const size_type npos;
-
- public:
- // We provide non-explicit singleton constructors so users can pass
- // in a "const char*" or a "string" wherever a "StringPiece" is
- // expected (likewise for char16, string16, StringPiece16).
- BasicStringPiece() : ptr_(NULL), length_(0) {}
- BasicStringPiece(const value_type* str)
- : ptr_(str),
- length_((str == NULL) ? 0 : STRING_TYPE::traits_type::length(str)) {}
- BasicStringPiece(const STRING_TYPE& str)
- : ptr_(str.data()), length_(str.size()) {}
- BasicStringPiece(const value_type* offset, size_type len)
- : ptr_(offset), length_(len) {}
- BasicStringPiece(const typename STRING_TYPE::const_iterator& begin,
- const typename STRING_TYPE::const_iterator& end) {
-#if DCHECK_IS_ON()
- // This assertion is done out-of-line to avoid bringing in logging.h and
- // instantiating logging macros for every instantiation.
- internal::AssertIteratorsInOrder(begin, end);
-#endif
- length_ = static_cast<size_t>(std::distance(begin, end));
-
- // The length test before assignment is to avoid dereferencing an iterator
- // that may point to the end() of a string.
- ptr_ = length_ > 0 ? &*begin : nullptr;
- }
-
- // 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 value_type* 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 value_type* data, size_type len) {
- ptr_ = data;
- length_ = len;
- }
- void set(const value_type* str) {
- ptr_ = str;
- length_ = str ? STRING_TYPE::traits_type::length(str) : 0;
- }
-
- value_type 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 BasicStringPiece<STRING_TYPE>& x) const {
- int r = wordmemcmp(
- ptr_, x.ptr_, (length_ < x.length_ ? length_ : x.length_));
- if (r == 0) {
- if (length_ < x.length_) r = -1;
- else if (length_ > x.length_) r = +1;
- }
- return r;
- }
-
- STRING_TYPE as_string() const {
- // std::string doesn't like to take a NULL pointer even with a 0 size.
- return empty() ? STRING_TYPE() : STRING_TYPE(data(), size());
- }
-
- const_iterator begin() const { return ptr_; }
- const_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_; }
-
- static int wordmemcmp(const value_type* p,
- const value_type* p2,
- size_type N) {
- return STRING_TYPE::traits_type::compare(p, p2, N);
- }
-
- // Sets the value of the given string target type to be the current string.
- // This saves a temporary over doing |a = b.as_string()|
- void CopyToString(STRING_TYPE* target) const {
- internal::CopyToString(*this, target);
- }
-
- void AppendToString(STRING_TYPE* target) const {
- internal::AppendToString(*this, target);
- }
-
- size_type copy(value_type* buf, size_type n, size_type pos = 0) const {
- return internal::copy(*this, buf, n, pos);
- }
-
- // Does "this" start with "x"
- bool starts_with(const BasicStringPiece& x) const {
- return ((this->length_ >= x.length_) &&
- (wordmemcmp(this->ptr_, x.ptr_, x.length_) == 0));
- }
-
- // Does "this" end with "x"
- bool ends_with(const BasicStringPiece& x) const {
- return ((this->length_ >= x.length_) &&
- (wordmemcmp(this->ptr_ + (this->length_-x.length_),
- x.ptr_, x.length_) == 0));
- }
-
- // find: Search for a character or substring at a given offset.
- size_type find(const BasicStringPiece<STRING_TYPE>& s,
- size_type pos = 0) const {
- return internal::find(*this, s, pos);
- }
- size_type find(value_type c, size_type pos = 0) const {
- return internal::find(*this, c, pos);
- }
-
- // rfind: Reverse find.
- size_type rfind(const BasicStringPiece& s,
- size_type pos = BasicStringPiece::npos) const {
- return internal::rfind(*this, s, pos);
- }
- size_type rfind(value_type c, size_type pos = BasicStringPiece::npos) const {
- return internal::rfind(*this, c, pos);
- }
-
- // find_first_of: Find the first occurence of one of a set of characters.
- size_type find_first_of(const BasicStringPiece& s,
- size_type pos = 0) const {
- return internal::find_first_of(*this, s, pos);
- }
- size_type find_first_of(value_type c, size_type pos = 0) const {
- return find(c, pos);
- }
-
- // find_first_not_of: Find the first occurence not of a set of characters.
- size_type find_first_not_of(const BasicStringPiece& s,
- size_type pos = 0) const {
- return internal::find_first_not_of(*this, s, pos);
- }
- size_type find_first_not_of(value_type c, size_type pos = 0) const {
- return internal::find_first_not_of(*this, c, pos);
- }
-
- // find_last_of: Find the last occurence of one of a set of characters.
- size_type find_last_of(const BasicStringPiece& s,
- size_type pos = BasicStringPiece::npos) const {
- return internal::find_last_of(*this, s, pos);
- }
- size_type find_last_of(value_type c,
- size_type pos = BasicStringPiece::npos) const {
- return rfind(c, pos);
- }
-
- // find_last_not_of: Find the last occurence not of a set of characters.
- size_type find_last_not_of(const BasicStringPiece& s,
- size_type pos = BasicStringPiece::npos) const {
- return internal::find_last_not_of(*this, s, pos);
- }
- size_type find_last_not_of(value_type c,
- size_type pos = BasicStringPiece::npos) const {
- return internal::find_last_not_of(*this, c, pos);
- }
-
- // substr.
- BasicStringPiece substr(size_type pos,
- size_type n = BasicStringPiece::npos) const {
- return internal::substr(*this, pos, n);
- }
-
- protected:
- const value_type* ptr_;
- size_type length_;
-};
-
-template <typename STRING_TYPE>
-const typename BasicStringPiece<STRING_TYPE>::size_type
-BasicStringPiece<STRING_TYPE>::npos =
- typename BasicStringPiece<STRING_TYPE>::size_type(-1);
-
-// MSVC doesn't like complex extern templates and DLLs.
-#if !defined(COMPILER_MSVC)
-extern template class BASE_EXPORT BasicStringPiece<std::string>;
-extern template class BASE_EXPORT BasicStringPiece<string16>;
-#endif
-
-// StingPiece operators --------------------------------------------------------
-
-BASE_EXPORT 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(), (x.size() < y.size() ? 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);
-}
-
-// StringPiece16 operators -----------------------------------------------------
-
-inline bool operator==(const StringPiece16& x, const StringPiece16& y) {
- if (x.size() != y.size())
- return false;
-
- return StringPiece16::wordmemcmp(x.data(), y.data(), x.size()) == 0;
-}
-
-inline bool operator!=(const StringPiece16& x, const StringPiece16& y) {
- return !(x == y);
-}
-
-inline bool operator<(const StringPiece16& x, const StringPiece16& y) {
- const int r = StringPiece16::wordmemcmp(
- x.data(), y.data(), (x.size() < y.size() ? x.size() : y.size()));
- return ((r < 0) || ((r == 0) && (x.size() < y.size())));
-}
-
-inline bool operator>(const StringPiece16& x, const StringPiece16& y) {
- return y < x;
-}
-
-inline bool operator<=(const StringPiece16& x, const StringPiece16& y) {
- return !(x > y);
-}
-
-inline bool operator>=(const StringPiece16& x, const StringPiece16& y) {
- return !(x < y);
-}
-
-BASE_EXPORT std::ostream& operator<<(std::ostream& o,
- const StringPiece& piece);
-
-} // namespace base
-
-// Hashing ---------------------------------------------------------------------
-
-// We provide appropriate hash functions so StringPiece and StringPiece16 can
-// be used as keys in hash sets and maps.
-
-// This hash function is copied from base/containers/hash_tables.h. We don't
-// use the ones already defined for string and string16 directly because it
-// would require the string constructors to be called, which we don't want.
-#define HASH_STRING_PIECE(StringPieceType, string_piece) \
- std::size_t result = 0; \
- for (StringPieceType::const_iterator i = string_piece.begin(); \
- i != string_piece.end(); ++i) \
- result = (result * 131) + *i; \
- return result; \
-
-namespace BASE_HASH_NAMESPACE {
-
-template<>
-struct hash<base::StringPiece> {
- std::size_t operator()(const base::StringPiece& sp) const {
- HASH_STRING_PIECE(base::StringPiece, sp);
- }
-};
-template<>
-struct hash<base::StringPiece16> {
- std::size_t operator()(const base::StringPiece16& sp16) const {
- HASH_STRING_PIECE(base::StringPiece16, sp16);
- }
-};
-
-} // namespace BASE_HASH_NAMESPACE
-
-#endif // BASE_STRINGS_STRING_PIECE_H_
diff --git a/security/sandbox/chromium/base/strings/string_split.cc b/security/sandbox/chromium/base/strings/string_split.cc
deleted file mode 100644
index 6c949b989..000000000
--- a/security/sandbox/chromium/base/strings/string_split.cc
+++ /dev/null
@@ -1,264 +0,0 @@
-// 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.
-
-#include "base/strings/string_split.h"
-
-#include <stddef.h>
-
-#include "base/logging.h"
-#include "base/strings/string_util.h"
-#include "base/third_party/icu/icu_utf.h"
-
-namespace base {
-
-namespace {
-
-// PieceToOutputType converts a StringPiece as needed to a given output type,
-// which is either the same type of StringPiece (a NOP) or the corresponding
-// non-piece string type.
-//
-// The default converter is a NOP, it works when the OutputType is the
-// correct StringPiece.
-template<typename Str, typename OutputType>
-OutputType PieceToOutputType(BasicStringPiece<Str> piece) {
- return piece;
-}
-template<> // Convert StringPiece to std::string
-std::string PieceToOutputType<std::string, std::string>(StringPiece piece) {
- return piece.as_string();
-}
-template<> // Convert StringPiece16 to string16.
-string16 PieceToOutputType<string16, string16>(StringPiece16 piece) {
- return piece.as_string();
-}
-
-// Returns either the ASCII or UTF-16 whitespace.
-template<typename Str> BasicStringPiece<Str> WhitespaceForType();
-template<> StringPiece16 WhitespaceForType<string16>() {
- return kWhitespaceUTF16;
-}
-template<> StringPiece WhitespaceForType<std::string>() {
- return kWhitespaceASCII;
-}
-
-// Optimize the single-character case to call find() on the string instead,
-// since this is the common case and can be made faster. This could have been
-// done with template specialization too, but would have been less clear.
-//
-// There is no corresponding FindFirstNotOf because StringPiece already
-// implements these different versions that do the optimized searching.
-size_t FindFirstOf(StringPiece piece, char c, size_t pos) {
- return piece.find(c, pos);
-}
-size_t FindFirstOf(StringPiece16 piece, char16 c, size_t pos) {
- return piece.find(c, pos);
-}
-size_t FindFirstOf(StringPiece piece, StringPiece one_of, size_t pos) {
- return piece.find_first_of(one_of, pos);
-}
-size_t FindFirstOf(StringPiece16 piece, StringPiece16 one_of, size_t pos) {
- return piece.find_first_of(one_of, pos);
-}
-
-// General string splitter template. Can take 8- or 16-bit input, can produce
-// the corresponding string or StringPiece output, and can take single- or
-// multiple-character delimiters.
-//
-// DelimiterType is either a character (Str::value_type) or a string piece of
-// multiple characters (BasicStringPiece<Str>). StringPiece has a version of
-// find for both of these cases, and the single-character version is the most
-// common and can be implemented faster, which is why this is a template.
-template<typename Str, typename OutputStringType, typename DelimiterType>
-static std::vector<OutputStringType> SplitStringT(
- BasicStringPiece<Str> str,
- DelimiterType delimiter,
- WhitespaceHandling whitespace,
- SplitResult result_type) {
- std::vector<OutputStringType> result;
- if (str.empty())
- return result;
-
- size_t start = 0;
- while (start != Str::npos) {
- size_t end = FindFirstOf(str, delimiter, start);
-
- BasicStringPiece<Str> piece;
- if (end == Str::npos) {
- piece = str.substr(start);
- start = Str::npos;
- } else {
- piece = str.substr(start, end - start);
- start = end + 1;
- }
-
- if (whitespace == TRIM_WHITESPACE)
- piece = TrimString(piece, WhitespaceForType<Str>(), TRIM_ALL);
-
- if (result_type == SPLIT_WANT_ALL || !piece.empty())
- result.push_back(PieceToOutputType<Str, OutputStringType>(piece));
- }
- return result;
-}
-
-bool AppendStringKeyValue(StringPiece input,
- char delimiter,
- StringPairs* result) {
- // Always append a new item regardless of success (it might be empty). The
- // below code will copy the strings directly into the result pair.
- result->resize(result->size() + 1);
- auto& result_pair = result->back();
-
- // Find the delimiter.
- size_t end_key_pos = input.find_first_of(delimiter);
- if (end_key_pos == std::string::npos) {
- DVLOG(1) << "cannot find delimiter in: " << input;
- return false; // No delimiter.
- }
- input.substr(0, end_key_pos).CopyToString(&result_pair.first);
-
- // Find the value string.
- StringPiece remains = input.substr(end_key_pos, input.size() - end_key_pos);
- size_t begin_value_pos = remains.find_first_not_of(delimiter);
- if (begin_value_pos == StringPiece::npos) {
- DVLOG(1) << "cannot parse value from input: " << input;
- return false; // No value.
- }
- remains.substr(begin_value_pos, remains.size() - begin_value_pos)
- .CopyToString(&result_pair.second);
-
- return true;
-}
-
-template <typename Str, typename OutputStringType>
-void SplitStringUsingSubstrT(BasicStringPiece<Str> input,
- BasicStringPiece<Str> delimiter,
- WhitespaceHandling whitespace,
- SplitResult result_type,
- std::vector<OutputStringType>* result) {
- using Piece = BasicStringPiece<Str>;
- using size_type = typename Piece::size_type;
-
- result->clear();
- for (size_type begin_index = 0, end_index = 0; end_index != Piece::npos;
- begin_index = end_index + delimiter.size()) {
- end_index = input.find(delimiter, begin_index);
- Piece term = end_index == Piece::npos
- ? input.substr(begin_index)
- : input.substr(begin_index, end_index - begin_index);
-
- if (whitespace == TRIM_WHITESPACE)
- term = TrimString(term, WhitespaceForType<Str>(), TRIM_ALL);
-
- if (result_type == SPLIT_WANT_ALL || !term.empty())
- result->push_back(PieceToOutputType<Str, OutputStringType>(term));
- }
-}
-
-} // namespace
-
-std::vector<std::string> SplitString(StringPiece input,
- StringPiece separators,
- WhitespaceHandling whitespace,
- SplitResult result_type) {
- if (separators.size() == 1) {
- return SplitStringT<std::string, std::string, char>(
- input, separators[0], whitespace, result_type);
- }
- return SplitStringT<std::string, std::string, StringPiece>(
- input, separators, whitespace, result_type);
-}
-
-std::vector<string16> SplitString(StringPiece16 input,
- StringPiece16 separators,
- WhitespaceHandling whitespace,
- SplitResult result_type) {
- if (separators.size() == 1) {
- return SplitStringT<string16, string16, char16>(
- input, separators[0], whitespace, result_type);
- }
- return SplitStringT<string16, string16, StringPiece16>(
- input, separators, whitespace, result_type);
-}
-
-std::vector<StringPiece> SplitStringPiece(StringPiece input,
- StringPiece separators,
- WhitespaceHandling whitespace,
- SplitResult result_type) {
- if (separators.size() == 1) {
- return SplitStringT<std::string, StringPiece, char>(
- input, separators[0], whitespace, result_type);
- }
- return SplitStringT<std::string, StringPiece, StringPiece>(
- input, separators, whitespace, result_type);
-}
-
-std::vector<StringPiece16> SplitStringPiece(StringPiece16 input,
- StringPiece16 separators,
- WhitespaceHandling whitespace,
- SplitResult result_type) {
- if (separators.size() == 1) {
- return SplitStringT<string16, StringPiece16, char16>(
- input, separators[0], whitespace, result_type);
- }
- return SplitStringT<string16, StringPiece16, StringPiece16>(
- input, separators, whitespace, result_type);
-}
-
-bool SplitStringIntoKeyValuePairs(StringPiece input,
- char key_value_delimiter,
- char key_value_pair_delimiter,
- StringPairs* key_value_pairs) {
- key_value_pairs->clear();
-
- std::vector<StringPiece> pairs = SplitStringPiece(
- input, std::string(1, key_value_pair_delimiter),
- TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
- key_value_pairs->reserve(pairs.size());
-
- bool success = true;
- for (const StringPiece& pair : pairs) {
- if (!AppendStringKeyValue(pair, key_value_delimiter, key_value_pairs)) {
- // Don't return here, to allow for pairs without associated
- // value or key; just record that the split failed.
- success = false;
- }
- }
- return success;
-}
-
-void SplitStringUsingSubstr(StringPiece16 input,
- StringPiece16 delimiter,
- std::vector<string16>* result) {
- SplitStringUsingSubstrT(input, delimiter, TRIM_WHITESPACE, SPLIT_WANT_ALL,
- result);
-}
-
-void SplitStringUsingSubstr(StringPiece input,
- StringPiece delimiter,
- std::vector<std::string>* result) {
- SplitStringUsingSubstrT(input, delimiter, TRIM_WHITESPACE, SPLIT_WANT_ALL,
- result);
-}
-
-std::vector<StringPiece16> SplitStringPieceUsingSubstr(
- StringPiece16 input,
- StringPiece16 delimiter,
- WhitespaceHandling whitespace,
- SplitResult result_type) {
- std::vector<StringPiece16> result;
- SplitStringUsingSubstrT(input, delimiter, whitespace, result_type, &result);
- return result;
-}
-
-std::vector<StringPiece> SplitStringPieceUsingSubstr(
- StringPiece input,
- StringPiece delimiter,
- WhitespaceHandling whitespace,
- SplitResult result_type) {
- std::vector<StringPiece> result;
- SplitStringUsingSubstrT(input, delimiter, whitespace, result_type, &result);
- return result;
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/string_split.h b/security/sandbox/chromium/base/strings/string_split.h
deleted file mode 100644
index ec9f24604..000000000
--- a/security/sandbox/chromium/base/strings/string_split.h
+++ /dev/null
@@ -1,129 +0,0 @@
-// 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.
-
-#ifndef BASE_STRINGS_STRING_SPLIT_H_
-#define BASE_STRINGS_STRING_SPLIT_H_
-
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_piece.h"
-
-namespace base {
-
-enum WhitespaceHandling {
- KEEP_WHITESPACE,
- TRIM_WHITESPACE,
-};
-
-enum SplitResult {
- // Strictly return all results.
- //
- // If the input is ",," and the separator is ',' this will return a
- // vector of three empty strings.
- SPLIT_WANT_ALL,
-
- // Only nonempty results will be added to the results. Multiple separators
- // will be coalesced. Separators at the beginning and end of the input will
- // be ignored. With TRIM_WHITESPACE, whitespace-only results will be dropped.
- //
- // If the input is ",," and the separator is ',', this will return an empty
- // vector.
- SPLIT_WANT_NONEMPTY,
-};
-
-// Split the given string on ANY of the given separators, returning copies of
-// the result.
-//
-// To split on either commas or semicolons, keeping all whitespace:
-//
-// std::vector<std::string> tokens = base::SplitString(
-// input, ",;", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
-BASE_EXPORT std::vector<std::string> SplitString(
- StringPiece input,
- StringPiece separators,
- WhitespaceHandling whitespace,
- SplitResult result_type);
-BASE_EXPORT std::vector<string16> SplitString(
- StringPiece16 input,
- StringPiece16 separators,
- WhitespaceHandling whitespace,
- SplitResult result_type);
-
-// Like SplitString above except it returns a vector of StringPieces which
-// reference the original buffer without copying. Although you have to be
-// careful to keep the original string unmodified, this provides an efficient
-// way to iterate through tokens in a string.
-//
-// To iterate through all whitespace-separated tokens in an input string:
-//
-// for (const auto& cur :
-// base::SplitStringPiece(input, base::kWhitespaceASCII,
-// base::KEEP_WHITESPACE,
-// base::SPLIT_WANT_NONEMPTY)) {
-// ...
-BASE_EXPORT std::vector<StringPiece> SplitStringPiece(
- StringPiece input,
- StringPiece separators,
- WhitespaceHandling whitespace,
- SplitResult result_type);
-BASE_EXPORT std::vector<StringPiece16> SplitStringPiece(
- StringPiece16 input,
- StringPiece16 separators,
- WhitespaceHandling whitespace,
- SplitResult result_type);
-
-using StringPairs = std::vector<std::pair<std::string, std::string>>;
-
-// Splits |line| into key value pairs according to the given delimiters and
-// removes whitespace leading each key and trailing each value. Returns true
-// only if each pair has a non-empty key and value. |key_value_pairs| will
-// include ("","") pairs for entries without |key_value_delimiter|.
-BASE_EXPORT bool SplitStringIntoKeyValuePairs(StringPiece input,
- char key_value_delimiter,
- char key_value_pair_delimiter,
- StringPairs* key_value_pairs);
-
-// Similar to SplitString, but use a substring delimiter instead of a list of
-// characters that are all possible delimiters.
-//
-// TODO(brettw) this should probably be changed and expanded to provide a
-// mirror of the SplitString[Piece] API above, just with the different
-// delimiter handling.
-BASE_EXPORT void SplitStringUsingSubstr(StringPiece16 input,
- StringPiece16 delimiter,
- std::vector<string16>* result);
-BASE_EXPORT void SplitStringUsingSubstr(StringPiece input,
- StringPiece delimiter,
- std::vector<std::string>* result);
-
-// Like SplitStringUsingSubstr above except it returns a vector of StringPieces
-// which reference the original buffer without copying. Although you have to be
-// careful to keep the original string unmodified, this provides an efficient
-// way to iterate through tokens in a string.
-//
-// To iterate through all newline-separated tokens in an input string:
-//
-// for (const auto& cur :
-// base::SplitStringUsingSubstr(input, "\r\n",
-// base::KEEP_WHITESPACE,
-// base::SPLIT_WANT_NONEMPTY)) {
-// ...
-BASE_EXPORT std::vector<StringPiece16> SplitStringPieceUsingSubstr(
- StringPiece16 input,
- StringPiece16 delimiter,
- WhitespaceHandling whitespace,
- SplitResult result_type);
-BASE_EXPORT std::vector<StringPiece> SplitStringPieceUsingSubstr(
- StringPiece input,
- StringPiece delimiter,
- WhitespaceHandling whitespace,
- SplitResult result_type);
-
-} // namespace base
-
-#endif // BASE_STRINGS_STRING_SPLIT_H_
diff --git a/security/sandbox/chromium/base/strings/string_util.cc b/security/sandbox/chromium/base/strings/string_util.cc
deleted file mode 100644
index e8000abd4..000000000
--- a/security/sandbox/chromium/base/strings/string_util.cc
+++ /dev/null
@@ -1,1001 +0,0 @@
-// Copyright 2013 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/strings/string_util.h"
-
-#include <ctype.h>
-#include <errno.h>
-#include <math.h>
-#include <stdarg.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <wchar.h>
-#include <wctype.h>
-
-#include <algorithm>
-#include <limits>
-#include <vector>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/singleton.h"
-#include "base/strings/string_split.h"
-#include "base/strings/utf_string_conversion_utils.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/third_party/icu/icu_utf.h"
-#include "build/build_config.h"
-
-namespace base {
-
-namespace {
-
-// Force the singleton used by EmptyString[16] to be a unique type. This
-// prevents other code that might accidentally use Singleton<string> from
-// getting our internal one.
-struct EmptyStrings {
- EmptyStrings() {}
- const std::string s;
- const string16 s16;
-
- static EmptyStrings* GetInstance() {
- return Singleton<EmptyStrings>::get();
- }
-};
-
-// Used by ReplaceStringPlaceholders to track the position in the string of
-// replaced parameters.
-struct ReplacementOffset {
- ReplacementOffset(uintptr_t parameter, size_t offset)
- : parameter(parameter),
- offset(offset) {}
-
- // Index of the parameter.
- uintptr_t parameter;
-
- // Starting position in the string.
- size_t offset;
-};
-
-static bool CompareParameter(const ReplacementOffset& elem1,
- const ReplacementOffset& elem2) {
- return elem1.parameter < elem2.parameter;
-}
-
-// Assuming that a pointer is the size of a "machine word", then
-// uintptr_t is an integer type that is also a machine word.
-typedef uintptr_t MachineWord;
-const uintptr_t kMachineWordAlignmentMask = sizeof(MachineWord) - 1;
-
-inline bool IsAlignedToMachineWord(const void* pointer) {
- return !(reinterpret_cast<MachineWord>(pointer) & kMachineWordAlignmentMask);
-}
-
-template<typename T> inline T* AlignToMachineWord(T* pointer) {
- return reinterpret_cast<T*>(reinterpret_cast<MachineWord>(pointer) &
- ~kMachineWordAlignmentMask);
-}
-
-template<size_t size, typename CharacterType> struct NonASCIIMask;
-template<> struct NonASCIIMask<4, char16> {
- static inline uint32_t value() { return 0xFF80FF80U; }
-};
-template<> struct NonASCIIMask<4, char> {
- static inline uint32_t value() { return 0x80808080U; }
-};
-template<> struct NonASCIIMask<8, char16> {
- static inline uint64_t value() { return 0xFF80FF80FF80FF80ULL; }
-};
-template<> struct NonASCIIMask<8, char> {
- static inline uint64_t value() { return 0x8080808080808080ULL; }
-};
-#if defined(WCHAR_T_IS_UTF32)
-template<> struct NonASCIIMask<4, wchar_t> {
- static inline uint32_t value() { return 0xFFFFFF80U; }
-};
-template<> struct NonASCIIMask<8, wchar_t> {
- static inline uint64_t value() { return 0xFFFFFF80FFFFFF80ULL; }
-};
-#endif // WCHAR_T_IS_UTF32
-
-} // namespace
-
-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 {
-
-template<typename StringType>
-StringType ToLowerASCIIImpl(BasicStringPiece<StringType> str) {
- StringType ret;
- ret.reserve(str.size());
- for (size_t i = 0; i < str.size(); i++)
- ret.push_back(ToLowerASCII(str[i]));
- return ret;
-}
-
-template<typename StringType>
-StringType ToUpperASCIIImpl(BasicStringPiece<StringType> str) {
- StringType ret;
- ret.reserve(str.size());
- for (size_t i = 0; i < str.size(); i++)
- ret.push_back(ToUpperASCII(str[i]));
- return ret;
-}
-
-} // namespace
-
-std::string ToLowerASCII(StringPiece str) {
- return ToLowerASCIIImpl<std::string>(str);
-}
-
-string16 ToLowerASCII(StringPiece16 str) {
- return ToLowerASCIIImpl<string16>(str);
-}
-
-std::string ToUpperASCII(StringPiece str) {
- return ToUpperASCIIImpl<std::string>(str);
-}
-
-string16 ToUpperASCII(StringPiece16 str) {
- return ToUpperASCIIImpl<string16>(str);
-}
-
-template<class StringType>
-int CompareCaseInsensitiveASCIIT(BasicStringPiece<StringType> a,
- BasicStringPiece<StringType> b) {
- // Find the first characters that aren't equal and compare them. If the end
- // of one of the strings is found before a nonequal character, the lengths
- // of the strings are compared.
- size_t i = 0;
- while (i < a.length() && i < b.length()) {
- typename StringType::value_type lower_a = ToLowerASCII(a[i]);
- typename StringType::value_type lower_b = ToLowerASCII(b[i]);
- if (lower_a < lower_b)
- return -1;
- if (lower_a > lower_b)
- return 1;
- i++;
- }
-
- // End of one string hit before finding a different character. Expect the
- // common case to be "strings equal" at this point so check that first.
- if (a.length() == b.length())
- return 0;
-
- if (a.length() < b.length())
- return -1;
- return 1;
-}
-
-int CompareCaseInsensitiveASCII(StringPiece a, StringPiece b) {
- return CompareCaseInsensitiveASCIIT<std::string>(a, b);
-}
-
-int CompareCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b) {
- return CompareCaseInsensitiveASCIIT<string16>(a, b);
-}
-
-bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b) {
- if (a.length() != b.length())
- return false;
- return CompareCaseInsensitiveASCIIT<std::string>(a, b) == 0;
-}
-
-bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b) {
- if (a.length() != b.length())
- return false;
- return CompareCaseInsensitiveASCIIT<string16>(a, b) == 0;
-}
-
-const std::string& EmptyString() {
- return EmptyStrings::GetInstance()->s;
-}
-
-const string16& EmptyString16() {
- return EmptyStrings::GetInstance()->s16;
-}
-
-template<typename STR>
-bool ReplaceCharsT(const STR& input,
- const STR& replace_chars,
- const STR& replace_with,
- STR* output) {
- bool removed = false;
- size_t replace_length = replace_with.length();
-
- *output = input;
-
- size_t found = output->find_first_of(replace_chars);
- while (found != STR::npos) {
- removed = true;
- output->replace(found, 1, replace_with);
- found = output->find_first_of(replace_chars, found + replace_length);
- }
-
- return removed;
-}
-
-bool ReplaceChars(const string16& input,
- const StringPiece16& replace_chars,
- const string16& replace_with,
- string16* output) {
- return ReplaceCharsT(input, replace_chars.as_string(), replace_with, output);
-}
-
-bool ReplaceChars(const std::string& input,
- const StringPiece& replace_chars,
- const std::string& replace_with,
- std::string* output) {
- return ReplaceCharsT(input, replace_chars.as_string(), replace_with, output);
-}
-
-bool RemoveChars(const string16& input,
- const StringPiece16& remove_chars,
- string16* output) {
- return ReplaceChars(input, remove_chars.as_string(), string16(), output);
-}
-
-bool RemoveChars(const std::string& input,
- const StringPiece& remove_chars,
- std::string* output) {
- return ReplaceChars(input, remove_chars.as_string(), std::string(), output);
-}
-
-template<typename Str>
-TrimPositions TrimStringT(const Str& input,
- BasicStringPiece<Str> trim_chars,
- TrimPositions positions,
- Str* output) {
- // Find the edges of leading/trailing whitespace as desired. Need to use
- // a StringPiece version of input to be able to call find* on it with the
- // StringPiece version of trim_chars (normally the trim_chars will be a
- // constant so avoid making a copy).
- BasicStringPiece<Str> input_piece(input);
- const size_t last_char = input.length() - 1;
- const size_t first_good_char = (positions & TRIM_LEADING) ?
- input_piece.find_first_not_of(trim_chars) : 0;
- const size_t last_good_char = (positions & TRIM_TRAILING) ?
- input_piece.find_last_not_of(trim_chars) : last_char;
-
- // When the string was all trimmed, report that we stripped off characters
- // from whichever position the caller was interested in. For empty input, we
- // stripped no characters, 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.
- *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));
-}
-
-bool TrimString(const string16& input,
- StringPiece16 trim_chars,
- string16* output) {
- return TrimStringT(input, trim_chars, TRIM_ALL, output) != TRIM_NONE;
-}
-
-bool TrimString(const std::string& input,
- StringPiece trim_chars,
- std::string* output) {
- return TrimStringT(input, trim_chars, TRIM_ALL, output) != TRIM_NONE;
-}
-
-template<typename Str>
-BasicStringPiece<Str> TrimStringPieceT(BasicStringPiece<Str> input,
- BasicStringPiece<Str> trim_chars,
- TrimPositions positions) {
- size_t begin = (positions & TRIM_LEADING) ?
- input.find_first_not_of(trim_chars) : 0;
- size_t end = (positions & TRIM_TRAILING) ?
- input.find_last_not_of(trim_chars) + 1 : input.size();
- return input.substr(begin, end - begin);
-}
-
-StringPiece16 TrimString(StringPiece16 input,
- const StringPiece16& trim_chars,
- TrimPositions positions) {
- return TrimStringPieceT(input, trim_chars, positions);
-}
-
-StringPiece TrimString(StringPiece input,
- const StringPiece& trim_chars,
- TrimPositions positions) {
- return TrimStringPieceT(input, trim_chars, positions);
-}
-
-void TruncateUTF8ToByteSize(const std::string& input,
- const size_t byte_size,
- std::string* output) {
- DCHECK(output);
- if (byte_size > input.length()) {
- *output = input;
- return;
- }
- DCHECK_LE(byte_size,
- static_cast<uint32_t>(std::numeric_limits<int32_t>::max()));
- // Note: This cast is necessary because CBU8_NEXT uses int32_ts.
- int32_t truncation_length = static_cast<int32_t>(byte_size);
- int32_t char_index = truncation_length - 1;
- const char* data = input.data();
-
- // Using CBU8, we will move backwards from the truncation point
- // to the beginning of the string looking for a valid UTF8
- // character. Once a full UTF8 character is found, we will
- // truncate the string to the end of that character.
- while (char_index >= 0) {
- int32_t prev = char_index;
- base_icu::UChar32 code_point = 0;
- CBU8_NEXT(data, char_index, truncation_length, code_point);
- if (!IsValidCharacter(code_point) ||
- !IsValidCodepoint(code_point)) {
- char_index = prev - 1;
- } else {
- break;
- }
- }
-
- if (char_index >= 0 )
- *output = input.substr(0, char_index);
- else
- output->clear();
-}
-
-TrimPositions TrimWhitespace(const string16& input,
- TrimPositions positions,
- string16* output) {
- return TrimStringT(input, StringPiece16(kWhitespaceUTF16), positions, output);
-}
-
-StringPiece16 TrimWhitespace(StringPiece16 input,
- TrimPositions positions) {
- return TrimStringPieceT(input, StringPiece16(kWhitespaceUTF16), positions);
-}
-
-TrimPositions TrimWhitespaceASCII(const std::string& input,
- TrimPositions positions,
- std::string* output) {
- return TrimStringT(input, StringPiece(kWhitespaceASCII), positions, output);
-}
-
-StringPiece TrimWhitespaceASCII(StringPiece input, TrimPositions positions) {
- return TrimStringPieceT(input, StringPiece(kWhitespaceASCII), positions);
-}
-
-template<typename STR>
-STR CollapseWhitespaceT(const STR& text,
- bool trim_sequences_with_line_breaks) {
- STR result;
- result.resize(text.size());
-
- // Set flags to pretend we're already in a trimmed whitespace sequence, so we
- // will trim any leading whitespace.
- bool in_whitespace = true;
- bool already_trimmed = true;
-
- int chars_written = 0;
- for (typename STR::const_iterator i(text.begin()); i != text.end(); ++i) {
- if (IsUnicodeWhitespace(*i)) {
- if (!in_whitespace) {
- // Reduce all whitespace sequences to a single space.
- in_whitespace = true;
- result[chars_written++] = L' ';
- }
- if (trim_sequences_with_line_breaks && !already_trimmed &&
- ((*i == '\n') || (*i == '\r'))) {
- // Whitespace sequences containing CR or LF are eliminated entirely.
- already_trimmed = true;
- --chars_written;
- }
- } else {
- // Non-whitespace chracters are copied straight across.
- in_whitespace = false;
- already_trimmed = false;
- result[chars_written++] = *i;
- }
- }
-
- if (in_whitespace && !already_trimmed) {
- // Any trailing whitespace is eliminated.
- --chars_written;
- }
-
- result.resize(chars_written);
- return result;
-}
-
-string16 CollapseWhitespace(const string16& text,
- bool trim_sequences_with_line_breaks) {
- return CollapseWhitespaceT(text, trim_sequences_with_line_breaks);
-}
-
-std::string CollapseWhitespaceASCII(const std::string& text,
- bool trim_sequences_with_line_breaks) {
- return CollapseWhitespaceT(text, trim_sequences_with_line_breaks);
-}
-
-bool ContainsOnlyChars(const StringPiece& input,
- const StringPiece& characters) {
- return input.find_first_not_of(characters) == StringPiece::npos;
-}
-
-bool ContainsOnlyChars(const StringPiece16& input,
- const StringPiece16& characters) {
- return input.find_first_not_of(characters) == StringPiece16::npos;
-}
-
-template <class Char>
-inline bool DoIsStringASCII(const Char* characters, size_t length) {
- MachineWord all_char_bits = 0;
- const Char* end = characters + length;
-
- // Prologue: align the input.
- while (!IsAlignedToMachineWord(characters) && characters != end) {
- all_char_bits |= *characters;
- ++characters;
- }
-
- // Compare the values of CPU word size.
- const Char* word_end = AlignToMachineWord(end);
- const size_t loop_increment = sizeof(MachineWord) / sizeof(Char);
- while (characters < word_end) {
- all_char_bits |= *(reinterpret_cast<const MachineWord*>(characters));
- characters += loop_increment;
- }
-
- // Process the remaining bytes.
- while (characters != end) {
- all_char_bits |= *characters;
- ++characters;
- }
-
- MachineWord non_ascii_bit_mask =
- NonASCIIMask<sizeof(MachineWord), Char>::value();
- return !(all_char_bits & non_ascii_bit_mask);
-}
-
-bool IsStringASCII(const StringPiece& str) {
- return DoIsStringASCII(str.data(), str.length());
-}
-
-bool IsStringASCII(const StringPiece16& str) {
- return DoIsStringASCII(str.data(), str.length());
-}
-
-bool IsStringASCII(const string16& str) {
- return DoIsStringASCII(str.data(), str.length());
-}
-
-#if defined(WCHAR_T_IS_UTF32)
-bool IsStringASCII(const std::wstring& str) {
- return DoIsStringASCII(str.data(), str.length());
-}
-#endif
-
-bool IsStringUTF8(const StringPiece& str) {
- const char *src = str.data();
- int32_t src_len = static_cast<int32_t>(str.length());
- int32_t char_index = 0;
-
- while (char_index < src_len) {
- int32_t code_point;
- CBU8_NEXT(src, char_index, src_len, code_point);
- if (!IsValidCharacter(code_point))
- return false;
- }
- return true;
-}
-
-// Implementation note: Normally this function will be called with a hardcoded
-// constant for the lowercase_ascii parameter. Constructing a StringPiece from
-// a C constant requires running strlen, so the result will be two passes
-// through the buffers, one to file the length of lowercase_ascii, and one to
-// compare each letter.
-//
-// This function could have taken a const char* to avoid this and only do one
-// pass through the string. But the strlen is faster than the case-insensitive
-// compares and lets us early-exit in the case that the strings are different
-// lengths (will often be the case for non-matches). So whether one approach or
-// the other will be faster depends on the case.
-//
-// The hardcoded strings are typically very short so it doesn't matter, and the
-// string piece gives additional flexibility for the caller (doesn't have to be
-// null terminated) so we choose the StringPiece route.
-template<typename Str>
-static inline bool DoLowerCaseEqualsASCII(BasicStringPiece<Str> str,
- StringPiece lowercase_ascii) {
- if (str.size() != lowercase_ascii.size())
- return false;
- for (size_t i = 0; i < str.size(); i++) {
- if (ToLowerASCII(str[i]) != lowercase_ascii[i])
- return false;
- }
- return true;
-}
-
-bool LowerCaseEqualsASCII(StringPiece str, StringPiece lowercase_ascii) {
- return DoLowerCaseEqualsASCII<std::string>(str, lowercase_ascii);
-}
-
-bool LowerCaseEqualsASCII(StringPiece16 str, StringPiece lowercase_ascii) {
- return DoLowerCaseEqualsASCII<string16>(str, lowercase_ascii);
-}
-
-bool EqualsASCII(StringPiece16 str, StringPiece ascii) {
- if (str.length() != ascii.length())
- return false;
- return std::equal(ascii.begin(), ascii.end(), str.begin());
-}
-
-template<typename Str>
-bool StartsWithT(BasicStringPiece<Str> str,
- BasicStringPiece<Str> search_for,
- CompareCase case_sensitivity) {
- if (search_for.size() > str.size())
- return false;
-
- BasicStringPiece<Str> source = str.substr(0, search_for.size());
-
- switch (case_sensitivity) {
- case CompareCase::SENSITIVE:
- return source == search_for;
-
- case CompareCase::INSENSITIVE_ASCII:
- return std::equal(
- search_for.begin(), search_for.end(),
- source.begin(),
- CaseInsensitiveCompareASCII<typename Str::value_type>());
-
- default:
- NOTREACHED();
- return false;
- }
-}
-
-bool StartsWith(StringPiece str,
- StringPiece search_for,
- CompareCase case_sensitivity) {
- return StartsWithT<std::string>(str, search_for, case_sensitivity);
-}
-
-bool StartsWith(StringPiece16 str,
- StringPiece16 search_for,
- CompareCase case_sensitivity) {
- return StartsWithT<string16>(str, search_for, case_sensitivity);
-}
-
-template <typename Str>
-bool EndsWithT(BasicStringPiece<Str> str,
- BasicStringPiece<Str> search_for,
- CompareCase case_sensitivity) {
- if (search_for.size() > str.size())
- return false;
-
- BasicStringPiece<Str> source = str.substr(str.size() - search_for.size(),
- search_for.size());
-
- switch (case_sensitivity) {
- case CompareCase::SENSITIVE:
- return source == search_for;
-
- case CompareCase::INSENSITIVE_ASCII:
- return std::equal(
- source.begin(), source.end(),
- search_for.begin(),
- CaseInsensitiveCompareASCII<typename Str::value_type>());
-
- default:
- NOTREACHED();
- return false;
- }
-}
-
-bool EndsWith(StringPiece str,
- StringPiece search_for,
- CompareCase case_sensitivity) {
- return EndsWithT<std::string>(str, search_for, case_sensitivity);
-}
-
-bool EndsWith(StringPiece16 str,
- StringPiece16 search_for,
- CompareCase case_sensitivity) {
- return EndsWithT<string16>(str, search_for, case_sensitivity);
-}
-
-char HexDigitToInt(wchar_t c) {
- DCHECK(IsHexDigit(c));
- if (c >= '0' && c <= '9')
- return static_cast<char>(c - '0');
- if (c >= 'A' && c <= 'F')
- return static_cast<char>(c - 'A' + 10);
- if (c >= 'a' && c <= 'f')
- return static_cast<char>(c - 'a' + 10);
- return 0;
-}
-
-bool IsUnicodeWhitespace(wchar_t c) {
- // kWhitespaceWide is a NULL-terminated string
- for (const wchar_t* cur = kWhitespaceWide; *cur; ++cur) {
- if (*cur == c)
- return true;
- }
- return false;
-}
-
-static const char* const kByteStringsUnlocalized[] = {
- " B",
- " kB",
- " MB",
- " GB",
- " TB",
- " PB"
-};
-
-string16 FormatBytesUnlocalized(int64_t bytes) {
- double unit_amount = static_cast<double>(bytes);
- size_t dimension = 0;
- const int kKilo = 1024;
- while (unit_amount >= kKilo &&
- dimension < arraysize(kByteStringsUnlocalized) - 1) {
- unit_amount /= kKilo;
- dimension++;
- }
-
- char buf[64];
- if (bytes != 0 && dimension > 0 && unit_amount < 100) {
- base::snprintf(buf, arraysize(buf), "%.1lf%s", unit_amount,
- kByteStringsUnlocalized[dimension]);
- } else {
- base::snprintf(buf, arraysize(buf), "%.0lf%s", unit_amount,
- kByteStringsUnlocalized[dimension]);
- }
-
- return ASCIIToUTF16(buf);
-}
-
-// Runs in O(n) time in the length of |str|.
-template<class StringType>
-void DoReplaceSubstringsAfterOffset(StringType* str,
- size_t offset,
- BasicStringPiece<StringType> find_this,
- BasicStringPiece<StringType> replace_with,
- bool replace_all) {
- DCHECK(!find_this.empty());
-
- // If the find string doesn't appear, there's nothing to do.
- offset = str->find(find_this.data(), offset, find_this.size());
- if (offset == StringType::npos)
- return;
-
- // If we're only replacing one instance, there's no need to do anything
- // complicated.
- size_t find_length = find_this.length();
- if (!replace_all) {
- str->replace(offset, find_length, replace_with.data(), replace_with.size());
- return;
- }
-
- // If the find and replace strings are the same length, we can simply use
- // replace() on each instance, and finish the entire operation in O(n) time.
- size_t replace_length = replace_with.length();
- if (find_length == replace_length) {
- do {
- str->replace(offset, find_length,
- replace_with.data(), replace_with.size());
- offset = str->find(find_this.data(), offset + replace_length,
- find_this.size());
- } while (offset != StringType::npos);
- return;
- }
-
- // Since the find and replace strings aren't the same length, a loop like the
- // one above would be O(n^2) in the worst case, as replace() will shift the
- // entire remaining string each time. We need to be more clever to keep
- // things O(n).
- //
- // If we're shortening the string, we can alternate replacements with shifting
- // forward the intervening characters using memmove().
- size_t str_length = str->length();
- if (find_length > replace_length) {
- size_t write_offset = offset;
- do {
- if (replace_length) {
- str->replace(write_offset, replace_length,
- replace_with.data(), replace_with.size());
- write_offset += replace_length;
- }
- size_t read_offset = offset + find_length;
- offset = std::min(
- str->find(find_this.data(), read_offset, find_this.size()),
- str_length);
- size_t length = offset - read_offset;
- if (length) {
- memmove(&(*str)[write_offset], &(*str)[read_offset],
- length * sizeof(typename StringType::value_type));
- write_offset += length;
- }
- } while (offset < str_length);
- str->resize(write_offset);
- return;
- }
-
- // We're lengthening the string. We can use alternating replacements and
- // memmove() calls like above, but we need to precalculate the final string
- // length and then expand from back-to-front to avoid overwriting the string
- // as we're reading it, needing to shift, or having to copy to a second string
- // temporarily.
- size_t first_match = offset;
-
- // First, calculate the final length and resize the string.
- size_t final_length = str_length;
- size_t expansion = replace_length - find_length;
- size_t current_match;
- do {
- final_length += expansion;
- // Minor optimization: save this offset into |current_match|, so that on
- // exit from the loop, |current_match| will point at the last instance of
- // the find string, and we won't need to find() it again immediately.
- current_match = offset;
- offset = str->find(find_this.data(), offset + find_length,
- find_this.size());
- } while (offset != StringType::npos);
- str->resize(final_length);
-
- // Now do the replacement loop, working backwards through the string.
- for (size_t prev_match = str_length, write_offset = final_length; ;
- current_match = str->rfind(find_this.data(), current_match - 1,
- find_this.size())) {
- size_t read_offset = current_match + find_length;
- size_t length = prev_match - read_offset;
- if (length) {
- write_offset -= length;
- memmove(&(*str)[write_offset], &(*str)[read_offset],
- length * sizeof(typename StringType::value_type));
- }
- write_offset -= replace_length;
- str->replace(write_offset, replace_length,
- replace_with.data(), replace_with.size());
- if (current_match == first_match)
- return;
- prev_match = current_match;
- }
-}
-
-void ReplaceFirstSubstringAfterOffset(string16* str,
- size_t start_offset,
- StringPiece16 find_this,
- StringPiece16 replace_with) {
- DoReplaceSubstringsAfterOffset<string16>(
- str, start_offset, find_this, replace_with, false); // Replace first.
-}
-
-void ReplaceFirstSubstringAfterOffset(std::string* str,
- size_t start_offset,
- StringPiece find_this,
- StringPiece replace_with) {
- DoReplaceSubstringsAfterOffset<std::string>(
- str, start_offset, find_this, replace_with, false); // Replace first.
-}
-
-void ReplaceSubstringsAfterOffset(string16* str,
- size_t start_offset,
- StringPiece16 find_this,
- StringPiece16 replace_with) {
- DoReplaceSubstringsAfterOffset<string16>(
- str, start_offset, find_this, replace_with, true); // Replace all.
-}
-
-void ReplaceSubstringsAfterOffset(std::string* str,
- size_t start_offset,
- StringPiece find_this,
- StringPiece replace_with) {
- DoReplaceSubstringsAfterOffset<std::string>(
- str, start_offset, find_this, replace_with, true); // Replace all.
-}
-
-template <class string_type>
-inline typename string_type::value_type* WriteIntoT(string_type* str,
- size_t length_with_null) {
- DCHECK_GT(length_with_null, 1u);
- str->reserve(length_with_null);
- str->resize(length_with_null - 1);
- return &((*str)[0]);
-}
-
-char* WriteInto(std::string* str, size_t length_with_null) {
- return WriteIntoT(str, length_with_null);
-}
-
-char16* WriteInto(string16* str, size_t length_with_null) {
- return WriteIntoT(str, length_with_null);
-}
-
-template<typename STR>
-static STR JoinStringT(const std::vector<STR>& parts,
- BasicStringPiece<STR> sep) {
- if (parts.empty())
- return STR();
-
- STR result(parts[0]);
- auto iter = parts.begin();
- ++iter;
-
- for (; iter != parts.end(); ++iter) {
- sep.AppendToString(&result);
- result += *iter;
- }
-
- return result;
-}
-
-std::string JoinString(const std::vector<std::string>& parts,
- StringPiece separator) {
- return JoinStringT(parts, separator);
-}
-
-string16 JoinString(const std::vector<string16>& parts,
- StringPiece16 separator) {
- return JoinStringT(parts, separator);
-}
-
-template<class FormatStringType, class OutStringType>
-OutStringType DoReplaceStringPlaceholders(
- const FormatStringType& format_string,
- const std::vector<OutStringType>& subst,
- std::vector<size_t>* offsets) {
- size_t substitutions = subst.size();
-
- size_t sub_length = 0;
- for (const auto& cur : subst)
- sub_length += cur.length();
-
- OutStringType formatted;
- formatted.reserve(format_string.length() + sub_length);
-
- std::vector<ReplacementOffset> r_offsets;
- for (auto i = format_string.begin(); i != format_string.end(); ++i) {
- if ('$' == *i) {
- if (i + 1 != format_string.end()) {
- ++i;
- DCHECK('$' == *i || '1' <= *i) << "Invalid placeholder: " << *i;
- if ('$' == *i) {
- while (i != format_string.end() && '$' == *i) {
- formatted.push_back('$');
- ++i;
- }
- --i;
- } else {
- uintptr_t index = 0;
- while (i != format_string.end() && '0' <= *i && *i <= '9') {
- index *= 10;
- index += *i - '0';
- ++i;
- }
- --i;
- index -= 1;
- if (offsets) {
- ReplacementOffset r_offset(index,
- static_cast<int>(formatted.size()));
- r_offsets.insert(std::lower_bound(r_offsets.begin(),
- r_offsets.end(),
- r_offset,
- &CompareParameter),
- r_offset);
- }
- if (index < substitutions)
- formatted.append(subst.at(index));
- }
- }
- } else {
- formatted.push_back(*i);
- }
- }
- if (offsets) {
- for (const auto& cur : r_offsets)
- offsets->push_back(cur.offset);
- }
- return formatted;
-}
-
-string16 ReplaceStringPlaceholders(const string16& format_string,
- const std::vector<string16>& subst,
- std::vector<size_t>* offsets) {
- return DoReplaceStringPlaceholders(format_string, subst, offsets);
-}
-
-std::string ReplaceStringPlaceholders(const StringPiece& format_string,
- const std::vector<std::string>& subst,
- std::vector<size_t>* offsets) {
- return DoReplaceStringPlaceholders(format_string, subst, offsets);
-}
-
-string16 ReplaceStringPlaceholders(const string16& format_string,
- const string16& a,
- size_t* offset) {
- std::vector<size_t> offsets;
- std::vector<string16> subst;
- subst.push_back(a);
- string16 result = ReplaceStringPlaceholders(format_string, subst, &offsets);
-
- DCHECK_EQ(1U, offsets.size());
- if (offset)
- *offset = offsets[0];
- 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 strlcpy(char* dst, const char* src, size_t dst_size) {
- return lcpyT<char>(dst, src, dst_size);
-}
-size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size) {
- return lcpyT<wchar_t>(dst, src, dst_size);
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/string_util.h b/security/sandbox/chromium/base/strings/string_util.h
deleted file mode 100644
index e369f294d..000000000
--- a/security/sandbox/chromium/base/strings/string_util.h
+++ /dev/null
@@ -1,461 +0,0 @@
-// Copyright 2013 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_STRINGS_STRING_UTIL_H_
-#define BASE_STRINGS_STRING_UTIL_H_
-
-#include <ctype.h>
-#include <stdarg.h> // va_list
-#include <stddef.h>
-#include <stdint.h>
-
-#include <string>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_piece.h" // For implicit conversions.
-#include "build/build_config.h"
-
-namespace base {
-
-// C standard-library functions that aren't cross-platform are provided as
-// "base::...", and their prototypes are listed below. These functions are
-// then implemented as inline calls to the platform-specific equivalents in the
-// platform-specific headers.
-
-// 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)
- PRINTF_FORMAT(3, 0);
-
-// Some of these implementations need to be inlined.
-
-// We separate the declaration from the implementation of this inline
-// function just so the PRINTF_FORMAT works.
-inline int snprintf(char* buffer,
- size_t size,
- _Printf_format_string_ const char* format,
- ...) PRINTF_FORMAT(3, 4);
-inline int snprintf(char* buffer,
- size_t size,
- _Printf_format_string_ const char* format,
- ...) {
- va_list arguments;
- va_start(arguments, format);
- int result = vsnprintf(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.
-BASE_EXPORT size_t strlcpy(char* dst, const char* src, size_t dst_size);
-BASE_EXPORT 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.
-BASE_EXPORT bool IsWprintfFormatPortable(const wchar_t* format);
-
-// ASCII-specific tolower. The standard library's tolower is locale sensitive,
-// so we don't want to use it here.
-inline char ToLowerASCII(char c) {
- return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
-}
-inline char16 ToLowerASCII(char16 c) {
- return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
-}
-
-// ASCII-specific toupper. The standard library's toupper is locale sensitive,
-// so we don't want to use it here.
-inline char ToUpperASCII(char c) {
- return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c;
-}
-inline char16 ToUpperASCII(char16 c) {
- return (c >= 'a' && c <= 'z') ? (c + ('A' - 'a')) : c;
-}
-
-// Converts the given string to it's ASCII-lowercase equivalent.
-BASE_EXPORT std::string ToLowerASCII(StringPiece str);
-BASE_EXPORT string16 ToLowerASCII(StringPiece16 str);
-
-// Converts the given string to it's ASCII-uppercase equivalent.
-BASE_EXPORT std::string ToUpperASCII(StringPiece str);
-BASE_EXPORT string16 ToUpperASCII(StringPiece16 str);
-
-// Functor for case-insensitive ASCII comparisons for STL algorithms like
-// std::search.
-//
-// Note that a full Unicode version of this functor is not possible to write
-// because case mappings might change the number of characters, depend on
-// context (combining accents), and require handling UTF-16. If you need
-// proper Unicode support, use base::i18n::ToLower/FoldCase and then just
-// use a normal operator== on the result.
-template<typename Char> struct CaseInsensitiveCompareASCII {
- public:
- bool operator()(Char x, Char y) const {
- return ToLowerASCII(x) == ToLowerASCII(y);
- }
-};
-
-// Like strcasecmp for case-insensitive ASCII characters only. Returns:
-// -1 (a < b)
-// 0 (a == b)
-// 1 (a > b)
-// (unlike strcasecmp which can return values greater or less than 1/-1). For
-// full Unicode support, use base::i18n::ToLower or base::i18h::FoldCase
-// and then just call the normal string operators on the result.
-BASE_EXPORT int CompareCaseInsensitiveASCII(StringPiece a, StringPiece b);
-BASE_EXPORT int CompareCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b);
-
-// Equality for ASCII case-insensitive comparisons. For full Unicode support,
-// use base::i18n::ToLower or base::i18h::FoldCase and then compare with either
-// == or !=.
-BASE_EXPORT bool EqualsCaseInsensitiveASCII(StringPiece a, StringPiece b);
-BASE_EXPORT bool EqualsCaseInsensitiveASCII(StringPiece16 a, StringPiece16 b);
-
-// These threadsafe functions return references to globally unique empty
-// strings.
-//
-// It is likely faster to construct a new empty string object (just a few
-// instructions to set the length to 0) than to get the empty string singleton
-// returned by these functions (which requires threadsafe singleton access).
-//
-// Therefore, DO NOT USE THESE AS A GENERAL-PURPOSE SUBSTITUTE FOR DEFAULT
-// CONSTRUCTORS. There is only one case where you should use these: functions
-// which need to return a string by reference (e.g. as a class member
-// accessor), and don't have an empty string to use (e.g. in an error case).
-// These should not be used as initializers, function arguments, or return
-// values for functions which return by value or outparam.
-BASE_EXPORT const std::string& EmptyString();
-BASE_EXPORT const string16& EmptyString16();
-
-// Contains the set of characters representing whitespace in the corresponding
-// encoding. Null-terminated. The ASCII versions are the whitespaces as defined
-// by HTML5, and don't include control characters.
-BASE_EXPORT extern const wchar_t kWhitespaceWide[]; // Includes Unicode.
-BASE_EXPORT extern const char16 kWhitespaceUTF16[]; // Includes Unicode.
-BASE_EXPORT extern const char kWhitespaceASCII[];
-BASE_EXPORT extern const char16 kWhitespaceASCIIAs16[]; // No unicode.
-
-// Null-terminated string representing the UTF-8 byte order mark.
-BASE_EXPORT extern const char kUtf8ByteOrderMark[];
-
-// Removes characters in |remove_chars| from anywhere in |input|. Returns true
-// if any characters were removed. |remove_chars| must be null-terminated.
-// NOTE: Safe to use the same variable for both |input| and |output|.
-BASE_EXPORT bool RemoveChars(const string16& input,
- const StringPiece16& remove_chars,
- string16* output);
-BASE_EXPORT bool RemoveChars(const std::string& input,
- const StringPiece& remove_chars,
- std::string* output);
-
-// Replaces characters in |replace_chars| from anywhere in |input| with
-// |replace_with|. Each character in |replace_chars| will be replaced with
-// the |replace_with| string. Returns true if any characters were replaced.
-// |replace_chars| must be null-terminated.
-// NOTE: Safe to use the same variable for both |input| and |output|.
-BASE_EXPORT bool ReplaceChars(const string16& input,
- const StringPiece16& replace_chars,
- const string16& replace_with,
- string16* output);
-BASE_EXPORT bool ReplaceChars(const std::string& input,
- const StringPiece& replace_chars,
- const std::string& replace_with,
- std::string* output);
-
-enum TrimPositions {
- TRIM_NONE = 0,
- TRIM_LEADING = 1 << 0,
- TRIM_TRAILING = 1 << 1,
- TRIM_ALL = TRIM_LEADING | TRIM_TRAILING,
-};
-
-// Removes characters in |trim_chars| from the beginning and end of |input|.
-// The 8-bit version only works on 8-bit characters, not UTF-8.
-//
-// It is safe to use the same variable for both |input| and |output| (this is
-// the normal usage to trim in-place).
-BASE_EXPORT bool TrimString(const string16& input,
- StringPiece16 trim_chars,
- string16* output);
-BASE_EXPORT bool TrimString(const std::string& input,
- StringPiece trim_chars,
- std::string* output);
-
-// StringPiece versions of the above. The returned pieces refer to the original
-// buffer.
-BASE_EXPORT StringPiece16 TrimString(StringPiece16 input,
- const StringPiece16& trim_chars,
- TrimPositions positions);
-BASE_EXPORT StringPiece TrimString(StringPiece input,
- const StringPiece& trim_chars,
- TrimPositions positions);
-
-// Truncates a string to the nearest UTF-8 character that will leave
-// the string less than or equal to the specified byte size.
-BASE_EXPORT void TruncateUTF8ToByteSize(const std::string& input,
- const size_t byte_size,
- std::string* output);
-
-// Trims any whitespace from either end of the input string.
-//
-// The StringPiece versions return a substring referencing the input buffer.
-// The ASCII versions look only for ASCII whitespace.
-//
-// The std::string versions return where whitespace was found.
-// NOTE: Safe to use the same variable for both input and output.
-BASE_EXPORT TrimPositions TrimWhitespace(const string16& input,
- TrimPositions positions,
- string16* output);
-BASE_EXPORT StringPiece16 TrimWhitespace(StringPiece16 input,
- TrimPositions positions);
-BASE_EXPORT TrimPositions TrimWhitespaceASCII(const std::string& input,
- TrimPositions positions,
- std::string* output);
-BASE_EXPORT StringPiece TrimWhitespaceASCII(StringPiece input,
- TrimPositions positions);
-
-// 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.
-BASE_EXPORT string16 CollapseWhitespace(
- const string16& text,
- bool trim_sequences_with_line_breaks);
-BASE_EXPORT std::string CollapseWhitespaceASCII(
- const std::string& text,
- bool trim_sequences_with_line_breaks);
-
-// Returns true if |input| is empty or contains only characters found in
-// |characters|.
-BASE_EXPORT bool ContainsOnlyChars(const StringPiece& input,
- const StringPiece& characters);
-BASE_EXPORT bool ContainsOnlyChars(const StringPiece16& input,
- const StringPiece16& characters);
-
-// Returns true if the specified string matches the criteria. How can a wide
-// string be 8-bit or UTF8? It contains only characters that are < 256 (in the
-// first case) or characters that use only 8-bits and whose 8-bit
-// representation looks like a UTF-8 string (the second case).
-//
-// Note that IsStringUTF8 checks not only if the input is structurally
-// valid but also if it doesn't contain any non-character codepoint
-// (e.g. U+FFFE). It's done on purpose because all the existing callers want
-// to have the maximum 'discriminating' power from other encodings. If
-// there's a use case for just checking the structural validity, we have to
-// add a new function for that.
-//
-// IsStringASCII assumes the input is likely all ASCII, and does not leave early
-// if it is not the case.
-BASE_EXPORT bool IsStringUTF8(const StringPiece& str);
-BASE_EXPORT bool IsStringASCII(const StringPiece& str);
-BASE_EXPORT bool IsStringASCII(const StringPiece16& str);
-// A convenience adaptor for WebStrings, as they don't convert into
-// StringPieces directly.
-BASE_EXPORT bool IsStringASCII(const string16& str);
-#if defined(WCHAR_T_IS_UTF32)
-BASE_EXPORT bool IsStringASCII(const std::wstring& str);
-#endif
-
-// Compare the lower-case form of the given string against the given
-// previously-lower-cased ASCII string (typically a constant).
-BASE_EXPORT bool LowerCaseEqualsASCII(StringPiece str,
- StringPiece lowecase_ascii);
-BASE_EXPORT bool LowerCaseEqualsASCII(StringPiece16 str,
- StringPiece lowecase_ascii);
-
-// Performs a case-sensitive string compare of the given 16-bit string against
-// the given 8-bit ASCII string (typically a constant). The behavior is
-// undefined if the |ascii| string is not ASCII.
-BASE_EXPORT bool EqualsASCII(StringPiece16 str, StringPiece ascii);
-
-// Indicates case sensitivity of comparisons. Only ASCII case insensitivity
-// is supported. Full Unicode case-insensitive conversions would need to go in
-// base/i18n so it can use ICU.
-//
-// If you need to do Unicode-aware case-insensitive StartsWith/EndsWith, it's
-// best to call base::i18n::ToLower() or base::i18n::FoldCase() (see
-// base/i18n/case_conversion.h for usage advice) on the arguments, and then use
-// the results to a case-sensitive comparison.
-enum class CompareCase {
- SENSITIVE,
- INSENSITIVE_ASCII,
-};
-
-BASE_EXPORT bool StartsWith(StringPiece str,
- StringPiece search_for,
- CompareCase case_sensitivity);
-BASE_EXPORT bool StartsWith(StringPiece16 str,
- StringPiece16 search_for,
- CompareCase case_sensitivity);
-BASE_EXPORT bool EndsWith(StringPiece str,
- StringPiece search_for,
- CompareCase case_sensitivity);
-BASE_EXPORT bool EndsWith(StringPiece16 str,
- StringPiece16 search_for,
- CompareCase case_sensitivity);
-
-// Determines the type of ASCII character, independent of locale (the C
-// library versions will change based on locale).
-template <typename Char>
-inline bool IsAsciiWhitespace(Char c) {
- return c == ' ' || c == '\r' || c == '\n' || c == '\t';
-}
-template <typename Char>
-inline bool IsAsciiAlpha(Char c) {
- return ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z'));
-}
-template <typename Char>
-inline bool IsAsciiDigit(Char c) {
- return c >= '0' && c <= '9';
-}
-
-template <typename Char>
-inline bool IsHexDigit(Char c) {
- return (c >= '0' && c <= '9') ||
- (c >= 'A' && c <= 'F') ||
- (c >= 'a' && c <= 'f');
-}
-
-// Returns the integer corresponding to the given hex character. For example:
-// '4' -> 4
-// 'a' -> 10
-// 'B' -> 11
-// Assumes the input is a valid hex character. DCHECKs in debug builds if not.
-BASE_EXPORT char HexDigitToInt(wchar_t c);
-
-// Returns true if it's a Unicode whitespace character.
-BASE_EXPORT bool IsUnicodeWhitespace(wchar_t c);
-
-// Return a byte string in human-readable format with a unit suffix. Not
-// appropriate for use in any UI; use of FormatBytes and friends in ui/base is
-// highly recommended instead. TODO(avi): Figure out how to get callers to use
-// FormatBytes instead; remove this.
-BASE_EXPORT string16 FormatBytesUnlocalized(int64_t bytes);
-
-// Starting at |start_offset| (usually 0), replace the first instance of
-// |find_this| with |replace_with|.
-BASE_EXPORT void ReplaceFirstSubstringAfterOffset(
- base::string16* str,
- size_t start_offset,
- StringPiece16 find_this,
- StringPiece16 replace_with);
-BASE_EXPORT void ReplaceFirstSubstringAfterOffset(
- std::string* str,
- size_t start_offset,
- StringPiece find_this,
- StringPiece replace_with);
-
-// Starting at |start_offset| (usually 0), look through |str| and replace all
-// instances of |find_this| with |replace_with|.
-//
-// This does entire substrings; use std::replace in <algorithm> for single
-// characters, for example:
-// std::replace(str.begin(), str.end(), 'a', 'b');
-BASE_EXPORT void ReplaceSubstringsAfterOffset(
- string16* str,
- size_t start_offset,
- StringPiece16 find_this,
- StringPiece16 replace_with);
-BASE_EXPORT void ReplaceSubstringsAfterOffset(
- std::string* str,
- size_t start_offset,
- StringPiece find_this,
- StringPiece replace_with);
-
-// Reserves enough memory in |str| to accommodate |length_with_null| characters,
-// sets the size of |str| to |length_with_null - 1| characters, and returns a
-// pointer to the underlying contiguous array of characters. This is typically
-// used when calling a function that writes results into a character array, but
-// the caller wants the data to be managed by a string-like object. It is
-// convenient in that is can be used inline in the call, and fast in that it
-// avoids copying the results of the call from a char* into a string.
-//
-// |length_with_null| must be at least 2, since otherwise the underlying string
-// would have size 0, and trying to access &((*str)[0]) in that case can result
-// in a number of problems.
-//
-// Internally, this takes linear time because the resize() call 0-fills the
-// underlying array for potentially all
-// (|length_with_null - 1| * sizeof(string_type::value_type)) bytes. Ideally we
-// could avoid this aspect of the resize() call, as we expect the caller to
-// immediately write over this memory, but there is no other way to set the size
-// of the string, and not doing that will mean people who access |str| rather
-// than str.c_str() will get back a string of whatever size |str| had on entry
-// to this function (probably 0).
-BASE_EXPORT char* WriteInto(std::string* str, size_t length_with_null);
-BASE_EXPORT char16* WriteInto(string16* str, size_t length_with_null);
-#ifndef OS_WIN
-BASE_EXPORT wchar_t* WriteInto(std::wstring* str, size_t length_with_null);
-#endif
-
-// Does the opposite of SplitString().
-BASE_EXPORT std::string JoinString(const std::vector<std::string>& parts,
- StringPiece separator);
-BASE_EXPORT string16 JoinString(const std::vector<string16>& parts,
- StringPiece16 separator);
-
-// Replace $1-$2-$3..$9 in the format string with |a|-|b|-|c|..|i| respectively.
-// Additionally, any number of consecutive '$' characters is replaced by that
-// number less one. Eg $$->$, $$$->$$, etc. The offsets parameter here can be
-// NULL. This only allows you to use up to nine replacements.
-BASE_EXPORT string16 ReplaceStringPlaceholders(
- const string16& format_string,
- const std::vector<string16>& subst,
- std::vector<size_t>* offsets);
-
-BASE_EXPORT std::string ReplaceStringPlaceholders(
- const StringPiece& format_string,
- const std::vector<std::string>& subst,
- std::vector<size_t>* offsets);
-
-// Single-string shortcut for ReplaceStringHolders. |offset| may be NULL.
-BASE_EXPORT string16 ReplaceStringPlaceholders(const string16& format_string,
- const string16& a,
- size_t* offset);
-
-} // namespace base
-
-#if defined(OS_WIN)
-#include "base/strings/string_util_win.h"
-#elif defined(OS_POSIX)
-#include "base/strings/string_util_posix.h"
-#else
-#error Define string operations appropriately for your platform
-#endif
-
-#endif // BASE_STRINGS_STRING_UTIL_H_
diff --git a/security/sandbox/chromium/base/strings/string_util_constants.cc b/security/sandbox/chromium/base/strings/string_util_constants.cc
deleted file mode 100644
index aba1b12b8..000000000
--- a/security/sandbox/chromium/base/strings/string_util_constants.cc
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2013 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/strings/string_util.h"
-
-namespace base {
-
-#define WHITESPACE_UNICODE \
- 0x0009, /* CHARACTER TABULATION */ \
- 0x000A, /* LINE FEED (LF) */ \
- 0x000B, /* LINE TABULATION */ \
- 0x000C, /* FORM FEED (FF) */ \
- 0x000D, /* CARRIAGE RETURN (CR) */ \
- 0x0020, /* SPACE */ \
- 0x0085, /* NEXT LINE (NEL) */ \
- 0x00A0, /* NO-BREAK SPACE */ \
- 0x1680, /* OGHAM SPACE MARK */ \
- 0x2000, /* EN QUAD */ \
- 0x2001, /* EM QUAD */ \
- 0x2002, /* EN SPACE */ \
- 0x2003, /* EM SPACE */ \
- 0x2004, /* THREE-PER-EM SPACE */ \
- 0x2005, /* FOUR-PER-EM SPACE */ \
- 0x2006, /* SIX-PER-EM SPACE */ \
- 0x2007, /* FIGURE SPACE */ \
- 0x2008, /* PUNCTUATION SPACE */ \
- 0x2009, /* THIN SPACE */ \
- 0x200A, /* HAIR SPACE */ \
- 0x2028, /* LINE SEPARATOR */ \
- 0x2029, /* PARAGRAPH SEPARATOR */ \
- 0x202F, /* NARROW NO-BREAK SPACE */ \
- 0x205F, /* MEDIUM MATHEMATICAL SPACE */ \
- 0x3000, /* IDEOGRAPHIC SPACE */ \
- 0
-
-const wchar_t kWhitespaceWide[] = {
- WHITESPACE_UNICODE
-};
-
-const char16 kWhitespaceUTF16[] = {
- WHITESPACE_UNICODE
-};
-
-const char kWhitespaceASCII[] = {
- 0x09, // CHARACTER TABULATION
- 0x0A, // LINE FEED (LF)
- 0x0B, // LINE TABULATION
- 0x0C, // FORM FEED (FF)
- 0x0D, // CARRIAGE RETURN (CR)
- 0x20, // SPACE
- 0
-};
-
-const char16 kWhitespaceASCIIAs16[] = {
- 0x09, // CHARACTER TABULATION
- 0x0A, // LINE FEED (LF)
- 0x0B, // LINE TABULATION
- 0x0C, // FORM FEED (FF)
- 0x0D, // CARRIAGE RETURN (CR)
- 0x20, // SPACE
- 0
-};
-
-const char kUtf8ByteOrderMark[] = "\xEF\xBB\xBF";
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/string_util_posix.h b/security/sandbox/chromium/base/strings/string_util_posix.h
deleted file mode 100644
index 8299118e1..000000000
--- a/security/sandbox/chromium/base/strings/string_util_posix.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2013 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_STRINGS_STRING_UTIL_POSIX_H_
-#define BASE_STRINGS_STRING_UTIL_POSIX_H_
-
-#include <stdarg.h>
-#include <stddef.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) {
- 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_STRINGS_STRING_UTIL_POSIX_H_
diff --git a/security/sandbox/chromium/base/strings/string_util_win.h b/security/sandbox/chromium/base/strings/string_util_win.h
deleted file mode 100644
index 7f260bfc8..000000000
--- a/security/sandbox/chromium/base/strings/string_util_win.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// Copyright 2013 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_STRINGS_STRING_UTIL_WIN_H_
-#define BASE_STRINGS_STRING_UTIL_WIN_H_
-
-#include <stdarg.h>
-#include <stddef.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_STRINGS_STRING_UTIL_WIN_H_
diff --git a/security/sandbox/chromium/base/strings/stringprintf.cc b/security/sandbox/chromium/base/strings/stringprintf.cc
deleted file mode 100644
index 415845d61..000000000
--- a/security/sandbox/chromium/base/strings/stringprintf.cc
+++ /dev/null
@@ -1,189 +0,0 @@
-// Copyright 2013 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/strings/stringprintf.h"
-
-#include <errno.h>
-#include <stddef.h>
-
-#include <vector>
-
-#include "base/macros.h"
-#include "base/scoped_clear_errno.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "build/build_config.h"
-
-namespace base {
-
-namespace {
-
-// 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);
-}
-
-#if defined(OS_WIN)
-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);
-}
-#endif
-
-// 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 ap_copy;
- va_copy(ap_copy, ap);
-
-#if !defined(OS_WIN)
- ScopedClearErrno clear_errno;
-#endif
- int result = vsnprintfT(stack_buf, arraysize(stack_buf), format, ap_copy);
- va_end(ap_copy);
-
- 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(OS_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.
- return;
-#else
- if (errno != 0 && errno != EOVERFLOW)
- return;
- // Try doubling the buffer size.
- mem_length *= 2;
-#endif
- } 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);
-
- // NOTE: You can only use a va_list once. Since we're in a while loop, we
- // need to make a new copy each time so we don't use up the original.
- va_copy(ap_copy, ap);
- result = vsnprintfT(&mem_buf[0], mem_length, format, ap_copy);
- va_end(ap_copy);
-
- if ((result >= 0) && (result < mem_length)) {
- // It fit.
- dst->append(&mem_buf[0], result);
- return;
- }
- }
-}
-
-} // namespace
-
-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;
-}
-
-#if defined(OS_WIN)
-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;
-}
-#endif
-
-std::string StringPrintV(const char* format, va_list ap) {
- std::string result;
- StringAppendV(&result, format, 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;
-}
-
-#if defined(OS_WIN)
-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;
-}
-#endif
-
-void StringAppendF(std::string* dst, const char* format, ...) {
- va_list ap;
- va_start(ap, format);
- StringAppendV(dst, format, ap);
- va_end(ap);
-}
-
-#if defined(OS_WIN)
-void StringAppendF(std::wstring* dst, const wchar_t* format, ...) {
- va_list ap;
- va_start(ap, format);
- StringAppendV(dst, format, ap);
- va_end(ap);
-}
-#endif
-
-void StringAppendV(std::string* dst, const char* format, va_list ap) {
- StringAppendVT(dst, format, ap);
-}
-
-#if defined(OS_WIN)
-void StringAppendV(std::wstring* dst, const wchar_t* format, va_list ap) {
- StringAppendVT(dst, format, ap);
-}
-#endif
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/stringprintf.h b/security/sandbox/chromium/base/strings/stringprintf.h
deleted file mode 100644
index 7a75d89e1..000000000
--- a/security/sandbox/chromium/base/strings/stringprintf.h
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright 2013 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_STRINGS_STRINGPRINTF_H_
-#define BASE_STRINGS_STRINGPRINTF_H_
-
-#include <stdarg.h> // va_list
-
-#include <string>
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "build/build_config.h"
-
-namespace base {
-
-// Return a C++ string given printf-like input.
-BASE_EXPORT std::string StringPrintf(_Printf_format_string_ const char* format,
- ...)
- PRINTF_FORMAT(1, 2) WARN_UNUSED_RESULT;
-#if defined(OS_WIN)
-BASE_EXPORT std::wstring StringPrintf(
- _Printf_format_string_ const wchar_t* format,
- ...) WPRINTF_FORMAT(1, 2) WARN_UNUSED_RESULT;
-#endif
-
-// Return a C++ string given vprintf-like input.
-BASE_EXPORT std::string StringPrintV(const char* format, va_list ap)
- PRINTF_FORMAT(1, 0) WARN_UNUSED_RESULT;
-
-// Store result into a supplied string and return it.
-BASE_EXPORT const std::string& SStringPrintf(
- std::string* dst,
- _Printf_format_string_ const char* format,
- ...) PRINTF_FORMAT(2, 3);
-#if defined(OS_WIN)
-BASE_EXPORT const std::wstring& SStringPrintf(
- std::wstring* dst,
- _Printf_format_string_ const wchar_t* format,
- ...) WPRINTF_FORMAT(2, 3);
-#endif
-
-// Append result to a supplied string.
-BASE_EXPORT void StringAppendF(std::string* dst,
- _Printf_format_string_ const char* format,
- ...) PRINTF_FORMAT(2, 3);
-#if defined(OS_WIN)
-BASE_EXPORT void StringAppendF(std::wstring* dst,
- _Printf_format_string_ const wchar_t* format,
- ...) WPRINTF_FORMAT(2, 3);
-#endif
-
-// Lower-level routine that takes a va_list and appends to a specified
-// string. All other routines are just convenience wrappers around it.
-BASE_EXPORT void StringAppendV(std::string* dst, const char* format, va_list ap)
- PRINTF_FORMAT(2, 0);
-#if defined(OS_WIN)
-BASE_EXPORT void StringAppendV(std::wstring* dst,
- const wchar_t* format, va_list ap)
- WPRINTF_FORMAT(2, 0);
-#endif
-
-} // namespace base
-
-#endif // BASE_STRINGS_STRINGPRINTF_H_
diff --git a/security/sandbox/chromium/base/strings/utf_string_conversion_utils.cc b/security/sandbox/chromium/base/strings/utf_string_conversion_utils.cc
deleted file mode 100644
index 3101a6028..000000000
--- a/security/sandbox/chromium/base/strings/utf_string_conversion_utils.cc
+++ /dev/null
@@ -1,148 +0,0 @@
-// 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/strings/utf_string_conversion_utils.h"
-
-#include "base/third_party/icu/icu_utf.h"
-
-namespace base {
-
-// ReadUnicodeCharacter --------------------------------------------------------
-
-bool ReadUnicodeCharacter(const char* src,
- int32_t src_len,
- int32_t* char_index,
- uint32_t* code_point_out) {
- // U8_NEXT expects to be able to use -1 to signal an error, so we must
- // use a signed type for code_point. But this function returns false
- // on error anyway, so code_point_out is unsigned.
- int32_t code_point;
- CBU8_NEXT(src, *char_index, src_len, code_point);
- *code_point_out = static_cast<uint32_t>(code_point);
-
- // The ICU macro above moves to the next char, we want to point to the last
- // char consumed.
- (*char_index)--;
-
- // Validate the decoded value.
- return IsValidCodepoint(code_point);
-}
-
-bool ReadUnicodeCharacter(const char16* src,
- int32_t src_len,
- int32_t* char_index,
- uint32_t* code_point) {
- if (CBU16_IS_SURROGATE(src[*char_index])) {
- if (!CBU16_IS_SURROGATE_LEAD(src[*char_index]) ||
- *char_index + 1 >= src_len ||
- !CBU16_IS_TRAIL(src[*char_index + 1])) {
- // Invalid surrogate pair.
- return false;
- }
-
- // Valid surrogate pair.
- *code_point = CBU16_GET_SUPPLEMENTARY(src[*char_index],
- src[*char_index + 1]);
- (*char_index)++;
- } else {
- // Not a surrogate, just one 16-bit word.
- *code_point = src[*char_index];
- }
-
- return IsValidCodepoint(*code_point);
-}
-
-#if defined(WCHAR_T_IS_UTF32)
-bool ReadUnicodeCharacter(const wchar_t* src,
- int32_t src_len,
- int32_t* char_index,
- uint32_t* code_point) {
- // Conversion is easy since the source is 32-bit.
- *code_point = src[*char_index];
-
- // Validate the value.
- return IsValidCodepoint(*code_point);
-}
-#endif // defined(WCHAR_T_IS_UTF32)
-
-// WriteUnicodeCharacter -------------------------------------------------------
-
-size_t WriteUnicodeCharacter(uint32_t code_point, std::string* output) {
- if (code_point <= 0x7f) {
- // Fast path the common case of one byte.
- output->push_back(static_cast<char>(code_point));
- return 1;
- }
-
-
- // CBU8_APPEND_UNSAFE can append up to 4 bytes.
- size_t char_offset = output->length();
- size_t original_char_offset = char_offset;
- output->resize(char_offset + CBU8_MAX_LENGTH);
-
- CBU8_APPEND_UNSAFE(&(*output)[0], char_offset, code_point);
-
- // CBU8_APPEND_UNSAFE will advance our pointer past the inserted character, so
- // it will represent the new length of the string.
- output->resize(char_offset);
- return char_offset - original_char_offset;
-}
-
-size_t WriteUnicodeCharacter(uint32_t code_point, string16* output) {
- if (CBU16_LENGTH(code_point) == 1) {
- // Thie code point is in the Basic Multilingual Plane (BMP).
- output->push_back(static_cast<char16>(code_point));
- return 1;
- }
- // Non-BMP characters use a double-character encoding.
- size_t char_offset = output->length();
- output->resize(char_offset + CBU16_MAX_LENGTH);
- CBU16_APPEND_UNSAFE(&(*output)[0], char_offset, code_point);
- return CBU16_MAX_LENGTH;
-}
-
-// Generalized Unicode converter -----------------------------------------------
-
-template<typename CHAR>
-void PrepareForUTF8Output(const CHAR* src,
- size_t src_len,
- std::string* output) {
- output->clear();
- if (src_len == 0)
- return;
- if (src[0] < 0x80) {
- // Assume that the entire input will be ASCII.
- output->reserve(src_len);
- } else {
- // Assume that the entire input is non-ASCII and will have 3 bytes per char.
- output->reserve(src_len * 3);
- }
-}
-
-// Instantiate versions we know callers will need.
-template void PrepareForUTF8Output(const wchar_t*, size_t, std::string*);
-template void PrepareForUTF8Output(const char16*, size_t, std::string*);
-
-template<typename STRING>
-void PrepareForUTF16Or32Output(const char* src,
- size_t src_len,
- STRING* output) {
- output->clear();
- if (src_len == 0)
- return;
- if (static_cast<unsigned char>(src[0]) < 0x80) {
- // Assume the input is all ASCII, which means 1:1 correspondence.
- output->reserve(src_len);
- } else {
- // Otherwise assume that the UTF-8 sequences will have 2 bytes for each
- // character.
- output->reserve(src_len / 2);
- }
-}
-
-// Instantiate versions we know callers will need.
-template void PrepareForUTF16Or32Output(const char*, size_t, std::wstring*);
-template void PrepareForUTF16Or32Output(const char*, size_t, string16*);
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/utf_string_conversion_utils.h b/security/sandbox/chromium/base/strings/utf_string_conversion_utils.h
deleted file mode 100644
index c71640453..000000000
--- a/security/sandbox/chromium/base/strings/utf_string_conversion_utils.h
+++ /dev/null
@@ -1,99 +0,0 @@
-// 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_STRINGS_UTF_STRING_CONVERSION_UTILS_H_
-#define BASE_STRINGS_UTF_STRING_CONVERSION_UTILS_H_
-
-// This should only be used by the various UTF string conversion files.
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/base_export.h"
-#include "base/strings/string16.h"
-
-namespace base {
-
-inline bool IsValidCodepoint(uint32_t code_point) {
- // Excludes the surrogate code points ([0xD800, 0xDFFF]) and
- // codepoints larger than 0x10FFFF (the highest codepoint allowed).
- // Non-characters and unassigned codepoints are allowed.
- return code_point < 0xD800u ||
- (code_point >= 0xE000u && code_point <= 0x10FFFFu);
-}
-
-inline bool IsValidCharacter(uint32_t code_point) {
- // Excludes non-characters (U+FDD0..U+FDEF, and all codepoints ending in
- // 0xFFFE or 0xFFFF) from the set of valid code points.
- return code_point < 0xD800u || (code_point >= 0xE000u &&
- code_point < 0xFDD0u) || (code_point > 0xFDEFu &&
- code_point <= 0x10FFFFu && (code_point & 0xFFFEu) != 0xFFFEu);
-}
-
-// ReadUnicodeCharacter --------------------------------------------------------
-
-// Reads a UTF-8 stream, placing the next code point into the given output
-// |*code_point|. |src| represents the entire string to read, and |*char_index|
-// is the character offset within the string to start reading at. |*char_index|
-// will be updated to index the last character read, such that incrementing it
-// (as in a for loop) will take the reader to the next character.
-//
-// Returns true on success. On false, |*code_point| will be invalid.
-BASE_EXPORT bool ReadUnicodeCharacter(const char* src,
- int32_t src_len,
- int32_t* char_index,
- uint32_t* code_point_out);
-
-// Reads a UTF-16 character. The usage is the same as the 8-bit version above.
-BASE_EXPORT bool ReadUnicodeCharacter(const char16* src,
- int32_t src_len,
- int32_t* char_index,
- uint32_t* code_point);
-
-#if defined(WCHAR_T_IS_UTF32)
-// Reads UTF-32 character. The usage is the same as the 8-bit version above.
-BASE_EXPORT bool ReadUnicodeCharacter(const wchar_t* src,
- int32_t src_len,
- int32_t* char_index,
- uint32_t* code_point);
-#endif // defined(WCHAR_T_IS_UTF32)
-
-// WriteUnicodeCharacter -------------------------------------------------------
-
-// Appends a UTF-8 character to the given 8-bit string. Returns the number of
-// bytes written.
-BASE_EXPORT size_t WriteUnicodeCharacter(uint32_t code_point,
- std::string* output);
-
-// Appends the given code point as a UTF-16 character to the given 16-bit
-// string. Returns the number of 16-bit values written.
-BASE_EXPORT size_t WriteUnicodeCharacter(uint32_t code_point, string16* output);
-
-#if defined(WCHAR_T_IS_UTF32)
-// Appends the given UTF-32 character to the given 32-bit string. Returns the
-// number of 32-bit values written.
-inline size_t WriteUnicodeCharacter(uint32_t code_point, std::wstring* output) {
- // This is the easy case, just append the character.
- output->push_back(code_point);
- return 1;
-}
-#endif // defined(WCHAR_T_IS_UTF32)
-
-// Generalized Unicode converter -----------------------------------------------
-
-// Guesses the length of the output in UTF-8 in bytes, clears that output
-// string, and reserves that amount of space. We assume that the input
-// character types are unsigned, which will be true for UTF-16 and -32 on our
-// systems.
-template<typename CHAR>
-void PrepareForUTF8Output(const CHAR* src, size_t src_len, std::string* output);
-
-// Prepares an output buffer (containing either UTF-16 or -32 data) given some
-// UTF-8 input that will be converted to it. See PrepareForUTF8Output().
-template<typename STRING>
-void PrepareForUTF16Or32Output(const char* src, size_t src_len, STRING* output);
-
-} // namespace base
-
-#endif // BASE_STRINGS_UTF_STRING_CONVERSION_UTILS_H_
diff --git a/security/sandbox/chromium/base/strings/utf_string_conversions.cc b/security/sandbox/chromium/base/strings/utf_string_conversions.cc
deleted file mode 100644
index 6b17eacd6..000000000
--- a/security/sandbox/chromium/base/strings/utf_string_conversions.cc
+++ /dev/null
@@ -1,231 +0,0 @@
-// 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/strings/utf_string_conversions.h"
-
-#include <stdint.h>
-
-#include "base/strings/string_piece.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversion_utils.h"
-#include "build/build_config.h"
-
-namespace base {
-
-namespace {
-
-// Generalized Unicode converter -----------------------------------------------
-
-// Converts the given source Unicode character type to the given destination
-// Unicode character type as a STL string. The given input buffer and size
-// determine the source, and the given output STL string will be replaced by
-// the result.
-template<typename SRC_CHAR, typename DEST_STRING>
-bool ConvertUnicode(const SRC_CHAR* src,
- size_t src_len,
- DEST_STRING* output) {
- // ICU requires 32-bit numbers.
- bool success = true;
- int32_t src_len32 = static_cast<int32_t>(src_len);
- for (int32_t i = 0; i < src_len32; i++) {
- uint32_t code_point;
- if (ReadUnicodeCharacter(src, src_len32, &i, &code_point)) {
- WriteUnicodeCharacter(code_point, output);
- } else {
- WriteUnicodeCharacter(0xFFFD, output);
- success = false;
- }
- }
-
- return success;
-}
-
-} // namespace
-
-// UTF-8 <-> Wide --------------------------------------------------------------
-
-bool WideToUTF8(const wchar_t* src, size_t src_len, std::string* output) {
- if (IsStringASCII(std::wstring(src, src_len))) {
- output->assign(src, src + src_len);
- return true;
- } else {
- PrepareForUTF8Output(src, src_len, output);
- return ConvertUnicode(src, src_len, output);
- }
-}
-
-std::string WideToUTF8(const std::wstring& wide) {
- if (IsStringASCII(wide)) {
- return std::string(wide.data(), wide.data() + wide.length());
- }
-
- std::string ret;
- PrepareForUTF8Output(wide.data(), wide.length(), &ret);
- ConvertUnicode(wide.data(), wide.length(), &ret);
- return ret;
-}
-
-bool UTF8ToWide(const char* src, size_t src_len, std::wstring* output) {
- if (IsStringASCII(StringPiece(src, src_len))) {
- output->assign(src, src + src_len);
- return true;
- } else {
- PrepareForUTF16Or32Output(src, src_len, output);
- return ConvertUnicode(src, src_len, output);
- }
-}
-
-std::wstring UTF8ToWide(StringPiece utf8) {
- if (IsStringASCII(utf8)) {
- return std::wstring(utf8.begin(), utf8.end());
- }
-
- std::wstring ret;
- PrepareForUTF16Or32Output(utf8.data(), utf8.length(), &ret);
- ConvertUnicode(utf8.data(), utf8.length(), &ret);
- return ret;
-}
-
-// UTF-16 <-> Wide -------------------------------------------------------------
-
-#if defined(WCHAR_T_IS_UTF16)
-
-// When wide == UTF-16, then conversions are a NOP.
-bool WideToUTF16(const wchar_t* src, size_t src_len, string16* output) {
- output->assign(src, src_len);
- return true;
-}
-
-string16 WideToUTF16(const std::wstring& wide) {
- return wide;
-}
-
-bool UTF16ToWide(const char16* src, size_t src_len, std::wstring* output) {
- output->assign(src, src_len);
- return true;
-}
-
-std::wstring UTF16ToWide(const string16& utf16) {
- return utf16;
-}
-
-#elif defined(WCHAR_T_IS_UTF32)
-
-bool WideToUTF16(const wchar_t* src, size_t src_len, string16* output) {
- output->clear();
- // Assume that normally we won't have any non-BMP characters so the counts
- // will be the same.
- output->reserve(src_len);
- return ConvertUnicode(src, src_len, output);
-}
-
-string16 WideToUTF16(const std::wstring& wide) {
- string16 ret;
- WideToUTF16(wide.data(), wide.length(), &ret);
- return ret;
-}
-
-bool UTF16ToWide(const char16* src, size_t src_len, std::wstring* output) {
- output->clear();
- // Assume that normally we won't have any non-BMP characters so the counts
- // will be the same.
- output->reserve(src_len);
- return ConvertUnicode(src, src_len, output);
-}
-
-std::wstring UTF16ToWide(const string16& utf16) {
- std::wstring ret;
- UTF16ToWide(utf16.data(), utf16.length(), &ret);
- return ret;
-}
-
-#endif // defined(WCHAR_T_IS_UTF32)
-
-// UTF16 <-> UTF8 --------------------------------------------------------------
-
-#if defined(WCHAR_T_IS_UTF32)
-
-bool UTF8ToUTF16(const char* src, size_t src_len, string16* output) {
- if (IsStringASCII(StringPiece(src, src_len))) {
- output->assign(src, src + src_len);
- return true;
- } else {
- PrepareForUTF16Or32Output(src, src_len, output);
- return ConvertUnicode(src, src_len, output);
- }
-}
-
-string16 UTF8ToUTF16(StringPiece utf8) {
- if (IsStringASCII(utf8)) {
- return string16(utf8.begin(), utf8.end());
- }
-
- string16 ret;
- PrepareForUTF16Or32Output(utf8.data(), utf8.length(), &ret);
- // Ignore the success flag of this call, it will do the best it can for
- // invalid input, which is what we want here.
- ConvertUnicode(utf8.data(), utf8.length(), &ret);
- return ret;
-}
-
-bool UTF16ToUTF8(const char16* src, size_t src_len, std::string* output) {
- if (IsStringASCII(StringPiece16(src, src_len))) {
- output->assign(src, src + src_len);
- return true;
- } else {
- PrepareForUTF8Output(src, src_len, output);
- return ConvertUnicode(src, src_len, output);
- }
-}
-
-std::string UTF16ToUTF8(StringPiece16 utf16) {
- if (IsStringASCII(utf16)) {
- return std::string(utf16.begin(), utf16.end());
- }
-
- std::string ret;
- // Ignore the success flag of this call, it will do the best it can for
- // invalid input, which is what we want here.
- UTF16ToUTF8(utf16.data(), utf16.length(), &ret);
- return ret;
-}
-
-#elif defined(WCHAR_T_IS_UTF16)
-// Easy case since we can use the "wide" versions we already wrote above.
-
-bool UTF8ToUTF16(const char* src, size_t src_len, string16* output) {
- return UTF8ToWide(src, src_len, output);
-}
-
-string16 UTF8ToUTF16(StringPiece utf8) {
- return UTF8ToWide(utf8);
-}
-
-bool UTF16ToUTF8(const char16* src, size_t src_len, std::string* output) {
- return WideToUTF8(src, src_len, output);
-}
-
-std::string UTF16ToUTF8(StringPiece16 utf16) {
- if (IsStringASCII(utf16))
- return std::string(utf16.data(), utf16.data() + utf16.length());
-
- std::string ret;
- PrepareForUTF8Output(utf16.data(), utf16.length(), &ret);
- ConvertUnicode(utf16.data(), utf16.length(), &ret);
- return ret;
-}
-
-#endif
-
-string16 ASCIIToUTF16(StringPiece ascii) {
- DCHECK(IsStringASCII(ascii)) << ascii;
- return string16(ascii.begin(), ascii.end());
-}
-
-std::string UTF16ToASCII(StringPiece16 utf16) {
- DCHECK(IsStringASCII(utf16)) << UTF16ToUTF8(utf16);
- return std::string(utf16.begin(), utf16.end());
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/strings/utf_string_conversions.h b/security/sandbox/chromium/base/strings/utf_string_conversions.h
deleted file mode 100644
index 2995f4cbc..000000000
--- a/security/sandbox/chromium/base/strings/utf_string_conversions.h
+++ /dev/null
@@ -1,54 +0,0 @@
-// 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_STRINGS_UTF_STRING_CONVERSIONS_H_
-#define BASE_STRINGS_UTF_STRING_CONVERSIONS_H_
-
-#include <stddef.h>
-
-#include <string>
-
-#include "base/base_export.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_piece.h"
-
-namespace base {
-
-// 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.
-BASE_EXPORT bool WideToUTF8(const wchar_t* src, size_t src_len,
- std::string* output);
-BASE_EXPORT std::string WideToUTF8(const std::wstring& wide);
-BASE_EXPORT bool UTF8ToWide(const char* src, size_t src_len,
- std::wstring* output);
-BASE_EXPORT std::wstring UTF8ToWide(StringPiece utf8);
-
-BASE_EXPORT bool WideToUTF16(const wchar_t* src, size_t src_len,
- string16* output);
-BASE_EXPORT string16 WideToUTF16(const std::wstring& wide);
-BASE_EXPORT bool UTF16ToWide(const char16* src, size_t src_len,
- std::wstring* output);
-BASE_EXPORT std::wstring UTF16ToWide(const string16& utf16);
-
-BASE_EXPORT bool UTF8ToUTF16(const char* src, size_t src_len, string16* output);
-BASE_EXPORT string16 UTF8ToUTF16(StringPiece utf8);
-BASE_EXPORT bool UTF16ToUTF8(const char16* src, size_t src_len,
- std::string* output);
-BASE_EXPORT std::string UTF16ToUTF8(StringPiece16 utf16);
-
-// This converts an ASCII string, typically a hardcoded constant, to a UTF16
-// string.
-BASE_EXPORT string16 ASCIIToUTF16(StringPiece ascii);
-
-// Converts to 7-bit ASCII by truncating. The result must be known to be ASCII
-// beforehand.
-BASE_EXPORT std::string UTF16ToASCII(StringPiece16 utf16);
-
-} // namespace base
-
-#endif // BASE_STRINGS_UTF_STRING_CONVERSIONS_H_
diff --git a/security/sandbox/chromium/base/synchronization/condition_variable.h b/security/sandbox/chromium/base/synchronization/condition_variable.h
deleted file mode 100644
index a41b2ba5a..000000000
--- a/security/sandbox/chromium/base/synchronization/condition_variable.h
+++ /dev/null
@@ -1,118 +0,0 @@
-// 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 thread pool managed
-// by a master. 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_SYNCHRONIZATION_CONDITION_VARIABLE_H_
-#define BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_
-
-#include "base/base_export.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-#include "build/build_config.h"
-
-#if defined(OS_POSIX)
-#include <pthread.h>
-#endif
-
-namespace base {
-
-class ConditionVarImpl;
-class TimeDelta;
-
-class BASE_EXPORT 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.
- void Wait();
- void TimedWait(const TimeDelta& max_time);
-
- // Broadcast() revives all waiting threads.
- void Broadcast();
- // Signal() revives one waiting thread.
- void Signal();
-
- private:
-
-#if defined(OS_WIN)
- ConditionVarImpl* impl_;
-#elif defined(OS_POSIX)
- pthread_cond_t condition_;
- pthread_mutex_t* user_mutex_;
-#if DCHECK_IS_ON()
- base::Lock* user_lock_; // Needed to adjust shadow lock state on wait.
-#endif
-
-#endif
-
- DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
-};
-
-} // namespace base
-
-#endif // BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_
diff --git a/security/sandbox/chromium/base/synchronization/condition_variable_posix.cc b/security/sandbox/chromium/base/synchronization/condition_variable_posix.cc
deleted file mode 100644
index d86fd180e..000000000
--- a/security/sandbox/chromium/base/synchronization/condition_variable_posix.cc
+++ /dev/null
@@ -1,137 +0,0 @@
-// 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/synchronization/condition_variable.h"
-
-#include <errno.h>
-#include <stdint.h>
-#include <sys/time.h>
-
-#include "base/synchronization/lock.h"
-#include "base/threading/thread_restrictions.h"
-#include "base/time/time.h"
-#include "build/build_config.h"
-
-namespace base {
-
-ConditionVariable::ConditionVariable(Lock* user_lock)
- : user_mutex_(user_lock->lock_.native_handle())
-#if DCHECK_IS_ON()
- , user_lock_(user_lock)
-#endif
-{
- int rv = 0;
- // http://crbug.com/293736
- // NaCl doesn't support monotonic clock based absolute deadlines.
- // On older Android platform versions, it's 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(OS_MACOSX) && !defined(OS_NACL) && \
- !(defined(OS_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(OS_MACOSX)
- // This hack is necessary to avoid a fatal pthreads subsystem bug in the
- // Darwin kernel. http://crbug.com/517681.
- {
- base::Lock lock;
- base::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() {
- base::ThreadRestrictions::AssertWaitAllowed();
-#if DCHECK_IS_ON()
- user_lock_->CheckHeldAndUnmark();
-#endif
- int rv = pthread_cond_wait(&condition_, user_mutex_);
- DCHECK_EQ(0, rv);
-#if DCHECK_IS_ON()
- user_lock_->CheckUnheldAndMark();
-#endif
-}
-
-void ConditionVariable::TimedWait(const TimeDelta& max_time) {
- base::ThreadRestrictions::AssertWaitAllowed();
- int64_t usecs = max_time.InMicroseconds();
- struct timespec relative_time;
- relative_time.tv_sec = usecs / Time::kMicrosecondsPerSecond;
- relative_time.tv_nsec =
- (usecs % Time::kMicrosecondsPerSecond) * Time::kNanosecondsPerMicrosecond;
-
-#if DCHECK_IS_ON()
- user_lock_->CheckHeldAndUnmark();
-#endif
-
-#if defined(OS_MACOSX)
- 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;
-#if defined(OS_NACL)
- // See comment in constructor for why this is different in NaCl.
- struct timeval now;
- gettimeofday(&now, NULL);
- absolute_time.tv_sec = now.tv_sec;
- absolute_time.tv_nsec = now.tv_usec * Time::kNanosecondsPerMicrosecond;
-#else
- struct timespec now;
- clock_gettime(CLOCK_MONOTONIC, &now);
- absolute_time.tv_sec = now.tv_sec;
- absolute_time.tv_nsec = now.tv_nsec;
-#endif
-
- absolute_time.tv_sec += relative_time.tv_sec;
- absolute_time.tv_nsec += relative_time.tv_nsec;
- absolute_time.tv_sec += absolute_time.tv_nsec / Time::kNanosecondsPerSecond;
- absolute_time.tv_nsec %= Time::kNanosecondsPerSecond;
- DCHECK_GE(absolute_time.tv_sec, now.tv_sec); // Overflow paranoia
-
-#if defined(OS_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 // OS_ANDROID && HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC
-#endif // OS_MACOSX
-
- DCHECK(rv == 0 || rv == ETIMEDOUT);
-#if DCHECK_IS_ON()
- user_lock_->CheckUnheldAndMark();
-#endif
-}
-
-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);
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/synchronization/lock.cc b/security/sandbox/chromium/base/synchronization/lock.cc
deleted file mode 100644
index 03297ada5..000000000
--- a/security/sandbox/chromium/base/synchronization/lock.cc
+++ /dev/null
@@ -1,38 +0,0 @@
-// 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.
-
-// This file is used for debugging assertion support. The Lock class
-// is functionally a wrapper around the LockImpl class, so the only
-// real intelligence in the class is in the debugging logic.
-
-#include "base/synchronization/lock.h"
-
-#if DCHECK_IS_ON()
-
-namespace base {
-
-Lock::Lock() : lock_() {
-}
-
-Lock::~Lock() {
- DCHECK(owning_thread_ref_.is_null());
-}
-
-void Lock::AssertAcquired() const {
- DCHECK(owning_thread_ref_ == PlatformThread::CurrentRef());
-}
-
-void Lock::CheckHeldAndUnmark() {
- DCHECK(owning_thread_ref_ == PlatformThread::CurrentRef());
- owning_thread_ref_ = PlatformThreadRef();
-}
-
-void Lock::CheckUnheldAndMark() {
- DCHECK(owning_thread_ref_.is_null());
- owning_thread_ref_ = PlatformThread::CurrentRef();
-}
-
-} // namespace base
-
-#endif // DCHECK_IS_ON()
diff --git a/security/sandbox/chromium/base/synchronization/lock.h b/security/sandbox/chromium/base/synchronization/lock.h
deleted file mode 100644
index f7dd35dcc..000000000
--- a/security/sandbox/chromium/base/synchronization/lock.h
+++ /dev/null
@@ -1,140 +0,0 @@
-// 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_SYNCHRONIZATION_LOCK_H_
-#define BASE_SYNCHRONIZATION_LOCK_H_
-
-#include "base/base_export.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/synchronization/lock_impl.h"
-#include "base/threading/platform_thread.h"
-#include "build/build_config.h"
-
-namespace base {
-
-// A convenient wrapper for an OS specific critical section. The only real
-// intelligence in this class is in debug mode for the support for the
-// AssertAcquired() method.
-class BASE_EXPORT Lock {
- public:
-#if !DCHECK_IS_ON()
- // Optimized wrapper implementation
- Lock() : lock_() {}
- ~Lock() {}
- 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 {}
-#else
- Lock();
- ~Lock();
-
- // NOTE: Although windows critical sections support recursive locks, we do not
- // allow this, and we will commonly fire a DCHECK() if a thread attempts to
- // acquire the lock a second time (while already holding it).
- void Acquire() {
- lock_.Lock();
- CheckUnheldAndMark();
- }
- void Release() {
- CheckHeldAndUnmark();
- lock_.Unlock();
- }
-
- bool Try() {
- bool rv = lock_.Try();
- if (rv) {
- CheckUnheldAndMark();
- }
- return rv;
- }
-
- void AssertAcquired() const;
-#endif // DCHECK_IS_ON()
-
-#if defined(OS_POSIX)
- // The posix implementation of ConditionVariable needs to be able
- // to see our lock and tweak our debugging counters, as it releases
- // and acquires locks inside of pthread_cond_{timed,}wait.
- friend class ConditionVariable;
-#elif defined(OS_WIN)
- // The Windows Vista implementation of ConditionVariable needs the
- // native handle of the critical section.
- friend class WinVistaCondVar;
-#endif
-
- private:
-#if DCHECK_IS_ON()
- // Members and routines taking care of locks assertions.
- // Note that this checks for recursive locks and allows them
- // if the variable is set. This is allowed by the underlying implementation
- // on windows but not on Posix, so we're doing unneeded checks on Posix.
- // It's worth it to share the code.
- void CheckHeldAndUnmark();
- void CheckUnheldAndMark();
-
- // All private data is implicitly protected by lock_.
- // Be VERY careful to only access members under that lock.
- base::PlatformThreadRef owning_thread_ref_;
-#endif // DCHECK_IS_ON()
-
- // Platform specific underlying lock implementation.
- 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);
-};
-
-} // namespace base
-
-#endif // BASE_SYNCHRONIZATION_LOCK_H_
diff --git a/security/sandbox/chromium/base/synchronization/lock_impl.h b/security/sandbox/chromium/base/synchronization/lock_impl.h
deleted file mode 100644
index ed85987b3..000000000
--- a/security/sandbox/chromium/base/synchronization/lock_impl.h
+++ /dev/null
@@ -1,60 +0,0 @@
-// 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_SYNCHRONIZATION_LOCK_IMPL_H_
-#define BASE_SYNCHRONIZATION_LOCK_IMPL_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "build/build_config.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#elif defined(OS_POSIX)
-#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 BASE_EXPORT LockImpl {
- public:
-#if defined(OS_WIN)
- typedef CRITICAL_SECTION NativeHandle;
-#elif defined(OS_POSIX)
- typedef pthread_mutex_t NativeHandle;
-#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_; }
-
- private:
- NativeHandle native_handle_;
-
- DISALLOW_COPY_AND_ASSIGN(LockImpl);
-};
-
-} // namespace internal
-} // namespace base
-
-#endif // BASE_SYNCHRONIZATION_LOCK_IMPL_H_
diff --git a/security/sandbox/chromium/base/synchronization/lock_impl_posix.cc b/security/sandbox/chromium/base/synchronization/lock_impl_posix.cc
deleted file mode 100644
index 5619adaf5..000000000
--- a/security/sandbox/chromium/base/synchronization/lock_impl_posix.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-// 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/synchronization/lock_impl.h"
-
-#include <errno.h>
-#include <string.h>
-
-#include "base/logging.h"
-
-namespace base {
-namespace internal {
-
-LockImpl::LockImpl() {
-#ifndef NDEBUG
- // In debug, setup attributes for lock error checking.
- pthread_mutexattr_t mta;
- int rv = pthread_mutexattr_init(&mta);
- DCHECK_EQ(rv, 0) << ". " << strerror(rv);
- rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK);
- DCHECK_EQ(rv, 0) << ". " << strerror(rv);
- rv = pthread_mutex_init(&native_handle_, &mta);
- DCHECK_EQ(rv, 0) << ". " << strerror(rv);
- rv = pthread_mutexattr_destroy(&mta);
- DCHECK_EQ(rv, 0) << ". " << strerror(rv);
-#else
- // In release, go with the default lock attributes.
- pthread_mutex_init(&native_handle_, NULL);
-#endif
-}
-
-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);
-}
-
-} // namespace internal
-} // namespace base
diff --git a/security/sandbox/chromium/base/synchronization/lock_impl_win.cc b/security/sandbox/chromium/base/synchronization/lock_impl_win.cc
deleted file mode 100644
index fbc1bdd46..000000000
--- a/security/sandbox/chromium/base/synchronization/lock_impl_win.cc
+++ /dev/null
@@ -1,36 +0,0 @@
-// 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/synchronization/lock_impl.h"
-
-namespace base {
-namespace internal {
-
-LockImpl::LockImpl() {
- // The second parameter is the spin count, for short-held locks it avoid the
- // contending thread from going to sleep which helps performance greatly.
- ::InitializeCriticalSectionAndSpinCount(&native_handle_, 2000);
-}
-
-LockImpl::~LockImpl() {
- ::DeleteCriticalSection(&native_handle_);
-}
-
-bool LockImpl::Try() {
- if (::TryEnterCriticalSection(&native_handle_) != FALSE) {
- return true;
- }
- return false;
-}
-
-void LockImpl::Lock() {
- ::EnterCriticalSection(&native_handle_);
-}
-
-void LockImpl::Unlock() {
- ::LeaveCriticalSection(&native_handle_);
-}
-
-} // namespace internal
-} // namespace base
diff --git a/security/sandbox/chromium/base/synchronization/waitable_event.h b/security/sandbox/chromium/base/synchronization/waitable_event.h
deleted file mode 100644
index b5d91d00b..000000000
--- a/security/sandbox/chromium/base/synchronization/waitable_event.h
+++ /dev/null
@@ -1,189 +0,0 @@
-// 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.
-
-#ifndef BASE_SYNCHRONIZATION_WAITABLE_EVENT_H_
-#define BASE_SYNCHRONIZATION_WAITABLE_EVENT_H_
-
-#include <stddef.h>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "build/build_config.h"
-
-#if defined(OS_WIN)
-#include "base/win/scoped_handle.h"
-#endif
-
-#if defined(OS_POSIX)
-#include <list>
-#include <utility>
-#include "base/memory/ref_counted.h"
-#include "base/synchronization/lock.h"
-#endif
-
-namespace base {
-
-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 BASE_EXPORT 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);
-
-#if defined(OS_WIN)
- // Create a WaitableEvent from an Event HANDLE which has already been
- // created. This objects takes ownership of the HANDLE and will close it when
- // deleted.
- explicit WaitableEvent(win::ScopedHandle event_handle);
-#endif
-
- ~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. Wait's return "happens
- // after" |Signal| has completed. This means that it's safe for a
- // WaitableEvent to synchronise its own destruction, like this:
- //
- // WaitableEvent *e = new WaitableEvent;
- // SendToOtherThread(e);
- // e->Wait();
- // delete e;
- void 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.
- //
- // TimedWait can synchronise its own destruction like |Wait|.
- bool TimedWait(const TimeDelta& max_time);
-
-#if defined(OS_WIN)
- HANDLE handle() const { return handle_.Get(); }
-#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, however WaitMany's return "happens after" the |Signal| call
- // that caused it has completed, like |Wait|.
- 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;
-
- protected:
- virtual ~Waiter() {}
- };
-
- private:
- friend class WaitableEventWatcher;
-
-#if defined(OS_WIN)
- win::ScopedHandle 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 :
- public RefCountedThreadSafe<WaitableEventKernel> {
- public:
- WaitableEventKernel(bool manual_reset, bool initially_signaled);
-
- bool Dequeue(Waiter* waiter, void* tag);
-
- base::Lock lock_;
- const bool manual_reset_;
- bool signaled_;
- std::list<Waiter*> waiters_;
-
- private:
- friend class RefCountedThreadSafe<WaitableEventKernel>;
- ~WaitableEventKernel();
- };
-
- typedef std::pair<WaitableEvent*, size_t> WaiterAndIndex;
-
- // 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.
- static size_t EnqueueMany(WaiterAndIndex* waitables,
- size_t count, Waiter* waiter);
-
- bool SignalAll();
- bool SignalOne();
- void Enqueue(Waiter* waiter);
-
- scoped_refptr<WaitableEventKernel> kernel_;
-#endif
-
- DISALLOW_COPY_AND_ASSIGN(WaitableEvent);
-};
-
-} // namespace base
-
-#endif // BASE_SYNCHRONIZATION_WAITABLE_EVENT_H_
diff --git a/security/sandbox/chromium/base/synchronization/waitable_event_posix.cc b/security/sandbox/chromium/base/synchronization/waitable_event_posix.cc
deleted file mode 100644
index 64d4376fe..000000000
--- a/security/sandbox/chromium/base/synchronization/waitable_event_posix.cc
+++ /dev/null
@@ -1,417 +0,0 @@
-// 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.
-
-#include <stddef.h>
-
-#include <algorithm>
-#include <vector>
-
-#include "base/logging.h"
-#include "base/synchronization/condition_variable.h"
-#include "base/synchronization/lock.h"
-#include "base/synchronization/waitable_event.h"
-#include "base/threading/thread_restrictions.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() {
- base::AutoLock locked(kernel_->lock_);
- kernel_->signaled_ = false;
-}
-
-void WaitableEvent::Signal() {
- base::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() {
- base::AutoLock locked(kernel_->lock_);
-
- const bool result = kernel_->signaled_;
- if (result && !kernel_->manual_reset_)
- kernel_->signaled_ = false;
- return result;
-}
-
-// -----------------------------------------------------------------------------
-// Synchronous waits
-
-// -----------------------------------------------------------------------------
-// This is a 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()
- : fired_(false),
- signaling_event_(NULL),
- lock_(),
- cv_(&lock_) {
- }
-
- bool Fire(WaitableEvent* signaling_event) override {
- base::AutoLock locked(lock_);
-
- if (fired_)
- return false;
-
- fired_ = true;
- signaling_event_ = signaling_event;
-
- cv_.Broadcast();
-
- // Unlike AsyncWaiter objects, SyncWaiter objects are stack-allocated on
- // the blocking thread's stack. There is no |delete this;| in Fire. The
- // SyncWaiter object is destroyed when it goes out of scope.
-
- return true;
- }
-
- WaitableEvent* signaling_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;
- }
-
- base::Lock* lock() {
- return &lock_;
- }
-
- base::ConditionVariable* cv() {
- return &cv_;
- }
-
- private:
- bool fired_;
- WaitableEvent* signaling_event_; // The WaitableEvent which woke us
- base::Lock lock_;
- base::ConditionVariable cv_;
-};
-
-void WaitableEvent::Wait() {
- bool result = TimedWait(TimeDelta::FromSeconds(-1));
- DCHECK(result) << "TimedWait() should never fail with infinite timeout";
-}
-
-bool WaitableEvent::TimedWait(const TimeDelta& max_time) {
- base::ThreadRestrictions::AssertWaitAllowed();
- 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;
- }
-
- SyncWaiter sw;
- sw.lock()->Acquire();
-
- 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 the SyncWaiter lock (because
- // of locking order), however, in between 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();
- sw.lock()->Release();
-
- // This is a bug that has been enshrined in the interface of
- // WaitableEvent now: |Dequeue| is called even when |sw.fired()| is true,
- // even though it'll always return false in that case. However, taking
- // the lock ensures that |Signal| has completed before we return and
- // means that a WaitableEvent can synchronise its own destruction.
- kernel_->lock_.Acquire();
- kernel_->Dequeue(&sw, &sw);
- kernel_->lock_.Release();
-
- return return_value;
- }
-
- if (finite_time) {
- const TimeDelta max_wait(end_time - current_time);
- sw.cv()->TimedWait(max_wait);
- } else {
- sw.cv()->Wait();
- }
- }
-}
-
-// -----------------------------------------------------------------------------
-// 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) {
- base::ThreadRestrictions::AssertWaitAllowed();
- 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);
- }
-
- SyncWaiter sw;
-
- 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.
- sw.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;
-
- sw.cv()->Wait();
- }
- sw.lock()->Release();
-
- // The address of the WaitableEvent which fired is stored in the SyncWaiter.
- WaitableEvent *const signaled_event = sw.signaling_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 {
- // By taking this lock here we ensure that |Signal| has completed by the
- // time we return, because |Signal| holds this lock. This matches the
- // behaviour of |Wait| and |TimedWait|.
- raw_waitables[i]->kernel_->lock_.Acquire();
- raw_waitables[i]->kernel_->lock_.Release();
- 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...
-
-WaitableEvent::WaitableEventKernel::WaitableEventKernel(bool manual_reset,
- bool initially_signaled)
- : manual_reset_(manual_reset),
- signaled_(initially_signaled) {
-}
-
-WaitableEvent::WaitableEventKernel::~WaitableEventKernel() {
-}
-
-// -----------------------------------------------------------------------------
-// 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/security/sandbox/chromium/base/task_runner.h b/security/sandbox/chromium/base/task_runner.h
deleted file mode 100644
index 6dd82ccac..000000000
--- a/security/sandbox/chromium/base/task_runner.h
+++ /dev/null
@@ -1,154 +0,0 @@
-// 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.
-
-#ifndef BASE_TASK_RUNNER_H_
-#define BASE_TASK_RUNNER_H_
-
-#include <stddef.h>
-
-#include "base/base_export.h"
-#include "base/callback_forward.h"
-#include "base/memory/ref_counted.h"
-#include "base/time/time.h"
-
-namespace tracked_objects {
-class Location;
-} // namespace tracked_objects
-
-namespace base {
-
-struct TaskRunnerTraits;
-
-// A TaskRunner is an object that runs posted tasks (in the form of
-// Closure objects). The TaskRunner interface provides a way of
-// decoupling task posting from the mechanics of how each task will be
-// run. TaskRunner provides very weak guarantees as to how posted
-// tasks are run (or if they're run at all). In particular, it only
-// guarantees:
-//
-// - Posting a task will not run it synchronously. That is, no
-// Post*Task method will call task.Run() directly.
-//
-// - Increasing the delay can only delay when the task gets run.
-// That is, increasing the delay may not affect when the task gets
-// run, or it could make it run later than it normally would, but
-// it won't make it run earlier than it normally would.
-//
-// TaskRunner does not guarantee the order in which posted tasks are
-// run, whether tasks overlap, or whether they're run on a particular
-// thread. Also it does not guarantee a memory model for shared data
-// between tasks. (In other words, you should use your own
-// synchronization/locking primitives if you need to share data
-// between tasks.)
-//
-// Implementations of TaskRunner should be thread-safe in that all
-// methods must be safe to call on any thread. Ownership semantics
-// for TaskRunners are in general not clear, which is why the
-// interface itself is RefCountedThreadSafe.
-//
-// Some theoretical implementations of TaskRunner:
-//
-// - A TaskRunner that uses a thread pool to run posted tasks.
-//
-// - A TaskRunner that, for each task, spawns a non-joinable thread
-// to run that task and immediately quit.
-//
-// - A TaskRunner that stores the list of posted tasks and has a
-// method Run() that runs each runnable task in random order.
-class BASE_EXPORT TaskRunner
- : public RefCountedThreadSafe<TaskRunner, TaskRunnerTraits> {
- public:
- // Posts the given task to be run. Returns true if the task may be
- // run at some point in the future, and false if the task definitely
- // will not be run.
- //
- // Equivalent to PostDelayedTask(from_here, task, 0).
- bool PostTask(const tracked_objects::Location& from_here,
- const Closure& task);
-
- // Like PostTask, but tries to run the posted task only after
- // |delay_ms| has passed.
- //
- // It is valid for an implementation to ignore |delay_ms|; that is,
- // to have PostDelayedTask behave the same as PostTask.
- virtual bool PostDelayedTask(const tracked_objects::Location& from_here,
- const Closure& task,
- base::TimeDelta delay) = 0;
-
- // Returns true if the current thread is a thread on which a task
- // may be run, and false if no task will be run on the current
- // thread.
- //
- // It is valid for an implementation to always return true, or in
- // general to use 'true' as a default value.
- virtual bool RunsTasksOnCurrentThread() const = 0;
-
- // Posts |task| on the current TaskRunner. On completion, |reply|
- // is posted to the thread that called PostTaskAndReply(). Both
- // |task| and |reply| are guaranteed to be deleted on the thread
- // from which PostTaskAndReply() is invoked. This allows objects
- // that must be deleted on the originating thread to be bound into
- // the |task| and |reply| Closures. In particular, it can be useful
- // to use WeakPtr<> in the |reply| Closure so that the reply
- // operation can be canceled. See the following pseudo-code:
- //
- // class DataBuffer : public RefCountedThreadSafe<DataBuffer> {
- // public:
- // // Called to add data into a buffer.
- // void AddData(void* buf, size_t length);
- // ...
- // };
- //
- //
- // class DataLoader : public SupportsWeakPtr<DataLoader> {
- // public:
- // void GetData() {
- // scoped_refptr<DataBuffer> buffer = new DataBuffer();
- // target_thread_.task_runner()->PostTaskAndReply(
- // FROM_HERE,
- // base::Bind(&DataBuffer::AddData, buffer),
- // base::Bind(&DataLoader::OnDataReceived, AsWeakPtr(), buffer));
- // }
- //
- // private:
- // void OnDataReceived(scoped_refptr<DataBuffer> buffer) {
- // // Do something with buffer.
- // }
- // };
- //
- //
- // Things to notice:
- // * Results of |task| are shared with |reply| by binding a shared argument
- // (a DataBuffer instance).
- // * The DataLoader object has no special thread safety.
- // * The DataLoader object can be deleted while |task| is still running,
- // and the reply will cancel itself safely because it is bound to a
- // WeakPtr<>.
- bool PostTaskAndReply(const tracked_objects::Location& from_here,
- const Closure& task,
- const Closure& reply);
-
- protected:
- friend struct TaskRunnerTraits;
-
- // Only the Windows debug build seems to need this: see
- // http://crbug.com/112250.
- friend class RefCountedThreadSafe<TaskRunner, TaskRunnerTraits>;
-
- TaskRunner();
- virtual ~TaskRunner();
-
- // Called when this object should be destroyed. By default simply
- // deletes |this|, but can be overridden to do something else, like
- // delete on a certain thread.
- virtual void OnDestruct() const;
-};
-
-struct BASE_EXPORT TaskRunnerTraits {
- static void Destruct(const TaskRunner* task_runner);
-};
-
-} // namespace base
-
-#endif // BASE_TASK_RUNNER_H_
diff --git a/security/sandbox/chromium/base/template_util.h b/security/sandbox/chromium/base/template_util.h
deleted file mode 100644
index d58807a77..000000000
--- a/security/sandbox/chromium/base/template_util.h
+++ /dev/null
@@ -1,122 +0,0 @@
-// 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_TEMPLATE_UTIL_H_
-#define BASE_TEMPLATE_UTIL_H_
-
-#include <stddef.h>
-
-#include "build/build_config.h"
-
-namespace base {
-
-// template definitions from tr1
-
-template<class T, T v>
-struct integral_constant {
- static const T value = v;
- typedef T value_type;
- typedef integral_constant<T, v> type;
-};
-
-template <class T, T v> const T integral_constant<T, v>::value;
-
-typedef integral_constant<bool, true> true_type;
-typedef integral_constant<bool, false> false_type;
-
-template <class T> struct is_pointer : false_type {};
-template <class T> struct is_pointer<T*> : true_type {};
-
-// Member function pointer detection. This is built-in to C++ 11's stdlib, and
-// we can remove this when we switch to it.
-template<typename T>
-struct is_member_function_pointer : false_type {};
-
-template <typename R, typename Z, typename... A>
-struct is_member_function_pointer<R(Z::*)(A...)> : true_type {};
-template <typename R, typename Z, typename... A>
-struct is_member_function_pointer<R(Z::*)(A...) const> : true_type {};
-
-
-template <class T, class U> struct is_same : public false_type {};
-template <class T> struct is_same<T,T> : true_type {};
-
-template<class> struct is_array : public false_type {};
-template<class T, size_t n> struct is_array<T[n]> : public true_type {};
-template<class T> struct is_array<T[]> : public true_type {};
-
-template <class T> struct is_non_const_reference : false_type {};
-template <class T> struct is_non_const_reference<T&> : true_type {};
-template <class T> struct is_non_const_reference<const T&> : false_type {};
-
-template <class T> struct is_const : false_type {};
-template <class T> struct is_const<const T> : true_type {};
-
-template <class T> struct is_void : false_type {};
-template <> struct is_void<void> : true_type {};
-
-namespace internal {
-
-// Types YesType and NoType are guaranteed such that sizeof(YesType) <
-// sizeof(NoType).
-typedef char YesType;
-
-struct NoType {
- YesType dummy[2];
-};
-
-// This class is an implementation detail for is_convertible, and you
-// don't need to know how it works to use is_convertible. For those
-// who care: we declare two different functions, one whose argument is
-// of type To and one with a variadic argument list. We give them
-// return types of different size, so we can use sizeof to trick the
-// compiler into telling us which function it would have chosen if we
-// had called it with an argument of type From. See Alexandrescu's
-// _Modern C++ Design_ for more details on this sort of trick.
-
-struct ConvertHelper {
- template <typename To>
- static YesType Test(To);
-
- template <typename To>
- static NoType Test(...);
-
- template <typename From>
- static From& Create();
-};
-
-// Used to determine if a type is a struct/union/class. Inspired by Boost's
-// is_class type_trait implementation.
-struct IsClassHelper {
- template <typename C>
- static YesType Test(void(C::*)(void));
-
- template <typename C>
- static NoType Test(...);
-};
-
-} // namespace internal
-
-// Inherits from true_type if From is convertible to To, false_type otherwise.
-//
-// Note that if the type is convertible, this will be a true_type REGARDLESS
-// of whether or not the conversion would emit a warning.
-template <typename From, typename To>
-struct is_convertible
- : integral_constant<bool,
- sizeof(internal::ConvertHelper::Test<To>(
- internal::ConvertHelper::Create<From>())) ==
- sizeof(internal::YesType)> {
-};
-
-template <typename T>
-struct is_class
- : integral_constant<bool,
- sizeof(internal::IsClassHelper::Test<T>(0)) ==
- sizeof(internal::YesType)> {
-};
-
-} // namespace base
-
-#endif // BASE_TEMPLATE_UTIL_H_
diff --git a/security/sandbox/chromium/base/third_party/dmg_fp/LICENSE b/security/sandbox/chromium/base/third_party/dmg_fp/LICENSE
deleted file mode 100644
index 716f1ef2b..000000000
--- a/security/sandbox/chromium/base/third_party/dmg_fp/LICENSE
+++ /dev/null
@@ -1,18 +0,0 @@
-/****************************************************************
- *
- * The author of this software is David M. Gay.
- *
- * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose without fee is hereby granted, provided that this entire notice
- * is included in all copies of any software which is or includes a copy
- * or modification of this software and in all copies of the supporting
- * documentation for such software.
- *
- * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
- * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
- * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
- * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
- *
- ***************************************************************/
diff --git a/security/sandbox/chromium/base/third_party/dmg_fp/dmg_fp.h b/security/sandbox/chromium/base/third_party/dmg_fp/dmg_fp.h
deleted file mode 100644
index 4795397ec..000000000
--- a/security/sandbox/chromium/base/third_party/dmg_fp/dmg_fp.h
+++ /dev/null
@@ -1,30 +0,0 @@
-// 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 THIRD_PARTY_DMG_FP_H_
-#define THIRD_PARTY_DMG_FP_H_
-
-namespace dmg_fp {
-
-// Return a nearest machine number to the input decimal
-// string (or set errno to ERANGE). With IEEE arithmetic, ties are
-// broken by the IEEE round-even rule. Otherwise ties are broken by
-// biased rounding (add half and chop).
-double strtod(const char* s00, char** se);
-
-// Convert double to ASCII string. For meaning of parameters
-// see dtoa.cc file.
-char* dtoa(double d, int mode, int ndigits,
- int* decpt, int* sign, char** rve);
-
-// Must be used to free values returned by dtoa.
-void freedtoa(char* s);
-
-// Store the closest decimal approximation to x in b (null terminated).
-// Returns a pointer to b. It is sufficient for |b| to be 32 characters.
-char* g_fmt(char* b, double x);
-
-} // namespace dmg_fp
-
-#endif // THIRD_PARTY_DMG_FP_H_
diff --git a/security/sandbox/chromium/base/third_party/dmg_fp/dtoa.cc b/security/sandbox/chromium/base/third_party/dmg_fp/dtoa.cc
deleted file mode 100644
index 502c16cc7..000000000
--- a/security/sandbox/chromium/base/third_party/dmg_fp/dtoa.cc
+++ /dev/null
@@ -1,4234 +0,0 @@
-/****************************************************************
- *
- * The author of this software is David M. Gay.
- *
- * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose without fee is hereby granted, provided that this entire notice
- * is included in all copies of any software which is or includes a copy
- * or modification of this software and in all copies of the supporting
- * documentation for such software.
- *
- * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
- * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
- * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
- * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
- *
- ***************************************************************/
-
-/* Please send bug reports to David M. Gay (dmg at acm dot org,
- * with " at " changed at "@" and " dot " changed to "."). */
-
-/* On a machine with IEEE extended-precision registers, it is
- * necessary to specify double-precision (53-bit) rounding precision
- * before invoking strtod or dtoa. If the machine uses (the equivalent
- * of) Intel 80x87 arithmetic, the call
- * _control87(PC_53, MCW_PC);
- * does this with many compilers. Whether this or another call is
- * appropriate depends on the compiler; for this to work, it may be
- * necessary to #include "float.h" or another system-dependent header
- * file.
- */
-
-/* strtod for IEEE-, VAX-, and IBM-arithmetic machines.
- *
- * This strtod returns a nearest machine number to the input decimal
- * string (or sets errno to ERANGE). With IEEE arithmetic, ties are
- * broken by the IEEE round-even rule. Otherwise ties are broken by
- * biased rounding (add half and chop).
- *
- * Inspired loosely by William D. Clinger's paper "How to Read Floating
- * Point Numbers Accurately" [Proc. ACM SIGPLAN '90, pp. 92-101].
- *
- * Modifications:
- *
- * 1. We only require IEEE, IBM, or VAX double-precision
- * arithmetic (not IEEE double-extended).
- * 2. We get by with floating-point arithmetic in a case that
- * Clinger missed -- when we're computing d * 10^n
- * for a small integer d and the integer n is not too
- * much larger than 22 (the maximum integer k for which
- * we can represent 10^k exactly), we may be able to
- * compute (d*10^k) * 10^(e-k) with just one roundoff.
- * 3. Rather than a bit-at-a-time adjustment of the binary
- * result in the hard case, we use floating-point
- * arithmetic to determine the adjustment to within
- * one bit; only in really hard cases do we need to
- * compute a second residual.
- * 4. Because of 3., we don't need a large table of powers of 10
- * for ten-to-e (just some small tables, e.g. of 10^k
- * for 0 <= k <= 22).
- */
-
-/*
- * #define IEEE_8087 for IEEE-arithmetic machines where the least
- * significant byte has the lowest address.
- * #define IEEE_MC68k for IEEE-arithmetic machines where the most
- * significant byte has the lowest address.
- * #define Long int on machines with 32-bit ints and 64-bit longs.
- * #define IBM for IBM mainframe-style floating-point arithmetic.
- * #define VAX for VAX-style floating-point arithmetic (D_floating).
- * #define No_leftright to omit left-right logic in fast floating-point
- * computation of dtoa.
- * #define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
- * and strtod and dtoa should round accordingly. Unless Trust_FLT_ROUNDS
- * is also #defined, fegetround() will be queried for the rounding mode.
- * Note that both FLT_ROUNDS and fegetround() are specified by the C99
- * standard (and are specified to be consistent, with fesetround()
- * affecting the value of FLT_ROUNDS), but that some (Linux) systems
- * do not work correctly in this regard, so using fegetround() is more
- * portable than using FLT_FOUNDS directly.
- * #define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
- * and Honor_FLT_ROUNDS is not #defined.
- * #define RND_PRODQUOT to use rnd_prod and rnd_quot (assembly routines
- * that use extended-precision instructions to compute rounded
- * products and quotients) with IBM.
- * #define ROUND_BIASED for IEEE-format with biased rounding.
- * #define Inaccurate_Divide for IEEE-format with correctly rounded
- * products but inaccurate quotients, e.g., for Intel i860.
- * #define NO_LONG_LONG on machines that do not have a "long long"
- * integer type (of >= 64 bits). On such machines, you can
- * #define Just_16 to store 16 bits per 32-bit Long when doing
- * high-precision integer arithmetic. Whether this speeds things
- * up or slows things down depends on the machine and the number
- * being converted. If long long is available and the name is
- * something other than "long long", #define Llong to be the name,
- * and if "unsigned Llong" does not work as an unsigned version of
- * Llong, #define #ULLong to be the corresponding unsigned type.
- * #define KR_headers for old-style C function headers.
- * #define Bad_float_h if your system lacks a float.h or if it does not
- * define some or all of DBL_DIG, DBL_MAX_10_EXP, DBL_MAX_EXP,
- * FLT_RADIX, FLT_ROUNDS, and DBL_MAX.
- * #define MALLOC your_malloc, where your_malloc(n) acts like malloc(n)
- * if memory is available and otherwise does something you deem
- * appropriate. If MALLOC is undefined, malloc will be invoked
- * directly -- and assumed always to succeed. Similarly, if you
- * want something other than the system's free() to be called to
- * recycle memory acquired from MALLOC, #define FREE to be the
- * name of the alternate routine. (FREE or free is only called in
- * pathological cases, e.g., in a dtoa call after a dtoa return in
- * mode 3 with thousands of digits requested.)
- * #define Omit_Private_Memory to omit logic (added Jan. 1998) for making
- * memory allocations from a private pool of memory when possible.
- * When used, the private pool is PRIVATE_MEM bytes long: 2304 bytes,
- * unless #defined to be a different length. This default length
- * suffices to get rid of MALLOC calls except for unusual cases,
- * such as decimal-to-binary conversion of a very long string of
- * digits. The longest string dtoa can return is about 751 bytes
- * long. For conversions by strtod of strings of 800 digits and
- * all dtoa conversions in single-threaded executions with 8-byte
- * pointers, PRIVATE_MEM >= 7400 appears to suffice; with 4-byte
- * pointers, PRIVATE_MEM >= 7112 appears adequate.
- * #define NO_INFNAN_CHECK if you do not wish to have INFNAN_CHECK
- * #defined automatically on IEEE systems. On such systems,
- * when INFNAN_CHECK is #defined, strtod checks
- * for Infinity and NaN (case insensitively). On some systems
- * (e.g., some HP systems), it may be necessary to #define NAN_WORD0
- * appropriately -- to the most significant word of a quiet NaN.
- * (On HP Series 700/800 machines, -DNAN_WORD0=0x7ff40000 works.)
- * When INFNAN_CHECK is #defined and No_Hex_NaN is not #defined,
- * strtod also accepts (case insensitively) strings of the form
- * NaN(x), where x is a string of hexadecimal digits and spaces;
- * if there is only one string of hexadecimal digits, it is taken
- * for the 52 fraction bits of the resulting NaN; if there are two
- * or more strings of hex digits, the first is for the high 20 bits,
- * the second and subsequent for the low 32 bits, with intervening
- * white space ignored; but if this results in none of the 52
- * fraction bits being on (an IEEE Infinity symbol), then NAN_WORD0
- * and NAN_WORD1 are used instead.
- * #define MULTIPLE_THREADS if the system offers preemptively scheduled
- * multiple threads. In this case, you must provide (or suitably
- * #define) two locks, acquired by ACQUIRE_DTOA_LOCK(n) and freed
- * by FREE_DTOA_LOCK(n) for n = 0 or 1. (The second lock, accessed
- * in pow5mult, ensures lazy evaluation of only one copy of high
- * powers of 5; omitting this lock would introduce a small
- * probability of wasting memory, but would otherwise be harmless.)
- * You must also invoke freedtoa(s) to free the value s returned by
- * dtoa. You may do so whether or not MULTIPLE_THREADS is #defined.
- * #define NO_IEEE_Scale to disable new (Feb. 1997) logic in strtod that
- * avoids underflows on inputs whose result does not underflow.
- * If you #define NO_IEEE_Scale on a machine that uses IEEE-format
- * floating-point numbers and flushes underflows to zero rather
- * than implementing gradual underflow, then you must also #define
- * Sudden_Underflow.
- * #define USE_LOCALE to use the current locale's decimal_point value.
- * #define SET_INEXACT if IEEE arithmetic is being used and extra
- * computation should be done to set the inexact flag when the
- * result is inexact and avoid setting inexact when the result
- * is exact. In this case, dtoa.c must be compiled in
- * an environment, perhaps provided by #include "dtoa.c" in a
- * suitable wrapper, that defines two functions,
- * int get_inexact(void);
- * void clear_inexact(void);
- * such that get_inexact() returns a nonzero value if the
- * inexact bit is already set, and clear_inexact() sets the
- * inexact bit to 0. When SET_INEXACT is #defined, strtod
- * also does extra computations to set the underflow and overflow
- * flags when appropriate (i.e., when the result is tiny and
- * inexact or when it is a numeric value rounded to +-infinity).
- * #define NO_ERRNO if strtod should not assign errno = ERANGE when
- * the result overflows to +-Infinity or underflows to 0.
- * #define NO_HEX_FP to omit recognition of hexadecimal floating-point
- * values by strtod.
- * #define NO_STRTOD_BIGCOMP (on IEEE-arithmetic systems only for now)
- * to disable logic for "fast" testing of very long input strings
- * to strtod. This testing proceeds by initially truncating the
- * input string, then if necessary comparing the whole string with
- * a decimal expansion to decide close cases. This logic is only
- * used for input more than STRTOD_DIGLIM digits long (default 40).
- */
-
-#define IEEE_8087
-#define NO_HEX_FP
-
-#ifndef Long
-#if __LP64__
-#define Long int
-#else
-#define Long long
-#endif
-#endif
-#ifndef ULong
-typedef unsigned Long ULong;
-#endif
-
-#ifdef DEBUG
-#include "stdio.h"
-#define Bug(x) {fprintf(stderr, "%s\n", x); exit(1);}
-#endif
-
-#include "stdlib.h"
-#include "string.h"
-
-#ifdef USE_LOCALE
-#include "locale.h"
-#endif
-
-#ifdef Honor_FLT_ROUNDS
-#ifndef Trust_FLT_ROUNDS
-#include <fenv.h>
-#endif
-#endif
-
-#ifdef MALLOC
-#ifdef KR_headers
-extern char *MALLOC();
-#else
-extern void *MALLOC(size_t);
-#endif
-#else
-#define MALLOC malloc
-#endif
-
-#ifndef Omit_Private_Memory
-#ifndef PRIVATE_MEM
-#define PRIVATE_MEM 2304
-#endif
-#define PRIVATE_mem ((unsigned)((PRIVATE_MEM+sizeof(double)-1)/sizeof(double)))
-static double private_mem[PRIVATE_mem], *pmem_next = private_mem;
-#endif
-
-#undef IEEE_Arith
-#undef Avoid_Underflow
-#ifdef IEEE_MC68k
-#define IEEE_Arith
-#endif
-#ifdef IEEE_8087
-#define IEEE_Arith
-#endif
-
-#ifdef IEEE_Arith
-#ifndef NO_INFNAN_CHECK
-#undef INFNAN_CHECK
-#define INFNAN_CHECK
-#endif
-#else
-#undef INFNAN_CHECK
-#define NO_STRTOD_BIGCOMP
-#endif
-
-#include "errno.h"
-
-#ifdef Bad_float_h
-
-#ifdef IEEE_Arith
-#define DBL_DIG 15
-#define DBL_MAX_10_EXP 308
-#define DBL_MAX_EXP 1024
-#define FLT_RADIX 2
-#endif /*IEEE_Arith*/
-
-#ifdef IBM
-#define DBL_DIG 16
-#define DBL_MAX_10_EXP 75
-#define DBL_MAX_EXP 63
-#define FLT_RADIX 16
-#define DBL_MAX 7.2370055773322621e+75
-#endif
-
-#ifdef VAX
-#define DBL_DIG 16
-#define DBL_MAX_10_EXP 38
-#define DBL_MAX_EXP 127
-#define FLT_RADIX 2
-#define DBL_MAX 1.7014118346046923e+38
-#endif
-
-#ifndef LONG_MAX
-#define LONG_MAX 2147483647
-#endif
-
-#else /* ifndef Bad_float_h */
-#include "float.h"
-#endif /* Bad_float_h */
-
-#ifndef __MATH_H__
-#include "math.h"
-#endif
-
-namespace dmg_fp {
-
-#ifndef CONST
-#ifdef KR_headers
-#define CONST /* blank */
-#else
-#define CONST const
-#endif
-#endif
-
-#if defined(IEEE_8087) + defined(IEEE_MC68k) + defined(VAX) + defined(IBM) != 1
-Exactly one of IEEE_8087, IEEE_MC68k, VAX, or IBM should be defined.
-#endif
-
-typedef union { double d; ULong L[2]; } U;
-
-#ifdef IEEE_8087
-#define word0(x) (x)->L[1]
-#define word1(x) (x)->L[0]
-#else
-#define word0(x) (x)->L[0]
-#define word1(x) (x)->L[1]
-#endif
-#define dval(x) (x)->d
-
-#ifndef STRTOD_DIGLIM
-#define STRTOD_DIGLIM 40
-#endif
-
-#ifdef DIGLIM_DEBUG
-extern int strtod_diglim;
-#else
-#define strtod_diglim STRTOD_DIGLIM
-#endif
-
-/* The following definition of Storeinc is appropriate for MIPS processors.
- * An alternative that might be better on some machines is
- * #define Storeinc(a,b,c) (*a++ = b << 16 | c & 0xffff)
- */
-#if defined(IEEE_8087) + defined(VAX)
-#define Storeinc(a,b,c) (((unsigned short *)a)[1] = (unsigned short)b, \
-((unsigned short *)a)[0] = (unsigned short)c, a++)
-#else
-#define Storeinc(a,b,c) (((unsigned short *)a)[0] = (unsigned short)b, \
-((unsigned short *)a)[1] = (unsigned short)c, a++)
-#endif
-
-/* #define P DBL_MANT_DIG */
-/* Ten_pmax = floor(P*log(2)/log(5)) */
-/* Bletch = (highest power of 2 < DBL_MAX_10_EXP) / 16 */
-/* Quick_max = floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
-/* Int_max = floor(P*log(FLT_RADIX)/log(10) - 1) */
-
-#ifdef IEEE_Arith
-#define Exp_shift 20
-#define Exp_shift1 20
-#define Exp_msk1 0x100000
-#define Exp_msk11 0x100000
-#define Exp_mask 0x7ff00000
-#define P 53
-#define Nbits 53
-#define Bias 1023
-#define Emax 1023
-#define Emin (-1022)
-#define Exp_1 0x3ff00000
-#define Exp_11 0x3ff00000
-#define Ebits 11
-#define Frac_mask 0xfffff
-#define Frac_mask1 0xfffff
-#define Ten_pmax 22
-#define Bletch 0x10
-#define Bndry_mask 0xfffff
-#define Bndry_mask1 0xfffff
-#define LSB 1
-#define Sign_bit 0x80000000
-#define Log2P 1
-#define Tiny0 0
-#define Tiny1 1
-#define Quick_max 14
-#define Int_max 14
-#ifndef NO_IEEE_Scale
-#define Avoid_Underflow
-#ifdef Flush_Denorm /* debugging option */
-#undef Sudden_Underflow
-#endif
-#endif
-
-#ifndef Flt_Rounds
-#ifdef FLT_ROUNDS
-#define Flt_Rounds FLT_ROUNDS
-#else
-#define Flt_Rounds 1
-#endif
-#endif /*Flt_Rounds*/
-
-#ifdef Honor_FLT_ROUNDS
-#undef Check_FLT_ROUNDS
-#define Check_FLT_ROUNDS
-#else
-#define Rounding Flt_Rounds
-#endif
-
-#else /* ifndef IEEE_Arith */
-#undef Check_FLT_ROUNDS
-#undef Honor_FLT_ROUNDS
-#undef SET_INEXACT
-#undef Sudden_Underflow
-#define Sudden_Underflow
-#ifdef IBM
-#undef Flt_Rounds
-#define Flt_Rounds 0
-#define Exp_shift 24
-#define Exp_shift1 24
-#define Exp_msk1 0x1000000
-#define Exp_msk11 0x1000000
-#define Exp_mask 0x7f000000
-#define P 14
-#define Nbits 56
-#define Bias 65
-#define Emax 248
-#define Emin (-260)
-#define Exp_1 0x41000000
-#define Exp_11 0x41000000
-#define Ebits 8 /* exponent has 7 bits, but 8 is the right value in b2d */
-#define Frac_mask 0xffffff
-#define Frac_mask1 0xffffff
-#define Bletch 4
-#define Ten_pmax 22
-#define Bndry_mask 0xefffff
-#define Bndry_mask1 0xffffff
-#define LSB 1
-#define Sign_bit 0x80000000
-#define Log2P 4
-#define Tiny0 0x100000
-#define Tiny1 0
-#define Quick_max 14
-#define Int_max 15
-#else /* VAX */
-#undef Flt_Rounds
-#define Flt_Rounds 1
-#define Exp_shift 23
-#define Exp_shift1 7
-#define Exp_msk1 0x80
-#define Exp_msk11 0x800000
-#define Exp_mask 0x7f80
-#define P 56
-#define Nbits 56
-#define Bias 129
-#define Emax 126
-#define Emin (-129)
-#define Exp_1 0x40800000
-#define Exp_11 0x4080
-#define Ebits 8
-#define Frac_mask 0x7fffff
-#define Frac_mask1 0xffff007f
-#define Ten_pmax 24
-#define Bletch 2
-#define Bndry_mask 0xffff007f
-#define Bndry_mask1 0xffff007f
-#define LSB 0x10000
-#define Sign_bit 0x8000
-#define Log2P 1
-#define Tiny0 0x80
-#define Tiny1 0
-#define Quick_max 15
-#define Int_max 15
-#endif /* IBM, VAX */
-#endif /* IEEE_Arith */
-
-#ifndef IEEE_Arith
-#define ROUND_BIASED
-#endif
-
-#ifdef RND_PRODQUOT
-#define rounded_product(a,b) a = rnd_prod(a, b)
-#define rounded_quotient(a,b) a = rnd_quot(a, b)
-#ifdef KR_headers
-extern double rnd_prod(), rnd_quot();
-#else
-extern double rnd_prod(double, double), rnd_quot(double, double);
-#endif
-#else
-#define rounded_product(a,b) a *= b
-#define rounded_quotient(a,b) a /= b
-#endif
-
-#define Big0 (Frac_mask1 | Exp_msk1*(DBL_MAX_EXP+Bias-1))
-#define Big1 0xffffffff
-
-#ifndef Pack_32
-#define Pack_32
-#endif
-
-typedef struct BCinfo BCinfo;
- struct
-BCinfo { int dp0, dp1, dplen, dsign, e0, inexact, nd, nd0, rounding, scale, uflchk; };
-
-#ifdef KR_headers
-#define FFFFFFFF ((((unsigned long)0xffff)<<16)|(unsigned long)0xffff)
-#else
-#define FFFFFFFF 0xffffffffUL
-#endif
-
-#ifdef NO_LONG_LONG
-#undef ULLong
-#ifdef Just_16
-#undef Pack_32
-/* When Pack_32 is not defined, we store 16 bits per 32-bit Long.
- * This makes some inner loops simpler and sometimes saves work
- * during multiplications, but it often seems to make things slightly
- * slower. Hence the default is now to store 32 bits per Long.
- */
-#endif
-#else /* long long available */
-#ifndef Llong
-#define Llong long long
-#endif
-#ifndef ULLong
-#define ULLong unsigned Llong
-#endif
-#endif /* NO_LONG_LONG */
-
-#ifndef MULTIPLE_THREADS
-#define ACQUIRE_DTOA_LOCK(n) /*nothing*/
-#define FREE_DTOA_LOCK(n) /*nothing*/
-#endif
-
-#define Kmax 7
-
-double strtod(const char *s00, char **se);
-char *dtoa(double d, int mode, int ndigits,
- int *decpt, int *sign, char **rve);
-
- struct
-Bigint {
- struct Bigint *next;
- int k, maxwds, sign, wds;
- ULong x[1];
- };
-
- typedef struct Bigint Bigint;
-
- static Bigint *freelist[Kmax+1];
-
- static Bigint *
-Balloc
-#ifdef KR_headers
- (k) int k;
-#else
- (int k)
-#endif
-{
- int x;
- Bigint *rv;
-#ifndef Omit_Private_Memory
- unsigned int len;
-#endif
-
- ACQUIRE_DTOA_LOCK(0);
- /* The k > Kmax case does not need ACQUIRE_DTOA_LOCK(0), */
- /* but this case seems very unlikely. */
- if (k <= Kmax && freelist[k]) {
- rv = freelist[k];
- freelist[k] = rv->next;
- }
- else {
- x = 1 << k;
-#ifdef Omit_Private_Memory
- rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong));
-#else
- len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
- /sizeof(double);
- if (k <= Kmax && pmem_next - private_mem + len <= PRIVATE_mem) {
- rv = (Bigint*)pmem_next;
- pmem_next += len;
- }
- else
- rv = (Bigint*)MALLOC(len*sizeof(double));
-#endif
- rv->k = k;
- rv->maxwds = x;
- }
- FREE_DTOA_LOCK(0);
- rv->sign = rv->wds = 0;
- return rv;
- }
-
- static void
-Bfree
-#ifdef KR_headers
- (v) Bigint *v;
-#else
- (Bigint *v)
-#endif
-{
- if (v) {
- if (v->k > Kmax)
-#ifdef FREE
- FREE((void*)v);
-#else
- free((void*)v);
-#endif
- else {
- ACQUIRE_DTOA_LOCK(0);
- v->next = freelist[v->k];
- freelist[v->k] = v;
- FREE_DTOA_LOCK(0);
- }
- }
- }
-
-#define Bcopy(x,y) memcpy((char *)&x->sign, (char *)&y->sign, \
-y->wds*sizeof(Long) + 2*sizeof(int))
-
- static Bigint *
-multadd
-#ifdef KR_headers
- (b, m, a) Bigint *b; int m, a;
-#else
- (Bigint *b, int m, int a) /* multiply by m and add a */
-#endif
-{
- int i, wds;
-#ifdef ULLong
- ULong *x;
- ULLong carry, y;
-#else
- ULong carry, *x, y;
-#ifdef Pack_32
- ULong xi, z;
-#endif
-#endif
- Bigint *b1;
-
- wds = b->wds;
- x = b->x;
- i = 0;
- carry = a;
- do {
-#ifdef ULLong
- y = *x * (ULLong)m + carry;
- carry = y >> 32;
- *x++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
- xi = *x;
- y = (xi & 0xffff) * m + carry;
- z = (xi >> 16) * m + (y >> 16);
- carry = z >> 16;
- *x++ = (z << 16) + (y & 0xffff);
-#else
- y = *x * m + carry;
- carry = y >> 16;
- *x++ = y & 0xffff;
-#endif
-#endif
- }
- while(++i < wds);
- if (carry) {
- if (wds >= b->maxwds) {
- b1 = Balloc(b->k+1);
- Bcopy(b1, b);
- Bfree(b);
- b = b1;
- }
- b->x[wds++] = (ULong)carry;
- b->wds = wds;
- }
- return b;
- }
-
- static Bigint *
-s2b
-#ifdef KR_headers
- (s, nd0, nd, y9, dplen) CONST char *s; int nd0, nd, dplen; ULong y9;
-#else
- (CONST char *s, int nd0, int nd, ULong y9, int dplen)
-#endif
-{
- Bigint *b;
- int i, k;
- Long x, y;
-
- x = (nd + 8) / 9;
- for(k = 0, y = 1; x > y; y <<= 1, k++) ;
-#ifdef Pack_32
- b = Balloc(k);
- b->x[0] = y9;
- b->wds = 1;
-#else
- b = Balloc(k+1);
- b->x[0] = y9 & 0xffff;
- b->wds = (b->x[1] = y9 >> 16) ? 2 : 1;
-#endif
-
- i = 9;
- if (9 < nd0) {
- s += 9;
- do b = multadd(b, 10, *s++ - '0');
- while(++i < nd0);
- s += dplen;
- }
- else
- s += dplen + 9;
- for(; i < nd; i++)
- b = multadd(b, 10, *s++ - '0');
- return b;
- }
-
- static int
-hi0bits
-#ifdef KR_headers
- (x) ULong x;
-#else
- (ULong x)
-#endif
-{
- int k = 0;
-
- if (!(x & 0xffff0000)) {
- k = 16;
- x <<= 16;
- }
- if (!(x & 0xff000000)) {
- k += 8;
- x <<= 8;
- }
- if (!(x & 0xf0000000)) {
- k += 4;
- x <<= 4;
- }
- if (!(x & 0xc0000000)) {
- k += 2;
- x <<= 2;
- }
- if (!(x & 0x80000000)) {
- k++;
- if (!(x & 0x40000000))
- return 32;
- }
- return k;
- }
-
- static int
-lo0bits
-#ifdef KR_headers
- (y) ULong *y;
-#else
- (ULong *y)
-#endif
-{
- int k;
- ULong x = *y;
-
- if (x & 7) {
- if (x & 1)
- return 0;
- if (x & 2) {
- *y = x >> 1;
- return 1;
- }
- *y = x >> 2;
- return 2;
- }
- k = 0;
- if (!(x & 0xffff)) {
- k = 16;
- x >>= 16;
- }
- if (!(x & 0xff)) {
- k += 8;
- x >>= 8;
- }
- if (!(x & 0xf)) {
- k += 4;
- x >>= 4;
- }
- if (!(x & 0x3)) {
- k += 2;
- x >>= 2;
- }
- if (!(x & 1)) {
- k++;
- x >>= 1;
- if (!x)
- return 32;
- }
- *y = x;
- return k;
- }
-
- static Bigint *
-i2b
-#ifdef KR_headers
- (i) int i;
-#else
- (int i)
-#endif
-{
- Bigint *b;
-
- b = Balloc(1);
- b->x[0] = i;
- b->wds = 1;
- return b;
- }
-
- static Bigint *
-mult
-#ifdef KR_headers
- (a, b) Bigint *a, *b;
-#else
- (Bigint *a, Bigint *b)
-#endif
-{
- Bigint *c;
- int k, wa, wb, wc;
- ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
- ULong y;
-#ifdef ULLong
- ULLong carry, z;
-#else
- ULong carry, z;
-#ifdef Pack_32
- ULong z2;
-#endif
-#endif
-
- if (a->wds < b->wds) {
- c = a;
- a = b;
- b = c;
- }
- k = a->k;
- wa = a->wds;
- wb = b->wds;
- wc = wa + wb;
- if (wc > a->maxwds)
- k++;
- c = Balloc(k);
- for(x = c->x, xa = x + wc; x < xa; x++)
- *x = 0;
- xa = a->x;
- xae = xa + wa;
- xb = b->x;
- xbe = xb + wb;
- xc0 = c->x;
-#ifdef ULLong
- for(; xb < xbe; xc0++) {
- y = *xb++;
- if (y) {
- x = xa;
- xc = xc0;
- carry = 0;
- do {
- z = *x++ * (ULLong)y + *xc + carry;
- carry = z >> 32;
- *xc++ = z & FFFFFFFF;
- }
- while(x < xae);
- *xc = (ULong)carry;
- }
- }
-#else
-#ifdef Pack_32
- for(; xb < xbe; xb++, xc0++) {
- if (y = *xb & 0xffff) {
- x = xa;
- xc = xc0;
- carry = 0;
- do {
- z = (*x & 0xffff) * y + (*xc & 0xffff) + carry;
- carry = z >> 16;
- z2 = (*x++ >> 16) * y + (*xc >> 16) + carry;
- carry = z2 >> 16;
- Storeinc(xc, z2, z);
- }
- while(x < xae);
- *xc = carry;
- }
- if (y = *xb >> 16) {
- x = xa;
- xc = xc0;
- carry = 0;
- z2 = *xc;
- do {
- z = (*x & 0xffff) * y + (*xc >> 16) + carry;
- carry = z >> 16;
- Storeinc(xc, z, z2);
- z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry;
- carry = z2 >> 16;
- }
- while(x < xae);
- *xc = z2;
- }
- }
-#else
- for(; xb < xbe; xc0++) {
- if (y = *xb++) {
- x = xa;
- xc = xc0;
- carry = 0;
- do {
- z = *x++ * y + *xc + carry;
- carry = z >> 16;
- *xc++ = z & 0xffff;
- }
- while(x < xae);
- *xc = carry;
- }
- }
-#endif
-#endif
- for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ;
- c->wds = wc;
- return c;
- }
-
- static Bigint *p5s;
-
- static Bigint *
-pow5mult
-#ifdef KR_headers
- (b, k) Bigint *b; int k;
-#else
- (Bigint *b, int k)
-#endif
-{
- Bigint *b1, *p5, *p51;
- int i;
- static int p05[3] = { 5, 25, 125 };
-
- i = k & 3;
- if (i)
- b = multadd(b, p05[i-1], 0);
-
- if (!(k >>= 2))
- return b;
- p5 = p5s;
- if (!p5) {
- /* first time */
-#ifdef MULTIPLE_THREADS
- ACQUIRE_DTOA_LOCK(1);
- p5 = p5s;
- if (!p5) {
- p5 = p5s = i2b(625);
- p5->next = 0;
- }
- FREE_DTOA_LOCK(1);
-#else
- p5 = p5s = i2b(625);
- p5->next = 0;
-#endif
- }
- for(;;) {
- if (k & 1) {
- b1 = mult(b, p5);
- Bfree(b);
- b = b1;
- }
- if (!(k >>= 1))
- break;
- p51 = p5->next;
- if (!p51) {
-#ifdef MULTIPLE_THREADS
- ACQUIRE_DTOA_LOCK(1);
- p51 = p5->next;
- if (!p51) {
- p51 = p5->next = mult(p5,p5);
- p51->next = 0;
- }
- FREE_DTOA_LOCK(1);
-#else
- p51 = p5->next = mult(p5,p5);
- p51->next = 0;
-#endif
- }
- p5 = p51;
- }
- return b;
- }
-
- static Bigint *
-lshift
-#ifdef KR_headers
- (b, k) Bigint *b; int k;
-#else
- (Bigint *b, int k)
-#endif
-{
- int i, k1, n, n1;
- Bigint *b1;
- ULong *x, *x1, *xe, z;
-
-#ifdef Pack_32
- n = k >> 5;
-#else
- n = k >> 4;
-#endif
- k1 = b->k;
- n1 = n + b->wds + 1;
- for(i = b->maxwds; n1 > i; i <<= 1)
- k1++;
- b1 = Balloc(k1);
- x1 = b1->x;
- for(i = 0; i < n; i++)
- *x1++ = 0;
- x = b->x;
- xe = x + b->wds;
-#ifdef Pack_32
- if (k &= 0x1f) {
- k1 = 32 - k;
- z = 0;
- do {
- *x1++ = *x << k | z;
- z = *x++ >> k1;
- }
- while(x < xe);
- *x1 = z;
- if (*x1)
- ++n1;
- }
-#else
- if (k &= 0xf) {
- k1 = 16 - k;
- z = 0;
- do {
- *x1++ = *x << k & 0xffff | z;
- z = *x++ >> k1;
- }
- while(x < xe);
- if (*x1 = z)
- ++n1;
- }
-#endif
- else do
- *x1++ = *x++;
- while(x < xe);
- b1->wds = n1 - 1;
- Bfree(b);
- return b1;
- }
-
- static int
-cmp
-#ifdef KR_headers
- (a, b) Bigint *a, *b;
-#else
- (Bigint *a, Bigint *b)
-#endif
-{
- ULong *xa, *xa0, *xb, *xb0;
- int i, j;
-
- i = a->wds;
- j = b->wds;
-#ifdef DEBUG
- if (i > 1 && !a->x[i-1])
- Bug("cmp called with a->x[a->wds-1] == 0");
- if (j > 1 && !b->x[j-1])
- Bug("cmp called with b->x[b->wds-1] == 0");
-#endif
- if (i -= j)
- return i;
- xa0 = a->x;
- xa = xa0 + j;
- xb0 = b->x;
- xb = xb0 + j;
- for(;;) {
- if (*--xa != *--xb)
- return *xa < *xb ? -1 : 1;
- if (xa <= xa0)
- break;
- }
- return 0;
- }
-
- static Bigint *
-diff
-#ifdef KR_headers
- (a, b) Bigint *a, *b;
-#else
- (Bigint *a, Bigint *b)
-#endif
-{
- Bigint *c;
- int i, wa, wb;
- ULong *xa, *xae, *xb, *xbe, *xc;
-#ifdef ULLong
- ULLong borrow, y;
-#else
- ULong borrow, y;
-#ifdef Pack_32
- ULong z;
-#endif
-#endif
-
- i = cmp(a,b);
- if (!i) {
- c = Balloc(0);
- c->wds = 1;
- c->x[0] = 0;
- return c;
- }
- if (i < 0) {
- c = a;
- a = b;
- b = c;
- i = 1;
- }
- else
- i = 0;
- c = Balloc(a->k);
- c->sign = i;
- wa = a->wds;
- xa = a->x;
- xae = xa + wa;
- wb = b->wds;
- xb = b->x;
- xbe = xb + wb;
- xc = c->x;
- borrow = 0;
-#ifdef ULLong
- do {
- y = (ULLong)*xa++ - *xb++ - borrow;
- borrow = y >> 32 & (ULong)1;
- *xc++ = y & FFFFFFFF;
- }
- while(xb < xbe);
- while(xa < xae) {
- y = *xa++ - borrow;
- borrow = y >> 32 & (ULong)1;
- *xc++ = y & FFFFFFFF;
- }
-#else
-#ifdef Pack_32
- do {
- y = (*xa & 0xffff) - (*xb & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- z = (*xa++ >> 16) - (*xb++ >> 16) - borrow;
- borrow = (z & 0x10000) >> 16;
- Storeinc(xc, z, y);
- }
- while(xb < xbe);
- while(xa < xae) {
- y = (*xa & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- z = (*xa++ >> 16) - borrow;
- borrow = (z & 0x10000) >> 16;
- Storeinc(xc, z, y);
- }
-#else
- do {
- y = *xa++ - *xb++ - borrow;
- borrow = (y & 0x10000) >> 16;
- *xc++ = y & 0xffff;
- }
- while(xb < xbe);
- while(xa < xae) {
- y = *xa++ - borrow;
- borrow = (y & 0x10000) >> 16;
- *xc++ = y & 0xffff;
- }
-#endif
-#endif
- while(!*--xc)
- wa--;
- c->wds = wa;
- return c;
- }
-
- static double
-ulp
-#ifdef KR_headers
- (x) U *x;
-#else
- (U *x)
-#endif
-{
- Long L;
- U u;
-
- L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1;
-#ifndef Avoid_Underflow
-#ifndef Sudden_Underflow
- if (L > 0) {
-#endif
-#endif
-#ifdef IBM
- L |= Exp_msk1 >> 4;
-#endif
- word0(&u) = L;
- word1(&u) = 0;
-#ifndef Avoid_Underflow
-#ifndef Sudden_Underflow
- }
- else {
- L = -L >> Exp_shift;
- if (L < Exp_shift) {
- word0(&u) = 0x80000 >> L;
- word1(&u) = 0;
- }
- else {
- word0(&u) = 0;
- L -= Exp_shift;
- word1(&u) = L >= 31 ? 1 : 1 << 31 - L;
- }
- }
-#endif
-#endif
- return dval(&u);
- }
-
- static double
-b2d
-#ifdef KR_headers
- (a, e) Bigint *a; int *e;
-#else
- (Bigint *a, int *e)
-#endif
-{
- ULong *xa, *xa0, w, y, z;
- int k;
- U d;
-#ifdef VAX
- ULong d0, d1;
-#else
-#define d0 word0(&d)
-#define d1 word1(&d)
-#endif
-
- xa0 = a->x;
- xa = xa0 + a->wds;
- y = *--xa;
-#ifdef DEBUG
- if (!y) Bug("zero y in b2d");
-#endif
- k = hi0bits(y);
- *e = 32 - k;
-#ifdef Pack_32
- if (k < Ebits) {
- d0 = Exp_1 | y >> (Ebits - k);
- w = xa > xa0 ? *--xa : 0;
- d1 = y << ((32-Ebits) + k) | w >> (Ebits - k);
- goto ret_d;
- }
- z = xa > xa0 ? *--xa : 0;
- if (k -= Ebits) {
- d0 = Exp_1 | y << k | z >> (32 - k);
- y = xa > xa0 ? *--xa : 0;
- d1 = z << k | y >> (32 - k);
- }
- else {
- d0 = Exp_1 | y;
- d1 = z;
- }
-#else
- if (k < Ebits + 16) {
- z = xa > xa0 ? *--xa : 0;
- d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k;
- w = xa > xa0 ? *--xa : 0;
- y = xa > xa0 ? *--xa : 0;
- d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k;
- goto ret_d;
- }
- z = xa > xa0 ? *--xa : 0;
- w = xa > xa0 ? *--xa : 0;
- k -= Ebits + 16;
- d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k;
- y = xa > xa0 ? *--xa : 0;
- d1 = w << k + 16 | y << k;
-#endif
- ret_d:
-#ifdef VAX
- word0(&d) = d0 >> 16 | d0 << 16;
- word1(&d) = d1 >> 16 | d1 << 16;
-#else
-#undef d0
-#undef d1
-#endif
- return dval(&d);
- }
-
- static Bigint *
-d2b
-#ifdef KR_headers
- (d, e, bits) U *d; int *e, *bits;
-#else
- (U *d, int *e, int *bits)
-#endif
-{
- Bigint *b;
- int de, k;
- ULong *x, y, z;
-#ifndef Sudden_Underflow
- int i;
-#endif
-#ifdef VAX
- ULong d0, d1;
- d0 = word0(d) >> 16 | word0(d) << 16;
- d1 = word1(d) >> 16 | word1(d) << 16;
-#else
-#define d0 word0(d)
-#define d1 word1(d)
-#endif
-
-#ifdef Pack_32
- b = Balloc(1);
-#else
- b = Balloc(2);
-#endif
- x = b->x;
-
- z = d0 & Frac_mask;
- d0 &= 0x7fffffff; /* clear sign bit, which we ignore */
-#ifdef Sudden_Underflow
- de = (int)(d0 >> Exp_shift);
-#ifndef IBM
- z |= Exp_msk11;
-#endif
-#else
- de = (int)(d0 >> Exp_shift);
- if (de)
- z |= Exp_msk1;
-#endif
-#ifdef Pack_32
- y = d1;
- if (y) {
- k = lo0bits(&y);
- if (k) {
- x[0] = y | z << (32 - k);
- z >>= k;
- }
- else
- x[0] = y;
- x[1] = z;
- b->wds = x[1] ? 2 : 1;
-#ifndef Sudden_Underflow
- i = b->wds;
-#endif
- }
- else {
- k = lo0bits(&z);
- x[0] = z;
-#ifndef Sudden_Underflow
- i =
-#endif
- b->wds = 1;
- k += 32;
- }
-#else
- if (y = d1) {
- if (k = lo0bits(&y))
- if (k >= 16) {
- x[0] = y | z << 32 - k & 0xffff;
- x[1] = z >> k - 16 & 0xffff;
- x[2] = z >> k;
- i = 2;
- }
- else {
- x[0] = y & 0xffff;
- x[1] = y >> 16 | z << 16 - k & 0xffff;
- x[2] = z >> k & 0xffff;
- x[3] = z >> k+16;
- i = 3;
- }
- else {
- x[0] = y & 0xffff;
- x[1] = y >> 16;
- x[2] = z & 0xffff;
- x[3] = z >> 16;
- i = 3;
- }
- }
- else {
-#ifdef DEBUG
- if (!z)
- Bug("Zero passed to d2b");
-#endif
- k = lo0bits(&z);
- if (k >= 16) {
- x[0] = z;
- i = 0;
- }
- else {
- x[0] = z & 0xffff;
- x[1] = z >> 16;
- i = 1;
- }
- k += 32;
- }
- while(!x[i])
- --i;
- b->wds = i + 1;
-#endif
-#ifndef Sudden_Underflow
- if (de) {
-#endif
-#ifdef IBM
- *e = (de - Bias - (P-1) << 2) + k;
- *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask);
-#else
- *e = de - Bias - (P-1) + k;
- *bits = P - k;
-#endif
-#ifndef Sudden_Underflow
- }
- else {
- *e = de - Bias - (P-1) + 1 + k;
-#ifdef Pack_32
- *bits = 32*i - hi0bits(x[i-1]);
-#else
- *bits = (i+2)*16 - hi0bits(x[i]);
-#endif
- }
-#endif
- return b;
- }
-#undef d0
-#undef d1
-
- static double
-ratio
-#ifdef KR_headers
- (a, b) Bigint *a, *b;
-#else
- (Bigint *a, Bigint *b)
-#endif
-{
- U da, db;
- int k, ka, kb;
-
- dval(&da) = b2d(a, &ka);
- dval(&db) = b2d(b, &kb);
-#ifdef Pack_32
- k = ka - kb + 32*(a->wds - b->wds);
-#else
- k = ka - kb + 16*(a->wds - b->wds);
-#endif
-#ifdef IBM
- if (k > 0) {
- word0(&da) += (k >> 2)*Exp_msk1;
- if (k &= 3)
- dval(&da) *= 1 << k;
- }
- else {
- k = -k;
- word0(&db) += (k >> 2)*Exp_msk1;
- if (k &= 3)
- dval(&db) *= 1 << k;
- }
-#else
- if (k > 0)
- word0(&da) += k*Exp_msk1;
- else {
- k = -k;
- word0(&db) += k*Exp_msk1;
- }
-#endif
- return dval(&da) / dval(&db);
- }
-
- static CONST double
-tens[] = {
- 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
- 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
- 1e20, 1e21, 1e22
-#ifdef VAX
- , 1e23, 1e24
-#endif
- };
-
- static CONST double
-#ifdef IEEE_Arith
-bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 };
-static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128,
-#ifdef Avoid_Underflow
- 9007199254740992.*9007199254740992.e-256
- /* = 2^106 * 1e-256 */
-#else
- 1e-256
-#endif
- };
-/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */
-/* flag unnecessarily. It leads to a song and dance at the end of strtod. */
-#define Scale_Bit 0x10
-#define n_bigtens 5
-#else
-#ifdef IBM
-bigtens[] = { 1e16, 1e32, 1e64 };
-static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 };
-#define n_bigtens 3
-#else
-bigtens[] = { 1e16, 1e32 };
-static CONST double tinytens[] = { 1e-16, 1e-32 };
-#define n_bigtens 2
-#endif
-#endif
-
-#undef Need_Hexdig
-#ifdef INFNAN_CHECK
-#ifndef No_Hex_NaN
-#define Need_Hexdig
-#endif
-#endif
-
-#ifndef Need_Hexdig
-#ifndef NO_HEX_FP
-#define Need_Hexdig
-#endif
-#endif
-
-#ifdef Need_Hexdig /*{*/
-static unsigned char hexdig[256];
-
- static void
-#ifdef KR_headers
-htinit(h, s, inc) unsigned char *h; unsigned char *s; int inc;
-#else
-htinit(unsigned char *h, unsigned char *s, int inc)
-#endif
-{
- int i, j;
- for(i = 0; (j = s[i]) !=0; i++)
- h[j] = (unsigned char)(i + inc);
- }
-
- static void
-#ifdef KR_headers
-hexdig_init()
-#else
-hexdig_init(void)
-#endif
-{
-#define USC (unsigned char *)
- htinit(hexdig, USC "0123456789", 0x10);
- htinit(hexdig, USC "abcdef", 0x10 + 10);
- htinit(hexdig, USC "ABCDEF", 0x10 + 10);
- }
-#endif /* } Need_Hexdig */
-
-#ifdef INFNAN_CHECK
-
-#ifndef NAN_WORD0
-#define NAN_WORD0 0x7ff80000
-#endif
-
-#ifndef NAN_WORD1
-#define NAN_WORD1 0
-#endif
-
- static int
-match
-#ifdef KR_headers
- (sp, t) char **sp, *t;
-#else
- (CONST char **sp, CONST char *t)
-#endif
-{
- int c, d;
- CONST char *s = *sp;
-
- for(d = *t++; d; d = *t++) {
- if ((c = *++s) >= 'A' && c <= 'Z')
- c += 'a' - 'A';
- if (c != d)
- return 0;
- }
- *sp = s + 1;
- return 1;
- }
-
-#ifndef No_Hex_NaN
- static void
-hexnan
-#ifdef KR_headers
- (rvp, sp) U *rvp; CONST char **sp;
-#else
- (U *rvp, CONST char **sp)
-#endif
-{
- ULong c, x[2];
- CONST char *s;
- int c1, havedig, udx0, xshift;
-
- if (!hexdig['0'])
- hexdig_init();
- x[0] = x[1] = 0;
- havedig = xshift = 0;
- udx0 = 1;
- s = *sp;
- /* allow optional initial 0x or 0X */
- for(c = *(CONST unsigned char*)(s+1); c && c <= ' '; c = *(CONST unsigned char*)(s+1))
- ++s;
- if (s[1] == '0' && (s[2] == 'x' || s[2] == 'X'))
- s += 2;
- for(c = *(CONST unsigned char*)++s; c; c = *(CONST unsigned char*)++s) {
- c1 = hexdig[c];
- if (c1)
- c = c1 & 0xf;
- else if (c <= ' ') {
- if (udx0 && havedig) {
- udx0 = 0;
- xshift = 1;
- }
- continue;
- }
-#ifdef GDTOA_NON_PEDANTIC_NANCHECK
- else if (/*(*/ c == ')' && havedig) {
- *sp = s + 1;
- break;
- }
- else
- return; /* invalid form: don't change *sp */
-#else
- else {
- do {
- if (/*(*/ c == ')') {
- *sp = s + 1;
- break;
- }
- c = *++s;
- } while(c);
- break;
- }
-#endif
- havedig = 1;
- if (xshift) {
- xshift = 0;
- x[0] = x[1];
- x[1] = 0;
- }
- if (udx0)
- x[0] = (x[0] << 4) | (x[1] >> 28);
- x[1] = (x[1] << 4) | c;
- }
- if ((x[0] &= 0xfffff) || x[1]) {
- word0(rvp) = Exp_mask | x[0];
- word1(rvp) = x[1];
- }
- }
-#endif /*No_Hex_NaN*/
-#endif /* INFNAN_CHECK */
-
-#ifdef Pack_32
-#define ULbits 32
-#define kshift 5
-#define kmask 31
-#else
-#define ULbits 16
-#define kshift 4
-#define kmask 15
-#endif
-#ifndef NO_HEX_FP /*{*/
-
- static void
-#ifdef KR_headers
-rshift(b, k) Bigint *b; int k;
-#else
-rshift(Bigint *b, int k)
-#endif
-{
- ULong *x, *x1, *xe, y;
- int n;
-
- x = x1 = b->x;
- n = k >> kshift;
- if (n < b->wds) {
- xe = x + b->wds;
- x += n;
- if (k &= kmask) {
- n = 32 - k;
- y = *x++ >> k;
- while(x < xe) {
- *x1++ = (y | (*x << n)) & 0xffffffff;
- y = *x++ >> k;
- }
- if ((*x1 = y) !=0)
- x1++;
- }
- else
- while(x < xe)
- *x1++ = *x++;
- }
- if ((b->wds = x1 - b->x) == 0)
- b->x[0] = 0;
- }
-
- static ULong
-#ifdef KR_headers
-any_on(b, k) Bigint *b; int k;
-#else
-any_on(Bigint *b, int k)
-#endif
-{
- int n, nwds;
- ULong *x, *x0, x1, x2;
-
- x = b->x;
- nwds = b->wds;
- n = k >> kshift;
- if (n > nwds)
- n = nwds;
- else if (n < nwds && (k &= kmask)) {
- x1 = x2 = x[n];
- x1 >>= k;
- x1 <<= k;
- if (x1 != x2)
- return 1;
- }
- x0 = x;
- x += n;
- while(x > x0)
- if (*--x)
- return 1;
- return 0;
- }
-
-enum { /* rounding values: same as FLT_ROUNDS */
- Round_zero = 0,
- Round_near = 1,
- Round_up = 2,
- Round_down = 3
- };
-
- static Bigint *
-#ifdef KR_headers
-increment(b) Bigint *b;
-#else
-increment(Bigint *b)
-#endif
-{
- ULong *x, *xe;
- Bigint *b1;
-
- x = b->x;
- xe = x + b->wds;
- do {
- if (*x < (ULong)0xffffffffL) {
- ++*x;
- return b;
- }
- *x++ = 0;
- } while(x < xe);
- {
- if (b->wds >= b->maxwds) {
- b1 = Balloc(b->k+1);
- Bcopy(b1,b);
- Bfree(b);
- b = b1;
- }
- b->x[b->wds++] = 1;
- }
- return b;
- }
-
- void
-#ifdef KR_headers
-gethex(sp, rvp, rounding, sign)
- CONST char **sp; U *rvp; int rounding, sign;
-#else
-gethex( CONST char **sp, U *rvp, int rounding, int sign)
-#endif
-{
- Bigint *b;
- CONST unsigned char *decpt, *s0, *s, *s1;
- Long e, e1;
- ULong L, lostbits, *x;
- int big, denorm, esign, havedig, k, n, nbits, up, zret;
-#ifdef IBM
- int j;
-#endif
- enum {
-#ifdef IEEE_Arith /*{{*/
- emax = 0x7fe - Bias - P + 1,
- emin = Emin - P + 1
-#else /*}{*/
- emin = Emin - P,
-#ifdef VAX
- emax = 0x7ff - Bias - P + 1
-#endif
-#ifdef IBM
- emax = 0x7f - Bias - P
-#endif
-#endif /*}}*/
- };
-#ifdef USE_LOCALE
- int i;
-#ifdef NO_LOCALE_CACHE
- const unsigned char *decimalpoint = (unsigned char*)
- localeconv()->decimal_point;
-#else
- const unsigned char *decimalpoint;
- static unsigned char *decimalpoint_cache;
- if (!(s0 = decimalpoint_cache)) {
- s0 = (unsigned char*)localeconv()->decimal_point;
- if ((decimalpoint_cache = (unsigned char*)
- MALLOC(strlen((CONST char*)s0) + 1))) {
- strcpy((char*)decimalpoint_cache, (CONST char*)s0);
- s0 = decimalpoint_cache;
- }
- }
- decimalpoint = s0;
-#endif
-#endif
-
- if (!hexdig['0'])
- hexdig_init();
- havedig = 0;
- s0 = *(CONST unsigned char **)sp + 2;
- while(s0[havedig] == '0')
- havedig++;
- s0 += havedig;
- s = s0;
- decpt = 0;
- zret = 0;
- e = 0;
- if (hexdig[*s])
- havedig++;
- else {
- zret = 1;
-#ifdef USE_LOCALE
- for(i = 0; decimalpoint[i]; ++i) {
- if (s[i] != decimalpoint[i])
- goto pcheck;
- }
- decpt = s += i;
-#else
- if (*s != '.')
- goto pcheck;
- decpt = ++s;
-#endif
- if (!hexdig[*s])
- goto pcheck;
- while(*s == '0')
- s++;
- if (hexdig[*s])
- zret = 0;
- havedig = 1;
- s0 = s;
- }
- while(hexdig[*s])
- s++;
-#ifdef USE_LOCALE
- if (*s == *decimalpoint && !decpt) {
- for(i = 1; decimalpoint[i]; ++i) {
- if (s[i] != decimalpoint[i])
- goto pcheck;
- }
- decpt = s += i;
-#else
- if (*s == '.' && !decpt) {
- decpt = ++s;
-#endif
- while(hexdig[*s])
- s++;
- }/*}*/
- if (decpt)
- e = -(((Long)(s-decpt)) << 2);
- pcheck:
- s1 = s;
- big = esign = 0;
- switch(*s) {
- case 'p':
- case 'P':
- switch(*++s) {
- case '-':
- esign = 1;
- /* no break */
- case '+':
- s++;
- }
- if ((n = hexdig[*s]) == 0 || n > 0x19) {
- s = s1;
- break;
- }
- e1 = n - 0x10;
- while((n = hexdig[*++s]) !=0 && n <= 0x19) {
- if (e1 & 0xf8000000)
- big = 1;
- e1 = 10*e1 + n - 0x10;
- }
- if (esign)
- e1 = -e1;
- e += e1;
- }
- *sp = (char*)s;
- if (!havedig)
- *sp = (char*)s0 - 1;
- if (zret)
- goto retz1;
- if (big) {
- if (esign) {
-#ifdef IEEE_Arith
- switch(rounding) {
- case Round_up:
- if (sign)
- break;
- goto ret_tiny;
- case Round_down:
- if (!sign)
- break;
- goto ret_tiny;
- }
-#endif
- goto retz;
-#ifdef IEEE_Arith
- ret_tiny:
-#ifndef NO_ERRNO
- errno = ERANGE;
-#endif
- word0(rvp) = 0;
- word1(rvp) = 1;
- return;
-#endif /* IEEE_Arith */
- }
- switch(rounding) {
- case Round_near:
- goto ovfl1;
- case Round_up:
- if (!sign)
- goto ovfl1;
- goto ret_big;
- case Round_down:
- if (sign)
- goto ovfl1;
- goto ret_big;
- }
- ret_big:
- word0(rvp) = Big0;
- word1(rvp) = Big1;
- return;
- }
- n = s1 - s0 - 1;
- for(k = 0; n > (1 << (kshift-2)) - 1; n >>= 1)
- k++;
- b = Balloc(k);
- x = b->x;
- n = 0;
- L = 0;
-#ifdef USE_LOCALE
- for(i = 0; decimalpoint[i+1]; ++i);
-#endif
- while(s1 > s0) {
-#ifdef USE_LOCALE
- if (*--s1 == decimalpoint[i]) {
- s1 -= i;
- continue;
- }
-#else
- if (*--s1 == '.')
- continue;
-#endif
- if (n == ULbits) {
- *x++ = L;
- L = 0;
- n = 0;
- }
- L |= (hexdig[*s1] & 0x0f) << n;
- n += 4;
- }
- *x++ = L;
- b->wds = n = x - b->x;
- n = ULbits*n - hi0bits(L);
- nbits = Nbits;
- lostbits = 0;
- x = b->x;
- if (n > nbits) {
- n -= nbits;
- if (any_on(b,n)) {
- lostbits = 1;
- k = n - 1;
- if (x[k>>kshift] & 1 << (k & kmask)) {
- lostbits = 2;
- if (k > 0 && any_on(b,k))
- lostbits = 3;
- }
- }
- rshift(b, n);
- e += n;
- }
- else if (n < nbits) {
- n = nbits - n;
- b = lshift(b, n);
- e -= n;
- x = b->x;
- }
- if (e > Emax) {
- ovfl:
- Bfree(b);
- ovfl1:
-#ifndef NO_ERRNO
- errno = ERANGE;
-#endif
- word0(rvp) = Exp_mask;
- word1(rvp) = 0;
- return;
- }
- denorm = 0;
- if (e < emin) {
- denorm = 1;
- n = emin - e;
- if (n >= nbits) {
-#ifdef IEEE_Arith /*{*/
- switch (rounding) {
- case Round_near:
- if (n == nbits && (n < 2 || any_on(b,n-1)))
- goto ret_tiny;
- break;
- case Round_up:
- if (!sign)
- goto ret_tiny;
- break;
- case Round_down:
- if (sign)
- goto ret_tiny;
- }
-#endif /* } IEEE_Arith */
- Bfree(b);
- retz:
-#ifndef NO_ERRNO
- errno = ERANGE;
-#endif
- retz1:
- rvp->d = 0.;
- return;
- }
- k = n - 1;
- if (lostbits)
- lostbits = 1;
- else if (k > 0)
- lostbits = any_on(b,k);
- if (x[k>>kshift] & 1 << (k & kmask))
- lostbits |= 2;
- nbits -= n;
- rshift(b,n);
- e = emin;
- }
- if (lostbits) {
- up = 0;
- switch(rounding) {
- case Round_zero:
- break;
- case Round_near:
- if (lostbits & 2
- && (lostbits & 1) | (x[0] & 1))
- up = 1;
- break;
- case Round_up:
- up = 1 - sign;
- break;
- case Round_down:
- up = sign;
- }
- if (up) {
- k = b->wds;
- b = increment(b);
- x = b->x;
- if (denorm) {
-#if 0
- if (nbits == Nbits - 1
- && x[nbits >> kshift] & 1 << (nbits & kmask))
- denorm = 0; /* not currently used */
-#endif
- }
- else if (b->wds > k
- || ((n = nbits & kmask) !=0
- && hi0bits(x[k-1]) < 32-n)) {
- rshift(b,1);
- if (++e > Emax)
- goto ovfl;
- }
- }
- }
-#ifdef IEEE_Arith
- if (denorm)
- word0(rvp) = b->wds > 1 ? b->x[1] & ~0x100000 : 0;
- else
- word0(rvp) = (b->x[1] & ~0x100000) | ((e + 0x3ff + 52) << 20);
- word1(rvp) = b->x[0];
-#endif
-#ifdef IBM
- if ((j = e & 3)) {
- k = b->x[0] & ((1 << j) - 1);
- rshift(b,j);
- if (k) {
- switch(rounding) {
- case Round_up:
- if (!sign)
- increment(b);
- break;
- case Round_down:
- if (sign)
- increment(b);
- break;
- case Round_near:
- j = 1 << (j-1);
- if (k & j && ((k & (j-1)) | lostbits))
- increment(b);
- }
- }
- }
- e >>= 2;
- word0(rvp) = b->x[1] | ((e + 65 + 13) << 24);
- word1(rvp) = b->x[0];
-#endif
-#ifdef VAX
- /* The next two lines ignore swap of low- and high-order 2 bytes. */
- /* word0(rvp) = (b->x[1] & ~0x800000) | ((e + 129 + 55) << 23); */
- /* word1(rvp) = b->x[0]; */
- word0(rvp) = ((b->x[1] & ~0x800000) >> 16) | ((e + 129 + 55) << 7) | (b->x[1] << 16);
- word1(rvp) = (b->x[0] >> 16) | (b->x[0] << 16);
-#endif
- Bfree(b);
- }
-#endif /*}!NO_HEX_FP*/
-
- static int
-#ifdef KR_headers
-dshift(b, p2) Bigint *b; int p2;
-#else
-dshift(Bigint *b, int p2)
-#endif
-{
- int rv = hi0bits(b->x[b->wds-1]) - 4;
- if (p2 > 0)
- rv -= p2;
- return rv & kmask;
- }
-
- static int
-quorem
-#ifdef KR_headers
- (b, S) Bigint *b, *S;
-#else
- (Bigint *b, Bigint *S)
-#endif
-{
- int n;
- ULong *bx, *bxe, q, *sx, *sxe;
-#ifdef ULLong
- ULLong borrow, carry, y, ys;
-#else
- ULong borrow, carry, y, ys;
-#ifdef Pack_32
- ULong si, z, zs;
-#endif
-#endif
-
- n = S->wds;
-#ifdef DEBUG
- /*debug*/ if (b->wds > n)
- /*debug*/ Bug("oversize b in quorem");
-#endif
- if (b->wds < n)
- return 0;
- sx = S->x;
- sxe = sx + --n;
- bx = b->x;
- bxe = bx + n;
- q = *bxe / (*sxe + 1); /* ensure q <= true quotient */
-#ifdef DEBUG
- /*debug*/ if (q > 9)
- /*debug*/ Bug("oversized quotient in quorem");
-#endif
- if (q) {
- borrow = 0;
- carry = 0;
- do {
-#ifdef ULLong
- ys = *sx++ * (ULLong)q + carry;
- carry = ys >> 32;
- y = *bx - (ys & FFFFFFFF) - borrow;
- borrow = y >> 32 & (ULong)1;
- *bx++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
- si = *sx++;
- ys = (si & 0xffff) * q + carry;
- zs = (si >> 16) * q + (ys >> 16);
- carry = zs >> 16;
- y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- z = (*bx >> 16) - (zs & 0xffff) - borrow;
- borrow = (z & 0x10000) >> 16;
- Storeinc(bx, z, y);
-#else
- ys = *sx++ * q + carry;
- carry = ys >> 16;
- y = *bx - (ys & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- *bx++ = y & 0xffff;
-#endif
-#endif
- }
- while(sx <= sxe);
- if (!*bxe) {
- bx = b->x;
- while(--bxe > bx && !*bxe)
- --n;
- b->wds = n;
- }
- }
- if (cmp(b, S) >= 0) {
- q++;
- borrow = 0;
- carry = 0;
- bx = b->x;
- sx = S->x;
- do {
-#ifdef ULLong
- ys = *sx++ + carry;
- carry = ys >> 32;
- y = *bx - (ys & FFFFFFFF) - borrow;
- borrow = y >> 32 & (ULong)1;
- *bx++ = y & FFFFFFFF;
-#else
-#ifdef Pack_32
- si = *sx++;
- ys = (si & 0xffff) + carry;
- zs = (si >> 16) + (ys >> 16);
- carry = zs >> 16;
- y = (*bx & 0xffff) - (ys & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- z = (*bx >> 16) - (zs & 0xffff) - borrow;
- borrow = (z & 0x10000) >> 16;
- Storeinc(bx, z, y);
-#else
- ys = *sx++ + carry;
- carry = ys >> 16;
- y = *bx - (ys & 0xffff) - borrow;
- borrow = (y & 0x10000) >> 16;
- *bx++ = y & 0xffff;
-#endif
-#endif
- }
- while(sx <= sxe);
- bx = b->x;
- bxe = bx + n;
- if (!*bxe) {
- while(--bxe > bx && !*bxe)
- --n;
- b->wds = n;
- }
- }
- return q;
- }
-
-#ifndef NO_STRTOD_BIGCOMP
-
- static void
-bigcomp
-#ifdef KR_headers
- (rv, s0, bc)
- U *rv; CONST char *s0; BCinfo *bc;
-#else
- (U *rv, CONST char *s0, BCinfo *bc)
-#endif
-{
- Bigint *b, *d;
- int b2, bbits, d2, dd, dig, dsign, i, j, nd, nd0, p2, p5, speccase;
-
- dsign = bc->dsign;
- nd = bc->nd;
- nd0 = bc->nd0;
- p5 = nd + bc->e0 - 1;
- dd = speccase = 0;
-#ifndef Sudden_Underflow
- if (rv->d == 0.) { /* special case: value near underflow-to-zero */
- /* threshold was rounded to zero */
- b = i2b(1);
- p2 = Emin - P + 1;
- bbits = 1;
-#ifdef Avoid_Underflow
- word0(rv) = (P+2) << Exp_shift;
-#else
- word1(rv) = 1;
-#endif
- i = 0;
-#ifdef Honor_FLT_ROUNDS
- if (bc->rounding == 1)
-#endif
- {
- speccase = 1;
- --p2;
- dsign = 0;
- goto have_i;
- }
- }
- else
-#endif
- b = d2b(rv, &p2, &bbits);
-#ifdef Avoid_Underflow
- p2 -= bc->scale;
-#endif
- /* floor(log2(rv)) == bbits - 1 + p2 */
- /* Check for denormal case. */
- i = P - bbits;
- if (i > (j = P - Emin - 1 + p2)) {
-#ifdef Sudden_Underflow
- Bfree(b);
- b = i2b(1);
- p2 = Emin;
- i = P - 1;
-#ifdef Avoid_Underflow
- word0(rv) = (1 + bc->scale) << Exp_shift;
-#else
- word0(rv) = Exp_msk1;
-#endif
- word1(rv) = 0;
-#else
- i = j;
-#endif
- }
-#ifdef Honor_FLT_ROUNDS
- if (bc->rounding != 1) {
- if (i > 0)
- b = lshift(b, i);
- if (dsign)
- b = increment(b);
- }
- else
-#endif
- {
- b = lshift(b, ++i);
- b->x[0] |= 1;
- }
-#ifndef Sudden_Underflow
- have_i:
-#endif
- p2 -= p5 + i;
- d = i2b(1);
- /* Arrange for convenient computation of quotients:
- * shift left if necessary so divisor has 4 leading 0 bits.
- */
- if (p5 > 0)
- d = pow5mult(d, p5);
- else if (p5 < 0)
- b = pow5mult(b, -p5);
- if (p2 > 0) {
- b2 = p2;
- d2 = 0;
- }
- else {
- b2 = 0;
- d2 = -p2;
- }
- i = dshift(d, d2);
- if ((b2 += i) > 0)
- b = lshift(b, b2);
- if ((d2 += i) > 0)
- d = lshift(d, d2);
-
- /* Now b/d = exactly half-way between the two floating-point values */
- /* on either side of the input string. Compute first digit of b/d. */
-
- dig = quorem(b,d);
- if (!dig) {
- b = multadd(b, 10, 0); /* very unlikely */
- dig = quorem(b,d);
- }
-
- /* Compare b/d with s0 */
-
- for(i = 0; i < nd0; ) {
- dd = s0[i++] - '0' - dig;
- if (dd)
- goto ret;
- if (!b->x[0] && b->wds == 1) {
- if (i < nd)
- dd = 1;
- goto ret;
- }
- b = multadd(b, 10, 0);
- dig = quorem(b,d);
- }
- for(j = bc->dp1; i++ < nd;) {
- dd = s0[j++] - '0' - dig;
- if (dd)
- goto ret;
- if (!b->x[0] && b->wds == 1) {
- if (i < nd)
- dd = 1;
- goto ret;
- }
- b = multadd(b, 10, 0);
- dig = quorem(b,d);
- }
- if (b->x[0] || b->wds > 1)
- dd = -1;
- ret:
- Bfree(b);
- Bfree(d);
-#ifdef Honor_FLT_ROUNDS
- if (bc->rounding != 1) {
- if (dd < 0) {
- if (bc->rounding == 0) {
- if (!dsign)
- goto retlow1;
- }
- else if (dsign)
- goto rethi1;
- }
- else if (dd > 0) {
- if (bc->rounding == 0) {
- if (dsign)
- goto rethi1;
- goto ret1;
- }
- if (!dsign)
- goto rethi1;
- dval(rv) += 2.*ulp(rv);
- }
- else {
- bc->inexact = 0;
- if (dsign)
- goto rethi1;
- }
- }
- else
-#endif
- if (speccase) {
- if (dd <= 0)
- rv->d = 0.;
- }
- else if (dd < 0) {
- if (!dsign) /* does not happen for round-near */
-retlow1:
- dval(rv) -= ulp(rv);
- }
- else if (dd > 0) {
- if (dsign) {
- rethi1:
- dval(rv) += ulp(rv);
- }
- }
- else {
- /* Exact half-way case: apply round-even rule. */
- if (word1(rv) & 1) {
- if (dsign)
- goto rethi1;
- goto retlow1;
- }
- }
-
-#ifdef Honor_FLT_ROUNDS
- ret1:
-#endif
- return;
- }
-#endif /* NO_STRTOD_BIGCOMP */
-
- double
-strtod
-#ifdef KR_headers
- (s00, se) CONST char *s00; char **se;
-#else
- (CONST char *s00, char **se)
-#endif
-{
- int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, e, e1;
- int esign, i, j, k, nd, nd0, nf, nz, nz0, sign;
- CONST char *s, *s0, *s1;
- double aadj, aadj1;
- Long L;
- U aadj2, adj, rv, rv0;
- ULong y, z;
- BCinfo bc;
- Bigint *bb, *bb1, *bd, *bd0, *bs, *delta;
-#ifdef SET_INEXACT
- int oldinexact;
-#endif
-#ifdef Honor_FLT_ROUNDS /*{*/
-#ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */
- bc.rounding = Flt_Rounds;
-#else /*}{*/
- bc.rounding = 1;
- switch(fegetround()) {
- case FE_TOWARDZERO: bc.rounding = 0; break;
- case FE_UPWARD: bc.rounding = 2; break;
- case FE_DOWNWARD: bc.rounding = 3;
- }
-#endif /*}}*/
-#endif /*}*/
-#ifdef USE_LOCALE
- CONST char *s2;
-#endif
-
- sign = nz0 = nz = bc.dplen = bc.uflchk = 0;
- dval(&rv) = 0.;
- for(s = s00;;s++) switch(*s) {
- case '-':
- sign = 1;
- /* no break */
- case '+':
- if (*++s)
- goto break2;
- /* no break */
- case 0:
- goto ret0;
- case '\t':
- case '\n':
- case '\v':
- case '\f':
- case '\r':
- case ' ':
- continue;
- default:
- goto break2;
- }
- break2:
- if (*s == '0') {
-#ifndef NO_HEX_FP /*{*/
- switch(s[1]) {
- case 'x':
- case 'X':
-#ifdef Honor_FLT_ROUNDS
- gethex(&s, &rv, bc.rounding, sign);
-#else
- gethex(&s, &rv, 1, sign);
-#endif
- goto ret;
- }
-#endif /*}*/
- nz0 = 1;
- while(*++s == '0') ;
- if (!*s)
- goto ret;
- }
- s0 = s;
- y = z = 0;
- for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++)
- if (nd < 9)
- y = 10*y + c - '0';
- else if (nd < 16)
- z = 10*z + c - '0';
- nd0 = nd;
- bc.dp0 = bc.dp1 = s - s0;
-#ifdef USE_LOCALE
- s1 = localeconv()->decimal_point;
- if (c == *s1) {
- c = '.';
- if (*++s1) {
- s2 = s;
- for(;;) {
- if (*++s2 != *s1) {
- c = 0;
- break;
- }
- if (!*++s1) {
- s = s2;
- break;
- }
- }
- }
- }
-#endif
- if (c == '.') {
- c = *++s;
- bc.dp1 = s - s0;
- bc.dplen = bc.dp1 - bc.dp0;
- if (!nd) {
- for(; c == '0'; c = *++s)
- nz++;
- if (c > '0' && c <= '9') {
- s0 = s;
- nf += nz;
- nz = 0;
- goto have_dig;
- }
- goto dig_done;
- }
- for(; c >= '0' && c <= '9'; c = *++s) {
- have_dig:
- nz++;
- if (c -= '0') {
- nf += nz;
- for(i = 1; i < nz; i++)
- if (nd++ < 9)
- y *= 10;
- else if (nd <= DBL_DIG + 1)
- z *= 10;
- if (nd++ < 9)
- y = 10*y + c;
- else if (nd <= DBL_DIG + 1)
- z = 10*z + c;
- nz = 0;
- }
- }
- }
- dig_done:
- e = 0;
- if (c == 'e' || c == 'E') {
- if (!nd && !nz && !nz0) {
- goto ret0;
- }
- s00 = s;
- esign = 0;
- switch(c = *++s) {
- case '-':
- esign = 1;
- case '+':
- c = *++s;
- }
- if (c >= '0' && c <= '9') {
- while(c == '0')
- c = *++s;
- if (c > '0' && c <= '9') {
- L = c - '0';
- s1 = s;
- while((c = *++s) >= '0' && c <= '9')
- L = 10*L + c - '0';
- if (s - s1 > 8 || L > 19999)
- /* Avoid confusion from exponents
- * so large that e might overflow.
- */
- e = 19999; /* safe for 16 bit ints */
- else
- e = (int)L;
- if (esign)
- e = -e;
- }
- else
- e = 0;
- }
- else
- s = s00;
- }
- if (!nd) {
- if (!nz && !nz0) {
-#ifdef INFNAN_CHECK
- /* Check for Nan and Infinity */
- if (!bc.dplen)
- switch(c) {
- case 'i':
- case 'I':
- if (match(&s,"nf")) {
- --s;
- if (!match(&s,"inity"))
- ++s;
- word0(&rv) = 0x7ff00000;
- word1(&rv) = 0;
- goto ret;
- }
- break;
- case 'n':
- case 'N':
- if (match(&s, "an")) {
- word0(&rv) = NAN_WORD0;
- word1(&rv) = NAN_WORD1;
-#ifndef No_Hex_NaN
- if (*s == '(') /*)*/
- hexnan(&rv, &s);
-#endif
- goto ret;
- }
- }
-#endif /* INFNAN_CHECK */
- ret0:
- s = s00;
- sign = 0;
- }
- goto ret;
- }
- bc.e0 = e1 = e -= nf;
-
- /* Now we have nd0 digits, starting at s0, followed by a
- * decimal point, followed by nd-nd0 digits. The number we're
- * after is the integer represented by those digits times
- * 10**e */
-
- if (!nd0)
- nd0 = nd;
- k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1;
- dval(&rv) = y;
- if (k > 9) {
-#ifdef SET_INEXACT
- if (k > DBL_DIG)
- oldinexact = get_inexact();
-#endif
- dval(&rv) = tens[k - 9] * dval(&rv) + z;
- }
- bd0 = 0;
- if (nd <= DBL_DIG
-#ifndef RND_PRODQUOT
-#ifndef Honor_FLT_ROUNDS
- && Flt_Rounds == 1
-#endif
-#endif
- ) {
- if (!e)
- goto ret;
- if (e > 0) {
- if (e <= Ten_pmax) {
-#ifdef VAX
- goto vax_ovfl_check;
-#else
-#ifdef Honor_FLT_ROUNDS
- /* round correctly FLT_ROUNDS = 2 or 3 */
- if (sign) {
- rv.d = -rv.d;
- sign = 0;
- }
-#endif
- /* rv = */ rounded_product(dval(&rv), tens[e]);
- goto ret;
-#endif
- }
- i = DBL_DIG - nd;
- if (e <= Ten_pmax + i) {
- /* A fancier test would sometimes let us do
- * this for larger i values.
- */
-#ifdef Honor_FLT_ROUNDS
- /* round correctly FLT_ROUNDS = 2 or 3 */
- if (sign) {
- rv.d = -rv.d;
- sign = 0;
- }
-#endif
- e -= i;
- dval(&rv) *= tens[i];
-#ifdef VAX
- /* VAX exponent range is so narrow we must
- * worry about overflow here...
- */
- vax_ovfl_check:
- word0(&rv) -= P*Exp_msk1;
- /* rv = */ rounded_product(dval(&rv), tens[e]);
- if ((word0(&rv) & Exp_mask)
- > Exp_msk1*(DBL_MAX_EXP+Bias-1-P))
- goto ovfl;
- word0(&rv) += P*Exp_msk1;
-#else
- /* rv = */ rounded_product(dval(&rv), tens[e]);
-#endif
- goto ret;
- }
- }
-#ifndef Inaccurate_Divide
- else if (e >= -Ten_pmax) {
-#ifdef Honor_FLT_ROUNDS
- /* round correctly FLT_ROUNDS = 2 or 3 */
- if (sign) {
- rv.d = -rv.d;
- sign = 0;
- }
-#endif
- /* rv = */ rounded_quotient(dval(&rv), tens[-e]);
- goto ret;
- }
-#endif
- }
- e1 += nd - k;
-
-#ifdef IEEE_Arith
-#ifdef SET_INEXACT
- bc.inexact = 1;
- if (k <= DBL_DIG)
- oldinexact = get_inexact();
-#endif
-#ifdef Avoid_Underflow
- bc.scale = 0;
-#endif
-#ifdef Honor_FLT_ROUNDS
- if (bc.rounding >= 2) {
- if (sign)
- bc.rounding = bc.rounding == 2 ? 0 : 2;
- else
- if (bc.rounding != 2)
- bc.rounding = 0;
- }
-#endif
-#endif /*IEEE_Arith*/
-
- /* Get starting approximation = rv * 10**e1 */
-
- if (e1 > 0) {
- i = e1 & 15;
- if (i)
- dval(&rv) *= tens[i];
- if (e1 &= ~15) {
- if (e1 > DBL_MAX_10_EXP) {
- ovfl:
-#ifndef NO_ERRNO
- errno = ERANGE;
-#endif
- /* Can't trust HUGE_VAL */
-#ifdef IEEE_Arith
-#ifdef Honor_FLT_ROUNDS
- switch(bc.rounding) {
- case 0: /* toward 0 */
- case 3: /* toward -infinity */
- word0(&rv) = Big0;
- word1(&rv) = Big1;
- break;
- default:
- word0(&rv) = Exp_mask;
- word1(&rv) = 0;
- }
-#else /*Honor_FLT_ROUNDS*/
- word0(&rv) = Exp_mask;
- word1(&rv) = 0;
-#endif /*Honor_FLT_ROUNDS*/
-#ifdef SET_INEXACT
- /* set overflow bit */
- dval(&rv0) = 1e300;
- dval(&rv0) *= dval(&rv0);
-#endif
-#else /*IEEE_Arith*/
- word0(&rv) = Big0;
- word1(&rv) = Big1;
-#endif /*IEEE_Arith*/
- goto ret;
- }
- e1 >>= 4;
- for(j = 0; e1 > 1; j++, e1 >>= 1)
- if (e1 & 1)
- dval(&rv) *= bigtens[j];
- /* The last multiplication could overflow. */
- word0(&rv) -= P*Exp_msk1;
- dval(&rv) *= bigtens[j];
- if ((z = word0(&rv) & Exp_mask)
- > Exp_msk1*(DBL_MAX_EXP+Bias-P))
- goto ovfl;
- if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) {
- /* set to largest number */
- /* (Can't trust DBL_MAX) */
- word0(&rv) = Big0;
- word1(&rv) = Big1;
- }
- else
- word0(&rv) += P*Exp_msk1;
- }
- }
- else if (e1 < 0) {
- e1 = -e1;
- i = e1 & 15;
- if (i)
- dval(&rv) /= tens[i];
- if (e1 >>= 4) {
- if (e1 >= 1 << n_bigtens)
- goto undfl;
-#ifdef Avoid_Underflow
- if (e1 & Scale_Bit)
- bc.scale = 2*P;
- for(j = 0; e1 > 0; j++, e1 >>= 1)
- if (e1 & 1)
- dval(&rv) *= tinytens[j];
- if (bc.scale && (j = 2*P + 1 - ((word0(&rv) & Exp_mask)
- >> Exp_shift)) > 0) {
- /* scaled rv is denormal; clear j low bits */
- if (j >= 32) {
- word1(&rv) = 0;
- if (j >= 53)
- word0(&rv) = (P+2)*Exp_msk1;
- else
- word0(&rv) &= 0xffffffff << (j-32);
- }
- else
- word1(&rv) &= 0xffffffff << j;
- }
-#else
- for(j = 0; e1 > 1; j++, e1 >>= 1)
- if (e1 & 1)
- dval(&rv) *= tinytens[j];
- /* The last multiplication could underflow. */
- dval(&rv0) = dval(&rv);
- dval(&rv) *= tinytens[j];
- if (!dval(&rv)) {
- dval(&rv) = 2.*dval(&rv0);
- dval(&rv) *= tinytens[j];
-#endif
- if (!dval(&rv)) {
- undfl:
- dval(&rv) = 0.;
-#ifndef NO_ERRNO
- errno = ERANGE;
-#endif
- goto ret;
- }
-#ifndef Avoid_Underflow
- word0(&rv) = Tiny0;
- word1(&rv) = Tiny1;
- /* The refinement below will clean
- * this approximation up.
- */
- }
-#endif
- }
- }
-
- /* Now the hard part -- adjusting rv to the correct value.*/
-
- /* Put digits into bd: true value = bd * 10^e */
-
- bc.nd = nd;
-#ifndef NO_STRTOD_BIGCOMP
- bc.nd0 = nd0; /* Only needed if nd > strtod_diglim, but done here */
- /* to silence an erroneous warning about bc.nd0 */
- /* possibly not being initialized. */
- if (nd > strtod_diglim) {
- /* ASSERT(strtod_diglim >= 18); 18 == one more than the */
- /* minimum number of decimal digits to distinguish double values */
- /* in IEEE arithmetic. */
- i = j = 18;
- if (i > nd0)
- j += bc.dplen;
- for(;;) {
- if (--j <= bc.dp1 && j >= bc.dp0)
- j = bc.dp0 - 1;
- if (s0[j] != '0')
- break;
- --i;
- }
- e += nd - i;
- nd = i;
- if (nd0 > nd)
- nd0 = nd;
- if (nd < 9) { /* must recompute y */
- y = 0;
- for(i = 0; i < nd0; ++i)
- y = 10*y + s0[i] - '0';
- for(j = bc.dp1; i < nd; ++i)
- y = 10*y + s0[j++] - '0';
- }
- }
-#endif
- bd0 = s2b(s0, nd0, nd, y, bc.dplen);
-
- for(;;) {
- bd = Balloc(bd0->k);
- Bcopy(bd, bd0);
- bb = d2b(&rv, &bbe, &bbbits); /* rv = bb * 2^bbe */
- bs = i2b(1);
-
- if (e >= 0) {
- bb2 = bb5 = 0;
- bd2 = bd5 = e;
- }
- else {
- bb2 = bb5 = -e;
- bd2 = bd5 = 0;
- }
- if (bbe >= 0)
- bb2 += bbe;
- else
- bd2 -= bbe;
- bs2 = bb2;
-#ifdef Honor_FLT_ROUNDS
- if (bc.rounding != 1)
- bs2++;
-#endif
-#ifdef Avoid_Underflow
- j = bbe - bc.scale;
- i = j + bbbits - 1; /* logb(rv) */
- if (i < Emin) /* denormal */
- j += P - Emin;
- else
- j = P + 1 - bbbits;
-#else /*Avoid_Underflow*/
-#ifdef Sudden_Underflow
-#ifdef IBM
- j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3);
-#else
- j = P + 1 - bbbits;
-#endif
-#else /*Sudden_Underflow*/
- j = bbe;
- i = j + bbbits - 1; /* logb(rv) */
- if (i < Emin) /* denormal */
- j += P - Emin;
- else
- j = P + 1 - bbbits;
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
- bb2 += j;
- bd2 += j;
-#ifdef Avoid_Underflow
- bd2 += bc.scale;
-#endif
- i = bb2 < bd2 ? bb2 : bd2;
- if (i > bs2)
- i = bs2;
- if (i > 0) {
- bb2 -= i;
- bd2 -= i;
- bs2 -= i;
- }
- if (bb5 > 0) {
- bs = pow5mult(bs, bb5);
- bb1 = mult(bs, bb);
- Bfree(bb);
- bb = bb1;
- }
- if (bb2 > 0)
- bb = lshift(bb, bb2);
- if (bd5 > 0)
- bd = pow5mult(bd, bd5);
- if (bd2 > 0)
- bd = lshift(bd, bd2);
- if (bs2 > 0)
- bs = lshift(bs, bs2);
- delta = diff(bb, bd);
- bc.dsign = delta->sign;
- delta->sign = 0;
- i = cmp(delta, bs);
-#ifndef NO_STRTOD_BIGCOMP
- if (bc.nd > nd && i <= 0) {
- if (bc.dsign)
- break; /* Must use bigcomp(). */
-#ifdef Honor_FLT_ROUNDS
- if (bc.rounding != 1) {
- if (i < 0)
- break;
- }
- else
-#endif
- {
- bc.nd = nd;
- i = -1; /* Discarded digits make delta smaller. */
- }
- }
-#endif
-#ifdef Honor_FLT_ROUNDS
- if (bc.rounding != 1) {
- if (i < 0) {
- /* Error is less than an ulp */
- if (!delta->x[0] && delta->wds <= 1) {
- /* exact */
-#ifdef SET_INEXACT
- bc.inexact = 0;
-#endif
- break;
- }
- if (bc.rounding) {
- if (bc.dsign) {
- adj.d = 1.;
- goto apply_adj;
- }
- }
- else if (!bc.dsign) {
- adj.d = -1.;
- if (!word1(&rv)
- && !(word0(&rv) & Frac_mask)) {
- y = word0(&rv) & Exp_mask;
-#ifdef Avoid_Underflow
- if (!bc.scale || y > 2*P*Exp_msk1)
-#else
- if (y)
-#endif
- {
- delta = lshift(delta,Log2P);
- if (cmp(delta, bs) <= 0)
- adj.d = -0.5;
- }
- }
- apply_adj:
-#ifdef Avoid_Underflow
- if (bc.scale && (y = word0(&rv) & Exp_mask)
- <= 2*P*Exp_msk1)
- word0(&adj) += (2*P+1)*Exp_msk1 - y;
-#else
-#ifdef Sudden_Underflow
- if ((word0(&rv) & Exp_mask) <=
- P*Exp_msk1) {
- word0(&rv) += P*Exp_msk1;
- dval(&rv) += adj.d*ulp(dval(&rv));
- word0(&rv) -= P*Exp_msk1;
- }
- else
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
- dval(&rv) += adj.d*ulp(&rv);
- }
- break;
- }
- adj.d = ratio(delta, bs);
- if (adj.d < 1.)
- adj.d = 1.;
- if (adj.d <= 0x7ffffffe) {
- /* adj = rounding ? ceil(adj) : floor(adj); */
- y = adj.d;
- if (y != adj.d) {
- if (!((bc.rounding>>1) ^ bc.dsign))
- y++;
- adj.d = y;
- }
- }
-#ifdef Avoid_Underflow
- if (bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1)
- word0(&adj) += (2*P+1)*Exp_msk1 - y;
-#else
-#ifdef Sudden_Underflow
- if ((word0(&rv) & Exp_mask) <= P*Exp_msk1) {
- word0(&rv) += P*Exp_msk1;
- adj.d *= ulp(dval(&rv));
- if (bc.dsign)
- dval(&rv) += adj.d;
- else
- dval(&rv) -= adj.d;
- word0(&rv) -= P*Exp_msk1;
- goto cont;
- }
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
- adj.d *= ulp(&rv);
- if (bc.dsign) {
- if (word0(&rv) == Big0 && word1(&rv) == Big1)
- goto ovfl;
- dval(&rv) += adj.d;
- }
- else
- dval(&rv) -= adj.d;
- goto cont;
- }
-#endif /*Honor_FLT_ROUNDS*/
-
- if (i < 0) {
- /* Error is less than half an ulp -- check for
- * special case of mantissa a power of two.
- */
- if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask
-#ifdef IEEE_Arith
-#ifdef Avoid_Underflow
- || (word0(&rv) & Exp_mask) <= (2*P+1)*Exp_msk1
-#else
- || (word0(&rv) & Exp_mask) <= Exp_msk1
-#endif
-#endif
- ) {
-#ifdef SET_INEXACT
- if (!delta->x[0] && delta->wds <= 1)
- bc.inexact = 0;
-#endif
- break;
- }
- if (!delta->x[0] && delta->wds <= 1) {
- /* exact result */
-#ifdef SET_INEXACT
- bc.inexact = 0;
-#endif
- break;
- }
- delta = lshift(delta,Log2P);
- if (cmp(delta, bs) > 0)
- goto drop_down;
- break;
- }
- if (i == 0) {
- /* exactly half-way between */
- if (bc.dsign) {
- if ((word0(&rv) & Bndry_mask1) == Bndry_mask1
- && word1(&rv) == (
-#ifdef Avoid_Underflow
- (bc.scale && (y = word0(&rv) & Exp_mask) <= 2*P*Exp_msk1)
- ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) :
-#endif
- 0xffffffff)) {
- /*boundary case -- increment exponent*/
- word0(&rv) = (word0(&rv) & Exp_mask)
- + Exp_msk1
-#ifdef IBM
- | Exp_msk1 >> 4
-#endif
- ;
- word1(&rv) = 0;
-#ifdef Avoid_Underflow
- bc.dsign = 0;
-#endif
- break;
- }
- }
- else if (!(word0(&rv) & Bndry_mask) && !word1(&rv)) {
- drop_down:
- /* boundary case -- decrement exponent */
-#ifdef Sudden_Underflow /*{{*/
- L = word0(&rv) & Exp_mask;
-#ifdef IBM
- if (L < Exp_msk1)
-#else
-#ifdef Avoid_Underflow
- if (L <= (bc.scale ? (2*P+1)*Exp_msk1 : Exp_msk1))
-#else
- if (L <= Exp_msk1)
-#endif /*Avoid_Underflow*/
-#endif /*IBM*/
- {
- if (bc.nd >nd) {
- bc.uflchk = 1;
- break;
- }
- goto undfl;
- }
- L -= Exp_msk1;
-#else /*Sudden_Underflow}{*/
-#ifdef Avoid_Underflow
- if (bc.scale) {
- L = word0(&rv) & Exp_mask;
- if (L <= (2*P+1)*Exp_msk1) {
- if (L > (P+2)*Exp_msk1)
- /* round even ==> */
- /* accept rv */
- break;
- /* rv = smallest denormal */
- if (bc.nd >nd) {
- bc.uflchk = 1;
- break;
- }
- goto undfl;
- }
- }
-#endif /*Avoid_Underflow*/
- L = (word0(&rv) & Exp_mask) - Exp_msk1;
-#endif /*Sudden_Underflow}}*/
- word0(&rv) = L | Bndry_mask1;
- word1(&rv) = 0xffffffff;
-#ifdef IBM
- goto cont;
-#else
- break;
-#endif
- }
-#ifndef ROUND_BIASED
- if (!(word1(&rv) & LSB))
- break;
-#endif
- if (bc.dsign)
- dval(&rv) += ulp(&rv);
-#ifndef ROUND_BIASED
- else {
- dval(&rv) -= ulp(&rv);
-#ifndef Sudden_Underflow
- if (!dval(&rv)) {
- if (bc.nd >nd) {
- bc.uflchk = 1;
- break;
- }
- goto undfl;
- }
-#endif
- }
-#ifdef Avoid_Underflow
- bc.dsign = 1 - bc.dsign;
-#endif
-#endif
- break;
- }
- if ((aadj = ratio(delta, bs)) <= 2.) {
- if (bc.dsign)
- aadj = aadj1 = 1.;
- else if (word1(&rv) || word0(&rv) & Bndry_mask) {
-#ifndef Sudden_Underflow
- if (word1(&rv) == Tiny1 && !word0(&rv)) {
- if (bc.nd >nd) {
- bc.uflchk = 1;
- break;
- }
- goto undfl;
- }
-#endif
- aadj = 1.;
- aadj1 = -1.;
- }
- else {
- /* special case -- power of FLT_RADIX to be */
- /* rounded down... */
-
- if (aadj < 2./FLT_RADIX)
- aadj = 1./FLT_RADIX;
- else
- aadj *= 0.5;
- aadj1 = -aadj;
- }
- }
- else {
- aadj *= 0.5;
- aadj1 = bc.dsign ? aadj : -aadj;
-#ifdef Check_FLT_ROUNDS
- switch(bc.rounding) {
- case 2: /* towards +infinity */
- aadj1 -= 0.5;
- break;
- case 0: /* towards 0 */
- case 3: /* towards -infinity */
- aadj1 += 0.5;
- }
-#else
- if (Flt_Rounds == 0)
- aadj1 += 0.5;
-#endif /*Check_FLT_ROUNDS*/
- }
- y = word0(&rv) & Exp_mask;
-
- /* Check for overflow */
-
- if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) {
- dval(&rv0) = dval(&rv);
- word0(&rv) -= P*Exp_msk1;
- adj.d = aadj1 * ulp(&rv);
- dval(&rv) += adj.d;
- if ((word0(&rv) & Exp_mask) >=
- Exp_msk1*(DBL_MAX_EXP+Bias-P)) {
- if (word0(&rv0) == Big0 && word1(&rv0) == Big1)
- goto ovfl;
- word0(&rv) = Big0;
- word1(&rv) = Big1;
- goto cont;
- }
- else
- word0(&rv) += P*Exp_msk1;
- }
- else {
-#ifdef Avoid_Underflow
- if (bc.scale && y <= 2*P*Exp_msk1) {
- if (aadj <= 0x7fffffff) {
- if ((z = (ULong)aadj) <= 0)
- z = 1;
- aadj = z;
- aadj1 = bc.dsign ? aadj : -aadj;
- }
- dval(&aadj2) = aadj1;
- word0(&aadj2) += (2*P+1)*Exp_msk1 - y;
- aadj1 = dval(&aadj2);
- }
- adj.d = aadj1 * ulp(&rv);
- dval(&rv) += adj.d;
-#else
-#ifdef Sudden_Underflow
- if ((word0(&rv) & Exp_mask) <= P*Exp_msk1) {
- dval(&rv0) = dval(&rv);
- word0(&rv) += P*Exp_msk1;
- adj.d = aadj1 * ulp(&rv);
- dval(&rv) += adj.d;
-#ifdef IBM
- if ((word0(&rv) & Exp_mask) < P*Exp_msk1)
-#else
- if ((word0(&rv) & Exp_mask) <= P*Exp_msk1)
-#endif
- {
- if (word0(&rv0) == Tiny0
- && word1(&rv0) == Tiny1) {
- if (bc.nd >nd) {
- bc.uflchk = 1;
- break;
- }
- goto undfl;
- }
- word0(&rv) = Tiny0;
- word1(&rv) = Tiny1;
- goto cont;
- }
- else
- word0(&rv) -= P*Exp_msk1;
- }
- else {
- adj.d = aadj1 * ulp(&rv);
- dval(&rv) += adj.d;
- }
-#else /*Sudden_Underflow*/
- /* Compute adj so that the IEEE rounding rules will
- * correctly round rv + adj in some half-way cases.
- * If rv * ulp(rv) is denormalized (i.e.,
- * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid
- * trouble from bits lost to denormalization;
- * example: 1.2e-307 .
- */
- if (y <= (P-1)*Exp_msk1 && aadj > 1.) {
- aadj1 = (double)(int)(aadj + 0.5);
- if (!bc.dsign)
- aadj1 = -aadj1;
- }
- adj.d = aadj1 * ulp(&rv);
- dval(&rv) += adj.d;
-#endif /*Sudden_Underflow*/
-#endif /*Avoid_Underflow*/
- }
- z = word0(&rv) & Exp_mask;
-#ifndef SET_INEXACT
- if (bc.nd == nd) {
-#ifdef Avoid_Underflow
- if (!bc.scale)
-#endif
- if (y == z) {
- /* Can we stop now? */
- L = (Long)aadj;
- aadj -= L;
- /* The tolerances below are conservative. */
- if (bc.dsign || word1(&rv) || word0(&rv) & Bndry_mask) {
- if (aadj < .4999999 || aadj > .5000001)
- break;
- }
- else if (aadj < .4999999/FLT_RADIX)
- break;
- }
- }
-#endif
- cont:
- Bfree(bb);
- Bfree(bd);
- Bfree(bs);
- Bfree(delta);
- }
- Bfree(bb);
- Bfree(bd);
- Bfree(bs);
- Bfree(bd0);
- Bfree(delta);
-#ifndef NO_STRTOD_BIGCOMP
- if (bc.nd > nd)
- bigcomp(&rv, s0, &bc);
-#endif
-#ifdef SET_INEXACT
- if (bc.inexact) {
- if (!oldinexact) {
- word0(&rv0) = Exp_1 + (70 << Exp_shift);
- word1(&rv0) = 0;
- dval(&rv0) += 1.;
- }
- }
- else if (!oldinexact)
- clear_inexact();
-#endif
-#ifdef Avoid_Underflow
- if (bc.scale) {
- word0(&rv0) = Exp_1 - 2*P*Exp_msk1;
- word1(&rv0) = 0;
- dval(&rv) *= dval(&rv0);
-#ifndef NO_ERRNO
- /* try to avoid the bug of testing an 8087 register value */
-#ifdef IEEE_Arith
- if (!(word0(&rv) & Exp_mask))
-#else
- if (word0(&rv) == 0 && word1(&rv) == 0)
-#endif
- errno = ERANGE;
-#endif
- }
-#endif /* Avoid_Underflow */
-#ifdef SET_INEXACT
- if (bc.inexact && !(word0(&rv) & Exp_mask)) {
- /* set underflow bit */
- dval(&rv0) = 1e-300;
- dval(&rv0) *= dval(&rv0);
- }
-#endif
- ret:
- if (se)
- *se = (char *)s;
- return sign ? -dval(&rv) : dval(&rv);
- }
-
-#ifndef MULTIPLE_THREADS
- static char *dtoa_result;
-#endif
-
- static char *
-#ifdef KR_headers
-rv_alloc(i) int i;
-#else
-rv_alloc(int i)
-#endif
-{
- int j, k, *r;
-
- j = sizeof(ULong);
- for(k = 0;
- sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= (size_t)i;
- j <<= 1)
- k++;
- r = (int*)Balloc(k);
- *r = k;
- return
-#ifndef MULTIPLE_THREADS
- dtoa_result =
-#endif
- (char *)(r+1);
- }
-
- static char *
-#ifdef KR_headers
-nrv_alloc(s, rve, n) char *s, **rve; int n;
-#else
-nrv_alloc(CONST char *s, char **rve, int n)
-#endif
-{
- char *rv, *t;
-
- t = rv = rv_alloc(n);
- for(*t = *s++; *t; *t = *s++) t++;
- if (rve)
- *rve = t;
- return rv;
- }
-
-/* freedtoa(s) must be used to free values s returned by dtoa
- * when MULTIPLE_THREADS is #defined. It should be used in all cases,
- * but for consistency with earlier versions of dtoa, it is optional
- * when MULTIPLE_THREADS is not defined.
- */
-
- void
-#ifdef KR_headers
-freedtoa(s) char *s;
-#else
-freedtoa(char *s)
-#endif
-{
- Bigint *b = (Bigint *)((int *)s - 1);
- b->maxwds = 1 << (b->k = *(int*)b);
- Bfree(b);
-#ifndef MULTIPLE_THREADS
- if (s == dtoa_result)
- dtoa_result = 0;
-#endif
- }
-
-/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string.
- *
- * Inspired by "How to Print Floating-Point Numbers Accurately" by
- * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 112-126].
- *
- * Modifications:
- * 1. Rather than iterating, we use a simple numeric overestimate
- * to determine k = floor(log10(d)). We scale relevant
- * quantities using O(log2(k)) rather than O(k) multiplications.
- * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't
- * try to generate digits strictly left to right. Instead, we
- * compute with fewer bits and propagate the carry if necessary
- * when rounding the final digit up. This is often faster.
- * 3. Under the assumption that input will be rounded nearest,
- * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22.
- * That is, we allow equality in stopping tests when the
- * round-nearest rule will give the same floating-point value
- * as would satisfaction of the stopping test with strict
- * inequality.
- * 4. We remove common factors of powers of 2 from relevant
- * quantities.
- * 5. When converting floating-point integers less than 1e16,
- * we use floating-point arithmetic rather than resorting
- * to multiple-precision integers.
- * 6. When asked to produce fewer than 15 digits, we first try
- * to get by with floating-point arithmetic; we resort to
- * multiple-precision integer arithmetic only if we cannot
- * guarantee that the floating-point calculation has given
- * the correctly rounded result. For k requested digits and
- * "uniformly" distributed input, the probability is
- * something like 10^(k-15) that we must resort to the Long
- * calculation.
- */
-
- char *
-dtoa
-#ifdef KR_headers
- (dd, mode, ndigits, decpt, sign, rve)
- double dd; int mode, ndigits, *decpt, *sign; char **rve;
-#else
- (double dd, int mode, int ndigits, int *decpt, int *sign, char **rve)
-#endif
-{
- /* Arguments ndigits, decpt, sign are similar to those
- of ecvt and fcvt; trailing zeros are suppressed from
- the returned string. If not null, *rve is set to point
- to the end of the return value. If d is +-Infinity or NaN,
- then *decpt is set to 9999.
-
- mode:
- 0 ==> shortest string that yields d when read in
- and rounded to nearest.
- 1 ==> like 0, but with Steele & White stopping rule;
- e.g. with IEEE P754 arithmetic , mode 0 gives
- 1e23 whereas mode 1 gives 9.999999999999999e22.
- 2 ==> max(1,ndigits) significant digits. This gives a
- return value similar to that of ecvt, except
- that trailing zeros are suppressed.
- 3 ==> through ndigits past the decimal point. This
- gives a return value similar to that from fcvt,
- except that trailing zeros are suppressed, and
- ndigits can be negative.
- 4,5 ==> similar to 2 and 3, respectively, but (in
- round-nearest mode) with the tests of mode 0 to
- possibly return a shorter string that rounds to d.
- With IEEE arithmetic and compilation with
- -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same
- as modes 2 and 3 when FLT_ROUNDS != 1.
- 6-9 ==> Debugging modes similar to mode - 4: don't try
- fast floating-point estimate (if applicable).
-
- Values of mode other than 0-9 are treated as mode 0.
-
- Sufficient space is allocated to the return value
- to hold the suppressed trailing zeros.
- */
-
- int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1,
- j, j1, k, k0, k_check, leftright, m2, m5, s2, s5,
- spec_case, try_quick;
- Long L;
-#ifndef Sudden_Underflow
- int denorm;
- ULong x;
-#endif
- Bigint *b, *b1, *delta, *mlo = NULL, *mhi, *S;
- U d2, eps, u;
- double ds;
- char *s, *s0;
-#ifdef SET_INEXACT
- int inexact, oldinexact;
-#endif
-#ifdef Honor_FLT_ROUNDS /*{*/
- int Rounding;
-#ifdef Trust_FLT_ROUNDS /*{{ only define this if FLT_ROUNDS really works! */
- Rounding = Flt_Rounds;
-#else /*}{*/
- Rounding = 1;
- switch(fegetround()) {
- case FE_TOWARDZERO: Rounding = 0; break;
- case FE_UPWARD: Rounding = 2; break;
- case FE_DOWNWARD: Rounding = 3;
- }
-#endif /*}}*/
-#endif /*}*/
-
-#ifndef MULTIPLE_THREADS
- if (dtoa_result) {
- freedtoa(dtoa_result);
- dtoa_result = 0;
- }
-#endif
-
- u.d = dd;
- if (word0(&u) & Sign_bit) {
- /* set sign for everything, including 0's and NaNs */
- *sign = 1;
- word0(&u) &= ~Sign_bit; /* clear sign bit */
- }
- else
- *sign = 0;
-
-#if defined(IEEE_Arith) + defined(VAX)
-#ifdef IEEE_Arith
- if ((word0(&u) & Exp_mask) == Exp_mask)
-#else
- if (word0(&u) == 0x8000)
-#endif
- {
- /* Infinity or NaN */
- *decpt = 9999;
-#ifdef IEEE_Arith
- if (!word1(&u) && !(word0(&u) & 0xfffff))
- return nrv_alloc("Infinity", rve, 8);
-#endif
- return nrv_alloc("NaN", rve, 3);
- }
-#endif
-#ifdef IBM
- dval(&u) += 0; /* normalize */
-#endif
- if (!dval(&u)) {
- *decpt = 1;
- return nrv_alloc("0", rve, 1);
- }
-
-#ifdef SET_INEXACT
- try_quick = oldinexact = get_inexact();
- inexact = 1;
-#endif
-#ifdef Honor_FLT_ROUNDS
- if (Rounding >= 2) {
- if (*sign)
- Rounding = Rounding == 2 ? 0 : 2;
- else
- if (Rounding != 2)
- Rounding = 0;
- }
-#endif
-
- b = d2b(&u, &be, &bbits);
- i = (int)(word0(&u) >> Exp_shift1 & (Exp_mask>>Exp_shift1));
-#ifndef Sudden_Underflow
- if (i) {
-#endif
- dval(&d2) = dval(&u);
- word0(&d2) &= Frac_mask1;
- word0(&d2) |= Exp_11;
-#ifdef IBM
- if (j = 11 - hi0bits(word0(&d2) & Frac_mask))
- dval(&d2) /= 1 << j;
-#endif
-
- /* log(x) ~=~ log(1.5) + (x-1.5)/1.5
- * log10(x) = log(x) / log(10)
- * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10))
- * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2)
- *
- * This suggests computing an approximation k to log10(d) by
- *
- * k = (i - Bias)*0.301029995663981
- * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 );
- *
- * We want k to be too large rather than too small.
- * The error in the first-order Taylor series approximation
- * is in our favor, so we just round up the constant enough
- * to compensate for any error in the multiplication of
- * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077,
- * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14,
- * adding 1e-13 to the constant term more than suffices.
- * Hence we adjust the constant term to 0.1760912590558.
- * (We could get a more accurate k by invoking log10,
- * but this is probably not worthwhile.)
- */
-
- i -= Bias;
-#ifdef IBM
- i <<= 2;
- i += j;
-#endif
-#ifndef Sudden_Underflow
- denorm = 0;
- }
- else {
- /* d is denormalized */
-
- i = bbits + be + (Bias + (P-1) - 1);
- x = i > 32 ? word0(&u) << (64 - i) | word1(&u) >> (i - 32)
- : word1(&u) << (32 - i);
- dval(&d2) = x;
- word0(&d2) -= 31*Exp_msk1; /* adjust exponent */
- i -= (Bias + (P-1) - 1) + 1;
- denorm = 1;
- }
-#endif
- ds = (dval(&d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981;
- k = (int)ds;
- if (ds < 0. && ds != k)
- k--; /* want k = floor(ds) */
- k_check = 1;
- if (k >= 0 && k <= Ten_pmax) {
- if (dval(&u) < tens[k])
- k--;
- k_check = 0;
- }
- j = bbits - i - 1;
- if (j >= 0) {
- b2 = 0;
- s2 = j;
- }
- else {
- b2 = -j;
- s2 = 0;
- }
- if (k >= 0) {
- b5 = 0;
- s5 = k;
- s2 += k;
- }
- else {
- b2 -= k;
- b5 = -k;
- s5 = 0;
- }
- if (mode < 0 || mode > 9)
- mode = 0;
-
-#ifndef SET_INEXACT
-#ifdef Check_FLT_ROUNDS
- try_quick = Rounding == 1;
-#else
- try_quick = 1;
-#endif
-#endif /*SET_INEXACT*/
-
- if (mode > 5) {
- mode -= 4;
- try_quick = 0;
- }
- leftright = 1;
- ilim = ilim1 = -1; /* Values for cases 0 and 1; done here to */
- /* silence erroneous "gcc -Wall" warning. */
- switch(mode) {
- case 0:
- case 1:
- i = 18;
- ndigits = 0;
- break;
- case 2:
- leftright = 0;
- /* no break */
- case 4:
- if (ndigits <= 0)
- ndigits = 1;
- ilim = ilim1 = i = ndigits;
- break;
- case 3:
- leftright = 0;
- /* no break */
- case 5:
- i = ndigits + k + 1;
- ilim = i;
- ilim1 = i - 1;
- if (i <= 0)
- i = 1;
- }
- s = s0 = rv_alloc(i);
-
-#ifdef Honor_FLT_ROUNDS
- if (mode > 1 && Rounding != 1)
- leftright = 0;
-#endif
-
- if (ilim >= 0 && ilim <= Quick_max && try_quick) {
-
- /* Try to get by with floating-point arithmetic. */
-
- i = 0;
- dval(&d2) = dval(&u);
- k0 = k;
- ilim0 = ilim;
- ieps = 2; /* conservative */
- if (k > 0) {
- ds = tens[k&0xf];
- j = k >> 4;
- if (j & Bletch) {
- /* prevent overflows */
- j &= Bletch - 1;
- dval(&u) /= bigtens[n_bigtens-1];
- ieps++;
- }
- for(; j; j >>= 1, i++)
- if (j & 1) {
- ieps++;
- ds *= bigtens[i];
- }
- dval(&u) /= ds;
- }
- else {
- j1 = -k;
- if (j1) {
- dval(&u) *= tens[j1 & 0xf];
- for(j = j1 >> 4; j; j >>= 1, i++)
- if (j & 1) {
- ieps++;
- dval(&u) *= bigtens[i];
- }
- }
- }
- if (k_check && dval(&u) < 1. && ilim > 0) {
- if (ilim1 <= 0)
- goto fast_failed;
- ilim = ilim1;
- k--;
- dval(&u) *= 10.;
- ieps++;
- }
- dval(&eps) = ieps*dval(&u) + 7.;
- word0(&eps) -= (P-1)*Exp_msk1;
- if (ilim == 0) {
- S = mhi = 0;
- dval(&u) -= 5.;
- if (dval(&u) > dval(&eps))
- goto one_digit;
- if (dval(&u) < -dval(&eps))
- goto no_digits;
- goto fast_failed;
- }
-#ifndef No_leftright
- if (leftright) {
- /* Use Steele & White method of only
- * generating digits needed.
- */
- dval(&eps) = 0.5/tens[ilim-1] - dval(&eps);
- for(i = 0;;) {
- L = (long)dval(&u);
- dval(&u) -= L;
- *s++ = '0' + (char)L;
- if (dval(&u) < dval(&eps))
- goto ret1;
- if (1. - dval(&u) < dval(&eps))
- goto bump_up;
- if (++i >= ilim)
- break;
- dval(&eps) *= 10.;
- dval(&u) *= 10.;
- }
- }
- else {
-#endif
- /* Generate ilim digits, then fix them up. */
- dval(&eps) *= tens[ilim-1];
- for(i = 1;; i++, dval(&u) *= 10.) {
- L = (Long)(dval(&u));
- if (!(dval(&u) -= L))
- ilim = i;
- *s++ = '0' + (char)L;
- if (i == ilim) {
- if (dval(&u) > 0.5 + dval(&eps))
- goto bump_up;
- else if (dval(&u) < 0.5 - dval(&eps)) {
- while(*--s == '0') {}
- s++;
- goto ret1;
- }
- break;
- }
- }
-#ifndef No_leftright
- }
-#endif
- fast_failed:
- s = s0;
- dval(&u) = dval(&d2);
- k = k0;
- ilim = ilim0;
- }
-
- /* Do we have a "small" integer? */
-
- if (be >= 0 && k <= Int_max) {
- /* Yes. */
- ds = tens[k];
- if (ndigits < 0 && ilim <= 0) {
- S = mhi = 0;
- if (ilim < 0 || dval(&u) <= 5*ds)
- goto no_digits;
- goto one_digit;
- }
- for(i = 1; i <= k + 1; i++, dval(&u) *= 10.) {
- L = (Long)(dval(&u) / ds);
- dval(&u) -= L*ds;
-#ifdef Check_FLT_ROUNDS
- /* If FLT_ROUNDS == 2, L will usually be high by 1 */
- if (dval(&u) < 0) {
- L--;
- dval(&u) += ds;
- }
-#endif
- *s++ = '0' + (char)L;
- if (!dval(&u)) {
-#ifdef SET_INEXACT
- inexact = 0;
-#endif
- break;
- }
- if (i == ilim) {
-#ifdef Honor_FLT_ROUNDS
- if (mode > 1)
- switch(Rounding) {
- case 0: goto ret1;
- case 2: goto bump_up;
- }
-#endif
- dval(&u) += dval(&u);
- if (dval(&u) > ds || (dval(&u) == ds && L & 1)) {
- bump_up:
- while(*--s == '9')
- if (s == s0) {
- k++;
- *s = '0';
- break;
- }
- ++*s++;
- }
- break;
- }
- }
- goto ret1;
- }
-
- m2 = b2;
- m5 = b5;
- mhi = mlo = 0;
- if (leftright) {
- i =
-#ifndef Sudden_Underflow
- denorm ? be + (Bias + (P-1) - 1 + 1) :
-#endif
-#ifdef IBM
- 1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3);
-#else
- 1 + P - bbits;
-#endif
- b2 += i;
- s2 += i;
- mhi = i2b(1);
- }
- if (m2 > 0 && s2 > 0) {
- i = m2 < s2 ? m2 : s2;
- b2 -= i;
- m2 -= i;
- s2 -= i;
- }
- if (b5 > 0) {
- if (leftright) {
- if (m5 > 0) {
- mhi = pow5mult(mhi, m5);
- b1 = mult(mhi, b);
- Bfree(b);
- b = b1;
- }
- j = b5 - m5;
- if (j)
- b = pow5mult(b, j);
- }
- else
- b = pow5mult(b, b5);
- }
- S = i2b(1);
- if (s5 > 0)
- S = pow5mult(S, s5);
-
- /* Check for special case that d is a normalized power of 2. */
-
- spec_case = 0;
- if ((mode < 2 || leftright)
-#ifdef Honor_FLT_ROUNDS
- && Rounding == 1
-#endif
- ) {
- if (!word1(&u) && !(word0(&u) & Bndry_mask)
-#ifndef Sudden_Underflow
- && word0(&u) & (Exp_mask & ~Exp_msk1)
-#endif
- ) {
- /* The special case */
- b2 += Log2P;
- s2 += Log2P;
- spec_case = 1;
- }
- }
-
- /* Arrange for convenient computation of quotients:
- * shift left if necessary so divisor has 4 leading 0 bits.
- *
- * Perhaps we should just compute leading 28 bits of S once
- * and for all and pass them and a shift to quorem, so it
- * can do shifts and ors to compute the numerator for q.
- */
-#ifdef Pack_32
- i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f;
- if (i)
- i = 32 - i;
-#define iInc 28
-#else
- if (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf)
- i = 16 - i;
-#define iInc 12
-#endif
- i = dshift(S, s2);
- b2 += i;
- m2 += i;
- s2 += i;
- if (b2 > 0)
- b = lshift(b, b2);
- if (s2 > 0)
- S = lshift(S, s2);
- if (k_check) {
- if (cmp(b,S) < 0) {
- k--;
- b = multadd(b, 10, 0); /* we botched the k estimate */
- if (leftright)
- mhi = multadd(mhi, 10, 0);
- ilim = ilim1;
- }
- }
- if (ilim <= 0 && (mode == 3 || mode == 5)) {
- if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) {
- /* no digits, fcvt style */
- no_digits:
- k = -1 - ndigits;
- goto ret;
- }
- one_digit:
- *s++ = '1';
- k++;
- goto ret;
- }
- if (leftright) {
- if (m2 > 0)
- mhi = lshift(mhi, m2);
-
- /* Compute mlo -- check for special case
- * that d is a normalized power of 2.
- */
-
- mlo = mhi;
- if (spec_case) {
- mhi = Balloc(mhi->k);
- Bcopy(mhi, mlo);
- mhi = lshift(mhi, Log2P);
- }
-
- for(i = 1;;i++) {
- dig = quorem(b,S) + '0';
- /* Do we yet have the shortest decimal string
- * that will round to d?
- */
- j = cmp(b, mlo);
- delta = diff(S, mhi);
- j1 = delta->sign ? 1 : cmp(b, delta);
- Bfree(delta);
-#ifndef ROUND_BIASED
- if (j1 == 0 && mode != 1 && !(word1(&u) & 1)
-#ifdef Honor_FLT_ROUNDS
- && Rounding >= 1
-#endif
- ) {
- if (dig == '9')
- goto round_9_up;
- if (j > 0)
- dig++;
-#ifdef SET_INEXACT
- else if (!b->x[0] && b->wds <= 1)
- inexact = 0;
-#endif
- *s++ = (char)dig;
- goto ret;
- }
-#endif
- if (j < 0 || (j == 0 && mode != 1
-#ifndef ROUND_BIASED
- && !(word1(&u) & 1)
-#endif
- )) {
- if (!b->x[0] && b->wds <= 1) {
-#ifdef SET_INEXACT
- inexact = 0;
-#endif
- goto accept_dig;
- }
-#ifdef Honor_FLT_ROUNDS
- if (mode > 1)
- switch(Rounding) {
- case 0: goto accept_dig;
- case 2: goto keep_dig;
- }
-#endif /*Honor_FLT_ROUNDS*/
- if (j1 > 0) {
- b = lshift(b, 1);
- j1 = cmp(b, S);
- if ((j1 > 0 || (j1 == 0 && dig & 1))
- && dig++ == '9')
- goto round_9_up;
- }
- accept_dig:
- *s++ = (char)dig;
- goto ret;
- }
- if (j1 > 0) {
-#ifdef Honor_FLT_ROUNDS
- if (!Rounding)
- goto accept_dig;
-#endif
- if (dig == '9') { /* possible if i == 1 */
- round_9_up:
- *s++ = '9';
- goto roundoff;
- }
- *s++ = (char)dig + 1;
- goto ret;
- }
-#ifdef Honor_FLT_ROUNDS
- keep_dig:
-#endif
- *s++ = (char)dig;
- if (i == ilim)
- break;
- b = multadd(b, 10, 0);
- if (mlo == mhi)
- mlo = mhi = multadd(mhi, 10, 0);
- else {
- mlo = multadd(mlo, 10, 0);
- mhi = multadd(mhi, 10, 0);
- }
- }
- }
- else
- for(i = 1;; i++) {
- dig = quorem(b,S) + '0';
- *s++ = (char)dig;
- if (!b->x[0] && b->wds <= 1) {
-#ifdef SET_INEXACT
- inexact = 0;
-#endif
- goto ret;
- }
- if (i >= ilim)
- break;
- b = multadd(b, 10, 0);
- }
-
- /* Round off last digit */
-
-#ifdef Honor_FLT_ROUNDS
- switch(Rounding) {
- case 0: goto trimzeros;
- case 2: goto roundoff;
- }
-#endif
- b = lshift(b, 1);
- j = cmp(b, S);
- if (j > 0 || (j == 0 && dig & 1)) {
- roundoff:
- while(*--s == '9')
- if (s == s0) {
- k++;
- *s++ = '1';
- goto ret;
- }
- ++*s++;
- }
- else {
-#ifdef Honor_FLT_ROUNDS
- trimzeros:
-#endif
- while(*--s == '0') {}
- s++;
- }
- ret:
- Bfree(S);
- if (mhi) {
- if (mlo && mlo != mhi)
- Bfree(mlo);
- Bfree(mhi);
- }
- ret1:
-#ifdef SET_INEXACT
- if (inexact) {
- if (!oldinexact) {
- word0(&u) = Exp_1 + (70 << Exp_shift);
- word1(&u) = 0;
- dval(&u) += 1.;
- }
- }
- else if (!oldinexact)
- clear_inexact();
-#endif
- Bfree(b);
- *s = 0;
- *decpt = k + 1;
- if (rve)
- *rve = s;
- return s0;
- }
-
-} // namespace dmg_fp
diff --git a/security/sandbox/chromium/base/third_party/dmg_fp/g_fmt.cc b/security/sandbox/chromium/base/third_party/dmg_fp/g_fmt.cc
deleted file mode 100644
index bfa358d15..000000000
--- a/security/sandbox/chromium/base/third_party/dmg_fp/g_fmt.cc
+++ /dev/null
@@ -1,102 +0,0 @@
-/****************************************************************
- *
- * The author of this software is David M. Gay.
- *
- * Copyright (c) 1991, 1996 by Lucent Technologies.
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose without fee is hereby granted, provided that this entire notice
- * is included in all copies of any software which is or includes a copy
- * or modification of this software and in all copies of the supporting
- * documentation for such software.
- *
- * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
- * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
- * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
- * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
- *
- ***************************************************************/
-
-/* g_fmt(buf,x) stores the closest decimal approximation to x in buf;
- * it suffices to declare buf
- * char buf[32];
- */
-
-#include "dmg_fp.h"
-
-namespace dmg_fp {
-
- char *
-g_fmt(register char *b, double x)
-{
- register int i, k;
- register char *s;
- int decpt, j, sign;
- char *b0, *s0, *se;
-
- b0 = b;
-#ifdef IGNORE_ZERO_SIGN
- if (!x) {
- *b++ = '0';
- *b = 0;
- goto done;
- }
-#endif
- s = s0 = dtoa(x, 0, 0, &decpt, &sign, &se);
- if (sign)
- *b++ = '-';
- if (decpt == 9999) /* Infinity or Nan */ {
- for(*b = *s++; *b++; *b = *s++) {}
- goto done0;
- }
- if (decpt <= -4 || decpt > se - s + 5) {
- *b++ = *s++;
- if (*s) {
- *b++ = '.';
- for(*b = *s++; *b; *b = *s++)
- b++;
- }
- *b++ = 'e';
- /* sprintf(b, "%+.2d", decpt - 1); */
- if (--decpt < 0) {
- *b++ = '-';
- decpt = -decpt;
- }
- else
- *b++ = '+';
- for(j = 2, k = 10; 10*k <= decpt; j++, k *= 10) {}
- for(;;) {
- i = decpt / k;
- *b++ = (char)i + '0';
- if (--j <= 0)
- break;
- decpt -= i*k;
- decpt *= 10;
- }
- *b = 0;
- }
- else if (decpt <= 0) {
- *b++ = '.';
- for(; decpt < 0; decpt++)
- *b++ = '0';
- for(*b = *s++; *b++; *b = *s++) {}
- }
- else {
- for(*b = *s++; *b; *b = *s++) {
- b++;
- if (--decpt == 0 && *s)
- *b++ = '.';
- }
- for(; decpt > 0; decpt--)
- *b++ = '0';
- *b = 0;
- }
- done0:
- freedtoa(s0);
-#ifdef IGNORE_ZERO_SIGN
- done:
-#endif
- return b0;
- }
-
-} // namespace dmg_fp
diff --git a/security/sandbox/chromium/base/third_party/dynamic_annotations/LICENSE b/security/sandbox/chromium/base/third_party/dynamic_annotations/LICENSE
deleted file mode 100644
index 5c581a939..000000000
--- a/security/sandbox/chromium/base/third_party/dynamic_annotations/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-/* Copyright (c) 2008-2009, Google Inc.
- * 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.
- * * 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.
- *
- * ---
- * Author: Kostya Serebryany
- */
diff --git a/security/sandbox/chromium/base/third_party/dynamic_annotations/dynamic_annotations.h b/security/sandbox/chromium/base/third_party/dynamic_annotations/dynamic_annotations.h
deleted file mode 100644
index 8d7f05202..000000000
--- a/security/sandbox/chromium/base/third_party/dynamic_annotations/dynamic_annotations.h
+++ /dev/null
@@ -1,595 +0,0 @@
-/* Copyright (c) 2011, Google Inc.
- * 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.
- * * 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.
- */
-
-/* This file defines dynamic annotations for use with dynamic analysis
- tool such as valgrind, PIN, etc.
-
- Dynamic annotation is a source code annotation that affects
- the generated code (that is, the annotation is not a comment).
- Each such annotation is attached to a particular
- instruction and/or to a particular object (address) in the program.
-
- The annotations that should be used by users are macros in all upper-case
- (e.g., ANNOTATE_NEW_MEMORY).
-
- Actual implementation of these macros may differ depending on the
- dynamic analysis tool being used.
-
- See http://code.google.com/p/data-race-test/ for more information.
-
- This file supports the following dynamic analysis tools:
- - None (DYNAMIC_ANNOTATIONS_ENABLED is not defined or zero).
- Macros are defined empty.
- - ThreadSanitizer, Helgrind, DRD (DYNAMIC_ANNOTATIONS_ENABLED is 1).
- Macros are defined as calls to non-inlinable empty functions
- that are intercepted by Valgrind. */
-
-#ifndef __DYNAMIC_ANNOTATIONS_H__
-#define __DYNAMIC_ANNOTATIONS_H__
-
-#ifndef DYNAMIC_ANNOTATIONS_PREFIX
-# define DYNAMIC_ANNOTATIONS_PREFIX
-#endif
-
-#ifndef DYNAMIC_ANNOTATIONS_PROVIDE_RUNNING_ON_VALGRIND
-# define DYNAMIC_ANNOTATIONS_PROVIDE_RUNNING_ON_VALGRIND 1
-#endif
-
-#ifdef DYNAMIC_ANNOTATIONS_WANT_ATTRIBUTE_WEAK
-# ifdef __GNUC__
-# define DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK __attribute__((weak))
-# else
-/* TODO(glider): for Windows support we may want to change this macro in order
- to prepend __declspec(selectany) to the annotations' declarations. */
-# error weak annotations are not supported for your compiler
-# endif
-#else
-# define DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK
-#endif
-
-/* The following preprocessor magic prepends the value of
- DYNAMIC_ANNOTATIONS_PREFIX to annotation function names. */
-#define DYNAMIC_ANNOTATIONS_GLUE0(A, B) A##B
-#define DYNAMIC_ANNOTATIONS_GLUE(A, B) DYNAMIC_ANNOTATIONS_GLUE0(A, B)
-#define DYNAMIC_ANNOTATIONS_NAME(name) \
- DYNAMIC_ANNOTATIONS_GLUE(DYNAMIC_ANNOTATIONS_PREFIX, name)
-
-#ifndef DYNAMIC_ANNOTATIONS_ENABLED
-# define DYNAMIC_ANNOTATIONS_ENABLED 0
-#endif
-
-#if DYNAMIC_ANNOTATIONS_ENABLED != 0
-
- /* -------------------------------------------------------------
- Annotations useful when implementing condition variables such as CondVar,
- using conditional critical sections (Await/LockWhen) and when constructing
- user-defined synchronization mechanisms.
-
- The annotations ANNOTATE_HAPPENS_BEFORE() and ANNOTATE_HAPPENS_AFTER() can
- be used to define happens-before arcs in user-defined synchronization
- mechanisms: the race detector will infer an arc from the former to the
- latter when they share the same argument pointer.
-
- Example 1 (reference counting):
-
- void Unref() {
- ANNOTATE_HAPPENS_BEFORE(&refcount_);
- if (AtomicDecrementByOne(&refcount_) == 0) {
- ANNOTATE_HAPPENS_AFTER(&refcount_);
- delete this;
- }
- }
-
- Example 2 (message queue):
-
- void MyQueue::Put(Type *e) {
- MutexLock lock(&mu_);
- ANNOTATE_HAPPENS_BEFORE(e);
- PutElementIntoMyQueue(e);
- }
-
- Type *MyQueue::Get() {
- MutexLock lock(&mu_);
- Type *e = GetElementFromMyQueue();
- ANNOTATE_HAPPENS_AFTER(e);
- return e;
- }
-
- Note: when possible, please use the existing reference counting and message
- queue implementations instead of inventing new ones. */
-
- /* Report that wait on the condition variable at address "cv" has succeeded
- and the lock at address "lock" is held. */
- #define ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateCondVarWait)(__FILE__, __LINE__, cv, lock)
-
- /* Report that wait on the condition variable at "cv" has succeeded. Variant
- w/o lock. */
- #define ANNOTATE_CONDVAR_WAIT(cv) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateCondVarWait)(__FILE__, __LINE__, cv, NULL)
-
- /* Report that we are about to signal on the condition variable at address
- "cv". */
- #define ANNOTATE_CONDVAR_SIGNAL(cv) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateCondVarSignal)(__FILE__, __LINE__, cv)
-
- /* Report that we are about to signal_all on the condition variable at address
- "cv". */
- #define ANNOTATE_CONDVAR_SIGNAL_ALL(cv) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateCondVarSignalAll)(__FILE__, __LINE__, cv)
-
- /* Annotations for user-defined synchronization mechanisms. */
- #define ANNOTATE_HAPPENS_BEFORE(obj) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateHappensBefore)(__FILE__, __LINE__, obj)
- #define ANNOTATE_HAPPENS_AFTER(obj) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateHappensAfter)(__FILE__, __LINE__, obj)
-
- /* DEPRECATED. Don't use it. */
- #define ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotatePublishMemoryRange)(__FILE__, __LINE__, \
- pointer, size)
-
- /* DEPRECATED. Don't use it. */
- #define ANNOTATE_UNPUBLISH_MEMORY_RANGE(pointer, size) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateUnpublishMemoryRange)(__FILE__, __LINE__, \
- pointer, size)
-
- /* DEPRECATED. Don't use it. */
- #define ANNOTATE_SWAP_MEMORY_RANGE(pointer, size) \
- do { \
- ANNOTATE_UNPUBLISH_MEMORY_RANGE(pointer, size); \
- ANNOTATE_PUBLISH_MEMORY_RANGE(pointer, size); \
- } while (0)
-
- /* Instruct the tool to create a happens-before arc between mu->Unlock() and
- mu->Lock(). This annotation may slow down the race detector and hide real
- races. Normally it is used only when it would be difficult to annotate each
- of the mutex's critical sections individually using the annotations above.
- This annotation makes sense only for hybrid race detectors. For pure
- happens-before detectors this is a no-op. For more details see
- http://code.google.com/p/data-race-test/wiki/PureHappensBeforeVsHybrid . */
- #define ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateMutexIsUsedAsCondVar)(__FILE__, __LINE__, \
- mu)
-
- /* Opposite to ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX.
- Instruct the tool to NOT create h-b arcs between Unlock and Lock, even in
- pure happens-before mode. For a hybrid mode this is a no-op. */
- #define ANNOTATE_NOT_HAPPENS_BEFORE_MUTEX(mu) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateMutexIsNotPHB)(__FILE__, __LINE__, mu)
-
- /* Deprecated. Use ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX. */
- #define ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateMutexIsUsedAsCondVar)(__FILE__, __LINE__, \
- mu)
-
- /* -------------------------------------------------------------
- Annotations useful when defining memory allocators, or when memory that
- was protected in one way starts to be protected in another. */
-
- /* Report that a new memory at "address" of size "size" has been allocated.
- This might be used when the memory has been retrieved from a free list and
- is about to be reused, or when a the locking discipline for a variable
- changes. */
- #define ANNOTATE_NEW_MEMORY(address, size) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateNewMemory)(__FILE__, __LINE__, address, \
- size)
-
- /* -------------------------------------------------------------
- Annotations useful when defining FIFO queues that transfer data between
- threads. */
-
- /* Report that the producer-consumer queue (such as ProducerConsumerQueue) at
- address "pcq" has been created. The ANNOTATE_PCQ_* annotations
- should be used only for FIFO queues. For non-FIFO queues use
- ANNOTATE_HAPPENS_BEFORE (for put) and ANNOTATE_HAPPENS_AFTER (for get). */
- #define ANNOTATE_PCQ_CREATE(pcq) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotatePCQCreate)(__FILE__, __LINE__, pcq)
-
- /* Report that the queue at address "pcq" is about to be destroyed. */
- #define ANNOTATE_PCQ_DESTROY(pcq) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotatePCQDestroy)(__FILE__, __LINE__, pcq)
-
- /* Report that we are about to put an element into a FIFO queue at address
- "pcq". */
- #define ANNOTATE_PCQ_PUT(pcq) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotatePCQPut)(__FILE__, __LINE__, pcq)
-
- /* Report that we've just got an element from a FIFO queue at address
- "pcq". */
- #define ANNOTATE_PCQ_GET(pcq) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotatePCQGet)(__FILE__, __LINE__, pcq)
-
- /* -------------------------------------------------------------
- Annotations that suppress errors. It is usually better to express the
- program's synchronization using the other annotations, but these can
- be used when all else fails. */
-
- /* Report that we may have a benign race at "pointer", with size
- "sizeof(*(pointer))". "pointer" must be a non-void* pointer. Insert at the
- point where "pointer" has been allocated, preferably close to the point
- where the race happens. See also ANNOTATE_BENIGN_RACE_STATIC. */
- #define ANNOTATE_BENIGN_RACE(pointer, description) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateBenignRaceSized)(__FILE__, __LINE__, \
- pointer, sizeof(*(pointer)), description)
-
- /* Same as ANNOTATE_BENIGN_RACE(address, description), but applies to
- the memory range [address, address+size). */
- #define ANNOTATE_BENIGN_RACE_SIZED(address, size, description) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateBenignRaceSized)(__FILE__, __LINE__, \
- address, size, description)
-
- /* Request the analysis tool to ignore all reads in the current thread
- until ANNOTATE_IGNORE_READS_END is called.
- Useful to ignore intentional racey reads, while still checking
- other reads and all writes.
- See also ANNOTATE_UNPROTECTED_READ. */
- #define ANNOTATE_IGNORE_READS_BEGIN() \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreReadsBegin)(__FILE__, __LINE__)
-
- /* Stop ignoring reads. */
- #define ANNOTATE_IGNORE_READS_END() \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreReadsEnd)(__FILE__, __LINE__)
-
- /* Similar to ANNOTATE_IGNORE_READS_BEGIN, but ignore writes. */
- #define ANNOTATE_IGNORE_WRITES_BEGIN() \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreWritesBegin)(__FILE__, __LINE__)
-
- /* Stop ignoring writes. */
- #define ANNOTATE_IGNORE_WRITES_END() \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreWritesEnd)(__FILE__, __LINE__)
-
- /* Start ignoring all memory accesses (reads and writes). */
- #define ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() \
- do {\
- ANNOTATE_IGNORE_READS_BEGIN();\
- ANNOTATE_IGNORE_WRITES_BEGIN();\
- }while(0)\
-
- /* Stop ignoring all memory accesses. */
- #define ANNOTATE_IGNORE_READS_AND_WRITES_END() \
- do {\
- ANNOTATE_IGNORE_WRITES_END();\
- ANNOTATE_IGNORE_READS_END();\
- }while(0)\
-
- /* Similar to ANNOTATE_IGNORE_READS_BEGIN, but ignore synchronization events:
- RWLOCK* and CONDVAR*. */
- #define ANNOTATE_IGNORE_SYNC_BEGIN() \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreSyncBegin)(__FILE__, __LINE__)
-
- /* Stop ignoring sync events. */
- #define ANNOTATE_IGNORE_SYNC_END() \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreSyncEnd)(__FILE__, __LINE__)
-
-
- /* Enable (enable!=0) or disable (enable==0) race detection for all threads.
- This annotation could be useful if you want to skip expensive race analysis
- during some period of program execution, e.g. during initialization. */
- #define ANNOTATE_ENABLE_RACE_DETECTION(enable) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateEnableRaceDetection)(__FILE__, __LINE__, \
- enable)
-
- /* -------------------------------------------------------------
- Annotations useful for debugging. */
-
- /* Request to trace every access to "address". */
- #define ANNOTATE_TRACE_MEMORY(address) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateTraceMemory)(__FILE__, __LINE__, address)
-
- /* Report the current thread name to a race detector. */
- #define ANNOTATE_THREAD_NAME(name) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateThreadName)(__FILE__, __LINE__, name)
-
- /* -------------------------------------------------------------
- Annotations useful when implementing locks. They are not
- normally needed by modules that merely use locks.
- The "lock" argument is a pointer to the lock object. */
-
- /* Report that a lock has been created at address "lock". */
- #define ANNOTATE_RWLOCK_CREATE(lock) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateRWLockCreate)(__FILE__, __LINE__, lock)
-
- /* Report that the lock at address "lock" is about to be destroyed. */
- #define ANNOTATE_RWLOCK_DESTROY(lock) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateRWLockDestroy)(__FILE__, __LINE__, lock)
-
- /* Report that the lock at address "lock" has been acquired.
- is_w=1 for writer lock, is_w=0 for reader lock. */
- #define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateRWLockAcquired)(__FILE__, __LINE__, lock, \
- is_w)
-
- /* Report that the lock at address "lock" is about to be released. */
- #define ANNOTATE_RWLOCK_RELEASED(lock, is_w) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateRWLockReleased)(__FILE__, __LINE__, lock, \
- is_w)
-
- /* -------------------------------------------------------------
- Annotations useful when implementing barriers. They are not
- normally needed by modules that merely use barriers.
- The "barrier" argument is a pointer to the barrier object. */
-
- /* Report that the "barrier" has been initialized with initial "count".
- If 'reinitialization_allowed' is true, initialization is allowed to happen
- multiple times w/o calling barrier_destroy() */
- #define ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateBarrierInit)(__FILE__, __LINE__, barrier, \
- count, reinitialization_allowed)
-
- /* Report that we are about to enter barrier_wait("barrier"). */
- #define ANNOTATE_BARRIER_WAIT_BEFORE(barrier) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateBarrierWaitBefore)(__FILE__, __LINE__, \
- barrier)
-
- /* Report that we just exited barrier_wait("barrier"). */
- #define ANNOTATE_BARRIER_WAIT_AFTER(barrier) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateBarrierWaitAfter)(__FILE__, __LINE__, \
- barrier)
-
- /* Report that the "barrier" has been destroyed. */
- #define ANNOTATE_BARRIER_DESTROY(barrier) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateBarrierDestroy)(__FILE__, __LINE__, \
- barrier)
-
- /* -------------------------------------------------------------
- Annotations useful for testing race detectors. */
-
- /* Report that we expect a race on the variable at "address".
- Use only in unit tests for a race detector. */
- #define ANNOTATE_EXPECT_RACE(address, description) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateExpectRace)(__FILE__, __LINE__, address, \
- description)
-
- #define ANNOTATE_FLUSH_EXPECTED_RACES() \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateFlushExpectedRaces)(__FILE__, __LINE__)
-
- /* A no-op. Insert where you like to test the interceptors. */
- #define ANNOTATE_NO_OP(arg) \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateNoOp)(__FILE__, __LINE__, arg)
-
- /* Force the race detector to flush its state. The actual effect depends on
- * the implementation of the detector. */
- #define ANNOTATE_FLUSH_STATE() \
- DYNAMIC_ANNOTATIONS_NAME(AnnotateFlushState)(__FILE__, __LINE__)
-
-
-#else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */
-
- #define ANNOTATE_RWLOCK_CREATE(lock) /* empty */
- #define ANNOTATE_RWLOCK_DESTROY(lock) /* empty */
- #define ANNOTATE_RWLOCK_ACQUIRED(lock, is_w) /* empty */
- #define ANNOTATE_RWLOCK_RELEASED(lock, is_w) /* empty */
- #define ANNOTATE_BARRIER_INIT(barrier, count, reinitialization_allowed) /* */
- #define ANNOTATE_BARRIER_WAIT_BEFORE(barrier) /* empty */
- #define ANNOTATE_BARRIER_WAIT_AFTER(barrier) /* empty */
- #define ANNOTATE_BARRIER_DESTROY(barrier) /* empty */
- #define ANNOTATE_CONDVAR_LOCK_WAIT(cv, lock) /* empty */
- #define ANNOTATE_CONDVAR_WAIT(cv) /* empty */
- #define ANNOTATE_CONDVAR_SIGNAL(cv) /* empty */
- #define ANNOTATE_CONDVAR_SIGNAL_ALL(cv) /* empty */
- #define ANNOTATE_HAPPENS_BEFORE(obj) /* empty */
- #define ANNOTATE_HAPPENS_AFTER(obj) /* empty */
- #define ANNOTATE_PUBLISH_MEMORY_RANGE(address, size) /* empty */
- #define ANNOTATE_UNPUBLISH_MEMORY_RANGE(address, size) /* empty */
- #define ANNOTATE_SWAP_MEMORY_RANGE(address, size) /* empty */
- #define ANNOTATE_PCQ_CREATE(pcq) /* empty */
- #define ANNOTATE_PCQ_DESTROY(pcq) /* empty */
- #define ANNOTATE_PCQ_PUT(pcq) /* empty */
- #define ANNOTATE_PCQ_GET(pcq) /* empty */
- #define ANNOTATE_NEW_MEMORY(address, size) /* empty */
- #define ANNOTATE_EXPECT_RACE(address, description) /* empty */
- #define ANNOTATE_FLUSH_EXPECTED_RACES(address, description) /* empty */
- #define ANNOTATE_BENIGN_RACE(address, description) /* empty */
- #define ANNOTATE_BENIGN_RACE_SIZED(address, size, description) /* empty */
- #define ANNOTATE_PURE_HAPPENS_BEFORE_MUTEX(mu) /* empty */
- #define ANNOTATE_MUTEX_IS_USED_AS_CONDVAR(mu) /* empty */
- #define ANNOTATE_TRACE_MEMORY(arg) /* empty */
- #define ANNOTATE_THREAD_NAME(name) /* empty */
- #define ANNOTATE_IGNORE_READS_BEGIN() /* empty */
- #define ANNOTATE_IGNORE_READS_END() /* empty */
- #define ANNOTATE_IGNORE_WRITES_BEGIN() /* empty */
- #define ANNOTATE_IGNORE_WRITES_END() /* empty */
- #define ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN() /* empty */
- #define ANNOTATE_IGNORE_READS_AND_WRITES_END() /* empty */
- #define ANNOTATE_IGNORE_SYNC_BEGIN() /* empty */
- #define ANNOTATE_IGNORE_SYNC_END() /* empty */
- #define ANNOTATE_ENABLE_RACE_DETECTION(enable) /* empty */
- #define ANNOTATE_NO_OP(arg) /* empty */
- #define ANNOTATE_FLUSH_STATE() /* empty */
-
-#endif /* DYNAMIC_ANNOTATIONS_ENABLED */
-
-/* Use the macros above rather than using these functions directly. */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateRWLockCreate)(
- const char *file, int line,
- const volatile void *lock) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateRWLockDestroy)(
- const char *file, int line,
- const volatile void *lock) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateRWLockAcquired)(
- const char *file, int line,
- const volatile void *lock, long is_w) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateRWLockReleased)(
- const char *file, int line,
- const volatile void *lock, long is_w) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateBarrierInit)(
- const char *file, int line, const volatile void *barrier, long count,
- long reinitialization_allowed) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateBarrierWaitBefore)(
- const char *file, int line,
- const volatile void *barrier) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateBarrierWaitAfter)(
- const char *file, int line,
- const volatile void *barrier) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateBarrierDestroy)(
- const char *file, int line,
- const volatile void *barrier) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateCondVarWait)(
- const char *file, int line, const volatile void *cv,
- const volatile void *lock) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateCondVarSignal)(
- const char *file, int line,
- const volatile void *cv) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateCondVarSignalAll)(
- const char *file, int line,
- const volatile void *cv) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateHappensBefore)(
- const char *file, int line,
- const volatile void *obj) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateHappensAfter)(
- const char *file, int line,
- const volatile void *obj) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotatePublishMemoryRange)(
- const char *file, int line,
- const volatile void *address, long size) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateUnpublishMemoryRange)(
- const char *file, int line,
- const volatile void *address, long size) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotatePCQCreate)(
- const char *file, int line,
- const volatile void *pcq) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotatePCQDestroy)(
- const char *file, int line,
- const volatile void *pcq) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotatePCQPut)(
- const char *file, int line,
- const volatile void *pcq) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotatePCQGet)(
- const char *file, int line,
- const volatile void *pcq) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateNewMemory)(
- const char *file, int line,
- const volatile void *mem, long size) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateExpectRace)(
- const char *file, int line, const volatile void *mem,
- const char *description) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateFlushExpectedRaces)(
- const char *file, int line) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateBenignRace)(
- const char *file, int line, const volatile void *mem,
- const char *description) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateBenignRaceSized)(
- const char *file, int line, const volatile void *mem, long size,
- const char *description) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateMutexIsUsedAsCondVar)(
- const char *file, int line,
- const volatile void *mu) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateMutexIsNotPHB)(
- const char *file, int line,
- const volatile void *mu) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateTraceMemory)(
- const char *file, int line,
- const volatile void *arg) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateThreadName)(
- const char *file, int line,
- const char *name) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreReadsBegin)(
- const char *file, int line) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreReadsEnd)(
- const char *file, int line) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreWritesBegin)(
- const char *file, int line) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreWritesEnd)(
- const char *file, int line) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreSyncBegin)(
- const char *file, int line) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateIgnoreSyncEnd)(
- const char *file, int line) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateEnableRaceDetection)(
- const char *file, int line, int enable) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateNoOp)(
- const char *file, int line,
- const volatile void *arg) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-void DYNAMIC_ANNOTATIONS_NAME(AnnotateFlushState)(
- const char *file, int line) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-
-#if DYNAMIC_ANNOTATIONS_PROVIDE_RUNNING_ON_VALGRIND == 1
-/* Return non-zero value if running under valgrind.
-
- If "valgrind.h" is included into dynamic_annotations.c,
- the regular valgrind mechanism will be used.
- See http://valgrind.org/docs/manual/manual-core-adv.html about
- RUNNING_ON_VALGRIND and other valgrind "client requests".
- The file "valgrind.h" may be obtained by doing
- svn co svn://svn.valgrind.org/valgrind/trunk/include
-
- If for some reason you can't use "valgrind.h" or want to fake valgrind,
- there are two ways to make this function return non-zero:
- - Use environment variable: export RUNNING_ON_VALGRIND=1
- - Make your tool intercept the function RunningOnValgrind() and
- change its return value.
- */
-int RunningOnValgrind(void) DYNAMIC_ANNOTATIONS_ATTRIBUTE_WEAK;
-#endif /* DYNAMIC_ANNOTATIONS_PROVIDE_RUNNING_ON_VALGRIND == 1 */
-
-#ifdef __cplusplus
-}
-#endif
-
-#if DYNAMIC_ANNOTATIONS_ENABLED != 0 && defined(__cplusplus)
-
- /* ANNOTATE_UNPROTECTED_READ is the preferred way to annotate racey reads.
-
- Instead of doing
- ANNOTATE_IGNORE_READS_BEGIN();
- ... = x;
- ANNOTATE_IGNORE_READS_END();
- one can use
- ... = ANNOTATE_UNPROTECTED_READ(x); */
- template <class T>
- inline T ANNOTATE_UNPROTECTED_READ(const volatile T &x) {
- ANNOTATE_IGNORE_READS_BEGIN();
- T res = x;
- ANNOTATE_IGNORE_READS_END();
- return res;
- }
- /* Apply ANNOTATE_BENIGN_RACE_SIZED to a static variable. */
- #define ANNOTATE_BENIGN_RACE_STATIC(static_var, description) \
- namespace { \
- class static_var ## _annotator { \
- public: \
- static_var ## _annotator() { \
- ANNOTATE_BENIGN_RACE_SIZED(&static_var, \
- sizeof(static_var), \
- # static_var ": " description); \
- } \
- }; \
- static static_var ## _annotator the ## static_var ## _annotator;\
- }
-#else /* DYNAMIC_ANNOTATIONS_ENABLED == 0 */
-
- #define ANNOTATE_UNPROTECTED_READ(x) (x)
- #define ANNOTATE_BENIGN_RACE_STATIC(static_var, description) /* empty */
-
-#endif /* DYNAMIC_ANNOTATIONS_ENABLED */
-
-#endif /* __DYNAMIC_ANNOTATIONS_H__ */
diff --git a/security/sandbox/chromium/base/third_party/icu/LICENSE b/security/sandbox/chromium/base/third_party/icu/LICENSE
deleted file mode 100644
index 40282f494..000000000
--- a/security/sandbox/chromium/base/third_party/icu/LICENSE
+++ /dev/null
@@ -1,32 +0,0 @@
-ICU License - ICU 1.8.1 and later
-
-COPYRIGHT AND PERMISSION NOTICE
-
-Copyright (c) 1995-2009 International Business Machines Corporation and others
-
-All rights reserved.
-
-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, and/or sell copies of the Software, and to permit persons
-to whom the Software is furnished to do so, provided that the above
-copyright notice(s) and this permission notice appear in all copies of
-the Software and that both the above copyright notice(s) and this
-permission notice appear in supporting documentation.
-
-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 COPYRIGHT HOLDER OR
-HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
-SPECIAL 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.
-
-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.
diff --git a/security/sandbox/chromium/base/third_party/icu/icu_utf.cc b/security/sandbox/chromium/base/third_party/icu/icu_utf.cc
deleted file mode 100644
index 2b67c5d9c..000000000
--- a/security/sandbox/chromium/base/third_party/icu/icu_utf.cc
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
-******************************************************************************
-*
-* Copyright (C) 1999-2006, International Business Machines
-* Corporation and others. All Rights Reserved.
-*
-******************************************************************************
-* file name: utf_impl.c
-* encoding: US-ASCII
-* tab size: 8 (not used)
-* indentation:4
-*
-* created on: 1999sep13
-* created by: Markus W. Scherer
-*
-* This file provides implementation functions for macros in the utfXX.h
-* that would otherwise be too long as macros.
-*/
-
-#include "base/third_party/icu/icu_utf.h"
-
-namespace base_icu {
-
-/**
- * UTF8_ERROR_VALUE_1 and UTF8_ERROR_VALUE_2 are special error values for UTF-8,
- * which need 1 or 2 bytes in UTF-8:
- * \code
- * U+0015 = NAK = Negative Acknowledge, C0 control character
- * U+009f = highest C1 control character
- * \endcode
- *
- * These are used by UTF8_..._SAFE macros so that they can return an error value
- * that needs the same number of code units (bytes) as were seen by
- * a macro. They should be tested with UTF_IS_ERROR() or UTF_IS_VALID().
- *
- * @deprecated ICU 2.4. Obsolete, see utf_old.h.
- */
-#define CBUTF8_ERROR_VALUE_1 0x15
-
-/**
- * See documentation on UTF8_ERROR_VALUE_1 for details.
- *
- * @deprecated ICU 2.4. Obsolete, see utf_old.h.
- */
-#define CBUTF8_ERROR_VALUE_2 0x9f
-
-
-/**
- * Error value for all UTFs. This code point value will be set by macros with e>
- * checking if an error is detected.
- *
- * @deprecated ICU 2.4. Obsolete, see utf_old.h.
- */
-#define CBUTF_ERROR_VALUE 0xffff
-
-/*
- * This table could be replaced on many machines by
- * a few lines of assembler code using an
- * "index of first 0-bit from msb" instruction and
- * one or two more integer instructions.
- *
- * For example, on an i386, do something like
- * - MOV AL, leadByte
- * - NOT AL (8-bit, leave b15..b8==0..0, reverse only b7..b0)
- * - MOV AH, 0
- * - BSR BX, AX (16-bit)
- * - MOV AX, 6 (result)
- * - JZ finish (ZF==1 if leadByte==0xff)
- * - SUB AX, BX (result)
- * -finish:
- * (BSR: Bit Scan Reverse, scans for a 1-bit, starting from the MSB)
- *
- * In Unicode, all UTF-8 byte sequences with more than 4 bytes are illegal;
- * lead bytes above 0xf4 are illegal.
- * We keep them in this table for skipping long ISO 10646-UTF-8 sequences.
- */
-const uint8_t utf8_countTrailBytes[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, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1,
-
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3,
- 3, 3, /* illegal in Unicode */
- 4, 4, 4, 4, /* illegal in Unicode */
- 5, 5, /* illegal in Unicode */
- 0, 0 /* illegal bytes 0xfe and 0xff */
-};
-
-static const UChar32
-utf8_minLegal[4]={ 0, 0x80, 0x800, 0x10000 };
-
-static const UChar32
-utf8_errorValue[6]={
- CBUTF8_ERROR_VALUE_1, CBUTF8_ERROR_VALUE_2, CBUTF_ERROR_VALUE, 0x10ffff,
- 0x3ffffff, 0x7fffffff
-};
-
-/*
- * Handle the non-inline part of the U8_NEXT() macro and its obsolete sibling
- * UTF8_NEXT_CHAR_SAFE().
- *
- * The "strict" parameter controls the error behavior:
- * <0 "Safe" behavior of U8_NEXT(): All illegal byte sequences yield a negative
- * code point result.
- * 0 Obsolete "safe" behavior of UTF8_NEXT_CHAR_SAFE(..., FALSE):
- * All illegal byte sequences yield a positive code point such that this
- * result code point would be encoded with the same number of bytes as
- * the illegal sequence.
- * >0 Obsolete "strict" behavior of UTF8_NEXT_CHAR_SAFE(..., TRUE):
- * Same as the obsolete "safe" behavior, but non-characters are also treated
- * like illegal sequences.
- *
- * The special negative (<0) value -2 is used for lenient treatment of surrogate
- * code points as legal. Some implementations use this for roundtripping of
- * Unicode 16-bit strings that are not well-formed UTF-16, that is, they
- * contain unpaired surrogates.
- *
- * Note that a UBool is the same as an int8_t.
- */
-UChar32 utf8_nextCharSafeBody(const uint8_t* s,
- int32_t* pi,
- int32_t length,
- UChar32 c,
- UBool strict) {
- int32_t i = *pi;
- uint8_t count = CBU8_COUNT_TRAIL_BYTES(c);
- if((i)+count<=(length)) {
- uint8_t trail, illegal = 0;
-
- CBU8_MASK_LEAD_BYTE((c), count);
- /* count==0 for illegally leading trail bytes and the illegal bytes 0xfe and 0xff */
- switch(count) {
- /* each branch falls through to the next one */
- case 5:
- case 4:
- /* count>=4 is always illegal: no more than 3 trail bytes in Unicode's UTF-8 */
- illegal=1;
- break;
- case 3:
- trail=s[(i)++];
- (c)=((c)<<6)|(trail&0x3f);
- if(c<0x110) {
- illegal|=(trail&0xc0)^0x80;
- } else {
- /* code point>0x10ffff, outside Unicode */
- illegal=1;
- break;
- }
- case 2:
- trail=s[(i)++];
- (c)=((c)<<6)|(trail&0x3f);
- illegal|=(trail&0xc0)^0x80;
- case 1:
- trail=s[(i)++];
- (c)=((c)<<6)|(trail&0x3f);
- illegal|=(trail&0xc0)^0x80;
- break;
- case 0:
- if(strict>=0) {
- return CBUTF8_ERROR_VALUE_1;
- } else {
- return CBU_SENTINEL;
- }
- /* no default branch to optimize switch() - all values are covered */
- }
-
- /*
- * All the error handling should return a value
- * that needs count bytes so that UTF8_GET_CHAR_SAFE() works right.
- *
- * Starting with Unicode 3.0.1, non-shortest forms are illegal.
- * Starting with Unicode 3.2, surrogate code points must not be
- * encoded in UTF-8, and there are no irregular sequences any more.
- *
- * U8_ macros (new in ICU 2.4) return negative values for error conditions.
- */
-
- /* correct sequence - all trail bytes have (b7..b6)==(10)? */
- /* illegal is also set if count>=4 */
- if(illegal || (c)<utf8_minLegal[count] || (CBU_IS_SURROGATE(c) && strict!=-2)) {
- /* error handling */
- uint8_t errorCount = count;
- /* don't go beyond this sequence */
- i=*pi;
- while(count>0 && CBU8_IS_TRAIL(s[i])) {
- ++(i);
- --count;
- }
- if(strict>=0) {
- c=utf8_errorValue[errorCount-count];
- } else {
- c=CBU_SENTINEL;
- }
- } else if((strict)>0 && CBU_IS_UNICODE_NONCHAR(c)) {
- /* strict: forbid non-characters like U+fffe */
- c=utf8_errorValue[count];
- }
- } else /* too few bytes left */ {
- /* error handling */
- int32_t i0 = i;
- /* don't just set (i)=(length) in case there is an illegal sequence */
- while((i)<(length) && CBU8_IS_TRAIL(s[i])) {
- ++(i);
- }
- if(strict>=0) {
- c=utf8_errorValue[i-i0];
- } else {
- c=CBU_SENTINEL;
- }
- }
- *pi=i;
- return c;
-}
-
-} // namespace base_icu
diff --git a/security/sandbox/chromium/base/third_party/icu/icu_utf.h b/security/sandbox/chromium/base/third_party/icu/icu_utf.h
deleted file mode 100644
index 4370fdec1..000000000
--- a/security/sandbox/chromium/base/third_party/icu/icu_utf.h
+++ /dev/null
@@ -1,400 +0,0 @@
-/*
-*******************************************************************************
-*
-* Copyright (C) 1999-2004, International Business Machines
-* Corporation and others. All Rights Reserved.
-*
-*******************************************************************************
-* file name: utf.h
-* encoding: US-ASCII
-* tab size: 8 (not used)
-* indentation:4
-*
-* created on: 1999sep09
-* created by: Markus W. Scherer
-*/
-
-#ifndef BASE_THIRD_PARTY_ICU_ICU_UTF_H_
-#define BASE_THIRD_PARTY_ICU_ICU_UTF_H_
-
-#include <stdint.h>
-
-namespace base_icu {
-
-typedef int32_t UChar32;
-typedef uint16_t UChar;
-typedef int8_t UBool;
-
-// General ---------------------------------------------------------------------
-// from utf.h
-
-/**
- * This value is intended for sentinel values for APIs that
- * (take or) return single code points (UChar32).
- * It is outside of the Unicode code point range 0..0x10ffff.
- *
- * For example, a "done" or "error" value in a new API
- * could be indicated with CBU_SENTINEL.
- *
- * ICU APIs designed before ICU 2.4 usually define service-specific "done"
- * values, mostly 0xffff.
- * Those may need to be distinguished from
- * actual U+ffff text contents by calling functions like
- * CharacterIterator::hasNext() or UnicodeString::length().
- *
- * @return -1
- * @see UChar32
- * @stable ICU 2.4
- */
-#define CBU_SENTINEL (-1)
-
-/**
- * Is this code point a Unicode noncharacter?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU_IS_UNICODE_NONCHAR(c) \
- ((c) >= 0xfdd0 && ((uint32_t)(c) <= 0xfdef || ((c)&0xfffe) == 0xfffe) && \
- (uint32_t)(c) <= 0x10ffff)
-
-/**
- * Is c a Unicode code point value (0..U+10ffff)
- * that can be assigned a character?
- *
- * Code points that are not characters include:
- * - single surrogate code points (U+d800..U+dfff, 2048 code points)
- * - the last two code points on each plane (U+__fffe and U+__ffff, 34 code points)
- * - U+fdd0..U+fdef (new with Unicode 3.1, 32 code points)
- * - the highest Unicode code point value is U+10ffff
- *
- * This means that all code points below U+d800 are character code points,
- * and that boundary is tested first for performance.
- *
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU_IS_UNICODE_CHAR(c) \
- ((uint32_t)(c) < 0xd800 || \
- ((uint32_t)(c) > 0xdfff && (uint32_t)(c) <= 0x10ffff && \
- !CBU_IS_UNICODE_NONCHAR(c)))
-
-/**
- * Is this code point a surrogate (U+d800..U+dfff)?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU_IS_SURROGATE(c) (((c)&0xfffff800)==0xd800)
-
-/**
- * Assuming c is a surrogate code point (U_IS_SURROGATE(c)),
- * is it a lead surrogate?
- * @param c 32-bit code point
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU_IS_SURROGATE_LEAD(c) (((c)&0x400)==0)
-
-
-// UTF-8 macros ----------------------------------------------------------------
-// from utf8.h
-
-extern const uint8_t utf8_countTrailBytes[256];
-
-/**
- * Count the trail bytes for a UTF-8 lead byte.
- * @internal
- */
-#define CBU8_COUNT_TRAIL_BYTES(leadByte) \
- (base_icu::utf8_countTrailBytes[(uint8_t)leadByte])
-
-/**
- * Mask a UTF-8 lead byte, leave only the lower bits that form part of the code point value.
- * @internal
- */
-#define CBU8_MASK_LEAD_BYTE(leadByte, countTrailBytes) ((leadByte)&=(1<<(6-(countTrailBytes)))-1)
-
-/**
- * Does this code unit (byte) encode a code point by itself (US-ASCII 0..0x7f)?
- * @param c 8-bit code unit (byte)
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU8_IS_SINGLE(c) (((c)&0x80)==0)
-
-/**
- * Is this code unit (byte) a UTF-8 lead byte?
- * @param c 8-bit code unit (byte)
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU8_IS_LEAD(c) ((uint8_t)((c)-0xc0) < 0x3e)
-
-/**
- * Is this code unit (byte) a UTF-8 trail byte?
- * @param c 8-bit code unit (byte)
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU8_IS_TRAIL(c) (((c)&0xc0)==0x80)
-
-/**
- * How many code units (bytes) are used for the UTF-8 encoding
- * of this Unicode code point?
- * @param c 32-bit code point
- * @return 1..4, or 0 if c is a surrogate or not a Unicode code point
- * @stable ICU 2.4
- */
-#define CBU8_LENGTH(c) \
- ((uint32_t)(c) <= 0x7f \
- ? 1 \
- : ((uint32_t)(c) <= 0x7ff \
- ? 2 \
- : ((uint32_t)(c) <= 0xd7ff \
- ? 3 \
- : ((uint32_t)(c) <= 0xdfff || (uint32_t)(c) > 0x10ffff \
- ? 0 \
- : ((uint32_t)(c) <= 0xffff ? 3 : 4)))))
-
-/**
- * The maximum number of UTF-8 code units (bytes) per Unicode code point (U+0000..U+10ffff).
- * @return 4
- * @stable ICU 2.4
- */
-#define CBU8_MAX_LENGTH 4
-
-/**
- * Function for handling "next code point" with error-checking.
- * @internal
- */
-UChar32 utf8_nextCharSafeBody(const uint8_t* s,
- int32_t* pi,
- int32_t length,
- UChar32 c,
- UBool strict);
-
-/**
- * Get a code point from a string at a code point boundary offset,
- * and advance the offset to the next code point boundary.
- * (Post-incrementing forward iteration.)
- * "Safe" macro, checks for illegal sequences and for string boundaries.
- *
- * The offset may point to the lead byte of a multi-byte sequence,
- * in which case the macro will read the whole sequence.
- * If the offset points to a trail byte or an illegal UTF-8 sequence, then
- * c is set to a negative value.
- *
- * @param s const uint8_t * string
- * @param i string offset, i<length
- * @param length string length
- * @param c output UChar32 variable, set to <0 in case of an error
- * @see CBU8_NEXT_UNSAFE
- * @stable ICU 2.4
- */
-#define CBU8_NEXT(s, i, length, c) \
- { \
- (c) = (s)[(i)++]; \
- if (((uint8_t)(c)) >= 0x80) { \
- if (CBU8_IS_LEAD(c)) { \
- (c) = base_icu::utf8_nextCharSafeBody((const uint8_t*)s, &(i), \
- (int32_t)(length), c, -1); \
- } else { \
- (c) = CBU_SENTINEL; \
- } \
- } \
- }
-
-/**
- * Append a code point to a string, overwriting 1 to 4 bytes.
- * The offset points to the current end of the string contents
- * and is advanced (post-increment).
- * "Unsafe" macro, assumes a valid code point and sufficient space in the
- * string.
- * Otherwise, the result is undefined.
- *
- * @param s const uint8_t * string buffer
- * @param i string offset
- * @param c code point to append
- * @see CBU8_APPEND
- * @stable ICU 2.4
- */
-#define CBU8_APPEND_UNSAFE(s, i, c) \
- { \
- if ((uint32_t)(c) <= 0x7f) { \
- (s)[(i)++] = (uint8_t)(c); \
- } else { \
- if ((uint32_t)(c) <= 0x7ff) { \
- (s)[(i)++] = (uint8_t)(((c) >> 6) | 0xc0); \
- } else { \
- if ((uint32_t)(c) <= 0xffff) { \
- (s)[(i)++] = (uint8_t)(((c) >> 12) | 0xe0); \
- } else { \
- (s)[(i)++] = (uint8_t)(((c) >> 18) | 0xf0); \
- (s)[(i)++] = (uint8_t)((((c) >> 12) & 0x3f) | 0x80); \
- } \
- (s)[(i)++] = (uint8_t)((((c) >> 6) & 0x3f) | 0x80); \
- } \
- (s)[(i)++] = (uint8_t)(((c)&0x3f) | 0x80); \
- } \
- }
-
-// UTF-16 macros ---------------------------------------------------------------
-// from utf16.h
-
-/**
- * Does this code unit alone encode a code point (BMP, not a surrogate)?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU16_IS_SINGLE(c) !CBU_IS_SURROGATE(c)
-
-/**
- * Is this code unit a lead surrogate (U+d800..U+dbff)?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU16_IS_LEAD(c) (((c)&0xfffffc00)==0xd800)
-
-/**
- * Is this code unit a trail surrogate (U+dc00..U+dfff)?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU16_IS_TRAIL(c) (((c)&0xfffffc00)==0xdc00)
-
-/**
- * Is this code unit a surrogate (U+d800..U+dfff)?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU16_IS_SURROGATE(c) CBU_IS_SURROGATE(c)
-
-/**
- * Assuming c is a surrogate code point (U16_IS_SURROGATE(c)),
- * is it a lead surrogate?
- * @param c 16-bit code unit
- * @return TRUE or FALSE
- * @stable ICU 2.4
- */
-#define CBU16_IS_SURROGATE_LEAD(c) (((c)&0x400)==0)
-
-/**
- * Helper constant for CBU16_GET_SUPPLEMENTARY.
- * @internal
- */
-#define CBU16_SURROGATE_OFFSET ((0xd800<<10UL)+0xdc00-0x10000)
-
-/**
- * Get a supplementary code point value (U+10000..U+10ffff)
- * from its lead and trail surrogates.
- * The result is undefined if the input values are not
- * lead and trail surrogates.
- *
- * @param lead lead surrogate (U+d800..U+dbff)
- * @param trail trail surrogate (U+dc00..U+dfff)
- * @return supplementary code point (U+10000..U+10ffff)
- * @stable ICU 2.4
- */
-#define CBU16_GET_SUPPLEMENTARY(lead, trail) \
- (((base_icu::UChar32)(lead)<<10UL)+(base_icu::UChar32)(trail)-CBU16_SURROGATE_OFFSET)
-
-
-/**
- * Get the lead surrogate (0xd800..0xdbff) for a
- * supplementary code point (0x10000..0x10ffff).
- * @param supplementary 32-bit code point (U+10000..U+10ffff)
- * @return lead surrogate (U+d800..U+dbff) for supplementary
- * @stable ICU 2.4
- */
-#define CBU16_LEAD(supplementary) \
- (base_icu::UChar)(((supplementary)>>10)+0xd7c0)
-
-/**
- * Get the trail surrogate (0xdc00..0xdfff) for a
- * supplementary code point (0x10000..0x10ffff).
- * @param supplementary 32-bit code point (U+10000..U+10ffff)
- * @return trail surrogate (U+dc00..U+dfff) for supplementary
- * @stable ICU 2.4
- */
-#define CBU16_TRAIL(supplementary) \
- (base_icu::UChar)(((supplementary)&0x3ff)|0xdc00)
-
-/**
- * How many 16-bit code units are used to encode this Unicode code point? (1 or 2)
- * The result is not defined if c is not a Unicode code point (U+0000..U+10ffff).
- * @param c 32-bit code point
- * @return 1 or 2
- * @stable ICU 2.4
- */
-#define CBU16_LENGTH(c) ((uint32_t)(c) <= 0xffff ? 1 : 2)
-
-/**
- * The maximum number of 16-bit code units per Unicode code point (U+0000..U+10ffff).
- * @return 2
- * @stable ICU 2.4
- */
-#define CBU16_MAX_LENGTH 2
-
-/**
- * Get a code point from a string at a code point boundary offset,
- * and advance the offset to the next code point boundary.
- * (Post-incrementing forward iteration.)
- * "Safe" macro, handles unpaired surrogates and checks for string boundaries.
- *
- * The offset may point to the lead surrogate unit
- * for a supplementary code point, in which case the macro will read
- * the following trail surrogate as well.
- * If the offset points to a trail surrogate or
- * to a single, unpaired lead surrogate, then that itself
- * will be returned as the code point.
- *
- * @param s const UChar * string
- * @param i string offset, i<length
- * @param length string length
- * @param c output UChar32 variable
- * @stable ICU 2.4
- */
-#define CBU16_NEXT(s, i, length, c) \
- { \
- (c) = (s)[(i)++]; \
- if (CBU16_IS_LEAD(c)) { \
- uint16_t __c2; \
- if ((i) < (length) && CBU16_IS_TRAIL(__c2 = (s)[(i)])) { \
- ++(i); \
- (c) = CBU16_GET_SUPPLEMENTARY((c), __c2); \
- } \
- } \
- }
-
-/**
- * Append a code point to a string, overwriting 1 or 2 code units.
- * The offset points to the current end of the string contents
- * and is advanced (post-increment).
- * "Unsafe" macro, assumes a valid code point and sufficient space in the string.
- * Otherwise, the result is undefined.
- *
- * @param s const UChar * string buffer
- * @param i string offset
- * @param c code point to append
- * @see CBU16_APPEND
- * @stable ICU 2.4
- */
-#define CBU16_APPEND_UNSAFE(s, i, c) \
- { \
- if ((uint32_t)(c) <= 0xffff) { \
- (s)[(i)++] = (uint16_t)(c); \
- } else { \
- (s)[(i)++] = (uint16_t)(((c) >> 10) + 0xd7c0); \
- (s)[(i)++] = (uint16_t)(((c)&0x3ff) | 0xdc00); \
- } \
- }
-
-} // namesapce base_icu
-
-#endif // BASE_THIRD_PARTY_ICU_ICU_UTF_H_
diff --git a/security/sandbox/chromium/base/third_party/superfasthash/LICENSE b/security/sandbox/chromium/base/third_party/superfasthash/LICENSE
deleted file mode 100644
index 3c40a3ecd..000000000
--- a/security/sandbox/chromium/base/third_party/superfasthash/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Paul Hsieh OLD BSD license
-
-Copyright (c) 2010, Paul Hsieh
-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 my name, Paul Hsieh, nor the names of any other contributors to the
- code use may not 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/security/sandbox/chromium/base/third_party/superfasthash/README.chromium b/security/sandbox/chromium/base/third_party/superfasthash/README.chromium
deleted file mode 100644
index d41ed7724..000000000
--- a/security/sandbox/chromium/base/third_party/superfasthash/README.chromium
+++ /dev/null
@@ -1,29 +0,0 @@
-Name: Paul Hsieh's SuperFastHash
-Short Name: SuperFastHash
-URL: http://www.azillionmonkeys.com/qed/hash.html
-Version: 0
-Date: 2012-02-21
-License: BSD
-License File: LICENSE
-Security Critical: yes
-
-Description:
-A fast string hashing algorithm.
-
-Local Modifications:
-- Added LICENSE.
-- Added license text as a comment to the top of superfasthash.c.
-- #include <stdint.h> instead of "pstdint.h".
-- #include <stdlib.h>.
-
-The license is a standard 3-clause BSD license with the following minor changes:
-
-"nor the names of its contributors may be used"
-is replaced with:
-"nor the names of any other contributors to the code use may not be used"
-
-and
-
-"IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE"
-is replaced with:
-"IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE"
diff --git a/security/sandbox/chromium/base/third_party/superfasthash/superfasthash.c b/security/sandbox/chromium/base/third_party/superfasthash/superfasthash.c
deleted file mode 100644
index 6e7687e13..000000000
--- a/security/sandbox/chromium/base/third_party/superfasthash/superfasthash.c
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright (c) 2010, Paul Hsieh
-// 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 my name, Paul Hsieh, nor the names of any other contributors to the
-// code use may not 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.
-
-#include <stdint.h>
-#include <stdlib.h>
-#undef get16bits
-#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \
- || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__)
-#define get16bits(d) (*((const uint16_t *) (d)))
-#endif
-
-#if !defined (get16bits)
-#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
- +(uint32_t)(((const uint8_t *)(d))[0]) )
-#endif
-
-uint32_t SuperFastHash (const char * data, int len) {
-uint32_t hash = len, tmp;
-int rem;
-
- if (len <= 0 || data == NULL) return 0;
-
- rem = len & 3;
- len >>= 2;
-
- /* Main loop */
- for (;len > 0; len--) {
- hash += get16bits (data);
- tmp = (get16bits (data+2) << 11) ^ hash;
- hash = (hash << 16) ^ tmp;
- data += 2*sizeof (uint16_t);
- hash += hash >> 11;
- }
-
- /* Handle end cases */
- switch (rem) {
- case 3: hash += get16bits (data);
- hash ^= hash << 16;
- hash ^= ((signed char)data[sizeof (uint16_t)]) << 18;
- hash += hash >> 11;
- break;
- case 2: hash += get16bits (data);
- hash ^= hash << 11;
- hash += hash >> 17;
- break;
- case 1: hash += (signed char)*data;
- hash ^= hash << 10;
- hash += hash >> 1;
- }
-
- /* Force "avalanching" of final 127 bits */
- hash ^= hash << 3;
- hash += hash >> 5;
- hash ^= hash << 4;
- hash += hash >> 17;
- hash ^= hash << 25;
- hash += hash >> 6;
-
- return hash;
-}
diff --git a/security/sandbox/chromium/base/third_party/valgrind/LICENSE b/security/sandbox/chromium/base/third_party/valgrind/LICENSE
deleted file mode 100644
index 41f677bd1..000000000
--- a/security/sandbox/chromium/base/third_party/valgrind/LICENSE
+++ /dev/null
@@ -1,39 +0,0 @@
- Notice that the following BSD-style license applies to the Valgrind header
- files used by Chromium (valgrind.h and memcheck.h). However, the rest of
- Valgrind is licensed under the terms of the GNU General Public License,
- version 2, unless otherwise indicated.
-
- ----------------------------------------------------------------
-
- Copyright (C) 2000-2008 Julian Seward. 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. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
- documentation would be appreciated but is not required.
-
- 3. Altered source versions must be plainly marked as such, and must
- not be misrepresented as being the original software.
-
- 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.
diff --git a/security/sandbox/chromium/base/third_party/valgrind/valgrind.h b/security/sandbox/chromium/base/third_party/valgrind/valgrind.h
deleted file mode 100644
index 0bae0aa13..000000000
--- a/security/sandbox/chromium/base/third_party/valgrind/valgrind.h
+++ /dev/null
@@ -1,4792 +0,0 @@
-/* -*- c -*-
- ----------------------------------------------------------------
-
- Notice that the following BSD-style license applies to this one
- file (valgrind.h) only. The rest of Valgrind is licensed under the
- terms of the GNU General Public License, version 2, unless
- otherwise indicated. See the COPYING file in the source
- distribution for details.
-
- ----------------------------------------------------------------
-
- This file is part of Valgrind, a dynamic binary instrumentation
- framework.
-
- Copyright (C) 2000-2010 Julian Seward. 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. The origin of this software must not be misrepresented; you must
- not claim that you wrote the original software. If you use this
- software in a product, an acknowledgment in the product
- documentation would be appreciated but is not required.
-
- 3. Altered source versions must be plainly marked as such, and must
- not be misrepresented as being the original software.
-
- 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.
-
- ----------------------------------------------------------------
-
- Notice that the above BSD-style license applies to this one file
- (valgrind.h) only. The entire rest of Valgrind is licensed under
- the terms of the GNU General Public License, version 2. See the
- COPYING file in the source distribution for details.
-
- ----------------------------------------------------------------
-*/
-
-
-/* This file is for inclusion into client (your!) code.
-
- You can use these macros to manipulate and query Valgrind's
- execution inside your own programs.
-
- The resulting executables will still run without Valgrind, just a
- little bit more slowly than they otherwise would, but otherwise
- unchanged. When not running on valgrind, each client request
- consumes very few (eg. 7) instructions, so the resulting performance
- loss is negligible unless you plan to execute client requests
- millions of times per second. Nevertheless, if that is still a
- problem, you can compile with the NVALGRIND symbol defined (gcc
- -DNVALGRIND) so that client requests are not even compiled in. */
-
-#ifndef __VALGRIND_H
-#define __VALGRIND_H
-
-
-/* ------------------------------------------------------------------ */
-/* VERSION NUMBER OF VALGRIND */
-/* ------------------------------------------------------------------ */
-
-/* Specify Valgrind's version number, so that user code can
- conditionally compile based on our version number. Note that these
- were introduced at version 3.6 and so do not exist in version 3.5
- or earlier. The recommended way to use them to check for "version
- X.Y or later" is (eg)
-
-#if defined(__VALGRIND_MAJOR__) && defined(__VALGRIND_MINOR__) \
- && (__VALGRIND_MAJOR__ > 3 \
- || (__VALGRIND_MAJOR__ == 3 && __VALGRIND_MINOR__ >= 6))
-*/
-#define __VALGRIND_MAJOR__ 3
-#define __VALGRIND_MINOR__ 6
-
-
-#include <stdarg.h>
-
-/* Nb: this file might be included in a file compiled with -ansi. So
- we can't use C++ style "//" comments nor the "asm" keyword (instead
- use "__asm__"). */
-
-/* Derive some tags indicating what the target platform is. Note
- that in this file we're using the compiler's CPP symbols for
- identifying architectures, which are different to the ones we use
- within the rest of Valgrind. Note, __powerpc__ is active for both
- 32 and 64-bit PPC, whereas __powerpc64__ is only active for the
- latter (on Linux, that is).
-
- Misc note: how to find out what's predefined in gcc by default:
- gcc -Wp,-dM somefile.c
-*/
-#undef PLAT_ppc64_aix5
-#undef PLAT_ppc32_aix5
-#undef PLAT_x86_darwin
-#undef PLAT_amd64_darwin
-#undef PLAT_x86_win32
-#undef PLAT_x86_linux
-#undef PLAT_amd64_linux
-#undef PLAT_ppc32_linux
-#undef PLAT_ppc64_linux
-#undef PLAT_arm_linux
-
-#if defined(_AIX) && defined(__64BIT__)
-# define PLAT_ppc64_aix5 1
-#elif defined(_AIX) && !defined(__64BIT__)
-# define PLAT_ppc32_aix5 1
-#elif defined(__APPLE__) && defined(__i386__)
-# define PLAT_x86_darwin 1
-#elif defined(__APPLE__) && defined(__x86_64__)
-# define PLAT_amd64_darwin 1
-#elif defined(__MINGW32__) || defined(__CYGWIN32__) || defined(_WIN32) && defined(_M_IX86)
-# define PLAT_x86_win32 1
-#elif defined(__linux__) && defined(__i386__)
-# define PLAT_x86_linux 1
-#elif defined(__linux__) && defined(__x86_64__)
-# define PLAT_amd64_linux 1
-#elif defined(__linux__) && defined(__powerpc__) && !defined(__powerpc64__)
-# define PLAT_ppc32_linux 1
-#elif defined(__linux__) && defined(__powerpc__) && defined(__powerpc64__)
-# define PLAT_ppc64_linux 1
-#elif defined(__linux__) && defined(__arm__)
-# define PLAT_arm_linux 1
-#else
-/* If we're not compiling for our target platform, don't generate
- any inline asms. */
-# if !defined(NVALGRIND)
-# define NVALGRIND 1
-# endif
-#endif
-
-
-/* ------------------------------------------------------------------ */
-/* ARCHITECTURE SPECIFICS for SPECIAL INSTRUCTIONS. There is nothing */
-/* in here of use to end-users -- skip to the next section. */
-/* ------------------------------------------------------------------ */
-
-#if defined(NVALGRIND)
-
-/* Define NVALGRIND to completely remove the Valgrind magic sequence
- from the compiled code (analogous to NDEBUG's effects on
- assert()) */
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- { \
- (_zzq_rlval) = (_zzq_default); \
- }
-
-#else /* ! NVALGRIND */
-
-/* The following defines the magic code sequences which the JITter
- spots and handles magically. Don't look too closely at them as
- they will rot your brain.
-
- The assembly code sequences for all architectures is in this one
- file. This is because this file must be stand-alone, and we don't
- want to have multiple files.
-
- For VALGRIND_DO_CLIENT_REQUEST, we must ensure that the default
- value gets put in the return slot, so that everything works when
- this is executed not under Valgrind. Args are passed in a memory
- block, and so there's no intrinsic limit to the number that could
- be passed, but it's currently five.
-
- The macro args are:
- _zzq_rlval result lvalue
- _zzq_default default value (result returned when running on real CPU)
- _zzq_request request code
- _zzq_arg1..5 request params
-
- The other two macros are used to support function wrapping, and are
- a lot simpler. VALGRIND_GET_NR_CONTEXT returns the value of the
- guest's NRADDR pseudo-register and whatever other information is
- needed to safely run the call original from the wrapper: on
- ppc64-linux, the R2 value at the divert point is also needed. This
- information is abstracted into a user-visible type, OrigFn.
-
- VALGRIND_CALL_NOREDIR_* behaves the same as the following on the
- guest, but guarantees that the branch instruction will not be
- redirected: x86: call *%eax, amd64: call *%rax, ppc32/ppc64:
- branch-and-link-to-r11. VALGRIND_CALL_NOREDIR is just text, not a
- complete inline asm, since it needs to be combined with more magic
- inline asm stuff to be useful.
-*/
-
-/* ------------------------- x86-{linux,darwin} ---------------- */
-
-#if defined(PLAT_x86_linux) || defined(PLAT_x86_darwin) \
- || (defined(PLAT_x86_win32) && defined(__GNUC__))
-
-typedef
- struct {
- unsigned int nraddr; /* where's the code? */
- }
- OrigFn;
-
-#define __SPECIAL_INSTRUCTION_PREAMBLE \
- "roll $3, %%edi ; roll $13, %%edi\n\t" \
- "roll $29, %%edi ; roll $19, %%edi\n\t"
-
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- { volatile unsigned int _zzq_args[6]; \
- volatile unsigned int _zzq_result; \
- _zzq_args[0] = (unsigned int)(_zzq_request); \
- _zzq_args[1] = (unsigned int)(_zzq_arg1); \
- _zzq_args[2] = (unsigned int)(_zzq_arg2); \
- _zzq_args[3] = (unsigned int)(_zzq_arg3); \
- _zzq_args[4] = (unsigned int)(_zzq_arg4); \
- _zzq_args[5] = (unsigned int)(_zzq_arg5); \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %EDX = client_request ( %EAX ) */ \
- "xchgl %%ebx,%%ebx" \
- : "=d" (_zzq_result) \
- : "a" (&_zzq_args[0]), "0" (_zzq_default) \
- : "cc", "memory" \
- ); \
- _zzq_rlval = _zzq_result; \
- }
-
-#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
- { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
- volatile unsigned int __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %EAX = guest_NRADDR */ \
- "xchgl %%ecx,%%ecx" \
- : "=a" (__addr) \
- : \
- : "cc", "memory" \
- ); \
- _zzq_orig->nraddr = __addr; \
- }
-
-#define VALGRIND_CALL_NOREDIR_EAX \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* call-noredir *%EAX */ \
- "xchgl %%edx,%%edx\n\t"
-#endif /* PLAT_x86_linux || PLAT_x86_darwin || (PLAT_x86_win32 && __GNUC__) */
-
-/* ------------------------- x86-Win32 ------------------------- */
-
-#if defined(PLAT_x86_win32) && !defined(__GNUC__)
-
-typedef
- struct {
- unsigned int nraddr; /* where's the code? */
- }
- OrigFn;
-
-#if defined(_MSC_VER)
-
-#define __SPECIAL_INSTRUCTION_PREAMBLE \
- __asm rol edi, 3 __asm rol edi, 13 \
- __asm rol edi, 29 __asm rol edi, 19
-
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- { volatile uintptr_t _zzq_args[6]; \
- volatile unsigned int _zzq_result; \
- _zzq_args[0] = (uintptr_t)(_zzq_request); \
- _zzq_args[1] = (uintptr_t)(_zzq_arg1); \
- _zzq_args[2] = (uintptr_t)(_zzq_arg2); \
- _zzq_args[3] = (uintptr_t)(_zzq_arg3); \
- _zzq_args[4] = (uintptr_t)(_zzq_arg4); \
- _zzq_args[5] = (uintptr_t)(_zzq_arg5); \
- __asm { __asm lea eax, _zzq_args __asm mov edx, _zzq_default \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* %EDX = client_request ( %EAX ) */ \
- __asm xchg ebx,ebx \
- __asm mov _zzq_result, edx \
- } \
- _zzq_rlval = _zzq_result; \
- }
-
-#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
- { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
- volatile unsigned int __addr; \
- __asm { __SPECIAL_INSTRUCTION_PREAMBLE \
- /* %EAX = guest_NRADDR */ \
- __asm xchg ecx,ecx \
- __asm mov __addr, eax \
- } \
- _zzq_orig->nraddr = __addr; \
- }
-
-#define VALGRIND_CALL_NOREDIR_EAX ERROR
-
-#else
-#error Unsupported compiler.
-#endif
-
-#endif /* PLAT_x86_win32 */
-
-/* ------------------------ amd64-{linux,darwin} --------------- */
-
-#if defined(PLAT_amd64_linux) || defined(PLAT_amd64_darwin)
-
-typedef
- struct {
- unsigned long long int nraddr; /* where's the code? */
- }
- OrigFn;
-
-#define __SPECIAL_INSTRUCTION_PREAMBLE \
- "rolq $3, %%rdi ; rolq $13, %%rdi\n\t" \
- "rolq $61, %%rdi ; rolq $51, %%rdi\n\t"
-
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- { volatile unsigned long long int _zzq_args[6]; \
- volatile unsigned long long int _zzq_result; \
- _zzq_args[0] = (unsigned long long int)(_zzq_request); \
- _zzq_args[1] = (unsigned long long int)(_zzq_arg1); \
- _zzq_args[2] = (unsigned long long int)(_zzq_arg2); \
- _zzq_args[3] = (unsigned long long int)(_zzq_arg3); \
- _zzq_args[4] = (unsigned long long int)(_zzq_arg4); \
- _zzq_args[5] = (unsigned long long int)(_zzq_arg5); \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %RDX = client_request ( %RAX ) */ \
- "xchgq %%rbx,%%rbx" \
- : "=d" (_zzq_result) \
- : "a" (&_zzq_args[0]), "0" (_zzq_default) \
- : "cc", "memory" \
- ); \
- _zzq_rlval = _zzq_result; \
- }
-
-#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
- { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
- volatile unsigned long long int __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %RAX = guest_NRADDR */ \
- "xchgq %%rcx,%%rcx" \
- : "=a" (__addr) \
- : \
- : "cc", "memory" \
- ); \
- _zzq_orig->nraddr = __addr; \
- }
-
-#define VALGRIND_CALL_NOREDIR_RAX \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* call-noredir *%RAX */ \
- "xchgq %%rdx,%%rdx\n\t"
-#endif /* PLAT_amd64_linux || PLAT_amd64_darwin */
-
-/* ------------------------ ppc32-linux ------------------------ */
-
-#if defined(PLAT_ppc32_linux)
-
-typedef
- struct {
- unsigned int nraddr; /* where's the code? */
- }
- OrigFn;
-
-#define __SPECIAL_INSTRUCTION_PREAMBLE \
- "rlwinm 0,0,3,0,0 ; rlwinm 0,0,13,0,0\n\t" \
- "rlwinm 0,0,29,0,0 ; rlwinm 0,0,19,0,0\n\t"
-
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- \
- { unsigned int _zzq_args[6]; \
- unsigned int _zzq_result; \
- unsigned int* _zzq_ptr; \
- _zzq_args[0] = (unsigned int)(_zzq_request); \
- _zzq_args[1] = (unsigned int)(_zzq_arg1); \
- _zzq_args[2] = (unsigned int)(_zzq_arg2); \
- _zzq_args[3] = (unsigned int)(_zzq_arg3); \
- _zzq_args[4] = (unsigned int)(_zzq_arg4); \
- _zzq_args[5] = (unsigned int)(_zzq_arg5); \
- _zzq_ptr = _zzq_args; \
- __asm__ volatile("mr 3,%1\n\t" /*default*/ \
- "mr 4,%2\n\t" /*ptr*/ \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = client_request ( %R4 ) */ \
- "or 1,1,1\n\t" \
- "mr %0,3" /*result*/ \
- : "=b" (_zzq_result) \
- : "b" (_zzq_default), "b" (_zzq_ptr) \
- : "cc", "memory", "r3", "r4"); \
- _zzq_rlval = _zzq_result; \
- }
-
-#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
- { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
- unsigned int __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = guest_NRADDR */ \
- "or 2,2,2\n\t" \
- "mr %0,3" \
- : "=b" (__addr) \
- : \
- : "cc", "memory", "r3" \
- ); \
- _zzq_orig->nraddr = __addr; \
- }
-
-#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* branch-and-link-to-noredir *%R11 */ \
- "or 3,3,3\n\t"
-#endif /* PLAT_ppc32_linux */
-
-/* ------------------------ ppc64-linux ------------------------ */
-
-#if defined(PLAT_ppc64_linux)
-
-typedef
- struct {
- unsigned long long int nraddr; /* where's the code? */
- unsigned long long int r2; /* what tocptr do we need? */
- }
- OrigFn;
-
-#define __SPECIAL_INSTRUCTION_PREAMBLE \
- "rotldi 0,0,3 ; rotldi 0,0,13\n\t" \
- "rotldi 0,0,61 ; rotldi 0,0,51\n\t"
-
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- \
- { unsigned long long int _zzq_args[6]; \
- register unsigned long long int _zzq_result __asm__("r3"); \
- register unsigned long long int* _zzq_ptr __asm__("r4"); \
- _zzq_args[0] = (unsigned long long int)(_zzq_request); \
- _zzq_args[1] = (unsigned long long int)(_zzq_arg1); \
- _zzq_args[2] = (unsigned long long int)(_zzq_arg2); \
- _zzq_args[3] = (unsigned long long int)(_zzq_arg3); \
- _zzq_args[4] = (unsigned long long int)(_zzq_arg4); \
- _zzq_args[5] = (unsigned long long int)(_zzq_arg5); \
- _zzq_ptr = _zzq_args; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = client_request ( %R4 ) */ \
- "or 1,1,1" \
- : "=r" (_zzq_result) \
- : "0" (_zzq_default), "r" (_zzq_ptr) \
- : "cc", "memory"); \
- _zzq_rlval = _zzq_result; \
- }
-
-#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
- { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
- register unsigned long long int __addr __asm__("r3"); \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = guest_NRADDR */ \
- "or 2,2,2" \
- : "=r" (__addr) \
- : \
- : "cc", "memory" \
- ); \
- _zzq_orig->nraddr = __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = guest_NRADDR_GPR2 */ \
- "or 4,4,4" \
- : "=r" (__addr) \
- : \
- : "cc", "memory" \
- ); \
- _zzq_orig->r2 = __addr; \
- }
-
-#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* branch-and-link-to-noredir *%R11 */ \
- "or 3,3,3\n\t"
-
-#endif /* PLAT_ppc64_linux */
-
-/* ------------------------- arm-linux ------------------------- */
-
-#if defined(PLAT_arm_linux)
-
-typedef
- struct {
- unsigned int nraddr; /* where's the code? */
- }
- OrigFn;
-
-#define __SPECIAL_INSTRUCTION_PREAMBLE \
- "mov r12, r12, ror #3 ; mov r12, r12, ror #13 \n\t" \
- "mov r12, r12, ror #29 ; mov r12, r12, ror #19 \n\t"
-
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- \
- { volatile unsigned int _zzq_args[6]; \
- volatile unsigned int _zzq_result; \
- _zzq_args[0] = (unsigned int)(_zzq_request); \
- _zzq_args[1] = (unsigned int)(_zzq_arg1); \
- _zzq_args[2] = (unsigned int)(_zzq_arg2); \
- _zzq_args[3] = (unsigned int)(_zzq_arg3); \
- _zzq_args[4] = (unsigned int)(_zzq_arg4); \
- _zzq_args[5] = (unsigned int)(_zzq_arg5); \
- __asm__ volatile("mov r3, %1\n\t" /*default*/ \
- "mov r4, %2\n\t" /*ptr*/ \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* R3 = client_request ( R4 ) */ \
- "orr r10, r10, r10\n\t" \
- "mov %0, r3" /*result*/ \
- : "=r" (_zzq_result) \
- : "r" (_zzq_default), "r" (&_zzq_args[0]) \
- : "cc","memory", "r3", "r4"); \
- _zzq_rlval = _zzq_result; \
- }
-
-#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
- { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
- unsigned int __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* R3 = guest_NRADDR */ \
- "orr r11, r11, r11\n\t" \
- "mov %0, r3" \
- : "=r" (__addr) \
- : \
- : "cc", "memory", "r3" \
- ); \
- _zzq_orig->nraddr = __addr; \
- }
-
-#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* branch-and-link-to-noredir *%R4 */ \
- "orr r12, r12, r12\n\t"
-
-#endif /* PLAT_arm_linux */
-
-/* ------------------------ ppc32-aix5 ------------------------- */
-
-#if defined(PLAT_ppc32_aix5)
-
-typedef
- struct {
- unsigned int nraddr; /* where's the code? */
- unsigned int r2; /* what tocptr do we need? */
- }
- OrigFn;
-
-#define __SPECIAL_INSTRUCTION_PREAMBLE \
- "rlwinm 0,0,3,0,0 ; rlwinm 0,0,13,0,0\n\t" \
- "rlwinm 0,0,29,0,0 ; rlwinm 0,0,19,0,0\n\t"
-
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- \
- { unsigned int _zzq_args[7]; \
- register unsigned int _zzq_result; \
- register unsigned int* _zzq_ptr; \
- _zzq_args[0] = (unsigned int)(_zzq_request); \
- _zzq_args[1] = (unsigned int)(_zzq_arg1); \
- _zzq_args[2] = (unsigned int)(_zzq_arg2); \
- _zzq_args[3] = (unsigned int)(_zzq_arg3); \
- _zzq_args[4] = (unsigned int)(_zzq_arg4); \
- _zzq_args[5] = (unsigned int)(_zzq_arg5); \
- _zzq_args[6] = (unsigned int)(_zzq_default); \
- _zzq_ptr = _zzq_args; \
- __asm__ volatile("mr 4,%1\n\t" \
- "lwz 3, 24(4)\n\t" \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = client_request ( %R4 ) */ \
- "or 1,1,1\n\t" \
- "mr %0,3" \
- : "=b" (_zzq_result) \
- : "b" (_zzq_ptr) \
- : "r3", "r4", "cc", "memory"); \
- _zzq_rlval = _zzq_result; \
- }
-
-#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
- { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
- register unsigned int __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = guest_NRADDR */ \
- "or 2,2,2\n\t" \
- "mr %0,3" \
- : "=b" (__addr) \
- : \
- : "r3", "cc", "memory" \
- ); \
- _zzq_orig->nraddr = __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = guest_NRADDR_GPR2 */ \
- "or 4,4,4\n\t" \
- "mr %0,3" \
- : "=b" (__addr) \
- : \
- : "r3", "cc", "memory" \
- ); \
- _zzq_orig->r2 = __addr; \
- }
-
-#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* branch-and-link-to-noredir *%R11 */ \
- "or 3,3,3\n\t"
-
-#endif /* PLAT_ppc32_aix5 */
-
-/* ------------------------ ppc64-aix5 ------------------------- */
-
-#if defined(PLAT_ppc64_aix5)
-
-typedef
- struct {
- unsigned long long int nraddr; /* where's the code? */
- unsigned long long int r2; /* what tocptr do we need? */
- }
- OrigFn;
-
-#define __SPECIAL_INSTRUCTION_PREAMBLE \
- "rotldi 0,0,3 ; rotldi 0,0,13\n\t" \
- "rotldi 0,0,61 ; rotldi 0,0,51\n\t"
-
-#define VALGRIND_DO_CLIENT_REQUEST( \
- _zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- \
- { unsigned long long int _zzq_args[7]; \
- register unsigned long long int _zzq_result; \
- register unsigned long long int* _zzq_ptr; \
- _zzq_args[0] = (unsigned int long long)(_zzq_request); \
- _zzq_args[1] = (unsigned int long long)(_zzq_arg1); \
- _zzq_args[2] = (unsigned int long long)(_zzq_arg2); \
- _zzq_args[3] = (unsigned int long long)(_zzq_arg3); \
- _zzq_args[4] = (unsigned int long long)(_zzq_arg4); \
- _zzq_args[5] = (unsigned int long long)(_zzq_arg5); \
- _zzq_args[6] = (unsigned int long long)(_zzq_default); \
- _zzq_ptr = _zzq_args; \
- __asm__ volatile("mr 4,%1\n\t" \
- "ld 3, 48(4)\n\t" \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = client_request ( %R4 ) */ \
- "or 1,1,1\n\t" \
- "mr %0,3" \
- : "=b" (_zzq_result) \
- : "b" (_zzq_ptr) \
- : "r3", "r4", "cc", "memory"); \
- _zzq_rlval = _zzq_result; \
- }
-
-#define VALGRIND_GET_NR_CONTEXT(_zzq_rlval) \
- { volatile OrigFn* _zzq_orig = &(_zzq_rlval); \
- register unsigned long long int __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = guest_NRADDR */ \
- "or 2,2,2\n\t" \
- "mr %0,3" \
- : "=b" (__addr) \
- : \
- : "r3", "cc", "memory" \
- ); \
- _zzq_orig->nraddr = __addr; \
- __asm__ volatile(__SPECIAL_INSTRUCTION_PREAMBLE \
- /* %R3 = guest_NRADDR_GPR2 */ \
- "or 4,4,4\n\t" \
- "mr %0,3" \
- : "=b" (__addr) \
- : \
- : "r3", "cc", "memory" \
- ); \
- _zzq_orig->r2 = __addr; \
- }
-
-#define VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- __SPECIAL_INSTRUCTION_PREAMBLE \
- /* branch-and-link-to-noredir *%R11 */ \
- "or 3,3,3\n\t"
-
-#endif /* PLAT_ppc64_aix5 */
-
-/* Insert assembly code for other platforms here... */
-
-#endif /* NVALGRIND */
-
-
-/* ------------------------------------------------------------------ */
-/* PLATFORM SPECIFICS for FUNCTION WRAPPING. This is all very */
-/* ugly. It's the least-worst tradeoff I can think of. */
-/* ------------------------------------------------------------------ */
-
-/* This section defines magic (a.k.a appalling-hack) macros for doing
- guaranteed-no-redirection macros, so as to get from function
- wrappers to the functions they are wrapping. The whole point is to
- construct standard call sequences, but to do the call itself with a
- special no-redirect call pseudo-instruction that the JIT
- understands and handles specially. This section is long and
- repetitious, and I can't see a way to make it shorter.
-
- The naming scheme is as follows:
-
- CALL_FN_{W,v}_{v,W,WW,WWW,WWWW,5W,6W,7W,etc}
-
- 'W' stands for "word" and 'v' for "void". Hence there are
- different macros for calling arity 0, 1, 2, 3, 4, etc, functions,
- and for each, the possibility of returning a word-typed result, or
- no result.
-*/
-
-/* Use these to write the name of your wrapper. NOTE: duplicates
- VG_WRAP_FUNCTION_Z{U,Z} in pub_tool_redir.h. */
-
-/* Use an extra level of macroisation so as to ensure the soname/fnname
- args are fully macro-expanded before pasting them together. */
-#define VG_CONCAT4(_aa,_bb,_cc,_dd) _aa##_bb##_cc##_dd
-
-#define I_WRAP_SONAME_FNNAME_ZU(soname,fnname) \
- VG_CONCAT4(_vgwZU_,soname,_,fnname)
-
-#define I_WRAP_SONAME_FNNAME_ZZ(soname,fnname) \
- VG_CONCAT4(_vgwZZ_,soname,_,fnname)
-
-/* Use this macro from within a wrapper function to collect the
- context (address and possibly other info) of the original function.
- Once you have that you can then use it in one of the CALL_FN_
- macros. The type of the argument _lval is OrigFn. */
-#define VALGRIND_GET_ORIG_FN(_lval) VALGRIND_GET_NR_CONTEXT(_lval)
-
-/* Derivatives of the main macros below, for calling functions
- returning void. */
-
-#define CALL_FN_v_v(fnptr) \
- do { volatile unsigned long _junk; \
- CALL_FN_W_v(_junk,fnptr); } while (0)
-
-#define CALL_FN_v_W(fnptr, arg1) \
- do { volatile unsigned long _junk; \
- CALL_FN_W_W(_junk,fnptr,arg1); } while (0)
-
-#define CALL_FN_v_WW(fnptr, arg1,arg2) \
- do { volatile unsigned long _junk; \
- CALL_FN_W_WW(_junk,fnptr,arg1,arg2); } while (0)
-
-#define CALL_FN_v_WWW(fnptr, arg1,arg2,arg3) \
- do { volatile unsigned long _junk; \
- CALL_FN_W_WWW(_junk,fnptr,arg1,arg2,arg3); } while (0)
-
-#define CALL_FN_v_WWWW(fnptr, arg1,arg2,arg3,arg4) \
- do { volatile unsigned long _junk; \
- CALL_FN_W_WWWW(_junk,fnptr,arg1,arg2,arg3,arg4); } while (0)
-
-#define CALL_FN_v_5W(fnptr, arg1,arg2,arg3,arg4,arg5) \
- do { volatile unsigned long _junk; \
- CALL_FN_W_5W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5); } while (0)
-
-#define CALL_FN_v_6W(fnptr, arg1,arg2,arg3,arg4,arg5,arg6) \
- do { volatile unsigned long _junk; \
- CALL_FN_W_6W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5,arg6); } while (0)
-
-#define CALL_FN_v_7W(fnptr, arg1,arg2,arg3,arg4,arg5,arg6,arg7) \
- do { volatile unsigned long _junk; \
- CALL_FN_W_7W(_junk,fnptr,arg1,arg2,arg3,arg4,arg5,arg6,arg7); } while (0)
-
-/* ------------------------- x86-{linux,darwin} ---------------- */
-
-#if defined(PLAT_x86_linux) || defined(PLAT_x86_darwin)
-
-/* These regs are trashed by the hidden call. No need to mention eax
- as gcc can already see that, plus causes gcc to bomb. */
-#define __CALLER_SAVED_REGS /*"eax"*/ "ecx", "edx"
-
-/* These CALL_FN_ macros assume that on x86-linux, sizeof(unsigned
- long) == 4. */
-
-#define CALL_FN_W_v(lval, orig) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[1]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- __asm__ volatile( \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_W(lval, orig, arg1) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[2]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- __asm__ volatile( \
- "subl $12, %%esp\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $16, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- __asm__ volatile( \
- "subl $8, %%esp\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $16, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[4]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- __asm__ volatile( \
- "subl $4, %%esp\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $16, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[5]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- __asm__ volatile( \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $16, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[6]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- __asm__ volatile( \
- "subl $12, %%esp\n\t" \
- "pushl 20(%%eax)\n\t" \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $32, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[7]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- __asm__ volatile( \
- "subl $8, %%esp\n\t" \
- "pushl 24(%%eax)\n\t" \
- "pushl 20(%%eax)\n\t" \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $32, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[8]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- __asm__ volatile( \
- "subl $4, %%esp\n\t" \
- "pushl 28(%%eax)\n\t" \
- "pushl 24(%%eax)\n\t" \
- "pushl 20(%%eax)\n\t" \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $32, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[9]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- __asm__ volatile( \
- "pushl 32(%%eax)\n\t" \
- "pushl 28(%%eax)\n\t" \
- "pushl 24(%%eax)\n\t" \
- "pushl 20(%%eax)\n\t" \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $32, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[10]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- __asm__ volatile( \
- "subl $12, %%esp\n\t" \
- "pushl 36(%%eax)\n\t" \
- "pushl 32(%%eax)\n\t" \
- "pushl 28(%%eax)\n\t" \
- "pushl 24(%%eax)\n\t" \
- "pushl 20(%%eax)\n\t" \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $48, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[11]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- __asm__ volatile( \
- "subl $8, %%esp\n\t" \
- "pushl 40(%%eax)\n\t" \
- "pushl 36(%%eax)\n\t" \
- "pushl 32(%%eax)\n\t" \
- "pushl 28(%%eax)\n\t" \
- "pushl 24(%%eax)\n\t" \
- "pushl 20(%%eax)\n\t" \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $48, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \
- arg6,arg7,arg8,arg9,arg10, \
- arg11) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[12]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- _argvec[11] = (unsigned long)(arg11); \
- __asm__ volatile( \
- "subl $4, %%esp\n\t" \
- "pushl 44(%%eax)\n\t" \
- "pushl 40(%%eax)\n\t" \
- "pushl 36(%%eax)\n\t" \
- "pushl 32(%%eax)\n\t" \
- "pushl 28(%%eax)\n\t" \
- "pushl 24(%%eax)\n\t" \
- "pushl 20(%%eax)\n\t" \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $48, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \
- arg6,arg7,arg8,arg9,arg10, \
- arg11,arg12) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[13]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- _argvec[11] = (unsigned long)(arg11); \
- _argvec[12] = (unsigned long)(arg12); \
- __asm__ volatile( \
- "pushl 48(%%eax)\n\t" \
- "pushl 44(%%eax)\n\t" \
- "pushl 40(%%eax)\n\t" \
- "pushl 36(%%eax)\n\t" \
- "pushl 32(%%eax)\n\t" \
- "pushl 28(%%eax)\n\t" \
- "pushl 24(%%eax)\n\t" \
- "pushl 20(%%eax)\n\t" \
- "pushl 16(%%eax)\n\t" \
- "pushl 12(%%eax)\n\t" \
- "pushl 8(%%eax)\n\t" \
- "pushl 4(%%eax)\n\t" \
- "movl (%%eax), %%eax\n\t" /* target->%eax */ \
- VALGRIND_CALL_NOREDIR_EAX \
- "addl $48, %%esp\n" \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#endif /* PLAT_x86_linux || PLAT_x86_darwin */
-
-/* ------------------------ amd64-{linux,darwin} --------------- */
-
-#if defined(PLAT_amd64_linux) || defined(PLAT_amd64_darwin)
-
-/* ARGREGS: rdi rsi rdx rcx r8 r9 (the rest on stack in R-to-L order) */
-
-/* These regs are trashed by the hidden call. */
-#define __CALLER_SAVED_REGS /*"rax",*/ "rcx", "rdx", "rsi", \
- "rdi", "r8", "r9", "r10", "r11"
-
-/* This is all pretty complex. It's so as to make stack unwinding
- work reliably. See bug 243270. The basic problem is the sub and
- add of 128 of %rsp in all of the following macros. If gcc believes
- the CFA is in %rsp, then unwinding may fail, because what's at the
- CFA is not what gcc "expected" when it constructs the CFIs for the
- places where the macros are instantiated.
-
- But we can't just add a CFI annotation to increase the CFA offset
- by 128, to match the sub of 128 from %rsp, because we don't know
- whether gcc has chosen %rsp as the CFA at that point, or whether it
- has chosen some other register (eg, %rbp). In the latter case,
- adding a CFI annotation to change the CFA offset is simply wrong.
-
- So the solution is to get hold of the CFA using
- __builtin_dwarf_cfa(), put it in a known register, and add a
- CFI annotation to say what the register is. We choose %rbp for
- this (perhaps perversely), because:
-
- (1) %rbp is already subject to unwinding. If a new register was
- chosen then the unwinder would have to unwind it in all stack
- traces, which is expensive, and
-
- (2) %rbp is already subject to precise exception updates in the
- JIT. If a new register was chosen, we'd have to have precise
- exceptions for it too, which reduces performance of the
- generated code.
-
- However .. one extra complication. We can't just whack the result
- of __builtin_dwarf_cfa() into %rbp and then add %rbp to the
- list of trashed registers at the end of the inline assembly
- fragments; gcc won't allow %rbp to appear in that list. Hence
- instead we need to stash %rbp in %r15 for the duration of the asm,
- and say that %r15 is trashed instead. gcc seems happy to go with
- that.
-
- Oh .. and this all needs to be conditionalised so that it is
- unchanged from before this commit, when compiled with older gccs
- that don't support __builtin_dwarf_cfa. Furthermore, since
- this header file is freestanding, it has to be independent of
- config.h, and so the following conditionalisation cannot depend on
- configure time checks.
-
- Although it's not clear from
- 'defined(__GNUC__) && defined(__GCC_HAVE_DWARF2_CFI_ASM)',
- this expression excludes Darwin.
- .cfi directives in Darwin assembly appear to be completely
- different and I haven't investigated how they work.
-
- For even more entertainment value, note we have to use the
- completely undocumented __builtin_dwarf_cfa(), which appears to
- really compute the CFA, whereas __builtin_frame_address(0) claims
- to but actually doesn't. See
- https://bugs.kde.org/show_bug.cgi?id=243270#c47
-*/
-#if defined(__GNUC__) && defined(__GCC_HAVE_DWARF2_CFI_ASM)
-# define __FRAME_POINTER \
- ,"r"(__builtin_dwarf_cfa())
-# define VALGRIND_CFI_PROLOGUE \
- "movq %%rbp, %%r15\n\t" \
- "movq %2, %%rbp\n\t" \
- ".cfi_remember_state\n\t" \
- ".cfi_def_cfa rbp, 0\n\t"
-# define VALGRIND_CFI_EPILOGUE \
- "movq %%r15, %%rbp\n\t" \
- ".cfi_restore_state\n\t"
-#else
-# define __FRAME_POINTER
-# define VALGRIND_CFI_PROLOGUE
-# define VALGRIND_CFI_EPILOGUE
-#endif
-
-
-/* These CALL_FN_ macros assume that on amd64-linux, sizeof(unsigned
- long) == 8. */
-
-/* NB 9 Sept 07. There is a nasty kludge here in all these CALL_FN_
- macros. In order not to trash the stack redzone, we need to drop
- %rsp by 128 before the hidden call, and restore afterwards. The
- nastyness is that it is only by luck that the stack still appears
- to be unwindable during the hidden call - since then the behaviour
- of any routine using this macro does not match what the CFI data
- says. Sigh.
-
- Why is this important? Imagine that a wrapper has a stack
- allocated local, and passes to the hidden call, a pointer to it.
- Because gcc does not know about the hidden call, it may allocate
- that local in the redzone. Unfortunately the hidden call may then
- trash it before it comes to use it. So we must step clear of the
- redzone, for the duration of the hidden call, to make it safe.
-
- Probably the same problem afflicts the other redzone-style ABIs too
- (ppc64-linux, ppc32-aix5, ppc64-aix5); but for those, the stack is
- self describing (none of this CFI nonsense) so at least messing
- with the stack pointer doesn't give a danger of non-unwindable
- stack. */
-
-#define CALL_FN_W_v(lval, orig) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[1]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_W(lval, orig, arg1) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[2]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[4]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[5]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[6]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "movq 40(%%rax), %%r8\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[7]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "movq 48(%%rax), %%r9\n\t" \
- "movq 40(%%rax), %%r8\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[8]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $136,%%rsp\n\t" \
- "pushq 56(%%rax)\n\t" \
- "movq 48(%%rax), %%r9\n\t" \
- "movq 40(%%rax), %%r8\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $8, %%rsp\n" \
- "addq $136,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[9]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "pushq 64(%%rax)\n\t" \
- "pushq 56(%%rax)\n\t" \
- "movq 48(%%rax), %%r9\n\t" \
- "movq 40(%%rax), %%r8\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $16, %%rsp\n" \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[10]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $136,%%rsp\n\t" \
- "pushq 72(%%rax)\n\t" \
- "pushq 64(%%rax)\n\t" \
- "pushq 56(%%rax)\n\t" \
- "movq 48(%%rax), %%r9\n\t" \
- "movq 40(%%rax), %%r8\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $24, %%rsp\n" \
- "addq $136,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[11]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "pushq 80(%%rax)\n\t" \
- "pushq 72(%%rax)\n\t" \
- "pushq 64(%%rax)\n\t" \
- "pushq 56(%%rax)\n\t" \
- "movq 48(%%rax), %%r9\n\t" \
- "movq 40(%%rax), %%r8\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $32, %%rsp\n" \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[12]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- _argvec[11] = (unsigned long)(arg11); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $136,%%rsp\n\t" \
- "pushq 88(%%rax)\n\t" \
- "pushq 80(%%rax)\n\t" \
- "pushq 72(%%rax)\n\t" \
- "pushq 64(%%rax)\n\t" \
- "pushq 56(%%rax)\n\t" \
- "movq 48(%%rax), %%r9\n\t" \
- "movq 40(%%rax), %%r8\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $40, %%rsp\n" \
- "addq $136,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11,arg12) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[13]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- _argvec[11] = (unsigned long)(arg11); \
- _argvec[12] = (unsigned long)(arg12); \
- __asm__ volatile( \
- VALGRIND_CFI_PROLOGUE \
- "subq $128,%%rsp\n\t" \
- "pushq 96(%%rax)\n\t" \
- "pushq 88(%%rax)\n\t" \
- "pushq 80(%%rax)\n\t" \
- "pushq 72(%%rax)\n\t" \
- "pushq 64(%%rax)\n\t" \
- "pushq 56(%%rax)\n\t" \
- "movq 48(%%rax), %%r9\n\t" \
- "movq 40(%%rax), %%r8\n\t" \
- "movq 32(%%rax), %%rcx\n\t" \
- "movq 24(%%rax), %%rdx\n\t" \
- "movq 16(%%rax), %%rsi\n\t" \
- "movq 8(%%rax), %%rdi\n\t" \
- "movq (%%rax), %%rax\n\t" /* target->%rax */ \
- VALGRIND_CALL_NOREDIR_RAX \
- "addq $48, %%rsp\n" \
- "addq $128,%%rsp\n\t" \
- VALGRIND_CFI_EPILOGUE \
- : /*out*/ "=a" (_res) \
- : /*in*/ "a" (&_argvec[0]) __FRAME_POINTER \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS, "r15" \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#endif /* PLAT_amd64_linux || PLAT_amd64_darwin */
-
-/* ------------------------ ppc32-linux ------------------------ */
-
-#if defined(PLAT_ppc32_linux)
-
-/* This is useful for finding out about the on-stack stuff:
-
- extern int f9 ( int,int,int,int,int,int,int,int,int );
- extern int f10 ( int,int,int,int,int,int,int,int,int,int );
- extern int f11 ( int,int,int,int,int,int,int,int,int,int,int );
- extern int f12 ( int,int,int,int,int,int,int,int,int,int,int,int );
-
- int g9 ( void ) {
- return f9(11,22,33,44,55,66,77,88,99);
- }
- int g10 ( void ) {
- return f10(11,22,33,44,55,66,77,88,99,110);
- }
- int g11 ( void ) {
- return f11(11,22,33,44,55,66,77,88,99,110,121);
- }
- int g12 ( void ) {
- return f12(11,22,33,44,55,66,77,88,99,110,121,132);
- }
-*/
-
-/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */
-
-/* These regs are trashed by the hidden call. */
-#define __CALLER_SAVED_REGS \
- "lr", "ctr", "xer", \
- "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \
- "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \
- "r11", "r12", "r13"
-
-/* These CALL_FN_ macros assume that on ppc32-linux,
- sizeof(unsigned long) == 4. */
-
-#define CALL_FN_W_v(lval, orig) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[1]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_W(lval, orig, arg1) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[2]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[4]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[5]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[6]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- _argvec[5] = (unsigned long)arg5; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 7,20(11)\n\t" \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[7]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- _argvec[5] = (unsigned long)arg5; \
- _argvec[6] = (unsigned long)arg6; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 7,20(11)\n\t" \
- "lwz 8,24(11)\n\t" \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[8]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- _argvec[5] = (unsigned long)arg5; \
- _argvec[6] = (unsigned long)arg6; \
- _argvec[7] = (unsigned long)arg7; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 7,20(11)\n\t" \
- "lwz 8,24(11)\n\t" \
- "lwz 9,28(11)\n\t" \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[9]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- _argvec[5] = (unsigned long)arg5; \
- _argvec[6] = (unsigned long)arg6; \
- _argvec[7] = (unsigned long)arg7; \
- _argvec[8] = (unsigned long)arg8; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 7,20(11)\n\t" \
- "lwz 8,24(11)\n\t" \
- "lwz 9,28(11)\n\t" \
- "lwz 10,32(11)\n\t" /* arg8->r10 */ \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[10]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- _argvec[5] = (unsigned long)arg5; \
- _argvec[6] = (unsigned long)arg6; \
- _argvec[7] = (unsigned long)arg7; \
- _argvec[8] = (unsigned long)arg8; \
- _argvec[9] = (unsigned long)arg9; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "addi 1,1,-16\n\t" \
- /* arg9 */ \
- "lwz 3,36(11)\n\t" \
- "stw 3,8(1)\n\t" \
- /* args1-8 */ \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 7,20(11)\n\t" \
- "lwz 8,24(11)\n\t" \
- "lwz 9,28(11)\n\t" \
- "lwz 10,32(11)\n\t" /* arg8->r10 */ \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "addi 1,1,16\n\t" \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[11]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- _argvec[5] = (unsigned long)arg5; \
- _argvec[6] = (unsigned long)arg6; \
- _argvec[7] = (unsigned long)arg7; \
- _argvec[8] = (unsigned long)arg8; \
- _argvec[9] = (unsigned long)arg9; \
- _argvec[10] = (unsigned long)arg10; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "addi 1,1,-16\n\t" \
- /* arg10 */ \
- "lwz 3,40(11)\n\t" \
- "stw 3,12(1)\n\t" \
- /* arg9 */ \
- "lwz 3,36(11)\n\t" \
- "stw 3,8(1)\n\t" \
- /* args1-8 */ \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 7,20(11)\n\t" \
- "lwz 8,24(11)\n\t" \
- "lwz 9,28(11)\n\t" \
- "lwz 10,32(11)\n\t" /* arg8->r10 */ \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "addi 1,1,16\n\t" \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[12]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- _argvec[5] = (unsigned long)arg5; \
- _argvec[6] = (unsigned long)arg6; \
- _argvec[7] = (unsigned long)arg7; \
- _argvec[8] = (unsigned long)arg8; \
- _argvec[9] = (unsigned long)arg9; \
- _argvec[10] = (unsigned long)arg10; \
- _argvec[11] = (unsigned long)arg11; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "addi 1,1,-32\n\t" \
- /* arg11 */ \
- "lwz 3,44(11)\n\t" \
- "stw 3,16(1)\n\t" \
- /* arg10 */ \
- "lwz 3,40(11)\n\t" \
- "stw 3,12(1)\n\t" \
- /* arg9 */ \
- "lwz 3,36(11)\n\t" \
- "stw 3,8(1)\n\t" \
- /* args1-8 */ \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 7,20(11)\n\t" \
- "lwz 8,24(11)\n\t" \
- "lwz 9,28(11)\n\t" \
- "lwz 10,32(11)\n\t" /* arg8->r10 */ \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "addi 1,1,32\n\t" \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11,arg12) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[13]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)arg1; \
- _argvec[2] = (unsigned long)arg2; \
- _argvec[3] = (unsigned long)arg3; \
- _argvec[4] = (unsigned long)arg4; \
- _argvec[5] = (unsigned long)arg5; \
- _argvec[6] = (unsigned long)arg6; \
- _argvec[7] = (unsigned long)arg7; \
- _argvec[8] = (unsigned long)arg8; \
- _argvec[9] = (unsigned long)arg9; \
- _argvec[10] = (unsigned long)arg10; \
- _argvec[11] = (unsigned long)arg11; \
- _argvec[12] = (unsigned long)arg12; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "addi 1,1,-32\n\t" \
- /* arg12 */ \
- "lwz 3,48(11)\n\t" \
- "stw 3,20(1)\n\t" \
- /* arg11 */ \
- "lwz 3,44(11)\n\t" \
- "stw 3,16(1)\n\t" \
- /* arg10 */ \
- "lwz 3,40(11)\n\t" \
- "stw 3,12(1)\n\t" \
- /* arg9 */ \
- "lwz 3,36(11)\n\t" \
- "stw 3,8(1)\n\t" \
- /* args1-8 */ \
- "lwz 3,4(11)\n\t" /* arg1->r3 */ \
- "lwz 4,8(11)\n\t" \
- "lwz 5,12(11)\n\t" \
- "lwz 6,16(11)\n\t" /* arg4->r6 */ \
- "lwz 7,20(11)\n\t" \
- "lwz 8,24(11)\n\t" \
- "lwz 9,28(11)\n\t" \
- "lwz 10,32(11)\n\t" /* arg8->r10 */ \
- "lwz 11,0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "addi 1,1,32\n\t" \
- "mr %0,3" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#endif /* PLAT_ppc32_linux */
-
-/* ------------------------ ppc64-linux ------------------------ */
-
-#if defined(PLAT_ppc64_linux)
-
-/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */
-
-/* These regs are trashed by the hidden call. */
-#define __CALLER_SAVED_REGS \
- "lr", "ctr", "xer", \
- "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \
- "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \
- "r11", "r12", "r13"
-
-/* These CALL_FN_ macros assume that on ppc64-linux, sizeof(unsigned
- long) == 8. */
-
-#define CALL_FN_W_v(lval, orig) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+0]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_W(lval, orig, arg1) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+1]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+2]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+3]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+4]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+5]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+6]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+7]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+8]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)" /* restore tocptr */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+9]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "addi 1,1,-128\n\t" /* expand stack frame */ \
- /* arg9 */ \
- "ld 3,72(11)\n\t" \
- "std 3,112(1)\n\t" \
- /* args1-8 */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- "addi 1,1,128" /* restore frame */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+10]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "addi 1,1,-128\n\t" /* expand stack frame */ \
- /* arg10 */ \
- "ld 3,80(11)\n\t" \
- "std 3,120(1)\n\t" \
- /* arg9 */ \
- "ld 3,72(11)\n\t" \
- "std 3,112(1)\n\t" \
- /* args1-8 */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- "addi 1,1,128" /* restore frame */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+11]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- _argvec[2+11] = (unsigned long)arg11; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "addi 1,1,-144\n\t" /* expand stack frame */ \
- /* arg11 */ \
- "ld 3,88(11)\n\t" \
- "std 3,128(1)\n\t" \
- /* arg10 */ \
- "ld 3,80(11)\n\t" \
- "std 3,120(1)\n\t" \
- /* arg9 */ \
- "ld 3,72(11)\n\t" \
- "std 3,112(1)\n\t" \
- /* args1-8 */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- "addi 1,1,144" /* restore frame */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11,arg12) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+12]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- _argvec[2+11] = (unsigned long)arg11; \
- _argvec[2+12] = (unsigned long)arg12; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "addi 1,1,-144\n\t" /* expand stack frame */ \
- /* arg12 */ \
- "ld 3,96(11)\n\t" \
- "std 3,136(1)\n\t" \
- /* arg11 */ \
- "ld 3,88(11)\n\t" \
- "std 3,128(1)\n\t" \
- /* arg10 */ \
- "ld 3,80(11)\n\t" \
- "std 3,120(1)\n\t" \
- /* arg9 */ \
- "ld 3,72(11)\n\t" \
- "std 3,112(1)\n\t" \
- /* args1-8 */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- "addi 1,1,144" /* restore frame */ \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#endif /* PLAT_ppc64_linux */
-
-/* ------------------------- arm-linux ------------------------- */
-
-#if defined(PLAT_arm_linux)
-
-/* These regs are trashed by the hidden call. */
-#define __CALLER_SAVED_REGS "r0", "r1", "r2", "r3","r4","r14"
-
-/* These CALL_FN_ macros assume that on arm-linux, sizeof(unsigned
- long) == 4. */
-
-#define CALL_FN_W_v(lval, orig) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[1]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- __asm__ volatile( \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "mov %0, r0\n" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_W(lval, orig, arg1) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[2]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- __asm__ volatile( \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "mov %0, r0\n" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- __asm__ volatile( \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "mov %0, r0\n" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[4]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- __asm__ volatile( \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "mov %0, r0\n" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[5]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- __asm__ volatile( \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[6]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- __asm__ volatile( \
- "ldr r0, [%1, #20] \n\t" \
- "push {r0} \n\t" \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "add sp, sp, #4 \n\t" \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[7]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- __asm__ volatile( \
- "ldr r0, [%1, #20] \n\t" \
- "ldr r1, [%1, #24] \n\t" \
- "push {r0, r1} \n\t" \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "add sp, sp, #8 \n\t" \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[8]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- __asm__ volatile( \
- "ldr r0, [%1, #20] \n\t" \
- "ldr r1, [%1, #24] \n\t" \
- "ldr r2, [%1, #28] \n\t" \
- "push {r0, r1, r2} \n\t" \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "add sp, sp, #12 \n\t" \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[9]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- __asm__ volatile( \
- "ldr r0, [%1, #20] \n\t" \
- "ldr r1, [%1, #24] \n\t" \
- "ldr r2, [%1, #28] \n\t" \
- "ldr r3, [%1, #32] \n\t" \
- "push {r0, r1, r2, r3} \n\t" \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "add sp, sp, #16 \n\t" \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[10]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- __asm__ volatile( \
- "ldr r0, [%1, #20] \n\t" \
- "ldr r1, [%1, #24] \n\t" \
- "ldr r2, [%1, #28] \n\t" \
- "ldr r3, [%1, #32] \n\t" \
- "ldr r4, [%1, #36] \n\t" \
- "push {r0, r1, r2, r3, r4} \n\t" \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "add sp, sp, #20 \n\t" \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[11]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- __asm__ volatile( \
- "ldr r0, [%1, #40] \n\t" \
- "push {r0} \n\t" \
- "ldr r0, [%1, #20] \n\t" \
- "ldr r1, [%1, #24] \n\t" \
- "ldr r2, [%1, #28] \n\t" \
- "ldr r3, [%1, #32] \n\t" \
- "ldr r4, [%1, #36] \n\t" \
- "push {r0, r1, r2, r3, r4} \n\t" \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "add sp, sp, #24 \n\t" \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5, \
- arg6,arg7,arg8,arg9,arg10, \
- arg11) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[12]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- _argvec[11] = (unsigned long)(arg11); \
- __asm__ volatile( \
- "ldr r0, [%1, #40] \n\t" \
- "ldr r1, [%1, #44] \n\t" \
- "push {r0, r1} \n\t" \
- "ldr r0, [%1, #20] \n\t" \
- "ldr r1, [%1, #24] \n\t" \
- "ldr r2, [%1, #28] \n\t" \
- "ldr r3, [%1, #32] \n\t" \
- "ldr r4, [%1, #36] \n\t" \
- "push {r0, r1, r2, r3, r4} \n\t" \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "add sp, sp, #28 \n\t" \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory",__CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5, \
- arg6,arg7,arg8,arg9,arg10, \
- arg11,arg12) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[13]; \
- volatile unsigned long _res; \
- _argvec[0] = (unsigned long)_orig.nraddr; \
- _argvec[1] = (unsigned long)(arg1); \
- _argvec[2] = (unsigned long)(arg2); \
- _argvec[3] = (unsigned long)(arg3); \
- _argvec[4] = (unsigned long)(arg4); \
- _argvec[5] = (unsigned long)(arg5); \
- _argvec[6] = (unsigned long)(arg6); \
- _argvec[7] = (unsigned long)(arg7); \
- _argvec[8] = (unsigned long)(arg8); \
- _argvec[9] = (unsigned long)(arg9); \
- _argvec[10] = (unsigned long)(arg10); \
- _argvec[11] = (unsigned long)(arg11); \
- _argvec[12] = (unsigned long)(arg12); \
- __asm__ volatile( \
- "ldr r0, [%1, #40] \n\t" \
- "ldr r1, [%1, #44] \n\t" \
- "ldr r2, [%1, #48] \n\t" \
- "push {r0, r1, r2} \n\t" \
- "ldr r0, [%1, #20] \n\t" \
- "ldr r1, [%1, #24] \n\t" \
- "ldr r2, [%1, #28] \n\t" \
- "ldr r3, [%1, #32] \n\t" \
- "ldr r4, [%1, #36] \n\t" \
- "push {r0, r1, r2, r3, r4} \n\t" \
- "ldr r0, [%1, #4] \n\t" \
- "ldr r1, [%1, #8] \n\t" \
- "ldr r2, [%1, #12] \n\t" \
- "ldr r3, [%1, #16] \n\t" \
- "ldr r4, [%1] \n\t" /* target->r4 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R4 \
- "add sp, sp, #32 \n\t" \
- "mov %0, r0" \
- : /*out*/ "=r" (_res) \
- : /*in*/ "0" (&_argvec[0]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#endif /* PLAT_arm_linux */
-
-/* ------------------------ ppc32-aix5 ------------------------- */
-
-#if defined(PLAT_ppc32_aix5)
-
-/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */
-
-/* These regs are trashed by the hidden call. */
-#define __CALLER_SAVED_REGS \
- "lr", "ctr", "xer", \
- "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \
- "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \
- "r11", "r12", "r13"
-
-/* Expand the stack frame, copying enough info that unwinding
- still works. Trashes r3. */
-
-#define VG_EXPAND_FRAME_BY_trashes_r3(_n_fr) \
- "addi 1,1,-" #_n_fr "\n\t" \
- "lwz 3," #_n_fr "(1)\n\t" \
- "stw 3,0(1)\n\t"
-
-#define VG_CONTRACT_FRAME_BY(_n_fr) \
- "addi 1,1," #_n_fr "\n\t"
-
-/* These CALL_FN_ macros assume that on ppc32-aix5, sizeof(unsigned
- long) == 4. */
-
-#define CALL_FN_W_v(lval, orig) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+0]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_W(lval, orig, arg1) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+1]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+2]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+3]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+4]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+5]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 7, 20(11)\n\t" /* arg5->r7 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+6]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 7, 20(11)\n\t" /* arg5->r7 */ \
- "lwz 8, 24(11)\n\t" /* arg6->r8 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+7]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 7, 20(11)\n\t" /* arg5->r7 */ \
- "lwz 8, 24(11)\n\t" /* arg6->r8 */ \
- "lwz 9, 28(11)\n\t" /* arg7->r9 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+8]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 7, 20(11)\n\t" /* arg5->r7 */ \
- "lwz 8, 24(11)\n\t" /* arg6->r8 */ \
- "lwz 9, 28(11)\n\t" /* arg7->r9 */ \
- "lwz 10, 32(11)\n\t" /* arg8->r10 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+9]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- VG_EXPAND_FRAME_BY_trashes_r3(64) \
- /* arg9 */ \
- "lwz 3,36(11)\n\t" \
- "stw 3,56(1)\n\t" \
- /* args1-8 */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 7, 20(11)\n\t" /* arg5->r7 */ \
- "lwz 8, 24(11)\n\t" /* arg6->r8 */ \
- "lwz 9, 28(11)\n\t" /* arg7->r9 */ \
- "lwz 10, 32(11)\n\t" /* arg8->r10 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(64) \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+10]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- VG_EXPAND_FRAME_BY_trashes_r3(64) \
- /* arg10 */ \
- "lwz 3,40(11)\n\t" \
- "stw 3,60(1)\n\t" \
- /* arg9 */ \
- "lwz 3,36(11)\n\t" \
- "stw 3,56(1)\n\t" \
- /* args1-8 */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 7, 20(11)\n\t" /* arg5->r7 */ \
- "lwz 8, 24(11)\n\t" /* arg6->r8 */ \
- "lwz 9, 28(11)\n\t" /* arg7->r9 */ \
- "lwz 10, 32(11)\n\t" /* arg8->r10 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(64) \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+11]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- _argvec[2+11] = (unsigned long)arg11; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- VG_EXPAND_FRAME_BY_trashes_r3(72) \
- /* arg11 */ \
- "lwz 3,44(11)\n\t" \
- "stw 3,64(1)\n\t" \
- /* arg10 */ \
- "lwz 3,40(11)\n\t" \
- "stw 3,60(1)\n\t" \
- /* arg9 */ \
- "lwz 3,36(11)\n\t" \
- "stw 3,56(1)\n\t" \
- /* args1-8 */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 7, 20(11)\n\t" /* arg5->r7 */ \
- "lwz 8, 24(11)\n\t" /* arg6->r8 */ \
- "lwz 9, 28(11)\n\t" /* arg7->r9 */ \
- "lwz 10, 32(11)\n\t" /* arg8->r10 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(72) \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11,arg12) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+12]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- _argvec[2+11] = (unsigned long)arg11; \
- _argvec[2+12] = (unsigned long)arg12; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "stw 2,-8(11)\n\t" /* save tocptr */ \
- "lwz 2,-4(11)\n\t" /* use nraddr's tocptr */ \
- VG_EXPAND_FRAME_BY_trashes_r3(72) \
- /* arg12 */ \
- "lwz 3,48(11)\n\t" \
- "stw 3,68(1)\n\t" \
- /* arg11 */ \
- "lwz 3,44(11)\n\t" \
- "stw 3,64(1)\n\t" \
- /* arg10 */ \
- "lwz 3,40(11)\n\t" \
- "stw 3,60(1)\n\t" \
- /* arg9 */ \
- "lwz 3,36(11)\n\t" \
- "stw 3,56(1)\n\t" \
- /* args1-8 */ \
- "lwz 3, 4(11)\n\t" /* arg1->r3 */ \
- "lwz 4, 8(11)\n\t" /* arg2->r4 */ \
- "lwz 5, 12(11)\n\t" /* arg3->r5 */ \
- "lwz 6, 16(11)\n\t" /* arg4->r6 */ \
- "lwz 7, 20(11)\n\t" /* arg5->r7 */ \
- "lwz 8, 24(11)\n\t" /* arg6->r8 */ \
- "lwz 9, 28(11)\n\t" /* arg7->r9 */ \
- "lwz 10, 32(11)\n\t" /* arg8->r10 */ \
- "lwz 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "lwz 2,-8(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(72) \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#endif /* PLAT_ppc32_aix5 */
-
-/* ------------------------ ppc64-aix5 ------------------------- */
-
-#if defined(PLAT_ppc64_aix5)
-
-/* ARGREGS: r3 r4 r5 r6 r7 r8 r9 r10 (the rest on stack somewhere) */
-
-/* These regs are trashed by the hidden call. */
-#define __CALLER_SAVED_REGS \
- "lr", "ctr", "xer", \
- "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", \
- "r0", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", \
- "r11", "r12", "r13"
-
-/* Expand the stack frame, copying enough info that unwinding
- still works. Trashes r3. */
-
-#define VG_EXPAND_FRAME_BY_trashes_r3(_n_fr) \
- "addi 1,1,-" #_n_fr "\n\t" \
- "ld 3," #_n_fr "(1)\n\t" \
- "std 3,0(1)\n\t"
-
-#define VG_CONTRACT_FRAME_BY(_n_fr) \
- "addi 1,1," #_n_fr "\n\t"
-
-/* These CALL_FN_ macros assume that on ppc64-aix5, sizeof(unsigned
- long) == 8. */
-
-#define CALL_FN_W_v(lval, orig) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+0]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_W(lval, orig, arg1) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+1]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WW(lval, orig, arg1,arg2) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+2]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWW(lval, orig, arg1,arg2,arg3) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+3]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_WWWW(lval, orig, arg1,arg2,arg3,arg4) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+4]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_5W(lval, orig, arg1,arg2,arg3,arg4,arg5) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+5]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_6W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+6]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_7W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+7]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_8W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+8]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_9W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+9]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- VG_EXPAND_FRAME_BY_trashes_r3(128) \
- /* arg9 */ \
- "ld 3,72(11)\n\t" \
- "std 3,112(1)\n\t" \
- /* args1-8 */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(128) \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_10W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+10]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- VG_EXPAND_FRAME_BY_trashes_r3(128) \
- /* arg10 */ \
- "ld 3,80(11)\n\t" \
- "std 3,120(1)\n\t" \
- /* arg9 */ \
- "ld 3,72(11)\n\t" \
- "std 3,112(1)\n\t" \
- /* args1-8 */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(128) \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_11W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+11]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- _argvec[2+11] = (unsigned long)arg11; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- VG_EXPAND_FRAME_BY_trashes_r3(144) \
- /* arg11 */ \
- "ld 3,88(11)\n\t" \
- "std 3,128(1)\n\t" \
- /* arg10 */ \
- "ld 3,80(11)\n\t" \
- "std 3,120(1)\n\t" \
- /* arg9 */ \
- "ld 3,72(11)\n\t" \
- "std 3,112(1)\n\t" \
- /* args1-8 */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(144) \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#define CALL_FN_W_12W(lval, orig, arg1,arg2,arg3,arg4,arg5,arg6, \
- arg7,arg8,arg9,arg10,arg11,arg12) \
- do { \
- volatile OrigFn _orig = (orig); \
- volatile unsigned long _argvec[3+12]; \
- volatile unsigned long _res; \
- /* _argvec[0] holds current r2 across the call */ \
- _argvec[1] = (unsigned long)_orig.r2; \
- _argvec[2] = (unsigned long)_orig.nraddr; \
- _argvec[2+1] = (unsigned long)arg1; \
- _argvec[2+2] = (unsigned long)arg2; \
- _argvec[2+3] = (unsigned long)arg3; \
- _argvec[2+4] = (unsigned long)arg4; \
- _argvec[2+5] = (unsigned long)arg5; \
- _argvec[2+6] = (unsigned long)arg6; \
- _argvec[2+7] = (unsigned long)arg7; \
- _argvec[2+8] = (unsigned long)arg8; \
- _argvec[2+9] = (unsigned long)arg9; \
- _argvec[2+10] = (unsigned long)arg10; \
- _argvec[2+11] = (unsigned long)arg11; \
- _argvec[2+12] = (unsigned long)arg12; \
- __asm__ volatile( \
- "mr 11,%1\n\t" \
- VG_EXPAND_FRAME_BY_trashes_r3(512) \
- "std 2,-16(11)\n\t" /* save tocptr */ \
- "ld 2,-8(11)\n\t" /* use nraddr's tocptr */ \
- VG_EXPAND_FRAME_BY_trashes_r3(144) \
- /* arg12 */ \
- "ld 3,96(11)\n\t" \
- "std 3,136(1)\n\t" \
- /* arg11 */ \
- "ld 3,88(11)\n\t" \
- "std 3,128(1)\n\t" \
- /* arg10 */ \
- "ld 3,80(11)\n\t" \
- "std 3,120(1)\n\t" \
- /* arg9 */ \
- "ld 3,72(11)\n\t" \
- "std 3,112(1)\n\t" \
- /* args1-8 */ \
- "ld 3, 8(11)\n\t" /* arg1->r3 */ \
- "ld 4, 16(11)\n\t" /* arg2->r4 */ \
- "ld 5, 24(11)\n\t" /* arg3->r5 */ \
- "ld 6, 32(11)\n\t" /* arg4->r6 */ \
- "ld 7, 40(11)\n\t" /* arg5->r7 */ \
- "ld 8, 48(11)\n\t" /* arg6->r8 */ \
- "ld 9, 56(11)\n\t" /* arg7->r9 */ \
- "ld 10, 64(11)\n\t" /* arg8->r10 */ \
- "ld 11, 0(11)\n\t" /* target->r11 */ \
- VALGRIND_BRANCH_AND_LINK_TO_NOREDIR_R11 \
- "mr 11,%1\n\t" \
- "mr %0,3\n\t" \
- "ld 2,-16(11)\n\t" /* restore tocptr */ \
- VG_CONTRACT_FRAME_BY(144) \
- VG_CONTRACT_FRAME_BY(512) \
- : /*out*/ "=r" (_res) \
- : /*in*/ "r" (&_argvec[2]) \
- : /*trash*/ "cc", "memory", __CALLER_SAVED_REGS \
- ); \
- lval = (__typeof__(lval)) _res; \
- } while (0)
-
-#endif /* PLAT_ppc64_aix5 */
-
-
-/* ------------------------------------------------------------------ */
-/* ARCHITECTURE INDEPENDENT MACROS for CLIENT REQUESTS. */
-/* */
-/* ------------------------------------------------------------------ */
-
-/* Some request codes. There are many more of these, but most are not
- exposed to end-user view. These are the public ones, all of the
- form 0x1000 + small_number.
-
- Core ones are in the range 0x00000000--0x0000ffff. The non-public
- ones start at 0x2000.
-*/
-
-/* These macros are used by tools -- they must be public, but don't
- embed them into other programs. */
-#define VG_USERREQ_TOOL_BASE(a,b) \
- ((unsigned int)(((a)&0xff) << 24 | ((b)&0xff) << 16))
-#define VG_IS_TOOL_USERREQ(a, b, v) \
- (VG_USERREQ_TOOL_BASE(a,b) == ((v) & 0xffff0000))
-
-/* !! ABIWARNING !! ABIWARNING !! ABIWARNING !! ABIWARNING !!
- This enum comprises an ABI exported by Valgrind to programs
- which use client requests. DO NOT CHANGE THE ORDER OF THESE
- ENTRIES, NOR DELETE ANY -- add new ones at the end. */
-typedef
- enum { VG_USERREQ__RUNNING_ON_VALGRIND = 0x1001,
- VG_USERREQ__DISCARD_TRANSLATIONS = 0x1002,
-
- /* These allow any function to be called from the simulated
- CPU but run on the real CPU. Nb: the first arg passed to
- the function is always the ThreadId of the running
- thread! So CLIENT_CALL0 actually requires a 1 arg
- function, etc. */
- VG_USERREQ__CLIENT_CALL0 = 0x1101,
- VG_USERREQ__CLIENT_CALL1 = 0x1102,
- VG_USERREQ__CLIENT_CALL2 = 0x1103,
- VG_USERREQ__CLIENT_CALL3 = 0x1104,
-
- /* Can be useful in regression testing suites -- eg. can
- send Valgrind's output to /dev/null and still count
- errors. */
- VG_USERREQ__COUNT_ERRORS = 0x1201,
-
- /* These are useful and can be interpreted by any tool that
- tracks malloc() et al, by using vg_replace_malloc.c. */
- VG_USERREQ__MALLOCLIKE_BLOCK = 0x1301,
- VG_USERREQ__FREELIKE_BLOCK = 0x1302,
- /* Memory pool support. */
- VG_USERREQ__CREATE_MEMPOOL = 0x1303,
- VG_USERREQ__DESTROY_MEMPOOL = 0x1304,
- VG_USERREQ__MEMPOOL_ALLOC = 0x1305,
- VG_USERREQ__MEMPOOL_FREE = 0x1306,
- VG_USERREQ__MEMPOOL_TRIM = 0x1307,
- VG_USERREQ__MOVE_MEMPOOL = 0x1308,
- VG_USERREQ__MEMPOOL_CHANGE = 0x1309,
- VG_USERREQ__MEMPOOL_EXISTS = 0x130a,
-
- /* Allow printfs to valgrind log. */
- /* The first two pass the va_list argument by value, which
- assumes it is the same size as or smaller than a UWord,
- which generally isn't the case. Hence are deprecated.
- The second two pass the vargs by reference and so are
- immune to this problem. */
- /* both :: char* fmt, va_list vargs (DEPRECATED) */
- VG_USERREQ__PRINTF = 0x1401,
- VG_USERREQ__PRINTF_BACKTRACE = 0x1402,
- /* both :: char* fmt, va_list* vargs */
- VG_USERREQ__PRINTF_VALIST_BY_REF = 0x1403,
- VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF = 0x1404,
-
- /* Stack support. */
- VG_USERREQ__STACK_REGISTER = 0x1501,
- VG_USERREQ__STACK_DEREGISTER = 0x1502,
- VG_USERREQ__STACK_CHANGE = 0x1503,
-
- /* Wine support */
- VG_USERREQ__LOAD_PDB_DEBUGINFO = 0x1601,
-
- /* Querying of debug info. */
- VG_USERREQ__MAP_IP_TO_SRCLOC = 0x1701
- } Vg_ClientRequest;
-
-#if !defined(__GNUC__)
-# define __extension__ /* */
-#endif
-
-
-/*
- * VALGRIND_DO_CLIENT_REQUEST_EXPR(): a C expression that invokes a Valgrind
- * client request and whose value equals the client request result.
- */
-
-#if defined(NVALGRIND)
-
-#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \
- _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- (_zzq_default)
-
-#else /*defined(NVALGRIND)*/
-
-#if defined(_MSC_VER)
-
-#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \
- _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- (vg_VALGRIND_DO_CLIENT_REQUEST_EXPR((uintptr_t)(_zzq_default), \
- (_zzq_request), (uintptr_t)(_zzq_arg1), (uintptr_t)(_zzq_arg2), \
- (uintptr_t)(_zzq_arg3), (uintptr_t)(_zzq_arg4), \
- (uintptr_t)(_zzq_arg5)))
-
-static __inline unsigned
-vg_VALGRIND_DO_CLIENT_REQUEST_EXPR(uintptr_t _zzq_default,
- unsigned _zzq_request, uintptr_t _zzq_arg1,
- uintptr_t _zzq_arg2, uintptr_t _zzq_arg3,
- uintptr_t _zzq_arg4, uintptr_t _zzq_arg5)
-{
- unsigned _zzq_rlval;
- VALGRIND_DO_CLIENT_REQUEST(_zzq_rlval, _zzq_default, _zzq_request,
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5);
- return _zzq_rlval;
-}
-
-#else /*defined(_MSC_VER)*/
-
-#define VALGRIND_DO_CLIENT_REQUEST_EXPR( \
- _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- (__extension__({unsigned int _zzq_rlval; \
- VALGRIND_DO_CLIENT_REQUEST(_zzq_rlval, _zzq_default, _zzq_request, \
- _zzq_arg1, _zzq_arg2, _zzq_arg3, _zzq_arg4, _zzq_arg5) \
- _zzq_rlval; \
- }))
-
-#endif /*defined(_MSC_VER)*/
-
-#endif /*defined(NVALGRIND)*/
-
-
-/* Returns the number of Valgrinds this code is running under. That
- is, 0 if running natively, 1 if running under Valgrind, 2 if
- running under Valgrind which is running under another Valgrind,
- etc. */
-#define RUNNING_ON_VALGRIND \
- VALGRIND_DO_CLIENT_REQUEST_EXPR(0 /* if not */, \
- VG_USERREQ__RUNNING_ON_VALGRIND, \
- 0, 0, 0, 0, 0) \
-
-
-/* Discard translation of code in the range [_qzz_addr .. _qzz_addr +
- _qzz_len - 1]. Useful if you are debugging a JITter or some such,
- since it provides a way to make sure valgrind will retranslate the
- invalidated area. Returns no value. */
-#define VALGRIND_DISCARD_TRANSLATIONS(_qzz_addr,_qzz_len) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__DISCARD_TRANSLATIONS, \
- _qzz_addr, _qzz_len, 0, 0, 0); \
- }
-
-
-/* These requests are for getting Valgrind itself to print something.
- Possibly with a backtrace. This is a really ugly hack. The return value
- is the number of characters printed, excluding the "**<pid>** " part at the
- start and the backtrace (if present). */
-
-#if defined(NVALGRIND)
-
-# define VALGRIND_PRINTF(...)
-# define VALGRIND_PRINTF_BACKTRACE(...)
-
-#else /* NVALGRIND */
-
-#if !defined(_MSC_VER)
-/* Modern GCC will optimize the static routine out if unused,
- and unused attribute will shut down warnings about it. */
-static int VALGRIND_PRINTF(const char *format, ...)
- __attribute__((format(__printf__, 1, 2), __unused__));
-#endif
-static int
-#if defined(_MSC_VER)
-__inline
-#endif
-VALGRIND_PRINTF(const char *format, ...)
-{
- unsigned long _qzz_res;
- va_list vargs;
- va_start(vargs, format);
-#if defined(_MSC_VER)
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0,
- VG_USERREQ__PRINTF_VALIST_BY_REF,
- (uintptr_t)format,
- (uintptr_t)&vargs,
- 0, 0, 0);
-#else
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0,
- VG_USERREQ__PRINTF_VALIST_BY_REF,
- (unsigned long)format,
- (unsigned long)&vargs,
- 0, 0, 0);
-#endif
- va_end(vargs);
- return (int)_qzz_res;
-}
-
-#if !defined(_MSC_VER)
-static int VALGRIND_PRINTF_BACKTRACE(const char *format, ...)
- __attribute__((format(__printf__, 1, 2), __unused__));
-#endif
-static int
-#if defined(_MSC_VER)
-__inline
-#endif
-VALGRIND_PRINTF_BACKTRACE(const char *format, ...)
-{
- unsigned long _qzz_res;
- va_list vargs;
- va_start(vargs, format);
-#if defined(_MSC_VER)
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0,
- VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF,
- (uintptr_t)format,
- (uintptr_t)&vargs,
- 0, 0, 0);
-#else
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0,
- VG_USERREQ__PRINTF_BACKTRACE_VALIST_BY_REF,
- (unsigned long)format,
- (unsigned long)&vargs,
- 0, 0, 0);
-#endif
- va_end(vargs);
- return (int)_qzz_res;
-}
-
-#endif /* NVALGRIND */
-
-
-/* These requests allow control to move from the simulated CPU to the
- real CPU, calling an arbitary function.
-
- Note that the current ThreadId is inserted as the first argument.
- So this call:
-
- VALGRIND_NON_SIMD_CALL2(f, arg1, arg2)
-
- requires f to have this signature:
-
- Word f(Word tid, Word arg1, Word arg2)
-
- where "Word" is a word-sized type.
-
- Note that these client requests are not entirely reliable. For example,
- if you call a function with them that subsequently calls printf(),
- there's a high chance Valgrind will crash. Generally, your prospects of
- these working are made higher if the called function does not refer to
- any global variables, and does not refer to any libc or other functions
- (printf et al). Any kind of entanglement with libc or dynamic linking is
- likely to have a bad outcome, for tricky reasons which we've grappled
- with a lot in the past.
-*/
-#define VALGRIND_NON_SIMD_CALL0(_qyy_fn) \
- __extension__ \
- ({unsigned long _qyy_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
- VG_USERREQ__CLIENT_CALL0, \
- _qyy_fn, \
- 0, 0, 0, 0); \
- _qyy_res; \
- })
-
-#define VALGRIND_NON_SIMD_CALL1(_qyy_fn, _qyy_arg1) \
- __extension__ \
- ({unsigned long _qyy_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
- VG_USERREQ__CLIENT_CALL1, \
- _qyy_fn, \
- _qyy_arg1, 0, 0, 0); \
- _qyy_res; \
- })
-
-#define VALGRIND_NON_SIMD_CALL2(_qyy_fn, _qyy_arg1, _qyy_arg2) \
- __extension__ \
- ({unsigned long _qyy_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
- VG_USERREQ__CLIENT_CALL2, \
- _qyy_fn, \
- _qyy_arg1, _qyy_arg2, 0, 0); \
- _qyy_res; \
- })
-
-#define VALGRIND_NON_SIMD_CALL3(_qyy_fn, _qyy_arg1, _qyy_arg2, _qyy_arg3) \
- __extension__ \
- ({unsigned long _qyy_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
- VG_USERREQ__CLIENT_CALL3, \
- _qyy_fn, \
- _qyy_arg1, _qyy_arg2, \
- _qyy_arg3, 0); \
- _qyy_res; \
- })
-
-
-/* Counts the number of errors that have been recorded by a tool. Nb:
- the tool must record the errors with VG_(maybe_record_error)() or
- VG_(unique_error)() for them to be counted. */
-#define VALGRIND_COUNT_ERRORS \
- __extension__ \
- ({unsigned int _qyy_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qyy_res, 0 /* default return */, \
- VG_USERREQ__COUNT_ERRORS, \
- 0, 0, 0, 0, 0); \
- _qyy_res; \
- })
-
-/* Several Valgrind tools (Memcheck, Massif, Helgrind, DRD) rely on knowing
- when heap blocks are allocated in order to give accurate results. This
- happens automatically for the standard allocator functions such as
- malloc(), calloc(), realloc(), memalign(), new, new[], free(), delete,
- delete[], etc.
-
- But if your program uses a custom allocator, this doesn't automatically
- happen, and Valgrind will not do as well. For example, if you allocate
- superblocks with mmap() and then allocates chunks of the superblocks, all
- Valgrind's observations will be at the mmap() level and it won't know that
- the chunks should be considered separate entities. In Memcheck's case,
- that means you probably won't get heap block overrun detection (because
- there won't be redzones marked as unaddressable) and you definitely won't
- get any leak detection.
-
- The following client requests allow a custom allocator to be annotated so
- that it can be handled accurately by Valgrind.
-
- VALGRIND_MALLOCLIKE_BLOCK marks a region of memory as having been allocated
- by a malloc()-like function. For Memcheck (an illustrative case), this
- does two things:
-
- - It records that the block has been allocated. This means any addresses
- within the block mentioned in error messages will be
- identified as belonging to the block. It also means that if the block
- isn't freed it will be detected by the leak checker.
-
- - It marks the block as being addressable and undefined (if 'is_zeroed' is
- not set), or addressable and defined (if 'is_zeroed' is set). This
- controls how accesses to the block by the program are handled.
-
- 'addr' is the start of the usable block (ie. after any
- redzone), 'sizeB' is its size. 'rzB' is the redzone size if the allocator
- can apply redzones -- these are blocks of padding at the start and end of
- each block. Adding redzones is recommended as it makes it much more likely
- Valgrind will spot block overruns. `is_zeroed' indicates if the memory is
- zeroed (or filled with another predictable value), as is the case for
- calloc().
-
- VALGRIND_MALLOCLIKE_BLOCK should be put immediately after the point where a
- heap block -- that will be used by the client program -- is allocated.
- It's best to put it at the outermost level of the allocator if possible;
- for example, if you have a function my_alloc() which calls
- internal_alloc(), and the client request is put inside internal_alloc(),
- stack traces relating to the heap block will contain entries for both
- my_alloc() and internal_alloc(), which is probably not what you want.
-
- For Memcheck users: if you use VALGRIND_MALLOCLIKE_BLOCK to carve out
- custom blocks from within a heap block, B, that has been allocated with
- malloc/calloc/new/etc, then block B will be *ignored* during leak-checking
- -- the custom blocks will take precedence.
-
- VALGRIND_FREELIKE_BLOCK is the partner to VALGRIND_MALLOCLIKE_BLOCK. For
- Memcheck, it does two things:
-
- - It records that the block has been deallocated. This assumes that the
- block was annotated as having been allocated via
- VALGRIND_MALLOCLIKE_BLOCK. Otherwise, an error will be issued.
-
- - It marks the block as being unaddressable.
-
- VALGRIND_FREELIKE_BLOCK should be put immediately after the point where a
- heap block is deallocated.
-
- In many cases, these two client requests will not be enough to get your
- allocator working well with Memcheck. More specifically, if your allocator
- writes to freed blocks in any way then a VALGRIND_MAKE_MEM_UNDEFINED call
- will be necessary to mark the memory as addressable just before the zeroing
- occurs, otherwise you'll get a lot of invalid write errors. For example,
- you'll need to do this if your allocator recycles freed blocks, but it
- zeroes them before handing them back out (via VALGRIND_MALLOCLIKE_BLOCK).
- Alternatively, if your allocator reuses freed blocks for allocator-internal
- data structures, VALGRIND_MAKE_MEM_UNDEFINED calls will also be necessary.
-
- Really, what's happening is a blurring of the lines between the client
- program and the allocator... after VALGRIND_FREELIKE_BLOCK is called, the
- memory should be considered unaddressable to the client program, but the
- allocator knows more than the rest of the client program and so may be able
- to safely access it. Extra client requests are necessary for Valgrind to
- understand the distinction between the allocator and the rest of the
- program.
-
- Note: there is currently no VALGRIND_REALLOCLIKE_BLOCK client request; it
- has to be emulated with MALLOCLIKE/FREELIKE and memory copying.
-
- Ignored if addr == 0.
-*/
-#define VALGRIND_MALLOCLIKE_BLOCK(addr, sizeB, rzB, is_zeroed) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__MALLOCLIKE_BLOCK, \
- addr, sizeB, rzB, is_zeroed, 0); \
- }
-
-/* See the comment for VALGRIND_MALLOCLIKE_BLOCK for details.
- Ignored if addr == 0.
-*/
-#define VALGRIND_FREELIKE_BLOCK(addr, rzB) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__FREELIKE_BLOCK, \
- addr, rzB, 0, 0, 0); \
- }
-
-/* Create a memory pool. */
-#define VALGRIND_CREATE_MEMPOOL(pool, rzB, is_zeroed) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__CREATE_MEMPOOL, \
- pool, rzB, is_zeroed, 0, 0); \
- }
-
-/* Destroy a memory pool. */
-#define VALGRIND_DESTROY_MEMPOOL(pool) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__DESTROY_MEMPOOL, \
- pool, 0, 0, 0, 0); \
- }
-
-/* Associate a piece of memory with a memory pool. */
-#define VALGRIND_MEMPOOL_ALLOC(pool, addr, size) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__MEMPOOL_ALLOC, \
- pool, addr, size, 0, 0); \
- }
-
-/* Disassociate a piece of memory from a memory pool. */
-#define VALGRIND_MEMPOOL_FREE(pool, addr) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__MEMPOOL_FREE, \
- pool, addr, 0, 0, 0); \
- }
-
-/* Disassociate any pieces outside a particular range. */
-#define VALGRIND_MEMPOOL_TRIM(pool, addr, size) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__MEMPOOL_TRIM, \
- pool, addr, size, 0, 0); \
- }
-
-/* Resize and/or move a piece associated with a memory pool. */
-#define VALGRIND_MOVE_MEMPOOL(poolA, poolB) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__MOVE_MEMPOOL, \
- poolA, poolB, 0, 0, 0); \
- }
-
-/* Resize and/or move a piece associated with a memory pool. */
-#define VALGRIND_MEMPOOL_CHANGE(pool, addrA, addrB, size) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__MEMPOOL_CHANGE, \
- pool, addrA, addrB, size, 0); \
- }
-
-/* Return 1 if a mempool exists, else 0. */
-#define VALGRIND_MEMPOOL_EXISTS(pool) \
- __extension__ \
- ({unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__MEMPOOL_EXISTS, \
- pool, 0, 0, 0, 0); \
- _qzz_res; \
- })
-
-/* Mark a piece of memory as being a stack. Returns a stack id. */
-#define VALGRIND_STACK_REGISTER(start, end) \
- __extension__ \
- ({unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__STACK_REGISTER, \
- start, end, 0, 0, 0); \
- _qzz_res; \
- })
-
-/* Unmark the piece of memory associated with a stack id as being a
- stack. */
-#define VALGRIND_STACK_DEREGISTER(id) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__STACK_DEREGISTER, \
- id, 0, 0, 0, 0); \
- }
-
-/* Change the start and end address of the stack id. */
-#define VALGRIND_STACK_CHANGE(id, start, end) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__STACK_CHANGE, \
- id, start, end, 0, 0); \
- }
-
-/* Load PDB debug info for Wine PE image_map. */
-#define VALGRIND_LOAD_PDB_DEBUGINFO(fd, ptr, total_size, delta) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__LOAD_PDB_DEBUGINFO, \
- fd, ptr, total_size, delta, 0); \
- }
-
-/* Map a code address to a source file name and line number. buf64
- must point to a 64-byte buffer in the caller's address space. The
- result will be dumped in there and is guaranteed to be zero
- terminated. If no info is found, the first byte is set to zero. */
-#define VALGRIND_MAP_IP_TO_SRCLOC(addr, buf64) \
- {unsigned int _qzz_res; \
- VALGRIND_DO_CLIENT_REQUEST(_qzz_res, 0, \
- VG_USERREQ__MAP_IP_TO_SRCLOC, \
- addr, buf64, 0, 0, 0); \
- }
-
-
-#undef PLAT_x86_linux
-#undef PLAT_amd64_linux
-#undef PLAT_ppc32_linux
-#undef PLAT_ppc64_linux
-#undef PLAT_arm_linux
-#undef PLAT_ppc32_aix5
-#undef PLAT_ppc64_aix5
-
-#endif /* __VALGRIND_H */
diff --git a/security/sandbox/chromium/base/threading/platform_thread.h b/security/sandbox/chromium/base/threading/platform_thread.h
deleted file mode 100644
index e2b09bcb5..000000000
--- a/security/sandbox/chromium/base/threading/platform_thread.h
+++ /dev/null
@@ -1,199 +0,0 @@
-// 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.
-
-// 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_THREADING_PLATFORM_THREAD_H_
-#define BASE_THREADING_PLATFORM_THREAD_H_
-
-#include <stddef.h>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/time/time.h"
-#include "build/build_config.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#elif defined(OS_POSIX)
-#include <pthread.h>
-#include <unistd.h>
-#endif
-
-namespace base {
-
-// Used for logging. Always an integer value.
-#if defined(OS_WIN)
-typedef DWORD PlatformThreadId;
-#elif defined(OS_POSIX)
-typedef pid_t PlatformThreadId;
-#endif
-
-// Used for thread checking and debugging.
-// Meant to be as fast as possible.
-// These are produced by PlatformThread::CurrentRef(), and used to later
-// check if we are on the same thread or not by using ==. These are safe
-// to copy between threads, but can't be copied to another process as they
-// have no meaning there. Also, the internal identifier can be re-used
-// after a thread dies, so a PlatformThreadRef cannot be reliably used
-// to distinguish a new thread from an old, dead thread.
-class PlatformThreadRef {
- public:
-#if defined(OS_WIN)
- typedef DWORD RefType;
-#elif defined(OS_POSIX)
- typedef pthread_t RefType;
-#endif
- PlatformThreadRef()
- : id_(0) {
- }
-
- explicit PlatformThreadRef(RefType id)
- : id_(id) {
- }
-
- bool operator==(PlatformThreadRef other) const {
- return id_ == other.id_;
- }
-
- bool is_null() const {
- return id_ == 0;
- }
- private:
- RefType id_;
-};
-
-// Used to operate on threads.
-class PlatformThreadHandle {
- public:
-#if defined(OS_WIN)
- typedef void* Handle;
-#elif defined(OS_POSIX)
- typedef pthread_t Handle;
-#endif
-
- PlatformThreadHandle() : handle_(0) {}
-
- explicit PlatformThreadHandle(Handle handle) : handle_(handle) {}
-
- bool is_equal(const PlatformThreadHandle& other) const {
- return handle_ == other.handle_;
- }
-
- bool is_null() const {
- return !handle_;
- }
-
- Handle platform_handle() const {
- return handle_;
- }
-
- private:
- Handle handle_;
-};
-
-const PlatformThreadId kInvalidThreadId(0);
-
-// Valid values for priority of Thread::Options and SimpleThread::Options, and
-// SetCurrentThreadPriority(), listed in increasing order of importance.
-enum class ThreadPriority {
- // Suitable for threads that shouldn't disrupt high priority work.
- BACKGROUND,
- // Default priority level.
- NORMAL,
- // Suitable for threads which generate data for the display (at ~60Hz).
- DISPLAY,
- // Suitable for low-latency, glitch-resistant audio.
- REALTIME_AUDIO,
-};
-
-// A namespace for low-level thread functions.
-class BASE_EXPORT PlatformThread {
- public:
- // Implement this interface to run code on a background thread. Your
- // ThreadMain method will be called on the newly created thread.
- class BASE_EXPORT Delegate {
- public:
- virtual void ThreadMain() = 0;
-
- protected:
- virtual ~Delegate() {}
- };
-
- // Gets the current thread id, which may be useful for logging purposes.
- static PlatformThreadId CurrentId();
-
- // Gets the current thread reference, which can be used to check if
- // we're on the right thread quickly.
- static PlatformThreadRef CurrentRef();
-
- // Get the handle representing the current thread. On Windows, this is a
- // pseudo handle constant which will always represent the thread using it and
- // hence should not be shared with other threads nor be used to differentiate
- // the current thread from another.
- static PlatformThreadHandle CurrentHandle();
-
- // Yield the current thread so another thread can be scheduled.
- static void YieldCurrentThread();
-
- // Sleeps for the specified duration.
- static void Sleep(base::TimeDelta duration);
-
- // Sets the thread name visible to debuggers/tools. This has no effect
- // otherwise.
- static void SetName(const std::string& name);
-
- // Gets the thread name, if previously set by SetName.
- static const char* GetName();
-
- // 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) {
- return CreateWithPriority(stack_size, delegate, thread_handle,
- ThreadPriority::NORMAL);
- }
-
- // CreateWithPriority() does the same thing as Create() except the priority of
- // the thread is set based on |priority|.
- static bool CreateWithPriority(size_t stack_size, Delegate* delegate,
- PlatformThreadHandle* thread_handle,
- ThreadPriority priority);
-
- // 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);
-
- // Toggles the current thread's priority at runtime. A thread may not be able
- // to raise its priority back up after lowering it if the process does not
- // have a proper permission, e.g. CAP_SYS_NICE on Linux.
- // Since changing other threads' priority is not permitted in favor of
- // security, this interface is restricted to change only the current thread
- // priority (https://crbug.com/399473).
- static void SetCurrentThreadPriority(ThreadPriority priority);
-
- static ThreadPriority GetCurrentThreadPriority();
-
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(PlatformThread);
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_PLATFORM_THREAD_H_
diff --git a/security/sandbox/chromium/base/threading/platform_thread_internal_posix.cc b/security/sandbox/chromium/base/threading/platform_thread_internal_posix.cc
deleted file mode 100644
index 9af02044f..000000000
--- a/security/sandbox/chromium/base/threading/platform_thread_internal_posix.cc
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2015 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/threading/platform_thread_internal_posix.h"
-
-#include "base/logging.h"
-
-namespace base {
-
-namespace internal {
-
-int ThreadPriorityToNiceValue(ThreadPriority priority) {
- for (const ThreadPriorityToNiceValuePair& pair :
- kThreadPriorityToNiceValueMap) {
- if (pair.priority == priority)
- return pair.nice_value;
- }
- NOTREACHED() << "Unknown ThreadPriority";
- return 0;
-}
-
-ThreadPriority NiceValueToThreadPriority(int nice_value) {
- for (const ThreadPriorityToNiceValuePair& pair :
- kThreadPriorityToNiceValueMap) {
- if (pair.nice_value == nice_value)
- return pair.priority;
- }
- NOTREACHED() << "Unknown nice value";
- return ThreadPriority::NORMAL;
-}
-
-} // namespace internal
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/threading/platform_thread_internal_posix.h b/security/sandbox/chromium/base/threading/platform_thread_internal_posix.h
deleted file mode 100644
index 05a8d1e26..000000000
--- a/security/sandbox/chromium/base/threading/platform_thread_internal_posix.h
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2015 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_THREADING_PLATFORM_THREAD_INTERNAL_POSIX_H_
-#define BASE_THREADING_PLATFORM_THREAD_INTERNAL_POSIX_H_
-
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-namespace internal {
-
-struct ThreadPriorityToNiceValuePair {
- ThreadPriority priority;
- int nice_value;
-};
-extern const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4];
-
-// Returns the nice value matching |priority| based on the platform-specific
-// implementation of kThreadPriorityToNiceValueMap.
-int ThreadPriorityToNiceValue(ThreadPriority priority);
-
-// Returns the ThreadPrioirty matching |nice_value| based on the platform-
-// specific implementation of kThreadPriorityToNiceValueMap.
-ThreadPriority NiceValueToThreadPriority(int nice_value);
-
-// Allows platform specific tweaks to the generic POSIX solution for
-// SetCurrentThreadPriority. Returns true if the platform-specific
-// implementation handled this |priority| change, false if the generic
-// implementation should instead proceed.
-bool SetCurrentThreadPriorityForPlatform(ThreadPriority priority);
-
-// Returns true if there is a platform-specific ThreadPriority set on the
-// current thread (and returns the actual ThreadPriority via |priority|).
-// Returns false otherwise, leaving |priority| untouched.
-bool GetCurrentThreadPriorityForPlatform(ThreadPriority* priority);
-
-} // namespace internal
-
-} // namespace base
-
-#endif // BASE_THREADING_PLATFORM_THREAD_INTERNAL_POSIX_H_
diff --git a/security/sandbox/chromium/base/threading/platform_thread_linux.cc b/security/sandbox/chromium/base/threading/platform_thread_linux.cc
deleted file mode 100644
index 4057ede94..000000000
--- a/security/sandbox/chromium/base/threading/platform_thread_linux.cc
+++ /dev/null
@@ -1,120 +0,0 @@
-// 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.
-
-#include "base/threading/platform_thread.h"
-
-#include <errno.h>
-#include <sched.h>
-#include <stddef.h>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/threading/platform_thread_internal_posix.h"
-#include "base/threading/thread_id_name_manager.h"
-#include "base/tracked_objects.h"
-#include "build/build_config.h"
-
-#if !defined(OS_NACL)
-#include <pthread.h>
-#include <sys/prctl.h>
-#include <sys/types.h>
-#include <unistd.h>
-#endif
-
-namespace base {
-
-namespace internal {
-
-namespace {
-#if !defined(OS_NACL)
-const struct sched_param kRealTimePrio = {8};
-const struct sched_param kResetPrio = {0};
-#endif
-} // namespace
-
-const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4] = {
- {ThreadPriority::BACKGROUND, 10},
- {ThreadPriority::NORMAL, 0},
- {ThreadPriority::DISPLAY, -6},
- {ThreadPriority::REALTIME_AUDIO, -10},
-};
-
-bool SetCurrentThreadPriorityForPlatform(ThreadPriority priority) {
-#if !defined(OS_NACL)
- ThreadPriority current_priority;
- if (priority != ThreadPriority::REALTIME_AUDIO &&
- GetCurrentThreadPriorityForPlatform(&current_priority) &&
- current_priority == ThreadPriority::REALTIME_AUDIO) {
- // If the pthread's round-robin scheduler is already enabled, and the new
- // priority will use setpriority() instead, the pthread scheduler should be
- // reset to use SCHED_OTHER so that setpriority() just works.
- pthread_setschedparam(pthread_self(), SCHED_OTHER, &kResetPrio);
- return false;
- }
- return priority == ThreadPriority::REALTIME_AUDIO &&
- pthread_setschedparam(pthread_self(), SCHED_RR, &kRealTimePrio) == 0;
-#else
- return false;
-#endif
-}
-
-bool GetCurrentThreadPriorityForPlatform(ThreadPriority* priority) {
-#if !defined(OS_NACL)
- int maybe_sched_rr = 0;
- struct sched_param maybe_realtime_prio = {0};
- if (pthread_getschedparam(pthread_self(), &maybe_sched_rr,
- &maybe_realtime_prio) == 0 &&
- maybe_sched_rr == SCHED_RR &&
- maybe_realtime_prio.sched_priority == kRealTimePrio.sched_priority) {
- *priority = ThreadPriority::REALTIME_AUDIO;
- return true;
- }
-#endif
- return false;
-}
-
-} // namespace internal
-
-// static
-void PlatformThread::SetName(const std::string& name) {
- ThreadIdNameManager::GetInstance()->SetName(CurrentId(), name);
- tracked_objects::ThreadData::InitializeThreadContext(name);
-
-#if !defined(OS_NACL)
- // 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;
-
- // http://0pointer.de/blog/projects/name-your-threads.html
- // Set the name for the LWP (which gets truncated to 15 characters).
- // Note that glibc also has a 'pthread_setname_np' api, but it may not be
- // available everywhere and it's only benefit over using prctl directly is
- // that it can set the name of threads other than the current thread.
- int err = prctl(PR_SET_NAME, name.c_str());
- // We expect EPERM failures in sandboxed processes, just ignore those.
- if (err < 0 && errno != EPERM)
- DPLOG(ERROR) << "prctl(PR_SET_NAME)";
-#endif // !defined(OS_NACL)
-}
-
-void InitThreading() {}
-
-void InitOnThread() {}
-
-void TerminateOnThread() {}
-
-size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes) {
-#if !defined(THREAD_SANITIZER)
- return 0;
-#else
- // ThreadSanitizer bloats the stack heavily. Evidence has been that the
- // default stack size isn't enough for some browser tests.
- return 2 * (1 << 23); // 2 times 8192K (the default stack size on Linux).
-#endif
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/threading/platform_thread_posix.cc b/security/sandbox/chromium/base/threading/platform_thread_posix.cc
deleted file mode 100644
index 39a007316..000000000
--- a/security/sandbox/chromium/base/threading/platform_thread_posix.cc
+++ /dev/null
@@ -1,263 +0,0 @@
-// 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.
-
-#include "base/threading/platform_thread.h"
-
-#include <errno.h>
-#include <pthread.h>
-#include <sched.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/resource.h>
-#include <sys/time.h>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/threading/platform_thread_internal_posix.h"
-#include "base/threading/thread_id_name_manager.h"
-#include "base/threading/thread_restrictions.h"
-#include "build/build_config.h"
-
-#if defined(OS_LINUX)
-#include <sys/syscall.h>
-#elif defined(OS_ANDROID)
-#include <sys/types.h>
-#endif
-
-namespace base {
-
-void InitThreading();
-void InitOnThread();
-void TerminateOnThread();
-size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes);
-
-namespace {
-
-struct ThreadParams {
- ThreadParams()
- : delegate(NULL), joinable(false), priority(ThreadPriority::NORMAL) {}
-
- PlatformThread::Delegate* delegate;
- bool joinable;
- ThreadPriority priority;
-};
-
-void* ThreadFunc(void* params) {
- base::InitOnThread();
-
- PlatformThread::Delegate* delegate = nullptr;
-
- {
- scoped_ptr<ThreadParams> thread_params(static_cast<ThreadParams*>(params));
-
- delegate = thread_params->delegate;
- if (!thread_params->joinable)
- base::ThreadRestrictions::SetSingletonAllowed(false);
-
- if (thread_params->priority != ThreadPriority::NORMAL)
- PlatformThread::SetCurrentThreadPriority(thread_params->priority);
- }
-
- ThreadIdNameManager::GetInstance()->RegisterThread(
- PlatformThread::CurrentHandle().platform_handle(),
- PlatformThread::CurrentId());
-
- delegate->ThreadMain();
-
- ThreadIdNameManager::GetInstance()->RemoveName(
- PlatformThread::CurrentHandle().platform_handle(),
- PlatformThread::CurrentId());
-
- base::TerminateOnThread();
- return NULL;
-}
-
-bool CreateThread(size_t stack_size,
- bool joinable,
- PlatformThread::Delegate* delegate,
- PlatformThreadHandle* thread_handle,
- ThreadPriority priority) {
- DCHECK(thread_handle);
- base::InitThreading();
-
- 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);
-
- // Get a better default if available.
- if (stack_size == 0)
- stack_size = base::GetDefaultThreadStackSize(attributes);
-
- if (stack_size > 0)
- pthread_attr_setstacksize(&attributes, stack_size);
-
- scoped_ptr<ThreadParams> params(new ThreadParams);
- params->delegate = delegate;
- params->joinable = joinable;
- params->priority = priority;
-
- pthread_t handle;
- int err = pthread_create(&handle, &attributes, ThreadFunc, params.get());
- bool success = !err;
- if (success) {
- // ThreadParams should be deleted on the created thread after used.
- ignore_result(params.release());
- } else {
- // Value of |handle| is undefined if pthread_create fails.
- handle = 0;
- errno = err;
- PLOG(ERROR) << "pthread_create";
- }
- *thread_handle = PlatformThreadHandle(handle);
-
- pthread_attr_destroy(&attributes);
-
- return success;
-}
-
-} // namespace
-
-// 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(OS_MACOSX)
- return pthread_mach_thread_np(pthread_self());
-#elif defined(OS_LINUX)
- return syscall(__NR_gettid);
-#elif defined(OS_ANDROID)
- return gettid();
-#elif defined(OS_SOLARIS) || defined(OS_QNX)
- return pthread_self();
-#elif defined(OS_NACL) && defined(__GLIBC__)
- return pthread_self();
-#elif defined(OS_NACL) && !defined(__GLIBC__)
- // Pointers are 32-bits in NaCl.
- return reinterpret_cast<int32_t>(pthread_self());
-#elif defined(OS_POSIX)
- return reinterpret_cast<int64_t>(pthread_self());
-#endif
-}
-
-// static
-PlatformThreadRef PlatformThread::CurrentRef() {
- return PlatformThreadRef(pthread_self());
-}
-
-// static
-PlatformThreadHandle PlatformThread::CurrentHandle() {
- return PlatformThreadHandle(pthread_self());
-}
-
-// static
-void PlatformThread::YieldCurrentThread() {
- sched_yield();
-}
-
-// static
-void PlatformThread::Sleep(TimeDelta duration) {
- struct timespec sleep_time, remaining;
-
- // Break the duration into seconds and nanoseconds.
- // NOTE: TimeDelta's microseconds are int64s while timespec's
- // nanoseconds are longs, so this unpacking must prevent overflow.
- sleep_time.tv_sec = duration.InSeconds();
- duration -= TimeDelta::FromSeconds(sleep_time.tv_sec);
- sleep_time.tv_nsec = duration.InMicroseconds() * 1000; // nanoseconds
-
- while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
- sleep_time = remaining;
-}
-
-// static
-const char* PlatformThread::GetName() {
- return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
-}
-
-// static
-bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
- PlatformThreadHandle* thread_handle,
- ThreadPriority priority) {
- return CreateThread(stack_size, true, // joinable thread
- delegate, thread_handle, priority);
-}
-
-// static
-bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
- PlatformThreadHandle unused;
-
- bool result = CreateThread(stack_size, false /* non-joinable thread */,
- delegate, &unused, ThreadPriority::NORMAL);
- return result;
-}
-
-// static
-void PlatformThread::Join(PlatformThreadHandle thread_handle) {
- // Joining another thread may block the current thread for a long time, since
- // the thread referred to by |thread_handle| may still be running long-lived /
- // blocking tasks.
- base::ThreadRestrictions::AssertIOAllowed();
- CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), NULL));
-}
-
-// Mac has its own Set/GetCurrentThreadPriority() implementations.
-#if !defined(OS_MACOSX)
-
-// static
-void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
-#if defined(OS_NACL)
- NOTIMPLEMENTED();
-#else
- if (internal::SetCurrentThreadPriorityForPlatform(priority))
- return;
-
- // setpriority(2) should change the whole thread group's (i.e. process)
- // priority. However, as stated in the bugs section of
- // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current
- // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread
- // attribute". Also, 0 is prefered to the current thread id since it is
- // equivalent but makes sandboxing easier (https://crbug.com/399473).
- const int nice_setting = internal::ThreadPriorityToNiceValue(priority);
- if (setpriority(PRIO_PROCESS, 0, nice_setting)) {
- DVPLOG(1) << "Failed to set nice value of thread ("
- << PlatformThread::CurrentId() << ") to " << nice_setting;
- }
-#endif // defined(OS_NACL)
-}
-
-// static
-ThreadPriority PlatformThread::GetCurrentThreadPriority() {
-#if defined(OS_NACL)
- NOTIMPLEMENTED();
- return ThreadPriority::NORMAL;
-#else
- // Mirrors SetCurrentThreadPriority()'s implementation.
- ThreadPriority platform_specific_priority;
- if (internal::GetCurrentThreadPriorityForPlatform(
- &platform_specific_priority)) {
- return platform_specific_priority;
- }
-
- // Need to clear errno before calling getpriority():
- // http://man7.org/linux/man-pages/man2/getpriority.2.html
- errno = 0;
- int nice_value = getpriority(PRIO_PROCESS, 0);
- if (errno != 0) {
- DVPLOG(1) << "Failed to get nice value of thread ("
- << PlatformThread::CurrentId() << ")";
- return ThreadPriority::NORMAL;
- }
-
- return internal::NiceValueToThreadPriority(nice_value);
-#endif // !defined(OS_NACL)
-}
-
-#endif // !defined(OS_MACOSX)
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/threading/platform_thread_win.cc b/security/sandbox/chromium/base/threading/platform_thread_win.cc
deleted file mode 100644
index d5bd9bed0..000000000
--- a/security/sandbox/chromium/base/threading/platform_thread_win.cc
+++ /dev/null
@@ -1,284 +0,0 @@
-// 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.
-
-#include "base/threading/platform_thread.h"
-
-#include <stddef.h>
-
-#include "base/debug/alias.h"
-#include "base/debug/profiler.h"
-#include "base/logging.h"
-#include "base/threading/thread_id_name_manager.h"
-#include "base/threading/thread_restrictions.h"
-#include "base/tracked_objects.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_version.h"
-
-namespace base {
-
-namespace {
-
-// The information on how to set the thread name comes from
-// a MSDN article: http://msdn2.microsoft.com/en-us/library/xcb2z8hs.aspx
-const DWORD kVCThreadNameException = 0x406D1388;
-
-typedef struct tagTHREADNAME_INFO {
- DWORD dwType; // Must be 0x1000.
- LPCSTR szName; // Pointer to name (in user addr space).
- DWORD dwThreadID; // Thread ID (-1=caller thread).
- DWORD dwFlags; // Reserved for future use, must be zero.
-} THREADNAME_INFO;
-
-// This function has try handling, so it is separated out of its caller.
-void SetNameInternal(PlatformThreadId thread_id, const char* name) {
- THREADNAME_INFO info;
- info.dwType = 0x1000;
- info.szName = name;
- info.dwThreadID = thread_id;
- info.dwFlags = 0;
-
- __try {
- RaiseException(kVCThreadNameException, 0, sizeof(info)/sizeof(DWORD),
- reinterpret_cast<DWORD_PTR*>(&info));
- } __except(EXCEPTION_CONTINUE_EXECUTION) {
- }
-}
-
-struct ThreadParams {
- PlatformThread::Delegate* delegate;
- bool joinable;
- ThreadPriority priority;
-};
-
-DWORD __stdcall ThreadFunc(void* params) {
- ThreadParams* thread_params = static_cast<ThreadParams*>(params);
- PlatformThread::Delegate* delegate = thread_params->delegate;
- if (!thread_params->joinable)
- base::ThreadRestrictions::SetSingletonAllowed(false);
-
- if (thread_params->priority != ThreadPriority::NORMAL)
- PlatformThread::SetCurrentThreadPriority(thread_params->priority);
-
- // Retrieve a copy of the thread handle to use as the key in the
- // thread name mapping.
- PlatformThreadHandle::Handle platform_handle;
- BOOL did_dup = DuplicateHandle(GetCurrentProcess(),
- GetCurrentThread(),
- GetCurrentProcess(),
- &platform_handle,
- 0,
- FALSE,
- DUPLICATE_SAME_ACCESS);
-
- win::ScopedHandle scoped_platform_handle;
-
- if (did_dup) {
- scoped_platform_handle.Set(platform_handle);
- ThreadIdNameManager::GetInstance()->RegisterThread(
- scoped_platform_handle.Get(),
- PlatformThread::CurrentId());
- }
-
- delete thread_params;
- delegate->ThreadMain();
-
- if (did_dup) {
- ThreadIdNameManager::GetInstance()->RemoveName(
- scoped_platform_handle.Get(),
- PlatformThread::CurrentId());
- }
-
- return 0;
-}
-
-// CreateThreadInternal() matches PlatformThread::CreateWithPriority(), except
-// that |out_thread_handle| may be nullptr, in which case a non-joinable thread
-// is created.
-bool CreateThreadInternal(size_t stack_size,
- PlatformThread::Delegate* delegate,
- PlatformThreadHandle* out_thread_handle,
- ThreadPriority priority) {
- unsigned int flags = 0;
- if (stack_size > 0 && base::win::GetVersion() >= base::win::VERSION_XP) {
- flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
- } else {
- stack_size = 0;
- }
-
- ThreadParams* params = new ThreadParams;
- params->delegate = delegate;
- params->joinable = out_thread_handle != nullptr;
- params->priority = priority;
-
- // 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
- void* thread_handle =
- ::CreateThread(nullptr, stack_size, ThreadFunc, params, flags, nullptr);
- if (!thread_handle) {
- delete params;
- return false;
- }
-
- if (out_thread_handle)
- *out_thread_handle = PlatformThreadHandle(thread_handle);
- else
- CloseHandle(thread_handle);
- return true;
-}
-
-} // namespace
-
-// static
-PlatformThreadId PlatformThread::CurrentId() {
- return ::GetCurrentThreadId();
-}
-
-// static
-PlatformThreadRef PlatformThread::CurrentRef() {
- return PlatformThreadRef(::GetCurrentThreadId());
-}
-
-// static
-PlatformThreadHandle PlatformThread::CurrentHandle() {
- return PlatformThreadHandle(::GetCurrentThread());
-}
-
-// static
-void PlatformThread::YieldCurrentThread() {
- ::Sleep(0);
-}
-
-// static
-void PlatformThread::Sleep(TimeDelta duration) {
- // When measured with a high resolution clock, Sleep() sometimes returns much
- // too early. We may need to call it repeatedly to get the desired duration.
- TimeTicks end = TimeTicks::Now() + duration;
- for (TimeTicks now = TimeTicks::Now(); now < end; now = TimeTicks::Now())
- ::Sleep(static_cast<DWORD>((end - now).InMillisecondsRoundedUp()));
-}
-
-// static
-void PlatformThread::SetName(const std::string& name) {
- ThreadIdNameManager::GetInstance()->SetName(CurrentId(), name);
-
- // On Windows only, we don't need to tell the profiler about the "BrokerEvent"
- // thread, as it exists only in the chrome.exe image, and never spawns or runs
- // tasks (items which could be profiled). This test avoids the notification,
- // which would also (as a side effect) initialize the profiler in this unused
- // context, including setting up thread local storage, etc. The performance
- // impact is not terrible, but there is no reason to do initialize it.
- if (name != "BrokerEvent")
- tracked_objects::ThreadData::InitializeThreadContext(name);
-
- // The debugger needs to be around to catch the name in the exception. If
- // there isn't a debugger, we are just needlessly throwing an exception.
- // If this image file is instrumented, we raise the exception anyway
- // to provide the profiler with human-readable thread names.
- if (!::IsDebuggerPresent() && !base::debug::IsBinaryInstrumented())
- return;
-
- SetNameInternal(CurrentId(), name.c_str());
-}
-
-// static
-const char* PlatformThread::GetName() {
- return ThreadIdNameManager::GetInstance()->GetName(CurrentId());
-}
-
-// static
-bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate,
- PlatformThreadHandle* thread_handle,
- ThreadPriority priority) {
- DCHECK(thread_handle);
- return CreateThreadInternal(stack_size, delegate, thread_handle, priority);
-}
-
-// static
-bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
- return CreateThreadInternal(stack_size, delegate, nullptr,
- ThreadPriority::NORMAL);
-}
-
-// static
-void PlatformThread::Join(PlatformThreadHandle thread_handle) {
- DCHECK(thread_handle.platform_handle());
- // TODO(willchan): Enable this check once I can get it to work for Windows
- // shutdown.
- // Joining another thread may block the current thread for a long time, since
- // the thread referred to by |thread_handle| may still be running long-lived /
- // blocking tasks.
-#if 0
- base::ThreadRestrictions::AssertIOAllowed();
-#endif
-
- // Wait for the thread to exit. It should already have terminated but make
- // sure this assumption is valid.
- DWORD result = WaitForSingleObject(thread_handle.platform_handle(), INFINITE);
- if (result != WAIT_OBJECT_0) {
- // Debug info for bug 127931.
- DWORD error = GetLastError();
- debug::Alias(&error);
- debug::Alias(&result);
- CHECK(false);
- }
-
- CloseHandle(thread_handle.platform_handle());
-}
-
-// static
-void PlatformThread::SetCurrentThreadPriority(ThreadPriority priority) {
- int desired_priority = THREAD_PRIORITY_ERROR_RETURN;
- switch (priority) {
- case ThreadPriority::BACKGROUND:
- desired_priority = THREAD_PRIORITY_LOWEST;
- break;
- case ThreadPriority::NORMAL:
- desired_priority = THREAD_PRIORITY_NORMAL;
- break;
- case ThreadPriority::DISPLAY:
- desired_priority = THREAD_PRIORITY_ABOVE_NORMAL;
- break;
- case ThreadPriority::REALTIME_AUDIO:
- desired_priority = THREAD_PRIORITY_TIME_CRITICAL;
- break;
- default:
- NOTREACHED() << "Unknown priority.";
- break;
- }
- DCHECK_NE(desired_priority, THREAD_PRIORITY_ERROR_RETURN);
-
-#ifndef NDEBUG
- const BOOL success =
-#endif
- ::SetThreadPriority(PlatformThread::CurrentHandle().platform_handle(),
- desired_priority);
- DPLOG_IF(ERROR, !success) << "Failed to set thread priority to "
- << desired_priority;
-}
-
-// static
-ThreadPriority PlatformThread::GetCurrentThreadPriority() {
- int priority =
- ::GetThreadPriority(PlatformThread::CurrentHandle().platform_handle());
- switch (priority) {
- case THREAD_PRIORITY_LOWEST:
- return ThreadPriority::BACKGROUND;
- case THREAD_PRIORITY_NORMAL:
- return ThreadPriority::NORMAL;
- case THREAD_PRIORITY_ABOVE_NORMAL:
- return ThreadPriority::DISPLAY;
- case THREAD_PRIORITY_TIME_CRITICAL:
- return ThreadPriority::REALTIME_AUDIO;
- case THREAD_PRIORITY_ERROR_RETURN:
- DPCHECK(false) << "GetThreadPriority error"; // Falls through.
- default:
- NOTREACHED() << "Unexpected priority: " << priority;
- return ThreadPriority::NORMAL;
- }
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/threading/sequenced_worker_pool.h b/security/sandbox/chromium/base/threading/sequenced_worker_pool.h
deleted file mode 100644
index ba0e44421..000000000
--- a/security/sandbox/chromium/base/threading/sequenced_worker_pool.h
+++ /dev/null
@@ -1,384 +0,0 @@
-// 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.
-
-#ifndef BASE_THREADING_SEQUENCED_WORKER_POOL_H_
-#define BASE_THREADING_SEQUENCED_WORKER_POOL_H_
-
-#include <stddef.h>
-
-#include <cstddef>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/callback_forward.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/single_thread_task_runner.h"
-#include "base/task_runner.h"
-
-namespace tracked_objects {
-class Location;
-} // namespace tracked_objects
-
-namespace base {
-
-class SingleThreadTaskRunner;
-
-template <class T> class DeleteHelper;
-
-class SequencedTaskRunner;
-
-// A worker thread pool that enforces ordering between sets of tasks. It also
-// allows you to specify what should happen to your tasks on shutdown.
-//
-// To enforce ordering, get a unique sequence token from the pool and post all
-// tasks you want to order with the token. All tasks with the same token are
-// guaranteed to execute serially, though not necessarily on the same thread.
-// This means that:
-//
-// - No two tasks with the same token will run at the same time.
-//
-// - Given two tasks T1 and T2 with the same token such that T2 will
-// run after T1, then T2 will start after T1 is destroyed.
-//
-// - If T2 will run after T1, then all memory changes in T1 and T1's
-// destruction will be visible to T2.
-//
-// Example:
-// SequencedWorkerPool::SequenceToken token =
-// SequencedWorkerPool::GetSequenceToken();
-// pool.PostSequencedWorkerTask(token, SequencedWorkerPool::SKIP_ON_SHUTDOWN,
-// FROM_HERE, base::Bind(...));
-// pool.PostSequencedWorkerTask(token, SequencedWorkerPool::SKIP_ON_SHUTDOWN,
-// FROM_HERE, base::Bind(...));
-//
-// You can make named sequence tokens to make it easier to share a token
-// across different components.
-//
-// You can also post tasks to the pool without ordering using PostWorkerTask.
-// These will be executed in an unspecified order. The order of execution
-// between tasks with different sequence tokens is also unspecified.
-//
-// This class may be leaked on shutdown to facilitate fast shutdown. The
-// expected usage, however, is to call Shutdown(), which correctly accounts
-// for CONTINUE_ON_SHUTDOWN behavior and is required for BLOCK_SHUTDOWN
-// behavior.
-//
-// Implementation note: This does not use a base::WorkerPool since that does
-// not enforce shutdown semantics or allow us to specify how many worker
-// threads to run. For the typical use case of random background work, we don't
-// necessarily want to be super aggressive about creating threads.
-//
-// Note that SequencedWorkerPool is RefCountedThreadSafe (inherited
-// from TaskRunner).
-//
-// Test-only code should wrap this in a base::SequencedWorkerPoolOwner to avoid
-// memory leaks. See http://crbug.com/273800
-class BASE_EXPORT SequencedWorkerPool : public TaskRunner {
- public:
- // Defines what should happen to a task posted to the worker pool on
- // shutdown.
- enum WorkerShutdown {
- // Tasks posted with this mode which have not run at shutdown will be
- // deleted rather than run, and any tasks with this mode running at
- // shutdown will be ignored (the worker thread will not be joined).
- //
- // This option provides a nice way to post stuff you don't want blocking
- // shutdown. For example, you might be doing a slow DNS lookup and if it's
- // blocked on the OS, you may not want to stop shutdown, since the result
- // doesn't really matter at that point.
- //
- // However, you need to be very careful what you do in your callback when
- // you use this option. Since the thread will continue to run until the OS
- // terminates the process, the app can be in the process of tearing down
- // when you're running. This means any singletons or global objects you
- // use may suddenly become invalid out from under you. For this reason,
- // it's best to use this only for slow but simple operations like the DNS
- // example.
- CONTINUE_ON_SHUTDOWN,
-
- // Tasks posted with this mode that have not started executing at
- // shutdown will be deleted rather than executed. However, any tasks that
- // have already begun executing when shutdown is called will be allowed
- // to continue, and will block shutdown until completion.
- //
- // Note: Because Shutdown() may block while these tasks are executing,
- // care must be taken to ensure that they do not block on the thread that
- // called Shutdown(), as this may lead to deadlock.
- SKIP_ON_SHUTDOWN,
-
- // Tasks posted with this mode will block shutdown until they're
- // executed. Since this can have significant performance implications,
- // use sparingly.
- //
- // Generally, this should be used only for user data, for example, a task
- // writing a preference file.
- //
- // If a task is posted during shutdown, it will not get run since the
- // workers may already be stopped. In this case, the post operation will
- // fail (return false) and the task will be deleted.
- BLOCK_SHUTDOWN,
- };
-
- // Opaque identifier that defines sequencing of tasks posted to the worker
- // pool.
- class BASE_EXPORT SequenceToken {
- public:
- SequenceToken() : id_(0) {}
- ~SequenceToken() {}
-
- bool Equals(const SequenceToken& other) const {
- return id_ == other.id_;
- }
-
- // Returns false if current thread is executing an unsequenced task.
- bool IsValid() const {
- return id_ != 0;
- }
-
- // Returns a string representation of this token. This method should only be
- // used for debugging.
- std::string ToString() const;
-
- private:
- friend class SequencedWorkerPool;
-
- explicit SequenceToken(int id) : id_(id) {}
-
- int id_;
- };
-
- // Allows tests to perform certain actions.
- class TestingObserver {
- public:
- virtual ~TestingObserver() {}
- virtual void OnHasWork() = 0;
- virtual void WillWaitForShutdown() = 0;
- virtual void OnDestruct() = 0;
- };
-
- // Gets the SequencedToken of the current thread.
- // If current thread is not a SequencedWorkerPool worker thread or is running
- // an unsequenced task, returns an invalid SequenceToken.
- static SequenceToken GetSequenceTokenForCurrentThread();
-
- // Gets a SequencedTaskRunner for the current thread. If the current thread is
- // running an unsequenced task, a new SequenceToken will be generated and set,
- // so that the returned SequencedTaskRunner is guaranteed to run tasks after
- // the current task has finished running.
- static scoped_refptr<SequencedTaskRunner>
- GetSequencedTaskRunnerForCurrentThread();
-
- // Returns a unique token that can be used to sequence tasks posted to
- // PostSequencedWorkerTask(). Valid tokens are always nonzero.
- // TODO(bauerb): Rename this to better differentiate from
- // GetSequenceTokenForCurrentThread().
- static SequenceToken GetSequenceToken();
-
- // Returns the SequencedWorkerPool that owns this thread, or null if the
- // current thread is not a SequencedWorkerPool worker thread.
- static scoped_refptr<SequencedWorkerPool> GetWorkerPoolForCurrentThread();
-
- // When constructing a SequencedWorkerPool, there must be a
- // ThreadTaskRunnerHandle on the current thread unless you plan to
- // deliberately leak it.
-
- // Pass the maximum number of threads (they will be lazily created as needed)
- // and a prefix for the thread name to aid in debugging.
- SequencedWorkerPool(size_t max_threads,
- const std::string& thread_name_prefix);
-
- // Like above, but with |observer| for testing. Does not take ownership of
- // |observer|.
- SequencedWorkerPool(size_t max_threads,
- const std::string& thread_name_prefix,
- TestingObserver* observer);
-
- // Returns the sequence token associated with the given name. Calling this
- // function multiple times with the same string will always produce the
- // same sequence token. If the name has not been used before, a new token
- // will be created.
- SequenceToken GetNamedSequenceToken(const std::string& name);
-
- // Returns a SequencedTaskRunner wrapper which posts to this
- // SequencedWorkerPool using the given sequence token. Tasks with nonzero
- // delay are posted with SKIP_ON_SHUTDOWN behavior and tasks with zero delay
- // are posted with BLOCK_SHUTDOWN behavior.
- scoped_refptr<SequencedTaskRunner> GetSequencedTaskRunner(
- SequenceToken token);
-
- // Returns a SequencedTaskRunner wrapper which posts to this
- // SequencedWorkerPool using the given sequence token. Tasks with nonzero
- // delay are posted with SKIP_ON_SHUTDOWN behavior and tasks with zero delay
- // are posted with the given shutdown behavior.
- scoped_refptr<SequencedTaskRunner> GetSequencedTaskRunnerWithShutdownBehavior(
- SequenceToken token,
- WorkerShutdown shutdown_behavior);
-
- // Returns a TaskRunner wrapper which posts to this SequencedWorkerPool using
- // the given shutdown behavior. Tasks with nonzero delay are posted with
- // SKIP_ON_SHUTDOWN behavior and tasks with zero delay are posted with the
- // given shutdown behavior.
- scoped_refptr<TaskRunner> GetTaskRunnerWithShutdownBehavior(
- WorkerShutdown shutdown_behavior);
-
- // Posts the given task for execution in the worker pool. Tasks posted with
- // this function will execute in an unspecified order on a background thread.
- // Returns true if the task was posted. If your tasks have ordering
- // requirements, see PostSequencedWorkerTask().
- //
- // This class will attempt to delete tasks that aren't run
- // (non-block-shutdown semantics) but can't guarantee that this happens. If
- // all worker threads are busy running CONTINUE_ON_SHUTDOWN tasks, there
- // will be no workers available to delete these tasks. And there may be
- // tasks with the same sequence token behind those CONTINUE_ON_SHUTDOWN
- // tasks. Deleting those tasks before the previous one has completed could
- // cause nondeterministic crashes because the task could be keeping some
- // objects alive which do work in their destructor, which could voilate the
- // assumptions of the running task.
- //
- // The task will be guaranteed to run to completion before shutdown
- // (BLOCK_SHUTDOWN semantics).
- //
- // Returns true if the task was posted successfully. This may fail during
- // shutdown regardless of the specified ShutdownBehavior.
- bool PostWorkerTask(const tracked_objects::Location& from_here,
- const Closure& task);
-
- // Same as PostWorkerTask but allows a delay to be specified (although doing
- // so changes the shutdown behavior). The task will be run after the given
- // delay has elapsed.
- //
- // If the delay is nonzero, the task won't be guaranteed to run to completion
- // before shutdown (SKIP_ON_SHUTDOWN semantics) to avoid shutdown hangs.
- // If the delay is zero, this behaves exactly like PostWorkerTask, i.e. the
- // task will be guaranteed to run to completion before shutdown
- // (BLOCK_SHUTDOWN semantics).
- bool PostDelayedWorkerTask(const tracked_objects::Location& from_here,
- const Closure& task,
- TimeDelta delay);
-
- // Same as PostWorkerTask but allows specification of the shutdown behavior.
- bool PostWorkerTaskWithShutdownBehavior(
- const tracked_objects::Location& from_here,
- const Closure& task,
- WorkerShutdown shutdown_behavior);
-
- // Like PostWorkerTask above, but provides sequencing semantics. This means
- // that tasks posted with the same sequence token (see GetSequenceToken())
- // are guaranteed to execute in order. This is useful in cases where you're
- // doing operations that may depend on previous ones, like appending to a
- // file.
- //
- // The task will be guaranteed to run to completion before shutdown
- // (BLOCK_SHUTDOWN semantics).
- //
- // Returns true if the task was posted successfully. This may fail during
- // shutdown regardless of the specified ShutdownBehavior.
- bool PostSequencedWorkerTask(SequenceToken sequence_token,
- const tracked_objects::Location& from_here,
- const Closure& task);
-
- // Like PostSequencedWorkerTask above, but allows you to specify a named
- // token, which saves an extra call to GetNamedSequenceToken.
- bool PostNamedSequencedWorkerTask(const std::string& token_name,
- const tracked_objects::Location& from_here,
- const Closure& task);
-
- // Same as PostSequencedWorkerTask but allows a delay to be specified
- // (although doing so changes the shutdown behavior). The task will be run
- // after the given delay has elapsed.
- //
- // If the delay is nonzero, the task won't be guaranteed to run to completion
- // before shutdown (SKIP_ON_SHUTDOWN semantics) to avoid shutdown hangs.
- // If the delay is zero, this behaves exactly like PostSequencedWorkerTask,
- // i.e. the task will be guaranteed to run to completion before shutdown
- // (BLOCK_SHUTDOWN semantics).
- bool PostDelayedSequencedWorkerTask(
- SequenceToken sequence_token,
- const tracked_objects::Location& from_here,
- const Closure& task,
- TimeDelta delay);
-
- // Same as PostSequencedWorkerTask but allows specification of the shutdown
- // behavior.
- bool PostSequencedWorkerTaskWithShutdownBehavior(
- SequenceToken sequence_token,
- const tracked_objects::Location& from_here,
- const Closure& task,
- WorkerShutdown shutdown_behavior);
-
- // TaskRunner implementation. Forwards to PostDelayedWorkerTask().
- bool PostDelayedTask(const tracked_objects::Location& from_here,
- const Closure& task,
- TimeDelta delay) override;
- bool RunsTasksOnCurrentThread() const override;
-
- // Returns true if the current thread is processing a task with the given
- // sequence_token.
- bool IsRunningSequenceOnCurrentThread(SequenceToken sequence_token) const;
-
- // Returns true if any thread is currently processing a task with the given
- // sequence token. Should only be called with a valid sequence token.
- bool IsRunningSequence(SequenceToken sequence_token) const;
-
- // Blocks until all pending tasks are complete. This should only be called in
- // unit tests when you want to validate something that should have happened.
- // This will not flush delayed tasks; delayed tasks get deleted.
- //
- // Note that calling this will not prevent other threads from posting work to
- // the queue while the calling thread is waiting on Flush(). In this case,
- // Flush will return only when there's no more work in the queue. Normally,
- // this doesn't come up since in a test, all the work is being posted from
- // the main thread.
- void FlushForTesting();
-
- // Spuriously signal that there is work to be done.
- void SignalHasWorkForTesting();
-
- // Implements the worker pool shutdown. This should be called during app
- // shutdown, and will discard/join with appropriate tasks before returning.
- // After this call, subsequent calls to post tasks will fail.
- //
- // Must be called from the same thread this object was constructed on.
- void Shutdown() { Shutdown(0); }
-
- // A variant that allows an arbitrary number of new blocking tasks to be
- // posted during shutdown. The tasks cannot be posted within the execution
- // context of tasks whose shutdown behavior is not BLOCKING_SHUTDOWN. Once
- // the limit is reached, subsequent calls to post task fail in all cases.
- // Must be called from the same thread this object was constructed on.
- void Shutdown(int max_new_blocking_tasks_after_shutdown);
-
- // Check if Shutdown was called for given threading pool. This method is used
- // for aborting time consuming operation to avoid blocking shutdown.
- //
- // Can be called from any thread.
- bool IsShutdownInProgress();
-
- protected:
- ~SequencedWorkerPool() override;
-
- void OnDestruct() const override;
-
- private:
- friend class RefCountedThreadSafe<SequencedWorkerPool>;
- friend class DeleteHelper<SequencedWorkerPool>;
-
- class Inner;
- class Worker;
-
- const scoped_refptr<SingleThreadTaskRunner> constructor_task_runner_;
-
- // Avoid pulling in too many headers by putting (almost) everything
- // into |inner_|.
- const scoped_ptr<Inner> inner_;
-
- DISALLOW_COPY_AND_ASSIGN(SequencedWorkerPool);
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_SEQUENCED_WORKER_POOL_H_
diff --git a/security/sandbox/chromium/base/threading/thread_checker_impl.h b/security/sandbox/chromium/base/threading/thread_checker_impl.h
deleted file mode 100644
index c92e143db..000000000
--- a/security/sandbox/chromium/base/threading/thread_checker_impl.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// 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_THREADING_THREAD_CHECKER_IMPL_H_
-#define BASE_THREADING_THREAD_CHECKER_IMPL_H_
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-// Real implementation of ThreadChecker, for use in debug mode, or
-// for temporary use in release mode (e.g. to CHECK on a threading issue
-// seen only in the wild).
-//
-// Note: You should almost always use the ThreadChecker class to get the
-// right version for your build configuration.
-class BASE_EXPORT ThreadCheckerImpl {
- public:
- ThreadCheckerImpl();
- ~ThreadCheckerImpl();
-
- bool CalledOnValidThread() const WARN_UNUSED_RESULT;
-
- // Changes the thread that is checked for in CalledOnValidThread. This may
- // be useful when an object may be created on one thread and then used
- // exclusively on another thread.
- void DetachFromThread();
-
- private:
- void EnsureThreadIdAssigned() const;
-
- mutable base::Lock lock_;
- // This is mutable so that CalledOnValidThread can set it.
- // It's guarded by |lock_|.
- mutable PlatformThreadRef valid_thread_id_;
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_THREAD_CHECKER_IMPL_H_
diff --git a/security/sandbox/chromium/base/threading/thread_collision_warner.cc b/security/sandbox/chromium/base/threading/thread_collision_warner.cc
deleted file mode 100644
index 547e11ca6..000000000
--- a/security/sandbox/chromium/base/threading/thread_collision_warner.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-// 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/threading/thread_collision_warner.h"
-
-#include "base/logging.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-void DCheckAsserter::warn() {
- NOTREACHED() << "Thread Collision";
-}
-
-static subtle::Atomic32 CurrentThread() {
- const PlatformThreadId current_thread_id = PlatformThread::CurrentId();
- // We need to get the thread id into an atomic data type. This might be a
- // truncating conversion, but any loss-of-information just increases the
- // chance of a fault negative, not a false positive.
- const subtle::Atomic32 atomic_thread_id =
- static_cast<subtle::Atomic32>(current_thread_id);
-
- return atomic_thread_id;
-}
-
-void ThreadCollisionWarner::EnterSelf() {
- // If the active thread is 0 then I'll write the current thread ID
- // if two or more threads arrive here only one will succeed to
- // write on valid_thread_id_ the current thread ID.
- subtle::Atomic32 current_thread_id = CurrentThread();
-
- int previous_value = subtle::NoBarrier_CompareAndSwap(&valid_thread_id_,
- 0,
- current_thread_id);
- if (previous_value != 0 && previous_value != current_thread_id) {
- // gotcha! a thread is trying to use the same class and that is
- // not current thread.
- asserter_->warn();
- }
-
- subtle::NoBarrier_AtomicIncrement(&counter_, 1);
-}
-
-void ThreadCollisionWarner::Enter() {
- subtle::Atomic32 current_thread_id = CurrentThread();
-
- if (subtle::NoBarrier_CompareAndSwap(&valid_thread_id_,
- 0,
- current_thread_id) != 0) {
- // gotcha! another thread is trying to use the same class.
- asserter_->warn();
- }
-
- subtle::NoBarrier_AtomicIncrement(&counter_, 1);
-}
-
-void ThreadCollisionWarner::Leave() {
- if (subtle::Barrier_AtomicIncrement(&counter_, -1) == 0) {
- subtle::NoBarrier_Store(&valid_thread_id_, 0);
- }
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/threading/thread_collision_warner.h b/security/sandbox/chromium/base/threading/thread_collision_warner.h
deleted file mode 100644
index 4699a910d..000000000
--- a/security/sandbox/chromium/base/threading/thread_collision_warner.h
+++ /dev/null
@@ -1,245 +0,0 @@
-// 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.
-
-#ifndef BASE_THREADING_THREAD_COLLISION_WARNER_H_
-#define BASE_THREADING_THREAD_COLLISION_WARNER_H_
-
-#include <memory>
-
-#include "base/atomicops.h"
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-
-// A helper class alongside macros to be used to verify assumptions about thread
-// safety of a class.
-//
-// Example: Queue implementation non thread-safe but still usable if clients
-// are synchronized somehow.
-//
-// In this case the macro DFAKE_SCOPED_LOCK has to be
-// used, it checks that if a thread is inside the push/pop then
-// noone else is still inside the pop/push
-//
-// class NonThreadSafeQueue {
-// public:
-// ...
-// void push(int) { DFAKE_SCOPED_LOCK(push_pop_); ... }
-// int pop() { DFAKE_SCOPED_LOCK(push_pop_); ... }
-// ...
-// private:
-// DFAKE_MUTEX(push_pop_);
-// };
-//
-//
-// Example: Queue implementation non thread-safe but still usable if clients
-// are synchronized somehow, it calls a method to "protect" from
-// a "protected" method
-//
-// In this case the macro DFAKE_SCOPED_RECURSIVE_LOCK
-// has to be used, it checks that if a thread is inside the push/pop
-// then noone else is still inside the pop/push
-//
-// class NonThreadSafeQueue {
-// public:
-// void push(int) {
-// DFAKE_SCOPED_LOCK(push_pop_);
-// ...
-// }
-// int pop() {
-// DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_);
-// bar();
-// ...
-// }
-// void bar() { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); ... }
-// ...
-// private:
-// DFAKE_MUTEX(push_pop_);
-// };
-//
-//
-// Example: Queue implementation not usable even if clients are synchronized,
-// so only one thread in the class life cycle can use the two members
-// push/pop.
-//
-// In this case the macro DFAKE_SCOPED_LOCK_THREAD_LOCKED pins the
-// specified
-// critical section the first time a thread enters push or pop, from
-// that time on only that thread is allowed to execute push or pop.
-//
-// class NonThreadSafeQueue {
-// public:
-// ...
-// void push(int) { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); ... }
-// int pop() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); ... }
-// ...
-// private:
-// DFAKE_MUTEX(push_pop_);
-// };
-//
-//
-// Example: Class that has to be contructed/destroyed on same thread, it has
-// a "shareable" method (with external synchronization) and a not
-// shareable method (even with external synchronization).
-//
-// In this case 3 Critical sections have to be defined
-//
-// class ExoticClass {
-// public:
-// ExoticClass() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... }
-// ~ExoticClass() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... }
-//
-// void Shareable() { DFAKE_SCOPED_LOCK(shareable_section_); ... }
-// void NotShareable() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... }
-// ...
-// private:
-// DFAKE_MUTEX(ctor_dtor_);
-// DFAKE_MUTEX(shareable_section_);
-// };
-
-
-#if !defined(NDEBUG)
-
-// Defines a class member that acts like a mutex. It is used only as a
-// verification tool.
-#define DFAKE_MUTEX(obj) \
- mutable base::ThreadCollisionWarner obj
-// Asserts the call is never called simultaneously in two threads. Used at
-// member function scope.
-#define DFAKE_SCOPED_LOCK(obj) \
- base::ThreadCollisionWarner::ScopedCheck s_check_##obj(&obj)
-// Asserts the call is never called simultaneously in two threads. Used at
-// member function scope. Same as DFAKE_SCOPED_LOCK but allows recursive locks.
-#define DFAKE_SCOPED_RECURSIVE_LOCK(obj) \
- base::ThreadCollisionWarner::ScopedRecursiveCheck sr_check_##obj(&obj)
-// Asserts the code is always executed in the same thread.
-#define DFAKE_SCOPED_LOCK_THREAD_LOCKED(obj) \
- base::ThreadCollisionWarner::Check check_##obj(&obj)
-
-#else
-
-#define DFAKE_MUTEX(obj) typedef void InternalFakeMutexType##obj
-#define DFAKE_SCOPED_LOCK(obj) ((void)0)
-#define DFAKE_SCOPED_RECURSIVE_LOCK(obj) ((void)0)
-#define DFAKE_SCOPED_LOCK_THREAD_LOCKED(obj) ((void)0)
-
-#endif
-
-namespace base {
-
-// The class ThreadCollisionWarner uses an Asserter to notify the collision
-// AsserterBase is the interfaces and DCheckAsserter is the default asserter
-// used. During the unit tests is used another class that doesn't "DCHECK"
-// in case of collision (check thread_collision_warner_unittests.cc)
-struct BASE_EXPORT AsserterBase {
- virtual ~AsserterBase() {}
- virtual void warn() = 0;
-};
-
-struct BASE_EXPORT DCheckAsserter : public AsserterBase {
- ~DCheckAsserter() override {}
- void warn() override;
-};
-
-class BASE_EXPORT ThreadCollisionWarner {
- public:
- // The parameter asserter is there only for test purpose
- explicit ThreadCollisionWarner(AsserterBase* asserter = new DCheckAsserter())
- : valid_thread_id_(0),
- counter_(0),
- asserter_(asserter) {}
-
- ~ThreadCollisionWarner() {
- delete asserter_;
- }
-
- // This class is meant to be used through the macro
- // DFAKE_SCOPED_LOCK_THREAD_LOCKED
- // it doesn't leave the critical section, as opposed to ScopedCheck,
- // because the critical section being pinned is allowed to be used only
- // from one thread
- class BASE_EXPORT Check {
- public:
- explicit Check(ThreadCollisionWarner* warner)
- : warner_(warner) {
- warner_->EnterSelf();
- }
-
- ~Check() {}
-
- private:
- ThreadCollisionWarner* warner_;
-
- DISALLOW_COPY_AND_ASSIGN(Check);
- };
-
- // This class is meant to be used through the macro
- // DFAKE_SCOPED_LOCK
- class BASE_EXPORT ScopedCheck {
- public:
- explicit ScopedCheck(ThreadCollisionWarner* warner)
- : warner_(warner) {
- warner_->Enter();
- }
-
- ~ScopedCheck() {
- warner_->Leave();
- }
-
- private:
- ThreadCollisionWarner* warner_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedCheck);
- };
-
- // This class is meant to be used through the macro
- // DFAKE_SCOPED_RECURSIVE_LOCK
- class BASE_EXPORT ScopedRecursiveCheck {
- public:
- explicit ScopedRecursiveCheck(ThreadCollisionWarner* warner)
- : warner_(warner) {
- warner_->EnterSelf();
- }
-
- ~ScopedRecursiveCheck() {
- warner_->Leave();
- }
-
- private:
- ThreadCollisionWarner* warner_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedRecursiveCheck);
- };
-
- private:
- // This method stores the current thread identifier and does a DCHECK
- // if a another thread has already done it, it is safe if same thread
- // calls this multiple time (recursion allowed).
- void EnterSelf();
-
- // Same as EnterSelf but recursion is not allowed.
- void Enter();
-
- // Removes the thread_id stored in order to allow other threads to
- // call EnterSelf or Enter.
- void Leave();
-
- // This stores the thread id that is inside the critical section, if the
- // value is 0 then no thread is inside.
- volatile subtle::Atomic32 valid_thread_id_;
-
- // Counter to trace how many time a critical section was "pinned"
- // (when allowed) in order to unpin it when counter_ reaches 0.
- volatile subtle::Atomic32 counter_;
-
- // Here only for class unit tests purpose, during the test I need to not
- // DCHECK but notify the collision with something else.
- AsserterBase* asserter_;
-
- DISALLOW_COPY_AND_ASSIGN(ThreadCollisionWarner);
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_THREAD_COLLISION_WARNER_H_
diff --git a/security/sandbox/chromium/base/threading/thread_id_name_manager.cc b/security/sandbox/chromium/base/threading/thread_id_name_manager.cc
deleted file mode 100644
index 56cfa273a..000000000
--- a/security/sandbox/chromium/base/threading/thread_id_name_manager.cc
+++ /dev/null
@@ -1,112 +0,0 @@
-// 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.
-
-#include "base/threading/thread_id_name_manager.h"
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "base/logging.h"
-#include "base/memory/singleton.h"
-#include "base/strings/string_util.h"
-
-namespace base {
-namespace {
-
-static const char kDefaultName[] = "";
-static std::string* g_default_name;
-
-}
-
-ThreadIdNameManager::ThreadIdNameManager()
- : main_process_name_(NULL),
- main_process_id_(kInvalidThreadId) {
- g_default_name = new std::string(kDefaultName);
-
- AutoLock locked(lock_);
- name_to_interned_name_[kDefaultName] = g_default_name;
-}
-
-ThreadIdNameManager::~ThreadIdNameManager() {
-}
-
-ThreadIdNameManager* ThreadIdNameManager::GetInstance() {
- return Singleton<ThreadIdNameManager,
- LeakySingletonTraits<ThreadIdNameManager> >::get();
-}
-
-const char* ThreadIdNameManager::GetDefaultInternedString() {
- return g_default_name->c_str();
-}
-
-void ThreadIdNameManager::RegisterThread(PlatformThreadHandle::Handle handle,
- PlatformThreadId id) {
- AutoLock locked(lock_);
- thread_id_to_handle_[id] = handle;
- thread_handle_to_interned_name_[handle] =
- name_to_interned_name_[kDefaultName];
-}
-
-void ThreadIdNameManager::SetName(PlatformThreadId id,
- const std::string& name) {
- AutoLock locked(lock_);
- NameToInternedNameMap::iterator iter = name_to_interned_name_.find(name);
- std::string* leaked_str = NULL;
- if (iter != name_to_interned_name_.end()) {
- leaked_str = iter->second;
- } else {
- leaked_str = new std::string(name);
- name_to_interned_name_[name] = leaked_str;
- }
-
- ThreadIdToHandleMap::iterator id_to_handle_iter =
- thread_id_to_handle_.find(id);
-
- // The main thread of a process will not be created as a Thread object which
- // means there is no PlatformThreadHandler registered.
- if (id_to_handle_iter == thread_id_to_handle_.end()) {
- main_process_name_ = leaked_str;
- main_process_id_ = id;
- return;
- }
- thread_handle_to_interned_name_[id_to_handle_iter->second] = leaked_str;
-}
-
-const char* ThreadIdNameManager::GetName(PlatformThreadId id) {
- AutoLock locked(lock_);
-
- if (id == main_process_id_)
- return main_process_name_->c_str();
-
- ThreadIdToHandleMap::iterator id_to_handle_iter =
- thread_id_to_handle_.find(id);
- if (id_to_handle_iter == thread_id_to_handle_.end())
- return name_to_interned_name_[kDefaultName]->c_str();
-
- ThreadHandleToInternedNameMap::iterator handle_to_name_iter =
- thread_handle_to_interned_name_.find(id_to_handle_iter->second);
- return handle_to_name_iter->second->c_str();
-}
-
-void ThreadIdNameManager::RemoveName(PlatformThreadHandle::Handle handle,
- PlatformThreadId id) {
- AutoLock locked(lock_);
- ThreadHandleToInternedNameMap::iterator handle_to_name_iter =
- thread_handle_to_interned_name_.find(handle);
-
- DCHECK(handle_to_name_iter != thread_handle_to_interned_name_.end());
- thread_handle_to_interned_name_.erase(handle_to_name_iter);
-
- ThreadIdToHandleMap::iterator id_to_handle_iter =
- thread_id_to_handle_.find(id);
- DCHECK((id_to_handle_iter!= thread_id_to_handle_.end()));
- // The given |id| may have been re-used by the system. Make sure the
- // mapping points to the provided |handle| before removal.
- if (id_to_handle_iter->second != handle)
- return;
-
- thread_id_to_handle_.erase(id_to_handle_iter);
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/threading/thread_id_name_manager.h b/security/sandbox/chromium/base/threading/thread_id_name_manager.h
deleted file mode 100644
index f469b605e..000000000
--- a/security/sandbox/chromium/base/threading/thread_id_name_manager.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// 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.
-
-#ifndef BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
-#define BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
-
-#include <map>
-#include <string>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/synchronization/lock.h"
-#include "base/threading/platform_thread.h"
-
-namespace base {
-
-template <typename T>
-struct DefaultSingletonTraits;
-
-class BASE_EXPORT ThreadIdNameManager {
- public:
- static ThreadIdNameManager* GetInstance();
-
- static const char* GetDefaultInternedString();
-
- // Register the mapping between a thread |id| and |handle|.
- void RegisterThread(PlatformThreadHandle::Handle handle, PlatformThreadId id);
-
- // Set the name for the given id.
- void SetName(PlatformThreadId id, const std::string& name);
-
- // Get the name for the given id.
- const char* GetName(PlatformThreadId id);
-
- // Remove the name for the given id.
- void RemoveName(PlatformThreadHandle::Handle handle, PlatformThreadId id);
-
- private:
- friend struct DefaultSingletonTraits<ThreadIdNameManager>;
-
- typedef std::map<PlatformThreadId, PlatformThreadHandle::Handle>
- ThreadIdToHandleMap;
- typedef std::map<PlatformThreadHandle::Handle, std::string*>
- ThreadHandleToInternedNameMap;
- typedef std::map<std::string, std::string*> NameToInternedNameMap;
-
- ThreadIdNameManager();
- ~ThreadIdNameManager();
-
- // lock_ protects the name_to_interned_name_, thread_id_to_handle_ and
- // thread_handle_to_interned_name_ maps.
- Lock lock_;
-
- NameToInternedNameMap name_to_interned_name_;
- ThreadIdToHandleMap thread_id_to_handle_;
- ThreadHandleToInternedNameMap thread_handle_to_interned_name_;
-
- // Treat the main process specially as there is no PlatformThreadHandle.
- std::string* main_process_name_;
- PlatformThreadId main_process_id_;
-
- DISALLOW_COPY_AND_ASSIGN(ThreadIdNameManager);
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_THREAD_ID_NAME_MANAGER_H_
diff --git a/security/sandbox/chromium/base/threading/thread_local.h b/security/sandbox/chromium/base/threading/thread_local.h
deleted file mode 100644
index f40420cd2..000000000
--- a/security/sandbox/chromium/base/threading/thread_local.h
+++ /dev/null
@@ -1,134 +0,0 @@
-// 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.
-
-// 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 wrapper 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.
-//
-// In Android, the system TLS is limited, the implementation is backed with
-// ThreadLocalStorage.
-//
-// 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_THREADING_THREAD_LOCAL_H_
-#define BASE_THREADING_THREAD_LOCAL_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/threading/thread_local_storage.h"
-#include "build/build_config.h"
-
-#if defined(OS_POSIX)
-#include <pthread.h>
-#endif
-
-namespace base {
-namespace internal {
-
-// Helper functions that abstract the cross-platform APIs. Do not use directly.
-struct BASE_EXPORT ThreadLocalPlatform {
-#if defined(OS_WIN)
- typedef unsigned long SlotType;
-#elif defined(OS_ANDROID)
- typedef ThreadLocalStorage::StaticSlot SlotType;
-#elif defined(OS_POSIX)
- 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);
-};
-
-} // namespace internal
-
-template <typename Type>
-class ThreadLocalPointer {
- public:
- ThreadLocalPointer() : slot_() {
- internal::ThreadLocalPlatform::AllocateSlot(&slot_);
- }
-
- ~ThreadLocalPointer() {
- internal::ThreadLocalPlatform::FreeSlot(slot_);
- }
-
- Type* Get() {
- return static_cast<Type*>(
- internal::ThreadLocalPlatform::GetValueFromSlot(slot_));
- }
-
- void Set(Type* ptr) {
- internal::ThreadLocalPlatform::SetValueInSlot(
- slot_, const_cast<void*>(static_cast<const void*>(ptr)));
- }
-
- private:
- typedef internal::ThreadLocalPlatform::SlotType SlotType;
-
- SlotType slot_;
-
- DISALLOW_COPY_AND_ASSIGN(ThreadLocalPointer<Type>);
-};
-
-class ThreadLocalBoolean {
- public:
- ThreadLocalBoolean() {}
- ~ThreadLocalBoolean() {}
-
- bool Get() {
- return tlp_.Get() != NULL;
- }
-
- void Set(bool val) {
- tlp_.Set(val ? this : NULL);
- }
-
- private:
- ThreadLocalPointer<void> tlp_;
-
- DISALLOW_COPY_AND_ASSIGN(ThreadLocalBoolean);
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_THREAD_LOCAL_H_
diff --git a/security/sandbox/chromium/base/threading/thread_local_posix.cc b/security/sandbox/chromium/base/threading/thread_local_posix.cc
deleted file mode 100644
index 8bc46ad19..000000000
--- a/security/sandbox/chromium/base/threading/thread_local_posix.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// 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/threading/thread_local.h"
-
-#include <pthread.h>
-
-#include "base/logging.h"
-#include "build/build_config.h"
-
-#if !defined(OS_ANDROID)
-
-namespace base {
-namespace internal {
-
-// static
-void ThreadLocalPlatform::AllocateSlot(SlotType* slot) {
- int error = pthread_key_create(slot, NULL);
- CHECK_EQ(error, 0);
-}
-
-// static
-void ThreadLocalPlatform::FreeSlot(SlotType slot) {
- int error = pthread_key_delete(slot);
- DCHECK_EQ(0, error);
-}
-
-// static
-void* ThreadLocalPlatform::GetValueFromSlot(SlotType slot) {
- return pthread_getspecific(slot);
-}
-
-// static
-void ThreadLocalPlatform::SetValueInSlot(SlotType slot, void* value) {
- int error = pthread_setspecific(slot, value);
- DCHECK_EQ(error, 0);
-}
-
-} // namespace internal
-} // namespace base
-
-#endif // !defined(OS_ANDROID)
diff --git a/security/sandbox/chromium/base/threading/thread_local_storage.h b/security/sandbox/chromium/base/threading/thread_local_storage.h
deleted file mode 100644
index 013b0aeff..000000000
--- a/security/sandbox/chromium/base/threading/thread_local_storage.h
+++ /dev/null
@@ -1,148 +0,0 @@
-// 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.
-
-#ifndef BASE_THREADING_THREAD_LOCAL_STORAGE_H_
-#define BASE_THREADING_THREAD_LOCAL_STORAGE_H_
-
-#include "base/atomicops.h"
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "build/build_config.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#elif defined(OS_POSIX)
-#include <pthread.h>
-#endif
-
-namespace base {
-
-namespace internal {
-
-// WARNING: You should *NOT* be using this class directly.
-// PlatformThreadLocalStorage is low-level abstraction to the OS's TLS
-// interface, you should instead be using ThreadLocalStorage::StaticSlot/Slot.
-class BASE_EXPORT PlatformThreadLocalStorage {
- public:
-
-#if defined(OS_WIN)
- typedef unsigned long TLSKey;
- enum : unsigned { TLS_KEY_OUT_OF_INDEXES = TLS_OUT_OF_INDEXES };
-#elif defined(OS_POSIX)
- typedef pthread_key_t TLSKey;
- // The following is a "reserved key" which is used in our generic Chromium
- // ThreadLocalStorage implementation. We expect that an OS will not return
- // such a key, but if it is returned (i.e., the OS tries to allocate it) we
- // will just request another key.
- enum { TLS_KEY_OUT_OF_INDEXES = 0x7FFFFFFF };
-#endif
-
- // The following methods need to be supported on each OS platform, so that
- // the Chromium ThreadLocalStore functionality can be constructed.
- // Chromium will use these methods to acquire a single OS slot, and then use
- // that to support a much larger number of Chromium slots (independent of the
- // OS restrictions).
- // The following returns true if it successfully is able to return an OS
- // key in |key|.
- static bool AllocTLS(TLSKey* key);
- // Note: FreeTLS() doesn't have to be called, it is fine with this leak, OS
- // might not reuse released slot, you might just reset the TLS value with
- // SetTLSValue().
- static void FreeTLS(TLSKey key);
- static void SetTLSValue(TLSKey key, void* value);
- static void* GetTLSValue(TLSKey key);
-
- // Each platform (OS implementation) is required to call this method on each
- // terminating thread when the thread is about to terminate. This method
- // will then call all registered destructors for slots in Chromium
- // ThreadLocalStorage, until there are no slot values remaining as having
- // been set on this thread.
- // Destructors may end up being called multiple times on a terminating
- // thread, as other destructors may re-set slots that were previously
- // destroyed.
-#if defined(OS_WIN)
- // Since Windows which doesn't support TLS destructor, the implementation
- // should use GetTLSValue() to retrieve the value of TLS slot.
- static void OnThreadExit();
-#elif defined(OS_POSIX)
- // |Value| is the data stored in TLS slot, The implementation can't use
- // GetTLSValue() to retrieve the value of slot as it has already been reset
- // in Posix.
- static void OnThreadExit(void* value);
-#endif
-};
-
-} // namespace internal
-
-// Wrapper for thread local storage. This class doesn't do much except provide
-// an API for portability.
-class BASE_EXPORT 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);
-
- // StaticSlot uses its own struct initializer-list style static
- // initialization, as base's LINKER_INITIALIZED requires a constructor and on
- // some compilers (notably gcc 4.4) this still ends up needing runtime
- // initialization.
- #define TLS_INITIALIZER {0}
-
- // A key representing one value stored in TLS.
- // Initialize like
- // ThreadLocalStorage::StaticSlot my_slot = TLS_INITIALIZER;
- // If you're not using a static variable, use the convenience class
- // ThreadLocalStorage::Slot (below) instead.
- struct BASE_EXPORT StaticSlot {
- // 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.
- void 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 base::subtle::Acquire_Load(&initialized_) != 0;
- }
-
- // The internals of this struct should be considered private.
- base::subtle::Atomic32 initialized_;
- int slot_;
- };
-
- // A convenience wrapper around StaticSlot with a constructor. Can be used
- // as a member variable.
- class BASE_EXPORT Slot : public StaticSlot {
- public:
- // Calls StaticSlot::Initialize().
- explicit Slot(TLSDestructorFunc destructor = NULL);
-
- private:
- using StaticSlot::initialized_;
- using StaticSlot::slot_;
-
- DISALLOW_COPY_AND_ASSIGN(Slot);
- };
-
- private:
- DISALLOW_COPY_AND_ASSIGN(ThreadLocalStorage);
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_THREAD_LOCAL_STORAGE_H_
diff --git a/security/sandbox/chromium/base/threading/thread_local_win.cc b/security/sandbox/chromium/base/threading/thread_local_win.cc
deleted file mode 100644
index 1c74e4213..000000000
--- a/security/sandbox/chromium/base/threading/thread_local_win.cc
+++ /dev/null
@@ -1,40 +0,0 @@
-// 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/threading/thread_local.h"
-
-#include <windows.h>
-
-#include "base/logging.h"
-
-namespace base {
-namespace internal {
-
-// static
-void ThreadLocalPlatform::AllocateSlot(SlotType* slot) {
- *slot = TlsAlloc();
- CHECK_NE(*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)) {
- LOG(FATAL) << "Failed to TlsSetValue().";
- }
-}
-
-} // namespace internal
-} // namespace base
diff --git a/security/sandbox/chromium/base/threading/thread_restrictions.cc b/security/sandbox/chromium/base/threading/thread_restrictions.cc
deleted file mode 100644
index 00306c5ae..000000000
--- a/security/sandbox/chromium/base/threading/thread_restrictions.cc
+++ /dev/null
@@ -1,85 +0,0 @@
-// 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.
-
-#include "base/threading/thread_restrictions.h"
-
-#if ENABLE_THREAD_RESTRICTIONS
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/threading/thread_local.h"
-
-namespace base {
-
-namespace {
-
-LazyInstance<ThreadLocalBoolean>::Leaky
- g_io_disallowed = LAZY_INSTANCE_INITIALIZER;
-
-LazyInstance<ThreadLocalBoolean>::Leaky
- g_singleton_disallowed = LAZY_INSTANCE_INITIALIZER;
-
-LazyInstance<ThreadLocalBoolean>::Leaky
- g_wait_disallowed = LAZY_INSTANCE_INITIALIZER;
-
-} // namespace
-
-// static
-bool ThreadRestrictions::SetIOAllowed(bool allowed) {
- bool previous_disallowed = g_io_disallowed.Get().Get();
- g_io_disallowed.Get().Set(!allowed);
- return !previous_disallowed;
-}
-
-// static
-void ThreadRestrictions::AssertIOAllowed() {
- if (g_io_disallowed.Get().Get()) {
- LOG(FATAL) <<
- "Function marked as IO-only was called from a thread that "
- "disallows IO! If this thread really should be allowed to "
- "make IO calls, adjust the call to "
- "base::ThreadRestrictions::SetIOAllowed() in this thread's "
- "startup.";
- }
-}
-
-// static
-bool ThreadRestrictions::SetSingletonAllowed(bool allowed) {
- bool previous_disallowed = g_singleton_disallowed.Get().Get();
- g_singleton_disallowed.Get().Set(!allowed);
- return !previous_disallowed;
-}
-
-// static
-void ThreadRestrictions::AssertSingletonAllowed() {
- if (g_singleton_disallowed.Get().Get()) {
- LOG(FATAL) << "LazyInstance/Singleton is not allowed to be used on this "
- << "thread. Most likely it's because this thread is not "
- << "joinable, so AtExitManager may have deleted the object "
- << "on shutdown, leading to a potential shutdown crash.";
- }
-}
-
-// static
-void ThreadRestrictions::DisallowWaiting() {
- g_wait_disallowed.Get().Set(true);
-}
-
-// static
-void ThreadRestrictions::AssertWaitAllowed() {
- if (g_wait_disallowed.Get().Get()) {
- LOG(FATAL) << "Waiting is not allowed to be used on this thread to prevent "
- << "jank and deadlock.";
- }
-}
-
-bool ThreadRestrictions::SetWaitAllowed(bool allowed) {
- bool previous_disallowed = g_wait_disallowed.Get().Get();
- g_wait_disallowed.Get().Set(!allowed);
- return !previous_disallowed;
-}
-
-} // namespace base
-
-#endif // ENABLE_THREAD_RESTRICTIONS
diff --git a/security/sandbox/chromium/base/threading/thread_restrictions.h b/security/sandbox/chromium/base/threading/thread_restrictions.h
deleted file mode 100644
index eec00fbb7..000000000
--- a/security/sandbox/chromium/base/threading/thread_restrictions.h
+++ /dev/null
@@ -1,266 +0,0 @@
-// 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.
-
-#ifndef BASE_THREADING_THREAD_RESTRICTIONS_H_
-#define BASE_THREADING_THREAD_RESTRICTIONS_H_
-
-#include "base/base_export.h"
-#include "base/macros.h"
-
-// See comment at top of thread_checker.h
-#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON))
-#define ENABLE_THREAD_RESTRICTIONS 1
-#else
-#define ENABLE_THREAD_RESTRICTIONS 0
-#endif
-
-class BrowserProcessImpl;
-class HistogramSynchronizer;
-class NativeBackendKWallet;
-class ScopedAllowWaitForLegacyWebViewApi;
-
-namespace cc {
-class CompletionEvent;
-class SingleThreadTaskGraphRunner;
-}
-namespace chromeos {
-class BlockingMethodCaller;
-namespace system {
-class StatisticsProviderImpl;
-}
-}
-namespace chrome_browser_net {
-class Predictor;
-}
-namespace content {
-class BrowserGpuChannelHostFactory;
-class BrowserGpuMemoryBufferManager;
-class BrowserShutdownProfileDumper;
-class BrowserTestBase;
-class GpuChannelHost;
-class NestedMessagePumpAndroid;
-class ScopedAllowWaitForAndroidLayoutTests;
-class ScopedAllowWaitForDebugURL;
-class SoftwareOutputDeviceMus;
-class TextInputClientMac;
-class RasterWorkerPool;
-} // namespace content
-namespace dbus {
-class Bus;
-}
-namespace disk_cache {
-class BackendImpl;
-class InFlightIO;
-}
-namespace gles2 {
-class CommandBufferClientImpl;
-}
-namespace mojo {
-namespace common {
-class MessagePumpMojo;
-}
-}
-namespace mus {
-class CommandBufferLocal;
-class GpuState;
-}
-namespace net {
-class NetworkChangeNotifierMac;
-namespace internal {
-class AddressTrackerLinux;
-}
-}
-
-namespace remoting {
-class AutoThread;
-}
-
-namespace ui {
-class WindowResizeHelperMac;
-}
-
-namespace views {
-class WindowManagerConnection;
-}
-
-namespace base {
-
-namespace android {
-class JavaHandlerThread;
-}
-
-class SequencedWorkerPool;
-class SimpleThread;
-class Thread;
-class ThreadTestHelper;
-
-// Certain behavior is disallowed on certain threads. ThreadRestrictions helps
-// enforce these rules. Examples of such rules:
-//
-// * Do not do blocking IO (makes the thread janky)
-// * Do not access Singleton/LazyInstance (may lead to shutdown crashes)
-//
-// Here's more about how the protection works:
-//
-// 1) If a thread should not be allowed to make IO calls, mark it:
-// base::ThreadRestrictions::SetIOAllowed(false);
-// By default, threads *are* allowed to make IO calls.
-// In Chrome browser code, IO calls should be proxied to the File thread.
-//
-// 2) If a function makes a call that will go out to disk, check whether the
-// current thread is allowed:
-// base::ThreadRestrictions::AssertIOAllowed();
-//
-//
-// Style tip: where should you put AssertIOAllowed checks? It's best
-// if you put them as close to the disk access as possible, at the
-// lowest level. This rule is simple to follow and helps catch all
-// callers. For example, if your function GoDoSomeBlockingDiskCall()
-// only calls other functions in Chrome and not fopen(), you should go
-// add the AssertIOAllowed checks in the helper functions.
-
-class BASE_EXPORT ThreadRestrictions {
- public:
- // Constructing a ScopedAllowIO temporarily allows IO for the current
- // thread. Doing this is almost certainly always incorrect.
- class BASE_EXPORT ScopedAllowIO {
- public:
- ScopedAllowIO() { previous_value_ = SetIOAllowed(true); }
- ~ScopedAllowIO() { SetIOAllowed(previous_value_); }
- private:
- // Whether IO is allowed when the ScopedAllowIO was constructed.
- bool previous_value_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedAllowIO);
- };
-
- // Constructing a ScopedAllowSingleton temporarily allows accessing for the
- // current thread. Doing this is almost always incorrect.
- class BASE_EXPORT ScopedAllowSingleton {
- public:
- ScopedAllowSingleton() { previous_value_ = SetSingletonAllowed(true); }
- ~ScopedAllowSingleton() { SetSingletonAllowed(previous_value_); }
- private:
- // Whether singleton use is allowed when the ScopedAllowSingleton was
- // constructed.
- bool previous_value_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedAllowSingleton);
- };
-
-#if ENABLE_THREAD_RESTRICTIONS
- // Set whether the current thread to make IO calls.
- // Threads start out in the *allowed* state.
- // Returns the previous value.
- static bool SetIOAllowed(bool allowed);
-
- // Check whether the current thread is allowed to make IO calls,
- // and DCHECK if not. See the block comment above the class for
- // a discussion of where to add these checks.
- static void AssertIOAllowed();
-
- // Set whether the current thread can use singletons. Returns the previous
- // value.
- static bool SetSingletonAllowed(bool allowed);
-
- // Check whether the current thread is allowed to use singletons (Singleton /
- // LazyInstance). DCHECKs if not.
- static void AssertSingletonAllowed();
-
- // Disable waiting on the current thread. Threads start out in the *allowed*
- // state. Returns the previous value.
- static void DisallowWaiting();
-
- // Check whether the current thread is allowed to wait, and DCHECK if not.
- static void AssertWaitAllowed();
-#else
- // Inline the empty definitions of these functions so that they can be
- // compiled out.
- static bool SetIOAllowed(bool allowed) { return true; }
- static void AssertIOAllowed() {}
- static bool SetSingletonAllowed(bool allowed) { return true; }
- static void AssertSingletonAllowed() {}
- static void DisallowWaiting() {}
- static void AssertWaitAllowed() {}
-#endif
-
- private:
- // DO NOT ADD ANY OTHER FRIEND STATEMENTS, talk to jam or brettw first.
- // BEGIN ALLOWED USAGE.
- friend class content::BrowserShutdownProfileDumper;
- friend class content::BrowserTestBase;
- friend class content::NestedMessagePumpAndroid;
- friend class content::ScopedAllowWaitForAndroidLayoutTests;
- friend class content::ScopedAllowWaitForDebugURL;
- friend class ::HistogramSynchronizer;
- friend class ::ScopedAllowWaitForLegacyWebViewApi;
- friend class cc::CompletionEvent;
- friend class cc::SingleThreadTaskGraphRunner;
- friend class content::RasterWorkerPool;
- friend class remoting::AutoThread;
- friend class ui::WindowResizeHelperMac;
- friend class MessagePumpDefault;
- friend class SequencedWorkerPool;
- friend class SimpleThread;
- friend class Thread;
- friend class ThreadTestHelper;
- friend class PlatformThread;
- friend class android::JavaHandlerThread;
- friend class gles2::CommandBufferClientImpl;
- friend class mojo::common::MessagePumpMojo;
- friend class mus::CommandBufferLocal;
- friend class mus::GpuState;
-
- // END ALLOWED USAGE.
- // BEGIN USAGE THAT NEEDS TO BE FIXED.
- friend class ::chromeos::BlockingMethodCaller; // http://crbug.com/125360
- friend class ::chromeos::system::StatisticsProviderImpl; // http://crbug.com/125385
- friend class chrome_browser_net::Predictor; // http://crbug.com/78451
- friend class
- content::BrowserGpuChannelHostFactory; // http://crbug.com/125248
- friend class
- content::BrowserGpuMemoryBufferManager; // http://crbug.com/420368
- friend class content::GpuChannelHost; // http://crbug.com/125264
- friend class content::TextInputClientMac; // http://crbug.com/121917
- friend class dbus::Bus; // http://crbug.com/125222
- friend class disk_cache::BackendImpl; // http://crbug.com/74623
- friend class disk_cache::InFlightIO; // http://crbug.com/74623
- friend class net::internal::AddressTrackerLinux; // http://crbug.com/125097
- friend class net::NetworkChangeNotifierMac; // http://crbug.com/125097
- friend class ::BrowserProcessImpl; // http://crbug.com/125207
- friend class ::NativeBackendKWallet; // http://crbug.com/125331
-#if !defined(OFFICIAL_BUILD)
- friend class content::SoftwareOutputDeviceMus; // Interim non-production code
-#endif
- friend class views::WindowManagerConnection;
-// END USAGE THAT NEEDS TO BE FIXED.
-
-#if ENABLE_THREAD_RESTRICTIONS
- static bool SetWaitAllowed(bool allowed);
-#else
- static bool SetWaitAllowed(bool allowed) { return true; }
-#endif
-
- // Constructing a ScopedAllowWait temporarily allows waiting on the current
- // thread. Doing this is almost always incorrect, which is why we limit who
- // can use this through friend. If you find yourself needing to use this, find
- // another way. Talk to jam or brettw.
- class BASE_EXPORT ScopedAllowWait {
- public:
- ScopedAllowWait() { previous_value_ = SetWaitAllowed(true); }
- ~ScopedAllowWait() { SetWaitAllowed(previous_value_); }
- private:
- // Whether singleton use is allowed when the ScopedAllowWait was
- // constructed.
- bool previous_value_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedAllowWait);
- };
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(ThreadRestrictions);
-};
-
-} // namespace base
-
-#endif // BASE_THREADING_THREAD_RESTRICTIONS_H_
diff --git a/security/sandbox/chromium/base/time/time.cc b/security/sandbox/chromium/base/time/time.cc
deleted file mode 100644
index 9188887e2..000000000
--- a/security/sandbox/chromium/base/time/time.cc
+++ /dev/null
@@ -1,349 +0,0 @@
-// 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.
-
-#include "base/time/time.h"
-
-#include <cmath>
-#include <ios>
-#include <limits>
-#include <ostream>
-#include <sstream>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/strings/stringprintf.h"
-#include "base/third_party/nspr/prtime.h"
-#include "build/build_config.h"
-
-namespace base {
-
-// TimeDelta ------------------------------------------------------------------
-
-// static
-TimeDelta TimeDelta::Max() {
- return TimeDelta(std::numeric_limits<int64_t>::max());
-}
-
-int TimeDelta::InDays() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<int>::max();
- }
- return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
-}
-
-int TimeDelta::InHours() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<int>::max();
- }
- return static_cast<int>(delta_ / Time::kMicrosecondsPerHour);
-}
-
-int TimeDelta::InMinutes() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<int>::max();
- }
- return static_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
-}
-
-double TimeDelta::InSecondsF() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<double>::infinity();
- }
- return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
-}
-
-int64_t TimeDelta::InSeconds() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<int64_t>::max();
- }
- return delta_ / Time::kMicrosecondsPerSecond;
-}
-
-double TimeDelta::InMillisecondsF() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<double>::infinity();
- }
- return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
-}
-
-int64_t TimeDelta::InMilliseconds() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<int64_t>::max();
- }
- return delta_ / Time::kMicrosecondsPerMillisecond;
-}
-
-int64_t TimeDelta::InMillisecondsRoundedUp() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<int64_t>::max();
- }
- return (delta_ + Time::kMicrosecondsPerMillisecond - 1) /
- Time::kMicrosecondsPerMillisecond;
-}
-
-int64_t TimeDelta::InMicroseconds() const {
- if (is_max()) {
- // Preserve max to prevent overflow.
- return std::numeric_limits<int64_t>::max();
- }
- return delta_;
-}
-
-namespace time_internal {
-
-int64_t SaturatedAdd(TimeDelta delta, int64_t value) {
- CheckedNumeric<int64_t> rv(delta.delta_);
- rv += value;
- return FromCheckedNumeric(rv);
-}
-
-int64_t SaturatedSub(TimeDelta delta, int64_t value) {
- CheckedNumeric<int64_t> rv(delta.delta_);
- rv -= value;
- return FromCheckedNumeric(rv);
-}
-
-int64_t FromCheckedNumeric(const CheckedNumeric<int64_t> value) {
- if (value.IsValid())
- return value.ValueUnsafe();
-
- // We could return max/min but we don't really expose what the maximum delta
- // is. Instead, return max/(-max), which is something that clients can reason
- // about.
- // TODO(rvargas) crbug.com/332611: don't use internal values.
- int64_t limit = std::numeric_limits<int64_t>::max();
- if (value.validity() == internal::RANGE_UNDERFLOW)
- limit = -limit;
- return value.ValueOrDefault(limit);
-}
-
-} // namespace time_internal
-
-std::ostream& operator<<(std::ostream& os, TimeDelta time_delta) {
- return os << time_delta.InSecondsF() << "s";
-}
-
-// Time -----------------------------------------------------------------------
-
-// static
-Time Time::Max() {
- return Time(std::numeric_limits<int64_t>::max());
-}
-
-// static
-Time Time::FromTimeT(time_t tt) {
- if (tt == 0)
- return Time(); // Preserve 0 so we can tell it doesn't exist.
- if (tt == std::numeric_limits<time_t>::max())
- return Max();
- return Time(kTimeTToMicrosecondsOffset) + TimeDelta::FromSeconds(tt);
-}
-
-time_t Time::ToTimeT() const {
- if (is_null())
- return 0; // Preserve 0 so we can tell it doesn't exist.
- if (is_max()) {
- // Preserve max without offset to prevent overflow.
- return std::numeric_limits<time_t>::max();
- }
- if (std::numeric_limits<int64_t>::max() - kTimeTToMicrosecondsOffset <= us_) {
- DLOG(WARNING) << "Overflow when converting base::Time with internal " <<
- "value " << us_ << " to time_t.";
- return std::numeric_limits<time_t>::max();
- }
- return (us_ - kTimeTToMicrosecondsOffset) / kMicrosecondsPerSecond;
-}
-
-// static
-Time Time::FromDoubleT(double dt) {
- if (dt == 0 || std::isnan(dt))
- return Time(); // Preserve 0 so we can tell it doesn't exist.
- return Time(kTimeTToMicrosecondsOffset) + TimeDelta::FromSecondsD(dt);
-}
-
-double Time::ToDoubleT() const {
- if (is_null())
- return 0; // Preserve 0 so we can tell it doesn't exist.
- if (is_max()) {
- // Preserve max without offset to prevent overflow.
- return std::numeric_limits<double>::infinity();
- }
- return (static_cast<double>(us_ - kTimeTToMicrosecondsOffset) /
- static_cast<double>(kMicrosecondsPerSecond));
-}
-
-#if defined(OS_POSIX)
-// static
-Time Time::FromTimeSpec(const timespec& ts) {
- return FromDoubleT(ts.tv_sec +
- static_cast<double>(ts.tv_nsec) /
- base::Time::kNanosecondsPerSecond);
-}
-#endif
-
-// static
-Time Time::FromJsTime(double ms_since_epoch) {
- // The epoch is a valid time, so this constructor doesn't interpret
- // 0 as the null time.
- return Time(kTimeTToMicrosecondsOffset) +
- TimeDelta::FromMillisecondsD(ms_since_epoch);
-}
-
-double Time::ToJsTime() const {
- if (is_null()) {
- // Preserve 0 so the invalid result doesn't depend on the platform.
- return 0;
- }
- if (is_max()) {
- // Preserve max without offset to prevent overflow.
- return std::numeric_limits<double>::infinity();
- }
- return (static_cast<double>(us_ - kTimeTToMicrosecondsOffset) /
- kMicrosecondsPerMillisecond);
-}
-
-int64_t Time::ToJavaTime() const {
- if (is_null()) {
- // Preserve 0 so the invalid result doesn't depend on the platform.
- return 0;
- }
- if (is_max()) {
- // Preserve max without offset to prevent overflow.
- return std::numeric_limits<int64_t>::max();
- }
- return ((us_ - kTimeTToMicrosecondsOffset) /
- kMicrosecondsPerMillisecond);
-}
-
-// static
-Time Time::UnixEpoch() {
- Time time;
- time.us_ = kTimeTToMicrosecondsOffset;
- return time;
-}
-
-Time Time::LocalMidnight() const {
- Exploded exploded;
- LocalExplode(&exploded);
- exploded.hour = 0;
- exploded.minute = 0;
- exploded.second = 0;
- exploded.millisecond = 0;
- return FromLocalExploded(exploded);
-}
-
-#if !defined(MOZ_SANDBOX)
-// static
-bool Time::FromStringInternal(const char* time_string,
- bool is_local,
- Time* parsed_time) {
- DCHECK((time_string != NULL) && (parsed_time != NULL));
-
- if (time_string[0] == '\0')
- return false;
-
- PRTime result_time = 0;
- PRStatus result = PR_ParseTimeString(time_string,
- is_local ? PR_FALSE : PR_TRUE,
- &result_time);
- if (PR_SUCCESS != result)
- return false;
-
- result_time += kTimeTToMicrosecondsOffset;
- *parsed_time = Time(result_time);
- return true;
-}
-#endif
-
-std::ostream& operator<<(std::ostream& os, Time time) {
- Time::Exploded exploded;
- time.UTCExplode(&exploded);
- // Use StringPrintf because iostreams formatting is painful.
- return os << StringPrintf("%04d-%02d-%02d %02d:%02d:%02d.%03d UTC",
- exploded.year,
- exploded.month,
- exploded.day_of_month,
- exploded.hour,
- exploded.minute,
- exploded.second,
- exploded.millisecond);
-}
-
-// Local helper class to hold the conversion from Time to TickTime at the
-// time of the Unix epoch.
-class UnixEpochSingleton {
- public:
- UnixEpochSingleton()
- : unix_epoch_(TimeTicks::Now() - (Time::Now() - Time::UnixEpoch())) {}
-
- TimeTicks unix_epoch() const { return unix_epoch_; }
-
- private:
- const TimeTicks unix_epoch_;
-
- DISALLOW_COPY_AND_ASSIGN(UnixEpochSingleton);
-};
-
-static LazyInstance<UnixEpochSingleton>::Leaky
- leaky_unix_epoch_singleton_instance = LAZY_INSTANCE_INITIALIZER;
-
-// Static
-TimeTicks TimeTicks::UnixEpoch() {
- return leaky_unix_epoch_singleton_instance.Get().unix_epoch();
-}
-
-TimeTicks TimeTicks::SnappedToNextTick(TimeTicks tick_phase,
- TimeDelta tick_interval) const {
- // |interval_offset| is the offset from |this| to the next multiple of
- // |tick_interval| after |tick_phase|, possibly negative if in the past.
- TimeDelta interval_offset = (tick_phase - *this) % tick_interval;
- // If |this| is exactly on the interval (i.e. offset==0), don't adjust.
- // Otherwise, if |tick_phase| was in the past, adjust forward to the next
- // tick after |this|.
- if (!interval_offset.is_zero() && tick_phase < *this)
- interval_offset += tick_interval;
- return *this + interval_offset;
-}
-
-std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks) {
- // This function formats a TimeTicks object as "bogo-microseconds".
- // The origin and granularity of the count are platform-specific, and may very
- // from run to run. Although bogo-microseconds usually roughly correspond to
- // real microseconds, the only real guarantee is that the number never goes
- // down during a single run.
- const TimeDelta as_time_delta = time_ticks - TimeTicks();
- return os << as_time_delta.InMicroseconds() << " bogo-microseconds";
-}
-
-std::ostream& operator<<(std::ostream& os, ThreadTicks thread_ticks) {
- const TimeDelta as_time_delta = thread_ticks - ThreadTicks();
- return os << as_time_delta.InMicroseconds() << " bogo-thread-microseconds";
-}
-
-// Time::Exploded -------------------------------------------------------------
-
-inline bool is_in_range(int value, int lo, int hi) {
- return lo <= value && value <= hi;
-}
-
-bool Time::Exploded::HasValidValues() const {
- return is_in_range(month, 1, 12) &&
- is_in_range(day_of_week, 0, 6) &&
- is_in_range(day_of_month, 1, 31) &&
- is_in_range(hour, 0, 23) &&
- is_in_range(minute, 0, 59) &&
- is_in_range(second, 0, 60) &&
- is_in_range(millisecond, 0, 999);
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/time/time.h b/security/sandbox/chromium/base/time/time.h
deleted file mode 100644
index ea19d7ed9..000000000
--- a/security/sandbox/chromium/base/time/time.h
+++ /dev/null
@@ -1,768 +0,0 @@
-// 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.
-
-// Time represents an absolute point in coordinated universal time (UTC),
-// internally represented as microseconds (s/1,000,000) since the Windows epoch
-// (1601-01-01 00:00:00 UTC). System-dependent clock interface routines are
-// defined in time_PLATFORM.cc. Note that values for Time may skew and jump
-// around as the operating system makes adjustments to synchronize (e.g., with
-// NTP servers). Thus, client code that uses the Time class must account for
-// this.
-//
-// TimeDelta represents a duration of time, internally represented in
-// microseconds.
-//
-// TimeTicks and ThreadTicks represent an abstract time that is most of the time
-// incrementing, for use in measuring time durations. Internally, they are
-// represented in microseconds. They can not be converted to a human-readable
-// time, but are guaranteed not to decrease (unlike the Time class). Note that
-// TimeTicks may "stand still" (e.g., if the computer is suspended), and
-// ThreadTicks will "stand still" whenever the thread has been de-scheduled by
-// the operating system.
-//
-// All time classes are copyable, assignable, and occupy 64-bits per
-// instance. Thus, they can be efficiently passed by-value (as opposed to
-// by-reference).
-//
-// Definitions of operator<< are provided to make these types work with
-// DCHECK_EQ() and other log macros. For human-readable formatting, see
-// "base/i18n/time_formatting.h".
-//
-// So many choices! Which time class should you use? Examples:
-//
-// Time: Interpreting the wall-clock time provided by a remote
-// system. Detecting whether cached resources have
-// expired. Providing the user with a display of the current date
-// and time. Determining the amount of time between events across
-// re-boots of the machine.
-//
-// TimeTicks: Tracking the amount of time a task runs. Executing delayed
-// tasks at the right time. Computing presentation timestamps.
-// Synchronizing audio and video using TimeTicks as a common
-// reference clock (lip-sync). Measuring network round-trip
-// latency.
-//
-// ThreadTicks: Benchmarking how long the current thread has been doing actual
-// work.
-
-#ifndef BASE_TIME_TIME_H_
-#define BASE_TIME_TIME_H_
-
-#include <stdint.h>
-#include <time.h>
-
-#include <iosfwd>
-#include <limits>
-
-#include "base/base_export.h"
-#include "base/numerics/safe_math.h"
-#include "build/build_config.h"
-
-#if defined(OS_MACOSX)
-#include <CoreFoundation/CoreFoundation.h>
-// Avoid Mac system header macro leak.
-#undef TYPE_BOOL
-#endif
-
-#if defined(OS_POSIX)
-#include <unistd.h>
-#include <sys/time.h>
-#endif
-
-#if defined(OS_WIN)
-// For FILETIME in FromFileTime, until it moves to a new converter class.
-// See TODO(iyengar) below.
-#include <windows.h>
-
-#include "base/gtest_prod_util.h"
-#endif
-
-namespace base {
-
-class TimeDelta;
-
-// The functions in the time_internal namespace are meant to be used only by the
-// time classes and functions. Please use the math operators defined in the
-// time classes instead.
-namespace time_internal {
-
-// Add or subtract |value| from a TimeDelta. The int64_t argument and return
-// value are in terms of a microsecond timebase.
-BASE_EXPORT int64_t SaturatedAdd(TimeDelta delta, int64_t value);
-BASE_EXPORT int64_t SaturatedSub(TimeDelta delta, int64_t value);
-
-// Clamp |value| on overflow and underflow conditions. The int64_t argument and
-// return value are in terms of a microsecond timebase.
-BASE_EXPORT int64_t FromCheckedNumeric(const CheckedNumeric<int64_t> value);
-
-} // namespace time_internal
-
-// TimeDelta ------------------------------------------------------------------
-
-class BASE_EXPORT TimeDelta {
- public:
- TimeDelta() : delta_(0) {
- }
-
- // Converts units of time to TimeDeltas.
- static TimeDelta FromDays(int days);
- static TimeDelta FromHours(int hours);
- static TimeDelta FromMinutes(int minutes);
- static TimeDelta FromSeconds(int64_t secs);
- static TimeDelta FromMilliseconds(int64_t ms);
- static TimeDelta FromSecondsD(double secs);
- static TimeDelta FromMillisecondsD(double ms);
- static TimeDelta FromMicroseconds(int64_t us);
-#if defined(OS_WIN)
- static TimeDelta FromQPCValue(LONGLONG qpc_value);
-#endif
-
- // Converts an integer value representing TimeDelta to a class. This is used
- // when deserializing a |TimeDelta| 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 TimeDelta FromInternalValue(int64_t delta) { return TimeDelta(delta); }
-
- // Returns the maximum time delta, which should be greater than any reasonable
- // time delta we might compare it to. Adding or subtracting the maximum time
- // delta to a time or another time delta has an undefined result.
- static TimeDelta Max();
-
- // 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.
- // For serializing, use FromInternalValue to reconstitute.
- int64_t ToInternalValue() const { return delta_; }
-
- // Returns the magnitude (absolute value) of this TimeDelta.
- TimeDelta magnitude() const {
- // Some toolchains provide an incomplete C++11 implementation and lack an
- // int64_t overload for std::abs(). The following is a simple branchless
- // implementation:
- const int64_t mask = delta_ >> (sizeof(delta_) * 8 - 1);
- return TimeDelta((delta_ + mask) ^ mask);
- }
-
- // Returns true if the time delta is zero.
- bool is_zero() const {
- return delta_ == 0;
- }
-
- // Returns true if the time delta is the maximum time delta.
- bool is_max() const { return delta_ == std::numeric_limits<int64_t>::max(); }
-
-#if defined(OS_POSIX)
- struct timespec ToTimeSpec() const;
-#endif
-
- // Returns the time delta in some unit. The F versions return a floating
- // point value, the "regular" versions return a rounded-down value.
- //
- // InMillisecondsRoundedUp() instead returns an integer that is rounded up
- // to the next full millisecond.
- 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 InMillisecondsRoundedUp() 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(time_internal::SaturatedAdd(*this, other.delta_));
- }
- TimeDelta operator-(TimeDelta other) const {
- return TimeDelta(time_internal::SaturatedSub(*this, other.delta_));
- }
-
- TimeDelta& operator+=(TimeDelta other) {
- return *this = (*this + other);
- }
- TimeDelta& operator-=(TimeDelta other) {
- return *this = (*this - other);
- }
- TimeDelta operator-() const {
- return TimeDelta(-delta_);
- }
-
- // Computations with numeric types.
- template<typename T>
- TimeDelta operator*(T a) const {
- CheckedNumeric<int64_t> rv(delta_);
- rv *= a;
- return TimeDelta(time_internal::FromCheckedNumeric(rv));
- }
- template<typename T>
- TimeDelta operator/(T a) const {
- CheckedNumeric<int64_t> rv(delta_);
- rv /= a;
- return TimeDelta(time_internal::FromCheckedNumeric(rv));
- }
- template<typename T>
- TimeDelta& operator*=(T a) {
- return *this = (*this * a);
- }
- template<typename T>
- TimeDelta& operator/=(T a) {
- return *this = (*this / a);
- }
-
- int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; }
- TimeDelta operator%(TimeDelta a) const {
- return TimeDelta(delta_ % a.delta_);
- }
-
- // 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 int64_t time_internal::SaturatedAdd(TimeDelta delta, int64_t value);
- friend int64_t time_internal::SaturatedSub(TimeDelta delta, int64_t value);
-
- // 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) {}
-
- // Private method to build a delta from a double.
- static TimeDelta FromDouble(double value);
-
- // Delta in microseconds.
- int64_t delta_;
-};
-
-template<typename T>
-inline TimeDelta operator*(T a, TimeDelta td) {
- return td * a;
-}
-
-// For logging use only.
-BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeDelta time_delta);
-
-// Do not reference the time_internal::TimeBase template class directly. Please
-// use one of the time subclasses instead, and only reference the public
-// TimeBase members via those classes.
-namespace time_internal {
-
-// TimeBase--------------------------------------------------------------------
-
-// Provides value storage and comparison/math operations common to all time
-// classes. Each subclass provides for strong type-checking to ensure
-// semantically meaningful comparison/math of time values from the same clock
-// source or timeline.
-template<class TimeClass>
-class TimeBase {
- public:
- static const int64_t kHoursPerDay = 24;
- static const int64_t kMillisecondsPerSecond = 1000;
- static const int64_t kMillisecondsPerDay =
- kMillisecondsPerSecond * 60 * 60 * kHoursPerDay;
- 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 * kHoursPerDay;
- static const int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
- static const int64_t kNanosecondsPerMicrosecond = 1000;
- static const int64_t kNanosecondsPerSecond =
- kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
-
- // Returns true if this object has not been initialized.
- //
- // Warning: Be careful when writing code that performs math on time values,
- // since it's possible to produce a valid "zero" result that should not be
- // interpreted as a "null" value.
- bool is_null() const {
- return us_ == 0;
- }
-
- // Returns true if this object represents the maximum time.
- bool is_max() const { return us_ == std::numeric_limits<int64_t>::max(); }
-
- // For serializing only. 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_; }
-
- TimeClass& operator=(TimeClass other) {
- us_ = other.us_;
- return *(static_cast<TimeClass*>(this));
- }
-
- // Compute the difference between two times.
- TimeDelta operator-(TimeClass other) const {
- return TimeDelta::FromMicroseconds(us_ - other.us_);
- }
-
- // Return a new time modified by some delta.
- TimeClass operator+(TimeDelta delta) const {
- return TimeClass(time_internal::SaturatedAdd(delta, us_));
- }
- TimeClass operator-(TimeDelta delta) const {
- return TimeClass(-time_internal::SaturatedSub(delta, us_));
- }
-
- // Modify by some time delta.
- TimeClass& operator+=(TimeDelta delta) {
- return static_cast<TimeClass&>(*this = (*this + delta));
- }
- TimeClass& operator-=(TimeDelta delta) {
- return static_cast<TimeClass&>(*this = (*this - delta));
- }
-
- // Comparison operators
- bool operator==(TimeClass other) const {
- return us_ == other.us_;
- }
- bool operator!=(TimeClass other) const {
- return us_ != other.us_;
- }
- bool operator<(TimeClass other) const {
- return us_ < other.us_;
- }
- bool operator<=(TimeClass other) const {
- return us_ <= other.us_;
- }
- bool operator>(TimeClass other) const {
- return us_ > other.us_;
- }
- bool operator>=(TimeClass other) const {
- return us_ >= other.us_;
- }
-
- // Converts an integer value representing TimeClass to a class. This is used
- // when deserializing a |TimeClass| 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 TimeClass FromInternalValue(int64_t us) { return TimeClass(us); }
-
- protected:
- explicit TimeBase(int64_t us) : us_(us) {}
-
- // Time value in a microsecond timebase.
- int64_t us_;
-};
-
-} // namespace time_internal
-
-template<class TimeClass>
-inline TimeClass operator+(TimeDelta delta, TimeClass t) {
- return t + delta;
-}
-
-// Time -----------------------------------------------------------------------
-
-// Represents a wall clock time in UTC. Values are not guaranteed to be
-// monotonically non-decreasing and are subject to large amounts of skew.
-class BASE_EXPORT Time : public time_internal::TimeBase<Time> {
- public:
- // The representation of Jan 1, 1970 UTC in microseconds since the
- // platform-dependent epoch.
- static const int64_t kTimeTToMicrosecondsOffset;
-
-#if !defined(OS_WIN)
- // On Mac & Linux, this value is the delta from the Windows epoch of 1601 to
- // the Posix delta of 1970. This is used for migrating between the old
- // 1970-based epochs to the new 1601-based ones. It should be removed from
- // this global header and put in the platform-specific ones when we remove the
- // migration code.
- static const int64_t kWindowsEpochDeltaMicroseconds;
-#else
- // To avoid overflow in QPC to Microseconds calculations, since we multiply
- // by kMicrosecondsPerSecond, then the QPC value should not exceed
- // (2^63 - 1) / 1E6. If it exceeds that threshold, we divide then multiply.
- enum : int64_t{kQPCOverflowThreshold = 0x8637BD05AF7};
-#endif
-
- // 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 BASE_EXPORT Exploded {
- int year; // Four digit year "2007"
- int month; // 1-based month (values 1 = January, etc.)
- int day_of_week; // 0-based day of week (0 = Sunday, etc.)
- int day_of_month; // 1-based day of month (1-31)
- int hour; // Hour within the current day (0-23)
- int minute; // Minute within the current hour (0-59)
- int 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)
-
- // A cursory test for whether the data members are within their
- // respective ranges. A 'true' return value does not guarantee the
- // Exploded value can be successfully converted to a Time value.
- bool HasValidValues() const;
- };
-
- // Contains the NULL time. Use Time::Now() to get the current time.
- Time() : TimeBase(0) {
- }
-
- // Returns the time for epoch in Unix-like system (Jan 1, 1970).
- static Time UnixEpoch();
-
- // 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 maximum time, which should be greater than any reasonable time
- // with which we might compare it.
- static Time Max();
-
- // 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.
- // Because WebKit initializes double time value to 0 to indicate "not
- // initialized", we map it to empty Time object that also means "not
- // initialized".
- static Time FromDoubleT(double dt);
- double ToDoubleT() const;
-
-#if defined(OS_POSIX)
- // Converts the timespec structure to time. MacOS X 10.8.3 (and tentatively,
- // earlier versions) will have the |ts|'s tv_nsec component zeroed out,
- // having a 1 second resolution, which agrees with
- // https://developer.apple.com/legacy/library/#technotes/tn/tn1150.html#HFSPlusDates.
- static Time FromTimeSpec(const timespec& ts);
-#endif
-
- // Converts to/from the Javascript convention for times, a number of
- // milliseconds since the epoch:
- // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime.
- static Time FromJsTime(double ms_since_epoch);
- double ToJsTime() const;
-
- // Converts to Java convention for times, a number of
- // milliseconds since the epoch.
- int64_t ToJavaTime() const;
-
-#if defined(OS_POSIX)
- static Time FromTimeVal(struct timeval t);
- struct timeval ToTimeVal() const;
-#endif
-
-#if defined(OS_MACOSX)
- static Time FromCFAbsoluteTime(CFAbsoluteTime t);
- CFAbsoluteTime ToCFAbsoluteTime() const;
-#endif
-
-#if defined(OS_WIN)
- static Time FromFileTime(FILETIME ft);
- FILETIME ToFileTime() const;
-
- // The minimum time of a low resolution timer. This is basically a windows
- // constant of ~15.6ms. While it does vary on some older OS versions, we'll
- // treat it as static across all windows versions.
- static const int kMinLowResolutionThresholdMs = 16;
-
- // Enable or disable Windows high resolution timer.
- static void EnableHighResolutionTimer(bool enable);
-
- // Activates or deactivates the high resolution timer based on the |activate|
- // flag. If the HighResolutionTimer is not Enabled (see
- // EnableHighResolutionTimer), this function will return false. Otherwise
- // returns true. Each successful activate call must be paired with a
- // subsequent deactivate call.
- // All callers to activate the high resolution timer must eventually call
- // this function to deactivate the high resolution timer.
- static bool ActivateHighResolutionTimer(bool activate);
-
- // Returns true if the high resolution timer is both enabled and activated.
- // This is provided for testing only, and is not tracked in a thread-safe
- // way.
- static bool IsHighResolutionTimerInUse();
-#endif
-
- // 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);
- }
-
-#if !defined(MOZ_SANDBOX)
- // 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, FromString assumes local time and FromUTCString
- // assumes UTC. A timezone that cannot be parsed (e.g. "UTC" which is not
- // specified in RFC822) is treated as if the timezone is not specified.
- // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
- // a new time converter class.
- static bool FromString(const char* time_string, Time* parsed_time) {
- return FromStringInternal(time_string, true, parsed_time);
- }
- static bool FromUTCString(const char* time_string, Time* parsed_time) {
- return FromStringInternal(time_string, false, parsed_time);
- }
-#endif
-
- // 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;
-
- private:
- friend class time_internal::TimeBase<Time>;
-
- explicit Time(int64_t us) : TimeBase(us) {}
-
- // 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);
-
-#if !defined(MOZ_SANDBOX)
- // 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, local time |is_local = true| or
- // UTC |is_local = false| is assumed. A timezone that cannot be parsed
- // (e.g. "UTC" which is not specified in RFC822) is treated as if the
- // timezone is not specified.
- static bool FromStringInternal(const char* time_string,
- bool is_local,
- Time* parsed_time);
-#endif
-};
-
-// Inline the TimeDelta factory methods, for fast TimeDelta construction.
-
-// static
-inline TimeDelta TimeDelta::FromDays(int days) {
- if (days == std::numeric_limits<int>::max())
- return Max();
- return TimeDelta(days * Time::kMicrosecondsPerDay);
-}
-
-// static
-inline TimeDelta TimeDelta::FromHours(int hours) {
- if (hours == std::numeric_limits<int>::max())
- return Max();
- return TimeDelta(hours * Time::kMicrosecondsPerHour);
-}
-
-// static
-inline TimeDelta TimeDelta::FromMinutes(int minutes) {
- if (minutes == std::numeric_limits<int>::max())
- return Max();
- 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::FromSecondsD(double secs) {
- return FromDouble(secs * Time::kMicrosecondsPerSecond);
-}
-
-// static
-inline TimeDelta TimeDelta::FromMillisecondsD(double ms) {
- return FromDouble(ms * Time::kMicrosecondsPerMillisecond);
-}
-
-// static
-inline TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
- return TimeDelta(us);
-}
-
-// static
-inline TimeDelta TimeDelta::FromDouble(double value) {
- double max_magnitude = std::numeric_limits<int64_t>::max();
- TimeDelta delta = TimeDelta(static_cast<int64_t>(value));
- if (value > max_magnitude)
- delta = Max();
- else if (value < -max_magnitude)
- delta = -Max();
- return delta;
-}
-
-// For logging use only.
-BASE_EXPORT std::ostream& operator<<(std::ostream& os, Time time);
-
-// TimeTicks ------------------------------------------------------------------
-
-// Represents monotonically non-decreasing clock time.
-class BASE_EXPORT TimeTicks : public time_internal::TimeBase<TimeTicks> {
- public:
- TimeTicks() : TimeBase(0) {
- }
-
- // Platform-dependent tick count representing "right now." When
- // IsHighResolution() returns false, the resolution of the clock could be
- // as coarse as ~15.6ms. Otherwise, the resolution should be no worse than one
- // microsecond.
- static TimeTicks Now();
-
- // Returns true if the high resolution clock is working on this system and
- // Now() will return high resolution values. Note that, on systems where the
- // high resolution clock works but is deemed inefficient, the low resolution
- // clock will be used instead.
- static bool IsHighResolution();
-
-#if defined(OS_WIN)
- // Translates an absolute QPC timestamp into a TimeTicks value. The returned
- // value has the same origin as Now(). Do NOT attempt to use this if
- // IsHighResolution() returns false.
- static TimeTicks FromQPCValue(LONGLONG qpc_value);
-#endif
-
- // Get an estimate of the TimeTick value at the time of the UnixEpoch. Because
- // Time and TimeTicks respond differently to user-set time and NTP
- // adjustments, this number is only an estimate. Nevertheless, this can be
- // useful when you need to relate the value of TimeTicks to a real time and
- // date. Note: Upon first invocation, this function takes a snapshot of the
- // realtime clock to establish a reference point. This function will return
- // the same value for the duration of the application, but will be different
- // in future application runs.
- static TimeTicks UnixEpoch();
-
- // Returns |this| snapped to the next tick, given a |tick_phase| and
- // repeating |tick_interval| in both directions. |this| may be before,
- // after, or equal to the |tick_phase|.
- TimeTicks SnappedToNextTick(TimeTicks tick_phase,
- TimeDelta tick_interval) const;
-
-#if defined(OS_WIN)
- protected:
- typedef DWORD (*TickFunctionType)(void);
- static TickFunctionType SetMockTickFunction(TickFunctionType ticker);
-#endif
-
- private:
- friend class time_internal::TimeBase<TimeTicks>;
-
- // Please use Now() to create a new object. This is for internal use
- // and testing.
- explicit TimeTicks(int64_t us) : TimeBase(us) {}
-};
-
-// For logging use only.
-BASE_EXPORT std::ostream& operator<<(std::ostream& os, TimeTicks time_ticks);
-
-// ThreadTicks ----------------------------------------------------------------
-
-// Represents a clock, specific to a particular thread, than runs only while the
-// thread is running.
-class BASE_EXPORT ThreadTicks : public time_internal::TimeBase<ThreadTicks> {
- public:
- ThreadTicks() : TimeBase(0) {
- }
-
- // Returns true if ThreadTicks::Now() is supported on this system.
- static bool IsSupported() {
-#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
- (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
- return true;
-#elif defined(OS_WIN)
- return IsSupportedWin();
-#else
- return false;
-#endif
- }
-
- // Waits until the initialization is completed. Needs to be guarded with a
- // call to IsSupported().
- static void WaitUntilInitialized() {
-#if defined(OS_WIN)
- WaitUntilInitializedWin();
-#endif
- }
-
- // Returns thread-specific CPU-time on systems that support this feature.
- // Needs to be guarded with a call to IsSupported(). Use this timer
- // to (approximately) measure how much time the calling thread spent doing
- // actual work vs. being de-scheduled. May return bogus results if the thread
- // migrates to another CPU between two calls. Returns an empty ThreadTicks
- // object until the initialization is completed. If a clock reading is
- // absolutely needed, call WaitUntilInitialized() before this method.
- static ThreadTicks Now();
-
- private:
- friend class time_internal::TimeBase<ThreadTicks>;
-
- // Please use Now() to create a new object. This is for internal use
- // and testing.
- explicit ThreadTicks(int64_t us) : TimeBase(us) {}
-
-#if defined(OS_WIN)
- FRIEND_TEST_ALL_PREFIXES(TimeTicks, TSCTicksPerSecond);
-
- // Returns the frequency of the TSC in ticks per second, or 0 if it hasn't
- // been measured yet. Needs to be guarded with a call to IsSupported().
- // This method is declared here rather than in the anonymous namespace to
- // allow testing.
- static double TSCTicksPerSecond();
-
- static bool IsSupportedWin();
- static void WaitUntilInitializedWin();
-#endif
-};
-
-// For logging use only.
-BASE_EXPORT std::ostream& operator<<(std::ostream& os, ThreadTicks time_ticks);
-
-} // namespace base
-
-#endif // BASE_TIME_TIME_H_
diff --git a/security/sandbox/chromium/base/time/time_posix.cc b/security/sandbox/chromium/base/time/time_posix.cc
deleted file mode 100644
index 4aadee618..000000000
--- a/security/sandbox/chromium/base/time/time_posix.cc
+++ /dev/null
@@ -1,363 +0,0 @@
-// 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.
-
-#include "base/time/time.h"
-
-#include <stdint.h>
-#include <sys/time.h>
-#include <time.h>
-#if defined(OS_ANDROID) && !defined(__LP64__)
-#include <time64.h>
-#endif
-#include <unistd.h>
-
-#include <limits>
-#include <ostream>
-
-#include "base/logging.h"
-#include "build/build_config.h"
-
-#if defined(OS_ANDROID)
-#include "base/os_compat_android.h"
-#elif defined(OS_NACL)
-#include "base/os_compat_nacl.h"
-#endif
-
-#if !defined(OS_MACOSX)
-#include "base/lazy_instance.h"
-#include "base/synchronization/lock.h"
-#endif
-
-namespace {
-
-#if !defined(OS_MACOSX)
-// This prevents a crash on traversing the environment global and looking up
-// the 'TZ' variable in libc. See: crbug.com/390567.
-base::LazyInstance<base::Lock>::Leaky
- g_sys_time_to_time_struct_lock = LAZY_INSTANCE_INITIALIZER;
-
-// Define a system-specific SysTime that wraps either to a time_t or
-// a time64_t depending on the host system, and associated convertion.
-// See crbug.com/162007
-#if defined(OS_ANDROID) && !defined(__LP64__)
-typedef time64_t SysTime;
-
-SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
- base::AutoLock locked(g_sys_time_to_time_struct_lock.Get());
- if (is_local)
- return mktime64(timestruct);
- else
- return timegm64(timestruct);
-}
-
-void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
- base::AutoLock locked(g_sys_time_to_time_struct_lock.Get());
- if (is_local)
- localtime64_r(&t, timestruct);
- else
- gmtime64_r(&t, timestruct);
-}
-
-#else // OS_ANDROID && !__LP64__
-typedef time_t SysTime;
-
-SysTime SysTimeFromTimeStruct(struct tm* timestruct, bool is_local) {
- base::AutoLock locked(g_sys_time_to_time_struct_lock.Get());
- if (is_local)
- return mktime(timestruct);
- else
- return timegm(timestruct);
-}
-
-void SysTimeToTimeStruct(SysTime t, struct tm* timestruct, bool is_local) {
- base::AutoLock locked(g_sys_time_to_time_struct_lock.Get());
- if (is_local)
- localtime_r(&t, timestruct);
- else
- gmtime_r(&t, timestruct);
-}
-#endif // OS_ANDROID
-
-int64_t ConvertTimespecToMicros(const struct timespec& ts) {
- base::CheckedNumeric<int64_t> result(ts.tv_sec);
- result *= base::Time::kMicrosecondsPerSecond;
- result += (ts.tv_nsec / base::Time::kNanosecondsPerMicrosecond);
- return result.ValueOrDie();
-}
-
-// Helper function to get results from clock_gettime() and convert to a
-// microsecond timebase. Minimum requirement is MONOTONIC_CLOCK to be supported
-// on the system. FreeBSD 6 has CLOCK_MONOTONIC but defines
-// _POSIX_MONOTONIC_CLOCK to -1.
-#if (defined(OS_POSIX) && \
- defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0) || \
- defined(OS_BSD) || defined(OS_ANDROID)
-int64_t ClockNow(clockid_t clk_id) {
- struct timespec ts;
- if (clock_gettime(clk_id, &ts) != 0) {
- NOTREACHED() << "clock_gettime(" << clk_id << ") failed.";
- return 0;
- }
- return ConvertTimespecToMicros(ts);
-}
-#else // _POSIX_MONOTONIC_CLOCK
-#error No usable tick clock function on this platform.
-#endif // _POSIX_MONOTONIC_CLOCK
-#endif // !defined(OS_MACOSX)
-
-} // namespace
-
-namespace base {
-
-struct timespec TimeDelta::ToTimeSpec() const {
- int64_t microseconds = InMicroseconds();
- time_t seconds = 0;
- if (microseconds >= Time::kMicrosecondsPerSecond) {
- seconds = InSeconds();
- microseconds -= seconds * Time::kMicrosecondsPerSecond;
- }
- struct timespec result =
- {seconds,
- static_cast<long>(microseconds * Time::kNanosecondsPerMicrosecond)};
- return result;
-}
-
-#if !defined(OS_MACOSX)
-// 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 -----------------------------------------------------------------------
-
-// Windows uses a Gregorian epoch of 1601. We need to match this internally
-// so that our time representations match across all platforms. See bug 14734.
-// irb(main):010:0> Time.at(0).getutc()
-// => Thu Jan 01 00:00:00 UTC 1970
-// irb(main):011:0> Time.at(-11644473600).getutc()
-// => Mon Jan 01 00:00:00 UTC 1601
-static const int64_t kWindowsEpochDeltaSeconds = INT64_C(11644473600);
-
-// static
-const int64_t Time::kWindowsEpochDeltaMicroseconds =
- kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond;
-
-// Some functions in time.cc use time_t directly, so we provide an offset
-// to convert from time_t (Unix epoch) and internal (Windows epoch).
-// static
-const int64_t Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds;
-
-// 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";
- PLOG(ERROR) << "Call to gettimeofday failed.";
- // Return null instead of uninitialized |tv| value, which contains random
- // garbage data. This may result in the crash seen in crbug.com/147570.
- return Time();
- }
- // Combine seconds and microseconds in a 64-bit field containing microseconds
- // since the epoch. That's enough for nearly 600 centuries. Adjust from
- // Unix (1970) to Windows (1601) epoch.
- return Time((tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec) +
- kWindowsEpochDeltaMicroseconds);
-}
-
-// static
-Time Time::NowFromSystemTime() {
- // Just use Now() because Now() returns the system time.
- return Now();
-}
-
-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. Adjust from Windows
- // epoch (1601) to Unix epoch (1970);
- int64_t microseconds = us_ - kWindowsEpochDeltaMicroseconds;
- // The following values are all rounded towards -infinity.
- int64_t milliseconds; // Milliseconds since epoch.
- SysTime seconds; // Seconds since epoch.
- int millisecond; // Exploded millisecond value (0-999).
- if (microseconds >= 0) {
- // Rounding towards -infinity <=> rounding towards 0, in this case.
- milliseconds = microseconds / kMicrosecondsPerMillisecond;
- seconds = milliseconds / kMillisecondsPerSecond;
- millisecond = milliseconds % kMillisecondsPerSecond;
- } else {
- // Round these *down* (towards -infinity).
- milliseconds = (microseconds - kMicrosecondsPerMillisecond + 1) /
- kMicrosecondsPerMillisecond;
- seconds = (milliseconds - kMillisecondsPerSecond + 1) /
- kMillisecondsPerSecond;
- // Make this nonnegative (and between 0 and 999 inclusive).
- millisecond = milliseconds % kMillisecondsPerSecond;
- if (millisecond < 0)
- millisecond += kMillisecondsPerSecond;
- }
-
- struct tm timestruct;
- SysTimeToTimeStruct(seconds, &timestruct, is_local);
-
- 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 = millisecond;
-}
-
-// 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
-#if !defined(OS_NACL) && !defined(OS_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
-
- int64_t milliseconds;
- SysTime seconds;
-
- // Certain exploded dates do not really exist due to daylight saving times,
- // and this causes mktime() to return implementation-defined values when
- // tm_isdst is set to -1. On Android, the function will return -1, while the
- // C libraries of other platforms typically return a liberally-chosen value.
- // Handling this requires the special code below.
-
- // SysTimeFromTimeStruct() modifies the input structure, save current value.
- struct tm timestruct0 = timestruct;
-
- seconds = SysTimeFromTimeStruct(&timestruct, is_local);
- if (seconds == -1) {
- // Get the time values with tm_isdst == 0 and 1, then select the closest one
- // to UTC 00:00:00 that isn't -1.
- timestruct = timestruct0;
- timestruct.tm_isdst = 0;
- int64_t seconds_isdst0 = SysTimeFromTimeStruct(&timestruct, is_local);
-
- timestruct = timestruct0;
- timestruct.tm_isdst = 1;
- int64_t seconds_isdst1 = SysTimeFromTimeStruct(&timestruct, is_local);
-
- // seconds_isdst0 or seconds_isdst1 can be -1 for some timezones.
- // E.g. "CLST" (Chile Summer Time) returns -1 for 'tm_isdt == 1'.
- if (seconds_isdst0 < 0)
- seconds = seconds_isdst1;
- else if (seconds_isdst1 < 0)
- seconds = seconds_isdst0;
- else
- seconds = std::min(seconds_isdst0, seconds_isdst1);
- }
-
- // 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.
-
- // On Android, SysTime is int64_t, special care must be taken to avoid
- // overflows.
- const int64_t min_seconds = (sizeof(SysTime) < sizeof(int64_t))
- ? std::numeric_limits<SysTime>::min()
- : std::numeric_limits<int32_t>::min();
- const int64_t max_seconds = (sizeof(SysTime) < sizeof(int64_t))
- ? std::numeric_limits<SysTime>::max()
- : std::numeric_limits<int32_t>::max();
- if (exploded.year < 1969) {
- milliseconds = min_seconds * kMillisecondsPerSecond;
- } else {
- milliseconds = max_seconds * kMillisecondsPerSecond;
- milliseconds += (kMillisecondsPerSecond - 1);
- }
- } else {
- milliseconds = seconds * kMillisecondsPerSecond + exploded.millisecond;
- }
-
- // Adjust from Unix (1970) to Windows (1601) epoch.
- return Time((milliseconds * kMicrosecondsPerMillisecond) +
- kWindowsEpochDeltaMicroseconds);
-}
-
-// TimeTicks ------------------------------------------------------------------
-// static
-TimeTicks TimeTicks::Now() {
- return TimeTicks(ClockNow(CLOCK_MONOTONIC));
-}
-
-// static
-bool TimeTicks::IsHighResolution() {
- return true;
-}
-
-// static
-ThreadTicks ThreadTicks::Now() {
-#if (defined(_POSIX_THREAD_CPUTIME) && (_POSIX_THREAD_CPUTIME >= 0)) || \
- defined(OS_ANDROID)
- return ThreadTicks(ClockNow(CLOCK_THREAD_CPUTIME_ID));
-#else
- NOTREACHED();
- return ThreadTicks();
-#endif
-}
-
-#endif // !OS_MACOSX
-
-// static
-Time Time::FromTimeVal(struct timeval t) {
- DCHECK_LT(t.tv_usec, static_cast<int>(Time::kMicrosecondsPerSecond));
- DCHECK_GE(t.tv_usec, 0);
- if (t.tv_usec == 0 && t.tv_sec == 0)
- return Time();
- if (t.tv_usec == static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1 &&
- t.tv_sec == std::numeric_limits<time_t>::max())
- return Max();
- return Time((static_cast<int64_t>(t.tv_sec) * Time::kMicrosecondsPerSecond) +
- t.tv_usec + kTimeTToMicrosecondsOffset);
-}
-
-struct timeval Time::ToTimeVal() const {
- struct timeval result;
- if (is_null()) {
- result.tv_sec = 0;
- result.tv_usec = 0;
- return result;
- }
- if (is_max()) {
- result.tv_sec = std::numeric_limits<time_t>::max();
- result.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1;
- return result;
- }
- int64_t us = us_ - kTimeTToMicrosecondsOffset;
- result.tv_sec = us / Time::kMicrosecondsPerSecond;
- result.tv_usec = us % Time::kMicrosecondsPerSecond;
- return result;
-}
-
-} // namespace base
diff --git a/security/sandbox/chromium/base/time/time_win.cc b/security/sandbox/chromium/base/time/time_win.cc
deleted file mode 100644
index dc968ad63..000000000
--- a/security/sandbox/chromium/base/time/time_win.cc
+++ /dev/null
@@ -1,616 +0,0 @@
-// 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.
-
-
-// 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.
-
-#include "base/time/time.h"
-
-#pragma comment(lib, "winmm.lib")
-#include <windows.h>
-#include <mmsystem.h>
-#include <stdint.h>
-
-#include "base/bit_cast.h"
-#include "base/cpu.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/synchronization/lock.h"
-
-using base::ThreadTicks;
-using base::Time;
-using base::TimeDelta;
-using base::TimeTicks;
-
-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 bit_cast to fix alignment, then divide by 10 to convert
- // 100-nanoseconds to microseconds. This only works on little-endian
- // machines.
- return bit_cast<int64_t, FILETIME>(ft) / 10;
-}
-
-void MicrosecondsToFileTime(int64_t us, FILETIME* ft) {
- DCHECK_GE(us, 0LL) << "Time is less than 0, negative values are not "
- "representable in FILETIME";
-
- // Multiply by 10 to convert microseconds to 100-nanoseconds. Bit_cast will
- // handle alignment problems. This only works on little-endian machines.
- *ft = bit_cast<FILETIME, int64_t>(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();
-}
-
-// The two values that ActivateHighResolutionTimer uses to set the systemwide
-// timer interrupt frequency on Windows. It controls how precise timers are
-// but also has a big impact on battery life.
-const int kMinTimerIntervalHighResMs = 1;
-const int kMinTimerIntervalLowResMs = 4;
-// Track if kMinTimerIntervalHighResMs or kMinTimerIntervalLowResMs is active.
-bool g_high_res_timer_enabled = false;
-// How many times the high resolution timer has been called.
-uint32_t g_high_res_timer_count = 0;
-// The lock to control access to the above two variables.
-base::LazyInstance<base::Lock>::Leaky g_high_res_lock =
- LAZY_INSTANCE_INITIALIZER;
-
-// Returns a pointer to the QueryThreadCycleTime() function from Windows.
-// Can't statically link to it because it is not available on XP.
-using QueryThreadCycleTimePtr = decltype(::QueryThreadCycleTime)*;
-QueryThreadCycleTimePtr GetQueryThreadCycleTimeFunction() {
- static const QueryThreadCycleTimePtr query_thread_cycle_time_fn =
- reinterpret_cast<QueryThreadCycleTimePtr>(::GetProcAddress(
- ::GetModuleHandle(L"kernel32.dll"), "QueryThreadCycleTime"));
- return query_thread_cycle_time_fn;
-}
-
-// Returns the current value of the performance counter.
-uint64_t QPCNowRaw() {
- LARGE_INTEGER perf_counter_now = {};
- // According to the MSDN documentation for QueryPerformanceCounter(), this
- // will never fail on systems that run XP or later.
- // https://msdn.microsoft.com/library/windows/desktop/ms644904.aspx
- ::QueryPerformanceCounter(&perf_counter_now);
- return perf_counter_now.QuadPart;
-}
-
-} // 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 = 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::FromFileTime(FILETIME ft) {
- if (bit_cast<int64_t, FILETIME>(ft) == 0)
- return Time();
- if (ft.dwHighDateTime == std::numeric_limits<DWORD>::max() &&
- ft.dwLowDateTime == std::numeric_limits<DWORD>::max())
- return Max();
- return Time(FileTimeToMicroseconds(ft));
-}
-
-FILETIME Time::ToFileTime() const {
- if (is_null())
- return bit_cast<FILETIME, int64_t>(0);
- if (is_max()) {
- FILETIME result;
- result.dwHighDateTime = std::numeric_limits<DWORD>::max();
- result.dwLowDateTime = std::numeric_limits<DWORD>::max();
- return result;
- }
- FILETIME utc_ft;
- MicrosecondsToFileTime(us_, &utc_ft);
- return utc_ft;
-}
-
-// static
-void Time::EnableHighResolutionTimer(bool enable) {
- base::AutoLock lock(g_high_res_lock.Get());
- if (g_high_res_timer_enabled == enable)
- return;
- g_high_res_timer_enabled = enable;
- if (!g_high_res_timer_count)
- return;
- // Since g_high_res_timer_count != 0, an ActivateHighResolutionTimer(true)
- // was called which called timeBeginPeriod with g_high_res_timer_enabled
- // with a value which is the opposite of |enable|. With that information we
- // call timeEndPeriod with the same value used in timeBeginPeriod and
- // therefore undo the period effect.
- if (enable) {
- timeEndPeriod(kMinTimerIntervalLowResMs);
- timeBeginPeriod(kMinTimerIntervalHighResMs);
- } else {
- timeEndPeriod(kMinTimerIntervalHighResMs);
- timeBeginPeriod(kMinTimerIntervalLowResMs);
- }
-}
-
-// static
-bool Time::ActivateHighResolutionTimer(bool activating) {
- // We only do work on the transition from zero to one or one to zero so we
- // can easily undo the effect (if necessary) when EnableHighResolutionTimer is
- // called.
- const uint32_t max = std::numeric_limits<uint32_t>::max();
-
- base::AutoLock lock(g_high_res_lock.Get());
- UINT period = g_high_res_timer_enabled ? kMinTimerIntervalHighResMs
- : kMinTimerIntervalLowResMs;
- if (activating) {
- DCHECK_NE(g_high_res_timer_count, max);
- ++g_high_res_timer_count;
- if (g_high_res_timer_count == 1)
- timeBeginPeriod(period);
- } else {
- DCHECK_NE(g_high_res_timer_count, 0u);
- --g_high_res_timer_count;
- if (g_high_res_timer_count == 0)
- timeEndPeriod(period);
- }
- return (period == kMinTimerIntervalHighResMs);
-}
-
-// static
-bool Time::IsHighResolutionTimerInUse() {
- base::AutoLock lock(g_high_res_lock.Get());
- return g_high_res_timer_enabled && g_high_res_timer_count > 0;
-}
-
-// 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 = static_cast<WORD>(exploded.year);
- st.wMonth = static_cast<WORD>(exploded.month);
- st.wDayOfWeek = static_cast<WORD>(exploded.day_of_week);
- st.wDay = static_cast<WORD>(exploded.day_of_month);
- st.wHour = static_cast<WORD>(exploded.hour);
- st.wMinute = static_cast<WORD>(exploded.minute);
- st.wSecond = static_cast<WORD>(exploded.second);
- st.wMilliseconds = static_cast<WORD>(exploded.millisecond);
-
- FILETIME ft;
- bool success = true;
- // Ensure that it's in UTC.
- if (is_local) {
- SYSTEMTIME utc_st;
- success = TzSpecificLocalTimeToSystemTime(NULL, &st, &utc_st) &&
- SystemTimeToFileTime(&utc_st, &ft);
- } else {
- success = !!SystemTimeToFileTime(&st, &ft);
- }
-
- if (!success) {
- NOTREACHED() << "Unable to convert time";
- return Time(0);
- }
- return Time(FileTimeToMicroseconds(ft));
-}
-
-void Time::Explode(bool is_local, Exploded* exploded) const {
- if (us_ < 0LL) {
- // We are not able to convert it to FILETIME.
- ZeroMemory(exploded, sizeof(*exploded));
- return;
- }
-
- // FILETIME in UTC.
- FILETIME utc_ft;
- MicrosecondsToFileTime(us_, &utc_ft);
-
- // FILETIME in local time if necessary.
- bool success = true;
- // FILETIME in SYSTEMTIME (exploded).
- SYSTEMTIME st = {0};
- if (is_local) {
- SYSTEMTIME utc_st;
- // We don't use FileTimeToLocalFileTime here, since it uses the current
- // settings for the time zone and daylight saving time. Therefore, if it is
- // daylight saving time, it will take daylight saving time into account,
- // even if the time you are converting is in standard time.
- success = FileTimeToSystemTime(&utc_ft, &utc_st) &&
- SystemTimeToTzSpecificLocalTime(NULL, &utc_st, &st);
- } else {
- success = !!FileTimeToSystemTime(&utc_ft, &st);
- }
-
- if (!success) {
- 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 (*g_tick_function)(void) = &timeGetTimeWrapper;
-
-// Accumulation of time lost due to rollover (in milliseconds).
-int64_t g_rollover_ms = 0;
-
-// The last timeGetTime value we saw, to detect rollover.
-DWORD g_last_seen_now = 0;
-
-// Lock protecting rollover_ms and last_seen_now.
-// Note: this is a global object, and we usually avoid these. However, the time
-// code is low-level, and we don't want to use Singletons here (it would be too
-// easy to use a Singleton without even knowing it, and that may lead to many
-// gotchas). Its impact on startup time should be negligible due to low-level
-// nature of time code.
-base::Lock g_rollover_lock;
-
-// 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.
-TimeDelta RolloverProtectedNow() {
- base::AutoLock locked(g_rollover_lock);
- // We should hold the lock while calling tick_function to make sure that
- // we keep last_seen_now stay correctly in sync.
- DWORD now = g_tick_function();
- if (now < g_last_seen_now)
- g_rollover_ms += 0x100000000I64; // ~49.7 days.
- g_last_seen_now = now;
- return TimeDelta::FromMilliseconds(now + g_rollover_ms);
-}
-
-// Discussion of tick counter options on Windows:
-//
-// (1) CPU cycle counter. (Retrieved via RDTSC)
-// The CPU counter provides the highest resolution time stamp and is the least
-// expensive to retrieve. However, on older CPUs, two issues can affect its
-// reliability: First it is maintained per processor and not synchronized
-// between processors. Also, the counters will change frequency due to thermal
-// and power changes, and stop in some states.
-//
-// (2) QueryPerformanceCounter (QPC). The QPC counter provides a high-
-// resolution (<1 microsecond) time stamp. On most hardware running today, it
-// auto-detects and uses the constant-rate RDTSC counter to provide extremely
-// efficient and reliable time stamps.
-//
-// On older CPUs where RDTSC is unreliable, it falls back to using more
-// expensive (20X to 40X more costly) alternate clocks, such as HPET or the ACPI
-// PM timer, and can involve system calls; and all this is up to the HAL (with
-// some help from ACPI). According to
-// http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx, in the
-// worst case, it gets the counter from the rollover interrupt on the
-// programmable interrupt timer. In best cases, the HAL may conclude that the
-// RDTSC counter runs at a constant frequency, then it uses that instead. On
-// multiprocessor machines, it will try to verify the values returned from
-// RDTSC on each processor are consistent with each other, and apply a handful
-// of workarounds for known buggy hardware. In other words, QPC is supposed to
-// give consistent results on a multiprocessor computer, but for older CPUs it
-// can be unreliable due bugs in BIOS or HAL.
-//
-// (3) System time. The system time provides a low-resolution (from ~1 to ~15.6
-// milliseconds) time stamp but is comparatively less expensive to retrieve and
-// more reliable. Time::EnableHighResolutionTimer() and
-// Time::ActivateHighResolutionTimer() can be called to alter the resolution of
-// this timer; and also other Windows applications can alter it, affecting this
-// one.
-
-using NowFunction = TimeDelta (*)(void);
-
-TimeDelta InitialNowFunction();
-
-// See "threading notes" in InitializeNowFunctionPointer() for details on how
-// concurrent reads/writes to these globals has been made safe.
-NowFunction g_now_function = &InitialNowFunction;
-int64_t g_qpc_ticks_per_second = 0;
-
-// As of January 2015, use of <atomic> is forbidden in Chromium code. This is
-// what std::atomic_thread_fence does on Windows on all Intel architectures when
-// the memory_order argument is anything but std::memory_order_seq_cst:
-#define ATOMIC_THREAD_FENCE(memory_order) _ReadWriteBarrier();
-
-TimeDelta QPCValueToTimeDelta(LONGLONG qpc_value) {
- // Ensure that the assignment to |g_qpc_ticks_per_second|, made in
- // InitializeNowFunctionPointer(), has happened by this point.
- ATOMIC_THREAD_FENCE(memory_order_acquire);
-
- DCHECK_GT(g_qpc_ticks_per_second, 0);
-
- // If the QPC Value is below the overflow threshold, we proceed with
- // simple multiply and divide.
- if (qpc_value < Time::kQPCOverflowThreshold) {
- return TimeDelta::FromMicroseconds(
- qpc_value * Time::kMicrosecondsPerSecond / g_qpc_ticks_per_second);
- }
- // Otherwise, calculate microseconds in a round about manner to avoid
- // overflow and precision issues.
- int64_t whole_seconds = qpc_value / g_qpc_ticks_per_second;
- int64_t leftover_ticks = qpc_value - (whole_seconds * g_qpc_ticks_per_second);
- return TimeDelta::FromMicroseconds(
- (whole_seconds * Time::kMicrosecondsPerSecond) +
- ((leftover_ticks * Time::kMicrosecondsPerSecond) /
- g_qpc_ticks_per_second));
-}
-
-TimeDelta QPCNow() {
- return QPCValueToTimeDelta(QPCNowRaw());
-}
-
-bool IsBuggyAthlon(const base::CPU& cpu) {
- // On Athlon X2 CPUs (e.g. model 15) QueryPerformanceCounter is unreliable.
- return cpu.vendor_name() == "AuthenticAMD" && cpu.family() == 15;
-}
-
-void InitializeNowFunctionPointer() {
- LARGE_INTEGER ticks_per_sec = {};
- if (!QueryPerformanceFrequency(&ticks_per_sec))
- ticks_per_sec.QuadPart = 0;
-
- // If Windows cannot provide a QPC implementation, TimeTicks::Now() must use
- // the low-resolution clock.
- //
- // If the QPC implementation is expensive and/or unreliable, TimeTicks::Now()
- // will still use the low-resolution clock. A CPU lacking a non-stop time
- // counter will cause Windows to provide an alternate QPC implementation that
- // works, but is expensive to use. Certain Athlon CPUs are known to make the
- // QPC implementation unreliable.
- //
- // Otherwise, Now uses the high-resolution QPC clock. As of 21 August 2015,
- // ~72% of users fall within this category.
- NowFunction now_function;
- base::CPU cpu;
- if (ticks_per_sec.QuadPart <= 0 ||
- !cpu.has_non_stop_time_stamp_counter() || IsBuggyAthlon(cpu)) {
- now_function = &RolloverProtectedNow;
- } else {
- now_function = &QPCNow;
- }
-
- // Threading note 1: In an unlikely race condition, it's possible for two or
- // more threads to enter InitializeNowFunctionPointer() in parallel. This is
- // not a problem since all threads should end up writing out the same values
- // to the global variables.
- //
- // Threading note 2: A release fence is placed here to ensure, from the
- // perspective of other threads using the function pointers, that the
- // assignment to |g_qpc_ticks_per_second| happens before the function pointers
- // are changed.
- g_qpc_ticks_per_second = ticks_per_sec.QuadPart;
- ATOMIC_THREAD_FENCE(memory_order_release);
- g_now_function = now_function;
-}
-
-TimeDelta InitialNowFunction() {
- InitializeNowFunctionPointer();
- return g_now_function();
-}
-
-} // namespace
-
-// static
-TimeTicks::TickFunctionType TimeTicks::SetMockTickFunction(
- TickFunctionType ticker) {
- base::AutoLock locked(g_rollover_lock);
- TickFunctionType old = g_tick_function;
- g_tick_function = ticker;
- g_rollover_ms = 0;
- g_last_seen_now = 0;
- return old;
-}
-
-// static
-TimeTicks TimeTicks::Now() {
- return TimeTicks() + g_now_function();
-}
-
-// static
-bool TimeTicks::IsHighResolution() {
- if (g_now_function == &InitialNowFunction)
- InitializeNowFunctionPointer();
- return g_now_function == &QPCNow;
-}
-
-// static
-ThreadTicks ThreadTicks::Now() {
- DCHECK(IsSupported());
-
- // Get the number of TSC ticks used by the current thread.
- ULONG64 thread_cycle_time = 0;
- GetQueryThreadCycleTimeFunction()(::GetCurrentThread(), &thread_cycle_time);
-
- // Get the frequency of the TSC.
- double tsc_ticks_per_second = TSCTicksPerSecond();
- if (tsc_ticks_per_second == 0)
- return ThreadTicks();
-
- // Return the CPU time of the current thread.
- double thread_time_seconds = thread_cycle_time / tsc_ticks_per_second;
- return ThreadTicks(
- static_cast<int64_t>(thread_time_seconds * Time::kMicrosecondsPerSecond));
-}
-
-// static
-bool ThreadTicks::IsSupportedWin() {
- static bool is_supported = GetQueryThreadCycleTimeFunction() &&
- base::CPU().has_non_stop_time_stamp_counter() &&
- !IsBuggyAthlon(base::CPU());
- return is_supported;
-}
-
-// static
-void ThreadTicks::WaitUntilInitializedWin() {
- while (TSCTicksPerSecond() == 0)
- ::Sleep(10);
-}
-
-double ThreadTicks::TSCTicksPerSecond() {
- DCHECK(IsSupported());
-
- // The value returned by QueryPerformanceFrequency() cannot be used as the TSC
- // frequency, because there is no guarantee that the TSC frequency is equal to
- // the performance counter frequency.
-
- // The TSC frequency is cached in a static variable because it takes some time
- // to compute it.
- static double tsc_ticks_per_second = 0;
- if (tsc_ticks_per_second != 0)
- return tsc_ticks_per_second;
-
- // Increase the thread priority to reduces the chances of having a context
- // switch during a reading of the TSC and the performance counter.
- int previous_priority = ::GetThreadPriority(::GetCurrentThread());
- ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
-
- // The first time that this function is called, make an initial reading of the
- // TSC and the performance counter.
- static const uint64_t tsc_initial = __rdtsc();
- static const uint64_t perf_counter_initial = QPCNowRaw();
-
- // Make a another reading of the TSC and the performance counter every time
- // that this function is called.
- uint64_t tsc_now = __rdtsc();
- uint64_t perf_counter_now = QPCNowRaw();
-
- // Reset the thread priority.
- ::SetThreadPriority(::GetCurrentThread(), previous_priority);
-
- // Make sure that at least 50 ms elapsed between the 2 readings. The first
- // time that this function is called, we don't expect this to be the case.
- // Note: The longer the elapsed time between the 2 readings is, the more
- // accurate the computed TSC frequency will be. The 50 ms value was
- // chosen because local benchmarks show that it allows us to get a
- // stddev of less than 1 tick/us between multiple runs.
- // Note: According to the MSDN documentation for QueryPerformanceFrequency(),
- // this will never fail on systems that run XP or later.
- // https://msdn.microsoft.com/library/windows/desktop/ms644905.aspx
- LARGE_INTEGER perf_counter_frequency = {};
- ::QueryPerformanceFrequency(&perf_counter_frequency);
- DCHECK_GE(perf_counter_now, perf_counter_initial);
- uint64_t perf_counter_ticks = perf_counter_now - perf_counter_initial;
- double elapsed_time_seconds =
- perf_counter_ticks / static_cast<double>(perf_counter_frequency.QuadPart);
-
- const double kMinimumEvaluationPeriodSeconds = 0.05;
- if (elapsed_time_seconds < kMinimumEvaluationPeriodSeconds)
- return 0;
-
- // Compute the frequency of the TSC.
- DCHECK_GE(tsc_now, tsc_initial);
- uint64_t tsc_ticks = tsc_now - tsc_initial;
- tsc_ticks_per_second = tsc_ticks / elapsed_time_seconds;
-
- return tsc_ticks_per_second;
-}
-
-// static
-TimeTicks TimeTicks::FromQPCValue(LONGLONG qpc_value) {
- return TimeTicks() + QPCValueToTimeDelta(qpc_value);
-}
-
-// TimeDelta ------------------------------------------------------------------
-
-// static
-TimeDelta TimeDelta::FromQPCValue(LONGLONG qpc_value) {
- return QPCValueToTimeDelta(qpc_value);
-}
diff --git a/security/sandbox/chromium/base/tuple.h b/security/sandbox/chromium/base/tuple.h
deleted file mode 100644
index e5872cc4f..000000000
--- a/security/sandbox/chromium/base/tuple.h
+++ /dev/null
@@ -1,306 +0,0 @@
-// 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.
-
-// A Tuple is a generic templatized container, similar in concept to std::pair
-// and std::tuple. The convenient MakeTuple() function takes any number of
-// 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.
-// Tuple<int, const char*> tuple_a(1, "wee");
-// Tuple<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_
-
-#include <stddef.h>
-
-#include "base/bind_helpers.h"
-#include "build/build_config.h"
-
-namespace base {
-
-// Index sequences
-//
-// Minimal clone of the similarly-named C++14 functionality.
-
-template <size_t...>
-struct IndexSequence {};
-
-template <size_t... Ns>
-struct MakeIndexSequenceImpl;
-
-#if defined(_PREFAST_) && defined(OS_WIN)
-
-// Work around VC++ 2013 /analyze internal compiler error:
-// https://connect.microsoft.com/VisualStudio/feedback/details/1053626
-
-template <> struct MakeIndexSequenceImpl<0> {
- using Type = IndexSequence<>;
-};
-template <> struct MakeIndexSequenceImpl<1> {
- using Type = IndexSequence<0>;
-};
-template <> struct MakeIndexSequenceImpl<2> {
- using Type = IndexSequence<0,1>;
-};
-template <> struct MakeIndexSequenceImpl<3> {
- using Type = IndexSequence<0,1,2>;
-};
-template <> struct MakeIndexSequenceImpl<4> {
- using Type = IndexSequence<0,1,2,3>;
-};
-template <> struct MakeIndexSequenceImpl<5> {
- using Type = IndexSequence<0,1,2,3,4>;
-};
-template <> struct MakeIndexSequenceImpl<6> {
- using Type = IndexSequence<0,1,2,3,4,5>;
-};
-template <> struct MakeIndexSequenceImpl<7> {
- using Type = IndexSequence<0,1,2,3,4,5,6>;
-};
-template <> struct MakeIndexSequenceImpl<8> {
- using Type = IndexSequence<0,1,2,3,4,5,6,7>;
-};
-template <> struct MakeIndexSequenceImpl<9> {
- using Type = IndexSequence<0,1,2,3,4,5,6,7,8>;
-};
-template <> struct MakeIndexSequenceImpl<10> {
- using Type = IndexSequence<0,1,2,3,4,5,6,7,8,9>;
-};
-template <> struct MakeIndexSequenceImpl<11> {
- using Type = IndexSequence<0,1,2,3,4,5,6,7,8,9,10>;
-};
-template <> struct MakeIndexSequenceImpl<12> {
- using Type = IndexSequence<0,1,2,3,4,5,6,7,8,9,10,11>;
-};
-template <> struct MakeIndexSequenceImpl<13> {
- using Type = IndexSequence<0,1,2,3,4,5,6,7,8,9,10,11,12>;
-};
-
-#else // defined(WIN) && defined(_PREFAST_)
-
-template <size_t... Ns>
-struct MakeIndexSequenceImpl<0, Ns...> {
- using Type = IndexSequence<Ns...>;
-};
-
-template <size_t N, size_t... Ns>
-struct MakeIndexSequenceImpl<N, Ns...>
- : MakeIndexSequenceImpl<N - 1, N - 1, Ns...> {};
-
-#endif // defined(WIN) && defined(_PREFAST_)
-
-template <size_t N>
-using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::Type;
-
-// 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.
-//
-// Tuple<> 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).
-// Tuple<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.
-
-template <typename IxSeq, typename... Ts>
-struct TupleBaseImpl;
-template <typename... Ts>
-using TupleBase = TupleBaseImpl<MakeIndexSequence<sizeof...(Ts)>, Ts...>;
-template <size_t N, typename T>
-struct TupleLeaf;
-
-template <typename... Ts>
-struct Tuple final : TupleBase<Ts...> {
- Tuple() : TupleBase<Ts...>() {}
- explicit Tuple(typename TupleTraits<Ts>::ParamType... args)
- : TupleBase<Ts...>(args...) {}
-};
-
-// Avoids ambiguity between Tuple's two constructors.
-template <>
-struct Tuple<> final {};
-
-template <size_t... Ns, typename... Ts>
-struct TupleBaseImpl<IndexSequence<Ns...>, Ts...> : TupleLeaf<Ns, Ts>... {
- TupleBaseImpl() : TupleLeaf<Ns, Ts>()... {}
- explicit TupleBaseImpl(typename TupleTraits<Ts>::ParamType... args)
- : TupleLeaf<Ns, Ts>(args)... {}
-};
-
-template <size_t N, typename T>
-struct TupleLeaf {
- TupleLeaf() {}
- explicit TupleLeaf(typename TupleTraits<T>::ParamType x) : x(x) {}
-
- T& get() { return x; }
- const T& get() const { return x; }
-
- T x;
-};
-
-// Tuple getters --------------------------------------------------------------
-//
-// Allows accessing an arbitrary tuple element by index.
-//
-// Example usage:
-// base::Tuple<int, double> t2;
-// base::get<0>(t2) = 42;
-// base::get<1>(t2) = 3.14;
-
-template <size_t I, typename T>
-T& get(TupleLeaf<I, T>& leaf) {
- return leaf.get();
-}
-
-template <size_t I, typename T>
-const T& get(const TupleLeaf<I, T>& leaf) {
- return leaf.get();
-}
-
-// Tuple types ----------------------------------------------------------------
-//
-// Allows for selection of ValueTuple/RefTuple/ParamTuple without needing the
-// definitions of class types the tuple takes as parameters.
-
-template <typename T>
-struct TupleTypes;
-
-template <typename... Ts>
-struct TupleTypes<Tuple<Ts...>> {
- using ValueTuple = Tuple<typename TupleTraits<Ts>::ValueType...>;
- using RefTuple = Tuple<typename TupleTraits<Ts>::RefType...>;
- using ParamTuple = Tuple<typename TupleTraits<Ts>::ParamType...>;
-};
-
-// Tuple creators -------------------------------------------------------------
-//
-// Helper functions for constructing tuples while inferring the template
-// argument types.
-
-template <typename... Ts>
-inline Tuple<Ts...> MakeTuple(const Ts&... arg) {
- return Tuple<Ts...>(arg...);
-}
-
-// The following set of helpers make what Boost refers to as "Tiers" - a tuple
-// of references.
-
-template <typename... Ts>
-inline Tuple<Ts&...> MakeRefTuple(Ts&... arg) {
- return Tuple<Ts&...>(arg...);
-}
-
-// 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 <typename ObjT, typename Method, typename... Ts, size_t... Ns>
-inline void DispatchToMethodImpl(ObjT* obj,
- Method method,
- const Tuple<Ts...>& arg,
- IndexSequence<Ns...>) {
- (obj->*method)(base::internal::UnwrapTraits<Ts>::Unwrap(get<Ns>(arg))...);
-}
-
-template <typename ObjT, typename Method, typename... Ts>
-inline void DispatchToMethod(ObjT* obj,
- Method method,
- const Tuple<Ts...>& arg) {
- DispatchToMethodImpl(obj, method, arg, MakeIndexSequence<sizeof...(Ts)>());
-}
-
-// Static Dispatchers with no out params.
-
-template <typename Function, typename... Ts, size_t... Ns>
-inline void DispatchToFunctionImpl(Function function,
- const Tuple<Ts...>& arg,
- IndexSequence<Ns...>) {
- (*function)(base::internal::UnwrapTraits<Ts>::Unwrap(get<Ns>(arg))...);
-}
-
-template <typename Function, typename... Ts>
-inline void DispatchToFunction(Function function, const Tuple<Ts...>& arg) {
- DispatchToFunctionImpl(function, arg, MakeIndexSequence<sizeof...(Ts)>());
-}
-
-// Dispatchers with out parameters.
-
-template <typename ObjT,
- typename Method,
- typename... InTs,
- typename... OutTs,
- size_t... InNs,
- size_t... OutNs>
-inline void DispatchToMethodImpl(ObjT* obj,
- Method method,
- const Tuple<InTs...>& in,
- Tuple<OutTs...>* out,
- IndexSequence<InNs...>,
- IndexSequence<OutNs...>) {
- (obj->*method)(base::internal::UnwrapTraits<InTs>::Unwrap(get<InNs>(in))...,
- &get<OutNs>(*out)...);
-}
-
-template <typename ObjT, typename Method, typename... InTs, typename... OutTs>
-inline void DispatchToMethod(ObjT* obj,
- Method method,
- const Tuple<InTs...>& in,
- Tuple<OutTs...>* out) {
- DispatchToMethodImpl(obj, method, in, out,
- MakeIndexSequence<sizeof...(InTs)>(),
- MakeIndexSequence<sizeof...(OutTs)>());
-}
-
-} // namespace base
-
-#endif // BASE_TUPLE_H_
diff --git a/security/sandbox/chromium/base/values.h b/security/sandbox/chromium/base/values.h
deleted file mode 100644
index 07e5b6c83..000000000
--- a/security/sandbox/chromium/base/values.h
+++ /dev/null
@@ -1,567 +0,0 @@
-// 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 file specifies a recursive data storage class called Value intended for
-// storing settings and other persistable data.
-//
-// A Value represents something that can be stored in JSON or passed to/from
-// JavaScript. As such, it is NOT a generalized variant type, since only the
-// types supported by JavaScript/JSON are supported.
-//
-// IN PARTICULAR this means that there is no support for int64_t or unsigned
-// numbers. Writing JSON with such types would violate the spec. If you need
-// something like this, either use a double or make a string value containing
-// the number you want.
-
-#ifndef BASE_VALUES_H_
-#define BASE_VALUES_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <iosfwd>
-#include <map>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "base/base_export.h"
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/strings/string16.h"
-#include "base/strings/string_piece.h"
-
-namespace base {
-
-class BinaryValue;
-class DictionaryValue;
-class FundamentalValue;
-class ListValue;
-class StringValue;
-class Value;
-
-typedef std::vector<Value*> ValueVector;
-typedef std::map<std::string, Value*> ValueMap;
-
-// The Value class is the base class for Values. A Value can be instantiated
-// via the Create*Value() factory methods, or by directly creating instances of
-// the subclasses.
-//
-// See the file-level comment above for more information.
-class BASE_EXPORT Value {
- public:
- enum Type {
- TYPE_NULL = 0,
- TYPE_BOOLEAN,
- TYPE_INTEGER,
- TYPE_DOUBLE,
- TYPE_STRING,
- TYPE_BINARY,
- TYPE_DICTIONARY,
- TYPE_LIST
- // Note: Do not add more types. See the file-level comment above for why.
- };
-
- virtual ~Value();
-
- static scoped_ptr<Value> CreateNullValue();
-
- // Returns the type of the value stored by the current Value object.
- // Each type will be implemented by only one subclass of Value, so it's
- // safe to use the Type to determine whether you can cast from
- // Value* to (Implementing Class)*. Also, a Value object never changes
- // its type after construction.
- Type GetType() const { return type_; }
-
- // Returns true if the current object represents a given type.
- bool IsType(Type type) const { return type == type_; }
-
- // These methods allow the convenient retrieval of the contents of the Value.
- // If the current object can be converted into the given type, the value is
- // returned through the |out_value| parameter and true is returned;
- // otherwise, false is returned and |out_value| is unchanged.
- virtual bool GetAsBoolean(bool* out_value) const;
- virtual bool GetAsInteger(int* out_value) const;
- virtual bool GetAsDouble(double* out_value) const;
- virtual bool GetAsString(std::string* out_value) const;
- virtual bool GetAsString(string16* out_value) const;
- virtual bool GetAsString(const StringValue** out_value) const;
- virtual bool GetAsBinary(const BinaryValue** out_value) const;
- virtual bool GetAsList(ListValue** out_value);
- virtual bool GetAsList(const ListValue** out_value) const;
- virtual bool GetAsDictionary(DictionaryValue** out_value);
- virtual bool GetAsDictionary(const DictionaryValue** out_value) const;
- // Note: Do not add more types. See the file-level comment above for why.
-
- // This creates a deep copy of the entire Value tree, and returns a pointer
- // to the copy. The caller gets ownership of the copy, of course.
- //
- // Subclasses return their own type directly in their overrides;
- // this works because C++ supports covariant return types.
- virtual Value* DeepCopy() const;
- // Preferred version of DeepCopy. TODO(estade): remove the above.
- scoped_ptr<Value> CreateDeepCopy() const;
-
- // Compares if two Value objects have equal contents.
- virtual bool Equals(const Value* other) const;
-
- // Compares if two Value objects have equal contents. Can handle NULLs.
- // NULLs are considered equal but different from Value::CreateNullValue().
- static bool Equals(const Value* a, const Value* b);
-
- protected:
- // These aren't safe for end-users, but they are useful for subclasses.
- explicit Value(Type type);
- Value(const Value& that);
- Value& operator=(const Value& that);
-
- private:
- Type type_;
-};
-
-// FundamentalValue represents the simple fundamental types of values.
-class BASE_EXPORT FundamentalValue : public Value {
- public:
- explicit FundamentalValue(bool in_value);
- explicit FundamentalValue(int in_value);
- explicit FundamentalValue(double in_value);
- ~FundamentalValue() override;
-
- // Overridden from Value:
- bool GetAsBoolean(bool* out_value) const override;
- bool GetAsInteger(int* out_value) const override;
- // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
- // doubles.
- bool GetAsDouble(double* out_value) const override;
- FundamentalValue* DeepCopy() const override;
- bool Equals(const Value* other) const override;
-
- private:
- union {
- bool boolean_value_;
- int integer_value_;
- double double_value_;
- };
-};
-
-class BASE_EXPORT StringValue : public Value {
- public:
- // Initializes a StringValue with a UTF-8 narrow character string.
- explicit StringValue(const std::string& in_value);
-
- // Initializes a StringValue with a string16.
- explicit StringValue(const string16& in_value);
-
- ~StringValue() override;
-
- // Returns |value_| as a pointer or reference.
- std::string* GetString();
- const std::string& GetString() const;
-
- // Overridden from Value:
- bool GetAsString(std::string* out_value) const override;
- bool GetAsString(string16* out_value) const override;
- bool GetAsString(const StringValue** out_value) const override;
- StringValue* DeepCopy() const override;
- bool Equals(const Value* other) const override;
-
- private:
- std::string value_;
-};
-
-class BASE_EXPORT BinaryValue: public Value {
- public:
- // Creates a BinaryValue with a null buffer and size of 0.
- BinaryValue();
-
- // Creates a BinaryValue, taking ownership of the bytes pointed to by
- // |buffer|.
- BinaryValue(scoped_ptr<char[]> buffer, size_t size);
-
- ~BinaryValue() override;
-
- // For situations where you want to keep ownership of your buffer, this
- // factory method creates a new BinaryValue by copying the contents of the
- // buffer that's passed in.
- static BinaryValue* CreateWithCopiedBuffer(const char* buffer, size_t size);
-
- size_t GetSize() const { return size_; }
-
- // May return NULL.
- char* GetBuffer() { return buffer_.get(); }
- const char* GetBuffer() const { return buffer_.get(); }
-
- // Overridden from Value:
- bool GetAsBinary(const BinaryValue** out_value) const override;
- BinaryValue* DeepCopy() const override;
- bool Equals(const Value* other) const override;
-
- private:
- scoped_ptr<char[]> buffer_;
- size_t size_;
-
- DISALLOW_COPY_AND_ASSIGN(BinaryValue);
-};
-
-// DictionaryValue provides a key-value dictionary with (optional) "path"
-// parsing for recursive access; see the comment at the top of the file. Keys
-// are |std::string|s and should be UTF-8 encoded.
-class BASE_EXPORT DictionaryValue : public Value {
- public:
- // Returns |value| if it is a dictionary, nullptr otherwise.
- static scoped_ptr<DictionaryValue> From(scoped_ptr<Value> value);
-
- DictionaryValue();
- ~DictionaryValue() override;
-
- // Overridden from Value:
- bool GetAsDictionary(DictionaryValue** out_value) override;
- bool GetAsDictionary(const DictionaryValue** out_value) const override;
-
- // Returns true if the current dictionary has a value for the given key.
- bool HasKey(const std::string& key) const;
-
- // Returns the number of Values in this dictionary.
- size_t size() const { return dictionary_.size(); }
-
- // Returns whether the dictionary is empty.
- bool empty() const { return dictionary_.empty(); }
-
- // Clears any current contents of this dictionary.
- void Clear();
-
- // Sets the Value associated with the given path starting from this object.
- // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
- // into the next DictionaryValue down. Obviously, "." can't be used
- // within a key, but there are no other restrictions on keys.
- // If the key at any step of the way doesn't exist, or exists but isn't
- // a DictionaryValue, a new DictionaryValue will be created and attached
- // to the path in that location. |in_value| must be non-null.
- void Set(const std::string& path, scoped_ptr<Value> in_value);
- // Deprecated version of the above. TODO(estade): remove.
- void Set(const std::string& path, Value* in_value);
-
- // Convenience forms of Set(). These methods will replace any existing
- // value at that path, even if it has a different type.
- void SetBoolean(const std::string& path, bool in_value);
- void SetInteger(const std::string& path, int in_value);
- void SetDouble(const std::string& path, double in_value);
- void SetString(const std::string& path, const std::string& in_value);
- void SetString(const std::string& path, const string16& in_value);
-
- // Like Set(), but without special treatment of '.'. This allows e.g. URLs to
- // be used as paths.
- void SetWithoutPathExpansion(const std::string& key,
- scoped_ptr<Value> in_value);
- // Deprecated version of the above. TODO(estade): remove.
- void SetWithoutPathExpansion(const std::string& key, Value* in_value);
-
- // Convenience forms of SetWithoutPathExpansion().
- void SetBooleanWithoutPathExpansion(const std::string& path, bool in_value);
- void SetIntegerWithoutPathExpansion(const std::string& path, int in_value);
- void SetDoubleWithoutPathExpansion(const std::string& path, double in_value);
- void SetStringWithoutPathExpansion(const std::string& path,
- const std::string& in_value);
- void SetStringWithoutPathExpansion(const std::string& path,
- const string16& in_value);
-
- // Gets the Value associated with the given path starting from this object.
- // A path has the form "<key>" or "<key>.<key>.[...]", where "." indexes
- // into the next DictionaryValue down. If the path can be resolved
- // successfully, the value for the last key in the path will be returned
- // through the |out_value| parameter, and the function will return true.
- // Otherwise, it will return false and |out_value| will be untouched.
- // Note that the dictionary always owns the value that's returned.
- // |out_value| is optional and will only be set if non-NULL.
- bool Get(StringPiece path, const Value** out_value) const;
- bool Get(StringPiece path, Value** out_value);
-
- // These are convenience forms of Get(). The value will be retrieved
- // and the return value will be true if the path is valid and the value at
- // the end of the path can be returned in the form specified.
- // |out_value| is optional and will only be set if non-NULL.
- bool GetBoolean(const std::string& path, bool* out_value) const;
- bool GetInteger(const std::string& path, int* out_value) const;
- // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
- // doubles.
- bool GetDouble(const std::string& path, double* out_value) const;
- bool GetString(const std::string& path, std::string* out_value) const;
- bool GetString(const std::string& path, string16* out_value) const;
- bool GetStringASCII(const std::string& path, std::string* out_value) const;
- bool GetBinary(const std::string& path, const BinaryValue** out_value) const;
- bool GetBinary(const std::string& path, BinaryValue** out_value);
- bool GetDictionary(StringPiece path,
- const DictionaryValue** out_value) const;
- bool GetDictionary(StringPiece path, DictionaryValue** out_value);
- bool GetList(const std::string& path, const ListValue** out_value) const;
- bool GetList(const std::string& path, ListValue** out_value);
-
- // Like Get(), but without special treatment of '.'. This allows e.g. URLs to
- // be used as paths.
- bool GetWithoutPathExpansion(const std::string& key,
- const Value** out_value) const;
- bool GetWithoutPathExpansion(const std::string& key, Value** out_value);
- bool GetBooleanWithoutPathExpansion(const std::string& key,
- bool* out_value) const;
- bool GetIntegerWithoutPathExpansion(const std::string& key,
- int* out_value) const;
- bool GetDoubleWithoutPathExpansion(const std::string& key,
- double* out_value) const;
- bool GetStringWithoutPathExpansion(const std::string& key,
- std::string* out_value) const;
- bool GetStringWithoutPathExpansion(const std::string& key,
- string16* out_value) const;
- bool GetDictionaryWithoutPathExpansion(
- const std::string& key,
- const DictionaryValue** out_value) const;
- bool GetDictionaryWithoutPathExpansion(const std::string& key,
- DictionaryValue** out_value);
- bool GetListWithoutPathExpansion(const std::string& key,
- const ListValue** out_value) const;
- bool GetListWithoutPathExpansion(const std::string& key,
- ListValue** out_value);
-
- // Removes the Value with the specified path from this dictionary (or one
- // of its child dictionaries, if the path is more than just a local key).
- // If |out_value| is non-NULL, the removed Value will be passed out via
- // |out_value|. If |out_value| is NULL, the removed value will be deleted.
- // This method returns true if |path| is a valid path; otherwise it will
- // return false and the DictionaryValue object will be unchanged.
- virtual bool Remove(const std::string& path, scoped_ptr<Value>* out_value);
-
- // Like Remove(), but without special treatment of '.'. This allows e.g. URLs
- // to be used as paths.
- virtual bool RemoveWithoutPathExpansion(const std::string& key,
- scoped_ptr<Value>* out_value);
-
- // Removes a path, clearing out all dictionaries on |path| that remain empty
- // after removing the value at |path|.
- virtual bool RemovePath(const std::string& path,
- scoped_ptr<Value>* out_value);
-
- // Makes a copy of |this| but doesn't include empty dictionaries and lists in
- // the copy. This never returns NULL, even if |this| itself is empty.
- scoped_ptr<DictionaryValue> DeepCopyWithoutEmptyChildren() const;
-
- // Merge |dictionary| into this dictionary. This is done recursively, i.e. any
- // sub-dictionaries will be merged as well. In case of key collisions, the
- // passed in dictionary takes precedence and data already present will be
- // replaced. Values within |dictionary| are deep-copied, so |dictionary| may
- // be freed any time after this call.
- void MergeDictionary(const DictionaryValue* dictionary);
-
- // Swaps contents with the |other| dictionary.
- virtual void Swap(DictionaryValue* other);
-
- // This class provides an iterator over both keys and values in the
- // dictionary. It can't be used to modify the dictionary.
- class BASE_EXPORT Iterator {
- public:
- explicit Iterator(const DictionaryValue& target);
- ~Iterator();
-
- bool IsAtEnd() const { return it_ == target_.dictionary_.end(); }
- void Advance() { ++it_; }
-
- const std::string& key() const { return it_->first; }
- const Value& value() const { return *it_->second; }
-
- private:
- const DictionaryValue& target_;
- ValueMap::const_iterator it_;
- };
-
- // Overridden from Value:
- DictionaryValue* DeepCopy() const override;
- // Preferred version of DeepCopy. TODO(estade): remove the above.
- scoped_ptr<DictionaryValue> CreateDeepCopy() const;
- bool Equals(const Value* other) const override;
-
- private:
- ValueMap dictionary_;
-
- DISALLOW_COPY_AND_ASSIGN(DictionaryValue);
-};
-
-// This type of Value represents a list of other Value values.
-class BASE_EXPORT ListValue : public Value {
- public:
- typedef ValueVector::iterator iterator;
- typedef ValueVector::const_iterator const_iterator;
-
- // Returns |value| if it is a list, nullptr otherwise.
- static scoped_ptr<ListValue> From(scoped_ptr<Value> value);
-
- ListValue();
- ~ListValue() override;
-
- // Clears the contents of this ListValue
- void Clear();
-
- // Returns the number of Values in this list.
- size_t GetSize() const { return list_.size(); }
-
- // Returns whether the list is empty.
- bool empty() const { return list_.empty(); }
-
- // Sets the list item at the given index to be the Value specified by
- // the value given. If the index beyond the current end of the list, null
- // Values will be used to pad out the list.
- // Returns true if successful, or false if the index was negative or
- // the value is a null pointer.
- bool Set(size_t index, Value* in_value);
- // Preferred version of the above. TODO(estade): remove the above.
- bool Set(size_t index, scoped_ptr<Value> in_value);
-
- // Gets the Value at the given index. Modifies |out_value| (and returns true)
- // only if the index falls within the current list range.
- // Note that the list always owns the Value passed out via |out_value|.
- // |out_value| is optional and will only be set if non-NULL.
- bool Get(size_t index, const Value** out_value) const;
- bool Get(size_t index, Value** out_value);
-
- // Convenience forms of Get(). Modifies |out_value| (and returns true)
- // only if the index is valid and the Value at that index can be returned
- // in the specified form.
- // |out_value| is optional and will only be set if non-NULL.
- bool GetBoolean(size_t index, bool* out_value) const;
- bool GetInteger(size_t index, int* out_value) const;
- // Values of both type TYPE_INTEGER and TYPE_DOUBLE can be obtained as
- // doubles.
- bool GetDouble(size_t index, double* out_value) const;
- bool GetString(size_t index, std::string* out_value) const;
- bool GetString(size_t index, string16* out_value) const;
- bool GetBinary(size_t index, const BinaryValue** out_value) const;
- bool GetBinary(size_t index, BinaryValue** out_value);
- bool GetDictionary(size_t index, const DictionaryValue** out_value) const;
- bool GetDictionary(size_t index, DictionaryValue** out_value);
- bool GetList(size_t index, const ListValue** out_value) const;
- bool GetList(size_t index, ListValue** out_value);
-
- // Removes the Value with the specified index from this list.
- // If |out_value| is non-NULL, the removed Value AND ITS OWNERSHIP will be
- // passed out via |out_value|. If |out_value| is NULL, the removed value will
- // be deleted. This method returns true if |index| is valid; otherwise
- // it will return false and the ListValue object will be unchanged.
- virtual bool Remove(size_t index, scoped_ptr<Value>* out_value);
-
- // Removes the first instance of |value| found in the list, if any, and
- // deletes it. |index| is the location where |value| was found. Returns false
- // if not found.
- bool Remove(const Value& value, size_t* index);
-
- // Removes the element at |iter|. If |out_value| is NULL, the value will be
- // deleted, otherwise ownership of the value is passed back to the caller.
- // Returns an iterator pointing to the location of the element that
- // followed the erased element.
- iterator Erase(iterator iter, scoped_ptr<Value>* out_value);
-
- // Appends a Value to the end of the list.
- void Append(scoped_ptr<Value> in_value);
- // Deprecated version of the above. TODO(estade): remove.
- void Append(Value* in_value);
-
- // Convenience forms of Append.
- void AppendBoolean(bool in_value);
- void AppendInteger(int in_value);
- void AppendDouble(double in_value);
- void AppendString(const std::string& in_value);
- void AppendString(const string16& in_value);
- void AppendStrings(const std::vector<std::string>& in_values);
- void AppendStrings(const std::vector<string16>& in_values);
-
- // Appends a Value if it's not already present. Takes ownership of the
- // |in_value|. Returns true if successful, or false if the value was already
- // present. If the value was already present the |in_value| is deleted.
- bool AppendIfNotPresent(Value* in_value);
-
- // Insert a Value at index.
- // Returns true if successful, or false if the index was out of range.
- bool Insert(size_t index, Value* in_value);
-
- // Searches for the first instance of |value| in the list using the Equals
- // method of the Value type.
- // Returns a const_iterator to the found item or to end() if none exists.
- const_iterator Find(const Value& value) const;
-
- // Swaps contents with the |other| list.
- virtual void Swap(ListValue* other);
-
- // Iteration.
- iterator begin() { return list_.begin(); }
- iterator end() { return list_.end(); }
-
- const_iterator begin() const { return list_.begin(); }
- const_iterator end() const { return list_.end(); }
-
- // Overridden from Value:
- bool GetAsList(ListValue** out_value) override;
- bool GetAsList(const ListValue** out_value) const override;
- ListValue* DeepCopy() const override;
- bool Equals(const Value* other) const override;
-
- // Preferred version of DeepCopy. TODO(estade): remove DeepCopy.
- scoped_ptr<ListValue> CreateDeepCopy() const;
-
- private:
- ValueVector list_;
-
- DISALLOW_COPY_AND_ASSIGN(ListValue);
-};
-
-// This interface is implemented by classes that know how to serialize
-// Value objects.
-class BASE_EXPORT ValueSerializer {
- public:
- virtual ~ValueSerializer();
-
- virtual bool Serialize(const Value& root) = 0;
-};
-
-// This interface is implemented by classes that know how to deserialize Value
-// objects.
-class BASE_EXPORT ValueDeserializer {
- public:
- virtual ~ValueDeserializer();
-
- // This method deserializes the subclass-specific format into a Value object.
- // If the return value is non-NULL, the caller takes ownership of returned
- // Value. If the return value is NULL, and if error_code is non-NULL,
- // error_code will be set with the underlying error.
- // If |error_message| is non-null, it will be filled in with a formatted
- // error message including the location of the error if appropriate.
- virtual scoped_ptr<Value> Deserialize(int* error_code,
- std::string* error_str) = 0;
-};
-
-// Stream operator so Values can be used in assertion statements. In order that
-// gtest uses this operator to print readable output on test failures, we must
-// override each specific type. Otherwise, the default template implementation
-// is preferred over an upcast.
-BASE_EXPORT std::ostream& operator<<(std::ostream& out, const Value& value);
-
-BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
- const FundamentalValue& value) {
- return out << static_cast<const Value&>(value);
-}
-
-BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
- const StringValue& value) {
- return out << static_cast<const Value&>(value);
-}
-
-BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
- const DictionaryValue& value) {
- return out << static_cast<const Value&>(value);
-}
-
-BASE_EXPORT inline std::ostream& operator<<(std::ostream& out,
- const ListValue& value) {
- return out << static_cast<const Value&>(value);
-}
-
-} // namespace base
-
-#endif // BASE_VALUES_H_
diff --git a/security/sandbox/chromium/base/version.h b/security/sandbox/chromium/base/version.h
deleted file mode 100644
index 85c99a355..000000000
--- a/security/sandbox/chromium/base/version.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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.
-
-#ifndef BASE_VERSION_H_
-#define BASE_VERSION_H_
-
-#include <stdint.h>
-#include <string>
-#include <vector>
-
-#include "base/base_export.h"
-
-namespace base {
-
-// Version represents a dotted version number, like "1.2.3.4", supporting
-// parsing and comparison.
-class BASE_EXPORT Version {
- public:
- // The only thing you can legally do to a default constructed
- // Version object is assign to it.
- Version();
-
- ~Version();
-
- // Initializes from a decimal dotted version number, like "0.1.1".
- // Each component is limited to a uint16_t. Call IsValid() to learn
- // the outcome.
- explicit Version(const std::string& version_str);
-
- // Returns true if the object contains a valid version number.
- bool IsValid() const;
-
- // Returns true if the version wildcard string is valid. The version wildcard
- // string may end with ".*" (e.g. 1.2.*, 1.*). Any other arrangement with "*"
- // is invalid (e.g. 1.*.3 or 1.2.3*). This functions defaults to standard
- // Version behavior (IsValid) if no wildcard is present.
- static bool IsValidWildcardString(const std::string& wildcard_string);
-
- // Commonly used pattern. Given a valid version object, compare if a
- // |version_str| results in a newer version. Returns true if the
- // string represents valid version and if the version is greater than
- // than the version of this object.
- bool IsOlderThan(const std::string& version_str) const;
-
- bool Equals(const Version& other) const;
-
- // Returns -1, 0, 1 for <, ==, >.
- int CompareTo(const Version& other) const;
-
- // Given a valid version object, compare if a |wildcard_string| results in a
- // newer version. This function will default to CompareTo if the string does
- // not end in wildcard sequence ".*". IsValidWildcard(wildcard_string) must be
- // true before using this function.
- int CompareToWildcardString(const std::string& wildcard_string) const;
-
- // Return the string representation of this version.
- const std::string GetString() const;
-
- const std::vector<uint32_t>& components() const { return components_; }
-
- private:
- std::vector<uint32_t> components_;
-};
-
-} // namespace base
-
-// TODO(xhwang) remove this when all users are updated to explicitly use the
-// namespace
-using base::Version;
-
-#endif // BASE_VERSION_H_
diff --git a/security/sandbox/chromium/base/win/pe_image.cc b/security/sandbox/chromium/base/win/pe_image.cc
deleted file mode 100644
index 4b5d62099..000000000
--- a/security/sandbox/chromium/base/win/pe_image.cc
+++ /dev/null
@@ -1,580 +0,0 @@
-// 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.
-
-// This file implements PEImage, a generic class to manipulate PE files.
-// This file was adapted from GreenBorder's Code.
-
-#include <stddef.h>
-
-#include "base/win/pe_image.h"
-
-namespace base {
-namespace win {
-
-// Structure to perform imports enumerations.
-struct EnumAllImportsStorage {
- PEImage::EnumImportsFunction callback;
- PVOID cookie;
-};
-
-namespace {
-
-// PdbInfo Signature
-const DWORD kPdbInfoSignature = 'SDSR';
-
-// Compare two strings byte by byte on an unsigned basis.
-// if s1 == s2, return 0
-// if s1 < s2, return negative
-// if s1 > s2, return positive
-// Exception if inputs are invalid.
-int StrCmpByByte(LPCSTR s1, LPCSTR s2) {
- while (*s1 != '\0' && *s1 == *s2) {
- ++s1;
- ++s2;
- }
-
- return (*reinterpret_cast<const unsigned char*>(s1) -
- *reinterpret_cast<const unsigned char*>(s2));
-}
-
-struct PdbInfo {
- DWORD Signature;
- GUID Guid;
- DWORD Age;
- char PdbFileName[1];
-};
-
-} // namespace
-
-// Callback used to enumerate imports. See EnumImportChunksFunction.
-bool ProcessImportChunk(const PEImage &image, LPCSTR module,
- PIMAGE_THUNK_DATA name_table,
- PIMAGE_THUNK_DATA iat, PVOID cookie) {
- EnumAllImportsStorage& storage =
- *reinterpret_cast<EnumAllImportsStorage*>(cookie);
-
- return image.EnumOneImportChunk(storage.callback, module, name_table, iat,
- storage.cookie);
-}
-
-// Callback used to enumerate delay imports. See EnumDelayImportChunksFunction.
-bool ProcessDelayImportChunk(const PEImage& image,
- PImgDelayDescr delay_descriptor,
- LPCSTR module,
- PIMAGE_THUNK_DATA name_table,
- PIMAGE_THUNK_DATA iat,
- PVOID cookie) {
- EnumAllImportsStorage& storage =
- *reinterpret_cast<EnumAllImportsStorage*>(cookie);
-
- return image.EnumOneDelayImportChunk(storage.callback, delay_descriptor,
- module, name_table, iat, storage.cookie);
-}
-
-void PEImage::set_module(HMODULE module) {
- module_ = module;
-}
-
-PIMAGE_DOS_HEADER PEImage::GetDosHeader() const {
- return reinterpret_cast<PIMAGE_DOS_HEADER>(module_);
-}
-
-PIMAGE_NT_HEADERS PEImage::GetNTHeaders() const {
- PIMAGE_DOS_HEADER dos_header = GetDosHeader();
-
- return reinterpret_cast<PIMAGE_NT_HEADERS>(
- reinterpret_cast<char*>(dos_header) + dos_header->e_lfanew);
-}
-
-PIMAGE_SECTION_HEADER PEImage::GetSectionHeader(UINT section) const {
- PIMAGE_NT_HEADERS nt_headers = GetNTHeaders();
- PIMAGE_SECTION_HEADER first_section = IMAGE_FIRST_SECTION(nt_headers);
-
- if (section < nt_headers->FileHeader.NumberOfSections)
- return first_section + section;
- else
- return NULL;
-}
-
-WORD PEImage::GetNumSections() const {
- return GetNTHeaders()->FileHeader.NumberOfSections;
-}
-
-DWORD PEImage::GetImageDirectoryEntrySize(UINT directory) const {
- PIMAGE_NT_HEADERS nt_headers = GetNTHeaders();
-
- return nt_headers->OptionalHeader.DataDirectory[directory].Size;
-}
-
-PVOID PEImage::GetImageDirectoryEntryAddr(UINT directory) const {
- PIMAGE_NT_HEADERS nt_headers = GetNTHeaders();
-
- return RVAToAddr(
- nt_headers->OptionalHeader.DataDirectory[directory].VirtualAddress);
-}
-
-PIMAGE_SECTION_HEADER PEImage::GetImageSectionFromAddr(PVOID address) const {
- PBYTE target = reinterpret_cast<PBYTE>(address);
- PIMAGE_SECTION_HEADER section;
-
- for (UINT i = 0; NULL != (section = GetSectionHeader(i)); i++) {
- // Don't use the virtual RVAToAddr.
- PBYTE start = reinterpret_cast<PBYTE>(
- PEImage::RVAToAddr(section->VirtualAddress));
-
- DWORD size = section->Misc.VirtualSize;
-
- if ((start <= target) && (start + size > target))
- return section;
- }
-
- return NULL;
-}
-
-PIMAGE_SECTION_HEADER PEImage::GetImageSectionHeaderByName(
- LPCSTR section_name) const {
- if (NULL == section_name)
- return NULL;
-
- PIMAGE_SECTION_HEADER ret = NULL;
- int num_sections = GetNumSections();
-
- for (int i = 0; i < num_sections; i++) {
- PIMAGE_SECTION_HEADER section = GetSectionHeader(i);
- if (0 == _strnicmp(reinterpret_cast<LPCSTR>(section->Name), section_name,
- sizeof(section->Name))) {
- ret = section;
- break;
- }
- }
-
- return ret;
-}
-
-bool PEImage::GetDebugId(LPGUID guid, LPDWORD age) const {
- if (NULL == guid || NULL == age) {
- return false;
- }
-
- DWORD debug_directory_size =
- GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_DEBUG);
- PIMAGE_DEBUG_DIRECTORY debug_directory =
- reinterpret_cast<PIMAGE_DEBUG_DIRECTORY>(
- GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_DEBUG));
-
- size_t directory_count =
- debug_directory_size / sizeof(IMAGE_DEBUG_DIRECTORY);
-
- for (size_t index = 0; index < directory_count; ++index) {
- if (debug_directory[index].Type == IMAGE_DEBUG_TYPE_CODEVIEW) {
- PdbInfo* pdb_info = reinterpret_cast<PdbInfo*>(
- RVAToAddr(debug_directory[index].AddressOfRawData));
- if (pdb_info->Signature != kPdbInfoSignature) {
- // Unsupported PdbInfo signature
- return false;
- }
- *guid = pdb_info->Guid;
- *age = pdb_info->Age;
- return true;
- }
- }
- return false;
-}
-
-PDWORD PEImage::GetExportEntry(LPCSTR name) const {
- PIMAGE_EXPORT_DIRECTORY exports = GetExportDirectory();
-
- if (NULL == exports)
- return NULL;
-
- WORD ordinal = 0;
- if (!GetProcOrdinal(name, &ordinal))
- return NULL;
-
- PDWORD functions = reinterpret_cast<PDWORD>(
- RVAToAddr(exports->AddressOfFunctions));
-
- return functions + ordinal - exports->Base;
-}
-
-FARPROC PEImage::GetProcAddress(LPCSTR function_name) const {
- PDWORD export_entry = GetExportEntry(function_name);
- if (NULL == export_entry)
- return NULL;
-
- PBYTE function = reinterpret_cast<PBYTE>(RVAToAddr(*export_entry));
-
- PBYTE exports = reinterpret_cast<PBYTE>(
- GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_EXPORT));
- DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_EXPORT);
-
- // Check for forwarded exports as a special case.
- if (exports <= function && exports + size > function)
- return reinterpret_cast<FARPROC>(-1);
-
- return reinterpret_cast<FARPROC>(function);
-}
-
-bool PEImage::GetProcOrdinal(LPCSTR function_name, WORD *ordinal) const {
- if (NULL == ordinal)
- return false;
-
- PIMAGE_EXPORT_DIRECTORY exports = GetExportDirectory();
-
- if (NULL == exports)
- return false;
-
- if (IsOrdinal(function_name)) {
- *ordinal = ToOrdinal(function_name);
- } else {
- PDWORD names = reinterpret_cast<PDWORD>(RVAToAddr(exports->AddressOfNames));
- PDWORD lower = names;
- PDWORD upper = names + exports->NumberOfNames;
- int cmp = -1;
-
- // Binary Search for the name.
- while (lower != upper) {
- PDWORD middle = lower + (upper - lower) / 2;
- LPCSTR name = reinterpret_cast<LPCSTR>(RVAToAddr(*middle));
-
- // This may be called by sandbox before MSVCRT dll loads, so can't use
- // CRT function here.
- cmp = StrCmpByByte(function_name, name);
-
- if (cmp == 0) {
- lower = middle;
- break;
- }
-
- if (cmp > 0)
- lower = middle + 1;
- else
- upper = middle;
- }
-
- if (cmp != 0)
- return false;
-
-
- PWORD ordinals = reinterpret_cast<PWORD>(
- RVAToAddr(exports->AddressOfNameOrdinals));
-
- *ordinal = ordinals[lower - names] + static_cast<WORD>(exports->Base);
- }
-
- return true;
-}
-
-bool PEImage::EnumSections(EnumSectionsFunction callback, PVOID cookie) const {
- PIMAGE_NT_HEADERS nt_headers = GetNTHeaders();
- UINT num_sections = nt_headers->FileHeader.NumberOfSections;
- PIMAGE_SECTION_HEADER section = GetSectionHeader(0);
-
- for (UINT i = 0; i < num_sections; i++, section++) {
- PVOID section_start = RVAToAddr(section->VirtualAddress);
- DWORD size = section->Misc.VirtualSize;
-
- if (!callback(*this, section, section_start, size, cookie))
- return false;
- }
-
- return true;
-}
-
-bool PEImage::EnumExports(EnumExportsFunction callback, PVOID cookie) const {
- PVOID directory = GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_EXPORT);
- DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_EXPORT);
-
- // Check if there are any exports at all.
- if (NULL == directory || 0 == size)
- return true;
-
- PIMAGE_EXPORT_DIRECTORY exports = reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>(
- directory);
- UINT ordinal_base = exports->Base;
- UINT num_funcs = exports->NumberOfFunctions;
- UINT num_names = exports->NumberOfNames;
- PDWORD functions = reinterpret_cast<PDWORD>(RVAToAddr(
- exports->AddressOfFunctions));
- PDWORD names = reinterpret_cast<PDWORD>(RVAToAddr(exports->AddressOfNames));
- PWORD ordinals = reinterpret_cast<PWORD>(RVAToAddr(
- exports->AddressOfNameOrdinals));
-
- for (UINT count = 0; count < num_funcs; count++) {
- PVOID func = RVAToAddr(functions[count]);
- if (NULL == func)
- continue;
-
- // Check for a name.
- LPCSTR name = NULL;
- UINT hint;
- for (hint = 0; hint < num_names; hint++) {
- if (ordinals[hint] == count) {
- name = reinterpret_cast<LPCSTR>(RVAToAddr(names[hint]));
- break;
- }
- }
-
- if (name == NULL)
- hint = 0;
-
- // Check for forwarded exports.
- LPCSTR forward = NULL;
- if (reinterpret_cast<char*>(func) >= reinterpret_cast<char*>(directory) &&
- reinterpret_cast<char*>(func) <= reinterpret_cast<char*>(directory) +
- size) {
- forward = reinterpret_cast<LPCSTR>(func);
- func = 0;
- }
-
- if (!callback(*this, ordinal_base + count, hint, name, func, forward,
- cookie))
- return false;
- }
-
- return true;
-}
-
-bool PEImage::EnumRelocs(EnumRelocsFunction callback, PVOID cookie) const {
- PVOID directory = GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_BASERELOC);
- DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_BASERELOC);
- PIMAGE_BASE_RELOCATION base = reinterpret_cast<PIMAGE_BASE_RELOCATION>(
- directory);
-
- if (!directory)
- return true;
-
- while (size >= sizeof(IMAGE_BASE_RELOCATION) && base->SizeOfBlock &&
- size >= base->SizeOfBlock) {
- PWORD reloc = reinterpret_cast<PWORD>(base + 1);
- UINT num_relocs = (base->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) /
- sizeof(WORD);
-
- for (UINT i = 0; i < num_relocs; i++, reloc++) {
- WORD type = *reloc >> 12;
- PVOID address = RVAToAddr(base->VirtualAddress + (*reloc & 0x0FFF));
-
- if (!callback(*this, type, address, cookie))
- return false;
- }
-
- size -= base->SizeOfBlock;
- base = reinterpret_cast<PIMAGE_BASE_RELOCATION>(
- reinterpret_cast<char*>(base) + base->SizeOfBlock);
- }
-
- return true;
-}
-
-bool PEImage::EnumImportChunks(EnumImportChunksFunction callback,
- PVOID cookie) const {
- DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_IMPORT);
- PIMAGE_IMPORT_DESCRIPTOR import = GetFirstImportChunk();
-
- if (import == NULL || size < sizeof(IMAGE_IMPORT_DESCRIPTOR))
- return true;
-
- for (; import->FirstThunk; import++) {
- LPCSTR module_name = reinterpret_cast<LPCSTR>(RVAToAddr(import->Name));
- PIMAGE_THUNK_DATA name_table = reinterpret_cast<PIMAGE_THUNK_DATA>(
- RVAToAddr(import->OriginalFirstThunk));
- PIMAGE_THUNK_DATA iat = reinterpret_cast<PIMAGE_THUNK_DATA>(
- RVAToAddr(import->FirstThunk));
-
- if (!callback(*this, module_name, name_table, iat, cookie))
- return false;
- }
-
- return true;
-}
-
-bool PEImage::EnumOneImportChunk(EnumImportsFunction callback,
- LPCSTR module_name,
- PIMAGE_THUNK_DATA name_table,
- PIMAGE_THUNK_DATA iat, PVOID cookie) const {
- if (NULL == name_table)
- return false;
-
- for (; name_table && name_table->u1.Ordinal; name_table++, iat++) {
- LPCSTR name = NULL;
- WORD ordinal = 0;
- WORD hint = 0;
-
- if (IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) {
- ordinal = static_cast<WORD>(IMAGE_ORDINAL32(name_table->u1.Ordinal));
- } else {
- PIMAGE_IMPORT_BY_NAME import = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>(
- RVAToAddr(name_table->u1.ForwarderString));
-
- hint = import->Hint;
- name = reinterpret_cast<LPCSTR>(&import->Name);
- }
-
- if (!callback(*this, module_name, ordinal, name, hint, iat, cookie))
- return false;
- }
-
- return true;
-}
-
-bool PEImage::EnumAllImports(EnumImportsFunction callback, PVOID cookie) const {
- EnumAllImportsStorage temp = { callback, cookie };
- return EnumImportChunks(ProcessImportChunk, &temp);
-}
-
-bool PEImage::EnumDelayImportChunks(EnumDelayImportChunksFunction callback,
- PVOID cookie) const {
- PVOID directory = GetImageDirectoryEntryAddr(
- IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT);
- DWORD size = GetImageDirectoryEntrySize(IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT);
- PImgDelayDescr delay_descriptor = reinterpret_cast<PImgDelayDescr>(directory);
-
- if (directory == NULL || size == 0)
- return true;
-
- for (; delay_descriptor->rvaHmod; delay_descriptor++) {
- PIMAGE_THUNK_DATA name_table;
- PIMAGE_THUNK_DATA iat;
- LPCSTR module_name;
-
- // check if VC7-style imports, using RVAs instead of
- // VC6-style addresses.
- bool rvas = (delay_descriptor->grAttrs & dlattrRva) != 0;
-
- if (rvas) {
- module_name =
- reinterpret_cast<LPCSTR>(RVAToAddr(delay_descriptor->rvaDLLName));
- name_table = reinterpret_cast<PIMAGE_THUNK_DATA>(
- RVAToAddr(delay_descriptor->rvaINT));
- iat = reinterpret_cast<PIMAGE_THUNK_DATA>(
- RVAToAddr(delay_descriptor->rvaIAT));
- } else {
- // Values in IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT are 32-bit, even on 64-bit
- // platforms. See section 4.8 of PECOFF image spec rev 8.3.
- module_name = reinterpret_cast<LPCSTR>(
- static_cast<uintptr_t>(delay_descriptor->rvaDLLName));
- name_table = reinterpret_cast<PIMAGE_THUNK_DATA>(
- static_cast<uintptr_t>(delay_descriptor->rvaINT));
- iat = reinterpret_cast<PIMAGE_THUNK_DATA>(
- static_cast<uintptr_t>(delay_descriptor->rvaIAT));
- }
-
- if (!callback(*this, delay_descriptor, module_name, name_table, iat,
- cookie))
- return false;
- }
-
- return true;
-}
-
-bool PEImage::EnumOneDelayImportChunk(EnumImportsFunction callback,
- PImgDelayDescr delay_descriptor,
- LPCSTR module_name,
- PIMAGE_THUNK_DATA name_table,
- PIMAGE_THUNK_DATA iat,
- PVOID cookie) const {
- for (; name_table->u1.Ordinal; name_table++, iat++) {
- LPCSTR name = NULL;
- WORD ordinal = 0;
- WORD hint = 0;
-
- if (IMAGE_SNAP_BY_ORDINAL(name_table->u1.Ordinal)) {
- ordinal = static_cast<WORD>(IMAGE_ORDINAL32(name_table->u1.Ordinal));
- } else {
- PIMAGE_IMPORT_BY_NAME import;
- bool rvas = (delay_descriptor->grAttrs & dlattrRva) != 0;
-
- if (rvas) {
- import = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>(
- RVAToAddr(name_table->u1.ForwarderString));
- } else {
- import = reinterpret_cast<PIMAGE_IMPORT_BY_NAME>(
- name_table->u1.ForwarderString);
- }
-
- hint = import->Hint;
- name = reinterpret_cast<LPCSTR>(&import->Name);
- }
-
- if (!callback(*this, module_name, ordinal, name, hint, iat, cookie))
- return false;
- }
-
- return true;
-}
-
-bool PEImage::EnumAllDelayImports(EnumImportsFunction callback,
- PVOID cookie) const {
- EnumAllImportsStorage temp = { callback, cookie };
- return EnumDelayImportChunks(ProcessDelayImportChunk, &temp);
-}
-
-bool PEImage::VerifyMagic() const {
- PIMAGE_DOS_HEADER dos_header = GetDosHeader();
-
- if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
- return false;
-
- PIMAGE_NT_HEADERS nt_headers = GetNTHeaders();
-
- if (nt_headers->Signature != IMAGE_NT_SIGNATURE)
- return false;
-
- if (nt_headers->FileHeader.SizeOfOptionalHeader !=
- sizeof(IMAGE_OPTIONAL_HEADER))
- return false;
-
- if (nt_headers->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR_MAGIC)
- return false;
-
- return true;
-}
-
-bool PEImage::ImageRVAToOnDiskOffset(DWORD rva, DWORD* on_disk_offset) const {
- LPVOID address = RVAToAddr(rva);
- return ImageAddrToOnDiskOffset(address, on_disk_offset);
-}
-
-bool PEImage::ImageAddrToOnDiskOffset(LPVOID address,
- DWORD* on_disk_offset) const {
- if (NULL == address)
- return false;
-
- // Get the section that this address belongs to.
- PIMAGE_SECTION_HEADER section_header = GetImageSectionFromAddr(address);
- if (NULL == section_header)
- return false;
-
- // Don't follow the virtual RVAToAddr, use the one on the base.
- DWORD offset_within_section =
- static_cast<DWORD>(reinterpret_cast<uintptr_t>(address)) -
- static_cast<DWORD>(reinterpret_cast<uintptr_t>(
- PEImage::RVAToAddr(section_header->VirtualAddress)));
-
- *on_disk_offset = section_header->PointerToRawData + offset_within_section;
- return true;
-}
-
-PVOID PEImage::RVAToAddr(DWORD rva) const {
- if (rva == 0)
- return NULL;
-
- return reinterpret_cast<char*>(module_) + rva;
-}
-
-PVOID PEImageAsData::RVAToAddr(DWORD rva) const {
- if (rva == 0)
- return NULL;
-
- PVOID in_memory = PEImage::RVAToAddr(rva);
- DWORD disk_offset;
-
- if (!ImageAddrToOnDiskOffset(in_memory, &disk_offset))
- return NULL;
-
- return PEImage::RVAToAddr(disk_offset);
-}
-
-} // namespace win
-} // namespace base
diff --git a/security/sandbox/chromium/base/win/pe_image.h b/security/sandbox/chromium/base/win/pe_image.h
deleted file mode 100644
index 4c36bcf85..000000000
--- a/security/sandbox/chromium/base/win/pe_image.h
+++ /dev/null
@@ -1,265 +0,0 @@
-// 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.
-
-// This file was adapted from GreenBorder's Code.
-// To understand what this class is about (for other than well known functions
-// as GetProcAddress), a good starting point is "An In-Depth Look into the
-// Win32 Portable Executable File Format" by Matt Pietrek:
-// http://msdn.microsoft.com/msdnmag/issues/02/02/PE/default.aspx
-
-#ifndef BASE_WIN_PE_IMAGE_H_
-#define BASE_WIN_PE_IMAGE_H_
-
-#include <windows.h>
-
-#if defined(_WIN32_WINNT_WIN8)
-// The Windows 8 SDK defines FACILITY_VISUALCPP in winerror.h.
-#undef FACILITY_VISUALCPP
-#endif
-#include <DelayIMP.h>
-
-namespace base {
-namespace win {
-
-// This class is a wrapper for the Portable Executable File Format (PE).
-// Its main purpose is to provide an easy way to work with imports and exports
-// from a file, mapped in memory as image.
-class PEImage {
- public:
- // Callback to enumerate sections.
- // cookie is the value passed to the enumerate method.
- // Returns true to continue the enumeration.
- typedef bool (*EnumSectionsFunction)(const PEImage &image,
- PIMAGE_SECTION_HEADER header,
- PVOID section_start, DWORD section_size,
- PVOID cookie);
-
- // Callback to enumerate exports.
- // function is the actual address of the symbol. If forward is not null, it
- // contains the dll and symbol to forward this export to. cookie is the value
- // passed to the enumerate method.
- // Returns true to continue the enumeration.
- typedef bool (*EnumExportsFunction)(const PEImage &image, DWORD ordinal,
- DWORD hint, LPCSTR name, PVOID function,
- LPCSTR forward, PVOID cookie);
-
- // Callback to enumerate import blocks.
- // name_table and iat point to the imports name table and address table for
- // this block. cookie is the value passed to the enumerate method.
- // Returns true to continue the enumeration.
- typedef bool (*EnumImportChunksFunction)(const PEImage &image, LPCSTR module,
- PIMAGE_THUNK_DATA name_table,
- PIMAGE_THUNK_DATA iat, PVOID cookie);
-
- // Callback to enumerate imports.
- // module is the dll that exports this symbol. cookie is the value passed to
- // the enumerate method.
- // Returns true to continue the enumeration.
- typedef bool (*EnumImportsFunction)(const PEImage &image, LPCSTR module,
- DWORD ordinal, LPCSTR name, DWORD hint,
- PIMAGE_THUNK_DATA iat, PVOID cookie);
-
- // Callback to enumerate dalayed import blocks.
- // module is the dll that exports this block of symbols. cookie is the value
- // passed to the enumerate method.
- // Returns true to continue the enumeration.
- typedef bool (*EnumDelayImportChunksFunction)(const PEImage &image,
- PImgDelayDescr delay_descriptor,
- LPCSTR module,
- PIMAGE_THUNK_DATA name_table,
- PIMAGE_THUNK_DATA iat,
- PVOID cookie);
-
- // Callback to enumerate relocations.
- // cookie is the value passed to the enumerate method.
- // Returns true to continue the enumeration.
- typedef bool (*EnumRelocsFunction)(const PEImage &image, WORD type,
- PVOID address, PVOID cookie);
-
- explicit PEImage(HMODULE module) : module_(module) {}
- explicit PEImage(const void* module) {
- module_ = reinterpret_cast<HMODULE>(const_cast<void*>(module));
- }
-
- virtual ~PEImage() {}
-
- // Gets the HMODULE for this object.
- HMODULE module() const;
-
- // Sets this object's HMODULE.
- void set_module(HMODULE module);
-
- // Checks if this symbol is actually an ordinal.
- static bool IsOrdinal(LPCSTR name);
-
- // Converts a named symbol to the corresponding ordinal.
- static WORD ToOrdinal(LPCSTR name);
-
- // Returns the DOS_HEADER for this PE.
- PIMAGE_DOS_HEADER GetDosHeader() const;
-
- // Returns the NT_HEADER for this PE.
- PIMAGE_NT_HEADERS GetNTHeaders() const;
-
- // Returns number of sections of this PE.
- WORD GetNumSections() const;
-
- // Returns the header for a given section.
- // returns NULL if there is no such section.
- PIMAGE_SECTION_HEADER GetSectionHeader(UINT section) const;
-
- // Returns the size of a given directory entry.
- DWORD GetImageDirectoryEntrySize(UINT directory) const;
-
- // Returns the address of a given directory entry.
- PVOID GetImageDirectoryEntryAddr(UINT directory) const;
-
- // Returns the section header for a given address.
- // Use: s = image.GetImageSectionFromAddr(a);
- // Post: 's' is the section header of the section that contains 'a'
- // or NULL if there is no such section.
- PIMAGE_SECTION_HEADER GetImageSectionFromAddr(PVOID address) const;
-
- // Returns the section header for a given section.
- PIMAGE_SECTION_HEADER GetImageSectionHeaderByName(LPCSTR section_name) const;
-
- // Returns the first block of imports.
- PIMAGE_IMPORT_DESCRIPTOR GetFirstImportChunk() const;
-
- // Returns the exports directory.
- PIMAGE_EXPORT_DIRECTORY GetExportDirectory() const;
-
- // Returns the debug id (guid+age).
- bool GetDebugId(LPGUID guid, LPDWORD age) const;
-
- // Returns a given export entry.
- // Use: e = image.GetExportEntry(f);
- // Pre: 'f' is either a zero terminated string or ordinal
- // Post: 'e' is a pointer to the export directory entry
- // that contains 'f's export RVA, or NULL if 'f'
- // is not exported from this image
- PDWORD GetExportEntry(LPCSTR name) const;
-
- // Returns the address for a given exported symbol.
- // Use: p = image.GetProcAddress(f);
- // Pre: 'f' is either a zero terminated string or ordinal.
- // Post: if 'f' is a non-forwarded export from image, 'p' is
- // the exported function. If 'f' is a forwarded export
- // then p is the special value -1. In this case
- // RVAToAddr(*GetExportEntry) can be used to resolve
- // the string that describes the forward.
- FARPROC GetProcAddress(LPCSTR function_name) const;
-
- // Retrieves the ordinal for a given exported symbol.
- // Returns true if the symbol was found.
- bool GetProcOrdinal(LPCSTR function_name, WORD *ordinal) const;
-
- // Enumerates PE sections.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumSections(EnumSectionsFunction callback, PVOID cookie) const;
-
- // Enumerates PE exports.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumExports(EnumExportsFunction callback, PVOID cookie) const;
-
- // Enumerates PE imports.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumAllImports(EnumImportsFunction callback, PVOID cookie) const;
-
- // Enumerates PE import blocks.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumImportChunks(EnumImportChunksFunction callback, PVOID cookie) const;
-
- // Enumerates the imports from a single PE import block.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumOneImportChunk(EnumImportsFunction callback, LPCSTR module_name,
- PIMAGE_THUNK_DATA name_table, PIMAGE_THUNK_DATA iat,
- PVOID cookie) const;
-
-
- // Enumerates PE delay imports.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumAllDelayImports(EnumImportsFunction callback, PVOID cookie) const;
-
- // Enumerates PE delay import blocks.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumDelayImportChunks(EnumDelayImportChunksFunction callback,
- PVOID cookie) const;
-
- // Enumerates imports from a single PE delay import block.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumOneDelayImportChunk(EnumImportsFunction callback,
- PImgDelayDescr delay_descriptor,
- LPCSTR module_name,
- PIMAGE_THUNK_DATA name_table,
- PIMAGE_THUNK_DATA iat,
- PVOID cookie) const;
-
- // Enumerates PE relocation entries.
- // cookie is a generic cookie to pass to the callback.
- // Returns true on success.
- bool EnumRelocs(EnumRelocsFunction callback, PVOID cookie) const;
-
- // Verifies the magic values on the PE file.
- // Returns true if all values are correct.
- bool VerifyMagic() const;
-
- // Converts an rva value to the appropriate address.
- virtual PVOID RVAToAddr(DWORD rva) const;
-
- // Converts an rva value to an offset on disk.
- // Returns true on success.
- bool ImageRVAToOnDiskOffset(DWORD rva, DWORD *on_disk_offset) const;
-
- // Converts an address to an offset on disk.
- // Returns true on success.
- bool ImageAddrToOnDiskOffset(LPVOID address, DWORD *on_disk_offset) const;
-
- private:
- HMODULE module_;
-};
-
-// This class is an extension to the PEImage class that allows working with PE
-// files mapped as data instead of as image file.
-class PEImageAsData : public PEImage {
- public:
- explicit PEImageAsData(HMODULE hModule) : PEImage(hModule) {}
-
- PVOID RVAToAddr(DWORD rva) const override;
-};
-
-inline bool PEImage::IsOrdinal(LPCSTR name) {
- return reinterpret_cast<uintptr_t>(name) <= 0xFFFF;
-}
-
-inline WORD PEImage::ToOrdinal(LPCSTR name) {
- return static_cast<WORD>(reinterpret_cast<intptr_t>(name));
-}
-
-inline HMODULE PEImage::module() const {
- return module_;
-}
-
-inline PIMAGE_IMPORT_DESCRIPTOR PEImage::GetFirstImportChunk() const {
- return reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>(
- GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_IMPORT));
-}
-
-inline PIMAGE_EXPORT_DIRECTORY PEImage::GetExportDirectory() const {
- return reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>(
- GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_EXPORT));
-}
-
-} // namespace win
-} // namespace base
-
-#endif // BASE_WIN_PE_IMAGE_H_
diff --git a/security/sandbox/chromium/base/win/scoped_handle.cc b/security/sandbox/chromium/base/win/scoped_handle.cc
deleted file mode 100644
index 9c21603a0..000000000
--- a/security/sandbox/chromium/base/win/scoped_handle.cc
+++ /dev/null
@@ -1,248 +0,0 @@
-// 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.
-
-#include "base/win/scoped_handle.h"
-
-#include <stddef.h>
-
-#include <unordered_map>
-
-#include "base/debug/alias.h"
-#include "base/hash.h"
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/synchronization/lock_impl.h"
-
-extern "C" {
-__declspec(dllexport) void* GetHandleVerifier();
-typedef void* (*GetHandleVerifierFn)();
-}
-
-namespace {
-
-struct HandleHash {
- size_t operator()(const HANDLE& handle) const {
- char buffer[sizeof(handle)];
- memcpy(buffer, &handle, sizeof(handle));
- return base::Hash(buffer, sizeof(buffer));
- }
-};
-
-struct Info {
- const void* owner;
- const void* pc1;
- const void* pc2;
- DWORD thread_id;
-};
-typedef std::unordered_map<HANDLE, Info, HandleHash> HandleMap;
-
-// g_lock protects the handle map and setting g_active_verifier.
-typedef base::internal::LockImpl NativeLock;
-base::LazyInstance<NativeLock>::Leaky g_lock = LAZY_INSTANCE_INITIALIZER;
-
-bool CloseHandleWrapper(HANDLE handle) {
- if (!::CloseHandle(handle))
- CHECK(false);
- return true;
-}
-
-// Simple automatic locking using a native critical section so it supports
-// recursive locking.
-class AutoNativeLock {
- public:
- explicit AutoNativeLock(NativeLock& lock) : lock_(lock) {
- lock_.Lock();
- }
-
- ~AutoNativeLock() {
- lock_.Unlock();
- }
-
- private:
- NativeLock& lock_;
- DISALLOW_COPY_AND_ASSIGN(AutoNativeLock);
-};
-
-// Implements the actual object that is verifying handles for this process.
-// The active instance is shared across the module boundary but there is no
-// way to delete this object from the wrong side of it (or any side, actually).
-class ActiveVerifier {
- public:
- explicit ActiveVerifier(bool enabled)
- : enabled_(enabled), closing_(false), lock_(g_lock.Pointer()) {
- }
-
- // Retrieves the current verifier.
- static ActiveVerifier* Get();
-
- // The methods required by HandleTraits. They are virtual because we need to
- // forward the call execution to another module, instead of letting the
- // compiler call the version that is linked in the current module.
- virtual bool CloseHandle(HANDLE handle);
- virtual void StartTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2);
- virtual void StopTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2);
- virtual void Disable();
- virtual void OnHandleBeingClosed(HANDLE handle);
-
- private:
- ~ActiveVerifier(); // Not implemented.
-
- static void InstallVerifier();
-
- bool enabled_;
- bool closing_;
- NativeLock* lock_;
- HandleMap map_;
- DISALLOW_COPY_AND_ASSIGN(ActiveVerifier);
-};
-ActiveVerifier* g_active_verifier = NULL;
-
-// static
-ActiveVerifier* ActiveVerifier::Get() {
- if (!g_active_verifier)
- ActiveVerifier::InstallVerifier();
-
- return g_active_verifier;
-}
-
-// static
-void ActiveVerifier::InstallVerifier() {
-#if defined(COMPONENT_BUILD)
- AutoNativeLock lock(g_lock.Get());
- g_active_verifier = new ActiveVerifier(true);
-#else
- // If you are reading this, wondering why your process seems deadlocked, take
- // a look at your DllMain code and remove things that should not be done
- // there, like doing whatever gave you that nice windows handle you are trying
- // to store in a ScopedHandle.
- HMODULE main_module = ::GetModuleHandle(NULL);
- GetHandleVerifierFn get_handle_verifier =
- reinterpret_cast<GetHandleVerifierFn>(::GetProcAddress(
- main_module, "GetHandleVerifier"));
-
- if (!get_handle_verifier) {
- g_active_verifier = new ActiveVerifier(false);
- return;
- }
-
- ActiveVerifier* verifier =
- reinterpret_cast<ActiveVerifier*>(get_handle_verifier());
-
- // This lock only protects against races in this module, which is fine.
- AutoNativeLock lock(g_lock.Get());
- g_active_verifier = verifier ? verifier : new ActiveVerifier(true);
-#endif
-}
-
-bool ActiveVerifier::CloseHandle(HANDLE handle) {
- if (!enabled_)
- return CloseHandleWrapper(handle);
-
- AutoNativeLock lock(*lock_);
- closing_ = true;
- CloseHandleWrapper(handle);
- closing_ = false;
-
- return true;
-}
-
-void ActiveVerifier::StartTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2) {
- if (!enabled_)
- return;
-
- // Grab the thread id before the lock.
- DWORD thread_id = GetCurrentThreadId();
-
- AutoNativeLock lock(*lock_);
-
- Info handle_info = { owner, pc1, pc2, thread_id };
- std::pair<HANDLE, Info> item(handle, handle_info);
- std::pair<HandleMap::iterator, bool> result = map_.insert(item);
- if (!result.second) {
- Info other = result.first->second;
- base::debug::Alias(&other);
- CHECK(false);
- }
-}
-
-void ActiveVerifier::StopTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2) {
- if (!enabled_)
- return;
-
- AutoNativeLock lock(*lock_);
- HandleMap::iterator i = map_.find(handle);
- if (i == map_.end())
- CHECK(false);
-
- Info other = i->second;
- if (other.owner != owner) {
- base::debug::Alias(&other);
- CHECK(false);
- }
-
- map_.erase(i);
-}
-
-void ActiveVerifier::Disable() {
- enabled_ = false;
-}
-
-void ActiveVerifier::OnHandleBeingClosed(HANDLE handle) {
- if (!enabled_)
- return;
-
- AutoNativeLock lock(*lock_);
- if (closing_)
- return;
-
- HandleMap::iterator i = map_.find(handle);
- if (i == map_.end())
- return;
-
- Info other = i->second;
- base::debug::Alias(&other);
- CHECK(false);
-}
-
-} // namespace
-
-void* GetHandleVerifier() {
- return g_active_verifier;
-}
-
-namespace base {
-namespace win {
-
-// Static.
-bool HandleTraits::CloseHandle(HANDLE handle) {
- return ActiveVerifier::Get()->CloseHandle(handle);
-}
-
-// Static.
-void VerifierTraits::StartTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2) {
- return ActiveVerifier::Get()->StartTracking(handle, owner, pc1, pc2);
-}
-
-// Static.
-void VerifierTraits::StopTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2) {
- return ActiveVerifier::Get()->StopTracking(handle, owner, pc1, pc2);
-}
-
-void DisableHandleVerifier() {
- return ActiveVerifier::Get()->Disable();
-}
-
-void OnHandleBeingClosed(HANDLE handle) {
- return ActiveVerifier::Get()->OnHandleBeingClosed(handle);
-}
-
-} // namespace win
-} // namespace base
diff --git a/security/sandbox/chromium/base/win/scoped_handle.h b/security/sandbox/chromium/base/win/scoped_handle.h
deleted file mode 100644
index 404ab6693..000000000
--- a/security/sandbox/chromium/base/win/scoped_handle.h
+++ /dev/null
@@ -1,182 +0,0 @@
-// 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.
-
-#ifndef BASE_WIN_SCOPED_HANDLE_H_
-#define BASE_WIN_SCOPED_HANDLE_H_
-
-#include <windows.h>
-
-#include "base/base_export.h"
-#include "base/location.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/move.h"
-
-// TODO(rvargas): remove this with the rest of the verifier.
-#if defined(COMPILER_MSVC)
-#include <intrin.h>
-#define BASE_WIN_GET_CALLER _ReturnAddress()
-#elif defined(COMPILER_GCC)
-#define BASE_WIN_GET_CALLER __builtin_extract_return_addr(\\
- __builtin_return_address(0))
-#endif
-
-namespace base {
-namespace win {
-
-// Generic wrapper for raw handles that takes care of closing handles
-// automatically. The class interface follows the style of
-// the ScopedFILE class with two additions:
-// - IsValid() method can tolerate multiple invalid handle values such as NULL
-// and INVALID_HANDLE_VALUE (-1) for Win32 handles.
-// - Set() (and the constructors and assignment operators that call it)
-// preserve the Windows LastError code. This ensures that GetLastError() can
-// be called after stashing a handle in a GenericScopedHandle object. Doing
-// this explicitly is necessary because of bug 528394 and VC++ 2015.
-template <class Traits, class Verifier>
-class GenericScopedHandle {
- MOVE_ONLY_TYPE_FOR_CPP_03(GenericScopedHandle)
-
- public:
- typedef typename Traits::Handle Handle;
-
- GenericScopedHandle() : handle_(Traits::NullHandle()) {}
-
- explicit GenericScopedHandle(Handle handle) : handle_(Traits::NullHandle()) {
- Set(handle);
- }
-
- GenericScopedHandle(GenericScopedHandle&& other)
- : handle_(Traits::NullHandle()) {
- Set(other.Take());
- }
-
- ~GenericScopedHandle() {
- Close();
- }
-
- bool IsValid() const {
- return Traits::IsHandleValid(handle_);
- }
-
- GenericScopedHandle& operator=(GenericScopedHandle&& other) {
- DCHECK_NE(this, &other);
- Set(other.Take());
- return *this;
- }
-
- void Set(Handle handle) {
- if (handle_ != handle) {
- // Preserve old LastError to avoid bug 528394.
- auto last_error = ::GetLastError();
- Close();
-
- if (Traits::IsHandleValid(handle)) {
- handle_ = handle;
- Verifier::StartTracking(handle, this, BASE_WIN_GET_CALLER,
- tracked_objects::GetProgramCounter());
- }
- ::SetLastError(last_error);
- }
- }
-
- Handle Get() const {
- return handle_;
- }
-
- // Transfers ownership away from this object.
- Handle Take() {
- Handle temp = handle_;
- handle_ = Traits::NullHandle();
- if (Traits::IsHandleValid(temp)) {
- Verifier::StopTracking(temp, this, BASE_WIN_GET_CALLER,
- tracked_objects::GetProgramCounter());
- }
- return temp;
- }
-
- // Explicitly closes the owned handle.
- void Close() {
- if (Traits::IsHandleValid(handle_)) {
- Verifier::StopTracking(handle_, this, BASE_WIN_GET_CALLER,
- tracked_objects::GetProgramCounter());
-
- Traits::CloseHandle(handle_);
- handle_ = Traits::NullHandle();
- }
- }
-
- private:
- Handle handle_;
-};
-
-#undef BASE_WIN_GET_CALLER
-
-// The traits class for Win32 handles that can be closed via CloseHandle() API.
-class HandleTraits {
- public:
- typedef HANDLE Handle;
-
- // Closes the handle.
- static bool BASE_EXPORT CloseHandle(HANDLE handle);
-
- // Returns true if the handle value is valid.
- static bool IsHandleValid(HANDLE handle) {
- return handle != NULL && handle != INVALID_HANDLE_VALUE;
- }
-
- // Returns NULL handle value.
- static HANDLE NullHandle() {
- return NULL;
- }
-
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(HandleTraits);
-};
-
-// Do-nothing verifier.
-class DummyVerifierTraits {
- public:
- typedef HANDLE Handle;
-
- static void StartTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2) {}
- static void StopTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2) {}
-
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(DummyVerifierTraits);
-};
-
-// Performs actual run-time tracking.
-class BASE_EXPORT VerifierTraits {
- public:
- typedef HANDLE Handle;
-
- static void StartTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2);
- static void StopTracking(HANDLE handle, const void* owner,
- const void* pc1, const void* pc2);
-
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(VerifierTraits);
-};
-
-typedef GenericScopedHandle<HandleTraits, VerifierTraits> ScopedHandle;
-
-// This function may be called by the embedder to disable the use of
-// VerifierTraits at runtime. It has no effect if DummyVerifierTraits is used
-// for ScopedHandle.
-void BASE_EXPORT DisableHandleVerifier();
-
-// This should be called whenever the OS is closing a handle, if extended
-// verification of improper handle closing is desired. If |handle| is being
-// tracked by the handle verifier and ScopedHandle is not the one closing it,
-// a CHECK is generated.
-void BASE_EXPORT OnHandleBeingClosed(HANDLE handle);
-
-} // namespace win
-} // namespace base
-
-#endif // BASE_WIN_SCOPED_HANDLE_H_
diff --git a/security/sandbox/chromium/base/win/scoped_process_information.cc b/security/sandbox/chromium/base/win/scoped_process_information.cc
deleted file mode 100644
index 634a538ee..000000000
--- a/security/sandbox/chromium/base/win/scoped_process_information.cc
+++ /dev/null
@@ -1,147 +0,0 @@
-// 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.
-
-#include "base/win/scoped_process_information.h"
-
-#include "base/logging.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_version.h"
-
-namespace base {
-namespace win {
-
-namespace {
-
-// Duplicates source into target, returning true upon success. |target| is
-// guaranteed to be untouched in case of failure. Succeeds with no side-effects
-// if source is NULL.
-bool CheckAndDuplicateHandle(HANDLE source, ScopedHandle* target) {
- if (!source)
- return true;
-
- HANDLE temp = NULL;
-
- // TODO(shrikant): Remove following code as soon as we gather some
- // information regarding AppContainer related DuplicateHandle failures that
- // only seem to happen on certain machine and only random launches (normally
- // renderer launches seem to succeed even on those machines.)
- if (base::win::GetVersion() == base::win::VERSION_WIN8 ||
- base::win::GetVersion() == base::win::VERSION_WIN8_1) {
- typedef LONG (WINAPI *NtDuplicateObject)(
- IN HANDLE SourceProcess,
- IN HANDLE SourceHandle,
- IN HANDLE TargetProcess,
- OUT PHANDLE TargetHandle,
- IN ACCESS_MASK DesiredAccess,
- IN ULONG Attributes,
- IN ULONG Options);
-
- typedef ULONG (WINAPI *RtlNtStatusToDosError)(IN LONG Status);
-
- NtDuplicateObject nt_duplicate_object =
- reinterpret_cast<NtDuplicateObject>(::GetProcAddress(
- GetModuleHandle(L"ntdll.dll"), "NtDuplicateObject"));
- if (nt_duplicate_object != NULL) {
- LONG status = nt_duplicate_object(::GetCurrentProcess(), source,
- ::GetCurrentProcess(), &temp,
- 0, FALSE, DUPLICATE_SAME_ACCESS);
- if (status < 0) {
- DPLOG(ERROR) << "Failed to duplicate a handle.";
- RtlNtStatusToDosError ntstatus_to_doserror =
- reinterpret_cast<RtlNtStatusToDosError>(::GetProcAddress(
- GetModuleHandle(L"ntdll.dll"), "RtlNtStatusToDosError"));
- if (ntstatus_to_doserror != NULL) {
- ::SetLastError(ntstatus_to_doserror(status));
- }
- return false;
- }
- }
- } else {
- if (!::DuplicateHandle(::GetCurrentProcess(), source,
- ::GetCurrentProcess(), &temp, 0, FALSE,
- DUPLICATE_SAME_ACCESS)) {
- DPLOG(ERROR) << "Failed to duplicate a handle.";
- return false;
- }
- }
- target->Set(temp);
- return true;
-}
-
-} // namespace
-
-ScopedProcessInformation::ScopedProcessInformation()
- : process_id_(0), thread_id_(0) {
-}
-
-ScopedProcessInformation::ScopedProcessInformation(
- const PROCESS_INFORMATION& process_info) : process_id_(0), thread_id_(0) {
- Set(process_info);
-}
-
-ScopedProcessInformation::~ScopedProcessInformation() {
- Close();
-}
-
-bool ScopedProcessInformation::IsValid() const {
- return process_id_ || process_handle_.Get() ||
- thread_id_ || thread_handle_.Get();
-}
-
-void ScopedProcessInformation::Close() {
- process_handle_.Close();
- thread_handle_.Close();
- process_id_ = 0;
- thread_id_ = 0;
-}
-
-void ScopedProcessInformation::Set(const PROCESS_INFORMATION& process_info) {
- if (IsValid())
- Close();
-
- process_handle_.Set(process_info.hProcess);
- thread_handle_.Set(process_info.hThread);
- process_id_ = process_info.dwProcessId;
- thread_id_ = process_info.dwThreadId;
-}
-
-bool ScopedProcessInformation::DuplicateFrom(
- const ScopedProcessInformation& other) {
- DCHECK(!IsValid()) << "target ScopedProcessInformation must be NULL";
- DCHECK(other.IsValid()) << "source ScopedProcessInformation must be valid";
-
- if (CheckAndDuplicateHandle(other.process_handle(), &process_handle_) &&
- CheckAndDuplicateHandle(other.thread_handle(), &thread_handle_)) {
- process_id_ = other.process_id();
- thread_id_ = other.thread_id();
- return true;
- }
-
- return false;
-}
-
-PROCESS_INFORMATION ScopedProcessInformation::Take() {
- PROCESS_INFORMATION process_information = {};
- process_information.hProcess = process_handle_.Take();
- process_information.hThread = thread_handle_.Take();
- process_information.dwProcessId = process_id();
- process_information.dwThreadId = thread_id();
- process_id_ = 0;
- thread_id_ = 0;
-
- return process_information;
-}
-
-HANDLE ScopedProcessInformation::TakeProcessHandle() {
- process_id_ = 0;
- return process_handle_.Take();
-}
-
-HANDLE ScopedProcessInformation::TakeThreadHandle() {
- thread_id_ = 0;
- return thread_handle_.Take();
-}
-
-} // namespace win
-} // namespace base
diff --git a/security/sandbox/chromium/base/win/scoped_process_information.h b/security/sandbox/chromium/base/win/scoped_process_information.h
deleted file mode 100644
index 01df861f0..000000000
--- a/security/sandbox/chromium/base/win/scoped_process_information.h
+++ /dev/null
@@ -1,83 +0,0 @@
-// 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.
-
-#ifndef BASE_WIN_SCOPED_PROCESS_INFORMATION_H_
-#define BASE_WIN_SCOPED_PROCESS_INFORMATION_H_
-
-#include <windows.h>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-#include "base/win/scoped_handle.h"
-
-namespace base {
-namespace win {
-
-// Manages the closing of process and thread handles from PROCESS_INFORMATION
-// structures. Allows clients to take ownership of either handle independently.
-class BASE_EXPORT ScopedProcessInformation {
- public:
- ScopedProcessInformation();
- explicit ScopedProcessInformation(const PROCESS_INFORMATION& process_info);
- ~ScopedProcessInformation();
-
- // Returns true iff this instance is holding a thread and/or process handle.
- bool IsValid() const;
-
- // Closes the held thread and process handles, if any.
- void Close();
-
- // Populates this instance with the provided |process_info|.
- void Set(const PROCESS_INFORMATION& process_info);
-
- // Populates this instance with duplicate handles and the thread/process IDs
- // from |other|. Returns false in case of failure, in which case this instance
- // will be completely unpopulated.
- bool DuplicateFrom(const ScopedProcessInformation& other);
-
- // Transfers ownership of the held PROCESS_INFORMATION, if any, away from this
- // instance.
- PROCESS_INFORMATION Take();
-
- // Transfers ownership of the held process handle, if any, away from this
- // instance. Note that the related process_id will also be cleared.
- HANDLE TakeProcessHandle();
-
- // Transfers ownership of the held thread handle, if any, away from this
- // instance. Note that the related thread_id will also be cleared.
- HANDLE TakeThreadHandle();
-
- // Returns the held process handle, if any, while retaining ownership.
- HANDLE process_handle() const {
- return process_handle_.Get();
- }
-
- // Returns the held thread handle, if any, while retaining ownership.
- HANDLE thread_handle() const {
- return thread_handle_.Get();
- }
-
- // Returns the held process id, if any.
- DWORD process_id() const {
- return process_id_;
- }
-
- // Returns the held thread id, if any.
- DWORD thread_id() const {
- return thread_id_;
- }
-
- private:
- ScopedHandle process_handle_;
- ScopedHandle thread_handle_;
- DWORD process_id_;
- DWORD thread_id_;
-
- DISALLOW_COPY_AND_ASSIGN(ScopedProcessInformation);
-};
-
-} // namespace win
-} // namespace base
-
-#endif // BASE_WIN_SCOPED_PROCESS_INFORMATION_H_
diff --git a/security/sandbox/chromium/base/win/startup_information.cc b/security/sandbox/chromium/base/win/startup_information.cc
deleted file mode 100644
index aff52eb79..000000000
--- a/security/sandbox/chromium/base/win/startup_information.cc
+++ /dev/null
@@ -1,109 +0,0 @@
-// 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.
-
-#include "base/win/startup_information.h"
-
-#include "base/logging.h"
-#include "base/win/windows_version.h"
-
-namespace {
-
-typedef BOOL (WINAPI *InitializeProcThreadAttributeListFunction)(
- LPPROC_THREAD_ATTRIBUTE_LIST attribute_list,
- DWORD attribute_count,
- DWORD flags,
- PSIZE_T size);
-static InitializeProcThreadAttributeListFunction
- initialize_proc_thread_attribute_list;
-
-typedef BOOL (WINAPI *UpdateProcThreadAttributeFunction)(
- LPPROC_THREAD_ATTRIBUTE_LIST attribute_list,
- DWORD flags,
- DWORD_PTR attribute,
- PVOID value,
- SIZE_T size,
- PVOID previous_value,
- PSIZE_T return_size);
-static UpdateProcThreadAttributeFunction update_proc_thread_attribute_list;
-
-typedef VOID (WINAPI *DeleteProcThreadAttributeListFunction)(
- LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList);
-static DeleteProcThreadAttributeListFunction delete_proc_thread_attribute_list;
-
-} // namespace
-
-namespace base {
-namespace win {
-
-StartupInformation::StartupInformation() {
- memset(&startup_info_, 0, sizeof(startup_info_));
-
- // Pre Windows Vista doesn't support STARTUPINFOEX.
- if (base::win::GetVersion() < base::win::VERSION_VISTA) {
- startup_info_.StartupInfo.cb = sizeof(STARTUPINFO);
- return;
- }
-
- startup_info_.StartupInfo.cb = sizeof(startup_info_);
-
- // Load the attribute API functions.
- if (!initialize_proc_thread_attribute_list ||
- !update_proc_thread_attribute_list ||
- !delete_proc_thread_attribute_list) {
- HMODULE module = ::GetModuleHandleW(L"kernel32.dll");
- initialize_proc_thread_attribute_list =
- reinterpret_cast<InitializeProcThreadAttributeListFunction>(
- ::GetProcAddress(module, "InitializeProcThreadAttributeList"));
- update_proc_thread_attribute_list =
- reinterpret_cast<UpdateProcThreadAttributeFunction>(
- ::GetProcAddress(module, "UpdateProcThreadAttribute"));
- delete_proc_thread_attribute_list =
- reinterpret_cast<DeleteProcThreadAttributeListFunction>(
- ::GetProcAddress(module, "DeleteProcThreadAttributeList"));
- }
-}
-
-StartupInformation::~StartupInformation() {
- if (startup_info_.lpAttributeList) {
- delete_proc_thread_attribute_list(startup_info_.lpAttributeList);
- delete [] reinterpret_cast<BYTE*>(startup_info_.lpAttributeList);
- }
-}
-
-bool StartupInformation::InitializeProcThreadAttributeList(
- DWORD attribute_count) {
- if (startup_info_.StartupInfo.cb != sizeof(startup_info_) ||
- startup_info_.lpAttributeList)
- return false;
-
- SIZE_T size = 0;
- initialize_proc_thread_attribute_list(NULL, attribute_count, 0, &size);
- if (size == 0)
- return false;
-
- startup_info_.lpAttributeList =
- reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(new BYTE[size]);
- if (!initialize_proc_thread_attribute_list(startup_info_.lpAttributeList,
- attribute_count, 0, &size)) {
- delete [] reinterpret_cast<BYTE*>(startup_info_.lpAttributeList);
- startup_info_.lpAttributeList = NULL;
- return false;
- }
-
- return true;
-}
-
-bool StartupInformation::UpdateProcThreadAttribute(
- DWORD_PTR attribute,
- void* value,
- size_t size) {
- if (!startup_info_.lpAttributeList)
- return false;
- return !!update_proc_thread_attribute_list(startup_info_.lpAttributeList, 0,
- attribute, value, size, NULL, NULL);
-}
-
-} // namespace win
-} // namespace base
-
diff --git a/security/sandbox/chromium/base/win/startup_information.h b/security/sandbox/chromium/base/win/startup_information.h
deleted file mode 100644
index 5b777baef..000000000
--- a/security/sandbox/chromium/base/win/startup_information.h
+++ /dev/null
@@ -1,51 +0,0 @@
-// 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.
-
-#ifndef BASE_WIN_STARTUP_INFORMATION_H_
-#define BASE_WIN_STARTUP_INFORMATION_H_
-
-#include <windows.h>
-#include <stddef.h>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-
-namespace base {
-namespace win {
-
-// Manages the lifetime of additional attributes in STARTUPINFOEX.
-class BASE_EXPORT StartupInformation {
- public:
- StartupInformation();
-
- ~StartupInformation();
-
- // Initialize the attribute list for the specified number of entries.
- bool InitializeProcThreadAttributeList(DWORD attribute_count);
-
- // Sets one entry in the initialized attribute list.
- // |value| needs to live at least as long as the StartupInformation object
- // this is called on.
- bool UpdateProcThreadAttribute(DWORD_PTR attribute,
- void* value,
- size_t size);
-
- LPSTARTUPINFOW startup_info() { return &startup_info_.StartupInfo; }
- LPSTARTUPINFOW startup_info() const {
- return const_cast<const LPSTARTUPINFOW>(&startup_info_.StartupInfo);
- }
-
- bool has_extended_startup_info() const {
- return !!startup_info_.lpAttributeList;
- }
-
- private:
- STARTUPINFOEXW startup_info_;
- DISALLOW_COPY_AND_ASSIGN(StartupInformation);
-};
-
-} // namespace win
-} // namespace base
-
-#endif // BASE_WIN_STARTUP_INFORMATION_H_
diff --git a/security/sandbox/chromium/base/win/windows_version.cc b/security/sandbox/chromium/base/win/windows_version.cc
deleted file mode 100644
index eb3f4993d..000000000
--- a/security/sandbox/chromium/base/win/windows_version.cc
+++ /dev/null
@@ -1,225 +0,0 @@
-// 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.
-
-#include "base/win/windows_version.h"
-
-#include <windows.h>
-
-#include "base/file_version_info_win.h"
-#include "base/files/file_path.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/strings/utf_string_conversions.h"
-#include "base/win/registry.h"
-
-namespace {
-typedef BOOL (WINAPI *GetProductInfoPtr)(DWORD, DWORD, DWORD, DWORD, PDWORD);
-} // namespace
-
-namespace base {
-namespace win {
-
-namespace {
-
-// Helper to map a major.minor.x.build version (e.g. 6.1) to a Windows release.
-Version MajorMinorBuildToVersion(int major, int minor, int build) {
- if ((major == 5) && (minor > 0)) {
- // Treat XP Pro x64, Home Server, and Server 2003 R2 as Server 2003.
- return (minor == 1) ? VERSION_XP : VERSION_SERVER_2003;
- } else if (major == 6) {
- switch (minor) {
- case 0:
- // Treat Windows Server 2008 the same as Windows Vista.
- return VERSION_VISTA;
- case 1:
- // Treat Windows Server 2008 R2 the same as Windows 7.
- return VERSION_WIN7;
- case 2:
- // Treat Windows Server 2012 the same as Windows 8.
- return VERSION_WIN8;
- default:
- DCHECK_EQ(minor, 3);
- return VERSION_WIN8_1;
- }
- } else if (major == 10) {
- if (build < 10586) {
- return VERSION_WIN10;
- } else {
- return VERSION_WIN10_TH2;
- }
- } else if (major > 6) {
- NOTREACHED();
- return VERSION_WIN_LAST;
- }
-
- return VERSION_PRE_XP;
-}
-
-// Retrieve a version from kernel32. This is useful because when running in
-// compatibility mode for a down-level version of the OS, the file version of
-// kernel32 will still be the "real" version.
-Version GetVersionFromKernel32() {
- scoped_ptr<FileVersionInfoWin> file_version_info(
- static_cast<FileVersionInfoWin*>(
- FileVersionInfoWin::CreateFileVersionInfo(
- base::FilePath(FILE_PATH_LITERAL("kernel32.dll")))));
- if (file_version_info) {
- const int major =
- HIWORD(file_version_info->fixed_file_info()->dwFileVersionMS);
- const int minor =
- LOWORD(file_version_info->fixed_file_info()->dwFileVersionMS);
- const int build =
- HIWORD(file_version_info->fixed_file_info()->dwFileVersionLS);
- return MajorMinorBuildToVersion(major, minor, build);
- }
-
- NOTREACHED();
- return VERSION_WIN_LAST;
-}
-
-} // namespace
-
-// static
-OSInfo* OSInfo::GetInstance() {
- // Note: we don't use the Singleton class because it depends on AtExitManager,
- // and it's convenient for other modules to use this classs without it. This
- // pattern is copied from gurl.cc.
- static OSInfo* info;
- if (!info) {
- OSInfo* new_info = new OSInfo();
- if (InterlockedCompareExchangePointer(
- reinterpret_cast<PVOID*>(&info), new_info, NULL)) {
- delete new_info;
- }
- }
- return info;
-}
-
-OSInfo::OSInfo()
- : version_(VERSION_PRE_XP),
- kernel32_version_(VERSION_PRE_XP),
- got_kernel32_version_(false),
- architecture_(OTHER_ARCHITECTURE),
- wow64_status_(GetWOW64StatusForProcess(GetCurrentProcess())) {
- OSVERSIONINFOEX version_info = { sizeof version_info };
- ::GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&version_info));
- version_number_.major = version_info.dwMajorVersion;
- version_number_.minor = version_info.dwMinorVersion;
- version_number_.build = version_info.dwBuildNumber;
- version_ = MajorMinorBuildToVersion(
- version_number_.major, version_number_.minor, version_number_.build);
- service_pack_.major = version_info.wServicePackMajor;
- service_pack_.minor = version_info.wServicePackMinor;
-
- SYSTEM_INFO system_info = {};
- ::GetNativeSystemInfo(&system_info);
- switch (system_info.wProcessorArchitecture) {
- case PROCESSOR_ARCHITECTURE_INTEL: architecture_ = X86_ARCHITECTURE; break;
- case PROCESSOR_ARCHITECTURE_AMD64: architecture_ = X64_ARCHITECTURE; break;
- case PROCESSOR_ARCHITECTURE_IA64: architecture_ = IA64_ARCHITECTURE; break;
- }
- processors_ = system_info.dwNumberOfProcessors;
- allocation_granularity_ = system_info.dwAllocationGranularity;
-
- GetProductInfoPtr get_product_info;
- DWORD os_type;
-
- if (version_info.dwMajorVersion == 6 || version_info.dwMajorVersion == 10) {
- // Only present on Vista+.
- get_product_info = reinterpret_cast<GetProductInfoPtr>(
- ::GetProcAddress(::GetModuleHandle(L"kernel32.dll"), "GetProductInfo"));
-
- get_product_info(version_info.dwMajorVersion, version_info.dwMinorVersion,
- 0, 0, &os_type);
- switch (os_type) {
- case PRODUCT_CLUSTER_SERVER:
- case PRODUCT_DATACENTER_SERVER:
- case PRODUCT_DATACENTER_SERVER_CORE:
- case PRODUCT_ENTERPRISE_SERVER:
- case PRODUCT_ENTERPRISE_SERVER_CORE:
- case PRODUCT_ENTERPRISE_SERVER_IA64:
- case PRODUCT_SMALLBUSINESS_SERVER:
- case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM:
- case PRODUCT_STANDARD_SERVER:
- case PRODUCT_STANDARD_SERVER_CORE:
- case PRODUCT_WEB_SERVER:
- version_type_ = SUITE_SERVER;
- break;
- case PRODUCT_PROFESSIONAL:
- case PRODUCT_ULTIMATE:
- case PRODUCT_ENTERPRISE:
- case PRODUCT_BUSINESS:
- version_type_ = SUITE_PROFESSIONAL;
- break;
- case PRODUCT_HOME_BASIC:
- case PRODUCT_HOME_PREMIUM:
- case PRODUCT_STARTER:
- default:
- version_type_ = SUITE_HOME;
- break;
- }
- } else if (version_info.dwMajorVersion == 5 &&
- version_info.dwMinorVersion == 2) {
- if (version_info.wProductType == VER_NT_WORKSTATION &&
- system_info.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
- version_type_ = SUITE_PROFESSIONAL;
- } else if (version_info.wSuiteMask & VER_SUITE_WH_SERVER ) {
- version_type_ = SUITE_HOME;
- } else {
- version_type_ = SUITE_SERVER;
- }
- } else if (version_info.dwMajorVersion == 5 &&
- version_info.dwMinorVersion == 1) {
- if(version_info.wSuiteMask & VER_SUITE_PERSONAL)
- version_type_ = SUITE_HOME;
- else
- version_type_ = SUITE_PROFESSIONAL;
- } else {
- // Windows is pre XP so we don't care but pick a safe default.
- version_type_ = SUITE_HOME;
- }
-}
-
-OSInfo::~OSInfo() {
-}
-
-Version OSInfo::Kernel32Version() const {
- if (!got_kernel32_version_) {
- kernel32_version_ = GetVersionFromKernel32();
- got_kernel32_version_ = true;
- }
- return kernel32_version_;
-}
-
-std::string OSInfo::processor_model_name() {
- if (processor_model_name_.empty()) {
- const wchar_t kProcessorNameString[] =
- L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0";
- base::win::RegKey key(HKEY_LOCAL_MACHINE, kProcessorNameString, KEY_READ);
- string16 value;
- key.ReadValue(L"ProcessorNameString", &value);
- processor_model_name_ = UTF16ToUTF8(value);
- }
- return processor_model_name_;
-}
-
-// static
-OSInfo::WOW64Status OSInfo::GetWOW64StatusForProcess(HANDLE process_handle) {
- typedef BOOL (WINAPI* IsWow64ProcessFunc)(HANDLE, PBOOL);
- IsWow64ProcessFunc is_wow64_process = reinterpret_cast<IsWow64ProcessFunc>(
- GetProcAddress(GetModuleHandle(L"kernel32.dll"), "IsWow64Process"));
- if (!is_wow64_process)
- return WOW64_DISABLED;
- BOOL is_wow64 = FALSE;
- if (!(*is_wow64_process)(process_handle, &is_wow64))
- return WOW64_UNKNOWN;
- return is_wow64 ? WOW64_ENABLED : WOW64_DISABLED;
-}
-
-Version GetVersion() {
- return OSInfo::GetInstance()->version();
-}
-
-} // namespace win
-} // namespace base
diff --git a/security/sandbox/chromium/base/win/windows_version.h b/security/sandbox/chromium/base/win/windows_version.h
deleted file mode 100644
index 7bc8b6fe5..000000000
--- a/security/sandbox/chromium/base/win/windows_version.h
+++ /dev/null
@@ -1,133 +0,0 @@
-// 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.
-
-#ifndef BASE_WIN_WINDOWS_VERSION_H_
-#define BASE_WIN_WINDOWS_VERSION_H_
-
-#include <stddef.h>
-
-#include <string>
-
-#include "base/base_export.h"
-#include "base/macros.h"
-
-typedef void* HANDLE;
-
-namespace base {
-namespace win {
-
-// The running version of Windows. This is declared outside OSInfo for
-// syntactic sugar reasons; see the declaration of GetVersion() below.
-// NOTE: Keep these in order so callers can do things like
-// "if (base::win::GetVersion() >= base::win::VERSION_VISTA) ...".
-//
-// This enum is used in metrics histograms, so they shouldn't be reordered or
-// removed. New values can be added before VERSION_WIN_LAST.
-enum Version {
- VERSION_PRE_XP = 0, // Not supported.
- VERSION_XP = 1,
- VERSION_SERVER_2003 = 2, // Also includes XP Pro x64 and Server 2003 R2.
- VERSION_VISTA = 3, // Also includes Windows Server 2008.
- VERSION_WIN7 = 4, // Also includes Windows Server 2008 R2.
- VERSION_WIN8 = 5, // Also includes Windows Server 2012.
- VERSION_WIN8_1 = 6, // Also includes Windows Server 2012 R2.
- VERSION_WIN10 = 7, // Also includes Windows 10 Server.
- VERSION_WIN10_TH2 = 8, // Threshold 2: Version 1511, Build 10586.
- VERSION_WIN_LAST, // Indicates error condition.
-};
-
-// A rough bucketing of the available types of versions of Windows. This is used
-// to distinguish enterprise enabled versions from home versions and potentially
-// server versions.
-enum VersionType {
- SUITE_HOME,
- SUITE_PROFESSIONAL,
- SUITE_SERVER,
- SUITE_LAST,
-};
-
-// A singleton that can be used to query various pieces of information about the
-// OS and process state. Note that this doesn't use the base Singleton class, so
-// it can be used without an AtExitManager.
-class BASE_EXPORT OSInfo {
- public:
- struct VersionNumber {
- int major;
- int minor;
- int build;
- };
-
- struct ServicePack {
- int major;
- int minor;
- };
-
- // The processor architecture this copy of Windows natively uses. For
- // example, given an x64-capable processor, we have three possibilities:
- // 32-bit Chrome running on 32-bit Windows: X86_ARCHITECTURE
- // 32-bit Chrome running on 64-bit Windows via WOW64: X64_ARCHITECTURE
- // 64-bit Chrome running on 64-bit Windows: X64_ARCHITECTURE
- enum WindowsArchitecture {
- X86_ARCHITECTURE,
- X64_ARCHITECTURE,
- IA64_ARCHITECTURE,
- OTHER_ARCHITECTURE,
- };
-
- // Whether a process is running under WOW64 (the wrapper that allows 32-bit
- // processes to run on 64-bit versions of Windows). This will return
- // WOW64_DISABLED for both "32-bit Chrome on 32-bit Windows" and "64-bit
- // Chrome on 64-bit Windows". WOW64_UNKNOWN means "an error occurred", e.g.
- // the process does not have sufficient access rights to determine this.
- enum WOW64Status {
- WOW64_DISABLED,
- WOW64_ENABLED,
- WOW64_UNKNOWN,
- };
-
- static OSInfo* GetInstance();
-
- Version version() const { return version_; }
- Version Kernel32Version() const;
- // The next two functions return arrays of values, [major, minor(, build)].
- VersionNumber version_number() const { return version_number_; }
- VersionType version_type() const { return version_type_; }
- ServicePack service_pack() const { return service_pack_; }
- WindowsArchitecture architecture() const { return architecture_; }
- int processors() const { return processors_; }
- size_t allocation_granularity() const { return allocation_granularity_; }
- WOW64Status wow64_status() const { return wow64_status_; }
- std::string processor_model_name();
-
- // Like wow64_status(), but for the supplied handle instead of the current
- // process. This doesn't touch member state, so you can bypass the singleton.
- static WOW64Status GetWOW64StatusForProcess(HANDLE process_handle);
-
- private:
- OSInfo();
- ~OSInfo();
-
- Version version_;
- mutable Version kernel32_version_;
- mutable bool got_kernel32_version_;
- VersionNumber version_number_;
- VersionType version_type_;
- ServicePack service_pack_;
- WindowsArchitecture architecture_;
- int processors_;
- size_t allocation_granularity_;
- WOW64Status wow64_status_;
- std::string processor_model_name_;
-
- DISALLOW_COPY_AND_ASSIGN(OSInfo);
-};
-
-// Because this is by far the most commonly-requested value from the above
-// singleton, we add a global-scope accessor here as syntactic sugar.
-BASE_EXPORT Version GetVersion();
-
-} // namespace win
-} // namespace base
-
-#endif // BASE_WIN_WINDOWS_VERSION_H_
diff --git a/security/sandbox/chromium/build/build_config.h b/security/sandbox/chromium/build/build_config.h
deleted file mode 100644
index d8c3db6ed..000000000
--- a/security/sandbox/chromium/build/build_config.h
+++ /dev/null
@@ -1,168 +0,0 @@
-// 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 file adds defines about the platform we're currently building on.
-// Operating System:
-// OS_WIN / OS_MACOSX / OS_LINUX / OS_POSIX (MACOSX or LINUX) /
-// OS_NACL (NACL_SFI or NACL_NONSFI) / OS_NACL_SFI / OS_NACL_NONSFI
-// Compiler:
-// COMPILER_MSVC / COMPILER_GCC
-// Processor:
-// ARCH_CPU_X86 / ARCH_CPU_X86_64 / ARCH_CPU_X86_FAMILY (X86 or X86_64)
-// ARCH_CPU_32_BITS / ARCH_CPU_64_BITS
-
-#ifndef BUILD_BUILD_CONFIG_H_
-#define BUILD_BUILD_CONFIG_H_
-
-// A set of macros to use for platform detection.
-#if defined(__native_client__)
-// __native_client__ must be first, so that other OS_ defines are not set.
-#define OS_NACL 1
-// OS_NACL comes in two sandboxing technology flavors, SFI or Non-SFI.
-// PNaCl toolchain defines __native_client_nonsfi__ macro in Non-SFI build
-// mode, while it does not in SFI build mode.
-#if defined(__native_client_nonsfi__)
-#define OS_NACL_NONSFI
-#else
-#define OS_NACL_SFI
-#endif
-#elif defined(ANDROID)
-#define OS_ANDROID 1
-#elif defined(__APPLE__)
-// only include TargetConditions after testing ANDROID as some android builds
-// on mac don't have this header available and it's not needed unless the target
-// is really mac/ios.
-#include <TargetConditionals.h>
-#define OS_MACOSX 1
-#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
-#define OS_IOS 1
-#endif // defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
-#elif defined(__linux__)
-#define OS_LINUX 1
-// include a system header to pull in features.h for glibc/uclibc macros.
-#include <unistd.h>
-#if defined(__GLIBC__) && !defined(__UCLIBC__)
-// we really are using glibc, not uClibc pretending to be glibc
-#define LIBC_GLIBC 1
-#endif
-#elif defined(_WIN32)
-#define OS_WIN 1
-#define TOOLKIT_VIEWS 1
-#elif defined(__FreeBSD__)
-#define OS_FREEBSD 1
-#elif defined(__OpenBSD__)
-#define OS_OPENBSD 1
-#elif defined(__sun)
-#define OS_SOLARIS 1
-#elif defined(__QNXNTO__)
-#define OS_QNX 1
-#else
-#error Please add support for your platform in build/build_config.h
-#endif
-
-#if defined(USE_OPENSSL_CERTS) && defined(USE_NSS_CERTS)
-#error Cannot use both OpenSSL and NSS for certificates
-#endif
-
-// For access to standard BSD features, use OS_BSD instead of a
-// more specific macro.
-#if defined(OS_FREEBSD) || defined(OS_OPENBSD)
-#define OS_BSD 1
-#endif
-
-// For access to standard POSIXish features, use OS_POSIX instead of a
-// more specific macro.
-#if defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_FREEBSD) || \
- defined(OS_OPENBSD) || defined(OS_SOLARIS) || defined(OS_ANDROID) || \
- defined(OS_NACL) || defined(OS_QNX)
-#define OS_POSIX 1
-#endif
-
-// Use tcmalloc
-#if (defined(OS_WIN) || defined(OS_LINUX) || defined(OS_ANDROID)) && \
- !defined(NO_TCMALLOC)
-#define USE_TCMALLOC 1
-#endif
-
-// Compiler detection.
-#if defined(__GNUC__)
-#define COMPILER_GCC 1
-#elif defined(_MSC_VER)
-#define COMPILER_MSVC 1
-#else
-#error Please add support for your compiler in build/build_config.h
-#endif
-
-// Processor architecture detection. For more info on what's defined, see:
-// http://msdn.microsoft.com/en-us/library/b0084kay.aspx
-// http://www.agner.org/optimize/calling_conventions.pdf
-// or with gcc, run: "echo | gcc -E -dM -"
-#if defined(_M_X64) || defined(__x86_64__)
-#define ARCH_CPU_X86_FAMILY 1
-#define ARCH_CPU_X86_64 1
-#define ARCH_CPU_64_BITS 1
-#define ARCH_CPU_LITTLE_ENDIAN 1
-#elif defined(_M_IX86) || defined(__i386__)
-#define ARCH_CPU_X86_FAMILY 1
-#define ARCH_CPU_X86 1
-#define ARCH_CPU_32_BITS 1
-#define ARCH_CPU_LITTLE_ENDIAN 1
-#elif defined(__ARMEL__)
-#define ARCH_CPU_ARM_FAMILY 1
-#define ARCH_CPU_ARMEL 1
-#define ARCH_CPU_32_BITS 1
-#define ARCH_CPU_LITTLE_ENDIAN 1
-#elif defined(__aarch64__)
-#define ARCH_CPU_ARM_FAMILY 1
-#define ARCH_CPU_ARM64 1
-#define ARCH_CPU_64_BITS 1
-#define ARCH_CPU_LITTLE_ENDIAN 1
-#elif defined(__pnacl__)
-#define ARCH_CPU_32_BITS 1
-#define ARCH_CPU_LITTLE_ENDIAN 1
-#elif defined(__MIPSEL__)
-#if defined(__LP64__)
-#define ARCH_CPU_MIPS64_FAMILY 1
-#define ARCH_CPU_MIPS64EL 1
-#define ARCH_CPU_64_BITS 1
-#define ARCH_CPU_LITTLE_ENDIAN 1
-#else
-#define ARCH_CPU_MIPS_FAMILY 1
-#define ARCH_CPU_MIPSEL 1
-#define ARCH_CPU_32_BITS 1
-#define ARCH_CPU_LITTLE_ENDIAN 1
-#endif
-#else
-#error Please add support for your architecture in build/build_config.h
-#endif
-
-// Type detection for wchar_t.
-#if defined(OS_WIN)
-#define WCHAR_T_IS_UTF16
-#elif defined(OS_POSIX) && defined(COMPILER_GCC) && \
- defined(__WCHAR_MAX__) && \
- (__WCHAR_MAX__ == 0x7fffffff || __WCHAR_MAX__ == 0xffffffff)
-#define WCHAR_T_IS_UTF32
-#elif defined(OS_POSIX) && defined(COMPILER_GCC) && \
- defined(__WCHAR_MAX__) && \
- (__WCHAR_MAX__ == 0x7fff || __WCHAR_MAX__ == 0xffff)
-// On Posix, we'll detect short wchar_t, but projects aren't guaranteed to
-// compile in this mode (in particular, Chrome doesn't). This is intended for
-// other projects using base who manage their own dependencies and make sure
-// short wchar works for them.
-#define WCHAR_T_IS_UTF16
-#else
-#error Please add support for your compiler in build/build_config.h
-#endif
-
-#if defined(OS_ANDROID)
-// The compiler thinks std::string::const_iterator and "const char*" are
-// equivalent types.
-#define STD_STRING_ITERATOR_IS_CHAR_POINTER
-// The compiler thinks base::string16::const_iterator and "char16*" are
-// equivalent types.
-#define BASE_STRING16_ITERATOR_IS_CHAR16_POINTER
-#endif
-
-#endif // BUILD_BUILD_CONFIG_H_
diff --git a/security/sandbox/chromium/build/buildflag.h b/security/sandbox/chromium/build/buildflag.h
deleted file mode 100644
index 283f5bce4..000000000
--- a/security/sandbox/chromium/build/buildflag.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2015 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 BUILD_BUILDFLAG_H_
-#define BUILD_BUILDFLAG_H_
-
-// These macros un-mangle the names of the build flags in a way that looks
-// natural, and gives errors if the flag is not defined. Normally in the
-// preprocessor it's easy to make mistakes that interpret "you haven't done
-// the setup to know what the flag is" as "flag is off". Normally you would
-// include the generated header rather than include this file directly.
-//
-// This is for use with generated headers. See build/build_header.gni.
-
-// This dance of two macros does a concatenation of two preprocessor args using
-// ## doubly indirectly because using ## directly prevents macros in that
-// parameter from being expanded.
-#define BUILDFLAG_CAT_INDIRECT(a, b) a ## b
-#define BUILDFLAG_CAT(a, b) BUILDFLAG_CAT_INDIRECT(a, b)
-
-// Accessor for build flags.
-//
-// To test for a value, if the build file specifies:
-//
-// ENABLE_FOO=true
-//
-// Then you would check at build-time in source code with:
-//
-// #include "foo_flags.h" // The header the build file specified.
-//
-// #if BUILDFLAG(ENABLE_FOO)
-// ...
-// #endif
-//
-// There will no #define called ENABLE_FOO so if you accidentally test for
-// whether that is defined, it will always be negative. You can also use
-// the value in expressions:
-//
-// const char kSpamServerName[] = BUILDFLAG(SPAM_SERVER_NAME);
-//
-// Because the flag is accessed as a preprocessor macro with (), an error
-// will be thrown if the proper header defining the internal flag value has
-// not been included.
-#define BUILDFLAG(flag) (BUILDFLAG_CAT(BUILDFLAG_INTERNAL_, flag)())
-
-#endif // BUILD_BUILDFLAG_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.cc b/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.cc
deleted file mode 100644
index 3330c4774..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.cc
+++ /dev/null
@@ -1,348 +0,0 @@
-// Copyright 2014 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 "sandbox/linux/bpf_dsl/bpf_dsl.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <limits>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl_impl.h"
-#include "sandbox/linux/bpf_dsl/errorcode.h"
-#include "sandbox/linux/bpf_dsl/policy_compiler.h"
-#include "sandbox/linux/system_headers/linux_seccomp.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-namespace {
-
-class ReturnResultExprImpl : public internal::ResultExprImpl {
- public:
- explicit ReturnResultExprImpl(uint32_t ret) : ret_(ret) {}
-
- CodeGen::Node Compile(PolicyCompiler* pc) const override {
- return pc->Return(ret_);
- }
-
- bool IsAllow() const override { return IsAction(SECCOMP_RET_ALLOW); }
-
- bool IsDeny() const override {
- return IsAction(SECCOMP_RET_ERRNO) || IsAction(SECCOMP_RET_KILL);
- }
-
- private:
- ~ReturnResultExprImpl() override {}
-
- bool IsAction(uint32_t action) const {
- return (ret_ & SECCOMP_RET_ACTION) == action;
- }
-
- uint32_t ret_;
-
- DISALLOW_COPY_AND_ASSIGN(ReturnResultExprImpl);
-};
-
-class TrapResultExprImpl : public internal::ResultExprImpl {
- public:
- TrapResultExprImpl(TrapRegistry::TrapFnc func, const void* arg, bool safe)
- : func_(func), arg_(arg), safe_(safe) {
- DCHECK(func_);
- }
-
- CodeGen::Node Compile(PolicyCompiler* pc) const override {
- return pc->Trap(func_, arg_, safe_);
- }
-
- bool HasUnsafeTraps() const override { return safe_ == false; }
-
- bool IsDeny() const override { return true; }
-
- private:
- ~TrapResultExprImpl() override {}
-
- TrapRegistry::TrapFnc func_;
- const void* arg_;
- bool safe_;
-
- DISALLOW_COPY_AND_ASSIGN(TrapResultExprImpl);
-};
-
-class IfThenResultExprImpl : public internal::ResultExprImpl {
- public:
- IfThenResultExprImpl(const BoolExpr& cond,
- const ResultExpr& then_result,
- const ResultExpr& else_result)
- : cond_(cond), then_result_(then_result), else_result_(else_result) {}
-
- CodeGen::Node Compile(PolicyCompiler* pc) const override {
- // We compile the "then" and "else" expressions in separate statements so
- // they have a defined sequencing. See https://crbug.com/529480.
- CodeGen::Node then_node = then_result_->Compile(pc);
- CodeGen::Node else_node = else_result_->Compile(pc);
- return cond_->Compile(pc, then_node, else_node);
- }
-
- bool HasUnsafeTraps() const override {
- return then_result_->HasUnsafeTraps() || else_result_->HasUnsafeTraps();
- }
-
- private:
- ~IfThenResultExprImpl() override {}
-
- BoolExpr cond_;
- ResultExpr then_result_;
- ResultExpr else_result_;
-
- DISALLOW_COPY_AND_ASSIGN(IfThenResultExprImpl);
-};
-
-class ConstBoolExprImpl : public internal::BoolExprImpl {
- public:
- ConstBoolExprImpl(bool value) : value_(value) {}
-
- CodeGen::Node Compile(PolicyCompiler* pc,
- CodeGen::Node then_node,
- CodeGen::Node else_node) const override {
- return value_ ? then_node : else_node;
- }
-
- private:
- ~ConstBoolExprImpl() override {}
-
- bool value_;
-
- DISALLOW_COPY_AND_ASSIGN(ConstBoolExprImpl);
-};
-
-class MaskedEqualBoolExprImpl : public internal::BoolExprImpl {
- public:
- MaskedEqualBoolExprImpl(int argno,
- size_t width,
- uint64_t mask,
- uint64_t value)
- : argno_(argno), width_(width), mask_(mask), value_(value) {}
-
- CodeGen::Node Compile(PolicyCompiler* pc,
- CodeGen::Node then_node,
- CodeGen::Node else_node) const override {
- return pc->MaskedEqual(argno_, width_, mask_, value_, then_node, else_node);
- }
-
- private:
- ~MaskedEqualBoolExprImpl() override {}
-
- int argno_;
- size_t width_;
- uint64_t mask_;
- uint64_t value_;
-
- DISALLOW_COPY_AND_ASSIGN(MaskedEqualBoolExprImpl);
-};
-
-class NegateBoolExprImpl : public internal::BoolExprImpl {
- public:
- explicit NegateBoolExprImpl(const BoolExpr& cond) : cond_(cond) {}
-
- CodeGen::Node Compile(PolicyCompiler* pc,
- CodeGen::Node then_node,
- CodeGen::Node else_node) const override {
- return cond_->Compile(pc, else_node, then_node);
- }
-
- private:
- ~NegateBoolExprImpl() override {}
-
- BoolExpr cond_;
-
- DISALLOW_COPY_AND_ASSIGN(NegateBoolExprImpl);
-};
-
-class AndBoolExprImpl : public internal::BoolExprImpl {
- public:
- AndBoolExprImpl(const BoolExpr& lhs, const BoolExpr& rhs)
- : lhs_(lhs), rhs_(rhs) {}
-
- CodeGen::Node Compile(PolicyCompiler* pc,
- CodeGen::Node then_node,
- CodeGen::Node else_node) const override {
- return lhs_->Compile(pc, rhs_->Compile(pc, then_node, else_node),
- else_node);
- }
-
- private:
- ~AndBoolExprImpl() override {}
-
- BoolExpr lhs_;
- BoolExpr rhs_;
-
- DISALLOW_COPY_AND_ASSIGN(AndBoolExprImpl);
-};
-
-class OrBoolExprImpl : public internal::BoolExprImpl {
- public:
- OrBoolExprImpl(const BoolExpr& lhs, const BoolExpr& rhs)
- : lhs_(lhs), rhs_(rhs) {}
-
- CodeGen::Node Compile(PolicyCompiler* pc,
- CodeGen::Node then_node,
- CodeGen::Node else_node) const override {
- return lhs_->Compile(pc, then_node,
- rhs_->Compile(pc, then_node, else_node));
- }
-
- private:
- ~OrBoolExprImpl() override {}
-
- BoolExpr lhs_;
- BoolExpr rhs_;
-
- DISALLOW_COPY_AND_ASSIGN(OrBoolExprImpl);
-};
-
-} // namespace
-
-namespace internal {
-
-bool ResultExprImpl::HasUnsafeTraps() const {
- return false;
-}
-
-bool ResultExprImpl::IsAllow() const {
- return false;
-}
-
-bool ResultExprImpl::IsDeny() const {
- return false;
-}
-
-uint64_t DefaultMask(size_t size) {
- switch (size) {
- case 4:
- return std::numeric_limits<uint32_t>::max();
- case 8:
- return std::numeric_limits<uint64_t>::max();
- default:
- CHECK(false) << "Unimplemented DefaultMask case";
- return 0;
- }
-}
-
-BoolExpr ArgEq(int num, size_t size, uint64_t mask, uint64_t val) {
- // If this is changed, update Arg<T>::EqualTo's static_cast rules
- // accordingly.
- CHECK(size == 4 || size == 8);
-
- return BoolExpr(new const MaskedEqualBoolExprImpl(num, size, mask, val));
-}
-
-} // namespace internal
-
-ResultExpr Allow() {
- return ResultExpr(new const ReturnResultExprImpl(SECCOMP_RET_ALLOW));
-}
-
-ResultExpr Error(int err) {
- CHECK(err >= ErrorCode::ERR_MIN_ERRNO && err <= ErrorCode::ERR_MAX_ERRNO);
- return ResultExpr(new const ReturnResultExprImpl(SECCOMP_RET_ERRNO + err));
-}
-
-ResultExpr Kill() {
- return ResultExpr(new const ReturnResultExprImpl(SECCOMP_RET_KILL));
-}
-
-ResultExpr Trace(uint16_t aux) {
- return ResultExpr(new const ReturnResultExprImpl(SECCOMP_RET_TRACE + aux));
-}
-
-ResultExpr Trap(TrapRegistry::TrapFnc trap_func, const void* aux) {
- return ResultExpr(
- new const TrapResultExprImpl(trap_func, aux, true /* safe */));
-}
-
-ResultExpr UnsafeTrap(TrapRegistry::TrapFnc trap_func, const void* aux) {
- return ResultExpr(
- new const TrapResultExprImpl(trap_func, aux, false /* unsafe */));
-}
-
-BoolExpr BoolConst(bool value) {
- return BoolExpr(new const ConstBoolExprImpl(value));
-}
-
-BoolExpr Not(const BoolExpr& cond) {
- return BoolExpr(new const NegateBoolExprImpl(cond));
-}
-
-BoolExpr AllOf() {
- return BoolConst(true);
-}
-
-BoolExpr AllOf(const BoolExpr& lhs, const BoolExpr& rhs) {
- return BoolExpr(new const AndBoolExprImpl(lhs, rhs));
-}
-
-BoolExpr AnyOf() {
- return BoolConst(false);
-}
-
-BoolExpr AnyOf(const BoolExpr& lhs, const BoolExpr& rhs) {
- return BoolExpr(new const OrBoolExprImpl(lhs, rhs));
-}
-
-Elser If(const BoolExpr& cond, const ResultExpr& then_result) {
- return Elser(nullptr).ElseIf(cond, then_result);
-}
-
-Elser::Elser(cons::List<Clause> clause_list) : clause_list_(clause_list) {
-}
-
-Elser::Elser(const Elser& elser) : clause_list_(elser.clause_list_) {
-}
-
-Elser::~Elser() {
-}
-
-Elser Elser::ElseIf(const BoolExpr& cond, const ResultExpr& then_result) const {
- return Elser(Cons(std::make_pair(cond, then_result), clause_list_));
-}
-
-ResultExpr Elser::Else(const ResultExpr& else_result) const {
- // We finally have the default result expression for this
- // if/then/else sequence. Also, we've already accumulated all
- // if/then pairs into a list of reverse order (i.e., lower priority
- // conditions are listed before higher priority ones). E.g., an
- // expression like
- //
- // If(b1, e1).ElseIf(b2, e2).ElseIf(b3, e3).Else(e4)
- //
- // will have built up a list like
- //
- // [(b3, e3), (b2, e2), (b1, e1)].
- //
- // Now that we have e4, we can walk the list and create a ResultExpr
- // tree like:
- //
- // expr = e4
- // expr = (b3 ? e3 : expr) = (b3 ? e3 : e4)
- // expr = (b2 ? e2 : expr) = (b2 ? e2 : (b3 ? e3 : e4))
- // expr = (b1 ? e1 : expr) = (b1 ? e1 : (b2 ? e2 : (b3 ? e3 : e4)))
- //
- // and end up with an appropriately chained tree.
-
- ResultExpr expr = else_result;
- for (const Clause& clause : clause_list_) {
- expr = ResultExpr(
- new const IfThenResultExprImpl(clause.first, clause.second, expr));
- }
- return expr;
-}
-
-} // namespace bpf_dsl
-} // namespace sandbox
-
-template class scoped_refptr<const sandbox::bpf_dsl::internal::BoolExprImpl>;
-template class scoped_refptr<const sandbox::bpf_dsl::internal::ResultExprImpl>;
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.h
deleted file mode 100644
index ffd20ff42..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.h
+++ /dev/null
@@ -1,335 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_BPF_DSL_BPF_DSL_H_
-#define SANDBOX_LINUX_BPF_DSL_BPF_DSL_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <utility>
-#include <vector>
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl_forward.h"
-#include "sandbox/linux/bpf_dsl/cons.h"
-#include "sandbox/linux/bpf_dsl/trap_registry.h"
-#include "sandbox/sandbox_export.h"
-
-// The sandbox::bpf_dsl namespace provides a domain-specific language
-// to make writing BPF policies more expressive. In general, the
-// object types all have value semantics (i.e., they can be copied
-// around, returned from or passed to function calls, etc. without any
-// surprising side effects), though not all support assignment.
-//
-// An idiomatic and demonstrative (albeit silly) example of this API
-// would be:
-//
-// #include "sandbox/linux/bpf_dsl/bpf_dsl.h"
-//
-// using namespace sandbox::bpf_dsl;
-//
-// class SillyPolicy : public Policy {
-// public:
-// SillyPolicy() {}
-// ~SillyPolicy() override {}
-// ResultExpr EvaluateSyscall(int sysno) const override {
-// if (sysno == __NR_fcntl) {
-// Arg<int> fd(0), cmd(1);
-// Arg<unsigned long> flags(2);
-// const uint64_t kGoodFlags = O_ACCMODE | O_NONBLOCK;
-// return If(AllOf(fd == 0,
-// cmd == F_SETFL,
-// (flags & ~kGoodFlags) == 0),
-// Allow())
-// .ElseIf(AnyOf(cmd == F_DUPFD, cmd == F_DUPFD_CLOEXEC),
-// Error(EMFILE))
-// .Else(Trap(SetFlagHandler, NULL));
-// } else {
-// return Allow();
-// }
-// }
-//
-// private:
-// DISALLOW_COPY_AND_ASSIGN(SillyPolicy);
-// };
-//
-// More generally, the DSL currently supports the following grammar:
-//
-// result = Allow() | Error(errno) | Kill() | Trace(aux)
-// | Trap(trap_func, aux) | UnsafeTrap(trap_func, aux)
-// | If(bool, result)[.ElseIf(bool, result)].Else(result)
-// | Switch(arg)[.Case(val, result)].Default(result)
-// bool = BoolConst(boolean) | Not(bool) | AllOf(bool...) | AnyOf(bool...)
-// | arg == val | arg != val
-// arg = Arg<T>(num) | arg & mask
-//
-// The semantics of each function and operator are intended to be
-// intuitive, but are described in more detail below.
-//
-// (Credit to Sean Parent's "Inheritance is the Base Class of Evil"
-// talk at Going Native 2013 for promoting value semantics via shared
-// pointers to immutable state.)
-
-namespace sandbox {
-namespace bpf_dsl {
-
-// ResultExpr is an opaque reference to an immutable result expression tree.
-typedef scoped_refptr<const internal::ResultExprImpl> ResultExpr;
-
-// BoolExpr is an opaque reference to an immutable boolean expression tree.
-typedef scoped_refptr<const internal::BoolExprImpl> BoolExpr;
-
-// Allow specifies a result that the system call should be allowed to
-// execute normally.
-SANDBOX_EXPORT ResultExpr Allow();
-
-// Error specifies a result that the system call should fail with
-// error number |err|. As a special case, Error(0) will result in the
-// system call appearing to have succeeded, but without having any
-// side effects.
-SANDBOX_EXPORT ResultExpr Error(int err);
-
-// Kill specifies a result to kill the process (task) immediately.
-SANDBOX_EXPORT ResultExpr Kill();
-
-// Trace specifies a result to notify a tracing process via the
-// PTRACE_EVENT_SECCOMP event and allow it to change or skip the system call.
-// The value of |aux| will be available to the tracer via PTRACE_GETEVENTMSG.
-SANDBOX_EXPORT ResultExpr Trace(uint16_t aux);
-
-// Trap specifies a result that the system call should be handled by
-// trapping back into userspace and invoking |trap_func|, passing
-// |aux| as the second parameter.
-SANDBOX_EXPORT ResultExpr
- Trap(TrapRegistry::TrapFnc trap_func, const void* aux);
-
-// UnsafeTrap is like Trap, except the policy is marked as "unsafe"
-// and allowed to use SandboxSyscall to invoke any system call.
-//
-// NOTE: This feature, by definition, disables all security features of
-// the sandbox. It should never be used in production, but it can be
-// very useful to diagnose code that is incompatible with the sandbox.
-// If even a single system call returns "UnsafeTrap", the security of
-// entire sandbox should be considered compromised.
-SANDBOX_EXPORT ResultExpr
- UnsafeTrap(TrapRegistry::TrapFnc trap_func, const void* aux);
-
-// BoolConst converts a bool value into a BoolExpr.
-SANDBOX_EXPORT BoolExpr BoolConst(bool value);
-
-// Not returns a BoolExpr representing the logical negation of |cond|.
-SANDBOX_EXPORT BoolExpr Not(const BoolExpr& cond);
-
-// AllOf returns a BoolExpr representing the logical conjunction ("and")
-// of zero or more BoolExprs.
-SANDBOX_EXPORT BoolExpr AllOf();
-SANDBOX_EXPORT BoolExpr AllOf(const BoolExpr& lhs, const BoolExpr& rhs);
-template <typename... Rest>
-SANDBOX_EXPORT BoolExpr AllOf(const BoolExpr& first, const Rest&... rest);
-
-// AnyOf returns a BoolExpr representing the logical disjunction ("or")
-// of zero or more BoolExprs.
-SANDBOX_EXPORT BoolExpr AnyOf();
-SANDBOX_EXPORT BoolExpr AnyOf(const BoolExpr& lhs, const BoolExpr& rhs);
-template <typename... Rest>
-SANDBOX_EXPORT BoolExpr AnyOf(const BoolExpr& first, const Rest&... rest);
-
-template <typename T>
-class SANDBOX_EXPORT Arg {
- public:
- // Initializes the Arg to represent the |num|th system call
- // argument (indexed from 0), which is of type |T|.
- explicit Arg(int num);
-
- Arg(const Arg& arg) : num_(arg.num_), mask_(arg.mask_) {}
-
- // Returns an Arg representing the current argument, but after
- // bitwise-and'ing it with |rhs|.
- friend Arg operator&(const Arg& lhs, uint64_t rhs) {
- return Arg(lhs.num_, lhs.mask_ & rhs);
- }
-
- // Returns a boolean expression comparing whether the system call argument
- // (after applying any bitmasks, if appropriate) equals |rhs|.
- friend BoolExpr operator==(const Arg& lhs, T rhs) { return lhs.EqualTo(rhs); }
-
- // Returns a boolean expression comparing whether the system call argument
- // (after applying any bitmasks, if appropriate) does not equal |rhs|.
- friend BoolExpr operator!=(const Arg& lhs, T rhs) { return Not(lhs == rhs); }
-
- private:
- Arg(int num, uint64_t mask) : num_(num), mask_(mask) {}
-
- BoolExpr EqualTo(T val) const;
-
- int num_;
- uint64_t mask_;
-
- DISALLOW_ASSIGN(Arg);
-};
-
-// If begins a conditional result expression predicated on the
-// specified boolean expression.
-SANDBOX_EXPORT Elser If(const BoolExpr& cond, const ResultExpr& then_result);
-
-class SANDBOX_EXPORT Elser {
- public:
- Elser(const Elser& elser);
- ~Elser();
-
- // ElseIf extends the conditional result expression with another
- // "if then" clause, predicated on the specified boolean expression.
- Elser ElseIf(const BoolExpr& cond, const ResultExpr& then_result) const;
-
- // Else terminates a conditional result expression using |else_result| as
- // the default fallback result expression.
- ResultExpr Else(const ResultExpr& else_result) const;
-
- private:
- typedef std::pair<BoolExpr, ResultExpr> Clause;
-
- explicit Elser(cons::List<Clause> clause_list);
-
- cons::List<Clause> clause_list_;
-
- friend Elser If(const BoolExpr&, const ResultExpr&);
- template <typename T>
- friend Caser<T> Switch(const Arg<T>&);
- DISALLOW_ASSIGN(Elser);
-};
-
-// Switch begins a switch expression dispatched according to the
-// specified argument value.
-template <typename T>
-SANDBOX_EXPORT Caser<T> Switch(const Arg<T>& arg);
-
-template <typename T>
-class SANDBOX_EXPORT Caser {
- public:
- Caser(const Caser<T>& caser) : arg_(caser.arg_), elser_(caser.elser_) {}
- ~Caser() {}
-
- // Case adds a single-value "case" clause to the switch.
- Caser<T> Case(T value, const ResultExpr& result) const;
-
- // Cases adds a multiple-value "case" clause to the switch.
- // See also the SANDBOX_BPF_DSL_CASES macro below for a more idiomatic way
- // of using this function.
- template <typename... Values>
- Caser<T> CasesImpl(const ResultExpr& result, const Values&... values) const;
-
- // Terminate the switch with a "default" clause.
- ResultExpr Default(const ResultExpr& result) const;
-
- private:
- Caser(const Arg<T>& arg, Elser elser) : arg_(arg), elser_(elser) {}
-
- Arg<T> arg_;
- Elser elser_;
-
- template <typename U>
- friend Caser<U> Switch(const Arg<U>&);
- DISALLOW_ASSIGN(Caser);
-};
-
-// Recommended usage is to put
-// #define CASES SANDBOX_BPF_DSL_CASES
-// near the top of the .cc file (e.g., nearby any "using" statements), then
-// use like:
-// Switch(arg).CASES((3, 5, 7), result)...;
-#define SANDBOX_BPF_DSL_CASES(values, result) \
- CasesImpl(result, SANDBOX_BPF_DSL_CASES_HELPER values)
-
-// Helper macro to strip parentheses.
-#define SANDBOX_BPF_DSL_CASES_HELPER(...) __VA_ARGS__
-
-// =====================================================================
-// Official API ends here.
-// =====================================================================
-
-namespace internal {
-
-// Make argument-dependent lookup work. This is necessary because although
-// BoolExpr is defined in bpf_dsl, since it's merely a typedef for
-// scoped_refptr<const internal::BoolExplImpl>, argument-dependent lookup only
-// searches the "internal" nested namespace.
-using bpf_dsl::Not;
-using bpf_dsl::AllOf;
-using bpf_dsl::AnyOf;
-
-// Returns a boolean expression that represents whether system call
-// argument |num| of size |size| is equal to |val|, when masked
-// according to |mask|. Users should use the Arg template class below
-// instead of using this API directly.
-SANDBOX_EXPORT BoolExpr
- ArgEq(int num, size_t size, uint64_t mask, uint64_t val);
-
-// Returns the default mask for a system call argument of the specified size.
-SANDBOX_EXPORT uint64_t DefaultMask(size_t size);
-
-} // namespace internal
-
-template <typename T>
-Arg<T>::Arg(int num)
- : num_(num), mask_(internal::DefaultMask(sizeof(T))) {
-}
-
-// Definition requires ArgEq to have been declared. Moved out-of-line
-// to minimize how much internal clutter users have to ignore while
-// reading the header documentation.
-//
-// Additionally, we use this helper member function to avoid linker errors
-// caused by defining operator== out-of-line. For a more detailed explanation,
-// see http://www.parashift.com/c++-faq-lite/template-friends.html.
-template <typename T>
-BoolExpr Arg<T>::EqualTo(T val) const {
- if (sizeof(T) == 4) {
- // Prevent sign-extension of negative int32_t values.
- return internal::ArgEq(num_, sizeof(T), mask_, static_cast<uint32_t>(val));
- }
- return internal::ArgEq(num_, sizeof(T), mask_, static_cast<uint64_t>(val));
-}
-
-template <typename T>
-SANDBOX_EXPORT Caser<T> Switch(const Arg<T>& arg) {
- return Caser<T>(arg, Elser(nullptr));
-}
-
-template <typename T>
-Caser<T> Caser<T>::Case(T value, const ResultExpr& result) const {
- return SANDBOX_BPF_DSL_CASES((value), result);
-}
-
-template <typename T>
-template <typename... Values>
-Caser<T> Caser<T>::CasesImpl(const ResultExpr& result,
- const Values&... values) const {
- // Theoretically we could evaluate arg_ just once and emit a more efficient
- // dispatch table, but for now we simply translate into an equivalent
- // If/ElseIf/Else chain.
-
- return Caser<T>(arg_, elser_.ElseIf(AnyOf((arg_ == values)...), result));
-}
-
-template <typename T>
-ResultExpr Caser<T>::Default(const ResultExpr& result) const {
- return elser_.Else(result);
-}
-
-template <typename... Rest>
-BoolExpr AllOf(const BoolExpr& first, const Rest&... rest) {
- return AllOf(first, AllOf(rest...));
-}
-
-template <typename... Rest>
-BoolExpr AnyOf(const BoolExpr& first, const Rest&... rest) {
- return AnyOf(first, AnyOf(rest...));
-}
-
-} // namespace bpf_dsl
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_BPF_DSL_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl_forward.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl_forward.h
deleted file mode 100644
index 183038990..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl_forward.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_BPF_DSL_BPF_DSL_FORWARD_H_
-#define SANDBOX_LINUX_BPF_DSL_BPF_DSL_FORWARD_H_
-
-#include "base/memory/ref_counted.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-
-// The bpf_dsl_forward.h header provides forward declarations for the
-// types defined in bpf_dsl.h. It's intended for use in user headers
-// that need to reference bpf_dsl types, but don't require definitions.
-
-namespace internal {
-class ResultExprImpl;
-class BoolExprImpl;
-}
-
-typedef scoped_refptr<const internal::ResultExprImpl> ResultExpr;
-typedef scoped_refptr<const internal::BoolExprImpl> BoolExpr;
-
-template <typename T>
-class Arg;
-
-class Elser;
-
-template <typename T>
-class Caser;
-
-} // namespace bpf_dsl
-} // namespace sandbox
-
-extern template class SANDBOX_EXPORT
- scoped_refptr<const sandbox::bpf_dsl::internal::BoolExprImpl>;
-extern template class SANDBOX_EXPORT
- scoped_refptr<const sandbox::bpf_dsl::internal::ResultExprImpl>;
-
-#endif // SANDBOX_LINUX_BPF_DSL_BPF_DSL_FORWARD_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl_impl.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl_impl.h
deleted file mode 100644
index 0064f8a7a..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl_impl.h
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_BPF_DSL_BPF_DSL_IMPL_H_
-#define SANDBOX_LINUX_BPF_DSL_BPF_DSL_IMPL_H_
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "sandbox/linux/bpf_dsl/codegen.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-class ErrorCode;
-class PolicyCompiler;
-
-namespace internal {
-
-// Internal interface implemented by BoolExpr implementations.
-class BoolExprImpl : public base::RefCounted<BoolExprImpl> {
- public:
- // Compile uses |pc| to emit a CodeGen::Node that conditionally continues
- // to either |then_node| or |false_node|, depending on whether the represented
- // boolean expression is true or false.
- virtual CodeGen::Node Compile(PolicyCompiler* pc,
- CodeGen::Node then_node,
- CodeGen::Node else_node) const = 0;
-
- protected:
- BoolExprImpl() {}
- virtual ~BoolExprImpl() {}
-
- private:
- friend class base::RefCounted<BoolExprImpl>;
- DISALLOW_COPY_AND_ASSIGN(BoolExprImpl);
-};
-
-// Internal interface implemented by ResultExpr implementations.
-class ResultExprImpl : public base::RefCounted<ResultExprImpl> {
- public:
- // Compile uses |pc| to emit a CodeGen::Node that executes the
- // represented result expression.
- virtual CodeGen::Node Compile(PolicyCompiler* pc) const = 0;
-
- // HasUnsafeTraps returns whether the result expression is or recursively
- // contains an unsafe trap expression.
- virtual bool HasUnsafeTraps() const;
-
- // IsAllow returns whether the result expression is an "allow" result.
- virtual bool IsAllow() const;
-
- // IsAllow returns whether the result expression is a "deny" result.
- virtual bool IsDeny() const;
-
- protected:
- ResultExprImpl() {}
- virtual ~ResultExprImpl() {}
-
- private:
- friend class base::RefCounted<ResultExprImpl>;
- DISALLOW_COPY_AND_ASSIGN(ResultExprImpl);
-};
-
-} // namespace internal
-} // namespace bpf_dsl
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_BPF_DSL_IMPL_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/codegen.cc b/security/sandbox/chromium/sandbox/linux/bpf_dsl/codegen.cc
deleted file mode 100644
index 647f55aa8..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/codegen.cc
+++ /dev/null
@@ -1,161 +0,0 @@
-// 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.
-
-#include "sandbox/linux/bpf_dsl/codegen.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <limits>
-#include <utility>
-
-#include "base/logging.h"
-#include "sandbox/linux/system_headers/linux_filter.h"
-
-// This CodeGen implementation strives for simplicity while still
-// generating acceptable BPF programs under typical usage patterns
-// (e.g., by PolicyCompiler).
-//
-// The key to its simplicity is that BPF programs only support forward
-// jumps/branches, which allows constraining the DAG construction API
-// to make instruction nodes immutable. Immutable nodes admits a
-// simple greedy approach of emitting new instructions as needed and
-// then reusing existing ones that have already been emitted. This
-// cleanly avoids any need to compute basic blocks or apply
-// topological sorting because the API effectively sorts instructions
-// for us (e.g., before MakeInstruction() can be called to emit a
-// branch instruction, it must have already been called for each
-// branch path).
-//
-// This greedy algorithm is not without (theoretical) weakness though:
-//
-// 1. In the general case, we don't eliminate dead code. If needed,
-// we could trace back through the program in Compile() and elide
-// any unneeded instructions, but in practice we only emit live
-// instructions anyway.
-//
-// 2. By not dividing instructions into basic blocks and sorting, we
-// lose an opportunity to move non-branch/non-return instructions
-// adjacent to their successor instructions, which means we might
-// need to emit additional jumps. But in practice, they'll
-// already be nearby as long as callers don't go out of their way
-// to interleave MakeInstruction() calls for unrelated code
-// sequences.
-
-namespace sandbox {
-
-// kBranchRange is the maximum value that can be stored in
-// sock_filter's 8-bit jt and jf fields.
-const size_t kBranchRange = std::numeric_limits<uint8_t>::max();
-
-const CodeGen::Node CodeGen::kNullNode;
-
-CodeGen::CodeGen() : program_(), equivalent_(), memos_() {
-}
-
-CodeGen::~CodeGen() {
-}
-
-CodeGen::Program CodeGen::Compile(CodeGen::Node head) {
- return Program(program_.rbegin() + Offset(head), program_.rend());
-}
-
-CodeGen::Node CodeGen::MakeInstruction(uint16_t code,
- uint32_t k,
- Node jt,
- Node jf) {
- // To avoid generating redundant code sequences, we memoize the
- // results from AppendInstruction().
- auto res = memos_.insert(std::make_pair(MemoKey(code, k, jt, jf), kNullNode));
- CodeGen::Node* node = &res.first->second;
- if (res.second) { // Newly inserted memo entry.
- *node = AppendInstruction(code, k, jt, jf);
- }
- return *node;
-}
-
-CodeGen::Node CodeGen::AppendInstruction(uint16_t code,
- uint32_t k,
- Node jt,
- Node jf) {
- if (BPF_CLASS(code) == BPF_JMP) {
- CHECK_NE(BPF_JA, BPF_OP(code)) << "CodeGen inserts JAs as needed";
-
- // Optimally adding jumps is rather tricky, so we use a quick
- // approximation: by artificially reducing |jt|'s range, |jt| will
- // stay within its true range even if we add a jump for |jf|.
- jt = WithinRange(jt, kBranchRange - 1);
- jf = WithinRange(jf, kBranchRange);
- return Append(code, k, Offset(jt), Offset(jf));
- }
-
- CHECK_EQ(kNullNode, jf) << "Non-branch instructions shouldn't provide jf";
- if (BPF_CLASS(code) == BPF_RET) {
- CHECK_EQ(kNullNode, jt) << "Return instructions shouldn't provide jt";
- } else {
- // For non-branch/non-return instructions, execution always
- // proceeds to the next instruction; so we need to arrange for
- // that to be |jt|.
- jt = WithinRange(jt, 0);
- CHECK_EQ(0U, Offset(jt)) << "ICE: Failed to setup next instruction";
- }
- return Append(code, k, 0, 0);
-}
-
-CodeGen::Node CodeGen::WithinRange(Node target, size_t range) {
- // Just use |target| if it's already within range.
- if (Offset(target) <= range) {
- return target;
- }
-
- // Alternatively, look for an equivalent instruction within range.
- if (Offset(equivalent_.at(target)) <= range) {
- return equivalent_.at(target);
- }
-
- // Otherwise, fall back to emitting a jump instruction.
- Node jump = Append(BPF_JMP | BPF_JA, Offset(target), 0, 0);
- equivalent_.at(target) = jump;
- return jump;
-}
-
-CodeGen::Node CodeGen::Append(uint16_t code, uint32_t k, size_t jt, size_t jf) {
- if (BPF_CLASS(code) == BPF_JMP && BPF_OP(code) != BPF_JA) {
- CHECK_LE(jt, kBranchRange);
- CHECK_LE(jf, kBranchRange);
- } else {
- CHECK_EQ(0U, jt);
- CHECK_EQ(0U, jf);
- }
-
- CHECK_LT(program_.size(), static_cast<size_t>(BPF_MAXINSNS));
- CHECK_EQ(program_.size(), equivalent_.size());
-
- Node res = program_.size();
- program_.push_back(sock_filter{
- code, static_cast<uint8_t>(jt), static_cast<uint8_t>(jf), k});
- equivalent_.push_back(res);
- return res;
-}
-
-size_t CodeGen::Offset(Node target) const {
- CHECK_LT(target, program_.size()) << "Bogus offset target node";
- return (program_.size() - 1) - target;
-}
-
-// TODO(mdempsky): Move into a general base::Tuple helper library.
-bool CodeGen::MemoKeyLess::operator()(const MemoKey& lhs,
- const MemoKey& rhs) const {
- if (base::get<0>(lhs) != base::get<0>(rhs))
- return base::get<0>(lhs) < base::get<0>(rhs);
- if (base::get<1>(lhs) != base::get<1>(rhs))
- return base::get<1>(lhs) < base::get<1>(rhs);
- if (base::get<2>(lhs) != base::get<2>(rhs))
- return base::get<2>(lhs) < base::get<2>(rhs);
- if (base::get<3>(lhs) != base::get<3>(rhs))
- return base::get<3>(lhs) < base::get<3>(rhs);
- return false;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/codegen.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/codegen.h
deleted file mode 100644
index 03c3b236e..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/codegen.h
+++ /dev/null
@@ -1,122 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_BPF_DSL_CODEGEN_H__
-#define SANDBOX_LINUX_BPF_DSL_CODEGEN_H__
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <map>
-#include <vector>
-
-#include "base/macros.h"
-#include "base/tuple.h"
-#include "sandbox/sandbox_export.h"
-
-struct sock_filter;
-
-namespace sandbox {
-
-// The code generator implements a basic assembler that can convert a
-// graph of BPF instructions into a well-formed array of BPF
-// instructions. Most notably, it ensures that jumps are always
-// forward and don't exceed the limit of 255 instructions imposed by
-// the instruction set.
-//
-// Callers would typically create a new CodeGen object and then use it
-// to build a DAG of instruction nodes. They'll eventually call
-// Compile() to convert this DAG to a Program.
-//
-// CodeGen gen;
-// CodeGen::Node allow, branch, dag;
-//
-// allow =
-// gen.MakeInstruction(BPF_RET+BPF_K,
-// ErrorCode(ErrorCode::ERR_ALLOWED).err()));
-// branch =
-// gen.MakeInstruction(BPF_JMP+BPF_EQ+BPF_K, __NR_getpid,
-// Trap(GetPidHandler, NULL), allow);
-// dag =
-// gen.MakeInstruction(BPF_LD+BPF_W+BPF_ABS,
-// offsetof(struct arch_seccomp_data, nr), branch);
-//
-// // Simplified code follows; in practice, it is important to avoid calling
-// // any C++ destructors after starting the sandbox.
-// CodeGen::Program program = gen.Compile(dag);
-// const struct sock_fprog prog = {
-// static_cast<unsigned short>(program.size()), &program[0] };
-// prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog);
-//
-class SANDBOX_EXPORT CodeGen {
- public:
- // A vector of BPF instructions that need to be installed as a filter
- // program in the kernel.
- typedef std::vector<struct sock_filter> Program;
-
- // Node represents a node within the instruction DAG being compiled.
- using Node = Program::size_type;
-
- // kNullNode represents the "null" node; i.e., the reserved node
- // value guaranteed to not equal any actual nodes.
- static const Node kNullNode = -1;
-
- CodeGen();
- ~CodeGen();
-
- // MakeInstruction creates a node representing the specified
- // instruction, or returns and existing equivalent node if one
- // exists. For details on the possible parameters refer to
- // https://www.kernel.org/doc/Documentation/networking/filter.txt.
- // TODO(mdempsky): Reconsider using default arguments here.
- Node MakeInstruction(uint16_t code,
- uint32_t k,
- Node jt = kNullNode,
- Node jf = kNullNode);
-
- // Compile linearizes the instruction DAG rooted at |head| into a
- // program that can be executed by a BPF virtual machine.
- Program Compile(Node head);
-
- private:
- using MemoKey = base::Tuple<uint16_t, uint32_t, Node, Node>;
- struct MemoKeyLess {
- bool operator()(const MemoKey& lhs, const MemoKey& rhs) const;
- };
-
- // AppendInstruction adds a new instruction, ensuring that |jt| and
- // |jf| are within range as necessary for |code|.
- Node AppendInstruction(uint16_t code, uint32_t k, Node jt, Node jf);
-
- // WithinRange returns a node equivalent to |next| that is at most
- // |range| instructions away from the (logical) beginning of the
- // program.
- Node WithinRange(Node next, size_t range);
-
- // Append appends a new instruction to the physical end (i.e.,
- // logical beginning) of |program_|.
- Node Append(uint16_t code, uint32_t k, size_t jt, size_t jf);
-
- // Offset returns how many instructions exist in |program_| after |target|.
- size_t Offset(Node target) const;
-
- // NOTE: program_ is the compiled program in *reverse*, so that
- // indices remain stable as we add instructions.
- Program program_;
-
- // equivalent_ stores the most recent semantically-equivalent node for each
- // instruction in program_. A node is defined as semantically-equivalent to N
- // if it has the same instruction code and constant as N and its successor
- // nodes (if any) are semantically-equivalent to N's successor nodes, or
- // if it's an unconditional jump to a node semantically-equivalent to N.
- std::vector<Node> equivalent_;
-
- std::map<MemoKey, Node, MemoKeyLess> memos_;
-
- DISALLOW_COPY_AND_ASSIGN(CodeGen);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_CODEGEN_H__
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/cons.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/cons.h
deleted file mode 100644
index be050f778..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/cons.h
+++ /dev/null
@@ -1,139 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_BPF_DSL_CONS_H_
-#define SANDBOX_LINUX_BPF_DSL_CONS_H_
-
-#include "base/macros.h"
-#include "base/memory/ref_counted.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-namespace cons {
-
-// Namespace cons provides an abstraction for immutable "cons list"
-// data structures as commonly provided in functional programming
-// languages like Lisp or Haskell.
-//
-// A cons list is a linked list consisting of "cells", each of which
-// have a "head" and a "tail" element. A cell's head element contains
-// a user specified value, while the tail element contains a (possibly
-// null) pointer to another cell.
-//
-// An empty list (idiomatically referred to as "nil") can be
-// constructed as "cons::List<Foo>()" or simply as "nullptr" if Foo
-// can be inferred from context (e.g., calling a function that has a
-// "cons::List<Foo>" parameter).
-//
-// Existing lists (including empty lists) can be extended by
-// prepending new values to the front using the "Cons(head, tail)"
-// function, which will allocate a new cons cell. Notably, cons lists
-// support creating multiple lists that share a common tail sequence.
-//
-// Lastly, lists support iteration via C++11's range-based for loop
-// construct.
-//
-// Examples:
-//
-// // basic construction
-// const cons::List<char> kNil = nullptr;
-// cons::List<char> ba = Cons('b', Cons('a', kNil));
-//
-// // common tail sequence
-// cons::List<char> cba = Cons('c', ba);
-// cons::List<char> dba = Cons('d', ba);
-//
-// // iteration
-// for (const char& ch : cba) {
-// // iterates 'c', 'b', 'a'
-// }
-// for (const char& ch : dba) {
-// // iterates 'd', 'b', 'a'
-// }
-
-// Forward declarations.
-template <typename T>
-class Cell;
-template <typename T>
-class ListIterator;
-
-// List represents a (possibly null) pointer to a cons cell.
-template <typename T>
-using List = scoped_refptr<const Cell<T>>;
-
-// Cons extends a cons list by prepending a new value to the front.
-template <typename T>
-List<T> Cons(const T& head, const List<T>& tail) {
- return List<T>(new const Cell<T>(head, tail));
-}
-
-// Cell represents an individual "cons cell" within a cons list.
-template <typename T>
-class Cell : public base::RefCounted<Cell<T>> {
- public:
- Cell(const T& head, const List<T>& tail) : head_(head), tail_(tail) {}
-
- // Head returns this cell's head element.
- const T& head() const { return head_; }
-
- // Tail returns this cell's tail element.
- const List<T>& tail() const { return tail_; }
-
- private:
- virtual ~Cell() {}
-
- T head_;
- List<T> tail_;
-
- friend class base::RefCounted<Cell<T>>;
- DISALLOW_COPY_AND_ASSIGN(Cell);
-};
-
-// Begin returns a list iterator pointing to the first element of the
-// cons list. It's provided to support range-based for loops.
-template <typename T>
-ListIterator<T> begin(const List<T>& list) {
- return ListIterator<T>(list);
-}
-
-// End returns a list iterator pointing to the "past-the-end" element
-// of the cons list (i.e., nil). It's provided to support range-based
-// for loops.
-template <typename T>
-ListIterator<T> end(const List<T>& list) {
- return ListIterator<T>();
-}
-
-// ListIterator provides C++ forward iterator semantics for traversing
-// a cons list.
-template <typename T>
-class ListIterator {
- public:
- ListIterator() : list_() {}
- explicit ListIterator(const List<T>& list) : list_(list) {}
-
- const T& operator*() const { return list_->head(); }
-
- ListIterator& operator++() {
- list_ = list_->tail();
- return *this;
- }
-
- friend bool operator==(const ListIterator& lhs, const ListIterator& rhs) {
- return lhs.list_ == rhs.list_;
- }
-
- private:
- List<T> list_;
-};
-
-template <typename T>
-bool operator!=(const ListIterator<T>& lhs, const ListIterator<T>& rhs) {
- return !(lhs == rhs);
-}
-
-} // namespace cons
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_CONS_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/dump_bpf.cc b/security/sandbox/chromium/sandbox/linux/bpf_dsl/dump_bpf.cc
deleted file mode 100644
index 2edf592f6..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/dump_bpf.cc
+++ /dev/null
@@ -1,159 +0,0 @@
-// Copyright 2014 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 "sandbox/linux/bpf_dsl/dump_bpf.h"
-
-#include <inttypes.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <stdio.h>
-
-#include <string>
-
-#include "base/strings/stringprintf.h"
-#include "sandbox/linux/bpf_dsl/codegen.h"
-#include "sandbox/linux/bpf_dsl/seccomp_macros.h"
-#include "sandbox/linux/bpf_dsl/trap_registry.h"
-#include "sandbox/linux/system_headers/linux_filter.h"
-#include "sandbox/linux/system_headers/linux_seccomp.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-
-namespace {
-
-const char* AluOpToken(uint32_t code) {
- switch (BPF_OP(code)) {
- case BPF_ADD:
- return "+";
- case BPF_SUB:
- return "-";
- case BPF_MUL:
- return "*";
- case BPF_DIV:
- return "/";
- case BPF_MOD:
- return "%";
- case BPF_OR:
- return "|";
- case BPF_XOR:
- return "^";
- case BPF_AND:
- return "&";
- case BPF_LSH:
- return "<<";
- case BPF_RSH:
- return ">>";
- default:
- return "???";
- }
-}
-
-const char* JmpOpToken(uint32_t code) {
- switch (BPF_OP(code)) {
- case BPF_JSET:
- return "&";
- case BPF_JEQ:
- return "==";
- case BPF_JGE:
- return ">=";
- default:
- return "???";
- }
-}
-
-const char* DataOffsetName(size_t off) {
- switch (off) {
- case SECCOMP_NR_IDX:
- return "System call number";
- case SECCOMP_ARCH_IDX:
- return "Architecture";
- case SECCOMP_IP_LSB_IDX:
- return "Instruction pointer (LSB)";
- case SECCOMP_IP_MSB_IDX:
- return "Instruction pointer (MSB)";
- default:
- return "???";
- }
-}
-
-void AppendInstruction(std::string* dst, size_t pc, const sock_filter& insn) {
- base::StringAppendF(dst, "%3zu) ", pc);
- switch (BPF_CLASS(insn.code)) {
- case BPF_LD:
- if (insn.code == BPF_LD + BPF_W + BPF_ABS) {
- base::StringAppendF(dst, "LOAD %" PRIu32 " // ", insn.k);
- size_t maybe_argno =
- (insn.k - offsetof(struct arch_seccomp_data, args)) /
- sizeof(uint64_t);
- if (maybe_argno < 6 && insn.k == SECCOMP_ARG_LSB_IDX(maybe_argno)) {
- base::StringAppendF(dst, "Argument %zu (LSB)\n", maybe_argno);
- } else if (maybe_argno < 6 &&
- insn.k == SECCOMP_ARG_MSB_IDX(maybe_argno)) {
- base::StringAppendF(dst, "Argument %zu (MSB)\n", maybe_argno);
- } else {
- base::StringAppendF(dst, "%s\n", DataOffsetName(insn.k));
- }
- } else {
- base::StringAppendF(dst, "Load ???\n");
- }
- break;
- case BPF_JMP:
- if (BPF_OP(insn.code) == BPF_JA) {
- base::StringAppendF(dst, "JMP %zu\n", pc + insn.k + 1);
- } else {
- base::StringAppendF(
- dst, "if A %s 0x%" PRIx32 "; then JMP %zu else JMP %zu\n",
- JmpOpToken(insn.code), insn.k, pc + insn.jt + 1, pc + insn.jf + 1);
- }
- break;
- case BPF_RET:
- base::StringAppendF(dst, "RET 0x%" PRIx32 " // ", insn.k);
- if ((insn.k & SECCOMP_RET_ACTION) == SECCOMP_RET_TRAP) {
- base::StringAppendF(dst, "Trap #%" PRIu32 "\n",
- insn.k & SECCOMP_RET_DATA);
- } else if ((insn.k & SECCOMP_RET_ACTION) == SECCOMP_RET_ERRNO) {
- base::StringAppendF(dst, "errno = %" PRIu32 "\n",
- insn.k & SECCOMP_RET_DATA);
- } else if ((insn.k & SECCOMP_RET_ACTION) == SECCOMP_RET_TRACE) {
- base::StringAppendF(dst, "Trace #%" PRIu32 "\n",
- insn.k & SECCOMP_RET_DATA);
- } else if (insn.k == SECCOMP_RET_ALLOW) {
- base::StringAppendF(dst, "Allowed\n");
- } else if (insn.k == SECCOMP_RET_KILL) {
- base::StringAppendF(dst, "Kill\n");
- } else {
- base::StringAppendF(dst, "???\n");
- }
- break;
- case BPF_ALU:
- if (BPF_OP(insn.code) == BPF_NEG) {
- base::StringAppendF(dst, "A := -A\n");
- } else {
- base::StringAppendF(dst, "A := A %s 0x%" PRIx32 "\n",
- AluOpToken(insn.code), insn.k);
- }
- break;
- default:
- base::StringAppendF(dst, "???\n");
- break;
- }
-}
-
-} // namespace
-
-void DumpBPF::PrintProgram(const CodeGen::Program& program) {
- fputs(StringPrintProgram(program).c_str(), stderr);
-}
-
-std::string DumpBPF::StringPrintProgram(const CodeGen::Program& program) {
- std::string res;
- for (size_t i = 0; i < program.size(); i++) {
- AppendInstruction(&res, i + 1, program[i]);
- }
- return res;
-}
-
-} // namespace bpf_dsl
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/dump_bpf.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/dump_bpf.h
deleted file mode 100644
index a7db58981..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/dump_bpf.h
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2014 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 <string>
-
-#include "sandbox/linux/bpf_dsl/codegen.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-
-class SANDBOX_EXPORT DumpBPF {
- public:
- // PrintProgram writes |program| in a human-readable format to stderr.
- static void PrintProgram(const CodeGen::Program& program);
-
- // StringPrintProgram writes |program| in a human-readable format to
- // a std::string.
- static std::string StringPrintProgram(const CodeGen::Program& program);
-};
-
-} // namespace bpf_dsl
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/errorcode.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/errorcode.h
deleted file mode 100644
index 611c27dd8..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/errorcode.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_BPF_DSL_ERRORCODE_H__
-#define SANDBOX_LINUX_BPF_DSL_ERRORCODE_H__
-
-#include "base/macros.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-
-// TODO(mdempsky): Find a proper home for ERR_{MIN,MAX}_ERRNO and
-// remove this header.
-class SANDBOX_EXPORT ErrorCode {
- public:
- enum {
- ERR_MIN_ERRNO = 0,
-#if defined(__mips__)
- // MIPS only supports errno up to 1133
- ERR_MAX_ERRNO = 1133,
-#else
- // TODO(markus): Android only supports errno up to 255
- // (crbug.com/181647).
- ERR_MAX_ERRNO = 4095,
-#endif
- };
-
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(ErrorCode);
-};
-
-} // namespace bpf_dsl
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_ERRORCODE_H__
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/linux_syscall_ranges.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/linux_syscall_ranges.h
deleted file mode 100644
index a747770c7..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/linux_syscall_ranges.h
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2015 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 SANDBOX_LINUX_BPF_DSL_LINUX_SYSCALL_RANGES_H_
-#define SANDBOX_LINUX_BPF_DSL_LINUX_SYSCALL_RANGES_H_
-
-#if defined(__x86_64__)
-
-#define MIN_SYSCALL 0u
-#define MAX_PUBLIC_SYSCALL 1024u
-#define MAX_SYSCALL MAX_PUBLIC_SYSCALL
-
-#elif defined(__i386__)
-
-#define MIN_SYSCALL 0u
-#define MAX_PUBLIC_SYSCALL 1024u
-#define MAX_SYSCALL MAX_PUBLIC_SYSCALL
-
-#elif defined(__arm__) && (defined(__thumb__) || defined(__ARM_EABI__))
-
-// ARM EABI includes "ARM private" system calls starting at |__ARM_NR_BASE|,
-// and a "ghost syscall private to the kernel", cmpxchg,
-// at |__ARM_NR_BASE+0x00fff0|.
-// See </arch/arm/include/asm/unistd.h> in the Linux kernel.
-
-// __NR_SYSCALL_BASE is 0 in thumb and ARM EABI.
-#define MIN_SYSCALL 0u
-#define MAX_PUBLIC_SYSCALL (MIN_SYSCALL + 1024u)
-// __ARM_NR_BASE is __NR_SYSCALL_BASE + 0xf0000u
-#define MIN_PRIVATE_SYSCALL 0xf0000u
-#define MAX_PRIVATE_SYSCALL (MIN_PRIVATE_SYSCALL + 16u)
-#define MIN_GHOST_SYSCALL (MIN_PRIVATE_SYSCALL + 0xfff0u)
-#define MAX_SYSCALL (MIN_GHOST_SYSCALL + 4u)
-
-#elif defined(__mips__) && (_MIPS_SIM == _ABIO32)
-
-#include <asm/unistd.h> // for __NR_O32_Linux and __NR_Linux_syscalls
-#define MIN_SYSCALL __NR_O32_Linux
-#define MAX_PUBLIC_SYSCALL (MIN_SYSCALL + __NR_Linux_syscalls)
-#define MAX_SYSCALL MAX_PUBLIC_SYSCALL
-
-#elif defined(__mips__) && (_MIPS_SIM == _ABI64)
-
-#error "Add support to header file"
-
-#elif defined(__aarch64__)
-
-#define MIN_SYSCALL 0u
-#define MAX_PUBLIC_SYSCALL 279u
-#define MAX_SYSCALL MAX_PUBLIC_SYSCALL
-
-#else
-#error "Unsupported architecture"
-#endif
-
-#endif // SANDBOX_LINUX_BPF_DSL_LINUX_SYSCALL_RANGES_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy.cc b/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy.cc
deleted file mode 100644
index c20edc6da..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy.cc
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2014 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 "sandbox/linux/bpf_dsl/policy.h"
-
-#include <errno.h>
-
-#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-
-ResultExpr Policy::InvalidSyscall() const {
- return Error(ENOSYS);
-}
-
-} // namespace bpf_dsl
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy.h
deleted file mode 100644
index 6c6758945..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_BPF_DSL_POLICY_H_
-#define SANDBOX_LINUX_BPF_DSL_POLICY_H_
-
-#include "base/macros.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl_forward.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-
-// Interface to implement to define a BPF sandbox policy.
-class SANDBOX_EXPORT Policy {
- public:
- Policy() {}
- virtual ~Policy() {}
-
- // User extension point for writing custom sandbox policies.
- // The returned ResultExpr will control how the kernel responds to the
- // specified system call number.
- virtual ResultExpr EvaluateSyscall(int sysno) const = 0;
-
- // Optional overload for specifying alternate behavior for invalid
- // system calls. The default is to return ENOSYS.
- virtual ResultExpr InvalidSyscall() const;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(Policy);
-};
-
-} // namespace bpf_dsl
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_POLICY_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy_compiler.cc b/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy_compiler.cc
deleted file mode 100644
index 7ce517a5d..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy_compiler.cc
+++ /dev/null
@@ -1,466 +0,0 @@
-// 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.
-
-#include "sandbox/linux/bpf_dsl/policy_compiler.h"
-
-#include <errno.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/syscall.h>
-
-#include <limits>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl_impl.h"
-#include "sandbox/linux/bpf_dsl/codegen.h"
-#include "sandbox/linux/bpf_dsl/policy.h"
-#include "sandbox/linux/bpf_dsl/seccomp_macros.h"
-#include "sandbox/linux/bpf_dsl/syscall_set.h"
-#include "sandbox/linux/system_headers/linux_filter.h"
-#include "sandbox/linux/system_headers/linux_seccomp.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-
-namespace {
-
-#if defined(__i386__) || defined(__x86_64__)
-const bool kIsIntel = true;
-#else
-const bool kIsIntel = false;
-#endif
-#if defined(__x86_64__) && defined(__ILP32__)
-const bool kIsX32 = true;
-#else
-const bool kIsX32 = false;
-#endif
-
-const int kSyscallsRequiredForUnsafeTraps[] = {
- __NR_rt_sigprocmask,
- __NR_rt_sigreturn,
-#if defined(__NR_sigprocmask)
- __NR_sigprocmask,
-#endif
-#if defined(__NR_sigreturn)
- __NR_sigreturn,
-#endif
-};
-
-bool HasExactlyOneBit(uint64_t x) {
- // Common trick; e.g., see http://stackoverflow.com/a/108329.
- return x != 0 && (x & (x - 1)) == 0;
-}
-
-ResultExpr DefaultPanic(const char* error) {
- return Kill();
-}
-
-// A Trap() handler that returns an "errno" value. The value is encoded
-// in the "aux" parameter.
-intptr_t ReturnErrno(const struct arch_seccomp_data&, void* aux) {
- // TrapFnc functions report error by following the native kernel convention
- // of returning an exit code in the range of -1..-4096. They do not try to
- // set errno themselves. The glibc wrapper that triggered the SIGSYS will
- // ultimately do so for us.
- int err = reinterpret_cast<intptr_t>(aux) & SECCOMP_RET_DATA;
- return -err;
-}
-
-bool HasUnsafeTraps(const Policy* policy) {
- DCHECK(policy);
- for (uint32_t sysnum : SyscallSet::ValidOnly()) {
- if (policy->EvaluateSyscall(sysnum)->HasUnsafeTraps()) {
- return true;
- }
- }
- return policy->InvalidSyscall()->HasUnsafeTraps();
-}
-
-} // namespace
-
-struct PolicyCompiler::Range {
- uint32_t from;
- CodeGen::Node node;
-};
-
-PolicyCompiler::PolicyCompiler(const Policy* policy, TrapRegistry* registry)
- : policy_(policy),
- registry_(registry),
- escapepc_(0),
- panic_func_(DefaultPanic),
- gen_(),
- has_unsafe_traps_(HasUnsafeTraps(policy_)) {
- DCHECK(policy);
-}
-
-PolicyCompiler::~PolicyCompiler() {
-}
-
-CodeGen::Program PolicyCompiler::Compile() {
- CHECK(policy_->InvalidSyscall()->IsDeny())
- << "Policies should deny invalid system calls";
-
- // If our BPF program has unsafe traps, enable support for them.
- if (has_unsafe_traps_) {
- CHECK_NE(0U, escapepc_) << "UnsafeTrap() requires a valid escape PC";
-
- for (int sysnum : kSyscallsRequiredForUnsafeTraps) {
- CHECK(policy_->EvaluateSyscall(sysnum)->IsAllow())
- << "Policies that use UnsafeTrap() must unconditionally allow all "
- "required system calls";
- }
-
- CHECK(registry_->EnableUnsafeTraps())
- << "We'd rather die than enable unsafe traps";
- }
-
- // Assemble the BPF filter program.
- return gen_.Compile(AssemblePolicy());
-}
-
-void PolicyCompiler::DangerousSetEscapePC(uint64_t escapepc) {
- escapepc_ = escapepc;
-}
-
-void PolicyCompiler::SetPanicFunc(PanicFunc panic_func) {
- panic_func_ = panic_func;
-}
-
-CodeGen::Node PolicyCompiler::AssemblePolicy() {
- // A compiled policy consists of three logical parts:
- // 1. Check that the "arch" field matches the expected architecture.
- // 2. If the policy involves unsafe traps, check if the syscall was
- // invoked by Syscall::Call, and then allow it unconditionally.
- // 3. Check the system call number and jump to the appropriate compiled
- // system call policy number.
- return CheckArch(MaybeAddEscapeHatch(DispatchSyscall()));
-}
-
-CodeGen::Node PolicyCompiler::CheckArch(CodeGen::Node passed) {
- // If the architecture doesn't match SECCOMP_ARCH, disallow the
- // system call.
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS, SECCOMP_ARCH_IDX,
- gen_.MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K, SECCOMP_ARCH, passed,
- CompileResult(panic_func_(
- "Invalid audit architecture in BPF filter"))));
-}
-
-CodeGen::Node PolicyCompiler::MaybeAddEscapeHatch(CodeGen::Node rest) {
- // If no unsafe traps, then simply return |rest|.
- if (!has_unsafe_traps_) {
- return rest;
- }
-
- // We already enabled unsafe traps in Compile, but enable them again to give
- // the trap registry a second chance to complain before we add the backdoor.
- CHECK(registry_->EnableUnsafeTraps());
-
- // Allow system calls, if they originate from our magic return address.
- const uint32_t lopc = static_cast<uint32_t>(escapepc_);
- const uint32_t hipc = static_cast<uint32_t>(escapepc_ >> 32);
-
- // BPF cannot do native 64-bit comparisons, so we have to compare
- // both 32-bit halves of the instruction pointer. If they match what
- // we expect, we return ERR_ALLOWED. If either or both don't match,
- // we continue evalutating the rest of the sandbox policy.
- //
- // For simplicity, we check the full 64-bit instruction pointer even
- // on 32-bit architectures.
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS, SECCOMP_IP_LSB_IDX,
- gen_.MakeInstruction(
- BPF_JMP + BPF_JEQ + BPF_K, lopc,
- gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS, SECCOMP_IP_MSB_IDX,
- gen_.MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K, hipc,
- CompileResult(Allow()), rest)),
- rest));
-}
-
-CodeGen::Node PolicyCompiler::DispatchSyscall() {
- // Evaluate all possible system calls and group their Nodes into
- // ranges of identical codes.
- Ranges ranges;
- FindRanges(&ranges);
-
- // Compile the system call ranges to an optimized BPF jumptable
- CodeGen::Node jumptable = AssembleJumpTable(ranges.begin(), ranges.end());
-
- // Grab the system call number, so that we can check it and then
- // execute the jump table.
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS, SECCOMP_NR_IDX, CheckSyscallNumber(jumptable));
-}
-
-CodeGen::Node PolicyCompiler::CheckSyscallNumber(CodeGen::Node passed) {
- if (kIsIntel) {
- // On Intel architectures, verify that system call numbers are in the
- // expected number range.
- CodeGen::Node invalidX32 =
- CompileResult(panic_func_("Illegal mixing of system call ABIs"));
- if (kIsX32) {
- // The newer x32 API always sets bit 30.
- return gen_.MakeInstruction(
- BPF_JMP + BPF_JSET + BPF_K, 0x40000000, passed, invalidX32);
- } else {
- // The older i386 and x86-64 APIs clear bit 30 on all system calls.
- return gen_.MakeInstruction(
- BPF_JMP + BPF_JSET + BPF_K, 0x40000000, invalidX32, passed);
- }
- }
-
- // TODO(mdempsky): Similar validation for other architectures?
- return passed;
-}
-
-void PolicyCompiler::FindRanges(Ranges* ranges) {
- // Please note that "struct seccomp_data" defines system calls as a signed
- // int32_t, but BPF instructions always operate on unsigned quantities. We
- // deal with this disparity by enumerating from MIN_SYSCALL to MAX_SYSCALL,
- // and then verifying that the rest of the number range (both positive and
- // negative) all return the same Node.
- const CodeGen::Node invalid_node = CompileResult(policy_->InvalidSyscall());
- uint32_t old_sysnum = 0;
- CodeGen::Node old_node =
- SyscallSet::IsValid(old_sysnum)
- ? CompileResult(policy_->EvaluateSyscall(old_sysnum))
- : invalid_node;
-
- for (uint32_t sysnum : SyscallSet::All()) {
- CodeGen::Node node =
- SyscallSet::IsValid(sysnum)
- ? CompileResult(policy_->EvaluateSyscall(static_cast<int>(sysnum)))
- : invalid_node;
- // N.B., here we rely on CodeGen folding (i.e., returning the same
- // node value for) identical code sequences, otherwise our jump
- // table will blow up in size.
- if (node != old_node) {
- ranges->push_back(Range{old_sysnum, old_node});
- old_sysnum = sysnum;
- old_node = node;
- }
- }
- ranges->push_back(Range{old_sysnum, old_node});
-}
-
-CodeGen::Node PolicyCompiler::AssembleJumpTable(Ranges::const_iterator start,
- Ranges::const_iterator stop) {
- // We convert the list of system call ranges into jump table that performs
- // a binary search over the ranges.
- // As a sanity check, we need to have at least one distinct ranges for us
- // to be able to build a jump table.
- CHECK(start < stop) << "Invalid iterator range";
- const auto n = stop - start;
- if (n == 1) {
- // If we have narrowed things down to a single range object, we can
- // return from the BPF filter program.
- return start->node;
- }
-
- // Pick the range object that is located at the mid point of our list.
- // We compare our system call number against the lowest valid system call
- // number in this range object. If our number is lower, it is outside of
- // this range object. If it is greater or equal, it might be inside.
- Ranges::const_iterator mid = start + n / 2;
-
- // Sub-divide the list of ranges and continue recursively.
- CodeGen::Node jf = AssembleJumpTable(start, mid);
- CodeGen::Node jt = AssembleJumpTable(mid, stop);
- return gen_.MakeInstruction(BPF_JMP + BPF_JGE + BPF_K, mid->from, jt, jf);
-}
-
-CodeGen::Node PolicyCompiler::CompileResult(const ResultExpr& res) {
- return res->Compile(this);
-}
-
-CodeGen::Node PolicyCompiler::MaskedEqual(int argno,
- size_t width,
- uint64_t mask,
- uint64_t value,
- CodeGen::Node passed,
- CodeGen::Node failed) {
- // Sanity check that arguments make sense.
- CHECK(argno >= 0 && argno < 6) << "Invalid argument number " << argno;
- CHECK(width == 4 || width == 8) << "Invalid argument width " << width;
- CHECK_NE(0U, mask) << "Zero mask is invalid";
- CHECK_EQ(value, value & mask) << "Value contains masked out bits";
- if (sizeof(void*) == 4) {
- CHECK_EQ(4U, width) << "Invalid width on 32-bit platform";
- }
- if (width == 4) {
- CHECK_EQ(0U, mask >> 32) << "Mask exceeds argument size";
- CHECK_EQ(0U, value >> 32) << "Value exceeds argument size";
- }
-
- // We want to emit code to check "(arg & mask) == value" where arg, mask, and
- // value are 64-bit values, but the BPF machine is only 32-bit. We implement
- // this by independently testing the upper and lower 32-bits and continuing to
- // |passed| if both evaluate true, or to |failed| if either evaluate false.
- return MaskedEqualHalf(argno, width, mask, value, ArgHalf::UPPER,
- MaskedEqualHalf(argno, width, mask, value,
- ArgHalf::LOWER, passed, failed),
- failed);
-}
-
-CodeGen::Node PolicyCompiler::MaskedEqualHalf(int argno,
- size_t width,
- uint64_t full_mask,
- uint64_t full_value,
- ArgHalf half,
- CodeGen::Node passed,
- CodeGen::Node failed) {
- if (width == 4 && half == ArgHalf::UPPER) {
- // Special logic for sanity checking the upper 32-bits of 32-bit system
- // call arguments.
-
- // TODO(mdempsky): Compile Unexpected64bitArgument() just per program.
- CodeGen::Node invalid_64bit = Unexpected64bitArgument();
-
- const uint32_t upper = SECCOMP_ARG_MSB_IDX(argno);
- const uint32_t lower = SECCOMP_ARG_LSB_IDX(argno);
-
- if (sizeof(void*) == 4) {
- // On 32-bit platforms, the upper 32-bits should always be 0:
- // LDW [upper]
- // JEQ 0, passed, invalid
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS,
- upper,
- gen_.MakeInstruction(
- BPF_JMP + BPF_JEQ + BPF_K, 0, passed, invalid_64bit));
- }
-
- // On 64-bit platforms, the upper 32-bits may be 0 or ~0; but we only allow
- // ~0 if the sign bit of the lower 32-bits is set too:
- // LDW [upper]
- // JEQ 0, passed, (next)
- // JEQ ~0, (next), invalid
- // LDW [lower]
- // JSET (1<<31), passed, invalid
- //
- // TODO(mdempsky): The JSET instruction could perhaps jump to passed->next
- // instead, as the first instruction of passed should be "LDW [lower]".
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS,
- upper,
- gen_.MakeInstruction(
- BPF_JMP + BPF_JEQ + BPF_K,
- 0,
- passed,
- gen_.MakeInstruction(
- BPF_JMP + BPF_JEQ + BPF_K,
- std::numeric_limits<uint32_t>::max(),
- gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS,
- lower,
- gen_.MakeInstruction(BPF_JMP + BPF_JSET + BPF_K,
- 1U << 31,
- passed,
- invalid_64bit)),
- invalid_64bit)));
- }
-
- const uint32_t idx = (half == ArgHalf::UPPER) ? SECCOMP_ARG_MSB_IDX(argno)
- : SECCOMP_ARG_LSB_IDX(argno);
- const uint32_t mask = (half == ArgHalf::UPPER) ? full_mask >> 32 : full_mask;
- const uint32_t value =
- (half == ArgHalf::UPPER) ? full_value >> 32 : full_value;
-
- // Emit a suitable instruction sequence for (arg & mask) == value.
-
- // For (arg & 0) == 0, just return passed.
- if (mask == 0) {
- CHECK_EQ(0U, value);
- return passed;
- }
-
- // For (arg & ~0) == value, emit:
- // LDW [idx]
- // JEQ value, passed, failed
- if (mask == std::numeric_limits<uint32_t>::max()) {
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS,
- idx,
- gen_.MakeInstruction(BPF_JMP + BPF_JEQ + BPF_K, value, passed, failed));
- }
-
- // For (arg & mask) == 0, emit:
- // LDW [idx]
- // JSET mask, failed, passed
- // (Note: failed and passed are intentionally swapped.)
- if (value == 0) {
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS,
- idx,
- gen_.MakeInstruction(BPF_JMP + BPF_JSET + BPF_K, mask, failed, passed));
- }
-
- // For (arg & x) == x where x is a single-bit value, emit:
- // LDW [idx]
- // JSET mask, passed, failed
- if (mask == value && HasExactlyOneBit(mask)) {
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS,
- idx,
- gen_.MakeInstruction(BPF_JMP + BPF_JSET + BPF_K, mask, passed, failed));
- }
-
- // Generic fallback:
- // LDW [idx]
- // AND mask
- // JEQ value, passed, failed
- return gen_.MakeInstruction(
- BPF_LD + BPF_W + BPF_ABS,
- idx,
- gen_.MakeInstruction(
- BPF_ALU + BPF_AND + BPF_K,
- mask,
- gen_.MakeInstruction(
- BPF_JMP + BPF_JEQ + BPF_K, value, passed, failed)));
-}
-
-CodeGen::Node PolicyCompiler::Unexpected64bitArgument() {
- return CompileResult(panic_func_("Unexpected 64bit argument detected"));
-}
-
-CodeGen::Node PolicyCompiler::Return(uint32_t ret) {
- if (has_unsafe_traps_ && (ret & SECCOMP_RET_ACTION) == SECCOMP_RET_ERRNO) {
- // When inside an UnsafeTrap() callback, we want to allow all system calls.
- // This means, we must conditionally disable the sandbox -- and that's not
- // something that kernel-side BPF filters can do, as they cannot inspect
- // any state other than the syscall arguments.
- // But if we redirect all error handlers to user-space, then we can easily
- // make this decision.
- // The performance penalty for this extra round-trip to user-space is not
- // actually that bad, as we only ever pay it for denied system calls; and a
- // typical program has very few of these.
- return Trap(ReturnErrno, reinterpret_cast<void*>(ret & SECCOMP_RET_DATA),
- true);
- }
-
- return gen_.MakeInstruction(BPF_RET + BPF_K, ret);
-}
-
-CodeGen::Node PolicyCompiler::Trap(TrapRegistry::TrapFnc fnc,
- const void* aux,
- bool safe) {
- uint16_t trap_id = registry_->Add(fnc, aux, safe);
- return gen_.MakeInstruction(BPF_RET + BPF_K, SECCOMP_RET_TRAP + trap_id);
-}
-
-bool PolicyCompiler::IsRequiredForUnsafeTrap(int sysno) {
- for (size_t i = 0; i < arraysize(kSyscallsRequiredForUnsafeTraps); ++i) {
- if (sysno == kSyscallsRequiredForUnsafeTraps[i]) {
- return true;
- }
- }
- return false;
-}
-
-} // namespace bpf_dsl
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy_compiler.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy_compiler.h
deleted file mode 100644
index 48b1d780d..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/policy_compiler.h
+++ /dev/null
@@ -1,153 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_BPF_DSL_POLICY_COMPILER_H_
-#define SANDBOX_LINUX_BPF_DSL_POLICY_COMPILER_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <vector>
-
-#include "base/macros.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl_forward.h"
-#include "sandbox/linux/bpf_dsl/codegen.h"
-#include "sandbox/linux/bpf_dsl/trap_registry.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-class Policy;
-
-// PolicyCompiler implements the bpf_dsl compiler, allowing users to
-// transform bpf_dsl policies into BPF programs to be executed by the
-// Linux kernel.
-class SANDBOX_EXPORT PolicyCompiler {
- public:
- using PanicFunc = bpf_dsl::ResultExpr (*)(const char* error);
-
- PolicyCompiler(const Policy* policy, TrapRegistry* registry);
- ~PolicyCompiler();
-
- // Compile registers any trap handlers needed by the policy and
- // compiles the policy to a BPF program, which it returns.
- CodeGen::Program Compile();
-
- // DangerousSetEscapePC sets the "escape PC" that is allowed to issue any
- // system calls, regardless of policy.
- void DangerousSetEscapePC(uint64_t escapepc);
-
- // SetPanicFunc sets the callback function used for handling faulty
- // system call conditions. The default behavior is to immediately kill
- // the process.
- // TODO(mdempsky): Move this into Policy?
- void SetPanicFunc(PanicFunc panic_func);
-
- // UnsafeTraps require some syscalls to always be allowed.
- // This helper function returns true for these calls.
- static bool IsRequiredForUnsafeTrap(int sysno);
-
- // Functions below are meant for use within bpf_dsl itself.
-
- // Return returns a CodeGen::Node that returns the specified seccomp
- // return value.
- CodeGen::Node Return(uint32_t ret);
-
- // Trap returns a CodeGen::Node to indicate the system call should
- // instead invoke a trap handler.
- CodeGen::Node Trap(TrapRegistry::TrapFnc fnc, const void* aux, bool safe);
-
- // MaskedEqual returns a CodeGen::Node that represents a conditional branch.
- // Argument "argno" (1..6) will be bitwise-AND'd with "mask" and compared
- // to "value"; if equal, then "passed" will be executed, otherwise "failed".
- // If "width" is 4, the argument must in the range of 0x0..(1u << 32 - 1)
- // If it is outside this range, the sandbox treats the system call just
- // the same as any other ABI violation (i.e., it panics).
- CodeGen::Node MaskedEqual(int argno,
- size_t width,
- uint64_t mask,
- uint64_t value,
- CodeGen::Node passed,
- CodeGen::Node failed);
-
- private:
- struct Range;
- typedef std::vector<Range> Ranges;
-
- // Used by MaskedEqualHalf to track which half of the argument it's
- // emitting instructions for.
- enum class ArgHalf {
- LOWER,
- UPPER,
- };
-
- // Compile the configured policy into a complete instruction sequence.
- CodeGen::Node AssemblePolicy();
-
- // Return an instruction sequence that checks the
- // arch_seccomp_data's "arch" field is valid, and then passes
- // control to |passed| if so.
- CodeGen::Node CheckArch(CodeGen::Node passed);
-
- // If |has_unsafe_traps_| is true, returns an instruction sequence
- // that allows all system calls from |escapepc_|, and otherwise
- // passes control to |rest|. Otherwise, simply returns |rest|.
- CodeGen::Node MaybeAddEscapeHatch(CodeGen::Node rest);
-
- // Return an instruction sequence that loads and checks the system
- // call number, performs a binary search, and then dispatches to an
- // appropriate instruction sequence compiled from the current
- // policy.
- CodeGen::Node DispatchSyscall();
-
- // Return an instruction sequence that checks the system call number
- // (expected to be loaded in register A) and if valid, passes
- // control to |passed| (with register A still valid).
- CodeGen::Node CheckSyscallNumber(CodeGen::Node passed);
-
- // Finds all the ranges of system calls that need to be handled. Ranges are
- // sorted in ascending order of system call numbers. There are no gaps in the
- // ranges. System calls with identical CodeGen::Nodes are coalesced into a
- // single
- // range.
- void FindRanges(Ranges* ranges);
-
- // Returns a BPF program snippet that implements a jump table for the
- // given range of system call numbers. This function runs recursively.
- CodeGen::Node AssembleJumpTable(Ranges::const_iterator start,
- Ranges::const_iterator stop);
-
- // CompileResult compiles an individual result expression into a
- // CodeGen node.
- CodeGen::Node CompileResult(const ResultExpr& res);
-
- // Returns a BPF program that evaluates half of a conditional expression;
- // it should only ever be called from CondExpression().
- CodeGen::Node MaskedEqualHalf(int argno,
- size_t width,
- uint64_t full_mask,
- uint64_t full_value,
- ArgHalf half,
- CodeGen::Node passed,
- CodeGen::Node failed);
-
- // Returns the fatal CodeGen::Node that is used to indicate that somebody
- // attempted to pass a 64bit value in a 32bit system call argument.
- CodeGen::Node Unexpected64bitArgument();
-
- const Policy* policy_;
- TrapRegistry* registry_;
- uint64_t escapepc_;
- PanicFunc panic_func_;
-
- CodeGen gen_;
- bool has_unsafe_traps_;
-
- DISALLOW_COPY_AND_ASSIGN(PolicyCompiler);
-};
-
-} // namespace bpf_dsl
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_POLICY_COMPILER_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/seccomp_macros.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/seccomp_macros.h
deleted file mode 100644
index af70f21cd..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/seccomp_macros.h
+++ /dev/null
@@ -1,294 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_BPF_DSL_SECCOMP_MACROS_H_
-#define SANDBOX_LINUX_BPF_DSL_SECCOMP_MACROS_H_
-
-#include <sys/types.h> // For __BIONIC__.
-// Old Bionic versions do not have sys/user.h. The if can be removed once we no
-// longer need to support these old Bionic versions.
-// All x86_64 builds use a new enough bionic to have sys/user.h.
-#if !defined(__BIONIC__) || defined(__x86_64__)
-#if !defined(__native_client_nonsfi__)
-#include <sys/user.h>
-#endif
-#if defined(__mips__)
-// sys/user.h in eglibc misses size_t definition
-#include <stddef.h>
-#endif
-#endif
-
-#include "sandbox/linux/system_headers/linux_seccomp.h" // For AUDIT_ARCH_*
-
-// Impose some reasonable maximum BPF program size. Realistically, the
-// kernel probably has much lower limits. But by limiting to less than
-// 30 bits, we can ease requirements on some of our data types.
-#define SECCOMP_MAX_PROGRAM_SIZE (1<<30)
-
-#if defined(__i386__)
-#define SECCOMP_ARCH AUDIT_ARCH_I386
-
-#define SECCOMP_REG(_ctx, _reg) ((_ctx)->uc_mcontext.gregs[(_reg)])
-#define SECCOMP_RESULT(_ctx) SECCOMP_REG(_ctx, REG_EAX)
-#define SECCOMP_SYSCALL(_ctx) SECCOMP_REG(_ctx, REG_EAX)
-#define SECCOMP_IP(_ctx) SECCOMP_REG(_ctx, REG_EIP)
-#define SECCOMP_PARM1(_ctx) SECCOMP_REG(_ctx, REG_EBX)
-#define SECCOMP_PARM2(_ctx) SECCOMP_REG(_ctx, REG_ECX)
-#define SECCOMP_PARM3(_ctx) SECCOMP_REG(_ctx, REG_EDX)
-#define SECCOMP_PARM4(_ctx) SECCOMP_REG(_ctx, REG_ESI)
-#define SECCOMP_PARM5(_ctx) SECCOMP_REG(_ctx, REG_EDI)
-#define SECCOMP_PARM6(_ctx) SECCOMP_REG(_ctx, REG_EBP)
-#define SECCOMP_NR_IDX (offsetof(struct arch_seccomp_data, nr))
-#define SECCOMP_ARCH_IDX (offsetof(struct arch_seccomp_data, arch))
-#define SECCOMP_IP_MSB_IDX (offsetof(struct arch_seccomp_data, \
- instruction_pointer) + 4)
-#define SECCOMP_IP_LSB_IDX (offsetof(struct arch_seccomp_data, \
- instruction_pointer) + 0)
-#define SECCOMP_ARG_MSB_IDX(nr) (offsetof(struct arch_seccomp_data, args) + \
- 8*(nr) + 4)
-#define SECCOMP_ARG_LSB_IDX(nr) (offsetof(struct arch_seccomp_data, args) + \
- 8*(nr) + 0)
-
-
-#if defined(__BIONIC__) || defined(__native_client_nonsfi__)
-// Old Bionic versions and PNaCl toolchain don't have sys/user.h, so we just
-// define regs_struct directly. This can be removed once we no longer need to
-// support these old Bionic versions and PNaCl toolchain.
-struct regs_struct {
- long int ebx;
- long int ecx;
- long int edx;
- long int esi;
- long int edi;
- long int ebp;
- long int eax;
- long int xds;
- long int xes;
- long int xfs;
- long int xgs;
- long int orig_eax;
- long int eip;
- long int xcs;
- long int eflags;
- long int esp;
- long int xss;
-};
-#else
-typedef user_regs_struct regs_struct;
-#endif
-
-#define SECCOMP_PT_RESULT(_regs) (_regs).eax
-#define SECCOMP_PT_SYSCALL(_regs) (_regs).orig_eax
-#define SECCOMP_PT_IP(_regs) (_regs).eip
-#define SECCOMP_PT_PARM1(_regs) (_regs).ebx
-#define SECCOMP_PT_PARM2(_regs) (_regs).ecx
-#define SECCOMP_PT_PARM3(_regs) (_regs).edx
-#define SECCOMP_PT_PARM4(_regs) (_regs).esi
-#define SECCOMP_PT_PARM5(_regs) (_regs).edi
-#define SECCOMP_PT_PARM6(_regs) (_regs).ebp
-
-#elif defined(__x86_64__)
-#define SECCOMP_ARCH AUDIT_ARCH_X86_64
-
-#define SECCOMP_REG(_ctx, _reg) ((_ctx)->uc_mcontext.gregs[(_reg)])
-#define SECCOMP_RESULT(_ctx) SECCOMP_REG(_ctx, REG_RAX)
-#define SECCOMP_SYSCALL(_ctx) SECCOMP_REG(_ctx, REG_RAX)
-#define SECCOMP_IP(_ctx) SECCOMP_REG(_ctx, REG_RIP)
-#define SECCOMP_PARM1(_ctx) SECCOMP_REG(_ctx, REG_RDI)
-#define SECCOMP_PARM2(_ctx) SECCOMP_REG(_ctx, REG_RSI)
-#define SECCOMP_PARM3(_ctx) SECCOMP_REG(_ctx, REG_RDX)
-#define SECCOMP_PARM4(_ctx) SECCOMP_REG(_ctx, REG_R10)
-#define SECCOMP_PARM5(_ctx) SECCOMP_REG(_ctx, REG_R8)
-#define SECCOMP_PARM6(_ctx) SECCOMP_REG(_ctx, REG_R9)
-#define SECCOMP_NR_IDX (offsetof(struct arch_seccomp_data, nr))
-#define SECCOMP_ARCH_IDX (offsetof(struct arch_seccomp_data, arch))
-#define SECCOMP_IP_MSB_IDX (offsetof(struct arch_seccomp_data, \
- instruction_pointer) + 4)
-#define SECCOMP_IP_LSB_IDX (offsetof(struct arch_seccomp_data, \
- instruction_pointer) + 0)
-#define SECCOMP_ARG_MSB_IDX(nr) (offsetof(struct arch_seccomp_data, args) + \
- 8*(nr) + 4)
-#define SECCOMP_ARG_LSB_IDX(nr) (offsetof(struct arch_seccomp_data, args) + \
- 8*(nr) + 0)
-
-typedef user_regs_struct regs_struct;
-#define SECCOMP_PT_RESULT(_regs) (_regs).rax
-#define SECCOMP_PT_SYSCALL(_regs) (_regs).orig_rax
-#define SECCOMP_PT_IP(_regs) (_regs).rip
-#define SECCOMP_PT_PARM1(_regs) (_regs).rdi
-#define SECCOMP_PT_PARM2(_regs) (_regs).rsi
-#define SECCOMP_PT_PARM3(_regs) (_regs).rdx
-#define SECCOMP_PT_PARM4(_regs) (_regs).r10
-#define SECCOMP_PT_PARM5(_regs) (_regs).r8
-#define SECCOMP_PT_PARM6(_regs) (_regs).r9
-
-#elif defined(__arm__) && (defined(__thumb__) || defined(__ARM_EABI__))
-#define SECCOMP_ARCH AUDIT_ARCH_ARM
-
-// ARM sigcontext_t is different from i386/x86_64.
-// See </arch/arm/include/asm/sigcontext.h> in the Linux kernel.
-#define SECCOMP_REG(_ctx, _reg) ((_ctx)->uc_mcontext.arm_##_reg)
-// ARM EABI syscall convention.
-#define SECCOMP_RESULT(_ctx) SECCOMP_REG(_ctx, r0)
-#define SECCOMP_SYSCALL(_ctx) SECCOMP_REG(_ctx, r7)
-#define SECCOMP_IP(_ctx) SECCOMP_REG(_ctx, pc)
-#define SECCOMP_PARM1(_ctx) SECCOMP_REG(_ctx, r0)
-#define SECCOMP_PARM2(_ctx) SECCOMP_REG(_ctx, r1)
-#define SECCOMP_PARM3(_ctx) SECCOMP_REG(_ctx, r2)
-#define SECCOMP_PARM4(_ctx) SECCOMP_REG(_ctx, r3)
-#define SECCOMP_PARM5(_ctx) SECCOMP_REG(_ctx, r4)
-#define SECCOMP_PARM6(_ctx) SECCOMP_REG(_ctx, r5)
-#define SECCOMP_NR_IDX (offsetof(struct arch_seccomp_data, nr))
-#define SECCOMP_ARCH_IDX (offsetof(struct arch_seccomp_data, arch))
-#define SECCOMP_IP_MSB_IDX (offsetof(struct arch_seccomp_data, \
- instruction_pointer) + 4)
-#define SECCOMP_IP_LSB_IDX (offsetof(struct arch_seccomp_data, \
- instruction_pointer) + 0)
-#define SECCOMP_ARG_MSB_IDX(nr) (offsetof(struct arch_seccomp_data, args) + \
- 8*(nr) + 4)
-#define SECCOMP_ARG_LSB_IDX(nr) (offsetof(struct arch_seccomp_data, args) + \
- 8*(nr) + 0)
-
-#if defined(__BIONIC__) || defined(__native_client_nonsfi__)
-// Old Bionic versions and PNaCl toolchain don't have sys/user.h, so we just
-// define regs_struct directly. This can be removed once we no longer need to
-// support these old Bionic versions and PNaCl toolchain.
-struct regs_struct {
- unsigned long uregs[18];
-};
-#else
-typedef user_regs regs_struct;
-#endif
-
-#define REG_cpsr uregs[16]
-#define REG_pc uregs[15]
-#define REG_lr uregs[14]
-#define REG_sp uregs[13]
-#define REG_ip uregs[12]
-#define REG_fp uregs[11]
-#define REG_r10 uregs[10]
-#define REG_r9 uregs[9]
-#define REG_r8 uregs[8]
-#define REG_r7 uregs[7]
-#define REG_r6 uregs[6]
-#define REG_r5 uregs[5]
-#define REG_r4 uregs[4]
-#define REG_r3 uregs[3]
-#define REG_r2 uregs[2]
-#define REG_r1 uregs[1]
-#define REG_r0 uregs[0]
-#define REG_ORIG_r0 uregs[17]
-
-#define SECCOMP_PT_RESULT(_regs) (_regs).REG_r0
-#define SECCOMP_PT_SYSCALL(_regs) (_regs).REG_r7
-#define SECCOMP_PT_IP(_regs) (_regs).REG_pc
-#define SECCOMP_PT_PARM1(_regs) (_regs).REG_r0
-#define SECCOMP_PT_PARM2(_regs) (_regs).REG_r1
-#define SECCOMP_PT_PARM3(_regs) (_regs).REG_r2
-#define SECCOMP_PT_PARM4(_regs) (_regs).REG_r3
-#define SECCOMP_PT_PARM5(_regs) (_regs).REG_r4
-#define SECCOMP_PT_PARM6(_regs) (_regs).REG_r5
-
-#elif defined(__mips__) && (_MIPS_SIM == _MIPS_SIM_ABI32)
-#define SECCOMP_ARCH AUDIT_ARCH_MIPSEL
-#define SYSCALL_EIGHT_ARGS
-// MIPS sigcontext_t is different from i386/x86_64 and ARM.
-// See </arch/mips/include/uapi/asm/sigcontext.h> in the Linux kernel.
-#define SECCOMP_REG(_ctx, _reg) ((_ctx)->uc_mcontext.gregs[_reg])
-// Based on MIPS o32 ABI syscall convention.
-// On MIPS, when indirect syscall is being made (syscall(__NR_foo)),
-// real identificator (__NR_foo) is not in v0, but in a0
-#define SECCOMP_RESULT(_ctx) SECCOMP_REG(_ctx, 2)
-#define SECCOMP_SYSCALL(_ctx) SECCOMP_REG(_ctx, 2)
-#define SECCOMP_IP(_ctx) (_ctx)->uc_mcontext.pc
-#define SECCOMP_PARM1(_ctx) SECCOMP_REG(_ctx, 4)
-#define SECCOMP_PARM2(_ctx) SECCOMP_REG(_ctx, 5)
-#define SECCOMP_PARM3(_ctx) SECCOMP_REG(_ctx, 6)
-#define SECCOMP_PARM4(_ctx) SECCOMP_REG(_ctx, 7)
-// Only the first 4 arguments of syscall are in registers.
-// The rest are on the stack.
-#define SECCOMP_STACKPARM(_ctx, n) (((long *)SECCOMP_REG(_ctx, 29))[(n)])
-#define SECCOMP_PARM5(_ctx) SECCOMP_STACKPARM(_ctx, 4)
-#define SECCOMP_PARM6(_ctx) SECCOMP_STACKPARM(_ctx, 5)
-#define SECCOMP_PARM7(_ctx) SECCOMP_STACKPARM(_ctx, 6)
-#define SECCOMP_PARM8(_ctx) SECCOMP_STACKPARM(_ctx, 7)
-#define SECCOMP_NR_IDX (offsetof(struct arch_seccomp_data, nr))
-#define SECCOMP_ARCH_IDX (offsetof(struct arch_seccomp_data, arch))
-#define SECCOMP_IP_MSB_IDX (offsetof(struct arch_seccomp_data, \
- instruction_pointer) + 4)
-#define SECCOMP_IP_LSB_IDX (offsetof(struct arch_seccomp_data, \
- instruction_pointer) + 0)
-#define SECCOMP_ARG_MSB_IDX(nr) (offsetof(struct arch_seccomp_data, args) + \
- 8*(nr) + 4)
-#define SECCOMP_ARG_LSB_IDX(nr) (offsetof(struct arch_seccomp_data, args) + \
- 8*(nr) + 0)
-
-// On Mips we don't have structures like user_regs or user_regs_struct in
-// sys/user.h that we could use, so we just define regs_struct directly.
-struct regs_struct {
- unsigned long long regs[32];
-};
-
-#define REG_a3 regs[7]
-#define REG_a2 regs[6]
-#define REG_a1 regs[5]
-#define REG_a0 regs[4]
-#define REG_v1 regs[3]
-#define REG_v0 regs[2]
-
-#define SECCOMP_PT_RESULT(_regs) (_regs).REG_v0
-#define SECCOMP_PT_SYSCALL(_regs) (_regs).REG_v0
-#define SECCOMP_PT_PARM1(_regs) (_regs).REG_a0
-#define SECCOMP_PT_PARM2(_regs) (_regs).REG_a1
-#define SECCOMP_PT_PARM3(_regs) (_regs).REG_a2
-#define SECCOMP_PT_PARM4(_regs) (_regs).REG_a3
-
-#elif defined(__aarch64__)
-struct regs_struct {
- unsigned long long regs[31];
- unsigned long long sp;
- unsigned long long pc;
- unsigned long long pstate;
-};
-
-#define SECCOMP_ARCH AUDIT_ARCH_AARCH64
-
-#define SECCOMP_REG(_ctx, _reg) ((_ctx)->uc_mcontext.regs[_reg])
-
-#define SECCOMP_RESULT(_ctx) SECCOMP_REG(_ctx, 0)
-#define SECCOMP_SYSCALL(_ctx) SECCOMP_REG(_ctx, 8)
-#define SECCOMP_IP(_ctx) (_ctx)->uc_mcontext.pc
-#define SECCOMP_PARM1(_ctx) SECCOMP_REG(_ctx, 0)
-#define SECCOMP_PARM2(_ctx) SECCOMP_REG(_ctx, 1)
-#define SECCOMP_PARM3(_ctx) SECCOMP_REG(_ctx, 2)
-#define SECCOMP_PARM4(_ctx) SECCOMP_REG(_ctx, 3)
-#define SECCOMP_PARM5(_ctx) SECCOMP_REG(_ctx, 4)
-#define SECCOMP_PARM6(_ctx) SECCOMP_REG(_ctx, 5)
-
-#define SECCOMP_NR_IDX (offsetof(struct arch_seccomp_data, nr))
-#define SECCOMP_ARCH_IDX (offsetof(struct arch_seccomp_data, arch))
-#define SECCOMP_IP_MSB_IDX \
- (offsetof(struct arch_seccomp_data, instruction_pointer) + 4)
-#define SECCOMP_IP_LSB_IDX \
- (offsetof(struct arch_seccomp_data, instruction_pointer) + 0)
-#define SECCOMP_ARG_MSB_IDX(nr) \
- (offsetof(struct arch_seccomp_data, args) + 8 * (nr) + 4)
-#define SECCOMP_ARG_LSB_IDX(nr) \
- (offsetof(struct arch_seccomp_data, args) + 8 * (nr) + 0)
-
-#define SECCOMP_PT_RESULT(_regs) (_regs).regs[0]
-#define SECCOMP_PT_SYSCALL(_regs) (_regs).regs[8]
-#define SECCOMP_PT_IP(_regs) (_regs).pc
-#define SECCOMP_PT_PARM1(_regs) (_regs).regs[0]
-#define SECCOMP_PT_PARM2(_regs) (_regs).regs[1]
-#define SECCOMP_PT_PARM3(_regs) (_regs).regs[2]
-#define SECCOMP_PT_PARM4(_regs) (_regs).regs[3]
-#define SECCOMP_PT_PARM5(_regs) (_regs).regs[4]
-#define SECCOMP_PT_PARM6(_regs) (_regs).regs[5]
-#else
-#error Unsupported target platform
-
-#endif
-
-#endif // SANDBOX_LINUX_BPF_DSL_SECCOMP_MACROS_H_
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/syscall_set.cc b/security/sandbox/chromium/sandbox/linux/bpf_dsl/syscall_set.cc
deleted file mode 100644
index 3d61fa31f..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/syscall_set.cc
+++ /dev/null
@@ -1,146 +0,0 @@
-// 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.
-
-#include "sandbox/linux/bpf_dsl/syscall_set.h"
-
-#include <stdint.h>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "sandbox/linux/bpf_dsl/linux_syscall_ranges.h"
-
-namespace sandbox {
-
-namespace {
-
-#if defined(__mips__) && (_MIPS_SIM == _MIPS_SIM_ABI32)
-// This is true for Mips O32 ABI.
-static_assert(MIN_SYSCALL == __NR_Linux, "min syscall number should be 4000");
-#else
-// This true for supported architectures (Intel and ARM EABI).
-static_assert(MIN_SYSCALL == 0u,
- "min syscall should always be zero");
-#endif
-
-// SyscallRange represents an inclusive range of system call numbers.
-struct SyscallRange {
- uint32_t first;
- uint32_t last;
-};
-
-const SyscallRange kValidSyscallRanges[] = {
- // First we iterate up to MAX_PUBLIC_SYSCALL, which is equal to MAX_SYSCALL
- // on Intel architectures, but leaves room for private syscalls on ARM.
- {MIN_SYSCALL, MAX_PUBLIC_SYSCALL},
-#if defined(__arm__)
- // ARM EABI includes "ARM private" system calls starting at
- // MIN_PRIVATE_SYSCALL, and a "ghost syscall private to the kernel" at
- // MIN_GHOST_SYSCALL.
- {MIN_PRIVATE_SYSCALL, MAX_PRIVATE_SYSCALL},
- {MIN_GHOST_SYSCALL, MAX_SYSCALL},
-#endif
-};
-
-} // namespace
-
-SyscallSet::Iterator SyscallSet::begin() const {
- return Iterator(set_, false);
-}
-
-SyscallSet::Iterator SyscallSet::end() const {
- return Iterator(set_, true);
-}
-
-bool SyscallSet::IsValid(uint32_t num) {
- for (const SyscallRange& range : kValidSyscallRanges) {
- if (num >= range.first && num <= range.last) {
- return true;
- }
- }
- return false;
-}
-
-bool operator==(const SyscallSet& lhs, const SyscallSet& rhs) {
- return (lhs.set_ == rhs.set_);
-}
-
-SyscallSet::Iterator::Iterator(Set set, bool done)
- : set_(set), done_(done), num_(0) {
- // If the set doesn't contain 0, we need to skip to the next element.
- if (!done && set_ == (IsValid(num_) ? Set::INVALID_ONLY : Set::VALID_ONLY)) {
- ++*this;
- }
-}
-
-uint32_t SyscallSet::Iterator::operator*() const {
- DCHECK(!done_);
- return num_;
-}
-
-SyscallSet::Iterator& SyscallSet::Iterator::operator++() {
- DCHECK(!done_);
-
- num_ = NextSyscall();
- if (num_ == 0) {
- done_ = true;
- }
-
- return *this;
-}
-
-// NextSyscall returns the next system call in the iterated system
-// call set after |num_|, or 0 if no such system call exists.
-uint32_t SyscallSet::Iterator::NextSyscall() const {
- const bool want_valid = (set_ != Set::INVALID_ONLY);
- const bool want_invalid = (set_ != Set::VALID_ONLY);
-
- for (const SyscallRange& range : kValidSyscallRanges) {
- if (want_invalid && range.first > 0 && num_ < range.first - 1) {
- // Even when iterating invalid syscalls, we only include the end points;
- // so skip directly to just before the next (valid) range.
- return range.first - 1;
- }
- if (want_valid && num_ < range.first) {
- return range.first;
- }
- if (want_valid && num_ < range.last) {
- return num_ + 1;
- }
- if (want_invalid && num_ <= range.last) {
- return range.last + 1;
- }
- }
-
- if (want_invalid) {
- // BPF programs only ever operate on unsigned quantities. So,
- // that's how we iterate; we return values from
- // 0..0xFFFFFFFFu. But there are places, where the kernel might
- // interpret system call numbers as signed quantities, so the
- // boundaries between signed and unsigned values are potential
- // problem cases. We want to explicitly return these values from
- // our iterator.
- if (num_ < 0x7FFFFFFFu)
- return 0x7FFFFFFFu;
- if (num_ < 0x80000000u)
- return 0x80000000u;
-
- if (num_ < 0xFFFFFFFFu)
- return 0xFFFFFFFFu;
- }
-
- return 0;
-}
-
-bool operator==(const SyscallSet::Iterator& lhs,
- const SyscallSet::Iterator& rhs) {
- DCHECK(lhs.set_ == rhs.set_);
- return (lhs.done_ == rhs.done_) && (lhs.num_ == rhs.num_);
-}
-
-bool operator!=(const SyscallSet::Iterator& lhs,
- const SyscallSet::Iterator& rhs) {
- return !(lhs == rhs);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/syscall_set.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/syscall_set.h
deleted file mode 100644
index b9f076d93..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/syscall_set.h
+++ /dev/null
@@ -1,103 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_BPF_DSL_SYSCALL_SET_H__
-#define SANDBOX_LINUX_BPF_DSL_SYSCALL_SET_H__
-
-#include <stdint.h>
-
-#include <iterator>
-
-#include "base/macros.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-
-// Iterates over the entire system call range from 0..0xFFFFFFFFu. This
-// iterator is aware of how system calls look like and will skip quickly
-// over ranges that can't contain system calls. It iterates more slowly
-// whenever it reaches a range that is potentially problematic, returning
-// the last invalid value before a valid range of system calls, and the
-// first invalid value after a valid range of syscalls. It iterates over
-// individual values whenever it is in the normal range for system calls
-// (typically MIN_SYSCALL..MAX_SYSCALL).
-//
-// Example usage:
-// for (uint32_t sysnum : SyscallSet::All()) {
-// // Do something with sysnum.
-// }
-class SANDBOX_EXPORT SyscallSet {
- public:
- class Iterator;
-
- SyscallSet(const SyscallSet& ss) : set_(ss.set_) {}
- ~SyscallSet() {}
-
- Iterator begin() const;
- Iterator end() const;
-
- // All returns a SyscallSet that contains both valid and invalid
- // system call numbers.
- static SyscallSet All() { return SyscallSet(Set::ALL); }
-
- // ValidOnly returns a SyscallSet that contains only valid system
- // call numbers.
- static SyscallSet ValidOnly() { return SyscallSet(Set::VALID_ONLY); }
-
- // InvalidOnly returns a SyscallSet that contains only invalid
- // system call numbers, but still omits numbers in the middle of a
- // range of invalid system call numbers.
- static SyscallSet InvalidOnly() { return SyscallSet(Set::INVALID_ONLY); }
-
- // IsValid returns whether |num| specifies a valid system call
- // number.
- static bool IsValid(uint32_t num);
-
- private:
- enum class Set { ALL, VALID_ONLY, INVALID_ONLY };
-
- explicit SyscallSet(Set set) : set_(set) {}
-
- Set set_;
-
- friend bool operator==(const SyscallSet&, const SyscallSet&);
- DISALLOW_ASSIGN(SyscallSet);
-};
-
-SANDBOX_EXPORT bool operator==(const SyscallSet& lhs, const SyscallSet& rhs);
-
-// Iterator provides C++ input iterator semantics for traversing a
-// SyscallSet.
-class SyscallSet::Iterator
- : public std::iterator<std::input_iterator_tag, uint32_t> {
- public:
- Iterator(const Iterator& it)
- : set_(it.set_), done_(it.done_), num_(it.num_) {}
- ~Iterator() {}
-
- uint32_t operator*() const;
- Iterator& operator++();
-
- private:
- Iterator(Set set, bool done);
-
- uint32_t NextSyscall() const;
-
- Set set_;
- bool done_;
- uint32_t num_;
-
- friend SyscallSet;
- friend bool operator==(const Iterator&, const Iterator&);
- DISALLOW_ASSIGN(Iterator);
-};
-
-SANDBOX_EXPORT bool operator==(const SyscallSet::Iterator& lhs,
- const SyscallSet::Iterator& rhs);
-SANDBOX_EXPORT bool operator!=(const SyscallSet::Iterator& lhs,
- const SyscallSet::Iterator& rhs);
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_SYSCALL_SET_H__
diff --git a/security/sandbox/chromium/sandbox/linux/bpf_dsl/trap_registry.h b/security/sandbox/chromium/sandbox/linux/bpf_dsl/trap_registry.h
deleted file mode 100644
index 0a5d2f14c..000000000
--- a/security/sandbox/chromium/sandbox/linux/bpf_dsl/trap_registry.h
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_BPF_DSL_TRAP_REGISTRY_H_
-#define SANDBOX_LINUX_BPF_DSL_TRAP_REGISTRY_H_
-
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-
-// This must match the kernel's seccomp_data structure.
-struct arch_seccomp_data {
- int nr;
- uint32_t arch;
- uint64_t instruction_pointer;
- uint64_t args[6];
-};
-
-namespace bpf_dsl {
-
-// TrapRegistry provides an interface for registering "trap handlers"
-// by associating them with non-zero 16-bit trap IDs. Trap IDs should
-// remain valid for the lifetime of the trap registry.
-class SANDBOX_EXPORT TrapRegistry {
- public:
- // TrapFnc is a pointer to a function that fulfills the trap handler
- // function signature.
- //
- // Trap handlers follow the calling convention of native system
- // calls; e.g., to report an error, they return an exit code in the
- // range -1..-4096 instead of directly modifying errno. However,
- // modifying errno is harmless, as the original value will be
- // restored afterwards.
- //
- // Trap handlers are executed from signal context and possibly an
- // async-signal context, so they must be async-signal safe:
- // http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html
- typedef intptr_t (*TrapFnc)(const struct arch_seccomp_data& args, void* aux);
-
- // Add registers the specified trap handler tuple and returns a
- // non-zero trap ID that uniquely identifies the tuple for the life
- // time of the trap registry. If the same tuple is registered
- // multiple times, the same value will be returned each time.
- virtual uint16_t Add(TrapFnc fnc, const void* aux, bool safe) = 0;
-
- // EnableUnsafeTraps tries to enable unsafe traps and returns
- // whether it was successful. This is a one-way operation.
- //
- // CAUTION: Enabling unsafe traps effectively defeats the security
- // guarantees provided by the sandbox policy. TrapRegistry
- // implementations should ensure unsafe traps are only enabled
- // during testing.
- virtual bool EnableUnsafeTraps() = 0;
-
- protected:
- TrapRegistry() {}
-
- // TrapRegistry's destructor is intentionally non-virtual so that
- // implementations can omit their destructor. Instead we protect against
- // misuse by marking it protected.
- ~TrapRegistry() {}
-
- DISALLOW_COPY_AND_ASSIGN(TrapRegistry);
-};
-
-} // namespace bpf_dsl
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_BPF_DSL_TRAP_REGISTRY_H_
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tester_compatibility_delegate.h b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tester_compatibility_delegate.h
deleted file mode 100644
index 00d415c3f..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tester_compatibility_delegate.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_SECCOMP_BPF_BPF_TESTER_COMPATIBILITY_DELEGATE_H_
-#define SANDBOX_LINUX_SECCOMP_BPF_BPF_TESTER_COMPATIBILITY_DELEGATE_H_
-
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.h"
-
-namespace sandbox {
-
-// This templated class allows building a BPFTesterDelegate from a
-// deprecated-style BPF policy (that is a SyscallEvaluator function pointer,
-// instead of a SandboxBPFPolicy class), specified in |policy_function| and a
-// function pointer to a test in |test_function|.
-// This allows both the policy and the test function to take a pointer to an
-// object of type "Aux" as a parameter. This is used to implement the BPF_TEST
-// macro and should generally not be used directly.
-template <class Policy, class Aux>
-class BPFTesterCompatibilityDelegate : public BPFTesterDelegate {
- public:
- typedef void (*TestFunction)(Aux*);
-
- explicit BPFTesterCompatibilityDelegate(TestFunction test_function)
- : aux_(), test_function_(test_function) {}
-
- ~BPFTesterCompatibilityDelegate() override {}
-
- scoped_ptr<bpf_dsl::Policy> GetSandboxBPFPolicy() override {
- // The current method is guaranteed to only run in the child process
- // running the test. In this process, the current object is guaranteed
- // to live forever. So it's ok to pass aux_pointer_for_policy_ to
- // the policy, which could in turn pass it to the kernel via Trap().
- return scoped_ptr<bpf_dsl::Policy>(new Policy(&aux_));
- }
-
- void RunTestFunction() override {
- // Run the actual test.
- // The current object is guaranteed to live forever in the child process
- // where this will run.
- test_function_(&aux_);
- }
-
- private:
- Aux aux_;
- TestFunction test_function_;
-
- DISALLOW_COPY_AND_ASSIGN(BPFTesterCompatibilityDelegate);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_SECCOMP_BPF_BPF_TESTER_COMPATIBILITY_DELEGATE_H_
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tests.h b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tests.h
deleted file mode 100644
index cc4debd4c..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tests.h
+++ /dev/null
@@ -1,122 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_SECCOMP_BPF_BPF_TESTS_H__
-#define SANDBOX_LINUX_SECCOMP_BPF_BPF_TESTS_H__
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "build/build_config.h"
-#include "sandbox/linux/seccomp-bpf/bpf_tester_compatibility_delegate.h"
-#include "sandbox/linux/tests/unit_tests.h"
-
-namespace sandbox {
-
-// BPF_TEST_C() is a special version of SANDBOX_TEST(). It runs a test function
-// in a sub-process, under a seccomp-bpf policy specified in
-// |bpf_policy_class_name| without failing on configurations that are allowed
-// to not support seccomp-bpf in their kernels.
-// This is the preferred format for new BPF tests. |bpf_policy_class_name| is a
-// class name (which will be default-constructed) that implements the
-// Policy interface.
-// The test function's body can simply follow. Test functions should use
-// the BPF_ASSERT macros defined below, not GTEST's macros. The use of
-// CHECK* macros is supported but less robust.
-#define BPF_TEST_C(test_case_name, test_name, bpf_policy_class_name) \
- BPF_DEATH_TEST_C( \
- test_case_name, test_name, DEATH_SUCCESS(), bpf_policy_class_name)
-
-// Identical to BPF_TEST_C but allows to specify the nature of death.
-#define BPF_DEATH_TEST_C( \
- test_case_name, test_name, death, bpf_policy_class_name) \
- void BPF_TEST_C_##test_name(); \
- TEST(test_case_name, DISABLE_ON_TSAN(test_name)) { \
- sandbox::SandboxBPFTestRunner bpf_test_runner( \
- new sandbox::BPFTesterSimpleDelegate<bpf_policy_class_name>( \
- BPF_TEST_C_##test_name)); \
- sandbox::UnitTests::RunTestInProcess(&bpf_test_runner, death); \
- } \
- void BPF_TEST_C_##test_name()
-
-// This form of BPF_TEST is a little verbose and should be reserved for complex
-// tests where a lot of control is required.
-// |bpf_tester_delegate_class| must be a classname implementing the
-// BPFTesterDelegate interface.
-#define BPF_TEST_D(test_case_name, test_name, bpf_tester_delegate_class) \
- BPF_DEATH_TEST_D( \
- test_case_name, test_name, DEATH_SUCCESS(), bpf_tester_delegate_class)
-
-// Identical to BPF_TEST_D but allows to specify the nature of death.
-#define BPF_DEATH_TEST_D( \
- test_case_name, test_name, death, bpf_tester_delegate_class) \
- TEST(test_case_name, DISABLE_ON_TSAN(test_name)) { \
- sandbox::SandboxBPFTestRunner bpf_test_runner( \
- new bpf_tester_delegate_class()); \
- sandbox::UnitTests::RunTestInProcess(&bpf_test_runner, death); \
- }
-
-// Assertions are handled exactly the same as with a normal SANDBOX_TEST()
-#define BPF_ASSERT SANDBOX_ASSERT
-#define BPF_ASSERT_EQ(x, y) BPF_ASSERT((x) == (y))
-#define BPF_ASSERT_NE(x, y) BPF_ASSERT((x) != (y))
-#define BPF_ASSERT_LT(x, y) BPF_ASSERT((x) < (y))
-#define BPF_ASSERT_GT(x, y) BPF_ASSERT((x) > (y))
-#define BPF_ASSERT_LE(x, y) BPF_ASSERT((x) <= (y))
-#define BPF_ASSERT_GE(x, y) BPF_ASSERT((x) >= (y))
-
-// This form of BPF_TEST is now discouraged (but still allowed) in favor of
-// BPF_TEST_D and BPF_TEST_C.
-// The |policy| parameter should be a Policy subclass.
-// BPF_TEST() takes a C++ data type as an fourth parameter. A variable
-// of this type will be allocated and a pointer to it will be
-// available within the test function as "BPF_AUX". The pointer will
-// also be passed as an argument to the policy's constructor. Policies
-// would typically use it as an argument to SandboxBPF::Trap(), if
-// they want to communicate data between the BPF_TEST() and a Trap()
-// function. The life-time of this object is the same as the life-time
-// of the process running under the seccomp-bpf policy.
-// |aux| must not be void.
-#define BPF_TEST(test_case_name, test_name, policy, aux) \
- BPF_DEATH_TEST(test_case_name, test_name, DEATH_SUCCESS(), policy, aux)
-
-// A BPF_DEATH_TEST is just the same as a BPF_TEST, but it assumes that the
-// test will fail with a particular known error condition. Use the DEATH_XXX()
-// macros from unit_tests.h to specify the expected error condition.
-#define BPF_DEATH_TEST(test_case_name, test_name, death, policy, aux) \
- void BPF_TEST_##test_name(aux* BPF_AUX); \
- TEST(test_case_name, DISABLE_ON_TSAN(test_name)) { \
- sandbox::SandboxBPFTestRunner bpf_test_runner( \
- new sandbox::BPFTesterCompatibilityDelegate<policy, aux>( \
- BPF_TEST_##test_name)); \
- sandbox::UnitTests::RunTestInProcess(&bpf_test_runner, death); \
- } \
- void BPF_TEST_##test_name(aux* BPF_AUX)
-
-// This class takes a simple function pointer as a constructor parameter and a
-// class name as a template parameter to implement the BPFTesterDelegate
-// interface which can be used to build BPF unittests with
-// the SandboxBPFTestRunner class.
-template <class PolicyClass>
-class BPFTesterSimpleDelegate : public BPFTesterDelegate {
- public:
- explicit BPFTesterSimpleDelegate(void (*test_function)(void))
- : test_function_(test_function) {}
- ~BPFTesterSimpleDelegate() override {}
-
- scoped_ptr<bpf_dsl::Policy> GetSandboxBPFPolicy() override {
- return scoped_ptr<bpf_dsl::Policy>(new PolicyClass());
- }
- void RunTestFunction() override {
- DCHECK(test_function_);
- test_function_();
- }
-
- private:
- void (*test_function_)(void);
- DISALLOW_COPY_AND_ASSIGN(BPFTesterSimpleDelegate);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_SECCOMP_BPF_BPF_TESTS_H__
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tests_unittest.cc b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tests_unittest.cc
deleted file mode 100644
index e300baf9b..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/bpf_tests_unittest.cc
+++ /dev/null
@@ -1,154 +0,0 @@
-// Copyright 2014 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 "sandbox/linux/seccomp-bpf/bpf_tests.h"
-
-#include <errno.h>
-#include <sys/ptrace.h>
-#include <sys/syscall.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "build/build_config.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
-#include "sandbox/linux/bpf_dsl/policy.h"
-#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
-#include "sandbox/linux/services/syscall_wrappers.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-#include "sandbox/linux/tests/unit_tests.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using sandbox::bpf_dsl::Allow;
-using sandbox::bpf_dsl::Error;
-using sandbox::bpf_dsl::ResultExpr;
-
-namespace sandbox {
-
-namespace {
-
-class FourtyTwo {
- public:
- static const int kMagicValue = 42;
- FourtyTwo() : value_(kMagicValue) {}
- int value() { return value_; }
-
- private:
- int value_;
- DISALLOW_COPY_AND_ASSIGN(FourtyTwo);
-};
-
-class EmptyClassTakingPolicy : public bpf_dsl::Policy {
- public:
- explicit EmptyClassTakingPolicy(FourtyTwo* fourty_two) {
- BPF_ASSERT(fourty_two);
- BPF_ASSERT(FourtyTwo::kMagicValue == fourty_two->value());
- }
- ~EmptyClassTakingPolicy() override {}
-
- ResultExpr EvaluateSyscall(int sysno) const override {
- DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
- return Allow();
- }
-};
-
-BPF_TEST(BPFTest,
- BPFAUXPointsToClass,
- EmptyClassTakingPolicy,
- FourtyTwo /* *BPF_AUX */) {
- // BPF_AUX should point to an instance of FourtyTwo.
- BPF_ASSERT(BPF_AUX);
- BPF_ASSERT(FourtyTwo::kMagicValue == BPF_AUX->value());
-}
-
-void DummyTestFunction(FourtyTwo *fourty_two) {
-}
-
-TEST(BPFTest, BPFTesterCompatibilityDelegateLeakTest) {
- // Don't do anything, simply gives dynamic tools an opportunity to detect
- // leaks.
- {
- BPFTesterCompatibilityDelegate<EmptyClassTakingPolicy, FourtyTwo>
- simple_delegate(DummyTestFunction);
- }
- {
- // Test polymorphism.
- scoped_ptr<BPFTesterDelegate> simple_delegate(
- new BPFTesterCompatibilityDelegate<EmptyClassTakingPolicy, FourtyTwo>(
- DummyTestFunction));
- }
-}
-
-class EnosysPtracePolicy : public bpf_dsl::Policy {
- public:
- EnosysPtracePolicy() { my_pid_ = sys_getpid(); }
- ~EnosysPtracePolicy() override {
- // Policies should be able to bind with the process on which they are
- // created. They should never be created in a parent process.
- BPF_ASSERT_EQ(my_pid_, sys_getpid());
- }
-
- ResultExpr EvaluateSyscall(int system_call_number) const override {
- CHECK(SandboxBPF::IsValidSyscallNumber(system_call_number));
- if (system_call_number == __NR_ptrace) {
- // The EvaluateSyscall function should run in the process that created
- // the current object.
- BPF_ASSERT_EQ(my_pid_, sys_getpid());
- return Error(ENOSYS);
- } else {
- return Allow();
- }
- }
-
- private:
- pid_t my_pid_;
- DISALLOW_COPY_AND_ASSIGN(EnosysPtracePolicy);
-};
-
-class BasicBPFTesterDelegate : public BPFTesterDelegate {
- public:
- BasicBPFTesterDelegate() {}
- ~BasicBPFTesterDelegate() override {}
-
- scoped_ptr<bpf_dsl::Policy> GetSandboxBPFPolicy() override {
- return scoped_ptr<bpf_dsl::Policy>(new EnosysPtracePolicy());
- }
- void RunTestFunction() override {
- errno = 0;
- int ret = ptrace(PTRACE_TRACEME, -1, NULL, NULL);
- BPF_ASSERT(-1 == ret);
- BPF_ASSERT(ENOSYS == errno);
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(BasicBPFTesterDelegate);
-};
-
-// This is the most powerful and complex way to create a BPF test, but it
-// requires a full class definition (BasicBPFTesterDelegate).
-BPF_TEST_D(BPFTest, BPFTestWithDelegateClass, BasicBPFTesterDelegate);
-
-// This is the simplest form of BPF tests.
-BPF_TEST_C(BPFTest, BPFTestWithInlineTest, EnosysPtracePolicy) {
- errno = 0;
- int ret = ptrace(PTRACE_TRACEME, -1, NULL, NULL);
- BPF_ASSERT(-1 == ret);
- BPF_ASSERT(ENOSYS == errno);
-}
-
-const char kHelloMessage[] = "Hello";
-
-BPF_DEATH_TEST_C(BPFTest,
- BPFDeathTestWithInlineTest,
- DEATH_MESSAGE(kHelloMessage),
- EnosysPtracePolicy) {
- LOG(ERROR) << kHelloMessage;
- _exit(1);
-}
-
-} // namespace
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/die.cc b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/die.cc
deleted file mode 100644
index 3baf1f13d..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/die.cc
+++ /dev/null
@@ -1,93 +0,0 @@
-// 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.
-
-#include "sandbox/linux/seccomp-bpf/die.h"
-
-#include <errno.h>
-#include <signal.h>
-#include <stdio.h>
-#include <sys/prctl.h>
-#include <sys/syscall.h>
-#include <unistd.h>
-
-#include <string>
-
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "sandbox/linux/seccomp-bpf/syscall.h"
-#include "sandbox/linux/services/syscall_wrappers.h"
-#include "sandbox/linux/system_headers/linux_signal.h"
-
-namespace sandbox {
-
-void Die::ExitGroup() {
- // exit_group() should exit our program. After all, it is defined as a
- // function that doesn't return. But things can theoretically go wrong.
- // Especially, since we are dealing with system call filters. Continuing
- // execution would be very bad in most cases where ExitGroup() gets called.
- // So, we'll try a few other strategies too.
- Syscall::Call(__NR_exit_group, 1);
-
- // We have no idea what our run-time environment looks like. So, signal
- // handlers might or might not do the right thing. Try to reset settings
- // to a defined state; but we have not way to verify whether we actually
- // succeeded in doing so. Nonetheless, triggering a fatal signal could help
- // us terminate.
- struct sigaction sa = {};
- sa.sa_handler = LINUX_SIG_DFL;
- sa.sa_flags = LINUX_SA_RESTART;
- sys_sigaction(LINUX_SIGSEGV, &sa, nullptr);
- Syscall::Call(__NR_prctl, PR_SET_DUMPABLE, (void*)0, (void*)0, (void*)0);
- if (*(volatile char*)0) {
- }
-
- // If there is no way for us to ask for the program to exit, the next
- // best thing we can do is to loop indefinitely. Maybe, somebody will notice
- // and file a bug...
- // We in fact retry the system call inside of our loop so that it will
- // stand out when somebody tries to diagnose the problem by using "strace".
- for (;;) {
- Syscall::Call(__NR_exit_group, 1);
- }
-}
-
-void Die::SandboxDie(const char* msg, const char* file, int line) {
- if (simple_exit_) {
- LogToStderr(msg, file, line);
- } else {
- logging::LogMessage(file, line, logging::LOG_FATAL).stream() << msg;
- }
- ExitGroup();
-}
-
-void Die::RawSandboxDie(const char* msg) {
- if (!msg)
- msg = "";
- RAW_LOG(FATAL, msg);
- ExitGroup();
-}
-
-void Die::SandboxInfo(const char* msg, const char* file, int line) {
- if (!suppress_info_) {
- logging::LogMessage(file, line, logging::LOG_INFO).stream() << msg;
- }
-}
-
-void Die::LogToStderr(const char* msg, const char* file, int line) {
- if (msg) {
- char buf[40];
- snprintf(buf, sizeof(buf), "%d", line);
- std::string s = std::string(file) + ":" + buf + ":" + msg + "\n";
-
- // No need to loop. Short write()s are unlikely and if they happen we
- // probably prefer them over a loop that blocks.
- ignore_result(
- HANDLE_EINTR(Syscall::Call(__NR_write, 2, s.c_str(), s.length())));
- }
-}
-
-bool Die::simple_exit_ = false;
-bool Die::suppress_info_ = false;
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/die.h b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/die.h
deleted file mode 100644
index b3f3f72c2..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/die.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_SECCOMP_BPF_DIE_H__
-#define SANDBOX_LINUX_SECCOMP_BPF_DIE_H__
-
-#include "base/macros.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-
-// This is the main API for using this file. Prints a error message and
-// exits with a fatal error. This is not async-signal safe.
-#define SANDBOX_DIE(m) sandbox::Die::SandboxDie(m, __FILE__, __LINE__)
-
-// An async signal safe version of the same API. Won't print the filename
-// and line numbers.
-#define RAW_SANDBOX_DIE(m) sandbox::Die::RawSandboxDie(m)
-
-// Adds an informational message to the log file or stderr as appropriate.
-#define SANDBOX_INFO(m) sandbox::Die::SandboxInfo(m, __FILE__, __LINE__)
-
-class SANDBOX_EXPORT Die {
- public:
- // Terminate the program, even if the current sandbox policy prevents some
- // of the more commonly used functions used for exiting.
- // Most users would want to call SANDBOX_DIE() instead, as it logs extra
- // information. But calling ExitGroup() is correct and in some rare cases
- // preferable. So, we make it part of the public API.
- static void ExitGroup() __attribute__((noreturn));
-
- // This method gets called by SANDBOX_DIE(). There is normally no reason
- // to call it directly unless you are defining your own exiting macro.
- static void SandboxDie(const char* msg, const char* file, int line)
- __attribute__((noreturn));
-
- static void RawSandboxDie(const char* msg) __attribute__((noreturn));
-
- // This method gets called by SANDBOX_INFO(). There is normally no reason
- // to call it directly unless you are defining your own logging macro.
- static void SandboxInfo(const char* msg, const char* file, int line);
-
- // Writes a message to stderr. Used as a fall-back choice, if we don't have
- // any other way to report an error.
- static void LogToStderr(const char* msg, const char* file, int line);
-
- // We generally want to run all exit handlers. This means, on SANDBOX_DIE()
- // we should be calling LOG(FATAL). But there are some situations where
- // we just need to print a message and then terminate. This would typically
- // happen in cases where we consume the error message internally (e.g. in
- // unit tests or in the supportsSeccompSandbox() method).
- static void EnableSimpleExit() { simple_exit_ = true; }
-
- // Sometimes we need to disable all informational messages (e.g. from within
- // unittests).
- static void SuppressInfoMessages(bool flag) { suppress_info_ = flag; }
-
- private:
- static bool simple_exit_;
- static bool suppress_info_;
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(Die);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_SECCOMP_BPF_DIE_H__
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf.cc b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf.cc
deleted file mode 100644
index b48682ba9..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf.cc
+++ /dev/null
@@ -1,280 +0,0 @@
-// 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.
-
-#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
-
-#include <errno.h>
-#include <stdint.h>
-#include <sys/prctl.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "base/compiler_specific.h"
-#include "base/files/scoped_file.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/third_party/valgrind/valgrind.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
-#include "sandbox/linux/bpf_dsl/codegen.h"
-#include "sandbox/linux/bpf_dsl/policy.h"
-#include "sandbox/linux/bpf_dsl/policy_compiler.h"
-#include "sandbox/linux/bpf_dsl/seccomp_macros.h"
-#include "sandbox/linux/bpf_dsl/syscall_set.h"
-#include "sandbox/linux/seccomp-bpf/die.h"
-#include "sandbox/linux/seccomp-bpf/syscall.h"
-#include "sandbox/linux/seccomp-bpf/trap.h"
-#include "sandbox/linux/services/proc_util.h"
-#include "sandbox/linux/services/syscall_wrappers.h"
-#include "sandbox/linux/services/thread_helpers.h"
-#include "sandbox/linux/system_headers/linux_filter.h"
-#include "sandbox/linux/system_headers/linux_seccomp.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-namespace sandbox {
-
-namespace {
-
-bool IsRunningOnValgrind() { return RUNNING_ON_VALGRIND; }
-
-bool IsSingleThreaded(int proc_fd) {
- return ThreadHelpers::IsSingleThreaded(proc_fd);
-}
-
-// Check if the kernel supports seccomp-filter (a.k.a. seccomp mode 2) via
-// prctl().
-bool KernelSupportsSeccompBPF() {
- errno = 0;
- const int rv = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, nullptr);
-
- if (rv == -1 && EFAULT == errno) {
- return true;
- }
- return false;
-}
-
-// LG introduced a buggy syscall, sys_set_media_ext, with the same number as
-// seccomp. Return true if the current kernel has this buggy syscall.
-//
-// We want this to work with upcoming versions of seccomp, so we pass bogus
-// flags that are unlikely to ever be used by the kernel. A normal kernel would
-// return -EINVAL, but a buggy LG kernel would return 1.
-bool KernelHasLGBug() {
-#if defined(OS_ANDROID)
- // sys_set_media will see this as NULL, which should be a safe (non-crashing)
- // way to invoke it. A genuine seccomp syscall will see it as
- // SECCOMP_SET_MODE_STRICT.
- const unsigned int operation = 0;
- // Chosen by fair dice roll. Guaranteed to be random.
- const unsigned int flags = 0xf7a46a5c;
- const int rv = sys_seccomp(operation, flags, nullptr);
- // A genuine kernel would return -EINVAL (which would set rv to -1 and errno
- // to EINVAL), or at the very least return some kind of error (which would
- // set rv to -1). Any other behavior indicates that whatever code received
- // our syscall was not the real seccomp.
- if (rv != -1) {
- return true;
- }
-#endif // defined(OS_ANDROID)
-
- return false;
-}
-
-// Check if the kernel supports seccomp-filter via the seccomp system call
-// and the TSYNC feature to enable seccomp on all threads.
-bool KernelSupportsSeccompTsync() {
- if (KernelHasLGBug()) {
- return false;
- }
-
- errno = 0;
- const int rv =
- sys_seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, nullptr);
-
- if (rv == -1 && errno == EFAULT) {
- return true;
- } else {
- // TODO(jln): turn these into DCHECK after 417888 is considered fixed.
- CHECK_EQ(-1, rv);
- CHECK(ENOSYS == errno || EINVAL == errno);
- return false;
- }
-}
-
-uint64_t EscapePC() {
- intptr_t rv = Syscall::Call(-1);
- if (rv == -1 && errno == ENOSYS) {
- return 0;
- }
- return static_cast<uint64_t>(static_cast<uintptr_t>(rv));
-}
-
-intptr_t SandboxPanicTrap(const struct arch_seccomp_data&, void* aux) {
- SANDBOX_DIE(static_cast<const char*>(aux));
-}
-
-bpf_dsl::ResultExpr SandboxPanic(const char* error) {
- return bpf_dsl::Trap(SandboxPanicTrap, error);
-}
-
-} // namespace
-
-SandboxBPF::SandboxBPF(bpf_dsl::Policy* policy)
- : proc_fd_(), sandbox_has_started_(false), policy_(policy) {
-}
-
-SandboxBPF::~SandboxBPF() {
-}
-
-// static
-bool SandboxBPF::SupportsSeccompSandbox(SeccompLevel level) {
- // Never pretend to support seccomp with Valgrind, as it
- // throws the tool off.
- if (IsRunningOnValgrind()) {
- return false;
- }
-
- switch (level) {
- case SeccompLevel::SINGLE_THREADED:
- return KernelSupportsSeccompBPF();
- case SeccompLevel::MULTI_THREADED:
- return KernelSupportsSeccompTsync();
- }
- NOTREACHED();
- return false;
-}
-
-bool SandboxBPF::StartSandbox(SeccompLevel seccomp_level) {
- DCHECK(policy_);
- CHECK(seccomp_level == SeccompLevel::SINGLE_THREADED ||
- seccomp_level == SeccompLevel::MULTI_THREADED);
-
- if (sandbox_has_started_) {
- SANDBOX_DIE(
- "Cannot repeatedly start sandbox. Create a separate Sandbox "
- "object instead.");
- return false;
- }
-
- if (!proc_fd_.is_valid()) {
- SetProcFd(ProcUtil::OpenProc());
- }
-
- const bool supports_tsync = KernelSupportsSeccompTsync();
-
- if (seccomp_level == SeccompLevel::SINGLE_THREADED) {
- // Wait for /proc/self/task/ to update if needed and assert the
- // process is single threaded.
- ThreadHelpers::AssertSingleThreaded(proc_fd_.get());
- } else if (seccomp_level == SeccompLevel::MULTI_THREADED) {
- if (IsSingleThreaded(proc_fd_.get())) {
- SANDBOX_DIE("Cannot start sandbox; "
- "process may be single-threaded when reported as not");
- return false;
- }
- if (!supports_tsync) {
- SANDBOX_DIE("Cannot start sandbox; kernel does not support synchronizing "
- "filters for a threadgroup");
- return false;
- }
- }
-
- // We no longer need access to any files in /proc. We want to do this
- // before installing the filters, just in case that our policy denies
- // close().
- if (proc_fd_.is_valid()) {
- proc_fd_.reset();
- }
-
- // Install the filters.
- InstallFilter(supports_tsync ||
- seccomp_level == SeccompLevel::MULTI_THREADED);
-
- return true;
-}
-
-void SandboxBPF::SetProcFd(base::ScopedFD proc_fd) {
- proc_fd_.swap(proc_fd);
-}
-
-// static
-bool SandboxBPF::IsValidSyscallNumber(int sysnum) {
- return SyscallSet::IsValid(sysnum);
-}
-
-// static
-bool SandboxBPF::IsRequiredForUnsafeTrap(int sysno) {
- return bpf_dsl::PolicyCompiler::IsRequiredForUnsafeTrap(sysno);
-}
-
-// static
-intptr_t SandboxBPF::ForwardSyscall(const struct arch_seccomp_data& args) {
- return Syscall::Call(
- args.nr, static_cast<intptr_t>(args.args[0]),
- static_cast<intptr_t>(args.args[1]), static_cast<intptr_t>(args.args[2]),
- static_cast<intptr_t>(args.args[3]), static_cast<intptr_t>(args.args[4]),
- static_cast<intptr_t>(args.args[5]));
-}
-
-CodeGen::Program SandboxBPF::AssembleFilter() {
- DCHECK(policy_);
-
- bpf_dsl::PolicyCompiler compiler(policy_.get(), Trap::Registry());
- if (Trap::SandboxDebuggingAllowedByUser()) {
- compiler.DangerousSetEscapePC(EscapePC());
- }
- compiler.SetPanicFunc(SandboxPanic);
- return compiler.Compile();
-}
-
-void SandboxBPF::InstallFilter(bool must_sync_threads) {
- // We want to be very careful in not imposing any requirements on the
- // policies that are set with SetSandboxPolicy(). This means, as soon as
- // the sandbox is active, we shouldn't be relying on libraries that could
- // be making system calls. This, for example, means we should avoid
- // using the heap and we should avoid using STL functions.
- // Temporarily copy the contents of the "program" vector into a
- // stack-allocated array; and then explicitly destroy that object.
- // This makes sure we don't ex- or implicitly call new/delete after we
- // installed the BPF filter program in the kernel. Depending on the
- // system memory allocator that is in effect, these operators can result
- // in system calls to things like munmap() or brk().
- CodeGen::Program program = AssembleFilter();
-
- struct sock_filter bpf[program.size()];
- const struct sock_fprog prog = {static_cast<unsigned short>(program.size()),
- bpf};
- memcpy(bpf, &program[0], sizeof(bpf));
- CodeGen::Program().swap(program); // vector swap trick
-
- // Make an attempt to release memory that is no longer needed here, rather
- // than in the destructor. Try to avoid as much as possible to presume of
- // what will be possible to do in the new (sandboxed) execution environment.
- policy_.reset();
-
- if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
- SANDBOX_DIE("Kernel refuses to enable no-new-privs");
- }
-
- // Install BPF filter program. If the thread state indicates multi-threading
- // support, then the kernel hass the seccomp system call. Otherwise, fall
- // back on prctl, which requires the process to be single-threaded.
- if (must_sync_threads) {
- int rv =
- sys_seccomp(SECCOMP_SET_MODE_FILTER, SECCOMP_FILTER_FLAG_TSYNC, &prog);
- if (rv) {
- SANDBOX_DIE(
- "Kernel refuses to turn on and synchronize threads for BPF filters");
- }
- } else {
- if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog)) {
- SANDBOX_DIE("Kernel refuses to turn on BPF filters");
- }
- }
-
- sandbox_has_started_ = true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf.h b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf.h
deleted file mode 100644
index e758e0312..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf.h
+++ /dev/null
@@ -1,114 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_H_
-#define SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_H_
-
-#include <stdint.h>
-
-#include "base/files/scoped_file.h"
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/linux/bpf_dsl/codegen.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-struct arch_seccomp_data;
-namespace bpf_dsl {
-class Policy;
-}
-
-// This class can be used to apply a syscall sandboxing policy expressed in a
-// bpf_dsl::Policy object to the current process.
-// Syscall sandboxing policies get inherited by subprocesses and, once applied,
-// can never be removed for the lifetime of the process.
-class SANDBOX_EXPORT SandboxBPF {
- public:
- enum class SeccompLevel {
- SINGLE_THREADED,
- MULTI_THREADED,
- };
-
- // Ownership of |policy| is transfered here to the sandbox object.
- // nullptr is allowed for unit tests.
- explicit SandboxBPF(bpf_dsl::Policy* policy);
- // NOTE: Setting a policy and starting the sandbox is a one-way operation.
- // The kernel does not provide any option for unloading a loaded sandbox. The
- // sandbox remains engaged even when the object is destructed.
- ~SandboxBPF();
-
- // Detect if the kernel supports the specified seccomp level.
- // See StartSandbox() for a description of these.
- static bool SupportsSeccompSandbox(SeccompLevel level);
-
- // This is the main public entry point. It sets up the resources needed by
- // the sandbox, and enters Seccomp mode.
- // The calling process must provide a |level| to tell the sandbox which type
- // of kernel support it should engage.
- // SINGLE_THREADED will only sandbox the calling thread. Since it would be a
- // security risk, the sandbox will also check that the current process is
- // single threaded and crash if it isn't the case.
- // MULTI_THREADED requires more recent kernel support and allows to sandbox
- // all the threads of the current process. Be mindful of potential races,
- // with other threads using disallowed system calls either before or after
- // the sandbox is engaged.
- //
- // It is possible to stack multiple sandboxes by creating separate "Sandbox"
- // objects and calling "StartSandbox()" on each of them. Please note, that
- // this requires special care, though, as newly stacked sandboxes can never
- // relax restrictions imposed by earlier sandboxes. Furthermore, installing
- // a new policy requires making system calls, that might already be
- // disallowed.
- // Finally, stacking does add more kernel overhead than having a single
- // combined policy. So, it should only be used if there are no alternatives.
- bool StartSandbox(SeccompLevel level) WARN_UNUSED_RESULT;
-
- // The sandbox needs to be able to access files in "/proc/self/". If
- // this directory is not accessible when "StartSandbox()" gets called, the
- // caller must provide an already opened file descriptor by calling
- // "SetProcFd()".
- // The sandbox becomes the new owner of this file descriptor and will
- // close it when "StartSandbox()" executes or when the sandbox object
- // disappears.
- void SetProcFd(base::ScopedFD proc_fd);
-
- // Checks whether a particular system call number is valid on the current
- // architecture.
- static bool IsValidSyscallNumber(int sysnum);
-
- // UnsafeTraps require some syscalls to always be allowed.
- // This helper function returns true for these calls.
- static bool IsRequiredForUnsafeTrap(int sysno);
-
- // From within an UnsafeTrap() it is often useful to be able to execute
- // the system call that triggered the trap. The ForwardSyscall() method
- // makes this easy. It is more efficient than calling glibc's syscall()
- // function, as it avoid the extra round-trip to the signal handler. And
- // it automatically does the correct thing to report kernel-style error
- // conditions, rather than setting errno. See the comments for TrapFnc for
- // details. In other words, the return value from ForwardSyscall() is
- // directly suitable as a return value for a trap handler.
- static intptr_t ForwardSyscall(const struct arch_seccomp_data& args);
-
- private:
- friend class SandboxBPFTestRunner;
-
- // Assembles a BPF filter program from the current policy. After calling this
- // function, you must not call any other sandboxing function.
- CodeGen::Program AssembleFilter();
-
- // Assembles and installs a filter based on the policy that has previously
- // been configured with SetSandboxPolicy().
- void InstallFilter(bool must_sync_threads);
-
- base::ScopedFD proc_fd_;
- bool sandbox_has_started_;
- scoped_ptr<bpf_dsl::Policy> policy_;
-
- DISALLOW_COPY_AND_ASSIGN(SandboxBPF);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_H_
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.cc b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.cc
deleted file mode 100644
index c0193f956..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.cc
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2014 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 "sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.h"
-
-#include <fcntl.h>
-
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/linux/bpf_dsl/policy.h"
-#include "sandbox/linux/seccomp-bpf/die.h"
-#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
-#include "sandbox/linux/system_headers/linux_filter.h"
-#include "sandbox/linux/tests/unit_tests.h"
-
-namespace sandbox {
-
-SandboxBPFTestRunner::SandboxBPFTestRunner(
- BPFTesterDelegate* bpf_tester_delegate)
- : bpf_tester_delegate_(bpf_tester_delegate) {
-}
-
-SandboxBPFTestRunner::~SandboxBPFTestRunner() {
-}
-
-void SandboxBPFTestRunner::Run() {
- DCHECK(bpf_tester_delegate_);
- sandbox::Die::EnableSimpleExit();
-
- scoped_ptr<bpf_dsl::Policy> policy =
- bpf_tester_delegate_->GetSandboxBPFPolicy();
-
- if (sandbox::SandboxBPF::SupportsSeccompSandbox(
- SandboxBPF::SeccompLevel::SINGLE_THREADED)) {
- // Initialize and then start the sandbox with our custom policy
- sandbox::SandboxBPF sandbox(policy.release());
- SANDBOX_ASSERT(sandbox.StartSandbox(
- sandbox::SandboxBPF::SeccompLevel::SINGLE_THREADED));
-
- // Run the actual test.
- bpf_tester_delegate_->RunTestFunction();
- } else {
- printf("This BPF test is not fully running in this configuration!\n");
- // Android and Valgrind are the only configurations where we accept not
- // having kernel BPF support.
- if (!IsAndroid() && !IsRunningOnValgrind()) {
- const bool seccomp_bpf_is_supported = false;
- SANDBOX_ASSERT(seccomp_bpf_is_supported);
- }
- // Call the compiler and verify the policy. That's the least we can do,
- // if we don't have kernel support.
- sandbox::SandboxBPF sandbox(policy.release());
- sandbox.AssembleFilter();
- sandbox::UnitTests::IgnoreThisTest();
- }
-}
-
-bool SandboxBPFTestRunner::ShouldCheckForLeaks() const {
- // LSAN requires being able to use ptrace() and other system calls that could
- // be denied.
- return false;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.h b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.h
deleted file mode 100644
index fef6240d7..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/sandbox_bpf_test_runner.h
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_TEST_RUNNER_H_
-#define SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_TEST_RUNNER_H_
-
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/linux/tests/sandbox_test_runner.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-class Policy;
-}
-
-// To create a SandboxBPFTestRunner object, one needs to implement this
-// interface and pass an instance to the SandboxBPFTestRunner constructor.
-// In the child process running the test, the BPFTesterDelegate object is
-// guaranteed to not be destroyed until the child process terminates.
-class BPFTesterDelegate {
- public:
- BPFTesterDelegate() {}
- virtual ~BPFTesterDelegate() {}
-
- // This will instanciate a policy suitable for the test we want to run. It is
- // guaranteed to only be called from the child process that will run the
- // test.
- virtual scoped_ptr<bpf_dsl::Policy> GetSandboxBPFPolicy() = 0;
- // This will be called from a child process with the BPF sandbox turned on.
- virtual void RunTestFunction() = 0;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(BPFTesterDelegate);
-};
-
-// This class implements the SandboxTestRunner interface and Run() will
-// initialize a seccomp-bpf sandbox (specified by |bpf_tester_delegate|) and
-// run a test function (via |bpf_tester_delegate|) if the current kernel
-// configuration allows it. If it can not run the test under seccomp-bpf,
-// Run() will still compile the policy which should allow to get some coverage
-// under tools such as Valgrind.
-class SandboxBPFTestRunner : public SandboxTestRunner {
- public:
- // This constructor takes ownership of the |bpf_tester_delegate| object.
- // (It doesn't take a scoped_ptr since they make polymorphism verbose).
- explicit SandboxBPFTestRunner(BPFTesterDelegate* bpf_tester_delegate);
- ~SandboxBPFTestRunner() override;
-
- void Run() override;
-
- bool ShouldCheckForLeaks() const override;
-
- private:
- scoped_ptr<BPFTesterDelegate> bpf_tester_delegate_;
- DISALLOW_COPY_AND_ASSIGN(SandboxBPFTestRunner);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_SECCOMP_BPF_SANDBOX_BPF_TEST_RUNNER_H_
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall.cc b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall.cc
deleted file mode 100644
index bc6461f11..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall.cc
+++ /dev/null
@@ -1,421 +0,0 @@
-// 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.
-
-#include "sandbox/linux/seccomp-bpf/syscall.h"
-
-#include <errno.h>
-#include <stdint.h>
-
-#include "base/logging.h"
-#include "sandbox/linux/bpf_dsl/seccomp_macros.h"
-
-namespace sandbox {
-
-namespace {
-
-#if defined(ARCH_CPU_X86_FAMILY) || defined(ARCH_CPU_ARM_FAMILY) || \
- defined(ARCH_CPU_MIPS_FAMILY)
-// Number that's not currently used by any Linux kernel ABIs.
-const int kInvalidSyscallNumber = 0x351d3;
-#else
-#error Unrecognized architecture
-#endif
-
-asm(// We need to be able to tell the kernel exactly where we made a
- // system call. The C++ compiler likes to sometimes clone or
- // inline code, which would inadvertently end up duplicating
- // the entry point.
- // "gcc" can suppress code duplication with suitable function
- // attributes, but "clang" doesn't have this ability.
- // The "clang" developer mailing list suggested that the correct
- // and portable solution is a file-scope assembly block.
- // N.B. We do mark our code as a proper function so that backtraces
- // work correctly. But we make absolutely no attempt to use the
- // ABI's calling conventions for passing arguments. We will only
- // ever be called from assembly code and thus can pick more
- // suitable calling conventions.
-#if defined(__i386__)
- ".text\n"
- ".align 16, 0x90\n"
- ".type SyscallAsm, @function\n"
- "SyscallAsm:.cfi_startproc\n"
- // Check if "%eax" is negative. If so, do not attempt to make a
- // system call. Instead, compute the return address that is visible
- // to the kernel after we execute "int $0x80". This address can be
- // used as a marker that BPF code inspects.
- "test %eax, %eax\n"
- "jge 1f\n"
- // Always, make sure that our code is position-independent, or
- // address space randomization might not work on i386. This means,
- // we can't use "lea", but instead have to rely on "call/pop".
- "call 0f; .cfi_adjust_cfa_offset 4\n"
- "0:pop %eax; .cfi_adjust_cfa_offset -4\n"
- "addl $2f-0b, %eax\n"
- "ret\n"
- // Save register that we don't want to clobber. On i386, we need to
- // save relatively aggressively, as there are a couple or registers
- // that are used internally (e.g. %ebx for position-independent
- // code, and %ebp for the frame pointer), and as we need to keep at
- // least a few registers available for the register allocator.
- "1:push %esi; .cfi_adjust_cfa_offset 4; .cfi_rel_offset esi, 0\n"
- "push %edi; .cfi_adjust_cfa_offset 4; .cfi_rel_offset edi, 0\n"
- "push %ebx; .cfi_adjust_cfa_offset 4; .cfi_rel_offset ebx, 0\n"
- "push %ebp; .cfi_adjust_cfa_offset 4; .cfi_rel_offset ebp, 0\n"
- // Copy entries from the array holding the arguments into the
- // correct CPU registers.
- "movl 0(%edi), %ebx\n"
- "movl 4(%edi), %ecx\n"
- "movl 8(%edi), %edx\n"
- "movl 12(%edi), %esi\n"
- "movl 20(%edi), %ebp\n"
- "movl 16(%edi), %edi\n"
- // Enter the kernel.
- "int $0x80\n"
- // This is our "magic" return address that the BPF filter sees.
- "2:"
- // Restore any clobbered registers that we didn't declare to the
- // compiler.
- "pop %ebp; .cfi_restore ebp; .cfi_adjust_cfa_offset -4\n"
- "pop %ebx; .cfi_restore ebx; .cfi_adjust_cfa_offset -4\n"
- "pop %edi; .cfi_restore edi; .cfi_adjust_cfa_offset -4\n"
- "pop %esi; .cfi_restore esi; .cfi_adjust_cfa_offset -4\n"
- "ret\n"
- ".cfi_endproc\n"
- "9:.size SyscallAsm, 9b-SyscallAsm\n"
-#elif defined(__x86_64__)
- ".text\n"
- ".align 16, 0x90\n"
- ".type SyscallAsm, @function\n"
- "SyscallAsm:.cfi_startproc\n"
- // Check if "%rdi" is negative. If so, do not attempt to make a
- // system call. Instead, compute the return address that is visible
- // to the kernel after we execute "syscall". This address can be
- // used as a marker that BPF code inspects.
- "test %rdi, %rdi\n"
- "jge 1f\n"
- // Always make sure that our code is position-independent, or the
- // linker will throw a hissy fit on x86-64.
- "lea 2f(%rip), %rax\n"
- "ret\n"
- // Now we load the registers used to pass arguments to the system
- // call: system call number in %rax, and arguments in %rdi, %rsi,
- // %rdx, %r10, %r8, %r9. Note: These are all caller-save registers
- // (only %rbx, %rbp, %rsp, and %r12-%r15 are callee-save), so no
- // need to worry here about spilling registers or CFI directives.
- "1:movq %rdi, %rax\n"
- "movq 0(%rsi), %rdi\n"
- "movq 16(%rsi), %rdx\n"
- "movq 24(%rsi), %r10\n"
- "movq 32(%rsi), %r8\n"
- "movq 40(%rsi), %r9\n"
- "movq 8(%rsi), %rsi\n"
- // Enter the kernel.
- "syscall\n"
- // This is our "magic" return address that the BPF filter sees.
- "2:ret\n"
- ".cfi_endproc\n"
- "9:.size SyscallAsm, 9b-SyscallAsm\n"
-#elif defined(__arm__)
- // Throughout this file, we use the same mode (ARM vs. thumb)
- // that the C++ compiler uses. This means, when transfering control
- // from C++ to assembly code, we do not need to switch modes (e.g.
- // by using the "bx" instruction). It also means that our assembly
- // code should not be invoked directly from code that lives in
- // other compilation units, as we don't bother implementing thumb
- // interworking. That's OK, as we don't make any of the assembly
- // symbols public. They are all local to this file.
- ".text\n"
- ".align 2\n"
- ".type SyscallAsm, %function\n"
-#if defined(__thumb__)
- ".thumb_func\n"
-#else
- ".arm\n"
-#endif
- "SyscallAsm:\n"
-#if !defined(__native_client_nonsfi__)
- // .fnstart and .fnend pseudo operations creates unwind table.
- // It also creates a reference to the symbol __aeabi_unwind_cpp_pr0, which
- // is not provided by PNaCl toolchain. Disable it.
- ".fnstart\n"
-#endif
- "@ args = 0, pretend = 0, frame = 8\n"
- "@ frame_needed = 1, uses_anonymous_args = 0\n"
-#if defined(__thumb__)
- ".cfi_startproc\n"
- "push {r7, lr}\n"
- ".save {r7, lr}\n"
- ".cfi_offset 14, -4\n"
- ".cfi_offset 7, -8\n"
- ".cfi_def_cfa_offset 8\n"
-#else
- "stmfd sp!, {fp, lr}\n"
- "add fp, sp, #4\n"
-#endif
- // Check if "r0" is negative. If so, do not attempt to make a
- // system call. Instead, compute the return address that is visible
- // to the kernel after we execute "swi 0". This address can be
- // used as a marker that BPF code inspects.
- "cmp r0, #0\n"
- "bge 1f\n"
- "adr r0, 2f\n"
- "b 2f\n"
- // We declared (almost) all clobbered registers to the compiler. On
- // ARM there is no particular register pressure. So, we can go
- // ahead and directly copy the entries from the arguments array
- // into the appropriate CPU registers.
- "1:ldr r5, [r6, #20]\n"
- "ldr r4, [r6, #16]\n"
- "ldr r3, [r6, #12]\n"
- "ldr r2, [r6, #8]\n"
- "ldr r1, [r6, #4]\n"
- "mov r7, r0\n"
- "ldr r0, [r6, #0]\n"
- // Enter the kernel
- "swi 0\n"
-// Restore the frame pointer. Also restore the program counter from
-// the link register; this makes us return to the caller.
-#if defined(__thumb__)
- "2:pop {r7, pc}\n"
- ".cfi_endproc\n"
-#else
- "2:ldmfd sp!, {fp, pc}\n"
-#endif
-#if !defined(__native_client_nonsfi__)
- // Do not use .fnstart and .fnend for PNaCl toolchain. See above comment,
- // for more details.
- ".fnend\n"
-#endif
- "9:.size SyscallAsm, 9b-SyscallAsm\n"
-#elif defined(__mips__)
- ".text\n"
- ".align 4\n"
- ".type SyscallAsm, @function\n"
- "SyscallAsm:.ent SyscallAsm\n"
- ".frame $sp, 40, $ra\n"
- ".set push\n"
- ".set noreorder\n"
- "addiu $sp, $sp, -40\n"
- "sw $ra, 36($sp)\n"
- // Check if "v0" is negative. If so, do not attempt to make a
- // system call. Instead, compute the return address that is visible
- // to the kernel after we execute "syscall". This address can be
- // used as a marker that BPF code inspects.
- "bgez $v0, 1f\n"
- " nop\n"
- "la $v0, 2f\n"
- "b 2f\n"
- " nop\n"
- // On MIPS first four arguments go to registers a0 - a3 and any
- // argument after that goes to stack. We can go ahead and directly
- // copy the entries from the arguments array into the appropriate
- // CPU registers and on the stack.
- "1:lw $a3, 28($a0)\n"
- "lw $a2, 24($a0)\n"
- "lw $a1, 20($a0)\n"
- "lw $t0, 16($a0)\n"
- "sw $a3, 28($sp)\n"
- "sw $a2, 24($sp)\n"
- "sw $a1, 20($sp)\n"
- "sw $t0, 16($sp)\n"
- "lw $a3, 12($a0)\n"
- "lw $a2, 8($a0)\n"
- "lw $a1, 4($a0)\n"
- "lw $a0, 0($a0)\n"
- // Enter the kernel
- "syscall\n"
- // This is our "magic" return address that the BPF filter sees.
- // Restore the return address from the stack.
- "2:lw $ra, 36($sp)\n"
- "jr $ra\n"
- " addiu $sp, $sp, 40\n"
- ".set pop\n"
- ".end SyscallAsm\n"
- ".size SyscallAsm,.-SyscallAsm\n"
-#elif defined(__aarch64__)
- ".text\n"
- ".align 2\n"
- ".type SyscallAsm, %function\n"
- "SyscallAsm:\n"
- ".cfi_startproc\n"
- "cmp x0, #0\n"
- "b.ge 1f\n"
- "adr x0,2f\n"
- "b 2f\n"
- "1:ldr x5, [x6, #40]\n"
- "ldr x4, [x6, #32]\n"
- "ldr x3, [x6, #24]\n"
- "ldr x2, [x6, #16]\n"
- "ldr x1, [x6, #8]\n"
- "mov x8, x0\n"
- "ldr x0, [x6, #0]\n"
- // Enter the kernel
- "svc 0\n"
- "2:ret\n"
- ".cfi_endproc\n"
- ".size SyscallAsm, .-SyscallAsm\n"
-#endif
- ); // asm
-
-#if defined(__x86_64__)
-extern "C" {
-intptr_t SyscallAsm(intptr_t nr, const intptr_t args[6]);
-}
-#endif
-
-} // namespace
-
-intptr_t Syscall::InvalidCall() {
- // Explicitly pass eight zero arguments just in case.
- return Call(kInvalidSyscallNumber, 0, 0, 0, 0, 0, 0, 0, 0);
-}
-
-intptr_t Syscall::Call(int nr,
- intptr_t p0,
- intptr_t p1,
- intptr_t p2,
- intptr_t p3,
- intptr_t p4,
- intptr_t p5,
- intptr_t p6,
- intptr_t p7) {
- // We rely on "intptr_t" to be the exact size as a "void *". This is
- // typically true, but just in case, we add a check. The language
- // specification allows platforms some leeway in cases, where
- // "sizeof(void *)" is not the same as "sizeof(void (*)())". We expect
- // that this would only be an issue for IA64, which we are currently not
- // planning on supporting. And it is even possible that this would work
- // on IA64, but for lack of actual hardware, I cannot test.
- static_assert(sizeof(void*) == sizeof(intptr_t),
- "pointer types and intptr_t must be exactly the same size");
-
- // TODO(nedeljko): Enable use of more than six parameters on architectures
- // where that makes sense.
-#if defined(__mips__)
- const intptr_t args[8] = {p0, p1, p2, p3, p4, p5, p6, p7};
-#else
- DCHECK_EQ(p6, 0) << " Support for syscalls with more than six arguments not "
- "added for this architecture";
- DCHECK_EQ(p7, 0) << " Support for syscalls with more than six arguments not "
- "added for this architecture";
- const intptr_t args[6] = {p0, p1, p2, p3, p4, p5};
-#endif // defined(__mips__)
-
-// Invoke our file-scope assembly code. The constraints have been picked
-// carefully to match what the rest of the assembly code expects in input,
-// output, and clobbered registers.
-#if defined(__i386__)
- intptr_t ret = nr;
- asm volatile(
- "call SyscallAsm\n"
- // N.B. These are not the calling conventions normally used by the ABI.
- : "=a"(ret)
- : "0"(ret), "D"(args)
- : "cc", "esp", "memory", "ecx", "edx");
-#elif defined(__x86_64__)
- intptr_t ret = SyscallAsm(nr, args);
-#elif defined(__arm__)
- intptr_t ret;
- {
- register intptr_t inout __asm__("r0") = nr;
- register const intptr_t* data __asm__("r6") = args;
- asm volatile(
- "bl SyscallAsm\n"
- // N.B. These are not the calling conventions normally used by the ABI.
- : "=r"(inout)
- : "0"(inout), "r"(data)
- : "cc",
- "lr",
- "memory",
- "r1",
- "r2",
- "r3",
- "r4",
- "r5"
-#if !defined(__thumb__)
- // In thumb mode, we cannot use "r7" as a general purpose register, as
- // it is our frame pointer. We have to manually manage and preserve
- // it.
- // In ARM mode, we have a dedicated frame pointer register and "r7" is
- // thus available as a general purpose register. We don't preserve it,
- // but instead mark it as clobbered.
- ,
- "r7"
-#endif // !defined(__thumb__)
- );
- ret = inout;
- }
-#elif defined(__mips__)
- int err_status;
- intptr_t ret = Syscall::SandboxSyscallRaw(nr, args, &err_status);
-
- if (err_status) {
- // On error, MIPS returns errno from syscall instead of -errno.
- // The purpose of this negation is for SandboxSyscall() to behave
- // more like it would on other architectures.
- ret = -ret;
- }
-#elif defined(__aarch64__)
- intptr_t ret;
- {
- register intptr_t inout __asm__("x0") = nr;
- register const intptr_t* data __asm__("x6") = args;
- asm volatile("bl SyscallAsm\n"
- : "=r"(inout)
- : "0"(inout), "r"(data)
- : "memory", "x1", "x2", "x3", "x4", "x5", "x8", "x30");
- ret = inout;
- }
-
-#else
-#error "Unimplemented architecture"
-#endif
- return ret;
-}
-
-void Syscall::PutValueInUcontext(intptr_t ret_val, ucontext_t* ctx) {
-#if defined(__mips__)
- // Mips ABI states that on error a3 CPU register has non zero value and if
- // there is no error, it should be zero.
- if (ret_val <= -1 && ret_val >= -4095) {
- // |ret_val| followes the Syscall::Call() convention of being -errno on
- // errors. In order to write correct value to return register this sign
- // needs to be changed back.
- ret_val = -ret_val;
- SECCOMP_PARM4(ctx) = 1;
- } else
- SECCOMP_PARM4(ctx) = 0;
-#endif
- SECCOMP_RESULT(ctx) = static_cast<greg_t>(ret_val);
-}
-
-#if defined(__mips__)
-intptr_t Syscall::SandboxSyscallRaw(int nr,
- const intptr_t* args,
- intptr_t* err_ret) {
- register intptr_t ret __asm__("v0") = nr;
- // a3 register becomes non zero on error.
- register intptr_t err_stat __asm__("a3") = 0;
- {
- register const intptr_t* data __asm__("a0") = args;
- asm volatile(
- "la $t9, SyscallAsm\n"
- "jalr $t9\n"
- " nop\n"
- : "=r"(ret), "=r"(err_stat)
- : "0"(ret),
- "r"(data)
- // a2 is in the clober list so inline assembly can not change its
- // value.
- : "memory", "ra", "t9", "a2");
- }
-
- // Set an error status so it can be used outside of this function
- *err_ret = err_stat;
-
- return ret;
-}
-#endif // defined(__mips__)
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall.h b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall.h
deleted file mode 100644
index ccfc88dcb..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall.h
+++ /dev/null
@@ -1,166 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_SECCOMP_BPF_SYSCALL_H__
-#define SANDBOX_LINUX_SECCOMP_BPF_SYSCALL_H__
-
-#include <signal.h>
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "sandbox/linux/system_headers/linux_signal.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-
-// This purely static class can be used to perform system calls with some
-// low-level control.
-class SANDBOX_EXPORT Syscall {
- public:
- // InvalidCall() invokes Call() with a platform-appropriate syscall
- // number that is guaranteed to not be implemented (i.e., normally
- // returns -ENOSYS).
- // This is primarily meant to be useful for writing sandbox policy
- // unit tests.
- static intptr_t InvalidCall();
-
- // System calls can take up to six parameters (up to eight on some
- // architectures). Traditionally, glibc
- // implements this property by using variadic argument lists. This works, but
- // confuses modern tools such as valgrind, because we are nominally passing
- // uninitialized data whenever we call through this function and pass less
- // than the full six arguments.
- // So, instead, we use C++'s template system to achieve a very similar
- // effect. C++ automatically sets the unused parameters to zero for us, and
- // it also does the correct type expansion (e.g. from 32bit to 64bit) where
- // necessary.
- // We have to use C-style cast operators as we want to be able to accept both
- // integer and pointer types.
- template <class T0,
- class T1,
- class T2,
- class T3,
- class T4,
- class T5,
- class T6,
- class T7>
- static inline intptr_t
- Call(int nr, T0 p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7) {
- return Call(nr,
- (intptr_t)p0,
- (intptr_t)p1,
- (intptr_t)p2,
- (intptr_t)p3,
- (intptr_t)p4,
- (intptr_t)p5,
- (intptr_t)p6,
- (intptr_t)p7);
- }
-
- template <class T0,
- class T1,
- class T2,
- class T3,
- class T4,
- class T5,
- class T6>
- static inline intptr_t
- Call(int nr, T0 p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6) {
- return Call(nr,
- (intptr_t)p0,
- (intptr_t)p1,
- (intptr_t)p2,
- (intptr_t)p3,
- (intptr_t)p4,
- (intptr_t)p5,
- (intptr_t)p6,
- 0);
- }
-
- template <class T0, class T1, class T2, class T3, class T4, class T5>
- static inline intptr_t
- Call(int nr, T0 p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5) {
- return Call(nr,
- (intptr_t)p0,
- (intptr_t)p1,
- (intptr_t)p2,
- (intptr_t)p3,
- (intptr_t)p4,
- (intptr_t)p5,
- 0,
- 0);
- }
-
- template <class T0, class T1, class T2, class T3, class T4>
- static inline intptr_t Call(int nr, T0 p0, T1 p1, T2 p2, T3 p3, T4 p4) {
- return Call(nr, p0, p1, p2, p3, p4, 0, 0, 0);
- }
-
- template <class T0, class T1, class T2, class T3>
- static inline intptr_t Call(int nr, T0 p0, T1 p1, T2 p2, T3 p3) {
- return Call(nr, p0, p1, p2, p3, 0, 0, 0, 0);
- }
-
- template <class T0, class T1, class T2>
- static inline intptr_t Call(int nr, T0 p0, T1 p1, T2 p2) {
- return Call(nr, p0, p1, p2, 0, 0, 0, 0, 0);
- }
-
- template <class T0, class T1>
- static inline intptr_t Call(int nr, T0 p0, T1 p1) {
- return Call(nr, p0, p1, 0, 0, 0, 0, 0, 0);
- }
-
- template <class T0>
- static inline intptr_t Call(int nr, T0 p0) {
- return Call(nr, p0, 0, 0, 0, 0, 0, 0, 0);
- }
-
- static inline intptr_t Call(int nr) {
- return Call(nr, 0, 0, 0, 0, 0, 0, 0, 0);
- }
-
- // Set the registers in |ctx| to match what they would be after a system call
- // returning |ret_val|. |ret_val| must follow the Syscall::Call() convention
- // of being -errno on errors.
- static void PutValueInUcontext(intptr_t ret_val, ucontext_t* ctx);
-
- private:
- // This performs system call |nr| with the arguments p0 to p7 from a constant
- // userland address, which is for instance observable by seccomp-bpf filters.
- // The constant userland address from which these system calls are made will
- // be returned if |nr| is passed as -1.
- // On error, this function will return a value between -1 and -4095 which
- // should be interpreted as -errno.
- static intptr_t Call(int nr,
- intptr_t p0,
- intptr_t p1,
- intptr_t p2,
- intptr_t p3,
- intptr_t p4,
- intptr_t p5,
- intptr_t p6,
- intptr_t p7);
-
-#if defined(__mips__)
- // This function basically does on MIPS what SandboxSyscall() is doing on
- // other architectures. However, because of specificity of MIPS regarding
- // handling syscall errors, SandboxSyscall() is made as a wrapper for this
- // function in order for SandboxSyscall() to behave more like on other
- // architectures on places where return value from SandboxSyscall() is used
- // directly (like in most tests).
- // The syscall "nr" is called with arguments that are set in an array on which
- // pointer "args" points to and an information weather there is an error or no
- // is returned to SandboxSyscall() by err_stat.
- static intptr_t SandboxSyscallRaw(int nr,
- const intptr_t* args,
- intptr_t* err_stat);
-#endif // defined(__mips__)
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(Syscall);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_SECCOMP_BPF_SYSCALL_H__
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall_unittest.cc b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall_unittest.cc
deleted file mode 100644
index 01336f9b6..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall_unittest.cc
+++ /dev/null
@@ -1,244 +0,0 @@
-// 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.
-
-#include "sandbox/linux/seccomp-bpf/syscall.h"
-
-#include <asm/unistd.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <sys/mman.h>
-#include <sys/syscall.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <vector>
-
-#include "base/macros.h"
-#include "base/posix/eintr_wrapper.h"
-#include "build/build_config.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
-#include "sandbox/linux/bpf_dsl/policy.h"
-#include "sandbox/linux/seccomp-bpf/bpf_tests.h"
-#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
-#include "sandbox/linux/tests/unit_tests.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using sandbox::bpf_dsl::Allow;
-using sandbox::bpf_dsl::ResultExpr;
-using sandbox::bpf_dsl::Trap;
-
-namespace sandbox {
-
-namespace {
-
-// Different platforms use different symbols for the six-argument version
-// of the mmap() system call. Test for the correct symbol at compile time.
-#ifdef __NR_mmap2
-const int kMMapNr = __NR_mmap2;
-#else
-const int kMMapNr = __NR_mmap;
-#endif
-
-TEST(Syscall, InvalidCallReturnsENOSYS) {
- EXPECT_EQ(-ENOSYS, Syscall::InvalidCall());
-}
-
-TEST(Syscall, WellKnownEntryPoint) {
-// Test that Syscall::Call(-1) is handled specially. Don't do this on ARM,
-// where syscall(-1) crashes with SIGILL. Not running the test is fine, as we
-// are still testing ARM code in the next set of tests.
-#if !defined(__arm__) && !defined(__aarch64__)
- EXPECT_NE(Syscall::Call(-1), syscall(-1));
-#endif
-
-// If possible, test that Syscall::Call(-1) returns the address right
-// after
-// a kernel entry point.
-#if defined(__i386__)
- EXPECT_EQ(0x80CDu, ((uint16_t*)Syscall::Call(-1))[-1]); // INT 0x80
-#elif defined(__x86_64__)
- EXPECT_EQ(0x050Fu, ((uint16_t*)Syscall::Call(-1))[-1]); // SYSCALL
-#elif defined(__arm__)
-#if defined(__thumb__)
- EXPECT_EQ(0xDF00u, ((uint16_t*)Syscall::Call(-1))[-1]); // SWI 0
-#else
- EXPECT_EQ(0xEF000000u, ((uint32_t*)Syscall::Call(-1))[-1]); // SVC 0
-#endif
-#elif defined(__mips__)
- // Opcode for MIPS sycall is in the lower 16-bits
- EXPECT_EQ(0x0cu, (((uint32_t*)Syscall::Call(-1))[-1]) & 0x0000FFFF);
-#elif defined(__aarch64__)
- EXPECT_EQ(0xD4000001u, ((uint32_t*)Syscall::Call(-1))[-1]); // SVC 0
-#else
-#warning Incomplete test case; need port for target platform
-#endif
-}
-
-TEST(Syscall, TrivialSyscallNoArgs) {
- // Test that we can do basic system calls
- EXPECT_EQ(Syscall::Call(__NR_getpid), syscall(__NR_getpid));
-}
-
-TEST(Syscall, TrivialSyscallOneArg) {
- int new_fd;
- // Duplicate standard error and close it.
- ASSERT_GE(new_fd = Syscall::Call(__NR_dup, 2), 0);
- int close_return_value = IGNORE_EINTR(Syscall::Call(__NR_close, new_fd));
- ASSERT_EQ(close_return_value, 0);
-}
-
-TEST(Syscall, TrivialFailingSyscall) {
- errno = -42;
- int ret = Syscall::Call(__NR_dup, -1);
- ASSERT_EQ(-EBADF, ret);
- // Verify that Syscall::Call does not touch errno.
- ASSERT_EQ(-42, errno);
-}
-
-// SIGSYS trap handler that will be called on __NR_uname.
-intptr_t CopySyscallArgsToAux(const struct arch_seccomp_data& args, void* aux) {
- // |aux| is our BPF_AUX pointer.
- std::vector<uint64_t>* const seen_syscall_args =
- static_cast<std::vector<uint64_t>*>(aux);
- BPF_ASSERT(arraysize(args.args) == 6);
- seen_syscall_args->assign(args.args, args.args + arraysize(args.args));
- return -ENOMEM;
-}
-
-class CopyAllArgsOnUnamePolicy : public bpf_dsl::Policy {
- public:
- explicit CopyAllArgsOnUnamePolicy(std::vector<uint64_t>* aux) : aux_(aux) {}
- ~CopyAllArgsOnUnamePolicy() override {}
-
- ResultExpr EvaluateSyscall(int sysno) const override {
- DCHECK(SandboxBPF::IsValidSyscallNumber(sysno));
- if (sysno == __NR_uname) {
- return Trap(CopySyscallArgsToAux, aux_);
- } else {
- return Allow();
- }
- }
-
- private:
- std::vector<uint64_t>* aux_;
-
- DISALLOW_COPY_AND_ASSIGN(CopyAllArgsOnUnamePolicy);
-};
-
-// We are testing Syscall::Call() by making use of a BPF filter that
-// allows us
-// to inspect the system call arguments that the kernel saw.
-BPF_TEST(Syscall,
- SyntheticSixArgs,
- CopyAllArgsOnUnamePolicy,
- std::vector<uint64_t> /* (*BPF_AUX) */) {
- const int kExpectedValue = 42;
- // In this test we only pass integers to the kernel. We might want to make
- // additional tests to try other types. What we will see depends on
- // implementation details of kernel BPF filters and we will need to document
- // the expected behavior very clearly.
- int syscall_args[6];
- for (size_t i = 0; i < arraysize(syscall_args); ++i) {
- syscall_args[i] = kExpectedValue + i;
- }
-
- // We could use pretty much any system call we don't need here. uname() is
- // nice because it doesn't have any dangerous side effects.
- BPF_ASSERT(Syscall::Call(__NR_uname,
- syscall_args[0],
- syscall_args[1],
- syscall_args[2],
- syscall_args[3],
- syscall_args[4],
- syscall_args[5]) == -ENOMEM);
-
- // We expect the trap handler to have copied the 6 arguments.
- BPF_ASSERT(BPF_AUX->size() == 6);
-
- // Don't loop here so that we can see which argument does cause the failure
- // easily from the failing line.
- // uint64_t is the type passed to our SIGSYS handler.
- BPF_ASSERT((*BPF_AUX)[0] == static_cast<uint64_t>(syscall_args[0]));
- BPF_ASSERT((*BPF_AUX)[1] == static_cast<uint64_t>(syscall_args[1]));
- BPF_ASSERT((*BPF_AUX)[2] == static_cast<uint64_t>(syscall_args[2]));
- BPF_ASSERT((*BPF_AUX)[3] == static_cast<uint64_t>(syscall_args[3]));
- BPF_ASSERT((*BPF_AUX)[4] == static_cast<uint64_t>(syscall_args[4]));
- BPF_ASSERT((*BPF_AUX)[5] == static_cast<uint64_t>(syscall_args[5]));
-}
-
-TEST(Syscall, ComplexSyscallSixArgs) {
- int fd;
- ASSERT_LE(0,
- fd = Syscall::Call(__NR_openat, AT_FDCWD, "/dev/null", O_RDWR, 0L));
-
- // Use mmap() to allocate some read-only memory
- char* addr0;
- ASSERT_NE(
- (char*)NULL,
- addr0 = reinterpret_cast<char*>(Syscall::Call(kMMapNr,
- (void*)NULL,
- 4096,
- PROT_READ,
- MAP_PRIVATE | MAP_ANONYMOUS,
- fd,
- 0L)));
-
- // Try to replace the existing mapping with a read-write mapping
- char* addr1;
- ASSERT_EQ(addr0,
- addr1 = reinterpret_cast<char*>(
- Syscall::Call(kMMapNr,
- addr0,
- 4096L,
- PROT_READ | PROT_WRITE,
- MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
- fd,
- 0L)));
- ++*addr1; // This should not seg fault
-
- // Clean up
- EXPECT_EQ(0, Syscall::Call(__NR_munmap, addr1, 4096L));
- EXPECT_EQ(0, IGNORE_EINTR(Syscall::Call(__NR_close, fd)));
-
- // Check that the offset argument (i.e. the sixth argument) is processed
- // correctly.
- ASSERT_GE(
- fd = Syscall::Call(__NR_openat, AT_FDCWD, "/proc/self/exe", O_RDONLY, 0L),
- 0);
- char* addr2, *addr3;
- ASSERT_NE((char*)NULL,
- addr2 = reinterpret_cast<char*>(Syscall::Call(
- kMMapNr, (void*)NULL, 8192L, PROT_READ, MAP_PRIVATE, fd, 0L)));
- ASSERT_NE((char*)NULL,
- addr3 = reinterpret_cast<char*>(Syscall::Call(kMMapNr,
- (void*)NULL,
- 4096L,
- PROT_READ,
- MAP_PRIVATE,
- fd,
-#if defined(__NR_mmap2)
- 1L
-#else
- 4096L
-#endif
- )));
- EXPECT_EQ(0, memcmp(addr2 + 4096, addr3, 4096));
-
- // Just to be absolutely on the safe side, also verify that the file
- // contents matches what we are getting from a read() operation.
- char buf[8192];
- EXPECT_EQ(8192, Syscall::Call(__NR_read, fd, buf, 8192L));
- EXPECT_EQ(0, memcmp(addr2, buf, 8192));
-
- // Clean up
- EXPECT_EQ(0, Syscall::Call(__NR_munmap, addr2, 8192L));
- EXPECT_EQ(0, Syscall::Call(__NR_munmap, addr3, 4096L));
- EXPECT_EQ(0, IGNORE_EINTR(Syscall::Call(__NR_close, fd)));
-}
-
-} // namespace
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/trap.cc b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/trap.cc
deleted file mode 100644
index 003708d2c..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/trap.cc
+++ /dev/null
@@ -1,387 +0,0 @@
-// 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.
-
-#include "sandbox/linux/seccomp-bpf/trap.h"
-
-#include <errno.h>
-#include <signal.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/syscall.h>
-
-#include <algorithm>
-#include <limits>
-#include <tuple>
-
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "build/build_config.h"
-#include "sandbox/linux/bpf_dsl/seccomp_macros.h"
-#include "sandbox/linux/seccomp-bpf/die.h"
-#include "sandbox/linux/seccomp-bpf/syscall.h"
-#include "sandbox/linux/services/syscall_wrappers.h"
-#include "sandbox/linux/system_headers/linux_seccomp.h"
-#include "sandbox/linux/system_headers/linux_signal.h"
-
-namespace {
-
-struct arch_sigsys {
- void* ip;
- int nr;
- unsigned int arch;
-};
-
-const int kCapacityIncrement = 20;
-
-// Unsafe traps can only be turned on, if the user explicitly allowed them
-// by setting the CHROME_SANDBOX_DEBUGGING environment variable.
-const char kSandboxDebuggingEnv[] = "CHROME_SANDBOX_DEBUGGING";
-
-// We need to tell whether we are performing a "normal" callback, or
-// whether we were called recursively from within a UnsafeTrap() callback.
-// This is a little tricky to do, because we need to somehow get access to
-// per-thread data from within a signal context. Normal TLS storage is not
-// safely accessible at this time. We could roll our own, but that involves
-// a lot of complexity. Instead, we co-opt one bit in the signal mask.
-// If BUS is blocked, we assume that we have been called recursively.
-// There is a possibility for collision with other code that needs to do
-// this, but in practice the risks are low.
-// If SIGBUS turns out to be a problem, we could instead co-opt one of the
-// realtime signals. There are plenty of them. Unfortunately, there is no
-// way to mark a signal as allocated. So, the potential for collision is
-// possibly even worse.
-bool GetIsInSigHandler(const ucontext_t* ctx) {
- // Note: on Android, sigismember does not take a pointer to const.
- return sigismember(const_cast<sigset_t*>(&ctx->uc_sigmask), LINUX_SIGBUS);
-}
-
-void SetIsInSigHandler() {
- sigset_t mask;
- if (sigemptyset(&mask) || sigaddset(&mask, LINUX_SIGBUS) ||
- sandbox::sys_sigprocmask(LINUX_SIG_BLOCK, &mask, NULL)) {
- SANDBOX_DIE("Failed to block SIGBUS");
- }
-}
-
-bool IsDefaultSignalAction(const struct sigaction& sa) {
- if (sa.sa_flags & SA_SIGINFO || sa.sa_handler != SIG_DFL) {
- return false;
- }
- return true;
-}
-
-} // namespace
-
-namespace sandbox {
-
-Trap::Trap()
- : trap_array_(NULL),
- trap_array_size_(0),
- trap_array_capacity_(0),
- has_unsafe_traps_(false) {
- // Set new SIGSYS handler
- struct sigaction sa = {};
- // In some toolchain, sa_sigaction is not declared in struct sigaction.
- // So, here cast the pointer to the sa_handler's type. This works because
- // |sa_handler| and |sa_sigaction| shares the same memory.
- sa.sa_handler = reinterpret_cast<void (*)(int)>(SigSysAction);
- sa.sa_flags = LINUX_SA_SIGINFO | LINUX_SA_NODEFER;
- struct sigaction old_sa = {};
- if (sys_sigaction(LINUX_SIGSYS, &sa, &old_sa) < 0) {
- SANDBOX_DIE("Failed to configure SIGSYS handler");
- }
-
- if (!IsDefaultSignalAction(old_sa)) {
- static const char kExistingSIGSYSMsg[] =
- "Existing signal handler when trying to install SIGSYS. SIGSYS needs "
- "to be reserved for seccomp-bpf.";
- DLOG(FATAL) << kExistingSIGSYSMsg;
- LOG(ERROR) << kExistingSIGSYSMsg;
- }
-
- // Unmask SIGSYS
- sigset_t mask;
- if (sigemptyset(&mask) || sigaddset(&mask, LINUX_SIGSYS) ||
- sys_sigprocmask(LINUX_SIG_UNBLOCK, &mask, NULL)) {
- SANDBOX_DIE("Failed to configure SIGSYS handler");
- }
-}
-
-bpf_dsl::TrapRegistry* Trap::Registry() {
- // Note: This class is not thread safe. It is the caller's responsibility
- // to avoid race conditions. Normally, this is a non-issue as the sandbox
- // can only be initialized if there are no other threads present.
- // Also, this is not a normal singleton. Once created, the global trap
- // object must never be destroyed again.
- if (!global_trap_) {
- global_trap_ = new Trap();
- if (!global_trap_) {
- SANDBOX_DIE("Failed to allocate global trap handler");
- }
- }
- return global_trap_;
-}
-
-void Trap::SigSysAction(int nr, LinuxSigInfo* info, void* void_context) {
- if (info) {
- MSAN_UNPOISON(info, sizeof(*info));
- }
-
- // Obtain the signal context. This, most notably, gives us access to
- // all CPU registers at the time of the signal.
- ucontext_t* ctx = reinterpret_cast<ucontext_t*>(void_context);
- if (ctx) {
- MSAN_UNPOISON(ctx, sizeof(*ctx));
- }
-
- if (!global_trap_) {
- RAW_SANDBOX_DIE(
- "This can't happen. Found no global singleton instance "
- "for Trap() handling.");
- }
- global_trap_->SigSys(nr, info, ctx);
-}
-
-void Trap::SigSys(int nr, LinuxSigInfo* info, ucontext_t* ctx) {
- // Signal handlers should always preserve "errno". Otherwise, we could
- // trigger really subtle bugs.
- const int old_errno = errno;
-
- // Various sanity checks to make sure we actually received a signal
- // triggered by a BPF filter. If something else triggered SIGSYS
- // (e.g. kill()), there is really nothing we can do with this signal.
- if (nr != LINUX_SIGSYS || info->si_code != SYS_SECCOMP || !ctx ||
- info->si_errno <= 0 ||
- static_cast<size_t>(info->si_errno) > trap_array_size_) {
- // ATI drivers seem to send SIGSYS, so this cannot be FATAL.
- // See crbug.com/178166.
- // TODO(jln): add a DCHECK or move back to FATAL.
- RAW_LOG(ERROR, "Unexpected SIGSYS received.");
- errno = old_errno;
- return;
- }
-
-
- // Obtain the siginfo information that is specific to SIGSYS. Unfortunately,
- // most versions of glibc don't include this information in siginfo_t. So,
- // we need to explicitly copy it into a arch_sigsys structure.
- struct arch_sigsys sigsys;
- memcpy(&sigsys, &info->_sifields, sizeof(sigsys));
-
-#if defined(__mips__)
- // When indirect syscall (syscall(__NR_foo, ...)) is made on Mips, the
- // number in register SECCOMP_SYSCALL(ctx) is always __NR_syscall and the
- // real number of a syscall (__NR_foo) is in SECCOMP_PARM1(ctx)
- bool sigsys_nr_is_bad = sigsys.nr != static_cast<int>(SECCOMP_SYSCALL(ctx)) &&
- sigsys.nr != static_cast<int>(SECCOMP_PARM1(ctx));
-#else
- bool sigsys_nr_is_bad = sigsys.nr != static_cast<int>(SECCOMP_SYSCALL(ctx));
-#endif
-
- // Some more sanity checks.
- if (sigsys.ip != reinterpret_cast<void*>(SECCOMP_IP(ctx)) ||
- sigsys_nr_is_bad || sigsys.arch != SECCOMP_ARCH) {
- // TODO(markus):
- // SANDBOX_DIE() can call LOG(FATAL). This is not normally async-signal
- // safe and can lead to bugs. We should eventually implement a different
- // logging and reporting mechanism that is safe to be called from
- // the sigSys() handler.
- RAW_SANDBOX_DIE("Sanity checks are failing after receiving SIGSYS.");
- }
-
- intptr_t rc;
- if (has_unsafe_traps_ && GetIsInSigHandler(ctx)) {
- errno = old_errno;
- if (sigsys.nr == __NR_clone) {
- RAW_SANDBOX_DIE("Cannot call clone() from an UnsafeTrap() handler.");
- }
-#if defined(__mips__)
- // Mips supports up to eight arguments for syscall.
- // However, seccomp bpf can filter only up to six arguments, so using eight
- // arguments has sense only when using UnsafeTrap() handler.
- rc = Syscall::Call(SECCOMP_SYSCALL(ctx),
- SECCOMP_PARM1(ctx),
- SECCOMP_PARM2(ctx),
- SECCOMP_PARM3(ctx),
- SECCOMP_PARM4(ctx),
- SECCOMP_PARM5(ctx),
- SECCOMP_PARM6(ctx),
- SECCOMP_PARM7(ctx),
- SECCOMP_PARM8(ctx));
-#else
- rc = Syscall::Call(SECCOMP_SYSCALL(ctx),
- SECCOMP_PARM1(ctx),
- SECCOMP_PARM2(ctx),
- SECCOMP_PARM3(ctx),
- SECCOMP_PARM4(ctx),
- SECCOMP_PARM5(ctx),
- SECCOMP_PARM6(ctx));
-#endif // defined(__mips__)
- } else {
- const TrapKey& trap = trap_array_[info->si_errno - 1];
- if (!trap.safe) {
- SetIsInSigHandler();
- }
-
- // Copy the seccomp-specific data into a arch_seccomp_data structure. This
- // is what we are showing to TrapFnc callbacks that the system call
- // evaluator registered with the sandbox.
- struct arch_seccomp_data data = {
- static_cast<int>(SECCOMP_SYSCALL(ctx)),
- SECCOMP_ARCH,
- reinterpret_cast<uint64_t>(sigsys.ip),
- {static_cast<uint64_t>(SECCOMP_PARM1(ctx)),
- static_cast<uint64_t>(SECCOMP_PARM2(ctx)),
- static_cast<uint64_t>(SECCOMP_PARM3(ctx)),
- static_cast<uint64_t>(SECCOMP_PARM4(ctx)),
- static_cast<uint64_t>(SECCOMP_PARM5(ctx)),
- static_cast<uint64_t>(SECCOMP_PARM6(ctx))}};
-
- // Now call the TrapFnc callback associated with this particular instance
- // of SECCOMP_RET_TRAP.
- rc = trap.fnc(data, const_cast<void*>(trap.aux));
- }
-
- // Update the CPU register that stores the return code of the system call
- // that we just handled, and restore "errno" to the value that it had
- // before entering the signal handler.
- Syscall::PutValueInUcontext(rc, ctx);
- errno = old_errno;
-
- return;
-}
-
-bool Trap::TrapKey::operator<(const TrapKey& o) const {
- return std::tie(fnc, aux, safe) < std::tie(o.fnc, o.aux, o.safe);
-}
-
-uint16_t Trap::Add(TrapFnc fnc, const void* aux, bool safe) {
- if (!safe && !SandboxDebuggingAllowedByUser()) {
- // Unless the user set the CHROME_SANDBOX_DEBUGGING environment variable,
- // we never return an ErrorCode that is marked as "unsafe". This also
- // means, the BPF compiler will never emit code that allow unsafe system
- // calls to by-pass the filter (because they use the magic return address
- // from Syscall::Call(-1)).
-
- // This SANDBOX_DIE() can optionally be removed. It won't break security,
- // but it might make error messages from the BPF compiler a little harder
- // to understand. Removing the SANDBOX_DIE() allows callers to easily check
- // whether unsafe traps are supported (by checking whether the returned
- // ErrorCode is ET_INVALID).
- SANDBOX_DIE(
- "Cannot use unsafe traps unless CHROME_SANDBOX_DEBUGGING "
- "is enabled");
-
- return 0;
- }
-
- // Each unique pair of TrapFnc and auxiliary data make up a distinct instance
- // of a SECCOMP_RET_TRAP.
- TrapKey key(fnc, aux, safe);
-
- // We return unique identifiers together with SECCOMP_RET_TRAP. This allows
- // us to associate trap with the appropriate handler. The kernel allows us
- // identifiers in the range from 0 to SECCOMP_RET_DATA (0xFFFF). We want to
- // avoid 0, as it could be confused for a trap without any specific id.
- // The nice thing about sequentially numbered identifiers is that we can also
- // trivially look them up from our signal handler without making any system
- // calls that might be async-signal-unsafe.
- // In order to do so, we store all of our traps in a C-style trap_array_.
-
- TrapIds::const_iterator iter = trap_ids_.find(key);
- if (iter != trap_ids_.end()) {
- // We have seen this pair before. Return the same id that we assigned
- // earlier.
- return iter->second;
- }
-
- // This is a new pair. Remember it and assign a new id.
- if (trap_array_size_ >= SECCOMP_RET_DATA /* 0xFFFF */ ||
- trap_array_size_ >= std::numeric_limits<uint16_t>::max()) {
- // In practice, this is pretty much impossible to trigger, as there
- // are other kernel limitations that restrict overall BPF program sizes.
- SANDBOX_DIE("Too many SECCOMP_RET_TRAP callback instances");
- }
-
- // Our callers ensure that there are no other threads accessing trap_array_
- // concurrently (typically this is done by ensuring that we are single-
- // threaded while the sandbox is being set up). But we nonetheless are
- // modifying a live data structure that could be accessed any time a
- // system call is made; as system calls could be triggering SIGSYS.
- // So, we have to be extra careful that we update trap_array_ atomically.
- // In particular, this means we shouldn't be using realloc() to resize it.
- // Instead, we allocate a new array, copy the values, and then switch the
- // pointer. We only really care about the pointer being updated atomically
- // and the data that is pointed to being valid, as these are the only
- // values accessed from the signal handler. It is OK if trap_array_size_
- // is inconsistent with the pointer, as it is monotonously increasing.
- // Also, we only care about compiler barriers, as the signal handler is
- // triggered synchronously from a system call. We don't have to protect
- // against issues with the memory model or with completely asynchronous
- // events.
- if (trap_array_size_ >= trap_array_capacity_) {
- trap_array_capacity_ += kCapacityIncrement;
- TrapKey* old_trap_array = trap_array_;
- TrapKey* new_trap_array = new TrapKey[trap_array_capacity_];
- std::copy_n(old_trap_array, trap_array_size_, new_trap_array);
-
- // Language specs are unclear on whether the compiler is allowed to move
- // the "delete[]" above our preceding assignments and/or memory moves,
- // iff the compiler believes that "delete[]" doesn't have any other
- // global side-effects.
- // We insert optimization barriers to prevent this from happening.
- // The first barrier is probably not needed, but better be explicit in
- // what we want to tell the compiler.
- // The clang developer mailing list couldn't answer whether this is a
- // legitimate worry; but they at least thought that the barrier is
- // sufficient to prevent the (so far hypothetical) problem of re-ordering
- // of instructions by the compiler.
- //
- // TODO(mdempsky): Try to clean this up using base/atomicops or C++11
- // atomics; see crbug.com/414363.
- asm volatile("" : "=r"(new_trap_array) : "0"(new_trap_array) : "memory");
- trap_array_ = new_trap_array;
- asm volatile("" : "=r"(trap_array_) : "0"(trap_array_) : "memory");
-
- delete[] old_trap_array;
- }
-
- uint16_t id = trap_array_size_ + 1;
- trap_ids_[key] = id;
- trap_array_[trap_array_size_] = key;
- trap_array_size_++;
- return id;
-}
-
-bool Trap::SandboxDebuggingAllowedByUser() {
- const char* debug_flag = getenv(kSandboxDebuggingEnv);
- return debug_flag && *debug_flag;
-}
-
-bool Trap::EnableUnsafeTraps() {
- if (!has_unsafe_traps_) {
- // Unsafe traps are a one-way fuse. Once enabled, they can never be turned
- // off again.
- // We only allow enabling unsafe traps, if the user explicitly set an
- // appropriate environment variable. This prevents bugs that accidentally
- // disable all sandboxing for all users.
- if (SandboxDebuggingAllowedByUser()) {
- // We only ever print this message once, when we enable unsafe traps the
- // first time.
- SANDBOX_INFO("WARNING! Disabling sandbox for debugging purposes");
- has_unsafe_traps_ = true;
- } else {
- SANDBOX_INFO(
- "Cannot disable sandbox and use unsafe traps unless "
- "CHROME_SANDBOX_DEBUGGING is turned on first");
- }
- }
- // Returns the, possibly updated, value of has_unsafe_traps_.
- return has_unsafe_traps_;
-}
-
-Trap* Trap::global_trap_;
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/trap.h b/security/sandbox/chromium/sandbox/linux/seccomp-bpf/trap.h
deleted file mode 100644
index a73d2064b..000000000
--- a/security/sandbox/chromium/sandbox/linux/seccomp-bpf/trap.h
+++ /dev/null
@@ -1,86 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_SECCOMP_BPF_TRAP_H__
-#define SANDBOX_LINUX_SECCOMP_BPF_TRAP_H__
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <map>
-
-#include "base/macros.h"
-#include "sandbox/linux/bpf_dsl/trap_registry.h"
-#include "sandbox/linux/system_headers/linux_signal.h"
-#include "sandbox/sandbox_export.h"
-
-namespace sandbox {
-
-// The Trap class allows a BPF filter program to branch out to user space by
-// raising a SIGSYS signal.
-// N.B.: This class does not perform any synchronization operations. If
-// modifications are made to any of the traps, it is the caller's
-// responsibility to ensure that this happens in a thread-safe fashion.
-// Preferably, that means that no other threads should be running at that
-// time. For the purposes of our sandbox, this assertion should always be
-// true. Threads are incompatible with the seccomp sandbox anyway.
-class SANDBOX_EXPORT Trap : public bpf_dsl::TrapRegistry {
- public:
- uint16_t Add(TrapFnc fnc, const void* aux, bool safe) override;
-
- bool EnableUnsafeTraps() override;
-
- // Registry returns the trap registry used by Trap's SIGSYS handler,
- // creating it if necessary.
- static bpf_dsl::TrapRegistry* Registry();
-
- // SandboxDebuggingAllowedByUser returns whether the
- // "CHROME_SANDBOX_DEBUGGING" environment variable is set.
- static bool SandboxDebuggingAllowedByUser();
-
- private:
- struct TrapKey {
- TrapKey() : fnc(NULL), aux(NULL), safe(false) {}
- TrapKey(TrapFnc f, const void* a, bool s) : fnc(f), aux(a), safe(s) {}
- TrapFnc fnc;
- const void* aux;
- bool safe;
- bool operator<(const TrapKey&) const;
- };
- typedef std::map<TrapKey, uint16_t> TrapIds;
-
- // Our constructor is private. A shared global instance is created
- // automatically as needed.
- Trap();
-
- // The destructor is unimplemented as destroying this object would
- // break subsequent system calls that trigger a SIGSYS.
- ~Trap() = delete;
-
- static void SigSysAction(int nr, LinuxSigInfo* info, void* void_context);
-
- // Make sure that SigSys is not inlined in order to get slightly better crash
- // dumps.
- void SigSys(int nr, LinuxSigInfo* info, ucontext_t* ctx)
- __attribute__((noinline));
- // We have a global singleton that handles all of our SIGSYS traps. This
- // variable must never be deallocated after it has been set up initially, as
- // there is no way to reset in-kernel BPF filters that generate SIGSYS
- // events.
- static Trap* global_trap_;
-
- TrapIds trap_ids_; // Maps from TrapKeys to numeric ids
- TrapKey* trap_array_; // Array of TrapKeys indexed by ids
- size_t trap_array_size_; // Currently used size of array
- size_t trap_array_capacity_; // Currently allocated capacity of array
- bool has_unsafe_traps_; // Whether unsafe traps have been enabled
-
- // Copying and assigning is unimplemented. It doesn't make sense for a
- // singleton.
- DISALLOW_COPY_AND_ASSIGN(Trap);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_SECCOMP_BPF_TRAP_H__
diff --git a/security/sandbox/chromium/sandbox/linux/services/syscall_wrappers.cc b/security/sandbox/chromium/sandbox/linux/services/syscall_wrappers.cc
deleted file mode 100644
index 9d5a6ada0..000000000
--- a/security/sandbox/chromium/sandbox/linux/services/syscall_wrappers.cc
+++ /dev/null
@@ -1,261 +0,0 @@
-// Copyright 2014 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 "sandbox/linux/services/syscall_wrappers.h"
-
-#include <pthread.h>
-#include <sched.h>
-#include <setjmp.h>
-#include <sys/resource.h>
-#include <sys/syscall.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <cstring>
-
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/third_party/valgrind/valgrind.h"
-#include "build/build_config.h"
-#include "sandbox/linux/system_headers/capability.h"
-#include "sandbox/linux/system_headers/linux_signal.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-namespace sandbox {
-
-pid_t sys_getpid(void) {
- return syscall(__NR_getpid);
-}
-
-pid_t sys_gettid(void) {
- return syscall(__NR_gettid);
-}
-
-long sys_clone(unsigned long flags,
- std::nullptr_t child_stack,
- pid_t* ptid,
- pid_t* ctid,
- std::nullptr_t tls) {
- const bool clone_tls_used = flags & CLONE_SETTLS;
- const bool invalid_ctid =
- (flags & (CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID)) && !ctid;
- const bool invalid_ptid = (flags & CLONE_PARENT_SETTID) && !ptid;
-
- // We do not support CLONE_VM.
- const bool clone_vm_used = flags & CLONE_VM;
- if (clone_tls_used || invalid_ctid || invalid_ptid || clone_vm_used) {
- RAW_LOG(FATAL, "Invalid usage of sys_clone");
- }
-
- if (ptid) MSAN_UNPOISON(ptid, sizeof(*ptid));
- if (ctid) MSAN_UNPOISON(ctid, sizeof(*ctid));
- // See kernel/fork.c in Linux. There is different ordering of sys_clone
- // parameters depending on CONFIG_CLONE_BACKWARDS* configuration options.
-#if defined(ARCH_CPU_X86_64)
- return syscall(__NR_clone, flags, child_stack, ptid, ctid, tls);
-#elif defined(ARCH_CPU_X86) || defined(ARCH_CPU_ARM_FAMILY) || \
- defined(ARCH_CPU_MIPS_FAMILY) || defined(ARCH_CPU_MIPS64_FAMILY)
- // CONFIG_CLONE_BACKWARDS defined.
- return syscall(__NR_clone, flags, child_stack, ptid, tls, ctid);
-#endif
-}
-
-long sys_clone(unsigned long flags) {
- return sys_clone(flags, nullptr, nullptr, nullptr, nullptr);
-}
-
-void sys_exit_group(int status) {
- syscall(__NR_exit_group, status);
-}
-
-int sys_seccomp(unsigned int operation,
- unsigned int flags,
- const struct sock_fprog* args) {
- return syscall(__NR_seccomp, operation, flags, args);
-}
-
-int sys_prlimit64(pid_t pid,
- int resource,
- const struct rlimit64* new_limit,
- struct rlimit64* old_limit) {
- int res = syscall(__NR_prlimit64, pid, resource, new_limit, old_limit);
- if (res == 0 && old_limit) MSAN_UNPOISON(old_limit, sizeof(*old_limit));
- return res;
-}
-
-int sys_capget(cap_hdr* hdrp, cap_data* datap) {
- int res = syscall(__NR_capget, hdrp, datap);
- if (res == 0) {
- if (hdrp) MSAN_UNPOISON(hdrp, sizeof(*hdrp));
- if (datap) MSAN_UNPOISON(datap, sizeof(*datap));
- }
- return res;
-}
-
-int sys_capset(cap_hdr* hdrp, const cap_data* datap) {
- return syscall(__NR_capset, hdrp, datap);
-}
-
-int sys_getresuid(uid_t* ruid, uid_t* euid, uid_t* suid) {
- int res;
-#if defined(ARCH_CPU_X86) || defined(ARCH_CPU_ARMEL)
- // On 32-bit x86 or 32-bit arm, getresuid supports 16bit values only.
- // Use getresuid32 instead.
- res = syscall(__NR_getresuid32, ruid, euid, suid);
-#else
- res = syscall(__NR_getresuid, ruid, euid, suid);
-#endif
- if (res == 0) {
- if (ruid) MSAN_UNPOISON(ruid, sizeof(*ruid));
- if (euid) MSAN_UNPOISON(euid, sizeof(*euid));
- if (suid) MSAN_UNPOISON(suid, sizeof(*suid));
- }
- return res;
-}
-
-int sys_getresgid(gid_t* rgid, gid_t* egid, gid_t* sgid) {
- int res;
-#if defined(ARCH_CPU_X86) || defined(ARCH_CPU_ARMEL)
- // On 32-bit x86 or 32-bit arm, getresgid supports 16bit values only.
- // Use getresgid32 instead.
- res = syscall(__NR_getresgid32, rgid, egid, sgid);
-#else
- res = syscall(__NR_getresgid, rgid, egid, sgid);
-#endif
- if (res == 0) {
- if (rgid) MSAN_UNPOISON(rgid, sizeof(*rgid));
- if (egid) MSAN_UNPOISON(egid, sizeof(*egid));
- if (sgid) MSAN_UNPOISON(sgid, sizeof(*sgid));
- }
- return res;
-}
-
-int sys_chroot(const char* path) {
- return syscall(__NR_chroot, path);
-}
-
-int sys_unshare(int flags) {
- return syscall(__NR_unshare, flags);
-}
-
-int sys_sigprocmask(int how, const sigset_t* set, std::nullptr_t oldset) {
- // In some toolchain (in particular Android and PNaCl toolchain),
- // sigset_t is 32 bits, but the Linux ABI uses more.
- LinuxSigSet linux_value;
- std::memset(&linux_value, 0, sizeof(LinuxSigSet));
- std::memcpy(&linux_value, set, std::min(sizeof(sigset_t),
- sizeof(LinuxSigSet)));
-
- return syscall(__NR_rt_sigprocmask, how, &linux_value, nullptr,
- sizeof(linux_value));
-}
-
-// When this is built with PNaCl toolchain, we should always use sys_sigaction
-// below, because sigaction() provided by the toolchain is incompatible with
-// Linux's ABI.
-#if !defined(OS_NACL_NONSFI)
-int sys_sigaction(int signum,
- const struct sigaction* act,
- struct sigaction* oldact) {
- return sigaction(signum, act, oldact);
-}
-#else
-#if defined(ARCH_CPU_X86_FAMILY)
-
-// On x86_64, sa_restorer is required. We specify it on x86 as well in order to
-// support kernels with VDSO disabled.
-#if !defined(SA_RESTORER)
-#define SA_RESTORER 0x04000000
-#endif
-
-// XSTR(__NR_foo) expands to a string literal containing the value value of
-// __NR_foo.
-#define STR(x) #x
-#define XSTR(x) STR(x)
-
-// rt_sigreturn is a special system call that interacts with the user land
-// stack. Thus, here prologue must not be created, which implies syscall()
-// does not work properly, too. Note that rt_sigreturn does not return.
-// TODO(rickyz): These assembly functions may still break stack unwinding on
-// nonsfi NaCl builds.
-#if defined(ARCH_CPU_X86_64)
-
-extern "C" {
- void sys_rt_sigreturn();
-}
-
-asm(
- ".text\n"
- "sys_rt_sigreturn:\n"
- "mov $" XSTR(__NR_rt_sigreturn) ", %eax\n"
- "syscall\n");
-
-#elif defined(ARCH_CPU_X86)
-extern "C" {
- void sys_sigreturn();
- void sys_rt_sigreturn();
-}
-
-asm(
- ".text\n"
- "sys_rt_sigreturn:\n"
- "mov $" XSTR(__NR_rt_sigreturn) ", %eax\n"
- "int $0x80\n"
-
- "sys_sigreturn:\n"
- "pop %eax\n"
- "mov $" XSTR(__NR_sigreturn) ", %eax\n"
- "int $0x80\n");
-#else
-#error "Unsupported architecture."
-#endif
-
-#undef STR
-#undef XSTR
-
-#endif
-
-int sys_sigaction(int signum,
- const struct sigaction* act,
- struct sigaction* oldact) {
- LinuxSigAction linux_act = {};
- if (act) {
- linux_act.kernel_handler = act->sa_handler;
- std::memcpy(&linux_act.sa_mask, &act->sa_mask,
- std::min(sizeof(linux_act.sa_mask), sizeof(act->sa_mask)));
- linux_act.sa_flags = act->sa_flags;
-
-#if defined(ARCH_CPU_X86_FAMILY)
- if (!(linux_act.sa_flags & SA_RESTORER)) {
- linux_act.sa_flags |= SA_RESTORER;
-#if defined(ARCH_CPU_X86_64)
- linux_act.sa_restorer = sys_rt_sigreturn;
-#elif defined(ARCH_CPU_X86)
- linux_act.sa_restorer =
- linux_act.sa_flags & SA_SIGINFO ? sys_rt_sigreturn : sys_sigreturn;
-#else
-#error "Unsupported architecture."
-#endif
- }
-#endif
- }
-
- LinuxSigAction linux_oldact = {};
- int result = syscall(__NR_rt_sigaction, signum, act ? &linux_act : nullptr,
- oldact ? &linux_oldact : nullptr,
- sizeof(LinuxSigSet));
-
- if (result == 0 && oldact) {
- oldact->sa_handler = linux_oldact.kernel_handler;
- sigemptyset(&oldact->sa_mask);
- std::memcpy(&oldact->sa_mask, &linux_oldact.sa_mask,
- std::min(sizeof(linux_act.sa_mask), sizeof(act->sa_mask)));
- oldact->sa_flags = linux_oldact.sa_flags;
- }
- return result;
-}
-
-#endif // defined(MEMORY_SANITIZER)
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/linux/services/syscall_wrappers.h b/security/sandbox/chromium/sandbox/linux/services/syscall_wrappers.h
deleted file mode 100644
index 057e4c87f..000000000
--- a/security/sandbox/chromium/sandbox/linux/services/syscall_wrappers.h
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_SERVICES_SYSCALL_WRAPPERS_H_
-#define SANDBOX_LINUX_SERVICES_SYSCALL_WRAPPERS_H_
-
-#include <signal.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <cstddef>
-
-#include "sandbox/sandbox_export.h"
-
-struct sock_fprog;
-struct rlimit64;
-struct cap_hdr;
-struct cap_data;
-
-namespace sandbox {
-
-// Provide direct system call wrappers for a few common system calls.
-// These are guaranteed to perform a system call and do not rely on things such
-// as caching the current pid (c.f. getpid()) unless otherwise specified.
-
-SANDBOX_EXPORT pid_t sys_getpid(void);
-
-SANDBOX_EXPORT pid_t sys_gettid(void);
-
-SANDBOX_EXPORT long sys_clone(unsigned long flags);
-
-// |regs| is not supported and must be passed as nullptr. |child_stack| must be
-// nullptr, since otherwise this function cannot safely return. As a
-// consequence, this function does not support CLONE_VM.
-SANDBOX_EXPORT long sys_clone(unsigned long flags,
- std::nullptr_t child_stack,
- pid_t* ptid,
- pid_t* ctid,
- std::nullptr_t regs);
-
-SANDBOX_EXPORT void sys_exit_group(int status);
-
-// The official system call takes |args| as void* (in order to be extensible),
-// but add more typing for the cases that are currently used.
-SANDBOX_EXPORT int sys_seccomp(unsigned int operation,
- unsigned int flags,
- const struct sock_fprog* args);
-
-// Some libcs do not expose a prlimit64 wrapper.
-SANDBOX_EXPORT int sys_prlimit64(pid_t pid,
- int resource,
- const struct rlimit64* new_limit,
- struct rlimit64* old_limit);
-
-// Some libcs do not expose capget/capset wrappers. We want to use these
-// directly in order to avoid pulling in libcap2.
-SANDBOX_EXPORT int sys_capget(struct cap_hdr* hdrp, struct cap_data* datap);
-SANDBOX_EXPORT int sys_capset(struct cap_hdr* hdrp,
- const struct cap_data* datap);
-
-// Some libcs do not expose getresuid/getresgid wrappers.
-SANDBOX_EXPORT int sys_getresuid(uid_t* ruid, uid_t* euid, uid_t* suid);
-SANDBOX_EXPORT int sys_getresgid(gid_t* rgid, gid_t* egid, gid_t* sgid);
-
-// Some libcs do not expose a chroot wrapper.
-SANDBOX_EXPORT int sys_chroot(const char* path);
-
-// Some libcs do not expose a unshare wrapper.
-SANDBOX_EXPORT int sys_unshare(int flags);
-
-// Some libcs do not expose a sigprocmask. Note that oldset must be a nullptr,
-// because of some ABI gap between toolchain's and Linux's.
-SANDBOX_EXPORT int sys_sigprocmask(int how,
- const sigset_t* set,
- std::nullptr_t oldset);
-
-// Some libcs do not expose a sigaction().
-SANDBOX_EXPORT int sys_sigaction(int signum,
- const struct sigaction* act,
- struct sigaction* oldact);
-
-} // namespace sandbox
-
-#endif // SANDBOX_LINUX_SERVICES_SYSCALL_WRAPPERS_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/arm_linux_syscalls.h b/security/sandbox/chromium/sandbox/linux/system_headers/arm_linux_syscalls.h
deleted file mode 100644
index 1addd5384..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/arm_linux_syscalls.h
+++ /dev/null
@@ -1,1418 +0,0 @@
-// 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.
-
-// Generated from the Linux kernel's calls.S.
-#ifndef SANDBOX_LINUX_SYSTEM_HEADERS_ARM_LINUX_SYSCALLS_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_ARM_LINUX_SYSCALLS_H_
-
-#if !defined(__arm__) || !defined(__ARM_EABI__)
-#error "Including header on wrong architecture"
-#endif
-
-#if !defined(__NR_SYSCALL_BASE)
-// On ARM EABI arch, __NR_SYSCALL_BASE is 0.
-#define __NR_SYSCALL_BASE 0
-#endif
-
-// This syscall list has holes, because ARM EABI makes some syscalls obsolete.
-
-#if !defined(__NR_restart_syscall)
-#define __NR_restart_syscall (__NR_SYSCALL_BASE+0)
-#endif
-
-#if !defined(__NR_exit)
-#define __NR_exit (__NR_SYSCALL_BASE+1)
-#endif
-
-#if !defined(__NR_fork)
-#define __NR_fork (__NR_SYSCALL_BASE+2)
-#endif
-
-#if !defined(__NR_read)
-#define __NR_read (__NR_SYSCALL_BASE+3)
-#endif
-
-#if !defined(__NR_write)
-#define __NR_write (__NR_SYSCALL_BASE+4)
-#endif
-
-#if !defined(__NR_open)
-#define __NR_open (__NR_SYSCALL_BASE+5)
-#endif
-
-#if !defined(__NR_close)
-#define __NR_close (__NR_SYSCALL_BASE+6)
-#endif
-
-#if !defined(__NR_creat)
-#define __NR_creat (__NR_SYSCALL_BASE+8)
-#endif
-
-#if !defined(__NR_link)
-#define __NR_link (__NR_SYSCALL_BASE+9)
-#endif
-
-#if !defined(__NR_unlink)
-#define __NR_unlink (__NR_SYSCALL_BASE+10)
-#endif
-
-#if !defined(__NR_execve)
-#define __NR_execve (__NR_SYSCALL_BASE+11)
-#endif
-
-#if !defined(__NR_chdir)
-#define __NR_chdir (__NR_SYSCALL_BASE+12)
-#endif
-
-#if !defined(__NR_mknod)
-#define __NR_mknod (__NR_SYSCALL_BASE+14)
-#endif
-
-#if !defined(__NR_chmod)
-#define __NR_chmod (__NR_SYSCALL_BASE+15)
-#endif
-
-#if !defined(__NR_lchown)
-#define __NR_lchown (__NR_SYSCALL_BASE+16)
-#endif
-
-#if !defined(__NR_lseek)
-#define __NR_lseek (__NR_SYSCALL_BASE+19)
-#endif
-
-#if !defined(__NR_getpid)
-#define __NR_getpid (__NR_SYSCALL_BASE+20)
-#endif
-
-#if !defined(__NR_mount)
-#define __NR_mount (__NR_SYSCALL_BASE+21)
-#endif
-
-#if !defined(__NR_setuid)
-#define __NR_setuid (__NR_SYSCALL_BASE+23)
-#endif
-
-#if !defined(__NR_getuid)
-#define __NR_getuid (__NR_SYSCALL_BASE+24)
-#endif
-
-#if !defined(__NR_ptrace)
-#define __NR_ptrace (__NR_SYSCALL_BASE+26)
-#endif
-
-#if !defined(__NR_pause)
-#define __NR_pause (__NR_SYSCALL_BASE+29)
-#endif
-
-#if !defined(__NR_access)
-#define __NR_access (__NR_SYSCALL_BASE+33)
-#endif
-
-#if !defined(__NR_nice)
-#define __NR_nice (__NR_SYSCALL_BASE+34)
-#endif
-
-#if !defined(__NR_sync)
-#define __NR_sync (__NR_SYSCALL_BASE+36)
-#endif
-
-#if !defined(__NR_kill)
-#define __NR_kill (__NR_SYSCALL_BASE+37)
-#endif
-
-#if !defined(__NR_rename)
-#define __NR_rename (__NR_SYSCALL_BASE+38)
-#endif
-
-#if !defined(__NR_mkdir)
-#define __NR_mkdir (__NR_SYSCALL_BASE+39)
-#endif
-
-#if !defined(__NR_rmdir)
-#define __NR_rmdir (__NR_SYSCALL_BASE+40)
-#endif
-
-#if !defined(__NR_dup)
-#define __NR_dup (__NR_SYSCALL_BASE+41)
-#endif
-
-#if !defined(__NR_pipe)
-#define __NR_pipe (__NR_SYSCALL_BASE+42)
-#endif
-
-#if !defined(__NR_times)
-#define __NR_times (__NR_SYSCALL_BASE+43)
-#endif
-
-#if !defined(__NR_brk)
-#define __NR_brk (__NR_SYSCALL_BASE+45)
-#endif
-
-#if !defined(__NR_setgid)
-#define __NR_setgid (__NR_SYSCALL_BASE+46)
-#endif
-
-#if !defined(__NR_getgid)
-#define __NR_getgid (__NR_SYSCALL_BASE+47)
-#endif
-
-#if !defined(__NR_geteuid)
-#define __NR_geteuid (__NR_SYSCALL_BASE+49)
-#endif
-
-#if !defined(__NR_getegid)
-#define __NR_getegid (__NR_SYSCALL_BASE+50)
-#endif
-
-#if !defined(__NR_acct)
-#define __NR_acct (__NR_SYSCALL_BASE+51)
-#endif
-
-#if !defined(__NR_umount2)
-#define __NR_umount2 (__NR_SYSCALL_BASE+52)
-#endif
-
-#if !defined(__NR_ioctl)
-#define __NR_ioctl (__NR_SYSCALL_BASE+54)
-#endif
-
-#if !defined(__NR_fcntl)
-#define __NR_fcntl (__NR_SYSCALL_BASE+55)
-#endif
-
-#if !defined(__NR_setpgid)
-#define __NR_setpgid (__NR_SYSCALL_BASE+57)
-#endif
-
-#if !defined(__NR_umask)
-#define __NR_umask (__NR_SYSCALL_BASE+60)
-#endif
-
-#if !defined(__NR_chroot)
-#define __NR_chroot (__NR_SYSCALL_BASE+61)
-#endif
-
-#if !defined(__NR_ustat)
-#define __NR_ustat (__NR_SYSCALL_BASE+62)
-#endif
-
-#if !defined(__NR_dup2)
-#define __NR_dup2 (__NR_SYSCALL_BASE+63)
-#endif
-
-#if !defined(__NR_getppid)
-#define __NR_getppid (__NR_SYSCALL_BASE+64)
-#endif
-
-#if !defined(__NR_getpgrp)
-#define __NR_getpgrp (__NR_SYSCALL_BASE+65)
-#endif
-
-#if !defined(__NR_setsid)
-#define __NR_setsid (__NR_SYSCALL_BASE+66)
-#endif
-
-#if !defined(__NR_sigaction)
-#define __NR_sigaction (__NR_SYSCALL_BASE+67)
-#endif
-
-#if !defined(__NR_setreuid)
-#define __NR_setreuid (__NR_SYSCALL_BASE+70)
-#endif
-
-#if !defined(__NR_setregid)
-#define __NR_setregid (__NR_SYSCALL_BASE+71)
-#endif
-
-#if !defined(__NR_sigsuspend)
-#define __NR_sigsuspend (__NR_SYSCALL_BASE+72)
-#endif
-
-#if !defined(__NR_sigpending)
-#define __NR_sigpending (__NR_SYSCALL_BASE+73)
-#endif
-
-#if !defined(__NR_sethostname)
-#define __NR_sethostname (__NR_SYSCALL_BASE+74)
-#endif
-
-#if !defined(__NR_setrlimit)
-#define __NR_setrlimit (__NR_SYSCALL_BASE+75)
-#endif
-
-#if !defined(__NR_getrusage)
-#define __NR_getrusage (__NR_SYSCALL_BASE+77)
-#endif
-
-#if !defined(__NR_gettimeofday)
-#define __NR_gettimeofday (__NR_SYSCALL_BASE+78)
-#endif
-
-#if !defined(__NR_settimeofday)
-#define __NR_settimeofday (__NR_SYSCALL_BASE+79)
-#endif
-
-#if !defined(__NR_getgroups)
-#define __NR_getgroups (__NR_SYSCALL_BASE+80)
-#endif
-
-#if !defined(__NR_setgroups)
-#define __NR_setgroups (__NR_SYSCALL_BASE+81)
-#endif
-
-#if !defined(__NR_symlink)
-#define __NR_symlink (__NR_SYSCALL_BASE+83)
-#endif
-
-#if !defined(__NR_readlink)
-#define __NR_readlink (__NR_SYSCALL_BASE+85)
-#endif
-
-#if !defined(__NR_uselib)
-#define __NR_uselib (__NR_SYSCALL_BASE+86)
-#endif
-
-#if !defined(__NR_swapon)
-#define __NR_swapon (__NR_SYSCALL_BASE+87)
-#endif
-
-#if !defined(__NR_reboot)
-#define __NR_reboot (__NR_SYSCALL_BASE+88)
-#endif
-
-#if !defined(__NR_munmap)
-#define __NR_munmap (__NR_SYSCALL_BASE+91)
-#endif
-
-#if !defined(__NR_truncate)
-#define __NR_truncate (__NR_SYSCALL_BASE+92)
-#endif
-
-#if !defined(__NR_ftruncate)
-#define __NR_ftruncate (__NR_SYSCALL_BASE+93)
-#endif
-
-#if !defined(__NR_fchmod)
-#define __NR_fchmod (__NR_SYSCALL_BASE+94)
-#endif
-
-#if !defined(__NR_fchown)
-#define __NR_fchown (__NR_SYSCALL_BASE+95)
-#endif
-
-#if !defined(__NR_getpriority)
-#define __NR_getpriority (__NR_SYSCALL_BASE+96)
-#endif
-
-#if !defined(__NR_setpriority)
-#define __NR_setpriority (__NR_SYSCALL_BASE+97)
-#endif
-
-#if !defined(__NR_statfs)
-#define __NR_statfs (__NR_SYSCALL_BASE+99)
-#endif
-
-#if !defined(__NR_fstatfs)
-#define __NR_fstatfs (__NR_SYSCALL_BASE+100)
-#endif
-
-#if !defined(__NR_syslog)
-#define __NR_syslog (__NR_SYSCALL_BASE+103)
-#endif
-
-#if !defined(__NR_setitimer)
-#define __NR_setitimer (__NR_SYSCALL_BASE+104)
-#endif
-
-#if !defined(__NR_getitimer)
-#define __NR_getitimer (__NR_SYSCALL_BASE+105)
-#endif
-
-#if !defined(__NR_stat)
-#define __NR_stat (__NR_SYSCALL_BASE+106)
-#endif
-
-#if !defined(__NR_lstat)
-#define __NR_lstat (__NR_SYSCALL_BASE+107)
-#endif
-
-#if !defined(__NR_fstat)
-#define __NR_fstat (__NR_SYSCALL_BASE+108)
-#endif
-
-#if !defined(__NR_vhangup)
-#define __NR_vhangup (__NR_SYSCALL_BASE+111)
-#endif
-
-#if !defined(__NR_wait4)
-#define __NR_wait4 (__NR_SYSCALL_BASE+114)
-#endif
-
-#if !defined(__NR_swapoff)
-#define __NR_swapoff (__NR_SYSCALL_BASE+115)
-#endif
-
-#if !defined(__NR_sysinfo)
-#define __NR_sysinfo (__NR_SYSCALL_BASE+116)
-#endif
-
-#if !defined(__NR_fsync)
-#define __NR_fsync (__NR_SYSCALL_BASE+118)
-#endif
-
-#if !defined(__NR_sigreturn)
-#define __NR_sigreturn (__NR_SYSCALL_BASE+119)
-#endif
-
-#if !defined(__NR_clone)
-#define __NR_clone (__NR_SYSCALL_BASE+120)
-#endif
-
-#if !defined(__NR_setdomainname)
-#define __NR_setdomainname (__NR_SYSCALL_BASE+121)
-#endif
-
-#if !defined(__NR_uname)
-#define __NR_uname (__NR_SYSCALL_BASE+122)
-#endif
-
-#if !defined(__NR_adjtimex)
-#define __NR_adjtimex (__NR_SYSCALL_BASE+124)
-#endif
-
-#if !defined(__NR_mprotect)
-#define __NR_mprotect (__NR_SYSCALL_BASE+125)
-#endif
-
-#if !defined(__NR_sigprocmask)
-#define __NR_sigprocmask (__NR_SYSCALL_BASE+126)
-#endif
-
-#if !defined(__NR_init_module)
-#define __NR_init_module (__NR_SYSCALL_BASE+128)
-#endif
-
-#if !defined(__NR_delete_module)
-#define __NR_delete_module (__NR_SYSCALL_BASE+129)
-#endif
-
-#if !defined(__NR_quotactl)
-#define __NR_quotactl (__NR_SYSCALL_BASE+131)
-#endif
-
-#if !defined(__NR_getpgid)
-#define __NR_getpgid (__NR_SYSCALL_BASE+132)
-#endif
-
-#if !defined(__NR_fchdir)
-#define __NR_fchdir (__NR_SYSCALL_BASE+133)
-#endif
-
-#if !defined(__NR_bdflush)
-#define __NR_bdflush (__NR_SYSCALL_BASE+134)
-#endif
-
-#if !defined(__NR_sysfs)
-#define __NR_sysfs (__NR_SYSCALL_BASE+135)
-#endif
-
-#if !defined(__NR_personality)
-#define __NR_personality (__NR_SYSCALL_BASE+136)
-#endif
-
-#if !defined(__NR_setfsuid)
-#define __NR_setfsuid (__NR_SYSCALL_BASE+138)
-#endif
-
-#if !defined(__NR_setfsgid)
-#define __NR_setfsgid (__NR_SYSCALL_BASE+139)
-#endif
-
-#if !defined(__NR__llseek)
-#define __NR__llseek (__NR_SYSCALL_BASE+140)
-#endif
-
-#if !defined(__NR_getdents)
-#define __NR_getdents (__NR_SYSCALL_BASE+141)
-#endif
-
-#if !defined(__NR__newselect)
-#define __NR__newselect (__NR_SYSCALL_BASE+142)
-#endif
-
-#if !defined(__NR_flock)
-#define __NR_flock (__NR_SYSCALL_BASE+143)
-#endif
-
-#if !defined(__NR_msync)
-#define __NR_msync (__NR_SYSCALL_BASE+144)
-#endif
-
-#if !defined(__NR_readv)
-#define __NR_readv (__NR_SYSCALL_BASE+145)
-#endif
-
-#if !defined(__NR_writev)
-#define __NR_writev (__NR_SYSCALL_BASE+146)
-#endif
-
-#if !defined(__NR_getsid)
-#define __NR_getsid (__NR_SYSCALL_BASE+147)
-#endif
-
-#if !defined(__NR_fdatasync)
-#define __NR_fdatasync (__NR_SYSCALL_BASE+148)
-#endif
-
-#if !defined(__NR__sysctl)
-#define __NR__sysctl (__NR_SYSCALL_BASE+149)
-#endif
-
-#if !defined(__NR_mlock)
-#define __NR_mlock (__NR_SYSCALL_BASE+150)
-#endif
-
-#if !defined(__NR_munlock)
-#define __NR_munlock (__NR_SYSCALL_BASE+151)
-#endif
-
-#if !defined(__NR_mlockall)
-#define __NR_mlockall (__NR_SYSCALL_BASE+152)
-#endif
-
-#if !defined(__NR_munlockall)
-#define __NR_munlockall (__NR_SYSCALL_BASE+153)
-#endif
-
-#if !defined(__NR_sched_setparam)
-#define __NR_sched_setparam (__NR_SYSCALL_BASE+154)
-#endif
-
-#if !defined(__NR_sched_getparam)
-#define __NR_sched_getparam (__NR_SYSCALL_BASE+155)
-#endif
-
-#if !defined(__NR_sched_setscheduler)
-#define __NR_sched_setscheduler (__NR_SYSCALL_BASE+156)
-#endif
-
-#if !defined(__NR_sched_getscheduler)
-#define __NR_sched_getscheduler (__NR_SYSCALL_BASE+157)
-#endif
-
-#if !defined(__NR_sched_yield)
-#define __NR_sched_yield (__NR_SYSCALL_BASE+158)
-#endif
-
-#if !defined(__NR_sched_get_priority_max)
-#define __NR_sched_get_priority_max (__NR_SYSCALL_BASE+159)
-#endif
-
-#if !defined(__NR_sched_get_priority_min)
-#define __NR_sched_get_priority_min (__NR_SYSCALL_BASE+160)
-#endif
-
-#if !defined(__NR_sched_rr_get_interval)
-#define __NR_sched_rr_get_interval (__NR_SYSCALL_BASE+161)
-#endif
-
-#if !defined(__NR_nanosleep)
-#define __NR_nanosleep (__NR_SYSCALL_BASE+162)
-#endif
-
-#if !defined(__NR_mremap)
-#define __NR_mremap (__NR_SYSCALL_BASE+163)
-#endif
-
-#if !defined(__NR_setresuid)
-#define __NR_setresuid (__NR_SYSCALL_BASE+164)
-#endif
-
-#if !defined(__NR_getresuid)
-#define __NR_getresuid (__NR_SYSCALL_BASE+165)
-#endif
-
-#if !defined(__NR_poll)
-#define __NR_poll (__NR_SYSCALL_BASE+168)
-#endif
-
-#if !defined(__NR_nfsservctl)
-#define __NR_nfsservctl (__NR_SYSCALL_BASE+169)
-#endif
-
-#if !defined(__NR_setresgid)
-#define __NR_setresgid (__NR_SYSCALL_BASE+170)
-#endif
-
-#if !defined(__NR_getresgid)
-#define __NR_getresgid (__NR_SYSCALL_BASE+171)
-#endif
-
-#if !defined(__NR_prctl)
-#define __NR_prctl (__NR_SYSCALL_BASE+172)
-#endif
-
-#if !defined(__NR_rt_sigreturn)
-#define __NR_rt_sigreturn (__NR_SYSCALL_BASE+173)
-#endif
-
-#if !defined(__NR_rt_sigaction)
-#define __NR_rt_sigaction (__NR_SYSCALL_BASE+174)
-#endif
-
-#if !defined(__NR_rt_sigprocmask)
-#define __NR_rt_sigprocmask (__NR_SYSCALL_BASE+175)
-#endif
-
-#if !defined(__NR_rt_sigpending)
-#define __NR_rt_sigpending (__NR_SYSCALL_BASE+176)
-#endif
-
-#if !defined(__NR_rt_sigtimedwait)
-#define __NR_rt_sigtimedwait (__NR_SYSCALL_BASE+177)
-#endif
-
-#if !defined(__NR_rt_sigqueueinfo)
-#define __NR_rt_sigqueueinfo (__NR_SYSCALL_BASE+178)
-#endif
-
-#if !defined(__NR_rt_sigsuspend)
-#define __NR_rt_sigsuspend (__NR_SYSCALL_BASE+179)
-#endif
-
-#if !defined(__NR_pread64)
-#define __NR_pread64 (__NR_SYSCALL_BASE+180)
-#endif
-
-#if !defined(__NR_pwrite64)
-#define __NR_pwrite64 (__NR_SYSCALL_BASE+181)
-#endif
-
-#if !defined(__NR_chown)
-#define __NR_chown (__NR_SYSCALL_BASE+182)
-#endif
-
-#if !defined(__NR_getcwd)
-#define __NR_getcwd (__NR_SYSCALL_BASE+183)
-#endif
-
-#if !defined(__NR_capget)
-#define __NR_capget (__NR_SYSCALL_BASE+184)
-#endif
-
-#if !defined(__NR_capset)
-#define __NR_capset (__NR_SYSCALL_BASE+185)
-#endif
-
-#if !defined(__NR_sigaltstack)
-#define __NR_sigaltstack (__NR_SYSCALL_BASE+186)
-#endif
-
-#if !defined(__NR_sendfile)
-#define __NR_sendfile (__NR_SYSCALL_BASE+187)
-#endif
-
-#if !defined(__NR_vfork)
-#define __NR_vfork (__NR_SYSCALL_BASE+190)
-#endif
-
-#if !defined(__NR_ugetrlimit)
-#define __NR_ugetrlimit (__NR_SYSCALL_BASE+191)
-#endif
-
-#if !defined(__NR_mmap2)
-#define __NR_mmap2 (__NR_SYSCALL_BASE+192)
-#endif
-
-#if !defined(__NR_truncate64)
-#define __NR_truncate64 (__NR_SYSCALL_BASE+193)
-#endif
-
-#if !defined(__NR_ftruncate64)
-#define __NR_ftruncate64 (__NR_SYSCALL_BASE+194)
-#endif
-
-#if !defined(__NR_stat64)
-#define __NR_stat64 (__NR_SYSCALL_BASE+195)
-#endif
-
-#if !defined(__NR_lstat64)
-#define __NR_lstat64 (__NR_SYSCALL_BASE+196)
-#endif
-
-#if !defined(__NR_fstat64)
-#define __NR_fstat64 (__NR_SYSCALL_BASE+197)
-#endif
-
-#if !defined(__NR_lchown32)
-#define __NR_lchown32 (__NR_SYSCALL_BASE+198)
-#endif
-
-#if !defined(__NR_getuid32)
-#define __NR_getuid32 (__NR_SYSCALL_BASE+199)
-#endif
-
-#if !defined(__NR_getgid32)
-#define __NR_getgid32 (__NR_SYSCALL_BASE+200)
-#endif
-
-#if !defined(__NR_geteuid32)
-#define __NR_geteuid32 (__NR_SYSCALL_BASE+201)
-#endif
-
-#if !defined(__NR_getegid32)
-#define __NR_getegid32 (__NR_SYSCALL_BASE+202)
-#endif
-
-#if !defined(__NR_setreuid32)
-#define __NR_setreuid32 (__NR_SYSCALL_BASE+203)
-#endif
-
-#if !defined(__NR_setregid32)
-#define __NR_setregid32 (__NR_SYSCALL_BASE+204)
-#endif
-
-#if !defined(__NR_getgroups32)
-#define __NR_getgroups32 (__NR_SYSCALL_BASE+205)
-#endif
-
-#if !defined(__NR_setgroups32)
-#define __NR_setgroups32 (__NR_SYSCALL_BASE+206)
-#endif
-
-#if !defined(__NR_fchown32)
-#define __NR_fchown32 (__NR_SYSCALL_BASE+207)
-#endif
-
-#if !defined(__NR_setresuid32)
-#define __NR_setresuid32 (__NR_SYSCALL_BASE+208)
-#endif
-
-#if !defined(__NR_getresuid32)
-#define __NR_getresuid32 (__NR_SYSCALL_BASE+209)
-#endif
-
-#if !defined(__NR_setresgid32)
-#define __NR_setresgid32 (__NR_SYSCALL_BASE+210)
-#endif
-
-#if !defined(__NR_getresgid32)
-#define __NR_getresgid32 (__NR_SYSCALL_BASE+211)
-#endif
-
-#if !defined(__NR_chown32)
-#define __NR_chown32 (__NR_SYSCALL_BASE+212)
-#endif
-
-#if !defined(__NR_setuid32)
-#define __NR_setuid32 (__NR_SYSCALL_BASE+213)
-#endif
-
-#if !defined(__NR_setgid32)
-#define __NR_setgid32 (__NR_SYSCALL_BASE+214)
-#endif
-
-#if !defined(__NR_setfsuid32)
-#define __NR_setfsuid32 (__NR_SYSCALL_BASE+215)
-#endif
-
-#if !defined(__NR_setfsgid32)
-#define __NR_setfsgid32 (__NR_SYSCALL_BASE+216)
-#endif
-
-#if !defined(__NR_getdents64)
-#define __NR_getdents64 (__NR_SYSCALL_BASE+217)
-#endif
-
-#if !defined(__NR_pivot_root)
-#define __NR_pivot_root (__NR_SYSCALL_BASE+218)
-#endif
-
-#if !defined(__NR_mincore)
-#define __NR_mincore (__NR_SYSCALL_BASE+219)
-#endif
-
-#if !defined(__NR_madvise)
-#define __NR_madvise (__NR_SYSCALL_BASE+220)
-#endif
-
-#if !defined(__NR_fcntl64)
-#define __NR_fcntl64 (__NR_SYSCALL_BASE+221)
-#endif
-
-#if !defined(__NR_gettid)
-#define __NR_gettid (__NR_SYSCALL_BASE+224)
-#endif
-
-#if !defined(__NR_readahead)
-#define __NR_readahead (__NR_SYSCALL_BASE+225)
-#endif
-
-#if !defined(__NR_setxattr)
-#define __NR_setxattr (__NR_SYSCALL_BASE+226)
-#endif
-
-#if !defined(__NR_lsetxattr)
-#define __NR_lsetxattr (__NR_SYSCALL_BASE+227)
-#endif
-
-#if !defined(__NR_fsetxattr)
-#define __NR_fsetxattr (__NR_SYSCALL_BASE+228)
-#endif
-
-#if !defined(__NR_getxattr)
-#define __NR_getxattr (__NR_SYSCALL_BASE+229)
-#endif
-
-#if !defined(__NR_lgetxattr)
-#define __NR_lgetxattr (__NR_SYSCALL_BASE+230)
-#endif
-
-#if !defined(__NR_fgetxattr)
-#define __NR_fgetxattr (__NR_SYSCALL_BASE+231)
-#endif
-
-#if !defined(__NR_listxattr)
-#define __NR_listxattr (__NR_SYSCALL_BASE+232)
-#endif
-
-#if !defined(__NR_llistxattr)
-#define __NR_llistxattr (__NR_SYSCALL_BASE+233)
-#endif
-
-#if !defined(__NR_flistxattr)
-#define __NR_flistxattr (__NR_SYSCALL_BASE+234)
-#endif
-
-#if !defined(__NR_removexattr)
-#define __NR_removexattr (__NR_SYSCALL_BASE+235)
-#endif
-
-#if !defined(__NR_lremovexattr)
-#define __NR_lremovexattr (__NR_SYSCALL_BASE+236)
-#endif
-
-#if !defined(__NR_fremovexattr)
-#define __NR_fremovexattr (__NR_SYSCALL_BASE+237)
-#endif
-
-#if !defined(__NR_tkill)
-#define __NR_tkill (__NR_SYSCALL_BASE+238)
-#endif
-
-#if !defined(__NR_sendfile64)
-#define __NR_sendfile64 (__NR_SYSCALL_BASE+239)
-#endif
-
-#if !defined(__NR_futex)
-#define __NR_futex (__NR_SYSCALL_BASE+240)
-#endif
-
-#if !defined(__NR_sched_setaffinity)
-#define __NR_sched_setaffinity (__NR_SYSCALL_BASE+241)
-#endif
-
-#if !defined(__NR_sched_getaffinity)
-#define __NR_sched_getaffinity (__NR_SYSCALL_BASE+242)
-#endif
-
-#if !defined(__NR_io_setup)
-#define __NR_io_setup (__NR_SYSCALL_BASE+243)
-#endif
-
-#if !defined(__NR_io_destroy)
-#define __NR_io_destroy (__NR_SYSCALL_BASE+244)
-#endif
-
-#if !defined(__NR_io_getevents)
-#define __NR_io_getevents (__NR_SYSCALL_BASE+245)
-#endif
-
-#if !defined(__NR_io_submit)
-#define __NR_io_submit (__NR_SYSCALL_BASE+246)
-#endif
-
-#if !defined(__NR_io_cancel)
-#define __NR_io_cancel (__NR_SYSCALL_BASE+247)
-#endif
-
-#if !defined(__NR_exit_group)
-#define __NR_exit_group (__NR_SYSCALL_BASE+248)
-#endif
-
-#if !defined(__NR_lookup_dcookie)
-#define __NR_lookup_dcookie (__NR_SYSCALL_BASE+249)
-#endif
-
-#if !defined(__NR_epoll_create)
-#define __NR_epoll_create (__NR_SYSCALL_BASE+250)
-#endif
-
-#if !defined(__NR_epoll_ctl)
-#define __NR_epoll_ctl (__NR_SYSCALL_BASE+251)
-#endif
-
-#if !defined(__NR_epoll_wait)
-#define __NR_epoll_wait (__NR_SYSCALL_BASE+252)
-#endif
-
-#if !defined(__NR_remap_file_pages)
-#define __NR_remap_file_pages (__NR_SYSCALL_BASE+253)
-#endif
-
-#if !defined(__NR_set_tid_address)
-#define __NR_set_tid_address (__NR_SYSCALL_BASE+256)
-#endif
-
-#if !defined(__NR_timer_create)
-#define __NR_timer_create (__NR_SYSCALL_BASE+257)
-#endif
-
-#if !defined(__NR_timer_settime)
-#define __NR_timer_settime (__NR_SYSCALL_BASE+258)
-#endif
-
-#if !defined(__NR_timer_gettime)
-#define __NR_timer_gettime (__NR_SYSCALL_BASE+259)
-#endif
-
-#if !defined(__NR_timer_getoverrun)
-#define __NR_timer_getoverrun (__NR_SYSCALL_BASE+260)
-#endif
-
-#if !defined(__NR_timer_delete)
-#define __NR_timer_delete (__NR_SYSCALL_BASE+261)
-#endif
-
-#if !defined(__NR_clock_settime)
-#define __NR_clock_settime (__NR_SYSCALL_BASE+262)
-#endif
-
-#if !defined(__NR_clock_gettime)
-#define __NR_clock_gettime (__NR_SYSCALL_BASE+263)
-#endif
-
-#if !defined(__NR_clock_getres)
-#define __NR_clock_getres (__NR_SYSCALL_BASE+264)
-#endif
-
-#if !defined(__NR_clock_nanosleep)
-#define __NR_clock_nanosleep (__NR_SYSCALL_BASE+265)
-#endif
-
-#if !defined(__NR_statfs64)
-#define __NR_statfs64 (__NR_SYSCALL_BASE+266)
-#endif
-
-#if !defined(__NR_fstatfs64)
-#define __NR_fstatfs64 (__NR_SYSCALL_BASE+267)
-#endif
-
-#if !defined(__NR_tgkill)
-#define __NR_tgkill (__NR_SYSCALL_BASE+268)
-#endif
-
-#if !defined(__NR_utimes)
-#define __NR_utimes (__NR_SYSCALL_BASE+269)
-#endif
-
-#if !defined(__NR_arm_fadvise64_64)
-#define __NR_arm_fadvise64_64 (__NR_SYSCALL_BASE+270)
-#endif
-
-#if !defined(__NR_pciconfig_iobase)
-#define __NR_pciconfig_iobase (__NR_SYSCALL_BASE+271)
-#endif
-
-#if !defined(__NR_pciconfig_read)
-#define __NR_pciconfig_read (__NR_SYSCALL_BASE+272)
-#endif
-
-#if !defined(__NR_pciconfig_write)
-#define __NR_pciconfig_write (__NR_SYSCALL_BASE+273)
-#endif
-
-#if !defined(__NR_mq_open)
-#define __NR_mq_open (__NR_SYSCALL_BASE+274)
-#endif
-
-#if !defined(__NR_mq_unlink)
-#define __NR_mq_unlink (__NR_SYSCALL_BASE+275)
-#endif
-
-#if !defined(__NR_mq_timedsend)
-#define __NR_mq_timedsend (__NR_SYSCALL_BASE+276)
-#endif
-
-#if !defined(__NR_mq_timedreceive)
-#define __NR_mq_timedreceive (__NR_SYSCALL_BASE+277)
-#endif
-
-#if !defined(__NR_mq_notify)
-#define __NR_mq_notify (__NR_SYSCALL_BASE+278)
-#endif
-
-#if !defined(__NR_mq_getsetattr)
-#define __NR_mq_getsetattr (__NR_SYSCALL_BASE+279)
-#endif
-
-#if !defined(__NR_waitid)
-#define __NR_waitid (__NR_SYSCALL_BASE+280)
-#endif
-
-#if !defined(__NR_socket)
-#define __NR_socket (__NR_SYSCALL_BASE+281)
-#endif
-
-#if !defined(__NR_bind)
-#define __NR_bind (__NR_SYSCALL_BASE+282)
-#endif
-
-#if !defined(__NR_connect)
-#define __NR_connect (__NR_SYSCALL_BASE+283)
-#endif
-
-#if !defined(__NR_listen)
-#define __NR_listen (__NR_SYSCALL_BASE+284)
-#endif
-
-#if !defined(__NR_accept)
-#define __NR_accept (__NR_SYSCALL_BASE+285)
-#endif
-
-#if !defined(__NR_getsockname)
-#define __NR_getsockname (__NR_SYSCALL_BASE+286)
-#endif
-
-#if !defined(__NR_getpeername)
-#define __NR_getpeername (__NR_SYSCALL_BASE+287)
-#endif
-
-#if !defined(__NR_socketpair)
-#define __NR_socketpair (__NR_SYSCALL_BASE+288)
-#endif
-
-#if !defined(__NR_send)
-#define __NR_send (__NR_SYSCALL_BASE+289)
-#endif
-
-#if !defined(__NR_sendto)
-#define __NR_sendto (__NR_SYSCALL_BASE+290)
-#endif
-
-#if !defined(__NR_recv)
-#define __NR_recv (__NR_SYSCALL_BASE+291)
-#endif
-
-#if !defined(__NR_recvfrom)
-#define __NR_recvfrom (__NR_SYSCALL_BASE+292)
-#endif
-
-#if !defined(__NR_shutdown)
-#define __NR_shutdown (__NR_SYSCALL_BASE+293)
-#endif
-
-#if !defined(__NR_setsockopt)
-#define __NR_setsockopt (__NR_SYSCALL_BASE+294)
-#endif
-
-#if !defined(__NR_getsockopt)
-#define __NR_getsockopt (__NR_SYSCALL_BASE+295)
-#endif
-
-#if !defined(__NR_sendmsg)
-#define __NR_sendmsg (__NR_SYSCALL_BASE+296)
-#endif
-
-#if !defined(__NR_recvmsg)
-#define __NR_recvmsg (__NR_SYSCALL_BASE+297)
-#endif
-
-#if !defined(__NR_semop)
-#define __NR_semop (__NR_SYSCALL_BASE+298)
-#endif
-
-#if !defined(__NR_semget)
-#define __NR_semget (__NR_SYSCALL_BASE+299)
-#endif
-
-#if !defined(__NR_semctl)
-#define __NR_semctl (__NR_SYSCALL_BASE+300)
-#endif
-
-#if !defined(__NR_msgsnd)
-#define __NR_msgsnd (__NR_SYSCALL_BASE+301)
-#endif
-
-#if !defined(__NR_msgrcv)
-#define __NR_msgrcv (__NR_SYSCALL_BASE+302)
-#endif
-
-#if !defined(__NR_msgget)
-#define __NR_msgget (__NR_SYSCALL_BASE+303)
-#endif
-
-#if !defined(__NR_msgctl)
-#define __NR_msgctl (__NR_SYSCALL_BASE+304)
-#endif
-
-#if !defined(__NR_shmat)
-#define __NR_shmat (__NR_SYSCALL_BASE+305)
-#endif
-
-#if !defined(__NR_shmdt)
-#define __NR_shmdt (__NR_SYSCALL_BASE+306)
-#endif
-
-#if !defined(__NR_shmget)
-#define __NR_shmget (__NR_SYSCALL_BASE+307)
-#endif
-
-#if !defined(__NR_shmctl)
-#define __NR_shmctl (__NR_SYSCALL_BASE+308)
-#endif
-
-#if !defined(__NR_add_key)
-#define __NR_add_key (__NR_SYSCALL_BASE+309)
-#endif
-
-#if !defined(__NR_request_key)
-#define __NR_request_key (__NR_SYSCALL_BASE+310)
-#endif
-
-#if !defined(__NR_keyctl)
-#define __NR_keyctl (__NR_SYSCALL_BASE+311)
-#endif
-
-#if !defined(__NR_semtimedop)
-#define __NR_semtimedop (__NR_SYSCALL_BASE+312)
-#endif
-
-#if !defined(__NR_vserver)
-#define __NR_vserver (__NR_SYSCALL_BASE+313)
-#endif
-
-#if !defined(__NR_ioprio_set)
-#define __NR_ioprio_set (__NR_SYSCALL_BASE+314)
-#endif
-
-#if !defined(__NR_ioprio_get)
-#define __NR_ioprio_get (__NR_SYSCALL_BASE+315)
-#endif
-
-#if !defined(__NR_inotify_init)
-#define __NR_inotify_init (__NR_SYSCALL_BASE+316)
-#endif
-
-#if !defined(__NR_inotify_add_watch)
-#define __NR_inotify_add_watch (__NR_SYSCALL_BASE+317)
-#endif
-
-#if !defined(__NR_inotify_rm_watch)
-#define __NR_inotify_rm_watch (__NR_SYSCALL_BASE+318)
-#endif
-
-#if !defined(__NR_mbind)
-#define __NR_mbind (__NR_SYSCALL_BASE+319)
-#endif
-
-#if !defined(__NR_get_mempolicy)
-#define __NR_get_mempolicy (__NR_SYSCALL_BASE+320)
-#endif
-
-#if !defined(__NR_set_mempolicy)
-#define __NR_set_mempolicy (__NR_SYSCALL_BASE+321)
-#endif
-
-#if !defined(__NR_openat)
-#define __NR_openat (__NR_SYSCALL_BASE+322)
-#endif
-
-#if !defined(__NR_mkdirat)
-#define __NR_mkdirat (__NR_SYSCALL_BASE+323)
-#endif
-
-#if !defined(__NR_mknodat)
-#define __NR_mknodat (__NR_SYSCALL_BASE+324)
-#endif
-
-#if !defined(__NR_fchownat)
-#define __NR_fchownat (__NR_SYSCALL_BASE+325)
-#endif
-
-#if !defined(__NR_futimesat)
-#define __NR_futimesat (__NR_SYSCALL_BASE+326)
-#endif
-
-#if !defined(__NR_fstatat64)
-#define __NR_fstatat64 (__NR_SYSCALL_BASE+327)
-#endif
-
-#if !defined(__NR_unlinkat)
-#define __NR_unlinkat (__NR_SYSCALL_BASE+328)
-#endif
-
-#if !defined(__NR_renameat)
-#define __NR_renameat (__NR_SYSCALL_BASE+329)
-#endif
-
-#if !defined(__NR_linkat)
-#define __NR_linkat (__NR_SYSCALL_BASE+330)
-#endif
-
-#if !defined(__NR_symlinkat)
-#define __NR_symlinkat (__NR_SYSCALL_BASE+331)
-#endif
-
-#if !defined(__NR_readlinkat)
-#define __NR_readlinkat (__NR_SYSCALL_BASE+332)
-#endif
-
-#if !defined(__NR_fchmodat)
-#define __NR_fchmodat (__NR_SYSCALL_BASE+333)
-#endif
-
-#if !defined(__NR_faccessat)
-#define __NR_faccessat (__NR_SYSCALL_BASE+334)
-#endif
-
-#if !defined(__NR_pselect6)
-#define __NR_pselect6 (__NR_SYSCALL_BASE+335)
-#endif
-
-#if !defined(__NR_ppoll)
-#define __NR_ppoll (__NR_SYSCALL_BASE+336)
-#endif
-
-#if !defined(__NR_unshare)
-#define __NR_unshare (__NR_SYSCALL_BASE+337)
-#endif
-
-#if !defined(__NR_set_robust_list)
-#define __NR_set_robust_list (__NR_SYSCALL_BASE+338)
-#endif
-
-#if !defined(__NR_get_robust_list)
-#define __NR_get_robust_list (__NR_SYSCALL_BASE+339)
-#endif
-
-#if !defined(__NR_splice)
-#define __NR_splice (__NR_SYSCALL_BASE+340)
-#endif
-
-#if !defined(__NR_arm_sync_file_range)
-#define __NR_arm_sync_file_range (__NR_SYSCALL_BASE+341)
-#endif
-
-#if !defined(__NR_sync_file_range2)
-#define __NR_sync_file_range2 (__NR_SYSCALL_BASE+341)
-#endif
-
-#if !defined(__NR_tee)
-#define __NR_tee (__NR_SYSCALL_BASE+342)
-#endif
-
-#if !defined(__NR_vmsplice)
-#define __NR_vmsplice (__NR_SYSCALL_BASE+343)
-#endif
-
-#if !defined(__NR_move_pages)
-#define __NR_move_pages (__NR_SYSCALL_BASE+344)
-#endif
-
-#if !defined(__NR_getcpu)
-#define __NR_getcpu (__NR_SYSCALL_BASE+345)
-#endif
-
-#if !defined(__NR_epoll_pwait)
-#define __NR_epoll_pwait (__NR_SYSCALL_BASE+346)
-#endif
-
-#if !defined(__NR_kexec_load)
-#define __NR_kexec_load (__NR_SYSCALL_BASE+347)
-#endif
-
-#if !defined(__NR_utimensat)
-#define __NR_utimensat (__NR_SYSCALL_BASE+348)
-#endif
-
-#if !defined(__NR_signalfd)
-#define __NR_signalfd (__NR_SYSCALL_BASE+349)
-#endif
-
-#if !defined(__NR_timerfd_create)
-#define __NR_timerfd_create (__NR_SYSCALL_BASE+350)
-#endif
-
-#if !defined(__NR_eventfd)
-#define __NR_eventfd (__NR_SYSCALL_BASE+351)
-#endif
-
-#if !defined(__NR_fallocate)
-#define __NR_fallocate (__NR_SYSCALL_BASE+352)
-#endif
-
-#if !defined(__NR_timerfd_settime)
-#define __NR_timerfd_settime (__NR_SYSCALL_BASE+353)
-#endif
-
-#if !defined(__NR_timerfd_gettime)
-#define __NR_timerfd_gettime (__NR_SYSCALL_BASE+354)
-#endif
-
-#if !defined(__NR_signalfd4)
-#define __NR_signalfd4 (__NR_SYSCALL_BASE+355)
-#endif
-
-#if !defined(__NR_eventfd2)
-#define __NR_eventfd2 (__NR_SYSCALL_BASE+356)
-#endif
-
-#if !defined(__NR_epoll_create1)
-#define __NR_epoll_create1 (__NR_SYSCALL_BASE+357)
-#endif
-
-#if !defined(__NR_dup3)
-#define __NR_dup3 (__NR_SYSCALL_BASE+358)
-#endif
-
-#if !defined(__NR_pipe2)
-#define __NR_pipe2 (__NR_SYSCALL_BASE+359)
-#endif
-
-#if !defined(__NR_inotify_init1)
-#define __NR_inotify_init1 (__NR_SYSCALL_BASE+360)
-#endif
-
-#if !defined(__NR_preadv)
-#define __NR_preadv (__NR_SYSCALL_BASE+361)
-#endif
-
-#if !defined(__NR_pwritev)
-#define __NR_pwritev (__NR_SYSCALL_BASE+362)
-#endif
-
-#if !defined(__NR_rt_tgsigqueueinfo)
-#define __NR_rt_tgsigqueueinfo (__NR_SYSCALL_BASE+363)
-#endif
-
-#if !defined(__NR_perf_event_open)
-#define __NR_perf_event_open (__NR_SYSCALL_BASE+364)
-#endif
-
-#if !defined(__NR_recvmmsg)
-#define __NR_recvmmsg (__NR_SYSCALL_BASE+365)
-#endif
-
-#if !defined(__NR_accept4)
-#define __NR_accept4 (__NR_SYSCALL_BASE+366)
-#endif
-
-#if !defined(__NR_fanotify_init)
-#define __NR_fanotify_init (__NR_SYSCALL_BASE+367)
-#endif
-
-#if !defined(__NR_fanotify_mark)
-#define __NR_fanotify_mark (__NR_SYSCALL_BASE+368)
-#endif
-
-#if !defined(__NR_prlimit64)
-#define __NR_prlimit64 (__NR_SYSCALL_BASE+369)
-#endif
-
-#if !defined(__NR_name_to_handle_at)
-#define __NR_name_to_handle_at (__NR_SYSCALL_BASE+370)
-#endif
-
-#if !defined(__NR_open_by_handle_at)
-#define __NR_open_by_handle_at (__NR_SYSCALL_BASE+371)
-#endif
-
-#if !defined(__NR_clock_adjtime)
-#define __NR_clock_adjtime (__NR_SYSCALL_BASE+372)
-#endif
-
-#if !defined(__NR_syncfs)
-#define __NR_syncfs (__NR_SYSCALL_BASE+373)
-#endif
-
-#if !defined(__NR_sendmmsg)
-#define __NR_sendmmsg (__NR_SYSCALL_BASE+374)
-#endif
-
-#if !defined(__NR_setns)
-#define __NR_setns (__NR_SYSCALL_BASE+375)
-#endif
-
-#if !defined(__NR_process_vm_readv)
-#define __NR_process_vm_readv (__NR_SYSCALL_BASE+376)
-#endif
-
-#if !defined(__NR_process_vm_writev)
-#define __NR_process_vm_writev (__NR_SYSCALL_BASE+377)
-#endif
-
-#if !defined(__NR_kcmp)
-#define __NR_kcmp (__NR_SYSCALL_BASE+378)
-#endif
-
-#if !defined(__NR_finit_module)
-#define __NR_finit_module (__NR_SYSCALL_BASE+379)
-#endif
-
-#if !defined(__NR_sched_setattr)
-#define __NR_sched_setattr (__NR_SYSCALL_BASE+380)
-#endif
-
-#if !defined(__NR_sched_getattr)
-#define __NR_sched_getattr (__NR_SYSCALL_BASE+381)
-#endif
-
-#if !defined(__NR_renameat2)
-#define __NR_renameat2 (__NR_SYSCALL_BASE+382)
-#endif
-
-#if !defined(__NR_seccomp)
-#define __NR_seccomp (__NR_SYSCALL_BASE+383)
-#endif
-
-#if !defined(__NR_getrandom)
-#define __NR_getrandom (__NR_SYSCALL_BASE+384)
-#endif
-
-#if !defined(__NR_memfd_create)
-#define __NR_memfd_create (__NR_SYSCALL_BASE+385)
-#endif
-
-// ARM private syscalls.
-#if !defined(__ARM_NR_BASE)
-#define __ARM_NR_BASE (__NR_SYSCALL_BASE + 0xF0000)
-#endif
-
-#if !defined(__ARM_NR_breakpoint)
-#define __ARM_NR_breakpoint (__ARM_NR_BASE+1)
-#endif
-
-#if !defined(__ARM_NR_cacheflush)
-#define __ARM_NR_cacheflush (__ARM_NR_BASE+2)
-#endif
-
-#if !defined(__ARM_NR_usr26)
-#define __ARM_NR_usr26 (__ARM_NR_BASE+3)
-#endif
-
-#if !defined(__ARM_NR_usr32)
-#define __ARM_NR_usr32 (__ARM_NR_BASE+4)
-#endif
-
-#if !defined(__ARM_NR_set_tls)
-#define __ARM_NR_set_tls (__ARM_NR_BASE+5)
-#endif
-
-// ARM kernel private syscall.
-#if !defined(__ARM_NR_cmpxchg)
-#define __ARM_NR_cmpxchg (__ARM_NR_BASE+0x00fff0)
-#endif
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_ARM_LINUX_SYSCALLS_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/arm_linux_ucontext.h b/security/sandbox/chromium/sandbox/linux/system_headers/arm_linux_ucontext.h
deleted file mode 100644
index 35208fa2a..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/arm_linux_ucontext.h
+++ /dev/null
@@ -1,69 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_SYSTEM_HEADERS_ARM_LINUX_UCONTEXT_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_ARM_LINUX_UCONTEXT_H_
-
-#include <stddef.h>
-
-#if !defined(__BIONIC_HAVE_UCONTEXT_T)
-#if !defined(__native_client_nonsfi__)
-#include <asm/sigcontext.h>
-#else
-// In PNaCl toolchain, sigcontext and stack_t is not defined. So here declare
-// them.
-struct sigcontext {
- unsigned long trap_no;
- unsigned long error_code;
- unsigned long oldmask;
- unsigned long arm_r0;
- unsigned long arm_r1;
- unsigned long arm_r2;
- unsigned long arm_r3;
- unsigned long arm_r4;
- unsigned long arm_r5;
- unsigned long arm_r6;
- unsigned long arm_r7;
- unsigned long arm_r8;
- unsigned long arm_r9;
- unsigned long arm_r10;
- unsigned long arm_fp;
- unsigned long arm_ip;
- unsigned long arm_sp;
- unsigned long arm_lr;
- unsigned long arm_pc;
- unsigned long arm_cpsr;
- unsigned long fault_address;
-};
-
-typedef struct sigaltstack {
- void* ss_sp;
- int ss_flags;
- size_t ss_size;
-} stack_t;
-
-#endif
-
-// We also need greg_t for the sandbox, include it in this header as well.
-typedef unsigned long greg_t;
-
-// typedef unsigned long sigset_t;
-typedef struct ucontext {
- unsigned long uc_flags;
- struct ucontext* uc_link;
- stack_t uc_stack;
- struct sigcontext uc_mcontext;
- sigset_t uc_sigmask;
- /* Allow for uc_sigmask growth. Glibc uses a 1024-bit sigset_t. */
- int __not_used[32 - (sizeof(sigset_t) / sizeof(int))];
- /* Last for extensibility. Eight byte aligned because some
- coprocessors require eight byte alignment. */
- unsigned long uc_regspace[128] __attribute__((__aligned__(8)));
-} ucontext_t;
-
-#else
-#include <sys/ucontext.h>
-#endif // __BIONIC_HAVE_UCONTEXT_T
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_ARM_LINUX_UCONTEXT_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/capability.h b/security/sandbox/chromium/sandbox/linux/system_headers/capability.h
deleted file mode 100644
index f91fcf78a..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/capability.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2015 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 SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_CAPABILITY_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_CAPABILITY_H_
-
-#include <stdint.h>
-
-// The following macros are taken from linux/capability.h.
-// We only support capability version 3, which was introduced in Linux 2.6.26.
-#ifndef _LINUX_CAPABILITY_VERSION_3
-#define _LINUX_CAPABILITY_VERSION_3 0x20080522
-#endif
-#ifndef _LINUX_CAPABILITY_U32S_3
-#define _LINUX_CAPABILITY_U32S_3 2
-#endif
-#ifndef CAP_TO_INDEX
-#define CAP_TO_INDEX(x) ((x) >> 5) // 1 << 5 == bits in __u32
-#endif
-#ifndef CAP_TO_MASK
-#define CAP_TO_MASK(x) (1 << ((x) & 31)) // mask for indexed __u32
-#endif
-#ifndef CAP_SYS_CHROOT
-#define CAP_SYS_CHROOT 18
-#endif
-#ifndef CAP_SYS_ADMIN
-#define CAP_SYS_ADMIN 21
-#endif
-
-struct cap_hdr {
- uint32_t version;
- int pid;
-};
-
-struct cap_data {
- uint32_t effective;
- uint32_t permitted;
- uint32_t inheritable;
-};
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_CAPABILITY_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/i386_linux_ucontext.h b/security/sandbox/chromium/sandbox/linux/system_headers/i386_linux_ucontext.h
deleted file mode 100644
index f4380339d..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/i386_linux_ucontext.h
+++ /dev/null
@@ -1,96 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_LINUX_SYSTEM_HEADERS_ANDROID_I386_UCONTEXT_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_ANDROID_I386_UCONTEXT_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-// We do something compatible with glibc. Hopefully, at some point Android will
-// provide that for us, and __BIONIC_HAVE_UCONTEXT_T should be defined.
-// This is mostly copied from breakpad (common/android/include/sys/ucontext.h),
-// except we do use sigset_t for uc_sigmask instead of a custom type.
-
-#if !defined(__BIONIC_HAVE_UCONTEXT_T)
-#if !defined(__native_client_nonsfi__)
-#include <asm/sigcontext.h>
-#else
-// In PNaCl toolchain, sigcontext is not defined. So here declare it.
-typedef struct sigaltstack {
- void* ss_sp;
- int ss_flags;
- size_t ss_size;
-} stack_t;
-#endif
-
-/* 80-bit floating-point register */
-struct _libc_fpreg {
- unsigned short significand[4];
- unsigned short exponent;
-};
-
-/* Simple floating-point state, see FNSTENV instruction */
-struct _libc_fpstate {
- unsigned long cw;
- unsigned long sw;
- unsigned long tag;
- unsigned long ipoff;
- unsigned long cssel;
- unsigned long dataoff;
- unsigned long datasel;
- struct _libc_fpreg _st[8];
- unsigned long status;
-};
-
-typedef uint32_t greg_t;
-
-typedef struct {
- uint32_t gregs[19];
- struct _libc_fpstate* fpregs;
- uint32_t oldmask;
- uint32_t cr2;
-} mcontext_t;
-
-enum {
- REG_GS = 0,
- REG_FS,
- REG_ES,
- REG_DS,
- REG_EDI,
- REG_ESI,
- REG_EBP,
- REG_ESP,
- REG_EBX,
- REG_EDX,
- REG_ECX,
- REG_EAX,
- REG_TRAPNO,
- REG_ERR,
- REG_EIP,
- REG_CS,
- REG_EFL,
- REG_UESP,
- REG_SS,
-};
-
-typedef struct ucontext {
- uint32_t uc_flags;
- struct ucontext* uc_link;
- stack_t uc_stack;
- mcontext_t uc_mcontext;
- // Android and PNaCl toolchain's sigset_t has only 32 bits, though Linux
- // ABI requires 64 bits.
- union {
- sigset_t uc_sigmask;
- uint32_t kernel_sigmask[2];
- };
- struct _libc_fpstate __fpregs_mem;
-} ucontext_t;
-
-#else
-#include <sys/ucontext.h>
-#endif // __BIONIC_HAVE_UCONTEXT_T
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_ANDROID_I386_UCONTEXT_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/linux_filter.h b/security/sandbox/chromium/sandbox/linux/system_headers/linux_filter.h
deleted file mode 100644
index b23b6eb0c..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/linux_filter.h
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright 2015 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 SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_FILTER_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_FILTER_H_
-
-#include <stdint.h>
-
-// The following structs and macros are taken from linux/filter.h,
-// as some toolchain does not expose them.
-struct sock_filter {
- uint16_t code;
- uint8_t jt;
- uint8_t jf;
- uint32_t k;
-};
-
-struct sock_fprog {
- uint16_t len;
- struct sock_filter *filter;
-};
-
-#ifndef BPF_CLASS
-#define BPF_CLASS(code) ((code) & 0x07)
-#endif
-
-#ifndef BPF_LD
-#define BPF_LD 0x00
-#endif
-
-#ifndef BPF_ALU
-#define BPF_ALU 0x04
-#endif
-
-#ifndef BPF_JMP
-#define BPF_JMP 0x05
-#endif
-
-#ifndef BPF_RET
-#define BPF_RET 0x06
-#endif
-
-#ifndef BPF_SIZE
-#define BPF_SIZE(code) ((code) & 0x18)
-#endif
-
-#ifndef BPF_W
-#define BPF_W 0x00
-#endif
-
-#ifndef BPF_MODE
-#define BPF_MODE(code) ((code) & 0xe0)
-#endif
-
-#ifndef BPF_ABS
-#define BPF_ABS 0x20
-#endif
-
-#ifndef BPF_OP
-#define BPF_OP(code) ((code) & 0xf0)
-#endif
-
-#ifndef BPF_ADD
-#define BPF_ADD 0x00
-#endif
-
-#ifndef BPF_SUB
-#define BPF_SUB 0x10
-#endif
-
-#ifndef BPF_MUL
-#define BPF_MUL 0x20
-#endif
-
-#ifndef BPF_DIV
-#define BPF_DIV 0x30
-#endif
-
-#ifndef BPF_OR
-#define BPF_OR 0x40
-#endif
-
-#ifndef BPF_AND
-#define BPF_AND 0x50
-#endif
-
-#ifndef BPF_LSH
-#define BPF_LSH 0x60
-#endif
-
-#ifndef BPF_RSH
-#define BPF_RSH 0x70
-#endif
-
-#ifndef BPF_NEG
-#define BPF_NEG 0x80
-#endif
-
-#ifndef BPF_MOD
-#define BPF_MOD 0x90
-#endif
-
-#ifndef BPF_XOR
-#define BPF_XOR 0xA0
-#endif
-
-#ifndef BPF_JA
-#define BPF_JA 0x00
-#endif
-
-#ifndef BPF_JEQ
-#define BPF_JEQ 0x10
-#endif
-
-#ifndef BPF_JGT
-#define BPF_JGT 0x20
-#endif
-
-#ifndef BPF_JGE
-#define BPF_JGE 0x30
-#endif
-
-#ifndef BPF_JSET
-#define BPF_JSET 0x40
-#endif
-
-#ifndef BPF_SRC
-#define BPF_SRC(code) ((code) & 0x08)
-#endif
-
-#ifndef BPF_K
-#define BPF_K 0x00
-#endif
-
-#ifndef BPF_MAXINSNS
-#define BPF_MAXINSNS 4096
-#endif
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_FILTER_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/linux_futex.h b/security/sandbox/chromium/sandbox/linux/system_headers/linux_futex.h
deleted file mode 100644
index 4e2840333..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/linux_futex.h
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_FUTEX_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_FUTEX_H_
-
-#if !defined(__native_client_nonsfi__)
-#include <linux/futex.h>
-#endif // !defined(__native_client_nonsfi__)
-
-#if !defined(FUTEX_WAIT)
-#define FUTEX_WAIT 0
-#endif
-
-#if !defined(FUTEX_WAKE)
-#define FUTEX_WAKE 1
-#endif
-
-#if !defined(FUTEX_FD)
-#define FUTEX_FD 2
-#endif
-
-#if !defined(FUTEX_REQUEUE)
-#define FUTEX_REQUEUE 3
-#endif
-
-#if !defined(FUTEX_CMP_REQUEUE)
-#define FUTEX_CMP_REQUEUE 4
-#endif
-
-#if !defined(FUTEX_WAKE_OP)
-#define FUTEX_WAKE_OP 5
-#endif
-
-#if !defined(FUTEX_LOCK_PI)
-#define FUTEX_LOCK_PI 6
-#endif
-
-#if !defined(FUTEX_UNLOCK_PI)
-#define FUTEX_UNLOCK_PI 7
-#endif
-
-#if !defined(FUTEX_TRYLOCK_PI)
-#define FUTEX_TRYLOCK_PI 8
-#endif
-
-#if !defined(FUTEX_WAIT_BITSET)
-#define FUTEX_WAIT_BITSET 9
-#endif
-
-#if !defined(FUTEX_WAKE_BITSET)
-#define FUTEX_WAKE_BITSET 10
-#endif
-
-#if !defined(FUTEX_WAIT_REQUEUE_PI)
-#define FUTEX_WAIT_REQUEUE_PI 11
-#endif
-
-#if !defined(FUTEX_CMP_REQUEUE_PI)
-#define FUTEX_CMP_REQUEUE_PI 12
-#endif
-
-#if !defined(FUTEX_PRIVATE_FLAG)
-#define FUTEX_PRIVATE_FLAG 128
-#endif
-
-#if !defined FUTEX_CLOCK_REALTIME
-#define FUTEX_CLOCK_REALTIME 256
-#endif
-
-#if !defined(FUTEX_CMD_MASK)
-#define FUTEX_CMD_MASK ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME)
-#endif
-
-#if !defined(FUTEX_CMP_REQUEUE_PI_PRIVATE)
-#define FUTEX_CMP_REQUEUE_PI_PRIVATE (FUTEX_CMP_REQUEUE_PI | FUTEX_PRIVATE_FLAG)
-#endif
-
-#if !defined(FUTEX_UNLOCK_PI_PRIVATE)
-#define FUTEX_UNLOCK_PI_PRIVATE (FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG)
-#endif
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_FUTEX_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/linux_seccomp.h b/security/sandbox/chromium/sandbox/linux/system_headers/linux_seccomp.h
deleted file mode 100644
index 3deb3d225..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/linux_seccomp.h
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright 2015 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 SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SECCOMP_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SECCOMP_H_
-
-// The Seccomp2 kernel ABI is not part of older versions of glibc.
-// As we can't break compilation with these versions of the library,
-// we explicitly define all missing symbols.
-// If we ever decide that we can now rely on system headers, the following
-// include files should be enabled:
-// #include <linux/audit.h>
-// #include <linux/seccomp.h>
-
-// For audit.h
-#ifndef EM_ARM
-#define EM_ARM 40
-#endif
-#ifndef EM_386
-#define EM_386 3
-#endif
-#ifndef EM_X86_64
-#define EM_X86_64 62
-#endif
-#ifndef EM_MIPS
-#define EM_MIPS 8
-#endif
-#ifndef EM_AARCH64
-#define EM_AARCH64 183
-#endif
-
-#ifndef __AUDIT_ARCH_64BIT
-#define __AUDIT_ARCH_64BIT 0x80000000
-#endif
-#ifndef __AUDIT_ARCH_LE
-#define __AUDIT_ARCH_LE 0x40000000
-#endif
-#ifndef AUDIT_ARCH_ARM
-#define AUDIT_ARCH_ARM (EM_ARM|__AUDIT_ARCH_LE)
-#endif
-#ifndef AUDIT_ARCH_I386
-#define AUDIT_ARCH_I386 (EM_386|__AUDIT_ARCH_LE)
-#endif
-#ifndef AUDIT_ARCH_X86_64
-#define AUDIT_ARCH_X86_64 (EM_X86_64|__AUDIT_ARCH_64BIT|__AUDIT_ARCH_LE)
-#endif
-#ifndef AUDIT_ARCH_MIPSEL
-#define AUDIT_ARCH_MIPSEL (EM_MIPS|__AUDIT_ARCH_LE)
-#endif
-#ifndef AUDIT_ARCH_AARCH64
-#define AUDIT_ARCH_AARCH64 (EM_AARCH64 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE)
-#endif
-
-// For prctl.h
-#ifndef PR_SET_SECCOMP
-#define PR_SET_SECCOMP 22
-#define PR_GET_SECCOMP 21
-#endif
-#ifndef PR_SET_NO_NEW_PRIVS
-#define PR_SET_NO_NEW_PRIVS 38
-#define PR_GET_NO_NEW_PRIVS 39
-#endif
-#ifndef IPC_64
-#define IPC_64 0x0100
-#endif
-
-// In order to build will older tool chains, we currently have to avoid
-// including <linux/seccomp.h>. Until that can be fixed (if ever). Rely on
-// our own definitions of the seccomp kernel ABI.
-#ifndef SECCOMP_MODE_FILTER
-#define SECCOMP_MODE_DISABLED 0
-#define SECCOMP_MODE_STRICT 1
-#define SECCOMP_MODE_FILTER 2 // User user-supplied filter
-#endif
-
-#ifndef SECCOMP_SET_MODE_STRICT
-#define SECCOMP_SET_MODE_STRICT 0
-#endif
-#ifndef SECCOMP_SET_MODE_FILTER
-#define SECCOMP_SET_MODE_FILTER 1
-#endif
-#ifndef SECCOMP_FILTER_FLAG_TSYNC
-#define SECCOMP_FILTER_FLAG_TSYNC 1
-#endif
-
-#ifndef SECCOMP_RET_KILL
-// Return values supported for BPF filter programs. Please note that the
-// "illegal" SECCOMP_RET_INVALID is not supported by the kernel, should only
-// ever be used internally, and would result in the kernel killing our process.
-#define SECCOMP_RET_KILL 0x00000000U // Kill the task immediately
-#define SECCOMP_RET_INVALID 0x00010000U // Illegal return value
-#define SECCOMP_RET_TRAP 0x00030000U // Disallow and force a SIGSYS
-#define SECCOMP_RET_ERRNO 0x00050000U // Returns an errno
-#define SECCOMP_RET_TRACE 0x7ff00000U // Pass to a tracer or disallow
-#define SECCOMP_RET_ALLOW 0x7fff0000U // Allow
-#define SECCOMP_RET_ACTION 0xffff0000U // Masks for the return value
-#define SECCOMP_RET_DATA 0x0000ffffU // sections
-#else
-#define SECCOMP_RET_INVALID 0x00010000U // Illegal return value
-#endif
-
-#ifndef SYS_SECCOMP
-#define SYS_SECCOMP 1
-#endif
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SECCOMP_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/linux_signal.h b/security/sandbox/chromium/sandbox/linux/system_headers/linux_signal.h
deleted file mode 100644
index fb9a47b8d..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/linux_signal.h
+++ /dev/null
@@ -1,146 +0,0 @@
-// Copyright 2015 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 SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SIGNAL_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SIGNAL_H_
-
-#include <stdint.h>
-
-// NOTE: On some toolchains, signal related ABI is incompatible with Linux's
-// (not undefined, but defined different values and in different memory
-// layouts). So, fill the gap here.
-#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || \
- defined(__aarch64__)
-
-#define LINUX_SIGHUP 1
-#define LINUX_SIGINT 2
-#define LINUX_SIGQUIT 3
-#define LINUX_SIGABRT 6
-#define LINUX_SIGBUS 7
-#define LINUX_SIGUSR1 10
-#define LINUX_SIGSEGV 11
-#define LINUX_SIGUSR2 12
-#define LINUX_SIGPIPE 13
-#define LINUX_SIGTERM 15
-#define LINUX_SIGCHLD 17
-#define LINUX_SIGSYS 31
-
-#define LINUX_SIG_BLOCK 0
-#define LINUX_SIG_UNBLOCK 1
-
-#define LINUX_SA_SIGINFO 4
-#define LINUX_SA_NODEFER 0x40000000
-#define LINUX_SA_RESTART 0x10000000
-
-#define LINUX_SIG_DFL 0
-
-#elif defined(__mips__)
-
-#define LINUX_SIGHUP 1
-#define LINUX_SIGINT 2
-#define LINUX_SIGQUIT 3
-#define LINUX_SIGABRT 6
-#define LINUX_SIGBUS 10
-#define LINUX_SIGSEGV 11
-#define LINUX_SIGSYS 12
-#define LINUX_SIGPIPE 13
-#define LINUX_SIGTERM 15
-#define LINUX_SIGUSR1 16
-#define LINUX_SIGUSR2 17
-#define LINUX_SIGCHLD 18
-
-#define LINUX_SIG_BLOCK 1
-#define LINUX_SIG_UNBLOCK 2
-
-#define LINUX_SA_SIGINFO 0x00000008
-#define LINUX_SA_NODEFER 0x40000000
-#define LINUX_SA_RESTART 0x10000000
-
-#define LINUX_SIG_DFL 0
-
-#else
-#error "Unsupported platform"
-#endif
-
-#if defined(__native_client_nonsfi__)
-#if !defined(__i386__) && !defined(__arm__)
-#error "Unsupported platform"
-#endif
-
-#include <signal.h>
-
-struct LinuxSigInfo {
- int si_signo;
- int si_errno;
- int si_code;
-
- // Extra data is followed by the |si_code|. The length depends on the
- // signal number.
- char _sifields[1];
-};
-
-#include "sandbox/linux/system_headers/linux_ucontext.h"
-
-#else // !defined(__native_client_nonsfi__)
-
-#include <signal.h>
-
-static_assert(LINUX_SIGHUP == SIGHUP, "LINUX_SIGHUP == SIGHUP");
-static_assert(LINUX_SIGINT == SIGINT, "LINUX_SIGINT == SIGINT");
-static_assert(LINUX_SIGQUIT == SIGQUIT, "LINUX_SIGQUIT == SIGQUIT");
-static_assert(LINUX_SIGABRT == SIGABRT, "LINUX_SIGABRT == SIGABRT");
-static_assert(LINUX_SIGBUS == SIGBUS, "LINUX_SIGBUS == SIGBUS");
-static_assert(LINUX_SIGUSR1 == SIGUSR1, "LINUX_SIGUSR1 == SIGUSR1");
-static_assert(LINUX_SIGSEGV == SIGSEGV, "LINUX_SIGSEGV == SIGSEGV");
-static_assert(LINUX_SIGUSR2 == SIGUSR2, "LINUX_SIGUSR2 == SIGUSR2");
-static_assert(LINUX_SIGPIPE == SIGPIPE, "LINUX_SIGPIPE == SIGPIPE");
-static_assert(LINUX_SIGTERM == SIGTERM, "LINUX_SIGTERM == SIGTERM");
-static_assert(LINUX_SIGCHLD == SIGCHLD, "LINUX_SIGCHLD == SIGCHLD");
-static_assert(LINUX_SIGSYS == SIGSYS, "LINUX_SIGSYS == SIGSYS");
-static_assert(LINUX_SIG_BLOCK == SIG_BLOCK, "LINUX_SIG_BLOCK == SIG_BLOCK");
-static_assert(LINUX_SIG_UNBLOCK == SIG_UNBLOCK,
- "LINUX_SIG_UNBLOCK == SIG_UNBLOCK");
-static_assert(LINUX_SA_SIGINFO == SA_SIGINFO, "LINUX_SA_SIGINFO == SA_SIGINFO");
-static_assert(LINUX_SA_NODEFER == SA_NODEFER, "LINUX_SA_NODEFER == SA_NODEFER");
-static_assert(LINUX_SA_RESTART == SA_RESTART, "LINUX_SA_RESTART == SA_RESTART");
-static_assert(LINUX_SIG_DFL == SIG_DFL, "LINUX_SIG_DFL == SIG_DFL");
-
-typedef siginfo_t LinuxSigInfo;
-
-#if defined(__ANDROID__)
-// Android's signal.h doesn't define ucontext etc.
-#include "sandbox/linux/system_headers/linux_ucontext.h"
-#endif // defined(__ANDROID__)
-
-#endif // !defined(__native_client_nonsfi__)
-
-// struct sigset_t is different size in PNaCl from the Linux's.
-#if defined(__mips__)
-#if !defined(_NSIG_WORDS)
-#define _NSIG_WORDS 4
-#endif
-struct LinuxSigSet {
- unsigned long sig[_NSIG_WORDS];
-};
-#else
-typedef uint64_t LinuxSigSet;
-#endif
-
-// struct sigaction is different in PNaCl from the Linux's.
-#if defined(__mips__)
-struct LinuxSigAction {
- unsigned int sa_flags;
- void (*kernel_handler)(int);
- LinuxSigSet sa_mask;
-};
-#else
-struct LinuxSigAction {
- void (*kernel_handler)(int);
- uint32_t sa_flags;
- void (*sa_restorer)(void);
- LinuxSigSet sa_mask;
-};
-#endif
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SIGNAL_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/linux_syscalls.h b/security/sandbox/chromium/sandbox/linux/system_headers/linux_syscalls.h
deleted file mode 100644
index 2b441e47e..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/linux_syscalls.h
+++ /dev/null
@@ -1,37 +0,0 @@
-// 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 header will be kept up to date so that we can compile system-call
-// policies even when system headers are old.
-// System call numbers are accessible through __NR_syscall_name.
-
-#ifndef SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SYSCALLS_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SYSCALLS_H_
-
-#if defined(__x86_64__)
-#include "sandbox/linux/system_headers/x86_64_linux_syscalls.h"
-#endif
-
-#if defined(__i386__)
-#include "sandbox/linux/system_headers/x86_32_linux_syscalls.h"
-#endif
-
-#if defined(__arm__) && defined(__ARM_EABI__)
-#include "sandbox/linux/system_headers/arm_linux_syscalls.h"
-#endif
-
-#if defined(__mips__) && (_MIPS_SIM == _ABIO32)
-#include "sandbox/linux/system_headers/mips_linux_syscalls.h"
-#endif
-
-#if defined(__mips__) && (_MIPS_SIM == _ABI64)
-#include "sandbox/linux/system_headers/mips64_linux_syscalls.h"
-#endif
-
-#if defined(__aarch64__)
-#include "sandbox/linux/system_headers/arm64_linux_syscalls.h"
-#endif
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_SYSCALLS_H_
-
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/linux_ucontext.h b/security/sandbox/chromium/sandbox/linux/system_headers/linux_ucontext.h
deleted file mode 100644
index ea4d8a6c1..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/linux_ucontext.h
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2013 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 SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_UCONTEXT_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_UCONTEXT_H_
-
-#if defined(__ANDROID__) || defined(__native_client_nonsfi__)
-
-#if defined(__arm__)
-#include "sandbox/linux/system_headers/arm_linux_ucontext.h"
-#elif defined(__i386__)
-#include "sandbox/linux/system_headers/i386_linux_ucontext.h"
-#elif defined(__x86_64__)
-#include "sandbox/linux/system_headers/x86_64_linux_ucontext.h"
-#elif defined(__mips__)
-#include "sandbox/linux/system_headers/mips_linux_ucontext.h"
-#elif defined(__aarch64__)
-#include "sandbox/linux/system_headers/arm64_linux_ucontext.h"
-#else
-#error "No support for your architecture in Android or PNaCl header"
-#endif
-
-#else // defined(__ANDROID__) || defined(__native_client_nonsfi__)
-#error "The header file included on non Android and non PNaCl."
-#endif // defined(__ANDROID__) || defined(__native_client_nonsfi__)
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_LINUX_UCONTEXT_H_
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/x86_32_linux_syscalls.h b/security/sandbox/chromium/sandbox/linux/system_headers/x86_32_linux_syscalls.h
deleted file mode 100644
index d9b7afc9b..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/x86_32_linux_syscalls.h
+++ /dev/null
@@ -1,1494 +0,0 @@
-// 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.
-
-// Generated from the Linux kernel's syscall_32.tbl.
-#ifndef SANDBOX_LINUX_SYSTEM_HEADERS_X86_32_LINUX_SYSCALLS_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_X86_32_LINUX_SYSCALLS_H_
-
-#if !defined(__i386__)
-#error "Including header on wrong architecture"
-#endif
-
-#if !defined(__NR_restart_syscall)
-#define __NR_restart_syscall 0
-#endif
-
-#if !defined(__NR_exit)
-#define __NR_exit 1
-#endif
-
-#if !defined(__NR_fork)
-#define __NR_fork 2
-#endif
-
-#if !defined(__NR_read)
-#define __NR_read 3
-#endif
-
-#if !defined(__NR_write)
-#define __NR_write 4
-#endif
-
-#if !defined(__NR_open)
-#define __NR_open 5
-#endif
-
-#if !defined(__NR_close)
-#define __NR_close 6
-#endif
-
-#if !defined(__NR_waitpid)
-#define __NR_waitpid 7
-#endif
-
-#if !defined(__NR_creat)
-#define __NR_creat 8
-#endif
-
-#if !defined(__NR_link)
-#define __NR_link 9
-#endif
-
-#if !defined(__NR_unlink)
-#define __NR_unlink 10
-#endif
-
-#if !defined(__NR_execve)
-#define __NR_execve 11
-#endif
-
-#if !defined(__NR_chdir)
-#define __NR_chdir 12
-#endif
-
-#if !defined(__NR_time)
-#define __NR_time 13
-#endif
-
-#if !defined(__NR_mknod)
-#define __NR_mknod 14
-#endif
-
-#if !defined(__NR_chmod)
-#define __NR_chmod 15
-#endif
-
-#if !defined(__NR_lchown)
-#define __NR_lchown 16
-#endif
-
-#if !defined(__NR_break)
-#define __NR_break 17
-#endif
-
-#if !defined(__NR_oldstat)
-#define __NR_oldstat 18
-#endif
-
-#if !defined(__NR_lseek)
-#define __NR_lseek 19
-#endif
-
-#if !defined(__NR_getpid)
-#define __NR_getpid 20
-#endif
-
-#if !defined(__NR_mount)
-#define __NR_mount 21
-#endif
-
-#if !defined(__NR_umount)
-#define __NR_umount 22
-#endif
-
-#if !defined(__NR_setuid)
-#define __NR_setuid 23
-#endif
-
-#if !defined(__NR_getuid)
-#define __NR_getuid 24
-#endif
-
-#if !defined(__NR_stime)
-#define __NR_stime 25
-#endif
-
-#if !defined(__NR_ptrace)
-#define __NR_ptrace 26
-#endif
-
-#if !defined(__NR_alarm)
-#define __NR_alarm 27
-#endif
-
-#if !defined(__NR_oldfstat)
-#define __NR_oldfstat 28
-#endif
-
-#if !defined(__NR_pause)
-#define __NR_pause 29
-#endif
-
-#if !defined(__NR_utime)
-#define __NR_utime 30
-#endif
-
-#if !defined(__NR_stty)
-#define __NR_stty 31
-#endif
-
-#if !defined(__NR_gtty)
-#define __NR_gtty 32
-#endif
-
-#if !defined(__NR_access)
-#define __NR_access 33
-#endif
-
-#if !defined(__NR_nice)
-#define __NR_nice 34
-#endif
-
-#if !defined(__NR_ftime)
-#define __NR_ftime 35
-#endif
-
-#if !defined(__NR_sync)
-#define __NR_sync 36
-#endif
-
-#if !defined(__NR_kill)
-#define __NR_kill 37
-#endif
-
-#if !defined(__NR_rename)
-#define __NR_rename 38
-#endif
-
-#if !defined(__NR_mkdir)
-#define __NR_mkdir 39
-#endif
-
-#if !defined(__NR_rmdir)
-#define __NR_rmdir 40
-#endif
-
-#if !defined(__NR_dup)
-#define __NR_dup 41
-#endif
-
-#if !defined(__NR_pipe)
-#define __NR_pipe 42
-#endif
-
-#if !defined(__NR_times)
-#define __NR_times 43
-#endif
-
-#if !defined(__NR_prof)
-#define __NR_prof 44
-#endif
-
-#if !defined(__NR_brk)
-#define __NR_brk 45
-#endif
-
-#if !defined(__NR_setgid)
-#define __NR_setgid 46
-#endif
-
-#if !defined(__NR_getgid)
-#define __NR_getgid 47
-#endif
-
-#if !defined(__NR_signal)
-#define __NR_signal 48
-#endif
-
-#if !defined(__NR_geteuid)
-#define __NR_geteuid 49
-#endif
-
-#if !defined(__NR_getegid)
-#define __NR_getegid 50
-#endif
-
-#if !defined(__NR_acct)
-#define __NR_acct 51
-#endif
-
-#if !defined(__NR_umount2)
-#define __NR_umount2 52
-#endif
-
-#if !defined(__NR_lock)
-#define __NR_lock 53
-#endif
-
-#if !defined(__NR_ioctl)
-#define __NR_ioctl 54
-#endif
-
-#if !defined(__NR_fcntl)
-#define __NR_fcntl 55
-#endif
-
-#if !defined(__NR_mpx)
-#define __NR_mpx 56
-#endif
-
-#if !defined(__NR_setpgid)
-#define __NR_setpgid 57
-#endif
-
-#if !defined(__NR_ulimit)
-#define __NR_ulimit 58
-#endif
-
-#if !defined(__NR_oldolduname)
-#define __NR_oldolduname 59
-#endif
-
-#if !defined(__NR_umask)
-#define __NR_umask 60
-#endif
-
-#if !defined(__NR_chroot)
-#define __NR_chroot 61
-#endif
-
-#if !defined(__NR_ustat)
-#define __NR_ustat 62
-#endif
-
-#if !defined(__NR_dup2)
-#define __NR_dup2 63
-#endif
-
-#if !defined(__NR_getppid)
-#define __NR_getppid 64
-#endif
-
-#if !defined(__NR_getpgrp)
-#define __NR_getpgrp 65
-#endif
-
-#if !defined(__NR_setsid)
-#define __NR_setsid 66
-#endif
-
-#if !defined(__NR_sigaction)
-#define __NR_sigaction 67
-#endif
-
-#if !defined(__NR_sgetmask)
-#define __NR_sgetmask 68
-#endif
-
-#if !defined(__NR_ssetmask)
-#define __NR_ssetmask 69
-#endif
-
-#if !defined(__NR_setreuid)
-#define __NR_setreuid 70
-#endif
-
-#if !defined(__NR_setregid)
-#define __NR_setregid 71
-#endif
-
-#if !defined(__NR_sigsuspend)
-#define __NR_sigsuspend 72
-#endif
-
-#if !defined(__NR_sigpending)
-#define __NR_sigpending 73
-#endif
-
-#if !defined(__NR_sethostname)
-#define __NR_sethostname 74
-#endif
-
-#if !defined(__NR_setrlimit)
-#define __NR_setrlimit 75
-#endif
-
-#if !defined(__NR_getrlimit)
-#define __NR_getrlimit 76
-#endif
-
-#if !defined(__NR_getrusage)
-#define __NR_getrusage 77
-#endif
-
-#if !defined(__NR_gettimeofday)
-#define __NR_gettimeofday 78
-#endif
-
-#if !defined(__NR_settimeofday)
-#define __NR_settimeofday 79
-#endif
-
-#if !defined(__NR_getgroups)
-#define __NR_getgroups 80
-#endif
-
-#if !defined(__NR_setgroups)
-#define __NR_setgroups 81
-#endif
-
-#if !defined(__NR_select)
-#define __NR_select 82
-#endif
-
-#if !defined(__NR_symlink)
-#define __NR_symlink 83
-#endif
-
-#if !defined(__NR_oldlstat)
-#define __NR_oldlstat 84
-#endif
-
-#if !defined(__NR_readlink)
-#define __NR_readlink 85
-#endif
-
-#if !defined(__NR_uselib)
-#define __NR_uselib 86
-#endif
-
-#if !defined(__NR_swapon)
-#define __NR_swapon 87
-#endif
-
-#if !defined(__NR_reboot)
-#define __NR_reboot 88
-#endif
-
-#if !defined(__NR_readdir)
-#define __NR_readdir 89
-#endif
-
-#if !defined(__NR_mmap)
-#define __NR_mmap 90
-#endif
-
-#if !defined(__NR_munmap)
-#define __NR_munmap 91
-#endif
-
-#if !defined(__NR_truncate)
-#define __NR_truncate 92
-#endif
-
-#if !defined(__NR_ftruncate)
-#define __NR_ftruncate 93
-#endif
-
-#if !defined(__NR_fchmod)
-#define __NR_fchmod 94
-#endif
-
-#if !defined(__NR_fchown)
-#define __NR_fchown 95
-#endif
-
-#if !defined(__NR_getpriority)
-#define __NR_getpriority 96
-#endif
-
-#if !defined(__NR_setpriority)
-#define __NR_setpriority 97
-#endif
-
-#if !defined(__NR_profil)
-#define __NR_profil 98
-#endif
-
-#if !defined(__NR_statfs)
-#define __NR_statfs 99
-#endif
-
-#if !defined(__NR_fstatfs)
-#define __NR_fstatfs 100
-#endif
-
-#if !defined(__NR_ioperm)
-#define __NR_ioperm 101
-#endif
-
-#if !defined(__NR_socketcall)
-#define __NR_socketcall 102
-#endif
-
-#if !defined(__NR_syslog)
-#define __NR_syslog 103
-#endif
-
-#if !defined(__NR_setitimer)
-#define __NR_setitimer 104
-#endif
-
-#if !defined(__NR_getitimer)
-#define __NR_getitimer 105
-#endif
-
-#if !defined(__NR_stat)
-#define __NR_stat 106
-#endif
-
-#if !defined(__NR_lstat)
-#define __NR_lstat 107
-#endif
-
-#if !defined(__NR_fstat)
-#define __NR_fstat 108
-#endif
-
-#if !defined(__NR_olduname)
-#define __NR_olduname 109
-#endif
-
-#if !defined(__NR_iopl)
-#define __NR_iopl 110
-#endif
-
-#if !defined(__NR_vhangup)
-#define __NR_vhangup 111
-#endif
-
-#if !defined(__NR_idle)
-#define __NR_idle 112
-#endif
-
-#if !defined(__NR_vm86old)
-#define __NR_vm86old 113
-#endif
-
-#if !defined(__NR_wait4)
-#define __NR_wait4 114
-#endif
-
-#if !defined(__NR_swapoff)
-#define __NR_swapoff 115
-#endif
-
-#if !defined(__NR_sysinfo)
-#define __NR_sysinfo 116
-#endif
-
-#if !defined(__NR_ipc)
-#define __NR_ipc 117
-#endif
-
-#if !defined(__NR_fsync)
-#define __NR_fsync 118
-#endif
-
-#if !defined(__NR_sigreturn)
-#define __NR_sigreturn 119
-#endif
-
-#if !defined(__NR_clone)
-#define __NR_clone 120
-#endif
-
-#if !defined(__NR_setdomainname)
-#define __NR_setdomainname 121
-#endif
-
-#if !defined(__NR_uname)
-#define __NR_uname 122
-#endif
-
-#if !defined(__NR_modify_ldt)
-#define __NR_modify_ldt 123
-#endif
-
-#if !defined(__NR_adjtimex)
-#define __NR_adjtimex 124
-#endif
-
-#if !defined(__NR_mprotect)
-#define __NR_mprotect 125
-#endif
-
-#if !defined(__NR_sigprocmask)
-#define __NR_sigprocmask 126
-#endif
-
-#if !defined(__NR_create_module)
-#define __NR_create_module 127
-#endif
-
-#if !defined(__NR_init_module)
-#define __NR_init_module 128
-#endif
-
-#if !defined(__NR_delete_module)
-#define __NR_delete_module 129
-#endif
-
-#if !defined(__NR_get_kernel_syms)
-#define __NR_get_kernel_syms 130
-#endif
-
-#if !defined(__NR_quotactl)
-#define __NR_quotactl 131
-#endif
-
-#if !defined(__NR_getpgid)
-#define __NR_getpgid 132
-#endif
-
-#if !defined(__NR_fchdir)
-#define __NR_fchdir 133
-#endif
-
-#if !defined(__NR_bdflush)
-#define __NR_bdflush 134
-#endif
-
-#if !defined(__NR_sysfs)
-#define __NR_sysfs 135
-#endif
-
-#if !defined(__NR_personality)
-#define __NR_personality 136
-#endif
-
-#if !defined(__NR_afs_syscall)
-#define __NR_afs_syscall 137
-#endif
-
-#if !defined(__NR_setfsuid)
-#define __NR_setfsuid 138
-#endif
-
-#if !defined(__NR_setfsgid)
-#define __NR_setfsgid 139
-#endif
-
-#if !defined(__NR__llseek)
-#define __NR__llseek 140
-#endif
-
-#if !defined(__NR_getdents)
-#define __NR_getdents 141
-#endif
-
-#if !defined(__NR__newselect)
-#define __NR__newselect 142
-#endif
-
-#if !defined(__NR_flock)
-#define __NR_flock 143
-#endif
-
-#if !defined(__NR_msync)
-#define __NR_msync 144
-#endif
-
-#if !defined(__NR_readv)
-#define __NR_readv 145
-#endif
-
-#if !defined(__NR_writev)
-#define __NR_writev 146
-#endif
-
-#if !defined(__NR_getsid)
-#define __NR_getsid 147
-#endif
-
-#if !defined(__NR_fdatasync)
-#define __NR_fdatasync 148
-#endif
-
-#if !defined(__NR__sysctl)
-#define __NR__sysctl 149
-#endif
-
-#if !defined(__NR_mlock)
-#define __NR_mlock 150
-#endif
-
-#if !defined(__NR_munlock)
-#define __NR_munlock 151
-#endif
-
-#if !defined(__NR_mlockall)
-#define __NR_mlockall 152
-#endif
-
-#if !defined(__NR_munlockall)
-#define __NR_munlockall 153
-#endif
-
-#if !defined(__NR_sched_setparam)
-#define __NR_sched_setparam 154
-#endif
-
-#if !defined(__NR_sched_getparam)
-#define __NR_sched_getparam 155
-#endif
-
-#if !defined(__NR_sched_setscheduler)
-#define __NR_sched_setscheduler 156
-#endif
-
-#if !defined(__NR_sched_getscheduler)
-#define __NR_sched_getscheduler 157
-#endif
-
-#if !defined(__NR_sched_yield)
-#define __NR_sched_yield 158
-#endif
-
-#if !defined(__NR_sched_get_priority_max)
-#define __NR_sched_get_priority_max 159
-#endif
-
-#if !defined(__NR_sched_get_priority_min)
-#define __NR_sched_get_priority_min 160
-#endif
-
-#if !defined(__NR_sched_rr_get_interval)
-#define __NR_sched_rr_get_interval 161
-#endif
-
-#if !defined(__NR_nanosleep)
-#define __NR_nanosleep 162
-#endif
-
-#if !defined(__NR_mremap)
-#define __NR_mremap 163
-#endif
-
-#if !defined(__NR_setresuid)
-#define __NR_setresuid 164
-#endif
-
-#if !defined(__NR_getresuid)
-#define __NR_getresuid 165
-#endif
-
-#if !defined(__NR_vm86)
-#define __NR_vm86 166
-#endif
-
-#if !defined(__NR_query_module)
-#define __NR_query_module 167
-#endif
-
-#if !defined(__NR_poll)
-#define __NR_poll 168
-#endif
-
-#if !defined(__NR_nfsservctl)
-#define __NR_nfsservctl 169
-#endif
-
-#if !defined(__NR_setresgid)
-#define __NR_setresgid 170
-#endif
-
-#if !defined(__NR_getresgid)
-#define __NR_getresgid 171
-#endif
-
-#if !defined(__NR_prctl)
-#define __NR_prctl 172
-#endif
-
-#if !defined(__NR_rt_sigreturn)
-#define __NR_rt_sigreturn 173
-#endif
-
-#if !defined(__NR_rt_sigaction)
-#define __NR_rt_sigaction 174
-#endif
-
-#if !defined(__NR_rt_sigprocmask)
-#define __NR_rt_sigprocmask 175
-#endif
-
-#if !defined(__NR_rt_sigpending)
-#define __NR_rt_sigpending 176
-#endif
-
-#if !defined(__NR_rt_sigtimedwait)
-#define __NR_rt_sigtimedwait 177
-#endif
-
-#if !defined(__NR_rt_sigqueueinfo)
-#define __NR_rt_sigqueueinfo 178
-#endif
-
-#if !defined(__NR_rt_sigsuspend)
-#define __NR_rt_sigsuspend 179
-#endif
-
-#if !defined(__NR_pread64)
-#define __NR_pread64 180
-#endif
-
-#if !defined(__NR_pwrite64)
-#define __NR_pwrite64 181
-#endif
-
-#if !defined(__NR_chown)
-#define __NR_chown 182
-#endif
-
-#if !defined(__NR_getcwd)
-#define __NR_getcwd 183
-#endif
-
-#if !defined(__NR_capget)
-#define __NR_capget 184
-#endif
-
-#if !defined(__NR_capset)
-#define __NR_capset 185
-#endif
-
-#if !defined(__NR_sigaltstack)
-#define __NR_sigaltstack 186
-#endif
-
-#if !defined(__NR_sendfile)
-#define __NR_sendfile 187
-#endif
-
-#if !defined(__NR_getpmsg)
-#define __NR_getpmsg 188
-#endif
-
-#if !defined(__NR_putpmsg)
-#define __NR_putpmsg 189
-#endif
-
-#if !defined(__NR_vfork)
-#define __NR_vfork 190
-#endif
-
-#if !defined(__NR_ugetrlimit)
-#define __NR_ugetrlimit 191
-#endif
-
-#if !defined(__NR_mmap2)
-#define __NR_mmap2 192
-#endif
-
-#if !defined(__NR_truncate64)
-#define __NR_truncate64 193
-#endif
-
-#if !defined(__NR_ftruncate64)
-#define __NR_ftruncate64 194
-#endif
-
-#if !defined(__NR_stat64)
-#define __NR_stat64 195
-#endif
-
-#if !defined(__NR_lstat64)
-#define __NR_lstat64 196
-#endif
-
-#if !defined(__NR_fstat64)
-#define __NR_fstat64 197
-#endif
-
-#if !defined(__NR_lchown32)
-#define __NR_lchown32 198
-#endif
-
-#if !defined(__NR_getuid32)
-#define __NR_getuid32 199
-#endif
-
-#if !defined(__NR_getgid32)
-#define __NR_getgid32 200
-#endif
-
-#if !defined(__NR_geteuid32)
-#define __NR_geteuid32 201
-#endif
-
-#if !defined(__NR_getegid32)
-#define __NR_getegid32 202
-#endif
-
-#if !defined(__NR_setreuid32)
-#define __NR_setreuid32 203
-#endif
-
-#if !defined(__NR_setregid32)
-#define __NR_setregid32 204
-#endif
-
-#if !defined(__NR_getgroups32)
-#define __NR_getgroups32 205
-#endif
-
-#if !defined(__NR_setgroups32)
-#define __NR_setgroups32 206
-#endif
-
-#if !defined(__NR_fchown32)
-#define __NR_fchown32 207
-#endif
-
-#if !defined(__NR_setresuid32)
-#define __NR_setresuid32 208
-#endif
-
-#if !defined(__NR_getresuid32)
-#define __NR_getresuid32 209
-#endif
-
-#if !defined(__NR_setresgid32)
-#define __NR_setresgid32 210
-#endif
-
-#if !defined(__NR_getresgid32)
-#define __NR_getresgid32 211
-#endif
-
-#if !defined(__NR_chown32)
-#define __NR_chown32 212
-#endif
-
-#if !defined(__NR_setuid32)
-#define __NR_setuid32 213
-#endif
-
-#if !defined(__NR_setgid32)
-#define __NR_setgid32 214
-#endif
-
-#if !defined(__NR_setfsuid32)
-#define __NR_setfsuid32 215
-#endif
-
-#if !defined(__NR_setfsgid32)
-#define __NR_setfsgid32 216
-#endif
-
-#if !defined(__NR_pivot_root)
-#define __NR_pivot_root 217
-#endif
-
-#if !defined(__NR_mincore)
-#define __NR_mincore 218
-#endif
-
-#if !defined(__NR_madvise)
-#define __NR_madvise 219
-#endif
-
-#if !defined(__NR_getdents64)
-#define __NR_getdents64 220
-#endif
-
-#if !defined(__NR_fcntl64)
-#define __NR_fcntl64 221
-#endif
-
-#if !defined(__NR_gettid)
-#define __NR_gettid 224
-#endif
-
-#if !defined(__NR_readahead)
-#define __NR_readahead 225
-#endif
-
-#if !defined(__NR_setxattr)
-#define __NR_setxattr 226
-#endif
-
-#if !defined(__NR_lsetxattr)
-#define __NR_lsetxattr 227
-#endif
-
-#if !defined(__NR_fsetxattr)
-#define __NR_fsetxattr 228
-#endif
-
-#if !defined(__NR_getxattr)
-#define __NR_getxattr 229
-#endif
-
-#if !defined(__NR_lgetxattr)
-#define __NR_lgetxattr 230
-#endif
-
-#if !defined(__NR_fgetxattr)
-#define __NR_fgetxattr 231
-#endif
-
-#if !defined(__NR_listxattr)
-#define __NR_listxattr 232
-#endif
-
-#if !defined(__NR_llistxattr)
-#define __NR_llistxattr 233
-#endif
-
-#if !defined(__NR_flistxattr)
-#define __NR_flistxattr 234
-#endif
-
-#if !defined(__NR_removexattr)
-#define __NR_removexattr 235
-#endif
-
-#if !defined(__NR_lremovexattr)
-#define __NR_lremovexattr 236
-#endif
-
-#if !defined(__NR_fremovexattr)
-#define __NR_fremovexattr 237
-#endif
-
-#if !defined(__NR_tkill)
-#define __NR_tkill 238
-#endif
-
-#if !defined(__NR_sendfile64)
-#define __NR_sendfile64 239
-#endif
-
-#if !defined(__NR_futex)
-#define __NR_futex 240
-#endif
-
-#if !defined(__NR_sched_setaffinity)
-#define __NR_sched_setaffinity 241
-#endif
-
-#if !defined(__NR_sched_getaffinity)
-#define __NR_sched_getaffinity 242
-#endif
-
-#if !defined(__NR_set_thread_area)
-#define __NR_set_thread_area 243
-#endif
-
-#if !defined(__NR_get_thread_area)
-#define __NR_get_thread_area 244
-#endif
-
-#if !defined(__NR_io_setup)
-#define __NR_io_setup 245
-#endif
-
-#if !defined(__NR_io_destroy)
-#define __NR_io_destroy 246
-#endif
-
-#if !defined(__NR_io_getevents)
-#define __NR_io_getevents 247
-#endif
-
-#if !defined(__NR_io_submit)
-#define __NR_io_submit 248
-#endif
-
-#if !defined(__NR_io_cancel)
-#define __NR_io_cancel 249
-#endif
-
-#if !defined(__NR_fadvise64)
-#define __NR_fadvise64 250
-#endif
-
-#if !defined(__NR_exit_group)
-#define __NR_exit_group 252
-#endif
-
-#if !defined(__NR_lookup_dcookie)
-#define __NR_lookup_dcookie 253
-#endif
-
-#if !defined(__NR_epoll_create)
-#define __NR_epoll_create 254
-#endif
-
-#if !defined(__NR_epoll_ctl)
-#define __NR_epoll_ctl 255
-#endif
-
-#if !defined(__NR_epoll_wait)
-#define __NR_epoll_wait 256
-#endif
-
-#if !defined(__NR_remap_file_pages)
-#define __NR_remap_file_pages 257
-#endif
-
-#if !defined(__NR_set_tid_address)
-#define __NR_set_tid_address 258
-#endif
-
-#if !defined(__NR_timer_create)
-#define __NR_timer_create 259
-#endif
-
-#if !defined(__NR_timer_settime)
-#define __NR_timer_settime 260
-#endif
-
-#if !defined(__NR_timer_gettime)
-#define __NR_timer_gettime 261
-#endif
-
-#if !defined(__NR_timer_getoverrun)
-#define __NR_timer_getoverrun 262
-#endif
-
-#if !defined(__NR_timer_delete)
-#define __NR_timer_delete 263
-#endif
-
-#if !defined(__NR_clock_settime)
-#define __NR_clock_settime 264
-#endif
-
-#if !defined(__NR_clock_gettime)
-#define __NR_clock_gettime 265
-#endif
-
-#if !defined(__NR_clock_getres)
-#define __NR_clock_getres 266
-#endif
-
-#if !defined(__NR_clock_nanosleep)
-#define __NR_clock_nanosleep 267
-#endif
-
-#if !defined(__NR_statfs64)
-#define __NR_statfs64 268
-#endif
-
-#if !defined(__NR_fstatfs64)
-#define __NR_fstatfs64 269
-#endif
-
-#if !defined(__NR_tgkill)
-#define __NR_tgkill 270
-#endif
-
-#if !defined(__NR_utimes)
-#define __NR_utimes 271
-#endif
-
-#if !defined(__NR_fadvise64_64)
-#define __NR_fadvise64_64 272
-#endif
-
-#if !defined(__NR_vserver)
-#define __NR_vserver 273
-#endif
-
-#if !defined(__NR_mbind)
-#define __NR_mbind 274
-#endif
-
-#if !defined(__NR_get_mempolicy)
-#define __NR_get_mempolicy 275
-#endif
-
-#if !defined(__NR_set_mempolicy)
-#define __NR_set_mempolicy 276
-#endif
-
-#if !defined(__NR_mq_open)
-#define __NR_mq_open 277
-#endif
-
-#if !defined(__NR_mq_unlink)
-#define __NR_mq_unlink 278
-#endif
-
-#if !defined(__NR_mq_timedsend)
-#define __NR_mq_timedsend 279
-#endif
-
-#if !defined(__NR_mq_timedreceive)
-#define __NR_mq_timedreceive 280
-#endif
-
-#if !defined(__NR_mq_notify)
-#define __NR_mq_notify 281
-#endif
-
-#if !defined(__NR_mq_getsetattr)
-#define __NR_mq_getsetattr 282
-#endif
-
-#if !defined(__NR_kexec_load)
-#define __NR_kexec_load 283
-#endif
-
-#if !defined(__NR_waitid)
-#define __NR_waitid 284
-#endif
-
-#if !defined(__NR_add_key)
-#define __NR_add_key 286
-#endif
-
-#if !defined(__NR_request_key)
-#define __NR_request_key 287
-#endif
-
-#if !defined(__NR_keyctl)
-#define __NR_keyctl 288
-#endif
-
-#if !defined(__NR_ioprio_set)
-#define __NR_ioprio_set 289
-#endif
-
-#if !defined(__NR_ioprio_get)
-#define __NR_ioprio_get 290
-#endif
-
-#if !defined(__NR_inotify_init)
-#define __NR_inotify_init 291
-#endif
-
-#if !defined(__NR_inotify_add_watch)
-#define __NR_inotify_add_watch 292
-#endif
-
-#if !defined(__NR_inotify_rm_watch)
-#define __NR_inotify_rm_watch 293
-#endif
-
-#if !defined(__NR_migrate_pages)
-#define __NR_migrate_pages 294
-#endif
-
-#if !defined(__NR_openat)
-#define __NR_openat 295
-#endif
-
-#if !defined(__NR_mkdirat)
-#define __NR_mkdirat 296
-#endif
-
-#if !defined(__NR_mknodat)
-#define __NR_mknodat 297
-#endif
-
-#if !defined(__NR_fchownat)
-#define __NR_fchownat 298
-#endif
-
-#if !defined(__NR_futimesat)
-#define __NR_futimesat 299
-#endif
-
-#if !defined(__NR_fstatat64)
-#define __NR_fstatat64 300
-#endif
-
-#if !defined(__NR_unlinkat)
-#define __NR_unlinkat 301
-#endif
-
-#if !defined(__NR_renameat)
-#define __NR_renameat 302
-#endif
-
-#if !defined(__NR_linkat)
-#define __NR_linkat 303
-#endif
-
-#if !defined(__NR_symlinkat)
-#define __NR_symlinkat 304
-#endif
-
-#if !defined(__NR_readlinkat)
-#define __NR_readlinkat 305
-#endif
-
-#if !defined(__NR_fchmodat)
-#define __NR_fchmodat 306
-#endif
-
-#if !defined(__NR_faccessat)
-#define __NR_faccessat 307
-#endif
-
-#if !defined(__NR_pselect6)
-#define __NR_pselect6 308
-#endif
-
-#if !defined(__NR_ppoll)
-#define __NR_ppoll 309
-#endif
-
-#if !defined(__NR_unshare)
-#define __NR_unshare 310
-#endif
-
-#if !defined(__NR_set_robust_list)
-#define __NR_set_robust_list 311
-#endif
-
-#if !defined(__NR_get_robust_list)
-#define __NR_get_robust_list 312
-#endif
-
-#if !defined(__NR_splice)
-#define __NR_splice 313
-#endif
-
-#if !defined(__NR_sync_file_range)
-#define __NR_sync_file_range 314
-#endif
-
-#if !defined(__NR_tee)
-#define __NR_tee 315
-#endif
-
-#if !defined(__NR_vmsplice)
-#define __NR_vmsplice 316
-#endif
-
-#if !defined(__NR_move_pages)
-#define __NR_move_pages 317
-#endif
-
-#if !defined(__NR_getcpu)
-#define __NR_getcpu 318
-#endif
-
-#if !defined(__NR_epoll_pwait)
-#define __NR_epoll_pwait 319
-#endif
-
-#if !defined(__NR_utimensat)
-#define __NR_utimensat 320
-#endif
-
-#if !defined(__NR_signalfd)
-#define __NR_signalfd 321
-#endif
-
-#if !defined(__NR_timerfd_create)
-#define __NR_timerfd_create 322
-#endif
-
-#if !defined(__NR_eventfd)
-#define __NR_eventfd 323
-#endif
-
-#if !defined(__NR_fallocate)
-#define __NR_fallocate 324
-#endif
-
-#if !defined(__NR_timerfd_settime)
-#define __NR_timerfd_settime 325
-#endif
-
-#if !defined(__NR_timerfd_gettime)
-#define __NR_timerfd_gettime 326
-#endif
-
-#if !defined(__NR_signalfd4)
-#define __NR_signalfd4 327
-#endif
-
-#if !defined(__NR_eventfd2)
-#define __NR_eventfd2 328
-#endif
-
-#if !defined(__NR_epoll_create1)
-#define __NR_epoll_create1 329
-#endif
-
-#if !defined(__NR_dup3)
-#define __NR_dup3 330
-#endif
-
-#if !defined(__NR_pipe2)
-#define __NR_pipe2 331
-#endif
-
-#if !defined(__NR_inotify_init1)
-#define __NR_inotify_init1 332
-#endif
-
-#if !defined(__NR_preadv)
-#define __NR_preadv 333
-#endif
-
-#if !defined(__NR_pwritev)
-#define __NR_pwritev 334
-#endif
-
-#if !defined(__NR_rt_tgsigqueueinfo)
-#define __NR_rt_tgsigqueueinfo 335
-#endif
-
-#if !defined(__NR_perf_event_open)
-#define __NR_perf_event_open 336
-#endif
-
-#if !defined(__NR_recvmmsg)
-#define __NR_recvmmsg 337
-#endif
-
-#if !defined(__NR_fanotify_init)
-#define __NR_fanotify_init 338
-#endif
-
-#if !defined(__NR_fanotify_mark)
-#define __NR_fanotify_mark 339
-#endif
-
-#if !defined(__NR_prlimit64)
-#define __NR_prlimit64 340
-#endif
-
-#if !defined(__NR_name_to_handle_at)
-#define __NR_name_to_handle_at 341
-#endif
-
-#if !defined(__NR_open_by_handle_at)
-#define __NR_open_by_handle_at 342
-#endif
-
-#if !defined(__NR_clock_adjtime)
-#define __NR_clock_adjtime 343
-#endif
-
-#if !defined(__NR_syncfs)
-#define __NR_syncfs 344
-#endif
-
-#if !defined(__NR_sendmmsg)
-#define __NR_sendmmsg 345
-#endif
-
-#if !defined(__NR_setns)
-#define __NR_setns 346
-#endif
-
-#if !defined(__NR_process_vm_readv)
-#define __NR_process_vm_readv 347
-#endif
-
-#if !defined(__NR_process_vm_writev)
-#define __NR_process_vm_writev 348
-#endif
-
-#if !defined(__NR_kcmp)
-#define __NR_kcmp 349
-#endif
-
-#if !defined(__NR_finit_module)
-#define __NR_finit_module 350
-#endif
-
-#if !defined(__NR_sched_setattr)
-#define __NR_sched_setattr 351
-#endif
-
-#if !defined(__NR_sched_getattr)
-#define __NR_sched_getattr 352
-#endif
-
-#if !defined(__NR_renameat2)
-#define __NR_renameat2 353
-#endif
-
-#if !defined(__NR_seccomp)
-#define __NR_seccomp 354
-#endif
-
-#if !defined(__NR_getrandom)
-#define __NR_getrandom 355
-#endif
-
-#if !defined(__NR_memfd_create)
-#define __NR_memfd_create 356
-#endif
-
-#if !defined(__NR_bpf)
-#define __NR_bpf 357
-#endif
-
-#if !defined(__NR_execveat)
-#define __NR_execveat 358
-#endif
-
-#if !defined(__NR_socket)
-#define __NR_socket 359
-#endif
-
-#if !defined(__NR_socketpair)
-#define __NR_socketpair 360
-#endif
-
-#if !defined(__NR_bind)
-#define __NR_bind 361
-#endif
-
-#if !defined(__NR_connect)
-#define __NR_connect 362
-#endif
-
-#if !defined(__NR_listen)
-#define __NR_listen 363
-#endif
-
-#if !defined(__NR_accept4)
-#define __NR_accept4 364
-#endif
-
-#if !defined(__NR_getsockopt)
-#define __NR_getsockopt 365
-#endif
-
-#if !defined(__NR_setsockopt)
-#define __NR_setsockopt 366
-#endif
-
-#if !defined(__NR_getsockname)
-#define __NR_getsockname 367
-#endif
-
-#if !defined(__NR_getpeername)
-#define __NR_getpeername 368
-#endif
-
-#if !defined(__NR_sendto)
-#define __NR_sendto 369
-#endif
-
-#if !defined(__NR_sendmsg)
-#define __NR_sendmsg 370
-#endif
-
-#if !defined(__NR_recvfrom)
-#define __NR_recvfrom 371
-#endif
-
-#if !defined(__NR_recvmsg)
-#define __NR_recvmsg 372
-#endif
-
-#if !defined(__NR_shutdown)
-#define __NR_shutdown 373
-#endif
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_X86_32_LINUX_SYSCALLS_H_
-
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_syscalls.h b/security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_syscalls.h
deleted file mode 100644
index 349504aee..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_syscalls.h
+++ /dev/null
@@ -1,1294 +0,0 @@
-// 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.
-
-// Generated from the Linux kernel's syscall_64.tbl.
-#ifndef SANDBOX_LINUX_SYSTEM_HEADERS_X86_64_LINUX_SYSCALLS_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_X86_64_LINUX_SYSCALLS_H_
-
-#if !defined(__x86_64__)
-#error "Including header on wrong architecture"
-#endif
-
-#if !defined(__NR_read)
-#define __NR_read 0
-#endif
-
-#if !defined(__NR_write)
-#define __NR_write 1
-#endif
-
-#if !defined(__NR_open)
-#define __NR_open 2
-#endif
-
-#if !defined(__NR_close)
-#define __NR_close 3
-#endif
-
-#if !defined(__NR_stat)
-#define __NR_stat 4
-#endif
-
-#if !defined(__NR_fstat)
-#define __NR_fstat 5
-#endif
-
-#if !defined(__NR_lstat)
-#define __NR_lstat 6
-#endif
-
-#if !defined(__NR_poll)
-#define __NR_poll 7
-#endif
-
-#if !defined(__NR_lseek)
-#define __NR_lseek 8
-#endif
-
-#if !defined(__NR_mmap)
-#define __NR_mmap 9
-#endif
-
-#if !defined(__NR_mprotect)
-#define __NR_mprotect 10
-#endif
-
-#if !defined(__NR_munmap)
-#define __NR_munmap 11
-#endif
-
-#if !defined(__NR_brk)
-#define __NR_brk 12
-#endif
-
-#if !defined(__NR_rt_sigaction)
-#define __NR_rt_sigaction 13
-#endif
-
-#if !defined(__NR_rt_sigprocmask)
-#define __NR_rt_sigprocmask 14
-#endif
-
-#if !defined(__NR_rt_sigreturn)
-#define __NR_rt_sigreturn 15
-#endif
-
-#if !defined(__NR_ioctl)
-#define __NR_ioctl 16
-#endif
-
-#if !defined(__NR_pread64)
-#define __NR_pread64 17
-#endif
-
-#if !defined(__NR_pwrite64)
-#define __NR_pwrite64 18
-#endif
-
-#if !defined(__NR_readv)
-#define __NR_readv 19
-#endif
-
-#if !defined(__NR_writev)
-#define __NR_writev 20
-#endif
-
-#if !defined(__NR_access)
-#define __NR_access 21
-#endif
-
-#if !defined(__NR_pipe)
-#define __NR_pipe 22
-#endif
-
-#if !defined(__NR_select)
-#define __NR_select 23
-#endif
-
-#if !defined(__NR_sched_yield)
-#define __NR_sched_yield 24
-#endif
-
-#if !defined(__NR_mremap)
-#define __NR_mremap 25
-#endif
-
-#if !defined(__NR_msync)
-#define __NR_msync 26
-#endif
-
-#if !defined(__NR_mincore)
-#define __NR_mincore 27
-#endif
-
-#if !defined(__NR_madvise)
-#define __NR_madvise 28
-#endif
-
-#if !defined(__NR_shmget)
-#define __NR_shmget 29
-#endif
-
-#if !defined(__NR_shmat)
-#define __NR_shmat 30
-#endif
-
-#if !defined(__NR_shmctl)
-#define __NR_shmctl 31
-#endif
-
-#if !defined(__NR_dup)
-#define __NR_dup 32
-#endif
-
-#if !defined(__NR_dup2)
-#define __NR_dup2 33
-#endif
-
-#if !defined(__NR_pause)
-#define __NR_pause 34
-#endif
-
-#if !defined(__NR_nanosleep)
-#define __NR_nanosleep 35
-#endif
-
-#if !defined(__NR_getitimer)
-#define __NR_getitimer 36
-#endif
-
-#if !defined(__NR_alarm)
-#define __NR_alarm 37
-#endif
-
-#if !defined(__NR_setitimer)
-#define __NR_setitimer 38
-#endif
-
-#if !defined(__NR_getpid)
-#define __NR_getpid 39
-#endif
-
-#if !defined(__NR_sendfile)
-#define __NR_sendfile 40
-#endif
-
-#if !defined(__NR_socket)
-#define __NR_socket 41
-#endif
-
-#if !defined(__NR_connect)
-#define __NR_connect 42
-#endif
-
-#if !defined(__NR_accept)
-#define __NR_accept 43
-#endif
-
-#if !defined(__NR_sendto)
-#define __NR_sendto 44
-#endif
-
-#if !defined(__NR_recvfrom)
-#define __NR_recvfrom 45
-#endif
-
-#if !defined(__NR_sendmsg)
-#define __NR_sendmsg 46
-#endif
-
-#if !defined(__NR_recvmsg)
-#define __NR_recvmsg 47
-#endif
-
-#if !defined(__NR_shutdown)
-#define __NR_shutdown 48
-#endif
-
-#if !defined(__NR_bind)
-#define __NR_bind 49
-#endif
-
-#if !defined(__NR_listen)
-#define __NR_listen 50
-#endif
-
-#if !defined(__NR_getsockname)
-#define __NR_getsockname 51
-#endif
-
-#if !defined(__NR_getpeername)
-#define __NR_getpeername 52
-#endif
-
-#if !defined(__NR_socketpair)
-#define __NR_socketpair 53
-#endif
-
-#if !defined(__NR_setsockopt)
-#define __NR_setsockopt 54
-#endif
-
-#if !defined(__NR_getsockopt)
-#define __NR_getsockopt 55
-#endif
-
-#if !defined(__NR_clone)
-#define __NR_clone 56
-#endif
-
-#if !defined(__NR_fork)
-#define __NR_fork 57
-#endif
-
-#if !defined(__NR_vfork)
-#define __NR_vfork 58
-#endif
-
-#if !defined(__NR_execve)
-#define __NR_execve 59
-#endif
-
-#if !defined(__NR_exit)
-#define __NR_exit 60
-#endif
-
-#if !defined(__NR_wait4)
-#define __NR_wait4 61
-#endif
-
-#if !defined(__NR_kill)
-#define __NR_kill 62
-#endif
-
-#if !defined(__NR_uname)
-#define __NR_uname 63
-#endif
-
-#if !defined(__NR_semget)
-#define __NR_semget 64
-#endif
-
-#if !defined(__NR_semop)
-#define __NR_semop 65
-#endif
-
-#if !defined(__NR_semctl)
-#define __NR_semctl 66
-#endif
-
-#if !defined(__NR_shmdt)
-#define __NR_shmdt 67
-#endif
-
-#if !defined(__NR_msgget)
-#define __NR_msgget 68
-#endif
-
-#if !defined(__NR_msgsnd)
-#define __NR_msgsnd 69
-#endif
-
-#if !defined(__NR_msgrcv)
-#define __NR_msgrcv 70
-#endif
-
-#if !defined(__NR_msgctl)
-#define __NR_msgctl 71
-#endif
-
-#if !defined(__NR_fcntl)
-#define __NR_fcntl 72
-#endif
-
-#if !defined(__NR_flock)
-#define __NR_flock 73
-#endif
-
-#if !defined(__NR_fsync)
-#define __NR_fsync 74
-#endif
-
-#if !defined(__NR_fdatasync)
-#define __NR_fdatasync 75
-#endif
-
-#if !defined(__NR_truncate)
-#define __NR_truncate 76
-#endif
-
-#if !defined(__NR_ftruncate)
-#define __NR_ftruncate 77
-#endif
-
-#if !defined(__NR_getdents)
-#define __NR_getdents 78
-#endif
-
-#if !defined(__NR_getcwd)
-#define __NR_getcwd 79
-#endif
-
-#if !defined(__NR_chdir)
-#define __NR_chdir 80
-#endif
-
-#if !defined(__NR_fchdir)
-#define __NR_fchdir 81
-#endif
-
-#if !defined(__NR_rename)
-#define __NR_rename 82
-#endif
-
-#if !defined(__NR_mkdir)
-#define __NR_mkdir 83
-#endif
-
-#if !defined(__NR_rmdir)
-#define __NR_rmdir 84
-#endif
-
-#if !defined(__NR_creat)
-#define __NR_creat 85
-#endif
-
-#if !defined(__NR_link)
-#define __NR_link 86
-#endif
-
-#if !defined(__NR_unlink)
-#define __NR_unlink 87
-#endif
-
-#if !defined(__NR_symlink)
-#define __NR_symlink 88
-#endif
-
-#if !defined(__NR_readlink)
-#define __NR_readlink 89
-#endif
-
-#if !defined(__NR_chmod)
-#define __NR_chmod 90
-#endif
-
-#if !defined(__NR_fchmod)
-#define __NR_fchmod 91
-#endif
-
-#if !defined(__NR_chown)
-#define __NR_chown 92
-#endif
-
-#if !defined(__NR_fchown)
-#define __NR_fchown 93
-#endif
-
-#if !defined(__NR_lchown)
-#define __NR_lchown 94
-#endif
-
-#if !defined(__NR_umask)
-#define __NR_umask 95
-#endif
-
-#if !defined(__NR_gettimeofday)
-#define __NR_gettimeofday 96
-#endif
-
-#if !defined(__NR_getrlimit)
-#define __NR_getrlimit 97
-#endif
-
-#if !defined(__NR_getrusage)
-#define __NR_getrusage 98
-#endif
-
-#if !defined(__NR_sysinfo)
-#define __NR_sysinfo 99
-#endif
-
-#if !defined(__NR_times)
-#define __NR_times 100
-#endif
-
-#if !defined(__NR_ptrace)
-#define __NR_ptrace 101
-#endif
-
-#if !defined(__NR_getuid)
-#define __NR_getuid 102
-#endif
-
-#if !defined(__NR_syslog)
-#define __NR_syslog 103
-#endif
-
-#if !defined(__NR_getgid)
-#define __NR_getgid 104
-#endif
-
-#if !defined(__NR_setuid)
-#define __NR_setuid 105
-#endif
-
-#if !defined(__NR_setgid)
-#define __NR_setgid 106
-#endif
-
-#if !defined(__NR_geteuid)
-#define __NR_geteuid 107
-#endif
-
-#if !defined(__NR_getegid)
-#define __NR_getegid 108
-#endif
-
-#if !defined(__NR_setpgid)
-#define __NR_setpgid 109
-#endif
-
-#if !defined(__NR_getppid)
-#define __NR_getppid 110
-#endif
-
-#if !defined(__NR_getpgrp)
-#define __NR_getpgrp 111
-#endif
-
-#if !defined(__NR_setsid)
-#define __NR_setsid 112
-#endif
-
-#if !defined(__NR_setreuid)
-#define __NR_setreuid 113
-#endif
-
-#if !defined(__NR_setregid)
-#define __NR_setregid 114
-#endif
-
-#if !defined(__NR_getgroups)
-#define __NR_getgroups 115
-#endif
-
-#if !defined(__NR_setgroups)
-#define __NR_setgroups 116
-#endif
-
-#if !defined(__NR_setresuid)
-#define __NR_setresuid 117
-#endif
-
-#if !defined(__NR_getresuid)
-#define __NR_getresuid 118
-#endif
-
-#if !defined(__NR_setresgid)
-#define __NR_setresgid 119
-#endif
-
-#if !defined(__NR_getresgid)
-#define __NR_getresgid 120
-#endif
-
-#if !defined(__NR_getpgid)
-#define __NR_getpgid 121
-#endif
-
-#if !defined(__NR_setfsuid)
-#define __NR_setfsuid 122
-#endif
-
-#if !defined(__NR_setfsgid)
-#define __NR_setfsgid 123
-#endif
-
-#if !defined(__NR_getsid)
-#define __NR_getsid 124
-#endif
-
-#if !defined(__NR_capget)
-#define __NR_capget 125
-#endif
-
-#if !defined(__NR_capset)
-#define __NR_capset 126
-#endif
-
-#if !defined(__NR_rt_sigpending)
-#define __NR_rt_sigpending 127
-#endif
-
-#if !defined(__NR_rt_sigtimedwait)
-#define __NR_rt_sigtimedwait 128
-#endif
-
-#if !defined(__NR_rt_sigqueueinfo)
-#define __NR_rt_sigqueueinfo 129
-#endif
-
-#if !defined(__NR_rt_sigsuspend)
-#define __NR_rt_sigsuspend 130
-#endif
-
-#if !defined(__NR_sigaltstack)
-#define __NR_sigaltstack 131
-#endif
-
-#if !defined(__NR_utime)
-#define __NR_utime 132
-#endif
-
-#if !defined(__NR_mknod)
-#define __NR_mknod 133
-#endif
-
-#if !defined(__NR_uselib)
-#define __NR_uselib 134
-#endif
-
-#if !defined(__NR_personality)
-#define __NR_personality 135
-#endif
-
-#if !defined(__NR_ustat)
-#define __NR_ustat 136
-#endif
-
-#if !defined(__NR_statfs)
-#define __NR_statfs 137
-#endif
-
-#if !defined(__NR_fstatfs)
-#define __NR_fstatfs 138
-#endif
-
-#if !defined(__NR_sysfs)
-#define __NR_sysfs 139
-#endif
-
-#if !defined(__NR_getpriority)
-#define __NR_getpriority 140
-#endif
-
-#if !defined(__NR_setpriority)
-#define __NR_setpriority 141
-#endif
-
-#if !defined(__NR_sched_setparam)
-#define __NR_sched_setparam 142
-#endif
-
-#if !defined(__NR_sched_getparam)
-#define __NR_sched_getparam 143
-#endif
-
-#if !defined(__NR_sched_setscheduler)
-#define __NR_sched_setscheduler 144
-#endif
-
-#if !defined(__NR_sched_getscheduler)
-#define __NR_sched_getscheduler 145
-#endif
-
-#if !defined(__NR_sched_get_priority_max)
-#define __NR_sched_get_priority_max 146
-#endif
-
-#if !defined(__NR_sched_get_priority_min)
-#define __NR_sched_get_priority_min 147
-#endif
-
-#if !defined(__NR_sched_rr_get_interval)
-#define __NR_sched_rr_get_interval 148
-#endif
-
-#if !defined(__NR_mlock)
-#define __NR_mlock 149
-#endif
-
-#if !defined(__NR_munlock)
-#define __NR_munlock 150
-#endif
-
-#if !defined(__NR_mlockall)
-#define __NR_mlockall 151
-#endif
-
-#if !defined(__NR_munlockall)
-#define __NR_munlockall 152
-#endif
-
-#if !defined(__NR_vhangup)
-#define __NR_vhangup 153
-#endif
-
-#if !defined(__NR_modify_ldt)
-#define __NR_modify_ldt 154
-#endif
-
-#if !defined(__NR_pivot_root)
-#define __NR_pivot_root 155
-#endif
-
-#if !defined(__NR__sysctl)
-#define __NR__sysctl 156
-#endif
-
-#if !defined(__NR_prctl)
-#define __NR_prctl 157
-#endif
-
-#if !defined(__NR_arch_prctl)
-#define __NR_arch_prctl 158
-#endif
-
-#if !defined(__NR_adjtimex)
-#define __NR_adjtimex 159
-#endif
-
-#if !defined(__NR_setrlimit)
-#define __NR_setrlimit 160
-#endif
-
-#if !defined(__NR_chroot)
-#define __NR_chroot 161
-#endif
-
-#if !defined(__NR_sync)
-#define __NR_sync 162
-#endif
-
-#if !defined(__NR_acct)
-#define __NR_acct 163
-#endif
-
-#if !defined(__NR_settimeofday)
-#define __NR_settimeofday 164
-#endif
-
-#if !defined(__NR_mount)
-#define __NR_mount 165
-#endif
-
-#if !defined(__NR_umount2)
-#define __NR_umount2 166
-#endif
-
-#if !defined(__NR_swapon)
-#define __NR_swapon 167
-#endif
-
-#if !defined(__NR_swapoff)
-#define __NR_swapoff 168
-#endif
-
-#if !defined(__NR_reboot)
-#define __NR_reboot 169
-#endif
-
-#if !defined(__NR_sethostname)
-#define __NR_sethostname 170
-#endif
-
-#if !defined(__NR_setdomainname)
-#define __NR_setdomainname 171
-#endif
-
-#if !defined(__NR_iopl)
-#define __NR_iopl 172
-#endif
-
-#if !defined(__NR_ioperm)
-#define __NR_ioperm 173
-#endif
-
-#if !defined(__NR_create_module)
-#define __NR_create_module 174
-#endif
-
-#if !defined(__NR_init_module)
-#define __NR_init_module 175
-#endif
-
-#if !defined(__NR_delete_module)
-#define __NR_delete_module 176
-#endif
-
-#if !defined(__NR_get_kernel_syms)
-#define __NR_get_kernel_syms 177
-#endif
-
-#if !defined(__NR_query_module)
-#define __NR_query_module 178
-#endif
-
-#if !defined(__NR_quotactl)
-#define __NR_quotactl 179
-#endif
-
-#if !defined(__NR_nfsservctl)
-#define __NR_nfsservctl 180
-#endif
-
-#if !defined(__NR_getpmsg)
-#define __NR_getpmsg 181
-#endif
-
-#if !defined(__NR_putpmsg)
-#define __NR_putpmsg 182
-#endif
-
-#if !defined(__NR_afs_syscall)
-#define __NR_afs_syscall 183
-#endif
-
-#if !defined(__NR_tuxcall)
-#define __NR_tuxcall 184
-#endif
-
-#if !defined(__NR_security)
-#define __NR_security 185
-#endif
-
-#if !defined(__NR_gettid)
-#define __NR_gettid 186
-#endif
-
-#if !defined(__NR_readahead)
-#define __NR_readahead 187
-#endif
-
-#if !defined(__NR_setxattr)
-#define __NR_setxattr 188
-#endif
-
-#if !defined(__NR_lsetxattr)
-#define __NR_lsetxattr 189
-#endif
-
-#if !defined(__NR_fsetxattr)
-#define __NR_fsetxattr 190
-#endif
-
-#if !defined(__NR_getxattr)
-#define __NR_getxattr 191
-#endif
-
-#if !defined(__NR_lgetxattr)
-#define __NR_lgetxattr 192
-#endif
-
-#if !defined(__NR_fgetxattr)
-#define __NR_fgetxattr 193
-#endif
-
-#if !defined(__NR_listxattr)
-#define __NR_listxattr 194
-#endif
-
-#if !defined(__NR_llistxattr)
-#define __NR_llistxattr 195
-#endif
-
-#if !defined(__NR_flistxattr)
-#define __NR_flistxattr 196
-#endif
-
-#if !defined(__NR_removexattr)
-#define __NR_removexattr 197
-#endif
-
-#if !defined(__NR_lremovexattr)
-#define __NR_lremovexattr 198
-#endif
-
-#if !defined(__NR_fremovexattr)
-#define __NR_fremovexattr 199
-#endif
-
-#if !defined(__NR_tkill)
-#define __NR_tkill 200
-#endif
-
-#if !defined(__NR_time)
-#define __NR_time 201
-#endif
-
-#if !defined(__NR_futex)
-#define __NR_futex 202
-#endif
-
-#if !defined(__NR_sched_setaffinity)
-#define __NR_sched_setaffinity 203
-#endif
-
-#if !defined(__NR_sched_getaffinity)
-#define __NR_sched_getaffinity 204
-#endif
-
-#if !defined(__NR_set_thread_area)
-#define __NR_set_thread_area 205
-#endif
-
-#if !defined(__NR_io_setup)
-#define __NR_io_setup 206
-#endif
-
-#if !defined(__NR_io_destroy)
-#define __NR_io_destroy 207
-#endif
-
-#if !defined(__NR_io_getevents)
-#define __NR_io_getevents 208
-#endif
-
-#if !defined(__NR_io_submit)
-#define __NR_io_submit 209
-#endif
-
-#if !defined(__NR_io_cancel)
-#define __NR_io_cancel 210
-#endif
-
-#if !defined(__NR_get_thread_area)
-#define __NR_get_thread_area 211
-#endif
-
-#if !defined(__NR_lookup_dcookie)
-#define __NR_lookup_dcookie 212
-#endif
-
-#if !defined(__NR_epoll_create)
-#define __NR_epoll_create 213
-#endif
-
-#if !defined(__NR_epoll_ctl_old)
-#define __NR_epoll_ctl_old 214
-#endif
-
-#if !defined(__NR_epoll_wait_old)
-#define __NR_epoll_wait_old 215
-#endif
-
-#if !defined(__NR_remap_file_pages)
-#define __NR_remap_file_pages 216
-#endif
-
-#if !defined(__NR_getdents64)
-#define __NR_getdents64 217
-#endif
-
-#if !defined(__NR_set_tid_address)
-#define __NR_set_tid_address 218
-#endif
-
-#if !defined(__NR_restart_syscall)
-#define __NR_restart_syscall 219
-#endif
-
-#if !defined(__NR_semtimedop)
-#define __NR_semtimedop 220
-#endif
-
-#if !defined(__NR_fadvise64)
-#define __NR_fadvise64 221
-#endif
-
-#if !defined(__NR_timer_create)
-#define __NR_timer_create 222
-#endif
-
-#if !defined(__NR_timer_settime)
-#define __NR_timer_settime 223
-#endif
-
-#if !defined(__NR_timer_gettime)
-#define __NR_timer_gettime 224
-#endif
-
-#if !defined(__NR_timer_getoverrun)
-#define __NR_timer_getoverrun 225
-#endif
-
-#if !defined(__NR_timer_delete)
-#define __NR_timer_delete 226
-#endif
-
-#if !defined(__NR_clock_settime)
-#define __NR_clock_settime 227
-#endif
-
-#if !defined(__NR_clock_gettime)
-#define __NR_clock_gettime 228
-#endif
-
-#if !defined(__NR_clock_getres)
-#define __NR_clock_getres 229
-#endif
-
-#if !defined(__NR_clock_nanosleep)
-#define __NR_clock_nanosleep 230
-#endif
-
-#if !defined(__NR_exit_group)
-#define __NR_exit_group 231
-#endif
-
-#if !defined(__NR_epoll_wait)
-#define __NR_epoll_wait 232
-#endif
-
-#if !defined(__NR_epoll_ctl)
-#define __NR_epoll_ctl 233
-#endif
-
-#if !defined(__NR_tgkill)
-#define __NR_tgkill 234
-#endif
-
-#if !defined(__NR_utimes)
-#define __NR_utimes 235
-#endif
-
-#if !defined(__NR_vserver)
-#define __NR_vserver 236
-#endif
-
-#if !defined(__NR_mbind)
-#define __NR_mbind 237
-#endif
-
-#if !defined(__NR_set_mempolicy)
-#define __NR_set_mempolicy 238
-#endif
-
-#if !defined(__NR_get_mempolicy)
-#define __NR_get_mempolicy 239
-#endif
-
-#if !defined(__NR_mq_open)
-#define __NR_mq_open 240
-#endif
-
-#if !defined(__NR_mq_unlink)
-#define __NR_mq_unlink 241
-#endif
-
-#if !defined(__NR_mq_timedsend)
-#define __NR_mq_timedsend 242
-#endif
-
-#if !defined(__NR_mq_timedreceive)
-#define __NR_mq_timedreceive 243
-#endif
-
-#if !defined(__NR_mq_notify)
-#define __NR_mq_notify 244
-#endif
-
-#if !defined(__NR_mq_getsetattr)
-#define __NR_mq_getsetattr 245
-#endif
-
-#if !defined(__NR_kexec_load)
-#define __NR_kexec_load 246
-#endif
-
-#if !defined(__NR_waitid)
-#define __NR_waitid 247
-#endif
-
-#if !defined(__NR_add_key)
-#define __NR_add_key 248
-#endif
-
-#if !defined(__NR_request_key)
-#define __NR_request_key 249
-#endif
-
-#if !defined(__NR_keyctl)
-#define __NR_keyctl 250
-#endif
-
-#if !defined(__NR_ioprio_set)
-#define __NR_ioprio_set 251
-#endif
-
-#if !defined(__NR_ioprio_get)
-#define __NR_ioprio_get 252
-#endif
-
-#if !defined(__NR_inotify_init)
-#define __NR_inotify_init 253
-#endif
-
-#if !defined(__NR_inotify_add_watch)
-#define __NR_inotify_add_watch 254
-#endif
-
-#if !defined(__NR_inotify_rm_watch)
-#define __NR_inotify_rm_watch 255
-#endif
-
-#if !defined(__NR_migrate_pages)
-#define __NR_migrate_pages 256
-#endif
-
-#if !defined(__NR_openat)
-#define __NR_openat 257
-#endif
-
-#if !defined(__NR_mkdirat)
-#define __NR_mkdirat 258
-#endif
-
-#if !defined(__NR_mknodat)
-#define __NR_mknodat 259
-#endif
-
-#if !defined(__NR_fchownat)
-#define __NR_fchownat 260
-#endif
-
-#if !defined(__NR_futimesat)
-#define __NR_futimesat 261
-#endif
-
-#if !defined(__NR_newfstatat)
-#define __NR_newfstatat 262
-#endif
-
-#if !defined(__NR_unlinkat)
-#define __NR_unlinkat 263
-#endif
-
-#if !defined(__NR_renameat)
-#define __NR_renameat 264
-#endif
-
-#if !defined(__NR_linkat)
-#define __NR_linkat 265
-#endif
-
-#if !defined(__NR_symlinkat)
-#define __NR_symlinkat 266
-#endif
-
-#if !defined(__NR_readlinkat)
-#define __NR_readlinkat 267
-#endif
-
-#if !defined(__NR_fchmodat)
-#define __NR_fchmodat 268
-#endif
-
-#if !defined(__NR_faccessat)
-#define __NR_faccessat 269
-#endif
-
-#if !defined(__NR_pselect6)
-#define __NR_pselect6 270
-#endif
-
-#if !defined(__NR_ppoll)
-#define __NR_ppoll 271
-#endif
-
-#if !defined(__NR_unshare)
-#define __NR_unshare 272
-#endif
-
-#if !defined(__NR_set_robust_list)
-#define __NR_set_robust_list 273
-#endif
-
-#if !defined(__NR_get_robust_list)
-#define __NR_get_robust_list 274
-#endif
-
-#if !defined(__NR_splice)
-#define __NR_splice 275
-#endif
-
-#if !defined(__NR_tee)
-#define __NR_tee 276
-#endif
-
-#if !defined(__NR_sync_file_range)
-#define __NR_sync_file_range 277
-#endif
-
-#if !defined(__NR_vmsplice)
-#define __NR_vmsplice 278
-#endif
-
-#if !defined(__NR_move_pages)
-#define __NR_move_pages 279
-#endif
-
-#if !defined(__NR_utimensat)
-#define __NR_utimensat 280
-#endif
-
-#if !defined(__NR_epoll_pwait)
-#define __NR_epoll_pwait 281
-#endif
-
-#if !defined(__NR_signalfd)
-#define __NR_signalfd 282
-#endif
-
-#if !defined(__NR_timerfd_create)
-#define __NR_timerfd_create 283
-#endif
-
-#if !defined(__NR_eventfd)
-#define __NR_eventfd 284
-#endif
-
-#if !defined(__NR_fallocate)
-#define __NR_fallocate 285
-#endif
-
-#if !defined(__NR_timerfd_settime)
-#define __NR_timerfd_settime 286
-#endif
-
-#if !defined(__NR_timerfd_gettime)
-#define __NR_timerfd_gettime 287
-#endif
-
-#if !defined(__NR_accept4)
-#define __NR_accept4 288
-#endif
-
-#if !defined(__NR_signalfd4)
-#define __NR_signalfd4 289
-#endif
-
-#if !defined(__NR_eventfd2)
-#define __NR_eventfd2 290
-#endif
-
-#if !defined(__NR_epoll_create1)
-#define __NR_epoll_create1 291
-#endif
-
-#if !defined(__NR_dup3)
-#define __NR_dup3 292
-#endif
-
-#if !defined(__NR_pipe2)
-#define __NR_pipe2 293
-#endif
-
-#if !defined(__NR_inotify_init1)
-#define __NR_inotify_init1 294
-#endif
-
-#if !defined(__NR_preadv)
-#define __NR_preadv 295
-#endif
-
-#if !defined(__NR_pwritev)
-#define __NR_pwritev 296
-#endif
-
-#if !defined(__NR_rt_tgsigqueueinfo)
-#define __NR_rt_tgsigqueueinfo 297
-#endif
-
-#if !defined(__NR_perf_event_open)
-#define __NR_perf_event_open 298
-#endif
-
-#if !defined(__NR_recvmmsg)
-#define __NR_recvmmsg 299
-#endif
-
-#if !defined(__NR_fanotify_init)
-#define __NR_fanotify_init 300
-#endif
-
-#if !defined(__NR_fanotify_mark)
-#define __NR_fanotify_mark 301
-#endif
-
-#if !defined(__NR_prlimit64)
-#define __NR_prlimit64 302
-#endif
-
-#if !defined(__NR_name_to_handle_at)
-#define __NR_name_to_handle_at 303
-#endif
-
-#if !defined(__NR_open_by_handle_at)
-#define __NR_open_by_handle_at 304
-#endif
-
-#if !defined(__NR_clock_adjtime)
-#define __NR_clock_adjtime 305
-#endif
-
-#if !defined(__NR_syncfs)
-#define __NR_syncfs 306
-#endif
-
-#if !defined(__NR_sendmmsg)
-#define __NR_sendmmsg 307
-#endif
-
-#if !defined(__NR_setns)
-#define __NR_setns 308
-#endif
-
-#if !defined(__NR_getcpu)
-#define __NR_getcpu 309
-#endif
-
-#if !defined(__NR_process_vm_readv)
-#define __NR_process_vm_readv 310
-#endif
-
-#if !defined(__NR_process_vm_writev)
-#define __NR_process_vm_writev 311
-#endif
-
-#if !defined(__NR_kcmp)
-#define __NR_kcmp 312
-#endif
-
-#if !defined(__NR_finit_module)
-#define __NR_finit_module 313
-#endif
-
-#if !defined(__NR_sched_setattr)
-#define __NR_sched_setattr 314
-#endif
-
-#if !defined(__NR_sched_getattr)
-#define __NR_sched_getattr 315
-#endif
-
-#if !defined(__NR_renameat2)
-#define __NR_renameat2 316
-#endif
-
-#if !defined(__NR_seccomp)
-#define __NR_seccomp 317
-#endif
-
-#if !defined(__NR_getrandom)
-#define __NR_getrandom 318
-#endif
-
-#if !defined(__NR_memfd_create)
-#define __NR_memfd_create 319
-#endif
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_X86_64_LINUX_SYSCALLS_H_
-
diff --git a/security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_ucontext.h b/security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_ucontext.h
deleted file mode 100644
index 1f1abe642..000000000
--- a/security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_ucontext.h
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright 2014 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 SANDBOX_LINUX_SYSTEM_HEADERS_X86_64_LINUX_UCONTEXT_H_
-#define SANDBOX_LINUX_SYSTEM_HEADERS_X86_64_LINUX_UCONTEXT_H_
-
-#include <stdint.h>
-
-// We do something compatible with glibc. Hopefully, at some point Android will
-// provide that for us, and __BIONIC_HAVE_UCONTEXT_T should be defined.
-// Spec:
-// http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-AMD64/LSB-Core-AMD64/libc-ddefs.html#AEN5668
-
-#if !defined(__BIONIC_HAVE_UCONTEXT_T)
-#include <asm/sigcontext.h>
-
-struct _libc_fpxreg {
- unsigned short significand[4];
- unsigned short exponent;
- unsigned short padding[3];
-};
-
-struct _libc_xmmreg {
- uint32_t element[4];
-};
-
-struct _libc_fpstate {
- uint16_t cwd;
- uint16_t swd;
- uint16_t twd;
- uint16_t fop;
- uint64_t rip;
- uint64_t rdp;
- uint32_t mxcsr;
- uint32_t mxcsr_mask;
- struct _libc_fpxreg _st[8];
- struct _libc_xmmreg _xmm[16];
- uint32_t padding[24];
-};
-
-typedef uint64_t greg_t;
-
-typedef struct {
- greg_t gregs[23];
- struct _libc_fpstate* fpregs;
- unsigned long __reserved1[8];
-} mcontext_t;
-
-enum {
- REG_R8 = 0,
- REG_R9,
- REG_R10,
- REG_R11,
- REG_R12,
- REG_R13,
- REG_R14,
- REG_R15,
- REG_RDI,
- REG_RSI,
- REG_RBP,
- REG_RBX,
- REG_RDX,
- REG_RAX,
- REG_RCX,
- REG_RSP,
- REG_RIP,
- REG_EFL,
- REG_CSGSFS,
- REG_ERR,
- REG_TRAPNO,
- REG_OLDMASK,
- REG_CR2,
- NGREG,
-};
-
-typedef struct ucontext {
- unsigned long uc_flags;
- struct ucontext* uc_link;
- stack_t uc_stack;
- mcontext_t uc_mcontext;
- sigset_t uc_sigmask;
- struct _libc_fpstate __fpregs_mem;
-} ucontext_t;
-
-#else
-#include <sys/ucontext.h>
-#endif // __BIONIC_HAVE_UCONTEXT_T
-
-#endif // SANDBOX_LINUX_SYSTEM_HEADERS_X86_64_LINUX_UCONTEXT_H_
diff --git a/security/sandbox/chromium/sandbox/sandbox_export.h b/security/sandbox/chromium/sandbox/sandbox_export.h
deleted file mode 100644
index 35d6a1ba2..000000000
--- a/security/sandbox/chromium/sandbox/sandbox_export.h
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright 2014 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 SANDBOX_SANDBOX_EXPORT_H_
-#define SANDBOX_SANDBOX_EXPORT_H_
-
-#if defined(WIN32)
-#error "sandbox_export.h does not support WIN32."
-#endif
-
-#if defined(COMPONENT_BUILD)
-
-#if defined(SANDBOX_IMPLEMENTATION)
-#define SANDBOX_EXPORT __attribute__((visibility("default")))
-#else
-#define SANDBOX_EXPORT
-#endif // defined(SANDBOX_IMPLEMENTATION)
-
-#else // defined(COMPONENT_BUILD)
-
-#define SANDBOX_EXPORT
-
-#endif // defined(COMPONENT_BUILD)
-
-#endif // SANDBOX_SANDBOX_EXPORT_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/Wow64.cc b/security/sandbox/chromium/sandbox/win/src/Wow64.cc
deleted file mode 100644
index c5984d629..000000000
--- a/security/sandbox/chromium/sandbox/win/src/Wow64.cc
+++ /dev/null
@@ -1,226 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/Wow64.h"
-
-#include <stddef.h>
-
-#include <sstream>
-
-#include "base/bit_cast.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/win/scoped_process_information.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/target_process.h"
-
-namespace {
-
-// Holds the information needed for the interception of NtMapViewOfSection on
-// 64 bits.
-// Warning: do not modify this definition without changing also the code on the
-// 64 bit helper process.
-struct PatchInfo32 {
- HANDLE dll_load; // Event to signal the broker.
- ULONG pad1;
- HANDLE continue_load; // Event to wait for the broker.
- ULONG pad2;
- HANDLE section; // First argument of the call.
- ULONG pad3;
- void* orig_MapViewOfSection;
- ULONG original_high;
- void* signal_and_wait;
- ULONG pad4;
- void* patch_location;
- ULONG patch_high;
-};
-
-// Size of the 64 bit service entry.
-const SIZE_T kServiceEntry64Size = 0x10;
-
-// Removes the interception of ntdll64.
-bool Restore64Code(HANDLE child, PatchInfo32* patch_info) {
- PatchInfo32 local_patch_info;
- SIZE_T actual;
- if (!::ReadProcessMemory(child, patch_info, &local_patch_info,
- sizeof(local_patch_info), &actual))
- return false;
- if (sizeof(local_patch_info) != actual)
- return false;
-
- if (local_patch_info.original_high)
- return false;
- if (local_patch_info.patch_high)
- return false;
-
- char buffer[kServiceEntry64Size];
-
- if (!::ReadProcessMemory(child, local_patch_info.orig_MapViewOfSection,
- &buffer, kServiceEntry64Size, &actual))
- return false;
- if (kServiceEntry64Size != actual)
- return false;
-
- if (!::WriteProcessMemory(child, local_patch_info.patch_location, &buffer,
- kServiceEntry64Size, &actual))
- return false;
- if (kServiceEntry64Size != actual)
- return false;
- return true;
-}
-
-typedef BOOL (WINAPI* IsWow64ProcessFunction)(HANDLE process, BOOL* wow64);
-
-} // namespace
-
-namespace sandbox {
-
-Wow64::Wow64(TargetProcess* child, HMODULE ntdll)
- : child_(child), ntdll_(ntdll), dll_load_(NULL), continue_load_(NULL) {
-}
-
-Wow64::~Wow64() {
-}
-
-// The basic idea is to allocate one page of memory on the child, and initialize
-// the first part of it with our version of PatchInfo32. Then launch the helper
-// process passing it that address on the child. The helper process will patch
-// the 64 bit version of NtMapViewOfFile, and the interception will signal the
-// first event on the buffer. We'll be waiting on that event and after the 32
-// bit version of ntdll is loaded, we'll remove the interception and return to
-// our caller.
-bool Wow64::WaitForNtdll() {
- if (base::win::OSInfo::GetInstance()->wow64_status() !=
- base::win::OSInfo::WOW64_ENABLED)
- return true;
-
- const size_t page_size = 4096;
-
- // Create some default manual reset un-named events, not signaled.
- dll_load_.Set(::CreateEvent(NULL, TRUE, FALSE, NULL));
- continue_load_.Set(::CreateEvent(NULL, TRUE, FALSE, NULL));
- HANDLE current_process = ::GetCurrentProcess();
- HANDLE remote_load, remote_continue;
- DWORD access = EVENT_MODIFY_STATE | SYNCHRONIZE;
- if (!::DuplicateHandle(current_process, dll_load_.Get(), child_->Process(),
- &remote_load, access, FALSE, 0)) {
- return false;
- }
- if (!::DuplicateHandle(current_process, continue_load_.Get(),
- child_->Process(), &remote_continue, access, FALSE,
- 0)) {
- return false;
- }
-
- void* buffer = ::VirtualAllocEx(child_->Process(), NULL, page_size,
- MEM_COMMIT, PAGE_EXECUTE_READWRITE);
- DCHECK(buffer);
- if (!buffer)
- return false;
-
- PatchInfo32* patch_info = reinterpret_cast<PatchInfo32*>(buffer);
- PatchInfo32 local_patch_info = {0};
- local_patch_info.dll_load = remote_load;
- local_patch_info.continue_load = remote_continue;
- SIZE_T written;
- if (!::WriteProcessMemory(child_->Process(), patch_info, &local_patch_info,
- offsetof(PatchInfo32, section), &written))
- return false;
- if (offsetof(PatchInfo32, section) != written)
- return false;
-
- if (!RunWowHelper(buffer))
- return false;
-
- // The child is intercepted on 64 bit, go on and wait for our event.
- if (!DllMapped())
- return false;
-
- // The 32 bit version is available, cleanup the child.
- return Restore64Code(child_->Process(), patch_info);
-}
-
-bool Wow64::RunWowHelper(void* buffer) {
- static_assert(sizeof(buffer) <= sizeof(DWORD), "unsupported 64 bits");
-
- // Get the path to the helper (beside the exe).
- wchar_t prog_name[MAX_PATH];
- GetModuleFileNameW(NULL, prog_name, MAX_PATH);
- base::string16 path(prog_name);
- size_t name_pos = path.find_last_of(L"\\");
- if (base::string16::npos == name_pos)
- return false;
- path.resize(name_pos + 1);
-
- std::basic_stringstream<base::char16> command;
- command << std::hex << std::showbase << L"\"" << path <<
- L"wow_helper.exe\" " << child_->ProcessId() << " " <<
- bit_cast<ULONG>(buffer);
-
- scoped_ptr<wchar_t, base::FreeDeleter>
- writable_command(_wcsdup(command.str().c_str()));
-
- STARTUPINFO startup_info = {0};
- startup_info.cb = sizeof(startup_info);
- PROCESS_INFORMATION temp_process_info = {};
- if (!::CreateProcess(NULL, writable_command.get(), NULL, NULL, FALSE, 0, NULL,
- NULL, &startup_info, &temp_process_info))
- return false;
- base::win::ScopedProcessInformation process_info(temp_process_info);
-
- DWORD reason = ::WaitForSingleObject(process_info.process_handle(), INFINITE);
-
- DWORD code;
- bool ok =
- ::GetExitCodeProcess(process_info.process_handle(), &code) ? true : false;
-
- if (WAIT_TIMEOUT == reason)
- return false;
-
- return ok && (0 == code);
-}
-
-// First we must wake up the child, then wait for dll loads on the child until
-// the one we care is loaded; at that point we must suspend the child again.
-bool Wow64::DllMapped() {
- if (1 != ::ResumeThread(child_->MainThread())) {
- NOTREACHED();
- return false;
- }
-
- for (;;) {
- DWORD reason = ::WaitForSingleObject(dll_load_.Get(), INFINITE);
- if (WAIT_TIMEOUT == reason || WAIT_ABANDONED == reason)
- return false;
-
- if (!::ResetEvent(dll_load_.Get()))
- return false;
-
- bool found = NtdllPresent();
- if (found) {
- if (::SuspendThread(child_->MainThread()))
- return false;
- }
-
- if (!::SetEvent(continue_load_.Get()))
- return false;
-
- if (found)
- return true;
- }
-}
-
-bool Wow64::NtdllPresent() {
- const size_t kBufferSize = 512;
- char buffer[kBufferSize];
- SIZE_T read;
- if (!::ReadProcessMemory(child_->Process(), ntdll_, &buffer, kBufferSize,
- &read))
- return false;
- if (kBufferSize != read)
- return false;
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/Wow64.h b/security/sandbox/chromium/sandbox/win/src/Wow64.h
deleted file mode 100644
index acabc3565..000000000
--- a/security/sandbox/chromium/sandbox/win/src/Wow64.h
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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 SANDBOX_SRC_WOW64_H__
-#define SANDBOX_SRC_WOW64_H__
-
-#include <windows.h>
-
-#include "base/macros.h"
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace sandbox {
-
-class TargetProcess;
-
-// This class wraps the code needed to interact with the Windows On Windows
-// subsystem on 64 bit OSes, from the point of view of interceptions.
-class Wow64 {
- public:
- Wow64(TargetProcess* child, HMODULE ntdll);
- ~Wow64();
-
- // Waits for the 32 bit DLL to get loaded on the child process. This function
- // will return immediately if not running under WOW, or launch the helper
- // process and wait until ntdll is ready.
- bool WaitForNtdll();
-
- private:
- // Runs the WOW helper process, passing the address of a buffer allocated on
- // the child (one page).
- bool RunWowHelper(void* buffer);
-
- // This method receives "notifications" whenever a DLL is mapped on the child.
- bool DllMapped();
-
- // Returns true if ntdll.dll is mapped on the child.
- bool NtdllPresent();
-
- TargetProcess* child_; // Child process.
- HMODULE ntdll_; // ntdll on the parent.
- // Event that is signaled on dll load.
- base::win::ScopedHandle dll_load_;
- // Event to signal to continue execution on the child.
- base::win::ScopedHandle continue_load_;
- DISALLOW_IMPLICIT_CONSTRUCTORS(Wow64);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_WOW64_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/Wow64_64.cc b/security/sandbox/chromium/sandbox/win/src/Wow64_64.cc
deleted file mode 100644
index 357deb855..000000000
--- a/security/sandbox/chromium/sandbox/win/src/Wow64_64.cc
+++ /dev/null
@@ -1,22 +0,0 @@
-// 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.
-
-// Wow64 implementation for native 64-bit Windows (in other words, never WOW).
-
-#include "sandbox/win/src/wow64.h"
-
-namespace sandbox {
-
-Wow64::Wow64(TargetProcess* child, HMODULE ntdll)
- : child_(child), ntdll_(ntdll), dll_load_(NULL), continue_load_(NULL) {
-}
-
-Wow64::~Wow64() {
-}
-
-bool Wow64::WaitForNtdll() {
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/acl.cc b/security/sandbox/chromium/sandbox/win/src/acl.cc
deleted file mode 100644
index f140c7e6c..000000000
--- a/security/sandbox/chromium/sandbox/win/src/acl.cc
+++ /dev/null
@@ -1,125 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/acl.h"
-
-#include <aclapi.h>
-#include <sddl.h>
-
-#include "base/logging.h"
-
-namespace sandbox {
-
-bool GetDefaultDacl(
- HANDLE token,
- scoped_ptr<TOKEN_DEFAULT_DACL, base::FreeDeleter>* default_dacl) {
- if (token == NULL)
- return false;
-
- DCHECK(default_dacl != NULL);
-
- unsigned long length = 0;
- ::GetTokenInformation(token, TokenDefaultDacl, NULL, 0, &length);
- if (length == 0) {
- NOTREACHED();
- return false;
- }
-
- TOKEN_DEFAULT_DACL* acl =
- reinterpret_cast<TOKEN_DEFAULT_DACL*>(malloc(length));
- default_dacl->reset(acl);
-
- if (!::GetTokenInformation(token, TokenDefaultDacl, default_dacl->get(),
- length, &length))
- return false;
-
- return true;
-}
-
-bool AddSidToDacl(const Sid& sid, ACL* old_dacl, ACCESS_MODE access_mode,
- ACCESS_MASK access, ACL** new_dacl) {
- EXPLICIT_ACCESS new_access = {0};
- new_access.grfAccessMode = access_mode;
- new_access.grfAccessPermissions = access;
- new_access.grfInheritance = NO_INHERITANCE;
-
- new_access.Trustee.pMultipleTrustee = NULL;
- new_access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
- new_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
- new_access.Trustee.ptstrName = reinterpret_cast<LPWSTR>(
- const_cast<SID*>(sid.GetPSID()));
-
- if (ERROR_SUCCESS != ::SetEntriesInAcl(1, &new_access, old_dacl, new_dacl))
- return false;
-
- return true;
-}
-
-bool AddSidToDefaultDacl(HANDLE token, const Sid& sid, ACCESS_MASK access) {
- if (token == NULL)
- return false;
-
- scoped_ptr<TOKEN_DEFAULT_DACL, base::FreeDeleter> default_dacl;
- if (!GetDefaultDacl(token, &default_dacl))
- return false;
-
- ACL* new_dacl = NULL;
- if (!AddSidToDacl(sid, default_dacl->DefaultDacl, GRANT_ACCESS, access,
- &new_dacl))
- return false;
-
- TOKEN_DEFAULT_DACL new_token_dacl = {0};
- new_token_dacl.DefaultDacl = new_dacl;
-
- BOOL ret = ::SetTokenInformation(token, TokenDefaultDacl, &new_token_dacl,
- sizeof(new_token_dacl));
- ::LocalFree(new_dacl);
- return (TRUE == ret);
-}
-
-bool AddUserSidToDefaultDacl(HANDLE token, ACCESS_MASK access) {
- DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
- TOKEN_USER* token_user = reinterpret_cast<TOKEN_USER*>(malloc(size));
-
- scoped_ptr<TOKEN_USER, base::FreeDeleter> token_user_ptr(token_user);
-
- if (!::GetTokenInformation(token, TokenUser, token_user, size, &size))
- return false;
-
- return AddSidToDefaultDacl(token,
- reinterpret_cast<SID*>(token_user->User.Sid),
- access);
-}
-
-bool AddKnownSidToObject(HANDLE object, SE_OBJECT_TYPE object_type,
- const Sid& sid, ACCESS_MODE access_mode,
- ACCESS_MASK access) {
- PSECURITY_DESCRIPTOR descriptor = NULL;
- PACL old_dacl = NULL;
- PACL new_dacl = NULL;
-
- if (ERROR_SUCCESS != ::GetSecurityInfo(object, object_type,
- DACL_SECURITY_INFORMATION, NULL, NULL,
- &old_dacl, NULL, &descriptor))
- return false;
-
- if (!AddSidToDacl(sid.GetPSID(), old_dacl, access_mode, access, &new_dacl)) {
- ::LocalFree(descriptor);
- return false;
- }
-
- DWORD result = ::SetSecurityInfo(object, object_type,
- DACL_SECURITY_INFORMATION, NULL, NULL,
- new_dacl, NULL);
-
- ::LocalFree(new_dacl);
- ::LocalFree(descriptor);
-
- if (ERROR_SUCCESS != result)
- return false;
-
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/acl.h b/security/sandbox/chromium/sandbox/win/src/acl.h
deleted file mode 100644
index b5021e7be..000000000
--- a/security/sandbox/chromium/sandbox/win/src/acl.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_ACL_H_
-#define SANDBOX_SRC_ACL_H_
-
-#include <AccCtrl.h>
-#include <windows.h>
-
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/sid.h"
-
-namespace sandbox {
-
-// Returns the default dacl from the token passed in.
-bool GetDefaultDacl(
- HANDLE token,
- scoped_ptr<TOKEN_DEFAULT_DACL, base::FreeDeleter>* default_dacl);
-
-// Appends an ACE represented by |sid|, |access_mode|, and |access| to
-// |old_dacl|. If the function succeeds, new_dacl contains the new dacl and
-// must be freed using LocalFree.
-bool AddSidToDacl(const Sid& sid, ACL* old_dacl, ACCESS_MODE access_mode,
- ACCESS_MASK access, ACL** new_dacl);
-
-// Adds and ACE represented by |sid| and |access| to the default dacl present
-// in the token.
-bool AddSidToDefaultDacl(HANDLE token, const Sid& sid, ACCESS_MASK access);
-
-// Adds an ACE represented by the user sid and |access| to the default dacl
-// present in the token.
-bool AddUserSidToDefaultDacl(HANDLE token, ACCESS_MASK access);
-
-// Adds an ACE represented by |known_sid|, |access_mode|, and |access| to
-// the dacl of the kernel object referenced by |object| and of |object_type|.
-bool AddKnownSidToObject(HANDLE object, SE_OBJECT_TYPE object_type,
- const Sid& sid, ACCESS_MODE access_mode,
- ACCESS_MASK access);
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_ACL_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/app_container.cc b/security/sandbox/chromium/sandbox/win/src/app_container.cc
deleted file mode 100644
index a51f09208..000000000
--- a/security/sandbox/chromium/sandbox/win/src/app_container.cc
+++ /dev/null
@@ -1,184 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/app_container.h"
-
-#include <Sddl.h>
-#include <stddef.h>
-#include <vector>
-
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/win/startup_information.h"
-#include "sandbox/win/src/internal_types.h"
-
-namespace {
-
-// Converts the passed in sid string to a PSID that must be relased with
-// LocalFree.
-PSID ConvertSid(const base::string16& sid) {
- PSID local_sid;
- if (!ConvertStringSidToSid(sid.c_str(), &local_sid))
- return NULL;
- return local_sid;
-}
-
-template <typename T>
-T BindFunction(const char* name) {
- HMODULE module = GetModuleHandle(sandbox::kKerneldllName);
- void* function = GetProcAddress(module, name);
- if (!function) {
- module = GetModuleHandle(sandbox::kKernelBasedllName);
- function = GetProcAddress(module, name);
- }
- return reinterpret_cast<T>(function);
-}
-
-} // namespace
-
-namespace sandbox {
-
-AppContainerAttributes::AppContainerAttributes() {
- memset(&capabilities_, 0, sizeof(capabilities_));
-}
-
-AppContainerAttributes::~AppContainerAttributes() {
- for (size_t i = 0; i < attributes_.size(); i++)
- LocalFree(attributes_[i].Sid);
- LocalFree(capabilities_.AppContainerSid);
-}
-
-ResultCode AppContainerAttributes::SetAppContainer(
- const base::string16& app_container_sid,
- const std::vector<base::string16>& capabilities) {
- DCHECK(!capabilities_.AppContainerSid);
- DCHECK(attributes_.empty());
- capabilities_.AppContainerSid = ConvertSid(app_container_sid);
- if (!capabilities_.AppContainerSid)
- return SBOX_ERROR_INVALID_APP_CONTAINER;
-
- for (size_t i = 0; i < capabilities.size(); i++) {
- SID_AND_ATTRIBUTES sid_and_attributes;
- sid_and_attributes.Sid = ConvertSid(capabilities[i]);
- if (!sid_and_attributes.Sid)
- return SBOX_ERROR_INVALID_CAPABILITY;
-
- sid_and_attributes.Attributes = SE_GROUP_ENABLED;
- attributes_.push_back(sid_and_attributes);
- }
-
- if (capabilities.size()) {
- capabilities_.CapabilityCount = static_cast<DWORD>(capabilities.size());
- capabilities_.Capabilities = &attributes_[0];
- }
- return SBOX_ALL_OK;
-}
-
-ResultCode AppContainerAttributes::ShareForStartup(
- base::win::StartupInformation* startup_information) const {
- // The only thing we support so far is an AppContainer.
- if (!capabilities_.AppContainerSid)
- return SBOX_ERROR_INVALID_APP_CONTAINER;
-
- if (!startup_information->UpdateProcThreadAttribute(
- PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,
- const_cast<SECURITY_CAPABILITIES*>(&capabilities_),
- sizeof(capabilities_))) {
- DPLOG(ERROR) << "Failed UpdateProcThreadAttribute";
- return SBOX_ERROR_CANNOT_INIT_APPCONTAINER;
- }
- return SBOX_ALL_OK;
-}
-
-bool AppContainerAttributes::HasAppContainer() const {
- return (capabilities_.AppContainerSid != NULL);
-}
-
-ResultCode CreateAppContainer(const base::string16& sid,
- const base::string16& name) {
- PSID local_sid;
- if (!ConvertStringSidToSid(sid.c_str(), &local_sid))
- return SBOX_ERROR_INVALID_APP_CONTAINER;
-
- typedef HRESULT (WINAPI* AppContainerRegisterSidPtr)(PSID sid,
- LPCWSTR moniker,
- LPCWSTR display_name);
- static AppContainerRegisterSidPtr AppContainerRegisterSid = NULL;
-
- if (!AppContainerRegisterSid) {
- AppContainerRegisterSid =
- BindFunction<AppContainerRegisterSidPtr>("AppContainerRegisterSid");
- }
-
- ResultCode operation_result = SBOX_ERROR_GENERIC;
- if (AppContainerRegisterSid) {
- HRESULT rv = AppContainerRegisterSid(local_sid, name.c_str(), name.c_str());
- if (SUCCEEDED(rv))
- operation_result = SBOX_ALL_OK;
- else
- DLOG(ERROR) << "AppContainerRegisterSid error:" << std::hex << rv;
- }
- LocalFree(local_sid);
- return operation_result;
-}
-
-ResultCode DeleteAppContainer(const base::string16& sid) {
- PSID local_sid;
- if (!ConvertStringSidToSid(sid.c_str(), &local_sid))
- return SBOX_ERROR_INVALID_APP_CONTAINER;
-
- typedef HRESULT (WINAPI* AppContainerUnregisterSidPtr)(PSID sid);
- static AppContainerUnregisterSidPtr AppContainerUnregisterSid = NULL;
-
- if (!AppContainerUnregisterSid) {
- AppContainerUnregisterSid =
- BindFunction<AppContainerUnregisterSidPtr>("AppContainerUnregisterSid");
- }
-
- ResultCode operation_result = SBOX_ERROR_GENERIC;
- if (AppContainerUnregisterSid) {
- HRESULT rv = AppContainerUnregisterSid(local_sid);
- if (SUCCEEDED(rv))
- operation_result = SBOX_ALL_OK;
- else
- DLOG(ERROR) << "AppContainerUnregisterSid error:" << std::hex << rv;
- }
- LocalFree(local_sid);
- return operation_result;
-}
-
-base::string16 LookupAppContainer(const base::string16& sid) {
- PSID local_sid;
- if (!ConvertStringSidToSid(sid.c_str(), &local_sid))
- return base::string16();
-
- typedef HRESULT (WINAPI* AppContainerLookupMonikerPtr)(PSID sid,
- LPWSTR* moniker);
- typedef BOOLEAN (WINAPI* AppContainerFreeMemoryPtr)(void* ptr);
-
- static AppContainerLookupMonikerPtr AppContainerLookupMoniker = NULL;
- static AppContainerFreeMemoryPtr AppContainerFreeMemory = NULL;
-
- if (!AppContainerLookupMoniker || !AppContainerFreeMemory) {
- AppContainerLookupMoniker =
- BindFunction<AppContainerLookupMonikerPtr>("AppContainerLookupMoniker");
- AppContainerFreeMemory =
- BindFunction<AppContainerFreeMemoryPtr>("AppContainerFreeMemory");
- }
-
- if (!AppContainerLookupMoniker || !AppContainerFreeMemory)
- return base::string16();
-
- wchar_t* buffer = NULL;
- HRESULT rv = AppContainerLookupMoniker(local_sid, &buffer);
- if (FAILED(rv))
- return base::string16();
-
- base::string16 name(buffer);
- if (!AppContainerFreeMemory(buffer))
- NOTREACHED();
- return name;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/app_container.h b/security/sandbox/chromium/sandbox/win/src/app_container.h
deleted file mode 100644
index fe2b18933..000000000
--- a/security/sandbox/chromium/sandbox/win/src/app_container.h
+++ /dev/null
@@ -1,70 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_WIN_SRC_APP_CONTAINER_H_
-#define SANDBOX_WIN_SRC_APP_CONTAINER_H_
-
-#include <windows.h>
-
-#include <vector>
-
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace base {
-namespace win {
-class StartupInformation;
-}
-}
-
-namespace sandbox {
-
-// Maintains an attribute list to be used during creation of a new sandboxed
-// process.
-class AppContainerAttributes {
- public:
- AppContainerAttributes();
- ~AppContainerAttributes();
-
- // Sets the AppContainer and capabilities to be used with the new process.
- ResultCode SetAppContainer(const base::string16& app_container_sid,
- const std::vector<base::string16>& capabilities);
-
- // Updates the proc_thred attribute list of the provided startup_information
- // with the app container related data.
- // WARNING: startup_information just points back to our internal memory, so
- // the lifetime of this object has to be greater than the lifetime of the
- // provided startup_information.
- ResultCode ShareForStartup(
- base::win::StartupInformation* startup_information) const;
-
- bool HasAppContainer() const;
-
- private:
- SECURITY_CAPABILITIES capabilities_;
- std::vector<SID_AND_ATTRIBUTES> attributes_;
-
- DISALLOW_COPY_AND_ASSIGN(AppContainerAttributes);
-};
-
-// Creates a new AppContainer on the system. |sid| is the identifier of the new
-// AppContainer, and |name| will be used as both the display name and moniker.
-// This function fails if the OS doesn't support AppContainers, or if there is
-// an AppContainer registered with the same id.
-ResultCode CreateAppContainer(const base::string16& sid,
- const base::string16& name);
-
-// Deletes an AppContainer previously created with a successful call to
-// CreateAppContainer.
-ResultCode DeleteAppContainer(const base::string16& sid);
-
-// Retrieves the name associated with the provided AppContainer sid. Returns an
-// empty string if the AppContainer is not registered with the system.
-base::string16 LookupAppContainer(const base::string16& sid);
-
-} // namespace sandbox
-
-#endif // SANDBOX_WIN_SRC_APP_CONTAINER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/app_container_test.cc b/security/sandbox/chromium/sandbox/win/src/app_container_test.cc
deleted file mode 100644
index ced5cbde7..000000000
--- a/security/sandbox/chromium/sandbox/win/src/app_container_test.cc
+++ /dev/null
@@ -1,161 +0,0 @@
-// 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.
-
-#include <windows.h>
-
-#define _ATL_NO_EXCEPTIONS
-#include <atlbase.h>
-#include <atlsecurity.h>
-
-#include "base/strings/string16.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/sync_policy_test.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-
-const wchar_t kAppContainerName[] = L"sbox_test";
-const wchar_t kAppContainerSid[] =
- L"S-1-15-2-3251537155-1984446955-2931258699-841473695-1938553385-"
- L"924012148-2839372144";
-
-const ULONG kSharing = FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE;
-
-HANDLE CreateTaggedEvent(const base::string16& name,
- const base::string16& sid) {
- base::win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, name.c_str()));
- if (!event.IsValid())
- return NULL;
-
- wchar_t file_name[MAX_PATH] = {};
- wchar_t temp_directory[MAX_PATH] = {};
- GetTempPath(MAX_PATH, temp_directory);
- GetTempFileName(temp_directory, L"test", 0, file_name);
-
- base::win::ScopedHandle file;
- file.Set(CreateFile(file_name, GENERIC_READ | STANDARD_RIGHTS_READ, kSharing,
- NULL, OPEN_EXISTING, 0, NULL));
- DeleteFile(file_name);
- if (!file.IsValid())
- return NULL;
-
- CSecurityDesc sd;
- if (!AtlGetSecurityDescriptor(file.Get(), SE_FILE_OBJECT, &sd,
- OWNER_SECURITY_INFORMATION |
- GROUP_SECURITY_INFORMATION |
- DACL_SECURITY_INFORMATION)) {
- return NULL;
- }
-
- PSID local_sid;
- if (!ConvertStringSidToSid(sid.c_str(), &local_sid))
- return NULL;
-
- CDacl new_dacl;
- sd.GetDacl(&new_dacl);
- CSid csid(reinterpret_cast<SID*>(local_sid));
- new_dacl.AddAllowedAce(csid, EVENT_ALL_ACCESS);
- if (!AtlSetDacl(event.Get(), SE_KERNEL_OBJECT, new_dacl))
- event.Close();
-
- LocalFree(local_sid);
- return event.IsValid() ? event.Take() : NULL;
-}
-
-} // namespace
-
-namespace sandbox {
-
-TEST(AppContainerTest, AllowOpenEvent) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner(JOB_UNPROTECTED, USER_UNPROTECTED, USER_UNPROTECTED);
-
- const wchar_t capability[] = L"S-1-15-3-12345678-87654321";
- base::win::ScopedHandle handle(CreateTaggedEvent(L"test", capability));
- ASSERT_TRUE(handle.IsValid());
-
- EXPECT_EQ(SBOX_ALL_OK,
- runner.broker()->InstallAppContainer(kAppContainerSid,
- kAppContainerName));
- EXPECT_EQ(SBOX_ALL_OK, runner.GetPolicy()->SetCapability(capability));
- EXPECT_EQ(SBOX_ALL_OK, runner.GetPolicy()->SetAppContainer(kAppContainerSid));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_Open f test"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_Open f test"));
- EXPECT_EQ(SBOX_ALL_OK,
- runner.broker()->UninstallAppContainer(kAppContainerSid));
-}
-
-TEST(AppContainerTest, DenyOpenEvent) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner(JOB_UNPROTECTED, USER_UNPROTECTED, USER_UNPROTECTED);
-
- const wchar_t capability[] = L"S-1-15-3-12345678-87654321";
- base::win::ScopedHandle handle(CreateTaggedEvent(L"test", capability));
- ASSERT_TRUE(handle.IsValid());
-
- EXPECT_EQ(SBOX_ALL_OK,
- runner.broker()->InstallAppContainer(kAppContainerSid,
- kAppContainerName));
- EXPECT_EQ(SBOX_ALL_OK, runner.GetPolicy()->SetAppContainer(kAppContainerSid));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test"));
- EXPECT_EQ(SBOX_ALL_OK,
- runner.broker()->UninstallAppContainer(kAppContainerSid));
-}
-
-TEST(AppContainerTest, NoImpersonation) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner(JOB_UNPROTECTED, USER_LIMITED, USER_LIMITED);
- EXPECT_EQ(SBOX_ALL_OK, runner.GetPolicy()->SetAppContainer(kAppContainerSid));
-}
-
-TEST(AppContainerTest, WantsImpersonation) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner(JOB_UNPROTECTED, USER_UNPROTECTED, USER_NON_ADMIN);
- EXPECT_EQ(SBOX_ERROR_CANNOT_INIT_APPCONTAINER,
- runner.GetPolicy()->SetAppContainer(kAppContainerSid));
-}
-
-TEST(AppContainerTest, RequiresImpersonation) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner(JOB_UNPROTECTED, USER_RESTRICTED, USER_RESTRICTED);
- EXPECT_EQ(SBOX_ERROR_CANNOT_INIT_APPCONTAINER,
- runner.GetPolicy()->SetAppContainer(kAppContainerSid));
-}
-
-TEST(AppContainerTest, DenyOpenEventForLowBox) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner(JOB_UNPROTECTED, USER_UNPROTECTED, USER_UNPROTECTED);
-
- base::win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, L"test"));
- ASSERT_TRUE(event.IsValid());
-
- EXPECT_EQ(SBOX_ALL_OK, runner.GetPolicy()->SetLowBox(kAppContainerSid));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test"));
-}
-
-// TODO(shrikant): Please add some tests to prove usage of lowbox token like
-// socket connection to local server in lock down mode.
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/app_container_unittest.cc b/security/sandbox/chromium/sandbox/win/src/app_container_unittest.cc
deleted file mode 100644
index 4bce16a42..000000000
--- a/security/sandbox/chromium/sandbox/win/src/app_container_unittest.cc
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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.
-
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/app_container.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-// Tests the low level AppContainer interface.
-TEST(AppContainerTest, CreateAppContainer) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return;
-
- const wchar_t kName[] = L"Test";
- const wchar_t kValidSid[] = L"S-1-15-2-12345-234-567-890-123-456-789";
-
- EXPECT_TRUE(LookupAppContainer(kValidSid).empty());
- EXPECT_EQ(SBOX_ERROR_GENERIC, DeleteAppContainer(kValidSid));
-
- EXPECT_EQ(SBOX_ALL_OK, CreateAppContainer(kValidSid, kName));
- EXPECT_EQ(SBOX_ERROR_GENERIC, CreateAppContainer(kValidSid, kName));
- EXPECT_EQ(kName, LookupAppContainer(kValidSid));
- EXPECT_EQ(SBOX_ALL_OK, DeleteAppContainer(kValidSid));
-
- EXPECT_TRUE(LookupAppContainer(kValidSid).empty());
- EXPECT_EQ(SBOX_ERROR_GENERIC, DeleteAppContainer(kValidSid));
-
- EXPECT_EQ(SBOX_ERROR_INVALID_APP_CONTAINER,
- CreateAppContainer(L"Foo", kName));
-}
-
-// Tests handling of security capabilities on the attribute list.
-TEST(AppContainerTest, SecurityCapabilities) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return;
-
- scoped_ptr<AppContainerAttributes> attributes(new AppContainerAttributes);
- std::vector<base::string16> capabilities;
- EXPECT_EQ(SBOX_ERROR_INVALID_APP_CONTAINER,
- attributes->SetAppContainer(L"S-1-foo", capabilities));
-
- EXPECT_EQ(SBOX_ALL_OK,
- attributes->SetAppContainer(L"S-1-15-2-12345-234", capabilities));
- EXPECT_TRUE(attributes->HasAppContainer());
-
- attributes.reset(new AppContainerAttributes);
- capabilities.push_back(L"S-1-15-3-12345678-87654321");
- capabilities.push_back(L"S-1-15-3-1");
- capabilities.push_back(L"S-1-15-3-2");
- capabilities.push_back(L"S-1-15-3-3");
- EXPECT_EQ(SBOX_ALL_OK,
- attributes->SetAppContainer(L"S-1-15-2-1-2", capabilities));
- EXPECT_TRUE(attributes->HasAppContainer());
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/broker_services.cc b/security/sandbox/chromium/sandbox/win/src/broker_services.cc
deleted file mode 100644
index d6acb66fd..000000000
--- a/security/sandbox/chromium/sandbox/win/src/broker_services.cc
+++ /dev/null
@@ -1,558 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/broker_services.h"
-
-#include <AclAPI.h>
-#include <stddef.h>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/stl_util.h"
-#include "base/threading/platform_thread.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/scoped_process_information.h"
-#include "base/win/startup_information.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/app_container.h"
-#include "sandbox/win/src/process_mitigations.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-#include "sandbox/win/src/target_process.h"
-#include "sandbox/win/src/win2k_threadpool.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-// Utility function to associate a completion port to a job object.
-bool AssociateCompletionPort(HANDLE job, HANDLE port, void* key) {
- JOBOBJECT_ASSOCIATE_COMPLETION_PORT job_acp = { key, port };
- return ::SetInformationJobObject(job,
- JobObjectAssociateCompletionPortInformation,
- &job_acp, sizeof(job_acp))? true : false;
-}
-
-// Utility function to do the cleanup necessary when something goes wrong
-// while in SpawnTarget and we must terminate the target process.
-sandbox::ResultCode SpawnCleanup(sandbox::TargetProcess* target, DWORD error) {
- if (0 == error)
- error = ::GetLastError();
-
- target->Terminate();
- delete target;
- ::SetLastError(error);
- return sandbox::SBOX_ERROR_GENERIC;
-}
-
-// the different commands that you can send to the worker thread that
-// executes TargetEventsThread().
-enum {
- THREAD_CTRL_NONE,
- THREAD_CTRL_REMOVE_PEER,
- THREAD_CTRL_QUIT,
- THREAD_CTRL_LAST,
-};
-
-// Helper structure that allows the Broker to associate a job notification
-// with a job object and with a policy.
-struct JobTracker {
- JobTracker(base::win::ScopedHandle job, sandbox::PolicyBase* policy)
- : job(job.Pass()), policy(policy) {
- }
- ~JobTracker() {
- FreeResources();
- }
-
- // Releases the Job and notifies the associated Policy object to release its
- // resources as well.
- void FreeResources();
-
- base::win::ScopedHandle job;
- sandbox::PolicyBase* policy;
-};
-
-void JobTracker::FreeResources() {
- if (policy) {
- BOOL res = ::TerminateJobObject(job.Get(), sandbox::SBOX_ALL_OK);
- DCHECK(res);
- // Closing the job causes the target process to be destroyed so this needs
- // to happen before calling OnJobEmpty().
- HANDLE stale_job_handle = job.Get();
- job.Close();
-
- // In OnJobEmpty() we don't actually use the job handle directly.
- policy->OnJobEmpty(stale_job_handle);
- policy->Release();
- policy = NULL;
- }
-}
-
-// Helper structure that allows the broker to track peer processes
-struct PeerTracker {
- PeerTracker(DWORD process_id, HANDLE broker_job_port)
- : wait_object(NULL), id(process_id), job_port(broker_job_port) {
- }
-
- HANDLE wait_object;
- base::win::ScopedHandle process;
- DWORD id;
- HANDLE job_port;
-};
-
-void DeregisterPeerTracker(PeerTracker* peer) {
- // Deregistration shouldn't fail, but we leak rather than crash if it does.
- if (::UnregisterWaitEx(peer->wait_object, INVALID_HANDLE_VALUE)) {
- delete peer;
- } else {
- NOTREACHED();
- }
-}
-
-} // namespace
-
-namespace sandbox {
-
-BrokerServicesBase::BrokerServicesBase() : thread_pool_(NULL) {
-}
-
-// The broker uses a dedicated worker thread that services the job completion
-// port to perform policy notifications and associated cleanup tasks.
-ResultCode BrokerServicesBase::Init() {
- if (job_port_.IsValid() || (NULL != thread_pool_))
- return SBOX_ERROR_UNEXPECTED_CALL;
-
- ::InitializeCriticalSection(&lock_);
-
- job_port_.Set(::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0));
- if (!job_port_.IsValid())
- return SBOX_ERROR_GENERIC;
-
- no_targets_.Set(::CreateEventW(NULL, TRUE, FALSE, NULL));
-
- job_thread_.Set(::CreateThread(NULL, 0, // Default security and stack.
- TargetEventsThread, this, NULL, NULL));
- if (!job_thread_.IsValid())
- return SBOX_ERROR_GENERIC;
-
- return SBOX_ALL_OK;
-}
-
-// The destructor should only be called when the Broker process is terminating.
-// Since BrokerServicesBase is a singleton, this is called from the CRT
-// termination handlers, if this code lives on a DLL it is called during
-// DLL_PROCESS_DETACH in other words, holding the loader lock, so we cannot
-// wait for threads here.
-BrokerServicesBase::~BrokerServicesBase() {
- // If there is no port Init() was never called successfully.
- if (!job_port_.IsValid())
- return;
-
- // Closing the port causes, that no more Job notifications are delivered to
- // the worker thread and also causes the thread to exit. This is what we
- // want to do since we are going to close all outstanding Jobs and notifying
- // the policy objects ourselves.
- ::PostQueuedCompletionStatus(job_port_.Get(), 0, THREAD_CTRL_QUIT, FALSE);
-
- if (job_thread_.IsValid() &&
- WAIT_TIMEOUT == ::WaitForSingleObject(job_thread_.Get(), 1000)) {
- // Cannot clean broker services.
- NOTREACHED();
- return;
- }
-
- STLDeleteElements(&tracker_list_);
- delete thread_pool_;
-
- // Cancel the wait events and delete remaining peer trackers.
- for (PeerTrackerMap::iterator it = peer_map_.begin();
- it != peer_map_.end(); ++it) {
- DeregisterPeerTracker(it->second);
- }
-
- ::DeleteCriticalSection(&lock_);
-}
-
-TargetPolicy* BrokerServicesBase::CreatePolicy() {
- // If you change the type of the object being created here you must also
- // change the downcast to it in SpawnTarget().
- return new PolicyBase;
-}
-
-// The worker thread stays in a loop waiting for asynchronous notifications
-// from the job objects. Right now we only care about knowing when the last
-// process on a job terminates, but in general this is the place to tell
-// the policy about events.
-DWORD WINAPI BrokerServicesBase::TargetEventsThread(PVOID param) {
- if (NULL == param)
- return 1;
-
- base::PlatformThread::SetName("BrokerEvent");
-
- BrokerServicesBase* broker = reinterpret_cast<BrokerServicesBase*>(param);
- HANDLE port = broker->job_port_.Get();
- HANDLE no_targets = broker->no_targets_.Get();
-
- int target_counter = 0;
- ::ResetEvent(no_targets);
-
- while (true) {
- DWORD events = 0;
- ULONG_PTR key = 0;
- LPOVERLAPPED ovl = NULL;
-
- if (!::GetQueuedCompletionStatus(port, &events, &key, &ovl, INFINITE)) {
- // this call fails if the port has been closed before we have a
- // chance to service the last packet which is 'exit' anyway so
- // this is not an error.
- return 1;
- }
-
- if (key > THREAD_CTRL_LAST) {
- // The notification comes from a job object. There are nine notifications
- // that jobs can send and some of them depend on the job attributes set.
- JobTracker* tracker = reinterpret_cast<JobTracker*>(key);
-
- switch (events) {
- case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: {
- // The job object has signaled that the last process associated
- // with it has terminated. Assuming there is no way for a process
- // to appear out of thin air in this job, it safe to assume that
- // we can tell the policy to destroy the target object, and for
- // us to release our reference to the policy object.
- tracker->FreeResources();
- break;
- }
-
- case JOB_OBJECT_MSG_NEW_PROCESS: {
- ++target_counter;
- if (1 == target_counter) {
- ::ResetEvent(no_targets);
- }
- break;
- }
-
- case JOB_OBJECT_MSG_EXIT_PROCESS:
- case JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: {
- {
- AutoLock lock(&broker->lock_);
- broker->child_process_ids_.erase(
- static_cast<DWORD>(reinterpret_cast<uintptr_t>(ovl)));
- }
- --target_counter;
- if (0 == target_counter)
- ::SetEvent(no_targets);
-
- DCHECK(target_counter >= 0);
- break;
- }
-
- case JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT: {
- break;
- }
-
- case JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT: {
- BOOL res = ::TerminateJobObject(tracker->job.Get(),
- SBOX_FATAL_MEMORY_EXCEEDED);
- DCHECK(res);
- break;
- }
-
- default: {
- NOTREACHED();
- break;
- }
- }
- } else if (THREAD_CTRL_REMOVE_PEER == key) {
- // Remove a process from our list of peers.
- AutoLock lock(&broker->lock_);
- PeerTrackerMap::iterator it = broker->peer_map_.find(
- static_cast<DWORD>(reinterpret_cast<uintptr_t>(ovl)));
- DeregisterPeerTracker(it->second);
- broker->peer_map_.erase(it);
- } else if (THREAD_CTRL_QUIT == key) {
- // The broker object is being destroyed so the thread needs to exit.
- return 0;
- } else {
- // We have not implemented more commands.
- NOTREACHED();
- }
- }
-
- NOTREACHED();
- return 0;
-}
-
-// SpawnTarget does all the interesting sandbox setup and creates the target
-// process inside the sandbox.
-ResultCode BrokerServicesBase::SpawnTarget(const wchar_t* exe_path,
- const wchar_t* command_line,
- TargetPolicy* policy,
- PROCESS_INFORMATION* target_info) {
- if (!exe_path)
- return SBOX_ERROR_BAD_PARAMS;
-
- if (!policy)
- return SBOX_ERROR_BAD_PARAMS;
-
- // Even though the resources touched by SpawnTarget can be accessed in
- // multiple threads, the method itself cannot be called from more than
- // 1 thread. This is to protect the global variables used while setting up
- // the child process.
- static DWORD thread_id = ::GetCurrentThreadId();
- DCHECK(thread_id == ::GetCurrentThreadId());
-
- AutoLock lock(&lock_);
-
- // This downcast is safe as long as we control CreatePolicy()
- PolicyBase* policy_base = static_cast<PolicyBase*>(policy);
-
- if (policy_base->GetAppContainer() && policy_base->GetLowBoxSid())
- return SBOX_ERROR_BAD_PARAMS;
-
- // Construct the tokens and the job object that we are going to associate
- // with the soon to be created target process.
- base::win::ScopedHandle initial_token;
- base::win::ScopedHandle lockdown_token;
- base::win::ScopedHandle lowbox_token;
- ResultCode result = SBOX_ALL_OK;
-
- result =
- policy_base->MakeTokens(&initial_token, &lockdown_token, &lowbox_token);
- if (SBOX_ALL_OK != result)
- return result;
-
- base::win::ScopedHandle job;
- result = policy_base->MakeJobObject(&job);
- if (SBOX_ALL_OK != result)
- return result;
-
- // Initialize the startup information from the policy.
- base::win::StartupInformation startup_info;
- // The liftime of |mitigations| and |inherit_handle_list| have to be at least
- // as long as |startup_info| because |UpdateProcThreadAttribute| requires that
- // its |lpValue| parameter persist until |DeleteProcThreadAttributeList| is
- // called; StartupInformation's destructor makes such a call.
- DWORD64 mitigations;
-
- std::vector<HANDLE> inherited_handle_list;
-
- base::string16 desktop = policy_base->GetAlternateDesktop();
- if (!desktop.empty()) {
- startup_info.startup_info()->lpDesktop =
- const_cast<wchar_t*>(desktop.c_str());
- }
-
- bool inherit_handles = false;
-
- if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
- int attribute_count = 0;
- const AppContainerAttributes* app_container =
- policy_base->GetAppContainer();
- if (app_container)
- ++attribute_count;
-
- size_t mitigations_size;
- ConvertProcessMitigationsToPolicy(policy->GetProcessMitigations(),
- &mitigations, &mitigations_size);
- if (mitigations)
- ++attribute_count;
-
- HANDLE stdout_handle = policy_base->GetStdoutHandle();
- HANDLE stderr_handle = policy_base->GetStderrHandle();
-
- if (stdout_handle != INVALID_HANDLE_VALUE)
- inherited_handle_list.push_back(stdout_handle);
-
- // Handles in the list must be unique.
- if (stderr_handle != stdout_handle && stderr_handle != INVALID_HANDLE_VALUE)
- inherited_handle_list.push_back(stderr_handle);
-
- const HandleList& policy_handle_list = policy_base->GetHandlesBeingShared();
-
- for (auto handle : policy_handle_list)
- inherited_handle_list.push_back(handle->Get());
-
- if (inherited_handle_list.size())
- ++attribute_count;
-
- if (!startup_info.InitializeProcThreadAttributeList(attribute_count))
- return SBOX_ERROR_PROC_THREAD_ATTRIBUTES;
-
- if (app_container) {
- result = app_container->ShareForStartup(&startup_info);
- if (SBOX_ALL_OK != result)
- return result;
- }
-
- if (mitigations) {
- if (!startup_info.UpdateProcThreadAttribute(
- PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY, &mitigations,
- mitigations_size)) {
- return SBOX_ERROR_PROC_THREAD_ATTRIBUTES;
- }
- }
-
- if (inherited_handle_list.size()) {
- if (!startup_info.UpdateProcThreadAttribute(
- PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
- &inherited_handle_list[0],
- sizeof(HANDLE) * inherited_handle_list.size())) {
- return SBOX_ERROR_PROC_THREAD_ATTRIBUTES;
- }
- startup_info.startup_info()->dwFlags |= STARTF_USESTDHANDLES;
- startup_info.startup_info()->hStdInput = INVALID_HANDLE_VALUE;
- startup_info.startup_info()->hStdOutput = stdout_handle;
- startup_info.startup_info()->hStdError = stderr_handle;
- // Allowing inheritance of handles is only secure now that we
- // have limited which handles will be inherited.
- inherit_handles = true;
- }
- } else if (getenv("MOZ_WIN_INHERIT_STD_HANDLES_PRE_VISTA")) {
- // On pre-Vista versions even if we can't limit what gets inherited, we
- // sometimes want to inherit stdout/err for testing purposes.
- startup_info.startup_info()->dwFlags |= STARTF_USESTDHANDLES;
- startup_info.startup_info()->hStdInput = INVALID_HANDLE_VALUE;
- startup_info.startup_info()->hStdOutput = policy_base->GetStdoutHandle();
- startup_info.startup_info()->hStdError = policy_base->GetStderrHandle();
- inherit_handles = true;
- }
-
- // Construct the thread pool here in case it is expensive.
- // The thread pool is shared by all the targets
- if (NULL == thread_pool_)
- thread_pool_ = new Win2kThreadPool();
-
- // Create the TargetProces object and spawn the target suspended. Note that
- // Brokerservices does not own the target object. It is owned by the Policy.
- base::win::ScopedProcessInformation process_info;
- TargetProcess* target =
- new TargetProcess(initial_token.Pass(), lockdown_token.Pass(),
- lowbox_token.Pass(), job.Get(), thread_pool_);
-
- DWORD win_result = target->Create(exe_path, command_line, inherit_handles,
- startup_info, &process_info);
-
- policy_base->ClearSharedHandles();
-
- if (ERROR_SUCCESS != win_result) {
- SpawnCleanup(target, win_result);
- return SBOX_ERROR_CREATE_PROCESS;
- }
-
- // Now the policy is the owner of the target.
- if (!policy_base->AddTarget(target)) {
- return SpawnCleanup(target, 0);
- }
-
- // We are going to keep a pointer to the policy because we'll call it when
- // the job object generates notifications using the completion port.
- policy_base->AddRef();
- if (job.IsValid()) {
- scoped_ptr<JobTracker> tracker(new JobTracker(job.Pass(), policy_base));
-
- // There is no obvious recovery after failure here. Previous version with
- // SpawnCleanup() caused deletion of TargetProcess twice. crbug.com/480639
- CHECK(AssociateCompletionPort(tracker->job.Get(), job_port_.Get(),
- tracker.get()));
-
- // Save the tracker because in cleanup we might need to force closing
- // the Jobs.
- tracker_list_.push_back(tracker.release());
- child_process_ids_.insert(process_info.process_id());
- } else {
- // We have to signal the event once here because the completion port will
- // never get a message that this target is being terminated thus we should
- // not block WaitForAllTargets until we have at least one target with job.
- if (child_process_ids_.empty())
- ::SetEvent(no_targets_.Get());
- // We can not track the life time of such processes and it is responsibility
- // of the host application to make sure that spawned targets without jobs
- // are terminated when the main application don't need them anymore.
- // Sandbox policy engine needs to know that these processes are valid
- // targets for e.g. BrokerDuplicateHandle so track them as peer processes.
- AddTargetPeer(process_info.process_handle());
- }
-
- *target_info = process_info.Take();
- return SBOX_ALL_OK;
-}
-
-
-ResultCode BrokerServicesBase::WaitForAllTargets() {
- ::WaitForSingleObject(no_targets_.Get(), INFINITE);
- return SBOX_ALL_OK;
-}
-
-bool BrokerServicesBase::IsActiveTarget(DWORD process_id) {
- AutoLock lock(&lock_);
- return child_process_ids_.find(process_id) != child_process_ids_.end() ||
- peer_map_.find(process_id) != peer_map_.end();
-}
-
-VOID CALLBACK BrokerServicesBase::RemovePeer(PVOID parameter, BOOLEAN timeout) {
- PeerTracker* peer = reinterpret_cast<PeerTracker*>(parameter);
- // Don't check the return code because we this may fail (safely) at shutdown.
- ::PostQueuedCompletionStatus(
- peer->job_port, 0, THREAD_CTRL_REMOVE_PEER,
- reinterpret_cast<LPOVERLAPPED>(static_cast<uintptr_t>(peer->id)));
-}
-
-ResultCode BrokerServicesBase::AddTargetPeer(HANDLE peer_process) {
- scoped_ptr<PeerTracker> peer(new PeerTracker(::GetProcessId(peer_process),
- job_port_.Get()));
- if (!peer->id)
- return SBOX_ERROR_GENERIC;
-
- HANDLE process_handle;
- if (!::DuplicateHandle(::GetCurrentProcess(), peer_process,
- ::GetCurrentProcess(), &process_handle,
- SYNCHRONIZE, FALSE, 0)) {
- return SBOX_ERROR_GENERIC;
- }
- peer->process.Set(process_handle);
-
- AutoLock lock(&lock_);
- if (!peer_map_.insert(std::make_pair(peer->id, peer.get())).second)
- return SBOX_ERROR_BAD_PARAMS;
-
- if (!::RegisterWaitForSingleObject(
- &peer->wait_object, peer->process.Get(), RemovePeer, peer.get(),
- INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD)) {
- peer_map_.erase(peer->id);
- return SBOX_ERROR_GENERIC;
- }
-
- // Release the pointer since it will be cleaned up by the callback.
- ignore_result(peer.release());
- return SBOX_ALL_OK;
-}
-
-ResultCode BrokerServicesBase::InstallAppContainer(const wchar_t* sid,
- const wchar_t* name) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return SBOX_ERROR_UNSUPPORTED;
-
- base::string16 old_name = LookupAppContainer(sid);
- if (old_name.empty())
- return CreateAppContainer(sid, name);
-
- if (old_name != name)
- return SBOX_ERROR_INVALID_APP_CONTAINER;
-
- return SBOX_ALL_OK;
-}
-
-ResultCode BrokerServicesBase::UninstallAppContainer(const wchar_t* sid) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return SBOX_ERROR_UNSUPPORTED;
-
- base::string16 name = LookupAppContainer(sid);
- if (name.empty())
- return SBOX_ERROR_INVALID_APP_CONTAINER;
-
- return DeleteAppContainer(sid);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/broker_services.h b/security/sandbox/chromium/sandbox/win/src/broker_services.h
deleted file mode 100644
index 6c8f5231c..000000000
--- a/security/sandbox/chromium/sandbox/win/src/broker_services.h
+++ /dev/null
@@ -1,112 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_WIN_SRC_BROKER_SERVICES_H_
-#define SANDBOX_WIN_SRC_BROKER_SERVICES_H_
-
-#include <list>
-#include <map>
-#include <set>
-#include <utility>
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/job.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sharedmem_ipc_server.h"
-#include "sandbox/win/src/win2k_threadpool.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-struct JobTracker;
-struct PeerTracker;
-
-} // namespace
-
-namespace sandbox {
-
-class PolicyBase;
-
-// BrokerServicesBase ---------------------------------------------------------
-// Broker implementation version 0
-//
-// This is an implementation of the interface BrokerServices and
-// of the associated TargetProcess interface. In this implementation
-// TargetProcess is a friend of BrokerServices where the later manages a
-// collection of the former.
-class BrokerServicesBase final : public BrokerServices,
- public SingletonBase<BrokerServicesBase> {
- public:
- BrokerServicesBase();
-
- ~BrokerServicesBase();
-
- // BrokerServices interface.
- ResultCode Init() override;
- TargetPolicy* CreatePolicy() override;
- ResultCode SpawnTarget(const wchar_t* exe_path,
- const wchar_t* command_line,
- TargetPolicy* policy,
- PROCESS_INFORMATION* target) override;
- ResultCode WaitForAllTargets() override;
- ResultCode AddTargetPeer(HANDLE peer_process) override;
- ResultCode InstallAppContainer(const wchar_t* sid,
- const wchar_t* name) override;
- ResultCode UninstallAppContainer(const wchar_t* sid) override;
-
- // Checks if the supplied process ID matches one of the broker's active
- // target processes
- // Returns:
- // true if there is an active target process for this ID, otherwise false.
- bool IsActiveTarget(DWORD process_id);
-
- private:
- typedef std::list<JobTracker*> JobTrackerList;
- typedef std::map<DWORD, PeerTracker*> PeerTrackerMap;
-
- // The routine that the worker thread executes. It is in charge of
- // notifications and cleanup-related tasks.
- static DWORD WINAPI TargetEventsThread(PVOID param);
-
- // Removes a target peer from the process list if it expires.
- static VOID CALLBACK RemovePeer(PVOID parameter, BOOLEAN timeout);
-
- // The completion port used by the job objects to communicate events to
- // the worker thread.
- base::win::ScopedHandle job_port_;
-
- // Handle to a manual-reset event that is signaled when the total target
- // process count reaches zero.
- base::win::ScopedHandle no_targets_;
-
- // Handle to the worker thread that reacts to job notifications.
- base::win::ScopedHandle job_thread_;
-
- // Lock used to protect the list of targets from being modified by 2
- // threads at the same time.
- CRITICAL_SECTION lock_;
-
- // provides a pool of threads that are used to wait on the IPC calls.
- ThreadProvider* thread_pool_;
-
- // List of the trackers for closing and cleanup purposes.
- JobTrackerList tracker_list_;
-
- // Maps peer process IDs to the saved handle and wait event.
- // Prevents peer callbacks from accessing the broker after destruction.
- PeerTrackerMap peer_map_;
-
- // Provides a fast lookup to identify sandboxed processes that belong to a
- // job. Consult |jobless_process_handles_| for handles of pocess without job.
- std::set<DWORD> child_process_ids_;
-
- DISALLOW_COPY_AND_ASSIGN(BrokerServicesBase);
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_WIN_SRC_BROKER_SERVICES_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/crosscall_client.h b/security/sandbox/chromium/sandbox/win/src/crosscall_client.h
deleted file mode 100644
index 60ff2437a..000000000
--- a/security/sandbox/chromium/sandbox/win/src/crosscall_client.h
+++ /dev/null
@@ -1,526 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_CROSSCALL_CLIENT_H_
-#define SANDBOX_SRC_CROSSCALL_CLIENT_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "sandbox/win/src/crosscall_params.h"
-#include "sandbox/win/src/sandbox.h"
-
-// This header defines the CrossCall(..) family of templated functions
-// Their purpose is to simulate the syntax of regular call but to generate
-// and IPC from the client-side.
-//
-// The basic pattern is to
-// 1) use template argument deduction to compute the size of each
-// parameter and the appropriate copy method
-// 2) pack the parameters in the appropriate ActualCallParams< > object
-// 3) call the IPC interface IPCProvider::DoCall( )
-//
-// The general interface of CrossCall is:
-// ResultCode CrossCall(IPCProvider& ipc_provider,
-// uint32_t tag,
-// const Par1& p1, const Par2& p2,...pn
-// CrossCallReturn* answer)
-//
-// where:
-// ipc_provider: is a specific implementation of the ipc transport see
-// sharedmem_ipc_server.h for an example.
-// tag : is the unique id for this IPC call. Is used to route the call to
-// the appropriate service.
-// p1, p2,.. pn : The input parameters of the IPC. Use only simple types
-// and wide strings (can add support for others).
-// answer : If the IPC was successful. The server-side answer is here. The
-// interpretation of the answer is private to client and server.
-//
-// The return value is ALL_OK if the IPC was delivered to the server, other
-// return codes indicate that the IPC transport failed to deliver it.
-namespace sandbox {
-
-// this is the assumed channel size. This can be overridden in a given
-// IPC implementation.
-const uint32_t kIPCChannelSize = 1024;
-
-// The copy helper uses templates to deduce the appropriate copy function to
-// copy the input parameters in the buffer that is going to be send across the
-// IPC. These template facility can be made more sophisticated as need arises.
-
-// The default copy helper. It catches the general case where no other
-// specialized template matches better. We set the type to UINT32_TYPE, so this
-// only works with objects whose size is 32 bits.
-template<typename T>
-class CopyHelper {
- public:
- CopyHelper(const T& t) : t_(t) {}
-
- // Returns the pointer to the start of the input.
- const void* GetStart() const {
- return &t_;
- }
-
- // Update the stored value with the value in the buffer. This is not
- // supported for this type.
- bool Update(void* buffer) {
- // Not supported;
- return true;
- }
-
- // Returns the size of the input in bytes.
- uint32_t GetSize() const { return sizeof(T); }
-
- // Returns true if the current type is used as an In or InOut parameter.
- bool IsInOut() {
- return false;
- }
-
- // Returns this object's type.
- ArgType GetType() {
- static_assert(sizeof(T) == sizeof(uint32_t), "specialization needed");
- return UINT32_TYPE;
- }
-
- private:
- const T& t_;
-};
-
-// This copy helper template specialization if for the void pointer
-// case both 32 and 64 bit.
-template<>
-class CopyHelper<void*> {
- public:
- CopyHelper(void* t) : t_(t) {}
-
- // Returns the pointer to the start of the input.
- const void* GetStart() const {
- return &t_;
- }
-
- // Update the stored value with the value in the buffer. This is not
- // supported for this type.
- bool Update(void* buffer) {
- // Not supported;
- return true;
- }
-
- // Returns the size of the input in bytes.
- uint32_t GetSize() const { return sizeof(t_); }
-
- // Returns true if the current type is used as an In or InOut parameter.
- bool IsInOut() {
- return false;
- }
-
- // Returns this object's type.
- ArgType GetType() {
- return VOIDPTR_TYPE;
- }
-
- private:
- const void* t_;
-};
-
-// This copy helper template specialization catches the cases where the
-// parameter is a pointer to a string.
-template<>
-class CopyHelper<const wchar_t*> {
- public:
- CopyHelper(const wchar_t* t)
- : t_(t) {
- }
-
- // Returns the pointer to the start of the string.
- const void* GetStart() const {
- return t_;
- }
-
- // Update the stored value with the value in the buffer. This is not
- // supported for this type.
- bool Update(void* buffer) {
- // Not supported;
- return true;
- }
-
- // Returns the size of the string in bytes. We define a NULL string to
- // be of zero length.
- uint32_t GetSize() const {
- __try {
- return (!t_) ? 0
- : static_cast<uint32_t>(StringLength(t_) * sizeof(t_[0]));
- }
- __except(EXCEPTION_EXECUTE_HANDLER) {
- return UINT32_MAX;
- }
- }
-
- // Returns true if the current type is used as an In or InOut parameter.
- bool IsInOut() {
- return false;
- }
-
- ArgType GetType() {
- return WCHAR_TYPE;
- }
-
- private:
- // We provide our not very optimized version of wcslen(), since we don't
- // want to risk having the linker use the version in the CRT since the CRT
- // might not be present when we do an early IPC call.
- static size_t __cdecl StringLength(const wchar_t* wcs) {
- const wchar_t *eos = wcs;
- while (*eos++);
- return static_cast<size_t>(eos - wcs - 1);
- }
-
- const wchar_t* t_;
-};
-
-// Specialization for non-const strings. We just reuse the implementation of the
-// const string specialization.
-template<>
-class CopyHelper<wchar_t*> : public CopyHelper<const wchar_t*> {
- public:
- typedef CopyHelper<const wchar_t*> Base;
- CopyHelper(wchar_t* t) : Base(t) {}
-
- const void* GetStart() const {
- return Base::GetStart();
- }
-
- bool Update(void* buffer) {
- return Base::Update(buffer);
- }
-
- uint32_t GetSize() const { return Base::GetSize(); }
-
- bool IsInOut() {
- return Base::IsInOut();
- }
-
- ArgType GetType() {
- return Base::GetType();
- }
-};
-
-// Specialization for wchar_t arrays strings. We just reuse the implementation
-// of the const string specialization.
-template<size_t n>
-class CopyHelper<const wchar_t[n]> : public CopyHelper<const wchar_t*> {
- public:
- typedef const wchar_t array[n];
- typedef CopyHelper<const wchar_t*> Base;
- CopyHelper(array t) : Base(t) {}
-
- const void* GetStart() const {
- return Base::GetStart();
- }
-
- bool Update(void* buffer) {
- return Base::Update(buffer);
- }
-
- uint32_t GetSize() const { return Base::GetSize(); }
-
- bool IsInOut() {
- return Base::IsInOut();
- }
-
- ArgType GetType() {
- return Base::GetType();
- }
-};
-
-// Generic encapsulation class containing a pointer to a buffer and the
-// size of the buffer. It is used by the IPC to be able to pass in/out
-// parameters.
-class InOutCountedBuffer : public CountedBuffer {
- public:
- InOutCountedBuffer(void* buffer, uint32_t size)
- : CountedBuffer(buffer, size) {}
-};
-
-// This copy helper template specialization catches the cases where the
-// parameter is a an input/output buffer.
-template<>
-class CopyHelper<InOutCountedBuffer> {
- public:
- CopyHelper(const InOutCountedBuffer t) : t_(t) {}
-
- // Returns the pointer to the start of the string.
- const void* GetStart() const {
- return t_.Buffer();
- }
-
- // Updates the buffer with the value from the new buffer in parameter.
- bool Update(void* buffer) {
- // We are touching user memory, this has to be done from inside a try
- // except.
- __try {
- memcpy(t_.Buffer(), buffer, t_.Size());
- }
- __except(EXCEPTION_EXECUTE_HANDLER) {
- return false;
- }
- return true;
- }
-
- // Returns the size of the string in bytes. We define a NULL string to
- // be of zero length.
- uint32_t GetSize() const { return t_.Size(); }
-
- // Returns true if the current type is used as an In or InOut parameter.
- bool IsInOut() {
- return true;
- }
-
- ArgType GetType() {
- return INOUTPTR_TYPE;
- }
-
- private:
- const InOutCountedBuffer t_;
-};
-
-// The following two macros make it less error prone the generation
-// of CrossCall functions with ever more input parameters.
-
-#define XCALL_GEN_PARAMS_OBJ(num, params) \
- typedef ActualCallParams<num, kIPCChannelSize> ActualParams; \
- void* raw_mem = ipc_provider.GetBuffer(); \
- if (NULL == raw_mem) \
- return SBOX_ERROR_NO_SPACE; \
- ActualParams* params = new(raw_mem) ActualParams(tag);
-
-#define XCALL_GEN_COPY_PARAM(num, params) \
- static_assert(kMaxIpcParams >= num, "too many parameters"); \
- CopyHelper<Par##num> ch##num(p##num); \
- if (!params->CopyParamIn(num - 1, ch##num.GetStart(), ch##num.GetSize(), \
- ch##num.IsInOut(), ch##num.GetType())) \
- return SBOX_ERROR_NO_SPACE;
-
-#define XCALL_GEN_UPDATE_PARAM(num, params) \
- if (!ch##num.Update(params->GetParamPtr(num-1))) {\
- ipc_provider.FreeBuffer(raw_mem); \
- return SBOX_ERROR_BAD_PARAMS; \
- }
-
-#define XCALL_GEN_FREE_CHANNEL() \
- ipc_provider.FreeBuffer(raw_mem);
-
-// CrossCall template with one input parameter
-template <typename IPCProvider, typename Par1>
-ResultCode CrossCall(IPCProvider& ipc_provider,
- uint32_t tag,
- const Par1& p1,
- CrossCallReturn* answer) {
- XCALL_GEN_PARAMS_OBJ(1, call_params);
- XCALL_GEN_COPY_PARAM(1, call_params);
-
- ResultCode result = ipc_provider.DoCall(call_params, answer);
-
- if (SBOX_ERROR_CHANNEL_ERROR != result) {
- XCALL_GEN_UPDATE_PARAM(1, call_params);
- XCALL_GEN_FREE_CHANNEL();
- }
-
- return result;
-}
-
-// CrossCall template with two input parameters.
-template <typename IPCProvider, typename Par1, typename Par2>
-ResultCode CrossCall(IPCProvider& ipc_provider,
- uint32_t tag,
- const Par1& p1,
- const Par2& p2,
- CrossCallReturn* answer) {
- XCALL_GEN_PARAMS_OBJ(2, call_params);
- XCALL_GEN_COPY_PARAM(1, call_params);
- XCALL_GEN_COPY_PARAM(2, call_params);
-
- ResultCode result = ipc_provider.DoCall(call_params, answer);
-
- if (SBOX_ERROR_CHANNEL_ERROR != result) {
- XCALL_GEN_UPDATE_PARAM(1, call_params);
- XCALL_GEN_UPDATE_PARAM(2, call_params);
- XCALL_GEN_FREE_CHANNEL();
- }
- return result;
-}
-
-// CrossCall template with three input parameters.
-template <typename IPCProvider, typename Par1, typename Par2, typename Par3>
-ResultCode CrossCall(IPCProvider& ipc_provider,
- uint32_t tag,
- const Par1& p1,
- const Par2& p2,
- const Par3& p3,
- CrossCallReturn* answer) {
- XCALL_GEN_PARAMS_OBJ(3, call_params);
- XCALL_GEN_COPY_PARAM(1, call_params);
- XCALL_GEN_COPY_PARAM(2, call_params);
- XCALL_GEN_COPY_PARAM(3, call_params);
-
- ResultCode result = ipc_provider.DoCall(call_params, answer);
-
- if (SBOX_ERROR_CHANNEL_ERROR != result) {
- XCALL_GEN_UPDATE_PARAM(1, call_params);
- XCALL_GEN_UPDATE_PARAM(2, call_params);
- XCALL_GEN_UPDATE_PARAM(3, call_params);
- XCALL_GEN_FREE_CHANNEL();
- }
- return result;
-}
-
-// CrossCall template with four input parameters.
-template <typename IPCProvider,
- typename Par1,
- typename Par2,
- typename Par3,
- typename Par4>
-ResultCode CrossCall(IPCProvider& ipc_provider,
- uint32_t tag,
- const Par1& p1,
- const Par2& p2,
- const Par3& p3,
- const Par4& p4,
- CrossCallReturn* answer) {
- XCALL_GEN_PARAMS_OBJ(4, call_params);
- XCALL_GEN_COPY_PARAM(1, call_params);
- XCALL_GEN_COPY_PARAM(2, call_params);
- XCALL_GEN_COPY_PARAM(3, call_params);
- XCALL_GEN_COPY_PARAM(4, call_params);
-
- ResultCode result = ipc_provider.DoCall(call_params, answer);
-
- if (SBOX_ERROR_CHANNEL_ERROR != result) {
- XCALL_GEN_UPDATE_PARAM(1, call_params);
- XCALL_GEN_UPDATE_PARAM(2, call_params);
- XCALL_GEN_UPDATE_PARAM(3, call_params);
- XCALL_GEN_UPDATE_PARAM(4, call_params);
- XCALL_GEN_FREE_CHANNEL();
- }
- return result;
-}
-
-// CrossCall template with five input parameters.
-template <typename IPCProvider,
- typename Par1,
- typename Par2,
- typename Par3,
- typename Par4,
- typename Par5>
-ResultCode CrossCall(IPCProvider& ipc_provider,
- uint32_t tag,
- const Par1& p1,
- const Par2& p2,
- const Par3& p3,
- const Par4& p4,
- const Par5& p5,
- CrossCallReturn* answer) {
- XCALL_GEN_PARAMS_OBJ(5, call_params);
- XCALL_GEN_COPY_PARAM(1, call_params);
- XCALL_GEN_COPY_PARAM(2, call_params);
- XCALL_GEN_COPY_PARAM(3, call_params);
- XCALL_GEN_COPY_PARAM(4, call_params);
- XCALL_GEN_COPY_PARAM(5, call_params);
-
- ResultCode result = ipc_provider.DoCall(call_params, answer);
-
- if (SBOX_ERROR_CHANNEL_ERROR != result) {
- XCALL_GEN_UPDATE_PARAM(1, call_params);
- XCALL_GEN_UPDATE_PARAM(2, call_params);
- XCALL_GEN_UPDATE_PARAM(3, call_params);
- XCALL_GEN_UPDATE_PARAM(4, call_params);
- XCALL_GEN_UPDATE_PARAM(5, call_params);
- XCALL_GEN_FREE_CHANNEL();
- }
- return result;
-}
-
-// CrossCall template with six input parameters.
-template <typename IPCProvider,
- typename Par1,
- typename Par2,
- typename Par3,
- typename Par4,
- typename Par5,
- typename Par6>
-ResultCode CrossCall(IPCProvider& ipc_provider,
- uint32_t tag,
- const Par1& p1,
- const Par2& p2,
- const Par3& p3,
- const Par4& p4,
- const Par5& p5,
- const Par6& p6,
- CrossCallReturn* answer) {
- XCALL_GEN_PARAMS_OBJ(6, call_params);
- XCALL_GEN_COPY_PARAM(1, call_params);
- XCALL_GEN_COPY_PARAM(2, call_params);
- XCALL_GEN_COPY_PARAM(3, call_params);
- XCALL_GEN_COPY_PARAM(4, call_params);
- XCALL_GEN_COPY_PARAM(5, call_params);
- XCALL_GEN_COPY_PARAM(6, call_params);
-
- ResultCode result = ipc_provider.DoCall(call_params, answer);
-
- if (SBOX_ERROR_CHANNEL_ERROR != result) {
- XCALL_GEN_UPDATE_PARAM(1, call_params);
- XCALL_GEN_UPDATE_PARAM(2, call_params);
- XCALL_GEN_UPDATE_PARAM(3, call_params);
- XCALL_GEN_UPDATE_PARAM(4, call_params);
- XCALL_GEN_UPDATE_PARAM(5, call_params);
- XCALL_GEN_UPDATE_PARAM(6, call_params);
- XCALL_GEN_FREE_CHANNEL();
- }
- return result;
-}
-
-// CrossCall template with seven input parameters.
-template <typename IPCProvider,
- typename Par1,
- typename Par2,
- typename Par3,
- typename Par4,
- typename Par5,
- typename Par6,
- typename Par7>
-ResultCode CrossCall(IPCProvider& ipc_provider,
- uint32_t tag,
- const Par1& p1,
- const Par2& p2,
- const Par3& p3,
- const Par4& p4,
- const Par5& p5,
- const Par6& p6,
- const Par7& p7,
- CrossCallReturn* answer) {
- XCALL_GEN_PARAMS_OBJ(7, call_params);
- XCALL_GEN_COPY_PARAM(1, call_params);
- XCALL_GEN_COPY_PARAM(2, call_params);
- XCALL_GEN_COPY_PARAM(3, call_params);
- XCALL_GEN_COPY_PARAM(4, call_params);
- XCALL_GEN_COPY_PARAM(5, call_params);
- XCALL_GEN_COPY_PARAM(6, call_params);
- XCALL_GEN_COPY_PARAM(7, call_params);
-
- ResultCode result = ipc_provider.DoCall(call_params, answer);
-
- if (SBOX_ERROR_CHANNEL_ERROR != result) {
- XCALL_GEN_UPDATE_PARAM(1, call_params);
- XCALL_GEN_UPDATE_PARAM(2, call_params);
- XCALL_GEN_UPDATE_PARAM(3, call_params);
- XCALL_GEN_UPDATE_PARAM(4, call_params);
- XCALL_GEN_UPDATE_PARAM(5, call_params);
- XCALL_GEN_UPDATE_PARAM(6, call_params);
- XCALL_GEN_UPDATE_PARAM(7, call_params);
- XCALL_GEN_FREE_CHANNEL();
- }
- return result;
-}
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_CROSSCALL_CLIENT_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/crosscall_params.h b/security/sandbox/chromium/sandbox/win/src/crosscall_params.h
deleted file mode 100644
index eb59c4423..000000000
--- a/security/sandbox/chromium/sandbox/win/src/crosscall_params.h
+++ /dev/null
@@ -1,287 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_CROSSCALL_PARAMS_H__
-#define SANDBOX_SRC_CROSSCALL_PARAMS_H__
-
-#include <windows.h>
-#include <lmaccess.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include <memory>
-
-#include "base/macros.h"
-#include "sandbox/win/src/internal_types.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-// Increases |value| until there is no need for padding given an int64_t
-// alignment. Returns the increased value.
-inline uint32_t Align(uint32_t value) {
- uint32_t alignment = sizeof(int64_t);
- return ((value + alignment - 1) / alignment) * alignment;
-}
-
-// This header is part of CrossCall: the sandbox inter-process communication.
-// This header defines the basic types used both in the client IPC and in the
-// server IPC code. CrossCallParams and ActualCallParams model the input
-// parameters of an IPC call and CrossCallReturn models the output params and
-// the return value.
-//
-// An IPC call is defined by its 'tag' which is a (uint32_t) unique identifier
-// that is used to route the IPC call to the proper server. Every tag implies
-// a complete call signature including the order and type of each parameter.
-//
-// Like most IPC systems. CrossCall is designed to take as inputs 'simple'
-// types such as integers and strings. Classes, generic arrays or pointers to
-// them are not supported.
-//
-// Another limitation of CrossCall is that the return value and output
-// parameters can only be uint32_t integers. Returning complex structures or
-// strings is not supported.
-
-namespace sandbox {
-
-// max number of extended return parameters. See CrossCallReturn
-const size_t kExtendedReturnCount = 8;
-
-// Union of multiple types to be used as extended results
-// in the CrossCallReturn.
-union MultiType {
- uint32_t unsigned_int;
- void* pointer;
- HANDLE handle;
- ULONG_PTR ulong_ptr;
-};
-
-// Maximum number of IPC parameters currently supported.
-// To increase this value, we have to:
-// - Add another Callback typedef to Dispatcher.
-// - Add another case to the switch on SharedMemIPCServer::InvokeCallback.
-// - Add another case to the switch in GetActualAndMaxBufferSize
-const int kMaxIpcParams = 9;
-
-// Contains the information about a parameter in the ipc buffer.
-struct ParamInfo {
- ArgType type_;
- uint32_t offset_;
- uint32_t size_;
-};
-
-// Models the return value and the return parameters of an IPC call
-// currently limited to one status code and eight generic return values
-// which cannot be pointers to other data. For x64 ports this structure
-// might have to use other integer types.
-struct CrossCallReturn {
- // the IPC tag. It should match the original IPC tag.
- uint32_t tag;
- // The result of the IPC operation itself.
- ResultCode call_outcome;
- // the result of the IPC call as executed in the server. The interpretation
- // of this value depends on the specific service.
- union {
- NTSTATUS nt_status;
- DWORD win32_result;
- };
- // Number of extended return values.
- uint32_t extended_count;
- // for calls that should return a windows handle. It is found here.
- HANDLE handle;
- // The array of extended values.
- MultiType extended[kExtendedReturnCount];
-};
-
-// CrossCallParams base class that models the input params all packed in a
-// single compact memory blob. The representation can vary but in general a
-// given child of this class is meant to represent all input parameters
-// necessary to make a IPC call.
-//
-// This class cannot have virtual members because its assumed the IPC
-// parameters start from the 'this' pointer to the end, which is defined by
-// one of the subclasses
-//
-// Objects of this class cannot be constructed directly. Only derived
-// classes have the proper knowledge to construct it.
-class CrossCallParams {
- public:
- // Returns the tag (ipc unique id) associated with this IPC.
- uint32_t GetTag() const { return tag_; }
-
- // Returns the beggining of the buffer where the IPC params can be stored.
- // prior to an IPC call
- const void* GetBuffer() const {
- return this;
- }
-
- // Returns how many parameter this IPC call should have.
- uint32_t GetParamsCount() const { return params_count_; }
-
- // Returns a pointer to the CrossCallReturn structure.
- CrossCallReturn* GetCallReturn() {
- return &call_return;
- }
-
- // Returns TRUE if this call contains InOut parameters.
- bool IsInOut() const { return (1 == is_in_out_); }
-
- // Tells the CrossCall object if it contains InOut parameters.
- void SetIsInOut(bool value) {
- if (value)
- is_in_out_ = 1;
- else
- is_in_out_ = 0;
- }
-
- protected:
- // constructs the IPC call params. Called only from the derived classes
- CrossCallParams(uint32_t tag, uint32_t params_count)
- : tag_(tag), is_in_out_(0), params_count_(params_count) {}
-
- private:
- uint32_t tag_;
- uint32_t is_in_out_;
- CrossCallReturn call_return;
- const uint32_t params_count_;
- DISALLOW_COPY_AND_ASSIGN(CrossCallParams);
-};
-
-// ActualCallParams models an specific IPC call parameters with respect to the
-// storage allocation that the packed parameters should need.
-// NUMBER_PARAMS: the number of parameters, valid from 1 to N
-// BLOCK_SIZE: the total storage that the NUMBER_PARAMS parameters can take,
-// typically the block size is defined by the channel size of the underlying
-// ipc mechanism.
-// In practice this class is used to levergage C++ capacity to properly
-// calculate sizes and displacements given the possibility of the packed params
-// blob to be complex.
-//
-// As is, this class assumes that the layout of the blob is as follows. Assume
-// that NUMBER_PARAMS = 2 and a 32-bit build:
-//
-// [ tag 4 bytes]
-// [ IsOnOut 4 bytes]
-// [ call return 52 bytes]
-// [ params count 4 bytes]
-// [ parameter 0 type 4 bytes]
-// [ parameter 0 offset 4 bytes] ---delta to ---\
-// [ parameter 0 size 4 bytes] |
-// [ parameter 1 type 4 bytes] |
-// [ parameter 1 offset 4 bytes] ---------------|--\
-// [ parameter 1 size 4 bytes] | |
-// [ parameter 2 type 4 bytes] | |
-// [ parameter 2 offset 4 bytes] ----------------------\
-// [ parameter 2 size 4 bytes] | | |
-// |---------------------------| | | |
-// | value 0 (x bytes) | <--------------/ | |
-// | value 1 (y bytes) | <-----------------/ |
-// | | |
-// | end of buffer | <---------------------/
-// |---------------------------|
-//
-// Note that the actual number of params is NUMBER_PARAMS + 1
-// so that the size of each actual param can be computed from the difference
-// between one parameter and the next down. The offset of the last param
-// points to the end of the buffer and the type and size are undefined.
-//
-template <size_t NUMBER_PARAMS, size_t BLOCK_SIZE>
-class ActualCallParams : public CrossCallParams {
- public:
- // constructor. Pass the ipc unique tag as input
- explicit ActualCallParams(uint32_t tag)
- : CrossCallParams(tag, NUMBER_PARAMS) {
- param_info_[0].offset_ =
- static_cast<uint32_t>(parameters_ - reinterpret_cast<char*>(this));
- }
-
- // Testing-only constructor. Allows setting the |number_params| to a
- // wrong value.
- ActualCallParams(uint32_t tag, uint32_t number_params)
- : CrossCallParams(tag, number_params) {
- param_info_[0].offset_ =
- static_cast<uint32_t>(parameters_ - reinterpret_cast<char*>(this));
- }
-
- // Testing-only method. Allows setting the apparent size to a wrong value.
- // returns the previous size.
- uint32_t OverrideSize(uint32_t new_size) {
- uint32_t previous_size = param_info_[NUMBER_PARAMS].offset_;
- param_info_[NUMBER_PARAMS].offset_ = new_size;
- return previous_size;
- }
-
- // Copies each paramter into the internal buffer. For each you must supply:
- // index: 0 for the first param, 1 for the next an so on
- bool CopyParamIn(uint32_t index,
- const void* parameter_address,
- uint32_t size,
- bool is_in_out,
- ArgType type) {
- if (index >= NUMBER_PARAMS) {
- return false;
- }
-
- if (UINT32_MAX == size) {
- // Memory error while getting the size.
- return false;
- }
-
- if (size && !parameter_address) {
- return false;
- }
-
- if ((size > sizeof(*this)) ||
- (param_info_[index].offset_ > (sizeof(*this) - size))) {
- // It does not fit, abort copy.
- return false;
- }
-
- char* dest = reinterpret_cast<char*>(this) + param_info_[index].offset_;
-
- // We might be touching user memory, this has to be done from inside a try
- // except.
- __try {
- memcpy(dest, parameter_address, size);
- }
- __except(EXCEPTION_EXECUTE_HANDLER) {
- return false;
- }
-
- // Set the flag to tell the broker to update the buffer once the call is
- // made.
- if (is_in_out)
- SetIsInOut(true);
-
- param_info_[index + 1].offset_ = Align(param_info_[index].offset_ +
- size);
- param_info_[index].size_ = size;
- param_info_[index].type_ = type;
- return true;
- }
-
- // Returns a pointer to a parameter in the memory section.
- void* GetParamPtr(size_t index) {
- return reinterpret_cast<char*>(this) + param_info_[index].offset_;
- }
-
- // Returns the total size of the buffer. Only valid once all the paramters
- // have been copied in with CopyParamIn.
- uint32_t GetSize() const { return param_info_[NUMBER_PARAMS].offset_; }
-
- protected:
- ActualCallParams() : CrossCallParams(0, NUMBER_PARAMS) { }
-
- private:
- ParamInfo param_info_[NUMBER_PARAMS + 1];
- char parameters_[BLOCK_SIZE - sizeof(CrossCallParams)
- - sizeof(ParamInfo) * (NUMBER_PARAMS + 1)];
- DISALLOW_COPY_AND_ASSIGN(ActualCallParams);
-};
-
-static_assert(sizeof(ActualCallParams<1, 1024>) == 1024, "bad size buffer");
-static_assert(sizeof(ActualCallParams<2, 1024>) == 1024, "bad size buffer");
-static_assert(sizeof(ActualCallParams<3, 1024>) == 1024, "bad size buffer");
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_CROSSCALL_PARAMS_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/crosscall_server.cc b/security/sandbox/chromium/sandbox/win/src/crosscall_server.cc
deleted file mode 100644
index 9f71f333f..000000000
--- a/security/sandbox/chromium/sandbox/win/src/crosscall_server.cc
+++ /dev/null
@@ -1,314 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/crosscall_server.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <string>
-#include <vector>
-
-#include "base/logging.h"
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/crosscall_params.h"
-
-// This code performs the ipc message validation. Potential security flaws
-// on the ipc are likelier to be found in this code than in the rest of
-// the ipc code.
-
-namespace {
-
-// The buffer for a message must match the max channel size.
-const size_t kMaxBufferSize = sandbox::kIPCChannelSize;
-
-}
-
-namespace sandbox {
-
-// Returns the actual size for the parameters in an IPC buffer. Returns
-// zero if the |param_count| is zero or too big.
-uint32_t GetActualBufferSize(uint32_t param_count, void* buffer_base) {
- // The template types are used to calculate the maximum expected size.
- typedef ActualCallParams<1, kMaxBufferSize> ActualCP1;
- typedef ActualCallParams<2, kMaxBufferSize> ActualCP2;
- typedef ActualCallParams<3, kMaxBufferSize> ActualCP3;
- typedef ActualCallParams<4, kMaxBufferSize> ActualCP4;
- typedef ActualCallParams<5, kMaxBufferSize> ActualCP5;
- typedef ActualCallParams<6, kMaxBufferSize> ActualCP6;
- typedef ActualCallParams<7, kMaxBufferSize> ActualCP7;
- typedef ActualCallParams<8, kMaxBufferSize> ActualCP8;
- typedef ActualCallParams<9, kMaxBufferSize> ActualCP9;
-
- // Retrieve the actual size and the maximum size of the params buffer.
- switch (param_count) {
- case 0:
- return 0;
- case 1:
- return reinterpret_cast<ActualCP1*>(buffer_base)->GetSize();
- case 2:
- return reinterpret_cast<ActualCP2*>(buffer_base)->GetSize();
- case 3:
- return reinterpret_cast<ActualCP3*>(buffer_base)->GetSize();
- case 4:
- return reinterpret_cast<ActualCP4*>(buffer_base)->GetSize();
- case 5:
- return reinterpret_cast<ActualCP5*>(buffer_base)->GetSize();
- case 6:
- return reinterpret_cast<ActualCP6*>(buffer_base)->GetSize();
- case 7:
- return reinterpret_cast<ActualCP7*>(buffer_base)->GetSize();
- case 8:
- return reinterpret_cast<ActualCP8*>(buffer_base)->GetSize();
- case 9:
- return reinterpret_cast<ActualCP9*>(buffer_base)->GetSize();
- default:
- return 0;
- }
-}
-
-// Verifies that the declared sizes of an IPC buffer are within range.
-bool IsSizeWithinRange(uint32_t buffer_size,
- uint32_t min_declared_size,
- uint32_t declared_size) {
- if ((buffer_size < min_declared_size) ||
- (sizeof(CrossCallParamsEx) > min_declared_size)) {
- // Minimal computed size bigger than existing buffer or param_count
- // integer overflow.
- return false;
- }
-
- if ((declared_size > buffer_size) || (declared_size < min_declared_size)) {
- // Declared size is bigger than buffer or smaller than computed size
- // or param_count is equal to 0 or bigger than 9.
- return false;
- }
-
- return true;
-}
-
-CrossCallParamsEx::CrossCallParamsEx()
- :CrossCallParams(0, 0) {
-}
-
-// We override the delete operator because the object's backing memory
-// is hand allocated in CreateFromBuffer. We don't override the new operator
-// because the constructors are private so there is no way to mismatch
-// new & delete.
-void CrossCallParamsEx::operator delete(void* raw_memory) throw() {
- if (NULL == raw_memory) {
- // C++ standard allows 'delete 0' behavior.
- return;
- }
- delete[] reinterpret_cast<char*>(raw_memory);
-}
-
-// This function uses a SEH try block so cannot use C++ objects that
-// have destructors or else you get Compiler Error C2712. So no DCHECKs
-// inside this function.
-CrossCallParamsEx* CrossCallParamsEx::CreateFromBuffer(void* buffer_base,
- uint32_t buffer_size,
- uint32_t* output_size) {
- // IMPORTANT: Everything inside buffer_base and derived from it such
- // as param_count and declared_size is untrusted.
- if (NULL == buffer_base) {
- return NULL;
- }
- if (buffer_size < sizeof(CrossCallParams)) {
- return NULL;
- }
- if (buffer_size > kMaxBufferSize) {
- return NULL;
- }
-
- char* backing_mem = NULL;
- uint32_t param_count = 0;
- uint32_t declared_size;
- uint32_t min_declared_size;
- CrossCallParamsEx* copied_params = NULL;
-
- // Touching the untrusted buffer is done under a SEH try block. This
- // will catch memory access violations so we don't crash.
- __try {
- CrossCallParams* call_params =
- reinterpret_cast<CrossCallParams*>(buffer_base);
-
- // Check against the minimum size given the number of stated params
- // if too small we bail out.
- param_count = call_params->GetParamsCount();
- min_declared_size = sizeof(CrossCallParams) +
- ((param_count + 1) * sizeof(ParamInfo));
-
- // Retrieve the declared size which if it fails returns 0.
- declared_size = GetActualBufferSize(param_count, buffer_base);
-
- if (!IsSizeWithinRange(buffer_size, min_declared_size, declared_size))
- return NULL;
-
- // Now we copy the actual amount of the message.
- *output_size = declared_size;
- backing_mem = new char[declared_size];
- copied_params = reinterpret_cast<CrossCallParamsEx*>(backing_mem);
- memcpy(backing_mem, call_params, declared_size);
-
- // Avoid compiler optimizations across this point. Any value stored in
- // memory should be stored for real, and values previously read from memory
- // should be actually read.
- _ReadWriteBarrier();
-
- min_declared_size = sizeof(CrossCallParams) +
- ((param_count + 1) * sizeof(ParamInfo));
-
- // Check that the copied buffer is still valid.
- if (copied_params->GetParamsCount() != param_count ||
- GetActualBufferSize(param_count, backing_mem) != declared_size ||
- !IsSizeWithinRange(buffer_size, min_declared_size, declared_size)) {
- delete [] backing_mem;
- return NULL;
- }
-
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- // In case of a windows exception we know it occurred while touching the
- // untrusted buffer so we bail out as is.
- delete [] backing_mem;
- return NULL;
- }
-
- const char* last_byte = &backing_mem[declared_size];
- const char* first_byte = &backing_mem[min_declared_size];
-
- // Verify here that all and each parameters make sense. This is done in the
- // local copy.
- for (uint32_t ix = 0; ix != param_count; ++ix) {
- uint32_t size = 0;
- ArgType type;
- char* address = reinterpret_cast<char*>(
- copied_params->GetRawParameter(ix, &size, &type));
- if ((NULL == address) || // No null params.
- (INVALID_TYPE >= type) || (LAST_TYPE <= type) || // Unknown type.
- (address < backing_mem) || // Start cannot point before buffer.
- (address < first_byte) || // Start cannot point too low.
- (address > last_byte) || // Start cannot point past buffer.
- ((address + size) < address) || // Invalid size.
- ((address + size) > last_byte)) { // End cannot point past buffer.
- // Malformed.
- delete[] backing_mem;
- return NULL;
- }
- }
- // The parameter buffer looks good.
- return copied_params;
-}
-
-// Accessors to the parameters in the raw buffer.
-void* CrossCallParamsEx::GetRawParameter(uint32_t index,
- uint32_t* size,
- ArgType* type) {
- if (index >= GetParamsCount()) {
- return NULL;
- }
- // The size is always computed from the parameter minus the next
- // parameter, this works because the message has an extra parameter slot
- *size = param_info_[index].size_;
- *type = param_info_[index].type_;
-
- return param_info_[index].offset_ + reinterpret_cast<char*>(this);
-}
-
-// Covers common case for 32 bit integers.
-bool CrossCallParamsEx::GetParameter32(uint32_t index, uint32_t* param) {
- uint32_t size = 0;
- ArgType type;
- void* start = GetRawParameter(index, &size, &type);
- if ((NULL == start) || (4 != size) || (UINT32_TYPE != type)) {
- return false;
- }
- // Copy the 4 bytes.
- *(reinterpret_cast<uint32_t*>(param)) = *(reinterpret_cast<uint32_t*>(start));
- return true;
-}
-
-bool CrossCallParamsEx::GetParameterVoidPtr(uint32_t index, void** param) {
- uint32_t size = 0;
- ArgType type;
- void* start = GetRawParameter(index, &size, &type);
- if ((NULL == start) || (sizeof(void*) != size) || (VOIDPTR_TYPE != type)) {
- return false;
- }
- *param = *(reinterpret_cast<void**>(start));
- return true;
-}
-
-// Covers the common case of reading a string. Note that the string is not
-// scanned for invalid characters.
-bool CrossCallParamsEx::GetParameterStr(uint32_t index,
- base::string16* string) {
- uint32_t size = 0;
- ArgType type;
- void* start = GetRawParameter(index, &size, &type);
- if (WCHAR_TYPE != type) {
- return false;
- }
-
- // Check if this is an empty string.
- if (size == 0) {
- *string = L"";
- return true;
- }
-
- if ((NULL == start) || ((size % sizeof(wchar_t)) != 0)) {
- return false;
- }
- string->append(reinterpret_cast<wchar_t*>(start), size/(sizeof(wchar_t)));
- return true;
-}
-
-bool CrossCallParamsEx::GetParameterPtr(uint32_t index,
- uint32_t expected_size,
- void** pointer) {
- uint32_t size = 0;
- ArgType type;
- void* start = GetRawParameter(index, &size, &type);
-
- if ((size != expected_size) || (INOUTPTR_TYPE != type)) {
- return false;
- }
-
- if (NULL == start) {
- return false;
- }
-
- *pointer = start;
- return true;
-}
-
-void SetCallError(ResultCode error, CrossCallReturn* call_return) {
- call_return->call_outcome = error;
- call_return->extended_count = 0;
-}
-
-void SetCallSuccess(CrossCallReturn* call_return) {
- call_return->call_outcome = SBOX_ALL_OK;
-}
-
-Dispatcher* Dispatcher::OnMessageReady(IPCParams* ipc,
- CallbackGeneric* callback) {
- DCHECK(callback);
- std::vector<IPCCall>::iterator it = ipc_calls_.begin();
- for (; it != ipc_calls_.end(); ++it) {
- if (it->params.Matches(ipc)) {
- *callback = it->callback;
- return this;
- }
- }
- return NULL;
-}
-
-Dispatcher::Dispatcher() {
-}
-
-Dispatcher::~Dispatcher() {
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/crosscall_server.h b/security/sandbox/chromium/sandbox/win/src/crosscall_server.h
deleted file mode 100644
index 0820ac440..000000000
--- a/security/sandbox/chromium/sandbox/win/src/crosscall_server.h
+++ /dev/null
@@ -1,228 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_CROSSCALL_SERVER_H_
-#define SANDBOX_SRC_CROSSCALL_SERVER_H_
-
-#include <stdint.h>
-
-#include <string>
-#include <vector>
-
-#include "base/callback.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_params.h"
-
-// This is the IPC server interface for CrossCall: The IPC for the Sandbox
-// On the server, CrossCall needs two things:
-// 1) threads: Or better said, someone to provide them, that is what the
-// ThreadProvider interface is defined for. These thread(s) are
-// the ones that will actually execute the IPC data retrieval.
-//
-// 2) a dispatcher: This interface represents the way to route and process
-// an IPC call given the IPC tag.
-//
-// The other class included here CrossCallParamsEx is the server side version
-// of the CrossCallParams class of /sandbox/crosscall_params.h The difference
-// is that the sever version is paranoid about the correctness of the IPC
-// message and will do all sorts of verifications.
-//
-// A general diagram of the interaction is as follows:
-//
-// ------------
-// | |
-// ThreadProvider <--(1)Register--| IPC |
-// | | Implemen |
-// | | -tation |
-// (2) | | OnMessage
-// IPC fired --callback ------>| |--(3)---> Dispatcher
-// | |
-// ------------
-//
-// The IPC implementation sits as a middleman between the handling of the
-// specifics of scheduling a thread to service the IPC and the multiple
-// entities that can potentially serve each particular IPC.
-namespace sandbox {
-
-class InterceptionManager;
-
-// This function signature is required as the callback when an IPC call fires.
-// context: a user-defined pointer that was set using ThreadProvider
-// reason: 0 if the callback was fired because of a timeout.
-// 1 if the callback was fired because of an event.
-typedef void (__stdcall * CrossCallIPCCallback)(void* context,
- unsigned char reason);
-
-// ThreadProvider models a thread factory. The idea is to decouple thread
-// creation and lifetime from the inner guts of the IPC. The contract is
-// simple:
-// - the IPC implementation calls RegisterWait with a waitable object that
-// becomes signaled when an IPC arrives and needs to be serviced.
-// - when the waitable object becomes signaled, the thread provider conjures
-// a thread that calls the callback (CrossCallIPCCallback) function
-// - the callback function tries its best not to block and return quickly
-// and should not assume that the next callback will use the same thread
-// - when the callback returns the ThreadProvider owns again the thread
-// and can destroy it or keep it around.
-class ThreadProvider {
- public:
- // Registers a waitable object with the thread provider.
- // client: A number to associate with all the RegisterWait calls, typically
- // this is the address of the caller object. This parameter cannot
- // be zero.
- // waitable_object : a kernel object that can be waited on
- // callback: a function pointer which is the function that will be called
- // when the waitable object fires
- // context: a user-provider pointer that is passed back to the callback
- // when its called
- virtual bool RegisterWait(const void* client, HANDLE waitable_object,
- CrossCallIPCCallback callback,
- void* context) = 0;
-
- // Removes all the registrations done with the same cookie parameter.
- // This frees internal thread pool resources.
- virtual bool UnRegisterWaits(void* cookie) = 0;
- virtual ~ThreadProvider() {}
-};
-
-// Models the server-side of the original input parameters.
-// Provides IPC buffer validation and it is capable of reading the parameters
-// out of the IPC buffer.
-class CrossCallParamsEx : public CrossCallParams {
- public:
- // Factory constructor. Pass an IPCbuffer (and buffer size) that contains a
- // pending IPCcall. This constructor will:
- // 1) validate the IPC buffer. returns NULL is the IPCbuffer is malformed.
- // 2) make a copy of the IPCbuffer (parameter capture)
- static CrossCallParamsEx* CreateFromBuffer(void* buffer_base,
- uint32_t buffer_size,
- uint32_t* output_size);
-
- // Provides IPCinput parameter raw access:
- // index : the parameter to read; 0 is the first parameter
- // returns NULL if the parameter is non-existent. If it exists it also
- // returns the size in *size
- void* GetRawParameter(uint32_t index, uint32_t* size, ArgType* type);
-
- // Gets a parameter that is four bytes in size.
- // Returns false if the parameter does not exist or is not 32 bits wide.
- bool GetParameter32(uint32_t index, uint32_t* param);
-
- // Gets a parameter that is void pointer in size.
- // Returns false if the parameter does not exist or is not void pointer sized.
- bool GetParameterVoidPtr(uint32_t index, void** param);
-
- // Gets a parameter that is a string. Returns false if the parameter does not
- // exist.
- bool GetParameterStr(uint32_t index, base::string16* string);
-
- // Gets a parameter that is an in/out buffer. Returns false is the parameter
- // does not exist or if the size of the actual parameter is not equal to the
- // expected size.
- bool GetParameterPtr(uint32_t index, uint32_t expected_size, void** pointer);
-
- // Frees the memory associated with the IPC parameters.
- static void operator delete(void* raw_memory) throw();
-
- private:
- // Only the factory method CreateFromBuffer can construct these objects.
- CrossCallParamsEx();
-
- ParamInfo param_info_[1];
- DISALLOW_COPY_AND_ASSIGN(CrossCallParamsEx);
-};
-
-// Simple helper function that sets the members of CrossCallReturn
-// to the proper state to signal a basic error.
-void SetCallError(ResultCode error, CrossCallReturn* call_return);
-
-// Sets the internal status of call_return to signify the that IPC call
-// completed successfully.
-void SetCallSuccess(CrossCallReturn* call_return);
-
-// Represents the client process that initiated the IPC which boils down to the
-// process handle and the job object handle that contains the client process.
-struct ClientInfo {
- HANDLE process;
- DWORD process_id;
-};
-
-// All IPC-related information to be passed to the IPC handler.
-struct IPCInfo {
- int ipc_tag;
- const ClientInfo* client_info;
- CrossCallReturn return_info;
-};
-
-// This structure identifies IPC signatures.
-struct IPCParams {
- int ipc_tag;
- ArgType args[kMaxIpcParams];
-
- bool Matches(IPCParams* other) const {
- return !memcmp(this, other, sizeof(*other));
- }
-};
-
-// Models an entity that can process an IPC message or it can route to another
-// one that could handle it. When an IPC arrives the IPC implementation will:
-// 1) call OnMessageReady() with the tag of the pending IPC. If the dispatcher
-// returns NULL it means that it cannot handle this IPC but if it returns
-// non-null, it must be the pointer to a dispatcher that can handle it.
-// 2) When the IPC finally obtains a valid Dispatcher the IPC
-// implementation creates a CrossCallParamsEx from the raw IPC buffer.
-// 3) It calls the returned callback, with the IPC info and arguments.
-class Dispatcher {
- public:
- // Called from the IPC implementation to handle a specific IPC message.
- typedef bool (Dispatcher::*CallbackGeneric)();
- typedef bool (Dispatcher::*Callback0)(IPCInfo* ipc);
- typedef bool (Dispatcher::*Callback1)(IPCInfo* ipc, void* p1);
- typedef bool (Dispatcher::*Callback2)(IPCInfo* ipc, void* p1, void* p2);
- typedef bool (Dispatcher::*Callback3)(IPCInfo* ipc, void* p1, void* p2,
- void* p3);
- typedef bool (Dispatcher::*Callback4)(IPCInfo* ipc, void* p1, void* p2,
- void* p3, void* p4);
- typedef bool (Dispatcher::*Callback5)(IPCInfo* ipc, void* p1, void* p2,
- void* p3, void* p4, void* p5);
- typedef bool (Dispatcher::*Callback6)(IPCInfo* ipc, void* p1, void* p2,
- void* p3, void* p4, void* p5, void* p6);
- typedef bool (Dispatcher::*Callback7)(IPCInfo* ipc, void* p1, void* p2,
- void* p3, void* p4, void* p5, void* p6,
- void* p7);
- typedef bool (Dispatcher::*Callback8)(IPCInfo* ipc, void* p1, void* p2,
- void* p3, void* p4, void* p5, void* p6,
- void* p7, void* p8);
- typedef bool (Dispatcher::*Callback9)(IPCInfo* ipc, void* p1, void* p2,
- void* p3, void* p4, void* p5, void* p6,
- void* p7, void* p8, void* p9);
-
- // Called from the IPC implementation when an IPC message is ready override
- // on a derived class to handle a set of IPC messages. Return NULL if your
- // subclass does not handle the message or return the pointer to the subclass
- // that can handle it.
- virtual Dispatcher* OnMessageReady(IPCParams* ipc, CallbackGeneric* callback);
-
- // Called when a target proces is created, to setup the interceptions related
- // with the given service (IPC).
- virtual bool SetupService(InterceptionManager* manager, int service) = 0;
-
- Dispatcher();
- virtual ~Dispatcher();
-
- protected:
- // Structure that defines an IPC Call with all the parameters and the handler.
- struct IPCCall {
- IPCParams params;
- CallbackGeneric callback;
- };
-
- // List of IPC Calls supported by the class.
- std::vector<IPCCall> ipc_calls_;
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_CROSSCALL_SERVER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/eat_resolver.cc b/security/sandbox/chromium/sandbox/win/src/eat_resolver.cc
deleted file mode 100644
index 48681e83b..000000000
--- a/security/sandbox/chromium/sandbox/win/src/eat_resolver.cc
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright (c) 2006-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 "sandbox/win/src/eat_resolver.h"
-
-#include <stddef.h>
-
-#include "base/win/pe_image.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-namespace sandbox {
-
-NTSTATUS EatResolverThunk::Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) {
- NTSTATUS ret = Init(target_module, interceptor_module, target_name,
- interceptor_name, interceptor_entry_point,
- thunk_storage, storage_bytes);
- if (!NT_SUCCESS(ret))
- return ret;
-
- if (!eat_entry_)
- return STATUS_INVALID_PARAMETER;
-
-#if defined(_WIN64)
- // We have two thunks, in order: the return path and the forward path.
- if (!SetInternalThunk(thunk_storage, storage_bytes, NULL, target_))
- return STATUS_BUFFER_TOO_SMALL;
-
- size_t thunk_bytes = GetInternalThunkSize();
- storage_bytes -= thunk_bytes;
- thunk_storage = reinterpret_cast<char*>(thunk_storage) + thunk_bytes;
-#endif
-
- if (!SetInternalThunk(thunk_storage, storage_bytes, target_, interceptor_))
- return STATUS_BUFFER_TOO_SMALL;
-
- AutoProtectMemory memory;
- ret = memory.ChangeProtection(eat_entry_, sizeof(DWORD), PAGE_READWRITE);
- if (!NT_SUCCESS(ret))
- return ret;
-
- // Perform the patch.
- *eat_entry_ = static_cast<DWORD>(reinterpret_cast<uintptr_t>(thunk_storage)) -
- static_cast<DWORD>(reinterpret_cast<uintptr_t>(target_module));
-
- if (NULL != storage_used)
- *storage_used = GetThunkSize();
-
- return ret;
-}
-
-NTSTATUS EatResolverThunk::ResolveTarget(const void* module,
- const char* function_name,
- void** address) {
- DCHECK_NT(address);
- if (!module)
- return STATUS_INVALID_PARAMETER;
-
- base::win::PEImage pe(module);
- if (!pe.VerifyMagic())
- return STATUS_INVALID_IMAGE_FORMAT;
-
- eat_entry_ = pe.GetExportEntry(function_name);
-
- if (!eat_entry_)
- return STATUS_PROCEDURE_NOT_FOUND;
-
- *address = pe.RVAToAddr(*eat_entry_);
-
- return STATUS_SUCCESS;
-}
-
-size_t EatResolverThunk::GetThunkSize() const {
-#if defined(_WIN64)
- return GetInternalThunkSize() * 2;
-#else
- return GetInternalThunkSize();
-#endif
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/eat_resolver.h b/security/sandbox/chromium/sandbox/win/src/eat_resolver.h
deleted file mode 100644
index a45d0063b..000000000
--- a/security/sandbox/chromium/sandbox/win/src/eat_resolver.h
+++ /dev/null
@@ -1,50 +0,0 @@
-// 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 SANDBOX_SRC_EAT_RESOLVER_H__
-#define SANDBOX_SRC_EAT_RESOLVER_H__
-
-#include <stddef.h>
-
-#include "base/macros.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/resolver.h"
-
-namespace sandbox {
-
-// This is the concrete resolver used to perform exports table interceptions.
-class EatResolverThunk : public ResolverThunk {
- public:
- EatResolverThunk() : eat_entry_(NULL) {}
- ~EatResolverThunk() override {}
-
- // Implementation of Resolver::Setup.
- NTSTATUS Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) override;
-
- // Implementation of Resolver::ResolveTarget.
- NTSTATUS ResolveTarget(const void* module,
- const char* function_name,
- void** address) override;
-
- // Implementation of Resolver::GetThunkSize.
- size_t GetThunkSize() const override;
-
- private:
- // The entry to patch.
- DWORD* eat_entry_;
-
- DISALLOW_COPY_AND_ASSIGN(EatResolverThunk);
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_EAT_RESOLVER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/file_policy_test.cc b/security/sandbox/chromium/sandbox/win/src/file_policy_test.cc
deleted file mode 100644
index f7509bd36..000000000
--- a/security/sandbox/chromium/sandbox/win/src/file_policy_test.cc
+++ /dev/null
@@ -1,673 +0,0 @@
-// 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 <algorithm>
-#include <cctype>
-
-#include <windows.h>
-#include <winioctl.h>
-
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/filesystem_policy.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/win_utils.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "sandbox/win/tests/common/test_utils.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-#define BINDNTDLL(name) \
- name ## Function name = reinterpret_cast<name ## Function>( \
- ::GetProcAddress(::GetModuleHandle(L"ntdll.dll"), #name))
-
-namespace sandbox {
-
-const ULONG kSharing = FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE;
-
-// Creates a file using different desired access. Returns if the call succeeded
-// or not. The first argument in argv is the filename. The second argument
-// determines the type of access and the dispositino of the file.
-SBOX_TESTS_COMMAND int File_Create(int argc, wchar_t **argv) {
- if (argc != 2)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- std::wstring operation(argv[0]);
-
- if (operation == L"Read") {
- base::win::ScopedHandle file1(CreateFile(
- argv[1], GENERIC_READ, kSharing, NULL, OPEN_EXISTING, 0, NULL));
- base::win::ScopedHandle file2(CreateFile(
- argv[1], FILE_EXECUTE, kSharing, NULL, OPEN_EXISTING, 0, NULL));
-
- if (file1.IsValid() == file2.IsValid())
- return file1.IsValid() ? SBOX_TEST_SUCCEEDED : SBOX_TEST_DENIED;
- return file1.IsValid() ? SBOX_TEST_FIRST_ERROR : SBOX_TEST_SECOND_ERROR;
-
- } else if (operation == L"Write") {
- base::win::ScopedHandle file1(CreateFile(
- argv[1], GENERIC_ALL, kSharing, NULL, OPEN_EXISTING, 0, NULL));
- base::win::ScopedHandle file2(CreateFile(
- argv[1], GENERIC_READ | FILE_WRITE_DATA, kSharing, NULL, OPEN_EXISTING,
- 0, NULL));
-
- if (file1.IsValid() == file2.IsValid())
- return file1.IsValid() ? SBOX_TEST_SUCCEEDED : SBOX_TEST_DENIED;
- return file1.IsValid() ? SBOX_TEST_FIRST_ERROR : SBOX_TEST_SECOND_ERROR;
-
- } else if (operation == L"ReadCreate") {
- base::win::ScopedHandle file2(CreateFile(
- argv[1], GENERIC_READ, kSharing, NULL, CREATE_NEW, 0, NULL));
- base::win::ScopedHandle file1(CreateFile(
- argv[1], GENERIC_READ, kSharing, NULL, CREATE_ALWAYS, 0, NULL));
-
- if (file1.IsValid() == file2.IsValid())
- return file1.IsValid() ? SBOX_TEST_SUCCEEDED : SBOX_TEST_DENIED;
- return file1.IsValid() ? SBOX_TEST_FIRST_ERROR : SBOX_TEST_SECOND_ERROR;
- }
-
- return SBOX_TEST_INVALID_PARAMETER;
-}
-
-SBOX_TESTS_COMMAND int File_Win32Create(int argc, wchar_t **argv) {
- if (argc != 1) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
-
- base::string16 full_path = MakePathToSys(argv[0], false);
- if (full_path.empty()) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
-
- HANDLE file = ::CreateFileW(full_path.c_str(), GENERIC_READ, kSharing,
- NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
-
- if (INVALID_HANDLE_VALUE != file) {
- ::CloseHandle(file);
- return SBOX_TEST_SUCCEEDED;
- } else {
- if (ERROR_ACCESS_DENIED == ::GetLastError()) {
- return SBOX_TEST_DENIED;
- } else {
- return SBOX_TEST_FAILED;
- }
- }
- return SBOX_TEST_SUCCEEDED;
-}
-
-// Creates the file in parameter using the NtCreateFile api and returns if the
-// call succeeded or not.
-SBOX_TESTS_COMMAND int File_CreateSys32(int argc, wchar_t **argv) {
- BINDNTDLL(NtCreateFile);
- BINDNTDLL(RtlInitUnicodeString);
- if (!NtCreateFile || !RtlInitUnicodeString)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- if (argc != 1)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- base::string16 file(argv[0]);
- if (0 != _wcsnicmp(file.c_str(), kNTDevicePrefix, kNTDevicePrefixLen))
- file = MakePathToSys(argv[0], true);
-
- UNICODE_STRING object_name;
- RtlInitUnicodeString(&object_name, file.c_str());
-
- OBJECT_ATTRIBUTES obj_attributes = {};
- InitializeObjectAttributes(&obj_attributes, &object_name,
- OBJ_CASE_INSENSITIVE, NULL, NULL);
-
- HANDLE handle;
- IO_STATUS_BLOCK io_block = {};
- NTSTATUS status = NtCreateFile(&handle, FILE_READ_DATA, &obj_attributes,
- &io_block, NULL, 0, kSharing, FILE_OPEN,
- 0, NULL, 0);
- if (NT_SUCCESS(status)) {
- ::CloseHandle(handle);
- return SBOX_TEST_SUCCEEDED;
- } else if (STATUS_ACCESS_DENIED == status) {
- return SBOX_TEST_DENIED;
- } else if (STATUS_OBJECT_NAME_NOT_FOUND == status) {
- return SBOX_TEST_NOT_FOUND;
- }
- return SBOX_TEST_FAILED;
-}
-
-// Opens the file in parameter using the NtOpenFile api and returns if the
-// call succeeded or not.
-SBOX_TESTS_COMMAND int File_OpenSys32(int argc, wchar_t **argv) {
- BINDNTDLL(NtOpenFile);
- BINDNTDLL(RtlInitUnicodeString);
- if (!NtOpenFile || !RtlInitUnicodeString)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- if (argc != 1)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- base::string16 file = MakePathToSys(argv[0], true);
- UNICODE_STRING object_name;
- RtlInitUnicodeString(&object_name, file.c_str());
-
- OBJECT_ATTRIBUTES obj_attributes = {};
- InitializeObjectAttributes(&obj_attributes, &object_name,
- OBJ_CASE_INSENSITIVE, NULL, NULL);
-
- HANDLE handle;
- IO_STATUS_BLOCK io_block = {};
- NTSTATUS status = NtOpenFile(&handle, FILE_READ_DATA, &obj_attributes,
- &io_block, kSharing, 0);
- if (NT_SUCCESS(status)) {
- ::CloseHandle(handle);
- return SBOX_TEST_SUCCEEDED;
- } else if (STATUS_ACCESS_DENIED == status) {
- return SBOX_TEST_DENIED;
- } else if (STATUS_OBJECT_NAME_NOT_FOUND == status) {
- return SBOX_TEST_NOT_FOUND;
- }
- return SBOX_TEST_FAILED;
-}
-
-SBOX_TESTS_COMMAND int File_GetDiskSpace(int argc, wchar_t **argv) {
- base::string16 sys_path = MakePathToSys(L"", false);
- if (sys_path.empty()) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- ULARGE_INTEGER free_user = {};
- ULARGE_INTEGER total = {};
- ULARGE_INTEGER free_total = {};
- if (::GetDiskFreeSpaceExW(sys_path.c_str(), &free_user, &total,
- &free_total)) {
- if ((total.QuadPart != 0) && (free_total.QuadPart !=0)) {
- return SBOX_TEST_SUCCEEDED;
- }
- } else {
- if (ERROR_ACCESS_DENIED == ::GetLastError()) {
- return SBOX_TEST_DENIED;
- } else {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- }
- return SBOX_TEST_SUCCEEDED;
-}
-
-// Move a file using the MoveFileEx api and returns if the call succeeded or
-// not.
-SBOX_TESTS_COMMAND int File_Rename(int argc, wchar_t **argv) {
- if (argc != 2)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- if (::MoveFileEx(argv[0], argv[1], 0))
- return SBOX_TEST_SUCCEEDED;
-
- if (::GetLastError() != ERROR_ACCESS_DENIED)
- return SBOX_TEST_FAILED;
-
- return SBOX_TEST_DENIED;
-}
-
-// Query the attributes of file in parameter using the NtQueryAttributesFile api
-// and NtQueryFullAttributesFile and returns if the call succeeded or not. The
-// second argument in argv is "d" or "f" telling if we expect the attributes to
-// specify a file or a directory. The expected attribute has to match the real
-// attributes for the call to be successful.
-SBOX_TESTS_COMMAND int File_QueryAttributes(int argc, wchar_t **argv) {
- BINDNTDLL(NtQueryAttributesFile);
- BINDNTDLL(NtQueryFullAttributesFile);
- BINDNTDLL(RtlInitUnicodeString);
- if (!NtQueryAttributesFile || !NtQueryFullAttributesFile ||
- !RtlInitUnicodeString)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- if (argc != 2)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- bool expect_directory = (L'd' == argv[1][0]);
-
- UNICODE_STRING object_name;
- base::string16 file = MakePathToSys(argv[0], true);
- RtlInitUnicodeString(&object_name, file.c_str());
-
- OBJECT_ATTRIBUTES obj_attributes = {};
- InitializeObjectAttributes(&obj_attributes, &object_name,
- OBJ_CASE_INSENSITIVE, NULL, NULL);
-
- FILE_BASIC_INFORMATION info = {};
- FILE_NETWORK_OPEN_INFORMATION full_info = {};
- NTSTATUS status1 = NtQueryAttributesFile(&obj_attributes, &info);
- NTSTATUS status2 = NtQueryFullAttributesFile(&obj_attributes, &full_info);
-
- if (status1 != status2)
- return SBOX_TEST_FAILED;
-
- if (NT_SUCCESS(status1)) {
- if (info.FileAttributes != full_info.FileAttributes)
- return SBOX_TEST_FAILED;
-
- bool is_directory1 = (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
- if (expect_directory == is_directory1)
- return SBOX_TEST_SUCCEEDED;
- } else if (STATUS_ACCESS_DENIED == status1) {
- return SBOX_TEST_DENIED;
- } else if (STATUS_OBJECT_NAME_NOT_FOUND == status1) {
- return SBOX_TEST_NOT_FOUND;
- }
-
- return SBOX_TEST_FAILED;
-}
-
-TEST(FilePolicyTest, DenyNtCreateCalc) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_DIR_ANY,
- L"calc.exe"));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"File_CreateSys32 calc.exe"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"File_CreateSys32 calc.exe"));
-}
-
-TEST(FilePolicyTest, AllowNtCreateCalc) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_ANY, L"calc.exe"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"File_CreateSys32 calc.exe"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"File_CreateSys32 calc.exe"));
-}
-
-TEST(FilePolicyTest, AllowNtCreateWithNativePath) {
- if (base::win::GetVersion() < base::win::VERSION_WIN7)
- return;
-
- base::string16 calc = MakePathToSys(L"calc.exe", false);
- base::string16 nt_path;
- ASSERT_TRUE(GetNtPathFromWin32Path(calc, &nt_path));
- TestRunner runner;
- runner.AddFsRule(TargetPolicy::FILES_ALLOW_READONLY, nt_path.c_str());
-
- wchar_t buff[MAX_PATH];
- ::wsprintfW(buff, L"File_CreateSys32 %s", nt_path.c_str());
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(buff));
-
- std::transform(nt_path.begin(), nt_path.end(), nt_path.begin(), std::tolower);
- ::wsprintfW(buff, L"File_CreateSys32 %s", nt_path.c_str());
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(buff));
-}
-
-TEST(FilePolicyTest, AllowReadOnly) {
- TestRunner runner;
-
- // Create a temp file because we need write access to it.
- wchar_t temp_directory[MAX_PATH];
- wchar_t temp_file_name[MAX_PATH];
- ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name), 0u);
-
- EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_READONLY,
- temp_file_name));
-
- wchar_t command_read[MAX_PATH + 20] = {};
- wsprintf(command_read, L"File_Create Read \"%ls\"", temp_file_name);
- wchar_t command_read_create[MAX_PATH + 20] = {};
- wsprintf(command_read_create, L"File_Create ReadCreate \"%ls\"",
- temp_file_name);
- wchar_t command_write[MAX_PATH + 20] = {};
- wsprintf(command_write, L"File_Create Write \"%ls\"", temp_file_name);
-
- // Verify that we cannot create the file after revert.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(command_read_create));
-
- // Verify that we don't have write access after revert.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(command_write));
-
- // Verify that we have read access after revert.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command_read));
-
- // Verify that we really have write access to the file.
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command_write));
-
- DeleteFile(temp_file_name);
-}
-
-// Tests support of "\\\\.\\DeviceName" kind of paths.
-TEST(FilePolicyTest, AllowImplicitDeviceName) {
- if (base::win::GetVersion() < base::win::VERSION_WIN7)
- return;
-
- TestRunner runner;
-
- wchar_t temp_directory[MAX_PATH];
- wchar_t temp_file_name[MAX_PATH];
- ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name), 0u);
-
- std::wstring path(temp_file_name);
- EXPECT_TRUE(ConvertToLongPath(&path));
- EXPECT_TRUE(GetNtPathFromWin32Path(path, &path));
- path = path.substr(sandbox::kNTDevicePrefixLen);
-
- wchar_t command[MAX_PATH + 20] = {};
- wsprintf(command, L"File_Create Read \"\\\\.\\%ls\"", path.c_str());
- path = std::wstring(kNTPrefix) + path;
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(command));
- EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY, path.c_str()));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command));
-
- DeleteFile(temp_file_name);
-}
-
-TEST(FilePolicyTest, AllowWildcard) {
- TestRunner runner;
-
- // Create a temp file because we need write access to it.
- wchar_t temp_directory[MAX_PATH];
- wchar_t temp_file_name[MAX_PATH];
- ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name), 0u);
-
- wcscat_s(temp_directory, MAX_PATH, L"*");
- EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY, temp_directory));
-
- wchar_t command_write[MAX_PATH + 20] = {};
- wsprintf(command_write, L"File_Create Write \"%ls\"", temp_file_name);
-
- // Verify that we have write access after revert.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command_write));
-
- DeleteFile(temp_file_name);
-}
-
-TEST(FilePolicyTest, AllowNtCreatePatternRule) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_ANY, L"App*.dll"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"File_OpenSys32 appmgmts.dll"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"File_OpenSys32 appwiz.cpl"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"File_OpenSys32 appmgmts.dll"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"File_OpenSys32 appwiz.cpl"));
-}
-
-TEST(FilePolicyTest, CheckNotFound) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_ANY, L"n*.dll"));
-
- EXPECT_EQ(SBOX_TEST_NOT_FOUND,
- runner.RunTest(L"File_OpenSys32 notfound.dll"));
-}
-
-TEST(FilePolicyTest, CheckNoLeak) {
- TestRunner runner;
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"File_CreateSys32 notfound.exe"));
-}
-
-TEST(FilePolicyTest, TestQueryAttributesFile) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_ANY,
- L"appmgmts.dll"));
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_ANY,
- L"notfound.exe"));
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_ANY, L"drivers"));
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_QUERY,
- L"ipconfig.exe"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"File_QueryAttributes drivers d"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"File_QueryAttributes appmgmts.dll f"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"File_QueryAttributes ipconfig.exe f"));
-
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"File_QueryAttributes ftp.exe f"));
-
- EXPECT_EQ(SBOX_TEST_NOT_FOUND,
- runner.RunTest(L"File_QueryAttributes notfound.exe f"));
-}
-
-// Makes sure that we don't leak information when there is not policy to allow
-// a path.
-TEST(FilePolicyTest, TestQueryAttributesFileNoPolicy) {
- TestRunner runner;
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"File_QueryAttributes ftp.exe f"));
-
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"File_QueryAttributes notfound.exe f"));
-}
-
-TEST(FilePolicyTest, TestRename) {
- TestRunner runner;
-
- // Give access to the temp directory.
- wchar_t temp_directory[MAX_PATH];
- wchar_t temp_file_name1[MAX_PATH];
- wchar_t temp_file_name2[MAX_PATH];
- wchar_t temp_file_name3[MAX_PATH];
- wchar_t temp_file_name4[MAX_PATH];
- wchar_t temp_file_name5[MAX_PATH];
- wchar_t temp_file_name6[MAX_PATH];
- wchar_t temp_file_name7[MAX_PATH];
- wchar_t temp_file_name8[MAX_PATH];
- ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name1), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name2), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name3), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name4), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name5), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name6), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name7), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name8), 0u);
-
-
- // Add rules to make file1->file2 succeed.
- ASSERT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY, temp_file_name1));
- ASSERT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY, temp_file_name2));
-
- // Add rules to make file3->file4 fail.
- ASSERT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY, temp_file_name3));
- ASSERT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_READONLY,
- temp_file_name4));
-
- // Add rules to make file5->file6 fail.
- ASSERT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_READONLY,
- temp_file_name5));
- ASSERT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY, temp_file_name6));
-
- // Add rules to make file7->no_pol_file fail.
- ASSERT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY, temp_file_name7));
-
- // Delete the files where the files are going to be renamed to.
- ::DeleteFile(temp_file_name2);
- ::DeleteFile(temp_file_name4);
- ::DeleteFile(temp_file_name6);
- ::DeleteFile(temp_file_name8);
-
- wchar_t command[MAX_PATH * 2 + 20] = {};
- wsprintf(command, L"File_Rename \"%ls\" \"%ls\"", temp_file_name1,
- temp_file_name2);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command));
-
- wsprintf(command, L"File_Rename \"%ls\" \"%ls\"", temp_file_name3,
- temp_file_name4);
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(command));
-
- wsprintf(command, L"File_Rename \"%ls\" \"%ls\"", temp_file_name5,
- temp_file_name6);
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(command));
-
- wsprintf(command, L"File_Rename \"%ls\" \"%ls\"", temp_file_name7,
- temp_file_name8);
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(command));
-
-
- // Delete all the files in case they are still there.
- ::DeleteFile(temp_file_name1);
- ::DeleteFile(temp_file_name2);
- ::DeleteFile(temp_file_name3);
- ::DeleteFile(temp_file_name4);
- ::DeleteFile(temp_file_name5);
- ::DeleteFile(temp_file_name6);
- ::DeleteFile(temp_file_name7);
- ::DeleteFile(temp_file_name8);
-}
-
-TEST(FilePolicyTest, OpenSys32FilesDenyBecauseOfDir) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_DIR_ANY,
- L"notepad.exe"));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"File_Win32Create notepad.exe"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"File_Win32Create notepad.exe"));
-}
-
-TEST(FilePolicyTest, OpenSys32FilesAllowNotepad) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_ANY,
- L"notepad.exe"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"File_Win32Create notepad.exe"));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"File_Win32Create calc.exe"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"File_Win32Create notepad.exe"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"File_Win32Create calc.exe"));
-}
-
-TEST(FilePolicyTest, FileGetDiskSpace) {
- TestRunner runner;
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"File_GetDiskSpace"));
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"File_GetDiskSpace"));
-
- // Add an 'allow' rule in the windows\system32 such that GetDiskFreeSpaceEx
- // succeeds (it does an NtOpenFile) but windows\system32\notepad.exe is
- // denied since there is no wild card in the rule.
- EXPECT_TRUE(runner.AddRuleSys32(TargetPolicy::FILES_ALLOW_DIR_ANY, L""));
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"File_GetDiskSpace"));
-
- runner.SetTestState(AFTER_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"File_GetDiskSpace"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"File_Win32Create notepad.exe"));
-}
-
-TEST(FilePolicyTest, TestReparsePoint) {
- TestRunner runner;
-
- // Create a temp file because we need write access to it.
- wchar_t temp_directory[MAX_PATH];
- wchar_t temp_file_name[MAX_PATH];
- ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, temp_file_name), 0u);
-
- // Delete the file and create a directory instead.
- ASSERT_TRUE(::DeleteFile(temp_file_name));
- ASSERT_TRUE(::CreateDirectory(temp_file_name, NULL));
-
- // Create a temporary file in the subfolder.
- base::string16 subfolder = temp_file_name;
- base::string16 temp_file_title = subfolder.substr(subfolder.rfind(L"\\") + 1);
- base::string16 temp_file = subfolder + L"\\file_" + temp_file_title;
-
- HANDLE file = ::CreateFile(temp_file.c_str(), FILE_ALL_ACCESS,
- FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
- CREATE_ALWAYS, 0, NULL);
- ASSERT_TRUE(INVALID_HANDLE_VALUE != file);
- ASSERT_TRUE(::CloseHandle(file));
-
- // Create a temporary file in the temp directory.
- base::string16 temp_dir = temp_directory;
- base::string16 temp_file_in_temp = temp_dir + L"file_" + temp_file_title;
- file = ::CreateFile(temp_file_in_temp.c_str(), FILE_ALL_ACCESS,
- FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
- CREATE_ALWAYS, 0, NULL);
- ASSERT_TRUE(file != NULL);
- ASSERT_TRUE(::CloseHandle(file));
-
- // Give write access to the temp directory.
- base::string16 temp_dir_wildcard = temp_dir + L"*";
- EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_ANY,
- temp_dir_wildcard.c_str()));
-
- // Prepare the command to execute.
- base::string16 command_write;
- command_write += L"File_Create Write \"";
- command_write += temp_file;
- command_write += L"\"";
-
- // Verify that we have write access to the original file
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command_write.c_str()));
-
- // Replace the subfolder by a reparse point to %temp%.
- ::DeleteFile(temp_file.c_str());
- HANDLE dir = ::CreateFile(subfolder.c_str(), FILE_ALL_ACCESS,
- FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
- OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
- EXPECT_TRUE(INVALID_HANDLE_VALUE != dir);
-
- base::string16 temp_dir_nt;
- temp_dir_nt += L"\\??\\";
- temp_dir_nt += temp_dir;
- EXPECT_TRUE(SetReparsePoint(dir, temp_dir_nt.c_str()));
- EXPECT_TRUE(::CloseHandle(dir));
-
- // Try to open the file again.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(command_write.c_str()));
-
- // Remove the reparse point.
- dir = ::CreateFile(subfolder.c_str(), FILE_ALL_ACCESS,
- FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
- FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
- NULL);
- EXPECT_TRUE(INVALID_HANDLE_VALUE != dir);
- EXPECT_TRUE(DeleteReparsePoint(dir));
- EXPECT_TRUE(::CloseHandle(dir));
-
- // Cleanup.
- EXPECT_TRUE(::DeleteFile(temp_file_in_temp.c_str()));
- EXPECT_TRUE(::RemoveDirectory(subfolder.c_str()));
-}
-
-TEST(FilePolicyTest, CheckExistingNTPrefixEscape) {
- base::string16 name = L"\\??\\NAME";
-
- base::string16 result = FixNTPrefixForMatch(name);
-
- EXPECT_STREQ(result.c_str(), L"\\/?/?\\NAME");
-}
-
-TEST(FilePolicyTest, CheckEscapedNTPrefixNoEscape) {
- base::string16 name = L"\\/?/?\\NAME";
-
- base::string16 result = FixNTPrefixForMatch(name);
-
- EXPECT_STREQ(result.c_str(), name.c_str());
-}
-
-TEST(FilePolicyTest, CheckMissingNTPrefixEscape) {
- base::string16 name = L"C:\\NAME";
-
- base::string16 result = FixNTPrefixForMatch(name);
-
- EXPECT_STREQ(result.c_str(), L"\\/?/?\\C:\\NAME");
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.cc b/security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.cc
deleted file mode 100644
index 6f96be240..000000000
--- a/security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.cc
+++ /dev/null
@@ -1,318 +0,0 @@
-// Copyright (c) 2006-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 "sandbox/win/src/filesystem_dispatcher.h"
-
-#include <stdint.h>
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/filesystem_interception.h"
-#include "sandbox/win/src/filesystem_policy.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_broker.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-namespace sandbox {
-
-FilesystemDispatcher::FilesystemDispatcher(PolicyBase* policy_base)
- : policy_base_(policy_base) {
- static const IPCCall create_params = {
- {IPC_NTCREATEFILE_TAG,
- {WCHAR_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(&FilesystemDispatcher::NtCreateFile)};
-
- static const IPCCall open_file = {
- {IPC_NTOPENFILE_TAG,
- {WCHAR_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(&FilesystemDispatcher::NtOpenFile)};
-
- static const IPCCall attribs = {
- {IPC_NTQUERYATTRIBUTESFILE_TAG, {WCHAR_TYPE, UINT32_TYPE, INOUTPTR_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &FilesystemDispatcher::NtQueryAttributesFile)};
-
- static const IPCCall full_attribs = {
- {IPC_NTQUERYFULLATTRIBUTESFILE_TAG,
- {WCHAR_TYPE, UINT32_TYPE, INOUTPTR_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &FilesystemDispatcher::NtQueryFullAttributesFile)};
-
- static const IPCCall set_info = {
- {IPC_NTSETINFO_RENAME_TAG,
- {VOIDPTR_TYPE, INOUTPTR_TYPE, INOUTPTR_TYPE, UINT32_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &FilesystemDispatcher::NtSetInformationFile)};
-
- ipc_calls_.push_back(create_params);
- ipc_calls_.push_back(open_file);
- ipc_calls_.push_back(attribs);
- ipc_calls_.push_back(full_attribs);
- ipc_calls_.push_back(set_info);
-}
-
-bool FilesystemDispatcher::SetupService(InterceptionManager* manager,
- int service) {
- switch (service) {
- case IPC_NTCREATEFILE_TAG:
- return INTERCEPT_NT(manager, NtCreateFile, CREATE_FILE_ID, 48);
-
- case IPC_NTOPENFILE_TAG:
- return INTERCEPT_NT(manager, NtOpenFile, OPEN_FILE_ID, 28);
-
- case IPC_NTQUERYATTRIBUTESFILE_TAG:
- return INTERCEPT_NT(manager, NtQueryAttributesFile, QUERY_ATTRIB_FILE_ID,
- 12);
-
- case IPC_NTQUERYFULLATTRIBUTESFILE_TAG:
- return INTERCEPT_NT(manager, NtQueryFullAttributesFile,
- QUERY_FULL_ATTRIB_FILE_ID, 12);
-
- case IPC_NTSETINFO_RENAME_TAG:
- return INTERCEPT_NT(manager, NtSetInformationFile, SET_INFO_FILE_ID, 24);
-
- default:
- return false;
- }
-}
-
-bool FilesystemDispatcher::NtCreateFile(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- uint32_t desired_access,
- uint32_t file_attributes,
- uint32_t share_access,
- uint32_t create_disposition,
- uint32_t create_options) {
- if (!PreProcessName(name)) {
- // The path requested might contain a reparse point.
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- const wchar_t* filename = name->c_str();
-
- uint32_t broker = TRUE;
- CountedParameterSet<OpenFile> params;
- params[OpenFile::NAME] = ParamPickerMake(filename);
- params[OpenFile::ACCESS] = ParamPickerMake(desired_access);
- params[OpenFile::DISPOSITION] = ParamPickerMake(create_disposition);
- params[OpenFile::OPTIONS] = ParamPickerMake(create_options);
- params[OpenFile::BROKER] = ParamPickerMake(broker);
-
- // To evaluate the policy we need to call back to the policy object. We
- // are just middlemen in the operation since is the FileSystemPolicy which
- // knows what to do.
- EvalResult result = policy_base_->EvalPolicy(IPC_NTCREATEFILE_TAG,
- params.GetBase());
- HANDLE handle;
- ULONG_PTR io_information = 0;
- NTSTATUS nt_status;
- if (!FileSystemPolicy::CreateFileAction(result, *ipc->client_info, *name,
- attributes, desired_access,
- file_attributes, share_access,
- create_disposition, create_options,
- &handle, &nt_status,
- &io_information)) {
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
- // Return operation status on the IPC.
- ipc->return_info.extended[0].ulong_ptr = io_information;
- ipc->return_info.nt_status = nt_status;
- ipc->return_info.handle = handle;
- return true;
-}
-
-bool FilesystemDispatcher::NtOpenFile(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- uint32_t desired_access,
- uint32_t share_access,
- uint32_t open_options) {
- if (!PreProcessName(name)) {
- // The path requested might contain a reparse point.
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- const wchar_t* filename = name->c_str();
-
- uint32_t broker = TRUE;
- uint32_t create_disposition = FILE_OPEN;
- CountedParameterSet<OpenFile> params;
- params[OpenFile::NAME] = ParamPickerMake(filename);
- params[OpenFile::ACCESS] = ParamPickerMake(desired_access);
- params[OpenFile::DISPOSITION] = ParamPickerMake(create_disposition);
- params[OpenFile::OPTIONS] = ParamPickerMake(open_options);
- params[OpenFile::BROKER] = ParamPickerMake(broker);
-
- // To evaluate the policy we need to call back to the policy object. We
- // are just middlemen in the operation since is the FileSystemPolicy which
- // knows what to do.
- EvalResult result = policy_base_->EvalPolicy(IPC_NTOPENFILE_TAG,
- params.GetBase());
- HANDLE handle;
- ULONG_PTR io_information = 0;
- NTSTATUS nt_status;
- if (!FileSystemPolicy::OpenFileAction(result, *ipc->client_info, *name,
- attributes, desired_access,
- share_access, open_options, &handle,
- &nt_status, &io_information)) {
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
- // Return operation status on the IPC.
- ipc->return_info.extended[0].ulong_ptr = io_information;
- ipc->return_info.nt_status = nt_status;
- ipc->return_info.handle = handle;
- return true;
-}
-
-bool FilesystemDispatcher::NtQueryAttributesFile(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- CountedBuffer* info) {
- if (sizeof(FILE_BASIC_INFORMATION) != info->Size())
- return false;
-
- if (!PreProcessName(name)) {
- // The path requested might contain a reparse point.
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- uint32_t broker = TRUE;
- const wchar_t* filename = name->c_str();
- CountedParameterSet<FileName> params;
- params[FileName::NAME] = ParamPickerMake(filename);
- params[FileName::BROKER] = ParamPickerMake(broker);
-
- // To evaluate the policy we need to call back to the policy object. We
- // are just middlemen in the operation since is the FileSystemPolicy which
- // knows what to do.
- EvalResult result = policy_base_->EvalPolicy(IPC_NTQUERYATTRIBUTESFILE_TAG,
- params.GetBase());
-
- FILE_BASIC_INFORMATION* information =
- reinterpret_cast<FILE_BASIC_INFORMATION*>(info->Buffer());
- NTSTATUS nt_status;
- if (!FileSystemPolicy::QueryAttributesFileAction(result, *ipc->client_info,
- *name, attributes,
- information, &nt_status)) {
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- // Return operation status on the IPC.
- ipc->return_info.nt_status = nt_status;
- return true;
-}
-
-bool FilesystemDispatcher::NtQueryFullAttributesFile(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- CountedBuffer* info) {
- if (sizeof(FILE_NETWORK_OPEN_INFORMATION) != info->Size())
- return false;
-
- if (!PreProcessName(name)) {
- // The path requested might contain a reparse point.
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- uint32_t broker = TRUE;
- const wchar_t* filename = name->c_str();
- CountedParameterSet<FileName> params;
- params[FileName::NAME] = ParamPickerMake(filename);
- params[FileName::BROKER] = ParamPickerMake(broker);
-
- // To evaluate the policy we need to call back to the policy object. We
- // are just middlemen in the operation since is the FileSystemPolicy which
- // knows what to do.
- EvalResult result = policy_base_->EvalPolicy(
- IPC_NTQUERYFULLATTRIBUTESFILE_TAG, params.GetBase());
-
- FILE_NETWORK_OPEN_INFORMATION* information =
- reinterpret_cast<FILE_NETWORK_OPEN_INFORMATION*>(info->Buffer());
- NTSTATUS nt_status;
- if (!FileSystemPolicy::QueryFullAttributesFileAction(result,
- *ipc->client_info,
- *name, attributes,
- information,
- &nt_status)) {
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- // Return operation status on the IPC.
- ipc->return_info.nt_status = nt_status;
- return true;
-}
-
-bool FilesystemDispatcher::NtSetInformationFile(IPCInfo* ipc,
- HANDLE handle,
- CountedBuffer* status,
- CountedBuffer* info,
- uint32_t length,
- uint32_t info_class) {
- if (sizeof(IO_STATUS_BLOCK) != status->Size())
- return false;
- if (length != info->Size())
- return false;
-
- FILE_RENAME_INFORMATION* rename_info =
- reinterpret_cast<FILE_RENAME_INFORMATION*>(info->Buffer());
-
- if (!IsSupportedRenameCall(rename_info, length, info_class))
- return false;
-
- base::string16 name;
- name.assign(rename_info->FileName, rename_info->FileNameLength /
- sizeof(rename_info->FileName[0]));
- if (!PreProcessName(&name)) {
- // The path requested might contain a reparse point.
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- uint32_t broker = TRUE;
- const wchar_t* filename = name.c_str();
- CountedParameterSet<FileName> params;
- params[FileName::NAME] = ParamPickerMake(filename);
- params[FileName::BROKER] = ParamPickerMake(broker);
-
- // To evaluate the policy we need to call back to the policy object. We
- // are just middlemen in the operation since is the FileSystemPolicy which
- // knows what to do.
- EvalResult result = policy_base_->EvalPolicy(IPC_NTSETINFO_RENAME_TAG,
- params.GetBase());
-
- IO_STATUS_BLOCK* io_status =
- reinterpret_cast<IO_STATUS_BLOCK*>(status->Buffer());
- NTSTATUS nt_status;
- if (!FileSystemPolicy::SetInformationFileAction(result, *ipc->client_info,
- handle, rename_info, length,
- info_class, io_status,
- &nt_status)) {
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- // Return operation status on the IPC.
- ipc->return_info.nt_status = nt_status;
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.h b/security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.h
deleted file mode 100644
index 61d918ed0..000000000
--- a/security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.h
+++ /dev/null
@@ -1,74 +0,0 @@
-// 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 SANDBOX_SRC_FILESYSTEM_DISPATCHER_H__
-#define SANDBOX_SRC_FILESYSTEM_DISPATCHER_H__
-
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-namespace sandbox {
-
-// This class handles file system-related IPC calls.
-class FilesystemDispatcher : public Dispatcher {
- public:
- explicit FilesystemDispatcher(PolicyBase* policy_base);
- ~FilesystemDispatcher() override {}
-
- // Dispatcher interface.
- bool SetupService(InterceptionManager* manager, int service) override;
-
- private:
- // Processes IPC requests coming from calls to NtCreateFile in the target.
- bool NtCreateFile(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- uint32_t desired_access,
- uint32_t file_attributes,
- uint32_t share_access,
- uint32_t create_disposition,
- uint32_t create_options);
-
- // Processes IPC requests coming from calls to NtOpenFile in the target.
- bool NtOpenFile(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- uint32_t desired_access,
- uint32_t share_access,
- uint32_t create_options);
-
- // Processes IPC requests coming from calls to NtQueryAttributesFile in the
- // target.
- bool NtQueryAttributesFile(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- CountedBuffer* info);
-
- // Processes IPC requests coming from calls to NtQueryFullAttributesFile in
- // the target.
- bool NtQueryFullAttributesFile(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- CountedBuffer* info);
-
- // Processes IPC requests coming from calls to NtSetInformationFile with the
- // rename information class.
- bool NtSetInformationFile(IPCInfo* ipc,
- HANDLE handle,
- CountedBuffer* status,
- CountedBuffer* info,
- uint32_t length,
- uint32_t info_class);
-
- PolicyBase* policy_base_;
- DISALLOW_COPY_AND_ASSIGN(FilesystemDispatcher);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_FILESYSTEM_DISPATCHER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
deleted file mode 100644
index 1da2b43db..000000000
--- a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
+++ /dev/null
@@ -1,402 +0,0 @@
-// 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 "sandbox/win/src/filesystem_interception.h"
-
-#include <stdint.h>
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/policy_target.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/target_services.h"
-#include "mozilla/sandboxing/sandboxLogging.h"
-
-namespace sandbox {
-
-NTSTATUS WINAPI TargetNtCreateFile(NtCreateFileFunction orig_CreateFile,
- PHANDLE file, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes,
- PIO_STATUS_BLOCK io_status,
- PLARGE_INTEGER allocation_size,
- ULONG file_attributes, ULONG sharing,
- ULONG disposition, ULONG options,
- PVOID ea_buffer, ULONG ea_length) {
- // Check if the process can open it first.
- NTSTATUS status = orig_CreateFile(file, desired_access, object_attributes,
- io_status, allocation_size,
- file_attributes, sharing, disposition,
- options, ea_buffer, ea_length);
- if (STATUS_ACCESS_DENIED != status)
- return status;
-
- mozilla::sandboxing::LogBlocked("NtCreateFile",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- wchar_t* name = NULL;
- do {
- if (!ValidParameter(file, sizeof(HANDLE), WRITE))
- break;
- if (!ValidParameter(io_status, sizeof(IO_STATUS_BLOCK), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- uint32_t attributes = 0;
- NTSTATUS ret = AllocAndCopyName(object_attributes, &name, &attributes,
- NULL);
- if (!NT_SUCCESS(ret) || NULL == name)
- break;
-
- uint32_t desired_access_uint32 = desired_access;
- uint32_t options_uint32 = options;
- uint32_t disposition_uint32 = disposition;
- uint32_t broker = FALSE;
- CountedParameterSet<OpenFile> params;
- params[OpenFile::NAME] = ParamPickerMake(name);
- params[OpenFile::ACCESS] = ParamPickerMake(desired_access_uint32);
- params[OpenFile::DISPOSITION] = ParamPickerMake(disposition_uint32);
- params[OpenFile::OPTIONS] = ParamPickerMake(options_uint32);
- params[OpenFile::BROKER] = ParamPickerMake(broker);
-
- if (!QueryBroker(IPC_NTCREATEFILE_TAG, params.GetBase()))
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- // The following call must match in the parameters with
- // FilesystemDispatcher::ProcessNtCreateFile.
- ResultCode code = CrossCall(ipc, IPC_NTCREATEFILE_TAG, name, attributes,
- desired_access_uint32, file_attributes, sharing,
- disposition, options_uint32, &answer);
- if (SBOX_ALL_OK != code)
- break;
-
- status = answer.nt_status;
-
- if (!NT_SUCCESS(answer.nt_status))
- break;
-
- __try {
- *file = answer.handle;
- io_status->Status = answer.nt_status;
- io_status->Information = answer.extended[0].ulong_ptr;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
- mozilla::sandboxing::LogAllowed("NtCreateFile",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- } while (false);
-
- if (name)
- operator delete(name, NT_ALLOC);
-
- return status;
-}
-
-NTSTATUS WINAPI TargetNtOpenFile(NtOpenFileFunction orig_OpenFile, PHANDLE file,
- ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes,
- PIO_STATUS_BLOCK io_status, ULONG sharing,
- ULONG options) {
- // Check if the process can open it first.
- NTSTATUS status = orig_OpenFile(file, desired_access, object_attributes,
- io_status, sharing, options);
- if (STATUS_ACCESS_DENIED != status)
- return status;
-
- mozilla::sandboxing::LogBlocked("NtOpenFile",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- wchar_t* name = NULL;
- do {
- if (!ValidParameter(file, sizeof(HANDLE), WRITE))
- break;
- if (!ValidParameter(io_status, sizeof(IO_STATUS_BLOCK), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- uint32_t attributes;
- NTSTATUS ret = AllocAndCopyName(object_attributes, &name, &attributes,
- NULL);
- if (!NT_SUCCESS(ret) || NULL == name)
- break;
-
- uint32_t desired_access_uint32 = desired_access;
- uint32_t options_uint32 = options;
- uint32_t disposition_uint32 = FILE_OPEN;
- uint32_t broker = FALSE;
- CountedParameterSet<OpenFile> params;
- params[OpenFile::NAME] = ParamPickerMake(name);
- params[OpenFile::ACCESS] = ParamPickerMake(desired_access_uint32);
- params[OpenFile::DISPOSITION] = ParamPickerMake(disposition_uint32);
- params[OpenFile::OPTIONS] = ParamPickerMake(options_uint32);
- params[OpenFile::BROKER] = ParamPickerMake(broker);
-
- if (!QueryBroker(IPC_NTOPENFILE_TAG, params.GetBase()))
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTOPENFILE_TAG, name, attributes,
- desired_access_uint32, sharing, options_uint32,
- &answer);
- if (SBOX_ALL_OK != code)
- break;
-
- status = answer.nt_status;
-
- if (!NT_SUCCESS(answer.nt_status))
- break;
-
- __try {
- *file = answer.handle;
- io_status->Status = answer.nt_status;
- io_status->Information = answer.extended[0].ulong_ptr;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
- mozilla::sandboxing::LogAllowed("NtOpenFile",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- } while (false);
-
- if (name)
- operator delete(name, NT_ALLOC);
-
- return status;
-}
-
-NTSTATUS WINAPI TargetNtQueryAttributesFile(
- NtQueryAttributesFileFunction orig_QueryAttributes,
- POBJECT_ATTRIBUTES object_attributes,
- PFILE_BASIC_INFORMATION file_attributes) {
- // Check if the process can query it first.
- NTSTATUS status = orig_QueryAttributes(object_attributes, file_attributes);
- if (STATUS_ACCESS_DENIED != status)
- return status;
-
- mozilla::sandboxing::LogBlocked("NtQueryAttributesFile",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- wchar_t* name = NULL;
- do {
- if (!ValidParameter(file_attributes, sizeof(FILE_BASIC_INFORMATION), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- uint32_t attributes = 0;
- NTSTATUS ret = AllocAndCopyName(object_attributes, &name, &attributes,
- NULL);
- if (!NT_SUCCESS(ret) || NULL == name)
- break;
-
- InOutCountedBuffer file_info(file_attributes,
- sizeof(FILE_BASIC_INFORMATION));
-
- uint32_t broker = FALSE;
- CountedParameterSet<FileName> params;
- params[FileName::NAME] = ParamPickerMake(name);
- params[FileName::BROKER] = ParamPickerMake(broker);
-
- if (!QueryBroker(IPC_NTQUERYATTRIBUTESFILE_TAG, params.GetBase()))
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTQUERYATTRIBUTESFILE_TAG, name,
- attributes, file_info, &answer);
-
- if (SBOX_ALL_OK != code)
- break;
-
- status = answer.nt_status;
-
- mozilla::sandboxing::LogAllowed("NtQueryAttributesFile",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- } while (false);
-
- if (name)
- operator delete(name, NT_ALLOC);
-
- return status;
-}
-
-NTSTATUS WINAPI TargetNtQueryFullAttributesFile(
- NtQueryFullAttributesFileFunction orig_QueryFullAttributes,
- POBJECT_ATTRIBUTES object_attributes,
- PFILE_NETWORK_OPEN_INFORMATION file_attributes) {
- // Check if the process can query it first.
- NTSTATUS status = orig_QueryFullAttributes(object_attributes,
- file_attributes);
- if (STATUS_ACCESS_DENIED != status)
- return status;
-
- mozilla::sandboxing::LogBlocked("NtQueryFullAttributesFile",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- wchar_t* name = NULL;
- do {
- if (!ValidParameter(file_attributes, sizeof(FILE_NETWORK_OPEN_INFORMATION),
- WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- uint32_t attributes = 0;
- NTSTATUS ret = AllocAndCopyName(object_attributes, &name, &attributes,
- NULL);
- if (!NT_SUCCESS(ret) || NULL == name)
- break;
-
- InOutCountedBuffer file_info(file_attributes,
- sizeof(FILE_NETWORK_OPEN_INFORMATION));
-
- uint32_t broker = FALSE;
- CountedParameterSet<FileName> params;
- params[FileName::NAME] = ParamPickerMake(name);
- params[FileName::BROKER] = ParamPickerMake(broker);
-
- if (!QueryBroker(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, params.GetBase()))
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTQUERYFULLATTRIBUTESFILE_TAG, name,
- attributes, file_info, &answer);
-
- if (SBOX_ALL_OK != code)
- break;
-
- status = answer.nt_status;
-
- mozilla::sandboxing::LogAllowed("NtQueryFullAttributesFile",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- } while (false);
-
- if (name)
- operator delete(name, NT_ALLOC);
-
- return status;
-}
-
-NTSTATUS WINAPI TargetNtSetInformationFile(
- NtSetInformationFileFunction orig_SetInformationFile, HANDLE file,
- PIO_STATUS_BLOCK io_status, PVOID file_info, ULONG length,
- FILE_INFORMATION_CLASS file_info_class) {
- // Check if the process can open it first.
- NTSTATUS status = orig_SetInformationFile(file, io_status, file_info, length,
- file_info_class);
- if (STATUS_ACCESS_DENIED != status)
- return status;
-
- mozilla::sandboxing::LogBlocked("NtSetInformationFile");
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- wchar_t* name = NULL;
- do {
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- if (!ValidParameter(io_status, sizeof(IO_STATUS_BLOCK), WRITE))
- break;
-
- if (!ValidParameter(file_info, length, READ))
- break;
-
- FILE_RENAME_INFORMATION* file_rename_info =
- reinterpret_cast<FILE_RENAME_INFORMATION*>(file_info);
- OBJECT_ATTRIBUTES object_attributes;
- UNICODE_STRING object_name;
- InitializeObjectAttributes(&object_attributes, &object_name, 0, NULL, NULL);
-
- __try {
- if (!IsSupportedRenameCall(file_rename_info, length, file_info_class))
- break;
-
- object_attributes.RootDirectory = file_rename_info->RootDirectory;
- object_name.Buffer = file_rename_info->FileName;
- object_name.Length = object_name.MaximumLength =
- static_cast<USHORT>(file_rename_info->FileNameLength);
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
-
- NTSTATUS ret = AllocAndCopyName(&object_attributes, &name, NULL, NULL);
- if (!NT_SUCCESS(ret) || !name)
- break;
-
- uint32_t broker = FALSE;
- CountedParameterSet<FileName> params;
- params[FileName::NAME] = ParamPickerMake(name);
- params[FileName::BROKER] = ParamPickerMake(broker);
-
- if (!QueryBroker(IPC_NTSETINFO_RENAME_TAG, params.GetBase()))
- break;
-
- InOutCountedBuffer io_status_buffer(io_status, sizeof(IO_STATUS_BLOCK));
- // This is actually not an InOut buffer, only In, but using InOut facility
- // really helps to simplify the code.
- InOutCountedBuffer file_info_buffer(file_info, length);
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTSETINFO_RENAME_TAG, file,
- io_status_buffer, file_info_buffer, length,
- file_info_class, &answer);
-
- if (SBOX_ALL_OK != code)
- break;
-
- status = answer.nt_status;
- mozilla::sandboxing::LogAllowed("NtSetInformationFile");
- } while (false);
-
- if (name)
- operator delete(name, NT_ALLOC);
-
- return status;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.h b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.h
deleted file mode 100644
index 2fafb4499..000000000
--- a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.h
+++ /dev/null
@@ -1,53 +0,0 @@
-// 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 "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_FILESYSTEM_INTERCEPTION_H__
-#define SANDBOX_SRC_FILESYSTEM_INTERCEPTION_H__
-
-namespace sandbox {
-
-extern "C" {
-
-// Interception of NtCreateFile on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateFile(
- NtCreateFileFunction orig_CreateFile, PHANDLE file,
- ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes,
- PIO_STATUS_BLOCK io_status, PLARGE_INTEGER allocation_size,
- ULONG file_attributes, ULONG sharing, ULONG disposition, ULONG options,
- PVOID ea_buffer, ULONG ea_length);
-
-// Interception of NtOpenFile on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenFile(
- NtOpenFileFunction orig_OpenFile, PHANDLE file, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
- ULONG sharing, ULONG options);
-
-// Interception of NtQueryAtttributesFile on the child process.
-// It should never be called directly.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryAttributesFile(
- NtQueryAttributesFileFunction orig_QueryAttributes,
- POBJECT_ATTRIBUTES object_attributes,
- PFILE_BASIC_INFORMATION file_attributes);
-
-// Interception of NtQueryFullAtttributesFile on the child process.
-// It should never be called directly.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryFullAttributesFile(
- NtQueryFullAttributesFileFunction orig_QueryAttributes,
- POBJECT_ATTRIBUTES object_attributes,
- PFILE_NETWORK_OPEN_INFORMATION file_attributes);
-
-// Interception of NtSetInformationFile on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationFile(
- NtSetInformationFileFunction orig_SetInformationFile, HANDLE file,
- PIO_STATUS_BLOCK io_status, PVOID file_information, ULONG length,
- FILE_INFORMATION_CLASS file_information_class);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_FILESYSTEM_INTERCEPTION_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_policy.cc b/security/sandbox/chromium/sandbox/win/src/filesystem_policy.cc
deleted file mode 100644
index fe7f62fc2..000000000
--- a/security/sandbox/chromium/sandbox/win/src/filesystem_policy.cc
+++ /dev/null
@@ -1,435 +0,0 @@
-// 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 <stdint.h>
-
-#include <string>
-
-#include "sandbox/win/src/filesystem_policy.h"
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sandbox_utils.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-NTSTATUS NtCreateFileInTarget(HANDLE* target_file_handle,
- ACCESS_MASK desired_access,
- OBJECT_ATTRIBUTES* obj_attributes,
- IO_STATUS_BLOCK* io_status_block,
- ULONG file_attributes,
- ULONG share_access,
- ULONG create_disposition,
- ULONG create_options,
- PVOID ea_buffer,
- ULONG ea_lenght,
- HANDLE target_process) {
- NtCreateFileFunction NtCreateFile = NULL;
- ResolveNTFunctionPtr("NtCreateFile", &NtCreateFile);
-
- HANDLE local_handle = INVALID_HANDLE_VALUE;
- NTSTATUS status = NtCreateFile(&local_handle, desired_access, obj_attributes,
- io_status_block, NULL, file_attributes,
- share_access, create_disposition,
- create_options, ea_buffer, ea_lenght);
- if (!NT_SUCCESS(status)) {
- return status;
- }
-
- if (!sandbox::SameObject(local_handle, obj_attributes->ObjectName->Buffer)) {
- // The handle points somewhere else. Fail the operation.
- ::CloseHandle(local_handle);
- return STATUS_ACCESS_DENIED;
- }
-
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- target_process, target_file_handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- return STATUS_SUCCESS;
-}
-
-// Get an initialized anonymous level Security QOS.
-SECURITY_QUALITY_OF_SERVICE GetAnonymousQOS() {
- SECURITY_QUALITY_OF_SERVICE security_qos = {0};
- security_qos.Length = sizeof(security_qos);
- security_qos.ImpersonationLevel = SecurityAnonymous;
- // Set dynamic tracking so that a pipe doesn't capture the broker's token
- security_qos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
- security_qos.EffectiveOnly = TRUE;
-
- return security_qos;
-}
-
-} // namespace.
-
-namespace sandbox {
-
-bool FileSystemPolicy::GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy) {
- base::string16 mod_name(name);
- if (mod_name.empty()) {
- return false;
- }
-
- if (!PreProcessName(&mod_name)) {
- // The path to be added might contain a reparse point.
- NOTREACHED();
- return false;
- }
-
- // TODO(cpu) bug 32224: This prefix add is a hack because we don't have the
- // infrastructure to normalize names. In any case we need to escape the
- // question marks.
- if (_wcsnicmp(mod_name.c_str(), kNTDevicePrefix, kNTDevicePrefixLen)) {
- mod_name = FixNTPrefixForMatch(mod_name);
- name = mod_name.c_str();
- }
-
- EvalResult result = ASK_BROKER;
-
- // List of supported calls for the filesystem.
- const unsigned kCallNtCreateFile = 0x1;
- const unsigned kCallNtOpenFile = 0x2;
- const unsigned kCallNtQueryAttributesFile = 0x4;
- const unsigned kCallNtQueryFullAttributesFile = 0x8;
- const unsigned kCallNtSetInfoRename = 0x10;
-
- DWORD rule_to_add = kCallNtOpenFile | kCallNtCreateFile |
- kCallNtQueryAttributesFile |
- kCallNtQueryFullAttributesFile | kCallNtSetInfoRename;
-
- PolicyRule create(result);
- PolicyRule open(result);
- PolicyRule query(result);
- PolicyRule query_full(result);
- PolicyRule rename(result);
-
- switch (semantics) {
- case TargetPolicy::FILES_ALLOW_DIR_ANY: {
- open.AddNumberMatch(IF, OpenFile::OPTIONS, FILE_DIRECTORY_FILE, AND);
- create.AddNumberMatch(IF, OpenFile::OPTIONS, FILE_DIRECTORY_FILE, AND);
- break;
- }
- case TargetPolicy::FILES_ALLOW_READONLY: {
- // We consider all flags that are not known to be readonly as potentially
- // used for write.
- DWORD allowed_flags = FILE_READ_DATA | FILE_READ_ATTRIBUTES |
- FILE_READ_EA | SYNCHRONIZE | FILE_EXECUTE |
- GENERIC_READ | GENERIC_EXECUTE | READ_CONTROL;
- DWORD restricted_flags = ~allowed_flags;
- open.AddNumberMatch(IF_NOT, OpenFile::ACCESS, restricted_flags, AND);
- open.AddNumberMatch(IF, OpenFile::DISPOSITION, FILE_OPEN, EQUAL);
- create.AddNumberMatch(IF_NOT, OpenFile::ACCESS, restricted_flags, AND);
- create.AddNumberMatch(IF, OpenFile::DISPOSITION, FILE_OPEN, EQUAL);
-
- // Read only access don't work for rename.
- rule_to_add &= ~kCallNtSetInfoRename;
- break;
- }
- case TargetPolicy::FILES_ALLOW_QUERY: {
- // Here we don't want to add policy for the open or the create.
- rule_to_add &= ~(kCallNtOpenFile | kCallNtCreateFile |
- kCallNtSetInfoRename);
- break;
- }
- case TargetPolicy::FILES_ALLOW_ANY: {
- break;
- }
- default: {
- NOTREACHED();
- return false;
- }
- }
-
- if ((rule_to_add & kCallNtCreateFile) &&
- (!create.AddStringMatch(IF, OpenFile::NAME, name, CASE_INSENSITIVE) ||
- !policy->AddRule(IPC_NTCREATEFILE_TAG, &create))) {
- return false;
- }
-
- if ((rule_to_add & kCallNtOpenFile) &&
- (!open.AddStringMatch(IF, OpenFile::NAME, name, CASE_INSENSITIVE) ||
- !policy->AddRule(IPC_NTOPENFILE_TAG, &open))) {
- return false;
- }
-
- if ((rule_to_add & kCallNtQueryAttributesFile) &&
- (!query.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) ||
- !policy->AddRule(IPC_NTQUERYATTRIBUTESFILE_TAG, &query))) {
- return false;
- }
-
- if ((rule_to_add & kCallNtQueryFullAttributesFile) &&
- (!query_full.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE)
- || !policy->AddRule(IPC_NTQUERYFULLATTRIBUTESFILE_TAG,
- &query_full))) {
- return false;
- }
-
- if ((rule_to_add & kCallNtSetInfoRename) &&
- (!rename.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) ||
- !policy->AddRule(IPC_NTSETINFO_RENAME_TAG, &rename))) {
- return false;
- }
-
- return true;
-}
-
-// Right now we insert two rules, to be evaluated before any user supplied rule:
-// - go to the broker if the path doesn't look like the paths that we push on
-// the policy (namely \??\something).
-// - go to the broker if it looks like this is a short-name path.
-//
-// It is possible to add a rule to go to the broker in any case; it would look
-// something like:
-// rule = new PolicyRule(ASK_BROKER);
-// rule->AddNumberMatch(IF_NOT, FileName::BROKER, TRUE, AND);
-// policy->AddRule(service, rule);
-bool FileSystemPolicy::SetInitialRules(LowLevelPolicy* policy) {
- PolicyRule format(ASK_BROKER);
- PolicyRule short_name(ASK_BROKER);
-
- bool rv = format.AddNumberMatch(IF_NOT, FileName::BROKER, TRUE, AND);
- rv &= format.AddStringMatch(IF_NOT, FileName::NAME, L"\\/?/?\\*",
- CASE_SENSITIVE);
-
- rv &= short_name.AddNumberMatch(IF_NOT, FileName::BROKER, TRUE, AND);
- rv &= short_name.AddStringMatch(IF, FileName::NAME, L"*~*", CASE_SENSITIVE);
-
- if (!rv || !policy->AddRule(IPC_NTCREATEFILE_TAG, &format))
- return false;
-
- if (!policy->AddRule(IPC_NTCREATEFILE_TAG, &short_name))
- return false;
-
- if (!policy->AddRule(IPC_NTOPENFILE_TAG, &format))
- return false;
-
- if (!policy->AddRule(IPC_NTOPENFILE_TAG, &short_name))
- return false;
-
- if (!policy->AddRule(IPC_NTQUERYATTRIBUTESFILE_TAG, &format))
- return false;
-
- if (!policy->AddRule(IPC_NTQUERYATTRIBUTESFILE_TAG, &short_name))
- return false;
-
- if (!policy->AddRule(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, &format))
- return false;
-
- if (!policy->AddRule(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, &short_name))
- return false;
-
- if (!policy->AddRule(IPC_NTSETINFO_RENAME_TAG, &format))
- return false;
-
- if (!policy->AddRule(IPC_NTSETINFO_RENAME_TAG, &short_name))
- return false;
-
- return true;
-}
-
-bool FileSystemPolicy::CreateFileAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& file,
- uint32_t attributes,
- uint32_t desired_access,
- uint32_t file_attributes,
- uint32_t share_access,
- uint32_t create_disposition,
- uint32_t create_options,
- HANDLE* handle,
- NTSTATUS* nt_status,
- ULONG_PTR* io_information) {
- // The only action supported is ASK_BROKER which means create the requested
- // file as specified.
- if (ASK_BROKER != eval_result) {
- *nt_status = STATUS_ACCESS_DENIED;
- return false;
- }
- IO_STATUS_BLOCK io_block = {};
- UNICODE_STRING uni_name = {};
- OBJECT_ATTRIBUTES obj_attributes = {};
- SECURITY_QUALITY_OF_SERVICE security_qos = GetAnonymousQOS();
-
- InitObjectAttribs(file, attributes, NULL, &obj_attributes,
- &uni_name, IsPipe(file) ? &security_qos : NULL);
- *nt_status = NtCreateFileInTarget(handle, desired_access, &obj_attributes,
- &io_block, file_attributes, share_access,
- create_disposition, create_options, NULL,
- 0, client_info.process);
-
- *io_information = io_block.Information;
- return true;
-}
-
-bool FileSystemPolicy::OpenFileAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& file,
- uint32_t attributes,
- uint32_t desired_access,
- uint32_t share_access,
- uint32_t open_options,
- HANDLE* handle,
- NTSTATUS* nt_status,
- ULONG_PTR* io_information) {
- // The only action supported is ASK_BROKER which means open the requested
- // file as specified.
- if (ASK_BROKER != eval_result) {
- *nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
- // An NtOpen is equivalent to an NtCreate with FileAttributes = 0 and
- // CreateDisposition = FILE_OPEN.
- IO_STATUS_BLOCK io_block = {};
- UNICODE_STRING uni_name = {};
- OBJECT_ATTRIBUTES obj_attributes = {};
- SECURITY_QUALITY_OF_SERVICE security_qos = GetAnonymousQOS();
-
- InitObjectAttribs(file, attributes, NULL, &obj_attributes,
- &uni_name, IsPipe(file) ? &security_qos : NULL);
- *nt_status = NtCreateFileInTarget(handle, desired_access, &obj_attributes,
- &io_block, 0, share_access, FILE_OPEN,
- open_options, NULL, 0,
- client_info.process);
-
- *io_information = io_block.Information;
- return true;
-}
-
-bool FileSystemPolicy::QueryAttributesFileAction(
- EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& file,
- uint32_t attributes,
- FILE_BASIC_INFORMATION* file_info,
- NTSTATUS* nt_status) {
- // The only action supported is ASK_BROKER which means query the requested
- // file as specified.
- if (ASK_BROKER != eval_result) {
- *nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- NtQueryAttributesFileFunction NtQueryAttributesFile = NULL;
- ResolveNTFunctionPtr("NtQueryAttributesFile", &NtQueryAttributesFile);
-
- UNICODE_STRING uni_name = {0};
- OBJECT_ATTRIBUTES obj_attributes = {0};
- SECURITY_QUALITY_OF_SERVICE security_qos = GetAnonymousQOS();
-
- InitObjectAttribs(file, attributes, NULL, &obj_attributes,
- &uni_name, IsPipe(file) ? &security_qos : NULL);
- *nt_status = NtQueryAttributesFile(&obj_attributes, file_info);
-
- return true;
-}
-
-bool FileSystemPolicy::QueryFullAttributesFileAction(
- EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& file,
- uint32_t attributes,
- FILE_NETWORK_OPEN_INFORMATION* file_info,
- NTSTATUS* nt_status) {
- // The only action supported is ASK_BROKER which means query the requested
- // file as specified.
- if (ASK_BROKER != eval_result) {
- *nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- NtQueryFullAttributesFileFunction NtQueryFullAttributesFile = NULL;
- ResolveNTFunctionPtr("NtQueryFullAttributesFile", &NtQueryFullAttributesFile);
-
- UNICODE_STRING uni_name = {0};
- OBJECT_ATTRIBUTES obj_attributes = {0};
- SECURITY_QUALITY_OF_SERVICE security_qos = GetAnonymousQOS();
-
- InitObjectAttribs(file, attributes, NULL, &obj_attributes,
- &uni_name, IsPipe(file) ? &security_qos : NULL);
- *nt_status = NtQueryFullAttributesFile(&obj_attributes, file_info);
-
- return true;
-}
-
-bool FileSystemPolicy::SetInformationFileAction(EvalResult eval_result,
- const ClientInfo& client_info,
- HANDLE target_file_handle,
- void* file_info,
- uint32_t length,
- uint32_t info_class,
- IO_STATUS_BLOCK* io_block,
- NTSTATUS* nt_status) {
- // The only action supported is ASK_BROKER which means open the requested
- // file as specified.
- if (ASK_BROKER != eval_result) {
- *nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- NtSetInformationFileFunction NtSetInformationFile = NULL;
- ResolveNTFunctionPtr("NtSetInformationFile", &NtSetInformationFile);
-
- HANDLE local_handle = NULL;
- if (!::DuplicateHandle(client_info.process, target_file_handle,
- ::GetCurrentProcess(), &local_handle, 0, FALSE,
- DUPLICATE_SAME_ACCESS)) {
- *nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- base::win::ScopedHandle handle(local_handle);
-
- FILE_INFORMATION_CLASS file_info_class =
- static_cast<FILE_INFORMATION_CLASS>(info_class);
- *nt_status = NtSetInformationFile(local_handle, io_block, file_info, length,
- file_info_class);
-
- return true;
-}
-
-bool PreProcessName(base::string16* path) {
- ConvertToLongPath(path);
-
- if (ERROR_NOT_A_REPARSE_POINT == IsReparsePoint(*path))
- return true;
-
- // We can't process a reparsed file.
- return false;
-}
-
-base::string16 FixNTPrefixForMatch(const base::string16& name) {
- base::string16 mod_name = name;
-
- // NT prefix escaped for rule matcher
- const wchar_t kNTPrefixEscaped[] = L"\\/?/?\\";
- const int kNTPrefixEscapedLen = arraysize(kNTPrefixEscaped) - 1;
-
- if (0 != mod_name.compare(0, kNTPrefixLen, kNTPrefix)) {
- if (0 != mod_name.compare(0, kNTPrefixEscapedLen, kNTPrefixEscaped)) {
- // TODO(nsylvain): Find a better way to do name resolution. Right now we
- // take the name and we expand it.
- mod_name.insert(0, kNTPrefixEscaped);
- }
- } else {
- // Start of name matches NT prefix, replace with escaped format
- // Fixes bug: 334882
- mod_name.replace(0, kNTPrefixLen, kNTPrefixEscaped);
- }
-
- return mod_name;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_policy.h b/security/sandbox/chromium/sandbox/win/src/filesystem_policy.h
deleted file mode 100644
index c2ee160d5..000000000
--- a/security/sandbox/chromium/sandbox/win/src/filesystem_policy.h
+++ /dev/null
@@ -1,113 +0,0 @@
-// 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 SANDBOX_SRC_FILESYSTEM_POLICY_H__
-#define SANDBOX_SRC_FILESYSTEM_POLICY_H__
-
-#include <stdint.h>
-
-#include <string>
-
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/sandbox_policy.h"
-
-namespace sandbox {
-
-enum EvalResult;
-
-// This class centralizes most of the knowledge related to file system policy
-class FileSystemPolicy {
- public:
- // Creates the required low-level policy rules to evaluate a high-level
- // policy rule for File IO, in particular open or create actions.
- // 'name' is the file or directory name.
- // 'semantics' is the desired semantics for the open or create.
- // 'policy' is the policy generator to which the rules are going to be added.
- static bool GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy);
-
- // Add basic file system rules.
- static bool SetInitialRules(LowLevelPolicy* policy);
-
- // Performs the desired policy action on a create request with an
- // API that is compatible with the IPC-received parameters.
- // 'client_info' : the target process that is making the request.
- // 'eval_result' : The desired policy action to accomplish.
- // 'file' : The target file or directory.
- static bool CreateFileAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& file,
- uint32_t attributes,
- uint32_t desired_access,
- uint32_t file_attributes,
- uint32_t share_access,
- uint32_t create_disposition,
- uint32_t create_options,
- HANDLE* handle,
- NTSTATUS* nt_status,
- ULONG_PTR* io_information);
-
- // Performs the desired policy action on an open request with an
- // API that is compatible with the IPC-received parameters.
- // 'client_info' : the target process that is making the request.
- // 'eval_result' : The desired policy action to accomplish.
- // 'file' : The target file or directory.
- static bool OpenFileAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& file,
- uint32_t attributes,
- uint32_t desired_access,
- uint32_t share_access,
- uint32_t open_options,
- HANDLE* handle,
- NTSTATUS* nt_status,
- ULONG_PTR* io_information);
-
- // Performs the desired policy action on a query request with an
- // API that is compatible with the IPC-received parameters.
- static bool QueryAttributesFileAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& file,
- uint32_t attributes,
- FILE_BASIC_INFORMATION* file_info,
- NTSTATUS* nt_status);
-
- // Performs the desired policy action on a query request with an
- // API that is compatible with the IPC-received parameters.
- static bool QueryFullAttributesFileAction(
- EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& file,
- uint32_t attributes,
- FILE_NETWORK_OPEN_INFORMATION* file_info,
- NTSTATUS* nt_status);
-
- // Performs the desired policy action on a set_info request with an
- // API that is compatible with the IPC-received parameters.
- static bool SetInformationFileAction(EvalResult eval_result,
- const ClientInfo& client_info,
- HANDLE target_file_handle,
- void* file_info,
- uint32_t length,
- uint32_t info_class,
- IO_STATUS_BLOCK* io_block,
- NTSTATUS* nt_status);
-};
-
-// Expands the path and check if it's a reparse point. Returns false if the path
-// cannot be trusted.
-bool PreProcessName(base::string16* path);
-
-// Corrects global paths to have a correctly escaped NT prefix at the
-// beginning. If the name has no NT prefix (either normal or escaped)
-// add the escaped form to the string
-base::string16 FixNTPrefixForMatch(const base::string16& name);
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_FILESYSTEM_POLICY_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_closer.cc b/security/sandbox/chromium/sandbox/win/src/handle_closer.cc
deleted file mode 100644
index f2012b7e0..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_closer.cc
+++ /dev/null
@@ -1,196 +0,0 @@
-// 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 "sandbox/win/src/handle_closer.h"
-
-#include <stddef.h>
-
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/internal_types.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/process_thread_interception.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-template<typename T> T RoundUpToWordSize(T v) {
- if (size_t mod = v % sizeof(size_t))
- v += sizeof(size_t) - mod;
- return v;
-}
-
-template<typename T> T* RoundUpToWordSize(T* v) {
- return reinterpret_cast<T*>(RoundUpToWordSize(reinterpret_cast<size_t>(v)));
-}
-
-} // namespace
-
-namespace sandbox {
-
-// Memory buffer mapped from the parent, with the list of handles.
-SANDBOX_INTERCEPT HandleCloserInfo* g_handles_to_close;
-
-HandleCloser::HandleCloser() {
-}
-
-HandleCloser::~HandleCloser() {
-}
-
-ResultCode HandleCloser::AddHandle(const base::char16* handle_type,
- const base::char16* handle_name) {
- if (!handle_type)
- return SBOX_ERROR_BAD_PARAMS;
-
- base::string16 resolved_name;
- if (handle_name) {
- resolved_name = handle_name;
- if (handle_type == base::string16(L"Key"))
- if (!ResolveRegistryName(resolved_name, &resolved_name))
- return SBOX_ERROR_BAD_PARAMS;
- }
-
- HandleMap::iterator names = handles_to_close_.find(handle_type);
- if (names == handles_to_close_.end()) { // We have no entries for this type.
- std::pair<HandleMap::iterator, bool> result = handles_to_close_.insert(
- HandleMap::value_type(handle_type, HandleMap::mapped_type()));
- names = result.first;
- if (handle_name)
- names->second.insert(resolved_name);
- } else if (!handle_name) { // Now we need to close all handles of this type.
- names->second.clear();
- } else if (!names->second.empty()) { // Add another name for this type.
- names->second.insert(resolved_name);
- } // If we're already closing all handles of type then we're done.
-
- return SBOX_ALL_OK;
-}
-
-size_t HandleCloser::GetBufferSize() {
- size_t bytes_total = offsetof(HandleCloserInfo, handle_entries);
-
- for (HandleMap::iterator i = handles_to_close_.begin();
- i != handles_to_close_.end(); ++i) {
- size_t bytes_entry = offsetof(HandleListEntry, handle_type) +
- (i->first.size() + 1) * sizeof(base::char16);
- for (HandleMap::mapped_type::iterator j = i->second.begin();
- j != i->second.end(); ++j) {
- bytes_entry += ((*j).size() + 1) * sizeof(base::char16);
- }
-
- // Round up to the nearest multiple of word size.
- bytes_entry = RoundUpToWordSize(bytes_entry);
- bytes_total += bytes_entry;
- }
-
- return bytes_total;
-}
-
-bool HandleCloser::InitializeTargetHandles(TargetProcess* target) {
- // Do nothing on an empty list (global pointer already initialized to NULL).
- if (handles_to_close_.empty())
- return true;
-
- size_t bytes_needed = GetBufferSize();
- scoped_ptr<size_t[]> local_buffer(
- new size_t[bytes_needed / sizeof(size_t)]);
-
- if (!SetupHandleList(local_buffer.get(), bytes_needed))
- return false;
-
- HANDLE child = target->Process();
-
- // Allocate memory in the target process without specifying the address
- void* remote_data = ::VirtualAllocEx(child, NULL, bytes_needed,
- MEM_COMMIT, PAGE_READWRITE);
- if (NULL == remote_data)
- return false;
-
- // Copy the handle buffer over.
- SIZE_T bytes_written;
- BOOL result = ::WriteProcessMemory(child, remote_data, local_buffer.get(),
- bytes_needed, &bytes_written);
- if (!result || bytes_written != bytes_needed) {
- ::VirtualFreeEx(child, remote_data, 0, MEM_RELEASE);
- return false;
- }
-
- g_handles_to_close = reinterpret_cast<HandleCloserInfo*>(remote_data);
-
- ResultCode rc = target->TransferVariable("g_handles_to_close",
- &g_handles_to_close,
- sizeof(g_handles_to_close));
-
- return (SBOX_ALL_OK == rc);
-}
-
-bool HandleCloser::SetupHandleList(void* buffer, size_t buffer_bytes) {
- ::ZeroMemory(buffer, buffer_bytes);
- HandleCloserInfo* handle_info = reinterpret_cast<HandleCloserInfo*>(buffer);
- handle_info->record_bytes = buffer_bytes;
- handle_info->num_handle_types = handles_to_close_.size();
-
- base::char16* output = reinterpret_cast<base::char16*>(
- &handle_info->handle_entries[0]);
- base::char16* end = reinterpret_cast<base::char16*>(
- reinterpret_cast<char*>(buffer) + buffer_bytes);
- for (HandleMap::iterator i = handles_to_close_.begin();
- i != handles_to_close_.end(); ++i) {
- if (output >= end)
- return false;
- HandleListEntry* list_entry = reinterpret_cast<HandleListEntry*>(output);
- output = &list_entry->handle_type[0];
-
- // Copy the typename and set the offset and count.
- i->first._Copy_s(output, i->first.size(), i->first.size());
- *(output += i->first.size()) = L'\0';
- output++;
- list_entry->offset_to_names = reinterpret_cast<char*>(output) -
- reinterpret_cast<char*>(list_entry);
- list_entry->name_count = i->second.size();
-
- // Copy the handle names.
- for (HandleMap::mapped_type::iterator j = i->second.begin();
- j != i->second.end(); ++j) {
- output = std::copy((*j).begin(), (*j).end(), output) + 1;
- }
-
- // Round up to the nearest multiple of sizeof(size_t).
- output = RoundUpToWordSize(output);
- list_entry->record_bytes = reinterpret_cast<char*>(output) -
- reinterpret_cast<char*>(list_entry);
- }
-
- DCHECK_EQ(reinterpret_cast<size_t>(output), reinterpret_cast<size_t>(end));
- return output <= end;
-}
-
-bool GetHandleName(HANDLE handle, base::string16* handle_name) {
- static NtQueryObject QueryObject = NULL;
- if (!QueryObject)
- ResolveNTFunctionPtr("NtQueryObject", &QueryObject);
-
- ULONG size = MAX_PATH;
- scoped_ptr<UNICODE_STRING, base::FreeDeleter> name;
- NTSTATUS result;
-
- do {
- name.reset(static_cast<UNICODE_STRING*>(malloc(size)));
- DCHECK(name.get());
- result = QueryObject(handle, ObjectNameInformation, name.get(),
- size, &size);
- } while (result == STATUS_INFO_LENGTH_MISMATCH ||
- result == STATUS_BUFFER_OVERFLOW);
-
- if (NT_SUCCESS(result) && name->Buffer && name->Length)
- handle_name->assign(name->Buffer, name->Length / sizeof(wchar_t));
- else
- handle_name->clear();
-
- return NT_SUCCESS(result);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_closer.h b/security/sandbox/chromium/sandbox/win/src/handle_closer.h
deleted file mode 100644
index 9592230a0..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_closer.h
+++ /dev/null
@@ -1,76 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_HANDLE_CLOSER_H_
-#define SANDBOX_SRC_HANDLE_CLOSER_H_
-
-#include <stddef.h>
-
-#include <map>
-#include <set>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/target_process.h"
-
-namespace sandbox {
-
-// This is a map of handle-types to names that we need to close in the
-// target process. A null set means we need to close all handles of the
-// given type.
-typedef std::map<const base::string16, std::set<base::string16> > HandleMap;
-
-// Type and set of corresponding handle names to close.
-struct HandleListEntry {
- size_t record_bytes; // Rounded to sizeof(size_t) bytes.
- size_t offset_to_names; // Nul terminated strings of name_count names.
- size_t name_count;
- base::char16 handle_type[1];
-};
-
-// Global parameters and a pointer to the list of entries.
-struct HandleCloserInfo {
- size_t record_bytes; // Rounded to sizeof(size_t) bytes.
- size_t num_handle_types;
- struct HandleListEntry handle_entries[1];
-};
-
-SANDBOX_INTERCEPT HandleCloserInfo* g_handle_closer_info;
-
-// Adds handles to close after lockdown.
-class HandleCloser {
- public:
- HandleCloser();
- ~HandleCloser();
-
- // Adds a handle that will be closed in the target process after lockdown.
- // A NULL value for handle_name indicates all handles of the specified type.
- // An empty string for handle_name indicates the handle is unnamed.
- ResultCode AddHandle(const base::char16* handle_type,
- const base::char16* handle_name);
-
- // Serializes and copies the closer table into the target process.
- bool InitializeTargetHandles(TargetProcess* target);
-
- private:
- // Calculates the memory needed to copy the serialized handles list (rounded
- // to the nearest machine-word size).
- size_t GetBufferSize();
-
- // Serializes the handle list into the target process.
- bool SetupHandleList(void* buffer, size_t buffer_bytes);
-
- HandleMap handles_to_close_;
-
- DISALLOW_COPY_AND_ASSIGN(HandleCloser);
-};
-
-// Returns the object manager's name associated with a handle
-bool GetHandleName(HANDLE handle, base::string16* handle_name);
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_HANDLE_CLOSER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_closer_agent.cc b/security/sandbox/chromium/sandbox/win/src/handle_closer_agent.cc
deleted file mode 100644
index 6b17f6547..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_closer_agent.cc
+++ /dev/null
@@ -1,203 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/handle_closer_agent.h"
-
-#include <limits.h>
-#include <stddef.h>
-
-#include "base/logging.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-// Returns type infomation for an NT object. This routine is expected to be
-// called for invalid handles so it catches STATUS_INVALID_HANDLE exceptions
-// that can be generated when handle tracing is enabled.
-NTSTATUS QueryObjectTypeInformation(HANDLE handle,
- void* buffer,
- ULONG* size) {
- static NtQueryObject QueryObject = NULL;
- if (!QueryObject)
- ResolveNTFunctionPtr("NtQueryObject", &QueryObject);
-
- NTSTATUS status = STATUS_UNSUCCESSFUL;
- __try {
- status = QueryObject(handle, ObjectTypeInformation, buffer, *size, size);
- } __except(GetExceptionCode() == STATUS_INVALID_HANDLE ?
- EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
- status = STATUS_INVALID_HANDLE;
- }
- return status;
-}
-
-} // namespace
-
-namespace sandbox {
-
-// Memory buffer mapped from the parent, with the list of handles.
-SANDBOX_INTERCEPT HandleCloserInfo* g_handles_to_close = NULL;
-
-bool HandleCloserAgent::NeedsHandlesClosed() {
- return g_handles_to_close != NULL;
-}
-
-HandleCloserAgent::HandleCloserAgent()
- : dummy_handle_(::CreateEvent(NULL, FALSE, FALSE, NULL)) {
-}
-
-HandleCloserAgent::~HandleCloserAgent() {
-}
-
-// Attempts to stuff |closed_handle| with a duplicated handle for a dummy Event
-// with no access. This should allow the handle to be closed, to avoid
-// generating EXCEPTION_INVALID_HANDLE on shutdown, but nothing else. For now
-// the only supported |type| is Event or File.
-bool HandleCloserAgent::AttemptToStuffHandleSlot(HANDLE closed_handle,
- const base::string16& type) {
- // Only attempt to stuff Files and Events at the moment.
- if (type != L"Event" && type != L"File") {
- return true;
- }
-
- if (!dummy_handle_.IsValid())
- return false;
-
- // This should never happen, as g_dummy is created before closing to_stuff.
- DCHECK(dummy_handle_.Get() != closed_handle);
-
- std::vector<HANDLE> to_close;
- HANDLE dup_dummy = NULL;
- size_t count = 16;
-
- do {
- if (!::DuplicateHandle(::GetCurrentProcess(), dummy_handle_.Get(),
- ::GetCurrentProcess(), &dup_dummy, 0, FALSE, 0))
- break;
- if (dup_dummy != closed_handle)
- to_close.push_back(dup_dummy);
- } while (count-- &&
- reinterpret_cast<uintptr_t>(dup_dummy) <
- reinterpret_cast<uintptr_t>(closed_handle));
-
- for (auto h : to_close)
- ::CloseHandle(h);
-
- // Useful to know when we're not able to stuff handles.
- DCHECK(dup_dummy == closed_handle);
-
- return dup_dummy == closed_handle;
-}
-
-// Reads g_handles_to_close and creates the lookup map.
-void HandleCloserAgent::InitializeHandlesToClose(bool* is_csrss_connected) {
- CHECK(g_handles_to_close != NULL);
-
- // Default to connected state
- *is_csrss_connected = true;
-
- // Grab the header.
- HandleListEntry* entry = g_handles_to_close->handle_entries;
- for (size_t i = 0; i < g_handles_to_close->num_handle_types; ++i) {
- // Set the type name.
- base::char16* input = entry->handle_type;
- if (!wcscmp(input, L"ALPC Port")) {
- *is_csrss_connected = false;
- }
- HandleMap::mapped_type& handle_names = handles_to_close_[input];
- input = reinterpret_cast<base::char16*>(reinterpret_cast<char*>(entry)
- + entry->offset_to_names);
- // Grab all the handle names.
- for (size_t j = 0; j < entry->name_count; ++j) {
- std::pair<HandleMap::mapped_type::iterator, bool> name
- = handle_names.insert(input);
- CHECK(name.second);
- input += name.first->size() + 1;
- }
-
- // Move on to the next entry.
- entry = reinterpret_cast<HandleListEntry*>(reinterpret_cast<char*>(entry)
- + entry->record_bytes);
-
- DCHECK(reinterpret_cast<base::char16*>(entry) >= input);
- DCHECK(reinterpret_cast<base::char16*>(entry) - input <
- static_cast<ptrdiff_t>(sizeof(size_t) / sizeof(base::char16)));
- }
-
- // Clean up the memory we copied over.
- ::VirtualFree(g_handles_to_close, 0, MEM_RELEASE);
- g_handles_to_close = NULL;
-}
-
-bool HandleCloserAgent::CloseHandles() {
- DWORD handle_count = UINT_MAX;
- const int kInvalidHandleThreshold = 100;
- const size_t kHandleOffset = 4; // Handles are always a multiple of 4.
-
- if (!::GetProcessHandleCount(::GetCurrentProcess(), &handle_count))
- return false;
-
- // Set up buffers for the type info and the name.
- std::vector<BYTE> type_info_buffer(sizeof(OBJECT_TYPE_INFORMATION) +
- 32 * sizeof(wchar_t));
- OBJECT_TYPE_INFORMATION* type_info =
- reinterpret_cast<OBJECT_TYPE_INFORMATION*>(&(type_info_buffer[0]));
- base::string16 handle_name;
- HANDLE handle = NULL;
- int invalid_count = 0;
-
- // Keep incrementing until we hit the number of handles reported by
- // GetProcessHandleCount(). If we hit a very long sequence of invalid
- // handles we assume that we've run past the end of the table.
- while (handle_count && invalid_count < kInvalidHandleThreshold) {
- reinterpret_cast<size_t&>(handle) += kHandleOffset;
- NTSTATUS rc;
-
- // Get the type name, reusing the buffer.
- ULONG size = static_cast<ULONG>(type_info_buffer.size());
- rc = QueryObjectTypeInformation(handle, type_info, &size);
- while (rc == STATUS_INFO_LENGTH_MISMATCH ||
- rc == STATUS_BUFFER_OVERFLOW) {
- type_info_buffer.resize(size + sizeof(wchar_t));
- type_info = reinterpret_cast<OBJECT_TYPE_INFORMATION*>(
- &(type_info_buffer[0]));
- rc = QueryObjectTypeInformation(handle, type_info, &size);
- // Leave padding for the nul terminator.
- if (NT_SUCCESS(rc) && size == type_info_buffer.size())
- rc = STATUS_INFO_LENGTH_MISMATCH;
- }
- if (!NT_SUCCESS(rc) || !type_info->Name.Buffer) {
- ++invalid_count;
- continue;
- }
-
- --handle_count;
- type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
-
- // Check if we're looking for this type of handle.
- HandleMap::iterator result =
- handles_to_close_.find(type_info->Name.Buffer);
- if (result != handles_to_close_.end()) {
- HandleMap::mapped_type& names = result->second;
- // Empty set means close all handles of this type; otherwise check name.
- if (!names.empty()) {
- // Move on to the next handle if this name doesn't match.
- if (!GetHandleName(handle, &handle_name) || !names.count(handle_name))
- continue;
- }
-
- if (!::SetHandleInformation(handle, HANDLE_FLAG_PROTECT_FROM_CLOSE, 0))
- return false;
- if (!::CloseHandle(handle))
- return false;
- // Attempt to stuff this handle with a new dummy Event.
- AttemptToStuffHandleSlot(handle, result->first);
- }
- }
-
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_closer_agent.h b/security/sandbox/chromium/sandbox/win/src/handle_closer_agent.h
deleted file mode 100644
index 042c98eaf..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_closer_agent.h
+++ /dev/null
@@ -1,47 +0,0 @@
-// 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 SANDBOX_SRC_HANDLE_CLOSER_AGENT_H_
-#define SANDBOX_SRC_HANDLE_CLOSER_AGENT_H_
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/handle_closer.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/target_services.h"
-
-
-namespace sandbox {
-
-// Target process code to close the handle list copied over from the broker.
-class HandleCloserAgent {
- public:
- HandleCloserAgent();
- ~HandleCloserAgent();
-
- // Reads the serialized list from the broker and creates the lookup map.
- // Updates is_csrss_connected based on type of handles closed.
- void InitializeHandlesToClose(bool* is_csrss_connected);
-
- // Closes any handles matching those in the lookup map.
- bool CloseHandles();
-
- // True if we have handles waiting to be closed.
- static bool NeedsHandlesClosed();
-
- private:
- // Attempt to stuff a closed handle with a dummy Event.
- bool AttemptToStuffHandleSlot(HANDLE closed_handle,
- const base::string16& type);
-
- HandleMap handles_to_close_;
- base::win::ScopedHandle dummy_handle_;
-
- DISALLOW_COPY_AND_ASSIGN(HandleCloserAgent);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_HANDLE_CLOSER_AGENT_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_closer_test.cc b/security/sandbox/chromium/sandbox/win/src/handle_closer_test.cc
deleted file mode 100644
index ceba818a7..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_closer_test.cc
+++ /dev/null
@@ -1,300 +0,0 @@
-// 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 <limits.h>
-#include <stddef.h>
-
-#include "base/strings/stringprintf.h"
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/handle_closer_agent.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/target_services.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-
-const wchar_t *kFileExtensions[] = { L".1", L".2", L".3", L".4" };
-
-// Returns a handle to a unique marker file that can be retrieved between runs.
-HANDLE GetMarkerFile(const wchar_t *extension) {
- wchar_t path_buffer[MAX_PATH + 1];
- CHECK(::GetTempPath(MAX_PATH, path_buffer));
- base::string16 marker_path = path_buffer;
- marker_path += L"\\sbox_marker_";
-
- // Generate a unique value from the exe's size and timestamp.
- CHECK(::GetModuleFileName(NULL, path_buffer, MAX_PATH));
- base::win::ScopedHandle module(::CreateFile(path_buffer,
- FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL,
- OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
- CHECK(module.IsValid());
- FILETIME timestamp;
- CHECK(::GetFileTime(module.Get(), &timestamp, NULL, NULL));
- marker_path += base::StringPrintf(L"%08x%08x%08x",
- ::GetFileSize(module.Get(), NULL),
- timestamp.dwLowDateTime,
- timestamp.dwHighDateTime);
- marker_path += extension;
-
- // Make the file delete-on-close so cleanup is automatic.
- return CreateFile(marker_path.c_str(), FILE_ALL_ACCESS,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
- NULL, OPEN_ALWAYS, FILE_FLAG_DELETE_ON_CLOSE, NULL);
-}
-
-// Returns type infomation for an NT object. This routine is expected to be
-// called for invalid handles so it catches STATUS_INVALID_HANDLE exceptions
-// that can be generated when handle tracing is enabled.
-NTSTATUS QueryObjectTypeInformation(HANDLE handle, void* buffer, ULONG* size) {
- static NtQueryObject QueryObject = NULL;
- if (!QueryObject)
- ResolveNTFunctionPtr("NtQueryObject", &QueryObject);
-
- NTSTATUS status = STATUS_UNSUCCESSFUL;
- __try {
- status = QueryObject(handle, ObjectTypeInformation, buffer, *size, size);
- }
- __except(GetExceptionCode() == STATUS_INVALID_HANDLE
- ? EXCEPTION_EXECUTE_HANDLER
- : EXCEPTION_CONTINUE_SEARCH) {
- status = STATUS_INVALID_HANDLE;
- }
- return status;
-}
-
-// Used by the thread pool tests.
-HANDLE finish_event;
-const int kWaitCount = 20;
-
-} // namespace
-
-namespace sandbox {
-
-// Checks for the presence of a list of files (in object path form).
-// Format: CheckForFileHandle (Y|N) \path\to\file1 [\path\to\file2 ...]
-// - Y or N depending if the file should exist or not.
-SBOX_TESTS_COMMAND int CheckForFileHandles(int argc, wchar_t **argv) {
- if (argc < 2)
- return SBOX_TEST_FAILED_TO_RUN_TEST;
- bool should_find = argv[0][0] == L'Y';
- if (argv[0][1] != L'\0' || (!should_find && argv[0][0] != L'N'))
- return SBOX_TEST_FAILED_TO_RUN_TEST;
-
- static int state = BEFORE_INIT;
- switch (state++) {
- case BEFORE_INIT:
- // Create a unique marker file that is open while the test is running.
- // The handles leak, but it will be closed by the test or on exit.
- for (const wchar_t* kExtension : kFileExtensions)
- CHECK_NE(GetMarkerFile(kExtension), INVALID_HANDLE_VALUE);
- return SBOX_TEST_SUCCEEDED;
-
- case AFTER_REVERT: {
- // Brute force the handle table to find what we're looking for.
- DWORD handle_count = UINT_MAX;
- const int kInvalidHandleThreshold = 100;
- const size_t kHandleOffset = 4; // Handles are always a multiple of 4.
- HANDLE handle = NULL;
- int invalid_count = 0;
- base::string16 handle_name;
-
- if (!::GetProcessHandleCount(::GetCurrentProcess(), &handle_count))
- return SBOX_TEST_FAILED_TO_RUN_TEST;
-
- while (handle_count && invalid_count < kInvalidHandleThreshold) {
- reinterpret_cast<size_t&>(handle) += kHandleOffset;
- if (GetHandleName(handle, &handle_name)) {
- for (int i = 1; i < argc; ++i) {
- if (handle_name == argv[i])
- return should_find ? SBOX_TEST_SUCCEEDED : SBOX_TEST_FAILED;
- }
- --handle_count;
- } else {
- ++invalid_count;
- }
- }
-
- return should_find ? SBOX_TEST_FAILED : SBOX_TEST_SUCCEEDED;
- }
-
- default: // Do nothing.
- break;
- }
-
- return SBOX_TEST_SUCCEEDED;
-}
-
-// Checks that supplied handle is an Event and it's not waitable.
-// Format: CheckForEventHandles
-SBOX_TESTS_COMMAND int CheckForEventHandles(int argc, wchar_t** argv) {
- static int state = BEFORE_INIT;
- static std::vector<HANDLE> to_check;
-
- switch (state++) {
- case BEFORE_INIT:
- // Create a unique marker file that is open while the test is running.
- for (const wchar_t* kExtension : kFileExtensions) {
- HANDLE handle = GetMarkerFile(kExtension);
- CHECK_NE(handle, INVALID_HANDLE_VALUE);
- to_check.push_back(handle);
- }
- return SBOX_TEST_SUCCEEDED;
-
- case AFTER_REVERT:
- for (auto handle : to_check) {
- // Set up buffers for the type info and the name.
- std::vector<BYTE> type_info_buffer(sizeof(OBJECT_TYPE_INFORMATION) +
- 32 * sizeof(wchar_t));
- OBJECT_TYPE_INFORMATION* type_info =
- reinterpret_cast<OBJECT_TYPE_INFORMATION*>(&(type_info_buffer[0]));
- NTSTATUS rc;
-
- // Get the type name, reusing the buffer.
- ULONG size = static_cast<ULONG>(type_info_buffer.size());
- rc = QueryObjectTypeInformation(handle, type_info, &size);
- while (rc == STATUS_INFO_LENGTH_MISMATCH ||
- rc == STATUS_BUFFER_OVERFLOW) {
- type_info_buffer.resize(size + sizeof(wchar_t));
- type_info = reinterpret_cast<OBJECT_TYPE_INFORMATION*>(
- &(type_info_buffer[0]));
- rc = QueryObjectTypeInformation(handle, type_info, &size);
- // Leave padding for the nul terminator.
- if (NT_SUCCESS(rc) && size == type_info_buffer.size())
- rc = STATUS_INFO_LENGTH_MISMATCH;
- }
-
- CHECK(NT_SUCCESS(rc));
- CHECK(type_info->Name.Buffer);
-
- type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] =
- L'\0';
-
- // Should be an Event now.
- CHECK_EQ(wcslen(type_info->Name.Buffer), 5U);
- CHECK_EQ(wcscmp(L"Event", type_info->Name.Buffer), 0);
-
- // Should not be able to wait.
- CHECK_EQ(WaitForSingleObject(handle, INFINITE), WAIT_FAILED);
-
- // Should be able to close.
- CHECK_EQ(TRUE, CloseHandle(handle));
- }
- return SBOX_TEST_SUCCEEDED;
-
- default: // Do nothing.
- break;
- }
-
- return SBOX_TEST_SUCCEEDED;
-}
-
-TEST(HandleCloserTest, CheckForMarkerFiles) {
- TestRunner runner;
- runner.SetTimeout(2000);
- runner.SetTestState(EVERY_STATE);
-
- base::string16 command = base::string16(L"CheckForFileHandles Y");
- for (const wchar_t* kExtension : kFileExtensions) {
- base::string16 handle_name;
- base::win::ScopedHandle marker(GetMarkerFile(kExtension));
- CHECK(marker.IsValid());
- CHECK(sandbox::GetHandleName(marker.Get(), &handle_name));
- command += (L" ");
- command += handle_name;
- }
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command.c_str())) <<
- "Failed: " << command;
-}
-
-TEST(HandleCloserTest, CloseMarkerFiles) {
- TestRunner runner;
- runner.SetTimeout(2000);
- runner.SetTestState(EVERY_STATE);
- sandbox::TargetPolicy* policy = runner.GetPolicy();
-
- base::string16 command = base::string16(L"CheckForFileHandles N");
- for (const wchar_t* kExtension : kFileExtensions) {
- base::string16 handle_name;
- base::win::ScopedHandle marker(GetMarkerFile(kExtension));
- CHECK(marker.IsValid());
- CHECK(sandbox::GetHandleName(marker.Get(), &handle_name));
- CHECK_EQ(policy->AddKernelObjectToClose(L"File", handle_name.c_str()),
- SBOX_ALL_OK);
- command += (L" ");
- command += handle_name;
- }
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(command.c_str())) <<
- "Failed: " << command;
-}
-
-TEST(HandleCloserTest, CheckStuffedHandle) {
- TestRunner runner;
- runner.SetTimeout(2000);
- runner.SetTestState(EVERY_STATE);
- sandbox::TargetPolicy* policy = runner.GetPolicy();
-
- for (const wchar_t* kExtension : kFileExtensions) {
- base::string16 handle_name;
- base::win::ScopedHandle marker(GetMarkerFile(kExtension));
- CHECK(marker.IsValid());
- CHECK(sandbox::GetHandleName(marker.Get(), &handle_name));
- CHECK_EQ(policy->AddKernelObjectToClose(L"File", handle_name.c_str()),
- SBOX_ALL_OK);
- }
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"CheckForEventHandles"));
-}
-
-void WINAPI ThreadPoolTask(void* event, BOOLEAN timeout) {
- static volatile LONG waiters_remaining = kWaitCount;
- CHECK(!timeout);
- CHECK(::CloseHandle(event));
- if (::InterlockedDecrement(&waiters_remaining) == 0)
- CHECK(::SetEvent(finish_event));
-}
-
-// Run a thread pool inside a sandbox without a CSRSS connection.
-SBOX_TESTS_COMMAND int RunThreadPool(int argc, wchar_t **argv) {
- HANDLE wait_list[20];
- finish_event = ::CreateEvent(NULL, TRUE, FALSE, NULL);
- CHECK(finish_event);
-
- // Set up a bunch of waiters.
- HANDLE pool = NULL;
- for (int i = 0; i < kWaitCount; ++i) {
- HANDLE event = ::CreateEvent(NULL, TRUE, FALSE, NULL);
- CHECK(event);
- CHECK(::RegisterWaitForSingleObject(&pool, event, ThreadPoolTask, event,
- INFINITE, WT_EXECUTEONLYONCE));
- wait_list[i] = event;
- }
-
- // Signal all the waiters.
- for (int i = 0; i < kWaitCount; ++i)
- CHECK(::SetEvent(wait_list[i]));
-
- CHECK_EQ(::WaitForSingleObject(finish_event, INFINITE), WAIT_OBJECT_0);
- CHECK(::CloseHandle(finish_event));
-
- return SBOX_TEST_SUCCEEDED;
-}
-
-TEST(HandleCloserTest, RunThreadPool) {
- TestRunner runner;
- runner.SetTimeout(2000);
- runner.SetTestState(AFTER_REVERT);
- sandbox::TargetPolicy* policy = runner.GetPolicy();
-
- // Sever the CSRSS connection by closing ALPC ports inside the sandbox.
- CHECK_EQ(policy->AddKernelObjectToClose(L"ALPC Port", NULL), SBOX_ALL_OK);
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"RunThreadPool"));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_dispatcher.cc b/security/sandbox/chromium/sandbox/win/src/handle_dispatcher.cc
deleted file mode 100644
index 4b98acd4c..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_dispatcher.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/handle_dispatcher.h"
-
-#include <stdint.h>
-
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/handle_interception.h"
-#include "sandbox/win/src/handle_policy.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_broker.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sandbox_utils.h"
-
-namespace sandbox {
-
-HandleDispatcher::HandleDispatcher(PolicyBase* policy_base)
- : policy_base_(policy_base) {
- static const IPCCall duplicate_handle_proxy = {
- {IPC_DUPLICATEHANDLEPROXY_TAG,
- {VOIDPTR_TYPE, UINT32_TYPE, UINT32_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &HandleDispatcher::DuplicateHandleProxy)};
-
- ipc_calls_.push_back(duplicate_handle_proxy);
-}
-
-bool HandleDispatcher::SetupService(InterceptionManager* manager,
- int service) {
- // We perform no interceptions for handles right now.
- switch (service) {
- case IPC_DUPLICATEHANDLEPROXY_TAG:
- return true;
- }
-
- return false;
-}
-
-bool HandleDispatcher::DuplicateHandleProxy(IPCInfo* ipc,
- HANDLE source_handle,
- uint32_t target_process_id,
- uint32_t desired_access,
- uint32_t options) {
- static NtQueryObject QueryObject = NULL;
- if (!QueryObject)
- ResolveNTFunctionPtr("NtQueryObject", &QueryObject);
-
- // Get a copy of the handle for use in the broker process.
- HANDLE handle_temp;
- if (!::DuplicateHandle(ipc->client_info->process, source_handle,
- ::GetCurrentProcess(), &handle_temp,
- 0, FALSE, DUPLICATE_SAME_ACCESS | options)) {
- ipc->return_info.win32_result = ::GetLastError();
- return false;
- }
- options &= ~DUPLICATE_CLOSE_SOURCE;
- base::win::ScopedHandle handle(handle_temp);
-
- // Get the object type (32 characters is safe; current max is 14).
- BYTE buffer[sizeof(OBJECT_TYPE_INFORMATION) + 32 * sizeof(wchar_t)];
- OBJECT_TYPE_INFORMATION* type_info =
- reinterpret_cast<OBJECT_TYPE_INFORMATION*>(buffer);
- ULONG size = sizeof(buffer) - sizeof(wchar_t);
- NTSTATUS error =
- QueryObject(handle.Get(), ObjectTypeInformation, type_info, size, &size);
- if (!NT_SUCCESS(error)) {
- ipc->return_info.nt_status = error;
- return false;
- }
- type_info->Name.Buffer[type_info->Name.Length / sizeof(wchar_t)] = L'\0';
-
- CountedParameterSet<HandleTarget> params;
- params[HandleTarget::NAME] = ParamPickerMake(type_info->Name.Buffer);
- params[HandleTarget::TARGET] = ParamPickerMake(target_process_id);
-
- EvalResult eval = policy_base_->EvalPolicy(IPC_DUPLICATEHANDLEPROXY_TAG,
- params.GetBase());
- ipc->return_info.win32_result =
- HandlePolicy::DuplicateHandleProxyAction(eval, handle.Get(),
- target_process_id,
- &ipc->return_info.handle,
- desired_access, options);
- return true;
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_dispatcher.h b/security/sandbox/chromium/sandbox/win/src/handle_dispatcher.h
deleted file mode 100644
index 24dcdac2a..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_dispatcher.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_HANDLE_DISPATCHER_H_
-#define SANDBOX_SRC_HANDLE_DISPATCHER_H_
-
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-namespace sandbox {
-
-// This class handles handle-related IPC calls.
-class HandleDispatcher : public Dispatcher {
- public:
- explicit HandleDispatcher(PolicyBase* policy_base);
- ~HandleDispatcher() override {}
-
- // Dispatcher interface.
- bool SetupService(InterceptionManager* manager, int service) override;
-
- private:
- // Processes IPC requests coming from calls to
- // TargetServices::DuplicateHandle() in the target.
- bool DuplicateHandleProxy(IPCInfo* ipc,
- HANDLE source_handle,
- uint32_t target_process_id,
- uint32_t desired_access,
- uint32_t options);
-
- PolicyBase* policy_base_;
- DISALLOW_COPY_AND_ASSIGN(HandleDispatcher);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_HANDLE_DISPATCHER_H_
-
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_inheritance_test.cc b/security/sandbox/chromium/sandbox/win/src/handle_inheritance_test.cc
deleted file mode 100644
index d8c2808da..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_inheritance_test.cc
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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.
-
-#include <stdio.h>
-
-#include "base/files/file_util.h"
-#include "base/files/scoped_temp_dir.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-SBOX_TESTS_COMMAND int HandleInheritanceTests_PrintToStdout(int argc,
- wchar_t** argv) {
- printf("Example output to stdout\n");
- return SBOX_TEST_SUCCEEDED;
-}
-
-TEST(HandleInheritanceTests, TestStdoutInheritance) {
- base::ScopedTempDir temp_directory;
- base::FilePath temp_file_name;
- ASSERT_TRUE(temp_directory.CreateUniqueTempDir());
- ASSERT_TRUE(CreateTemporaryFileInDir(temp_directory.path(), &temp_file_name));
-
- SECURITY_ATTRIBUTES attrs = {};
- attrs.nLength = sizeof(attrs);
- attrs.bInheritHandle = TRUE;
- base::win::ScopedHandle tmp_handle(
- CreateFile(temp_file_name.value().c_str(), GENERIC_WRITE,
- FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
- &attrs, OPEN_EXISTING, 0, NULL));
- ASSERT_TRUE(tmp_handle.IsValid());
-
- TestRunner runner;
- ASSERT_EQ(SBOX_ALL_OK, runner.GetPolicy()->SetStdoutHandle(tmp_handle.Get()));
- int result = runner.RunTest(L"HandleInheritanceTests_PrintToStdout");
- ASSERT_EQ(SBOX_TEST_SUCCEEDED, result);
-
- std::string data;
- ASSERT_TRUE(base::ReadFileToString(base::FilePath(temp_file_name), &data));
- // Redirection uses a feature that was added in Windows Vista.
- if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
- ASSERT_EQ("Example output to stdout\r\n", data);
- } else {
- ASSERT_EQ("", data);
- }
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_interception.cc b/security/sandbox/chromium/sandbox/win/src/handle_interception.cc
deleted file mode 100644
index 6fe2f117d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_interception.cc
+++ /dev/null
@@ -1,48 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/handle_interception.h"
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/target_services.h"
-#include "mozilla/sandboxing/sandboxLogging.h"
-
-namespace sandbox {
-
-ResultCode DuplicateHandleProxy(HANDLE source_handle,
- DWORD target_process_id,
- HANDLE* target_handle,
- DWORD desired_access,
- DWORD options) {
- *target_handle = NULL;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- return SBOX_ERROR_NO_SPACE;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_DUPLICATEHANDLEPROXY_TAG,
- source_handle, target_process_id,
- desired_access, options, &answer);
- if (SBOX_ALL_OK != code)
- return code;
-
- if (answer.win32_result) {
- ::SetLastError(answer.win32_result);
- mozilla::sandboxing::LogBlocked("DuplicateHandle");
- return SBOX_ERROR_GENERIC;
- }
-
- *target_handle = answer.handle;
- mozilla::sandboxing::LogAllowed("DuplicateHandle");
- return SBOX_ALL_OK;
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_interception.h b/security/sandbox/chromium/sandbox/win/src/handle_interception.h
deleted file mode 100644
index 6f60811f1..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_interception.h
+++ /dev/null
@@ -1,24 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_HANDLE_INTERCEPTION_H_
-#define SANDBOX_SRC_HANDLE_INTERCEPTION_H_
-
-namespace sandbox {
-
-// TODO(jschuh) Add an interception to catch dangerous DuplicateHandle calls.
-
-ResultCode DuplicateHandleProxy(HANDLE source_handle,
- DWORD target_process_id,
- HANDLE* target_handle,
- DWORD desired_access,
- DWORD options);
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_HANDLE_INTERCEPTION_H_
-
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_policy.cc b/security/sandbox/chromium/sandbox/win/src/handle_policy.cc
deleted file mode 100644
index 102303079..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_policy.cc
+++ /dev/null
@@ -1,92 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/handle_policy.h"
-
-#include <string>
-
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/broker_services.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sandbox_utils.h"
-
-namespace sandbox {
-
-bool HandlePolicy::GenerateRules(const wchar_t* type_name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy) {
- PolicyRule duplicate_rule(ASK_BROKER);
-
- switch (semantics) {
- case TargetPolicy::HANDLES_DUP_ANY: {
- if (!duplicate_rule.AddNumberMatch(IF_NOT, HandleTarget::TARGET,
- ::GetCurrentProcessId(), EQUAL)) {
- return false;
- }
- break;
- }
-
- case TargetPolicy::HANDLES_DUP_BROKER: {
- if (!duplicate_rule.AddNumberMatch(IF, HandleTarget::TARGET,
- ::GetCurrentProcessId(), EQUAL)) {
- return false;
- }
- break;
- }
-
- default:
- return false;
- }
- if (!duplicate_rule.AddStringMatch(IF, HandleTarget::NAME, type_name,
- CASE_INSENSITIVE)) {
- return false;
- }
- if (!policy->AddRule(IPC_DUPLICATEHANDLEPROXY_TAG, &duplicate_rule)) {
- return false;
- }
- return true;
-}
-
-DWORD HandlePolicy::DuplicateHandleProxyAction(EvalResult eval_result,
- HANDLE source_handle,
- DWORD target_process_id,
- HANDLE* target_handle,
- DWORD desired_access,
- DWORD options) {
- // The only action supported is ASK_BROKER which means duplicate the handle.
- if (ASK_BROKER != eval_result) {
- return ERROR_ACCESS_DENIED;
- }
-
- base::win::ScopedHandle remote_target_process;
- if (target_process_id != ::GetCurrentProcessId()) {
- // Sandboxed children are dynamic, so we check that manually.
- if (!BrokerServicesBase::GetInstance()->IsActiveTarget(target_process_id)) {
- return ERROR_ACCESS_DENIED;
- }
-
- remote_target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE,
- target_process_id));
- if (!remote_target_process.IsValid())
- return ::GetLastError();
- }
-
- // If the policy didn't block us and we have no valid target, then the broker
- // (this process) is the valid target.
- HANDLE target_process = remote_target_process.IsValid() ?
- remote_target_process.Get() : ::GetCurrentProcess();
- if (!::DuplicateHandle(::GetCurrentProcess(), source_handle, target_process,
- target_handle, desired_access, FALSE,
- options)) {
- return ::GetLastError();
- }
-
- return ERROR_SUCCESS;
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_policy.h b/security/sandbox/chromium/sandbox/win/src/handle_policy.h
deleted file mode 100644
index 29ce5ab66..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_policy.h
+++ /dev/null
@@ -1,39 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_HANDLE_POLICY_H_
-#define SANDBOX_SRC_HANDLE_POLICY_H_
-
-#include <string>
-
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/sandbox_policy.h"
-
-namespace sandbox {
-
-enum EvalResult;
-
-// This class centralizes most of the knowledge related to handle policy.
-class HandlePolicy {
- public:
- // Creates the required low-level policy rules to evaluate a high-level
- // policy rule for handles, in particular duplicate action.
- static bool GenerateRules(const wchar_t* type_name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy);
-
- // Processes a 'TargetPolicy::DuplicateHandle()' request from the target.
- static DWORD DuplicateHandleProxyAction(EvalResult eval_result,
- HANDLE source_handle,
- DWORD target_process_id,
- HANDLE* target_handle,
- DWORD desired_access,
- DWORD options);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_HANDLE_POLICY_H_
-
diff --git a/security/sandbox/chromium/sandbox/win/src/handle_policy_test.cc b/security/sandbox/chromium/sandbox/win/src/handle_policy_test.cc
deleted file mode 100644
index 11382da81..000000000
--- a/security/sandbox/chromium/sandbox/win/src/handle_policy_test.cc
+++ /dev/null
@@ -1,114 +0,0 @@
-// 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.
-
-#include "base/strings/stringprintf.h"
-#include "sandbox/win/src/handle_policy.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/win_utils.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-// Just waits for the supplied number of milliseconds.
-SBOX_TESTS_COMMAND int Handle_WaitProcess(int argc, wchar_t **argv) {
- if (argc != 1)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- ::Sleep(::wcstoul(argv[0], NULL, 10));
- return SBOX_TEST_TIMED_OUT;
-}
-
-// Attempts to duplicate an event handle into the target process.
-SBOX_TESTS_COMMAND int Handle_DuplicateEvent(int argc, wchar_t **argv) {
- if (argc != 1)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- // Create a test event to use as a handle.
- base::win::ScopedHandle test_event;
- test_event.Set(::CreateEvent(NULL, TRUE, TRUE, NULL));
- if (!test_event.IsValid())
- return SBOX_TEST_FIRST_ERROR;
-
- // Get the target process ID.
- DWORD target_process_id = ::wcstoul(argv[0], NULL, 10);
-
- HANDLE handle = NULL;
- ResultCode result = SandboxFactory::GetTargetServices()->DuplicateHandle(
- test_event.Get(), target_process_id, &handle, 0, DUPLICATE_SAME_ACCESS);
-
- return (result == SBOX_ALL_OK) ? SBOX_TEST_SUCCEEDED : SBOX_TEST_DENIED;
-}
-
-// Tests that duplicating an object works only when the policy allows it.
-TEST(HandlePolicyTest, DuplicateHandle) {
- TestRunner target;
- TestRunner runner;
-
- // Kick off an asynchronous target process for testing.
- target.SetAsynchronous(true);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, target.RunTest(L"Handle_WaitProcess 30000"));
-
- // First test that we fail to open the event.
- base::string16 cmd_line = base::StringPrintf(L"Handle_DuplicateEvent %d",
- target.process_id());
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(cmd_line.c_str()));
-
- // Now successfully open the event after adding a duplicate handle rule.
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_HANDLES,
- TargetPolicy::HANDLES_DUP_ANY,
- L"Event"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(cmd_line.c_str()));
-}
-
-// Tests that duplicating an object works only when the policy allows it.
-TEST(HandlePolicyTest, DuplicatePeerHandle) {
- TestRunner target;
- TestRunner runner;
-
- // Kick off an asynchronous target process for testing.
- target.SetAsynchronous(true);
- target.SetUnsandboxed(true);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, target.RunTest(L"Handle_WaitProcess 30000"));
-
- // First test that we fail to open the event.
- base::string16 cmd_line = base::StringPrintf(L"Handle_DuplicateEvent %d",
- target.process_id());
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(cmd_line.c_str()));
-
- // Now successfully open the event after adding a duplicate handle rule.
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_HANDLES,
- TargetPolicy::HANDLES_DUP_ANY,
- L"Event"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(cmd_line.c_str()));
-}
-
-// Tests that duplicating an object works only when the policy allows it.
-TEST(HandlePolicyTest, DuplicateBrokerHandle) {
- TestRunner runner;
-
- // First test that we fail to open the event.
- base::string16 cmd_line = base::StringPrintf(L"Handle_DuplicateEvent %d",
- ::GetCurrentProcessId());
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(cmd_line.c_str()));
-
- // Add the peer rule and make sure we fail again.
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_HANDLES,
- TargetPolicy::HANDLES_DUP_ANY,
- L"Event"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(cmd_line.c_str()));
-
-
- // Now successfully open the event after adding a broker handle rule.
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_HANDLES,
- TargetPolicy::HANDLES_DUP_BROKER,
- L"Event"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(cmd_line.c_str()));
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/integrity_level_test.cc b/security/sandbox/chromium/sandbox/win/src/integrity_level_test.cc
deleted file mode 100644
index f962033ca..000000000
--- a/security/sandbox/chromium/sandbox/win/src/integrity_level_test.cc
+++ /dev/null
@@ -1,91 +0,0 @@
-// 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 <windows.h>
-#include <atlsecurity.h>
-
-#include "base/win/windows_version.h"
-#include "testing/gtest/include/gtest/gtest.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/tests/common/controller.h"
-
-namespace sandbox {
-
-
-SBOX_TESTS_COMMAND int CheckIntegrityLevel(int argc, wchar_t **argv) {
- ATL::CAccessToken token;
- if (!token.GetEffectiveToken(TOKEN_READ))
- return SBOX_TEST_FAILED;
-
- char* buffer[100];
- DWORD buf_size = 100;
- if (!::GetTokenInformation(token.GetHandle(), TokenIntegrityLevel,
- reinterpret_cast<void*>(buffer), buf_size,
- &buf_size))
- return SBOX_TEST_FAILED;
-
- TOKEN_MANDATORY_LABEL* label =
- reinterpret_cast<TOKEN_MANDATORY_LABEL*>(buffer);
-
- PSID sid_low = NULL;
- if (!::ConvertStringSidToSid(L"S-1-16-4096", &sid_low))
- return SBOX_TEST_FAILED;
-
- BOOL is_low_sid = ::EqualSid(label->Label.Sid, sid_low);
-
- ::LocalFree(sid_low);
-
- if (is_low_sid)
- return SBOX_TEST_SUCCEEDED;
-
- return SBOX_TEST_DENIED;
-}
-
-TEST(IntegrityLevelTest, TestLowILReal) {
- if (base::win::GetVersion() != base::win::VERSION_VISTA)
- return;
-
- TestRunner runner(JOB_LOCKDOWN, USER_INTERACTIVE, USER_INTERACTIVE);
-
- runner.SetTimeout(INFINITE);
-
- runner.GetPolicy()->SetAlternateDesktop(true);
- runner.GetPolicy()->SetIntegrityLevel(INTEGRITY_LEVEL_LOW);
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"CheckIntegrityLevel"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"CheckIntegrityLevel"));
-}
-
-TEST(DelayedIntegrityLevelTest, TestLowILDelayed) {
- if (base::win::GetVersion() != base::win::VERSION_VISTA)
- return;
-
- TestRunner runner(JOB_LOCKDOWN, USER_INTERACTIVE, USER_INTERACTIVE);
-
- runner.SetTimeout(INFINITE);
-
- runner.GetPolicy()->SetDelayedIntegrityLevel(INTEGRITY_LEVEL_LOW);
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"CheckIntegrityLevel"));
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"CheckIntegrityLevel"));
-}
-
-TEST(IntegrityLevelTest, TestNoILChange) {
- if (base::win::GetVersion() != base::win::VERSION_VISTA)
- return;
-
- TestRunner runner(JOB_LOCKDOWN, USER_INTERACTIVE, USER_INTERACTIVE);
-
- runner.SetTimeout(INFINITE);
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"CheckIntegrityLevel"));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/interception.cc b/security/sandbox/chromium/sandbox/win/src/interception.cc
deleted file mode 100644
index f0a2a61fb..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interception.cc
+++ /dev/null
@@ -1,560 +0,0 @@
-// 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.
-
-// For information about interceptions as a whole see
-// http://dev.chromium.org/developers/design-documents/sandbox .
-
-#include <stddef.h>
-
-#include <set>
-
-#include "sandbox/win/src/interception.h"
-
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/strings/string16.h"
-#include "base/win/pe_image.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/interception_internal.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_rand.h"
-#include "sandbox/win/src/service_resolver.h"
-#include "sandbox/win/src/target_interceptions.h"
-#include "sandbox/win/src/target_process.h"
-#include "sandbox/win/src/wow64.h"
-
-namespace sandbox {
-
-namespace {
-
-// Standard allocation granularity and page size for Windows.
-const size_t kAllocGranularity = 65536;
-const size_t kPageSize = 4096;
-
-} // namespace
-
-namespace internal {
-
-// Find a random offset within 64k and aligned to ceil(log2(size)).
-size_t GetGranularAlignedRandomOffset(size_t size) {
- CHECK_LE(size, kAllocGranularity);
- unsigned int offset;
-
- do {
- GetRandom(&offset);
- offset &= (kAllocGranularity - 1);
- } while (offset > (kAllocGranularity - size));
-
- // Find an alignment between 64 and the page size (4096).
- size_t align_size = kPageSize;
- for (size_t new_size = align_size / 2; new_size >= size; new_size /= 2) {
- align_size = new_size;
- }
- return offset & ~(align_size - 1);
-}
-
-} // namespace internal
-
-SANDBOX_INTERCEPT SharedMemory* g_interceptions;
-
-// Table of the unpatched functions that we intercept. Mapped from the parent.
-SANDBOX_INTERCEPT OriginalFunctions g_originals = { NULL };
-
-// Magic constant that identifies that this function is not to be patched.
-const char kUnloadDLLDummyFunction[] = "@";
-
-InterceptionManager::InterceptionData::InterceptionData() {
-}
-
-InterceptionManager::InterceptionData::~InterceptionData() {
-}
-
-InterceptionManager::InterceptionManager(TargetProcess* child_process,
- bool relaxed)
- : child_(child_process), names_used_(false), relaxed_(relaxed) {
- child_->AddRef();
-}
-InterceptionManager::~InterceptionManager() {
- child_->Release();
-}
-
-bool InterceptionManager::AddToPatchedFunctions(
- const wchar_t* dll_name, const char* function_name,
- InterceptionType interception_type, const void* replacement_code_address,
- InterceptorId id) {
- InterceptionData function;
- function.type = interception_type;
- function.id = id;
- function.dll = dll_name;
- function.function = function_name;
- function.interceptor_address = replacement_code_address;
-
- interceptions_.push_back(function);
- return true;
-}
-
-bool InterceptionManager::AddToPatchedFunctions(
- const wchar_t* dll_name, const char* function_name,
- InterceptionType interception_type, const char* replacement_function_name,
- InterceptorId id) {
- InterceptionData function;
- function.type = interception_type;
- function.id = id;
- function.dll = dll_name;
- function.function = function_name;
- function.interceptor = replacement_function_name;
- function.interceptor_address = NULL;
-
- interceptions_.push_back(function);
- names_used_ = true;
- return true;
-}
-
-bool InterceptionManager::AddToUnloadModules(const wchar_t* dll_name) {
- InterceptionData module_to_unload;
- module_to_unload.type = INTERCEPTION_UNLOAD_MODULE;
- module_to_unload.dll = dll_name;
- // The next two are dummy values that make the structures regular, instead
- // of having special cases. They should not be used.
- module_to_unload.function = kUnloadDLLDummyFunction;
- module_to_unload.interceptor_address = reinterpret_cast<void*>(1);
-
- interceptions_.push_back(module_to_unload);
- return true;
-}
-
-bool InterceptionManager::InitializeInterceptions() {
- if (interceptions_.empty())
- return true; // Nothing to do here
-
- size_t buffer_bytes = GetBufferSize();
- scoped_ptr<char[]> local_buffer(new char[buffer_bytes]);
-
- if (!SetupConfigBuffer(local_buffer.get(), buffer_bytes))
- return false;
-
- void* remote_buffer;
- if (!CopyDataToChild(local_buffer.get(), buffer_bytes, &remote_buffer))
- return false;
-
- bool hot_patch_needed = (0 != buffer_bytes);
- if (!PatchNtdll(hot_patch_needed))
- return false;
-
- g_interceptions = reinterpret_cast<SharedMemory*>(remote_buffer);
- ResultCode rc = child_->TransferVariable("g_interceptions",
- &g_interceptions,
- sizeof(g_interceptions));
- return (SBOX_ALL_OK == rc);
-}
-
-size_t InterceptionManager::GetBufferSize() const {
- std::set<base::string16> dlls;
- size_t buffer_bytes = 0;
-
- std::list<InterceptionData>::const_iterator it = interceptions_.begin();
- for (; it != interceptions_.end(); ++it) {
- // skip interceptions that are performed from the parent
- if (!IsInterceptionPerformedByChild(*it))
- continue;
-
- if (!dlls.count(it->dll)) {
- // NULL terminate the dll name on the structure
- size_t dll_name_bytes = (it->dll.size() + 1) * sizeof(wchar_t);
-
- // include the dll related size
- buffer_bytes += RoundUpToMultiple(offsetof(DllPatchInfo, dll_name) +
- dll_name_bytes, sizeof(size_t));
- dlls.insert(it->dll);
- }
-
- // we have to NULL terminate the strings on the structure
- size_t strings_chars = it->function.size() + it->interceptor.size() + 2;
-
- // a new FunctionInfo is required per function
- size_t record_bytes = offsetof(FunctionInfo, function) + strings_chars;
- record_bytes = RoundUpToMultiple(record_bytes, sizeof(size_t));
- buffer_bytes += record_bytes;
- }
-
- if (0 != buffer_bytes)
- // add the part of SharedMemory that we have not counted yet
- buffer_bytes += offsetof(SharedMemory, dll_list);
-
- return buffer_bytes;
-}
-
-// Basically, walk the list of interceptions moving them to the config buffer,
-// but keeping together all interceptions that belong to the same dll.
-// The config buffer is a local buffer, not the one allocated on the child.
-bool InterceptionManager::SetupConfigBuffer(void* buffer, size_t buffer_bytes) {
- if (0 == buffer_bytes)
- return true;
-
- DCHECK(buffer_bytes > sizeof(SharedMemory));
-
- SharedMemory* shared_memory = reinterpret_cast<SharedMemory*>(buffer);
- DllPatchInfo* dll_info = shared_memory->dll_list;
- int num_dlls = 0;
-
- shared_memory->interceptor_base = names_used_ ? child_->MainModule() : NULL;
-
- buffer_bytes -= offsetof(SharedMemory, dll_list);
- buffer = dll_info;
-
- std::list<InterceptionData>::iterator it = interceptions_.begin();
- for (; it != interceptions_.end();) {
- // skip interceptions that are performed from the parent
- if (!IsInterceptionPerformedByChild(*it)) {
- ++it;
- continue;
- }
-
- const base::string16 dll = it->dll;
- if (!SetupDllInfo(*it, &buffer, &buffer_bytes))
- return false;
-
- // walk the interceptions from this point, saving the ones that are
- // performed on this dll, and removing the entry from the list.
- // advance the iterator before removing the element from the list
- std::list<InterceptionData>::iterator rest = it;
- for (; rest != interceptions_.end();) {
- if (rest->dll == dll) {
- if (!SetupInterceptionInfo(*rest, &buffer, &buffer_bytes, dll_info))
- return false;
- if (it == rest)
- ++it;
- rest = interceptions_.erase(rest);
- } else {
- ++rest;
- }
- }
- dll_info = reinterpret_cast<DllPatchInfo*>(buffer);
- ++num_dlls;
- }
-
- shared_memory->num_intercepted_dlls = num_dlls;
- return true;
-}
-
-// Fills up just the part that depends on the dll, not the info that depends on
-// the actual interception.
-bool InterceptionManager::SetupDllInfo(const InterceptionData& data,
- void** buffer,
- size_t* buffer_bytes) const {
- DCHECK(buffer_bytes);
- DCHECK(buffer);
- DCHECK(*buffer);
-
- DllPatchInfo* dll_info = reinterpret_cast<DllPatchInfo*>(*buffer);
-
- // the strings have to be zero terminated
- size_t required = offsetof(DllPatchInfo, dll_name) +
- (data.dll.size() + 1) * sizeof(wchar_t);
- required = RoundUpToMultiple(required, sizeof(size_t));
- if (*buffer_bytes < required)
- return false;
-
- *buffer_bytes -= required;
- *buffer = reinterpret_cast<char*>(*buffer) + required;
-
- // set up the dll info to be what we know about it at this time
- dll_info->unload_module = (data.type == INTERCEPTION_UNLOAD_MODULE);
- dll_info->record_bytes = required;
- dll_info->offset_to_functions = required;
- dll_info->num_functions = 0;
- data.dll._Copy_s(dll_info->dll_name, data.dll.size(), data.dll.size());
- dll_info->dll_name[data.dll.size()] = L'\0';
-
- return true;
-}
-
-bool InterceptionManager::SetupInterceptionInfo(const InterceptionData& data,
- void** buffer,
- size_t* buffer_bytes,
- DllPatchInfo* dll_info) const {
- DCHECK(buffer_bytes);
- DCHECK(buffer);
- DCHECK(*buffer);
-
- if ((dll_info->unload_module) &&
- (data.function != kUnloadDLLDummyFunction)) {
- // Can't specify a dll for both patch and unload.
- NOTREACHED();
- }
-
- FunctionInfo* function = reinterpret_cast<FunctionInfo*>(*buffer);
-
- size_t name_bytes = data.function.size();
- size_t interceptor_bytes = data.interceptor.size();
-
- // the strings at the end of the structure are zero terminated
- size_t required = offsetof(FunctionInfo, function) +
- name_bytes + interceptor_bytes + 2;
- required = RoundUpToMultiple(required, sizeof(size_t));
- if (*buffer_bytes < required)
- return false;
-
- // update the caller's values
- *buffer_bytes -= required;
- *buffer = reinterpret_cast<char*>(*buffer) + required;
-
- function->record_bytes = required;
- function->type = data.type;
- function->id = data.id;
- function->interceptor_address = data.interceptor_address;
- char* names = function->function;
-
- data.function._Copy_s(names, name_bytes, name_bytes);
- names += name_bytes;
- *names++ = '\0';
-
- // interceptor follows the function_name
- data.interceptor._Copy_s(names, interceptor_bytes, interceptor_bytes);
- names += interceptor_bytes;
- *names++ = '\0';
-
- // update the dll table
- dll_info->num_functions++;
- dll_info->record_bytes += required;
-
- return true;
-}
-
-bool InterceptionManager::CopyDataToChild(const void* local_buffer,
- size_t buffer_bytes,
- void** remote_buffer) const {
- DCHECK(NULL != remote_buffer);
- if (0 == buffer_bytes) {
- *remote_buffer = NULL;
- return true;
- }
-
- HANDLE child = child_->Process();
-
- // Allocate memory on the target process without specifying the address
- void* remote_data = ::VirtualAllocEx(child, NULL, buffer_bytes,
- MEM_COMMIT, PAGE_READWRITE);
- if (NULL == remote_data)
- return false;
-
- SIZE_T bytes_written;
- BOOL success = ::WriteProcessMemory(child, remote_data, local_buffer,
- buffer_bytes, &bytes_written);
- if (FALSE == success || bytes_written != buffer_bytes) {
- ::VirtualFreeEx(child, remote_data, 0, MEM_RELEASE);
- return false;
- }
-
- *remote_buffer = remote_data;
-
- return true;
-}
-
-// Only return true if the child should be able to perform this interception.
-bool InterceptionManager::IsInterceptionPerformedByChild(
- const InterceptionData& data) const {
- if (INTERCEPTION_INVALID == data.type)
- return false;
-
- if (INTERCEPTION_SERVICE_CALL == data.type)
- return false;
-
- if (data.type >= INTERCEPTION_LAST)
- return false;
-
- base::string16 ntdll(kNtdllName);
- if (ntdll == data.dll)
- return false; // ntdll has to be intercepted from the parent
-
- return true;
-}
-
-bool InterceptionManager::PatchNtdll(bool hot_patch_needed) {
- // Maybe there is nothing to do
- if (!hot_patch_needed && interceptions_.empty())
- return true;
-
- if (hot_patch_needed) {
-#if SANDBOX_EXPORTS
- // Make sure the functions are not excluded by the linker.
-#if defined(_WIN64)
- #pragma comment(linker, "/include:TargetNtMapViewOfSection64")
- #pragma comment(linker, "/include:TargetNtUnmapViewOfSection64")
-#else
- #pragma comment(linker, "/include:_TargetNtMapViewOfSection@44")
- #pragma comment(linker, "/include:_TargetNtUnmapViewOfSection@12")
-#endif
-#endif
- ADD_NT_INTERCEPTION(NtMapViewOfSection, MAP_VIEW_OF_SECTION_ID, 44);
- ADD_NT_INTERCEPTION(NtUnmapViewOfSection, UNMAP_VIEW_OF_SECTION_ID, 12);
- }
-
- // Reserve a full 64k memory range in the child process.
- HANDLE child = child_->Process();
- BYTE* thunk_base = reinterpret_cast<BYTE*>(
- ::VirtualAllocEx(child, NULL, kAllocGranularity,
- MEM_RESERVE, PAGE_NOACCESS));
-
- // Find an aligned, random location within the reserved range.
- size_t thunk_bytes = interceptions_.size() * sizeof(ThunkData) +
- sizeof(DllInterceptionData);
- size_t thunk_offset = internal::GetGranularAlignedRandomOffset(thunk_bytes);
-
- // Split the base and offset along page boundaries.
- thunk_base += thunk_offset & ~(kPageSize - 1);
- thunk_offset &= kPageSize - 1;
-
- // Make an aligned, padded allocation, and move the pointer to our chunk.
- size_t thunk_bytes_padded = (thunk_bytes + kPageSize - 1) & ~(kPageSize - 1);
- thunk_base = reinterpret_cast<BYTE*>(
- ::VirtualAllocEx(child, thunk_base, thunk_bytes_padded,
- MEM_COMMIT, PAGE_EXECUTE_READWRITE));
- CHECK(thunk_base); // If this fails we'd crash anyway on an invalid access.
- DllInterceptionData* thunks = reinterpret_cast<DllInterceptionData*>(
- thunk_base + thunk_offset);
-
- DllInterceptionData dll_data;
- dll_data.data_bytes = thunk_bytes;
- dll_data.num_thunks = 0;
- dll_data.used_bytes = offsetof(DllInterceptionData, thunks);
-
- // Reset all helpers for a new child.
- memset(g_originals, 0, sizeof(g_originals));
-
- // this should write all the individual thunks to the child's memory
- if (!PatchClientFunctions(thunks, thunk_bytes, &dll_data))
- return false;
-
- // and now write the first part of the table to the child's memory
- SIZE_T written;
- bool ok = FALSE != ::WriteProcessMemory(child, thunks, &dll_data,
- offsetof(DllInterceptionData, thunks),
- &written);
-
- if (!ok || (offsetof(DllInterceptionData, thunks) != written))
- return false;
-
- // Attempt to protect all the thunks, but ignore failure
- DWORD old_protection;
- ::VirtualProtectEx(child, thunks, thunk_bytes,
- PAGE_EXECUTE_READ, &old_protection);
-
- ResultCode ret = child_->TransferVariable("g_originals", g_originals,
- sizeof(g_originals));
- return (SBOX_ALL_OK == ret);
-}
-
-bool InterceptionManager::PatchClientFunctions(DllInterceptionData* thunks,
- size_t thunk_bytes,
- DllInterceptionData* dll_data) {
- DCHECK(NULL != thunks);
- DCHECK(NULL != dll_data);
-
- HMODULE ntdll_base = ::GetModuleHandle(kNtdllName);
- if (!ntdll_base)
- return false;
-
- base::win::PEImage ntdll_image(ntdll_base);
-
- // Bypass purify's interception.
- wchar_t* loader_get = reinterpret_cast<wchar_t*>(
- ntdll_image.GetProcAddress("LdrGetDllHandle"));
- if (loader_get) {
- if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
- GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
- loader_get, &ntdll_base))
- return false;
- }
-
- if (base::win::GetVersion() <= base::win::VERSION_VISTA) {
- Wow64 WowHelper(child_, ntdll_base);
- if (!WowHelper.WaitForNtdll())
- return false;
- }
-
- char* interceptor_base = NULL;
-
-#if SANDBOX_EXPORTS
- interceptor_base = reinterpret_cast<char*>(child_->MainModule());
- HMODULE local_interceptor = ::LoadLibrary(child_->Name());
-#endif
-
- ServiceResolverThunk* thunk;
-#if defined(_WIN64)
- thunk = new ServiceResolverThunk(child_->Process(), relaxed_);
-#else
- base::win::OSInfo* os_info = base::win::OSInfo::GetInstance();
- if (os_info->wow64_status() == base::win::OSInfo::WOW64_ENABLED) {
- if (os_info->version() >= base::win::VERSION_WIN10)
- thunk = new Wow64W10ResolverThunk(child_->Process(), relaxed_);
- else if (os_info->version() >= base::win::VERSION_WIN8)
- thunk = new Wow64W8ResolverThunk(child_->Process(), relaxed_);
- else
- thunk = new Wow64ResolverThunk(child_->Process(), relaxed_);
- } else if (os_info->version() >= base::win::VERSION_WIN8) {
- thunk = new Win8ResolverThunk(child_->Process(), relaxed_);
- } else {
- thunk = new ServiceResolverThunk(child_->Process(), relaxed_);
- }
-#endif
-
- std::list<InterceptionData>::iterator it = interceptions_.begin();
- for (; it != interceptions_.end(); ++it) {
- const base::string16 ntdll(kNtdllName);
- if (it->dll != ntdll)
- break;
-
- if (INTERCEPTION_SERVICE_CALL != it->type)
- break;
-
-#if SANDBOX_EXPORTS
- // We may be trying to patch by function name.
- if (NULL == it->interceptor_address) {
- const char* address;
- NTSTATUS ret = thunk->ResolveInterceptor(local_interceptor,
- it->interceptor.c_str(),
- reinterpret_cast<const void**>(
- &address));
- if (!NT_SUCCESS(ret))
- break;
-
- // Translate the local address to an address on the child.
- it->interceptor_address = interceptor_base + (address -
- reinterpret_cast<char*>(local_interceptor));
- }
-#endif
- NTSTATUS ret = thunk->Setup(ntdll_base,
- interceptor_base,
- it->function.c_str(),
- it->interceptor.c_str(),
- it->interceptor_address,
- &thunks->thunks[dll_data->num_thunks],
- thunk_bytes - dll_data->used_bytes,
- NULL);
- if (!NT_SUCCESS(ret))
- break;
-
- DCHECK(!g_originals[it->id]);
- g_originals[it->id] = &thunks->thunks[dll_data->num_thunks];
-
- dll_data->num_thunks++;
- dll_data->used_bytes += sizeof(ThunkData);
- }
-
- delete(thunk);
-
-#if SANDBOX_EXPORTS
- if (NULL != local_interceptor)
- ::FreeLibrary(local_interceptor);
-#endif
-
- if (it != interceptions_.end())
- return false;
-
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/interception.h b/security/sandbox/chromium/sandbox/win/src/interception.h
deleted file mode 100644
index 4d1ee82ba..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interception.h
+++ /dev/null
@@ -1,286 +0,0 @@
-// 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.
-
-// Defines InterceptionManager, the class in charge of setting up interceptions
-// for the sandboxed process. For more details see
-// http://dev.chromium.org/developers/design-documents/sandbox .
-
-#ifndef SANDBOX_SRC_INTERCEPTION_H_
-#define SANDBOX_SRC_INTERCEPTION_H_
-
-#include <stddef.h>
-
-#include <list>
-#include <string>
-
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace sandbox {
-
-class TargetProcess;
-enum InterceptorId;
-
-// Internal structures used for communication between the broker and the target.
-struct DllPatchInfo;
-struct DllInterceptionData;
-
-// The InterceptionManager executes on the parent application, and it is in
-// charge of setting up the desired interceptions, and placing the Interception
-// Agent into the child application.
-//
-// The exposed API consists of two methods: AddToPatchedFunctions to set up a
-// particular interception, and InitializeInterceptions to actually go ahead and
-// perform all interceptions and transfer data to the child application.
-//
-// The typical usage is something like this:
-//
-// InterceptionManager interception_manager(child);
-// if (!interception_manager.AddToPatchedFunctions(
-// L"ntdll.dll", "NtCreateFile",
-// sandbox::INTERCEPTION_SERVICE_CALL, &MyNtCreateFile, MY_ID_1))
-// return false;
-//
-// if (!interception_manager.AddToPatchedFunctions(
-// L"kernel32.dll", "CreateDirectoryW",
-// sandbox::INTERCEPTION_EAT, L"MyCreateDirectoryW@12", MY_ID_2))
-// return false;
-//
-// if (!interception_manager.InitializeInterceptions()) {
-// DWORD error = ::GetLastError();
-// return false;
-// }
-//
-// Any required syncronization must be performed outside this class. Also, it is
-// not possible to perform further interceptions after InitializeInterceptions
-// is called.
-//
-class InterceptionManager {
- // The unit test will access private members.
- // Allow tests to be marked DISABLED_. Note that FLAKY_ and FAILS_ prefixes
- // do not work with sandbox tests.
- FRIEND_TEST_ALL_PREFIXES(InterceptionManagerTest, BufferLayout1);
- FRIEND_TEST_ALL_PREFIXES(InterceptionManagerTest, BufferLayout2);
-
- public:
- // An interception manager performs interceptions on a given child process.
- // If we are allowed to intercept functions that have been patched by somebody
- // else, relaxed should be set to true.
- // Note: We increase the child's reference count internally.
- InterceptionManager(TargetProcess* child_process, bool relaxed);
- ~InterceptionManager();
-
- // Patches function_name inside dll_name to point to replacement_code_address.
- // function_name has to be an exported symbol of dll_name.
- // Returns true on success.
- //
- // The new function should match the prototype and calling convention of the
- // function to intercept except for one extra argument (the first one) that
- // contains a pointer to the original function, to simplify the development
- // of interceptors (for IA32). In x64, there is no extra argument to the
- // interceptor, so the provided InterceptorId is used to keep a table of
- // intercepted functions so that the interceptor can index that table to get
- // the pointer that would have been the first argument (g_originals[id]).
- //
- // For example, to intercept NtClose, the following code could be used:
- //
- // typedef NTSTATUS (WINAPI *NtCloseFunction) (IN HANDLE Handle);
- // NTSTATUS WINAPI MyNtCose(IN NtCloseFunction OriginalClose,
- // IN HANDLE Handle) {
- // // do something
- // // call the original function
- // return OriginalClose(Handle);
- // }
- //
- // And in x64:
- //
- // typedef NTSTATUS (WINAPI *NtCloseFunction) (IN HANDLE Handle);
- // NTSTATUS WINAPI MyNtCose64(IN HANDLE Handle) {
- // // do something
- // // call the original function
- // NtCloseFunction OriginalClose = g_originals[NT_CLOSE_ID];
- // return OriginalClose(Handle);
- // }
- bool AddToPatchedFunctions(const wchar_t* dll_name,
- const char* function_name,
- InterceptionType interception_type,
- const void* replacement_code_address,
- InterceptorId id);
-
- // Patches function_name inside dll_name to point to
- // replacement_function_name.
- bool AddToPatchedFunctions(const wchar_t* dll_name,
- const char* function_name,
- InterceptionType interception_type,
- const char* replacement_function_name,
- InterceptorId id);
-
- // The interception agent will unload the dll with dll_name.
- bool AddToUnloadModules(const wchar_t* dll_name);
-
- // Initializes all interceptions on the client.
- // Returns true on success.
- //
- // The child process must be created suspended, and cannot be resumed until
- // after this method returns. In addition, no action should be performed on
- // the child that may cause it to resume momentarily, such as injecting
- // threads or APCs.
- //
- // This function must be called only once, after all interceptions have been
- // set up using AddToPatchedFunctions.
- bool InitializeInterceptions();
-
- private:
- // Used to store the interception information until the actual set-up.
- struct InterceptionData {
- InterceptionData();
- ~InterceptionData();
-
- InterceptionType type; // Interception type.
- InterceptorId id; // Interceptor id.
- base::string16 dll; // Name of dll to intercept.
- std::string function; // Name of function to intercept.
- std::string interceptor; // Name of interceptor function.
- const void* interceptor_address; // Interceptor's entry point.
- };
-
- // Calculates the size of the required configuration buffer.
- size_t GetBufferSize() const;
-
- // Rounds up the size of a given buffer, considering alignment (padding).
- // value is the current size of the buffer, and alignment is specified in
- // bytes.
- static inline size_t RoundUpToMultiple(size_t value, size_t alignment) {
- return ((value + alignment -1) / alignment) * alignment;
- }
-
- // Sets up a given buffer with all the information that has to be transfered
- // to the child.
- // Returns true on success.
- //
- // The buffer size should be at least the value returned by GetBufferSize
- bool SetupConfigBuffer(void* buffer, size_t buffer_bytes);
-
- // Fills up the part of the transfer buffer that corresponds to information
- // about one dll to patch.
- // data is the first recorded interception for this dll.
- // Returns true on success.
- //
- // On successful return, buffer will be advanced from it's current position
- // to the point where the next block of configuration data should be written
- // (the actual interception info), and the current size of the buffer will
- // decrease to account the space used by this method.
- bool SetupDllInfo(const InterceptionData& data,
- void** buffer, size_t* buffer_bytes) const;
-
- // Fills up the part of the transfer buffer that corresponds to a single
- // function to patch.
- // dll_info points to the dll being updated with the interception stored on
- // data. The buffer pointer and remaining size are updated by this call.
- // Returns true on success.
- bool SetupInterceptionInfo(const InterceptionData& data, void** buffer,
- size_t* buffer_bytes,
- DllPatchInfo* dll_info) const;
-
- // Returns true if this interception is to be performed by the child
- // as opposed to from the parent.
- bool IsInterceptionPerformedByChild(const InterceptionData& data) const;
-
- // Allocates a buffer on the child's address space (returned on
- // remote_buffer), and fills it with the contents of a local buffer.
- // Returns true on success.
- bool CopyDataToChild(const void* local_buffer, size_t buffer_bytes,
- void** remote_buffer) const;
-
- // Performs the cold patch (from the parent) of ntdll.
- // Returns true on success.
- //
- // This method will insert additional interceptions to launch the interceptor
- // agent on the child process, if there are additional interceptions to do.
- bool PatchNtdll(bool hot_patch_needed);
-
- // Peforms the actual interceptions on ntdll.
- // thunks is the memory to store all the thunks for this dll (on the child),
- // and dll_data is a local buffer to hold global dll interception info.
- // Returns true on success.
- bool PatchClientFunctions(DllInterceptionData* thunks,
- size_t thunk_bytes,
- DllInterceptionData* dll_data);
-
- // The process to intercept.
- TargetProcess* child_;
- // Holds all interception info until the call to initialize (perform the
- // actual patch).
- std::list<InterceptionData> interceptions_;
-
- // Keep track of patches added by name.
- bool names_used_;
-
- // true if we are allowed to patch already-patched functions.
- bool relaxed_;
-
- DISALLOW_COPY_AND_ASSIGN(InterceptionManager);
-};
-
-// This macro simply calls interception_manager.AddToPatchedFunctions with
-// the given service to intercept (INTERCEPTION_SERVICE_CALL), and assumes that
-// the interceptor is called "TargetXXX", where XXX is the name of the service.
-// Note that num_params is the number of bytes to pop out of the stack for
-// the exported interceptor, following the calling convention of a service call
-// (WINAPI = with the "C" underscore).
-#if SANDBOX_EXPORTS
-#if defined(_WIN64)
-#define MAKE_SERVICE_NAME(service, params) "Target" # service "64"
-#else
-#define MAKE_SERVICE_NAME(service, params) "_Target" # service "@" # params
-#endif
-
-#define ADD_NT_INTERCEPTION(service, id, num_params) \
- AddToPatchedFunctions(kNtdllName, #service, \
- sandbox::INTERCEPTION_SERVICE_CALL, \
- MAKE_SERVICE_NAME(service, num_params), id)
-
-#define INTERCEPT_NT(manager, service, id, num_params) \
- ((&Target##service) ? \
- manager->ADD_NT_INTERCEPTION(service, id, num_params) : false)
-
-// When intercepting the EAT it is important that the patched version of the
-// function not call any functions imported from system libraries unless
-// |TargetServices::InitCalled()| returns true, because it is only then that
-// we are guaranteed that our IAT has been initialized.
-#define INTERCEPT_EAT(manager, dll, function, id, num_params) \
- ((&Target##function) ? \
- manager->AddToPatchedFunctions(dll, #function, sandbox::INTERCEPTION_EAT, \
- MAKE_SERVICE_NAME(function, num_params), \
- id) : \
- false)
-#else // SANDBOX_EXPORTS
-#if defined(_WIN64)
-#define MAKE_SERVICE_NAME(service) &Target##service##64
-#else
-#define MAKE_SERVICE_NAME(service) &Target##service
-#endif
-
-#define ADD_NT_INTERCEPTION(service, id, num_params) \
- AddToPatchedFunctions(kNtdllName, #service, \
- sandbox::INTERCEPTION_SERVICE_CALL, \
- MAKE_SERVICE_NAME(service), id)
-
-#define INTERCEPT_NT(manager, service, id, num_params) \
- manager->ADD_NT_INTERCEPTION(service, id, num_params)
-
-// When intercepting the EAT it is important that the patched version of the
-// function not call any functions imported from system libraries unless
-// |TargetServices::InitCalled()| returns true, because it is only then that
-// we are guaranteed that our IAT has been initialized.
-#define INTERCEPT_EAT(manager, dll, function, id, num_params) \
- manager->AddToPatchedFunctions(dll, #function, sandbox::INTERCEPTION_EAT, \
- MAKE_SERVICE_NAME(function), id)
-#endif // SANDBOX_EXPORTS
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_INTERCEPTION_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/interception_agent.cc b/security/sandbox/chromium/sandbox/win/src/interception_agent.cc
deleted file mode 100644
index 1ef688638..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interception_agent.cc
+++ /dev/null
@@ -1,235 +0,0 @@
-// Copyright (c) 2006-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.
-
-// For information about interceptions as a whole see
-// http://dev.chromium.org/developers/design-documents/sandbox .
-
-#include "sandbox/win/src/interception_agent.h"
-
-#include <stddef.h>
-
-#include "sandbox/win/src/eat_resolver.h"
-#include "sandbox/win/src/interception_internal.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sidestep_resolver.h"
-
-namespace {
-
-// Returns true if target lies between base and base + range.
-bool IsWithinRange(const void* base, size_t range, const void* target) {
- const char* end = reinterpret_cast<const char*>(base) + range;
- return reinterpret_cast<const char*>(target) < end;
-}
-
-} // namespace
-
-namespace sandbox {
-
-// This is the list of all imported symbols from ntdll.dll.
-SANDBOX_INTERCEPT NtExports g_nt;
-
-// The list of intercepted functions back-pointers.
-SANDBOX_INTERCEPT OriginalFunctions g_originals;
-
-// Memory buffer mapped from the parent, with the list of interceptions.
-SANDBOX_INTERCEPT SharedMemory* g_interceptions = NULL;
-
-InterceptionAgent* InterceptionAgent::GetInterceptionAgent() {
- static InterceptionAgent* s_singleton = NULL;
- if (!s_singleton) {
- if (!g_interceptions)
- return NULL;
-
- size_t array_bytes = g_interceptions->num_intercepted_dlls * sizeof(void*);
- s_singleton = reinterpret_cast<InterceptionAgent*>(
- new(NT_ALLOC) char[array_bytes + sizeof(InterceptionAgent)]);
-
- bool success = s_singleton->Init(g_interceptions);
- if (!success) {
- operator delete(s_singleton, NT_ALLOC);
- s_singleton = NULL;
- }
- }
- return s_singleton;
-}
-
-bool InterceptionAgent::Init(SharedMemory* shared_memory) {
- interceptions_ = shared_memory;
- for (int i = 0 ; i < shared_memory->num_intercepted_dlls; i++)
- dlls_[i] = NULL;
- return true;
-}
-
-bool InterceptionAgent::DllMatch(const UNICODE_STRING* full_path,
- const UNICODE_STRING* name,
- const DllPatchInfo* dll_info) {
- UNICODE_STRING current_name;
- current_name.Length = static_cast<USHORT>(g_nt.wcslen(dll_info->dll_name) *
- sizeof(wchar_t));
- current_name.MaximumLength = current_name.Length;
- current_name.Buffer = const_cast<wchar_t*>(dll_info->dll_name);
-
- BOOLEAN case_insensitive = TRUE;
- if (full_path &&
- !g_nt.RtlCompareUnicodeString(&current_name, full_path, case_insensitive))
- return true;
-
- if (name &&
- !g_nt.RtlCompareUnicodeString(&current_name, name, case_insensitive))
- return true;
-
- return false;
-}
-
-bool InterceptionAgent::OnDllLoad(const UNICODE_STRING* full_path,
- const UNICODE_STRING* name,
- void* base_address) {
- DllPatchInfo* dll_info = interceptions_->dll_list;
- int i = 0;
- for (; i < interceptions_->num_intercepted_dlls; i++) {
- if (DllMatch(full_path, name, dll_info))
- break;
-
- dll_info = reinterpret_cast<DllPatchInfo*>(
- reinterpret_cast<char*>(dll_info) + dll_info->record_bytes);
- }
-
- // Return now if the dll is not in our list of interest.
- if (i == interceptions_->num_intercepted_dlls)
- return true;
-
- // The dll must be unloaded.
- if (dll_info->unload_module)
- return false;
-
- // Purify causes this condition to trigger.
- if (dlls_[i])
- return true;
-
- size_t buffer_bytes = offsetof(DllInterceptionData, thunks) +
- dll_info->num_functions * sizeof(ThunkData);
- dlls_[i] = reinterpret_cast<DllInterceptionData*>(
- new(NT_PAGE, base_address) char[buffer_bytes]);
-
- DCHECK_NT(dlls_[i]);
- if (!dlls_[i])
- return true;
-
- dlls_[i]->data_bytes = buffer_bytes;
- dlls_[i]->num_thunks = 0;
- dlls_[i]->base = base_address;
- dlls_[i]->used_bytes = offsetof(DllInterceptionData, thunks);
-
- VERIFY(PatchDll(dll_info, dlls_[i]));
-
- ULONG old_protect;
- SIZE_T real_size = buffer_bytes;
- void* to_protect = dlls_[i];
- VERIFY_SUCCESS(g_nt.ProtectVirtualMemory(NtCurrentProcess, &to_protect,
- &real_size, PAGE_EXECUTE_READ,
- &old_protect));
- return true;
-}
-
-void InterceptionAgent::OnDllUnload(void* base_address) {
- for (int i = 0; i < interceptions_->num_intercepted_dlls; i++) {
- if (dlls_[i] && dlls_[i]->base == base_address) {
- operator delete(dlls_[i], NT_PAGE);
- dlls_[i] = NULL;
- break;
- }
- }
-}
-
-// TODO(rvargas): We have to deal with prebinded dlls. I see two options: change
-// the timestamp of the patched dll, or modify the info on the prebinded dll.
-// the first approach messes matching of debug symbols, the second one is more
-// complicated.
-bool InterceptionAgent::PatchDll(const DllPatchInfo* dll_info,
- DllInterceptionData* thunks) {
- DCHECK_NT(NULL != thunks);
- DCHECK_NT(NULL != dll_info);
-
- const FunctionInfo* function = reinterpret_cast<const FunctionInfo*>(
- reinterpret_cast<const char*>(dll_info) + dll_info->offset_to_functions);
-
- for (int i = 0; i < dll_info->num_functions; i++) {
- if (!IsWithinRange(dll_info, dll_info->record_bytes, function->function)) {
- NOTREACHED_NT();
- return false;
- }
-
- ResolverThunk* resolver = GetResolver(function->type);
- if (!resolver)
- return false;
-
- const char* interceptor = function->function +
- g_nt.strlen(function->function) + 1;
-
- if (!IsWithinRange(function, function->record_bytes, interceptor) ||
- !IsWithinRange(dll_info, dll_info->record_bytes, interceptor)) {
- NOTREACHED_NT();
- return false;
- }
-
- NTSTATUS ret = resolver->Setup(thunks->base,
- interceptions_->interceptor_base,
- function->function,
- interceptor,
- function->interceptor_address,
- &thunks->thunks[i],
- sizeof(ThunkData),
- NULL);
- if (!NT_SUCCESS(ret)) {
- NOTREACHED_NT();
- return false;
- }
-
- DCHECK_NT(!g_originals[function->id]);
- g_originals[function->id] = &thunks->thunks[i];
-
- thunks->num_thunks++;
- thunks->used_bytes += sizeof(ThunkData);
-
- function = reinterpret_cast<const FunctionInfo*>(
- reinterpret_cast<const char*>(function) + function->record_bytes);
- }
-
- return true;
-}
-
-// This method is called from within the loader lock
-ResolverThunk* InterceptionAgent::GetResolver(InterceptionType type) {
- static EatResolverThunk* eat_resolver = NULL;
- static SidestepResolverThunk* sidestep_resolver = NULL;
- static SmartSidestepResolverThunk* smart_sidestep_resolver = NULL;
-
- if (!eat_resolver)
- eat_resolver = new(NT_ALLOC) EatResolverThunk;
-
-#if !defined(_WIN64)
- // Sidestep is not supported for x64.
- if (!sidestep_resolver)
- sidestep_resolver = new(NT_ALLOC) SidestepResolverThunk;
-
- if (!smart_sidestep_resolver)
- smart_sidestep_resolver = new(NT_ALLOC) SmartSidestepResolverThunk;
-#endif
-
- switch (type) {
- case INTERCEPTION_EAT:
- return eat_resolver;
- case INTERCEPTION_SIDESTEP:
- return sidestep_resolver;
- case INTERCEPTION_SMART_SIDESTEP:
- return smart_sidestep_resolver;
- default:
- NOTREACHED_NT();
- }
-
- return NULL;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/interception_agent.h b/security/sandbox/chromium/sandbox/win/src/interception_agent.h
deleted file mode 100644
index b2bce08b0..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interception_agent.h
+++ /dev/null
@@ -1,87 +0,0 @@
-// 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.
-
-// Defines InterceptionAgent, the class in charge of setting up interceptions
-// from the inside of the sandboxed process. For more details see
-// http://dev.chromium.org/developers/design-documents/sandbox .
-
-#ifndef SANDBOX_SRC_INTERCEPTION_AGENT_H__
-#define SANDBOX_SRC_INTERCEPTION_AGENT_H__
-
-#include "base/macros.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace sandbox {
-
-// Internal structures used for communication between the broker and the target.
-struct DllInterceptionData;
-struct SharedMemory;
-struct DllPatchInfo;
-
-class ResolverThunk;
-
-// The InterceptionAgent executes on the target application, and it is in charge
-// of setting up the desired interceptions or indicating what module needs to
-// be unloaded.
-//
-// The exposed API consists of three methods: GetInterceptionAgent to retrieve
-// the single class instance, OnDllLoad and OnDllUnload to process a dll being
-// loaded and unloaded respectively.
-//
-// This class assumes that it will get called for every dll being loaded,
-// starting with kernel32, so the singleton will be instantiated from within the
-// loader lock.
-class InterceptionAgent {
- public:
- // Returns the single InterceptionAgent object for this process.
- static InterceptionAgent* GetInterceptionAgent();
-
- // This method should be invoked whenever a new dll is loaded to perform the
- // required patches. If the return value is false, this dll should not be
- // allowed to load.
- //
- // full_path is the (optional) full name of the module being loaded and name
- // is the internal module name. If full_path is provided, it will be used
- // before the internal name to determine if we care about this dll.
- bool OnDllLoad(const UNICODE_STRING* full_path, const UNICODE_STRING* name,
- void* base_address);
-
- // Performs cleanup when a dll is unloaded.
- void OnDllUnload(void* base_address);
-
- private:
- ~InterceptionAgent() {}
-
- // Performs initialization of the singleton.
- bool Init(SharedMemory* shared_memory);
-
- // Returns true if we are interested on this dll. dll_info is an entry of the
- // list of intercepted dlls.
- bool DllMatch(const UNICODE_STRING* full_path, const UNICODE_STRING* name,
- const DllPatchInfo* dll_info);
-
- // Performs the patching of the dll loaded at base_address.
- // The patches to perform are described on dll_info, and thunks is the thunk
- // storage for the whole dll.
- // Returns true on success.
- bool PatchDll(const DllPatchInfo* dll_info, DllInterceptionData* thunks);
-
- // Returns a resolver for a given interception type.
- ResolverThunk* GetResolver(InterceptionType type);
-
- // Shared memory containing the list of functions to intercept.
- SharedMemory* interceptions_;
-
- // Array of thunk data buffers for the intercepted dlls. This object singleton
- // is allocated with a placement new with enough space to hold the complete
- // array of pointers, not just the first element.
- DllInterceptionData* dlls_[1];
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(InterceptionAgent);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_INTERCEPTION_AGENT_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/interception_internal.h b/security/sandbox/chromium/sandbox/win/src/interception_internal.h
deleted file mode 100644
index 45a0557e5..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interception_internal.h
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright (c) 2006-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.
-
-// Defines InterceptionManager, the class in charge of setting up interceptions
-// for the sandboxed process. For more details see:
-// http://dev.chromium.org/developers/design-documents/sandbox .
-
-#ifndef SANDBOX_SRC_INTERCEPTION_INTERNAL_H_
-#define SANDBOX_SRC_INTERCEPTION_INTERNAL_H_
-
-#include <stddef.h>
-
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace sandbox {
-
-const int kMaxThunkDataBytes = 64;
-
-enum InterceptorId;
-
-// The following structures contain variable size fields at the end, and will be
-// used to transfer information between two processes. In order to guarantee
-// our ability to follow the chain of structures, the alignment should be fixed,
-// hence this pragma.
-#pragma pack(push, 4)
-
-// Structures for the shared memory that contains patching information
-// for the InterceptionAgent.
-// A single interception:
-struct FunctionInfo {
- size_t record_bytes; // rounded to sizeof(size_t) bytes
- InterceptionType type;
- InterceptorId id;
- const void* interceptor_address;
- char function[1]; // placeholder for null terminated name
- // char interceptor[] // followed by the interceptor function
-};
-
-// A single dll:
-struct DllPatchInfo {
- size_t record_bytes; // rounded to sizeof(size_t) bytes
- size_t offset_to_functions;
- int num_functions;
- bool unload_module;
- wchar_t dll_name[1]; // placeholder for null terminated name
- // FunctionInfo function_info[] // followed by the functions to intercept
-};
-
-// All interceptions:
-struct SharedMemory {
- int num_intercepted_dlls;
- void* interceptor_base;
- DllPatchInfo dll_list[1]; // placeholder for the list of dlls
-};
-
-// Dummy single thunk:
-struct ThunkData {
- char data[kMaxThunkDataBytes];
-};
-
-// In-memory representation of the interceptions for a given dll:
-struct DllInterceptionData {
- size_t data_bytes;
- size_t used_bytes;
- void* base;
- int num_thunks;
-#if defined(_WIN64)
- int dummy; // Improve alignment.
-#endif
- ThunkData thunks[1];
-};
-
-#pragma pack(pop)
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_INTERCEPTION_INTERNAL_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/interception_unittest.cc b/security/sandbox/chromium/sandbox/win/src/interception_unittest.cc
deleted file mode 100644
index 7b7932af6..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interception_unittest.cc
+++ /dev/null
@@ -1,260 +0,0 @@
-// 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.
-
-// This file contains unit tests for InterceptionManager.
-// The tests require private information so the whole interception.cc file is
-// included from this file.
-
-#include <windows.h>
-#include <stddef.h>
-
-#include <algorithm>
-#include <set>
-
-#include "base/bits.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/interception_internal.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/target_process.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-namespace internal {
-size_t GetGranularAlignedRandomOffset(size_t size);
-}
-
-// Walks the settings buffer, verifying that the values make sense and counting
-// objects.
-// Arguments:
-// buffer (in): the buffer to walk.
-// size (in): buffer size
-// num_dlls (out): count of the dlls on the buffer.
-// num_function (out): count of intercepted functions.
-// num_names (out): count of named interceptor functions.
-void WalkBuffer(void* buffer, size_t size, int* num_dlls, int* num_functions,
- int* num_names) {
- ASSERT_TRUE(NULL != buffer);
- ASSERT_TRUE(NULL != num_functions);
- ASSERT_TRUE(NULL != num_names);
- *num_dlls = *num_functions = *num_names = 0;
- SharedMemory *memory = reinterpret_cast<SharedMemory*>(buffer);
-
- ASSERT_GT(size, sizeof(SharedMemory));
- DllPatchInfo *dll = &memory->dll_list[0];
-
- for (int i = 0; i < memory->num_intercepted_dlls; i++) {
- ASSERT_NE(0u, wcslen(dll->dll_name));
- ASSERT_EQ(0u, dll->record_bytes % sizeof(size_t));
- ASSERT_EQ(0u, dll->offset_to_functions % sizeof(size_t));
- ASSERT_NE(0, dll->num_functions);
-
- FunctionInfo *function = reinterpret_cast<FunctionInfo*>(
- reinterpret_cast<char*>(dll) + dll->offset_to_functions);
-
- for (int j = 0; j < dll->num_functions; j++) {
- ASSERT_EQ(0u, function->record_bytes % sizeof(size_t));
-
- char* name = function->function;
- size_t length = strlen(name);
- ASSERT_NE(0u, length);
- name += length + 1;
-
- // look for overflows
- ASSERT_GT(reinterpret_cast<char*>(buffer) + size, name + strlen(name));
-
- // look for a named interceptor
- if (strlen(name)) {
- (*num_names)++;
- EXPECT_TRUE(NULL == function->interceptor_address);
- } else {
- EXPECT_TRUE(NULL != function->interceptor_address);
- }
-
- (*num_functions)++;
- function = reinterpret_cast<FunctionInfo*>(
- reinterpret_cast<char*>(function) + function->record_bytes);
- }
-
- (*num_dlls)++;
- dll = reinterpret_cast<DllPatchInfo*>(reinterpret_cast<char*>(dll) +
- dll->record_bytes);
- }
-}
-
-TEST(InterceptionManagerTest, GetGranularAlignedRandomOffset) {
- std::set<size_t> sizes;
-
- // 544 is current value of interceptions_.size() * sizeof(ThunkData) +
- // sizeof(DllInterceptionData).
- const size_t kThunkBytes = 544;
-
- // ciel(log2(544)) = 10.
- // Alignment must be 2^10 = 1024.
- const size_t kAlignmentBits = base::bits::Log2Ceiling(kThunkBytes);
- const size_t kAlignment = static_cast<size_t>(1) << kAlignmentBits;
-
- const size_t kAllocGranularity = 65536;
-
- // Generate enough sample data to ensure there is at least one value in each
- // potential bucket.
- for (size_t i = 0; i < 1000000; i++)
- sizes.insert(internal::GetGranularAlignedRandomOffset(kThunkBytes));
-
- size_t prev_val = 0;
- size_t min_val = kAllocGranularity;
- size_t min_nonzero_val = kAllocGranularity;
- size_t max_val = 0;
-
- for (size_t val : sizes) {
- ASSERT_LT(val, kAllocGranularity);
- if (prev_val)
- ASSERT_EQ(val - prev_val, kAlignment);
- if (val)
- min_nonzero_val = std::min(val, min_nonzero_val);
- min_val = std::min(val, min_val);
- prev_val = val;
- max_val = std::max(val, max_val);
- }
- ASSERT_EQ(max_val, kAllocGranularity - kAlignment);
- ASSERT_EQ(0u, min_val);
- ASSERT_EQ(min_nonzero_val, kAlignment);
-}
-
-TEST(InterceptionManagerTest, BufferLayout1) {
- wchar_t exe_name[MAX_PATH];
- ASSERT_NE(0u, GetModuleFileName(NULL, exe_name, MAX_PATH - 1));
-
- TargetProcess *target = MakeTestTargetProcess(::GetCurrentProcess(),
- ::GetModuleHandle(exe_name));
-
- InterceptionManager interceptions(target, true);
-
- // Any pointer will do for a function pointer.
- void* function = &interceptions;
-
- // We don't care about the interceptor id.
- interceptions.AddToPatchedFunctions(L"ntdll.dll", "NtCreateFile",
- INTERCEPTION_SERVICE_CALL, function,
- OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"kernel32.dll", "CreateFileEx",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"kernel32.dll", "SomeFileEx",
- INTERCEPTION_SMART_SIDESTEP, function,
- OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"user32.dll", "FindWindow",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"kernel32.dll", "CreateMutex",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"user32.dll", "PostMsg",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"user32.dll", "PostMsg",
- INTERCEPTION_EAT, "replacement",
- OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"comctl.dll", "SaveAsDlg",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"ntdll.dll", "NtClose",
- INTERCEPTION_SERVICE_CALL, function,
- OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"ntdll.dll", "NtOpenFile",
- INTERCEPTION_SIDESTEP, function,
- OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"some.dll", "Superfn",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"comctl.dll", "SaveAsDlg",
- INTERCEPTION_EAT, "a", OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"comctl.dll", "SaveAsDlg",
- INTERCEPTION_SIDESTEP, "ab", OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"comctl.dll", "SaveAsDlg",
- INTERCEPTION_EAT, "abc", OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"a.dll", "p",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"b.dll",
- "TheIncredibleCallToSaveTheWorld",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"a.dll", "BIsLame",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
- interceptions.AddToPatchedFunctions(L"a.dll", "ARules",
- INTERCEPTION_EAT, function, OPEN_KEY_ID);
-
- // Verify that all interceptions were added
- ASSERT_EQ(18u, interceptions.interceptions_.size());
-
- size_t buffer_size = interceptions.GetBufferSize();
- scoped_ptr<BYTE[]> local_buffer(new BYTE[buffer_size]);
-
- ASSERT_TRUE(interceptions.SetupConfigBuffer(local_buffer.get(),
- buffer_size));
-
- // At this point, the interceptions should have been separated into two
- // groups: one group with the local ("cold") interceptions, consisting of
- // everything from ntdll and stuff set as INTRECEPTION_SERVICE_CALL, and
- // another group with the interceptions belonging to dlls that will be "hot"
- // patched on the client. The second group lives on local_buffer, and the
- // first group remains on the list of interceptions (inside the object
- // "interceptions"). There are 3 local interceptions (of ntdll); the
- // other 15 have to be sent to the child to be performed "hot".
- EXPECT_EQ(3u, interceptions.interceptions_.size());
-
- int num_dlls, num_functions, num_names;
- WalkBuffer(local_buffer.get(), buffer_size, &num_dlls, &num_functions,
- &num_names);
-
- // The 15 interceptions on the buffer (to the child) should be grouped on 6
- // dlls. Only four interceptions are using an explicit name for the
- // interceptor function.
- EXPECT_EQ(6, num_dlls);
- EXPECT_EQ(15, num_functions);
- EXPECT_EQ(4, num_names);
-}
-
-TEST(InterceptionManagerTest, BufferLayout2) {
- wchar_t exe_name[MAX_PATH];
- ASSERT_NE(0u, GetModuleFileName(NULL, exe_name, MAX_PATH - 1));
-
- TargetProcess *target = MakeTestTargetProcess(::GetCurrentProcess(),
- ::GetModuleHandle(exe_name));
-
- InterceptionManager interceptions(target, true);
-
- // Any pointer will do for a function pointer.
- void* function = &interceptions;
- interceptions.AddToUnloadModules(L"some01.dll");
- // We don't care about the interceptor id.
- interceptions.AddToPatchedFunctions(L"ntdll.dll", "NtCreateFile",
- INTERCEPTION_SERVICE_CALL, function,
- OPEN_FILE_ID);
- interceptions.AddToPatchedFunctions(L"kernel32.dll", "CreateFileEx",
- INTERCEPTION_EAT, function, OPEN_FILE_ID);
- interceptions.AddToUnloadModules(L"some02.dll");
- interceptions.AddToPatchedFunctions(L"kernel32.dll", "SomeFileEx",
- INTERCEPTION_SMART_SIDESTEP, function,
- OPEN_FILE_ID);
- // Verify that all interceptions were added
- ASSERT_EQ(5u, interceptions.interceptions_.size());
-
- size_t buffer_size = interceptions.GetBufferSize();
- scoped_ptr<BYTE[]> local_buffer(new BYTE[buffer_size]);
-
- ASSERT_TRUE(interceptions.SetupConfigBuffer(local_buffer.get(),
- buffer_size));
-
- // At this point, the interceptions should have been separated into two
- // groups: one group with the local ("cold") interceptions, and another
- // group with the interceptions belonging to dlls that will be "hot"
- // patched on the client. The second group lives on local_buffer, and the
- // first group remains on the list of interceptions, in this case just one.
- EXPECT_EQ(1u, interceptions.interceptions_.size());
-
- int num_dlls, num_functions, num_names;
- WalkBuffer(local_buffer.get(), buffer_size, &num_dlls, &num_functions,
- &num_names);
-
- EXPECT_EQ(3, num_dlls);
- EXPECT_EQ(4, num_functions);
- EXPECT_EQ(0, num_names);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/interceptors.h b/security/sandbox/chromium/sandbox/win/src/interceptors.h
deleted file mode 100644
index a17447aa1..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interceptors.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// 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 SANDBOX_SRC_INTERCEPTORS_H_
-#define SANDBOX_SRC_INTERCEPTORS_H_
-
-#if defined(_WIN64)
-#include "sandbox/win/src/interceptors_64.h"
-#endif
-
-namespace sandbox {
-
-enum InterceptorId {
- // Internal use:
- MAP_VIEW_OF_SECTION_ID = 0,
- UNMAP_VIEW_OF_SECTION_ID,
- // Policy broker:
- SET_INFORMATION_THREAD_ID,
- OPEN_THREAD_TOKEN_ID,
- OPEN_THREAD_TOKEN_EX_ID,
- OPEN_TREAD_ID,
- OPEN_PROCESS_ID,
- OPEN_PROCESS_TOKEN_ID,
- OPEN_PROCESS_TOKEN_EX_ID,
- // Filesystem dispatcher:
- CREATE_FILE_ID,
- OPEN_FILE_ID,
- QUERY_ATTRIB_FILE_ID,
- QUERY_FULL_ATTRIB_FILE_ID,
- SET_INFO_FILE_ID,
- // Named pipe dispatcher:
- CREATE_NAMED_PIPE_ID,
- // Process-thread dispatcher:
- CREATE_PROCESSW_ID,
- CREATE_PROCESSA_ID,
- // Registry dispatcher:
- CREATE_KEY_ID,
- OPEN_KEY_ID,
- OPEN_KEY_EX_ID,
- // Sync dispatcher:
- CREATE_EVENT_ID,
- OPEN_EVENT_ID,
- // Process mitigations Win32k dispatcher:
- GDIINITIALIZE_ID,
- GETSTOCKOBJECT_ID,
- REGISTERCLASSW_ID,
- INTERCEPTOR_MAX_ID
-};
-
-typedef void* OriginalFunctions[INTERCEPTOR_MAX_ID];
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_INTERCEPTORS_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/interceptors_64.cc b/security/sandbox/chromium/sandbox/win/src/interceptors_64.cc
deleted file mode 100644
index ef0b5f001..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interceptors_64.cc
+++ /dev/null
@@ -1,278 +0,0 @@
-// 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 "sandbox/win/src/interceptors_64.h"
-
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/filesystem_interception.h"
-#include "sandbox/win/src/named_pipe_interception.h"
-#include "sandbox/win/src/policy_target.h"
-#include "sandbox/win/src/process_mitigations_win32k_interception.h"
-#include "sandbox/win/src/process_thread_interception.h"
-#include "sandbox/win/src/registry_interception.h"
-#include "sandbox/win/src/sandbox_nt_types.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sync_interception.h"
-#include "sandbox/win/src/target_interceptions.h"
-
-namespace sandbox {
-
-SANDBOX_INTERCEPT NtExports g_nt;
-SANDBOX_INTERCEPT OriginalFunctions g_originals;
-
-NTSTATUS WINAPI TargetNtMapViewOfSection64(
- HANDLE section, HANDLE process, PVOID *base, ULONG_PTR zero_bits,
- SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size,
- SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect) {
- NtMapViewOfSectionFunction orig_fn = reinterpret_cast<
- NtMapViewOfSectionFunction>(g_originals[MAP_VIEW_OF_SECTION_ID]);
-
- return TargetNtMapViewOfSection(orig_fn, section, process, base, zero_bits,
- commit_size, offset, view_size, inherit,
- allocation_type, protect);
-}
-
-NTSTATUS WINAPI TargetNtUnmapViewOfSection64(HANDLE process, PVOID base) {
- NtUnmapViewOfSectionFunction orig_fn = reinterpret_cast<
- NtUnmapViewOfSectionFunction>(g_originals[UNMAP_VIEW_OF_SECTION_ID]);
- return TargetNtUnmapViewOfSection(orig_fn, process, base);
-}
-
-// -----------------------------------------------------------------------
-
-NTSTATUS WINAPI TargetNtSetInformationThread64(
- HANDLE thread, NT_THREAD_INFORMATION_CLASS thread_info_class,
- PVOID thread_information, ULONG thread_information_bytes) {
- NtSetInformationThreadFunction orig_fn = reinterpret_cast<
- NtSetInformationThreadFunction>(g_originals[SET_INFORMATION_THREAD_ID]);
- return TargetNtSetInformationThread(orig_fn, thread, thread_info_class,
- thread_information,
- thread_information_bytes);
-}
-
-NTSTATUS WINAPI TargetNtOpenThreadToken64(
- HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self,
- PHANDLE token) {
- NtOpenThreadTokenFunction orig_fn = reinterpret_cast<
- NtOpenThreadTokenFunction>(g_originals[OPEN_THREAD_TOKEN_ID]);
- return TargetNtOpenThreadToken(orig_fn, thread, desired_access, open_as_self,
- token);
-}
-
-NTSTATUS WINAPI TargetNtOpenThreadTokenEx64(
- HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self,
- ULONG handle_attributes, PHANDLE token) {
- NtOpenThreadTokenExFunction orig_fn = reinterpret_cast<
- NtOpenThreadTokenExFunction>(g_originals[OPEN_THREAD_TOKEN_EX_ID]);
- return TargetNtOpenThreadTokenEx(orig_fn, thread, desired_access,
- open_as_self, handle_attributes, token);
-}
-
-// -----------------------------------------------------------------------
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateFile64(
- PHANDLE file, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
- PLARGE_INTEGER allocation_size, ULONG file_attributes, ULONG sharing,
- ULONG disposition, ULONG options, PVOID ea_buffer, ULONG ea_length) {
- NtCreateFileFunction orig_fn = reinterpret_cast<
- NtCreateFileFunction>(g_originals[CREATE_FILE_ID]);
- return TargetNtCreateFile(orig_fn, file, desired_access, object_attributes,
- io_status, allocation_size, file_attributes,
- sharing, disposition, options, ea_buffer,
- ea_length);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenFile64(
- PHANDLE file, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
- ULONG sharing, ULONG options) {
- NtOpenFileFunction orig_fn = reinterpret_cast<
- NtOpenFileFunction>(g_originals[OPEN_FILE_ID]);
- return TargetNtOpenFile(orig_fn, file, desired_access, object_attributes,
- io_status, sharing, options);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryAttributesFile64(
- POBJECT_ATTRIBUTES object_attributes,
- PFILE_BASIC_INFORMATION file_attributes) {
- NtQueryAttributesFileFunction orig_fn = reinterpret_cast<
- NtQueryAttributesFileFunction>(g_originals[QUERY_ATTRIB_FILE_ID]);
- return TargetNtQueryAttributesFile(orig_fn, object_attributes,
- file_attributes);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryFullAttributesFile64(
- POBJECT_ATTRIBUTES object_attributes,
- PFILE_NETWORK_OPEN_INFORMATION file_attributes) {
- NtQueryFullAttributesFileFunction orig_fn = reinterpret_cast<
- NtQueryFullAttributesFileFunction>(
- g_originals[QUERY_FULL_ATTRIB_FILE_ID]);
- return TargetNtQueryFullAttributesFile(orig_fn, object_attributes,
- file_attributes);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationFile64(
- HANDLE file, PIO_STATUS_BLOCK io_status, PVOID file_information,
- ULONG length, FILE_INFORMATION_CLASS file_information_class) {
- NtSetInformationFileFunction orig_fn = reinterpret_cast<
- NtSetInformationFileFunction>(g_originals[SET_INFO_FILE_ID]);
- return TargetNtSetInformationFile(orig_fn, file, io_status, file_information,
- length, file_information_class);
-}
-
-// -----------------------------------------------------------------------
-
-SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateNamedPipeW64(
- LPCWSTR pipe_name, DWORD open_mode, DWORD pipe_mode, DWORD max_instance,
- DWORD out_buffer_size, DWORD in_buffer_size, DWORD default_timeout,
- LPSECURITY_ATTRIBUTES security_attributes) {
- CreateNamedPipeWFunction orig_fn = reinterpret_cast<
- CreateNamedPipeWFunction>(g_originals[CREATE_NAMED_PIPE_ID]);
- return TargetCreateNamedPipeW(orig_fn, pipe_name, open_mode, pipe_mode,
- max_instance, out_buffer_size, in_buffer_size,
- default_timeout, security_attributes);
-}
-
-// -----------------------------------------------------------------------
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThread64(
- PHANDLE thread, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) {
- NtOpenThreadFunction orig_fn = reinterpret_cast<
- NtOpenThreadFunction>(g_originals[OPEN_TREAD_ID]);
- return TargetNtOpenThread(orig_fn, thread, desired_access, object_attributes,
- client_id);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcess64(
- PHANDLE process, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) {
- NtOpenProcessFunction orig_fn = reinterpret_cast<
- NtOpenProcessFunction>(g_originals[OPEN_PROCESS_ID]);
- return TargetNtOpenProcess(orig_fn, process, desired_access,
- object_attributes, client_id);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessToken64(
- HANDLE process, ACCESS_MASK desired_access, PHANDLE token) {
- NtOpenProcessTokenFunction orig_fn = reinterpret_cast<
- NtOpenProcessTokenFunction>(g_originals[OPEN_PROCESS_TOKEN_ID]);
- return TargetNtOpenProcessToken(orig_fn, process, desired_access, token);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessTokenEx64(
- HANDLE process, ACCESS_MASK desired_access, ULONG handle_attributes,
- PHANDLE token) {
- NtOpenProcessTokenExFunction orig_fn = reinterpret_cast<
- NtOpenProcessTokenExFunction>(g_originals[OPEN_PROCESS_TOKEN_EX_ID]);
- return TargetNtOpenProcessTokenEx(orig_fn, process, desired_access,
- handle_attributes, token);
-}
-
-SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessW64(
- LPCWSTR application_name, LPWSTR command_line,
- LPSECURITY_ATTRIBUTES process_attributes,
- LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
- LPVOID environment, LPCWSTR current_directory, LPSTARTUPINFOW startup_info,
- LPPROCESS_INFORMATION process_information) {
- CreateProcessWFunction orig_fn = reinterpret_cast<
- CreateProcessWFunction>(g_originals[CREATE_PROCESSW_ID]);
- return TargetCreateProcessW(orig_fn, application_name, command_line,
- process_attributes, thread_attributes,
- inherit_handles, flags, environment,
- current_directory, startup_info,
- process_information);
-}
-
-SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessA64(
- LPCSTR application_name, LPSTR command_line,
- LPSECURITY_ATTRIBUTES process_attributes,
- LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
- LPVOID environment, LPCSTR current_directory, LPSTARTUPINFOA startup_info,
- LPPROCESS_INFORMATION process_information) {
- CreateProcessAFunction orig_fn = reinterpret_cast<
- CreateProcessAFunction>(g_originals[CREATE_PROCESSA_ID]);
- return TargetCreateProcessA(orig_fn, application_name, command_line,
- process_attributes, thread_attributes,
- inherit_handles, flags, environment,
- current_directory, startup_info,
- process_information);
-}
-
-// -----------------------------------------------------------------------
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateKey64(
- PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, ULONG title_index,
- PUNICODE_STRING class_name, ULONG create_options, PULONG disposition) {
- NtCreateKeyFunction orig_fn = reinterpret_cast<
- NtCreateKeyFunction>(g_originals[CREATE_KEY_ID]);
- return TargetNtCreateKey(orig_fn, key, desired_access, object_attributes,
- title_index, class_name, create_options,
- disposition);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKey64(
- PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes) {
- NtOpenKeyFunction orig_fn = reinterpret_cast<
- NtOpenKeyFunction>(g_originals[OPEN_KEY_ID]);
- return TargetNtOpenKey(orig_fn, key, desired_access, object_attributes);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKeyEx64(
- PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, ULONG open_options) {
- NtOpenKeyExFunction orig_fn = reinterpret_cast<
- NtOpenKeyExFunction>(g_originals[OPEN_KEY_EX_ID]);
- return TargetNtOpenKeyEx(orig_fn, key, desired_access, object_attributes,
- open_options);
-}
-
-// -----------------------------------------------------------------------
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateEvent64(
- PHANDLE event_handle, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, EVENT_TYPE event_type,
- BOOLEAN initial_state) {
- NtCreateEventFunction orig_fn = reinterpret_cast<
- NtCreateEventFunction>(g_originals[CREATE_EVENT_ID]);
- return TargetNtCreateEvent(orig_fn, event_handle, desired_access,
- object_attributes, event_type, initial_state);
-}
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenEvent64(
- PHANDLE event_handle, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes) {
- NtOpenEventFunction orig_fn = reinterpret_cast<
- NtOpenEventFunction>(g_originals[OPEN_EVENT_ID]);
- return TargetNtOpenEvent(orig_fn, event_handle, desired_access,
- object_attributes);
-}
-
-// -----------------------------------------------------------------------
-
-SANDBOX_INTERCEPT BOOL WINAPI TargetGdiDllInitialize64(
- HANDLE dll,
- DWORD reason) {
- GdiDllInitializeFunction orig_fn = reinterpret_cast<
- GdiDllInitializeFunction>(g_originals[GDIINITIALIZE_ID]);
- return TargetGdiDllInitialize(orig_fn, dll, reason);
-}
-
-SANDBOX_INTERCEPT HGDIOBJ WINAPI TargetGetStockObject64(int object) {
- GetStockObjectFunction orig_fn = reinterpret_cast<
- GetStockObjectFunction>(g_originals[GETSTOCKOBJECT_ID]);
- return TargetGetStockObject(orig_fn, object);
-}
-
-SANDBOX_INTERCEPT ATOM WINAPI TargetRegisterClassW64(
- const WNDCLASS* wnd_class) {
- RegisterClassWFunction orig_fn = reinterpret_cast<
- RegisterClassWFunction>(g_originals[REGISTERCLASSW_ID]);
- return TargetRegisterClassW(orig_fn, wnd_class);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/interceptors_64.h b/security/sandbox/chromium/sandbox/win/src/interceptors_64.h
deleted file mode 100644
index 7368ceb84..000000000
--- a/security/sandbox/chromium/sandbox/win/src/interceptors_64.h
+++ /dev/null
@@ -1,175 +0,0 @@
-// 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 "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_INTERCEPTORS_64_H_
-#define SANDBOX_SRC_INTERCEPTORS_64_H_
-
-namespace sandbox {
-
-extern "C" {
-
-// Interception of NtMapViewOfSection on the child process.
-// It should never be called directly. This function provides the means to
-// detect dlls being loaded, so we can patch them if needed.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtMapViewOfSection64(
- HANDLE section, HANDLE process, PVOID *base, ULONG_PTR zero_bits,
- SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size,
- SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect);
-
-// Interception of NtUnmapViewOfSection on the child process.
-// It should never be called directly. This function provides the means to
-// detect dlls being unloaded, so we can clean up our interceptions.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtUnmapViewOfSection64(HANDLE process,
- PVOID base);
-
-// -----------------------------------------------------------------------
-// Interceptors without IPC.
-
-// Interception of NtSetInformationThread on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationThread64(
- HANDLE thread, NT_THREAD_INFORMATION_CLASS thread_info_class,
- PVOID thread_information, ULONG thread_information_bytes);
-
-// Interception of NtOpenThreadToken on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThreadToken64(
- HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self,
- PHANDLE token);
-
-// Interception of NtOpenThreadTokenEx on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThreadTokenEx64(
- HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self,
- ULONG handle_attributes, PHANDLE token);
-
-// -----------------------------------------------------------------------
-// Interceptors handled by the file system dispatcher.
-
-// Interception of NtCreateFile on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateFile64(
- PHANDLE file, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
- PLARGE_INTEGER allocation_size, ULONG file_attributes, ULONG sharing,
- ULONG disposition, ULONG options, PVOID ea_buffer, ULONG ea_length);
-
-// Interception of NtOpenFile on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenFile64(
- PHANDLE file, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status,
- ULONG sharing, ULONG options);
-
-// Interception of NtQueryAtttributesFile on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryAttributesFile64(
- POBJECT_ATTRIBUTES object_attributes,
- PFILE_BASIC_INFORMATION file_attributes);
-
-// Interception of NtQueryFullAtttributesFile on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryFullAttributesFile64(
- POBJECT_ATTRIBUTES object_attributes,
- PFILE_NETWORK_OPEN_INFORMATION file_attributes);
-
-// Interception of NtSetInformationFile on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationFile64(
- HANDLE file, PIO_STATUS_BLOCK io_status, PVOID file_information,
- ULONG length, FILE_INFORMATION_CLASS file_information_class);
-
-// -----------------------------------------------------------------------
-// Interceptors handled by the named pipe dispatcher.
-
-// Interception of CreateNamedPipeW in kernel32.dll
-SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateNamedPipeW64(
- LPCWSTR pipe_name, DWORD open_mode, DWORD pipe_mode, DWORD max_instance,
- DWORD out_buffer_size, DWORD in_buffer_size, DWORD default_timeout,
- LPSECURITY_ATTRIBUTES security_attributes);
-
-// -----------------------------------------------------------------------
-// Interceptors handled by the process-thread dispatcher.
-
-// Interception of NtOpenThread on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThread64(
- PHANDLE thread, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id);
-
-// Interception of NtOpenProcess on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcess64(
- PHANDLE process, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id);
-
-// Interception of NtOpenProcessToken on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessToken64(
- HANDLE process, ACCESS_MASK desired_access, PHANDLE token);
-
-// Interception of NtOpenProcessTokenEx on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessTokenEx64(
- HANDLE process, ACCESS_MASK desired_access, ULONG handle_attributes,
- PHANDLE token);
-
-// Interception of CreateProcessW in kernel32.dll.
-SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessW64(
- LPCWSTR application_name, LPWSTR command_line,
- LPSECURITY_ATTRIBUTES process_attributes,
- LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
- LPVOID environment, LPCWSTR current_directory, LPSTARTUPINFOW startup_info,
- LPPROCESS_INFORMATION process_information);
-
-// Interception of CreateProcessA in kernel32.dll.
-SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessA64(
- LPCSTR application_name, LPSTR command_line,
- LPSECURITY_ATTRIBUTES process_attributes,
- LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
- LPVOID environment, LPCSTR current_directory, LPSTARTUPINFOA startup_info,
- LPPROCESS_INFORMATION process_information);
-
-// -----------------------------------------------------------------------
-// Interceptors handled by the registry dispatcher.
-
-// Interception of NtCreateKey on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateKey64(
- PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, ULONG title_index,
- PUNICODE_STRING class_name, ULONG create_options, PULONG disposition);
-
-// Interception of NtOpenKey on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKey64(
- PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes);
-
-// Interception of NtOpenKeyEx on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKeyEx64(
- PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, ULONG open_options);
-
-// -----------------------------------------------------------------------
-// Interceptors handled by the sync dispatcher.
-
-// Interception of NtCreateEvent/NtOpenEvent on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateEvent64(
- PHANDLE event_handle, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, EVENT_TYPE event_type,
- BOOLEAN initial_state);
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenEvent64(
- PHANDLE event_handle, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes);
-
-// -----------------------------------------------------------------------
-// Interceptors handled by the process mitigations win32k lockdown code.
-
-// Interceptor for the GdiDllInitialize function.
-SANDBOX_INTERCEPT BOOL WINAPI TargetGdiDllInitialize64(
- HANDLE dll,
- DWORD reason);
-
-// Interceptor for the GetStockObject function.
-SANDBOX_INTERCEPT HGDIOBJ WINAPI TargetGetStockObject64(int object);
-
-// Interceptor for the RegisterClassW function.
-SANDBOX_INTERCEPT ATOM WINAPI TargetRegisterClassW64(const WNDCLASS* wnd_class);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_INTERCEPTORS_64_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/internal_types.h b/security/sandbox/chromium/sandbox/win/src/internal_types.h
deleted file mode 100644
index e1028189d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/internal_types.h
+++ /dev/null
@@ -1,76 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_WIN_SRC_INTERNAL_TYPES_H_
-#define SANDBOX_WIN_SRC_INTERNAL_TYPES_H_
-
-#include <stdint.h>
-
-namespace sandbox {
-
-const wchar_t kNtdllName[] = L"ntdll.dll";
-const wchar_t kKerneldllName[] = L"kernel32.dll";
-const wchar_t kKernelBasedllName[] = L"kernelbase.dll";
-
-// Defines the supported C++ types encoding to numeric id. Like a poor's man
-// RTTI. Note that true C++ RTTI will not work because the types are not
-// polymorphic anyway.
-enum ArgType {
- INVALID_TYPE = 0,
- WCHAR_TYPE,
- UINT32_TYPE,
- UNISTR_TYPE,
- VOIDPTR_TYPE,
- INPTR_TYPE,
- INOUTPTR_TYPE,
- LAST_TYPE
-};
-
-// Encapsulates a pointer to a buffer and the size of the buffer.
-class CountedBuffer {
- public:
- CountedBuffer(void* buffer, uint32_t size) : size_(size), buffer_(buffer) {}
-
- uint32_t Size() const { return size_; }
-
- void* Buffer() const {
- return buffer_;
- }
-
- private:
- uint32_t size_;
- void* buffer_;
-};
-
-// Helper class to convert void-pointer packed ints for both
-// 32 and 64 bit builds. This construct is non-portable.
-class IPCInt {
- public:
- explicit IPCInt(void* buffer) {
- buffer_.vp = buffer;
- }
-
- explicit IPCInt(unsigned __int32 i32) {
- buffer_.vp = NULL;
- buffer_.i32 = i32;
- }
-
- unsigned __int32 As32Bit() const {
- return buffer_.i32;
- }
-
- void* AsVoidPtr() const {
- return buffer_.vp;
- }
-
- private:
- union U {
- void* vp;
- unsigned __int32 i32;
- } buffer_;
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_WIN_SRC_INTERNAL_TYPES_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/ipc_ping_test.cc b/security/sandbox/chromium/sandbox/win/src/ipc_ping_test.cc
deleted file mode 100644
index 64e3de6c5..000000000
--- a/security/sandbox/chromium/sandbox/win/src/ipc_ping_test.cc
+++ /dev/null
@@ -1,58 +0,0 @@
-// 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 "testing/gtest/include/gtest/gtest.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/target_services.h"
-#include "sandbox/win/tests/common/controller.h"
-
-namespace sandbox {
-
-// Tests that the IPC is working by issuing a special IPC that is not exposed
-// in the public API.
-SBOX_TESTS_COMMAND int IPC_Ping(int argc, wchar_t **argv) {
- if (argc != 1)
- return SBOX_TEST_FAILED;
-
- TargetServices* ts = SandboxFactory::GetTargetServices();
- if (NULL == ts)
- return SBOX_TEST_FAILED;
-
- // Downcast because we have internal knowledge of the object returned.
- TargetServicesBase* ts_base = reinterpret_cast<TargetServicesBase*>(ts);
-
- int version = 0;
- if (L'1' == argv[0][0])
- version = 1;
- else
- version = 2;
-
- if (!ts_base->TestIPCPing(version))
- return SBOX_TEST_FAILED;
-
- ::Sleep(1);
- if (!ts_base->TestIPCPing(version))
- return SBOX_TEST_FAILED;
-
- return SBOX_TEST_SUCCEEDED;
-}
-
-// The IPC ping test should work before and after the token drop.
-TEST(IPCTest, IPCPingTestSimple) {
- TestRunner runner;
- runner.SetTimeout(2000);
- runner.SetTestState(EVERY_STATE);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"IPC_Ping 1"));
-}
-
-TEST(IPCTest, IPCPingTestWithOutput) {
- TestRunner runner;
- runner.SetTimeout(2000);
- runner.SetTestState(EVERY_STATE);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"IPC_Ping 2"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"IPC_Ping 2"));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/ipc_tags.h b/security/sandbox/chromium/sandbox/win/src/ipc_tags.h
deleted file mode 100644
index d680411da..000000000
--- a/security/sandbox/chromium/sandbox/win/src/ipc_tags.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_IPC_TAGS_H__
-#define SANDBOX_SRC_IPC_TAGS_H__
-
-namespace sandbox {
-
-enum {
- IPC_UNUSED_TAG = 0,
- IPC_PING1_TAG, // Takes a cookie in parameters and returns the cookie
- // multiplied by 2 and the tick_count. Used for testing only.
- IPC_PING2_TAG, // Takes an in/out cookie in parameters and modify the cookie
- // to be multiplied by 3. Used for testing only.
- IPC_NTCREATEFILE_TAG,
- IPC_NTOPENFILE_TAG,
- IPC_NTQUERYATTRIBUTESFILE_TAG,
- IPC_NTQUERYFULLATTRIBUTESFILE_TAG,
- IPC_NTSETINFO_RENAME_TAG,
- IPC_CREATENAMEDPIPEW_TAG,
- IPC_NTOPENTHREAD_TAG,
- IPC_NTOPENPROCESS_TAG,
- IPC_NTOPENPROCESSTOKEN_TAG,
- IPC_NTOPENPROCESSTOKENEX_TAG,
- IPC_CREATEPROCESSW_TAG,
- IPC_CREATEEVENT_TAG,
- IPC_OPENEVENT_TAG,
- IPC_NTCREATEKEY_TAG,
- IPC_NTOPENKEY_TAG,
- IPC_DUPLICATEHANDLEPROXY_TAG,
- IPC_GDI_GDIDLLINITIALIZE_TAG,
- IPC_GDI_GETSTOCKOBJECT_TAG,
- IPC_USER_REGISTERCLASSW_TAG,
- IPC_LAST_TAG
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_IPC_TAGS_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/ipc_unittest.cc b/security/sandbox/chromium/sandbox/win/src/ipc_unittest.cc
deleted file mode 100644
index c41720da3..000000000
--- a/security/sandbox/chromium/sandbox/win/src/ipc_unittest.cc
+++ /dev/null
@@ -1,632 +0,0 @@
-// 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.
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/sharedmem_ipc_server.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-// Helper function to make the fake shared memory with some
-// basic elements initialized.
-IPCControl* MakeChannels(size_t channel_size, size_t total_shared_size,
- size_t* base_start) {
- // Allocate memory
- char* mem = new char[total_shared_size];
- memset(mem, 0, total_shared_size);
- // Calculate how many channels we can fit in the shared memory.
- total_shared_size -= offsetof(IPCControl, channels);
- size_t channel_count =
- total_shared_size / (sizeof(ChannelControl) + channel_size);
- // Calculate the start of the first channel.
- *base_start = (sizeof(ChannelControl)* channel_count) +
- offsetof(IPCControl, channels);
- // Setup client structure.
- IPCControl* client_control = reinterpret_cast<IPCControl*>(mem);
- client_control->channels_count = channel_count;
- return client_control;
-}
-
-enum TestFixMode {
- FIX_NO_EVENTS,
- FIX_PONG_READY,
- FIX_PONG_NOT_READY
-};
-
-void FixChannels(IPCControl* client_control, size_t base_start,
- size_t channel_size, TestFixMode mode) {
- for (size_t ix = 0; ix != client_control->channels_count; ++ix) {
- ChannelControl& channel = client_control->channels[ix];
- channel.channel_base = base_start;
- channel.state = kFreeChannel;
- if (mode != FIX_NO_EVENTS) {
- BOOL signaled = (FIX_PONG_READY == mode)? TRUE : FALSE;
- channel.ping_event = ::CreateEventW(NULL, FALSE, FALSE, NULL);
- channel.pong_event = ::CreateEventW(NULL, FALSE, signaled, NULL);
- }
- base_start += channel_size;
- }
-}
-
-void CloseChannelEvents(IPCControl* client_control) {
- for (size_t ix = 0; ix != client_control->channels_count; ++ix) {
- ChannelControl& channel = client_control->channels[ix];
- ::CloseHandle(channel.ping_event);
- ::CloseHandle(channel.pong_event);
- }
-}
-
-TEST(IPCTest, ChannelMaker) {
- // Test that our testing rig is computing offsets properly. We should have
- // 5 channnels and the offset to the first channel is 108 bytes in 32 bits
- // and 216 in 64 bits.
- size_t channel_start = 0;
- IPCControl* client_control = MakeChannels(12 * 64, 4096, &channel_start);
- ASSERT_TRUE(NULL != client_control);
- EXPECT_EQ(5u, client_control->channels_count);
-#if defined(_WIN64)
- EXPECT_EQ(216u, channel_start);
-#else
- EXPECT_EQ(108u, channel_start);
-#endif
- delete[] reinterpret_cast<char*>(client_control);
-}
-
-TEST(IPCTest, ClientLockUnlock) {
- // Make 7 channels of kIPCChannelSize (1kb) each. Test that we lock and
- // unlock channels properly.
- size_t base_start = 0;
- IPCControl* client_control =
- MakeChannels(kIPCChannelSize, 4096 * 2, &base_start);
- FixChannels(client_control, base_start, kIPCChannelSize, FIX_NO_EVENTS);
-
- char* mem = reinterpret_cast<char*>(client_control);
- SharedMemIPCClient client(mem);
-
- // Test that we lock the first 3 channels in sequence.
- void* buff0 = client.GetBuffer();
- EXPECT_TRUE(mem + client_control->channels[0].channel_base == buff0);
- EXPECT_EQ(kBusyChannel, client_control->channels[0].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[1].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[2].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[3].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[4].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[5].state);
-
- void* buff1 = client.GetBuffer();
- EXPECT_TRUE(mem + client_control->channels[1].channel_base == buff1);
- EXPECT_EQ(kBusyChannel, client_control->channels[0].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[1].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[2].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[3].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[4].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[5].state);
-
- void* buff2 = client.GetBuffer();
- EXPECT_TRUE(mem + client_control->channels[2].channel_base == buff2);
- EXPECT_EQ(kBusyChannel, client_control->channels[0].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[1].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[2].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[3].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[4].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[5].state);
-
- // Test that we unlock and re-lock the right channel.
- client.FreeBuffer(buff1);
- EXPECT_EQ(kBusyChannel, client_control->channels[0].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[1].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[2].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[3].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[4].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[5].state);
-
- void* buff2b = client.GetBuffer();
- EXPECT_TRUE(mem + client_control->channels[1].channel_base == buff2b);
- EXPECT_EQ(kBusyChannel, client_control->channels[0].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[1].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[2].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[3].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[4].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[5].state);
-
- client.FreeBuffer(buff0);
- EXPECT_EQ(kFreeChannel, client_control->channels[0].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[1].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[2].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[3].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[4].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[5].state);
-
- delete[] reinterpret_cast<char*>(client_control);
-}
-
-TEST(IPCTest, CrossCallStrPacking) {
- // This test tries the CrossCall object with null and non-null string
- // combination of parameters, integer types and verifies that the unpacker
- // can read them properly.
- size_t base_start = 0;
- IPCControl* client_control =
- MakeChannels(kIPCChannelSize, 4096 * 4, &base_start);
- client_control->server_alive = HANDLE(1);
- FixChannels(client_control, base_start, kIPCChannelSize, FIX_PONG_READY);
-
- char* mem = reinterpret_cast<char*>(client_control);
- SharedMemIPCClient client(mem);
-
- CrossCallReturn answer;
- uint32_t tag1 = 666;
- const wchar_t *text = L"98765 - 43210";
- base::string16 copied_text;
- CrossCallParamsEx* actual_params;
-
- CrossCall(client, tag1, text, &answer);
- actual_params = reinterpret_cast<CrossCallParamsEx*>(client.GetBuffer());
- EXPECT_EQ(1u, actual_params->GetParamsCount());
- EXPECT_EQ(tag1, actual_params->GetTag());
- EXPECT_TRUE(actual_params->GetParameterStr(0, &copied_text));
- EXPECT_STREQ(text, copied_text.c_str());
-
- // Check with an empty string.
- uint32_t tag2 = 777;
- const wchar_t* null_text = NULL;
- CrossCall(client, tag2, null_text, &answer);
- actual_params = reinterpret_cast<CrossCallParamsEx*>(client.GetBuffer());
- EXPECT_EQ(1u, actual_params->GetParamsCount());
- EXPECT_EQ(tag2, actual_params->GetTag());
- uint32_t param_size = 1;
- ArgType type = INVALID_TYPE;
- void* param_addr = actual_params->GetRawParameter(0, &param_size, &type);
- EXPECT_TRUE(NULL != param_addr);
- EXPECT_EQ(0u, param_size);
- EXPECT_EQ(WCHAR_TYPE, type);
- EXPECT_TRUE(actual_params->GetParameterStr(0, &copied_text));
-
- uint32_t tag3 = 888;
- param_size = 1;
- copied_text.clear();
-
- // Check with an empty string and a non-empty string.
- CrossCall(client, tag3, null_text, text, &answer);
- actual_params = reinterpret_cast<CrossCallParamsEx*>(client.GetBuffer());
- EXPECT_EQ(2u, actual_params->GetParamsCount());
- EXPECT_EQ(tag3, actual_params->GetTag());
- type = INVALID_TYPE;
- param_addr = actual_params->GetRawParameter(0, &param_size, &type);
- EXPECT_TRUE(NULL != param_addr);
- EXPECT_EQ(0u, param_size);
- EXPECT_EQ(WCHAR_TYPE, type);
- EXPECT_TRUE(actual_params->GetParameterStr(0, &copied_text));
- EXPECT_TRUE(actual_params->GetParameterStr(1, &copied_text));
- EXPECT_STREQ(text, copied_text.c_str());
-
- param_size = 1;
- base::string16 copied_text_p0, copied_text_p2;
-
- const wchar_t *text2 = L"AeFG";
- CrossCall(client, tag1, text2, null_text, text, &answer);
- actual_params = reinterpret_cast<CrossCallParamsEx*>(client.GetBuffer());
- EXPECT_EQ(3u, actual_params->GetParamsCount());
- EXPECT_EQ(tag1, actual_params->GetTag());
- EXPECT_TRUE(actual_params->GetParameterStr(0, &copied_text_p0));
- EXPECT_STREQ(text2, copied_text_p0.c_str());
- EXPECT_TRUE(actual_params->GetParameterStr(2, &copied_text_p2));
- EXPECT_STREQ(text, copied_text_p2.c_str());
- type = INVALID_TYPE;
- param_addr = actual_params->GetRawParameter(1, &param_size, &type);
- EXPECT_TRUE(NULL != param_addr);
- EXPECT_EQ(0u, param_size);
- EXPECT_EQ(WCHAR_TYPE, type);
-
- CloseChannelEvents(client_control);
- delete[] reinterpret_cast<char*>(client_control);
-}
-
-TEST(IPCTest, CrossCallIntPacking) {
- // Check handling for regular 32 bit integers used in Windows.
- size_t base_start = 0;
- IPCControl* client_control =
- MakeChannels(kIPCChannelSize, 4096 * 4, &base_start);
- client_control->server_alive = HANDLE(1);
- FixChannels(client_control, base_start, kIPCChannelSize, FIX_PONG_READY);
-
- uint32_t tag1 = 999;
- uint32_t tag2 = 111;
- const wchar_t *text = L"godzilla";
- CrossCallParamsEx* actual_params;
-
- char* mem = reinterpret_cast<char*>(client_control);
- SharedMemIPCClient client(mem);
-
- CrossCallReturn answer;
- DWORD dw = 0xE6578;
- CrossCall(client, tag2, dw, &answer);
- actual_params = reinterpret_cast<CrossCallParamsEx*>(client.GetBuffer());
- EXPECT_EQ(1u, actual_params->GetParamsCount());
- EXPECT_EQ(tag2, actual_params->GetTag());
- ArgType type = INVALID_TYPE;
- uint32_t param_size = 1;
- void* param_addr = actual_params->GetRawParameter(0, &param_size, &type);
- ASSERT_EQ(sizeof(dw), param_size);
- EXPECT_EQ(UINT32_TYPE, type);
- ASSERT_TRUE(NULL != param_addr);
- EXPECT_EQ(0, memcmp(&dw, param_addr, param_size));
-
- // Check handling for windows HANDLES.
- HANDLE h = HANDLE(0x70000500);
- CrossCall(client, tag1, text, h, &answer);
- actual_params = reinterpret_cast<CrossCallParamsEx*>(client.GetBuffer());
- EXPECT_EQ(2u, actual_params->GetParamsCount());
- EXPECT_EQ(tag1, actual_params->GetTag());
- type = INVALID_TYPE;
- param_addr = actual_params->GetRawParameter(1, &param_size, &type);
- ASSERT_EQ(sizeof(h), param_size);
- EXPECT_EQ(VOIDPTR_TYPE, type);
- ASSERT_TRUE(NULL != param_addr);
- EXPECT_EQ(0, memcmp(&h, param_addr, param_size));
-
- // Check combination of 32 and 64 bits.
- CrossCall(client, tag2, h, dw, h, &answer);
- actual_params = reinterpret_cast<CrossCallParamsEx*>(client.GetBuffer());
- EXPECT_EQ(3u, actual_params->GetParamsCount());
- EXPECT_EQ(tag2, actual_params->GetTag());
- type = INVALID_TYPE;
- param_addr = actual_params->GetRawParameter(0, &param_size, &type);
- ASSERT_EQ(sizeof(h), param_size);
- EXPECT_EQ(VOIDPTR_TYPE, type);
- ASSERT_TRUE(NULL != param_addr);
- EXPECT_EQ(0, memcmp(&h, param_addr, param_size));
- type = INVALID_TYPE;
- param_addr = actual_params->GetRawParameter(1, &param_size, &type);
- ASSERT_EQ(sizeof(dw), param_size);
- EXPECT_EQ(UINT32_TYPE, type);
- ASSERT_TRUE(NULL != param_addr);
- EXPECT_EQ(0, memcmp(&dw, param_addr, param_size));
- type = INVALID_TYPE;
- param_addr = actual_params->GetRawParameter(2, &param_size, &type);
- ASSERT_EQ(sizeof(h), param_size);
- EXPECT_EQ(VOIDPTR_TYPE, type);
- ASSERT_TRUE(NULL != param_addr);
- EXPECT_EQ(0, memcmp(&h, param_addr, param_size));
-
- CloseChannelEvents(client_control);
- delete[] reinterpret_cast<char*>(client_control);
-}
-
-TEST(IPCTest, CrossCallValidation) {
- // First a sanity test with a well formed parameter object.
- unsigned long value = 124816;
- const uint32_t kTag = 33;
- const uint32_t kBufferSize = 256;
- ActualCallParams<1, kBufferSize> params_1(kTag);
- params_1.CopyParamIn(0, &value, sizeof(value), false, UINT32_TYPE);
- void* buffer = const_cast<void*>(params_1.GetBuffer());
-
- uint32_t out_size = 0;
- CrossCallParamsEx* ccp = 0;
- ccp = CrossCallParamsEx::CreateFromBuffer(buffer, params_1.GetSize(),
- &out_size);
- ASSERT_TRUE(NULL != ccp);
- EXPECT_TRUE(ccp->GetBuffer() != buffer);
- EXPECT_EQ(kTag, ccp->GetTag());
- EXPECT_EQ(1u, ccp->GetParamsCount());
- delete[] (reinterpret_cast<char*>(ccp));
-
- // Test that we handle integer overflow on the number of params
- // correctly. We use a test-only ctor for ActualCallParams that
- // allows to create malformed cross-call buffers.
- const int32_t kPtrDiffSz = sizeof(ptrdiff_t);
- for (int32_t ix = -1; ix != 3; ++ix) {
- uint32_t fake_num_params = (UINT32_MAX / kPtrDiffSz) + ix;
- ActualCallParams<1, kBufferSize> params_2(kTag, fake_num_params);
- params_2.CopyParamIn(0, &value, sizeof(value), false, UINT32_TYPE);
- buffer = const_cast<void*>(params_2.GetBuffer());
-
- EXPECT_TRUE(NULL != buffer);
- ccp = CrossCallParamsEx::CreateFromBuffer(buffer, params_1.GetSize(),
- &out_size);
- // If the buffer is malformed the return is NULL.
- EXPECT_TRUE(NULL == ccp);
- }
-
- ActualCallParams<1, kBufferSize> params_3(kTag, 1);
- params_3.CopyParamIn(0, &value, sizeof(value), false, UINT32_TYPE);
- buffer = const_cast<void*>(params_3.GetBuffer());
- EXPECT_TRUE(NULL != buffer);
-
- uint32_t correct_size = params_3.OverrideSize(1);
- ccp = CrossCallParamsEx::CreateFromBuffer(buffer, kBufferSize, &out_size);
- EXPECT_TRUE(NULL == ccp);
-
- // The correct_size is 8 bytes aligned.
- params_3.OverrideSize(correct_size - 7);
- ccp = CrossCallParamsEx::CreateFromBuffer(buffer, kBufferSize, &out_size);
- EXPECT_TRUE(NULL == ccp);
-
- params_3.OverrideSize(correct_size);
- ccp = CrossCallParamsEx::CreateFromBuffer(buffer, kBufferSize, &out_size);
- EXPECT_TRUE(NULL != ccp);
-
- // Make sure that two parameters work as expected.
- ActualCallParams<2, kBufferSize> params_4(kTag, 2);
- params_4.CopyParamIn(0, &value, sizeof(value), false, UINT32_TYPE);
- params_4.CopyParamIn(1, buffer, sizeof(buffer), false, VOIDPTR_TYPE);
- buffer = const_cast<void*>(params_4.GetBuffer());
- EXPECT_TRUE(NULL != buffer);
-
- ccp = CrossCallParamsEx::CreateFromBuffer(buffer, kBufferSize, &out_size);
- EXPECT_TRUE(NULL != ccp);
-
-#if defined(_WIN64)
- correct_size = params_4.OverrideSize(1);
- params_4.OverrideSize(correct_size - 1);
- ccp = CrossCallParamsEx::CreateFromBuffer(buffer, kBufferSize, &out_size);
- EXPECT_TRUE(NULL == ccp);
-#endif
-}
-
-// This structure is passed to the mock server threads to simulate
-// the server side IPC so it has the required kernel objects.
-struct ServerEvents {
- HANDLE ping;
- HANDLE pong;
- volatile LONG* state;
- HANDLE mutex;
-};
-
-// This is the server thread that quicky answers an IPC and exits.
-DWORD WINAPI QuickResponseServer(PVOID param) {
- ServerEvents* events = reinterpret_cast<ServerEvents*>(param);
- DWORD wait_result = 0;
- wait_result = ::WaitForSingleObject(events->ping, INFINITE);
- ::InterlockedExchange(events->state, kAckChannel);
- ::SetEvent(events->pong);
- return wait_result;
-}
-
-class CrossCallParamsMock : public CrossCallParams {
- public:
- CrossCallParamsMock(uint32_t tag, uint32_t params_count)
- : CrossCallParams(tag, params_count) {}
-};
-
-void FakeOkAnswerInChannel(void* channel) {
- CrossCallReturn* answer = reinterpret_cast<CrossCallReturn*>(channel);
- answer->call_outcome = SBOX_ALL_OK;
-}
-
-// Create two threads that will quickly answer IPCs; the first one
-// using channel 1 (channel 0 is busy) and one using channel 0. No time-out
-// should occur.
-TEST(IPCTest, ClientFastServer) {
- const size_t channel_size = kIPCChannelSize;
- size_t base_start = 0;
- IPCControl* client_control =
- MakeChannels(channel_size, 4096 * 2, &base_start);
- FixChannels(client_control, base_start, kIPCChannelSize, FIX_PONG_NOT_READY);
- client_control->server_alive = ::CreateMutex(NULL, FALSE, NULL);
-
- char* mem = reinterpret_cast<char*>(client_control);
- SharedMemIPCClient client(mem);
-
- ServerEvents events = {0};
- events.ping = client_control->channels[1].ping_event;
- events.pong = client_control->channels[1].pong_event;
- events.state = &client_control->channels[1].state;
-
- HANDLE t1 = ::CreateThread(NULL, 0, QuickResponseServer, &events, 0, NULL);
- ASSERT_TRUE(NULL != t1);
- ::CloseHandle(t1);
-
- void* buff0 = client.GetBuffer();
- EXPECT_TRUE(mem + client_control->channels[0].channel_base == buff0);
- EXPECT_EQ(kBusyChannel, client_control->channels[0].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[1].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[2].state);
-
- void* buff1 = client.GetBuffer();
- EXPECT_TRUE(mem + client_control->channels[1].channel_base == buff1);
- EXPECT_EQ(kBusyChannel, client_control->channels[0].state);
- EXPECT_EQ(kBusyChannel, client_control->channels[1].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[2].state);
-
- EXPECT_EQ(0u, client_control->channels[1].ipc_tag);
-
- uint32_t tag = 7654;
- CrossCallReturn answer;
- CrossCallParamsMock* params1 = new(buff1) CrossCallParamsMock(tag, 1);
- FakeOkAnswerInChannel(buff1);
-
- ResultCode result = client.DoCall(params1, &answer);
- if (SBOX_ERROR_CHANNEL_ERROR != result)
- client.FreeBuffer(buff1);
-
- EXPECT_TRUE(SBOX_ALL_OK == result);
- EXPECT_EQ(tag, client_control->channels[1].ipc_tag);
- EXPECT_EQ(kBusyChannel, client_control->channels[0].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[1].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[2].state);
-
- HANDLE t2 = ::CreateThread(NULL, 0, QuickResponseServer, &events, 0, NULL);
- ASSERT_TRUE(NULL != t2);
- ::CloseHandle(t2);
-
- client.FreeBuffer(buff0);
- events.ping = client_control->channels[0].ping_event;
- events.pong = client_control->channels[0].pong_event;
- events.state = &client_control->channels[0].state;
-
- tag = 4567;
- CrossCallParamsMock* params2 = new(buff0) CrossCallParamsMock(tag, 1);
- FakeOkAnswerInChannel(buff0);
-
- result = client.DoCall(params2, &answer);
- if (SBOX_ERROR_CHANNEL_ERROR != result)
- client.FreeBuffer(buff0);
-
- EXPECT_TRUE(SBOX_ALL_OK == result);
- EXPECT_EQ(tag, client_control->channels[0].ipc_tag);
- EXPECT_EQ(kFreeChannel, client_control->channels[0].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[1].state);
- EXPECT_EQ(kFreeChannel, client_control->channels[2].state);
-
- CloseChannelEvents(client_control);
- ::CloseHandle(client_control->server_alive);
-
- delete[] reinterpret_cast<char*>(client_control);
-}
-
-// This is the server thread that very slowly answers an IPC and exits. Note
-// that the pong event needs to be signaled twice.
-DWORD WINAPI SlowResponseServer(PVOID param) {
- ServerEvents* events = reinterpret_cast<ServerEvents*>(param);
- DWORD wait_result = 0;
- wait_result = ::WaitForSingleObject(events->ping, INFINITE);
- ::Sleep(kIPCWaitTimeOut1 + kIPCWaitTimeOut2 + 200);
- ::InterlockedExchange(events->state, kAckChannel);
- ::SetEvent(events->pong);
- return wait_result;
-}
-
-// This thread's job is to keep the mutex locked.
-DWORD WINAPI MainServerThread(PVOID param) {
- ServerEvents* events = reinterpret_cast<ServerEvents*>(param);
- DWORD wait_result = 0;
- wait_result = ::WaitForSingleObject(events->mutex, INFINITE);
- Sleep(kIPCWaitTimeOut1 * 20);
- return wait_result;
-}
-
-// Creates a server thread that answers the IPC so slow that is guaranteed to
-// trigger the time-out code path in the client. A second thread is created
-// to hold locked the server_alive mutex: this signals the client that the
-// server is not dead and it retries the wait.
-TEST(IPCTest, ClientSlowServer) {
- size_t base_start = 0;
- IPCControl* client_control =
- MakeChannels(kIPCChannelSize, 4096*2, &base_start);
- FixChannels(client_control, base_start, kIPCChannelSize, FIX_PONG_NOT_READY);
- client_control->server_alive = ::CreateMutex(NULL, FALSE, NULL);
-
- char* mem = reinterpret_cast<char*>(client_control);
- SharedMemIPCClient client(mem);
-
- ServerEvents events = {0};
- events.ping = client_control->channels[0].ping_event;
- events.pong = client_control->channels[0].pong_event;
- events.state = &client_control->channels[0].state;
-
- HANDLE t1 = ::CreateThread(NULL, 0, SlowResponseServer, &events, 0, NULL);
- ASSERT_TRUE(NULL != t1);
- ::CloseHandle(t1);
-
- ServerEvents events2 = {0};
- events2.pong = events.pong;
- events2.mutex = client_control->server_alive;
-
- HANDLE t2 = ::CreateThread(NULL, 0, MainServerThread, &events2, 0, NULL);
- ASSERT_TRUE(NULL != t2);
- ::CloseHandle(t2);
-
- ::Sleep(1);
-
- void* buff0 = client.GetBuffer();
- uint32_t tag = 4321;
- CrossCallReturn answer;
- CrossCallParamsMock* params1 = new(buff0) CrossCallParamsMock(tag, 1);
- FakeOkAnswerInChannel(buff0);
-
- ResultCode result = client.DoCall(params1, &answer);
- if (SBOX_ERROR_CHANNEL_ERROR != result)
- client.FreeBuffer(buff0);
-
- EXPECT_TRUE(SBOX_ALL_OK == result);
- EXPECT_EQ(tag, client_control->channels[0].ipc_tag);
- EXPECT_EQ(kFreeChannel, client_control->channels[0].state);
-
- CloseChannelEvents(client_control);
- ::CloseHandle(client_control->server_alive);
- delete[] reinterpret_cast<char*>(client_control);
-}
-
-// This test-only IPC dispatcher has two handlers with the same signature
-// but only CallOneHandler should be used.
-class UnitTestIPCDispatcher : public Dispatcher {
- public:
- enum {
- CALL_ONE_TAG = 78,
- CALL_TWO_TAG = 87
- };
-
- UnitTestIPCDispatcher();
- ~UnitTestIPCDispatcher() override{};
-
- bool SetupService(InterceptionManager* manager, int service) override {
- return true;
- }
-
- private:
- bool CallOneHandler(IPCInfo* ipc, HANDLE p1, uint32_t p2) {
- ipc->return_info.extended[0].handle = p1;
- ipc->return_info.extended[1].unsigned_int = p2;
- return true;
- }
-
- bool CallTwoHandler(IPCInfo* ipc, HANDLE p1, uint32_t p2) { return true; }
-};
-
-UnitTestIPCDispatcher::UnitTestIPCDispatcher() {
- static const IPCCall call_one = {{CALL_ONE_TAG, {VOIDPTR_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &UnitTestIPCDispatcher::CallOneHandler)};
- static const IPCCall call_two = {{CALL_TWO_TAG, {VOIDPTR_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &UnitTestIPCDispatcher::CallTwoHandler)};
- ipc_calls_.push_back(call_one);
- ipc_calls_.push_back(call_two);
-}
-
-// This test does most of the shared memory IPC client-server roundtrip
-// and tests the packing, unpacking and call dispatching.
-TEST(IPCTest, SharedMemServerTests) {
- size_t base_start = 0;
- IPCControl* client_control =
- MakeChannels(kIPCChannelSize, 4096, &base_start);
- client_control->server_alive = HANDLE(1);
- FixChannels(client_control, base_start, kIPCChannelSize, FIX_PONG_READY);
-
- char* mem = reinterpret_cast<char*>(client_control);
- SharedMemIPCClient client(mem);
-
- CrossCallReturn answer;
- HANDLE bar = HANDLE(191919);
- DWORD foo = 6767676;
- CrossCall(client, UnitTestIPCDispatcher::CALL_ONE_TAG, bar, foo, &answer);
- void* buff = client.GetBuffer();
- ASSERT_TRUE(NULL != buff);
-
- UnitTestIPCDispatcher dispatcher;
- // Since we are directly calling InvokeCallback, most of this structure
- // can be set to NULL.
- sandbox::SharedMemIPCServer::ServerControl srv_control = {};
- srv_control.channel_size = kIPCChannelSize;
- srv_control.shared_base = reinterpret_cast<char*>(client_control);
- srv_control.dispatcher = &dispatcher;
-
- sandbox::CrossCallReturn call_return = {0};
- EXPECT_TRUE(SharedMemIPCServer::InvokeCallback(&srv_control, buff,
- &call_return));
- EXPECT_EQ(SBOX_ALL_OK, call_return.call_outcome);
- EXPECT_TRUE(bar == call_return.extended[0].handle);
- EXPECT_EQ(foo, call_return.extended[1].unsigned_int);
-
- CloseChannelEvents(client_control);
- delete[] reinterpret_cast<char*>(client_control);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/job.cc b/security/sandbox/chromium/sandbox/win/src/job.cc
deleted file mode 100644
index adf392ddd..000000000
--- a/security/sandbox/chromium/sandbox/win/src/job.cc
+++ /dev/null
@@ -1,119 +0,0 @@
-// 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 "sandbox/win/src/job.h"
-
-#include <stddef.h>
-
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/restricted_token.h"
-
-namespace sandbox {
-
-Job::Job() : job_handle_(NULL) {
-};
-
-Job::~Job() {
-};
-
-DWORD Job::Init(JobLevel security_level,
- const wchar_t* job_name,
- DWORD ui_exceptions,
- size_t memory_limit) {
- if (job_handle_.IsValid())
- return ERROR_ALREADY_INITIALIZED;
-
- job_handle_.Set(::CreateJobObject(NULL, // No security attribute
- job_name));
- if (!job_handle_.IsValid())
- return ::GetLastError();
-
- JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = {};
- JOBOBJECT_BASIC_UI_RESTRICTIONS jbur = {};
-
- // Set the settings for the different security levels. Note: The higher levels
- // inherit from the lower levels.
- switch (security_level) {
- case JOB_LOCKDOWN: {
- jeli.BasicLimitInformation.LimitFlags |=
- JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
- }
- case JOB_RESTRICTED: {
- jbur.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_WRITECLIPBOARD;
- jbur.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_READCLIPBOARD;
- jbur.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_HANDLES;
- jbur.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_GLOBALATOMS;
- }
- case JOB_LIMITED_USER: {
- jbur.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_DISPLAYSETTINGS;
- jeli.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
- jeli.BasicLimitInformation.ActiveProcessLimit = 1;
- }
- case JOB_INTERACTIVE: {
- jbur.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS;
- jbur.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_DESKTOP;
- jbur.UIRestrictionsClass |= JOB_OBJECT_UILIMIT_EXITWINDOWS;
- }
- case JOB_UNPROTECTED: {
- if (memory_limit) {
- jeli.BasicLimitInformation.LimitFlags |=
- JOB_OBJECT_LIMIT_PROCESS_MEMORY;
- jeli.ProcessMemoryLimit = memory_limit;
- }
-
- jeli.BasicLimitInformation.LimitFlags |=
- JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
- break;
- }
- default: {
- return ERROR_BAD_ARGUMENTS;
- }
- }
-
- if (FALSE == ::SetInformationJobObject(job_handle_.Get(),
- JobObjectExtendedLimitInformation,
- &jeli,
- sizeof(jeli))) {
- return ::GetLastError();
- }
-
- jbur.UIRestrictionsClass = jbur.UIRestrictionsClass & (~ui_exceptions);
- if (FALSE == ::SetInformationJobObject(job_handle_.Get(),
- JobObjectBasicUIRestrictions,
- &jbur,
- sizeof(jbur))) {
- return ::GetLastError();
- }
-
- return ERROR_SUCCESS;
-}
-
-DWORD Job::UserHandleGrantAccess(HANDLE handle) {
- if (!job_handle_.IsValid())
- return ERROR_NO_DATA;
-
- if (!::UserHandleGrantAccess(handle,
- job_handle_.Get(),
- TRUE)) { // Access allowed.
- return ::GetLastError();
- }
-
- return ERROR_SUCCESS;
-}
-
-base::win::ScopedHandle Job::Take() {
- return job_handle_.Pass();
-}
-
-DWORD Job::AssignProcessToJob(HANDLE process_handle) {
- if (!job_handle_.IsValid())
- return ERROR_NO_DATA;
-
- if (FALSE == ::AssignProcessToJobObject(job_handle_.Get(), process_handle))
- return ::GetLastError();
-
- return ERROR_SUCCESS;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/job.h b/security/sandbox/chromium/sandbox/win/src/job.h
deleted file mode 100644
index ad3dd41f2..000000000
--- a/security/sandbox/chromium/sandbox/win/src/job.h
+++ /dev/null
@@ -1,67 +0,0 @@
-// 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 SANDBOX_SRC_JOB_H_
-#define SANDBOX_SRC_JOB_H_
-
-#include <stddef.h>
-
-#include "base/macros.h"
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/restricted_token_utils.h"
-
-namespace sandbox {
-
-// Handles the creation of job objects based on a security profile.
-// Sample usage:
-// Job job;
-// job.Init(JOB_LOCKDOWN, NULL); //no job name
-// job.AssignProcessToJob(process_handle);
-class Job {
- public:
- Job();
-
- ~Job();
-
- // Initializes and creates the job object. The security of the job is based
- // on the security_level parameter.
- // job_name can be NULL if the job is unnamed.
- // If the chosen profile has too many ui restrictions, you can disable some
- // by specifying them in the ui_exceptions parameters.
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- DWORD Init(JobLevel security_level,
- const wchar_t* job_name,
- DWORD ui_exceptions,
- size_t memory_limit);
-
- // Assigns the process referenced by process_handle to the job.
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- DWORD AssignProcessToJob(HANDLE process_handle);
-
- // Grants access to "handle" to the job. All processes in the job can
- // subsequently recognize and use the handle.
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- DWORD UserHandleGrantAccess(HANDLE handle);
-
- // Revokes ownership to the job handle and returns it.
- // If the object is not yet initialized, it returns an invalid handle.
- base::win::ScopedHandle Take();
-
- private:
- // Handle to the job referenced by the object.
- base::win::ScopedHandle job_handle_;
-
- DISALLOW_COPY_AND_ASSIGN(Job);
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_JOB_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/job_unittest.cc b/security/sandbox/chromium/sandbox/win/src/job_unittest.cc
deleted file mode 100644
index 7ed9cf0d7..000000000
--- a/security/sandbox/chromium/sandbox/win/src/job_unittest.cc
+++ /dev/null
@@ -1,204 +0,0 @@
-// 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 file contains unit tests for the job object.
-
-#include "base/win/scoped_process_information.h"
-#include "sandbox/win/src/job.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-// Tests the creation and destruction of the job.
-TEST(JobTest, TestCreation) {
- // Scope the creation of Job.
- {
- // Create the job.
- Job job;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job.Init(JOB_LOCKDOWN, L"my_test_job_name", 0, 0));
-
- // check if the job exists.
- HANDLE job_handle = ::OpenJobObjectW(GENERIC_ALL, FALSE,
- L"my_test_job_name");
- ASSERT_TRUE(job_handle != NULL);
-
- if (job_handle)
- CloseHandle(job_handle);
- }
-
- // Check if the job is destroyed when the object goes out of scope.
- HANDLE job_handle = ::OpenJobObjectW(GENERIC_ALL, FALSE, L"my_test_job_name");
- ASSERT_TRUE(job_handle == NULL);
- ASSERT_EQ(static_cast<DWORD>(ERROR_FILE_NOT_FOUND), ::GetLastError());
-}
-
-// Tests the method "Take".
-TEST(JobTest, Take) {
- base::win::ScopedHandle job_handle;
- // Scope the creation of Job.
- {
- // Create the job.
- Job job;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job.Init(JOB_LOCKDOWN, L"my_test_job_name", 0, 0));
-
- job_handle = job.Take();
- ASSERT_TRUE(job_handle.IsValid());
- }
-
- // Check to be sure that the job is still alive even after the object is gone
- // out of scope.
- HANDLE job_handle_dup = ::OpenJobObjectW(GENERIC_ALL, FALSE,
- L"my_test_job_name");
- ASSERT_TRUE(job_handle_dup != NULL);
-
- // Remove all references.
- if (job_handle_dup)
- ::CloseHandle(job_handle_dup);
-
- job_handle.Close();
-
- // Check if the jbo is really dead.
- job_handle_dup = ::OpenJobObjectW(GENERIC_ALL, FALSE, L"my_test_job_name");
- ASSERT_TRUE(job_handle_dup == NULL);
- ASSERT_EQ(static_cast<DWORD>(ERROR_FILE_NOT_FOUND), ::GetLastError());
-}
-
-// Tests the ui exceptions
-TEST(JobTest, TestExceptions) {
- base::win::ScopedHandle job_handle;
- // Scope the creation of Job.
- {
- // Create the job.
- Job job;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job.Init(JOB_LOCKDOWN, L"my_test_job_name",
- JOB_OBJECT_UILIMIT_READCLIPBOARD, 0));
-
- job_handle = job.Take();
- ASSERT_TRUE(job_handle.IsValid());
-
- JOBOBJECT_BASIC_UI_RESTRICTIONS jbur = {0};
- DWORD size = sizeof(jbur);
- BOOL result = ::QueryInformationJobObject(job_handle.Get(),
- JobObjectBasicUIRestrictions,
- &jbur, size, &size);
- ASSERT_TRUE(result);
-
- ASSERT_EQ(0u, jbur.UIRestrictionsClass & JOB_OBJECT_UILIMIT_READCLIPBOARD);
- job_handle.Close();
- }
-
- // Scope the creation of Job.
- {
- // Create the job.
- Job job;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job.Init(JOB_LOCKDOWN, L"my_test_job_name", 0, 0));
-
- job_handle = job.Take();
- ASSERT_TRUE(job_handle.IsValid());
-
- JOBOBJECT_BASIC_UI_RESTRICTIONS jbur = {0};
- DWORD size = sizeof(jbur);
- BOOL result = ::QueryInformationJobObject(job_handle.Get(),
- JobObjectBasicUIRestrictions,
- &jbur, size, &size);
- ASSERT_TRUE(result);
-
- ASSERT_EQ(static_cast<DWORD>(JOB_OBJECT_UILIMIT_READCLIPBOARD),
- jbur.UIRestrictionsClass & JOB_OBJECT_UILIMIT_READCLIPBOARD);
- }
-}
-
-// Tests the error case when the job is initialized twice.
-TEST(JobTest, DoubleInit) {
- // Create the job.
- Job job;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job.Init(JOB_LOCKDOWN, L"my_test_job_name", 0, 0));
- ASSERT_EQ(static_cast<DWORD>(ERROR_ALREADY_INITIALIZED),
- job.Init(JOB_LOCKDOWN, L"test", 0, 0));
-}
-
-// Tests the error case when we use a method and the object is not yet
-// initialized.
-TEST(JobTest, NoInit) {
- Job job;
- ASSERT_EQ(static_cast<DWORD>(ERROR_NO_DATA), job.UserHandleGrantAccess(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_NO_DATA), job.AssignProcessToJob(NULL));
- ASSERT_FALSE(job.Take().IsValid());
-}
-
-// Tests the initialization of the job with different security level.
-TEST(JobTest, SecurityLevel) {
- Job job1;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job1.Init(JOB_LOCKDOWN, L"job1", 0, 0));
-
- Job job2;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job2.Init(JOB_RESTRICTED, L"job2", 0, 0));
-
- Job job3;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job3.Init(JOB_LIMITED_USER, L"job3", 0, 0));
-
- Job job4;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job4.Init(JOB_INTERACTIVE, L"job4", 0, 0));
-
- Job job5;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job5.Init(JOB_UNPROTECTED, L"job5", 0, 0));
-
- // JOB_NONE means we run without a job object so Init should fail.
- Job job6;
- ASSERT_EQ(static_cast<DWORD>(ERROR_BAD_ARGUMENTS),
- job6.Init(JOB_NONE, L"job6", 0, 0));
-
- Job job7;
- ASSERT_EQ(static_cast<DWORD>(ERROR_BAD_ARGUMENTS),
- job7.Init(static_cast<JobLevel>(JOB_NONE + 1), L"job7", 0, 0));
-}
-
-// Tests the method "AssignProcessToJob".
-TEST(JobTest, ProcessInJob) {
- // Create the job.
- Job job;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job.Init(JOB_UNPROTECTED, L"job_test_process", 0, 0));
-
- BOOL result = FALSE;
-
- wchar_t notepad[] = L"notepad";
- STARTUPINFO si = { sizeof(si) };
- PROCESS_INFORMATION temp_process_info = {};
- result = ::CreateProcess(NULL, notepad, NULL, NULL, FALSE, 0, NULL, NULL, &si,
- &temp_process_info);
- ASSERT_TRUE(result);
- base::win::ScopedProcessInformation pi(temp_process_info);
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- job.AssignProcessToJob(pi.process_handle()));
-
- // Get the job handle.
- base::win::ScopedHandle job_handle = job.Take();
-
- // Check if the process is in the job.
- JOBOBJECT_BASIC_PROCESS_ID_LIST jbpidl = {0};
- DWORD size = sizeof(jbpidl);
- result = ::QueryInformationJobObject(job_handle.Get(),
- JobObjectBasicProcessIdList,
- &jbpidl, size, &size);
- EXPECT_TRUE(result);
-
- EXPECT_EQ(1u, jbpidl.NumberOfAssignedProcesses);
- EXPECT_EQ(1u, jbpidl.NumberOfProcessIdsInList);
- EXPECT_EQ(pi.process_id(), jbpidl.ProcessIdList[0]);
-
- EXPECT_TRUE(::TerminateProcess(pi.process_handle(), 0));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/named_pipe_dispatcher.cc b/security/sandbox/chromium/sandbox/win/src/named_pipe_dispatcher.cc
deleted file mode 100644
index ea8d38035..000000000
--- a/security/sandbox/chromium/sandbox/win/src/named_pipe_dispatcher.cc
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright (c) 2013 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 "sandbox/win/src/named_pipe_dispatcher.h"
-
-#include <stdint.h>
-
-#include "base/strings/string_split.h"
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/named_pipe_interception.h"
-#include "sandbox/win/src/named_pipe_policy.h"
-#include "sandbox/win/src/policy_broker.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox.h"
-
-
-namespace sandbox {
-
-NamedPipeDispatcher::NamedPipeDispatcher(PolicyBase* policy_base)
- : policy_base_(policy_base) {
- static const IPCCall create_params = {
- {IPC_CREATENAMEDPIPEW_TAG,
- {WCHAR_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(&NamedPipeDispatcher::CreateNamedPipe)};
-
- ipc_calls_.push_back(create_params);
-}
-
-bool NamedPipeDispatcher::SetupService(InterceptionManager* manager,
- int service) {
- if (IPC_CREATENAMEDPIPEW_TAG == service)
- return INTERCEPT_EAT(manager, kKerneldllName, CreateNamedPipeW,
- CREATE_NAMED_PIPE_ID, 36);
-
- return false;
-}
-
-bool NamedPipeDispatcher::CreateNamedPipe(IPCInfo* ipc,
- base::string16* name,
- uint32_t open_mode,
- uint32_t pipe_mode,
- uint32_t max_instances,
- uint32_t out_buffer_size,
- uint32_t in_buffer_size,
- uint32_t default_timeout) {
- ipc->return_info.win32_result = ERROR_ACCESS_DENIED;
- ipc->return_info.handle = INVALID_HANDLE_VALUE;
-
- base::StringPiece16 dotdot(L"..");
-
- for (const base::StringPiece16& path : base::SplitStringPiece(
- *name, base::string16(1, '/'),
- base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
- for (const base::StringPiece16& inner : base::SplitStringPiece(
- path, base::string16(1, '\\'),
- base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
- if (inner == dotdot)
- return true;
- }
- }
-
- const wchar_t* pipe_name = name->c_str();
- CountedParameterSet<NameBased> params;
- params[NameBased::NAME] = ParamPickerMake(pipe_name);
-
- EvalResult eval = policy_base_->EvalPolicy(IPC_CREATENAMEDPIPEW_TAG,
- params.GetBase());
-
- // "For file I/O, the "\\?\" prefix to a path string tells the Windows APIs to
- // disable all string parsing and to send the string that follows it straight
- // to the file system."
- // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
- // This ensures even if there is a path traversal in the pipe name, and it is
- // able to get past the checks above, it will still not be allowed to escape
- // our whitelisted namespace.
- if (name->compare(0, 4, L"\\\\.\\") == 0)
- name->replace(0, 4, L"\\\\\?\\");
-
- HANDLE pipe;
- DWORD ret = NamedPipePolicy::CreateNamedPipeAction(eval, *ipc->client_info,
- *name, open_mode,
- pipe_mode, max_instances,
- out_buffer_size,
- in_buffer_size,
- default_timeout, &pipe);
-
- ipc->return_info.win32_result = ret;
- ipc->return_info.handle = pipe;
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/named_pipe_dispatcher.h b/security/sandbox/chromium/sandbox/win/src/named_pipe_dispatcher.h
deleted file mode 100644
index 83f45e093..000000000
--- a/security/sandbox/chromium/sandbox/win/src/named_pipe_dispatcher.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// 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 SANDBOX_SRC_NAMED_PIPE_DISPATCHER_H__
-#define SANDBOX_SRC_NAMED_PIPE_DISPATCHER_H__
-
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-namespace sandbox {
-
-// This class handles named pipe related IPC calls.
-class NamedPipeDispatcher : public Dispatcher {
- public:
- explicit NamedPipeDispatcher(PolicyBase* policy_base);
- ~NamedPipeDispatcher() override {}
-
- // Dispatcher interface.
- bool SetupService(InterceptionManager* manager, int service) override;
-
- private:
- // Processes IPC requests coming from calls to CreateNamedPipeW() in the
- // target.
- bool CreateNamedPipe(IPCInfo* ipc,
- base::string16* name,
- uint32_t open_mode,
- uint32_t pipe_mode,
- uint32_t max_instances,
- uint32_t out_buffer_size,
- uint32_t in_buffer_size,
- uint32_t default_timeout);
-
- PolicyBase* policy_base_;
- DISALLOW_COPY_AND_ASSIGN(NamedPipeDispatcher);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_NAMED_PIPE_DISPATCHER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.cc b/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.cc
deleted file mode 100644
index a18327308..000000000
--- a/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-// 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 "sandbox/win/src/named_pipe_interception.h"
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/policy_target.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/target_services.h"
-#include "mozilla/sandboxing/sandboxLogging.h"
-
-namespace sandbox {
-
-HANDLE WINAPI TargetCreateNamedPipeW(
- CreateNamedPipeWFunction orig_CreateNamedPipeW, LPCWSTR pipe_name,
- DWORD open_mode, DWORD pipe_mode, DWORD max_instance, DWORD out_buffer_size,
- DWORD in_buffer_size, DWORD default_timeout,
- LPSECURITY_ATTRIBUTES security_attributes) {
- HANDLE pipe = orig_CreateNamedPipeW(pipe_name, open_mode, pipe_mode,
- max_instance, out_buffer_size,
- in_buffer_size, default_timeout,
- security_attributes);
- if (INVALID_HANDLE_VALUE != pipe)
- return pipe;
-
- mozilla::sandboxing::LogBlocked("CreateNamedPipeW", pipe_name);
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return INVALID_HANDLE_VALUE;
-
- DWORD original_error = ::GetLastError();
-
- // We don't support specific Security Attributes.
- if (security_attributes)
- return INVALID_HANDLE_VALUE;
-
- do {
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- CountedParameterSet<NameBased> params;
- params[NameBased::NAME] = ParamPickerMake(pipe_name);
-
- if (!QueryBroker(IPC_CREATENAMEDPIPEW_TAG, params.GetBase()))
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_CREATENAMEDPIPEW_TAG, pipe_name,
- open_mode, pipe_mode, max_instance,
- out_buffer_size, in_buffer_size,
- default_timeout, &answer);
- if (SBOX_ALL_OK != code)
- break;
-
- ::SetLastError(answer.win32_result);
-
- if (ERROR_SUCCESS != answer.win32_result)
- return INVALID_HANDLE_VALUE;
-
- mozilla::sandboxing::LogAllowed("CreateNamedPipeW", pipe_name);
- return answer.handle;
- } while (false);
-
- ::SetLastError(original_error);
- return INVALID_HANDLE_VALUE;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.h b/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.h
deleted file mode 100644
index fdbee1976..000000000
--- a/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.h
+++ /dev/null
@@ -1,36 +0,0 @@
-// 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 "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_NAMED_PIPE_INTERCEPTION_H__
-#define SANDBOX_SRC_NAMED_PIPE_INTERCEPTION_H__
-
-namespace sandbox {
-
-extern "C" {
-
-typedef HANDLE (WINAPI *CreateNamedPipeWFunction) (
- LPCWSTR lpName,
- DWORD dwOpenMode,
- DWORD dwPipeMode,
- DWORD nMaxInstances,
- DWORD nOutBufferSize,
- DWORD nInBufferSize,
- DWORD nDefaultTimeOut,
- LPSECURITY_ATTRIBUTES lpSecurityAttributes);
-
-// Interception of CreateNamedPipeW in kernel32.dll
-SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateNamedPipeW(
- CreateNamedPipeWFunction orig_CreateNamedPipeW, LPCWSTR pipe_name,
- DWORD open_mode, DWORD pipe_mode, DWORD max_instance, DWORD out_buffer_size,
- DWORD in_buffer_size, DWORD default_timeout,
- LPSECURITY_ATTRIBUTES security_attributes);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_NAMED_PIPE_INTERCEPTION_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/named_pipe_policy.cc b/security/sandbox/chromium/sandbox/win/src/named_pipe_policy.cc
deleted file mode 100644
index eee719e50..000000000
--- a/security/sandbox/chromium/sandbox/win/src/named_pipe_policy.cc
+++ /dev/null
@@ -1,86 +0,0 @@
-// 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 "sandbox/win/src/named_pipe_policy.h"
-
-#include <string>
-
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace {
-
-// Creates a named pipe and duplicates the handle to 'target_process'. The
-// remaining parameters are the same as CreateNamedPipeW().
-HANDLE CreateNamedPipeHelper(HANDLE target_process, LPCWSTR pipe_name,
- DWORD open_mode, DWORD pipe_mode,
- DWORD max_instances, DWORD out_buffer_size,
- DWORD in_buffer_size, DWORD default_timeout,
- LPSECURITY_ATTRIBUTES security_attributes) {
- HANDLE pipe = ::CreateNamedPipeW(pipe_name, open_mode, pipe_mode,
- max_instances, out_buffer_size,
- in_buffer_size, default_timeout,
- security_attributes);
- if (INVALID_HANDLE_VALUE == pipe)
- return pipe;
-
- HANDLE new_pipe;
- if (!::DuplicateHandle(::GetCurrentProcess(), pipe,
- target_process, &new_pipe,
- 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return INVALID_HANDLE_VALUE;
- }
-
- return new_pipe;
-}
-
-} // namespace
-
-namespace sandbox {
-
-bool NamedPipePolicy::GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy) {
- if (TargetPolicy::NAMEDPIPES_ALLOW_ANY != semantics) {
- return false;
- }
- PolicyRule pipe(ASK_BROKER);
- if (!pipe.AddStringMatch(IF, NameBased::NAME, name, CASE_INSENSITIVE)) {
- return false;
- }
- if (!policy->AddRule(IPC_CREATENAMEDPIPEW_TAG, &pipe)) {
- return false;
- }
- return true;
-}
-
-DWORD NamedPipePolicy::CreateNamedPipeAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16 &name,
- DWORD open_mode, DWORD pipe_mode,
- DWORD max_instances,
- DWORD out_buffer_size,
- DWORD in_buffer_size,
- DWORD default_timeout,
- HANDLE* pipe) {
- // The only action supported is ASK_BROKER which means create the pipe.
- if (ASK_BROKER != eval_result) {
- return ERROR_ACCESS_DENIED;
- }
-
- *pipe = CreateNamedPipeHelper(client_info.process, name.c_str(),
- open_mode, pipe_mode, max_instances,
- out_buffer_size, in_buffer_size,
- default_timeout, NULL);
-
- if (INVALID_HANDLE_VALUE == *pipe)
- return ERROR_ACCESS_DENIED;
-
- return ERROR_SUCCESS;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/named_pipe_policy.h b/security/sandbox/chromium/sandbox/win/src/named_pipe_policy.h
deleted file mode 100644
index 02aa26c61..000000000
--- a/security/sandbox/chromium/sandbox/win/src/named_pipe_policy.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// 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 SANDBOX_SRC_NAMED_PIPE_POLICY_H__
-#define SANDBOX_SRC_NAMED_PIPE_POLICY_H__
-
-#include <string>
-
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/sandbox_policy.h"
-
-namespace sandbox {
-
-enum EvalResult;
-
-// This class centralizes most of the knowledge related to named pipe creation.
-class NamedPipePolicy {
- public:
- // Creates the required low-level policy rules to evaluate a high-level.
- // policy rule for named pipe creation
- // 'name' is the named pipe to be created
- // 'semantics' is the desired semantics.
- // 'policy' is the policy generator to which the rules are going to be added.
- static bool GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy);
-
- // Processes a 'CreateNamedPipeW()' request from the target.
- static DWORD CreateNamedPipeAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16 &name,
- DWORD open_mode, DWORD pipe_mode,
- DWORD max_instances,
- DWORD out_buffer_size,
- DWORD in_buffer_size,
- DWORD default_timeout, HANDLE* pipe);
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_NAMED_PIPE_POLICY_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/named_pipe_policy_test.cc b/security/sandbox/chromium/sandbox/win/src/named_pipe_policy_test.cc
deleted file mode 100644
index 813cf1f46..000000000
--- a/security/sandbox/chromium/sandbox/win/src/named_pipe_policy_test.cc
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright (c) 2014 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/windows_version.h"
-#include "sandbox/win/src/handle_closer.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-
-SBOX_TESTS_COMMAND int NamedPipe_Create(int argc, wchar_t **argv) {
- if (argc < 1 || argc > 2) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- if ((NULL == argv) || (NULL == argv[0])) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
-
- HANDLE pipe = ::CreateNamedPipeW(argv[0],
- PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
- PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 4096,
- 4096, 2000, NULL);
- if (INVALID_HANDLE_VALUE == pipe)
- return SBOX_TEST_DENIED;
-
- // The second parameter allows us to enforce a whitelist for where the
- // pipe should be in the object namespace after creation.
- if (argc == 2) {
- base::string16 handle_name;
- if (GetHandleName(pipe, &handle_name)) {
- if (handle_name.compare(0, wcslen(argv[1]), argv[1]) != 0)
- return SBOX_TEST_FAILED;
- } else {
- return SBOX_TEST_FAILED;
- }
- }
-
- OVERLAPPED overlapped = {0};
- overlapped.hEvent = ::CreateEvent(NULL, TRUE, TRUE, NULL);
- BOOL result = ::ConnectNamedPipe(pipe, &overlapped);
-
- if (!result) {
- DWORD error = ::GetLastError();
- if (ERROR_PIPE_CONNECTED != error &&
- ERROR_IO_PENDING != error) {
- return SBOX_TEST_FAILED;
- }
- }
-
- if (!::CloseHandle(pipe))
- return SBOX_TEST_FAILED;
-
- ::CloseHandle(overlapped.hEvent);
- return SBOX_TEST_SUCCEEDED;
-}
-
-// Tests if we can create a pipe in the sandbox.
-TEST(NamedPipePolicyTest, CreatePipe) {
- TestRunner runner;
- // TODO(nsylvain): This policy is wrong because "*" is a valid char in a
- // namedpipe name. Here we apply it like a wildcard. http://b/893603
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_NAMED_PIPES,
- TargetPolicy::NAMEDPIPES_ALLOW_ANY,
- L"\\\\.\\pipe\\test*"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"NamedPipe_Create \\\\.\\pipe\\testbleh"));
-
- // On XP, the sandbox can create a pipe without any help but it fails on
- // Vista+, this is why we do not test the "denied" case.
- if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_VISTA) {
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"NamedPipe_Create \\\\.\\pipe\\bleh"));
- }
-}
-
-// Tests if we can create a pipe with a path traversal in the sandbox.
-TEST(NamedPipePolicyTest, CreatePipeTraversal) {
- TestRunner runner;
- // TODO(nsylvain): This policy is wrong because "*" is a valid char in a
- // namedpipe name. Here we apply it like a wildcard. http://b/893603
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_NAMED_PIPES,
- TargetPolicy::NAMEDPIPES_ALLOW_ANY,
- L"\\\\.\\pipe\\test*"));
-
- // On XP, the sandbox can create a pipe without any help but it fails on
- // Vista+, this is why we do not test the "denied" case.
- if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_VISTA) {
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"NamedPipe_Create \\\\.\\pipe\\test\\..\\bleh"));
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"NamedPipe_Create \\\\.\\pipe\\test/../bleh"));
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"NamedPipe_Create \\\\.\\pipe\\test\\../bleh"));
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"NamedPipe_Create \\\\.\\pipe\\test/..\\bleh"));
- }
-}
-
-// This tests that path canonicalization is actually disabled if we use \\?\
-// syntax.
-TEST(NamedPipePolicyTest, CreatePipeCanonicalization) {
- // "For file I/O, the "\\?\" prefix to a path string tells the Windows APIs to
- // disable all string parsing and to send the string that follows it straight
- // to the file system."
- // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
- const wchar_t* argv[2] = { L"\\\\?\\pipe\\test\\..\\bleh",
- L"\\Device\\NamedPipe\\test" };
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- NamedPipe_Create(2, const_cast<wchar_t**>(argv)));
-}
-
-// The same test as CreatePipe but this time using strict interceptions.
-TEST(NamedPipePolicyTest, CreatePipeStrictInterceptions) {
- TestRunner runner;
- runner.GetPolicy()->SetStrictInterceptions();
-
- // TODO(nsylvain): This policy is wrong because "*" is a valid char in a
- // namedpipe name. Here we apply it like a wildcard. http://b/893603
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_NAMED_PIPES,
- TargetPolicy::NAMEDPIPES_ALLOW_ANY,
- L"\\\\.\\pipe\\test*"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"NamedPipe_Create \\\\.\\pipe\\testbleh"));
-
- // On XP, the sandbox can create a pipe without any help but it fails on
- // Vista+, this is why we do not test the "denied" case.
- if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_VISTA) {
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"NamedPipe_Create \\\\.\\pipe\\bleh"));
- }
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/nt_internals.h b/security/sandbox/chromium/sandbox/win/src/nt_internals.h
deleted file mode 100644
index 2a39d5b94..000000000
--- a/security/sandbox/chromium/sandbox/win/src/nt_internals.h
+++ /dev/null
@@ -1,703 +0,0 @@
-// Copyright 2013 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 holds definitions related to the ntdll API.
-
-#ifndef SANDBOX_WIN_SRC_NT_INTERNALS_H__
-#define SANDBOX_WIN_SRC_NT_INTERNALS_H__
-
-#include <windows.h>
-#include <stddef.h>
-
-typedef LONG NTSTATUS;
-#define NT_SUCCESS(st) (st >= 0)
-
-#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
-#define STATUS_BUFFER_OVERFLOW ((NTSTATUS)0x80000005L)
-#define STATUS_UNSUCCESSFUL ((NTSTATUS)0xC0000001L)
-#define STATUS_NOT_IMPLEMENTED ((NTSTATUS)0xC0000002L)
-#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
-#ifndef STATUS_INVALID_PARAMETER
-// It is now defined in Windows 2008 SDK.
-#define STATUS_INVALID_PARAMETER ((NTSTATUS)0xC000000DL)
-#endif
-#define STATUS_CONFLICTING_ADDRESSES ((NTSTATUS)0xC0000018L)
-#define STATUS_ACCESS_DENIED ((NTSTATUS)0xC0000022L)
-#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L)
-#define STATUS_OBJECT_NAME_NOT_FOUND ((NTSTATUS)0xC0000034L)
-#define STATUS_OBJECT_NAME_COLLISION ((NTSTATUS)0xC0000035L)
-#define STATUS_PROCEDURE_NOT_FOUND ((NTSTATUS)0xC000007AL)
-#define STATUS_INVALID_IMAGE_FORMAT ((NTSTATUS)0xC000007BL)
-#define STATUS_NO_TOKEN ((NTSTATUS)0xC000007CL)
-
-#define CURRENT_PROCESS ((HANDLE) -1)
-#define CURRENT_THREAD ((HANDLE) -2)
-#define NtCurrentProcess CURRENT_PROCESS
-
-typedef struct _UNICODE_STRING {
- USHORT Length;
- USHORT MaximumLength;
- PWSTR Buffer;
-} UNICODE_STRING;
-typedef UNICODE_STRING *PUNICODE_STRING;
-typedef const UNICODE_STRING *PCUNICODE_STRING;
-
-typedef struct _STRING {
- USHORT Length;
- USHORT MaximumLength;
- PCHAR Buffer;
-} STRING;
-typedef STRING *PSTRING;
-
-typedef STRING ANSI_STRING;
-typedef PSTRING PANSI_STRING;
-typedef CONST PSTRING PCANSI_STRING;
-
-typedef STRING OEM_STRING;
-typedef PSTRING POEM_STRING;
-typedef CONST STRING* PCOEM_STRING;
-
-#define OBJ_CASE_INSENSITIVE 0x00000040L
-#define OBJ_OPENIF 0x00000080L
-
-typedef struct _OBJECT_ATTRIBUTES {
- ULONG Length;
- HANDLE RootDirectory;
- PUNICODE_STRING ObjectName;
- ULONG Attributes;
- PVOID SecurityDescriptor;
- PVOID SecurityQualityOfService;
-} OBJECT_ATTRIBUTES;
-typedef OBJECT_ATTRIBUTES *POBJECT_ATTRIBUTES;
-
-#define InitializeObjectAttributes(p, n, a, r, s) { \
- (p)->Length = sizeof(OBJECT_ATTRIBUTES);\
- (p)->RootDirectory = r;\
- (p)->Attributes = a;\
- (p)->ObjectName = n;\
- (p)->SecurityDescriptor = s;\
- (p)->SecurityQualityOfService = NULL;\
-}
-
-typedef struct _IO_STATUS_BLOCK {
- union {
- NTSTATUS Status;
- PVOID Pointer;
- };
- ULONG_PTR Information;
-} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
-
-// -----------------------------------------------------------------------
-// File IO
-
-// Create disposition values.
-
-#define FILE_SUPERSEDE 0x00000000
-#define FILE_OPEN 0x00000001
-#define FILE_CREATE 0x00000002
-#define FILE_OPEN_IF 0x00000003
-#define FILE_OVERWRITE 0x00000004
-#define FILE_OVERWRITE_IF 0x00000005
-#define FILE_MAXIMUM_DISPOSITION 0x00000005
-
-// Create/open option flags.
-
-#define FILE_DIRECTORY_FILE 0x00000001
-#define FILE_WRITE_THROUGH 0x00000002
-#define FILE_SEQUENTIAL_ONLY 0x00000004
-#define FILE_NO_INTERMEDIATE_BUFFERING 0x00000008
-
-#define FILE_SYNCHRONOUS_IO_ALERT 0x00000010
-#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020
-#define FILE_NON_DIRECTORY_FILE 0x00000040
-#define FILE_CREATE_TREE_CONNECTION 0x00000080
-
-#define FILE_COMPLETE_IF_OPLOCKED 0x00000100
-#define FILE_NO_EA_KNOWLEDGE 0x00000200
-#define FILE_OPEN_REMOTE_INSTANCE 0x00000400
-#define FILE_RANDOM_ACCESS 0x00000800
-
-#define FILE_DELETE_ON_CLOSE 0x00001000
-#define FILE_OPEN_BY_FILE_ID 0x00002000
-#define FILE_OPEN_FOR_BACKUP_INTENT 0x00004000
-#define FILE_NO_COMPRESSION 0x00008000
-
-#define FILE_RESERVE_OPFILTER 0x00100000
-#define FILE_OPEN_REPARSE_POINT 0x00200000
-#define FILE_OPEN_NO_RECALL 0x00400000
-#define FILE_OPEN_FOR_FREE_SPACE_QUERY 0x00800000
-
-// Create/open result values. These are the disposition values returned on the
-// io status information.
-#define FILE_SUPERSEDED 0x00000000
-#define FILE_OPENED 0x00000001
-#define FILE_CREATED 0x00000002
-#define FILE_OVERWRITTEN 0x00000003
-#define FILE_EXISTS 0x00000004
-#define FILE_DOES_NOT_EXIST 0x00000005
-
-typedef NTSTATUS (WINAPI *NtCreateFileFunction)(
- OUT PHANDLE FileHandle,
- IN ACCESS_MASK DesiredAccess,
- IN POBJECT_ATTRIBUTES ObjectAttributes,
- OUT PIO_STATUS_BLOCK IoStatusBlock,
- IN PLARGE_INTEGER AllocationSize OPTIONAL,
- IN ULONG FileAttributes,
- IN ULONG ShareAccess,
- IN ULONG CreateDisposition,
- IN ULONG CreateOptions,
- IN PVOID EaBuffer OPTIONAL,
- IN ULONG EaLength);
-
-typedef NTSTATUS (WINAPI *NtOpenFileFunction)(
- OUT PHANDLE FileHandle,
- IN ACCESS_MASK DesiredAccess,
- IN POBJECT_ATTRIBUTES ObjectAttributes,
- OUT PIO_STATUS_BLOCK IoStatusBlock,
- IN ULONG ShareAccess,
- IN ULONG OpenOptions);
-
-typedef NTSTATUS (WINAPI *NtCloseFunction)(
- IN HANDLE Handle);
-
-typedef enum _FILE_INFORMATION_CLASS {
- FileRenameInformation = 10
-} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS;
-
-typedef struct _FILE_RENAME_INFORMATION {
- BOOLEAN ReplaceIfExists;
- HANDLE RootDirectory;
- ULONG FileNameLength;
- WCHAR FileName[1];
-} FILE_RENAME_INFORMATION, *PFILE_RENAME_INFORMATION;
-
-typedef NTSTATUS (WINAPI *NtSetInformationFileFunction)(
- IN HANDLE FileHandle,
- OUT PIO_STATUS_BLOCK IoStatusBlock,
- IN PVOID FileInformation,
- IN ULONG Length,
- IN FILE_INFORMATION_CLASS FileInformationClass);
-
-typedef struct FILE_BASIC_INFORMATION {
- LARGE_INTEGER CreationTime;
- LARGE_INTEGER LastAccessTime;
- LARGE_INTEGER LastWriteTime;
- LARGE_INTEGER ChangeTime;
- ULONG FileAttributes;
-} FILE_BASIC_INFORMATION, *PFILE_BASIC_INFORMATION;
-
-typedef NTSTATUS (WINAPI *NtQueryAttributesFileFunction)(
- IN POBJECT_ATTRIBUTES ObjectAttributes,
- OUT PFILE_BASIC_INFORMATION FileAttributes);
-
-typedef struct _FILE_NETWORK_OPEN_INFORMATION {
- LARGE_INTEGER CreationTime;
- LARGE_INTEGER LastAccessTime;
- LARGE_INTEGER LastWriteTime;
- LARGE_INTEGER ChangeTime;
- LARGE_INTEGER AllocationSize;
- LARGE_INTEGER EndOfFile;
- ULONG FileAttributes;
-} FILE_NETWORK_OPEN_INFORMATION, *PFILE_NETWORK_OPEN_INFORMATION;
-
-typedef NTSTATUS (WINAPI *NtQueryFullAttributesFileFunction)(
- IN POBJECT_ATTRIBUTES ObjectAttributes,
- OUT PFILE_NETWORK_OPEN_INFORMATION FileAttributes);
-
-// -----------------------------------------------------------------------
-// Sections
-
-typedef NTSTATUS (WINAPI *NtCreateSectionFunction)(
- OUT PHANDLE SectionHandle,
- IN ACCESS_MASK DesiredAccess,
- IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
- IN PLARGE_INTEGER MaximumSize OPTIONAL,
- IN ULONG SectionPageProtection,
- IN ULONG AllocationAttributes,
- IN HANDLE FileHandle OPTIONAL);
-
-typedef ULONG SECTION_INHERIT;
-#define ViewShare 1
-#define ViewUnmap 2
-
-typedef NTSTATUS (WINAPI *NtMapViewOfSectionFunction)(
- IN HANDLE SectionHandle,
- IN HANDLE ProcessHandle,
- IN OUT PVOID *BaseAddress,
- IN ULONG_PTR ZeroBits,
- IN SIZE_T CommitSize,
- IN OUT PLARGE_INTEGER SectionOffset OPTIONAL,
- IN OUT PSIZE_T ViewSize,
- IN SECTION_INHERIT InheritDisposition,
- IN ULONG AllocationType,
- IN ULONG Win32Protect);
-
-typedef NTSTATUS (WINAPI *NtUnmapViewOfSectionFunction)(
- IN HANDLE ProcessHandle,
- IN PVOID BaseAddress);
-
-typedef enum _SECTION_INFORMATION_CLASS {
- SectionBasicInformation = 0,
- SectionImageInformation
-} SECTION_INFORMATION_CLASS;
-
-typedef struct _SECTION_BASIC_INFORMATION {
- PVOID BaseAddress;
- ULONG Attributes;
- LARGE_INTEGER Size;
-} SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION;
-
-typedef NTSTATUS (WINAPI *NtQuerySectionFunction)(
- IN HANDLE SectionHandle,
- IN SECTION_INFORMATION_CLASS SectionInformationClass,
- OUT PVOID SectionInformation,
- IN SIZE_T SectionInformationLength,
- OUT PSIZE_T ReturnLength OPTIONAL);
-
-// -----------------------------------------------------------------------
-// Process and Thread
-
-typedef struct _CLIENT_ID {
- PVOID UniqueProcess;
- PVOID UniqueThread;
-} CLIENT_ID, *PCLIENT_ID;
-
-typedef NTSTATUS (WINAPI *NtOpenThreadFunction) (
- OUT PHANDLE ThreadHandle,
- IN ACCESS_MASK DesiredAccess,
- IN POBJECT_ATTRIBUTES ObjectAttributes,
- IN PCLIENT_ID ClientId);
-
-typedef NTSTATUS (WINAPI *NtOpenProcessFunction) (
- OUT PHANDLE ProcessHandle,
- IN ACCESS_MASK DesiredAccess,
- IN POBJECT_ATTRIBUTES ObjectAttributes,
- IN PCLIENT_ID ClientId);
-
-typedef enum _NT_THREAD_INFORMATION_CLASS {
- ThreadBasicInformation,
- ThreadTimes,
- ThreadPriority,
- ThreadBasePriority,
- ThreadAffinityMask,
- ThreadImpersonationToken,
- ThreadDescriptorTableEntry,
- ThreadEnableAlignmentFaultFixup,
- ThreadEventPair,
- ThreadQuerySetWin32StartAddress,
- ThreadZeroTlsCell,
- ThreadPerformanceCount,
- ThreadAmILastThread,
- ThreadIdealProcessor,
- ThreadPriorityBoost,
- ThreadSetTlsArrayAddress,
- ThreadIsIoPending,
- ThreadHideFromDebugger
-} NT_THREAD_INFORMATION_CLASS, *PNT_THREAD_INFORMATION_CLASS;
-
-typedef NTSTATUS (WINAPI *NtSetInformationThreadFunction) (
- IN HANDLE ThreadHandle,
- IN NT_THREAD_INFORMATION_CLASS ThreadInformationClass,
- IN PVOID ThreadInformation,
- IN ULONG ThreadInformationLength);
-
-// Partial definition only:
-typedef enum _PROCESSINFOCLASS {
- ProcessBasicInformation = 0,
- ProcessExecuteFlags = 0x22
-} PROCESSINFOCLASS;
-
-typedef PVOID PPEB;
-typedef LONG KPRIORITY;
-
-typedef struct _PROCESS_BASIC_INFORMATION {
- union {
- NTSTATUS ExitStatus;
- PVOID padding_for_x64_0;
- };
- PPEB PebBaseAddress;
- KAFFINITY AffinityMask;
- union {
- KPRIORITY BasePriority;
- PVOID padding_for_x64_1;
- };
- union {
- DWORD UniqueProcessId;
- PVOID padding_for_x64_2;
- };
- union {
- DWORD InheritedFromUniqueProcessId;
- PVOID padding_for_x64_3;
- };
-} PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;
-
-typedef NTSTATUS (WINAPI *NtQueryInformationProcessFunction)(
- IN HANDLE ProcessHandle,
- IN PROCESSINFOCLASS ProcessInformationClass,
- OUT PVOID ProcessInformation,
- IN ULONG ProcessInformationLength,
- OUT PULONG ReturnLength OPTIONAL);
-
-typedef NTSTATUS (WINAPI *NtSetInformationProcessFunction)(
- HANDLE ProcessHandle,
- IN PROCESSINFOCLASS ProcessInformationClass,
- IN PVOID ProcessInformation,
- IN ULONG ProcessInformationLength);
-
-typedef NTSTATUS (WINAPI *NtOpenThreadTokenFunction) (
- IN HANDLE ThreadHandle,
- IN ACCESS_MASK DesiredAccess,
- IN BOOLEAN OpenAsSelf,
- OUT PHANDLE TokenHandle);
-
-typedef NTSTATUS (WINAPI *NtOpenThreadTokenExFunction) (
- IN HANDLE ThreadHandle,
- IN ACCESS_MASK DesiredAccess,
- IN BOOLEAN OpenAsSelf,
- IN ULONG HandleAttributes,
- OUT PHANDLE TokenHandle);
-
-typedef NTSTATUS (WINAPI *NtOpenProcessTokenFunction) (
- IN HANDLE ProcessHandle,
- IN ACCESS_MASK DesiredAccess,
- OUT PHANDLE TokenHandle);
-
-typedef NTSTATUS (WINAPI *NtOpenProcessTokenExFunction) (
- IN HANDLE ProcessHandle,
- IN ACCESS_MASK DesiredAccess,
- IN ULONG HandleAttributes,
- OUT PHANDLE TokenHandle);
-
-typedef NTSTATUS (WINAPI * RtlCreateUserThreadFunction)(
- IN HANDLE Process,
- IN PSECURITY_DESCRIPTOR ThreadSecurityDescriptor,
- IN BOOLEAN CreateSuspended,
- IN ULONG ZeroBits,
- IN SIZE_T MaximumStackSize,
- IN SIZE_T CommittedStackSize,
- IN LPTHREAD_START_ROUTINE StartAddress,
- IN PVOID Parameter,
- OUT PHANDLE Thread,
- OUT PCLIENT_ID ClientId);
-
-// -----------------------------------------------------------------------
-// Registry
-
-typedef NTSTATUS (WINAPI *NtCreateKeyFunction)(
- OUT PHANDLE KeyHandle,
- IN ACCESS_MASK DesiredAccess,
- IN POBJECT_ATTRIBUTES ObjectAttributes,
- IN ULONG TitleIndex,
- IN PUNICODE_STRING Class OPTIONAL,
- IN ULONG CreateOptions,
- OUT PULONG Disposition OPTIONAL);
-
-typedef NTSTATUS (WINAPI *NtOpenKeyFunction)(
- OUT PHANDLE KeyHandle,
- IN ACCESS_MASK DesiredAccess,
- IN POBJECT_ATTRIBUTES ObjectAttributes);
-
-typedef NTSTATUS (WINAPI *NtOpenKeyExFunction)(
- OUT PHANDLE KeyHandle,
- IN ACCESS_MASK DesiredAccess,
- IN POBJECT_ATTRIBUTES ObjectAttributes,
- IN DWORD open_options);
-
-typedef NTSTATUS (WINAPI *NtDeleteKeyFunction)(
- IN HANDLE KeyHandle);
-
-// -----------------------------------------------------------------------
-// Memory
-
-// Don't really need this structure right now.
-typedef PVOID PRTL_HEAP_PARAMETERS;
-
-typedef PVOID (WINAPI *RtlCreateHeapFunction)(
- IN ULONG Flags,
- IN PVOID HeapBase OPTIONAL,
- IN SIZE_T ReserveSize OPTIONAL,
- IN SIZE_T CommitSize OPTIONAL,
- IN PVOID Lock OPTIONAL,
- IN PRTL_HEAP_PARAMETERS Parameters OPTIONAL);
-
-typedef PVOID (WINAPI *RtlDestroyHeapFunction)(
- IN PVOID HeapHandle);
-
-typedef PVOID (WINAPI *RtlAllocateHeapFunction)(
- IN PVOID HeapHandle,
- IN ULONG Flags,
- IN SIZE_T Size);
-
-typedef BOOLEAN (WINAPI *RtlFreeHeapFunction)(
- IN PVOID HeapHandle,
- IN ULONG Flags,
- IN PVOID HeapBase);
-
-typedef NTSTATUS (WINAPI *NtAllocateVirtualMemoryFunction) (
- IN HANDLE ProcessHandle,
- IN OUT PVOID *BaseAddress,
- IN ULONG_PTR ZeroBits,
- IN OUT PSIZE_T RegionSize,
- IN ULONG AllocationType,
- IN ULONG Protect);
-
-typedef NTSTATUS (WINAPI *NtFreeVirtualMemoryFunction) (
- IN HANDLE ProcessHandle,
- IN OUT PVOID *BaseAddress,
- IN OUT PSIZE_T RegionSize,
- IN ULONG FreeType);
-
-typedef enum _MEMORY_INFORMATION_CLASS {
- MemoryBasicInformation = 0,
- MemoryWorkingSetList,
- MemorySectionName,
- MemoryBasicVlmInformation
-} MEMORY_INFORMATION_CLASS;
-
-typedef struct _MEMORY_SECTION_NAME { // Information Class 2
- UNICODE_STRING SectionFileName;
-} MEMORY_SECTION_NAME, *PMEMORY_SECTION_NAME;
-
-typedef NTSTATUS (WINAPI *NtQueryVirtualMemoryFunction)(
- IN HANDLE ProcessHandle,
- IN PVOID BaseAddress,
- IN MEMORY_INFORMATION_CLASS MemoryInformationClass,
- OUT PVOID MemoryInformation,
- IN SIZE_T MemoryInformationLength,
- OUT PSIZE_T ReturnLength OPTIONAL);
-
-typedef NTSTATUS (WINAPI *NtProtectVirtualMemoryFunction)(
- IN HANDLE ProcessHandle,
- IN OUT PVOID* BaseAddress,
- IN OUT PSIZE_T ProtectSize,
- IN ULONG NewProtect,
- OUT PULONG OldProtect);
-
-// -----------------------------------------------------------------------
-// Objects
-
-typedef enum _OBJECT_INFORMATION_CLASS {
- ObjectBasicInformation,
- ObjectNameInformation,
- ObjectTypeInformation,
- ObjectAllInformation,
- ObjectDataInformation
-} OBJECT_INFORMATION_CLASS, *POBJECT_INFORMATION_CLASS;
-
-typedef struct _OBJDIR_INFORMATION {
- UNICODE_STRING ObjectName;
- UNICODE_STRING ObjectTypeName;
- BYTE Data[1];
-} OBJDIR_INFORMATION;
-
-typedef struct _PUBLIC_OBJECT_BASIC_INFORMATION {
- ULONG Attributes;
- ACCESS_MASK GrantedAccess;
- ULONG HandleCount;
- ULONG PointerCount;
- ULONG Reserved[10]; // reserved for internal use
-} PUBLIC_OBJECT_BASIC_INFORMATION, *PPUBLIC_OBJECT_BASIC_INFORMATION;
-
-typedef struct __PUBLIC_OBJECT_TYPE_INFORMATION {
- UNICODE_STRING TypeName;
- ULONG Reserved[22]; // reserved for internal use
-} PUBLIC_OBJECT_TYPE_INFORMATION, *PPUBLIC_OBJECT_TYPE_INFORMATION;
-
-typedef enum _POOL_TYPE {
- NonPagedPool,
- PagedPool,
- NonPagedPoolMustSucceed,
- ReservedType,
- NonPagedPoolCacheAligned,
- PagedPoolCacheAligned,
- NonPagedPoolCacheAlignedMustS
-} POOL_TYPE;
-
-typedef struct _OBJECT_BASIC_INFORMATION {
- ULONG Attributes;
- ACCESS_MASK GrantedAccess;
- ULONG HandleCount;
- ULONG PointerCount;
- ULONG PagedPoolUsage;
- ULONG NonPagedPoolUsage;
- ULONG Reserved[3];
- ULONG NameInformationLength;
- ULONG TypeInformationLength;
- ULONG SecurityDescriptorLength;
- LARGE_INTEGER CreateTime;
-} OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION;
-
-typedef struct _OBJECT_TYPE_INFORMATION {
- UNICODE_STRING Name;
- ULONG TotalNumberOfObjects;
- ULONG TotalNumberOfHandles;
- ULONG TotalPagedPoolUsage;
- ULONG TotalNonPagedPoolUsage;
- ULONG TotalNamePoolUsage;
- ULONG TotalHandleTableUsage;
- ULONG HighWaterNumberOfObjects;
- ULONG HighWaterNumberOfHandles;
- ULONG HighWaterPagedPoolUsage;
- ULONG HighWaterNonPagedPoolUsage;
- ULONG HighWaterNamePoolUsage;
- ULONG HighWaterHandleTableUsage;
- ULONG InvalidAttributes;
- GENERIC_MAPPING GenericMapping;
- ULONG ValidAccess;
- BOOLEAN SecurityRequired;
- BOOLEAN MaintainHandleCount;
- USHORT MaintainTypeList;
- POOL_TYPE PoolType;
- ULONG PagedPoolUsage;
- ULONG NonPagedPoolUsage;
-} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;
-
-typedef enum _SYSTEM_INFORMATION_CLASS {
- SystemHandleInformation = 16
-} SYSTEM_INFORMATION_CLASS;
-
-typedef struct _SYSTEM_HANDLE_INFORMATION {
- USHORT ProcessId;
- USHORT CreatorBackTraceIndex;
- UCHAR ObjectTypeNumber;
- UCHAR Flags;
- USHORT Handle;
- PVOID Object;
- ACCESS_MASK GrantedAccess;
-} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
-
-typedef struct _SYSTEM_HANDLE_INFORMATION_EX {
- ULONG NumberOfHandles;
- SYSTEM_HANDLE_INFORMATION Information[1];
-} SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX;
-
-typedef struct _OBJECT_NAME_INFORMATION {
- UNICODE_STRING ObjectName;
-} OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION;
-
-typedef NTSTATUS (WINAPI *NtQueryObjectFunction)(
- IN HANDLE Handle,
- IN OBJECT_INFORMATION_CLASS ObjectInformationClass,
- OUT PVOID ObjectInformation OPTIONAL,
- IN ULONG ObjectInformationLength,
- OUT PULONG ReturnLength OPTIONAL);
-
-typedef NTSTATUS (WINAPI *NtDuplicateObjectFunction)(
- IN HANDLE SourceProcess,
- IN HANDLE SourceHandle,
- IN HANDLE TargetProcess,
- OUT PHANDLE TargetHandle,
- IN ACCESS_MASK DesiredAccess,
- IN ULONG Attributes,
- IN ULONG Options);
-
-typedef NTSTATUS (WINAPI *NtSignalAndWaitForSingleObjectFunction)(
- IN HANDLE HandleToSignal,
- IN HANDLE HandleToWait,
- IN BOOLEAN Alertable,
- IN PLARGE_INTEGER Timeout OPTIONAL);
-
-typedef NTSTATUS (WINAPI *NtQuerySystemInformation)(
- IN SYSTEM_INFORMATION_CLASS SystemInformationClass,
- OUT PVOID SystemInformation,
- IN ULONG SystemInformationLength,
- OUT PULONG ReturnLength);
-
-typedef NTSTATUS (WINAPI *NtQueryObject)(
- IN HANDLE Handle,
- IN OBJECT_INFORMATION_CLASS ObjectInformationClass,
- OUT PVOID ObjectInformation,
- IN ULONG ObjectInformationLength,
- OUT PULONG ReturnLength);
-
-// -----------------------------------------------------------------------
-// Strings
-
-typedef int (__cdecl *_strnicmpFunction)(
- IN const char* _Str1,
- IN const char* _Str2,
- IN size_t _MaxCount);
-
-typedef size_t (__cdecl *strlenFunction)(
- IN const char * _Str);
-
-typedef size_t (__cdecl *wcslenFunction)(
- IN const wchar_t* _Str);
-
-typedef void* (__cdecl *memcpyFunction)(
- IN void* dest,
- IN const void* src,
- IN size_t count);
-
-typedef NTSTATUS (WINAPI *RtlAnsiStringToUnicodeStringFunction)(
- IN OUT PUNICODE_STRING DestinationString,
- IN PANSI_STRING SourceString,
- IN BOOLEAN AllocateDestinationString);
-
-typedef LONG (WINAPI *RtlCompareUnicodeStringFunction)(
- IN PCUNICODE_STRING String1,
- IN PCUNICODE_STRING String2,
- IN BOOLEAN CaseInSensitive);
-
-typedef VOID (WINAPI *RtlInitUnicodeStringFunction) (
- IN OUT PUNICODE_STRING DestinationString,
- IN PCWSTR SourceString);
-
-typedef enum _EVENT_TYPE {
- NotificationEvent,
- SynchronizationEvent
-} EVENT_TYPE, *PEVENT_TYPE;
-
-typedef NTSTATUS (WINAPI* NtCreateDirectoryObjectFunction) (
- PHANDLE DirectoryHandle,
- ACCESS_MASK DesiredAccess,
- POBJECT_ATTRIBUTES ObjectAttributes);
-
-typedef NTSTATUS (WINAPI* NtOpenDirectoryObjectFunction) (
- PHANDLE DirectoryHandle,
- ACCESS_MASK DesiredAccess,
- POBJECT_ATTRIBUTES ObjectAttributes);
-
-typedef NTSTATUS (WINAPI* NtQuerySymbolicLinkObjectFunction) (
- HANDLE LinkHandle,
- PUNICODE_STRING LinkTarget,
- PULONG ReturnedLength);
-
-typedef NTSTATUS (WINAPI* NtOpenSymbolicLinkObjectFunction) (
- PHANDLE LinkHandle,
- ACCESS_MASK DesiredAccess,
- POBJECT_ATTRIBUTES ObjectAttributes);
-
-#define DIRECTORY_QUERY 0x0001
-#define DIRECTORY_TRAVERSE 0x0002
-#define DIRECTORY_CREATE_OBJECT 0x0004
-#define DIRECTORY_CREATE_SUBDIRECTORY 0x0008
-#define DIRECTORY_ALL_ACCESS 0x000F
-
-typedef NTSTATUS (WINAPI* NtCreateLowBoxToken)(
- OUT PHANDLE token,
- IN HANDLE original_handle,
- IN ACCESS_MASK access,
- IN POBJECT_ATTRIBUTES object_attribute,
- IN PSID appcontainer_sid,
- IN DWORD capabilityCount,
- IN PSID_AND_ATTRIBUTES capabilities,
- IN DWORD handle_count,
- IN PHANDLE handles);
-
-typedef NTSTATUS(WINAPI *NtSetInformationProcess)(
- IN HANDLE process_handle,
- IN ULONG info_class,
- IN PVOID process_information,
- IN ULONG information_length);
-
-struct PROCESS_ACCESS_TOKEN {
- HANDLE token;
- HANDLE thread;
-};
-
-const unsigned int NtProcessInformationAccessToken = 9;
-
-#endif // SANDBOX_WIN_SRC_NT_INTERNALS_H__
-
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_broker.cc b/security/sandbox/chromium/sandbox/win/src/policy_broker.cc
deleted file mode 100644
index a946ebc76..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_broker.cc
+++ /dev/null
@@ -1,126 +0,0 @@
-// 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.
-
-#include <stddef.h>
-
-#include <map>
-
-#include "sandbox/win/src/policy_broker.h"
-
-#include "base/logging.h"
-#include "base/win/pe_image.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/policy_target.h"
-#include "sandbox/win/src/process_thread_interception.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_nt_types.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/target_process.h"
-
-// This code executes on the broker side, as a callback from the policy on the
-// target side (the child).
-
-namespace sandbox {
-
-// This is the list of all imported symbols from ntdll.dll.
-SANDBOX_INTERCEPT NtExports g_nt;
-
-#define INIT_GLOBAL_NT(member) \
- g_nt.member = reinterpret_cast<Nt##member##Function>( \
- ntdll_image.GetProcAddress("Nt" #member)); \
- if (NULL == g_nt.member) \
- return false
-
-#define INIT_GLOBAL_RTL(member) \
- g_nt.member = reinterpret_cast<member##Function>( \
- ntdll_image.GetProcAddress(#member)); \
- if (NULL == g_nt.member) \
- return false
-
-bool InitGlobalNt() {
- HMODULE ntdll = ::GetModuleHandle(kNtdllName);
- base::win::PEImage ntdll_image(ntdll);
-
- // Bypass purify's interception.
- wchar_t* loader_get = reinterpret_cast<wchar_t*>(
- ntdll_image.GetProcAddress("LdrGetDllHandle"));
- if (loader_get) {
- GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
- GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
- loader_get, &ntdll);
- }
-
- INIT_GLOBAL_NT(AllocateVirtualMemory);
- INIT_GLOBAL_NT(Close);
- INIT_GLOBAL_NT(DuplicateObject);
- INIT_GLOBAL_NT(FreeVirtualMemory);
- INIT_GLOBAL_NT(MapViewOfSection);
- INIT_GLOBAL_NT(ProtectVirtualMemory);
- INIT_GLOBAL_NT(QueryInformationProcess);
- INIT_GLOBAL_NT(QueryObject);
- INIT_GLOBAL_NT(QuerySection);
- INIT_GLOBAL_NT(QueryVirtualMemory);
- INIT_GLOBAL_NT(UnmapViewOfSection);
-
- INIT_GLOBAL_RTL(RtlAllocateHeap);
- INIT_GLOBAL_RTL(RtlAnsiStringToUnicodeString);
- INIT_GLOBAL_RTL(RtlCompareUnicodeString);
- INIT_GLOBAL_RTL(RtlCreateHeap);
- INIT_GLOBAL_RTL(RtlCreateUserThread);
- INIT_GLOBAL_RTL(RtlDestroyHeap);
- INIT_GLOBAL_RTL(RtlFreeHeap);
- INIT_GLOBAL_RTL(_strnicmp);
- INIT_GLOBAL_RTL(strlen);
- INIT_GLOBAL_RTL(wcslen);
- INIT_GLOBAL_RTL(memcpy);
-
- return true;
-}
-
-bool SetupNtdllImports(TargetProcess *child) {
- if (!InitGlobalNt()) {
- return false;
- }
-
-#ifndef NDEBUG
- // Verify that the structure is fully initialized.
- for (size_t i = 0; i < sizeof(g_nt)/sizeof(void*); i++)
- DCHECK(reinterpret_cast<char**>(&g_nt)[i]);
-#endif
- return (SBOX_ALL_OK == child->TransferVariable("g_nt", &g_nt, sizeof(g_nt)));
-}
-
-#undef INIT_GLOBAL_NT
-#undef INIT_GLOBAL_RTL
-
-bool SetupBasicInterceptions(InterceptionManager* manager) {
- // Interceptions provided by process_thread_policy, without actual policy.
- if (!INTERCEPT_NT(manager, NtOpenThread, OPEN_TREAD_ID, 20) ||
- !INTERCEPT_NT(manager, NtOpenProcess, OPEN_PROCESS_ID, 20) ||
- !INTERCEPT_NT(manager, NtOpenProcessToken, OPEN_PROCESS_TOKEN_ID, 16))
- return false;
-
- // Interceptions with neither policy nor IPC.
- if (!INTERCEPT_NT(manager, NtSetInformationThread, SET_INFORMATION_THREAD_ID,
- 20) ||
- !INTERCEPT_NT(manager, NtOpenThreadToken, OPEN_THREAD_TOKEN_ID, 20))
- return false;
-
- if (base::win::GetVersion() >= base::win::VERSION_XP) {
- // Bug 27218: We don't have dispatch for some x64 syscalls.
- // This one is also provided by process_thread_policy.
- if (!INTERCEPT_NT(manager, NtOpenProcessTokenEx, OPEN_PROCESS_TOKEN_EX_ID,
- 20))
- return false;
-
- return INTERCEPT_NT(manager, NtOpenThreadTokenEx, OPEN_THREAD_TOKEN_EX_ID,
- 24);
- }
-
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_broker.h b/security/sandbox/chromium/sandbox/win/src/policy_broker.h
deleted file mode 100644
index 15d3b21ef..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_broker.h
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2006-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 SANDBOX_SRC_POLICY_BROKER_H_
-#define SANDBOX_SRC_POLICY_BROKER_H_
-
-#include "sandbox/win/src/interception.h"
-
-namespace sandbox {
-
-class TargetProcess;
-
-// Initializes global imported symbols from ntdll.
-bool InitGlobalNt();
-
-// Sets up interceptions not controlled by explicit policies.
-bool SetupBasicInterceptions(InterceptionManager* manager);
-
-// Sets up imports from NTDLL for the given target process so the interceptions
-// can work.
-bool SetupNtdllImports(TargetProcess *child);
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_POLICY_BROKER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_engine_opcodes.cc b/security/sandbox/chromium/sandbox/win/src/policy_engine_opcodes.cc
deleted file mode 100644
index 8dca0d9d6..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_engine_opcodes.cc
+++ /dev/null
@@ -1,446 +0,0 @@
-// 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 "sandbox/win/src/policy_engine_opcodes.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "sandbox/win/src/sandbox_nt_types.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace {
-const unsigned short kMaxUniStrSize = 0xfffc / sizeof(wchar_t);
-
-bool InitStringUnicode(const wchar_t* source, size_t length,
- UNICODE_STRING* ustring) {
- if (length > kMaxUniStrSize) {
- return false;
- }
- ustring->Buffer = const_cast<wchar_t*>(source);
- ustring->Length = static_cast<USHORT>(length) * sizeof(wchar_t);
- ustring->MaximumLength = (NULL != source) ?
- ustring->Length + sizeof(wchar_t) : 0;
- return true;
-}
-
-} // namespace
-
-namespace sandbox {
-
-SANDBOX_INTERCEPT NtExports g_nt;
-
-// Note: The opcodes are implemented as functions (as opposed to classes derived
-// from PolicyOpcode) because you should not add more member variables to the
-// PolicyOpcode class since it would cause object slicing on the target. So to
-// enforce that (instead of just trusting the developer) the opcodes became
-// just functions.
-//
-// In the code that follows I have keep the evaluation function and the factory
-// function together to stress the close relationship between both. For example,
-// only the factory method and the evaluation function know the stored argument
-// order and meaning.
-
-template <int>
-EvalResult OpcodeEval(PolicyOpcode* opcode, const ParameterSet* pp,
- MatchContext* match);
-
-//////////////////////////////////////////////////////////////////////////////
-// Opcode OpAlwaysFalse:
-// Does not require input parameter.
-
-PolicyOpcode* OpcodeFactory::MakeOpAlwaysFalse(uint32_t options) {
- return MakeBase(OP_ALWAYS_FALSE, options, -1);
-}
-
-template <>
-EvalResult OpcodeEval<OP_ALWAYS_FALSE>(PolicyOpcode* opcode,
- const ParameterSet* param,
- MatchContext* context) {
- return EVAL_FALSE;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-// Opcode OpAlwaysTrue:
-// Does not require input parameter.
-
-PolicyOpcode* OpcodeFactory::MakeOpAlwaysTrue(uint32_t options) {
- return MakeBase(OP_ALWAYS_TRUE, options, -1);
-}
-
-template <>
-EvalResult OpcodeEval<OP_ALWAYS_TRUE>(PolicyOpcode* opcode,
- const ParameterSet* param,
- MatchContext* context) {
- return EVAL_TRUE;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-// Opcode OpAction:
-// Does not require input parameter.
-// Argument 0 contains the actual action to return.
-
-PolicyOpcode* OpcodeFactory::MakeOpAction(EvalResult action, uint32_t options) {
- PolicyOpcode* opcode = MakeBase(OP_ACTION, options, 0);
- if (NULL == opcode) return NULL;
- opcode->SetArgument(0, action);
- return opcode;
-}
-
-template <>
-EvalResult OpcodeEval<OP_ACTION>(PolicyOpcode* opcode,
- const ParameterSet* param,
- MatchContext* context) {
- int action = 0;
- opcode->GetArgument(0, &action);
- return static_cast<EvalResult>(action);
-}
-
-//////////////////////////////////////////////////////////////////////////////
-// Opcode OpNumberMatch:
-// Requires a uint32_t or void* in selected_param
-// Argument 0 is the stored number to match.
-// Argument 1 is the C++ type of the 0th argument.
-
-PolicyOpcode* OpcodeFactory::MakeOpNumberMatch(int16_t selected_param,
- uint32_t match,
- uint32_t options) {
- PolicyOpcode* opcode = MakeBase(OP_NUMBER_MATCH, options, selected_param);
- if (NULL == opcode) return NULL;
- opcode->SetArgument(0, match);
- opcode->SetArgument(1, UINT32_TYPE);
- return opcode;
-}
-
-PolicyOpcode* OpcodeFactory::MakeOpVoidPtrMatch(int16_t selected_param,
- const void* match,
- uint32_t options) {
- PolicyOpcode* opcode = MakeBase(OP_NUMBER_MATCH, options, selected_param);
- if (NULL == opcode) return NULL;
- opcode->SetArgument(0, match);
- opcode->SetArgument(1, VOIDPTR_TYPE);
- return opcode;
-}
-
-template <>
-EvalResult OpcodeEval<OP_NUMBER_MATCH>(PolicyOpcode* opcode,
- const ParameterSet* param,
- MatchContext* context) {
- uint32_t value_uint32 = 0;
- if (param->Get(&value_uint32)) {
- uint32_t match_uint32 = 0;
- opcode->GetArgument(0, &match_uint32);
- return (match_uint32 != value_uint32)? EVAL_FALSE : EVAL_TRUE;
- } else {
- const void* value_ptr = NULL;
- if (param->Get(&value_ptr)) {
- const void* match_ptr = NULL;
- opcode->GetArgument(0, &match_ptr);
- return (match_ptr != value_ptr)? EVAL_FALSE : EVAL_TRUE;
- }
- }
- return EVAL_ERROR;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-// Opcode OpNumberMatchRange
-// Requires a uint32_t in selected_param.
-// Argument 0 is the stored lower bound to match.
-// Argument 1 is the stored upper bound to match.
-
-PolicyOpcode* OpcodeFactory::MakeOpNumberMatchRange(int16_t selected_param,
- uint32_t lower_bound,
- uint32_t upper_bound,
- uint32_t options) {
- if (lower_bound > upper_bound) {
- return NULL;
- }
- PolicyOpcode* opcode = MakeBase(OP_NUMBER_MATCH_RANGE, options,
- selected_param);
- if (NULL == opcode) return NULL;
- opcode->SetArgument(0, lower_bound);
- opcode->SetArgument(1, upper_bound);
- return opcode;
-}
-
-template <>
-EvalResult OpcodeEval<OP_NUMBER_MATCH_RANGE>(PolicyOpcode* opcode,
- const ParameterSet* param,
- MatchContext* context) {
- uint32_t value = 0;
- if (!param->Get(&value)) return EVAL_ERROR;
-
- uint32_t lower_bound = 0;
- uint32_t upper_bound = 0;
- opcode->GetArgument(0, &lower_bound);
- opcode->GetArgument(1, &upper_bound);
- return((lower_bound <= value) && (upper_bound >= value))?
- EVAL_TRUE : EVAL_FALSE;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-// Opcode OpNumberAndMatch:
-// Requires a uint32_t in selected_param.
-// Argument 0 is the stored number to match.
-
-PolicyOpcode* OpcodeFactory::MakeOpNumberAndMatch(int16_t selected_param,
- uint32_t match,
- uint32_t options) {
- PolicyOpcode* opcode = MakeBase(OP_NUMBER_AND_MATCH, options, selected_param);
- if (NULL == opcode) return NULL;
- opcode->SetArgument(0, match);
- return opcode;
-}
-
-template <>
-EvalResult OpcodeEval<OP_NUMBER_AND_MATCH>(PolicyOpcode* opcode,
- const ParameterSet* param,
- MatchContext* context) {
- uint32_t value = 0;
- if (!param->Get(&value)) return EVAL_ERROR;
-
- uint32_t number = 0;
- opcode->GetArgument(0, &number);
- return (number & value)? EVAL_TRUE : EVAL_FALSE;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-// Opcode OpWStringMatch:
-// Requires a wchar_t* in selected_param.
-// Argument 0 is the byte displacement of the stored string.
-// Argument 1 is the lenght in chars of the stored string.
-// Argument 2 is the offset to apply on the input string. It has special values.
-// as noted in the header file.
-// Argument 3 is the string matching options.
-
-PolicyOpcode* OpcodeFactory::MakeOpWStringMatch(int16_t selected_param,
- const wchar_t* match_str,
- int start_position,
- StringMatchOptions match_opts,
- uint32_t options) {
- if (NULL == match_str) {
- return NULL;
- }
- if ('\0' == match_str[0]) {
- return NULL;
- }
-
- int lenght = lstrlenW(match_str);
-
- PolicyOpcode* opcode = MakeBase(OP_WSTRING_MATCH, options, selected_param);
- if (NULL == opcode) {
- return NULL;
- }
- ptrdiff_t delta_str = AllocRelative(opcode, match_str, wcslen(match_str)+1);
- if (0 == delta_str) {
- return NULL;
- }
- opcode->SetArgument(0, delta_str);
- opcode->SetArgument(1, lenght);
- opcode->SetArgument(2, start_position);
- opcode->SetArgument(3, match_opts);
- return opcode;
-}
-
-template<>
-EvalResult OpcodeEval<OP_WSTRING_MATCH>(PolicyOpcode* opcode,
- const ParameterSet* param,
- MatchContext* context) {
- if (NULL == context) {
- return EVAL_ERROR;
- }
- const wchar_t* source_str = NULL;
- if (!param->Get(&source_str)) return EVAL_ERROR;
-
- int start_position = 0;
- int match_len = 0;
- unsigned int match_opts = 0;
- opcode->GetArgument(1, &match_len);
- opcode->GetArgument(2, &start_position);
- opcode->GetArgument(3, &match_opts);
-
- const wchar_t* match_str = opcode->GetRelativeString(0);
- // Advance the source string to the last successfully evaluated position
- // according to the match context.
- source_str = &source_str[context->position];
- int source_len = static_cast<int>(g_nt.wcslen(source_str));
-
- if (0 == source_len) {
- // If we reached the end of the source string there is nothing we can
- // match against.
- return EVAL_FALSE;
- }
- if (match_len > source_len) {
- // There can't be a positive match when the target string is bigger than
- // the source string
- return EVAL_FALSE;
- }
-
- BOOLEAN case_sensitive = (match_opts & CASE_INSENSITIVE) ? TRUE : FALSE;
-
- // We have three cases, depending on the value of start_pos:
- // Case 1. We skip N characters and compare once.
- // Case 2: We skip to the end and compare once.
- // Case 3: We match the first substring (if we find any).
- if (start_position >= 0) {
- if (kSeekToEnd == start_position) {
- start_position = source_len - match_len;
- } else if (match_opts & EXACT_LENGHT) {
- // A sub-case of case 3 is when the EXACT_LENGHT flag is on
- // the match needs to be not just substring but full match.
- if ((match_len + start_position) != source_len) {
- return EVAL_FALSE;
- }
- }
-
- // Advance start_pos characters. Warning! this does not consider
- // utf16 encodings (surrogate pairs) or other Unicode 'features'.
- source_str += start_position;
-
- // Since we skipped, lets reevaluate just the lengths again.
- if ((match_len + start_position) > source_len) {
- return EVAL_FALSE;
- }
-
- UNICODE_STRING match_ustr;
- UNICODE_STRING source_ustr;
- if (!InitStringUnicode(match_str, match_len, &match_ustr) ||
- !InitStringUnicode(source_str, match_len, &source_ustr))
- return EVAL_ERROR;
-
- if (0 == g_nt.RtlCompareUnicodeString(&match_ustr, &source_ustr,
- case_sensitive)) {
- // Match! update the match context.
- context->position += start_position + match_len;
- return EVAL_TRUE;
- } else {
- return EVAL_FALSE;
- }
- } else if (start_position < 0) {
- UNICODE_STRING match_ustr;
- UNICODE_STRING source_ustr;
- if (!InitStringUnicode(match_str, match_len, &match_ustr) ||
- !InitStringUnicode(source_str, match_len, &source_ustr))
- return EVAL_ERROR;
-
- do {
- if (0 == g_nt.RtlCompareUnicodeString(&match_ustr, &source_ustr,
- case_sensitive)) {
- // Match! update the match context.
- context->position += (source_ustr.Buffer - source_str) + match_len;
- return EVAL_TRUE;
- }
- ++source_ustr.Buffer;
- --source_len;
- } while (source_len >= match_len);
- }
- return EVAL_FALSE;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-// OpcodeMaker (other member functions).
-
-PolicyOpcode* OpcodeFactory::MakeBase(OpcodeID opcode_id,
- uint32_t options,
- int16_t selected_param) {
- if (memory_size() < sizeof(PolicyOpcode)) {
- return NULL;
- }
-
- // Create opcode using placement-new on the buffer memory.
- PolicyOpcode* opcode = new(memory_top_) PolicyOpcode();
-
- // Fill in the standard fields, that every opcode has.
- memory_top_ += sizeof(PolicyOpcode);
- opcode->opcode_id_ = opcode_id;
- opcode->SetOptions(options);
- opcode->parameter_ = selected_param;
- return opcode;
-}
-
-ptrdiff_t OpcodeFactory::AllocRelative(void* start, const wchar_t* str,
- size_t lenght) {
- size_t bytes = lenght * sizeof(wchar_t);
- if (memory_size() < bytes) {
- return 0;
- }
- memory_bottom_ -= bytes;
- if (reinterpret_cast<UINT_PTR>(memory_bottom_) & 1) {
- // TODO(cpu) replace this for something better.
- ::DebugBreak();
- }
- memcpy(memory_bottom_, str, bytes);
- ptrdiff_t delta = memory_bottom_ - reinterpret_cast<char*>(start);
- return delta;
-}
-
-//////////////////////////////////////////////////////////////////////////////
-// Opcode evaluation dispatchers.
-
-// This function is the one and only entry for evaluating any opcode. It is
-// in charge of applying any relevant opcode options and calling EvaluateInner
-// were the actual dispatch-by-id is made. It would seem at first glance that
-// the dispatch should be done by virtual function (vtable) calls but you have
-// to remember that the opcodes are made in the broker process and copied as
-// raw memory to the target process.
-
-EvalResult PolicyOpcode::Evaluate(const ParameterSet* call_params,
- size_t param_count, MatchContext* match) {
- if (NULL == call_params) {
- return EVAL_ERROR;
- }
- const ParameterSet* selected_param = NULL;
- if (parameter_ >= 0) {
- if (static_cast<size_t>(parameter_) >= param_count) {
- return EVAL_ERROR;
- }
- selected_param = &call_params[parameter_];
- }
- EvalResult result = EvaluateHelper(selected_param, match);
-
- // Apply the general options regardless of the particular type of opcode.
- if (kPolNone == options_) {
- return result;
- }
-
- if (options_ & kPolNegateEval) {
- if (EVAL_TRUE == result) {
- result = EVAL_FALSE;
- } else if (EVAL_FALSE == result) {
- result = EVAL_TRUE;
- } else if (EVAL_ERROR != result) {
- result = EVAL_ERROR;
- }
- }
- if (NULL != match) {
- if (options_ & kPolClearContext) {
- match->Clear();
- }
- if (options_ & kPolUseOREval) {
- match->options = kPolUseOREval;
- }
- }
- return result;
-}
-
-#define OPCODE_EVAL(op, x, y, z) case op: return OpcodeEval<op>(x, y, z)
-
-EvalResult PolicyOpcode::EvaluateHelper(const ParameterSet* parameters,
- MatchContext* match) {
- switch (opcode_id_) {
- OPCODE_EVAL(OP_ALWAYS_FALSE, this, parameters, match);
- OPCODE_EVAL(OP_ALWAYS_TRUE, this, parameters, match);
- OPCODE_EVAL(OP_NUMBER_MATCH, this, parameters, match);
- OPCODE_EVAL(OP_NUMBER_MATCH_RANGE, this, parameters, match);
- OPCODE_EVAL(OP_NUMBER_AND_MATCH, this, parameters, match);
- OPCODE_EVAL(OP_WSTRING_MATCH, this, parameters, match);
- OPCODE_EVAL(OP_ACTION, this, parameters, match);
- default:
- return EVAL_ERROR;
- }
-}
-
-#undef OPCODE_EVAL
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_engine_opcodes.h b/security/sandbox/chromium/sandbox/win/src/policy_engine_opcodes.h
deleted file mode 100644
index 11a9c813e..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_engine_opcodes.h
+++ /dev/null
@@ -1,388 +0,0 @@
-// 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 SANDBOX_WIN_SRC_POLICY_ENGINE_OPCODES_H_
-#define SANDBOX_WIN_SRC_POLICY_ENGINE_OPCODES_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/numerics/safe_conversions.h"
-#include "sandbox/win/src/policy_engine_params.h"
-
-// The low-level policy is implemented using the concept of policy 'opcodes'.
-// An opcode is a structure that contains enough information to perform one
-// comparison against one single input parameter. For example, an opcode can
-// encode just one of the following comparison:
-//
-// - Is input parameter 3 not equal to NULL?
-// - Does input parameter 2 start with L"c:\\"?
-// - Is input parameter 5, bit 3 is equal 1?
-//
-// Each opcode is in fact equivalent to a function invocation where all
-// the parameters are known by the opcode except one. So say you have a
-// function of this form:
-// bool fn(a, b, c, d) with 4 arguments
-//
-// Then an opcode is:
-// op(fn, b, c, d)
-// Which stores the function to call and its 3 last arguments
-//
-// Then and opcode evaluation is:
-// op.eval(a) ------------------------> fn(a,b,c,d)
-// internally calls
-//
-// The idea is that complex policy rules can be split into streams of
-// opcodes which are evaluated in sequence. The evaluation is done in
-// groups of opcodes that have N comparison opcodes plus 1 action opcode:
-//
-// [comparison 1][comparison 2]...[comparison N][action][comparison 1]...
-// ----- evaluation order----------->
-//
-// Each opcode group encodes one high-level policy rule. The rule applies
-// only if all the conditions on the group evaluate to true. The action
-// opcode contains the policy outcome for that particular rule.
-//
-// Note that this header contains the main building blocks of low-level policy
-// but not the low level policy class.
-namespace sandbox {
-
-// These are the possible policy outcomes. Note that some of them might
-// not apply and can be removed. Also note that The following values only
-// specify what to do, not how to do it and it is acceptable given specific
-// cases to ignore the policy outcome.
-enum EvalResult {
- // Comparison opcode values:
- EVAL_TRUE, // Opcode condition evaluated true.
- EVAL_FALSE, // Opcode condition evaluated false.
- EVAL_ERROR, // Opcode condition generated an error while evaluating.
- // Action opcode values:
- ASK_BROKER, // The target must generate an IPC to the broker. On the broker
- // side, this means grant access to the resource.
- DENY_ACCESS, // No access granted to the resource.
- GIVE_READONLY, // Give readonly access to the resource.
- GIVE_ALLACCESS, // Give full access to the resource.
- GIVE_CACHED, // IPC is not required. Target can return a cached handle.
- GIVE_FIRST, // TODO(cpu)
- SIGNAL_ALARM, // Unusual activity. Generate an alarm.
- FAKE_SUCCESS, // Do not call original function. Just return 'success'.
- FAKE_ACCESS_DENIED, // Do not call original function. Just return 'denied'
- // and do not do IPC.
- TERMINATE_PROCESS, // Destroy target process. Do IPC as well.
-};
-
-// The following are the implemented opcodes.
-enum OpcodeID {
- OP_ALWAYS_FALSE, // Evaluates to false (EVAL_FALSE).
- OP_ALWAYS_TRUE, // Evaluates to true (EVAL_TRUE).
- OP_NUMBER_MATCH, // Match a 32-bit integer as n == a.
- OP_NUMBER_MATCH_RANGE, // Match a 32-bit integer as a <= n <= b.
- OP_NUMBER_AND_MATCH, // Match using bitwise AND; as in: n & a != 0.
- OP_WSTRING_MATCH, // Match a string for equality.
- OP_ACTION // Evaluates to an action opcode.
-};
-
-// Options that apply to every opcode. They are specified when creating
-// each opcode using OpcodeFactory::MakeOpXXXXX() family of functions
-// Do nothing special.
-const uint32_t kPolNone = 0;
-
-// Convert EVAL_TRUE into EVAL_FALSE and vice-versa. This allows to express
-// negated conditions such as if ( a && !b).
-const uint32_t kPolNegateEval = 1;
-
-// Zero the MatchContext context structure. This happens after the opcode
-// is evaluated.
-const uint32_t kPolClearContext = 2;
-
-// Use OR when evaluating this set of opcodes. The policy evaluator by default
-// uses AND when evaluating. Very helpful when
-// used with kPolNegateEval. For example if you have a condition best expressed
-// as if(! (a && b && c)), the use of this flags allows it to be expressed as
-// if ((!a) || (!b) || (!c)).
-const uint32_t kPolUseOREval = 4;
-
-// Keeps the evaluation state between opcode evaluations. This is used
-// for string matching where the next opcode needs to continue matching
-// from the last character position from the current opcode. The match
-// context is preserved across opcode evaluation unless an opcode specifies
-// as an option kPolClearContext.
-struct MatchContext {
- size_t position;
- uint32_t options;
-
- MatchContext() {
- Clear();
- }
-
- void Clear() {
- position = 0;
- options = 0;
- }
-};
-
-// Models a policy opcode; that is a condition evaluation were all the
-// arguments but one are stored in objects of this class. Use OpcodeFactory
-// to create objects of this type.
-// This class is just an implementation artifact and not exposed to the
-// API clients or visible in the intercepted service. Internally, an
-// opcode is just:
-// - An integer that identifies the actual opcode.
-// - An index to indicate which one is the input argument
-// - An array of arguments.
-// While an OO hierarchy of objects would have been a natural choice, the fact
-// that 1) this code can execute before the CRT is loaded, presents serious
-// problems in terms of guarantees about the actual state of the vtables and
-// 2) because the opcode objects are generated in the broker process, we need to
-// use plain objects. To preserve some minimal type safety templates are used
-// when possible.
-class PolicyOpcode {
- friend class OpcodeFactory;
- public:
- // Evaluates the opcode. For a typical comparison opcode the return value
- // is EVAL_TRUE or EVAL_FALSE. If there was an error in the evaluation the
- // the return is EVAL_ERROR. If the opcode is an action opcode then the
- // return can take other values such as ASK_BROKER.
- // parameters: An array of all input parameters. This argument is normally
- // created by the macros POLPARAMS_BEGIN() POLPARAMS_END.
- // count: The number of parameters passed as first argument.
- // match: The match context that is persisted across the opcode evaluation
- // sequence.
- EvalResult Evaluate(const ParameterSet* parameters, size_t count,
- MatchContext* match);
-
- // Retrieves a stored argument by index. Valid index values are
- // from 0 to < kArgumentCount.
- template <typename T>
- void GetArgument(size_t index, T* argument) const {
- static_assert(sizeof(T) <= sizeof(arguments_[0]), "invalid size");
- *argument = *reinterpret_cast<const T*>(&arguments_[index].mem);
- }
-
- // Sets a stored argument by index. Valid index values are
- // from 0 to < kArgumentCount.
- template <typename T>
- void SetArgument(size_t index, const T& argument) {
- static_assert(sizeof(T) <= sizeof(arguments_[0]), "invalid size");
- *reinterpret_cast<T*>(&arguments_[index].mem) = argument;
- }
-
- // Retrieves the actual address of an string argument. When using
- // GetArgument() to retrieve an index that contains a string, the returned
- // value is just an offset to the actual string.
- // index: the stored string index. Valid values are from 0
- // to < kArgumentCount.
- const wchar_t* GetRelativeString(size_t index) const {
- ptrdiff_t str_delta = 0;
- GetArgument(index, &str_delta);
- const char* delta = reinterpret_cast<const char*>(this) + str_delta;
- return reinterpret_cast<const wchar_t*>(delta);
- }
-
- // Returns true if this opcode is an action opcode without actually
- // evaluating it. Used to do a quick scan forward to the next opcode group.
- bool IsAction() const {
- return (OP_ACTION == opcode_id_);
- };
-
- // Returns the opcode type.
- OpcodeID GetID() const {
- return opcode_id_;
- }
-
- // Returns the stored options such as kPolNegateEval and others.
- uint32_t GetOptions() const { return options_; }
-
- // Sets the stored options such as kPolNegateEval.
- void SetOptions(uint32_t options) {
- options_ = base::checked_cast<uint16_t>(options);
- }
-
- private:
-
- static const size_t kArgumentCount = 4; // The number of supported argument.
-
- struct OpcodeArgument {
- UINT_PTR mem;
- };
-
- // Better define placement new in the class instead of relying on the
- // global definition which seems to be fubared.
- void* operator new(size_t, void* location) {
- return location;
- }
-
- // Helper function to evaluate the opcode. The parameters have the same
- // meaning that in Evaluate().
- EvalResult EvaluateHelper(const ParameterSet* parameters,
- MatchContext* match);
- OpcodeID opcode_id_;
- int16_t parameter_;
- // TODO(cpu): Making |options_| a uint32_t would avoid casting, but causes
- // test failures. Somewhere code is relying on the size of this struct.
- // http://crbug.com/420296
- uint16_t options_;
- OpcodeArgument arguments_[PolicyOpcode::kArgumentCount];
-};
-
-enum StringMatchOptions {
- CASE_SENSITIVE = 0, // Pay or Not attention to the case as defined by
- CASE_INSENSITIVE = 1, // RtlCompareUnicodeString windows API.
- EXACT_LENGHT = 2 // Don't do substring match. Do full string match.
-};
-
-// Opcodes that do string comparisons take a parameter that is the starting
-// position to perform the comparison so we can do substring matching. There
-// are two special values:
-//
-// Start from the current position and compare strings advancing forward until
-// a match is found if any. Similar to CRT strstr().
-const int kSeekForward = -1;
-// Perform a match with the end of the string. It only does a single comparison.
-const int kSeekToEnd = 0xfffff;
-
-
-// A PolicyBuffer is a variable size structure that contains all the opcodes
-// that are to be created or evaluated in sequence.
-struct PolicyBuffer {
- size_t opcode_count;
- PolicyOpcode opcodes[1];
-};
-
-// Helper class to create any opcode sequence. This class is normally invoked
-// only by the high level policy module or when you need to handcraft a special
-// policy.
-// The factory works by creating the opcodes using a chunk of memory given
-// in the constructor. The opcodes themselves are allocated from the beginning
-// (top) of the memory, while any string that an opcode needs is allocated from
-// the end (bottom) of the memory.
-//
-// In essence:
-//
-// low address ---> [opcode 1]
-// [opcode 2]
-// [opcode 3]
-// | | <--- memory_top_
-// | free |
-// | |
-// | | <--- memory_bottom_
-// [string 1]
-// high address --> [string 2]
-//
-// Note that this class does not keep track of the number of opcodes made and
-// it is designed to be a building block for low-level policy.
-//
-// Note that any of the MakeOpXXXXX member functions below can return NULL on
-// failure. When that happens opcode sequence creation must be aborted.
-class OpcodeFactory {
- public:
- // memory: base pointer to a chunk of memory where the opcodes are created.
- // memory_size: the size in bytes of the memory chunk.
- OpcodeFactory(char* memory, size_t memory_size)
- : memory_top_(memory) {
- memory_bottom_ = &memory_top_[memory_size];
- }
-
- // policy: contains the raw memory where the opcodes are created.
- // memory_size: contains the actual size of the policy argument.
- OpcodeFactory(PolicyBuffer* policy, size_t memory_size) {
- memory_top_ = reinterpret_cast<char*>(&policy->opcodes[0]);
- memory_bottom_ = &memory_top_[memory_size];
- }
-
- // Returns the available memory to make opcodes.
- size_t memory_size() const {
- return memory_bottom_ - memory_top_;
- }
-
- // Creates an OpAlwaysFalse opcode.
- PolicyOpcode* MakeOpAlwaysFalse(uint32_t options);
-
- // Creates an OpAlwaysFalse opcode.
- PolicyOpcode* MakeOpAlwaysTrue(uint32_t options);
-
- // Creates an OpAction opcode.
- // action: The action to return when Evaluate() is called.
- PolicyOpcode* MakeOpAction(EvalResult action, uint32_t options);
-
- // Creates an OpNumberMatch opcode.
- // selected_param: index of the input argument. It must be a uint32_t or the
- // evaluation result will generate a EVAL_ERROR.
- // match: the number to compare against the selected_param.
- PolicyOpcode* MakeOpNumberMatch(int16_t selected_param,
- uint32_t match,
- uint32_t options);
-
- // Creates an OpNumberMatch opcode (void pointers are cast to numbers).
- // selected_param: index of the input argument. It must be an void* or the
- // evaluation result will generate a EVAL_ERROR.
- // match: the pointer numeric value to compare against selected_param.
- PolicyOpcode* MakeOpVoidPtrMatch(int16_t selected_param,
- const void* match,
- uint32_t options);
-
- // Creates an OpNumberMatchRange opcode using the memory passed in the ctor.
- // selected_param: index of the input argument. It must be a uint32_t or the
- // evaluation result will generate a EVAL_ERROR.
- // lower_bound, upper_bound: the range to compare against selected_param.
- PolicyOpcode* MakeOpNumberMatchRange(int16_t selected_param,
- uint32_t lower_bound,
- uint32_t upper_bound,
- uint32_t options);
-
- // Creates an OpWStringMatch opcode using the raw memory passed in the ctor.
- // selected_param: index of the input argument. It must be a wide string
- // pointer or the evaluation result will generate a EVAL_ERROR.
- // match_str: string to compare against selected_param.
- // start_position: when its value is from 0 to < 0x7fff it indicates an
- // offset from the selected_param string where to perform the comparison. If
- // the value is SeekForward then a substring search is performed. If the
- // value is SeekToEnd the comparison is performed against the last part of
- // the selected_param string.
- // Note that the range in the position (0 to 0x7fff) is dictated by the
- // current implementation.
- // match_opts: Indicates additional matching flags. Currently CaseInsensitive
- // is supported.
- PolicyOpcode* MakeOpWStringMatch(int16_t selected_param,
- const wchar_t* match_str,
- int start_position,
- StringMatchOptions match_opts,
- uint32_t options);
-
- // Creates an OpNumberAndMatch opcode using the raw memory passed in the ctor.
- // selected_param: index of the input argument. It must be uint32_t or the
- // evaluation result will generate a EVAL_ERROR.
- // match: the value to bitwise AND against selected_param.
- PolicyOpcode* MakeOpNumberAndMatch(int16_t selected_param,
- uint32_t match,
- uint32_t options);
-
- private:
- // Constructs the common part of every opcode. selected_param is the index
- // of the input param to use when evaluating the opcode. Pass -1 in
- // selected_param to indicate that no input parameter is required.
- PolicyOpcode* MakeBase(OpcodeID opcode_id,
- uint32_t options,
- int16_t selected_param);
-
- // Allocates (and copies) a string (of size length) inside the buffer and
- // returns the displacement with respect to start.
- ptrdiff_t AllocRelative(void* start, const wchar_t* str, size_t lenght);
-
- // Points to the lowest currently available address of the memory
- // used to make the opcodes. This pointer increments as opcodes are made.
- char* memory_top_;
-
- // Points to the highest currently available address of the memory
- // used to make the opcodes. This pointer decrements as opcode strings are
- // allocated.
- char* memory_bottom_;
-
- DISALLOW_COPY_AND_ASSIGN(OpcodeFactory);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_WIN_SRC_POLICY_ENGINE_OPCODES_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_engine_params.h b/security/sandbox/chromium/sandbox/win/src/policy_engine_params.h
deleted file mode 100644
index fb4c00e3d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_engine_params.h
+++ /dev/null
@@ -1,202 +0,0 @@
-// 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 SANDBOX_SRC_POLICY_ENGINE_PARAMS_H__
-#define SANDBOX_SRC_POLICY_ENGINE_PARAMS_H__
-
-#include <stdint.h>
-
-#include "sandbox/win/src/internal_types.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-// This header defines the classes that allow the low level policy to select
-// the input parameters. In order to better make sense of this header is
-// recommended that you check policy_engine_opcodes.h first.
-
-namespace sandbox {
-
-// Models the set of interesting parameters of an intercepted system call
-// normally you don't create objects of this class directly, instead you
-// use the POLPARAMS_XXX macros.
-// For example, if an intercepted function has the following signature:
-//
-// NTSTATUS NtOpenFileFunction (PHANDLE FileHandle,
-// ACCESS_MASK DesiredAccess,
-// POBJECT_ATTRIBUTES ObjectAttributes,
-// PIO_STATUS_BLOCK IoStatusBlock,
-// ULONG ShareAccess,
-// ULONG OpenOptions);
-//
-// You could say that the following parameters are of interest to policy:
-//
-// POLPARAMS_BEGIN(open_params)
-// POLPARAM(DESIRED_ACCESS)
-// POLPARAM(OBJECT_NAME)
-// POLPARAM(SECURITY_DESCRIPTOR)
-// POLPARAM(IO_STATUS)
-// POLPARAM(OPEN_OPTIONS)
-// POLPARAMS_END;
-//
-// and the actual code will use this for defining the parameters:
-//
-// CountedParameterSet<open_params> p;
-// p[open_params::DESIRED_ACCESS] = ParamPickerMake(DesiredAccess);
-// p[open_params::OBJECT_NAME] =
-// ParamPickerMake(ObjectAttributes->ObjectName);
-// p[open_params::SECURITY_DESCRIPTOR] =
-// ParamPickerMake(ObjectAttributes->SecurityDescriptor);
-// p[open_params::IO_STATUS] = ParamPickerMake(IoStatusBlock);
-// p[open_params::OPEN_OPTIONS] = ParamPickerMake(OpenOptions);
-//
-// These will create an stack-allocated array of ParameterSet objects which
-// have each 1) the address of the parameter 2) a numeric id that encodes the
-// original C++ type. This allows the policy to treat any set of supported
-// argument types uniformily and with some type safety.
-//
-// TODO(cpu): support not fully implemented yet for unicode string and will
-// probably add other types as well.
-class ParameterSet {
- public:
- ParameterSet() : real_type_(INVALID_TYPE), address_(NULL) {}
-
- // Retrieve the stored parameter. If the type does not match ulong fail.
- bool Get(uint32_t* destination) const {
- if (real_type_ != UINT32_TYPE) {
- return false;
- }
- *destination = Void2TypePointerCopy<uint32_t>();
- return true;
- }
-
- // Retrieve the stored parameter. If the type does not match void* fail.
- bool Get(const void** destination) const {
- if (real_type_ != VOIDPTR_TYPE) {
- return false;
- }
- *destination = Void2TypePointerCopy<void*>();
- return true;
- }
-
- // Retrieve the stored parameter. If the type does not match wchar_t* fail.
- bool Get(const wchar_t** destination) const {
- if (real_type_ != WCHAR_TYPE) {
- return false;
- }
- *destination = Void2TypePointerCopy<const wchar_t*>();
- return true;
- }
-
- // False if the parameter is not properly initialized.
- bool IsValid() const {
- return real_type_ != INVALID_TYPE;
- }
-
- protected:
- // The constructor can only be called by derived types, which should
- // safely provide the real_type and the address of the argument.
- ParameterSet(ArgType real_type, const void* address)
- : real_type_(real_type), address_(address) {
- }
-
- private:
- // This template provides the same functionality as bits_cast but
- // it works with pointer while the former works only with references.
- template <typename T>
- T Void2TypePointerCopy() const {
- return *(reinterpret_cast<const T*>(address_));
- }
-
- ArgType real_type_;
- const void* address_;
-};
-
-// To safely infer the type, we use a set of template specializations
-// in ParameterSetEx with a template function ParamPickerMake to do the
-// parameter type deduction.
-
-// Base template class. Not implemented so using unsupported types should
-// fail to compile.
-template <typename T>
-class ParameterSetEx : public ParameterSet {
- public:
- ParameterSetEx(const void* address);
-};
-
-template<>
-class ParameterSetEx<void const*> : public ParameterSet {
- public:
- ParameterSetEx(const void* address)
- : ParameterSet(VOIDPTR_TYPE, address) {}
-};
-
-template<>
-class ParameterSetEx<void*> : public ParameterSet {
- public:
- ParameterSetEx(const void* address)
- : ParameterSet(VOIDPTR_TYPE, address) {}
-};
-
-
-template<>
-class ParameterSetEx<wchar_t*> : public ParameterSet {
- public:
- ParameterSetEx(const void* address)
- : ParameterSet(WCHAR_TYPE, address) {}
-};
-
-template<>
-class ParameterSetEx<wchar_t const*> : public ParameterSet {
- public:
- ParameterSetEx(const void* address)
- : ParameterSet(WCHAR_TYPE, address) {}
-};
-
-template <>
-class ParameterSetEx<uint32_t> : public ParameterSet {
- public:
- ParameterSetEx(const void* address)
- : ParameterSet(UINT32_TYPE, address) {}
-};
-
-template<>
-class ParameterSetEx<UNICODE_STRING> : public ParameterSet {
- public:
- ParameterSetEx(const void* address)
- : ParameterSet(UNISTR_TYPE, address) {}
-};
-
-template <typename T>
-ParameterSet ParamPickerMake(T& parameter) {
- return ParameterSetEx<T>(&parameter);
-};
-
-struct CountedParameterSetBase {
- int count;
- ParameterSet parameters[1];
-};
-
-// This template defines the actual list of policy parameters for a given
-// interception.
-// Warning: This template stores the address to the actual variables, in
-// other words, the values are not copied.
-template <typename T>
-struct CountedParameterSet {
- CountedParameterSet() : count(T::PolParamLast) {}
-
- ParameterSet& operator[](typename T::Args n) {
- return parameters[n];
- }
-
- CountedParameterSetBase* GetBase() {
- return reinterpret_cast<CountedParameterSetBase*>(this);
- }
-
- int count;
- ParameterSet parameters[T::PolParamLast];
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_POLICY_ENGINE_PARAMS_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_engine_processor.cc b/security/sandbox/chromium/sandbox/win/src/policy_engine_processor.cc
deleted file mode 100644
index 960db085c..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_engine_processor.cc
+++ /dev/null
@@ -1,110 +0,0 @@
-// 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 <stddef.h>
-#include <stdint.h>
-
-#include "sandbox/win/src/policy_engine_processor.h"
-
-namespace sandbox {
-
-void PolicyProcessor::SetInternalState(size_t index, EvalResult result) {
- state_.current_index_ = index;
- state_.current_result_ = result;
-}
-
-EvalResult PolicyProcessor::GetAction() const {
- return state_.current_result_;
-}
-
-// Decides if an opcode can be skipped (not evaluated) or not. The function
-// takes as inputs the opcode and the current evaluation context and returns
-// true if the opcode should be skipped or not and also can set keep_skipping
-// to false to signal that the current instruction should be skipped but not
-// the next after the current one.
-bool SkipOpcode(const PolicyOpcode& opcode, MatchContext* context,
- bool* keep_skipping) {
- if (opcode.IsAction()) {
- uint32_t options = context->options;
- context->Clear();
- *keep_skipping = false;
- return (kPolUseOREval != options);
- }
- *keep_skipping = true;
- return true;
-}
-
-PolicyResult PolicyProcessor::Evaluate(uint32_t options,
- ParameterSet* parameters,
- size_t param_count) {
- if (NULL == policy_) {
- return NO_POLICY_MATCH;
- }
- if (0 == policy_->opcode_count) {
- return NO_POLICY_MATCH;
- }
- if (!(kShortEval & options)) {
- return POLICY_ERROR;
- }
-
- MatchContext context;
- bool evaluation = false;
- bool skip_group = false;
- SetInternalState(0, EVAL_FALSE);
- size_t count = policy_->opcode_count;
-
- // Loop over all the opcodes Evaluating in sequence. Since we only support
- // short circuit evaluation, we stop as soon as we find an 'action' opcode
- // and the current evaluation is true.
- //
- // Skipping opcodes can happen when we are in AND mode (!kPolUseOREval) and
- // have got EVAL_FALSE or when we are in OR mode (kPolUseOREval) and got
- // EVAL_TRUE. Skipping will stop at the next action opcode or at the opcode
- // after the action depending on kPolUseOREval.
-
- for (size_t ix = 0; ix != count; ++ix) {
- PolicyOpcode& opcode = policy_->opcodes[ix];
- // Skipping block.
- if (skip_group) {
- if (SkipOpcode(opcode, &context, &skip_group)) {
- continue;
- }
- }
- // Evaluation block.
- EvalResult result = opcode.Evaluate(parameters, param_count, &context);
- switch (result) {
- case EVAL_FALSE:
- evaluation = false;
- if (kPolUseOREval != context.options) {
- skip_group = true;
- }
- break;
- case EVAL_ERROR:
- if (kStopOnErrors & options) {
- return POLICY_ERROR;
- }
- break;
- case EVAL_TRUE:
- evaluation = true;
- if (kPolUseOREval == context.options) {
- skip_group = true;
- }
- break;
- default:
- // We have evaluated an action.
- SetInternalState(ix, result);
- return POLICY_MATCH;
- }
- }
-
- if (evaluation) {
- // Reaching the end of the policy with a positive evaluation is probably
- // an error: we did not find a final action opcode?
- return POLICY_ERROR;
- }
- return NO_POLICY_MATCH;
-}
-
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_engine_processor.h b/security/sandbox/chromium/sandbox/win/src/policy_engine_processor.h
deleted file mode 100644
index 0d5689604..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_engine_processor.h
+++ /dev/null
@@ -1,148 +0,0 @@
-// 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 SANDBOX_SRC_POLICY_ENGINE_PROCESSOR_H__
-#define SANDBOX_SRC_POLICY_ENGINE_PROCESSOR_H__
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_engine_params.h"
-
-namespace sandbox {
-
-// This header contains the core policy evaluator. In its simplest form
-// it evaluates a stream of opcodes assuming that they are laid out in
-// memory as opcode groups.
-//
-// An opcode group has N comparison opcodes plus 1 action opcode. For
-// example here we have 3 opcode groups (A, B,C):
-//
-// [comparison 1] <-- group A start
-// [comparison 2]
-// [comparison 3]
-// [action A ]
-// [comparison 1] <-- group B start
-// [action B ]
-// [comparison 1] <-- group C start
-// [comparison 2]
-// [action C ]
-//
-// The opcode evaluator proceeds from the top, evaluating each opcode in
-// sequence. An opcode group is evaluated until the first comparison that
-// returns false. At that point the rest of the group is skipped and evaluation
-// resumes with the first comparison of the next group. When all the comparisons
-// in a group have evaluated to true and the action is reached. The group is
-// considered a matching group.
-//
-// In the 'ShortEval' mode evaluation stops when it reaches the end or the first
-// matching group. The action opcode from this group is the resulting policy
-// action.
-//
-// In the 'RankedEval' mode evaluation stops only when it reaches the end of the
-// the opcode stream. In the process all matching groups are saved and at the
-// end the 'best' group is selected (what makes the best is TBD) and the action
-// from this group is the resulting policy action.
-//
-// As explained above, the policy evaluation of a group is a logical AND of
-// the evaluation of each opcode. However an opcode can request kPolUseOREval
-// which makes the evaluation to use logical OR. Given that each opcode can
-// request its evaluation result to be negated with kPolNegateEval you can
-// achieve the negation of the total group evaluation. This means that if you
-// need to express:
-// if (!(c1 && c2 && c3))
-// You can do it by:
-// if ((!c1) || (!c2) || (!c3))
-//
-
-// Possible outcomes of policy evaluation.
-enum PolicyResult {
- NO_POLICY_MATCH,
- POLICY_MATCH,
- POLICY_ERROR
-};
-
-// Policy evaluation flags
-// TODO(cpu): implement the options kStopOnErrors & kRankedEval.
-//
-// Stop evaluating as soon as an error is encountered.
-const uint32_t kStopOnErrors = 1;
-// Ignore all non fatal opcode evaluation errors.
-const uint32_t kIgnoreErrors = 2;
-// Short-circuit evaluation: Only evaluate until opcode group that
-// evaluated to true has been found.
-const uint32_t kShortEval = 4;
-// Discussed briefly at the policy design meeting. It will evaluate
-// all rules and then return the 'best' rule that evaluated true.
-const uint32_t kRankedEval = 8;
-
-// This class evaluates a policy-opcode stream given the memory where the
-// opcodes are and an input 'parameter set'.
-//
-// This class is designed to be callable from interception points
-// as low as the NtXXXX service level (it is not currently safe, but
-// it is designed to be made safe).
-//
-// Its usage in an interception is:
-//
-// POLPARAMS_BEGIN(eval_params)
-// POLPARAM(param1)
-// POLPARAM(param2)
-// POLPARAM(param3)
-// POLPARAM(param4)
-// POLPARAM(param5)
-// POLPARAMS_END;
-//
-// PolicyProcessor pol_evaluator(policy_memory);
-// PolicyResult pr = pol_evaluator.Evaluate(ShortEval, eval_params,
-// _countof(eval_params));
-// if (NO_POLICY_MATCH == pr) {
-// EvalResult policy_action = pol_evaluator.GetAction();
-// // apply policy here...
-// }
-//
-// Where the POLPARAM() arguments are derived from the intercepted function
-// arguments, and represent all the 'interesting' policy inputs, and
-// policy_memory is a memory buffer containing the opcode stream that is the
-// relevant policy for this intercept.
-class PolicyProcessor {
- public:
- // policy_buffer contains opcodes made with OpcodeFactory. They are usually
- // created in the broker process and evaluated in the target process.
-
- // This constructor is just a variant of the previous constructor.
- explicit PolicyProcessor(PolicyBuffer* policy)
- : policy_(policy) {
- SetInternalState(0, EVAL_FALSE);
- }
-
- // Evaluates a policy-opcode stream. See the comments at the top of this
- // class for more info. Returns POLICY_MATCH if a rule set was found that
- // matches an active policy.
- PolicyResult Evaluate(uint32_t options,
- ParameterSet* parameters,
- size_t parameter_count);
-
- // If the result of Evaluate() was POLICY_MATCH, calling this function returns
- // the recommended policy action.
- EvalResult GetAction() const;
-
- private:
- struct {
- size_t current_index_;
- EvalResult current_result_;
- } state_;
-
- // Sets the currently matching action result.
- void SetInternalState(size_t index, EvalResult result);
-
- PolicyBuffer* policy_;
- DISALLOW_COPY_AND_ASSIGN(PolicyProcessor);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_POLICY_ENGINE_PROCESSOR_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_engine_unittest.cc b/security/sandbox/chromium/sandbox/win/src/policy_engine_unittest.cc
deleted file mode 100644
index 5572bdcd3..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_engine_unittest.cc
+++ /dev/null
@@ -1,105 +0,0 @@
-// 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 <stddef.h>
-#include <stdint.h>
-
-#include "sandbox/win/src/policy_engine_params.h"
-#include "sandbox/win/src/policy_engine_processor.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-#define POLPARAMS_BEGIN(x) sandbox::ParameterSet x[] = {
-#define POLPARAM(p) sandbox::ParamPickerMake(p),
-#define POLPARAMS_END }
-
-namespace sandbox {
-
-bool SetupNtdllImports();
-
-TEST(PolicyEngineTest, Rules1) {
- SetupNtdllImports();
-
- // Construct two policy rules that say:
- //
- // #1
- // If the path is c:\\documents and settings\\* AND
- // If the creation mode is 'open existing' AND
- // If the security descriptor is null THEN
- // Ask the broker.
- //
- // #2
- // If the security descriptor is null AND
- // If the path ends with *.txt AND
- // If the creation mode is not 'create new' THEN
- // return Access Denied.
-
- enum FileCreateArgs {
- FileNameArg,
- CreationDispositionArg,
- FlagsAndAttributesArg,
- SecurityAttributes
- };
-
- const size_t policy_sz = 1024;
- PolicyBuffer* policy = reinterpret_cast<PolicyBuffer*>(new char[policy_sz]);
- OpcodeFactory opcode_maker(policy, policy_sz - 0x40);
-
- // Add rule set #1
- opcode_maker.MakeOpWStringMatch(FileNameArg,
- L"c:\\documents and settings\\",
- 0, CASE_INSENSITIVE, kPolNone);
- opcode_maker.MakeOpNumberMatch(CreationDispositionArg, OPEN_EXISTING,
- kPolNone);
- opcode_maker.MakeOpVoidPtrMatch(SecurityAttributes, (void*)NULL,
- kPolNone);
- opcode_maker.MakeOpAction(ASK_BROKER, kPolNone);
-
- // Add rule set #2
- opcode_maker.MakeOpWStringMatch(FileNameArg, L".TXT",
- kSeekToEnd, CASE_INSENSITIVE, kPolNone);
- opcode_maker.MakeOpNumberMatch(CreationDispositionArg, CREATE_NEW,
- kPolNegateEval);
- opcode_maker.MakeOpAction(FAKE_ACCESS_DENIED, kPolNone);
- policy->opcode_count = 7;
-
- const wchar_t* filename = L"c:\\Documents and Settings\\Microsoft\\BLAH.txt";
- uint32_t creation_mode = OPEN_EXISTING;
- uint32_t flags = FILE_ATTRIBUTE_NORMAL;
- void* security_descriptor = NULL;
-
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(filename)
- POLPARAM(creation_mode)
- POLPARAM(flags)
- POLPARAM(security_descriptor)
- POLPARAMS_END;
-
- PolicyResult pr;
- PolicyProcessor pol_ev(policy);
-
- // Test should match the first rule set.
- pr = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, pr);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- // Test should still match the first rule set.
- pr = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, pr);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- // Changing creation_mode such that evaluation should not match any rule.
- creation_mode = CREATE_NEW;
- pr = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, pr);
-
- // Changing creation_mode such that evaluation should match rule #2.
- creation_mode = OPEN_ALWAYS;
- pr = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, pr);
- EXPECT_EQ(FAKE_ACCESS_DENIED, pol_ev.GetAction());
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_low_level.cc b/security/sandbox/chromium/sandbox/win/src/policy_low_level.cc
deleted file mode 100644
index 526b23d6b..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_low_level.cc
+++ /dev/null
@@ -1,360 +0,0 @@
-// 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 "sandbox/win/src/policy_low_level.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <map>
-#include <string>
-
-namespace {
-
- // A single rule can use at most this amount of memory.
- const size_t kRuleBufferSize = 1024*4;
-
- // The possible states of the string matching opcode generator.
- enum {
- PENDING_NONE,
- PENDING_ASTERISK, // Have seen an '*' but have not generated an opcode.
- PENDING_QMARK, // Have seen an '?' but have not generated an opcode.
- };
-
- // The category of the last character seen by the string matching opcode
- // generator.
- const uint32_t kLastCharIsNone = 0;
- const uint32_t kLastCharIsAlpha = 1;
- const uint32_t kLastCharIsWild = 2;
- const uint32_t kLastCharIsAsterisk = kLastCharIsWild + 4;
- const uint32_t kLastCharIsQuestionM = kLastCharIsWild + 8;
-}
-
-namespace sandbox {
-
-LowLevelPolicy::LowLevelPolicy(PolicyGlobal* policy_store)
- : policy_store_(policy_store) {
-}
-
-// Adding a rule is nothing more than pushing it into an stl container. Done()
-// is called for the rule in case the code that made the rule in the first
-// place has not done it.
-bool LowLevelPolicy::AddRule(int service, PolicyRule* rule) {
- if (!rule->Done()) {
- return false;
- }
-
- PolicyRule* local_rule = new PolicyRule(*rule);
- RuleNode node = {local_rule, service};
- rules_.push_back(node);
- return true;
-}
-
-LowLevelPolicy::~LowLevelPolicy() {
- // Delete all the rules.
- typedef std::list<RuleNode> RuleNodes;
- for (RuleNodes::iterator it = rules_.begin(); it != rules_.end(); ++it) {
- delete it->rule;
- }
-}
-
-// Here is where the heavy byte shuffling is done. We take all the rules and
-// 'compile' them into a single memory region. Now, the rules are in random
-// order so the first step is to reorganize them into a stl map that is keyed
-// by the service id and as a value contains a list with all the rules that
-// belong to that service. Then we enter the big for-loop where we carve a
-// memory zone for the opcodes and the data and call RebindCopy on each rule
-// so they all end up nicely packed in the policy_store_.
-bool LowLevelPolicy::Done() {
- typedef std::list<RuleNode> RuleNodes;
- typedef std::list<const PolicyRule*> RuleList;
- typedef std::map<uint32_t, RuleList> Mmap;
- Mmap mmap;
-
- for (RuleNodes::iterator it = rules_.begin(); it != rules_.end(); ++it) {
- mmap[it->service].push_back(it->rule);
- }
-
- PolicyBuffer* current_buffer = &policy_store_->data[0];
- char* buffer_end = reinterpret_cast<char*>(current_buffer) +
- policy_store_->data_size;
- size_t avail_size = policy_store_->data_size;
-
- for (Mmap::iterator it = mmap.begin(); it != mmap.end(); ++it) {
- uint32_t service = (*it).first;
- if (service >= kMaxServiceCount) {
- return false;
- }
- policy_store_->entry[service] = current_buffer;
-
- RuleList::iterator rules_it = (*it).second.begin();
- RuleList::iterator rules_it_end = (*it).second.end();
-
- size_t svc_opcode_count = 0;
-
- for (; rules_it != rules_it_end; ++rules_it) {
- const PolicyRule* rule = (*rules_it);
- size_t op_count = rule->GetOpcodeCount();
-
- size_t opcodes_size = op_count * sizeof(PolicyOpcode);
- if (avail_size < opcodes_size) {
- return false;
- }
- size_t data_size = avail_size - opcodes_size;
- PolicyOpcode* opcodes_start = &current_buffer->opcodes[svc_opcode_count];
- if (!rule->RebindCopy(opcodes_start, opcodes_size,
- buffer_end, &data_size)) {
- return false;
- }
- size_t used = avail_size - data_size;
- buffer_end -= used;
- avail_size -= used;
- svc_opcode_count += op_count;
- }
-
- current_buffer->opcode_count += svc_opcode_count;
- size_t policy_byte_count = (svc_opcode_count * sizeof(PolicyOpcode))
- / sizeof(current_buffer[0]);
- current_buffer = &current_buffer[policy_byte_count + 1];
- }
-
- return true;
-}
-
-PolicyRule::PolicyRule(EvalResult action)
- : action_(action), done_(false) {
- char* memory = new char[sizeof(PolicyBuffer) + kRuleBufferSize];
- buffer_ = reinterpret_cast<PolicyBuffer*>(memory);
- buffer_->opcode_count = 0;
- opcode_factory_ = new OpcodeFactory(buffer_,
- kRuleBufferSize + sizeof(PolicyOpcode));
-}
-
-PolicyRule::PolicyRule(const PolicyRule& other) {
- if (this == &other)
- return;
- action_ = other.action_;
- done_ = other.done_;
- size_t buffer_size = sizeof(PolicyBuffer) + kRuleBufferSize;
- char* memory = new char[buffer_size];
- buffer_ = reinterpret_cast<PolicyBuffer*>(memory);
- memcpy(buffer_, other.buffer_, buffer_size);
-
- char* opcode_buffer = reinterpret_cast<char*>(&buffer_->opcodes[0]);
- char* next_opcode = &opcode_buffer[GetOpcodeCount() * sizeof(PolicyOpcode)];
- opcode_factory_ =
- new OpcodeFactory(next_opcode, other.opcode_factory_->memory_size());
-}
-
-// This function get called from a simple state machine implemented in
-// AddStringMatch() which passes the current state (in state) and it passes
-// true in last_call if AddStringMatch() has finished processing the input
-// pattern string and this would be the last call to generate any pending
-// opcode. The skip_count is the currently accumulated number of '?' seen so
-// far and once the associated opcode is generated this function sets it back
-// to zero.
-bool PolicyRule::GenStringOpcode(RuleType rule_type,
- StringMatchOptions match_opts,
- uint16_t parameter,
- int state,
- bool last_call,
- int* skip_count,
- base::string16* fragment) {
- // The last opcode must:
- // 1) Always clear the context.
- // 2) Preserve the negation.
- // 3) Remove the 'OR' mode flag.
- uint32_t options = kPolNone;
- if (last_call) {
- if (IF_NOT == rule_type) {
- options = kPolClearContext | kPolNegateEval;
- } else {
- options = kPolClearContext;
- }
- } else if (IF_NOT == rule_type) {
- options = kPolUseOREval | kPolNegateEval;
- }
-
- PolicyOpcode* op = NULL;
-
- // The fragment string contains the accumulated characters to match with, it
- // never contains wildcards (unless they have been escaped) and while there
- // is no fragment there is no new string match opcode to generate.
- if (fragment->empty()) {
- // There is no new opcode to generate but in the last call we have to fix
- // the previous opcode because it was really the last but we did not know
- // it at that time.
- if (last_call && (buffer_->opcode_count > 0)) {
- op = &buffer_->opcodes[buffer_->opcode_count - 1];
- op->SetOptions(options);
- }
- return true;
- }
-
- if (PENDING_ASTERISK == state) {
- if (last_call) {
- op = opcode_factory_->MakeOpWStringMatch(parameter, fragment->c_str(),
- kSeekToEnd, match_opts,
- options);
- } else {
- op = opcode_factory_->MakeOpWStringMatch(parameter, fragment->c_str(),
- kSeekForward, match_opts,
- options);
- }
-
- } else if (PENDING_QMARK == state) {
- op = opcode_factory_->MakeOpWStringMatch(parameter, fragment->c_str(),
- *skip_count, match_opts, options);
- *skip_count = 0;
- } else {
- if (last_call) {
- match_opts = static_cast<StringMatchOptions>(EXACT_LENGHT | match_opts);
- }
- op = opcode_factory_->MakeOpWStringMatch(parameter, fragment->c_str(), 0,
- match_opts, options);
- }
- if (NULL == op) {
- return false;
- }
- ++buffer_->opcode_count;
- fragment->clear();
- return true;
-}
-
-bool PolicyRule::AddStringMatch(RuleType rule_type,
- int16_t parameter,
- const wchar_t* string,
- StringMatchOptions match_opts) {
- if (done_) {
- // Do not allow to add more rules after generating the action opcode.
- return false;
- }
-
- const wchar_t* current_char = string;
- uint32_t last_char = kLastCharIsNone;
- int state = PENDING_NONE;
- int skip_count = 0; // counts how many '?' we have seen in a row.
- base::string16 fragment; // accumulates the non-wildcard part.
-
- while (L'\0' != *current_char) {
- switch (*current_char) {
- case L'*':
- if (kLastCharIsWild & last_char) {
- // '**' and '&*' is an error.
- return false;
- }
- if (!GenStringOpcode(rule_type, match_opts, parameter,
- state, false, &skip_count, &fragment)) {
- return false;
- }
- last_char = kLastCharIsAsterisk;
- state = PENDING_ASTERISK;
- break;
- case L'?':
- if (kLastCharIsAsterisk == last_char) {
- // '*?' is an error.
- return false;
- }
- if (!GenStringOpcode(rule_type, match_opts, parameter,
- state, false, &skip_count, &fragment)) {
- return false;
- }
- ++skip_count;
- last_char = kLastCharIsQuestionM;
- state = PENDING_QMARK;
- break;
- case L'/':
- // Note: "/?" is an escaped '?'. Eat the slash and fall through.
- if (L'?' == current_char[1]) {
- ++current_char;
- }
- default:
- fragment += *current_char;
- last_char = kLastCharIsAlpha;
- }
- ++current_char;
- }
-
- if (!GenStringOpcode(rule_type, match_opts, parameter,
- state, true, &skip_count, &fragment)) {
- return false;
- }
- return true;
-}
-
-bool PolicyRule::AddNumberMatch(RuleType rule_type,
- int16_t parameter,
- uint32_t number,
- RuleOp comparison_op) {
- if (done_) {
- // Do not allow to add more rules after generating the action opcode.
- return false;
- }
- uint32_t opts = (rule_type == IF_NOT) ? kPolNegateEval : kPolNone;
-
- if (EQUAL == comparison_op) {
- if (NULL == opcode_factory_->MakeOpNumberMatch(parameter, number, opts)) {
- return false;
- }
- } else if (AND == comparison_op) {
- if (NULL == opcode_factory_->MakeOpNumberAndMatch(parameter, number,
- opts)) {
- return false;
- }
- }
- ++buffer_->opcode_count;
- return true;
-}
-
-bool PolicyRule::Done() {
- if (done_) {
- return true;
- }
- if (NULL == opcode_factory_->MakeOpAction(action_, kPolNone)) {
- return false;
- }
- ++buffer_->opcode_count;
- done_ = true;
- return true;
-}
-
-bool PolicyRule::RebindCopy(PolicyOpcode* opcode_start, size_t opcode_size,
- char* data_start, size_t* data_size) const {
- size_t count = buffer_->opcode_count;
- for (size_t ix = 0; ix != count; ++ix) {
- if (opcode_size < sizeof(PolicyOpcode)) {
- return false;
- }
- PolicyOpcode& opcode = buffer_->opcodes[ix];
- *opcode_start = opcode;
- if (OP_WSTRING_MATCH == opcode.GetID()) {
- // For this opcode argument 0 is a delta to the string and argument 1
- // is the length (in chars) of the string.
- const wchar_t* str = opcode.GetRelativeString(0);
- size_t str_len;
- opcode.GetArgument(1, &str_len);
- str_len = str_len * sizeof(wchar_t);
- if ((*data_size) < str_len) {
- return false;
- }
- *data_size -= str_len;
- data_start -= str_len;
- memcpy(data_start, str, str_len);
- // Recompute the string displacement
- ptrdiff_t delta = data_start - reinterpret_cast<char*>(opcode_start);
- opcode_start->SetArgument(0, delta);
- }
- ++opcode_start;
- opcode_size -= sizeof(PolicyOpcode);
- }
-
- return true;
-}
-
-PolicyRule::~PolicyRule() {
- delete [] reinterpret_cast<char*>(buffer_);
- delete opcode_factory_;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_low_level.h b/security/sandbox/chromium/sandbox/win/src/policy_low_level.h
deleted file mode 100644
index f77787c77..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_low_level.h
+++ /dev/null
@@ -1,193 +0,0 @@
-// 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 SANDBOX_SRC_POLICY_LOW_LEVEL_H__
-#define SANDBOX_SRC_POLICY_LOW_LEVEL_H__
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <list>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_engine_params.h"
-
-// Low level policy classes.
-// Built on top of the PolicyOpcode and OpcodeFatory, the low level policy
-// provides a way to define rules on strings and numbers but it is unaware
-// of Windows specific details or how the Interceptions must be set up.
-// To use these classes you construct one or more rules and add them to the
-// LowLevelPolicy object like this:
-//
-// PolicyRule rule1(ASK_BROKER);
-// rule1.AddStringMatch(IF, 0, L"\\\\/?/?\\c:\\*Microsoft*\\*.exe", true);
-// rule1.AddNumberMatch(IF_NOT, 1, CREATE_ALWAYS, EQUAL);
-// rule1.AddNumberMatch(IF, 2, FILE_ATTRIBUTE_NORMAL, EQUAL);
-//
-// PolicyRule rule2(FAKE_SUCCESS);
-// rule2.AddStringMatch(IF, 0, L"\\\\/?/?\\Pipe\\Chrome.*", false));
-// rule2.AddNumberMatch(IF, 1, OPEN_EXISTING, EQUAL));
-//
-// LowLevelPolicy policyGen(*policy_memory);
-// policyGen.AddRule(kNtCreateFileSvc, &rule1);
-// policyGen.AddRule(kNtCreateFileSvc, &rule2);
-// policyGen.Done();
-//
-// At this point (error checking omitted) the policy_memory can be copied
-// to the target process where it can be evaluated.
-
-namespace sandbox {
-
-// TODO(cpu): Move this constant to crosscall_client.h.
-const size_t kMaxServiceCount = 32;
-static_assert(IPC_LAST_TAG <= kMaxServiceCount,
- "kMaxServiceCount is too low");
-
-// Defines the memory layout of the policy. This memory is filled by
-// LowLevelPolicy object.
-// For example:
-//
-// [Service 0] --points to---\
-// [Service 1] --------------|-----\
-// ...... | |
-// [Service N] | |
-// [data_size] | |
-// [Policy Buffer 0] <-------/ |
-// [opcodes of] |
-// ....... |
-// [Policy Buffer 1] <-------------/
-// [opcodes]
-// .......
-// .......
-// [Policy Buffer N]
-// [opcodes]
-// .......
-// <possibly unused space here>
-// .......
-// [opcode string ]
-// [opcode string ]
-// .......
-// [opcode string ]
-struct PolicyGlobal {
- PolicyBuffer* entry[kMaxServiceCount];
- size_t data_size;
- PolicyBuffer data[1];
-};
-
-class PolicyRule;
-
-// Provides the means to collect rules into a policy store (memory)
-class LowLevelPolicy {
- public:
- // policy_store: must contain allocated memory and the internal
- // size fields set to correct values.
- explicit LowLevelPolicy(PolicyGlobal* policy_store);
-
- // Destroys all the policy rules.
- ~LowLevelPolicy();
-
- // Adds a rule to be generated when Done() is called.
- // service: The id of the service that this rule is associated with,
- // for example the 'Open Thread' service or the "Create File" service.
- // returns false on error.
- bool AddRule(int service, PolicyRule* rule);
-
- // Generates all the rules added with AddRule() into the memory area
- // passed on the constructor. Returns false on error.
- bool Done();
-
- private:
- struct RuleNode {
- const PolicyRule* rule;
- int service;
- };
- std::list<RuleNode> rules_;
- PolicyGlobal* policy_store_;
- DISALLOW_IMPLICIT_CONSTRUCTORS(LowLevelPolicy);
-};
-
-// There are 'if' rules and 'if not' comparisons
-enum RuleType {
- IF = 0,
- IF_NOT = 1,
-};
-
-// Possible comparisons for numbers
-enum RuleOp {
- EQUAL,
- AND,
- RANGE // TODO(cpu): Implement this option.
-};
-
-// Provides the means to collect a set of comparisons into a single
-// rule and its associated action.
-class PolicyRule {
- friend class LowLevelPolicy;
-
- public:
- explicit PolicyRule(EvalResult action);
- PolicyRule(const PolicyRule& other);
- ~PolicyRule();
-
- // Adds a string comparison to the rule.
- // rule_type: possible values are IF and IF_NOT.
- // parameter: the expected index of the argument for this rule. For example
- // in a 'create file' service the file name argument can be at index 0.
- // string: is the desired matching pattern.
- // match_opts: if the pattern matching is case sensitive or not.
- bool AddStringMatch(RuleType rule_type,
- int16_t parameter,
- const wchar_t* string,
- StringMatchOptions match_opts);
-
- // Adds a number match comparison to the rule.
- // rule_type: possible values are IF and IF_NOT.
- // parameter: the expected index of the argument for this rule.
- // number: the value to compare the input to.
- // comparison_op: the comparison kind (equal, logical and, etc).
- bool AddNumberMatch(RuleType rule_type,
- int16_t parameter,
- uint32_t number,
- RuleOp comparison_op);
-
- // Returns the number of opcodes generated so far.
- size_t GetOpcodeCount() const {
- return buffer_->opcode_count;
- }
-
- // Called when there is no more comparisons to add. Internally it generates
- // the last opcode (the action opcode). Returns false if this operation fails.
- bool Done();
-
- private:
- void operator=(const PolicyRule&);
- // Called in a loop from AddStringMatch to generate the required string
- // match opcodes. rule_type, match_opts and parameter are the same as
- // in AddStringMatch.
- bool GenStringOpcode(RuleType rule_type,
- StringMatchOptions match_opts,
- uint16_t parameter,
- int state,
- bool last_call,
- int* skip_count,
- base::string16* fragment);
-
- // Loop over all generated opcodes and copy them to increasing memory
- // addresses from opcode_start and copy the extra data (strings usually) into
- // decreasing addresses from data_start. Extra data is only present in the
- // string evaluation opcodes.
- bool RebindCopy(PolicyOpcode* opcode_start, size_t opcode_size,
- char* data_start, size_t* data_size) const;
- PolicyBuffer* buffer_;
- OpcodeFactory* opcode_factory_;
- EvalResult action_;
- bool done_;
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_POLICY_LOW_LEVEL_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_low_level_unittest.cc b/security/sandbox/chromium/sandbox/win/src/policy_low_level_unittest.cc
deleted file mode 100644
index fd67469f7..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_low_level_unittest.cc
+++ /dev/null
@@ -1,621 +0,0 @@
-// 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 <stddef.h>
-#include <stdint.h>
-
-#include "sandbox/win/src/policy_engine_params.h"
-#include "sandbox/win/src/policy_engine_processor.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-#define POLPARAMS_BEGIN(x) sandbox::ParameterSet x[] = {
-#define POLPARAM(p) sandbox::ParamPickerMake(p),
-#define POLPARAMS_END }
-
-namespace sandbox {
-
-bool SetupNtdllImports();
-
-// Testing that we allow opcode generation on valid string patterns.
-TEST(PolicyEngineTest, StringPatternsOK) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_TRUE(pr.AddStringMatch(IF, 0, L"c:\\adobe\\ver??\\", CASE_SENSITIVE));
- EXPECT_TRUE(pr.AddStringMatch(IF, 0, L"*.tmp", CASE_SENSITIVE));
- EXPECT_TRUE(pr.AddStringMatch(IF, 0, L"c:\\*.doc", CASE_SENSITIVE));
- EXPECT_TRUE(pr.AddStringMatch(IF, 0, L"c:\\windows\\*", CASE_SENSITIVE));
- EXPECT_TRUE(pr.AddStringMatch(IF, 0, L"d:\\adobe\\acrobat.exe",
- CASE_SENSITIVE));
-}
-
-// Testing that we signal invalid string patterns.
-TEST(PolicyEngineTest, StringPatternsBAD) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_FALSE(pr.AddStringMatch(IF, 0, L"one**two", CASE_SENSITIVE));
- EXPECT_FALSE(pr.AddStringMatch(IF, 0, L"**three", CASE_SENSITIVE));
- EXPECT_FALSE(pr.AddStringMatch(IF, 0, L"five?six*?seven", CASE_SENSITIVE));
- EXPECT_FALSE(pr.AddStringMatch(IF, 0, L"eight?*nine", CASE_SENSITIVE));
-}
-
-// Helper function to allocate space (on the heap) for policy.
-PolicyGlobal* MakePolicyMemory() {
- const size_t kTotalPolicySz = 4096*8;
- char* mem = new char[kTotalPolicySz];
- memset(mem, 0, kTotalPolicySz);
- PolicyGlobal* policy = reinterpret_cast<PolicyGlobal*>(mem);
- policy->data_size = kTotalPolicySz - sizeof(PolicyGlobal);
- return policy;
-}
-
-// The simplest test using LowLevelPolicy it should test a single opcode which
-// does a exact string comparison.
-TEST(PolicyEngineTest, SimpleStrMatch) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_TRUE(pr.AddStringMatch(IF, 0, L"z:\\Directory\\domo.txt",
- CASE_INSENSITIVE));
-
- PolicyGlobal* policy = MakePolicyMemory();
- const uint32_t kFakeService = 2;
-
- LowLevelPolicy policyGen(policy);
- EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr));
- EXPECT_TRUE(policyGen.Done());
-
- const wchar_t* filename = L"Z:\\Directory\\domo.txt";
-
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(filename) // Argument 0
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor pol_ev(policy->entry[kFakeService]);
-
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- filename = L"Z:\\Directory\\domo.txt.tmp";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-TEST(PolicyEngineTest, SimpleIfNotStrMatch) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_TRUE(pr.AddStringMatch(IF_NOT, 0, L"c:\\Microsoft\\",
- CASE_SENSITIVE));
-
- PolicyGlobal* policy = MakePolicyMemory();
- const uint32_t kFakeService = 2;
- LowLevelPolicy policyGen(policy);
-
- EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr));
- EXPECT_TRUE(policyGen.Done());
-
- const wchar_t* filename = NULL;
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(filename) // Argument 0
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor pol_ev(policy->entry[kFakeService]);
-
- filename = L"c:\\Microsoft\\";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\MicroNerd\\";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- filename = L"c:\\Microsoft\\domo.txt";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-TEST(PolicyEngineTest, SimpleIfNotStrMatchWild1) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_TRUE(pr.AddStringMatch(IF_NOT, 0, L"c:\\Microsoft\\*",
- CASE_SENSITIVE));
-
- PolicyGlobal* policy = MakePolicyMemory();
- const uint32_t kFakeService = 3;
- LowLevelPolicy policyGen(policy);
-
- EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr));
- EXPECT_TRUE(policyGen.Done());
-
- const wchar_t* filename = NULL;
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(filename) // Argument 0
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor pol_ev(policy->entry[kFakeService]);
-
- filename = L"c:\\Microsoft\\domo.txt";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\MicroNerd\\domo.txt";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-TEST(PolicyEngineTest, SimpleIfNotStrMatchWild2) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_TRUE(pr.AddStringMatch(IF_NOT, 0, L"c:\\Microsoft\\*.txt",
- CASE_SENSITIVE));
-
- PolicyGlobal* policy = MakePolicyMemory();
- const uint32_t kFakeService = 3;
- LowLevelPolicy policyGen(policy);
-
- EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr));
- EXPECT_TRUE(policyGen.Done());
-
- const wchar_t* filename = NULL;
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(filename) // Argument 0
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor pol_ev(policy->entry[kFakeService]);
-
- filename = L"c:\\Microsoft\\domo.txt";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\MicroNerd\\domo.txt";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- filename = L"c:\\Microsoft\\domo.bmp";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-TEST(PolicyEngineTest, IfNotStrMatchTwoRulesWild1) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_TRUE(pr.AddStringMatch(IF_NOT, 0, L"c:\\Microsoft\\*",
- CASE_SENSITIVE));
- EXPECT_TRUE(pr.AddNumberMatch(IF, 1, 24, EQUAL));
-
- PolicyGlobal* policy = MakePolicyMemory();
- const uint32_t kFakeService = 3;
- LowLevelPolicy policyGen(policy);
-
- EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr));
- EXPECT_TRUE(policyGen.Done());
-
- const wchar_t* filename = NULL;
- uint32_t access = 0;
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(filename) // Argument 0
- POLPARAM(access) // Argument 1
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor pol_ev(policy->entry[kFakeService]);
-
- filename = L"c:\\Microsoft\\domo.txt";
- access = 24;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\Microsoft\\domo.txt";
- access = 42;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\MicroNerd\\domo.txt";
- access = 24;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- filename = L"c:\\Micronesia\\domo.txt";
- access = 42;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-TEST(PolicyEngineTest, IfNotStrMatchTwoRulesWild2) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_TRUE(pr.AddNumberMatch(IF, 1, 24, EQUAL));
- EXPECT_TRUE(pr.AddStringMatch(IF_NOT, 0, L"c:\\GoogleV?\\*.txt",
- CASE_SENSITIVE));
- EXPECT_TRUE(pr.AddNumberMatch(IF, 2, 66, EQUAL));
-
- PolicyGlobal* policy = MakePolicyMemory();
- const uint32_t kFakeService = 3;
- LowLevelPolicy policyGen(policy);
-
- EXPECT_TRUE(policyGen.AddRule(kFakeService, &pr));
- EXPECT_TRUE(policyGen.Done());
-
- const wchar_t* filename = NULL;
- uint32_t access = 0;
- uint32_t sharing = 66;
-
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(filename) // Argument 0
- POLPARAM(access) // Argument 1
- POLPARAM(sharing) // Argument 2
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor pol_ev(policy->entry[kFakeService]);
-
- filename = L"c:\\GoogleV2\\domo.txt";
- access = 24;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\GoogleV2\\domo.bmp";
- access = 24;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- filename = L"c:\\GoogleV23\\domo.txt";
- access = 24;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
-
- filename = L"c:\\GoogleV2\\domo.txt";
- access = 42;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\Google\\domo.txt";
- access = 24;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- filename = L"c:\\Micronesia\\domo.txt";
- access = 42;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\GoogleV2\\domo.bmp";
- access = 24;
- sharing = 0;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-// Testing one single rule in one single service. The service is made to
-// resemble NtCreateFile.
-TEST(PolicyEngineTest, OneRuleTest) {
- SetupNtdllImports();
- PolicyRule pr(ASK_BROKER);
- EXPECT_TRUE(pr.AddStringMatch(IF, 0, L"c:\\*Microsoft*\\*.txt",
- CASE_SENSITIVE));
- EXPECT_TRUE(pr.AddNumberMatch(IF_NOT, 1, CREATE_ALWAYS, EQUAL));
- EXPECT_TRUE(pr.AddNumberMatch(IF, 2, FILE_ATTRIBUTE_NORMAL, EQUAL));
-
- PolicyGlobal* policy = MakePolicyMemory();
-
- const uint32_t kNtFakeCreateFile = 7;
-
- LowLevelPolicy policyGen(policy);
- EXPECT_TRUE(policyGen.AddRule(kNtFakeCreateFile, &pr));
- EXPECT_TRUE(policyGen.Done());
-
- const wchar_t* filename = L"c:\\Documents and Settings\\Microsoft\\BLAH.txt";
- uint32_t creation_mode = OPEN_EXISTING;
- uint32_t flags = FILE_ATTRIBUTE_NORMAL;
- void* security_descriptor = NULL;
-
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(filename) // Argument 0
- POLPARAM(creation_mode) // Argument 1
- POLPARAM(flags) // Argument 2
- POLPARAM(security_descriptor)
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor pol_ev(policy->entry[kNtFakeCreateFile]);
-
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- creation_mode = CREATE_ALWAYS;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- creation_mode = OPEN_EXISTING;
- filename = L"c:\\Other\\Path\\Microsoft\\Another file.txt";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- filename = L"c:\\Other\\Path\\Microsoft\\Another file.txt.tmp";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- flags = FILE_ATTRIBUTE_DEVICE;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\Other\\Macrosoft\\Another file.txt";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\Microsoft\\1.txt";
- flags = FILE_ATTRIBUTE_NORMAL;
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev.GetAction());
-
- filename = L"c:\\Microsoft\\1.ttt";
- result = pol_ev.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-// Testing 3 rules in 3 services. Two of the services resemble File services.
-TEST(PolicyEngineTest, ThreeRulesTest) {
- SetupNtdllImports();
- PolicyRule pr_pipe(FAKE_SUCCESS);
- EXPECT_TRUE(pr_pipe.AddStringMatch(IF, 0, L"\\\\/?/?\\Pipe\\Chrome.*",
- CASE_INSENSITIVE));
- EXPECT_TRUE(pr_pipe.AddNumberMatch(IF, 1, OPEN_EXISTING, EQUAL));
- EXPECT_TRUE(pr_pipe.AddNumberMatch(IF, 2, FILE_ATTRIBUTE_NORMAL, EQUAL));
-
- size_t opc1 = pr_pipe.GetOpcodeCount();
- EXPECT_EQ(3u, opc1);
-
- PolicyRule pr_dump(ASK_BROKER);
- EXPECT_TRUE(pr_dump.AddStringMatch(IF, 0, L"\\\\/?/?\\*\\Crash Reports\\*",
- CASE_INSENSITIVE));
- EXPECT_TRUE(pr_dump.AddNumberMatch(IF, 1, CREATE_ALWAYS, EQUAL));
- EXPECT_TRUE(pr_dump.AddNumberMatch(IF, 2, FILE_ATTRIBUTE_NORMAL, EQUAL));
-
- size_t opc2 = pr_dump.GetOpcodeCount();
- EXPECT_EQ(4u, opc2);
-
- PolicyRule pr_winexe(SIGNAL_ALARM);
- EXPECT_TRUE(pr_winexe.AddStringMatch(IF, 0, L"\\\\/?/?\\C:\\Windows\\*.exe",
- CASE_INSENSITIVE));
- EXPECT_TRUE(pr_winexe.AddNumberMatch(IF, 2, FILE_ATTRIBUTE_NORMAL, EQUAL));
-
- size_t opc3 = pr_winexe.GetOpcodeCount();
- EXPECT_EQ(3u, opc3);
-
- PolicyRule pr_adobe(GIVE_CACHED);
- EXPECT_TRUE(pr_adobe.AddStringMatch(IF, 0, L"c:\\adobe\\ver?.?\\",
- CASE_SENSITIVE));
- EXPECT_TRUE(pr_adobe.AddNumberMatch(IF, 2, FILE_ATTRIBUTE_NORMAL, EQUAL));
-
- size_t opc4 = pr_adobe.GetOpcodeCount();
- EXPECT_EQ(4u, opc4);
-
- PolicyRule pr_none(GIVE_FIRST);
- EXPECT_TRUE(pr_none.AddNumberMatch(IF, 2, FILE_ATTRIBUTE_READONLY, AND));
- EXPECT_TRUE(pr_none.AddNumberMatch(IF, 2, FILE_ATTRIBUTE_SYSTEM, AND));
-
- size_t opc5 = pr_none.GetOpcodeCount();
- EXPECT_EQ(2u, opc5);
-
- PolicyGlobal* policy = MakePolicyMemory();
-
- const uint32_t kNtFakeNone = 4;
- const uint32_t kNtFakeCreateFile = 5;
- const uint32_t kNtFakeOpenFile = 6;
-
- LowLevelPolicy policyGen(policy);
- EXPECT_TRUE(policyGen.AddRule(kNtFakeCreateFile, &pr_pipe));
- EXPECT_TRUE(policyGen.AddRule(kNtFakeCreateFile, &pr_dump));
- EXPECT_TRUE(policyGen.AddRule(kNtFakeCreateFile, &pr_winexe));
-
- EXPECT_TRUE(policyGen.AddRule(kNtFakeOpenFile, &pr_adobe));
- EXPECT_TRUE(policyGen.AddRule(kNtFakeOpenFile, &pr_pipe));
-
- EXPECT_TRUE(policyGen.AddRule(kNtFakeNone, &pr_none));
-
- EXPECT_TRUE(policyGen.Done());
-
- // Inspect the policy structure manually.
- EXPECT_TRUE(NULL == policy->entry[0]);
- EXPECT_TRUE(NULL == policy->entry[1]);
- EXPECT_TRUE(NULL == policy->entry[2]);
- EXPECT_TRUE(NULL == policy->entry[3]);
- EXPECT_TRUE(NULL != policy->entry[4]); // kNtFakeNone.
- EXPECT_TRUE(NULL != policy->entry[5]); // kNtFakeCreateFile.
- EXPECT_TRUE(NULL != policy->entry[6]); // kNtFakeOpenFile.
- EXPECT_TRUE(NULL == policy->entry[7]);
-
- // The total per service opcode counts now must take in account one
- // extra opcode (action opcode) per rule.
- ++opc1;
- ++opc2;
- ++opc3;
- ++opc4;
- ++opc5;
-
- size_t tc1 = policy->entry[kNtFakeNone]->opcode_count;
- size_t tc2 = policy->entry[kNtFakeCreateFile]->opcode_count;
- size_t tc3 = policy->entry[kNtFakeOpenFile]->opcode_count;
-
- EXPECT_EQ(opc5, tc1);
- EXPECT_EQ((opc1 + opc2 + opc3), tc2);
- EXPECT_EQ((opc1 + opc4), tc3);
-
- // Check the type of the first and last opcode of each service.
-
- EXPECT_EQ(OP_NUMBER_AND_MATCH,
- policy->entry[kNtFakeNone]->opcodes[0].GetID());
- EXPECT_EQ(OP_ACTION, policy->entry[kNtFakeNone]->opcodes[tc1-1].GetID());
- EXPECT_EQ(OP_WSTRING_MATCH,
- policy->entry[kNtFakeCreateFile]->opcodes[0].GetID());
- EXPECT_EQ(OP_ACTION,
- policy->entry[kNtFakeCreateFile]->opcodes[tc2-1].GetID());
- EXPECT_EQ(OP_WSTRING_MATCH,
- policy->entry[kNtFakeOpenFile]->opcodes[0].GetID());
- EXPECT_EQ(OP_ACTION, policy->entry[kNtFakeOpenFile]->opcodes[tc3-1].GetID());
-
- // Test the policy evaluation.
-
- const wchar_t* filename = L"";
- uint32_t creation_mode = OPEN_EXISTING;
- uint32_t flags = FILE_ATTRIBUTE_NORMAL;
- void* security_descriptor = NULL;
-
- POLPARAMS_BEGIN(params)
- POLPARAM(filename) // Argument 0
- POLPARAM(creation_mode) // Argument 1
- POLPARAM(flags) // Argument 2
- POLPARAM(security_descriptor)
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor eval_CreateFile(policy->entry[kNtFakeCreateFile]);
- PolicyProcessor eval_OpenFile(policy->entry[kNtFakeOpenFile]);
- PolicyProcessor eval_None(policy->entry[kNtFakeNone]);
-
- result = eval_CreateFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_OpenFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_None.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"\\\\??\\c:\\Windows\\System32\\calc.exe";
- flags = FILE_ATTRIBUTE_SYSTEM;
- result = eval_CreateFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_None.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_OpenFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- flags += FILE_ATTRIBUTE_READONLY;
- result = eval_CreateFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_None.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(GIVE_FIRST, eval_None.GetAction());
- result = eval_OpenFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- flags = FILE_ATTRIBUTE_NORMAL;
- result = eval_CreateFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(SIGNAL_ALARM, eval_CreateFile.GetAction());
- result = eval_None.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_OpenFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"c:\\adobe\\ver3.2\\temp";
- result = eval_CreateFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_None.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_OpenFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(GIVE_CACHED, eval_OpenFile.GetAction());
-
- filename = L"c:\\adobe\\ver3.22\\temp";
- result = eval_OpenFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"\\\\??\\c:\\some path\\other path\\crash reports\\some path";
- creation_mode = CREATE_ALWAYS;
- result = eval_CreateFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, eval_CreateFile.GetAction());
- result = eval_None.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_OpenFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- filename = L"\\\\??\\Pipe\\Chrome.12345";
- creation_mode = OPEN_EXISTING;
- result = eval_CreateFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(FAKE_SUCCESS, eval_CreateFile.GetAction());
- result = eval_None.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
- result = eval_OpenFile.Evaluate(kShortEval, params, _countof(params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(FAKE_SUCCESS, eval_OpenFile.GetAction());
-
- delete [] reinterpret_cast<char*>(policy);
-}
-
-TEST(PolicyEngineTest, PolicyRuleCopyConstructorTwoStrings) {
- SetupNtdllImports();
- // Both pr_orig and pr_copy should allow hello.* but not *.txt files.
- PolicyRule pr_orig(ASK_BROKER);
- EXPECT_TRUE(pr_orig.AddStringMatch(IF, 0, L"hello.*", CASE_SENSITIVE));
-
- PolicyRule pr_copy(pr_orig);
- EXPECT_TRUE(pr_orig.AddStringMatch(IF_NOT, 0, L"*.txt", CASE_SENSITIVE));
- EXPECT_TRUE(pr_copy.AddStringMatch(IF_NOT, 0, L"*.txt", CASE_SENSITIVE));
-
- PolicyGlobal* policy = MakePolicyMemory();
- LowLevelPolicy policyGen(policy);
- EXPECT_TRUE(policyGen.AddRule(1, &pr_orig));
- EXPECT_TRUE(policyGen.AddRule(2, &pr_copy));
- EXPECT_TRUE(policyGen.Done());
-
- const wchar_t* name = NULL;
- POLPARAMS_BEGIN(eval_params)
- POLPARAM(name)
- POLPARAMS_END;
-
- PolicyResult result;
- PolicyProcessor pol_ev_orig(policy->entry[1]);
- name = L"domo.txt";
- result = pol_ev_orig.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- name = L"hello.bmp";
- result = pol_ev_orig.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev_orig.GetAction());
-
- PolicyProcessor pol_ev_copy(policy->entry[2]);
- name = L"domo.txt";
- result = pol_ev_copy.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(NO_POLICY_MATCH, result);
-
- name = L"hello.bmp";
- result = pol_ev_copy.Evaluate(kShortEval, eval_params, _countof(eval_params));
- EXPECT_EQ(POLICY_MATCH, result);
- EXPECT_EQ(ASK_BROKER, pol_ev_copy.GetAction());
-}
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_opcodes_unittest.cc b/security/sandbox/chromium/sandbox/win/src/policy_opcodes_unittest.cc
deleted file mode 100644
index f8c210e87..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_opcodes_unittest.cc
+++ /dev/null
@@ -1,372 +0,0 @@
-// 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 <stddef.h>
-#include <stdint.h>
-
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_engine_params.h"
-#include "sandbox/win/src/sandbox_nt_types.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-
-#define INIT_GLOBAL_RTL(member) \
- g_nt.member = reinterpret_cast<member##Function>( \
- ::GetProcAddress(ntdll, #member)); \
- if (NULL == g_nt.member) \
- return false
-
-namespace sandbox {
-
-const size_t kOpcodeMemory = 1024;
-
-SANDBOX_INTERCEPT NtExports g_nt;
-
-bool SetupNtdllImports() {
- HMODULE ntdll = ::GetModuleHandle(kNtdllName);
-
- INIT_GLOBAL_RTL(RtlAllocateHeap);
- INIT_GLOBAL_RTL(RtlAnsiStringToUnicodeString);
- INIT_GLOBAL_RTL(RtlCompareUnicodeString);
- INIT_GLOBAL_RTL(RtlCreateHeap);
- INIT_GLOBAL_RTL(RtlDestroyHeap);
- INIT_GLOBAL_RTL(RtlFreeHeap);
- INIT_GLOBAL_RTL(_strnicmp);
- INIT_GLOBAL_RTL(strlen);
- INIT_GLOBAL_RTL(wcslen);
-
- return true;
-}
-
-TEST(PolicyEngineTest, ParameterSetTest) {
- void* pv1 = reinterpret_cast<void*>(0x477EAA5);
- const void* pv2 = reinterpret_cast<void*>(0x987654);
- ParameterSet pset1 = ParamPickerMake(pv1);
- ParameterSet pset2 = ParamPickerMake(pv2);
-
- // Test that we can store and retrieve a void pointer:
- const void* result1 =0;
- uint32_t result2 = 0;
- EXPECT_TRUE(pset1.Get(&result1));
- EXPECT_TRUE(pv1 == result1);
- EXPECT_FALSE(pset1.Get(&result2));
- EXPECT_TRUE(pset2.Get(&result1));
- EXPECT_TRUE(pv2 == result1);
- EXPECT_FALSE(pset2.Get(&result2));
-
- // Test that we can store and retrieve a uint32_t:
- uint32_t number = 12747;
- ParameterSet pset3 = ParamPickerMake(number);
- EXPECT_FALSE(pset3.Get(&result1));
- EXPECT_TRUE(pset3.Get(&result2));
- EXPECT_EQ(number, result2);
-
- // Test that we can store and retrieve a string:
- const wchar_t* txt = L"S231L";
- ParameterSet pset4 = ParamPickerMake(txt);
- const wchar_t* result3 = NULL;
- EXPECT_TRUE(pset4.Get(&result3));
- EXPECT_EQ(0, wcscmp(txt, result3));
-}
-
-TEST(PolicyEngineTest, OpcodeConstraints) {
- // Test that PolicyOpcode has no virtual functions
- // because these objects are copied over to other processes
- // so they cannot have vtables.
- EXPECT_FALSE(__is_polymorphic(PolicyOpcode));
- // Keep developers from adding smarts to the opcodes which should
- // be pretty much a bag of bytes with a OO interface.
- EXPECT_TRUE(__has_trivial_destructor(PolicyOpcode));
- EXPECT_TRUE(__has_trivial_constructor(PolicyOpcode));
- EXPECT_TRUE(__has_trivial_copy(PolicyOpcode));
-}
-
-TEST(PolicyEngineTest, TrueFalseOpcodes) {
- void* dummy = NULL;
- ParameterSet ppb1 = ParamPickerMake(dummy);
- char memory[kOpcodeMemory];
- OpcodeFactory opcode_maker(memory, sizeof(memory));
-
- // This opcode always evaluates to true.
- PolicyOpcode* op1 = opcode_maker.MakeOpAlwaysFalse(kPolNone);
- ASSERT_NE(nullptr, op1);
- EXPECT_EQ(EVAL_FALSE, op1->Evaluate(&ppb1, 1, NULL));
- EXPECT_FALSE(op1->IsAction());
-
- // This opcode always evaluates to false.
- PolicyOpcode* op2 = opcode_maker.MakeOpAlwaysTrue(kPolNone);
- ASSERT_NE(nullptr, op2);
- EXPECT_EQ(EVAL_TRUE, op2->Evaluate(&ppb1, 1, NULL));
-
- // Nulls not allowed on the params.
- EXPECT_EQ(EVAL_ERROR, op2->Evaluate(NULL, 0, NULL));
- EXPECT_EQ(EVAL_ERROR, op2->Evaluate(NULL, 1, NULL));
-
- // True and False opcodes do not 'require' a number of parameters
- EXPECT_EQ(EVAL_TRUE, op2->Evaluate(&ppb1, 0, NULL));
- EXPECT_EQ(EVAL_TRUE, op2->Evaluate(&ppb1, 1, NULL));
-
- // Test Inverting the logic. Note that inversion is done outside
- // any particular opcode evaluation so no need to repeat for all
- // opcodes.
- PolicyOpcode* op3 = opcode_maker.MakeOpAlwaysFalse(kPolNegateEval);
- ASSERT_NE(nullptr, op3);
- EXPECT_EQ(EVAL_TRUE, op3->Evaluate(&ppb1, 1, NULL));
- PolicyOpcode* op4 = opcode_maker.MakeOpAlwaysTrue(kPolNegateEval);
- ASSERT_NE(nullptr, op4);
- EXPECT_EQ(EVAL_FALSE, op4->Evaluate(&ppb1, 1, NULL));
-
- // Test that we clear the match context
- PolicyOpcode* op5 = opcode_maker.MakeOpAlwaysTrue(kPolClearContext);
- ASSERT_NE(nullptr, op5);
- MatchContext context;
- context.position = 1;
- context.options = kPolUseOREval;
- EXPECT_EQ(EVAL_TRUE, op5->Evaluate(&ppb1, 1, &context));
- EXPECT_EQ(0u, context.position);
- MatchContext context2;
- EXPECT_EQ(context2.options, context.options);
-}
-
-TEST(PolicyEngineTest, OpcodeMakerCase1) {
- // Testing that the opcode maker does not overrun the
- // supplied buffer. It should only be able to make 'count' opcodes.
- void* dummy = NULL;
- ParameterSet ppb1 = ParamPickerMake(dummy);
-
- char memory[kOpcodeMemory];
- OpcodeFactory opcode_maker(memory, sizeof(memory));
- size_t count = sizeof(memory) / sizeof(PolicyOpcode);
-
- for (size_t ix =0; ix != count; ++ix) {
- PolicyOpcode* op = opcode_maker.MakeOpAlwaysFalse(kPolNone);
- ASSERT_NE(nullptr, op);
- EXPECT_EQ(EVAL_FALSE, op->Evaluate(&ppb1, 1, NULL));
- }
- // There should be no room more another opcode:
- PolicyOpcode* op1 = opcode_maker.MakeOpAlwaysFalse(kPolNone);
- ASSERT_EQ(nullptr, op1);
-}
-
-TEST(PolicyEngineTest, OpcodeMakerCase2) {
- SetupNtdllImports();
- // Testing that the opcode maker does not overrun the
- // supplied buffer. It should only be able to make 'count' opcodes.
- // The difference with the previous test is that this opcodes allocate
- // the string 'txt2' inside the same buffer.
- const wchar_t* txt1 = L"1234";
- const wchar_t txt2[] = L"123";
-
- ParameterSet ppb1 = ParamPickerMake(txt1);
- MatchContext mc1;
-
- char memory[kOpcodeMemory];
- OpcodeFactory opcode_maker(memory, sizeof(memory));
- size_t count = sizeof(memory) / (sizeof(PolicyOpcode) + sizeof(txt2));
-
- // Test that it does not overrun the buffer.
- for (size_t ix =0; ix != count; ++ix) {
- PolicyOpcode* op = opcode_maker.MakeOpWStringMatch(0, txt2, 0,
- CASE_SENSITIVE,
- kPolClearContext);
- ASSERT_NE(nullptr, op);
- EXPECT_EQ(EVAL_TRUE, op->Evaluate(&ppb1, 1, &mc1));
- }
-
- // There should be no room more another opcode:
- PolicyOpcode* op1 = opcode_maker.MakeOpWStringMatch(0, txt2, 0,
- CASE_SENSITIVE,
- kPolNone);
- ASSERT_EQ(nullptr, op1);
-}
-
-TEST(PolicyEngineTest, IntegerOpcodes) {
- const wchar_t* txt = L"abcdef";
- uint32_t num1 = 42;
- uint32_t num2 = 113377;
-
- ParameterSet pp_wrong1 = ParamPickerMake(txt);
- ParameterSet pp_num1 = ParamPickerMake(num1);
- ParameterSet pp_num2 = ParamPickerMake(num2);
-
- char memory[kOpcodeMemory];
- OpcodeFactory opcode_maker(memory, sizeof(memory));
-
- // Test basic match for uint32s 42 == 42 and 42 != 113377.
- PolicyOpcode* op_m42 = opcode_maker.MakeOpNumberMatch(0, 42UL, kPolNone);
- ASSERT_NE(nullptr, op_m42);
- EXPECT_EQ(EVAL_TRUE, op_m42->Evaluate(&pp_num1, 1, NULL));
- EXPECT_EQ(EVAL_FALSE, op_m42->Evaluate(&pp_num2, 1, NULL));
- EXPECT_EQ(EVAL_ERROR, op_m42->Evaluate(&pp_wrong1, 1, NULL));
-
- // Test basic match for void pointers.
- const void* vp = NULL;
- ParameterSet pp_num3 = ParamPickerMake(vp);
- PolicyOpcode* op_vp_null = opcode_maker.MakeOpVoidPtrMatch(0, NULL,
- kPolNone);
- ASSERT_NE(nullptr, op_vp_null);
- EXPECT_EQ(EVAL_TRUE, op_vp_null->Evaluate(&pp_num3, 1, NULL));
- EXPECT_EQ(EVAL_FALSE, op_vp_null->Evaluate(&pp_num1, 1, NULL));
- EXPECT_EQ(EVAL_ERROR, op_vp_null->Evaluate(&pp_wrong1, 1, NULL));
-
- // Basic range test [41 43] (inclusive).
- PolicyOpcode* op_range1 =
- opcode_maker.MakeOpNumberMatchRange(0, 41, 43, kPolNone);
- ASSERT_NE(nullptr, op_range1);
- EXPECT_EQ(EVAL_TRUE, op_range1->Evaluate(&pp_num1, 1, NULL));
- EXPECT_EQ(EVAL_FALSE, op_range1->Evaluate(&pp_num2, 1, NULL));
- EXPECT_EQ(EVAL_ERROR, op_range1->Evaluate(&pp_wrong1, 1, NULL));
-}
-
-TEST(PolicyEngineTest, LogicalOpcodes) {
- char memory[kOpcodeMemory];
- OpcodeFactory opcode_maker(memory, sizeof(memory));
-
- uint32_t num1 = 0x10100702;
- ParameterSet pp_num1 = ParamPickerMake(num1);
-
- PolicyOpcode* op_and1 =
- opcode_maker.MakeOpNumberAndMatch(0, 0x00100000, kPolNone);
- ASSERT_NE(nullptr, op_and1);
- EXPECT_EQ(EVAL_TRUE, op_and1->Evaluate(&pp_num1, 1, NULL));
- PolicyOpcode* op_and2 =
- opcode_maker.MakeOpNumberAndMatch(0, 0x00000001, kPolNone);
- ASSERT_NE(nullptr, op_and2);
- EXPECT_EQ(EVAL_FALSE, op_and2->Evaluate(&pp_num1, 1, NULL));
-}
-
-TEST(PolicyEngineTest, WCharOpcodes1) {
- SetupNtdllImports();
-
- const wchar_t* txt1 = L"the quick fox jumps over the lazy dog";
- const wchar_t txt2[] = L"the quick";
- const wchar_t txt3[] = L" fox jumps";
- const wchar_t txt4[] = L"the lazy dog";
- const wchar_t txt5[] = L"jumps over";
- const wchar_t txt6[] = L"g";
-
- ParameterSet pp_tc1 = ParamPickerMake(txt1);
- char memory[kOpcodeMemory];
- OpcodeFactory opcode_maker(memory, sizeof(memory));
-
- PolicyOpcode* op1 = opcode_maker.MakeOpWStringMatch(0, txt2, 0,
- CASE_SENSITIVE,
- kPolNone);
- ASSERT_NE(nullptr, op1);
-
- // Simplest substring match from pos 0. It should be a successful match
- // and the match context should be updated.
- MatchContext mc1;
- EXPECT_EQ(EVAL_TRUE, op1->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_TRUE(_countof(txt2) == mc1.position + 1);
-
- // Matching again should fail and the context should be unmodified.
- EXPECT_EQ(EVAL_FALSE, op1->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_TRUE(_countof(txt2) == mc1.position + 1);
-
- // Using the same match context we should continue where we left
- // in the previous successful match,
- PolicyOpcode* op3 = opcode_maker.MakeOpWStringMatch(0, txt3, 0,
- CASE_SENSITIVE,
- kPolNone);
- ASSERT_NE(nullptr, op3);
- EXPECT_EQ(EVAL_TRUE, op3->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_TRUE(_countof(txt3) + _countof(txt2) == mc1.position + 2);
-
- // We now keep on matching but now we skip 6 characters which means
- // we skip the string ' over '. And we zero the match context. This is
- // the primitive that we use to build '??'.
- PolicyOpcode* op4 = opcode_maker.MakeOpWStringMatch(0, txt4, 6,
- CASE_SENSITIVE,
- kPolClearContext);
- ASSERT_NE(nullptr, op4);
- EXPECT_EQ(EVAL_TRUE, op4->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_EQ(0u, mc1.position);
-
- // Test that we can properly match the last part of the string
- PolicyOpcode* op4b = opcode_maker.MakeOpWStringMatch(0, txt4, kSeekToEnd,
- CASE_SENSITIVE,
- kPolClearContext);
- ASSERT_NE(nullptr, op4b);
- EXPECT_EQ(EVAL_TRUE, op4b->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_EQ(0u, mc1.position);
-
- // Test matching 'jumps over' over the entire string. This is the
- // primitive we build '*' from.
- PolicyOpcode* op5 = opcode_maker.MakeOpWStringMatch(0, txt5, kSeekForward,
- CASE_SENSITIVE, kPolNone);
- ASSERT_NE(nullptr, op5);
- EXPECT_EQ(EVAL_TRUE, op5->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_EQ(24u, mc1.position);
-
- // Test that we don't match because it is not at the end of the string
- PolicyOpcode* op5b = opcode_maker.MakeOpWStringMatch(0, txt5, kSeekToEnd,
- CASE_SENSITIVE,
- kPolNone);
- ASSERT_NE(nullptr, op5b);
- EXPECT_EQ(EVAL_FALSE, op5b->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_EQ(24u, mc1.position);
-
- // Test that we function if the string does not fit. In this case we
- // try to match 'the lazy dog' against 'he lazy dog'.
- PolicyOpcode* op6 = opcode_maker.MakeOpWStringMatch(0, txt4, 2,
- CASE_SENSITIVE, kPolNone);
- ASSERT_NE(nullptr, op6);
- EXPECT_EQ(EVAL_FALSE, op6->Evaluate(&pp_tc1, 1, &mc1));
-
- // Testing matching against 'g' which should be the last char.
- MatchContext mc2;
- PolicyOpcode* op7 = opcode_maker.MakeOpWStringMatch(0, txt6, kSeekForward,
- CASE_SENSITIVE, kPolNone);
- ASSERT_NE(nullptr, op7);
- EXPECT_EQ(EVAL_TRUE, op7->Evaluate(&pp_tc1, 1, &mc2));
- EXPECT_EQ(37u, mc2.position);
-
- // Trying to match again should fail since we are in the last char.
- // This also covers a couple of boundary conditions.
- EXPECT_EQ(EVAL_FALSE, op7->Evaluate(&pp_tc1, 1, &mc2));
- EXPECT_EQ(37u, mc2.position);
-}
-
-TEST(PolicyEngineTest, WCharOpcodes2) {
- SetupNtdllImports();
-
- const wchar_t* path1 = L"c:\\documents and settings\\Microsoft\\BLAH.txt";
- const wchar_t txt1[] = L"Settings\\microsoft";
- ParameterSet pp_tc1 = ParamPickerMake(path1);
-
- char memory[kOpcodeMemory];
- OpcodeFactory opcode_maker(memory, sizeof(memory));
- MatchContext mc1;
-
- // Testing case-insensitive does not buy us much since it this option
- // is just passed to the Microsoft API that we use normally, but just for
- // coverage, here it is:
- PolicyOpcode* op1s = opcode_maker.MakeOpWStringMatch(0, txt1, kSeekForward,
- CASE_SENSITIVE, kPolNone);
- ASSERT_NE(nullptr, op1s);
- PolicyOpcode* op1i = opcode_maker.MakeOpWStringMatch(0, txt1, kSeekForward,
- CASE_INSENSITIVE,
- kPolNone);
- ASSERT_NE(nullptr, op1i);
- EXPECT_EQ(EVAL_FALSE, op1s->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_EQ(EVAL_TRUE, op1i->Evaluate(&pp_tc1, 1, &mc1));
- EXPECT_EQ(35u, mc1.position);
-}
-
-TEST(PolicyEngineTest, ActionOpcodes) {
- char memory[kOpcodeMemory];
- OpcodeFactory opcode_maker(memory, sizeof(memory));
- MatchContext mc1;
- void* dummy = NULL;
- ParameterSet ppb1 = ParamPickerMake(dummy);
-
- PolicyOpcode* op1 = opcode_maker.MakeOpAction(ASK_BROKER, kPolNone);
- ASSERT_NE(nullptr, op1);
- EXPECT_TRUE(op1->IsAction());
- EXPECT_EQ(ASK_BROKER, op1->Evaluate(&ppb1, 1, &mc1));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_params.h b/security/sandbox/chromium/sandbox/win/src/policy_params.h
deleted file mode 100644
index e051d2b59..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_params.h
+++ /dev/null
@@ -1,67 +0,0 @@
-// 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 SANDBOX_SRC_POLICY_PARAMS_H__
-#define SANDBOX_SRC_POLICY_PARAMS_H__
-
-#include "sandbox/win/src/policy_engine_params.h"
-
-namespace sandbox {
-
-class ParameterSet;
-
-// Warning: The following macros store the address to the actual variables, in
-// other words, the values are not copied.
-#define POLPARAMS_BEGIN(type) class type { public: enum Args {
-#define POLPARAM(arg) arg,
-#define POLPARAMS_END(type) PolParamLast }; }; \
- typedef sandbox::ParameterSet type##Array [type::PolParamLast];
-
-// Policy parameters for file open / create.
-POLPARAMS_BEGIN(OpenFile)
- POLPARAM(NAME)
- POLPARAM(BROKER) // TRUE if called from the broker.
- POLPARAM(ACCESS)
- POLPARAM(DISPOSITION)
- POLPARAM(OPTIONS)
-POLPARAMS_END(OpenFile)
-
-// Policy parameter for name-based policies.
-POLPARAMS_BEGIN(FileName)
- POLPARAM(NAME)
- POLPARAM(BROKER) // TRUE if called from the broker.
-POLPARAMS_END(FileName)
-
-static_assert(OpenFile::NAME == static_cast<int>(FileName::NAME),
- "to simplify fs policies");
-static_assert(OpenFile::BROKER == static_cast<int>(FileName::BROKER),
- "to simplify fs policies");
-
-// Policy parameter for name-based policies.
-POLPARAMS_BEGIN(NameBased)
- POLPARAM(NAME)
-POLPARAMS_END(NameBased)
-
-// Policy parameters for open event.
-POLPARAMS_BEGIN(OpenEventParams)
- POLPARAM(NAME)
- POLPARAM(ACCESS)
-POLPARAMS_END(OpenEventParams)
-
-// Policy Parameters for reg open / create.
-POLPARAMS_BEGIN(OpenKey)
- POLPARAM(NAME)
- POLPARAM(ACCESS)
-POLPARAMS_END(OpenKey)
-
-// Policy parameter for name-based policies.
-POLPARAMS_BEGIN(HandleTarget)
- POLPARAM(NAME)
- POLPARAM(TARGET)
-POLPARAMS_END(HandleTarget)
-
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_POLICY_PARAMS_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_target.cc b/security/sandbox/chromium/sandbox/win/src/policy_target.cc
deleted file mode 100644
index 800302805..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_target.cc
+++ /dev/null
@@ -1,129 +0,0 @@
-// 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 "sandbox/win/src/policy_target.h"
-
-#include <stddef.h>
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_engine_processor.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/target_services.h"
-
-namespace sandbox {
-
-// Handle for our private heap.
-extern void* g_heap;
-
-// This is the list of all imported symbols from ntdll.dll.
-SANDBOX_INTERCEPT NtExports g_nt;
-
-// Policy data.
-extern void* volatile g_shared_policy_memory;
-SANDBOX_INTERCEPT size_t g_shared_policy_size;
-
-bool QueryBroker(int ipc_id, CountedParameterSetBase* params) {
- DCHECK_NT(static_cast<size_t>(ipc_id) < kMaxServiceCount);
- DCHECK_NT(g_shared_policy_memory);
- DCHECK_NT(g_shared_policy_size > 0);
-
- if (static_cast<size_t>(ipc_id) >= kMaxServiceCount)
- return false;
-
- PolicyGlobal* global_policy =
- reinterpret_cast<PolicyGlobal*>(g_shared_policy_memory);
-
- if (!global_policy->entry[ipc_id])
- return false;
-
- PolicyBuffer* policy = reinterpret_cast<PolicyBuffer*>(
- reinterpret_cast<char*>(g_shared_policy_memory) +
- reinterpret_cast<size_t>(global_policy->entry[ipc_id]));
-
- if ((reinterpret_cast<size_t>(global_policy->entry[ipc_id]) >
- global_policy->data_size) ||
- (g_shared_policy_size < global_policy->data_size)) {
- NOTREACHED_NT();
- return false;
- }
-
- for (int i = 0; i < params->count; i++) {
- if (!params->parameters[i].IsValid()) {
- NOTREACHED_NT();
- return false;
- }
- }
-
- PolicyProcessor processor(policy);
- PolicyResult result = processor.Evaluate(kShortEval, params->parameters,
- params->count);
- DCHECK_NT(POLICY_ERROR != result);
-
- return POLICY_MATCH == result && ASK_BROKER == processor.GetAction();
-}
-
-// -----------------------------------------------------------------------
-
-// Hooks NtSetInformationThread to block RevertToSelf from being
-// called before the actual call to LowerToken.
-NTSTATUS WINAPI TargetNtSetInformationThread(
- NtSetInformationThreadFunction orig_SetInformationThread, HANDLE thread,
- NT_THREAD_INFORMATION_CLASS thread_info_class, PVOID thread_information,
- ULONG thread_information_bytes) {
- do {
- if (SandboxFactory::GetTargetServices()->GetState()->RevertedToSelf())
- break;
- if (ThreadImpersonationToken != thread_info_class)
- break;
- if (!thread_information)
- break;
- HANDLE token;
- if (sizeof(token) > thread_information_bytes)
- break;
-
- NTSTATUS ret = CopyData(&token, thread_information, sizeof(token));
- if (!NT_SUCCESS(ret) || NULL != token)
- break;
-
- // This is a revert to self.
- return STATUS_SUCCESS;
- } while (false);
-
- return orig_SetInformationThread(thread, thread_info_class,
- thread_information,
- thread_information_bytes);
-}
-
-// Hooks NtOpenThreadToken to force the open_as_self parameter to be set to
-// FALSE if we are still running with the impersonation token. open_as_self set
-// to TRUE means that the token will be open using the process token instead of
-// the impersonation token. This is bad because the process token does not have
-// access to open the thread token.
-NTSTATUS WINAPI TargetNtOpenThreadToken(
- NtOpenThreadTokenFunction orig_OpenThreadToken, HANDLE thread,
- ACCESS_MASK desired_access, BOOLEAN open_as_self, PHANDLE token) {
- if (!SandboxFactory::GetTargetServices()->GetState()->RevertedToSelf())
- open_as_self = FALSE;
-
- return orig_OpenThreadToken(thread, desired_access, open_as_self, token);
-}
-
-// See comment for TargetNtOpenThreadToken
-NTSTATUS WINAPI TargetNtOpenThreadTokenEx(
- NtOpenThreadTokenExFunction orig_OpenThreadTokenEx, HANDLE thread,
- ACCESS_MASK desired_access, BOOLEAN open_as_self, ULONG handle_attributes,
- PHANDLE token) {
- if (!SandboxFactory::GetTargetServices()->GetState()->RevertedToSelf())
- open_as_self = FALSE;
-
- return orig_OpenThreadTokenEx(thread, desired_access, open_as_self,
- handle_attributes, token);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_target.h b/security/sandbox/chromium/sandbox/win/src/policy_target.h
deleted file mode 100644
index 8a2b43709..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_target.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// 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 "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_POLICY_TARGET_H__
-#define SANDBOX_SRC_POLICY_TARGET_H__
-
-namespace sandbox {
-
-struct CountedParameterSetBase;
-
-// Performs a policy lookup and returns true if the request should be passed to
-// the broker process.
-bool QueryBroker(int ipc_id, CountedParameterSetBase* params);
-
-extern "C" {
-
-// Interception of NtSetInformationThread on the child process.
-// It should never be called directly.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationThread(
- NtSetInformationThreadFunction orig_SetInformationThread, HANDLE thread,
- NT_THREAD_INFORMATION_CLASS thread_info_class, PVOID thread_information,
- ULONG thread_information_bytes);
-
-// Interception of NtOpenThreadToken on the child process.
-// It should never be called directly
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThreadToken(
- NtOpenThreadTokenFunction orig_OpenThreadToken, HANDLE thread,
- ACCESS_MASK desired_access, BOOLEAN open_as_self, PHANDLE token);
-
-// Interception of NtOpenThreadTokenEx on the child process.
-// It should never be called directly
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThreadTokenEx(
- NtOpenThreadTokenExFunction orig_OpenThreadTokenEx, HANDLE thread,
- ACCESS_MASK desired_access, BOOLEAN open_as_self, ULONG handle_attributes,
- PHANDLE token);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_POLICY_TARGET_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/policy_target_test.cc b/security/sandbox/chromium/sandbox/win/src/policy_target_test.cc
deleted file mode 100644
index d1a82e54d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/policy_target_test.cc
+++ /dev/null
@@ -1,417 +0,0 @@
-// 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.
-
-#include "base/memory/shared_memory.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_piece.h"
-#include "base/win/scoped_process_information.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_utils.h"
-#include "sandbox/win/src/target_services.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-#if defined(OS_WIN)
-#include "base/win/win_util.h"
-#endif
-
-namespace sandbox {
-
-#define BINDNTDLL(name) \
- name ## Function name = reinterpret_cast<name ## Function>( \
- ::GetProcAddress(::GetModuleHandle(L"ntdll.dll"), #name))
-
-// Reverts to self and verify that SetInformationToken was faked. Returns
-// SBOX_TEST_SUCCEEDED if faked and SBOX_TEST_FAILED if not faked.
-SBOX_TESTS_COMMAND int PolicyTargetTest_token(int argc, wchar_t **argv) {
- HANDLE thread_token;
- // Get the thread token, using impersonation.
- if (!::OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE |
- TOKEN_DUPLICATE, FALSE, &thread_token))
- return ::GetLastError();
-
- ::RevertToSelf();
- ::CloseHandle(thread_token);
-
- int ret = SBOX_TEST_FAILED;
- if (::OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE | TOKEN_DUPLICATE,
- FALSE, &thread_token)) {
- ret = SBOX_TEST_SUCCEEDED;
- ::CloseHandle(thread_token);
- }
- return ret;
-}
-
-// Stores the high privilege token on a static variable, change impersonation
-// again to that one and verify that we are not interfering anymore with
-// RevertToSelf.
-SBOX_TESTS_COMMAND int PolicyTargetTest_steal(int argc, wchar_t **argv) {
- static HANDLE thread_token;
- if (!SandboxFactory::GetTargetServices()->GetState()->RevertedToSelf()) {
- if (!::OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE |
- TOKEN_DUPLICATE, FALSE, &thread_token))
- return ::GetLastError();
- } else {
- if (!::SetThreadToken(NULL, thread_token))
- return ::GetLastError();
-
- // See if we fake the call again.
- int ret = PolicyTargetTest_token(argc, argv);
- ::CloseHandle(thread_token);
- return ret;
- }
- return 0;
-}
-
-// Opens the thread token with and without impersonation.
-SBOX_TESTS_COMMAND int PolicyTargetTest_token2(int argc, wchar_t **argv) {
- HANDLE thread_token;
- // Get the thread token, using impersonation.
- if (!::OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE |
- TOKEN_DUPLICATE, FALSE, &thread_token))
- return ::GetLastError();
- ::CloseHandle(thread_token);
-
- // Get the thread token, without impersonation.
- if (!OpenThreadToken(GetCurrentThread(), TOKEN_IMPERSONATE | TOKEN_DUPLICATE,
- TRUE, &thread_token))
- return ::GetLastError();
- ::CloseHandle(thread_token);
- return SBOX_TEST_SUCCEEDED;
-}
-
-// Opens the thread token with and without impersonation, using
-// NtOpenThreadTokenEX.
-SBOX_TESTS_COMMAND int PolicyTargetTest_token3(int argc, wchar_t **argv) {
- BINDNTDLL(NtOpenThreadTokenEx);
- if (!NtOpenThreadTokenEx)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- HANDLE thread_token;
- // Get the thread token, using impersonation.
- NTSTATUS status = NtOpenThreadTokenEx(GetCurrentThread(),
- TOKEN_IMPERSONATE | TOKEN_DUPLICATE,
- FALSE, 0, &thread_token);
- if (status == STATUS_NO_TOKEN)
- return ERROR_NO_TOKEN;
- if (!NT_SUCCESS(status))
- return SBOX_TEST_FAILED;
-
- ::CloseHandle(thread_token);
-
- // Get the thread token, without impersonation.
- status = NtOpenThreadTokenEx(GetCurrentThread(),
- TOKEN_IMPERSONATE | TOKEN_DUPLICATE, TRUE, 0,
- &thread_token);
- if (!NT_SUCCESS(status))
- return SBOX_TEST_FAILED;
-
- ::CloseHandle(thread_token);
- return SBOX_TEST_SUCCEEDED;
-}
-
-// Tests that we can open the current thread.
-SBOX_TESTS_COMMAND int PolicyTargetTest_thread(int argc, wchar_t **argv) {
- DWORD thread_id = ::GetCurrentThreadId();
- HANDLE thread = ::OpenThread(SYNCHRONIZE, FALSE, thread_id);
- if (!thread)
- return ::GetLastError();
- if (!::CloseHandle(thread))
- return ::GetLastError();
-
- return SBOX_TEST_SUCCEEDED;
-}
-
-// New thread entry point: do nothing.
-DWORD WINAPI PolicyTargetTest_thread_main(void* param) {
- ::Sleep(INFINITE);
- return 0;
-}
-
-// Tests that we can create a new thread, and open it.
-SBOX_TESTS_COMMAND int PolicyTargetTest_thread2(int argc, wchar_t **argv) {
- // Use default values to create a new thread.
- DWORD thread_id;
- HANDLE thread = ::CreateThread(NULL, 0, &PolicyTargetTest_thread_main, 0, 0,
- &thread_id);
- if (!thread)
- return ::GetLastError();
- if (!::CloseHandle(thread))
- return ::GetLastError();
-
- thread = ::OpenThread(SYNCHRONIZE, FALSE, thread_id);
- if (!thread)
- return ::GetLastError();
-
- if (!::CloseHandle(thread))
- return ::GetLastError();
-
- return SBOX_TEST_SUCCEEDED;
-}
-
-// Tests that we can call CreateProcess.
-SBOX_TESTS_COMMAND int PolicyTargetTest_process(int argc, wchar_t **argv) {
- // Use default values to create a new process.
- STARTUPINFO startup_info = {0};
- startup_info.cb = sizeof(startup_info);
- PROCESS_INFORMATION temp_process_info = {};
- // Note: CreateProcessW() can write to its lpCommandLine, don't pass a
- // raw string literal.
- base::string16 writable_cmdline_str(L"foo.exe");
- if (!::CreateProcessW(L"foo.exe", &writable_cmdline_str[0], NULL, NULL, FALSE,
- 0, NULL, NULL, &startup_info, &temp_process_info))
- return SBOX_TEST_SUCCEEDED;
- base::win::ScopedProcessInformation process_info(temp_process_info);
- return SBOX_TEST_FAILED;
-}
-
-TEST(PolicyTargetTest, SetInformationThread) {
- TestRunner runner;
- if (base::win::GetVersion() >= base::win::VERSION_XP) {
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"PolicyTargetTest_token"));
- }
-
- runner.SetTestState(AFTER_REVERT);
- EXPECT_EQ(ERROR_NO_TOKEN, runner.RunTest(L"PolicyTargetTest_token"));
-
- runner.SetTestState(EVERY_STATE);
- if (base::win::GetVersion() >= base::win::VERSION_XP)
- EXPECT_EQ(SBOX_TEST_FAILED, runner.RunTest(L"PolicyTargetTest_steal"));
-}
-
-TEST(PolicyTargetTest, OpenThreadToken) {
- TestRunner runner;
- if (base::win::GetVersion() >= base::win::VERSION_XP) {
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"PolicyTargetTest_token2"));
- }
-
- runner.SetTestState(AFTER_REVERT);
- EXPECT_EQ(ERROR_NO_TOKEN, runner.RunTest(L"PolicyTargetTest_token2"));
-}
-
-TEST(PolicyTargetTest, OpenThreadTokenEx) {
- TestRunner runner;
- if (base::win::GetVersion() < base::win::VERSION_XP)
- return;
-
- runner.SetTestState(BEFORE_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"PolicyTargetTest_token3"));
-
- runner.SetTestState(AFTER_REVERT);
- EXPECT_EQ(ERROR_NO_TOKEN, runner.RunTest(L"PolicyTargetTest_token3"));
-}
-
-TEST(PolicyTargetTest, OpenThread) {
- TestRunner runner;
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"PolicyTargetTest_thread")) <<
- "Opens the current thread";
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"PolicyTargetTest_thread2")) <<
- "Creates a new thread and opens it";
-}
-
-TEST(PolicyTargetTest, OpenProcess) {
- TestRunner runner;
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"PolicyTargetTest_process")) <<
- "Opens a process";
-}
-
-// Launches the app in the sandbox and ask it to wait in an
-// infinite loop. Waits for 2 seconds and then check if the
-// desktop associated with the app thread is not the same as the
-// current desktop.
-TEST(PolicyTargetTest, DesktopPolicy) {
- BrokerServices* broker = GetBroker();
-
- // Precreate the desktop.
- TargetPolicy* temp_policy = broker->CreatePolicy();
- temp_policy->CreateAlternateDesktop(false);
- temp_policy->Release();
-
- ASSERT_TRUE(broker != NULL);
-
- // Get the path to the sandboxed app.
- wchar_t prog_name[MAX_PATH];
- GetModuleFileNameW(NULL, prog_name, MAX_PATH);
-
- base::string16 arguments(L"\"");
- arguments += prog_name;
- arguments += L"\" -child 0 wait"; // Don't care about the "state" argument.
-
- // Launch the app.
- ResultCode result = SBOX_ALL_OK;
- base::win::ScopedProcessInformation target;
-
- TargetPolicy* policy = broker->CreatePolicy();
- policy->SetAlternateDesktop(false);
- policy->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);
- PROCESS_INFORMATION temp_process_info = {};
- result = broker->SpawnTarget(prog_name, arguments.c_str(), policy,
- &temp_process_info);
- base::string16 desktop_name = policy->GetAlternateDesktop();
- policy->Release();
-
- EXPECT_EQ(SBOX_ALL_OK, result);
- if (result == SBOX_ALL_OK)
- target.Set(temp_process_info);
-
- EXPECT_EQ(1u, ::ResumeThread(target.thread_handle()));
-
- EXPECT_EQ(static_cast<DWORD>(WAIT_TIMEOUT),
- ::WaitForSingleObject(target.process_handle(), 2000));
-
- EXPECT_NE(::GetThreadDesktop(target.thread_id()),
- ::GetThreadDesktop(::GetCurrentThreadId()));
-
- HDESK desk = ::OpenDesktop(desktop_name.c_str(), 0, FALSE, DESKTOP_ENUMERATE);
- EXPECT_TRUE(NULL != desk);
- EXPECT_TRUE(::CloseDesktop(desk));
- EXPECT_TRUE(::TerminateProcess(target.process_handle(), 0));
-
- ::WaitForSingleObject(target.process_handle(), INFINITE);
-
- // Close the desktop handle.
- temp_policy = broker->CreatePolicy();
- temp_policy->DestroyAlternateDesktop();
- temp_policy->Release();
-
- // Make sure the desktop does not exist anymore.
- desk = ::OpenDesktop(desktop_name.c_str(), 0, FALSE, DESKTOP_ENUMERATE);
- EXPECT_TRUE(NULL == desk);
-}
-
-// Launches the app in the sandbox and ask it to wait in an
-// infinite loop. Waits for 2 seconds and then check if the
-// winstation associated with the app thread is not the same as the
-// current desktop.
-TEST(PolicyTargetTest, WinstaPolicy) {
- BrokerServices* broker = GetBroker();
-
- // Precreate the desktop.
- TargetPolicy* temp_policy = broker->CreatePolicy();
- temp_policy->CreateAlternateDesktop(true);
- temp_policy->Release();
-
- ASSERT_TRUE(broker != NULL);
-
- // Get the path to the sandboxed app.
- wchar_t prog_name[MAX_PATH];
- GetModuleFileNameW(NULL, prog_name, MAX_PATH);
-
- base::string16 arguments(L"\"");
- arguments += prog_name;
- arguments += L"\" -child 0 wait"; // Don't care about the "state" argument.
-
- // Launch the app.
- ResultCode result = SBOX_ALL_OK;
- base::win::ScopedProcessInformation target;
-
- TargetPolicy* policy = broker->CreatePolicy();
- policy->SetAlternateDesktop(true);
- policy->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);
- PROCESS_INFORMATION temp_process_info = {};
- result = broker->SpawnTarget(prog_name, arguments.c_str(), policy,
- &temp_process_info);
- base::string16 desktop_name = policy->GetAlternateDesktop();
- policy->Release();
-
- EXPECT_EQ(SBOX_ALL_OK, result);
- if (result == SBOX_ALL_OK)
- target.Set(temp_process_info);
-
- EXPECT_EQ(1u, ::ResumeThread(target.thread_handle()));
-
- EXPECT_EQ(static_cast<DWORD>(WAIT_TIMEOUT),
- ::WaitForSingleObject(target.process_handle(), 2000));
-
- EXPECT_NE(::GetThreadDesktop(target.thread_id()),
- ::GetThreadDesktop(::GetCurrentThreadId()));
-
- ASSERT_FALSE(desktop_name.empty());
-
- // Make sure there is a backslash, for the window station name.
- EXPECT_NE(desktop_name.find_first_of(L'\\'), base::string16::npos);
-
- // Isolate the desktop name.
- desktop_name = desktop_name.substr(desktop_name.find_first_of(L'\\') + 1);
-
- HDESK desk = ::OpenDesktop(desktop_name.c_str(), 0, FALSE, DESKTOP_ENUMERATE);
- // This should fail if the desktop is really on another window station.
- EXPECT_FALSE(NULL != desk);
- EXPECT_TRUE(::TerminateProcess(target.process_handle(), 0));
-
- ::WaitForSingleObject(target.process_handle(), INFINITE);
-
- // Close the desktop handle.
- temp_policy = broker->CreatePolicy();
- temp_policy->DestroyAlternateDesktop();
- temp_policy->Release();
-}
-
-// Launches the app in the sandbox and share a handle with it. The app should
-// be able to use the handle.
-TEST(PolicyTargetTest, ShareHandleTest) {
- // The way we share handles via STARTUPINFOEX does not work on XP.
- if (base::win::GetVersion() < base::win::VERSION_VISTA)
- return;
-
- BrokerServices* broker = GetBroker();
- ASSERT_TRUE(broker != NULL);
-
- base::StringPiece contents = "Hello World";
- std::string name = "TestSharedMemory";
- base::SharedMemoryCreateOptions options;
- options.size = contents.size();
- options.share_read_only = true;
- options.name_deprecated = &name;
- base::SharedMemory writable_shmem;
- ASSERT_TRUE(writable_shmem.Create(options));
- ASSERT_TRUE(writable_shmem.Map(options.size));
- memcpy(writable_shmem.memory(), contents.data(), contents.size());
-
- base::SharedMemory read_only_view;
- ASSERT_TRUE(read_only_view.Open(name, true));
-
- // Get the path to the sandboxed app.
- wchar_t prog_name[MAX_PATH];
- GetModuleFileNameW(NULL, prog_name, MAX_PATH);
-
- TargetPolicy* policy = broker->CreatePolicy();
- void* shared_handle =
- policy->AddHandleToShare(read_only_view.handle().GetHandle());
-
- base::string16 arguments(L"\"");
- arguments += prog_name;
- arguments += L"\" -child 0 shared_memory_handle ";
- arguments += base::UintToString16(base::win::HandleToUint32(shared_handle));
-
- // Launch the app.
- ResultCode result = SBOX_ALL_OK;
- base::win::ScopedProcessInformation target;
-
- policy->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);
- PROCESS_INFORMATION temp_process_info = {};
- result = broker->SpawnTarget(prog_name, arguments.c_str(), policy,
- &temp_process_info);
- policy->Release();
-
- EXPECT_EQ(SBOX_ALL_OK, result);
- if (result == SBOX_ALL_OK)
- target.Set(temp_process_info);
-
- EXPECT_EQ(1u, ::ResumeThread(target.thread_handle()));
-
- EXPECT_EQ(static_cast<DWORD>(WAIT_TIMEOUT),
- ::WaitForSingleObject(target.process_handle(), 2000));
-
- EXPECT_TRUE(::TerminateProcess(target.process_handle(), 0));
-
- ::WaitForSingleObject(target.process_handle(), INFINITE);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations.cc b/security/sandbox/chromium/sandbox/win/src/process_mitigations.cc
deleted file mode 100644
index 6ca8a8d7e..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations.cc
+++ /dev/null
@@ -1,333 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/process_mitigations.h"
-
-#include <stddef.h>
-
-#include <algorithm>
-
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/restricted_token_utils.h"
-#include "sandbox/win/src/sandbox_rand.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-// Functions for enabling policies.
-typedef BOOL (WINAPI *SetProcessDEPPolicyFunction)(DWORD dwFlags);
-
-typedef BOOL (WINAPI *SetProcessMitigationPolicyFunction)(
- PROCESS_MITIGATION_POLICY mitigation_policy,
- PVOID buffer,
- SIZE_T length);
-
-typedef BOOL (WINAPI *SetDefaultDllDirectoriesFunction)(
- DWORD DirectoryFlags);
-
-} // namespace
-
-namespace sandbox {
-
-bool ApplyProcessMitigationsToCurrentProcess(MitigationFlags flags) {
- if (!CanSetProcessMitigationsPostStartup(flags))
- return false;
-
- base::win::Version version = base::win::GetVersion();
- HMODULE module = ::GetModuleHandleA("kernel32.dll");
-
- if (version >= base::win::VERSION_VISTA &&
- (flags & MITIGATION_DLL_SEARCH_ORDER)) {
- SetDefaultDllDirectoriesFunction set_default_dll_directories =
- reinterpret_cast<SetDefaultDllDirectoriesFunction>(
- ::GetProcAddress(module, "SetDefaultDllDirectories"));
-
- // Check for SetDefaultDllDirectories since it requires KB2533623.
- if (set_default_dll_directories) {
- if (!set_default_dll_directories(LOAD_LIBRARY_SEARCH_DEFAULT_DIRS) &&
- ERROR_ACCESS_DENIED != ::GetLastError()) {
- return false;
- }
- }
- }
-
- // Set the heap to terminate on corruption
- if (version >= base::win::VERSION_VISTA &&
- (flags & MITIGATION_HEAP_TERMINATE)) {
- if (!::HeapSetInformation(NULL, HeapEnableTerminationOnCorruption,
- NULL, 0) &&
- ERROR_ACCESS_DENIED != ::GetLastError()) {
- return false;
- }
- }
-
- if (version >= base::win::VERSION_WIN7 &&
- (flags & MITIGATION_HARDEN_TOKEN_IL_POLICY)) {
- DWORD error = HardenProcessIntegrityLevelPolicy();
- if ((error != ERROR_SUCCESS) && (error != ERROR_ACCESS_DENIED))
- return false;
- }
-
-#if !defined(_WIN64) // DEP is always enabled on 64-bit.
- if (flags & MITIGATION_DEP) {
- DWORD dep_flags = PROCESS_DEP_ENABLE;
- // DEP support is quirky on XP, so don't force a failure in that case.
- const bool return_on_fail = version >= base::win::VERSION_VISTA;
-
- if (flags & MITIGATION_DEP_NO_ATL_THUNK)
- dep_flags |= PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION;
-
- SetProcessDEPPolicyFunction set_process_dep_policy =
- reinterpret_cast<SetProcessDEPPolicyFunction>(
- ::GetProcAddress(module, "SetProcessDEPPolicy"));
- if (set_process_dep_policy) {
- if (!set_process_dep_policy(dep_flags) &&
- ERROR_ACCESS_DENIED != ::GetLastError() && return_on_fail) {
- return false;
- }
- } else {
- // We're on XP sp2, so use the less standard approach.
- // For reference: http://www.uninformed.org/?v=2&a=4
- static const int MEM_EXECUTE_OPTION_DISABLE = 2;
- static const int MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION = 4;
- static const int MEM_EXECUTE_OPTION_PERMANENT = 8;
-
- NtSetInformationProcessFunction set_information_process = NULL;
- ResolveNTFunctionPtr("NtSetInformationProcess",
- &set_information_process);
- if (!set_information_process)
- return false;
- ULONG dep = MEM_EXECUTE_OPTION_DISABLE | MEM_EXECUTE_OPTION_PERMANENT;
- if (!(dep_flags & PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION))
- dep |= MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION;
- if (!SUCCEEDED(set_information_process(GetCurrentProcess(),
- ProcessExecuteFlags,
- &dep, sizeof(dep))) &&
- ERROR_ACCESS_DENIED != ::GetLastError() && return_on_fail) {
- return false;
- }
- }
- }
-#endif
-
- // This is all we can do in Win7 and below.
- if (version < base::win::VERSION_WIN8)
- return true;
-
- SetProcessMitigationPolicyFunction set_process_mitigation_policy =
- reinterpret_cast<SetProcessMitigationPolicyFunction>(
- ::GetProcAddress(module, "SetProcessMitigationPolicy"));
- if (!set_process_mitigation_policy)
- return false;
-
- // Enable ASLR policies.
- if (flags & MITIGATION_RELOCATE_IMAGE) {
- PROCESS_MITIGATION_ASLR_POLICY policy = {};
- policy.EnableForceRelocateImages = true;
- policy.DisallowStrippedImages = (flags &
- MITIGATION_RELOCATE_IMAGE_REQUIRED) ==
- MITIGATION_RELOCATE_IMAGE_REQUIRED;
-
- if (!set_process_mitigation_policy(ProcessASLRPolicy, &policy,
- sizeof(policy)) &&
- ERROR_ACCESS_DENIED != ::GetLastError()) {
- return false;
- }
- }
-
- // Enable strict handle policies.
- if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {
- PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY policy = {};
- policy.HandleExceptionsPermanentlyEnabled =
- policy.RaiseExceptionOnInvalidHandleReference = true;
-
- if (!set_process_mitigation_policy(ProcessStrictHandleCheckPolicy, &policy,
- sizeof(policy)) &&
- ERROR_ACCESS_DENIED != ::GetLastError()) {
- return false;
- }
- }
-
- // Enable system call policies.
- if (flags & MITIGATION_WIN32K_DISABLE) {
- PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy = {};
- policy.DisallowWin32kSystemCalls = true;
-
- if (!set_process_mitigation_policy(ProcessSystemCallDisablePolicy, &policy,
- sizeof(policy)) &&
- ERROR_ACCESS_DENIED != ::GetLastError()) {
- return false;
- }
- }
-
- // Enable system call policies.
- if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {
- PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY policy = {};
- policy.DisableExtensionPoints = true;
-
- if (!set_process_mitigation_policy(ProcessExtensionPointDisablePolicy,
- &policy, sizeof(policy)) &&
- ERROR_ACCESS_DENIED != ::GetLastError()) {
- return false;
- }
- }
-
- return true;
-}
-
-void ConvertProcessMitigationsToPolicy(MitigationFlags flags,
- DWORD64* policy_flags, size_t* size) {
- base::win::Version version = base::win::GetVersion();
-
- *policy_flags = 0;
-#if defined(_WIN64)
- *size = sizeof(*policy_flags);
-#elif defined(_M_IX86)
- // A 64-bit flags attribute is illegal on 32-bit Win 7 and below.
- if (version < base::win::VERSION_WIN8)
- *size = sizeof(DWORD);
- else
- *size = sizeof(*policy_flags);
-#else
-#error This platform is not supported.
-#endif
-
- // Nothing for Win XP or Vista.
- if (version <= base::win::VERSION_VISTA)
- return;
-
- // DEP and SEHOP are not valid for 64-bit Windows
-#if !defined(_WIN64)
- if (flags & MITIGATION_DEP) {
- *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE;
- if (!(flags & MITIGATION_DEP_NO_ATL_THUNK))
- *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE;
- }
-
- if (flags & MITIGATION_SEHOP)
- *policy_flags |= PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE;
-#endif
-
- // Win 7
- if (version < base::win::VERSION_WIN8)
- return;
-
- if (flags & MITIGATION_RELOCATE_IMAGE) {
- *policy_flags |=
- PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON;
- if (flags & MITIGATION_RELOCATE_IMAGE_REQUIRED) {
- *policy_flags |=
- PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS;
- }
- }
-
- if (flags & MITIGATION_HEAP_TERMINATE) {
- *policy_flags |=
- PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON;
- }
-
- if (flags & MITIGATION_BOTTOM_UP_ASLR) {
- *policy_flags |=
- PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON;
- }
-
- if (flags & MITIGATION_HIGH_ENTROPY_ASLR) {
- *policy_flags |=
- PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON;
- }
-
- if (flags & MITIGATION_STRICT_HANDLE_CHECKS) {
- *policy_flags |=
- PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON;
- }
-
- if (flags & MITIGATION_WIN32K_DISABLE) {
- *policy_flags |=
- PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON;
- }
-
- if (flags & MITIGATION_EXTENSION_DLL_DISABLE) {
- *policy_flags |=
- PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON;
- }
-}
-
-MitigationFlags FilterPostStartupProcessMitigations(MitigationFlags flags) {
- base::win::Version version = base::win::GetVersion();
-
- // Windows XP SP2+.
- if (version < base::win::VERSION_VISTA) {
- return flags & (MITIGATION_DEP |
- MITIGATION_DEP_NO_ATL_THUNK);
- }
-
- // Windows Vista
- if (version < base::win::VERSION_WIN7) {
- return flags & (MITIGATION_BOTTOM_UP_ASLR |
- MITIGATION_DLL_SEARCH_ORDER |
- MITIGATION_HEAP_TERMINATE);
- }
-
- // Windows 7.
- if (version < base::win::VERSION_WIN8) {
- return flags & (MITIGATION_BOTTOM_UP_ASLR |
- MITIGATION_DLL_SEARCH_ORDER |
- MITIGATION_HEAP_TERMINATE);
- }
-
- // Windows 8 and above.
- return flags & (MITIGATION_BOTTOM_UP_ASLR |
- MITIGATION_DLL_SEARCH_ORDER);
-}
-
-bool ApplyProcessMitigationsToSuspendedProcess(HANDLE process,
- MitigationFlags flags) {
-// This is a hack to fake a weak bottom-up ASLR on 32-bit Windows.
-#if !defined(_WIN64)
- if (flags & MITIGATION_BOTTOM_UP_ASLR) {
- unsigned int limit;
- GetRandom(&limit);
- char* ptr = 0;
- const size_t kMask64k = 0xFFFF;
- // Random range (512k-16.5mb) in 64k steps.
- const char* end = ptr + ((((limit % 16384) + 512) * 1024) & ~kMask64k);
- while (ptr < end) {
- MEMORY_BASIC_INFORMATION memory_info;
- if (!::VirtualQueryEx(process, ptr, &memory_info, sizeof(memory_info)))
- break;
- size_t size = std::min((memory_info.RegionSize + kMask64k) & ~kMask64k,
- static_cast<SIZE_T>(end - ptr));
- if (ptr && memory_info.State == MEM_FREE)
- ::VirtualAllocEx(process, ptr, size, MEM_RESERVE, PAGE_NOACCESS);
- ptr += size;
- }
- }
-#endif
-
- return true;
-}
-
-bool CanSetProcessMitigationsPostStartup(MitigationFlags flags) {
- // All of these mitigations can be enabled after startup.
- return !(flags & ~(MITIGATION_HEAP_TERMINATE |
- MITIGATION_DEP |
- MITIGATION_DEP_NO_ATL_THUNK |
- MITIGATION_RELOCATE_IMAGE |
- MITIGATION_RELOCATE_IMAGE_REQUIRED |
- MITIGATION_BOTTOM_UP_ASLR |
- MITIGATION_STRICT_HANDLE_CHECKS |
- MITIGATION_EXTENSION_DLL_DISABLE |
- MITIGATION_DLL_SEARCH_ORDER |
- MITIGATION_HARDEN_TOKEN_IL_POLICY));
-}
-
-bool CanSetProcessMitigationsPreStartup(MitigationFlags flags) {
- // These mitigations cannot be enabled prior to startup.
- return !(flags & (MITIGATION_STRICT_HANDLE_CHECKS |
- MITIGATION_DLL_SEARCH_ORDER));
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations.h b/security/sandbox/chromium/sandbox/win/src/process_mitigations.h
deleted file mode 100644
index 8bee0245a..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations.h
+++ /dev/null
@@ -1,44 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_WIN_PROCESS_MITIGATIONS_H_
-#define SANDBOX_SRC_WIN_PROCESS_MITIGATIONS_H_
-
-#include <windows.h>
-#include <stddef.h>
-
-#include "sandbox/win/src/security_level.h"
-
-namespace sandbox {
-
-// Sets the mitigation policy for the current process, ignoring any settings
-// that are invalid for the current version of Windows.
-bool ApplyProcessMitigationsToCurrentProcess(MitigationFlags flags);
-
-// Returns the flags that must be enforced after startup for the current OS
-// version.
-MitigationFlags FilterPostStartupProcessMitigations(MitigationFlags flags);
-
-// Converts sandbox flags to the PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES
-// policy flags used by UpdateProcThreadAttribute(). The size field varies
-// between a 32-bit and a 64-bit type based on the exact build and version of
-// Windows, so the returned size must be passed to UpdateProcThreadAttribute().
-void ConvertProcessMitigationsToPolicy(MitigationFlags flags,
- DWORD64* policy_flags, size_t* size);
-
-// Adds mitigations that need to be performed on the suspended target process
-// before execution begins.
-bool ApplyProcessMitigationsToSuspendedProcess(HANDLE process,
- MitigationFlags flags);
-
-// Returns true if all the supplied flags can be set after a process starts.
-bool CanSetProcessMitigationsPostStartup(MitigationFlags flags);
-
-// Returns true if all the supplied flags can be set before a process starts.
-bool CanSetProcessMitigationsPreStartup(MitigationFlags flags);
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_WIN_PROCESS_MITIGATIONS_H_
-
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations_test.cc b/security/sandbox/chromium/sandbox/win/src/process_mitigations_test.cc
deleted file mode 100644
index 080d8eca3..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations_test.cc
+++ /dev/null
@@ -1,252 +0,0 @@
-// 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/strings/stringprintf.h"
-#include "base/win/scoped_handle.h"
-
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/process_mitigations.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/target_services.h"
-#include "sandbox/win/src/win_utils.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-
-typedef BOOL (WINAPI *GetProcessDEPPolicyFunction)(
- HANDLE process,
- LPDWORD flags,
- PBOOL permanent);
-
-typedef BOOL (WINAPI *GetProcessMitigationPolicyFunction)(
- HANDLE process,
- PROCESS_MITIGATION_POLICY mitigation_policy,
- PVOID buffer,
- SIZE_T length);
-
-GetProcessMitigationPolicyFunction get_process_mitigation_policy;
-
-#if !defined(_WIN64)
-bool CheckWin8DepPolicy() {
- PROCESS_MITIGATION_DEP_POLICY policy = {};
- if (!get_process_mitigation_policy(::GetCurrentProcess(), ProcessDEPPolicy,
- &policy, sizeof(policy))) {
- return false;
- }
- return policy.Enable && policy.Permanent;
-}
-#endif // !defined(_WIN64)
-
-#if defined(NDEBUG)
-bool CheckWin8AslrPolicy() {
- PROCESS_MITIGATION_ASLR_POLICY policy = {};
- if (!get_process_mitigation_policy(::GetCurrentProcess(), ProcessASLRPolicy,
- &policy, sizeof(policy))) {
- return false;
- }
- return policy.EnableForceRelocateImages && policy.DisallowStrippedImages;
-}
-#endif // defined(NDEBUG)
-
-bool CheckWin8StrictHandlePolicy() {
- PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY policy = {};
- if (!get_process_mitigation_policy(::GetCurrentProcess(),
- ProcessStrictHandleCheckPolicy,
- &policy, sizeof(policy))) {
- return false;
- }
- return policy.RaiseExceptionOnInvalidHandleReference &&
- policy.HandleExceptionsPermanentlyEnabled;
-}
-
-bool CheckWin8Win32CallPolicy() {
- PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY policy = {};
- if (!get_process_mitigation_policy(::GetCurrentProcess(),
- ProcessSystemCallDisablePolicy,
- &policy, sizeof(policy))) {
- return false;
- }
- return policy.DisallowWin32kSystemCalls;
-}
-
-bool CheckWin8DllExtensionPolicy() {
- PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY policy = {};
- if (!get_process_mitigation_policy(::GetCurrentProcess(),
- ProcessExtensionPointDisablePolicy,
- &policy, sizeof(policy))) {
- return false;
- }
- return policy.DisableExtensionPoints;
-}
-
-} // namespace
-
-namespace sandbox {
-
-SBOX_TESTS_COMMAND int CheckWin8(int argc, wchar_t **argv) {
- get_process_mitigation_policy =
- reinterpret_cast<GetProcessMitigationPolicyFunction>(
- ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"),
- "GetProcessMitigationPolicy"));
- if (!get_process_mitigation_policy)
- return SBOX_TEST_NOT_FOUND;
-
-#if !defined(_WIN64) // DEP is always enabled on 64-bit.
- if (!CheckWin8DepPolicy())
- return SBOX_TEST_FIRST_ERROR;
-#endif
-
-#if defined(NDEBUG) // ASLR cannot be forced in debug builds.
- if (!CheckWin8AslrPolicy())
- return SBOX_TEST_SECOND_ERROR;
-#endif
-
- if (!CheckWin8StrictHandlePolicy())
- return SBOX_TEST_THIRD_ERROR;
-
- if (!CheckWin8DllExtensionPolicy())
- return SBOX_TEST_FIFTH_ERROR;
-
- return SBOX_TEST_SUCCEEDED;
-}
-
-TEST(ProcessMitigationsTest, CheckWin8) {
- if (base::win::GetVersion() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner;
- sandbox::TargetPolicy* policy = runner.GetPolicy();
-
- sandbox::MitigationFlags mitigations = MITIGATION_DEP |
- MITIGATION_DEP_NO_ATL_THUNK |
- MITIGATION_EXTENSION_DLL_DISABLE;
-#if defined(NDEBUG) // ASLR cannot be forced in debug builds.
- mitigations |= MITIGATION_RELOCATE_IMAGE |
- MITIGATION_RELOCATE_IMAGE_REQUIRED;
-#endif
-
- EXPECT_EQ(policy->SetProcessMitigations(mitigations), SBOX_ALL_OK);
-
- mitigations |= MITIGATION_STRICT_HANDLE_CHECKS;
-
- EXPECT_EQ(policy->SetDelayedProcessMitigations(mitigations), SBOX_ALL_OK);
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"CheckWin8"));
-}
-
-
-SBOX_TESTS_COMMAND int CheckDep(int argc, wchar_t **argv) {
- GetProcessDEPPolicyFunction get_process_dep_policy =
- reinterpret_cast<GetProcessDEPPolicyFunction>(
- ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"),
- "GetProcessDEPPolicy"));
- if (get_process_dep_policy) {
- BOOL is_permanent = FALSE;
- DWORD dep_flags = 0;
-
- if (!get_process_dep_policy(::GetCurrentProcess(), &dep_flags,
- &is_permanent)) {
- return SBOX_TEST_FIRST_ERROR;
- }
-
- if (!(dep_flags & PROCESS_DEP_ENABLE) || !is_permanent)
- return SBOX_TEST_SECOND_ERROR;
-
- } else {
- NtQueryInformationProcessFunction query_information_process = NULL;
- ResolveNTFunctionPtr("NtQueryInformationProcess",
- &query_information_process);
- if (!query_information_process)
- return SBOX_TEST_NOT_FOUND;
-
- ULONG size = 0;
- ULONG dep_flags = 0;
- if (!SUCCEEDED(query_information_process(::GetCurrentProcess(),
- ProcessExecuteFlags, &dep_flags,
- sizeof(dep_flags), &size))) {
- return SBOX_TEST_THIRD_ERROR;
- }
-
- static const int MEM_EXECUTE_OPTION_DISABLE = 2;
- static const int MEM_EXECUTE_OPTION_PERMANENT = 8;
- dep_flags &= 0xff;
-
- if (dep_flags != (MEM_EXECUTE_OPTION_DISABLE |
- MEM_EXECUTE_OPTION_PERMANENT)) {
- return SBOX_TEST_FOURTH_ERROR;
- }
- }
-
- return SBOX_TEST_SUCCEEDED;
-}
-
-#if !defined(_WIN64) // DEP is always enabled on 64-bit.
-TEST(ProcessMitigationsTest, CheckDep) {
- if (base::win::GetVersion() > base::win::VERSION_WIN7)
- return;
-
- TestRunner runner;
- sandbox::TargetPolicy* policy = runner.GetPolicy();
-
- EXPECT_EQ(policy->SetProcessMitigations(
- MITIGATION_DEP |
- MITIGATION_DEP_NO_ATL_THUNK |
- MITIGATION_SEHOP),
- SBOX_ALL_OK);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"CheckDep"));
-}
-#endif
-
-SBOX_TESTS_COMMAND int CheckWin8Lockdown(int argc, wchar_t **argv) {
- get_process_mitigation_policy =
- reinterpret_cast<GetProcessMitigationPolicyFunction>(
- ::GetProcAddress(::GetModuleHandleW(L"kernel32.dll"),
- "GetProcessMitigationPolicy"));
- if (!get_process_mitigation_policy)
- return SBOX_TEST_NOT_FOUND;
-
- if (!CheckWin8Win32CallPolicy())
- return SBOX_TEST_FIRST_ERROR;
- return SBOX_TEST_SUCCEEDED;
-}
-
-// This test validates that setting the MITIGATION_WIN32K_DISABLE mitigation on
-// the target process causes the launch to fail in process initialization.
-// The test process itself links against user32/gdi32.
-TEST(ProcessMitigationsTest, CheckWin8Win32KLockDownFailure) {
- if (base::win::GetVersion() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner;
- sandbox::TargetPolicy* policy = runner.GetPolicy();
-
- EXPECT_EQ(policy->SetProcessMitigations(MITIGATION_WIN32K_DISABLE),
- SBOX_ALL_OK);
- EXPECT_NE(SBOX_TEST_SUCCEEDED, runner.RunTest(L"CheckWin8Lockdown"));
-}
-
-// This test validates that setting the MITIGATION_WIN32K_DISABLE mitigation
-// along with the policy to fake user32 and gdi32 initialization successfully
-// launches the target process.
-// The test process itself links against user32/gdi32.
-TEST(ProcessMitigationsTest, CheckWin8Win32KLockDownSuccess) {
- if (base::win::GetVersion() < base::win::VERSION_WIN8)
- return;
-
- TestRunner runner;
- sandbox::TargetPolicy* policy = runner.GetPolicy();
-
- EXPECT_EQ(policy->SetProcessMitigations(MITIGATION_WIN32K_DISABLE),
- SBOX_ALL_OK);
- EXPECT_EQ(policy->AddRule(sandbox::TargetPolicy::SUBSYS_WIN32K_LOCKDOWN,
- sandbox::TargetPolicy::FAKE_USER_GDI_INIT, NULL),
- sandbox::SBOX_ALL_OK);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"CheckWin8Lockdown"));
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc b/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc
deleted file mode 100644
index e426084f8..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2014 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 "sandbox/win/src/process_mitigations_win32k_dispatcher.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/process_mitigations_win32k_interception.h"
-
-namespace sandbox {
-
-ProcessMitigationsWin32KDispatcher::ProcessMitigationsWin32KDispatcher(
- PolicyBase* policy_base)
- : policy_base_(policy_base) {
-}
-
-bool ProcessMitigationsWin32KDispatcher::SetupService(
- InterceptionManager* manager, int service) {
- if (!(policy_base_->GetProcessMitigations() &
- sandbox::MITIGATION_WIN32K_DISABLE)) {
- return false;
- }
-
- switch (service) {
- case IPC_GDI_GDIDLLINITIALIZE_TAG: {
- if (!INTERCEPT_EAT(manager, L"gdi32.dll", GdiDllInitialize,
- GDIINITIALIZE_ID, 12)) {
- return false;
- }
- return true;
- }
-
- case IPC_GDI_GETSTOCKOBJECT_TAG: {
- if (!INTERCEPT_EAT(manager, L"gdi32.dll", GetStockObject,
- GETSTOCKOBJECT_ID, 8)) {
- return false;
- }
- return true;
- }
-
- case IPC_USER_REGISTERCLASSW_TAG: {
- if (!INTERCEPT_EAT(manager, L"user32.dll", RegisterClassW,
- REGISTERCLASSW_ID, 8)) {
- return false;
- }
- return true;
- }
-
- default:
- break;
- }
- return false;
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.h b/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.h
deleted file mode 100644
index 55a84a76e..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.h
+++ /dev/null
@@ -1,31 +0,0 @@
-// Copyright 2014 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 SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_DISPATCHER_H_
-#define SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_DISPATCHER_H_
-
-#include "base/macros.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-namespace sandbox {
-
-// This class sets up intercepts for the Win32K lockdown policy which is set
-// on Windows 8 and beyond.
-class ProcessMitigationsWin32KDispatcher : public Dispatcher {
- public:
- explicit ProcessMitigationsWin32KDispatcher(PolicyBase* policy_base);
- ~ProcessMitigationsWin32KDispatcher() override {}
-
- // Dispatcher interface.
- bool SetupService(InterceptionManager* manager, int service) override;
-
- private:
- PolicyBase* policy_base_;
-
- DISALLOW_COPY_AND_ASSIGN(ProcessMitigationsWin32KDispatcher);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_DISPATCHER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_interception.cc b/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_interception.cc
deleted file mode 100644
index ee24fbf43..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_interception.cc
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2014 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 "sandbox/win/src/process_mitigations_win32k_interception.h"
-
-namespace sandbox {
-
-BOOL WINAPI TargetGdiDllInitialize(
- GdiDllInitializeFunction orig_gdi_dll_initialize,
- HANDLE dll,
- DWORD reason) {
- return TRUE;
-}
-
-HGDIOBJ WINAPI TargetGetStockObject(
- GetStockObjectFunction orig_get_stock_object,
- int object) {
- return reinterpret_cast<HGDIOBJ>(NULL);
-}
-
-ATOM WINAPI TargetRegisterClassW(
- RegisterClassWFunction orig_register_class_function,
- const WNDCLASS* wnd_class) {
- return TRUE;
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_interception.h b/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_interception.h
deleted file mode 100644
index 0b295eacd..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_interception.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2014 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 SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_INTERCEPTION_H_
-#define SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_INTERCEPTION_H_
-
-#include <windows.h>
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace sandbox {
-
-extern "C" {
-
-typedef BOOL (WINAPI* GdiDllInitializeFunction) (
- HANDLE dll,
- DWORD reason,
- LPVOID reserved);
-
-typedef HGDIOBJ (WINAPI *GetStockObjectFunction) (int object);
-
-typedef ATOM (WINAPI *RegisterClassWFunction) (const WNDCLASS* wnd_class);
-
-// Interceptor for the GdiDllInitialize function.
-SANDBOX_INTERCEPT BOOL WINAPI TargetGdiDllInitialize(
- GdiDllInitializeFunction orig_gdi_dll_initialize,
- HANDLE dll,
- DWORD reason);
-
-// Interceptor for the GetStockObject function.
-SANDBOX_INTERCEPT HGDIOBJ WINAPI TargetGetStockObject(
- GetStockObjectFunction orig_get_stock_object,
- int object);
-
-// Interceptor for the RegisterClassW function.
-SANDBOX_INTERCEPT ATOM WINAPI TargetRegisterClassW(
- RegisterClassWFunction orig_register_class_function,
- const WNDCLASS* wnd_class);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_INTERCEPTION_H_
-
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_policy.cc b/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_policy.cc
deleted file mode 100644
index af18c5413..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_policy.cc
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright 2014 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 "sandbox/win/src/process_mitigations_win32k_policy.h"
-
-namespace sandbox {
-
-bool ProcessMitigationsWin32KLockdownPolicy::GenerateRules(
- const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy) {
- PolicyRule rule(FAKE_SUCCESS);
- if (!policy->AddRule(IPC_GDI_GDIDLLINITIALIZE_TAG, &rule))
- return false;
- if (!policy->AddRule(IPC_GDI_GETSTOCKOBJECT_TAG, &rule))
- return false;
- if (!policy->AddRule(IPC_USER_REGISTERCLASSW_TAG, &rule))
- return false;
- return true;
-}
-
-} // namespace sandbox
-
diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_policy.h b/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_policy.h
deleted file mode 100644
index 32af16864..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_mitigations_win32k_policy.h
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright 2014 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 SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_POLICY_H_
-#define SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_POLICY_H_
-
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/sandbox_policy.h"
-
-namespace sandbox {
-
-enum EvalResult;
-
-// This class centralizes most of the knowledge related to the process
-// mitigations Win32K lockdown policy.
-class ProcessMitigationsWin32KLockdownPolicy {
- public:
- // Creates the required low-level policy rules to evaluate a high-level
- // policy rule for the Win32K process mitigation policy.
- // name is the object name, semantics is the desired semantics for the
- // open or create and policy is the policy generator to which the rules are
- // going to be added.
- static bool GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_PROCESS_MITIGATIONS_WIN32K_POLICY_H_
-
-
diff --git a/security/sandbox/chromium/sandbox/win/src/process_policy_test.cc b/security/sandbox/chromium/sandbox/win/src/process_policy_test.cc
deleted file mode 100644
index 44effa363..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_policy_test.cc
+++ /dev/null
@@ -1,385 +0,0 @@
-// 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.
-
-#include <memory>
-#include <string>
-
-#include "base/strings/string16.h"
-#include "base/strings/sys_string_conversions.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/scoped_process_information.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-
-// While the shell API provides better calls than this home brew function
-// we use GetSystemWindowsDirectoryW which does not query the registry so
-// it is safe to use after revert.
-base::string16 MakeFullPathToSystem32(const wchar_t* name) {
- wchar_t windows_path[MAX_PATH] = {0};
- ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH);
- base::string16 full_path(windows_path);
- if (full_path.empty()) {
- return full_path;
- }
- full_path += L"\\system32\\";
- full_path += name;
- return full_path;
-}
-
-// Creates a process with the |exe| and |command| parameter using the
-// unicode and ascii version of the api.
-sandbox::SboxTestResult CreateProcessHelper(const base::string16& exe,
- const base::string16& command) {
- base::win::ScopedProcessInformation pi;
- STARTUPINFOW si = {sizeof(si)};
-
- const wchar_t *exe_name = NULL;
- if (!exe.empty())
- exe_name = exe.c_str();
-
- base::string16 writable_command = command;
-
- // Create the process with the unicode version of the API.
- sandbox::SboxTestResult ret1 = sandbox::SBOX_TEST_FAILED;
- PROCESS_INFORMATION temp_process_info = {};
- if (::CreateProcessW(exe_name,
- command.empty() ? NULL : &writable_command[0],
- NULL,
- NULL,
- FALSE,
- 0,
- NULL,
- NULL,
- &si,
- &temp_process_info)) {
- pi.Set(temp_process_info);
- ret1 = sandbox::SBOX_TEST_SUCCEEDED;
- } else {
- DWORD last_error = GetLastError();
- if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
- (ERROR_ACCESS_DENIED == last_error) ||
- (ERROR_FILE_NOT_FOUND == last_error)) {
- ret1 = sandbox::SBOX_TEST_DENIED;
- } else {
- ret1 = sandbox::SBOX_TEST_FAILED;
- }
- }
-
- pi.Close();
-
- // Do the same with the ansi version of the api
- STARTUPINFOA sia = {sizeof(sia)};
- sandbox::SboxTestResult ret2 = sandbox::SBOX_TEST_FAILED;
-
- std::string narrow_cmd_line =
- base::SysWideToMultiByte(command.c_str(), CP_UTF8);
- if (::CreateProcessA(
- exe_name ? base::SysWideToMultiByte(exe_name, CP_UTF8).c_str() : NULL,
- command.empty() ? NULL : &narrow_cmd_line[0],
- NULL, NULL, FALSE, 0, NULL, NULL, &sia, &temp_process_info)) {
- pi.Set(temp_process_info);
- ret2 = sandbox::SBOX_TEST_SUCCEEDED;
- } else {
- DWORD last_error = GetLastError();
- if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||
- (ERROR_ACCESS_DENIED == last_error) ||
- (ERROR_FILE_NOT_FOUND == last_error)) {
- ret2 = sandbox::SBOX_TEST_DENIED;
- } else {
- ret2 = sandbox::SBOX_TEST_FAILED;
- }
- }
-
- if (ret1 == ret2)
- return ret1;
-
- return sandbox::SBOX_TEST_FAILED;
-}
-
-} // namespace
-
-namespace sandbox {
-
-SBOX_TESTS_COMMAND int Process_RunApp1(int argc, wchar_t **argv) {
- if (argc != 1) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- if ((NULL == argv) || (NULL == argv[0])) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- base::string16 path = MakeFullPathToSystem32(argv[0]);
-
- // TEST 1: Try with the path in the app_name.
- return CreateProcessHelper(path, base::string16());
-}
-
-SBOX_TESTS_COMMAND int Process_RunApp2(int argc, wchar_t **argv) {
- if (argc != 1) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- if ((NULL == argv) || (NULL == argv[0])) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- base::string16 path = MakeFullPathToSystem32(argv[0]);
-
- // TEST 2: Try with the path in the cmd_line.
- base::string16 cmd_line = L"\"";
- cmd_line += path;
- cmd_line += L"\"";
- return CreateProcessHelper(base::string16(), cmd_line);
-}
-
-SBOX_TESTS_COMMAND int Process_RunApp3(int argc, wchar_t **argv) {
- if (argc != 1) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- if ((NULL == argv) || (NULL == argv[0])) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
-
- // TEST 3: Try file name in the cmd_line.
- return CreateProcessHelper(base::string16(), argv[0]);
-}
-
-SBOX_TESTS_COMMAND int Process_RunApp4(int argc, wchar_t **argv) {
- if (argc != 1) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- if ((NULL == argv) || (NULL == argv[0])) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
-
- // TEST 4: Try file name in the app_name and current directory sets correctly.
- base::string16 system32 = MakeFullPathToSystem32(L"");
- wchar_t current_directory[MAX_PATH + 1];
- DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
- if (!ret)
- return SBOX_TEST_FIRST_ERROR;
- if (ret >= MAX_PATH)
- return SBOX_TEST_FAILED;
-
- current_directory[ret] = L'\\';
- current_directory[ret+1] = L'\0';
- if (!::SetCurrentDirectory(system32.c_str())) {
- return SBOX_TEST_SECOND_ERROR;
- }
-
- const int result4 = CreateProcessHelper(argv[0], base::string16());
- return ::SetCurrentDirectory(current_directory) ? result4 : SBOX_TEST_FAILED;
-}
-
-SBOX_TESTS_COMMAND int Process_RunApp5(int argc, wchar_t **argv) {
- if (argc != 1) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- if ((NULL == argv) || (NULL == argv[0])) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- base::string16 path = MakeFullPathToSystem32(argv[0]);
-
- // TEST 5: Try with the path in the cmd_line and arguments.
- base::string16 cmd_line = L"\"";
- cmd_line += path;
- cmd_line += L"\" /I";
- return CreateProcessHelper(base::string16(), cmd_line);
-}
-
-SBOX_TESTS_COMMAND int Process_RunApp6(int argc, wchar_t **argv) {
- if (argc != 1) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
- if ((NULL == argv) || (NULL == argv[0])) {
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
- }
-
- // TEST 6: Try with the file_name in the cmd_line and arguments.
- base::string16 cmd_line = argv[0];
- cmd_line += L" /I";
- return CreateProcessHelper(base::string16(), cmd_line);
-}
-
-// Creates a process and checks if it's possible to get a handle to it's token.
-SBOX_TESTS_COMMAND int Process_GetChildProcessToken(int argc, wchar_t **argv) {
- if (argc != 1)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- if ((NULL == argv) || (NULL == argv[0]))
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- base::string16 path = MakeFullPathToSystem32(argv[0]);
-
- STARTUPINFOW si = {sizeof(si)};
-
- PROCESS_INFORMATION temp_process_info = {};
- if (!::CreateProcessW(path.c_str(), NULL, NULL, NULL, FALSE, CREATE_SUSPENDED,
- NULL, NULL, &si, &temp_process_info)) {
- return SBOX_TEST_FAILED;
- }
- base::win::ScopedProcessInformation pi(temp_process_info);
-
- HANDLE token = NULL;
- BOOL result =
- ::OpenProcessToken(pi.process_handle(), TOKEN_IMPERSONATE, &token);
- DWORD error = ::GetLastError();
-
- base::win::ScopedHandle token_handle(token);
-
- if (!::TerminateProcess(pi.process_handle(), 0))
- return SBOX_TEST_FAILED;
-
- if (result && token)
- return SBOX_TEST_SUCCEEDED;
-
- if (ERROR_ACCESS_DENIED == error)
- return SBOX_TEST_DENIED;
-
- return SBOX_TEST_FAILED;
-}
-
-
-SBOX_TESTS_COMMAND int Process_OpenToken(int argc, wchar_t **argv) {
- HANDLE token;
- if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {
- if (ERROR_ACCESS_DENIED == ::GetLastError()) {
- return SBOX_TEST_DENIED;
- }
- } else {
- ::CloseHandle(token);
- return SBOX_TEST_SUCCEEDED;
- }
-
- return SBOX_TEST_FAILED;
-}
-
-TEST(ProcessPolicyTest, TestAllAccess) {
- // Check if the "all access" rule fails to be added when the token is too
- // powerful.
- TestRunner runner;
-
- // Check the failing case.
- runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);
- EXPECT_EQ(SBOX_ERROR_UNSUPPORTED,
- runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
- TargetPolicy::PROCESS_ALL_EXEC,
- L"this is not important"));
-
- // Check the working case.
- runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_INTERACTIVE);
-
- EXPECT_EQ(SBOX_ALL_OK,
- runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,
- TargetPolicy::PROCESS_ALL_EXEC,
- L"this is not important"));
-}
-
-TEST(ProcessPolicyTest, CreateProcessAW) {
- TestRunner runner;
- base::string16 exe_path = MakeFullPathToSystem32(L"findstr.exe");
- base::string16 system32 = MakeFullPathToSystem32(L"");
- ASSERT_TRUE(!exe_path.empty());
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
- TargetPolicy::PROCESS_MIN_EXEC,
- exe_path.c_str()));
-
- // Need to add directory rules for the directories that we use in
- // SetCurrentDirectory.
- EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
- system32.c_str()));
-
- wchar_t current_directory[MAX_PATH];
- DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);
- ASSERT_TRUE(0 != ret && ret < MAX_PATH);
-
- wcscat_s(current_directory, MAX_PATH, L"\\");
- EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,
- current_directory));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp1 calc.exe"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp2 calc.exe"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp3 calc.exe"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp5 calc.exe"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Process_RunApp6 calc.exe"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"Process_RunApp1 findstr.exe"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"Process_RunApp2 findstr.exe"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"Process_RunApp3 findstr.exe"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"Process_RunApp5 findstr.exe"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"Process_RunApp6 findstr.exe"));
-
-#if !defined(_WIN64)
- if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_VISTA) {
- // WinXP results are not reliable.
- EXPECT_EQ(SBOX_TEST_SECOND_ERROR,
- runner.RunTest(L"Process_RunApp4 calc.exe"));
- EXPECT_EQ(SBOX_TEST_SECOND_ERROR,
- runner.RunTest(L"Process_RunApp4 findstr.exe"));
- }
-#endif
-}
-
-TEST(ProcessPolicyTest, OpenToken) {
- TestRunner runner;
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Process_OpenToken"));
-}
-
-TEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) {
- TestRunner runner;
- base::string16 exe_path = MakeFullPathToSystem32(L"findstr.exe");
- ASSERT_TRUE(!exe_path.empty());
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
- TargetPolicy::PROCESS_MIN_EXEC,
- exe_path.c_str()));
-
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
-}
-
-TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) {
- TestRunner runner(JOB_UNPROTECTED, USER_INTERACTIVE, USER_INTERACTIVE);
- base::string16 exe_path = MakeFullPathToSystem32(L"findstr.exe");
- ASSERT_TRUE(!exe_path.empty());
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
- TargetPolicy::PROCESS_ALL_EXEC,
- exe_path.c_str()));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
-}
-
-TEST(ProcessPolicyTest, TestGetProcessTokenMinAccessNoJob) {
- TestRunner runner(JOB_NONE, USER_RESTRICTED_SAME_ACCESS, USER_LOCKDOWN);
- base::string16 exe_path = MakeFullPathToSystem32(L"findstr.exe");
- ASSERT_TRUE(!exe_path.empty());
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
- TargetPolicy::PROCESS_MIN_EXEC,
- exe_path.c_str()));
-
- EXPECT_EQ(SBOX_TEST_DENIED,
- runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
-}
-
-TEST(ProcessPolicyTest, TestGetProcessTokenMaxAccessNoJob) {
- TestRunner runner(JOB_NONE, USER_INTERACTIVE, USER_INTERACTIVE);
- base::string16 exe_path = MakeFullPathToSystem32(L"findstr.exe");
- ASSERT_TRUE(!exe_path.empty());
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,
- TargetPolicy::PROCESS_ALL_EXEC,
- exe_path.c_str()));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED,
- runner.RunTest(L"Process_GetChildProcessToken findstr.exe"));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/process_thread_dispatcher.cc b/security/sandbox/chromium/sandbox/win/src/process_thread_dispatcher.cc
deleted file mode 100644
index 8debd1e0f..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_thread_dispatcher.cc
+++ /dev/null
@@ -1,247 +0,0 @@
-// Copyright (c) 2013 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 "sandbox/win/src/process_thread_dispatcher.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/logging.h"
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_broker.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/process_thread_interception.h"
-#include "sandbox/win/src/process_thread_policy.h"
-#include "sandbox/win/src/sandbox.h"
-
-namespace {
-
-// Extracts the application name from a command line.
-//
-// The application name is the first element of the command line. If
-// there is no quotes, the first element is delimited by the first space.
-// If there are quotes, the first element is delimited by the quotes.
-//
-// The create process call is smarter than us. It tries really hard to launch
-// the process even if the command line is wrong. For example:
-// "c:\program files\test param" will first try to launch c:\program.exe then
-// c:\program files\test.exe. We don't do that, we stop after at the first
-// space when there is no quotes.
-base::string16 GetPathFromCmdLine(const base::string16 &cmd_line) {
- base::string16 exe_name;
- // Check if it starts with '"'.
- if (cmd_line[0] == L'\"') {
- // Find the position of the second '"', this terminates the path.
- base::string16::size_type pos = cmd_line.find(L'\"', 1);
- if (base::string16::npos == pos)
- return cmd_line;
- exe_name = cmd_line.substr(1, pos - 1);
- } else {
- // There is no '"', that means that the appname is terminated at the
- // first space.
- base::string16::size_type pos = cmd_line.find(L' ');
- if (base::string16::npos == pos) {
- // There is no space, the cmd_line contains only the app_name
- exe_name = cmd_line;
- } else {
- exe_name = cmd_line.substr(0, pos);
- }
- }
-
- return exe_name;
-}
-
-// Returns true is the path in parameter is relative. False if it's
-// absolute.
-bool IsPathRelative(const base::string16 &path) {
- // A path is Relative if it's not a UNC path beginnning with \\ or a
- // path beginning with a drive. (i.e. X:\)
- if (path.find(L"\\\\") == 0 || path.find(L":\\") == 1)
- return false;
- return true;
-}
-
-// Converts a relative path to an absolute path.
-bool ConvertToAbsolutePath(const base::string16& child_current_directory,
- bool use_env_path, base::string16 *path) {
- wchar_t file_buffer[MAX_PATH];
- wchar_t *file_part = NULL;
-
- // Here we should start by looking at the path where the child application was
- // started. We don't have this information yet.
- DWORD result = 0;
- if (use_env_path) {
- // Try with the complete path
- result = ::SearchPath(NULL, path->c_str(), NULL, MAX_PATH, file_buffer,
- &file_part);
- }
-
- if (0 == result) {
- // Try with the current directory of the child
- result = ::SearchPath(child_current_directory.c_str(), path->c_str(), NULL,
- MAX_PATH, file_buffer, &file_part);
- }
-
- if (0 == result || result >= MAX_PATH)
- return false;
-
- *path = file_buffer;
- return true;
-}
-
-} // namespace
-namespace sandbox {
-
-ThreadProcessDispatcher::ThreadProcessDispatcher(PolicyBase* policy_base)
- : policy_base_(policy_base) {
- static const IPCCall open_thread = {
- {IPC_NTOPENTHREAD_TAG, {UINT32_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &ThreadProcessDispatcher::NtOpenThread)};
-
- static const IPCCall open_process = {
- {IPC_NTOPENPROCESS_TAG, {UINT32_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &ThreadProcessDispatcher::NtOpenProcess)};
-
- static const IPCCall process_token = {
- {IPC_NTOPENPROCESSTOKEN_TAG, {VOIDPTR_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &ThreadProcessDispatcher::NtOpenProcessToken)};
-
- static const IPCCall process_tokenex = {
- {IPC_NTOPENPROCESSTOKENEX_TAG, {VOIDPTR_TYPE, UINT32_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &ThreadProcessDispatcher::NtOpenProcessTokenEx)};
-
- static const IPCCall create_params = {
- {IPC_CREATEPROCESSW_TAG,
- {WCHAR_TYPE, WCHAR_TYPE, WCHAR_TYPE, INOUTPTR_TYPE}},
- reinterpret_cast<CallbackGeneric>(
- &ThreadProcessDispatcher::CreateProcessW)};
-
- ipc_calls_.push_back(open_thread);
- ipc_calls_.push_back(open_process);
- ipc_calls_.push_back(process_token);
- ipc_calls_.push_back(process_tokenex);
- ipc_calls_.push_back(create_params);
-}
-
-bool ThreadProcessDispatcher::SetupService(InterceptionManager* manager,
- int service) {
- switch (service) {
- case IPC_NTOPENTHREAD_TAG:
- case IPC_NTOPENPROCESS_TAG:
- case IPC_NTOPENPROCESSTOKEN_TAG:
- case IPC_NTOPENPROCESSTOKENEX_TAG:
- // There is no explicit policy for these services.
- NOTREACHED();
- return false;
-
- case IPC_CREATEPROCESSW_TAG:
- return INTERCEPT_EAT(manager, kKerneldllName, CreateProcessW,
- CREATE_PROCESSW_ID, 44) &&
- INTERCEPT_EAT(manager, L"kernel32.dll", CreateProcessA,
- CREATE_PROCESSA_ID, 44);
-
- default:
- return false;
- }
-}
-
-bool ThreadProcessDispatcher::NtOpenThread(IPCInfo* ipc,
- uint32_t desired_access,
- uint32_t thread_id) {
- HANDLE handle;
- NTSTATUS ret = ProcessPolicy::OpenThreadAction(*ipc->client_info,
- desired_access, thread_id,
- &handle);
- ipc->return_info.nt_status = ret;
- ipc->return_info.handle = handle;
- return true;
-}
-
-bool ThreadProcessDispatcher::NtOpenProcess(IPCInfo* ipc,
- uint32_t desired_access,
- uint32_t process_id) {
- HANDLE handle;
- NTSTATUS ret = ProcessPolicy::OpenProcessAction(*ipc->client_info,
- desired_access, process_id,
- &handle);
- ipc->return_info.nt_status = ret;
- ipc->return_info.handle = handle;
- return true;
-}
-
-bool ThreadProcessDispatcher::NtOpenProcessToken(IPCInfo* ipc,
- HANDLE process,
- uint32_t desired_access) {
- HANDLE handle;
- NTSTATUS ret = ProcessPolicy::OpenProcessTokenAction(*ipc->client_info,
- process, desired_access,
- &handle);
- ipc->return_info.nt_status = ret;
- ipc->return_info.handle = handle;
- return true;
-}
-
-bool ThreadProcessDispatcher::NtOpenProcessTokenEx(IPCInfo* ipc,
- HANDLE process,
- uint32_t desired_access,
- uint32_t attributes) {
- HANDLE handle;
- NTSTATUS ret = ProcessPolicy::OpenProcessTokenExAction(*ipc->client_info,
- process,
- desired_access,
- attributes, &handle);
- ipc->return_info.nt_status = ret;
- ipc->return_info.handle = handle;
- return true;
-}
-
-bool ThreadProcessDispatcher::CreateProcessW(IPCInfo* ipc, base::string16* name,
- base::string16* cmd_line,
- base::string16* cur_dir,
- CountedBuffer* info) {
- if (sizeof(PROCESS_INFORMATION) != info->Size())
- return false;
-
- // Check if there is an application name.
- base::string16 exe_name;
- if (!name->empty())
- exe_name = *name;
- else
- exe_name = GetPathFromCmdLine(*cmd_line);
-
- if (IsPathRelative(exe_name)) {
- if (!ConvertToAbsolutePath(*cur_dir, name->empty(), &exe_name)) {
- // Cannot find the path. Maybe the file does not exist.
- ipc->return_info.win32_result = ERROR_FILE_NOT_FOUND;
- return true;
- }
- }
-
- const wchar_t* const_exe_name = exe_name.c_str();
- CountedParameterSet<NameBased> params;
- params[NameBased::NAME] = ParamPickerMake(const_exe_name);
-
- EvalResult eval = policy_base_->EvalPolicy(IPC_CREATEPROCESSW_TAG,
- params.GetBase());
-
- PROCESS_INFORMATION* proc_info =
- reinterpret_cast<PROCESS_INFORMATION*>(info->Buffer());
- // Here we force the app_name to be the one we used for the policy lookup.
- // If our logic was wrong, at least we wont allow create a random process.
- DWORD ret = ProcessPolicy::CreateProcessWAction(eval, *ipc->client_info,
- exe_name, *cmd_line,
- proc_info);
-
- ipc->return_info.win32_result = ret;
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/process_thread_dispatcher.h b/security/sandbox/chromium/sandbox/win/src/process_thread_dispatcher.h
deleted file mode 100644
index 008385f42..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_thread_dispatcher.h
+++ /dev/null
@@ -1,59 +0,0 @@
-// 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 SANDBOX_SRC_PROCESS_THREAD_DISPATCHER_H_
-#define SANDBOX_SRC_PROCESS_THREAD_DISPATCHER_H_
-
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-namespace sandbox {
-
-// This class handles process and thread-related IPC calls.
-class ThreadProcessDispatcher : public Dispatcher {
- public:
- explicit ThreadProcessDispatcher(PolicyBase* policy_base);
- ~ThreadProcessDispatcher() override {}
-
- // Dispatcher interface.
- bool SetupService(InterceptionManager* manager, int service) override;
-
- private:
- // Processes IPC requests coming from calls to NtOpenThread() in the target.
- bool NtOpenThread(IPCInfo* ipc, uint32_t desired_access, uint32_t thread_id);
-
- // Processes IPC requests coming from calls to NtOpenProcess() in the target.
- bool NtOpenProcess(IPCInfo* ipc,
- uint32_t desired_access,
- uint32_t process_id);
-
- // Processes IPC requests from calls to NtOpenProcessToken() in the target.
- bool NtOpenProcessToken(IPCInfo* ipc,
- HANDLE process,
- uint32_t desired_access);
-
- // Processes IPC requests from calls to NtOpenProcessTokenEx() in the target.
- bool NtOpenProcessTokenEx(IPCInfo* ipc,
- HANDLE process,
- uint32_t desired_access,
- uint32_t attributes);
-
- // Processes IPC requests coming from calls to CreateProcessW() in the target.
- bool CreateProcessW(IPCInfo* ipc,
- base::string16* name,
- base::string16* cmd_line,
- base::string16* cur_dir,
- CountedBuffer* info);
-
- PolicyBase* policy_base_;
- DISALLOW_COPY_AND_ASSIGN(ThreadProcessDispatcher);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_PROCESS_THREAD_DISPATCHER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/process_thread_interception.cc b/security/sandbox/chromium/sandbox/win/src/process_thread_interception.cc
deleted file mode 100644
index 6507da3f7..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_thread_interception.cc
+++ /dev/null
@@ -1,423 +0,0 @@
-// Copyright (c) 2013 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 "sandbox/win/src/process_thread_interception.h"
-
-#include <stdint.h>
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/policy_target.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/target_services.h"
-#include "mozilla/sandboxing/sandboxLogging.h"
-
-namespace sandbox {
-
-SANDBOX_INTERCEPT NtExports g_nt;
-
-// Hooks NtOpenThread and proxy the call to the broker if it's trying to
-// open a thread in the same process.
-NTSTATUS WINAPI TargetNtOpenThread(NtOpenThreadFunction orig_OpenThread,
- PHANDLE thread, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes,
- PCLIENT_ID client_id) {
- NTSTATUS status = orig_OpenThread(thread, desired_access, object_attributes,
- client_id);
- if (NT_SUCCESS(status))
- return status;
-
- mozilla::sandboxing::LogBlocked("NtOpenThread");
- do {
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- break;
- if (!client_id)
- break;
-
- uint32_t thread_id = 0;
- bool should_break = false;
- __try {
- // We support only the calls for the current process
- if (NULL != client_id->UniqueProcess)
- should_break = true;
-
- // Object attributes should be NULL or empty.
- if (!should_break && NULL != object_attributes) {
- if (0 != object_attributes->Attributes ||
- NULL != object_attributes->ObjectName ||
- NULL != object_attributes->RootDirectory ||
- NULL != object_attributes->SecurityDescriptor ||
- NULL != object_attributes->SecurityQualityOfService) {
- should_break = true;
- }
- }
-
- thread_id = static_cast<uint32_t>(
- reinterpret_cast<ULONG_PTR>(client_id->UniqueThread));
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
-
- if (should_break)
- break;
-
- if (!ValidParameter(thread, sizeof(HANDLE), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTOPENTHREAD_TAG, desired_access,
- thread_id, &answer);
- if (SBOX_ALL_OK != code)
- break;
-
- if (!NT_SUCCESS(answer.nt_status))
- // The nt_status here is most likely STATUS_INVALID_CID because
- // in the broker we set the process id in the CID (client ID) param
- // to be the current process. If you try to open a thread from another
- // process you will get this INVALID_CID error. On the other hand, if you
- // try to open a thread in your own process, it should return success.
- // We don't want to return STATUS_INVALID_CID here, so we return the
- // return of the original open thread status, which is most likely
- // STATUS_ACCESS_DENIED.
- break;
-
- __try {
- // Write the output parameters.
- *thread = answer.handle;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
-
- mozilla::sandboxing::LogAllowed("NtOpenThread");
- return answer.nt_status;
- } while (false);
-
- return status;
-}
-
-// Hooks NtOpenProcess and proxy the call to the broker if it's trying to
-// open the current process.
-NTSTATUS WINAPI TargetNtOpenProcess(NtOpenProcessFunction orig_OpenProcess,
- PHANDLE process, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes,
- PCLIENT_ID client_id) {
- NTSTATUS status = orig_OpenProcess(process, desired_access, object_attributes,
- client_id);
- if (NT_SUCCESS(status))
- return status;
-
- do {
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- break;
- if (!client_id)
- break;
-
- uint32_t process_id = 0;
- bool should_break = false;
- __try {
- // Object attributes should be NULL or empty.
- if (!should_break && NULL != object_attributes) {
- if (0 != object_attributes->Attributes ||
- NULL != object_attributes->ObjectName ||
- NULL != object_attributes->RootDirectory ||
- NULL != object_attributes->SecurityDescriptor ||
- NULL != object_attributes->SecurityQualityOfService) {
- should_break = true;
- }
- }
-
- process_id = static_cast<uint32_t>(
- reinterpret_cast<ULONG_PTR>(client_id->UniqueProcess));
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
-
- if (should_break)
- break;
-
- if (!ValidParameter(process, sizeof(HANDLE), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTOPENPROCESS_TAG, desired_access,
- process_id, &answer);
- if (SBOX_ALL_OK != code)
- break;
-
- if (!NT_SUCCESS(answer.nt_status))
- return answer.nt_status;
-
- __try {
- // Write the output parameters.
- *process = answer.handle;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
-
- return answer.nt_status;
- } while (false);
-
- return status;
-}
-
-
-NTSTATUS WINAPI TargetNtOpenProcessToken(
- NtOpenProcessTokenFunction orig_OpenProcessToken, HANDLE process,
- ACCESS_MASK desired_access, PHANDLE token) {
- NTSTATUS status = orig_OpenProcessToken(process, desired_access, token);
- if (NT_SUCCESS(status))
- return status;
-
- mozilla::sandboxing::LogBlocked("NtOpenProcessToken");
- do {
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- break;
-
- if (CURRENT_PROCESS != process)
- break;
-
- if (!ValidParameter(token, sizeof(HANDLE), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTOPENPROCESSTOKEN_TAG, process,
- desired_access, &answer);
- if (SBOX_ALL_OK != code)
- break;
-
- if (!NT_SUCCESS(answer.nt_status))
- return answer.nt_status;
-
- __try {
- // Write the output parameters.
- *token = answer.handle;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
-
- mozilla::sandboxing::LogAllowed("NtOpenProcessToken");
- return answer.nt_status;
- } while (false);
-
- return status;
-}
-
-NTSTATUS WINAPI TargetNtOpenProcessTokenEx(
- NtOpenProcessTokenExFunction orig_OpenProcessTokenEx, HANDLE process,
- ACCESS_MASK desired_access, ULONG handle_attributes, PHANDLE token) {
- NTSTATUS status = orig_OpenProcessTokenEx(process, desired_access,
- handle_attributes, token);
- if (NT_SUCCESS(status))
- return status;
-
- mozilla::sandboxing::LogBlocked("NtOpenProcessTokenEx");
- do {
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- break;
-
- if (CURRENT_PROCESS != process)
- break;
-
- if (!ValidParameter(token, sizeof(HANDLE), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTOPENPROCESSTOKENEX_TAG, process,
- desired_access, handle_attributes, &answer);
- if (SBOX_ALL_OK != code)
- break;
-
- if (!NT_SUCCESS(answer.nt_status))
- return answer.nt_status;
-
- __try {
- // Write the output parameters.
- *token = answer.handle;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
-
- mozilla::sandboxing::LogAllowed("NtOpenProcessTokenEx");
- return answer.nt_status;
- } while (false);
-
- return status;
-}
-
-BOOL WINAPI TargetCreateProcessW(CreateProcessWFunction orig_CreateProcessW,
- LPCWSTR application_name, LPWSTR command_line,
- LPSECURITY_ATTRIBUTES process_attributes,
- LPSECURITY_ATTRIBUTES thread_attributes,
- BOOL inherit_handles, DWORD flags,
- LPVOID environment, LPCWSTR current_directory,
- LPSTARTUPINFOW startup_info,
- LPPROCESS_INFORMATION process_information) {
- if (SandboxFactory::GetTargetServices()->GetState()->IsCsrssConnected() &&
- orig_CreateProcessW(application_name, command_line, process_attributes,
- thread_attributes, inherit_handles, flags,
- environment, current_directory, startup_info,
- process_information)) {
- return TRUE;
- }
-
- mozilla::sandboxing::LogBlocked("CreateProcessW", application_name);
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return FALSE;
-
- // Don't call GetLastError before InitCalled() succeeds because kernel32 may
- // not be mapped yet.
- DWORD original_error = ::GetLastError();
-
- do {
- if (!ValidParameter(process_information, sizeof(PROCESS_INFORMATION),
- WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- const wchar_t* cur_dir = NULL;
-
- wchar_t current_directory[MAX_PATH];
- DWORD result = ::GetCurrentDirectory(MAX_PATH, current_directory);
- if (0 != result && result < MAX_PATH)
- cur_dir = current_directory;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
-
- InOutCountedBuffer proc_info(process_information,
- sizeof(PROCESS_INFORMATION));
-
- ResultCode code = CrossCall(ipc, IPC_CREATEPROCESSW_TAG, application_name,
- command_line, cur_dir, proc_info, &answer);
- if (SBOX_ALL_OK != code)
- break;
-
- ::SetLastError(answer.win32_result);
- if (ERROR_SUCCESS != answer.win32_result)
- return FALSE;
-
- mozilla::sandboxing::LogAllowed("CreateProcessW", application_name);
- return TRUE;
- } while (false);
-
- ::SetLastError(original_error);
- return FALSE;
-}
-
-BOOL WINAPI TargetCreateProcessA(CreateProcessAFunction orig_CreateProcessA,
- LPCSTR application_name, LPSTR command_line,
- LPSECURITY_ATTRIBUTES process_attributes,
- LPSECURITY_ATTRIBUTES thread_attributes,
- BOOL inherit_handles, DWORD flags,
- LPVOID environment, LPCSTR current_directory,
- LPSTARTUPINFOA startup_info,
- LPPROCESS_INFORMATION process_information) {
- if (orig_CreateProcessA(application_name, command_line, process_attributes,
- thread_attributes, inherit_handles, flags,
- environment, current_directory, startup_info,
- process_information)) {
- return TRUE;
- }
-
- mozilla::sandboxing::LogBlocked("CreateProcessA", application_name);
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return FALSE;
-
- // Don't call GetLastError before InitCalled() succeeds because kernel32 may
- // not be mapped yet.
- DWORD original_error = ::GetLastError();
-
- do {
- if (!ValidParameter(process_information, sizeof(PROCESS_INFORMATION),
- WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- // Convert the input params to unicode.
- UNICODE_STRING *cmd_unicode = NULL;
- UNICODE_STRING *app_unicode = NULL;
- if (command_line) {
- cmd_unicode = AnsiToUnicode(command_line);
- if (!cmd_unicode)
- break;
- }
-
- if (application_name) {
- app_unicode = AnsiToUnicode(application_name);
- if (!app_unicode) {
- operator delete(cmd_unicode, NT_ALLOC);
- break;
- }
- }
-
- const wchar_t* cmd_line = cmd_unicode ? cmd_unicode->Buffer : NULL;
- const wchar_t* app_name = app_unicode ? app_unicode->Buffer : NULL;
- const wchar_t* cur_dir = NULL;
-
- wchar_t current_directory[MAX_PATH];
- DWORD result = ::GetCurrentDirectory(MAX_PATH, current_directory);
- if (0 != result && result < MAX_PATH)
- cur_dir = current_directory;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
-
- InOutCountedBuffer proc_info(process_information,
- sizeof(PROCESS_INFORMATION));
-
- ResultCode code = CrossCall(ipc, IPC_CREATEPROCESSW_TAG, app_name,
- cmd_line, cur_dir, proc_info, &answer);
-
- operator delete(cmd_unicode, NT_ALLOC);
- operator delete(app_unicode, NT_ALLOC);
-
- if (SBOX_ALL_OK != code)
- break;
-
- ::SetLastError(answer.win32_result);
- if (ERROR_SUCCESS != answer.win32_result)
- return FALSE;
-
- mozilla::sandboxing::LogAllowed("CreateProcessA", application_name);
- return TRUE;
- } while (false);
-
- ::SetLastError(original_error);
- return FALSE;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/process_thread_interception.h b/security/sandbox/chromium/sandbox/win/src/process_thread_interception.h
deleted file mode 100644
index 31dc23154..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_thread_interception.h
+++ /dev/null
@@ -1,90 +0,0 @@
-// Copyright (c) 2014 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 "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_PROCESS_THREAD_INTERCEPTION_H__
-#define SANDBOX_SRC_PROCESS_THREAD_INTERCEPTION_H__
-
-namespace sandbox {
-
-extern "C" {
-
-typedef BOOL (WINAPI *CreateProcessWFunction)(
- LPCWSTR lpApplicationName,
- LPWSTR lpCommandLine,
- LPSECURITY_ATTRIBUTES lpProcessAttributes,
- LPSECURITY_ATTRIBUTES lpThreadAttributes,
- BOOL bInheritHandles,
- DWORD dwCreationFlags,
- LPVOID lpEnvironment,
- LPCWSTR lpCurrentDirectory,
- LPSTARTUPINFOW lpStartupInfo,
- LPPROCESS_INFORMATION lpProcessInformation);
-
-typedef BOOL (WINAPI *CreateProcessAFunction)(
- LPCSTR lpApplicationName,
- LPSTR lpCommandLine,
- LPSECURITY_ATTRIBUTES lpProcessAttributes,
- LPSECURITY_ATTRIBUTES lpThreadAttributes,
- BOOL bInheritHandles,
- DWORD dwCreationFlags,
- LPVOID lpEnvironment,
- LPCSTR lpCurrentDirectory,
- LPSTARTUPINFOA lpStartupInfo,
- LPPROCESS_INFORMATION lpProcessInformation);
-
-typedef HANDLE (WINAPI *CreateThreadFunction)(
- LPSECURITY_ATTRIBUTES lpThreadAttributes,
- SIZE_T dwStackSize,
- LPTHREAD_START_ROUTINE lpStartAddress,
- PVOID lpParameter,
- DWORD dwCreationFlags,
- LPDWORD lpThreadId);
-
-typedef LCID (WINAPI *GetUserDefaultLCIDFunction)();
-
-// Interception of NtOpenThread on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThread(
- NtOpenThreadFunction orig_OpenThread, PHANDLE thread,
- ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes,
- PCLIENT_ID client_id);
-
-// Interception of NtOpenProcess on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcess(
- NtOpenProcessFunction orig_OpenProcess, PHANDLE process,
- ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes,
- PCLIENT_ID client_id);
-
-// Interception of NtOpenProcessToken on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessToken(
- NtOpenProcessTokenFunction orig_OpenProcessToken, HANDLE process,
- ACCESS_MASK desired_access, PHANDLE token);
-
-// Interception of NtOpenProcessTokenEx on the child process.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessTokenEx(
- NtOpenProcessTokenExFunction orig_OpenProcessTokenEx, HANDLE process,
- ACCESS_MASK desired_access, ULONG handle_attributes, PHANDLE token);
-
-// Interception of CreateProcessW and A in kernel32.dll.
-SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessW(
- CreateProcessWFunction orig_CreateProcessW, LPCWSTR application_name,
- LPWSTR command_line, LPSECURITY_ATTRIBUTES process_attributes,
- LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
- LPVOID environment, LPCWSTR current_directory, LPSTARTUPINFOW startup_info,
- LPPROCESS_INFORMATION process_information);
-
-SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessA(
- CreateProcessAFunction orig_CreateProcessA, LPCSTR application_name,
- LPSTR command_line, LPSECURITY_ATTRIBUTES process_attributes,
- LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags,
- LPVOID environment, LPCSTR current_directory, LPSTARTUPINFOA startup_info,
- LPPROCESS_INFORMATION process_information);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_PROCESS_THREAD_INTERCEPTION_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/process_thread_policy.cc b/security/sandbox/chromium/sandbox/win/src/process_thread_policy.cc
deleted file mode 100644
index b4976c0bb..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_thread_policy.cc
+++ /dev/null
@@ -1,241 +0,0 @@
-// 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 "sandbox/win/src/process_thread_policy.h"
-
-#include <stdint.h>
-
-#include <string>
-
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-// These are the only safe rights that can be given to a sandboxed
-// process for the process created by the broker. All others are potential
-// vectors of privilege elevation.
-const DWORD kProcessRights = SYNCHRONIZE |
- PROCESS_QUERY_INFORMATION |
- PROCESS_QUERY_LIMITED_INFORMATION |
- PROCESS_TERMINATE |
- PROCESS_SUSPEND_RESUME;
-
-const DWORD kThreadRights = SYNCHRONIZE |
- THREAD_TERMINATE |
- THREAD_SUSPEND_RESUME |
- THREAD_QUERY_INFORMATION |
- THREAD_QUERY_LIMITED_INFORMATION |
- THREAD_SET_LIMITED_INFORMATION;
-
-// Creates a child process and duplicates the handles to 'target_process'. The
-// remaining parameters are the same as CreateProcess().
-BOOL CreateProcessExWHelper(HANDLE target_process, BOOL give_full_access,
- LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
- LPSECURITY_ATTRIBUTES lpProcessAttributes,
- LPSECURITY_ATTRIBUTES lpThreadAttributes,
- BOOL bInheritHandles, DWORD dwCreationFlags,
- LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
- LPSTARTUPINFOW lpStartupInfo,
- LPPROCESS_INFORMATION lpProcessInformation) {
- if (!::CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes,
- lpThreadAttributes, bInheritHandles, dwCreationFlags,
- lpEnvironment, lpCurrentDirectory, lpStartupInfo,
- lpProcessInformation)) {
- return FALSE;
- }
-
- DWORD process_access = kProcessRights;
- DWORD thread_access = kThreadRights;
- if (give_full_access) {
- process_access = PROCESS_ALL_ACCESS;
- thread_access = THREAD_ALL_ACCESS;
- }
- if (!::DuplicateHandle(::GetCurrentProcess(), lpProcessInformation->hProcess,
- target_process, &lpProcessInformation->hProcess,
- process_access, FALSE, DUPLICATE_CLOSE_SOURCE)) {
- ::CloseHandle(lpProcessInformation->hThread);
- return FALSE;
- }
- if (!::DuplicateHandle(::GetCurrentProcess(), lpProcessInformation->hThread,
- target_process, &lpProcessInformation->hThread,
- thread_access, FALSE, DUPLICATE_CLOSE_SOURCE)) {
- return FALSE;
- }
- return TRUE;
-}
-
-}
-
-namespace sandbox {
-
-bool ProcessPolicy::GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy) {
- scoped_ptr<PolicyRule> process;
- switch (semantics) {
- case TargetPolicy::PROCESS_MIN_EXEC: {
- process.reset(new PolicyRule(GIVE_READONLY));
- break;
- };
- case TargetPolicy::PROCESS_ALL_EXEC: {
- process.reset(new PolicyRule(GIVE_ALLACCESS));
- break;
- };
- default: {
- return false;
- };
- }
-
- if (!process->AddStringMatch(IF, NameBased::NAME, name, CASE_INSENSITIVE)) {
- return false;
- }
- if (!policy->AddRule(IPC_CREATEPROCESSW_TAG, process.get())) {
- return false;
- }
- return true;
-}
-
-NTSTATUS ProcessPolicy::OpenThreadAction(const ClientInfo& client_info,
- uint32_t desired_access,
- uint32_t thread_id,
- HANDLE* handle) {
- *handle = NULL;
-
- NtOpenThreadFunction NtOpenThread = NULL;
- ResolveNTFunctionPtr("NtOpenThread", &NtOpenThread);
-
- OBJECT_ATTRIBUTES attributes = {0};
- attributes.Length = sizeof(attributes);
- CLIENT_ID client_id = {0};
- client_id.UniqueProcess = reinterpret_cast<PVOID>(
- static_cast<ULONG_PTR>(client_info.process_id));
- client_id.UniqueThread =
- reinterpret_cast<PVOID>(static_cast<ULONG_PTR>(thread_id));
-
- HANDLE local_handle = NULL;
- NTSTATUS status = NtOpenThread(&local_handle, desired_access, &attributes,
- &client_id);
- if (NT_SUCCESS(status)) {
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- client_info.process, handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- }
-
- return status;
-}
-
-NTSTATUS ProcessPolicy::OpenProcessAction(const ClientInfo& client_info,
- uint32_t desired_access,
- uint32_t process_id,
- HANDLE* handle) {
- *handle = NULL;
-
- NtOpenProcessFunction NtOpenProcess = NULL;
- ResolveNTFunctionPtr("NtOpenProcess", &NtOpenProcess);
-
- if (client_info.process_id != process_id)
- return STATUS_ACCESS_DENIED;
-
- OBJECT_ATTRIBUTES attributes = {0};
- attributes.Length = sizeof(attributes);
- CLIENT_ID client_id = {0};
- client_id.UniqueProcess = reinterpret_cast<PVOID>(
- static_cast<ULONG_PTR>(client_info.process_id));
- HANDLE local_handle = NULL;
- NTSTATUS status = NtOpenProcess(&local_handle, desired_access, &attributes,
- &client_id);
- if (NT_SUCCESS(status)) {
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- client_info.process, handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- }
-
- return status;
-}
-
-NTSTATUS ProcessPolicy::OpenProcessTokenAction(const ClientInfo& client_info,
- HANDLE process,
- uint32_t desired_access,
- HANDLE* handle) {
- *handle = NULL;
- NtOpenProcessTokenFunction NtOpenProcessToken = NULL;
- ResolveNTFunctionPtr("NtOpenProcessToken", &NtOpenProcessToken);
-
- if (CURRENT_PROCESS != process)
- return STATUS_ACCESS_DENIED;
-
- HANDLE local_handle = NULL;
- NTSTATUS status = NtOpenProcessToken(client_info.process, desired_access,
- &local_handle);
- if (NT_SUCCESS(status)) {
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- client_info.process, handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- }
- return status;
-}
-
-NTSTATUS ProcessPolicy::OpenProcessTokenExAction(const ClientInfo& client_info,
- HANDLE process,
- uint32_t desired_access,
- uint32_t attributes,
- HANDLE* handle) {
- *handle = NULL;
- NtOpenProcessTokenExFunction NtOpenProcessTokenEx = NULL;
- ResolveNTFunctionPtr("NtOpenProcessTokenEx", &NtOpenProcessTokenEx);
-
- if (CURRENT_PROCESS != process)
- return STATUS_ACCESS_DENIED;
-
- HANDLE local_handle = NULL;
- NTSTATUS status = NtOpenProcessTokenEx(client_info.process, desired_access,
- attributes, &local_handle);
- if (NT_SUCCESS(status)) {
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- client_info.process, handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- }
- return status;
-}
-
-DWORD ProcessPolicy::CreateProcessWAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16 &app_name,
- const base::string16 &command_line,
- PROCESS_INFORMATION* process_info) {
- // The only action supported is ASK_BROKER which means create the process.
- if (GIVE_ALLACCESS != eval_result && GIVE_READONLY != eval_result) {
- return ERROR_ACCESS_DENIED;
- }
-
- STARTUPINFO startup_info = {0};
- startup_info.cb = sizeof(startup_info);
- scoped_ptr<wchar_t, base::FreeDeleter>
- cmd_line(_wcsdup(command_line.c_str()));
-
- BOOL should_give_full_access = (GIVE_ALLACCESS == eval_result);
- if (!CreateProcessExWHelper(client_info.process, should_give_full_access,
- app_name.c_str(), cmd_line.get(), NULL, NULL,
- FALSE, 0, NULL, NULL, &startup_info,
- process_info)) {
- return ERROR_ACCESS_DENIED;
- }
- return ERROR_SUCCESS;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/process_thread_policy.h b/security/sandbox/chromium/sandbox/win/src/process_thread_policy.h
deleted file mode 100644
index a66b52eb2..000000000
--- a/security/sandbox/chromium/sandbox/win/src/process_thread_policy.h
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright (c) 2006-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 SANDBOX_SRC_PROCESS_THREAD_POLICY_H_
-#define SANDBOX_SRC_PROCESS_THREAD_POLICY_H_
-
-#include <stdint.h>
-
-#include <string>
-
-#include "sandbox/win/src/policy_low_level.h"
-
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox_policy.h"
-
-namespace sandbox {
-
-enum EvalResult;
-
-// This class centralizes most of the knowledge related to process execution.
-class ProcessPolicy {
- public:
- // Creates the required low-level policy rules to evaluate a high-level.
- // policy rule for process creation
- // 'name' is the executable to be spawn.
- // 'semantics' is the desired semantics.
- // 'policy' is the policy generator to which the rules are going to be added.
- static bool GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy);
-
- // Opens a thread from the child process and returns the handle.
- // client_info contains the information about the child process,
- // desired_access is the access requested by the child and thread_id
- // is the thread_id to be opened.
- // The function returns the return value of NtOpenThread.
- static NTSTATUS OpenThreadAction(const ClientInfo& client_info,
- uint32_t desired_access,
- uint32_t thread_id,
- HANDLE* handle);
-
- // Opens the process id passed in and returns the duplicated handle to
- // the child. We only allow the child processes to open themselves. Any other
- // pid open is denied.
- static NTSTATUS OpenProcessAction(const ClientInfo& client_info,
- uint32_t desired_access,
- uint32_t process_id,
- HANDLE* handle);
-
- // Opens the token associated with the process and returns the duplicated
- // handle to the child. We only allow the child processes to open his own
- // token (using ::GetCurrentProcess()).
- static NTSTATUS OpenProcessTokenAction(const ClientInfo& client_info,
- HANDLE process,
- uint32_t desired_access,
- HANDLE* handle);
-
- // Opens the token associated with the process and returns the duplicated
- // handle to the child. We only allow the child processes to open his own
- // token (using ::GetCurrentProcess()).
- static NTSTATUS OpenProcessTokenExAction(const ClientInfo& client_info,
- HANDLE process,
- uint32_t desired_access,
- uint32_t attributes,
- HANDLE* handle);
-
- // Processes a 'CreateProcessW()' request from the target.
- // 'client_info' : the target process that is making the request.
- // 'eval_result' : The desired policy action to accomplish.
- // 'app_name' : The full path of the process to be created.
- // 'command_line' : The command line passed to the created process.
- static DWORD CreateProcessWAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16 &app_name,
- const base::string16 &command_line,
- PROCESS_INFORMATION* process_info);
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_PROCESS_THREAD_POLICY_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/registry_dispatcher.cc b/security/sandbox/chromium/sandbox/win/src/registry_dispatcher.cc
deleted file mode 100644
index fef727dac..000000000
--- a/security/sandbox/chromium/sandbox/win/src/registry_dispatcher.cc
+++ /dev/null
@@ -1,175 +0,0 @@
-// 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 "sandbox/win/src/registry_dispatcher.h"
-
-#include <stdint.h>
-
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_broker.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/registry_interception.h"
-#include "sandbox/win/src/registry_policy.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-namespace {
-
-// Builds a path using the root directory and the name.
-bool GetCompletePath(HANDLE root, const base::string16& name,
- base::string16* complete_name) {
- if (root) {
- if (!sandbox::GetPathFromHandle(root, complete_name))
- return false;
-
- *complete_name += L"\\";
- *complete_name += name;
- } else {
- *complete_name = name;
- }
-
- return true;
-}
-
-}
-
-namespace sandbox {
-
-RegistryDispatcher::RegistryDispatcher(PolicyBase* policy_base)
- : policy_base_(policy_base) {
- static const IPCCall create_params = {
- {IPC_NTCREATEKEY_TAG,
- {WCHAR_TYPE,
- UINT32_TYPE,
- VOIDPTR_TYPE,
- UINT32_TYPE,
- UINT32_TYPE,
- UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(&RegistryDispatcher::NtCreateKey)};
-
- static const IPCCall open_params = {
- {IPC_NTOPENKEY_TAG, {WCHAR_TYPE, UINT32_TYPE, VOIDPTR_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(&RegistryDispatcher::NtOpenKey)};
-
- ipc_calls_.push_back(create_params);
- ipc_calls_.push_back(open_params);
-}
-
-bool RegistryDispatcher::SetupService(InterceptionManager* manager,
- int service) {
- if (IPC_NTCREATEKEY_TAG == service)
- return INTERCEPT_NT(manager, NtCreateKey, CREATE_KEY_ID, 32);
-
- if (IPC_NTOPENKEY_TAG == service) {
- bool result = INTERCEPT_NT(manager, NtOpenKey, OPEN_KEY_ID, 16);
- if (base::win::GetVersion() >= base::win::VERSION_WIN7 ||
- (base::win::GetVersion() == base::win::VERSION_VISTA &&
- base::win::OSInfo::GetInstance()->version_type() ==
- base::win::SUITE_SERVER))
- result &= INTERCEPT_NT(manager, NtOpenKeyEx, OPEN_KEY_EX_ID, 20);
- return result;
- }
-
- return false;
-}
-
-bool RegistryDispatcher::NtCreateKey(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- HANDLE root,
- uint32_t desired_access,
- uint32_t title_index,
- uint32_t create_options) {
- base::win::ScopedHandle root_handle;
- base::string16 real_path = *name;
-
- // If there is a root directory, we need to duplicate the handle to make
- // it valid in this process.
- if (root) {
- if (!::DuplicateHandle(ipc->client_info->process, root,
- ::GetCurrentProcess(), &root, 0, FALSE,
- DUPLICATE_SAME_ACCESS))
- return false;
-
- root_handle.Set(root);
- }
-
- if (!GetCompletePath(root, *name, &real_path))
- return false;
-
- const wchar_t* regname = real_path.c_str();
- CountedParameterSet<OpenKey> params;
- params[OpenKey::NAME] = ParamPickerMake(regname);
- params[OpenKey::ACCESS] = ParamPickerMake(desired_access);
-
- EvalResult result = policy_base_->EvalPolicy(IPC_NTCREATEKEY_TAG,
- params.GetBase());
-
- HANDLE handle;
- NTSTATUS nt_status;
- ULONG disposition = 0;
- if (!RegistryPolicy::CreateKeyAction(result, *ipc->client_info, *name,
- attributes, root, desired_access,
- title_index, create_options, &handle,
- &nt_status, &disposition)) {
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- // Return operation status on the IPC.
- ipc->return_info.extended[0].unsigned_int = disposition;
- ipc->return_info.nt_status = nt_status;
- ipc->return_info.handle = handle;
- return true;
-}
-
-bool RegistryDispatcher::NtOpenKey(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- HANDLE root,
- uint32_t desired_access) {
- base::win::ScopedHandle root_handle;
- base::string16 real_path = *name;
-
- // If there is a root directory, we need to duplicate the handle to make
- // it valid in this process.
- if (root) {
- if (!::DuplicateHandle(ipc->client_info->process, root,
- ::GetCurrentProcess(), &root, 0, FALSE,
- DUPLICATE_SAME_ACCESS))
- return false;
- root_handle.Set(root);
- }
-
- if (!GetCompletePath(root, *name, &real_path))
- return false;
-
- const wchar_t* regname = real_path.c_str();
- CountedParameterSet<OpenKey> params;
- params[OpenKey::NAME] = ParamPickerMake(regname);
- params[OpenKey::ACCESS] = ParamPickerMake(desired_access);
-
- EvalResult result = policy_base_->EvalPolicy(IPC_NTOPENKEY_TAG,
- params.GetBase());
- HANDLE handle;
- NTSTATUS nt_status;
- if (!RegistryPolicy::OpenKeyAction(result, *ipc->client_info, *name,
- attributes, root, desired_access, &handle,
- &nt_status)) {
- ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- // Return operation status on the IPC.
- ipc->return_info.nt_status = nt_status;
- ipc->return_info.handle = handle;
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/registry_dispatcher.h b/security/sandbox/chromium/sandbox/win/src/registry_dispatcher.h
deleted file mode 100644
index cb5af0c3d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/registry_dispatcher.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// 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 SANDBOX_SRC_REGISTRY_DISPATCHER_H_
-#define SANDBOX_SRC_REGISTRY_DISPATCHER_H_
-
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-namespace sandbox {
-
-// This class handles registry-related IPC calls.
-class RegistryDispatcher : public Dispatcher {
- public:
- explicit RegistryDispatcher(PolicyBase* policy_base);
- ~RegistryDispatcher() override {}
-
- // Dispatcher interface.
- bool SetupService(InterceptionManager* manager, int service) override;
-
- private:
- // Processes IPC requests coming from calls to NtCreateKey in the target.
- bool NtCreateKey(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- HANDLE root,
- uint32_t desired_access,
- uint32_t title_index,
- uint32_t create_options);
-
- // Processes IPC requests coming from calls to NtOpenKey in the target.
- bool NtOpenKey(IPCInfo* ipc,
- base::string16* name,
- uint32_t attributes,
- HANDLE root,
- uint32_t desired_access);
-
- PolicyBase* policy_base_;
- DISALLOW_COPY_AND_ASSIGN(RegistryDispatcher);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_REGISTRY_DISPATCHER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/registry_interception.cc b/security/sandbox/chromium/sandbox/win/src/registry_interception.cc
deleted file mode 100644
index 2ff1b33f8..000000000
--- a/security/sandbox/chromium/sandbox/win/src/registry_interception.cc
+++ /dev/null
@@ -1,251 +0,0 @@
-// 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 "sandbox/win/src/registry_interception.h"
-
-#include <stdint.h>
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/policy_target.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/target_services.h"
-#include "mozilla/sandboxing/sandboxLogging.h"
-
-namespace sandbox {
-
-NTSTATUS WINAPI TargetNtCreateKey(NtCreateKeyFunction orig_CreateKey,
- PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes,
- ULONG title_index, PUNICODE_STRING class_name,
- ULONG create_options, PULONG disposition) {
- // Check if the process can create it first.
- NTSTATUS status = orig_CreateKey(key, desired_access, object_attributes,
- title_index, class_name, create_options,
- disposition);
- if (NT_SUCCESS(status))
- return status;
-
- if (STATUS_OBJECT_NAME_NOT_FOUND != status) {
- mozilla::sandboxing::LogBlocked("NtCreateKey",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- }
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- do {
- if (!ValidParameter(key, sizeof(HANDLE), WRITE))
- break;
-
- if (disposition && !ValidParameter(disposition, sizeof(ULONG), WRITE))
- break;
-
- // At this point we don't support class_name.
- if (class_name && class_name->Buffer && class_name->Length)
- break;
-
- // We don't support creating link keys, volatile keys and backup/restore.
- if (create_options)
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- wchar_t* name;
- uint32_t attributes = 0;
- HANDLE root_directory = 0;
- NTSTATUS ret = AllocAndCopyName(object_attributes, &name, &attributes,
- &root_directory);
- if (!NT_SUCCESS(ret) || NULL == name)
- break;
-
- uint32_t desired_access_uint32 = desired_access;
- CountedParameterSet<OpenKey> params;
- params[OpenKey::ACCESS] = ParamPickerMake(desired_access_uint32);
-
- wchar_t* full_name = NULL;
-
- if (root_directory) {
- ret = sandbox::AllocAndGetFullPath(root_directory, name, &full_name);
- if (!NT_SUCCESS(ret) || NULL == full_name)
- break;
- params[OpenKey::NAME] = ParamPickerMake(full_name);
- } else {
- params[OpenKey::NAME] = ParamPickerMake(name);
- }
-
- bool query_broker = QueryBroker(IPC_NTCREATEKEY_TAG, params.GetBase());
-
- if (full_name != NULL)
- operator delete(full_name, NT_ALLOC);
-
- if (!query_broker)
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
-
- ResultCode code = CrossCall(ipc, IPC_NTCREATEKEY_TAG, name, attributes,
- root_directory, desired_access, title_index,
- create_options, &answer);
-
- operator delete(name, NT_ALLOC);
-
- if (SBOX_ALL_OK != code)
- break;
-
- if (!NT_SUCCESS(answer.nt_status))
- // TODO(nsylvain): We should return answer.nt_status here instead
- // of status. We can do this only after we checked the policy.
- // otherwise we will returns ACCESS_DENIED for all paths
- // that are not specified by a policy, even though your token allows
- // access to that path, and the original call had a more meaningful
- // error. Bug 4369
- break;
-
- __try {
- *key = answer.handle;
-
- if (disposition)
- *disposition = answer.extended[0].unsigned_int;
-
- status = answer.nt_status;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
- mozilla::sandboxing::LogAllowed("NtCreateKey",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- } while (false);
-
- return status;
-}
-
-NTSTATUS WINAPI CommonNtOpenKey(NTSTATUS status, PHANDLE key,
- ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes) {
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- do {
- if (!ValidParameter(key, sizeof(HANDLE), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory)
- break;
-
- wchar_t* name;
- uint32_t attributes;
- HANDLE root_directory;
- NTSTATUS ret = AllocAndCopyName(object_attributes, &name, &attributes,
- &root_directory);
- if (!NT_SUCCESS(ret) || NULL == name)
- break;
-
- uint32_t desired_access_uint32 = desired_access;
- CountedParameterSet<OpenKey> params;
- params[OpenKey::ACCESS] = ParamPickerMake(desired_access_uint32);
-
- wchar_t* full_name = NULL;
-
- if (root_directory) {
- ret = sandbox::AllocAndGetFullPath(root_directory, name, &full_name);
- if (!NT_SUCCESS(ret) || NULL == full_name)
- break;
- params[OpenKey::NAME] = ParamPickerMake(full_name);
- } else {
- params[OpenKey::NAME] = ParamPickerMake(name);
- }
-
- bool query_broker = QueryBroker(IPC_NTOPENKEY_TAG, params.GetBase());
-
- if (full_name != NULL)
- operator delete(full_name, NT_ALLOC);
-
- if (!query_broker)
- break;
-
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
- ResultCode code = CrossCall(ipc, IPC_NTOPENKEY_TAG, name, attributes,
- root_directory, desired_access, &answer);
-
- operator delete(name, NT_ALLOC);
-
- if (SBOX_ALL_OK != code)
- break;
-
- if (!NT_SUCCESS(answer.nt_status))
- // TODO(nsylvain): We should return answer.nt_status here instead
- // of status. We can do this only after we checked the policy.
- // otherwise we will returns ACCESS_DENIED for all paths
- // that are not specified by a policy, even though your token allows
- // access to that path, and the original call had a more meaningful
- // error. Bug 4369
- break;
-
- __try {
- *key = answer.handle;
- status = answer.nt_status;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
- mozilla::sandboxing::LogAllowed("NtOpenKey[Ex]",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- } while (false);
-
- return status;
-}
-
-NTSTATUS WINAPI TargetNtOpenKey(NtOpenKeyFunction orig_OpenKey, PHANDLE key,
- ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes) {
- // Check if the process can open it first.
- NTSTATUS status = orig_OpenKey(key, desired_access, object_attributes);
- if (NT_SUCCESS(status))
- return status;
-
- if (STATUS_OBJECT_NAME_NOT_FOUND != status) {
- mozilla::sandboxing::LogBlocked("NtOpenKey",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- }
-
- return CommonNtOpenKey(status, key, desired_access, object_attributes);
-}
-
-NTSTATUS WINAPI TargetNtOpenKeyEx(NtOpenKeyExFunction orig_OpenKeyEx,
- PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes,
- ULONG open_options) {
- // Check if the process can open it first.
- NTSTATUS status = orig_OpenKeyEx(key, desired_access, object_attributes,
- open_options);
-
- // We do not support open_options at this time. The 2 current known values
- // are REG_OPTION_CREATE_LINK, to open a symbolic link, and
- // REG_OPTION_BACKUP_RESTORE to open the key with special privileges.
- if (NT_SUCCESS(status) || open_options != 0)
- return status;
-
- if (STATUS_OBJECT_NAME_NOT_FOUND != status) {
- mozilla::sandboxing::LogBlocked("NtOpenKeyEx",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- }
-
- return CommonNtOpenKey(status, key, desired_access, object_attributes);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/registry_interception.h b/security/sandbox/chromium/sandbox/win/src/registry_interception.h
deleted file mode 100644
index c3cbde02e..000000000
--- a/security/sandbox/chromium/sandbox/win/src/registry_interception.h
+++ /dev/null
@@ -1,38 +0,0 @@
-// 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 "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_REGISTRY_INTERCEPTION_H__
-#define SANDBOX_SRC_REGISTRY_INTERCEPTION_H__
-
-namespace sandbox {
-
-extern "C" {
-
-// Interception of NtCreateKey on the child process.
-// It should never be called directly
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateKey(
- NtCreateKeyFunction orig_CreateKey, PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, ULONG title_index,
- PUNICODE_STRING class_name, ULONG create_options, PULONG disposition);
-
-// Interception of NtOpenKey on the child process.
-// It should never be called directly
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKey(
- NtOpenKeyFunction orig_OpenKey, PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes);
-
-// Interception of NtOpenKeyEx on the child process.
-// It should never be called directly
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKeyEx(
- NtOpenKeyExFunction orig_OpenKeyEx, PHANDLE key, ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes, ULONG open_options);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_REGISTRY_INTERCEPTION_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/registry_policy.cc b/security/sandbox/chromium/sandbox/win/src/registry_policy.cc
deleted file mode 100644
index d056c9c59..000000000
--- a/security/sandbox/chromium/sandbox/win/src/registry_policy.cc
+++ /dev/null
@@ -1,228 +0,0 @@
-// 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 <stdint.h>
-
-#include <string>
-
-#include "sandbox/win/src/registry_policy.h"
-
-#include "base/logging.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sandbox_utils.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-static const uint32_t kAllowedRegFlags =
- KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY | KEY_READ |
- GENERIC_READ | GENERIC_EXECUTE | READ_CONTROL | KEY_WOW64_64KEY |
- KEY_WOW64_32KEY;
-
-// Opens the key referenced by |obj_attributes| with |access| and
-// checks what permission was given. Remove the WRITE flags and update
-// |access| with the new value.
-NTSTATUS TranslateMaximumAllowed(OBJECT_ATTRIBUTES* obj_attributes,
- DWORD* access) {
- NtOpenKeyFunction NtOpenKey = NULL;
- ResolveNTFunctionPtr("NtOpenKey", &NtOpenKey);
-
- NtCloseFunction NtClose = NULL;
- ResolveNTFunctionPtr("NtClose", &NtClose);
-
- NtQueryObjectFunction NtQueryObject = NULL;
- ResolveNTFunctionPtr("NtQueryObject", &NtQueryObject);
-
- // Open the key.
- HANDLE handle;
- NTSTATUS status = NtOpenKey(&handle, *access, obj_attributes);
- if (!NT_SUCCESS(status))
- return status;
-
- OBJECT_BASIC_INFORMATION info = {0};
- status = NtQueryObject(handle, ObjectBasicInformation, &info, sizeof(info),
- NULL);
- CHECK(NT_SUCCESS(NtClose(handle)));
- if (!NT_SUCCESS(status))
- return status;
-
- *access = info.GrantedAccess & kAllowedRegFlags;
- return STATUS_SUCCESS;
-}
-
-NTSTATUS NtCreateKeyInTarget(HANDLE* target_key_handle,
- ACCESS_MASK desired_access,
- OBJECT_ATTRIBUTES* obj_attributes,
- ULONG title_index,
- UNICODE_STRING* class_name,
- ULONG create_options,
- ULONG* disposition,
- HANDLE target_process) {
- NtCreateKeyFunction NtCreateKey = NULL;
- ResolveNTFunctionPtr("NtCreateKey", &NtCreateKey);
-
- if (MAXIMUM_ALLOWED & desired_access) {
- NTSTATUS status = TranslateMaximumAllowed(obj_attributes, &desired_access);
- if (!NT_SUCCESS(status))
- return STATUS_ACCESS_DENIED;
- }
-
- HANDLE local_handle = INVALID_HANDLE_VALUE;
- NTSTATUS status = NtCreateKey(&local_handle, desired_access, obj_attributes,
- title_index, class_name, create_options,
- disposition);
- if (!NT_SUCCESS(status))
- return status;
-
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- target_process, target_key_handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- return STATUS_SUCCESS;
-}
-
-NTSTATUS NtOpenKeyInTarget(HANDLE* target_key_handle,
- ACCESS_MASK desired_access,
- OBJECT_ATTRIBUTES* obj_attributes,
- HANDLE target_process) {
- NtOpenKeyFunction NtOpenKey = NULL;
- ResolveNTFunctionPtr("NtOpenKey", &NtOpenKey);
-
- if (MAXIMUM_ALLOWED & desired_access) {
- NTSTATUS status = TranslateMaximumAllowed(obj_attributes, &desired_access);
- if (!NT_SUCCESS(status))
- return STATUS_ACCESS_DENIED;
- }
-
- HANDLE local_handle = INVALID_HANDLE_VALUE;
- NTSTATUS status = NtOpenKey(&local_handle, desired_access, obj_attributes);
-
- if (!NT_SUCCESS(status))
- return status;
-
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- target_process, target_key_handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- return STATUS_SUCCESS;
-}
-
-}
-
-namespace sandbox {
-
-bool RegistryPolicy::GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy) {
- base::string16 resovled_name(name);
- if (resovled_name.empty()) {
- return false;
- }
-
- if (!ResolveRegistryName(resovled_name, &resovled_name))
- return false;
-
- name = resovled_name.c_str();
-
- EvalResult result = ASK_BROKER;
-
- PolicyRule open(result);
- PolicyRule create(result);
-
- switch (semantics) {
- case TargetPolicy::REG_ALLOW_READONLY: {
- // We consider all flags that are not known to be readonly as potentially
- // used for write. Here we also support MAXIMUM_ALLOWED, but we are going
- // to expand it to read-only before the call.
- uint32_t restricted_flags = ~(kAllowedRegFlags | MAXIMUM_ALLOWED);
- open.AddNumberMatch(IF_NOT, OpenKey::ACCESS, restricted_flags, AND);
- create.AddNumberMatch(IF_NOT, OpenKey::ACCESS, restricted_flags, AND);
- break;
- }
- case TargetPolicy::REG_ALLOW_ANY: {
- break;
- }
- default: {
- NOTREACHED();
- return false;
- }
- }
-
- if (!create.AddStringMatch(IF, OpenKey::NAME, name, CASE_INSENSITIVE) ||
- !policy->AddRule(IPC_NTCREATEKEY_TAG, &create)) {
- return false;
- }
-
- if (!open.AddStringMatch(IF, OpenKey::NAME, name, CASE_INSENSITIVE) ||
- !policy->AddRule(IPC_NTOPENKEY_TAG, &open)) {
- return false;
- }
-
- return true;
-}
-
-bool RegistryPolicy::CreateKeyAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& key,
- uint32_t attributes,
- HANDLE root_directory,
- uint32_t desired_access,
- uint32_t title_index,
- uint32_t create_options,
- HANDLE* handle,
- NTSTATUS* nt_status,
- ULONG* disposition) {
- // The only action supported is ASK_BROKER which means create the requested
- // file as specified.
- if (ASK_BROKER != eval_result) {
- *nt_status = STATUS_ACCESS_DENIED;
- return false;
- }
-
- // We don't support creating link keys, volatile keys or backup/restore.
- if (create_options) {
- *nt_status = STATUS_ACCESS_DENIED;
- return false;
- }
-
- UNICODE_STRING uni_name = {0};
- OBJECT_ATTRIBUTES obj_attributes = {0};
- InitObjectAttribs(key, attributes, root_directory, &obj_attributes,
- &uni_name, NULL);
- *nt_status = NtCreateKeyInTarget(handle, desired_access, &obj_attributes,
- title_index, NULL, create_options,
- disposition, client_info.process);
- return true;
-}
-
-bool RegistryPolicy::OpenKeyAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& key,
- uint32_t attributes,
- HANDLE root_directory,
- uint32_t desired_access,
- HANDLE* handle,
- NTSTATUS* nt_status) {
- // The only action supported is ASK_BROKER which means open the requested
- // file as specified.
- if (ASK_BROKER != eval_result) {
- *nt_status = STATUS_ACCESS_DENIED;
- return true;
- }
-
- UNICODE_STRING uni_name = {0};
- OBJECT_ATTRIBUTES obj_attributes = {0};
- InitObjectAttribs(key, attributes, root_directory, &obj_attributes,
- &uni_name, NULL);
- *nt_status = NtOpenKeyInTarget(handle, desired_access, &obj_attributes,
- client_info.process);
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/registry_policy.h b/security/sandbox/chromium/sandbox/win/src/registry_policy.h
deleted file mode 100644
index ddea1bf5a..000000000
--- a/security/sandbox/chromium/sandbox/win/src/registry_policy.h
+++ /dev/null
@@ -1,59 +0,0 @@
-// 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 SANDBOX_SRC_REGISTRY_POLICY_H__
-#define SANDBOX_SRC_REGISTRY_POLICY_H__
-
-#include <stdint.h>
-
-#include <string>
-
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/sandbox_policy.h"
-
-namespace sandbox {
-
-enum EvalResult;
-
-// This class centralizes most of the knowledge related to registry policy
-class RegistryPolicy {
- public:
- // Creates the required low-level policy rules to evaluate a high-level
- // policy rule for registry IO, in particular open or create actions.
- static bool GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy);
-
- // Performs the desired policy action on a create request with an
- // API that is compatible with the IPC-received parameters.
- static bool CreateKeyAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& key,
- uint32_t attributes,
- HANDLE root_directory,
- uint32_t desired_access,
- uint32_t title_index,
- uint32_t create_options,
- HANDLE* handle,
- NTSTATUS* nt_status,
- ULONG* disposition);
-
- // Performs the desired policy action on an open request with an
- // API that is compatible with the IPC-received parameters.
- static bool OpenKeyAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& key,
- uint32_t attributes,
- HANDLE root_directory,
- uint32_t desired_access,
- HANDLE* handle,
- NTSTATUS* nt_status);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_REGISTRY_POLICY_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/registry_policy_test.cc b/security/sandbox/chromium/sandbox/win/src/registry_policy_test.cc
deleted file mode 100644
index d8ee34b06..000000000
--- a/security/sandbox/chromium/sandbox/win/src/registry_policy_test.cc
+++ /dev/null
@@ -1,289 +0,0 @@
-// Copyright (c) 2006-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 <shlobj.h>
-
-#include "testing/gtest/include/gtest/gtest.h"
-#include "sandbox/win/src/registry_policy.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/win_utils.h"
-#include "sandbox/win/tests/common/controller.h"
-
-namespace {
-
-static const DWORD kAllowedRegFlags = KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS |
- KEY_NOTIFY | KEY_READ | GENERIC_READ |
- GENERIC_EXECUTE | READ_CONTROL;
-
-#define BINDNTDLL(name) \
- name ## Function name = reinterpret_cast<name ## Function>( \
- ::GetProcAddress(::GetModuleHandle(L"ntdll.dll"), #name))
-
-bool IsKeyOpenForRead(HKEY handle) {
- BINDNTDLL(NtQueryObject);
-
- OBJECT_BASIC_INFORMATION info = {0};
- NTSTATUS status = NtQueryObject(handle, ObjectBasicInformation, &info,
- sizeof(info), NULL);
-
- if (!NT_SUCCESS(status))
- return false;
-
- if ((info.GrantedAccess & (~kAllowedRegFlags)) != 0)
- return false;
- return true;
-}
-
-}
-
-namespace sandbox {
-
-SBOX_TESTS_COMMAND int Reg_OpenKey(int argc, wchar_t **argv) {
- if (argc != 4)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- REGSAM desired_access = 0;
- ULONG options = 0;
- if (wcscmp(argv[1], L"read") == 0) {
- desired_access = KEY_READ;
- } else if (wcscmp(argv[1], L"write") == 0) {
- desired_access = KEY_ALL_ACCESS;
- } else if (wcscmp(argv[1], L"link") == 0) {
- options = REG_OPTION_CREATE_LINK;
- desired_access = KEY_ALL_ACCESS;
- } else {
- desired_access = MAXIMUM_ALLOWED;
- }
-
- HKEY root = GetReservedKeyFromName(argv[2]);
- HKEY key;
- LRESULT result = 0;
-
- if (wcscmp(argv[0], L"create") == 0)
- result = ::RegCreateKeyEx(root, argv[3], 0, NULL, options, desired_access,
- NULL, &key, NULL);
- else
- result = ::RegOpenKeyEx(root, argv[3], 0, desired_access, &key);
-
- if (ERROR_SUCCESS == result) {
- if (MAXIMUM_ALLOWED == desired_access) {
- if (!IsKeyOpenForRead(key)) {
- ::RegCloseKey(key);
- return SBOX_TEST_FAILED;
- }
- }
- ::RegCloseKey(key);
- return SBOX_TEST_SUCCEEDED;
- } else if (ERROR_ACCESS_DENIED == result) {
- return SBOX_TEST_DENIED;
- }
-
- return SBOX_TEST_FAILED;
-}
-
-TEST(RegistryPolicyTest, TestKeyAnyAccess) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_ANY,
- L"HKEY_LOCAL_MACHINE\\Software\\Microsoft"));
-
- // Tests read access on key allowed for read-write.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(
- L"Reg_OpenKey create read HKEY_LOCAL_MACHINE software\\microsoft"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(
- L"Reg_OpenKey open read HKEY_LOCAL_MACHINE software\\microsoft"));
-
- if (::IsUserAnAdmin()) {
- // Tests write access on key allowed for read-write.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(
- L"Reg_OpenKey create write HKEY_LOCAL_MACHINE software\\microsoft"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(
- L"Reg_OpenKey open write HKEY_LOCAL_MACHINE software\\microsoft"));
- }
-
- // Tests subdirectory access on keys where we don't have subdirectory acess.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Reg_OpenKey create read "
- L"HKEY_LOCAL_MACHINE software\\microsoft\\Windows"));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Reg_OpenKey open read "
- L"HKEY_LOCAL_MACHINE software\\microsoft\\windows"));
-
- // Tests to see if we can create keys where we dont have subdirectory access.
- // This is denied.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Reg_OpenKey create write "
- L"HKEY_LOCAL_MACHINE software\\Microsoft\\google_unit_tests"));
-
- RegDeleteKey(HKEY_LOCAL_MACHINE, L"software\\Microsoft\\google_unit_tests");
-
- // Tests if we need to handle differently the "\\" at the end.
- // This is denied. We need to add both rules.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(
- L"Reg_OpenKey create read HKEY_LOCAL_MACHINE software\\microsoft\\"));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(
- L"Reg_OpenKey open read HKEY_LOCAL_MACHINE software\\microsoft\\"));
-}
-
-TEST(RegistryPolicyTest, TestKeyNoAccess) {
- TestRunner runner;
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE"));
-
- // Tests read access where we don't have access at all.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(
- L"Reg_OpenKey create read HKEY_LOCAL_MACHINE software"));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(
- L"Reg_OpenKey open read HKEY_LOCAL_MACHINE software"));
-}
-
-TEST(RegistryPolicyTest, TestKeyReadOnlyAccess) {
- TestRunner runner;
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE\\Software\\Policies"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE\\Software\\Policies\\*"));
-
- // Tests subdirectory acess on keys where we have subdirectory acess.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Reg_OpenKey create read "
- L"HKEY_LOCAL_MACHINE software\\Policies\\microsoft"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Reg_OpenKey open read "
- L"HKEY_LOCAL_MACHINE software\\Policies\\microsoft"));
-
- // Tests to see if we can create keys where we have subdirectory access.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Reg_OpenKey create write "
- L"HKEY_LOCAL_MACHINE software\\Policies\\google_unit_tests"));
-
- RegDeleteKey(HKEY_LOCAL_MACHINE, L"software\\Policies\\google_unit_tests");
-}
-
-TEST(RegistryPolicyTest, TestKeyAllAccessSubDir) {
- TestRunner runner;
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_ANY,
- L"HKEY_LOCAL_MACHINE\\Software\\Policies"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_ANY,
- L"HKEY_LOCAL_MACHINE\\Software\\Policies\\*"));
-
- if (::IsUserAnAdmin()) {
- // Tests to see if we can create keys where we have subdirectory access.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Reg_OpenKey create write "
- L"HKEY_LOCAL_MACHINE software\\Policies\\google_unit_tests"));
-
- RegDeleteKey(HKEY_LOCAL_MACHINE, L"software\\Policies\\google_unit_tests");
- }
-}
-
-TEST(RegistryPolicyTest, TestKeyCreateLink) {
- TestRunner runner;
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_ANY,
- L"HKEY_LOCAL_MACHINE\\Software\\Policies"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_ANY,
- L"HKEY_LOCAL_MACHINE\\Software\\Policies\\*"));
-
- // Tests to see if we can create a registry link key.
- // NOTE: In theory here we should make sure to check for SBOX_TEST_DENIED
- // instead of !SBOX_TEST_SUCCEEDED, but unfortunately the result is not
- // access denied. Internally RegCreateKeyEx (At least on Vista 64) tries to
- // create the link, and we return successfully access denied, then, it
- // decides to try to break the path in multiple chunks, and create the links
- // one by one. In this scenario, it tries to create "HKLM\Software" as a
- // link key, which obviously fail with STATUS_OBJECT_NAME_COLLISION, and
- // this is what is returned to the user.
- EXPECT_NE(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Reg_OpenKey create link "
- L"HKEY_LOCAL_MACHINE software\\Policies\\google_unit_tests"));
-
- // In case our code fails, and the call works, we need to delete the new
- // link. There is no api for this, so we need to use the NT call.
- HKEY key = NULL;
- LRESULT result = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- L"software\\Policies\\google_unit_tests",
- REG_OPTION_OPEN_LINK, MAXIMUM_ALLOWED,
- &key);
-
- if (!result) {
- HMODULE ntdll = GetModuleHandle(L"ntdll.dll");
- NtDeleteKeyFunction NtDeleteKey =
- reinterpret_cast<NtDeleteKeyFunction>(GetProcAddress(ntdll,
- "NtDeleteKey"));
- NtDeleteKey(key);
- }
-}
-
-TEST(RegistryPolicyTest, TestKeyReadOnlyHKCU) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_CURRENT_USER"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_CURRENT_USER\\Software"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_USERS\\.default"));
-
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_USERS\\.default\\software"));
-
- // Tests read access where we only have read-only access.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(
- L"Reg_OpenKey create read HKEY_CURRENT_USER software"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(
- L"Reg_OpenKey open read HKEY_CURRENT_USER software"));
-
- // Tests write access where we only have read-only acess.
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(
- L"Reg_OpenKey create write HKEY_CURRENT_USER software"));
-
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(
- L"Reg_OpenKey open write HKEY_CURRENT_USER software"));
-
- // Tests maximum allowed access where we only have read-only access.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(
- L"Reg_OpenKey create maximum_allowed HKEY_CURRENT_USER software"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(
- L"Reg_OpenKey open maximum_allowed HKEY_CURRENT_USER software"));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/resolver.cc b/security/sandbox/chromium/sandbox/win/src/resolver.cc
deleted file mode 100644
index d1719da51..000000000
--- a/security/sandbox/chromium/sandbox/win/src/resolver.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright (c) 2006-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 "sandbox/win/src/resolver.h"
-
-#include <stddef.h>
-
-#include "base/win/pe_image.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-namespace sandbox {
-
-NTSTATUS ResolverThunk::Init(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes) {
- if (NULL == thunk_storage || 0 == storage_bytes ||
- NULL == target_module || NULL == target_name)
- return STATUS_INVALID_PARAMETER;
-
- if (storage_bytes < GetThunkSize())
- return STATUS_BUFFER_TOO_SMALL;
-
- NTSTATUS ret = STATUS_SUCCESS;
- if (NULL == interceptor_entry_point) {
- ret = ResolveInterceptor(interceptor_module, interceptor_name,
- &interceptor_entry_point);
- if (!NT_SUCCESS(ret))
- return ret;
- }
-
- ret = ResolveTarget(target_module, target_name, &target_);
- if (!NT_SUCCESS(ret))
- return ret;
-
- interceptor_ = interceptor_entry_point;
-
- return ret;
-}
-
-NTSTATUS ResolverThunk::ResolveInterceptor(const void* interceptor_module,
- const char* interceptor_name,
- const void** address) {
- DCHECK_NT(address);
- if (!interceptor_module)
- return STATUS_INVALID_PARAMETER;
-
- base::win::PEImage pe(interceptor_module);
- if (!pe.VerifyMagic())
- return STATUS_INVALID_IMAGE_FORMAT;
-
- *address = pe.GetProcAddress(interceptor_name);
-
- if (!(*address))
- return STATUS_PROCEDURE_NOT_FOUND;
-
- return STATUS_SUCCESS;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/resolver.h b/security/sandbox/chromium/sandbox/win/src/resolver.h
deleted file mode 100644
index 9424060a3..000000000
--- a/security/sandbox/chromium/sandbox/win/src/resolver.h
+++ /dev/null
@@ -1,107 +0,0 @@
-// 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.
-
-// Defines ResolverThunk, the interface for classes that perform interceptions.
-// For more details see
-// http://dev.chromium.org/developers/design-documents/sandbox .
-
-#include <stddef.h>
-
-#include "base/macros.h"
-#include "sandbox/win/src/nt_internals.h"
-
-#ifndef SANDBOX_SRC_RESOLVER_H__
-#define SANDBOX_SRC_RESOLVER_H__
-
-namespace sandbox {
-
-// A resolver is the object in charge of performing the actual interception of
-// a function. There should be a concrete implementation of a resolver roughly
-// per type of interception.
-class ResolverThunk {
- public:
- ResolverThunk() {}
- virtual ~ResolverThunk() {}
-
- // Performs the actual interception of a function.
- // target_name is an exported function from the module loaded at
- // target_module, and must be replaced by interceptor_name, exported from
- // interceptor_module. interceptor_entry_point can be provided instead of
- // interceptor_name / interceptor_module.
- // thunk_storage must point to a buffer on the child's address space, to hold
- // the patch thunk, and related data. If provided, storage_used will receive
- // the number of bytes used from thunk_storage.
- //
- // Example: (without error checking)
- //
- // size_t size = resolver.GetThunkSize();
- // char* buffer = ::VirtualAllocEx(child_process, NULL, size,
- // MEM_COMMIT, PAGE_READWRITE);
- // resolver.Setup(ntdll_module, NULL, L"NtCreateFile", NULL,
- // &MyReplacementFunction, buffer, size, NULL);
- //
- // In general, the idea is to allocate a single big buffer for all
- // interceptions on the same dll, and call Setup n times.
- // WARNING: This means that any data member that is specific to a single
- // interception must be reset within this method.
- virtual NTSTATUS Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) = 0;
-
- // Gets the address of function_name inside module (main exe).
- virtual NTSTATUS ResolveInterceptor(const void* module,
- const char* function_name,
- const void** address);
-
- // Gets the address of an exported function_name inside module.
- virtual NTSTATUS ResolveTarget(const void* module,
- const char* function_name,
- void** address);
-
- // Gets the required buffer size for this type of thunk.
- virtual size_t GetThunkSize() const = 0;
-
- protected:
- // Performs basic initialization on behalf of a concrete instance of a
- // resolver. That is, parameter validation and resolution of the target
- // and the interceptor into the member variables.
- //
- // target_name is an exported function from the module loaded at
- // target_module, and must be replaced by interceptor_name, exported from
- // interceptor_module. interceptor_entry_point can be provided instead of
- // interceptor_name / interceptor_module.
- // thunk_storage must point to a buffer on the child's address space, to hold
- // the patch thunk, and related data.
- virtual NTSTATUS Init(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes);
-
- // Gets the required buffer size for the internal part of the thunk.
- size_t GetInternalThunkSize() const;
-
- // Initializes the internal part of the thunk.
- // interceptor is the function to be called instead of original_function.
- bool SetInternalThunk(void* storage, size_t storage_bytes,
- const void* original_function, const void* interceptor);
-
- // Holds the resolved interception target.
- void* target_;
- // Holds the resolved interception interceptor.
- const void* interceptor_;
-
- DISALLOW_COPY_AND_ASSIGN(ResolverThunk);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_RESOLVER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/resolver_32.cc b/security/sandbox/chromium/sandbox/win/src/resolver_32.cc
deleted file mode 100644
index 25df11cc4..000000000
--- a/security/sandbox/chromium/sandbox/win/src/resolver_32.cc
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright (c) 2006-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 "sandbox/win/src/resolver.h"
-
-#include <stddef.h>
-
-// For placement new. This file must not depend on the CRT at runtime, but
-// placement operator new is inline.
-#include <new>
-
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-namespace {
-
-#pragma pack(push, 1)
-struct InternalThunk {
- // This struct contains roughly the following code:
- // sub esp, 8 // Create working space
- // push edx // Save register
- // mov edx, [esp + 0xc] // Get return adddress
- // mov [esp + 8], edx // Store return address
- // mov dword ptr [esp + 0xc], 0x7c401200 // Store extra argument
- // mov dword ptr [esp + 4], 0x40010203 // Store address to jump to
- // pop edx // Restore register
- // ret // Jump to interceptor
- //
- // This code only modifies esp and eip so it must work with to normal calling
- // convention. It is assembled as:
- //
- // 00 83ec08 sub esp,8
- // 03 52 push edx
- // 04 8b54240c mov edx,dword ptr [esp + 0Ch]
- // 08 89542408 mov dword ptr [esp + 8], edx
- // 0c c744240c0012407c mov dword ptr [esp + 0Ch], 7C401200h
- // 14 c744240403020140 mov dword ptr [esp + 4], 40010203h
- // 1c 5a pop edx
- // 1d c3 ret
- InternalThunk() {
- opcodes_1 = 0x5208ec83;
- opcodes_2 = 0x0c24548b;
- opcodes_3 = 0x08245489;
- opcodes_4 = 0x0c2444c7;
- opcodes_5 = 0x042444c7;
- opcodes_6 = 0xc35a;
- extra_argument = 0;
- interceptor_function = 0;
- };
- ULONG opcodes_1; // = 0x5208ec83
- ULONG opcodes_2; // = 0x0c24548b
- ULONG opcodes_3; // = 0x08245489
- ULONG opcodes_4; // = 0x0c2444c7
- ULONG extra_argument;
- ULONG opcodes_5; // = 0x042444c7
- ULONG interceptor_function;
- USHORT opcodes_6; // = 0xc35a
-};
-#pragma pack(pop)
-
-}; // namespace
-
-namespace sandbox {
-
-bool ResolverThunk::SetInternalThunk(void* storage, size_t storage_bytes,
- const void* original_function,
- const void* interceptor) {
- if (storage_bytes < sizeof(InternalThunk))
- return false;
-
- InternalThunk* thunk = new(storage) InternalThunk;
-
-#pragma warning(push)
-#pragma warning(disable: 4311)
- // These casts generate warnings because they are 32 bit specific.
- thunk->interceptor_function = reinterpret_cast<ULONG>(interceptor);
- thunk->extra_argument = reinterpret_cast<ULONG>(original_function);
-#pragma warning(pop)
-
- return true;
-}
-
-size_t ResolverThunk::GetInternalThunkSize() const {
- return sizeof(InternalThunk);
-}
-
-NTSTATUS ResolverThunk::ResolveTarget(const void* module,
- const char* function_name,
- void** address) {
- const void** casted = const_cast<const void**>(address);
- return ResolverThunk::ResolveInterceptor(module, function_name, casted);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/resolver_64.cc b/security/sandbox/chromium/sandbox/win/src/resolver_64.cc
deleted file mode 100644
index 6a9973544..000000000
--- a/security/sandbox/chromium/sandbox/win/src/resolver_64.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) 2006-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 "sandbox/win/src/resolver.h"
-
-#include <stddef.h>
-
-// For placement new. This file must not depend on the CRT at runtime, but
-// placement operator new is inline.
-#include <new>
-
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-namespace {
-
-const USHORT kMovRax = 0xB848;
-const USHORT kJmpRax = 0xe0ff;
-
-#pragma pack(push, 1)
-struct InternalThunk {
- // This struct contains roughly the following code:
- // 01 48b8f0debc9a78563412 mov rax,123456789ABCDEF0h
- // ff e0 jmp rax
- //
- // The code modifies rax, but that's fine for x64 ABI.
-
- InternalThunk() {
- mov_rax = kMovRax;
- jmp_rax = kJmpRax;
- interceptor_function = 0;
- };
- USHORT mov_rax; // = 48 B8
- ULONG_PTR interceptor_function;
- USHORT jmp_rax; // = ff e0
-};
-#pragma pack(pop)
-
-} // namespace.
-
-namespace sandbox {
-
-size_t ResolverThunk::GetInternalThunkSize() const {
- return sizeof(InternalThunk);
-}
-
-bool ResolverThunk::SetInternalThunk(void* storage, size_t storage_bytes,
- const void* original_function,
- const void* interceptor) {
- if (storage_bytes < sizeof(InternalThunk))
- return false;
-
- InternalThunk* thunk = new(storage) InternalThunk;
- thunk->interceptor_function = reinterpret_cast<ULONG_PTR>(interceptor);
-
- return true;
-}
-
-NTSTATUS ResolverThunk::ResolveTarget(const void* module,
- const char* function_name,
- void** address) {
- // We don't support sidestep & co.
- return STATUS_NOT_IMPLEMENTED;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/restricted_token.cc b/security/sandbox/chromium/sandbox/win/src/restricted_token.cc
deleted file mode 100644
index 607795240..000000000
--- a/security/sandbox/chromium/sandbox/win/src/restricted_token.cc
+++ /dev/null
@@ -1,458 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/restricted_token.h"
-
-#include <stddef.h>
-
-#include <vector>
-
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/acl.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-// Calls GetTokenInformation with the desired |info_class| and returns a buffer
-// with the result.
-scoped_ptr<BYTE[]> GetTokenInfo(const base::win::ScopedHandle& token,
- TOKEN_INFORMATION_CLASS info_class,
- DWORD* error) {
- // Get the required buffer size.
- DWORD size = 0;
- ::GetTokenInformation(token.Get(), info_class, NULL, 0, &size);
- if (!size) {
- *error = ::GetLastError();
- return nullptr;
- }
-
- scoped_ptr<BYTE[]> buffer(new BYTE[size]);
- if (!::GetTokenInformation(token.Get(), info_class, buffer.get(), size,
- &size)) {
- *error = ::GetLastError();
- return nullptr;
- }
-
- *error = ERROR_SUCCESS;
- return buffer.Pass();
-}
-
-} // namespace
-
-namespace sandbox {
-
-RestrictedToken::RestrictedToken()
- : integrity_level_(INTEGRITY_LEVEL_LAST),
- init_(false) {
-}
-
-RestrictedToken::~RestrictedToken() {
-}
-
-DWORD RestrictedToken::Init(const HANDLE effective_token) {
- if (init_)
- return ERROR_ALREADY_INITIALIZED;
-
- HANDLE temp_token;
- if (effective_token) {
- // We duplicate the handle to be able to use it even if the original handle
- // is closed.
- if (!::DuplicateHandle(::GetCurrentProcess(), effective_token,
- ::GetCurrentProcess(), &temp_token,
- 0, FALSE, DUPLICATE_SAME_ACCESS)) {
- return ::GetLastError();
- }
- } else {
- if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
- &temp_token)) {
- return ::GetLastError();
- }
- }
- effective_token_.Set(temp_token);
-
- init_ = true;
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::GetRestrictedToken(
- base::win::ScopedHandle* token) const {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- size_t deny_size = sids_for_deny_only_.size();
- size_t restrict_size = sids_to_restrict_.size();
- size_t privileges_size = privileges_to_disable_.size();
-
- SID_AND_ATTRIBUTES *deny_only_array = NULL;
- if (deny_size) {
- deny_only_array = new SID_AND_ATTRIBUTES[deny_size];
-
- for (unsigned int i = 0; i < sids_for_deny_only_.size() ; ++i) {
- deny_only_array[i].Attributes = SE_GROUP_USE_FOR_DENY_ONLY;
- deny_only_array[i].Sid =
- const_cast<SID*>(sids_for_deny_only_[i].GetPSID());
- }
- }
-
- SID_AND_ATTRIBUTES *sids_to_restrict_array = NULL;
- if (restrict_size) {
- sids_to_restrict_array = new SID_AND_ATTRIBUTES[restrict_size];
-
- for (unsigned int i = 0; i < restrict_size; ++i) {
- sids_to_restrict_array[i].Attributes = 0;
- sids_to_restrict_array[i].Sid =
- const_cast<SID*>(sids_to_restrict_[i].GetPSID());
- }
- }
-
- LUID_AND_ATTRIBUTES *privileges_to_disable_array = NULL;
- if (privileges_size) {
- privileges_to_disable_array = new LUID_AND_ATTRIBUTES[privileges_size];
-
- for (unsigned int i = 0; i < privileges_size; ++i) {
- privileges_to_disable_array[i].Attributes = 0;
- privileges_to_disable_array[i].Luid = privileges_to_disable_[i];
- }
- }
-
- BOOL result = TRUE;
- HANDLE new_token_handle = NULL;
- // The SANDBOX_INERT flag did nothing in XP and it was just a way to tell
- // if a token has ben restricted given the limiations of IsTokenRestricted()
- // but it appears that in Windows 7 it hints the AppLocker subsystem to
- // leave us alone.
- if (deny_size || restrict_size || privileges_size) {
- result = ::CreateRestrictedToken(effective_token_.Get(),
- SANDBOX_INERT,
- static_cast<DWORD>(deny_size),
- deny_only_array,
- static_cast<DWORD>(privileges_size),
- privileges_to_disable_array,
- static_cast<DWORD>(restrict_size),
- sids_to_restrict_array,
- &new_token_handle);
- } else {
- // Duplicate the token even if it's not modified at this point
- // because any subsequent changes to this token would also affect the
- // current process.
- result = ::DuplicateTokenEx(effective_token_.Get(), TOKEN_ALL_ACCESS, NULL,
- SecurityIdentification, TokenPrimary,
- &new_token_handle);
- }
- auto last_error = ::GetLastError();
-
- if (deny_only_array)
- delete[] deny_only_array;
-
- if (sids_to_restrict_array)
- delete[] sids_to_restrict_array;
-
- if (privileges_to_disable_array)
- delete[] privileges_to_disable_array;
-
- if (!result)
- return last_error;
-
- base::win::ScopedHandle new_token(new_token_handle);
-
- // Modify the default dacl on the token to contain Restricted and the user.
- if (!AddSidToDefaultDacl(new_token.Get(), WinRestrictedCodeSid, GENERIC_ALL))
- return ::GetLastError();
-
- if (!AddUserSidToDefaultDacl(new_token.Get(), GENERIC_ALL))
- return ::GetLastError();
-
- DWORD error = SetTokenIntegrityLevel(new_token.Get(), integrity_level_);
- if (ERROR_SUCCESS != error)
- return error;
-
- HANDLE token_handle;
- if (!::DuplicateHandle(::GetCurrentProcess(), new_token.Get(),
- ::GetCurrentProcess(), &token_handle,
- TOKEN_ALL_ACCESS, FALSE, // Don't inherit.
- 0)) {
- return ::GetLastError();
- }
-
- token->Set(token_handle);
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::GetRestrictedTokenForImpersonation(
- base::win::ScopedHandle* token) const {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- base::win::ScopedHandle restricted_token;
- DWORD err_code = GetRestrictedToken(&restricted_token);
- if (ERROR_SUCCESS != err_code)
- return err_code;
-
- HANDLE impersonation_token_handle;
- if (!::DuplicateToken(restricted_token.Get(),
- SecurityImpersonation,
- &impersonation_token_handle)) {
- return ::GetLastError();
- }
- base::win::ScopedHandle impersonation_token(impersonation_token_handle);
-
- HANDLE token_handle;
- if (!::DuplicateHandle(::GetCurrentProcess(), impersonation_token.Get(),
- ::GetCurrentProcess(), &token_handle,
- TOKEN_ALL_ACCESS, FALSE, // Don't inherit.
- 0)) {
- return ::GetLastError();
- }
-
- token->Set(token_handle);
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::AddAllSidsForDenyOnly(std::vector<Sid> *exceptions) {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- DWORD error;
- scoped_ptr<BYTE[]> buffer =
- GetTokenInfo(effective_token_, TokenGroups, &error);
-
- if (!buffer)
- return error;
-
- TOKEN_GROUPS* token_groups = reinterpret_cast<TOKEN_GROUPS*>(buffer.get());
-
- // Build the list of the deny only group SIDs
- for (unsigned int i = 0; i < token_groups->GroupCount ; ++i) {
- if ((token_groups->Groups[i].Attributes & SE_GROUP_INTEGRITY) == 0 &&
- (token_groups->Groups[i].Attributes & SE_GROUP_LOGON_ID) == 0) {
- bool should_ignore = false;
- if (exceptions) {
- for (unsigned int j = 0; j < exceptions->size(); ++j) {
- if (::EqualSid(const_cast<SID*>((*exceptions)[j].GetPSID()),
- token_groups->Groups[i].Sid)) {
- should_ignore = true;
- break;
- }
- }
- }
- if (!should_ignore) {
- sids_for_deny_only_.push_back(
- reinterpret_cast<SID*>(token_groups->Groups[i].Sid));
- }
- }
- }
-
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::AddDenyOnlySids(const std::vector<Sid>& deny_only_sids) {
- DCHECK(init_);
- if (!init_) {
- return ERROR_NO_TOKEN;
- }
-
- DWORD error;
- scoped_ptr<BYTE[]> buffer = GetTokenInfo(effective_token_, TokenGroups, &error);
-
- if (!buffer) {
- return error;
- }
-
- TOKEN_GROUPS* token_groups = reinterpret_cast<TOKEN_GROUPS*>(buffer.get());
-
- // Build the list of the deny only group SIDs
- for (unsigned int i = 0; i < token_groups->GroupCount ; ++i) {
- if ((token_groups->Groups[i].Attributes & SE_GROUP_INTEGRITY) == 0 &&
- (token_groups->Groups[i].Attributes & SE_GROUP_LOGON_ID) == 0) {
- for (unsigned int j = 0; j < deny_only_sids.size(); ++j) {
- if (::EqualSid(const_cast<SID*>(deny_only_sids[j].GetPSID()),
- token_groups->Groups[i].Sid)) {
- sids_for_deny_only_.push_back(
- reinterpret_cast<SID*>(token_groups->Groups[i].Sid));
- break;
- }
- }
- }
- }
-
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::AddSidForDenyOnly(const Sid &sid) {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- sids_for_deny_only_.push_back(sid);
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::AddUserSidForDenyOnly() {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
- scoped_ptr<BYTE[]> buffer(new BYTE[size]);
- TOKEN_USER* token_user = reinterpret_cast<TOKEN_USER*>(buffer.get());
-
- BOOL result = ::GetTokenInformation(effective_token_.Get(), TokenUser,
- token_user, size, &size);
-
- if (!result)
- return ::GetLastError();
-
- Sid user = reinterpret_cast<SID*>(token_user->User.Sid);
- sids_for_deny_only_.push_back(user);
-
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::DeleteAllPrivileges(
- const std::vector<base::string16> *exceptions) {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- DWORD error;
- scoped_ptr<BYTE[]> buffer =
- GetTokenInfo(effective_token_, TokenPrivileges, &error);
-
- if (!buffer)
- return error;
-
- TOKEN_PRIVILEGES* token_privileges =
- reinterpret_cast<TOKEN_PRIVILEGES*>(buffer.get());
-
- // Build the list of privileges to disable
- for (unsigned int i = 0; i < token_privileges->PrivilegeCount; ++i) {
- bool should_ignore = false;
- if (exceptions) {
- for (unsigned int j = 0; j < exceptions->size(); ++j) {
- LUID luid = {0};
- ::LookupPrivilegeValue(NULL, (*exceptions)[j].c_str(), &luid);
- if (token_privileges->Privileges[i].Luid.HighPart == luid.HighPart &&
- token_privileges->Privileges[i].Luid.LowPart == luid.LowPart) {
- should_ignore = true;
- break;
- }
- }
- }
- if (!should_ignore) {
- privileges_to_disable_.push_back(token_privileges->Privileges[i].Luid);
- }
- }
-
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::DeletePrivilege(const wchar_t *privilege) {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- LUID luid = {0};
- if (LookupPrivilegeValue(NULL, privilege, &luid))
- privileges_to_disable_.push_back(luid);
- else
- return ::GetLastError();
-
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::AddRestrictingSid(const Sid &sid) {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- sids_to_restrict_.push_back(sid); // No attributes
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::AddRestrictingSidLogonSession() {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- DWORD error;
- scoped_ptr<BYTE[]> buffer =
- GetTokenInfo(effective_token_, TokenGroups, &error);
-
- if (!buffer)
- return error;
-
- TOKEN_GROUPS* token_groups = reinterpret_cast<TOKEN_GROUPS*>(buffer.get());
-
- SID *logon_sid = NULL;
- for (unsigned int i = 0; i < token_groups->GroupCount ; ++i) {
- if ((token_groups->Groups[i].Attributes & SE_GROUP_LOGON_ID) != 0) {
- logon_sid = static_cast<SID*>(token_groups->Groups[i].Sid);
- break;
- }
- }
-
- if (logon_sid)
- sids_to_restrict_.push_back(logon_sid);
-
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::AddRestrictingSidCurrentUser() {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
- scoped_ptr<BYTE[]> buffer(new BYTE[size]);
- TOKEN_USER* token_user = reinterpret_cast<TOKEN_USER*>(buffer.get());
-
- BOOL result = ::GetTokenInformation(effective_token_.Get(), TokenUser,
- token_user, size, &size);
-
- if (!result)
- return ::GetLastError();
-
- Sid user = reinterpret_cast<SID*>(token_user->User.Sid);
- sids_to_restrict_.push_back(user);
-
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::AddRestrictingSidAllSids() {
- DCHECK(init_);
- if (!init_)
- return ERROR_NO_TOKEN;
-
- // Add the current user to the list.
- DWORD error = AddRestrictingSidCurrentUser();
- if (ERROR_SUCCESS != error)
- return error;
-
- scoped_ptr<BYTE[]> buffer =
- GetTokenInfo(effective_token_, TokenGroups, &error);
-
- if (!buffer)
- return error;
-
- TOKEN_GROUPS* token_groups = reinterpret_cast<TOKEN_GROUPS*>(buffer.get());
-
- // Build the list of restricting sids from all groups.
- for (unsigned int i = 0; i < token_groups->GroupCount ; ++i) {
- if ((token_groups->Groups[i].Attributes & SE_GROUP_INTEGRITY) == 0)
- AddRestrictingSid(reinterpret_cast<SID*>(token_groups->Groups[i].Sid));
- }
-
- return ERROR_SUCCESS;
-}
-
-DWORD RestrictedToken::SetIntegrityLevel(IntegrityLevel integrity_level) {
- integrity_level_ = integrity_level;
- return ERROR_SUCCESS;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/restricted_token.h b/security/sandbox/chromium/sandbox/win/src/restricted_token.h
deleted file mode 100644
index 623c885fc..000000000
--- a/security/sandbox/chromium/sandbox/win/src/restricted_token.h
+++ /dev/null
@@ -1,201 +0,0 @@
-// 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 SANDBOX_SRC_RESTRICTED_TOKEN_H_
-#define SANDBOX_SRC_RESTRICTED_TOKEN_H_
-
-#include <windows.h>
-#include <vector>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/restricted_token_utils.h"
-#include "sandbox/win/src/security_level.h"
-#include "sandbox/win/src/sid.h"
-
-// Flags present in the Group SID list. These 2 flags are new in Windows Vista
-#ifndef SE_GROUP_INTEGRITY
-#define SE_GROUP_INTEGRITY (0x00000020L)
-#endif
-#ifndef SE_GROUP_INTEGRITY_ENABLED
-#define SE_GROUP_INTEGRITY_ENABLED (0x00000040L)
-#endif
-
-namespace sandbox {
-
-// Handles the creation of a restricted token using the effective token or
-// any token handle.
-// Sample usage:
-// RestrictedToken restricted_token;
-// DWORD err_code = restricted_token.Init(NULL); // Use the current
-// // effective token
-// if (ERROR_SUCCESS != err_code) {
-// // handle error.
-// }
-//
-// restricted_token.AddRestrictingSid(ATL::Sids::Users().GetPSID());
-// base::win::ScopedHandle token_handle;
-// err_code = restricted_token.GetRestrictedToken(&token_handle);
-// if (ERROR_SUCCESS != err_code) {
-// // handle error.
-// }
-// [...]
-class RestrictedToken {
- public:
- // Init() has to be called before calling any other method in the class.
- RestrictedToken();
- ~RestrictedToken();
-
- // Initializes the RestrictedToken object with effective_token.
- // If effective_token is NULL, it initializes the RestrictedToken object with
- // the effective token of the current process.
- DWORD Init(HANDLE effective_token);
-
- // Creates a restricted token.
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- DWORD GetRestrictedToken(base::win::ScopedHandle* token) const;
-
- // Creates a restricted token and uses this new token to create a new token
- // for impersonation. Returns this impersonation token.
- //
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- //
- // The sample usage is the same as the GetRestrictedToken function.
- DWORD GetRestrictedTokenForImpersonation(
- base::win::ScopedHandle* token) const;
-
- // Lists all sids in the token and mark them as Deny Only except for those
- // present in the exceptions parameter. If there is no exception needed,
- // the caller can pass an empty list or NULL for the exceptions
- // parameter.
- //
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- //
- // Sample usage:
- // std::vector<Sid> sid_exceptions;
- // sid_exceptions.push_back(ATL::Sids::Users().GetPSID());
- // sid_exceptions.push_back(ATL::Sids::World().GetPSID());
- // restricted_token.AddAllSidsForDenyOnly(&sid_exceptions);
- // Note: A Sid marked for Deny Only in a token cannot be used to grant
- // access to any resource. It can only be used to deny access.
- DWORD AddAllSidsForDenyOnly(std::vector<Sid> *exceptions);
-
- // Lists all sids in the token and mark them as Deny Only if present in the
- // deny_only_sids parameter.
- //
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- //
- // Note: A Sid marked for Deny Only in a token cannot be used to grant
- // access to any resource. It can only be used to deny access.
- DWORD AddDenyOnlySids(const std::vector<Sid>& deny_only_sids);
-
- // Adds a user or group SID for Deny Only in the restricted token.
- // Parameter: sid is the SID to add in the Deny Only list.
- // The return value is always ERROR_SUCCESS.
- //
- // Sample Usage:
- // restricted_token.AddSidForDenyOnly(ATL::Sids::Admins().GetPSID());
- DWORD AddSidForDenyOnly(const Sid &sid);
-
- // Adds the user sid of the token for Deny Only in the restricted token.
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- DWORD AddUserSidForDenyOnly();
-
- // Lists all privileges in the token and add them to the list of privileges
- // to remove except for those present in the exceptions parameter. If
- // there is no exception needed, the caller can pass an empty list or NULL
- // for the exceptions parameter.
- //
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- //
- // Sample usage:
- // std::vector<base::string16> privilege_exceptions;
- // privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
- // restricted_token.DeleteAllPrivileges(&privilege_exceptions);
- DWORD DeleteAllPrivileges(const std::vector<base::string16> *exceptions);
-
- // Adds a privilege to the list of privileges to remove in the restricted
- // token.
- // Parameter: privilege is the privilege name to remove. This is the string
- // representing the privilege. (e.g. "SeChangeNotifyPrivilege").
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- //
- // Sample usage:
- // restricted_token.DeletePrivilege(SE_LOAD_DRIVER_NAME);
- DWORD DeletePrivilege(const wchar_t *privilege);
-
- // Adds a SID to the list of restricting sids in the restricted token.
- // Parameter: sid is the sid to add to the list restricting sids.
- // The return value is always ERROR_SUCCESS.
- //
- // Sample usage:
- // restricted_token.AddRestrictingSid(ATL::Sids::Users().GetPSID());
- // Note: The list of restricting is used to force Windows to perform all
- // access checks twice. The first time using your user SID and your groups,
- // and the second time using your list of restricting sids. The access has
- // to be granted in both places to get access to the resource requested.
- DWORD AddRestrictingSid(const Sid &sid);
-
- // Adds the logon sid of the token in the list of restricting sids for the
- // restricted token.
- //
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- DWORD AddRestrictingSidLogonSession();
-
- // Adds the owner sid of the token in the list of restricting sids for the
- // restricted token.
- //
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- DWORD AddRestrictingSidCurrentUser();
-
- // Adds all group sids and the user sid to the restricting sids list.
- //
- // If the function succeeds, the return value is ERROR_SUCCESS. If the
- // function fails, the return value is the win32 error code corresponding to
- // the error.
- DWORD AddRestrictingSidAllSids();
-
- // Sets the token integrity level. This is only valid on Vista. The integrity
- // level cannot be higher than your current integrity level.
- DWORD SetIntegrityLevel(IntegrityLevel integrity_level);
-
- private:
- // The list of restricting sids in the restricted token.
- std::vector<Sid> sids_to_restrict_;
- // The list of privileges to remove in the restricted token.
- std::vector<LUID> privileges_to_disable_;
- // The list of sids to mark as Deny Only in the restricted token.
- std::vector<Sid> sids_for_deny_only_;
- // The token to restrict. Can only be set in a constructor.
- base::win::ScopedHandle effective_token_;
- // The token integrity level. Only valid on Vista.
- IntegrityLevel integrity_level_;
- // Tells if the object is initialized or not (if Init() has been called)
- bool init_;
-
- DISALLOW_COPY_AND_ASSIGN(RestrictedToken);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_RESTRICTED_TOKEN_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/restricted_token_unittest.cc b/security/sandbox/chromium/sandbox/win/src/restricted_token_unittest.cc
deleted file mode 100644
index b11948e9f..000000000
--- a/security/sandbox/chromium/sandbox/win/src/restricted_token_unittest.cc
+++ /dev/null
@@ -1,620 +0,0 @@
-// 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 file contains unit tests for the RestrictedToken.
-
-#define _ATL_NO_EXCEPTIONS
-#include <atlbase.h>
-#include <atlsecurity.h>
-#include <vector>
-
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/restricted_token.h"
-#include "sandbox/win/src/sid.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-// Tests the initializatioin with an invalid token handle.
-TEST(RestrictedTokenTest, InvalidHandle) {
- RestrictedToken token;
- ASSERT_EQ(static_cast<DWORD>(ERROR_INVALID_HANDLE),
- token.Init(reinterpret_cast<HANDLE>(0x5555)));
-}
-
-// Tests the initialization with NULL as parameter.
-TEST(RestrictedTokenTest, DefaultInit) {
- // Get the current process token.
- HANDLE token_handle = INVALID_HANDLE_VALUE;
- ASSERT_TRUE(::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
- &token_handle));
-
- ASSERT_NE(INVALID_HANDLE_VALUE, token_handle);
-
- ATL::CAccessToken access_token;
- access_token.Attach(token_handle);
-
- // Create the token using the current token.
- RestrictedToken token_default;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token_default.Init(NULL));
-
- // Get the handle to the restricted token.
-
- base::win::ScopedHandle restricted_token_handle;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token_default.GetRestrictedToken(&restricted_token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(restricted_token_handle.Take());
-
- ATL::CSid sid_user_restricted;
- ATL::CSid sid_user_default;
- ATL::CSid sid_owner_restricted;
- ATL::CSid sid_owner_default;
- ASSERT_TRUE(restricted_token.GetUser(&sid_user_restricted));
- ASSERT_TRUE(access_token.GetUser(&sid_user_default));
- ASSERT_TRUE(restricted_token.GetOwner(&sid_owner_restricted));
- ASSERT_TRUE(access_token.GetOwner(&sid_owner_default));
-
- // Check if both token have the same owner and user.
- ASSERT_EQ(sid_user_restricted, sid_user_default);
- ASSERT_EQ(sid_owner_restricted, sid_owner_default);
-}
-
-// Tests the initialization with a custom token as parameter.
-TEST(RestrictedTokenTest, CustomInit) {
- // Get the current process token.
- HANDLE token_handle = INVALID_HANDLE_VALUE;
- ASSERT_TRUE(::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
- &token_handle));
-
- ASSERT_NE(INVALID_HANDLE_VALUE, token_handle);
-
- ATL::CAccessToken access_token;
- access_token.Attach(token_handle);
-
- // Change the primary group.
- access_token.SetPrimaryGroup(ATL::Sids::World());
-
- // Create the token using the current token.
- RestrictedToken token;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.Init(access_token.GetHandle()));
-
- // Get the handle to the restricted token.
-
- base::win::ScopedHandle restricted_token_handle;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&restricted_token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(restricted_token_handle.Take());
-
- ATL::CSid sid_restricted;
- ATL::CSid sid_default;
- ASSERT_TRUE(restricted_token.GetPrimaryGroup(&sid_restricted));
- ASSERT_TRUE(access_token.GetPrimaryGroup(&sid_default));
-
- // Check if both token have the same owner.
- ASSERT_EQ(sid_restricted, sid_default);
-}
-
-// Verifies that the token created by the object are valid.
-TEST(RestrictedTokenTest, ResultToken) {
- RestrictedToken token;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSid(ATL::Sids::World().GetPSID()));
-
- base::win::ScopedHandle restricted_token;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&restricted_token));
-
- ASSERT_TRUE(::IsTokenRestricted(restricted_token.Get()));
-
- DWORD length = 0;
- TOKEN_TYPE type;
- ASSERT_TRUE(::GetTokenInformation(restricted_token.Get(),
- ::TokenType,
- &type,
- sizeof(type),
- &length));
-
- ASSERT_EQ(type, TokenPrimary);
-
- base::win::ScopedHandle impersonation_token;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedTokenForImpersonation(&impersonation_token));
-
- ASSERT_TRUE(::IsTokenRestricted(impersonation_token.Get()));
-
- ASSERT_TRUE(::GetTokenInformation(impersonation_token.Get(),
- ::TokenType,
- &type,
- sizeof(type),
- &length));
-
- ASSERT_EQ(type, TokenImpersonation);
-}
-
-// Verifies that the token created has "Restricted" in its default dacl.
-TEST(RestrictedTokenTest, DefaultDacl) {
- RestrictedToken token;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSid(ATL::Sids::World().GetPSID()));
-
- base::win::ScopedHandle handle;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(handle.Take());
-
- ATL::CDacl dacl;
- ASSERT_TRUE(restricted_token.GetDefaultDacl(&dacl));
-
- bool restricted_found = false;
-
- unsigned int ace_count = dacl.GetAceCount();
- for (unsigned int i = 0; i < ace_count ; ++i) {
- ATL::CSid sid;
- ACCESS_MASK mask = 0;
- dacl.GetAclEntry(i, &sid, &mask);
- if (sid == ATL::Sids::RestrictedCode() && mask == GENERIC_ALL) {
- restricted_found = true;
- break;
- }
- }
-
- ASSERT_TRUE(restricted_found);
-}
-
-// Tests the method "AddSidForDenyOnly".
-TEST(RestrictedTokenTest, DenySid) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddSidForDenyOnly(Sid(WinWorldSid)));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenGroups groups;
- ASSERT_TRUE(restricted_token.GetGroups(&groups));
-
- ATL::CSid::CSidArray sids;
- ATL::CAtlArray<DWORD> attributes;
- groups.GetSidsAndAttributes(&sids, &attributes);
-
- for (unsigned int i = 0; i < sids.GetCount(); i++) {
- if (ATL::Sids::World() == sids[i]) {
- ASSERT_EQ(static_cast<DWORD>(SE_GROUP_USE_FOR_DENY_ONLY),
- attributes[i] & SE_GROUP_USE_FOR_DENY_ONLY);
- }
- }
-}
-
-// Tests the method "AddAllSidsForDenyOnly".
-TEST(RestrictedTokenTest, DenySids) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddAllSidsForDenyOnly(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenGroups groups;
- ASSERT_TRUE(restricted_token.GetGroups(&groups));
-
- ATL::CSid::CSidArray sids;
- ATL::CAtlArray<DWORD> attributes;
- groups.GetSidsAndAttributes(&sids, &attributes);
-
- // Verify that all sids are really gone.
- for (unsigned int i = 0; i < sids.GetCount(); i++) {
- if ((attributes[i] & SE_GROUP_LOGON_ID) == 0 &&
- (attributes[i] & SE_GROUP_INTEGRITY) == 0) {
- ASSERT_EQ(static_cast<DWORD>(SE_GROUP_USE_FOR_DENY_ONLY),
- attributes[i] & SE_GROUP_USE_FOR_DENY_ONLY);
- }
- }
-}
-
-// Tests the method "AddAllSidsForDenyOnly" using an exception list.
-TEST(RestrictedTokenTest, DenySidsException) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- std::vector<Sid> sids_exception;
- sids_exception.push_back(Sid(WinWorldSid));
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddAllSidsForDenyOnly(&sids_exception));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenGroups groups;
- ASSERT_TRUE(restricted_token.GetGroups(&groups));
-
- ATL::CSid::CSidArray sids;
- ATL::CAtlArray<DWORD> attributes;
- groups.GetSidsAndAttributes(&sids, &attributes);
-
- // Verify that all sids are really gone.
- for (unsigned int i = 0; i < sids.GetCount(); i++) {
- if ((attributes[i] & SE_GROUP_LOGON_ID) == 0 &&
- (attributes[i] & SE_GROUP_INTEGRITY) == 0) {
- if (ATL::Sids::World() == sids[i]) {
- ASSERT_EQ(0u, attributes[i] & SE_GROUP_USE_FOR_DENY_ONLY);
- } else {
- ASSERT_EQ(static_cast<DWORD>(SE_GROUP_USE_FOR_DENY_ONLY),
- attributes[i] & SE_GROUP_USE_FOR_DENY_ONLY);
- }
- }
- }
-}
-
-// Tests test method AddOwnerSidForDenyOnly.
-TEST(RestrictedTokenTest, DenyOwnerSid) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.AddUserSidForDenyOnly());
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenGroups groups;
- ASSERT_TRUE(restricted_token.GetGroups(&groups));
-
- ATL::CSid::CSidArray sids;
- ATL::CAtlArray<DWORD> attributes;
- groups.GetSidsAndAttributes(&sids, &attributes);
-
- ATL::CSid user_sid;
- ASSERT_TRUE(restricted_token.GetUser(&user_sid));
-
- for (unsigned int i = 0; i < sids.GetCount(); ++i) {
- if (user_sid == sids[i]) {
- ASSERT_EQ(static_cast<DWORD>(SE_GROUP_USE_FOR_DENY_ONLY),
- attributes[i] & SE_GROUP_USE_FOR_DENY_ONLY);
- }
- }
-}
-
-// Tests test method AddOwnerSidForDenyOnly with a custom effective token.
-TEST(RestrictedTokenTest, DenyOwnerSidCustom) {
- // Get the current process token.
- HANDLE access_handle = INVALID_HANDLE_VALUE;
- ASSERT_TRUE(::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
- &access_handle));
-
- ASSERT_NE(INVALID_HANDLE_VALUE, access_handle);
-
- ATL::CAccessToken access_token;
- access_token.Attach(access_handle);
-
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.Init(access_token.GetHandle()));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.AddUserSidForDenyOnly());
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenGroups groups;
- ASSERT_TRUE(restricted_token.GetGroups(&groups));
-
- ATL::CSid::CSidArray sids;
- ATL::CAtlArray<DWORD> attributes;
- groups.GetSidsAndAttributes(&sids, &attributes);
-
- ATL::CSid user_sid;
- ASSERT_TRUE(restricted_token.GetUser(&user_sid));
-
- for (unsigned int i = 0; i < sids.GetCount(); ++i) {
- if (user_sid == sids[i]) {
- ASSERT_EQ(static_cast<DWORD>(SE_GROUP_USE_FOR_DENY_ONLY),
- attributes[i] & SE_GROUP_USE_FOR_DENY_ONLY);
- }
- }
-}
-
-// Tests the method DeleteAllPrivileges.
-TEST(RestrictedTokenTest, DeleteAllPrivileges) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.DeleteAllPrivileges(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenPrivileges privileges;
- ASSERT_TRUE(restricted_token.GetPrivileges(&privileges));
-
- ASSERT_EQ(0u, privileges.GetCount());
-}
-
-// Tests the method DeleteAllPrivileges with an exception list.
-TEST(RestrictedTokenTest, DeleteAllPrivilegesException) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- std::vector<base::string16> exceptions;
- exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.DeleteAllPrivileges(&exceptions));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenPrivileges privileges;
- ASSERT_TRUE(restricted_token.GetPrivileges(&privileges));
-
- ATL::CTokenPrivileges::CNames privilege_names;
- ATL::CTokenPrivileges::CAttributes privilege_name_attributes;
- privileges.GetNamesAndAttributes(&privilege_names,
- &privilege_name_attributes);
-
- ASSERT_EQ(1u, privileges.GetCount());
-
- for (unsigned int i = 0; i < privileges.GetCount(); ++i) {
- ASSERT_EQ(privilege_names[i], SE_CHANGE_NOTIFY_NAME);
- }
-}
-
-// Tests the method DeletePrivilege.
-TEST(RestrictedTokenTest, DeletePrivilege) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.DeletePrivilege(SE_CHANGE_NOTIFY_NAME));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenPrivileges privileges;
- ASSERT_TRUE(restricted_token.GetPrivileges(&privileges));
-
- ATL::CTokenPrivileges::CNames privilege_names;
- ATL::CTokenPrivileges::CAttributes privilege_name_attributes;
- privileges.GetNamesAndAttributes(&privilege_names,
- &privilege_name_attributes);
-
- for (unsigned int i = 0; i < privileges.GetCount(); ++i) {
- ASSERT_NE(privilege_names[i], SE_CHANGE_NOTIFY_NAME);
- }
-}
-
-// Checks if a sid is in the restricting list of the restricted token.
-// Asserts if it's not the case. If count is a positive number, the number of
-// elements in the restricting sids list has to be equal.
-void CheckRestrictingSid(const ATL::CAccessToken &restricted_token,
- ATL::CSid sid, int count) {
- DWORD length = 8192;
- BYTE *memory = new BYTE[length];
- TOKEN_GROUPS *groups = reinterpret_cast<TOKEN_GROUPS*>(memory);
- ASSERT_TRUE(::GetTokenInformation(restricted_token.GetHandle(),
- TokenRestrictedSids,
- groups,
- length,
- &length));
-
- ATL::CTokenGroups atl_groups(*groups);
- delete[] memory;
-
- if (count >= 0)
- ASSERT_EQ(static_cast<unsigned>(count), atl_groups.GetCount());
-
- ATL::CSid::CSidArray sids;
- ATL::CAtlArray<DWORD> attributes;
- atl_groups.GetSidsAndAttributes(&sids, &attributes);
-
- bool present = false;
- for (unsigned int i = 0; i < sids.GetCount(); ++i) {
- if (sids[i] == sid) {
- present = true;
- break;
- }
- }
-
- ASSERT_TRUE(present);
-}
-
-// Tests the method AddRestrictingSid.
-TEST(RestrictedTokenTest, AddRestrictingSid) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSid(ATL::Sids::World().GetPSID()));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- CheckRestrictingSid(restricted_token, ATL::Sids::World(), 1);
-}
-
-// Tests the method AddRestrictingSidCurrentUser.
-TEST(RestrictedTokenTest, AddRestrictingSidCurrentUser) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSidCurrentUser());
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
- ATL::CSid user;
- restricted_token.GetUser(&user);
-
- CheckRestrictingSid(restricted_token, user, 1);
-}
-
-// Tests the method AddRestrictingSidCurrentUser with a custom effective token.
-TEST(RestrictedTokenTest, AddRestrictingSidCurrentUserCustom) {
- // Get the current process token.
- HANDLE access_handle = INVALID_HANDLE_VALUE;
- ASSERT_TRUE(::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS,
- &access_handle));
-
- ASSERT_NE(INVALID_HANDLE_VALUE, access_handle);
-
- ATL::CAccessToken access_token;
- access_token.Attach(access_handle);
-
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.Init(access_token.GetHandle()));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSidCurrentUser());
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
- ATL::CSid user;
- restricted_token.GetUser(&user);
-
- CheckRestrictingSid(restricted_token, user, 1);
-}
-
-// Tests the method AddRestrictingSidLogonSession.
-TEST(RestrictedTokenTest, AddRestrictingSidLogonSession) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSidLogonSession());
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
- ATL::CSid session;
- restricted_token.GetLogonSid(&session);
-
- CheckRestrictingSid(restricted_token, session, 1);
-}
-
-// Tests adding a lot of restricting sids.
-TEST(RestrictedTokenTest, AddMultipleRestrictingSids) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSidCurrentUser());
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSidLogonSession());
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSid(ATL::Sids::World().GetPSID()));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
- ATL::CSid session;
- restricted_token.GetLogonSid(&session);
-
- DWORD length = 8192;
- BYTE *memory = new BYTE[length];
- TOKEN_GROUPS *groups = reinterpret_cast<TOKEN_GROUPS*>(memory);
- ASSERT_TRUE(::GetTokenInformation(restricted_token.GetHandle(),
- TokenRestrictedSids,
- groups,
- length,
- &length));
-
- ATL::CTokenGroups atl_groups(*groups);
- delete[] memory;
-
- ASSERT_EQ(3u, atl_groups.GetCount());
-}
-
-// Tests the method "AddRestrictingSidAllSids".
-TEST(RestrictedTokenTest, AddAllSidToRestrictingSids) {
- RestrictedToken token;
- base::win::ScopedHandle token_handle;
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.AddRestrictingSidAllSids());
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS),
- token.GetRestrictedToken(&token_handle));
-
- ATL::CAccessToken restricted_token;
- restricted_token.Attach(token_handle.Take());
-
- ATL::CTokenGroups groups;
- ASSERT_TRUE(restricted_token.GetGroups(&groups));
-
- ATL::CSid::CSidArray sids;
- ATL::CAtlArray<DWORD> attributes;
- groups.GetSidsAndAttributes(&sids, &attributes);
-
- // Verify that all group sids are in the restricting sid list.
- for (unsigned int i = 0; i < sids.GetCount(); i++) {
- if ((attributes[i] & SE_GROUP_INTEGRITY) == 0) {
- CheckRestrictingSid(restricted_token, sids[i], -1);
- }
- }
-
- // Verify that the user is in the restricting sid list.
- ATL::CSid user;
- restricted_token.GetUser(&user);
- CheckRestrictingSid(restricted_token, user, -1);
-}
-
-// Checks the error code when the object is initialized twice.
-TEST(RestrictedTokenTest, DoubleInit) {
- RestrictedToken token;
- ASSERT_EQ(static_cast<DWORD>(ERROR_SUCCESS), token.Init(NULL));
-
- ASSERT_EQ(static_cast<DWORD>(ERROR_ALREADY_INITIALIZED), token.Init(NULL));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.cc b/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.cc
deleted file mode 100644
index d5b0e13c3..000000000
--- a/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.cc
+++ /dev/null
@@ -1,323 +0,0 @@
-// 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.
-
-#include <aclapi.h>
-#include <sddl.h>
-#include <vector>
-
-#include "sandbox/win/src/restricted_token_utils.h"
-
-#include "base/logging.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/job.h"
-#include "sandbox/win/src/restricted_token.h"
-#include "sandbox/win/src/security_level.h"
-#include "sandbox/win/src/sid.h"
-
-namespace sandbox {
-
-DWORD CreateRestrictedToken(TokenLevel security_level,
- IntegrityLevel integrity_level,
- TokenType token_type,
- base::win::ScopedHandle* token) {
- RestrictedToken restricted_token;
- restricted_token.Init(NULL); // Initialized with the current process token
-
- std::vector<base::string16> privilege_exceptions;
- std::vector<Sid> sid_exceptions;
- std::vector<Sid> deny_only_sids;
-
- bool deny_sids = true;
- bool remove_privileges = true;
-
- switch (security_level) {
- case USER_UNPROTECTED: {
- deny_sids = false;
- remove_privileges = false;
- break;
- }
- case USER_RESTRICTED_SAME_ACCESS: {
- deny_sids = false;
- remove_privileges = false;
-
- unsigned err_code = restricted_token.AddRestrictingSidAllSids();
- if (ERROR_SUCCESS != err_code)
- return err_code;
-
- break;
- }
- case USER_NON_ADMIN: {
- deny_sids = false;
- deny_only_sids.push_back(WinBuiltinAdministratorsSid);
- deny_only_sids.push_back(WinAccountAdministratorSid);
- deny_only_sids.push_back(WinAccountDomainAdminsSid);
- deny_only_sids.push_back(WinAccountCertAdminsSid);
- deny_only_sids.push_back(WinAccountSchemaAdminsSid);
- deny_only_sids.push_back(WinAccountEnterpriseAdminsSid);
- deny_only_sids.push_back(WinAccountPolicyAdminsSid);
- deny_only_sids.push_back(WinBuiltinHyperVAdminsSid);
- deny_only_sids.push_back(WinLocalAccountAndAdministratorSid);
- privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
- break;
- }
- case USER_INTERACTIVE: {
- sid_exceptions.push_back(WinBuiltinUsersSid);
- sid_exceptions.push_back(WinWorldSid);
- sid_exceptions.push_back(WinInteractiveSid);
- sid_exceptions.push_back(WinAuthenticatedUserSid);
- privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
- restricted_token.AddRestrictingSid(WinBuiltinUsersSid);
- restricted_token.AddRestrictingSid(WinWorldSid);
- restricted_token.AddRestrictingSid(WinRestrictedCodeSid);
- restricted_token.AddRestrictingSidCurrentUser();
- restricted_token.AddRestrictingSidLogonSession();
- break;
- }
- case USER_LIMITED: {
- sid_exceptions.push_back(WinBuiltinUsersSid);
- sid_exceptions.push_back(WinWorldSid);
- sid_exceptions.push_back(WinInteractiveSid);
- privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
- restricted_token.AddRestrictingSid(WinBuiltinUsersSid);
- restricted_token.AddRestrictingSid(WinWorldSid);
- restricted_token.AddRestrictingSid(WinRestrictedCodeSid);
-
- // This token has to be able to create objects in BNO.
- // Unfortunately, on vista, it needs the current logon sid
- // in the token to achieve this. You should also set the process to be
- // low integrity level so it can't access object created by other
- // processes.
- if (base::win::GetVersion() >= base::win::VERSION_VISTA)
- restricted_token.AddRestrictingSidLogonSession();
- break;
- }
- case USER_RESTRICTED: {
- privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
- restricted_token.AddUserSidForDenyOnly();
- restricted_token.AddRestrictingSid(WinRestrictedCodeSid);
- break;
- }
- case USER_LOCKDOWN: {
- restricted_token.AddUserSidForDenyOnly();
- restricted_token.AddRestrictingSid(WinNullSid);
- break;
- }
- default: {
- return ERROR_BAD_ARGUMENTS;
- }
- }
-
- DWORD err_code = ERROR_SUCCESS;
- if (deny_sids) {
- err_code = restricted_token.AddAllSidsForDenyOnly(&sid_exceptions);
- if (ERROR_SUCCESS != err_code)
- return err_code;
- } else if (!deny_only_sids.empty()) {
- err_code = restricted_token.AddDenyOnlySids(deny_only_sids);
- if (ERROR_SUCCESS != err_code) {
- return err_code;
- }
- }
-
- if (remove_privileges) {
- err_code = restricted_token.DeleteAllPrivileges(&privilege_exceptions);
- if (ERROR_SUCCESS != err_code)
- return err_code;
- }
-
- restricted_token.SetIntegrityLevel(integrity_level);
-
- switch (token_type) {
- case PRIMARY: {
- err_code = restricted_token.GetRestrictedToken(token);
- break;
- }
- case IMPERSONATION: {
- err_code = restricted_token.GetRestrictedTokenForImpersonation(token);
- break;
- }
- default: {
- err_code = ERROR_BAD_ARGUMENTS;
- break;
- }
- }
-
- return err_code;
-}
-
-DWORD SetObjectIntegrityLabel(HANDLE handle, SE_OBJECT_TYPE type,
- const wchar_t* ace_access,
- const wchar_t* integrity_level_sid) {
- // Build the SDDL string for the label.
- base::string16 sddl = L"S:("; // SDDL for a SACL.
- sddl += SDDL_MANDATORY_LABEL; // Ace Type is "Mandatory Label".
- sddl += L";;"; // No Ace Flags.
- sddl += ace_access; // Add the ACE access.
- sddl += L";;;"; // No ObjectType and Inherited Object Type.
- sddl += integrity_level_sid; // Trustee Sid.
- sddl += L")";
-
- DWORD error = ERROR_SUCCESS;
- PSECURITY_DESCRIPTOR sec_desc = NULL;
-
- PACL sacl = NULL;
- BOOL sacl_present = FALSE;
- BOOL sacl_defaulted = FALSE;
-
- if (::ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.c_str(),
- SDDL_REVISION,
- &sec_desc, NULL)) {
- if (::GetSecurityDescriptorSacl(sec_desc, &sacl_present, &sacl,
- &sacl_defaulted)) {
- error = ::SetSecurityInfo(handle, type,
- LABEL_SECURITY_INFORMATION, NULL, NULL, NULL,
- sacl);
- } else {
- error = ::GetLastError();
- }
-
- ::LocalFree(sec_desc);
- } else {
- return::GetLastError();
- }
-
- return error;
-}
-
-const wchar_t* GetIntegrityLevelString(IntegrityLevel integrity_level) {
- switch (integrity_level) {
- case INTEGRITY_LEVEL_SYSTEM:
- return L"S-1-16-16384";
- case INTEGRITY_LEVEL_HIGH:
- return L"S-1-16-12288";
- case INTEGRITY_LEVEL_MEDIUM:
- return L"S-1-16-8192";
- case INTEGRITY_LEVEL_MEDIUM_LOW:
- return L"S-1-16-6144";
- case INTEGRITY_LEVEL_LOW:
- return L"S-1-16-4096";
- case INTEGRITY_LEVEL_BELOW_LOW:
- return L"S-1-16-2048";
- case INTEGRITY_LEVEL_UNTRUSTED:
- return L"S-1-16-0";
- case INTEGRITY_LEVEL_LAST:
- return NULL;
- }
-
- NOTREACHED();
- return NULL;
-}
-DWORD SetTokenIntegrityLevel(HANDLE token, IntegrityLevel integrity_level) {
- if (base::win::GetVersion() < base::win::VERSION_VISTA)
- return ERROR_SUCCESS;
-
- const wchar_t* integrity_level_str = GetIntegrityLevelString(integrity_level);
- if (!integrity_level_str) {
- // No mandatory level specified, we don't change it.
- return ERROR_SUCCESS;
- }
-
- PSID integrity_sid = NULL;
- if (!::ConvertStringSidToSid(integrity_level_str, &integrity_sid))
- return ::GetLastError();
-
- TOKEN_MANDATORY_LABEL label = {};
- label.Label.Attributes = SE_GROUP_INTEGRITY;
- label.Label.Sid = integrity_sid;
-
- DWORD size = sizeof(TOKEN_MANDATORY_LABEL) + ::GetLengthSid(integrity_sid);
- BOOL result = ::SetTokenInformation(token, TokenIntegrityLevel, &label,
- size);
- auto last_error = ::GetLastError();
- ::LocalFree(integrity_sid);
-
- return result ? ERROR_SUCCESS : last_error;
-}
-
-DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level) {
- if (base::win::GetVersion() < base::win::VERSION_VISTA)
- return ERROR_SUCCESS;
-
- // We don't check for an invalid level here because we'll just let it
- // fail on the SetTokenIntegrityLevel call later on.
- if (integrity_level == INTEGRITY_LEVEL_LAST) {
- // No mandatory level specified, we don't change it.
- return ERROR_SUCCESS;
- }
-
- HANDLE token_handle;
- if (!::OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_DEFAULT,
- &token_handle))
- return ::GetLastError();
-
- base::win::ScopedHandle token(token_handle);
-
- return SetTokenIntegrityLevel(token.Get(), integrity_level);
-}
-
-DWORD HardenTokenIntegrityLevelPolicy(HANDLE token) {
- if (base::win::GetVersion() < base::win::VERSION_WIN7)
- return ERROR_SUCCESS;
-
- DWORD last_error = 0;
- DWORD length_needed = 0;
-
- ::GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION,
- NULL, 0, &length_needed);
-
- last_error = ::GetLastError();
- if (last_error != ERROR_INSUFFICIENT_BUFFER)
- return last_error;
-
- std::vector<char> security_desc_buffer(length_needed);
- PSECURITY_DESCRIPTOR security_desc =
- reinterpret_cast<PSECURITY_DESCRIPTOR>(&security_desc_buffer[0]);
-
- if (!::GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION,
- security_desc, length_needed,
- &length_needed))
- return ::GetLastError();
-
- PACL sacl = NULL;
- BOOL sacl_present = FALSE;
- BOOL sacl_defaulted = FALSE;
-
- if (!::GetSecurityDescriptorSacl(security_desc, &sacl_present,
- &sacl, &sacl_defaulted))
- return ::GetLastError();
-
- for (DWORD ace_index = 0; ace_index < sacl->AceCount; ++ace_index) {
- PSYSTEM_MANDATORY_LABEL_ACE ace;
-
- if (::GetAce(sacl, ace_index, reinterpret_cast<LPVOID*>(&ace))
- && ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE) {
- ace->Mask |= SYSTEM_MANDATORY_LABEL_NO_READ_UP
- | SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP;
- break;
- }
- }
-
- if (!::SetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION,
- security_desc))
- return ::GetLastError();
-
- return ERROR_SUCCESS;
-}
-
-DWORD HardenProcessIntegrityLevelPolicy() {
- if (base::win::GetVersion() < base::win::VERSION_WIN7)
- return ERROR_SUCCESS;
-
- HANDLE token_handle;
- if (!::OpenProcessToken(GetCurrentProcess(), READ_CONTROL | WRITE_OWNER,
- &token_handle))
- return ::GetLastError();
-
- base::win::ScopedHandle token(token_handle);
-
- return HardenTokenIntegrityLevelPolicy(token.Get());
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.h b/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.h
deleted file mode 100644
index b4e4fded9..000000000
--- a/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.h
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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 SANDBOX_SRC_RESTRICTED_TOKEN_UTILS_H__
-#define SANDBOX_SRC_RESTRICTED_TOKEN_UTILS_H__
-
-#include <accctrl.h>
-#include <windows.h>
-
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/restricted_token.h"
-#include "sandbox/win/src/security_level.h"
-
-// Contains the utility functions to be able to create restricted tokens based
-// on a security profiles.
-
-namespace sandbox {
-
-// The type of the token returned by the CreateNakedToken.
-enum TokenType {
- IMPERSONATION = 0,
- PRIMARY
-};
-
-// Creates a restricted token based on the effective token of the current
-// process. The parameter security_level determines how much the token is
-// restricted. The token_type determines if the token will be used as a primary
-// token or impersonation token. The integrity level of the token is set to
-// |integrity level| on Vista only.
-// |token| is the output value containing the handle of the newly created
-// restricted token.
-// If the function succeeds, the return value is ERROR_SUCCESS. If the
-// function fails, the return value is the win32 error code corresponding to
-// the error.
-DWORD CreateRestrictedToken(TokenLevel security_level,
- IntegrityLevel integrity_level,
- TokenType token_type,
- base::win::ScopedHandle* token);
-
-// Sets the integrity label on a object handle.
-DWORD SetObjectIntegrityLabel(HANDLE handle, SE_OBJECT_TYPE type,
- const wchar_t* ace_access,
- const wchar_t* integrity_level_sid);
-
-// Sets the integrity level on a token. This is only valid on Vista. It returns
-// without failing on XP. If the integrity level that you specify is greater
-// than the current integrity level, the function will fail.
-DWORD SetTokenIntegrityLevel(HANDLE token, IntegrityLevel integrity_level);
-
-// Returns the integrity level SDDL string associated with a given
-// IntegrityLevel value.
-const wchar_t* GetIntegrityLevelString(IntegrityLevel integrity_level);
-
-// Sets the integrity level on the current process on Vista. It returns without
-// failing on XP. If the integrity level that you specify is greater than the
-// current integrity level, the function will fail.
-DWORD SetProcessIntegrityLevel(IntegrityLevel integrity_level);
-
-// Hardens the integrity level policy on a token. This is only valid on Win 7
-// and above. Specifically it sets the policy to block read and execute so
-// that a lower privileged process cannot open the token for impersonate or
-// duplicate permissions. This should limit potential security holes.
-DWORD HardenTokenIntegrityLevelPolicy(HANDLE token);
-
-// Hardens the integrity level policy on the current process. This is only
-// valid on Win 7 and above. Specifically it sets the policy to block read
-// and execute so that a lower privileged process cannot open the token for
-// impersonate or duplicate permissions. This should limit potential security
-// holes.
-DWORD HardenProcessIntegrityLevelPolicy();
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_RESTRICTED_TOKEN_UTILS_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox.cc b/security/sandbox/chromium/sandbox/win/src/sandbox.cc
deleted file mode 100644
index 984dfecec..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox.cc
+++ /dev/null
@@ -1,48 +0,0 @@
-// 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 <stdio.h>
-#include <windows.h>
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/broker_services.h"
-#include "sandbox/win/src/target_services.h"
-
-namespace sandbox {
-// The section for IPC and policy.
-SANDBOX_INTERCEPT HANDLE g_shared_section;
-static bool s_is_broker = false;
-
-// GetBrokerServices: the current implementation relies on a shared section
-// that is created by the broker and opened by the target.
-BrokerServices* SandboxFactory::GetBrokerServices() {
- // Can't be the broker if the shared section is open.
- if (NULL != g_shared_section) {
- return NULL;
- }
- // If the shared section does not exist we are the broker, then create
- // the broker object.
- s_is_broker = true;
- return BrokerServicesBase::GetInstance();
-}
-
-// GetTargetServices implementation must follow the same technique as the
-// GetBrokerServices, but in this case the logic is the opposite.
-TargetServices* SandboxFactory::GetTargetServices() {
- // Can't be the target if the section handle is not valid.
- if (NULL == g_shared_section) {
- return NULL;
- }
- // We are the target
- s_is_broker = false;
- // Creates and returns the target services implementation.
- return TargetServicesBase::GetInstance();
-}
-
-} // namespace sandbox
-
-// Allows querying for whether the current process has been sandboxed.
-extern "C" bool __declspec(dllexport) IsSandboxedProcess() {
- return sandbox::g_shared_section != NULL;
-}
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox.h b/security/sandbox/chromium/sandbox/win/src/sandbox.h
deleted file mode 100644
index 193605d1e..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox.h
+++ /dev/null
@@ -1,164 +0,0 @@
-// 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.
-
-// Sandbox is a sandbox library for windows processes. Use when you want a
-// 'privileged' process and a 'locked down process' to interact with.
-// The privileged process is called the broker and it is started by external
-// means (such as the user starting it). The 'sandboxed' process is called the
-// target and it is started by the broker. There can be many target processes
-// started by a single broker process. This library provides facilities
-// for both the broker and the target.
-//
-// The design rationale and relevant documents can be found at http://go/sbox.
-//
-// Note: this header does not include the SandboxFactory definitions because
-// there are cases where the Sandbox library is linked against the main .exe
-// while its API needs to be used in a DLL.
-
-#ifndef SANDBOX_WIN_SRC_SANDBOX_H_
-#define SANDBOX_WIN_SRC_SANDBOX_H_
-
-#include <windows.h>
-
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-// sandbox: Google User-Land Application Sandbox
-namespace sandbox {
-
-class BrokerServices;
-class ProcessState;
-class TargetPolicy;
-class TargetServices;
-
-// BrokerServices exposes all the broker API.
-// The basic use is to start the target(s) and wait for them to end.
-//
-// This API is intended to be called in the following order
-// (error checking omitted):
-// BrokerServices* broker = SandboxFactory::GetBrokerServices();
-// broker->Init();
-// PROCESS_INFORMATION target;
-// broker->SpawnTarget(target_exe_path, target_args, &target);
-// ::ResumeThread(target->hThread);
-// // -- later you can call:
-// broker->WaitForAllTargets(option);
-//
-class BrokerServices {
- public:
- // Initializes the broker. Must be called before any other on this class.
- // returns ALL_OK if successful. All other return values imply failure.
- // If the return is ERROR_GENERIC, you can call ::GetLastError() to get
- // more information.
- virtual ResultCode Init() = 0;
-
- // Returns the interface pointer to a new, empty policy object. Use this
- // interface to specify the sandbox policy for new processes created by
- // SpawnTarget()
- virtual TargetPolicy* CreatePolicy() = 0;
-
- // Creates a new target (child process) in a suspended state.
- // Parameters:
- // exe_path: This is the full path to the target binary. This parameter
- // can be null and in this case the exe path must be the first argument
- // of the command_line.
- // command_line: The arguments to be passed as command line to the new
- // process. This can be null if the exe_path parameter is not null.
- // policy: This is the pointer to the policy object for the sandbox to
- // be created.
- // target: returns the resulting target process information such as process
- // handle and PID just as if CreateProcess() had been called. The caller is
- // responsible for closing the handles returned in this structure.
- // Returns:
- // ALL_OK if successful. All other return values imply failure.
- virtual ResultCode SpawnTarget(const wchar_t* exe_path,
- const wchar_t* command_line,
- TargetPolicy* policy,
- PROCESS_INFORMATION* target) = 0;
-
- // This call blocks (waits) for all the targets to terminate.
- // Returns:
- // ALL_OK if successful. All other return values imply failure.
- // If the return is ERROR_GENERIC, you can call ::GetLastError() to get
- // more information.
- virtual ResultCode WaitForAllTargets() = 0;
-
- // Adds an unsandboxed process as a peer for policy decisions (e.g.
- // HANDLES_DUP_ANY policy).
- // Returns:
- // ALL_OK if successful. All other return values imply failure.
- // If the return is ERROR_GENERIC, you can call ::GetLastError() to get
- // more information.
- virtual ResultCode AddTargetPeer(HANDLE peer_process) = 0;
-
- // Install the AppContainer with the specified sid an name. Returns ALL_OK if
- // successful or an error code if the AppContainer cannot be installed.
- virtual ResultCode InstallAppContainer(const wchar_t* sid,
- const wchar_t* name) = 0;
-
- // Removes from the system the AppContainer with the specified sid.
- // Returns ALL_OK if successful or an error code otherwise.
- virtual ResultCode UninstallAppContainer(const wchar_t* sid) = 0;
-};
-
-// TargetServices models the current process from the perspective
-// of a target process. To obtain a pointer to it use
-// Sandbox::GetTargetServices(). Note that this call returns a non-null
-// pointer only if this process is in fact a target. A process is a target
-// only if the process was spawned by a call to BrokerServices::SpawnTarget().
-//
-// This API allows the target to gain access to resources with a high
-// privilege token and then when it is ready to perform dangerous activities
-// (such as download content from the web) it can lower its token and
-// enter into locked-down (sandbox) mode.
-// The typical usage is as follows:
-//
-// TargetServices* target_services = Sandbox::GetTargetServices();
-// if (NULL != target_services) {
-// // We are the target.
-// target_services->Init();
-// // Do work that requires high privileges here.
-// // ....
-// // When ready to enter lock-down mode call LowerToken:
-// target_services->LowerToken();
-// }
-//
-// For more information see the BrokerServices API documentation.
-class TargetServices {
- public:
- // Initializes the target. Must call this function before any other.
- // returns ALL_OK if successful. All other return values imply failure.
- // If the return is ERROR_GENERIC, you can call ::GetLastError() to get
- // more information.
- virtual ResultCode Init() = 0;
-
- // Discards the impersonation token and uses the lower token, call before
- // processing any untrusted data or running third-party code. If this call
- // fails the current process could be terminated immediately.
- virtual void LowerToken() = 0;
-
- // Returns the ProcessState object. Through that object it's possible to have
- // information about the current state of the process, such as whether
- // LowerToken has been called or not.
- virtual ProcessState* GetState() = 0;
-
- // Requests the broker to duplicate the supplied handle into the target
- // process. The target process must be an active sandbox child process
- // and the source process must have a corresponding policy allowing
- // handle duplication for this object type.
- // Returns:
- // ALL_OK if successful. All other return values imply failure.
- // If the return is ERROR_GENERIC, you can call ::GetLastError() to get
- // more information.
- virtual ResultCode DuplicateHandle(HANDLE source_handle,
- DWORD target_process_id,
- HANDLE* target_handle,
- DWORD desired_access,
- DWORD options) = 0;
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_WIN_SRC_SANDBOX_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox.vcproj b/security/sandbox/chromium/sandbox/win/src/sandbox.vcproj
deleted file mode 100644
index f206e01a1..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox.vcproj
+++ /dev/null
@@ -1,658 +0,0 @@
-<?xml version="1.0" encoding="Windows-1252"?>
-<VisualStudioProject
- ProjectType="Visual C++"
- Version="8.00"
- Name="sandbox"
- ProjectGUID="{881F6A97-D539-4C48-B401-DF04385B2343}"
- RootNamespace="sandbox"
- Keyword="Win32Proj"
- >
- <Platforms>
- <Platform
- Name="Win32"
- />
- </Platforms>
- <ToolFiles>
- </ToolFiles>
- <Configurations>
- <Configuration
- Name="Debug|Win32"
- ConfigurationType="4"
- InheritedPropertySheets="$(SolutionDir)..\build\debug.vsprops;$(SolutionDir)..\build\common.vsprops;$(SolutionDir)..\testing\using_gtest.vsprops"
- >
- <Tool
- Name="VCPreBuildEventTool"
- />
- <Tool
- Name="VCCustomBuildTool"
- />
- <Tool
- Name="VCXMLDataGeneratorTool"
- />
- <Tool
- Name="VCWebServiceProxyGeneratorTool"
- />
- <Tool
- Name="VCMIDLTool"
- />
- <Tool
- Name="VCCLCompilerTool"
- UsePrecompiledHeader="2"
- ForcedIncludeFiles="stdafx.h"
- />
- <Tool
- Name="VCManagedResourceCompilerTool"
- />
- <Tool
- Name="VCResourceCompilerTool"
- />
- <Tool
- Name="VCPreLinkEventTool"
- />
- <Tool
- Name="VCLibrarianTool"
- />
- <Tool
- Name="VCALinkTool"
- />
- <Tool
- Name="VCXDCMakeTool"
- />
- <Tool
- Name="VCBscMakeTool"
- />
- <Tool
- Name="VCFxCopTool"
- />
- <Tool
- Name="VCPostBuildEventTool"
- Description="Copy wow_helper to output directory"
- CommandLine="copy $(ProjectDir)\..\wow_helper\wow_helper.exe $(OutDir) &amp;&amp; copy $(ProjectDir)\..\wow_helper\wow_helper.pdb $(OutDir)"
- />
- </Configuration>
- <Configuration
- Name="Release|Win32"
- ConfigurationType="4"
- InheritedPropertySheets="$(SolutionDir)..\build\release.vsprops;$(SolutionDir)..\build\common.vsprops;$(SolutionDir)..\testing\using_gtest.vsprops"
- >
- <Tool
- Name="VCPreBuildEventTool"
- />
- <Tool
- Name="VCCustomBuildTool"
- />
- <Tool
- Name="VCXMLDataGeneratorTool"
- />
- <Tool
- Name="VCWebServiceProxyGeneratorTool"
- />
- <Tool
- Name="VCMIDLTool"
- />
- <Tool
- Name="VCCLCompilerTool"
- UsePrecompiledHeader="0"
- />
- <Tool
- Name="VCManagedResourceCompilerTool"
- />
- <Tool
- Name="VCResourceCompilerTool"
- />
- <Tool
- Name="VCPreLinkEventTool"
- />
- <Tool
- Name="VCLibrarianTool"
- />
- <Tool
- Name="VCALinkTool"
- />
- <Tool
- Name="VCXDCMakeTool"
- />
- <Tool
- Name="VCBscMakeTool"
- />
- <Tool
- Name="VCFxCopTool"
- />
- <Tool
- Name="VCPostBuildEventTool"
- Description="Copy wow_helper to output directory"
- CommandLine="copy $(ProjectDir)\..\wow_helper\wow_helper.exe $(OutDir) &amp;&amp; copy $(ProjectDir)\..\wow_helper\wow_helper.pdb $(OutDir)"
- />
- </Configuration>
- </Configurations>
- <References>
- </References>
- <Files>
- <Filter
- Name="security"
- >
- <File
- RelativePath=".\acl.cc"
- >
- </File>
- <File
- RelativePath=".\acl.h"
- >
- </File>
- <File
- RelativePath=".\dep.cc"
- >
- </File>
- <File
- RelativePath=".\dep.h"
- >
- </File>
- <File
- RelativePath=".\job.cc"
- >
- </File>
- <File
- RelativePath=".\job.h"
- >
- </File>
- <File
- RelativePath=".\restricted_token.cc"
- >
- </File>
- <File
- RelativePath=".\restricted_token.h"
- >
- </File>
- <File
- RelativePath=".\restricted_token_utils.cc"
- >
- </File>
- <File
- RelativePath=".\restricted_token_utils.h"
- >
- </File>
- <File
- RelativePath=".\security_level.h"
- >
- </File>
- <File
- RelativePath=".\sid.cc"
- >
- </File>
- <File
- RelativePath=".\sid.h"
- >
- </File>
- <File
- RelativePath=".\window.cc"
- >
- </File>
- <File
- RelativePath=".\window.h"
- >
- </File>
- </Filter>
- <Filter
- Name="Interception"
- >
- <File
- RelativePath=".\eat_resolver.cc"
- >
- </File>
- <File
- RelativePath=".\eat_resolver.h"
- >
- </File>
- <File
- RelativePath=".\interception.cc"
- >
- </File>
- <File
- RelativePath=".\interception.h"
- >
- </File>
- <File
- RelativePath=".\interception_agent.cc"
- >
- </File>
- <File
- RelativePath=".\interception_agent.h"
- >
- </File>
- <File
- RelativePath=".\interception_internal.h"
- >
- </File>
- <File
- RelativePath=".\pe_image.cc"
- >
- </File>
- <File
- RelativePath=".\pe_image.h"
- >
- </File>
- <File
- RelativePath=".\resolver.cc"
- >
- </File>
- <File
- RelativePath=".\resolver.h"
- >
- </File>
- <File
- RelativePath=".\service_resolver.cc"
- >
- </File>
- <File
- RelativePath=".\service_resolver.h"
- >
- </File>
- <File
- RelativePath=".\sidestep_resolver.cc"
- >
- </File>
- <File
- RelativePath=".\sidestep_resolver.h"
- >
- </File>
- <File
- RelativePath=".\target_interceptions.cc"
- >
- </File>
- <File
- RelativePath=".\target_interceptions.h"
- >
- </File>
- <File
- RelativePath=".\Wow64.cc"
- >
- </File>
- <File
- RelativePath=".\Wow64.h"
- >
- </File>
- <Filter
- Name="sidestep"
- >
- <File
- RelativePath=".\sidestep\ia32_modrm_map.cpp"
- >
- </File>
- <File
- RelativePath=".\sidestep\ia32_opcode_map.cpp"
- >
- </File>
- <File
- RelativePath=".\sidestep\mini_disassembler.cpp"
- >
- </File>
- <File
- RelativePath=".\sidestep\mini_disassembler.h"
- >
- </File>
- <File
- RelativePath=".\sidestep\mini_disassembler_types.h"
- >
- </File>
- <File
- RelativePath=".\sidestep\preamble_patcher.h"
- >
- </File>
- <File
- RelativePath=".\sidestep\preamble_patcher_with_stub.cpp"
- >
- </File>
- </Filter>
- </Filter>
- <Filter
- Name="nt_level"
- >
- <File
- RelativePath=".\nt_internals.h"
- >
- </File>
- <File
- RelativePath=".\policy_target.cc"
- >
- </File>
- <File
- RelativePath=".\policy_target.h"
- >
- </File>
- <File
- RelativePath=".\sandbox_nt_types.h"
- >
- </File>
- <File
- RelativePath=".\sandbox_nt_util.cc"
- >
- </File>
- <File
- RelativePath=".\sandbox_nt_util.h"
- >
- </File>
- </Filter>
- <Filter
- Name="Policy_handlers"
- >
- <File
- RelativePath=".\filesystem_dispatcher.cc"
- >
- </File>
- <File
- RelativePath=".\filesystem_dispatcher.h"
- >
- </File>
- <File
- RelativePath=".\filesystem_interception.cc"
- >
- </File>
- <File
- RelativePath=".\filesystem_interception.h"
- >
- </File>
- <File
- RelativePath=".\filesystem_policy.cc"
- >
- </File>
- <File
- RelativePath=".\filesystem_policy.h"
- >
- </File>
- <File
- RelativePath=".\named_pipe_dispatcher.cc"
- >
- </File>
- <File
- RelativePath=".\named_pipe_dispatcher.h"
- >
- </File>
- <File
- RelativePath=".\named_pipe_interception.cc"
- >
- </File>
- <File
- RelativePath=".\named_pipe_interception.h"
- >
- </File>
- <File
- RelativePath=".\named_pipe_policy.cc"
- >
- </File>
- <File
- RelativePath=".\named_pipe_policy.h"
- >
- </File>
- <File
- RelativePath=".\policy_params.h"
- >
- </File>
- <File
- RelativePath=".\process_thread_dispatcher.cc"
- >
- </File>
- <File
- RelativePath=".\process_thread_dispatcher.h"
- >
- </File>
- <File
- RelativePath=".\process_thread_interception.cc"
- >
- </File>
- <File
- RelativePath=".\process_thread_interception.h"
- >
- </File>
- <File
- RelativePath=".\process_thread_policy.cc"
- >
- </File>
- <File
- RelativePath=".\process_thread_policy.h"
- >
- </File>
- <File
- RelativePath=".\registry_dispatcher.cc"
- >
- </File>
- <File
- RelativePath=".\registry_dispatcher.h"
- >
- </File>
- <File
- RelativePath=".\registry_interception.cc"
- >
- </File>
- <File
- RelativePath=".\registry_interception.h"
- >
- </File>
- <File
- RelativePath=".\registry_policy.cc"
- >
- </File>
- <File
- RelativePath=".\registry_policy.h"
- >
- </File>
- <File
- RelativePath=".\sync_dispatcher.cc"
- >
- </File>
- <File
- RelativePath=".\sync_dispatcher.h"
- >
- </File>
- <File
- RelativePath=".\sync_interception.cc"
- >
- </File>
- <File
- RelativePath=".\sync_interception.h"
- >
- </File>
- <File
- RelativePath=".\sync_policy.cc"
- >
- </File>
- <File
- RelativePath=".\sync_policy.h"
- >
- </File>
- </Filter>
- <Filter
- Name="IPC"
- >
- <File
- RelativePath=".\crosscall_client.h"
- >
- </File>
- <File
- RelativePath=".\crosscall_params.h"
- >
- </File>
- <File
- RelativePath=".\crosscall_server.cc"
- >
- </File>
- <File
- RelativePath=".\crosscall_server.h"
- >
- </File>
- <File
- RelativePath=".\ipc_tags.h"
- >
- </File>
- <File
- RelativePath=".\sharedmem_ipc_client.cc"
- >
- </File>
- <File
- RelativePath=".\sharedmem_ipc_client.h"
- >
- </File>
- <File
- RelativePath=".\sharedmem_ipc_server.cc"
- >
- </File>
- <File
- RelativePath=".\sharedmem_ipc_server.h"
- >
- </File>
- </Filter>
- <Filter
- Name="Policy_base"
- >
- <File
- RelativePath=".\policy_engine_opcodes.cc"
- >
- </File>
- <File
- RelativePath=".\policy_engine_opcodes.h"
- >
- </File>
- <File
- RelativePath=".\policy_engine_params.h"
- >
- </File>
- <File
- RelativePath=".\policy_engine_processor.cc"
- >
- </File>
- <File
- RelativePath=".\policy_engine_processor.h"
- >
- </File>
- <File
- RelativePath=".\policy_low_level.cc"
- >
- </File>
- <File
- RelativePath=".\policy_low_level.h"
- >
- </File>
- <File
- RelativePath=".\sandbox_policy_base.cc"
- >
- </File>
- <File
- RelativePath=".\sandbox_policy_base.h"
- >
- </File>
- </Filter>
- <File
- RelativePath=".\broker_services.cc"
- >
- </File>
- <File
- RelativePath=".\broker_services.h"
- >
- </File>
- <File
- RelativePath=".\internal_types.h"
- >
- </File>
- <File
- RelativePath=".\policy_broker.cc"
- >
- </File>
- <File
- RelativePath=".\policy_broker.h"
- >
- </File>
- <File
- RelativePath=".\sandbox.cc"
- >
- </File>
- <File
- RelativePath=".\sandbox.h"
- >
- </File>
- <File
- RelativePath=".\sandbox_factory.h"
- >
- </File>
- <File
- RelativePath=".\sandbox_policy.h"
- >
- </File>
- <File
- RelativePath=".\sandbox_types.h"
- >
- </File>
- <File
- RelativePath=".\sandbox_utils.cc"
- >
- </File>
- <File
- RelativePath=".\sandbox_utils.h"
- >
- </File>
- <File
- RelativePath=".\shared_handles.cc"
- >
- </File>
- <File
- RelativePath=".\shared_handles.h"
- >
- </File>
- <File
- RelativePath=".\stdafx.cc"
- >
- <FileConfiguration
- Name="Debug|Win32"
- >
- <Tool
- Name="VCCLCompilerTool"
- UsePrecompiledHeader="1"
- />
- </FileConfiguration>
- <FileConfiguration
- Name="Release|Win32"
- >
- <Tool
- Name="VCCLCompilerTool"
- UsePrecompiledHeader="0"
- />
- </FileConfiguration>
- </File>
- <File
- RelativePath=".\stdafx.h"
- >
- </File>
- <File
- RelativePath=".\target_process.cc"
- >
- </File>
- <File
- RelativePath=".\target_process.h"
- >
- </File>
- <File
- RelativePath=".\target_services.cc"
- >
- </File>
- <File
- RelativePath=".\target_services.h"
- >
- </File>
- <File
- RelativePath=".\win2k_threadpool.cc"
- >
- </File>
- <File
- RelativePath=".\win2k_threadpool.h"
- >
- </File>
- <File
- RelativePath=".\win_utils.cc"
- >
- </File>
- <File
- RelativePath=".\win_utils.h"
- >
- </File>
- </Files>
- <Globals>
- </Globals>
-</VisualStudioProject>
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_factory.h b/security/sandbox/chromium/sandbox/win/src/sandbox_factory.h
deleted file mode 100644
index f5888ffcd..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_factory.h
+++ /dev/null
@@ -1,51 +0,0 @@
-// 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 SANDBOX_SRC_SANDBOX_FACTORY_H__
-#define SANDBOX_SRC_SANDBOX_FACTORY_H__
-
-#include "base/macros.h"
-#include "sandbox/win/src/sandbox.h"
-
-// SandboxFactory is a set of static methods to get access to the broker
-// or target services object. Only one of the two methods (GetBrokerServices,
-// GetTargetServices) will return a non-null pointer and that should be used
-// as the indication that the process is the broker or the target:
-//
-// BrokerServices* broker_services = SandboxFactory::GetBrokerServices();
-// if (NULL != broker_services) {
-// //we are the broker, call broker api here
-// broker_services->Init();
-// } else {
-// TargetServices* target_services = SandboxFactory::GetTargetServices();
-// if (NULL != target_services) {
-// //we are the target, call target api here
-// target_services->Init();
-// }
-//
-// The methods in this class are expected to be called from a single thread
-//
-// The Sandbox library needs to be linked against the main executable, but
-// sometimes the API calls are issued from a DLL that loads into the exe
-// process. These factory methods then need to be called from the main
-// exe and the interface pointers then can be safely passed to the DLL where
-// the Sandbox API calls are made.
-namespace sandbox {
-
-class SandboxFactory {
- public:
- // Returns the Broker API interface, returns NULL if this process is the
- // target.
- static BrokerServices* GetBrokerServices();
-
- // Returns the Target API interface, returns NULL if this process is the
- // broker.
- static TargetServices* GetTargetServices();
- private:
- DISALLOW_IMPLICIT_CONSTRUCTORS(SandboxFactory);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SANDBOX_FACTORY_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_globals.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_globals.cc
deleted file mode 100644
index b4ab52392..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_globals.cc
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2013 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 <windows.h>
-
-#include "sandbox/win/src/sandbox_nt_types.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace sandbox {
-
-// The section for IPC and policy.
-SANDBOX_INTERCEPT HANDLE g_shared_section = NULL;
-
-// This is the list of all imported symbols from ntdll.dll.
-SANDBOX_INTERCEPT NtExports g_nt = {};
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_types.h b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_types.h
deleted file mode 100644
index a4a88bba7..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_types.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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 SANDBOX_SRC_SANDBOX_NT_TYPES_H__
-#define SANDBOX_SRC_SANDBOX_NT_TYPES_H__
-
-#include "sandbox/win/src/nt_internals.h"
-
-namespace sandbox {
-
-struct NtExports {
- NtAllocateVirtualMemoryFunction AllocateVirtualMemory;
- NtCloseFunction Close;
- NtDuplicateObjectFunction DuplicateObject;
- NtFreeVirtualMemoryFunction FreeVirtualMemory;
- NtMapViewOfSectionFunction MapViewOfSection;
- NtProtectVirtualMemoryFunction ProtectVirtualMemory;
- NtQueryInformationProcessFunction QueryInformationProcess;
- NtQueryObjectFunction QueryObject;
- NtQuerySectionFunction QuerySection;
- NtQueryVirtualMemoryFunction QueryVirtualMemory;
- NtUnmapViewOfSectionFunction UnmapViewOfSection;
- RtlAllocateHeapFunction RtlAllocateHeap;
- RtlAnsiStringToUnicodeStringFunction RtlAnsiStringToUnicodeString;
- RtlCompareUnicodeStringFunction RtlCompareUnicodeString;
- RtlCreateHeapFunction RtlCreateHeap;
- RtlCreateUserThreadFunction RtlCreateUserThread;
- RtlDestroyHeapFunction RtlDestroyHeap;
- RtlFreeHeapFunction RtlFreeHeap;
- _strnicmpFunction _strnicmp;
- strlenFunction strlen;
- wcslenFunction wcslen;
- memcpyFunction memcpy;
-};
-
-// This is the value used for the ntdll level allocator.
-enum AllocationType {
- NT_ALLOC,
- NT_PAGE
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_SANDBOX_NT_TYPES_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.cc
deleted file mode 100644
index 62f2422ca..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.cc
+++ /dev/null
@@ -1,676 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <string>
-
-#include "base/win/pe_image.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/target_services.h"
-
-namespace sandbox {
-
-// This is the list of all imported symbols from ntdll.dll.
-SANDBOX_INTERCEPT NtExports g_nt;
-
-} // namespace sandbox
-
-namespace {
-
-#if defined(_WIN64)
-void* AllocateNearTo(void* source, size_t size) {
- using sandbox::g_nt;
-
- // Start with 1 GB above the source.
- const size_t kOneGB = 0x40000000;
- void* base = reinterpret_cast<char*>(source) + kOneGB;
- SIZE_T actual_size = size;
- ULONG_PTR zero_bits = 0; // Not the correct type if used.
- ULONG type = MEM_RESERVE;
-
- NTSTATUS ret;
- int attempts = 0;
- for (; attempts < 41; attempts++) {
- ret = g_nt.AllocateVirtualMemory(NtCurrentProcess, &base, zero_bits,
- &actual_size, type, PAGE_READWRITE);
- if (NT_SUCCESS(ret)) {
- if (base < source ||
- base >= reinterpret_cast<char*>(source) + 4 * kOneGB) {
- // We won't be able to patch this dll.
- VERIFY_SUCCESS(g_nt.FreeVirtualMemory(NtCurrentProcess, &base, &size,
- MEM_RELEASE));
- return NULL;
- }
- break;
- }
-
- if (attempts == 30) {
- // Try the first GB.
- base = reinterpret_cast<char*>(source);
- } else if (attempts == 40) {
- // Try the highest available address.
- base = NULL;
- type |= MEM_TOP_DOWN;
- }
-
- // Try 100 MB higher.
- base = reinterpret_cast<char*>(base) + 100 * 0x100000;
- }
-
- if (attempts == 41)
- return NULL;
-
- ret = g_nt.AllocateVirtualMemory(NtCurrentProcess, &base, zero_bits,
- &actual_size, MEM_COMMIT, PAGE_READWRITE);
-
- if (!NT_SUCCESS(ret)) {
- VERIFY_SUCCESS(g_nt.FreeVirtualMemory(NtCurrentProcess, &base, &size,
- MEM_RELEASE));
- base = NULL;
- }
-
- return base;
-}
-#else // defined(_WIN64).
-void* AllocateNearTo(void* source, size_t size) {
- using sandbox::g_nt;
-
- // In 32-bit processes allocations below 512k are predictable, so mark
- // anything in that range as reserved and retry until we get a good address.
- const void* const kMinAddress = reinterpret_cast<void*>(512 * 1024);
- NTSTATUS ret;
- SIZE_T actual_size;
- void* base;
- do {
- base = NULL;
- actual_size = 64 * 1024;
- ret = g_nt.AllocateVirtualMemory(NtCurrentProcess, &base, 0, &actual_size,
- MEM_RESERVE, PAGE_NOACCESS);
- if (!NT_SUCCESS(ret))
- return NULL;
- } while (base < kMinAddress);
-
- actual_size = size;
- ret = g_nt.AllocateVirtualMemory(NtCurrentProcess, &base, 0, &actual_size,
- MEM_COMMIT, PAGE_READWRITE);
- if (!NT_SUCCESS(ret))
- return NULL;
- return base;
-}
-#endif // defined(_WIN64).
-
-} // namespace.
-
-namespace sandbox {
-
-// Handle for our private heap.
-void* g_heap = NULL;
-
-SANDBOX_INTERCEPT HANDLE g_shared_section;
-SANDBOX_INTERCEPT size_t g_shared_IPC_size = 0;
-SANDBOX_INTERCEPT size_t g_shared_policy_size = 0;
-
-void* volatile g_shared_policy_memory = NULL;
-void* volatile g_shared_IPC_memory = NULL;
-
-// Both the IPC and the policy share a single region of memory in which the IPC
-// memory is first and the policy memory is last.
-bool MapGlobalMemory() {
- if (NULL == g_shared_IPC_memory) {
- void* memory = NULL;
- SIZE_T size = 0;
- // Map the entire shared section from the start.
- NTSTATUS ret = g_nt.MapViewOfSection(g_shared_section, NtCurrentProcess,
- &memory, 0, 0, NULL, &size, ViewUnmap,
- 0, PAGE_READWRITE);
-
- if (!NT_SUCCESS(ret) || NULL == memory) {
- NOTREACHED_NT();
- return false;
- }
-
- if (NULL != _InterlockedCompareExchangePointer(&g_shared_IPC_memory,
- memory, NULL)) {
- // Somebody beat us to the memory setup.
- VERIFY_SUCCESS(g_nt.UnmapViewOfSection(NtCurrentProcess, memory));
- }
- DCHECK_NT(g_shared_IPC_size > 0);
- g_shared_policy_memory = reinterpret_cast<char*>(g_shared_IPC_memory)
- + g_shared_IPC_size;
- }
- DCHECK_NT(g_shared_policy_memory);
- DCHECK_NT(g_shared_policy_size > 0);
- return true;
-}
-
-void* GetGlobalIPCMemory() {
- if (!MapGlobalMemory())
- return NULL;
- return g_shared_IPC_memory;
-}
-
-void* GetGlobalPolicyMemory() {
- if (!MapGlobalMemory())
- return NULL;
- return g_shared_policy_memory;
-}
-
-bool InitHeap() {
- if (!g_heap) {
- // Create a new heap using default values for everything.
- void* heap = g_nt.RtlCreateHeap(HEAP_GROWABLE, NULL, 0, 0, NULL, NULL);
- if (!heap)
- return false;
-
- if (NULL != _InterlockedCompareExchangePointer(&g_heap, heap, NULL)) {
- // Somebody beat us to the memory setup.
- g_nt.RtlDestroyHeap(heap);
- }
- }
- return (g_heap != NULL);
-}
-
-// Physically reads or writes from memory to verify that (at this time), it is
-// valid. Returns a dummy value.
-int TouchMemory(void* buffer, size_t size_bytes, RequiredAccess intent) {
- const int kPageSize = 4096;
- int dummy = 0;
- char* start = reinterpret_cast<char*>(buffer);
- char* end = start + size_bytes - 1;
-
- if (WRITE == intent) {
- for (; start < end; start += kPageSize) {
- *start = 0;
- }
- *end = 0;
- } else {
- for (; start < end; start += kPageSize) {
- dummy += *start;
- }
- dummy += *end;
- }
-
- return dummy;
-}
-
-bool ValidParameter(void* buffer, size_t size, RequiredAccess intent) {
- DCHECK_NT(size);
- __try {
- TouchMemory(buffer, size, intent);
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- return false;
- }
- return true;
-}
-
-NTSTATUS CopyData(void* destination, const void* source, size_t bytes) {
- NTSTATUS ret = STATUS_SUCCESS;
- __try {
- g_nt.memcpy(destination, source, bytes);
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- ret = GetExceptionCode();
- }
- return ret;
-}
-
-NTSTATUS AllocAndGetFullPath(HANDLE root,
- wchar_t* path,
- wchar_t** full_path) {
- if (!InitHeap())
- return STATUS_NO_MEMORY;
-
- DCHECK_NT(full_path);
- DCHECK_NT(path);
- *full_path = NULL;
- OBJECT_NAME_INFORMATION* handle_name = NULL;
- NTSTATUS ret = STATUS_UNSUCCESSFUL;
- __try {
- do {
- static NtQueryObjectFunction NtQueryObject = NULL;
- if (!NtQueryObject)
- ResolveNTFunctionPtr("NtQueryObject", &NtQueryObject);
-
- ULONG size = 0;
- // Query the name information a first time to get the size of the name.
- ret = NtQueryObject(root, ObjectNameInformation, NULL, 0, &size);
-
- if (size) {
- handle_name = reinterpret_cast<OBJECT_NAME_INFORMATION*>(
- new(NT_ALLOC) BYTE[size]);
-
- // Query the name information a second time to get the name of the
- // object referenced by the handle.
- ret = NtQueryObject(root, ObjectNameInformation, handle_name, size,
- &size);
- }
-
- if (STATUS_SUCCESS != ret)
- break;
-
- // Space for path + '\' + name + '\0'.
- size_t name_length = handle_name->ObjectName.Length +
- (wcslen(path) + 2) * sizeof(wchar_t);
- *full_path = new(NT_ALLOC) wchar_t[name_length/sizeof(wchar_t)];
- if (NULL == *full_path)
- break;
- wchar_t* off = *full_path;
- ret = CopyData(off, handle_name->ObjectName.Buffer,
- handle_name->ObjectName.Length);
- if (!NT_SUCCESS(ret))
- break;
- off += handle_name->ObjectName.Length / sizeof(wchar_t);
- *off = L'\\';
- off += 1;
- ret = CopyData(off, path, wcslen(path) * sizeof(wchar_t));
- if (!NT_SUCCESS(ret))
- break;
- off += wcslen(path);
- *off = L'\0';
- } while (false);
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- ret = GetExceptionCode();
- }
-
- if (!NT_SUCCESS(ret)) {
- if (*full_path) {
- operator delete(*full_path, NT_ALLOC);
- *full_path = NULL;
- }
- if (handle_name) {
- operator delete(handle_name, NT_ALLOC);
- handle_name = NULL;
- }
- }
-
- return ret;
-}
-
-// Hacky code... replace with AllocAndCopyObjectAttributes.
-NTSTATUS AllocAndCopyName(const OBJECT_ATTRIBUTES* in_object,
- wchar_t** out_name,
- uint32_t* attributes,
- HANDLE* root) {
- if (!InitHeap())
- return STATUS_NO_MEMORY;
-
- DCHECK_NT(out_name);
- *out_name = NULL;
- NTSTATUS ret = STATUS_UNSUCCESSFUL;
- __try {
- do {
- if (in_object->RootDirectory != static_cast<HANDLE>(0) && !root)
- break;
- if (NULL == in_object->ObjectName)
- break;
- if (NULL == in_object->ObjectName->Buffer)
- break;
-
- size_t size = in_object->ObjectName->Length + sizeof(wchar_t);
- *out_name = new(NT_ALLOC) wchar_t[size/sizeof(wchar_t)];
- if (NULL == *out_name)
- break;
-
- ret = CopyData(*out_name, in_object->ObjectName->Buffer,
- size - sizeof(wchar_t));
- if (!NT_SUCCESS(ret))
- break;
-
- (*out_name)[size / sizeof(wchar_t) - 1] = L'\0';
-
- if (attributes)
- *attributes = in_object->Attributes;
-
- if (root)
- *root = in_object->RootDirectory;
- ret = STATUS_SUCCESS;
- } while (false);
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- ret = GetExceptionCode();
- }
-
- if (!NT_SUCCESS(ret) && *out_name) {
- operator delete(*out_name, NT_ALLOC);
- *out_name = NULL;
- }
-
- return ret;
-}
-
-NTSTATUS GetProcessId(HANDLE process, DWORD *process_id) {
- PROCESS_BASIC_INFORMATION proc_info;
- ULONG bytes_returned;
-
- NTSTATUS ret = g_nt.QueryInformationProcess(process, ProcessBasicInformation,
- &proc_info, sizeof(proc_info),
- &bytes_returned);
- if (!NT_SUCCESS(ret) || sizeof(proc_info) != bytes_returned)
- return ret;
-
- *process_id = proc_info.UniqueProcessId;
- return STATUS_SUCCESS;
-}
-
-bool IsSameProcess(HANDLE process) {
- if (NtCurrentProcess == process)
- return true;
-
- static DWORD s_process_id = 0;
-
- if (!s_process_id) {
- NTSTATUS ret = GetProcessId(NtCurrentProcess, &s_process_id);
- if (!NT_SUCCESS(ret))
- return false;
- }
-
- DWORD process_id;
- NTSTATUS ret = GetProcessId(process, &process_id);
- if (!NT_SUCCESS(ret))
- return false;
-
- return (process_id == s_process_id);
-}
-
-bool IsValidImageSection(HANDLE section, PVOID *base, PLARGE_INTEGER offset,
- PSIZE_T view_size) {
- if (!section || !base || !view_size || offset)
- return false;
-
- HANDLE query_section;
-
- NTSTATUS ret = g_nt.DuplicateObject(NtCurrentProcess, section,
- NtCurrentProcess, &query_section,
- SECTION_QUERY, 0, 0);
- if (!NT_SUCCESS(ret))
- return false;
-
- SECTION_BASIC_INFORMATION basic_info;
- SIZE_T bytes_returned;
- ret = g_nt.QuerySection(query_section, SectionBasicInformation, &basic_info,
- sizeof(basic_info), &bytes_returned);
-
- VERIFY_SUCCESS(g_nt.Close(query_section));
-
- if (!NT_SUCCESS(ret) || sizeof(basic_info) != bytes_returned)
- return false;
-
- if (!(basic_info.Attributes & SEC_IMAGE))
- return false;
-
- return true;
-}
-
-UNICODE_STRING* AnsiToUnicode(const char* string) {
- ANSI_STRING ansi_string;
- ansi_string.Length = static_cast<USHORT>(g_nt.strlen(string));
- ansi_string.MaximumLength = ansi_string.Length + 1;
- ansi_string.Buffer = const_cast<char*>(string);
-
- if (ansi_string.Length > ansi_string.MaximumLength)
- return NULL;
-
- size_t name_bytes = ansi_string.MaximumLength * sizeof(wchar_t) +
- sizeof(UNICODE_STRING);
-
- UNICODE_STRING* out_string = reinterpret_cast<UNICODE_STRING*>(
- new(NT_ALLOC) char[name_bytes]);
- if (!out_string)
- return NULL;
-
- out_string->MaximumLength = ansi_string.MaximumLength * sizeof(wchar_t);
- out_string->Buffer = reinterpret_cast<wchar_t*>(&out_string[1]);
-
- BOOLEAN alloc_destination = FALSE;
- NTSTATUS ret = g_nt.RtlAnsiStringToUnicodeString(out_string, &ansi_string,
- alloc_destination);
- DCHECK_NT(STATUS_BUFFER_OVERFLOW != ret);
- if (!NT_SUCCESS(ret)) {
- operator delete(out_string, NT_ALLOC);
- return NULL;
- }
-
- return out_string;
-}
-
-UNICODE_STRING* GetImageInfoFromModule(HMODULE module, uint32_t* flags) {
- // PEImage's dtor won't be run during SEH unwinding, but that's OK.
-#pragma warning(push)
-#pragma warning(disable: 4509)
- UNICODE_STRING* out_name = NULL;
- __try {
- do {
- *flags = 0;
- base::win::PEImage pe(module);
-
- if (!pe.VerifyMagic())
- break;
- *flags |= MODULE_IS_PE_IMAGE;
-
- PIMAGE_EXPORT_DIRECTORY exports = pe.GetExportDirectory();
- if (exports) {
- char* name = reinterpret_cast<char*>(pe.RVAToAddr(exports->Name));
- out_name = AnsiToUnicode(name);
- }
-
- PIMAGE_NT_HEADERS headers = pe.GetNTHeaders();
- if (headers) {
- if (headers->OptionalHeader.AddressOfEntryPoint)
- *flags |= MODULE_HAS_ENTRY_POINT;
- if (headers->OptionalHeader.SizeOfCode)
- *flags |= MODULE_HAS_CODE;
- }
- } while (false);
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- }
-
- return out_name;
-#pragma warning(pop)
-}
-
-UNICODE_STRING* GetBackingFilePath(PVOID address) {
- // We'll start with something close to max_path charactes for the name.
- SIZE_T buffer_bytes = MAX_PATH * 2;
-
- for (;;) {
- MEMORY_SECTION_NAME* section_name = reinterpret_cast<MEMORY_SECTION_NAME*>(
- new(NT_ALLOC) char[buffer_bytes]);
-
- if (!section_name)
- return NULL;
-
- SIZE_T returned_bytes;
- NTSTATUS ret = g_nt.QueryVirtualMemory(NtCurrentProcess, address,
- MemorySectionName, section_name,
- buffer_bytes, &returned_bytes);
-
- if (STATUS_BUFFER_OVERFLOW == ret) {
- // Retry the call with the given buffer size.
- operator delete(section_name, NT_ALLOC);
- section_name = NULL;
- buffer_bytes = returned_bytes;
- continue;
- }
- if (!NT_SUCCESS(ret)) {
- operator delete(section_name, NT_ALLOC);
- return NULL;
- }
-
- return reinterpret_cast<UNICODE_STRING*>(section_name);
- }
-}
-
-UNICODE_STRING* ExtractModuleName(const UNICODE_STRING* module_path) {
- if ((!module_path) || (!module_path->Buffer))
- return NULL;
-
- wchar_t* sep = NULL;
- int start_pos = module_path->Length / sizeof(wchar_t) - 1;
- int ix = start_pos;
-
- for (; ix >= 0; --ix) {
- if (module_path->Buffer[ix] == L'\\') {
- sep = &module_path->Buffer[ix];
- break;
- }
- }
-
- // Ends with path separator. Not a valid module name.
- if ((ix == start_pos) && sep)
- return NULL;
-
- // No path separator found. Use the entire name.
- if (!sep) {
- sep = &module_path->Buffer[-1];
- }
-
- // Add one to the size so we can null terminate the string.
- size_t size_bytes = (start_pos - ix + 1) * sizeof(wchar_t);
-
- // Based on the code above, size_bytes should always be small enough
- // to make the static_cast below safe.
- DCHECK_NT(UINT16_MAX > size_bytes);
- char* str_buffer = new(NT_ALLOC) char[size_bytes + sizeof(UNICODE_STRING)];
- if (!str_buffer)
- return NULL;
-
- UNICODE_STRING* out_string = reinterpret_cast<UNICODE_STRING*>(str_buffer);
- out_string->Buffer = reinterpret_cast<wchar_t*>(&out_string[1]);
- out_string->Length = static_cast<USHORT>(size_bytes - sizeof(wchar_t));
- out_string->MaximumLength = static_cast<USHORT>(size_bytes);
-
- NTSTATUS ret = CopyData(out_string->Buffer, &sep[1], out_string->Length);
- if (!NT_SUCCESS(ret)) {
- operator delete(out_string, NT_ALLOC);
- return NULL;
- }
-
- out_string->Buffer[out_string->Length / sizeof(wchar_t)] = L'\0';
- return out_string;
-}
-
-NTSTATUS AutoProtectMemory::ChangeProtection(void* address, size_t bytes,
- ULONG protect) {
- DCHECK_NT(!changed_);
- SIZE_T new_bytes = bytes;
- NTSTATUS ret = g_nt.ProtectVirtualMemory(NtCurrentProcess, &address,
- &new_bytes, protect, &old_protect_);
- if (NT_SUCCESS(ret)) {
- changed_ = true;
- address_ = address;
- bytes_ = new_bytes;
- }
-
- return ret;
-}
-
-NTSTATUS AutoProtectMemory::RevertProtection() {
- if (!changed_)
- return STATUS_SUCCESS;
-
- DCHECK_NT(address_);
- DCHECK_NT(bytes_);
-
- SIZE_T new_bytes = bytes_;
- NTSTATUS ret = g_nt.ProtectVirtualMemory(NtCurrentProcess, &address_,
- &new_bytes, old_protect_,
- &old_protect_);
- DCHECK_NT(NT_SUCCESS(ret));
-
- changed_ = false;
- address_ = NULL;
- bytes_ = 0;
- old_protect_ = 0;
-
- return ret;
-}
-
-bool IsSupportedRenameCall(FILE_RENAME_INFORMATION* file_info,
- DWORD length,
- uint32_t file_info_class) {
- if (FileRenameInformation != file_info_class)
- return false;
-
- if (length < sizeof(FILE_RENAME_INFORMATION))
- return false;
-
- // Make sure file name length doesn't exceed the message length
- if (length - offsetof(FILE_RENAME_INFORMATION, FileName) <
- file_info->FileNameLength)
- return false;
-
- // We don't support a root directory.
- if (file_info->RootDirectory)
- return false;
-
- static const wchar_t kPathPrefix[] = { L'\\', L'?', L'?', L'\\'};
-
- // Check if it starts with \\??\\. We don't support relative paths.
- if (file_info->FileNameLength < sizeof(kPathPrefix) ||
- file_info->FileNameLength > UINT16_MAX)
- return false;
-
- if (file_info->FileName[0] != kPathPrefix[0] ||
- file_info->FileName[1] != kPathPrefix[1] ||
- file_info->FileName[2] != kPathPrefix[2] ||
- file_info->FileName[3] != kPathPrefix[3])
- return false;
-
- return true;
-}
-
-} // namespace sandbox
-
-void* operator new(size_t size, sandbox::AllocationType type,
- void* near_to) {
- void* result = NULL;
- if (type == sandbox::NT_ALLOC) {
- if (sandbox::InitHeap()) {
- // Use default flags for the allocation.
- result = sandbox::g_nt.RtlAllocateHeap(sandbox::g_heap, 0, size);
- }
- } else if (type == sandbox::NT_PAGE) {
- result = AllocateNearTo(near_to, size);
- } else {
- NOTREACHED_NT();
- }
-
- // TODO: Returning NULL from operator new has undefined behavior, but
- // the Allocate() functions called above can return NULL. Consider checking
- // for NULL here and crashing or throwing.
-
- return result;
-}
-
-void operator delete(void* memory, sandbox::AllocationType type) {
- if (type == sandbox::NT_ALLOC) {
- // Use default flags.
- VERIFY(sandbox::g_nt.RtlFreeHeap(sandbox::g_heap, 0, memory));
- } else if (type == sandbox::NT_PAGE) {
- void* base = memory;
- SIZE_T size = 0;
- VERIFY_SUCCESS(sandbox::g_nt.FreeVirtualMemory(NtCurrentProcess, &base,
- &size, MEM_RELEASE));
- } else {
- NOTREACHED_NT();
- }
-}
-
-void operator delete(void* memory,
- sandbox::AllocationType type,
- void* near_to) {
- operator delete(memory, type);
-}
-
-void* __cdecl operator new(size_t size,
- void* buffer,
- sandbox::AllocationType type) {
- return buffer;
-}
-
-void __cdecl operator delete(void* memory,
- void* buffer,
- sandbox::AllocationType type) {}
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h
deleted file mode 100644
index 3e0238206..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h
+++ /dev/null
@@ -1,196 +0,0 @@
-// 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 SANDBOX_SRC_SANDBOX_NT_UTIL_H_
-#define SANDBOX_SRC_SANDBOX_NT_UTIL_H_
-
-#include <intrin.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_nt_types.h"
-
-// Placement new and delete to be used from ntdll interception code.
-void* __cdecl operator new(size_t size, sandbox::AllocationType type,
- void* near_to = NULL);
-void __cdecl operator delete(void* memory, sandbox::AllocationType type);
-// Add operator delete that matches the placement form of the operator new
-// above. This is required by compiler to generate code to call operator delete
-// in case the object's constructor throws an exception.
-// See http://msdn.microsoft.com/en-us/library/cxdxz3x6.aspx
-void __cdecl operator delete(void* memory, sandbox::AllocationType type,
- void* near_to);
-
-// Regular placement new and delete
-void* __cdecl operator new(size_t size, void* buffer,
- sandbox::AllocationType type);
-void __cdecl operator delete(void* memory, void* buffer,
- sandbox::AllocationType type);
-
-// DCHECK_NT is defined to be pretty much an assert at this time because we
-// don't have logging from the ntdll layer on the child.
-//
-// VERIFY_NT and VERIFY_SUCCESS are the standard asserts on debug, but
-// execute the actual argument on release builds. VERIFY_NT expects an action
-// returning a bool, while VERIFY_SUCCESS expects an action returning
-// NTSTATUS.
-#ifndef NDEBUG
-#define DCHECK_NT(condition) { (condition) ? (void)0 : __debugbreak(); }
-#define VERIFY(action) DCHECK_NT(action)
-#define VERIFY_SUCCESS(action) DCHECK_NT(NT_SUCCESS(action))
-#else
-#define DCHECK_NT(condition)
-#define VERIFY(action) (action)
-#define VERIFY_SUCCESS(action) (action)
-#endif
-
-#define CHECK_NT(condition) { (condition) ? (void)0 : __debugbreak(); }
-
-#define NOTREACHED_NT() DCHECK_NT(false)
-
-namespace sandbox {
-
-#if defined(_M_X64)
-#pragma intrinsic(_InterlockedCompareExchange)
-#pragma intrinsic(_InterlockedCompareExchangePointer)
-
-#elif defined(_M_IX86)
-extern "C" long _InterlockedCompareExchange(long volatile* destination,
- long exchange, long comperand);
-
-#pragma intrinsic(_InterlockedCompareExchange)
-
-// We want to make sure that we use an intrinsic version of the function, not
-// the one provided by kernel32.
-__forceinline void* _InterlockedCompareExchangePointer(
- void* volatile* destination, void* exchange, void* comperand) {
- size_t ret = _InterlockedCompareExchange(
- reinterpret_cast<long volatile*>(destination),
- static_cast<long>(reinterpret_cast<size_t>(exchange)),
- static_cast<long>(reinterpret_cast<size_t>(comperand)));
-
- return reinterpret_cast<void*>(static_cast<size_t>(ret));
-}
-
-#else
-#error Architecture not supported.
-
-#endif
-
-// Returns a pointer to the IPC shared memory.
-void* GetGlobalIPCMemory();
-
-// Returns a pointer to the Policy shared memory.
-void* GetGlobalPolicyMemory();
-
-enum RequiredAccess {
- READ,
- WRITE
-};
-
-// Performs basic user mode buffer validation. In any case, buffers access must
-// be protected by SEH. intent specifies if the buffer should be tested for read
-// or write.
-// Note that write intent implies destruction of the buffer content (we actually
-// write)
-bool ValidParameter(void* buffer, size_t size, RequiredAccess intent);
-
-// Copies data from a user buffer to our buffer. Returns the operation status.
-NTSTATUS CopyData(void* destination, const void* source, size_t bytes);
-
-// Copies the name from an object attributes.
-NTSTATUS AllocAndCopyName(const OBJECT_ATTRIBUTES* in_object,
- wchar_t** out_name,
- uint32_t* attributes,
- HANDLE* root);
-
-// Determine full path name from object root and path.
-NTSTATUS AllocAndGetFullPath(HANDLE root,
- wchar_t* path,
- wchar_t** full_path);
-
-// Initializes our ntdll level heap
-bool InitHeap();
-
-// Returns true if the provided handle refers to the current process.
-bool IsSameProcess(HANDLE process);
-
-enum MappedModuleFlags {
- MODULE_IS_PE_IMAGE = 1, // Module is an executable.
- MODULE_HAS_ENTRY_POINT = 2, // Execution entry point found.
- MODULE_HAS_CODE = 4 // Non zero size of executable sections.
-};
-
-// Returns the name and characteristics for a given PE module. The return
-// value is the name as defined by the export table and the flags is any
-// combination of the MappedModuleFlags enumeration.
-//
-// The returned buffer must be freed with a placement delete from the ntdll
-// level allocator:
-//
-// UNICODE_STRING* name = GetPEImageInfoFromModule(HMODULE module, &flags);
-// if (!name) {
-// // probably not a valid dll
-// return;
-// }
-// InsertYourLogicHere(name);
-// operator delete(name, NT_ALLOC);
-UNICODE_STRING* GetImageInfoFromModule(HMODULE module, uint32_t* flags);
-
-// Returns the full path and filename for a given dll.
-// May return NULL if the provided address is not backed by a named section, or
-// if the current OS version doesn't support the call. The returned buffer must
-// be freed with a placement delete (see GetImageNameFromModule example).
-UNICODE_STRING* GetBackingFilePath(PVOID address);
-
-// Returns the last component of a path that contains the module name.
-// It will return NULL if the path ends with the path separator. The returned
-// buffer must be freed with a placement delete (see GetImageNameFromModule
-// example).
-UNICODE_STRING* ExtractModuleName(const UNICODE_STRING* module_path);
-
-// Returns true if the parameters correspond to a dll mapped as code.
-bool IsValidImageSection(HANDLE section, PVOID *base, PLARGE_INTEGER offset,
- PSIZE_T view_size);
-
-// Converts an ansi string to an UNICODE_STRING.
-UNICODE_STRING* AnsiToUnicode(const char* string);
-
-// Provides a simple way to temporarily change the protection of a memory page.
-class AutoProtectMemory {
- public:
- AutoProtectMemory()
- : changed_(false), address_(NULL), bytes_(0), old_protect_(0) {}
-
- ~AutoProtectMemory() {
- RevertProtection();
- }
-
- // Sets the desired protection of a given memory range.
- NTSTATUS ChangeProtection(void* address, size_t bytes, ULONG protect);
-
- // Restores the original page protection.
- NTSTATUS RevertProtection();
-
- private:
- bool changed_;
- void* address_;
- size_t bytes_;
- ULONG old_protect_;
-
- DISALLOW_COPY_AND_ASSIGN(AutoProtectMemory);
-};
-
-// Returns true if the file_rename_information structure is supported by our
-// rename handler.
-bool IsSupportedRenameCall(FILE_RENAME_INFORMATION* file_info,
- DWORD length,
- uint32_t file_info_class);
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_SANDBOX_NT_UTIL_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h b/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h
deleted file mode 100644
index cc39c6283..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h
+++ /dev/null
@@ -1,259 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_WIN_SRC_SANDBOX_POLICY_H_
-#define SANDBOX_WIN_SRC_SANDBOX_POLICY_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <string>
-
-#include "base/strings/string16.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/security_level.h"
-
-namespace sandbox {
-
-class TargetPolicy {
- public:
- // Windows subsystems that can have specific rules.
- // Note: The process subsystem(SUBSY_PROCESS) does not evaluate the request
- // exactly like the CreateProcess API does. See the comment at the top of
- // process_thread_dispatcher.cc for more details.
- enum SubSystem {
- SUBSYS_FILES, // Creation and opening of files and pipes.
- SUBSYS_NAMED_PIPES, // Creation of named pipes.
- SUBSYS_PROCESS, // Creation of child processes.
- SUBSYS_REGISTRY, // Creation and opening of registry keys.
- SUBSYS_SYNC, // Creation of named sync objects.
- SUBSYS_HANDLES, // Duplication of handles to other processes.
- SUBSYS_WIN32K_LOCKDOWN // Win32K Lockdown related policy.
- };
-
- // Allowable semantics when a rule is matched.
- enum Semantics {
- FILES_ALLOW_ANY, // Allows open or create for any kind of access that
- // the file system supports.
- FILES_ALLOW_READONLY, // Allows open or create with read access only.
- FILES_ALLOW_QUERY, // Allows access to query the attributes of a file.
- FILES_ALLOW_DIR_ANY, // Allows open or create with directory semantics
- // only.
- HANDLES_DUP_ANY, // Allows duplicating handles opened with any
- // access permissions.
- HANDLES_DUP_BROKER, // Allows duplicating handles to the broker process.
- NAMEDPIPES_ALLOW_ANY, // Allows creation of a named pipe.
- PROCESS_MIN_EXEC, // Allows to create a process with minimal rights
- // over the resulting process and thread handles.
- // No other parameters besides the command line are
- // passed to the child process.
- PROCESS_ALL_EXEC, // Allows the creation of a process and return fill
- // access on the returned handles.
- // This flag can be used only when the main token of
- // the sandboxed application is at least INTERACTIVE.
- EVENTS_ALLOW_ANY, // Allows the creation of an event with full access.
- EVENTS_ALLOW_READONLY, // Allows opening an even with synchronize access.
- REG_ALLOW_READONLY, // Allows readonly access to a registry key.
- REG_ALLOW_ANY, // Allows read and write access to a registry key.
- FAKE_USER_GDI_INIT // Fakes user32 and gdi32 initialization. This can
- // be used to allow the DLLs to load and initialize
- // even if the process cannot access that subsystem.
- };
-
- // Increments the reference count of this object. The reference count must
- // be incremented if this interface is given to another component.
- virtual void AddRef() = 0;
-
- // Decrements the reference count of this object. When the reference count
- // is zero the object is automatically destroyed.
- // Indicates that the caller is done with this interface. After calling
- // release no other method should be called.
- virtual void Release() = 0;
-
- // Sets the security level for the target process' two tokens.
- // This setting is permanent and cannot be changed once the target process is
- // spawned.
- // initial: the security level for the initial token. This is the token that
- // is used by the process from the creation of the process until the moment
- // the process calls TargetServices::LowerToken() or the process calls
- // win32's RevertToSelf(). Once this happens the initial token is no longer
- // available and the lockdown token is in effect. Using an initial token is
- // not compatible with AppContainer, see SetAppContainer.
- // lockdown: the security level for the token that comes into force after the
- // process calls TargetServices::LowerToken() or the process calls
- // RevertToSelf(). See the explanation of each level in the TokenLevel
- // definition.
- // Return value: SBOX_ALL_OK if the setting succeeds and false otherwise.
- // Returns false if the lockdown value is more permissive than the initial
- // value.
- //
- // Important: most of the sandbox-provided security relies on this single
- // setting. The caller should strive to set the lockdown level as restricted
- // as possible.
- virtual ResultCode SetTokenLevel(TokenLevel initial, TokenLevel lockdown) = 0;
-
- // Returns the initial token level.
- virtual TokenLevel GetInitialTokenLevel() const = 0;
-
- // Returns the lockdown token level.
- virtual TokenLevel GetLockdownTokenLevel() const = 0;
-
- // Sets the security level of the Job Object to which the target process will
- // belong. This setting is permanent and cannot be changed once the target
- // process is spawned. The job controls the global security settings which
- // can not be specified in the token security profile.
- // job_level: the security level for the job. See the explanation of each
- // level in the JobLevel definition.
- // ui_exceptions: specify what specific rights that are disabled in the
- // chosen job_level that need to be granted. Use this parameter to avoid
- // selecting the next permissive job level unless you need all the rights
- // that are granted in such level.
- // The exceptions can be specified as a combination of the following
- // constants:
- // JOB_OBJECT_UILIMIT_HANDLES : grant access to all user-mode handles. These
- // include windows, icons, menus and various GDI objects. In addition the
- // target process can set hooks, and broadcast messages to other processes
- // that belong to the same desktop.
- // JOB_OBJECT_UILIMIT_READCLIPBOARD : grant read-only access to the clipboard.
- // JOB_OBJECT_UILIMIT_WRITECLIPBOARD : grant write access to the clipboard.
- // JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS : allow changes to the system-wide
- // parameters as defined by the Win32 call SystemParametersInfo().
- // JOB_OBJECT_UILIMIT_DISPLAYSETTINGS : allow programmatic changes to the
- // display settings.
- // JOB_OBJECT_UILIMIT_GLOBALATOMS : allow access to the global atoms table.
- // JOB_OBJECT_UILIMIT_DESKTOP : allow the creation of new desktops.
- // JOB_OBJECT_UILIMIT_EXITWINDOWS : allow the call to ExitWindows().
- //
- // Return value: SBOX_ALL_OK if the setting succeeds and false otherwise.
- //
- // Note: JOB_OBJECT_XXXX constants are defined in winnt.h and documented at
- // length in:
- // http://msdn2.microsoft.com/en-us/library/ms684152.aspx
- //
- // Note: the recommended level is JOB_RESTRICTED or JOB_LOCKDOWN.
- virtual ResultCode SetJobLevel(JobLevel job_level,
- uint32_t ui_exceptions) = 0;
-
- // Sets a hard limit on the size of the commit set for the sandboxed process.
- // If the limit is reached, the process will be terminated with
- // SBOX_FATAL_MEMORY_EXCEEDED (7012).
- virtual ResultCode SetJobMemoryLimit(size_t memory_limit) = 0;
-
- // Specifies the desktop on which the application is going to run. If the
- // desktop does not exist, it will be created. If alternate_winstation is
- // set to true, the desktop will be created on an alternate window station.
- virtual ResultCode SetAlternateDesktop(bool alternate_winstation) = 0;
-
- // Returns the name of the alternate desktop used. If an alternate window
- // station is specified, the name is prepended by the window station name,
- // followed by a backslash.
- virtual base::string16 GetAlternateDesktop() const = 0;
-
- // Precreates the desktop and window station, if any.
- virtual ResultCode CreateAlternateDesktop(bool alternate_winstation) = 0;
-
- // Destroys the desktop and windows station.
- virtual void DestroyAlternateDesktop() = 0;
-
- // Sets the integrity level of the process in the sandbox. Both the initial
- // token and the main token will be affected by this. If the integrity level
- // is set to a level higher than the current level, the sandbox will fail
- // to start.
- virtual ResultCode SetIntegrityLevel(IntegrityLevel level) = 0;
-
- // Returns the initial integrity level used.
- virtual IntegrityLevel GetIntegrityLevel() const = 0;
-
- // Sets the integrity level of the process in the sandbox. The integrity level
- // will not take effect before you call LowerToken. User Interface Privilege
- // Isolation is not affected by this setting and will remain off for the
- // process in the sandbox. If the integrity level is set to a level higher
- // than the current level, the sandbox will fail to start.
- virtual ResultCode SetDelayedIntegrityLevel(IntegrityLevel level) = 0;
-
- // Sets the AppContainer to be used for the sandboxed process. Any capability
- // to be enabled for the process should be added before this method is invoked
- // (by calling SetCapability() as many times as needed).
- // The desired AppContainer must be already installed on the system, otherwise
- // launching the sandboxed process will fail. See BrokerServices for details
- // about installing an AppContainer.
- // Note that currently Windows restricts the use of impersonation within
- // AppContainers, so this function is incompatible with the use of an initial
- // token.
- virtual ResultCode SetAppContainer(const wchar_t* sid) = 0;
-
- // Sets a capability to be enabled for the sandboxed process' AppContainer.
- virtual ResultCode SetCapability(const wchar_t* sid) = 0;
-
- // Sets the LowBox token for sandboxed process. This is mutually exclusive
- // with SetAppContainer method.
- virtual ResultCode SetLowBox(const wchar_t* sid) = 0;
-
- // Sets the mitigations enabled when the process is created. Most of these
- // are implemented as attributes passed via STARTUPINFOEX. So they take
- // effect before any thread in the target executes. The declaration of
- // MitigationFlags is followed by a detailed description of each flag.
- virtual ResultCode SetProcessMitigations(MitigationFlags flags) = 0;
-
- // Returns the currently set mitigation flags.
- virtual MitigationFlags GetProcessMitigations() = 0;
-
- // Sets process mitigation flags that don't take effect before the call to
- // LowerToken().
- virtual ResultCode SetDelayedProcessMitigations(MitigationFlags flags) = 0;
-
- // Returns the currently set delayed mitigation flags.
- virtual MitigationFlags GetDelayedProcessMitigations() const = 0;
-
- // Sets the interceptions to operate in strict mode. By default, interceptions
- // are performed in "relaxed" mode, where if something inside NTDLL.DLL is
- // already patched we attempt to intercept it anyway. Setting interceptions
- // to strict mode means that when we detect that the function is patched we'll
- // refuse to perform the interception.
- virtual void SetStrictInterceptions() = 0;
-
- // Set the handles the target process should inherit for stdout and
- // stderr. The handles the caller passes must remain valid for the
- // lifetime of the policy object. This only has an effect on
- // Windows Vista and later versions. These methods accept pipe and
- // file handles, but not console handles.
- virtual ResultCode SetStdoutHandle(HANDLE handle) = 0;
- virtual ResultCode SetStderrHandle(HANDLE handle) = 0;
-
- // Adds a policy rule effective for processes spawned using this policy.
- // subsystem: One of the above enumerated windows subsystems.
- // semantics: One of the above enumerated FileSemantics.
- // pattern: A specific full path or a full path with wildcard patterns.
- // The valid wildcards are:
- // '*' : Matches zero or more character. Only one in series allowed.
- // '?' : Matches a single character. One or more in series are allowed.
- // Examples:
- // "c:\\documents and settings\\vince\\*.dmp"
- // "c:\\documents and settings\\*\\crashdumps\\*.dmp"
- // "c:\\temp\\app_log_?????_chrome.txt"
- virtual ResultCode AddRule(SubSystem subsystem, Semantics semantics,
- const wchar_t* pattern) = 0;
-
- // Adds a dll that will be unloaded in the target process before it gets
- // a chance to initialize itself. Typically, dlls that cause the target
- // to crash go here.
- virtual ResultCode AddDllToUnload(const wchar_t* dll_name) = 0;
-
- // Adds a handle that will be closed in the target process after lockdown.
- // A NULL value for handle_name indicates all handles of the specified type.
- // An empty string for handle_name indicates the handle is unnamed.
- virtual ResultCode AddKernelObjectToClose(const wchar_t* handle_type,
- const wchar_t* handle_name) = 0;
-
- // Adds a handle that will be shared with the target process.
- // Returns the handle which was actually shared with the target. This is
- // achieved by duplicating the handle to ensure that it is inheritable by
- // the target. The caller should treat this as an opaque value.
- virtual void* AddHandleToShare(HANDLE handle) = 0;
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_WIN_SRC_SANDBOX_POLICY_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc
deleted file mode 100644
index 28662b42d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc
+++ /dev/null
@@ -1,770 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-#include <sddl.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/callback.h"
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/stl_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/app_container.h"
-#include "sandbox/win/src/filesystem_policy.h"
-#include "sandbox/win/src/handle_policy.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/job.h"
-#include "sandbox/win/src/named_pipe_policy.h"
-#include "sandbox/win/src/policy_broker.h"
-#include "sandbox/win/src/policy_engine_processor.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/process_mitigations.h"
-#include "sandbox/win/src/process_mitigations_win32k_policy.h"
-#include "sandbox/win/src/process_thread_policy.h"
-#include "sandbox/win/src/registry_policy.h"
-#include "sandbox/win/src/restricted_token_utils.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/sandbox_utils.h"
-#include "sandbox/win/src/sync_policy.h"
-#include "sandbox/win/src/target_process.h"
-#include "sandbox/win/src/top_level_dispatcher.h"
-#include "sandbox/win/src/window.h"
-
-namespace {
-
-// The standard windows size for one memory page.
-const size_t kOneMemPage = 4096;
-// The IPC and Policy shared memory sizes.
-const size_t kIPCMemSize = kOneMemPage * 2;
-const size_t kPolMemSize = kOneMemPage * 14;
-
-// Helper function to allocate space (on the heap) for policy.
-sandbox::PolicyGlobal* MakeBrokerPolicyMemory() {
- const size_t kTotalPolicySz = kPolMemSize;
- sandbox::PolicyGlobal* policy = static_cast<sandbox::PolicyGlobal*>
- (::operator new(kTotalPolicySz));
- DCHECK(policy);
- memset(policy, 0, kTotalPolicySz);
- policy->data_size = kTotalPolicySz - sizeof(sandbox::PolicyGlobal);
- return policy;
-}
-
-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;
-}
-
-HANDLE CreateLowBoxObjectDirectory(PSID lowbox_sid) {
- DWORD session_id = 0;
- if (!::ProcessIdToSessionId(::GetCurrentProcessId(), &session_id))
- return NULL;
-
- LPWSTR sid_string = NULL;
- if (!::ConvertSidToStringSid(lowbox_sid, &sid_string))
- return NULL;
-
- base::string16 directory_path = base::StringPrintf(
- L"\\Sessions\\%d\\AppContainerNamedObjects\\%ls",
- session_id, sid_string).c_str();
- ::LocalFree(sid_string);
-
- NtCreateDirectoryObjectFunction CreateObjectDirectory = NULL;
- ResolveNTFunctionPtr("NtCreateDirectoryObject", &CreateObjectDirectory);
-
- OBJECT_ATTRIBUTES obj_attr;
- UNICODE_STRING obj_name;
- sandbox::InitObjectAttribs(directory_path,
- OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
- NULL,
- &obj_attr,
- &obj_name,
- NULL);
-
- HANDLE handle = NULL;
- NTSTATUS status = CreateObjectDirectory(&handle,
- DIRECTORY_ALL_ACCESS,
- &obj_attr);
-
- if (!NT_SUCCESS(status))
- return NULL;
-
- return handle;
-}
-
-} // namespace
-
-namespace sandbox {
-
-SANDBOX_INTERCEPT IntegrityLevel g_shared_delayed_integrity_level;
-SANDBOX_INTERCEPT MitigationFlags g_shared_delayed_mitigations;
-
-// Initializes static members.
-HWINSTA PolicyBase::alternate_winstation_handle_ = NULL;
-HDESK PolicyBase::alternate_desktop_handle_ = NULL;
-IntegrityLevel PolicyBase::alternate_desktop_integrity_level_label_ =
- INTEGRITY_LEVEL_SYSTEM;
-
-PolicyBase::PolicyBase()
- : ref_count(1),
- lockdown_level_(USER_LOCKDOWN),
- initial_level_(USER_LOCKDOWN),
- job_level_(JOB_LOCKDOWN),
- ui_exceptions_(0),
- memory_limit_(0),
- use_alternate_desktop_(false),
- use_alternate_winstation_(false),
- file_system_init_(false),
- relaxed_interceptions_(true),
- stdout_handle_(INVALID_HANDLE_VALUE),
- stderr_handle_(INVALID_HANDLE_VALUE),
- integrity_level_(INTEGRITY_LEVEL_LAST),
- delayed_integrity_level_(INTEGRITY_LEVEL_LAST),
- mitigations_(0),
- delayed_mitigations_(0),
- policy_maker_(NULL),
- policy_(NULL),
- lowbox_sid_(NULL) {
- ::InitializeCriticalSection(&lock_);
- dispatcher_.reset(new TopLevelDispatcher(this));
-}
-
-PolicyBase::~PolicyBase() {
- ClearSharedHandles();
-
- TargetSet::iterator it;
- for (it = targets_.begin(); it != targets_.end(); ++it) {
- TargetProcess* target = (*it);
- delete target;
- }
- delete policy_maker_;
- delete policy_;
-
- if (lowbox_sid_)
- ::LocalFree(lowbox_sid_);
-
- ::DeleteCriticalSection(&lock_);
-}
-
-void PolicyBase::AddRef() {
- ::InterlockedIncrement(&ref_count);
-}
-
-void PolicyBase::Release() {
- if (0 == ::InterlockedDecrement(&ref_count))
- delete this;
-}
-
-ResultCode PolicyBase::SetTokenLevel(TokenLevel initial, TokenLevel lockdown) {
- if (initial < lockdown) {
- return SBOX_ERROR_BAD_PARAMS;
- }
- initial_level_ = initial;
- lockdown_level_ = lockdown;
- return SBOX_ALL_OK;
-}
-
-TokenLevel PolicyBase::GetInitialTokenLevel() const {
- return initial_level_;
-}
-
-TokenLevel PolicyBase::GetLockdownTokenLevel() const{
- return lockdown_level_;
-}
-
-ResultCode PolicyBase::SetJobLevel(JobLevel job_level, uint32_t ui_exceptions) {
- if (memory_limit_ && job_level == JOB_NONE) {
- return SBOX_ERROR_BAD_PARAMS;
- }
- job_level_ = job_level;
- ui_exceptions_ = ui_exceptions;
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::SetJobMemoryLimit(size_t memory_limit) {
- if (memory_limit && job_level_ == JOB_NONE) {
- return SBOX_ERROR_BAD_PARAMS;
- }
- memory_limit_ = memory_limit;
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::SetAlternateDesktop(bool alternate_winstation) {
- use_alternate_desktop_ = true;
- use_alternate_winstation_ = alternate_winstation;
- return CreateAlternateDesktop(alternate_winstation);
-}
-
-base::string16 PolicyBase::GetAlternateDesktop() const {
- // No alternate desktop or winstation. Return an empty string.
- if (!use_alternate_desktop_ && !use_alternate_winstation_) {
- return base::string16();
- }
-
- // The desktop and winstation should have been created by now.
- // If we hit this scenario, it means that the user ignored the failure
- // during SetAlternateDesktop, so we ignore it here too.
- if (use_alternate_desktop_ && !alternate_desktop_handle_) {
- return base::string16();
- }
- if (use_alternate_winstation_ && (!alternate_desktop_handle_ ||
- !alternate_winstation_handle_)) {
- return base::string16();
- }
-
- return GetFullDesktopName(alternate_winstation_handle_,
- alternate_desktop_handle_);
-}
-
-ResultCode PolicyBase::CreateAlternateDesktop(bool alternate_winstation) {
- if (alternate_winstation) {
- // Previously called with alternate_winstation = false?
- if (!alternate_winstation_handle_ && alternate_desktop_handle_)
- return SBOX_ERROR_UNSUPPORTED;
-
- // Check if it's already created.
- if (alternate_winstation_handle_ && alternate_desktop_handle_)
- return SBOX_ALL_OK;
-
- DCHECK(!alternate_winstation_handle_);
- // Create the window station.
- ResultCode result = CreateAltWindowStation(&alternate_winstation_handle_);
- if (SBOX_ALL_OK != result)
- return result;
-
- // Verify that everything is fine.
- if (!alternate_winstation_handle_ ||
- GetWindowObjectName(alternate_winstation_handle_).empty())
- return SBOX_ERROR_CANNOT_CREATE_DESKTOP;
-
- // Create the destkop.
- result = CreateAltDesktop(alternate_winstation_handle_,
- &alternate_desktop_handle_);
- if (SBOX_ALL_OK != result)
- return result;
-
- // Verify that everything is fine.
- if (!alternate_desktop_handle_ ||
- GetWindowObjectName(alternate_desktop_handle_).empty())
- return SBOX_ERROR_CANNOT_CREATE_DESKTOP;
- } else {
- // Previously called with alternate_winstation = true?
- if (alternate_winstation_handle_)
- return SBOX_ERROR_UNSUPPORTED;
-
- // Check if it already exists.
- if (alternate_desktop_handle_)
- return SBOX_ALL_OK;
-
- // Create the destkop.
- ResultCode result = CreateAltDesktop(NULL, &alternate_desktop_handle_);
- if (SBOX_ALL_OK != result)
- return result;
-
- // Verify that everything is fine.
- if (!alternate_desktop_handle_ ||
- GetWindowObjectName(alternate_desktop_handle_).empty())
- return SBOX_ERROR_CANNOT_CREATE_DESKTOP;
- }
-
- return SBOX_ALL_OK;
-}
-
-void PolicyBase::DestroyAlternateDesktop() {
- if (alternate_desktop_handle_) {
- ::CloseDesktop(alternate_desktop_handle_);
- alternate_desktop_handle_ = NULL;
- }
-
- if (alternate_winstation_handle_) {
- ::CloseWindowStation(alternate_winstation_handle_);
- alternate_winstation_handle_ = NULL;
- }
-}
-
-ResultCode PolicyBase::SetIntegrityLevel(IntegrityLevel integrity_level) {
- integrity_level_ = integrity_level;
- return SBOX_ALL_OK;
-}
-
-IntegrityLevel PolicyBase::GetIntegrityLevel() const {
- return integrity_level_;
-}
-
-ResultCode PolicyBase::SetDelayedIntegrityLevel(
- IntegrityLevel integrity_level) {
- delayed_integrity_level_ = integrity_level;
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::SetAppContainer(const wchar_t* sid) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return SBOX_ALL_OK;
-
- // SetLowBox and SetAppContainer are mutually exclusive.
- if (lowbox_sid_)
- return SBOX_ERROR_UNSUPPORTED;
-
- // Windows refuses to work with an impersonation token for a process inside
- // an AppContainer. If the caller wants to use a more privileged initial
- // token, or if the lockdown level will prevent the process from starting,
- // we have to fail the operation.
- if (lockdown_level_ < USER_LIMITED || lockdown_level_ != initial_level_)
- return SBOX_ERROR_CANNOT_INIT_APPCONTAINER;
-
- DCHECK(!appcontainer_list_.get());
- appcontainer_list_.reset(new AppContainerAttributes);
- ResultCode rv = appcontainer_list_->SetAppContainer(sid, capabilities_);
- if (rv != SBOX_ALL_OK)
- return rv;
-
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::SetCapability(const wchar_t* sid) {
- capabilities_.push_back(sid);
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::SetLowBox(const wchar_t* sid) {
- if (base::win::OSInfo::GetInstance()->version() < base::win::VERSION_WIN8)
- return SBOX_ERROR_UNSUPPORTED;
-
- // SetLowBox and SetAppContainer are mutually exclusive.
- if (appcontainer_list_.get())
- return SBOX_ERROR_UNSUPPORTED;
-
- DCHECK(sid);
-
- if (lowbox_sid_)
- return SBOX_ERROR_BAD_PARAMS;
-
- if (!ConvertStringSidToSid(sid, &lowbox_sid_))
- return SBOX_ERROR_GENERIC;
-
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::SetProcessMitigations(
- MitigationFlags flags) {
- if (!CanSetProcessMitigationsPreStartup(flags))
- return SBOX_ERROR_BAD_PARAMS;
- mitigations_ = flags;
- return SBOX_ALL_OK;
-}
-
-MitigationFlags PolicyBase::GetProcessMitigations() {
- return mitigations_;
-}
-
-ResultCode PolicyBase::SetDelayedProcessMitigations(
- MitigationFlags flags) {
- if (!CanSetProcessMitigationsPostStartup(flags))
- return SBOX_ERROR_BAD_PARAMS;
- delayed_mitigations_ = flags;
- return SBOX_ALL_OK;
-}
-
-MitigationFlags PolicyBase::GetDelayedProcessMitigations() const {
- return delayed_mitigations_;
-}
-
-void PolicyBase::SetStrictInterceptions() {
- relaxed_interceptions_ = false;
-}
-
-ResultCode PolicyBase::SetStdoutHandle(HANDLE handle) {
- if (!IsInheritableHandle(handle))
- return SBOX_ERROR_BAD_PARAMS;
- stdout_handle_ = handle;
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::SetStderrHandle(HANDLE handle) {
- if (!IsInheritableHandle(handle))
- return SBOX_ERROR_BAD_PARAMS;
- stderr_handle_ = handle;
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::AddRule(SubSystem subsystem,
- Semantics semantics,
- const wchar_t* pattern) {
- ResultCode result = AddRuleInternal(subsystem, semantics, pattern);
- LOG_IF(ERROR, result != SBOX_ALL_OK) << "Failed to add sandbox rule."
- << " error = " << result
- << ", subsystem = " << subsystem
- << ", semantics = " << semantics
- << ", pattern = '" << pattern << "'";
- return result;
-}
-
-ResultCode PolicyBase::AddDllToUnload(const wchar_t* dll_name) {
- blacklisted_dlls_.push_back(dll_name);
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::AddKernelObjectToClose(const base::char16* handle_type,
- const base::char16* handle_name) {
- return handle_closer_.AddHandle(handle_type, handle_name);
-}
-
-void* PolicyBase::AddHandleToShare(HANDLE handle) {
- if (base::win::GetVersion() < base::win::VERSION_VISTA)
- return nullptr;
-
- if (!handle)
- return nullptr;
-
- HANDLE duped_handle = nullptr;
- if (!::DuplicateHandle(::GetCurrentProcess(), handle, ::GetCurrentProcess(),
- &duped_handle, 0, TRUE, DUPLICATE_SAME_ACCESS)) {
- return nullptr;
- }
- handles_to_share_.push_back(new base::win::ScopedHandle(duped_handle));
- return duped_handle;
-}
-
-const HandleList& PolicyBase::GetHandlesBeingShared() {
- return handles_to_share_;
-}
-
-void PolicyBase::ClearSharedHandles() {
- STLDeleteElements(&handles_to_share_);
-}
-
-ResultCode PolicyBase::MakeJobObject(base::win::ScopedHandle* job) {
- if (job_level_ != JOB_NONE) {
- // Create the windows job object.
- Job job_obj;
- DWORD result = job_obj.Init(job_level_, NULL, ui_exceptions_,
- memory_limit_);
- if (ERROR_SUCCESS != result)
- return SBOX_ERROR_GENERIC;
-
- *job = job_obj.Take();
- } else {
- *job = base::win::ScopedHandle();
- }
- return SBOX_ALL_OK;
-}
-
-ResultCode PolicyBase::MakeTokens(base::win::ScopedHandle* initial,
- base::win::ScopedHandle* lockdown,
- base::win::ScopedHandle* lowbox) {
- if (appcontainer_list_.get() && appcontainer_list_->HasAppContainer() &&
- lowbox_sid_) {
- return SBOX_ERROR_BAD_PARAMS;
- }
-
- // Create the 'naked' token. This will be the permanent token associated
- // with the process and therefore with any thread that is not impersonating.
- DWORD result = CreateRestrictedToken(lockdown_level_, integrity_level_,
- PRIMARY, lockdown);
- if (ERROR_SUCCESS != result)
- return SBOX_ERROR_GENERIC;
-
- // If we're launching on the alternate desktop we need to make sure the
- // integrity label on the object is no higher than the sandboxed process's
- // integrity level. So, we lower the label on the desktop process if it's
- // not already low enough for our process.
- if (alternate_desktop_handle_ && use_alternate_desktop_ &&
- integrity_level_ != INTEGRITY_LEVEL_LAST &&
- alternate_desktop_integrity_level_label_ < integrity_level_ &&
- base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_VISTA) {
- // Integrity label enum is reversed (higher level is a lower value).
- static_assert(INTEGRITY_LEVEL_SYSTEM < INTEGRITY_LEVEL_UNTRUSTED,
- "Integrity level ordering reversed.");
- result = SetObjectIntegrityLabel(alternate_desktop_handle_,
- SE_WINDOW_OBJECT,
- L"",
- GetIntegrityLevelString(integrity_level_));
- if (ERROR_SUCCESS != result)
- return SBOX_ERROR_GENERIC;
-
- alternate_desktop_integrity_level_label_ = integrity_level_;
- }
-
- // We are maintaining two mutually exclusive approaches. One is to start an
- // AppContainer process through StartupInfoEx and other is replacing
- // existing token with LowBox token after process creation.
- if (appcontainer_list_.get() && appcontainer_list_->HasAppContainer()) {
- // Windows refuses to work with an impersonation token. See SetAppContainer
- // implementation for more details.
- if (lockdown_level_ < USER_LIMITED || lockdown_level_ != initial_level_)
- return SBOX_ERROR_CANNOT_INIT_APPCONTAINER;
-
- *initial = base::win::ScopedHandle();
- return SBOX_ALL_OK;
- }
-
- if (lowbox_sid_) {
- NtCreateLowBoxToken CreateLowBoxToken = NULL;
- ResolveNTFunctionPtr("NtCreateLowBoxToken", &CreateLowBoxToken);
- OBJECT_ATTRIBUTES obj_attr;
- InitializeObjectAttributes(&obj_attr, NULL, 0, NULL, NULL);
- HANDLE token_lowbox = NULL;
-
- if (!lowbox_directory_.IsValid())
- lowbox_directory_.Set(CreateLowBoxObjectDirectory(lowbox_sid_));
- DCHECK(lowbox_directory_.IsValid());
-
- // The order of handles isn't important in the CreateLowBoxToken call.
- // The kernel will maintain a reference to the object directory handle.
- HANDLE saved_handles[1] = {lowbox_directory_.Get()};
- DWORD saved_handles_count = lowbox_directory_.IsValid() ? 1 : 0;
-
- NTSTATUS status = CreateLowBoxToken(&token_lowbox, lockdown->Get(),
- TOKEN_ALL_ACCESS, &obj_attr,
- lowbox_sid_, 0, NULL,
- saved_handles_count, saved_handles);
- if (!NT_SUCCESS(status))
- return SBOX_ERROR_GENERIC;
-
- DCHECK(token_lowbox);
- lowbox->Set(token_lowbox);
- }
-
- // Create the 'better' token. We use this token as the one that the main
- // thread uses when booting up the process. It should contain most of
- // what we need (before reaching main( ))
- result = CreateRestrictedToken(initial_level_, integrity_level_,
- IMPERSONATION, initial);
- if (ERROR_SUCCESS != result)
- return SBOX_ERROR_GENERIC;
-
- return SBOX_ALL_OK;
-}
-
-const AppContainerAttributes* PolicyBase::GetAppContainer() const {
- if (!appcontainer_list_.get() || !appcontainer_list_->HasAppContainer())
- return NULL;
-
- return appcontainer_list_.get();
-}
-
-PSID PolicyBase::GetLowBoxSid() const {
- return lowbox_sid_;
-}
-
-bool PolicyBase::AddTarget(TargetProcess* target) {
- if (NULL != policy_)
- policy_maker_->Done();
-
- if (!ApplyProcessMitigationsToSuspendedProcess(target->Process(),
- mitigations_)) {
- return false;
- }
-
- if (!SetupAllInterceptions(target))
- return false;
-
- if (!SetupHandleCloser(target))
- return false;
-
- // Initialize the sandbox infrastructure for the target.
- if (ERROR_SUCCESS !=
- target->Init(dispatcher_.get(), policy_, kIPCMemSize, kPolMemSize))
- return false;
-
- g_shared_delayed_integrity_level = delayed_integrity_level_;
- ResultCode ret = target->TransferVariable(
- "g_shared_delayed_integrity_level",
- &g_shared_delayed_integrity_level,
- sizeof(g_shared_delayed_integrity_level));
- g_shared_delayed_integrity_level = INTEGRITY_LEVEL_LAST;
- if (SBOX_ALL_OK != ret)
- return false;
-
- // Add in delayed mitigations and pseudo-mitigations enforced at startup.
- g_shared_delayed_mitigations = delayed_mitigations_ |
- FilterPostStartupProcessMitigations(mitigations_);
- if (!CanSetProcessMitigationsPostStartup(g_shared_delayed_mitigations))
- return false;
-
- ret = target->TransferVariable("g_shared_delayed_mitigations",
- &g_shared_delayed_mitigations,
- sizeof(g_shared_delayed_mitigations));
- g_shared_delayed_mitigations = 0;
- if (SBOX_ALL_OK != ret)
- return false;
-
- AutoLock lock(&lock_);
- targets_.push_back(target);
- return true;
-}
-
-bool PolicyBase::OnJobEmpty(HANDLE job) {
- AutoLock lock(&lock_);
- TargetSet::iterator it;
- for (it = targets_.begin(); it != targets_.end(); ++it) {
- if ((*it)->Job() == job)
- break;
- }
- if (it == targets_.end()) {
- return false;
- }
- TargetProcess* target = *it;
- targets_.erase(it);
- delete target;
- return true;
-}
-
-EvalResult PolicyBase::EvalPolicy(int service,
- CountedParameterSetBase* params) {
- if (NULL != policy_) {
- if (NULL == policy_->entry[service]) {
- // There is no policy for this particular service. This is not a big
- // deal.
- return DENY_ACCESS;
- }
- for (int i = 0; i < params->count; i++) {
- if (!params->parameters[i].IsValid()) {
- NOTREACHED();
- return SIGNAL_ALARM;
- }
- }
- PolicyProcessor pol_evaluator(policy_->entry[service]);
- PolicyResult result = pol_evaluator.Evaluate(kShortEval,
- params->parameters,
- params->count);
- if (POLICY_MATCH == result) {
- return pol_evaluator.GetAction();
- }
- DCHECK(POLICY_ERROR != result);
- }
-
- return DENY_ACCESS;
-}
-
-HANDLE PolicyBase::GetStdoutHandle() {
- return stdout_handle_;
-}
-
-HANDLE PolicyBase::GetStderrHandle() {
- return stderr_handle_;
-}
-
-bool PolicyBase::SetupAllInterceptions(TargetProcess* target) {
- InterceptionManager manager(target, relaxed_interceptions_);
-
- if (policy_) {
- for (int i = 0; i < IPC_LAST_TAG; i++) {
- if (policy_->entry[i] && !dispatcher_->SetupService(&manager, i))
- return false;
- }
- }
-
- if (!blacklisted_dlls_.empty()) {
- std::vector<base::string16>::iterator it = blacklisted_dlls_.begin();
- for (; it != blacklisted_dlls_.end(); ++it) {
- manager.AddToUnloadModules(it->c_str());
- }
- }
-
- if (!SetupBasicInterceptions(&manager))
- return false;
-
- if (!manager.InitializeInterceptions())
- return false;
-
- // Finally, setup imports on the target so the interceptions can work.
- return SetupNtdllImports(target);
-}
-
-bool PolicyBase::SetupHandleCloser(TargetProcess* target) {
- return handle_closer_.InitializeTargetHandles(target);
-}
-
-ResultCode PolicyBase::AddRuleInternal(SubSystem subsystem,
- Semantics semantics,
- const wchar_t* pattern) {
- if (NULL == policy_) {
- policy_ = MakeBrokerPolicyMemory();
- DCHECK(policy_);
- policy_maker_ = new LowLevelPolicy(policy_);
- DCHECK(policy_maker_);
- }
-
- switch (subsystem) {
- case SUBSYS_FILES: {
- if (!file_system_init_) {
- if (!FileSystemPolicy::SetInitialRules(policy_maker_))
- return SBOX_ERROR_BAD_PARAMS;
- file_system_init_ = true;
- }
- if (!FileSystemPolicy::GenerateRules(pattern, semantics, policy_maker_)) {
- NOTREACHED();
- return SBOX_ERROR_BAD_PARAMS;
- }
- break;
- }
- case SUBSYS_SYNC: {
- if (!SyncPolicy::GenerateRules(pattern, semantics, policy_maker_)) {
- NOTREACHED();
- return SBOX_ERROR_BAD_PARAMS;
- }
- break;
- }
- case SUBSYS_PROCESS: {
- if (lockdown_level_ < USER_INTERACTIVE &&
- TargetPolicy::PROCESS_ALL_EXEC == semantics) {
- // This is unsupported. This is a huge security risk to give full access
- // to a process handle.
- return SBOX_ERROR_UNSUPPORTED;
- }
- if (!ProcessPolicy::GenerateRules(pattern, semantics, policy_maker_)) {
- NOTREACHED();
- return SBOX_ERROR_BAD_PARAMS;
- }
- break;
- }
- case SUBSYS_NAMED_PIPES: {
- if (!NamedPipePolicy::GenerateRules(pattern, semantics, policy_maker_)) {
- NOTREACHED();
- return SBOX_ERROR_BAD_PARAMS;
- }
- break;
- }
- case SUBSYS_REGISTRY: {
- if (!RegistryPolicy::GenerateRules(pattern, semantics, policy_maker_)) {
- NOTREACHED();
- return SBOX_ERROR_BAD_PARAMS;
- }
- break;
- }
- case SUBSYS_HANDLES: {
- if (!HandlePolicy::GenerateRules(pattern, semantics, policy_maker_)) {
- NOTREACHED();
- return SBOX_ERROR_BAD_PARAMS;
- }
- break;
- }
-
- case SUBSYS_WIN32K_LOCKDOWN: {
- if (!ProcessMitigationsWin32KLockdownPolicy::GenerateRules(
- pattern, semantics, policy_maker_)) {
- NOTREACHED();
- return SBOX_ERROR_BAD_PARAMS;
- }
- break;
- }
-
- default: { return SBOX_ERROR_UNSUPPORTED; }
- }
-
- return SBOX_ALL_OK;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.h b/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.h
deleted file mode 100644
index b2d1b7c85..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.h
+++ /dev/null
@@ -1,177 +0,0 @@
-// 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 SANDBOX_WIN_SRC_SANDBOX_POLICY_BASE_H_
-#define SANDBOX_WIN_SRC_SANDBOX_POLICY_BASE_H_
-
-#include <windows.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include <list>
-#include <vector>
-
-#include "base/compiler_specific.h"
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/strings/string16.h"
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/handle_closer.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_engine_params.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace sandbox {
-
-class AppContainerAttributes;
-class LowLevelPolicy;
-class TargetProcess;
-struct PolicyGlobal;
-
-typedef std::vector<base::win::ScopedHandle*> HandleList;
-
-class PolicyBase final : public TargetPolicy {
- public:
- PolicyBase();
-
- // TargetPolicy:
- void AddRef() override;
- void Release() override;
- ResultCode SetTokenLevel(TokenLevel initial, TokenLevel lockdown) override;
- TokenLevel GetInitialTokenLevel() const override;
- TokenLevel GetLockdownTokenLevel() const override;
- ResultCode SetJobLevel(JobLevel job_level, uint32_t ui_exceptions) override;
- ResultCode SetJobMemoryLimit(size_t memory_limit) override;
- ResultCode SetAlternateDesktop(bool alternate_winstation) override;
- base::string16 GetAlternateDesktop() const override;
- ResultCode CreateAlternateDesktop(bool alternate_winstation) override;
- void DestroyAlternateDesktop() override;
- ResultCode SetIntegrityLevel(IntegrityLevel integrity_level) override;
- IntegrityLevel GetIntegrityLevel() const override;
- ResultCode SetDelayedIntegrityLevel(IntegrityLevel integrity_level) override;
- ResultCode SetAppContainer(const wchar_t* sid) override;
- ResultCode SetCapability(const wchar_t* sid) override;
- ResultCode SetLowBox(const wchar_t* sid) override;
- ResultCode SetProcessMitigations(MitigationFlags flags) override;
- MitigationFlags GetProcessMitigations() override;
- ResultCode SetDelayedProcessMitigations(MitigationFlags flags) override;
- MitigationFlags GetDelayedProcessMitigations() const override;
- void SetStrictInterceptions() override;
- ResultCode SetStdoutHandle(HANDLE handle) override;
- ResultCode SetStderrHandle(HANDLE handle) override;
- ResultCode AddRule(SubSystem subsystem,
- Semantics semantics,
- const wchar_t* pattern) override;
- ResultCode AddDllToUnload(const wchar_t* dll_name) override;
- ResultCode AddKernelObjectToClose(const base::char16* handle_type,
- const base::char16* handle_name) override;
- void* AddHandleToShare(HANDLE handle) override;
-
- // Creates a Job object with the level specified in a previous call to
- // SetJobLevel().
- ResultCode MakeJobObject(base::win::ScopedHandle* job);
-
- // Creates the two tokens with the levels specified in a previous call to
- // SetTokenLevel(). Also creates a lowbox token if specified based on the
- // lowbox SID.
- ResultCode MakeTokens(base::win::ScopedHandle* initial,
- base::win::ScopedHandle* lockdown,
- base::win::ScopedHandle* lowbox);
-
- const AppContainerAttributes* GetAppContainer() const;
-
- PSID GetLowBoxSid() const;
-
- // Adds a target process to the internal list of targets. Internally a
- // call to TargetProcess::Init() is issued.
- bool AddTarget(TargetProcess* target);
-
- // Called when there are no more active processes in a Job.
- // Removes a Job object associated with this policy and the target associated
- // with the job.
- bool OnJobEmpty(HANDLE job);
-
- EvalResult EvalPolicy(int service, CountedParameterSetBase* params);
-
- HANDLE GetStdoutHandle();
- HANDLE GetStderrHandle();
-
- // Returns the list of handles being shared with the target process.
- const HandleList& GetHandlesBeingShared();
-
- // Closes the handles being shared with the target and clears out the list.
- void ClearSharedHandles();
-
- private:
- ~PolicyBase();
-
- // Sets up interceptions for a new target.
- bool SetupAllInterceptions(TargetProcess* target);
-
- // Sets up the handle closer for a new target.
- bool SetupHandleCloser(TargetProcess* target);
-
- ResultCode AddRuleInternal(SubSystem subsystem,
- Semantics semantics,
- const wchar_t* pattern);
-
- // This lock synchronizes operations on the targets_ collection.
- CRITICAL_SECTION lock_;
- // Maintains the list of target process associated with this policy.
- // The policy takes ownership of them.
- typedef std::list<TargetProcess*> TargetSet;
- TargetSet targets_;
- // Standard object-lifetime reference counter.
- volatile LONG ref_count;
- // The user-defined global policy settings.
- TokenLevel lockdown_level_;
- TokenLevel initial_level_;
- JobLevel job_level_;
- uint32_t ui_exceptions_;
- size_t memory_limit_;
- bool use_alternate_desktop_;
- bool use_alternate_winstation_;
- // Helps the file system policy initialization.
- bool file_system_init_;
- bool relaxed_interceptions_;
- HANDLE stdout_handle_;
- HANDLE stderr_handle_;
- IntegrityLevel integrity_level_;
- IntegrityLevel delayed_integrity_level_;
- MitigationFlags mitigations_;
- MitigationFlags delayed_mitigations_;
- // Object in charge of generating the low level policy.
- LowLevelPolicy* policy_maker_;
- // Memory structure that stores the low level policy.
- PolicyGlobal* policy_;
- // The list of dlls to unload in the target process.
- std::vector<base::string16> blacklisted_dlls_;
- // This is a map of handle-types to names that we need to close in the
- // target process. A null set means we need to close all handles of the
- // given type.
- HandleCloser handle_closer_;
- std::vector<base::string16> capabilities_;
- scoped_ptr<AppContainerAttributes> appcontainer_list_;
- PSID lowbox_sid_;
- base::win::ScopedHandle lowbox_directory_;
- scoped_ptr<Dispatcher> dispatcher_;
-
- static HDESK alternate_desktop_handle_;
- static HWINSTA alternate_winstation_handle_;
- static IntegrityLevel alternate_desktop_integrity_level_label_;
-
- // Contains the list of handles being shared with the target process.
- // This list contains handles other than the stderr/stdout handles which are
- // shared with the target at times.
- HandleList handles_to_share_;
-
- DISALLOW_COPY_AND_ASSIGN(PolicyBase);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_WIN_SRC_SANDBOX_POLICY_BASE_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_rand.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_rand.cc
deleted file mode 100644
index b3f977374..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_rand.cc
+++ /dev/null
@@ -1,22 +0,0 @@
-// Copyright (c) 2015 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 "sandbox/win/src/sandbox_rand.h"
-
-#include <windows.h>
-
-// #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036. See the
-// "Community Additions" comment on MSDN here:
-// http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx
-#define SystemFunction036 NTAPI SystemFunction036
-#include <NTSecAPI.h>
-#undef SystemFunction036
-
-namespace sandbox {
-
-bool GetRandom(unsigned int* random_value) {
- return RtlGenRandom(random_value, sizeof(unsigned int)) != FALSE;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_rand.h b/security/sandbox/chromium/sandbox/win/src/sandbox_rand.h
deleted file mode 100644
index 7c4febcd5..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_rand.h
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright (c) 2015 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 SANDBOX_SRC_SANDBOX_RAND_H_
-#define SANDBOX_SRC_SANDBOX_RAND_H_
-
-
-namespace sandbox {
-
-// Generate a random value in |random_value|. Returns true on success.
-bool GetRandom(unsigned int* random_value);
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SANDBOX_RAND_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_types.h b/security/sandbox/chromium/sandbox/win/src/sandbox_types.h
deleted file mode 100644
index b749b9ca5..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_types.h
+++ /dev/null
@@ -1,95 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_WIN_SRC_SANDBOX_TYPES_H_
-#define SANDBOX_WIN_SRC_SANDBOX_TYPES_H_
-
-namespace sandbox {
-
-// Operation result codes returned by the sandbox API.
-enum ResultCode {
- SBOX_ALL_OK = 0,
- // Error is originating on the win32 layer. Call GetlastError() for more
- // information.
- SBOX_ERROR_GENERIC = 1,
- // An invalid combination of parameters was given to the API.
- SBOX_ERROR_BAD_PARAMS = 2,
- // The desired operation is not supported at this time.
- SBOX_ERROR_UNSUPPORTED = 3,
- // The request requires more memory that allocated or available.
- SBOX_ERROR_NO_SPACE = 4,
- // The ipc service requested does not exist.
- SBOX_ERROR_INVALID_IPC = 5,
- // The ipc service did not complete.
- SBOX_ERROR_FAILED_IPC = 6,
- // The requested handle was not found.
- SBOX_ERROR_NO_HANDLE = 7,
- // This function was not expected to be called at this time.
- SBOX_ERROR_UNEXPECTED_CALL = 8,
- // WaitForAllTargets is already called.
- SBOX_ERROR_WAIT_ALREADY_CALLED = 9,
- // A channel error prevented DoCall from executing.
- SBOX_ERROR_CHANNEL_ERROR = 10,
- // Failed to create the alternate desktop.
- SBOX_ERROR_CANNOT_CREATE_DESKTOP = 11,
- // Failed to create the alternate window station.
- SBOX_ERROR_CANNOT_CREATE_WINSTATION = 12,
- // Failed to switch back to the interactive window station.
- SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION = 13,
- // The supplied AppContainer is not valid.
- SBOX_ERROR_INVALID_APP_CONTAINER = 14,
- // The supplied capability is not valid.
- SBOX_ERROR_INVALID_CAPABILITY = 15,
- // There is a failure initializing the AppContainer.
- SBOX_ERROR_CANNOT_INIT_APPCONTAINER = 16,
- // Initializing or updating ProcThreadAttributes failed.
- SBOX_ERROR_PROC_THREAD_ATTRIBUTES = 17,
- // Error in creating process.
- SBOX_ERROR_CREATE_PROCESS = 18,
- // Placeholder for last item of the enum.
- SBOX_ERROR_LAST
-};
-
-// If the sandbox cannot create a secure environment for the target, the
-// target will be forcibly terminated. These are the process exit codes.
-enum TerminationCodes {
- SBOX_FATAL_INTEGRITY = 7006, // Could not set the integrity level.
- SBOX_FATAL_DROPTOKEN = 7007, // Could not lower the token.
- SBOX_FATAL_FLUSHANDLES = 7008, // Failed to flush registry handles.
- SBOX_FATAL_CACHEDISABLE = 7009, // Failed to forbid HCKU caching.
- SBOX_FATAL_CLOSEHANDLES = 7010, // Failed to close pending handles.
- SBOX_FATAL_MITIGATION = 7011, // Could not set the mitigation policy.
- SBOX_FATAL_MEMORY_EXCEEDED = 7012, // Exceeded the job memory limit.
- SBOX_FATAL_WARMUP = 7013, // Failed to warmup.
- SBOX_FATAL_LAST
-};
-
-class BrokerServices;
-class TargetServices;
-
-// Contains the pointer to a target or broker service.
-struct SandboxInterfaceInfo {
- BrokerServices* broker_services;
- TargetServices* target_services;
-};
-
-#if SANDBOX_EXPORTS
-#define SANDBOX_INTERCEPT extern "C" __declspec(dllexport)
-#else
-#define SANDBOX_INTERCEPT extern "C"
-#endif
-
-enum InterceptionType {
- INTERCEPTION_INVALID = 0,
- INTERCEPTION_SERVICE_CALL, // Trampoline of an NT native call
- INTERCEPTION_EAT,
- INTERCEPTION_SIDESTEP, // Preamble patch
- INTERCEPTION_SMART_SIDESTEP, // Preamble patch but bypass internal calls
- INTERCEPTION_UNLOAD_MODULE, // Unload the module (don't patch)
- INTERCEPTION_LAST // Placeholder for last item in the enumeration
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_WIN_SRC_SANDBOX_TYPES_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_utils.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_utils.cc
deleted file mode 100644
index 6057caffc..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_utils.cc
+++ /dev/null
@@ -1,32 +0,0 @@
-// 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 "sandbox/win/src/sandbox_utils.h"
-
-#include <windows.h>
-
-#include "base/logging.h"
-#include "sandbox/win/src/internal_types.h"
-
-namespace sandbox {
-
-void InitObjectAttribs(const base::string16& name,
- ULONG attributes,
- HANDLE root,
- OBJECT_ATTRIBUTES* obj_attr,
- UNICODE_STRING* uni_name,
- SECURITY_QUALITY_OF_SERVICE* security_qos) {
- static RtlInitUnicodeStringFunction RtlInitUnicodeString;
- if (!RtlInitUnicodeString) {
- HMODULE ntdll = ::GetModuleHandle(kNtdllName);
- RtlInitUnicodeString = reinterpret_cast<RtlInitUnicodeStringFunction>(
- GetProcAddress(ntdll, "RtlInitUnicodeString"));
- DCHECK(RtlInitUnicodeString);
- }
- RtlInitUnicodeString(uni_name, name.c_str());
- InitializeObjectAttributes(obj_attr, uni_name, attributes, root, NULL);
- obj_attr->SecurityQualityOfService = security_qos;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_utils.h b/security/sandbox/chromium/sandbox/win/src/sandbox_utils.h
deleted file mode 100644
index b1c1f3134..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sandbox_utils.h
+++ /dev/null
@@ -1,25 +0,0 @@
-// 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 SANDBOX_SRC_SANDBOX_UTILS_H_
-#define SANDBOX_SRC_SANDBOX_UTILS_H_
-
-#include <windows.h>
-#include <string>
-
-#include "base/strings/string16.h"
-#include "sandbox/win/src/nt_internals.h"
-
-namespace sandbox {
-
-void InitObjectAttribs(const base::string16& name,
- ULONG attributes,
- HANDLE root,
- OBJECT_ATTRIBUTES* obj_attr,
- UNICODE_STRING* uni_name,
- SECURITY_QUALITY_OF_SERVICE* security_qos);
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SANDBOX_UTILS_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/security_level.h b/security/sandbox/chromium/sandbox/win/src/security_level.h
deleted file mode 100644
index 26ec306a6..000000000
--- a/security/sandbox/chromium/sandbox/win/src/security_level.h
+++ /dev/null
@@ -1,209 +0,0 @@
-// 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 SANDBOX_SRC_SECURITY_LEVEL_H_
-#define SANDBOX_SRC_SECURITY_LEVEL_H_
-
-#include <stdint.h>
-
-namespace sandbox {
-
-// List of all the integrity levels supported in the sandbox. This is used
-// only on Windows Vista. You can't set the integrity level of the process
-// in the sandbox to a level higher than yours.
-enum IntegrityLevel {
- INTEGRITY_LEVEL_SYSTEM,
- INTEGRITY_LEVEL_HIGH,
- INTEGRITY_LEVEL_MEDIUM,
- INTEGRITY_LEVEL_MEDIUM_LOW,
- INTEGRITY_LEVEL_LOW,
- INTEGRITY_LEVEL_BELOW_LOW,
- INTEGRITY_LEVEL_UNTRUSTED,
- INTEGRITY_LEVEL_LAST
-};
-
-// The Token level specifies a set of security profiles designed to
-// provide the bulk of the security of sandbox.
-//
-// TokenLevel |Restricting |Deny Only |Privileges|
-// |Sids |Sids | |
-// ----------------------------|--------------|----------------|----------|
-// USER_LOCKDOWN | Null Sid | All | None |
-// ----------------------------|--------------|----------------|----------|
-// USER_RESTRICTED | RESTRICTED | All | Traverse |
-// ----------------------------|--------------|----------------|----------|
-// USER_LIMITED | Users | All except: | Traverse |
-// | Everyone | Users | |
-// | RESTRICTED | Everyone | |
-// | | Interactive | |
-// ----------------------------|--------------|----------------|----------|
-// USER_INTERACTIVE | Users | All except: | Traverse |
-// | Everyone | Users | |
-// | RESTRICTED | Everyone | |
-// | Owner | Interactive | |
-// | | Local | |
-// | | Authent-users | |
-// | | User | |
-// ----------------------------|--------------|----------------|----------|
-// USER_NON_ADMIN | None | All except: | Traverse |
-// | | Users | |
-// | | Everyone | |
-// | | Interactive | |
-// | | Local | |
-// | | Authent-users | |
-// | | User | |
-// ----------------------------|--------------|----------------|----------|
-// USER_RESTRICTED_SAME_ACCESS | All | None | All |
-// ----------------------------|--------------|----------------|----------|
-// USER_UNPROTECTED | None | None | All |
-// ----------------------------|--------------|----------------|----------|
-//
-// The above restrictions are actually a transformation that is applied to
-// the existing broker process token. The resulting token that will be
-// applied to the target process depends both on the token level selected
-// and on the broker token itself.
-//
-// The LOCKDOWN and RESTRICTED are designed to allow access to almost
-// nothing that has security associated with and they are the recommended
-// levels to run sandboxed code specially if there is a chance that the
-// broker is process might be started by a user that belongs to the Admins
-// or power users groups.
-enum TokenLevel {
- USER_LOCKDOWN = 0,
- USER_RESTRICTED,
- USER_LIMITED,
- USER_INTERACTIVE,
- USER_NON_ADMIN,
- USER_RESTRICTED_SAME_ACCESS,
- USER_UNPROTECTED,
- USER_LAST
-};
-
-// The Job level specifies a set of decreasing security profiles for the
-// Job object that the target process will be placed into.
-// This table summarizes the security associated with each level:
-//
-// JobLevel |General |Quota |
-// |restrictions |restrictions |
-// -----------------|---------------------------------- |--------------------|
-// JOB_NONE | No job is assigned to the | None |
-// | sandboxed process. | |
-// -----------------|---------------------------------- |--------------------|
-// JOB_UNPROTECTED | None | *Kill on Job close.|
-// -----------------|---------------------------------- |--------------------|
-// JOB_INTERACTIVE | *Forbid system-wide changes using | |
-// | SystemParametersInfo(). | *Kill on Job close.|
-// | *Forbid the creation/switch of | |
-// | Desktops. | |
-// | *Forbids calls to ExitWindows(). | |
-// -----------------|---------------------------------- |--------------------|
-// JOB_LIMITED_USER | Same as INTERACTIVE_USER plus: | *One active process|
-// | *Forbid changes to the display | limit. |
-// | settings. | *Kill on Job close.|
-// -----------------|---------------------------------- |--------------------|
-// JOB_RESTRICTED | Same as LIMITED_USER plus: | *One active process|
-// | * No read/write to the clipboard. | limit. |
-// | * No access to User Handles that | *Kill on Job close.|
-// | belong to other processes. | |
-// | * Forbid message broadcasts. | |
-// | * Forbid setting global hooks. | |
-// | * No access to the global atoms | |
-// | table. | |
-// -----------------|-----------------------------------|--------------------|
-// JOB_LOCKDOWN | Same as RESTRICTED | *One active process|
-// | | limit. |
-// | | *Kill on Job close.|
-// | | *Kill on unhandled |
-// | | exception. |
-// | | |
-// In the context of the above table, 'user handles' refers to the handles of
-// windows, bitmaps, menus, etc. Files, treads and registry handles are kernel
-// handles and are not affected by the job level settings.
-enum JobLevel {
- JOB_LOCKDOWN = 0,
- JOB_RESTRICTED,
- JOB_LIMITED_USER,
- JOB_INTERACTIVE,
- JOB_UNPROTECTED,
- JOB_NONE
-};
-
-// These flags correspond to various process-level mitigations (eg. ASLR and
-// DEP). Most are implemented via UpdateProcThreadAttribute() plus flags for
-// the PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY attribute argument; documented
-// here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686880
-// Some mitigations are implemented directly by the sandbox or emulated to
-// the greatest extent possible when not directly supported by the OS.
-// Flags that are unsupported for the target OS will be silently ignored.
-// Flags that are invalid for their application (pre or post startup) will
-// return SBOX_ERROR_BAD_PARAMS.
-typedef uint64_t MitigationFlags;
-
-// Permanently enables DEP for the target process. Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE.
-const MitigationFlags MITIGATION_DEP = 0x00000001;
-
-// Permanently Disables ATL thunk emulation when DEP is enabled. Valid
-// only when MITIGATION_DEP is passed. Corresponds to not passing
-// PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE.
-const MitigationFlags MITIGATION_DEP_NO_ATL_THUNK = 0x00000002;
-
-// Enables Structured exception handling override prevention. Must be
-// enabled prior to process start. Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE.
-const MitigationFlags MITIGATION_SEHOP = 0x00000004;
-
-// Forces ASLR on all images in the child process. Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON .
-const MitigationFlags MITIGATION_RELOCATE_IMAGE = 0x00000008;
-
-// Refuses to load DLLs that cannot support ASLR. Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS.
-const MitigationFlags MITIGATION_RELOCATE_IMAGE_REQUIRED = 0x00000010;
-
-// Terminates the process on Windows heap corruption. Coresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON.
-const MitigationFlags MITIGATION_HEAP_TERMINATE = 0x00000020;
-
-// Sets a random lower bound as the minimum user address. Must be
-// enabled prior to process start. On 32-bit processes this is
-// emulated to a much smaller degree. Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON.
-const MitigationFlags MITIGATION_BOTTOM_UP_ASLR = 0x00000040;
-
-// Increases the randomness range of bottom-up ASLR to up to 1TB. Must be
-// enabled prior to process start and with MITIGATION_BOTTOM_UP_ASLR.
-// Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON
-const MitigationFlags MITIGATION_HIGH_ENTROPY_ASLR = 0x00000080;
-
-// Immediately raises an exception on a bad handle reference. Must be
-// enabled after startup. Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON.
-const MitigationFlags MITIGATION_STRICT_HANDLE_CHECKS = 0x00000100;
-
-// Prevents the process from making Win32k calls. Must be enabled after
-// startup. Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON.
-const MitigationFlags MITIGATION_WIN32K_DISABLE = 0x00000200;
-
-// Disables common DLL injection methods (e.g. window hooks and
-// App_InitDLLs). Corresponds to
-// PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON.
-const MitigationFlags MITIGATION_EXTENSION_DLL_DISABLE = 0x00000400;
-
-// Sets the DLL search order to LOAD_LIBRARY_SEARCH_DEFAULT_DIRS. Additional
-// directories can be added via the Windows AddDllDirectory() function.
-// http://msdn.microsoft.com/en-us/library/windows/desktop/hh310515
-// Must be enabled after startup.
-const MitigationFlags MITIGATION_DLL_SEARCH_ORDER = 0x00000001ULL << 32;
-
-// Changes the mandatory integrity level policy on the current process' token
-// to enable no-read and no-execute up. This prevents a lower IL process from
-// opening the process token for impersonate/duplicate/assignment.
-const MitigationFlags MITIGATION_HARDEN_TOKEN_IL_POLICY = 0x00000001ULL << 33;
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SECURITY_LEVEL_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/service_resolver.cc b/security/sandbox/chromium/sandbox/win/src/service_resolver.cc
deleted file mode 100644
index 92f21a7c2..000000000
--- a/security/sandbox/chromium/sandbox/win/src/service_resolver.cc
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright 2013 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 "sandbox/win/src/service_resolver.h"
-
-#include "base/win/pe_image.h"
-#include "sandbox/win/src/internal_types.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-namespace sandbox {
-
-NTSTATUS ServiceResolverThunk::ResolveInterceptor(
- const void* interceptor_module,
- const char* interceptor_name,
- const void** address) {
- // After all, we are using a locally mapped version of the exe, so the
- // action is the same as for a target function.
- return ResolveTarget(interceptor_module, interceptor_name,
- const_cast<void**>(address));
-}
-
-// In this case all the work is done from the parent, so resolve is
-// just a simple GetProcAddress.
-NTSTATUS ServiceResolverThunk::ResolveTarget(const void* module,
- const char* function_name,
- void** address) {
- if (NULL == module)
- return STATUS_UNSUCCESSFUL;
-
- base::win::PEImage module_image(module);
- *address = module_image.GetProcAddress(function_name);
-
- if (NULL == *address) {
- NOTREACHED_NT();
- return STATUS_UNSUCCESSFUL;
- }
-
- return STATUS_SUCCESS;
-}
-
-void ServiceResolverThunk::AllowLocalPatches() {
- ntdll_base_ = ::GetModuleHandle(kNtdllName);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/service_resolver.h b/security/sandbox/chromium/sandbox/win/src/service_resolver.h
deleted file mode 100644
index 7ac5a2490..000000000
--- a/security/sandbox/chromium/sandbox/win/src/service_resolver.h
+++ /dev/null
@@ -1,159 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_SERVICE_RESOLVER_H__
-#define SANDBOX_SRC_SERVICE_RESOLVER_H__
-
-#include <stddef.h>
-
-#include "base/macros.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/resolver.h"
-
-namespace sandbox {
-
-// This is the concrete resolver used to perform service-call type functions
-// inside ntdll.dll.
-class ServiceResolverThunk : public ResolverThunk {
- public:
- // The service resolver needs a child process to write to.
- ServiceResolverThunk(HANDLE process, bool relaxed)
- : ntdll_base_(NULL),
- process_(process),
- relaxed_(relaxed),
- relative_jump_(0) {}
- ~ServiceResolverThunk() override {}
-
- // Implementation of Resolver::Setup.
- NTSTATUS Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) override;
-
- // Implementation of Resolver::ResolveInterceptor.
- NTSTATUS ResolveInterceptor(const void* module,
- const char* function_name,
- const void** address) override;
-
- // Implementation of Resolver::ResolveTarget.
- NTSTATUS ResolveTarget(const void* module,
- const char* function_name,
- void** address) override;
-
- // Implementation of Resolver::GetThunkSize.
- size_t GetThunkSize() const override;
-
- // Call this to set up ntdll_base_ which will allow for local patches.
- virtual void AllowLocalPatches();
-
- // Verifies that the function specified by |target_name| in |target_module| is
- // a service and copies the data from that function into |thunk_storage|. If
- // |storage_bytes| is too small, then the method fails.
- virtual NTSTATUS CopyThunk(const void* target_module,
- const char* target_name,
- BYTE* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used);
-
- protected:
- // The unit test will use this member to allow local patch on a buffer.
- HMODULE ntdll_base_;
-
- // Handle of the child process.
- HANDLE process_;
-
- private:
- // Returns true if the code pointer by target_ corresponds to the expected
- // type of function. Saves that code on the first part of the thunk pointed
- // by local_thunk (should be directly accessible from the parent).
- virtual bool IsFunctionAService(void* local_thunk) const;
-
- // Performs the actual patch of target_.
- // local_thunk must be already fully initialized, and the first part must
- // contain the original code. The real type of this buffer is ServiceFullThunk
- // (yes, private). remote_thunk (real type ServiceFullThunk), must be
- // allocated on the child, and will contain the thunk data, after this call.
- // Returns the apropriate status code.
- virtual NTSTATUS PerformPatch(void* local_thunk, void* remote_thunk);
-
- // Provides basically the same functionality as IsFunctionAService but it
- // continues even if it does not recognize the function code. remote_thunk
- // is the address of our memory on the child.
- bool SaveOriginalFunction(void* local_thunk, void* remote_thunk);
-
- // true if we are allowed to patch already-patched functions.
- bool relaxed_;
- ULONG relative_jump_;
-
- DISALLOW_COPY_AND_ASSIGN(ServiceResolverThunk);
-};
-
-// This is the concrete resolver used to perform service-call type functions
-// inside ntdll.dll on WOW64 (32 bit ntdll on 64 bit Vista).
-class Wow64ResolverThunk : public ServiceResolverThunk {
- public:
- // The service resolver needs a child process to write to.
- Wow64ResolverThunk(HANDLE process, bool relaxed)
- : ServiceResolverThunk(process, relaxed) {}
- ~Wow64ResolverThunk() override {}
-
- private:
- bool IsFunctionAService(void* local_thunk) const override;
-
- DISALLOW_COPY_AND_ASSIGN(Wow64ResolverThunk);
-};
-
-// This is the concrete resolver used to perform service-call type functions
-// inside ntdll.dll on WOW64 for Windows 8.
-class Wow64W8ResolverThunk : public ServiceResolverThunk {
- public:
- // The service resolver needs a child process to write to.
- Wow64W8ResolverThunk(HANDLE process, bool relaxed)
- : ServiceResolverThunk(process, relaxed) {}
- ~Wow64W8ResolverThunk() override {}
-
- private:
- bool IsFunctionAService(void* local_thunk) const override;
-
- DISALLOW_COPY_AND_ASSIGN(Wow64W8ResolverThunk);
-};
-
-// This is the concrete resolver used to perform service-call type functions
-// inside ntdll.dll on Windows 8.
-class Win8ResolverThunk : public ServiceResolverThunk {
- public:
- // The service resolver needs a child process to write to.
- Win8ResolverThunk(HANDLE process, bool relaxed)
- : ServiceResolverThunk(process, relaxed) {}
- ~Win8ResolverThunk() override {}
-
- private:
- bool IsFunctionAService(void* local_thunk) const override;
-
- DISALLOW_COPY_AND_ASSIGN(Win8ResolverThunk);
-};
-
-// This is the concrete resolver used to perform service-call type functions
-// inside ntdll.dll on WOW64 for Windows 10.
-class Wow64W10ResolverThunk : public ServiceResolverThunk {
- public:
- // The service resolver needs a child process to write to.
- Wow64W10ResolverThunk(HANDLE process, bool relaxed)
- : ServiceResolverThunk(process, relaxed) {}
- ~Wow64W10ResolverThunk() override {}
-
- private:
- bool IsFunctionAService(void* local_thunk) const override;
-
- DISALLOW_COPY_AND_ASSIGN(Wow64W10ResolverThunk);
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_SERVICE_RESOLVER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/service_resolver_32.cc b/security/sandbox/chromium/sandbox/win/src/service_resolver_32.cc
deleted file mode 100644
index f809227e9..000000000
--- a/security/sandbox/chromium/sandbox/win/src/service_resolver_32.cc
+++ /dev/null
@@ -1,478 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/service_resolver.h"
-
-#include <stddef.h>
-
-#include "base/bit_cast.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-#pragma pack(push, 1)
-
-const BYTE kMovEax = 0xB8;
-const BYTE kMovEdx = 0xBA;
-const USHORT kMovEdxEsp = 0xD48B;
-const USHORT kCallPtrEdx = 0x12FF;
-const USHORT kCallEdx = 0xD2FF;
-const BYTE kCallEip = 0xE8;
-const BYTE kRet = 0xC2;
-const BYTE kRet2 = 0xC3;
-const USHORT kJmpEdx = 0xE2FF;
-const USHORT kXorEcx = 0xC933;
-const ULONG kLeaEdx = 0x0424548D;
-const ULONG kCallFs1 = 0xC015FF64;
-const USHORT kCallFs2 = 0;
-const BYTE kCallFs3 = 0;
-const BYTE kAddEsp1 = 0x83;
-const USHORT kAddEsp2 = 0x4C4;
-const BYTE kJmp32 = 0xE9;
-const USHORT kSysenter = 0x340F;
-
-// Service code for 32 bit systems.
-// NOTE: on win2003 "call dword ptr [edx]" is "call edx".
-struct ServiceEntry {
- // This struct contains roughly the following code:
- // 00 mov eax,25h
- // 05 mov edx,offset SharedUserData!SystemCallStub (7ffe0300)
- // 0a call dword ptr [edx]
- // 0c ret 2Ch
- // 0f nop
- BYTE mov_eax; // = B8
- ULONG service_id;
- BYTE mov_edx; // = BA
- ULONG stub;
- USHORT call_ptr_edx; // = FF 12
- BYTE ret; // = C2
- USHORT num_params;
- BYTE nop;
-};
-
-// Service code for 32 bit Windows 8.
-struct ServiceEntryW8 {
- // This struct contains the following code:
- // 00 b825000000 mov eax,25h
- // 05 e803000000 call eip+3
- // 0a c22c00 ret 2Ch
- // 0d 8bd4 mov edx,esp
- // 0f 0f34 sysenter
- // 11 c3 ret
- // 12 8bff mov edi,edi
- BYTE mov_eax; // = B8
- ULONG service_id;
- BYTE call_eip; // = E8
- ULONG call_offset;
- BYTE ret_p; // = C2
- USHORT num_params;
- USHORT mov_edx_esp; // = BD D4
- USHORT sysenter; // = 0F 34
- BYTE ret; // = C3
- USHORT nop;
-};
-
-// Service code for a 32 bit process running on a 64 bit os.
-struct Wow64Entry {
- // This struct may contain one of two versions of code:
- // 1. For XP, Vista and 2K3:
- // 00 b825000000 mov eax, 25h
- // 05 33c9 xor ecx, ecx
- // 07 8d542404 lea edx, [esp + 4]
- // 0b 64ff15c0000000 call dword ptr fs:[0C0h]
- // 12 c22c00 ret 2Ch
- //
- // 2. For Windows 7:
- // 00 b825000000 mov eax, 25h
- // 05 33c9 xor ecx, ecx
- // 07 8d542404 lea edx, [esp + 4]
- // 0b 64ff15c0000000 call dword ptr fs:[0C0h]
- // 12 83c404 add esp, 4
- // 15 c22c00 ret 2Ch
- //
- // So we base the structure on the bigger one:
- BYTE mov_eax; // = B8
- ULONG service_id;
- USHORT xor_ecx; // = 33 C9
- ULONG lea_edx; // = 8D 54 24 04
- ULONG call_fs1; // = 64 FF 15 C0
- USHORT call_fs2; // = 00 00
- BYTE call_fs3; // = 00
- BYTE add_esp1; // = 83 or ret
- USHORT add_esp2; // = C4 04 or num_params
- BYTE ret; // = C2
- USHORT num_params;
-};
-
-// Service code for a 32 bit process running on 64 bit Windows 8.
-struct Wow64EntryW8 {
- // 00 b825000000 mov eax, 25h
- // 05 64ff15c0000000 call dword ptr fs:[0C0h]
- // 0b c22c00 ret 2Ch
- // 0f 90 nop
- BYTE mov_eax; // = B8
- ULONG service_id;
- ULONG call_fs1; // = 64 FF 15 C0
- USHORT call_fs2; // = 00 00
- BYTE call_fs3; // = 00
- BYTE ret; // = C2
- USHORT num_params;
- BYTE nop;
-};
-
-// Service code for a 32 bit process running on 64 bit Windows 10.
-struct Wow64EntryW10 {
- // 00 b828000000 mov eax, 28h
- // 05 bab0d54877 mov edx, 7748D5B0h
- // 09 ffd2 call edx
- // 0b c22800 ret 28h
- BYTE mov_eax; // = B8
- ULONG service_id;
- BYTE mov_edx; // = BA
- ULONG mov_edx_param;
- USHORT call_edx; // = FF D2
- BYTE ret; // = C2
- USHORT num_params;
-};
-
-// Make sure that relaxed patching works as expected.
-const size_t kMinServiceSize = offsetof(ServiceEntry, ret);
-static_assert(sizeof(ServiceEntryW8) >= kMinServiceSize,
- "wrong service length");
-static_assert(sizeof(Wow64Entry) >= kMinServiceSize, "wrong service length");
-static_assert(sizeof(Wow64EntryW8) >= kMinServiceSize, "wrong service length");
-
-struct ServiceFullThunk {
- union {
- ServiceEntry original;
- ServiceEntryW8 original_w8;
- Wow64Entry wow_64;
- Wow64EntryW8 wow_64_w8;
- };
- int internal_thunk; // Dummy member to the beginning of the internal thunk.
-};
-
-#pragma pack(pop)
-
-}; // namespace
-
-namespace sandbox {
-
-NTSTATUS ServiceResolverThunk::Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) {
- NTSTATUS ret = Init(target_module, interceptor_module, target_name,
- interceptor_name, interceptor_entry_point,
- thunk_storage, storage_bytes);
- if (!NT_SUCCESS(ret))
- return ret;
-
- relative_jump_ = 0;
- size_t thunk_bytes = GetThunkSize();
- scoped_ptr<char[]> thunk_buffer(new char[thunk_bytes]);
- ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(
- thunk_buffer.get());
-
- if (!IsFunctionAService(&thunk->original) &&
- (!relaxed_ || !SaveOriginalFunction(&thunk->original, thunk_storage))) {
- return STATUS_UNSUCCESSFUL;
- }
-
- ret = PerformPatch(thunk, thunk_storage);
-
- if (NULL != storage_used)
- *storage_used = thunk_bytes;
-
- return ret;
-}
-
-size_t ServiceResolverThunk::GetThunkSize() const {
- return offsetof(ServiceFullThunk, internal_thunk) + GetInternalThunkSize();
-}
-
-NTSTATUS ServiceResolverThunk::CopyThunk(const void* target_module,
- const char* target_name,
- BYTE* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) {
- NTSTATUS ret = ResolveTarget(target_module, target_name, &target_);
- if (!NT_SUCCESS(ret))
- return ret;
-
- size_t thunk_bytes = GetThunkSize();
- if (storage_bytes < thunk_bytes)
- return STATUS_UNSUCCESSFUL;
-
- ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(thunk_storage);
-
- if (!IsFunctionAService(&thunk->original) &&
- (!relaxed_ || !SaveOriginalFunction(&thunk->original, thunk_storage))) {
- return STATUS_UNSUCCESSFUL;
- }
-
- if (NULL != storage_used)
- *storage_used = thunk_bytes;
-
- return ret;
-}
-
-bool ServiceResolverThunk::IsFunctionAService(void* local_thunk) const {
- ServiceEntry function_code;
- SIZE_T read;
- if (!::ReadProcessMemory(process_, target_, &function_code,
- sizeof(function_code), &read)) {
- return false;
- }
-
- if (sizeof(function_code) != read)
- return false;
-
- if (kMovEax != function_code.mov_eax ||
- kMovEdx != function_code.mov_edx ||
- (kCallPtrEdx != function_code.call_ptr_edx &&
- kCallEdx != function_code.call_ptr_edx) ||
- kRet != function_code.ret) {
- return false;
- }
-
- // Find the system call pointer if we don't already have it.
- if (kCallEdx != function_code.call_ptr_edx) {
- DWORD ki_system_call;
- if (!::ReadProcessMemory(process_,
- bit_cast<const void*>(function_code.stub),
- &ki_system_call, sizeof(ki_system_call), &read)) {
- return false;
- }
-
- if (sizeof(ki_system_call) != read)
- return false;
-
- HMODULE module_1, module_2;
- // last check, call_stub should point to a KiXXSystemCall function on ntdll
- if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
- GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
- bit_cast<const wchar_t*>(ki_system_call),
- &module_1)) {
- return false;
- }
-
- if (NULL != ntdll_base_) {
- // This path is only taken when running the unit tests. We want to be
- // able to patch a buffer in memory, so target_ is not inside ntdll.
- module_2 = ntdll_base_;
- } else {
- if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
- GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
- reinterpret_cast<const wchar_t*>(target_),
- &module_2))
- return false;
- }
-
- if (module_1 != module_2)
- return false;
- }
-
- // Save the verified code
- memcpy(local_thunk, &function_code, sizeof(function_code));
-
- return true;
-}
-
-NTSTATUS ServiceResolverThunk::PerformPatch(void* local_thunk,
- void* remote_thunk) {
- ServiceEntry intercepted_code;
- size_t bytes_to_write = sizeof(intercepted_code);
- ServiceFullThunk *full_local_thunk = reinterpret_cast<ServiceFullThunk*>(
- local_thunk);
- ServiceFullThunk *full_remote_thunk = reinterpret_cast<ServiceFullThunk*>(
- remote_thunk);
-
- // patch the original code
- memcpy(&intercepted_code, &full_local_thunk->original,
- sizeof(intercepted_code));
- intercepted_code.mov_eax = kMovEax;
- intercepted_code.service_id = full_local_thunk->original.service_id;
- intercepted_code.mov_edx = kMovEdx;
- intercepted_code.stub = bit_cast<ULONG>(&full_remote_thunk->internal_thunk);
- intercepted_code.call_ptr_edx = kJmpEdx;
- bytes_to_write = kMinServiceSize;
-
- if (relative_jump_) {
- intercepted_code.mov_eax = kJmp32;
- intercepted_code.service_id = relative_jump_;
- bytes_to_write = offsetof(ServiceEntry, mov_edx);
- }
-
- // setup the thunk
- SetInternalThunk(&full_local_thunk->internal_thunk, GetInternalThunkSize(),
- remote_thunk, interceptor_);
-
- size_t thunk_size = GetThunkSize();
-
- // copy the local thunk buffer to the child
- SIZE_T written;
- if (!::WriteProcessMemory(process_, remote_thunk, local_thunk,
- thunk_size, &written)) {
- return STATUS_UNSUCCESSFUL;
- }
-
- if (thunk_size != written)
- return STATUS_UNSUCCESSFUL;
-
- // and now change the function to intercept, on the child
- if (NULL != ntdll_base_) {
- // running a unit test
- if (!::WriteProcessMemory(process_, target_, &intercepted_code,
- bytes_to_write, &written))
- return STATUS_UNSUCCESSFUL;
- } else {
- if (!WriteProtectedChildMemory(process_, target_, &intercepted_code,
- bytes_to_write))
- return STATUS_UNSUCCESSFUL;
- }
-
- return STATUS_SUCCESS;
-}
-
-bool ServiceResolverThunk::SaveOriginalFunction(void* local_thunk,
- void* remote_thunk) {
- ServiceEntry function_code;
- SIZE_T read;
- if (!::ReadProcessMemory(process_, target_, &function_code,
- sizeof(function_code), &read)) {
- return false;
- }
-
- if (sizeof(function_code) != read)
- return false;
-
- if (kJmp32 == function_code.mov_eax) {
- // Plain old entry point patch. The relative jump address follows it.
- ULONG relative = function_code.service_id;
-
- // First, fix our copy of their patch.
- relative += bit_cast<ULONG>(target_) - bit_cast<ULONG>(remote_thunk);
-
- function_code.service_id = relative;
-
- // And now, remember how to re-patch it.
- ServiceFullThunk *full_thunk =
- reinterpret_cast<ServiceFullThunk*>(remote_thunk);
-
- const ULONG kJmp32Size = 5;
-
- relative_jump_ = bit_cast<ULONG>(&full_thunk->internal_thunk) -
- bit_cast<ULONG>(target_) - kJmp32Size;
- }
-
- // Save the verified code
- memcpy(local_thunk, &function_code, sizeof(function_code));
-
- return true;
-}
-
-bool Wow64ResolverThunk::IsFunctionAService(void* local_thunk) const {
- Wow64Entry function_code;
- SIZE_T read;
- if (!::ReadProcessMemory(process_, target_, &function_code,
- sizeof(function_code), &read)) {
- return false;
- }
-
- if (sizeof(function_code) != read)
- return false;
-
- if (kMovEax != function_code.mov_eax || kXorEcx != function_code.xor_ecx ||
- kLeaEdx != function_code.lea_edx || kCallFs1 != function_code.call_fs1 ||
- kCallFs2 != function_code.call_fs2 ||
- kCallFs3 != function_code.call_fs3) {
- return false;
- }
-
- if ((kAddEsp1 == function_code.add_esp1 &&
- kAddEsp2 == function_code.add_esp2 &&
- kRet == function_code.ret) || kRet == function_code.add_esp1) {
- // Save the verified code
- memcpy(local_thunk, &function_code, sizeof(function_code));
- return true;
- }
-
- return false;
-}
-
-bool Wow64W8ResolverThunk::IsFunctionAService(void* local_thunk) const {
- Wow64EntryW8 function_code;
- SIZE_T read;
- if (!::ReadProcessMemory(process_, target_, &function_code,
- sizeof(function_code), &read)) {
- return false;
- }
-
- if (sizeof(function_code) != read)
- return false;
-
- if (kMovEax != function_code.mov_eax || kCallFs1 != function_code.call_fs1 ||
- kCallFs2 != function_code.call_fs2 ||
- kCallFs3 != function_code.call_fs3 || kRet != function_code.ret) {
- return false;
- }
-
- // Save the verified code
- memcpy(local_thunk, &function_code, sizeof(function_code));
- return true;
-}
-
-bool Win8ResolverThunk::IsFunctionAService(void* local_thunk) const {
- ServiceEntryW8 function_code;
- SIZE_T read;
- if (!::ReadProcessMemory(process_, target_, &function_code,
- sizeof(function_code), &read)) {
- return false;
- }
-
- if (sizeof(function_code) != read)
- return false;
-
- if (kMovEax != function_code.mov_eax || kCallEip != function_code.call_eip ||
- function_code.call_offset != 3 || kRet != function_code.ret_p ||
- kMovEdxEsp != function_code.mov_edx_esp ||
- kSysenter != function_code.sysenter || kRet2 != function_code.ret) {
- return false;
- }
-
- // Save the verified code
- memcpy(local_thunk, &function_code, sizeof(function_code));
-
- return true;
-}
-
-bool Wow64W10ResolverThunk::IsFunctionAService(void* local_thunk) const {
- Wow64EntryW10 function_code;
- SIZE_T read;
- if (!::ReadProcessMemory(process_, target_, &function_code,
- sizeof(function_code), &read)) {
- return false;
- }
-
- if (sizeof(function_code) != read)
- return false;
-
- if (kMovEax != function_code.mov_eax ||
- kMovEdx != function_code.mov_edx ||
- kCallEdx != function_code.call_edx ||
- kRet != function_code.ret) {
- return false;
- }
-
- // Save the verified code
- memcpy(local_thunk, &function_code, sizeof(function_code));
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/service_resolver_64.cc b/security/sandbox/chromium/sandbox/win/src/service_resolver_64.cc
deleted file mode 100644
index 25ee9db26..000000000
--- a/security/sandbox/chromium/sandbox/win/src/service_resolver_64.cc
+++ /dev/null
@@ -1,252 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/service_resolver.h"
-
-#include <stddef.h>
-
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-#pragma pack(push, 1)
-
-const ULONG kMmovR10EcxMovEax = 0xB8D18B4C;
-const USHORT kSyscall = 0x050F;
-const BYTE kRetNp = 0xC3;
-const ULONG64 kMov1 = 0x54894808244C8948;
-const ULONG64 kMov2 = 0x4C182444894C1024;
-const ULONG kMov3 = 0x20244C89;
-const USHORT kTestByte = 0x04F6;
-const BYTE kPtr = 0x25;
-const BYTE kRet = 0xC3;
-const USHORT kJne = 0x0375;
-
-// Service code for 64 bit systems.
-struct ServiceEntry {
- // This struct contains roughly the following code:
- // 00 mov r10,rcx
- // 03 mov eax,52h
- // 08 syscall
- // 0a ret
- // 0b xchg ax,ax
- // 0e xchg ax,ax
-
- ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8
- ULONG service_id;
- USHORT syscall; // = 0F 05
- BYTE ret; // = C3
- BYTE pad; // = 66
- USHORT xchg_ax_ax1; // = 66 90
- USHORT xchg_ax_ax2; // = 66 90
-};
-
-// Service code for 64 bit Windows 8.
-struct ServiceEntryW8 {
- // This struct contains the following code:
- // 00 48894c2408 mov [rsp+8], rcx
- // 05 4889542410 mov [rsp+10], rdx
- // 0a 4c89442418 mov [rsp+18], r8
- // 0f 4c894c2420 mov [rsp+20], r9
- // 14 4c8bd1 mov r10,rcx
- // 17 b825000000 mov eax,25h
- // 1c 0f05 syscall
- // 1e c3 ret
- // 1f 90 nop
-
- ULONG64 mov_1; // = 48 89 4C 24 08 48 89 54
- ULONG64 mov_2; // = 24 10 4C 89 44 24 18 4C
- ULONG mov_3; // = 89 4C 24 20
- ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8
- ULONG service_id;
- USHORT syscall; // = 0F 05
- BYTE ret; // = C3
- BYTE nop; // = 90
-};
-
-// Service code for 64 bit systems with int 2e fallback.
-struct ServiceEntryWithInt2E {
- // This struct contains roughly the following code:
- // 00 4c8bd1 mov r10,rcx
- // 03 b855000000 mov eax,52h
- // 08 f604250803fe7f01 test byte ptr SharedUserData!308, 1
- // 10 7503 jne [over syscall]
- // 12 0f05 syscall
- // 14 c3 ret
- // 15 cd2e int 2e
- // 17 c3 ret
-
- ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8
- ULONG service_id;
- USHORT test_byte; // = F6 04
- BYTE ptr; // = 25
- ULONG user_shared_data_ptr;
- BYTE one; // = 01
- USHORT jne_over_syscall; // = 75 03
- USHORT syscall; // = 0F 05
- BYTE ret; // = C3
- USHORT int2e; // = CD 2E
- BYTE ret2; // = C3
-};
-
-// We don't have an internal thunk for x64.
-struct ServiceFullThunk {
- union {
- ServiceEntry original;
- ServiceEntryW8 original_w8;
- ServiceEntryWithInt2E original_int2e_fallback;
- };
-};
-
-#pragma pack(pop)
-
-bool IsService(const void* source) {
- const ServiceEntry* service =
- reinterpret_cast<const ServiceEntry*>(source);
-
- return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax &&
- kSyscall == service->syscall && kRetNp == service->ret);
-}
-
-bool IsServiceW8(const void* source) {
- const ServiceEntryW8* service =
- reinterpret_cast<const ServiceEntryW8*>(source);
-
- return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax &&
- kMov1 == service->mov_1 && kMov2 == service->mov_2 &&
- kMov3 == service->mov_3);
-}
-
-bool IsServiceWithInt2E(const void* source) {
- const ServiceEntryWithInt2E* service =
- reinterpret_cast<const ServiceEntryWithInt2E*>(source);
-
- return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax &&
- kTestByte == service->test_byte && kPtr == service->ptr &&
- kJne == service->jne_over_syscall && kSyscall == service->syscall &&
- kRet == service->ret && kRet == service->ret2);
-}
-
-}; // namespace
-
-namespace sandbox {
-
-NTSTATUS ServiceResolverThunk::Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) {
- NTSTATUS ret =
- Init(target_module, interceptor_module, target_name, interceptor_name,
- interceptor_entry_point, thunk_storage, storage_bytes);
- if (!NT_SUCCESS(ret))
- return ret;
-
- size_t thunk_bytes = GetThunkSize();
- scoped_ptr<char[]> thunk_buffer(new char[thunk_bytes]);
- ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(
- thunk_buffer.get());
-
- if (!IsFunctionAService(&thunk->original))
- return STATUS_UNSUCCESSFUL;
-
- ret = PerformPatch(thunk, thunk_storage);
-
- if (NULL != storage_used)
- *storage_used = thunk_bytes;
-
- return ret;
-}
-
-size_t ServiceResolverThunk::GetThunkSize() const {
- return sizeof(ServiceFullThunk);
-}
-
-NTSTATUS ServiceResolverThunk::CopyThunk(const void* target_module,
- const char* target_name,
- BYTE* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) {
- NTSTATUS ret = ResolveTarget(target_module, target_name, &target_);
- if (!NT_SUCCESS(ret))
- return ret;
-
- size_t thunk_bytes = GetThunkSize();
- if (storage_bytes < thunk_bytes)
- return STATUS_UNSUCCESSFUL;
-
- ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(thunk_storage);
-
- if (!IsFunctionAService(&thunk->original))
- return STATUS_UNSUCCESSFUL;
-
- if (NULL != storage_used)
- *storage_used = thunk_bytes;
-
- return ret;
-}
-
-bool ServiceResolverThunk::IsFunctionAService(void* local_thunk) const {
- ServiceFullThunk function_code;
- SIZE_T read;
- if (!::ReadProcessMemory(process_, target_, &function_code,
- sizeof(function_code), &read))
- return false;
-
- if (sizeof(function_code) != read)
- return false;
-
- if (!IsService(&function_code) && !IsServiceW8(&function_code) &&
- !IsServiceWithInt2E(&function_code))
- return false;
-
- // Save the verified code.
- memcpy(local_thunk, &function_code, sizeof(function_code));
-
- return true;
-}
-
-NTSTATUS ServiceResolverThunk::PerformPatch(void* local_thunk,
- void* remote_thunk) {
- // Patch the original code.
- ServiceEntry local_service;
- DCHECK_NT(GetInternalThunkSize() <= sizeof(local_service));
- if (!SetInternalThunk(&local_service, sizeof(local_service), NULL,
- interceptor_))
- return STATUS_UNSUCCESSFUL;
-
- // Copy the local thunk buffer to the child.
- SIZE_T actual;
- if (!::WriteProcessMemory(process_, remote_thunk, local_thunk,
- sizeof(ServiceFullThunk), &actual))
- return STATUS_UNSUCCESSFUL;
-
- if (sizeof(ServiceFullThunk) != actual)
- return STATUS_UNSUCCESSFUL;
-
- // And now change the function to intercept, on the child.
- if (NULL != ntdll_base_) {
- // Running a unit test.
- if (!::WriteProcessMemory(process_, target_, &local_service,
- sizeof(local_service), &actual))
- return STATUS_UNSUCCESSFUL;
- } else {
- if (!WriteProtectedChildMemory(process_, target_, &local_service,
- sizeof(local_service)))
- return STATUS_UNSUCCESSFUL;
- }
-
- return STATUS_SUCCESS;
-}
-
-bool Wow64ResolverThunk::IsFunctionAService(void* local_thunk) const {
- NOTREACHED_NT();
- return false;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/service_resolver_unittest.cc b/security/sandbox/chromium/sandbox/win/src/service_resolver_unittest.cc
deleted file mode 100644
index 25d087573..000000000
--- a/security/sandbox/chromium/sandbox/win/src/service_resolver_unittest.cc
+++ /dev/null
@@ -1,268 +0,0 @@
-// 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 file contains unit tests for ServiceResolverThunk.
-
-#include <stddef.h>
-
-#include "base/bit_cast.h"
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/resolver.h"
-#include "sandbox/win/src/sandbox_utils.h"
-#include "sandbox/win/src/service_resolver.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-
-// This is the concrete resolver used to perform service-call type functions
-// inside ntdll.dll.
-template<typename T>
-class ResolverThunkTest : public T {
- public:
- // The service resolver needs a child process to write to.
- explicit ResolverThunkTest(bool relaxed)
- : T(::GetCurrentProcess(), relaxed) {}
-
- // Sets the interception target to the desired address.
- void set_target(void* target) {
- fake_target_ = target;
- }
-
- protected:
- // Overrides Resolver::Init
- virtual NTSTATUS Init(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes) {
- NTSTATUS ret = STATUS_SUCCESS;
- ret = T::Init(target_module, interceptor_module, target_name,
- interceptor_name, interceptor_entry_point, thunk_storage,
- storage_bytes);
- EXPECT_EQ(STATUS_SUCCESS, ret);
-
- this->target_ = fake_target_;
-
- return ret;
- };
-
- private:
- // Holds the address of the fake target.
- void* fake_target_;
-
- DISALLOW_COPY_AND_ASSIGN(ResolverThunkTest);
-};
-
-typedef ResolverThunkTest<sandbox::ServiceResolverThunk> WinXpResolverTest;
-
-#if !defined(_WIN64)
-typedef ResolverThunkTest<sandbox::Win8ResolverThunk> Win8ResolverTest;
-typedef ResolverThunkTest<sandbox::Wow64ResolverThunk> Wow64ResolverTest;
-typedef ResolverThunkTest<sandbox::Wow64W8ResolverThunk> Wow64W8ResolverTest;
-typedef ResolverThunkTest<sandbox::Wow64W10ResolverThunk> Wow64W10ResolverTest;
-#endif
-
-const BYTE kJump32 = 0xE9;
-
-void CheckJump(void* source, void* target) {
-#pragma pack(push)
-#pragma pack(1)
- struct Code {
- BYTE jump;
- ULONG delta;
- };
-#pragma pack(pop)
-
-#if defined(_WIN64)
- FAIL() << "Running 32-bit codepath";
-#else
- Code* patched = reinterpret_cast<Code*>(source);
- EXPECT_EQ(kJump32, patched->jump);
-
- ULONG source_addr = bit_cast<ULONG>(source);
- ULONG target_addr = bit_cast<ULONG>(target);
- EXPECT_EQ(target_addr + 19 - source_addr, patched->delta);
-#endif
-}
-
-NTSTATUS PatchNtdllWithResolver(const char* function, bool relaxed,
- sandbox::ServiceResolverThunk* resolver) {
- HMODULE ntdll_base = ::GetModuleHandle(L"ntdll.dll");
- EXPECT_TRUE(NULL != ntdll_base);
-
- void* target = ::GetProcAddress(ntdll_base, function);
- EXPECT_TRUE(NULL != target);
- if (NULL == target)
- return STATUS_UNSUCCESSFUL;
-
- BYTE service[50];
- memcpy(service, target, sizeof(service));
-
- static_cast<WinXpResolverTest*>(resolver)->set_target(service);
-
- // Any pointer will do as an interception_entry_point
- void* function_entry = resolver;
- size_t thunk_size = resolver->GetThunkSize();
- scoped_ptr<char[]> thunk(new char[thunk_size]);
- size_t used;
-
- resolver->AllowLocalPatches();
-
- NTSTATUS ret = resolver->Setup(ntdll_base, NULL, function, NULL,
- function_entry, thunk.get(), thunk_size,
- &used);
- if (NT_SUCCESS(ret)) {
- EXPECT_EQ(thunk_size, used);
- EXPECT_NE(0, memcmp(service, target, sizeof(service)));
- EXPECT_NE(kJump32, service[0]);
-
- if (relaxed) {
- // It's already patched, let's patch again, and simulate a direct patch.
- service[0] = kJump32;
- ret = resolver->Setup(ntdll_base, NULL, function, NULL, function_entry,
- thunk.get(), thunk_size, &used);
- CheckJump(service, thunk.get());
- }
- }
-
- return ret;
-}
-
-sandbox::ServiceResolverThunk* GetTestResolver(bool relaxed) {
-#if defined(_WIN64)
- return new WinXpResolverTest(relaxed);
-#else
- base::win::OSInfo* os_info = base::win::OSInfo::GetInstance();
- if (os_info->wow64_status() == base::win::OSInfo::WOW64_ENABLED) {
- if (os_info->version() >= base::win::VERSION_WIN10)
- return new Wow64W10ResolverTest(relaxed);
- if (os_info->version() >= base::win::VERSION_WIN8)
- return new Wow64W8ResolverTest(relaxed);
- return new Wow64ResolverTest(relaxed);
- }
-
- if (os_info->version() >= base::win::VERSION_WIN8)
- return new Win8ResolverTest(relaxed);
-
- return new WinXpResolverTest(relaxed);
-#endif
-}
-
-NTSTATUS PatchNtdll(const char* function, bool relaxed) {
- sandbox::ServiceResolverThunk* resolver = GetTestResolver(relaxed);
-
- NTSTATUS ret = PatchNtdllWithResolver(function, relaxed, resolver);
- delete resolver;
- return ret;
-}
-
-TEST(ServiceResolverTest, PatchesServices) {
- NTSTATUS ret = PatchNtdll("NtClose", false);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtClose, last error: " << ::GetLastError();
-
- ret = PatchNtdll("NtCreateFile", false);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtCreateFile, last error: " <<
- ::GetLastError();
-
- ret = PatchNtdll("NtCreateMutant", false);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtCreateMutant, last error: " <<
- ::GetLastError();
-
- ret = PatchNtdll("NtMapViewOfSection", false);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtMapViewOfSection, last error: " <<
- ::GetLastError();
-}
-
-TEST(ServiceResolverTest, FailsIfNotService) {
-#if !defined(_WIN64)
- EXPECT_NE(STATUS_SUCCESS, PatchNtdll("RtlUlongByteSwap", false));
-#endif
-
- EXPECT_NE(STATUS_SUCCESS, PatchNtdll("LdrLoadDll", false));
-}
-
-TEST(ServiceResolverTest, PatchesPatchedServices) {
-// We don't support "relaxed mode" for Win64 apps.
-#if !defined(_WIN64)
- NTSTATUS ret = PatchNtdll("NtClose", true);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtClose, last error: " << ::GetLastError();
-
- ret = PatchNtdll("NtCreateFile", true);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtCreateFile, last error: " <<
- ::GetLastError();
-
- ret = PatchNtdll("NtCreateMutant", true);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtCreateMutant, last error: " <<
- ::GetLastError();
-
- ret = PatchNtdll("NtMapViewOfSection", true);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtMapViewOfSection, last error: " <<
- ::GetLastError();
-#endif
-}
-
-TEST(ServiceResolverTest, MultiplePatchedServices) {
-// We don't support "relaxed mode" for Win64 apps.
-#if !defined(_WIN64)
- sandbox::ServiceResolverThunk* resolver = GetTestResolver(true);
- NTSTATUS ret = PatchNtdllWithResolver("NtClose", true, resolver);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtClose, last error: " << ::GetLastError();
-
- ret = PatchNtdllWithResolver("NtCreateFile", true, resolver);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtCreateFile, last error: " <<
- ::GetLastError();
-
- ret = PatchNtdllWithResolver("NtCreateMutant", true, resolver);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtCreateMutant, last error: " <<
- ::GetLastError();
-
- ret = PatchNtdllWithResolver("NtMapViewOfSection", true, resolver);
- EXPECT_EQ(STATUS_SUCCESS, ret) << "NtMapViewOfSection, last error: " <<
- ::GetLastError();
- delete resolver;
-#endif
-}
-
-TEST(ServiceResolverTest, LocalPatchesAllowed) {
- sandbox::ServiceResolverThunk* resolver = GetTestResolver(true);
-
- HMODULE ntdll_base = ::GetModuleHandle(L"ntdll.dll");
- ASSERT_TRUE(NULL != ntdll_base);
-
- const char kFunctionName[] = "NtClose";
-
- void* target = ::GetProcAddress(ntdll_base, kFunctionName);
- ASSERT_TRUE(NULL != target);
-
- BYTE service[50];
- memcpy(service, target, sizeof(service));
- static_cast<WinXpResolverTest*>(resolver)->set_target(service);
-
- // Any pointer will do as an interception_entry_point
- void* function_entry = resolver;
- size_t thunk_size = resolver->GetThunkSize();
- scoped_ptr<char[]> thunk(new char[thunk_size]);
- size_t used;
-
- NTSTATUS ret = STATUS_UNSUCCESSFUL;
-
- // First try patching without having allowed local patches.
- ret = resolver->Setup(ntdll_base, NULL, kFunctionName, NULL,
- function_entry, thunk.get(), thunk_size,
- &used);
- EXPECT_FALSE(NT_SUCCESS(ret));
-
- // Now allow local patches and check that things work.
- resolver->AllowLocalPatches();
- ret = resolver->Setup(ntdll_base, NULL, kFunctionName, NULL,
- function_entry, thunk.get(), thunk_size,
- &used);
- EXPECT_EQ(STATUS_SUCCESS, ret);
-}
-
-} // namespace
diff --git a/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_client.cc b/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_client.cc
deleted file mode 100644
index eac13937c..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_client.cc
+++ /dev/null
@@ -1,153 +0,0 @@
-// 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 <stddef.h>
-#include <string.h>
-
-#include "base/logging.h"
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/crosscall_params.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-
-namespace sandbox {
-
-// Get the base of the data buffer of the channel; this is where the input
-// parameters get serialized. Since they get serialized directly into the
-// channel we avoid one copy.
-void* SharedMemIPCClient::GetBuffer() {
- bool failure = false;
- size_t ix = LockFreeChannel(&failure);
- if (failure) {
- return NULL;
- }
- return reinterpret_cast<char*>(control_) +
- control_->channels[ix].channel_base;
-}
-
-// If we need to cancel an IPC before issuing DoCall
-// our client should call FreeBuffer with the same pointer
-// returned by GetBuffer.
-void SharedMemIPCClient::FreeBuffer(void* buffer) {
- size_t num = ChannelIndexFromBuffer(buffer);
- ChannelControl* channel = control_->channels;
- LONG result = ::InterlockedExchange(&channel[num].state, kFreeChannel);
- DCHECK_NE(kFreeChannel, static_cast<ChannelState>(result));
-}
-
-// The constructor simply casts the shared memory to the internal
-// structures. This is a cheap step that is why this IPC object can
-// and should be constructed per call.
-SharedMemIPCClient::SharedMemIPCClient(void* shared_mem)
- : control_(reinterpret_cast<IPCControl*>(shared_mem)) {
- first_base_ = reinterpret_cast<char*>(shared_mem) +
- control_->channels[0].channel_base;
- // There must be at least one channel.
- DCHECK(0 != control_->channels_count);
-}
-
-// Do the IPC. At this point the channel should have already been
-// filled with the serialized input parameters.
-// We follow the pattern explained in the header file.
-ResultCode SharedMemIPCClient::DoCall(CrossCallParams* params,
- CrossCallReturn* answer) {
- if (!control_->server_alive)
- return SBOX_ERROR_CHANNEL_ERROR;
-
- size_t num = ChannelIndexFromBuffer(params->GetBuffer());
- ChannelControl* channel = control_->channels;
- // Note that the IPC tag goes outside the buffer as well inside
- // the buffer. This should enable the server to prioritize based on
- // IPC tags without having to de-serialize the entire message.
- channel[num].ipc_tag = params->GetTag();
-
- // Wait for the server to service this IPC call. After kIPCWaitTimeOut1
- // we check if the server_alive mutex was abandoned which will indicate
- // that the server has died.
-
- // While the atomic signaling and waiting is not a requirement, it
- // is nice because we save a trip to kernel.
- DWORD wait = ::SignalObjectAndWait(channel[num].ping_event,
- channel[num].pong_event,
- kIPCWaitTimeOut1, FALSE);
- if (WAIT_TIMEOUT == wait) {
- // The server is taking too long. Enter a loop were we check if the
- // server_alive mutex has been abandoned which would signal a server crash
- // or else we keep waiting for a response.
- while (true) {
- wait = ::WaitForSingleObject(control_->server_alive, 0);
- if (WAIT_TIMEOUT == wait) {
- // Server seems still alive. We already signaled so here we just wait.
- wait = ::WaitForSingleObject(channel[num].pong_event, kIPCWaitTimeOut1);
- if (WAIT_OBJECT_0 == wait) {
- // The server took a long time but responded.
- break;
- } else if (WAIT_TIMEOUT == wait) {
- continue;
- } else {
- return SBOX_ERROR_CHANNEL_ERROR;
- }
- } else {
- // The server has crashed and windows has signaled the mutex as
- // abandoned.
- ::InterlockedExchange(&channel[num].state, kAbandonedChannel);
- control_->server_alive = 0;
- return SBOX_ERROR_CHANNEL_ERROR;
- }
- }
- } else if (WAIT_OBJECT_0 != wait) {
- // Probably the server crashed before the kIPCWaitTimeOut1 occurred.
- return SBOX_ERROR_CHANNEL_ERROR;
- }
-
- // The server has returned an answer, copy it and free the channel.
- memcpy(answer, params->GetCallReturn(), sizeof(CrossCallReturn));
-
- // Return the IPC state It can indicate that while the IPC has
- // completed some error in the Broker has caused to not return valid
- // results.
- return answer->call_outcome;
-}
-
-// Locking a channel is a simple as looping over all the channels
-// looking for one that is has state = kFreeChannel and atomically
-// swapping it to kBusyChannel.
-// If there is no free channel, then we must back off so some other
-// thread makes progress and frees a channel. To back off we sleep.
-size_t SharedMemIPCClient::LockFreeChannel(bool* severe_failure) {
- if (0 == control_->channels_count) {
- *severe_failure = true;
- return 0;
- }
- ChannelControl* channel = control_->channels;
- do {
- for (size_t ix = 0; ix != control_->channels_count; ++ix) {
- if (kFreeChannel == ::InterlockedCompareExchange(&channel[ix].state,
- kBusyChannel,
- kFreeChannel)) {
- *severe_failure = false;
- return ix;
- }
- }
- // We did not find any available channel, maybe the server is dead.
- DWORD wait = ::WaitForSingleObject(control_->server_alive,
- kIPCWaitTimeOut2);
- if (WAIT_TIMEOUT != wait) {
- // The server is dead and we outlive it enough to get in trouble.
- *severe_failure = true;
- return 0;
- }
- }
- while (true);
-}
-
-// Find out which channel we are from the pointer returned by GetBuffer.
-size_t SharedMemIPCClient::ChannelIndexFromBuffer(const void* buffer) {
- ptrdiff_t d = reinterpret_cast<const char*>(buffer) - first_base_;
- size_t num = d/kIPCChannelSize;
- DCHECK_LT(num, control_->channels_count);
- return (num);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_client.h b/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_client.h
deleted file mode 100644
index 67fd06359..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_client.h
+++ /dev/null
@@ -1,139 +0,0 @@
-// 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 SANDBOX_SRC_SHAREDMEM_IPC_CLIENT_H__
-#define SANDBOX_SRC_SHAREDMEM_IPC_CLIENT_H__
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "sandbox/win/src/crosscall_params.h"
-#include "sandbox/win/src/sandbox.h"
-
-// IPC transport implementation that uses shared memory.
-// This is the client side
-//
-// The shared memory is divided on blocks called channels, and potentially
-// it can perform as many concurrent IPC calls as channels. The IPC over
-// each channel is strictly synchronous for the client.
-//
-// Each channel as a channel control section associated with. Each control
-// section has two kernel events (known as ping and pong) and a integer
-// variable that maintains a state
-//
-// this is the state diagram of a channel:
-//
-// locked in service
-// kFreeChannel---------->BusyChannel-------------->kAckChannel
-// ^ |
-// |_________________________________________________|
-// answer ready
-//
-// The protocol is as follows:
-// 1) client finds a free channel: state = kFreeChannel
-// 2) does an atomic compare-and-swap, now state = BusyChannel
-// 3) client writes the data into the channel buffer
-// 4) client signals the ping event and waits (blocks) on the pong event
-// 5) eventually the server signals the pong event
-// 6) the client awakes and reads the answer from the same channel
-// 7) the client updates its InOut parameters with the new data from the
-// shared memory section.
-// 8) the client atomically sets the state = kFreeChannel
-//
-// In the shared memory the layout is as follows:
-//
-// [ channel count ]
-// [ channel control 0]
-// [ channel control 1]
-// [ channel control N]
-// [ channel buffer 0 ] 1024 bytes
-// [ channel buffer 1 ] 1024 bytes
-// [ channel buffer N ] 1024 bytes
-//
-// By default each channel buffer is 1024 bytes
-namespace sandbox {
-
-// the possible channel states as described above
-enum ChannelState {
- // channel is free
- kFreeChannel = 1,
- // IPC in progress client side
- kBusyChannel,
- // IPC in progress server side
- kAckChannel,
- // not used right now
- kReadyChannel,
- // IPC abandoned by client side
- kAbandonedChannel
-};
-
-// The next two constants control the time outs for the IPC.
-const DWORD kIPCWaitTimeOut1 = 1000; // Milliseconds.
-const DWORD kIPCWaitTimeOut2 = 50; // Milliseconds.
-
-// the channel control structure
-struct ChannelControl {
- // points to be beginning of the channel buffer, where data goes
- size_t channel_base;
- // maintains the state from the ChannelState enumeration
- volatile LONG state;
- // the ping event is signaled by the client when the IPC data is ready on
- // the buffer
- HANDLE ping_event;
- // the client waits on the pong event for the IPC answer back
- HANDLE pong_event;
- // the IPC unique identifier
- uint32_t ipc_tag;
-};
-
-struct IPCControl {
- // total number of channels available, some might be busy at a given time
- size_t channels_count;
- // handle to a shared mutex to detect when the server is dead
- HANDLE server_alive;
- // array of channel control structures
- ChannelControl channels[1];
-};
-
-// the actual shared memory IPC implementation class. This object is designed
-// to be lightweight so it can be constructed on-site (at the calling place)
-// wherever an IPC call is needed.
-class SharedMemIPCClient {
- public:
- // Creates the IPC client.
- // as parameter it takes the base address of the shared memory
- explicit SharedMemIPCClient(void* shared_mem);
-
- // locks a free channel and returns the channel buffer memory base. This call
- // blocks until there is a free channel
- void* GetBuffer();
-
- // releases the lock on the channel, for other to use. call this if you have
- // called GetBuffer and you want to abort but have not called yet DoCall()
- void FreeBuffer(void* buffer);
-
- // Performs the actual IPC call.
- // params: The blob of packed input parameters.
- // answer: upon IPC completion, it contains the server answer to the IPC.
- // If the return value is not SBOX_ERROR_CHANNEL_ERROR, the caller has to free
- // the channel.
- // returns ALL_OK if the IPC mechanism successfully delivered. You still need
- // to check on the answer structure to see the actual IPC result.
- ResultCode DoCall(CrossCallParams* params, CrossCallReturn* answer);
-
- private:
- // Returns the index of the first free channel. It sets 'severe_failure'
- // to true if there is an unrecoverable error that does not allow to
- // find a channel.
- size_t LockFreeChannel(bool* severe_failure);
- // Return the channel index given the address of the buffer.
- size_t ChannelIndexFromBuffer(const void* buffer);
- IPCControl* control_;
- // point to the first channel base
- char* first_base_;
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SHAREDMEM_IPC_CLIENT_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_server.cc b/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_server.cc
deleted file mode 100644
index cf2d800e5..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_server.cc
+++ /dev/null
@@ -1,430 +0,0 @@
-// 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.
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/callback.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/stl_util.h"
-#include "sandbox/win/src/crosscall_params.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/sharedmem_ipc_server.h"
-
-namespace {
-// This handle must not be closed.
-volatile HANDLE g_alive_mutex = NULL;
-}
-
-namespace sandbox {
-
-SharedMemIPCServer::ServerControl::ServerControl() {
-}
-
-SharedMemIPCServer::ServerControl::~ServerControl() {
-}
-
-SharedMemIPCServer::SharedMemIPCServer(HANDLE target_process,
- DWORD target_process_id,
- ThreadProvider* thread_provider,
- Dispatcher* dispatcher)
- : client_control_(NULL),
- thread_provider_(thread_provider),
- target_process_(target_process),
- target_process_id_(target_process_id),
- call_dispatcher_(dispatcher) {
- // We create a initially owned mutex. If the server dies unexpectedly,
- // the thread that owns it will fail to release the lock and windows will
- // report to the target (when it tries to acquire it) that the wait was
- // abandoned. Note: We purposely leak the local handle because we want it to
- // be closed by Windows itself so it is properly marked as abandoned if the
- // server dies.
- if (!g_alive_mutex) {
- HANDLE mutex = ::CreateMutexW(NULL, TRUE, NULL);
- if (::InterlockedCompareExchangePointer(&g_alive_mutex, mutex, NULL)) {
- // We lost the race to create the mutex.
- ::CloseHandle(mutex);
- }
- }
-}
-
-SharedMemIPCServer::~SharedMemIPCServer() {
- // Free the wait handles associated with the thread pool.
- if (!thread_provider_->UnRegisterWaits(this)) {
- // Better to leak than to crash.
- return;
- }
- STLDeleteElements(&server_contexts_);
-
- if (client_control_)
- ::UnmapViewOfFile(client_control_);
-}
-
-bool SharedMemIPCServer::Init(void* shared_mem,
- uint32_t shared_size,
- uint32_t channel_size) {
- // The shared memory needs to be at least as big as a channel.
- if (shared_size < channel_size) {
- return false;
- }
- // The channel size should be aligned.
- if (0 != (channel_size % 32)) {
- return false;
- }
-
- // Calculate how many channels we can fit in the shared memory.
- shared_size -= offsetof(IPCControl, channels);
- size_t channel_count = shared_size / (sizeof(ChannelControl) + channel_size);
-
- // If we cannot fit even one channel we bail out.
- if (0 == channel_count) {
- return false;
- }
- // Calculate the start of the first channel.
- size_t base_start = (sizeof(ChannelControl)* channel_count) +
- offsetof(IPCControl, channels);
-
- client_control_ = reinterpret_cast<IPCControl*>(shared_mem);
- client_control_->channels_count = 0;
-
- // This is the initialization that we do per-channel. Basically:
- // 1) make two events (ping & pong)
- // 2) create handles to the events for the client and the server.
- // 3) initialize the channel (client_context) with the state.
- // 4) initialize the server side of the channel (service_context).
- // 5) call the thread provider RegisterWait to register the ping events.
- for (size_t ix = 0; ix != channel_count; ++ix) {
- ChannelControl* client_context = &client_control_->channels[ix];
- ServerControl* service_context = new ServerControl;
- server_contexts_.push_back(service_context);
-
- if (!MakeEvents(&service_context->ping_event,
- &service_context->pong_event,
- &client_context->ping_event,
- &client_context->pong_event)) {
- return false;
- }
-
- client_context->channel_base = base_start;
- client_context->state = kFreeChannel;
-
- // Note that some of these values are available as members of this object
- // but we put them again into the service_context because we will be called
- // on a static method (ThreadPingEventReady). In particular, target_process_
- // is a raw handle that is not owned by this object (it's owned by the
- // owner of this object), and we are storing it in multiple places.
- service_context->shared_base = reinterpret_cast<char*>(shared_mem);
- service_context->channel_size = channel_size;
- service_context->channel = client_context;
- service_context->channel_buffer = service_context->shared_base +
- client_context->channel_base;
- service_context->dispatcher = call_dispatcher_;
- service_context->target_info.process = target_process_;
- service_context->target_info.process_id = target_process_id_;
- // Advance to the next channel.
- base_start += channel_size;
- // Register the ping event with the threadpool.
- thread_provider_->RegisterWait(this, service_context->ping_event.Get(),
- ThreadPingEventReady, service_context);
- }
- if (!::DuplicateHandle(::GetCurrentProcess(), g_alive_mutex,
- target_process_, &client_control_->server_alive,
- SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, 0)) {
- return false;
- }
- // This last setting indicates to the client all is setup.
- client_control_->channels_count = channel_count;
- return true;
-}
-
-// Releases memory allocated for IPC arguments, if needed.
-void ReleaseArgs(const IPCParams* ipc_params, void* args[kMaxIpcParams]) {
- for (size_t i = 0; i < kMaxIpcParams; i++) {
- switch (ipc_params->args[i]) {
- case WCHAR_TYPE: {
- delete reinterpret_cast<base::string16*>(args[i]);
- args[i] = NULL;
- break;
- }
- case INOUTPTR_TYPE: {
- delete reinterpret_cast<CountedBuffer*>(args[i]);
- args[i] = NULL;
- break;
- }
- default: break;
- }
- }
-}
-
-// Fills up the list of arguments (args and ipc_params) for an IPC call.
-bool GetArgs(CrossCallParamsEx* params, IPCParams* ipc_params,
- void* args[kMaxIpcParams]) {
- if (kMaxIpcParams < params->GetParamsCount())
- return false;
-
- for (uint32_t i = 0; i < params->GetParamsCount(); i++) {
- uint32_t size;
- ArgType type;
- args[i] = params->GetRawParameter(i, &size, &type);
- if (args[i]) {
- ipc_params->args[i] = type;
- switch (type) {
- case WCHAR_TYPE: {
- scoped_ptr<base::string16> data(new base::string16);
- if (!params->GetParameterStr(i, data.get())) {
- args[i] = 0;
- ReleaseArgs(ipc_params, args);
- return false;
- }
- args[i] = data.release();
- break;
- }
- case UINT32_TYPE: {
- uint32_t data;
- if (!params->GetParameter32(i, &data)) {
- ReleaseArgs(ipc_params, args);
- return false;
- }
- IPCInt ipc_int(data);
- args[i] = ipc_int.AsVoidPtr();
- break;
- }
- case VOIDPTR_TYPE : {
- void* data;
- if (!params->GetParameterVoidPtr(i, &data)) {
- ReleaseArgs(ipc_params, args);
- return false;
- }
- args[i] = data;
- break;
- }
- case INOUTPTR_TYPE: {
- if (!args[i]) {
- ReleaseArgs(ipc_params, args);
- return false;
- }
- CountedBuffer* buffer = new CountedBuffer(args[i] , size);
- args[i] = buffer;
- break;
- }
- default: break;
- }
- }
- }
- return true;
-}
-
-bool SharedMemIPCServer::InvokeCallback(const ServerControl* service_context,
- void* ipc_buffer,
- CrossCallReturn* call_result) {
- // Set the default error code;
- SetCallError(SBOX_ERROR_INVALID_IPC, call_result);
- uint32_t output_size = 0;
- // Parse, verify and copy the message. The handler operates on a copy
- // of the message so the client cannot play dirty tricks by changing the
- // data in the channel while the IPC is being processed.
- scoped_ptr<CrossCallParamsEx> params(
- CrossCallParamsEx::CreateFromBuffer(ipc_buffer,
- service_context->channel_size,
- &output_size));
- if (!params.get())
- return false;
-
- uint32_t tag = params->GetTag();
- static_assert(0 == INVALID_TYPE, "incorrect type enum");
- IPCParams ipc_params = {0};
- ipc_params.ipc_tag = tag;
-
- void* args[kMaxIpcParams];
- if (!GetArgs(params.get(), &ipc_params, args))
- return false;
-
- IPCInfo ipc_info = {0};
- ipc_info.ipc_tag = tag;
- ipc_info.client_info = &service_context->target_info;
- Dispatcher* dispatcher = service_context->dispatcher;
- DCHECK(dispatcher);
- bool error = true;
- Dispatcher* handler = NULL;
-
- Dispatcher::CallbackGeneric callback_generic;
- handler = dispatcher->OnMessageReady(&ipc_params, &callback_generic);
- if (handler) {
- switch (params->GetParamsCount()) {
- case 0: {
- // Ask the IPC dispatcher if she can service this IPC.
- Dispatcher::Callback0 callback =
- reinterpret_cast<Dispatcher::Callback0>(callback_generic);
- if (!(handler->*callback)(&ipc_info))
- break;
- error = false;
- break;
- }
- case 1: {
- Dispatcher::Callback1 callback =
- reinterpret_cast<Dispatcher::Callback1>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0]))
- break;
- error = false;
- break;
- }
- case 2: {
- Dispatcher::Callback2 callback =
- reinterpret_cast<Dispatcher::Callback2>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0], args[1]))
- break;
- error = false;
- break;
- }
- case 3: {
- Dispatcher::Callback3 callback =
- reinterpret_cast<Dispatcher::Callback3>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2]))
- break;
- error = false;
- break;
- }
- case 4: {
- Dispatcher::Callback4 callback =
- reinterpret_cast<Dispatcher::Callback4>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2],
- args[3]))
- break;
- error = false;
- break;
- }
- case 5: {
- Dispatcher::Callback5 callback =
- reinterpret_cast<Dispatcher::Callback5>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
- args[4]))
- break;
- error = false;
- break;
- }
- case 6: {
- Dispatcher::Callback6 callback =
- reinterpret_cast<Dispatcher::Callback6>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
- args[4], args[5]))
- break;
- error = false;
- break;
- }
- case 7: {
- Dispatcher::Callback7 callback =
- reinterpret_cast<Dispatcher::Callback7>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
- args[4], args[5], args[6]))
- break;
- error = false;
- break;
- }
- case 8: {
- Dispatcher::Callback8 callback =
- reinterpret_cast<Dispatcher::Callback8>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
- args[4], args[5], args[6], args[7]))
- break;
- error = false;
- break;
- }
- case 9: {
- Dispatcher::Callback9 callback =
- reinterpret_cast<Dispatcher::Callback9>(callback_generic);
- if (!(handler->*callback)(&ipc_info, args[0], args[1], args[2], args[3],
- args[4], args[5], args[6], args[7], args[8]))
- break;
- error = false;
- break;
- }
- default: {
- NOTREACHED();
- break;
- }
- }
- }
-
- if (error) {
- if (handler)
- SetCallError(SBOX_ERROR_FAILED_IPC, call_result);
- } else {
- memcpy(call_result, &ipc_info.return_info, sizeof(*call_result));
- SetCallSuccess(call_result);
- if (params->IsInOut()) {
- // Maybe the params got changed by the broker. We need to upadte the
- // memory section.
- memcpy(ipc_buffer, params.get(), output_size);
- }
- }
-
- ReleaseArgs(&ipc_params, args);
-
- return !error;
-}
-
-// This function gets called by a thread from the thread pool when a
-// ping event fires. The context is the same as passed in the RegisterWait()
-// call above.
-void __stdcall SharedMemIPCServer::ThreadPingEventReady(void* context,
- unsigned char) {
- if (NULL == context) {
- DCHECK(false);
- return;
- }
- ServerControl* service_context = reinterpret_cast<ServerControl*>(context);
- // Since the event fired, the channel *must* be busy. Change to kAckChannel
- // while we service it.
- LONG last_state =
- ::InterlockedCompareExchange(&service_context->channel->state,
- kAckChannel, kBusyChannel);
- if (kBusyChannel != last_state) {
- DCHECK(false);
- return;
- }
-
- // Prepare the result structure. At this point we will return some result
- // even if the IPC is invalid, malformed or has no handler.
- CrossCallReturn call_result = {0};
- void* buffer = service_context->channel_buffer;
-
- InvokeCallback(service_context, buffer, &call_result);
-
- // Copy the answer back into the channel and signal the pong event. This
- // should wake up the client so he can finish the the ipc cycle.
- CrossCallParams* call_params = reinterpret_cast<CrossCallParams*>(buffer);
- memcpy(call_params->GetCallReturn(), &call_result, sizeof(call_result));
- ::InterlockedExchange(&service_context->channel->state, kAckChannel);
- ::SetEvent(service_context->pong_event.Get());
-}
-
-bool SharedMemIPCServer::MakeEvents(base::win::ScopedHandle* server_ping,
- base::win::ScopedHandle* server_pong,
- HANDLE* client_ping, HANDLE* client_pong) {
- // Note that the IPC client has no right to delete the events. That would
- // cause problems. The server *owns* the events.
- const DWORD kDesiredAccess = SYNCHRONIZE | EVENT_MODIFY_STATE;
-
- // The events are auto reset, and start not signaled.
- server_ping->Set(::CreateEventW(NULL, FALSE, FALSE, NULL));
- if (!::DuplicateHandle(::GetCurrentProcess(), server_ping->Get(),
- target_process_, client_ping, kDesiredAccess, FALSE,
- 0)) {
- return false;
- }
-
- server_pong->Set(::CreateEventW(NULL, FALSE, FALSE, NULL));
- if (!::DuplicateHandle(::GetCurrentProcess(), server_pong->Get(),
- target_process_, client_pong, kDesiredAccess, FALSE,
- 0)) {
- return false;
- }
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_server.h b/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_server.h
deleted file mode 100644
index 5afca1d6c..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sharedmem_ipc_server.h
+++ /dev/null
@@ -1,134 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_SHAREDMEM_IPC_SERVER_H_
-#define SANDBOX_SRC_SHAREDMEM_IPC_SERVER_H_
-
-#include <stdint.h>
-
-#include <list>
-
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/crosscall_params.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-
-// IPC transport implementation that uses shared memory.
-// This is the server side
-//
-// The server side has knowledge about the layout of the shared memory
-// and the state transitions. Both are explained in sharedmem_ipc_client.h
-//
-// As opposed to SharedMemIPClient, the Server object should be one for the
-// entire lifetime of the target process. The server is in charge of creating
-// the events (ping, pong) both for the client and for the target that are used
-// to signal the IPC and also in charge of setting the initial state of the
-// channels.
-//
-// When an IPC is ready, the server relies on being called by on the
-// ThreadPingEventReady callback. The IPC server then retrieves the buffer,
-// marshals it into a CrossCallParam object and calls the Dispatcher, who is in
-// charge of fulfilling the IPC request.
-namespace sandbox {
-
-// the shared memory implementation of the IPC server. There should be one
-// of these objects per target (IPC client) process
-class SharedMemIPCServer {
- public:
- // Creates the IPC server.
- // target_process: handle to the target process. It must be suspended. It is
- // unfortunate to receive a raw handle (and store it inside this object) as
- // that dilutes ownership of the process, but in practice a SharedMemIPCServer
- // is owned by TargetProcess, which calls this method, and owns the handle, so
- // everything is safe. If that changes, we should break this dependency and
- // duplicate the handle instead.
- // target_process_id: process id of the target process.
- // thread_provider: a thread provider object.
- // dispatcher: an object that can service IPC calls.
- SharedMemIPCServer(HANDLE target_process, DWORD target_process_id,
- ThreadProvider* thread_provider, Dispatcher* dispatcher);
-
- ~SharedMemIPCServer();
-
- // Initializes the server structures, shared memory structures and
- // creates the kernels events used to signal the IPC.
- bool Init(void* shared_mem, uint32_t shared_size, uint32_t channel_size);
-
- private:
- // Allow tests to be marked DISABLED_. Note that FLAKY_ and FAILS_ prefixes
- // do not work with sandbox tests.
- FRIEND_TEST_ALL_PREFIXES(IPCTest, SharedMemServerTests);
- // When an event fires (IPC request). A thread from the ThreadProvider
- // will call this function. The context parameter should be the same as
- // provided when ThreadProvider::RegisterWait was called.
- static void __stdcall ThreadPingEventReady(void* context,
- unsigned char);
-
- // Makes the client and server events. This function is called once
- // per channel.
- bool MakeEvents(base::win::ScopedHandle* server_ping,
- base::win::ScopedHandle* server_pong,
- HANDLE* client_ping, HANDLE* client_pong);
-
- // A copy this structure is maintained per channel.
- // Note that a lot of the fields are just the same of what we have in the IPC
- // object itself. It is better to have the copies since we can dispatch in the
- // static method without worrying about converting back to a member function
- // call or about threading issues.
- struct ServerControl {
- ServerControl();
- ~ServerControl();
-
- // This channel server ping event.
- base::win::ScopedHandle ping_event;
- // This channel server pong event.
- base::win::ScopedHandle pong_event;
- // The size of this channel.
- uint32_t channel_size;
- // The pointer to the actual channel data.
- char* channel_buffer;
- // The pointer to the base of the shared memory.
- char* shared_base;
- // A pointer to this channel's client-side control structure this structure
- // lives in the shared memory.
- ChannelControl* channel;
- // the IPC dispatcher associated with this channel.
- Dispatcher* dispatcher;
- // The target process information associated with this channel.
- ClientInfo target_info;
- };
-
- // Looks for the appropriate handler for this IPC and invokes it.
- static bool InvokeCallback(const ServerControl* service_context,
- void* ipc_buffer, CrossCallReturn* call_result);
-
- // Points to the shared memory channel control which lives at
- // the start of the shared section.
- IPCControl* client_control_;
-
- // Keeps track of the server side objects that are used to answer an IPC.
- typedef std::list<ServerControl*> ServerContexts;
- ServerContexts server_contexts_;
-
- // The thread provider provides the threads that call back into this object
- // when the IPC events fire.
- ThreadProvider* thread_provider_;
-
- // The IPC object is associated with a target process.
- HANDLE target_process_;
-
- // The target process id associated with the IPC object.
- DWORD target_process_id_;
-
- // The dispatcher handles 'ready' IPC calls.
- Dispatcher* call_dispatcher_;
-
- DISALLOW_COPY_AND_ASSIGN(SharedMemIPCServer);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SHAREDMEM_IPC_SERVER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/sid.cc b/security/sandbox/chromium/sandbox/win/src/sid.cc
deleted file mode 100644
index 19c645bf6..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sid.cc
+++ /dev/null
@@ -1,26 +0,0 @@
-// 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 "sandbox/win/src/sid.h"
-
-#include "base/logging.h"
-
-namespace sandbox {
-
-Sid::Sid(const SID *sid) {
- ::CopySid(SECURITY_MAX_SID_SIZE, sid_, const_cast<SID*>(sid));
-};
-
-Sid::Sid(WELL_KNOWN_SID_TYPE type) {
- DWORD size_sid = SECURITY_MAX_SID_SIZE;
- BOOL result = ::CreateWellKnownSid(type, NULL, sid_, &size_sid);
- DCHECK(result);
- (void)result;
-}
-
-const SID *Sid::GetPSID() const {
- return reinterpret_cast<SID*>(const_cast<BYTE*>(sid_));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sid.h b/security/sandbox/chromium/sandbox/win/src/sid.h
deleted file mode 100644
index 4656859be..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sid.h
+++ /dev/null
@@ -1,29 +0,0 @@
-// 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 SANDBOX_SRC_SID_H_
-#define SANDBOX_SRC_SID_H_
-
-#include <windows.h>
-
-namespace sandbox {
-
-// This class is used to hold and generate SIDS.
-class Sid {
- public:
- // Constructors initializing the object with the SID passed.
- // This is a converting constructor. It is not explicit.
- Sid(const SID *sid);
- Sid(WELL_KNOWN_SID_TYPE type);
-
- // Returns sid_.
- const SID *GetPSID() const;
-
- private:
- BYTE sid_[SECURITY_MAX_SID_SIZE];
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SID_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/sid_unittest.cc b/security/sandbox/chromium/sandbox/win/src/sid_unittest.cc
deleted file mode 100644
index 76d61e82f..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sid_unittest.cc
+++ /dev/null
@@ -1,71 +0,0 @@
-// 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 contains unit tests for the sid class.
-
-#define _ATL_NO_EXCEPTIONS
-#include <atlbase.h>
-#include <atlsecurity.h>
-
-#include "sandbox/win/src/sid.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-// Calls ::EqualSid. This function exists only to simplify the calls to
-// ::EqualSid by removing the need to cast the input params.
-BOOL EqualSid(const SID *sid1, const SID *sid2) {
- return ::EqualSid(const_cast<SID*>(sid1), const_cast<SID*>(sid2));
-}
-
-// Tests the creation if a Sid
-TEST(SidTest, Constructors) {
- ATL::CSid sid_world = ATL::Sids::World();
- SID *sid_world_pointer = const_cast<SID*>(sid_world.GetPSID());
-
- // Check the SID* constructor
- Sid sid_sid_star(sid_world_pointer);
- ASSERT_TRUE(EqualSid(sid_world_pointer, sid_sid_star.GetPSID()));
-
- // Check the copy constructor
- Sid sid_copy(sid_sid_star);
- ASSERT_TRUE(EqualSid(sid_world_pointer, sid_copy.GetPSID()));
-
- // Note that the WELL_KNOWN_SID_TYPE constructor is tested in the GetPSID
- // test.
-}
-
-// Tests the method GetPSID
-TEST(SidTest, GetPSID) {
- // Check for non-null result;
- ASSERT_NE(static_cast<SID*>(NULL), Sid(::WinLocalSid).GetPSID());
- ASSERT_NE(static_cast<SID*>(NULL), Sid(::WinCreatorOwnerSid).GetPSID());
- ASSERT_NE(static_cast<SID*>(NULL), Sid(::WinBatchSid).GetPSID());
-
- ASSERT_TRUE(EqualSid(Sid(::WinNullSid).GetPSID(),
- ATL::Sids::Null().GetPSID()));
-
- ASSERT_TRUE(EqualSid(Sid(::WinWorldSid).GetPSID(),
- ATL::Sids::World().GetPSID()));
-
- ASSERT_TRUE(EqualSid(Sid(::WinDialupSid).GetPSID(),
- ATL::Sids::Dialup().GetPSID()));
-
- ASSERT_TRUE(EqualSid(Sid(::WinNetworkSid).GetPSID(),
- ATL::Sids::Network().GetPSID()));
-
- ASSERT_TRUE(EqualSid(Sid(::WinBuiltinAdministratorsSid).GetPSID(),
- ATL::Sids::Admins().GetPSID()));
-
- ASSERT_TRUE(EqualSid(Sid(::WinBuiltinUsersSid).GetPSID(),
- ATL::Sids::Users().GetPSID()));
-
- ASSERT_TRUE(EqualSid(Sid(::WinBuiltinGuestsSid).GetPSID(),
- ATL::Sids::Guests().GetPSID()));
-
- ASSERT_TRUE(EqualSid(Sid(::WinProxySid).GetPSID(),
- ATL::Sids::Proxy().GetPSID()));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep/ia32_modrm_map.cpp b/security/sandbox/chromium/sandbox/win/src/sidestep/ia32_modrm_map.cpp
deleted file mode 100644
index 89bc1895e..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep/ia32_modrm_map.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-// 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.
-
-// Table of relevant information about how to decode the ModR/M byte.
-// Based on information in the IA-32 Intel Architecture
-// Software Developer's Manual Volume 2: Instruction Set Reference.
-
-#include "sandbox/win/src/sidestep/mini_disassembler.h"
-#include "sandbox/win/src/sidestep/mini_disassembler_types.h"
-
-namespace sidestep {
-
-const ModrmEntry MiniDisassembler::s_ia16_modrm_map_[] = {
-// mod == 00
- /* r/m == 000 */ { false, false, OS_ZERO },
- /* r/m == 001 */ { false, false, OS_ZERO },
- /* r/m == 010 */ { false, false, OS_ZERO },
- /* r/m == 011 */ { false, false, OS_ZERO },
- /* r/m == 100 */ { false, false, OS_ZERO },
- /* r/m == 101 */ { false, false, OS_ZERO },
- /* r/m == 110 */ { true, false, OS_WORD },
- /* r/m == 111 */ { false, false, OS_ZERO },
-// mod == 01
- /* r/m == 000 */ { true, false, OS_BYTE },
- /* r/m == 001 */ { true, false, OS_BYTE },
- /* r/m == 010 */ { true, false, OS_BYTE },
- /* r/m == 011 */ { true, false, OS_BYTE },
- /* r/m == 100 */ { true, false, OS_BYTE },
- /* r/m == 101 */ { true, false, OS_BYTE },
- /* r/m == 110 */ { true, false, OS_BYTE },
- /* r/m == 111 */ { true, false, OS_BYTE },
-// mod == 10
- /* r/m == 000 */ { true, false, OS_WORD },
- /* r/m == 001 */ { true, false, OS_WORD },
- /* r/m == 010 */ { true, false, OS_WORD },
- /* r/m == 011 */ { true, false, OS_WORD },
- /* r/m == 100 */ { true, false, OS_WORD },
- /* r/m == 101 */ { true, false, OS_WORD },
- /* r/m == 110 */ { true, false, OS_WORD },
- /* r/m == 111 */ { true, false, OS_WORD },
-// mod == 11
- /* r/m == 000 */ { false, false, OS_ZERO },
- /* r/m == 001 */ { false, false, OS_ZERO },
- /* r/m == 010 */ { false, false, OS_ZERO },
- /* r/m == 011 */ { false, false, OS_ZERO },
- /* r/m == 100 */ { false, false, OS_ZERO },
- /* r/m == 101 */ { false, false, OS_ZERO },
- /* r/m == 110 */ { false, false, OS_ZERO },
- /* r/m == 111 */ { false, false, OS_ZERO }
-};
-
-const ModrmEntry MiniDisassembler::s_ia32_modrm_map_[] = {
-// mod == 00
- /* r/m == 000 */ { false, false, OS_ZERO },
- /* r/m == 001 */ { false, false, OS_ZERO },
- /* r/m == 010 */ { false, false, OS_ZERO },
- /* r/m == 011 */ { false, false, OS_ZERO },
- /* r/m == 100 */ { false, true, OS_ZERO },
- /* r/m == 101 */ { true, false, OS_DOUBLE_WORD },
- /* r/m == 110 */ { false, false, OS_ZERO },
- /* r/m == 111 */ { false, false, OS_ZERO },
-// mod == 01
- /* r/m == 000 */ { true, false, OS_BYTE },
- /* r/m == 001 */ { true, false, OS_BYTE },
- /* r/m == 010 */ { true, false, OS_BYTE },
- /* r/m == 011 */ { true, false, OS_BYTE },
- /* r/m == 100 */ { true, true, OS_BYTE },
- /* r/m == 101 */ { true, false, OS_BYTE },
- /* r/m == 110 */ { true, false, OS_BYTE },
- /* r/m == 111 */ { true, false, OS_BYTE },
-// mod == 10
- /* r/m == 000 */ { true, false, OS_DOUBLE_WORD },
- /* r/m == 001 */ { true, false, OS_DOUBLE_WORD },
- /* r/m == 010 */ { true, false, OS_DOUBLE_WORD },
- /* r/m == 011 */ { true, false, OS_DOUBLE_WORD },
- /* r/m == 100 */ { true, true, OS_DOUBLE_WORD },
- /* r/m == 101 */ { true, false, OS_DOUBLE_WORD },
- /* r/m == 110 */ { true, false, OS_DOUBLE_WORD },
- /* r/m == 111 */ { true, false, OS_DOUBLE_WORD },
-// mod == 11
- /* r/m == 000 */ { false, false, OS_ZERO },
- /* r/m == 001 */ { false, false, OS_ZERO },
- /* r/m == 010 */ { false, false, OS_ZERO },
- /* r/m == 011 */ { false, false, OS_ZERO },
- /* r/m == 100 */ { false, false, OS_ZERO },
- /* r/m == 101 */ { false, false, OS_ZERO },
- /* r/m == 110 */ { false, false, OS_ZERO },
- /* r/m == 111 */ { false, false, OS_ZERO },
-};
-
-}; // namespace sidestep
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep/ia32_opcode_map.cpp b/security/sandbox/chromium/sandbox/win/src/sidestep/ia32_opcode_map.cpp
deleted file mode 100644
index b7d8a60bc..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep/ia32_opcode_map.cpp
+++ /dev/null
@@ -1,1159 +0,0 @@
-// 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.
-
-// Opcode decoding maps. Based on the IA-32 Intel Architecture
-// Software Developer's Manual Volume 2: Instruction Set Reference. Idea
-// for how to lay out the tables in memory taken from the implementation
-// in the Bastard disassembly environment.
-
-#include "sandbox/win/src/sidestep/mini_disassembler.h"
-
-namespace sidestep {
-
-/*
-* This is the first table to be searched; the first field of each
-* Opcode in the table is either 0 to indicate you're in the
-* right table, or an index to the correct table, in the global
-* map g_pentiumOpcodeMap
-*/
-const Opcode s_first_opcode_byte[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF */ { 1, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x10 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x11 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x12 */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x13 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x14 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x15 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x16 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x17 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x18 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x19 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1A */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1C */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1E */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1F */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x20 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x21 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x22 */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x23 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x24 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x25 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x26 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x27 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "daa", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x28 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x29 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2A */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2C */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2E */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2F */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "das", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x30 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x31 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x32 */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x33 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x34 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x35 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x36 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x37 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "aaa", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x38 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x39 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3A */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3C */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3E */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3F */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "aas", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x40 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x41 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x42 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x43 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x44 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x45 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x46 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x47 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x48 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x49 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4A */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4B */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4C */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4E */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4F */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x50 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x51 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x52 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x53 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x54 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x55 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x56 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x57 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x58 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x59 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5A */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5B */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5C */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5D */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5E */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5F */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x60 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "pushad", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x61 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "popad", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x62 */ { 0, IT_GENERIC, AM_G | OT_V, AM_M | OT_A, AM_NOT_USED, "bound", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x63 */ { 0, IT_GENERIC, AM_E | OT_W, AM_G | OT_W, AM_NOT_USED, "arpl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x64 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x65 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x66 */ { 0, IT_PREFIX_OPERAND, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x67 */ { 0, IT_PREFIX_ADDRESS, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x68 */ { 0, IT_GENERIC, AM_I | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x69 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_I | OT_V, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6A */ { 0, IT_GENERIC, AM_I | OT_B, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_I | OT_B, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6C */ { 0, IT_GENERIC, AM_Y | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "insb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6D */ { 0, IT_GENERIC, AM_Y | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "insd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6E */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_X | OT_B, AM_NOT_USED, "outsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6F */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_X | OT_V, AM_NOT_USED, "outsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x70 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x71 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jno", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x72 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x73 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jnc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x74 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x75 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x76 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jbe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x77 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "ja", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x78 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "js", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x79 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jns", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7A */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jpe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7B */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jpo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7C */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7D */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jge", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7E */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jle", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7F */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x80 */ { 2, IT_REFERENCE, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x81 */ { 3, IT_REFERENCE, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x82 */ { 4, IT_REFERENCE, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x83 */ { 5, IT_REFERENCE, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x84 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x85 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x86 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x87 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x88 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x89 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8A */ { 0, IT_GENERIC, AM_G | OT_B, AM_E | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8C */ { 0, IT_GENERIC, AM_E | OT_W, AM_S | OT_W, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8D */ { 0, IT_GENERIC, AM_G | OT_V, AM_M | OT_ADDRESS_MODE_M, AM_NOT_USED, "lea", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8E */ { 0, IT_GENERIC, AM_S | OT_W, AM_E | OT_W, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8F */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x90 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "nop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x91 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x92 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x93 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x94 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x95 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x96 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x97 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "xchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x98 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cwde", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x99 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cdq", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9A */ { 0, IT_JUMP, AM_A | OT_P, AM_NOT_USED, AM_NOT_USED, "callf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9B */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "wait", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9C */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "pushfd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9D */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "popfd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9E */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "sahf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9F */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "lahf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA0 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_O | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA1 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_O | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA2 */ { 0, IT_GENERIC, AM_O | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA3 */ { 0, IT_GENERIC, AM_O | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA4 */ { 0, IT_GENERIC, AM_X | OT_B, AM_Y | OT_B, AM_NOT_USED, "movsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA5 */ { 0, IT_GENERIC, AM_X | OT_V, AM_Y | OT_V, AM_NOT_USED, "movsd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA6 */ { 0, IT_GENERIC, AM_X | OT_B, AM_Y | OT_B, AM_NOT_USED, "cmpsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA7 */ { 0, IT_GENERIC, AM_X | OT_V, AM_Y | OT_V, AM_NOT_USED, "cmpsd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA8 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA9 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAA */ { 0, IT_GENERIC, AM_Y | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "stosb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAB */ { 0, IT_GENERIC, AM_Y | OT_V, AM_REGISTER | OT_V, AM_NOT_USED, "stosd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAC */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_X| OT_B, AM_NOT_USED, "lodsb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAD */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_X| OT_V, AM_NOT_USED, "lodsd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAE */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_Y | OT_B, AM_NOT_USED, "scasb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAF */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_Y | OT_V, AM_NOT_USED, "scasd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB0 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB1 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB2 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB3 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB4 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB5 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB6 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB7 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB8 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB9 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBA */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBB */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBC */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBD */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBE */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBF */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC0 */ { 6, IT_REFERENCE, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC1 */ { 7, IT_REFERENCE, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC2 */ { 0, IT_RETURN, AM_I | OT_W, AM_NOT_USED, AM_NOT_USED, "ret", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC3 */ { 0, IT_RETURN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "ret", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC4 */ { 0, IT_GENERIC, AM_G | OT_V, AM_M | OT_P, AM_NOT_USED, "les", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC5 */ { 0, IT_GENERIC, AM_G | OT_V, AM_M | OT_P, AM_NOT_USED, "lds", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC8 */ { 0, IT_GENERIC, AM_I | OT_W, AM_I | OT_B, AM_NOT_USED, "enter", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC9 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "leave", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCA */ { 0, IT_RETURN, AM_I | OT_W, AM_NOT_USED, AM_NOT_USED, "retf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCB */ { 0, IT_RETURN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "retf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCC */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "int3", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCD */ { 0, IT_GENERIC, AM_I | OT_B, AM_NOT_USED, AM_NOT_USED, "int", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCE */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "into", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCF */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "iret", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD0 */ { 8, IT_REFERENCE, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD1 */ { 9, IT_REFERENCE, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD2 */ { 10, IT_REFERENCE, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD3 */ { 11, IT_REFERENCE, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD4 */ { 0, IT_GENERIC, AM_I | OT_B, AM_NOT_USED, AM_NOT_USED, "aam", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD5 */ { 0, IT_GENERIC, AM_I | OT_B, AM_NOT_USED, AM_NOT_USED, "aad", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD6 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD7 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "xlat", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
-
- // The following 8 lines would be references to the FPU tables, but we currently
- // do not support the FPU instructions in this disassembler.
-
- /* 0xD8 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD9 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xDA */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xDB */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xDC */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xDD */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xDE */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xDF */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
-
-
- /* 0xE0 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "loopnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE1 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "loopz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE2 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "loop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE3 */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jcxz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE4 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "in", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE5 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_I | OT_B, AM_NOT_USED, "in", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE6 */ { 0, IT_GENERIC, AM_I | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "out", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE7 */ { 0, IT_GENERIC, AM_I | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "out", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE8 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "call", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE9 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xEA */ { 0, IT_JUMP, AM_A | OT_P, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xEB */ { 0, IT_JUMP, AM_J | OT_B, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xEC */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_REGISTER | OT_W, AM_NOT_USED, "in", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xED */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_REGISTER | OT_W, AM_NOT_USED, "in", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xEE */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_REGISTER | OT_B, AM_NOT_USED, "out", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xEF */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_REGISTER | OT_V, AM_NOT_USED, "out", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF0 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "lock:", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF2 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "repne:", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF3 */ { 0, IT_PREFIX, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rep:", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF4 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "hlt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF5 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cmc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF6 */ { 12, IT_REFERENCE, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF7 */ { 13, IT_REFERENCE, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF8 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "clc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF9 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "stc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xFA */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cli", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xFB */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "sti", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xFC */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cld", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xFD */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "std", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xFE */ { 14, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xFF */ { 15, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_0f[] = {
- /* 0x0 */ { 16, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 17, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_W, AM_NOT_USED, "lar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_W, AM_NOT_USED, "lsl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "clts", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "invd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "wbinvd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "ud2", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xE */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x10 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "movups", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "movsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "movss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "movupd" } },
- /* 0x11 */ { 0, IT_GENERIC, AM_W | OT_PS, AM_V | OT_PS, AM_NOT_USED, "movups", true,
- /* F2h */ { 0, IT_GENERIC, AM_W | OT_SD, AM_V | OT_SD, AM_NOT_USED, "movsd" },
- /* F3h */ { 0, IT_GENERIC, AM_W | OT_SS, AM_V | OT_SS, AM_NOT_USED, "movss" },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_PD, AM_V | OT_PD, AM_NOT_USED, "movupd" } },
- /* 0x12 */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movlps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movhlps" }, // only one of ...
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movhlps" }, // ...these two is correct, Intel doesn't specify which
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_S, AM_NOT_USED, "movlpd" } },
- /* 0x13 */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movlps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movlpd" } },
- /* 0x14 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_Q, AM_NOT_USED, "unpcklps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_Q, AM_NOT_USED, "unpcklpd" } },
- /* 0x15 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_Q, AM_NOT_USED, "unpckhps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_Q, AM_NOT_USED, "unpckhpd" } },
- /* 0x16 */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movhps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movlhps" }, // only one of...
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movlhps" }, // ...these two is correct, Intel doesn't specify which
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movhpd" } },
- /* 0x17 */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movhps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movhpd" } },
- /* 0x18 */ { 18, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x19 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1A */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1B */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1C */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1D */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1E */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1F */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x20 */ { 0, IT_GENERIC, AM_R | OT_D, AM_C | OT_D, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x21 */ { 0, IT_GENERIC, AM_R | OT_D, AM_D | OT_D, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x22 */ { 0, IT_GENERIC, AM_C | OT_D, AM_R | OT_D, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x23 */ { 0, IT_GENERIC, AM_D | OT_D, AM_R | OT_D, AM_NOT_USED, "mov", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x24 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x25 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x26 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x27 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x28 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "movaps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "movapd" } },
- /* 0x29 */ { 0, IT_GENERIC, AM_W | OT_PS, AM_V | OT_PS, AM_NOT_USED, "movaps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_PD, AM_V | OT_PD, AM_NOT_USED, "movapd" } },
- /* 0x2A */ { 0, IT_GENERIC, AM_V | OT_PS, AM_Q | OT_Q, AM_NOT_USED, "cvtpi2ps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_E | OT_D, AM_NOT_USED, "cvtsi2sd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_E | OT_D, AM_NOT_USED, "cvtsi2ss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_Q | OT_DQ, AM_NOT_USED, "cvtpi2pd" } },
- /* 0x2B */ { 0, IT_GENERIC, AM_W | OT_PS, AM_V | OT_PS, AM_NOT_USED, "movntps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_PD, AM_V | OT_PD, AM_NOT_USED, "movntpd" } },
- /* 0x2C */ { 0, IT_GENERIC, AM_Q | OT_Q, AM_W | OT_PS, AM_NOT_USED, "cvttps2pi", true,
- /* F2h */ { 0, IT_GENERIC, AM_G | OT_D, AM_W | OT_SD, AM_NOT_USED, "cvttsd2si" },
- /* F3h */ { 0, IT_GENERIC, AM_G | OT_D, AM_W | OT_SS, AM_NOT_USED, "cvttss2si" },
- /* 66h */ { 0, IT_GENERIC, AM_Q | OT_DQ, AM_W | OT_PD, AM_NOT_USED, "cvttpd2pi" } },
- /* 0x2D */ { 0, IT_GENERIC, AM_Q | OT_Q, AM_W | OT_PS, AM_NOT_USED, "cvtps2pi", true,
- /* F2h */ { 0, IT_GENERIC, AM_G | OT_D, AM_W | OT_SD, AM_NOT_USED, "cvtsd2si" },
- /* F3h */ { 0, IT_GENERIC, AM_G | OT_D, AM_W | OT_SS, AM_NOT_USED, "cvtss2si" },
- /* 66h */ { 0, IT_GENERIC, AM_Q | OT_DQ, AM_W | OT_PD, AM_NOT_USED, "cvtpd2pi" } },
- /* 0x2E */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "ucomiss", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "ucomisd" } },
- /* 0x2F */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_SS, AM_NOT_USED, "comiss", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "comisd" } },
- /* 0x30 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "wrmsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x31 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rdtsc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x32 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rdmsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x33 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rdpmc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x34 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "sysenter", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x35 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "sysexit", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x36 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x37 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x38 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x39 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3A */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3B */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3C */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "movnti", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3D */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3E */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3F */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x40 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x41 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovno", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x42 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x43 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovnc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x44 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x45 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x46 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovbe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x47 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmova", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x48 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovs", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x49 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovns", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4A */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovpe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4B */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovpo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4C */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4D */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovge", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4E */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovle", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4F */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "cmovg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x50 */ { 0, IT_GENERIC, AM_E | OT_D, AM_V | OT_PS, AM_NOT_USED, "movmskps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_E | OT_D, AM_V | OT_PD, AM_NOT_USED, "movmskpd" } },
- /* 0x51 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "sqrtps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "sqrtsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "sqrtss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "sqrtpd" } },
- /* 0x52 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "rsqrtps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "rsqrtss" },
- /* 66h */ { 0 } },
- /* 0x53 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "rcpps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "rcpss" },
- /* 66h */ { 0 } },
- /* 0x54 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "andps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "andpd" } },
- /* 0x55 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "andnps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "andnpd" } },
- /* 0x56 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "orps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "orpd" } },
- /* 0x57 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "xorps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "xorpd" } },
- /* 0x58 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "addps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "addsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "addss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "addpd" } },
- /* 0x59 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "mulps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "mulsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "mulss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "mulpd" } },
- /* 0x5A */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PS, AM_NOT_USED, "cvtps2pd", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "cvtsd2ss" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "cvtss2sd" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PD, AM_NOT_USED, "cvtpd2ps" } },
- /* 0x5B */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_DQ, AM_NOT_USED, "cvtdq2ps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_PS, AM_NOT_USED, "cvttps2dq" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_PS, AM_NOT_USED, "cvtps2dq" } },
- /* 0x5C */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "subps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "subsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "subss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "subpd" } },
- /* 0x5D */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "minps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "minsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "minss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "minpd" } },
- /* 0x5E */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "divps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "divsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "divss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "divpd" } },
- /* 0x5F */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_NOT_USED, "maxps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_NOT_USED, "maxsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_NOT_USED, "maxss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_NOT_USED, "maxpd" } },
- /* 0x60 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpcklbw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpcklbw" } },
- /* 0x61 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpcklwd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpcklwd" } },
- /* 0x62 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpckldq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpckldq" } },
- /* 0x63 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "packsswb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "packsswb" } },
- /* 0x64 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "pcmpgtb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpgtb" } },
- /* 0x65 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "pcmpgtw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpgtw" } },
- /* 0x66 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "pcmpgtd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpgtd" } },
- /* 0x67 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "packuswb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "packuswb" } },
- /* 0x68 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpckhbw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_Q | OT_DQ, AM_NOT_USED, "punpckhbw" } },
- /* 0x69 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpckhwd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_Q | OT_DQ, AM_NOT_USED, "punpckhwd" } },
- /* 0x6A */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "punpckhdq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_Q | OT_DQ, AM_NOT_USED, "punpckhdq" } },
- /* 0x6B */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "packssdw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_Q | OT_DQ, AM_NOT_USED, "packssdw" } },
- /* 0x6C */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "not used without prefix", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpcklqdq" } },
- /* 0x6D */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "not used without prefix", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "punpcklqdq" } },
- /* 0x6E */ { 0, IT_GENERIC, AM_P | OT_D, AM_E | OT_D, AM_NOT_USED, "movd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_E | OT_D, AM_NOT_USED, "movd" } },
- /* 0x6F */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_D, AM_NOT_USED, "movq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "movdqu" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "movdqa" } },
- /* 0x70 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_I | OT_B, "pshuf", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_I | OT_B, "pshuflw" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_I | OT_B, "pshufhw" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_I | OT_B, "pshufd" } },
- /* 0x71 */ { 19, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x72 */ { 20, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x73 */ { 21, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x74 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pcmpeqb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpeqb" } },
- /* 0x75 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pcmpeqw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpeqw" } },
- /* 0x76 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pcmpeqd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pcmpeqd" } },
- /* 0x77 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "emms", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
-
- // The following six opcodes are escapes into the MMX stuff, which this disassembler does not support.
- /* 0x78 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x79 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7A */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7B */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7C */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7D */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
-
- /* 0x7E */ { 0, IT_GENERIC, AM_E | OT_D, AM_P | OT_D, AM_NOT_USED, "movd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movq" },
- /* 66h */ { 0, IT_GENERIC, AM_E | OT_D, AM_V | OT_DQ, AM_NOT_USED, "movd" } },
- /* 0x7F */ { 0, IT_GENERIC, AM_Q | OT_Q, AM_P | OT_Q, AM_NOT_USED, "movq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_V | OT_DQ, AM_NOT_USED, "movdqu" },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_V | OT_DQ, AM_NOT_USED, "movdqa" } },
- /* 0x80 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x81 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jno", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x82 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x83 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jnc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x84 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x85 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x86 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jbe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x87 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "ja", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x88 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "js", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x89 */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jns", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8A */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jpe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8B */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jpo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8C */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8D */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jge", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8E */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jle", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x8F */ { 0, IT_JUMP, AM_J | OT_V, AM_NOT_USED, AM_NOT_USED, "jg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x90 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "seto", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x91 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setno", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x92 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x93 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setnc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x94 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x95 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setnz", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x96 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setbe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x97 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "seta", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x98 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "sets", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x99 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setns", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9A */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setpe", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9B */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setpo", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9C */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9D */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setge", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9E */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setle", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x9F */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "setg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA0 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA1 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA2 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "cpuid", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "bt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_I | OT_B, "shld", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_I | OT_B | AM_REGISTER, "shld", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA6 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA7 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA8 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xA9 */ { 0, IT_GENERIC, AM_REGISTER | OT_W, AM_NOT_USED, AM_NOT_USED, "pop", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAA */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "rsm", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAB */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "bts", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAC */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_I | OT_B, "shrd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAD */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_I | OT_B | AM_REGISTER, "shrd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAE */ { 22, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xAF */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "cmpxchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "cmpxchg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB2 */ { 0, IT_GENERIC, AM_M | OT_P, AM_NOT_USED, AM_NOT_USED, "lss", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "btr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB4 */ { 0, IT_GENERIC, AM_M | OT_P, AM_NOT_USED, AM_NOT_USED, "lfs", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB5 */ { 0, IT_GENERIC, AM_M | OT_P, AM_NOT_USED, AM_NOT_USED, "lgs", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB6 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_B, AM_NOT_USED, "movzx", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB7 */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_W, AM_NOT_USED, "movzx", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB8 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xB9 */ { 0, IT_UNKNOWN, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "ud1", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBA */ { 23, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBB */ { 0, IT_GENERIC, AM_E | OT_V, AM_G | OT_V, AM_NOT_USED, "btc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBC */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "bsf", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBD */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_V, AM_NOT_USED, "bsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBE */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_B, AM_NOT_USED, "movsx", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xBF */ { 0, IT_GENERIC, AM_G | OT_V, AM_E | OT_W, AM_NOT_USED, "movsx", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_G | OT_B, AM_NOT_USED, "xadd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "xadd", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC2 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_I | OT_B, "cmpps", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_SD, AM_W | OT_SD, AM_I | OT_B, "cmpsd" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_SS, AM_W | OT_SS, AM_I | OT_B, "cmpss" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_I | OT_B, "cmppd" } },
- /* 0xC3 */ { 0, IT_GENERIC, AM_E | OT_D, AM_G | OT_D, AM_NOT_USED, "movnti", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_E | OT_D, AM_I | OT_B, "pinsrw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_E | OT_D, AM_I | OT_B, "pinsrw" } },
- /* 0xC5 */ { 0, IT_GENERIC, AM_G | OT_D, AM_P | OT_Q, AM_I | OT_B, "pextrw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_G | OT_D, AM_V | OT_DQ, AM_I | OT_B, "pextrw" } },
- /* 0xC6 */ { 0, IT_GENERIC, AM_V | OT_PS, AM_W | OT_PS, AM_I | OT_B, "shufps", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_PD, AM_I | OT_B, "shufpd" } },
- /* 0xC7 */ { 24, IT_REFERENCE, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC8 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xC9 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCA */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCB */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCC */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCD */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCE */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xCF */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "bswap", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xD1 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psrlw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrlw" } },
- /* 0xD2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psrld", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrld" } },
- /* 0xD3 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psrlq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrlq" } },
- /* 0xD4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddq" } },
- /* 0xD5 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmullw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmullw" } },
- /* 0xD6 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "unused without prefix", true,
- /* F2h */ { 0, IT_GENERIC, AM_P | OT_Q, AM_W | OT_Q, AM_NOT_USED, "movdq2q" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_Q | OT_Q, AM_NOT_USED, "movq2dq" },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movq" } },
- /* 0xD7 */ { 0, IT_GENERIC, AM_G | OT_D, AM_P | OT_Q, AM_NOT_USED, "pmovmskb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_G | OT_D, AM_V | OT_DQ, AM_NOT_USED, "pmovmskb" } },
- /* 0xD8 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubusb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubusb" } },
- /* 0xD9 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubusw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubusw" } },
- /* 0xDA */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pminub", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pminub" } },
- /* 0xDB */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pand", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pand" } },
- /* 0xDC */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddusb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddusb" } },
- /* 0xDD */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddusw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddusw" } },
- /* 0xDE */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmaxub", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmaxub" } },
- /* 0xDF */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pandn", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pandn" } },
- /* 0xE0 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pavgb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pavgb" } },
- /* 0xE1 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psraw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrqw" } },
- /* 0xE2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psrad", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psrad" } },
- /* 0xE3 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pavgw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pavgw" } },
- /* 0xE4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmulhuw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmulhuw" } },
- /* 0xE5 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmulhuw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmulhw" } },
- /* 0xE6 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "not used without prefix", true,
- /* F2h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_PD, AM_NOT_USED, "cvtpd2dq" },
- /* F3h */ { 0, IT_GENERIC, AM_V | OT_PD, AM_W | OT_DQ, AM_NOT_USED, "cvtdq2pd" },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_PD, AM_NOT_USED, "cvttpd2dq" } },
- /* 0xE7 */ { 0, IT_GENERIC, AM_W | OT_Q, AM_V | OT_Q, AM_NOT_USED, "movntq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_V | OT_DQ, AM_NOT_USED, "movntdq" } },
- /* 0xE8 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubsb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubsb" } },
- /* 0xE9 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubsw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubsw" } },
- /* 0xEA */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pminsw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pminsw" } },
- /* 0xEB */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "por", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "por" } },
- /* 0xEC */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddsb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddsb" } },
- /* 0xED */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddsw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddsw" } },
- /* 0xEE */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmaxsw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmaxsw" } },
- /* 0xEF */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pxor", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pxor" } },
- /* 0xF0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0xF1 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psllw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psllw" } },
- /* 0xF2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pslld", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pslld" } },
- /* 0xF3 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psllq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psllq" } },
- /* 0xF4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmuludq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmuludq" } },
- /* 0xF5 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "pmaddwd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "pmaddwd" } },
- /* 0xF6 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psadbw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psadbw" } },
- /* 0xF7 */ { 0, IT_GENERIC, AM_P | OT_PI, AM_Q | OT_PI, AM_NOT_USED, "maskmovq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "maskmovdqu" } },
- /* 0xF8 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubb" } },
- /* 0xF9 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubw" } },
- /* 0xFA */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubd" } },
- /* 0xFB */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "psubq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "psubq" } },
- /* 0xFC */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddb", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddb" } },
- /* 0xFD */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddw" } },
- /* 0xFE */ { 0, IT_GENERIC, AM_P | OT_Q, AM_Q | OT_Q, AM_NOT_USED, "paddd", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_V | OT_DQ, AM_W | OT_DQ, AM_NOT_USED, "paddd" } },
- /* 0xFF */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_0f00[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "sldt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "str", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "lldt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "ltr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "verr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "verw", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_0f01[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_M | OT_S, AM_NOT_USED, AM_NOT_USED, "sgdt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_M | OT_S, AM_NOT_USED, AM_NOT_USED, "sidt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_M | OT_S, AM_NOT_USED, AM_NOT_USED, "lgdt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_M | OT_S, AM_NOT_USED, AM_NOT_USED, "lidt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "smsw", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_W, AM_NOT_USED, AM_NOT_USED, "lmsw", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_M | OT_B, AM_NOT_USED, AM_NOT_USED, "invlpg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_0f18[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_M | OT_ADDRESS_MODE_M, AM_NOT_USED, AM_NOT_USED, "prefetch", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "prefetch", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "prefetch", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_REGISTER | OT_D, AM_NOT_USED, AM_NOT_USED, "prefetch", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_0f71[] = {
- /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psrlw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psrlw" } },
- /* 0x3 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psraw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psraw" } },
- /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psllw", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_P | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psllw" } },
- /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_0f72[] = {
- /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psrld", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psrld" } },
- /* 0x3 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psrad", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psrad" } },
- /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "pslld", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "pslld" } },
- /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_0f73[] = {
- /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psrlq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psrlq" } },
- /* 0x3 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_P | OT_Q, AM_I | OT_B, AM_NOT_USED, "psllq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "psllq" } },
- /* 0x7 */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "pslldq", true,
- /* F2h */ { 0 },
- /* F3h */ { 0 },
- /* 66h */ { 0, IT_GENERIC, AM_W | OT_DQ, AM_I | OT_B, AM_NOT_USED, "pslldq" } },
-};
-
-const Opcode s_opcode_byte_after_0fae[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "fxsave", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "fxrstor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "ldmxcsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "stmxcsr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "lfence", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "mfence", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, "clflush/sfence", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
-};
-
-const Opcode s_opcode_byte_after_0fba[] = {
- /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "bt", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "bts", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "btr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "btc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_0fc7[] = {
- /* 0x0 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_M | OT_Q, AM_NOT_USED, AM_NOT_USED, "cmpxch8b", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_80[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_81[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_82[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_83[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "add", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "or", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "adc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sbb", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "and", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sub", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "xor", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "cmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_c0[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_c1[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_B, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_d0[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_B, AM_IMPLICIT, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_d1[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_IMPLICIT, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_d2[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_B, AM_REGISTER | OT_B, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_d3[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "rol", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "ror", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "rcl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "rcr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "shl", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "shr", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "sal", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_E | OT_V, AM_REGISTER | OT_B, AM_NOT_USED, "sar", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_f6[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_I | OT_B, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "not", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "neg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, OT_B | AM_REGISTER, AM_E | OT_B, AM_NOT_USED, "mul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, OT_B | AM_REGISTER, AM_E | OT_B, AM_NOT_USED, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_E | OT_B, AM_NOT_USED, "div", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_REGISTER | OT_B, AM_E | OT_B, AM_NOT_USED, "idiv", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_f7[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_I | OT_V, AM_NOT_USED, "test", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "not", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "neg", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_E | OT_V, AM_NOT_USED, "mul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_E | OT_V, AM_NOT_USED, "imul", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_E | OT_V, AM_NOT_USED, "div", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_GENERIC, AM_REGISTER | OT_V, AM_E | OT_V, AM_NOT_USED, "idiv", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_fe[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_B, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-const Opcode s_opcode_byte_after_ff[] = {
- /* 0x0 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "inc", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x1 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "dec", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x2 */ { 0, IT_JUMP, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "call", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x3 */ { 0, IT_JUMP, AM_E | OT_P, AM_NOT_USED, AM_NOT_USED, "call", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x4 */ { 0, IT_JUMP, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x5 */ { 0, IT_JUMP, AM_E | OT_P, AM_NOT_USED, AM_NOT_USED, "jmp", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x6 */ { 0, IT_GENERIC, AM_E | OT_V, AM_NOT_USED, AM_NOT_USED, "push", false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } },
- /* 0x7 */ { 0, IT_UNUSED, AM_NOT_USED, AM_NOT_USED, AM_NOT_USED, 0, false, /* F2h */ { 0 }, /* F3h */ { 0 }, /* 66h */ { 0 } }
-};
-
-/*
-* A table of all the other tables, containing some extra information, e.g.
-* how to mask out the byte we're looking at.
-*/
-const OpcodeTable MiniDisassembler::s_ia32_opcode_map_[]={
- // One-byte opcodes and jumps to larger
- /* 0 */ {s_first_opcode_byte, 0, 0xff, 0, 0xff},
- // Two-byte opcodes (second byte)
- /* 1 */ {s_opcode_byte_after_0f, 0, 0xff, 0, 0xff},
- // Start of tables for opcodes using ModR/M bits as extension
- /* 2 */ {s_opcode_byte_after_80, 3, 0x07, 0, 0x07},
- /* 3 */ {s_opcode_byte_after_81, 3, 0x07, 0, 0x07},
- /* 4 */ {s_opcode_byte_after_82, 3, 0x07, 0, 0x07},
- /* 5 */ {s_opcode_byte_after_83, 3, 0x07, 0, 0x07},
- /* 6 */ {s_opcode_byte_after_c0, 3, 0x07, 0, 0x07},
- /* 7 */ {s_opcode_byte_after_c1, 3, 0x07, 0, 0x07},
- /* 8 */ {s_opcode_byte_after_d0, 3, 0x07, 0, 0x07},
- /* 9 */ {s_opcode_byte_after_d1, 3, 0x07, 0, 0x07},
- /* 10 */ {s_opcode_byte_after_d2, 3, 0x07, 0, 0x07},
- /* 11 */ {s_opcode_byte_after_d3, 3, 0x07, 0, 0x07},
- /* 12 */ {s_opcode_byte_after_f6, 3, 0x07, 0, 0x07},
- /* 13 */ {s_opcode_byte_after_f7, 3, 0x07, 0, 0x07},
- /* 14 */ {s_opcode_byte_after_fe, 3, 0x07, 0, 0x01},
- /* 15 */ {s_opcode_byte_after_ff, 3, 0x07, 0, 0x07},
- /* 16 */ {s_opcode_byte_after_0f00, 3, 0x07, 0, 0x07},
- /* 17 */ {s_opcode_byte_after_0f01, 3, 0x07, 0, 0x07},
- /* 18 */ {s_opcode_byte_after_0f18, 3, 0x07, 0, 0x07},
- /* 19 */ {s_opcode_byte_after_0f71, 3, 0x07, 0, 0x07},
- /* 20 */ {s_opcode_byte_after_0f72, 3, 0x07, 0, 0x07},
- /* 21 */ {s_opcode_byte_after_0f73, 3, 0x07, 0, 0x07},
- /* 22 */ {s_opcode_byte_after_0fae, 3, 0x07, 0, 0x07},
- /* 23 */ {s_opcode_byte_after_0fba, 3, 0x07, 0, 0x07},
- /* 24 */ {s_opcode_byte_after_0fc7, 3, 0x07, 0, 0x01}
-};
-
-}; // namespace sidestep
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler.cpp b/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler.cpp
deleted file mode 100644
index 1e8e0bd97..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler.cpp
+++ /dev/null
@@ -1,395 +0,0 @@
-// 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.
-
-// Implementation of MiniDisassembler.
-
-#ifdef _WIN64
-#error The code in this file should not be used on 64-bit Windows.
-#endif
-
-#include "sandbox/win/src/sidestep/mini_disassembler.h"
-
-namespace sidestep {
-
-MiniDisassembler::MiniDisassembler(bool operand_default_is_32_bits,
- bool address_default_is_32_bits)
- : operand_default_is_32_bits_(operand_default_is_32_bits),
- address_default_is_32_bits_(address_default_is_32_bits) {
- Initialize();
-}
-
-MiniDisassembler::MiniDisassembler()
- : operand_default_is_32_bits_(true),
- address_default_is_32_bits_(true) {
- Initialize();
-}
-
-InstructionType MiniDisassembler::Disassemble(
- unsigned char* start_byte,
- unsigned int* instruction_bytes) {
- // Clean up any state from previous invocations.
- Initialize();
-
- // Start by processing any prefixes.
- unsigned char* current_byte = start_byte;
- unsigned int size = 0;
- InstructionType instruction_type = ProcessPrefixes(current_byte, &size);
-
- if (IT_UNKNOWN == instruction_type)
- return instruction_type;
-
- current_byte += size;
- size = 0;
-
- // Invariant: We have stripped all prefixes, and the operand_is_32_bits_
- // and address_is_32_bits_ flags are correctly set.
-
- instruction_type = ProcessOpcode(current_byte, 0, &size);
-
- // Check for error processing instruction
- if ((IT_UNKNOWN == instruction_type_) || (IT_UNUSED == instruction_type_)) {
- return IT_UNKNOWN;
- }
-
- current_byte += size;
-
- // Invariant: operand_bytes_ indicates the total size of operands
- // specified by the opcode and/or ModR/M byte and/or SIB byte.
- // pCurrentByte points to the first byte after the ModR/M byte, or after
- // the SIB byte if it is present (i.e. the first byte of any operands
- // encoded in the instruction).
-
- // We get the total length of any prefixes, the opcode, and the ModR/M and
- // SIB bytes if present, by taking the difference of the original starting
- // address and the current byte (which points to the first byte of the
- // operands if present, or to the first byte of the next instruction if
- // they are not). Adding the count of bytes in the operands encoded in
- // the instruction gives us the full length of the instruction in bytes.
- *instruction_bytes += operand_bytes_ + (current_byte - start_byte);
-
- // Return the instruction type, which was set by ProcessOpcode().
- return instruction_type_;
-}
-
-void MiniDisassembler::Initialize() {
- operand_is_32_bits_ = operand_default_is_32_bits_;
- address_is_32_bits_ = address_default_is_32_bits_;
- operand_bytes_ = 0;
- have_modrm_ = false;
- should_decode_modrm_ = false;
- instruction_type_ = IT_UNKNOWN;
- got_f2_prefix_ = false;
- got_f3_prefix_ = false;
- got_66_prefix_ = false;
-}
-
-InstructionType MiniDisassembler::ProcessPrefixes(unsigned char* start_byte,
- unsigned int* size) {
- InstructionType instruction_type = IT_GENERIC;
- const Opcode& opcode = s_ia32_opcode_map_[0].table_[*start_byte];
-
- switch (opcode.type_) {
- case IT_PREFIX_ADDRESS:
- address_is_32_bits_ = !address_default_is_32_bits_;
- goto nochangeoperand;
- case IT_PREFIX_OPERAND:
- operand_is_32_bits_ = !operand_default_is_32_bits_;
- nochangeoperand:
- case IT_PREFIX:
-
- if (0xF2 == (*start_byte))
- got_f2_prefix_ = true;
- else if (0xF3 == (*start_byte))
- got_f3_prefix_ = true;
- else if (0x66 == (*start_byte))
- got_66_prefix_ = true;
-
- instruction_type = opcode.type_;
- (*size)++;
- // we got a prefix, so add one and check next byte
- ProcessPrefixes(start_byte + 1, size);
- default:
- break; // not a prefix byte
- }
-
- return instruction_type;
-}
-
-InstructionType MiniDisassembler::ProcessOpcode(unsigned char* start_byte,
- unsigned int table_index,
- unsigned int* size) {
- const OpcodeTable& table = s_ia32_opcode_map_[table_index]; // Get our table
- unsigned char current_byte = (*start_byte) >> table.shift_;
- current_byte = current_byte & table.mask_; // Mask out the bits we will use
-
- // Check whether the byte we have is inside the table we have.
- if (current_byte < table.min_lim_ || current_byte > table.max_lim_) {
- instruction_type_ = IT_UNKNOWN;
- return instruction_type_;
- }
-
- const Opcode& opcode = table.table_[current_byte];
- if (IT_UNUSED == opcode.type_) {
- // This instruction is not used by the IA-32 ISA, so we indicate
- // this to the user. Probably means that we were pointed to
- // a byte in memory that was not the start of an instruction.
- instruction_type_ = IT_UNUSED;
- return instruction_type_;
- } else if (IT_REFERENCE == opcode.type_) {
- // We are looking at an opcode that has more bytes (or is continued
- // in the ModR/M byte). Recursively find the opcode definition in
- // the table for the opcode's next byte.
- (*size)++;
- ProcessOpcode(start_byte + 1, opcode.table_index_, size);
- return instruction_type_;
- }
-
- const SpecificOpcode* specific_opcode = reinterpret_cast<
- const SpecificOpcode*>(&opcode);
- if (opcode.is_prefix_dependent_) {
- if (got_f2_prefix_ && opcode.opcode_if_f2_prefix_.mnemonic_ != 0) {
- specific_opcode = &opcode.opcode_if_f2_prefix_;
- } else if (got_f3_prefix_ && opcode.opcode_if_f3_prefix_.mnemonic_ != 0) {
- specific_opcode = &opcode.opcode_if_f3_prefix_;
- } else if (got_66_prefix_ && opcode.opcode_if_66_prefix_.mnemonic_ != 0) {
- specific_opcode = &opcode.opcode_if_66_prefix_;
- }
- }
-
- // Inv: The opcode type is known.
- instruction_type_ = specific_opcode->type_;
-
- // Let's process the operand types to see if we have any immediate
- // operands, and/or a ModR/M byte.
-
- ProcessOperand(specific_opcode->flag_dest_);
- ProcessOperand(specific_opcode->flag_source_);
- ProcessOperand(specific_opcode->flag_aux_);
-
- // Inv: We have processed the opcode and incremented operand_bytes_
- // by the number of bytes of any operands specified by the opcode
- // that are stored in the instruction (not registers etc.). Now
- // we need to return the total number of bytes for the opcode and
- // for the ModR/M or SIB bytes if they are present.
-
- if (table.mask_ != 0xff) {
- if (have_modrm_) {
- // we're looking at a ModR/M byte so we're not going to
- // count that into the opcode size
- ProcessModrm(start_byte, size);
- return IT_GENERIC;
- } else {
- // need to count the ModR/M byte even if it's just being
- // used for opcode extension
- (*size)++;
- return IT_GENERIC;
- }
- } else {
- if (have_modrm_) {
- // The ModR/M byte is the next byte.
- (*size)++;
- ProcessModrm(start_byte + 1, size);
- return IT_GENERIC;
- } else {
- (*size)++;
- return IT_GENERIC;
- }
- }
-}
-
-bool MiniDisassembler::ProcessOperand(int flag_operand) {
- bool succeeded = true;
- if (AM_NOT_USED == flag_operand)
- return succeeded;
-
- // Decide what to do based on the addressing mode.
- switch (flag_operand & AM_MASK) {
- // No ModR/M byte indicated by these addressing modes, and no
- // additional (e.g. immediate) parameters.
- case AM_A: // Direct address
- case AM_F: // EFLAGS register
- case AM_X: // Memory addressed by the DS:SI register pair
- case AM_Y: // Memory addressed by the ES:DI register pair
- case AM_IMPLICIT: // Parameter is implicit, occupies no space in
- // instruction
- break;
-
- // There is a ModR/M byte but it does not necessarily need
- // to be decoded.
- case AM_C: // reg field of ModR/M selects a control register
- case AM_D: // reg field of ModR/M selects a debug register
- case AM_G: // reg field of ModR/M selects a general register
- case AM_P: // reg field of ModR/M selects an MMX register
- case AM_R: // mod field of ModR/M may refer only to a general register
- case AM_S: // reg field of ModR/M selects a segment register
- case AM_T: // reg field of ModR/M selects a test register
- case AM_V: // reg field of ModR/M selects a 128-bit XMM register
- have_modrm_ = true;
- break;
-
- // In these addressing modes, there is a ModR/M byte and it needs to be
- // decoded. No other (e.g. immediate) params than indicated in ModR/M.
- case AM_E: // Operand is either a general-purpose register or memory,
- // specified by ModR/M byte
- case AM_M: // ModR/M byte will refer only to memory
- case AM_Q: // Operand is either an MMX register or memory (complex
- // evaluation), specified by ModR/M byte
- case AM_W: // Operand is either a 128-bit XMM register or memory (complex
- // eval), specified by ModR/M byte
- have_modrm_ = true;
- should_decode_modrm_ = true;
- break;
-
- // These addressing modes specify an immediate or an offset value
- // directly, so we need to look at the operand type to see how many
- // bytes.
- case AM_I: // Immediate data.
- case AM_J: // Jump to offset.
- case AM_O: // Operand is at offset.
- switch (flag_operand & OT_MASK) {
- case OT_B: // Byte regardless of operand-size attribute.
- operand_bytes_ += OS_BYTE;
- break;
- case OT_C: // Byte or word, depending on operand-size attribute.
- if (operand_is_32_bits_)
- operand_bytes_ += OS_WORD;
- else
- operand_bytes_ += OS_BYTE;
- break;
- case OT_D: // Doubleword, regardless of operand-size attribute.
- operand_bytes_ += OS_DOUBLE_WORD;
- break;
- case OT_DQ: // Double-quadword, regardless of operand-size attribute.
- operand_bytes_ += OS_DOUBLE_QUAD_WORD;
- break;
- case OT_P: // 32-bit or 48-bit pointer, depending on operand-size
- // attribute.
- if (operand_is_32_bits_)
- operand_bytes_ += OS_48_BIT_POINTER;
- else
- operand_bytes_ += OS_32_BIT_POINTER;
- break;
- case OT_PS: // 128-bit packed single-precision floating-point data.
- operand_bytes_ += OS_128_BIT_PACKED_SINGLE_PRECISION_FLOATING;
- break;
- case OT_Q: // Quadword, regardless of operand-size attribute.
- operand_bytes_ += OS_QUAD_WORD;
- break;
- case OT_S: // 6-byte pseudo-descriptor.
- operand_bytes_ += OS_PSEUDO_DESCRIPTOR;
- break;
- case OT_SD: // Scalar Double-Precision Floating-Point Value
- case OT_PD: // Unaligned packed double-precision floating point value
- operand_bytes_ += OS_DOUBLE_PRECISION_FLOATING;
- break;
- case OT_SS:
- // Scalar element of a 128-bit packed single-precision
- // floating data.
- // We simply return enItUnknown since we don't have to support
- // floating point
- succeeded = false;
- break;
- case OT_V: // Word or doubleword, depending on operand-size attribute.
- if (operand_is_32_bits_)
- operand_bytes_ += OS_DOUBLE_WORD;
- else
- operand_bytes_ += OS_WORD;
- break;
- case OT_W: // Word, regardless of operand-size attribute.
- operand_bytes_ += OS_WORD;
- break;
-
- // Can safely ignore these.
- case OT_A: // Two one-word operands in memory or two double-word
- // operands in memory
- case OT_PI: // Quadword MMX technology register (e.g. mm0)
- case OT_SI: // Doubleword integer register (e.g., eax)
- break;
-
- default:
- break;
- }
- break;
-
- default:
- break;
- }
-
- return succeeded;
-}
-
-bool MiniDisassembler::ProcessModrm(unsigned char* start_byte,
- unsigned int* size) {
- // If we don't need to decode, we just return the size of the ModR/M
- // byte (there is never a SIB byte in this case).
- if (!should_decode_modrm_) {
- (*size)++;
- return true;
- }
-
- // We never care about the reg field, only the combination of the mod
- // and r/m fields, so let's start by packing those fields together into
- // 5 bits.
- unsigned char modrm = (*start_byte);
- unsigned char mod = modrm & 0xC0; // mask out top two bits to get mod field
- modrm = modrm & 0x07; // mask out bottom 3 bits to get r/m field
- mod = mod >> 3; // shift the mod field to the right place
- modrm = mod | modrm; // combine the r/m and mod fields as discussed
- mod = mod >> 3; // shift the mod field to bits 2..0
-
- // Invariant: modrm contains the mod field in bits 4..3 and the r/m field
- // in bits 2..0, and mod contains the mod field in bits 2..0
-
- const ModrmEntry* modrm_entry = 0;
- if (address_is_32_bits_)
- modrm_entry = &s_ia32_modrm_map_[modrm];
- else
- modrm_entry = &s_ia16_modrm_map_[modrm];
-
- // Invariant: modrm_entry points to information that we need to decode
- // the ModR/M byte.
-
- // Add to the count of operand bytes, if the ModR/M byte indicates
- // that some operands are encoded in the instruction.
- if (modrm_entry->is_encoded_in_instruction_)
- operand_bytes_ += modrm_entry->operand_size_;
-
- // Process the SIB byte if necessary, and return the count
- // of ModR/M and SIB bytes.
- if (modrm_entry->use_sib_byte_) {
- (*size)++;
- return ProcessSib(start_byte + 1, mod, size);
- } else {
- (*size)++;
- return true;
- }
-}
-
-bool MiniDisassembler::ProcessSib(unsigned char* start_byte,
- unsigned char mod,
- unsigned int* size) {
- // get the mod field from the 2..0 bits of the SIB byte
- unsigned char sib_base = (*start_byte) & 0x07;
- if (0x05 == sib_base) {
- switch (mod) {
- case 0x00: // mod == 00
- case 0x02: // mod == 10
- operand_bytes_ += OS_DOUBLE_WORD;
- break;
- case 0x01: // mod == 01
- operand_bytes_ += OS_BYTE;
- break;
- case 0x03: // mod == 11
- // According to the IA-32 docs, there does not seem to be a disp
- // value for this value of mod
- default:
- break;
- }
- }
-
- (*size)++;
- return true;
-}
-
-}; // namespace sidestep
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler.h b/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler.h
deleted file mode 100644
index 202c4ecc2..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler.h
+++ /dev/null
@@ -1,156 +0,0 @@
-// 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.
-
-// Definition of MiniDisassembler.
-
-#ifndef SANDBOX_SRC_SIDESTEP_MINI_DISASSEMBLER_H__
-#define SANDBOX_SRC_SIDESTEP_MINI_DISASSEMBLER_H__
-
-#include "sandbox/win/src/sidestep/mini_disassembler_types.h"
-
-namespace sidestep {
-
-// This small disassembler is very limited
-// in its functionality, and in fact does only the bare minimum required by the
-// preamble patching utility. It may be useful for other purposes, however.
-//
-// The limitations include at least the following:
-// -# No support for coprocessor opcodes, MMX, etc.
-// -# No machine-readable identification of opcodes or decoding of
-// assembly parameters. The name of the opcode (as a string) is given,
-// however, to aid debugging.
-//
-// You may ask what this little disassembler actually does, then? The answer is
-// that it does the following, which is exactly what the patching utility needs:
-// -# Indicates if opcode is a jump (any kind) or a return (any kind)
-// because this is important for the patching utility to determine if
-// a function is too short or there are jumps too early in it for it
-// to be preamble patched.
-// -# The opcode length is always calculated, so that the patching utility
-// can figure out where the next instruction starts, and whether it
-// already has enough instructions to replace with the absolute jump
-// to the patching code.
-//
-// The usage is quite simple; just create a MiniDisassembler and use its
-// Disassemble() method.
-//
-// If you would like to extend this disassembler, please refer to the
-// IA-32 Intel Architecture Software Developer's Manual Volume 2:
-// Instruction Set Reference for information about operand decoding
-// etc.
-class MiniDisassembler {
- public:
-
- // Creates a new instance and sets defaults.
- //
- // operand_default_32_bits: If true, the default operand size is
- // set to 32 bits, which is the default under Win32. Otherwise it is 16 bits.
- // address_default_32_bits: If true, the default address size is
- // set to 32 bits, which is the default under Win32. Otherwise it is 16 bits.
- MiniDisassembler(bool operand_default_32_bits,
- bool address_default_32_bits);
-
- // Equivalent to MiniDisassembler(true, true);
- MiniDisassembler();
-
- // Attempts to disassemble a single instruction starting from the
- // address in memory it is pointed to.
- //
- // start: Address where disassembly should start.
- // instruction_bytes: Variable that will be incremented by
- // the length in bytes of the instruction.
- // Returns enItJump, enItReturn or enItGeneric on success. enItUnknown
- // if unable to disassemble, enItUnused if this seems to be an unused
- // opcode. In the last two (error) cases, cbInstruction will be set
- // to 0xffffffff.
- //
- // Postcondition: This instance of the disassembler is ready to be used again,
- // with unchanged defaults from creation time.
- InstructionType Disassemble(unsigned char* start,
- unsigned int* instruction_bytes);
-
- private:
-
- // Makes the disassembler ready for reuse.
- void Initialize();
-
- // Sets the flags for address and operand sizes.
- // Returns Number of prefix bytes.
- InstructionType ProcessPrefixes(unsigned char* start, unsigned int* size);
-
- // Sets the flag for whether we have ModR/M, and increments
- // operand_bytes_ if any are specifies by the opcode directly.
- // Returns Number of opcode bytes.
- InstructionType ProcessOpcode(unsigned char* start,
- unsigned int table,
- unsigned int* size);
-
- // Checks the type of the supplied operand. Increments
- // operand_bytes_ if it directly indicates an immediate etc.
- // operand. Asserts have_modrm_ if the operand specifies
- // a ModR/M byte.
- bool ProcessOperand(int flag_operand);
-
- // Increments operand_bytes_ by size specified by ModR/M and
- // by SIB if present.
- // Returns 0 in case of error, 1 if there is just a ModR/M byte,
- // 2 if there is a ModR/M byte and a SIB byte.
- bool ProcessModrm(unsigned char* start, unsigned int* size);
-
- // Processes the SIB byte that it is pointed to.
- // start: Pointer to the SIB byte.
- // mod: The mod field from the ModR/M byte.
- // Returns 1 to indicate success (indicates 1 SIB byte)
- bool ProcessSib(unsigned char* start, unsigned char mod, unsigned int* size);
-
- // The instruction type we have decoded from the opcode.
- InstructionType instruction_type_;
-
- // Counts the number of bytes that is occupied by operands in
- // the current instruction (note: we don't care about how large
- // operands stored in registers etc. are).
- unsigned int operand_bytes_;
-
- // True iff there is a ModR/M byte in this instruction.
- bool have_modrm_;
-
- // True iff we need to decode the ModR/M byte (sometimes it just
- // points to a register, we can tell by the addressing mode).
- bool should_decode_modrm_;
-
- // Current operand size is 32 bits if true, 16 bits if false.
- bool operand_is_32_bits_;
-
- // Default operand size is 32 bits if true, 16 bits if false.
- bool operand_default_is_32_bits_;
-
- // Current address size is 32 bits if true, 16 bits if false.
- bool address_is_32_bits_;
-
- // Default address size is 32 bits if true, 16 bits if false.
- bool address_default_is_32_bits_;
-
- // Huge big opcode table based on the IA-32 manual, defined
- // in Ia32OpcodeMap.cpp
- static const OpcodeTable s_ia32_opcode_map_[];
-
- // Somewhat smaller table to help with decoding ModR/M bytes
- // when 16-bit addressing mode is being used. Defined in
- // Ia32ModrmMap.cpp
- static const ModrmEntry s_ia16_modrm_map_[];
-
- // Somewhat smaller table to help with decoding ModR/M bytes
- // when 32-bit addressing mode is being used. Defined in
- // Ia32ModrmMap.cpp
- static const ModrmEntry s_ia32_modrm_map_[];
-
- // Indicators of whether we got certain prefixes that certain
- // silly Intel instructions depend on in nonstandard ways for
- // their behaviors.
- bool got_f2_prefix_, got_f3_prefix_, got_66_prefix_;
-};
-
-}; // namespace sidestep
-
-#endif // SANDBOX_SRC_SIDESTEP_MINI_DISASSEMBLER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler_types.h b/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler_types.h
deleted file mode 100644
index 1c1062631..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep/mini_disassembler_types.h
+++ /dev/null
@@ -1,197 +0,0 @@
-// 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.
-//
-// Several simple types used by the disassembler and some of the patching
-// mechanisms.
-
-#ifndef SANDBOX_SRC_SIDESTEP_MINI_DISASSEMBLER_TYPES_H__
-#define SANDBOX_SRC_SIDESTEP_MINI_DISASSEMBLER_TYPES_H__
-
-namespace sidestep {
-
-// Categories of instructions that we care about
-enum InstructionType {
- // This opcode is not used
- IT_UNUSED,
- // This disassembler does not recognize this opcode (error)
- IT_UNKNOWN,
- // This is not an instruction but a reference to another table
- IT_REFERENCE,
- // This byte is a prefix byte that we can ignore
- IT_PREFIX,
- // This is a prefix byte that switches to the nondefault address size
- IT_PREFIX_ADDRESS,
- // This is a prefix byte that switches to the nondefault operand size
- IT_PREFIX_OPERAND,
- // A jump or call instruction
- IT_JUMP,
- // A return instruction
- IT_RETURN,
- // Any other type of instruction (in this case we don't care what it is)
- IT_GENERIC,
-};
-
-// Lists IA-32 operand sizes in multiples of 8 bits
-enum OperandSize {
- OS_ZERO = 0,
- OS_BYTE = 1,
- OS_WORD = 2,
- OS_DOUBLE_WORD = 4,
- OS_QUAD_WORD = 8,
- OS_DOUBLE_QUAD_WORD = 16,
- OS_32_BIT_POINTER = 32/8,
- OS_48_BIT_POINTER = 48/8,
- OS_SINGLE_PRECISION_FLOATING = 32/8,
- OS_DOUBLE_PRECISION_FLOATING = 64/8,
- OS_DOUBLE_EXTENDED_PRECISION_FLOATING = 80/8,
- OS_128_BIT_PACKED_SINGLE_PRECISION_FLOATING = 128/8,
- OS_PSEUDO_DESCRIPTOR = 6
-};
-
-// Operand addressing methods from the IA-32 manual. The enAmMask value
-// is a mask for the rest. The other enumeration values are named for the
-// names given to the addressing methods in the manual, e.g. enAm_D is for
-// the D addressing method.
-//
-// The reason we use a full 4 bytes and a mask, is that we need to combine
-// these flags with the enOperandType to store the details
-// on the operand in a single integer.
-enum AddressingMethod {
- AM_NOT_USED = 0, // This operand is not used for this instruction
- AM_MASK = 0x00FF0000, // Mask for the rest of the values in this enumeration
- AM_A = 0x00010000, // A addressing type
- AM_C = 0x00020000, // C addressing type
- AM_D = 0x00030000, // D addressing type
- AM_E = 0x00040000, // E addressing type
- AM_F = 0x00050000, // F addressing type
- AM_G = 0x00060000, // G addressing type
- AM_I = 0x00070000, // I addressing type
- AM_J = 0x00080000, // J addressing type
- AM_M = 0x00090000, // M addressing type
- AM_O = 0x000A0000, // O addressing type
- AM_P = 0x000B0000, // P addressing type
- AM_Q = 0x000C0000, // Q addressing type
- AM_R = 0x000D0000, // R addressing type
- AM_S = 0x000E0000, // S addressing type
- AM_T = 0x000F0000, // T addressing type
- AM_V = 0x00100000, // V addressing type
- AM_W = 0x00110000, // W addressing type
- AM_X = 0x00120000, // X addressing type
- AM_Y = 0x00130000, // Y addressing type
- AM_REGISTER = 0x00140000, // Specific register is always used as this op
- AM_IMPLICIT = 0x00150000, // An implicit, fixed value is used
-};
-
-// Operand types from the IA-32 manual. The enOtMask value is
-// a mask for the rest. The rest of the values are named for the
-// names given to these operand types in the manual, e.g. enOt_ps
-// is for the ps operand type in the manual.
-//
-// The reason we use a full 4 bytes and a mask, is that we need
-// to combine these flags with the enAddressingMethod to store the details
-// on the operand in a single integer.
-enum OperandType {
- OT_MASK = 0xFF000000,
- OT_A = 0x01000000,
- OT_B = 0x02000000,
- OT_C = 0x03000000,
- OT_D = 0x04000000,
- OT_DQ = 0x05000000,
- OT_P = 0x06000000,
- OT_PI = 0x07000000,
- OT_PS = 0x08000000, // actually unsupported for (we don't know its size)
- OT_Q = 0x09000000,
- OT_S = 0x0A000000,
- OT_SS = 0x0B000000,
- OT_SI = 0x0C000000,
- OT_V = 0x0D000000,
- OT_W = 0x0E000000,
- OT_SD = 0x0F000000, // scalar double-precision floating-point value
- OT_PD = 0x10000000, // double-precision floating point
- // dummy "operand type" for address mode M - which doesn't specify
- // operand type
- OT_ADDRESS_MODE_M = 0x80000000
-};
-
-// Everything that's in an Opcode (see below) except the three
-// alternative opcode structs for different prefixes.
-struct SpecificOpcode {
- // Index to continuation table, or 0 if this is the last
- // byte in the opcode.
- int table_index_;
-
- // The opcode type
- InstructionType type_;
-
- // Description of the type of the dest, src and aux operands,
- // put together from an enOperandType flag and an enAddressingMethod
- // flag.
- int flag_dest_;
- int flag_source_;
- int flag_aux_;
-
- // We indicate the mnemonic for debugging purposes
- const char* mnemonic_;
-};
-
-// The information we keep in our tables about each of the different
-// valid instructions recognized by the IA-32 architecture.
-struct Opcode {
- // Index to continuation table, or 0 if this is the last
- // byte in the opcode.
- int table_index_;
-
- // The opcode type
- InstructionType type_;
-
- // Description of the type of the dest, src and aux operands,
- // put together from an enOperandType flag and an enAddressingMethod
- // flag.
- int flag_dest_;
- int flag_source_;
- int flag_aux_;
-
- // We indicate the mnemonic for debugging purposes
- const char* mnemonic_;
-
- // Alternative opcode info if certain prefixes are specified.
- // In most cases, all of these are zeroed-out. Only used if
- // bPrefixDependent is true.
- bool is_prefix_dependent_;
- SpecificOpcode opcode_if_f2_prefix_;
- SpecificOpcode opcode_if_f3_prefix_;
- SpecificOpcode opcode_if_66_prefix_;
-};
-
-// Information about each table entry.
-struct OpcodeTable {
- // Table of instruction entries
- const Opcode* table_;
- // How many bytes left to shift ModR/M byte <b>before</b> applying mask
- unsigned char shift_;
- // Mask to apply to byte being looked at before comparing to table
- unsigned char mask_;
- // Minimum/maximum indexes in table.
- unsigned char min_lim_;
- unsigned char max_lim_;
-};
-
-// Information about each entry in table used to decode ModR/M byte.
-struct ModrmEntry {
- // Is the operand encoded as bytes in the instruction (rather than
- // if it's e.g. a register in which case it's just encoded in the
- // ModR/M byte)
- bool is_encoded_in_instruction_;
-
- // Is there a SIB byte? In this case we always need to decode it.
- bool use_sib_byte_;
-
- // What is the size of the operand (only important if it's encoded
- // in the instruction)?
- OperandSize operand_size_;
-};
-
-}; // namespace sidestep
-
-#endif // SANDBOX_SRC_SIDESTEP_MINI_DISASSEMBLER_TYPES_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep/preamble_patcher.h b/security/sandbox/chromium/sandbox/win/src/sidestep/preamble_patcher.h
deleted file mode 100644
index 3a0985ce9..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep/preamble_patcher.h
+++ /dev/null
@@ -1,111 +0,0 @@
-// 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.
-
-// Definition of PreamblePatcher
-
-#ifndef SANDBOX_SRC_SIDESTEP_PREAMBLE_PATCHER_H__
-#define SANDBOX_SRC_SIDESTEP_PREAMBLE_PATCHER_H__
-
-#include <stddef.h>
-
-namespace sidestep {
-
-// Maximum size of the preamble stub. We overwrite at least the first 5
-// bytes of the function. Considering the worst case scenario, we need 4
-// bytes + the max instruction size + 5 more bytes for our jump back to
-// the original code. With that in mind, 32 is a good number :)
-const size_t kMaxPreambleStubSize = 32;
-
-// Possible results of patching/unpatching
-enum SideStepError {
- SIDESTEP_SUCCESS = 0,
- SIDESTEP_INVALID_PARAMETER,
- SIDESTEP_INSUFFICIENT_BUFFER,
- SIDESTEP_JUMP_INSTRUCTION,
- SIDESTEP_FUNCTION_TOO_SMALL,
- SIDESTEP_UNSUPPORTED_INSTRUCTION,
- SIDESTEP_NO_SUCH_MODULE,
- SIDESTEP_NO_SUCH_FUNCTION,
- SIDESTEP_ACCESS_DENIED,
- SIDESTEP_UNEXPECTED,
-};
-
-// Implements a patching mechanism that overwrites the first few bytes of
-// a function preamble with a jump to our hook function, which is then
-// able to call the original function via a specially-made preamble-stub
-// that imitates the action of the original preamble.
-//
-// Note that there are a number of ways that this method of patching can
-// fail. The most common are:
-// - If there is a jump (jxx) instruction in the first 5 bytes of
-// the function being patched, we cannot patch it because in the
-// current implementation we do not know how to rewrite relative
-// jumps after relocating them to the preamble-stub. Note that
-// if you really really need to patch a function like this, it
-// would be possible to add this functionality (but at some cost).
-// - If there is a return (ret) instruction in the first 5 bytes
-// we cannot patch the function because it may not be long enough
-// for the jmp instruction we use to inject our patch.
-// - If there is another thread currently executing within the bytes
-// that are copied to the preamble stub, it will crash in an undefined
-// way.
-//
-// If you get any other error than the above, you're either pointing the
-// patcher at an invalid instruction (e.g. into the middle of a multi-
-// byte instruction, or not at memory containing executable instructions)
-// or, there may be a bug in the disassembler we use to find
-// instruction boundaries.
-class PreamblePatcher {
- public:
- // Patches target_function to point to replacement_function using a provided
- // preamble_stub of stub_size bytes.
- // Returns An error code indicating the result of patching.
- template <class T>
- static SideStepError Patch(T target_function, T replacement_function,
- void* preamble_stub, size_t stub_size) {
- return RawPatchWithStub(target_function, replacement_function,
- reinterpret_cast<unsigned char*>(preamble_stub),
- stub_size, NULL);
- }
-
- private:
-
- // Patches a function by overwriting its first few bytes with
- // a jump to a different function. This is similar to the RawPatch
- // function except that it uses the stub allocated by the caller
- // instead of allocating it.
- //
- // To use this function, you first have to call VirtualProtect to make the
- // target function writable at least for the duration of the call.
- //
- // target_function: A pointer to the function that should be
- // patched.
- //
- // replacement_function: A pointer to the function that should
- // replace the target function. The replacement function must have
- // exactly the same calling convention and parameters as the original
- // function.
- //
- // preamble_stub: A pointer to a buffer where the preamble stub
- // should be copied. The size of the buffer should be sufficient to
- // hold the preamble bytes.
- //
- // stub_size: Size in bytes of the buffer allocated for the
- // preamble_stub
- //
- // bytes_needed: Pointer to a variable that receives the minimum
- // number of bytes required for the stub. Can be set to NULL if you're
- // not interested.
- //
- // Returns An error code indicating the result of patching.
- static SideStepError RawPatchWithStub(void* target_function,
- void *replacement_function,
- unsigned char* preamble_stub,
- size_t stub_size,
- size_t* bytes_needed);
-};
-
-}; // namespace sidestep
-
-#endif // SANDBOX_SRC_SIDESTEP_PREAMBLE_PATCHER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep/preamble_patcher_with_stub.cpp b/security/sandbox/chromium/sandbox/win/src/sidestep/preamble_patcher_with_stub.cpp
deleted file mode 100644
index b5016009d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep/preamble_patcher_with_stub.cpp
+++ /dev/null
@@ -1,181 +0,0 @@
-// 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.
-
-// Implementation of PreamblePatcher
-
-#include "sandbox/win/src/sidestep/preamble_patcher.h"
-
-#include <stddef.h>
-
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sidestep/mini_disassembler.h"
-
-// Definitions of assembly statements we need
-#define ASM_JMP32REL 0xE9
-#define ASM_INT3 0xCC
-
-namespace {
-
-// Very basic memcpy. We are copying 4 to 12 bytes most of the time, so there
-// is no attempt to optimize this code or have a general purpose function.
-// We don't want to call the crt from this code.
-inline void* RawMemcpy(void* destination, const void* source, size_t bytes) {
- const char* from = reinterpret_cast<const char*>(source);
- char* to = reinterpret_cast<char*>(destination);
-
- for (size_t i = 0; i < bytes ; i++)
- to[i] = from[i];
-
- return destination;
-}
-
-// Very basic memset. We are filling 1 to 7 bytes most of the time, so there
-// is no attempt to optimize this code or have a general purpose function.
-// We don't want to call the crt from this code.
-inline void* RawMemset(void* destination, int value, size_t bytes) {
- char* to = reinterpret_cast<char*>(destination);
-
- for (size_t i = 0; i < bytes ; i++)
- to[i] = static_cast<char>(value);
-
- return destination;
-}
-
-} // namespace
-
-#define ASSERT(a, b) DCHECK_NT(a)
-
-namespace sidestep {
-
-SideStepError PreamblePatcher::RawPatchWithStub(
- void* target_function,
- void* replacement_function,
- unsigned char* preamble_stub,
- size_t stub_size,
- size_t* bytes_needed) {
- if ((NULL == target_function) ||
- (NULL == replacement_function) ||
- (NULL == preamble_stub)) {
- ASSERT(false, (L"Invalid parameters - either pTargetFunction or "
- L"pReplacementFunction or pPreambleStub were NULL."));
- return SIDESTEP_INVALID_PARAMETER;
- }
-
- // TODO(V7:joi) Siggi and I just had a discussion and decided that both
- // patching and unpatching are actually unsafe. We also discussed a
- // method of making it safe, which is to freeze all other threads in the
- // process, check their thread context to see if their eip is currently
- // inside the block of instructions we need to copy to the stub, and if so
- // wait a bit and try again, then unfreeze all threads once we've patched.
- // Not implementing this for now since we're only using SideStep for unit
- // testing, but if we ever use it for production code this is what we
- // should do.
- //
- // NOTE: Stoyan suggests we can write 8 or even 10 bytes atomically using
- // FPU instructions, and on newer processors we could use cmpxchg8b or
- // cmpxchg16b. So it might be possible to do the patching/unpatching
- // atomically and avoid having to freeze other threads. Note though, that
- // doing it atomically does not help if one of the other threads happens
- // to have its eip in the middle of the bytes you change while you change
- // them.
- unsigned char* target = reinterpret_cast<unsigned char*>(target_function);
-
- // Let's disassemble the preamble of the target function to see if we can
- // patch, and to see how much of the preamble we need to take. We need 5
- // bytes for our jmp instruction, so let's find the minimum number of
- // instructions to get 5 bytes.
- MiniDisassembler disassembler;
- unsigned int preamble_bytes = 0;
- while (preamble_bytes < 5) {
- InstructionType instruction_type =
- disassembler.Disassemble(target + preamble_bytes, &preamble_bytes);
- if (IT_JUMP == instruction_type) {
- ASSERT(false, (L"Unable to patch because there is a jump instruction "
- L"in the first 5 bytes."));
- return SIDESTEP_JUMP_INSTRUCTION;
- } else if (IT_RETURN == instruction_type) {
- ASSERT(false, (L"Unable to patch because function is too short"));
- return SIDESTEP_FUNCTION_TOO_SMALL;
- } else if (IT_GENERIC != instruction_type) {
- ASSERT(false, (L"Disassembler encountered unsupported instruction "
- L"(either unused or unknown"));
- return SIDESTEP_UNSUPPORTED_INSTRUCTION;
- }
- }
-
- if (NULL != bytes_needed)
- *bytes_needed = preamble_bytes + 5;
-
- // Inv: preamble_bytes is the number of bytes (at least 5) that we need to
- // take from the preamble to have whole instructions that are 5 bytes or more
- // in size total. The size of the stub required is cbPreamble + size of
- // jmp (5)
- if (preamble_bytes + 5 > stub_size) {
- NOTREACHED_NT();
- return SIDESTEP_INSUFFICIENT_BUFFER;
- }
-
- // First, copy the preamble that we will overwrite.
- RawMemcpy(reinterpret_cast<void*>(preamble_stub),
- reinterpret_cast<void*>(target), preamble_bytes);
-
- // Now, make a jmp instruction to the rest of the target function (minus the
- // preamble bytes we moved into the stub) and copy it into our preamble-stub.
- // find address to jump to, relative to next address after jmp instruction
-#pragma warning(push)
-#pragma warning(disable:4244)
- // This assignment generates a warning because it is 32 bit specific.
- int relative_offset_to_target_rest
- = ((reinterpret_cast<unsigned char*>(target) + preamble_bytes) -
- (preamble_stub + preamble_bytes + 5));
-#pragma warning(pop)
- // jmp (Jump near, relative, displacement relative to next instruction)
- preamble_stub[preamble_bytes] = ASM_JMP32REL;
- // copy the address
- RawMemcpy(reinterpret_cast<void*>(preamble_stub + preamble_bytes + 1),
- reinterpret_cast<void*>(&relative_offset_to_target_rest), 4);
-
- // Inv: preamble_stub points to assembly code that will execute the
- // original function by first executing the first cbPreamble bytes of the
- // preamble, then jumping to the rest of the function.
-
- // Overwrite the first 5 bytes of the target function with a jump to our
- // replacement function.
- // (Jump near, relative, displacement relative to next instruction)
- target[0] = ASM_JMP32REL;
-
- // Find offset from instruction after jmp, to the replacement function.
-#pragma warning(push)
-#pragma warning(disable:4244)
- int offset_to_replacement_function =
- reinterpret_cast<unsigned char*>(replacement_function) -
- reinterpret_cast<unsigned char*>(target) - 5;
-#pragma warning(pop)
- // complete the jmp instruction
- RawMemcpy(reinterpret_cast<void*>(target + 1),
- reinterpret_cast<void*>(&offset_to_replacement_function), 4);
- // Set any remaining bytes that were moved to the preamble-stub to INT3 so
- // as not to cause confusion (otherwise you might see some strange
- // instructions if you look at the disassembly, or even invalid
- // instructions). Also, by doing this, we will break into the debugger if
- // some code calls into this portion of the code. If this happens, it
- // means that this function cannot be patched using this patcher without
- // further thought.
- if (preamble_bytes > 5) {
- RawMemset(reinterpret_cast<void*>(target + 5), ASM_INT3,
- preamble_bytes - 5);
- }
-
- // Inv: The memory pointed to by target_function now points to a relative
- // jump instruction that jumps over to the preamble_stub. The preamble
- // stub contains the first stub_size bytes of the original target
- // function's preamble code, followed by a relative jump back to the next
- // instruction after the first cbPreamble bytes.
-
- return SIDESTEP_SUCCESS;
-}
-
-}; // namespace sidestep
-
-#undef ASSERT
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep_resolver.cc b/security/sandbox/chromium/sandbox/win/src/sidestep_resolver.cc
deleted file mode 100644
index d5da2fbe9..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep_resolver.cc
+++ /dev/null
@@ -1,204 +0,0 @@
-// 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 "sandbox/win/src/sidestep_resolver.h"
-
-#include <stddef.h>
-
-#include "base/win/pe_image.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sidestep/preamble_patcher.h"
-
-namespace {
-
-const size_t kSizeOfSidestepStub = sidestep::kMaxPreambleStubSize;
-
-struct SidestepThunk {
- char sidestep[kSizeOfSidestepStub]; // Storage for the sidestep stub.
- int internal_thunk; // Dummy member to the beginning of the internal thunk.
-};
-
-struct SmartThunk {
- const void* module_base; // Target module's base.
- const void* interceptor; // Real interceptor.
- SidestepThunk sidestep; // Standard sidestep thunk.
-};
-
-} // namespace
-
-namespace sandbox {
-
-NTSTATUS SidestepResolverThunk::Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) {
- NTSTATUS ret = Init(target_module, interceptor_module, target_name,
- interceptor_name, interceptor_entry_point,
- thunk_storage, storage_bytes);
- if (!NT_SUCCESS(ret))
- return ret;
-
- SidestepThunk* thunk = reinterpret_cast<SidestepThunk*>(thunk_storage);
-
- size_t internal_bytes = storage_bytes - kSizeOfSidestepStub;
- if (!SetInternalThunk(&thunk->internal_thunk, internal_bytes, thunk_storage,
- interceptor_))
- return STATUS_BUFFER_TOO_SMALL;
-
- AutoProtectMemory memory;
- ret = memory.ChangeProtection(target_, kSizeOfSidestepStub, PAGE_READWRITE);
- if (!NT_SUCCESS(ret))
- return ret;
-
- sidestep::SideStepError rv = sidestep::PreamblePatcher::Patch(
- target_, reinterpret_cast<void*>(&thunk->internal_thunk), thunk_storage,
- kSizeOfSidestepStub);
-
- if (sidestep::SIDESTEP_INSUFFICIENT_BUFFER == rv)
- return STATUS_BUFFER_TOO_SMALL;
-
- if (sidestep::SIDESTEP_SUCCESS != rv)
- return STATUS_UNSUCCESSFUL;
-
- if (storage_used)
- *storage_used = GetThunkSize();
-
- return ret;
-}
-
-size_t SidestepResolverThunk::GetThunkSize() const {
- return GetInternalThunkSize() + kSizeOfSidestepStub;
-}
-
-// This is basically a wrapper around the normal sidestep patch that extends
-// the thunk to use a chained interceptor. It uses the fact that
-// SetInternalThunk generates the code to pass as the first parameter whatever
-// it receives as original_function; we let SidestepResolverThunk set this value
-// to its saved code, and then we change it to our thunk data.
-NTSTATUS SmartSidestepResolverThunk::Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) {
- if (storage_bytes < GetThunkSize())
- return STATUS_BUFFER_TOO_SMALL;
-
- SmartThunk* thunk = reinterpret_cast<SmartThunk*>(thunk_storage);
- thunk->module_base = target_module;
-
- NTSTATUS ret;
- if (interceptor_entry_point) {
- thunk->interceptor = interceptor_entry_point;
- } else {
- ret = ResolveInterceptor(interceptor_module, interceptor_name,
- &thunk->interceptor);
- if (!NT_SUCCESS(ret))
- return ret;
- }
-
- // Perform a standard sidestep patch on the last part of the thunk, but point
- // to our internal smart interceptor.
- size_t standard_bytes = storage_bytes - offsetof(SmartThunk, sidestep);
- ret = SidestepResolverThunk::Setup(target_module, interceptor_module,
- target_name, NULL, &SmartStub,
- &thunk->sidestep, standard_bytes, NULL);
- if (!NT_SUCCESS(ret))
- return ret;
-
- // Fix the internal thunk to pass the whole buffer to the interceptor.
- SetInternalThunk(&thunk->sidestep.internal_thunk, GetInternalThunkSize(),
- thunk_storage, &SmartStub);
-
- if (storage_used)
- *storage_used = GetThunkSize();
-
- return ret;
-}
-
-size_t SmartSidestepResolverThunk::GetThunkSize() const {
- return GetInternalThunkSize() + kSizeOfSidestepStub +
- offsetof(SmartThunk, sidestep);
-}
-
-// This code must basically either call the intended interceptor or skip the
-// call and invoke instead the original function. In any case, we are saving
-// the registers that may be trashed by our c++ code.
-//
-// This function is called with a first parameter inserted by us, that points
-// to our SmartThunk. When we call the interceptor we have to replace this
-// parameter with the one expected by that function (stored inside our
-// structure); on the other hand, when we skip the interceptor we have to remove
-// that extra argument before calling the original function.
-//
-// When we skip the interceptor, the transformation of the stack looks like:
-// On Entry: On Use: On Exit:
-// [param 2] = first real argument [param 2] (esp+1c) [param 2]
-// [param 1] = our SmartThunk [param 1] (esp+18) [ret address]
-// [ret address] = real caller [ret address] (esp+14) [xxx]
-// [xxx] [addr to jump to] (esp+10) [xxx]
-// [xxx] [saved eax] [xxx]
-// [xxx] [saved ebx] [xxx]
-// [xxx] [saved ecx] [xxx]
-// [xxx] [saved edx] [xxx]
-__declspec(naked)
-void SmartSidestepResolverThunk::SmartStub() {
- __asm {
- push eax // Space for the jump.
- push eax // Save registers.
- push ebx
- push ecx
- push edx
- mov ebx, [esp + 0x18] // First parameter = SmartThunk.
- mov edx, [esp + 0x14] // Get the return address.
- mov eax, [ebx]SmartThunk.module_base
- push edx
- push eax
- call SmartSidestepResolverThunk::IsInternalCall
- add esp, 8
-
- test eax, eax
- lea edx, [ebx]SmartThunk.sidestep // The original function.
- jz call_interceptor
-
- // Skip this call
- mov ecx, [esp + 0x14] // Return address.
- mov [esp + 0x18], ecx // Remove first parameter.
- mov [esp + 0x10], edx
- pop edx // Restore registers.
- pop ecx
- pop ebx
- pop eax
- ret 4 // Jump to original function.
-
- call_interceptor:
- mov ecx, [ebx]SmartThunk.interceptor
- mov [esp + 0x18], edx // Replace first parameter.
- mov [esp + 0x10], ecx
- pop edx // Restore registers.
- pop ecx
- pop ebx
- pop eax
- ret // Jump to original function.
- }
-}
-
-bool SmartSidestepResolverThunk::IsInternalCall(const void* base,
- void* return_address) {
- DCHECK_NT(base);
- DCHECK_NT(return_address);
-
- base::win::PEImage pe(base);
- if (pe.GetImageSectionFromAddr(return_address))
- return true;
- return false;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sidestep_resolver.h b/security/sandbox/chromium/sandbox/win/src/sidestep_resolver.h
deleted file mode 100644
index 8088272ee..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sidestep_resolver.h
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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 SANDBOX_SRC_SIDESTEP_RESOLVER_H__
-#define SANDBOX_SRC_SIDESTEP_RESOLVER_H__
-
-#include <stddef.h>
-
-#include "base/macros.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/resolver.h"
-
-namespace sandbox {
-
-// This is the concrete resolver used to perform sidestep interceptions.
-class SidestepResolverThunk : public ResolverThunk {
- public:
- SidestepResolverThunk() {}
- ~SidestepResolverThunk() override {}
-
- // Implementation of Resolver::Setup.
- NTSTATUS Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) override;
-
- // Implementation of Resolver::GetThunkSize.
- size_t GetThunkSize() const override;
-
- private:
- DISALLOW_COPY_AND_ASSIGN(SidestepResolverThunk);
-};
-
-// This is the concrete resolver used to perform smart sidestep interceptions.
-// This means basically a sidestep interception that skips the interceptor when
-// the caller resides on the same dll being intercepted. It is intended as
-// a helper only, because that determination is not infallible.
-class SmartSidestepResolverThunk : public SidestepResolverThunk {
- public:
- SmartSidestepResolverThunk() {}
- ~SmartSidestepResolverThunk() override {}
-
- // Implementation of Resolver::Setup.
- NTSTATUS Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) override;
-
- // Implementation of Resolver::GetThunkSize.
- size_t GetThunkSize() const override;
-
- private:
- // Performs the actual call to the interceptor if the conditions are correct
- // (as determined by IsInternalCall).
- static void SmartStub();
-
- // Returns true if return_address is inside the module loaded at base.
- static bool IsInternalCall(const void* base, void* return_address);
-
- DISALLOW_COPY_AND_ASSIGN(SmartSidestepResolverThunk);
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_SRC_SIDESTEP_RESOLVER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sync_dispatcher.cc b/security/sandbox/chromium/sandbox/win/src/sync_dispatcher.cc
deleted file mode 100644
index 2e5d1c50f..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sync_dispatcher.cc
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright (c) 2013 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 "sandbox/win/src/sync_dispatcher.h"
-
-#include <stdint.h>
-
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/interceptors.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_broker.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sync_interception.h"
-#include "sandbox/win/src/sync_policy.h"
-
-namespace sandbox {
-
-SyncDispatcher::SyncDispatcher(PolicyBase* policy_base)
- : policy_base_(policy_base) {
- static const IPCCall create_params = {
- {IPC_CREATEEVENT_TAG, {WCHAR_TYPE, UINT32_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(&SyncDispatcher::CreateEvent)};
-
- static const IPCCall open_params = {
- {IPC_OPENEVENT_TAG, {WCHAR_TYPE, UINT32_TYPE}},
- reinterpret_cast<CallbackGeneric>(&SyncDispatcher::OpenEvent)};
-
- ipc_calls_.push_back(create_params);
- ipc_calls_.push_back(open_params);
-}
-
-bool SyncDispatcher::SetupService(InterceptionManager* manager,
- int service) {
- if (service == IPC_CREATEEVENT_TAG) {
- return INTERCEPT_NT(manager, NtCreateEvent, CREATE_EVENT_ID, 24);
- }
- return (service == IPC_OPENEVENT_TAG) &&
- INTERCEPT_NT(manager, NtOpenEvent, OPEN_EVENT_ID, 16);
-}
-
-bool SyncDispatcher::CreateEvent(IPCInfo* ipc,
- base::string16* name,
- uint32_t event_type,
- uint32_t initial_state) {
- const wchar_t* event_name = name->c_str();
- CountedParameterSet<NameBased> params;
- params[NameBased::NAME] = ParamPickerMake(event_name);
-
- EvalResult result = policy_base_->EvalPolicy(IPC_CREATEEVENT_TAG,
- params.GetBase());
- HANDLE handle = NULL;
- // Return operation status on the IPC.
- ipc->return_info.nt_status = SyncPolicy::CreateEventAction(
- result, *ipc->client_info, *name, event_type, initial_state, &handle);
- ipc->return_info.handle = handle;
- return true;
-}
-
-bool SyncDispatcher::OpenEvent(IPCInfo* ipc,
- base::string16* name,
- uint32_t desired_access) {
- const wchar_t* event_name = name->c_str();
-
- CountedParameterSet<OpenEventParams> params;
- params[OpenEventParams::NAME] = ParamPickerMake(event_name);
- params[OpenEventParams::ACCESS] = ParamPickerMake(desired_access);
-
- EvalResult result = policy_base_->EvalPolicy(IPC_OPENEVENT_TAG,
- params.GetBase());
- HANDLE handle = NULL;
- // Return operation status on the IPC.
- ipc->return_info.nt_status = SyncPolicy::OpenEventAction(
- result, *ipc->client_info, *name, desired_access, &handle);
- ipc->return_info.handle = handle;
- return true;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sync_dispatcher.h b/security/sandbox/chromium/sandbox/win/src/sync_dispatcher.h
deleted file mode 100644
index 8a2a0e582..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sync_dispatcher.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// 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 SANDBOX_SRC_SYNC_DISPATCHER_H_
-#define SANDBOX_SRC_SYNC_DISPATCHER_H_
-
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-namespace sandbox {
-
-// This class handles sync-related IPC calls.
-class SyncDispatcher : public Dispatcher {
- public:
- explicit SyncDispatcher(PolicyBase* policy_base);
- ~SyncDispatcher() override {}
-
- // Dispatcher interface.
- bool SetupService(InterceptionManager* manager, int service) override;
-
-private:
- // Processes IPC requests coming from calls to CreateEvent in the target.
- bool CreateEvent(IPCInfo* ipc,
- base::string16* name,
- uint32_t event_type,
- uint32_t initial_state);
-
- // Processes IPC requests coming from calls to OpenEvent in the target.
- bool OpenEvent(IPCInfo* ipc, base::string16* name, uint32_t desired_access);
-
- PolicyBase* policy_base_;
- DISALLOW_COPY_AND_ASSIGN(SyncDispatcher);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SYNC_DISPATCHER_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/sync_interception.cc b/security/sandbox/chromium/sandbox/win/src/sync_interception.cc
deleted file mode 100644
index 35d092492..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sync_interception.cc
+++ /dev/null
@@ -1,178 +0,0 @@
-// 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 "sandbox/win/src/sync_interception.h"
-
-#include <stdint.h>
-
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/policy_target.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-#include "sandbox/win/src/target_services.h"
-#include "mozilla/sandboxing/sandboxLogging.h"
-
-namespace sandbox {
-
-ResultCode ProxyCreateEvent(LPCWSTR name,
- uint32_t initial_state,
- EVENT_TYPE event_type,
- void* ipc_memory,
- CrossCallReturn* answer) {
- CountedParameterSet<NameBased> params;
- params[NameBased::NAME] = ParamPickerMake(name);
-
- if (!QueryBroker(IPC_CREATEEVENT_TAG, params.GetBase()))
- return SBOX_ERROR_GENERIC;
-
- SharedMemIPCClient ipc(ipc_memory);
- ResultCode code = CrossCall(ipc, IPC_CREATEEVENT_TAG, name, event_type,
- initial_state, answer);
- return code;
-}
-
-ResultCode ProxyOpenEvent(LPCWSTR name,
- uint32_t desired_access,
- void* ipc_memory,
- CrossCallReturn* answer) {
- CountedParameterSet<OpenEventParams> params;
- params[OpenEventParams::NAME] = ParamPickerMake(name);
- params[OpenEventParams::ACCESS] = ParamPickerMake(desired_access);
-
- if (!QueryBroker(IPC_OPENEVENT_TAG, params.GetBase()))
- return SBOX_ERROR_GENERIC;
-
- SharedMemIPCClient ipc(ipc_memory);
- ResultCode code = CrossCall(ipc, IPC_OPENEVENT_TAG, name, desired_access,
- answer);
-
- return code;
-}
-
-NTSTATUS WINAPI TargetNtCreateEvent(NtCreateEventFunction orig_CreateEvent,
- PHANDLE event_handle,
- ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes,
- EVENT_TYPE event_type,
- BOOLEAN initial_state) {
- NTSTATUS status = orig_CreateEvent(event_handle, desired_access,
- object_attributes, event_type,
- initial_state);
- if (status != STATUS_ACCESS_DENIED || !object_attributes)
- return status;
-
- mozilla::sandboxing::LogBlocked("NtCreatEvent",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
-
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- do {
- if (!ValidParameter(event_handle, sizeof(HANDLE), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (memory == NULL)
- break;
-
- OBJECT_ATTRIBUTES object_attribs_copy = *object_attributes;
- // The RootDirectory points to BaseNamedObjects. We can ignore it.
- object_attribs_copy.RootDirectory = NULL;
-
- wchar_t* name = NULL;
- uint32_t attributes = 0;
- NTSTATUS ret = AllocAndCopyName(&object_attribs_copy, &name, &attributes,
- NULL);
- if (!NT_SUCCESS(ret) || name == NULL)
- break;
-
- CrossCallReturn answer = {0};
- answer.nt_status = status;
- ResultCode code = ProxyCreateEvent(name, initial_state, event_type, memory,
- &answer);
- operator delete(name, NT_ALLOC);
-
- if (code != SBOX_ALL_OK) {
- status = answer.nt_status;
- break;
- }
- __try {
- *event_handle = answer.handle;
- status = STATUS_SUCCESS;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
- mozilla::sandboxing::LogAllowed("NtCreateEvent",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- } while (false);
-
- return status;
-}
-
-NTSTATUS WINAPI TargetNtOpenEvent(NtOpenEventFunction orig_OpenEvent,
- PHANDLE event_handle,
- ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes) {
- NTSTATUS status = orig_OpenEvent(event_handle, desired_access,
- object_attributes);
- if (status != STATUS_ACCESS_DENIED || !object_attributes)
- return status;
-
- mozilla::sandboxing::LogBlocked("NtOpenEvent",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- //
- // We don't trust that the IPC can work this early.
- if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
- return status;
-
- do {
- if (!ValidParameter(event_handle, sizeof(HANDLE), WRITE))
- break;
-
- void* memory = GetGlobalIPCMemory();
- if (memory == NULL)
- break;
-
- OBJECT_ATTRIBUTES object_attribs_copy = *object_attributes;
- // The RootDirectory points to BaseNamedObjects. We can ignore it.
- object_attribs_copy.RootDirectory = NULL;
-
- wchar_t* name = NULL;
- uint32_t attributes = 0;
- NTSTATUS ret = AllocAndCopyName(&object_attribs_copy, &name, &attributes,
- NULL);
- if (!NT_SUCCESS(ret) || name == NULL)
- break;
-
- CrossCallReturn answer = {0};
- answer.nt_status = status;
- ResultCode code = ProxyOpenEvent(name, desired_access, memory, &answer);
- operator delete(name, NT_ALLOC);
-
- if (code != SBOX_ALL_OK) {
- status = answer.nt_status;
- break;
- }
- __try {
- *event_handle = answer.handle;
- status = STATUS_SUCCESS;
- } __except(EXCEPTION_EXECUTE_HANDLER) {
- break;
- }
- mozilla::sandboxing::LogAllowed("NtOpenEvent",
- object_attributes->ObjectName->Buffer,
- object_attributes->ObjectName->Length);
- } while (false);
-
- return status;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sync_interception.h b/security/sandbox/chromium/sandbox/win/src/sync_interception.h
deleted file mode 100644
index 0f985a8ed..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sync_interception.h
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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 "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_SYNC_INTERCEPTION_H__
-#define SANDBOX_SRC_SYNC_INTERCEPTION_H__
-
-namespace sandbox {
-
-extern "C" {
-
-typedef NTSTATUS (WINAPI* NtCreateEventFunction) (
- PHANDLE EventHandle,
- ACCESS_MASK DesiredAccess,
- POBJECT_ATTRIBUTES ObjectAttributes,
- EVENT_TYPE EventType,
- BOOLEAN InitialState);
-
-typedef NTSTATUS (WINAPI *NtOpenEventFunction) (
- PHANDLE EventHandle,
- ACCESS_MASK DesiredAccess,
- POBJECT_ATTRIBUTES ObjectAttributes);
-
-// Interceptors for NtCreateEvent/NtOpenEvent
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateEvent(
- NtCreateEventFunction orig_CreateEvent,
- PHANDLE event_handle,
- ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes,
- EVENT_TYPE event_type,
- BOOLEAN initial_state);
-
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenEvent(
- NtOpenEventFunction orig_OpenEvent,
- PHANDLE event_handle,
- ACCESS_MASK desired_access,
- POBJECT_ATTRIBUTES object_attributes);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SYNC_INTERCEPTION_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sync_policy.cc b/security/sandbox/chromium/sandbox/win/src/sync_policy.cc
deleted file mode 100644
index 7ef094ff7..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sync_policy.cc
+++ /dev/null
@@ -1,246 +0,0 @@
-// 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 <stdint.h>
-
-#include <string>
-
-#include "sandbox/win/src/sync_policy.h"
-
-#include "base/logging.h"
-#include "base/strings/stringprintf.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/policy_engine_opcodes.h"
-#include "sandbox/win/src/policy_params.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sandbox_utils.h"
-#include "sandbox/win/src/sync_interception.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace sandbox {
-
-// Provides functionality to resolve a symbolic link within the object
-// directory passed in.
-NTSTATUS ResolveSymbolicLink(const base::string16& directory_name,
- const base::string16& name,
- base::string16* target) {
- NtOpenDirectoryObjectFunction NtOpenDirectoryObject = NULL;
- ResolveNTFunctionPtr("NtOpenDirectoryObject", &NtOpenDirectoryObject);
-
- NtQuerySymbolicLinkObjectFunction NtQuerySymbolicLinkObject = NULL;
- ResolveNTFunctionPtr("NtQuerySymbolicLinkObject",
- &NtQuerySymbolicLinkObject);
-
- NtOpenSymbolicLinkObjectFunction NtOpenSymbolicLinkObject = NULL;
- ResolveNTFunctionPtr("NtOpenSymbolicLinkObject", &NtOpenSymbolicLinkObject);
-
- NtCloseFunction NtClose = NULL;
- ResolveNTFunctionPtr("NtClose", &NtClose);
-
- OBJECT_ATTRIBUTES symbolic_link_directory_attributes = {};
- UNICODE_STRING symbolic_link_directory_string = {};
- InitObjectAttribs(directory_name, OBJ_CASE_INSENSITIVE, NULL,
- &symbolic_link_directory_attributes,
- &symbolic_link_directory_string, NULL);
-
- HANDLE symbolic_link_directory = NULL;
- NTSTATUS status = NtOpenDirectoryObject(&symbolic_link_directory,
- DIRECTORY_QUERY,
- &symbolic_link_directory_attributes);
- if (!NT_SUCCESS(status))
- return status;
-
- OBJECT_ATTRIBUTES symbolic_link_attributes = {};
- UNICODE_STRING name_string = {};
- InitObjectAttribs(name, OBJ_CASE_INSENSITIVE, symbolic_link_directory,
- &symbolic_link_attributes, &name_string, NULL);
-
- HANDLE symbolic_link = NULL;
- status = NtOpenSymbolicLinkObject(&symbolic_link, GENERIC_READ,
- &symbolic_link_attributes);
- CHECK(NT_SUCCESS(NtClose(symbolic_link_directory)));
- if (!NT_SUCCESS(status))
- return status;
-
- UNICODE_STRING target_path = {};
- unsigned long target_length = 0;
- status = NtQuerySymbolicLinkObject(symbolic_link, &target_path,
- &target_length);
- if (status != STATUS_BUFFER_TOO_SMALL) {
- CHECK(NT_SUCCESS(NtClose(symbolic_link)));
- return status;
- }
-
- target_path.Length = 0;
- target_path.MaximumLength = static_cast<USHORT>(target_length);
- target_path.Buffer = new wchar_t[target_path.MaximumLength + 1];
- status = NtQuerySymbolicLinkObject(symbolic_link, &target_path,
- &target_length);
- if (NT_SUCCESS(status))
- target->assign(target_path.Buffer, target_length);
-
- CHECK(NT_SUCCESS(NtClose(symbolic_link)));
- delete[] target_path.Buffer;
- return status;
-}
-
-NTSTATUS GetBaseNamedObjectsDirectory(HANDLE* directory) {
- static HANDLE base_named_objects_handle = NULL;
- if (base_named_objects_handle) {
- *directory = base_named_objects_handle;
- return STATUS_SUCCESS;
- }
-
- NtOpenDirectoryObjectFunction NtOpenDirectoryObject = NULL;
- ResolveNTFunctionPtr("NtOpenDirectoryObject", &NtOpenDirectoryObject);
-
- DWORD session_id = 0;
- ProcessIdToSessionId(::GetCurrentProcessId(), &session_id);
-
- base::string16 base_named_objects_path;
-
- NTSTATUS status = ResolveSymbolicLink(L"\\Sessions\\BNOLINKS",
- base::StringPrintf(L"%d", session_id),
- &base_named_objects_path);
- if (!NT_SUCCESS(status)) {
- DLOG(ERROR) << "Failed to resolve BaseNamedObjects path. Error: "
- << status;
- return status;
- }
-
- UNICODE_STRING directory_name = {};
- OBJECT_ATTRIBUTES object_attributes = {};
- InitObjectAttribs(base_named_objects_path, OBJ_CASE_INSENSITIVE, NULL,
- &object_attributes, &directory_name, NULL);
- status = NtOpenDirectoryObject(&base_named_objects_handle,
- DIRECTORY_ALL_ACCESS,
- &object_attributes);
- if (NT_SUCCESS(status))
- *directory = base_named_objects_handle;
- return status;
-}
-
-bool SyncPolicy::GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy) {
- base::string16 mod_name(name);
- if (mod_name.empty()) {
- return false;
- }
-
- if (TargetPolicy::EVENTS_ALLOW_ANY != semantics &&
- TargetPolicy::EVENTS_ALLOW_READONLY != semantics) {
- // Other flags are not valid for sync policy yet.
- NOTREACHED();
- return false;
- }
-
- // Add the open rule.
- EvalResult result = ASK_BROKER;
- PolicyRule open(result);
-
- if (!open.AddStringMatch(IF, OpenEventParams::NAME, name, CASE_INSENSITIVE))
- return false;
-
- if (TargetPolicy::EVENTS_ALLOW_READONLY == semantics) {
- // We consider all flags that are not known to be readonly as potentially
- // used for write.
- uint32_t allowed_flags = SYNCHRONIZE | GENERIC_READ | READ_CONTROL;
- uint32_t restricted_flags = ~allowed_flags;
- open.AddNumberMatch(IF_NOT, OpenEventParams::ACCESS, restricted_flags, AND);
- }
-
- if (!policy->AddRule(IPC_OPENEVENT_TAG, &open))
- return false;
-
- // If it's not a read only, add the create rule.
- if (TargetPolicy::EVENTS_ALLOW_READONLY != semantics) {
- PolicyRule create(result);
- if (!create.AddStringMatch(IF, NameBased::NAME, name, CASE_INSENSITIVE))
- return false;
-
- if (!policy->AddRule(IPC_CREATEEVENT_TAG, &create))
- return false;
- }
-
- return true;
-}
-
-NTSTATUS SyncPolicy::CreateEventAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& event_name,
- uint32_t event_type,
- uint32_t initial_state,
- HANDLE* handle) {
- NtCreateEventFunction NtCreateEvent = NULL;
- ResolveNTFunctionPtr("NtCreateEvent", &NtCreateEvent);
-
- // The only action supported is ASK_BROKER which means create the requested
- // file as specified.
- if (ASK_BROKER != eval_result)
- return false;
-
- HANDLE object_directory = NULL;
- NTSTATUS status = GetBaseNamedObjectsDirectory(&object_directory);
- if (status != STATUS_SUCCESS)
- return status;
-
- UNICODE_STRING unicode_event_name = {};
- OBJECT_ATTRIBUTES object_attributes = {};
- InitObjectAttribs(event_name, OBJ_CASE_INSENSITIVE, object_directory,
- &object_attributes, &unicode_event_name, NULL);
-
- HANDLE local_handle = NULL;
- status = NtCreateEvent(&local_handle, EVENT_ALL_ACCESS, &object_attributes,
- static_cast<EVENT_TYPE>(event_type),
- static_cast<BOOLEAN>(initial_state));
- if (NULL == local_handle)
- return status;
-
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- client_info.process, handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- return status;
-}
-
-NTSTATUS SyncPolicy::OpenEventAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& event_name,
- uint32_t desired_access,
- HANDLE* handle) {
- NtOpenEventFunction NtOpenEvent = NULL;
- ResolveNTFunctionPtr("NtOpenEvent", &NtOpenEvent);
-
- // The only action supported is ASK_BROKER which means create the requested
- // event as specified.
- if (ASK_BROKER != eval_result)
- return false;
-
- HANDLE object_directory = NULL;
- NTSTATUS status = GetBaseNamedObjectsDirectory(&object_directory);
- if (status != STATUS_SUCCESS)
- return status;
-
- UNICODE_STRING unicode_event_name = {};
- OBJECT_ATTRIBUTES object_attributes = {};
- InitObjectAttribs(event_name, OBJ_CASE_INSENSITIVE, object_directory,
- &object_attributes, &unicode_event_name, NULL);
-
- HANDLE local_handle = NULL;
- status = NtOpenEvent(&local_handle, desired_access, &object_attributes);
- if (NULL == local_handle)
- return status;
-
- if (!::DuplicateHandle(::GetCurrentProcess(), local_handle,
- client_info.process, handle, 0, FALSE,
- DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) {
- return STATUS_ACCESS_DENIED;
- }
- return status;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sync_policy.h b/security/sandbox/chromium/sandbox/win/src/sync_policy.h
deleted file mode 100644
index 24e5c7d87..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sync_policy.h
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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 SANDBOX_SRC_SYNC_POLICY_H__
-#define SANDBOX_SRC_SYNC_POLICY_H__
-
-#include <stdint.h>
-
-#include <string>
-
-#include "base/strings/string16.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/sandbox_policy.h"
-
-namespace sandbox {
-
-enum EvalResult;
-
-// This class centralizes most of the knowledge related to sync policy
-class SyncPolicy {
- public:
- // Creates the required low-level policy rules to evaluate a high-level
- // policy rule for sync calls, in particular open or create actions.
- // name is the sync object name, semantics is the desired semantics for the
- // open or create and policy is the policy generator to which the rules are
- // going to be added.
- static bool GenerateRules(const wchar_t* name,
- TargetPolicy::Semantics semantics,
- LowLevelPolicy* policy);
-
- // Performs the desired policy action on a request.
- // client_info is the target process that is making the request and
- // eval_result is the desired policy action to accomplish.
- static NTSTATUS CreateEventAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& event_name,
- uint32_t event_type,
- uint32_t initial_state,
- HANDLE* handle);
- static NTSTATUS OpenEventAction(EvalResult eval_result,
- const ClientInfo& client_info,
- const base::string16& event_name,
- uint32_t desired_access,
- HANDLE* handle);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_SYNC_POLICY_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/sync_policy_test.cc b/security/sandbox/chromium/sandbox/win/src/sync_policy_test.cc
deleted file mode 100644
index 875bc4b2c..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sync_policy_test.cc
+++ /dev/null
@@ -1,149 +0,0 @@
-// 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 "sandbox/win/src/sync_policy_test.h"
-
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_policy.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-SBOX_TESTS_COMMAND int Event_Open(int argc, wchar_t **argv) {
- if (argc != 2)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- DWORD desired_access = SYNCHRONIZE;
- if (L'f' == argv[0][0])
- desired_access = EVENT_ALL_ACCESS;
-
- base::win::ScopedHandle event_open(::OpenEvent(
- desired_access, FALSE, argv[1]));
- DWORD error_open = ::GetLastError();
-
- if (event_open.IsValid())
- return SBOX_TEST_SUCCEEDED;
-
- if (ERROR_ACCESS_DENIED == error_open ||
- ERROR_BAD_PATHNAME == error_open ||
- ERROR_FILE_NOT_FOUND == error_open)
- return SBOX_TEST_DENIED;
-
- return SBOX_TEST_FAILED;
-}
-
-SBOX_TESTS_COMMAND int Event_CreateOpen(int argc, wchar_t **argv) {
- if (argc < 2 || argc > 3)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- wchar_t *event_name = NULL;
- if (3 == argc)
- event_name = argv[2];
-
- BOOL manual_reset = FALSE;
- BOOL initial_state = FALSE;
- if (L't' == argv[0][0])
- manual_reset = TRUE;
- if (L't' == argv[1][0])
- initial_state = TRUE;
-
- base::win::ScopedHandle event_create(::CreateEvent(
- NULL, manual_reset, initial_state, event_name));
- DWORD error_create = ::GetLastError();
- base::win::ScopedHandle event_open;
- if (event_name)
- event_open.Set(::OpenEvent(EVENT_ALL_ACCESS, FALSE, event_name));
-
- if (event_create.IsValid()) {
- DWORD wait = ::WaitForSingleObject(event_create.Get(), 0);
- if (initial_state && WAIT_OBJECT_0 != wait)
- return SBOX_TEST_FAILED;
-
- if (!initial_state && WAIT_TIMEOUT != wait)
- return SBOX_TEST_FAILED;
- }
-
- if (event_name) {
- // Both event_open and event_create have to be valid.
- if (event_open.IsValid() && event_create.IsValid())
- return SBOX_TEST_SUCCEEDED;
-
- if ((event_open.IsValid() && !event_create.IsValid()) ||
- (!event_open.IsValid() && event_create.IsValid())) {
- return SBOX_TEST_FAILED;
- }
- } else {
- // Only event_create has to be valid.
- if (event_create.Get())
- return SBOX_TEST_SUCCEEDED;
- }
-
- if (ERROR_ACCESS_DENIED == error_create ||
- ERROR_BAD_PATHNAME == error_create)
- return SBOX_TEST_DENIED;
-
- return SBOX_TEST_FAILED;
-}
-
-// Tests the creation of events using all the possible combinations.
-TEST(SyncPolicyTest, TestEvent) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
- TargetPolicy::EVENTS_ALLOW_ANY,
- L"test1"));
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
- TargetPolicy::EVENTS_ALLOW_ANY,
- L"test2"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f t"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t t"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f test1"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f test2"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f t test1"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t t test2"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f f test3"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t f test4"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f t test3"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t t test4"));
-}
-
-// Tests opening events with read only access.
-TEST(SyncPolicyTest, TestEventReadOnly) {
- TestRunner runner;
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
- TargetPolicy::EVENTS_ALLOW_READONLY,
- L"test1"));
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
- TargetPolicy::EVENTS_ALLOW_READONLY,
- L"test2"));
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
- TargetPolicy::EVENTS_ALLOW_READONLY,
- L"test5"));
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
- TargetPolicy::EVENTS_ALLOW_READONLY,
- L"test6"));
-
- base::win::ScopedHandle handle1(::CreateEvent(NULL, FALSE, FALSE, L"test1"));
- base::win::ScopedHandle handle2(::CreateEvent(NULL, FALSE, FALSE, L"test2"));
- base::win::ScopedHandle handle3(::CreateEvent(NULL, FALSE, FALSE, L"test3"));
- base::win::ScopedHandle handle4(::CreateEvent(NULL, FALSE, FALSE, L"test4"));
-
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test1"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_Open s test2"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test3"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open s test4"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f f test5"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t f test6"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f t test5"));
- EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t t test6"));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/sync_policy_test.h b/security/sandbox/chromium/sandbox/win/src/sync_policy_test.h
deleted file mode 100644
index 4f354b35b..000000000
--- a/security/sandbox/chromium/sandbox/win/src/sync_policy_test.h
+++ /dev/null
@@ -1,18 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_WIN_SRC_SYNC_POLICY_TEST_H_
-#define SANDBOX_WIN_SRC_SYNC_POLICY_TEST_H_
-
-#include "sandbox/win/tests/common/controller.h"
-
-namespace sandbox {
-
-// Opens the named event received on argv[1]. The requested access is
-// EVENT_ALL_ACCESS if argv[0] starts with 'f', or SYNCHRONIZE otherwise.
-SBOX_TESTS_COMMAND int Event_Open(int argc, wchar_t **argv);
-
-} // namespace sandbox
-
-#endif // SANDBOX_WIN_SRC_SYNC_POLICY_TEST_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/target_interceptions.cc b/security/sandbox/chromium/sandbox/win/src/target_interceptions.cc
deleted file mode 100644
index e6b0dcf78..000000000
--- a/security/sandbox/chromium/sandbox/win/src/target_interceptions.cc
+++ /dev/null
@@ -1,100 +0,0 @@
-// 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 "sandbox/win/src/target_interceptions.h"
-
-#include "sandbox/win/src/interception_agent.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/target_services.h"
-
-namespace sandbox {
-
-SANDBOX_INTERCEPT NtExports g_nt;
-
-// Hooks NtMapViewOfSection to detect the load of DLLs. If hot patching is
-// required for this dll, this functions patches it.
-NTSTATUS WINAPI TargetNtMapViewOfSection(
- NtMapViewOfSectionFunction orig_MapViewOfSection, HANDLE section,
- HANDLE process, PVOID *base, ULONG_PTR zero_bits, SIZE_T commit_size,
- PLARGE_INTEGER offset, PSIZE_T view_size, SECTION_INHERIT inherit,
- ULONG allocation_type, ULONG protect) {
- NTSTATUS ret = orig_MapViewOfSection(section, process, base, zero_bits,
- commit_size, offset, view_size, inherit,
- allocation_type, protect);
-
- static int s_load_count = 0;
- if (1 == s_load_count) {
- SandboxFactory::GetTargetServices()->GetState()->SetKernel32Loaded();
- s_load_count = 2;
- }
-
- do {
- if (!NT_SUCCESS(ret))
- break;
-
- if (!InitHeap())
- break;
-
- if (!IsSameProcess(process))
- break;
-
- if (!IsValidImageSection(section, base, offset, view_size))
- break;
-
- UINT image_flags;
- UNICODE_STRING* module_name =
- GetImageInfoFromModule(reinterpret_cast<HMODULE>(*base), &image_flags);
- UNICODE_STRING* file_name = GetBackingFilePath(*base);
-
- if ((!module_name) && (image_flags & MODULE_HAS_CODE)) {
- // If the module has no exports we retrieve the module name from the
- // full path of the mapped section.
- module_name = ExtractModuleName(file_name);
- }
-
- InterceptionAgent* agent = InterceptionAgent::GetInterceptionAgent();
-
- if (agent) {
- if (!agent->OnDllLoad(file_name, module_name, *base)) {
- // Interception agent is demanding to un-map the module.
- g_nt.UnmapViewOfSection(process, *base);
- ret = STATUS_UNSUCCESSFUL;
- }
- }
-
- if (module_name)
- operator delete(module_name, NT_ALLOC);
-
- if (file_name)
- operator delete(file_name, NT_ALLOC);
-
- } while (false);
-
- if (!s_load_count)
- s_load_count = 1;
-
- return ret;
-}
-
-NTSTATUS WINAPI TargetNtUnmapViewOfSection(
- NtUnmapViewOfSectionFunction orig_UnmapViewOfSection, HANDLE process,
- PVOID base) {
- NTSTATUS ret = orig_UnmapViewOfSection(process, base);
-
- if (!NT_SUCCESS(ret))
- return ret;
-
- if (!IsSameProcess(process))
- return ret;
-
- InterceptionAgent* agent = InterceptionAgent::GetInterceptionAgent();
-
- if (agent)
- agent->OnDllUnload(base);
-
- return ret;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/target_interceptions.h b/security/sandbox/chromium/sandbox/win/src/target_interceptions.h
deleted file mode 100644
index f4805fec5..000000000
--- a/security/sandbox/chromium/sandbox/win/src/target_interceptions.h
+++ /dev/null
@@ -1,35 +0,0 @@
-// 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 "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-#ifndef SANDBOX_SRC_TARGET_INTERCEPTIONS_H__
-#define SANDBOX_SRC_TARGET_INTERCEPTIONS_H__
-
-namespace sandbox {
-
-extern "C" {
-
-// Interception of NtMapViewOfSection on the child process.
-// It should never be called directly. This function provides the means to
-// detect dlls being loaded, so we can patch them if needed.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtMapViewOfSection(
- NtMapViewOfSectionFunction orig_MapViewOfSection, HANDLE section,
- HANDLE process, PVOID *base, ULONG_PTR zero_bits, SIZE_T commit_size,
- PLARGE_INTEGER offset, PSIZE_T view_size, SECTION_INHERIT inherit,
- ULONG allocation_type, ULONG protect);
-
-// Interception of NtUnmapViewOfSection on the child process.
-// It should never be called directly. This function provides the means to
-// detect dlls being unloaded, so we can clean up our interceptions.
-SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtUnmapViewOfSection(
- NtUnmapViewOfSectionFunction orig_UnmapViewOfSection, HANDLE process,
- PVOID base);
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_TARGET_INTERCEPTIONS_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/target_process.cc b/security/sandbox/chromium/sandbox/win/src/target_process.cc
deleted file mode 100644
index e27655e7e..000000000
--- a/security/sandbox/chromium/sandbox/win/src/target_process.cc
+++ /dev/null
@@ -1,368 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/target_process.h"
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/win/pe_image.h"
-#include "base/win/startup_information.h"
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/policy_low_level.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sharedmem_ipc_server.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace {
-
-void CopyPolicyToTarget(const void* source, size_t size, void* dest) {
- if (!source || !size)
- return;
- memcpy(dest, source, size);
- sandbox::PolicyGlobal* policy =
- reinterpret_cast<sandbox::PolicyGlobal*>(dest);
-
- size_t offset = reinterpret_cast<size_t>(source);
-
- for (size_t i = 0; i < sandbox::kMaxServiceCount; i++) {
- size_t buffer = reinterpret_cast<size_t>(policy->entry[i]);
- if (buffer) {
- buffer -= offset;
- policy->entry[i] = reinterpret_cast<sandbox::PolicyBuffer*>(buffer);
- }
- }
-}
-
-} // namespace
-
-namespace sandbox {
-
-SANDBOX_INTERCEPT HANDLE g_shared_section;
-SANDBOX_INTERCEPT size_t g_shared_IPC_size;
-SANDBOX_INTERCEPT size_t g_shared_policy_size;
-
-// Returns the address of the main exe module in memory taking in account
-// address space layout randomization.
-void* GetBaseAddress(const wchar_t* exe_name, void* entry_point) {
- HMODULE exe = ::LoadLibrary(exe_name);
- if (NULL == exe)
- return exe;
-
- base::win::PEImage pe(exe);
- if (!pe.VerifyMagic()) {
- ::FreeLibrary(exe);
- return exe;
- }
- PIMAGE_NT_HEADERS nt_header = pe.GetNTHeaders();
- char* base = reinterpret_cast<char*>(entry_point) -
- nt_header->OptionalHeader.AddressOfEntryPoint;
-
- ::FreeLibrary(exe);
- return base;
-}
-
-TargetProcess::TargetProcess(base::win::ScopedHandle initial_token,
- base::win::ScopedHandle lockdown_token,
- base::win::ScopedHandle lowbox_token,
- HANDLE job,
- ThreadProvider* thread_pool)
- // This object owns everything initialized here except thread_pool and
- // the job_ handle. The Job handle is closed by BrokerServices and results
- // eventually in a call to our dtor.
- : lockdown_token_(lockdown_token.Pass()),
- initial_token_(initial_token.Pass()),
- lowbox_token_(lowbox_token.Pass()),
- job_(job),
- thread_pool_(thread_pool),
- base_address_(NULL) {}
-
-TargetProcess::~TargetProcess() {
- DWORD exit_code = 0;
- // Give a chance to the process to die. In most cases the JOB_KILL_ON_CLOSE
- // will take effect only when the context changes. As far as the testing went,
- // this wait was enough to switch context and kill the processes in the job.
- // If this process is already dead, the function will return without waiting.
- // TODO(nsylvain): If the process is still alive at the end, we should kill
- // it. http://b/893891
- // For now, this wait is there only to do a best effort to prevent some leaks
- // from showing up in purify.
- if (sandbox_process_info_.IsValid()) {
- ::WaitForSingleObject(sandbox_process_info_.process_handle(), 50);
- // At this point, the target process should have been killed. Check.
- if (!::GetExitCodeProcess(sandbox_process_info_.process_handle(),
- &exit_code) || (STILL_ACTIVE == exit_code)) {
- // Something went wrong. We don't know if the target is in a state where
- // it can manage to do another IPC call. If it can, and we've destroyed
- // the |ipc_server_|, it will crash the broker. So we intentionally leak
- // that.
- if (shared_section_.IsValid())
- shared_section_.Take();
- ignore_result(ipc_server_.release());
- sandbox_process_info_.TakeProcessHandle();
- return;
- }
- }
-
- // ipc_server_ references our process handle, so make sure the former is shut
- // down before the latter is closed (by ScopedProcessInformation).
- ipc_server_.reset();
-}
-
-// Creates the target (child) process suspended and assigns it to the job
-// object.
-DWORD TargetProcess::Create(const wchar_t* exe_path,
- const wchar_t* command_line,
- bool inherit_handles,
- const base::win::StartupInformation& startup_info,
- base::win::ScopedProcessInformation* target_info) {
- if (lowbox_token_.IsValid() &&
- base::win::GetVersion() < base::win::VERSION_WIN8) {
- // We don't allow lowbox_token below Windows 8.
- return ERROR_INVALID_PARAMETER;
- }
-
- exe_name_.reset(_wcsdup(exe_path));
-
- // the command line needs to be writable by CreateProcess().
- scoped_ptr<wchar_t, base::FreeDeleter> cmd_line(_wcsdup(command_line));
-
- // Start the target process suspended.
- DWORD flags =
- CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | DETACHED_PROCESS;
-
- if (startup_info.has_extended_startup_info())
- flags |= EXTENDED_STARTUPINFO_PRESENT;
-
- if (job_ && base::win::GetVersion() < base::win::VERSION_WIN8) {
- // Windows 8 implements nested jobs, but for older systems we need to
- // break out of any job we're in to enforce our restrictions.
- flags |= CREATE_BREAKAWAY_FROM_JOB;
- }
-
- PROCESS_INFORMATION temp_process_info = {};
- if (!::CreateProcessAsUserW(lockdown_token_.Get(), exe_path, cmd_line.get(),
- NULL, // No security attribute.
- NULL, // No thread attribute.
- inherit_handles, flags,
- NULL, // Use the environment of the caller.
- NULL, // Use current directory of the caller.
- startup_info.startup_info(),
- &temp_process_info)) {
- return ::GetLastError();
- }
- base::win::ScopedProcessInformation process_info(temp_process_info);
-
- DWORD win_result = ERROR_SUCCESS;
-
- if (job_) {
- // Assign the suspended target to the windows job object.
- if (!::AssignProcessToJobObject(job_, process_info.process_handle())) {
- win_result = ::GetLastError();
- ::TerminateProcess(process_info.process_handle(), 0);
- return win_result;
- }
- }
-
- if (initial_token_.IsValid()) {
- // Change the token of the main thread of the new process for the
- // impersonation token with more rights. This allows the target to start;
- // otherwise it will crash too early for us to help.
- HANDLE temp_thread = process_info.thread_handle();
- if (!::SetThreadToken(&temp_thread, initial_token_.Get())) {
- win_result = ::GetLastError();
- // It might be a security breach if we let the target run outside the job
- // so kill it before it causes damage.
- ::TerminateProcess(process_info.process_handle(), 0);
- return win_result;
- }
- initial_token_.Close();
- }
-
- CONTEXT context;
- context.ContextFlags = CONTEXT_ALL;
- if (!::GetThreadContext(process_info.thread_handle(), &context)) {
- win_result = ::GetLastError();
- ::TerminateProcess(process_info.process_handle(), 0);
- return win_result;
- }
-
-#if defined(_WIN64)
- void* entry_point = reinterpret_cast<void*>(context.Rcx);
-#else
-#pragma warning(push)
-#pragma warning(disable: 4312)
- // This cast generates a warning because it is 32 bit specific.
- void* entry_point = reinterpret_cast<void*>(context.Eax);
-#pragma warning(pop)
-#endif // _WIN64
-
- if (!target_info->DuplicateFrom(process_info)) {
- win_result = ::GetLastError(); // This may or may not be correct.
- ::TerminateProcess(process_info.process_handle(), 0);
- return win_result;
- }
-
- if (lowbox_token_.IsValid()) {
- PROCESS_ACCESS_TOKEN process_access_token;
- process_access_token.thread = process_info.thread_handle();
- process_access_token.token = lowbox_token_.Get();
-
- NtSetInformationProcess SetInformationProcess = NULL;
- ResolveNTFunctionPtr("NtSetInformationProcess", &SetInformationProcess);
-
- NTSTATUS status = SetInformationProcess(
- process_info.process_handle(),
- static_cast<PROCESS_INFORMATION_CLASS>(NtProcessInformationAccessToken),
- &process_access_token, sizeof(process_access_token));
- if (!NT_SUCCESS(status)) {
- win_result = ERROR_INVALID_TOKEN;
- ::TerminateProcess(process_info.process_handle(), 0); // exit code
- return win_result;
- }
- }
-
- base_address_ = GetBaseAddress(exe_path, entry_point);
- sandbox_process_info_.Set(process_info.Take());
- return win_result;
-}
-
-ResultCode TargetProcess::TransferVariable(const char* name, void* address,
- size_t size) {
- if (!sandbox_process_info_.IsValid())
- return SBOX_ERROR_UNEXPECTED_CALL;
-
- void* child_var = address;
-
-#if SANDBOX_EXPORTS
- HMODULE module = ::LoadLibrary(exe_name_.get());
- if (NULL == module)
- return SBOX_ERROR_GENERIC;
-
- child_var = ::GetProcAddress(module, name);
- ::FreeLibrary(module);
-
- if (NULL == child_var)
- return SBOX_ERROR_GENERIC;
-
- size_t offset = reinterpret_cast<char*>(child_var) -
- reinterpret_cast<char*>(module);
- child_var = reinterpret_cast<char*>(MainModule()) + offset;
-#endif
-
- SIZE_T written;
- if (!::WriteProcessMemory(sandbox_process_info_.process_handle(),
- child_var, address, size, &written))
- return SBOX_ERROR_GENERIC;
-
- if (written != size)
- return SBOX_ERROR_GENERIC;
-
- return SBOX_ALL_OK;
-}
-
-// Construct the IPC server and the IPC dispatcher. When the target does
-// an IPC it will eventually call the dispatcher.
-DWORD TargetProcess::Init(Dispatcher* ipc_dispatcher,
- void* policy,
- uint32_t shared_IPC_size,
- uint32_t shared_policy_size) {
- // We need to map the shared memory on the target. This is necessary for
- // any IPC that needs to take place, even if the target has not yet hit
- // the main( ) function or even has initialized the CRT. So here we set
- // the handle to the shared section. The target on the first IPC must do
- // the rest, which boils down to calling MapViewofFile()
-
- // We use this single memory pool for IPC and for policy.
- DWORD shared_mem_size = static_cast<DWORD>(shared_IPC_size +
- shared_policy_size);
- shared_section_.Set(::CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
- PAGE_READWRITE | SEC_COMMIT,
- 0, shared_mem_size, NULL));
- if (!shared_section_.IsValid()) {
- return ::GetLastError();
- }
-
- DWORD access = FILE_MAP_READ | FILE_MAP_WRITE | SECTION_QUERY;
- HANDLE target_shared_section;
- if (!::DuplicateHandle(::GetCurrentProcess(), shared_section_.Get(),
- sandbox_process_info_.process_handle(),
- &target_shared_section, access, FALSE, 0)) {
- return ::GetLastError();
- }
-
- void* shared_memory = ::MapViewOfFile(shared_section_.Get(),
- FILE_MAP_WRITE|FILE_MAP_READ,
- 0, 0, 0);
- if (NULL == shared_memory) {
- return ::GetLastError();
- }
-
- CopyPolicyToTarget(policy, shared_policy_size,
- reinterpret_cast<char*>(shared_memory) + shared_IPC_size);
-
- ResultCode ret;
- // Set the global variables in the target. These are not used on the broker.
- g_shared_section = target_shared_section;
- ret = TransferVariable("g_shared_section", &g_shared_section,
- sizeof(g_shared_section));
- g_shared_section = NULL;
- if (SBOX_ALL_OK != ret) {
- return (SBOX_ERROR_GENERIC == ret)?
- ::GetLastError() : ERROR_INVALID_FUNCTION;
- }
- g_shared_IPC_size = shared_IPC_size;
- ret = TransferVariable("g_shared_IPC_size", &g_shared_IPC_size,
- sizeof(g_shared_IPC_size));
- g_shared_IPC_size = 0;
- if (SBOX_ALL_OK != ret) {
- return (SBOX_ERROR_GENERIC == ret) ?
- ::GetLastError() : ERROR_INVALID_FUNCTION;
- }
- g_shared_policy_size = shared_policy_size;
- ret = TransferVariable("g_shared_policy_size", &g_shared_policy_size,
- sizeof(g_shared_policy_size));
- g_shared_policy_size = 0;
- if (SBOX_ALL_OK != ret) {
- return (SBOX_ERROR_GENERIC == ret) ?
- ::GetLastError() : ERROR_INVALID_FUNCTION;
- }
-
- ipc_server_.reset(
- new SharedMemIPCServer(sandbox_process_info_.process_handle(),
- sandbox_process_info_.process_id(),
- thread_pool_, ipc_dispatcher));
-
- if (!ipc_server_->Init(shared_memory, shared_IPC_size, kIPCChannelSize))
- return ERROR_NOT_ENOUGH_MEMORY;
-
- // After this point we cannot use this handle anymore.
- ::CloseHandle(sandbox_process_info_.TakeThreadHandle());
-
- return ERROR_SUCCESS;
-}
-
-void TargetProcess::Terminate() {
- if (!sandbox_process_info_.IsValid())
- return;
-
- ::TerminateProcess(sandbox_process_info_.process_handle(), 0);
-}
-
-TargetProcess* MakeTestTargetProcess(HANDLE process, HMODULE base_address) {
- TargetProcess* target =
- new TargetProcess(base::win::ScopedHandle(), base::win::ScopedHandle(),
- base::win::ScopedHandle(), NULL, NULL);
- PROCESS_INFORMATION process_info = {};
- process_info.hProcess = process;
- target->sandbox_process_info_.Set(process_info);
- target->base_address_ = base_address;
- return target;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/target_process.h b/security/sandbox/chromium/sandbox/win/src/target_process.h
deleted file mode 100644
index c00f2cea8..000000000
--- a/security/sandbox/chromium/sandbox/win/src/target_process.h
+++ /dev/null
@@ -1,143 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_WIN_SRC_TARGET_PROCESS_H_
-#define SANDBOX_WIN_SRC_TARGET_PROCESS_H_
-
-#include <windows.h>
-#include <stddef.h>
-#include <stdint.h>
-
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/win/scoped_handle.h"
-#include "base/win/scoped_process_information.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace base {
-namespace win {
-
-class StartupInformation;
-
-}; // namespace win
-}; // namespace base
-
-namespace sandbox {
-
-class AttributeList;
-class SharedMemIPCServer;
-class ThreadProvider;
-
-// TargetProcess models a target instance (child process). Objects of this
-// class are owned by the Policy used to create them.
-class TargetProcess {
- public:
- // The constructor takes ownership of |initial_token|, |lockdown_token|
- // and |lowbox_token|.
- TargetProcess(base::win::ScopedHandle initial_token,
- base::win::ScopedHandle lockdown_token,
- base::win::ScopedHandle lowbox_token,
- HANDLE job,
- ThreadProvider* thread_pool);
- ~TargetProcess();
-
- // TODO(cpu): Currently there does not seem to be a reason to implement
- // reference counting for this class since is internal, but kept the
- // the same interface so the interception framework does not need to be
- // touched at this point.
- void AddRef() {}
- void Release() {}
-
- // Creates the new target process. The process is created suspended.
- DWORD Create(const wchar_t* exe_path,
- const wchar_t* command_line,
- bool inherit_handles,
- const base::win::StartupInformation& startup_info,
- base::win::ScopedProcessInformation* target_info);
-
- // Destroys the target process.
- void Terminate();
-
- // Creates the IPC objects such as the BrokerDispatcher and the
- // IPC server. The IPC server uses the services of the thread_pool.
- DWORD Init(Dispatcher* ipc_dispatcher,
- void* policy,
- uint32_t shared_IPC_size,
- uint32_t shared_policy_size);
-
- // Returns the handle to the target process.
- HANDLE Process() const {
- return sandbox_process_info_.process_handle();
- }
-
- // Returns the handle to the job object that the target process belongs to.
- HANDLE Job() const {
- return job_;
- }
-
- // Returns the address of the target main exe. This is used by the
- // interceptions framework.
- HMODULE MainModule() const {
- return reinterpret_cast<HMODULE>(base_address_);
- }
-
- // Returns the name of the executable.
- const wchar_t* Name() const {
- return exe_name_.get();
- }
-
- // Returns the process id.
- DWORD ProcessId() const {
- return sandbox_process_info_.process_id();
- }
-
- // Returns the handle to the main thread.
- HANDLE MainThread() const {
- return sandbox_process_info_.thread_handle();
- }
-
- // Transfers a 32-bit variable between the broker and the target.
- ResultCode TransferVariable(const char* name, void* address, size_t size);
-
- private:
- // Details of the target process.
- base::win::ScopedProcessInformation sandbox_process_info_;
- // The token associated with the process. It provides the core of the
- // sbox security.
- base::win::ScopedHandle lockdown_token_;
- // The token given to the initial thread so that the target process can
- // start. It has more powers than the lockdown_token.
- base::win::ScopedHandle initial_token_;
- // The lowbox token associated with the process. This token is set after the
- // process creation.
- base::win::ScopedHandle lowbox_token_;
- // Kernel handle to the shared memory used by the IPC server.
- base::win::ScopedHandle shared_section_;
- // Job object containing the target process.
- HANDLE job_;
- // Reference to the IPC subsystem.
- scoped_ptr<SharedMemIPCServer> ipc_server_;
- // Provides the threads used by the IPC. This class does not own this pointer.
- ThreadProvider* thread_pool_;
- // Base address of the main executable
- void* base_address_;
- // Full name of the target executable.
- scoped_ptr<wchar_t, base::FreeDeleter> exe_name_;
-
- // Function used for testing.
- friend TargetProcess* MakeTestTargetProcess(HANDLE process,
- HMODULE base_address);
-
- DISALLOW_IMPLICIT_CONSTRUCTORS(TargetProcess);
-};
-
-// Creates a mock TargetProcess used for testing interceptions.
-// TODO(cpu): It seems that this method is not going to be used anymore.
-TargetProcess* MakeTestTargetProcess(HANDLE process, HMODULE base_address);
-
-
-} // namespace sandbox
-
-#endif // SANDBOX_WIN_SRC_TARGET_PROCESS_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/target_services.cc b/security/sandbox/chromium/sandbox/win/src/target_services.cc
deleted file mode 100644
index 7537245b6..000000000
--- a/security/sandbox/chromium/sandbox/win/src/target_services.cc
+++ /dev/null
@@ -1,261 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/target_services.h"
-
-#include <new>
-
-#include <process.h>
-#include <stdint.h>
-
-#include "base/win/windows_version.h"
-#include "sandbox/win/src/crosscall_client.h"
-#include "sandbox/win/src/handle_closer_agent.h"
-#include "sandbox/win/src/handle_interception.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/process_mitigations.h"
-#include "sandbox/win/src/restricted_token_utils.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-#include "sandbox/win/src/sandbox_types.h"
-#include "sandbox/win/src/sharedmem_ipc_client.h"
-
-namespace {
-
-// Flushing a cached key is triggered by just opening the key and closing the
-// resulting handle. RegDisablePredefinedCache() is the documented way to flush
-// HKCU so do not use it with this function.
-bool FlushRegKey(HKEY root) {
- HKEY key;
- if (ERROR_SUCCESS == ::RegOpenKeyExW(root, NULL, 0, MAXIMUM_ALLOWED, &key)) {
- if (ERROR_SUCCESS != ::RegCloseKey(key))
- return false;
- }
- return true;
-}
-
-// This function forces advapi32.dll to release some internally cached handles
-// that were made during calls to RegOpenkey and RegOpenKeyEx if it is called
-// with a more restrictive token. Returns true if the flushing is succesful
-// although this behavior is undocumented and there is no guarantee that in
-// fact this will happen in future versions of windows.
-bool FlushCachedRegHandles() {
- return (FlushRegKey(HKEY_LOCAL_MACHINE) &&
- FlushRegKey(HKEY_CLASSES_ROOT) &&
- FlushRegKey(HKEY_USERS));
-}
-
-// Checks if we have handle entries pending and runs the closer.
-// Updates is_csrss_connected based on which handle types are closed.
-bool CloseOpenHandles(bool* is_csrss_connected) {
- if (sandbox::HandleCloserAgent::NeedsHandlesClosed()) {
- sandbox::HandleCloserAgent handle_closer;
- handle_closer.InitializeHandlesToClose(is_csrss_connected);
- if (!handle_closer.CloseHandles())
- return false;
- }
-
- return true;
-}
-
-// GetUserDefaultLocaleName is not available on WIN XP. So we'll
-// load it on-the-fly.
-const wchar_t kKernel32DllName[] = L"kernel32.dll";
-typedef decltype(GetUserDefaultLocaleName)* GetUserDefaultLocaleNameFunction;
-
-// Warm up language subsystems before the sandbox is turned on.
-// Tested on Win8.1 x64:
-// This needs to happen after RevertToSelf() is called, because (at least) in
-// the case of GetUserDefaultLCID() it checks the TEB to see if the process is
-// impersonating (TEB!IsImpersonating). If it is, the cached locale information
-// is not used, nor is it set. Therefore, calls after RevertToSelf() will not
-// have warmed-up values to use.
-bool WarmupWindowsLocales() {
- // NOTE(liamjm): When last checked (Win 8.1 x64) it wasn't necessary to
- // warmup all of these functions, but let's not assume that.
- ::GetUserDefaultLangID();
- ::GetUserDefaultLCID();
- if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
- static GetUserDefaultLocaleNameFunction GetUserDefaultLocaleName_func =
- NULL;
- if (!GetUserDefaultLocaleName_func) {
- HMODULE kernel32_dll = ::GetModuleHandle(kKernel32DllName);
- if (!kernel32_dll) {
- return false;
- }
- GetUserDefaultLocaleName_func =
- reinterpret_cast<GetUserDefaultLocaleNameFunction>(
- GetProcAddress(kernel32_dll, "GetUserDefaultLocaleName"));
- if (!GetUserDefaultLocaleName_func) {
- return false;
- }
- }
- wchar_t localeName[LOCALE_NAME_MAX_LENGTH] = {0};
- return (0 != GetUserDefaultLocaleName_func(
- localeName, LOCALE_NAME_MAX_LENGTH * sizeof(wchar_t)));
- }
- return true;
-}
-
-// Used as storage for g_target_services, because other allocation facilities
-// are not available early. We can't use a regular function static because on
-// VS2015, because the CRT tries to acquire a lock to guard initialization, but
-// this code runs before the CRT is initialized.
-char g_target_services_memory[sizeof(sandbox::TargetServicesBase)];
-sandbox::TargetServicesBase* g_target_services = nullptr;
-
-} // namespace
-
-namespace sandbox {
-
-SANDBOX_INTERCEPT IntegrityLevel g_shared_delayed_integrity_level =
- INTEGRITY_LEVEL_LAST;
-SANDBOX_INTERCEPT MitigationFlags g_shared_delayed_mitigations = 0;
-
-TargetServicesBase::TargetServicesBase() {
-}
-
-ResultCode TargetServicesBase::Init() {
- process_state_.SetInitCalled();
- return SBOX_ALL_OK;
-}
-
-// Failure here is a breach of security so the process is terminated.
-void TargetServicesBase::LowerToken() {
- if (ERROR_SUCCESS !=
- SetProcessIntegrityLevel(g_shared_delayed_integrity_level))
- ::TerminateProcess(::GetCurrentProcess(), SBOX_FATAL_INTEGRITY);
- process_state_.SetRevertedToSelf();
- // If the client code as called RegOpenKey, advapi32.dll has cached some
- // handles. The following code gets rid of them.
- if (!::RevertToSelf())
- ::TerminateProcess(::GetCurrentProcess(), SBOX_FATAL_DROPTOKEN);
- if (!FlushCachedRegHandles())
- ::TerminateProcess(::GetCurrentProcess(), SBOX_FATAL_FLUSHANDLES);
- if (ERROR_SUCCESS != ::RegDisablePredefinedCache())
- ::TerminateProcess(::GetCurrentProcess(), SBOX_FATAL_CACHEDISABLE);
- if (!WarmupWindowsLocales())
- ::TerminateProcess(::GetCurrentProcess(), SBOX_FATAL_WARMUP);
- bool is_csrss_connected = true;
- if (!CloseOpenHandles(&is_csrss_connected))
- ::TerminateProcess(::GetCurrentProcess(), SBOX_FATAL_CLOSEHANDLES);
- process_state_.SetCsrssConnected(is_csrss_connected);
- // Enabling mitigations must happen last otherwise handle closing breaks
- if (g_shared_delayed_mitigations &&
- !ApplyProcessMitigationsToCurrentProcess(g_shared_delayed_mitigations))
- ::TerminateProcess(::GetCurrentProcess(), SBOX_FATAL_MITIGATION);
-}
-
-ProcessState* TargetServicesBase::GetState() {
- return &process_state_;
-}
-
-TargetServicesBase* TargetServicesBase::GetInstance() {
- // Leak on purpose TargetServicesBase.
- if (!g_target_services)
- g_target_services = new (g_target_services_memory) TargetServicesBase;
- return g_target_services;
-}
-
-// The broker services a 'test' IPC service with the IPC_PING_TAG tag.
-bool TargetServicesBase::TestIPCPing(int version) {
- void* memory = GetGlobalIPCMemory();
- if (NULL == memory) {
- return false;
- }
- SharedMemIPCClient ipc(memory);
- CrossCallReturn answer = {0};
-
- if (1 == version) {
- uint32_t tick1 = ::GetTickCount();
- uint32_t cookie = 717115;
- ResultCode code = CrossCall(ipc, IPC_PING1_TAG, cookie, &answer);
-
- if (SBOX_ALL_OK != code) {
- return false;
- }
- // We should get two extended returns values from the IPC, one is the
- // tick count on the broker and the other is the cookie times two.
- if ((answer.extended_count != 2)) {
- return false;
- }
- // We test the first extended answer to be within the bounds of the tick
- // count only if there was no tick count wraparound.
- uint32_t tick2 = ::GetTickCount();
- if (tick2 >= tick1) {
- if ((answer.extended[0].unsigned_int < tick1) ||
- (answer.extended[0].unsigned_int > tick2)) {
- return false;
- }
- }
-
- if (answer.extended[1].unsigned_int != cookie * 2) {
- return false;
- }
- } else if (2 == version) {
- uint32_t cookie = 717111;
- InOutCountedBuffer counted_buffer(&cookie, sizeof(cookie));
- ResultCode code = CrossCall(ipc, IPC_PING2_TAG, counted_buffer, &answer);
-
- if (SBOX_ALL_OK != code) {
- return false;
- }
- if (cookie != 717111 * 3) {
- return false;
- }
- } else {
- return false;
- }
- return true;
-}
-
-ProcessState::ProcessState() : process_state_(0), csrss_connected_(true) {
-}
-
-bool ProcessState::IsKernel32Loaded() const {
- return process_state_ != 0;
-}
-
-bool ProcessState::InitCalled() const {
- return process_state_ > 1;
-}
-
-bool ProcessState::RevertedToSelf() const {
- return process_state_ > 2;
-}
-
-bool ProcessState::IsCsrssConnected() const {
- return csrss_connected_;
-}
-
-void ProcessState::SetKernel32Loaded() {
- if (!process_state_)
- process_state_ = 1;
-}
-
-void ProcessState::SetInitCalled() {
- if (process_state_ < 2)
- process_state_ = 2;
-}
-
-void ProcessState::SetRevertedToSelf() {
- if (process_state_ < 3)
- process_state_ = 3;
-}
-
-void ProcessState::SetCsrssConnected(bool csrss_connected) {
- csrss_connected_ = csrss_connected;
-}
-
-
-ResultCode TargetServicesBase::DuplicateHandle(HANDLE source_handle,
- DWORD target_process_id,
- HANDLE* target_handle,
- DWORD desired_access,
- DWORD options) {
- return sandbox::DuplicateHandleProxy(source_handle, target_process_id,
- target_handle, desired_access, options);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/target_services.h b/security/sandbox/chromium/sandbox/win/src/target_services.h
deleted file mode 100644
index 37169485d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/target_services.h
+++ /dev/null
@@ -1,71 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_TARGET_SERVICES_H__
-#define SANDBOX_SRC_TARGET_SERVICES_H__
-
-#include "base/macros.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/win_utils.h"
-
-namespace sandbox {
-
-class ProcessState {
- public:
- ProcessState();
- // Returns true if kernel32.dll has been loaded.
- bool IsKernel32Loaded() const;
- // Returns true if main has been called.
- bool InitCalled() const;
- // Returns true if LowerToken has been called.
- bool RevertedToSelf() const;
- // Returns true if Csrss is connected.
- bool IsCsrssConnected() const;
- // Set the current state.
- void SetKernel32Loaded();
- void SetInitCalled();
- void SetRevertedToSelf();
- void SetCsrssConnected(bool csrss_connected);
-
- private:
- int process_state_;
- bool csrss_connected_;
- DISALLOW_COPY_AND_ASSIGN(ProcessState);
-};
-
-// This class is an implementation of the TargetServices.
-// Look in the documentation of sandbox::TargetServices for more info.
-// Do NOT add a destructor to this class without changing the implementation of
-// the factory method.
-class TargetServicesBase : public TargetServices {
- public:
- TargetServicesBase();
-
- // Public interface of TargetServices.
- ResultCode Init() override;
- void LowerToken() override;
- ProcessState* GetState() override;
- ResultCode DuplicateHandle(HANDLE source_handle,
- DWORD target_process_id,
- HANDLE* target_handle,
- DWORD desired_access,
- DWORD options) override;
-
- // Factory method.
- static TargetServicesBase* GetInstance();
-
- // Sends a simple IPC Message that has a well-known answer. Returns true
- // if the IPC was successful and false otherwise. There are 2 versions of
- // this test: 1 and 2. The first one send a simple message while the
- // second one send a message with an in/out param.
- bool TestIPCPing(int version);
-
- private:
- ProcessState process_state_;
- DISALLOW_COPY_AND_ASSIGN(TargetServicesBase);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_TARGET_SERVICES_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/threadpool_unittest.cc b/security/sandbox/chromium/sandbox/win/src/threadpool_unittest.cc
deleted file mode 100644
index d32fdda5b..000000000
--- a/security/sandbox/chromium/sandbox/win/src/threadpool_unittest.cc
+++ /dev/null
@@ -1,97 +0,0 @@
-// 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 <stdint.h>
-
-#include "sandbox/win/src/win2k_threadpool.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-void __stdcall EmptyCallBack(void*, unsigned char) {
-}
-
-void __stdcall TestCallBack(void* context, unsigned char) {
- HANDLE event = reinterpret_cast<HANDLE>(context);
- ::SetEvent(event);
-}
-
-namespace sandbox {
-
-// Test that register and unregister work, part 1.
-TEST(IPCTest, ThreadPoolRegisterTest1) {
- Win2kThreadPool thread_pool;
-
- EXPECT_EQ(0u, thread_pool.OutstandingWaits());
-
- HANDLE event1 = ::CreateEventW(NULL, FALSE, FALSE, NULL);
- HANDLE event2 = ::CreateEventW(NULL, FALSE, FALSE, NULL);
-
- uint32_t context = 0;
- EXPECT_FALSE(thread_pool.RegisterWait(0, event1, EmptyCallBack, &context));
- EXPECT_EQ(0u, thread_pool.OutstandingWaits());
-
- EXPECT_TRUE(thread_pool.RegisterWait(this, event1, EmptyCallBack, &context));
- EXPECT_EQ(1u, thread_pool.OutstandingWaits());
- EXPECT_TRUE(thread_pool.RegisterWait(this, event2, EmptyCallBack, &context));
- EXPECT_EQ(2u, thread_pool.OutstandingWaits());
-
- EXPECT_TRUE(thread_pool.UnRegisterWaits(this));
- EXPECT_EQ(0u, thread_pool.OutstandingWaits());
-
- EXPECT_EQ(TRUE, ::CloseHandle(event1));
- EXPECT_EQ(TRUE, ::CloseHandle(event2));
-}
-
-// Test that register and unregister work, part 2.
-TEST(IPCTest, ThreadPoolRegisterTest2) {
- Win2kThreadPool thread_pool;
-
- HANDLE event1 = ::CreateEventW(NULL, FALSE, FALSE, NULL);
- HANDLE event2 = ::CreateEventW(NULL, FALSE, FALSE, NULL);
-
- uint32_t context = 0;
- uint32_t c1 = 0;
- uint32_t c2 = 0;
-
- EXPECT_TRUE(thread_pool.RegisterWait(&c1, event1, EmptyCallBack, &context));
- EXPECT_EQ(1u, thread_pool.OutstandingWaits());
- EXPECT_TRUE(thread_pool.RegisterWait(&c2, event2, EmptyCallBack, &context));
- EXPECT_EQ(2u, thread_pool.OutstandingWaits());
-
- EXPECT_TRUE(thread_pool.UnRegisterWaits(&c2));
- EXPECT_EQ(1u, thread_pool.OutstandingWaits());
- EXPECT_TRUE(thread_pool.UnRegisterWaits(&c2));
- EXPECT_EQ(1u, thread_pool.OutstandingWaits());
-
- EXPECT_TRUE(thread_pool.UnRegisterWaits(&c1));
- EXPECT_EQ(0u, thread_pool.OutstandingWaits());
-
- EXPECT_EQ(TRUE, ::CloseHandle(event1));
- EXPECT_EQ(TRUE, ::CloseHandle(event2));
-}
-
-// Test that the thread pool has at least a thread that services an event.
-// Test that when the event is un-registered is no longer serviced.
-TEST(IPCTest, ThreadPoolSignalAndWaitTest) {
- Win2kThreadPool thread_pool;
-
- // The events are auto reset and start not signaled.
- HANDLE event1 = ::CreateEventW(NULL, FALSE, FALSE, NULL);
- HANDLE event2 = ::CreateEventW(NULL, FALSE, FALSE, NULL);
-
- EXPECT_TRUE(thread_pool.RegisterWait(this, event1, TestCallBack, event2));
-
- EXPECT_EQ(WAIT_OBJECT_0, ::SignalObjectAndWait(event1, event2, 5000, FALSE));
- EXPECT_EQ(WAIT_OBJECT_0, ::SignalObjectAndWait(event1, event2, 5000, FALSE));
-
- EXPECT_TRUE(thread_pool.UnRegisterWaits(this));
- EXPECT_EQ(0u, thread_pool.OutstandingWaits());
-
- EXPECT_EQ(static_cast<DWORD>(WAIT_TIMEOUT),
- ::SignalObjectAndWait(event1, event2, 1000, FALSE));
-
- EXPECT_EQ(TRUE, ::CloseHandle(event1));
- EXPECT_EQ(TRUE, ::CloseHandle(event2));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/top_level_dispatcher.cc b/security/sandbox/chromium/sandbox/win/src/top_level_dispatcher.cc
deleted file mode 100644
index e6e224b4d..000000000
--- a/security/sandbox/chromium/sandbox/win/src/top_level_dispatcher.cc
+++ /dev/null
@@ -1,146 +0,0 @@
-// Copyright 2015 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 "sandbox/win/src/top_level_dispatcher.h"
-
-#include <stdint.h>
-#include <string.h>
-
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/filesystem_dispatcher.h"
-#include "sandbox/win/src/handle_dispatcher.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/internal_types.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/named_pipe_dispatcher.h"
-#include "sandbox/win/src/process_mitigations_win32k_dispatcher.h"
-#include "sandbox/win/src/process_thread_dispatcher.h"
-#include "sandbox/win/src/registry_dispatcher.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-#include "sandbox/win/src/sync_dispatcher.h"
-
-namespace sandbox {
-
-TopLevelDispatcher::TopLevelDispatcher(PolicyBase* policy) : policy_(policy) {
- // Initialize the IPC dispatcher array.
- memset(ipc_targets_, 0, sizeof(ipc_targets_));
- Dispatcher* dispatcher;
-
- dispatcher = new FilesystemDispatcher(policy_);
- ipc_targets_[IPC_NTCREATEFILE_TAG] = dispatcher;
- ipc_targets_[IPC_NTOPENFILE_TAG] = dispatcher;
- ipc_targets_[IPC_NTSETINFO_RENAME_TAG] = dispatcher;
- ipc_targets_[IPC_NTQUERYATTRIBUTESFILE_TAG] = dispatcher;
- ipc_targets_[IPC_NTQUERYFULLATTRIBUTESFILE_TAG] = dispatcher;
- filesystem_dispatcher_.reset(dispatcher);
-
- dispatcher = new NamedPipeDispatcher(policy_);
- ipc_targets_[IPC_CREATENAMEDPIPEW_TAG] = dispatcher;
- named_pipe_dispatcher_.reset(dispatcher);
-
- dispatcher = new ThreadProcessDispatcher(policy_);
- ipc_targets_[IPC_NTOPENTHREAD_TAG] = dispatcher;
- ipc_targets_[IPC_NTOPENPROCESS_TAG] = dispatcher;
- ipc_targets_[IPC_CREATEPROCESSW_TAG] = dispatcher;
- ipc_targets_[IPC_NTOPENPROCESSTOKEN_TAG] = dispatcher;
- ipc_targets_[IPC_NTOPENPROCESSTOKENEX_TAG] = dispatcher;
- thread_process_dispatcher_.reset(dispatcher);
-
- dispatcher = new SyncDispatcher(policy_);
- ipc_targets_[IPC_CREATEEVENT_TAG] = dispatcher;
- ipc_targets_[IPC_OPENEVENT_TAG] = dispatcher;
- sync_dispatcher_.reset(dispatcher);
-
- dispatcher = new RegistryDispatcher(policy_);
- ipc_targets_[IPC_NTCREATEKEY_TAG] = dispatcher;
- ipc_targets_[IPC_NTOPENKEY_TAG] = dispatcher;
- registry_dispatcher_.reset(dispatcher);
-
- dispatcher = new HandleDispatcher(policy_);
- ipc_targets_[IPC_DUPLICATEHANDLEPROXY_TAG] = dispatcher;
- handle_dispatcher_.reset(dispatcher);
-
- dispatcher = new ProcessMitigationsWin32KDispatcher(policy_);
- ipc_targets_[IPC_GDI_GDIDLLINITIALIZE_TAG] = dispatcher;
- ipc_targets_[IPC_GDI_GETSTOCKOBJECT_TAG] = dispatcher;
- ipc_targets_[IPC_USER_REGISTERCLASSW_TAG] = dispatcher;
- process_mitigations_win32k_dispatcher_.reset(dispatcher);
-}
-
-TopLevelDispatcher::~TopLevelDispatcher() {}
-
-// When an IPC is ready in any of the targets we get called. We manage an array
-// of IPC dispatchers which are keyed on the IPC tag so we normally delegate
-// to the appropriate dispatcher unless we can handle the IPC call ourselves.
-Dispatcher* TopLevelDispatcher::OnMessageReady(IPCParams* ipc,
- CallbackGeneric* callback) {
- DCHECK(callback);
- static const IPCParams ping1 = {IPC_PING1_TAG, {UINT32_TYPE}};
- static const IPCParams ping2 = {IPC_PING2_TAG, {INOUTPTR_TYPE}};
-
- if (ping1.Matches(ipc) || ping2.Matches(ipc)) {
- *callback = reinterpret_cast<CallbackGeneric>(
- static_cast<Callback1>(&TopLevelDispatcher::Ping));
- return this;
- }
-
- Dispatcher* dispatcher = GetDispatcher(ipc->ipc_tag);
- if (!dispatcher) {
- NOTREACHED();
- return NULL;
- }
- return dispatcher->OnMessageReady(ipc, callback);
-}
-
-// Delegate to the appropriate dispatcher.
-bool TopLevelDispatcher::SetupService(InterceptionManager* manager,
- int service) {
- if (IPC_PING1_TAG == service || IPC_PING2_TAG == service)
- return true;
-
- Dispatcher* dispatcher = GetDispatcher(service);
- if (!dispatcher) {
- NOTREACHED();
- return false;
- }
- return dispatcher->SetupService(manager, service);
-}
-
-// We service IPC_PING_TAG message which is a way to test a round trip of the
-// IPC subsystem. We receive a integer cookie and we are expected to return the
-// cookie times two (or three) and the current tick count.
-bool TopLevelDispatcher::Ping(IPCInfo* ipc, void* arg1) {
- switch (ipc->ipc_tag) {
- case IPC_PING1_TAG: {
- IPCInt ipc_int(arg1);
- uint32_t cookie = ipc_int.As32Bit();
- ipc->return_info.extended_count = 2;
- ipc->return_info.extended[0].unsigned_int = ::GetTickCount();
- ipc->return_info.extended[1].unsigned_int = 2 * cookie;
- return true;
- }
- case IPC_PING2_TAG: {
- CountedBuffer* io_buffer = reinterpret_cast<CountedBuffer*>(arg1);
- if (sizeof(uint32_t) != io_buffer->Size())
- return false;
-
- uint32_t* cookie = reinterpret_cast<uint32_t*>(io_buffer->Buffer());
- *cookie = (*cookie) * 3;
- return true;
- }
- default:
- return false;
- }
-}
-
-Dispatcher* TopLevelDispatcher::GetDispatcher(int ipc_tag) {
- if (ipc_tag >= IPC_LAST_TAG || ipc_tag <= IPC_UNUSED_TAG)
- return NULL;
-
- return ipc_targets_[ipc_tag];
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/top_level_dispatcher.h b/security/sandbox/chromium/sandbox/win/src/top_level_dispatcher.h
deleted file mode 100644
index c9306de1c..000000000
--- a/security/sandbox/chromium/sandbox/win/src/top_level_dispatcher.h
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2015 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 SANDBOX_SRC_TOP_LEVEL_DISPATCHER_H__
-#define SANDBOX_SRC_TOP_LEVEL_DISPATCHER_H__
-
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/crosscall_server.h"
-#include "sandbox/win/src/interception.h"
-#include "sandbox/win/src/ipc_tags.h"
-#include "sandbox/win/src/sandbox_policy_base.h"
-
-namespace sandbox {
-
-// Top level dispatcher which hands requests to the appropriate service
-// dispatchers.
-class TopLevelDispatcher : public Dispatcher {
- public:
- // |policy| must outlive this class.
- explicit TopLevelDispatcher(PolicyBase* policy);
- ~TopLevelDispatcher() override;
-
- Dispatcher* OnMessageReady(IPCParams* ipc,
- CallbackGeneric* callback) override;
- bool SetupService(InterceptionManager* manager, int service) override;
-
- private:
- // Test IPC provider.
- bool Ping(IPCInfo* ipc, void* cookie);
-
- // Returns a dispatcher from ipc_targets_.
- Dispatcher* GetDispatcher(int ipc_tag);
-
- PolicyBase* policy_;
- scoped_ptr<Dispatcher> filesystem_dispatcher_;
- scoped_ptr<Dispatcher> named_pipe_dispatcher_;
- scoped_ptr<Dispatcher> thread_process_dispatcher_;
- scoped_ptr<Dispatcher> sync_dispatcher_;
- scoped_ptr<Dispatcher> registry_dispatcher_;
- scoped_ptr<Dispatcher> handle_dispatcher_;
- scoped_ptr<Dispatcher> process_mitigations_win32k_dispatcher_;
- Dispatcher* ipc_targets_[IPC_LAST_TAG];
-
- DISALLOW_COPY_AND_ASSIGN(TopLevelDispatcher);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_TOP_LEVEL_DISPATCHER_H__
diff --git a/security/sandbox/chromium/sandbox/win/src/unload_dll_test.cc b/security/sandbox/chromium/sandbox/win/src/unload_dll_test.cc
deleted file mode 100644
index 7e398f686..000000000
--- a/security/sandbox/chromium/sandbox/win/src/unload_dll_test.cc
+++ /dev/null
@@ -1,93 +0,0 @@
-// 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.
-
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/sandbox_factory.h"
-#include "sandbox/win/src/target_services.h"
-#include "sandbox/win/tests/common/controller.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace sandbox {
-
-// Loads and or unloads a DLL passed in the second parameter of argv.
-// The first parameter of argv is 'L' = load, 'U' = unload or 'B' for both.
-SBOX_TESTS_COMMAND int UseOneDLL(int argc, wchar_t **argv) {
- if (argc != 2)
- return SBOX_TEST_FAILED_TO_RUN_TEST;
- int rv = SBOX_TEST_FAILED_TO_RUN_TEST;
-
- wchar_t option = (argv[0])[0];
- if ((option == L'L') || (option == L'B')) {
- HMODULE module1 = ::LoadLibraryW(argv[1]);
- rv = (module1 == NULL) ? SBOX_TEST_FAILED : SBOX_TEST_SUCCEEDED;
- }
-
- if ((option == L'U') || (option == L'B')) {
- HMODULE module2 = ::GetModuleHandleW(argv[1]);
- rv = ::FreeLibrary(module2) ? SBOX_TEST_SUCCEEDED : SBOX_TEST_FAILED;
- }
- return rv;
-}
-
-// Opens an event passed as the first parameter of argv.
-SBOX_TESTS_COMMAND int SimpleOpenEvent(int argc, wchar_t **argv) {
- if (argc != 1)
- return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
-
- base::win::ScopedHandle event_open(::OpenEvent(SYNCHRONIZE, FALSE, argv[0]));
- return event_open.Get() ? SBOX_TEST_SUCCEEDED : SBOX_TEST_FAILED;
-}
-
-TEST(UnloadDllTest, BaselineAvicapDll) {
- TestRunner runner;
- runner.SetTestState(BEFORE_REVERT);
- runner.SetTimeout(2000);
- // Add a sync rule, because that ensures that the interception agent has
- // more than one item in its internal table.
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
- TargetPolicy::EVENTS_ALLOW_ANY, L"t0001"));
-
- // Note for the puzzled: avicap32.dll is a 64-bit dll in 64-bit versions of
- // windows so this test and the others just work.
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"UseOneDLL L avicap32.dll"));
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"UseOneDLL B avicap32.dll"));
-}
-
-TEST(UnloadDllTest, UnloadAviCapDllNoPatching) {
- TestRunner runner;
- runner.SetTestState(BEFORE_REVERT);
- runner.SetTimeout(2000);
- sandbox::TargetPolicy* policy = runner.GetPolicy();
- policy->AddDllToUnload(L"avicap32.dll");
- EXPECT_EQ(SBOX_TEST_FAILED, runner.RunTest(L"UseOneDLL L avicap32.dll"));
- EXPECT_EQ(SBOX_TEST_FAILED, runner.RunTest(L"UseOneDLL B avicap32.dll"));
-}
-
-TEST(UnloadDllTest, UnloadAviCapDllWithPatching) {
- TestRunner runner;
- runner.SetTimeout(2000);
- runner.SetTestState(BEFORE_REVERT);
- sandbox::TargetPolicy* policy = runner.GetPolicy();
- policy->AddDllToUnload(L"avicap32.dll");
-
- base::win::ScopedHandle handle1(::CreateEvent(
- NULL, FALSE, FALSE, L"tst0001"));
-
- // Add a couple of rules that ensures that the interception agent add EAT
- // patching on the client which makes sure that the unload dll record does
- // not interact badly with them.
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_REGISTRY,
- TargetPolicy::REG_ALLOW_ANY,
- L"HKEY_LOCAL_MACHINE\\Software\\Microsoft"));
- EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
- TargetPolicy::EVENTS_ALLOW_ANY, L"tst0001"));
-
- EXPECT_EQ(SBOX_TEST_FAILED, runner.RunTest(L"UseOneDLL L avicap32.dll"));
-
- runner.SetTestState(AFTER_REVERT);
- EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"SimpleOpenEvent tst0001"));
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/win2k_threadpool.cc b/security/sandbox/chromium/sandbox/win/src/win2k_threadpool.cc
deleted file mode 100644
index 35de38a0f..000000000
--- a/security/sandbox/chromium/sandbox/win/src/win2k_threadpool.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-// 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.
-
-#include "sandbox/win/src/win2k_threadpool.h"
-
-#include <stddef.h>
-
-#include "sandbox/win/src/win_utils.h"
-
-namespace sandbox {
-
-Win2kThreadPool::Win2kThreadPool() {
- ::InitializeCriticalSection(&lock_);
-}
-
-bool Win2kThreadPool::RegisterWait(const void* cookie, HANDLE waitable_object,
- CrossCallIPCCallback callback,
- void* context) {
- if (0 == cookie) {
- return false;
- }
- HANDLE pool_object = NULL;
- // create a wait for a kernel object, with no timeout
- if (!::RegisterWaitForSingleObject(&pool_object, waitable_object, callback,
- context, INFINITE, WT_EXECUTEDEFAULT)) {
- return false;
- }
- PoolObject pool_obj = {cookie, pool_object};
- AutoLock lock(&lock_);
- pool_objects_.push_back(pool_obj);
- return true;
-}
-
-bool Win2kThreadPool::UnRegisterWaits(void* cookie) {
- if (0 == cookie) {
- return false;
- }
- AutoLock lock(&lock_);
- bool success = true;
- PoolObjects::iterator it = pool_objects_.begin();
- while (it != pool_objects_.end()) {
- if (it->cookie == cookie) {
- HANDLE wait = it->wait;
- it = pool_objects_.erase(it);
- success &= (::UnregisterWaitEx(wait, INVALID_HANDLE_VALUE) != 0);
- } else {
- ++it;
- }
- }
- return success;
-}
-
-size_t Win2kThreadPool::OutstandingWaits() {
- AutoLock lock(&lock_);
- return pool_objects_.size();
-}
-
-Win2kThreadPool::~Win2kThreadPool() {
- // Here we used to unregister all the pool wait handles. Now, following the
- // rest of the code we avoid lengthy or blocking calls given that the process
- // is being torn down.
- ::DeleteCriticalSection(&lock_);
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/win2k_threadpool.h b/security/sandbox/chromium/sandbox/win/src/win2k_threadpool.h
deleted file mode 100644
index c4d539dd7..000000000
--- a/security/sandbox/chromium/sandbox/win/src/win2k_threadpool.h
+++ /dev/null
@@ -1,61 +0,0 @@
-// 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.
-
-#ifndef SANDBOX_SRC_WIN2K_THREADPOOL_H_
-#define SANDBOX_SRC_WIN2K_THREADPOOL_H_
-
-#include <stddef.h>
-
-#include <algorithm>
-#include <list>
-#include "base/macros.h"
-#include "sandbox/win/src/crosscall_server.h"
-
-namespace sandbox {
-
-// Win2kThreadPool a simple implementation of a thread provider as required
-// for the sandbox IPC subsystem. See sandbox\crosscall_server.h for the details
-// and requirements of this interface.
-//
-// Implementing the thread provider as a thread pool is desirable in the case
-// of shared memory IPC because it can generate a large number of waitable
-// events: as many as channels. A thread pool does not create a thread per
-// event, instead maintains a few idle threads but can create more if the need
-// arises.
-//
-// This implementation simply thunks to the nice thread pool API of win2k.
-class Win2kThreadPool : public ThreadProvider {
- public:
- Win2kThreadPool();
- ~Win2kThreadPool() override;
-
- bool RegisterWait(const void* cookie,
- HANDLE waitable_object,
- CrossCallIPCCallback callback,
- void* context) override;
-
- bool UnRegisterWaits(void* cookie) override;
-
- // Returns the total number of wait objects associated with
- // the thread pool.
- size_t OutstandingWaits();
-
- private:
- // record to keep track of a wait and its associated cookie.
- struct PoolObject {
- const void* cookie;
- HANDLE wait;
- };
- // The list of pool wait objects.
- typedef std::list<PoolObject> PoolObjects;
- PoolObjects pool_objects_;
- // This lock protects the list of pool wait objects.
- CRITICAL_SECTION lock_;
-
- DISALLOW_COPY_AND_ASSIGN(Win2kThreadPool);
-};
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_WIN2K_THREADPOOL_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/win_utils.cc b/security/sandbox/chromium/sandbox/win/src/win_utils.cc
deleted file mode 100644
index 1e4675f8e..000000000
--- a/security/sandbox/chromium/sandbox/win/src/win_utils.cc
+++ /dev/null
@@ -1,437 +0,0 @@
-// 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 "sandbox/win/src/win_utils.h"
-
-#include <stddef.h>
-
-#include <map>
-
-#include "base/macros.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/strings/string_util.h"
-#include "base/win/pe_image.h"
-#include "sandbox/win/src/internal_types.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/sandbox_nt_util.h"
-
-namespace {
-
-// Holds the information about a known registry key.
-struct KnownReservedKey {
- const wchar_t* name;
- HKEY key;
-};
-
-// Contains all the known registry key by name and by handle.
-const KnownReservedKey kKnownKey[] = {
- { L"HKEY_CLASSES_ROOT", HKEY_CLASSES_ROOT },
- { L"HKEY_CURRENT_USER", HKEY_CURRENT_USER },
- { L"HKEY_LOCAL_MACHINE", HKEY_LOCAL_MACHINE},
- { L"HKEY_USERS", HKEY_USERS},
- { L"HKEY_PERFORMANCE_DATA", HKEY_PERFORMANCE_DATA},
- { L"HKEY_PERFORMANCE_TEXT", HKEY_PERFORMANCE_TEXT},
- { L"HKEY_PERFORMANCE_NLSTEXT", HKEY_PERFORMANCE_NLSTEXT},
- { L"HKEY_CURRENT_CONFIG", HKEY_CURRENT_CONFIG},
- { L"HKEY_DYN_DATA", HKEY_DYN_DATA}
-};
-
-// These functions perform case independent path comparisons.
-bool EqualPath(const base::string16& first, const base::string16& second) {
- return _wcsicmp(first.c_str(), second.c_str()) == 0;
-}
-
-bool EqualPath(const base::string16& first, size_t first_offset,
- const base::string16& second, size_t second_offset) {
- return _wcsicmp(first.c_str() + first_offset,
- second.c_str() + second_offset) == 0;
-}
-
-bool EqualPath(const base::string16& first,
- const wchar_t* second, size_t second_len) {
- return _wcsnicmp(first.c_str(), second, second_len) == 0;
-}
-
-bool EqualPath(const base::string16& first, size_t first_offset,
- const wchar_t* second, size_t second_len) {
- return _wcsnicmp(first.c_str() + first_offset, second, second_len) == 0;
-}
-
-// Returns true if |path| starts with "\??\" and returns a path without that
-// component.
-bool IsNTPath(const base::string16& path, base::string16* trimmed_path ) {
- if ((path.size() < sandbox::kNTPrefixLen) ||
- (0 != path.compare(0, sandbox::kNTPrefixLen, sandbox::kNTPrefix))) {
- *trimmed_path = path;
- return false;
- }
-
- *trimmed_path = path.substr(sandbox::kNTPrefixLen);
- return true;
-}
-
-// Returns true if |path| starts with "\Device\" and returns a path without that
-// component.
-bool IsDevicePath(const base::string16& path, base::string16* trimmed_path ) {
- if ((path.size() < sandbox::kNTDevicePrefixLen) ||
- (!EqualPath(path, sandbox::kNTDevicePrefix,
- sandbox::kNTDevicePrefixLen))) {
- *trimmed_path = path;
- return false;
- }
-
- *trimmed_path = path.substr(sandbox::kNTDevicePrefixLen);
- return true;
-}
-
-bool StartsWithDriveLetter(const base::string16& path) {
- if (path.size() < 3)
- return false;
-
- if (path[1] != L':' || path[2] != L'\\')
- return false;
-
- return (path[0] >= 'a' && path[0] <= 'z') ||
- (path[0] >= 'A' && path[0] <= 'Z');
-}
-
-const wchar_t kNTDotPrefix[] = L"\\\\.\\";
-const size_t kNTDotPrefixLen = arraysize(kNTDotPrefix) - 1;
-
-// Removes "\\\\.\\" from the path.
-void RemoveImpliedDevice(base::string16* path) {
- if (0 == path->compare(0, kNTDotPrefixLen, kNTDotPrefix))
- *path = path->substr(kNTDotPrefixLen);
-}
-
-} // namespace
-
-namespace sandbox {
-
-// Returns true if the provided path points to a pipe.
-bool IsPipe(const base::string16& path) {
- size_t start = 0;
- if (0 == path.compare(0, sandbox::kNTPrefixLen, sandbox::kNTPrefix))
- start = sandbox::kNTPrefixLen;
-
- const wchar_t kPipe[] = L"pipe\\";
- if (path.size() < start + arraysize(kPipe) - 1)
- return false;
-
- return EqualPath(path, start, kPipe, arraysize(kPipe) - 1);
-}
-
-HKEY GetReservedKeyFromName(const base::string16& name) {
- for (size_t i = 0; i < arraysize(kKnownKey); ++i) {
- if (name == kKnownKey[i].name)
- return kKnownKey[i].key;
- }
-
- return NULL;
-}
-
-bool ResolveRegistryName(base::string16 name, base::string16* resolved_name) {
- for (size_t i = 0; i < arraysize(kKnownKey); ++i) {
- if (name.find(kKnownKey[i].name) == 0) {
- HKEY key;
- DWORD disposition;
- if (ERROR_SUCCESS != ::RegCreateKeyEx(kKnownKey[i].key, L"", 0, NULL, 0,
- MAXIMUM_ALLOWED, NULL, &key,
- &disposition))
- return false;
-
- bool result = GetPathFromHandle(key, resolved_name);
- ::RegCloseKey(key);
-
- if (!result)
- return false;
-
- *resolved_name += name.substr(wcslen(kKnownKey[i].name));
- return true;
- }
- }
-
- return false;
-}
-
-// |full_path| can have any of the following forms:
-// \??\c:\some\foo\bar
-// \Device\HarddiskVolume0\some\foo\bar
-// \??\HarddiskVolume0\some\foo\bar
-// \??\UNC\SERVER\Share\some\foo\bar
-DWORD IsReparsePoint(const base::string16& full_path) {
- // Check if it's a pipe. We can't query the attributes of a pipe.
- if (IsPipe(full_path))
- return ERROR_NOT_A_REPARSE_POINT;
-
- base::string16 path;
- bool nt_path = IsNTPath(full_path, &path);
- bool has_drive = StartsWithDriveLetter(path);
- bool is_device_path = IsDevicePath(path, &path);
-
- if (!has_drive && !is_device_path && !nt_path)
- return ERROR_INVALID_NAME;
-
- if (!has_drive) {
- // Add Win32 device namespace prefix, required for some Windows APIs.
- path.insert(0, kNTDotPrefix);
- }
-
- // Ensure that volume path matches start of path.
- wchar_t vol_path[MAX_PATH];
- if (!::GetVolumePathNameW(path.c_str(), vol_path, MAX_PATH)) {
- // This will fail if this is a device that isn't volume related, which can't
- // then be a reparse point.
- return is_device_path ? ERROR_NOT_A_REPARSE_POINT : ERROR_INVALID_NAME;
- }
-
- // vol_path includes a trailing slash, so reduce size for path and loop check.
- size_t vol_path_len = wcslen(vol_path) - 1;
- if (!EqualPath(path, vol_path, vol_path_len)) {
- return ERROR_INVALID_NAME;
- }
-
- do {
- DWORD attributes = ::GetFileAttributes(path.c_str());
- if (INVALID_FILE_ATTRIBUTES == attributes) {
- DWORD error = ::GetLastError();
- if (error != ERROR_FILE_NOT_FOUND &&
- error != ERROR_PATH_NOT_FOUND &&
- error != ERROR_INVALID_FUNCTION &&
- error != ERROR_INVALID_NAME) {
- // Unexpected error.
- NOTREACHED_NT();
- return error;
- }
- } else if (FILE_ATTRIBUTE_REPARSE_POINT & attributes) {
- // This is a reparse point.
- return ERROR_SUCCESS;
- }
-
- path.resize(path.rfind(L'\\'));
- } while (path.size() > vol_path_len); // Skip root dir.
-
- return ERROR_NOT_A_REPARSE_POINT;
-}
-
-// We get a |full_path| of the forms accepted by IsReparsePoint(), and the name
-// we'll get from |handle| will be \device\harddiskvolume1\some\foo\bar.
-bool SameObject(HANDLE handle, const wchar_t* full_path) {
- // Check if it's a pipe.
- if (IsPipe(full_path))
- return true;
-
- base::string16 actual_path;
- if (!GetPathFromHandle(handle, &actual_path))
- return false;
-
- base::string16 path(full_path);
- DCHECK_NT(!path.empty());
-
- // This may end with a backslash.
- if (path.back() == L'\\') {
- path.pop_back();
- }
-
- // Perfect match (case-insensitive check).
- if (EqualPath(actual_path, path))
- return true;
-
- bool nt_path = IsNTPath(path, &path);
- bool has_drive = StartsWithDriveLetter(path);
-
- if (!has_drive && nt_path) {
- base::string16 simple_actual_path;
- if (IsDevicePath(path, &path)) {
- if (IsDevicePath(actual_path, &simple_actual_path)) {
- // Perfect match (case-insensitive check).
- return (EqualPath(simple_actual_path, path));
- } else {
- return false;
- }
- } else {
- // Add Win32 device namespace for GetVolumePathName.
- path.insert(0, kNTDotPrefix);
- }
- }
-
- // Get the volume path in the same format as actual_path.
- wchar_t vol_path[MAX_PATH];
- if (!::GetVolumePathName(path.c_str(), vol_path, MAX_PATH)) {
- return false;
- }
- size_t vol_path_len = wcslen(vol_path);
- base::string16 nt_vol;
- if (!GetNtPathFromWin32Path(vol_path, &nt_vol)) {
- return false;
- }
-
- // The two paths should be the same length.
- if (nt_vol.size() + path.size() - vol_path_len != actual_path.size()) {
- return false;
- }
-
- // Check the volume matches.
- if (!EqualPath(actual_path, nt_vol.c_str(), nt_vol.size())) {
- return false;
- }
-
- // Check the path after the volume matches.
- if (!EqualPath(actual_path, nt_vol.size(), path, vol_path_len)) {
- return false;
- }
-
- return true;
-}
-
-// Paths like \Device\HarddiskVolume0\some\foo\bar are assumed to be already
-// expanded.
-bool ConvertToLongPath(base::string16* path) {
- if (IsPipe(*path))
- return true;
-
- base::string16 temp_path;
- if (IsDevicePath(*path, &temp_path))
- return false;
-
- bool is_nt_path = IsNTPath(temp_path, &temp_path);
- bool added_implied_device = false;
- if (!StartsWithDriveLetter(temp_path) && is_nt_path) {
- temp_path = base::string16(kNTDotPrefix) + temp_path;
- added_implied_device = true;
- }
-
- DWORD size = MAX_PATH;
- scoped_ptr<wchar_t[]> long_path_buf(new wchar_t[size]);
-
- DWORD return_value = ::GetLongPathName(temp_path.c_str(), long_path_buf.get(),
- size);
- while (return_value >= size) {
- size *= 2;
- long_path_buf.reset(new wchar_t[size]);
- return_value = ::GetLongPathName(temp_path.c_str(), long_path_buf.get(),
- size);
- }
-
- DWORD last_error = ::GetLastError();
- if (0 == return_value && (ERROR_FILE_NOT_FOUND == last_error ||
- ERROR_PATH_NOT_FOUND == last_error ||
- ERROR_INVALID_NAME == last_error)) {
- // The file does not exist, but maybe a sub path needs to be expanded.
- base::string16::size_type last_slash = temp_path.rfind(L'\\');
- if (base::string16::npos == last_slash)
- return false;
-
- base::string16 begin = temp_path.substr(0, last_slash);
- base::string16 end = temp_path.substr(last_slash);
- if (!ConvertToLongPath(&begin))
- return false;
-
- // Ok, it worked. Let's reset the return value.
- temp_path = begin + end;
- return_value = 1;
- } else if (0 != return_value) {
- temp_path = long_path_buf.get();
- }
-
- if (return_value != 0) {
- if (added_implied_device)
- RemoveImpliedDevice(&temp_path);
-
- if (is_nt_path) {
- *path = kNTPrefix;
- *path += temp_path;
- } else {
- *path = temp_path;
- }
-
- return true;
- }
-
- return false;
-}
-
-bool GetPathFromHandle(HANDLE handle, base::string16* path) {
- NtQueryObjectFunction NtQueryObject = NULL;
- ResolveNTFunctionPtr("NtQueryObject", &NtQueryObject);
-
- OBJECT_NAME_INFORMATION initial_buffer;
- OBJECT_NAME_INFORMATION* name = &initial_buffer;
- ULONG size = sizeof(initial_buffer);
- // Query the name information a first time to get the size of the name.
- // Windows XP requires that the size of the buffer passed in here be != 0.
- NTSTATUS status = NtQueryObject(handle, ObjectNameInformation, name, size,
- &size);
-
- scoped_ptr<BYTE[]> name_ptr;
- if (size) {
- name_ptr.reset(new BYTE[size]);
- name = reinterpret_cast<OBJECT_NAME_INFORMATION*>(name_ptr.get());
-
- // Query the name information a second time to get the name of the
- // object referenced by the handle.
- status = NtQueryObject(handle, ObjectNameInformation, name, size, &size);
- }
-
- if (STATUS_SUCCESS != status)
- return false;
-
- path->assign(name->ObjectName.Buffer, name->ObjectName.Length /
- sizeof(name->ObjectName.Buffer[0]));
- return true;
-}
-
-bool GetNtPathFromWin32Path(const base::string16& path,
- base::string16* nt_path) {
- HANDLE file = ::CreateFileW(path.c_str(), 0,
- FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
- OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
- if (file == INVALID_HANDLE_VALUE)
- return false;
- bool rv = GetPathFromHandle(file, nt_path);
- ::CloseHandle(file);
- return rv;
-}
-
-bool WriteProtectedChildMemory(HANDLE child_process, void* address,
- const void* buffer, size_t length) {
- // First, remove the protections.
- DWORD old_protection;
- if (!::VirtualProtectEx(child_process, address, length,
- PAGE_WRITECOPY, &old_protection))
- return false;
-
- SIZE_T written;
- bool ok = ::WriteProcessMemory(child_process, address, buffer, length,
- &written) && (length == written);
-
- // Always attempt to restore the original protection.
- if (!::VirtualProtectEx(child_process, address, length,
- old_protection, &old_protection))
- return false;
-
- return ok;
-}
-
-}; // namespace sandbox
-
-void ResolveNTFunctionPtr(const char* name, void* ptr) {
- static volatile HMODULE ntdll = NULL;
-
- if (!ntdll) {
- HMODULE ntdll_local = ::GetModuleHandle(sandbox::kNtdllName);
- // Use PEImage to sanity-check that we have a valid ntdll handle.
- base::win::PEImage ntdll_peimage(ntdll_local);
- CHECK_NT(ntdll_peimage.VerifyMagic());
- // Race-safe way to set static ntdll.
- ::InterlockedCompareExchangePointer(
- reinterpret_cast<PVOID volatile*>(&ntdll), ntdll_local, NULL);
-
- }
-
- CHECK_NT(ntdll);
- FARPROC* function_ptr = reinterpret_cast<FARPROC*>(ptr);
- *function_ptr = ::GetProcAddress(ntdll, name);
- CHECK_NT(*function_ptr);
-}
diff --git a/security/sandbox/chromium/sandbox/win/src/win_utils.h b/security/sandbox/chromium/sandbox/win/src/win_utils.h
deleted file mode 100644
index f7895c1b8..000000000
--- a/security/sandbox/chromium/sandbox/win/src/win_utils.h
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright (c) 2006-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 SANDBOX_SRC_WIN_UTILS_H_
-#define SANDBOX_SRC_WIN_UTILS_H_
-
-#include <windows.h>
-#include <stddef.h>
-#include <string>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-
-namespace sandbox {
-
-// Prefix for path used by NT calls.
-const wchar_t kNTPrefix[] = L"\\??\\";
-const size_t kNTPrefixLen = arraysize(kNTPrefix) - 1;
-
-const wchar_t kNTDevicePrefix[] = L"\\Device\\";
-const size_t kNTDevicePrefixLen = arraysize(kNTDevicePrefix) - 1;
-
-// Automatically acquires and releases a lock when the object is
-// is destroyed.
-class AutoLock {
- public:
- // Acquires the lock.
- explicit AutoLock(CRITICAL_SECTION *lock) : lock_(lock) {
- ::EnterCriticalSection(lock);
- };
-
- // Releases the lock;
- ~AutoLock() {
- ::LeaveCriticalSection(lock_);
- };
-
- private:
- CRITICAL_SECTION *lock_;
- DISALLOW_IMPLICIT_CONSTRUCTORS(AutoLock);
-};
-
-// Basic implementation of a singleton which calls the destructor
-// when the exe is shutting down or the DLL is being unloaded.
-template <typename Derived>
-class SingletonBase {
- public:
- static Derived* GetInstance() {
- static Derived* instance = NULL;
- if (NULL == instance) {
- instance = new Derived();
- // Microsoft CRT extension. In an exe this this called after
- // winmain returns, in a dll is called in DLL_PROCESS_DETACH
- _onexit(OnExit);
- }
- return instance;
- }
-
- private:
- // this is the function that gets called by the CRT when the
- // process is shutting down.
- static int __cdecl OnExit() {
- delete GetInstance();
- return 0;
- }
-};
-
-// Convert a short path (C:\path~1 or \\??\\c:\path~1) to the long version of
-// the path. If the path is not a valid filesystem path, the function returns
-// false and argument is not modified.
-bool ConvertToLongPath(base::string16* path);
-
-// Returns ERROR_SUCCESS if the path contains a reparse point,
-// ERROR_NOT_A_REPARSE_POINT if there's no reparse point in this path, or an
-// error code when the function fails.
-// This function is not smart. It looks for each element in the path and
-// returns true if any of them is a reparse point.
-DWORD IsReparsePoint(const base::string16& full_path);
-
-// Returns true if the handle corresponds to the object pointed by this path.
-bool SameObject(HANDLE handle, const wchar_t* full_path);
-
-// Resolves a handle to an nt path. Returns true if the handle can be resolved.
-bool GetPathFromHandle(HANDLE handle, base::string16* path);
-
-// Resolves a win32 path to an nt path using GetPathFromHandle. The path must
-// exist. Returs true if the translation was succesful.
-bool GetNtPathFromWin32Path(const base::string16& path,
- base::string16* nt_path);
-
-// Translates a reserved key name to its handle.
-// For example "HKEY_LOCAL_MACHINE" returns HKEY_LOCAL_MACHINE.
-// Returns NULL if the name does not represent any reserved key name.
-HKEY GetReservedKeyFromName(const base::string16& name);
-
-// Resolves a user-readable registry path to a system-readable registry path.
-// For example, HKEY_LOCAL_MACHINE\\Software\\microsoft is translated to
-// \\registry\\machine\\software\\microsoft. Returns false if the path
-// cannot be resolved.
-bool ResolveRegistryName(base::string16 name, base::string16* resolved_name);
-
-// Writes |length| bytes from the provided |buffer| into the address space of
-// |child_process|, at the specified |address|, preserving the original write
-// protection attributes. Returns true on success.
-bool WriteProtectedChildMemory(HANDLE child_process, void* address,
- const void* buffer, size_t length);
-
-// Returns true if the provided path points to a pipe.
-bool IsPipe(const base::string16& path);
-
-} // namespace sandbox
-
-// Resolves a function name in NTDLL to a function pointer. The second parameter
-// is a pointer to the function pointer.
-void ResolveNTFunctionPtr(const char* name, void* ptr);
-
-#endif // SANDBOX_SRC_WIN_UTILS_H_
diff --git a/security/sandbox/chromium/sandbox/win/src/win_utils_unittest.cc b/security/sandbox/chromium/sandbox/win/src/win_utils_unittest.cc
deleted file mode 100644
index fb72eb338..000000000
--- a/security/sandbox/chromium/sandbox/win/src/win_utils_unittest.cc
+++ /dev/null
@@ -1,111 +0,0 @@
-// 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 <windows.h>
-
-#include "base/win/scoped_handle.h"
-#include "sandbox/win/src/win_utils.h"
-#include "sandbox/win/tests/common/test_utils.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-TEST(WinUtils, IsReparsePoint) {
- using sandbox::IsReparsePoint;
-
- // Create a temp file because we need write access to it.
- wchar_t temp_directory[MAX_PATH];
- wchar_t my_folder[MAX_PATH];
- ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, my_folder), 0u);
-
- // Delete the file and create a directory instead.
- ASSERT_TRUE(::DeleteFile(my_folder));
- ASSERT_TRUE(::CreateDirectory(my_folder, NULL));
-
- EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT),
- IsReparsePoint(my_folder));
-
- base::string16 not_found = base::string16(my_folder) + L"\\foo\\bar";
- EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT),
- IsReparsePoint(not_found));
-
- base::string16 new_file = base::string16(my_folder) + L"\\foo";
- EXPECT_EQ(static_cast<DWORD>(ERROR_NOT_A_REPARSE_POINT),
- IsReparsePoint(new_file));
-
- // Replace the directory with a reparse point to %temp%.
- HANDLE dir = ::CreateFile(my_folder, FILE_ALL_ACCESS,
- FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
- OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
- EXPECT_NE(INVALID_HANDLE_VALUE, dir);
-
- base::string16 temp_dir_nt = base::string16(L"\\??\\") + temp_directory;
- EXPECT_TRUE(SetReparsePoint(dir, temp_dir_nt.c_str()));
-
- EXPECT_EQ(static_cast<DWORD>(ERROR_SUCCESS), IsReparsePoint(new_file));
-
- EXPECT_TRUE(DeleteReparsePoint(dir));
- EXPECT_TRUE(::CloseHandle(dir));
- EXPECT_TRUE(::RemoveDirectory(my_folder));
-}
-
-TEST(WinUtils, SameObject) {
- using sandbox::SameObject;
-
- // Create a temp file because we need write access to it.
- wchar_t temp_directory[MAX_PATH];
- wchar_t my_folder[MAX_PATH];
- ASSERT_NE(::GetTempPath(MAX_PATH, temp_directory), 0u);
- ASSERT_NE(::GetTempFileName(temp_directory, L"test", 0, my_folder), 0u);
-
- // Delete the file and create a directory instead.
- ASSERT_TRUE(::DeleteFile(my_folder));
- ASSERT_TRUE(::CreateDirectory(my_folder, NULL));
-
- base::string16 folder(my_folder);
- base::string16 file_name = folder + L"\\foo.txt";
- const ULONG kSharing = FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE;
- base::win::ScopedHandle file(CreateFile(
- file_name.c_str(), GENERIC_WRITE, kSharing, NULL, CREATE_ALWAYS,
- FILE_FLAG_DELETE_ON_CLOSE, NULL));
-
- EXPECT_TRUE(file.IsValid());
- base::string16 file_name_nt1 = base::string16(L"\\??\\") + file_name;
- base::string16 file_name_nt2 =
- base::string16(L"\\??\\") + folder + L"\\FOO.txT";
- EXPECT_TRUE(SameObject(file.Get(), file_name_nt1.c_str()));
- EXPECT_TRUE(SameObject(file.Get(), file_name_nt2.c_str()));
-
- file.Close();
- EXPECT_TRUE(::RemoveDirectory(my_folder));
-}
-
-TEST(WinUtils, IsPipe) {
- using sandbox::IsPipe;
-
- base::string16 pipe_name = L"\\??\\pipe\\mypipe";
- EXPECT_TRUE(IsPipe(pipe_name));
-
- pipe_name = L"\\??\\PiPe\\mypipe";
- EXPECT_TRUE(IsPipe(pipe_name));
-
- pipe_name = L"\\??\\pipe";
- EXPECT_FALSE(IsPipe(pipe_name));
-
- pipe_name = L"\\??\\_pipe_\\mypipe";
- EXPECT_FALSE(IsPipe(pipe_name));
-
- pipe_name = L"\\??\\ABCD\\mypipe";
- EXPECT_FALSE(IsPipe(pipe_name));
-
-
- // Written as two strings to prevent trigraph '?' '?' '/'.
- pipe_name = L"/?" L"?/pipe/mypipe";
- EXPECT_FALSE(IsPipe(pipe_name));
-
- pipe_name = L"\\XX\\pipe\\mypipe";
- EXPECT_FALSE(IsPipe(pipe_name));
-
- pipe_name = L"\\Device\\NamedPipe\\mypipe";
- EXPECT_FALSE(IsPipe(pipe_name));
-}
diff --git a/security/sandbox/chromium/sandbox/win/src/window.cc b/security/sandbox/chromium/sandbox/win/src/window.cc
deleted file mode 100644
index cfbf280d9..000000000
--- a/security/sandbox/chromium/sandbox/win/src/window.cc
+++ /dev/null
@@ -1,161 +0,0 @@
-// 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 "sandbox/win/src/window.h"
-
-#include <aclapi.h>
-
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/src/acl.h"
-#include "sandbox/win/src/sid.h"
-
-namespace {
-
-// Gets the security attributes of a window object referenced by |handle|. The
-// lpSecurityDescriptor member of the SECURITY_ATTRIBUTES parameter returned
-// must be freed using LocalFree by the caller.
-bool GetSecurityAttributes(HANDLE handle, SECURITY_ATTRIBUTES* attributes) {
- attributes->bInheritHandle = FALSE;
- attributes->nLength = sizeof(SECURITY_ATTRIBUTES);
-
- PACL dacl = NULL;
- DWORD result = ::GetSecurityInfo(handle, SE_WINDOW_OBJECT,
- DACL_SECURITY_INFORMATION, NULL, NULL, &dacl,
- NULL, &attributes->lpSecurityDescriptor);
- if (ERROR_SUCCESS == result)
- return true;
-
- return false;
-}
-
-}
-
-namespace sandbox {
-
-ResultCode CreateAltWindowStation(HWINSTA* winsta) {
- // Get the security attributes from the current window station; we will
- // use this as the base security attributes for the new window station.
- SECURITY_ATTRIBUTES attributes = {0};
- if (!GetSecurityAttributes(::GetProcessWindowStation(), &attributes)) {
- return SBOX_ERROR_CANNOT_CREATE_WINSTATION;
- }
-
- // Create the window station using NULL for the name to ask the os to
- // generate it.
- *winsta = ::CreateWindowStationW(
- NULL, 0, GENERIC_READ | WINSTA_CREATEDESKTOP, &attributes);
- LocalFree(attributes.lpSecurityDescriptor);
-
- if (*winsta)
- return SBOX_ALL_OK;
-
- return SBOX_ERROR_CANNOT_CREATE_WINSTATION;
-}
-
-ResultCode CreateAltDesktop(HWINSTA winsta, HDESK* desktop) {
- base::string16 desktop_name = L"sbox_alternate_desktop_";
-
- // Append the current PID to the desktop name.
- wchar_t buffer[16];
- _snwprintf_s(buffer, sizeof(buffer) / sizeof(wchar_t), L"0x%X",
- ::GetCurrentProcessId());
- desktop_name += buffer;
-
- // Get the security attributes from the current desktop, we will use this as
- // the base security attributes for the new desktop.
- SECURITY_ATTRIBUTES attributes = {0};
- if (!GetSecurityAttributes(GetThreadDesktop(GetCurrentThreadId()),
- &attributes)) {
- return SBOX_ERROR_CANNOT_CREATE_DESKTOP;
- }
-
- // Back up the current window station, in case we need to switch it.
- HWINSTA current_winsta = ::GetProcessWindowStation();
-
- if (winsta) {
- // We need to switch to the alternate window station before creating the
- // desktop.
- if (!::SetProcessWindowStation(winsta)) {
- ::LocalFree(attributes.lpSecurityDescriptor);
- return SBOX_ERROR_CANNOT_CREATE_DESKTOP;
- }
- }
-
- // Create the destkop.
- *desktop = ::CreateDesktop(desktop_name.c_str(),
- NULL,
- NULL,
- 0,
- DESKTOP_CREATEWINDOW | DESKTOP_READOBJECTS |
- READ_CONTROL | WRITE_DAC | WRITE_OWNER,
- &attributes);
- ::LocalFree(attributes.lpSecurityDescriptor);
-
- if (winsta) {
- // Revert to the right window station.
- if (!::SetProcessWindowStation(current_winsta)) {
- return SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION;
- }
- }
-
- if (*desktop) {
- // Replace the DACL on the new Desktop with a reduced privilege version.
- // We can soft fail on this for now, as it's just an extra mitigation.
- static const ACCESS_MASK kDesktopDenyMask = WRITE_DAC | WRITE_OWNER |
- DELETE |
- DESKTOP_CREATEMENU |
- DESKTOP_CREATEWINDOW |
- DESKTOP_HOOKCONTROL |
- DESKTOP_JOURNALPLAYBACK |
- DESKTOP_JOURNALRECORD |
- DESKTOP_SWITCHDESKTOP;
- AddKnownSidToObject(*desktop, SE_WINDOW_OBJECT, Sid(WinRestrictedCodeSid),
- DENY_ACCESS, kDesktopDenyMask);
- return SBOX_ALL_OK;
- }
-
- return SBOX_ERROR_CANNOT_CREATE_DESKTOP;
-}
-
-base::string16 GetWindowObjectName(HANDLE handle) {
- // Get the size of the name.
- DWORD size = 0;
- ::GetUserObjectInformation(handle, UOI_NAME, NULL, 0, &size);
-
- if (!size) {
- NOTREACHED();
- return base::string16();
- }
-
- // Create the buffer that will hold the name.
- scoped_ptr<wchar_t[]> name_buffer(new wchar_t[size]);
-
- // Query the name of the object.
- if (!::GetUserObjectInformation(handle, UOI_NAME, name_buffer.get(), size,
- &size)) {
- NOTREACHED();
- return base::string16();
- }
-
- return base::string16(name_buffer.get());
-}
-
-base::string16 GetFullDesktopName(HWINSTA winsta, HDESK desktop) {
- if (!desktop) {
- NOTREACHED();
- return base::string16();
- }
-
- base::string16 name;
- if (winsta) {
- name = GetWindowObjectName(winsta);
- name += L'\\';
- }
-
- name += GetWindowObjectName(desktop);
- return name;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/src/window.h b/security/sandbox/chromium/sandbox/win/src/window.h
deleted file mode 100644
index 62fe7c474..000000000
--- a/security/sandbox/chromium/sandbox/win/src/window.h
+++ /dev/null
@@ -1,40 +0,0 @@
-// 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 SANDBOX_SRC_WINDOW_H_
-#define SANDBOX_SRC_WINDOW_H_
-
-#include <windows.h>
-#include <string>
-
-#include "base/strings/string16.h"
-#include "sandbox/win/src/sandbox_types.h"
-
-namespace sandbox {
-
- // Creates a window station. The name is generated by the OS. The security
- // descriptor is based on the security descriptor of the current window
- // station.
- ResultCode CreateAltWindowStation(HWINSTA* winsta);
-
- // Creates a desktop. The name is a static string followed by the pid of the
- // current process. The security descriptor on the new desktop is based on the
- // security descriptor of the desktop associated with the current thread.
- // If a winsta is specified, the function will switch to it before creating
- // the desktop. If the functions fails the switch back to the current winsta,
- // the function will return SBOX_ERROR_FAILED_TO_SWITCH_BACK_WINSTATION.
- ResultCode CreateAltDesktop(HWINSTA winsta, HDESK* desktop);
-
- // Returns the name of a desktop or a window station.
- base::string16 GetWindowObjectName(HANDLE handle);
-
- // Returns the name of the desktop referenced by |desktop|. If a window
- // station is specified, the name is prepended with the window station name,
- // followed by a backslash. This name can be used as the lpDesktop parameter
- // to CreateProcess.
- base::string16 GetFullDesktopName(HWINSTA winsta, HDESK desktop);
-
-} // namespace sandbox
-
-#endif // SANDBOX_SRC_WINDOW_H_
diff --git a/security/sandbox/chromium/sandbox/win/wow_helper/service64_resolver.cc b/security/sandbox/chromium/sandbox/win/wow_helper/service64_resolver.cc
deleted file mode 100644
index 0424d9fdd..000000000
--- a/security/sandbox/chromium/sandbox/win/wow_helper/service64_resolver.cc
+++ /dev/null
@@ -1,346 +0,0 @@
-// 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 "sandbox/win/wow_helper/service64_resolver.h"
-
-#include <limits.h>
-#include <stddef.h>
-
-#include "base/bit_cast.h"
-#include "base/memory/scoped_ptr.h"
-#include "sandbox/win/wow_helper/target_code.h"
-
-namespace {
-#pragma pack(push, 1)
-
-const BYTE kMovEax = 0xB8;
-const BYTE kMovEdx = 0xBA;
-const USHORT kCallPtrEdx = 0x12FF;
-const BYTE kRet = 0xC2;
-const BYTE kNop = 0x90;
-const USHORT kJmpEdx = 0xE2FF;
-const USHORT kXorEcx = 0xC933;
-const ULONG kLeaEdx = 0x0424548D;
-const ULONG kCallFs1 = 0xC015FF64;
-const ULONG kCallFs2Ret = 0xC2000000;
-const BYTE kPopEdx = 0x5A;
-const BYTE kPushEdx = 0x52;
-const BYTE kPush32 = 0x68;
-
-const ULONG kMmovR10EcxMovEax = 0xB8D18B4C;
-const USHORT kSyscall = 0x050F;
-const BYTE kRetNp = 0xC3;
-const BYTE kPad = 0x66;
-const USHORT kNop16 = 0x9066;
-const BYTE kRelJmp = 0xE9;
-
-const ULONG kXorRaxMovEax = 0xB8C03148;
-const ULONG kSaveRcx = 0x10488948;
-const ULONG kMovRcxRaxJmp = 0xE9C88B48;
-
-// Service code for 64 bit systems.
-struct ServiceEntry {
- // this struct contains roughly the following code:
- // mov r10,rcx
- // mov eax,52h
- // syscall
- // ret
- // xchg ax,ax
- // xchg ax,ax
-
- ULONG mov_r10_ecx_mov_eax; // = 4C 8B D1 B8
- ULONG service_id;
- USHORT syscall; // = 0F 05
- BYTE ret; // = C3
- BYTE pad; // = 66
- USHORT xchg_ax_ax1; // = 66 90
- USHORT xchg_ax_ax2; // = 66 90
-};
-
-struct Redirected {
- // this struct contains roughly the following code:
- // jmp relative_32
- // xchg ax,ax // 3 byte nop
-
- Redirected() {
- jmp = kRelJmp;
- relative = 0;
- pad = kPad;
- xchg_ax_ax = kNop16;
- };
- BYTE jmp; // = E9
- ULONG relative;
- BYTE pad; // = 66
- USHORT xchg_ax_ax; // = 66 90
-};
-
-struct InternalThunk {
- // this struct contains roughly the following code:
- // xor rax,rax
- // mov eax, 0x00080000 // Thunk storage.
- // mov [rax]PatchInfo.service, rcx // Save first argument.
- // mov rcx, rax
- // jmp relative_to_interceptor
-
- InternalThunk() {
- xor_rax_mov_eax = kXorRaxMovEax;
- patch_info = 0;
- save_rcx = kSaveRcx;
- mov_rcx_rax_jmp = kMovRcxRaxJmp;
- relative = 0;
- };
- ULONG xor_rax_mov_eax; // = 48 31 C0 B8
- ULONG patch_info;
- ULONG save_rcx; // = 48 89 48 10
- ULONG mov_rcx_rax_jmp; // = 48 8b c8 e9
- ULONG relative;
-};
-
-struct ServiceFullThunk {
- sandbox::PatchInfo patch_info;
- ServiceEntry original;
- InternalThunk internal_thunk;
-};
-
-#pragma pack(pop)
-
-// Simple utility function to write to a buffer on the child, if the memery has
-// write protection attributes.
-// Arguments:
-// child_process (in): process to write to.
-// address (out): memory position on the child to write to.
-// buffer (in): local buffer with the data to write .
-// length (in): number of bytes to write.
-// Returns true on success.
-bool WriteProtectedChildMemory(HANDLE child_process,
- void* address,
- const void* buffer,
- size_t length) {
- // first, remove the protections
- DWORD old_protection;
- if (!::VirtualProtectEx(child_process, address, length,
- PAGE_WRITECOPY, &old_protection))
- return false;
-
- SIZE_T written;
- bool ok = ::WriteProcessMemory(child_process, address, buffer, length,
- &written) && (length == written);
-
- // always attempt to restore the original protection
- if (!::VirtualProtectEx(child_process, address, length,
- old_protection, &old_protection))
- return false;
-
- return ok;
-}
-
-// Get pointers to the functions that we need from ntdll.dll.
-NTSTATUS ResolveNtdll(sandbox::PatchInfo* patch_info) {
- wchar_t* ntdll_name = L"ntdll.dll";
- HMODULE ntdll = ::GetModuleHandle(ntdll_name);
- if (!ntdll)
- return STATUS_PROCEDURE_NOT_FOUND;
-
- void* signal = ::GetProcAddress(ntdll, "NtSignalAndWaitForSingleObject");
- if (!signal)
- return STATUS_PROCEDURE_NOT_FOUND;
-
- patch_info->signal_and_wait =
- reinterpret_cast<NtSignalAndWaitForSingleObjectFunction>(signal);
-
- return STATUS_SUCCESS;
-}
-
-}; // namespace
-
-namespace sandbox {
-
-NTSTATUS ResolverThunk::Init(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes) {
- if (NULL == thunk_storage || 0 == storage_bytes ||
- NULL == target_module || NULL == target_name)
- return STATUS_INVALID_PARAMETER;
-
- if (storage_bytes < GetThunkSize())
- return STATUS_BUFFER_TOO_SMALL;
-
- NTSTATUS ret = STATUS_SUCCESS;
- if (NULL == interceptor_entry_point) {
- ret = ResolveInterceptor(interceptor_module, interceptor_name,
- &interceptor_entry_point);
- if (!NT_SUCCESS(ret))
- return ret;
- }
-
- ret = ResolveTarget(target_module, target_name, &target_);
- if (!NT_SUCCESS(ret))
- return ret;
-
- interceptor_ = interceptor_entry_point;
-
- return ret;
-}
-
-NTSTATUS ResolverThunk::ResolveInterceptor(const void* interceptor_module,
- const char* interceptor_name,
- const void** address) {
- return STATUS_NOT_IMPLEMENTED;
-}
-
-NTSTATUS ResolverThunk::ResolveTarget(const void* module,
- const char* function_name,
- void** address) {
- return STATUS_NOT_IMPLEMENTED;
-}
-
-NTSTATUS Service64ResolverThunk::Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used) {
- NTSTATUS ret = Init(target_module, interceptor_module, target_name,
- interceptor_name, interceptor_entry_point,
- thunk_storage, storage_bytes);
- if (!NT_SUCCESS(ret))
- return ret;
-
- size_t thunk_bytes = GetThunkSize();
- scoped_ptr<char[]> thunk_buffer(new char[thunk_bytes]);
- ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(
- thunk_buffer.get());
-
- if (!IsFunctionAService(&thunk->original))
- return STATUS_UNSUCCESSFUL;
-
- ret = PerformPatch(thunk, thunk_storage);
-
- if (NULL != storage_used)
- *storage_used = thunk_bytes;
-
- return ret;
-}
-
-NTSTATUS Service64ResolverThunk::ResolveInterceptor(
- const void* interceptor_module,
- const char* interceptor_name,
- const void** address) {
- // After all, we are using a locally mapped version of the exe, so the
- // action is the same as for a target function.
- return ResolveTarget(interceptor_module, interceptor_name,
- const_cast<void**>(address));
-}
-
-// In this case all the work is done from the parent, so resolve is
-// just a simple GetProcAddress.
-NTSTATUS Service64ResolverThunk::ResolveTarget(const void* module,
- const char* function_name,
- void** address) {
- if (NULL == module)
- return STATUS_UNSUCCESSFUL;
-
- *address = ::GetProcAddress(bit_cast<HMODULE>(module), function_name);
-
- if (NULL == *address)
- return STATUS_UNSUCCESSFUL;
-
- return STATUS_SUCCESS;
-}
-
-size_t Service64ResolverThunk::GetThunkSize() const {
- return sizeof(ServiceFullThunk);
-}
-
-bool Service64ResolverThunk::IsFunctionAService(void* local_thunk) const {
- ServiceEntry function_code;
- SIZE_T read;
- if (!::ReadProcessMemory(process_, target_, &function_code,
- sizeof(function_code), &read))
- return false;
-
- if (sizeof(function_code) != read)
- return false;
-
- if (kMmovR10EcxMovEax != function_code.mov_r10_ecx_mov_eax ||
- kSyscall != function_code.syscall || kRetNp != function_code.ret)
- return false;
-
- // Save the verified code
- memcpy(local_thunk, &function_code, sizeof(function_code));
-
- return true;
-}
-
-NTSTATUS Service64ResolverThunk::PerformPatch(void* local_thunk,
- void* remote_thunk) {
- ServiceFullThunk* full_local_thunk = reinterpret_cast<ServiceFullThunk*>(
- local_thunk);
- ServiceFullThunk* full_remote_thunk = reinterpret_cast<ServiceFullThunk*>(
- remote_thunk);
-
- // If the source or target are above 4GB we cannot do this relative jump.
- if (reinterpret_cast<ULONG_PTR>(full_remote_thunk) >
- static_cast<ULONG_PTR>(ULONG_MAX))
- return STATUS_CONFLICTING_ADDRESSES;
-
- if (reinterpret_cast<ULONG_PTR>(target_) > static_cast<ULONG_PTR>(ULONG_MAX))
- return STATUS_CONFLICTING_ADDRESSES;
-
- // Patch the original code.
- Redirected local_service;
- Redirected* remote_service = reinterpret_cast<Redirected*>(target_);
- ULONG_PTR diff = reinterpret_cast<BYTE*>(&full_remote_thunk->internal_thunk) -
- &remote_service->pad;
- local_service.relative = static_cast<ULONG>(diff);
-
- // Setup the PatchInfo structure.
- SIZE_T actual;
- if (!::ReadProcessMemory(process_, remote_thunk, local_thunk,
- sizeof(PatchInfo), &actual))
- return STATUS_UNSUCCESSFUL;
- if (sizeof(PatchInfo) != actual)
- return STATUS_UNSUCCESSFUL;
-
- full_local_thunk->patch_info.orig_MapViewOfSection = reinterpret_cast<
- NtMapViewOfSectionFunction>(&full_remote_thunk->original);
- full_local_thunk->patch_info.patch_location = target_;
- NTSTATUS ret = ResolveNtdll(&full_local_thunk->patch_info);
- if (!NT_SUCCESS(ret))
- return ret;
-
- // Setup the thunk. The jump out is performed from right after the end of the
- // thunk (full_remote_thunk + 1).
- InternalThunk my_thunk;
- ULONG_PTR patch_info = reinterpret_cast<ULONG_PTR>(remote_thunk);
- my_thunk.patch_info = static_cast<ULONG>(patch_info);
- diff = reinterpret_cast<const BYTE*>(interceptor_) -
- reinterpret_cast<BYTE*>(full_remote_thunk + 1);
- my_thunk.relative = static_cast<ULONG>(diff);
-
- memcpy(&full_local_thunk->internal_thunk, &my_thunk, sizeof(my_thunk));
-
- // copy the local thunk buffer to the child
- if (!::WriteProcessMemory(process_, remote_thunk, local_thunk,
- sizeof(ServiceFullThunk), &actual))
- return STATUS_UNSUCCESSFUL;
-
- if (sizeof(ServiceFullThunk) != actual)
- return STATUS_UNSUCCESSFUL;
-
- // and now change the function to intercept, on the child
- if (!::WriteProtectedChildMemory(process_, target_, &local_service,
- sizeof(local_service)))
- return STATUS_UNSUCCESSFUL;
-
- return STATUS_SUCCESS;
-}
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/wow_helper/service64_resolver.h b/security/sandbox/chromium/sandbox/win/wow_helper/service64_resolver.h
deleted file mode 100644
index 32ee46f8e..000000000
--- a/security/sandbox/chromium/sandbox/win/wow_helper/service64_resolver.h
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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 SANDBOX_WOW_HELPER_SERVICE64_RESOLVER_H__
-#define SANDBOX_WOW_HELPER_SERVICE64_RESOLVER_H__
-
-#include <stddef.h>
-
-#include "base/macros.h"
-#include "sandbox/win/src/nt_internals.h"
-#include "sandbox/win/src/resolver.h"
-
-namespace sandbox {
-
-// This is the concrete resolver used to perform service-call type functions
-// inside ntdll.dll (64-bit).
-class Service64ResolverThunk : public ResolverThunk {
- public:
- // The service resolver needs a child process to write to.
- explicit Service64ResolverThunk(HANDLE process)
- : process_(process), ntdll_base_(NULL) {}
- virtual ~Service64ResolverThunk() {}
-
- // Implementation of Resolver::Setup.
- virtual NTSTATUS Setup(const void* target_module,
- const void* interceptor_module,
- const char* target_name,
- const char* interceptor_name,
- const void* interceptor_entry_point,
- void* thunk_storage,
- size_t storage_bytes,
- size_t* storage_used);
-
- // Implementation of Resolver::ResolveInterceptor.
- virtual NTSTATUS ResolveInterceptor(const void* module,
- const char* function_name,
- const void** address);
-
- // Implementation of Resolver::ResolveTarget.
- virtual NTSTATUS ResolveTarget(const void* module,
- const char* function_name,
- void** address);
-
- // Implementation of Resolver::GetThunkSize.
- virtual size_t GetThunkSize() const;
-
- protected:
- // The unit test will use this member to allow local patch on a buffer.
- HMODULE ntdll_base_;
-
- // Handle of the child process.
- HANDLE process_;
-
- private:
- // Returns true if the code pointer by target_ corresponds to the expected
- // type of function. Saves that code on the first part of the thunk pointed
- // by local_thunk (should be directly accessible from the parent).
- virtual bool IsFunctionAService(void* local_thunk) const;
-
- // Performs the actual patch of target_.
- // local_thunk must be already fully initialized, and the first part must
- // contain the original code. The real type of this buffer is ServiceFullThunk
- // (yes, private). remote_thunk (real type ServiceFullThunk), must be
- // allocated on the child, and will contain the thunk data, after this call.
- // Returns the apropriate status code.
- virtual NTSTATUS PerformPatch(void* local_thunk, void* remote_thunk);
-
- DISALLOW_COPY_AND_ASSIGN(Service64ResolverThunk);
-};
-
-} // namespace sandbox
-
-
-#endif // SANDBOX_WOW_HELPER_SERVICE64_RESOLVER_H__
diff --git a/security/sandbox/chromium/sandbox/win/wow_helper/target_code.cc b/security/sandbox/chromium/sandbox/win/wow_helper/target_code.cc
deleted file mode 100644
index ce44eeba2..000000000
--- a/security/sandbox/chromium/sandbox/win/wow_helper/target_code.cc
+++ /dev/null
@@ -1,38 +0,0 @@
-// 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 "sandbox/win/wow_helper/target_code.h"
-
-namespace sandbox {
-
-// Hooks NtMapViewOfSection to detect the load of dlls.
-#pragma code_seg(push, code, ".TargetCode$A")
-NTSTATUS WINAPI TargetNtMapViewOfSection(
- PatchInfo *patch_info, HANDLE process, PVOID *base, ULONG_PTR zero_bits,
- SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size,
- SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect) {
- NTSTATUS ret = patch_info->orig_MapViewOfSection(patch_info->section, process,
- base, zero_bits, commit_size,
- offset, view_size, inherit,
- allocation_type, protect);
-
- LARGE_INTEGER timeout;
- timeout.QuadPart = -(5 * 10000000); // 5 seconds.
-
- // The wait is alertable.
- patch_info->signal_and_wait(patch_info->dll_load, patch_info->continue_load,
- TRUE, &timeout);
-
- return ret;
-}
-#pragma code_seg(pop, code)
-
-// Marks the end of the code to copy to the target process.
-#pragma code_seg(push, code, ".TargetCode$B")
-NTSTATUS WINAPI TargetEnd() {
- return STATUS_SUCCESS;
-}
-#pragma code_seg(pop, code)
-
-} // namespace sandbox
diff --git a/security/sandbox/chromium/sandbox/win/wow_helper/target_code.h b/security/sandbox/chromium/sandbox/win/wow_helper/target_code.h
deleted file mode 100644
index c198a852e..000000000
--- a/security/sandbox/chromium/sandbox/win/wow_helper/target_code.h
+++ /dev/null
@@ -1,41 +0,0 @@
-// 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 SANDBOX_WOW_HELPER_TARGET_CODE_H__
-#define SANDBOX_WOW_HELPER_TARGET_CODE_H__
-
-#include "sandbox/win/src/nt_internals.h"
-
-namespace sandbox {
-
-extern "C" {
-
-// Holds the information needed for the interception of NtMapViewOfSection.
-// Changes of this structure must be synchronized with changes of PatchInfo32
-// on sandbox/win/src/wow64.cc.
-struct PatchInfo {
- HANDLE dll_load; // Event to signal the broker.
- HANDLE continue_load; // Event to wait for the broker.
- HANDLE section; // First argument of the call.
- NtMapViewOfSectionFunction orig_MapViewOfSection;
- NtSignalAndWaitForSingleObjectFunction signal_and_wait;
- void* patch_location;
-};
-
-// Interception of NtMapViewOfSection on the child process.
-// It should never be called directly. This function provides the means to
-// detect dlls being loaded, so we can patch them if needed.
-NTSTATUS WINAPI TargetNtMapViewOfSection(
- PatchInfo* patch_info, HANDLE process, PVOID* base, ULONG_PTR zero_bits,
- SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size,
- SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect);
-
-// Marker of the end of TargetNtMapViewOfSection.
-NTSTATUS WINAPI TargetEnd();
-
-} // extern "C"
-
-} // namespace sandbox
-
-#endif // SANDBOX_WOW_HELPER_TARGET_CODE_H__
diff --git a/security/sandbox/chromium/sandbox/win/wow_helper/wow_helper.cc b/security/sandbox/chromium/sandbox/win/wow_helper/wow_helper.cc
deleted file mode 100644
index af76cbc13..000000000
--- a/security/sandbox/chromium/sandbox/win/wow_helper/wow_helper.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-// 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.
-
-// Wow_helper.exe is a simple Win32 64-bit executable designed to help to
-// sandbox a 32 bit application running on a 64 bit OS. The basic idea is to
-// perform a 64 bit interception of the target process and notify the 32-bit
-// broker process whenever a DLL is being loaded. This allows the broker to
-// setup the interceptions (32-bit) properly on the target.
-
-#include <windows.h>
-#include <stddef.h>
-
-#include <string>
-
-#include "sandbox/win/wow_helper/service64_resolver.h"
-#include "sandbox/win/wow_helper/target_code.h"
-
-namespace sandbox {
-
-// Performs the interception of NtMapViewOfSection on the 64-bit version of
-// ntdll.dll. 'thunk' is the buffer on the address space of process 'child',
-// that will be used to store the information about the patch.
-int PatchNtdll(HANDLE child, void* thunk, size_t thunk_bytes) {
- wchar_t* ntdll_name = L"ntdll.dll";
- HMODULE ntdll_base = ::GetModuleHandle(ntdll_name);
- if (!ntdll_base)
- return 100;
-
- Service64ResolverThunk resolver(child);
- size_t used = resolver.GetThunkSize();
- char* code = reinterpret_cast<char*>(thunk) + used;
- NTSTATUS ret = resolver.Setup(ntdll_base, NULL, "NtMapViewOfSection", NULL,
- code, thunk, thunk_bytes, NULL);
- if (!NT_SUCCESS(ret))
- return 101;
-
- size_t size = reinterpret_cast<char*>(&TargetEnd) -
- reinterpret_cast<char*>(&TargetNtMapViewOfSection);
-
- if (size + used > thunk_bytes)
- return 102;
-
- SIZE_T written;
- if (!::WriteProcessMemory(child, code, &TargetNtMapViewOfSection, size,
- &written))
- return 103;
-
- if (size != written)
- return 104;
-
- return 0;
-}
-
-} // namespace sandbox
-
-// We must receive two arguments: the process id of the target to intercept and
-// the address of a page of memory on that process that will be used for the
-// interception. We receive the address because the broker will cleanup the
-// patch when the work is performed.
-//
-// It should be noted that we don't wait until the real work is done; this
-// program quits as soon as the 64-bit interception is performed.
-int wWinMain(HINSTANCE, HINSTANCE, wchar_t* command_line, int) {
- static_assert(sizeof(void*) > sizeof(DWORD), "unsupported 32 bits");
- if (!command_line)
- return 1;
-
- wchar_t* next;
- DWORD process_id = wcstoul(command_line, &next, 0);
- if (!process_id)
- return 2;
-
- DWORD access = PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE;
- HANDLE child = ::OpenProcess(access, FALSE, process_id);
- if (!child)
- return 3;
-
- DWORD buffer = wcstoul(next, NULL, 0);
- if (!buffer)
- return 4;
-
- void* thunk = reinterpret_cast<void*>(static_cast<ULONG_PTR>(buffer));
-
- const size_t kPageSize = 4096;
- return sandbox::PatchNtdll(child, thunk, kPageSize);
-}
diff --git a/security/sandbox/linux/LinuxCapabilities.cpp b/security/sandbox/linux/LinuxCapabilities.cpp
deleted file mode 100644
index 87e24a009..000000000
--- a/security/sandbox/linux/LinuxCapabilities.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/* -*- 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 "LinuxCapabilities.h"
-
-#include <unistd.h>
-#include <sys/syscall.h>
-
-namespace mozilla {
-
-bool
-LinuxCapabilities::GetCurrent() {
- __user_cap_header_struct header = { _LINUX_CAPABILITY_VERSION_3, 0 };
- return syscall(__NR_capget, &header, &mBits) == 0
- && header.version == _LINUX_CAPABILITY_VERSION_3;
-}
-
-bool
-LinuxCapabilities::SetCurrentRaw() const {
- __user_cap_header_struct header = { _LINUX_CAPABILITY_VERSION_3, 0 };
- return syscall(__NR_capset, &header, &mBits) == 0
- && header.version == _LINUX_CAPABILITY_VERSION_3;
-}
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/LinuxCapabilities.h b/security/sandbox/linux/LinuxCapabilities.h
deleted file mode 100644
index 9d3220841..000000000
--- a/security/sandbox/linux/LinuxCapabilities.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/* -*- 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_LinuxCapabilities_h
-#define mozilla_LinuxCapabilities_h
-
-#include <linux/capability.h>
-#include <stdint.h>
-
-#include "mozilla/Assertions.h"
-#include "mozilla/Attributes.h"
-#include "mozilla/PodOperations.h"
-
-// This class is a relatively simple interface to manipulating the
-// capabilities of a Linux process/thread; see the capabilities(7) man
-// page for background information.
-
-// Unfortunately, Android's kernel headers omit some definitions
-// needed for the low-level capability interface. They're part of the
-// stable syscall ABI, so it's safe to include them here.
-#ifndef _LINUX_CAPABILITY_VERSION_3
-#define _LINUX_CAPABILITY_VERSION_3 0x20080522
-#define _LINUX_CAPABILITY_U32S_3 2
-#endif
-#ifndef CAP_TO_INDEX
-#define CAP_TO_INDEX(x) ((x) >> 5)
-#define CAP_TO_MASK(x) (1 << ((x) & 31))
-#endif
-
-namespace mozilla {
-
-class LinuxCapabilities final
-{
-public:
- // A class to represent a bit within the capability sets as an lvalue.
- class BitRef {
- __u32& mWord;
- __u32 mMask;
- friend class LinuxCapabilities;
- BitRef(__u32& aWord, uint32_t aMask) : mWord(aWord), mMask(aMask) { }
- BitRef(const BitRef& aBit) : mWord(aBit.mWord), mMask(aBit.mMask) { }
- public:
- MOZ_IMPLICIT operator bool() const {
- return mWord & mMask;
- }
- BitRef& operator=(bool aSetTo) {
- if (aSetTo) {
- mWord |= mMask;
- } else {
- mWord &= mMask;
- }
- return *this;
- }
- };
-
- // The default value is the empty set.
- LinuxCapabilities() { PodArrayZero(mBits); }
-
- // Get the current thread's capability sets and assign them to this
- // object. Returns whether it succeeded and sets errno on failure.
- // Shouldn't fail unless the kernel is very old.
- bool GetCurrent();
-
- // Try to set the current thread's capability sets to those
- // specified in this object. Returns whether it succeeded and sets
- // errno on failure.
- bool SetCurrentRaw() const;
-
- // The capability model requires that the permitted set always be a
- // superset of the effective and inheritable sets. This method
- // expands the permitted set as needed and then sets the current
- // thread's capabilities, as described above.
- bool SetCurrent() {
- Normalize();
- return SetCurrentRaw();
- }
-
- void Normalize() {
- for (size_t i = 0; i < _LINUX_CAPABILITY_U32S_3; ++i) {
- mBits[i].permitted |= mBits[i].effective | mBits[i].inheritable;
- }
- }
-
- bool AnyEffective() const {
- for (size_t i = 0; i < _LINUX_CAPABILITY_U32S_3; ++i) {
- if (mBits[i].effective != 0) {
- return true;
- }
- }
- return false;
- }
-
- // These three methods expose individual bits in the three
- // capability sets as objects that can be used as bool lvalues.
- // The argument is the capability number, as defined in
- // the <linux/capability.h> header.
- BitRef Effective(unsigned aCap)
- {
- return GenericBitRef(&__user_cap_data_struct::effective, aCap);
- }
-
- BitRef Permitted(unsigned aCap)
- {
- return GenericBitRef(&__user_cap_data_struct::permitted, aCap);
- }
-
- BitRef Inheritable(unsigned aCap)
- {
- return GenericBitRef(&__user_cap_data_struct::inheritable, aCap);
- }
-
-private:
- __user_cap_data_struct mBits[_LINUX_CAPABILITY_U32S_3];
-
- BitRef GenericBitRef(__u32 __user_cap_data_struct::* aField, unsigned aCap)
- {
- // Please don't pass untrusted data as the capability number.
- MOZ_ASSERT(CAP_TO_INDEX(aCap) < _LINUX_CAPABILITY_U32S_3);
- return BitRef(mBits[CAP_TO_INDEX(aCap)].*aField, CAP_TO_MASK(aCap));
- }
-};
-
-} // namespace mozilla
-
-#endif // mozilla_LinuxCapabilities_h
diff --git a/security/sandbox/linux/LinuxSched.h b/security/sandbox/linux/LinuxSched.h
deleted file mode 100644
index 148067d34..000000000
--- a/security/sandbox/linux/LinuxSched.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/* -*- 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_LinuxSched_h
-#define mozilla_LinuxSched_h
-
-#include <linux/sched.h>
-
-// Some build environments, in particular the Android NDK, don't
-// define some of the newer clone/unshare flags ("newer" relatively
-// speaking; CLONE_NEWUTS is present since kernel 2.6.19 in 2006).
-
-#ifndef CLONE_NEWUTS
-#define CLONE_NEWUTS 0x04000000
-#endif
-#ifndef CLONE_NEWIPC
-#define CLONE_NEWIPC 0x08000000
-#endif
-#ifndef CLONE_NEWUSER
-#define CLONE_NEWUSER 0x10000000
-#endif
-#ifndef CLONE_NEWPID
-#define CLONE_NEWPID 0x20000000
-#endif
-#ifndef CLONE_NEWNET
-#define CLONE_NEWNET 0x40000000
-#endif
-#ifndef CLONE_IO
-#define CLONE_IO 0x80000000
-#endif
-
-#endif
diff --git a/security/sandbox/linux/Sandbox.cpp b/security/sandbox/linux/Sandbox.cpp
deleted file mode 100644
index 7f1182be9..000000000
--- a/security/sandbox/linux/Sandbox.cpp
+++ /dev/null
@@ -1,693 +0,0 @@
-/* -*- 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 "Sandbox.h"
-
-#include "LinuxCapabilities.h"
-#include "LinuxSched.h"
-#include "SandboxBrokerClient.h"
-#include "SandboxChroot.h"
-#include "SandboxFilter.h"
-#include "SandboxInternal.h"
-#include "SandboxLogging.h"
-#include "SandboxUtil.h"
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/futex.h>
-#include <pthread.h>
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/prctl.h>
-#include <sys/ptrace.h>
-#include <sys/syscall.h>
-#include <sys/time.h>
-#include <unistd.h>
-
-#include "mozilla/Atomics.h"
-#include "mozilla/Maybe.h"
-#include "mozilla/SandboxInfo.h"
-#include "mozilla/UniquePtr.h"
-#include "mozilla/Unused.h"
-#include "sandbox/linux/bpf_dsl/codegen.h"
-#include "sandbox/linux/bpf_dsl/dump_bpf.h"
-#include "sandbox/linux/bpf_dsl/policy.h"
-#include "sandbox/linux/bpf_dsl/policy_compiler.h"
-#include "sandbox/linux/bpf_dsl/seccomp_macros.h"
-#include "sandbox/linux/seccomp-bpf/trap.h"
-#include "sandbox/linux/system_headers/linux_filter.h"
-#include "sandbox/linux/system_headers/linux_seccomp.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-#if defined(ANDROID)
-#include "sandbox/linux/system_headers/linux_ucontext.h"
-#endif
-
-#ifdef MOZ_ASAN
-// Copy libsanitizer declarations to avoid depending on ASAN headers.
-// See also bug 1081242 comment #4.
-extern "C" {
-namespace __sanitizer {
-// Win64 uses long long, but this is Linux.
-typedef signed long sptr;
-} // namespace __sanitizer
-
-typedef struct {
- int coverage_sandboxed;
- __sanitizer::sptr coverage_fd;
- unsigned int coverage_max_block_size;
-} __sanitizer_sandbox_arguments;
-
-MOZ_IMPORT_API void
-__sanitizer_sandbox_on_notify(__sanitizer_sandbox_arguments *args);
-} // extern "C"
-#endif // MOZ_ASAN
-
-// Signal number used to enable seccomp on each thread.
-int gSeccompTsyncBroadcastSignum = 0;
-
-namespace mozilla {
-
-// This is initialized by SandboxSetCrashFunc().
-SandboxCrashFunc gSandboxCrashFunc;
-
-#ifdef MOZ_GMP_SANDBOX
-// For media plugins, we can start the sandbox before we dlopen the
-// module, so we have to pre-open the file and simulate the sandboxed
-// open().
-static SandboxOpenedFile gMediaPluginFile;
-#endif
-
-static UniquePtr<SandboxChroot> gChrootHelper;
-static void (*gChromiumSigSysHandler)(int, siginfo_t*, void*);
-
-// Test whether a ucontext, interpreted as the state after a syscall,
-// indicates the given error. See also sandbox::Syscall::PutValueInUcontext.
-static bool
-ContextIsError(const ucontext_t *aContext, int aError)
-{
- // Avoid integer promotion warnings. (The unary addition makes
- // the decltype not evaluate to a reference type.)
- typedef decltype(+SECCOMP_RESULT(aContext)) reg_t;
-
-#ifdef __mips__
- return SECCOMP_PARM4(aContext) != 0
- && SECCOMP_RESULT(aContext) == static_cast<reg_t>(aError);
-#else
- return SECCOMP_RESULT(aContext) == static_cast<reg_t>(-aError);
-#endif
-}
-
-/**
- * This is the SIGSYS handler function. It delegates to the Chromium
- * TrapRegistry handler (see InstallSigSysHandler, below) and, if the
- * trap handler installed by the policy would fail with ENOSYS,
- * crashes the process. This allows unintentional policy failures to
- * be reported as crash dumps and fixed. It also logs information
- * about the failed system call.
- *
- * Note that this could be invoked in parallel on multiple threads and
- * that it could be in async signal context (e.g., intercepting an
- * open() called from an async signal handler).
- */
-static void
-SigSysHandler(int nr, siginfo_t *info, void *void_context)
-{
- ucontext_t *ctx = static_cast<ucontext_t*>(void_context);
- // This shouldn't ever be null, but the Chromium handler checks for
- // that and refrains from crashing, so let's not crash release builds:
- MOZ_DIAGNOSTIC_ASSERT(ctx);
- if (!ctx) {
- return;
- }
-
- // Save a copy of the context before invoking the trap handler,
- // which will overwrite one or more registers with the return value.
- ucontext_t savedCtx = *ctx;
-
- gChromiumSigSysHandler(nr, info, ctx);
- if (!ContextIsError(ctx, ENOSYS)) {
- return;
- }
-
- pid_t pid = getpid();
- unsigned long syscall_nr = SECCOMP_SYSCALL(&savedCtx);
- unsigned long args[6];
- args[0] = SECCOMP_PARM1(&savedCtx);
- args[1] = SECCOMP_PARM2(&savedCtx);
- args[2] = SECCOMP_PARM3(&savedCtx);
- args[3] = SECCOMP_PARM4(&savedCtx);
- args[4] = SECCOMP_PARM5(&savedCtx);
- args[5] = SECCOMP_PARM6(&savedCtx);
-
- // TODO, someday when this is enabled on MIPS: include the two extra
- // args in the error message.
- SANDBOX_LOG_ERROR("seccomp sandbox violation: pid %d, syscall %d,"
- " args %d %d %d %d %d %d. Killing process.",
- pid, syscall_nr,
- args[0], args[1], args[2], args[3], args[4], args[5]);
-
- // Bug 1017393: record syscall number somewhere useful.
- info->si_addr = reinterpret_cast<void*>(syscall_nr);
-
- gSandboxCrashFunc(nr, info, &savedCtx);
- _exit(127);
-}
-
-/**
- * This function installs the SIGSYS handler. This is slightly
- * complicated because we want to use Chromium's handler to dispatch
- * to specific trap handlers defined in the policy, but we also need
- * the full original signal context to give to Breakpad for crash
- * dumps. So we install Chromium's handler first, then retrieve its
- * address so our replacement can delegate to it.
- */
-static void
-InstallSigSysHandler(void)
-{
- struct sigaction act;
-
- // Ensure that the Chromium handler is installed.
- Unused << sandbox::Trap::Registry();
-
- // If the signal handling state isn't as expected, crash now instead
- // of crashing later (and more confusingly) when SIGSYS happens.
-
- if (sigaction(SIGSYS, nullptr, &act) != 0) {
- MOZ_CRASH("Couldn't read old SIGSYS disposition");
- }
- if ((act.sa_flags & SA_SIGINFO) != SA_SIGINFO) {
- MOZ_CRASH("SIGSYS not already set to a siginfo handler?");
- }
- MOZ_RELEASE_ASSERT(act.sa_sigaction);
- gChromiumSigSysHandler = act.sa_sigaction;
- act.sa_sigaction = SigSysHandler;
- // Currently, SA_NODEFER should already be set by the Chromium code,
- // but it's harmless to ensure that it's set:
- MOZ_ASSERT(act.sa_flags & SA_NODEFER);
- act.sa_flags |= SA_NODEFER;
- if (sigaction(SIGSYS, &act, nullptr) < 0) {
- MOZ_CRASH("Couldn't change SIGSYS disposition");
- }
-}
-
-/**
- * This function installs the syscall filter, a.k.a. seccomp. The
- * aUseTSync flag indicates whether this should apply to all threads
- * in the process -- which will fail if the kernel doesn't support
- * that -- or only the current thread.
- *
- * SECCOMP_MODE_FILTER is the "bpf" mode of seccomp which allows
- * to pass a bpf program (in our case, it contains a syscall
- * whitelist).
- *
- * PR_SET_NO_NEW_PRIVS ensures that it is impossible to grant more
- * syscalls to the process beyond this point (even after fork()), and
- * prevents gaining capabilities (e.g., by exec'ing a setuid root
- * program). The kernel won't allow seccomp-bpf without doing this,
- * because otherwise it could be used for privilege escalation attacks.
- *
- * Returns false if the filter was already installed (see the
- * PR_SET_NO_NEW_PRIVS rule in SandboxFilter.cpp). Crashes on any
- * other error condition.
- *
- * @see SandboxInfo
- * @see BroadcastSetThreadSandbox
- */
-static bool MOZ_MUST_USE
-InstallSyscallFilter(const sock_fprog *aProg, bool aUseTSync)
-{
- if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
- if (!aUseTSync && errno == ETXTBSY) {
- return false;
- }
- SANDBOX_LOG_ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %s", strerror(errno));
- MOZ_CRASH("prctl(PR_SET_NO_NEW_PRIVS)");
- }
-
- if (aUseTSync) {
- if (syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER,
- SECCOMP_FILTER_FLAG_TSYNC, aProg) != 0) {
- SANDBOX_LOG_ERROR("thread-synchronized seccomp failed: %s",
- strerror(errno));
- MOZ_CRASH("prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER)");
- }
- } else {
- if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, (unsigned long)aProg, 0, 0)) {
- SANDBOX_LOG_ERROR("prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER) failed: %s",
- strerror(errno));
- MOZ_CRASH("seccomp+tsync failed, but kernel supports tsync");
- }
- }
- return true;
-}
-
-// Use signals for permissions that need to be set per-thread.
-// The communication channel from the signal handler back to the main thread.
-static mozilla::Atomic<int> gSetSandboxDone;
-// Pass the filter itself through a global.
-const sock_fprog* gSetSandboxFilter;
-
-// We have to dynamically allocate the signal number; see bug 1038900.
-// This function returns the first realtime signal currently set to
-// default handling (i.e., not in use), or 0 if none could be found.
-//
-// WARNING: if this function or anything similar to it (including in
-// external libraries) is used on multiple threads concurrently, there
-// will be a race condition.
-static int
-FindFreeSignalNumber()
-{
- for (int signum = SIGRTMAX; signum >= SIGRTMIN; --signum) {
- struct sigaction sa;
-
- if (sigaction(signum, nullptr, &sa) == 0 &&
- (sa.sa_flags & SA_SIGINFO) == 0 &&
- sa.sa_handler == SIG_DFL) {
- return signum;
- }
- }
- return 0;
-}
-
-// Returns true if sandboxing was enabled, or false if sandboxing
-// already was enabled. Crashes if sandboxing could not be enabled.
-static bool
-SetThreadSandbox()
-{
- return InstallSyscallFilter(gSetSandboxFilter, false);
-}
-
-static void
-SetThreadSandboxHandler(int signum)
-{
- // The non-zero number sent back to the main thread indicates
- // whether action was taken.
- if (SetThreadSandbox()) {
- gSetSandboxDone = 2;
- } else {
- gSetSandboxDone = 1;
- }
- // Wake up the main thread. See the FUTEX_WAIT call, below, for an
- // explanation.
- syscall(__NR_futex, reinterpret_cast<int*>(&gSetSandboxDone),
- FUTEX_WAKE, 1);
-}
-
-static void
-EnterChroot()
-{
- if (gChrootHelper) {
- gChrootHelper->Invoke();
- gChrootHelper = nullptr;
- }
-}
-
-static void
-BroadcastSetThreadSandbox(const sock_fprog* aFilter)
-{
- pid_t pid, tid, myTid;
- DIR *taskdp;
- struct dirent *de;
-
- // This function does not own *aFilter, so this global needs to
- // always be zeroed before returning.
- gSetSandboxFilter = aFilter;
-
- static_assert(sizeof(mozilla::Atomic<int>) == sizeof(int),
- "mozilla::Atomic<int> isn't represented by an int");
- pid = getpid();
- myTid = syscall(__NR_gettid);
- taskdp = opendir("/proc/self/task");
- if (taskdp == nullptr) {
- SANDBOX_LOG_ERROR("opendir /proc/self/task: %s\n", strerror(errno));
- MOZ_CRASH();
- }
-
- EnterChroot();
-
- // In case this races with a not-yet-deprivileged thread cloning
- // itself, repeat iterating over all threads until we find none
- // that are still privileged.
- bool sandboxProgress;
- do {
- sandboxProgress = false;
- // For each thread...
- while ((de = readdir(taskdp))) {
- char *endptr;
- tid = strtol(de->d_name, &endptr, 10);
- if (*endptr != '\0' || tid <= 0) {
- // Not a task ID.
- continue;
- }
- if (tid == myTid) {
- // Drop this thread's privileges last, below, so we can
- // continue to signal other threads.
- continue;
- }
-
- MOZ_RELEASE_ASSERT(gSeccompTsyncBroadcastSignum != 0);
-
- // Reset the futex cell and signal.
- gSetSandboxDone = 0;
- if (syscall(__NR_tgkill, pid, tid, gSeccompTsyncBroadcastSignum) != 0) {
- if (errno == ESRCH) {
- SANDBOX_LOG_ERROR("Thread %d unexpectedly exited.", tid);
- // Rescan threads, in case it forked before exiting.
- sandboxProgress = true;
- continue;
- }
- SANDBOX_LOG_ERROR("tgkill(%d,%d): %s\n", pid, tid, strerror(errno));
- MOZ_CRASH();
- }
- // It's unlikely, but if the thread somehow manages to exit
- // after receiving the signal but before entering the signal
- // handler, we need to avoid blocking forever.
- //
- // Using futex directly lets the signal handler send the wakeup
- // from an async signal handler (pthread mutex/condvar calls
- // aren't allowed), and to use a relative timeout that isn't
- // affected by changes to the system clock (not possible with
- // POSIX semaphores).
- //
- // If a thread doesn't respond within a reasonable amount of
- // time, but still exists, we crash -- the alternative is either
- // blocking forever or silently losing security, and it
- // shouldn't actually happen.
- static const int crashDelay = 10; // seconds
- struct timespec timeLimit;
- clock_gettime(CLOCK_MONOTONIC, &timeLimit);
- timeLimit.tv_sec += crashDelay;
- while (true) {
- static const struct timespec futexTimeout = { 0, 10*1000*1000 }; // 10ms
- // Atomically: if gSetSandboxDone == 0, then sleep.
- if (syscall(__NR_futex, reinterpret_cast<int*>(&gSetSandboxDone),
- FUTEX_WAIT, 0, &futexTimeout) != 0) {
- if (errno != EWOULDBLOCK && errno != ETIMEDOUT && errno != EINTR) {
- SANDBOX_LOG_ERROR("FUTEX_WAIT: %s\n", strerror(errno));
- MOZ_CRASH();
- }
- }
- // Did the handler finish?
- if (gSetSandboxDone > 0) {
- if (gSetSandboxDone == 2) {
- sandboxProgress = true;
- }
- break;
- }
- // Has the thread ceased to exist?
- if (syscall(__NR_tgkill, pid, tid, 0) != 0) {
- if (errno == ESRCH) {
- SANDBOX_LOG_ERROR("Thread %d unexpectedly exited.", tid);
- }
- // Rescan threads, in case it forked before exiting.
- // Also, if it somehow failed in a way that wasn't ESRCH,
- // and still exists, that will be handled on the next pass.
- sandboxProgress = true;
- break;
- }
- struct timespec now;
- clock_gettime(CLOCK_MONOTONIC, &now);
- if (now.tv_sec > timeLimit.tv_sec ||
- (now.tv_sec == timeLimit.tv_sec &&
- now.tv_nsec > timeLimit.tv_nsec)) {
- SANDBOX_LOG_ERROR("Thread %d unresponsive for %d seconds."
- " Killing process.",
- tid, crashDelay);
- MOZ_CRASH();
- }
- }
- }
- rewinddir(taskdp);
- } while (sandboxProgress);
-
- void (*oldHandler)(int);
- oldHandler = signal(gSeccompTsyncBroadcastSignum, SIG_DFL);
- gSeccompTsyncBroadcastSignum = 0;
- if (oldHandler != SetThreadSandboxHandler) {
- // See the comment on FindFreeSignalNumber about race conditions.
- SANDBOX_LOG_ERROR("handler for signal %d was changed to %p!",
- gSeccompTsyncBroadcastSignum, oldHandler);
- MOZ_CRASH();
- }
- Unused << closedir(taskdp);
- // And now, deprivilege the main thread:
- SetThreadSandbox();
- gSetSandboxFilter = nullptr;
-}
-
-static void
-ApplySandboxWithTSync(sock_fprog* aFilter)
-{
- EnterChroot();
- // At this point we're committed to using tsync, because the signal
- // broadcast workaround needs to access procfs. (Unless chroot
- // isn't used... but this failure shouldn't happen in the first
- // place, so let's not make extra special cases for it.)
- if (!InstallSyscallFilter(aFilter, true)) {
- MOZ_CRASH();
- }
-}
-
-// Common code for sandbox startup.
-static void
-SetCurrentProcessSandbox(UniquePtr<sandbox::bpf_dsl::Policy> aPolicy)
-{
- MOZ_ASSERT(gSandboxCrashFunc);
-
- // Note: PolicyCompiler borrows the policy and registry for its
- // lifetime, but does not take ownership of them.
- sandbox::bpf_dsl::PolicyCompiler compiler(aPolicy.get(),
- sandbox::Trap::Registry());
- sandbox::CodeGen::Program program = compiler.Compile();
- if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
- sandbox::bpf_dsl::DumpBPF::PrintProgram(program);
- }
-
- InstallSigSysHandler();
-
-#ifdef MOZ_ASAN
- __sanitizer_sandbox_arguments asanArgs;
- asanArgs.coverage_sandboxed = 1;
- asanArgs.coverage_fd = -1;
- asanArgs.coverage_max_block_size = 0;
- __sanitizer_sandbox_on_notify(&asanArgs);
-#endif
-
- // The syscall takes a C-style array, so copy the vector into one.
- size_t programLen = program.size();
- UniquePtr<sock_filter[]> flatProgram(new sock_filter[programLen]);
- for (auto i = program.begin(); i != program.end(); ++i) {
- flatProgram[i - program.begin()] = *i;
- }
-
- sock_fprog fprog;
- fprog.filter = flatProgram.get();
- fprog.len = static_cast<unsigned short>(programLen);
- MOZ_RELEASE_ASSERT(static_cast<size_t>(fprog.len) == programLen);
-
- const SandboxInfo info = SandboxInfo::Get();
- if (info.Test(SandboxInfo::kHasSeccompTSync)) {
- if (info.Test(SandboxInfo::kVerbose)) {
- SANDBOX_LOG_ERROR("using seccomp tsync");
- }
- ApplySandboxWithTSync(&fprog);
- } else {
- if (info.Test(SandboxInfo::kVerbose)) {
- SANDBOX_LOG_ERROR("no tsync support; using signal broadcast");
- }
- BroadcastSetThreadSandbox(&fprog);
- }
- MOZ_RELEASE_ASSERT(!gChrootHelper, "forgot to chroot");
-}
-
-void
-SandboxEarlyInit(GeckoProcessType aType)
-{
- const SandboxInfo info = SandboxInfo::Get();
- if (info.Test(SandboxInfo::kUnexpectedThreads)) {
- return;
- }
- MOZ_RELEASE_ASSERT(IsSingleThreaded());
-
- // Which kinds of resource isolation (of those that need to be set
- // up at this point) can be used by this process?
- bool canChroot = false;
- bool canUnshareNet = false;
- bool canUnshareIPC = false;
-
- switch (aType) {
- case GeckoProcessType_Default:
- MOZ_ASSERT(false, "SandboxEarlyInit in parent process");
- return;
-#ifdef MOZ_GMP_SANDBOX
- case GeckoProcessType_GMPlugin:
- if (!info.Test(SandboxInfo::kEnabledForMedia)) {
- break;
- }
- canUnshareNet = true;
- canUnshareIPC = true;
- // Need seccomp-bpf to intercept open().
- canChroot = info.Test(SandboxInfo::kHasSeccompBPF);
- break;
-#endif
- // In the future, content processes will be able to use some of
- // these.
- default:
- // Other cases intentionally left blank.
- break;
- }
-
- // If TSYNC is not supported, set up signal handler
- // used to enable seccomp on each thread.
- if (!info.Test(SandboxInfo::kHasSeccompTSync)) {
- gSeccompTsyncBroadcastSignum = FindFreeSignalNumber();
- if (gSeccompTsyncBroadcastSignum == 0) {
- SANDBOX_LOG_ERROR("No available signal numbers!");
- MOZ_CRASH();
- }
-
- void (*oldHandler)(int);
- oldHandler = signal(gSeccompTsyncBroadcastSignum, SetThreadSandboxHandler);
- if (oldHandler != SIG_DFL) {
- // See the comment on FindFreeSignalNumber about race conditions.
- SANDBOX_LOG_ERROR("signal %d in use by handler %p!\n",
- gSeccompTsyncBroadcastSignum, oldHandler);
- MOZ_CRASH();
- }
- }
-
- // If there's nothing to do, then we're done.
- if (!canChroot && !canUnshareNet && !canUnshareIPC) {
- return;
- }
-
- {
- LinuxCapabilities existingCaps;
- if (existingCaps.GetCurrent() && existingCaps.AnyEffective()) {
- SANDBOX_LOG_ERROR("PLEASE DO NOT RUN THIS AS ROOT. Strange things may"
- " happen when capabilities are dropped.");
- }
- }
-
- // If capabilities can't be gained, then nothing can be done.
- if (!info.Test(SandboxInfo::kHasUserNamespaces)) {
- // Drop any existing capabilities; unsharing the user namespace
- // would implicitly drop them, so if we're running in a broken
- // configuration where that would matter (e.g., running as root
- // from a non-root-owned mode-0700 directory) this means it will
- // break the same way on all kernels and be easier to troubleshoot.
- LinuxCapabilities().SetCurrent();
- return;
- }
-
- // The failure cases for the various unshares, and setting up the
- // chroot helper, don't strictly need to be fatal -- but they also
- // shouldn't fail on any reasonable system, so let's take the small
- // risk of breakage over the small risk of quietly providing less
- // security than we expect. (Unlike in SandboxInfo, this is in the
- // child process, so crashing here isn't as severe a response to the
- // unexpected.)
- if (!UnshareUserNamespace()) {
- SANDBOX_LOG_ERROR("unshare(CLONE_NEWUSER): %s", strerror(errno));
- // If CanCreateUserNamespace (SandboxInfo.cpp) returns true, then
- // the unshare shouldn't have failed.
- MOZ_CRASH("unshare(CLONE_NEWUSER)");
- }
- // No early returns after this point! We need to drop the
- // capabilities that were gained by unsharing the user namesapce.
-
- if (canUnshareIPC && syscall(__NR_unshare, CLONE_NEWIPC) != 0) {
- SANDBOX_LOG_ERROR("unshare(CLONE_NEWIPC): %s", strerror(errno));
- MOZ_CRASH("unshare(CLONE_NEWIPC)");
- }
-
- if (canUnshareNet && syscall(__NR_unshare, CLONE_NEWNET) != 0) {
- SANDBOX_LOG_ERROR("unshare(CLONE_NEWNET): %s", strerror(errno));
- MOZ_CRASH("unshare(CLONE_NEWNET)");
- }
-
- if (canChroot) {
- gChrootHelper = MakeUnique<SandboxChroot>();
- if (!gChrootHelper->Prepare()) {
- SANDBOX_LOG_ERROR("failed to set up chroot helper");
- MOZ_CRASH("SandboxChroot::Prepare");
- }
- }
-
- if (!LinuxCapabilities().SetCurrent()) {
- SANDBOX_LOG_ERROR("dropping capabilities: %s", strerror(errno));
- MOZ_CRASH("can't drop capabilities");
- }
-}
-
-#ifdef MOZ_CONTENT_SANDBOX
-/**
- * Starts the seccomp sandbox for a content process. Should be called
- * only once, and before any potentially harmful content is loaded.
- *
- * Will normally make the process exit on failure.
-*/
-bool
-SetContentProcessSandbox(int aBrokerFd)
-{
- if (!SandboxInfo::Get().Test(SandboxInfo::kEnabledForContent)) {
- if (aBrokerFd >= 0) {
- close(aBrokerFd);
- }
- return false;
- }
-
- // This needs to live until the process exits.
- static Maybe<SandboxBrokerClient> sBroker;
- if (aBrokerFd >= 0) {
- sBroker.emplace(aBrokerFd);
- }
-
- SetCurrentProcessSandbox(GetContentSandboxPolicy(sBroker.ptrOr(nullptr)));
- return true;
-}
-#endif // MOZ_CONTENT_SANDBOX
-
-#ifdef MOZ_GMP_SANDBOX
-/**
- * Starts the seccomp sandbox for a media plugin process. Should be
- * called only once, and before any potentially harmful content is
- * loaded -- including the plugin itself, if it's considered untrusted.
- *
- * The file indicated by aFilePath, if non-null, can be open()ed
- * read-only, once, after the sandbox starts; it should be the .so
- * file implementing the not-yet-loaded plugin.
- *
- * Will normally make the process exit on failure.
-*/
-void
-SetMediaPluginSandbox(const char *aFilePath)
-{
- if (!SandboxInfo::Get().Test(SandboxInfo::kEnabledForMedia)) {
- return;
- }
-
- MOZ_ASSERT(!gMediaPluginFile.mPath);
- if (aFilePath) {
- gMediaPluginFile.mPath = strdup(aFilePath);
- gMediaPluginFile.mFd = open(aFilePath, O_RDONLY | O_CLOEXEC);
- if (gMediaPluginFile.mFd == -1) {
- SANDBOX_LOG_ERROR("failed to open plugin file %s: %s",
- aFilePath, strerror(errno));
- MOZ_CRASH();
- }
- } else {
- gMediaPluginFile.mFd = -1;
- }
- // Finally, start the sandbox.
- SetCurrentProcessSandbox(GetMediaSandboxPolicy(&gMediaPluginFile));
-}
-#endif // MOZ_GMP_SANDBOX
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/Sandbox.h b/security/sandbox/linux/Sandbox.h
deleted file mode 100644
index 94b26e25b..000000000
--- a/security/sandbox/linux/Sandbox.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* -*- 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_Sandbox_h
-#define mozilla_Sandbox_h
-
-#include "mozilla/Types.h"
-#include "nsXULAppAPI.h"
-
-// This defines the entry points for a content process to start
-// sandboxing itself. See also SandboxInfo.h for what parts of
-// sandboxing are enabled/supported.
-
-namespace mozilla {
-
-// This must be called early, while the process is still single-threaded.
-MOZ_EXPORT void SandboxEarlyInit(GeckoProcessType aType);
-
-#ifdef MOZ_CONTENT_SANDBOX
-// Call only if SandboxInfo::CanSandboxContent() returns true.
-// (No-op if MOZ_DISABLE_CONTENT_SANDBOX is set.)
-// aBrokerFd is the filesystem broker client file descriptor,
-// or -1 to allow direct filesystem access.
-MOZ_EXPORT bool SetContentProcessSandbox(int aBrokerFd);
-#endif
-
-#ifdef MOZ_GMP_SANDBOX
-// Call only if SandboxInfo::CanSandboxMedia() returns true.
-// (No-op if MOZ_DISABLE_GMP_SANDBOX is set.)
-// aFilePath is the path to the plugin file.
-MOZ_EXPORT void SetMediaPluginSandbox(const char *aFilePath);
-#endif
-
-} // namespace mozilla
-
-#endif // mozilla_Sandbox_h
diff --git a/security/sandbox/linux/SandboxBrokerClient.cpp b/security/sandbox/linux/SandboxBrokerClient.cpp
deleted file mode 100644
index 68744ad02..000000000
--- a/security/sandbox/linux/SandboxBrokerClient.cpp
+++ /dev/null
@@ -1,247 +0,0 @@
-/* -*- 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 "SandboxBrokerClient.h"
-#include "SandboxInfo.h"
-#include "SandboxLogging.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "mozilla/Assertions.h"
-#include "mozilla/NullPtr.h"
-#include "base/strings/safe_sprintf.h"
-
-namespace mozilla {
-
-SandboxBrokerClient::SandboxBrokerClient(int aFd)
-: mFileDesc(aFd)
-{
-}
-
-SandboxBrokerClient::~SandboxBrokerClient()
-{
- close(mFileDesc);
-}
-
-int
-SandboxBrokerClient::DoCall(const Request* aReq, const char* aPath,
- const char* aPath2, void* aResponseBuff,
- bool expectFd)
-{
- // Remap /proc/self to the actual pid, so that the broker can open
- // it. This happens here instead of in the broker to follow the
- // principle of least privilege and keep the broker as simple as
- // possible. (Note: when pid namespaces happen, this will also need
- // to remap the inner pid to the outer pid.)
- // We only remap the first path.
- static const char kProcSelf[] = "/proc/self/";
- static const size_t kProcSelfLen = sizeof(kProcSelf) - 1;
- const char* path = aPath;
- // This buffer just needs to be large enough for any such path that
- // the policy would actually allow. sizeof("/proc/2147483647/") == 18.
- char rewrittenPath[64];
- if (strncmp(aPath, kProcSelf, kProcSelfLen) == 0) {
- ssize_t len =
- base::strings::SafeSPrintf(rewrittenPath, "/proc/%d/%s",
- getpid(), aPath + kProcSelfLen);
- if (static_cast<size_t>(len) < sizeof(rewrittenPath)) {
- if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
- SANDBOX_LOG_ERROR("rewriting %s -> %s", aPath, rewrittenPath);
- }
- path = rewrittenPath;
- } else {
- SANDBOX_LOG_ERROR("not rewriting unexpectedly long path %s", aPath);
- }
- }
-
- struct iovec ios[3];
- int respFds[2];
-
- // Set up iovecs for request + path.
- ios[0].iov_base = const_cast<Request*>(aReq);
- ios[0].iov_len = sizeof(*aReq);
- ios[1].iov_base = const_cast<char*>(path);
- ios[1].iov_len = strlen(path) + 1;
- if (aPath2 != nullptr) {
- ios[2].iov_base = const_cast<char*>(aPath2);
- ios[2].iov_len = strlen(aPath2) + 1;
- } else {
- ios[2].iov_base = 0;
- ios[2].iov_len = 0;
- }
- if (ios[1].iov_len > kMaxPathLen) {
- return -ENAMETOOLONG;
- }
- if (ios[2].iov_len > kMaxPathLen) {
- return -ENAMETOOLONG;
- }
-
- // Create response socket and send request.
- if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, respFds) < 0) {
- return -errno;
- }
- const ssize_t sent = SendWithFd(mFileDesc, ios, 3, respFds[1]);
- const int sendErrno = errno;
- MOZ_ASSERT(sent < 0 ||
- static_cast<size_t>(sent) == ios[0].iov_len
- + ios[1].iov_len
- + ios[2].iov_len);
- close(respFds[1]);
- if (sent < 0) {
- close(respFds[0]);
- return -sendErrno;
- }
-
- // Set up iovecs for response.
- Response resp;
- ios[0].iov_base = &resp;
- ios[0].iov_len = sizeof(resp);
- if (aResponseBuff) {
- ios[1].iov_base = aResponseBuff;
- ios[1].iov_len = aReq->mBufSize;
- } else {
- ios[1].iov_base = nullptr;
- ios[1].iov_len = 0;
- }
-
- // Wait for response and return appropriately.
- int openedFd = -1;
- const ssize_t recvd = RecvWithFd(respFds[0], ios, aResponseBuff ? 2 : 1,
- expectFd ? &openedFd : nullptr);
- const int recvErrno = errno;
- close(respFds[0]);
- if (recvd < 0) {
- return -recvErrno;
- }
- if (recvd == 0) {
- SANDBOX_LOG_ERROR("Unexpected EOF, op %d flags 0%o path %s",
- aReq->mOp, aReq->mFlags, path);
- return -EIO;
- }
- MOZ_ASSERT(static_cast<size_t>(recvd) <= ios[0].iov_len + ios[1].iov_len);
- // Some calls such as readlink return a size if successful
- if (resp.mError >= 0) {
- // Success!
- if (expectFd) {
- MOZ_ASSERT(openedFd >= 0);
- return openedFd;
- }
- return resp.mError;
- }
- if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
- // Keep in mind that "rejected" files can include ones that don't
- // actually exist, if it's something that's optional or part of a
- // search path (e.g., shared libraries). In those cases, this
- // error message is expected.
- SANDBOX_LOG_ERROR("Rejected errno %d op %d flags 0%o path %s",
- resp.mError, aReq->mOp, aReq->mFlags, path);
- }
- if (openedFd >= 0) {
- close(openedFd);
- }
- return resp.mError;
-}
-
-int
-SandboxBrokerClient::Open(const char* aPath, int aFlags)
-{
- Request req = { SANDBOX_FILE_OPEN, aFlags, 0 };
- int maybeFd = DoCall(&req, aPath, nullptr, nullptr, true);
- if (maybeFd >= 0) {
- // NSPR has opinions about file flags. Fix O_CLOEXEC.
- if ((aFlags & O_CLOEXEC) == 0) {
- fcntl(maybeFd, F_SETFD, 0);
- }
- }
- return maybeFd;
-}
-
-int
-SandboxBrokerClient::Access(const char* aPath, int aMode)
-{
- Request req = { SANDBOX_FILE_ACCESS, aMode, 0 };
- return DoCall(&req, aPath, nullptr, nullptr, false);
-}
-
-int
-SandboxBrokerClient::Stat(const char* aPath, statstruct* aStat)
-{
- Request req = { SANDBOX_FILE_STAT, 0, sizeof(statstruct) };
- return DoCall(&req, aPath, nullptr, (void*)aStat, false);
-}
-
-int
-SandboxBrokerClient::LStat(const char* aPath, statstruct* aStat)
-{
- Request req = { SANDBOX_FILE_STAT, O_NOFOLLOW, sizeof(statstruct) };
- return DoCall(&req, aPath, nullptr, (void*)aStat, false);
-}
-
-int
-SandboxBrokerClient::Chmod(const char* aPath, int aMode)
-{
- Request req = {SANDBOX_FILE_CHMOD, aMode, 0};
- return DoCall(&req, aPath, nullptr, nullptr, false);
-}
-
-int
-SandboxBrokerClient::Link(const char* aOldPath, const char* aNewPath)
-{
- Request req = {SANDBOX_FILE_LINK, 0, 0};
- return DoCall(&req, aOldPath, aNewPath, nullptr, false);
-}
-
-int
-SandboxBrokerClient::Symlink(const char* aOldPath, const char* aNewPath)
-{
- Request req = {SANDBOX_FILE_SYMLINK, 0, 0};
- return DoCall(&req, aOldPath, aNewPath, nullptr, false);
-}
-
-int
-SandboxBrokerClient::Rename(const char* aOldPath, const char* aNewPath)
-{
- Request req = {SANDBOX_FILE_RENAME, 0, 0};
- return DoCall(&req, aOldPath, aNewPath, nullptr, false);
-}
-
-int
-SandboxBrokerClient::Mkdir(const char* aPath, int aMode)
-{
- Request req = {SANDBOX_FILE_MKDIR, aMode, 0};
- return DoCall(&req, aPath, nullptr, nullptr, false);
-}
-
-int
-SandboxBrokerClient::Unlink(const char* aPath)
-{
- Request req = {SANDBOX_FILE_UNLINK, 0, 0};
- return DoCall(&req, aPath, nullptr, nullptr, false);
-}
-
-int
-SandboxBrokerClient::Rmdir(const char* aPath)
-{
- Request req = {SANDBOX_FILE_RMDIR, 0, 0};
- return DoCall(&req, aPath, nullptr, nullptr, false);
-}
-
-int
-SandboxBrokerClient::Readlink(const char* aPath, void* aBuff, size_t aSize)
-{
- Request req = {SANDBOX_FILE_READLINK, 0, aSize};
- return DoCall(&req, aPath, nullptr, aBuff, false);
-}
-
-} // namespace mozilla
-
diff --git a/security/sandbox/linux/SandboxBrokerClient.h b/security/sandbox/linux/SandboxBrokerClient.h
deleted file mode 100644
index 06db2f183..000000000
--- a/security/sandbox/linux/SandboxBrokerClient.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/* -*- 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_SandboxBrokerClient_h
-#define mozilla_SandboxBrokerClient_h
-
-#include "broker/SandboxBrokerCommon.h"
-#include "broker/SandboxBrokerUtils.h"
-
-#include "mozilla/Attributes.h"
-
-// This is the client for the sandbox broker described in
-// broker/SandboxBroker.h; its constructor takes the file descriptor
-// returned by SandboxBroker::Create, passed to the child over IPC.
-//
-// The operations exposed here can be called from any thread and in
-// async signal handlers, like the corresponding system calls. The
-// intended use is from a seccomp-bpf SIGSYS handler, to transparently
-// replace those syscalls, but they could also be used directly.
-
-struct stat;
-
-namespace mozilla {
-
-class SandboxBrokerClient final : private SandboxBrokerCommon {
- public:
- explicit SandboxBrokerClient(int aFd);
- ~SandboxBrokerClient();
-
- int Open(const char* aPath, int aFlags);
- int Access(const char* aPath, int aMode);
- int Stat(const char* aPath, statstruct* aStat);
- int LStat(const char* aPath, statstruct* aStat);
- int Chmod(const char* aPath, int aMode);
- int Link(const char* aPath, const char* aPath2);
- int Mkdir(const char* aPath, int aMode);
- int Symlink(const char* aOldPath, const char* aNewPath);
- int Rename(const char* aOldPath, const char* aNewPath);
- int Unlink(const char* aPath);
- int Rmdir(const char* aPath);
- int Readlink(const char* aPath, void* aBuf, size_t aBufSize);
-
- private:
- int mFileDesc;
-
- int DoCall(const Request* aReq,
- const char* aPath,
- const char* aPath2,
- void *aReponseBuff,
- bool expectFd);
-};
-
-} // namespace mozilla
-
-#endif // mozilla_SandboxBrokerClient_h
diff --git a/security/sandbox/linux/SandboxChroot.cpp b/security/sandbox/linux/SandboxChroot.cpp
deleted file mode 100644
index 2091bfe05..000000000
--- a/security/sandbox/linux/SandboxChroot.cpp
+++ /dev/null
@@ -1,212 +0,0 @@
-/* -*- 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 "SandboxChroot.h"
-
-#include "SandboxLogging.h"
-#include "LinuxCapabilities.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "base/posix/eintr_wrapper.h"
-#include "mozilla/Assertions.h"
-#include "mozilla/DebugOnly.h"
-#include "mozilla/NullPtr.h"
-
-#define MOZ_ALWAYS_ZERO(e) MOZ_ALWAYS_TRUE((e) == 0)
-
-namespace mozilla {
-
-SandboxChroot::SandboxChroot()
-{
- pthread_mutexattr_t attr;
- MOZ_ALWAYS_ZERO(pthread_mutexattr_init(&attr));
- MOZ_ALWAYS_ZERO(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK));
- MOZ_ALWAYS_ZERO(pthread_mutex_init(&mMutex, &attr));
- MOZ_ALWAYS_ZERO(pthread_cond_init(&mWakeup, nullptr));
- mCommand = NO_THREAD;
-}
-
-SandboxChroot::~SandboxChroot()
-{
- SendCommand(JUST_EXIT);
- MOZ_ALWAYS_ZERO(pthread_mutex_destroy(&mMutex));
- MOZ_ALWAYS_ZERO(pthread_cond_destroy(&mWakeup));
-}
-
-bool
-SandboxChroot::SendCommand(Command aComm)
-{
- MOZ_ALWAYS_ZERO(pthread_mutex_lock(&mMutex));
- if (mCommand == NO_THREAD) {
- MOZ_RELEASE_ASSERT(aComm == JUST_EXIT);
- MOZ_ALWAYS_ZERO(pthread_mutex_unlock(&mMutex));
- return false;
- } else {
- MOZ_ASSERT(mCommand == NO_COMMAND);
- mCommand = aComm;
- MOZ_ALWAYS_ZERO(pthread_mutex_unlock(&mMutex));
- MOZ_ALWAYS_ZERO(pthread_cond_signal(&mWakeup));
- void *retval;
- if (pthread_join(mThread, &retval) != 0 || retval != nullptr) {
- MOZ_CRASH("Failed to stop privileged chroot thread");
- }
- MOZ_ASSERT(mCommand == NO_THREAD);
- }
- return true;
-}
-
-static void
-AlwaysClose(int fd)
-{
- if (IGNORE_EINTR(close(fd)) != 0) {
- SANDBOX_LOG_ERROR("close: %s", strerror(errno));
- MOZ_CRASH("failed to close()");
- }
-}
-
-static int
-OpenDeletedDirectory()
-{
- // We don't need this directory to persist between invocations of
- // the program (nor need it to be cleaned up if something goes wrong
- // here, because mkdtemp will choose a fresh name), so /tmp as
- // specified by FHS is adequate.
- //
- // However, this needs a filesystem where a deleted directory can
- // still be used, and /tmp is sometimes not that; e.g., aufs(5),
- // often used for containers, will cause the chroot() to fail with
- // ESTALE (bug 1162965). So this uses /dev/shm if possible instead.
- char tmpPath[] = "/tmp/mozsandbox.XXXXXX";
- char shmPath[] = "/dev/shm/mozsandbox.XXXXXX";
- char* path;
- if (mkdtemp(shmPath)) {
- path = shmPath;
- } else if (mkdtemp(tmpPath)) {
- path = tmpPath;
- } else {
- SANDBOX_LOG_ERROR("mkdtemp: %s", strerror(errno));
- return -1;
- }
- int fd = HANDLE_EINTR(open(path, O_RDONLY | O_DIRECTORY));
- if (fd < 0) {
- SANDBOX_LOG_ERROR("open %s: %s", path, strerror(errno));
- // Try to clean up. Shouldn't fail, but livable if it does.
- DebugOnly<bool> ok = HANDLE_EINTR(rmdir(path)) == 0;
- MOZ_ASSERT(ok);
- return -1;
- }
- if (HANDLE_EINTR(rmdir(path)) != 0) {
- SANDBOX_LOG_ERROR("rmdir %s: %s", path, strerror(errno));
- AlwaysClose(fd);
- return -1;
- }
- return fd;
-}
-
-bool
-SandboxChroot::Prepare()
-{
- LinuxCapabilities caps;
- if (!caps.GetCurrent() || !caps.Effective(CAP_SYS_CHROOT)) {
- SANDBOX_LOG_ERROR("don't have permission to chroot");
- return false;
- }
- mFd = OpenDeletedDirectory();
- if (mFd < 0) {
- SANDBOX_LOG_ERROR("failed to create empty directory for chroot");
- return false;
- }
- MOZ_ALWAYS_ZERO(pthread_mutex_lock(&mMutex));
- MOZ_ASSERT(mCommand == NO_THREAD);
- if (pthread_create(&mThread, nullptr, StaticThreadMain, this) != 0) {
- MOZ_ALWAYS_ZERO(pthread_mutex_unlock(&mMutex));
- SANDBOX_LOG_ERROR("pthread_create: %s", strerror(errno));
- return false;
- }
- while (mCommand != NO_COMMAND) {
- MOZ_ASSERT(mCommand == NO_THREAD);
- MOZ_ALWAYS_ZERO(pthread_cond_wait(&mWakeup, &mMutex));
- }
- MOZ_ALWAYS_ZERO(pthread_mutex_unlock(&mMutex));
- return true;
-}
-
-void
-SandboxChroot::Invoke()
-{
- MOZ_ALWAYS_TRUE(SendCommand(DO_CHROOT));
-}
-
-static bool
-ChrootToFileDesc(int fd)
-{
- if (fchdir(fd) != 0) {
- SANDBOX_LOG_ERROR("fchdir: %s", strerror(errno));
- return false;
- }
- if (chroot(".") != 0) {
- SANDBOX_LOG_ERROR("chroot: %s", strerror(errno));
- return false;
- }
- return true;
-}
-
-/* static */ void*
-SandboxChroot::StaticThreadMain(void* aVoidPtr)
-{
- static_cast<SandboxChroot*>(aVoidPtr)->ThreadMain();
- return nullptr;
-}
-
-void
-SandboxChroot::ThreadMain()
-{
- // First, drop everything that isn't CAP_SYS_CHROOT. (This code
- // assumes that this thread already has effective CAP_SYS_CHROOT,
- // because Prepare() checked for it before creating this thread.)
- LinuxCapabilities caps;
- caps.Effective(CAP_SYS_CHROOT) = true;
- if (!caps.SetCurrent()) {
- SANDBOX_LOG_ERROR("capset: %s", strerror(errno));
- MOZ_CRASH("Can't limit chroot thread's capabilities");
- }
-
- MOZ_ALWAYS_ZERO(pthread_mutex_lock(&mMutex));
- MOZ_ASSERT(mCommand == NO_THREAD);
- mCommand = NO_COMMAND;
- MOZ_ALWAYS_ZERO(pthread_cond_signal(&mWakeup));
- while (mCommand == NO_COMMAND) {
- MOZ_ALWAYS_ZERO(pthread_cond_wait(&mWakeup, &mMutex));
- }
- if (mCommand == DO_CHROOT) {
- MOZ_ASSERT(mFd >= 0);
- if (!ChrootToFileDesc(mFd)) {
- MOZ_CRASH("Failed to chroot");
- }
- } else {
- MOZ_ASSERT(mCommand == JUST_EXIT);
- }
- if (mFd >= 0) {
- AlwaysClose(mFd);
- mFd = -1;
- }
- mCommand = NO_THREAD;
- MOZ_ALWAYS_ZERO(pthread_mutex_unlock(&mMutex));
- // Drop the remaining capabilities; see note in SandboxChroot.h
- // about the potential unreliability of pthread_join.
- if (!LinuxCapabilities().SetCurrent()) {
- MOZ_CRASH("can't drop capabilities");
- }
-}
-
-} // namespace mozilla
-
-#undef MOZ_ALWAYS_ZERO
diff --git a/security/sandbox/linux/SandboxChroot.h b/security/sandbox/linux/SandboxChroot.h
deleted file mode 100644
index 3ad89b732..000000000
--- a/security/sandbox/linux/SandboxChroot.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/* -*- 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_SandboxChroot_h
-#define mozilla_SandboxChroot_h
-
-#include <pthread.h>
-
-#include "mozilla/Attributes.h"
-
-// This class uses the chroot(2) system call and Linux namespaces to
-// revoke the process's access to the filesystem. It requires that
-// the process be able to create user namespaces; this is the
-// kHasUserNamespaces in SandboxInfo.h.
-//
-// Usage: call Prepare() from a thread with CAP_SYS_CHROOT in its
-// effective capability set, then later call Invoke() when ready to
-// drop filesystem access. Prepare() creates a thread to do the
-// chrooting, so the caller can (and should!) drop its own
-// capabilities afterwards. When Invoke() returns, the thread will
-// have exited.
-//
-// (Exception: on Android/B2G <= KitKat, because of how pthread_join
-// is implemented, the thread may still exist, but it will not have
-// capabilities. Accordingly, on such systems, be careful about
-// namespaces or other resources the thread might have inherited.)
-//
-// Prepare() can fail (return false); for example, if it doesn't have
-// CAP_SYS_CHROOT or if it can't create a directory to chroot into.
-//
-// The root directory will be empty and deleted, so the process will
-// not be able to create new entries in it regardless of permissions.
-
-namespace mozilla {
-
-class SandboxChroot final {
-public:
- SandboxChroot();
- ~SandboxChroot();
- bool Prepare();
- void Invoke();
-private:
- enum Command {
- NO_THREAD,
- NO_COMMAND,
- DO_CHROOT,
- JUST_EXIT,
- };
-
- pthread_t mThread;
- pthread_mutex_t mMutex;
- pthread_cond_t mWakeup;
- Command mCommand;
- int mFd;
-
- void ThreadMain();
- static void* StaticThreadMain(void* aVoidPtr);
- bool SendCommand(Command aComm);
-};
-
-} // namespace mozilla
-
-#endif // mozilla_SandboxChroot_h
diff --git a/security/sandbox/linux/SandboxFilter.cpp b/security/sandbox/linux/SandboxFilter.cpp
deleted file mode 100644
index f8db9dc80..000000000
--- a/security/sandbox/linux/SandboxFilter.cpp
+++ /dev/null
@@ -1,961 +0,0 @@
-/* -*- 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 "SandboxFilter.h"
-#include "SandboxFilterUtil.h"
-
-#include "SandboxBrokerClient.h"
-#include "SandboxInfo.h"
-#include "SandboxInternal.h"
-#include "SandboxLogging.h"
-
-#include "mozilla/UniquePtr.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/ipc.h>
-#include <linux/net.h>
-#include <linux/prctl.h>
-#include <linux/sched.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <sys/socket.h>
-#include <sys/syscall.h>
-#include <time.h>
-#include <unistd.h>
-
-#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
-#include "sandbox/linux/system_headers/linux_seccomp.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-using namespace sandbox::bpf_dsl;
-#define CASES SANDBOX_BPF_DSL_CASES
-
-// Fill in defines in case of old headers.
-// (Warning: these are wrong on PA-RISC.)
-#ifndef MADV_NOHUGEPAGE
-#define MADV_NOHUGEPAGE 15
-#endif
-#ifndef MADV_DONTDUMP
-#define MADV_DONTDUMP 16
-#endif
-
-// Added in Linux 4.5; see bug 1303813.
-#ifndef MADV_FREE
-#define MADV_FREE 8
-#endif
-
-#ifndef PR_SET_PTRACER
-#define PR_SET_PTRACER 0x59616d61
-#endif
-
-// To avoid visual confusion between "ifdef ANDROID" and "ifndef ANDROID":
-#ifndef ANDROID
-#define DESKTOP
-#endif
-
-// This file defines the seccomp-bpf system call filter policies.
-// See also SandboxFilterUtil.h, for the CASES_FOR_* macros and
-// SandboxFilterBase::Evaluate{Socket,Ipc}Call.
-//
-// One important difference from how Chromium bpf_dsl filters are
-// normally interpreted: returning -ENOSYS from a Trap() handler
-// indicates an unexpected system call; SigSysHandler() in Sandbox.cpp
-// will detect this, request a crash dump, and terminate the process.
-// This does not apply to using Error(ENOSYS) in the policy, so that
-// can be used if returning an actual ENOSYS is needed.
-
-namespace mozilla {
-
-// This class whitelists everything used by the sandbox itself, by the
-// core IPC code, by the crash reporter, or other core code.
-class SandboxPolicyCommon : public SandboxPolicyBase
-{
-protected:
- typedef const sandbox::arch_seccomp_data& ArgsRef;
-
- static intptr_t BlockedSyscallTrap(ArgsRef aArgs, void *aux) {
- MOZ_ASSERT(!aux);
- return -ENOSYS;
- }
-
-private:
-#if defined(ANDROID) && ANDROID_VERSION < 16
- // Bug 1093893: Translate tkill to tgkill for pthread_kill; fixed in
- // bionic commit 10c8ce59a (in JB and up; API level 16 = Android 4.1).
- static intptr_t TKillCompatTrap(const sandbox::arch_seccomp_data& aArgs,
- void *aux)
- {
- return syscall(__NR_tgkill, getpid(), aArgs.args[0], aArgs.args[1]);
- }
-#endif
-
- static intptr_t SetNoNewPrivsTrap(ArgsRef& aArgs, void* aux) {
- if (gSetSandboxFilter == nullptr) {
- // Called after BroadcastSetThreadSandbox finished, therefore
- // not our doing and not expected.
- return BlockedSyscallTrap(aArgs, nullptr);
- }
- // Signal that the filter is already in place.
- return -ETXTBSY;
- }
-
-public:
- virtual ResultExpr InvalidSyscall() const override {
- return Trap(BlockedSyscallTrap, nullptr);
- }
-
- virtual ResultExpr ClonePolicy(ResultExpr failPolicy) const {
- // Allow use for simple thread creation (pthread_create) only.
-
- // WARNING: s390 and cris pass the flags in the second arg -- see
- // CLONE_BACKWARDS2 in arch/Kconfig in the kernel source -- but we
- // don't support seccomp-bpf on those archs yet.
- Arg<int> flags(0);
-
- // The glibc source hasn't changed the thread creation clone flags
- // since 2004, so this *should* be safe to hard-code. Bionic's
- // value has changed a few times, and has converged on the same one
- // as glibc; allow any of them.
- static const int flags_common = CLONE_VM | CLONE_FS | CLONE_FILES |
- CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM;
- static const int flags_modern = flags_common | CLONE_SETTLS |
- CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID;
-
- // Can't use CASES here because its decltype magic infers const
- // int instead of regular int and bizarre voluminous errors issue
- // forth from the depths of the standard library implementation.
- return Switch(flags)
-#ifdef ANDROID
- .Case(flags_common | CLONE_DETACHED, Allow()) // <= JB 4.2
- .Case(flags_common, Allow()) // JB 4.3 or KK 4.4
-#endif
- .Case(flags_modern, Allow()) // Android L or glibc
- .Default(failPolicy);
- }
-
- virtual ResultExpr PrctlPolicy() const {
- // Note: this will probably need PR_SET_VMA if/when it's used on
- // Android without being overridden by an allow-all policy, and
- // the constant will need to be defined locally.
- Arg<int> op(0);
- return Switch(op)
- .CASES((PR_GET_SECCOMP, // BroadcastSetThreadSandbox, etc.
- PR_SET_NAME, // Thread creation
- PR_SET_DUMPABLE, // Crash reporting
- PR_SET_PTRACER), // Debug-mode crash handling
- Allow())
- .Default(InvalidSyscall());
- }
-
- virtual Maybe<ResultExpr> EvaluateSocketCall(int aCall) const override {
- switch (aCall) {
- case SYS_RECVMSG:
- case SYS_SENDMSG:
- return Some(Allow());
- default:
- return Nothing();
- }
- }
-
- virtual ResultExpr EvaluateSyscall(int sysno) const override {
- switch (sysno) {
- // Timekeeping
- case __NR_clock_gettime: {
- Arg<clockid_t> clk_id(0);
- return If(clk_id == CLOCK_MONOTONIC, Allow())
-#ifdef CLOCK_MONOTONIC_COARSE
- .ElseIf(clk_id == CLOCK_MONOTONIC_COARSE, Allow())
-#endif
- .ElseIf(clk_id == CLOCK_PROCESS_CPUTIME_ID, Allow())
- .ElseIf(clk_id == CLOCK_REALTIME, Allow())
-#ifdef CLOCK_REALTIME_COARSE
- .ElseIf(clk_id == CLOCK_REALTIME_COARSE, Allow())
-#endif
- .ElseIf(clk_id == CLOCK_THREAD_CPUTIME_ID, Allow())
- .Else(InvalidSyscall());
- }
- case __NR_gettimeofday:
-#ifdef __NR_time
- case __NR_time:
-#endif
- case __NR_nanosleep:
- return Allow();
-
- // Thread synchronization
- case __NR_futex:
- // FIXME: This could be more restrictive....
- return Allow();
-
- // Asynchronous I/O
- case __NR_epoll_wait:
- case __NR_epoll_pwait:
- case __NR_epoll_ctl:
- case __NR_ppoll:
- case __NR_poll:
- return Allow();
-
- // Used when requesting a crash dump.
- case __NR_pipe:
- return Allow();
-
- // Metadata of opened files
- CASES_FOR_fstat:
- return Allow();
-
- // Simple I/O
- case __NR_write:
- case __NR_read:
- case __NR_readv:
- case __NR_writev: // see SandboxLogging.cpp
- CASES_FOR_lseek:
- return Allow();
-
- // Memory mapping
- CASES_FOR_mmap:
- case __NR_munmap:
- return Allow();
-
- // Signal handling
-#if defined(ANDROID) || defined(MOZ_ASAN)
- case __NR_sigaltstack:
-#endif
- CASES_FOR_sigreturn:
- CASES_FOR_sigprocmask:
- CASES_FOR_sigaction:
- return Allow();
-
- // Send signals within the process (raise(), profiling, etc.)
- case __NR_tgkill: {
- Arg<pid_t> tgid(0);
- return If(tgid == getpid(), Allow())
- .Else(InvalidSyscall());
- }
-
-#if defined(ANDROID) && ANDROID_VERSION < 16
- // Polyfill with tgkill; see above.
- case __NR_tkill:
- return Trap(TKillCompatTrap, nullptr);
-#endif
-
- // Yield
- case __NR_sched_yield:
- return Allow();
-
- // Thread creation.
- case __NR_clone:
- return ClonePolicy(InvalidSyscall());
-
- // More thread creation.
-#ifdef __NR_set_robust_list
- case __NR_set_robust_list:
- return Allow();
-#endif
-#ifdef ANDROID
- case __NR_set_tid_address:
- return Allow();
-#endif
-
- // prctl
- case __NR_prctl: {
- if (SandboxInfo::Get().Test(SandboxInfo::kHasSeccompTSync)) {
- return PrctlPolicy();
- }
-
- Arg<int> option(0);
- return If(option == PR_SET_NO_NEW_PRIVS,
- Trap(SetNoNewPrivsTrap, nullptr))
- .Else(PrctlPolicy());
- }
-
- // NSPR can call this when creating a thread, but it will accept a
- // polite "no".
- case __NR_getpriority:
- // But if thread creation races with sandbox startup, that call
- // could succeed, and then we get one of these:
- case __NR_setpriority:
- return Error(EACCES);
-
- // Stack bounds are obtained via pthread_getattr_np, which calls
- // this but doesn't actually need it:
- case __NR_sched_getaffinity:
- return Error(ENOSYS);
-
- // Read own pid/tid.
- case __NR_getpid:
- case __NR_gettid:
- return Allow();
-
- // Discard capabilities
- case __NR_close:
- return Allow();
-
- // Machine-dependent stuff
-#ifdef __arm__
- case __ARM_NR_breakpoint:
- case __ARM_NR_cacheflush:
- case __ARM_NR_usr26: // FIXME: do we actually need this?
- case __ARM_NR_usr32:
- case __ARM_NR_set_tls:
- return Allow();
-#endif
-
- // Needed when being debugged:
- case __NR_restart_syscall:
- return Allow();
-
- // Terminate threads or the process
- case __NR_exit:
- case __NR_exit_group:
- return Allow();
-
-#ifdef MOZ_ASAN
- // ASAN's error reporter wants to know if stderr is a tty.
- case __NR_ioctl: {
- Arg<int> fd(0);
- return If(fd == STDERR_FILENO, Allow())
- .Else(InvalidSyscall());
- }
-
- // ...and before compiler-rt r209773, it will call readlink on
- // /proc/self/exe and use the cached value only if that fails:
- case __NR_readlink:
- case __NR_readlinkat:
- return Error(ENOENT);
-
- // ...and if it found an external symbolizer, it will try to run it:
- // (See also bug 1081242 comment #7.)
- CASES_FOR_stat:
- return Error(ENOENT);
-#endif
-
- default:
- return SandboxPolicyBase::EvaluateSyscall(sysno);
- }
- }
-};
-
-// The process-type-specific syscall rules start here:
-
-#ifdef MOZ_CONTENT_SANDBOX
-// The seccomp-bpf filter for content processes is not a true sandbox
-// on its own; its purpose is attack surface reduction and syscall
-// interception in support of a semantic sandboxing layer. On B2G
-// this is the Android process permission model; on desktop,
-// namespaces and chroot() will be used.
-class ContentSandboxPolicy : public SandboxPolicyCommon {
- SandboxBrokerClient* mBroker;
-
- // Trap handlers for filesystem brokering.
- // (The amount of code duplication here could be improved....)
-#ifdef __NR_open
- static intptr_t OpenTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto flags = static_cast<int>(aArgs.args[1]);
- return broker->Open(path, flags);
- }
-#endif
-
- static intptr_t OpenAtTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto fd = static_cast<int>(aArgs.args[0]);
- auto path = reinterpret_cast<const char*>(aArgs.args[1]);
- auto flags = static_cast<int>(aArgs.args[2]);
- if (fd != AT_FDCWD && path[0] != '/') {
- SANDBOX_LOG_ERROR("unsupported fd-relative openat(%d, \"%s\", 0%o)",
- fd, path, flags);
- return BlockedSyscallTrap(aArgs, nullptr);
- }
- return broker->Open(path, flags);
- }
-
-#ifdef __NR_access
- static intptr_t AccessTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto mode = static_cast<int>(aArgs.args[1]);
- return broker->Access(path, mode);
- }
-#endif
-
- static intptr_t AccessAtTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto fd = static_cast<int>(aArgs.args[0]);
- auto path = reinterpret_cast<const char*>(aArgs.args[1]);
- auto mode = static_cast<int>(aArgs.args[2]);
- // Linux's faccessat syscall has no "flags" argument. Attempting
- // to handle the flags != 0 case is left to userspace; this is
- // impossible to do correctly in all cases, but that's not our
- // problem.
- if (fd != AT_FDCWD && path[0] != '/') {
- SANDBOX_LOG_ERROR("unsupported fd-relative faccessat(%d, \"%s\", %d)",
- fd, path, mode);
- return BlockedSyscallTrap(aArgs, nullptr);
- }
- return broker->Access(path, mode);
- }
-
- static intptr_t StatTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto buf = reinterpret_cast<statstruct*>(aArgs.args[1]);
- return broker->Stat(path, buf);
- }
-
- static intptr_t LStatTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto buf = reinterpret_cast<statstruct*>(aArgs.args[1]);
- return broker->LStat(path, buf);
- }
-
- static intptr_t StatAtTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto fd = static_cast<int>(aArgs.args[0]);
- auto path = reinterpret_cast<const char*>(aArgs.args[1]);
- auto buf = reinterpret_cast<statstruct*>(aArgs.args[2]);
- auto flags = static_cast<int>(aArgs.args[3]);
- if (fd != AT_FDCWD && path[0] != '/') {
- SANDBOX_LOG_ERROR("unsupported fd-relative fstatat(%d, \"%s\", %p, %d)",
- fd, path, buf, flags);
- return BlockedSyscallTrap(aArgs, nullptr);
- }
- if ((flags & ~AT_SYMLINK_NOFOLLOW) != 0) {
- SANDBOX_LOG_ERROR("unsupported flags %d in fstatat(%d, \"%s\", %p, %d)",
- (flags & ~AT_SYMLINK_NOFOLLOW), fd, path, buf, flags);
- return BlockedSyscallTrap(aArgs, nullptr);
- }
- return (flags & AT_SYMLINK_NOFOLLOW) == 0
- ? broker->Stat(path, buf)
- : broker->LStat(path, buf);
- }
-
- static intptr_t ChmodTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto mode = static_cast<mode_t>(aArgs.args[1]);
- return broker->Chmod(path, mode);
- }
-
- static intptr_t LinkTrap(ArgsRef aArgs, void *aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto path2 = reinterpret_cast<const char*>(aArgs.args[1]);
- return broker->Link(path, path2);
- }
-
- static intptr_t SymlinkTrap(ArgsRef aArgs, void *aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto path2 = reinterpret_cast<const char*>(aArgs.args[1]);
- return broker->Symlink(path, path2);
- }
-
- static intptr_t RenameTrap(ArgsRef aArgs, void *aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto path2 = reinterpret_cast<const char*>(aArgs.args[1]);
- return broker->Rename(path, path2);
- }
-
- static intptr_t MkdirTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto mode = static_cast<mode_t>(aArgs.args[1]);
- return broker->Mkdir(path, mode);
- }
-
- static intptr_t RmdirTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- return broker->Rmdir(path);
- }
-
- static intptr_t UnlinkTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- return broker->Unlink(path);
- }
-
- static intptr_t ReadlinkTrap(ArgsRef aArgs, void* aux) {
- auto broker = static_cast<SandboxBrokerClient*>(aux);
- auto path = reinterpret_cast<const char*>(aArgs.args[0]);
- auto buf = reinterpret_cast<char*>(aArgs.args[1]);
- auto size = static_cast<size_t>(aArgs.args[2]);
- return broker->Readlink(path, buf, size);
- }
-
- static intptr_t GetPPidTrap(ArgsRef aArgs, void* aux) {
- // In a pid namespace, getppid() will return 0. We will return 0 instead
- // of the real parent pid to see what breaks when we introduce the
- // pid namespace (Bug 1151624).
- return 0;
- }
-
-public:
- explicit ContentSandboxPolicy(SandboxBrokerClient* aBroker):mBroker(aBroker) { }
- virtual ~ContentSandboxPolicy() { }
- virtual ResultExpr PrctlPolicy() const override {
- // Ideally this should be restricted to a whitelist, but content
- // uses enough things that it's not trivial to determine it.
- return Allow();
- }
- virtual Maybe<ResultExpr> EvaluateSocketCall(int aCall) const override {
- switch(aCall) {
- case SYS_RECVFROM:
- case SYS_SENDTO:
- return Some(Allow());
-
- case SYS_SOCKETPAIR: {
- // See bug 1066750.
- if (!kSocketCallHasArgs) {
- // We can't filter the args if the platform passes them by pointer.
- return Some(Allow());
- }
- Arg<int> domain(0), type(1);
- return Some(If(AllOf(domain == AF_UNIX,
- AnyOf(type == SOCK_STREAM, type == SOCK_SEQPACKET)),
- Allow())
- .Else(InvalidSyscall()));
- }
-
-#ifdef ANDROID
- case SYS_SOCKET:
- return Some(Error(EACCES));
-#else // #ifdef DESKTOP
- case SYS_RECV:
- case SYS_SEND:
- case SYS_SOCKET: // DANGEROUS
- case SYS_CONNECT: // DANGEROUS
- case SYS_ACCEPT:
- case SYS_ACCEPT4:
- case SYS_BIND:
- case SYS_LISTEN:
- case SYS_GETSOCKOPT:
- case SYS_SETSOCKOPT:
- case SYS_GETSOCKNAME:
- case SYS_GETPEERNAME:
- case SYS_SHUTDOWN:
- return Some(Allow());
-#endif
- default:
- return SandboxPolicyCommon::EvaluateSocketCall(aCall);
- }
- }
-
-#ifdef DESKTOP
- virtual Maybe<ResultExpr> EvaluateIpcCall(int aCall) const override {
- switch(aCall) {
- // These are a problem: SysV shared memory follows the Unix
- // "same uid policy" and can't be restricted/brokered like file
- // access. But the graphics layer might not be using them
- // anymore; this needs to be studied.
- case SHMGET:
- case SHMCTL:
- case SHMAT:
- case SHMDT:
- case SEMGET:
- case SEMCTL:
- case SEMOP:
- case MSGGET:
- return Some(Allow());
- default:
- return SandboxPolicyCommon::EvaluateIpcCall(aCall);
- }
- }
-#endif
-
- virtual ResultExpr EvaluateSyscall(int sysno) const override {
- if (mBroker) {
- // Have broker; route the appropriate syscalls to it.
- switch (sysno) {
- case __NR_open:
- return Trap(OpenTrap, mBroker);
- case __NR_openat:
- return Trap(OpenAtTrap, mBroker);
- case __NR_access:
- return Trap(AccessTrap, mBroker);
- case __NR_faccessat:
- return Trap(AccessAtTrap, mBroker);
- CASES_FOR_stat:
- return Trap(StatTrap, mBroker);
- CASES_FOR_lstat:
- return Trap(LStatTrap, mBroker);
- CASES_FOR_fstatat:
- return Trap(StatAtTrap, mBroker);
- case __NR_chmod:
- return Trap(ChmodTrap, mBroker);
- case __NR_link:
- return Trap(LinkTrap, mBroker);
- case __NR_mkdir:
- return Trap(MkdirTrap, mBroker);
- case __NR_symlink:
- return Trap(SymlinkTrap, mBroker);
- case __NR_rename:
- return Trap(RenameTrap, mBroker);
- case __NR_rmdir:
- return Trap(RmdirTrap, mBroker);
- case __NR_unlink:
- return Trap(UnlinkTrap, mBroker);
- case __NR_readlink:
- return Trap(ReadlinkTrap, mBroker);
- }
- } else {
- // No broker; allow the syscalls directly. )-:
- switch(sysno) {
- case __NR_open:
- case __NR_openat:
- case __NR_access:
- case __NR_faccessat:
- CASES_FOR_stat:
- CASES_FOR_lstat:
- CASES_FOR_fstatat:
- case __NR_chmod:
- case __NR_link:
- case __NR_mkdir:
- case __NR_symlink:
- case __NR_rename:
- case __NR_rmdir:
- case __NR_unlink:
- case __NR_readlink:
- return Allow();
- }
- }
-
- switch (sysno) {
-#ifdef DESKTOP
- case __NR_getppid:
- return Trap(GetPPidTrap, nullptr);
-
- // Filesystem syscalls that need more work to determine who's
- // using them, if they need to be, and what we intend to about it.
- case __NR_getcwd:
- CASES_FOR_statfs:
- CASES_FOR_fstatfs:
- case __NR_quotactl:
- CASES_FOR_fchown:
- case __NR_fchmod:
- case __NR_flock:
-#endif
- return Allow();
-
- case __NR_readlinkat:
-#ifdef DESKTOP
- // Bug 1290896
- return Allow();
-#else
- // Workaround for bug 964455:
- return Error(EINVAL);
-#endif
-
- CASES_FOR_select:
- case __NR_pselect6:
- return Allow();
-
- CASES_FOR_getdents:
- CASES_FOR_ftruncate:
- case __NR_writev:
- case __NR_pread64:
-#ifdef DESKTOP
- case __NR_pwrite64:
- case __NR_readahead:
-#endif
- return Allow();
-
- case __NR_ioctl:
- // ioctl() is for GL. Remove when GL proxy is implemented.
- // Additionally ioctl() might be a place where we want to have
- // argument filtering
- return Allow();
-
- CASES_FOR_fcntl:
- // Some fcntls have significant side effects like sending
- // arbitrary signals, and there's probably nontrivial kernel
- // attack surface; this should be locked down more if possible.
- return Allow();
-
- case __NR_mprotect:
- case __NR_brk:
- case __NR_madvise:
-#if !defined(MOZ_MEMORY)
- // libc's realloc uses mremap (Bug 1286119).
- case __NR_mremap:
-#endif
- return Allow();
-
- case __NR_sigaltstack:
- return Allow();
-
-#ifdef __NR_set_thread_area
- case __NR_set_thread_area:
- return Allow();
-#endif
-
- case __NR_getrusage:
- case __NR_times:
- return Allow();
-
- case __NR_dup:
- return Allow();
-
- CASES_FOR_getuid:
- CASES_FOR_getgid:
- CASES_FOR_geteuid:
- CASES_FOR_getegid:
- return Allow();
-
- case __NR_fsync:
- case __NR_msync:
- return Allow();
-
- case __NR_getpriority:
- case __NR_setpriority:
- case __NR_sched_get_priority_min:
- case __NR_sched_get_priority_max:
- case __NR_sched_getscheduler:
- case __NR_sched_setscheduler:
- case __NR_sched_getparam:
- case __NR_sched_setparam:
-#ifdef DESKTOP
- case __NR_sched_getaffinity:
-#endif
- return Allow();
-
-#ifdef DESKTOP
- case __NR_pipe2:
- return Allow();
-
- CASES_FOR_getrlimit:
- case __NR_clock_getres:
- CASES_FOR_getresuid:
- CASES_FOR_getresgid:
- return Allow();
-
- case __NR_umask:
- case __NR_kill:
- case __NR_wait4:
-#ifdef __NR_waitpid
- case __NR_waitpid:
-#endif
-#ifdef __NR_arch_prctl
- case __NR_arch_prctl:
-#endif
- return Allow();
-
- case __NR_eventfd2:
- case __NR_inotify_init1:
- case __NR_inotify_add_watch:
- case __NR_inotify_rm_watch:
- return Allow();
-
-#ifdef __NR_memfd_create
- case __NR_memfd_create:
- return Allow();
-#endif
-
-#ifdef __NR_rt_tgsigqueueinfo
- // Only allow to send signals within the process.
- case __NR_rt_tgsigqueueinfo: {
- Arg<pid_t> tgid(0);
- return If(tgid == getpid(), Allow())
- .Else(InvalidSyscall());
- }
-#endif
-
- case __NR_mlock:
- case __NR_munlock:
- return Allow();
-
- // We can't usefully allow fork+exec, even on a temporary basis;
- // the child would inherit the seccomp-bpf policy and almost
- // certainly die from an unexpected SIGSYS. We also can't have
- // fork() crash, currently, because there are too many system
- // libraries/plugins that try to run commands. But they can
- // usually do something reasonable on error.
- case __NR_clone:
- return ClonePolicy(Error(EPERM));
-
-#ifdef __NR_fadvise64
- case __NR_fadvise64:
- return Allow();
-#endif
-
-#ifdef __NR_fadvise64_64
- case __NR_fadvise64_64:
- return Allow();
-#endif
-
- case __NR_fallocate:
- return Allow();
-
- case __NR_get_mempolicy:
- return Allow();
-
-#endif // DESKTOP
-
-#ifdef __NR_getrandom
- case __NR_getrandom:
- return Allow();
-#endif
-
- // nsSystemInfo uses uname (and we cache an instance, so
- // the info remains present even if we block the syscall)
- case __NR_uname:
-#ifdef DESKTOP
- case __NR_sysinfo:
-#endif
- return Allow();
-
-#ifdef MOZ_JPROF
- case __NR_setitimer:
- return Allow();
-#endif // MOZ_JPROF
-
- default:
- return SandboxPolicyCommon::EvaluateSyscall(sysno);
- }
- }
-};
-
-UniquePtr<sandbox::bpf_dsl::Policy>
-GetContentSandboxPolicy(SandboxBrokerClient* aMaybeBroker)
-{
- return UniquePtr<sandbox::bpf_dsl::Policy>(new ContentSandboxPolicy(aMaybeBroker));
-}
-#endif // MOZ_CONTENT_SANDBOX
-
-
-#ifdef MOZ_GMP_SANDBOX
-// Unlike for content, the GeckoMediaPlugin seccomp-bpf policy needs
-// to be an effective sandbox by itself, because we allow GMP on Linux
-// systems where that's the only sandboxing mechanism we can use.
-//
-// Be especially careful about what this policy allows.
-class GMPSandboxPolicy : public SandboxPolicyCommon {
- static intptr_t OpenTrap(const sandbox::arch_seccomp_data& aArgs,
- void* aux)
- {
- auto plugin = static_cast<SandboxOpenedFile*>(aux);
- const char* path;
- int flags;
-
- switch (aArgs.nr) {
-#ifdef __NR_open
- case __NR_open:
- path = reinterpret_cast<const char*>(aArgs.args[0]);
- flags = static_cast<int>(aArgs.args[1]);
- break;
-#endif
- case __NR_openat:
- // The path has to be absolute to match the pre-opened file (see
- // assertion in ctor) so the dirfd argument is ignored.
- path = reinterpret_cast<const char*>(aArgs.args[1]);
- flags = static_cast<int>(aArgs.args[2]);
- break;
- default:
- MOZ_CRASH("unexpected syscall number");
- }
-
- if (strcmp(path, plugin->mPath) != 0) {
- SANDBOX_LOG_ERROR("attempt to open file %s (flags=0%o) which is not the"
- " media plugin %s", path, flags, plugin->mPath);
- return -EPERM;
- }
- if ((flags & O_ACCMODE) != O_RDONLY) {
- SANDBOX_LOG_ERROR("non-read-only open of file %s attempted (flags=0%o)",
- path, flags);
- return -EPERM;
- }
- int fd = plugin->mFd.exchange(-1);
- if (fd < 0) {
- SANDBOX_LOG_ERROR("multiple opens of media plugin file unimplemented");
- return -ENOSYS;
- }
- return fd;
- }
-
- static intptr_t SchedTrap(const sandbox::arch_seccomp_data& aArgs,
- void* aux)
- {
- const pid_t tid = syscall(__NR_gettid);
- if (aArgs.args[0] == static_cast<uint64_t>(tid)) {
- return syscall(aArgs.nr,
- 0,
- aArgs.args[1],
- aArgs.args[2],
- aArgs.args[3],
- aArgs.args[4],
- aArgs.args[5]);
- }
- SANDBOX_LOG_ERROR("unsupported tid in SchedTrap");
- return BlockedSyscallTrap(aArgs, nullptr);
- }
-
- SandboxOpenedFile* mPlugin;
-public:
- explicit GMPSandboxPolicy(SandboxOpenedFile* aPlugin)
- : mPlugin(aPlugin)
- {
- MOZ_ASSERT(aPlugin->mPath[0] == '/', "plugin path should be absolute");
- }
-
- virtual ~GMPSandboxPolicy() { }
-
- virtual ResultExpr EvaluateSyscall(int sysno) const override {
- switch (sysno) {
- // Simulate opening the plugin file.
-#ifdef __NR_open
- case __NR_open:
-#endif
- case __NR_openat:
- return Trap(OpenTrap, mPlugin);
-
- // ipc::Shmem
- case __NR_mprotect:
- return Allow();
- case __NR_madvise: {
- Arg<int> advice(2);
- return If(advice == MADV_DONTNEED, Allow())
- .ElseIf(advice == MADV_FREE, Allow())
-#ifdef MOZ_ASAN
- .ElseIf(advice == MADV_NOHUGEPAGE, Allow())
- .ElseIf(advice == MADV_DONTDUMP, Allow())
-#endif
- .Else(InvalidSyscall());
- }
- case __NR_brk:
- CASES_FOR_geteuid:
- return Allow();
- case __NR_sched_getparam:
- case __NR_sched_getscheduler:
- case __NR_sched_get_priority_min:
- case __NR_sched_get_priority_max:
- case __NR_sched_setscheduler: {
- Arg<pid_t> pid(0);
- return If(pid == 0, Allow())
- .Else(Trap(SchedTrap, nullptr));
- }
-
- // For clock(3) on older glibcs; bug 1304220.
- case __NR_times:
- return Allow();
-
- default:
- return SandboxPolicyCommon::EvaluateSyscall(sysno);
- }
- }
-};
-
-UniquePtr<sandbox::bpf_dsl::Policy>
-GetMediaSandboxPolicy(SandboxOpenedFile* aPlugin)
-{
- return UniquePtr<sandbox::bpf_dsl::Policy>(new GMPSandboxPolicy(aPlugin));
-}
-
-#endif // MOZ_GMP_SANDBOX
-
-}
diff --git a/security/sandbox/linux/SandboxFilter.h b/security/sandbox/linux/SandboxFilter.h
deleted file mode 100644
index 6b1cb47f4..000000000
--- a/security/sandbox/linux/SandboxFilter.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/* -*- 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_SandboxFilter_h
-#define mozilla_SandboxFilter_h
-
-#include "mozilla/Atomics.h"
-#include "mozilla/UniquePtr.h"
-
-namespace sandbox {
-namespace bpf_dsl {
-class Policy;
-}
-}
-
-namespace mozilla {
-
-#ifdef MOZ_CONTENT_SANDBOX
-class SandboxBrokerClient;
-
-UniquePtr<sandbox::bpf_dsl::Policy> GetContentSandboxPolicy(SandboxBrokerClient* aMaybeBroker);
-#endif
-
-#ifdef MOZ_GMP_SANDBOX
-struct SandboxOpenedFile {
- const char *mPath;
- Atomic<int> mFd;
-};
-
-UniquePtr<sandbox::bpf_dsl::Policy> GetMediaSandboxPolicy(SandboxOpenedFile* aPlugin);
-#endif
-
-} // namespace mozilla
-
-#endif
diff --git a/security/sandbox/linux/SandboxFilterUtil.cpp b/security/sandbox/linux/SandboxFilterUtil.cpp
deleted file mode 100644
index 04fd6709c..000000000
--- a/security/sandbox/linux/SandboxFilterUtil.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/* -*- 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 "SandboxFilterUtil.h"
-
-#ifndef ANDROID
-#include <linux/ipc.h>
-#endif
-#include <linux/net.h>
-
-#include "mozilla/UniquePtr.h"
-#include "sandbox/linux/bpf_dsl/bpf_dsl.h"
-
-// Older kernel headers (mostly Android, but also some older desktop
-// distributions) are missing some or all of these:
-#ifndef SYS_ACCEPT4
-#define SYS_ACCEPT4 18
-#endif
-#ifndef SYS_RECVMMSG
-#define SYS_RECVMMSG 19
-#endif
-#ifndef SYS_SENDMMSG
-#define SYS_SENDMMSG 20
-#endif
-
-using namespace sandbox::bpf_dsl;
-#define CASES SANDBOX_BPF_DSL_CASES
-
-namespace mozilla {
-
-sandbox::bpf_dsl::ResultExpr
-SandboxPolicyBase::EvaluateSyscall(int aSysno) const {
- switch (aSysno) {
-#ifdef __NR_socketcall
- case __NR_socketcall: {
- Arg<int> call(0);
- UniquePtr<Caser<int>> acc(new Caser<int>(Switch(call)));
- for (int i = SYS_SOCKET; i <= SYS_SENDMMSG; ++i) {
- auto thisCase = EvaluateSocketCall(i);
- // Optimize out cases that are equal to the default.
- if (thisCase) {
- acc.reset(new Caser<int>(acc->Case(i, *thisCase)));
- }
- }
- return acc->Default(InvalidSyscall());
- }
-#ifndef ANDROID
- case __NR_ipc: {
- Arg<int> callAndVersion(0);
- auto call = callAndVersion & 0xFFFF;
- UniquePtr<Caser<int>> acc(new Caser<int>(Switch(call)));
- for (int i = SEMOP; i <= DIPC; ++i) {
- auto thisCase = EvaluateIpcCall(i);
- // Optimize out cases that are equal to the default.
- if (thisCase) {
- acc.reset(new Caser<int>(acc->Case(i, *thisCase)));
- }
- }
- return acc->Default(InvalidSyscall());
- }
-#endif // ANDROID
-#endif // __NR_socketcall
-#define DISPATCH_SOCKETCALL(sysnum, socketnum) \
- case sysnum: \
- return EvaluateSocketCall(socketnum).valueOr(InvalidSyscall())
-#ifdef __NR_socket
- DISPATCH_SOCKETCALL(__NR_socket, SYS_SOCKET);
- DISPATCH_SOCKETCALL(__NR_bind, SYS_BIND);
- DISPATCH_SOCKETCALL(__NR_connect, SYS_CONNECT);
- DISPATCH_SOCKETCALL(__NR_listen, SYS_LISTEN);
-#ifdef __NR_accept
- DISPATCH_SOCKETCALL(__NR_accept, SYS_ACCEPT);
-#endif
- DISPATCH_SOCKETCALL(__NR_getsockname, SYS_GETSOCKNAME);
- DISPATCH_SOCKETCALL(__NR_getpeername, SYS_GETPEERNAME);
- DISPATCH_SOCKETCALL(__NR_socketpair, SYS_SOCKETPAIR);
-#ifdef __NR_send
- DISPATCH_SOCKETCALL(__NR_send, SYS_SEND);
- DISPATCH_SOCKETCALL(__NR_recv, SYS_RECV);
-#endif // __NR_send
- DISPATCH_SOCKETCALL(__NR_sendto, SYS_SENDTO);
- DISPATCH_SOCKETCALL(__NR_recvfrom, SYS_RECVFROM);
- DISPATCH_SOCKETCALL(__NR_shutdown, SYS_SHUTDOWN);
- DISPATCH_SOCKETCALL(__NR_setsockopt, SYS_SETSOCKOPT);
- DISPATCH_SOCKETCALL(__NR_getsockopt, SYS_GETSOCKOPT);
- DISPATCH_SOCKETCALL(__NR_sendmsg, SYS_SENDMSG);
- DISPATCH_SOCKETCALL(__NR_recvmsg, SYS_RECVMSG);
- DISPATCH_SOCKETCALL(__NR_accept4, SYS_ACCEPT4);
- DISPATCH_SOCKETCALL(__NR_recvmmsg, SYS_RECVMMSG);
- DISPATCH_SOCKETCALL(__NR_sendmmsg, SYS_SENDMMSG);
-#endif // __NR_socket
-#undef DISPATCH_SOCKETCALL
-#ifndef __NR_socketcall
-#ifndef ANDROID
-#define DISPATCH_SYSVCALL(sysnum, ipcnum) \
- case sysnum: \
- return EvaluateIpcCall(ipcnum).valueOr(InvalidSyscall())
- DISPATCH_SYSVCALL(__NR_semop, SEMOP);
- DISPATCH_SYSVCALL(__NR_semget, SEMGET);
- DISPATCH_SYSVCALL(__NR_semctl, SEMCTL);
- DISPATCH_SYSVCALL(__NR_semtimedop, SEMTIMEDOP);
- DISPATCH_SYSVCALL(__NR_msgsnd, MSGSND);
- DISPATCH_SYSVCALL(__NR_msgrcv, MSGRCV);
- DISPATCH_SYSVCALL(__NR_msgget, MSGGET);
- DISPATCH_SYSVCALL(__NR_msgctl, MSGCTL);
- DISPATCH_SYSVCALL(__NR_shmat, SHMAT);
- DISPATCH_SYSVCALL(__NR_shmdt, SHMDT);
- DISPATCH_SYSVCALL(__NR_shmget, SHMGET);
- DISPATCH_SYSVCALL(__NR_shmctl, SHMCTL);
-#undef DISPATCH_SYSVCALL
-#endif // ANDROID
-#endif // __NR_socketcall
- default:
- return InvalidSyscall();
- }
-}
-
-}
diff --git a/security/sandbox/linux/SandboxFilterUtil.h b/security/sandbox/linux/SandboxFilterUtil.h
deleted file mode 100644
index fb9afa79f..000000000
--- a/security/sandbox/linux/SandboxFilterUtil.h
+++ /dev/null
@@ -1,148 +0,0 @@
-/* -*- 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_SandboxFilterUtil_h
-#define mozilla_SandboxFilterUtil_h
-
-// This header file exists to hold helper code for SandboxFilter.cpp,
-// to make that file easier to read for anyone trying to understand
-// the filter policy. It's mostly about smoothing out differences
-// between different Linux architectures.
-
-#include "mozilla/Maybe.h"
-#include "sandbox/linux/bpf_dsl/policy.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-namespace mozilla {
-
-// This class handles syscalls for BSD socket and SysV IPC operations.
-// On 32-bit x86 they're multiplexed via socketcall(2) and ipc(2),
-// respectively; on most other architectures they're individual system
-// calls. It translates the syscalls into socketcall/ipc selector
-// values, because those are defined (even if not used) for all
-// architectures.
-//
-// This EvaluateSyscall() routine always returns InvalidSyscall() for
-// everything else. It's assumed that subclasses will be implementing
-// a whitelist policy, so they can handle what they're whitelisting
-// and then defer to this class in the default case.
-class SandboxPolicyBase : public sandbox::bpf_dsl::Policy
-{
-public:
- using ResultExpr = sandbox::bpf_dsl::ResultExpr;
-
- virtual ResultExpr EvaluateSyscall(int aSysno) const override;
- virtual Maybe<ResultExpr> EvaluateSocketCall(int aCall) const {
- return Nothing();
- }
-#ifndef ANDROID
- // Android doesn't use SysV IPC (and doesn't define the selector
- // constants in its headers), so this isn't implemented there.
- virtual Maybe<ResultExpr> EvaluateIpcCall(int aCall) const {
- return Nothing();
- }
-#endif
-
-#ifdef __NR_socketcall
- // socketcall(2) takes the actual call's arguments via a pointer, so
- // seccomp-bpf can't inspect them; ipc(2) takes them at different indices.
- static const bool kSocketCallHasArgs = false;
- static const bool kIpcCallNormalArgs = false;
-#else
- // Otherwise, the bpf_dsl Arg<> class can be used normally.
- static const bool kSocketCallHasArgs = true;
- static const bool kIpcCallNormalArgs = true;
-#endif
-};
-
-} // namespace mozilla
-
-// "Machine independent" pseudo-syscall numbers, to deal with arch
-// dependencies. (Most 32-bit archs started with 32-bit off_t; older
-// archs started with 16-bit uid_t/gid_t; 32-bit registers can't hold
-// a 64-bit offset for mmap; and so on.)
-//
-// For some of these, the "old" syscalls are also in use in some
-// cases; see, e.g., the handling of RT vs. non-RT signal syscalls.
-
-#ifdef __NR_mmap2
-#define CASES_FOR_mmap case __NR_mmap2
-#else
-#define CASES_FOR_mmap case __NR_mmap
-#endif
-
-#ifdef __NR_fchown32
-#define CASES_FOR_fchown case __NR_fchown32: case __NR_fchown
-#else
-#define CASES_FOR_fchown case __NR_fchown
-#endif
-
-#ifdef __NR_getuid32
-#define CASES_FOR_getuid case __NR_getuid32
-#define CASES_FOR_getgid case __NR_getgid32
-#define CASES_FOR_geteuid case __NR_geteuid32
-#define CASES_FOR_getegid case __NR_getegid32
-#define CASES_FOR_getresuid case __NR_getresuid32: case __NR_getresuid
-#define CASES_FOR_getresgid case __NR_getresgid32: case __NR_getresgid
-// The set*id syscalls are omitted; we'll probably never need to allow them.
-#else
-#define CASES_FOR_getuid case __NR_getuid
-#define CASES_FOR_getgid case __NR_getgid
-#define CASES_FOR_geteuid case __NR_geteuid
-#define CASES_FOR_getegid case __NR_getegid
-#define CASES_FOR_getresuid case __NR_getresuid
-#define CASES_FOR_getresgid case __NR_getresgid
-#endif
-
-#ifdef __NR_stat64
-#define CASES_FOR_stat case __NR_stat64
-#define CASES_FOR_lstat case __NR_lstat64
-#define CASES_FOR_fstat case __NR_fstat64
-#define CASES_FOR_fstatat case __NR_fstatat64
-#define CASES_FOR_statfs case __NR_statfs64: case __NR_statfs
-#define CASES_FOR_fstatfs case __NR_fstatfs64: case __NR_fstatfs
-#define CASES_FOR_fcntl case __NR_fcntl64
-// We're using the 32-bit version on 32-bit desktop for some reason.
-#define CASES_FOR_getdents case __NR_getdents64: case __NR_getdents
-// FIXME: we might not need the compat cases for these on non-Android:
-#define CASES_FOR_lseek case __NR_lseek: case __NR__llseek
-#define CASES_FOR_ftruncate case __NR_ftruncate: case __NR_ftruncate64
-#else
-#define CASES_FOR_stat case __NR_stat
-#define CASES_FOR_lstat case __NR_lstat
-#define CASES_FOR_fstatat case __NR_newfstatat
-#define CASES_FOR_fstat case __NR_fstat
-#define CASES_FOR_fstatfs case __NR_fstatfs
-#define CASES_FOR_statfs case __NR_statfs
-#define CASES_FOR_fcntl case __NR_fcntl
-#define CASES_FOR_getdents case __NR_getdents
-#define CASES_FOR_lseek case __NR_lseek
-#define CASES_FOR_ftruncate case __NR_ftruncate
-#endif
-
-#ifdef __NR_sigprocmask
-#define CASES_FOR_sigprocmask case __NR_sigprocmask: case __NR_rt_sigprocmask
-#define CASES_FOR_sigaction case __NR_sigaction: case __NR_rt_sigaction
-#define CASES_FOR_sigreturn case __NR_sigreturn: case __NR_rt_sigreturn
-#else
-#define CASES_FOR_sigprocmask case __NR_rt_sigprocmask
-#define CASES_FOR_sigaction case __NR_rt_sigaction
-#define CASES_FOR_sigreturn case __NR_rt_sigreturn
-#endif
-
-#ifdef __NR__newselect
-#define CASES_FOR_select case __NR__newselect
-#else
-#define CASES_FOR_select case __NR_select
-#endif
-
-#ifdef __NR_ugetrlimit
-#define CASES_FOR_getrlimit case __NR_ugetrlimit
-#else
-#define CASES_FOR_getrlimit case __NR_getrlimit
-#endif
-
-#endif // mozilla_SandboxFilterUtil_h
diff --git a/security/sandbox/linux/SandboxHooks.cpp b/security/sandbox/linux/SandboxHooks.cpp
deleted file mode 100644
index eaaf56982..000000000
--- a/security/sandbox/linux/SandboxHooks.cpp
+++ /dev/null
@@ -1,72 +0,0 @@
-/* -*- 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 <dlfcn.h>
-#include <signal.h>
-#include <errno.h>
-
-#include "mozilla/Types.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-
-// Signal number used to enable seccomp on each thread.
-extern int gSeccompTsyncBroadcastSignum;
-
-// This file defines a hook for sigprocmask() and pthread_sigmask().
-// Bug 1176099: some threads block SIGSYS signal which breaks our seccomp-bpf
-// sandbox. To avoid this, we intercept the call and remove SIGSYS.
-//
-// ENOSYS indicates an error within the hook function itself.
-static int HandleSigset(int (*aRealFunc)(int, const sigset_t*, sigset_t*),
- int aHow, const sigset_t* aSet,
- sigset_t* aOldSet, bool aUseErrno)
-{
- if (!aRealFunc) {
- if (aUseErrno) {
- errno = ENOSYS;
- return -1;
- }
-
- return ENOSYS;
- }
-
- // Avoid unnecessary work
- if (aSet == NULL || aHow == SIG_UNBLOCK) {
- return aRealFunc(aHow, aSet, aOldSet);
- }
-
- sigset_t newSet = *aSet;
- if (sigdelset(&newSet, SIGSYS) != 0 ||
- (gSeccompTsyncBroadcastSignum &&
- sigdelset(&newSet, gSeccompTsyncBroadcastSignum) != 0)) {
- if (aUseErrno) {
- errno = ENOSYS;
- return -1;
- }
-
- return ENOSYS;
- }
-
- return aRealFunc(aHow, &newSet, aOldSet);
-}
-
-extern "C" MOZ_EXPORT int
-sigprocmask(int how, const sigset_t* set, sigset_t* oldset)
-{
- static auto sRealFunc = (int (*)(int, const sigset_t*, sigset_t*))
- dlsym(RTLD_NEXT, "sigprocmask");
-
- return HandleSigset(sRealFunc, how, set, oldset, true);
-}
-
-extern "C" MOZ_EXPORT int
-pthread_sigmask(int how, const sigset_t* set, sigset_t* oldset)
-{
- static auto sRealFunc = (int (*)(int, const sigset_t*, sigset_t*))
- dlsym(RTLD_NEXT, "pthread_sigmask");
-
- return HandleSigset(sRealFunc, how, set, oldset, false);
-}
diff --git a/security/sandbox/linux/SandboxInfo.cpp b/security/sandbox/linux/SandboxInfo.cpp
deleted file mode 100644
index f813fb026..000000000
--- a/security/sandbox/linux/SandboxInfo.cpp
+++ /dev/null
@@ -1,272 +0,0 @@
-/* -*- 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 "SandboxInfo.h"
-#include "SandboxLogging.h"
-#include "LinuxSched.h"
-
-#include <errno.h>
-#include <stdlib.h>
-#include <sys/prctl.h>
-#include <sys/stat.h>
-#include <sys/syscall.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#include "base/posix/eintr_wrapper.h"
-#include "mozilla/Assertions.h"
-#include "mozilla/ArrayUtils.h"
-#include "sandbox/linux/system_headers/linux_seccomp.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-#ifdef MOZ_VALGRIND
-#include <valgrind/valgrind.h>
-#endif
-
-
-// A note about assertions: in general, the worst thing this module
-// should be able to do is disable sandboxing features, so release
-// asserts or MOZ_CRASH should be avoided, even for seeming
-// impossibilities like an unimplemented syscall returning success
-// (which has happened: https://crbug.com/439795 ).
-//
-// MOZ_DIAGNOSTIC_ASSERT (debug builds, plus Nightly/Aurora non-debug)
-// is probably the best choice for conditions that shouldn't be able
-// to fail without the help of bugs in the kernel or system libraries.
-//
-// Regardless of assertion type, whatever condition caused it to fail
-// should generally also disable the corresponding feature on builds
-// that omit the assertion.
-
-namespace mozilla {
-
-// Bug 1229136: this is copied from ../SandboxUtil.cpp to avoid
-// complicated build issues; renamespaced to avoid the possibility of
-// symbol conflict.
-namespace {
-
-static bool
-IsSingleThreaded()
-{
- // This detects the thread count indirectly. /proc/<pid>/task has a
- // subdirectory for each thread in <pid>'s thread group, and the
- // link count on the "task" directory follows Unix expectations: the
- // link from its parent, the "." link from itself, and the ".." link
- // from each subdirectory; thus, 2+N links for N threads.
- struct stat sb;
- if (stat("/proc/self/task", &sb) < 0) {
- MOZ_DIAGNOSTIC_ASSERT(false, "Couldn't access /proc/self/task!");
- return false;
- }
- MOZ_DIAGNOSTIC_ASSERT(sb.st_nlink >= 3);
- return sb.st_nlink == 3;
-}
-
-} // anonymous namespace
-
-static bool
-HasSeccompBPF()
-{
- // Allow simulating the absence of seccomp-bpf support, for testing.
- if (getenv("MOZ_FAKE_NO_SANDBOX")) {
- return false;
- }
-
- // Valgrind and the sandbox don't interact well, probably because Valgrind
- // does various system calls which aren't allowed, even if Firefox itself
- // is playing by the rules.
-# if defined(MOZ_VALGRIND)
- if (RUNNING_ON_VALGRIND) {
- return false;
- }
-# endif
-
- // Determine whether seccomp-bpf is supported by trying to
- // enable it with an invalid pointer for the filter. This will
- // fail with EFAULT if supported and EINVAL if not, without
- // changing the process's state.
-
- int rv = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, nullptr);
- MOZ_DIAGNOSTIC_ASSERT(rv == -1, "prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER,"
- " nullptr) didn't fail");
- MOZ_DIAGNOSTIC_ASSERT(errno == EFAULT || errno == EINVAL);
- return rv == -1 && errno == EFAULT;
-}
-
-static bool
-HasSeccompTSync()
-{
- // Similar to above, but for thread-sync mode. See also Chromium's
- // sandbox::SandboxBPF::SupportsSeccompThreadFilterSynchronization
- if (getenv("MOZ_FAKE_NO_SECCOMP_TSYNC")) {
- return false;
- }
- int rv = syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER,
- SECCOMP_FILTER_FLAG_TSYNC, nullptr);
- MOZ_DIAGNOSTIC_ASSERT(rv == -1, "seccomp(..., SECCOMP_FILTER_FLAG_TSYNC,"
- " nullptr) didn't fail");
- MOZ_DIAGNOSTIC_ASSERT(errno == EFAULT || errno == EINVAL || errno == ENOSYS);
- return rv == -1 && errno == EFAULT;
-}
-
-static bool
-HasUserNamespaceSupport()
-{
- // Note: the /proc/<pid>/ns/* files track setns(2) support, which in
- // some cases (e.g., pid) significantly postdates kernel support for
- // the namespace type, so in general this type of check could be a
- // false negative. However, for user namespaces, any kernel new
- // enough for the feature to be usable for us has setns support
- // (v3.8), so this is okay.
- //
- // The non-user namespaces all default to "y" in init/Kconfig, but
- // check them explicitly in case someone has a weird custom config.
- static const char* const paths[] = {
- "/proc/self/ns/user",
- "/proc/self/ns/pid",
- "/proc/self/ns/net",
- "/proc/self/ns/ipc",
- };
- for (size_t i = 0; i < ArrayLength(paths); ++i) {
- if (access(paths[i], F_OK) == -1) {
- MOZ_ASSERT(errno == ENOENT);
- return false;
- }
- }
- return true;
-}
-
-static bool
-CanCreateUserNamespace()
-{
- // Unfortunately, the only way to verify that this process can
- // create a new user namespace is to actually create one; because
- // this process's namespaces shouldn't be side-effected (yet), it's
- // necessary to clone (and collect) a child process. See also
- // Chromium's sandbox::Credentials::SupportsNewUserNS.
- //
- // This is somewhat more expensive than the other tests, so it's
- // cached in the environment to prevent child processes from having
- // to re-run the test.
- //
- // This is run at static initializer time, while single-threaded, so
- // locking isn't needed to access the environment.
- static const char kCacheEnvName[] = "MOZ_ASSUME_USER_NS";
- const char* cached = getenv(kCacheEnvName);
- if (cached) {
- return cached[0] > '0';
- }
-
- // Valgrind might allow the clone, but doesn't know what to do with
- // unshare. Check for that by unsharing nothing. (Valgrind will
- // probably need sandboxing disabled entirely, but no need to break
- // things worse than strictly necessary.)
- if (syscall(__NR_unshare, 0) != 0) {
-#ifdef MOZ_VALGRIND
- MOZ_ASSERT(errno == ENOSYS);
-#else
- // If something else can cause that call to fail, we's like to know
- // about it; the right way to handle it might not be the same.
- MOZ_ASSERT(false);
-#endif
- return false;
- }
-
- pid_t pid = syscall(__NR_clone, SIGCHLD | CLONE_NEWUSER,
- nullptr, nullptr, nullptr, nullptr);
- if (pid == 0) {
- // In the child. Do as little as possible.
- _exit(0);
- }
- if (pid == -1) {
- // Failure.
- MOZ_ASSERT(errno == EINVAL || // unsupported
- errno == EPERM || // root-only, or we're already chrooted
- errno == EUSERS); // already at user namespace nesting limit
- setenv(kCacheEnvName, "0", 1);
- return false;
- }
- // Otherwise, in the parent and successful.
- bool waitpid_ok = HANDLE_EINTR(waitpid(pid, nullptr, 0)) == pid;
- MOZ_ASSERT(waitpid_ok);
- if (!waitpid_ok) {
- return false;
- }
- setenv(kCacheEnvName, "1", 1);
- return true;
-}
-
-/* static */
-SandboxInfo SandboxInfo::sSingleton = SandboxInfo();
-
-SandboxInfo::SandboxInfo() {
- int flags = 0;
- static_assert(sizeof(flags) >= sizeof(Flags), "enum Flags fits in an int");
-
- if (HasSeccompBPF()) {
- flags |= kHasSeccompBPF;
- if (HasSeccompTSync()) {
- flags |= kHasSeccompTSync;
- }
- }
-
- // Detect the threading-problem signal from the parent process.
- if (getenv("MOZ_SANDBOX_UNEXPECTED_THREADS")) {
- flags |= kUnexpectedThreads;
- } else {
- if (HasUserNamespaceSupport()) {
- flags |= kHasPrivilegedUserNamespaces;
- if (CanCreateUserNamespace()) {
- flags |= kHasUserNamespaces;
- }
- }
- }
-
-#ifdef MOZ_CONTENT_SANDBOX
- if (!getenv("MOZ_DISABLE_CONTENT_SANDBOX")) {
- flags |= kEnabledForContent;
- }
- if (getenv("MOZ_PERMISSIVE_CONTENT_SANDBOX")) {
- flags |= kPermissive;
- }
-#endif
-#ifdef MOZ_GMP_SANDBOX
- if (!getenv("MOZ_DISABLE_GMP_SANDBOX")) {
- flags |= kEnabledForMedia;
- }
-#endif
- if (getenv("MOZ_SANDBOX_VERBOSE")) {
- flags |= kVerbose;
- }
-
- mFlags = static_cast<Flags>(flags);
-}
-
-/* static */ void
-SandboxInfo::ThreadingCheck()
-{
- // Allow MOZ_SANDBOX_UNEXPECTED_THREADS to be set manually for testing.
- if (IsSingleThreaded() &&
- !getenv("MOZ_SANDBOX_UNEXPECTED_THREADS")) {
- return;
- }
- SANDBOX_LOG_ERROR("unexpected multithreading found; this prevents using"
- " namespace sandboxing.%s",
- // getenv isn't thread-safe, but see below.
- getenv("LD_PRELOAD") ? " (If you're LD_PRELOAD'ing"
- " nVidia GL: that's not necessary for Gecko.)" : "");
-
- // Propagate this information for use by child processes. (setenv
- // isn't thread-safe, but other threads are from non-Gecko code so
- // they wouldn't be using NSPR; we have to hope for the best.)
- setenv("MOZ_SANDBOX_UNEXPECTED_THREADS", "1", 0);
- int flags = sSingleton.mFlags;
- flags |= kUnexpectedThreads;
- flags &= ~(kHasUserNamespaces | kHasPrivilegedUserNamespaces);
- sSingleton.mFlags = static_cast<Flags>(flags);
-}
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/SandboxInfo.h b/security/sandbox/linux/SandboxInfo.h
deleted file mode 100644
index 1999ac392..000000000
--- a/security/sandbox/linux/SandboxInfo.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/* -*- 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_SandboxInfo_h
-#define mozilla_SandboxInfo_h
-
-#include "mozilla/Types.h"
-
-// Information on what parts of sandboxing are enabled in this build
-// and/or supported by the system.
-
-namespace mozilla {
-
-class SandboxInfo {
-public:
- // No need to prevent copying; this is essentially just a const int.
- SandboxInfo(const SandboxInfo& aOther) : mFlags(aOther.mFlags) { }
-
- // Flags are checked at initializer time; this returns them.
- static const SandboxInfo& Get() { return sSingleton; }
-
- enum Flags {
- // System call filtering; kernel config option CONFIG_SECCOMP_FILTER.
- kHasSeccompBPF = 1 << 0,
- // Config flag MOZ_CONTENT_SANDBOX; env var MOZ_DISABLE_CONTENT_SANDBOX.
- kEnabledForContent = 1 << 1,
- // Config flag MOZ_GMP_SANDBOX; env var MOZ_DISABLE_GMP_SANDBOX.
- kEnabledForMedia = 1 << 2,
- // Env var MOZ_SANDBOX_VERBOSE.
- kVerbose = 1 << 3,
- // Kernel can atomically set system call filtering on entire thread group.
- kHasSeccompTSync = 1 << 4,
- // Can this process create user namespaces? (Man page user_namespaces(7).)
- kHasUserNamespaces = 1 << 5,
- // Could a more privileged process have user namespaces, even if we can't?
- kHasPrivilegedUserNamespaces = 1 << 6,
- // Env var MOZ_PERMISSIVE_CONTENT_SANDBOX
- kPermissive = 1 << 7,
- // Something is creating threads when we need to still be single-threaded.
- kUnexpectedThreads = 1 << 8,
- };
-
- bool Test(Flags aFlag) const { return (mFlags & aFlag) == aFlag; }
-
- // Returns true if SetContentProcessSandbox may be called.
- bool CanSandboxContent() const
- {
- return !Test(kEnabledForContent) || Test(kHasSeccompBPF);
- }
-
- // Returns true if SetMediaPluginSandbox may be called.
- bool CanSandboxMedia() const
- {
- return !Test(kEnabledForMedia) || Test(kHasSeccompBPF);
- }
-
- // For telemetry / crash annotation uses.
- uint32_t AsInteger() const {
- return mFlags;
- }
-
- // For bug 1222500 or anything else like it: On desktop, this is
- // called in the parent process at a point when it should still be
- // single-threaded, to check that the SandboxEarlyInit() call in a
- // child process is early enough to be single-threaded. If not,
- // kUnexpectedThreads is set and affected flags (user namespaces;
- // possibly others in the future) are cleared.
- static MOZ_EXPORT void ThreadingCheck();
-private:
- enum Flags mFlags;
- // This should be const, but has to allow for ThreadingCheck.
- static MOZ_EXPORT SandboxInfo sSingleton;
- SandboxInfo();
-};
-
-} // namespace mozilla
-
-#endif // mozilla_SandboxInfo_h
diff --git a/security/sandbox/linux/SandboxInternal.h b/security/sandbox/linux/SandboxInternal.h
deleted file mode 100644
index 90a688421..000000000
--- a/security/sandbox/linux/SandboxInternal.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/* -*- 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_SandboxInternal_h
-#define mozilla_SandboxInternal_h
-
-#include <signal.h>
-
-#include "mozilla/Types.h"
-
-struct sock_fprog;
-
-namespace mozilla {
-
-// SandboxCrash() has to be in libxul to use internal interfaces, but
-// its caller in libmozsandbox.
-// See also bug 1101170.
-
-typedef void (*SandboxCrashFunc)(int, siginfo_t*, void*);
-extern MOZ_EXPORT SandboxCrashFunc gSandboxCrashFunc;
-extern const sock_fprog* gSetSandboxFilter;
-
-} // namespace mozilla
-
-#endif // mozilla_SandboxInternal_h
diff --git a/security/sandbox/linux/SandboxLogging.cpp b/security/sandbox/linux/SandboxLogging.cpp
deleted file mode 100644
index 19196a75a..000000000
--- a/security/sandbox/linux/SandboxLogging.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/* -*- 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 "SandboxLogging.h"
-
-#ifdef ANDROID
-#include <android/log.h>
-#endif
-#include <algorithm>
-#include <stdio.h>
-#include <string.h>
-#include <sys/uio.h>
-#include <unistd.h>
-
-#include "base/posix/eintr_wrapper.h"
-
-namespace mozilla {
-
-// Alters an iovec array to remove the first `toDrop` bytes. This
-// complexity is necessary because writev can return a short write
-// (e.g., if stderr is a pipe and the buffer is almost full).
-static void
-IOVecDrop(struct iovec* iov, int iovcnt, size_t toDrop)
-{
- while (toDrop > 0 && iovcnt > 0) {
- size_t toDropHere = std::min(toDrop, iov->iov_len);
- iov->iov_base = static_cast<char*>(iov->iov_base) + toDropHere;
- iov->iov_len -= toDropHere;
- toDrop -= toDropHere;
- ++iov;
- --iovcnt;
- }
-}
-
-void
-SandboxLogError(const char* message)
-{
-#ifdef ANDROID
- // This uses writev internally and appears to be async signal safe.
- __android_log_write(ANDROID_LOG_ERROR, "Sandbox", message);
-#endif
- static const char logPrefix[] = "Sandbox: ", logSuffix[] = "\n";
- struct iovec iovs[3] = {
- { const_cast<char*>(logPrefix), sizeof(logPrefix) - 1 },
- { const_cast<char*>(message), strlen(message) },
- { const_cast<char*>(logSuffix), sizeof(logSuffix) - 1 },
- };
- while (iovs[2].iov_len > 0) {
- ssize_t written = HANDLE_EINTR(writev(STDERR_FILENO, iovs, 3));
- if (written <= 0) {
- break;
- }
- IOVecDrop(iovs, 3, static_cast<size_t>(written));
- }
-}
-
-}
diff --git a/security/sandbox/linux/SandboxLogging.h b/security/sandbox/linux/SandboxLogging.h
deleted file mode 100644
index 88891adfb..000000000
--- a/security/sandbox/linux/SandboxLogging.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/* -*- 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_SandboxLogging_h
-#define mozilla_SandboxLogging_h
-
-// This header defines the SANDBOX_LOG_ERROR macro used in the Linux
-// sandboxing code. It uses Android logging on Android and writes to
-// stderr otherwise. Android logging has severity levels; currently
-// only "error" severity is exposed here, and this isn't marked when
-// writing to stderr.
-//
-// The format strings are processed by Chromium SafeSPrintf, which
-// doesn't accept size modifiers or %u because it uses C++11 variadic
-// templates to obtain the actual argument types; all decimal integer
-// formatting uses %d. See safe_sprintf.h for more details.
-
-// Build SafeSPrintf without assertions to avoid a dependency on
-// Chromium logging. This doesn't affect safety; it just means that
-// type mismatches (pointer vs. integer) always result in unexpanded
-// %-directives instead of crashing. See also the moz.build files,
-// which apply NDEBUG to the .cc file.
-#ifndef NDEBUG
-#define NDEBUG 1
-#include "base/strings/safe_sprintf.h"
-#undef NDEBUG
-#else
-#include "base/strings/safe_sprintf.h"
-#endif
-
-namespace mozilla {
-// Logs the formatted string (marked with "error" severity, if supported).
-void SandboxLogError(const char* aMessage);
-}
-
-#define SANDBOX_LOG_LEN 256
-
-// Formats a log message and logs it (with "error" severity, if supported).
-//
-// Note that SafeSPrintf doesn't accept size modifiers or %u; all
-// decimal integers are %d, because it uses C++11 variadic templates
-// to use the actual argument type.
-#define SANDBOX_LOG_ERROR(fmt, args...) do { \
- char _sandboxLogBuf[SANDBOX_LOG_LEN]; \
- ::base::strings::SafeSPrintf(_sandboxLogBuf, fmt, ## args); \
- ::mozilla::SandboxLogError(_sandboxLogBuf); \
-} while(0)
-
-#endif // mozilla_SandboxLogging_h
diff --git a/security/sandbox/linux/SandboxUtil.cpp b/security/sandbox/linux/SandboxUtil.cpp
deleted file mode 100644
index 999329882..000000000
--- a/security/sandbox/linux/SandboxUtil.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/* -*- 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 "SandboxUtil.h"
-
-#include "LinuxCapabilities.h"
-#include "LinuxSched.h"
-#include "SandboxLogging.h"
-
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <sys/syscall.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "mozilla/Assertions.h"
-#include "mozilla/Sprintf.h"
-#include "mozilla/Unused.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-namespace mozilla {
-
-bool
-IsSingleThreaded()
-{
- // This detects the thread count indirectly. /proc/<pid>/task has a
- // subdirectory for each thread in <pid>'s thread group, and the
- // link count on the "task" directory follows Unix expectations: the
- // link from its parent, the "." link from itself, and the ".." link
- // from each subdirectory; thus, 2+N links for N threads.
- struct stat sb;
- if (stat("/proc/self/task", &sb) < 0) {
- MOZ_DIAGNOSTIC_ASSERT(false, "Couldn't access /proc/self/task!");
- return false;
- }
- MOZ_DIAGNOSTIC_ASSERT(sb.st_nlink >= 3);
- return sb.st_nlink == 3;
-}
-
-static bool
-WriteStringToFile(const char* aPath, const char* aStr, const size_t aLen)
-{
- int fd = open(aPath, O_WRONLY);
- if (fd < 0) {
- return false;
- }
- ssize_t written = write(fd, aStr, aLen);
- if (close(fd) != 0 || written != ssize_t(aLen)) {
- return false;
- }
- return true;
-}
-
-bool
-UnshareUserNamespace()
-{
- // The uid and gid need to be retrieved before the unshare; see
- // below.
- uid_t uid = getuid();
- gid_t gid = getgid();
- char buf[80];
-
- if (syscall(__NR_unshare, CLONE_NEWUSER) != 0) {
- return false;
- }
-
- // As mentioned in the header, this function sets up uid/gid
- // mappings that preserve the process's previous ids. Mapping the
- // uid/gid to something is necessary in order to nest user
- // namespaces (not used yet, but we'll need this in the future for
- // pid namespace support), and leaving the ids unchanged is the
- // least confusing option.
- //
- // In recent kernels (3.19, 3.18.2, 3.17.8), for security reasons,
- // establishing gid mappings will fail unless the process first
- // revokes its ability to call setgroups() by using a /proc node
- // added in the same set of patches.
- //
- // Note that /proc/self points to the thread group leader, not the
- // current thread. However, CLONE_NEWUSER can be unshared only in a
- // single-threaded process, so those are equivalent if we reach this
- // point.
- int len = SprintfLiteral(buf, "%u %u 1\n", uid, uid);
- if (len >= int(sizeof(buf)) || len < 0) {
- return false;
- }
- if (!WriteStringToFile("/proc/self/uid_map", buf, size_t(len))) {
- MOZ_CRASH("Failed to write /proc/self/uid_map");
- }
-
- Unused << WriteStringToFile("/proc/self/setgroups", "deny", 4);
-
- len = SprintfLiteral(buf, "%u %u 1\n", gid, gid);
- if (len >= int(sizeof(buf)) || len < 0) {
- return false;
- }
- if (!WriteStringToFile("/proc/self/gid_map", buf, size_t(len))) {
- MOZ_CRASH("Failed to write /proc/self/gid_map");
- }
- return true;
-}
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/SandboxUtil.h b/security/sandbox/linux/SandboxUtil.h
deleted file mode 100644
index 7bd84f798..000000000
--- a/security/sandbox/linux/SandboxUtil.h
+++ /dev/null
@@ -1,21 +0,0 @@
-/* -*- 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_SandboxUtil_h
-#define mozilla_SandboxUtil_h
-
-namespace mozilla {
-
-bool IsSingleThreaded();
-
-// Unshare the user namespace, and set up id mappings so that the
-// process's subjective uid and gid are unchanged. This will always
-// fail if the process is multithreaded.
-bool UnshareUserNamespace();
-
-} // namespace mozilla
-
-#endif // mozilla_SandboxUtil_h
diff --git a/security/sandbox/linux/broker/SandboxBroker.cpp b/security/sandbox/linux/broker/SandboxBroker.cpp
deleted file mode 100644
index a31d1fc66..000000000
--- a/security/sandbox/linux/broker/SandboxBroker.cpp
+++ /dev/null
@@ -1,731 +0,0 @@
-/* -*- 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 "SandboxBroker.h"
-#include "SandboxInfo.h"
-#include "SandboxLogging.h"
-#include "SandboxBrokerUtils.h"
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#ifdef XP_LINUX
-#include <sys/prctl.h>
-#endif
-
-#ifdef MOZ_WIDGET_GONK
-#include <private/android_filesystem_config.h>
-#include <sys/syscall.h>
-#endif
-
-#include "mozilla/Assertions.h"
-#include "mozilla/DebugOnly.h"
-#include "mozilla/Move.h"
-#include "mozilla/NullPtr.h"
-#include "mozilla/Sprintf.h"
-#include "mozilla/ipc/FileDescriptor.h"
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-namespace mozilla {
-
-// This constructor signals failure by setting mFileDesc and aClientFd to -1.
-SandboxBroker::SandboxBroker(UniquePtr<const Policy> aPolicy, int aChildPid,
- int& aClientFd)
- : mChildPid(aChildPid), mPolicy(Move(aPolicy))
-{
- int fds[2];
- if (0 != socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds)) {
- SANDBOX_LOG_ERROR("SandboxBroker: socketpair failed: %s", strerror(errno));
- mFileDesc = -1;
- aClientFd = -1;
- return;
- }
- mFileDesc = fds[0];
- aClientFd = fds[1];
-
- if (!PlatformThread::Create(0, this, &mThread)) {
- SANDBOX_LOG_ERROR("SandboxBroker: thread creation failed: %s",
- strerror(errno));
- close(mFileDesc);
- close(aClientFd);
- mFileDesc = -1;
- aClientFd = -1;
- }
-}
-
-UniquePtr<SandboxBroker>
-SandboxBroker::Create(UniquePtr<const Policy> aPolicy, int aChildPid,
- ipc::FileDescriptor& aClientFdOut)
-{
- int clientFd;
- // Can't use MakeUnique here because the constructor is private.
- UniquePtr<SandboxBroker> rv(new SandboxBroker(Move(aPolicy), aChildPid,
- clientFd));
- if (clientFd < 0) {
- rv = nullptr;
- } else {
- aClientFdOut = ipc::FileDescriptor(clientFd);
- }
- return Move(rv);
-}
-
-SandboxBroker::~SandboxBroker() {
- // If the constructor failed, there's nothing to be done here.
- if (mFileDesc < 0) {
- return;
- }
-
- shutdown(mFileDesc, SHUT_RD);
- // The thread will now get EOF even if the client hasn't exited.
- PlatformThread::Join(mThread);
- // Now that the thread has exited, the fd will no longer be accessed.
- close(mFileDesc);
- // Having ensured that this object outlives the thread, this
- // destructor can now return.
-}
-
-SandboxBroker::Policy::Policy() { }
-SandboxBroker::Policy::~Policy() { }
-
-SandboxBroker::Policy::Policy(const Policy& aOther) {
- for (auto iter = aOther.mMap.ConstIter(); !iter.Done(); iter.Next()) {
- mMap.Put(iter.Key(), iter.Data());
- }
-}
-
-// Chromium
-// sandbox/linux/syscall_broker/broker_file_permission.cc
-// Async signal safe
-bool
-SandboxBroker::Policy::ValidatePath(const char* path) const {
- if (!path)
- return false;
-
- const size_t len = strlen(path);
- // No empty paths
- if (len == 0)
- return false;
- // Paths must be absolute and not relative
- if (path[0] != '/')
- return false;
- // No trailing / (but "/" is valid)
- if (len > 1 && path[len - 1] == '/')
- return false;
- // No trailing /.
- if (len >= 2 && path[len - 2] == '/' && path[len - 1] == '.')
- return false;
- // No trailing /..
- if (len >= 3 && path[len - 3] == '/' && path[len - 2] == '.' &&
- path[len - 1] == '.')
- return false;
- // No /../ anywhere
- for (size_t i = 0; i < len; i++) {
- if (path[i] == '/' && (len - i) > 3) {
- if (path[i + 1] == '.' && path[i + 2] == '.' && path[i + 3] == '/') {
- return false;
- }
- }
- }
- return true;
-}
-
-void
-SandboxBroker::Policy::AddPath(int aPerms, const char* aPath,
- AddCondition aCond)
-{
- nsDependentCString path(aPath);
- MOZ_ASSERT(path.Length() <= kMaxPathLen);
- int perms;
- if (aCond == AddIfExistsNow) {
- struct stat statBuf;
- if (lstat(aPath, &statBuf) != 0) {
- return;
- }
- }
- if (!mMap.Get(path, &perms)) {
- perms = MAY_ACCESS;
- } else {
- MOZ_ASSERT(perms & MAY_ACCESS);
- }
- if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
- SANDBOX_LOG_ERROR("policy for %s: %d -> %d", aPath, perms, perms | aPerms);
- }
- perms |= aPerms;
- mMap.Put(path, perms);
-}
-
-void
-SandboxBroker::Policy::AddTree(int aPerms, const char* aPath)
-{
- struct stat statBuf;
-
- if (stat(aPath, &statBuf) != 0) {
- return;
- }
- if (!S_ISDIR(statBuf.st_mode)) {
- AddPath(aPerms, aPath, AddAlways);
- } else {
- DIR* dirp = opendir(aPath);
- if (!dirp) {
- return;
- }
- while (struct dirent* de = readdir(dirp)) {
- if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) {
- continue;
- }
- // Note: could optimize the string handling.
- nsAutoCString subPath;
- subPath.Assign(aPath);
- subPath.Append('/');
- subPath.Append(de->d_name);
- AddTree(aPerms, subPath.get());
- }
- closedir(dirp);
- }
-}
-
-void
-SandboxBroker::Policy::AddDir(int aPerms, const char* aPath)
-{
- struct stat statBuf;
-
- if (stat(aPath, &statBuf) != 0) {
- return;
- }
-
- if (!S_ISDIR(statBuf.st_mode)) {
- return;
- }
-
- nsDependentCString path(aPath);
- MOZ_ASSERT(path.Length() <= kMaxPathLen - 1);
- // Enforce trailing / on aPath
- if (path[path.Length() - 1] != '/') {
- path.Append('/');
- }
- int origPerms;
- if (!mMap.Get(path, &origPerms)) {
- origPerms = MAY_ACCESS;
- } else {
- MOZ_ASSERT(origPerms & MAY_ACCESS);
- }
- int newPerms = origPerms | aPerms | RECURSIVE;
- if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
- SANDBOX_LOG_ERROR("policy for %s: %d -> %d", aPath, origPerms, newPerms);
- }
- mMap.Put(path, newPerms);
-}
-
-void
-SandboxBroker::Policy::AddPrefix(int aPerms, const char* aDir,
- const char* aPrefix)
-{
- size_t prefixLen = strlen(aPrefix);
- DIR* dirp = opendir(aDir);
- struct dirent* de;
- if (!dirp) {
- return;
- }
- while ((de = readdir(dirp))) {
- if (strncmp(de->d_name, aPrefix, prefixLen) == 0) {
- nsAutoCString subPath;
- subPath.Assign(aDir);
- subPath.Append('/');
- subPath.Append(de->d_name);
- AddPath(aPerms, subPath.get(), AddAlways);
- }
- }
- closedir(dirp);
-}
-
-int
-SandboxBroker::Policy::Lookup(const nsACString& aPath) const
-{
- // Early exit for paths explicitly found in the
- // whitelist.
- // This means they will not gain extra permissions
- // from recursive paths.
- int perms = mMap.Get(aPath);
- if (perms) {
- return perms;
- }
-
- // Not a legally constructed path
- if (!ValidatePath(PromiseFlatCString(aPath).get()))
- return 0;
-
- // Now it's either an illegal access, or a recursive
- // directory permission. We'll have to check the entire
- // whitelist for the best match (slower).
- int allPerms = 0;
- for (auto iter = mMap.ConstIter(); !iter.Done(); iter.Next()) {
- const nsACString& whiteListPath = iter.Key();
- const int& perms = iter.Data();
-
- if (!(perms & RECURSIVE))
- continue;
-
- // passed part starts with something on the whitelist
- if (StringBeginsWith(aPath, whiteListPath)) {
- allPerms |= perms;
- }
- }
-
- // Strip away the RECURSIVE flag as it doesn't
- // necessarily apply to aPath.
- return allPerms & ~RECURSIVE;
-}
-
-static bool
-AllowOperation(int aReqFlags, int aPerms)
-{
- int needed = 0;
- if (aReqFlags & R_OK) {
- needed |= SandboxBroker::MAY_READ;
- }
- if (aReqFlags & W_OK) {
- needed |= SandboxBroker::MAY_WRITE;
- }
- // We don't really allow executing anything,
- // so in true unix tradition we hijack this
- // for directories.
- if (aReqFlags & X_OK) {
- needed |= SandboxBroker::MAY_CREATE;
- }
- return (aPerms & needed) == needed;
-}
-
-static bool
-AllowAccess(int aReqFlags, int aPerms)
-{
- if (aReqFlags & ~(R_OK|W_OK|F_OK)) {
- return false;
- }
- int needed = 0;
- if (aReqFlags & R_OK) {
- needed |= SandboxBroker::MAY_READ;
- }
- if (aReqFlags & W_OK) {
- needed |= SandboxBroker::MAY_WRITE;
- }
- return (aPerms & needed) == needed;
-}
-
-// These flags are added to all opens to prevent possible side-effects
-// on this process. These shouldn't be relevant to the child process
-// in any case due to the sandboxing restrictions on it. (See also
-// the use of MSG_CMSG_CLOEXEC in SandboxBrokerCommon.cpp).
-static const int kRequiredOpenFlags = O_CLOEXEC | O_NOCTTY;
-
-// Linux originally assigned a flag bit to O_SYNC but implemented the
-// semantics standardized as O_DSYNC; later, that bit was renamed and
-// a new bit was assigned to the full O_SYNC, and O_SYNC was redefined
-// to be both bits. As a result, this #define is needed to compensate
-// for outdated kernel headers like Android's.
-#define O_SYNC_NEW 04010000
-static const int kAllowedOpenFlags =
- O_APPEND | O_ASYNC | O_DIRECT | O_DIRECTORY | O_EXCL | O_LARGEFILE
- | O_NOATIME | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK | O_NDELAY | O_SYNC_NEW
- | O_TRUNC | O_CLOEXEC | O_CREAT;
-#undef O_SYNC_NEW
-
-static bool
-AllowOpen(int aReqFlags, int aPerms)
-{
- if (aReqFlags & ~O_ACCMODE & ~kAllowedOpenFlags) {
- return false;
- }
- int needed;
- switch(aReqFlags & O_ACCMODE) {
- case O_RDONLY:
- needed = SandboxBroker::MAY_READ;
- break;
- case O_WRONLY:
- needed = SandboxBroker::MAY_WRITE;
- break;
- case O_RDWR:
- needed = SandboxBroker::MAY_READ | SandboxBroker::MAY_WRITE;
- break;
- default:
- return false;
- }
- if (aReqFlags & O_CREAT) {
- needed |= SandboxBroker::MAY_CREATE;
- }
- return (aPerms & needed) == needed;
-}
-
-static int
-DoStat(const char* aPath, void* aBuff, int aFlags)
-{
- if (aFlags & O_NOFOLLOW) {
- return lstatsyscall(aPath, (statstruct*)aBuff);
- }
- return statsyscall(aPath, (statstruct*)aBuff);
-}
-
-static int
-DoLink(const char* aPath, const char* aPath2,
- SandboxBrokerCommon::Operation aOper)
-{
- if (aOper == SandboxBrokerCommon::Operation::SANDBOX_FILE_LINK) {
- return link(aPath, aPath2);
- } else if (aOper == SandboxBrokerCommon::Operation::SANDBOX_FILE_SYMLINK) {
- return symlink(aPath, aPath2);
- }
- MOZ_CRASH("SandboxBroker: Unknown link operation");
-}
-
-size_t
-SandboxBroker::ConvertToRealPath(char* aPath, size_t aBufSize, size_t aPathLen)
-{
- if (strstr(aPath, "..") != NULL) {
- char* result = realpath(aPath, NULL);
- if (result != NULL) {
- strncpy(aPath, result, aBufSize);
- aPath[aBufSize - 1] = '\0';
- free(result);
- // Size changed, but guaranteed to be 0 terminated
- aPathLen = strlen(aPath);
- }
- // ValidatePath will handle failure to translate
- }
- return aPathLen;
-}
-
-void
-SandboxBroker::ThreadMain(void)
-{
- char threadName[16];
- SprintfLiteral(threadName, "FS Broker %d", mChildPid);
- PlatformThread::SetName(threadName);
-
- // Permissive mode can only be enabled through an environment variable,
- // therefore it is sufficient to fetch the value once
- // before the main thread loop starts
- bool permissive = SandboxInfo::Get().Test(SandboxInfo::kPermissive);
-
-#ifdef MOZ_WIDGET_GONK
-#ifdef __NR_setreuid32
- static const long nr_setreuid = __NR_setreuid32;
- static const long nr_setregid = __NR_setregid32;
-#else
- static const long nr_setreuid = __NR_setreuid;
- static const long nr_setregid = __NR_setregid;
-#endif
- if (syscall(nr_setregid, getgid(), AID_APP + mChildPid) != 0 ||
- syscall(nr_setreuid, getuid(), AID_APP + mChildPid) != 0) {
- MOZ_CRASH("SandboxBroker: failed to drop privileges");
- }
-#endif
-
- while (true) {
- struct iovec ios[2];
- // We will receive the path strings in 1 buffer and split them back up.
- char recvBuf[2 * (kMaxPathLen + 1)];
- char pathBuf[kMaxPathLen + 1];
- char pathBuf2[kMaxPathLen + 1];
- size_t pathLen;
- size_t pathLen2;
- char respBuf[kMaxPathLen + 1]; // Also serves as struct stat
- Request req;
- Response resp;
- int respfd;
-
- // Make sure stat responses fit in the response buffer
- MOZ_ASSERT((kMaxPathLen + 1) > sizeof(struct stat));
-
- // This makes our string handling below a bit less error prone.
- memset(recvBuf, 0, sizeof(recvBuf));
-
- ios[0].iov_base = &req;
- ios[0].iov_len = sizeof(req);
- ios[1].iov_base = recvBuf;
- ios[1].iov_len = sizeof(recvBuf);
-
- const ssize_t recvd = RecvWithFd(mFileDesc, ios, 2, &respfd);
- if (recvd == 0) {
- if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
- SANDBOX_LOG_ERROR("EOF from pid %d", mChildPid);
- }
- break;
- }
- // It could be possible to continue after errors and short reads,
- // at least in some cases, but protocol violation indicates a
- // hostile client, so terminate the broker instead.
- if (recvd < 0) {
- SANDBOX_LOG_ERROR("bad read from pid %d: %s",
- mChildPid, strerror(errno));
- shutdown(mFileDesc, SHUT_RD);
- break;
- }
- if (recvd < static_cast<ssize_t>(sizeof(req))) {
- SANDBOX_LOG_ERROR("bad read from pid %d (%d < %d)",
- mChildPid, recvd, sizeof(req));
- shutdown(mFileDesc, SHUT_RD);
- break;
- }
- if (respfd == -1) {
- SANDBOX_LOG_ERROR("no response fd from pid %d", mChildPid);
- shutdown(mFileDesc, SHUT_RD);
- break;
- }
-
- // Initialize the response with the default failure.
- memset(&resp, 0, sizeof(resp));
- memset(&respBuf, 0, sizeof(respBuf));
- resp.mError = -EACCES;
- ios[0].iov_base = &resp;
- ios[0].iov_len = sizeof(resp);
- ios[1].iov_base = nullptr;
- ios[1].iov_len = 0;
- int openedFd = -1;
-
- // Clear permissions
- int perms;
-
- // Find end of first string, make sure the buffer is still
- // 0 terminated.
- size_t recvBufLen = static_cast<size_t>(recvd) - sizeof(req);
- if (recvBufLen > 0 && recvBuf[recvBufLen - 1] != 0) {
- SANDBOX_LOG_ERROR("corrupted path buffer from pid %d", mChildPid);
- shutdown(mFileDesc, SHUT_RD);
- break;
- }
-
- // First path should fit in maximum path length buffer.
- size_t first_len = strlen(recvBuf);
- if (first_len <= kMaxPathLen) {
- strcpy(pathBuf, recvBuf);
- // Skip right over the terminating 0, and try to copy in the
- // second path, if any. If there's no path, this will hit a
- // 0 immediately (we nulled the buffer before receiving).
- // We do not assume the second path is 0-terminated, this is
- // enforced below.
- strncpy(pathBuf2, recvBuf + first_len + 1, kMaxPathLen + 1);
-
- // First string is guaranteed to be 0-terminated.
- pathLen = first_len;
-
- // Look up the first pathname but first translate relative paths.
- pathLen = ConvertToRealPath(pathBuf, sizeof(pathBuf), pathLen);
- perms = mPolicy->Lookup(nsDependentCString(pathBuf, pathLen));
-
- // Same for the second path.
- pathLen2 = strnlen(pathBuf2, kMaxPathLen);
- if (pathLen2 > 0) {
- // Force 0 termination.
- pathBuf2[pathLen2] = '\0';
- pathLen2 = ConvertToRealPath(pathBuf2, sizeof(pathBuf2), pathLen2);
- int perms2 = mPolicy->Lookup(nsDependentCString(pathBuf2, pathLen2));
-
- // Take the intersection of the permissions for both paths.
- perms &= perms2;
- }
- } else {
- // Failed to receive intelligible paths.
- perms = 0;
- }
-
- // And now perform the operation if allowed.
- if (perms & CRASH_INSTEAD) {
- // This is somewhat nonmodular, but it works.
- resp.mError = -ENOSYS;
- } else if (permissive || perms & MAY_ACCESS) {
- // If the operation was only allowed because of permissive mode, log it.
- if (permissive && !(perms & MAY_ACCESS)) {
- AuditPermissive(req.mOp, req.mFlags, perms, pathBuf);
- }
-
- switch(req.mOp) {
- case SANDBOX_FILE_OPEN:
- if (permissive || AllowOpen(req.mFlags, perms)) {
- // Permissions for O_CREAT hardwired to 0600; if that's
- // ever a problem we can change the protocol (but really we
- // should be trying to remove uses of MAY_CREATE, not add
- // new ones).
- openedFd = open(pathBuf, req.mFlags | kRequiredOpenFlags, 0600);
- if (openedFd >= 0) {
- resp.mError = 0;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
-
- case SANDBOX_FILE_ACCESS:
- if (permissive || AllowAccess(req.mFlags, perms)) {
- // This can't use access() itself because that uses the ruid
- // and not the euid. In theory faccessat() with AT_EACCESS
- // would work, but Linux doesn't actually implement the
- // flags != 0 case; glibc has a hack which doesn't even work
- // in this case so it'll ignore the flag, and Bionic just
- // passes through the syscall and always ignores the flags.
- //
- // Instead, because we've already checked the requested
- // r/w/x bits against the policy, just return success if the
- // file exists and hope that's close enough.
- if (stat(pathBuf, (struct stat*)&respBuf) == 0) {
- resp.mError = 0;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
-
- case SANDBOX_FILE_STAT:
- if (DoStat(pathBuf, (struct stat*)&respBuf, req.mFlags) == 0) {
- resp.mError = 0;
- ios[1].iov_base = &respBuf;
- ios[1].iov_len = req.mBufSize;
- } else {
- resp.mError = -errno;
- }
- break;
-
- case SANDBOX_FILE_CHMOD:
- if (permissive || AllowOperation(W_OK, perms)) {
- if (chmod(pathBuf, req.mFlags) == 0) {
- resp.mError = 0;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
-
- case SANDBOX_FILE_LINK:
- case SANDBOX_FILE_SYMLINK:
- if (permissive || AllowOperation(W_OK, perms)) {
- if (DoLink(pathBuf, pathBuf2, req.mOp) == 0) {
- resp.mError = 0;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
-
- case SANDBOX_FILE_RENAME:
- if (permissive || AllowOperation(W_OK, perms)) {
- if (rename(pathBuf, pathBuf2) == 0) {
- resp.mError = 0;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
-
- case SANDBOX_FILE_MKDIR:
- if (permissive || AllowOperation(W_OK | X_OK, perms)) {
- if (mkdir(pathBuf, req.mFlags) == 0) {
- resp.mError = 0;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
-
- case SANDBOX_FILE_UNLINK:
- if (permissive || AllowOperation(W_OK, perms)) {
- if (unlink(pathBuf) == 0) {
- resp.mError = 0;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
-
- case SANDBOX_FILE_RMDIR:
- if (permissive || AllowOperation(W_OK | X_OK, perms)) {
- if (rmdir(pathBuf) == 0) {
- resp.mError = 0;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
-
- case SANDBOX_FILE_READLINK:
- if (permissive || AllowOperation(R_OK, perms)) {
- ssize_t respSize = readlink(pathBuf, (char*)&respBuf, sizeof(respBuf));
- if (respSize >= 0) {
- resp.mError = respSize;
- ios[1].iov_base = &respBuf;
- ios[1].iov_len = respSize;
- } else {
- resp.mError = -errno;
- }
- } else {
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
- break;
- }
- } else {
- MOZ_ASSERT(perms == 0);
- AuditDenial(req.mOp, req.mFlags, perms, pathBuf);
- }
-
- const size_t numIO = ios[1].iov_len > 0 ? 2 : 1;
- DebugOnly<const ssize_t> sent = SendWithFd(respfd, ios, numIO, openedFd);
- close(respfd);
- MOZ_ASSERT(sent < 0 ||
- static_cast<size_t>(sent) == ios[0].iov_len + ios[1].iov_len);
-
- if (openedFd >= 0) {
- close(openedFd);
- }
- }
-}
-
-void
-SandboxBroker::AuditPermissive(int aOp, int aFlags, int aPerms, const char* aPath)
-{
- MOZ_RELEASE_ASSERT(SandboxInfo::Get().Test(SandboxInfo::kPermissive));
-
- struct stat statBuf;
-
- if (lstat(aPath, &statBuf) == 0) {
- // Path exists, set errno to 0 to indicate "success".
- errno = 0;
- }
-
- SANDBOX_LOG_ERROR("SandboxBroker: would have denied op=%d rflags=%o perms=%d path=%s for pid=%d" \
- " permissive=1 error=\"%s\"", aOp, aFlags, aPerms,
- aPath, mChildPid, strerror(errno));
-}
-
-void
-SandboxBroker::AuditDenial(int aOp, int aFlags, int aPerms, const char* aPath)
-{
- if (SandboxInfo::Get().Test(SandboxInfo::kVerbose)) {
- SANDBOX_LOG_ERROR("SandboxBroker: denied op=%d rflags=%o perms=%d path=%s for pid=%d" \
- " error=\"%s\"", aOp, aFlags, aPerms, aPath, mChildPid,
- strerror(errno));
- }
-}
-
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/broker/SandboxBroker.h b/security/sandbox/linux/broker/SandboxBroker.h
deleted file mode 100644
index bb4570a64..000000000
--- a/security/sandbox/linux/broker/SandboxBroker.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/* -*- 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_SandboxBroker_h
-#define mozilla_SandboxBroker_h
-
-#include "mozilla/SandboxBrokerCommon.h"
-
-#include "base/platform_thread.h"
-#include "mozilla/Attributes.h"
-#include "mozilla/UniquePtr.h"
-#include "nsDataHashtable.h"
-#include "nsHashKeys.h"
-#include "nsString.h"
-
-namespace mozilla {
-
-namespace ipc {
-class FileDescriptor;
-}
-
-// This class implements a broker for filesystem operations requested
-// by a sandboxed child process -- opening files and accessing their
-// metadata. (This is necessary in order to restrict access by path;
-// seccomp-bpf can filter only on argument register values, not
-// parameters passed in memory like pathnames.)
-//
-// The broker currently runs on a thread in the parent process (with
-// effective uid changed on B2G), which is for memory efficiency
-// (compared to forking a process) and simplicity (compared to having
-// a separate executable and serializing/deserializing the policy).
-//
-// See also ../SandboxBrokerClient.h for the corresponding client.
-
-class SandboxBroker final
- : private SandboxBrokerCommon
- , public PlatformThread::Delegate
-{
- public:
- enum Perms {
- MAY_ACCESS = 1 << 0,
- MAY_READ = 1 << 1,
- MAY_WRITE = 1 << 2,
- MAY_CREATE = 1 << 3,
- // This flag is for testing policy changes -- when the client is
- // used with the seccomp-bpf integration, an access to this file
- // will invoke a crash dump with the context of the syscall.
- // (This overrides all other flags.)
- CRASH_INSTEAD = 1 << 4,
- // Applies to everything below this path, including subdirs created
- // at runtime
- RECURSIVE = 1 << 5,
- };
- // Bitwise operations on enum values return ints, so just use int in
- // the hash table type (and below) to avoid cluttering code with casts.
- typedef nsDataHashtable<nsCStringHashKey, int> PathMap;
-
- class Policy {
- PathMap mMap;
- public:
- Policy();
- Policy(const Policy& aOther);
- ~Policy();
-
- enum AddCondition {
- AddIfExistsNow,
- AddAlways,
- };
- // Typically, files that don't exist at policy creation time don't
- // need to be whitelisted, but this allows adding entries for
- // them if they'll exist later. See also the overload below.
- void AddPath(int aPerms, const char* aPath, AddCondition aCond);
- // This adds all regular files (not directories) in the tree
- // rooted at the given path.
- void AddTree(int aPerms, const char* aPath);
- // A directory, and all files and directories under it, even those
- // added after creation (the dir itself must exist).
- void AddDir(int aPerms, const char* aPath);
- // All files in a directory with a given prefix; useful for devices.
- void AddPrefix(int aPerms, const char* aDir, const char* aPrefix);
- // Default: add file if it exists when creating policy or if we're
- // conferring permission to create it (log files, etc.).
- void AddPath(int aPerms, const char* aPath) {
- AddPath(aPerms, aPath,
- (aPerms & MAY_CREATE) ? AddAlways : AddIfExistsNow);
- }
- int Lookup(const nsACString& aPath) const;
- int Lookup(const char* aPath) const {
- return Lookup(nsDependentCString(aPath));
- }
- private:
- // ValidatePath checks |path| and returns true if these conditions are met
- // * Greater than 0 length
- // * Is an absolute path
- // * No trailing slash
- // * No /../ path traversal
- bool ValidatePath(const char* path) const;
- };
-
- // Constructing a broker involves creating a socketpair and a
- // background thread to handle requests, so it can fail. If this
- // returns nullptr, do not use the value of aClientFdOut.
- static UniquePtr<SandboxBroker>
- Create(UniquePtr<const Policy> aPolicy, int aChildPid,
- ipc::FileDescriptor& aClientFdOut);
- virtual ~SandboxBroker();
-
- private:
- PlatformThreadHandle mThread;
- int mFileDesc;
- const int mChildPid;
- const UniquePtr<const Policy> mPolicy;
-
- SandboxBroker(UniquePtr<const Policy> aPolicy, int aChildPid,
- int& aClientFd);
- void ThreadMain(void) override;
- void AuditPermissive(int aOp, int aFlags, int aPerms, const char* aPath);
- void AuditDenial(int aOp, int aFlags, int aPerms, const char* aPath);
- // Remap relative paths to absolute paths.
- size_t ConvertToRealPath(char* aPath, size_t aBufSize, size_t aPathLen);
-
- // Holding a UniquePtr should disallow copying, but to make that explicit:
- SandboxBroker(const SandboxBroker&) = delete;
- void operator=(const SandboxBroker&) = delete;
-};
-
-} // namespace mozilla
-
-#endif // mozilla_SandboxBroker_h
diff --git a/security/sandbox/linux/broker/SandboxBrokerCommon.cpp b/security/sandbox/linux/broker/SandboxBrokerCommon.cpp
deleted file mode 100644
index fe7bc8c45..000000000
--- a/security/sandbox/linux/broker/SandboxBrokerCommon.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/* -*- 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 "SandboxBrokerCommon.h"
-
-#include "mozilla/Assertions.h"
-
-#include <errno.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#ifndef MSG_CMSG_CLOEXEC
-#ifdef XP_LINUX
-// As always, Android's kernel headers are somewhat old.
-#define MSG_CMSG_CLOEXEC 0x40000000
-#else
-// Most of this code can support other POSIX OSes, but being able to
-// receive fds and atomically make them close-on-exec is important,
-// because this is running in a multithreaded process that can fork.
-// In the future, if the broker becomes a dedicated executable, this
-// can change.
-#error "No MSG_CMSG_CLOEXEC?"
-#endif // XP_LINUX
-#endif // MSG_CMSG_CLOEXEC
-
-namespace mozilla {
-
-/* static */ ssize_t
-SandboxBrokerCommon::RecvWithFd(int aFd, const iovec* aIO, size_t aNumIO,
- int* aPassedFdPtr)
-{
- struct msghdr msg = {};
- msg.msg_iov = const_cast<iovec*>(aIO);
- msg.msg_iovlen = aNumIO;
-
- char cmsg_buf[CMSG_SPACE(sizeof(int))];
- if (aPassedFdPtr) {
- msg.msg_control = cmsg_buf;
- msg.msg_controllen = sizeof(cmsg_buf);
- *aPassedFdPtr = -1;
- }
-
- ssize_t rv;
- do {
- // MSG_CMSG_CLOEXEC is needed to prevent the parent process from
- // accidentally leaking a copy of the child's response socket to a
- // new child process. (The child won't be able to exec, so this
- // doesn't matter as much for that direction.)
- rv = recvmsg(aFd, &msg, MSG_CMSG_CLOEXEC);
- } while (rv < 0 && errno == EINTR);
-
- if (rv <= 0) {
- return rv;
- }
- if (msg.msg_controllen > 0) {
- MOZ_ASSERT(aPassedFdPtr);
- struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
- if (cmsg->cmsg_level == SOL_SOCKET &&
- cmsg->cmsg_type == SCM_RIGHTS) {
- int* fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
- if (cmsg->cmsg_len != CMSG_LEN(sizeof(int))) {
- // A client could, for example, send an extra 32-bit int if
- // CMSG_SPACE pads to 64-bit size_t alignment. If so, treat
- // it as an error, but also don't leak the fds.
- for (size_t i = 0; CMSG_LEN(sizeof(int) * i) < cmsg->cmsg_len; ++i) {
- close(fds[i]);
- }
- errno = EMSGSIZE;
- return -1;
- }
- *aPassedFdPtr = fds[0];
- } else {
- errno = EPROTO;
- return -1;
- }
- }
- if (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC)) {
- if (aPassedFdPtr && *aPassedFdPtr >= 0) {
- close(*aPassedFdPtr);
- *aPassedFdPtr = -1;
- }
- errno = EMSGSIZE;
- return -1;
- }
-
- return rv;
-}
-
-/* static */ ssize_t
-SandboxBrokerCommon::SendWithFd(int aFd, const iovec* aIO, size_t aNumIO,
- int aPassedFd)
-{
- struct msghdr msg = {};
- msg.msg_iov = const_cast<iovec*>(aIO);
- msg.msg_iovlen = aNumIO;
-
- char cmsg_buf[CMSG_SPACE(sizeof(int))];
- if (aPassedFd != -1) {
- msg.msg_control = cmsg_buf;
- msg.msg_controllen = sizeof(cmsg_buf);
- struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
- cmsg->cmsg_level = SOL_SOCKET;
- cmsg->cmsg_type = SCM_RIGHTS;
- cmsg->cmsg_len = CMSG_LEN(sizeof(int));
- *reinterpret_cast<int*>(CMSG_DATA(cmsg)) = aPassedFd;
- }
-
- ssize_t rv;
- do {
- rv = sendmsg(aFd, &msg, MSG_NOSIGNAL);
- } while (rv < 0 && errno == EINTR);
-
- return rv;
-}
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/broker/SandboxBrokerCommon.h b/security/sandbox/linux/broker/SandboxBrokerCommon.h
deleted file mode 100644
index dbd17e0b9..000000000
--- a/security/sandbox/linux/broker/SandboxBrokerCommon.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/* -*- 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_SandboxBrokerCommon_h
-#define mozilla_SandboxBrokerCommon_h
-
-#include <sys/types.h>
-
-struct iovec;
-
-// This file defines the protocol between the filesystem broker,
-// described in SandboxBroker.h, and its client, described in
-// ../SandboxBrokerClient.h; and it defines some utility functions
-// used by both.
-//
-// In order to keep the client simple while allowing it to be thread
-// safe and async signal safe, the main broker socket is used only for
-// requests; responses arrive on a per-request socketpair sent with
-// the request. (This technique is also used by Chromium and Breakpad.)
-
-namespace mozilla {
-
-class SandboxBrokerCommon {
-public:
- enum Operation {
- SANDBOX_FILE_OPEN,
- SANDBOX_FILE_ACCESS,
- SANDBOX_FILE_STAT,
- SANDBOX_FILE_CHMOD,
- SANDBOX_FILE_LINK,
- SANDBOX_FILE_SYMLINK,
- SANDBOX_FILE_MKDIR,
- SANDBOX_FILE_RENAME,
- SANDBOX_FILE_RMDIR,
- SANDBOX_FILE_UNLINK,
- SANDBOX_FILE_READLINK,
- };
-
- struct Request {
- Operation mOp;
- // For open, flags; for access, "mode"; for stat, O_NOFOLLOW for lstat.
- int mFlags;
- // Size of return value buffer, if any
- size_t mBufSize;
- // The rest of the packet is the pathname.
- // SCM_RIGHTS for response socket attached.
- };
-
- struct Response {
- // Syscall result, -errno if failure, or 0 for no error
- int mError;
- // Followed by struct stat for stat/lstat.
- // SCM_RIGHTS attached for successful open.
- };
-
- // This doesn't need to be the system's maximum path length, just
- // the largest path that would be allowed by any policy. (It's used
- // to size a stack-allocated buffer.)
- static const size_t kMaxPathLen = 4096;
-
- static ssize_t RecvWithFd(int aFd, const iovec* aIO, size_t aNumIO,
- int* aPassedFdPtr);
- static ssize_t SendWithFd(int aFd, const iovec* aIO, size_t aNumIO,
- int aPassedFd);
-};
-
-} // namespace mozilla
-
-#endif // mozilla_SandboxBrokerCommon_h
diff --git a/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp b/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp
deleted file mode 100644
index 8e698606e..000000000
--- a/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp
+++ /dev/null
@@ -1,194 +0,0 @@
-/* -*- 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 "SandboxBrokerPolicyFactory.h"
-#include "SandboxInfo.h"
-
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/Preferences.h"
-#include "nsPrintfCString.h"
-#include "nsString.h"
-#include "nsThreadUtils.h"
-#include "nsXULAppAPI.h"
-#include "SpecialSystemDirectory.h"
-
-#ifdef ANDROID
-#include "cutils/properties.h"
-#endif
-
-namespace mozilla {
-
-/* static */ bool
-SandboxBrokerPolicyFactory::IsSystemSupported() {
-#ifdef ANDROID
- char hardware[PROPERTY_VALUE_MAX];
- int length = property_get("ro.hardware", hardware, nullptr);
- // "goldfish" -> emulator. Other devices can be added when we're
- // reasonably sure they work. Eventually this won't be needed....
- if (length > 0 && strcmp(hardware, "goldfish") == 0) {
- return true;
- }
-
- // When broker is running in permissive mode, we enable it
- // automatically regardless of the device.
- if (SandboxInfo::Get().Test(SandboxInfo::kPermissive)) {
- return true;
- }
-#endif
- return false;
-}
-
-#if defined(MOZ_CONTENT_SANDBOX)
-namespace {
-static const int rdonly = SandboxBroker::MAY_READ;
-static const int wronly = SandboxBroker::MAY_WRITE;
-static const int rdwr = rdonly | wronly;
-static const int rdwrcr = rdwr | SandboxBroker::MAY_CREATE;
-#if defined(MOZ_WIDGET_GONK)
-static const int wrlog = wronly | SandboxBroker::MAY_CREATE;
-#endif
-}
-#endif
-
-SandboxBrokerPolicyFactory::SandboxBrokerPolicyFactory()
-{
- // Policy entries that are the same in every process go here, and
- // are cached over the lifetime of the factory.
-#if defined(MOZ_CONTENT_SANDBOX) && defined(MOZ_WIDGET_GONK)
- SandboxBroker::Policy* policy = new SandboxBroker::Policy;
-
- // Devices that need write access:
- policy->AddPath(rdwr, "/dev/genlock"); // bug 980924
- policy->AddPath(rdwr, "/dev/ashmem"); // bug 980947
- policy->AddTree(wronly, "/dev/log"); // bug 1199857
- // Graphics devices are a significant source of attack surface, but
- // there's not much we can do about it without proxying (which is
- // very difficult and a perforamnce hit).
- policy->AddPrefix(rdwr, "/dev", "kgsl"); // bug 995072
- policy->AddPath(rdwr, "/dev/qemu_pipe"); // but 1198410: goldfish gralloc.
-
- // Bug 1198475: mochitest logs. (This is actually passed in via URL
- // query param to the mochitest page, and is configurable, so this
- // isn't enough in general, but hopefully it's good enough for B2G.)
- // Conditional on tests being run, using the same check seen in
- // DirectoryProvider.js to set ProfD.
- if (access("/data/local/tests/profile", R_OK) == 0) {
- policy->AddPath(wrlog, "/data/local/tests/log/mochitest.log");
- }
-
- // Read-only items below this line.
-
- policy->AddPath(rdonly, "/dev/urandom"); // bug 964500, bug 995069
- policy->AddPath(rdonly, "/dev/ion"); // bug 980937
- policy->AddPath(rdonly, "/proc/cpuinfo"); // bug 995067
- policy->AddPath(rdonly, "/proc/meminfo"); // bug 1025333
- policy->AddPath(rdonly, "/sys/devices/system/cpu/present"); // bug 1025329
- policy->AddPath(rdonly, "/sys/devices/system/soc/soc0/id"); // bug 1025339
- policy->AddPath(rdonly, "/etc/media_profiles.xml"); // bug 1198419
- policy->AddPath(rdonly, "/etc/media_codecs.xml"); // bug 1198460
- policy->AddTree(rdonly, "/system/fonts"); // bug 1026063
-
- // Bug 1199051 (crossplatformly, this is NS_GRE_DIR).
- policy->AddTree(rdonly, "/system/b2g");
-
- // Bug 1026356: dynamic library loading from assorted frameworks we
- // don't control (media codecs, maybe others).
- //
- // Bug 1198515: Also, the profiler calls breakpad code to get info
- // on all loaded ELF objects, which opens those files.
- policy->AddTree(rdonly, "/system/lib");
- policy->AddTree(rdonly, "/vendor/lib");
- policy->AddPath(rdonly, "/system/bin/linker"); // (profiler only)
-
- // Bug 1199866: EGL/WebGL.
- policy->AddPath(rdonly, "/system/lib/egl");
- policy->AddPath(rdonly, "/vendor/lib/egl");
-
- // Bug 1198401: timezones. Yes, we need both of these; see bug.
- policy->AddTree(rdonly, "/system/usr/share/zoneinfo");
- policy->AddTree(rdonly, "/system//usr/share/zoneinfo");
-
- policy->AddPath(rdonly, "/data/local/tmp/profiler.options",
- SandboxBroker::Policy::AddAlways); // bug 1029337
-
- mCommonContentPolicy.reset(policy);
-#elif defined(MOZ_CONTENT_SANDBOX)
- SandboxBroker::Policy* policy = new SandboxBroker::Policy;
- policy->AddDir(rdonly, "/");
- policy->AddDir(rdwrcr, "/dev/shm");
- // Add write permissions on the temporary directory. This can come
- // from various environment variables (TMPDIR,TMP,TEMP,...) so
- // make sure to use the full logic.
- nsCOMPtr<nsIFile> tmpDir;
- nsresult rv = GetSpecialSystemDirectory(OS_TemporaryDirectory,
- getter_AddRefs(tmpDir));
- if (NS_SUCCEEDED(rv)) {
- nsAutoCString tmpPath;
- rv = tmpDir->GetNativePath(tmpPath);
- if (NS_SUCCEEDED(rv)) {
- policy->AddDir(rdwrcr, tmpPath.get());
- }
- }
- // If the above fails at any point, fall back to a very good guess.
- if (NS_FAILED(rv)) {
- policy->AddDir(rdwrcr, "/tmp");
- }
-
- // Bug 1308851: NVIDIA proprietary driver when using WebGL
- policy->AddPrefix(rdwr, "/dev", "nvidia");
-
- // Bug 1312678: radeonsi/Intel with DRI when using WebGL
- policy->AddDir(rdwr, "/dev/dri");
-
- mCommonContentPolicy.reset(policy);
-#endif
-}
-
-#ifdef MOZ_CONTENT_SANDBOX
-UniquePtr<SandboxBroker::Policy>
-SandboxBrokerPolicyFactory::GetContentPolicy(int aPid)
-{
- // Policy entries that vary per-process (currently the only reason
- // that can happen is because they contain the pid) are added here.
-
- MOZ_ASSERT(NS_IsMainThread());
- // File broker usage is controlled through a pref.
- if (Preferences::GetInt("security.sandbox.content.level") <= 1) {
- return nullptr;
- }
-
- MOZ_ASSERT(mCommonContentPolicy);
-#if defined(MOZ_WIDGET_GONK)
- // Allow overriding "unsupported"ness with a pref, for testing.
- if (!IsSystemSupported()) {
- return nullptr;
- }
- UniquePtr<SandboxBroker::Policy>
- policy(new SandboxBroker::Policy(*mCommonContentPolicy));
-
- // Bug 1029337: where the profiler writes the data.
- nsPrintfCString profilerLogPath("/data/local/tmp/profile_%d_%d.txt",
- GeckoProcessType_Content, aPid);
- policy->AddPath(wrlog, profilerLogPath.get());
-
- // Bug 1198550: the profiler's replacement for dl_iterate_phdr
- policy->AddPath(rdonly, nsPrintfCString("/proc/%d/maps", aPid).get());
-
- // Bug 1198552: memory reporting.
- policy->AddPath(rdonly, nsPrintfCString("/proc/%d/statm", aPid).get());
- policy->AddPath(rdonly, nsPrintfCString("/proc/%d/smaps", aPid).get());
-
- return policy;
-#else
- UniquePtr<SandboxBroker::Policy>
- policy(new SandboxBroker::Policy(*mCommonContentPolicy));
- // Return the common policy.
- return policy;
-#endif
-}
-
-#endif // MOZ_CONTENT_SANDBOX
-} // namespace mozilla
diff --git a/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.h b/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.h
deleted file mode 100644
index c66a09189..000000000
--- a/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/* -*- 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_SandboxBrokerPolicyFactory_h
-#define mozilla_SandboxBrokerPolicyFactory_h
-
-#include "mozilla/SandboxBroker.h"
-
-namespace mozilla {
-
-class SandboxBrokerPolicyFactory {
-public:
- SandboxBrokerPolicyFactory();
-
-#ifdef MOZ_CONTENT_SANDBOX
- UniquePtr<SandboxBroker::Policy> GetContentPolicy(int aPid);
-#endif
-
-private:
- UniquePtr<const SandboxBroker::Policy> mCommonContentPolicy;
- // B2G devices tend to have hardware-specific paths used by device
- // drivers, so rollout of filesystem isolation will need per-device
- // testing. This predicate allows that to happen gradually.
- static bool IsSystemSupported();
-};
-
-} // namespace mozilla
-
-#endif // mozilla_SandboxBrokerPolicyFactory_h
diff --git a/security/sandbox/linux/broker/SandboxBrokerUtils.h b/security/sandbox/linux/broker/SandboxBrokerUtils.h
deleted file mode 100644
index 1db4f4411..000000000
--- a/security/sandbox/linux/broker/SandboxBrokerUtils.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* -*- 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_SandboxBrokerUtils_h
-#define mozilla_SandboxBrokerUtils_h
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include "sandbox/linux/system_headers/linux_syscalls.h"
-
-// On 32-bit Linux, stat calls are translated by libc into stat64
-// calls. We'll intercept those and handle them in the stat functions
-// but must be sure to use the right structure layout.
-
-#if defined(__NR_stat64)
-typedef struct stat64 statstruct;
-#define statsyscall stat64
-#define lstatsyscall lstat64
-#elif defined(__NR_stat)
-typedef struct stat statstruct;
-#define statsyscall stat
-#define lstatsyscall lstat
-#else
-#error Missing stat syscall include.
-#endif
-
-#endif // mozilla_SandboxBrokerUtils_h
diff --git a/security/sandbox/linux/broker/moz.build b/security/sandbox/linux/broker/moz.build
deleted file mode 100644
index 343a5cfad..000000000
--- a/security/sandbox/linux/broker/moz.build
+++ /dev/null
@@ -1,37 +0,0 @@
-# -*- Mode: python; python-indent: 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/.
-
-EXPORTS.mozilla += [
- 'SandboxBroker.h',
- 'SandboxBrokerCommon.h',
- 'SandboxBrokerPolicyFactory.h',
-]
-
-SOURCES += [
- 'SandboxBroker.cpp',
- 'SandboxBrokerCommon.cpp',
- 'SandboxBrokerPolicyFactory.cpp',
-]
-
-if CONFIG['OS_TARGET'] == 'Android':
- if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DEFINES['HAVE_ANDROID_OS'] = True
-
-LOCAL_INCLUDES += [
- '/security/sandbox/linux', # SandboxLogging.h, SandboxInfo.h
-]
-
-# Need this for mozilla::ipc::FileDescriptor etc.
-include('/ipc/chromium/chromium-config.mozbuild')
-
-# Need this for safe_sprintf.h used by SandboxLogging.h,
-# but it has to be after ipc/chromium/src.
-LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
-]
-
-
-FINAL_LIBRARY = 'xul'
diff --git a/security/sandbox/linux/glue/SandboxCrash.cpp b/security/sandbox/linux/glue/SandboxCrash.cpp
deleted file mode 100644
index 8ead16bdf..000000000
--- a/security/sandbox/linux/glue/SandboxCrash.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/* -*- 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/. */
-
-// This file needs to be linked into libxul, so it can access the JS
-// stack and the crash reporter. Everything else in this directory
-// should be able to be linked into its own shared library, in order
-// to be able to isolate sandbox/chromium from ipc/chromium.
-
-#include "SandboxInternal.h"
-#include "SandboxLogging.h"
-
-#include <unistd.h>
-#include <sys/syscall.h>
-
-#include "mozilla/Unused.h"
-#include "mozilla/dom/Exceptions.h"
-#include "nsContentUtils.h"
-#include "mozilla/StackWalk.h"
-#include "nsString.h"
-#include "nsThreadUtils.h"
-
-namespace mozilla {
-
-// Log JS stack info in the same place as the sandbox violation
-// message. Useful in case the responsible code is JS and all we have
-// are logs and a minidump with the C++ stacks (e.g., on TBPL).
-static void
-SandboxLogJSStack(void)
-{
- if (!NS_IsMainThread()) {
- // This might be a worker thread... or it might be a non-JS
- // thread, or a non-NSPR thread. There's isn't a good API for
- // dealing with this, yet.
- return;
- }
- if (!nsContentUtils::XPConnect()) {
- // There is no content (e.g., the process is a media plugin), in
- // which case this will probably crash and definitely not work.
- return;
- }
- nsCOMPtr<nsIStackFrame> frame = dom::GetCurrentJSStack();
- // If we got a stack, we must have a current JSContext. This is icky. :(
- // Would be better if GetCurrentJSStack() handed out the JSContext it ended up
- // using or something.
- JSContext* cx = frame ? nsContentUtils::GetCurrentJSContext() : nullptr;
- for (int i = 0; frame != nullptr; ++i) {
- nsAutoString fileName, funName;
- int32_t lineNumber;
-
- // Don't stop unwinding if an attribute can't be read.
- fileName.SetIsVoid(true);
- Unused << frame->GetFilename(cx, fileName);
- lineNumber = 0;
- Unused << frame->GetLineNumber(cx, &lineNumber);
- funName.SetIsVoid(true);
- Unused << frame->GetName(cx, funName);
-
- if (!funName.IsVoid() || !fileName.IsVoid()) {
- SANDBOX_LOG_ERROR("JS frame %d: %s %s line %d", i,
- funName.IsVoid() ?
- "(anonymous)" : NS_ConvertUTF16toUTF8(funName).get(),
- fileName.IsVoid() ?
- "(no file)" : NS_ConvertUTF16toUTF8(fileName).get(),
- lineNumber);
- }
-
- nsCOMPtr<nsIStackFrame> nextFrame;
- nsresult rv = frame->GetCaller(cx, getter_AddRefs(nextFrame));
- NS_ENSURE_SUCCESS_VOID(rv);
- frame = nextFrame;
- }
-}
-
-static void SandboxPrintStackFrame(uint32_t aFrameNumber, void *aPC, void *aSP,
- void *aClosure)
-{
- char buf[1024];
- MozCodeAddressDetails details;
-
- MozDescribeCodeAddress(aPC, &details);
- MozFormatCodeAddressDetails(buf, sizeof(buf), aFrameNumber, aPC, &details);
- SANDBOX_LOG_ERROR("frame %s", buf);
-}
-
-static void
-SandboxLogCStack()
-{
- // Skip 3 frames: one for this module, one for the signal handler in
- // libmozsandbox, and one for the signal trampoline.
- //
- // Warning: this might not print any stack frames. MozStackWalk
- // can't walk past the signal trampoline on ARM (bug 968531), and
- // x86 frame pointer walking may or may not work (bug 1082276).
-
- MozStackWalk(SandboxPrintStackFrame, /* skip */ 3, /* max */ 0,
- nullptr, 0, nullptr);
- SANDBOX_LOG_ERROR("end of stack.");
-}
-
-static void
-SandboxCrash(int nr, siginfo_t *info, void *void_context)
-{
- pid_t pid = getpid(), tid = syscall(__NR_gettid);
- bool dumped = false;
-
- if (!dumped) {
- SANDBOX_LOG_ERROR("crash reporter is disabled (or failed);"
- " trying stack trace:");
- SandboxLogCStack();
- }
-
- // Do this last, in case it crashes or deadlocks.
- SandboxLogJSStack();
-
- // Try to reraise, so the parent sees that this process crashed.
- // (If tgkill is forbidden, then seccomp will raise SIGSYS, which
- // also accomplishes that goal.)
- signal(SIGSYS, SIG_DFL);
- syscall(__NR_tgkill, pid, tid, nr);
-}
-
-static void __attribute__((constructor))
-SandboxSetCrashFunc()
-{
- gSandboxCrashFunc = SandboxCrash;
-}
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/glue/moz.build b/security/sandbox/linux/glue/moz.build
deleted file mode 100644
index 0d40dcd63..000000000
--- a/security/sandbox/linux/glue/moz.build
+++ /dev/null
@@ -1,29 +0,0 @@
-# -*- Mode: python; python-indent: 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/.
-
-SOURCES += [
- '../../chromium/base/strings/safe_sprintf.cc',
- '../SandboxLogging.cpp',
- 'SandboxCrash.cpp',
-]
-
-# Avoid Chromium logging dependency, because this is going into
-# libxul. See also the comment in SandboxLogging.h.
-SOURCES['../../chromium/base/strings/safe_sprintf.cc'].flags += ['-DNDEBUG']
-
-LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/linux',
-]
-
-USE_LIBS += [
- 'mozsandbox',
-]
-
-FINAL_LIBRARY = 'xul'
-
-if CONFIG['GNU_CXX']:
- CXXFLAGS += ['-Wno-error=shadow']
diff --git a/security/sandbox/linux/gtest/TestBroker.cpp b/security/sandbox/linux/gtest/TestBroker.cpp
deleted file mode 100644
index a311e181a..000000000
--- a/security/sandbox/linux/gtest/TestBroker.cpp
+++ /dev/null
@@ -1,626 +0,0 @@
-/* -*- 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 "broker/SandboxBroker.h"
-#include "broker/SandboxBrokerUtils.h"
-#include "SandboxBrokerClient.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <stdlib.h>
-#include <sched.h>
-#include <semaphore.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <time.h>
-#include <unistd.h>
-
-#include "mozilla/Atomics.h"
-#include "mozilla/NullPtr.h"
-#include "mozilla/PodOperations.h"
-#include "mozilla/UniquePtr.h"
-#include "mozilla/ipc/FileDescriptor.h"
-
-namespace mozilla {
-
-static const int MAY_ACCESS = SandboxBroker::MAY_ACCESS;
-static const int MAY_READ = SandboxBroker::MAY_READ;
-static const int MAY_WRITE = SandboxBroker::MAY_WRITE;
-static const int MAY_CREATE = SandboxBroker::MAY_CREATE;
-static const auto AddAlways = SandboxBroker::Policy::AddAlways;
-
-class SandboxBrokerTest : public ::testing::Test
-{
- UniquePtr<SandboxBroker> mServer;
- UniquePtr<SandboxBrokerClient> mClient;
-
- UniquePtr<const SandboxBroker::Policy> GetPolicy() const;
-
- template<class C, void (C::* Main)()>
- static void* ThreadMain(void* arg) {
- (static_cast<C*>(arg)->*Main)();
- return nullptr;
- }
-
-protected:
- int Open(const char* aPath, int aFlags) {
- return mClient->Open(aPath, aFlags);
- }
- int Access(const char* aPath, int aMode) {
- return mClient->Access(aPath, aMode);
- }
- int Stat(const char* aPath, statstruct* aStat) {
- return mClient->Stat(aPath, aStat);
- }
- int LStat(const char* aPath, statstruct* aStat) {
- return mClient->LStat(aPath, aStat);
- }
- int Chmod(const char* aPath, int aMode) {
- return mClient->Chmod(aPath, aMode);
- }
- int Link(const char* aPath, const char* bPath) {
- return mClient->Link(aPath, bPath);
- }
- int Mkdir(const char* aPath, int aMode) {
- return mClient->Mkdir(aPath, aMode);
- }
- int Symlink(const char* aPath, const char* bPath) {
- return mClient->Symlink(aPath, bPath);
- }
- int Rename(const char* aPath, const char* bPath) {
- return mClient->Rename(aPath, bPath);
- }
- int Rmdir(const char* aPath) {
- return mClient->Rmdir(aPath);
- }
- int Unlink(const char* aPath) {
- return mClient->Unlink(aPath);
- }
- ssize_t Readlink(const char* aPath, char* aBuff, size_t aSize) {
- return mClient->Readlink(aPath, aBuff, aSize);
- }
-
- virtual void SetUp() {
- ipc::FileDescriptor fd;
-
- mServer = SandboxBroker::Create(GetPolicy(), getpid(), fd);
- ASSERT_NE(mServer, nullptr);
- ASSERT_TRUE(fd.IsValid());
- auto rawFD = fd.ClonePlatformHandle();
- mClient.reset(new SandboxBrokerClient(rawFD.release()));
- }
-
- template<class C, void (C::* Main)()>
- void StartThread(pthread_t *aThread) {
- ASSERT_EQ(0, pthread_create(aThread, nullptr, ThreadMain<C, Main>,
- static_cast<C*>(this)));
- }
-
- template<class C, void (C::* Main)()>
- void RunOnManyThreads() {
- static const int kNumThreads = 5;
- pthread_t threads[kNumThreads];
- for (int i = 0; i < kNumThreads; ++i) {
- StartThread<C, Main>(&threads[i]);
- }
- for (int i = 0; i < kNumThreads; ++i) {
- void* retval;
- ASSERT_EQ(pthread_join(threads[i], &retval), 0);
- ASSERT_EQ(retval, static_cast<void*>(nullptr));
- }
- }
-
-public:
- void MultiThreadOpenWorker();
- void MultiThreadStatWorker();
-};
-
-UniquePtr<const SandboxBroker::Policy>
-SandboxBrokerTest::GetPolicy() const
-{
- UniquePtr<SandboxBroker::Policy> policy(new SandboxBroker::Policy());
-
- policy->AddPath(MAY_READ | MAY_WRITE, "/dev/null", AddAlways);
- policy->AddPath(MAY_READ, "/dev/zero", AddAlways);
- policy->AddPath(MAY_READ, "/var/empty/qwertyuiop", AddAlways);
- policy->AddPath(MAY_ACCESS, "/proc/self", AddAlways); // Warning: Linux-specific.
- policy->AddPath(MAY_READ | MAY_WRITE, "/tmp", AddAlways);
- policy->AddPath(MAY_READ | MAY_WRITE | MAY_CREATE, "/tmp/blublu", AddAlways);
- policy->AddPath(MAY_READ | MAY_WRITE | MAY_CREATE, "/tmp/blublublu", AddAlways);
-
- return Move(policy);
-}
-
-TEST_F(SandboxBrokerTest, OpenForRead)
-{
- int fd;
-
- fd = Open("/dev/null", O_RDONLY);
- ASSERT_GE(fd, 0) << "Opening /dev/null failed.";
- close(fd);
- fd = Open("/dev/zero", O_RDONLY);
- ASSERT_GE(fd, 0) << "Opening /dev/zero failed.";
- close(fd);
- fd = Open("/var/empty/qwertyuiop", O_RDONLY);
- EXPECT_EQ(-ENOENT, fd) << "Opening allowed but nonexistent file succeeded.";
- fd = Open("/proc/self", O_RDONLY);
- EXPECT_EQ(-EACCES, fd) << "Opening stat-only file for read succeeded.";
- fd = Open("/proc/self/stat", O_RDONLY);
- EXPECT_EQ(-EACCES, fd) << "Opening disallowed file succeeded.";
-}
-
-TEST_F(SandboxBrokerTest, OpenForWrite)
-{
- int fd;
-
- fd = Open("/dev/null", O_WRONLY);
- ASSERT_GE(fd, 0) << "Opening /dev/null write-only failed.";
- close(fd);
- fd = Open("/dev/null", O_RDWR);
- ASSERT_GE(fd, 0) << "Opening /dev/null read/write failed.";
- close(fd);
- fd = Open("/dev/zero", O_WRONLY);
- ASSERT_EQ(-EACCES, fd) << "Opening read-only-by-policy file write-only succeeded.";
- fd = Open("/dev/zero", O_RDWR);
- ASSERT_EQ(-EACCES, fd) << "Opening read-only-by-policy file read/write succeeded.";
-}
-
-TEST_F(SandboxBrokerTest, SimpleRead)
-{
- int fd;
- char c;
-
- fd = Open("/dev/null", O_RDONLY);
- ASSERT_GE(fd, 0);
- EXPECT_EQ(0, read(fd, &c, 1));
- close(fd);
- fd = Open("/dev/zero", O_RDONLY);
- ASSERT_GE(fd, 0);
- ASSERT_EQ(1, read(fd, &c, 1));
- EXPECT_EQ(c, '\0');
-}
-
-TEST_F(SandboxBrokerTest, Access)
-{
- EXPECT_EQ(0, Access("/dev/null", F_OK));
- EXPECT_EQ(0, Access("/dev/null", R_OK));
- EXPECT_EQ(0, Access("/dev/null", W_OK));
- EXPECT_EQ(0, Access("/dev/null", R_OK|W_OK));
- EXPECT_EQ(-EACCES, Access("/dev/null", X_OK));
- EXPECT_EQ(-EACCES, Access("/dev/null", R_OK|X_OK));
-
- EXPECT_EQ(0, Access("/dev/zero", R_OK));
- EXPECT_EQ(-EACCES, Access("/dev/zero", W_OK));
- EXPECT_EQ(-EACCES, Access("/dev/zero", R_OK|W_OK));
-
- EXPECT_EQ(-ENOENT, Access("/var/empty/qwertyuiop", R_OK));
- EXPECT_EQ(-EACCES, Access("/var/empty/qwertyuiop", W_OK));
-
- EXPECT_EQ(0, Access("/proc/self", F_OK));
- EXPECT_EQ(-EACCES, Access("/proc/self", R_OK));
-
- EXPECT_EQ(-EACCES, Access("/proc/self/stat", F_OK));
-}
-
-TEST_F(SandboxBrokerTest, Stat)
-{
- statstruct realStat, brokeredStat;
- ASSERT_EQ(0, statsyscall("/dev/null", &realStat)) << "Shouldn't ever fail!";
- EXPECT_EQ(0, Stat("/dev/null", &brokeredStat));
- EXPECT_EQ(realStat.st_ino, brokeredStat.st_ino);
- EXPECT_EQ(realStat.st_rdev, brokeredStat.st_rdev);
-
- EXPECT_EQ(-ENOENT, Stat("/var/empty/qwertyuiop", &brokeredStat));
- EXPECT_EQ(-EACCES, Stat("/dev", &brokeredStat));
-
- EXPECT_EQ(0, Stat("/proc/self", &brokeredStat));
- EXPECT_TRUE(S_ISDIR(brokeredStat.st_mode));
-}
-
-TEST_F(SandboxBrokerTest, LStat)
-{
- statstruct realStat, brokeredStat;
- ASSERT_EQ(0, lstatsyscall("/dev/null", &realStat));
- EXPECT_EQ(0, LStat("/dev/null", &brokeredStat));
- EXPECT_EQ(realStat.st_ino, brokeredStat.st_ino);
- EXPECT_EQ(realStat.st_rdev, brokeredStat.st_rdev);
-
- EXPECT_EQ(-ENOENT, LStat("/var/empty/qwertyuiop", &brokeredStat));
- EXPECT_EQ(-EACCES, LStat("/dev", &brokeredStat));
-
- EXPECT_EQ(0, LStat("/proc/self", &brokeredStat));
- EXPECT_TRUE(S_ISLNK(brokeredStat.st_mode));
-}
-
-static void PrePostTestCleanup(void)
-{
- unlink("/tmp/blublu");
- rmdir("/tmp/blublu");
- unlink("/tmp/nope");
- rmdir("/tmp/nope");
- unlink("/tmp/blublublu");
- rmdir("/tmp/blublublu");
-}
-
-TEST_F(SandboxBrokerTest, Chmod)
-{
- PrePostTestCleanup();
-
- int fd = Open("/tmp/blublu", O_WRONLY | O_CREAT);
- ASSERT_GE(fd, 0) << "Opening /tmp/blublu for writing failed.";
- close(fd);
- // Set read only. SandboxBroker enforces 0600 mode flags.
- ASSERT_EQ(0, Chmod("/tmp/blublu", S_IRUSR));
- // SandboxBroker doesn't use real access(), it just checks against
- // the policy. So it can't see the change in permisions here.
- // This won't work:
- // EXPECT_EQ(-EACCES, Access("/tmp/blublu", W_OK));
- statstruct realStat;
- EXPECT_EQ(0, statsyscall("/tmp/blublu", &realStat));
- EXPECT_EQ((mode_t)S_IRUSR, realStat.st_mode & 0777);
-
- ASSERT_EQ(0, Chmod("/tmp/blublu", S_IRUSR | S_IWUSR));
- EXPECT_EQ(0, statsyscall("/tmp/blublu", &realStat));
- EXPECT_EQ((mode_t)(S_IRUSR | S_IWUSR), realStat.st_mode & 0777);
- EXPECT_EQ(0, unlink("/tmp/blublu"));
-
- PrePostTestCleanup();
-}
-
-TEST_F(SandboxBrokerTest, Link)
-{
- PrePostTestCleanup();
-
- int fd = Open("/tmp/blublu", O_WRONLY | O_CREAT);
- ASSERT_GE(fd, 0) << "Opening /tmp/blublu for writing failed.";
- close(fd);
- ASSERT_EQ(0, Link("/tmp/blublu", "/tmp/blublublu"));
- EXPECT_EQ(0, Access("/tmp/blublublu", F_OK));
- // Not whitelisted target path
- EXPECT_EQ(-EACCES, Link("/tmp/blublu", "/tmp/nope"));
- EXPECT_EQ(0, unlink("/tmp/blublublu"));
- EXPECT_EQ(0, unlink("/tmp/blublu"));
-
- PrePostTestCleanup();
-}
-
-TEST_F(SandboxBrokerTest, Symlink)
-{
- PrePostTestCleanup();
-
- int fd = Open("/tmp/blublu", O_WRONLY | O_CREAT);
- ASSERT_GE(fd, 0) << "Opening /tmp/blublu for writing failed.";
- close(fd);
- ASSERT_EQ(0, Symlink("/tmp/blublu", "/tmp/blublublu"));
- EXPECT_EQ(0, Access("/tmp/blublublu", F_OK));
- statstruct aStat;
- ASSERT_EQ(0, lstatsyscall("/tmp/blublublu", &aStat));
- EXPECT_EQ((mode_t)S_IFLNK, aStat.st_mode & S_IFMT);
- // Not whitelisted target path
- EXPECT_EQ(-EACCES, Symlink("/tmp/blublu", "/tmp/nope"));
- EXPECT_EQ(0, unlink("/tmp/blublublu"));
- EXPECT_EQ(0, unlink("/tmp/blublu"));
-
- PrePostTestCleanup();
-}
-
-TEST_F(SandboxBrokerTest, Mkdir)
-{
- PrePostTestCleanup();
-
- ASSERT_EQ(0, mkdir("/tmp/blublu", 0600))
- << "Creating dir /tmp/blublu failed.";
- EXPECT_EQ(0, Access("/tmp/blublu", F_OK));
- // Not whitelisted target path
- EXPECT_EQ(-EACCES, Mkdir("/tmp/nope", 0600))
- << "Creating dir without MAY_CREATE succeed.";
- EXPECT_EQ(0, rmdir("/tmp/blublu"));
-
- PrePostTestCleanup();
-}
-
-TEST_F(SandboxBrokerTest, Rename)
-{
- PrePostTestCleanup();
-
- ASSERT_EQ(0, mkdir("/tmp/blublu", 0600))
- << "Creating dir /tmp/blublu failed.";
- EXPECT_EQ(0, Access("/tmp/blublu", F_OK));
- ASSERT_EQ(0, Rename("/tmp/blublu", "/tmp/blublublu"));
- EXPECT_EQ(0, Access("/tmp/blublublu", F_OK));
- EXPECT_EQ(-ENOENT , Access("/tmp/blublu", F_OK));
- // Not whitelisted target path
- EXPECT_EQ(-EACCES, Rename("/tmp/blublublu", "/tmp/nope"))
- << "Renaming dir without write access succeed.";
- EXPECT_EQ(0, rmdir("/tmp/blublublu"));
-
- PrePostTestCleanup();
-}
-
-TEST_F(SandboxBrokerTest, Rmdir)
-{
- PrePostTestCleanup();
-
- ASSERT_EQ(0, mkdir("/tmp/blublu", 0600))
- << "Creating dir /tmp/blublu failed.";
- EXPECT_EQ(0, Access("/tmp/blublu", F_OK));
- ASSERT_EQ(0, Rmdir("/tmp/blublu"));
- EXPECT_EQ(-ENOENT, Access("/tmp/blublu", F_OK));
- // Bypass sandbox to create a non-deletable dir
- ASSERT_EQ(0, mkdir("/tmp/nope", 0600));
- EXPECT_EQ(-EACCES, Rmdir("/tmp/nope"));
-
- PrePostTestCleanup();
-}
-
-TEST_F(SandboxBrokerTest, Unlink)
-{
- PrePostTestCleanup();
-
- int fd = Open("/tmp/blublu", O_WRONLY | O_CREAT);
- ASSERT_GE(fd, 0) << "Opening /tmp/blublu for writing failed.";
- close(fd);
- EXPECT_EQ(0, Access("/tmp/blublu", F_OK));
- EXPECT_EQ(0, Unlink("/tmp/blublu"));
- EXPECT_EQ(-ENOENT , Access("/tmp/blublu", F_OK));
- // Bypass sandbox to write a non-deletable file
- fd = open("/tmp/nope", O_WRONLY | O_CREAT, 0600);
- ASSERT_GE(fd, 0) << "Opening /tmp/nope for writing failed.";
- close(fd);
- EXPECT_EQ(-EACCES, Unlink("/tmp/nope"));
-
- PrePostTestCleanup();
-}
-
-TEST_F(SandboxBrokerTest, Readlink)
-{
- PrePostTestCleanup();
-
- int fd = Open("/tmp/blublu", O_WRONLY | O_CREAT);
- ASSERT_GE(fd, 0) << "Opening /tmp/blublu for writing failed.";
- close(fd);
- ASSERT_EQ(0, Symlink("/tmp/blublu", "/tmp/blublublu"));
- EXPECT_EQ(0, Access("/tmp/blublublu", F_OK));
- char linkBuff[256];
- EXPECT_EQ(11, Readlink("/tmp/blublublu", linkBuff, sizeof(linkBuff)));
- linkBuff[11] = '\0';
- EXPECT_EQ(0, strcmp(linkBuff, "/tmp/blublu"));
-
- PrePostTestCleanup();
-}
-
-TEST_F(SandboxBrokerTest, MultiThreadOpen) {
- RunOnManyThreads<SandboxBrokerTest,
- &SandboxBrokerTest::MultiThreadOpenWorker>();
-}
-void SandboxBrokerTest::MultiThreadOpenWorker() {
- static const int kNumLoops = 10000;
-
- for (int i = 1; i <= kNumLoops; ++i) {
- int nullfd = Open("/dev/null", O_RDONLY);
- int zerofd = Open("/dev/zero", O_RDONLY);
- ASSERT_GE(nullfd, 0) << "Loop " << i << "/" << kNumLoops;
- ASSERT_GE(zerofd, 0) << "Loop " << i << "/" << kNumLoops;
- char c;
- ASSERT_EQ(0, read(nullfd, &c, 1)) << "Loop " << i << "/" << kNumLoops;
- ASSERT_EQ(1, read(zerofd, &c, 1)) << "Loop " << i << "/" << kNumLoops;
- ASSERT_EQ('\0', c) << "Loop " << i << "/" << kNumLoops;
- close(nullfd);
- close(zerofd);
- }
-}
-
-TEST_F(SandboxBrokerTest, MultiThreadStat) {
- RunOnManyThreads<SandboxBrokerTest,
- &SandboxBrokerTest::MultiThreadStatWorker>();
-}
-void SandboxBrokerTest::MultiThreadStatWorker() {
- static const int kNumLoops = 7500;
- statstruct nullStat, zeroStat, selfStat;
- dev_t realNullDev, realZeroDev;
- ino_t realSelfInode;
-
- ASSERT_EQ(0, statsyscall("/dev/null", &nullStat)) << "Shouldn't ever fail!";
- ASSERT_EQ(0, statsyscall("/dev/zero", &zeroStat)) << "Shouldn't ever fail!";
- ASSERT_EQ(0, lstatsyscall("/proc/self", &selfStat)) << "Shouldn't ever fail!";
- ASSERT_TRUE(S_ISLNK(selfStat.st_mode)) << "Shouldn't ever fail!";
- realNullDev = nullStat.st_rdev;
- realZeroDev = zeroStat.st_rdev;
- realSelfInode = selfStat.st_ino;
- for (int i = 1; i <= kNumLoops; ++i) {
- ASSERT_EQ(0, Stat("/dev/null", &nullStat))
- << "Loop " << i << "/" << kNumLoops;
- ASSERT_EQ(0, Stat("/dev/zero", &zeroStat))
- << "Loop " << i << "/" << kNumLoops;
- ASSERT_EQ(0, LStat("/proc/self", &selfStat))
- << "Loop " << i << "/" << kNumLoops;
-
- ASSERT_EQ(realNullDev, nullStat.st_rdev)
- << "Loop " << i << "/" << kNumLoops;
- ASSERT_EQ(realZeroDev, zeroStat.st_rdev)
- << "Loop " << i << "/" << kNumLoops;
- ASSERT_TRUE(S_ISLNK(selfStat.st_mode))
- << "Loop " << i << "/" << kNumLoops;
- ASSERT_EQ(realSelfInode, selfStat.st_ino)
- << "Loop " << i << "/" << kNumLoops;
- }
-}
-
-#if 0
-class SandboxBrokerSigStress : public SandboxBrokerTest
-{
- int mSigNum;
- struct sigaction mOldAction;
- Atomic<void*> mVoidPtr;
-
- static void SigHandler(int aSigNum, siginfo_t* aSigInfo, void *aCtx) {
- ASSERT_EQ(SI_QUEUE, aSigInfo->si_code);
- SandboxBrokerSigStress* that =
- static_cast<SandboxBrokerSigStress*>(aSigInfo->si_value.sival_ptr);
- ASSERT_EQ(that->mSigNum, aSigNum);
- that->DoSomething();
- }
-
-protected:
- Atomic<int> mTestIter;
- sem_t mSemaphore;
-
- void SignalThread(pthread_t aThread) {
- union sigval sv;
- sv.sival_ptr = this;
- ASSERT_NE(0, mSigNum);
- ASSERT_EQ(0, pthread_sigqueue(aThread, mSigNum, sv));
- }
-
- virtual void SetUp() {
- ASSERT_EQ(0, sem_init(&mSemaphore, 0, 0));
- mVoidPtr = nullptr;
- mSigNum = 0;
- for (int sigNum = SIGRTMIN; sigNum < SIGRTMAX; ++sigNum) {
- ASSERT_EQ(0, sigaction(sigNum, nullptr, &mOldAction));
- if ((mOldAction.sa_flags & SA_SIGINFO) == 0 &&
- mOldAction.sa_handler == SIG_DFL) {
- struct sigaction newAction;
- PodZero(&newAction);
- newAction.sa_flags = SA_SIGINFO;
- newAction.sa_sigaction = SigHandler;
- ASSERT_EQ(0, sigaction(sigNum, &newAction, nullptr));
- mSigNum = sigNum;
- break;
- }
- }
- ASSERT_NE(mSigNum, 0);
-
- SandboxBrokerTest::SetUp();
- }
-
- virtual void TearDown() {
- ASSERT_EQ(0, sem_destroy(&mSemaphore));
- if (mSigNum != 0) {
- ASSERT_EQ(0, sigaction(mSigNum, &mOldAction, nullptr));
- }
- if (mVoidPtr) {
- free(mVoidPtr);
- }
- }
-
- void DoSomething();
-
-public:
- void MallocWorker();
- void FreeWorker();
-};
-
-TEST_F(SandboxBrokerSigStress, StressTest)
-{
- static const int kIters = 6250;
- static const int kNsecPerIterPerIter = 4;
- struct timespec delay = { 0, 0 };
- pthread_t threads[2];
-
- mTestIter = kIters;
-
- StartThread<SandboxBrokerSigStress,
- &SandboxBrokerSigStress::MallocWorker>(&threads[0]);
- StartThread<SandboxBrokerSigStress,
- &SandboxBrokerSigStress::FreeWorker>(&threads[1]);
-
- for (int i = kIters; i > 0; --i) {
- SignalThread(threads[i % 2]);
- while (sem_wait(&mSemaphore) == -1 && errno == EINTR)
- /* retry */;
- ASSERT_EQ(i - 1, mTestIter);
- delay.tv_nsec += kNsecPerIterPerIter;
- struct timespec req = delay, rem;
- while (nanosleep(&req, &rem) == -1 && errno == EINTR) {
- req = rem;
- }
- }
- void *retval;
- ASSERT_EQ(0, pthread_join(threads[0], &retval));
- ASSERT_EQ(nullptr, retval);
- ASSERT_EQ(0, pthread_join(threads[1], &retval));
- ASSERT_EQ(nullptr, retval);
-}
-
-void
-SandboxBrokerSigStress::MallocWorker()
-{
- static const size_t kSize = 64;
-
- void* mem = malloc(kSize);
- while (mTestIter > 0) {
- ASSERT_NE(mem, mVoidPtr);
- mem = mVoidPtr.exchange(mem);
- if (mem) {
- sched_yield();
- } else {
- mem = malloc(kSize);
- }
- }
- if (mem) {
- free(mem);
- }
-}
-
-void
-SandboxBrokerSigStress::FreeWorker()
-{
- void *mem = nullptr;
- while (mTestIter > 0) {
- mem = mVoidPtr.exchange(mem);
- if (mem) {
- free(mem);
- mem = nullptr;
- } else {
- sched_yield();
- }
- }
-}
-
-void
-SandboxBrokerSigStress::DoSomething()
-{
- int fd;
- char c;
- struct stat st;
-
- //fprintf(stderr, "Don't try this at home: %d\n", static_cast<int>(mTestIter));
- switch (mTestIter % 5) {
- case 0:
- fd = Open("/dev/null", O_RDWR);
- ASSERT_GE(fd, 0);
- ASSERT_EQ(0, read(fd, &c, 1));
- close(fd);
- break;
- case 1:
- fd = Open("/dev/zero", O_RDONLY);
- ASSERT_GE(fd, 0);
- ASSERT_EQ(1, read(fd, &c, 1));
- ASSERT_EQ('\0', c);
- close(fd);
- break;
- case 2:
- ASSERT_EQ(0, Access("/dev/null", W_OK));
- break;
- case 3:
- ASSERT_EQ(0, Stat("/proc/self", &st));
- ASSERT_TRUE(S_ISDIR(st.st_mode));
- break;
- case 4:
- ASSERT_EQ(0, LStat("/proc/self", &st));
- ASSERT_TRUE(S_ISLNK(st.st_mode));
- break;
- }
- mTestIter--;
- sem_post(&mSemaphore);
-}
-#endif
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/gtest/TestBrokerPolicy.cpp b/security/sandbox/linux/gtest/TestBrokerPolicy.cpp
deleted file mode 100644
index 474458446..000000000
--- a/security/sandbox/linux/gtest/TestBrokerPolicy.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/* -*- 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 "broker/SandboxBroker.h"
-
-namespace mozilla {
-
-static const int MAY_ACCESS = SandboxBroker::MAY_ACCESS;
-static const int MAY_READ = SandboxBroker::MAY_READ;
-static const int MAY_WRITE = SandboxBroker::MAY_WRITE;
-//static const int MAY_CREATE = SandboxBroker::MAY_CREATE;
-//static const int RECURSIVE = SandboxBroker::RECURSIVE;
-static const auto AddAlways = SandboxBroker::Policy::AddAlways;
-
-TEST(SandboxBrokerPolicyLookup, Simple)
-{
- SandboxBroker::Policy p;
- p.AddPath(MAY_READ, "/dev/urandom", AddAlways);
-
- EXPECT_NE(0, p.Lookup("/dev/urandom")) << "Added path not found.";
- EXPECT_EQ(MAY_ACCESS | MAY_READ, p.Lookup("/dev/urandom"))
- << "Added path found with wrong perms.";
- EXPECT_EQ(0, p.Lookup("/etc/passwd")) << "Non-added path was found.";
-}
-
-TEST(SandboxBrokerPolicyLookup, CopyCtor)
-{
- SandboxBroker::Policy psrc;
- psrc.AddPath(MAY_READ | MAY_WRITE, "/dev/null", AddAlways);
- SandboxBroker::Policy pdst(psrc);
- psrc.AddPath(MAY_READ, "/dev/zero", AddAlways);
- pdst.AddPath(MAY_READ, "/dev/urandom", AddAlways);
-
- EXPECT_EQ(MAY_ACCESS | MAY_READ | MAY_WRITE, psrc.Lookup("/dev/null"))
- << "Common path absent in copy source.";
- EXPECT_EQ(MAY_ACCESS | MAY_READ | MAY_WRITE, pdst.Lookup("/dev/null"))
- << "Common path absent in copy destination.";
-
- EXPECT_EQ(MAY_ACCESS | MAY_READ, psrc.Lookup("/dev/zero"))
- << "Source-only path is absent.";
- EXPECT_EQ(0, pdst.Lookup("/dev/zero"))
- << "Source-only path is present in copy destination.";
-
- EXPECT_EQ(0, psrc.Lookup("/dev/urandom"))
- << "Destination-only path is present in copy source.";
- EXPECT_EQ(MAY_ACCESS | MAY_READ, pdst.Lookup("/dev/urandom"))
- << "Destination-only path is absent.";
-
- EXPECT_EQ(0, psrc.Lookup("/etc/passwd"))
- << "Non-added path is present in copy source.";
- EXPECT_EQ(0, pdst.Lookup("/etc/passwd"))
- << "Non-added path is present in copy source.";
-}
-
-TEST(SandboxBrokerPolicyLookup, Recursive)
-{
- SandboxBroker::Policy psrc;
- psrc.AddPath(MAY_READ | MAY_WRITE, "/dev/null", AddAlways);
- psrc.AddPath(MAY_READ, "/dev/zero", AddAlways);
- psrc.AddPath(MAY_READ, "/dev/urandom", AddAlways);
-
- EXPECT_EQ(MAY_ACCESS | MAY_READ | MAY_WRITE, psrc.Lookup("/dev/null"))
- << "Basic path is present.";
- EXPECT_EQ(MAY_ACCESS | MAY_READ, psrc.Lookup("/dev/zero"))
- << "Basic path has no extra flags";
-
- psrc.AddDir(MAY_READ | MAY_WRITE, "/dev/");
-
- EXPECT_EQ(MAY_ACCESS | MAY_READ | MAY_WRITE, psrc.Lookup("/dev/random"))
- << "Permission via recursive dir.";
- EXPECT_EQ(MAY_ACCESS | MAY_READ | MAY_WRITE, psrc.Lookup("/dev/sd/0"))
- << "Permission via recursive dir, nested deeper";
- EXPECT_EQ(0, psrc.Lookup("/dev/sd/0/"))
- << "Invalid path format.";
- EXPECT_EQ(0, psrc.Lookup("/usr/dev/sd"))
- << "Match must be a prefix.";
-
- psrc.AddDir(MAY_READ, "/dev/sd/");
- EXPECT_EQ(MAY_ACCESS | MAY_READ | MAY_WRITE, psrc.Lookup("/dev/sd/0"))
- << "Extra permissions from parent path granted.";
- EXPECT_EQ(0, psrc.Lookup("/dev/.."))
- << "Refuse attempted subdir escape.";
-
- psrc.AddDir(MAY_READ, "/tmp");
- EXPECT_EQ(MAY_ACCESS | MAY_READ, psrc.Lookup("/tmp/good/a"))
- << "Check whether dir add with no trailing / was sucessful.";
- EXPECT_EQ(0, psrc.Lookup("/tmp_good_but_bad"))
- << "Enforce terminator on directories.";
- EXPECT_EQ(0, psrc.Lookup("/tmp/."))
- << "Do not allow opening a directory handle.";
-}
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/gtest/TestSandboxUtil.cpp b/security/sandbox/linux/gtest/TestSandboxUtil.cpp
deleted file mode 100644
index cd29813f9..000000000
--- a/security/sandbox/linux/gtest/TestSandboxUtil.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/* -*- 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 "SandboxUtil.h"
-#include "SandboxInfo.h"
-
-#include <pthread.h>
-
-namespace mozilla {
-
-// In order to test IsSingleThreaded when the test-running process is
-// single-threaded, before assorted XPCOM components have created many
-// additional threads, a static initializer is used.
-
-namespace {
-
-struct EarlyTest {
- bool mWasSingleThreaded;
-
- EarlyTest()
- : mWasSingleThreaded(IsSingleThreaded())
- { }
-};
-
-static const EarlyTest gEarlyTest;
-
-} // namespace
-
-TEST(SandboxUtil, IsSingleThreaded)
-{
- // If the test system if affected by kUnexpectedThreads, (1) there's
- // no point in doing this test, and (2) if that happens on Mozilla
- // CI then burning the tree is an appropriate response.
- ASSERT_FALSE(SandboxInfo::Get().Test(SandboxInfo::kUnexpectedThreads));
- EXPECT_TRUE(gEarlyTest.mWasSingleThreaded);
- EXPECT_FALSE(IsSingleThreaded());
-}
-
-} // namespace mozilla
diff --git a/security/sandbox/linux/gtest/moz.build b/security/sandbox/linux/gtest/moz.build
deleted file mode 100644
index 7aecc7fe3..000000000
--- a/security/sandbox/linux/gtest/moz.build
+++ /dev/null
@@ -1,27 +0,0 @@
-# -*- 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('sandboxtest')
-
-SOURCES = [
- '../SandboxBrokerClient.cpp',
- '../SandboxUtil.cpp',
- 'TestBroker.cpp',
- 'TestBrokerPolicy.cpp',
- 'TestSandboxUtil.cpp',
-]
-
-LOCAL_INCLUDES += [
- '/security/sandbox/linux',
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
-]
-
-FINAL_LIBRARY = 'xul-gtest'
diff --git a/security/sandbox/linux/moz.build b/security/sandbox/linux/moz.build
deleted file mode 100644
index 4273da955..000000000
--- a/security/sandbox/linux/moz.build
+++ /dev/null
@@ -1,116 +0,0 @@
-# -*- 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/.
-
-SharedLibrary('mozsandbox')
-
-# Depend on mozglue if and only if it's a shared library;
-# this needs to match mozglue/build/moz.build:
-if CONFIG['OS_TARGET'] == 'Android':
- USE_LIBS += [
- 'mozglue',
- ]
-
-EXPORTS.mozilla += [
- 'Sandbox.h',
- 'SandboxInfo.h',
-]
-
-SOURCES += [
- '../chromium-shim/base/logging.cpp',
- '../chromium/base/at_exit.cc',
- '../chromium/base/callback_internal.cc',
- '../chromium/base/lazy_instance.cc',
- '../chromium/base/memory/ref_counted.cc',
- '../chromium/base/memory/singleton.cc',
- '../chromium/base/strings/safe_sprintf.cc',
- '../chromium/base/strings/string16.cc',
- '../chromium/base/strings/string_piece.cc',
- '../chromium/base/strings/string_util.cc',
- '../chromium/base/strings/string_util_constants.cc',
- '../chromium/base/strings/stringprintf.cc',
- '../chromium/base/strings/utf_string_conversion_utils.cc',
- '../chromium/base/strings/utf_string_conversions.cc',
- '../chromium/base/synchronization/condition_variable_posix.cc',
- '../chromium/base/synchronization/lock.cc',
- '../chromium/base/synchronization/lock_impl_posix.cc',
- '../chromium/base/synchronization/waitable_event_posix.cc',
- '../chromium/base/third_party/icu/icu_utf.cc',
- '../chromium/base/threading/platform_thread_internal_posix.cc',
- '../chromium/base/threading/platform_thread_linux.cc',
- '../chromium/base/threading/platform_thread_posix.cc',
- '../chromium/base/threading/thread_collision_warner.cc',
- '../chromium/base/threading/thread_id_name_manager.cc',
- '../chromium/base/threading/thread_local_posix.cc',
- '../chromium/base/threading/thread_restrictions.cc',
- '../chromium/base/time/time.cc',
- '../chromium/base/time/time_posix.cc',
- '../chromium/sandbox/linux/bpf_dsl/bpf_dsl.cc',
- '../chromium/sandbox/linux/bpf_dsl/codegen.cc',
- '../chromium/sandbox/linux/bpf_dsl/dump_bpf.cc',
- '../chromium/sandbox/linux/bpf_dsl/policy.cc',
- '../chromium/sandbox/linux/bpf_dsl/policy_compiler.cc',
- '../chromium/sandbox/linux/bpf_dsl/syscall_set.cc',
- '../chromium/sandbox/linux/seccomp-bpf/die.cc',
- '../chromium/sandbox/linux/seccomp-bpf/syscall.cc',
- '../chromium/sandbox/linux/seccomp-bpf/trap.cc',
- '../chromium/sandbox/linux/services/syscall_wrappers.cc',
- 'broker/SandboxBrokerCommon.cpp',
- 'LinuxCapabilities.cpp',
- 'Sandbox.cpp',
- 'SandboxBrokerClient.cpp',
- 'SandboxChroot.cpp',
- 'SandboxFilter.cpp',
- 'SandboxFilterUtil.cpp',
- 'SandboxHooks.cpp',
- 'SandboxInfo.cpp',
- 'SandboxLogging.cpp',
- 'SandboxUtil.cpp',
-]
-
-# This copy of SafeSPrintf doesn't need to avoid the Chromium logging
-# dependency like the one in libxul does, but this way the behavior is
-# consistent. See also the comment in SandboxLogging.h.
-SOURCES['../chromium/base/strings/safe_sprintf.cc'].flags += ['-DNDEBUG']
-
-# Keep clang and GCC from warning about intentional 'switch' fallthrough in icu_utf.cc:
-if CONFIG['CLANG_CXX'] or CONFIG['GNU_CXX']:
- SOURCES['../chromium/base/third_party/icu/icu_utf.cc'].flags += ['-Wno-implicit-fallthrough']
-
-if CONFIG['GNU_CXX']:
- CXXFLAGS += ['-Wno-shadow']
- SOURCES['../chromium/sandbox/linux/services/syscall_wrappers.cc'].flags += [
- '-Wno-empty-body',
- ]
-
-# gcc lto likes to put the top level asm in syscall.cc in a different partition
-# from the function using it which breaks the build. Work around that by
-# forcing there to be only one partition.
-if '-flto' in CONFIG['OS_CXXFLAGS'] and not CONFIG['CLANG_CXX']:
- LDFLAGS += ['--param lto-partitions=1']
-
-DEFINES['NS_NO_XPCOM'] = True
-DISABLE_STL_WRAPPING = True
-
-LOCAL_INCLUDES += ['/security/sandbox/linux']
-LOCAL_INCLUDES += ['/security/sandbox/chromium-shim']
-LOCAL_INCLUDES += ['/security/sandbox/chromium']
-LOCAL_INCLUDES += ['/nsprpub']
-
-
-if CONFIG['OS_TARGET'] != 'Android':
- # Needed for clock_gettime with glibc < 2.17:
- OS_LIBS += [
- 'rt',
- ]
-
-DIRS += [
- 'broker',
- 'glue',
-]
-
-TEST_DIRS += [
- 'gtest',
-]
diff --git a/security/sandbox/mac/Sandbox.h b/security/sandbox/mac/Sandbox.h
deleted file mode 100644
index b2e1a7ec5..000000000
--- a/security/sandbox/mac/Sandbox.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/* -*- 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/. */
-
-#ifndef mozilla_Sandbox_h
-#define mozilla_Sandbox_h
-
-#include <string>
-
-enum MacSandboxType {
- MacSandboxType_Default = 0,
- MacSandboxType_Plugin,
- MacSandboxType_Content,
- MacSandboxType_Invalid
-};
-
-enum MacSandboxPluginType {
- MacSandboxPluginType_Default = 0,
- MacSandboxPluginType_GMPlugin_Default, // Any Gecko Media Plugin
- MacSandboxPluginType_GMPlugin_OpenH264, // Gecko Media Plugin, OpenH264
- MacSandboxPluginType_GMPlugin_EME, // Gecko Media Plugin, EME
- MacSandboxPluginType_GMPlugin_EME_Widevine, // Gecko Media Plugin, Widevine
- MacSandboxPluginType_Invalid
-};
-
-typedef struct _MacSandboxPluginInfo {
- _MacSandboxPluginInfo()
- : type(MacSandboxPluginType_Default) {}
- _MacSandboxPluginInfo(const struct _MacSandboxPluginInfo& other)
- : type(other.type), pluginPath(other.pluginPath),
- pluginBinaryPath(other.pluginBinaryPath) {}
- MacSandboxPluginType type;
- std::string pluginPath;
- std::string pluginBinaryPath;
-} MacSandboxPluginInfo;
-
-typedef struct _MacSandboxInfo {
- _MacSandboxInfo()
- : type(MacSandboxType_Default), level(0) {}
- _MacSandboxInfo(const struct _MacSandboxInfo& other)
- : type(other.type), level(other.level),
- hasSandboxedProfile(other.hasSandboxedProfile),
- pluginInfo(other.pluginInfo),
- appPath(other.appPath), appBinaryPath(other.appBinaryPath),
- appDir(other.appDir), appTempDir(other.appTempDir),
- profileDir(other.profileDir) {}
- MacSandboxType type;
- int32_t level;
- bool hasSandboxedProfile;
- MacSandboxPluginInfo pluginInfo;
- std::string appPath;
- std::string appBinaryPath;
- std::string appDir;
- std::string appTempDir;
- std::string profileDir;
-} MacSandboxInfo;
-
-namespace mozilla {
-
-bool StartMacSandbox(MacSandboxInfo aInfo, std::string &aErrorMessage);
-
-} // namespace mozilla
-
-#endif // mozilla_Sandbox_h
diff --git a/security/sandbox/mac/Sandbox.mm b/security/sandbox/mac/Sandbox.mm
deleted file mode 100644
index ae1612ffa..000000000
--- a/security/sandbox/mac/Sandbox.mm
+++ /dev/null
@@ -1,489 +0,0 @@
-/* -*- 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/. */
-
-// The Mac sandbox module is a static library (a Library in moz.build terms)
-// that can be linked into any binary (for example plugin-container or XUL).
-// It must not have dependencies on any other Mozilla module. This is why,
-// for example, it has its own OS X version detection code, rather than
-// linking to nsCocoaFeatures.mm in XUL.
-
-#include "Sandbox.h"
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <CoreFoundation/CoreFoundation.h>
-
-#include "mozilla/Assertions.h"
-
-// XXX There are currently problems with the /usr/include/sandbox.h file on
-// some/all of the Macs in Mozilla's build system. For the time being (until
-// this problem is resolved), we refer directly to what we need from it,
-// rather than including it here.
-extern "C" int sandbox_init(const char *profile, uint64_t flags, char **errorbuf);
-extern "C" void sandbox_free_error(char *errorbuf);
-
-#define MAC_OS_X_VERSION_10_0_HEX 0x00001000
-#define MAC_OS_X_VERSION_10_6_HEX 0x00001060
-#define MAC_OS_X_VERSION_10_7_HEX 0x00001070
-#define MAC_OS_X_VERSION_10_8_HEX 0x00001080
-#define MAC_OS_X_VERSION_10_9_HEX 0x00001090
-#define MAC_OS_X_VERSION_10_10_HEX 0x000010A0
-
-// Note about "major", "minor" and "bugfix" in the following code:
-//
-// The code decomposes an OS X version number into these components, and in
-// doing so follows Apple's terminology in Gestalt.h. But this is very
-// misleading, because in other contexts Apple uses the "minor" component of
-// an OS X version number to indicate a "major" release (for example the "9"
-// in OS X 10.9.5), and the "bugfix" component to indicate a "minor" release
-// (for example the "5" in OS X 10.9.5).
-
-class OSXVersion {
-public:
- static int32_t OSXVersionMinor();
-
-private:
- static void GetSystemVersion(int32_t& aMajor, int32_t& aMinor, int32_t& aBugFix);
- static int32_t GetVersionNumber();
- static int32_t mOSXVersion;
-};
-
-int32_t OSXVersion::mOSXVersion = -1;
-
-int32_t OSXVersion::OSXVersionMinor()
-{
- return (GetVersionNumber() & 0xF0) >> 4;
-}
-
-void
-OSXVersion::GetSystemVersion(int32_t& aMajor, int32_t& aMinor, int32_t& aBugFix)
-{
- SInt32 major = 0, minor = 0, bugfix = 0;
-
- CFURLRef url =
- CFURLCreateWithString(kCFAllocatorDefault,
- CFSTR("file:///System/Library/CoreServices/SystemVersion.plist"),
- NULL);
- CFReadStreamRef stream =
- CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
- CFReadStreamOpen(stream);
- CFDictionaryRef sysVersionPlist = (CFDictionaryRef)
- CFPropertyListCreateWithStream(kCFAllocatorDefault,
- stream, 0, kCFPropertyListImmutable,
- NULL, NULL);
- CFReadStreamClose(stream);
- CFRelease(stream);
- CFRelease(url);
-
- CFStringRef versionString = (CFStringRef)
- CFDictionaryGetValue(sysVersionPlist, CFSTR("ProductVersion"));
- CFArrayRef versions =
- CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault,
- versionString, CFSTR("."));
- CFIndex count = CFArrayGetCount(versions);
- if (count > 0) {
- CFStringRef component = (CFStringRef) CFArrayGetValueAtIndex(versions, 0);
- major = CFStringGetIntValue(component);
- if (count > 1) {
- component = (CFStringRef) CFArrayGetValueAtIndex(versions, 1);
- minor = CFStringGetIntValue(component);
- if (count > 2) {
- component = (CFStringRef) CFArrayGetValueAtIndex(versions, 2);
- bugfix = CFStringGetIntValue(component);
- }
- }
- }
- CFRelease(sysVersionPlist);
- CFRelease(versions);
-
- // If 'major' isn't what we expect, assume the oldest version of OS X we
- // currently support (OS X 10.6).
- if (major != 10) {
- aMajor = 10; aMinor = 6; aBugFix = 0;
- } else {
- aMajor = major; aMinor = minor; aBugFix = bugfix;
- }
-}
-
-int32_t
-OSXVersion::GetVersionNumber()
-{
- if (mOSXVersion == -1) {
- int32_t major, minor, bugfix;
- GetSystemVersion(major, minor, bugfix);
- mOSXVersion = MAC_OS_X_VERSION_10_0_HEX + (minor << 4) + bugfix;
- }
- return mOSXVersion;
-}
-
-namespace mozilla {
-
-static const char pluginSandboxRules[] =
- "(version 1)\n"
- "(deny default)\n"
- "(allow signal (target self))\n"
- "(allow sysctl-read)\n"
- "(allow iokit-open (iokit-user-client-class \"IOHIDParamUserClient\"))\n"
- "(allow mach-lookup\n"
- " (global-name \"com.apple.cfprefsd.agent\")\n"
- " (global-name \"com.apple.cfprefsd.daemon\")\n"
- " (global-name \"com.apple.system.opendirectoryd.libinfo\")\n"
- " (global-name \"com.apple.system.logger\")\n"
- " (global-name \"com.apple.ls.boxd\"))\n"
- "(allow file-read*\n"
- " (regex #\"^/etc$\")\n"
- " (regex #\"^/dev/u?random$\")\n"
- " (literal \"/usr/share/icu/icudt51l.dat\")\n"
- " (regex #\"^/System/Library/Displays/Overrides/*\")\n"
- " (regex #\"^/System/Library/CoreServices/CoreTypes.bundle/*\")\n"
- " (regex #\"^/System/Library/PrivateFrameworks/*\")\n"
- " (regex #\"^/usr/lib/libstdc\\+\\+\\..*dylib$\")\n"
- " (literal \"%s\")\n"
- " (literal \"%s\")\n"
- " (literal \"%s\"))\n";
-
-static const char widevinePluginSandboxRulesAddend[] =
- "(allow mach-lookup (global-name \"com.apple.windowserver.active\"))\n";
-
-static const char contentSandboxRules[] =
- "(version 1)\n"
- "\n"
- "(define sandbox-level %d)\n"
- "(define macosMinorVersion %d)\n"
- "(define appPath \"%s\")\n"
- "(define appBinaryPath \"%s\")\n"
- "(define appDir \"%s\")\n"
- "(define appTempDir \"%s\")\n"
- "(define hasProfileDir %d)\n"
- "(define profileDir \"%s\")\n"
- "(define home-path \"%s\")\n"
- "\n"
- "; Allow read access to standard system paths.\n"
- "(allow file-read*\n"
- " (require-all (file-mode #o0004)\n"
- " (require-any (subpath \"/Library/Filesystems/NetFSPlugins\")\n"
- " (subpath \"/System\")\n"
- " (subpath \"/private/var/db/dyld\")\n"
- " (subpath \"/usr/lib\")\n"
- " (subpath \"/usr/share\"))))\n"
- "\n"
- "(allow file-read-metadata\n"
- " (literal \"/etc\")\n"
- " (literal \"/tmp\")\n"
- " (literal \"/var\")\n"
- " (literal \"/private/etc/localtime\"))\n"
- "\n"
- "; Allow read access to standard special files.\n"
- "(allow file-read*\n"
- " (literal \"/dev/autofs_nowait\")\n"
- " (literal \"/dev/random\")\n"
- " (literal \"/dev/urandom\"))\n"
- "\n"
- "(allow file-read*\n"
- " file-write-data\n"
- " (literal \"/dev/null\")\n"
- " (literal \"/dev/zero\"))\n"
- "\n"
- "(allow file-read*\n"
- " file-write-data\n"
- " file-ioctl\n"
- " (literal \"/dev/dtracehelper\"))\n"
- "\n"
- "; Used to read hw.ncpu, hw.physicalcpu_max, kern.ostype, and others\n"
- "(allow sysctl-read)\n"
- "\n"
- "(begin\n"
- " (deny default)\n"
- " (debug deny)\n"
- "\n"
- " (define resolving-literal literal)\n"
- " (define resolving-subpath subpath)\n"
- " (define resolving-regex regex)\n"
- "\n"
- " (define container-path appPath)\n"
- " (define appdir-path appDir)\n"
- " (define var-folders-re \"^/private/var/folders/[^/][^/]\")\n"
- " (define var-folders2-re (string-append var-folders-re \"/[^/]+/[^/]\"))\n"
- "\n"
- " (define (home-regex home-relative-regex)\n"
- " (resolving-regex (string-append \"^\" (regex-quote home-path) home-relative-regex)))\n"
- " (define (home-subpath home-relative-subpath)\n"
- " (resolving-subpath (string-append home-path home-relative-subpath)))\n"
- " (define (home-literal home-relative-literal)\n"
- " (resolving-literal (string-append home-path home-relative-literal)))\n"
- "\n"
- " (define (profile-subpath profile-relative-subpath)\n"
- " (resolving-subpath (string-append profileDir profile-relative-subpath)))\n"
- "\n"
- " (define (var-folders-regex var-folders-relative-regex)\n"
- " (resolving-regex (string-append var-folders-re var-folders-relative-regex)))\n"
- " (define (var-folders2-regex var-folders2-relative-regex)\n"
- " (resolving-regex (string-append var-folders2-re var-folders2-relative-regex)))\n"
- "\n"
- " (define (allow-shared-preferences-read domain)\n"
- " (begin\n"
- " (if (defined? `user-preference-read)\n"
- " (allow user-preference-read (preference-domain domain)))\n"
- " (allow file-read*\n"
- " (home-literal (string-append \"/Library/Preferences/\" domain \".plist\"))\n"
- " (home-regex (string-append \"/Library/Preferences/ByHost/\" (regex-quote domain) \"\\..*\\.plist$\")))\n"
- " ))\n"
- "\n"
- " (define (allow-shared-list domain)\n"
- " (allow file-read*\n"
- " (home-regex (string-append \"/Library/Preferences/\" (regex-quote domain)))))\n"
- "\n"
- " (allow ipc-posix-shm\n"
- " (ipc-posix-name-regex \"^/tmp/com.apple.csseed:\")\n"
- " (ipc-posix-name-regex \"^CFPBS:\")\n"
- " (ipc-posix-name-regex \"^AudioIO\"))\n"
- "\n"
- " (allow file-read-metadata\n"
- " (literal \"/home\")\n"
- " (literal \"/net\")\n"
- " (regex \"^/private/tmp/KSInstallAction\\.\")\n"
- " (var-folders-regex \"/\")\n"
- " (home-subpath \"/Library\"))\n"
- "\n"
- " (allow signal (target self))\n"
- " (allow job-creation (literal \"/Library/CoreMediaIO/Plug-Ins/DAL\"))\n"
- " (allow iokit-set-properties (iokit-property \"IOAudioControlValue\"))\n"
- "\n"
- " (allow mach-lookup\n"
- " (global-name \"com.apple.coreservices.launchservicesd\")\n"
- " (global-name \"com.apple.coreservices.appleevents\")\n"
- " (global-name \"com.apple.pasteboard.1\")\n"
- " (global-name \"com.apple.window_proxies\")\n"
- " (global-name \"com.apple.windowserver.active\")\n"
- " (global-name \"com.apple.audio.coreaudiod\")\n"
- " (global-name \"com.apple.audio.audiohald\")\n"
- " (global-name \"com.apple.PowerManagement.control\")\n"
- " (global-name \"com.apple.cmio.VDCAssistant\")\n"
- " (global-name \"com.apple.SystemConfiguration.configd\")\n"
- " (global-name \"com.apple.iconservices\")\n"
- " (global-name \"com.apple.cookied\")\n"
- " (global-name \"com.apple.cache_delete\")\n"
- " (global-name \"com.apple.pluginkit.pkd\")\n"
- " (global-name \"com.apple.bird\")\n"
- " (global-name \"com.apple.ocspd\")\n"
- " (global-name \"com.apple.cmio.AppleCameraAssistant\")\n"
- " (global-name \"com.apple.DesktopServicesHelper\"))\n"
- "\n"
- "; bug 1312273\n"
- " (if (= macosMinorVersion 9)\n"
- " (allow mach-lookup (global-name \"com.apple.xpcd\")))\n"
- "\n"
- " (if (>= macosMinorVersion 13)\n"
- " (allow mach-lookup\n"
- " ; bug 1376163\n"
- " (global-name \"com.apple.audio.AudioComponentRegistrar\")\n"
- " ; bug 1392988\n"
- " (xpc-service-name \"com.apple.coremedia.videodecoder\")\n"
- " (xpc-service-name \"com.apple.coremedia.videoencoder\")))\n"
- "\n"
- " (allow iokit-open\n"
- " (iokit-user-client-class \"IOHIDParamUserClient\")\n"
- " (iokit-user-client-class \"IOAudioControlUserClient\")\n"
- " (iokit-user-client-class \"IOAudioEngineUserClient\")\n"
- " (iokit-user-client-class \"IGAccelDevice\")\n"
- " (iokit-user-client-class \"nvDevice\")\n"
- " (iokit-user-client-class \"nvSharedUserClient\")\n"
- " (iokit-user-client-class \"nvFermiGLContext\")\n"
- " (iokit-user-client-class \"IGAccelGLContext\")\n"
- " (iokit-user-client-class \"IGAccelSharedUserClient\")\n"
- " (iokit-user-client-class \"IGAccelVideoContextMain\")\n"
- " (iokit-user-client-class \"IGAccelVideoContextMedia\")\n"
- " (iokit-user-client-class \"IGAccelVideoContextVEBox\")\n"
- " (iokit-user-client-class \"RootDomainUserClient\")\n"
- " (iokit-user-client-class \"IOUSBDeviceUserClientV2\")\n"
- " (iokit-user-client-class \"IOUSBInterfaceUserClientV2\"))\n"
- "\n"
- "; depending on systems, the 1st, 2nd or both rules are necessary\n"
- " (allow-shared-preferences-read \"com.apple.HIToolbox\")\n"
- " (allow file-read-data (literal \"/Library/Preferences/com.apple.HIToolbox.plist\"))\n"
- "\n"
- " (allow-shared-preferences-read \"com.apple.ATS\")\n"
- " (allow file-read-data (literal \"/Library/Preferences/.GlobalPreferences.plist\"))\n"
- "\n"
- " (allow file-read*\n"
- " (subpath \"/Library/Fonts\")\n"
- " (subpath \"/Library/Audio/Plug-Ins\")\n"
- " (subpath \"/Library/CoreMediaIO/Plug-Ins/DAL\")\n"
- " (subpath \"/Library/Spelling\")\n"
- " (literal \"/\")\n"
- " (literal \"/private/tmp\")\n"
- " (literal \"/private/var/tmp\")\n"
- "\n"
- " (home-literal \"/.CFUserTextEncoding\")\n"
- " (home-literal \"/Library/Preferences/com.apple.DownloadAssessment.plist\")\n"
- " (home-subpath \"/Library/Colors\")\n"
- " (home-subpath \"/Library/Fonts\")\n"
- " (home-subpath \"/Library/FontCollections\")\n"
- " (home-subpath \"/Library/Keyboard Layouts\")\n"
- " (home-subpath \"/Library/Input Methods\")\n"
- " (home-subpath \"/Library/Spelling\")\n"
- "\n"
- " (subpath appdir-path)\n"
- "\n"
- " (literal appPath)\n"
- " (literal appBinaryPath))\n"
- "\n"
- " (allow-shared-list \"org.mozilla.plugincontainer\")\n"
- "\n"
- "; the following rule should be removed when microphone access\n"
- "; is brokered through the content process\n"
- " (allow device-microphone)\n"
- "\n"
- " (allow file* (var-folders2-regex \"/com\\.apple\\.IntlDataCache\\.le$\"))\n"
- " (allow file-read*\n"
- " (var-folders2-regex \"/com\\.apple\\.IconServices/\")\n"
- " (var-folders2-regex \"/[^/]+\\.mozrunner/extensions/[^/]+/chrome/[^/]+/content/[^/]+\\.j(s|ar)$\"))\n"
- "\n"
- " (allow file-write* (var-folders2-regex \"/org\\.chromium\\.[a-zA-Z0-9]*$\"))\n"
- "\n"
- "; Per-user and system-wide Extensions dir\n"
- " (allow file-read*\n"
- " (home-regex \"/Library/Application Support/[^/]+/Extensions/[^/]/\")\n"
- " (resolving-regex \"/Library/Application Support/[^/]+/Extensions/[^/]/\"))\n"
- "\n"
- "; The following rules impose file access restrictions which get\n"
- "; more restrictive in higher levels. When file-origin-specific\n"
- "; content processes are used for file:// origin browsing, the\n"
- "; global file-read* permission should be removed from each level.\n"
- "\n"
- "; level 1: global read access permitted, no global write access\n"
- " (if (= sandbox-level 1) (allow file-read*))\n"
- "\n"
- "; level 2: global read access permitted, no global write access,\n"
- "; no read/write access to ~/Library,\n"
- "; no read/write access to $PROFILE,\n"
- "; read access permitted to $PROFILE/{extensions,weave}\n"
- " (if (= sandbox-level 2)\n"
- " (if (not (zero? hasProfileDir))\n"
- " ; we have a profile dir\n"
- " (begin\n"
- " (allow file-read* (require-all\n"
- " (require-not (home-subpath \"/Library\"))\n"
- " (require-not (subpath profileDir))))\n"
- " (allow file-read*\n"
- " (profile-subpath \"/extensions\")\n"
- " (profile-subpath \"/weave\")))\n"
- " ; we don't have a profile dir\n"
- " (allow file-read* (require-not (home-subpath \"/Library\")))))\n"
- "\n"
- "; accelerated graphics\n"
- " (allow-shared-preferences-read \"com.apple.opengl\")\n"
- " (allow-shared-preferences-read \"com.nvidia.OpenGL\")\n"
- " (allow mach-lookup\n"
- " (global-name \"com.apple.cvmsServ\"))\n"
- " (allow iokit-open\n"
- " (iokit-connection \"IOAccelerator\")\n"
- " (iokit-user-client-class \"IOAccelerationUserClient\")\n"
- " (iokit-user-client-class \"IOSurfaceRootUserClient\")\n"
- " (iokit-user-client-class \"IOSurfaceSendRight\")\n"
- " (iokit-user-client-class \"IOFramebufferSharedUserClient\")\n"
- " (iokit-user-client-class \"AppleSNBFBUserClient\")\n"
- " (iokit-user-client-class \"AGPMClient\")\n"
- " (iokit-user-client-class \"AppleGraphicsControlClient\")\n"
- " (iokit-user-client-class \"AppleGraphicsPolicyClient\"))\n"
- "\n"
- "; bug 1153809\n"
- " (allow iokit-open\n"
- " (iokit-user-client-class \"NVDVDContextTesla\")\n"
- " (iokit-user-client-class \"Gen6DVDContext\"))\n"
- "\n"
- "; bug 1201935\n"
- " (allow file-read*\n"
- " (home-subpath \"/Library/Caches/TemporaryItems\"))\n"
- "\n"
- "; bug 1237847\n"
- " (allow file-read*\n"
- " (subpath appTempDir))\n"
- " (allow file-write*\n"
- " (subpath appTempDir))\n"
- "\n"
- "; bug 1324610\n"
- " (allow network-outbound (literal \"/private/var/run/cupsd\"))\n"
-#ifdef DEBUG
- "\n"
- "; bug 1303987\n"
- " (allow file-write* (var-folders-regex \"/\"))\n"
-#endif
- ")\n";
-
-bool StartMacSandbox(MacSandboxInfo aInfo, std::string &aErrorMessage)
-{
- char *profile = NULL;
- if (aInfo.type == MacSandboxType_Plugin) {
- asprintf(&profile, pluginSandboxRules,
- aInfo.pluginInfo.pluginBinaryPath.c_str(),
- aInfo.appPath.c_str(),
- aInfo.appBinaryPath.c_str());
-
- if (profile &&
- aInfo.pluginInfo.type == MacSandboxPluginType_GMPlugin_EME_Widevine) {
- char *widevineProfile = NULL;
- asprintf(&widevineProfile, "%s%s", profile,
- widevinePluginSandboxRulesAddend);
- free(profile);
- profile = widevineProfile;
- }
- }
- else if (aInfo.type == MacSandboxType_Content) {
- MOZ_ASSERT(aInfo.level >= 1);
- if (aInfo.level >= 1) {
- asprintf(&profile, contentSandboxRules, aInfo.level,
- OSXVersion::OSXVersionMinor(),
- aInfo.appPath.c_str(),
- aInfo.appBinaryPath.c_str(),
- aInfo.appDir.c_str(),
- aInfo.appTempDir.c_str(),
- aInfo.hasSandboxedProfile ? 1 : 0,
- aInfo.profileDir.c_str(),
- getenv("HOME"));
- } else {
- fprintf(stderr,
- "Content sandbox disabled due to sandbox level setting\n");
- return false;
- }
- }
- else {
- char *msg = NULL;
- asprintf(&msg, "Unexpected sandbox type %u", aInfo.type);
- if (msg) {
- aErrorMessage.assign(msg);
- free(msg);
- }
- return false;
- }
-
- if (!profile) {
- fprintf(stderr, "Out of memory in StartMacSandbox()!\n");
- return false;
- }
-
- char *errorbuf = NULL;
- int rv = sandbox_init(profile, 0, &errorbuf);
- if (rv) {
- if (errorbuf) {
- char *msg = NULL;
- asprintf(&msg, "sandbox_init() failed with error \"%s\"", errorbuf);
- if (msg) {
- aErrorMessage.assign(msg);
- free(msg);
- }
- fprintf(stderr, "profile: %s\n", profile);
- sandbox_free_error(errorbuf);
- }
- }
- free(profile);
- if (rv) {
- return false;
- }
-
- return true;
-}
-
-} // namespace mozilla
diff --git a/security/sandbox/mac/moz.build b/security/sandbox/mac/moz.build
deleted file mode 100644
index 28aa06bfa..000000000
--- a/security/sandbox/mac/moz.build
+++ /dev/null
@@ -1,15 +0,0 @@
-# -*- 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 += [
- 'Sandbox.h',
-]
-
-SOURCES += [
- 'Sandbox.mm',
-]
-
-Library('mozsandbox');
diff --git a/security/sandbox/modifications-to-chromium-to-reapply-after-upstream-merge.txt b/security/sandbox/modifications-to-chromium-to-reapply-after-upstream-merge.txt
deleted file mode 100644
index 62c2dac0b..000000000
--- a/security/sandbox/modifications-to-chromium-to-reapply-after-upstream-merge.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-Please add a link to the bugzilla bug and patch name that should be re-applied.
-Also, please update any existing links to their actual mozilla-central changeset.
-
-https://bugzilla.mozilla.org/show_bug.cgi?id=1287426 bug1287426part4.patch
-https://bugzilla.mozilla.org/show_bug.cgi?id=1287426 bug1287426part5.patch
-https://hg.mozilla.org/mozilla-central/rev/7df8d6639971
-https://bugzilla.mozilla.org/show_bug.cgi?id=1287426 bug1287426part7.patch
-https://bugzilla.mozilla.org/show_bug.cgi?id=1273372 bug1273372part2.patch
-https://bugzilla.mozilla.org/show_bug.cgi?id=1273372 bug1273372part3.patch
diff --git a/security/sandbox/moz-chromium-commit-status.txt b/security/sandbox/moz-chromium-commit-status.txt
deleted file mode 100644
index 501e18b4b..000000000
--- a/security/sandbox/moz-chromium-commit-status.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Chromium Commit Directory / File (relative to security/sandbox/)
----------------------------------------- ------------------------------------------------
-4ec79b7f2379a60cdc15599e93255c0fa417f1ed chromium
-611754aea9d1c0ba5c7980fa267fd005dc249b85 chromium/sandbox/win/src/policy_target.cc
diff --git a/security/sandbox/moz.build b/security/sandbox/moz.build
deleted file mode 100644
index 1420d6498..000000000
--- a/security/sandbox/moz.build
+++ /dev/null
@@ -1,176 +0,0 @@
-# -*- 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 += ['test/browser.ini']
-
-with Files('**'):
- BUG_COMPONENT = ('Core', 'Security: Process Sandboxing')
-
-if CONFIG['OS_ARCH'] == 'Linux':
- DIRS += ['linux']
-elif CONFIG['OS_ARCH'] == 'Darwin':
- DIRS += ['mac']
-elif CONFIG['OS_ARCH'] == 'WINNT':
- Library('sandbox_s')
- FORCE_STATIC_LIB = True
-
- DIRS += [
- 'win/src/sandboxbroker',
- 'win/src/sandboxtarget',
- ]
-
- if (CONFIG['CPU_ARCH'] == 'x86' and CONFIG['_MSC_VER'] and not
- CONFIG['CLANG_CL']):
- DIRS += ['win/wow_helper']
-
- EXPORTS.mozilla.sandboxing += [
- 'chromium-shim/sandbox/win/loggingCallbacks.h',
- 'chromium-shim/sandbox/win/loggingTypes.h',
- 'chromium-shim/sandbox/win/sandboxLogging.h',
- 'win/SandboxInitialization.h',
- ]
-
- SOURCES += [
- 'chromium-shim/base/files/file_path.cpp',
- 'chromium-shim/base/logging.cpp',
- 'chromium-shim/sandbox/win/sandboxLogging.cpp',
- 'chromium/base/at_exit.cc',
- 'chromium/base/base_switches.cc',
- 'chromium/base/callback_internal.cc',
- 'chromium/base/cpu.cc',
- 'chromium/base/debug/alias.cc',
- 'chromium/base/debug/profiler.cc',
- 'chromium/base/hash.cc',
- 'chromium/base/lazy_instance.cc',
- 'chromium/base/location.cc',
- 'chromium/base/memory/ref_counted.cc',
- 'chromium/base/memory/singleton.cc',
- 'chromium/base/strings/nullable_string16.cc',
- 'chromium/base/strings/string_number_conversions.cc',
- 'chromium/base/strings/string_piece.cc',
- 'chromium/base/strings/string_split.cc',
- 'chromium/base/strings/string_util.cc',
- 'chromium/base/strings/string_util_constants.cc',
- 'chromium/base/strings/stringprintf.cc',
- 'chromium/base/strings/utf_string_conversion_utils.cc',
- 'chromium/base/strings/utf_string_conversions.cc',
- 'chromium/base/synchronization/lock.cc',
- 'chromium/base/synchronization/lock_impl_win.cc',
- 'chromium/base/third_party/dmg_fp/dtoa.cc',
- 'chromium/base/third_party/dmg_fp/g_fmt.cc',
- 'chromium/base/third_party/icu/icu_utf.cc',
- 'chromium/base/third_party/superfasthash/superfasthash.c',
- 'chromium/base/threading/platform_thread_win.cc',
- 'chromium/base/threading/thread_collision_warner.cc',
- 'chromium/base/threading/thread_id_name_manager.cc',
- 'chromium/base/threading/thread_local_win.cc',
- 'chromium/base/threading/thread_restrictions.cc',
- 'chromium/base/time/time.cc',
- 'chromium/base/time/time_win.cc',
- 'chromium/base/win/pe_image.cc',
- 'chromium/base/win/scoped_handle.cc',
- 'chromium/base/win/scoped_process_information.cc',
- 'chromium/base/win/startup_information.cc',
- 'chromium/base/win/windows_version.cc',
- 'chromium/sandbox/win/src/acl.cc',
- 'chromium/sandbox/win/src/app_container.cc',
- 'chromium/sandbox/win/src/broker_services.cc',
- 'chromium/sandbox/win/src/crosscall_server.cc',
- 'chromium/sandbox/win/src/eat_resolver.cc',
- 'chromium/sandbox/win/src/filesystem_dispatcher.cc',
- 'chromium/sandbox/win/src/filesystem_interception.cc',
- 'chromium/sandbox/win/src/filesystem_policy.cc',
- 'chromium/sandbox/win/src/handle_closer.cc',
- 'chromium/sandbox/win/src/handle_closer_agent.cc',
- 'chromium/sandbox/win/src/handle_dispatcher.cc',
- 'chromium/sandbox/win/src/handle_interception.cc',
- 'chromium/sandbox/win/src/handle_policy.cc',
- 'chromium/sandbox/win/src/interception.cc',
- 'chromium/sandbox/win/src/interception_agent.cc',
- 'chromium/sandbox/win/src/job.cc',
- 'chromium/sandbox/win/src/named_pipe_dispatcher.cc',
- 'chromium/sandbox/win/src/named_pipe_interception.cc',
- 'chromium/sandbox/win/src/named_pipe_policy.cc',
- 'chromium/sandbox/win/src/policy_broker.cc',
- 'chromium/sandbox/win/src/policy_engine_opcodes.cc',
- 'chromium/sandbox/win/src/policy_engine_processor.cc',
- 'chromium/sandbox/win/src/policy_low_level.cc',
- 'chromium/sandbox/win/src/policy_target.cc',
- 'chromium/sandbox/win/src/process_mitigations.cc',
- 'chromium/sandbox/win/src/process_mitigations_win32k_dispatcher.cc',
- 'chromium/sandbox/win/src/process_mitigations_win32k_interception.cc',
- 'chromium/sandbox/win/src/process_mitigations_win32k_policy.cc',
- 'chromium/sandbox/win/src/process_thread_dispatcher.cc',
- 'chromium/sandbox/win/src/process_thread_interception.cc',
- 'chromium/sandbox/win/src/process_thread_policy.cc',
- 'chromium/sandbox/win/src/registry_dispatcher.cc',
- 'chromium/sandbox/win/src/registry_interception.cc',
- 'chromium/sandbox/win/src/registry_policy.cc',
- 'chromium/sandbox/win/src/resolver.cc',
- 'chromium/sandbox/win/src/restricted_token.cc',
- 'chromium/sandbox/win/src/restricted_token_utils.cc',
- 'chromium/sandbox/win/src/sandbox.cc',
- 'chromium/sandbox/win/src/sandbox_globals.cc',
- 'chromium/sandbox/win/src/sandbox_nt_util.cc',
- 'chromium/sandbox/win/src/sandbox_policy_base.cc',
- 'chromium/sandbox/win/src/sandbox_rand.cc',
- 'chromium/sandbox/win/src/sandbox_utils.cc',
- 'chromium/sandbox/win/src/service_resolver.cc',
- 'chromium/sandbox/win/src/sharedmem_ipc_client.cc',
- 'chromium/sandbox/win/src/sharedmem_ipc_server.cc',
- 'chromium/sandbox/win/src/sid.cc',
- 'chromium/sandbox/win/src/sync_dispatcher.cc',
- 'chromium/sandbox/win/src/sync_interception.cc',
- 'chromium/sandbox/win/src/sync_policy.cc',
- 'chromium/sandbox/win/src/target_interceptions.cc',
- 'chromium/sandbox/win/src/target_process.cc',
- 'chromium/sandbox/win/src/target_services.cc',
- 'chromium/sandbox/win/src/top_level_dispatcher.cc',
- 'chromium/sandbox/win/src/win2k_threadpool.cc',
- 'chromium/sandbox/win/src/win_utils.cc',
- 'chromium/sandbox/win/src/window.cc',
- 'win/SandboxInitialization.cpp',
- ]
-
- if CONFIG['CPU_ARCH'] == 'x86_64':
- SOURCES += [
- 'chromium/sandbox/win/src/interceptors_64.cc',
- 'chromium/sandbox/win/src/resolver_64.cc',
- 'chromium/sandbox/win/src/service_resolver_64.cc',
- 'chromium/sandbox/win/src/Wow64_64.cc',
- ]
- else:
- SOURCES += [
- 'chromium/sandbox/win/src/resolver_32.cc',
- 'chromium/sandbox/win/src/service_resolver_32.cc',
- 'chromium/sandbox/win/src/sidestep/ia32_modrm_map.cpp',
- 'chromium/sandbox/win/src/sidestep/ia32_opcode_map.cpp',
- 'chromium/sandbox/win/src/sidestep/mini_disassembler.cpp',
- 'chromium/sandbox/win/src/sidestep/preamble_patcher_with_stub.cpp',
- 'chromium/sandbox/win/src/sidestep_resolver.cc',
- 'chromium/sandbox/win/src/Wow64.cc',
- ]
-
- for var in ('UNICODE', '_UNICODE', 'NS_NO_XPCOM', 'SANDBOX_EXPORTS',
- '_CRT_RAND_S', 'CHROMIUM_SANDBOX_BUILD'):
- DEFINES[var] = True
-
- LOCAL_INCLUDES += ['/security/sandbox/chromium-shim']
- LOCAL_INCLUDES += ['/security/sandbox/chromium']
- LOCAL_INCLUDES += ['/nsprpub']
-
- DISABLE_STL_WRAPPING = True
-
- # Suppress warnings in third-party code.
- if CONFIG['_MSC_VER']:
- CXXFLAGS += [
- '-wd4275', # non dll-interface class exception used as base for dll-interface class
- '-wd4717', # recursive on all control paths, function will cause runtime stack overflow
- '-wd4996', # 'GetVersionExW': was declared deprecated
- '-wd4302', # 'reinterpret_cast': truncation from 'LPCSTR' to 'WORD'
- '-wd4311', # 'reinterpret_cast': pointer truncation from 'LPOVERLAPPED' to 'DWORD'
- '-wd4312', # 'reinterpret_cast': conversion from 'DWORD' to 'LPOVERLAPPED' of greater size
- ]
diff --git a/security/sandbox/test/browser.ini b/security/sandbox/test/browser.ini
deleted file mode 100644
index 7e3e96ea4..000000000
--- a/security/sandbox/test/browser.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-# Any copyright is dedicated to the Public Domain.
-# http://creativecommons.org/publicdomain/zero/1.0/
-[DEFAULT]
-tags = contentsandbox
-support-files =
- browser_content_sandbox_utils.js
-
-skip-if = !e10s
-[browser_content_sandbox_fs.js]
-skip-if = !e10s
-[browser_content_sandbox_syscalls.js]
diff --git a/security/sandbox/test/browser_content_sandbox_fs.js b/security/sandbox/test/browser_content_sandbox_fs.js
deleted file mode 100644
index 946f86bb9..000000000
--- a/security/sandbox/test/browser_content_sandbox_fs.js
+++ /dev/null
@@ -1,169 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var prefs = Cc["@mozilla.org/preferences-service;1"]
- .getService(Ci.nsIPrefBranch);
-
-Services.scriptloader.loadSubScript("chrome://mochitests/content/browser/" +
- "security/sandbox/test/browser_content_sandbox_utils.js", this);
-
-/*
- * This test exercises file I/O from the content process using OS.File
- * methods to validate that calls that are meant to be blocked by content
- * sandboxing are blocked.
- */
-
-// Creates file at |path| and returns a promise that resolves with true
-// if the file was successfully created, otherwise false. Include imports
-// so this can be safely serialized and run remotely by ContentTask.spawn.
-function createFile(path) {
- Components.utils.import("resource://gre/modules/osfile.jsm");
- let encoder = new TextEncoder();
- let array = encoder.encode("WRITING FROM CONTENT PROCESS");
- return OS.File.writeAtomic(path, array).then(function(value) {
- return true;
- }, function(reason) {
- return false;
- });
-}
-
-// Deletes file at |path| and returns a promise that resolves with true
-// if the file was successfully deleted, otherwise false. Include imports
-// so this can be safely serialized and run remotely by ContentTask.spawn.
-function deleteFile(path) {
- Components.utils.import("resource://gre/modules/osfile.jsm");
- return OS.File.remove(path, {ignoreAbsent: false}).then(function(value) {
- return true;
- }).catch(function(err) {
- return false;
- });
-}
-
-// Returns true if the current content sandbox level, passed in
-// the |level| argument, supports filesystem sandboxing.
-function isContentFileIOSandboxed(level) {
- let fileIOSandboxMinLevel = 0;
-
- // Set fileIOSandboxMinLevel to the lowest level that has
- // content filesystem sandboxing enabled. For now, this
- // varies across Windows, Mac, Linux, other.
- switch (Services.appinfo.OS) {
- case "WINNT":
- fileIOSandboxMinLevel = 1;
- break;
- case "Darwin":
- fileIOSandboxMinLevel = 1;
- break;
- case "Linux":
- fileIOSandboxMinLevel = 2;
- break;
- default:
- Assert.ok(false, "Unknown OS");
- }
-
- return (level >= fileIOSandboxMinLevel);
-}
-
-//
-// Drive tests for a single content process.
-//
-// Tests attempting to write to a file in the home directory from the
-// content process--expected to fail.
-//
-// Tests attempting to write to a file in the content temp directory
-// from the content process--expected to succeed. On Mac and Windows,
-// use "ContentTmpD", but on Linux use "TmpD" until Linux uses the
-// content temp dir key.
-//
-add_task(function*() {
- // This test is only relevant in e10s
- if (!gMultiProcessBrowser) {
- ok(false, "e10s is enabled");
- info("e10s is not enabled, exiting");
- return;
- }
-
- let level = 0;
- let prefExists = true;
-
- // Read the security.sandbox.content.level pref.
- // If the pref isn't set and we're running on Linux on !isNightly(),
- // exit without failing. The Linux content sandbox is only enabled
- // on Nightly at this time.
- try {
- level = prefs.getIntPref("security.sandbox.content.level");
- } catch (e) {
- prefExists = false;
- }
-
- // Special case Linux on !isNightly
- if (isLinux() && !isNightly()) {
- todo(prefExists, "pref security.sandbox.content.level exists");
- if (!prefExists) {
- return;
- }
- }
-
- ok(prefExists, "pref security.sandbox.content.level exists");
- if (!prefExists) {
- return;
- }
-
- // Special case Linux on !isNightly
- if (isLinux() && !isNightly()) {
- todo(level > 0, "content sandbox enabled for !nightly.");
- return;
- }
-
- info(`security.sandbox.content.level=${level}`);
- ok(level > 0, "content sandbox is enabled.");
- if (level == 0) {
- info("content sandbox is not enabled, exiting");
- return;
- }
-
- let isFileIOSandboxed = isContentFileIOSandboxed(level);
-
- // Special case Linux on !isNightly
- if (isLinux() && !isNightly()) {
- todo(isFileIOSandboxed, "content file I/O sandbox enabled for !nightly.");
- return;
- }
-
- // Content sandbox enabled, but level doesn't include file I/O sandboxing.
- ok(isFileIOSandboxed, "content file I/O sandboxing is enabled.");
- if (!isFileIOSandboxed) {
- info("content sandbox level too low for file I/O tests, exiting\n");
- return;
- }
-
- let browser = gBrowser.selectedBrowser;
-
- {
- // test if the content process can create in $HOME, this should fail
- let homeFile = fileInHomeDir();
- let path = homeFile.path;
- let fileCreated = yield ContentTask.spawn(browser, path, createFile);
- ok(fileCreated == false, "creating a file in home dir is not permitted");
- if (fileCreated == true) {
- // content process successfully created the file, now remove it
- homeFile.remove(false);
- }
- }
-
- {
- // test if the content process can create a temp file, should pass
- let path = fileInTempDir().path;
- let fileCreated = yield ContentTask.spawn(browser, path, createFile);
- if (!fileCreated && isWin()) {
- // TODO: fix 1329294 and enable this test for Windows.
- // Not using todo() because this only fails on automation.
- info("ignoring failure to write to content temp due to 1329294\n");
- return;
- }
- ok(fileCreated == true, "creating a file in content temp is permitted");
- // now delete the file
- let fileDeleted = yield ContentTask.spawn(browser, path, deleteFile);
- ok(fileDeleted == true, "deleting a file in content temp is permitted");
- }
-});
diff --git a/security/sandbox/test/browser_content_sandbox_syscalls.js b/security/sandbox/test/browser_content_sandbox_syscalls.js
deleted file mode 100644
index d56456966..000000000
--- a/security/sandbox/test/browser_content_sandbox_syscalls.js
+++ /dev/null
@@ -1,223 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-var prefs = Cc["@mozilla.org/preferences-service;1"]
- .getService(Ci.nsIPrefBranch);
-
-Services.scriptloader.loadSubScript("chrome://mochitests/content/browser/" +
- "security/sandbox/test/browser_content_sandbox_utils.js", this);
-
-/*
- * This test is for executing system calls in content processes to validate
- * that calls that are meant to be blocked by content sandboxing are blocked.
- * We use the term system calls loosely so that any OS API call such as
- * fopen could be included.
- */
-
-// Calls the native execv library function. Include imports so this can be
-// safely serialized and run remotely by ContentTask.spawn.
-function callExec(args) {
- Components.utils.import("resource://gre/modules/ctypes.jsm");
- let {lib, cmd} = args;
- let libc = ctypes.open(lib);
- let exec = libc.declare("execv", ctypes.default_abi,
- ctypes.int, ctypes.char.ptr);
- let rv = exec(cmd);
- libc.close();
- return (rv);
-}
-
-// Calls the native fork syscall.
-function callFork(args) {
- Components.utils.import("resource://gre/modules/ctypes.jsm");
- let {lib} = args;
- let libc = ctypes.open(lib);
- let fork = libc.declare("fork", ctypes.default_abi, ctypes.int);
- let rv = fork();
- libc.close();
- return (rv);
-}
-
-// Calls the native open/close syscalls.
-function callOpen(args) {
- Components.utils.import("resource://gre/modules/ctypes.jsm");
- let {lib, path, flags} = args;
- let libc = ctypes.open(lib);
- let open = libc.declare("open", ctypes.default_abi,
- ctypes.int, ctypes.char.ptr, ctypes.int);
- let close = libc.declare("close", ctypes.default_abi,
- ctypes.int, ctypes.int);
- let fd = open(path, flags);
- close(fd);
- libc.close();
- return (fd);
-}
-
-// open syscall flags
-function openWriteCreateFlags() {
- Assert.ok(isMac() || isLinux());
- if (isMac()) {
- let O_WRONLY = 0x001;
- let O_CREAT = 0x200;
- return (O_WRONLY | O_CREAT);
- } else {
- // Linux
- let O_WRONLY = 0x01;
- let O_CREAT = 0x40;
- return (O_WRONLY | O_CREAT);
- }
-}
-
-// Returns the name of the native library needed for native syscalls
-function getOSLib() {
- switch (Services.appinfo.OS) {
- case "WINNT":
- return "kernel32.dll";
- case "Darwin":
- return "libc.dylib";
- case "Linux":
- return "libc.so.6";
- default:
- Assert.ok(false, "Unknown OS");
- }
-}
-
-// Returns a harmless command to execute with execv
-function getOSExecCmd() {
- Assert.ok(!isWin());
- return ("/bin/cat");
-}
-
-// Returns true if the current content sandbox level, passed in
-// the |level| argument, supports syscall sandboxing.
-function areContentSyscallsSandboxed(level) {
- let syscallsSandboxMinLevel = 0;
-
- // Set syscallsSandboxMinLevel to the lowest level that has
- // syscall sandboxing enabled. For now, this varies across
- // Windows, Mac, Linux, other.
- switch (Services.appinfo.OS) {
- case "WINNT":
- syscallsSandboxMinLevel = 1;
- break;
- case "Darwin":
- syscallsSandboxMinLevel = 1;
- break;
- case "Linux":
- syscallsSandboxMinLevel = 2;
- break;
- default:
- Assert.ok(false, "Unknown OS");
- }
-
- return (level >= syscallsSandboxMinLevel);
-}
-
-//
-// Drive tests for a single content process.
-//
-// Tests executing OS API calls in the content process. Limited to Mac
-// and Linux calls for now.
-//
-add_task(function*() {
- // This test is only relevant in e10s
- if (!gMultiProcessBrowser) {
- ok(false, "e10s is enabled");
- info("e10s is not enabled, exiting");
- return;
- }
-
- let level = 0;
- let prefExists = true;
-
- // Read the security.sandbox.content.level pref.
- // If the pref isn't set and we're running on Linux on !isNightly(),
- // exit without failing. The Linux content sandbox is only enabled
- // on Nightly at this time.
- try {
- level = prefs.getIntPref("security.sandbox.content.level");
- } catch (e) {
- prefExists = false;
- }
-
- // Special case Linux on !isNightly
- if (isLinux() && !isNightly()) {
- todo(prefExists, "pref security.sandbox.content.level exists");
- if (!prefExists) {
- return;
- }
- }
-
- ok(prefExists, "pref security.sandbox.content.level exists");
- if (!prefExists) {
- return;
- }
-
- // Special case Linux on !isNightly
- if (isLinux() && !isNightly()) {
- todo(level > 0, "content sandbox enabled for !nightly.");
- return;
- }
-
- info(`security.sandbox.content.level=${level}`);
- ok(level > 0, "content sandbox is enabled.");
- if (level == 0) {
- info("content sandbox is not enabled, exiting");
- return;
- }
-
- let areSyscallsSandboxed = areContentSyscallsSandboxed(level);
-
- // Special case Linux on !isNightly
- if (isLinux() && !isNightly()) {
- todo(areSyscallsSandboxed, "content syscall sandbox enabled for !nightly.");
- return;
- }
-
- // Content sandbox enabled, but level doesn't include syscall sandboxing.
- ok(areSyscallsSandboxed, "content syscall sandboxing is enabled.");
- if (!areSyscallsSandboxed) {
- info("content sandbox level too low for syscall tests, exiting\n");
- return;
- }
-
- let browser = gBrowser.selectedBrowser;
- let lib = getOSLib();
-
- // use execv syscall
- // (causes content process to be killed on Linux)
- if (isMac()) {
- // exec something harmless, this should fail
- let cmd = getOSExecCmd();
- let rv = yield ContentTask.spawn(browser, {lib, cmd}, callExec);
- ok(rv == -1, `exec(${cmd}) is not permitted`);
- }
-
- // use open syscall
- if (isLinux() || isMac())
- {
- // open a file for writing in $HOME, this should fail
- let path = fileInHomeDir().path;
- let flags = openWriteCreateFlags();
- let fd = yield ContentTask.spawn(browser, {lib, path, flags}, callOpen);
- ok(fd < 0, "opening a file for writing in home is not permitted");
- }
-
- // use open syscall
- if (isLinux() || isMac())
- {
- // open a file for writing in the content temp dir, this should work
- // and the open handler in the content process closes the file for us
- let path = fileInTempDir().path;
- let flags = openWriteCreateFlags();
- let fd = yield ContentTask.spawn(browser, {lib, path, flags}, callOpen);
- ok(fd >= 0, "opening a file for writing in content temp is permitted");
- }
-
- // use fork syscall
- if (isLinux() || isMac())
- {
- let rv = yield ContentTask.spawn(browser, {lib}, callFork);
- ok(rv == -1, "calling fork is not permitted");
- }
-});
diff --git a/security/sandbox/test/browser_content_sandbox_utils.js b/security/sandbox/test/browser_content_sandbox_utils.js
deleted file mode 100644
index 0e9d01352..000000000
--- a/security/sandbox/test/browser_content_sandbox_utils.js
+++ /dev/null
@@ -1,57 +0,0 @@
-/* Any copyright is dedicated to the Public Domain.
- * http://creativecommons.org/publicdomain/zero/1.0/ */
-
-const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"]
- .getService(Ci.nsIUUIDGenerator);
-
-/*
- * Utility functions for the browser content sandbox tests.
- */
-
-function isMac() { return Services.appinfo.OS == "Darwin" }
-function isWin() { return Services.appinfo.OS == "WINNT" }
-function isLinux() { return Services.appinfo.OS == "Linux" }
-
-function isNightly() {
- let version = SpecialPowers.Cc["@mozilla.org/xre/app-info;1"].
- getService(SpecialPowers.Ci.nsIXULAppInfo).version;
- return (version.endsWith("a1"));
-}
-
-function uuid() {
- return uuidGenerator.generateUUID().toString();
-}
-
-// Returns a file object for a new file in the home dir ($HOME/<UUID>).
-function fileInHomeDir() {
- // get home directory, make sure it exists
- let homeDir = Services.dirsvc.get("Home", Ci.nsILocalFile);
- Assert.ok(homeDir.exists(), "Home dir exists");
- Assert.ok(homeDir.isDirectory(), "Home dir is a directory");
-
- // build a file object for a new file named $HOME/<UUID>
- let homeFile = homeDir.clone();
- homeFile.appendRelativePath(uuid());
- Assert.ok(!homeFile.exists(), homeFile.path + " does not exist");
- return (homeFile);
-}
-
-// Returns a file object for a new file in the content temp dir (.../<UUID>).
-function fileInTempDir() {
- let contentTempKey = "ContentTmpD";
- if (Services.appinfo.OS == "Linux") {
- // Linux builds don't use the content-specific temp key
- contentTempKey = "TmpD";
- }
-
- // get the content temp dir, make sure it exists
- let ctmp = Services.dirsvc.get(contentTempKey, Ci.nsILocalFile);
- Assert.ok(ctmp.exists(), "Content temp dir exists");
- Assert.ok(ctmp.isDirectory(), "Content temp dir is a directory");
-
- // build a file object for a new file in content temp
- let tempFile = ctmp.clone();
- tempFile.appendRelativePath(uuid());
- Assert.ok(!tempFile.exists(), tempFile.path + " does not exist");
- return (tempFile);
-}
diff --git a/security/sandbox/win/SandboxInitialization.cpp b/security/sandbox/win/SandboxInitialization.cpp
deleted file mode 100644
index e587c2598..000000000
--- a/security/sandbox/win/SandboxInitialization.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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 "SandboxInitialization.h"
-
-#include "sandbox/win/src/sandbox_factory.h"
-
-namespace mozilla {
-namespace sandboxing {
-
-static sandbox::TargetServices*
-InitializeTargetServices()
-{
- sandbox::TargetServices* targetServices =
- sandbox::SandboxFactory::GetTargetServices();
- if (!targetServices) {
- return nullptr;
- }
-
- if (targetServices->Init() != sandbox::SBOX_ALL_OK) {
- return nullptr;
- }
-
- return targetServices;
-}
-
-sandbox::TargetServices*
-GetInitializedTargetServices()
-{
- static sandbox::TargetServices* sInitializedTargetServices =
- InitializeTargetServices();
-
- return sInitializedTargetServices;
-}
-
-void
-LowerSandbox()
-{
- GetInitializedTargetServices()->LowerToken();
-}
-
-static sandbox::BrokerServices*
-InitializeBrokerServices()
-{
- sandbox::BrokerServices* brokerServices =
- sandbox::SandboxFactory::GetBrokerServices();
- if (!brokerServices) {
- return nullptr;
- }
-
- if (brokerServices->Init() != sandbox::SBOX_ALL_OK) {
- return nullptr;
- }
-
- // Comment below copied from Chromium code.
- // Precreate the desktop and window station used by the renderers.
- // IMPORTANT: This piece of code needs to run as early as possible in the
- // process because it will initialize the sandbox broker, which requires
- // the process to swap its window station. During this time all the UI
- // will be broken. This has to run before threads and windows are created.
- sandbox::TargetPolicy* policy = brokerServices->CreatePolicy();
- sandbox::ResultCode result = policy->CreateAlternateDesktop(true);
- policy->Release();
-
- return brokerServices;
-}
-
-sandbox::BrokerServices*
-GetInitializedBrokerServices()
-{
- static sandbox::BrokerServices* sInitializedBrokerServices =
- InitializeBrokerServices();
-
- return sInitializedBrokerServices;
-}
-
-} // sandboxing
-} // mozilla
diff --git a/security/sandbox/win/SandboxInitialization.h b/security/sandbox/win/SandboxInitialization.h
deleted file mode 100644
index e5be08904..000000000
--- a/security/sandbox/win/SandboxInitialization.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef mozilla_sandboxing_SandboxInitialization_h
-#define mozilla_sandboxing_SandboxInitialization_h
-
-namespace sandbox {
-class BrokerServices;
-class TargetServices;
-}
-
-// Things that use this file will probably want access to the IsSandboxedProcess
-// function defined in one of the Chromium sandbox cc files.
-extern "C" bool IsSandboxedProcess();
-
-namespace mozilla {
-// Note the Chromium code just uses a bare sandbox namespace, which makes using
-// sandbox for our namespace painful.
-namespace sandboxing {
-
-/**
- * Initializes (if required) and returns the Chromium sandbox TargetServices.
- *
- * @return the TargetServices or null if the creation or initialization failed.
- */
-sandbox::TargetServices* GetInitializedTargetServices();
-
-/**
- * Lowers the permissions on the process sandbox.
- * Provided because the GMP sandbox needs to be lowered from the executable.
- */
-void LowerSandbox();
-
-/**
- * Initializes (if required) and returns the Chromium sandbox BrokerServices.
- *
- * @return the BrokerServices or null if the creation or initialization failed.
- */
-sandbox::BrokerServices* GetInitializedBrokerServices();
-
-} // sandboxing
-} // mozilla
-
-#endif // mozilla_sandboxing_SandboxInitialization_h
diff --git a/security/sandbox/win/src/sandboxbroker/moz.build b/security/sandbox/win/src/sandboxbroker/moz.build
deleted file mode 100644
index 4a9d01cc5..000000000
--- a/security/sandbox/win/src/sandboxbroker/moz.build
+++ /dev/null
@@ -1,33 +0,0 @@
-# -*- 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/.
-
-SOURCES += [
- 'sandboxBroker.cpp',
-]
-
-EXPORTS += [
- 'sandboxBroker.h',
-]
-
-for var in ('UNICODE', '_UNICODE', 'SANDBOX_EXPORTS'):
- DEFINES[var] = True
-
-LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
-]
-
-DISABLE_STL_WRAPPING = True
-
-OS_LIBS += [
- 'dbghelp',
-]
-
-if CONFIG['_MSC_VER']:
- CXXFLAGS += [
- '-wd4275', # non dll-interface class exception used as base for dll-interface class
- ]
-
-FINAL_LIBRARY = 'xul'
diff --git a/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp b/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp
deleted file mode 100644
index 10b796268..000000000
--- a/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp
+++ /dev/null
@@ -1,595 +0,0 @@
-/* -*- 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 "sandboxBroker.h"
-
-#include "base/win/windows_version.h"
-#include "mozilla/Assertions.h"
-#include "mozilla/Logging.h"
-#include "sandbox/win/src/sandbox.h"
-#include "sandbox/win/src/security_level.h"
-
-namespace mozilla
-{
-
-sandbox::BrokerServices *SandboxBroker::sBrokerService = nullptr;
-
-static LazyLogModule sSandboxBrokerLog("SandboxBroker");
-
-#define LOG_E(...) MOZ_LOG(sSandboxBrokerLog, LogLevel::Error, (__VA_ARGS__))
-
-/* static */
-void
-SandboxBroker::Initialize(sandbox::BrokerServices* aBrokerServices)
-{
- sBrokerService = aBrokerServices;
-}
-
-SandboxBroker::SandboxBroker()
-{
- if (sBrokerService) {
- mPolicy = sBrokerService->CreatePolicy();
- } else {
- mPolicy = nullptr;
- }
-}
-
-bool
-SandboxBroker::LaunchApp(const wchar_t *aPath,
- const wchar_t *aArguments,
- const bool aEnableLogging,
- void **aProcessHandle)
-{
- if (!sBrokerService || !mPolicy) {
- return false;
- }
-
- // Set stdout and stderr, to allow inheritance for logging.
- mPolicy->SetStdoutHandle(::GetStdHandle(STD_OUTPUT_HANDLE));
- mPolicy->SetStderrHandle(::GetStdHandle(STD_ERROR_HANDLE));
-
- // If logging enabled, set up the policy.
- if (aEnableLogging) {
- ApplyLoggingPolicy();
- }
-
-#if defined(DEBUG)
- // Allow write access to TEMP directory in debug builds for logging purposes.
- // The path from GetTempPathW can have a length up to MAX_PATH + 1, including
- // the null, so we need MAX_PATH + 2, so we can add an * to the end.
- wchar_t tempPath[MAX_PATH + 2];
- uint32_t pathLen = ::GetTempPathW(MAX_PATH + 1, tempPath);
- if (pathLen > 0) {
- // GetTempPath path ends with \ and returns the length without the null.
- tempPath[pathLen] = L'*';
- tempPath[pathLen + 1] = L'\0';
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY, tempPath);
- }
-#endif
-
- // Ceate the sandboxed process
- PROCESS_INFORMATION targetInfo = {0};
- sandbox::ResultCode result;
- result = sBrokerService->SpawnTarget(aPath, aArguments, mPolicy, &targetInfo);
- if (sandbox::SBOX_ALL_OK != result) {
- return false;
- }
-
- // The sandboxed process is started in a suspended state, resume it now that
- // we've set things up.
- ResumeThread(targetInfo.hThread);
- CloseHandle(targetInfo.hThread);
-
- // Return the process handle to the caller
- *aProcessHandle = targetInfo.hProcess;
-
- return true;
-}
-
-#if defined(MOZ_CONTENT_SANDBOX)
-void
-SandboxBroker::SetSecurityLevelForContentProcess(int32_t aSandboxLevel)
-{
- MOZ_RELEASE_ASSERT(mPolicy, "mPolicy must be set before this call.");
-
- sandbox::JobLevel jobLevel;
- sandbox::TokenLevel accessTokenLevel;
- sandbox::IntegrityLevel initialIntegrityLevel;
- sandbox::IntegrityLevel delayedIntegrityLevel;
-
- // The setting of these levels is pretty arbitrary, but they are a useful (if
- // crude) tool while we are tightening the policy. Gaps are left to try and
- // avoid changing their meaning.
- MOZ_RELEASE_ASSERT(aSandboxLevel >= 1, "Should not be called with aSandboxLevel < 1");
- if (aSandboxLevel >= 20) {
- jobLevel = sandbox::JOB_LOCKDOWN;
- accessTokenLevel = sandbox::USER_LOCKDOWN;
- initialIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- delayedIntegrityLevel = sandbox::INTEGRITY_LEVEL_UNTRUSTED;
- } else if (aSandboxLevel >= 10) {
- jobLevel = sandbox::JOB_RESTRICTED;
- accessTokenLevel = sandbox::USER_LIMITED;
- initialIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- delayedIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- } else if (aSandboxLevel >= 2) {
- jobLevel = sandbox::JOB_INTERACTIVE;
- accessTokenLevel = sandbox::USER_INTERACTIVE;
- initialIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- delayedIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- } else if (aSandboxLevel == 1) {
- jobLevel = sandbox::JOB_NONE;
- accessTokenLevel = sandbox::USER_NON_ADMIN;
- initialIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- delayedIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- }
-
- sandbox::ResultCode result = mPolicy->SetJobLevel(jobLevel,
- 0 /* ui_exceptions */);
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "Setting job level failed, have you set memory limit when jobLevel == JOB_NONE?");
-
- // If the delayed access token is not restricted we don't want the initial one
- // to be either, because it can interfere with running from a network drive.
- sandbox::TokenLevel initialAccessTokenLevel =
- (accessTokenLevel == sandbox::USER_UNPROTECTED ||
- accessTokenLevel == sandbox::USER_NON_ADMIN)
- ? sandbox::USER_UNPROTECTED : sandbox::USER_RESTRICTED_SAME_ACCESS;
-
- result = mPolicy->SetTokenLevel(initialAccessTokenLevel, accessTokenLevel);
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "Lockdown level cannot be USER_UNPROTECTED or USER_LAST if initial level was USER_RESTRICTED_SAME_ACCESS");
-
- result = mPolicy->SetIntegrityLevel(initialIntegrityLevel);
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "SetIntegrityLevel should never fail, what happened?");
- result = mPolicy->SetDelayedIntegrityLevel(delayedIntegrityLevel);
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "SetDelayedIntegrityLevel should never fail, what happened?");
-
- if (aSandboxLevel > 2) {
- result = mPolicy->SetAlternateDesktop(true);
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "Failed to create alternate desktop for sandbox.");
- }
-
- sandbox::MitigationFlags mitigations =
- sandbox::MITIGATION_BOTTOM_UP_ASLR |
- sandbox::MITIGATION_HEAP_TERMINATE |
- sandbox::MITIGATION_SEHOP |
- sandbox::MITIGATION_DEP_NO_ATL_THUNK |
- sandbox::MITIGATION_DEP;
-
- result = mPolicy->SetProcessMitigations(mitigations);
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "Invalid flags for SetProcessMitigations.");
-
- mitigations =
- sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
- sandbox::MITIGATION_DLL_SEARCH_ORDER;
-
- result = mPolicy->SetDelayedProcessMitigations(mitigations);
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "Invalid flags for SetDelayedProcessMitigations.");
-
- // Add the policy for the client side of a pipe. It is just a file
- // in the \pipe\ namespace. We restrict it to pipes that start with
- // "chrome." so the sandboxed process cannot connect to system services.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- L"\\??\\pipe\\chrome.*");
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // Add the policy for the client side of the crash server pipe.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- L"\\??\\pipe\\gecko-crash-server-pipe.*");
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // The content process needs to be able to duplicate named pipes back to the
- // broker process, which are File type handles.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
- sandbox::TargetPolicy::HANDLES_DUP_BROKER,
- L"File");
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // The content process needs to be able to duplicate shared memory handles,
- // which are Section handles, to the broker process and other child processes.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
- sandbox::TargetPolicy::HANDLES_DUP_BROKER,
- L"Section");
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "With these static arguments AddRule should never fail, what happened?");
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
- sandbox::TargetPolicy::HANDLES_DUP_ANY,
- L"Section");
- MOZ_RELEASE_ASSERT(sandbox::SBOX_ALL_OK == result,
- "With these static arguments AddRule should never fail, what happened?");
-}
-#endif
-
-#define SANDBOX_ENSURE_SUCCESS(result, message) \
- do { \
- MOZ_ASSERT(sandbox::SBOX_ALL_OK == result, message); \
- if (sandbox::SBOX_ALL_OK != result) \
- return false; \
- } while (0)
-
-bool
-SandboxBroker::SetSecurityLevelForPluginProcess(int32_t aSandboxLevel)
-{
- if (!mPolicy) {
- return false;
- }
-
- sandbox::JobLevel jobLevel;
- sandbox::TokenLevel accessTokenLevel;
- sandbox::IntegrityLevel initialIntegrityLevel;
- sandbox::IntegrityLevel delayedIntegrityLevel;
-
- if (aSandboxLevel > 2) {
- jobLevel = sandbox::JOB_UNPROTECTED;
- accessTokenLevel = sandbox::USER_LIMITED;
- initialIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- delayedIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- } else if (aSandboxLevel == 2) {
- jobLevel = sandbox::JOB_UNPROTECTED;
- accessTokenLevel = sandbox::USER_INTERACTIVE;
- initialIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- delayedIntegrityLevel = sandbox::INTEGRITY_LEVEL_LOW;
- } else {
- jobLevel = sandbox::JOB_NONE;
- accessTokenLevel = sandbox::USER_NON_ADMIN;
- initialIntegrityLevel = sandbox::INTEGRITY_LEVEL_MEDIUM;
- delayedIntegrityLevel = sandbox::INTEGRITY_LEVEL_MEDIUM;
- }
-
- sandbox::ResultCode result = mPolicy->SetJobLevel(jobLevel,
- 0 /* ui_exceptions */);
- SANDBOX_ENSURE_SUCCESS(result,
- "Setting job level failed, have you set memory limit when jobLevel == JOB_NONE?");
-
- result = mPolicy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
- accessTokenLevel);
- SANDBOX_ENSURE_SUCCESS(result,
- "Lockdown level cannot be USER_UNPROTECTED or USER_LAST if initial level was USER_RESTRICTED_SAME_ACCESS");
-
- result = mPolicy->SetIntegrityLevel(initialIntegrityLevel);
- SANDBOX_ENSURE_SUCCESS(result,
- "SetIntegrityLevel should never fail, what happened?");
-
- result = mPolicy->SetDelayedIntegrityLevel(delayedIntegrityLevel);
- SANDBOX_ENSURE_SUCCESS(result,
- "SetDelayedIntegrityLevel should never fail, what happened?");
-
- sandbox::MitigationFlags mitigations =
- sandbox::MITIGATION_BOTTOM_UP_ASLR |
- sandbox::MITIGATION_HEAP_TERMINATE |
- sandbox::MITIGATION_SEHOP |
- sandbox::MITIGATION_DEP_NO_ATL_THUNK |
- sandbox::MITIGATION_DEP;
-
- result = mPolicy->SetProcessMitigations(mitigations);
- SANDBOX_ENSURE_SUCCESS(result,
- "Invalid flags for SetProcessMitigations.");
-
- // Add the policy for the client side of a pipe. It is just a file
- // in the \pipe\ namespace. We restrict it to pipes that start with
- // "chrome." so the sandboxed process cannot connect to system services.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- L"\\??\\pipe\\chrome.*");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // Add the policy for the client side of the crash server pipe.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- L"\\??\\pipe\\gecko-crash-server-pipe.*");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // The NPAPI process needs to be able to duplicate shared memory to the
- // content process and broker process, which are Section type handles.
- // Content and broker are for e10s and non-e10s cases.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
- sandbox::TargetPolicy::HANDLES_DUP_ANY,
- L"Section");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
- sandbox::TargetPolicy::HANDLES_DUP_BROKER,
- L"Section");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // The following is required for the Java plugin.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- L"\\??\\pipe\\jpi2_pid*_pipe*");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // These register keys are used by the file-browser dialog box. They
- // remember the most-recently-used folders.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_ANY,
- L"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSavePidlMRU\\*");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_ANY,
- L"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\LastVisitedPidlMRULegacy\\*");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- return true;
-}
-
-bool
-SandboxBroker::SetSecurityLevelForGMPlugin(SandboxLevel aLevel)
-{
- if (!mPolicy) {
- return false;
- }
-
- auto result = mPolicy->SetJobLevel(sandbox::JOB_LOCKDOWN, 0);
- SANDBOX_ENSURE_SUCCESS(result,
- "SetJobLevel should never fail with these arguments, what happened?");
- auto level = (aLevel == Restricted) ?
- sandbox::USER_RESTRICTED : sandbox::USER_LOCKDOWN;
- result = mPolicy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, level);
- SANDBOX_ENSURE_SUCCESS(result,
- "SetTokenLevel should never fail with these arguments, what happened?");
-
- result = mPolicy->SetAlternateDesktop(true);
- SANDBOX_ENSURE_SUCCESS(result,
- "Failed to create alternate desktop for sandbox.");
-
- result = mPolicy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
- MOZ_ASSERT(sandbox::SBOX_ALL_OK == result,
- "SetIntegrityLevel should never fail with these arguments, what happened?");
-
- result =
- mPolicy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED);
- SANDBOX_ENSURE_SUCCESS(result,
- "SetIntegrityLevel should never fail with these arguments, what happened?");
-
- sandbox::MitigationFlags mitigations =
- sandbox::MITIGATION_BOTTOM_UP_ASLR |
- sandbox::MITIGATION_HEAP_TERMINATE |
- sandbox::MITIGATION_SEHOP |
- sandbox::MITIGATION_DEP_NO_ATL_THUNK |
- sandbox::MITIGATION_DEP;
-
- result = mPolicy->SetProcessMitigations(mitigations);
- SANDBOX_ENSURE_SUCCESS(result,
- "Invalid flags for SetProcessMitigations.");
-
- mitigations =
- sandbox::MITIGATION_STRICT_HANDLE_CHECKS |
- sandbox::MITIGATION_DLL_SEARCH_ORDER;
-
- result = mPolicy->SetDelayedProcessMitigations(mitigations);
- SANDBOX_ENSURE_SUCCESS(result,
- "Invalid flags for SetDelayedProcessMitigations.");
-
- // Add the policy for the client side of a pipe. It is just a file
- // in the \pipe\ namespace. We restrict it to pipes that start with
- // "chrome." so the sandboxed process cannot connect to system services.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- L"\\??\\pipe\\chrome.*");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // Add the policy for the client side of the crash server pipe.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- L"\\??\\pipe\\gecko-crash-server-pipe.*");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
-#ifdef DEBUG
- // The plugin process can't create named events, but we'll
- // make an exception for the events used in logging. Removing
- // this will break EME in debug builds.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_SYNC,
- sandbox::TargetPolicy::EVENTS_ALLOW_ANY,
- L"ChromeIPCLog.*");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-#endif
-
- // The following rules were added because, during analysis of an EME
- // plugin during development, these registry keys were accessed when
- // loading the plugin. Commenting out these policy exceptions caused
- // plugin loading to fail, so they are necessary for proper functioning
- // of at least one EME plugin.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_CURRENT_USER");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_CURRENT_USER\\Control Panel\\Desktop");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_CURRENT_USER\\Control Panel\\Desktop\\LanguageConfiguration");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\SideBySide");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
-
- // The following rules were added because, during analysis of an EME
- // plugin during development, these registry keys were accessed when
- // loading the plugin. Commenting out these policy exceptions did not
- // cause anything to break during initial testing, but might cause
- // unforeseen issues down the road.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE\\SOFTWARE\\Policies\\Microsoft\\MUI\\Settings");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_CURRENT_USER\\Software\\Policies\\Microsoft\\Control Panel\\Desktop");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_CURRENT_USER\\Control Panel\\Desktop\\PreferredUILanguages");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\SideBySide\\PreferExternalManifest");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
- // The following rules were added to allow a GMP to be loaded when any
- // AppLocker DLL rules are specified. If the rules specifically block the DLL
- // then it will not load.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_READONLY,
- L"\\Device\\SrpDevice");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Srp\\GP\\");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
- // On certain Windows versions there is a double slash before GP in the path.
- result = mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Srp\\\\GP\\");
- SANDBOX_ENSURE_SUCCESS(result,
- "With these static arguments AddRule should never fail, what happened?");
-
-
- return true;
-}
-#undef SANDBOX_ENSURE_SUCCESS
-
-bool
-SandboxBroker::AllowReadFile(wchar_t const *file)
-{
- if (!mPolicy) {
- return false;
- }
-
- auto result =
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_READONLY,
- file);
- if (sandbox::SBOX_ALL_OK != result) {
- LOG_E("Failed (ResultCode %d) to add read access to: %S", result, file);
- return false;
- }
-
- return true;
-}
-
-bool
-SandboxBroker::AllowReadWriteFile(wchar_t const *file)
-{
- if (!mPolicy) {
- return false;
- }
-
- auto result =
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_ANY,
- file);
- if (sandbox::SBOX_ALL_OK != result) {
- LOG_E("Failed (ResultCode %d) to add read/write access to: %S",
- result, file);
- return false;
- }
-
- return true;
-}
-
-bool
-SandboxBroker::AllowDirectory(wchar_t const *dir)
-{
- if (!mPolicy) {
- return false;
- }
-
- auto result =
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_FILES,
- sandbox::TargetPolicy::FILES_ALLOW_DIR_ANY,
- dir);
- if (sandbox::SBOX_ALL_OK != result) {
- LOG_E("Failed (ResultCode %d) to add directory access to: %S", result, dir);
- return false;
- }
-
- return true;
-}
-
-bool
-SandboxBroker::AddTargetPeer(HANDLE aPeerProcess)
-{
- if (!sBrokerService) {
- return false;
- }
-
- sandbox::ResultCode result = sBrokerService->AddTargetPeer(aPeerProcess);
- return (sandbox::SBOX_ALL_OK == result);
-}
-
-void
-SandboxBroker::ApplyLoggingPolicy()
-{
- MOZ_ASSERT(mPolicy);
-
- // Add dummy rules, so that we can log in the interception code.
- // We already have a file interception set up for the client side of pipes.
- // Also, passing just "dummy" for file system policy causes win_utils.cc
- // IsReparsePoint() to loop.
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
- sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY, L"dummy");
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_PROCESS,
- sandbox::TargetPolicy::PROCESS_MIN_EXEC, L"dummy");
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_REGISTRY,
- sandbox::TargetPolicy::REG_ALLOW_READONLY,
- L"HKEY_CURRENT_USER\\dummy");
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_SYNC,
- sandbox::TargetPolicy::EVENTS_ALLOW_READONLY, L"dummy");
- mPolicy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
- sandbox::TargetPolicy::HANDLES_DUP_BROKER, L"dummy");
-}
-
-SandboxBroker::~SandboxBroker()
-{
- if (mPolicy) {
- mPolicy->Release();
- mPolicy = nullptr;
- }
-}
-
-}
diff --git a/security/sandbox/win/src/sandboxbroker/sandboxBroker.h b/security/sandbox/win/src/sandboxbroker/sandboxBroker.h
deleted file mode 100644
index 3f73ec890..000000000
--- a/security/sandbox/win/src/sandboxbroker/sandboxBroker.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef __SECURITY_SANDBOX_SANDBOXBROKER_H__
-#define __SECURITY_SANDBOX_SANDBOXBROKER_H__
-
-#include <stdint.h>
-#include <windows.h>
-
-namespace sandbox {
- class BrokerServices;
- class TargetPolicy;
-}
-
-namespace mozilla {
-
-class SandboxBroker
-{
-public:
- SandboxBroker();
-
- static void Initialize(sandbox::BrokerServices* aBrokerServices);
-
- bool LaunchApp(const wchar_t *aPath,
- const wchar_t *aArguments,
- const bool aEnableLogging,
- void **aProcessHandle);
- virtual ~SandboxBroker();
-
- // Security levels for different types of processes
-#if defined(MOZ_CONTENT_SANDBOX)
- void SetSecurityLevelForContentProcess(int32_t aSandboxLevel);
-#endif
- bool SetSecurityLevelForPluginProcess(int32_t aSandboxLevel);
- enum SandboxLevel {
- LockDown,
- Restricted
- };
- bool SetSecurityLevelForGMPlugin(SandboxLevel aLevel);
-
- // File system permissions
- bool AllowReadFile(wchar_t const *file);
- bool AllowReadWriteFile(wchar_t const *file);
- bool AllowDirectory(wchar_t const *dir);
-
- // Exposes AddTargetPeer from broker services, so that none sandboxed
- // processes can be added as handle duplication targets.
- bool AddTargetPeer(HANDLE aPeerProcess);
-
- // Set up dummy interceptions via the broker, so we can log calls.
- void ApplyLoggingPolicy();
-
-private:
- static sandbox::BrokerServices *sBrokerService;
- sandbox::TargetPolicy *mPolicy;
-};
-
-} // mozilla
-
-#endif
diff --git a/security/sandbox/win/src/sandboxtarget/moz.build b/security/sandbox/win/src/sandboxtarget/moz.build
deleted file mode 100644
index 7315a34ed..000000000
--- a/security/sandbox/win/src/sandboxtarget/moz.build
+++ /dev/null
@@ -1,20 +0,0 @@
-# -*- 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 += [
- 'sandboxTarget.h',
-]
-
-SOURCES += [
- 'sandboxTarget.cpp',
-]
-
-LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
-]
-
-FINAL_LIBRARY = 'xul'
diff --git a/security/sandbox/win/src/sandboxtarget/sandboxTarget.cpp b/security/sandbox/win/src/sandboxtarget/sandboxTarget.cpp
deleted file mode 100644
index a989b3625..000000000
--- a/security/sandbox/win/src/sandboxtarget/sandboxTarget.cpp
+++ /dev/null
@@ -1,21 +0,0 @@
-/* -*- 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/. */
-
-#define TARGET_SANDBOX_EXPORTS
-#include "sandboxTarget.h"
-
-namespace mozilla {
-
-// We need to define this function out of line so that clang-cl doesn't inline
-// it.
-/* static */ SandboxTarget*
-SandboxTarget::Instance()
-{
- static SandboxTarget sb;
- return &sb;
-}
-
-}
diff --git a/security/sandbox/win/src/sandboxtarget/sandboxTarget.h b/security/sandbox/win/src/sandboxtarget/sandboxTarget.h
deleted file mode 100644
index f46a2ce70..000000000
--- a/security/sandbox/win/src/sandboxtarget/sandboxTarget.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/* -*- 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 __SECURITY_SANDBOX_SANDBOXTARGET_H__
-#define __SECURITY_SANDBOX_SANDBOXTARGET_H__
-
-#include <windows.h>
-
-#include "mozilla/Assertions.h"
-#include "base/MissingBasicTypes.h"
-#include "sandbox/win/src/sandbox.h"
-
-namespace mozilla {
-
-class SandboxTarget
-{
-public:
- /**
- * Obtains a pointer to the singleton instance
- */
- static SandboxTarget* Instance();
-
- /**
- * Used by the application to pass in the target services that provide certain
- * functions to the sandboxed code.
- * The target services must already be initialized.
- *
- * @param aTargetServices The target services that will be used
- */
- void SetTargetServices(sandbox::TargetServices* aTargetServices)
- {
- MOZ_ASSERT(aTargetServices);
- MOZ_ASSERT(!mTargetServices,
- "Sandbox TargetServices must only be set once.");
-
- mTargetServices = aTargetServices;
- }
-
- /**
- * Called by the library that wants to "start" the sandbox, i.e. change to the
- * more secure delayed / lockdown policy.
- */
- void StartSandbox()
- {
- if (mTargetServices) {
- mTargetServices->LowerToken();
- }
- }
-
- /**
- * Used to duplicate handles via the broker process. The permission for the
- * handle type and target process has to have been set on the sandbox policy.
- */
- bool BrokerDuplicateHandle(HANDLE aSourceHandle, DWORD aTargetProcessId,
- HANDLE* aTargetHandle, DWORD aDesiredAccess,
- DWORD aOptions)
- {
- if (!mTargetServices) {
- return false;
- }
-
- sandbox::ResultCode result =
- mTargetServices->DuplicateHandle(aSourceHandle, aTargetProcessId,
- aTargetHandle, aDesiredAccess, aOptions);
- return (sandbox::SBOX_ALL_OK == result);
- }
-
-protected:
- SandboxTarget() :
- mTargetServices(nullptr)
- {
- }
-
- sandbox::TargetServices* mTargetServices;
-};
-
-
-} // mozilla
-
-#endif
diff --git a/security/sandbox/win/wow_helper/Makefile.in b/security/sandbox/win/wow_helper/Makefile.in
deleted file mode 100644
index aee81f3fe..000000000
--- a/security/sandbox/win/wow_helper/Makefile.in
+++ /dev/null
@@ -1,47 +0,0 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-
-# We need to build a 64-bits binary during a 32-bits build. This requires
-# a different compiler and different library paths. Until the build system
-# supports this natively.
-
-# Some Make magic to avoid CXX and LIB being evaluated when nothing
-# is built in this directory
-lazy = $(if $(___$(1)),,$(eval ___$(1) := $(2)))$(___$(1))
-
-# We could use the `which` python module, but it needs more code to handle
-# the situation where CXX points to an absolute path. But using the shell
-# which returns a msys path, while we need a windows path. So force msys
-# to do the conversion for us by calling python with an environment variable
-# with the result of the call to `which`. Then munge that path to add the
-# x64 cross-compiler path.
-ifdef MOZ_USING_COMPILER_WRAPPER
-ORIG_CXX := cl
-else
-ORIG_CXX := $(CXX)
-endif
-CXX = $(call lazy,CXX,"$$(subst amd64_x86/x86_amd64/,amd64/,$$(shell CL=`which "$(ORIG_CXX)"` $(PYTHON) -c 'import os; print os.path.dirname(os.environ["CL"])')/x86_amd64/cl.exe)")
-
-MOZ_WINCONSOLE = 0
-
-include $(topsrcdir)/config/config.mk
-
-# Munge the LIB variable to contain paths to the x64 CRT and system libraries.
-# Unconveniently, none of the paths have the same convention, including the
-# compiler path above.
-LIB = $(call lazy,LIB,$$(shell python -c 'import os; print ";".join(s.lower().replace(os.sep, "/").replace("/vc/lib", "/vc/lib/amd64").replace("/um/x86", "/um/x64").replace("/ucrt/x86", "/ucrt/x64") for s in os.environ["LIB"].split(";"))'))
-
-CXXFLAGS := $(filter-out -arch:%,$(CXXFLAGS))
-
-# OS_COMPILE_CXXFLAGS includes mozilla-config.h, which contains x86-specific
-# defines breaking the build.
-OS_COMPILE_CXXFLAGS :=
-
-# LNK1246: '/SAFESEH' not compatible with 'x64' target machine
-LDFLAGS := $(filter-out -SAFESEH,$(LDFLAGS))
-
-# When targetting x64, we need to specify a subsystem of at least 5.02, because
-# the 5.01 value we inherit from the x86 parts is silently ignored, making the
-# linker default to 6.00 (Vista) as of VS2013.
-WIN32_GUI_EXE_LDFLAGS=-SUBSYSTEM:WINDOWS,5.02
diff --git a/security/sandbox/win/wow_helper/moz.build b/security/sandbox/win/wow_helper/moz.build
deleted file mode 100644
index d9c307def..000000000
--- a/security/sandbox/win/wow_helper/moz.build
+++ /dev/null
@@ -1,30 +0,0 @@
-# -*- 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/.
-
-Program('wow_helper')
-
-SOURCES += [ '../../chromium/sandbox/win/wow_helper/' + f for f in (
- 'service64_resolver.cc',
- 'target_code.cc',
- 'wow_helper.cc',
-)]
-
-LOCAL_INCLUDES += [
- '../../',
- '../../../',
- '../../chromium/',
-]
-
-DISABLE_STL_WRAPPING = True
-
-DEFINES['UNICODE'] = True
-
-USE_STATIC_LIBS = True
-
-# The rules in Makefile.in only force the use of the 64-bits compiler, not
-# the 64-bits linker, and the 32-bits linker can't do 64-bits compilation for
-# PGO, so disable PGO, which is not interesting for this small binary anyways.
-NO_PGO = True
diff --git a/services/fxaccounts/FxAccountsManager.jsm b/services/fxaccounts/FxAccountsManager.jsm
deleted file mode 100644
index 680310ff5..000000000
--- a/services/fxaccounts/FxAccountsManager.jsm
+++ /dev/null
@@ -1,654 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/**
- * Temporary abstraction layer for common Fx Accounts operations.
- * For now, we will be using this module only from B2G but in the end we might
- * want this to be merged with FxAccounts.jsm and let other products also use
- * it.
- */
-
-"use strict";
-
-this.EXPORTED_SYMBOLS = ["FxAccountsManager"];
-
-const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
-
-Cu.import("resource://gre/modules/XPCOMUtils.jsm");
-Cu.import("resource://gre/modules/Services.jsm");
-Cu.import("resource://gre/modules/FxAccounts.jsm");
-Cu.import("resource://gre/modules/Promise.jsm");
-Cu.import("resource://gre/modules/FxAccountsCommon.js");
-
-XPCOMUtils.defineLazyServiceGetter(this, "permissionManager",
- "@mozilla.org/permissionmanager;1",
- "nsIPermissionManager");
-
-this.FxAccountsManager = {
-
- init: function() {
- Services.obs.addObserver(this, ONLOGOUT_NOTIFICATION, false);
- Services.obs.addObserver(this, ON_FXA_UPDATE_NOTIFICATION, false);
- },
-
- observe: function(aSubject, aTopic, aData) {
- // Both topics indicate our cache is invalid
- this._activeSession = null;
-
- if (aData == ONVERIFIED_NOTIFICATION) {
- log.debug("FxAccountsManager: cache cleared, broadcasting: " + aData);
- Services.obs.notifyObservers(null, aData, null);
- }
- },
-
- // We don't really need to save fxAccounts instance but this way we allow
- // to mock FxAccounts from tests.
- _fxAccounts: fxAccounts,
-
- // We keep the session details here so consumers don't need to deal with
- // session tokens and are only required to handle the email.
- _activeSession: null,
-
- // Are we refreshing our authentication? If so, allow attempts to sign in
- // while we are already signed in.
- _refreshing: false,
-
- // We only expose the email and the verified status so far.
- get _user() {
- if (!this._activeSession || !this._activeSession.email) {
- return null;
- }
-
- return {
- email: this._activeSession.email,
- verified: this._activeSession.verified,
- profile: this._activeSession.profile,
- }
- },
-
- _error: function(aError, aDetails) {
- log.error(aError);
- let reason = {
- error: aError
- };
- if (aDetails) {
- reason.details = aDetails;
- }
- return Promise.reject(reason);
- },
-
- _getError: function(aServerResponse) {
- if (!aServerResponse || !aServerResponse.error || !aServerResponse.error.errno) {
- return;
- }
- let error = SERVER_ERRNO_TO_ERROR[aServerResponse.error.errno];
- return error;
- },
-
- _serverError: function(aServerResponse) {
- let error = this._getError({ error: aServerResponse });
- return this._error(error ? error : ERROR_SERVER_ERROR, aServerResponse);
- },
-
- // As with _fxAccounts, we don't really need this method, but this way we
- // allow tests to mock FxAccountsClient. By default, we want to return the
- // client used by the fxAccounts object because deep down they should have
- // access to the same hawk request object which will enable them to share
- // local clock skeq data.
- _getFxAccountsClient: function() {
- return this._fxAccounts.getAccountsClient();
- },
-
- _signInSignUp: function(aMethod, aEmail, aPassword, aFetchKeys) {
- if (Services.io.offline) {
- return this._error(ERROR_OFFLINE);
- }
-
- if (!aEmail) {
- return this._error(ERROR_INVALID_EMAIL);
- }
-
- if (!aPassword) {
- return this._error(ERROR_INVALID_PASSWORD);
- }
-
- // Check that there is no signed in account first.
- if ((!this._refreshing) && this._activeSession) {
- return this._error(ERROR_ALREADY_SIGNED_IN_USER, {
- user: this._user
- });
- }
-
- let client = this._getFxAccountsClient();
- return this._fxAccounts.getSignedInUser().then(
- user => {
- if ((!this._refreshing) && user) {
- return this._error(ERROR_ALREADY_SIGNED_IN_USER, {
- user: this._user
- });
- }
- return client[aMethod](aEmail, aPassword, aFetchKeys);
- }
- ).then(
- user => {
- let error = this._getError(user);
- if (!user || !user.uid || !user.sessionToken || error) {
- return this._error(error ? error : ERROR_INTERNAL_INVALID_USER, {
- user: user
- });
- }
-
- // If the user object includes an email field, it may differ in
- // capitalization from what we sent down. This is the server's
- // canonical capitalization and should be used instead.
- user.email = user.email || aEmail;
-
- // If we're using server-side sign to refreshAuthentication
- // we don't need to update local state; also because of two
- // interacting glitches we need to bypass an event emission.
- // See https://bugzilla.mozilla.org/show_bug.cgi?id=1031580
- if (this._refreshing) {
- return Promise.resolve({user: this._user});
- }
-
- return this._fxAccounts.setSignedInUser(user).then(
- () => {
- this._activeSession = user;
- log.debug("User signed in: " + JSON.stringify(this._user) +
- " - Account created " + (aMethod == "signUp"));
-
- // There is no way to obtain the key fetch token afterwards
- // without login out the user and asking her to log in again.
- // Also, key fetch tokens are designed to be short-lived, so
- // we need to fetch kB as soon as we have the key fetch token.
- if (aFetchKeys) {
- this._fxAccounts.getKeys();
- }
-
- return this._fxAccounts.getSignedInUserProfile().catch(error => {
- // Not fetching the profile is sad but the FxA logs will already
- // have noise.
- return null;
- });
- }
- ).then(profile => {
- if (profile) {
- this._activeSession.profile = profile;
- }
-
- return Promise.resolve({
- accountCreated: aMethod === "signUp",
- user: this._user
- });
- });
- },
- reason => { return this._serverError(reason); }
- );
- },
-
- /**
- * Determine whether the incoming error means that the current account
- * has new server-side state via deletion or password change, and if so,
- * spawn the appropriate UI (sign in or refresh); otherwise re-reject.
- *
- * As of May 2014, the only HTTP call triggered by this._getAssertion()
- * is to /certificate/sign via:
- * FxAccounts.getAssertion()
- * FxAccountsInternal.getCertificateSigned()
- * FxAccountsClient.signCertificate()
- * See the latter method for possible (error code, errno) pairs.
- */
- _handleGetAssertionError: function(reason, aAudience, aPrincipal) {
- log.debug("FxAccountsManager._handleGetAssertionError()");
- let errno = (reason ? reason.errno : NaN) || NaN;
- // If the previously valid email/password pair is no longer valid ...
- if (errno == ERRNO_INVALID_AUTH_TOKEN) {
- return this._fxAccounts.accountStatus().then(
- (exists) => {
- // ... if the email still maps to an account, the password
- // must have changed, so ask the user to enter the new one ...
- if (exists) {
- return this.getAccount().then(
- (user) => {
- return this._refreshAuthentication(aAudience, user.email,
- aPrincipal,
- true /* logoutOnFailure */);
- }
- );
- }
- // ... otherwise, the account was deleted, so ask for Sign In/Up
- return this._localSignOut().then(
- () => {
- return this._uiRequest(UI_REQUEST_SIGN_IN_FLOW, aAudience,
- aPrincipal);
- },
- (reason) => {
- // reject primary problem, not signout failure
- log.error("Signing out in response to server error threw: " +
- reason);
- return this._error(reason);
- }
- );
- }
- );
- }
- return Promise.reject(reason.message ? { error: reason.message } : reason);
- },
-
- _getAssertion: function(aAudience, aPrincipal) {
- return this._fxAccounts.getAssertion(aAudience).then(
- (result) => {
- if (aPrincipal) {
- this._addPermission(aPrincipal);
- }
- return result;
- },
- (reason) => {
- return this._handleGetAssertionError(reason, aAudience, aPrincipal);
- }
- );
- },
-
- /**
- * "Refresh authentication" means:
- * Interactively demonstrate knowledge of the FxA password
- * for the currently logged-in account.
- * There are two very different scenarios:
- * 1) The password has changed on the server. Failure should log
- * the current account OUT.
- * 2) The person typing can't prove knowledge of the password used
- * to log in. Failure should do nothing.
- */
- _refreshAuthentication: function(aAudience, aEmail, aPrincipal,
- logoutOnFailure=false) {
- this._refreshing = true;
- return this._uiRequest(UI_REQUEST_REFRESH_AUTH,
- aAudience, aPrincipal, aEmail).then(
- (assertion) => {
- this._refreshing = false;
- return assertion;
- },
- (reason) => {
- this._refreshing = false;
- if (logoutOnFailure) {
- return this._signOut().then(
- () => {
- return this._error(reason);
- }
- );
- }
- return this._error(reason);
- }
- );
- },
-
- _localSignOut: function() {
- return this._fxAccounts.signOut(true);
- },
-
- _signOut: function() {
- if (!this._activeSession) {
- return Promise.resolve();
- }
-
- // We clear the local session cache as soon as we get the onlogout
- // notification triggered within FxAccounts.signOut, so we save the
- // session token value to be able to remove the remote server session
- // in case that we have network connection.
- let sessionToken = this._activeSession.sessionToken;
-
- return this._localSignOut().then(
- () => {
- // At this point the local session should already be removed.
-
- // The client can create new sessions up to the limit (100?).
- // Orphaned tokens on the server will eventually be garbage collected.
- if (Services.io.offline) {
- return Promise.resolve();
- }
- // Otherwise, we try to remove the remote session.
- let client = this._getFxAccountsClient();
- return client.signOut(sessionToken).then(
- result => {
- let error = this._getError(result);
- if (error) {
- return this._error(error, result);
- }
- log.debug("Signed out");
- return Promise.resolve();
- },
- reason => {
- return this._serverError(reason);
- }
- );
- }
- );
- },
-
- _uiRequest: function(aRequest, aAudience, aPrincipal, aParams) {
- if (Services.io.offline) {
- return this._error(ERROR_OFFLINE);
- }
- let ui = Cc["@mozilla.org/fxaccounts/fxaccounts-ui-glue;1"]
- .createInstance(Ci.nsIFxAccountsUIGlue);
- if (!ui[aRequest]) {
- return this._error(ERROR_UI_REQUEST);
- }
-
- if (!aParams || !Array.isArray(aParams)) {
- aParams = [aParams];
- }
-
- return ui[aRequest].apply(this, aParams).then(
- result => {
- // Even if we get a successful result from the UI, the account will
- // most likely be unverified, so we cannot get an assertion.
- if (result && result.verified) {
- return this._getAssertion(aAudience, aPrincipal);
- }
-
- return this._error(ERROR_UNVERIFIED_ACCOUNT, {
- user: result
- });
- },
- error => {
- return this._error(ERROR_UI_ERROR, error);
- }
- );
- },
-
- _addPermission: function(aPrincipal) {
- // This will fail from tests cause we are running them in the child
- // process until we have chrome tests in b2g. Bug 797164.
- try {
- permissionManager.addFromPrincipal(aPrincipal, FXACCOUNTS_PERMISSION,
- Ci.nsIPermissionManager.ALLOW_ACTION);
- } catch (e) {
- log.warn("Could not add permission " + e);
- }
- },
-
- // -- API --
-
- signIn: function(aEmail, aPassword, aFetchKeys) {
- return this._signInSignUp("signIn", aEmail, aPassword, aFetchKeys);
- },
-
- signUp: function(aEmail, aPassword, aFetchKeys) {
- return this._signInSignUp("signUp", aEmail, aPassword, aFetchKeys);
- },
-
- signOut: function() {
- if (!this._activeSession) {
- // If there is no cached active session, we try to get it from the
- // account storage.
- return this.getAccount().then(
- result => {
- if (!result) {
- return Promise.resolve();
- }
- return this._signOut();
- }
- );
- }
- return this._signOut();
- },
-
- resendVerificationEmail: function() {
- return this._fxAccounts.resendVerificationEmail().then(
- (result) => {
- return result;
- },
- (error) => {
- return this._error(ERROR_SERVER_ERROR, error);
- }
- );
- },
-
- getAccount: function() {
- // We check first if we have session details cached.
- if (this._activeSession) {
- // If our cache says that the account is not yet verified,
- // we kick off verification before returning what we have.
- if (!this._activeSession.verified) {
- this.verificationStatus(this._activeSession);
- }
- log.debug("Account " + JSON.stringify(this._user));
- return Promise.resolve(this._user);
- }
-
- // If no cached information, we try to get it from the persistent storage.
- return this._fxAccounts.getSignedInUser().then(
- user => {
- if (!user || !user.email) {
- log.debug("No signed in account");
- return Promise.resolve(null);
- }
-
- this._activeSession = user;
- // If we get a stored information of a not yet verified account,
- // we kick off verification before returning what we have.
- if (!user.verified) {
- this.verificationStatus(user);
- // Trying to get the profile for unverified users will fail, so we
- // don't even try in that case.
- log.debug("Account ", this._user);
- return Promise.resolve(this._user);
- }
-
- return this._fxAccounts.getSignedInUserProfile().then(profile => {
- if (profile) {
- this._activeSession.profile = profile;
- }
- log.debug("Account ", this._user);
- return Promise.resolve(this._user);
- }).catch(error => {
- // FxAccounts logs already inform about the error.
- log.debug("Account ", this._user);
- return Promise.resolve(this._user);
- });
- }
- );
- },
-
- queryAccount: function(aEmail) {
- log.debug("queryAccount " + aEmail);
- if (Services.io.offline) {
- return this._error(ERROR_OFFLINE);
- }
-
- let deferred = Promise.defer();
-
- if (!aEmail) {
- return this._error(ERROR_INVALID_EMAIL);
- }
-
- let client = this._getFxAccountsClient();
- return client.accountExists(aEmail).then(
- result => {
- log.debug("Account " + result ? "" : "does not" + " exists");
- let error = this._getError(result);
- if (error) {
- return this._error(error, result);
- }
-
- return Promise.resolve({
- registered: result
- });
- },
- reason => { this._serverError(reason); }
- );
- },
-
- verificationStatus: function() {
- log.debug("verificationStatus");
- if (!this._activeSession || !this._activeSession.sessionToken) {
- this._error(ERROR_NO_TOKEN_SESSION);
- }
-
- // There is no way to unverify an already verified account, so we just
- // return the account details of a verified account
- if (this._activeSession.verified) {
- log.debug("Account already verified");
- return;
- }
-
- if (Services.io.offline) {
- log.warn("Offline; skipping verification.");
- return;
- }
-
- let client = this._getFxAccountsClient();
- client.recoveryEmailStatus(this._activeSession.sessionToken).then(
- data => {
- let error = this._getError(data);
- if (error) {
- this._error(error, data);
- }
- // If the verification status has changed, update state.
- if (this._activeSession.verified != data.verified) {
- this._activeSession.verified = data.verified;
- this._fxAccounts.setSignedInUser(this._activeSession);
- this._fxAccounts.getSignedInUserProfile().then(profile => {
- if (profile) {
- this._activeSession.profile = profile;
- }
- }).catch(error => {
- // FxAccounts logs already inform about the error.
- });
- }
- log.debug(JSON.stringify(this._user));
- },
- reason => { this._serverError(reason); }
- );
- },
-
- /*
- * Try to get an assertion for the given audience. Here we implement
- * the heart of the response to navigator.mozId.request() on device.
- * (We can also be called via the IAC API, but it's request() that
- * makes this method complex.) The state machine looks like this,
- * ignoring simple errors:
- * If no one is signed in, and we aren't suppressing the UI:
- * trigger the sign in flow.
- * else if we were asked to refresh and the grace period is up:
- * trigger the refresh flow.
- * else:
- * request user permission to share an assertion if we don't have it
- * already and ask the core code for an assertion, which might itself
- * trigger either the sign in or refresh flows (if our account
- * changed on the server).
- *
- * aOptions can include:
- * refreshAuthentication - (bool) Force re-auth.
- * silent - (bool) Prevent any UI interaction.
- * I.e., try to get an automatic assertion.
- */
- getAssertion: function(aAudience, aPrincipal, aOptions) {
- if (!aAudience) {
- return this._error(ERROR_INVALID_AUDIENCE);
- }
-
- let principal = aPrincipal;
- log.debug("FxAccountsManager.getAssertion() aPrincipal: ",
- principal.origin, principal.appId,
- principal.isInIsolatedMozBrowserElement);
-
- return this.getAccount().then(
- user => {
- if (user) {
- // Three have-user cases to consider. First: are we unverified?
- if (!user.verified) {
- return this._error(ERROR_UNVERIFIED_ACCOUNT, {
- user: user
- });
- }
- // Second case: do we need to refresh?
- if (aOptions &&
- (typeof(aOptions.refreshAuthentication) != "undefined")) {
- let gracePeriod = aOptions.refreshAuthentication;
- if (typeof(gracePeriod) !== "number" || isNaN(gracePeriod)) {
- return this._error(ERROR_INVALID_REFRESH_AUTH_VALUE);
- }
- // Forcing refreshAuth to silent is a contradiction in terms,
- // though it might succeed silently if we didn't reject here.
- if (aOptions.silent) {
- return this._error(ERROR_NO_SILENT_REFRESH_AUTH);
- }
- let secondsSinceAuth = (Date.now() / 1000) -
- this._activeSession.authAt;
- if (secondsSinceAuth > gracePeriod) {
- return this._refreshAuthentication(aAudience, user.email,
- principal,
- false /* logoutOnFailure */);
- }
- }
- // Third case: we are all set *locally*. Probably we just return
- // the assertion, but the attempt might lead to the server saying
- // we are deleted or have a new password, which will trigger a flow.
- // Also we need to check if we have permission to get the assertion,
- // otherwise we need to show the forceAuth UI to let the user know
- // that the RP with no fxa permissions is trying to obtain an
- // assertion. Once the user authenticates herself in the forceAuth UI
- // the permission will be remembered by default.
- let permission = permissionManager.testPermissionFromPrincipal(
- principal,
- FXACCOUNTS_PERMISSION
- );
- if (permission == Ci.nsIPermissionManager.PROMPT_ACTION &&
- !this._refreshing) {
- return this._refreshAuthentication(aAudience, user.email,
- principal,
- false /* logoutOnFailure */);
- } else if (permission == Ci.nsIPermissionManager.DENY_ACTION &&
- !this._refreshing) {
- return this._error(ERROR_PERMISSION_DENIED);
- } else if (this._refreshing) {
- // If we are blocked asking for a password we should not continue
- // the getAssertion process.
- return Promise.resolve(null);
- }
- return this._getAssertion(aAudience, principal);
- }
- log.debug("No signed in user");
- if (aOptions && aOptions.silent) {
- return Promise.resolve(null);
- }
- return this._uiRequest(UI_REQUEST_SIGN_IN_FLOW, aAudience, principal);
- }
- );
- },
-
- getKeys: function() {
- let syncEnabled = false;
- try {
- syncEnabled = Services.prefs.getBoolPref("services.sync.enabled");
- } catch(e) {
- dump("Sync is disabled, so you won't get the keys. " + e + "\n");
- }
-
- if (!syncEnabled) {
- return Promise.reject(ERROR_SYNC_DISABLED);
- }
-
- return this.getAccount().then(
- user => {
- if (!user) {
- log.debug("No signed in user");
- return Promise.resolve(null);
- }
-
- if (!user.verified) {
- return this._error(ERROR_UNVERIFIED_ACCOUNT, {
- user: user
- });
- }
-
- return this._fxAccounts.getKeys();
- }
- );
- }
-};
-
-FxAccountsManager.init();
diff --git a/services/fxaccounts/FxAccountsProfileClient.jsm b/services/fxaccounts/FxAccountsProfileClient.jsm
index 37115a3fa..1e5edc634 100644
--- a/services/fxaccounts/FxAccountsProfileClient.jsm
+++ b/services/fxaccounts/FxAccountsProfileClient.jsm
@@ -89,7 +89,7 @@ this.FxAccountsProfileClient.prototype = {
try {
return (yield this._rawRequest(path, method, token));
} catch (ex) {
- if (!ex instanceof FxAccountsProfileClientError || ex.code != 401) {
+ if (!(ex instanceof FxAccountsProfileClientError) || ex.code != 401) {
throw ex;
}
// If this object was instantiated with a token then we don't refresh it.
@@ -105,7 +105,7 @@ this.FxAccountsProfileClient.prototype = {
try {
return (yield this._rawRequest(path, method, token));
} catch (ex) {
- if (!ex instanceof FxAccountsProfileClientError || ex.code != 401) {
+ if (!(ex instanceof FxAccountsProfileClientError) || ex.code != 401) {
throw ex;
}
log.info("Retry fetching the profile still returned a 401 - revoking our token and failing");
diff --git a/services/fxaccounts/FxAccountsStorage.jsm b/services/fxaccounts/FxAccountsStorage.jsm
index 021763b92..4362cdf5b 100644
--- a/services/fxaccounts/FxAccountsStorage.jsm
+++ b/services/fxaccounts/FxAccountsStorage.jsm
@@ -17,6 +17,8 @@ Cu.import("resource://gre/modules/FxAccountsCommon.js");
Cu.import("resource://gre/modules/osfile.jsm");
Cu.import("resource://services-common/utils.js");
+var haveLoginManager = true;
+
// A helper function so code can check what fields are able to be stored by
// the storage manager without having a reference to a manager instance.
function FxAccountsStorageManagerCanStoreField(fieldName) {
@@ -403,7 +405,7 @@ this.FxAccountsStorageManager.prototype = {
try {
yield this.secureStorage.set(this.cachedPlain.uid, toWriteSecure);
} catch (ex) {
- if (!ex instanceof this.secureStorage.STORAGE_LOCKED) {
+ if (!(ex instanceof this.secureStorage.STORAGE_LOCKED)) {
throw ex;
}
// This shouldn't be possible as once it is unlocked it can't be
@@ -602,8 +604,3 @@ LoginManagerStorage.prototype = {
}),
}
-// A global variable to indicate if the login manager is available - it doesn't
-// exist on b2g. Defined here as the use of preprocessor directives skews line
-// numbers in the runtime, meaning stack-traces etc end up off by a few lines.
-// Doing it at the end of the file makes that less of a pita.
-var haveLoginManager = !AppConstants.MOZ_B2G;
diff --git a/services/fxaccounts/moz.build b/services/fxaccounts/moz.build
index 30c8944c2..b1cd3b59c 100644
--- a/services/fxaccounts/moz.build
+++ b/services/fxaccounts/moz.build
@@ -30,6 +30,3 @@ EXTRA_JS_MODULES += [
'FxAccountsWebChannel.jsm',
]
-# For now, we will only be using the FxA manager in B2G.
-if CONFIG['MOZ_B2G']:
- EXTRA_JS_MODULES += ['FxAccountsManager.jsm']
diff --git a/services/sync/modules/record.js b/services/sync/modules/record.js
index 02f7f281a..f7a69d9ef 100644
--- a/services/sync/modules/record.js
+++ b/services/sync/modules/record.js
@@ -43,7 +43,7 @@ WBORecord.prototype = {
// Get thyself from your URI, then deserialize.
// Set thine 'response' field.
fetch: function fetch(resource) {
- if (!resource instanceof Resource) {
+ if (!(resource instanceof Resource)) {
throw new Error("First argument must be a Resource instance.");
}
@@ -56,7 +56,7 @@ WBORecord.prototype = {
},
upload: function upload(resource) {
- if (!resource instanceof Resource) {
+ if (!(resource instanceof Resource)) {
throw new Error("First argument must be a Resource instance.");
}
diff --git a/services/sync/modules/service.js b/services/sync/modules/service.js
index b0eb0f41d..5c91323b5 100644
--- a/services/sync/modules/service.js
+++ b/services/sync/modules/service.js
@@ -455,7 +455,7 @@ Sync11Service.prototype = {
this.clientsEngine = new ClientEngine(this);
for (let name of engines) {
- if (!name in ENGINE_MODULES) {
+ if (!(name in ENGINE_MODULES)) {
this._log.info("Do not know about engine: " + name);
continue;
}
diff --git a/services/sync/tps/extensions/mozmill/resource/driver/controller.js b/services/sync/tps/extensions/mozmill/resource/driver/controller.js
index a378ce51f..8d66a41ae 100644
--- a/services/sync/tps/extensions/mozmill/resource/driver/controller.js
+++ b/services/sync/tps/extensions/mozmill/resource/driver/controller.js
@@ -978,7 +978,7 @@ function browserAdditions (controller) {
}, "Timeout", timeout, aInterval);
}
catch (ex) {
- if (!ex instanceof errors.TimeoutError) {
+ if (!(ex instanceof errors.TimeoutError)) {
throw ex;
}
timed_out = true;
diff --git a/services/sync/tps/extensions/mozmill/resource/modules/assertions.js b/services/sync/tps/extensions/mozmill/resource/modules/assertions.js
index c9991acf0..c76f95747 100644
--- a/services/sync/tps/extensions/mozmill/resource/modules/assertions.js
+++ b/services/sync/tps/extensions/mozmill/resource/modules/assertions.js
@@ -659,7 +659,7 @@ Expect.prototype.waitFor = function Expect_waitFor(aCallback, aMessage, aTimeout
Assert.prototype.waitFor.apply(this, arguments);
}
catch (ex) {
- if (!ex instanceof errors.AssertionError) {
+ if (!(ex instanceof errors.AssertionError)) {
throw ex;
}
message = ex.message;
diff --git a/startupcache/moz.build b/startupcache/moz.build
index 24068cb7e..f7e930b5b 100644
--- a/startupcache/moz.build
+++ b/startupcache/moz.build
@@ -4,8 +4,7 @@
# License, v. 2.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 not CONFIG['MOZ_B2G']:
- TEST_DIRS += ['test']
+TEST_DIRS += ['test']
XPIDL_SOURCES += [
'nsIStartupCache.idl',
diff --git a/storage/moz.build b/storage/moz.build
index 8863105c9..216a1cf74 100644
--- a/storage/moz.build
+++ b/storage/moz.build
@@ -98,8 +98,7 @@ FINAL_LIBRARY = 'xul'
# Note: On Windows our sqlite build assumes we use jemalloc. If you disable
# MOZ_STORAGE_MEMORY on Windows, you will also need to change the "ifdef
# MOZ_MEMORY" options in db/sqlite3/src/Makefile.in.
-if CONFIG['MOZ_MEMORY'] and (not CONFIG['MOZ_SYSTEM_SQLITE']
- or CONFIG['MOZ_SYSTEM_JEMALLOC']):
+if CONFIG['MOZ_MEMORY'] and not CONFIG['MOZ_SYSTEM_SQLITE']:
if CONFIG['OS_TARGET'] != 'Android':
DEFINES['MOZ_STORAGE_MEMORY'] = True
diff --git a/testing/marionette/assert.js b/testing/marionette/assert.js
index d1a55bd7c..b2d228d0e 100644
--- a/testing/marionette/assert.js
+++ b/testing/marionette/assert.js
@@ -15,7 +15,7 @@ Cu.import("chrome://marionette/content/error.js");
this.EXPORTED_SYMBOLS = ["assert"];
const isFennec = () => AppConstants.platform == "android";
-const isB2G = () => AppConstants.MOZ_B2G;
+const isB2G = () => false;
const isFirefox = () => Services.appinfo.name == "Firefox";
/** Shorthands for common assertions made in Marionette. */
diff --git a/testing/marionette/harness/marionette_harness/tests/webapi-tests.ini b/testing/marionette/harness/marionette_harness/tests/webapi-tests.ini
index 2c9dd1dce..5c94220af 100644
--- a/testing/marionette/harness/marionette_harness/tests/webapi-tests.ini
+++ b/testing/marionette/harness/marionette_harness/tests/webapi-tests.ini
@@ -1,8 +1,5 @@
-[include:../../../../../dom/system/gonk/tests/marionette/manifest.ini]
[include:../../../../../dom/system/tests/marionette/manifest.ini]
skip-if = android_version > '15' # Bug 1203072
[include:../../../../../dom/events/test/marionette/manifest.ini]
-[include:../../../../../dom/wifi/test/marionette/manifest.ini]
-[include:../../../../../dom/tethering/tests/marionette/manifest.ini]
skip-if = android_version > '15' # Bug 1203075
[include:../../../../../dom/network/tests/marionette/manifest.ini]
diff --git a/testing/mochitest/runtests.py b/testing/mochitest/runtests.py
index 7d0c89a99..dd5439bd1 100644
--- a/testing/mochitest/runtests.py
+++ b/testing/mochitest/runtests.py
@@ -2024,9 +2024,8 @@ toolbar#nav-bar {
# install specialpowers and mochikit as temporary addons
addons = Addons(self.marionette)
- if mozinfo.info.get('toolkit') != 'gonk':
- addons.install(os.path.join(here, 'extensions', 'specialpowers'), temp=True)
- addons.install(self.mochijar, temp=True)
+ addons.install(os.path.join(here, 'extensions', 'specialpowers'), temp=True)
+ addons.install(self.mochijar, temp=True)
self.execute_start_script()
diff --git a/testing/modules/tests/xpcshell/xpcshell.ini b/testing/modules/tests/xpcshell/xpcshell.ini
index 40dc9920e..7ff4e27e3 100644
--- a/testing/modules/tests/xpcshell/xpcshell.ini
+++ b/testing/modules/tests/xpcshell/xpcshell.ini
@@ -1,7 +1,7 @@
[DEFAULT]
head =
tail =
-skip-if = toolkit == 'android' || toolkit == 'gonk'
+skip-if = toolkit == 'android'
[test_assert.js]
[test_mockRegistrar.js]
diff --git a/testing/mozbase/mozrunner/mozrunner/utils.py b/testing/mozbase/mozrunner/mozrunner/utils.py
index 79f26b8f2..c26055f30 100755
--- a/testing/mozbase/mozrunner/mozrunner/utils.py
+++ b/testing/mozbase/mozrunner/mozrunner/utils.py
@@ -101,10 +101,7 @@ def test_environment(xrePath, env=None, crashreporter=True, debugger=False,
envVar = None
dmdLibrary = None
preloadEnvVar = None
- if 'toolkit' in mozinfo.info and mozinfo.info['toolkit'] == "gonk":
- # Skip all of this, it's only valid for the host.
- pass
- elif mozinfo.isUnix:
+ if mozinfo.isUnix:
envVar = "LD_LIBRARY_PATH"
env['MOZILLA_FIVE_HOME'] = xrePath
dmdLibrary = "libdmd.so"
diff --git a/testing/profiles/prefs_general.js b/testing/profiles/prefs_general.js
index ac2c1e077..d30ae89f5 100644
--- a/testing/profiles/prefs_general.js
+++ b/testing/profiles/prefs_general.js
@@ -182,6 +182,9 @@ user_pref("layout.css.prefixes.device-pixel-ratio-webkit", true);
// Enable CSS shape-outside for testing
user_pref("layout.css.shape-outside.enabled", true);
+// Enable CSS text-justify for testing
+user_pref("layout.css.text-justify.enabled", true);
+
// Disable spammy layout warnings because they pollute test logs
user_pref("layout.spammy_warnings.enabled", false);
diff --git a/testing/specialpowers/content/specialpowersAPI.js b/testing/specialpowers/content/specialpowersAPI.js
index 8f1ff7465..e97ad89c4 100644
--- a/testing/specialpowers/content/specialpowersAPI.js
+++ b/testing/specialpowers/content/specialpowersAPI.js
@@ -1529,11 +1529,7 @@ SpecialPowersAPI.prototype = {
},
get isB2G() {
-#ifdef MOZ_B2G
- return true;
-#else
return false;
-#endif
},
addSystemEventListener: function(target, type, listener, useCapture) {
diff --git a/testing/talos/talos/test.py b/testing/talos/talos/test.py
index 0de9f19bb..dc1306b8e 100644
--- a/testing/talos/talos/test.py
+++ b/testing/talos/talos/test.py
@@ -194,6 +194,7 @@ class tpaint(TsBase):
tpmozafterpaint = True
filters = filter.ignore_first.prepare(5) + filter.median.prepare()
unit = 'ms'
+ preferences = {'security.data_uri.block_toplevel_data_uri_navigations': False}
@register_test()
diff --git a/testing/testsuite-targets.mk b/testing/testsuite-targets.mk
index 8b1d7d50d..ebe0d06cf 100644
--- a/testing/testsuite-targets.mk
+++ b/testing/testsuite-targets.mk
@@ -18,10 +18,6 @@ ifneq (1_WINNT,$(MOZ_PGO)_$(OS_ARCH))
BUILD_GTEST=1
endif
-ifdef MOZ_B2G
-BUILD_GTEST=
-endif
-
ifndef MOZ_PHOENIX
BUILD_GTEST=
endif
diff --git a/testing/web-platform/meta/MANIFEST.json b/testing/web-platform/meta/MANIFEST.json
index 3c7df67fa..496f8e3cb 100644
--- a/testing/web-platform/meta/MANIFEST.json
+++ b/testing/web-platform/meta/MANIFEST.json
@@ -31100,6 +31100,10 @@
"url": "/user-timing/test_user_timing_mark.html"
},
{
+ "path": "user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.html",
+ "url": "/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.html"
+ },
+ {
"path": "user-timing/test_user_timing_mark_and_measure_exception_when_invoke_without_parameter.html",
"url": "/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_without_parameter.html"
},
diff --git a/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini
new file mode 100644
index 000000000..c65b27a08
--- /dev/null
+++ b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini
@@ -0,0 +1,3 @@
+[no-opt-in-blocks.https.html]
+ type: testharness
+ prefs: [security.mixed_content.send_hsts_priming:false, security.mixed_content.use_hsts:false]
diff --git a/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/no-redirect/no-opt-in-blocks.https.html.ini b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/no-redirect/no-opt-in-blocks.https.html.ini
new file mode 100644
index 000000000..c65b27a08
--- /dev/null
+++ b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/no-redirect/no-opt-in-blocks.https.html.ini
@@ -0,0 +1,3 @@
+[no-opt-in-blocks.https.html]
+ type: testharness
+ prefs: [security.mixed_content.send_hsts_priming:false, security.mixed_content.use_hsts:false]
diff --git a/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini
new file mode 100644
index 000000000..c65b27a08
--- /dev/null
+++ b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/cross-origin-http/iframe-tag/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini
@@ -0,0 +1,3 @@
+[no-opt-in-blocks.https.html]
+ type: testharness
+ prefs: [security.mixed_content.send_hsts_priming:false, security.mixed_content.use_hsts:false]
diff --git a/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini
new file mode 100644
index 000000000..c65b27a08
--- /dev/null
+++ b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/keep-scheme-redirect/no-opt-in-blocks.https.html.ini
@@ -0,0 +1,3 @@
+[no-opt-in-blocks.https.html]
+ type: testharness
+ prefs: [security.mixed_content.send_hsts_priming:false, security.mixed_content.use_hsts:false]
diff --git a/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/no-redirect/no-opt-in-blocks.https.html.ini b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/no-redirect/no-opt-in-blocks.https.html.ini
new file mode 100644
index 000000000..c65b27a08
--- /dev/null
+++ b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/no-redirect/no-opt-in-blocks.https.html.ini
@@ -0,0 +1,3 @@
+[no-opt-in-blocks.https.html]
+ type: testharness
+ prefs: [security.mixed_content.send_hsts_priming:false, security.mixed_content.use_hsts:false]
diff --git a/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini
new file mode 100644
index 000000000..c65b27a08
--- /dev/null
+++ b/testing/web-platform/meta/mixed-content/blockable/no-opt-in/same-host-http/iframe-tag/top-level/swap-scheme-redirect/no-opt-in-blocks.https.html.ini
@@ -0,0 +1,3 @@
+[no-opt-in-blocks.https.html]
+ type: testharness
+ prefs: [security.mixed_content.send_hsts_priming:false, security.mixed_content.use_hsts:false]
diff --git a/testing/web-platform/meta/service-workers/service-worker/resource-timing.https.html.ini b/testing/web-platform/meta/service-workers/service-worker/resource-timing.https.html.ini
index b399d5f38..b6f02262b 100644
--- a/testing/web-platform/meta/service-workers/service-worker/resource-timing.https.html.ini
+++ b/testing/web-platform/meta/service-workers/service-worker/resource-timing.https.html.ini
@@ -1,9 +1,2 @@
[resource-timing.https.html]
type: testharness
- disabled: https://bugzilla.mozilla.org/show_bug.cgi?id=1178713
- [Controlled resource loads]
- expected: FAIL
-
- [Non-controlled resource loads]
- expected: FAIL
-
diff --git a/testing/web-platform/tests/service-workers/service-worker/fetch-frame-resource.https.html b/testing/web-platform/tests/service-workers/service-worker/fetch-frame-resource.https.html
index cc1dac472..fd7419832 100644
--- a/testing/web-platform/tests/service-workers/service-worker/fetch-frame-resource.https.html
+++ b/testing/web-platform/tests/service-workers/service-worker/fetch-frame-resource.https.html
@@ -110,7 +110,8 @@ async_test(function(t) {
frame.src =
scope + '?mode=cors&url=' +
encodeURIComponent(host_info['HTTPS_REMOTE_ORIGIN'] + path +
- '?ACAOrigin=' + host_info['HTTPS_ORIGIN']);
+ '?ACAOrigin=' + host_info['HTTPS_ORIGIN'] +
+ '&ACACredentials=true');
document.body.appendChild(frame);
return getLoadedFrameAsObject(frame);
})
@@ -183,7 +184,8 @@ async_test(function(t) {
var win = window.open(
scope + '?mode=cors&url=' +
encodeURIComponent(host_info['HTTPS_REMOTE_ORIGIN'] + path +
- '?ACAOrigin=' + host_info['HTTPS_ORIGIN']));
+ '?ACAOrigin=' + host_info['HTTPS_ORIGIN'] +
+ '&ACACredentials=true'));
return getLoadedWindowAsObject(win);
})
.then(function(result) {
diff --git a/testing/web-platform/tests/service-workers/service-worker/resource-timing.https.html b/testing/web-platform/tests/service-workers/service-worker/resource-timing.https.html
index f33c41d71..3a1adfa48 100644
--- a/testing/web-platform/tests/service-workers/service-worker/resource-timing.https.html
+++ b/testing/web-platform/tests/service-workers/service-worker/resource-timing.https.html
@@ -13,6 +13,10 @@ function verify(performance, resource, description) {
assert_greater_than(entry.workerStart, 0, description);
assert_greater_than_equal(entry.workerStart, entry.startTime, description);
assert_less_than_equal(entry.workerStart, entry.fetchStart, description);
+ assert_greater_than_equal(entry.responseStart, entry.fetchStart, description);
+ assert_greater_than_equal(entry.responseEnd, entry.responseStart, description);
+ assert_greater_than(entry.responseEnd, entry.fetchStart, description);
+ assert_greater_than(entry.duration, 0, description);
if (resource.indexOf('redirect.py') != -1) {
assert_less_than_equal(entry.workerStart, entry.redirectStart,
description);
diff --git a/testing/web-platform/tests/service-workers/service-worker/resources/resource-timing-worker.js b/testing/web-platform/tests/service-workers/service-worker/resources/resource-timing-worker.js
index 481a6536a..452876838 100644
--- a/testing/web-platform/tests/service-workers/service-worker/resources/resource-timing-worker.js
+++ b/testing/web-platform/tests/service-workers/service-worker/resources/resource-timing-worker.js
@@ -1,5 +1,9 @@
self.addEventListener('fetch', function(event) {
if (event.request.url.indexOf('dummy.js') != -1) {
- event.respondWith(new Response());
+ event.respondWith(new Promise(resolve => {
+ // Slightly delay the response so we ensure we get a non-zero
+ // duration.
+ setTimeout(_ => resolve(new Response()), 100);
+ }));
}
});
diff --git a/testing/web-platform/tests/user-timing/resources/webperftestharness.js b/testing/web-platform/tests/user-timing/resources/webperftestharness.js
index 750946dde..f1597bbe7 100644
--- a/testing/web-platform/tests/user-timing/resources/webperftestharness.js
+++ b/testing/web-platform/tests/user-timing/resources/webperftestharness.js
@@ -12,7 +12,7 @@ policies and contribution forms [3].
// Helper Functions for NavigationTiming W3C tests
//
-var performanceNamespace = window.performance;
+var performanceNamespace = self.performance;
var timingAttributes = [
'connectEnd',
'connectStart',
diff --git a/testing/web-platform/tests/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.html b/testing/web-platform/tests/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.html
new file mode 100644
index 000000000..aea8cb6e9
--- /dev/null
+++ b/testing/web-platform/tests/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.html
@@ -0,0 +1,32 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <title>exception test of performance.mark and performance.measure</title>
+ <meta rel="help" href="http://www.w3.org/TR/user-timing/#extensions-performance-interface"/>
+ <script src="/resources/testharness.js"></script>
+ <script src="/resources/testharnessreport.js"></script>
+ <script src="resources/webperftestharness.js"></script>
+ </head>
+ <body>
+ <script>
+ setup({explicit_done: true});
+ test_namespace();
+
+ test(function() {
+ for (var i in timingAttributes) {
+ assert_throws("SyntaxError", function() { window.performance.mark(timingAttributes[i]); });
+ assert_throws("SyntaxError", function() { window.performance.measure(timingAttributes[i]); });
+ }
+ }, "performance.mark and performance.measure should throw if used with timing attribute values");
+
+ fetch_tests_from_worker(new Worker("test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.js"));
+
+ done();
+
+ </script>
+ <h1>Description</h1>
+ <p>This test validates exception scenarios of invoking mark() and measure() with timing attributes as value.</p>
+ <div id="log"></div>
+ </body>
+</html>
diff --git a/testing/web-platform/tests/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.js b/testing/web-platform/tests/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.js
new file mode 100644
index 000000000..f015402f9
--- /dev/null
+++ b/testing/web-platform/tests/user-timing/test_user_timing_mark_and_measure_exception_when_invoke_with_timing_attributes.js
@@ -0,0 +1,14 @@
+importScripts("/resources/testharness.js");
+importScripts("resources/webperftestharness.js");
+
+test(function() {
+ for (var i in timingAttributes) {
+ performance.mark(timingAttributes[i]);
+ performance.clearMarks(timingAttributes[i]);
+
+ performance.measure(timingAttributes[i]);
+ performance.clearMeasures(timingAttributes[i]);
+ }
+}, "performance.mark and performance.measure should not throw if used with timing attribute values in workers");
+
+done();
diff --git a/testing/web-platform/tests/websockets/unload-a-document/001-1.html b/testing/web-platform/tests/websockets/unload-a-document/001-1.html
index 214246b2e..926a68a06 100644
--- a/testing/web-platform/tests/websockets/unload-a-document/001-1.html
+++ b/testing/web-platform/tests/websockets/unload-a-document/001-1.html
@@ -22,7 +22,7 @@ t.step(function() {
}), 1000);
controller.navigate();
})
- ws.onerror = ws.onmessage = ws.onclose = t.step_func(function(e) {assert_unreached("Got unexpected event " + e.type)});
+ ws.onerror = ws.onmessage = t.step_func(e => assert_unreached("Got unexpected event " + e.type));
}
});
</script>
diff --git a/testing/web-platform/tests/websockets/unload-a-document/001-2.html b/testing/web-platform/tests/websockets/unload-a-document/001-2.html
new file mode 100644
index 000000000..24c419ce1
--- /dev/null
+++ b/testing/web-platform/tests/websockets/unload-a-document/001-2.html
@@ -0,0 +1,4 @@
+<!doctype html>
+<title>WebSockets: navigating top-level browsing context</title>
+<body onload="history.back()"></body>
+</html>
diff --git a/testing/web-platform/tests/websockets/unload-a-document/001.html b/testing/web-platform/tests/websockets/unload-a-document/001.html
index d949b6eba..56e883c64 100644
--- a/testing/web-platform/tests/websockets/unload-a-document/001.html
+++ b/testing/web-platform/tests/websockets/unload-a-document/001.html
@@ -20,6 +20,6 @@ t.step(function() {
});
});
navigate = t.step_func(function() {
- w.location = 'data:text/html,<body onload="history.back()">';
+ w.location = w.location.href.replace("001-1.html", "001-2.html");
});
</script>
diff --git a/testing/web-platform/tests/websockets/unload-a-document/002-1.html b/testing/web-platform/tests/websockets/unload-a-document/002-1.html
index 86a852b10..52f188fa4 100644
--- a/testing/web-platform/tests/websockets/unload-a-document/002-1.html
+++ b/testing/web-platform/tests/websockets/unload-a-document/002-1.html
@@ -28,7 +28,7 @@ t.step(function() {
controller.navigate();
});
})
- ws.onerror = ws.onmessage = ws.onclose = t.step_func(function(e) {assert_unreached("Got unexpected event " + e.type)});
+ ws.onerror = ws.onmessage = t.step_func(e => assert_unreached("Got unexpected event " + e.type));
}
});
</script>
diff --git a/testing/web-platform/tests/websockets/unload-a-document/002-2.html b/testing/web-platform/tests/websockets/unload-a-document/002-2.html
new file mode 100644
index 000000000..9a246a1dd
--- /dev/null
+++ b/testing/web-platform/tests/websockets/unload-a-document/002-2.html
@@ -0,0 +1,4 @@
+<!doctype html>
+<title>WebSockets: navigating top-level browsing context with closed websocket</title>
+<body onload="history.back()"></body>
+</html>
diff --git a/testing/web-platform/tests/websockets/unload-a-document/002.html b/testing/web-platform/tests/websockets/unload-a-document/002.html
index df35192d6..03764c345 100644
--- a/testing/web-platform/tests/websockets/unload-a-document/002.html
+++ b/testing/web-platform/tests/websockets/unload-a-document/002.html
@@ -21,6 +21,6 @@ t.step(function() {
});
});
navigate = t.step_func(function() {
- w.location = 'data:text/html,<body onload="history.back()">';
+ w.location = w.location.href.replace("002-1.html", "002-2.html");
});
</script>
diff --git a/testing/xpcshell/example/unit/xpcshell.ini b/testing/xpcshell/example/unit/xpcshell.ini
index 3af6770af..dde767225 100644
--- a/testing/xpcshell/example/unit/xpcshell.ini
+++ b/testing/xpcshell/example/unit/xpcshell.ini
@@ -5,7 +5,7 @@
[DEFAULT]
head =
tail =
-skip-if = toolkit == 'gonk'
+skip-if =
support-files =
subdir/file.txt
file.txt
diff --git a/toolkit/.eslintrc.js b/toolkit/.eslintrc.js
index 181f19f29..891a114b3 100644
--- a/toolkit/.eslintrc.js
+++ b/toolkit/.eslintrc.js
@@ -111,9 +111,6 @@ module.exports = {
// No reassigning native JS objects
"no-native-reassign": "error",
- // No (!foo in bar)
- "no-negated-in-lhs": "error",
-
// Nested ternary statements are confusing
"no-nested-ternary": "error",
diff --git a/toolkit/components/alerts/resources/content/alert.js b/toolkit/components/alerts/resources/content/alert.js
index ce60ab0fa..12068b548 100644
--- a/toolkit/components/alerts/resources/content/alert.js
+++ b/toolkit/components/alerts/resources/content/alert.js
@@ -313,6 +313,7 @@ function onAlertClick() {
let alertBox = document.getElementById("alertBox");
if (alertBox.getAttribute("animate") == "true") {
// Closed when the animation ends.
+ alertBox.style.animationDuration = ".6s";
alertBox.setAttribute("clicked", "true");
} else {
window.close();
@@ -355,6 +356,7 @@ function onAlertClose() {
let alertBox = document.getElementById("alertBox");
if (alertBox.getAttribute("animate") == "true") {
// Closed when the animation ends.
+ alertBox.style.animationDuration = ".6s";
alertBox.setAttribute("closing", "true");
} else {
window.close();
diff --git a/toolkit/components/build/nsToolkitCompsModule.cpp b/toolkit/components/build/nsToolkitCompsModule.cpp
index 22bb434a0..2c7287d8c 100644
--- a/toolkit/components/build/nsToolkitCompsModule.cpp
+++ b/toolkit/components/build/nsToolkitCompsModule.cpp
@@ -46,7 +46,7 @@
#include "NativeFileWatcherNotSupported.h"
#endif // (XP_WIN)
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
#define MOZ_HAS_TERMINATOR
#endif
diff --git a/toolkit/components/captivedetect/captivedetect.js b/toolkit/components/captivedetect/captivedetect.js
index 5493ecec6..0e8c75981 100644
--- a/toolkit/components/captivedetect/captivedetect.js
+++ b/toolkit/components/captivedetect/captivedetect.js
@@ -90,7 +90,7 @@ function LoginObserver(captivePortalDetector) {
.getService(Ci.nsIHttpActivityDistributor);
let urlFetcher = null;
- let waitForNetworkActivity = Services.appinfo.widgetToolkit == "gonk";
+ let waitForNetworkActivity = false;
let pageCheckingDone = function pageCheckingDone() {
if (state === LOGIN_OBSERVER_STATE_VERIFYING) {
diff --git a/toolkit/components/diskspacewatcher/DiskSpaceWatcher.cpp b/toolkit/components/diskspacewatcher/DiskSpaceWatcher.cpp
index 950d3b487..7f3b8cd08 100644
--- a/toolkit/components/diskspacewatcher/DiskSpaceWatcher.cpp
+++ b/toolkit/components/diskspacewatcher/DiskSpaceWatcher.cpp
@@ -145,9 +145,6 @@ static const mozilla::Module::ContractIDEntry kDiskSpaceWatcherContracts[] = {
};
static const mozilla::Module::CategoryEntry kDiskSpaceWatcherCategories[] = {
-#ifdef MOZ_WIDGET_GONK
- { "profile-after-change", "Disk Space Watcher Service", DISKSPACEWATCHER_CONTRACTID },
-#endif
{ nullptr }
};
diff --git a/toolkit/components/jsdownloads/src/DownloadIntegration.jsm b/toolkit/components/jsdownloads/src/DownloadIntegration.jsm
index 7439d9d11..bee5bf269 100644
--- a/toolkit/components/jsdownloads/src/DownloadIntegration.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadIntegration.jsm
@@ -300,12 +300,7 @@ this.DownloadIntegration = {
aDownload.hasBlockedData) {
return true;
}
-#ifdef MOZ_B2G
- // On B2G we keep a few days of history.
- let maxTime = Date.now() -
- Services.prefs.getIntPref("dom.downloads.max_retention_days") * 24 * 60 * 60 * 1000;
- return aDownload.startTime > maxTime;
-#elif defined(MOZ_WIDGET_ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
// On Android we store all history.
return true;
#else
@@ -415,8 +410,6 @@ this.DownloadIntegration = {
directoryPath = yield this.getPreferredDownloadsDirectory();
#elifdef MOZ_WIDGET_ANDROID
directoryPath = yield this.getSystemDownloadsDirectory();
-#elifdef MOZ_WIDGET_GONK
- directoryPath = yield this.getSystemDownloadsDirectory();
#else
directoryPath = this._getDirectory("TmpD");
#endif
diff --git a/toolkit/components/jsdownloads/src/DownloadPlatform.cpp b/toolkit/components/jsdownloads/src/DownloadPlatform.cpp
index 1506b7c30..d91124ee6 100644
--- a/toolkit/components/jsdownloads/src/DownloadPlatform.cpp
+++ b/toolkit/components/jsdownloads/src/DownloadPlatform.cpp
@@ -102,7 +102,7 @@ nsresult DownloadPlatform::DownloadDone(nsIURI* aSource, nsIURI* aReferrer, nsIF
const nsACString& aContentType, bool aIsPrivate)
{
#if defined(XP_WIN) || defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID) \
- || defined(MOZ_WIDGET_GTK) || defined(MOZ_WIDGET_GONK)
+ || defined(MOZ_WIDGET_GTK)
nsAutoString path;
if (aTarget && NS_SUCCEEDED(aTarget->GetPath(path))) {
diff --git a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm
index f5102b4a8..5bd351ee9 100644
--- a/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm
+++ b/toolkit/components/jsdownloads/src/DownloadUIHelper.jsm
@@ -106,12 +106,7 @@ XPCOMUtils.defineLazyGetter(DownloadUIHelper, "strings", function () {
*/
this.DownloadPrompter = function (aParent)
{
- if (AppConstants.MOZ_B2G) {
- // On B2G there is no prompter implementation.
- this._prompter = null;
- } else {
- this._prompter = Services.ww.getNewPrompter(aParent);
- }
+ this._prompter = Services.ww.getNewPrompter(aParent);
}
this.DownloadPrompter.prototype = {
diff --git a/toolkit/components/moz.build b/toolkit/components/moz.build
index 5dba09a32..e0b412428 100644
--- a/toolkit/components/moz.build
+++ b/toolkit/components/moz.build
@@ -70,8 +70,7 @@ DIRS += [
if CONFIG['MOZ_WEBEXTENSIONS']:
DIRS += ['webextensions']
-if CONFIG['ENABLE_INTL_API']:
- DIRS += ['mozintl']
+DIRS += ['mozintl']
if not CONFIG['MOZ_FENNEC']:
DIRS += ['narrate', 'viewsource'];
diff --git a/toolkit/components/osfile/modules/osfile_async_front.jsm b/toolkit/components/osfile/modules/osfile_async_front.jsm
index 181471cd8..964e53084 100644
--- a/toolkit/components/osfile/modules/osfile_async_front.jsm
+++ b/toolkit/components/osfile/modules/osfile_async_front.jsm
@@ -753,13 +753,13 @@ File.prototype = {
};
-if (SharedAll.Constants.Sys.Name != "Android" && SharedAll.Constants.Sys.Name != "Gonk") {
+if (SharedAll.Constants.Sys.Name != "Android") {
/**
* Set the last access and modification date of the file.
* The time stamp resolution is 1 second at best, but might be worse
* depending on the platform.
*
- * WARNING: This method is not implemented on Android/B2G. On Android/B2G,
+ * WARNING: This method is not implemented on Android. On Android,
* you should use File.setDates instead.
*
* @return {promise}
diff --git a/toolkit/components/osfile/modules/osfile_unix_front.jsm b/toolkit/components/osfile/modules/osfile_unix_front.jsm
index 19a27ae1a..bd60d4d84 100644
--- a/toolkit/components/osfile/modules/osfile_unix_front.jsm
+++ b/toolkit/components/osfile/modules/osfile_unix_front.jsm
@@ -838,7 +838,7 @@
* implementation.
*/
File.DirectoryIterator.Entry.toMsg = function toMsg(value) {
- if (!value instanceof File.DirectoryIterator.Entry) {
+ if (!(value instanceof File.DirectoryIterator.Entry)) {
throw new TypeError("parameter of " +
"File.DirectoryIterator.Entry.toMsg must be a " +
"File.DirectoryIterator.Entry");
@@ -905,7 +905,7 @@
* is asymmetric and returns an object with a different implementation.
*/
File.Info.toMsg = function toMsg(stat) {
- if (!stat instanceof File.Info) {
+ if (!(stat instanceof File.Info)) {
throw new TypeError("parameter of File.Info.toMsg must be a File.Info");
}
let serialized = {};
diff --git a/toolkit/components/osfile/modules/osfile_win_front.jsm b/toolkit/components/osfile/modules/osfile_win_front.jsm
index 387dd08b5..1123b251c 100644
--- a/toolkit/components/osfile/modules/osfile_win_front.jsm
+++ b/toolkit/components/osfile/modules/osfile_win_front.jsm
@@ -909,7 +909,7 @@
* implementation.
*/
File.DirectoryIterator.Entry.toMsg = function toMsg(value) {
- if (!value instanceof File.DirectoryIterator.Entry) {
+ if (!(value instanceof File.DirectoryIterator.Entry)) {
throw new TypeError("parameter of " +
"File.DirectoryIterator.Entry.toMsg must be a " +
"File.DirectoryIterator.Entry");
@@ -958,7 +958,7 @@
* is asymmetric and returns an object with a different implementation.
*/
File.Info.toMsg = function toMsg(stat) {
- if (!stat instanceof File.Info) {
+ if (!(stat instanceof File.Info)) {
throw new TypeError("parameter of File.Info.toMsg must be a File.Info");
}
let serialized = {};
diff --git a/toolkit/components/osfile/tests/xpcshell/test_constants.js b/toolkit/components/osfile/tests/xpcshell/test_constants.js
index e92f33ab8..5b91484bd 100644
--- a/toolkit/components/osfile/tests/xpcshell/test_constants.js
+++ b/toolkit/components/osfile/tests/xpcshell/test_constants.js
@@ -15,12 +15,7 @@ add_task(function* check_definition() {
do_check_true(OS.Constants.Path!=null);
do_check_true(OS.Constants.Sys!=null);
//check system name
- if (OS.Constants.Sys.Name == "Gonk") {
- // Services.appinfo.OS doesn't know the difference between Gonk and Android
- do_check_eq(Services.appinfo.OS, "Android");
- } else {
- do_check_eq(Services.appinfo.OS, OS.Constants.Sys.Name);
- }
+ do_check_eq(Services.appinfo.OS, OS.Constants.Sys.Name);
//check if using DEBUG build
if (Components.classes["@mozilla.org/xpcom/debug;1"].getService(Components.interfaces.nsIDebug2).isDebugBuild == true) {
diff --git a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js
index 17d3afa7c..6a5ecd5e3 100644
--- a/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js
+++ b/toolkit/components/osfile/tests/xpcshell/test_osfile_async_setDates.js
@@ -96,8 +96,8 @@ add_task(function* test_nonproto() {
// Prototypical tests, operating on |File| handles.
add_task(function* test_proto() {
- if (OS.Constants.Sys.Name == "Android" || OS.Constants.Sys.Name == "Gonk") {
- do_print("File.prototype.setDates is not implemented for Android/B2G");
+ if (OS.Constants.Sys.Name == "Android") {
+ do_print("File.prototype.setDates is not implemented for Android");
do_check_eq(OS.File.prototype.setDates, undefined);
return;
}
@@ -107,7 +107,7 @@ add_task(function* test_proto() {
"test_osfile_async_setDates_proto.tmp");
yield OS.File.writeAtomic(path, new Uint8Array(1));
- try {
+ try {
let fd = yield OS.File.open(path, {write: true});
try {
diff --git a/toolkit/components/osfile/tests/xpcshell/test_path_constants.js b/toolkit/components/osfile/tests/xpcshell/test_path_constants.js
index c0057c750..9b9868bb2 100644
--- a/toolkit/components/osfile/tests/xpcshell/test_path_constants.js
+++ b/toolkit/components/osfile/tests/xpcshell/test_path_constants.js
@@ -58,7 +58,7 @@ add_task(function* test_simple_paths() {
// Test presence of paths that only exist on Desktop platforms
add_task(function* test_desktop_paths() {
- if (OS.Constants.Sys.Name == "Android" || OS.Constants.Sys.Name == "Gonk") {
+ if (OS.Constants.Sys.Name == "Android") {
return;
}
do_check_true(!!OS.Constants.Path.desktopDir);
diff --git a/toolkit/components/printing/tests/browser.ini b/toolkit/components/printing/tests/browser.ini
index 88d6bb454..5f2867189 100644
--- a/toolkit/components/printing/tests/browser.ini
+++ b/toolkit/components/printing/tests/browser.ini
@@ -1,2 +1,5 @@
[browser_page_change_print_original.js]
+support-files =
+ file_page_change_print_original_1.html
+ file_page_change_print_original_2.html
skip-if = os == "mac"
diff --git a/toolkit/components/printing/tests/browser_page_change_print_original.js b/toolkit/components/printing/tests/browser_page_change_print_original.js
index 5990a486b..864150451 100644
--- a/toolkit/components/printing/tests/browser_page_change_print_original.js
+++ b/toolkit/components/printing/tests/browser_page_change_print_original.js
@@ -3,8 +3,11 @@
* and we re-initialize print preview (e.g. by changing page orientation),
* we still show (and will therefore print) the original contents.
*/
+const TEST_PATH = getRootDirectory(gTestPath)
+ .replace("chrome://mochitests/content", "http://example.com");
+
add_task(function* pp_after_orientation_change() {
- const DATA_URI = `data:text/html,<script>window.onafterprint = function() { setTimeout("window.location = 'data:text/plain,REPLACED PAGE!'", 0); }</script><pre>INITIAL PAGE</pre>`;
+ const URI = TEST_PATH + "file_page_change_print_original_1.html";
// Can only do something if we have a print preview UI:
if (AppConstants.platform != "win" && AppConstants.platform != "linux") {
ok(true, "Can't test if there's no print preview.");
@@ -12,7 +15,7 @@ add_task(function* pp_after_orientation_change() {
}
// Ensure we get a browserStopped for this browser
- let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, DATA_URI, false, true);
+ let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, URI, false, true);
let browserToPrint = tab.linkedBrowser;
let ppBrowser = PrintPreviewListener.getPrintPreviewBrowser();
@@ -26,7 +29,7 @@ add_task(function* pp_after_orientation_change() {
// Assert that we are showing the original page
yield ContentTask.spawn(ppBrowser, null, function* () {
- is(content.document.body.textContent, "INITIAL PAGE", "Should have initial page print previewed.");
+ is(content.document.body.textContent.trim(), "INITIAL PAGE", "Should have initial page print previewed.");
});
yield originalTabNavigated;
@@ -43,12 +46,12 @@ add_task(function* pp_after_orientation_change() {
// Check that we're still showing the original page.
yield ContentTask.spawn(ppBrowser, null, function* () {
- is(content.document.body.textContent, "INITIAL PAGE", "Should still have initial page print previewed.");
+ is(content.document.body.textContent.trim(), "INITIAL PAGE", "Should still have initial page print previewed.");
});
// Check that the other tab is definitely showing the new page:
yield ContentTask.spawn(browserToPrint, null, function* () {
- is(content.document.body.textContent, "REPLACED PAGE!", "Original page should have changed.");
+ is(content.document.body.textContent.trim(), "REPLACED PAGE!", "Original page should have changed.");
});
PrintUtils.exitPrintPreview();
diff --git a/toolkit/components/printing/tests/file_page_change_print_original_1.html b/toolkit/components/printing/tests/file_page_change_print_original_1.html
new file mode 100644
index 000000000..76e3be137
--- /dev/null
+++ b/toolkit/components/printing/tests/file_page_change_print_original_1.html
@@ -0,0 +1,8 @@
+<script>
+window.onafterprint = function() {
+ setTimeout(function() {
+ window.location = "file_page_change_print_original_2.html"
+ }, 0);
+}
+</script>
+<pre>INITIAL PAGE</pre>
diff --git a/toolkit/components/printing/tests/file_page_change_print_original_2.html b/toolkit/components/printing/tests/file_page_change_print_original_2.html
new file mode 100644
index 000000000..44f33281c
--- /dev/null
+++ b/toolkit/components/printing/tests/file_page_change_print_original_2.html
@@ -0,0 +1 @@
+REPLACED PAGE!
diff --git a/toolkit/components/reader/.eslintrc.js b/toolkit/components/reader/.eslintrc.js
index 1c09e0bf7..617c1f9cf 100644
--- a/toolkit/components/reader/.eslintrc.js
+++ b/toolkit/components/reader/.eslintrc.js
@@ -109,9 +109,6 @@ module.exports = {
// No reassigning native JS objects
"no-native-reassign": "error",
- // No (!foo in bar)
- "no-negated-in-lhs": "error",
-
// Nested ternary statements are confusing
"no-nested-ternary": "error",
diff --git a/toolkit/components/search/nsSearchService.js b/toolkit/components/search/nsSearchService.js
index fb3f69f4c..9f9003516 100644
--- a/toolkit/components/search/nsSearchService.js
+++ b/toolkit/components/search/nsSearchService.js
@@ -23,8 +23,6 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "TelemetryStopwatch",
"resource://gre/modules/TelemetryStopwatch.jsm");
-XPCOMUtils.defineLazyModuleGetter(this, "Deprecated",
- "resource://gre/modules/Deprecated.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "SearchStaticData",
"resource://gre/modules/SearchStaticData.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "setTimeout",
@@ -2695,13 +2693,6 @@ SearchService.prototype = {
return;
}
- let warning =
- "Search service falling back to synchronous initialization. " +
- "This is generally the consequence of an add-on using a deprecated " +
- "search service API.";
- Deprecated.warning(warning, "https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIBrowserSearchService#async_warning");
- LOG(warning);
-
this._syncInit();
if (!Components.isSuccessCode(this._initRV)) {
throw this._initRV;
diff --git a/toolkit/components/startup/nsAppStartup.cpp b/toolkit/components/startup/nsAppStartup.cpp
index 85d5afdf9..fde00d1db 100644
--- a/toolkit/components/startup/nsAppStartup.cpp
+++ b/toolkit/components/startup/nsAppStartup.cpp
@@ -237,7 +237,7 @@ NS_IMPL_ISUPPORTS(nsAppStartup,
NS_IMETHODIMP
nsAppStartup::CreateHiddenWindow()
{
-#if defined(MOZ_WIDGET_GONK) || defined(MOZ_WIDGET_UIKIT)
+#if defined(MOZ_WIDGET_UIKIT)
return NS_OK;
#else
nsCOMPtr<nsIAppShellService> appShellService
@@ -252,7 +252,7 @@ nsAppStartup::CreateHiddenWindow()
NS_IMETHODIMP
nsAppStartup::DestroyHiddenWindow()
{
-#if defined(MOZ_WIDGET_GONK) || defined(MOZ_WIDGET_UIKIT)
+#if defined(MOZ_WIDGET_UIKIT)
return NS_OK;
#else
nsCOMPtr<nsIAppShellService> appShellService
diff --git a/toolkit/components/telemetry/Telemetry.cpp b/toolkit/components/telemetry/Telemetry.cpp
index ad2263c9b..6dbd59bcf 100644
--- a/toolkit/components/telemetry/Telemetry.cpp
+++ b/toolkit/components/telemetry/Telemetry.cpp
@@ -1127,7 +1127,7 @@ TelemetryImpl::SnapshotSubsessionHistograms(bool clearSubsession,
JSContext *cx,
JS::MutableHandle<JS::Value> ret)
{
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
return TelemetryHistogram::CreateHistogramSnapshots(cx, ret, true,
clearSubsession);
#else
diff --git a/toolkit/components/telemetry/TelemetryEnvironment.jsm b/toolkit/components/telemetry/TelemetryEnvironment.jsm
index 910d804ae..295679ca4 100644
--- a/toolkit/components/telemetry/TelemetryEnvironment.jsm
+++ b/toolkit/components/telemetry/TelemetryEnvironment.jsm
@@ -28,11 +28,9 @@ XPCOMUtils.defineLazyModuleGetter(this, "AttributionCode",
"resource:///modules/AttributionCode.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ctypes",
"resource://gre/modules/ctypes.jsm");
-if (AppConstants.platform !== "gonk") {
- Cu.import("resource://gre/modules/AddonManager.jsm");
- XPCOMUtils.defineLazyModuleGetter(this, "LightweightThemeManager",
- "resource://gre/modules/LightweightThemeManager.jsm");
-}
+Cu.import("resource://gre/modules/AddonManager.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "LightweightThemeManager",
+ "resource://gre/modules/LightweightThemeManager.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "ProfileAge",
"resource://gre/modules/ProfileAge.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",
@@ -528,11 +526,9 @@ EnvironmentAddonBuilder.prototype = {
_updateAddons: Task.async(function* () {
this._environment._log.trace("_updateAddons");
let personaId = null;
- if (AppConstants.platform !== "gonk") {
- let theme = LightweightThemeManager.currentTheme;
- if (theme) {
- personaId = theme.id;
- }
+ let theme = LightweightThemeManager.currentTheme;
+ if (theme) {
+ personaId = theme.id;
}
let addons = {
@@ -745,14 +741,8 @@ function EnvironmentCache() {
// until the initial environment has been built.
let p = [];
- if (AppConstants.platform === "gonk") {
- this._addonBuilder = {
- watchForChanges: function() {}
- };
- } else {
- this._addonBuilder = new EnvironmentAddonBuilder(this);
- p = [ this._addonBuilder.init() ];
- }
+ this._addonBuilder = new EnvironmentAddonBuilder(this);
+ p = [ this._addonBuilder.init() ];
this._currentEnvironment.profile = {};
p.push(this._updateProfile());
@@ -1079,10 +1069,6 @@ EnvironmentCache.prototype = {
* @returns null on error, true if we are the default browser, or false otherwise.
*/
_isDefaultBrowser: function () {
- if (AppConstants.platform === "gonk") {
- return true;
- }
-
if (!("@mozilla.org/browser/shell-service;1" in Cc)) {
this._log.info("_isDefaultBrowser - Could not obtain browser shell service");
return null;
@@ -1139,10 +1125,8 @@ EnvironmentCache.prototype = {
userPrefs: this._getPrefData(),
};
- if (AppConstants.platform !== "gonk") {
- this._currentEnvironment.settings.addonCompatibilityCheckEnabled =
- AddonManager.checkCompatibility;
- }
+ this._currentEnvironment.settings.addonCompatibilityCheckEnabled =
+ AddonManager.checkCompatibility;
if (AppConstants.platform !== "android") {
this._currentEnvironment.settings.isDefaultBrowser =
@@ -1246,7 +1230,7 @@ EnvironmentCache.prototype = {
* not a portable device.
*/
_getDeviceData: function () {
- if (!["gonk", "android"].includes(AppConstants.platform)) {
+ if (!["android"].includes(AppConstants.platform)) {
return null;
}
@@ -1269,7 +1253,7 @@ EnvironmentCache.prototype = {
locale: forceToStringOrNull(getSystemLocale()),
};
- if (["gonk", "android"].includes(AppConstants.platform)) {
+ if (["android"].includes(AppConstants.platform)) {
data.kernelVersion = forceToStringOrNull(getSysinfoProperty("kernel_version", null));
} else if (AppConstants.platform === "win") {
// The path to the "UBR" key, queried to get additional version details on Windows.
@@ -1333,7 +1317,7 @@ EnvironmentCache.prototype = {
features: {},
};
- if (!["gonk", "android", "linux"].includes(AppConstants.platform)) {
+ if (!["android", "linux"].includes(AppConstants.platform)) {
let gfxInfo = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo);
try {
gfxData.monitors = gfxInfo.getMonitors();
@@ -1398,7 +1382,7 @@ EnvironmentCache.prototype = {
if (AppConstants.platform === "win") {
data.isWow64 = getSysinfoProperty("isWow64", null);
- } else if (["gonk", "android"].includes(AppConstants.platform)) {
+ } else if (["android"].includes(AppConstants.platform)) {
data.device = this._getDeviceData();
}
diff --git a/toolkit/components/telemetry/TelemetryHistogram.cpp b/toolkit/components/telemetry/TelemetryHistogram.cpp
index abae9c613..ba0288979 100644
--- a/toolkit/components/telemetry/TelemetryHistogram.cpp
+++ b/toolkit/components/telemetry/TelemetryHistogram.cpp
@@ -583,7 +583,7 @@ internal_GetHistogramByName(const nsACString &name, Histogram **ret)
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
/**
* This clones a histogram |existing| with the id |existingId| to a
@@ -684,7 +684,7 @@ internal_HistogramAdd(Histogram& histogram, int32_t value, uint32_t dataset)
return NS_OK;
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
if (Histogram* subsession = internal_GetSubsessionHistogram(histogram)) {
subsession->Add(value);
}
@@ -729,7 +729,7 @@ internal_HistogramClear(Histogram& aHistogram, bool onlySubsession)
aHistogram.Clear();
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
if (Histogram* subsession = internal_GetSubsessionHistogram(aHistogram)) {
subsession->Clear();
}
@@ -926,7 +926,7 @@ private:
typedef nsBaseHashtableET<nsCStringHashKey, Histogram*> KeyedHistogramEntry;
typedef AutoHashtable<KeyedHistogramEntry> KeyedHistogramMapType;
KeyedHistogramMapType mHistogramMap;
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
KeyedHistogramMapType mSubsessionMap;
#endif
@@ -950,7 +950,7 @@ KeyedHistogram::KeyedHistogram(const nsACString &name,
uint32_t min, uint32_t max,
uint32_t bucketCount, uint32_t dataset)
: mHistogramMap()
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
, mSubsessionMap()
#endif
, mName(name)
@@ -968,7 +968,7 @@ nsresult
KeyedHistogram::GetHistogram(const nsCString& key, Histogram** histogram,
bool subsession)
{
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
KeyedHistogramMapType& map = subsession ? mSubsessionMap : mHistogramMap;
#else
KeyedHistogramMapType& map = mHistogramMap;
@@ -980,7 +980,7 @@ KeyedHistogram::GetHistogram(const nsCString& key, Histogram** histogram,
}
nsCString histogramName;
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
if (subsession) {
histogramName.AppendLiteral(SUBSESSION_HISTOGRAM_PREFIX);
}
@@ -1042,7 +1042,7 @@ KeyedHistogram::Add(const nsCString& key, uint32_t sample)
if (!histogram) {
return NS_ERROR_FAILURE;
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
Histogram* subsession = GetHistogram(key, true);
MOZ_ASSERT(subsession);
if (!subsession) {
@@ -1055,7 +1055,7 @@ KeyedHistogram::Add(const nsCString& key, uint32_t sample)
}
histogram->Add(sample);
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
subsession->Add(sample);
#endif
return NS_OK;
@@ -1068,7 +1068,7 @@ KeyedHistogram::Clear(bool onlySubsession)
if (!XRE_IsParentProcess()) {
return;
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
for (auto iter = mSubsessionMap.Iter(); !iter.Done(); iter.Next()) {
iter.Get()->mData->Clear();
}
@@ -1137,7 +1137,7 @@ nsresult
KeyedHistogram::GetJSSnapshot(JSContext* cx, JS::Handle<JSObject*> obj,
bool subsession, bool clearSubsession)
{
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
KeyedHistogramMapType& map = subsession ? mSubsessionMap : mHistogramMap;
#else
KeyedHistogramMapType& map = mHistogramMap;
@@ -1146,7 +1146,7 @@ KeyedHistogram::GetJSSnapshot(JSContext* cx, JS::Handle<JSObject*> obj,
return NS_ERROR_FAILURE;
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
if (subsession && clearSubsession) {
Clear(true);
}
@@ -1637,7 +1637,7 @@ internal_JSHistogram_Clear(JSContext *cx, unsigned argc, JS::Value *vp)
}
bool onlySubsession = false;
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
if (args.length() >= 1) {
@@ -1874,7 +1874,7 @@ internal_JSKeyedHistogram_Snapshot(JSContext *cx, unsigned argc, JS::Value *vp)
return internal_KeyedHistogram_SnapshotImpl(cx, argc, vp, false, false);
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
bool
internal_JSKeyedHistogram_SubsessionSnapshot(JSContext *cx,
unsigned argc, JS::Value *vp)
@@ -1883,7 +1883,7 @@ internal_JSKeyedHistogram_SubsessionSnapshot(JSContext *cx,
}
#endif
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
bool
internal_JSKeyedHistogram_SnapshotSubsessionAndClear(JSContext *cx,
unsigned argc,
@@ -1911,7 +1911,7 @@ internal_JSKeyedHistogram_Clear(JSContext *cx, unsigned argc, JS::Value *vp)
return false;
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
bool onlySubsession = false;
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
@@ -1974,7 +1974,7 @@ internal_WrapAndReturnKeyedHistogram(KeyedHistogram *h, JSContext *cx,
if (!(JS_DefineFunction(cx, obj, "add", internal_JSKeyedHistogram_Add, 2, 0)
&& JS_DefineFunction(cx, obj, "snapshot",
internal_JSKeyedHistogram_Snapshot, 1, 0)
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
&& JS_DefineFunction(cx, obj, "subsessionSnapshot",
internal_JSKeyedHistogram_SubsessionSnapshot, 1, 0)
&& JS_DefineFunction(cx, obj, "snapshotSubsessionAndClear",
@@ -2425,7 +2425,7 @@ TelemetryHistogram::CreateHistogramSnapshots(JSContext *cx,
}
Histogram* original = h;
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
if (subsession) {
h = internal_GetSubsessionHistogram(*h);
if (!h) {
@@ -2453,7 +2453,7 @@ TelemetryHistogram::CreateHistogramSnapshots(JSContext *cx,
}
}
-#if !defined(MOZ_WIDGET_GONK) && !defined(MOZ_WIDGET_ANDROID)
+#if !defined(MOZ_WIDGET_ANDROID)
if (subsession && clearSubsession) {
h->Clear();
}
diff --git a/toolkit/components/telemetry/TelemetrySession.jsm b/toolkit/components/telemetry/TelemetrySession.jsm
index 3d97dc155..179e6436a 100644
--- a/toolkit/components/telemetry/TelemetrySession.jsm
+++ b/toolkit/components/telemetry/TelemetrySession.jsm
@@ -1372,7 +1372,7 @@ var Impl = {
let payload;
try {
- const isMobile = ["gonk", "android"].includes(AppConstants.platform);
+ const isMobile = ["android"].includes(AppConstants.platform);
const isSubsession = isMobile ? false : !this._isClassicReason(reason);
if (isMobile) {
diff --git a/toolkit/components/telemetry/TelemetryStorage.jsm b/toolkit/components/telemetry/TelemetryStorage.jsm
index 91cfc993d..c844aacf0 100644
--- a/toolkit/components/telemetry/TelemetryStorage.jsm
+++ b/toolkit/components/telemetry/TelemetryStorage.jsm
@@ -106,7 +106,7 @@ PingParseError.prototype.constructor = PingParseError;
var Policy = {
now: () => new Date(),
getArchiveQuota: () => ARCHIVE_QUOTA_BYTES,
- getPendingPingsQuota: () => (AppConstants.platform in ["android", "gonk"])
+ getPendingPingsQuota: () => (AppConstants.platform in ["android"])
? PENDING_PINGS_QUOTA_BYTES_MOBILE
: PENDING_PINGS_QUOTA_BYTES_DESKTOP,
};
diff --git a/toolkit/components/telemetry/tests/unit/head.js b/toolkit/components/telemetry/tests/unit/head.js
index 51be25766..87afd3617 100644
--- a/toolkit/components/telemetry/tests/unit/head.js
+++ b/toolkit/components/telemetry/tests/unit/head.js
@@ -20,7 +20,7 @@ XPCOMUtils.defineLazyModuleGetter(this, "OS",
const gIsWindows = AppConstants.platform == "win";
const gIsMac = AppConstants.platform == "macosx";
const gIsAndroid = AppConstants.platform == "android";
-const gIsGonk = AppConstants.platform == "gonk";
+const gIsGonk = false;
const gIsLinux = AppConstants.platform == "linux";
const Telemetry = Cc["@mozilla.org/base/telemetry;1"].getService(Ci.nsITelemetry);
diff --git a/toolkit/components/viewsource/content/viewSource-content.js b/toolkit/components/viewsource/content/viewSource-content.js
index fa1dd19f1..70d23eaa4 100644
--- a/toolkit/components/viewsource/content/viewSource-content.js
+++ b/toolkit/components/viewsource/content/viewSource-content.js
@@ -330,6 +330,8 @@ var ViewSourceContent = {
.createInstance(Ci.nsISHEntry);
shEntry.setURI(BrowserUtils.makeURI(viewSrcURL, null, null));
shEntry.setTitle(viewSrcURL);
+ let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal();
+ shEntry.triggeringPrincipal = systemPrincipal;
shEntry.loadType = Ci.nsIDocShellLoadInfo.loadHistory;
shEntry.cacheKey = shEntrySource.cacheKey;
docShell.QueryInterface(Ci.nsIWebNavigation)
diff --git a/toolkit/components/webextensions/.eslintrc.js b/toolkit/components/webextensions/.eslintrc.js
index 70196fc6a..70f91ab6d 100644
--- a/toolkit/components/webextensions/.eslintrc.js
+++ b/toolkit/components/webextensions/.eslintrc.js
@@ -173,9 +173,6 @@ module.exports = { // eslint-disable-line no-undef
// No reassigning native JS objects
"no-native-reassign": "error",
- // No (!foo in bar)
- "no-negated-in-lhs": "error",
-
// Nested ternary statements are confusing
"no-nested-ternary": "error",
diff --git a/toolkit/content/aboutSupport.js b/toolkit/content/aboutSupport.js
index e9087dfcb..7209b7ad0 100644
--- a/toolkit/content/aboutSupport.js
+++ b/toolkit/content/aboutSupport.js
@@ -497,26 +497,7 @@ var snapshotFormatters = {
$("prefs-user-js-section").style.display = "";
// Clear the no-copy class
$("prefs-user-js-section").className = "";
- },
-
- sandbox: function sandbox(data) {
- if (!AppConstants.MOZ_SANDBOX)
- return;
-
- let strings = stringBundle();
- let tbody = $("sandbox-tbody");
- for (let key in data) {
- // Simplify the display a little in the common case.
- if (key === "hasPrivilegedUserNamespaces" &&
- data[key] === data["hasUserNamespaces"]) {
- continue;
- }
- tbody.appendChild($.new("tr", [
- $.new("th", strings.GetStringFromName(key), "column"),
- $.new("td", data[key])
- ]));
- }
- },
+ }
};
var $ = document.getElementById.bind(document);
diff --git a/toolkit/content/aboutSupport.xhtml b/toolkit/content/aboutSupport.xhtml
index 9574365a3..a92dcfb4a 100644
--- a/toolkit/content/aboutSupport.xhtml
+++ b/toolkit/content/aboutSupport.xhtml
@@ -475,20 +475,6 @@
</tbody>
</table>
-
- <!-- - - - - - - - - - - - - - - - - - - - - -->
-
-#if defined(MOZ_SANDBOX)
- <h2 class="major-section" id="sandbox">
- &aboutSupport.sandboxTitle;
- </h2>
-
- <table>
- <tbody id="sandbox-tbody">
- </tbody>
- </table>
-#endif
-
</div>
</body>
diff --git a/toolkit/content/license.html b/toolkit/content/license.html
index 45889a191..a348fdfa6 100644
--- a/toolkit/content/license.html
+++ b/toolkit/content/license.html
@@ -103,7 +103,6 @@
<li><a href="about:license#icu">ICU License</a></li>
<li><a href="about:license#immutable">Immutable.js License</a></li>
<li><a href="about:license#jpnic">Japan Network Information Center License</a></li>
- <li><a href="about:license#jemalloc">jemalloc License</a></li>
<li><a href="about:license#jquery">jQuery License</a></li>
<li><a href="about:license#k_exp">k_exp License</a></li>
<li><a href="about:license#khronos">Khronos group License</a></li>
@@ -3527,46 +3526,6 @@ Chiyoda-ku, Tokyo 101-0047, Japan.
<hr>
- <h1><a id="jemalloc"></a>jemalloc License</h1>
-
- <p>This license applies to files in the directories
- <span class="path">memory/mozjemalloc/</span> and
- <span class="path">memory/jemalloc/</span>.
- </p>
-
-<pre>
-Copyright (C) 2002-2012 Jason Evans &lt;jasone@canonware.com&gt;.
-All rights reserved.
-Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved.
-Copyright (C) 2009-2012 Facebook, Inc. 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(s), this list of conditions and the following disclaimer as
- the first lines of this file unmodified other than the possible
- addition of one or more copyright notices.
-2. Redistributions in binary form must reproduce the above copyright
- notice(s), 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 COPYRIGHT HOLDER(S) ``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(S) 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.
-</pre>
-
- <hr>
-
<h1><a id="jquery"></a>jQuery License</h1>
<p>This license applies to all copies of jQuery in the code.</p>
diff --git a/toolkit/content/widgets/browser.xml b/toolkit/content/widgets/browser.xml
index a5f37b62a..e595c847d 100644
--- a/toolkit/content/widgets/browser.xml
+++ b/toolkit/content/widgets/browser.xml
@@ -135,6 +135,7 @@
aURI = "about:blank";
var aReferrerPolicy = Components.interfaces.nsIHttpChannel.REFERRER_POLICY_DEFAULT;
+ var aTriggeringPrincipal;
// Check for loadURIWithFlags(uri, { ... });
var params = arguments[1];
@@ -144,6 +145,9 @@
if ('referrerPolicy' in params) {
aReferrerPolicy = params.referrerPolicy;
}
+ if ("triggeringPrincipal" in params) {
+ aTriggeringPrincipal = params.triggeringPrincipal;
+ }
aCharset = params.charset;
aPostData = params.postData;
}
@@ -151,7 +155,7 @@
this._wrapURIChangeCall(() =>
this.webNavigation.loadURIWithOptions(
aURI, aFlags, aReferrerURI, aReferrerPolicy,
- aPostData, null, null));
+ aPostData, null, null, aTriggeringPrincipal));
]]>
</body>
</method>
diff --git a/toolkit/content/widgets/datetimepopup.xml b/toolkit/content/widgets/datetimepopup.xml
index b4335e1ce..19e7b4f8a 100644
--- a/toolkit/content/widgets/datetimepopup.xml
+++ b/toolkit/content/widgets/datetimepopup.xml
@@ -26,8 +26,8 @@
this.l10n = {};
const mozIntl = Components.classes["@mozilla.org/mozintl;1"]
.getService(Components.interfaces.mozIMozIntl);
- mozIntl.addGetCalendarInfo(l10n);
- mozIntl.addGetDisplayNames(l10n);
+ mozIntl.addGetCalendarInfo(this.l10n);
+ mozIntl.addGetDisplayNames(this.l10n);
// Notify DateTimePickerHelper.jsm that binding is ready.
this.dispatchEvent(new CustomEvent("DateTimePickerBindingReady"));
]]></constructor>
diff --git a/toolkit/crashreporter/crashreporter.mozbuild b/toolkit/crashreporter/crashreporter.mozbuild
index b8c639175..a9824517c 100644
--- a/toolkit/crashreporter/crashreporter.mozbuild
+++ b/toolkit/crashreporter/crashreporter.mozbuild
@@ -21,7 +21,4 @@ elif CONFIG['GNU_CXX']:
if CONFIG['CLANG_CXX']:
CXXFLAGS += ['-Wno-implicit-fallthrough']
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DEFINES['ELFSIZE'] = 32
-
DEFINES['NO_STABS_SUPPORT'] = True
diff --git a/toolkit/crashreporter/google-breakpad/src/client/linux/moz.build b/toolkit/crashreporter/google-breakpad/src/client/linux/moz.build
index 71a438940..9bb8bace3 100644
--- a/toolkit/crashreporter/google-breakpad/src/client/linux/moz.build
+++ b/toolkit/crashreporter/google-breakpad/src/client/linux/moz.build
@@ -32,7 +32,4 @@ if CONFIG['OS_TARGET'] == 'Android' and CONFIG['CPU_ARCH'] == 'x86':
# The NDK's user.h defines this struct with a different name.
DEFINES['user_fpxregs_struct'] = 'user_fxsr_struct'
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- DEFINES['getcontext'] = 'breakpad_getcontext'
-
include('/toolkit/crashreporter/crashreporter.mozbuild')
diff --git a/toolkit/crashreporter/nsExceptionHandler.cpp b/toolkit/crashreporter/nsExceptionHandler.cpp
index 1e0743192..0d1286bdc 100644
--- a/toolkit/crashreporter/nsExceptionHandler.cpp
+++ b/toolkit/crashreporter/nsExceptionHandler.cpp
@@ -1527,11 +1527,9 @@ nsresult SetExceptionHandler(nsIFile* aXREDirectory,
if (gExceptionHandler)
return NS_ERROR_ALREADY_INITIALIZED;
-#if !defined(DEBUG) || defined(MOZ_WIDGET_GONK)
+#if !defined(DEBUG)
// In non-debug builds, enable the crash reporter by default, and allow
// disabling it with the MOZ_CRASHREPORTER_DISABLE environment variable.
- // Also enable it by default in debug gonk builds as it is difficult to
- // set environment on startup.
const char *envvar = PR_GetEnv("MOZ_CRASHREPORTER_DISABLE");
if (envvar && *envvar && !force)
return NS_OK;
@@ -1543,10 +1541,7 @@ nsresult SetExceptionHandler(nsIFile* aXREDirectory,
return NS_OK;
#endif
-#if defined(MOZ_WIDGET_GONK)
- doReport = false;
- headlessClient = true;
-#elif defined(XP_WIN)
+#if defined(XP_WIN)
doReport = ShouldReport();
#else
// this environment variable prevents us from launching
@@ -3417,22 +3412,10 @@ OOPInit()
#if (defined(XP_WIN) || defined(XP_MACOSX))
nsCOMPtr<nsIFile> tmpDir;
-# if defined(MOZ_CONTENT_SANDBOX)
- nsresult rv = NS_GetSpecialDirectory(NS_APP_CONTENT_PROCESS_TEMP_DIR,
- getter_AddRefs(tmpDir));
- if (NS_FAILED(rv) && PR_GetEnv("XPCSHELL_TEST_PROFILE_DIR")) {
- // Temporary hack for xpcshell, will be fixed in bug 1257098
- rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tmpDir));
- }
- if (NS_SUCCEEDED(rv)) {
- childProcessTmpDir = CreatePathFromFile(tmpDir);
- }
-# else
if (NS_SUCCEEDED(NS_GetSpecialDirectory(NS_OS_TEMP_DIR,
getter_AddRefs(tmpDir)))) {
childProcessTmpDir = CreatePathFromFile(tmpDir);
}
-# endif // defined(MOZ_CONTENT_SANDBOX)
#endif // (defined(XP_WIN) || defined(XP_MACOSX))
#if defined(XP_WIN)
diff --git a/toolkit/identity/FirefoxAccounts.jsm b/toolkit/identity/FirefoxAccounts.jsm
index 54efaf3b4..1d2ed0439 100644
--- a/toolkit/identity/FirefoxAccounts.jsm
+++ b/toolkit/identity/FirefoxAccounts.jsm
@@ -35,18 +35,11 @@ var log = Log.repository.getLogger("Identity.FxAccounts");
log.level = LOG_LEVEL;
log.addAppender(new Log.ConsoleAppender(new Log.BasicFormatter()));
-#ifdef MOZ_B2G
-XPCOMUtils.defineLazyModuleGetter(this, "FxAccountsManager",
- "resource://gre/modules/FxAccountsManager.jsm",
- "FxAccountsManager");
-Cu.import("resource://gre/modules/FxAccountsCommon.js");
-#else
-log.warn("The FxAccountsManager is only functional in B2G at this time.");
+log.warn("The FxAccountsManager has been removed.");
var FxAccountsManager = null;
var ONVERIFIED_NOTIFICATION = null;
var ONLOGIN_NOTIFICATION = null;
var ONLOGOUT_NOTIFICATION = null;
-#endif
function FxAccountsService() {
Services.obs.addObserver(this, "quit-application-granted", false);
diff --git a/toolkit/identity/tests/unit/xpcshell.ini b/toolkit/identity/tests/unit/xpcshell.ini
index 8ef9b79bc..38b37402c 100644
--- a/toolkit/identity/tests/unit/xpcshell.ini
+++ b/toolkit/identity/tests/unit/xpcshell.ini
@@ -1,7 +1,7 @@
[DEFAULT]
head = head_identity.js
tail = tail_identity.js
-skip-if = (appname != "b2g" || toolkit == 'gonk')
+skip-if = true
support-files =
data/idp_1/.well-known/browserid
data/idp_invalid_1/.well-known/browserid
diff --git a/toolkit/jetpack/dev/volcan.js b/toolkit/jetpack/dev/volcan.js
index 6a68ed12d..7ec208eec 100644
--- a/toolkit/jetpack/dev/volcan.js
+++ b/toolkit/jetpack/dev/volcan.js
@@ -139,7 +139,7 @@ var Client = Class({
.then(this.onReady.bind(this, this.root), this.onFail);
} else {
var actor = this.get(packet.from) || this.root;
- var event = actor.events[packet.type];
+ event = actor.events[packet.type];
if (event) {
var message = new MessageEvent(packet.type, {
data: event.read(packet)
diff --git a/toolkit/jetpack/moz.build b/toolkit/jetpack/moz.build
index 2e5dbe5e8..22be010d6 100644
--- a/toolkit/jetpack/moz.build
+++ b/toolkit/jetpack/moz.build
@@ -12,116 +12,115 @@ EXTRA_JS_MODULES.sdk.system += [
'modules/system/Startup.js',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] != "gonk":
- EXTRA_JS_MODULES.commonjs.method.test += [
- 'method/test/browser.js',
- 'method/test/common.js',
- ]
+EXTRA_JS_MODULES.commonjs.method.test += [
+ 'method/test/browser.js',
+ 'method/test/common.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.deprecated += [
- 'sdk/deprecated/api-utils.js',
- 'sdk/deprecated/sync-worker.js',
- 'sdk/deprecated/unit-test-finder.js',
- 'sdk/deprecated/unit-test.js',
- 'sdk/deprecated/window-utils.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.deprecated += [
+ 'sdk/deprecated/api-utils.js',
+ 'sdk/deprecated/sync-worker.js',
+ 'sdk/deprecated/unit-test-finder.js',
+ 'sdk/deprecated/unit-test.js',
+ 'sdk/deprecated/window-utils.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.frame += [
- 'sdk/frame/hidden-frame.js',
- 'sdk/frame/utils.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.frame += [
+ 'sdk/frame/hidden-frame.js',
+ 'sdk/frame/utils.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.panel += [
- 'sdk/panel/events.js',
- 'sdk/panel/utils.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.panel += [
+ 'sdk/panel/events.js',
+ 'sdk/panel/utils.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.places += [
- 'sdk/places/bookmarks.js',
- 'sdk/places/contract.js',
- 'sdk/places/events.js',
- 'sdk/places/favicon.js',
- 'sdk/places/history.js',
- 'sdk/places/utils.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.places += [
+ 'sdk/places/bookmarks.js',
+ 'sdk/places/contract.js',
+ 'sdk/places/events.js',
+ 'sdk/places/favicon.js',
+ 'sdk/places/history.js',
+ 'sdk/places/utils.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.places.host += [
- 'sdk/places/host/host-bookmarks.js',
- 'sdk/places/host/host-query.js',
- 'sdk/places/host/host-tags.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.places.host += [
+ 'sdk/places/host/host-bookmarks.js',
+ 'sdk/places/host/host-query.js',
+ 'sdk/places/host/host-tags.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.tabs += [
- 'sdk/tabs/common.js',
- 'sdk/tabs/events.js',
- 'sdk/tabs/helpers.js',
- 'sdk/tabs/namespace.js',
- 'sdk/tabs/observer.js',
- 'sdk/tabs/tab-fennec.js',
- 'sdk/tabs/tab-firefox.js',
- 'sdk/tabs/tab.js',
- 'sdk/tabs/tabs-firefox.js',
- 'sdk/tabs/utils.js',
- 'sdk/tabs/worker.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.tabs += [
+ 'sdk/tabs/common.js',
+ 'sdk/tabs/events.js',
+ 'sdk/tabs/helpers.js',
+ 'sdk/tabs/namespace.js',
+ 'sdk/tabs/observer.js',
+ 'sdk/tabs/tab-fennec.js',
+ 'sdk/tabs/tab-firefox.js',
+ 'sdk/tabs/tab.js',
+ 'sdk/tabs/tabs-firefox.js',
+ 'sdk/tabs/utils.js',
+ 'sdk/tabs/worker.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.test += [
- 'sdk/test/assert.js',
- 'sdk/test/harness.js',
- 'sdk/test/httpd.js',
- 'sdk/test/loader.js',
- 'sdk/test/memory.js',
- 'sdk/test/options.js',
- 'sdk/test/runner.js',
- 'sdk/test/utils.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.test += [
+ 'sdk/test/assert.js',
+ 'sdk/test/harness.js',
+ 'sdk/test/httpd.js',
+ 'sdk/test/loader.js',
+ 'sdk/test/memory.js',
+ 'sdk/test/options.js',
+ 'sdk/test/runner.js',
+ 'sdk/test/utils.js',
+]
+
+EXTRA_JS_MODULES.commonjs.sdk.ui += [
+ 'sdk/ui/component.js',
+ 'sdk/ui/frame.js',
+ 'sdk/ui/id.js',
+ 'sdk/ui/sidebar.js',
+ 'sdk/ui/state.js',
+ 'sdk/ui/toolbar.js',
+]
+if CONFIG['MC_PALEMOON']:
EXTRA_JS_MODULES.commonjs.sdk.ui += [
- 'sdk/ui/component.js',
- 'sdk/ui/frame.js',
- 'sdk/ui/id.js',
- 'sdk/ui/sidebar.js',
- 'sdk/ui/state.js',
- 'sdk/ui/toolbar.js',
+ 'sdk/ui/buttons.js',
]
- if CONFIG['MC_PALEMOON']:
- EXTRA_JS_MODULES.commonjs.sdk.ui += [
- 'sdk/ui/buttons.js',
- ]
-
- EXTRA_JS_MODULES.commonjs.sdk.ui.button += [
- 'sdk/ui/button/action.js',
- 'sdk/ui/button/contract.js',
- 'sdk/ui/button/toggle.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.ui.button += [
+ 'sdk/ui/button/action.js',
+ 'sdk/ui/button/contract.js',
+ 'sdk/ui/button/toggle.js',
+]
- EXTRA_PP_JS_MODULES.commonjs.sdk.ui.button += [
- 'sdk/ui/button/view.js',
- ]
+EXTRA_PP_JS_MODULES.commonjs.sdk.ui.button += [
+ 'sdk/ui/button/view.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.ui.sidebar += [
- 'sdk/ui/sidebar/actions.js',
- 'sdk/ui/sidebar/contract.js',
- 'sdk/ui/sidebar/namespace.js',
- 'sdk/ui/sidebar/utils.js',
- 'sdk/ui/sidebar/view.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.ui.sidebar += [
+ 'sdk/ui/sidebar/actions.js',
+ 'sdk/ui/sidebar/contract.js',
+ 'sdk/ui/sidebar/namespace.js',
+ 'sdk/ui/sidebar/utils.js',
+ 'sdk/ui/sidebar/view.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.window += [
- 'sdk/window/browser.js',
- 'sdk/window/events.js',
- 'sdk/window/helpers.js',
- 'sdk/window/namespace.js',
- 'sdk/window/utils.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.window += [
+ 'sdk/window/browser.js',
+ 'sdk/window/events.js',
+ 'sdk/window/helpers.js',
+ 'sdk/window/namespace.js',
+ 'sdk/window/utils.js',
+]
- EXTRA_JS_MODULES.commonjs.sdk.windows += [
- 'sdk/windows/fennec.js',
- 'sdk/windows/firefox.js',
- 'sdk/windows/observer.js',
- 'sdk/windows/tabs-fennec.js',
- ]
+EXTRA_JS_MODULES.commonjs.sdk.windows += [
+ 'sdk/windows/fennec.js',
+ 'sdk/windows/firefox.js',
+ 'sdk/windows/observer.js',
+ 'sdk/windows/tabs-fennec.js',
+]
EXTRA_JS_MODULES.commonjs += [
'index.js',
diff --git a/toolkit/jetpack/sdk/lang/weak-set.js b/toolkit/jetpack/sdk/lang/weak-set.js
index 8972602a5..0b81a395b 100644
--- a/toolkit/jetpack/sdk/lang/weak-set.js
+++ b/toolkit/jetpack/sdk/lang/weak-set.js
@@ -2,12 +2,12 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+"use strict";
+
module.metadata = {
"stability": "experimental"
};
-"use strict";
-
const { Cu } = require("chrome");
function makeGetterFor(Type) {
diff --git a/toolkit/jetpack/sdk/ui/buttons.js b/toolkit/jetpack/sdk/ui/buttons.js
index 66e0fd742..6aaed3865 100644
--- a/toolkit/jetpack/sdk/ui/buttons.js
+++ b/toolkit/jetpack/sdk/ui/buttons.js
@@ -50,7 +50,7 @@ function insertButton(aWindow, id, onBuild) {
let toolbar = toolbarId != "" && doc.getElementById(toolbarId);
if (toolbar) {
- let nextItem = doc.getElementById(nextItemId);
+ let nextItem = nextItemId != "" && doc.getElementById(nextItemId);
// If nextItem not in toolbar then retrieve it by reading currentset attribute
if (!(nextItem && nextItem.parentNode && nextItem.parentNode.id == toolbarId)) {
nextItem = null;
diff --git a/toolkit/library/moz.build b/toolkit/library/moz.build
index 556b779dd..102ebb44b 100644
--- a/toolkit/library/moz.build
+++ b/toolkit/library/moz.build
@@ -204,11 +204,6 @@ if CONFIG['OS_ARCH'] == 'WINNT':
'winspool',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- OS_LIBS += [
- 'dbus',
- ]
-
if CONFIG['OS_ARCH'] == 'Linux' and CONFIG['OS_TARGET'] != 'Android':
OS_LIBS += [
'rt',
@@ -252,35 +247,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':
'GLESv2',
]
-if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- OS_LIBS += [
- 'ui',
- 'media',
- 'hardware_legacy',
- 'hardware',
- 'utils',
- 'cutils',
- 'sysutils',
- 'camera_client',
- 'sensorservice',
- 'stagefright',
- 'stagefright_foundation',
- 'stagefright_omx',
- 'binder',
- 'gui',
- 'mtp',
- ]
-
- if int(CONFIG['ANDROID_VERSION']) >= 17:
- OS_LIBS += [
- 'sync',
- ]
-
- if CONFIG['ANDROID_VERSION'] >= '16':
- OS_LIBS += [
- 'mdnssd',
- ]
-
if 'rtsp' in CONFIG['NECKO_PROTOCOLS']:
OS_LIBS += [
'stagefright_foundation',
diff --git a/toolkit/locales/en-US/chrome/global/aboutSupport.dtd b/toolkit/locales/en-US/chrome/global/aboutSupport.dtd
index 9f64ef0f1..8459300c5 100644
--- a/toolkit/locales/en-US/chrome/global/aboutSupport.dtd
+++ b/toolkit/locales/en-US/chrome/global/aboutSupport.dtd
@@ -109,8 +109,6 @@ variant of aboutSupport.showDir.label. -->
<!ENTITY aboutSupport.copyTextToClipboard.label "Copy text to clipboard">
<!ENTITY aboutSupport.copyRawDataToClipboard.label "Copy raw data to clipboard">
-<!ENTITY aboutSupport.sandboxTitle "Sandbox">
-
<!ENTITY aboutSupport.safeModeTitle "Try Safe Mode">
<!ENTITY aboutSupport.restartInSafeMode.label "Restart with Add-ons Disabled…">
diff --git a/toolkit/locales/en-US/chrome/global/aboutSupport.properties b/toolkit/locales/en-US/chrome/global/aboutSupport.properties
index 41501c01b..0bc612b79 100644
--- a/toolkit/locales/en-US/chrome/global/aboutSupport.properties
+++ b/toolkit/locales/en-US/chrome/global/aboutSupport.properties
@@ -91,14 +91,6 @@ gpuProcessKillButton = Terminate GPU Process
minLibVersions = Expected minimum version
loadedLibVersions = Version in use
-hasSeccompBPF = Seccomp-BPF (System Call Filtering)
-hasSeccompTSync = Seccomp Thread Synchronization
-hasUserNamespaces = User Namespaces
-hasPrivilegedUserNamespaces = User Namespaces for privileged processes
-canSandboxContent = Content Process Sandboxing
-canSandboxMedia = Media Plugin Sandboxing
-contentSandboxLevel = Content Process Sandbox Level
-
# LOCALIZATION NOTE %1$S and %2$S will be replaced with the number of remote and the total number
# of windows, respectively, while %3$S will be replaced with one of the status strings below,
# which contains a description of the multi-process preference and status.
diff --git a/toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd b/toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd
index c74fdeb2f..febc18dfd 100644
--- a/toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd
+++ b/toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd
@@ -1,6 +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/. -->
+
<!ENTITY addons.windowTitle "Add-ons Manager">
<!ENTITY search.placeholder "Search all add-ons">
@@ -210,7 +211,7 @@
<!ENTITY addon.loadingReleaseNotes.label "Loading…">
<!ENTITY addon.errorLoadingReleaseNotes.label "Sorry, but there was an error loading the release notes.">
-<!ENTITY addon.nativeAddon "This add-on directly targets Pale Moon">
+<!ENTITY addon.nativeAddon "This add-on directly targets &brandFullName;">
<!ENTITY addon.compatAddon "This add-on targets Mozilla Firefox and runs in compatibility mode">
<!ENTITY addon.createdBy.label "By ">
diff --git a/toolkit/modules/AppConstants.jsm b/toolkit/modules/AppConstants.jsm
index 2b18f3c1a..a0ca00935 100644
--- a/toolkit/modules/AppConstants.jsm
+++ b/toolkit/modules/AppConstants.jsm
@@ -81,20 +81,6 @@ this.AppConstants = Object.freeze({
false,
#endif
- MOZ_SANDBOX:
-#ifdef MOZ_SANDBOX
- true,
-#else
- false,
-#endif
-
- MOZ_CONTENT_SANDBOX:
-#ifdef MOZ_CONTENT_SANDBOX
- true,
-#else
- false,
-#endif
-
MOZ_TELEMETRY_REPORTING:
#ifdef MOZ_TELEMETRY_REPORTING
true,
@@ -144,14 +130,6 @@ this.AppConstants = Object.freeze({
false,
#endif
-# MOZ_B2G covers both device and desktop b2g
- MOZ_B2G:
-#ifdef MOZ_B2G
- true,
-#else
- false,
-#endif
-
XP_UNIX:
#ifdef XP_UNIX
true,
@@ -170,8 +148,6 @@ this.AppConstants = Object.freeze({
"macosx",
#elif MOZ_WIDGET_ANDROID
"android",
-#elif MOZ_WIDGET_GONK
- "gonk",
#elif XP_LINUX
"linux",
#else
@@ -218,13 +194,6 @@ this.AppConstants = Object.freeze({
false,
#endif
- MOZ_B2G_RIL:
-#ifdef MOZ_B2G_RIL
- true,
-#else
- false,
-#endif
-
MOZ_GRAPHENE:
#ifdef MOZ_GRAPHENE
true,
@@ -314,8 +283,6 @@ this.AppConstants = Object.freeze({
INSTALL_LOCALE: "@AB_CD@",
MOZ_WIDGET_TOOLKIT: "@MOZ_WIDGET_TOOLKIT@",
ANDROID_PACKAGE_NAME: "@ANDROID_PACKAGE_NAME@",
- MOZ_B2G_VERSION: @MOZ_B2G_VERSION@,
- MOZ_B2G_OS_NAME: @MOZ_B2G_OS_NAME@,
DEBUG_JS_MODULES: "@DEBUG_JS_MODULES@",
diff --git a/toolkit/modules/Sqlite.jsm b/toolkit/modules/Sqlite.jsm
index e8d986c0e..6f7a7d94c 100644
--- a/toolkit/modules/Sqlite.jsm
+++ b/toolkit/modules/Sqlite.jsm
@@ -995,7 +995,7 @@ function cloneStorageConnection(options) {
if (!source) {
throw new TypeError("connection not specified in clone options.");
}
- if (!source instanceof Ci.mozIStorageAsyncConnection) {
+ if (!(source instanceof Ci.mozIStorageAsyncConnection)) {
throw new TypeError("Connection must be a valid Storage connection.");
}
diff --git a/toolkit/modules/Troubleshoot.jsm b/toolkit/modules/Troubleshoot.jsm
index 60f7e8666..e11d47774 100644
--- a/toolkit/modules/Troubleshoot.jsm
+++ b/toolkit/modules/Troubleshoot.jsm
@@ -530,28 +530,3 @@ var dataProviders = {
}
};
-if (AppConstants.MOZ_SANDBOX) {
- dataProviders.sandbox = function sandbox(done) {
- let data = {};
- if (AppConstants.platform == "linux") {
- const keys = ["hasSeccompBPF", "hasSeccompTSync",
- "hasPrivilegedUserNamespaces", "hasUserNamespaces",
- "canSandboxContent", "canSandboxMedia"];
-
- let sysInfo = Cc["@mozilla.org/system-info;1"].
- getService(Ci.nsIPropertyBag2);
- for (let key of keys) {
- if (sysInfo.hasKey(key)) {
- data[key] = sysInfo.getPropertyAsBool(key);
- }
- }
- }
-
- if (AppConstants.MOZ_CONTENT_SANDBOX) {
- data.contentSandboxLevel =
- Services.prefs.getIntPref("security.sandbox.content.level");
- }
-
- done(data);
- }
-}
diff --git a/toolkit/modules/UpdateUtils.jsm b/toolkit/modules/UpdateUtils.jsm
index ef8475364..e92b1b797 100644
--- a/toolkit/modules/UpdateUtils.jsm
+++ b/toolkit/modules/UpdateUtils.jsm
@@ -87,24 +87,6 @@ this.UpdateUtils = {
url = url.replace(/%CUSTOM%/g, Preferences.get(PREF_APP_UPDATE_CUSTOM, ""));
url = url.replace(/\+/g, "%2B");
- if (AppConstants.platform == "gonk") {
- let sysLibs = {};
- Cu.import("resource://gre/modules/systemlibs.js", sysLibs);
- let productDevice = sysLibs.libcutils.property_get("ro.product.device");
- let buildType = sysLibs.libcutils.property_get("ro.build.type");
- url = url.replace(/%PRODUCT_MODEL%/g,
- sysLibs.libcutils.property_get("ro.product.model"));
- if (buildType == "user" || buildType == "userdebug") {
- url = url.replace(/%PRODUCT_DEVICE%/g, productDevice);
- } else {
- url = url.replace(/%PRODUCT_DEVICE%/g, productDevice + "-" + buildType);
- }
- url = url.replace(/%B2G_VERSION%/g,
- Preferences.get(PREF_APP_B2G_VERSION, null));
- url = url.replace(/%IMEI%/g,
- Preferences.get(PREF_APP_UPDATE_IMEI_HASH, "default"));
- }
-
return url;
}
};
diff --git a/toolkit/modules/sessionstore/Utils.jsm b/toolkit/modules/sessionstore/Utils.jsm
index 863bca6f5..25b75c71b 100644
--- a/toolkit/modules/sessionstore/Utils.jsm
+++ b/toolkit/modules/sessionstore/Utils.jsm
@@ -16,12 +16,17 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm", this);
XPCOMUtils.defineLazyServiceGetter(this, "serializationHelper",
"@mozilla.org/network/serialization-helper;1",
"nsISerializationHelper");
+XPCOMUtils.defineLazyGetter(this, "SERIALIZED_SYSTEMPRINCIPAL", function() {
+ return Utils.serializePrincipal(Services.scriptSecurityManager.getSystemPrincipal());
+});
function debug(msg) {
Services.console.logStringMessage("Utils: " + msg);
}
this.Utils = Object.freeze({
+ get SERIALIZED_SYSTEMPRINCIPAL() { return SERIALIZED_SYSTEMPRINCIPAL; },
+
makeURI: function (url) {
return Services.io.newURI(url, null, null);
},
diff --git a/toolkit/modules/tests/browser/browser_Troubleshoot.js b/toolkit/modules/tests/browser/browser_Troubleshoot.js
index 34c2a2791..7f0069dc9 100644
--- a/toolkit/modules/tests/browser/browser_Troubleshoot.js
+++ b/toolkit/modules/tests/browser/browser_Troubleshoot.js
@@ -469,10 +469,6 @@ const SNAPSHOT_SCHEMA = {
required: false,
type: "boolean"
},
- contentSandboxLevel: {
- required: AppConstants.MOZ_CONTENT_SANDBOX,
- type: "number"
- },
},
},
},
diff --git a/toolkit/moz.configure b/toolkit/moz.configure
index c1e0880c9..854814292 100644
--- a/toolkit/moz.configure
+++ b/toolkit/moz.configure
@@ -112,8 +112,7 @@ set_config('L10NBASEDIR', l10n_base)
# reason.
option('--enable-default-toolkit', nargs=1,
choices=('cairo-windows', 'cairo-gtk2', 'cairo-gtk2-x11', 'cairo-gtk3',
- 'cairo-cocoa', 'cairo-uikit', 'cairo-android',
- 'cairo-gonk'),
+ 'cairo-cocoa', 'cairo-uikit', 'cairo-android'),
help='Select default toolkit')
@depends('--enable-default-toolkit', target)
@@ -232,7 +231,7 @@ set_define(gl_provider_define, True)
# ==============================================================
@depends(toolkit)
def pdf_printing(toolkit):
- if toolkit in ('windows', 'gtk2', 'gtk3', 'android', 'gonk'):
+ if toolkit in ('windows', 'gtk2', 'gtk3', 'android'):
return True
@depends(pdf_printing)
@@ -254,8 +253,8 @@ option(env='MOZ_INSTRUMENT_EVENT_LOOP',
@depends('MOZ_INSTRUMENT_EVENT_LOOP', toolkit)
def instrument_event_loop(value, toolkit):
- if value or (toolkit in ('windows', 'gtk2', 'gtk3', 'cocoa', 'android',
- 'gonk') and value.origin == 'default'):
+ if value or (toolkit in ('windows', 'gtk2', 'gtk3', 'cocoa',
+ 'android') and value.origin == 'default'):
return True
set_config('MOZ_INSTRUMENT_EVENT_LOOP', instrument_event_loop)
diff --git a/toolkit/mozapps/extensions/AddonManager.jsm b/toolkit/mozapps/extensions/AddonManager.jsm
index 3913c2088..d4c3a6967 100644
--- a/toolkit/mozapps/extensions/AddonManager.jsm
+++ b/toolkit/mozapps/extensions/AddonManager.jsm
@@ -2671,6 +2671,8 @@ this.AddonManager = {
ERROR_CORRUPT_FILE: -3,
// An error occured trying to write to the filesystem.
ERROR_FILE_ACCESS: -4,
+ // The downloaded file seems to be Jetpack.
+ ERROR_JETPACKSDK_FILE: -8,
// The downloaded file seems to be WebExtension.
ERROR_WEBEXT_FILE: -9,
diff --git a/toolkit/mozapps/extensions/AddonPathService.cpp b/toolkit/mozapps/extensions/AddonPathService.cpp
index 006149100..ddfdbe817 100644
--- a/toolkit/mozapps/extensions/AddonPathService.cpp
+++ b/toolkit/mozapps/extensions/AddonPathService.cpp
@@ -128,6 +128,16 @@ AddonPathService::InsertPath(const nsAString& path, const nsAString& addonIdStri
return NS_OK;
}
+NS_IMETHODIMP
+AddonPathService::MapURIToAddonId(nsIURI* aURI, nsAString& addonIdString)
+{
+ if (JSAddonId* id = MapURIToAddonID(aURI)) {
+ JSFlatString* flat = JS_ASSERT_STRING_IS_FLAT(JS::StringOfAddonId(id));
+ AssignJSFlatString(addonIdString, flat);
+ }
+ return NS_OK;
+}
+
static nsresult
ResolveURI(nsIURI* aURI, nsAString& out)
{
diff --git a/toolkit/mozapps/extensions/amIAddonPathService.idl b/toolkit/mozapps/extensions/amIAddonPathService.idl
index 863689858..9c9197a61 100644
--- a/toolkit/mozapps/extensions/amIAddonPathService.idl
+++ b/toolkit/mozapps/extensions/amIAddonPathService.idl
@@ -5,6 +5,8 @@
#include "nsISupports.idl"
+interface nsIURI;
+
/**
* This service maps file system paths where add-ons reside to the ID
* of the add-on. Paths are added by the add-on manager. They can
@@ -26,4 +28,10 @@ interface amIAddonPathService : nsISupports
* associated with the given add-on ID.
*/
void insertPath(in AString path, in AString addonId);
+
+ /**
+ * Given a URI to a file, return the ID of the add-on that the file belongs
+ * to. Returns an empty string if there is no add-on there.
+ */
+ AString mapURIToAddonId(in nsIURI aURI);
};
diff --git a/toolkit/mozapps/extensions/content/extensions.js b/toolkit/mozapps/extensions/content/extensions.js
index 8d9c132e6..fc4392231 100644
--- a/toolkit/mozapps/extensions/content/extensions.js
+++ b/toolkit/mozapps/extensions/content/extensions.js
@@ -18,10 +18,12 @@ Cu.import("resource://gre/modules/addons/AddonRepository.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "PluralForm",
"resource://gre/modules/PluralForm.jsm");
+#ifdef MOZ_DEVTOOLS
XPCOMUtils.defineLazyGetter(this, "BrowserToolboxProcess", function () {
return Cu.import("resource://devtools/client/framework/ToolboxProcess.jsm", {}).
BrowserToolboxProcess;
});
+#endif
const PREF_DISCOVERURL = "extensions.webservice.discoverURL";
const PREF_DISCOVER_ENABLED = "extensions.getAddons.showPane";
@@ -1002,6 +1004,7 @@ var gViewController = {
}
},
+#ifdef MOZ_DEVTOOLS
cmd_debugItem: {
doCommand: function cmd_debugItem_doCommand(aAddon) {
BrowserToolboxProcess.init({ addonID: aAddon.id });
@@ -1015,6 +1018,7 @@ var gViewController = {
return aAddon && aAddon.isDebuggable && debuggerEnabled && remoteEnabled;
}
},
+#endif
cmd_showItemPreferences: {
isEnabled: function cmd_showItemPreferences_isEnabled(aAddon) {
diff --git a/toolkit/mozapps/extensions/content/extensions.xml b/toolkit/mozapps/extensions/content/extensions.xml
index fab340540..cbd05bfa9 100644
--- a/toolkit/mozapps/extensions/content/extensions.xml
+++ b/toolkit/mozapps/extensions/content/extensions.xml
@@ -9,6 +9,8 @@
%extensionsDTD;
<!ENTITY % aboutDTD SYSTEM "chrome://mozapps/locale/extensions/about.dtd">
%aboutDTD;
+<!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd" >
+%brandDTD;
]>
<bindings id="addonBindings"
@@ -855,8 +857,10 @@
<xul:label anonid="name" class="name" crop="end" flex="1"
xbl:inherits="value=name,tooltiptext=name"/>
<xul:label anonid="version" class="version"/>
+#ifdef MOZ_PHOENIX_EXTENSIONS
<xul:label class="nativeIndicator nativeAddon" value="●" tooltiptext="&addon.nativeAddon;"/>
<xul:label class="nativeIndicator compatAddon" value="●" tooltiptext="&addon.compatAddon;"/>
+#endif
<xul:label class="disabled-postfix" value="&addon.disabled.postfix;"/>
<xul:label class="update-postfix" value="&addon.update.postfix;"/>
<xul:spacer flex="5000"/> <!-- Necessary to make the name crop -->
@@ -1362,8 +1366,10 @@
[this.mAddon.name], 1);
} else {
this.removeAttribute("notification");
+#ifdef MOZ_PHOENIX_EXTENSIONS
if (this.mAddon.type == "extension")
this.setAttribute("native", this.mAddon.native);
+#endif
}
}
@@ -1622,11 +1628,13 @@
]]></body>
</method>
+#ifdef MOZ_DEVTOOLS
<method name="debug">
<body><![CDATA[
gViewController.doCommand("cmd_debugItem", this.mAddon);
]]></body>
</method>
+#endif
<method name="showPreferences">
<body><![CDATA[
diff --git a/toolkit/mozapps/extensions/content/extensions.xul b/toolkit/mozapps/extensions/content/extensions.xul
index c1a8edc86..c5eeb534f 100644
--- a/toolkit/mozapps/extensions/content/extensions.xul
+++ b/toolkit/mozapps/extensions/content/extensions.xul
@@ -53,8 +53,10 @@
<menuitem id="menuitem_uninstallItem" command="cmd_uninstallItem"
label="&cmd.uninstallAddon.label;"
accesskey="&cmd.uninstallAddon.accesskey;"/>
+#ifdef MOZ_DEVTOOLS
<menuitem id="menuitem_debugItem" command="cmd_debugItem"
label="&cmd.debugAddon.label;"/>
+#endif
<menuseparator id="addonitem-menuseparator" />
<menuitem id="menuitem_preferences" command="cmd_showItemPreferences"
#ifdef XP_WIN
@@ -101,7 +103,9 @@
<command id="cmd_findItemUpdates"/>
<command id="cmd_showItemPreferences"/>
<command id="cmd_showItemAbout"/>
+#ifdef MOZ_DEVTOOLS
<command id="cmd_debugItem"/>
+#endif
<command id="cmd_enableItem"/>
<command id="cmd_disableItem"/>
<command id="cmd_installItem"/>
@@ -631,9 +635,11 @@
#endif
command="cmd_showItemPreferences"/>
<spacer flex="1"/>
+#ifdef MOZ_DEVTOOLS
<button id="detail-debug-btn" class="addon-control debug"
label="Debug"
command="cmd_debugItem" />
+#endif
<button id="detail-enable-btn" class="addon-control enable"
label="&cmd.enableAddon.label;"
accesskey="&cmd.enableAddon.accesskey;"
diff --git a/toolkit/mozapps/extensions/extensions.manifest b/toolkit/mozapps/extensions/extensions.manifest
index f0f00545f..14aca3ff6 100644
--- a/toolkit/mozapps/extensions/extensions.manifest
+++ b/toolkit/mozapps/extensions/extensions.manifest
@@ -1,7 +1,6 @@
component {66354bc9-7ed1-4692-ae1d-8da97d6b205e} nsBlocklistService.js
contract @mozilla.org/extensions/blocklist;1 {66354bc9-7ed1-4692-ae1d-8da97d6b205e}
category profile-after-change nsBlocklistService @mozilla.org/extensions/blocklist;1
-#ifndef MOZ_WIDGET_GONK
category update-timer nsBlocklistService @mozilla.org/extensions/blocklist;1,getService,blocklist-background-update-timer,extensions.blocklist.interval,86400
component {4399533d-08d1-458c-a87a-235f74451cfa} addonManager.js
contract @mozilla.org/addons/integration;1 {4399533d-08d1-458c-a87a-235f74451cfa}
@@ -17,4 +16,3 @@ category JavaScript-global-property InstallTrigger @mozilla.org/addons/installtr
category addon-provider-module PluginProvider resource://gre/modules/addons/PluginProvider.jsm
#endif
category addon-provider-module GMPProvider resource://gre/modules/addons/GMPProvider.jsm
-#endif
diff --git a/toolkit/mozapps/extensions/internal/AddonUpdateChecker.jsm b/toolkit/mozapps/extensions/internal/AddonUpdateChecker.jsm
index 939e2e269..8d742ea42 100644
--- a/toolkit/mozapps/extensions/internal/AddonUpdateChecker.jsm
+++ b/toolkit/mozapps/extensions/internal/AddonUpdateChecker.jsm
@@ -766,8 +766,17 @@ this.AddonUpdateChecker = {
* down in-progress update requests
*/
checkForUpdates: function AUC_checkForUpdates(aId, aUpdateKey, aUrl, aObserver) {
- // Exclude default theme
- if (aId != "{972ce4c6-7e08-4474-a285-3208198ce6fd}")
+ // Define an array of internally used IDs to NOT send to AUS such as the
+ // Default Theme. Please keep this list in sync with:
+ // toolkit/mozapps/webextensions/AddonUpdateChecker.jsm
+ let internalIDS = [
+ '{972ce4c6-7e08-4474-a285-3208198ce6fd}',
+ 'modern@themes.mozilla.org'
+ ];
+
+ // If the ID is not in the array then go ahead and query AUS
+ if (internalIDS.indexOf(aId) == -1) {
return new UpdateParser(aId, aUpdateKey, aUrl, aObserver);
+ }
}
};
diff --git a/toolkit/mozapps/extensions/internal/XPIProvider.jsm b/toolkit/mozapps/extensions/internal/XPIProvider.jsm
index c43811ba8..5b3585cd8 100644
--- a/toolkit/mozapps/extensions/internal/XPIProvider.jsm
+++ b/toolkit/mozapps/extensions/internal/XPIProvider.jsm
@@ -36,8 +36,10 @@ XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "OS",
"resource://gre/modules/osfile.jsm");
+#ifdef MOZ_DEVTOOLS
XPCOMUtils.defineLazyModuleGetter(this, "BrowserToolboxProcess",
"resource://devtools/client/framework/ToolboxProcess.jsm");
+#endif
XPCOMUtils.defineLazyModuleGetter(this, "ConsoleAPI",
"resource://gre/modules/Console.jsm");
@@ -52,6 +54,10 @@ XPCOMUtils.defineLazyServiceGetter(this,
"ResProtocolHandler",
"@mozilla.org/network/protocol;1?name=resource",
"nsIResProtocolHandler");
+XPCOMUtils.defineLazyServiceGetter(this,
+ "AddonPathService",
+ "@mozilla.org/addon-path-service;1",
+ "amIAddonPathService");
const nsIFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile",
"initWithPath");
@@ -106,6 +112,10 @@ const DIR_TRASH = "trash";
const FILE_DATABASE = "extensions.json";
const FILE_OLD_CACHE = "extensions.cache";
const FILE_INSTALL_MANIFEST = "install.rdf";
+#ifndef MOZ_JETPACK
+const FILE_JETPACK_MANIFEST_1 = "harness-options.json";
+const FILE_JETPACK_MANIFEST_2 = "package.json";
+#endif
const FILE_WEBEXT_MANIFEST = "manifest.json";
const FILE_XPI_ADDONS_LIST = "extensions.ini";
@@ -134,7 +144,9 @@ const FIREFOX_APPCOMPATVERSION = "56.9"
// The value for this is in Makefile.in
#expand const DB_SCHEMA = __MOZ_EXTENSIONS_DB_SCHEMA__;
+#ifdef MOZ_DEVTOOLS
const NOTIFICATION_TOOLBOXPROCESS_LOADED = "ToolboxProcessLoaded";
+#endif
// Properties that exist in the install manifest
const PROP_METADATA = ["id", "version", "type", "internalName", "updateURL",
@@ -1059,37 +1071,36 @@ function loadManifestFromDir(aDir) {
* @throws if the XPI file does not contain a valid install manifest.
* Throws with |webext:true| if a WebExtension manifest was found
* to distinguish between WebExtensions and corrupt files.
+ * Throws with |jetpacksdk:true| if a Jetpack files were found
+ * if Jetpack its self isn't built.
*/
function loadManifestFromZipReader(aZipReader) {
- let zis;
- try {
- zis = aZipReader.getInputStream(FILE_INSTALL_MANIFEST);
- } catch (e) {
- // We're going to throw here, but depending on whether we have a
- // WebExtension manifest in the XPI, we'll throw with the webext flag.
- try {
- let zws = aZipReader.getInputStream(FILE_WEBEXT_MANIFEST);
- zws.close();
- } catch(e2) {
- // We have neither an install manifest nor a WebExtension manifest;
- // this means the extension file has a structural problem.
- // Just pass the original error up the chain in that case.
+ // If WebExtension but not install.rdf throw an error
+ if (aZipReader.hasEntry(FILE_WEBEXT_MANIFEST)) {
+ if (!aZipReader.hasEntry(FILE_INSTALL_MANIFEST)) {
throw {
- name: e.name,
- message: e.message
+ name: "UnsupportedExtension",
+ message: Services.appinfo.name + " does not support WebExtensions",
+ webext: true
};
}
- // If we get here, we have a WebExtension manifest but no install
- // manifest. Pass the error up the chain with the webext flag.
+ }
+
+#ifndef MOZ_JETPACK
+ // If Jetpack is not built throw an error
+ if (aZipReader.hasEntry(FILE_JETPACK_MANIFEST_1) ||
+ aZipReader.hasEntry(FILE_JETPACK_MANIFEST_2)) {
throw {
- name: e.name,
- message: e.message,
- webext: true
+ name: "UnsupportedExtension",
+ message: Services.appinfo.name + " does not support Jetpack Extensions",
+ jetpacksdk: true
};
}
-
- // We found an install manifest, so it's either a regular or hybrid
- // extension. Continue processing.
+#endif
+
+ // Attempt to open install.rdf else throw normally
+ let zis = aZipReader.getInputStream(FILE_INSTALL_MANIFEST);
+ // Create a buffered input stream for install.rdf
let bis = Cc["@mozilla.org/network/buffered-input-stream;1"].
createInstance(Ci.nsIBufferedInputStream);
bis.init(zis, 4096);
@@ -1118,7 +1129,9 @@ function loadManifestFromZipReader(aZipReader) {
return addon;
}
finally {
+ // Close the buffered input stream
bis.close();
+ // Close the input stream to install.rdf
zis.close();
}
}
@@ -1842,8 +1855,10 @@ this.XPIProvider = {
_enabledExperiments: null,
// A Map from an add-on install to its ID
_addonFileMap: new Map(),
+#ifdef MOZ_DEVTOOLS
// Flag to know if ToolboxProcess.jsm has already been loaded by someone or not
_toolboxProcessLoaded: false,
+#endif
// Have we started shutting down bootstrap add-ons?
_closing: false,
@@ -1887,8 +1902,7 @@ this.XPIProvider = {
logger.info("Mapping " + aID + " to " + aFile.path);
this._addonFileMap.set(aID, aFile.path);
- let service = Cc["@mozilla.org/addon-path-service;1"].getService(Ci.amIAddonPathService);
- service.insertPath(aFile.path, aID);
+ AddonPathService.insertPath(aFile.path, aID);
},
/**
@@ -2080,6 +2094,8 @@ this.XPIProvider = {
Services.prefs.addObserver(PREF_EM_MIN_COMPAT_APP_VERSION, this, false);
Services.prefs.addObserver(PREF_EM_MIN_COMPAT_PLATFORM_VERSION, this, false);
Services.obs.addObserver(this, NOTIFICATION_FLUSH_PERMISSIONS, false);
+
+#ifdef MOZ_DEVTOOLS
if (Cu.isModuleLoaded("resource://devtools/client/framework/ToolboxProcess.jsm")) {
// If BrowserToolboxProcess is already loaded, set the boolean to true
// and do whatever is needed
@@ -2091,6 +2107,7 @@ this.XPIProvider = {
// Else, wait for it to load
Services.obs.addObserver(this, NOTIFICATION_TOOLBOXPROCESS_LOADED, false);
}
+#endif
let flushCaches = this.checkForChanges(aAppChanged, aOldAppVersion,
aOldPlatformVersion);
@@ -3916,16 +3933,8 @@ this.XPIProvider = {
* @see amIAddonManager.mapURIToAddonID
*/
mapURIToAddonID: function XPI_mapURIToAddonID(aURI) {
- let resolved = this._resolveURIToFile(aURI);
- if (!resolved || !(resolved instanceof Ci.nsIFileURL))
- return null;
-
- for (let [id, path] of this._addonFileMap) {
- if (resolved.file.path.startsWith(path))
- return id;
- }
-
- return null;
+ // Returns `null` instead of empty string if the URI can't be mapped.
+ return AddonPathService.mapURIToAddonId(aURI) || null;
},
/**
@@ -4093,12 +4102,14 @@ this.XPIProvider = {
}
return;
}
+#ifdef MOZ_DEVTOOLS
else if (aTopic == NOTIFICATION_TOOLBOXPROCESS_LOADED) {
Services.obs.removeObserver(this, NOTIFICATION_TOOLBOXPROCESS_LOADED, false);
this._toolboxProcessLoaded = true;
BrowserToolboxProcess.on("connectionchange",
this.onDebugConnectionChange.bind(this));
}
+#endif
if (aTopic == "nsPref:changed") {
switch (aData) {
@@ -4363,12 +4374,14 @@ this.XPIProvider = {
logger.warn("Error loading bootstrap.js for " + aId, e);
}
+#ifdef MOZ_DEVTOOLS
// Only access BrowserToolboxProcess if ToolboxProcess.jsm has been
// initialized as otherwise, when it will be initialized, all addons'
// globals will be added anyways
if (this._toolboxProcessLoaded) {
BrowserToolboxProcess.setAddonOptions(aId, { global: this.bootstrapScopes[aId] });
}
+#endif
},
/**
@@ -4388,11 +4401,13 @@ this.XPIProvider = {
this.persistBootstrappedAddons();
this.addAddonsToCrashReporter();
+#ifdef MOZ_DEVTOOLS
// Only access BrowserToolboxProcess if ToolboxProcess.jsm has been
// initialized as otherwise, there won't be any addon globals added to it
if (this._toolboxProcessLoaded) {
BrowserToolboxProcess.setAddonOptions(aId, { global: null });
}
+#endif
},
/**
@@ -5010,6 +5025,11 @@ AddonInstall.prototype = {
if (e.webext) {
logger.warn("WebExtension XPI", e);
this.error = AddonManager.ERROR_WEBEXT_FILE;
+#ifndef MOZ_JETPACK
+ } else if (e.jetpacksdk) {
+ logger.warn("Jetpack XPI", e);
+ this.error = AddonManager.ERROR_JETPACKSDK_FILE;
+#endif
} else {
logger.warn("Invalid XPI", e);
this.error = AddonManager.ERROR_CORRUPT_FILE;
@@ -5651,6 +5671,10 @@ AddonInstall.prototype = {
catch (e) {
if (e.webext) {
this.downloadFailed(AddonManager.ERROR_WEBEXT_FILE, e);
+#ifndef MOZ_JETPACK
+ } else if (e.jetpacksdk) {
+ this.downloadFailed(AddonManager.ERROR_JETPACKSDK_FILE, e);
+#endif
} else {
this.downloadFailed(AddonManager.ERROR_CORRUPT_FILE, e);
}
@@ -6447,21 +6471,23 @@ AddonInternal.prototype = {
if (!aPlatformVersion)
aPlatformVersion = Services.appinfo.platformVersion;
+#ifdef MOZ_PHOENIX_EXTENSIONS
this.native = false;
-
+#endif
+
let version;
if (app.id == Services.appinfo.ID) {
version = aAppVersion;
+#ifdef MOZ_PHOENIX_EXTENSIONS
this.native = true;
}
-#ifdef MOZ_PHOENIX_EXTENSIONS
else if (app.id == FIREFOX_ID) {
version = FIREFOX_APPCOMPATVERSION;
if (this.type == "locale")
//Never allow language packs in Firefox compatibility mode
return false;
- }
#endif
+ }
else if (app.id == TOOLKIT_ID)
version = aPlatformVersion
diff --git a/toolkit/mozapps/extensions/internal/XPIProviderUtils.js b/toolkit/mozapps/extensions/internal/XPIProviderUtils.js
index d26029455..6b37ed640 100644
--- a/toolkit/mozapps/extensions/internal/XPIProviderUtils.js
+++ b/toolkit/mozapps/extensions/internal/XPIProviderUtils.js
@@ -70,7 +70,11 @@ const PROP_JSON_FIELDS = ["id", "syncGUID", "location", "version", "type",
"skinnable", "size", "sourceURI", "releaseNotesURI",
"softDisabled", "foreignInstall", "hasBinaryComponents",
"strictCompatibility", "locales", "targetApplications",
- "targetPlatforms", "multiprocessCompatible", "native"];
+ "targetPlatforms", "multiprocessCompatible",
+#ifdef MOZ_PHOENIX_EXTENSIONS
+ "native"
+#endif
+ ];
// Time to wait before async save of XPI JSON database, in milliseconds
const ASYNC_SAVE_DELAY_MS = 20;
diff --git a/toolkit/mozapps/extensions/nsBlocklistService.js b/toolkit/mozapps/extensions/nsBlocklistService.js
index 936c9d1b5..487dae8e5 100644
--- a/toolkit/mozapps/extensions/nsBlocklistService.js
+++ b/toolkit/mozapps/extensions/nsBlocklistService.js
@@ -910,7 +910,7 @@ Blocklist.prototype = {
let issuer = blocklistElement.getAttribute("issuerName");
for (let snElement of blocklistElement.children) {
try {
- gCertBlocklistService.addRevokedCert(issuer, snElement.textContent);
+ gCertBlocklistService.revokeCertByIssuerAndSerial(issuer, snElement.textContent);
} catch (e) {
// we want to keep trying other elements since missing all items
// is worse than missing one
diff --git a/toolkit/mozapps/extensions/test/xpcshell/test_mapURIToAddonID.js b/toolkit/mozapps/extensions/test/xpcshell/test_mapURIToAddonID.js
index a6f9c8052..a153256dc 100644
--- a/toolkit/mozapps/extensions/test/xpcshell/test_mapURIToAddonID.js
+++ b/toolkit/mozapps/extensions/test/xpcshell/test_mapURIToAddonID.js
@@ -95,8 +95,10 @@ function run_test_early() {
"resource://gre/modules/addons/XPIProvider.jsm", {});
// Make the early API call.
- do_check_null(s.XPIProvider.mapURIToAddonID(uri));
+ // AddonManager still misses its provider and so doesn't work yet.
do_check_null(AddonManager.mapURIToAddonID(uri));
+ // But calling XPIProvider directly works immediately
+ do_check_eq(s.XPIProvider.mapURIToAddonID(uri), id);
// Actually start up the manager.
startupManager(false);
diff --git a/toolkit/mozapps/extensions/test/xpcshell/xpcshell-shared.ini b/toolkit/mozapps/extensions/test/xpcshell/xpcshell-shared.ini
index 2a12f147a..51419a6e3 100644
--- a/toolkit/mozapps/extensions/test/xpcshell/xpcshell-shared.ini
+++ b/toolkit/mozapps/extensions/test/xpcshell/xpcshell-shared.ini
@@ -1,6 +1,6 @@
# The file is shared between the two main xpcshell manifest files.
[DEFAULT]
-skip-if = toolkit == 'android' || toolkit == 'gonk'
+skip-if = toolkit == 'android'
[test_AddonRepository.js]
# Bug 676992: test consistently hangs on Android
diff --git a/toolkit/mozapps/extensions/test/xpcshell/xpcshell-unpack.ini b/toolkit/mozapps/extensions/test/xpcshell/xpcshell-unpack.ini
index 51520f888..1f4fd692e 100644
--- a/toolkit/mozapps/extensions/test/xpcshell/xpcshell-unpack.ini
+++ b/toolkit/mozapps/extensions/test/xpcshell/xpcshell-unpack.ini
@@ -2,7 +2,7 @@
head = head_addons.js head_unpack.js
tail =
firefox-appdir = browser
-skip-if = toolkit == 'android' || toolkit == 'gonk'
+skip-if = toolkit == 'android'
dupe-manifest =
[include:xpcshell-shared.ini]
diff --git a/toolkit/mozapps/extensions/test/xpcshell/xpcshell.ini b/toolkit/mozapps/extensions/test/xpcshell/xpcshell.ini
index 83ab77c74..afe13895d 100644
--- a/toolkit/mozapps/extensions/test/xpcshell/xpcshell.ini
+++ b/toolkit/mozapps/extensions/test/xpcshell/xpcshell.ini
@@ -1,5 +1,5 @@
[DEFAULT]
-skip-if = buildapp == 'mulet' || toolkit == 'android' || toolkit == 'gonk'
+skip-if = buildapp == 'mulet' || toolkit == 'android'
head = head_addons.js
tail =
firefox-appdir = browser
diff --git a/toolkit/mozapps/extensions/test/xpinstall/browser_datauri.js b/toolkit/mozapps/extensions/test/xpinstall/browser_datauri.js
index 917f2465d..b24bce4b5 100644
--- a/toolkit/mozapps/extensions/test/xpinstall/browser_datauri.js
+++ b/toolkit/mozapps/extensions/test/xpinstall/browser_datauri.js
@@ -13,6 +13,13 @@ function setup_redirect(aSettings) {
}
function test() {
+ waitForExplicitFinish();
+ SpecialPowers.pushPrefEnv({
+ "set": [["security.data_uri.block_toplevel_data_uri_navigations", false]]
+ }, runTest);
+}
+
+function runTest() {
Harness.installOriginBlockedCallback = install_blocked;
Harness.installsCompletedCallback = finish_test;
Harness.setup();
@@ -33,4 +40,5 @@ function finish_test(count) {
gBrowser.removeCurrentTab();
Harness.finish();
+ finish();
}
diff --git a/toolkit/mozapps/update/nsUpdateService.js b/toolkit/mozapps/update/nsUpdateService.js
index e23ab3f40..0cf7b8938 100644
--- a/toolkit/mozapps/update/nsUpdateService.js
+++ b/toolkit/mozapps/update/nsUpdateService.js
@@ -55,8 +55,6 @@ const URI_UPDATES_PROPERTIES = "chrome://mozapps/locale/update/updates.proper
const KEY_UPDROOT = "UpdRootD";
const KEY_EXECUTABLE = "XREExeF";
-// Gonk only
-const KEY_UPDATE_ARCHIVE_DIR = "UpdArchD";
const DIR_UPDATES = "updates";
@@ -198,17 +196,6 @@ const APPID_TO_TOPIC = {
var gUpdateMutexHandle = null;
-// Gonk only
-var gSDCardMountLock = null;
-
-// Gonk only
-XPCOMUtils.defineLazyGetter(this, "gExtStorage", function aus_gExtStorage() {
- if (AppConstants.platform != "gonk") {
- throw Cr.NS_ERROR_NOT_IMPLEMENTED;
- }
- return Services.env.get("EXTERNAL_STORAGE");
-});
-
XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",
"resource://gre/modules/UpdateUtils.jsm");
@@ -564,13 +551,6 @@ function getCanStageUpdates() {
return true;
}
- // For Gonk, the updater will remount the /system partition to move staged
- // files into place.
- if (AppConstants.platform == "gonk") {
- LOG("getCanStageUpdates - able to stage updates because this is gonk");
- return true;
- }
-
if (!hasUpdateMutex()) {
LOG("getCanStageUpdates - unable to apply updates because another " +
"instance of the application is already handling updates for this " +
@@ -798,105 +778,6 @@ function writeVersionFile(dir, version) {
}
/**
- * Gonk only function that reads the link file specified in the update.link file
- * in the specified directory and returns the nsIFile for the corresponding
- * file.
- * @param dir
- * The dir to look for an update.link file in
- * @return A nsIFile for the file path specified in the
- * update.link file or null if the update.link file
- * doesn't exist.
- */
-function getFileFromUpdateLink(dir) {
- if (AppConstants.platform != "gonk") {
- throw Cr.NS_ERROR_NOT_IMPLEMENTED;
- }
- let linkFile = dir.clone();
- linkFile.append(FILE_UPDATE_LINK);
- let link = readStringFromFile(linkFile);
- LOG("getFileFromUpdateLink linkFile.path: " + linkFile.path + ", link: " + link);
- if (!link) {
- return null;
- }
- let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
- file.initWithPath(link);
- return file;
-}
-
-/**
- * Gonk only function to create a link file. This allows the actual patch to
- * live in a directory different from the update directory.
- * @param dir
- * The patch directory where the update.link file
- * should be written.
- * @param patchFile
- * The fully qualified filename of the patchfile.
- */
-function writeLinkFile(dir, patchFile) {
- if (AppConstants.platform != "gonk") {
- throw Cr.NS_ERROR_NOT_IMPLEMENTED;
- }
- let linkFile = dir.clone();
- linkFile.append(FILE_UPDATE_LINK);
- writeStringToFile(linkFile, patchFile.path);
- if (patchFile.path.indexOf(gExtStorage) == 0) {
- // The patchfile is being stored on external storage. Try to lock it
- // so that it doesn't get shared with the PC while we're downloading
- // to it.
- acquireSDCardMountLock();
- }
-}
-
-/**
- * Gonk only function to acquire a VolumeMountLock for the sdcard volume.
- *
- * This prevents the SDCard from being shared with the PC while
- * we're downloading the update.
- */
-function acquireSDCardMountLock() {
- if (AppConstants.platform != "gonk") {
- throw Cr.NS_ERROR_NOT_IMPLEMENTED;
- }
- let volsvc = Cc["@mozilla.org/telephony/volume-service;1"].
- getService(Ci.nsIVolumeService);
- if (volsvc) {
- gSDCardMountLock = volsvc.createMountLock("sdcard");
- }
-}
-
-/**
- * Gonk only function that determines if the state corresponds to an
- * interrupted update. This could either be because the download was
- * interrupted, or because staging the update was interrupted.
- *
- * @return true if the state corresponds to an interrupted
- * update.
- */
-function isInterruptedUpdate(status) {
- if (AppConstants.platform != "gonk") {
- throw Cr.NS_ERROR_NOT_IMPLEMENTED;
- }
- return (status == STATE_DOWNLOADING) ||
- (status == STATE_PENDING) ||
- (status == STATE_APPLYING);
-}
-
-/**
- * Releases any SDCard mount lock that we might have.
- *
- * This once again allows the SDCard to be shared with the PC.
- */
-function releaseSDCardMountLock() {
- if (AppConstants.platform != "gonk") {
- throw Cr.NS_ERROR_UNEXPECTED;
- }
- if (gSDCardMountLock) {
- gSDCardMountLock.unlock();
- gSDCardMountLock = null;
- }
-}
-
-/**
* Determines if the service should be used to attempt an update
* or not.
*
@@ -1058,14 +939,6 @@ function cleanUpUpdatesDir(aRemovePatchFiles = true) {
let dirEntries = updateDir.directoryEntries;
while (dirEntries.hasMoreElements()) {
let file = dirEntries.getNext().QueryInterface(Ci.nsIFile);
- if (AppConstants.platform == "gonk") {
- if (file.leafName == FILE_UPDATE_LINK) {
- let linkedFile = getFileFromUpdateLink(updateDir);
- if (linkedFile && linkedFile.exists()) {
- linkedFile.remove(false);
- }
- }
- }
// Now, recursively remove this file. The recursive removal is needed for
// Mac OSX because this directory will contain a copy of updater.app,
@@ -1078,9 +951,6 @@ function cleanUpUpdatesDir(aRemovePatchFiles = true) {
}
}
}
- if (AppConstants.platform == "gonk") {
- releaseSDCardMountLock();
- }
}
/**
@@ -1809,12 +1679,6 @@ function UpdateService() {
LOG("Creating UpdateService");
Services.obs.addObserver(this, "xpcom-shutdown", false);
Services.prefs.addObserver(PREF_APP_UPDATE_LOG, this, false);
- if (AppConstants.platform == "gonk") {
- // PowerManagerService::SyncProfile (which is called for Reboot, PowerOff
- // and Restart) sends the profile-change-net-teardown event. We can then
- // pause the download in a similar manner to xpcom-shutdown.
- Services.obs.addObserver(this, "profile-change-net-teardown", false);
- }
}
UpdateService.prototype = {
@@ -1980,23 +1844,6 @@ UpdateService.prototype = {
}
}
- if (AppConstants.platform == "gonk") {
- // This code is called very early in the boot process, before we've even
- // had a chance to setup the UI so we can give feedback to the user.
- //
- // Since the download may be occuring over a link which has associated
- // cost, we want to require user-consent before resuming the download.
- // Also, applying an already downloaded update now is undesireable,
- // since the phone will look dead while the update is being applied.
- // Applying the update can take several minutes. Instead we wait until
- // the UI is initialized so it is possible to give feedback to and get
- // consent to update from the user.
- if (isInterruptedUpdate(status)) {
- LOG("UpdateService:_postUpdateProcessing - interrupted update detected - wait for user consent");
- return;
- }
- }
-
if (status == STATE_DOWNLOADING) {
LOG("UpdateService:_postUpdateProcessing - patch found in downloading " +
"state");
@@ -2038,34 +1885,6 @@ UpdateService.prototype = {
return;
}
- if (AppConstants.platform == "gonk") {
- // The update is only applied but not selected to be installed
- if (status == STATE_APPLIED && update && update.isOSUpdate) {
- LOG("UpdateService:_postUpdateProcessing - update staged as applied found");
- return;
- }
-
- if (status == STATE_APPLIED_OS && update && update.isOSUpdate) {
- // In gonk, we need to check for OS update status after startup, since
- // the recovery partition won't write to update.status for us
- let recoveryService = Cc["@mozilla.org/recovery-service;1"].
- getService(Ci.nsIRecoveryService);
- let fotaStatus = recoveryService.getFotaUpdateStatus();
- switch (fotaStatus) {
- case Ci.nsIRecoveryService.FOTA_UPDATE_SUCCESS:
- status = STATE_SUCCEEDED;
- break;
- case Ci.nsIRecoveryService.FOTA_UPDATE_FAIL:
- status = STATE_FAILED + ": " + FOTA_GENERAL_ERROR;
- break;
- case Ci.nsIRecoveryService.FOTA_UPDATE_UNKNOWN:
- default:
- status = STATE_FAILED + ": " + FOTA_UNKNOWN_ERROR;
- break;
- }
- }
- }
-
if (!update) {
if (status != STATE_SUCCEEDED) {
LOG("UpdateService:_postUpdateProcessing - previous patch failed " +
@@ -2519,11 +2338,6 @@ UpdateService.prototype = {
var um = Cc["@mozilla.org/updates/update-manager;1"].
getService(Ci.nsIUpdateManager);
if (um.activeUpdate) {
- if (AppConstants.platform == "gonk") {
- // For gonk, the user isn't necessarily aware of the update, so we need
- // to show the prompt to make sure.
- this._showPrompt(um.activeUpdate);
- }
AUSTLMY.pingCheckCode(this._pingSuffix, AUSTLMY.CHK_HAS_ACTIVEUPDATE);
return;
}
@@ -2714,21 +2528,6 @@ UpdateService.prototype = {
}
this._downloader.cancel();
}
- if (AppConstants.platform == "gonk") {
- let um = Cc["@mozilla.org/updates/update-manager;1"].
- getService(Ci.nsIUpdateManager);
- let activeUpdate = um.activeUpdate;
- if (activeUpdate &&
- (activeUpdate.appVersion != update.appVersion ||
- activeUpdate.buildID != update.buildID)) {
- // We have an activeUpdate (which presumably was interrupted), and are
- // about start downloading a new one. Make sure we remove all traces
- // of the active one (otherwise we'll start appending the new update.mar
- // the the one that's been partially downloaded).
- LOG("UpdateService:downloadUpdate - removing stale active update.");
- cleanupActiveUpdate();
- }
- }
// Set the previous application version prior to downloading the update.
update.previousAppVersion = Services.appinfo.version;
this._downloader = new Downloader(background, this);
@@ -3142,21 +2941,6 @@ UpdateManager.prototype = {
"the update was staged. state: " + update.state + ", status: " + status);
Services.obs.notifyObservers(null, "update-staged", update.state);
- if (AppConstants.platform == "gonk") {
- // Do this after everything else, since it will likely cause the app to
- // shut down.
- if (update.state == STATE_APPLIED) {
- // Notify the user that an update has been staged and is ready for
- // installation (i.e. that they should restart the application). We do
- // not notify on failed update attempts.
- let prompter = Cc["@mozilla.org/updates/update-prompt;1"].
- createInstance(Ci.nsIUpdatePrompt);
- prompter.showUpdateDownloaded(update, true);
- } else {
- releaseSDCardMountLock();
- }
- return;
- }
// Only prompt when the UI isn't already open.
let windowType = getPref("getCharPref", PREF_APP_UPDATE_ALTWINDOWTYPE, null);
if (Services.wm.getMostRecentWindow(UPDATE_WINDOW_NAME) ||
@@ -3515,9 +3299,6 @@ Downloader.prototype = {
if (this._request && this._request instanceof Ci.nsIRequest) {
this._request.cancel(cancelError);
}
- if (AppConstants.platform == "gonk") {
- releaseSDCardMountLock();
- }
},
/**
@@ -3647,17 +3428,8 @@ Downloader.prototype = {
return selectedPatch;
}
- if (AppConstants.platform == "gonk") {
- if (state == STATE_PENDING || state == STATE_APPLYING) {
- LOG("Downloader:_selectPatch - resuming interrupted apply");
- return selectedPatch;
- }
- if (state == STATE_APPLIED) {
- LOG("Downloader:_selectPatch - already downloaded and staged");
- return null;
- }
- } else if (state == STATE_PENDING || state == STATE_PENDING_SERVICE ||
- state == STATE_PENDING_ELEVATE) {
+ if (state == STATE_PENDING || state == STATE_PENDING_SERVICE ||
+ state == STATE_PENDING_ELEVATE) {
LOG("Downloader:_selectPatch - already downloaded and staged");
return null;
}
@@ -3719,15 +3491,7 @@ Downloader.prototype = {
*/
_getUpdateArchiveFile: function Downloader__getUpdateArchiveFile() {
var updateArchive;
- if (AppConstants.platform == "gonk") {
- try {
- updateArchive = FileUtils.getDir(KEY_UPDATE_ARCHIVE_DIR, [], true);
- } catch (e) {
- return null;
- }
- } else {
- updateArchive = getUpdatesDir().clone();
- }
+ updateArchive = getUpdatesDir().clone();
updateArchive.append(FILE_UPDATE_MAR);
return updateArchive;
@@ -3761,71 +3525,6 @@ Downloader.prototype = {
let patchFile = null;
- // Only used by gonk
- let status = STATE_NONE;
- if (AppConstants.platform == "gonk") {
- status = readStatusFile(updateDir);
- if (isInterruptedUpdate(status)) {
- LOG("Downloader:downloadUpdate - interruptted update");
- // The update was interrupted. Try to locate the existing patch file.
- // For an interrupted download, this allows a resume rather than a
- // re-download.
- patchFile = getFileFromUpdateLink(updateDir);
- if (!patchFile) {
- // No link file. We'll just assume that the update.mar is in the
- // update directory.
- patchFile = updateDir.clone();
- patchFile.append(FILE_UPDATE_MAR);
- }
- if (patchFile.exists()) {
- LOG("Downloader:downloadUpdate - resuming with patchFile " + patchFile.path);
- if (patchFile.fileSize == this._patch.size) {
- LOG("Downloader:downloadUpdate - patchFile appears to be fully downloaded");
- // Bump the status along so that we don't try to redownload again.
- if (getElevationRequired()) {
- status = STATE_PENDING_ELEVATE;
- } else {
- status = STATE_PENDING;
- }
- }
- } else {
- LOG("Downloader:downloadUpdate - patchFile " + patchFile.path +
- " doesn't exist - performing full download");
- // The patchfile doesn't exist, we might as well treat this like
- // a new download.
- patchFile = null;
- }
- if (patchFile && status != STATE_DOWNLOADING) {
- // It looks like the patch was downloaded, but got interrupted while it
- // was being verified or applied. So we'll fake the downloading portion.
-
- if (getElevationRequired()) {
- writeStatusFile(updateDir, STATE_PENDING_ELEVATE);
- } else {
- writeStatusFile(updateDir, STATE_PENDING);
- }
-
- // Since the code expects the onStopRequest callback to happen
- // asynchronously (And you have to call AUS_addDownloadListener
- // after calling AUS_downloadUpdate) we need to defer this.
-
- this._downloadTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
- this._downloadTimer.initWithCallback(function() {
- this._downloadTimer = null;
- // Send a fake onStopRequest. Filling in the destination allows
- // _verifyDownload to work, and then the update will be applied.
- this._request = {destination: patchFile};
- this.onStopRequest(this._request, null, Cr.NS_OK);
- }.bind(this), 0, Ci.nsITimer.TYPE_ONE_SHOT);
-
- // Returning STATE_DOWNLOADING makes UpdatePrompt think we're
- // downloading. The onStopRequest that we spoofed above will make it
- // look like the download finished.
- return STATE_DOWNLOADING;
- }
- }
- }
-
if (!patchFile) {
// Find a place to put the patchfile that we're going to download.
patchFile = this._getUpdateArchiveFile();
@@ -3836,19 +3535,6 @@ Downloader.prototype = {
return STATE_NONE;
}
- if (AppConstants.platform == "gonk") {
- if (patchFile.path.indexOf(updateDir.path) != 0) {
- // The patchFile is in a directory which is different from the
- // updateDir, create a link file.
- writeLinkFile(updateDir, patchFile);
-
- if (!isInterruptedUpdate(status) && patchFile.exists()) {
- // Remove stale patchFile
- patchFile.remove(false);
- }
- }
- }
-
update.QueryInterface(Ci.nsIPropertyBag);
let interval = this.background ? update.getProperty("backgroundInterval")
: DOWNLOAD_FOREGROUND_INTERVAL;
@@ -4119,13 +3805,6 @@ Downloader.prototype = {
this._update.statusText = getStatusTextFromCode(status,
Cr.NS_BINDING_FAILED);
- if (AppConstants.platform == "gonk") {
- // bug891009: On FirefoxOS, manaully retry OTA download will reuse
- // the Update object. We need to remove selected patch so that download
- // can be triggered again successfully.
- this._update.selectedPatch.selected = false;
- }
-
// Destroy the updates directory, since we're done with it.
cleanUpUpdatesDir();
@@ -4187,13 +3866,6 @@ Downloader.prototype = {
}
}
- if (AppConstants.platform == "gonk") {
- // We always forward errors in B2G, since Gaia controls the update UI
- let prompter = Cc["@mozilla.org/updates/update-prompt;1"].
- createInstance(Ci.nsIUpdatePrompt);
- prompter.showUpdateError(this._update);
- }
-
// Prevent leaking the update object (bug 454964).
this._update = null;
}
diff --git a/toolkit/mozapps/update/updater/automounter_gonk.cpp b/toolkit/mozapps/update/updater/automounter_gonk.cpp
deleted file mode 100644
index 3dff2a133..000000000
--- a/toolkit/mozapps/update/updater/automounter_gonk.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 <android/log.h>
-#include <cutils/android_reboot.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <sys/mount.h>
-#include <sys/reboot.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-#include "automounter_gonk.h"
-#include "updatedefines.h"
-#include "updatelogging.h"
-
-#define LOG_TAG "GonkAutoMounter"
-
-#define GONK_LOG(level, format, ...) \
- LOG((LOG_TAG ": " format "\n", ##__VA_ARGS__)); \
- __android_log_print(level, LOG_TAG, format, ##__VA_ARGS__)
-
-#define LOGI(format, ...) GONK_LOG(ANDROID_LOG_INFO, format, ##__VA_ARGS__)
-#define LOGE(format, ...) GONK_LOG(ANDROID_LOG_ERROR, format, ##__VA_ARGS__)
-
-const char *kGonkMountsPath = "/proc/mounts";
-const char *kGonkSystemPath = "/system";
-
-GonkAutoMounter::GonkAutoMounter() : mDevice(nullptr), mAccess(Unknown)
-{
- if (!RemountSystem(ReadWrite)) {
- LOGE("Could not remount %s as read-write.", kGonkSystemPath);
- }
-}
-
-GonkAutoMounter::~GonkAutoMounter()
-{
- bool result = RemountSystem(ReadOnly);
- free(mDevice);
-
- if (!result) {
- // Don't take any chances when remounting as read-only fails, just reboot.
- Reboot();
- }
-}
-
-void
-GonkAutoMounter::Reboot()
-{
- // The android_reboot wrapper provides more safety, doing fancier read-only
- // remounting and attempting to sync() the filesystem first. If this fails
- // our only hope is to force a reboot directly without these protections.
- // For more, see system/core/libcutils/android_reboot.c
- LOGE("Could not remount %s as read-only, forcing a system reboot.",
- kGonkSystemPath);
- LogFlush();
-
- if (android_reboot(ANDROID_RB_RESTART, 0, nullptr) != 0) {
- LOGE("Safe system reboot failed, attempting to force");
- LogFlush();
-
- if (reboot(RB_AUTOBOOT) != 0) {
- LOGE("CRITICAL: Failed to force restart");
- }
- }
-}
-
-static const char *
-MountAccessToString(MountAccess access)
-{
- switch (access) {
- case ReadOnly: return "read-only";
- case ReadWrite: return "read-write";
- default: return "unknown";
- }
-}
-
-bool
-GonkAutoMounter::RemountSystem(MountAccess access)
-{
- if (!UpdateMountStatus()) {
- return false;
- }
-
- if (mAccess == access) {
- return true;
- }
-
- unsigned long flags = MS_REMOUNT;
- if (access == ReadOnly) {
- flags |= MS_RDONLY;
- // Give the system a chance to flush file buffers
- sync();
- }
-
- if (!MountSystem(flags)) {
- return false;
- }
-
- // Check status again to verify /system has been properly remounted
- if (!UpdateMountStatus()) {
- return false;
- }
-
- if (mAccess != access) {
- LOGE("Updated mount status %s should be %s",
- MountAccessToString(mAccess),
- MountAccessToString(access));
- return false;
- }
-
- return true;
-}
-
-bool
-GonkAutoMounter::UpdateMountStatus()
-{
- FILE *mountsFile = NS_tfopen(kGonkMountsPath, "r");
-
- if (mountsFile == nullptr) {
- LOGE("Error opening %s: %s", kGonkMountsPath, strerror(errno));
- return false;
- }
-
- // /proc/mounts returns a 0 size from fstat, so we use the same
- // pre-allocated buffer size that ADB does here
- const int mountsMaxSize = 4096;
- char mountData[mountsMaxSize];
- size_t read = fread(mountData, 1, mountsMaxSize - 1, mountsFile);
- mountData[read + 1] = '\0';
-
- if (ferror(mountsFile)) {
- LOGE("Error reading %s, %s", kGonkMountsPath, strerror(errno));
- fclose(mountsFile);
- return false;
- }
-
- char *token, *tokenContext;
- bool foundSystem = false;
-
- for (token = strtok_r(mountData, "\n", &tokenContext);
- token;
- token = strtok_r(nullptr, "\n", &tokenContext))
- {
- if (ProcessMount(token)) {
- foundSystem = true;
- break;
- }
- }
-
- fclose(mountsFile);
-
- if (!foundSystem) {
- LOGE("Couldn't find %s mount in %s", kGonkSystemPath, kGonkMountsPath);
- }
- return foundSystem;
-}
-
-bool
-GonkAutoMounter::ProcessMount(const char *mount)
-{
- const int strSize = 256;
- char mountDev[strSize];
- char mountDir[strSize];
- char mountAccess[strSize];
-
- int rv = sscanf(mount, "%255s %255s %*s %255s %*d %*d\n",
- mountDev, mountDir, mountAccess);
- mountDev[strSize - 1] = '\0';
- mountDir[strSize - 1] = '\0';
- mountAccess[strSize - 1] = '\0';
-
- if (rv != 3) {
- return false;
- }
-
- if (strcmp(kGonkSystemPath, mountDir) != 0) {
- return false;
- }
-
- free(mDevice);
- mDevice = strdup(mountDev);
- mAccess = Unknown;
-
- char *option, *optionContext;
- for (option = strtok_r(mountAccess, ",", &optionContext);
- option;
- option = strtok_r(nullptr, ",", &optionContext))
- {
- if (strcmp("ro", option) == 0) {
- mAccess = ReadOnly;
- break;
- } else if (strcmp("rw", option) == 0) {
- mAccess = ReadWrite;
- break;
- }
- }
-
- return true;
-}
-
-/*
- * Mark the given block device as read-write or read-only, using the BLKROSET
- * ioctl.
- */
-static void SetBlockReadWriteStatus(const char *blockdev, bool setReadOnly) {
- int fd;
- int roMode = setReadOnly ? 1 : 0;
-
- fd = open(blockdev, O_RDONLY);
- if (fd < 0) {
- return;
- }
-
- if (ioctl(fd, BLKROSET, &roMode) == -1) {
- LOGE("Error setting read-only mode on %s to %s: %s", blockdev,
- setReadOnly ? "true": "false", strerror(errno));
- }
- close(fd);
-}
-
-
-bool
-GonkAutoMounter::MountSystem(unsigned long flags)
-{
- if (!mDevice) {
- LOGE("No device was found for %s", kGonkSystemPath);
- return false;
- }
-
- // Without setting the block device ro mode to false, we get a permission
- // denied error while trying to remount it in read-write.
- SetBlockReadWriteStatus(mDevice, (flags & MS_RDONLY));
-
- const char *readOnly = flags & MS_RDONLY ? "read-only" : "read-write";
- int result = mount(mDevice, kGonkSystemPath, "none", flags, nullptr);
-
- if (result != 0) {
- LOGE("Error mounting %s as %s: %s", kGonkSystemPath, readOnly,
- strerror(errno));
- return false;
- }
-
- LOGI("Mounted %s partition as %s", kGonkSystemPath, readOnly);
- return true;
-}
diff --git a/toolkit/mozapps/update/updater/automounter_gonk.h b/toolkit/mozapps/update/updater/automounter_gonk.h
deleted file mode 100644
index e40cacbc2..000000000
--- a/toolkit/mozapps/update/updater/automounter_gonk.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=2 sts=2 et cindent: */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 AUTOMOUNTER_GONK_H__
-#define AUTOMOUNTER_GONK_H__
-
-typedef enum {
- ReadOnly,
- ReadWrite,
- Unknown
-} MountAccess;
-
-/**
- * This class will remount the /system partition as read-write in Gonk to allow
- * the updater write access. Upon destruction, /system will be remounted back to
- * read-only. If something causes /system to remain read-write, this class will
- * reboot the device and allow the system to mount as read-only.
- *
- * Code inspired from AOSP system/core/adb/remount_service.c
- */
-class GonkAutoMounter
-{
-public:
- GonkAutoMounter();
- ~GonkAutoMounter();
-
- MountAccess GetAccess() const
- {
- return mAccess;
- }
-
-private:
- bool RemountSystem(MountAccess access);
- bool ForceRemountReadOnly();
- bool UpdateMountStatus();
- bool ProcessMount(const char *mount);
- bool MountSystem(unsigned long flags);
- void Reboot();
-
-private:
- char *mDevice;
- MountAccess mAccess;
-};
-
-#endif // AUTOMOUNTER_GONK_H__
diff --git a/toolkit/mozapps/update/updater/progressui_gonk.cpp b/toolkit/mozapps/update/updater/progressui_gonk.cpp
deleted file mode 100644
index f77d0af63..000000000
--- a/toolkit/mozapps/update/updater/progressui_gonk.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/* -*- 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 <assert.h>
-#include <stdio.h>
-
-#include <string>
-
-#include "android/log.h"
-
-#include "progressui.h"
-
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "GeckoUpdater" , ## args)
-
-using namespace std;
-
-int InitProgressUI(int *argc, char ***argv)
-{
- return 0;
-}
-
-int ShowProgressUI()
-{
- LOG("Starting to apply update ...\n");
- return 0;
-}
-
-void QuitProgressUI()
-{
- LOG("Finished applying update\n");
-}
-
-void UpdateProgressUI(float progress)
-{
- assert(0.0f <= progress && progress <= 100.0f);
-
- static const size_t kProgressBarLength = 50;
- static size_t sLastNumBars;
- size_t numBars = size_t(float(kProgressBarLength) * progress / 100.0f);
- if (numBars == sLastNumBars) {
- return;
- }
- sLastNumBars = numBars;
-
- size_t numSpaces = kProgressBarLength - numBars;
- string bars(numBars, '=');
- string spaces(numSpaces, ' ');
- LOG("Progress [ %s%s ]\n", bars.c_str(), spaces.c_str());
-}
diff --git a/toolkit/mozapps/update/updater/updater-common.build b/toolkit/mozapps/update/updater/updater-common.build
index 02b7338bc..6444df8d9 100644
--- a/toolkit/mozapps/update/updater/updater-common.build
+++ b/toolkit/mozapps/update/updater/updater-common.build
@@ -90,17 +90,6 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
LOCAL_INCLUDES += [
'/toolkit/xre',
]
-elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk':
- have_progressui = 1
- srcs += [
- 'automounter_gonk.cpp',
- 'progressui_gonk.cpp',
- ]
- DISABLE_STL_WRAPPING = True
- OS_LIBS += [
- 'cutils',
- 'sysutils',
- ]
if have_progressui == 0:
srcs += [
diff --git a/toolkit/mozapps/update/updater/updater.cpp b/toolkit/mozapps/update/updater/updater.cpp
index 63a92c084..dbf50329c 100644
--- a/toolkit/mozapps/update/updater/updater.cpp
+++ b/toolkit/mozapps/update/updater/updater.cpp
@@ -110,33 +110,10 @@ struct UpdateServerThreadArgs
#define USE_EXECV
#endif
-#if defined(MOZ_WIDGET_GONK)
-# include "automounter_gonk.h"
-# include <unistd.h>
-# include <android/log.h>
-# include <linux/ioprio.h>
-# include <sys/resource.h>
-
-#if ANDROID_VERSION < 21
-// The only header file in bionic which has a function prototype for ioprio_set
-// is libc/include/sys/linux-unistd.h. However, linux-unistd.h conflicts
-// badly with unistd.h, so we declare the prototype for ioprio_set directly.
-extern "C" MOZ_EXPORT int ioprio_set(int which, int who, int ioprio);
-#else
-# include <sys/syscall.h>
-static int ioprio_set(int which, int who, int ioprio) {
- return syscall(__NR_ioprio_set, which, who, ioprio);
-}
-#endif
-
-# define MAYBE_USE_HARD_LINKS 1
-static bool sUseHardLinks = true;
-#else
# define MAYBE_USE_HARD_LINKS 0
-#endif
#if defined(MOZ_VERIFY_MAR_SIGNATURE) && !defined(XP_WIN) && \
- !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+ !defined(XP_MACOSX)
#include "nss.h"
#include "prerror.h"
#endif
@@ -2495,44 +2472,9 @@ ReadMARChannelIDs(const NS_tchar *path, MARChannelStringTable *results)
static int
GetUpdateFileName(NS_tchar *fileName, int maxChars)
{
-#if defined(MOZ_WIDGET_GONK)
- // If an update.link file exists, then it will contain the name
- // of the update file (terminated by a newline).
-
- NS_tchar linkFileName[MAXPATHLEN];
- NS_tsnprintf(linkFileName, sizeof(linkFileName)/sizeof(linkFileName[0]),
- NS_T("%s/update.link"), gPatchDirPath);
- AutoFile linkFile(NS_tfopen(linkFileName, NS_T("rb")));
- if (linkFile == nullptr) {
- NS_tsnprintf(fileName, maxChars,
- NS_T("%s/update.mar"), gPatchDirPath);
- return OK;
- }
-
- char dataFileName[MAXPATHLEN];
- size_t bytesRead;
-
- if ((bytesRead = fread(dataFileName, 1, sizeof(dataFileName)-1, linkFile)) <= 0) {
- *fileName = NS_T('\0');
- return READ_ERROR;
- }
- if (dataFileName[bytesRead-1] == '\n') {
- // Strip trailing newline (for \n and \r\n)
- bytesRead--;
- }
- if (dataFileName[bytesRead-1] == '\r') {
- // Strip trailing CR (for \r, \r\n)
- bytesRead--;
- }
- dataFileName[bytesRead] = '\0';
-
- strncpy(fileName, dataFileName, maxChars-1);
- fileName[maxChars-1] = '\0';
-#else
- // We currently only support update.link files under GONK
+ // We currently don't support update.link files
NS_tsnprintf(fileName, maxChars,
NS_T("%s/update.mar"), gPatchDirPath);
-#endif
return OK;
}
@@ -2776,26 +2718,8 @@ int NS_main(int argc, NS_tchar **argv)
}
#endif
-#if defined(MOZ_WIDGET_GONK)
- if (EnvHasValue("LD_PRELOAD")) {
- // If the updater is launched with LD_PRELOAD set, then we wind up
- // preloading libmozglue.so. Under some circumstances, this can cause
- // the remount of /system to fail when going from rw to ro, so if we
- // detect LD_PRELOAD we unsetenv it and relaunch ourselves without it.
- // This will cause the offending preloaded library to be closed.
- //
- // For a variety of reasons, this is really hard to do in a safe manner
- // in the parent process, so we do it here.
- unsetenv("LD_PRELOAD");
- execv(argv[0], argv);
- __android_log_print(ANDROID_LOG_INFO, "updater",
- "execve failed: errno: %d. Exiting...", errno);
- _exit(1);
- }
-#endif
-
#if defined(MOZ_VERIFY_MAR_SIGNATURE) && !defined(XP_WIN) && \
- !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+ !defined(XP_MACOSX)
// On Windows and Mac we rely on native APIs to do verifications so we don't
// need to initialize NSS at all there.
// Otherwise, minimize the amount of NSS we depend on by avoiding all the NSS
@@ -3085,36 +3009,6 @@ int NS_main(int argc, NS_tchar **argv)
}
#endif
-#ifdef MOZ_WIDGET_GONK
- const char *prioEnv = getenv("MOZ_UPDATER_PRIO");
- if (prioEnv) {
- int32_t prioVal;
- int32_t oomScoreAdj;
- int32_t ioprioClass;
- int32_t ioprioLevel;
- if (sscanf(prioEnv, "%d/%d/%d/%d",
- &prioVal, &oomScoreAdj, &ioprioClass, &ioprioLevel) == 4) {
- LOG(("MOZ_UPDATER_PRIO=%s", prioEnv));
- if (setpriority(PRIO_PROCESS, 0, prioVal)) {
- LOG(("setpriority(%d) failed, errno = %d", prioVal, errno));
- }
- if (ioprio_set(IOPRIO_WHO_PROCESS, 0,
- IOPRIO_PRIO_VALUE(ioprioClass, ioprioLevel))) {
- LOG(("ioprio_set(%d,%d) failed: errno = %d",
- ioprioClass, ioprioLevel, errno));
- }
- FILE *fs = fopen("/proc/self/oom_score_adj", "w");
- if (fs) {
- fprintf(fs, "%d", oomScoreAdj);
- fclose(fs);
- } else {
- LOG(("Unable to open /proc/self/oom_score_adj for writing, errno = %d",
- errno));
- }
- }
- }
-#endif
-
#ifdef XP_WIN
if (pid > 0) {
HANDLE parent = OpenProcess(SYNCHRONIZE, false, (DWORD) pid);
@@ -3439,27 +3333,6 @@ int NS_main(int argc, NS_tchar **argv)
}
#endif
-#if defined(MOZ_WIDGET_GONK)
- // In gonk, the master b2g process sets its umask to 0027 because
- // there's no reason for it to ever create world-readable files.
- // The updater binary, however, needs to do this, and it inherits
- // the master process's cautious umask. So we drop down a bit here.
- umask(0022);
-
- // Remount the /system partition as read-write for gonk. The destructor will
- // remount /system as read-only. We add an extra level of scope here to avoid
- // calling LogFinish() before the GonkAutoMounter destructor has a chance
- // to be called
- {
-#if !defined(TEST_UPDATER)
- GonkAutoMounter mounter;
- if (mounter.GetAccess() != MountAccess::ReadWrite) {
- WriteStatusFile(FILESYSTEM_MOUNT_READWRITE_ERROR);
- return 1;
- }
-#endif
-#endif
-
if (sStagedUpdate) {
// When staging updates, blow away the old installation directory and create
// it from scratch.
@@ -3759,10 +3632,6 @@ int NS_main(int argc, NS_tchar **argv)
}
#endif /* XP_WIN */
-#if defined(MOZ_WIDGET_GONK)
- } // end the extra level of scope for the GonkAutoMounter
-#endif
-
#ifdef XP_MACOSX
// When the update is successful remove the precomplete file in the root of
// the application bundle and move the distribution directory from
diff --git a/toolkit/mozapps/webextensions/extensions.manifest b/toolkit/mozapps/webextensions/extensions.manifest
index c7d2ee386..7ce20c3ec 100644
--- a/toolkit/mozapps/webextensions/extensions.manifest
+++ b/toolkit/mozapps/webextensions/extensions.manifest
@@ -5,7 +5,6 @@ component {e0a106ed-6ad4-47a4-b6af-2f1c8aa4712d} nsBlocklistServiceContent.js pr
contract @mozilla.org/extensions/blocklist;1 {e0a106ed-6ad4-47a4-b6af-2f1c8aa4712d} process=content
category update-timer nsBlocklistService @mozilla.org/extensions/blocklist;1,getService,blocklist-background-update-timer,extensions.blocklist.interval,86400
-#ifndef MOZ_WIDGET_GONK
component {4399533d-08d1-458c-a87a-235f74451cfa} addonManager.js
contract @mozilla.org/addons/integration;1 {4399533d-08d1-458c-a87a-235f74451cfa}
#ifndef MOZ_WIDGET_ANDROID
@@ -22,6 +21,5 @@ category JavaScript-global-property InstallTrigger @mozilla.org/addons/installtr
category addon-provider-module PluginProvider resource://gre/modules/addons/PluginProvider.jsm
#endif
category addon-provider-module GMPProvider resource://gre/modules/addons/GMPProvider.jsm
-#endif
component {8866d8e3-4ea5-48b7-a891-13ba0ac15235} amWebAPI.js
contract @mozilla.org/addon-web-api/manager;1 {8866d8e3-4ea5-48b7-a891-13ba0ac15235}
diff --git a/toolkit/mozapps/webextensions/internal/AddonUpdateChecker.jsm b/toolkit/mozapps/webextensions/internal/AddonUpdateChecker.jsm
index 918ba5328..bdd3a81e7 100644
--- a/toolkit/mozapps/webextensions/internal/AddonUpdateChecker.jsm
+++ b/toolkit/mozapps/webextensions/internal/AddonUpdateChecker.jsm
@@ -929,8 +929,17 @@ this.AddonUpdateChecker = {
* down in-progress update requests
*/
checkForUpdates: function(aId, aUpdateKey, aUrl, aObserver) {
- // Exclude default theme
- if (aId != "{972ce4c6-7e08-4474-a285-3208198ce6fd}")
+ // Define an array of internally used IDs to NOT send to AUS such as the
+ // Default Theme. Please keep this list in sync with:
+ // toolkit/mozapps/extensions/AddonUpdateChecker.jsm
+ let internalIDS = [
+ '{972ce4c6-7e08-4474-a285-3208198ce6fd}',
+ 'modern@themes.mozilla.org'
+ ];
+
+ // If the ID is not in the array then go ahead and query AUS
+ if (internalIDS.indexOf(aId) == -1) {
return new UpdateParser(aId, aUpdateKey, aUrl, aObserver);
+ }
}
};
diff --git a/toolkit/mozapps/webextensions/nsBlocklistService.js b/toolkit/mozapps/webextensions/nsBlocklistService.js
index 0af90430c..268c197fc 100644
--- a/toolkit/mozapps/webextensions/nsBlocklistService.js
+++ b/toolkit/mozapps/webextensions/nsBlocklistService.js
@@ -907,10 +907,6 @@ Blocklist.prototype = {
this._handleEmItemNode);
break;
case "pluginItems":
- // We don't support plugins on b2g.
- if (AppConstants.MOZ_B2G) {
- return;
- }
this._pluginEntries = this._processItemNodes(element.childNodes, "pluginItem",
this._handlePluginItemNode);
break;
@@ -1151,8 +1147,7 @@ Blocklist.prototype = {
/* See nsIBlocklistService */
getPluginBlocklistState: function(plugin, appVersion, toolkitVersion) {
- if (AppConstants.platform == "android" ||
- AppConstants.MOZ_B2G) {
+ if (AppConstants.platform == "android") {
return Ci.nsIBlocklistService.STATE_NOT_BLOCKED;
}
if (!this._isBlocklistLoaded())
@@ -1314,10 +1309,6 @@ Blocklist.prototype = {
},
_blocklistUpdated: function(oldAddonEntries, oldPluginEntries) {
- if (AppConstants.MOZ_B2G) {
- return;
- }
-
var addonList = [];
// A helper function that reverts the prefs passed to default values.
diff --git a/toolkit/profile/nsProfileLock.cpp b/toolkit/profile/nsProfileLock.cpp
index cc9ecb62e..d75b6082d 100644
--- a/toolkit/profile/nsProfileLock.cpp
+++ b/toolkit/profile/nsProfileLock.cpp
@@ -30,10 +30,6 @@
#include "prenv.h"
#endif
-#if defined(MOZ_WIDGET_GONK)
-#include <sys/syscall.h>
-#endif
-
// **********************************************************************
// class nsProfileLock
//
@@ -192,25 +188,6 @@ void nsProfileLock::FatalSignalHandler(int signo
}
}
-#ifdef MOZ_WIDGET_GONK
- switch (signo) {
- case SIGQUIT:
- case SIGILL:
- case SIGABRT:
- case SIGSEGV:
- // Retrigger the signal for those that can generate a core dump
- signal(signo, SIG_DFL);
- if (info->si_code <= 0) {
- if (syscall(__NR_tgkill, getpid(), syscall(__NR_gettid), signo) < 0) {
- break;
- }
- }
- return;
- default:
- break;
- }
-#endif
-
// Backstop exit call, just in case.
_exit(signo);
}
diff --git a/toolkit/themes/linux/global/inContentUI.css b/toolkit/themes/linux/global/inContentUI.css
new file mode 100644
index 000000000..afcef9274
--- /dev/null
+++ b/toolkit/themes/linux/global/inContentUI.css
@@ -0,0 +1,41 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * The default namespace for this file is XUL. Be sure to prefix rules that
+ * are applicable to both XUL and HTML with '*|'.
+ */
+@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
+@namespace html url("http://www.w3.org/1999/xhtml");
+
+/* Page background */
+*|*:root {
+ -moz-appearance: none;
+ padding: 18px;
+ background-color: Window;
+ background-image: /* Texture */
+ url("chrome://global/skin/inContentUI/background-texture.png");
+ color: WindowText;
+}
+
+/* Use the new in-content colors for #contentAreaDownloadsView. After landing
+ of bug 989469 the colors can be moved to *|*:root */
+*|*#contentAreaDownloadsView {
+ background: #f1f1f1;
+ color: #424e5a;
+}
+
+html|html {
+ font: message-box;
+}
+
+/* Content */
+*|*.main-content {
+ /* Needed to allow the radius to clip the inner content, see bug 595656 */
+ overflow: hidden;
+ background-color: -moz-Field;
+ color: -moz-FieldText;
+ border: 1px solid ThreeDShadow;
+ border-radius: 5px;
+}
diff --git a/toolkit/themes/linux/global/jar.mn b/toolkit/themes/linux/global/jar.mn
index b0d0b9ddb..0efc8c5cf 100644
--- a/toolkit/themes/linux/global/jar.mn
+++ b/toolkit/themes/linux/global/jar.mn
@@ -16,6 +16,7 @@ toolkit.jar:
skin/classic/global/findBar.css
skin/classic/global/global.css
skin/classic/global/groupbox.css
+ skin/classic/global/inContentUI.css
skin/classic/global/listbox.css
skin/classic/global/menu.css
skin/classic/global/menulist.css
diff --git a/toolkit/themes/osx/global/inContentUI.css b/toolkit/themes/osx/global/inContentUI.css
new file mode 100644
index 000000000..17e2e6ae3
--- /dev/null
+++ b/toolkit/themes/osx/global/inContentUI.css
@@ -0,0 +1,144 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.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 shared.inc
+
+/*
+ * The default namespace for this file is XUL. Be sure to prefix rules that
+ * are applicable to both XUL and HTML with '*|'.
+ */
+@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
+@namespace html url("http://www.w3.org/1999/xhtml");
+
+/* Page background */
+*|*:root {
+ -moz-appearance: none;
+ padding: 18px;
+ background-image: /* Texture */
+ url("chrome://global/skin/inContentUI/background-texture.png"),
+ /* Gradient */
+ linear-gradient(#ADB5C2, #BFC6D1);
+}
+
+/* Use the new in-content colors for #contentAreaDownloadsView. After landing
+ of bug 989469 the colors can be moved to *|*:root */
+*|*#contentAreaDownloadsView {
+ background: #f1f1f1;
+ color: #424e5a;
+}
+
+html|html {
+ font: message-box;
+}
+
+/* Content */
+*|*.main-content {
+ /* Needed to allow the radius to clip the inner content, see bug 595656 */
+ overflow: hidden;
+ background-image: linear-gradient(rgba(255, 255, 255, 0.4), rgba(255, 255, 255, 0.25) 50%, rgba(255, 255, 255, 0.05));
+ border: 1px solid rgba(50, 65, 92, 0.4);
+ border-radius: 5px;
+}
+
+/* Buttons */
+*|button,
+menulist,
+colorpicker[type="button"] {
+ -moz-appearance: none;
+ padding: 1px 4px;
+ min-width: 60px;
+ border-radius: 3px;
+ border: 1px solid rgba(60,73,97,0.5);
+ box-shadow: inset 0 1px rgba(255,255,255,0.25), 0 1px rgba(255,255,255,0.25);
+ background-color: transparent;
+ background-image: linear-gradient(rgba(255,255,255,0.45), rgba(255,255,255,0.2));
+ background-clip: padding-box;
+ color: #252F3B;
+ text-shadow: @loweredShadow@;
+}
+
+button:-moz-focusring > .button-box,
+menulist:-moz-focusring:not([open="true"]) > .menulist-label-box,
+colorpicker[type="button"]:-moz-focusring:not([open="true"]) > .colorpicker-button-colorbox {
+ outline: 1px dotted #252F3B;
+}
+
+html|button[disabled],
+button[disabled="true"],
+menulist[disabled="true"],
+colorpicker[type="button"][disabled="true"] {
+ opacity: 0.8;
+ color: #505050;
+}
+
+html|button:not([disabled]):active:hover,
+button:not([disabled="true"]):active:hover,
+menulist[open="true"]:not([disabled="true"]),
+colorpicker[type="button"][open="true"]:not([disabled="true"]) {
+ box-shadow: inset 0 1px 3px rgba(0,0,0,.2), 0 1px rgba(255,255,255,0.25);
+ background-image: linear-gradient(rgba(45,54,71,0.3), rgba(45,54,71,0.1));
+ border-color: rgba(60,73,97,0.7);
+}
+
+menulist {
+ -moz-padding-end: 0;
+ margin-left: 5px;
+ margin-right: 5px;
+}
+
+/* Tweak margins so the focus ring is in the right place. */
+menulist > .menulist-label-box {
+ -moz-margin-end: 3px;
+ margin-top: 1px;
+}
+
+menulist > .menulist-label-box > .menulist-label {
+ margin-top: 0px !important;
+ margin-bottom: 0px !important;
+}
+
+menulist > .menulist-dropmarker {
+ -moz-appearance: none;
+ display: -moz-box;
+ background: transparent;
+ border: none;
+ -moz-border-start: 1px solid rgba(60,73,97,0.5);
+ margin-top: -1px;
+ margin-bottom: -1px;
+}
+
+colorpicker[type="button"] {
+ margin: 1px 5px 2px 5px;
+ padding: 3px;
+ height: 25px;
+}
+
+spinbuttons {
+ -moz-appearance: none;
+}
+
+spinbuttons > .spinbuttons-box > .spinbuttons-button {
+ min-width: 12px;
+}
+
+.spinbuttons-button > .button-box > .button-text {
+ display: none;
+}
+
+.spinbuttons-button[disabled="true"] > .button-box > .button-icon {
+ opacity: 0.5;
+}
+
+spinbuttons > .spinbuttons-box > .spinbuttons-up {
+ list-style-image: url("chrome://global/skin/arrow/arrow-up.gif");
+ border-bottom-width: 0;
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: 0;
+}
+
+spinbuttons > .spinbuttons-box > .spinbuttons-down {
+ list-style-image: url("chrome://global/skin/arrow/arrow-dn.gif");
+ border-top-left-radius: 0;
+ border-top-right-radius: 0;
+}
diff --git a/toolkit/themes/osx/global/jar.mn b/toolkit/themes/osx/global/jar.mn
index 79bb062ab..9407ccee5 100644
--- a/toolkit/themes/osx/global/jar.mn
+++ b/toolkit/themes/osx/global/jar.mn
@@ -21,6 +21,7 @@ toolkit.jar:
* skin/classic/global/findBar.css
* skin/classic/global/global.css
skin/classic/global/groupbox.css
+* skin/classic/global/inContentUI.css
skin/classic/global/linkTree.css
skin/classic/global/listbox.css
skin/classic/global/menu.css
diff --git a/toolkit/themes/shared/alert-common.css b/toolkit/themes/shared/alert-common.css
index 010e89393..17510c0db 100644
--- a/toolkit/themes/shared/alert-common.css
+++ b/toolkit/themes/shared/alert-common.css
@@ -15,14 +15,12 @@
}
#alertBox[animate][clicked] {
- animation-duration: .6s;
animation-name: alert-clicked-animation;
}
/* This is used if the close button is clicked
before the animation has finished. */
#alertBox[animate][closing] {
- animation-duration: .6s;
animation-name: alert-closing-animation;
}
diff --git a/toolkit/themes/windows/global/inContentUI.css b/toolkit/themes/windows/global/inContentUI.css
new file mode 100644
index 000000000..a3bca7b06
--- /dev/null
+++ b/toolkit/themes/windows/global/inContentUI.css
@@ -0,0 +1,159 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/*
+ * The default namespace for this file is XUL. Be sure to prefix rules that
+ * are applicable to both XUL and HTML with '*|'.
+ */
+@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
+@namespace html url("http://www.w3.org/1999/xhtml");
+
+/* Page background */
+*|*:root {
+ -moz-appearance: none;
+ padding: 18px;
+ background-repeat: repeat;
+ color: -moz-dialogText;
+ background-color: -moz-dialog;
+ background-image: /* Texture */
+ url("chrome://global/skin/inContentUI/background-texture.png");
+}
+
+html|html {
+ font: message-box;
+}
+
+@media (-moz-windows-default-theme) and (-moz-os-version: windows-vista),
+ (-moz-windows-default-theme) and (-moz-os-version: windows-win7) {
+ *|*:root {
+ color: #000;
+ background-color: #CCD9EA;
+ }
+}
+
+@media (-moz-windows-glass) {
+ *|*:root {
+ /* Blame shorlander for this monstrosity. */
+ background-image: /* Side gradients */
+ linear-gradient(to right,
+ rgba(255,255,255,0.2), transparent 40%,
+ transparent 60%, rgba(255,255,255,0.2)),
+ /* Aero-style light beams */
+ -moz-linear-gradient(left 32deg,
+ /* First light beam */
+ transparent 19.5%, rgba(255,255,255,0.1) 20%,
+ rgba(255,255,255,0.1) 21.5%, rgba(255,255,255,0.2) 22%,
+ rgba(255,255,255,0.2) 25.5%, rgba(255,255,255,0.1) 26%,
+ rgba(255,255,255,0.1) 27.5%, transparent 28%,
+ /* Second light beam */
+ transparent 49.5%, rgba(255,255,255,0.1) 50%,
+ rgba(255,255,255,0.1) 52.5%, rgba(255,255,255,0.2) 53%,
+ rgba(255,255,255,0.2) 54.5%, rgba(255,255,255,0.1) 55%,
+ rgba(255,255,255,0.1) 57.5%, transparent 58%,
+ /* Third light beam */
+ transparent 87%, rgba(255,255,255,0.2) 90%),
+ /* Texture */
+ url("chrome://global/skin/inContentUI/background-texture.png");
+ }
+}
+
+/* Use the new in-content colors for #contentAreaDownloadsView. After landing
+ of bug 989469 the colors can be moved to *|*:root */
+*|*#contentAreaDownloadsView {
+ background: #f1f1f1;
+ color: #424e5a;
+}
+
+/* Content */
+*|*.main-content {
+ /* Needed to allow the radius to clip the inner content, see bug 595656 */
+ overflow: hidden;
+ background-color: rgba(255, 255, 255, 0.35);
+ background-image: linear-gradient(rgba(255, 255, 255, 0),
+ rgba(255, 255, 255, 0.75));
+ border: 1px solid #C3CEDF;
+}
+
+%ifdef XP_WIN
+@media (-moz-os-version: windows-vista),
+ (-moz-os-version: windows-win7) {
+%endif
+ *|*.main-content {
+ border-radius: 5px;
+ }
+%ifdef XP_WIN
+}
+%endif
+
+@media (-moz-windows-glass) {
+ /* Buttons */
+ *|button,
+ menulist,
+ colorpicker[type="button"] {
+ -moz-appearance: none;
+ color: black;
+ padding: 0 5px;
+ background: linear-gradient(rgba(251, 252, 253, 0.95), transparent 49%,
+ rgba(211, 212, 213, 0.45) 51%, rgba(225, 226, 229, 0.3));
+ background-clip: padding-box;
+ border-radius: 3px;
+ border: 1px solid rgba(31, 64, 100, 0.4);
+ border-top-color: rgba(31, 64, 100, 0.3);
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.25) inset,
+ 0 0 2px 1px rgba(255, 255, 255, 0.25) inset;
+ }
+
+ menulist {
+ -moz-padding-end: 0;
+ }
+
+ colorpicker[type="button"]:-moz-focusring:not([open="true"]) > .colorpicker-button-colorbox {
+ outline: 1px dotted ThreeDDarkShadow;
+ }
+
+ html|button[disabled],
+ button[disabled="true"],
+ menulist[disabled="true"],
+ colorpicker[type="button"][disabled="true"] {
+ -moz-border-top-colors: rgba(31, 64, 100, 0.3) !important;
+ -moz-border-right-colors: rgba(31, 64, 100, 0.4) !important;
+ -moz-border-bottom-colors: rgba(31, 64, 100, 0.4) !important;
+ -moz-border-left-colors: rgba(31, 64, 100, 0.4) !important;
+ opacity: 0.8;
+ color: #505050;
+ }
+
+ html|button:not([disabled]):active:hover,
+ button:not([disabled="true"]):active:hover,
+ menulist[open="true"]:not([disabled="true"]),
+ colorpicker[type="button"][open="true"]:not([disabled="true"]) {
+ background-color: rgba(61, 76, 92, 0.2);
+ border-color: rgba(39, 53, 68, 0.5);
+ box-shadow: 0 0 3px 1px rgba(39, 53, 68, 0.2) inset;
+ }
+
+ button > .button-box {
+ padding: 1px !important;
+ }
+
+ spinbuttons > .spinbuttons-box > .spinbuttons-button {
+ border-radius: 0;
+ padding: 0 4px;
+ }
+
+ spinbuttons > .spinbuttons-box > .spinbuttons-up {
+ list-style-image: url("chrome://global/skin/arrow/arrow-up.gif");
+ border-bottom-width: 0;
+ }
+
+ spinbuttons > .spinbuttons-box > .spinbuttons-down {
+ list-style-image: url("chrome://global/skin/arrow/arrow-dn.gif");
+ }
+}
+
+colorpicker[type="button"] {
+ margin: 1px 5px 2px 5px;
+ padding: 3px;
+ height: 25px;
+}
diff --git a/toolkit/themes/windows/global/jar.mn b/toolkit/themes/windows/global/jar.mn
index a6ccbd71d..8c5d5de5a 100644
--- a/toolkit/themes/windows/global/jar.mn
+++ b/toolkit/themes/windows/global/jar.mn
@@ -27,6 +27,7 @@ toolkit.jar:
skin/classic/global/console/itemSelected.png (console/itemSelected.png)
skin/classic/global/findBar.css
* skin/classic/global/global.css
+* skin/classic/global/inContentUI.css
skin/classic/global/listbox.css
skin/classic/global/netError.css
skin/classic/global/numberbox.css
diff --git a/toolkit/toolkit.mozbuild b/toolkit/toolkit.mozbuild
index 3b3bf80ae..98c109c1b 100644
--- a/toolkit/toolkit.mozbuild
+++ b/toolkit/toolkit.mozbuild
@@ -4,12 +4,8 @@
# License, v. 2.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_SANDBOX']:
- DIRS += ['/security/sandbox']
-
DIRS += [
- # Depends on NSS and NSPR, and must be built after sandbox or else B2G emulator
- # builds fail.
+ # Depends on NSS and NSPR
'/security/certverifier',
# Depends on certverifier
'/security/apps',
@@ -132,8 +128,7 @@ DIRS += [
if CONFIG['MOZ_PREF_EXTENSIONS']:
DIRS += ['/extensions/pref']
-if CONFIG['MOZ_DEVTOOLS_SERVER']:
- DIRS += ['/devtools']
+DIRS += ['/devtools']
DIRS += [
'/services',
@@ -153,7 +148,7 @@ DIRS += [
if 'gtk' in CONFIG['MOZ_WIDGET_TOOLKIT']:
DIRS += ['/toolkit/system/gnome']
-if CONFIG['ENABLE_MARIONETTE'] or CONFIG['MOZ_WIDGET_TOOLKIT'] not in ('gonk', 'android'):
+if CONFIG['ENABLE_MARIONETTE'] or CONFIG['MOZ_WIDGET_TOOLKIT'] not in ('android'):
DIRS += [
'/testing/firefox-ui',
'/testing/marionette',
diff --git a/toolkit/xre/EventTracer.cpp b/toolkit/xre/EventTracer.cpp
index cb0d88524..f1118f1b2 100644
--- a/toolkit/xre/EventTracer.cpp
+++ b/toolkit/xre/EventTracer.cpp
@@ -65,12 +65,6 @@
#include <prthread.h>
#include <prtime.h>
-#ifdef MOZ_WIDGET_GONK
-#include "nsThreadUtils.h"
-#include "nsIObserverService.h"
-#include "mozilla/Services.h"
-#endif
-
using mozilla::TimeDuration;
using mozilla::TimeStamp;
using mozilla::FireAndWaitForTracerEvent;
@@ -85,31 +79,6 @@ struct TracerStartClosure {
int32_t mThresholdInterval;
};
-#ifdef MOZ_WIDGET_GONK
-class EventLoopLagDispatcher : public Runnable
-{
- public:
- explicit EventLoopLagDispatcher(int aLag)
- : mLag(aLag) {}
-
- NS_IMETHOD Run() override
- {
- nsCOMPtr<nsIObserverService> obsService =
- mozilla::services::GetObserverService();
- if (!obsService) {
- return NS_ERROR_FAILURE;
- }
-
- nsAutoString value;
- value.AppendInt(mLag);
- return obsService->NotifyObservers(nullptr, "event-loop-lag", value.get());
- }
-
- private:
- int mLag;
-};
-#endif
-
/*
* The tracer thread fires events at the native event loop roughly
* every kMeasureInterval. It will sleep to attempt not to send them
@@ -180,10 +149,6 @@ void TracerThread(void *arg)
fprintf(log, "MOZ_EVENT_TRACE sample %llu %lf\n",
now,
duration.ToMilliseconds());
-#ifdef MOZ_WIDGET_GONK
- NS_DispatchToMainThread(
- new EventLoopLagDispatcher(int(duration.ToSecondsSigDigits() * 1000)));
-#endif
}
if (next_sleep > duration.ToMilliseconds()) {
diff --git a/toolkit/xre/moz.build b/toolkit/xre/moz.build
index 7ada19d41..55b59ca83 100644
--- a/toolkit/xre/moz.build
+++ b/toolkit/xre/moz.build
@@ -149,12 +149,6 @@ LOCAL_INCLUDES += [
'/xpcom/build',
]
-if CONFIG['MOZ_SANDBOX'] and CONFIG['OS_ARCH'] == 'WINNT':
- LOCAL_INCLUDES += [
- '/security/sandbox/chromium',
- '/security/sandbox/chromium-shim',
- ]
-
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
LOCAL_INCLUDES += [
'/widget',
diff --git a/toolkit/xre/nsAppRunner.cpp b/toolkit/xre/nsAppRunner.cpp
index 3493cd837..2050b9671 100644
--- a/toolkit/xre/nsAppRunner.cpp
+++ b/toolkit/xre/nsAppRunner.cpp
@@ -106,10 +106,6 @@
#endif
#endif
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
-#include "nsIUUIDGenerator.h"
-#endif
-
#ifdef ACCESSIBILITY
#include "nsAccessibilityService.h"
#if defined(XP_WIN)
@@ -197,14 +193,6 @@
#include "GeneratedJNIWrappers.h"
#endif
-#if defined(MOZ_SANDBOX)
-#if defined(XP_LINUX) && !defined(ANDROID)
-#include "mozilla/SandboxInfo.h"
-#elif defined(XP_WIN)
-#include "SandboxBroker.h"
-#endif
-#endif
-
extern uint32_t gRestartMode;
extern void InstallSignalHandlers(const char *ProgramName);
@@ -2952,25 +2940,6 @@ XREMain::XRE_mainInit(bool* aExitFlag)
if (NS_FAILED(rv))
return 1;
-#if defined(MOZ_SANDBOX) && defined(XP_WIN)
- if (mAppData->sandboxBrokerServices) {
- SandboxBroker::Initialize(mAppData->sandboxBrokerServices);
- Telemetry::Accumulate(Telemetry::SANDBOX_BROKER_INITIALIZED, true);
- } else {
- Telemetry::Accumulate(Telemetry::SANDBOX_BROKER_INITIALIZED, false);
-#if defined(MOZ_CONTENT_SANDBOX)
- // If we're sandboxing content and we fail to initialize, then crashing here
- // seems like the sensible option.
- if (BrowserTabsRemoteAutostart()) {
- MOZ_CRASH("Failed to initialize broker services, can't continue.");
- }
-#endif
- // Otherwise just warn for the moment, as most things will work.
- NS_WARNING("Failed to initialize broker services, sandboxed processes will "
- "fail to start.");
- }
-#endif
-
#ifdef XP_MACOSX
// Set up ability to respond to system (Apple) events. This must occur before
// ProcessUpdates to ensure that links clicked in external applications aren't
@@ -3913,24 +3882,6 @@ XREMain::XRE_mainRun()
}
#endif /* MOZ_INSTRUMENT_EVENT_LOOP */
-#if defined(MOZ_SANDBOX) && defined(XP_LINUX) && !defined(MOZ_WIDGET_GONK)
- // If we're on Linux, we now have information about the OS capabilities
- // available to us.
- SandboxInfo sandboxInfo = SandboxInfo::Get();
- Telemetry::Accumulate(Telemetry::SANDBOX_HAS_SECCOMP_BPF,
- sandboxInfo.Test(SandboxInfo::kHasSeccompBPF));
- Telemetry::Accumulate(Telemetry::SANDBOX_HAS_SECCOMP_TSYNC,
- sandboxInfo.Test(SandboxInfo::kHasSeccompTSync));
- Telemetry::Accumulate(Telemetry::SANDBOX_HAS_USER_NAMESPACES_PRIVILEGED,
- sandboxInfo.Test(SandboxInfo::kHasPrivilegedUserNamespaces));
- Telemetry::Accumulate(Telemetry::SANDBOX_HAS_USER_NAMESPACES,
- sandboxInfo.Test(SandboxInfo::kHasUserNamespaces));
- Telemetry::Accumulate(Telemetry::SANDBOX_CONTENT_ENABLED,
- sandboxInfo.Test(SandboxInfo::kEnabledForContent));
- Telemetry::Accumulate(Telemetry::SANDBOX_MEDIA_ENABLED,
- sandboxInfo.Test(SandboxInfo::kEnabledForMedia));
-#endif /* MOZ_SANDBOX && XP_LINUX && !MOZ_WIDGET_GONK */
-
{
rv = appStartup->Run();
if (NS_FAILED(rv)) {
@@ -3996,10 +3947,6 @@ XREMain::XRE_main(int argc, char* argv[], const nsXREAppData* aAppData)
// See bug 1279614.
XRE_CreateStatsObject();
-#if defined(MOZ_SANDBOX) && defined(XP_LINUX) && !defined(ANDROID)
- SandboxInfo::ThreadingCheck();
-#endif
-
char aLocal;
GeckoProfilerInitRAII profilerGuard(&aLocal);
diff --git a/toolkit/xre/nsEmbedFunctions.cpp b/toolkit/xre/nsEmbedFunctions.cpp
index 4a612e495..f62dbdd6d 100644
--- a/toolkit/xre/nsEmbedFunctions.cpp
+++ b/toolkit/xre/nsEmbedFunctions.cpp
@@ -75,15 +75,6 @@
#include "mozilla/Telemetry.h"
-#if defined(MOZ_SANDBOX) && defined(XP_WIN)
-#include "mozilla/sandboxTarget.h"
-#include "mozilla/sandboxing/loggingCallbacks.h"
-#endif
-
-#if defined(MOZ_CONTENT_SANDBOX) && !defined(MOZ_WIDGET_GONK)
-#include "mozilla/Preferences.h"
-#endif
-
#ifdef MOZ_IPDL_TESTS
#include "mozilla/_ipdltest/IPDLUnitTests.h"
#include "mozilla/_ipdltest/IPDLUnitTestProcessChild.h"
@@ -264,7 +255,7 @@ XRE_InitChildProcess(int aArgc,
setupProfilingStuff();
#endif
-#if !defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if !defined(MOZ_WIDGET_ANDROID)
// On non-Fennec Gecko, the GMPLoader code resides in plugin-container,
// and we must forward it through to the GMP code here.
GMPProcessChild::SetGMPLoader(aChildData->gmpLoader.get());
@@ -299,11 +290,6 @@ XRE_InitChildProcess(int aArgc,
freopen("CONIN$", "r", stdin);
}
-#if defined(MOZ_SANDBOX)
- if (aChildData->sandboxTargetServices) {
- SandboxTarget::Instance()->SetTargetServices(aChildData->sandboxTargetServices);
- }
-#endif
#endif
// NB: This must be called before profiler_init
@@ -519,11 +505,6 @@ XRE_InitChildProcess(int aArgc,
// If passed in grab the application path for xpcom init
bool foundAppdir = false;
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
- // If passed in grab the profile path for sandboxing
- bool foundProfile = false;
-#endif
-
for (int idx = aArgc; idx > 0; idx--) {
if (aArgv[idx] && !strcmp(aArgv[idx], "-appdir")) {
MOZ_ASSERT(!foundAppdir);
@@ -539,19 +520,6 @@ XRE_InitChildProcess(int aArgc,
if (aArgv[idx] && !strcmp(aArgv[idx], "-safeMode")) {
gSafeMode = true;
}
-
-#if defined(XP_MACOSX) && defined(MOZ_CONTENT_SANDBOX)
- if (aArgv[idx] && !strcmp(aArgv[idx], "-profile")) {
- MOZ_ASSERT(!foundProfile);
- if (foundProfile) {
- continue;
- }
- nsCString profile;
- profile.Assign(nsDependentCString(aArgv[idx+1]));
- static_cast<ContentProcess*>(process.get())->SetProfile(profile);
- foundProfile = true;
- }
-#endif /* XP_MACOSX && MOZ_CONTENT_SANDBOX */
}
}
break;
@@ -587,12 +555,6 @@ XRE_InitChildProcess(int aArgc,
::SetProcessShutdownParameters(0x280 - 1, SHUTDOWN_NORETRY);
#endif
-#if defined(MOZ_SANDBOX) && defined(XP_WIN)
- // We need to do this after the process has been initialised, as
- // InitLoggingIfRequired may need access to prefs.
- mozilla::sandboxing::InitLoggingIfRequired(aChildData->ProvideLogFunction);
-#endif
-
OverrideDefaultLocaleIfNeeded();
// Run the UI event loop on the main thread.
diff --git a/toolkit/xre/nsUpdateDriver.cpp b/toolkit/xre/nsUpdateDriver.cpp
index 54a711000..ab0bdf005 100644
--- a/toolkit/xre/nsUpdateDriver.cpp
+++ b/toolkit/xre/nsUpdateDriver.cpp
@@ -74,23 +74,6 @@ GetUpdateLog()
#define UPDATER_PNG "updater.png"
#endif
-#if defined(MOZ_WIDGET_GONK)
-#include <linux/ioprio.h>
-
-static const int kB2GServiceArgc = 2;
-static const char *kB2GServiceArgv[] = { "/system/bin/start", "b2g" };
-
-static const char kAppUpdaterPrio[] = "app.update.updater.prio";
-static const char kAppUpdaterOomScoreAdj[] = "app.update.updater.oom_score_adj";
-static const char kAppUpdaterIOPrioClass[] = "app.update.updater.ioprio.class";
-static const char kAppUpdaterIOPrioLevel[] = "app.update.updater.ioprio.level";
-
-static const int kAppUpdaterPrioDefault = 19; // -20..19 where 19 = lowest priority
-static const int kAppUpdaterOomScoreAdjDefault = -1000; // -1000 = Never kill
-static const int kAppUpdaterIOPrioClassDefault = IOPRIO_CLASS_IDLE;
-static const int kAppUpdaterIOPrioLevelDefault = 0; // Doesn't matter for CLASS IDLE
-#endif
-
static nsresult
GetCurrentWorkingDir(char *buf, size_t size)
{
@@ -387,7 +370,7 @@ CopyUpdaterIntoUpdateDir(nsIFile *greDir, nsIFile *appDir, nsIFile *updateDir,
* @param pathToAppend A new library path to prepend to LD_LIBRARY_PATH
*/
#if defined(MOZ_VERIFY_MAR_SIGNATURE) && !defined(XP_WIN) && \
- !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+ !defined(XP_MACOSX)
#include "prprf.h"
#define PATH_SEPARATOR ":"
#define LD_LIBRARY_PATH_ENVVAR_NAME "LD_LIBRARY_PATH"
@@ -503,15 +486,9 @@ SwitchToUpdatedApp(nsIFile *greDir, nsIFile *updateDir,
#else
nsAutoCString appFilePath;
-#if defined(MOZ_WIDGET_GONK)
- appFilePath.Assign(kB2GServiceArgv[0]);
- appArgc = kB2GServiceArgc;
- appArgv = const_cast<char**>(kB2GServiceArgv);
-#else
rv = appFile->GetNativePath(appFilePath);
if (NS_FAILED(rv))
return;
-#endif
nsAutoCString updaterPath;
rv = updater->GetNativePath(updaterPath);
@@ -617,19 +594,13 @@ SwitchToUpdatedApp(nsIFile *greDir, nsIFile *updateDir,
PR_SetEnv("MOZ_SAFE_MODE_RESTART=1");
}
#if defined(MOZ_VERIFY_MAR_SIGNATURE) && !defined(XP_WIN) && \
- !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+ !defined(XP_MACOSX)
AppendToLibPath(installDirPath.get());
#endif
LOG(("spawning updater process for replacing [%s]\n", updaterPath.get()));
#if defined(XP_UNIX) & !defined(XP_MACOSX)
-# if defined(MOZ_WIDGET_GONK)
- // In Gonk, we preload libmozglue, which the updater process doesn't need.
- // Since the updater will move and delete libmozglue.so, this can actually
- // stop the /system mount from correctly being remounted as read-only.
- unsetenv("LD_PRELOAD");
-# endif
exit(execv(updaterPath.get(), argv));
#elif defined(XP_WIN)
// Switch the application using updater.exe
@@ -647,46 +618,6 @@ SwitchToUpdatedApp(nsIFile *greDir, nsIFile *updateDir,
#endif
}
-#if defined(MOZ_WIDGET_GONK)
-static nsresult
-GetOSApplyToDir(nsACString& applyToDir)
-{
- nsCOMPtr<nsIProperties> ds =
- do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
- NS_ASSERTION(ds, "Can't get directory service");
-
- nsCOMPtr<nsIFile> osApplyToDir;
- nsresult rv = ds->Get(XRE_OS_UPDATE_APPLY_TO_DIR, NS_GET_IID(nsIFile),
- getter_AddRefs(osApplyToDir));
- if (NS_FAILED(rv)) {
- LOG(("Can't get the OS applyTo dir"));
- return rv;
- }
-
- return osApplyToDir->GetNativePath(applyToDir);
-}
-
-static void
-SetOSApplyToDir(nsIUpdate* update, const nsACString& osApplyToDir)
-{
- nsresult rv;
- nsCOMPtr<nsIWritablePropertyBag> updateProperties =
- do_QueryInterface(update, &rv);
-
- if (NS_FAILED(rv)) {
- return;
- }
-
- RefPtr<nsVariant> variant = new nsVariant();
- rv = variant->SetAsACString(osApplyToDir);
- if (NS_FAILED(rv)) {
- return;
- }
-
- updateProperties->SetProperty(NS_LITERAL_STRING("osApplyToDir"), variant);
-}
-#endif
-
/**
* Apply an update. This applies to both normal and staged updates.
*
@@ -780,13 +711,9 @@ ApplyUpdate(nsIFile *greDir, nsIFile *updateDir, nsIFile *statusFile,
if (NS_FAILED(rv))
return;
- // Get the directory where the update was staged for replace and GONK OS
- // Updates or where it will be applied.
-#ifndef MOZ_WIDGET_GONK
- // OS Updates are only supported on GONK so force it to false on everything
+ // OS Updates were only supported on GONK so force it to false on everything
// but GONK to simplify the following logic.
isOSUpdate = false;
-#endif
nsAutoCString applyToDir;
nsCOMPtr<nsIFile> updatedDir;
if (restart && !isOSUpdate) {
@@ -806,15 +733,6 @@ ApplyUpdate(nsIFile *greDir, nsIFile *updateDir, nsIFile *statusFile,
return;
}
applyToDir = NS_ConvertUTF16toUTF8(applyToDirW);
-#elif MOZ_WIDGET_GONK
- if (isOSUpdate) {
- if (!osApplyToDir) {
- return;
- }
- rv = osApplyToDir->GetNativePath(applyToDir);
- } else {
- rv = updatedDir->GetNativePath(applyToDir);
- }
#else
rv = updatedDir->GetNativePath(applyToDir);
#endif
@@ -900,33 +818,13 @@ ApplyUpdate(nsIFile *greDir, nsIFile *updateDir, nsIFile *statusFile,
PR_SetEnv("MOZ_SAFE_MODE_RESTART=1");
}
#if defined(MOZ_VERIFY_MAR_SIGNATURE) && !defined(XP_WIN) && \
- !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
+ !defined(XP_MACOSX)
AppendToLibPath(installDirPath.get());
#endif
if (isOSUpdate) {
PR_SetEnv("MOZ_OS_UPDATE=1");
}
-#if defined(MOZ_WIDGET_GONK)
- // We want the updater to be CPU friendly and not subject to being killed by
- // the low memory killer, so we pass in some preferences to allow it to
- // adjust its priority.
-
- int32_t prioVal = Preferences::GetInt(kAppUpdaterPrio,
- kAppUpdaterPrioDefault);
- int32_t oomScoreAdj = Preferences::GetInt(kAppUpdaterOomScoreAdj,
- kAppUpdaterOomScoreAdjDefault);
- int32_t ioprioClass = Preferences::GetInt(kAppUpdaterIOPrioClass,
- kAppUpdaterIOPrioClassDefault);
- int32_t ioprioLevel = Preferences::GetInt(kAppUpdaterIOPrioLevel,
- kAppUpdaterIOPrioLevelDefault);
- nsPrintfCString prioEnv("MOZ_UPDATER_PRIO=%d/%d/%d/%d",
- prioVal, oomScoreAdj, ioprioClass, ioprioLevel);
- // Note: we allocate a new string on heap and pass that to PR_SetEnv, since
- // the string can be used after this function returns. This means that we
- // will intentionally leak this buffer.
- PR_SetEnv(ToNewCString(prioEnv));
-#endif
LOG(("spawning updater process [%s]\n", updaterPath.get()));
@@ -1122,12 +1020,6 @@ nsUpdateProcessor::ProcessUpdate(nsIUpdate* aUpdate)
// Check for and process any available updates
bool persistent;
nsresult rv = NS_ERROR_FAILURE; // Take the NS_FAILED path when non-GONK
-#ifdef MOZ_WIDGET_GONK
- // Check in the sdcard for updates first, since that's our preferred
- // download location.
- rv = dirProvider->GetFile(XRE_UPDATE_ARCHIVE_DIR, &persistent,
- getter_AddRefs(updRoot));
-#endif
if (NS_FAILED(rv)) {
rv = dirProvider->GetFile(XRE_UPDATE_ROOT_DIR, &persistent,
getter_AddRefs(updRoot));
@@ -1217,34 +1109,6 @@ nsUpdateProcessor::ProcessUpdate(nsIUpdate* aUpdate)
}
mInfo.mAppVersion = appVersion;
-#if defined(MOZ_WIDGET_GONK)
- NS_ENSURE_ARG_POINTER(aUpdate);
-
- bool isOSUpdate;
- if (NS_SUCCEEDED(aUpdate->GetIsOSUpdate(&isOSUpdate)) &&
- isOSUpdate) {
- nsAutoCString osApplyToDir;
-
- // This needs to be done on the main thread, so we pass it along in
- // BackgroundThreadInfo
- nsresult rv = GetOSApplyToDir(osApplyToDir);
- if (NS_FAILED(rv)) {
- LOG(("Can't get the OS apply to dir"));
- return rv;
- }
-
- SetOSApplyToDir(aUpdate, osApplyToDir);
-
- mInfo.mIsOSUpdate = true;
- rv = NS_NewNativeLocalFile(osApplyToDir, false,
- getter_AddRefs(mInfo.mOSApplyToDir));
- if (NS_FAILED(rv)) {
- LOG(("Can't create nsIFile for OS apply to dir"));
- return rv;
- }
- }
-#endif
-
MOZ_ASSERT(NS_IsMainThread(), "not main thread");
nsCOMPtr<nsIRunnable> r = NewRunnableMethod(this, &nsUpdateProcessor::StartStagedUpdate);
return NS_NewThread(getter_AddRefs(mProcessWatcher), r);
diff --git a/toolkit/xre/nsXREDirProvider.cpp b/toolkit/xre/nsXREDirProvider.cpp
index 09168319f..d904cb83a 100644
--- a/toolkit/xre/nsXREDirProvider.cpp
+++ b/toolkit/xre/nsXREDirProvider.cpp
@@ -62,11 +62,6 @@
#include "UIKitDirProvider.h"
#endif
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
-#include "nsIUUIDGenerator.h"
-#include "mozilla/Unused.h"
-#endif
-
#if defined(XP_MACOSX)
#define APP_REGISTRY_NAME "Application Registry"
#elif defined(XP_WIN)
@@ -77,14 +72,6 @@
#define PREF_OVERRIDE_DIRNAME "preferences"
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
-static already_AddRefed<nsIFile> GetContentProcessSandboxTempDir();
-static nsresult DeleteDirIfExists(nsIFile *dir);
-static bool IsContentSandboxDisabled();
-static const char* GetContentProcessTempBaseDirKey();
-static already_AddRefed<nsIFile> CreateContentProcessSandboxTempDir();
-#endif
-
static already_AddRefed<nsIFile>
CloneAndAppend(nsIFile* aFile, const char* name)
{
@@ -139,10 +126,6 @@ nsXREDirProvider::Initialize(nsIFile *aXULAppDir,
}
}
-#ifdef MOZ_B2G
- LoadAppBundleDirs();
-#endif
-
return NS_OK;
}
@@ -495,14 +478,6 @@ nsXREDirProvider::GetFile(const char* aProperty, bool* aPersistent,
bool unused;
rv = dirsvc->GetFile("XCurProcD", &unused, getter_AddRefs(file));
}
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
- else if (!strcmp(aProperty, NS_APP_CONTENT_PROCESS_TEMP_DIR)) {
- if (!mContentTempDir && NS_FAILED((rv = LoadContentProcessTempDir()))) {
- return rv;
- }
- rv = mContentTempDir->Clone(getter_AddRefs(file));
- }
-#endif // defined(XP_WIN) && defined(MOZ_CONTENT_SANDBOX)
else if (NS_SUCCEEDED(GetProfileStartupDir(getter_AddRefs(file)))) {
// We need to allow component, xpt, and chrome registration to
// occur prior to the profile-after-change notification.
@@ -729,176 +704,6 @@ LoadExtensionDirectories(nsINIParser &parser,
while (true);
}
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
-
-static const char*
-GetContentProcessTempBaseDirKey()
-{
-#if defined(XP_WIN)
- return NS_WIN_LOW_INTEGRITY_TEMP_BASE;
-#else
- return NS_OS_TEMP_DIR;
-#endif
-}
-
-//
-// Sets mContentTempDir so that it refers to the appropriate temp dir.
-// If the sandbox is enabled, NS_APP_CONTENT_PROCESS_TEMP_DIR, otherwise
-// NS_OS_TEMP_DIR is used.
-//
-nsresult
-nsXREDirProvider::LoadContentProcessTempDir()
-{
- mContentTempDir = GetContentProcessSandboxTempDir();
- if (mContentTempDir) {
- return NS_OK;
- } else {
- return NS_GetSpecialDirectory(NS_OS_TEMP_DIR,
- getter_AddRefs(mContentTempDir));
- }
-}
-
-static bool
-IsContentSandboxDisabled()
-{
- bool isSandboxDisabled = false;
- if (!BrowserTabsRemoteAutostart()) {
- return false;
- }
-#if defined(XP_WIN) || defined(XP_MACOSX)
- isSandboxDisabled = Preferences::GetInt("security.sandbox.content.level") < 1;
-#endif
- return isSandboxDisabled;
-}
-
-//
-// If a content process sandbox temp dir is to be used, returns an nsIFile
-// for the directory. Returns null if the content sandbox is disabled or
-// an error occurs.
-//
-static already_AddRefed<nsIFile>
-GetContentProcessSandboxTempDir()
-{
- if (IsContentSandboxDisabled()) {
- return nullptr;
- }
-
- nsCOMPtr<nsIFile> localFile;
-
- nsresult rv = NS_GetSpecialDirectory(GetContentProcessTempBaseDirKey(),
- getter_AddRefs(localFile));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return nullptr;
- }
-
- nsAutoString tempDirSuffix;
- rv = Preferences::GetString("security.sandbox.content.tempDirSuffix",
- &tempDirSuffix);
- if (NS_WARN_IF(NS_FAILED(rv)) || tempDirSuffix.IsEmpty()) {
- return nullptr;
- }
-
- rv = localFile->Append(NS_LITERAL_STRING("Temp-") + tempDirSuffix);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return nullptr;
- }
-
- return localFile.forget();
-}
-
-//
-// Create a temporary directory for use from sandboxed content processes.
-// Only called in the parent. The path is derived from a UUID stored in a
-// pref which is available to content processes. Returns null if the
-// content sandbox is disabled or if an error occurs.
-//
-static already_AddRefed<nsIFile>
-CreateContentProcessSandboxTempDir()
-{
- if (IsContentSandboxDisabled()) {
- return nullptr;
- }
-
- // Get (and create if blank) temp directory suffix pref.
- nsresult rv;
- nsAdoptingString tempDirSuffix =
- Preferences::GetString("security.sandbox.content.tempDirSuffix");
- if (tempDirSuffix.IsEmpty()) {
- nsCOMPtr<nsIUUIDGenerator> uuidgen =
- do_GetService("@mozilla.org/uuid-generator;1", &rv);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return nullptr;
- }
-
- nsID uuid;
- rv = uuidgen->GenerateUUIDInPlace(&uuid);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return nullptr;
- }
-
- char uuidChars[NSID_LENGTH];
- uuid.ToProvidedString(uuidChars);
- tempDirSuffix.AssignASCII(uuidChars);
-
- // Save the pref
- rv = Preferences::SetCString("security.sandbox.content.tempDirSuffix",
- uuidChars);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- // If we fail to save the pref we don't want to create the temp dir,
- // because we won't be able to clean it up later.
- return nullptr;
- }
-
- nsCOMPtr<nsIPrefService> prefsvc = Preferences::GetService();
- if (!prefsvc || NS_FAILED((rv = prefsvc->SavePrefFile(nullptr)))) {
- // Again, if we fail to save the pref file we might not be able to clean
- // up the temp directory, so don't create one.
- NS_WARNING("Failed to save pref file, cannot create temp dir.");
- return nullptr;
- }
- }
-
- nsCOMPtr<nsIFile> sandboxTempDir = GetContentProcessSandboxTempDir();
- if (!sandboxTempDir) {
- NS_WARNING("Failed to determine sandbox temp dir path.");
- return nullptr;
- }
-
- // Remove the directory. It may exist due to a previous crash.
- if (NS_FAILED(DeleteDirIfExists(sandboxTempDir))) {
- NS_WARNING("Failed to reset sandbox temp dir.");
- return nullptr;
- }
-
- // Create the directory
- rv = sandboxTempDir->Create(nsIFile::DIRECTORY_TYPE, 0700);
- if (NS_FAILED(rv)) {
- NS_WARNING("Failed to create sandbox temp dir.");
- return nullptr;
- }
-
- return sandboxTempDir.forget();
-}
-
-static nsresult
-DeleteDirIfExists(nsIFile* dir)
-{
- if (dir) {
- // Don't return an error if the directory doesn't exist.
- // Windows Remove() returns NS_ERROR_FILE_NOT_FOUND while
- // OS X returns NS_ERROR_FILE_TARGET_DOES_NOT_EXIST.
- nsresult rv = dir->Remove(/* aRecursive */ true);
- if (NS_FAILED(rv) && rv != NS_ERROR_FILE_NOT_FOUND &&
- rv != NS_ERROR_FILE_TARGET_DOES_NOT_EXIST) {
- return rv;
- }
- }
- return NS_OK;
-}
-
-#endif // (defined(XP_WIN) || defined(XP_MACOSX)) &&
- // defined(MOZ_CONTENT_SANDBOX)
-
void
nsXREDirProvider::LoadExtensionBundleDirectories()
{
@@ -952,38 +757,6 @@ nsXREDirProvider::LoadExtensionBundleDirectories()
}
}
-#ifdef MOZ_B2G
-void
-nsXREDirProvider::LoadAppBundleDirs()
-{
- nsCOMPtr<nsIFile> dir;
- bool persistent = false;
- nsresult rv = GetFile(XRE_APP_DISTRIBUTION_DIR, &persistent, getter_AddRefs(dir));
- if (NS_FAILED(rv))
- return;
-
- dir->AppendNative(NS_LITERAL_CSTRING("bundles"));
-
- nsCOMPtr<nsISimpleEnumerator> e;
- rv = dir->GetDirectoryEntries(getter_AddRefs(e));
- if (NS_FAILED(rv))
- return;
-
- nsCOMPtr<nsIDirectoryEnumerator> files = do_QueryInterface(e);
- if (!files)
- return;
-
- nsCOMPtr<nsIFile> subdir;
- while (NS_SUCCEEDED(files->GetNextFile(getter_AddRefs(subdir))) && subdir) {
- mAppBundleDirectories.AppendObject(subdir);
-
- nsCOMPtr<nsIFile> manifest =
- CloneAndAppend(subdir, "chrome.manifest");
- XRE_AddManifestLocation(NS_APP_LOCATION, manifest);
- }
-}
-#endif
-
static const char *const kAppendPrefDir[] = { "defaults", "preferences", nullptr };
#ifdef DEBUG_bsmedberg
@@ -1203,14 +976,6 @@ nsXREDirProvider::DoStartup()
}
obsSvc->NotifyObservers(nullptr, "profile-initial-state", nullptr);
-
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
- // The parent is responsible for creating the sandbox temp dir
- if (XRE_IsParentProcess()) {
- mContentProcessSandboxTempDir = CreateContentProcessSandboxTempDir();
- mContentTempDir = mContentProcessSandboxTempDir;
- }
-#endif
}
return NS_OK;
}
@@ -1221,12 +986,6 @@ nsXREDirProvider::DoShutdown()
PROFILER_LABEL_FUNC(js::ProfileEntry::Category::OTHER);
if (mProfileNotified) {
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
- if (XRE_IsParentProcess()) {
- Unused << DeleteDirIfExists(mContentProcessSandboxTempDir);
- }
-#endif
-
nsCOMPtr<nsIObserverService> obsSvc =
mozilla::services::GetObserverService();
NS_ASSERTION(obsSvc, "No observer service?");
@@ -1363,14 +1122,6 @@ nsresult
nsXREDirProvider::GetUpdateRootDir(nsIFile* *aResult)
{
nsCOMPtr<nsIFile> updRoot;
-#if defined(MOZ_WIDGET_GONK)
-
- nsresult rv = NS_NewNativeLocalFile(nsDependentCString("/data/local"),
- true,
- getter_AddRefs(updRoot));
- NS_ENSURE_SUCCESS(rv, rv);
-
-#else
nsCOMPtr<nsIFile> appFile;
bool per = false;
nsresult rv = GetFile(XRE_EXECUTABLE_FILE, &per, getter_AddRefs(appFile));
@@ -1502,7 +1253,6 @@ nsXREDirProvider::GetUpdateRootDir(nsIFile* *aResult)
NS_ENSURE_SUCCESS(rv, rv);
#endif // XP_WIN
-#endif
updRoot.forget(aResult);
return NS_OK;
}
@@ -1606,9 +1356,6 @@ nsXREDirProvider::GetUserDataDirectoryHome(nsIFile** aFile, bool aLocal)
NS_ENSURE_SUCCESS(rv, rv);
rv = NS_NewLocalFile(path, true, getter_AddRefs(localDir));
-#elif defined(MOZ_WIDGET_GONK)
- rv = NS_NewNativeLocalFile(NS_LITERAL_CSTRING("/data/b2g"), true,
- getter_AddRefs(localDir));
#elif defined(XP_UNIX)
const char* homeDir = getenv("HOME");
if (!homeDir || !*homeDir)
diff --git a/toolkit/xre/nsXREDirProvider.h b/toolkit/xre/nsXREDirProvider.h
index 7ec64da78..655f664e6 100644
--- a/toolkit/xre/nsXREDirProvider.h
+++ b/toolkit/xre/nsXREDirProvider.h
@@ -121,19 +121,9 @@ protected:
// delimiters.
static inline nsresult AppendProfileString(nsIFile* aFile, const char* aPath);
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
- // Load the temp directory for sandboxed content processes
- nsresult LoadContentProcessTempDir();
-#endif
-
// Calculate and register extension and theme bundle directories.
void LoadExtensionBundleDirectories();
-#ifdef MOZ_B2G
- // Calculate and register app-bundled extension directories.
- void LoadAppBundleDirs();
-#endif
-
void Append(nsIFile* aDirectory);
nsCOMPtr<nsIDirectoryServiceProvider> mAppProvider;
@@ -146,10 +136,6 @@ protected:
nsCOMPtr<nsIFile> mProfileDir;
nsCOMPtr<nsIFile> mProfileLocalDir;
bool mProfileNotified;
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
- nsCOMPtr<nsIFile> mContentTempDir;
- nsCOMPtr<nsIFile> mContentProcessSandboxTempDir;
-#endif
nsCOMArray<nsIFile> mAppBundleDirectories;
nsCOMArray<nsIFile> mExtensionDirectories;
nsCOMArray<nsIFile> mThemeDirectories;
diff --git a/tools/profiler/core/GeckoSampler.cpp b/tools/profiler/core/GeckoSampler.cpp
index f4249a7a5..4283542f6 100644
--- a/tools/profiler/core/GeckoSampler.cpp
+++ b/tools/profiler/core/GeckoSampler.cpp
@@ -44,7 +44,7 @@
#include "mozilla/ProfileGatherer.h"
#endif
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
#include "FennecJNIWrappers.h"
#endif
@@ -213,7 +213,7 @@ GeckoSampler::GeckoSampler(double aInterval, int aEntrySize,
}
#endif
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
mProfileJava = mozilla::jni::IsFennec() &&
hasFeature(aFeatures, aFeatureCount, "java");
#else
@@ -462,7 +462,7 @@ void SubProcessCallback(const char* aProfile, void* aClosure)
}
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
static
void BuildJavaThreadJSObject(SpliceableJSONWriter& aWriter)
{
@@ -567,7 +567,7 @@ void GeckoSampler::StreamJSON(SpliceableJSONWriter& aWriter, double aSinceTime)
}
}
- #if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+ #if defined(SPS_OS_android)
if (ProfileJava()) {
java::GeckoJavaSampler::Pause();
diff --git a/tools/profiler/core/platform.cpp b/tools/profiler/core/platform.cpp
index 0d3cb1648..a8a09d66f 100644
--- a/tools/profiler/core/platform.cpp
+++ b/tools/profiler/core/platform.cpp
@@ -36,11 +36,11 @@
#include "GeckoTaskTracer.h"
#endif
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
#include "FennecJNIWrappers.h"
#endif
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
#include "FennecJNINatives.h"
#endif
@@ -52,7 +52,7 @@
#endif
#endif
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
class GeckoJavaSampler : public java::GeckoJavaSampler::Natives<GeckoJavaSampler>
{
private:
@@ -502,7 +502,7 @@ void mozilla_sampler_init(void* stackTop)
set_stderr_callback(mozilla_sampler_log);
#endif
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
if (mozilla::jni::IsFennec()) {
GeckoJavaSampler::Init();
}
@@ -524,7 +524,7 @@ void mozilla_sampler_init(void* stackTop)
|| defined(SPS_PLAT_amd64_linux) || defined(SPS_PLAT_x86_linux)
, "stackwalk"
#endif
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
, "java"
#endif
};
@@ -819,7 +819,7 @@ void mozilla_sampler_start(int aProfileEntries, double aInterval,
}
}
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
if (t->ProfileJava()) {
int javaInterval = aInterval;
// Java sampling doesn't accuratly keep up with 1ms sampling
@@ -1021,15 +1021,6 @@ bool mozilla_sampler_register_thread(const char* aName, void* aGuessStackTop)
return false;
}
-#if defined(MOZ_WIDGET_GONK) && !defined(MOZ_PROFILING)
- // The only way to profile secondary threads on b2g
- // is to build with profiling OR have the profiler
- // running on startup.
- if (!profiler_is_active()) {
- return false;
- }
-#endif
-
MOZ_ASSERT(tlsPseudoStack.get() == nullptr);
PseudoStack* stack = PseudoStack::create();
tlsPseudoStack.set(stack);
diff --git a/tools/profiler/core/platform.h b/tools/profiler/core/platform.h
index 2e736d97c..17c8dd25c 100644
--- a/tools/profiler/core/platform.h
+++ b/tools/profiler/core/platform.h
@@ -393,10 +393,7 @@ class Sampler {
static mozilla::UniquePtr<Mutex> sRegisteredThreadsMutex;
static bool CanNotifyObservers() {
-#ifdef MOZ_WIDGET_GONK
- // We use profile.sh on b2g to manually select threads and options per process.
- return false;
-#elif defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
// Android ANR reporter uses the profiler off the main thread
return NS_IsMainThread();
#else
diff --git a/tools/profiler/core/shared-libraries-linux.cc b/tools/profiler/core/shared-libraries-linux.cc
index 24437fb4e..553039fb7 100644
--- a/tools/profiler/core/shared-libraries-linux.cc
+++ b/tools/profiler/core/shared-libraries-linux.cc
@@ -37,7 +37,6 @@ static std::string getId(const char *bin_name)
return "";
}
-#if !defined(MOZ_WIDGET_GONK)
// TODO fix me with proper include
#include "nsDebug.h"
#ifdef ANDROID
@@ -86,13 +85,10 @@ dl_iterate_callback(struct dl_phdr_info *dl_info, size_t size, void *data)
return 0;
}
-#endif // !MOZ_WIDGET_GONK
-
SharedLibraryInfo SharedLibraryInfo::GetInfoForSelf()
{
SharedLibraryInfo info;
-#if !defined(MOZ_WIDGET_GONK)
#ifdef ANDROID
if (!dl_iterate_phdr) {
// On ARM Android, dl_iterate_phdr is provided by the custom linker.
@@ -104,9 +100,8 @@ SharedLibraryInfo SharedLibraryInfo::GetInfoForSelf()
#endif // ANDROID
dl_iterate_phdr(dl_iterate_callback, &info);
-#endif // !MOZ_WIDGET_GONK
-#if defined(ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(ANDROID)
pid_t pid = getpid();
char path[PATH_MAX];
snprintf(path, PATH_MAX, "/proc/%d/maps", pid);
@@ -132,19 +127,10 @@ SharedLibraryInfo SharedLibraryInfo::GetInfoForSelf()
LOG("Get maps line failed");
continue;
}
-#if defined(ANDROID) && !defined(MOZ_WIDGET_GONK)
// Use proc/pid/maps to get the dalvik-jit section since it has
// no associated phdrs
if (strcmp(name, "/dev/ashmem/dalvik-jit-code-cache") != 0)
continue;
-#else
- if (strcmp(perm, "r-xp") != 0) {
- // Ignore entries that are writable and/or shared.
- // At least one graphics driver uses short-lived "rwxs" mappings
- // (see bug 926734 comment 5), so just checking for 'x' isn't enough.
- continue;
- }
-#endif
SharedLibrary shlib(start, end, offset, getId(name), name);
info.AddSharedLibrary(shlib);
if (count > 10000) {
@@ -153,7 +139,7 @@ SharedLibraryInfo SharedLibraryInfo::GetInfoForSelf()
}
count++;
}
-#endif // ANDROID || MOZ_WIDGET_GONK
+#endif // ANDROID
return info;
}
diff --git a/tools/profiler/gecko/SaveProfileTask.cpp b/tools/profiler/gecko/SaveProfileTask.cpp
index 497385355..dbbbe4836 100644
--- a/tools/profiler/gecko/SaveProfileTask.cpp
+++ b/tools/profiler/gecko/SaveProfileTask.cpp
@@ -9,7 +9,7 @@
nsresult
SaveProfileTask::Run() {
// Get file path
-#if defined(SPS_PLAT_arm_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_PLAT_arm_android)
nsCString tmpPath;
tmpPath.AppendPrintf("/sdcard/profile_%i_%i.txt", XRE_GetProcessType(), getpid());
#else
diff --git a/tools/profiler/lul/AutoObjectMapper.cpp b/tools/profiler/lul/AutoObjectMapper.cpp
index a5dc902fd..1bc5ce62a 100644
--- a/tools/profiler/lul/AutoObjectMapper.cpp
+++ b/tools/profiler/lul/AutoObjectMapper.cpp
@@ -16,7 +16,7 @@
#include "PlatformMacros.h"
#include "AutoObjectMapper.h"
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
# include <dlfcn.h>
# include "mozilla/Types.h"
// FIXME move these out of mozglue/linker/ElfLoader.h into their
@@ -108,7 +108,7 @@ bool AutoObjectMapperPOSIX::Map(/*OUT*/void** start, /*OUT*/size_t* length,
}
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
// A helper function for AutoObjectMapperFaultyLib::Map. Finds out
// where the installation's lib directory is, since we'll have to look
// in there to get hold of libmozglue.so. Returned C string is heap
@@ -204,4 +204,4 @@ bool AutoObjectMapperFaultyLib::Map(/*OUT*/void** start, /*OUT*/size_t* length,
}
}
-#endif // defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#endif // defined(SPS_OS_android)
diff --git a/tools/profiler/lul/AutoObjectMapper.h b/tools/profiler/lul/AutoObjectMapper.h
index 1f813d6f2..3f60dc44d 100644
--- a/tools/profiler/lul/AutoObjectMapper.h
+++ b/tools/profiler/lul/AutoObjectMapper.h
@@ -62,7 +62,7 @@ private:
};
-#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#if defined(SPS_OS_android)
// This is a variant of AutoObjectMapperPOSIX suitable for use in
// conjunction with faulty.lib on Android. How it behaves depends on
// the name of the file to be mapped. There are three possible cases:
@@ -110,6 +110,6 @@ private:
void operator delete[](void*);
};
-#endif // defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+#endif // defined(SPS_OS_android)
#endif // AutoObjectMapper_h
diff --git a/tools/profiler/lul/platform-linux-lul.cpp b/tools/profiler/lul/platform-linux-lul.cpp
index 9541534a1..da764f3cf 100644
--- a/tools/profiler/lul/platform-linux-lul.cpp
+++ b/tools/profiler/lul/platform-linux-lul.cpp
@@ -32,7 +32,7 @@ read_procmaps(lul::LUL* aLUL)
for (size_t i = 0; i < info.GetSize(); i++) {
const SharedLibrary& lib = info.GetEntry(i);
-# if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
+# if defined(SPS_OS_android)
// We're using faulty.lib. Use a special-case object mapper.
AutoObjectMapperFaultyLib mapper(aLUL->mLog);
# else
diff --git a/tools/profiler/moz.build b/tools/profiler/moz.build
index 08103f126..57a74cefc 100644
--- a/tools/profiler/moz.build
+++ b/tools/profiler/moz.build
@@ -108,9 +108,6 @@ if CONFIG['MOZ_ENABLE_PROFILER_SPS']:
if CONFIG['ENABLE_TESTS']:
DIRS += ['tests/gtest']
- if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and (CONFIG['ANDROID_VERSION'] <= '17' or CONFIG['ANDROID_VERSION'] >= '21'):
- DEFINES['ELFSIZE'] = 32
-
FINAL_LIBRARY = 'xul'
IPDL_SOURCES += [
diff --git a/tools/profiler/public/GeckoProfilerImpl.h b/tools/profiler/public/GeckoProfilerImpl.h
index a32096b94..7011e5cdb 100644
--- a/tools/profiler/public/GeckoProfilerImpl.h
+++ b/tools/profiler/public/GeckoProfilerImpl.h
@@ -346,13 +346,6 @@ static inline void profiler_tracing(const char* aCategory, const char* aInfo,
#define PROFILER_MAIN_THREAD_LABEL_PRINTF(name_space, info, category, ...) MOZ_ASSERT(NS_IsMainThread(), "This can only be called on the main thread"); mozilla::SamplerStackFramePrintfRAII SAMPLER_APPEND_LINE_NUMBER(sampler_raii)(name_space "::" info, category, __LINE__, __VA_ARGS__)
-/* FIXME/bug 789667: memory constraints wouldn't much of a problem for
- * this small a sample buffer size, except that serializing the
- * profile data is extremely, unnecessarily memory intensive. */
-#ifdef MOZ_WIDGET_GONK
-# define PLATFORM_LIKELY_MEMORY_CONSTRAINED
-#endif
-
#if !defined(PLATFORM_LIKELY_MEMORY_CONSTRAINED) && !defined(ARCH_ARMV6)
# define PROFILE_DEFAULT_ENTRY 1000000
#else
diff --git a/tools/rewriting/ThirdPartyPaths.txt b/tools/rewriting/ThirdPartyPaths.txt
index fb644e350..a5822c981 100644
--- a/tools/rewriting/ThirdPartyPaths.txt
+++ b/tools/rewriting/ThirdPartyPaths.txt
@@ -42,7 +42,6 @@ media/openmax_dl/
media/pocketsphinx/
media/sphinxbase/
media/webrtc/trunk/
-memory/jemalloc/src/
mfbt/decimal/
mfbt/double-conversion/
mfbt/lz4
diff --git a/uriloader/base/nsURILoader.cpp b/uriloader/base/nsURILoader.cpp
index 69475d68f..5a6b38028 100644
--- a/uriloader/base/nsURILoader.cpp
+++ b/uriloader/base/nsURILoader.cpp
@@ -385,16 +385,6 @@ nsresult nsDocumentOpenInfo::DispatchContent(nsIRequest *request, nsISupports *
bool allowContentDispositionToForceExternalHandling = true;
-#ifdef MOZ_B2G
-
- // On B2G, OMA content files should never be handled by an external handler
- // (even if the server specifies Content-Disposition: attachment) because the
- // data should never be stored on an unencrypted form.
- allowContentDispositionToForceExternalHandling =
- !mContentType.LowerCaseEqualsASCII("application/vnd.oma.drm.message");
-
-#endif
-
if (NS_SUCCEEDED(rv) && (disposition == nsIChannel::DISPOSITION_ATTACHMENT) &&
allowContentDispositionToForceExternalHandling) {
forceExternalHandling = true;
@@ -834,7 +824,7 @@ NS_IMETHODIMP nsURILoader::OpenURI(nsIChannel *channel,
// the preferred protocol handler.
// But for now, I'm going to let necko do the work for us....
- rv = channel->AsyncOpen(loader, nullptr);
+ rv = channel->AsyncOpen2(loader);
// no content from this load - that's OK.
if (rv == NS_ERROR_NO_CONTENT) {
diff --git a/uriloader/exthandler/gonk/nsOSHelperAppService.cpp b/uriloader/exthandler/gonk/nsOSHelperAppService.cpp
deleted file mode 100644
index d1342ec18..000000000
--- a/uriloader/exthandler/gonk/nsOSHelperAppService.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nsOSHelperAppService.h"
-#include "nsMIMEInfoImpl.h"
-
-class nsGonkMIMEInfo : public nsMIMEInfoImpl {
-public:
- nsGonkMIMEInfo(const nsACString& aMIMEType) : nsMIMEInfoImpl(aMIMEType) { }
-
-protected:
- virtual nsresult LoadUriInternal(nsIURI *aURI) {
- return NS_ERROR_NOT_IMPLEMENTED;
- }
-};
-
-nsOSHelperAppService::nsOSHelperAppService() : nsExternalHelperAppService()
-{
-}
-
-nsOSHelperAppService::~nsOSHelperAppService()
-{
-}
-
-already_AddRefed<nsIMIMEInfo>
-nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType,
- const nsACString& aFileExt,
- bool* aFound)
-{
- *aFound = false;
- // Even if we return false for aFound, we need to return a working
- // nsIMIMEInfo implementation that will be used by the caller.
- RefPtr<nsGonkMIMEInfo> mimeInfo = new nsGonkMIMEInfo(aMIMEType);
- return mimeInfo.forget();
-}
-
-nsresult
-nsOSHelperAppService::OSProtocolHandlerExists(const char* aScheme,
- bool* aExists)
-{
- *aExists = false;
- return NS_OK;
-}
diff --git a/uriloader/exthandler/gonk/nsOSHelperAppService.h b/uriloader/exthandler/gonk/nsOSHelperAppService.h
deleted file mode 100644
index 99a280bfc..000000000
--- a/uriloader/exthandler/gonk/nsOSHelperAppService.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/* -*- Mode: c++; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef nsOSHelperAppService_h
-#define nsOSHelperAppService_h
-
-#include "nsCExternalHandlerService.h"
-#include "nsExternalHelperAppService.h"
-
-class nsOSHelperAppService : public nsExternalHelperAppService
-{
-public:
- nsOSHelperAppService();
- virtual ~nsOSHelperAppService();
-
- virtual already_AddRefed<nsIMIMEInfo>
- GetMIMEInfoFromOS(const nsACString& aMIMEType,
- const nsACString& aFileExt,
- bool* aFound);
-
- virtual MOZ_MUST_USE nsresult
- OSProtocolHandlerExists(const char* aScheme,
- bool* aExists);
-};
-
-#endif /* nsOSHelperAppService_h */
diff --git a/uriloader/exthandler/moz.build b/uriloader/exthandler/moz.build
index 6a3ca08af..714b275f1 100644
--- a/uriloader/exthandler/moz.build
+++ b/uriloader/exthandler/moz.build
@@ -24,7 +24,7 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
LOCAL_INCLUDES += ['win']
elif CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa':
osdir = 'mac'
-elif CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gonk', 'uikit'):
+elif CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'uikit'):
osdir = CONFIG['MOZ_WIDGET_TOOLKIT']
else:
osdir = 'unix'
diff --git a/uriloader/exthandler/nsExternalHelperAppService.cpp b/uriloader/exthandler/nsExternalHelperAppService.cpp
index 5afaae319..455ac457a 100644
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -552,16 +552,6 @@ static const nsExtraMimeTypeEntry extraMimeEntries[] =
{ APPLICATION_OGG, "ogg", "Ogg Video"},
{ AUDIO_OGG, "oga", "Ogg Audio" },
{ AUDIO_OGG, "opus", "Opus Audio" },
-#ifdef MOZ_WIDGET_GONK
- { AUDIO_AMR, "amr", "Adaptive Multi-Rate Audio" },
- { AUDIO_FLAC, "flac", "FLAC Audio" },
- { VIDEO_AVI, "avi", "Audio Video Interleave" },
- { VIDEO_AVI, "divx", "Audio Video Interleave" },
- { VIDEO_MPEG_TS, "ts", "MPEG Transport Stream" },
- { VIDEO_MPEG_TS, "m2ts", "MPEG-2 Transport Stream" },
- { VIDEO_MATROSKA, "mkv", "MATROSKA VIDEO" },
- { AUDIO_MATROSKA, "mka", "MATROSKA AUDIO" },
-#endif
{ VIDEO_WEBM, "webm", "Web Media Video" },
{ AUDIO_WEBM, "webm", "Web Media Audio" },
{ AUDIO_MP3, "mp3", "MPEG Audio" },
@@ -571,13 +561,6 @@ static const nsExtraMimeTypeEntry extraMimeEntries[] =
{ AUDIO_WAV, "wav", "Waveform Audio" },
{ VIDEO_3GPP, "3gpp,3gp", "3GPP Video" },
{ VIDEO_3GPP2,"3g2", "3GPP2 Video" },
-#ifdef MOZ_WIDGET_GONK
- // The AUDIO_3GPP has to come after the VIDEO_3GPP entry because the Gallery
- // app on Firefox OS depends on the "3gp" extension mapping to the
- // "video/3gpp" MIME type.
- { AUDIO_3GPP, "3gpp,3gp", "3GPP Audio" },
- { AUDIO_3GPP2, "3g2", "3GPP2 Audio" },
-#endif
{ AUDIO_MIDI, "mid", "Standard MIDI Audio" }
};
diff --git a/uriloader/exthandler/win/nsMIMEInfoWin.cpp b/uriloader/exthandler/win/nsMIMEInfoWin.cpp
index 2c7171c87..6ead8f4c3 100644
--- a/uriloader/exthandler/win/nsMIMEInfoWin.cpp
+++ b/uriloader/exthandler/win/nsMIMEInfoWin.cpp
@@ -243,8 +243,7 @@ nsMIMEInfoWin::LoadUriInternal(nsIURI * aURL)
SHELLEXECUTEINFOW sinfo;
memset(&sinfo, 0, sizeof(sinfo));
sinfo.cbSize = sizeof(sinfo);
- sinfo.fMask = SEE_MASK_FLAG_DDEWAIT |
- SEE_MASK_FLAG_NO_UI;
+ sinfo.fMask = SEE_MASK_FLAG_DDEWAIT;
sinfo.hwnd = nullptr;
sinfo.lpVerb = (LPWSTR)&cmdVerb;
sinfo.nShow = SW_SHOWNORMAL;
diff --git a/widget/BasicEvents.h b/widget/BasicEvents.h
index da8d819ef..a6228f179 100644
--- a/widget/BasicEvents.h
+++ b/widget/BasicEvents.h
@@ -585,6 +585,7 @@ public:
case eMouseEventClass:
mFlags.mComposed = mMessage == eMouseClick ||
mMessage == eMouseDoubleClick ||
+ mMessage == eMouseAuxClick ||
mMessage == eMouseDown || mMessage == eMouseUp ||
mMessage == eMouseEnter || mMessage == eMouseLeave ||
mMessage == eMouseOver || mMessage == eMouseOut ||
diff --git a/widget/EventMessageList.h b/widget/EventMessageList.h
index 7fe642637..372ca90fb 100644
--- a/widget/EventMessageList.h
+++ b/widget/EventMessageList.h
@@ -84,6 +84,7 @@ NS_EVENT_MESSAGE(eMouseEnterIntoWidget)
NS_EVENT_MESSAGE(eMouseExitFromWidget)
NS_EVENT_MESSAGE(eMouseDoubleClick)
NS_EVENT_MESSAGE(eMouseClick)
+NS_EVENT_MESSAGE(eMouseAuxClick)
// eMouseActivate is fired when the widget is activated by a click.
NS_EVENT_MESSAGE(eMouseActivate)
NS_EVENT_MESSAGE(eMouseOver)
@@ -340,9 +341,11 @@ NS_EVENT_MESSAGE(eScrolledAreaChanged)
NS_EVENT_MESSAGE(eTransitionStart)
NS_EVENT_MESSAGE(eTransitionRun)
NS_EVENT_MESSAGE(eTransitionEnd)
+NS_EVENT_MESSAGE(eTransitionCancel)
NS_EVENT_MESSAGE(eAnimationStart)
NS_EVENT_MESSAGE(eAnimationEnd)
NS_EVENT_MESSAGE(eAnimationIteration)
+NS_EVENT_MESSAGE(eAnimationCancel)
// Webkit-prefixed versions of Transition & Animation events, for web compat:
NS_EVENT_MESSAGE(eWebkitTransitionEnd)
@@ -376,7 +379,7 @@ NS_EVENT_MESSAGE(eDeviceMotion)
NS_EVENT_MESSAGE(eDeviceProximity)
NS_EVENT_MESSAGE(eUserProximity)
NS_EVENT_MESSAGE(eDeviceLight)
-#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GONK)
+#if defined(MOZ_WIDGET_ANDROID)
NS_EVENT_MESSAGE(eOrientationChange)
#endif
diff --git a/widget/NativeKeyToDOMKeyName.h b/widget/NativeKeyToDOMKeyName.h
index e060a313c..a818108db 100644
--- a/widget/NativeKeyToDOMKeyName.h
+++ b/widget/NativeKeyToDOMKeyName.h
@@ -25,12 +25,7 @@
#define KEY_MAP_COCOA(aCPPKeyName, aNativeKey)
// GTK
#define KEY_MAP_GTK(aCPPKeyName, aNativeKey)
-// Android and B2G
#define KEY_MAP_ANDROID(aCPPKeyName, aNativeKey)
-// Only for Android
-#define KEY_MAP_ANDROID_EXCEPT_B2G(aCPPKeyName, aNativeKey)
-// Only for B2G
-#define KEY_MAP_B2G(aCPPKeyName, aNativeKey)
#if defined(XP_WIN)
#if defined(NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX)
@@ -80,15 +75,6 @@
#undef KEY_MAP_ANDROID
#define KEY_MAP_ANDROID(aCPPKeyName, aNativeKey) \
NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, KEY_NAME_INDEX_##aCPPKeyName)
-#ifndef MOZ_B2G
-#undef KEY_MAP_ANDROID_EXCEPT_B2G
-#define KEY_MAP_ANDROID_EXCEPT_B2G(aCPPKeyName, aNativeKey) \
- NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, KEY_NAME_INDEX_##aCPPKeyName)
-#else // #ifndef MOZ_B2G
-#undef KEY_MAP_B2G
-#define KEY_MAP_B2G(aCPPKeyName, aNativeKey) \
- NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, KEY_NAME_INDEX_##aCPPKeyName)
-#endif // #ifndef MOZ_B2G #else
#endif
/******************************************************************************
@@ -1039,11 +1025,10 @@ KEY_MAP_ANDROID (Call, AKEYCODE_CALL)
KEY_MAP_ANDROID (Camera, AKEYCODE_CAMERA)
// CameraFocus
-KEY_MAP_ANDROID_EXCEPT_B2G(CameraFocus, AKEYCODE_FOCUS)
+KEY_MAP_ANDROID (CameraFocus, AKEYCODE_FOCUS)
// GoHome
-KEY_MAP_ANDROID_EXCEPT_B2G(GoHome, AKEYCODE_HOME)
-KEY_MAP_B2G (HomeScreen, AKEYCODE_HOME)
+KEY_MAP_ANDROID (GoHome, AKEYCODE_HOME)
/******************************************************************************
* TV Keys
@@ -1140,5 +1125,3 @@ KEY_MAP_ANDROID (SoftRight, AKEYCODE_SOFT_RIGHT)
#undef KEY_MAP_COCOA
#undef KEY_MAP_GTK
#undef KEY_MAP_ANDROID
-#undef KEY_MAP_ANDROID_EXCEPT_B2G
-#undef KEY_MAP_B2G
diff --git a/widget/PuppetWidget.cpp b/widget/PuppetWidget.cpp
index 1fa13ee6f..657f70551 100644
--- a/widget/PuppetWidget.cpp
+++ b/widget/PuppetWidget.cpp
@@ -541,10 +541,6 @@ PuppetWidget::ExecuteNativeKeyBinding(NativeKeyBindingsType aType,
DoCommandCallback aCallback,
void* aCallbackData)
{
- // B2G doesn't have native key bindings.
-#ifdef MOZ_WIDGET_GONK
- return false;
-#else // #ifdef MOZ_WIDGET_GONK
AutoCacheNativeKeyCommands autoCache(this);
if (!aEvent.mWidget && !mNativeKeyCommandsValid) {
MOZ_ASSERT(!aEvent.mFlags.mIsSynthesizedForTests);
@@ -581,7 +577,6 @@ PuppetWidget::ExecuteNativeKeyBinding(NativeKeyBindingsType aType,
aCallback(static_cast<mozilla::Command>((*commands)[i]), aCallbackData);
}
return true;
-#endif
}
LayerManager*
diff --git a/widget/WidgetEventImpl.cpp b/widget/WidgetEventImpl.cpp
index 52e2b9b40..7dd292cb0 100644
--- a/widget/WidgetEventImpl.cpp
+++ b/widget/WidgetEventImpl.cpp
@@ -236,6 +236,7 @@ WidgetEvent::HasMouseEventMessage() const
case eMouseUp:
case eMouseClick:
case eMouseDoubleClick:
+ case eMouseAuxClick:
case eMouseEnterIntoWidget:
case eMouseExitFromWidget:
case eMouseActivate:
diff --git a/widget/gonk/GeckoTouchDispatcher.cpp b/widget/gonk/GeckoTouchDispatcher.cpp
deleted file mode 100644
index 0b18c91a1..000000000
--- a/widget/gonk/GeckoTouchDispatcher.cpp
+++ /dev/null
@@ -1,358 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 sts=2 et sw=2 tw=80: */
-/* Copyright 2014 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "FrameMetrics.h"
-#include "GeckoProfiler.h"
-#include "GeckoTouchDispatcher.h"
-#include "InputData.h"
-#include "ProfilerMarkers.h"
-#include "base/basictypes.h"
-#include "gfxPrefs.h"
-#include "libui/Input.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/Mutex.h"
-#include "mozilla/TimeStamp.h"
-#include "mozilla/TouchEvents.h"
-#include "mozilla/dom/Touch.h"
-#include "mozilla/layers/APZThreadUtils.h"
-#include "mozilla/layers/CompositorBridgeParent.h"
-#include "nsAppShell.h"
-#include "nsDebug.h"
-#include "nsThreadUtils.h"
-#include "nsWindow.h"
-#include <sys/types.h>
-#include <unistd.h>
-#include <utils/Timers.h>
-
-#undef LOG
-#define LOG(args...) \
- __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
-
-// uncomment to print log resample data
-// #define LOG_RESAMPLE_DATA 1
-
-namespace mozilla {
-
-// Amount of time in MS before an input is considered expired.
-static const uint64_t kInputExpirationThresholdMs = 1000;
-
-static StaticRefPtr<GeckoTouchDispatcher> sTouchDispatcher;
-
-/* static */ GeckoTouchDispatcher*
-GeckoTouchDispatcher::GetInstance()
-{
- if (!sTouchDispatcher) {
- sTouchDispatcher = new GeckoTouchDispatcher();
- ClearOnShutdown(&sTouchDispatcher);
- }
- return sTouchDispatcher;
-}
-
-GeckoTouchDispatcher::GeckoTouchDispatcher()
- : mTouchQueueLock("GeckoTouchDispatcher::mTouchQueueLock")
- , mHavePendingTouchMoves(false)
- , mInflightNonMoveEvents(0)
- , mTouchEventsFiltered(false)
-{
- // Since GeckoTouchDispatcher is initialized when input is initialized
- // and reads gfxPrefs, it is the first thing to touch gfxPrefs.
- // The first thing to touch gfxPrefs MUST occur on the main thread and init
- // the singleton
- MOZ_ASSERT(sTouchDispatcher == nullptr);
- MOZ_ASSERT(NS_IsMainThread());
- gfxPrefs::GetSingleton();
-
- mEnabledUniformityInfo = gfxPrefs::UniformityInfo();
- mVsyncAdjust = TimeDuration::FromMilliseconds(gfxPrefs::TouchVsyncSampleAdjust());
- mMaxPredict = TimeDuration::FromMilliseconds(gfxPrefs::TouchResampleMaxPredict());
- mMinDelta = TimeDuration::FromMilliseconds(gfxPrefs::TouchResampleMinDelta());
- mOldTouchThreshold = TimeDuration::FromMilliseconds(gfxPrefs::TouchResampleOldTouchThreshold());
- mDelayedVsyncThreshold = TimeDuration::FromMilliseconds(gfxPrefs::TouchResampleVsyncDelayThreshold());
-}
-
-void
-GeckoTouchDispatcher::SetCompositorVsyncScheduler(mozilla::layers::CompositorVsyncScheduler *aObserver)
-{
- MOZ_ASSERT(NS_IsMainThread());
- // We assume on b2g that there is only 1 CompositorBridgeParent
- MOZ_ASSERT(mCompositorVsyncScheduler == nullptr);
- mCompositorVsyncScheduler = aObserver;
-}
-
-void
-GeckoTouchDispatcher::NotifyVsync(TimeStamp aVsyncTimestamp)
-{
- layers::APZThreadUtils::AssertOnControllerThread();
- DispatchTouchMoveEvents(aVsyncTimestamp);
-}
-
-// Touch data timestamps are in milliseconds, aEventTime is in nanoseconds
-void
-GeckoTouchDispatcher::NotifyTouch(MultiTouchInput& aTouch, TimeStamp aEventTime)
-{
- if (mCompositorVsyncScheduler) {
- mCompositorVsyncScheduler->SetNeedsComposite();
- }
-
- if (aTouch.mType == MultiTouchInput::MULTITOUCH_MOVE) {
- MutexAutoLock lock(mTouchQueueLock);
- if (mInflightNonMoveEvents > 0) {
- // If we have any pending non-move events, we shouldn't resample the
- // move events because we might end up dispatching events out of order.
- // Instead, fall back to a non-resampling in-order dispatch until we're
- // done processing the non-move events.
- layers::APZThreadUtils::RunOnControllerThread(NewRunnableMethod<MultiTouchInput>(
- this, &GeckoTouchDispatcher::DispatchTouchEvent, aTouch));
- return;
- }
-
- mTouchMoveEvents.push_back(aTouch);
- mHavePendingTouchMoves = true;
- } else {
- { // scope lock
- MutexAutoLock lock(mTouchQueueLock);
- mInflightNonMoveEvents++;
- }
- layers::APZThreadUtils::RunOnControllerThread(NewRunnableMethod<MultiTouchInput>(
- this, &GeckoTouchDispatcher::DispatchTouchNonMoveEvent, aTouch));
- }
-}
-
-void
-GeckoTouchDispatcher::DispatchTouchNonMoveEvent(MultiTouchInput aInput)
-{
- layers::APZThreadUtils::AssertOnControllerThread();
-
- // Flush pending touch move events, if there are any
- // (DispatchTouchMoveEvents will check the mHavePendingTouchMoves flag and
- // bail out if there's nothing to be done).
- NotifyVsync(TimeStamp::Now());
- DispatchTouchEvent(aInput);
-
- { // scope lock
- MutexAutoLock lock(mTouchQueueLock);
- mInflightNonMoveEvents--;
- MOZ_ASSERT(mInflightNonMoveEvents >= 0);
- }
-}
-
-void
-GeckoTouchDispatcher::DispatchTouchMoveEvents(TimeStamp aVsyncTime)
-{
- MultiTouchInput touchMove;
-
- {
- MutexAutoLock lock(mTouchQueueLock);
- if (!mHavePendingTouchMoves) {
- return;
- }
- mHavePendingTouchMoves = false;
-
- int touchCount = mTouchMoveEvents.size();
- TimeDuration vsyncTouchDiff = aVsyncTime - mTouchMoveEvents.back().mTimeStamp;
- // The delay threshold is a positive pref, but we're testing to see if the
- // vsync time is delayed from the touch, so add a negative sign.
- bool isDelayedVsyncEvent = vsyncTouchDiff < -mDelayedVsyncThreshold;
- bool isOldTouch = vsyncTouchDiff > mOldTouchThreshold;
- bool resample = (touchCount > 1) && !isDelayedVsyncEvent && !isOldTouch;
-
- if (!resample) {
- touchMove = mTouchMoveEvents.back();
- mTouchMoveEvents.clear();
- if (!isDelayedVsyncEvent && !isOldTouch) {
- mTouchMoveEvents.push_back(touchMove);
- }
- } else {
- ResampleTouchMoves(touchMove, aVsyncTime);
- }
- }
-
- DispatchTouchEvent(touchMove);
-}
-
-static int
-Interpolate(int start, int end, TimeDuration aFrameDiff, TimeDuration aTouchDiff)
-{
- return start + (((end - start) * aFrameDiff.ToMicroseconds()) / aTouchDiff.ToMicroseconds());
-}
-
-static const SingleTouchData&
-GetTouchByID(const SingleTouchData& aCurrentTouch, MultiTouchInput& aOtherTouch)
-{
- int32_t index = aOtherTouch.IndexOfTouch(aCurrentTouch.mIdentifier);
- if (index < 0) {
- // We can have situations where a previous touch event had 2 fingers
- // and we lift 1 finger off. In those cases, we won't find the touch event
- // with given id, so just return the current touch, which will be resampled
- // without modification and dispatched.
- return aCurrentTouch;
- }
- return aOtherTouch.mTouches[index];
-}
-
-
-// aTouchDiff is the duration between the base and current touch times
-// aFrameDiff is the duration between the base and the time we're resampling to
-static void
-ResampleTouch(MultiTouchInput& aOutTouch,
- MultiTouchInput& aBase, MultiTouchInput& aCurrent,
- TimeDuration aFrameDiff, TimeDuration aTouchDiff)
-{
- aOutTouch = aCurrent;
-
- // Make sure we only resample the correct finger.
- for (size_t i = 0; i < aOutTouch.mTouches.Length(); i++) {
- const SingleTouchData& current = aCurrent.mTouches[i];
- const SingleTouchData& base = GetTouchByID(current, aBase);
-
- const ScreenIntPoint& baseTouchPoint = base.mScreenPoint;
- const ScreenIntPoint& currentTouchPoint = current.mScreenPoint;
-
- ScreenIntPoint newSamplePoint;
- newSamplePoint.x = Interpolate(baseTouchPoint.x, currentTouchPoint.x, aFrameDiff, aTouchDiff);
- newSamplePoint.y = Interpolate(baseTouchPoint.y, currentTouchPoint.y, aFrameDiff, aTouchDiff);
-
- aOutTouch.mTouches[i].mScreenPoint = newSamplePoint;
-
-#ifdef LOG_RESAMPLE_DATA
- const char* type = "extrapolate";
- if (aFrameDiff < aTouchDiff) {
- type = "interpolate";
- }
-
- float alpha = aFrameDiff / aTouchDiff;
- LOG("%s base (%d, %d), current (%d, %d) to (%d, %d) alpha %f, touch diff %d, frame diff %d\n",
- type,
- baseTouchPoint.x, baseTouchPoint.y,
- currentTouchPoint.x, currentTouchPoint.y,
- newSamplePoint.x, newSamplePoint.y,
- alpha, (int)aTouchDiff.ToMilliseconds(), (int)aFrameDiff.ToMilliseconds());
-#endif
- }
-}
-
-/*
- * +> Base touch (The touch before current touch)
- * |
- * | +> Current touch (Latest touch)
- * | |
- * | | +> Maximum resample time
- * | | |
- * +-----+------+--------------------> Time
- * ^ ^
- * | |
- * +------+--> Potential vsync events which the touches are resampled to
- * | |
- * | +> Extrapolation
- * |
- * +> Interpolation
- */
-
-void
-GeckoTouchDispatcher::ResampleTouchMoves(MultiTouchInput& aOutTouch, TimeStamp aVsyncTime)
-{
- MOZ_RELEASE_ASSERT(mTouchMoveEvents.size() >= 2);
- mTouchQueueLock.AssertCurrentThreadOwns();
-
- MultiTouchInput currentTouch = mTouchMoveEvents.back();
- mTouchMoveEvents.pop_back();
- MultiTouchInput baseTouch = mTouchMoveEvents.back();
- mTouchMoveEvents.clear();
- mTouchMoveEvents.push_back(currentTouch);
-
- TimeStamp sampleTime = aVsyncTime - mVsyncAdjust;
- TimeDuration touchDiff = currentTouch.mTimeStamp - baseTouch.mTimeStamp;
-
- if (touchDiff < mMinDelta) {
- aOutTouch = currentTouch;
- #ifdef LOG_RESAMPLE_DATA
- LOG("The touches are too close, skip resampling\n");
- #endif
- return;
- }
-
- if (currentTouch.mTimeStamp < sampleTime) {
- TimeDuration maxResampleTime = std::min(touchDiff / int64_t(2), mMaxPredict);
- TimeStamp maxTimestamp = currentTouch.mTimeStamp + maxResampleTime;
- if (sampleTime > maxTimestamp) {
- sampleTime = maxTimestamp;
- #ifdef LOG_RESAMPLE_DATA
- LOG("Overshot extrapolation time, adjusting sample time\n");
- #endif
- }
- }
-
- ResampleTouch(aOutTouch, baseTouch, currentTouch, sampleTime - baseTouch.mTimeStamp, touchDiff);
-
- // Both mTimeStamp and mTime are being updated to sampleTime here.
- // mTime needs to be updated using a delta since TimeStamp doesn't
- // provide a way to obtain a raw value.
- aOutTouch.mTime += (sampleTime - aOutTouch.mTimeStamp).ToMilliseconds();
- aOutTouch.mTimeStamp = sampleTime;
-}
-
-static bool
-IsExpired(const MultiTouchInput& aTouch)
-{
- // No pending events, the filter state can be updated.
- uint64_t timeNowMs = systemTime(SYSTEM_TIME_MONOTONIC) / 1000000;
- return (timeNowMs - aTouch.mTime) > kInputExpirationThresholdMs;
-}
-void
-GeckoTouchDispatcher::DispatchTouchEvent(MultiTouchInput aMultiTouch)
-{
- if ((aMultiTouch.mType == MultiTouchInput::MULTITOUCH_END ||
- aMultiTouch.mType == MultiTouchInput::MULTITOUCH_CANCEL) &&
- aMultiTouch.mTouches.Length() == 1) {
- MutexAutoLock lock(mTouchQueueLock);
- mTouchMoveEvents.clear();
- } else if (aMultiTouch.mType == MultiTouchInput::MULTITOUCH_START &&
- aMultiTouch.mTouches.Length() == 1) {
- mTouchEventsFiltered = IsExpired(aMultiTouch);
- }
-
- if (mTouchEventsFiltered) {
- return;
- }
-
- nsWindow::DispatchTouchInput(aMultiTouch);
-
- if (mEnabledUniformityInfo && profiler_is_active()) {
- const char* touchAction = "Invalid";
- switch (aMultiTouch.mType) {
- case MultiTouchInput::MULTITOUCH_START:
- touchAction = "Touch_Event_Down";
- break;
- case MultiTouchInput::MULTITOUCH_MOVE:
- touchAction = "Touch_Event_Move";
- break;
- case MultiTouchInput::MULTITOUCH_END:
- case MultiTouchInput::MULTITOUCH_CANCEL:
- touchAction = "Touch_Event_Up";
- break;
- case MultiTouchInput::MULTITOUCH_SENTINEL:
- MOZ_ASSERT_UNREACHABLE("Invalid MultTouchInput.");
- break;
- }
-
- const ScreenIntPoint& touchPoint = aMultiTouch.mTouches[0].mScreenPoint;
- TouchDataPayload* payload = new TouchDataPayload(touchPoint);
- PROFILER_MARKER_PAYLOAD(touchAction, payload);
- }
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/GeckoTouchDispatcher.h b/widget/gonk/GeckoTouchDispatcher.h
deleted file mode 100644
index 3c7acd0e3..000000000
--- a/widget/gonk/GeckoTouchDispatcher.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set ts=2 sts=2 et sw=2 tw=80: */
-/* Copyright 2014 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef GECKO_TOUCH_INPUT_DISPATCHER_h
-#define GECKO_TOUCH_INPUT_DISPATCHER_h
-
-#include "InputData.h"
-#include "Units.h"
-#include "mozilla/Mutex.h"
-#include <vector>
-#include "mozilla/RefPtr.h"
-
-class nsIWidget;
-
-namespace mozilla {
-namespace layers {
-class CompositorVsyncScheduler;
-}
-
-// Used to resample touch events whenever a vsync event occurs. It batches
-// touch moves and on every vsync, resamples the touch position to create smooth
-// scrolls. We use the Android touch resample algorithm. It uses a combination of
-// extrapolation and interpolation. The algorithm takes the vsync time and
-// subtracts mVsyncAdjust time in ms and creates a sample time. All touch events are
-// relative to this sample time. If the last touch event occurs AFTER this
-// sample time, interpolate the last two touch events. If the last touch event occurs BEFORE
-// this sample time, we extrapolate the last two touch events to the sample
-// time. The magic numbers defined as constants are taken from android
-// InputTransport.cpp.
-class GeckoTouchDispatcher final
-{
- NS_INLINE_DECL_THREADSAFE_REFCOUNTING(GeckoTouchDispatcher)
-
-public:
- static GeckoTouchDispatcher* GetInstance();
- void NotifyTouch(MultiTouchInput& aTouch, TimeStamp aEventTime);
- void DispatchTouchEvent(MultiTouchInput aMultiTouch);
- void DispatchTouchNonMoveEvent(MultiTouchInput aInput);
- void DispatchTouchMoveEvents(TimeStamp aVsyncTime);
- void NotifyVsync(TimeStamp aVsyncTimestamp);
- void SetCompositorVsyncScheduler(layers::CompositorVsyncScheduler* aObserver);
-
-protected:
- ~GeckoTouchDispatcher() {}
-
-private:
- GeckoTouchDispatcher();
- void ResampleTouchMoves(MultiTouchInput& aOutTouch, TimeStamp vsyncTime);
- void SendTouchEvent(MultiTouchInput& aData);
- void DispatchMouseEvent(MultiTouchInput& aMultiTouch,
- bool aForwardToChildren);
-
- // mTouchQueueLock is used to protect the vector and state below
- // as it is accessed on multiple threads.
- Mutex mTouchQueueLock;
- std::vector<MultiTouchInput> mTouchMoveEvents;
- bool mHavePendingTouchMoves;
- int mInflightNonMoveEvents;
- // end stuff protected by mTouchQueueLock
-
- bool mResamplingEnabled;
- bool mTouchEventsFiltered;
- bool mEnabledUniformityInfo;
-
- // All times below are in nanoseconds
- TimeDuration mVsyncAdjust; // Time from vsync we create sample times from
- TimeDuration mMaxPredict; // How far into the future we're allowed to extrapolate
- TimeDuration mMinDelta; // Minimal time difference between touches for resampling
-
- // Amount of time between vsync and the last event that is required before we
- // resample
- TimeDuration mMinResampleTime;
-
- // Threshold if a vsync event runs too far behind touch events
- TimeDuration mDelayedVsyncThreshold;
-
- // How far ahead can vsync events get ahead of touch events.
- TimeDuration mOldTouchThreshold;
-
- RefPtr<layers::CompositorVsyncScheduler> mCompositorVsyncScheduler;
-};
-
-} // namespace mozilla
-
-#endif // GECKO_TOUCH_INPUT_DISPATCHER_h
diff --git a/widget/gonk/GfxInfo.cpp b/widget/gonk/GfxInfo.cpp
deleted file mode 100644
index 7ddd39038..000000000
--- a/widget/gonk/GfxInfo.cpp
+++ /dev/null
@@ -1,194 +0,0 @@
-/* -*- 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 "GfxInfo.h"
-
-using namespace mozilla::widget;
-
-/* GetD2DEnabled and GetDwriteEnabled shouldn't be called until after gfxPlatform initialization
- * has occurred because they depend on it for information. (See bug 591561) */
-nsresult
-GfxInfo::GetD2DEnabled(bool *aEnabled)
-{
- return NS_ERROR_FAILURE;
-}
-
-nsresult
-GfxInfo::GetDWriteEnabled(bool *aEnabled)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetDWriteVersion(nsAString & aDwriteVersion)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetCleartypeParameters(nsAString & aCleartypeParams)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDescription(nsAString & aAdapterDescription)
-{
- aAdapterDescription.Truncate();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDescription2(nsAString & aAdapterDescription)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterRAM(nsAString & aAdapterRAM)
-{
- aAdapterRAM.Truncate();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterRAM2(nsAString & aAdapterRAM)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriver(nsAString & aAdapterDriver)
-{
- aAdapterDriver.Truncate();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriver2(nsAString & aAdapterDriver)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriverVersion(nsAString & aAdapterDriverVersion)
-{
- aAdapterDriverVersion.Truncate();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriverVersion2(nsAString & aAdapterDriverVersion)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriverDate(nsAString & aAdapterDriverDate)
-{
- aAdapterDriverDate.Truncate();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDriverDate2(nsAString & aAdapterDriverDate)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterVendorID(nsAString & aAdapterVendorID)
-{
- aAdapterVendorID.Truncate();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterVendorID2(nsAString & aAdapterVendorID)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDeviceID(nsAString & aAdapterDeviceID)
-{
- aAdapterDeviceID.Truncate();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterDeviceID2(nsAString & aAdapterDeviceID)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterSubsysID(nsAString & aAdapterSubsysID)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetAdapterSubsysID2(nsAString & aAdapterSubsysID)
-{
- return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-GfxInfo::GetIsGPU2Active(bool* aIsGPU2Active)
-{
- return NS_ERROR_FAILURE;
-}
-
-const nsTArray<GfxDriverInfo>&
-GfxInfo::GetGfxDriverInfo()
-{
- return *mDriverInfo;
-}
-
-uint32_t GfxInfo::OperatingSystemVersion()
-{
- return 0;
-}
-
-nsresult
-GfxInfo::GetFeatureStatusImpl(int32_t /*aFeature*/,
- int32_t *aStatus,
- nsAString & /*aSuggestedDriverVersion*/,
- const nsTArray<GfxDriverInfo>& /*aDriverInfo*/,
- nsACString& aFailureId,
- OperatingSystem* /*aOS*/ /* = nullptr */)
-{
- NS_ENSURE_ARG_POINTER(aStatus);
- *aStatus = nsIGfxInfo::FEATURE_STATUS_OK;
-
- return NS_OK;
-}
-
-#ifdef DEBUG
-
-// Implement nsIGfxInfoDebug
-
-NS_IMETHODIMP GfxInfo::SpoofVendorID(const nsAString &)
-{
- return NS_OK;
-}
-
-NS_IMETHODIMP GfxInfo::SpoofDeviceID(const nsAString &)
-{
- return NS_OK;
-}
-
-NS_IMETHODIMP GfxInfo::SpoofDriverVersion(const nsAString &)
-{
- return NS_OK;
-}
-
-NS_IMETHODIMP GfxInfo::SpoofOSVersion(uint32_t)
-{
- return NS_OK;
-}
-
-#endif
diff --git a/widget/gonk/GfxInfo.h b/widget/gonk/GfxInfo.h
deleted file mode 100644
index 61494713f..000000000
--- a/widget/gonk/GfxInfo.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* vim: se cin sw=2 ts=2 et : */
-/* -*- 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/. */
-
-#ifndef __mozilla_widget_GfxInfo_h__
-#define __mozilla_widget_GfxInfo_h__
-
-#include "GfxInfoBase.h"
-#include "GfxDriverInfo.h"
-
-#include "nsString.h"
-
-namespace mozilla {
-namespace widget {
-
-class GfxInfo : public GfxInfoBase
-{
-public:
- // We only declare the subset of nsIGfxInfo that we actually implement. The
- // rest is brought forward from GfxInfoBase.
- NS_IMETHOD GetD2DEnabled(bool *aD2DEnabled);
- NS_IMETHOD GetDWriteEnabled(bool *aDWriteEnabled);
- NS_IMETHOD GetDWriteVersion(nsAString & aDwriteVersion);
- NS_IMETHOD GetCleartypeParameters(nsAString & aCleartypeParams);
- NS_IMETHOD GetAdapterDescription(nsAString & aAdapterDescription);
- NS_IMETHOD GetAdapterDriver(nsAString & aAdapterDriver);
- NS_IMETHOD GetAdapterVendorID(nsAString & aAdapterVendorID);
- NS_IMETHOD GetAdapterDeviceID(nsAString & aAdapterDeviceID);
- NS_IMETHOD GetAdapterSubsysID(nsAString & aAdapterSubsysID);
- NS_IMETHOD GetAdapterRAM(nsAString & aAdapterRAM);
- NS_IMETHOD GetAdapterDriverVersion(nsAString & aAdapterDriverVersion);
- NS_IMETHOD GetAdapterDriverDate(nsAString & aAdapterDriverDate);
- NS_IMETHOD GetAdapterDescription2(nsAString & aAdapterDescription);
- NS_IMETHOD GetAdapterDriver2(nsAString & aAdapterDriver);
- NS_IMETHOD GetAdapterVendorID2(nsAString & aAdapterVendorID);
- NS_IMETHOD GetAdapterDeviceID2(nsAString & aAdapterDeviceID);
- NS_IMETHOD GetAdapterSubsysID2(nsAString & aAdapterSubsysID);
- NS_IMETHOD GetAdapterRAM2(nsAString & aAdapterRAM);
- NS_IMETHOD GetAdapterDriverVersion2(nsAString & aAdapterDriverVersion);
- NS_IMETHOD GetAdapterDriverDate2(nsAString & aAdapterDriverDate);
- NS_IMETHOD GetIsGPU2Active(bool *aIsGPU2Active);
- using GfxInfoBase::GetFeatureStatus;
- using GfxInfoBase::GetFeatureSuggestedDriverVersion;
- using GfxInfoBase::GetWebGLParameter;
-
- virtual uint32_t OperatingSystemVersion() override;
-
-#ifdef DEBUG
- NS_DECL_NSIGFXINFODEBUG
-#endif
-
-protected:
-
- virtual nsresult GetFeatureStatusImpl(int32_t aFeature,
- int32_t *aStatus,
- nsAString & aSuggestedDriverVersion,
- const nsTArray<GfxDriverInfo>& aDriverInfo,
- nsACString& aFailureId,
- OperatingSystem* aOS = nullptr);
- virtual const nsTArray<GfxDriverInfo>& GetGfxDriverInfo();
-};
-
-} // namespace widget
-} // namespace mozilla
-
-#endif /* __mozilla_widget_GfxInfo_h__ */
diff --git a/widget/gonk/GonkClipboardData.cpp b/widget/gonk/GonkClipboardData.cpp
deleted file mode 100644
index ced6422a5..000000000
--- a/widget/gonk/GonkClipboardData.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "GonkClipboardData.h"
-#include "mozilla/gfx/DataSurfaceHelpers.h"
-
-namespace mozilla {
-
-void
-GonkClipboardData::SetText(const nsAString &aText)
-{
- mPlain = aText;
-}
-
-bool
-GonkClipboardData::HasText() const
-{
- return !mPlain.IsEmpty();
-}
-
-const nsAString&
-GonkClipboardData::GetText() const
-{
- return mPlain;
-}
-
-void
-GonkClipboardData::SetHTML(const nsAString &aHTML)
-{
- mHTML = aHTML;
-}
-
-bool
-GonkClipboardData::HasHTML() const
-{
- return !mHTML.IsEmpty();
-}
-
-const nsAString&
-GonkClipboardData::GetHTML() const
-{
- return mHTML;
-}
-
-void
-GonkClipboardData::SetImage(gfx::DataSourceSurface* aDataSource)
-{
- // Clone a new DataSourceSurface and store it.
- mImage = gfx::CreateDataSourceSurfaceByCloning(aDataSource);
-}
-
-bool
-GonkClipboardData::HasImage() const
-{
- return static_cast<bool>(mImage);
-}
-
-already_AddRefed<gfx::DataSourceSurface>
-GonkClipboardData::GetImage() const
-{
- // Return cloned DataSourceSurface.
- RefPtr<gfx::DataSourceSurface> cloned = gfx::CreateDataSourceSurfaceByCloning(mImage);
- return cloned.forget();
-}
-
-void
-GonkClipboardData::Clear()
-{
- mPlain.Truncate(0);
- mHTML.Truncate(0);
- mImage = nullptr;
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/GonkClipboardData.h b/widget/gonk/GonkClipboardData.h
deleted file mode 100644
index 8bc1f1c9c..000000000
--- a/widget/gonk/GonkClipboardData.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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_GonkClipboardData
-#define mozilla_GonkClipboardData
-
-#include "mozilla/RefPtr.h"
-#include "nsString.h"
-
-namespace mozilla {
-
-namespace gfx {
-class DataSourceSurface;
-}
-
-class GonkClipboardData final
-{
-public:
- explicit GonkClipboardData() = default;
- ~GonkClipboardData() = default;
-
- // For text/plain
- void SetText(const nsAString &aText);
- bool HasText() const;
- const nsAString& GetText() const;
-
- // For text/html
- void SetHTML(const nsAString &aHTML);
- bool HasHTML() const;
- const nsAString& GetHTML() const;
-
- // For images
- void SetImage(gfx::DataSourceSurface* aDataSource);
- bool HasImage() const;
- already_AddRefed<gfx::DataSourceSurface> GetImage() const;
-
- // For other APIs
- void Clear();
-
-private:
- nsAutoString mPlain;
- nsAutoString mHTML;
- RefPtr<gfx::DataSourceSurface> mImage;
-};
-
-} // namespace mozilla
-
-#endif // mozilla_GonkClipboardData
diff --git a/widget/gonk/GonkKeyMapping.h b/widget/gonk/GonkKeyMapping.h
deleted file mode 100644
index d5d4e7a0b..000000000
--- a/widget/gonk/GonkKeyMapping.h
+++ /dev/null
@@ -1,301 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef GONKKEYMAPPING_H
-#define GONKKEYMAPPING_H
-
-#include "libui/android_keycodes.h"
-#include "mozilla/EventForwards.h"
-
-namespace mozilla {
-namespace widget {
-
-/* See libui/KeycodeLabels.h for the mapping */
-static const unsigned long kKeyMapping[] = {
- 0,
- 0, // SOFT_LEFT
- 0, // SOFT_RIGHT
- NS_VK_HOME, // HOME
- NS_VK_ESCAPE, // BACK
- 0, // CALL
- NS_VK_SLEEP, // ENDCALL
- NS_VK_0,
- NS_VK_1,
- NS_VK_2,
- NS_VK_3,
- NS_VK_4,
- NS_VK_5,
- NS_VK_6,
- NS_VK_7,
- NS_VK_8,
- NS_VK_9,
- NS_VK_ASTERISK,
- NS_VK_HASH,
- NS_VK_UP,
- NS_VK_DOWN,
- NS_VK_LEFT,
- NS_VK_RIGHT,
- NS_VK_RETURN,
- NS_VK_VOLUME_UP,
- NS_VK_VOLUME_DOWN,
- NS_VK_SLEEP, // POWER
- NS_VK_PRINTSCREEN, // CAMERA
- NS_VK_CLEAR,
- NS_VK_A,
- NS_VK_B,
- NS_VK_C,
- NS_VK_D,
- NS_VK_E,
- NS_VK_F,
- NS_VK_G,
- NS_VK_H,
- NS_VK_I,
- NS_VK_J,
- NS_VK_K,
- NS_VK_L,
- NS_VK_M,
- NS_VK_N,
- NS_VK_O,
- NS_VK_P,
- NS_VK_Q,
- NS_VK_R,
- NS_VK_S,
- NS_VK_T,
- NS_VK_U,
- NS_VK_V,
- NS_VK_W,
- NS_VK_X,
- NS_VK_Y,
- NS_VK_Z,
- NS_VK_COMMA,
- NS_VK_PERIOD,
- 0,
- 0,
- 0,
- 0,
- NS_VK_TAB,
- NS_VK_SPACE,
- NS_VK_META, // SYM
- 0, // EXPLORER
- 0, // ENVELOPE
- NS_VK_RETURN, // ENTER
- NS_VK_BACK,
- NS_VK_BACK_QUOTE, // GRAVE
- NS_VK_HYPHEN_MINUS,
- NS_VK_EQUALS,
- NS_VK_OPEN_BRACKET,
- NS_VK_CLOSE_BRACKET,
- NS_VK_BACK_SLASH,
- NS_VK_SEMICOLON,
- NS_VK_QUOTE,
- NS_VK_SLASH,
- NS_VK_AT,
- 0, // NUM
- NS_VK_F1, // HEADSETHOOK
- 0, // FOCUS
- NS_VK_PLUS,
- NS_VK_CONTEXT_MENU,
- 0, // NOTIFICATION
- NS_VK_F5, // SEARCH
- 0, // MEDIA_PLAY_PAUSE
- 0, // MEDIA_STOP
- 0, // MEDIA_NEXT
- 0, // MEDIA_PREVIOUS
- 0, // MEDIA_REWIND
- 0, // MEDIA_FAST_FORWARD
- 0, // MUTE
- NS_VK_PAGE_UP,
- NS_VK_PAGE_DOWN,
- 0, // PICTSYMBOLS
- 0, // SWITCH_CHARSET
- 0, // BUTTON_A
- 0, // BUTTON_B
- 0, // BUTTON_C
- 0, // BUTTON_X
- 0, // BUTTON_Y
- 0, // BUTTON_Z
- 0, // BUTTON_L1
- 0, // BUTTON_R1
- 0, // BUTTON_L2
- 0, // BUTTON_R2
- 0, // BUTTON_THUMBL
- 0, // BUTTON_THUMBR
- 0, // BUTTON_START
- 0, // BUTTON_SELECT
- 0, // BUTTON_MODE
- NS_VK_ESCAPE,
- NS_VK_DELETE,
- 0, // CTRL_LEFT
- 0, // CTRL_RIGHT
- NS_VK_CAPS_LOCK,
- NS_VK_SCROLL_LOCK,
- 0, // META_LEFT
- 0, // META_RIGHT
- 0, // FUNCTION
- 0, // SYSRQ
- 0, // BREAK
- NS_VK_HOME, // MOVE_HOME
- NS_VK_END,
- NS_VK_INSERT,
- 0, // FORWARD
- 0, // MEDIA_PLAY
- 0, // MEDIA_PAUSE
- 0, // MEDIA_CLOSE
- 0, // MEDIA_EJECT
- 0, // MEDIA_RECORD
- NS_VK_F1,
- NS_VK_F2,
- NS_VK_F3,
- NS_VK_F4,
- NS_VK_F5,
- NS_VK_F6,
- NS_VK_F7,
- NS_VK_F8,
- NS_VK_F9,
- NS_VK_F10,
- NS_VK_F11,
- NS_VK_F12,
- NS_VK_NUM_LOCK,
- NS_VK_NUMPAD0,
- NS_VK_NUMPAD1,
- NS_VK_NUMPAD2,
- NS_VK_NUMPAD3,
- NS_VK_NUMPAD4,
- NS_VK_NUMPAD5,
- NS_VK_NUMPAD6,
- NS_VK_NUMPAD7,
- NS_VK_NUMPAD8,
- NS_VK_NUMPAD9,
- NS_VK_DIVIDE,
- NS_VK_MULTIPLY,
- NS_VK_SUBTRACT,
- NS_VK_ADD,
- NS_VK_PERIOD,
- NS_VK_COMMA,
- NS_VK_RETURN,
- NS_VK_EQUALS,
- 0, // NUMPAD_LEFT_PAREN
- 0, // NUMPAD_RIGHT_PAREN
- NS_VK_VOLUME_MUTE,
- // There are more but we don't map them
-};
-
-static KeyNameIndex GetKeyNameIndex(int aKeyCode)
-{
- switch (aKeyCode) {
-#define NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX(aNativeKey, aKeyNameIndex) \
- case aNativeKey: return aKeyNameIndex;
-
-#include "NativeKeyToDOMKeyName.h"
-
-#undef NS_NATIVE_KEY_TO_DOM_KEY_NAME_INDEX
-
- case AKEYCODE_0:
- case AKEYCODE_1:
- case AKEYCODE_2:
- case AKEYCODE_3:
- case AKEYCODE_4:
- case AKEYCODE_5:
- case AKEYCODE_6:
- case AKEYCODE_7:
- case AKEYCODE_8:
- case AKEYCODE_9:
- case AKEYCODE_STAR:
- case AKEYCODE_POUND:
- case AKEYCODE_A:
- case AKEYCODE_B:
- case AKEYCODE_C:
- case AKEYCODE_D:
- case AKEYCODE_E:
- case AKEYCODE_F:
- case AKEYCODE_G:
- case AKEYCODE_H:
- case AKEYCODE_I:
- case AKEYCODE_J:
- case AKEYCODE_K:
- case AKEYCODE_L:
- case AKEYCODE_M:
- case AKEYCODE_N:
- case AKEYCODE_O:
- case AKEYCODE_P:
- case AKEYCODE_Q:
- case AKEYCODE_R:
- case AKEYCODE_S:
- case AKEYCODE_T:
- case AKEYCODE_U:
- case AKEYCODE_V:
- case AKEYCODE_W:
- case AKEYCODE_X:
- case AKEYCODE_Y:
- case AKEYCODE_Z:
- case AKEYCODE_COMMA:
- case AKEYCODE_PERIOD:
- case AKEYCODE_SPACE:
- case AKEYCODE_GRAVE:
- case AKEYCODE_MINUS:
- case AKEYCODE_EQUALS:
- case AKEYCODE_LEFT_BRACKET:
- case AKEYCODE_RIGHT_BRACKET:
- case AKEYCODE_BACKSLASH:
- case AKEYCODE_SEMICOLON:
- case AKEYCODE_APOSTROPHE:
- case AKEYCODE_SLASH:
- case AKEYCODE_AT:
- case AKEYCODE_PLUS:
- case AKEYCODE_NUMPAD_0:
- case AKEYCODE_NUMPAD_1:
- case AKEYCODE_NUMPAD_2:
- case AKEYCODE_NUMPAD_3:
- case AKEYCODE_NUMPAD_4:
- case AKEYCODE_NUMPAD_5:
- case AKEYCODE_NUMPAD_6:
- case AKEYCODE_NUMPAD_7:
- case AKEYCODE_NUMPAD_8:
- case AKEYCODE_NUMPAD_9:
- case AKEYCODE_NUMPAD_DIVIDE:
- case AKEYCODE_NUMPAD_MULTIPLY:
- case AKEYCODE_NUMPAD_SUBTRACT:
- case AKEYCODE_NUMPAD_ADD:
- case AKEYCODE_NUMPAD_DOT:
- case AKEYCODE_NUMPAD_COMMA:
- case AKEYCODE_NUMPAD_EQUALS:
- case AKEYCODE_NUMPAD_LEFT_PAREN:
- case AKEYCODE_NUMPAD_RIGHT_PAREN:
- return KEY_NAME_INDEX_USE_STRING;
-
- default:
- return KEY_NAME_INDEX_Unidentified;
- }
-}
-
-static CodeNameIndex GetCodeNameIndex(int aScanCode)
-{
- switch (aScanCode) {
-#define NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX(aNativeKey, aCodeNameIndex) \
- case aNativeKey: return aCodeNameIndex;
-
-#include "NativeKeyToDOMCodeName.h"
-
-#undef NS_NATIVE_KEY_TO_DOM_CODE_NAME_INDEX
-
- default:
- return CODE_NAME_INDEX_UNKNOWN;
- }
-}
-
-} // namespace widget
-} // namespace mozilla
-
-#endif /* GONKKEYMAPPING_H */
diff --git a/widget/gonk/GonkMemoryPressureMonitoring.cpp b/widget/gonk/GonkMemoryPressureMonitoring.cpp
deleted file mode 100644
index 0fafb37cf..000000000
--- a/widget/gonk/GonkMemoryPressureMonitoring.cpp
+++ /dev/null
@@ -1,359 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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 <android/log.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <sys/sysinfo.h>
-
-#include "GonkMemoryPressureMonitoring.h"
-#include "mozilla/ArrayUtils.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/Monitor.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/ProcessPriorityManager.h"
-#include "mozilla/Services.h"
-#include "nsIObserver.h"
-#include "nsIObserverService.h"
-#include "nsMemoryPressure.h"
-#include "nsPrintfCString.h"
-#include "nsThreadUtils.h"
-
-#define LOG(args...) \
- __android_log_print(ANDROID_LOG_INFO, "GonkMemoryPressure" , ## args)
-
-using namespace mozilla;
-
-namespace {
-
-/**
- * MemoryPressureWatcher watches sysfs from its own thread to notice when the
- * system is under memory pressure. When we observe memory pressure, we use
- * MemoryPressureRunnable to notify observers that they should release memory.
- *
- * When the system is under memory pressure, we don't want to constantly fire
- * memory-pressure events. So instead, we try to detect when sysfs indicates
- * that we're no longer under memory pressure, and only then start firing events
- * again.
- *
- * (This is a bit problematic because we can't poll() to detect when we're no
- * longer under memory pressure; instead we have to periodically read the sysfs
- * node. If we remain under memory pressure for a long time, this means we'll
- * continue waking up to read from the node for a long time, potentially wasting
- * battery life. Hopefully we don't hit this case in practice! We write to
- * logcat each time we go around this loop so it's at least noticable.)
- *
- * Shutting down safely is a bit of a chore. XPCOM won't shut down until all
- * threads exit, so we need to exit the Run() method below on shutdown. But our
- * thread might be blocked in one of two situations: We might be poll()'ing the
- * sysfs node waiting for memory pressure to occur, or we might be asleep
- * waiting to read() the sysfs node to see if we're no longer under memory
- * pressure.
- *
- * To let us wake up from the poll(), we poll() not just the sysfs node but also
- * a pipe, which we write to on shutdown. To let us wake up from sleeping
- * between read()s, we sleep by Wait()'ing on a monitor, which we notify on
- * shutdown.
- */
-class MemoryPressureWatcher final
- : public nsIRunnable
- , public nsIObserver
-{
-public:
- MemoryPressureWatcher()
- : mMonitor("MemoryPressureWatcher")
- , mLowMemTriggerKB(0)
- , mPageSize(0)
- , mShuttingDown(false)
- , mTriggerFd(-1)
- , mShutdownPipeRead(-1)
- , mShutdownPipeWrite(-1)
- {
- }
-
- NS_DECL_THREADSAFE_ISUPPORTS
-
- nsresult Init()
- {
- nsCOMPtr<nsIObserverService> os = services::GetObserverService();
- NS_ENSURE_STATE(os);
-
- // The observer service holds us alive.
- os->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, /* ownsWeak */ false);
-
- // Initialize the internal state
- mPageSize = sysconf(_SC_PAGESIZE);
- ReadPrefs();
- nsresult rv = OpenFiles();
- NS_ENSURE_SUCCESS(rv, rv);
- SetLowMemTrigger(mSoftLowMemTriggerKB);
-
- return NS_OK;
- }
-
- NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic,
- const char16_t* aData)
- {
- MOZ_ASSERT(strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0);
- LOG("Observed XPCOM shutdown.");
-
- MonitorAutoLock lock(mMonitor);
- mShuttingDown = true;
- mMonitor.Notify();
-
- int rv;
- do {
- // Write something to the pipe; doesn't matter what.
- uint32_t dummy = 0;
- rv = write(mShutdownPipeWrite, &dummy, sizeof(dummy));
- } while(rv == -1 && errno == EINTR);
-
- return NS_OK;
- }
-
- NS_IMETHOD Run() override
- {
- MOZ_ASSERT(!NS_IsMainThread());
-
- int triggerResetTimeout = -1;
- bool memoryPressure;
- nsresult rv = CheckForMemoryPressure(&memoryPressure);
- NS_ENSURE_SUCCESS(rv, rv);
-
- while (true) {
- // Wait for a notification on mTriggerFd or for data to be written to
- // mShutdownPipeWrite. (poll(mTriggerFd, POLLPRI) blocks until we're
- // under memory pressure or until we time out, the time out is used
- // to adjust the trigger level after a memory pressure event.)
- struct pollfd pollfds[2];
- pollfds[0].fd = mTriggerFd;
- pollfds[0].events = POLLPRI;
- pollfds[1].fd = mShutdownPipeRead;
- pollfds[1].events = POLLIN;
-
- int pollRv = MOZ_TEMP_FAILURE_RETRY(
- poll(pollfds, ArrayLength(pollfds), triggerResetTimeout)
- );
-
- if (pollRv == 0) {
- // Timed out, adjust the trigger and update the timeout.
- triggerResetTimeout = AdjustTrigger(triggerResetTimeout);
- continue;
- }
-
- if (pollfds[1].revents) {
- // Something was written to our shutdown pipe; we're outta here.
- LOG("shutting down (1)");
- return NS_OK;
- }
-
- // If pollfds[1] isn't happening, pollfds[0] ought to be!
- if (!(pollfds[0].revents & POLLPRI)) {
- LOG("Unexpected revents value after poll(): %d. "
- "Shutting down GonkMemoryPressureMonitoring.", pollfds[0].revents);
- return NS_ERROR_FAILURE;
- }
-
- // POLLPRI on mTriggerFd indicates that we're in a low-memory situation.
- // We could read lowMemFd to double-check, but we've observed that the
- // read sometimes completes after the memory-pressure event is over, so
- // let's just believe the result of poll().
- rv = DispatchMemoryPressure(MemPressure_New);
- NS_ENSURE_SUCCESS(rv, rv);
-
- // Move to the hard level if we're on the soft one.
- if (mLowMemTriggerKB > mHardLowMemTriggerKB) {
- SetLowMemTrigger(mHardLowMemTriggerKB);
- }
-
- // Manually check mTriggerFd until we observe that memory pressure is
- // over. We won't fire any more low-memory events until we observe that
- // we're no longer under pressure. Instead, we fire low-memory-ongoing
- // events, which cause processes to keep flushing caches but will not
- // trigger expensive GCs and other attempts to save memory that are
- // likely futile at this point.
- do {
- {
- MonitorAutoLock lock(mMonitor);
-
- // We need to check mShuttingDown before we wait here, in order to
- // catch a shutdown signal sent after we poll()'ed mShutdownPipeRead
- // above but before we started waiting on the monitor. But we don't
- // need to check after we wait, because we'll either do another
- // iteration of this inner loop, in which case we'll check
- // mShuttingDown, or we'll exit this loop and do another iteration
- // of the outer loop, in which case we'll check the shutdown pipe.
- if (mShuttingDown) {
- LOG("shutting down (2)");
- return NS_OK;
- }
- mMonitor.Wait(PR_MillisecondsToInterval(mPollMS));
- }
-
- LOG("Checking to see if memory pressure is over.");
- rv = CheckForMemoryPressure(&memoryPressure);
- NS_ENSURE_SUCCESS(rv, rv);
-
- if (memoryPressure) {
- rv = DispatchMemoryPressure(MemPressure_Ongoing);
- NS_ENSURE_SUCCESS(rv, rv);
- continue;
- }
- } while (false);
-
- if (XRE_IsParentProcess()) {
- // The main process will try to adjust the trigger.
- triggerResetTimeout = mPollMS * 2;
- }
-
- LOG("Memory pressure is over.");
- }
-
- return NS_OK;
- }
-
-protected:
- ~MemoryPressureWatcher() {}
-
-private:
- void ReadPrefs() {
- // While we're under memory pressure, we periodically read()
- // notify_trigger_active to try and see when we're no longer under memory
- // pressure. mPollMS indicates how many milliseconds we wait between those
- // read()s.
- Preferences::AddUintVarCache(&mPollMS,
- "gonk.systemMemoryPressureRecoveryPollMS", /* default */ 5000);
-
- // We have two values for the notify trigger, a soft one which is triggered
- // before we start killing background applications and an hard one which is
- // after we've killed background applications but before we start killing
- // foreground ones.
- Preferences::AddUintVarCache(&mSoftLowMemTriggerKB,
- "gonk.notifySoftLowMemUnderKB", /* default */ 43008);
- Preferences::AddUintVarCache(&mHardLowMemTriggerKB,
- "gonk.notifyHardLowMemUnderKB", /* default */ 14336);
- }
-
- nsresult OpenFiles() {
- mTriggerFd = open("/sys/kernel/mm/lowmemkiller/notify_trigger_active",
- O_RDONLY | O_CLOEXEC);
- NS_ENSURE_STATE(mTriggerFd != -1);
-
- int pipes[2];
- NS_ENSURE_STATE(!pipe(pipes));
- mShutdownPipeRead = pipes[0];
- mShutdownPipeWrite = pipes[1];
- return NS_OK;
- }
-
- /**
- * Set the low memory trigger to the specified value, this can be done by
- * the main process alone.
- */
- void SetLowMemTrigger(uint32_t aValue) {
- if (XRE_IsParentProcess()) {
- nsPrintfCString str("%ld", (aValue * 1024) / mPageSize);
- if (WriteSysFile("/sys/module/lowmemorykiller/parameters/notify_trigger",
- str.get())) {
- mLowMemTriggerKB = aValue;
- }
- }
- }
-
- /**
- * Read from the trigger file descriptor and determine whether we're
- * currently under memory pressure.
- *
- * We don't expect this method to block.
- */
- nsresult CheckForMemoryPressure(bool* aOut)
- {
- *aOut = false;
-
- lseek(mTriggerFd, 0, SEEK_SET);
-
- char buf[2];
- int nread = MOZ_TEMP_FAILURE_RETRY(read(mTriggerFd, buf, sizeof(buf)));
- NS_ENSURE_STATE(nread == 2);
-
- // The notify_trigger_active sysfs node should contain either "0\n" or
- // "1\n". The latter indicates memory pressure.
- *aOut = (buf[0] == '1');
- return NS_OK;
- }
-
- int AdjustTrigger(int timeout)
- {
- if (!XRE_IsParentProcess()) {
- return -1; // Only the main process can adjust the trigger.
- }
-
- struct sysinfo info;
- int rv = sysinfo(&info);
- if (rv < 0) {
- return -1; // Without system information we're blind, bail out.
- }
-
- size_t freeMemory = (info.freeram * info.mem_unit) / 1024;
-
- if (freeMemory > mSoftLowMemTriggerKB) {
- SetLowMemTrigger(mSoftLowMemTriggerKB);
- return -1; // Trigger adjusted, wait indefinitely.
- }
-
- // Wait again but double the duration, max once per day.
- return std::min(86400000, timeout * 2);
- }
-
- /**
- * Dispatch the specified memory pressure event unless a high-priority
- * process is present. If a high-priority process is present then it's likely
- * responding to an urgent event (an incoming call or message for example) so
- * avoid wasting CPU time responding to low-memory events.
- */
- nsresult DispatchMemoryPressure(MemoryPressureState state)
- {
- if (ProcessPriorityManager::AnyProcessHasHighPriority()) {
- return NS_OK;
- }
-
- return NS_DispatchMemoryPressure(state);
- }
-
- Monitor mMonitor;
- uint32_t mPollMS; // Ongoing pressure poll delay
- uint32_t mSoftLowMemTriggerKB; // Soft memory pressure level
- uint32_t mHardLowMemTriggerKB; // Hard memory pressure level
- uint32_t mLowMemTriggerKB; // Current value of the trigger
- size_t mPageSize;
- bool mShuttingDown;
-
- ScopedClose mTriggerFd;
- ScopedClose mShutdownPipeRead;
- ScopedClose mShutdownPipeWrite;
-};
-
-NS_IMPL_ISUPPORTS(MemoryPressureWatcher, nsIRunnable, nsIObserver);
-
-} // namespace
-
-namespace mozilla {
-
-void
-InitGonkMemoryPressureMonitoring()
-{
- // memoryPressureWatcher is held alive by the observer service.
- RefPtr<MemoryPressureWatcher> memoryPressureWatcher =
- new MemoryPressureWatcher();
- NS_ENSURE_SUCCESS_VOID(memoryPressureWatcher->Init());
-
- nsCOMPtr<nsIThread> thread;
- NS_NewNamedThread("MemoryPressure", getter_AddRefs(thread),
- memoryPressureWatcher);
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/GonkMemoryPressureMonitoring.h b/widget/gonk/GonkMemoryPressureMonitoring.h
deleted file mode 100644
index 4d5149cd6..000000000
--- a/widget/gonk/GonkMemoryPressureMonitoring.h
+++ /dev/null
@@ -1,14 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; 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/. */
-
-#ifndef mozilla_GonkMemoryPressureMonitoring_h_
-#define mozilla_GonkMemoryPressureMonitoring_h_
-
-namespace mozilla {
-void InitGonkMemoryPressureMonitoring();
-}
-
-#endif /* mozilla_GonkMemoryPressureMonitoring_h_ */
diff --git a/widget/gonk/GonkPermission.cpp b/widget/gonk/GonkPermission.cpp
deleted file mode 100644
index 8ebc43de8..000000000
--- a/widget/gonk/GonkPermission.cpp
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (C) 2012 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "GonkPermission.h"
-#include <binder/IPCThreadState.h>
-#include <binder/ProcessState.h>
-#include <binder/IServiceManager.h>
-#include <binder/IPermissionController.h>
-
-#ifndef HAVE_ANDROID_OS
-#define HAVE_ANDROID_OS 1
-#endif
-#include <private/android_filesystem_config.h>
-
-#include "mozilla/dom/ContentParent.h"
-#include "mozilla/dom/TabParent.h"
-#include "mozilla/SyncRunnable.h"
-#include "nsIAppsService.h"
-#include "mozIApplication.h"
-#include "nsThreadUtils.h"
-
-#undef LOG
-#include <android/log.h>
-#undef ALOGE
-#define ALOGE(args...) __android_log_print(ANDROID_LOG_ERROR, "gonkperm" , ## args)
-
-using namespace android;
-using namespace mozilla;
-
-// Checking permissions needs to happen on the main thread, but the
-// binder callback is called on a special binder thread, so we use
-// this runnable for that.
-class GonkPermissionChecker : public Runnable {
- int32_t mPid;
- bool mCanUseCamera;
-
- explicit GonkPermissionChecker(int32_t pid)
- : mPid(pid)
- , mCanUseCamera(false)
- {
- }
-
-public:
- static already_AddRefed<GonkPermissionChecker> Inspect(int32_t pid)
- {
- RefPtr<GonkPermissionChecker> that = new GonkPermissionChecker(pid);
- nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
- MOZ_ASSERT(mainThread);
- SyncRunnable::DispatchToThread(mainThread, that);
- return that.forget();
- }
-
- bool CanUseCamera()
- {
- return mCanUseCamera;
- }
-
- NS_IMETHOD Run();
-};
-
-NS_IMETHODIMP
-GonkPermissionChecker::Run()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- // Find our ContentParent.
- dom::ContentParent *contentParent = nullptr;
- {
- nsTArray<dom::ContentParent*> parents;
- dom::ContentParent::GetAll(parents);
- for (uint32_t i = 0; i < parents.Length(); ++i) {
- if (parents[i]->Pid() == mPid) {
- contentParent = parents[i];
- break;
- }
- }
- }
- if (!contentParent) {
- ALOGE("pid=%d denied: can't find ContentParent", mPid);
- return NS_OK;
- }
-
- // Now iterate its apps...
- const ManagedContainer<dom::PBrowserParent>& browsers =
- contentParent->ManagedPBrowserParent();
- for (auto iter = browsers.ConstIter(); !iter.Done(); iter.Next()) {
- dom::TabParent *tabParent =
- static_cast<dom::TabParent*>(iter.Get()->GetKey());
- nsCOMPtr<mozIApplication> mozApp = tabParent->GetOwnOrContainingApp();
- if (!mozApp) {
- continue;
- }
-
- // ...and check if any of them has camera access.
- bool appCanUseCamera;
- nsresult rv = mozApp->HasPermission("camera", &appCanUseCamera);
- if (NS_SUCCEEDED(rv) && appCanUseCamera) {
- mCanUseCamera = true;
- return NS_OK;
- }
- }
- return NS_OK;
-}
-
-bool
-GonkPermissionService::checkPermission(const String16& permission, int32_t pid,
- int32_t uid)
-{
- // root can do anything.
- if (0 == uid) {
- return true;
- }
-
- String8 perm8(permission);
-
- // Some ril implementations need android.permission.MODIFY_AUDIO_SETTINGS
- if ((uid == AID_SYSTEM || uid == AID_RADIO || uid == AID_BLUETOOTH) &&
- perm8 == "android.permission.MODIFY_AUDIO_SETTINGS") {
- return true;
- }
-
- // No other permissions apply to non-app processes.
- if (uid < AID_APP) {
- ALOGE("%s for pid=%d,uid=%d denied: not an app",
- String8(permission).string(), pid, uid);
- return false;
- }
-
- // Only these permissions can be granted to apps through this service.
- if (perm8 != "android.permission.CAMERA" &&
- perm8 != "android.permission.RECORD_AUDIO") {
- ALOGE("%s for pid=%d,uid=%d denied: unsupported permission",
- String8(permission).string(), pid, uid);
- return false;
- }
-
- // Users granted the permission through a prompt dialog.
- // Before permission managment of gUM is done, app cannot remember the
- // permission.
- PermissionGrant permGrant(perm8.string(), pid);
- if (nsTArray<PermissionGrant>::NoIndex != mGrantArray.IndexOf(permGrant)) {
- mGrantArray.RemoveElement(permGrant);
- return true;
- }
-
- // Camera/audio record permissions are allowed for apps with the
- // "camera" permission.
- RefPtr<GonkPermissionChecker> checker =
- GonkPermissionChecker::Inspect(pid);
- bool canUseCamera = checker->CanUseCamera();
- if (!canUseCamera) {
- ALOGE("%s for pid=%d,uid=%d denied: not granted by user or app manifest",
- String8(permission).string(), pid, uid);
- }
- return canUseCamera;
-}
-
-static GonkPermissionService* gGonkPermissionService = NULL;
-
-/* static */
-void
-GonkPermissionService::instantiate()
-{
- defaultServiceManager()->addService(String16(getServiceName()),
- GetInstance());
-}
-
-/* static */
-GonkPermissionService*
-GonkPermissionService::GetInstance()
-{
- if (!gGonkPermissionService) {
- gGonkPermissionService = new GonkPermissionService();
- }
- return gGonkPermissionService;
-}
-
-void
-GonkPermissionService::addGrantInfo(const char* permission, int32_t pid)
-{
- mGrantArray.AppendElement(PermissionGrant(permission, pid));
-}
diff --git a/widget/gonk/GonkPermission.h b/widget/gonk/GonkPermission.h
deleted file mode 100644
index d34fcd8ac..000000000
--- a/widget/gonk/GonkPermission.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2012 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#ifndef GONKPERMISSION_H
-#define GONKPERMISSION_H
-
-#include <binder/BinderService.h>
-#include "nsString.h"
-#include "nsTArray.h"
-
-namespace mozilla {
-class PermissionGrant
-{
-public:
- PermissionGrant(const char* perm, int32_t p) : mPid(p)
- {
- mPermission.Assign(perm);
- }
-
- PermissionGrant(const nsACString& permission, int32_t pid) : mPid(pid),
- mPermission(permission)
- {
- }
-
- bool operator==(const PermissionGrant& other) const
- {
- return (mPid == other.pid() && mPermission.Equals(other.permission()));
- }
-
- int32_t pid() const
- {
- return mPid;
- }
-
- const nsACString& permission() const
- {
- return mPermission;
- }
-
-private:
- int32_t mPid;
- nsCString mPermission;
-};
-
-class PermissionGrant;
-
-class GonkPermissionService :
- public android::BinderService<GonkPermissionService>,
- public android::BnPermissionController
-{
-public:
- virtual ~GonkPermissionService() {}
- static GonkPermissionService* GetInstance();
- static const char *getServiceName() {
- return "permission";
- }
-
- static void instantiate();
-
- virtual android::status_t dump(int fd, const android::Vector<android::String16>& args) {
- return android::NO_ERROR;
- }
- virtual bool checkPermission(const android::String16& permission, int32_t pid,
- int32_t uid);
-
- void addGrantInfo(const char* permission, int32_t pid);
-private:
- GonkPermissionService(): android::BnPermissionController() {}
- nsTArray<PermissionGrant> mGrantArray;
-};
-
-} // namespace mozilla
-
-#endif // GONKPERMISSION_H
diff --git a/widget/gonk/HwcComposer2D.cpp b/widget/gonk/HwcComposer2D.cpp
deleted file mode 100644
index 6b4c7a1cc..000000000
--- a/widget/gonk/HwcComposer2D.cpp
+++ /dev/null
@@ -1,971 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:set ts=4 sw=4 sts=4 et: */
-/*
- * Copyright (c) 2012, 2013 The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <android/log.h>
-#include <string.h>
-
-#include "gfxPrefs.h"
-#include "ImageLayers.h"
-#include "libdisplay/GonkDisplay.h"
-#include "HwcComposer2D.h"
-#include "LayerScope.h"
-#include "Units.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/layers/CompositorBridgeParent.h"
-#include "mozilla/layers/LayerManagerComposite.h"
-#include "mozilla/layers/PLayerTransaction.h"
-#include "mozilla/layers/ShadowLayerUtilsGralloc.h"
-#include "mozilla/layers/TextureHostOGL.h" // for TextureHostOGL
-#include "mozilla/StaticPtr.h"
-#include "nsThreadUtils.h"
-#include "cutils/properties.h"
-#include "gfx2DGlue.h"
-#include "gfxPlatform.h"
-#include "VsyncSource.h"
-#include "nsScreenManagerGonk.h"
-#include "nsWindow.h"
-
-#if ANDROID_VERSION >= 17
-#include "libdisplay/DisplaySurface.h"
-#endif
-
-#ifdef LOG_TAG
-#undef LOG_TAG
-#endif
-#define LOG_TAG "HWComposer"
-
-/*
- * By default the debug message of hwcomposer (LOG_DEBUG level) are undefined,
- * but can be enabled by uncommenting HWC_DEBUG below.
- */
-//#define HWC_DEBUG
-
-#ifdef HWC_DEBUG
-#define LOGD(args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, ## args)
-#else
-#define LOGD(args...) ((void)0)
-#endif
-
-#define LOGI(args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, ## args)
-#define LOGE(args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, ## args)
-
-#define LAYER_COUNT_INCREMENTS 5
-
-using namespace android;
-using namespace mozilla::gfx;
-using namespace mozilla::layers;
-
-namespace mozilla {
-
-static void
-HookInvalidate(const struct hwc_procs* aProcs)
-{
- HwcComposer2D::GetInstance()->Invalidate();
-}
-
-static void
-HookVsync(const struct hwc_procs* aProcs, int aDisplay,
- int64_t aTimestamp)
-{
- HwcComposer2D::GetInstance()->Vsync(aDisplay, aTimestamp);
-}
-
-static void
-HookHotplug(const struct hwc_procs* aProcs, int aDisplay,
- int aConnected)
-{
- HwcComposer2D::GetInstance()->Hotplug(aDisplay, aConnected);
-}
-
-static StaticRefPtr<HwcComposer2D> sInstance;
-
-HwcComposer2D::HwcComposer2D()
- : mList(nullptr)
- , mMaxLayerCount(0)
- , mColorFill(false)
- , mRBSwapSupport(false)
- , mPrepared(false)
- , mHasHWVsync(false)
- , mLock("mozilla.HwcComposer2D.mLock")
-{
- mHal = HwcHALBase::CreateHwcHAL();
- if (!mHal->HasHwc()) {
- LOGD("no hwc support");
- return;
- }
-
- RegisterHwcEventCallback();
-
- nsIntSize screenSize;
-
- GonkDisplay::NativeData data = GetGonkDisplay()->GetNativeData(GonkDisplay::DISPLAY_PRIMARY);
- ANativeWindow *win = data.mNativeWindow.get();
- win->query(win, NATIVE_WINDOW_WIDTH, &screenSize.width);
- win->query(win, NATIVE_WINDOW_HEIGHT, &screenSize.height);
- mScreenRect = gfx::IntRect(gfx::IntPoint(0, 0), screenSize);
-
- mColorFill = mHal->Query(HwcHALBase::QueryType::COLOR_FILL);
- mRBSwapSupport = mHal->Query(HwcHALBase::QueryType::RB_SWAP);
-}
-
-HwcComposer2D::~HwcComposer2D()
-{
- free(mList);
-}
-
-HwcComposer2D*
-HwcComposer2D::GetInstance()
-{
- if (!sInstance) {
-#ifdef HWC_DEBUG
- // Make sure only create once
- static int timesCreated = 0;
- ++timesCreated;
- MOZ_ASSERT(timesCreated == 1);
-#endif
- LOGI("Creating new instance");
- sInstance = new HwcComposer2D();
-
- // If anyone uses the compositor thread to create HwcComposer2D,
- // we just skip this function.
- // If ClearOnShutdown() can handle objects in other threads
- // in the future, we can remove this check.
- if (NS_IsMainThread()) {
- // If we create HwcComposer2D by the main thread, we can use
- // ClearOnShutdown() to make sure it will be nullified properly.
- ClearOnShutdown(&sInstance);
- }
- }
- return sInstance;
-}
-
-bool
-HwcComposer2D::EnableVsync(bool aEnable)
-{
- MOZ_ASSERT(NS_IsMainThread());
- if (!mHasHWVsync) {
- return false;
- }
- return mHal->EnableVsync(aEnable) && aEnable;
-}
-
-bool
-HwcComposer2D::RegisterHwcEventCallback()
-{
- const HwcHALProcs_t cHWCProcs = {
- &HookInvalidate, // 1st: void (*invalidate)(...)
- &HookVsync, // 2nd: void (*vsync)(...)
- &HookHotplug // 3rd: void (*hotplug)(...)
- };
- mHasHWVsync = mHal->RegisterHwcEventCallback(cHWCProcs);
- return mHasHWVsync;
-}
-
-void
-HwcComposer2D::Vsync(int aDisplay, nsecs_t aVsyncTimestamp)
-{
- // Only support hardware vsync on kitkat, L and up due to inaccurate timings
- // with JellyBean.
-#if (ANDROID_VERSION == 19 || ANDROID_VERSION >= 21)
- TimeStamp vsyncTime = mozilla::TimeStamp::FromSystemTime(aVsyncTimestamp);
- gfxPlatform::GetPlatform()->GetHardwareVsync()->GetGlobalDisplay().NotifyVsync(vsyncTime);
-#else
- // If this device doesn't support vsync, this function should not be used.
- MOZ_ASSERT(false);
-#endif
-}
-
-// Called on the "invalidator" thread (run from HAL).
-void
-HwcComposer2D::Invalidate()
-{
- if (!mHal->HasHwc()) {
- LOGE("HwcComposer2D::Invalidate failed!");
- return;
- }
-
- MutexAutoLock lock(mLock);
- if (mCompositorBridgeParent) {
- mCompositorBridgeParent->ScheduleRenderOnCompositorThread();
- }
-}
-
-namespace {
-class HotplugEvent : public Runnable {
-public:
- HotplugEvent(GonkDisplay::DisplayType aType, bool aConnected)
- : mType(aType)
- , mConnected(aConnected)
- {
- }
-
- NS_IMETHOD Run() override
- {
- RefPtr<nsScreenManagerGonk> screenManager =
- nsScreenManagerGonk::GetInstance();
- if (mConnected) {
- screenManager->AddScreen(mType);
- } else {
- screenManager->RemoveScreen(mType);
- }
- return NS_OK;
- }
-private:
- GonkDisplay::DisplayType mType;
- bool mConnected;
-};
-} // namespace
-
-void
-HwcComposer2D::Hotplug(int aDisplay, int aConnected)
-{
- NS_DispatchToMainThread(new HotplugEvent(GonkDisplay::DISPLAY_EXTERNAL,
- aConnected));
-}
-
-void
-HwcComposer2D::SetCompositorBridgeParent(CompositorBridgeParent* aCompositorBridgeParent)
-{
- MutexAutoLock lock(mLock);
- mCompositorBridgeParent = aCompositorBridgeParent;
-}
-
-bool
-HwcComposer2D::ReallocLayerList()
-{
- int size = sizeof(HwcList) +
- ((mMaxLayerCount + LAYER_COUNT_INCREMENTS) * sizeof(HwcLayer));
-
- HwcList* listrealloc = (HwcList*)realloc(mList, size);
-
- if (!listrealloc) {
- return false;
- }
-
- if (!mList) {
- //first alloc, initialize
- listrealloc->numHwLayers = 0;
- listrealloc->flags = 0;
- }
-
- mList = listrealloc;
- mMaxLayerCount += LAYER_COUNT_INCREMENTS;
- return true;
-}
-
-bool
-HwcComposer2D::PrepareLayerList(Layer* aLayer,
- const nsIntRect& aClip,
- const Matrix& aParentTransform,
- bool aFindSidebandStreams)
-{
- // NB: we fall off this path whenever there are container layers
- // that require intermediate surfaces. That means all the
- // GetEffective*() coordinates are relative to the framebuffer.
-
- bool fillColor = false;
-
- const nsIntRegion visibleRegion = aLayer->GetLocalVisibleRegion().ToUnknownRegion();
- if (visibleRegion.IsEmpty()) {
- return true;
- }
-
- uint8_t opacity = std::min(0xFF, (int)(aLayer->GetEffectiveOpacity() * 256.0));
- if (opacity == 0) {
- LOGD("%s Layer has zero opacity; skipping", aLayer->Name());
- return true;
- }
-
- if (!mHal->SupportTransparency() && opacity < 0xFF && !aFindSidebandStreams) {
- LOGD("%s Layer has planar semitransparency which is unsupported by hwcomposer", aLayer->Name());
- return false;
- }
-
- if (aLayer->GetMaskLayer() && !aFindSidebandStreams) {
- LOGD("%s Layer has MaskLayer which is unsupported by hwcomposer", aLayer->Name());
- return false;
- }
-
- nsIntRect clip;
- nsIntRect layerClip = aLayer->GetLocalClipRect().valueOr(ParentLayerIntRect()).ToUnknownRect();
- nsIntRect* layerClipPtr = aLayer->GetLocalClipRect() ? &layerClip : nullptr;
- if (!HwcUtils::CalculateClipRect(aParentTransform,
- layerClipPtr,
- aClip,
- &clip))
- {
- LOGD("%s Clip rect is empty. Skip layer", aLayer->Name());
- return true;
- }
-
- // HWC supports only the following 2D transformations:
- //
- // Scaling via the sourceCrop and displayFrame in HwcLayer
- // Translation via the sourceCrop and displayFrame in HwcLayer
- // Rotation (in square angles only) via the HWC_TRANSFORM_ROT_* flags
- // Reflection (horizontal and vertical) via the HWC_TRANSFORM_FLIP_* flags
- //
- // A 2D transform with PreservesAxisAlignedRectangles() has all the attributes
- // above
- Matrix layerTransform;
- if (!aLayer->GetEffectiveTransform().Is2D(&layerTransform) ||
- !layerTransform.PreservesAxisAlignedRectangles()) {
- LOGD("Layer EffectiveTransform has a 3D transform or a non-square angle rotation");
- return false;
- }
-
- Matrix layerBufferTransform;
- if (!aLayer->GetEffectiveTransformForBuffer().Is2D(&layerBufferTransform) ||
- !layerBufferTransform.PreservesAxisAlignedRectangles()) {
- LOGD("Layer EffectiveTransformForBuffer has a 3D transform or a non-square angle rotation");
- return false;
- }
-
- if (ContainerLayer* container = aLayer->AsContainerLayer()) {
- if (container->UseIntermediateSurface() && !aFindSidebandStreams) {
- LOGD("Container layer needs intermediate surface");
- return false;
- }
- AutoTArray<Layer*, 12> children;
- container->SortChildrenBy3DZOrder(children);
-
- for (uint32_t i = 0; i < children.Length(); i++) {
- if (!PrepareLayerList(children[i], clip, layerTransform, aFindSidebandStreams) &&
- !aFindSidebandStreams) {
- return false;
- }
- }
- return true;
- }
-
- LayerRenderState state = aLayer->GetRenderState();
-
-#if ANDROID_VERSION >= 21
- if (!state.GetGrallocBuffer() && !state.GetSidebandStream().IsValid()) {
-#else
- if (!state.GetGrallocBuffer()) {
-#endif
- if (aLayer->AsColorLayer() && mColorFill) {
- fillColor = true;
- } else {
- LOGD("%s Layer doesn't have a gralloc buffer", aLayer->Name());
- return false;
- }
- }
-
- nsIntRect visibleRect = visibleRegion.GetBounds();
-
- nsIntRect bufferRect;
- if (fillColor) {
- bufferRect = nsIntRect(visibleRect);
- } else {
- nsIntRect layerRect;
- if (state.mHasOwnOffset) {
- bufferRect = nsIntRect(state.mOffset.x, state.mOffset.y,
- state.mSize.width, state.mSize.height);
- layerRect = bufferRect;
- } else {
- //Since the buffer doesn't have its own offset, assign the whole
- //surface size as its buffer bounds
- bufferRect = nsIntRect(0, 0, state.mSize.width, state.mSize.height);
- layerRect = bufferRect;
- if (aLayer->GetType() == Layer::TYPE_IMAGE) {
- ImageLayer* imageLayer = static_cast<ImageLayer*>(aLayer);
- if(imageLayer->GetScaleMode() != ScaleMode::SCALE_NONE) {
- layerRect = nsIntRect(0, 0, imageLayer->GetScaleToSize().width, imageLayer->GetScaleToSize().height);
- }
- }
- }
- // In some cases the visible rect assigned to the layer can be larger
- // than the layer's surface, e.g., an ImageLayer with a small Image
- // in it.
- visibleRect.IntersectRect(visibleRect, layerRect);
- }
-
- // Buffer rotation is not to be confused with the angled rotation done by a transform matrix
- // It's a fancy PaintedLayer feature used for scrolling
- if (state.BufferRotated()) {
- LOGD("%s Layer has a rotated buffer", aLayer->Name());
- return false;
- }
-
- const bool needsYFlip = state.OriginBottomLeft() ? true
- : false;
-
- hwc_rect_t sourceCrop, displayFrame;
- if(!HwcUtils::PrepareLayerRects(visibleRect,
- layerTransform,
- layerBufferTransform,
- clip,
- bufferRect,
- needsYFlip,
- &(sourceCrop),
- &(displayFrame)))
- {
- return true;
- }
-
- // OK! We can compose this layer with hwc.
- int current = mList ? mList->numHwLayers : 0;
-
- // Do not compose any layer below full-screen Opaque layer
- // Note: It can be generalized to non-fullscreen Opaque layers.
- bool isOpaque = opacity == 0xFF &&
- (state.mFlags & LayerRenderStateFlags::OPAQUE);
- // Currently we perform opacity calculation using the *bounds* of the layer.
- // We can only make this assumption if we're not dealing with a complex visible region.
- bool isSimpleVisibleRegion = visibleRegion.Contains(visibleRect);
- if (current && isOpaque && isSimpleVisibleRegion) {
- nsIntRect displayRect = nsIntRect(displayFrame.left, displayFrame.top,
- displayFrame.right - displayFrame.left, displayFrame.bottom - displayFrame.top);
- if (displayRect.Contains(mScreenRect)) {
- // In z-order, all previous layers are below
- // the current layer. We can ignore them now.
- mList->numHwLayers = current = 0;
- mHwcLayerMap.Clear();
- }
- }
-
- if (!mList || current >= mMaxLayerCount) {
- if (!ReallocLayerList() || current >= mMaxLayerCount) {
- LOGE("PrepareLayerList failed! Could not increase the maximum layer count");
- return false;
- }
- }
-
- HwcLayer& hwcLayer = mList->hwLayers[current];
- hwcLayer.displayFrame = displayFrame;
- mHal->SetCrop(hwcLayer, sourceCrop);
- buffer_handle_t handle = nullptr;
-#if ANDROID_VERSION >= 21
- if (state.GetSidebandStream().IsValid()) {
- handle = state.GetSidebandStream().GetRawNativeHandle();
- } else if (state.GetGrallocBuffer()) {
- handle = state.GetGrallocBuffer()->getNativeBuffer()->handle;
- }
-#else
- if (state.GetGrallocBuffer()) {
- handle = state.GetGrallocBuffer()->getNativeBuffer()->handle;
- }
-#endif
- hwcLayer.handle = handle;
-
- hwcLayer.flags = 0;
- hwcLayer.hints = 0;
- hwcLayer.blending = isOpaque ? HWC_BLENDING_NONE : HWC_BLENDING_PREMULT;
-#if ANDROID_VERSION >= 17
- hwcLayer.compositionType = HWC_FRAMEBUFFER;
-#if ANDROID_VERSION >= 21
- if (state.GetSidebandStream().IsValid()) {
- hwcLayer.compositionType = HWC_SIDEBAND;
- }
-#endif
- hwcLayer.acquireFenceFd = -1;
- hwcLayer.releaseFenceFd = -1;
-#if ANDROID_VERSION >= 18
- hwcLayer.planeAlpha = opacity;
-#endif
-#else
- hwcLayer.compositionType = HwcUtils::HWC_USE_COPYBIT;
-#endif
-
- if (!fillColor) {
- if (state.FormatRBSwapped()) {
- if (!mRBSwapSupport) {
- LOGD("No R/B swap support in H/W Composer");
- return false;
- }
- hwcLayer.flags |= HwcUtils::HWC_FORMAT_RB_SWAP;
- }
-
- // Translation and scaling have been addressed in PrepareLayerRects().
- // Given the above and that we checked for PreservesAxisAlignedRectangles()
- // the only possible transformations left to address are
- // square angle rotation and horizontal/vertical reflection.
- //
- // The rotation and reflection permutations total 16 but can be
- // reduced to 8 transformations after eliminating redundancies.
- //
- // All matrices represented here are in the form
- //
- // | xx xy |
- // | yx yy |
- //
- // And ignore scaling.
- //
- // Reflection is applied before rotation
- gfx::Matrix rotation = layerTransform;
- // Compute fuzzy zero like PreservesAxisAlignedRectangles()
- if (fabs(rotation._11) < 1e-6) {
- if (rotation._21 < 0) {
- if (rotation._12 > 0) {
- // 90 degree rotation
- //
- // | 0 -1 |
- // | 1 0 |
- //
- hwcLayer.transform = HWC_TRANSFORM_ROT_90;
- LOGD("Layer rotated 90 degrees");
- }
- else {
- // Horizontal reflection then 90 degree rotation
- //
- // | 0 -1 | | -1 0 | = | 0 -1 |
- // | 1 0 | | 0 1 | | -1 0 |
- //
- // same as vertical reflection then 270 degree rotation
- //
- // | 0 1 | | 1 0 | = | 0 -1 |
- // | -1 0 | | 0 -1 | | -1 0 |
- //
- hwcLayer.transform = HWC_TRANSFORM_ROT_90 | HWC_TRANSFORM_FLIP_H;
- LOGD("Layer vertically reflected then rotated 270 degrees");
- }
- } else {
- if (rotation._12 < 0) {
- // 270 degree rotation
- //
- // | 0 1 |
- // | -1 0 |
- //
- hwcLayer.transform = HWC_TRANSFORM_ROT_270;
- LOGD("Layer rotated 270 degrees");
- }
- else {
- // Vertical reflection then 90 degree rotation
- //
- // | 0 1 | | -1 0 | = | 0 1 |
- // | -1 0 | | 0 1 | | 1 0 |
- //
- // Same as horizontal reflection then 270 degree rotation
- //
- // | 0 -1 | | 1 0 | = | 0 1 |
- // | 1 0 | | 0 -1 | | 1 0 |
- //
- hwcLayer.transform = HWC_TRANSFORM_ROT_90 | HWC_TRANSFORM_FLIP_V;
- LOGD("Layer horizontally reflected then rotated 270 degrees");
- }
- }
- } else if (rotation._11 < 0) {
- if (rotation._22 > 0) {
- // Horizontal reflection
- //
- // | -1 0 |
- // | 0 1 |
- //
- hwcLayer.transform = HWC_TRANSFORM_FLIP_H;
- LOGD("Layer rotated 180 degrees");
- }
- else {
- // 180 degree rotation
- //
- // | -1 0 |
- // | 0 -1 |
- //
- // Same as horizontal and vertical reflection
- //
- // | -1 0 | | 1 0 | = | -1 0 |
- // | 0 1 | | 0 -1 | | 0 -1 |
- //
- hwcLayer.transform = HWC_TRANSFORM_ROT_180;
- LOGD("Layer rotated 180 degrees");
- }
- } else {
- if (rotation._22 < 0) {
- // Vertical reflection
- //
- // | 1 0 |
- // | 0 -1 |
- //
- hwcLayer.transform = HWC_TRANSFORM_FLIP_V;
- LOGD("Layer rotated 180 degrees");
- }
- else {
- // No rotation or reflection
- //
- // | 1 0 |
- // | 0 1 |
- //
- hwcLayer.transform = 0;
- }
- }
-
- const bool needsYFlip = state.OriginBottomLeft() ? true
- : false;
-
- if (needsYFlip) {
- // Invert vertical reflection flag if it was already set
- hwcLayer.transform ^= HWC_TRANSFORM_FLIP_V;
- }
- hwc_region_t region;
- if (visibleRegion.GetNumRects() > 1) {
- mVisibleRegions.push_back(HwcUtils::RectVector());
- HwcUtils::RectVector* visibleRects = &(mVisibleRegions.back());
- bool isVisible = false;
- if(!HwcUtils::PrepareVisibleRegion(visibleRegion,
- layerTransform,
- layerBufferTransform,
- clip,
- bufferRect,
- visibleRects,
- isVisible)) {
- LOGD("A region of layer is too small to be rendered by HWC");
- return false;
- }
- if (!isVisible) {
- // Layer is not visible, no need to render it
- return true;
- }
- region.numRects = visibleRects->size();
- region.rects = &((*visibleRects)[0]);
- } else {
- region.numRects = 1;
- region.rects = &(hwcLayer.displayFrame);
- }
- hwcLayer.visibleRegionScreen = region;
- } else {
- hwcLayer.flags |= HwcUtils::HWC_COLOR_FILL;
- ColorLayer* colorLayer = aLayer->AsColorLayer();
- if (colorLayer->GetColor().a < 1.0) {
- LOGD("Color layer has semitransparency which is unsupported");
- return false;
- }
- hwcLayer.transform = colorLayer->GetColor().ToABGR();
- }
-
-#if ANDROID_VERSION >= 21
- if (aFindSidebandStreams && hwcLayer.compositionType == HWC_SIDEBAND) {
- mCachedSidebandLayers.AppendElement(hwcLayer);
- }
-#endif
-
- mHwcLayerMap.AppendElement(static_cast<LayerComposite*>(aLayer->ImplData()));
- mList->numHwLayers++;
- return true;
-}
-
-
-#if ANDROID_VERSION >= 17
-bool
-HwcComposer2D::TryHwComposition(nsScreenGonk* aScreen)
-{
- DisplaySurface* dispSurface = aScreen->GetDisplaySurface();
-
- if (!(dispSurface && dispSurface->lastHandle)) {
- LOGD("H/W Composition failed. DispSurface not initialized.");
- return false;
- }
-
- // Add FB layer
- int idx = mList->numHwLayers++;
- if (idx >= mMaxLayerCount) {
- if (!ReallocLayerList() || idx >= mMaxLayerCount) {
- LOGE("TryHwComposition failed! Could not add FB layer");
- return false;
- }
- }
-
- Prepare(dispSurface->lastHandle, -1, aScreen);
-
- /* Possible composition paths, after hwc prepare:
- 1. GPU Composition
- 2. BLIT Composition
- 3. Full OVERLAY Composition
- 4. Partial OVERLAY Composition (GPU + OVERLAY) */
-
- bool gpuComposite = false;
- bool blitComposite = false;
- bool overlayComposite = true;
-
- for (int j=0; j < idx; j++) {
- if (mList->hwLayers[j].compositionType == HWC_FRAMEBUFFER ||
- mList->hwLayers[j].compositionType == HWC_BLIT) {
- // Full OVERLAY composition is not possible on this frame
- // It is either GPU / BLIT / partial OVERLAY composition.
- overlayComposite = false;
- break;
- }
- }
-
- if (!overlayComposite) {
- for (int k=0; k < idx; k++) {
- switch (mList->hwLayers[k].compositionType) {
- case HWC_FRAMEBUFFER:
- gpuComposite = true;
- break;
- case HWC_BLIT:
- blitComposite = true;
- break;
-#if ANDROID_VERSION >= 21
- case HWC_SIDEBAND:
-#endif
- case HWC_OVERLAY: {
- // HWC will compose HWC_OVERLAY layers in partial
- // Overlay Composition, set layer composition flag
- // on mapped LayerComposite to skip GPU composition
- mHwcLayerMap[k]->SetLayerComposited(true);
-
- uint8_t opacity = std::min(0xFF, (int)(mHwcLayerMap[k]->GetLayer()->GetEffectiveOpacity() * 256.0));
- if ((mList->hwLayers[k].hints & HWC_HINT_CLEAR_FB) &&
- (opacity == 0xFF)) {
- // Clear visible rect on FB with transparent pixels.
- hwc_rect_t r = mList->hwLayers[k].displayFrame;
- mHwcLayerMap[k]->SetClearRect(nsIntRect(r.left, r.top,
- r.right - r.left,
- r.bottom - r.top));
- }
- break;
- }
- default:
- break;
- }
- }
-
- if (gpuComposite) {
- // GPU or partial OVERLAY Composition
- return false;
- } else if (blitComposite) {
- // BLIT Composition, flip DispSurface target
- GetGonkDisplay()->UpdateDispSurface(aScreen->GetEGLDisplay(), aScreen->GetEGLSurface());
- DisplaySurface* dispSurface = aScreen->GetDisplaySurface();
- if (!dispSurface) {
- LOGE("H/W Composition failed. NULL DispSurface.");
- return false;
- }
- mList->hwLayers[idx].handle = dispSurface->lastHandle;
- mList->hwLayers[idx].acquireFenceFd = dispSurface->GetPrevDispAcquireFd();
- }
- }
-
- // BLIT or full OVERLAY Composition
- return Commit(aScreen);
-}
-
-bool
-HwcComposer2D::Render(nsIWidget* aWidget)
-{
- nsScreenGonk* screen = static_cast<nsWindow*>(aWidget)->GetScreen();
-
- // HWC module does not exist or mList is not created yet.
- if (!mHal->HasHwc() || !mList) {
- return GetGonkDisplay()->SwapBuffers(screen->GetEGLDisplay(), screen->GetEGLSurface());
- } else if (!mList && !ReallocLayerList()) {
- LOGE("Cannot realloc layer list");
- return false;
- }
-
- DisplaySurface* dispSurface = screen->GetDisplaySurface();
- if (!dispSurface) {
- LOGE("H/W Composition failed. DispSurface not initialized.");
- return false;
- }
-
- if (mPrepared) {
- // No mHwc prepare, if already prepared in current draw cycle
- mList->hwLayers[mList->numHwLayers - 1].handle = dispSurface->lastHandle;
- mList->hwLayers[mList->numHwLayers - 1].acquireFenceFd = dispSurface->GetPrevDispAcquireFd();
- } else {
- // Update screen rect to handle a case that TryRenderWithHwc() is not called.
- mScreenRect = screen->GetNaturalBounds().ToUnknownRect();
-
- mList->flags = HWC_GEOMETRY_CHANGED;
- mList->numHwLayers = 2;
- mList->hwLayers[0].hints = 0;
- mList->hwLayers[0].compositionType = HWC_FRAMEBUFFER;
- mList->hwLayers[0].flags = HWC_SKIP_LAYER;
- mList->hwLayers[0].backgroundColor = {0};
- mList->hwLayers[0].acquireFenceFd = -1;
- mList->hwLayers[0].releaseFenceFd = -1;
- mList->hwLayers[0].displayFrame = {0, 0, mScreenRect.width, mScreenRect.height};
-
-#if ANDROID_VERSION >= 21
- // Prepare layers for sideband streams
- const uint32_t len = mCachedSidebandLayers.Length();
- for (uint32_t i = 0; i < len; ++i) {
- ++mList->numHwLayers;
- mList->hwLayers[i+1] = mCachedSidebandLayers[i];
- }
-#endif
- Prepare(dispSurface->lastHandle, dispSurface->GetPrevDispAcquireFd(), screen);
- }
-
- // GPU or partial HWC Composition
- return Commit(screen);
-}
-
-void
-HwcComposer2D::Prepare(buffer_handle_t dispHandle, int fence, nsScreenGonk* screen)
-{
- if (mPrepared) {
- LOGE("Multiple hwc prepare calls!");
- }
- hwc_rect_t dispRect = {0, 0, mScreenRect.width, mScreenRect.height};
- mHal->Prepare(mList, screen->GetDisplayType(), dispRect, dispHandle, fence);
- mPrepared = true;
-}
-
-bool
-HwcComposer2D::Commit(nsScreenGonk* aScreen)
-{
- for (uint32_t j=0; j < (mList->numHwLayers - 1); j++) {
- mList->hwLayers[j].acquireFenceFd = -1;
- if (mHwcLayerMap.IsEmpty() ||
- (mList->hwLayers[j].compositionType == HWC_FRAMEBUFFER)) {
- continue;
- }
- LayerRenderState state = mHwcLayerMap[j]->GetLayer()->GetRenderState();
- if (!state.mTexture) {
- continue;
- }
- FenceHandle fence = state.mTexture->GetAndResetAcquireFenceHandle();
- if (fence.IsValid()) {
- RefPtr<FenceHandle::FdObj> fdObj = fence.GetAndResetFdObj();
- mList->hwLayers[j].acquireFenceFd = fdObj->GetAndResetFd();
- }
- }
-
- int err = mHal->Set(mList, aScreen->GetDisplayType());
-
- mPrevRetireFence.TransferToAnotherFenceHandle(mPrevDisplayFence);
-
- for (uint32_t j=0; j < (mList->numHwLayers - 1); j++) {
- if (mList->hwLayers[j].releaseFenceFd >= 0) {
- int fd = mList->hwLayers[j].releaseFenceFd;
- mList->hwLayers[j].releaseFenceFd = -1;
- RefPtr<FenceHandle::FdObj> fdObj = new FenceHandle::FdObj(fd);
- FenceHandle fence(fdObj);
-
- LayerRenderState state = mHwcLayerMap[j]->GetLayer()->GetRenderState();
- if (!state.mTexture) {
- continue;
- }
- state.mTexture->SetReleaseFenceHandle(fence);
- }
- }
-
- if (mList->retireFenceFd >= 0) {
- mPrevRetireFence = FenceHandle(new FenceHandle::FdObj(mList->retireFenceFd));
- }
-
- // Set DisplaySurface layer fence
- DisplaySurface* displaySurface = aScreen->GetDisplaySurface();
- displaySurface->setReleaseFenceFd(mList->hwLayers[mList->numHwLayers - 1].releaseFenceFd);
- mList->hwLayers[mList->numHwLayers - 1].releaseFenceFd = -1;
-
- mPrepared = false;
- return !err;
-}
-#else
-bool
-HwcComposer2D::TryHwComposition(nsScreenGonk* aScreen)
-{
- mHal->SetEGLInfo(aScreen->GetEGLDisplay(), aScreen->GetEGLSurface());
- return !mHal->Set(mList, aScreen->GetDisplayType());
-}
-
-bool
-HwcComposer2D::Render(nsIWidget* aWidget)
-{
- nsScreenGonk* screen = static_cast<nsWindow*>(aWidget)->GetScreen();
- return GetGonkDisplay()->SwapBuffers(screen->GetEGLDisplay(), screen->GetEGLSurface());
-}
-#endif
-
-bool
-HwcComposer2D::TryRenderWithHwc(Layer* aRoot,
- nsIWidget* aWidget,
- bool aGeometryChanged,
- bool aHasImageHostOverlays)
-{
- if (!mHal->HasHwc()) {
- return false;
- }
-
- nsScreenGonk* screen = static_cast<nsWindow*>(aWidget)->GetScreen();
-
- if (mList) {
- mList->flags = mHal->GetGeometryChangedFlag(aGeometryChanged);
- mList->numHwLayers = 0;
- mHwcLayerMap.Clear();
- }
-
- if (mPrepared) {
- mHal->ResetHwc();
- mPrepared = false;
- }
-
- // XXX: The clear() below means all rect vectors will be have to be
- // reallocated. We may want to avoid this if possible
- mVisibleRegions.clear();
-
- mScreenRect = screen->GetNaturalBounds().ToUnknownRect();
- MOZ_ASSERT(mHwcLayerMap.IsEmpty());
- mCachedSidebandLayers.Clear();
- if (!PrepareLayerList(aRoot,
- mScreenRect,
- gfx::Matrix(),
- /* aFindSidebandStreams */ false))
- {
- mHwcLayerMap.Clear();
- LOGD("Render aborted. Fallback to GPU Composition");
- if (aHasImageHostOverlays) {
- LOGD("Prepare layers of SidebandStreams");
- // Failed to create a layer list for hwc. But we need the list
- // only for handling sideband streams. Traverse layer tree without
- // some early returns to make sure we can find all the layers.
- // It is the best wrong thing that we can do.
- PrepareLayerList(aRoot,
- mScreenRect,
- gfx::Matrix(),
- /* aFindSidebandStreams */ true);
- // Reset mPrepared to false, since we already fell back to
- // gpu composition.
- mPrepared = false;
- }
- return false;
- }
-
- // Send data to LayerScope for debugging
- SendtoLayerScope();
-
- if (!TryHwComposition(screen)) {
- LOGD("Full HWC Composition failed. Fallback to GPU Composition or partial OVERLAY Composition");
- LayerScope::CleanLayer();
- return false;
- }
-
- LOGD("Frame rendered");
- return true;
-}
-
-void
-HwcComposer2D::SendtoLayerScope()
-{
- if (!LayerScope::CheckSendable()) {
- return;
- }
-
- const int len = mList->numHwLayers;
- for (int i = 0; i < len; ++i) {
- LayerComposite* layer = mHwcLayerMap[i];
- const hwc_rect_t r = mList->hwLayers[i].displayFrame;
- LayerScope::SendLayer(layer, r.right - r.left, r.bottom - r.top);
- }
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/HwcComposer2D.h b/widget/gonk/HwcComposer2D.h
deleted file mode 100644
index 56c1d1ec1..000000000
--- a/widget/gonk/HwcComposer2D.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:set ts=4 sw=4 sts=4 et: */
-/*
- * Copyright (c) 2012, The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef mozilla_HwcComposer2D
-#define mozilla_HwcComposer2D
-
-#include "Composer2D.h"
-#include "hwchal/HwcHALBase.h" // for HwcHAL
-#include "HwcUtils.h" // for RectVector
-#include "Layers.h"
-#include "mozilla/Mutex.h"
-#include "mozilla/layers/FenceUtils.h" // for FenceHandle
-#include "mozilla/UniquePtr.h" // for HwcHAL
-
-#include <vector>
-#include <list>
-
-#include <utils/Timers.h>
-
-class nsScreenGonk;
-
-namespace mozilla {
-
-namespace gl {
- class GLContext;
-}
-
-namespace layers {
-class CompositorBridgeParent;
-class Layer;
-}
-
-/*
- * HwcComposer2D provides a way for gecko to render frames
- * using hwcomposer.h in the AOSP HAL.
- *
- * hwcomposer.h defines an interface for display composition
- * using dedicated hardware. This hardware is usually faster
- * or more power efficient than the GPU. However, in exchange
- * for better performance, generality has to be sacrificed:
- * no 3d transforms, no intermediate surfaces, no special shader effects,
- * and loss of other goodies depending on the platform.
- *
- * In general, when hwc is enabled gecko tries to compose
- * its frames using HwcComposer2D first. Then if HwcComposer2D is
- * unable to compose a frame then it falls back to compose it
- * using the GPU with OpenGL.
- *
- */
-class HwcComposer2D : public mozilla::layers::Composer2D {
-public:
- HwcComposer2D();
- virtual ~HwcComposer2D();
-
- static HwcComposer2D* GetInstance();
-
- // Returns TRUE if the container has been succesfully rendered
- // Returns FALSE if the container cannot be fully rendered
- // by this composer so nothing was rendered at all
- virtual bool TryRenderWithHwc(layers::Layer* aRoot,
- nsIWidget* aWidget,
- bool aGeometryChanged,
- bool aHasImageHostOverlays) override;
-
- virtual bool Render(nsIWidget* aWidget) override;
-
- virtual bool HasHwc() override { return mHal->HasHwc(); }
-
- bool EnableVsync(bool aEnable);
- bool RegisterHwcEventCallback();
- void Vsync(int aDisplay, int64_t aTimestamp);
- void Invalidate();
- void Hotplug(int aDisplay, int aConnected);
- void SetCompositorBridgeParent(layers::CompositorBridgeParent* aCompositorBridgeParent);
-
-private:
- void Reset();
- void Prepare(buffer_handle_t dispHandle, int fence, nsScreenGonk* screen);
- bool Commit(nsScreenGonk* aScreen);
- bool TryHwComposition(nsScreenGonk* aScreen);
- bool ReallocLayerList();
- bool PrepareLayerList(layers::Layer* aContainer, const nsIntRect& aClip,
- const gfx::Matrix& aParentTransform,
- bool aFindSidebandStreams);
- void SendtoLayerScope();
-
- UniquePtr<HwcHALBase> mHal;
- HwcList* mList;
- nsIntRect mScreenRect;
- int mMaxLayerCount;
- bool mColorFill;
- bool mRBSwapSupport;
- //Holds all the dynamically allocated RectVectors needed
- //to render the current frame
- std::list<HwcUtils::RectVector> mVisibleRegions;
- layers::FenceHandle mPrevRetireFence;
- layers::FenceHandle mPrevDisplayFence;
- nsTArray<HwcLayer> mCachedSidebandLayers;
- nsTArray<layers::LayerComposite*> mHwcLayerMap;
- bool mPrepared;
- bool mHasHWVsync;
- layers::CompositorBridgeParent* mCompositorBridgeParent;
- Mutex mLock;
-};
-
-} // namespace mozilla
-
-#endif // mozilla_HwcComposer2D
diff --git a/widget/gonk/HwcUtils.cpp b/widget/gonk/HwcUtils.cpp
deleted file mode 100644
index a8f030f3c..000000000
--- a/widget/gonk/HwcUtils.cpp
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (c) 2013 The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <android/log.h>
-#include "HwcUtils.h"
-#include "gfxUtils.h"
-#include "gfx2DGlue.h"
-
-#define LOG_TAG "HwcUtils"
-
-#if (LOG_NDEBUG == 0)
-#define LOGD(args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, ## args)
-#else
-#define LOGD(args...) ((void)0)
-#endif
-
-#define LOGE(args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, ## args)
-
-
-namespace mozilla {
-
-/* Utility functions for HwcComposer */
-
-
-
-/* static */ bool
-HwcUtils::PrepareLayerRects(nsIntRect aVisible,
- const gfx::Matrix& aLayerTransform,
- const gfx::Matrix& aLayerBufferTransform,
- nsIntRect aClip, nsIntRect aBufferRect,
- bool aYFlipped,
- hwc_rect_t* aSourceCrop, hwc_rect_t* aVisibleRegionScreen) {
-
- gfxMatrix aTransform = gfx::ThebesMatrix(aLayerTransform);
- gfxRect visibleRect(ThebesRect(aVisible));
- gfxRect clip(ThebesRect(aClip));
- gfxRect visibleRectScreen = aTransform.TransformBounds(visibleRect);
- // |clip| is guaranteed to be integer
- visibleRectScreen.IntersectRect(visibleRectScreen, clip);
-
- if (visibleRectScreen.IsEmpty()) {
- return false;
- }
-
- gfxMatrix inverse = gfx::ThebesMatrix(aLayerBufferTransform);
- inverse.Invert();
- gfxRect crop = inverse.TransformBounds(visibleRectScreen);
-
- //clip to buffer size
- crop.IntersectRect(crop, ThebesRect(aBufferRect));
- crop.Round();
-
- if (crop.IsEmpty()) {
- return false;
- }
-
- //propagate buffer clipping back to visible rect
- gfxMatrix layerBufferTransform = gfx::ThebesMatrix(aLayerBufferTransform);
- visibleRectScreen = layerBufferTransform.TransformBounds(crop);
- visibleRectScreen.Round();
-
- // Map from layer space to buffer space
- crop -= aBufferRect.TopLeft();
- if (aYFlipped) {
- crop.y = aBufferRect.height - (crop.y + crop.height);
- }
-
- aSourceCrop->left = crop.x;
- aSourceCrop->top = crop.y;
- aSourceCrop->right = crop.x + crop.width;
- aSourceCrop->bottom = crop.y + crop.height;
-
- aVisibleRegionScreen->left = visibleRectScreen.x;
- aVisibleRegionScreen->top = visibleRectScreen.y;
- aVisibleRegionScreen->right = visibleRectScreen.x + visibleRectScreen.width;
- aVisibleRegionScreen->bottom = visibleRectScreen.y + visibleRectScreen.height;
-
- return true;
-}
-
-/* static */ bool
-HwcUtils::PrepareVisibleRegion(const nsIntRegion& aVisible,
- const gfx::Matrix& aLayerTransform,
- const gfx::Matrix& aLayerBufferTransform,
- nsIntRect aClip, nsIntRect aBufferRect,
- RectVector* aVisibleRegionScreen,
- bool& aIsVisible) {
- const float MIN_SRC_WIDTH = 2.f;
- const float MIN_SRC_HEIGHT = 2.f;
-
- gfxMatrix layerTransform = gfx::ThebesMatrix(aLayerTransform);
- gfxMatrix layerBufferTransform = gfx::ThebesMatrix(aLayerBufferTransform);
- gfxRect bufferRect =
- layerBufferTransform.TransformBounds(ThebesRect(aBufferRect));
- gfxMatrix inverse = gfx::ThebesMatrix(aLayerBufferTransform);
- inverse.Invert();
- aIsVisible = false;
-
- for (auto iter = aVisible.RectIter(); !iter.Done(); iter.Next()) {
- gfxRect screenRect =
- layerTransform.TransformBounds(ThebesRect(iter.Get()));
- screenRect.IntersectRect(screenRect, bufferRect);
- screenRect.IntersectRect(screenRect, ThebesRect(aClip));
- screenRect.Round();
- if (screenRect.IsEmpty()) {
- continue;
- }
-
- hwc_rect_t visibleRectScreen;
- visibleRectScreen.left = screenRect.x;
- visibleRectScreen.top = screenRect.y;
- visibleRectScreen.right = screenRect.XMost();
- visibleRectScreen.bottom = screenRect.YMost();
-
- gfxRect srcCrop = inverse.TransformBounds(screenRect);
- // When src crop is very small, HWC could not render correctly in some cases.
- // See Bug 1169093
- if(srcCrop.Width() < MIN_SRC_WIDTH || srcCrop.Height() < MIN_SRC_HEIGHT) {
- return false;
- }
-
- aVisibleRegionScreen->push_back(visibleRectScreen);
- aIsVisible = true;
- }
-
- return true;
-}
-
-/* static */ bool
-HwcUtils::CalculateClipRect(const gfx::Matrix& transform,
- const nsIntRect* aLayerClip,
- nsIntRect aParentClip, nsIntRect* aRenderClip) {
-
- gfxMatrix aTransform = gfx::ThebesMatrix(transform);
- *aRenderClip = aParentClip;
-
- if (!aLayerClip) {
- return true;
- }
-
- if (aLayerClip->IsEmpty()) {
- return false;
- }
-
- nsIntRect clip = *aLayerClip;
-
- gfxRect r = ThebesRect(clip);
- gfxRect trClip = aTransform.TransformBounds(r);
- trClip.Round();
- gfxUtils::GfxRectToIntRect(trClip, &clip);
-
- aRenderClip->IntersectRect(*aRenderClip, clip);
- return true;
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/HwcUtils.h b/widget/gonk/HwcUtils.h
deleted file mode 100644
index 876ff8e99..000000000
--- a/widget/gonk/HwcUtils.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (c) 2013, The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef mozilla_HwcUtils
-#define mozilla_HwcUtils
-
-#include "Layers.h"
-#include <vector>
-#include "hardware/hwcomposer.h"
-
-namespace mozilla {
-
-namespace gfx {
-class Matrix;
-}
-
-class HwcUtils {
-public:
-
-enum {
- HWC_USE_GPU = HWC_FRAMEBUFFER,
- HWC_USE_OVERLAY = HWC_OVERLAY,
- HWC_USE_COPYBIT
-};
-
-// HWC layer flags
-enum {
- // Draw a solid color rectangle
- // The color should be set on the transform member of the hwc_layer_t struct
- // The expected format is a 32 bit ABGR with 8 bits per component
- HWC_COLOR_FILL = 0x8,
- // Swap the RB pixels of gralloc buffer, like RGBA<->BGRA or RGBX<->BGRX
- // The flag will be set inside LayerRenderState
- HWC_FORMAT_RB_SWAP = 0x40
-};
-
-typedef std::vector<hwc_rect_t> RectVector;
-
-/* Utility functions - implemented in HwcUtils.cpp */
-
-/**
- * Calculates the layer's clipping rectangle
- *
- * @param aTransform Input. A transformation matrix
- * It transforms the clip rect to screen space
- * @param aLayerClip Input. The layer's internal clipping rectangle.
- * This may be NULL which means the layer has no internal clipping
- * The origin is the top-left corner of the layer
- * @param aParentClip Input. The parent layer's rendering clipping rectangle
- * The origin is the top-left corner of the screen
- * @param aRenderClip Output. The layer's rendering clipping rectangle
- * The origin is the top-left corner of the screen
- * @return true if the layer should be rendered.
- * false if the layer can be skipped
- */
-static bool CalculateClipRect(const gfx::Matrix& aTransform,
- const nsIntRect* aLayerClip,
- nsIntRect aParentClip, nsIntRect* aRenderClip);
-
-
-/**
- * Prepares hwc layer visible region required for hwc composition
- *
- * @param aVisible Input. Layer's unclipped visible region
- * The origin is the top-left corner of the layer
- * @param aLayerTransform Input. Layer's transformation matrix
- * It transforms from layer space to screen space
- * @param aLayerBufferTransform Input. Layer buffer's transformation matrix
- * It transforms from layer buffer's space to screen space
- * @param aClip Input. A clipping rectangle.
- * The origin is the top-left corner of the screen
- * @param aBufferRect Input. The layer's buffer bounds
- * The origin is the top-left corner of the layer
- * @param aVisibleRegionScreen Output. Visible region in screen space.
- * The origin is the top-left corner of the screen
- * @param aIsVisible Output. true if region is visible
- * false if region is not visible
- * @return true if region can be rendered by HWC.
- * false if region should not be rendered by HWC
- */
-static bool PrepareVisibleRegion(const nsIntRegion& aVisible,
- const gfx::Matrix& aLayerTransform,
- const gfx::Matrix& aLayerBufferTransform,
- nsIntRect aClip, nsIntRect aBufferRect,
- RectVector* aVisibleRegionScreen,
- bool& aIsVisible);
-
-
-/**
- * Sets hwc layer rectangles required for hwc composition
- *
- * @param aVisible Input. Layer's unclipped visible rectangle
- * The origin is the top-left corner of the layer
- * @param aLayerTransform Input. Layer's transformation matrix
- * It transforms from layer space to screen space
- * @param aLayerBufferTransform Input. Layer buffer's transformation matrix
- * It transforms from layer buffer's space to screen space
- * @param aClip Input. A clipping rectangle.
- * The origin is the top-left corner of the screen
- * @param aBufferRect Input. The layer's buffer bounds
- * The origin is the top-left corner of the layer
- * @param aYFlipped Input. true if the buffer is rendered as Y flipped
- * @param aSurceCrop Output. Area of the source to consider,
- * the origin is the top-left corner of the buffer
- * @param aVisibleRegionScreen Output. Visible region in screen space.
- * The origin is the top-left corner of the screen
- * @return true if the layer should be rendered.
- * false if the layer can be skipped
- */
-static bool PrepareLayerRects(nsIntRect aVisible,
- const gfx::Matrix& aLayerTransform,
- const gfx::Matrix& aLayerBufferTransform,
- nsIntRect aClip, nsIntRect aBufferRect,
- bool aYFlipped,
- hwc_rect_t* aSourceCrop,
- hwc_rect_t* aVisibleRegionScreen);
-
-};
-
-} // namespace mozilla
-
-#endif // mozilla_HwcUtils
diff --git a/widget/gonk/OrientationObserver.cpp b/widget/gonk/OrientationObserver.cpp
deleted file mode 100644
index 9096404cf..000000000
--- a/widget/gonk/OrientationObserver.cpp
+++ /dev/null
@@ -1,332 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=8 et ft=cpp : */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "base/basictypes.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/StaticPtr.h"
-#include "mozilla/Hal.h"
-#include "nsIScreen.h"
-#include "nsIScreenManager.h"
-#include "OrientationObserver.h"
-#include "mozilla/HalSensor.h"
-#include "ProcessOrientation.h"
-#include "nsServiceManagerUtils.h"
-
-using namespace mozilla;
-using namespace dom;
-
-namespace {
-
-struct OrientationMapping {
- uint32_t mScreenRotation;
- ScreenOrientationInternal mDomOrientation;
-};
-
-static OrientationMapping sOrientationMappings[] = {
- {nsIScreen::ROTATION_0_DEG, eScreenOrientation_PortraitPrimary},
- {nsIScreen::ROTATION_180_DEG, eScreenOrientation_PortraitSecondary},
- {nsIScreen::ROTATION_90_DEG, eScreenOrientation_LandscapePrimary},
- {nsIScreen::ROTATION_270_DEG, eScreenOrientation_LandscapeSecondary},
-};
-
-const static uint32_t sDefaultLandscape = 2;
-const static uint32_t sDefaultPortrait = 0;
-
-static uint32_t sOrientationOffset = 0;
-
-static already_AddRefed<nsIScreen>
-GetPrimaryScreen()
-{
- nsCOMPtr<nsIScreenManager> screenMgr =
- do_GetService("@mozilla.org/gfx/screenmanager;1");
- NS_ENSURE_TRUE(screenMgr, nullptr);
-
- nsCOMPtr<nsIScreen> screen;
- screenMgr->GetPrimaryScreen(getter_AddRefs(screen));
- return screen.forget();
-}
-
-static void
-DetectDefaultOrientation()
-{
- nsCOMPtr<nsIScreen> screen = GetPrimaryScreen();
- if (!screen) {
- return;
- }
-
- int32_t left, top, width, height;
- if (NS_FAILED(screen->GetRect(&left, &top, &width, &height))) {
- return;
- }
-
- uint32_t rotation;
- if (NS_FAILED(screen->GetRotation(&rotation))) {
- return;
- }
-
- if (width < height) {
- if (rotation == nsIScreen::ROTATION_0_DEG ||
- rotation == nsIScreen::ROTATION_180_DEG) {
- sOrientationOffset = sDefaultPortrait;
- } else {
- sOrientationOffset = sDefaultLandscape;
- }
- } else {
- if (rotation == nsIScreen::ROTATION_0_DEG ||
- rotation == nsIScreen::ROTATION_180_DEG) {
- sOrientationOffset = sDefaultLandscape;
- } else {
- sOrientationOffset = sDefaultPortrait;
- }
- }
-}
-
-/**
- * Converts DOM orientation to nsIScreen rotation. Portrait and Landscape are
- * treated as PortraitPrimary and LandscapePrimary, respectively, during
- * conversion.
- *
- * @param aOrientation DOM orientation e.g.
- * dom::eScreenOrientation_PortraitPrimary.
- * @param aResult output nsIScreen rotation e.g. nsIScreen::ROTATION_0_DEG.
- * @return NS_OK on success. NS_ILLEGAL_VALUE on failure.
- */
-static nsresult
-ConvertToScreenRotation(ScreenOrientationInternal aOrientation, uint32_t *aResult)
-{
- for (uint32_t i = 0; i < ArrayLength(sOrientationMappings); i++) {
- if (aOrientation & sOrientationMappings[i].mDomOrientation) {
- // Shift the mappings in sOrientationMappings so devices with default
- // landscape orientation map landscape-primary to 0 degree and so forth.
- int adjusted = (i + sOrientationOffset) %
- ArrayLength(sOrientationMappings);
- *aResult = sOrientationMappings[adjusted].mScreenRotation;
- return NS_OK;
- }
- }
-
- *aResult = nsIScreen::ROTATION_0_DEG;
- return NS_ERROR_ILLEGAL_VALUE;
-}
-
-/**
- * Converts nsIScreen rotation to DOM orientation.
- *
- * @param aRotation nsIScreen rotation e.g. nsIScreen::ROTATION_0_DEG.
- * @param aResult output DOM orientation e.g.
- * dom::eScreenOrientation_PortraitPrimary.
- * @return NS_OK on success. NS_ILLEGAL_VALUE on failure.
- */
-nsresult
-ConvertToDomOrientation(uint32_t aRotation, ScreenOrientationInternal *aResult)
-{
- for (uint32_t i = 0; i < ArrayLength(sOrientationMappings); i++) {
- if (aRotation == sOrientationMappings[i].mScreenRotation) {
- // Shift the mappings in sOrientationMappings so devices with default
- // landscape orientation map 0 degree to landscape-primary and so forth.
- int adjusted = (i + sOrientationOffset) %
- ArrayLength(sOrientationMappings);
- *aResult = sOrientationMappings[adjusted].mDomOrientation;
- return NS_OK;
- }
- }
-
- *aResult = eScreenOrientation_None;
- return NS_ERROR_ILLEGAL_VALUE;
-}
-
-// Note that all operations with sOrientationSensorObserver
-// should be on the main thread.
-static StaticAutoPtr<OrientationObserver> sOrientationSensorObserver;
-
-} // namespace
-
-OrientationObserver*
-OrientationObserver::GetInstance()
-{
- if (!sOrientationSensorObserver) {
- sOrientationSensorObserver = new OrientationObserver();
- ClearOnShutdown(&sOrientationSensorObserver);
- }
-
- return sOrientationSensorObserver;
-}
-
-OrientationObserver::OrientationObserver()
- : mAutoOrientationEnabled(false)
- , mAllowedOrientations(sDefaultOrientations)
- , mOrientation(new mozilla::ProcessOrientation())
-{
- DetectDefaultOrientation();
-
- EnableAutoOrientation();
-}
-
-OrientationObserver::~OrientationObserver()
-{
- if (mAutoOrientationEnabled) {
- DisableAutoOrientation();
- }
-}
-
-/* static */ void
-OrientationObserver::ShutDown()
-{
- if (!sOrientationSensorObserver) {
- return;
- }
-
- if (sOrientationSensorObserver->mAutoOrientationEnabled) {
- sOrientationSensorObserver->DisableAutoOrientation();
- }
-}
-
-void
-OrientationObserver::Notify(const hal::SensorData& aSensorData)
-{
- // Sensor will call us on the main thread.
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(aSensorData.sensor() == hal::SensorType::SENSOR_ACCELERATION);
-
- nsCOMPtr<nsIScreen> screen = GetPrimaryScreen();
- if (!screen) {
- return;
- }
-
- uint32_t currRotation;
- if(NS_FAILED(screen->GetRotation(&currRotation))) {
- return;
- }
-
- int rotation = mOrientation->OnSensorChanged(aSensorData, static_cast<int>(currRotation));
- if (rotation < 0 || uint32_t(rotation) == currRotation) {
- return;
- }
-
- ScreenOrientationInternal orientation;
- if (NS_FAILED(ConvertToDomOrientation(rotation, &orientation))) {
- return;
- }
-
- if ((mAllowedOrientations & orientation) == eScreenOrientation_None) {
- // The orientation from sensor is not allowed.
- return;
- }
-
- if (NS_FAILED(screen->SetRotation(static_cast<uint32_t>(rotation)))) {
- // Don't notify dom on rotation failure.
- return;
- }
-}
-
-/**
- * Register the observer. Note that the observer shouldn't be registered.
- */
-void
-OrientationObserver::EnableAutoOrientation()
-{
- MOZ_ASSERT(NS_IsMainThread() && !mAutoOrientationEnabled);
-
- mOrientation->Reset();
- hal::RegisterSensorObserver(hal::SENSOR_ACCELERATION, this);
- mAutoOrientationEnabled = true;
-}
-
-/**
- * Unregister the observer. Note that the observer should already be registered.
- */
-void
-OrientationObserver::DisableAutoOrientation()
-{
- MOZ_ASSERT(NS_IsMainThread() && mAutoOrientationEnabled);
-
- hal::UnregisterSensorObserver(hal::SENSOR_ACCELERATION, this);
- mAutoOrientationEnabled = false;
-}
-
-bool
-OrientationObserver::LockScreenOrientation(ScreenOrientationInternal aOrientation)
-{
- MOZ_ASSERT(aOrientation | (eScreenOrientation_PortraitPrimary |
- eScreenOrientation_PortraitSecondary |
- eScreenOrientation_LandscapePrimary |
- eScreenOrientation_LandscapeSecondary |
- eScreenOrientation_Default));
-
- if (aOrientation == eScreenOrientation_Default) {
- aOrientation = (sOrientationOffset == sDefaultPortrait) ?
- eScreenOrientation_PortraitPrimary :
- eScreenOrientation_LandscapePrimary;
- }
-
- // If there are multiple orientations allowed, we should enable the
- // auto-rotation.
- if (aOrientation != eScreenOrientation_LandscapePrimary &&
- aOrientation != eScreenOrientation_LandscapeSecondary &&
- aOrientation != eScreenOrientation_PortraitPrimary &&
- aOrientation != eScreenOrientation_PortraitSecondary) {
- if (!mAutoOrientationEnabled) {
- EnableAutoOrientation();
- }
- } else if (mAutoOrientationEnabled) {
- DisableAutoOrientation();
- }
-
- mAllowedOrientations = aOrientation;
-
- nsCOMPtr<nsIScreen> screen = GetPrimaryScreen();
- NS_ENSURE_TRUE(screen, false);
-
- uint32_t currRotation;
- nsresult rv = screen->GetRotation(&currRotation);
- NS_ENSURE_SUCCESS(rv, false);
-
- ScreenOrientationInternal currOrientation = eScreenOrientation_None;
- rv = ConvertToDomOrientation(currRotation, &currOrientation);
- NS_ENSURE_SUCCESS(rv, false);
-
- // Don't rotate if the current orientation matches one of the
- // requested orientations.
- if (currOrientation & aOrientation) {
- return true;
- }
-
- // Return false on invalid orientation value.
- uint32_t rotation;
- rv = ConvertToScreenRotation(aOrientation, &rotation);
- NS_ENSURE_SUCCESS(rv, false);
-
- rv = screen->SetRotation(rotation);
- NS_ENSURE_SUCCESS(rv, false);
-
- // This conversion will disambiguate aOrientation.
- ScreenOrientationInternal orientation;
- rv = ConvertToDomOrientation(rotation, &orientation);
- NS_ENSURE_SUCCESS(rv, false);
-
- return true;
-}
-
-void
-OrientationObserver::UnlockScreenOrientation()
-{
- if (!mAutoOrientationEnabled) {
- EnableAutoOrientation();
- }
-
- mAllowedOrientations = sDefaultOrientations;
-}
diff --git a/widget/gonk/OrientationObserver.h b/widget/gonk/OrientationObserver.h
deleted file mode 100644
index c841ea878..000000000
--- a/widget/gonk/OrientationObserver.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim: set sw=2 ts=8 et ft=cpp : */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef OrientationObserver_h
-#define OrientationObserver_h
-
-#include "mozilla/Observer.h"
-#include "mozilla/dom/ScreenOrientation.h"
-#include "mozilla/UniquePtr.h"
-
-namespace mozilla {
-class ProcessOrientation;
-namespace hal {
-class SensorData;
-typedef mozilla::Observer<SensorData> ISensorObserver;
-} // namespace hal
-} // namespace mozilla
-
-using mozilla::hal::ISensorObserver;
-using mozilla::hal::SensorData;
-using mozilla::dom::ScreenOrientationInternal;
-
-class OrientationObserver : public ISensorObserver {
-public:
- OrientationObserver();
- ~OrientationObserver();
-
- // Call DisableAutoOrientation on the existing OrientatiOnobserver singleton,
- // if it exists. If no OrientationObserver exists, do nothing.
- static void ShutDown();
-
- // Notification from sensor.
- void Notify(const SensorData& aSensorData);
-
- // Methods to enable/disable automatic orientation.
- void EnableAutoOrientation();
- void DisableAutoOrientation();
-
- // Methods called by methods in hal_impl namespace.
- bool LockScreenOrientation(ScreenOrientationInternal aOrientation);
- void UnlockScreenOrientation();
-
- static OrientationObserver* GetInstance();
-
-private:
- bool mAutoOrientationEnabled;
- uint32_t mAllowedOrientations;
- mozilla::UniquePtr<mozilla::ProcessOrientation> mOrientation;
-
- static const uint32_t sDefaultOrientations =
- mozilla::dom::eScreenOrientation_PortraitPrimary |
- mozilla::dom::eScreenOrientation_PortraitSecondary |
- mozilla::dom::eScreenOrientation_LandscapePrimary |
- mozilla::dom::eScreenOrientation_LandscapeSecondary;
-};
-
-#endif
diff --git a/widget/gonk/ProcessOrientation.cpp b/widget/gonk/ProcessOrientation.cpp
deleted file mode 100644
index bbdcface8..000000000
--- a/widget/gonk/ProcessOrientation.cpp
+++ /dev/null
@@ -1,519 +0,0 @@
-/*
- * Copyright (c) 2013, Linux Foundation. All rights reserved
- *
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "base/basictypes.h"
-#include "mozilla/Hal.h"
-#include "mozilla/Unused.h"
-#include "nsIScreen.h"
-#include "nsIScreenManager.h"
-#include "OrientationObserver.h"
-#include "ProcessOrientation.h"
-#include "mozilla/HalSensor.h"
-#include "math.h"
-#include "limits.h"
-#include "android/log.h"
-
-#if 0
-#define LOGD(args...) __android_log_print(ANDROID_LOG_DEBUG, "ProcessOrientation" , ## args)
-#else
-#define LOGD(args...)
-#endif
-
-namespace mozilla {
-
-// We work with all angles in degrees in this class.
-#define RADIANS_TO_DEGREES (180/M_PI)
-
-// Number of nanoseconds per millisecond.
-#define NANOS_PER_MS 1000000
-
-// Indices into SensorEvent.values for the accelerometer sensor.
-#define ACCELEROMETER_DATA_X 0
-#define ACCELEROMETER_DATA_Y 1
-#define ACCELEROMETER_DATA_Z 2
-
-// The minimum amount of time that a predicted rotation must be stable before
-// it is accepted as a valid rotation proposal. This value can be quite small
-// because the low-pass filter already suppresses most of the noise so we're
-// really just looking for quick confirmation that the last few samples are in
-// agreement as to the desired orientation.
-#define PROPOSAL_SETTLE_TIME_NANOS (40*NANOS_PER_MS)
-
-// The minimum amount of time that must have elapsed since the device last
-// exited the flat state (time since it was picked up) before the proposed
-// rotation can change.
-#define PROPOSAL_MIN_TIME_SINCE_FLAT_ENDED_NANOS (500*NANOS_PER_MS)
-
-// The minimum amount of time that must have elapsed since the device stopped
-// swinging (time since device appeared to be in the process of being put down
-// or put away into a pocket) before the proposed rotation can change.
-#define PROPOSAL_MIN_TIME_SINCE_SWING_ENDED_NANOS (300*NANOS_PER_MS)
-
-// The minimum amount of time that must have elapsed since the device stopped
-// undergoing external acceleration before the proposed rotation can change.
-#define PROPOSAL_MIN_TIME_SINCE_ACCELERATION_ENDED_NANOS (500*NANOS_PER_MS)
-
-// If the tilt angle remains greater than the specified angle for a minimum of
-// the specified time, then the device is deemed to be lying flat
-// (just chillin' on a table).
-#define FLAT_ANGLE 75
-#define FLAT_TIME_NANOS (1000*NANOS_PER_MS)
-
-// If the tilt angle has increased by at least delta degrees within the
-// specified amount of time, then the device is deemed to be swinging away
-// from the user down towards flat (tilt = 90).
-#define SWING_AWAY_ANGLE_DELTA 20
-#define SWING_TIME_NANOS (300*NANOS_PER_MS)
-
-// The maximum sample inter-arrival time in milliseconds. If the acceleration
-// samples are further apart than this amount in time, we reset the state of
-// the low-pass filter and orientation properties. This helps to handle
-// boundary conditions when the device is turned on, wakes from suspend or
-// there is a significant gap in samples.
-#define MAX_FILTER_DELTA_TIME_NANOS (1000*NANOS_PER_MS)
-
-// The acceleration filter time constant.
-//
-// This time constant is used to tune the acceleration filter such that
-// impulses and vibrational noise (think car dock) is suppressed before we try
-// to calculate the tilt and orientation angles.
-//
-// The filter time constant is related to the filter cutoff frequency, which
-// is the frequency at which signals are attenuated by 3dB (half the passband
-// power). Each successive octave beyond this frequency is attenuated by an
-// additional 6dB.
-//
-// Given a time constant t in seconds, the filter cutoff frequency Fc in Hertz
-// is given by Fc = 1 / (2pi * t).
-//
-// The higher the time constant, the lower the cutoff frequency, so more noise
-// will be suppressed.
-//
-// Filtering adds latency proportional the time constant (inversely
-// proportional to the cutoff frequency) so we don't want to make the time
-// constant too large or we can lose responsiveness. Likewise we don't want
-// to make it too small or we do a poor job suppressing acceleration spikes.
-// Empirically, 100ms seems to be too small and 500ms is too large. Android
-// default is 200.
-#define FILTER_TIME_CONSTANT_MS 200.0f
-
-// State for orientation detection. Thresholds for minimum and maximum
-// allowable deviation from gravity.
-//
-// If the device is undergoing external acceleration (being bumped, in a car
-// that is turning around a corner or a plane taking off) then the magnitude
-// may be substantially more or less than gravity. This can skew our
-// orientation detection by making us think that up is pointed in a different
-// direction.
-//
-// Conversely, if the device is in freefall, then there will be no gravity to
-// measure at all. This is problematic because we cannot detect the orientation
-// without gravity to tell us which way is up. A magnitude near 0 produces
-// singularities in the tilt and orientation calculations.
-//
-// In both cases, we postpone choosing an orientation.
-//
-// However, we need to tolerate some acceleration because the angular momentum
-// of turning the device can skew the observed acceleration for a short period
-// of time.
-#define NEAR_ZERO_MAGNITUDE 1 // m/s^2
-#define ACCELERATION_TOLERANCE 4 // m/s^2
-#define STANDARD_GRAVITY 9.80665f
-#define MIN_ACCELERATION_MAGNITUDE (STANDARD_GRAVITY-ACCELERATION_TOLERANCE)
-#define MAX_ACCELERATION_MAGNITUDE (STANDARD_GRAVITY+ACCELERATION_TOLERANCE)
-
-// Maximum absolute tilt angle at which to consider orientation data. Beyond
-// this (i.e. when screen is facing the sky or ground), we completely ignore
-// orientation data.
-#define MAX_TILT 75
-
-// The gap angle in degrees between adjacent orientation angles for
-// hysteresis.This creates a "dead zone" between the current orientation and a
-// proposed adjacent orientation. No orientation proposal is made when the
-// orientation angle is within the gap between the current orientation and the
-// adjacent orientation.
-#define ADJACENT_ORIENTATION_ANGLE_GAP 45
-
-const int
-ProcessOrientation::tiltTolerance[][4] = {
- {-25, 70}, // ROTATION_0
- {-25, 65}, // ROTATION_90
- {-25, 60}, // ROTATION_180
- {-25, 65} // ROTATION_270
-};
-
-int
-ProcessOrientation::GetProposedRotation()
-{
- return mProposedRotation;
-}
-
-int
-ProcessOrientation::OnSensorChanged(const SensorData& event,
- int deviceCurrentRotation)
-{
- // The vector given in the SensorEvent points straight up (towards the sky)
- // under ideal conditions (the phone is not accelerating). I'll call this up
- // vector elsewhere.
- const InfallibleTArray<float>& values = event.values();
- float x = values[ACCELEROMETER_DATA_X];
- float y = values[ACCELEROMETER_DATA_Y];
- float z = values[ACCELEROMETER_DATA_Z];
-
- LOGD
- ("ProcessOrientation: Raw acceleration vector: x = %f, y = %f, z = %f,"
- "magnitude = %f\n", x, y, z, sqrt(x * x + y * y + z * z));
- // Apply a low-pass filter to the acceleration up vector in cartesian space.
- // Reset the orientation listener state if the samples are too far apart in
- // time or when we see values of (0, 0, 0) which indicates that we polled the
- // accelerometer too soon after turning it on and we don't have any data yet.
- const int64_t now = (int64_t) event.timestamp();
- const int64_t then = mLastFilteredTimestampNanos;
- const float timeDeltaMS = (now - then) * 0.000001f;
- bool skipSample = false;
- if (now < then
- || now > then + MAX_FILTER_DELTA_TIME_NANOS
- || (x == 0 && y == 0 && z == 0)) {
- LOGD
- ("ProcessOrientation: Resetting orientation listener.");
- Reset();
- skipSample = true;
- } else {
- const float alpha = timeDeltaMS / (FILTER_TIME_CONSTANT_MS + timeDeltaMS);
- x = alpha * (x - mLastFilteredX) + mLastFilteredX;
- y = alpha * (y - mLastFilteredY) + mLastFilteredY;
- z = alpha * (z - mLastFilteredZ) + mLastFilteredZ;
- LOGD
- ("ProcessOrientation: Filtered acceleration vector: x=%f, y=%f, z=%f,"
- "magnitude=%f", z, y, z, sqrt(x * x + y * y + z * z));
- skipSample = false;
- }
- mLastFilteredTimestampNanos = now;
- mLastFilteredX = x;
- mLastFilteredY = y;
- mLastFilteredZ = z;
-
- bool isAccelerating = false;
- bool isFlat = false;
- bool isSwinging = false;
- if (skipSample) {
- return -1;
- }
-
- // Calculate the magnitude of the acceleration vector.
- const float magnitude = sqrt(x * x + y * y + z * z);
- if (magnitude < NEAR_ZERO_MAGNITUDE) {
- LOGD
- ("ProcessOrientation: Ignoring sensor data, magnitude too close to"
- " zero.");
- ClearPredictedRotation();
- } else {
- // Determine whether the device appears to be undergoing external
- // acceleration.
- if (this->IsAccelerating(magnitude)) {
- isAccelerating = true;
- mAccelerationTimestampNanos = now;
- }
- // Calculate the tilt angle. This is the angle between the up vector and
- // the x-y plane (the plane of the screen) in a range of [-90, 90]
- // degrees.
- // -90 degrees: screen horizontal and facing the ground (overhead)
- // 0 degrees: screen vertical
- // 90 degrees: screen horizontal and facing the sky (on table)
- const int tiltAngle =
- static_cast<int>(roundf(asin(z / magnitude) * RADIANS_TO_DEGREES));
- AddTiltHistoryEntry(now, tiltAngle);
-
- // Determine whether the device appears to be flat or swinging.
- if (this->IsFlat(now)) {
- isFlat = true;
- mFlatTimestampNanos = now;
- }
- if (this->IsSwinging(now, tiltAngle)) {
- isSwinging = true;
- mSwingTimestampNanos = now;
- }
- // If the tilt angle is too close to horizontal then we cannot determine
- // the orientation angle of the screen.
- if (abs(tiltAngle) > MAX_TILT) {
- LOGD
- ("ProcessOrientation: Ignoring sensor data, tilt angle too high:"
- " tiltAngle=%d", tiltAngle);
- ClearPredictedRotation();
- } else {
- // Calculate the orientation angle.
- // This is the angle between the x-y projection of the up vector onto
- // the +y-axis, increasing clockwise in a range of [0, 360] degrees.
- int orientationAngle =
- static_cast<int>(roundf(-atan2f(-x, y) * RADIANS_TO_DEGREES));
- if (orientationAngle < 0) {
- // atan2 returns [-180, 180]; normalize to [0, 360]
- orientationAngle += 360;
- }
- // Find the nearest rotation.
- int nearestRotation = (orientationAngle + 45) / 90;
- if (nearestRotation == 4) {
- nearestRotation = 0;
- }
- // Determine the predicted orientation.
- if (IsTiltAngleAcceptable(nearestRotation, tiltAngle)
- &&
- IsOrientationAngleAcceptable
- (nearestRotation, orientationAngle, deviceCurrentRotation)) {
- UpdatePredictedRotation(now, nearestRotation);
- LOGD
- ("ProcessOrientation: Predicted: tiltAngle=%d, orientationAngle=%d,"
- " predictedRotation=%d, predictedRotationAgeMS=%f",
- tiltAngle,
- orientationAngle,
- mPredictedRotation,
- ((now - mPredictedRotationTimestampNanos) * 0.000001f));
- } else {
- LOGD
- ("ProcessOrientation: Ignoring sensor data, no predicted rotation:"
- " tiltAngle=%d, orientationAngle=%d",
- tiltAngle,
- orientationAngle);
- ClearPredictedRotation();
- }
- }
- }
-
- // Determine new proposed rotation.
- const int oldProposedRotation = mProposedRotation;
- if (mPredictedRotation < 0 || IsPredictedRotationAcceptable(now)) {
- mProposedRotation = mPredictedRotation;
- }
- // Write final statistics about where we are in the orientation detection
- // process.
- LOGD
- ("ProcessOrientation: Result: oldProposedRotation=%d,currentRotation=%d, "
- "proposedRotation=%d, predictedRotation=%d, timeDeltaMS=%f, "
- "isAccelerating=%d, isFlat=%d, isSwinging=%d, timeUntilSettledMS=%f, "
- "timeUntilAccelerationDelayExpiredMS=%f, timeUntilFlatDelayExpiredMS=%f, "
- "timeUntilSwingDelayExpiredMS=%f",
- oldProposedRotation,
- deviceCurrentRotation, mProposedRotation,
- mPredictedRotation, timeDeltaMS, isAccelerating, isFlat,
- isSwinging, RemainingMS(now,
- mPredictedRotationTimestampNanos +
- PROPOSAL_SETTLE_TIME_NANOS),
- RemainingMS(now,
- mAccelerationTimestampNanos +
- PROPOSAL_MIN_TIME_SINCE_ACCELERATION_ENDED_NANOS),
- RemainingMS(now,
- mFlatTimestampNanos +
- PROPOSAL_MIN_TIME_SINCE_FLAT_ENDED_NANOS),
- RemainingMS(now,
- mSwingTimestampNanos +
- PROPOSAL_MIN_TIME_SINCE_SWING_ENDED_NANOS));
-
- // Avoid unused-but-set compile warnings for these variables, when LOGD is
- // a no-op, as it is by default:
- Unused << isAccelerating;
- Unused << isFlat;
- Unused << isSwinging;
-
- // Tell the listener.
- if (mProposedRotation != oldProposedRotation && mProposedRotation >= 0) {
- LOGD
- ("ProcessOrientation: Proposed rotation changed! proposedRotation=%d, "
- "oldProposedRotation=%d",
- mProposedRotation,
- oldProposedRotation);
- return mProposedRotation;
- }
- // Don't rotate screen
- return -1;
-}
-
-bool
-ProcessOrientation::IsTiltAngleAcceptable(int rotation, int tiltAngle)
-{
- return (tiltAngle >= tiltTolerance[rotation][0]
- && tiltAngle <= tiltTolerance[rotation][1]);
-}
-
-bool
-ProcessOrientation::IsOrientationAngleAcceptable(int rotation,
- int orientationAngle,
- int currentRotation)
-{
- // If there is no current rotation, then there is no gap.
- // The gap is used only to introduce hysteresis among advertised orientation
- // changes to avoid flapping.
- if (currentRotation < 0) {
- return true;
- }
- // If the specified rotation is the same or is counter-clockwise adjacent
- // to the current rotation, then we set a lower bound on the orientation
- // angle. For example, if currentRotation is ROTATION_0 and proposed is
- // ROTATION_90, then we want to check orientationAngle > 45 + GAP / 2.
- if (rotation == currentRotation || rotation == (currentRotation + 1) % 4) {
- int lowerBound = rotation * 90 - 45 + ADJACENT_ORIENTATION_ANGLE_GAP / 2;
- if (rotation == 0) {
- if (orientationAngle >= 315 && orientationAngle < lowerBound + 360) {
- return false;
- }
- } else {
- if (orientationAngle < lowerBound) {
- return false;
- }
- }
- }
- // If the specified rotation is the same or is clockwise adjacent, then we
- // set an upper bound on the orientation angle. For example, if
- // currentRotation is ROTATION_0 and rotation is ROTATION_270, then we want
- // to check orientationAngle < 315 - GAP / 2.
- if (rotation == currentRotation || rotation == (currentRotation + 3) % 4) {
- int upperBound = rotation * 90 + 45 - ADJACENT_ORIENTATION_ANGLE_GAP / 2;
- if (rotation == 0) {
- if (orientationAngle <= 45 && orientationAngle > upperBound) {
- return false;
- }
- } else {
- if (orientationAngle > upperBound) {
- return false;
- }
- }
- }
- return true;
-}
-
-bool
-ProcessOrientation::IsPredictedRotationAcceptable(int64_t now)
-{
- // The predicted rotation must have settled long enough.
- if (now < mPredictedRotationTimestampNanos + PROPOSAL_SETTLE_TIME_NANOS) {
- return false;
- }
- // The last flat state (time since picked up) must have been sufficiently long
- // ago.
- if (now < mFlatTimestampNanos + PROPOSAL_MIN_TIME_SINCE_FLAT_ENDED_NANOS) {
- return false;
- }
- // The last swing state (time since last movement to put down) must have been
- // sufficiently long ago.
- if (now < mSwingTimestampNanos + PROPOSAL_MIN_TIME_SINCE_SWING_ENDED_NANOS) {
- return false;
- }
- // The last acceleration state must have been sufficiently long ago.
- if (now < mAccelerationTimestampNanos
- + PROPOSAL_MIN_TIME_SINCE_ACCELERATION_ENDED_NANOS) {
- return false;
- }
- // Looks good!
- return true;
-}
-
-int
-ProcessOrientation::Reset()
-{
- mLastFilteredTimestampNanos = std::numeric_limits<int64_t>::min();
- mProposedRotation = -1;
- mFlatTimestampNanos = std::numeric_limits<int64_t>::min();
- mSwingTimestampNanos = std::numeric_limits<int64_t>::min();
- mAccelerationTimestampNanos = std::numeric_limits<int64_t>::min();
- ClearPredictedRotation();
- ClearTiltHistory();
- return -1;
-}
-
-void
-ProcessOrientation::ClearPredictedRotation()
-{
- mPredictedRotation = -1;
- mPredictedRotationTimestampNanos = std::numeric_limits<int64_t>::min();
-}
-
-void
-ProcessOrientation::UpdatePredictedRotation(int64_t now, int rotation)
-{
- if (mPredictedRotation != rotation) {
- mPredictedRotation = rotation;
- mPredictedRotationTimestampNanos = now;
- }
-}
-
-bool
-ProcessOrientation::IsAccelerating(float magnitude)
-{
- return magnitude < MIN_ACCELERATION_MAGNITUDE
- || magnitude > MAX_ACCELERATION_MAGNITUDE;
-}
-
-void
-ProcessOrientation::ClearTiltHistory()
-{
- mTiltHistory.history[0].timestampNanos = std::numeric_limits<int64_t>::min();
- mTiltHistory.index = 1;
-}
-
-void
-ProcessOrientation::AddTiltHistoryEntry(int64_t now, float tilt)
-{
- mTiltHistory.history[mTiltHistory.index].tiltAngle = tilt;
- mTiltHistory.history[mTiltHistory.index].timestampNanos = now;
- mTiltHistory.index = (mTiltHistory.index + 1) % TILT_HISTORY_SIZE;
- mTiltHistory.history[mTiltHistory.index].timestampNanos = std::numeric_limits<int64_t>::min();
-}
-
-bool
-ProcessOrientation::IsFlat(int64_t now)
-{
- for (int i = mTiltHistory.index; (i = NextTiltHistoryIndex(i)) >= 0;) {
- if (mTiltHistory.history[i].tiltAngle < FLAT_ANGLE) {
- break;
- }
- if (mTiltHistory.history[i].timestampNanos + FLAT_TIME_NANOS <= now) {
- // Tilt has remained greater than FLAT_TILT_ANGLE for FLAT_TIME_NANOS.
- return true;
- }
- }
- return false;
-}
-
-bool
-ProcessOrientation::IsSwinging(int64_t now, float tilt)
-{
- for (int i = mTiltHistory.index; (i = NextTiltHistoryIndex(i)) >= 0;) {
- if (mTiltHistory.history[i].timestampNanos + SWING_TIME_NANOS < now) {
- break;
- }
- if (mTiltHistory.history[i].tiltAngle + SWING_AWAY_ANGLE_DELTA <= tilt) {
- // Tilted away by SWING_AWAY_ANGLE_DELTA within SWING_TIME_NANOS.
- return true;
- }
- }
- return false;
-}
-
-int
-ProcessOrientation::NextTiltHistoryIndex(int index)
-{
- index = (index == 0 ? TILT_HISTORY_SIZE : index) - 1;
- return mTiltHistory.history[index].timestampNanos != std::numeric_limits<int64_t>::min() ? index : -1;
-}
-
-float
-ProcessOrientation::RemainingMS(int64_t now, int64_t until)
-{
- return now >= until ? 0 : (until - now) * 0.000001f;
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/ProcessOrientation.h b/widget/gonk/ProcessOrientation.h
deleted file mode 100644
index d6d4bc3b6..000000000
--- a/widget/gonk/ProcessOrientation.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (c) 2013, Linux Foundation. All rights reserved
- *
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ProcessOrientation_h
-#define ProcessOrientation_h
-
-#include "mozilla/Hal.h"
-
-namespace mozilla {
-
-// History of observed tilt angles.
-#define TILT_HISTORY_SIZE 40
-
-class ProcessOrientation {
-public:
- ProcessOrientation() {};
- ~ProcessOrientation() {};
-
- int OnSensorChanged(const mozilla::hal::SensorData& event, int deviceCurrentRotation);
- int Reset();
-
-private:
- int GetProposedRotation();
-
- // Returns true if the tilt angle is acceptable for a given predicted
- // rotation.
- bool IsTiltAngleAcceptable(int rotation, int tiltAngle);
-
- // Returns true if the orientation angle is acceptable for a given predicted
- // rotation. This function takes into account the gap between adjacent
- // orientations for hysteresis.
- bool IsOrientationAngleAcceptable(int rotation, int orientationAngle,
- int currentRotation);
-
- // Returns true if the predicted rotation is ready to be advertised as a
- // proposed rotation.
- bool IsPredictedRotationAcceptable(int64_t now);
-
- void ClearPredictedRotation();
- void UpdatePredictedRotation(int64_t now, int rotation);
- bool IsAccelerating(float magnitude);
- void ClearTiltHistory();
- void AddTiltHistoryEntry(int64_t now, float tilt);
- bool IsFlat(int64_t now);
- bool IsSwinging(int64_t now, float tilt);
- int NextTiltHistoryIndex(int index);
- float RemainingMS(int64_t now, int64_t until);
-
- // The tilt angle range in degrees for each orientation. Beyond these tilt
- // angles, we don't even consider transitioning into the specified orientation.
- // We place more stringent requirements on unnatural orientations than natural
- // ones to make it less likely to accidentally transition into those states.
- // The first value of each pair is negative so it applies a limit when the
- // device is facing down (overhead reading in bed). The second value of each
- // pair is positive so it applies a limit when the device is facing up
- // (resting on a table). The ideal tilt angle is 0 (when the device is vertical)
- // so the limits establish how close to vertical the device must be in order
- // to change orientation.
- static const int tiltTolerance[][4];
-
- // Timestamp and value of the last accelerometer sample.
- int64_t mLastFilteredTimestampNanos;
- float mLastFilteredX, mLastFilteredY, mLastFilteredZ;
-
- // The last proposed rotation, -1 if unknown.
- int mProposedRotation;
-
- // Value of the current predicted rotation, -1 if unknown.
- int mPredictedRotation;
-
- // Timestamp of when the predicted rotation most recently changed.
- int64_t mPredictedRotationTimestampNanos;
-
- // Timestamp when the device last appeared to be flat for sure (the flat delay
- // elapsed).
- int64_t mFlatTimestampNanos;
-
- // Timestamp when the device last appeared to be swinging.
- int64_t mSwingTimestampNanos;
-
- // Timestamp when the device last appeared to be undergoing external
- // acceleration.
- int64_t mAccelerationTimestampNanos;
-
- struct {
- struct {
- float tiltAngle;
- int64_t timestampNanos;
- } history[TILT_HISTORY_SIZE];
- int index;
- } mTiltHistory;
-};
-
-} // namespace mozilla
-
-#endif
diff --git a/widget/gonk/WidgetTraceEvent.cpp b/widget/gonk/WidgetTraceEvent.cpp
deleted file mode 100644
index 558d9313e..000000000
--- a/widget/gonk/WidgetTraceEvent.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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/WidgetTraceEvent.h"
-#include "mozilla/StaticPtr.h"
-#include "nsThreadUtils.h"
-#include <mozilla/CondVar.h>
-#include <mozilla/Mutex.h>
-
-using mozilla::CondVar;
-using mozilla::Mutex;
-using mozilla::MutexAutoLock;
-
-namespace mozilla {
- class TracerRunnable : public Runnable {
- public:
- TracerRunnable() {
- mTracerLock = new Mutex("TracerRunnable");
- mTracerCondVar = new CondVar(*mTracerLock, "TracerRunnable");
- mMainThread = do_GetMainThread();
- }
-
- ~TracerRunnable() {
- delete mTracerCondVar;
- delete mTracerLock;
- mTracerLock = nullptr;
- mTracerCondVar = nullptr;
- }
-
- virtual nsresult Run() {
- MutexAutoLock lock(*mTracerLock);
- mHasRun = true;
- mTracerCondVar->Notify();
- return NS_OK;
- }
-
- bool Fire() {
- if (!mTracerLock || !mTracerCondVar) {
- return false;
- }
-
- MutexAutoLock lock(*mTracerLock);
- mHasRun = false;
- mMainThread->Dispatch(this, NS_DISPATCH_NORMAL);
- while (!mHasRun) {
- mTracerCondVar->Wait();
- }
- return true;
- }
-
- void Signal() {
- MutexAutoLock lock(*mTracerLock);
- mHasRun = true;
- mTracerCondVar->Notify();
- }
-
- private:
- Mutex* mTracerLock;
- CondVar* mTracerCondVar;
- bool mHasRun;
- nsCOMPtr<nsIThread> mMainThread;
- };
-
- StaticRefPtr<TracerRunnable> sTracerRunnable;
-
- bool InitWidgetTracing()
- {
- if (!sTracerRunnable) {
- sTracerRunnable = new TracerRunnable();
- }
- return true;
- }
-
- void CleanUpWidgetTracing()
- {
- sTracerRunnable = nullptr;
- }
-
- bool FireAndWaitForTracerEvent()
- {
- if (sTracerRunnable) {
- return sTracerRunnable->Fire();
- }
-
- return false;
- }
-
- void SignalTracerThread()
- {
- if (sTracerRunnable) {
- return sTracerRunnable->Signal();
- }
- }
-} // namespace mozilla
-
diff --git a/widget/gonk/hwchal/HwcHAL.cpp b/widget/gonk/hwchal/HwcHAL.cpp
deleted file mode 100644
index 1793b75e6..000000000
--- a/widget/gonk/hwchal/HwcHAL.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:set ts=4 sw=4 sts=4 et: */
-/*
- * Copyright (c) 2015 The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "HwcHAL.h"
-#include "libdisplay/GonkDisplay.h"
-#include "mozilla/Assertions.h"
-
-namespace mozilla {
-
-HwcHAL::HwcHAL()
- : HwcHALBase()
-{
- // Some HALs don't want to open hwc twice.
- // If GetDisplay already load hwc module, we don't need to load again
- mHwc = (HwcDevice*)GetGonkDisplay()->GetHWCDevice();
- if (!mHwc) {
- printf_stderr("HwcHAL Error: Cannot load hwcomposer");
- return;
- }
-}
-
-HwcHAL::~HwcHAL()
-{
- mHwc = nullptr;
-}
-
-bool
-HwcHAL::Query(QueryType aType)
-{
- if (!mHwc || !mHwc->query) {
- return false;
- }
-
- bool value = false;
- int supported = 0;
- if (mHwc->query(mHwc, static_cast<int>(aType), &supported) == 0/*android::NO_ERROR*/) {
- value = !!supported;
- }
- return value;
-}
-
-int
-HwcHAL::Set(HwcList *aList,
- uint32_t aDisp)
-{
- MOZ_ASSERT(mHwc);
- if (!mHwc) {
- return -1;
- }
-
- HwcList *displays[HWC_NUM_DISPLAY_TYPES] = { nullptr };
- displays[aDisp] = aList;
- return mHwc->set(mHwc, HWC_NUM_DISPLAY_TYPES, displays);
-}
-
-int
-HwcHAL::ResetHwc()
-{
- return Set(nullptr, HWC_DISPLAY_PRIMARY);
-}
-
-int
-HwcHAL::Prepare(HwcList *aList,
- uint32_t aDisp,
- hwc_rect_t aDispRect,
- buffer_handle_t aHandle,
- int aFenceFd)
-{
- MOZ_ASSERT(mHwc);
- if (!mHwc) {
- printf_stderr("HwcHAL Error: HwcDevice doesn't exist. A fence might be leaked.");
- return -1;
- }
-
- HwcList *displays[HWC_NUM_DISPLAY_TYPES] = { nullptr };
- displays[aDisp] = aList;
-#if ANDROID_VERSION >= 18
- aList->outbufAcquireFenceFd = -1;
- aList->outbuf = nullptr;
-#endif
- aList->retireFenceFd = -1;
-
- const auto idx = aList->numHwLayers - 1;
- aList->hwLayers[idx].hints = 0;
- aList->hwLayers[idx].flags = 0;
- aList->hwLayers[idx].transform = 0;
- aList->hwLayers[idx].handle = aHandle;
- aList->hwLayers[idx].blending = HWC_BLENDING_PREMULT;
- aList->hwLayers[idx].compositionType = HWC_FRAMEBUFFER_TARGET;
- SetCrop(aList->hwLayers[idx], aDispRect);
- aList->hwLayers[idx].displayFrame = aDispRect;
- aList->hwLayers[idx].visibleRegionScreen.numRects = 1;
- aList->hwLayers[idx].visibleRegionScreen.rects = &aList->hwLayers[idx].displayFrame;
- aList->hwLayers[idx].acquireFenceFd = aFenceFd;
- aList->hwLayers[idx].releaseFenceFd = -1;
-#if ANDROID_VERSION >= 18
- aList->hwLayers[idx].planeAlpha = 0xFF;
-#endif
- return mHwc->prepare(mHwc, HWC_NUM_DISPLAY_TYPES, displays);
-}
-
-bool
-HwcHAL::SupportTransparency() const
-{
-#if ANDROID_VERSION >= 18
- return true;
-#endif
- return false;
-}
-
-uint32_t
-HwcHAL::GetGeometryChangedFlag(bool aGeometryChanged) const
-{
-#if ANDROID_VERSION >= 19
- return aGeometryChanged ? HWC_GEOMETRY_CHANGED : 0;
-#else
- return HWC_GEOMETRY_CHANGED;
-#endif
-}
-
-void
-HwcHAL::SetCrop(HwcLayer &aLayer,
- const hwc_rect_t &aSrcCrop) const
-{
- if (GetAPIVersion() >= HwcAPIVersion(1, 3)) {
-#if ANDROID_VERSION >= 19
- aLayer.sourceCropf.left = aSrcCrop.left;
- aLayer.sourceCropf.top = aSrcCrop.top;
- aLayer.sourceCropf.right = aSrcCrop.right;
- aLayer.sourceCropf.bottom = aSrcCrop.bottom;
-#endif
- } else {
- aLayer.sourceCrop = aSrcCrop;
- }
-}
-
-bool
-HwcHAL::EnableVsync(bool aEnable)
-{
- // Only support hardware vsync on kitkat, L and up due to inaccurate timings
- // with JellyBean.
-#if (ANDROID_VERSION == 19 || ANDROID_VERSION >= 21)
- if (!mHwc) {
- return false;
- }
- return !mHwc->eventControl(mHwc,
- HWC_DISPLAY_PRIMARY,
- HWC_EVENT_VSYNC,
- aEnable);
-#else
- return false;
-#endif
-}
-
-bool
-HwcHAL::RegisterHwcEventCallback(const HwcHALProcs_t &aProcs)
-{
- if (!mHwc || !mHwc->registerProcs) {
- printf_stderr("Failed to get hwc\n");
- return false;
- }
-
- // Disable Vsync first, and then register callback functions.
- mHwc->eventControl(mHwc,
- HWC_DISPLAY_PRIMARY,
- HWC_EVENT_VSYNC,
- false);
- static const hwc_procs_t sHwcJBProcs = {aProcs.invalidate,
- aProcs.vsync,
- aProcs.hotplug};
- mHwc->registerProcs(mHwc, &sHwcJBProcs);
-
- // Only support hardware vsync on kitkat, L and up due to inaccurate timings
- // with JellyBean.
-#if (ANDROID_VERSION == 19 || ANDROID_VERSION >= 21)
- return true;
-#else
- return false;
-#endif
-}
-
-uint32_t
-HwcHAL::GetAPIVersion() const
-{
- if (!mHwc) {
- // default value: HWC_MODULE_API_VERSION_0_1
- return 1;
- }
- return mHwc->common.version;
-}
-
-// Create HwcHAL
-UniquePtr<HwcHALBase>
-HwcHALBase::CreateHwcHAL()
-{
- return Move(MakeUnique<HwcHAL>());
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/hwchal/HwcHAL.h b/widget/gonk/hwchal/HwcHAL.h
deleted file mode 100644
index 05cb6a45f..000000000
--- a/widget/gonk/hwchal/HwcHAL.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:set ts=4 sw=4 sts=4 et: */
-/*
- * Copyright (c) 2015 The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef mozilla_HwcHAL
-#define mozilla_HwcHAL
-
-#include "HwcHALBase.h"
-
-namespace mozilla {
-
-class HwcHAL final : public HwcHALBase {
-public:
- explicit HwcHAL();
-
- virtual ~HwcHAL();
-
- virtual bool HasHwc() const override { return static_cast<bool>(mHwc); }
-
- virtual void SetEGLInfo(hwc_display_t aDpy,
- hwc_surface_t aSur) override { }
-
- virtual bool Query(QueryType aType) override;
-
- virtual int Set(HwcList *aList,
- uint32_t aDisp) override;
-
- virtual int ResetHwc() override;
-
- virtual int Prepare(HwcList *aList,
- uint32_t aDisp,
- hwc_rect_t aDispRect,
- buffer_handle_t aHandle,
- int aFenceFd) override;
-
- virtual bool SupportTransparency() const override;
-
- virtual uint32_t GetGeometryChangedFlag(bool aGeometryChanged) const override;
-
- virtual void SetCrop(HwcLayer &aLayer,
- const hwc_rect_t &aSrcCrop) const override;
-
- virtual bool EnableVsync(bool aEnable) override;
-
- virtual bool RegisterHwcEventCallback(const HwcHALProcs_t &aProcs) override;
-
-private:
- uint32_t GetAPIVersion() const;
-
-private:
- HwcDevice *mHwc = nullptr;
-};
-
-} // namespace mozilla
-
-#endif // mozilla_HwcHAL
diff --git a/widget/gonk/hwchal/HwcHALBase.h b/widget/gonk/hwchal/HwcHALBase.h
deleted file mode 100644
index 0ef00a325..000000000
--- a/widget/gonk/hwchal/HwcHALBase.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:set ts=4 sw=4 sts=4 et: */
-/*
- * Copyright (c) 2015 The Linux Foundation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef mozilla_HwcHALBase
-#define mozilla_HwcHALBase
-
-#include "mozilla/UniquePtr.h"
-#include "nsRect.h"
-
-#include <hardware/hwcomposer.h>
-
-#ifndef HWC_BLIT
-#if ANDROID_VERSION >= 21
-#define HWC_BLIT 0xFF
-#elif ANDROID_VERSION >= 17
-#define HWC_BLIT (HWC_FRAMEBUFFER_TARGET + 1)
-#else
-// ICS didn't support this. However, we define this
-// for passing compilation
-#define HWC_BLIT 0xFF
-#endif // #if ANDROID_VERSION
-#endif // #ifndef HWC_BLIT
-
-namespace mozilla {
-
-#if ANDROID_VERSION >= 17
-using HwcDevice = hwc_composer_device_1_t;
-using HwcList = hwc_display_contents_1_t;
-using HwcLayer = hwc_layer_1_t;
-#else
-using HwcDevice = hwc_composer_device_t;
-using HwcList = hwc_layer_list_t;
-using HwcLayer = hwc_layer_t;
-#endif
-
-// HwcHAL definition for HwcEvent callback types
-// Note: hwc_procs is different between ICS and later,
-// and the signature of invalidate is also different.
-// Use this wrap struct to hide the detail. BTW,
-// we don't have to register callback functions on ICS, so
-// there is no callbacks for ICS in HwcHALProcs.
-typedef struct HwcHALProcs {
- void (*invalidate)(const struct hwc_procs* procs);
- void (*vsync)(const struct hwc_procs* procs, int disp, int64_t timestamp);
- void (*hotplug)(const struct hwc_procs* procs, int disp, int connected);
-} HwcHALProcs_t;
-
-// HwcHAL class
-// This class handle all the HAL related work
-// The purpose of HwcHAL is to make HwcComposer2D simpler.
-class HwcHALBase {
-
-public:
- // Query Types. We can add more types easily in the future
- enum class QueryType {
- COLOR_FILL = 0x8,
- RB_SWAP = 0x40
- };
-
-public:
- explicit HwcHALBase() = default;
-
- virtual ~HwcHALBase() {}
-
- // Create HwcHAL module, Only HwcComposer2D calls this.
- // If other modules want to use HwcHAL, please use APIs in
- // HwcComposer2D
- static UniquePtr<HwcHALBase> CreateHwcHAL();
-
- // Check if mHwc exists
- virtual bool HasHwc() const = 0;
-
- // Set EGL info (only ICS need this info)
- virtual void SetEGLInfo(hwc_display_t aEGLDisplay,
- hwc_surface_t aEGLSurface) = 0;
-
- // HwcDevice query properties
- virtual bool Query(QueryType aType) = 0;
-
- // HwcDevice set
- virtual int Set(HwcList *aList,
- uint32_t aDisp) = 0;
-
- // Reset HwcDevice
- virtual int ResetHwc() = 0;
-
- // HwcDevice prepare
- virtual int Prepare(HwcList *aList,
- uint32_t aDisp,
- hwc_rect_t aDispRect,
- buffer_handle_t aHandle,
- int aFenceFd) = 0;
-
- // Check transparency support
- virtual bool SupportTransparency() const = 0;
-
- // Get a geometry change flag
- virtual uint32_t GetGeometryChangedFlag(bool aGeometryChanged) const = 0;
-
- // Set crop help
- virtual void SetCrop(HwcLayer &aLayer,
- const hwc_rect_t &aSrcCrop) const = 0;
-
- // Enable HW Vsync
- virtual bool EnableVsync(bool aEnable) = 0;
-
- // Register HW event callback functions
- virtual bool RegisterHwcEventCallback(const HwcHALProcs_t &aProcs) = 0;
-
-protected:
- constexpr static uint32_t HwcAPIVersion(uint32_t aMaj, uint32_t aMin) {
- // HARDWARE_MAKE_API_VERSION_2, from Android hardware.h
- return (((aMaj & 0xff) << 24) | ((aMin & 0xff) << 16) | (1 & 0xffff));
- }
-};
-
-} // namespace mozilla
-
-#endif // mozilla_HwcHALBase
diff --git a/widget/gonk/libdisplay/BootAnimation.cpp b/widget/gonk/libdisplay/BootAnimation.cpp
deleted file mode 100644
index c275179fc..000000000
--- a/widget/gonk/libdisplay/BootAnimation.cpp
+++ /dev/null
@@ -1,726 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <algorithm>
-#include <endian.h>
-#include <fcntl.h>
-#include <pthread.h>
-#include <string>
-#include <sys/mman.h>
-#include <sys/stat.h>
-#include <vector>
-#include "mozilla/FileUtils.h"
-#include "png.h"
-
-#include "android/log.h"
-#include "GonkDisplay.h"
-#include "hardware/gralloc.h"
-
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
-#define LOGW(args...) __android_log_print(ANDROID_LOG_WARN, "Gonk", ## args)
-#define LOGE(args...) __android_log_print(ANDROID_LOG_ERROR, "Gonk", ## args)
-
-using namespace mozilla;
-using namespace std;
-
-static pthread_t sAnimationThread;
-static bool sRunAnimation;
-
-/* See http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
-struct local_file_header {
- uint32_t signature;
- uint16_t min_version;
- uint16_t general_flag;
- uint16_t compression;
- uint16_t lastmod_time;
- uint16_t lastmod_date;
- uint32_t crc32;
- uint32_t compressed_size;
- uint32_t uncompressed_size;
- uint16_t filename_size;
- uint16_t extra_field_size;
- char data[0];
-
- uint32_t GetDataSize() const
- {
- return letoh32(uncompressed_size);
- }
-
- uint32_t GetSize() const
- {
- /* XXX account for data descriptor */
- return sizeof(local_file_header) + letoh16(filename_size) +
- letoh16(extra_field_size) + GetDataSize();
- }
-
- const char * GetData() const
- {
- return data + letoh16(filename_size) + letoh16(extra_field_size);
- }
-} __attribute__((__packed__));
-
-struct data_descriptor {
- uint32_t crc32;
- uint32_t compressed_size;
- uint32_t uncompressed_size;
-} __attribute__((__packed__));
-
-struct cdir_entry {
- uint32_t signature;
- uint16_t creator_version;
- uint16_t min_version;
- uint16_t general_flag;
- uint16_t compression;
- uint16_t lastmod_time;
- uint16_t lastmod_date;
- uint32_t crc32;
- uint32_t compressed_size;
- uint32_t uncompressed_size;
- uint16_t filename_size;
- uint16_t extra_field_size;
- uint16_t file_comment_size;
- uint16_t disk_num;
- uint16_t internal_attr;
- uint32_t external_attr;
- uint32_t offset;
- char data[0];
-
- uint32_t GetDataSize() const
- {
- return letoh32(compressed_size);
- }
-
- uint32_t GetSize() const
- {
- return sizeof(cdir_entry) + letoh16(filename_size) +
- letoh16(extra_field_size) + letoh16(file_comment_size);
- }
-
- bool Valid() const
- {
- return signature == htole32(0x02014b50);
- }
-} __attribute__((__packed__));
-
-struct cdir_end {
- uint32_t signature;
- uint16_t disk_num;
- uint16_t cdir_disk;
- uint16_t disk_entries;
- uint16_t cdir_entries;
- uint32_t cdir_size;
- uint32_t cdir_offset;
- uint16_t comment_size;
- char comment[0];
-
- bool Valid() const
- {
- return signature == htole32(0x06054b50);
- }
-} __attribute__((__packed__));
-
-/* We don't have access to libjar and the zip reader in android
- * doesn't quite fit what we want to do. */
-class ZipReader {
- const char *mBuf;
- const cdir_end *mEnd;
- const char *mCdir_limit;
- uint32_t mBuflen;
-
-public:
- ZipReader() : mBuf(nullptr) {}
- ~ZipReader() {
- if (mBuf)
- munmap((void *)mBuf, mBuflen);
- }
-
- bool OpenArchive(const char *path)
- {
- int fd;
- do {
- fd = open(path, O_RDONLY);
- } while (fd == -1 && errno == EINTR);
- if (fd == -1)
- return false;
-
- struct stat sb;
- if (fstat(fd, &sb) == -1 || sb.st_size < sizeof(cdir_end)) {
- close(fd);
- return false;
- }
-
- mBuflen = sb.st_size;
- mBuf = (char *)mmap(nullptr, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
- close(fd);
-
- if (!mBuf) {
- return false;
- }
-
- madvise(mBuf, sb.st_size, MADV_SEQUENTIAL);
-
- mEnd = (cdir_end *)(mBuf + mBuflen - sizeof(cdir_end));
- while (!mEnd->Valid() &&
- (char *)mEnd > mBuf) {
- mEnd = (cdir_end *)((char *)mEnd - 1);
- }
-
- mCdir_limit = mBuf + letoh32(mEnd->cdir_offset) + letoh32(mEnd->cdir_size);
-
- if (!mEnd->Valid() || mCdir_limit > (char *)mEnd) {
- munmap((void *)mBuf, mBuflen);
- mBuf = nullptr;
- return false;
- }
-
- return true;
- }
-
- /* Pass null to get the first cdir entry */
- const cdir_entry * GetNextEntry(const cdir_entry *prev)
- {
- const cdir_entry *entry;
- if (prev)
- entry = (cdir_entry *)((char *)prev + prev->GetSize());
- else
- entry = (cdir_entry *)(mBuf + letoh32(mEnd->cdir_offset));
-
- if (((char *)entry + entry->GetSize()) > mCdir_limit ||
- !entry->Valid())
- return nullptr;
- return entry;
- }
-
- string GetEntryName(const cdir_entry *entry)
- {
- uint16_t len = letoh16(entry->filename_size);
-
- string name;
- name.append(entry->data, len);
- return name;
- }
-
- const local_file_header * GetLocalEntry(const cdir_entry *entry)
- {
- const local_file_header * data =
- (local_file_header *)(mBuf + letoh32(entry->offset));
- if (((char *)data + data->GetSize()) > (char *)mEnd)
- return nullptr;
- return data;
- }
-};
-
-struct AnimationFrame {
- char path[256];
- png_color_16 bgcolor;
- char *buf;
- const local_file_header *file;
- uint32_t width;
- uint32_t height;
- uint16_t bytepp;
- bool has_bgcolor;
-
- AnimationFrame() : buf(nullptr) {}
- AnimationFrame(const AnimationFrame &frame) : buf(nullptr) {
- strncpy(path, frame.path, sizeof(path));
- file = frame.file;
- }
- ~AnimationFrame()
- {
- if (buf)
- free(buf);
- }
-
- bool operator<(const AnimationFrame &other) const
- {
- return strcmp(path, other.path) < 0;
- }
-
- void ReadPngFrame(int outputFormat);
-};
-
-struct AnimationPart {
- int32_t count;
- int32_t pause;
- // If you alter the size of the path, change ReadFromString() as well.
- char path[256];
- vector<AnimationFrame> frames;
-
- bool
- ReadFromString(const char* aLine)
- {
- MOZ_ASSERT(aLine);
- // this 255 value must be in sync with AnimationPart::path.
- return sscanf(aLine, "p %d %d %255s", &count, &pause, path) == 3;
- }
-};
-
-struct RawReadState {
- const char *start;
- uint32_t offset;
- uint32_t length;
-};
-
-static void
-RawReader(png_structp png_ptr, png_bytep data, png_size_t length)
-{
- RawReadState *state = (RawReadState *)png_get_io_ptr(png_ptr);
- if (length > (state->length - state->offset))
- png_error(png_ptr, "PNG read overrun");
-
- memcpy(data, state->start + state->offset, length);
- state->offset += length;
-}
-
-static void
-TransformTo565(png_structp png_ptr, png_row_infop row_info, png_bytep data)
-{
- uint16_t *outbuf = (uint16_t *)data;
- uint8_t *inbuf = (uint8_t *)data;
- for (uint32_t i = 0; i < row_info->rowbytes; i += 3) {
- *outbuf++ = ((inbuf[i] & 0xF8) << 8) |
- ((inbuf[i + 1] & 0xFC) << 3) |
- ((inbuf[i + 2] ) >> 3);
- }
-}
-
-static uint16_t
-GetFormatBPP(int aFormat)
-{
- uint16_t bpp = 0;
-
- switch (aFormat) {
- case HAL_PIXEL_FORMAT_BGRA_8888:
- case HAL_PIXEL_FORMAT_RGBA_8888:
- case HAL_PIXEL_FORMAT_RGBX_8888:
- bpp = 4;
- break;
- case HAL_PIXEL_FORMAT_RGB_888:
- bpp = 3;
- break;
- default:
- LOGW("Unknown pixel format %d. Assuming RGB 565.", aFormat);
- // FALL THROUGH
- case HAL_PIXEL_FORMAT_RGB_565:
- bpp = 2;
- break;
- }
-
- return bpp;
-}
-
-void
-AnimationFrame::ReadPngFrame(int outputFormat)
-{
-#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
- static const png_byte unused_chunks[] =
- { 99, 72, 82, 77, '\0', /* cHRM */
- 104, 73, 83, 84, '\0', /* hIST */
- 105, 67, 67, 80, '\0', /* iCCP */
- 105, 84, 88, 116, '\0', /* iTXt */
- 111, 70, 70, 115, '\0', /* oFFs */
- 112, 67, 65, 76, '\0', /* pCAL */
- 115, 67, 65, 76, '\0', /* sCAL */
- 112, 72, 89, 115, '\0', /* pHYs */
- 115, 66, 73, 84, '\0', /* sBIT */
- 115, 80, 76, 84, '\0', /* sPLT */
- 116, 69, 88, 116, '\0', /* tEXt */
- 116, 73, 77, 69, '\0', /* tIME */
- 122, 84, 88, 116, '\0'}; /* zTXt */
- static const png_byte tRNS_chunk[] =
- {116, 82, 78, 83, '\0'}; /* tRNS */
-#endif
-
- png_structp pngread = png_create_read_struct(PNG_LIBPNG_VER_STRING,
- nullptr, nullptr, nullptr);
-
- if (!pngread)
- return;
-
- png_infop pnginfo = png_create_info_struct(pngread);
-
- if (!pnginfo) {
- png_destroy_read_struct(&pngread, &pnginfo, nullptr);
- return;
- }
-
- if (setjmp(png_jmpbuf(pngread))) {
- // libpng reported an error and longjumped here. Clean up and return.
- png_destroy_read_struct(&pngread, &pnginfo, nullptr);
- return;
- }
-
- RawReadState state;
- state.start = file->GetData();
- state.length = file->GetDataSize();
- state.offset = 0;
-
- png_set_read_fn(pngread, &state, RawReader);
-
-#ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
- /* Ignore unused chunks */
- png_set_keep_unknown_chunks(pngread, 1, unused_chunks,
- (int)sizeof(unused_chunks)/5);
-
- /* Ignore the tRNS chunk if we only want opaque output */
- if (outputFormat == HAL_PIXEL_FORMAT_RGB_888 ||
- outputFormat == HAL_PIXEL_FORMAT_RGB_565) {
- png_set_keep_unknown_chunks(pngread, 1, tRNS_chunk, 1);
- }
-#endif
-
- png_read_info(pngread, pnginfo);
-
- png_color_16p colorp;
- has_bgcolor = (PNG_INFO_bKGD == png_get_bKGD(pngread, pnginfo, &colorp));
- bgcolor = has_bgcolor ? *colorp : png_color_16();
- width = png_get_image_width(pngread, pnginfo);
- height = png_get_image_height(pngread, pnginfo);
-
- LOG("Decoded %s: %d x %d frame with bgcolor? %s (%#x, %#x, %#x; gray:%#x)",
- path, width, height, has_bgcolor ? "yes" : "no",
- bgcolor.red, bgcolor.green, bgcolor.blue, bgcolor.gray);
-
- bytepp = GetFormatBPP(outputFormat);
-
- switch (outputFormat) {
- case HAL_PIXEL_FORMAT_BGRA_8888:
- png_set_bgr(pngread);
- // FALL THROUGH
- case HAL_PIXEL_FORMAT_RGBA_8888:
- case HAL_PIXEL_FORMAT_RGBX_8888:
- png_set_filler(pngread, 0xFF, PNG_FILLER_AFTER);
- break;
- case HAL_PIXEL_FORMAT_RGB_888:
- png_set_strip_alpha(pngread);
- break;
- default:
- LOGW("Unknown pixel format %d. Assuming RGB 565.", outputFormat);
- // FALL THROUGH
- case HAL_PIXEL_FORMAT_RGB_565:
- png_set_strip_alpha(pngread);
- png_set_read_user_transform_fn(pngread, TransformTo565);
- break;
- }
-
- // An extra row is added to give libpng enough space when
- // decoding 3/4 bytepp inputs for 2 bytepp output surfaces
- buf = (char *)malloc(width * (height + 1) * bytepp);
-
- vector<char *> rows(height + 1);
- uint32_t stride = width * bytepp;
- for (uint32_t i = 0; i < height; i++) {
- rows[i] = buf + (stride * i);
- }
- rows[height] = nullptr;
- png_set_strip_16(pngread);
- png_set_palette_to_rgb(pngread);
- png_set_gray_to_rgb(pngread);
- png_read_image(pngread, (png_bytepp)&rows.front());
- png_destroy_read_struct(&pngread, &pnginfo, nullptr);
-}
-
-/**
- * Return a wchar_t that when used to |wmemset()| an image buffer will
- * fill it with the color defined by |color16|. The packed wchar_t
- * may comprise one or two pixels depending on |outputFormat|.
- */
-static wchar_t
-AsBackgroundFill(const png_color_16& color16, int outputFormat)
-{
- static_assert(sizeof(wchar_t) == sizeof(uint32_t),
- "TODO: support 2-byte wchar_t");
- union {
- uint32_t r8g8b8;
- struct {
- uint8_t b8;
- uint8_t g8;
- uint8_t r8;
- uint8_t x8;
- };
- } color;
- color.b8 = color16.blue;
- color.g8 = color16.green;
- color.r8 = color16.red;
- color.x8 = 0xFF;
-
- switch (outputFormat) {
- case HAL_PIXEL_FORMAT_RGBA_8888:
- case HAL_PIXEL_FORMAT_RGBX_8888:
- return color.r8g8b8;
-
- case HAL_PIXEL_FORMAT_BGRA_8888:
- swap(color.r8, color.b8);
- return color.r8g8b8;
-
- case HAL_PIXEL_FORMAT_RGB_565: {
- // NB: we could do a higher-quality downsample here, but we
- // want the results to be a pixel-perfect match with the fast
- // downsample in TransformTo565().
- uint16_t color565 = ((color.r8 & 0xF8) << 8) |
- ((color.g8 & 0xFC) << 3) |
- ((color.b8 ) >> 3);
- return (color565 << 16) | color565;
- }
- default:
- LOGW("Unhandled pixel format %d; falling back on black", outputFormat);
- return 0;
- }
-}
-
-void
-ShowSolidColorFrame(GonkDisplay *aDisplay,
- const gralloc_module_t *grallocModule,
- int32_t aFormat)
-{
- LOGW("Show solid color frame for bootAnim");
-
- ANativeWindowBuffer *buffer = aDisplay->DequeueBuffer();
- void *mappedAddress = nullptr;
-
- if (!buffer) {
- LOGW("Failed to get an ANativeWindowBuffer");
- return;
- }
-
- if (!grallocModule->lock(grallocModule, buffer->handle,
- GRALLOC_USAGE_SW_READ_NEVER |
- GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_FB,
- 0, 0, buffer->width, buffer->height, &mappedAddress)) {
- // Just show a black solid color frame.
- memset(mappedAddress, 0, buffer->height * buffer->stride * GetFormatBPP(aFormat));
- grallocModule->unlock(grallocModule, buffer->handle);
- }
-
- aDisplay->QueueBuffer(buffer);
-}
-
-static void *
-AnimationThread(void *)
-{
- GonkDisplay *display = GetGonkDisplay();
- int32_t format = display->surfaceformat;
-
- const hw_module_t *module = nullptr;
- if (hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module)) {
- LOGW("Could not get gralloc module");
- return nullptr;
- }
- const gralloc_module_t *grmodule =
- reinterpret_cast<gralloc_module_t const*>(module);
-
- ZipReader reader;
- if (!reader.OpenArchive("/system/media/bootanimation.zip")) {
- LOGW("Could not open boot animation");
- ShowSolidColorFrame(display, grmodule, format);
- return nullptr;
- }
-
- const cdir_entry *entry = nullptr;
- const local_file_header *file = nullptr;
- while ((entry = reader.GetNextEntry(entry))) {
- string name = reader.GetEntryName(entry);
- if (!name.compare("desc.txt")) {
- file = reader.GetLocalEntry(entry);
- break;
- }
- }
-
- if (!file) {
- LOGW("Could not find desc.txt in boot animation");
- ShowSolidColorFrame(display, grmodule, format);
- return nullptr;
- }
-
- string descCopy;
- descCopy.append(file->GetData(), entry->GetDataSize());
- int32_t width, height, fps;
- const char *line = descCopy.c_str();
- const char *end;
- bool headerRead = true;
- vector<AnimationPart> parts;
- bool animPlayed = false;
-
- /*
- * bootanimation.zip
- *
- * This is the boot animation file format that Android uses.
- * It's a zip file with a directories containing png frames
- * and a desc.txt that describes how they should be played.
- *
- * desc.txt contains two types of lines
- * 1. [width] [height] [fps]
- * There is one of these lines per bootanimation.
- * If the width and height are smaller than the screen,
- * the frames are centered on a black background.
- * XXX: Currently we stretch instead of centering the frame.
- * 2. p [count] [pause] [path]
- * This describes one animation part.
- * Each animation part is played in sequence.
- * An animation part contains all the files/frames in the
- * directory specified in [path]
- * [count] indicates the number of times this part repeats.
- * [pause] indicates the number of frames that this part
- * should pause for after playing the full sequence but
- * before repeating.
- */
-
- do {
- end = strstr(line, "\n");
-
- AnimationPart part;
- if (headerRead &&
- sscanf(line, "%d %d %d", &width, &height, &fps) == 3) {
- headerRead = false;
- } else if (part.ReadFromString(line)) {
- parts.push_back(part);
- }
- } while (end && *(line = end + 1));
-
- for (uint32_t i = 0; i < parts.size(); i++) {
- AnimationPart &part = parts[i];
- entry = nullptr;
- char search[256];
- snprintf(search, sizeof(search), "%s/", part.path);
- while ((entry = reader.GetNextEntry(entry))) {
- string name = reader.GetEntryName(entry);
- if (name.find(search) ||
- !entry->GetDataSize() ||
- name.length() >= 256)
- continue;
-
- part.frames.resize(part.frames.size() + 1);
- AnimationFrame &frame = part.frames.back();
- strcpy(frame.path, name.c_str());
- frame.file = reader.GetLocalEntry(entry);
- }
-
- sort(part.frames.begin(), part.frames.end());
- }
-
- long int frameDelayUs = 1000000 / fps;
-
- for (uint32_t i = 0; i < parts.size(); i++) {
- AnimationPart &part = parts[i];
-
- int32_t j = 0;
- while (sRunAnimation && (!part.count || j++ < part.count)) {
- for (uint32_t k = 0; k < part.frames.size(); k++) {
- struct timeval tv1, tv2;
- gettimeofday(&tv1, nullptr);
- AnimationFrame &frame = part.frames[k];
- if (!frame.buf) {
- frame.ReadPngFrame(format);
- }
-
- ANativeWindowBuffer *buf = display->DequeueBuffer();
- if (!buf) {
- LOGW("Failed to get an ANativeWindowBuffer");
- break;
- }
-
- void *vaddr;
- if (grmodule->lock(grmodule, buf->handle,
- GRALLOC_USAGE_SW_READ_NEVER |
- GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_FB,
- 0, 0, width, height, &vaddr)) {
- LOGW("Failed to lock buffer_handle_t");
- display->QueueBuffer(buf);
- break;
- }
-
- if (frame.has_bgcolor) {
- wchar_t bgfill = AsBackgroundFill(frame.bgcolor, format);
- wmemset((wchar_t*)vaddr, bgfill,
- (buf->height * buf->stride * frame.bytepp) / sizeof(wchar_t));
- }
-
- if ((uint32_t)buf->height == frame.height && (uint32_t)buf->stride == frame.width) {
- memcpy(vaddr, frame.buf,
- frame.width * frame.height * frame.bytepp);
- } else if ((uint32_t)buf->height >= frame.height &&
- (uint32_t)buf->width >= frame.width) {
- int startx = (buf->width - frame.width) / 2;
- int starty = (buf->height - frame.height) / 2;
-
- int src_stride = frame.width * frame.bytepp;
- int dst_stride = buf->stride * frame.bytepp;
-
- char *src = frame.buf;
- char *dst = (char *) vaddr + starty * dst_stride + startx * frame.bytepp;
-
- for (uint32_t i = 0; i < frame.height; i++) {
- memcpy(dst, src, src_stride);
- src += src_stride;
- dst += dst_stride;
- }
- }
- grmodule->unlock(grmodule, buf->handle);
-
- gettimeofday(&tv2, nullptr);
-
- timersub(&tv2, &tv1, &tv2);
-
- if (tv2.tv_usec < frameDelayUs) {
- usleep(frameDelayUs - tv2.tv_usec);
- } else {
- LOGW("Frame delay is %ld us but decoding took %ld us",
- frameDelayUs, tv2.tv_usec);
- }
-
- animPlayed = true;
- display->QueueBuffer(buf);
-
- if (part.count && j >= part.count) {
- free(frame.buf);
- frame.buf = nullptr;
- }
- }
- usleep(frameDelayUs * part.pause);
- }
- }
-
- if (!animPlayed) {
- ShowSolidColorFrame(display, grmodule, format);
- }
-
- return nullptr;
-}
-
-namespace mozilla {
-
-__attribute__ ((visibility ("default")))
-void
-StartBootAnimation()
-{
- GetGonkDisplay(); // Ensure GonkDisplay exist
- sRunAnimation = true;
- pthread_create(&sAnimationThread, nullptr, AnimationThread, nullptr);
-}
-
-__attribute__ ((visibility ("default")))
-void
-StopBootAnimation()
-{
- if (sRunAnimation) {
- sRunAnimation = false;
- pthread_join(sAnimationThread, nullptr);
- GetGonkDisplay()->NotifyBootAnimationStopped();
- }
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/libdisplay/BootAnimation.h b/widget/gonk/libdisplay/BootAnimation.h
deleted file mode 100644
index 9fdc20eca..000000000
--- a/widget/gonk/libdisplay/BootAnimation.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef BOOTANIMATION_H
-#define BOOTANIMATION_H
-
-namespace mozilla {
-
-MOZ_EXPORT __attribute__ ((weak))
-void StartBootAnimation();
-
-/* Stop the boot animation if it's still running. */
-MOZ_EXPORT __attribute__ ((weak))
-void StopBootAnimation();
-
-} // namespace mozilla
-
-#endif /* BOOTANIMATION_H */
diff --git a/widget/gonk/libdisplay/DisplaySurface.h b/widget/gonk/libdisplay/DisplaySurface.h
deleted file mode 100644
index 398541c49..000000000
--- a/widget/gonk/libdisplay/DisplaySurface.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_SF_DISPLAY_SURFACE_H
-#define ANDROID_SF_DISPLAY_SURFACE_H
-
-#include <gui/ConsumerBase.h>
-#include <system/window.h>
-#include <utils/Errors.h>
-#include <utils/RefBase.h>
-#include <utils/StrongPointer.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class IGraphicBufferProducer;
-class String8;
-
-#if ANDROID_VERSION >= 21
-typedef IGraphicBufferConsumer StreamConsumer;
-#else
-typedef BufferQueue StreamConsumer;
-#endif
-
-class DisplaySurface : public ConsumerBase {
-public:
- // beginFrame is called at the beginning of the composition loop, before
- // the configuration is known. The DisplaySurface should do anything it
- // needs to do to enable HWComposer to decide how to compose the frame.
- // We pass in mustRecompose so we can keep VirtualDisplaySurface's state
- // machine happy without actually queueing a buffer if nothing has changed.
- virtual status_t beginFrame(bool mustRecompose) = 0;
-
- // prepareFrame is called after the composition configuration is known but
- // before composition takes place. The DisplaySurface can use the
- // composition type to decide how to manage the flow of buffers between
- // GLES and HWC for this frame.
- enum CompositionType {
- COMPOSITION_UNKNOWN = 0,
- COMPOSITION_GLES = 1,
- COMPOSITION_HWC = 2,
- COMPOSITION_MIXED = COMPOSITION_GLES | COMPOSITION_HWC
- };
- virtual status_t prepareFrame(CompositionType compositionType) = 0;
-
- // Should be called when composition rendering is complete for a frame (but
- // eglSwapBuffers hasn't necessarily been called). Required by certain
- // older drivers for synchronization.
- // TODO: Remove this when we drop support for HWC 1.0.
- virtual status_t compositionComplete() = 0;
-
- // Inform the surface that GLES composition is complete for this frame, and
- // the surface should make sure that HWComposer has the correct buffer for
- // this frame. Some implementations may only push a new buffer to
- // HWComposer if GLES composition took place, others need to push a new
- // buffer on every frame.
- //
- // advanceFrame must be followed by a call to onFrameCommitted before
- // advanceFrame may be called again.
- virtual status_t advanceFrame() = 0;
-
- // onFrameCommitted is called after the frame has been committed to the
- // hardware composer. The surface collects the release fence for this
- // frame's buffer.
- virtual void onFrameCommitted() = 0;
-
- virtual void resizeBuffers(const uint32_t w, const uint32_t h) = 0;
-
- // setReleaseFenceFd stores a fence file descriptor that will signal when the
- // current buffer is no longer being read. This fence will be returned to
- // the producer when the current buffer is released by updateTexImage().
- // Multiple fences can be set for a given buffer; they will be merged into
- // a single union fence. The SurfaceTexture will close the file descriptor
- // when finished with it.
- virtual status_t setReleaseFenceFd(int fenceFd) = 0;
-
- virtual int GetPrevDispAcquireFd() = 0;
-
- buffer_handle_t lastHandle;
-
-protected:
- DisplaySurface(const sp<StreamConsumer>& sc)
-#if ANDROID_VERSION >= 19
- : ConsumerBase(sc, true)
-#else
- : ConsumerBase(sc)
-#endif
- , lastHandle(0)
- { }
- virtual ~DisplaySurface() {}
-};
-
-// ---------------------------------------------------------------------------
-} // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_SF_DISPLAY_SURFACE_H
-
diff --git a/widget/gonk/libdisplay/FramebufferSurface.cpp b/widget/gonk/libdisplay/FramebufferSurface.cpp
deleted file mode 100644
index a289acbb8..000000000
--- a/widget/gonk/libdisplay/FramebufferSurface.cpp
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- **
- ** Copyright 2012 The Android Open Source Project
- **
- ** Licensed under the Apache License Version 2.0(the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- ** http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing software
- ** distributed under the License is distributed on an "AS IS" BASIS
- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied.
- ** See the License for the specific language governing permissions and
- ** limitations under the License.
- */
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <errno.h>
-
-#include <cutils/log.h>
-
-#include <utils/String8.h>
-
-#include <ui/Rect.h>
-
-#include <EGL/egl.h>
-
-#include <hardware/hardware.h>
-#if ANDROID_VERSION == 17
-#include <gui/SurfaceTextureClient.h>
-#endif
-#include <ui/GraphicBuffer.h>
-
-#include "FramebufferSurface.h"
-#include "GraphicBufferAlloc.h"
-
-#ifndef NUM_FRAMEBUFFER_SURFACE_BUFFERS
-#define NUM_FRAMEBUFFER_SURFACE_BUFFERS (2)
-#endif
-
-// ----------------------------------------------------------------------------
-namespace android {
-// ----------------------------------------------------------------------------
-
-/*
- * This implements the (main) framebuffer management. This class
- * was adapted from the version in SurfaceFlinger
- */
-FramebufferSurface::FramebufferSurface(int disp,
- uint32_t width,
- uint32_t height,
- uint32_t format,
- const sp<StreamConsumer>& sc)
- : DisplaySurface(sc)
- , mDisplayType(disp)
- , mCurrentBufferSlot(-1)
- , mCurrentBuffer(0)
-{
- mName = "FramebufferSurface";
-
-#if ANDROID_VERSION >= 19
- sp<IGraphicBufferConsumer> consumer = mConsumer;
-#else
- sp<BufferQueue> consumer = mBufferQueue;
- consumer->setSynchronousMode(true);
-#endif
- consumer->setConsumerName(mName);
- consumer->setConsumerUsageBits(GRALLOC_USAGE_HW_FB |
- GRALLOC_USAGE_HW_RENDER |
- GRALLOC_USAGE_HW_COMPOSER);
- consumer->setDefaultBufferFormat(format);
- consumer->setDefaultBufferSize(width, height);
- consumer->setDefaultMaxBufferCount(NUM_FRAMEBUFFER_SURFACE_BUFFERS);
-}
-
-status_t FramebufferSurface::beginFrame(bool /*mustRecompose*/) {
- return NO_ERROR;
-}
-
-status_t FramebufferSurface::prepareFrame(CompositionType /*compositionType*/) {
- return NO_ERROR;
-}
-
-status_t FramebufferSurface::advanceFrame() {
- // Once we remove FB HAL support, we can call nextBuffer() from here
- // instead of using onFrameAvailable(). No real benefit, except it'll be
- // more like VirtualDisplaySurface.
- return NO_ERROR;
-}
-
-status_t FramebufferSurface::nextBuffer(sp<GraphicBuffer>& outBuffer, sp<Fence>& outFence) {
- Mutex::Autolock lock(mMutex);
-
- BufferQueue::BufferItem item;
-#if ANDROID_VERSION >= 19
- status_t err = acquireBufferLocked(&item, 0);
-#else
- status_t err = acquireBufferLocked(&item);
-#endif
- if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
- outBuffer = mCurrentBuffer;
- return NO_ERROR;
- } else if (err != NO_ERROR) {
- ALOGE("error acquiring buffer: %s (%d)", strerror(-err), err);
- return err;
- }
-
- // If the BufferQueue has freed and reallocated a buffer in mCurrentSlot
- // then we may have acquired the slot we already own. If we had released
- // our current buffer before we call acquireBuffer then that release call
- // would have returned STALE_BUFFER_SLOT, and we would have called
- // freeBufferLocked on that slot. Because the buffer slot has already
- // been overwritten with the new buffer all we have to do is skip the
- // releaseBuffer call and we should be in the same state we'd be in if we
- // had released the old buffer first.
- if (mCurrentBufferSlot != BufferQueue::INVALID_BUFFER_SLOT &&
- item.mBuf != mCurrentBufferSlot) {
- // Release the previous buffer.
-#if ANDROID_VERSION >= 19
- err = releaseBufferLocked(mCurrentBufferSlot, mCurrentBuffer,
- EGL_NO_DISPLAY, EGL_NO_SYNC_KHR);
-#else
- err = releaseBufferLocked(mCurrentBufferSlot, EGL_NO_DISPLAY,
- EGL_NO_SYNC_KHR);
-#endif
- if (err != NO_ERROR && err != StreamConsumer::STALE_BUFFER_SLOT) {
- ALOGE("error releasing buffer: %s (%d)", strerror(-err), err);
- return err;
- }
- }
- mCurrentBufferSlot = item.mBuf;
- mCurrentBuffer = mSlots[mCurrentBufferSlot].mGraphicBuffer;
- outFence = item.mFence;
- outBuffer = mCurrentBuffer;
- return NO_ERROR;
-}
-
-// Overrides ConsumerBase::onFrameAvailable(), does not call base class impl.
-#if ANDROID_VERSION >= 22
-void FramebufferSurface::onFrameAvailable(const ::android::BufferItem &item) {
-#else
-void FramebufferSurface::onFrameAvailable() {
-#endif
- sp<GraphicBuffer> buf;
- sp<Fence> acquireFence;
- status_t err = nextBuffer(buf, acquireFence);
- if (err != NO_ERROR) {
- ALOGE("error latching nnext FramebufferSurface buffer: %s (%d)",
- strerror(-err), err);
- return;
- }
- if (acquireFence.get() && acquireFence->isValid())
- mPrevFBAcquireFence = new Fence(acquireFence->dup());
- else
- mPrevFBAcquireFence = Fence::NO_FENCE;
-
- lastHandle = buf->handle;
-}
-
-void FramebufferSurface::freeBufferLocked(int slotIndex) {
- ConsumerBase::freeBufferLocked(slotIndex);
- if (slotIndex == mCurrentBufferSlot) {
- mCurrentBufferSlot = BufferQueue::INVALID_BUFFER_SLOT;
- }
-}
-
-status_t FramebufferSurface::setReleaseFenceFd(int fenceFd) {
- status_t err = NO_ERROR;
- if (fenceFd >= 0) {
- sp<Fence> fence(new Fence(fenceFd));
- if (mCurrentBufferSlot != BufferQueue::INVALID_BUFFER_SLOT) {
-#if ANDROID_VERSION >= 19
- status_t err = addReleaseFence(mCurrentBufferSlot, mCurrentBuffer, fence);
-#else
- status_t err = addReleaseFence(mCurrentBufferSlot, fence);
-#endif
- ALOGE_IF(err, "setReleaseFenceFd: failed to add the fence: %s (%d)",
- strerror(-err), err);
- }
- }
- return err;
-}
-
-int FramebufferSurface::GetPrevDispAcquireFd() {
- if (mPrevFBAcquireFence.get() && mPrevFBAcquireFence->isValid()) {
- return mPrevFBAcquireFence->dup();
- }
- return -1;
-}
-
-void FramebufferSurface::onFrameCommitted() {
- // XXX This role is almost same to setReleaseFenceFd().
-}
-
-status_t FramebufferSurface::compositionComplete()
-{
- // Actual implementaiton is in GonkDisplay::SwapBuffers()
- // XXX need to move that to here.
- return NO_ERROR;
-}
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-// ----------------------------------------------------------------------------
diff --git a/widget/gonk/libdisplay/FramebufferSurface.h b/widget/gonk/libdisplay/FramebufferSurface.h
deleted file mode 100644
index c1cc84272..000000000
--- a/widget/gonk/libdisplay/FramebufferSurface.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_SF_FRAMEBUFFER_SURFACE_H
-#define ANDROID_SF_FRAMEBUFFER_SURFACE_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include "DisplaySurface.h"
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class Rect;
-class String8;
-
-// ---------------------------------------------------------------------------
-
-class FramebufferSurface : public DisplaySurface {
-public:
- FramebufferSurface(int disp, uint32_t width, uint32_t height, uint32_t format, const sp<StreamConsumer>& sc);
-
- // From DisplaySurface
- virtual status_t beginFrame(bool mustRecompose);
- virtual status_t prepareFrame(CompositionType compositionType);
- virtual status_t compositionComplete();
- virtual status_t advanceFrame();
- virtual void onFrameCommitted();
- // Cannot resize a buffers in a FramebufferSurface. Only works with virtual
- // displays.
- virtual void resizeBuffers(const uint32_t /*w*/, const uint32_t /*h*/) { };
-
- // setReleaseFenceFd stores a fence file descriptor that will signal when the
- // current buffer is no longer being read. This fence will be returned to
- // the producer when the current buffer is released by updateTexImage().
- // Multiple fences can be set for a given buffer; they will be merged into
- // a single union fence. The SurfaceTexture will close the file descriptor
- // when finished with it.
- status_t setReleaseFenceFd(int fenceFd);
-
- virtual int GetPrevDispAcquireFd();
-
-private:
- virtual ~FramebufferSurface() { }; // this class cannot be overloaded
-
-#if ANDROID_VERSION >= 22
- virtual void onFrameAvailable(const ::android::BufferItem &item);
-#else
- virtual void onFrameAvailable();
-#endif
- virtual void freeBufferLocked(int slotIndex);
-
- // nextBuffer waits for and then latches the next buffer from the
- // BufferQueue and releases the previously latched buffer to the
- // BufferQueue. The new buffer is returned in the 'buffer' argument.
- status_t nextBuffer(sp<GraphicBuffer>& outBuffer, sp<Fence>& outFence);
-
- // mDisplayType must match one of the HWC display types
- int mDisplayType;
-
- // mCurrentBufferIndex is the slot index of the current buffer or
- // INVALID_BUFFER_SLOT to indicate that either there is no current buffer
- // or the buffer is not associated with a slot.
- int mCurrentBufferSlot;
-
- // mCurrentBuffer is the current buffer or NULL to indicate that there is
- // no current buffer.
- sp<GraphicBuffer> mCurrentBuffer;
-
- android::sp<android::Fence> mPrevFBAcquireFence;
-};
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_SF_FRAMEBUFFER_SURFACE_H
-
diff --git a/widget/gonk/libdisplay/GonkDisplay.h b/widget/gonk/libdisplay/GonkDisplay.h
deleted file mode 100644
index 96978a6e9..000000000
--- a/widget/gonk/libdisplay/GonkDisplay.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/* Copyright 2013 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef GONKDISPLAY_H
-#define GONKDISPLAY_H
-
-#include <system/window.h>
-#include <utils/StrongPointer.h>
-#include "mozilla/Types.h"
-
-namespace android {
-class DisplaySurface;
-class IGraphicBufferProducer;
-}
-
-namespace mozilla {
-
-typedef void * EGLDisplay;
-typedef void * EGLSurface;
-
-class MOZ_EXPORT GonkDisplay {
-public:
- /**
- * This enum is for types of display. DISPLAY_PRIMARY refers to the default
- * built-in display, DISPLAY_EXTERNAL refers to displays connected with
- * HDMI, and DISPLAY_VIRTUAL are displays which makes composited output
- * available within the system. Currently, displays of external are detected
- * via the hotplug detection in HWC, and displays of virtual are connected
- * via Wifi Display.
- */
- enum DisplayType {
- DISPLAY_PRIMARY,
- DISPLAY_EXTERNAL,
- DISPLAY_VIRTUAL,
- NUM_DISPLAY_TYPES
- };
-
- struct NativeData {
- android::sp<ANativeWindow> mNativeWindow;
-#if ANDROID_VERSION >= 17
- android::sp<android::DisplaySurface> mDisplaySurface;
-#endif
- float mXdpi;
- };
-
- virtual void SetEnabled(bool enabled) = 0;
-
- typedef void (*OnEnabledCallbackType)(bool enabled);
-
- virtual void OnEnabled(OnEnabledCallbackType callback) = 0;
-
- virtual void* GetHWCDevice() = 0;
-
- /**
- * Only GonkDisplayICS uses arguments.
- */
- virtual bool SwapBuffers(EGLDisplay dpy, EGLSurface sur) = 0;
-
- virtual ANativeWindowBuffer* DequeueBuffer() = 0;
-
- virtual bool QueueBuffer(ANativeWindowBuffer* buf) = 0;
-
- virtual void UpdateDispSurface(EGLDisplay dpy, EGLSurface sur) = 0;
-
- virtual NativeData GetNativeData(
- GonkDisplay::DisplayType aDisplayType,
- android::IGraphicBufferProducer* aSink = nullptr) = 0;
-
- virtual void NotifyBootAnimationStopped() = 0;
-
- float xdpi;
- int32_t surfaceformat;
-};
-
-MOZ_EXPORT __attribute__ ((weak))
-GonkDisplay* GetGonkDisplay();
-
-}
-#endif /* GONKDISPLAY_H */
diff --git a/widget/gonk/libdisplay/GonkDisplayJB.cpp b/widget/gonk/libdisplay/GonkDisplayJB.cpp
deleted file mode 100644
index 197b85a47..000000000
--- a/widget/gonk/libdisplay/GonkDisplayJB.cpp
+++ /dev/null
@@ -1,461 +0,0 @@
-/* Copyright 2013 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "GonkDisplayJB.h"
-#if ANDROID_VERSION == 17
-#include <gui/SurfaceTextureClient.h>
-#else
-#include <gui/Surface.h>
-#include <gui/GraphicBufferAlloc.h>
-#endif
-
-#include <hardware/hardware.h>
-#include <hardware/hwcomposer.h>
-#include <hardware/power.h>
-#include <suspend/autosuspend.h>
-
-#if ANDROID_VERSION >= 19
-#include "VirtualDisplaySurface.h"
-#endif
-#include "FramebufferSurface.h"
-#if ANDROID_VERSION == 17
-#include "GraphicBufferAlloc.h"
-#endif
-#include "mozilla/Assertions.h"
-
-#define DEFAULT_XDPI 75.0
-
-using namespace android;
-
-namespace mozilla {
-
-static GonkDisplayJB* sGonkDisplay = nullptr;
-
-GonkDisplayJB::GonkDisplayJB()
- : mModule(nullptr)
- , mFBModule(nullptr)
- , mHwc(nullptr)
- , mFBDevice(nullptr)
- , mPowerModule(nullptr)
- , mList(nullptr)
- , mWidth(0)
- , mHeight(0)
- , mEnabledCallback(nullptr)
-{
- int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &mFBModule);
- ALOGW_IF(err, "%s module not found", GRALLOC_HARDWARE_MODULE_ID);
- if (!err) {
- err = framebuffer_open(mFBModule, &mFBDevice);
- ALOGW_IF(err, "could not open framebuffer");
- }
-
- if (!err && mFBDevice) {
- mWidth = mFBDevice->width;
- mHeight = mFBDevice->height;
- xdpi = mFBDevice->xdpi;
- /* The emulator actually reports RGBA_8888, but EGL doesn't return
- * any matching configuration. We force RGBX here to fix it. */
- surfaceformat = HAL_PIXEL_FORMAT_RGBX_8888;
- }
-
- err = hw_get_module(HWC_HARDWARE_MODULE_ID, &mModule);
- ALOGW_IF(err, "%s module not found", HWC_HARDWARE_MODULE_ID);
- if (!err) {
- err = hwc_open_1(mModule, &mHwc);
- ALOGE_IF(err, "%s device failed to initialize (%s)",
- HWC_HARDWARE_COMPOSER, strerror(-err));
- }
-
- /* Fallback on the FB rendering path instead of trying to support HWC 1.0 */
- if (!err && mHwc->common.version == HWC_DEVICE_API_VERSION_1_0) {
- hwc_close_1(mHwc);
- mHwc = nullptr;
- }
-
- if (!err && mHwc) {
- if (mFBDevice) {
- framebuffer_close(mFBDevice);
- mFBDevice = nullptr;
- }
-
- int32_t values[3];
- const uint32_t attrs[] = {
- HWC_DISPLAY_WIDTH,
- HWC_DISPLAY_HEIGHT,
- HWC_DISPLAY_DPI_X,
- HWC_DISPLAY_NO_ATTRIBUTE
- };
- mHwc->getDisplayAttributes(mHwc, 0, 0, attrs, values);
-
- mWidth = values[0];
- mHeight = values[1];
- xdpi = values[2] / 1000.0f;
- surfaceformat = HAL_PIXEL_FORMAT_RGBA_8888;
- }
-
- err = hw_get_module(POWER_HARDWARE_MODULE_ID,
- (hw_module_t const**)&mPowerModule);
- if (!err)
- mPowerModule->init(mPowerModule);
- ALOGW_IF(err, "Couldn't load %s module (%s)", POWER_HARDWARE_MODULE_ID, strerror(-err));
-
- mAlloc = new GraphicBufferAlloc();
-
- CreateFramebufferSurface(mSTClient, mDispSurface, mWidth, mHeight);
-
- mList = (hwc_display_contents_1_t *)calloc(1, sizeof(*mList) + (sizeof(hwc_layer_1_t)*2));
-
- uint32_t usage = GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_COMPOSER;
- if (mFBDevice) {
- // If device uses fb, they can not use single buffer for boot animation
- mSTClient->perform(mSTClient.get(), NATIVE_WINDOW_SET_BUFFER_COUNT, 2);
- mSTClient->perform(mSTClient.get(), NATIVE_WINDOW_SET_USAGE, usage);
- } else if (mHwc) {
- PowerOnDisplay(HWC_DISPLAY_PRIMARY);
- // For devices w/ hwc v1.0 or no hwc, this buffer can not be created,
- // only create this buffer for devices w/ hwc version > 1.0.
- CreateFramebufferSurface(mBootAnimSTClient, mBootAnimDispSurface, mWidth, mHeight);
- }
-}
-
-GonkDisplayJB::~GonkDisplayJB()
-{
- if (mHwc)
- hwc_close_1(mHwc);
- if (mFBDevice)
- framebuffer_close(mFBDevice);
- free(mList);
-}
-
-void
-GonkDisplayJB::CreateFramebufferSurface(android::sp<ANativeWindow>& aNativeWindow,
- android::sp<android::DisplaySurface>& aDisplaySurface,
- uint32_t aWidth,
- uint32_t aHeight)
-{
-#if ANDROID_VERSION >= 21
- sp<IGraphicBufferProducer> producer;
- sp<IGraphicBufferConsumer> consumer;
- BufferQueue::createBufferQueue(&producer, &consumer, mAlloc);
-#elif ANDROID_VERSION >= 19
- sp<BufferQueue> consumer = new BufferQueue(mAlloc);
- sp<IGraphicBufferProducer> producer = consumer;
-#elif ANDROID_VERSION >= 18
- sp<BufferQueue> consumer = new BufferQueue(true, mAlloc);
- sp<IGraphicBufferProducer> producer = consumer;
-#else
- sp<BufferQueue> consumer = new BufferQueue(true, mAlloc);
-#endif
-
- aDisplaySurface = new FramebufferSurface(0, aWidth, aHeight, surfaceformat, consumer);
-
-#if ANDROID_VERSION == 17
- aNativeWindow = new SurfaceTextureClient(
- static_cast<sp<ISurfaceTexture>>(aDisplaySurface->getBufferQueue()));
-#else
- aNativeWindow = new Surface(producer);
-#endif
-}
-
-void
-GonkDisplayJB::CreateVirtualDisplaySurface(android::IGraphicBufferProducer* aSink,
- android::sp<ANativeWindow>& aNativeWindow,
- android::sp<android::DisplaySurface>& aDisplaySurface)
-{
-#if ANDROID_VERSION >= 21
- sp<IGraphicBufferProducer> producer;
- sp<IGraphicBufferConsumer> consumer;
- BufferQueue::createBufferQueue(&producer, &consumer, mAlloc);
-#elif ANDROID_VERSION >= 19
- sp<BufferQueue> consumer = new BufferQueue(mAlloc);
- sp<IGraphicBufferProducer> producer = consumer;
-#endif
-
-#if ANDROID_VERSION >= 19
- sp<VirtualDisplaySurface> virtualDisplay;
- virtualDisplay = new VirtualDisplaySurface(-1, aSink, producer, consumer, String8("VirtualDisplaySurface"));
- aDisplaySurface = virtualDisplay;
- aNativeWindow = new Surface(virtualDisplay);
-#endif
-}
-
-void
-GonkDisplayJB::SetEnabled(bool enabled)
-{
- if (enabled) {
- autosuspend_disable();
- mPowerModule->setInteractive(mPowerModule, true);
- }
-
- if (!enabled && mEnabledCallback) {
- mEnabledCallback(enabled);
- }
-
-#if ANDROID_VERSION >= 21
- if (mHwc) {
- if (mHwc->common.version >= HWC_DEVICE_API_VERSION_1_4) {
- mHwc->setPowerMode(mHwc, HWC_DISPLAY_PRIMARY,
- (enabled ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF));
- } else {
- mHwc->blank(mHwc, HWC_DISPLAY_PRIMARY, !enabled);
- }
- } else if (mFBDevice && mFBDevice->enableScreen) {
- mFBDevice->enableScreen(mFBDevice, enabled);
- }
-#else
- if (mHwc && mHwc->blank) {
- mHwc->blank(mHwc, HWC_DISPLAY_PRIMARY, !enabled);
- } else if (mFBDevice && mFBDevice->enableScreen) {
- mFBDevice->enableScreen(mFBDevice, enabled);
- }
-#endif
-
- if (enabled && mEnabledCallback) {
- mEnabledCallback(enabled);
- }
-
- if (!enabled) {
- autosuspend_enable();
- mPowerModule->setInteractive(mPowerModule, false);
- }
-}
-
-void
-GonkDisplayJB::OnEnabled(OnEnabledCallbackType callback)
-{
- mEnabledCallback = callback;
-}
-
-void*
-GonkDisplayJB::GetHWCDevice()
-{
- return mHwc;
-}
-
-bool
-GonkDisplayJB::SwapBuffers(EGLDisplay dpy, EGLSurface sur)
-{
- // Should be called when composition rendering is complete for a frame.
- // Only HWC v1.0 needs this call.
- // HWC > v1.0 case, do not call compositionComplete().
- // mFBDevice is present only when HWC is v1.0.
- if (mFBDevice && mFBDevice->compositionComplete) {
- mFBDevice->compositionComplete(mFBDevice);
- }
- return Post(mDispSurface->lastHandle, mDispSurface->GetPrevDispAcquireFd());
-}
-
-bool
-GonkDisplayJB::Post(buffer_handle_t buf, int fence)
-{
- if (!mHwc) {
- if (fence >= 0)
- close(fence);
- return !mFBDevice->post(mFBDevice, buf);
- }
-
- hwc_display_contents_1_t *displays[HWC_NUM_DISPLAY_TYPES] = {NULL};
- const hwc_rect_t r = { 0, 0, static_cast<int>(mWidth), static_cast<int>(mHeight) };
- displays[HWC_DISPLAY_PRIMARY] = mList;
- mList->retireFenceFd = -1;
- mList->numHwLayers = 2;
- mList->flags = HWC_GEOMETRY_CHANGED;
-#if ANDROID_VERSION >= 18
- mList->outbuf = nullptr;
- mList->outbufAcquireFenceFd = -1;
-#endif
- mList->hwLayers[0].compositionType = HWC_FRAMEBUFFER;
- mList->hwLayers[0].hints = 0;
- /* Skip this layer so the hwc module doesn't complain about null handles */
- mList->hwLayers[0].flags = HWC_SKIP_LAYER;
- mList->hwLayers[0].backgroundColor = {0};
- mList->hwLayers[0].acquireFenceFd = -1;
- mList->hwLayers[0].releaseFenceFd = -1;
- /* hwc module checks displayFrame even though it shouldn't */
- mList->hwLayers[0].displayFrame = r;
- mList->hwLayers[1].compositionType = HWC_FRAMEBUFFER_TARGET;
- mList->hwLayers[1].hints = 0;
- mList->hwLayers[1].flags = 0;
- mList->hwLayers[1].handle = buf;
- mList->hwLayers[1].transform = 0;
- mList->hwLayers[1].blending = HWC_BLENDING_NONE;
-#if ANDROID_VERSION >= 19
- if (mHwc->common.version >= HWC_DEVICE_API_VERSION_1_3) {
- mList->hwLayers[1].sourceCropf.left = 0;
- mList->hwLayers[1].sourceCropf.top = 0;
- mList->hwLayers[1].sourceCropf.right = mWidth;
- mList->hwLayers[1].sourceCropf.bottom = mHeight;
- } else {
- mList->hwLayers[1].sourceCrop = r;
- }
-#else
- mList->hwLayers[1].sourceCrop = r;
-#endif
- mList->hwLayers[1].displayFrame = r;
- mList->hwLayers[1].visibleRegionScreen.numRects = 1;
- mList->hwLayers[1].visibleRegionScreen.rects = &mList->hwLayers[1].displayFrame;
- mList->hwLayers[1].acquireFenceFd = fence;
- mList->hwLayers[1].releaseFenceFd = -1;
-#if ANDROID_VERSION >= 18
- mList->hwLayers[1].planeAlpha = 0xFF;
-#endif
- mHwc->prepare(mHwc, HWC_NUM_DISPLAY_TYPES, displays);
- int err = mHwc->set(mHwc, HWC_NUM_DISPLAY_TYPES, displays);
-
- if (!mBootAnimDispSurface.get()) {
- mDispSurface->setReleaseFenceFd(mList->hwLayers[1].releaseFenceFd);
- } else {
- mBootAnimDispSurface->setReleaseFenceFd(mList->hwLayers[1].releaseFenceFd);
- }
-
- if (mList->retireFenceFd >= 0)
- close(mList->retireFenceFd);
- return !err;
-}
-
-ANativeWindowBuffer*
-GonkDisplayJB::DequeueBuffer()
-{
- // Check for bootAnim or normal display flow.
- sp<ANativeWindow> nativeWindow =
- !mBootAnimSTClient.get() ? mSTClient : mBootAnimSTClient;
-
- ANativeWindowBuffer *buf;
- int fenceFd = -1;
- nativeWindow->dequeueBuffer(nativeWindow.get(), &buf, &fenceFd);
- sp<Fence> fence(new Fence(fenceFd));
-#if ANDROID_VERSION == 17
- fence->waitForever(1000, "GonkDisplayJB_DequeueBuffer");
- // 1000 is what Android uses. It is a warning timeout in ms.
- // This timeout was removed in ANDROID_VERSION 18.
-#else
- fence->waitForever("GonkDisplayJB_DequeueBuffer");
-#endif
- return buf;
-}
-
-bool
-GonkDisplayJB::QueueBuffer(ANativeWindowBuffer* buf)
-{
- bool success = false;
- int error = DoQueueBuffer(buf);
- // Check for bootAnim or normal display flow.
- if (!mBootAnimSTClient.get()) {
- success = Post(mDispSurface->lastHandle, mDispSurface->GetPrevDispAcquireFd());
- } else {
- success = Post(mBootAnimDispSurface->lastHandle, mBootAnimDispSurface->GetPrevDispAcquireFd());
- }
- return error == 0 && success;
-}
-
-int
-GonkDisplayJB::DoQueueBuffer(ANativeWindowBuffer* buf)
-{
- int error = 0;
- // Check for bootAnim or normal display flow.
- if (!mBootAnimSTClient.get()) {
- error = mSTClient->queueBuffer(mSTClient.get(), buf, -1);
- } else {
- error = mBootAnimSTClient->queueBuffer(mBootAnimSTClient.get(), buf, -1);
- }
- return error;
-}
-
-void
-GonkDisplayJB::UpdateDispSurface(EGLDisplay dpy, EGLSurface sur)
-{
- if (sur != EGL_NO_SURFACE) {
- eglSwapBuffers(dpy, sur);
- } else {
- // When BasicCompositor is used as Compositor,
- // EGLSurface does not exit.
- ANativeWindowBuffer* buf = DequeueBuffer();
- DoQueueBuffer(buf);
- }
-}
-
-void
-GonkDisplayJB::NotifyBootAnimationStopped()
-{
- if (mBootAnimSTClient.get()) {
- mBootAnimSTClient = nullptr;
- mBootAnimDispSurface = nullptr;
- }
-}
-
-void
-GonkDisplayJB::PowerOnDisplay(int aDpy)
-{
- MOZ_ASSERT(mHwc);
-#if ANDROID_VERSION >= 21
- if (mHwc->common.version >= HWC_DEVICE_API_VERSION_1_4) {
- mHwc->setPowerMode(mHwc, aDpy, HWC_POWER_MODE_NORMAL);
- } else {
- mHwc->blank(mHwc, aDpy, 0);
- }
-#else
- mHwc->blank(mHwc, aDpy, 0);
-#endif
-}
-
-GonkDisplay::NativeData
-GonkDisplayJB::GetNativeData(GonkDisplay::DisplayType aDisplayType,
- android::IGraphicBufferProducer* aSink)
-{
- NativeData data;
-
- if (aDisplayType == DISPLAY_PRIMARY) {
- data.mNativeWindow = mSTClient;
- data.mDisplaySurface = mDispSurface;
- data.mXdpi = xdpi;
- } else if (aDisplayType == DISPLAY_EXTERNAL) {
- int32_t values[3];
- const uint32_t attrs[] = {
- HWC_DISPLAY_WIDTH,
- HWC_DISPLAY_HEIGHT,
- HWC_DISPLAY_DPI_X,
- HWC_DISPLAY_NO_ATTRIBUTE
- };
- mHwc->getDisplayAttributes(mHwc, aDisplayType, 0, attrs, values);
- int width = values[0];
- int height = values[1];
- // FIXME!! values[2] returns 0 for external display, which doesn't
- // sound right, Bug 1169176 is the follow-up bug for this issue.
- data.mXdpi = values[2] ? values[2] / 1000.f : DEFAULT_XDPI;
- PowerOnDisplay(HWC_DISPLAY_EXTERNAL);
- CreateFramebufferSurface(data.mNativeWindow,
- data.mDisplaySurface,
- width,
- height);
- } else if (aDisplayType == DISPLAY_VIRTUAL) {
- data.mXdpi = xdpi;
- CreateVirtualDisplaySurface(aSink,
- data.mNativeWindow,
- data.mDisplaySurface);
- }
-
- return data;
-}
-
-__attribute__ ((visibility ("default")))
-GonkDisplay*
-GetGonkDisplay()
-{
- if (!sGonkDisplay)
- sGonkDisplay = new GonkDisplayJB();
- return sGonkDisplay;
-}
-
-} // namespace mozilla
diff --git a/widget/gonk/libdisplay/GonkDisplayJB.h b/widget/gonk/libdisplay/GonkDisplayJB.h
deleted file mode 100644
index 60bcdffc4..000000000
--- a/widget/gonk/libdisplay/GonkDisplayJB.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/* Copyright 2013 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef GONKDISPLAYJB_H
-#define GONKDISPLAYJB_H
-
-#include "DisplaySurface.h"
-#include "GonkDisplay.h"
-#include "hardware/hwcomposer.h"
-#include "hardware/power.h"
-#include "ui/Fence.h"
-#include "utils/RefBase.h"
-
-namespace mozilla {
-
-class MOZ_EXPORT GonkDisplayJB : public GonkDisplay {
-public:
- GonkDisplayJB();
- ~GonkDisplayJB();
-
- virtual void SetEnabled(bool enabled);
-
- virtual void OnEnabled(OnEnabledCallbackType callback);
-
- virtual void* GetHWCDevice();
-
- virtual bool SwapBuffers(EGLDisplay dpy, EGLSurface sur);
-
- virtual ANativeWindowBuffer* DequeueBuffer();
-
- virtual bool QueueBuffer(ANativeWindowBuffer* buf);
-
- virtual void UpdateDispSurface(EGLDisplay dpy, EGLSurface sur);
-
- bool Post(buffer_handle_t buf, int fence);
-
- virtual NativeData GetNativeData(
- GonkDisplay::DisplayType aDisplayType,
- android::IGraphicBufferProducer* aSink = nullptr);
-
- virtual void NotifyBootAnimationStopped();
-
-private:
- void CreateFramebufferSurface(android::sp<ANativeWindow>& aNativeWindow,
- android::sp<android::DisplaySurface>& aDisplaySurface,
- uint32_t aWidth, uint32_t aHeight);
- void CreateVirtualDisplaySurface(android::IGraphicBufferProducer* aSink,
- android::sp<ANativeWindow>& aNativeWindow,
- android::sp<android::DisplaySurface>& aDisplaySurface);
-
- void PowerOnDisplay(int aDpy);
-
- int DoQueueBuffer(ANativeWindowBuffer* buf);
-
- hw_module_t const* mModule;
- hw_module_t const* mFBModule;
- hwc_composer_device_1_t* mHwc;
- framebuffer_device_t* mFBDevice;
- power_module_t* mPowerModule;
- android::sp<android::DisplaySurface> mDispSurface;
- android::sp<ANativeWindow> mSTClient;
- android::sp<android::DisplaySurface> mBootAnimDispSurface;
- android::sp<ANativeWindow> mBootAnimSTClient;
- android::sp<android::IGraphicBufferAlloc> mAlloc;
- hwc_display_contents_1_t* mList;
- uint32_t mWidth;
- uint32_t mHeight;
- OnEnabledCallbackType mEnabledCallback;
-};
-
-}
-
-#endif /* GONKDISPLAYJB_H */
diff --git a/widget/gonk/libdisplay/GraphicBufferAlloc.cpp b/widget/gonk/libdisplay/GraphicBufferAlloc.cpp
deleted file mode 100644
index 5722b7fe3..000000000
--- a/widget/gonk/libdisplay/GraphicBufferAlloc.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- **
- ** Copyright 2012 The Android Open Source Project
- **
- ** Licensed under the Apache License Version 2.0(the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- ** http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing software
- ** distributed under the License is distributed on an "AS IS" BASIS
- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied.
- ** See the License for the specific language governing permissions and
- ** limitations under the License.
- */
-
-#include <cutils/log.h>
-
-#include <ui/GraphicBuffer.h>
-
-#include "GraphicBufferAlloc.h"
-
-// ----------------------------------------------------------------------------
-namespace android {
-// ----------------------------------------------------------------------------
-
-GraphicBufferAlloc::GraphicBufferAlloc() {
-}
-
-GraphicBufferAlloc::~GraphicBufferAlloc() {
-}
-
-sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
- PixelFormat format, uint32_t usage, status_t* error) {
- sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
- status_t err = graphicBuffer->initCheck();
- *error = err;
- if (err != 0 || graphicBuffer->handle == 0) {
- if (err == NO_MEMORY) {
- GraphicBuffer::dumpAllocationsToSystemLog();
- }
- ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
- "failed (%s), handle=%p",
- w, h, strerror(-err), graphicBuffer->handle);
- return 0;
- }
- return graphicBuffer;
-}
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-// ----------------------------------------------------------------------------
diff --git a/widget/gonk/libdisplay/GraphicBufferAlloc.h b/widget/gonk/libdisplay/GraphicBufferAlloc.h
deleted file mode 100644
index b08750c2f..000000000
--- a/widget/gonk/libdisplay/GraphicBufferAlloc.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_SF_GRAPHIC_BUFFER_ALLOC_H
-#define ANDROID_SF_GRAPHIC_BUFFER_ALLOC_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <gui/IGraphicBufferAlloc.h>
-#include <ui/PixelFormat.h>
-#include <utils/Errors.h>
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-class GraphicBuffer;
-
-class GraphicBufferAlloc : public BnGraphicBufferAlloc {
-public:
- GraphicBufferAlloc();
- virtual ~GraphicBufferAlloc();
- virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
- PixelFormat format, uint32_t usage, status_t* error);
-};
-
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_SF_GRAPHIC_BUFFER_ALLOC_H
diff --git a/widget/gonk/libdisplay/VirtualDisplaySurface.cpp b/widget/gonk/libdisplay/VirtualDisplaySurface.cpp
deleted file mode 100644
index 746707885..000000000
--- a/widget/gonk/libdisplay/VirtualDisplaySurface.cpp
+++ /dev/null
@@ -1,635 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// #define LOG_NDEBUG 0
-#include "VirtualDisplaySurface.h"
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-#if defined(FORCE_HWC_COPY_FOR_VIRTUAL_DISPLAYS)
-static const bool sForceHwcCopy = true;
-#else
-static const bool sForceHwcCopy = false;
-#endif
-
-#define VDS_LOGE(msg, ...) ALOGE("[%s] " msg, \
- mDisplayName.string(), ##__VA_ARGS__)
-#define VDS_LOGW_IF(cond, msg, ...) ALOGW_IF(cond, "[%s] " msg, \
- mDisplayName.string(), ##__VA_ARGS__)
-#define VDS_LOGV(msg, ...) ALOGV("[%s] " msg, \
- mDisplayName.string(), ##__VA_ARGS__)
-
-__attribute__((unused))
-static const char* dbgCompositionTypeStr(DisplaySurface::CompositionType type) {
- switch (type) {
- case DisplaySurface::COMPOSITION_UNKNOWN: return "UNKNOWN";
- case DisplaySurface::COMPOSITION_GLES: return "GLES";
- case DisplaySurface::COMPOSITION_HWC: return "HWC";
- case DisplaySurface::COMPOSITION_MIXED: return "MIXED";
- default: return "<INVALID>";
- }
-}
-
-VirtualDisplaySurface::VirtualDisplaySurface(int32_t dispId,
- const sp<IGraphicBufferProducer>& sink,
- const sp<IGraphicBufferProducer>& bqProducer,
- const sp<StreamConsumer>& bqConsumer,
- const String8& name)
-: DisplaySurface(bqConsumer),
- mDisplayId(dispId),
- mDisplayName(name),
- mOutputUsage(GRALLOC_USAGE_HW_COMPOSER),
- mProducerSlotSource(0),
- mDbgState(DBG_STATE_IDLE),
- mDbgLastCompositionType(COMPOSITION_UNKNOWN),
- mMustRecompose(false)
-{
- mSource[SOURCE_SINK] = sink;
- mSource[SOURCE_SCRATCH] = bqProducer;
-
- resetPerFrameState();
-
- int sinkWidth, sinkHeight;
- sink->query(NATIVE_WINDOW_WIDTH, &sinkWidth);
- sink->query(NATIVE_WINDOW_HEIGHT, &sinkHeight);
- mSinkBufferWidth = sinkWidth;
- mSinkBufferHeight = sinkHeight;
-
- // Pick the buffer format to request from the sink when not rendering to it
- // with GLES. If the consumer needs CPU access, use the default format
- // set by the consumer. Otherwise allow gralloc to decide the format based
- // on usage bits.
- int sinkUsage;
- sink->query(NATIVE_WINDOW_CONSUMER_USAGE_BITS, &sinkUsage);
- if (sinkUsage & (GRALLOC_USAGE_SW_READ_MASK | GRALLOC_USAGE_SW_WRITE_MASK)) {
- int sinkFormat;
- sink->query(NATIVE_WINDOW_FORMAT, &sinkFormat);
- mDefaultOutputFormat = sinkFormat;
- } else {
- mDefaultOutputFormat = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
- }
- mOutputFormat = mDefaultOutputFormat;
-
- ConsumerBase::mName = String8::format("VDS: %s", mDisplayName.string());
- mConsumer->setConsumerName(ConsumerBase::mName);
- mConsumer->setConsumerUsageBits(GRALLOC_USAGE_HW_COMPOSER);
- mConsumer->setDefaultBufferSize(sinkWidth, sinkHeight);
- mConsumer->setDefaultMaxBufferCount(2);
-}
-
-VirtualDisplaySurface::~VirtualDisplaySurface() {
-}
-
-status_t VirtualDisplaySurface::beginFrame(bool mustRecompose) {
- if (mDisplayId < 0)
- return NO_ERROR;
-
- mMustRecompose = mustRecompose;
-
- VDS_LOGW_IF(mDbgState != DBG_STATE_IDLE,
- "Unexpected beginFrame() in %s state", dbgStateStr());
- mDbgState = DBG_STATE_BEGUN;
-
- return refreshOutputBuffer();
-}
-
-status_t VirtualDisplaySurface::prepareFrame(CompositionType compositionType) {
- if (mDisplayId < 0)
- return NO_ERROR;
-
- VDS_LOGW_IF(mDbgState != DBG_STATE_BEGUN,
- "Unexpected prepareFrame() in %s state", dbgStateStr());
- mDbgState = DBG_STATE_PREPARED;
-
- mCompositionType = compositionType;
- if (sForceHwcCopy && mCompositionType == COMPOSITION_GLES) {
- // Some hardware can do RGB->YUV conversion more efficiently in hardware
- // controlled by HWC than in hardware controlled by the video encoder.
- // Forcing GLES-composed frames to go through an extra copy by the HWC
- // allows the format conversion to happen there, rather than passing RGB
- // directly to the consumer.
- //
- // On the other hand, when the consumer prefers RGB or can consume RGB
- // inexpensively, this forces an unnecessary copy.
- mCompositionType = COMPOSITION_MIXED;
- }
-
- if (mCompositionType != mDbgLastCompositionType) {
- VDS_LOGV("prepareFrame: composition type changed to %s",
- dbgCompositionTypeStr(mCompositionType));
- mDbgLastCompositionType = mCompositionType;
- }
-
- if (mCompositionType != COMPOSITION_GLES &&
- (mOutputFormat != mDefaultOutputFormat ||
- mOutputUsage != GRALLOC_USAGE_HW_COMPOSER)) {
- // We must have just switched from GLES-only to MIXED or HWC
- // composition. Stop using the format and usage requested by the GLES
- // driver; they may be suboptimal when HWC is writing to the output
- // buffer. For example, if the output is going to a video encoder, and
- // HWC can write directly to YUV, some hardware can skip a
- // memory-to-memory RGB-to-YUV conversion step.
- //
- // If we just switched *to* GLES-only mode, we'll change the
- // format/usage and get a new buffer when the GLES driver calls
- // dequeueBuffer().
- mOutputFormat = mDefaultOutputFormat;
- mOutputUsage = GRALLOC_USAGE_HW_COMPOSER;
- refreshOutputBuffer();
- }
-
- return NO_ERROR;
-}
-
-status_t VirtualDisplaySurface::compositionComplete() {
- return NO_ERROR;
-}
-
-status_t VirtualDisplaySurface::advanceFrame() {
- return NO_ERROR;
-
-// XXX Add HWC support
-
-#if 0
- if (mDisplayId < 0)
- return NO_ERROR;
-
- if (mCompositionType == COMPOSITION_HWC) {
- VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
- "Unexpected advanceFrame() in %s state on HWC frame",
- dbgStateStr());
- } else {
- VDS_LOGW_IF(mDbgState != DBG_STATE_GLES_DONE,
- "Unexpected advanceFrame() in %s state on GLES/MIXED frame",
- dbgStateStr());
- }
- mDbgState = DBG_STATE_HWC;
-
- if (mOutputProducerSlot < 0 ||
- (mCompositionType != COMPOSITION_HWC && mFbProducerSlot < 0)) {
- // Last chance bailout if something bad happened earlier. For example,
- // in a GLES configuration, if the sink disappears then dequeueBuffer
- // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
- // will soldier on. So we end up here without a buffer. There should
- // be lots of scary messages in the log just before this.
- VDS_LOGE("advanceFrame: no buffer, bailing out");
- return NO_MEMORY;
- }
-
- sp<GraphicBuffer> fbBuffer = mFbProducerSlot >= 0 ?
- mProducerBuffers[mFbProducerSlot] : sp<GraphicBuffer>(NULL);
- sp<GraphicBuffer> outBuffer = mProducerBuffers[mOutputProducerSlot];
- VDS_LOGV("advanceFrame: fb=%d(%p) out=%d(%p)",
- mFbProducerSlot, fbBuffer.get(),
- mOutputProducerSlot, outBuffer.get());
-
- // At this point we know the output buffer acquire fence,
- // so update HWC state with it.
- mHwc.setOutputBuffer(mDisplayId, mOutputFence, outBuffer);
-
- status_t result = NO_ERROR;
- if (fbBuffer != NULL) {
- result = mHwc.fbPost(mDisplayId, mFbFence, fbBuffer);
- }
-
- return result;
-#endif
-}
-
-void VirtualDisplaySurface::onFrameCommitted() {
- return;
-
-// XXX Add HWC support
-
-#if 0
- if (mDisplayId < 0)
- return;
-
- VDS_LOGW_IF(mDbgState != DBG_STATE_HWC,
- "Unexpected onFrameCommitted() in %s state", dbgStateStr());
- mDbgState = DBG_STATE_IDLE;
-
- sp<Fence> fbFence = mHwc.getAndResetReleaseFence(mDisplayId);
- if (mCompositionType == COMPOSITION_MIXED && mFbProducerSlot >= 0) {
- // release the scratch buffer back to the pool
- Mutex::Autolock lock(mMutex);
- int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, mFbProducerSlot);
- VDS_LOGV("onFrameCommitted: release scratch sslot=%d", sslot);
- addReleaseFenceLocked(sslot, mProducerBuffers[mFbProducerSlot], fbFence);
- releaseBufferLocked(sslot, mProducerBuffers[mFbProducerSlot],
- EGL_NO_DISPLAY, EGL_NO_SYNC_KHR);
- }
-
- if (mOutputProducerSlot >= 0) {
- int sslot = mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot);
- QueueBufferOutput qbo;
- sp<Fence> outFence = mHwc.getLastRetireFence(mDisplayId);
- VDS_LOGV("onFrameCommitted: queue sink sslot=%d", sslot);
- if (mMustRecompose) {
- status_t result = mSource[SOURCE_SINK]->queueBuffer(sslot,
- QueueBufferInput(
- systemTime(), false /* isAutoTimestamp */,
- Rect(mSinkBufferWidth, mSinkBufferHeight),
- NATIVE_WINDOW_SCALING_MODE_FREEZE, 0 /* transform */,
- true /* async*/,
- outFence),
- &qbo);
- if (result == NO_ERROR) {
- updateQueueBufferOutput(qbo);
- }
- } else {
- // If the surface hadn't actually been updated, then we only went
- // through the motions of updating the display to keep our state
- // machine happy. We cancel the buffer to avoid triggering another
- // re-composition and causing an infinite loop.
- mSource[SOURCE_SINK]->cancelBuffer(sslot, outFence);
- }
- }
-
- resetPerFrameState();
-#endif
-}
-
-void VirtualDisplaySurface::resizeBuffers(const uint32_t w, const uint32_t h) {
- uint32_t tmpW, tmpH, transformHint, numPendingBuffers;
- mQueueBufferOutput.deflate(&tmpW, &tmpH, &transformHint, &numPendingBuffers);
- mQueueBufferOutput.inflate(w, h, transformHint, numPendingBuffers);
-
- mSinkBufferWidth = w;
- mSinkBufferHeight = h;
-}
-
-status_t VirtualDisplaySurface::requestBuffer(int pslot,
- sp<GraphicBuffer>* outBuf) {
- if (mDisplayId < 0)
- return mSource[SOURCE_SINK]->requestBuffer(pslot, outBuf);
-
- VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
- "Unexpected requestBuffer pslot=%d in %s state",
- pslot, dbgStateStr());
-
- *outBuf = mProducerBuffers[pslot];
- return NO_ERROR;
-}
-
-status_t VirtualDisplaySurface::setBufferCount(int bufferCount) {
- return mSource[SOURCE_SINK]->setBufferCount(bufferCount);
-}
-
-status_t VirtualDisplaySurface::dequeueBuffer(Source source,
- uint32_t format, uint32_t usage, int* sslot, sp<Fence>* fence) {
- LOG_FATAL_IF(mDisplayId < 0, "mDisplayId=%d but should not be < 0.", mDisplayId);
- // Don't let a slow consumer block us
- bool async = (source == SOURCE_SINK);
-
- status_t result = mSource[source]->dequeueBuffer(sslot, fence, async,
- mSinkBufferWidth, mSinkBufferHeight, format, usage);
- if (result < 0)
- return result;
- int pslot = mapSource2ProducerSlot(source, *sslot);
- VDS_LOGV("dequeueBuffer(%s): sslot=%d pslot=%d result=%d",
- dbgSourceStr(source), *sslot, pslot, result);
- uint64_t sourceBit = static_cast<uint64_t>(source) << pslot;
-
- if ((mProducerSlotSource & (1ULL << pslot)) != sourceBit) {
- // This slot was previously dequeued from the other source; must
- // re-request the buffer.
- result |= BUFFER_NEEDS_REALLOCATION;
- mProducerSlotSource &= ~(1ULL << pslot);
- mProducerSlotSource |= sourceBit;
- }
-
- if (result & RELEASE_ALL_BUFFERS) {
- for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
- if ((mProducerSlotSource & (1ULL << i)) == sourceBit)
- mProducerBuffers[i].clear();
- }
- }
- if (result & BUFFER_NEEDS_REALLOCATION) {
- result = mSource[source]->requestBuffer(*sslot, &mProducerBuffers[pslot]);
- if (result < 0) {
- mProducerBuffers[pslot].clear();
- mSource[source]->cancelBuffer(*sslot, *fence);
- return result;
- }
- VDS_LOGV("dequeueBuffer(%s): buffers[%d]=%p fmt=%d usage=%#x",
- dbgSourceStr(source), pslot, mProducerBuffers[pslot].get(),
- mProducerBuffers[pslot]->getPixelFormat(),
- mProducerBuffers[pslot]->getUsage());
- }
-
- return result;
-}
-
-status_t VirtualDisplaySurface::dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
- uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
- if (mDisplayId < 0)
- return mSource[SOURCE_SINK]->dequeueBuffer(pslot, fence, async, w, h, format, usage);
-
- VDS_LOGW_IF(mDbgState != DBG_STATE_PREPARED,
- "Unexpected dequeueBuffer() in %s state", dbgStateStr());
- mDbgState = DBG_STATE_GLES;
-
- VDS_LOGW_IF(!async, "EGL called dequeueBuffer with !async despite eglSwapInterval(0)");
- VDS_LOGV("dequeueBuffer %dx%d fmt=%d usage=%#x", w, h, format, usage);
-
- status_t result = NO_ERROR;
- Source source = fbSourceForCompositionType(mCompositionType);
-
- if (source == SOURCE_SINK) {
-
- if (mOutputProducerSlot < 0) {
- // Last chance bailout if something bad happened earlier. For example,
- // in a GLES configuration, if the sink disappears then dequeueBuffer
- // will fail, the GLES driver won't queue a buffer, but SurfaceFlinger
- // will soldier on. So we end up here without a buffer. There should
- // be lots of scary messages in the log just before this.
- VDS_LOGE("dequeueBuffer: no buffer, bailing out");
- return NO_MEMORY;
- }
-
- // We already dequeued the output buffer. If the GLES driver wants
- // something incompatible, we have to cancel and get a new one. This
- // will mean that HWC will see a different output buffer between
- // prepare and set, but since we're in GLES-only mode already it
- // shouldn't matter.
-
- usage |= GRALLOC_USAGE_HW_COMPOSER;
- const sp<GraphicBuffer>& buf = mProducerBuffers[mOutputProducerSlot];
- if ((usage & ~buf->getUsage()) != 0 ||
- (format != 0 && format != (uint32_t)buf->getPixelFormat()) ||
- (w != 0 && w != mSinkBufferWidth) ||
- (h != 0 && h != mSinkBufferHeight)) {
- VDS_LOGV("dequeueBuffer: dequeueing new output buffer: "
- "want %dx%d fmt=%d use=%#x, "
- "have %dx%d fmt=%d use=%#x",
- w, h, format, usage,
- mSinkBufferWidth, mSinkBufferHeight,
- buf->getPixelFormat(), buf->getUsage());
- mOutputFormat = format;
- mOutputUsage = usage;
- result = refreshOutputBuffer();
- if (result < 0)
- return result;
- }
- }
-
- if (source == SOURCE_SINK) {
- *pslot = mOutputProducerSlot;
- *fence = mOutputFence;
- } else {
- int sslot;
- result = dequeueBuffer(source, format, usage, &sslot, fence);
- if (result >= 0) {
- *pslot = mapSource2ProducerSlot(source, sslot);
- }
- }
- return result;
-}
-
-status_t VirtualDisplaySurface::detachBuffer(int /* slot */) {
- VDS_LOGE("detachBuffer is not available for VirtualDisplaySurface");
- return INVALID_OPERATION;
-}
-
-status_t VirtualDisplaySurface::detachNextBuffer(
- sp<GraphicBuffer>* /* outBuffer */, sp<Fence>* /* outFence */) {
- VDS_LOGE("detachNextBuffer is not available for VirtualDisplaySurface");
- return INVALID_OPERATION;
-}
-
-status_t VirtualDisplaySurface::attachBuffer(int* /* outSlot */,
- const sp<GraphicBuffer>& /* buffer */) {
- VDS_LOGE("attachBuffer is not available for VirtualDisplaySurface");
- return INVALID_OPERATION;
-}
-
-status_t VirtualDisplaySurface::queueBuffer(int pslot,
- const QueueBufferInput& input, QueueBufferOutput* output) {
- if (mDisplayId < 0)
- return mSource[SOURCE_SINK]->queueBuffer(pslot, input, output);
-
- VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
- "Unexpected queueBuffer(pslot=%d) in %s state", pslot,
- dbgStateStr());
- mDbgState = DBG_STATE_GLES_DONE;
-
- VDS_LOGV("queueBuffer pslot=%d", pslot);
-
- status_t result;
- if (mCompositionType == COMPOSITION_MIXED) {
- // Queue the buffer back into the scratch pool
- QueueBufferOutput scratchQBO;
- int sslot = mapProducer2SourceSlot(SOURCE_SCRATCH, pslot);
- result = mSource[SOURCE_SCRATCH]->queueBuffer(sslot, input, &scratchQBO);
- if (result != NO_ERROR)
- return result;
-
- // Now acquire the buffer from the scratch pool -- should be the same
- // slot and fence as we just queued.
- Mutex::Autolock lock(mMutex);
- BufferQueue::BufferItem item;
- result = acquireBufferLocked(&item, 0);
- if (result != NO_ERROR)
- return result;
- VDS_LOGW_IF(item.mBuf != sslot,
- "queueBuffer: acquired sslot %d from SCRATCH after queueing sslot %d",
- item.mBuf, sslot);
- mFbProducerSlot = mapSource2ProducerSlot(SOURCE_SCRATCH, item.mBuf);
- mFbFence = mSlots[item.mBuf].mFence;
-
- } else {
- LOG_FATAL_IF(mCompositionType != COMPOSITION_GLES,
- "Unexpected queueBuffer in state %s for compositionType %s",
- dbgStateStr(), dbgCompositionTypeStr(mCompositionType));
-
- // Extract the GLES release fence for HWC to acquire
- int64_t timestamp;
- bool isAutoTimestamp;
- Rect crop;
- int scalingMode;
- uint32_t transform;
- bool async;
- input.deflate(&timestamp, &isAutoTimestamp, &crop, &scalingMode,
- &transform, &async, &mFbFence);
-
- mFbProducerSlot = pslot;
- mOutputFence = mFbFence;
- }
-
- *output = mQueueBufferOutput;
- return NO_ERROR;
-}
-
-void VirtualDisplaySurface::cancelBuffer(int pslot, const sp<Fence>& fence) {
- if (mDisplayId < 0)
- return mSource[SOURCE_SINK]->cancelBuffer(mapProducer2SourceSlot(SOURCE_SINK, pslot), fence);
-
- VDS_LOGW_IF(mDbgState != DBG_STATE_GLES,
- "Unexpected cancelBuffer(pslot=%d) in %s state", pslot,
- dbgStateStr());
- VDS_LOGV("cancelBuffer pslot=%d", pslot);
- Source source = fbSourceForCompositionType(mCompositionType);
- return mSource[source]->cancelBuffer(
- mapProducer2SourceSlot(source, pslot), fence);
-}
-
-int VirtualDisplaySurface::query(int what, int* value) {
- switch (what) {
- case NATIVE_WINDOW_WIDTH:
- *value = mSinkBufferWidth;
- break;
- case NATIVE_WINDOW_HEIGHT:
- *value = mSinkBufferHeight;
- break;
- default:
- return mSource[SOURCE_SINK]->query(what, value);
- }
- return NO_ERROR;
-}
-
-#if ANDROID_VERSION >= 21
-status_t VirtualDisplaySurface::connect(const sp<IProducerListener>& listener,
- int api, bool producerControlledByApp,
- QueueBufferOutput* output) {
- QueueBufferOutput qbo;
- status_t result = mSource[SOURCE_SINK]->connect(listener, api,
- producerControlledByApp, &qbo);
- if (result == NO_ERROR) {
- updateQueueBufferOutput(qbo);
- *output = mQueueBufferOutput;
- }
- return result;
-}
-#else
-status_t VirtualDisplaySurface::connect(const sp<IBinder>& token,
- int api, bool producerControlledByApp,
- QueueBufferOutput* output) {
- QueueBufferOutput qbo;
- status_t result = mSource[SOURCE_SINK]->connect(token, api, producerControlledByApp, &qbo);
- if (result == NO_ERROR) {
- updateQueueBufferOutput(qbo);
- *output = mQueueBufferOutput;
- }
- return result;
-}
-#endif
-
-status_t VirtualDisplaySurface::disconnect(int api) {
- return mSource[SOURCE_SINK]->disconnect(api);
-}
-
-#if ANDROID_VERSION >= 21
-status_t VirtualDisplaySurface::setSidebandStream(const sp<NativeHandle>& /*stream*/) {
- return INVALID_OPERATION;
-}
-#endif
-
-void VirtualDisplaySurface::allocateBuffers(bool /* async */,
- uint32_t /* width */, uint32_t /* height */, uint32_t /* format */,
- uint32_t /* usage */) {
- // TODO: Should we actually allocate buffers for a virtual display?
-}
-
-void VirtualDisplaySurface::updateQueueBufferOutput(
- const QueueBufferOutput& qbo) {
- uint32_t w, h, transformHint, numPendingBuffers;
- qbo.deflate(&w, &h, &transformHint, &numPendingBuffers);
- mQueueBufferOutput.inflate(w, h, 0, numPendingBuffers);
-}
-
-void VirtualDisplaySurface::resetPerFrameState() {
- mCompositionType = COMPOSITION_UNKNOWN;
- mFbFence = Fence::NO_FENCE;
- mOutputFence = Fence::NO_FENCE;
- mOutputProducerSlot = -1;
- mFbProducerSlot = -1;
-}
-
-status_t VirtualDisplaySurface::refreshOutputBuffer() {
-
- return INVALID_OPERATION;
-
-// XXX Add HWC support
-
-#if 0
- if (mOutputProducerSlot >= 0) {
- mSource[SOURCE_SINK]->cancelBuffer(
- mapProducer2SourceSlot(SOURCE_SINK, mOutputProducerSlot),
- mOutputFence);
- }
-
- int sslot;
- status_t result = dequeueBuffer(SOURCE_SINK, mOutputFormat, mOutputUsage,
- &sslot, &mOutputFence);
- if (result < 0)
- return result;
- mOutputProducerSlot = mapSource2ProducerSlot(SOURCE_SINK, sslot);
-
- // On GLES-only frames, we don't have the right output buffer acquire fence
- // until after GLES calls queueBuffer(). So here we just set the buffer
- // (for use in HWC prepare) but not the fence; we'll call this again with
- // the proper fence once we have it.
- result = mHwc.setOutputBuffer(mDisplayId, Fence::NO_FENCE,
- mProducerBuffers[mOutputProducerSlot]);
-
- return result;
-#endif
-}
-
-// This slot mapping function is its own inverse, so two copies are unnecessary.
-// Both are kept to make the intent clear where the function is called, and for
-// the (unlikely) chance that we switch to a different mapping function.
-int VirtualDisplaySurface::mapSource2ProducerSlot(Source source, int sslot) {
- if (source == SOURCE_SCRATCH) {
- return BufferQueue::NUM_BUFFER_SLOTS - sslot - 1;
- } else {
- return sslot;
- }
-}
-int VirtualDisplaySurface::mapProducer2SourceSlot(Source source, int pslot) {
- return mapSource2ProducerSlot(source, pslot);
-}
-
-VirtualDisplaySurface::Source
-VirtualDisplaySurface::fbSourceForCompositionType(CompositionType type) {
- return type == COMPOSITION_MIXED ? SOURCE_SCRATCH : SOURCE_SINK;
-}
-
-const char* VirtualDisplaySurface::dbgStateStr() const {
- switch (mDbgState) {
- case DBG_STATE_IDLE: return "IDLE";
- case DBG_STATE_PREPARED: return "PREPARED";
- case DBG_STATE_GLES: return "GLES";
- case DBG_STATE_GLES_DONE: return "GLES_DONE";
- case DBG_STATE_HWC: return "HWC";
- default: return "INVALID";
- }
-}
-
-const char* VirtualDisplaySurface::dbgSourceStr(Source s) {
- switch (s) {
- case SOURCE_SINK: return "SINK";
- case SOURCE_SCRATCH: return "SCRATCH";
- default: return "INVALID";
- }
-}
-
-// ---------------------------------------------------------------------------
-} // namespace android
-// ---------------------------------------------------------------------------
diff --git a/widget/gonk/libdisplay/VirtualDisplaySurface.h b/widget/gonk/libdisplay/VirtualDisplaySurface.h
deleted file mode 100644
index 9125d8751..000000000
--- a/widget/gonk/libdisplay/VirtualDisplaySurface.h
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * Copyright 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_SF_VIRTUAL_DISPLAY_SURFACE_H
-#define ANDROID_SF_VIRTUAL_DISPLAY_SURFACE_H
-
-#include <gui/IGraphicBufferProducer.h>
-
-#include "DisplaySurface.h"
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class HWComposer;
-class IProducerListener;
-
-/* This DisplaySurface implementation supports virtual displays, where GLES
- * and/or HWC compose into a buffer that is then passed to an arbitrary
- * consumer (the sink) running in another process.
- *
- * The simplest case is when the virtual display will never use the h/w
- * composer -- either the h/w composer doesn't support writing to buffers, or
- * there are more virtual displays than it supports simultaneously. In this
- * case, the GLES driver works directly with the output buffer queue, and
- * calls to the VirtualDisplay from SurfaceFlinger and DisplayHardware do
- * nothing.
- *
- * If h/w composer might be used, then each frame will fall into one of three
- * configurations: GLES-only, HWC-only, and MIXED composition. In all of these,
- * we must provide a FB target buffer and output buffer for the HWC set() call.
- *
- * In GLES-only composition, the GLES driver is given a buffer from the sink to
- * render into. When the GLES driver queues the buffer to the
- * VirtualDisplaySurface, the VirtualDisplaySurface holds onto it instead of
- * immediately queueing it to the sink. The buffer is used as both the FB
- * target and output buffer for HWC, though on these frames the HWC doesn't
- * do any work for this display and doesn't write to the output buffer. After
- * composition is complete, the buffer is queued to the sink.
- *
- * In HWC-only composition, the VirtualDisplaySurface dequeues a buffer from
- * the sink and passes it to HWC as both the FB target buffer and output
- * buffer. The HWC doesn't need to read from the FB target buffer, but does
- * write to the output buffer. After composition is complete, the buffer is
- * queued to the sink.
- *
- * On MIXED frames, things become more complicated, since some h/w composer
- * implementations can't read from and write to the same buffer. This class has
- * an internal BufferQueue that it uses as a scratch buffer pool. The GLES
- * driver is given a scratch buffer to render into. When it finishes rendering,
- * the buffer is queued and then immediately acquired by the
- * VirtualDisplaySurface. The scratch buffer is then used as the FB target
- * buffer for HWC, and a separate buffer is dequeued from the sink and used as
- * the HWC output buffer. When HWC composition is complete, the scratch buffer
- * is released and the output buffer is queued to the sink.
- */
-class VirtualDisplaySurface : public DisplaySurface,
- public BnGraphicBufferProducer {
-public:
- VirtualDisplaySurface(int32_t dispId,
- const sp<IGraphicBufferProducer>& sink,
- const sp<IGraphicBufferProducer>& bqProducer,
- const sp<StreamConsumer>& bqConsumer,
- const String8& name);
-
- //
- // DisplaySurface interface
- //
- virtual status_t beginFrame(bool mustRecompose);
- virtual status_t prepareFrame(CompositionType compositionType);
- virtual status_t compositionComplete();
- virtual status_t advanceFrame();
- virtual void onFrameCommitted();
- virtual void resizeBuffers(const uint32_t w, const uint32_t h);
-
- virtual status_t setReleaseFenceFd(int fenceFd) { return INVALID_OPERATION; }
- virtual int GetPrevDispAcquireFd() { return -1; };
-
-private:
- enum Source {SOURCE_SINK = 0, SOURCE_SCRATCH = 1};
-
- virtual ~VirtualDisplaySurface();
-
- //
- // IGraphicBufferProducer interface, used by the GLES driver.
- //
- virtual status_t requestBuffer(int pslot, sp<GraphicBuffer>* outBuf);
- virtual status_t setBufferCount(int bufferCount);
- virtual status_t dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
- uint32_t w, uint32_t h, uint32_t format, uint32_t usage);
- virtual status_t detachBuffer(int slot);
- virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
- sp<Fence>* outFence);
- virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer);
- virtual status_t queueBuffer(int pslot,
- const QueueBufferInput& input, QueueBufferOutput* output);
- virtual void cancelBuffer(int pslot, const sp<Fence>& fence);
- virtual int query(int what, int* value);
-#if ANDROID_VERSION >= 21
- virtual status_t connect(const sp<IProducerListener>& listener,
- int api, bool producerControlledByApp, QueueBufferOutput* output);
-#else
- virtual status_t connect(const sp<IBinder>& token,
- int api, bool producerControlledByApp, QueueBufferOutput* output);
-#endif
- virtual status_t disconnect(int api);
-#if ANDROID_VERSION >= 21
- virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
-#endif
- virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
- uint32_t format, uint32_t usage);
-
- //
- // Utility methods
- //
- static Source fbSourceForCompositionType(CompositionType type);
- status_t dequeueBuffer(Source source, uint32_t format, uint32_t usage,
- int* sslot, sp<Fence>* fence);
- void updateQueueBufferOutput(const QueueBufferOutput& qbo);
- void resetPerFrameState();
- status_t refreshOutputBuffer();
-
- // Both the sink and scratch buffer pools have their own set of slots
- // ("source slots", or "sslot"). We have to merge these into the single
- // set of slots used by the GLES producer ("producer slots" or "pslot") and
- // internally in the VirtualDisplaySurface. To minimize the number of times
- // a producer slot switches which source it comes from, we map source slot
- // numbers to producer slot numbers differently for each source.
- static int mapSource2ProducerSlot(Source source, int sslot);
- static int mapProducer2SourceSlot(Source source, int pslot);
-
- //
- // Immutable after construction
- //
- const int32_t mDisplayId;
- const String8 mDisplayName;
- sp<IGraphicBufferProducer> mSource[2]; // indexed by SOURCE_*
- uint32_t mDefaultOutputFormat;
-
- //
- // Inter-frame state
- //
-
- // To avoid buffer reallocations, we track the buffer usage and format
- // we used on the previous frame and use it again on the new frame. If
- // the composition type changes or the GLES driver starts requesting
- // different usage/format, we'll get a new buffer.
- uint32_t mOutputFormat;
- uint32_t mOutputUsage;
-
- // Since we present a single producer interface to the GLES driver, but
- // are internally muxing between the sink and scratch producers, we have
- // to keep track of which source last returned each producer slot from
- // dequeueBuffer. Each bit in mProducerSlotSource corresponds to a producer
- // slot. Both mProducerSlotSource and mProducerBuffers are indexed by a
- // "producer slot"; see the mapSlot*() functions.
- uint64_t mProducerSlotSource;
- sp<GraphicBuffer> mProducerBuffers[BufferQueue::NUM_BUFFER_SLOTS];
-
- // The QueueBufferOutput with the latest info from the sink, and with the
- // transform hint cleared. Since we defer queueBuffer from the GLES driver
- // to the sink, we have to return the previous version.
- QueueBufferOutput mQueueBufferOutput;
-
- // Details of the current sink buffer. These become valid when a buffer is
- // dequeued from the sink, and are used when queueing the buffer.
- uint32_t mSinkBufferWidth, mSinkBufferHeight;
-
- //
- // Intra-frame state
- //
-
- // Composition type and GLES buffer source for the current frame.
- // Valid after prepareFrame(), cleared in onFrameCommitted.
- CompositionType mCompositionType;
-
- // mFbFence is the fence HWC should wait for before reading the framebuffer
- // target buffer.
- sp<Fence> mFbFence;
-
- // mOutputFence is the fence HWC should wait for before writing to the
- // output buffer.
- sp<Fence> mOutputFence;
-
- // Producer slot numbers for the buffers to use for HWC framebuffer target
- // and output.
- int mFbProducerSlot;
- int mOutputProducerSlot;
-
- // Debug only -- track the sequence of events in each frame so we can make
- // sure they happen in the order we expect. This class implicitly models
- // a state machine; this enum/variable makes it explicit.
- //
- // +-----------+-------------------+-------------+
- // | State | Event || Next State |
- // +-----------+-------------------+-------------+
- // | IDLE | beginFrame || BEGUN |
- // | BEGUN | prepareFrame || PREPARED |
- // | PREPARED | dequeueBuffer [1] || GLES |
- // | PREPARED | advanceFrame [2] || HWC |
- // | GLES | queueBuffer || GLES_DONE |
- // | GLES_DONE | advanceFrame || HWC |
- // | HWC | onFrameCommitted || IDLE |
- // +-----------+-------------------++------------+
- // [1] COMPOSITION_GLES and COMPOSITION_MIXED frames.
- // [2] COMPOSITION_HWC frames.
- //
- enum DbgState {
- // no buffer dequeued, don't know anything about the next frame
- DBG_STATE_IDLE,
- // output buffer dequeued, framebuffer source not yet known
- DBG_STATE_BEGUN,
- // output buffer dequeued, framebuffer source known but not provided
- // to GLES yet.
- DBG_STATE_PREPARED,
- // GLES driver has a buffer dequeued
- DBG_STATE_GLES,
- // GLES driver has queued the buffer, we haven't sent it to HWC yet
- DBG_STATE_GLES_DONE,
- // HWC has the buffer for this frame
- DBG_STATE_HWC,
- };
- DbgState mDbgState;
- CompositionType mDbgLastCompositionType;
-
- const char* dbgStateStr() const;
- static const char* dbgSourceStr(Source s);
-
- bool mMustRecompose;
-};
-
-// ---------------------------------------------------------------------------
-} // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_SF_VIRTUAL_DISPLAY_SURFACE_H
-
diff --git a/widget/gonk/libdisplay/moz.build b/widget/gonk/libdisplay/moz.build
deleted file mode 100644
index 917320592..000000000
--- a/widget/gonk/libdisplay/moz.build
+++ /dev/null
@@ -1,59 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# Copyright 2013 Mozilla Foundation and Mozilla contributors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-SOURCES += [
- 'BootAnimation.cpp',
-]
-
-if CONFIG['ANDROID_VERSION'] >= '19':
- SOURCES += [
- 'FramebufferSurface.cpp',
- 'GonkDisplayJB.cpp',
- 'VirtualDisplaySurface.cpp',
- ]
-elif CONFIG['ANDROID_VERSION'] == '18':
- SOURCES += [
- 'FramebufferSurface.cpp',
- 'GonkDisplayJB.cpp',
- ]
-elif CONFIG['ANDROID_VERSION'] == '17':
- SOURCES += [
- 'FramebufferSurface.cpp',
- 'GonkDisplayJB.cpp',
- 'GraphicBufferAlloc.cpp',
- ]
-elif CONFIG['ANDROID_VERSION'] and CONFIG['COMPILE_ENVIRONMENT']:
- error('Unsupported platform version: %s' % (CONFIG['ANDROID_VERSION']))
-
-Library('display')
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FORCE_STATIC_LIB = True
-
-DEFINES['XPCOM_GLUE'] = True
-
-DISABLE_STL_WRAPPING = True
-
-LOCAL_INCLUDES += [
- '%' + '%s/%s' % (CONFIG['ANDROID_SOURCE'], d) for d in [
- 'frameworks/native/include/gui',
- 'frameworks/native/opengl/include',
- 'hardware/libhardware/include',
- 'hardware/libhardware_legacy/include',
- 'system/core/libsuspend/include',
- ]
-]
diff --git a/widget/gonk/libui/EventHub.cpp b/widget/gonk/libui/EventHub.cpp
deleted file mode 100644
index 9da29bbeb..000000000
--- a/widget/gonk/libui/EventHub.cpp
+++ /dev/null
@@ -1,1549 +0,0 @@
-/*
- * Copyright (C) 2005 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "EventHub"
-
-// #define LOG_NDEBUG 0
-#include "cutils_log.h"
-
-#include "EventHub.h"
-
-#include <hardware_legacy/power.h>
-
-#include <cutils/properties.h>
-#include "cutils_log.h"
-#include <utils/Timers.h>
-#include <utils/threads.h>
-#include <utils/Errors.h>
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <memory.h>
-#include <errno.h>
-#include <assert.h>
-
-#include "KeyLayoutMap.h"
-#include "KeyCharacterMap.h"
-#include "VirtualKeyMap.h"
-
-#include <string.h>
-#include <stdint.h>
-#include <dirent.h>
-
-#include <sys/inotify.h>
-#include <sys/epoll.h>
-#include <sys/ioctl.h>
-#include <sys/limits.h>
-#include "sha1.h"
-
-/* this macro is used to tell if "bit" is set in "array"
- * it selects a byte from the array, and does a boolean AND
- * operation with a byte that only has the relevant bit set.
- * eg. to check for the 12th bit, we do (array[1] & 1<<4)
- */
-#define test_bit(bit, array) (array[bit/8] & (1<<(bit%8)))
-
-/* this macro computes the number of bytes needed to represent a bit array of the specified size */
-#define sizeof_bit_array(bits) ((bits + 7) / 8)
-
-#define INDENT " "
-#define INDENT2 " "
-#define INDENT3 " "
-
-namespace android {
-
-static const char *WAKE_LOCK_ID = "KeyEvents";
-static const char *DEVICE_PATH = "/dev/input";
-
-/* return the larger integer */
-static inline int max(int v1, int v2)
-{
- return (v1 > v2) ? v1 : v2;
-}
-
-static inline const char* toString(bool value) {
- return value ? "true" : "false";
-}
-
-static String8 sha1(const String8& in) {
- SHA1_CTX ctx;
- SHA1Init(&ctx);
- SHA1Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
- u_char digest[SHA1_DIGEST_LENGTH];
- SHA1Final(digest, &ctx);
-
- String8 out;
- for (size_t i = 0; i < SHA1_DIGEST_LENGTH; i++) {
- out.appendFormat("%02x", digest[i]);
- }
- return out;
-}
-
-static void setDescriptor(InputDeviceIdentifier& identifier) {
- // Compute a device descriptor that uniquely identifies the device.
- // The descriptor is assumed to be a stable identifier. Its value should not
- // change between reboots, reconnections, firmware updates or new releases of Android.
- // Ideally, we also want the descriptor to be short and relatively opaque.
- String8 rawDescriptor;
- rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor, identifier.product);
- if (!identifier.uniqueId.isEmpty()) {
- rawDescriptor.append("uniqueId:");
- rawDescriptor.append(identifier.uniqueId);
- } if (identifier.vendor == 0 && identifier.product == 0) {
- // If we don't know the vendor and product id, then the device is probably
- // built-in so we need to rely on other information to uniquely identify
- // the input device. Usually we try to avoid relying on the device name or
- // location but for built-in input device, they are unlikely to ever change.
- if (!identifier.name.isEmpty()) {
- rawDescriptor.append("name:");
- rawDescriptor.append(identifier.name);
- } else if (!identifier.location.isEmpty()) {
- rawDescriptor.append("location:");
- rawDescriptor.append(identifier.location);
- }
- }
- identifier.descriptor = sha1(rawDescriptor);
- ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
- identifier.descriptor.string());
-}
-
-// --- Global Functions ---
-
-uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
- // Touch devices get dibs on touch-related axes.
- if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
- switch (axis) {
- case ABS_X:
- case ABS_Y:
- case ABS_PRESSURE:
- case ABS_TOOL_WIDTH:
- case ABS_DISTANCE:
- case ABS_TILT_X:
- case ABS_TILT_Y:
- case ABS_MT_SLOT:
- case ABS_MT_TOUCH_MAJOR:
- case ABS_MT_TOUCH_MINOR:
- case ABS_MT_WIDTH_MAJOR:
- case ABS_MT_WIDTH_MINOR:
- case ABS_MT_ORIENTATION:
- case ABS_MT_POSITION_X:
- case ABS_MT_POSITION_Y:
- case ABS_MT_TOOL_TYPE:
- case ABS_MT_BLOB_ID:
- case ABS_MT_TRACKING_ID:
- case ABS_MT_PRESSURE:
- case ABS_MT_DISTANCE:
- return INPUT_DEVICE_CLASS_TOUCH;
- }
- }
-
- // Joystick devices get the rest.
- return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
-}
-
-// --- EventHub::Device ---
-
-EventHub::Device::Device(int fd, int32_t id, const String8& path,
- const InputDeviceIdentifier& identifier) :
- next(NULL),
- fd(fd), id(id), path(path), identifier(identifier),
- classes(0), configuration(NULL), virtualKeyMap(NULL),
- ffEffectPlaying(false), ffEffectId(-1),
- timestampOverrideSec(0), timestampOverrideUsec(0) {
- memset(keyBitmask, 0, sizeof(keyBitmask));
- memset(absBitmask, 0, sizeof(absBitmask));
- memset(relBitmask, 0, sizeof(relBitmask));
- memset(swBitmask, 0, sizeof(swBitmask));
- memset(ledBitmask, 0, sizeof(ledBitmask));
- memset(ffBitmask, 0, sizeof(ffBitmask));
- memset(propBitmask, 0, sizeof(propBitmask));
-}
-
-EventHub::Device::~Device() {
- close();
- delete configuration;
- delete virtualKeyMap;
-}
-
-void EventHub::Device::close() {
- if (fd >= 0) {
- ::close(fd);
- fd = -1;
- }
-}
-
-
-// --- EventHub ---
-
-const uint32_t EventHub::EPOLL_ID_INOTIFY;
-const uint32_t EventHub::EPOLL_ID_WAKE;
-const int EventHub::EPOLL_SIZE_HINT;
-const int EventHub::EPOLL_MAX_EVENTS;
-
-EventHub::EventHub(void) :
- mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1),
- mOpeningDevices(0), mClosingDevices(0),
- mNeedToSendFinishedDeviceScan(false),
- mNeedToReopenDevices(false), mNeedToScanDevices(true),
- mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
- acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
-
- mEpollFd = epoll_create(EPOLL_SIZE_HINT);
- LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
-
- mINotifyFd = inotify_init();
- int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
- LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
- DEVICE_PATH, errno);
-
- struct epoll_event eventItem;
- memset(&eventItem, 0, sizeof(eventItem));
- eventItem.events = EPOLLIN;
- eventItem.data.u32 = EPOLL_ID_INOTIFY;
- result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
- LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
-
- int wakeFds[2];
- result = pipe(wakeFds);
- LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
-
- mWakeReadPipeFd = wakeFds[0];
- mWakeWritePipeFd = wakeFds[1];
-
- result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
- LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
- errno);
-
- result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
- LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
- errno);
-
- eventItem.data.u32 = EPOLL_ID_WAKE;
- result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
- LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
- errno);
-}
-
-EventHub::~EventHub(void) {
- closeAllDevicesLocked();
-
- while (mClosingDevices) {
- Device* device = mClosingDevices;
- mClosingDevices = device->next;
- delete device;
- }
-
- ::close(mEpollFd);
- ::close(mINotifyFd);
- ::close(mWakeReadPipeFd);
- ::close(mWakeWritePipeFd);
-
- release_wake_lock(WAKE_LOCK_ID);
-}
-
-InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device == NULL) return InputDeviceIdentifier();
- return device->identifier;
-}
-
-uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device == NULL) return 0;
- return device->classes;
-}
-
-void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device && device->configuration) {
- *outConfiguration = *device->configuration;
- } else {
- outConfiguration->clear();
- }
-}
-
-status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
- RawAbsoluteAxisInfo* outAxisInfo) const {
- outAxisInfo->clear();
-
- if (axis >= 0 && axis <= ABS_MAX) {
- AutoMutex _l(mLock);
-
- Device* device = getDeviceLocked(deviceId);
- if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
- struct input_absinfo info;
- if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
- ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
- axis, device->identifier.name.string(), device->fd, errno);
- return -errno;
- }
-
- if (info.minimum != info.maximum) {
- outAxisInfo->valid = true;
- outAxisInfo->minValue = info.minimum;
- outAxisInfo->maxValue = info.maximum;
- outAxisInfo->flat = info.flat;
- outAxisInfo->fuzz = info.fuzz;
- outAxisInfo->resolution = info.resolution;
- }
- return OK;
- }
- }
- return -1;
-}
-
-bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
- if (axis >= 0 && axis <= REL_MAX) {
- AutoMutex _l(mLock);
-
- Device* device = getDeviceLocked(deviceId);
- if (device) {
- return test_bit(axis, device->relBitmask);
- }
- }
- return false;
-}
-
-bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
- if (property >= 0 && property <= INPUT_PROP_MAX) {
- AutoMutex _l(mLock);
-
- Device* device = getDeviceLocked(deviceId);
- if (device) {
- return test_bit(property, device->propBitmask);
- }
- }
- return false;
-}
-
-int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
- if (scanCode >= 0 && scanCode <= KEY_MAX) {
- AutoMutex _l(mLock);
-
- Device* device = getDeviceLocked(deviceId);
- if (device && !device->isVirtual() && test_bit(scanCode, device->keyBitmask)) {
- uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
- memset(keyState, 0, sizeof(keyState));
- if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
- return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
- }
- }
- }
- return AKEY_STATE_UNKNOWN;
-}
-
-int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
- AutoMutex _l(mLock);
-
- Device* device = getDeviceLocked(deviceId);
- if (device && !device->isVirtual() && device->keyMap.haveKeyLayout()) {
- Vector<int32_t> scanCodes;
- device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
- if (scanCodes.size() != 0) {
- uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
- memset(keyState, 0, sizeof(keyState));
- if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
- for (size_t i = 0; i < scanCodes.size(); i++) {
- int32_t sc = scanCodes.itemAt(i);
- if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
- return AKEY_STATE_DOWN;
- }
- }
- return AKEY_STATE_UP;
- }
- }
- }
- return AKEY_STATE_UNKNOWN;
-}
-
-int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
- if (sw >= 0 && sw <= SW_MAX) {
- AutoMutex _l(mLock);
-
- Device* device = getDeviceLocked(deviceId);
- if (device && !device->isVirtual() && test_bit(sw, device->swBitmask)) {
- uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
- memset(swState, 0, sizeof(swState));
- if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
- return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
- }
- }
- }
- return AKEY_STATE_UNKNOWN;
-}
-
-status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
- *outValue = 0;
-
- if (axis >= 0 && axis <= ABS_MAX) {
- AutoMutex _l(mLock);
-
- Device* device = getDeviceLocked(deviceId);
- if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
- struct input_absinfo info;
- if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
- ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
- axis, device->identifier.name.string(), device->fd, errno);
- return -errno;
- }
-
- *outValue = info.value;
- return OK;
- }
- }
- return -1;
-}
-
-bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags) const {
- AutoMutex _l(mLock);
-
- Device* device = getDeviceLocked(deviceId);
- if (device && device->keyMap.haveKeyLayout()) {
- Vector<int32_t> scanCodes;
- for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
- scanCodes.clear();
-
- status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
- keyCodes[codeIndex], &scanCodes);
- if (! err) {
- // check the possible scan codes identified by the layout map against the
- // map of codes actually emitted by the driver
- for (size_t sc = 0; sc < scanCodes.size(); sc++) {
- if (test_bit(scanCodes[sc], device->keyBitmask)) {
- outFlags[codeIndex] = 1;
- break;
- }
- }
- }
- }
- return true;
- }
- return false;
-}
-
-status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
- int32_t* outKeycode, uint32_t* outFlags) const {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
-
- if (device) {
- // Check the key character map first.
- sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
- if (kcm != NULL) {
- if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
- *outFlags = 0;
- return NO_ERROR;
- }
- }
-
- // Check the key layout next.
- if (device->keyMap.haveKeyLayout()) {
- if (!device->keyMap.keyLayoutMap->mapKey(
- scanCode, usageCode, outKeycode, outFlags)) {
- return NO_ERROR;
- }
- }
- }
-
- *outKeycode = 0;
- *outFlags = 0;
- return NAME_NOT_FOUND;
-}
-
-status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
-
- if (device && device->keyMap.haveKeyLayout()) {
- status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
- if (err == NO_ERROR) {
- return NO_ERROR;
- }
- }
-
- return NAME_NOT_FOUND;
-}
-
-void EventHub::setExcludedDevices(const Vector<String8>& devices) {
- AutoMutex _l(mLock);
-
- mExcludedDevices = devices;
-}
-
-bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
- if (test_bit(scanCode, device->keyBitmask)) {
- return true;
- }
- }
- return false;
-}
-
-bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device && led >= 0 && led <= LED_MAX) {
- if (test_bit(led, device->ledBitmask)) {
- return true;
- }
- }
- return false;
-}
-
-void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device && !device->isVirtual() && led >= 0 && led <= LED_MAX) {
- struct input_event ev;
- ev.time.tv_sec = 0;
- ev.time.tv_usec = 0;
- ev.type = EV_LED;
- ev.code = led;
- ev.value = on ? 1 : 0;
-
- ssize_t nWrite;
- do {
- nWrite = write(device->fd, &ev, sizeof(struct input_event));
- } while (nWrite == -1 && errno == EINTR);
- }
-}
-
-void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
- Vector<VirtualKeyDefinition>& outVirtualKeys) const {
- outVirtualKeys.clear();
-
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device && device->virtualKeyMap) {
- outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
- }
-}
-
-sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device) {
- return device->getKeyCharacterMap();
- }
- return NULL;
-}
-
-bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
- const sp<KeyCharacterMap>& map) {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device) {
- if (map != device->overlayKeyMap) {
- device->overlayKeyMap = map;
- device->combinedKeyMap = KeyCharacterMap::combine(
- device->keyMap.keyCharacterMap, map);
- return true;
- }
- }
- return false;
-}
-
-void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device && !device->isVirtual()) {
- ff_effect effect;
- memset(&effect, 0, sizeof(effect));
- effect.type = FF_RUMBLE;
- effect.id = device->ffEffectId;
- effect.u.rumble.strong_magnitude = 0xc000;
- effect.u.rumble.weak_magnitude = 0xc000;
- effect.replay.length = (duration + 999999LL) / 1000000LL;
- effect.replay.delay = 0;
- if (ioctl(device->fd, EVIOCSFF, &effect)) {
- ALOGW("Could not upload force feedback effect to device %s due to error %d.",
- device->identifier.name.string(), errno);
- return;
- }
- device->ffEffectId = effect.id;
-
- struct input_event ev;
- ev.time.tv_sec = 0;
- ev.time.tv_usec = 0;
- ev.type = EV_FF;
- ev.code = device->ffEffectId;
- ev.value = 1;
- if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
- ALOGW("Could not start force feedback effect on device %s due to error %d.",
- device->identifier.name.string(), errno);
- return;
- }
- device->ffEffectPlaying = true;
- }
-}
-
-void EventHub::cancelVibrate(int32_t deviceId) {
- AutoMutex _l(mLock);
- Device* device = getDeviceLocked(deviceId);
- if (device && !device->isVirtual()) {
- if (device->ffEffectPlaying) {
- device->ffEffectPlaying = false;
-
- struct input_event ev;
- ev.time.tv_sec = 0;
- ev.time.tv_usec = 0;
- ev.type = EV_FF;
- ev.code = device->ffEffectId;
- ev.value = 0;
- if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
- ALOGW("Could not stop force feedback effect on device %s due to error %d.",
- device->identifier.name.string(), errno);
- return;
- }
- }
- }
-}
-
-EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
- if (deviceId == BUILT_IN_KEYBOARD_ID) {
- deviceId = mBuiltInKeyboardId;
- }
- ssize_t index = mDevices.indexOfKey(deviceId);
- return index >= 0 ? mDevices.valueAt(index) : NULL;
-}
-
-EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
- for (size_t i = 0; i < mDevices.size(); i++) {
- Device* device = mDevices.valueAt(i);
- if (device->path == devicePath) {
- return device;
- }
- }
- return NULL;
-}
-
-size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
- ALOG_ASSERT(bufferSize >= 1);
-
- AutoMutex _l(mLock);
-
- struct input_event readBuffer[bufferSize];
-
- RawEvent* event = buffer;
- size_t capacity = bufferSize;
- bool awoken = false;
- for (;;) {
- nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
-
- // Reopen input devices if needed.
- if (mNeedToReopenDevices) {
- mNeedToReopenDevices = false;
-
- ALOGI("Reopening all input devices due to a configuration change.");
-
- closeAllDevicesLocked();
- mNeedToScanDevices = true;
- break; // return to the caller before we actually rescan
- }
-
- // Report any devices that had last been added/removed.
- while (mClosingDevices) {
- Device* device = mClosingDevices;
- ALOGV("Reporting device closed: id=%d, name=%s\n",
- device->id, device->path.string());
- mClosingDevices = device->next;
- event->when = now;
- event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
- event->type = DEVICE_REMOVED;
- event += 1;
- delete device;
- mNeedToSendFinishedDeviceScan = true;
- if (--capacity == 0) {
- break;
- }
- }
-
- if (mNeedToScanDevices) {
- mNeedToScanDevices = false;
- scanDevicesLocked();
- mNeedToSendFinishedDeviceScan = true;
- }
-
- while (mOpeningDevices != NULL) {
- Device* device = mOpeningDevices;
- ALOGV("Reporting device opened: id=%d, name=%s\n",
- device->id, device->path.string());
- mOpeningDevices = device->next;
- event->when = now;
- event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
- event->type = DEVICE_ADDED;
- event += 1;
- mNeedToSendFinishedDeviceScan = true;
- if (--capacity == 0) {
- break;
- }
- }
-
- if (mNeedToSendFinishedDeviceScan) {
- mNeedToSendFinishedDeviceScan = false;
- event->when = now;
- event->type = FINISHED_DEVICE_SCAN;
- event += 1;
- if (--capacity == 0) {
- break;
- }
- }
-
- // Grab the next input event.
- bool deviceChanged = false;
- while (mPendingEventIndex < mPendingEventCount) {
- const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
- if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
- if (eventItem.events & EPOLLIN) {
- mPendingINotify = true;
- } else {
- ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
- }
- continue;
- }
-
- if (eventItem.data.u32 == EPOLL_ID_WAKE) {
- if (eventItem.events & EPOLLIN) {
- ALOGV("awoken after wake()");
- awoken = true;
- char buffer[16];
- ssize_t nRead;
- do {
- nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
- } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
- } else {
- ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
- eventItem.events);
- }
- continue;
- }
-
- ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
- if (deviceIndex < 0) {
- ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
- eventItem.events, eventItem.data.u32);
- continue;
- }
-
- Device* device = mDevices.valueAt(deviceIndex);
- if (eventItem.events & EPOLLIN) {
- int32_t readSize = read(device->fd, readBuffer,
- sizeof(struct input_event) * capacity);
- if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
- // Device was removed before INotify noticed.
- ALOGW("could not get event, removed? (fd: %d size: %d bufferSize: %d "
- "capacity: %d errno: %d)\n",
- device->fd, readSize, bufferSize, capacity, errno);
- deviceChanged = true;
- closeDeviceLocked(device);
- } else if (readSize < 0) {
- if (errno != EAGAIN && errno != EINTR) {
- ALOGW("could not get event (errno=%d)", errno);
- }
- } else if ((readSize % sizeof(struct input_event)) != 0) {
- ALOGE("could not get event (wrong size: %d)", readSize);
- } else {
- int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
-
- size_t count = size_t(readSize) / sizeof(struct input_event);
- for (size_t i = 0; i < count; i++) {
- struct input_event& iev = readBuffer[i];
- ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
- device->path.string(),
- (int) iev.time.tv_sec, (int) iev.time.tv_usec,
- iev.type, iev.code, iev.value);
-
- // Some input devices may have a better concept of the time
- // when an input event was actually generated than the kernel
- // which simply timestamps all events on entry to evdev.
- // This is a custom Android extension of the input protocol
- // mainly intended for use with uinput based device drivers.
- if (iev.type == EV_MSC) {
- if (iev.code == MSC_ANDROID_TIME_SEC) {
- device->timestampOverrideSec = iev.value;
- continue;
- } else if (iev.code == MSC_ANDROID_TIME_USEC) {
- device->timestampOverrideUsec = iev.value;
- continue;
- }
- }
- if (device->timestampOverrideSec || device->timestampOverrideUsec) {
- iev.time.tv_sec = device->timestampOverrideSec;
- iev.time.tv_usec = device->timestampOverrideUsec;
- if (iev.type == EV_SYN && iev.code == SYN_REPORT) {
- device->timestampOverrideSec = 0;
- device->timestampOverrideUsec = 0;
- }
- ALOGV("applied override time %d.%06d",
- int(iev.time.tv_sec), int(iev.time.tv_usec));
- }
-
-#ifdef HAVE_POSIX_CLOCKS
- // Use the time specified in the event instead of the current time
- // so that downstream code can get more accurate estimates of
- // event dispatch latency from the time the event is enqueued onto
- // the evdev client buffer.
- //
- // The event's timestamp fortuitously uses the same monotonic clock
- // time base as the rest of Android. The kernel event device driver
- // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
- // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
- // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
- // system call that also queries ktime_get_ts().
- event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
- + nsecs_t(iev.time.tv_usec) * 1000LL;
- ALOGV("event time %lld, now %lld", event->when, now);
-
- // Bug 7291243: Add a guard in case the kernel generates timestamps
- // that appear to be far into the future because they were generated
- // using the wrong clock source.
- //
- // This can happen because when the input device is initially opened
- // it has a default clock source of CLOCK_REALTIME. Any input events
- // enqueued right after the device is opened will have timestamps
- // generated using CLOCK_REALTIME. We later set the clock source
- // to CLOCK_MONOTONIC but it is already too late.
- //
- // Invalid input event timestamps can result in ANRs, crashes and
- // and other issues that are hard to track down. We must not let them
- // propagate through the system.
- //
- // Log a warning so that we notice the problem and recover gracefully.
- if (event->when >= now + 10 * 1000000000LL) {
- // Double-check. Time may have moved on.
- nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
- if (event->when > time) {
- ALOGW("An input event from %s has a timestamp that appears to "
- "have been generated using the wrong clock source "
- "(expected CLOCK_MONOTONIC): "
- "event time %lld, current time %lld, call time %lld. "
- "Using current time instead.",
- device->path.string(), event->when, time, now);
- event->when = time;
- } else {
- ALOGV("Event time is ok but failed the fast path and required "
- "an extra call to systemTime: "
- "event time %lld, current time %lld, call time %lld.",
- event->when, time, now);
- }
- }
-#else
- event->when = now;
-#endif
- event->deviceId = deviceId;
- event->type = iev.type;
- event->code = iev.code;
- event->value = iev.value;
- event += 1;
- capacity -= 1;
- }
- if (capacity == 0) {
- // The result buffer is full. Reset the pending event index
- // so we will try to read the device again on the next iteration.
- mPendingEventIndex -= 1;
- break;
- }
- }
- } else if (eventItem.events & EPOLLHUP) {
- ALOGI("Removing device %s due to epoll hang-up event.",
- device->identifier.name.string());
- deviceChanged = true;
- closeDeviceLocked(device);
- } else {
- ALOGW("Received unexpected epoll event 0x%08x for device %s.",
- eventItem.events, device->identifier.name.string());
- }
- }
-
- // readNotify() will modify the list of devices so this must be done after
- // processing all other events to ensure that we read all remaining events
- // before closing the devices.
- if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
- mPendingINotify = false;
- readNotifyLocked();
- deviceChanged = true;
- }
-
- // Report added or removed devices immediately.
- if (deviceChanged) {
- continue;
- }
-
- // Return now if we have collected any events or if we were explicitly awoken.
- if (event != buffer || awoken) {
- break;
- }
-
- // Poll for events. Mind the wake lock dance!
- // We hold a wake lock at all times except during epoll_wait(). This works due to some
- // subtle choreography. When a device driver has pending (unread) events, it acquires
- // a kernel wake lock. However, once the last pending event has been read, the device
- // driver will release the kernel wake lock. To prevent the system from going to sleep
- // when this happens, the EventHub holds onto its own user wake lock while the client
- // is processing events. Thus the system can only sleep if there are no events
- // pending or currently being processed.
- //
- // The timeout is advisory only. If the device is asleep, it will not wake just to
- // service the timeout.
- mPendingEventIndex = 0;
-
- mLock.unlock(); // release lock before poll, must be before release_wake_lock
- release_wake_lock(WAKE_LOCK_ID);
-
- int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
-
- acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
- mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
-
- if (pollResult == 0) {
- // Timed out.
- mPendingEventCount = 0;
- break;
- }
-
- if (pollResult < 0) {
- // An error occurred.
- mPendingEventCount = 0;
-
- // Sleep after errors to avoid locking up the system.
- // Hopefully the error is transient.
- if (errno != EINTR) {
- ALOGW("poll failed (errno=%d)\n", errno);
- usleep(100000);
- }
- } else {
- // Some events occurred.
- mPendingEventCount = size_t(pollResult);
- }
- }
-
- // All done, return the number of events we read.
- return event - buffer;
-}
-
-void EventHub::wake() {
- ALOGV("wake() called");
-
- ssize_t nWrite;
- do {
- nWrite = write(mWakeWritePipeFd, "W", 1);
- } while (nWrite == -1 && errno == EINTR);
-
- if (nWrite != 1 && errno != EAGAIN) {
- ALOGW("Could not write wake signal, errno=%d", errno);
- }
-}
-
-void EventHub::scanDevicesLocked() {
- status_t res = scanDirLocked(DEVICE_PATH);
- if(res < 0) {
- ALOGE("scan dir failed for %s\n", DEVICE_PATH);
- }
- if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
- createVirtualKeyboardLocked();
- }
-}
-
-// ----------------------------------------------------------------------------
-
-static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
- const uint8_t* end = array + endIndex;
- array += startIndex;
- while (array != end) {
- if (*(array++) != 0) {
- return true;
- }
- }
- return false;
-}
-
-static const int32_t GAMEPAD_KEYCODES[] = {
- AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
- AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
- AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
- AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
- AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
- AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
- AKEYCODE_BUTTON_1, AKEYCODE_BUTTON_2, AKEYCODE_BUTTON_3, AKEYCODE_BUTTON_4,
- AKEYCODE_BUTTON_5, AKEYCODE_BUTTON_6, AKEYCODE_BUTTON_7, AKEYCODE_BUTTON_8,
- AKEYCODE_BUTTON_9, AKEYCODE_BUTTON_10, AKEYCODE_BUTTON_11, AKEYCODE_BUTTON_12,
- AKEYCODE_BUTTON_13, AKEYCODE_BUTTON_14, AKEYCODE_BUTTON_15, AKEYCODE_BUTTON_16,
-};
-
-status_t EventHub::openDeviceLocked(const char *devicePath) {
- char buffer[80];
-
- ALOGV("Opening device: %s", devicePath);
-
- int fd = open(devicePath, O_RDWR | O_CLOEXEC);
- if(fd < 0) {
- ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
- return -1;
- }
-
- InputDeviceIdentifier identifier;
-
- // Get device name.
- if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
- //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
- } else {
- buffer[sizeof(buffer) - 1] = '\0';
- identifier.name.setTo(buffer);
- }
-
- // Check to see if the device is on our excluded list
- for (size_t i = 0; i < mExcludedDevices.size(); i++) {
- const String8& item = mExcludedDevices.itemAt(i);
- if (identifier.name == item) {
- ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
- close(fd);
- return -1;
- }
- }
-
- // Get device driver version.
- int driverVersion;
- if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
- ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
- close(fd);
- return -1;
- }
-
- // Get device identifier.
- struct input_id inputId;
- if(ioctl(fd, EVIOCGID, &inputId)) {
- ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
- close(fd);
- return -1;
- }
- identifier.bus = inputId.bustype;
- identifier.product = inputId.product;
- identifier.vendor = inputId.vendor;
- identifier.version = inputId.version;
-
- // Get device physical location.
- if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
- //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
- } else {
- buffer[sizeof(buffer) - 1] = '\0';
- identifier.location.setTo(buffer);
- }
-
- // Get device unique id.
- if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
- //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
- } else {
- buffer[sizeof(buffer) - 1] = '\0';
- identifier.uniqueId.setTo(buffer);
- }
-
- // Fill in the descriptor.
- setDescriptor(identifier);
-
- // Make file descriptor non-blocking for use with poll().
- if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
- ALOGE("Error %d making device file descriptor non-blocking.", errno);
- close(fd);
- return -1;
- }
-
- // Allocate device. (The device object takes ownership of the fd at this point.)
- int32_t deviceId = mNextDeviceId++;
- Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
-
- ALOGV("add device %d: %s\n", deviceId, devicePath);
- ALOGV(" bus: %04x\n"
- " vendor %04x\n"
- " product %04x\n"
- " version %04x\n",
- identifier.bus, identifier.vendor, identifier.product, identifier.version);
- ALOGV(" name: \"%s\"\n", identifier.name.string());
- ALOGV(" location: \"%s\"\n", identifier.location.string());
- ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string());
- ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string());
- ALOGV(" driver: v%d.%d.%d\n",
- driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
-
- // Load the configuration file for the device.
- loadConfigurationLocked(device);
-
- // Figure out the kinds of events the device reports.
- ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
- ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
- ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
- ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
- ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
- ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
- ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
-
- // See if this is a keyboard. Ignore everything in the button range except for
- // joystick and gamepad buttons which are handled like keyboards for the most part.
- bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
- || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
- sizeof_bit_array(KEY_MAX + 1));
- bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
- sizeof_bit_array(BTN_MOUSE))
- || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
- sizeof_bit_array(BTN_DIGI));
- if (haveKeyboardKeys || haveGamepadButtons) {
- device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
- }
-
- // See if this is a cursor device such as a trackball or mouse.
- if (test_bit(BTN_MOUSE, device->keyBitmask)
- && test_bit(REL_X, device->relBitmask)
- && test_bit(REL_Y, device->relBitmask)) {
- device->classes |= INPUT_DEVICE_CLASS_CURSOR;
- }
-
- // See if this is a touch pad.
- // Is this a new modern multi-touch driver?
- if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
- && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
- // Some joysticks such as the PS3 controller report axes that conflict
- // with the ABS_MT range. Try to confirm that the device really is
- // a touch screen.
- if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
- device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
- }
- // Is this an old style single-touch driver?
- } else if (test_bit(BTN_TOUCH, device->keyBitmask)
- && test_bit(ABS_X, device->absBitmask)
- && test_bit(ABS_Y, device->absBitmask)) {
- device->classes |= INPUT_DEVICE_CLASS_TOUCH;
- }
-
- // See if this device is a joystick.
- // Assumes that joysticks always have gamepad buttons in order to distinguish them
- // from other devices such as accelerometers that also have absolute axes.
- if (haveGamepadButtons) {
- uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
- for (int i = 0; i <= ABS_MAX; i++) {
- if (test_bit(i, device->absBitmask)
- && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
- device->classes = assumedClasses;
- break;
- }
- }
- }
-
- // Check whether this device has switches.
- for (int i = 0; i <= SW_MAX; i++) {
- if (test_bit(i, device->swBitmask)) {
- device->classes |= INPUT_DEVICE_CLASS_SWITCH;
- break;
- }
- }
-
- // Check whether this device supports the vibrator.
- if (test_bit(FF_RUMBLE, device->ffBitmask)) {
- device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
- }
-
- // Configure virtual keys.
- if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
- // Load the virtual keys for the touch screen, if any.
- // We do this now so that we can make sure to load the keymap if necessary.
- status_t status = loadVirtualKeyMapLocked(device);
- if (!status) {
- device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
- }
- }
-
- // Load the key map.
- // We need to do this for joysticks too because the key layout may specify axes.
- status_t keyMapStatus = NAME_NOT_FOUND;
- if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
- // Load the keymap for the device.
- keyMapStatus = loadKeyMapLocked(device);
- }
-
- // Configure the keyboard, gamepad or virtual keyboard.
- if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
- // Register the keyboard as a built-in keyboard if it is eligible.
- if (!keyMapStatus
- && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
- && isEligibleBuiltInKeyboard(device->identifier,
- device->configuration, &device->keyMap)) {
- mBuiltInKeyboardId = device->id;
- }
-
- // 'Q' key support = cheap test of whether this is an alpha-capable kbd
- if (hasKeycodeLocked(device, AKEYCODE_Q)) {
- device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
- }
-
- // See if this device has a DPAD.
- if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
- hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
- hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
- hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
- hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
- device->classes |= INPUT_DEVICE_CLASS_DPAD;
- }
-
- // See if this device has a gamepad.
- for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
- if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
- device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
- break;
- }
- }
-
- // Disable kernel key repeat since we handle it ourselves
- unsigned int repeatRate[] = {0,0};
- if (ioctl(fd, EVIOCSREP, repeatRate)) {
- ALOGW("Unable to disable kernel key repeat for %s: %s", devicePath, strerror(errno));
- }
- }
-
- // If the device isn't recognized as something we handle, don't monitor it.
- if (device->classes == 0) {
- ALOGV("Dropping device: id=%d, path='%s', name='%s'",
- deviceId, devicePath, device->identifier.name.string());
- delete device;
- return -1;
- }
-
- // Determine whether the device is external or internal.
- if (isExternalDeviceLocked(device)) {
- device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
- }
-
- // Register with epoll.
- struct epoll_event eventItem;
- memset(&eventItem, 0, sizeof(eventItem));
- eventItem.events = EPOLLIN;
- eventItem.data.u32 = deviceId;
- if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
- ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
- delete device;
- return -1;
- }
-
- // Enable wake-lock behavior on kernels that support it.
- // TODO: Only need this for devices that can really wake the system.
- bool usingSuspendBlockIoctl = !ioctl(fd, EVIOCSSUSPENDBLOCK, 1);
-
- // Tell the kernel that we want to use the monotonic clock for reporting timestamps
- // associated with input events. This is important because the input system
- // uses the timestamps extensively and assumes they were recorded using the monotonic
- // clock.
- //
- // In older kernel, before Linux 3.4, there was no way to tell the kernel which
- // clock to use to input event timestamps. The standard kernel behavior was to
- // record a real time timestamp, which isn't what we want. Android kernels therefore
- // contained a patch to the evdev_event() function in drivers/input/evdev.c to
- // replace the call to do_gettimeofday() with ktime_get_ts() to cause the monotonic
- // clock to be used instead of the real time clock.
- //
- // As of Linux 3.4, there is a new EVIOCSCLOCKID ioctl to set the desired clock.
- // Therefore, we no longer require the Android-specific kernel patch described above
- // as long as we make sure to set select the monotonic clock. We do that here.
- int clockId = CLOCK_MONOTONIC;
- bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
-
- ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
- "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, "
- "usingSuspendBlockIoctl=%s, usingClockIoctl=%s",
- deviceId, fd, devicePath, device->identifier.name.string(),
- device->classes,
- device->configurationFile.string(),
- device->keyMap.keyLayoutFile.string(),
- device->keyMap.keyCharacterMapFile.string(),
- toString(mBuiltInKeyboardId == deviceId),
- toString(usingSuspendBlockIoctl), toString(usingClockIoctl));
-
- addDeviceLocked(device);
- return 0;
-}
-
-void EventHub::createVirtualKeyboardLocked() {
- InputDeviceIdentifier identifier;
- identifier.name = "Virtual";
- identifier.uniqueId = "<virtual>";
- setDescriptor(identifier);
-
- Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
- device->classes = INPUT_DEVICE_CLASS_KEYBOARD
- | INPUT_DEVICE_CLASS_ALPHAKEY
- | INPUT_DEVICE_CLASS_DPAD
- | INPUT_DEVICE_CLASS_VIRTUAL;
- loadKeyMapLocked(device);
- addDeviceLocked(device);
-}
-
-void EventHub::addDeviceLocked(Device* device) {
- mDevices.add(device->id, device);
- device->next = mOpeningDevices;
- mOpeningDevices = device;
-}
-
-void EventHub::loadConfigurationLocked(Device* device) {
- device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
- device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
- if (device->configurationFile.isEmpty()) {
- ALOGD("No input device configuration file found for device '%s'.",
- device->identifier.name.string());
- } else {
- status_t status = PropertyMap::load(device->configurationFile,
- &device->configuration);
- if (status) {
- ALOGE("Error loading input device configuration file for device '%s'. "
- "Using default configuration.",
- device->identifier.name.string());
- }
- }
-}
-
-status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
- // The virtual key map is supplied by the kernel as a system board property file.
- String8 path;
- path.append("/sys/board_properties/virtualkeys.");
- path.append(device->identifier.name);
- if (access(path.string(), R_OK)) {
- return NAME_NOT_FOUND;
- }
- return VirtualKeyMap::load(path, &device->virtualKeyMap);
-}
-
-status_t EventHub::loadKeyMapLocked(Device* device) {
- return device->keyMap.load(device->identifier, device->configuration);
-}
-
-bool EventHub::isExternalDeviceLocked(Device* device) {
- if (device->configuration) {
- bool value;
- if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
- return !value;
- }
- }
- return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
-}
-
-bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
- if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
- return false;
- }
-
- Vector<int32_t> scanCodes;
- device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
- const size_t N = scanCodes.size();
- for (size_t i=0; i<N && i<=KEY_MAX; i++) {
- int32_t sc = scanCodes.itemAt(i);
- if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
- return true;
- }
- }
-
- return false;
-}
-
-status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
- Device* device = getDeviceByPathLocked(devicePath);
- if (device) {
- closeDeviceLocked(device);
- return 0;
- }
- ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
- return -1;
-}
-
-void EventHub::closeAllDevicesLocked() {
- while (mDevices.size() > 0) {
- closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
- }
-}
-
-void EventHub::closeDeviceLocked(Device* device) {
- ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
- device->path.string(), device->identifier.name.string(), device->id,
- device->fd, device->classes);
-
- if (device->id == mBuiltInKeyboardId) {
- ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
- device->path.string(), mBuiltInKeyboardId);
- mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
- }
-
- if (!device->isVirtual()) {
- if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
- ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
- }
- }
-
- mDevices.removeItem(device->id);
- device->close();
-
- // Unlink for opening devices list if it is present.
- Device* pred = NULL;
- bool found = false;
- for (Device* entry = mOpeningDevices; entry != NULL; ) {
- if (entry == device) {
- found = true;
- break;
- }
- pred = entry;
- entry = entry->next;
- }
- if (found) {
- // Unlink the device from the opening devices list then delete it.
- // We don't need to tell the client that the device was closed because
- // it does not even know it was opened in the first place.
- ALOGI("Device %s was immediately closed after opening.", device->path.string());
- if (pred) {
- pred->next = device->next;
- } else {
- mOpeningDevices = device->next;
- }
- delete device;
- } else {
- // Link into closing devices list.
- // The device will be deleted later after we have informed the client.
- device->next = mClosingDevices;
- mClosingDevices = device;
- }
-}
-
-status_t EventHub::readNotifyLocked() {
- int res;
- char devname[PATH_MAX];
- char *filename;
- char event_buf[512];
- int event_size;
- int event_pos = 0;
- struct inotify_event *event;
-
- ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
- res = read(mINotifyFd, event_buf, sizeof(event_buf));
- if(res < (int)sizeof(*event)) {
- if(errno == EINTR)
- return 0;
- ALOGW("could not get event, %s\n", strerror(errno));
- return -1;
- }
- //printf("got %d bytes of event information\n", res);
-
- strcpy(devname, DEVICE_PATH);
- filename = devname + strlen(devname);
- *filename++ = '/';
-
- while(res >= (int)sizeof(*event)) {
- event = (struct inotify_event *)(event_buf + event_pos);
- //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
- if(event->len) {
- strcpy(filename, event->name);
- if(event->mask & IN_CREATE) {
- openDeviceLocked(devname);
- } else {
- ALOGI("Removing device '%s' due to inotify event\n", devname);
- closeDeviceByPathLocked(devname);
- }
- }
- event_size = sizeof(*event) + event->len;
- res -= event_size;
- event_pos += event_size;
- }
- return 0;
-}
-
-status_t EventHub::scanDirLocked(const char *dirname)
-{
- char devname[PATH_MAX];
- char *filename;
- DIR *dir;
- struct dirent *de;
- dir = opendir(dirname);
- if(dir == NULL)
- return -1;
- strcpy(devname, dirname);
- filename = devname + strlen(devname);
- *filename++ = '/';
- while((de = readdir(dir))) {
- if(de->d_name[0] == '.' &&
- (de->d_name[1] == '\0' ||
- (de->d_name[1] == '.' && de->d_name[2] == '\0')))
- continue;
- strcpy(filename, de->d_name);
- openDeviceLocked(devname);
- }
- closedir(dir);
- return 0;
-}
-
-void EventHub::requestReopenDevices() {
- ALOGV("requestReopenDevices() called");
-
- AutoMutex _l(mLock);
- mNeedToReopenDevices = true;
-}
-
-void EventHub::dump(String8& dump) {
- dump.append("Event Hub State:\n");
-
- { // acquire lock
- AutoMutex _l(mLock);
-
- dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
-
- dump.append(INDENT "Devices:\n");
-
- for (size_t i = 0; i < mDevices.size(); i++) {
- const Device* device = mDevices.valueAt(i);
- if (mBuiltInKeyboardId == device->id) {
- dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
- device->id, device->identifier.name.string());
- } else {
- dump.appendFormat(INDENT2 "%d: %s\n", device->id,
- device->identifier.name.string());
- }
- dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
- dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
- dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
- dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
- dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
- dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
- "product=0x%04x, version=0x%04x\n",
- device->identifier.bus, device->identifier.vendor,
- device->identifier.product, device->identifier.version);
- dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
- device->keyMap.keyLayoutFile.string());
- dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
- device->keyMap.keyCharacterMapFile.string());
- dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
- device->configurationFile.string());
- dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
- toString(device->overlayKeyMap != NULL));
- }
- } // release lock
-}
-
-void EventHub::monitor() {
- // Acquire and release the lock to ensure that the event hub has not deadlocked.
- mLock.lock();
- mLock.unlock();
-}
-
-
-}; // namespace android
diff --git a/widget/gonk/libui/EventHub.h b/widget/gonk/libui/EventHub.h
deleted file mode 100644
index e4e658b21..000000000
--- a/widget/gonk/libui/EventHub.h
+++ /dev/null
@@ -1,435 +0,0 @@
-/*
- * Copyright (C) 2005 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//
-#ifndef _RUNTIME_EVENT_HUB_H
-#define _RUNTIME_EVENT_HUB_H
-
-#include "Input.h"
-#include "InputDevice.h"
-#include "Keyboard.h"
-#include "KeyLayoutMap.h"
-#include "KeyCharacterMap.h"
-#include "VirtualKeyMap.h"
-#include <utils/String8.h>
-#include <utils/threads.h>
-#include "cutils_log.h"
-#include <utils/threads.h>
-#include <utils/List.h>
-#include <utils/Errors.h>
-#include <utils/PropertyMap.h>
-#include <utils/Vector.h>
-#include <utils/KeyedVector.h>
-
-#include "linux_input.h"
-#include <sys/epoll.h>
-
-/* Convenience constants. */
-
-#define BTN_FIRST 0x100 // first button code
-#define BTN_LAST 0x15f // last button code
-
-/*
- * These constants are used privately in Android to pass raw timestamps
- * through evdev from uinput device drivers because there is currently no
- * other way to transfer this information. The evdev driver automatically
- * timestamps all input events with the time they were posted and clobbers
- * whatever information was passed in.
- *
- * For the purposes of this hack, the timestamp is specified in the
- * CLOCK_MONOTONIC timebase and is split into two EV_MSC events specifying
- * seconds and microseconds.
- */
-#define MSC_ANDROID_TIME_SEC 0x6
-#define MSC_ANDROID_TIME_USEC 0x7
-
-namespace android {
-
-enum {
- // Device id of a special "virtual" keyboard that is always present.
- VIRTUAL_KEYBOARD_ID = -1,
- // Device id of the "built-in" keyboard if there is one.
- BUILT_IN_KEYBOARD_ID = 0,
-};
-
-/*
- * A raw event as retrieved from the EventHub.
- */
-struct RawEvent {
- nsecs_t when;
- int32_t deviceId;
- int32_t type;
- int32_t code;
- int32_t value;
-};
-
-/* Describes an absolute axis. */
-struct RawAbsoluteAxisInfo {
- bool valid; // true if the information is valid, false otherwise
-
- int32_t minValue; // minimum value
- int32_t maxValue; // maximum value
- int32_t flat; // center flat position, eg. flat == 8 means center is between -8 and 8
- int32_t fuzz; // error tolerance, eg. fuzz == 4 means value is +/- 4 due to noise
- int32_t resolution; // resolution in units per mm or radians per mm
-
- inline void clear() {
- valid = false;
- minValue = 0;
- maxValue = 0;
- flat = 0;
- fuzz = 0;
- resolution = 0;
- }
-};
-
-/*
- * Input device classes.
- */
-enum {
- /* The input device is a keyboard or has buttons. */
- INPUT_DEVICE_CLASS_KEYBOARD = 0x00000001,
-
- /* The input device is an alpha-numeric keyboard (not just a dial pad). */
- INPUT_DEVICE_CLASS_ALPHAKEY = 0x00000002,
-
- /* The input device is a touchscreen or a touchpad (either single-touch or multi-touch). */
- INPUT_DEVICE_CLASS_TOUCH = 0x00000004,
-
- /* The input device is a cursor device such as a trackball or mouse. */
- INPUT_DEVICE_CLASS_CURSOR = 0x00000008,
-
- /* The input device is a multi-touch touchscreen. */
- INPUT_DEVICE_CLASS_TOUCH_MT = 0x00000010,
-
- /* The input device is a directional pad (implies keyboard, has DPAD keys). */
- INPUT_DEVICE_CLASS_DPAD = 0x00000020,
-
- /* The input device is a gamepad (implies keyboard, has BUTTON keys). */
- INPUT_DEVICE_CLASS_GAMEPAD = 0x00000040,
-
- /* The input device has switches. */
- INPUT_DEVICE_CLASS_SWITCH = 0x00000080,
-
- /* The input device is a joystick (implies gamepad, has joystick absolute axes). */
- INPUT_DEVICE_CLASS_JOYSTICK = 0x00000100,
-
- /* The input device has a vibrator (supports FF_RUMBLE). */
- INPUT_DEVICE_CLASS_VIBRATOR = 0x00000200,
-
- /* The input device is virtual (not a real device, not part of UI configuration). */
- INPUT_DEVICE_CLASS_VIRTUAL = 0x40000000,
-
- /* The input device is external (not built-in). */
- INPUT_DEVICE_CLASS_EXTERNAL = 0x80000000,
-};
-
-/*
- * Gets the class that owns an axis, in cases where multiple classes might claim
- * the same axis for different purposes.
- */
-extern uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses);
-
-/*
- * Grand Central Station for events.
- *
- * The event hub aggregates input events received across all known input
- * devices on the system, including devices that may be emulated by the simulator
- * environment. In addition, the event hub generates fake input events to indicate
- * when devices are added or removed.
- *
- * The event hub provides a stream of input events (via the getEvent function).
- * It also supports querying the current actual state of input devices such as identifying
- * which keys are currently down. Finally, the event hub keeps track of the capabilities of
- * individual input devices, such as their class and the set of key codes that they support.
- */
-class EventHubInterface : public virtual RefBase {
-protected:
- EventHubInterface() { }
- virtual ~EventHubInterface() { }
-
-public:
- // Synthetic raw event type codes produced when devices are added or removed.
- enum {
- // Sent when a device is added.
- DEVICE_ADDED = 0x10000000,
- // Sent when a device is removed.
- DEVICE_REMOVED = 0x20000000,
- // Sent when all added/removed devices from the most recent scan have been reported.
- // This event is always sent at least once.
- FINISHED_DEVICE_SCAN = 0x30000000,
-
- FIRST_SYNTHETIC_EVENT = DEVICE_ADDED,
- };
-
- virtual uint32_t getDeviceClasses(int32_t deviceId) const = 0;
-
- virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const = 0;
-
- virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const = 0;
-
- virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
- RawAbsoluteAxisInfo* outAxisInfo) const = 0;
-
- virtual bool hasRelativeAxis(int32_t deviceId, int axis) const = 0;
-
- virtual bool hasInputProperty(int32_t deviceId, int property) const = 0;
-
- virtual status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
- int32_t* outKeycode, uint32_t* outFlags) const = 0;
-
- virtual status_t mapAxis(int32_t deviceId, int32_t scanCode,
- AxisInfo* outAxisInfo) const = 0;
-
- // Sets devices that are excluded from opening.
- // This can be used to ignore input devices for sensors.
- virtual void setExcludedDevices(const Vector<String8>& devices) = 0;
-
- /*
- * Wait for events to become available and returns them.
- * After returning, the EventHub holds onto a wake lock until the next call to getEvent.
- * This ensures that the device will not go to sleep while the event is being processed.
- * If the device needs to remain awake longer than that, then the caller is responsible
- * for taking care of it (say, by poking the power manager user activity timer).
- *
- * The timeout is advisory only. If the device is asleep, it will not wake just to
- * service the timeout.
- *
- * Returns the number of events obtained, or 0 if the timeout expired.
- */
- virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) = 0;
-
- /*
- * Query current input state.
- */
- virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const = 0;
- virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const = 0;
- virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const = 0;
- virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis,
- int32_t* outValue) const = 0;
-
- /*
- * Examine key input devices for specific framework keycode support
- */
- virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
- uint8_t* outFlags) const = 0;
-
- virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0;
- virtual bool hasLed(int32_t deviceId, int32_t led) const = 0;
- virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0;
-
- virtual void getVirtualKeyDefinitions(int32_t deviceId,
- Vector<VirtualKeyDefinition>& outVirtualKeys) const = 0;
-
- virtual sp<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const = 0;
- virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) = 0;
-
- /* Control the vibrator. */
- virtual void vibrate(int32_t deviceId, nsecs_t duration) = 0;
- virtual void cancelVibrate(int32_t deviceId) = 0;
-
- /* Requests the EventHub to reopen all input devices on the next call to getEvents(). */
- virtual void requestReopenDevices() = 0;
-
- /* Wakes up getEvents() if it is blocked on a read. */
- virtual void wake() = 0;
-
- /* Dump EventHub state to a string. */
- virtual void dump(String8& dump) = 0;
-
- /* Called by the heatbeat to ensures that the reader has not deadlocked. */
- virtual void monitor() = 0;
-};
-
-class EventHub : public EventHubInterface
-{
-public:
- EventHub();
-
- virtual uint32_t getDeviceClasses(int32_t deviceId) const;
-
- virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const;
-
- virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const;
-
- virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
- RawAbsoluteAxisInfo* outAxisInfo) const;
-
- virtual bool hasRelativeAxis(int32_t deviceId, int axis) const;
-
- virtual bool hasInputProperty(int32_t deviceId, int property) const;
-
- virtual status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
- int32_t* outKeycode, uint32_t* outFlags) const;
-
- virtual status_t mapAxis(int32_t deviceId, int32_t scanCode,
- AxisInfo* outAxisInfo) const;
-
- virtual void setExcludedDevices(const Vector<String8>& devices);
-
- virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const;
- virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const;
- virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const;
- virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const;
-
- virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags) const;
-
- virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize);
-
- virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const;
- virtual bool hasLed(int32_t deviceId, int32_t led) const;
- virtual void setLedState(int32_t deviceId, int32_t led, bool on);
-
- virtual void getVirtualKeyDefinitions(int32_t deviceId,
- Vector<VirtualKeyDefinition>& outVirtualKeys) const;
-
- virtual sp<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const;
- virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map);
-
- virtual void vibrate(int32_t deviceId, nsecs_t duration);
- virtual void cancelVibrate(int32_t deviceId);
-
- virtual void requestReopenDevices();
-
- virtual void wake();
-
- virtual void dump(String8& dump);
- virtual void monitor();
-
-protected:
- virtual ~EventHub();
-
-private:
- struct Device {
- Device* next;
-
- int fd; // may be -1 if device is virtual
- const int32_t id;
- const String8 path;
- const InputDeviceIdentifier identifier;
-
- uint32_t classes;
-
- uint8_t keyBitmask[(KEY_MAX + 1) / 8];
- uint8_t absBitmask[(ABS_MAX + 1) / 8];
- uint8_t relBitmask[(REL_MAX + 1) / 8];
- uint8_t swBitmask[(SW_MAX + 1) / 8];
- uint8_t ledBitmask[(LED_MAX + 1) / 8];
- uint8_t ffBitmask[(FF_MAX + 1) / 8];
- uint8_t propBitmask[(INPUT_PROP_MAX + 1) / 8];
-
- String8 configurationFile;
- PropertyMap* configuration;
- VirtualKeyMap* virtualKeyMap;
- KeyMap keyMap;
-
- sp<KeyCharacterMap> overlayKeyMap;
- sp<KeyCharacterMap> combinedKeyMap;
-
- bool ffEffectPlaying;
- int16_t ffEffectId; // initially -1
-
- int32_t timestampOverrideSec;
- int32_t timestampOverrideUsec;
-
- Device(int fd, int32_t id, const String8& path, const InputDeviceIdentifier& identifier);
- ~Device();
-
- void close();
-
- inline bool isVirtual() const { return fd < 0; }
-
- const sp<KeyCharacterMap>& getKeyCharacterMap() const {
- if (combinedKeyMap != NULL) {
- return combinedKeyMap;
- }
- return keyMap.keyCharacterMap;
- }
- };
-
- status_t openDeviceLocked(const char *devicePath);
- void createVirtualKeyboardLocked();
- void addDeviceLocked(Device* device);
-
- status_t closeDeviceByPathLocked(const char *devicePath);
- void closeDeviceLocked(Device* device);
- void closeAllDevicesLocked();
-
- status_t scanDirLocked(const char *dirname);
- void scanDevicesLocked();
- status_t readNotifyLocked();
-
- Device* getDeviceLocked(int32_t deviceId) const;
- Device* getDeviceByPathLocked(const char* devicePath) const;
-
- bool hasKeycodeLocked(Device* device, int keycode) const;
-
- void loadConfigurationLocked(Device* device);
- status_t loadVirtualKeyMapLocked(Device* device);
- status_t loadKeyMapLocked(Device* device);
-
- bool isExternalDeviceLocked(Device* device);
-
- // Protect all internal state.
- mutable Mutex mLock;
-
- // The actual id of the built-in keyboard, or NO_BUILT_IN_KEYBOARD if none.
- // EventHub remaps the built-in keyboard to id 0 externally as required by the API.
- enum {
- // Must not conflict with any other assigned device ids, including
- // the virtual keyboard id (-1).
- NO_BUILT_IN_KEYBOARD = -2,
- };
- int32_t mBuiltInKeyboardId;
-
- int32_t mNextDeviceId;
-
- KeyedVector<int32_t, Device*> mDevices;
-
- Device *mOpeningDevices;
- Device *mClosingDevices;
-
- bool mNeedToSendFinishedDeviceScan;
- bool mNeedToReopenDevices;
- bool mNeedToScanDevices;
- Vector<String8> mExcludedDevices;
-
- int mEpollFd;
- int mINotifyFd;
- int mWakeReadPipeFd;
- int mWakeWritePipeFd;
-
- // Ids used for epoll notifications not associated with devices.
- static const uint32_t EPOLL_ID_INOTIFY = 0x80000001;
- static const uint32_t EPOLL_ID_WAKE = 0x80000002;
-
- // Epoll FD list size hint.
- static const int EPOLL_SIZE_HINT = 8;
-
- // Maximum number of signalled FDs to handle at a time.
- static const int EPOLL_MAX_EVENTS = 16;
-
- // The array of pending epoll events and the index of the next event to be handled.
- struct epoll_event mPendingEventItems[EPOLL_MAX_EVENTS];
- size_t mPendingEventCount;
- size_t mPendingEventIndex;
- bool mPendingINotify;
-};
-
-}; // namespace android
-
-#endif // _RUNTIME_EVENT_HUB_H
diff --git a/widget/gonk/libui/Input.cpp b/widget/gonk/libui/Input.cpp
deleted file mode 100644
index 2208191e6..000000000
--- a/widget/gonk/libui/Input.cpp
+++ /dev/null
@@ -1,635 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "Input"
-//#define LOG_NDEBUG 0
-#include "cutils_log.h"
-
-#include <math.h>
-#include <limits.h>
-
-#include "Input.h"
-
-#ifdef HAVE_ANDROID_OS
-#include <binder/Parcel.h>
-
-#include "SkPoint.h"
-#include "SkMatrix.h"
-#include "SkScalar.h"
-#endif
-
-namespace android {
-
-// --- InputEvent ---
-
-void InputEvent::initialize(int32_t deviceId, int32_t source) {
- mDeviceId = deviceId;
- mSource = source;
-}
-
-void InputEvent::initialize(const InputEvent& from) {
- mDeviceId = from.mDeviceId;
- mSource = from.mSource;
-}
-
-// --- KeyEvent ---
-
-bool KeyEvent::hasDefaultAction(int32_t keyCode) {
- switch (keyCode) {
- case AKEYCODE_HOME:
- case AKEYCODE_BACK:
- case AKEYCODE_CALL:
- case AKEYCODE_ENDCALL:
- case AKEYCODE_VOLUME_UP:
- case AKEYCODE_VOLUME_DOWN:
- case AKEYCODE_VOLUME_MUTE:
- case AKEYCODE_POWER:
- case AKEYCODE_CAMERA:
- case AKEYCODE_HEADSETHOOK:
- case AKEYCODE_MENU:
- case AKEYCODE_NOTIFICATION:
- case AKEYCODE_FOCUS:
- case AKEYCODE_SEARCH:
- case AKEYCODE_MEDIA_PLAY:
- case AKEYCODE_MEDIA_PAUSE:
- case AKEYCODE_MEDIA_PLAY_PAUSE:
- case AKEYCODE_MEDIA_STOP:
- case AKEYCODE_MEDIA_NEXT:
- case AKEYCODE_MEDIA_PREVIOUS:
- case AKEYCODE_MEDIA_REWIND:
- case AKEYCODE_MEDIA_RECORD:
- case AKEYCODE_MEDIA_FAST_FORWARD:
- case AKEYCODE_MUTE:
- case AKEYCODE_BRIGHTNESS_DOWN:
- case AKEYCODE_BRIGHTNESS_UP:
- return true;
- }
-
- return false;
-}
-
-bool KeyEvent::hasDefaultAction() const {
- return hasDefaultAction(getKeyCode());
-}
-
-bool KeyEvent::isSystemKey(int32_t keyCode) {
- switch (keyCode) {
- case AKEYCODE_MENU:
- case AKEYCODE_SOFT_RIGHT:
- case AKEYCODE_HOME:
- case AKEYCODE_BACK:
- case AKEYCODE_CALL:
- case AKEYCODE_ENDCALL:
- case AKEYCODE_VOLUME_UP:
- case AKEYCODE_VOLUME_DOWN:
- case AKEYCODE_VOLUME_MUTE:
- case AKEYCODE_MUTE:
- case AKEYCODE_POWER:
- case AKEYCODE_HEADSETHOOK:
- case AKEYCODE_MEDIA_PLAY:
- case AKEYCODE_MEDIA_PAUSE:
- case AKEYCODE_MEDIA_PLAY_PAUSE:
- case AKEYCODE_MEDIA_STOP:
- case AKEYCODE_MEDIA_NEXT:
- case AKEYCODE_MEDIA_PREVIOUS:
- case AKEYCODE_MEDIA_REWIND:
- case AKEYCODE_MEDIA_RECORD:
- case AKEYCODE_MEDIA_FAST_FORWARD:
- case AKEYCODE_CAMERA:
- case AKEYCODE_FOCUS:
- case AKEYCODE_SEARCH:
- case AKEYCODE_BRIGHTNESS_DOWN:
- case AKEYCODE_BRIGHTNESS_UP:
- return true;
- }
-
- return false;
-}
-
-bool KeyEvent::isSystemKey() const {
- return isSystemKey(getKeyCode());
-}
-
-void KeyEvent::initialize(
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t keyCode,
- int32_t scanCode,
- int32_t metaState,
- int32_t repeatCount,
- nsecs_t downTime,
- nsecs_t eventTime) {
- InputEvent::initialize(deviceId, source);
- mAction = action;
- mFlags = flags;
- mKeyCode = keyCode;
- mScanCode = scanCode;
- mMetaState = metaState;
- mRepeatCount = repeatCount;
- mDownTime = downTime;
- mEventTime = eventTime;
-}
-
-void KeyEvent::initialize(const KeyEvent& from) {
- InputEvent::initialize(from);
- mAction = from.mAction;
- mFlags = from.mFlags;
- mKeyCode = from.mKeyCode;
- mScanCode = from.mScanCode;
- mMetaState = from.mMetaState;
- mRepeatCount = from.mRepeatCount;
- mDownTime = from.mDownTime;
- mEventTime = from.mEventTime;
-}
-
-
-// --- PointerCoords ---
-
-float PointerCoords::getAxisValue(int32_t axis) const {
- if (axis < 0 || axis > 63) {
- return 0;
- }
-
- uint64_t axisBit = 1LL << axis;
- if (!(bits & axisBit)) {
- return 0;
- }
- uint32_t index = __builtin_popcountll(bits & (axisBit - 1LL));
- return values[index];
-}
-
-status_t PointerCoords::setAxisValue(int32_t axis, float value) {
- if (axis < 0 || axis > 63) {
- return NAME_NOT_FOUND;
- }
-
- uint64_t axisBit = 1LL << axis;
- uint32_t index = __builtin_popcountll(bits & (axisBit - 1LL));
- if (!(bits & axisBit)) {
- if (value == 0) {
- return OK; // axes with value 0 do not need to be stored
- }
- uint32_t count = __builtin_popcountll(bits);
- if (count >= MAX_AXES) {
- tooManyAxes(axis);
- return NO_MEMORY;
- }
- bits |= axisBit;
- for (uint32_t i = count; i > index; i--) {
- values[i] = values[i - 1];
- }
- }
- values[index] = value;
- return OK;
-}
-
-static inline void scaleAxisValue(PointerCoords& c, int axis, float scaleFactor) {
- float value = c.getAxisValue(axis);
- if (value != 0) {
- c.setAxisValue(axis, value * scaleFactor);
- }
-}
-
-void PointerCoords::scale(float scaleFactor) {
- // No need to scale pressure or size since they are normalized.
- // No need to scale orientation since it is meaningless to do so.
- scaleAxisValue(*this, AMOTION_EVENT_AXIS_X, scaleFactor);
- scaleAxisValue(*this, AMOTION_EVENT_AXIS_Y, scaleFactor);
- scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MAJOR, scaleFactor);
- scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MINOR, scaleFactor);
- scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MAJOR, scaleFactor);
- scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MINOR, scaleFactor);
-}
-
-#ifdef HAVE_ANDROID_OS
-status_t PointerCoords::readFromParcel(Parcel* parcel) {
- bits = parcel->readInt64();
-
- uint32_t count = __builtin_popcountll(bits);
- if (count > MAX_AXES) {
- return BAD_VALUE;
- }
-
- for (uint32_t i = 0; i < count; i++) {
- values[i] = parcel->readFloat();
- }
- return OK;
-}
-
-status_t PointerCoords::writeToParcel(Parcel* parcel) const {
- parcel->writeInt64(bits);
-
- uint32_t count = __builtin_popcountll(bits);
- for (uint32_t i = 0; i < count; i++) {
- parcel->writeFloat(values[i]);
- }
- return OK;
-}
-#endif
-
-void PointerCoords::tooManyAxes(int axis) {
- ALOGW("Could not set value for axis %d because the PointerCoords structure is full and "
- "cannot contain more than %d axis values.", axis, int(MAX_AXES));
-}
-
-bool PointerCoords::operator==(const PointerCoords& other) const {
- if (bits != other.bits) {
- return false;
- }
- uint32_t count = __builtin_popcountll(bits);
- for (uint32_t i = 0; i < count; i++) {
- if (values[i] != other.values[i]) {
- return false;
- }
- }
- return true;
-}
-
-void PointerCoords::copyFrom(const PointerCoords& other) {
- bits = other.bits;
- uint32_t count = __builtin_popcountll(bits);
- for (uint32_t i = 0; i < count; i++) {
- values[i] = other.values[i];
- }
-}
-
-
-// --- PointerProperties ---
-
-bool PointerProperties::operator==(const PointerProperties& other) const {
- return id == other.id
- && toolType == other.toolType;
-}
-
-void PointerProperties::copyFrom(const PointerProperties& other) {
- id = other.id;
- toolType = other.toolType;
-}
-
-
-// --- MotionEvent ---
-
-void MotionEvent::initialize(
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t edgeFlags,
- int32_t metaState,
- int32_t buttonState,
- float xOffset,
- float yOffset,
- float xPrecision,
- float yPrecision,
- nsecs_t downTime,
- nsecs_t eventTime,
- size_t pointerCount,
- const PointerProperties* pointerProperties,
- const PointerCoords* pointerCoords) {
- InputEvent::initialize(deviceId, source);
- mAction = action;
- mFlags = flags;
- mEdgeFlags = edgeFlags;
- mMetaState = metaState;
- mButtonState = buttonState;
- mXOffset = xOffset;
- mYOffset = yOffset;
- mXPrecision = xPrecision;
- mYPrecision = yPrecision;
- mDownTime = downTime;
- mPointerProperties.clear();
- mPointerProperties.appendArray(pointerProperties, pointerCount);
- mSampleEventTimes.clear();
- mSamplePointerCoords.clear();
- addSample(eventTime, pointerCoords);
-}
-
-void MotionEvent::copyFrom(const MotionEvent* other, bool keepHistory) {
- InputEvent::initialize(other->mDeviceId, other->mSource);
- mAction = other->mAction;
- mFlags = other->mFlags;
- mEdgeFlags = other->mEdgeFlags;
- mMetaState = other->mMetaState;
- mButtonState = other->mButtonState;
- mXOffset = other->mXOffset;
- mYOffset = other->mYOffset;
- mXPrecision = other->mXPrecision;
- mYPrecision = other->mYPrecision;
- mDownTime = other->mDownTime;
- mPointerProperties = other->mPointerProperties;
-
- if (keepHistory) {
- mSampleEventTimes = other->mSampleEventTimes;
- mSamplePointerCoords = other->mSamplePointerCoords;
- } else {
- mSampleEventTimes.clear();
- mSampleEventTimes.push(other->getEventTime());
- mSamplePointerCoords.clear();
- size_t pointerCount = other->getPointerCount();
- size_t historySize = other->getHistorySize();
- mSamplePointerCoords.appendArray(other->mSamplePointerCoords.array()
- + (historySize * pointerCount), pointerCount);
- }
-}
-
-void MotionEvent::addSample(
- int64_t eventTime,
- const PointerCoords* pointerCoords) {
- mSampleEventTimes.push(eventTime);
- mSamplePointerCoords.appendArray(pointerCoords, getPointerCount());
-}
-
-const PointerCoords* MotionEvent::getRawPointerCoords(size_t pointerIndex) const {
- return &mSamplePointerCoords[getHistorySize() * getPointerCount() + pointerIndex];
-}
-
-float MotionEvent::getRawAxisValue(int32_t axis, size_t pointerIndex) const {
- return getRawPointerCoords(pointerIndex)->getAxisValue(axis);
-}
-
-float MotionEvent::getAxisValue(int32_t axis, size_t pointerIndex) const {
- float value = getRawPointerCoords(pointerIndex)->getAxisValue(axis);
- switch (axis) {
- case AMOTION_EVENT_AXIS_X:
- return value + mXOffset;
- case AMOTION_EVENT_AXIS_Y:
- return value + mYOffset;
- }
- return value;
-}
-
-const PointerCoords* MotionEvent::getHistoricalRawPointerCoords(
- size_t pointerIndex, size_t historicalIndex) const {
- return &mSamplePointerCoords[historicalIndex * getPointerCount() + pointerIndex];
-}
-
-float MotionEvent::getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
- size_t historicalIndex) const {
- return getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
-}
-
-float MotionEvent::getHistoricalAxisValue(int32_t axis, size_t pointerIndex,
- size_t historicalIndex) const {
- float value = getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
- switch (axis) {
- case AMOTION_EVENT_AXIS_X:
- return value + mXOffset;
- case AMOTION_EVENT_AXIS_Y:
- return value + mYOffset;
- }
- return value;
-}
-
-ssize_t MotionEvent::findPointerIndex(int32_t pointerId) const {
- size_t pointerCount = mPointerProperties.size();
- for (size_t i = 0; i < pointerCount; i++) {
- if (mPointerProperties.itemAt(i).id == pointerId) {
- return i;
- }
- }
- return -1;
-}
-
-void MotionEvent::offsetLocation(float xOffset, float yOffset) {
- mXOffset += xOffset;
- mYOffset += yOffset;
-}
-
-void MotionEvent::scale(float scaleFactor) {
- mXOffset *= scaleFactor;
- mYOffset *= scaleFactor;
- mXPrecision *= scaleFactor;
- mYPrecision *= scaleFactor;
-
- size_t numSamples = mSamplePointerCoords.size();
- for (size_t i = 0; i < numSamples; i++) {
- mSamplePointerCoords.editItemAt(i).scale(scaleFactor);
- }
-}
-
-#ifdef HAVE_ANDROID_OS
-static inline float transformAngle(const SkMatrix* matrix, float angleRadians) {
- // Construct and transform a vector oriented at the specified clockwise angle from vertical.
- // Coordinate system: down is increasing Y, right is increasing X.
- SkPoint vector;
- vector.fX = SkFloatToScalar(sinf(angleRadians));
- vector.fY = SkFloatToScalar(-cosf(angleRadians));
- matrix->mapVectors(& vector, 1);
-
- // Derive the transformed vector's clockwise angle from vertical.
- float result = atan2f(SkScalarToFloat(vector.fX), SkScalarToFloat(-vector.fY));
- if (result < - M_PI_2) {
- result += M_PI;
- } else if (result > M_PI_2) {
- result -= M_PI;
- }
- return result;
-}
-
-void MotionEvent::transform(const SkMatrix* matrix) {
- float oldXOffset = mXOffset;
- float oldYOffset = mYOffset;
-
- // The tricky part of this implementation is to preserve the value of
- // rawX and rawY. So we apply the transformation to the first point
- // then derive an appropriate new X/Y offset that will preserve rawX and rawY.
- SkPoint point;
- float rawX = getRawX(0);
- float rawY = getRawY(0);
- matrix->mapXY(SkFloatToScalar(rawX + oldXOffset), SkFloatToScalar(rawY + oldYOffset),
- & point);
- float newX = SkScalarToFloat(point.fX);
- float newY = SkScalarToFloat(point.fY);
- float newXOffset = newX - rawX;
- float newYOffset = newY - rawY;
-
- mXOffset = newXOffset;
- mYOffset = newYOffset;
-
- // Apply the transformation to all samples.
- size_t numSamples = mSamplePointerCoords.size();
- for (size_t i = 0; i < numSamples; i++) {
- PointerCoords& c = mSamplePointerCoords.editItemAt(i);
- float x = c.getAxisValue(AMOTION_EVENT_AXIS_X) + oldXOffset;
- float y = c.getAxisValue(AMOTION_EVENT_AXIS_Y) + oldYOffset;
- matrix->mapXY(SkFloatToScalar(x), SkFloatToScalar(y), &point);
- c.setAxisValue(AMOTION_EVENT_AXIS_X, SkScalarToFloat(point.fX) - newXOffset);
- c.setAxisValue(AMOTION_EVENT_AXIS_Y, SkScalarToFloat(point.fY) - newYOffset);
-
- float orientation = c.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
- c.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, transformAngle(matrix, orientation));
- }
-}
-
-status_t MotionEvent::readFromParcel(Parcel* parcel) {
- size_t pointerCount = parcel->readInt32();
- size_t sampleCount = parcel->readInt32();
- if (pointerCount == 0 || pointerCount > MAX_POINTERS || sampleCount == 0) {
- return BAD_VALUE;
- }
-
- mDeviceId = parcel->readInt32();
- mSource = parcel->readInt32();
- mAction = parcel->readInt32();
- mFlags = parcel->readInt32();
- mEdgeFlags = parcel->readInt32();
- mMetaState = parcel->readInt32();
- mButtonState = parcel->readInt32();
- mXOffset = parcel->readFloat();
- mYOffset = parcel->readFloat();
- mXPrecision = parcel->readFloat();
- mYPrecision = parcel->readFloat();
- mDownTime = parcel->readInt64();
-
- mPointerProperties.clear();
- mPointerProperties.setCapacity(pointerCount);
- mSampleEventTimes.clear();
- mSampleEventTimes.setCapacity(sampleCount);
- mSamplePointerCoords.clear();
- mSamplePointerCoords.setCapacity(sampleCount * pointerCount);
-
- for (size_t i = 0; i < pointerCount; i++) {
- mPointerProperties.push();
- PointerProperties& properties = mPointerProperties.editTop();
- properties.id = parcel->readInt32();
- properties.toolType = parcel->readInt32();
- }
-
- while (sampleCount-- > 0) {
- mSampleEventTimes.push(parcel->readInt64());
- for (size_t i = 0; i < pointerCount; i++) {
- mSamplePointerCoords.push();
- status_t status = mSamplePointerCoords.editTop().readFromParcel(parcel);
- if (status) {
- return status;
- }
- }
- }
- return OK;
-}
-
-status_t MotionEvent::writeToParcel(Parcel* parcel) const {
- size_t pointerCount = mPointerProperties.size();
- size_t sampleCount = mSampleEventTimes.size();
-
- parcel->writeInt32(pointerCount);
- parcel->writeInt32(sampleCount);
-
- parcel->writeInt32(mDeviceId);
- parcel->writeInt32(mSource);
- parcel->writeInt32(mAction);
- parcel->writeInt32(mFlags);
- parcel->writeInt32(mEdgeFlags);
- parcel->writeInt32(mMetaState);
- parcel->writeInt32(mButtonState);
- parcel->writeFloat(mXOffset);
- parcel->writeFloat(mYOffset);
- parcel->writeFloat(mXPrecision);
- parcel->writeFloat(mYPrecision);
- parcel->writeInt64(mDownTime);
-
- for (size_t i = 0; i < pointerCount; i++) {
- const PointerProperties& properties = mPointerProperties.itemAt(i);
- parcel->writeInt32(properties.id);
- parcel->writeInt32(properties.toolType);
- }
-
- const PointerCoords* pc = mSamplePointerCoords.array();
- for (size_t h = 0; h < sampleCount; h++) {
- parcel->writeInt64(mSampleEventTimes.itemAt(h));
- for (size_t i = 0; i < pointerCount; i++) {
- status_t status = (pc++)->writeToParcel(parcel);
- if (status) {
- return status;
- }
- }
- }
- return OK;
-}
-#endif
-
-bool MotionEvent::isTouchEvent(int32_t source, int32_t action) {
- if (source & AINPUT_SOURCE_CLASS_POINTER) {
- // Specifically excludes HOVER_MOVE and SCROLL.
- switch (action & AMOTION_EVENT_ACTION_MASK) {
- case AMOTION_EVENT_ACTION_DOWN:
- case AMOTION_EVENT_ACTION_MOVE:
- case AMOTION_EVENT_ACTION_UP:
- case AMOTION_EVENT_ACTION_POINTER_DOWN:
- case AMOTION_EVENT_ACTION_POINTER_UP:
- case AMOTION_EVENT_ACTION_CANCEL:
- case AMOTION_EVENT_ACTION_OUTSIDE:
- return true;
- }
- }
- return false;
-}
-
-
-// --- PooledInputEventFactory ---
-
-PooledInputEventFactory::PooledInputEventFactory(size_t maxPoolSize) :
- mMaxPoolSize(maxPoolSize) {
-}
-
-PooledInputEventFactory::~PooledInputEventFactory() {
- for (size_t i = 0; i < mKeyEventPool.size(); i++) {
- delete mKeyEventPool.itemAt(i);
- }
- for (size_t i = 0; i < mMotionEventPool.size(); i++) {
- delete mMotionEventPool.itemAt(i);
- }
-}
-
-KeyEvent* PooledInputEventFactory::createKeyEvent() {
- if (!mKeyEventPool.isEmpty()) {
- KeyEvent* event = mKeyEventPool.top();
- mKeyEventPool.pop();
- return event;
- }
- return new KeyEvent();
-}
-
-MotionEvent* PooledInputEventFactory::createMotionEvent() {
- if (!mMotionEventPool.isEmpty()) {
- MotionEvent* event = mMotionEventPool.top();
- mMotionEventPool.pop();
- return event;
- }
- return new MotionEvent();
-}
-
-void PooledInputEventFactory::recycle(InputEvent* event) {
- switch (event->getType()) {
- case AINPUT_EVENT_TYPE_KEY:
- if (mKeyEventPool.size() < mMaxPoolSize) {
- mKeyEventPool.push(static_cast<KeyEvent*>(event));
- return;
- }
- break;
- case AINPUT_EVENT_TYPE_MOTION:
- if (mMotionEventPool.size() < mMaxPoolSize) {
- mMotionEventPool.push(static_cast<MotionEvent*>(event));
- return;
- }
- break;
- }
- delete event;
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/Input.h b/widget/gonk/libui/Input.h
deleted file mode 100644
index 3d958bfab..000000000
--- a/widget/gonk/libui/Input.h
+++ /dev/null
@@ -1,622 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_INPUT_H
-#define _ANDROIDFW_INPUT_H
-
-/**
- * Native input event structures.
- */
-
-#include "android_input.h"
-#include <utils/Vector.h>
-#include <utils/KeyedVector.h>
-#include <utils/Timers.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-
-#ifdef HAVE_ANDROID_OS
-class SkMatrix;
-#endif
-
-/*
- * Additional private constants not defined in ndk/ui/input.h.
- */
-enum {
- /* Signifies that the key is being predispatched */
- AKEY_EVENT_FLAG_PREDISPATCH = 0x20000000,
-
- /* Private control to determine when an app is tracking a key sequence. */
- AKEY_EVENT_FLAG_START_TRACKING = 0x40000000,
-
- /* Key event is inconsistent with previously sent key events. */
- AKEY_EVENT_FLAG_TAINTED = 0x80000000,
-};
-
-enum {
- /* Motion event is inconsistent with previously sent motion events. */
- AMOTION_EVENT_FLAG_TAINTED = 0x80000000,
-};
-
-enum {
- /* Used when a motion event is not associated with any display.
- * Typically used for non-pointer events. */
- ADISPLAY_ID_NONE = -1,
-
- /* The default display id. */
- ADISPLAY_ID_DEFAULT = 0,
-};
-
-enum {
- /*
- * Indicates that an input device has switches.
- * This input source flag is hidden from the API because switches are only used by the system
- * and applications have no way to interact with them.
- */
- AINPUT_SOURCE_SWITCH = 0x80000000,
-};
-
-/*
- * SystemUiVisibility constants from View.
- */
-enum {
- ASYSTEM_UI_VISIBILITY_STATUS_BAR_VISIBLE = 0,
- ASYSTEM_UI_VISIBILITY_STATUS_BAR_HIDDEN = 0x00000001,
-};
-
-/*
- * Maximum number of pointers supported per motion event.
- * Smallest number of pointers is 1.
- * (We want at least 10 but some touch controllers obstensibly configured for 10 pointers
- * will occasionally emit 11. There is not much harm making this constant bigger.)
- */
-#define MAX_POINTERS 16
-
-/*
- * Maximum pointer id value supported in a motion event.
- * Smallest pointer id is 0.
- * (This is limited by our use of BitSet32 to track pointer assignments.)
- */
-#define MAX_POINTER_ID 31
-
-/*
- * Declare a concrete type for the NDK's input event forward declaration.
- */
-struct AInputEvent {
- virtual ~AInputEvent() { }
-};
-
-/*
- * Declare a concrete type for the NDK's input device forward declaration.
- */
-struct AInputDevice {
- virtual ~AInputDevice() { }
-};
-
-
-namespace android {
-
-#ifdef HAVE_ANDROID_OS
-class Parcel;
-#endif
-
-/*
- * Flags that flow alongside events in the input dispatch system to help with certain
- * policy decisions such as waking from device sleep.
- *
- * These flags are also defined in frameworks/base/core/java/android/view/WindowManagerPolicy.java.
- */
-enum {
- /* These flags originate in RawEvents and are generally set in the key map.
- * NOTE: If you edit these flags, also edit labels in KeycodeLabels.h. */
-
- POLICY_FLAG_WAKE = 0x00000001,
- POLICY_FLAG_WAKE_DROPPED = 0x00000002,
- POLICY_FLAG_SHIFT = 0x00000004,
- POLICY_FLAG_CAPS_LOCK = 0x00000008,
- POLICY_FLAG_ALT = 0x00000010,
- POLICY_FLAG_ALT_GR = 0x00000020,
- POLICY_FLAG_MENU = 0x00000040,
- POLICY_FLAG_LAUNCHER = 0x00000080,
- POLICY_FLAG_VIRTUAL = 0x00000100,
- POLICY_FLAG_FUNCTION = 0x00000200,
-
- POLICY_FLAG_RAW_MASK = 0x0000ffff,
-
- /* These flags are set by the input dispatcher. */
-
- // Indicates that the input event was injected.
- POLICY_FLAG_INJECTED = 0x01000000,
-
- // Indicates that the input event is from a trusted source such as a directly attached
- // input device or an application with system-wide event injection permission.
- POLICY_FLAG_TRUSTED = 0x02000000,
-
- // Indicates that the input event has passed through an input filter.
- POLICY_FLAG_FILTERED = 0x04000000,
-
- // Disables automatic key repeating behavior.
- POLICY_FLAG_DISABLE_KEY_REPEAT = 0x08000000,
-
- /* These flags are set by the input reader policy as it intercepts each event. */
-
- // Indicates that the screen was off when the event was received and the event
- // should wake the device.
- POLICY_FLAG_WOKE_HERE = 0x10000000,
-
- // Indicates that the screen was dim when the event was received and the event
- // should brighten the device.
- POLICY_FLAG_BRIGHT_HERE = 0x20000000,
-
- // Indicates that the event should be dispatched to applications.
- // The input event should still be sent to the InputDispatcher so that it can see all
- // input events received include those that it will not deliver.
- POLICY_FLAG_PASS_TO_USER = 0x40000000,
-};
-
-/*
- * Pointer coordinate data.
- */
-struct PointerCoords {
- enum { MAX_AXES = 14 }; // 14 so that sizeof(PointerCoords) == 64
-
- // Bitfield of axes that are present in this structure.
- uint64_t bits;
-
- // Values of axes that are stored in this structure packed in order by axis id
- // for each axis that is present in the structure according to 'bits'.
- float values[MAX_AXES];
-
- inline void clear() {
- bits = 0;
- }
-
- float getAxisValue(int32_t axis) const;
- status_t setAxisValue(int32_t axis, float value);
-
- void scale(float scale);
-
- inline float getX() const {
- return getAxisValue(AMOTION_EVENT_AXIS_X);
- }
-
- inline float getY() const {
- return getAxisValue(AMOTION_EVENT_AXIS_Y);
- }
-
-#ifdef HAVE_ANDROID_OS
- status_t readFromParcel(Parcel* parcel);
- status_t writeToParcel(Parcel* parcel) const;
-#endif
-
- bool operator==(const PointerCoords& other) const;
- inline bool operator!=(const PointerCoords& other) const {
- return !(*this == other);
- }
-
- void copyFrom(const PointerCoords& other);
-
-private:
- void tooManyAxes(int axis);
-};
-
-/*
- * Pointer property data.
- */
-struct PointerProperties {
- // The id of the pointer.
- int32_t id;
-
- // The pointer tool type.
- int32_t toolType;
-
- inline void clear() {
- id = -1;
- toolType = 0;
- }
-
- bool operator==(const PointerProperties& other) const;
- inline bool operator!=(const PointerProperties& other) const {
- return !(*this == other);
- }
-
- void copyFrom(const PointerProperties& other);
-};
-
-/*
- * Input events.
- */
-class InputEvent : public AInputEvent {
-public:
- virtual ~InputEvent() { }
-
- virtual int32_t getType() const = 0;
-
- inline int32_t getDeviceId() const { return mDeviceId; }
-
- inline int32_t getSource() const { return mSource; }
-
- inline void setSource(int32_t source) { mSource = source; }
-
-protected:
- void initialize(int32_t deviceId, int32_t source);
- void initialize(const InputEvent& from);
-
- int32_t mDeviceId;
- int32_t mSource;
-};
-
-/*
- * Key events.
- */
-class KeyEvent : public InputEvent {
-public:
- virtual ~KeyEvent() { }
-
- virtual int32_t getType() const { return AINPUT_EVENT_TYPE_KEY; }
-
- inline int32_t getAction() const { return mAction; }
-
- inline int32_t getFlags() const { return mFlags; }
-
- inline void setFlags(int32_t flags) { mFlags = flags; }
-
- inline int32_t getKeyCode() const { return mKeyCode; }
-
- inline int32_t getScanCode() const { return mScanCode; }
-
- inline int32_t getMetaState() const { return mMetaState; }
-
- inline int32_t getRepeatCount() const { return mRepeatCount; }
-
- inline nsecs_t getDownTime() const { return mDownTime; }
-
- inline nsecs_t getEventTime() const { return mEventTime; }
-
- // Return true if this event may have a default action implementation.
- static bool hasDefaultAction(int32_t keyCode);
- bool hasDefaultAction() const;
-
- // Return true if this event represents a system key.
- static bool isSystemKey(int32_t keyCode);
- bool isSystemKey() const;
-
- void initialize(
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t keyCode,
- int32_t scanCode,
- int32_t metaState,
- int32_t repeatCount,
- nsecs_t downTime,
- nsecs_t eventTime);
- void initialize(const KeyEvent& from);
-
-protected:
- int32_t mAction;
- int32_t mFlags;
- int32_t mKeyCode;
- int32_t mScanCode;
- int32_t mMetaState;
- int32_t mRepeatCount;
- nsecs_t mDownTime;
- nsecs_t mEventTime;
-};
-
-/*
- * Motion events.
- */
-class MotionEvent : public InputEvent {
-public:
- virtual ~MotionEvent() { }
-
- virtual int32_t getType() const { return AINPUT_EVENT_TYPE_MOTION; }
-
- inline int32_t getAction() const { return mAction; }
-
- inline int32_t getActionMasked() const { return mAction & AMOTION_EVENT_ACTION_MASK; }
-
- inline int32_t getActionIndex() const {
- return (mAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
- >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
- }
-
- inline void setAction(int32_t action) { mAction = action; }
-
- inline int32_t getFlags() const { return mFlags; }
-
- inline void setFlags(int32_t flags) { mFlags = flags; }
-
- inline int32_t getEdgeFlags() const { return mEdgeFlags; }
-
- inline void setEdgeFlags(int32_t edgeFlags) { mEdgeFlags = edgeFlags; }
-
- inline int32_t getMetaState() const { return mMetaState; }
-
- inline void setMetaState(int32_t metaState) { mMetaState = metaState; }
-
- inline int32_t getButtonState() const { return mButtonState; }
-
- inline float getXOffset() const { return mXOffset; }
-
- inline float getYOffset() const { return mYOffset; }
-
- inline float getXPrecision() const { return mXPrecision; }
-
- inline float getYPrecision() const { return mYPrecision; }
-
- inline nsecs_t getDownTime() const { return mDownTime; }
-
- inline void setDownTime(nsecs_t downTime) { mDownTime = downTime; }
-
- inline size_t getPointerCount() const { return mPointerProperties.size(); }
-
- inline const PointerProperties* getPointerProperties(size_t pointerIndex) const {
- return &mPointerProperties[pointerIndex];
- }
-
- inline int32_t getPointerId(size_t pointerIndex) const {
- return mPointerProperties[pointerIndex].id;
- }
-
- inline int32_t getToolType(size_t pointerIndex) const {
- return mPointerProperties[pointerIndex].toolType;
- }
-
- inline nsecs_t getEventTime() const { return mSampleEventTimes[getHistorySize()]; }
-
- const PointerCoords* getRawPointerCoords(size_t pointerIndex) const;
-
- float getRawAxisValue(int32_t axis, size_t pointerIndex) const;
-
- inline float getRawX(size_t pointerIndex) const {
- return getRawAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
- }
-
- inline float getRawY(size_t pointerIndex) const {
- return getRawAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
- }
-
- float getAxisValue(int32_t axis, size_t pointerIndex) const;
-
- inline float getX(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
- }
-
- inline float getY(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
- }
-
- inline float getPressure(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerIndex);
- }
-
- inline float getSize(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_SIZE, pointerIndex);
- }
-
- inline float getTouchMajor(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex);
- }
-
- inline float getTouchMinor(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex);
- }
-
- inline float getToolMajor(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex);
- }
-
- inline float getToolMinor(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex);
- }
-
- inline float getOrientation(size_t pointerIndex) const {
- return getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex);
- }
-
- inline size_t getHistorySize() const { return mSampleEventTimes.size() - 1; }
-
- inline nsecs_t getHistoricalEventTime(size_t historicalIndex) const {
- return mSampleEventTimes[historicalIndex];
- }
-
- const PointerCoords* getHistoricalRawPointerCoords(
- size_t pointerIndex, size_t historicalIndex) const;
-
- float getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
- size_t historicalIndex) const;
-
- inline float getHistoricalRawX(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalRawAxisValue(
- AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalRawY(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalRawAxisValue(
- AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
- }
-
- float getHistoricalAxisValue(int32_t axis, size_t pointerIndex, size_t historicalIndex) const;
-
- inline float getHistoricalX(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalY(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalPressure(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_PRESSURE, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalSize(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_SIZE, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalTouchMajor(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalTouchMinor(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalToolMajor(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalToolMinor(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex, historicalIndex);
- }
-
- inline float getHistoricalOrientation(size_t pointerIndex, size_t historicalIndex) const {
- return getHistoricalAxisValue(
- AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex, historicalIndex);
- }
-
- ssize_t findPointerIndex(int32_t pointerId) const;
-
- void initialize(
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t edgeFlags,
- int32_t metaState,
- int32_t buttonState,
- float xOffset,
- float yOffset,
- float xPrecision,
- float yPrecision,
- nsecs_t downTime,
- nsecs_t eventTime,
- size_t pointerCount,
- const PointerProperties* pointerProperties,
- const PointerCoords* pointerCoords);
-
- void copyFrom(const MotionEvent* other, bool keepHistory);
-
- void addSample(
- nsecs_t eventTime,
- const PointerCoords* pointerCoords);
-
- void offsetLocation(float xOffset, float yOffset);
-
- void scale(float scaleFactor);
-
-#ifdef HAVE_ANDROID_OS
- void transform(const SkMatrix* matrix);
-
- status_t readFromParcel(Parcel* parcel);
- status_t writeToParcel(Parcel* parcel) const;
-#endif
-
- static bool isTouchEvent(int32_t source, int32_t action);
- inline bool isTouchEvent() const {
- return isTouchEvent(mSource, mAction);
- }
-
- // Low-level accessors.
- inline const PointerProperties* getPointerProperties() const {
- return mPointerProperties.array();
- }
- inline const nsecs_t* getSampleEventTimes() const { return mSampleEventTimes.array(); }
- inline const PointerCoords* getSamplePointerCoords() const {
- return mSamplePointerCoords.array();
- }
-
-protected:
- int32_t mAction;
- int32_t mFlags;
- int32_t mEdgeFlags;
- int32_t mMetaState;
- int32_t mButtonState;
- float mXOffset;
- float mYOffset;
- float mXPrecision;
- float mYPrecision;
- nsecs_t mDownTime;
- Vector<PointerProperties> mPointerProperties;
- Vector<nsecs_t> mSampleEventTimes;
- Vector<PointerCoords> mSamplePointerCoords;
-};
-
-/*
- * Input event factory.
- */
-class InputEventFactoryInterface {
-protected:
- virtual ~InputEventFactoryInterface() { }
-
-public:
- InputEventFactoryInterface() { }
-
- virtual KeyEvent* createKeyEvent() = 0;
- virtual MotionEvent* createMotionEvent() = 0;
-};
-
-/*
- * A simple input event factory implementation that uses a single preallocated instance
- * of each type of input event that are reused for each request.
- */
-class PreallocatedInputEventFactory : public InputEventFactoryInterface {
-public:
- PreallocatedInputEventFactory() { }
- virtual ~PreallocatedInputEventFactory() { }
-
- virtual KeyEvent* createKeyEvent() { return & mKeyEvent; }
- virtual MotionEvent* createMotionEvent() { return & mMotionEvent; }
-
-private:
- KeyEvent mKeyEvent;
- MotionEvent mMotionEvent;
-};
-
-/*
- * An input event factory implementation that maintains a pool of input events.
- */
-class PooledInputEventFactory : public InputEventFactoryInterface {
-public:
- PooledInputEventFactory(size_t maxPoolSize = 20);
- virtual ~PooledInputEventFactory();
-
- virtual KeyEvent* createKeyEvent();
- virtual MotionEvent* createMotionEvent();
-
- void recycle(InputEvent* event);
-
-private:
- const size_t mMaxPoolSize;
-
- Vector<KeyEvent*> mKeyEventPool;
- Vector<MotionEvent*> mMotionEventPool;
-};
-
-} // namespace android
-
-#endif // _ANDROIDFW_INPUT_H
diff --git a/widget/gonk/libui/InputApplication.cpp b/widget/gonk/libui/InputApplication.cpp
deleted file mode 100644
index ce432356b..000000000
--- a/widget/gonk/libui/InputApplication.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "InputApplication"
-
-#include "InputApplication.h"
-
-#include "cutils_log.h"
-
-namespace android {
-
-// --- InputApplicationHandle ---
-
-InputApplicationHandle::InputApplicationHandle() :
- mInfo(NULL) {
-}
-
-InputApplicationHandle::~InputApplicationHandle() {
- delete mInfo;
-}
-
-void InputApplicationHandle::releaseInfo() {
- if (mInfo) {
- delete mInfo;
- mInfo = NULL;
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/InputApplication.h b/widget/gonk/libui/InputApplication.h
deleted file mode 100644
index ba789559c..000000000
--- a/widget/gonk/libui/InputApplication.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_INPUT_APPLICATION_H
-#define _UI_INPUT_APPLICATION_H
-
-#include "Input.h"
-
-#include <utils/RefBase.h>
-#include <utils/Timers.h>
-#include <utils/String8.h>
-
-namespace android {
-
-/*
- * Describes the properties of an application that can receive input.
- */
-struct InputApplicationInfo {
- String8 name;
- nsecs_t dispatchingTimeout;
-};
-
-
-/*
- * Handle for an application that can receive input.
- *
- * Used by the native input dispatcher as a handle for the window manager objects
- * that describe an application.
- */
-class InputApplicationHandle : public RefBase {
-public:
- inline const InputApplicationInfo* getInfo() const {
- return mInfo;
- }
-
- inline String8 getName() const {
- return mInfo ? mInfo->name : String8("<invalid>");
- }
-
- inline nsecs_t getDispatchingTimeout(nsecs_t defaultValue) const {
- return mInfo ? mInfo->dispatchingTimeout : defaultValue;
- }
-
- /**
- * Requests that the state of this object be updated to reflect
- * the most current available information about the application.
- *
- * This method should only be called from within the input dispatcher's
- * critical section.
- *
- * Returns true on success, or false if the handle is no longer valid.
- */
- virtual bool updateInfo() = 0;
-
- /**
- * Releases the storage used by the associated information when it is
- * no longer needed.
- */
- void releaseInfo();
-
-protected:
- InputApplicationHandle();
- virtual ~InputApplicationHandle();
-
- InputApplicationInfo* mInfo;
-};
-
-} // namespace android
-
-#endif // _UI_INPUT_APPLICATION_H
diff --git a/widget/gonk/libui/InputDevice.cpp b/widget/gonk/libui/InputDevice.cpp
deleted file mode 100644
index 01a437dd4..000000000
--- a/widget/gonk/libui/InputDevice.cpp
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "InputDevice"
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <ctype.h>
-
-#include "InputDevice.h"
-
-namespace android {
-
-static const char* CONFIGURATION_FILE_DIR[] = {
- "idc/",
- "keylayout/",
- "keychars/",
-};
-
-static const char* CONFIGURATION_FILE_EXTENSION[] = {
- ".idc",
- ".kl",
- ".kcm",
-};
-
-static bool isValidNameChar(char ch) {
- return isascii(ch) && (isdigit(ch) || isalpha(ch) || ch == '-' || ch == '_');
-}
-
-static void appendInputDeviceConfigurationFileRelativePath(String8& path,
- const String8& name, InputDeviceConfigurationFileType type) {
- path.append(CONFIGURATION_FILE_DIR[type]);
- for (size_t i = 0; i < name.length(); i++) {
- char ch = name[i];
- if (!isValidNameChar(ch)) {
- ch = '_';
- }
- path.append(&ch, 1);
- }
- path.append(CONFIGURATION_FILE_EXTENSION[type]);
-}
-
-String8 getInputDeviceConfigurationFilePathByDeviceIdentifier(
- const InputDeviceIdentifier& deviceIdentifier,
- InputDeviceConfigurationFileType type) {
- if (deviceIdentifier.vendor !=0 && deviceIdentifier.product != 0) {
- if (deviceIdentifier.version != 0) {
- // Try vendor product version.
- String8 versionPath(getInputDeviceConfigurationFilePathByName(
- String8::format("Vendor_%04x_Product_%04x_Version_%04x",
- deviceIdentifier.vendor, deviceIdentifier.product,
- deviceIdentifier.version),
- type));
- if (!versionPath.isEmpty()) {
- return versionPath;
- }
- }
-
- // Try vendor product.
- String8 productPath(getInputDeviceConfigurationFilePathByName(
- String8::format("Vendor_%04x_Product_%04x",
- deviceIdentifier.vendor, deviceIdentifier.product),
- type));
- if (!productPath.isEmpty()) {
- return productPath;
- }
- }
-
- // Try device name.
- return getInputDeviceConfigurationFilePathByName(deviceIdentifier.name, type);
-}
-
-String8 getInputDeviceConfigurationFilePathByName(
- const String8& name, InputDeviceConfigurationFileType type) {
- // Search system repository.
- String8 path;
- path.setTo(getenv("ANDROID_ROOT"));
- path.append("/usr/");
- appendInputDeviceConfigurationFileRelativePath(path, name, type);
-#if DEBUG_PROBE
- ALOGD("Probing for system provided input device configuration file: path='%s'", path.string());
-#endif
- if (!access(path.string(), R_OK)) {
-#if DEBUG_PROBE
- ALOGD("Found");
-#endif
- return path;
- }
-
- // Search user repository.
- // TODO Should only look here if not in safe mode.
- path.setTo(getenv("ANDROID_DATA"));
- path.append("/system/devices/");
- appendInputDeviceConfigurationFileRelativePath(path, name, type);
-#if DEBUG_PROBE
- ALOGD("Probing for system user input device configuration file: path='%s'", path.string());
-#endif
- if (!access(path.string(), R_OK)) {
-#if DEBUG_PROBE
- ALOGD("Found");
-#endif
- return path;
- }
-
- // Not found.
-#if DEBUG_PROBE
- ALOGD("Probe failed to find input device configuration file: name='%s', type=%d",
- name.string(), type);
-#endif
- return String8();
-}
-
-
-// --- InputDeviceInfo ---
-
-InputDeviceInfo::InputDeviceInfo() {
- initialize(-1, -1, InputDeviceIdentifier(), String8(), false);
-}
-
-InputDeviceInfo::InputDeviceInfo(const InputDeviceInfo& other) :
- mId(other.mId), mGeneration(other.mGeneration), mIdentifier(other.mIdentifier),
- mAlias(other.mAlias), mIsExternal(other.mIsExternal), mSources(other.mSources),
- mKeyboardType(other.mKeyboardType),
- mKeyCharacterMap(other.mKeyCharacterMap),
- mHasVibrator(other.mHasVibrator),
- mMotionRanges(other.mMotionRanges) {
-}
-
-InputDeviceInfo::~InputDeviceInfo() {
-}
-
-void InputDeviceInfo::initialize(int32_t id, int32_t generation,
- const InputDeviceIdentifier& identifier, const String8& alias, bool isExternal) {
- mId = id;
- mGeneration = generation;
- mIdentifier = identifier;
- mAlias = alias;
- mIsExternal = isExternal;
- mSources = 0;
- mKeyboardType = AINPUT_KEYBOARD_TYPE_NONE;
- mHasVibrator = false;
- mMotionRanges.clear();
-}
-
-const InputDeviceInfo::MotionRange* InputDeviceInfo::getMotionRange(
- int32_t axis, uint32_t source) const {
- size_t numRanges = mMotionRanges.size();
- for (size_t i = 0; i < numRanges; i++) {
- const MotionRange& range = mMotionRanges.itemAt(i);
- if (range.axis == axis && range.source == source) {
- return &range;
- }
- }
- return NULL;
-}
-
-void InputDeviceInfo::addSource(uint32_t source) {
- mSources |= source;
-}
-
-void InputDeviceInfo::addMotionRange(int32_t axis, uint32_t source, float min, float max,
- float flat, float fuzz, float resolution) {
- MotionRange range = { axis, source, min, max, flat, fuzz, resolution };
- mMotionRanges.add(range);
-}
-
-void InputDeviceInfo::addMotionRange(const MotionRange& range) {
- mMotionRanges.add(range);
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/InputDevice.h b/widget/gonk/libui/InputDevice.h
deleted file mode 100644
index 0ab5863c9..000000000
--- a/widget/gonk/libui/InputDevice.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_INPUT_DEVICE_H
-#define _ANDROIDFW_INPUT_DEVICE_H
-
-#include "Input.h"
-#include "KeyCharacterMap.h"
-
-namespace android {
-
-/*
- * Identifies a device.
- */
-struct InputDeviceIdentifier {
- inline InputDeviceIdentifier() :
- bus(0), vendor(0), product(0), version(0) {
- }
-
- // Information provided by the kernel.
- String8 name;
- String8 location;
- String8 uniqueId;
- uint16_t bus;
- uint16_t vendor;
- uint16_t product;
- uint16_t version;
-
- // A composite input device descriptor string that uniquely identifies the device
- // even across reboots or reconnections. The value of this field is used by
- // upper layers of the input system to associate settings with individual devices.
- // It is hashed from whatever kernel provided information is available.
- // Ideally, the way this value is computed should not change between Android releases
- // because that would invalidate persistent settings that rely on it.
- String8 descriptor;
-};
-
-/*
- * Describes the characteristics and capabilities of an input device.
- */
-class InputDeviceInfo {
-public:
- InputDeviceInfo();
- InputDeviceInfo(const InputDeviceInfo& other);
- ~InputDeviceInfo();
-
- struct MotionRange {
- int32_t axis;
- uint32_t source;
- float min;
- float max;
- float flat;
- float fuzz;
- float resolution;
- };
-
- void initialize(int32_t id, int32_t generation, const InputDeviceIdentifier& identifier,
- const String8& alias, bool isExternal);
-
- inline int32_t getId() const { return mId; }
- inline int32_t getGeneration() const { return mGeneration; }
- inline const InputDeviceIdentifier& getIdentifier() const { return mIdentifier; }
- inline const String8& getAlias() const { return mAlias; }
- inline const String8& getDisplayName() const {
- return mAlias.isEmpty() ? mIdentifier.name : mAlias;
- }
- inline bool isExternal() const { return mIsExternal; }
- inline uint32_t getSources() const { return mSources; }
-
- const MotionRange* getMotionRange(int32_t axis, uint32_t source) const;
-
- void addSource(uint32_t source);
- void addMotionRange(int32_t axis, uint32_t source,
- float min, float max, float flat, float fuzz, float resolution);
- void addMotionRange(const MotionRange& range);
-
- inline void setKeyboardType(int32_t keyboardType) { mKeyboardType = keyboardType; }
- inline int32_t getKeyboardType() const { return mKeyboardType; }
-
- inline void setKeyCharacterMap(const sp<KeyCharacterMap>& value) {
- mKeyCharacterMap = value;
- }
-
- inline sp<KeyCharacterMap> getKeyCharacterMap() const {
- return mKeyCharacterMap;
- }
-
- inline void setVibrator(bool hasVibrator) { mHasVibrator = hasVibrator; }
- inline bool hasVibrator() const { return mHasVibrator; }
-
- inline const Vector<MotionRange>& getMotionRanges() const {
- return mMotionRanges;
- }
-
-private:
- int32_t mId;
- int32_t mGeneration;
- InputDeviceIdentifier mIdentifier;
- String8 mAlias;
- bool mIsExternal;
- uint32_t mSources;
- int32_t mKeyboardType;
- sp<KeyCharacterMap> mKeyCharacterMap;
- bool mHasVibrator;
-
- Vector<MotionRange> mMotionRanges;
-};
-
-/* Types of input device configuration files. */
-enum InputDeviceConfigurationFileType {
- INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION = 0, /* .idc file */
- INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_LAYOUT = 1, /* .kl file */
- INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_CHARACTER_MAP = 2, /* .kcm file */
-};
-
-/*
- * Gets the path of an input device configuration file, if one is available.
- * Considers both system provided and user installed configuration files.
- *
- * The device identifier is used to construct several default configuration file
- * names to try based on the device name, vendor, product, and version.
- *
- * Returns an empty string if not found.
- */
-extern String8 getInputDeviceConfigurationFilePathByDeviceIdentifier(
- const InputDeviceIdentifier& deviceIdentifier,
- InputDeviceConfigurationFileType type);
-
-/*
- * Gets the path of an input device configuration file, if one is available.
- * Considers both system provided and user installed configuration files.
- *
- * The name is case-sensitive and is used to construct the filename to resolve.
- * All characters except 'a'-'z', 'A'-'Z', '0'-'9', '-', and '_' are replaced by underscores.
- *
- * Returns an empty string if not found.
- */
-extern String8 getInputDeviceConfigurationFilePathByName(
- const String8& name, InputDeviceConfigurationFileType type);
-
-} // namespace android
-
-#endif // _ANDROIDFW_INPUT_DEVICE_H
diff --git a/widget/gonk/libui/InputDispatcher.cpp b/widget/gonk/libui/InputDispatcher.cpp
deleted file mode 100644
index 7adaa1998..000000000
--- a/widget/gonk/libui/InputDispatcher.cpp
+++ /dev/null
@@ -1,4430 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "InputDispatcher"
-#define ATRACE_TAG ATRACE_TAG_INPUT
-
-//#define LOG_NDEBUG 0
-#include "cutils_log.h"
-
-// Log detailed debug messages about each inbound event notification to the dispatcher.
-#define DEBUG_INBOUND_EVENT_DETAILS 0
-
-// Log detailed debug messages about each outbound event processed by the dispatcher.
-#define DEBUG_OUTBOUND_EVENT_DETAILS 0
-
-// Log debug messages about the dispatch cycle.
-#define DEBUG_DISPATCH_CYCLE 0
-
-// Log debug messages about registrations.
-#define DEBUG_REGISTRATION 0
-
-// Log debug messages about input event injection.
-#define DEBUG_INJECTION 0
-
-// Log debug messages about input focus tracking.
-#define DEBUG_FOCUS 0
-
-// Log debug messages about the app switch latency optimization.
-#define DEBUG_APP_SWITCH 0
-
-// Log debug messages about hover events.
-#define DEBUG_HOVER 0
-
-#include "InputDispatcher.h"
-
-#include "Trace.h"
-#include "PowerManager.h"
-
-#include <stddef.h>
-#include <unistd.h>
-#include <errno.h>
-#include <limits.h>
-#include <time.h>
-
-#define INDENT " "
-#define INDENT2 " "
-#define INDENT3 " "
-#define INDENT4 " "
-
-namespace android {
-
-// Default input dispatching timeout if there is no focused application or paused window
-// from which to determine an appropriate dispatching timeout.
-const nsecs_t DEFAULT_INPUT_DISPATCHING_TIMEOUT = 5000 * 1000000LL; // 5 sec
-
-// Amount of time to allow for all pending events to be processed when an app switch
-// key is on the way. This is used to preempt input dispatch and drop input events
-// when an application takes too long to respond and the user has pressed an app switch key.
-const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
-
-// Amount of time to allow for an event to be dispatched (measured since its eventTime)
-// before considering it stale and dropping it.
-const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
-
-// Amount of time to allow touch events to be streamed out to a connection before requiring
-// that the first event be finished. This value extends the ANR timeout by the specified
-// amount. For example, if streaming is allowed to get ahead by one second relative to the
-// queue of waiting unfinished events, then ANRs will similarly be delayed by one second.
-const nsecs_t STREAM_AHEAD_EVENT_TIMEOUT = 500 * 1000000LL; // 0.5sec
-
-// Log a warning when an event takes longer than this to process, even if an ANR does not occur.
-const nsecs_t SLOW_EVENT_PROCESSING_WARNING_TIMEOUT = 2000 * 1000000LL; // 2sec
-
-
-static inline nsecs_t now() {
- return systemTime(SYSTEM_TIME_MONOTONIC);
-}
-
-static inline const char* toString(bool value) {
- return value ? "true" : "false";
-}
-
-static inline int32_t getMotionEventActionPointerIndex(int32_t action) {
- return (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
- >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
-}
-
-static bool isValidKeyAction(int32_t action) {
- switch (action) {
- case AKEY_EVENT_ACTION_DOWN:
- case AKEY_EVENT_ACTION_UP:
- return true;
- default:
- return false;
- }
-}
-
-static bool validateKeyEvent(int32_t action) {
- if (! isValidKeyAction(action)) {
- ALOGE("Key event has invalid action code 0x%x", action);
- return false;
- }
- return true;
-}
-
-static bool isValidMotionAction(int32_t action, size_t pointerCount) {
- switch (action & AMOTION_EVENT_ACTION_MASK) {
- case AMOTION_EVENT_ACTION_DOWN:
- case AMOTION_EVENT_ACTION_UP:
- case AMOTION_EVENT_ACTION_CANCEL:
- case AMOTION_EVENT_ACTION_MOVE:
- case AMOTION_EVENT_ACTION_OUTSIDE:
- case AMOTION_EVENT_ACTION_HOVER_ENTER:
- case AMOTION_EVENT_ACTION_HOVER_MOVE:
- case AMOTION_EVENT_ACTION_HOVER_EXIT:
- case AMOTION_EVENT_ACTION_SCROLL:
- return true;
- case AMOTION_EVENT_ACTION_POINTER_DOWN:
- case AMOTION_EVENT_ACTION_POINTER_UP: {
- int32_t index = getMotionEventActionPointerIndex(action);
- return index >= 0 && size_t(index) < pointerCount;
- }
- default:
- return false;
- }
-}
-
-static bool validateMotionEvent(int32_t action, size_t pointerCount,
- const PointerProperties* pointerProperties) {
- if (! isValidMotionAction(action, pointerCount)) {
- ALOGE("Motion event has invalid action code 0x%x", action);
- return false;
- }
- if (pointerCount < 1 || pointerCount > MAX_POINTERS) {
- ALOGE("Motion event has invalid pointer count %d; value must be between 1 and %d.",
- pointerCount, MAX_POINTERS);
- return false;
- }
- BitSet32 pointerIdBits;
- for (size_t i = 0; i < pointerCount; i++) {
- int32_t id = pointerProperties[i].id;
- if (id < 0 || id > MAX_POINTER_ID) {
- ALOGE("Motion event has invalid pointer id %d; value must be between 0 and %d",
- id, MAX_POINTER_ID);
- return false;
- }
- if (pointerIdBits.hasBit(id)) {
- ALOGE("Motion event has duplicate pointer id %d", id);
- return false;
- }
- pointerIdBits.markBit(id);
- }
- return true;
-}
-
-static bool isMainDisplay(int32_t displayId) {
- return displayId == ADISPLAY_ID_DEFAULT || displayId == ADISPLAY_ID_NONE;
-}
-
-static void dumpRegion(String8& dump, const SkRegion& region) {
- if (region.isEmpty()) {
- dump.append("<empty>");
- return;
- }
-
- bool first = true;
- for (SkRegion::Iterator it(region); !it.done(); it.next()) {
- if (first) {
- first = false;
- } else {
- dump.append("|");
- }
- const SkIRect& rect = it.rect();
- dump.appendFormat("[%d,%d][%d,%d]", rect.fLeft, rect.fTop, rect.fRight, rect.fBottom);
- }
-}
-
-
-// --- InputDispatcher ---
-
-InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
- mPolicy(policy),
- mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
- mNextUnblockedEvent(NULL),
- mDispatchEnabled(false), mDispatchFrozen(false), mInputFilterEnabled(false),
- mInputTargetWaitCause(INPUT_TARGET_WAIT_CAUSE_NONE) {
- mLooper = new Looper(false);
-
- mKeyRepeatState.lastKeyEntry = NULL;
-
- policy->getDispatcherConfiguration(&mConfig);
-}
-
-InputDispatcher::~InputDispatcher() {
- { // acquire lock
- AutoMutex _l(mLock);
-
- resetKeyRepeatLocked();
- releasePendingEventLocked();
- drainInboundQueueLocked();
- }
-
- while (mConnectionsByFd.size() != 0) {
- unregisterInputChannel(mConnectionsByFd.valueAt(0)->inputChannel);
- }
-}
-
-void InputDispatcher::dispatchOnce() {
- nsecs_t nextWakeupTime = LONG_LONG_MAX;
- { // acquire lock
- AutoMutex _l(mLock);
- mDispatcherIsAliveCondition.broadcast();
-
- // Run a dispatch loop if there are no pending commands.
- // The dispatch loop might enqueue commands to run afterwards.
- if (!haveCommandsLocked()) {
- dispatchOnceInnerLocked(&nextWakeupTime);
- }
-
- // Run all pending commands if there are any.
- // If any commands were run then force the next poll to wake up immediately.
- if (runCommandsLockedInterruptible()) {
- nextWakeupTime = LONG_LONG_MIN;
- }
- } // release lock
-
- // Wait for callback or timeout or wake. (make sure we round up, not down)
- nsecs_t currentTime = now();
- int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
- mLooper->pollOnce(timeoutMillis);
-}
-
-void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {
- nsecs_t currentTime = now();
-
- // Reset the key repeat timer whenever we disallow key events, even if the next event
- // is not a key. This is to ensure that we abort a key repeat if the device is just coming
- // out of sleep.
- if (!mPolicy->isKeyRepeatEnabled()) {
- resetKeyRepeatLocked();
- }
-
- // If dispatching is frozen, do not process timeouts or try to deliver any new events.
- if (mDispatchFrozen) {
-#if DEBUG_FOCUS
- ALOGD("Dispatch frozen. Waiting some more.");
-#endif
- return;
- }
-
- // Optimize latency of app switches.
- // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has
- // been pressed. When it expires, we preempt dispatch and drop all other pending events.
- bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;
- if (mAppSwitchDueTime < *nextWakeupTime) {
- *nextWakeupTime = mAppSwitchDueTime;
- }
-
- // Ready to start a new event.
- // If we don't already have a pending event, go grab one.
- if (! mPendingEvent) {
- if (mInboundQueue.isEmpty()) {
- if (isAppSwitchDue) {
- // The inbound queue is empty so the app switch key we were waiting
- // for will never arrive. Stop waiting for it.
- resetPendingAppSwitchLocked(false);
- isAppSwitchDue = false;
- }
-
- // Synthesize a key repeat if appropriate.
- if (mKeyRepeatState.lastKeyEntry) {
- if (currentTime >= mKeyRepeatState.nextRepeatTime) {
- mPendingEvent = synthesizeKeyRepeatLocked(currentTime);
- } else {
- if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {
- *nextWakeupTime = mKeyRepeatState.nextRepeatTime;
- }
- }
- }
-
- // Nothing to do if there is no pending event.
- if (!mPendingEvent) {
- return;
- }
- } else {
- // Inbound queue has at least one entry.
- mPendingEvent = mInboundQueue.dequeueAtHead();
- traceInboundQueueLengthLocked();
- }
-
- // Poke user activity for this event.
- if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {
- pokeUserActivityLocked(mPendingEvent);
- }
-
- // Get ready to dispatch the event.
- resetANRTimeoutsLocked();
- }
-
- // Now we have an event to dispatch.
- // All events are eventually dequeued and processed this way, even if we intend to drop them.
- ALOG_ASSERT(mPendingEvent != NULL);
- bool done = false;
- DropReason dropReason = DROP_REASON_NOT_DROPPED;
- if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {
- dropReason = DROP_REASON_POLICY;
- } else if (!mDispatchEnabled) {
- dropReason = DROP_REASON_DISABLED;
- }
-
- if (mNextUnblockedEvent == mPendingEvent) {
- mNextUnblockedEvent = NULL;
- }
-
- switch (mPendingEvent->type) {
- case EventEntry::TYPE_CONFIGURATION_CHANGED: {
- ConfigurationChangedEntry* typedEntry =
- static_cast<ConfigurationChangedEntry*>(mPendingEvent);
- done = dispatchConfigurationChangedLocked(currentTime, typedEntry);
- dropReason = DROP_REASON_NOT_DROPPED; // configuration changes are never dropped
- break;
- }
-
- case EventEntry::TYPE_DEVICE_RESET: {
- DeviceResetEntry* typedEntry =
- static_cast<DeviceResetEntry*>(mPendingEvent);
- done = dispatchDeviceResetLocked(currentTime, typedEntry);
- dropReason = DROP_REASON_NOT_DROPPED; // device resets are never dropped
- break;
- }
-
- case EventEntry::TYPE_KEY: {
- KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);
- if (isAppSwitchDue) {
- if (isAppSwitchKeyEventLocked(typedEntry)) {
- resetPendingAppSwitchLocked(true);
- isAppSwitchDue = false;
- } else if (dropReason == DROP_REASON_NOT_DROPPED) {
- dropReason = DROP_REASON_APP_SWITCH;
- }
- }
- if (dropReason == DROP_REASON_NOT_DROPPED
- && isStaleEventLocked(currentTime, typedEntry)) {
- dropReason = DROP_REASON_STALE;
- }
- if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
- dropReason = DROP_REASON_BLOCKED;
- }
- done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);
- break;
- }
-
- case EventEntry::TYPE_MOTION: {
- MotionEntry* typedEntry = static_cast<MotionEntry*>(mPendingEvent);
- if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
- dropReason = DROP_REASON_APP_SWITCH;
- }
- if (dropReason == DROP_REASON_NOT_DROPPED
- && isStaleEventLocked(currentTime, typedEntry)) {
- dropReason = DROP_REASON_STALE;
- }
- if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
- dropReason = DROP_REASON_BLOCKED;
- }
- done = dispatchMotionLocked(currentTime, typedEntry,
- &dropReason, nextWakeupTime);
- break;
- }
-
- default:
- ALOG_ASSERT(false);
- break;
- }
-
- if (done) {
- if (dropReason != DROP_REASON_NOT_DROPPED) {
- dropInboundEventLocked(mPendingEvent, dropReason);
- }
-
- releasePendingEventLocked();
- *nextWakeupTime = LONG_LONG_MIN; // force next poll to wake up immediately
- }
-}
-
-bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {
- bool needWake = mInboundQueue.isEmpty();
- mInboundQueue.enqueueAtTail(entry);
- traceInboundQueueLengthLocked();
-
- switch (entry->type) {
- case EventEntry::TYPE_KEY: {
- // Optimize app switch latency.
- // If the application takes too long to catch up then we drop all events preceding
- // the app switch key.
- KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
- if (isAppSwitchKeyEventLocked(keyEntry)) {
- if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
- mAppSwitchSawKeyDown = true;
- } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
- if (mAppSwitchSawKeyDown) {
-#if DEBUG_APP_SWITCH
- ALOGD("App switch is pending!");
-#endif
- mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;
- mAppSwitchSawKeyDown = false;
- needWake = true;
- }
- }
- }
- break;
- }
-
- case EventEntry::TYPE_MOTION: {
- // Optimize case where the current application is unresponsive and the user
- // decides to touch a window in a different application.
- // If the application takes too long to catch up then we drop all events preceding
- // the touch into the other window.
- MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
- if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
- && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
- && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
- && mInputTargetWaitApplicationHandle != NULL) {
- int32_t displayId = motionEntry->displayId;
- int32_t x = int32_t(motionEntry->pointerCoords[0].
- getAxisValue(AMOTION_EVENT_AXIS_X));
- int32_t y = int32_t(motionEntry->pointerCoords[0].
- getAxisValue(AMOTION_EVENT_AXIS_Y));
- sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);
- if (touchedWindowHandle != NULL
- && touchedWindowHandle->inputApplicationHandle
- != mInputTargetWaitApplicationHandle) {
- // User touched a different application than the one we are waiting on.
- // Flag the event, and start pruning the input queue.
- mNextUnblockedEvent = motionEntry;
- needWake = true;
- }
- }
- break;
- }
- }
-
- return needWake;
-}
-
-sp<InputWindowHandle> InputDispatcher::findTouchedWindowAtLocked(int32_t displayId,
- int32_t x, int32_t y) {
- // Traverse windows from front to back to find touched window.
- size_t numWindows = mWindowHandles.size();
- for (size_t i = 0; i < numWindows; i++) {
- sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
- const InputWindowInfo* windowInfo = windowHandle->getInfo();
- if (windowInfo->displayId == displayId) {
- int32_t flags = windowInfo->layoutParamsFlags;
-
- if (windowInfo->visible) {
- if (!(flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
- bool isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
- | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
- if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
- // Found window.
- return windowHandle;
- }
- }
- }
-
- if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
- // Error window is on top but not visible, so touch is dropped.
- return NULL;
- }
- }
- }
- return NULL;
-}
-
-void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
- const char* reason;
- switch (dropReason) {
- case DROP_REASON_POLICY:
-#if DEBUG_INBOUND_EVENT_DETAILS
- ALOGD("Dropped event because policy consumed it.");
-#endif
- reason = "inbound event was dropped because the policy consumed it";
- break;
- case DROP_REASON_DISABLED:
- ALOGI("Dropped event because input dispatch is disabled.");
- reason = "inbound event was dropped because input dispatch is disabled";
- break;
- case DROP_REASON_APP_SWITCH:
- ALOGI("Dropped event because of pending overdue app switch.");
- reason = "inbound event was dropped because of pending overdue app switch";
- break;
- case DROP_REASON_BLOCKED:
- ALOGI("Dropped event because the current application is not responding and the user "
- "has started interacting with a different application.");
- reason = "inbound event was dropped because the current application is not responding "
- "and the user has started interacting with a different application";
- break;
- case DROP_REASON_STALE:
- ALOGI("Dropped event because it is stale.");
- reason = "inbound event was dropped because it is stale";
- break;
- default:
- ALOG_ASSERT(false);
- return;
- }
-
- switch (entry->type) {
- case EventEntry::TYPE_KEY: {
- CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
- synthesizeCancelationEventsForAllConnectionsLocked(options);
- break;
- }
- case EventEntry::TYPE_MOTION: {
- MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
- if (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER) {
- CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS, reason);
- synthesizeCancelationEventsForAllConnectionsLocked(options);
- } else {
- CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS, reason);
- synthesizeCancelationEventsForAllConnectionsLocked(options);
- }
- break;
- }
- }
-}
-
-bool InputDispatcher::isAppSwitchKeyCode(int32_t keyCode) {
- return keyCode == AKEYCODE_HOME
- || keyCode == AKEYCODE_ENDCALL
- || keyCode == AKEYCODE_APP_SWITCH;
-}
-
-bool InputDispatcher::isAppSwitchKeyEventLocked(KeyEntry* keyEntry) {
- return ! (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED)
- && isAppSwitchKeyCode(keyEntry->keyCode)
- && (keyEntry->policyFlags & POLICY_FLAG_TRUSTED)
- && (keyEntry->policyFlags & POLICY_FLAG_PASS_TO_USER);
-}
-
-bool InputDispatcher::isAppSwitchPendingLocked() {
- return mAppSwitchDueTime != LONG_LONG_MAX;
-}
-
-void InputDispatcher::resetPendingAppSwitchLocked(bool handled) {
- mAppSwitchDueTime = LONG_LONG_MAX;
-
-#if DEBUG_APP_SWITCH
- if (handled) {
- ALOGD("App switch has arrived.");
- } else {
- ALOGD("App switch was abandoned.");
- }
-#endif
-}
-
-bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
- return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
-}
-
-bool InputDispatcher::haveCommandsLocked() const {
- return !mCommandQueue.isEmpty();
-}
-
-bool InputDispatcher::runCommandsLockedInterruptible() {
- if (mCommandQueue.isEmpty()) {
- return false;
- }
-
- do {
- CommandEntry* commandEntry = mCommandQueue.dequeueAtHead();
-
- Command command = commandEntry->command;
- (this->*command)(commandEntry); // commands are implicitly 'LockedInterruptible'
-
- commandEntry->connection.clear();
- delete commandEntry;
- } while (! mCommandQueue.isEmpty());
- return true;
-}
-
-InputDispatcher::CommandEntry* InputDispatcher::postCommandLocked(Command command) {
- CommandEntry* commandEntry = new CommandEntry(command);
- mCommandQueue.enqueueAtTail(commandEntry);
- return commandEntry;
-}
-
-void InputDispatcher::drainInboundQueueLocked() {
- while (! mInboundQueue.isEmpty()) {
- EventEntry* entry = mInboundQueue.dequeueAtHead();
- releaseInboundEventLocked(entry);
- }
- traceInboundQueueLengthLocked();
-}
-
-void InputDispatcher::releasePendingEventLocked() {
- if (mPendingEvent) {
- resetANRTimeoutsLocked();
- releaseInboundEventLocked(mPendingEvent);
- mPendingEvent = NULL;
- }
-}
-
-void InputDispatcher::releaseInboundEventLocked(EventEntry* entry) {
- InjectionState* injectionState = entry->injectionState;
- if (injectionState && injectionState->injectionResult == INPUT_EVENT_INJECTION_PENDING) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("Injected inbound event was dropped.");
-#endif
- setInjectionResultLocked(entry, INPUT_EVENT_INJECTION_FAILED);
- }
- if (entry == mNextUnblockedEvent) {
- mNextUnblockedEvent = NULL;
- }
- entry->release();
-}
-
-void InputDispatcher::resetKeyRepeatLocked() {
- if (mKeyRepeatState.lastKeyEntry) {
- mKeyRepeatState.lastKeyEntry->release();
- mKeyRepeatState.lastKeyEntry = NULL;
- }
-}
-
-InputDispatcher::KeyEntry* InputDispatcher::synthesizeKeyRepeatLocked(nsecs_t currentTime) {
- KeyEntry* entry = mKeyRepeatState.lastKeyEntry;
-
- // Reuse the repeated key entry if it is otherwise unreferenced.
- uint32_t policyFlags = (entry->policyFlags & POLICY_FLAG_RAW_MASK)
- | POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_TRUSTED;
- if (entry->refCount == 1) {
- entry->recycle();
- entry->eventTime = currentTime;
- entry->policyFlags = policyFlags;
- entry->repeatCount += 1;
- } else {
- KeyEntry* newEntry = new KeyEntry(currentTime,
- entry->deviceId, entry->source, policyFlags,
- entry->action, entry->flags, entry->keyCode, entry->scanCode,
- entry->metaState, entry->repeatCount + 1, entry->downTime);
-
- mKeyRepeatState.lastKeyEntry = newEntry;
- entry->release();
-
- entry = newEntry;
- }
- entry->syntheticRepeat = true;
-
- // Increment reference count since we keep a reference to the event in
- // mKeyRepeatState.lastKeyEntry in addition to the one we return.
- entry->refCount += 1;
-
- mKeyRepeatState.nextRepeatTime = currentTime + mConfig.keyRepeatDelay;
- return entry;
-}
-
-bool InputDispatcher::dispatchConfigurationChangedLocked(
- nsecs_t currentTime, ConfigurationChangedEntry* entry) {
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("dispatchConfigurationChanged - eventTime=%lld", entry->eventTime);
-#endif
-
- // Reset key repeating in case a keyboard device was added or removed or something.
- resetKeyRepeatLocked();
-
- // Enqueue a command to run outside the lock to tell the policy that the configuration changed.
- CommandEntry* commandEntry = postCommandLocked(
- & InputDispatcher::doNotifyConfigurationChangedInterruptible);
- commandEntry->eventTime = entry->eventTime;
- return true;
-}
-
-bool InputDispatcher::dispatchDeviceResetLocked(
- nsecs_t currentTime, DeviceResetEntry* entry) {
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("dispatchDeviceReset - eventTime=%lld, deviceId=%d", entry->eventTime, entry->deviceId);
-#endif
-
- CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
- "device was reset");
- options.deviceId = entry->deviceId;
- synthesizeCancelationEventsForAllConnectionsLocked(options);
- return true;
-}
-
-bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,
- DropReason* dropReason, nsecs_t* nextWakeupTime) {
- // Preprocessing.
- if (! entry->dispatchInProgress) {
- if (entry->repeatCount == 0
- && entry->action == AKEY_EVENT_ACTION_DOWN
- && (entry->policyFlags & POLICY_FLAG_TRUSTED)
- && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {
- if (mKeyRepeatState.lastKeyEntry
- && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {
- // We have seen two identical key downs in a row which indicates that the device
- // driver is automatically generating key repeats itself. We take note of the
- // repeat here, but we disable our own next key repeat timer since it is clear that
- // we will not need to synthesize key repeats ourselves.
- entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;
- resetKeyRepeatLocked();
- mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves
- } else {
- // Not a repeat. Save key down state in case we do see a repeat later.
- resetKeyRepeatLocked();
- mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;
- }
- mKeyRepeatState.lastKeyEntry = entry;
- entry->refCount += 1;
- } else if (! entry->syntheticRepeat) {
- resetKeyRepeatLocked();
- }
-
- if (entry->repeatCount == 1) {
- entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;
- } else {
- entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;
- }
-
- entry->dispatchInProgress = true;
-
- logOutboundKeyDetailsLocked("dispatchKey - ", entry);
- }
-
- // Handle case where the policy asked us to try again later last time.
- if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {
- if (currentTime < entry->interceptKeyWakeupTime) {
- if (entry->interceptKeyWakeupTime < *nextWakeupTime) {
- *nextWakeupTime = entry->interceptKeyWakeupTime;
- }
- return false; // wait until next wakeup
- }
- entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
- entry->interceptKeyWakeupTime = 0;
- }
-
- // Give the policy a chance to intercept the key.
- if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {
- if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {
- CommandEntry* commandEntry = postCommandLocked(
- & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
- if (mFocusedWindowHandle != NULL) {
- commandEntry->inputWindowHandle = mFocusedWindowHandle;
- }
- commandEntry->keyEntry = entry;
- entry->refCount += 1;
- return false; // wait for the command to run
- } else {
- entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
- }
- } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {
- if (*dropReason == DROP_REASON_NOT_DROPPED) {
- *dropReason = DROP_REASON_POLICY;
- }
- }
-
- // Clean up if dropping the event.
- if (*dropReason != DROP_REASON_NOT_DROPPED) {
- setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
- ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
- return true;
- }
-
- // Identify targets.
- Vector<InputTarget> inputTargets;
- int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,
- entry, inputTargets, nextWakeupTime);
- if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
- return false;
- }
-
- setInjectionResultLocked(entry, injectionResult);
- if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
- return true;
- }
-
- addMonitoringTargetsLocked(inputTargets);
-
- // Dispatch the key.
- dispatchEventLocked(currentTime, entry, inputTargets);
- return true;
-}
-
-void InputDispatcher::logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry) {
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
- "action=0x%x, flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, "
- "repeatCount=%d, downTime=%lld",
- prefix,
- entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
- entry->action, entry->flags, entry->keyCode, entry->scanCode, entry->metaState,
- entry->repeatCount, entry->downTime);
-#endif
-}
-
-bool InputDispatcher::dispatchMotionLocked(
- nsecs_t currentTime, MotionEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) {
- // Preprocessing.
- if (! entry->dispatchInProgress) {
- entry->dispatchInProgress = true;
-
- logOutboundMotionDetailsLocked("dispatchMotion - ", entry);
- }
-
- // Clean up if dropping the event.
- if (*dropReason != DROP_REASON_NOT_DROPPED) {
- setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY
- ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);
- return true;
- }
-
- bool isPointerEvent = entry->source & AINPUT_SOURCE_CLASS_POINTER;
-
- // Identify targets.
- Vector<InputTarget> inputTargets;
-
- bool conflictingPointerActions = false;
- int32_t injectionResult;
- if (isPointerEvent) {
- // Pointer event. (eg. touchscreen)
- injectionResult = findTouchedWindowTargetsLocked(currentTime,
- entry, inputTargets, nextWakeupTime, &conflictingPointerActions);
- } else {
- // Non touch event. (eg. trackball)
- injectionResult = findFocusedWindowTargetsLocked(currentTime,
- entry, inputTargets, nextWakeupTime);
- }
- if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {
- return false;
- }
-
- setInjectionResultLocked(entry, injectionResult);
- if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {
- return true;
- }
-
- // TODO: support sending secondary display events to input monitors
- if (isMainDisplay(entry->displayId)) {
- addMonitoringTargetsLocked(inputTargets);
- }
-
- // Dispatch the motion.
- if (conflictingPointerActions) {
- CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
- "conflicting pointer actions");
- synthesizeCancelationEventsForAllConnectionsLocked(options);
- }
- dispatchEventLocked(currentTime, entry, inputTargets);
- return true;
-}
-
-
-void InputDispatcher::logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry) {
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("%seventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
- "action=0x%x, flags=0x%x, "
- "metaState=0x%x, buttonState=0x%x, "
- "edgeFlags=0x%x, xPrecision=%f, yPrecision=%f, downTime=%lld",
- prefix,
- entry->eventTime, entry->deviceId, entry->source, entry->policyFlags,
- entry->action, entry->flags,
- entry->metaState, entry->buttonState,
- entry->edgeFlags, entry->xPrecision, entry->yPrecision,
- entry->downTime);
-
- for (uint32_t i = 0; i < entry->pointerCount; i++) {
- ALOGD(" Pointer %d: id=%d, toolType=%d, "
- "x=%f, y=%f, pressure=%f, size=%f, "
- "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
- "orientation=%f",
- i, entry->pointerProperties[i].id,
- entry->pointerProperties[i].toolType,
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
- entry->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
- }
-#endif
-}
-
-void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,
- EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("dispatchEventToCurrentInputTargets");
-#endif
-
- ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true
-
- pokeUserActivityLocked(eventEntry);
-
- for (size_t i = 0; i < inputTargets.size(); i++) {
- const InputTarget& inputTarget = inputTargets.itemAt(i);
-
- ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);
- if (connectionIndex >= 0) {
- sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
- prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);
- } else {
-#if DEBUG_FOCUS
- ALOGD("Dropping event delivery to target with channel '%s' because it "
- "is no longer registered with the input dispatcher.",
- inputTarget.inputChannel->getName().string());
-#endif
- }
- }
-}
-
-int32_t InputDispatcher::handleTargetsNotReadyLocked(nsecs_t currentTime,
- const EventEntry* entry,
- const sp<InputApplicationHandle>& applicationHandle,
- const sp<InputWindowHandle>& windowHandle,
- nsecs_t* nextWakeupTime, const char* reason) {
- if (applicationHandle == NULL && windowHandle == NULL) {
- if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY) {
-#if DEBUG_FOCUS
- ALOGD("Waiting for system to become ready for input. Reason: %s", reason);
-#endif
- mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY;
- mInputTargetWaitStartTime = currentTime;
- mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
- mInputTargetWaitTimeoutExpired = false;
- mInputTargetWaitApplicationHandle.clear();
- }
- } else {
- if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
-#if DEBUG_FOCUS
- ALOGD("Waiting for application to become ready for input: %s. Reason: %s",
- getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
- reason);
-#endif
- nsecs_t timeout;
- if (windowHandle != NULL) {
- timeout = windowHandle->getDispatchingTimeout(DEFAULT_INPUT_DISPATCHING_TIMEOUT);
- } else if (applicationHandle != NULL) {
- timeout = applicationHandle->getDispatchingTimeout(
- DEFAULT_INPUT_DISPATCHING_TIMEOUT);
- } else {
- timeout = DEFAULT_INPUT_DISPATCHING_TIMEOUT;
- }
-
- mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY;
- mInputTargetWaitStartTime = currentTime;
- mInputTargetWaitTimeoutTime = currentTime + timeout;
- mInputTargetWaitTimeoutExpired = false;
- mInputTargetWaitApplicationHandle.clear();
-
- if (windowHandle != NULL) {
- mInputTargetWaitApplicationHandle = windowHandle->inputApplicationHandle;
- }
- if (mInputTargetWaitApplicationHandle == NULL && applicationHandle != NULL) {
- mInputTargetWaitApplicationHandle = applicationHandle;
- }
- }
- }
-
- if (mInputTargetWaitTimeoutExpired) {
- return INPUT_EVENT_INJECTION_TIMED_OUT;
- }
-
- if (currentTime >= mInputTargetWaitTimeoutTime) {
- onANRLocked(currentTime, applicationHandle, windowHandle,
- entry->eventTime, mInputTargetWaitStartTime, reason);
-
- // Force poll loop to wake up immediately on next iteration once we get the
- // ANR response back from the policy.
- *nextWakeupTime = LONG_LONG_MIN;
- return INPUT_EVENT_INJECTION_PENDING;
- } else {
- // Force poll loop to wake up when timeout is due.
- if (mInputTargetWaitTimeoutTime < *nextWakeupTime) {
- *nextWakeupTime = mInputTargetWaitTimeoutTime;
- }
- return INPUT_EVENT_INJECTION_PENDING;
- }
-}
-
-void InputDispatcher::resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
- const sp<InputChannel>& inputChannel) {
- if (newTimeout > 0) {
- // Extend the timeout.
- mInputTargetWaitTimeoutTime = now() + newTimeout;
- } else {
- // Give up.
- mInputTargetWaitTimeoutExpired = true;
-
- // Input state will not be realistic. Mark it out of sync.
- if (inputChannel.get()) {
- ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
- if (connectionIndex >= 0) {
- sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
- sp<InputWindowHandle> windowHandle = connection->inputWindowHandle;
-
- if (windowHandle != NULL) {
- mTouchState.removeWindow(windowHandle);
- }
-
- if (connection->status == Connection::STATUS_NORMAL) {
- CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS,
- "application not responding");
- synthesizeCancelationEventsForConnectionLocked(connection, options);
- }
- }
- }
- }
-}
-
-nsecs_t InputDispatcher::getTimeSpentWaitingForApplicationLocked(
- nsecs_t currentTime) {
- if (mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
- return currentTime - mInputTargetWaitStartTime;
- }
- return 0;
-}
-
-void InputDispatcher::resetANRTimeoutsLocked() {
-#if DEBUG_FOCUS
- ALOGD("Resetting ANR timeouts.");
-#endif
-
- // Reset input target wait timeout.
- mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
- mInputTargetWaitApplicationHandle.clear();
-}
-
-int32_t InputDispatcher::findFocusedWindowTargetsLocked(nsecs_t currentTime,
- const EventEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime) {
- int32_t injectionResult;
-
- // If there is no currently focused window and no focused application
- // then drop the event.
- if (mFocusedWindowHandle == NULL) {
- if (mFocusedApplicationHandle != NULL) {
- injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
- mFocusedApplicationHandle, NULL, nextWakeupTime,
- "Waiting because no window has focus but there is a "
- "focused application that may eventually add a window "
- "when it finishes starting up.");
- goto Unresponsive;
- }
-
- ALOGI("Dropping event because there is no focused window or focused application.");
- injectionResult = INPUT_EVENT_INJECTION_FAILED;
- goto Failed;
- }
-
- // Check permissions.
- if (! checkInjectionPermission(mFocusedWindowHandle, entry->injectionState)) {
- injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
- goto Failed;
- }
-
- // If the currently focused window is paused then keep waiting.
- if (mFocusedWindowHandle->getInfo()->paused) {
- injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
- mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
- "Waiting because the focused window is paused.");
- goto Unresponsive;
- }
-
- // If the currently focused window is still working on previous events then keep waiting.
- if (!isWindowReadyForMoreInputLocked(currentTime, mFocusedWindowHandle, entry)) {
- injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
- mFocusedApplicationHandle, mFocusedWindowHandle, nextWakeupTime,
- "Waiting because the focused window has not finished "
- "processing the input events that were previously delivered to it.");
- goto Unresponsive;
- }
-
- // Success! Output targets.
- injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
- addWindowTargetLocked(mFocusedWindowHandle,
- InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS, BitSet32(0),
- inputTargets);
-
- // Done.
-Failed:
-Unresponsive:
- nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
- updateDispatchStatisticsLocked(currentTime, entry,
- injectionResult, timeSpentWaitingForApplication);
-#if DEBUG_FOCUS
- ALOGD("findFocusedWindow finished: injectionResult=%d, "
- "timeSpentWaitingForApplication=%0.1fms",
- injectionResult, timeSpentWaitingForApplication / 1000000.0);
-#endif
- return injectionResult;
-}
-
-int32_t InputDispatcher::findTouchedWindowTargetsLocked(nsecs_t currentTime,
- const MotionEntry* entry, Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
- bool* outConflictingPointerActions) {
- enum InjectionPermission {
- INJECTION_PERMISSION_UNKNOWN,
- INJECTION_PERMISSION_GRANTED,
- INJECTION_PERMISSION_DENIED
- };
-
- // For security reasons, we defer updating the touch state until we are sure that
- // event injection will be allowed.
- //
- // FIXME In the original code, screenWasOff could never be set to true.
- // The reason is that the POLICY_FLAG_WOKE_HERE
- // and POLICY_FLAG_BRIGHT_HERE flags were set only when preprocessing raw
- // EV_KEY, EV_REL and EV_ABS events. As it happens, the touch event was
- // actually enqueued using the policyFlags that appeared in the final EV_SYN
- // events upon which no preprocessing took place. So policyFlags was always 0.
- // In the new native input dispatcher we're a bit more careful about event
- // preprocessing so the touches we receive can actually have non-zero policyFlags.
- // Unfortunately we obtain undesirable behavior.
- //
- // Here's what happens:
- //
- // When the device dims in anticipation of going to sleep, touches
- // in windows which have FLAG_TOUCHABLE_WHEN_WAKING cause
- // the device to brighten and reset the user activity timer.
- // Touches on other windows (such as the launcher window)
- // are dropped. Then after a moment, the device goes to sleep. Oops.
- //
- // Also notice how screenWasOff was being initialized using POLICY_FLAG_BRIGHT_HERE
- // instead of POLICY_FLAG_WOKE_HERE...
- //
- bool screenWasOff = false; // original policy: policyFlags & POLICY_FLAG_BRIGHT_HERE;
-
- int32_t displayId = entry->displayId;
- int32_t action = entry->action;
- int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
-
- // Update the touch state as needed based on the properties of the touch event.
- int32_t injectionResult = INPUT_EVENT_INJECTION_PENDING;
- InjectionPermission injectionPermission = INJECTION_PERMISSION_UNKNOWN;
- sp<InputWindowHandle> newHoverWindowHandle;
-
- bool isSplit = mTouchState.split;
- bool switchedDevice = mTouchState.deviceId >= 0 && mTouchState.displayId >= 0
- && (mTouchState.deviceId != entry->deviceId
- || mTouchState.source != entry->source
- || mTouchState.displayId != displayId);
- bool isHoverAction = (maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
- || maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
- || maskedAction == AMOTION_EVENT_ACTION_HOVER_EXIT);
- bool newGesture = (maskedAction == AMOTION_EVENT_ACTION_DOWN
- || maskedAction == AMOTION_EVENT_ACTION_SCROLL
- || isHoverAction);
- bool wrongDevice = false;
- if (newGesture) {
- bool down = maskedAction == AMOTION_EVENT_ACTION_DOWN;
- if (switchedDevice && mTouchState.down && !down) {
-#if DEBUG_FOCUS
- ALOGD("Dropping event because a pointer for a different device is already down.");
-#endif
- mTempTouchState.copyFrom(mTouchState);
- injectionResult = INPUT_EVENT_INJECTION_FAILED;
- switchedDevice = false;
- wrongDevice = true;
- goto Failed;
- }
- mTempTouchState.reset();
- mTempTouchState.down = down;
- mTempTouchState.deviceId = entry->deviceId;
- mTempTouchState.source = entry->source;
- mTempTouchState.displayId = displayId;
- isSplit = false;
- } else {
- mTempTouchState.copyFrom(mTouchState);
- }
-
- if (newGesture || (isSplit && maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN)) {
- /* Case 1: New splittable pointer going down, or need target for hover or scroll. */
-
- int32_t pointerIndex = getMotionEventActionPointerIndex(action);
- int32_t x = int32_t(entry->pointerCoords[pointerIndex].
- getAxisValue(AMOTION_EVENT_AXIS_X));
- int32_t y = int32_t(entry->pointerCoords[pointerIndex].
- getAxisValue(AMOTION_EVENT_AXIS_Y));
- sp<InputWindowHandle> newTouchedWindowHandle;
- sp<InputWindowHandle> topErrorWindowHandle;
- bool isTouchModal = false;
-
- // Traverse windows from front to back to find touched window and outside targets.
- size_t numWindows = mWindowHandles.size();
- for (size_t i = 0; i < numWindows; i++) {
- sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
- const InputWindowInfo* windowInfo = windowHandle->getInfo();
- if (windowInfo->displayId != displayId) {
- continue; // wrong display
- }
-
- int32_t flags = windowInfo->layoutParamsFlags;
- if (flags & InputWindowInfo::FLAG_SYSTEM_ERROR) {
- if (topErrorWindowHandle == NULL) {
- topErrorWindowHandle = windowHandle;
- }
- }
-
- if (windowInfo->visible) {
- if (! (flags & InputWindowInfo::FLAG_NOT_TOUCHABLE)) {
- isTouchModal = (flags & (InputWindowInfo::FLAG_NOT_FOCUSABLE
- | InputWindowInfo::FLAG_NOT_TOUCH_MODAL)) == 0;
- if (isTouchModal || windowInfo->touchableRegionContainsPoint(x, y)) {
- if (! screenWasOff
- || (flags & InputWindowInfo::FLAG_TOUCHABLE_WHEN_WAKING)) {
- newTouchedWindowHandle = windowHandle;
- }
- break; // found touched window, exit window loop
- }
- }
-
- if (maskedAction == AMOTION_EVENT_ACTION_DOWN
- && (flags & InputWindowInfo::FLAG_WATCH_OUTSIDE_TOUCH)) {
- int32_t outsideTargetFlags = InputTarget::FLAG_DISPATCH_AS_OUTSIDE;
- if (isWindowObscuredAtPointLocked(windowHandle, x, y)) {
- outsideTargetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
- }
-
- mTempTouchState.addOrUpdateWindow(
- windowHandle, outsideTargetFlags, BitSet32(0));
- }
- }
- }
-
- // If there is an error window but it is not taking focus (typically because
- // it is invisible) then wait for it. Any other focused window may in
- // fact be in ANR state.
- if (topErrorWindowHandle != NULL && newTouchedWindowHandle != topErrorWindowHandle) {
- injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
- NULL, NULL, nextWakeupTime,
- "Waiting because a system error window is about to be displayed.");
- injectionPermission = INJECTION_PERMISSION_UNKNOWN;
- goto Unresponsive;
- }
-
- // Figure out whether splitting will be allowed for this window.
- if (newTouchedWindowHandle != NULL
- && newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
- // New window supports splitting.
- isSplit = true;
- } else if (isSplit) {
- // New window does not support splitting but we have already split events.
- // Ignore the new window.
- newTouchedWindowHandle = NULL;
- }
-
- // Handle the case where we did not find a window.
- if (newTouchedWindowHandle == NULL) {
- // Try to assign the pointer to the first foreground window we find, if there is one.
- newTouchedWindowHandle = mTempTouchState.getFirstForegroundWindowHandle();
- if (newTouchedWindowHandle == NULL) {
- // There is no touched window. If this is an initial down event
- // then wait for a window to appear that will handle the touch. This is
- // to ensure that we report an ANR in the case where an application has started
- // but not yet put up a window and the user is starting to get impatient.
- if (maskedAction == AMOTION_EVENT_ACTION_DOWN
- && mFocusedApplicationHandle != NULL) {
- injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
- mFocusedApplicationHandle, NULL, nextWakeupTime,
- "Waiting because there is no touchable window that can "
- "handle the event but there is focused application that may "
- "eventually add a new window when it finishes starting up.");
- goto Unresponsive;
- }
-
- ALOGI("Dropping event because there is no touched window.");
- injectionResult = INPUT_EVENT_INJECTION_FAILED;
- goto Failed;
- }
- }
-
- // Set target flags.
- int32_t targetFlags = InputTarget::FLAG_FOREGROUND | InputTarget::FLAG_DISPATCH_AS_IS;
- if (isSplit) {
- targetFlags |= InputTarget::FLAG_SPLIT;
- }
- if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
- targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
- }
-
- // Update hover state.
- if (isHoverAction) {
- newHoverWindowHandle = newTouchedWindowHandle;
- } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
- newHoverWindowHandle = mLastHoverWindowHandle;
- }
-
- // Update the temporary touch state.
- BitSet32 pointerIds;
- if (isSplit) {
- uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
- pointerIds.markBit(pointerId);
- }
- mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
- } else {
- /* Case 2: Pointer move, up, cancel or non-splittable pointer down. */
-
- // If the pointer is not currently down, then ignore the event.
- if (! mTempTouchState.down) {
-#if DEBUG_FOCUS
- ALOGD("Dropping event because the pointer is not down or we previously "
- "dropped the pointer down event.");
-#endif
- injectionResult = INPUT_EVENT_INJECTION_FAILED;
- goto Failed;
- }
-
- // Check whether touches should slip outside of the current foreground window.
- if (maskedAction == AMOTION_EVENT_ACTION_MOVE
- && entry->pointerCount == 1
- && mTempTouchState.isSlippery()) {
- int32_t x = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X));
- int32_t y = int32_t(entry->pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y));
-
- sp<InputWindowHandle> oldTouchedWindowHandle =
- mTempTouchState.getFirstForegroundWindowHandle();
- sp<InputWindowHandle> newTouchedWindowHandle =
- findTouchedWindowAtLocked(displayId, x, y);
- if (oldTouchedWindowHandle != newTouchedWindowHandle
- && newTouchedWindowHandle != NULL) {
-#if DEBUG_FOCUS
- ALOGD("Touch is slipping out of window %s into window %s.",
- oldTouchedWindowHandle->getName().string(),
- newTouchedWindowHandle->getName().string());
-#endif
- // Make a slippery exit from the old window.
- mTempTouchState.addOrUpdateWindow(oldTouchedWindowHandle,
- InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT, BitSet32(0));
-
- // Make a slippery entrance into the new window.
- if (newTouchedWindowHandle->getInfo()->supportsSplitTouch()) {
- isSplit = true;
- }
-
- int32_t targetFlags = InputTarget::FLAG_FOREGROUND
- | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER;
- if (isSplit) {
- targetFlags |= InputTarget::FLAG_SPLIT;
- }
- if (isWindowObscuredAtPointLocked(newTouchedWindowHandle, x, y)) {
- targetFlags |= InputTarget::FLAG_WINDOW_IS_OBSCURED;
- }
-
- BitSet32 pointerIds;
- if (isSplit) {
- pointerIds.markBit(entry->pointerProperties[0].id);
- }
- mTempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds);
- }
- }
- }
-
- if (newHoverWindowHandle != mLastHoverWindowHandle) {
- // Let the previous window know that the hover sequence is over.
- if (mLastHoverWindowHandle != NULL) {
-#if DEBUG_HOVER
- ALOGD("Sending hover exit event to window %s.",
- mLastHoverWindowHandle->getName().string());
-#endif
- mTempTouchState.addOrUpdateWindow(mLastHoverWindowHandle,
- InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT, BitSet32(0));
- }
-
- // Let the new window know that the hover sequence is starting.
- if (newHoverWindowHandle != NULL) {
-#if DEBUG_HOVER
- ALOGD("Sending hover enter event to window %s.",
- newHoverWindowHandle->getName().string());
-#endif
- mTempTouchState.addOrUpdateWindow(newHoverWindowHandle,
- InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER, BitSet32(0));
- }
- }
-
- // Check permission to inject into all touched foreground windows and ensure there
- // is at least one touched foreground window.
- {
- bool haveForegroundWindow = false;
- for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
- const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
- if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
- haveForegroundWindow = true;
- if (! checkInjectionPermission(touchedWindow.windowHandle,
- entry->injectionState)) {
- injectionResult = INPUT_EVENT_INJECTION_PERMISSION_DENIED;
- injectionPermission = INJECTION_PERMISSION_DENIED;
- goto Failed;
- }
- }
- }
- if (! haveForegroundWindow) {
-#if DEBUG_FOCUS
- ALOGD("Dropping event because there is no touched foreground window to receive it.");
-#endif
- injectionResult = INPUT_EVENT_INJECTION_FAILED;
- goto Failed;
- }
-
- // Permission granted to injection into all touched foreground windows.
- injectionPermission = INJECTION_PERMISSION_GRANTED;
- }
-
- // Check whether windows listening for outside touches are owned by the same UID. If it is
- // set the policy flag that we will not reveal coordinate information to this window.
- if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
- sp<InputWindowHandle> foregroundWindowHandle =
- mTempTouchState.getFirstForegroundWindowHandle();
- const int32_t foregroundWindowUid = foregroundWindowHandle->getInfo()->ownerUid;
- for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
- const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
- if (touchedWindow.targetFlags & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
- sp<InputWindowHandle> inputWindowHandle = touchedWindow.windowHandle;
- if (inputWindowHandle->getInfo()->ownerUid != foregroundWindowUid) {
- mTempTouchState.addOrUpdateWindow(inputWindowHandle,
- InputTarget::FLAG_ZERO_COORDS, BitSet32(0));
- }
- }
- }
- }
-
- // Ensure all touched foreground windows are ready for new input.
- for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
- const TouchedWindow& touchedWindow = mTempTouchState.windows[i];
- if (touchedWindow.targetFlags & InputTarget::FLAG_FOREGROUND) {
- // If the touched window is paused then keep waiting.
- if (touchedWindow.windowHandle->getInfo()->paused) {
- injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
- NULL, touchedWindow.windowHandle, nextWakeupTime,
- "Waiting because the touched window is paused.");
- goto Unresponsive;
- }
-
- // If the touched window is still working on previous events then keep waiting.
- if (!isWindowReadyForMoreInputLocked(currentTime, touchedWindow.windowHandle, entry)) {
- injectionResult = handleTargetsNotReadyLocked(currentTime, entry,
- NULL, touchedWindow.windowHandle, nextWakeupTime,
- "Waiting because the touched window has not finished "
- "processing the input events that were previously delivered to it.");
- goto Unresponsive;
- }
- }
- }
-
- // If this is the first pointer going down and the touched window has a wallpaper
- // then also add the touched wallpaper windows so they are locked in for the duration
- // of the touch gesture.
- // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
- // engine only supports touch events. We would need to add a mechanism similar
- // to View.onGenericMotionEvent to enable wallpapers to handle these events.
- if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
- sp<InputWindowHandle> foregroundWindowHandle =
- mTempTouchState.getFirstForegroundWindowHandle();
- if (foregroundWindowHandle->getInfo()->hasWallpaper) {
- for (size_t i = 0; i < mWindowHandles.size(); i++) {
- sp<InputWindowHandle> windowHandle = mWindowHandles.itemAt(i);
- const InputWindowInfo* info = windowHandle->getInfo();
- if (info->displayId == displayId
- && windowHandle->getInfo()->layoutParamsType
- == InputWindowInfo::TYPE_WALLPAPER) {
- mTempTouchState.addOrUpdateWindow(windowHandle,
- InputTarget::FLAG_WINDOW_IS_OBSCURED
- | InputTarget::FLAG_DISPATCH_AS_IS,
- BitSet32(0));
- }
- }
- }
- }
-
- // Success! Output targets.
- injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
-
- for (size_t i = 0; i < mTempTouchState.windows.size(); i++) {
- const TouchedWindow& touchedWindow = mTempTouchState.windows.itemAt(i);
- addWindowTargetLocked(touchedWindow.windowHandle, touchedWindow.targetFlags,
- touchedWindow.pointerIds, inputTargets);
- }
-
- // Drop the outside or hover touch windows since we will not care about them
- // in the next iteration.
- mTempTouchState.filterNonAsIsTouchWindows();
-
-Failed:
- // Check injection permission once and for all.
- if (injectionPermission == INJECTION_PERMISSION_UNKNOWN) {
- if (checkInjectionPermission(NULL, entry->injectionState)) {
- injectionPermission = INJECTION_PERMISSION_GRANTED;
- } else {
- injectionPermission = INJECTION_PERMISSION_DENIED;
- }
- }
-
- // Update final pieces of touch state if the injector had permission.
- if (injectionPermission == INJECTION_PERMISSION_GRANTED) {
- if (!wrongDevice) {
- if (switchedDevice) {
-#if DEBUG_FOCUS
- ALOGD("Conflicting pointer actions: Switched to a different device.");
-#endif
- *outConflictingPointerActions = true;
- }
-
- if (isHoverAction) {
- // Started hovering, therefore no longer down.
- if (mTouchState.down) {
-#if DEBUG_FOCUS
- ALOGD("Conflicting pointer actions: Hover received while pointer was down.");
-#endif
- *outConflictingPointerActions = true;
- }
- mTouchState.reset();
- if (maskedAction == AMOTION_EVENT_ACTION_HOVER_ENTER
- || maskedAction == AMOTION_EVENT_ACTION_HOVER_MOVE) {
- mTouchState.deviceId = entry->deviceId;
- mTouchState.source = entry->source;
- mTouchState.displayId = displayId;
- }
- } else if (maskedAction == AMOTION_EVENT_ACTION_UP
- || maskedAction == AMOTION_EVENT_ACTION_CANCEL) {
- // All pointers up or canceled.
- mTouchState.reset();
- } else if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
- // First pointer went down.
- if (mTouchState.down) {
-#if DEBUG_FOCUS
- ALOGD("Conflicting pointer actions: Down received while already down.");
-#endif
- *outConflictingPointerActions = true;
- }
- mTouchState.copyFrom(mTempTouchState);
- } else if (maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
- // One pointer went up.
- if (isSplit) {
- int32_t pointerIndex = getMotionEventActionPointerIndex(action);
- uint32_t pointerId = entry->pointerProperties[pointerIndex].id;
-
- for (size_t i = 0; i < mTempTouchState.windows.size(); ) {
- TouchedWindow& touchedWindow = mTempTouchState.windows.editItemAt(i);
- if (touchedWindow.targetFlags & InputTarget::FLAG_SPLIT) {
- touchedWindow.pointerIds.clearBit(pointerId);
- if (touchedWindow.pointerIds.isEmpty()) {
- mTempTouchState.windows.removeAt(i);
- continue;
- }
- }
- i += 1;
- }
- }
- mTouchState.copyFrom(mTempTouchState);
- } else if (maskedAction == AMOTION_EVENT_ACTION_SCROLL) {
- // Discard temporary touch state since it was only valid for this action.
- } else {
- // Save changes to touch state as-is for all other actions.
- mTouchState.copyFrom(mTempTouchState);
- }
-
- // Update hover state.
- mLastHoverWindowHandle = newHoverWindowHandle;
- }
- } else {
-#if DEBUG_FOCUS
- ALOGD("Not updating touch focus because injection was denied.");
-#endif
- }
-
-Unresponsive:
- // Reset temporary touch state to ensure we release unnecessary references to input channels.
- mTempTouchState.reset();
-
- nsecs_t timeSpentWaitingForApplication = getTimeSpentWaitingForApplicationLocked(currentTime);
- updateDispatchStatisticsLocked(currentTime, entry,
- injectionResult, timeSpentWaitingForApplication);
-#if DEBUG_FOCUS
- ALOGD("findTouchedWindow finished: injectionResult=%d, injectionPermission=%d, "
- "timeSpentWaitingForApplication=%0.1fms",
- injectionResult, injectionPermission, timeSpentWaitingForApplication / 1000000.0);
-#endif
- return injectionResult;
-}
-
-void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
- int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
- inputTargets.push();
-
- const InputWindowInfo* windowInfo = windowHandle->getInfo();
- InputTarget& target = inputTargets.editTop();
- target.inputChannel = windowInfo->inputChannel;
- target.flags = targetFlags;
- target.xOffset = - windowInfo->frameLeft;
- target.yOffset = - windowInfo->frameTop;
- target.scaleFactor = windowInfo->scaleFactor;
- target.pointerIds = pointerIds;
-}
-
-void InputDispatcher::addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets) {
- for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
- inputTargets.push();
-
- InputTarget& target = inputTargets.editTop();
- target.inputChannel = mMonitoringChannels[i];
- target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
- target.xOffset = 0;
- target.yOffset = 0;
- target.pointerIds.clear();
- target.scaleFactor = 1.0f;
- }
-}
-
-bool InputDispatcher::checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
- const InjectionState* injectionState) {
- if (injectionState
- && (windowHandle == NULL
- || windowHandle->getInfo()->ownerUid != injectionState->injectorUid)
- && !hasInjectionPermission(injectionState->injectorPid, injectionState->injectorUid)) {
- if (windowHandle != NULL) {
- ALOGW("Permission denied: injecting event from pid %d uid %d to window %s "
- "owned by uid %d",
- injectionState->injectorPid, injectionState->injectorUid,
- windowHandle->getName().string(),
- windowHandle->getInfo()->ownerUid);
- } else {
- ALOGW("Permission denied: injecting event from pid %d uid %d",
- injectionState->injectorPid, injectionState->injectorUid);
- }
- return false;
- }
- return true;
-}
-
-bool InputDispatcher::isWindowObscuredAtPointLocked(
- const sp<InputWindowHandle>& windowHandle, int32_t x, int32_t y) const {
- int32_t displayId = windowHandle->getInfo()->displayId;
- size_t numWindows = mWindowHandles.size();
- for (size_t i = 0; i < numWindows; i++) {
- sp<InputWindowHandle> otherHandle = mWindowHandles.itemAt(i);
- if (otherHandle == windowHandle) {
- break;
- }
-
- const InputWindowInfo* otherInfo = otherHandle->getInfo();
- if (otherInfo->displayId == displayId
- && otherInfo->visible && !otherInfo->isTrustedOverlay()
- && otherInfo->frameContainsPoint(x, y)) {
- return true;
- }
- }
- return false;
-}
-
-bool InputDispatcher::isWindowReadyForMoreInputLocked(nsecs_t currentTime,
- const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry) {
- ssize_t connectionIndex = getConnectionIndexLocked(windowHandle->getInputChannel());
- if (connectionIndex >= 0) {
- sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
- if (connection->inputPublisherBlocked) {
- return false;
- }
- if (eventEntry->type == EventEntry::TYPE_KEY) {
- // If the event is a key event, then we must wait for all previous events to
- // complete before delivering it because previous events may have the
- // side-effect of transferring focus to a different window and we want to
- // ensure that the following keys are sent to the new window.
- //
- // Suppose the user touches a button in a window then immediately presses "A".
- // If the button causes a pop-up window to appear then we want to ensure that
- // the "A" key is delivered to the new pop-up window. This is because users
- // often anticipate pending UI changes when typing on a keyboard.
- // To obtain this behavior, we must serialize key events with respect to all
- // prior input events.
- return connection->outboundQueue.isEmpty()
- && connection->waitQueue.isEmpty();
- }
- // Touch events can always be sent to a window immediately because the user intended
- // to touch whatever was visible at the time. Even if focus changes or a new
- // window appears moments later, the touch event was meant to be delivered to
- // whatever window happened to be on screen at the time.
- //
- // Generic motion events, such as trackball or joystick events are a little trickier.
- // Like key events, generic motion events are delivered to the focused window.
- // Unlike key events, generic motion events don't tend to transfer focus to other
- // windows and it is not important for them to be serialized. So we prefer to deliver
- // generic motion events as soon as possible to improve efficiency and reduce lag
- // through batching.
- //
- // The one case where we pause input event delivery is when the wait queue is piling
- // up with lots of events because the application is not responding.
- // This condition ensures that ANRs are detected reliably.
- if (!connection->waitQueue.isEmpty()
- && currentTime >= connection->waitQueue.head->eventEntry->eventTime
- + STREAM_AHEAD_EVENT_TIMEOUT) {
- return false;
- }
- }
- return true;
-}
-
-String8 InputDispatcher::getApplicationWindowLabelLocked(
- const sp<InputApplicationHandle>& applicationHandle,
- const sp<InputWindowHandle>& windowHandle) {
- if (applicationHandle != NULL) {
- if (windowHandle != NULL) {
- String8 label(applicationHandle->getName());
- label.append(" - ");
- label.append(windowHandle->getName());
- return label;
- } else {
- return applicationHandle->getName();
- }
- } else if (windowHandle != NULL) {
- return windowHandle->getName();
- } else {
- return String8("<unknown application or window>");
- }
-}
-
-void InputDispatcher::pokeUserActivityLocked(const EventEntry* eventEntry) {
- if (mFocusedWindowHandle != NULL) {
- const InputWindowInfo* info = mFocusedWindowHandle->getInfo();
- if (info->inputFeatures & InputWindowInfo::INPUT_FEATURE_DISABLE_USER_ACTIVITY) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("Not poking user activity: disabled by window '%s'.", info->name.string());
-#endif
- return;
- }
- }
-
- int32_t eventType = USER_ACTIVITY_EVENT_OTHER;
- switch (eventEntry->type) {
- case EventEntry::TYPE_MOTION: {
- const MotionEntry* motionEntry = static_cast<const MotionEntry*>(eventEntry);
- if (motionEntry->action == AMOTION_EVENT_ACTION_CANCEL) {
- return;
- }
-
- if (MotionEvent::isTouchEvent(motionEntry->source, motionEntry->action)) {
- eventType = USER_ACTIVITY_EVENT_TOUCH;
- }
- break;
- }
- case EventEntry::TYPE_KEY: {
- const KeyEntry* keyEntry = static_cast<const KeyEntry*>(eventEntry);
- if (keyEntry->flags & AKEY_EVENT_FLAG_CANCELED) {
- return;
- }
- eventType = USER_ACTIVITY_EVENT_BUTTON;
- break;
- }
- }
-
- CommandEntry* commandEntry = postCommandLocked(
- & InputDispatcher::doPokeUserActivityLockedInterruptible);
- commandEntry->eventTime = eventEntry->eventTime;
- commandEntry->userActivityEventType = eventType;
-}
-
-void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,
- const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "
- "xOffset=%f, yOffset=%f, scaleFactor=%f, "
- "pointerIds=0x%x",
- connection->getInputChannelName(), inputTarget->flags,
- inputTarget->xOffset, inputTarget->yOffset,
- inputTarget->scaleFactor, inputTarget->pointerIds.value);
-#endif
-
- // Skip this event if the connection status is not normal.
- // We don't want to enqueue additional outbound events if the connection is broken.
- if (connection->status != Connection::STATUS_NORMAL) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ Dropping event because the channel status is %s",
- connection->getInputChannelName(), connection->getStatusLabel());
-#endif
- return;
- }
-
- // Split a motion event if needed.
- if (inputTarget->flags & InputTarget::FLAG_SPLIT) {
- ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);
-
- MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);
- if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {
- MotionEntry* splitMotionEntry = splitMotionEvent(
- originalMotionEntry, inputTarget->pointerIds);
- if (!splitMotionEntry) {
- return; // split event was dropped
- }
-#if DEBUG_FOCUS
- ALOGD("channel '%s' ~ Split motion event.",
- connection->getInputChannelName());
- logOutboundMotionDetailsLocked(" ", splitMotionEntry);
-#endif
- enqueueDispatchEntriesLocked(currentTime, connection,
- splitMotionEntry, inputTarget);
- splitMotionEntry->release();
- return;
- }
- }
-
- // Not splitting. Enqueue dispatch entries for the event as is.
- enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);
-}
-
-void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,
- const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {
- bool wasEmpty = connection->outboundQueue.isEmpty();
-
- // Enqueue dispatch entries for the requested modes.
- enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
- InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);
- enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
- InputTarget::FLAG_DISPATCH_AS_OUTSIDE);
- enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
- InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);
- enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
- InputTarget::FLAG_DISPATCH_AS_IS);
- enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
- InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);
- enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
- InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);
-
- // If the outbound queue was previously empty, start the dispatch cycle going.
- if (wasEmpty && !connection->outboundQueue.isEmpty()) {
- startDispatchCycleLocked(currentTime, connection);
- }
-}
-
-void InputDispatcher::enqueueDispatchEntryLocked(
- const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget,
- int32_t dispatchMode) {
- int32_t inputTargetFlags = inputTarget->flags;
- if (!(inputTargetFlags & dispatchMode)) {
- return;
- }
- inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode;
-
- // This is a new event.
- // Enqueue a new dispatch entry onto the outbound queue for this connection.
- DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref
- inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset,
- inputTarget->scaleFactor);
-
- // Apply target flags and update the connection's input state.
- switch (eventEntry->type) {
- case EventEntry::TYPE_KEY: {
- KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
- dispatchEntry->resolvedAction = keyEntry->action;
- dispatchEntry->resolvedFlags = keyEntry->flags;
-
- if (!connection->inputState.trackKey(keyEntry,
- dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event",
- connection->getInputChannelName());
-#endif
- delete dispatchEntry;
- return; // skip the inconsistent event
- }
- break;
- }
-
- case EventEntry::TYPE_MOTION: {
- MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
- if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) {
- dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE;
- } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) {
- dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT;
- } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) {
- dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
- } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
- dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL;
- } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) {
- dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN;
- } else {
- dispatchEntry->resolvedAction = motionEntry->action;
- }
- if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE
- && !connection->inputState.isHovering(
- motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event",
- connection->getInputChannelName());
-#endif
- dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER;
- }
-
- dispatchEntry->resolvedFlags = motionEntry->flags;
- if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) {
- dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED;
- }
-
- if (!connection->inputState.trackMotion(motionEntry,
- dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event",
- connection->getInputChannelName());
-#endif
- delete dispatchEntry;
- return; // skip the inconsistent event
- }
- break;
- }
- }
-
- // Remember that we are waiting for this dispatch to complete.
- if (dispatchEntry->hasForegroundTarget()) {
- incrementPendingForegroundDispatchesLocked(eventEntry);
- }
-
- // Enqueue the dispatch entry.
- connection->outboundQueue.enqueueAtTail(dispatchEntry);
- traceOutboundQueueLengthLocked(connection);
-}
-
-void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,
- const sp<Connection>& connection) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ startDispatchCycle",
- connection->getInputChannelName());
-#endif
-
- while (connection->status == Connection::STATUS_NORMAL
- && !connection->outboundQueue.isEmpty()) {
- DispatchEntry* dispatchEntry = connection->outboundQueue.head;
- dispatchEntry->deliveryTime = currentTime;
-
- // Publish the event.
- status_t status;
- EventEntry* eventEntry = dispatchEntry->eventEntry;
- switch (eventEntry->type) {
- case EventEntry::TYPE_KEY: {
- KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);
-
- // Publish the key event.
- status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,
- keyEntry->deviceId, keyEntry->source,
- dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
- keyEntry->keyCode, keyEntry->scanCode,
- keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,
- keyEntry->eventTime);
- break;
- }
-
- case EventEntry::TYPE_MOTION: {
- MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);
-
- PointerCoords scaledCoords[MAX_POINTERS];
- const PointerCoords* usingCoords = motionEntry->pointerCoords;
-
- // Set the X and Y offset depending on the input source.
- float xOffset, yOffset, scaleFactor;
- if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
- && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {
- scaleFactor = dispatchEntry->scaleFactor;
- xOffset = dispatchEntry->xOffset * scaleFactor;
- yOffset = dispatchEntry->yOffset * scaleFactor;
- if (scaleFactor != 1.0f) {
- for (size_t i = 0; i < motionEntry->pointerCount; i++) {
- scaledCoords[i] = motionEntry->pointerCoords[i];
- scaledCoords[i].scale(scaleFactor);
- }
- usingCoords = scaledCoords;
- }
- } else {
- xOffset = 0.0f;
- yOffset = 0.0f;
- scaleFactor = 1.0f;
-
- // We don't want the dispatch target to know.
- if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {
- for (size_t i = 0; i < motionEntry->pointerCount; i++) {
- scaledCoords[i].clear();
- }
- usingCoords = scaledCoords;
- }
- }
-
- // Publish the motion event.
- status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,
- motionEntry->deviceId, motionEntry->source,
- dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,
- motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,
- xOffset, yOffset,
- motionEntry->xPrecision, motionEntry->yPrecision,
- motionEntry->downTime, motionEntry->eventTime,
- motionEntry->pointerCount, motionEntry->pointerProperties,
- usingCoords);
- break;
- }
-
- default:
- ALOG_ASSERT(false);
- return;
- }
-
- // Check the result.
- if (status) {
- if (status == WOULD_BLOCK) {
- if (connection->waitQueue.isEmpty()) {
- ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "
- "This is unexpected because the wait queue is empty, so the pipe "
- "should be empty and we shouldn't have any problems writing an "
- "event to it, status=%d", connection->getInputChannelName(), status);
- abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
- } else {
- // Pipe is full and we are waiting for the app to finish process some events
- // before sending more events to it.
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "
- "waiting for the application to catch up",
- connection->getInputChannelName());
-#endif
- connection->inputPublisherBlocked = true;
- }
- } else {
- ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "
- "status=%d", connection->getInputChannelName(), status);
- abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);
- }
- return;
- }
-
- // Re-enqueue the event on the wait queue.
- connection->outboundQueue.dequeue(dispatchEntry);
- traceOutboundQueueLengthLocked(connection);
- connection->waitQueue.enqueueAtTail(dispatchEntry);
- traceWaitQueueLengthLocked(connection);
- }
-}
-
-void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,
- const sp<Connection>& connection, uint32_t seq, bool handled) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",
- connection->getInputChannelName(), seq, toString(handled));
-#endif
-
- connection->inputPublisherBlocked = false;
-
- if (connection->status == Connection::STATUS_BROKEN
- || connection->status == Connection::STATUS_ZOMBIE) {
- return;
- }
-
- // Notify other system components and prepare to start the next dispatch cycle.
- onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);
-}
-
-void InputDispatcher::abortBrokenDispatchCycleLocked(nsecs_t currentTime,
- const sp<Connection>& connection, bool notify) {
-#if DEBUG_DISPATCH_CYCLE
- ALOGD("channel '%s' ~ abortBrokenDispatchCycle - notify=%s",
- connection->getInputChannelName(), toString(notify));
-#endif
-
- // Clear the dispatch queues.
- drainDispatchQueueLocked(&connection->outboundQueue);
- traceOutboundQueueLengthLocked(connection);
- drainDispatchQueueLocked(&connection->waitQueue);
- traceWaitQueueLengthLocked(connection);
-
- // The connection appears to be unrecoverably broken.
- // Ignore already broken or zombie connections.
- if (connection->status == Connection::STATUS_NORMAL) {
- connection->status = Connection::STATUS_BROKEN;
-
- if (notify) {
- // Notify other system components.
- onDispatchCycleBrokenLocked(currentTime, connection);
- }
- }
-}
-
-void InputDispatcher::drainDispatchQueueLocked(Queue<DispatchEntry>* queue) {
- while (!queue->isEmpty()) {
- DispatchEntry* dispatchEntry = queue->dequeueAtHead();
- releaseDispatchEntryLocked(dispatchEntry);
- }
-}
-
-void InputDispatcher::releaseDispatchEntryLocked(DispatchEntry* dispatchEntry) {
- if (dispatchEntry->hasForegroundTarget()) {
- decrementPendingForegroundDispatchesLocked(dispatchEntry->eventEntry);
- }
- delete dispatchEntry;
-}
-
-int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {
- InputDispatcher* d = static_cast<InputDispatcher*>(data);
-
- { // acquire lock
- AutoMutex _l(d->mLock);
-
- ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);
- if (connectionIndex < 0) {
- ALOGE("Received spurious receive callback for unknown input channel. "
- "fd=%d, events=0x%x", fd, events);
- return 0; // remove the callback
- }
-
- bool notify;
- sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);
- if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {
- if (!(events & ALOOPER_EVENT_INPUT)) {
- ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event. "
- "events=0x%x", connection->getInputChannelName(), events);
- return 1;
- }
-
- nsecs_t currentTime = now();
- bool gotOne = false;
- status_t status;
- for (;;) {
- uint32_t seq;
- bool handled;
- status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
- if (status) {
- break;
- }
- d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
- gotOne = true;
- }
- if (gotOne) {
- d->runCommandsLockedInterruptible();
- if (status == WOULD_BLOCK) {
- return 1;
- }
- }
-
- notify = status != DEAD_OBJECT || !connection->monitor;
- if (notify) {
- ALOGE("channel '%s' ~ Failed to receive finished signal. status=%d",
- connection->getInputChannelName(), status);
- }
- } else {
- // Monitor channels are never explicitly unregistered.
- // We do it automatically when the remote endpoint is closed so don't warn
- // about them.
- notify = !connection->monitor;
- if (notify) {
- ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred. "
- "events=0x%x", connection->getInputChannelName(), events);
- }
- }
-
- // Unregister the channel.
- d->unregisterInputChannelLocked(connection->inputChannel, notify);
- return 0; // remove the callback
- } // release lock
-}
-
-void InputDispatcher::synthesizeCancelationEventsForAllConnectionsLocked(
- const CancelationOptions& options) {
- for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
- synthesizeCancelationEventsForConnectionLocked(
- mConnectionsByFd.valueAt(i), options);
- }
-}
-
-void InputDispatcher::synthesizeCancelationEventsForInputChannelLocked(
- const sp<InputChannel>& channel, const CancelationOptions& options) {
- ssize_t index = getConnectionIndexLocked(channel);
- if (index >= 0) {
- synthesizeCancelationEventsForConnectionLocked(
- mConnectionsByFd.valueAt(index), options);
- }
-}
-
-void InputDispatcher::synthesizeCancelationEventsForConnectionLocked(
- const sp<Connection>& connection, const CancelationOptions& options) {
- if (connection->status == Connection::STATUS_BROKEN) {
- return;
- }
-
- nsecs_t currentTime = now();
-
- Vector<EventEntry*> cancelationEvents;
- connection->inputState.synthesizeCancelationEvents(currentTime,
- cancelationEvents, options);
-
- if (!cancelationEvents.isEmpty()) {
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("channel '%s' ~ Synthesized %d cancelation events to bring channel back in sync "
- "with reality: %s, mode=%d.",
- connection->getInputChannelName(), cancelationEvents.size(),
- options.reason, options.mode);
-#endif
- for (size_t i = 0; i < cancelationEvents.size(); i++) {
- EventEntry* cancelationEventEntry = cancelationEvents.itemAt(i);
- switch (cancelationEventEntry->type) {
- case EventEntry::TYPE_KEY:
- logOutboundKeyDetailsLocked("cancel - ",
- static_cast<KeyEntry*>(cancelationEventEntry));
- break;
- case EventEntry::TYPE_MOTION:
- logOutboundMotionDetailsLocked("cancel - ",
- static_cast<MotionEntry*>(cancelationEventEntry));
- break;
- }
-
- InputTarget target;
- sp<InputWindowHandle> windowHandle = getWindowHandleLocked(connection->inputChannel);
- if (windowHandle != NULL) {
- const InputWindowInfo* windowInfo = windowHandle->getInfo();
- target.xOffset = -windowInfo->frameLeft;
- target.yOffset = -windowInfo->frameTop;
- target.scaleFactor = windowInfo->scaleFactor;
- } else {
- target.xOffset = 0;
- target.yOffset = 0;
- target.scaleFactor = 1.0f;
- }
- target.inputChannel = connection->inputChannel;
- target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
-
- enqueueDispatchEntryLocked(connection, cancelationEventEntry, // increments ref
- &target, InputTarget::FLAG_DISPATCH_AS_IS);
-
- cancelationEventEntry->release();
- }
-
- startDispatchCycleLocked(currentTime, connection);
- }
-}
-
-InputDispatcher::MotionEntry*
-InputDispatcher::splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds) {
- ALOG_ASSERT(pointerIds.value != 0);
-
- PointerProperties splitPointerProperties[MAX_POINTERS];
- PointerCoords splitPointerCoords[MAX_POINTERS];
-
- uint32_t originalPointerCount = originalMotionEntry->pointerCount;
- uint32_t splitPointerCount = 0;
-
- for (uint32_t originalPointerIndex = 0; originalPointerIndex < originalPointerCount;
- originalPointerIndex++) {
- const PointerProperties& pointerProperties =
- originalMotionEntry->pointerProperties[originalPointerIndex];
- uint32_t pointerId = uint32_t(pointerProperties.id);
- if (pointerIds.hasBit(pointerId)) {
- splitPointerProperties[splitPointerCount].copyFrom(pointerProperties);
- splitPointerCoords[splitPointerCount].copyFrom(
- originalMotionEntry->pointerCoords[originalPointerIndex]);
- splitPointerCount += 1;
- }
- }
-
- if (splitPointerCount != pointerIds.count()) {
- // This is bad. We are missing some of the pointers that we expected to deliver.
- // Most likely this indicates that we received an ACTION_MOVE events that has
- // different pointer ids than we expected based on the previous ACTION_DOWN
- // or ACTION_POINTER_DOWN events that caused us to decide to split the pointers
- // in this way.
- ALOGW("Dropping split motion event because the pointer count is %d but "
- "we expected there to be %d pointers. This probably means we received "
- "a broken sequence of pointer ids from the input device.",
- splitPointerCount, pointerIds.count());
- return NULL;
- }
-
- int32_t action = originalMotionEntry->action;
- int32_t maskedAction = action & AMOTION_EVENT_ACTION_MASK;
- if (maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
- || maskedAction == AMOTION_EVENT_ACTION_POINTER_UP) {
- int32_t originalPointerIndex = getMotionEventActionPointerIndex(action);
- const PointerProperties& pointerProperties =
- originalMotionEntry->pointerProperties[originalPointerIndex];
- uint32_t pointerId = uint32_t(pointerProperties.id);
- if (pointerIds.hasBit(pointerId)) {
- if (pointerIds.count() == 1) {
- // The first/last pointer went down/up.
- action = maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN
- ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
- } else {
- // A secondary pointer went down/up.
- uint32_t splitPointerIndex = 0;
- while (pointerId != uint32_t(splitPointerProperties[splitPointerIndex].id)) {
- splitPointerIndex += 1;
- }
- action = maskedAction | (splitPointerIndex
- << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
- }
- } else {
- // An unrelated pointer changed.
- action = AMOTION_EVENT_ACTION_MOVE;
- }
- }
-
- MotionEntry* splitMotionEntry = new MotionEntry(
- originalMotionEntry->eventTime,
- originalMotionEntry->deviceId,
- originalMotionEntry->source,
- originalMotionEntry->policyFlags,
- action,
- originalMotionEntry->flags,
- originalMotionEntry->metaState,
- originalMotionEntry->buttonState,
- originalMotionEntry->edgeFlags,
- originalMotionEntry->xPrecision,
- originalMotionEntry->yPrecision,
- originalMotionEntry->downTime,
- originalMotionEntry->displayId,
- splitPointerCount, splitPointerProperties, splitPointerCoords);
-
- if (originalMotionEntry->injectionState) {
- splitMotionEntry->injectionState = originalMotionEntry->injectionState;
- splitMotionEntry->injectionState->refCount += 1;
- }
-
- return splitMotionEntry;
-}
-
-void InputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) {
-#if DEBUG_INBOUND_EVENT_DETAILS
- ALOGD("notifyConfigurationChanged - eventTime=%lld", args->eventTime);
-#endif
-
- bool needWake;
- { // acquire lock
- AutoMutex _l(mLock);
-
- ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
- needWake = enqueueInboundEventLocked(newEntry);
- } // release lock
-
- if (needWake) {
- mLooper->wake();
- }
-}
-
-void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {
-#if DEBUG_INBOUND_EVENT_DETAILS
- ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "
- "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",
- args->eventTime, args->deviceId, args->source, args->policyFlags,
- args->action, args->flags, args->keyCode, args->scanCode,
- args->metaState, args->downTime);
-#endif
- if (!validateKeyEvent(args->action)) {
- return;
- }
-
- uint32_t policyFlags = args->policyFlags;
- int32_t flags = args->flags;
- int32_t metaState = args->metaState;
- if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {
- policyFlags |= POLICY_FLAG_VIRTUAL;
- flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
- }
- if (policyFlags & POLICY_FLAG_ALT) {
- metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
- }
- if (policyFlags & POLICY_FLAG_ALT_GR) {
- metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
- }
- if (policyFlags & POLICY_FLAG_SHIFT) {
- metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
- }
- if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
- metaState |= AMETA_CAPS_LOCK_ON;
- }
- if (policyFlags & POLICY_FLAG_FUNCTION) {
- metaState |= AMETA_FUNCTION_ON;
- }
-
- policyFlags |= POLICY_FLAG_TRUSTED;
-
- KeyEvent event;
- event.initialize(args->deviceId, args->source, args->action,
- flags, args->keyCode, args->scanCode, metaState, 0,
- args->downTime, args->eventTime);
-
- mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);
-
- if (policyFlags & POLICY_FLAG_WOKE_HERE) {
- flags |= AKEY_EVENT_FLAG_WOKE_HERE;
- }
-
- bool needWake;
- { // acquire lock
- mLock.lock();
-
- if (shouldSendKeyToInputFilterLocked(args)) {
- mLock.unlock();
-
- policyFlags |= POLICY_FLAG_FILTERED;
- if (!mPolicy->filterInputEvent(&event, policyFlags)) {
- return; // event was consumed by the filter
- }
-
- mLock.lock();
- }
-
- int32_t repeatCount = 0;
- KeyEntry* newEntry = new KeyEntry(args->eventTime,
- args->deviceId, args->source, policyFlags,
- args->action, flags, args->keyCode, args->scanCode,
- metaState, repeatCount, args->downTime);
-
- needWake = enqueueInboundEventLocked(newEntry);
- mLock.unlock();
- } // release lock
-
- if (needWake) {
- mLooper->wake();
- }
-}
-
-bool InputDispatcher::shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args) {
- return mInputFilterEnabled;
-}
-
-void InputDispatcher::notifyMotion(const NotifyMotionArgs* args) {
-#if DEBUG_INBOUND_EVENT_DETAILS
- ALOGD("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, "
- "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, "
- "xPrecision=%f, yPrecision=%f, downTime=%lld",
- args->eventTime, args->deviceId, args->source, args->policyFlags,
- args->action, args->flags, args->metaState, args->buttonState,
- args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime);
- for (uint32_t i = 0; i < args->pointerCount; i++) {
- ALOGD(" Pointer %d: id=%d, toolType=%d, "
- "x=%f, y=%f, pressure=%f, size=%f, "
- "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, "
- "orientation=%f",
- i, args->pointerProperties[i].id,
- args->pointerProperties[i].toolType,
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X),
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y),
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE),
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
- args->pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
- }
-#endif
- if (!validateMotionEvent(args->action, args->pointerCount, args->pointerProperties)) {
- return;
- }
-
- uint32_t policyFlags = args->policyFlags;
- policyFlags |= POLICY_FLAG_TRUSTED;
- mPolicy->interceptMotionBeforeQueueing(args->eventTime, /*byref*/ policyFlags);
-
- bool needWake;
- { // acquire lock
- mLock.lock();
-
- if (shouldSendMotionToInputFilterLocked(args)) {
- mLock.unlock();
-
- MotionEvent event;
- event.initialize(args->deviceId, args->source, args->action, args->flags,
- args->edgeFlags, args->metaState, args->buttonState, 0, 0,
- args->xPrecision, args->yPrecision,
- args->downTime, args->eventTime,
- args->pointerCount, args->pointerProperties, args->pointerCoords);
-
- policyFlags |= POLICY_FLAG_FILTERED;
- if (!mPolicy->filterInputEvent(&event, policyFlags)) {
- return; // event was consumed by the filter
- }
-
- mLock.lock();
- }
-
- // Just enqueue a new motion event.
- MotionEntry* newEntry = new MotionEntry(args->eventTime,
- args->deviceId, args->source, policyFlags,
- args->action, args->flags, args->metaState, args->buttonState,
- args->edgeFlags, args->xPrecision, args->yPrecision, args->downTime,
- args->displayId,
- args->pointerCount, args->pointerProperties, args->pointerCoords);
-
- needWake = enqueueInboundEventLocked(newEntry);
- mLock.unlock();
- } // release lock
-
- if (needWake) {
- mLooper->wake();
- }
-}
-
-bool InputDispatcher::shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args) {
- // TODO: support sending secondary display events to input filter
- return mInputFilterEnabled && isMainDisplay(args->displayId);
-}
-
-void InputDispatcher::notifySwitch(const NotifySwitchArgs* args) {
-#if DEBUG_INBOUND_EVENT_DETAILS
- ALOGD("notifySwitch - eventTime=%lld, policyFlags=0x%x, switchValues=0x%08x, switchMask=0x%08x",
- args->eventTime, args->policyFlags,
- args->switchValues, args->switchMask);
-#endif
-
- uint32_t policyFlags = args->policyFlags;
- policyFlags |= POLICY_FLAG_TRUSTED;
- mPolicy->notifySwitch(args->eventTime,
- args->switchValues, args->switchMask, policyFlags);
-}
-
-void InputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
-#if DEBUG_INBOUND_EVENT_DETAILS
- ALOGD("notifyDeviceReset - eventTime=%lld, deviceId=%d",
- args->eventTime, args->deviceId);
-#endif
-
- bool needWake;
- { // acquire lock
- AutoMutex _l(mLock);
-
- DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
- needWake = enqueueInboundEventLocked(newEntry);
- } // release lock
-
- if (needWake) {
- mLooper->wake();
- }
-}
-
-int32_t InputDispatcher::injectInputEvent(const InputEvent* event,
- int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
- uint32_t policyFlags) {
-#if DEBUG_INBOUND_EVENT_DETAILS
- ALOGD("injectInputEvent - eventType=%d, injectorPid=%d, injectorUid=%d, "
- "syncMode=%d, timeoutMillis=%d, policyFlags=0x%08x",
- event->getType(), injectorPid, injectorUid, syncMode, timeoutMillis, policyFlags);
-#endif
-
- nsecs_t endTime = now() + milliseconds_to_nanoseconds(timeoutMillis);
-
- policyFlags |= POLICY_FLAG_INJECTED;
- if (hasInjectionPermission(injectorPid, injectorUid)) {
- policyFlags |= POLICY_FLAG_TRUSTED;
- }
-
- EventEntry* firstInjectedEntry;
- EventEntry* lastInjectedEntry;
- switch (event->getType()) {
- case AINPUT_EVENT_TYPE_KEY: {
- const KeyEvent* keyEvent = static_cast<const KeyEvent*>(event);
- int32_t action = keyEvent->getAction();
- if (! validateKeyEvent(action)) {
- return INPUT_EVENT_INJECTION_FAILED;
- }
-
- int32_t flags = keyEvent->getFlags();
- if (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY) {
- policyFlags |= POLICY_FLAG_VIRTUAL;
- }
-
- if (!(policyFlags & POLICY_FLAG_FILTERED)) {
- mPolicy->interceptKeyBeforeQueueing(keyEvent, /*byref*/ policyFlags);
- }
-
- if (policyFlags & POLICY_FLAG_WOKE_HERE) {
- flags |= AKEY_EVENT_FLAG_WOKE_HERE;
- }
-
- mLock.lock();
- firstInjectedEntry = new KeyEntry(keyEvent->getEventTime(),
- keyEvent->getDeviceId(), keyEvent->getSource(),
- policyFlags, action, flags,
- keyEvent->getKeyCode(), keyEvent->getScanCode(), keyEvent->getMetaState(),
- keyEvent->getRepeatCount(), keyEvent->getDownTime());
- lastInjectedEntry = firstInjectedEntry;
- break;
- }
-
- case AINPUT_EVENT_TYPE_MOTION: {
- const MotionEvent* motionEvent = static_cast<const MotionEvent*>(event);
- int32_t displayId = ADISPLAY_ID_DEFAULT;
- int32_t action = motionEvent->getAction();
- size_t pointerCount = motionEvent->getPointerCount();
- const PointerProperties* pointerProperties = motionEvent->getPointerProperties();
- if (! validateMotionEvent(action, pointerCount, pointerProperties)) {
- return INPUT_EVENT_INJECTION_FAILED;
- }
-
- if (!(policyFlags & POLICY_FLAG_FILTERED)) {
- nsecs_t eventTime = motionEvent->getEventTime();
- mPolicy->interceptMotionBeforeQueueing(eventTime, /*byref*/ policyFlags);
- }
-
- mLock.lock();
- const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
- const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
- firstInjectedEntry = new MotionEntry(*sampleEventTimes,
- motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
- action, motionEvent->getFlags(),
- motionEvent->getMetaState(), motionEvent->getButtonState(),
- motionEvent->getEdgeFlags(),
- motionEvent->getXPrecision(), motionEvent->getYPrecision(),
- motionEvent->getDownTime(), displayId,
- uint32_t(pointerCount), pointerProperties, samplePointerCoords);
- lastInjectedEntry = firstInjectedEntry;
- for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
- sampleEventTimes += 1;
- samplePointerCoords += pointerCount;
- MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
- motionEvent->getDeviceId(), motionEvent->getSource(), policyFlags,
- action, motionEvent->getFlags(),
- motionEvent->getMetaState(), motionEvent->getButtonState(),
- motionEvent->getEdgeFlags(),
- motionEvent->getXPrecision(), motionEvent->getYPrecision(),
- motionEvent->getDownTime(), displayId,
- uint32_t(pointerCount), pointerProperties, samplePointerCoords);
- lastInjectedEntry->next = nextInjectedEntry;
- lastInjectedEntry = nextInjectedEntry;
- }
- break;
- }
-
- default:
- ALOGW("Cannot inject event of type %d", event->getType());
- return INPUT_EVENT_INJECTION_FAILED;
- }
-
- InjectionState* injectionState = new InjectionState(injectorPid, injectorUid);
- if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
- injectionState->injectionIsAsync = true;
- }
-
- injectionState->refCount += 1;
- lastInjectedEntry->injectionState = injectionState;
-
- bool needWake = false;
- for (EventEntry* entry = firstInjectedEntry; entry != NULL; ) {
- EventEntry* nextEntry = entry->next;
- needWake |= enqueueInboundEventLocked(entry);
- entry = nextEntry;
- }
-
- mLock.unlock();
-
- if (needWake) {
- mLooper->wake();
- }
-
- int32_t injectionResult;
- { // acquire lock
- AutoMutex _l(mLock);
-
- if (syncMode == INPUT_EVENT_INJECTION_SYNC_NONE) {
- injectionResult = INPUT_EVENT_INJECTION_SUCCEEDED;
- } else {
- for (;;) {
- injectionResult = injectionState->injectionResult;
- if (injectionResult != INPUT_EVENT_INJECTION_PENDING) {
- break;
- }
-
- nsecs_t remainingTimeout = endTime - now();
- if (remainingTimeout <= 0) {
-#if DEBUG_INJECTION
- ALOGD("injectInputEvent - Timed out waiting for injection result "
- "to become available.");
-#endif
- injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
- break;
- }
-
- mInjectionResultAvailableCondition.waitRelative(mLock, remainingTimeout);
- }
-
- if (injectionResult == INPUT_EVENT_INJECTION_SUCCEEDED
- && syncMode == INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED) {
- while (injectionState->pendingForegroundDispatches != 0) {
-#if DEBUG_INJECTION
- ALOGD("injectInputEvent - Waiting for %d pending foreground dispatches.",
- injectionState->pendingForegroundDispatches);
-#endif
- nsecs_t remainingTimeout = endTime - now();
- if (remainingTimeout <= 0) {
-#if DEBUG_INJECTION
- ALOGD("injectInputEvent - Timed out waiting for pending foreground "
- "dispatches to finish.");
-#endif
- injectionResult = INPUT_EVENT_INJECTION_TIMED_OUT;
- break;
- }
-
- mInjectionSyncFinishedCondition.waitRelative(mLock, remainingTimeout);
- }
- }
- }
-
- injectionState->release();
- } // release lock
-
-#if DEBUG_INJECTION
- ALOGD("injectInputEvent - Finished with result %d. "
- "injectorPid=%d, injectorUid=%d",
- injectionResult, injectorPid, injectorUid);
-#endif
-
- return injectionResult;
-}
-
-bool InputDispatcher::hasInjectionPermission(int32_t injectorPid, int32_t injectorUid) {
- return injectorUid == 0
- || mPolicy->checkInjectEventsPermissionNonReentrant(injectorPid, injectorUid);
-}
-
-void InputDispatcher::setInjectionResultLocked(EventEntry* entry, int32_t injectionResult) {
- InjectionState* injectionState = entry->injectionState;
- if (injectionState) {
-#if DEBUG_INJECTION
- ALOGD("Setting input event injection result to %d. "
- "injectorPid=%d, injectorUid=%d",
- injectionResult, injectionState->injectorPid, injectionState->injectorUid);
-#endif
-
- if (injectionState->injectionIsAsync
- && !(entry->policyFlags & POLICY_FLAG_FILTERED)) {
- // Log the outcome since the injector did not wait for the injection result.
- switch (injectionResult) {
- case INPUT_EVENT_INJECTION_SUCCEEDED:
- ALOGV("Asynchronous input event injection succeeded.");
- break;
- case INPUT_EVENT_INJECTION_FAILED:
- ALOGW("Asynchronous input event injection failed.");
- break;
- case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
- ALOGW("Asynchronous input event injection permission denied.");
- break;
- case INPUT_EVENT_INJECTION_TIMED_OUT:
- ALOGW("Asynchronous input event injection timed out.");
- break;
- }
- }
-
- injectionState->injectionResult = injectionResult;
- mInjectionResultAvailableCondition.broadcast();
- }
-}
-
-void InputDispatcher::incrementPendingForegroundDispatchesLocked(EventEntry* entry) {
- InjectionState* injectionState = entry->injectionState;
- if (injectionState) {
- injectionState->pendingForegroundDispatches += 1;
- }
-}
-
-void InputDispatcher::decrementPendingForegroundDispatchesLocked(EventEntry* entry) {
- InjectionState* injectionState = entry->injectionState;
- if (injectionState) {
- injectionState->pendingForegroundDispatches -= 1;
-
- if (injectionState->pendingForegroundDispatches == 0) {
- mInjectionSyncFinishedCondition.broadcast();
- }
- }
-}
-
-sp<InputWindowHandle> InputDispatcher::getWindowHandleLocked(
- const sp<InputChannel>& inputChannel) const {
- size_t numWindows = mWindowHandles.size();
- for (size_t i = 0; i < numWindows; i++) {
- const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
- if (windowHandle->getInputChannel() == inputChannel) {
- return windowHandle;
- }
- }
- return NULL;
-}
-
-bool InputDispatcher::hasWindowHandleLocked(
- const sp<InputWindowHandle>& windowHandle) const {
- size_t numWindows = mWindowHandles.size();
- for (size_t i = 0; i < numWindows; i++) {
- if (mWindowHandles.itemAt(i) == windowHandle) {
- return true;
- }
- }
- return false;
-}
-
-void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {
-#if DEBUG_FOCUS
- ALOGD("setInputWindows");
-#endif
- { // acquire lock
- AutoMutex _l(mLock);
-
- Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;
- mWindowHandles = inputWindowHandles;
-
- sp<InputWindowHandle> newFocusedWindowHandle;
- bool foundHoveredWindow = false;
- for (size_t i = 0; i < mWindowHandles.size(); i++) {
- const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
- if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {
- mWindowHandles.removeAt(i--);
- continue;
- }
- if (windowHandle->getInfo()->hasFocus) {
- newFocusedWindowHandle = windowHandle;
- }
- if (windowHandle == mLastHoverWindowHandle) {
- foundHoveredWindow = true;
- }
- }
-
- if (!foundHoveredWindow) {
- mLastHoverWindowHandle = NULL;
- }
-
- if (mFocusedWindowHandle != newFocusedWindowHandle) {
- if (mFocusedWindowHandle != NULL) {
-#if DEBUG_FOCUS
- ALOGD("Focus left window: %s",
- mFocusedWindowHandle->getName().string());
-#endif
- sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();
- if (focusedInputChannel != NULL) {
- CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
- "focus left window");
- synthesizeCancelationEventsForInputChannelLocked(
- focusedInputChannel, options);
- }
- }
- if (newFocusedWindowHandle != NULL) {
-#if DEBUG_FOCUS
- ALOGD("Focus entered window: %s",
- newFocusedWindowHandle->getName().string());
-#endif
- }
- mFocusedWindowHandle = newFocusedWindowHandle;
- }
-
- for (size_t i = 0; i < mTouchState.windows.size(); i++) {
- TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);
- if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
-#if DEBUG_FOCUS
- ALOGD("Touched window was removed: %s",
- touchedWindow.windowHandle->getName().string());
-#endif
- sp<InputChannel> touchedInputChannel =
- touchedWindow.windowHandle->getInputChannel();
- if (touchedInputChannel != NULL) {
- CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
- "touched window was removed");
- synthesizeCancelationEventsForInputChannelLocked(
- touchedInputChannel, options);
- }
- mTouchState.windows.removeAt(i--);
- }
- }
-
- // Release information for windows that are no longer present.
- // This ensures that unused input channels are released promptly.
- // Otherwise, they might stick around until the window handle is destroyed
- // which might not happen until the next GC.
- for (size_t i = 0; i < oldWindowHandles.size(); i++) {
- const sp<InputWindowHandle>& oldWindowHandle = oldWindowHandles.itemAt(i);
- if (!hasWindowHandleLocked(oldWindowHandle)) {
-#if DEBUG_FOCUS
- ALOGD("Window went away: %s", oldWindowHandle->getName().string());
-#endif
- oldWindowHandle->releaseInfo();
- }
- }
- } // release lock
-
- // Wake up poll loop since it may need to make new input dispatching choices.
- mLooper->wake();
-}
-
-void InputDispatcher::setFocusedApplication(
- const sp<InputApplicationHandle>& inputApplicationHandle) {
-#if DEBUG_FOCUS
- ALOGD("setFocusedApplication");
-#endif
- { // acquire lock
- AutoMutex _l(mLock);
-
- if (inputApplicationHandle != NULL && inputApplicationHandle->updateInfo()) {
- if (mFocusedApplicationHandle != inputApplicationHandle) {
- if (mFocusedApplicationHandle != NULL) {
- resetANRTimeoutsLocked();
- mFocusedApplicationHandle->releaseInfo();
- }
- mFocusedApplicationHandle = inputApplicationHandle;
- }
- } else if (mFocusedApplicationHandle != NULL) {
- resetANRTimeoutsLocked();
- mFocusedApplicationHandle->releaseInfo();
- mFocusedApplicationHandle.clear();
- }
-
-#if DEBUG_FOCUS
- //logDispatchStateLocked();
-#endif
- } // release lock
-
- // Wake up poll loop since it may need to make new input dispatching choices.
- mLooper->wake();
-}
-
-void InputDispatcher::setInputDispatchMode(bool enabled, bool frozen) {
-#if DEBUG_FOCUS
- ALOGD("setInputDispatchMode: enabled=%d, frozen=%d", enabled, frozen);
-#endif
-
- bool changed;
- { // acquire lock
- AutoMutex _l(mLock);
-
- if (mDispatchEnabled != enabled || mDispatchFrozen != frozen) {
- if (mDispatchFrozen && !frozen) {
- resetANRTimeoutsLocked();
- }
-
- if (mDispatchEnabled && !enabled) {
- resetAndDropEverythingLocked("dispatcher is being disabled");
- }
-
- mDispatchEnabled = enabled;
- mDispatchFrozen = frozen;
- changed = true;
- } else {
- changed = false;
- }
-
-#if DEBUG_FOCUS
- //logDispatchStateLocked();
-#endif
- } // release lock
-
- if (changed) {
- // Wake up poll loop since it may need to make new input dispatching choices.
- mLooper->wake();
- }
-}
-
-void InputDispatcher::setInputFilterEnabled(bool enabled) {
-#if DEBUG_FOCUS
- ALOGD("setInputFilterEnabled: enabled=%d", enabled);
-#endif
-
- { // acquire lock
- AutoMutex _l(mLock);
-
- if (mInputFilterEnabled == enabled) {
- return;
- }
-
- mInputFilterEnabled = enabled;
- resetAndDropEverythingLocked("input filter is being enabled or disabled");
- } // release lock
-
- // Wake up poll loop since there might be work to do to drop everything.
- mLooper->wake();
-}
-
-bool InputDispatcher::transferTouchFocus(const sp<InputChannel>& fromChannel,
- const sp<InputChannel>& toChannel) {
-#if DEBUG_FOCUS
- ALOGD("transferTouchFocus: fromChannel=%s, toChannel=%s",
- fromChannel->getName().string(), toChannel->getName().string());
-#endif
- { // acquire lock
- AutoMutex _l(mLock);
-
- sp<InputWindowHandle> fromWindowHandle = getWindowHandleLocked(fromChannel);
- sp<InputWindowHandle> toWindowHandle = getWindowHandleLocked(toChannel);
- if (fromWindowHandle == NULL || toWindowHandle == NULL) {
-#if DEBUG_FOCUS
- ALOGD("Cannot transfer focus because from or to window not found.");
-#endif
- return false;
- }
- if (fromWindowHandle == toWindowHandle) {
-#if DEBUG_FOCUS
- ALOGD("Trivial transfer to same window.");
-#endif
- return true;
- }
- if (fromWindowHandle->getInfo()->displayId != toWindowHandle->getInfo()->displayId) {
-#if DEBUG_FOCUS
- ALOGD("Cannot transfer focus because windows are on different displays.");
-#endif
- return false;
- }
-
- bool found = false;
- for (size_t i = 0; i < mTouchState.windows.size(); i++) {
- const TouchedWindow& touchedWindow = mTouchState.windows[i];
- if (touchedWindow.windowHandle == fromWindowHandle) {
- int32_t oldTargetFlags = touchedWindow.targetFlags;
- BitSet32 pointerIds = touchedWindow.pointerIds;
-
- mTouchState.windows.removeAt(i);
-
- int32_t newTargetFlags = oldTargetFlags
- & (InputTarget::FLAG_FOREGROUND
- | InputTarget::FLAG_SPLIT | InputTarget::FLAG_DISPATCH_AS_IS);
- mTouchState.addOrUpdateWindow(toWindowHandle, newTargetFlags, pointerIds);
-
- found = true;
- break;
- }
- }
-
- if (! found) {
-#if DEBUG_FOCUS
- ALOGD("Focus transfer failed because from window did not have focus.");
-#endif
- return false;
- }
-
- ssize_t fromConnectionIndex = getConnectionIndexLocked(fromChannel);
- ssize_t toConnectionIndex = getConnectionIndexLocked(toChannel);
- if (fromConnectionIndex >= 0 && toConnectionIndex >= 0) {
- sp<Connection> fromConnection = mConnectionsByFd.valueAt(fromConnectionIndex);
- sp<Connection> toConnection = mConnectionsByFd.valueAt(toConnectionIndex);
-
- fromConnection->inputState.copyPointerStateTo(toConnection->inputState);
- CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
- "transferring touch focus from this window to another window");
- synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
- }
-
-#if DEBUG_FOCUS
- logDispatchStateLocked();
-#endif
- } // release lock
-
- // Wake up poll loop since it may need to make new input dispatching choices.
- mLooper->wake();
- return true;
-}
-
-void InputDispatcher::resetAndDropEverythingLocked(const char* reason) {
-#if DEBUG_FOCUS
- ALOGD("Resetting and dropping all events (%s).", reason);
-#endif
-
- CancelationOptions options(CancelationOptions::CANCEL_ALL_EVENTS, reason);
- synthesizeCancelationEventsForAllConnectionsLocked(options);
-
- resetKeyRepeatLocked();
- releasePendingEventLocked();
- drainInboundQueueLocked();
- resetANRTimeoutsLocked();
-
- mTouchState.reset();
- mLastHoverWindowHandle.clear();
-}
-
-void InputDispatcher::logDispatchStateLocked() {
- String8 dump;
- dumpDispatchStateLocked(dump);
-
- char* text = dump.lockBuffer(dump.size());
- char* start = text;
- while (*start != '\0') {
- char* end = strchr(start, '\n');
- if (*end == '\n') {
- *(end++) = '\0';
- }
- ALOGD("%s", start);
- start = end;
- }
-}
-
-void InputDispatcher::dumpDispatchStateLocked(String8& dump) {
- dump.appendFormat(INDENT "DispatchEnabled: %d\n", mDispatchEnabled);
- dump.appendFormat(INDENT "DispatchFrozen: %d\n", mDispatchFrozen);
-
- if (mFocusedApplicationHandle != NULL) {
- dump.appendFormat(INDENT "FocusedApplication: name='%s', dispatchingTimeout=%0.3fms\n",
- mFocusedApplicationHandle->getName().string(),
- mFocusedApplicationHandle->getDispatchingTimeout(
- DEFAULT_INPUT_DISPATCHING_TIMEOUT) / 1000000.0);
- } else {
- dump.append(INDENT "FocusedApplication: <null>\n");
- }
- dump.appendFormat(INDENT "FocusedWindow: name='%s'\n",
- mFocusedWindowHandle != NULL ? mFocusedWindowHandle->getName().string() : "<null>");
-
- dump.appendFormat(INDENT "TouchDown: %s\n", toString(mTouchState.down));
- dump.appendFormat(INDENT "TouchSplit: %s\n", toString(mTouchState.split));
- dump.appendFormat(INDENT "TouchDeviceId: %d\n", mTouchState.deviceId);
- dump.appendFormat(INDENT "TouchSource: 0x%08x\n", mTouchState.source);
- dump.appendFormat(INDENT "TouchDisplayId: %d\n", mTouchState.displayId);
- if (!mTouchState.windows.isEmpty()) {
- dump.append(INDENT "TouchedWindows:\n");
- for (size_t i = 0; i < mTouchState.windows.size(); i++) {
- const TouchedWindow& touchedWindow = mTouchState.windows[i];
- dump.appendFormat(INDENT2 "%d: name='%s', pointerIds=0x%0x, targetFlags=0x%x\n",
- i, touchedWindow.windowHandle->getName().string(),
- touchedWindow.pointerIds.value,
- touchedWindow.targetFlags);
- }
- } else {
- dump.append(INDENT "TouchedWindows: <none>\n");
- }
-
- if (!mWindowHandles.isEmpty()) {
- dump.append(INDENT "Windows:\n");
- for (size_t i = 0; i < mWindowHandles.size(); i++) {
- const sp<InputWindowHandle>& windowHandle = mWindowHandles.itemAt(i);
- const InputWindowInfo* windowInfo = windowHandle->getInfo();
-
- dump.appendFormat(INDENT2 "%d: name='%s', displayId=%d, "
- "paused=%s, hasFocus=%s, hasWallpaper=%s, "
- "visible=%s, canReceiveKeys=%s, flags=0x%08x, type=0x%08x, layer=%d, "
- "frame=[%d,%d][%d,%d], scale=%f, "
- "touchableRegion=",
- i, windowInfo->name.string(), windowInfo->displayId,
- toString(windowInfo->paused),
- toString(windowInfo->hasFocus),
- toString(windowInfo->hasWallpaper),
- toString(windowInfo->visible),
- toString(windowInfo->canReceiveKeys),
- windowInfo->layoutParamsFlags, windowInfo->layoutParamsType,
- windowInfo->layer,
- windowInfo->frameLeft, windowInfo->frameTop,
- windowInfo->frameRight, windowInfo->frameBottom,
- windowInfo->scaleFactor);
- dumpRegion(dump, windowInfo->touchableRegion);
- dump.appendFormat(", inputFeatures=0x%08x", windowInfo->inputFeatures);
- dump.appendFormat(", ownerPid=%d, ownerUid=%d, dispatchingTimeout=%0.3fms\n",
- windowInfo->ownerPid, windowInfo->ownerUid,
- windowInfo->dispatchingTimeout / 1000000.0);
- }
- } else {
- dump.append(INDENT "Windows: <none>\n");
- }
-
- if (!mMonitoringChannels.isEmpty()) {
- dump.append(INDENT "MonitoringChannels:\n");
- for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
- const sp<InputChannel>& channel = mMonitoringChannels[i];
- dump.appendFormat(INDENT2 "%d: '%s'\n", i, channel->getName().string());
- }
- } else {
- dump.append(INDENT "MonitoringChannels: <none>\n");
- }
-
- nsecs_t currentTime = now();
-
- if (!mInboundQueue.isEmpty()) {
- dump.appendFormat(INDENT "InboundQueue: length=%u\n", mInboundQueue.count());
- for (EventEntry* entry = mInboundQueue.head; entry; entry = entry->next) {
- dump.append(INDENT2);
- entry->appendDescription(dump);
- dump.appendFormat(", age=%0.1fms\n",
- (currentTime - entry->eventTime) * 0.000001f);
- }
- } else {
- dump.append(INDENT "InboundQueue: <empty>\n");
- }
-
- if (!mConnectionsByFd.isEmpty()) {
- dump.append(INDENT "Connections:\n");
- for (size_t i = 0; i < mConnectionsByFd.size(); i++) {
- const sp<Connection>& connection = mConnectionsByFd.valueAt(i);
- dump.appendFormat(INDENT2 "%d: channelName='%s', windowName='%s', "
- "status=%s, monitor=%s, inputPublisherBlocked=%s\n",
- i, connection->getInputChannelName(), connection->getWindowName(),
- connection->getStatusLabel(), toString(connection->monitor),
- toString(connection->inputPublisherBlocked));
-
- if (!connection->outboundQueue.isEmpty()) {
- dump.appendFormat(INDENT3 "OutboundQueue: length=%u\n",
- connection->outboundQueue.count());
- for (DispatchEntry* entry = connection->outboundQueue.head; entry;
- entry = entry->next) {
- dump.append(INDENT4);
- entry->eventEntry->appendDescription(dump);
- dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, age=%0.1fms\n",
- entry->targetFlags, entry->resolvedAction,
- (currentTime - entry->eventEntry->eventTime) * 0.000001f);
- }
- } else {
- dump.append(INDENT3 "OutboundQueue: <empty>\n");
- }
-
- if (!connection->waitQueue.isEmpty()) {
- dump.appendFormat(INDENT3 "WaitQueue: length=%u\n",
- connection->waitQueue.count());
- for (DispatchEntry* entry = connection->waitQueue.head; entry;
- entry = entry->next) {
- dump.append(INDENT4);
- entry->eventEntry->appendDescription(dump);
- dump.appendFormat(", targetFlags=0x%08x, resolvedAction=%d, "
- "age=%0.1fms, wait=%0.1fms\n",
- entry->targetFlags, entry->resolvedAction,
- (currentTime - entry->eventEntry->eventTime) * 0.000001f,
- (currentTime - entry->deliveryTime) * 0.000001f);
- }
- } else {
- dump.append(INDENT3 "WaitQueue: <empty>\n");
- }
- }
- } else {
- dump.append(INDENT "Connections: <none>\n");
- }
-
- if (isAppSwitchPendingLocked()) {
- dump.appendFormat(INDENT "AppSwitch: pending, due in %0.1fms\n",
- (mAppSwitchDueTime - now()) / 1000000.0);
- } else {
- dump.append(INDENT "AppSwitch: not pending\n");
- }
-
- dump.append(INDENT "Configuration:\n");
- dump.appendFormat(INDENT2 "KeyRepeatDelay: %0.1fms\n",
- mConfig.keyRepeatDelay * 0.000001f);
- dump.appendFormat(INDENT2 "KeyRepeatTimeout: %0.1fms\n",
- mConfig.keyRepeatTimeout * 0.000001f);
-}
-
-status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
- const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
-#if DEBUG_REGISTRATION
- ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
- toString(monitor));
-#endif
-
- { // acquire lock
- AutoMutex _l(mLock);
-
- if (getConnectionIndexLocked(inputChannel) >= 0) {
- ALOGW("Attempted to register already registered input channel '%s'",
- inputChannel->getName().string());
- return BAD_VALUE;
- }
-
- sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);
-
- int fd = inputChannel->getFd();
- mConnectionsByFd.add(fd, connection);
-
- if (monitor) {
- mMonitoringChannels.push(inputChannel);
- }
-
- mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
- } // release lock
-
- // Wake the looper because some connections have changed.
- mLooper->wake();
- return OK;
-}
-
-status_t InputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel) {
-#if DEBUG_REGISTRATION
- ALOGD("channel '%s' ~ unregisterInputChannel", inputChannel->getName().string());
-#endif
-
- { // acquire lock
- AutoMutex _l(mLock);
-
- status_t status = unregisterInputChannelLocked(inputChannel, false /*notify*/);
- if (status) {
- return status;
- }
- } // release lock
-
- // Wake the poll loop because removing the connection may have changed the current
- // synchronization state.
- mLooper->wake();
- return OK;
-}
-
-status_t InputDispatcher::unregisterInputChannelLocked(const sp<InputChannel>& inputChannel,
- bool notify) {
- ssize_t connectionIndex = getConnectionIndexLocked(inputChannel);
- if (connectionIndex < 0) {
- ALOGW("Attempted to unregister already unregistered input channel '%s'",
- inputChannel->getName().string());
- return BAD_VALUE;
- }
-
- sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
- mConnectionsByFd.removeItemsAt(connectionIndex);
-
- if (connection->monitor) {
- removeMonitorChannelLocked(inputChannel);
- }
-
- mLooper->removeFd(inputChannel->getFd());
-
- nsecs_t currentTime = now();
- abortBrokenDispatchCycleLocked(currentTime, connection, notify);
-
- connection->status = Connection::STATUS_ZOMBIE;
- return OK;
-}
-
-void InputDispatcher::removeMonitorChannelLocked(const sp<InputChannel>& inputChannel) {
- for (size_t i = 0; i < mMonitoringChannels.size(); i++) {
- if (mMonitoringChannels[i] == inputChannel) {
- mMonitoringChannels.removeAt(i);
- break;
- }
- }
-}
-
-ssize_t InputDispatcher::getConnectionIndexLocked(const sp<InputChannel>& inputChannel) {
- ssize_t connectionIndex = mConnectionsByFd.indexOfKey(inputChannel->getFd());
- if (connectionIndex >= 0) {
- sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);
- if (connection->inputChannel.get() == inputChannel.get()) {
- return connectionIndex;
- }
- }
-
- return -1;
-}
-
-void InputDispatcher::onDispatchCycleFinishedLocked(
- nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {
- CommandEntry* commandEntry = postCommandLocked(
- & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);
- commandEntry->connection = connection;
- commandEntry->eventTime = currentTime;
- commandEntry->seq = seq;
- commandEntry->handled = handled;
-}
-
-void InputDispatcher::onDispatchCycleBrokenLocked(
- nsecs_t currentTime, const sp<Connection>& connection) {
- ALOGE("channel '%s' ~ Channel is unrecoverably broken and will be disposed!",
- connection->getInputChannelName());
-
- CommandEntry* commandEntry = postCommandLocked(
- & InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible);
- commandEntry->connection = connection;
-}
-
-void InputDispatcher::onANRLocked(
- nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
- const sp<InputWindowHandle>& windowHandle,
- nsecs_t eventTime, nsecs_t waitStartTime, const char* reason) {
- float dispatchLatency = (currentTime - eventTime) * 0.000001f;
- float waitDuration = (currentTime - waitStartTime) * 0.000001f;
- ALOGI("Application is not responding: %s. "
- "It has been %0.1fms since event, %0.1fms since wait started. Reason: %s",
- getApplicationWindowLabelLocked(applicationHandle, windowHandle).string(),
- dispatchLatency, waitDuration, reason);
-
- // Capture a record of the InputDispatcher state at the time of the ANR.
- time_t t = time(NULL);
- struct tm tm;
- localtime_r(&t, &tm);
- char timestr[64];
- strftime(timestr, sizeof(timestr), "%F %T", &tm);
- mLastANRState.clear();
- mLastANRState.append(INDENT "ANR:\n");
- mLastANRState.appendFormat(INDENT2 "Time: %s\n", timestr);
- mLastANRState.appendFormat(INDENT2 "Window: %s\n",
- getApplicationWindowLabelLocked(applicationHandle, windowHandle).string());
- mLastANRState.appendFormat(INDENT2 "DispatchLatency: %0.1fms\n", dispatchLatency);
- mLastANRState.appendFormat(INDENT2 "WaitDuration: %0.1fms\n", waitDuration);
- mLastANRState.appendFormat(INDENT2 "Reason: %s\n", reason);
- dumpDispatchStateLocked(mLastANRState);
-
- CommandEntry* commandEntry = postCommandLocked(
- & InputDispatcher::doNotifyANRLockedInterruptible);
- commandEntry->inputApplicationHandle = applicationHandle;
- commandEntry->inputWindowHandle = windowHandle;
-}
-
-void InputDispatcher::doNotifyConfigurationChangedInterruptible(
- CommandEntry* commandEntry) {
- mLock.unlock();
-
- mPolicy->notifyConfigurationChanged(commandEntry->eventTime);
-
- mLock.lock();
-}
-
-void InputDispatcher::doNotifyInputChannelBrokenLockedInterruptible(
- CommandEntry* commandEntry) {
- sp<Connection> connection = commandEntry->connection;
-
- if (connection->status != Connection::STATUS_ZOMBIE) {
- mLock.unlock();
-
- mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
-
- mLock.lock();
- }
-}
-
-void InputDispatcher::doNotifyANRLockedInterruptible(
- CommandEntry* commandEntry) {
- mLock.unlock();
-
- nsecs_t newTimeout = mPolicy->notifyANR(
- commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
-
- mLock.lock();
-
- resumeAfterTargetsNotReadyTimeoutLocked(newTimeout,
- commandEntry->inputWindowHandle != NULL
- ? commandEntry->inputWindowHandle->getInputChannel() : NULL);
-}
-
-void InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible(
- CommandEntry* commandEntry) {
- KeyEntry* entry = commandEntry->keyEntry;
-
- KeyEvent event;
- initializeKeyEvent(&event, entry);
-
- mLock.unlock();
-
- nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
- &event, entry->policyFlags);
-
- mLock.lock();
-
- if (delay < 0) {
- entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_SKIP;
- } else if (!delay) {
- entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;
- } else {
- entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER;
- entry->interceptKeyWakeupTime = now() + delay;
- }
- entry->release();
-}
-
-void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(
- CommandEntry* commandEntry) {
- sp<Connection> connection = commandEntry->connection;
- nsecs_t finishTime = commandEntry->eventTime;
- uint32_t seq = commandEntry->seq;
- bool handled = commandEntry->handled;
-
- // Handle post-event policy actions.
- DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);
- if (dispatchEntry) {
- nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;
- if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {
- String8 msg;
- msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",
- connection->getWindowName(), eventDuration * 0.000001f);
- dispatchEntry->eventEntry->appendDescription(msg);
- ALOGI("%s", msg.string());
- }
-
- bool restartEvent;
- if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {
- KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);
- restartEvent = afterKeyEventLockedInterruptible(connection,
- dispatchEntry, keyEntry, handled);
- } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {
- MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);
- restartEvent = afterMotionEventLockedInterruptible(connection,
- dispatchEntry, motionEntry, handled);
- } else {
- restartEvent = false;
- }
-
- // Dequeue the event and start the next cycle.
- // Note that because the lock might have been released, it is possible that the
- // contents of the wait queue to have been drained, so we need to double-check
- // a few things.
- if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
- connection->waitQueue.dequeue(dispatchEntry);
- traceWaitQueueLengthLocked(connection);
- if (restartEvent && connection->status == Connection::STATUS_NORMAL) {
- connection->outboundQueue.enqueueAtHead(dispatchEntry);
- traceOutboundQueueLengthLocked(connection);
- } else {
- releaseDispatchEntryLocked(dispatchEntry);
- }
- }
-
- // Start the next dispatch cycle for this connection.
- startDispatchCycleLocked(now(), connection);
- }
-}
-
-bool InputDispatcher::afterKeyEventLockedInterruptible(const sp<Connection>& connection,
- DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled) {
- if (!(keyEntry->flags & AKEY_EVENT_FLAG_FALLBACK)) {
- // Get the fallback key state.
- // Clear it out after dispatching the UP.
- int32_t originalKeyCode = keyEntry->keyCode;
- int32_t fallbackKeyCode = connection->inputState.getFallbackKey(originalKeyCode);
- if (keyEntry->action == AKEY_EVENT_ACTION_UP) {
- connection->inputState.removeFallbackKey(originalKeyCode);
- }
-
- if (handled || !dispatchEntry->hasForegroundTarget()) {
- // If the application handles the original key for which we previously
- // generated a fallback or if the window is not a foreground window,
- // then cancel the associated fallback key, if any.
- if (fallbackKeyCode != -1) {
- // Dispatch the unhandled key to the policy with the cancel flag.
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Unhandled key event: Asking policy to cancel fallback action. "
- "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
- keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
- keyEntry->policyFlags);
-#endif
- KeyEvent event;
- initializeKeyEvent(&event, keyEntry);
- event.setFlags(event.getFlags() | AKEY_EVENT_FLAG_CANCELED);
-
- mLock.unlock();
-
- mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
- &event, keyEntry->policyFlags, &event);
-
- mLock.lock();
-
- // Cancel the fallback key.
- if (fallbackKeyCode != AKEYCODE_UNKNOWN) {
- CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
- "application handled the original non-fallback key "
- "or is no longer a foreground target, "
- "canceling previously dispatched fallback key");
- options.keyCode = fallbackKeyCode;
- synthesizeCancelationEventsForConnectionLocked(connection, options);
- }
- connection->inputState.removeFallbackKey(originalKeyCode);
- }
- } else {
- // If the application did not handle a non-fallback key, first check
- // that we are in a good state to perform unhandled key event processing
- // Then ask the policy what to do with it.
- bool initialDown = keyEntry->action == AKEY_EVENT_ACTION_DOWN
- && keyEntry->repeatCount == 0;
- if (fallbackKeyCode == -1 && !initialDown) {
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Unhandled key event: Skipping unhandled key event processing "
- "since this is not an initial down. "
- "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
- originalKeyCode, keyEntry->action, keyEntry->repeatCount,
- keyEntry->policyFlags);
-#endif
- return false;
- }
-
- // Dispatch the unhandled key to the policy.
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Unhandled key event: Asking policy to perform fallback action. "
- "keyCode=%d, action=%d, repeatCount=%d, policyFlags=0x%08x",
- keyEntry->keyCode, keyEntry->action, keyEntry->repeatCount,
- keyEntry->policyFlags);
-#endif
- KeyEvent event;
- initializeKeyEvent(&event, keyEntry);
-
- mLock.unlock();
-
- bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
- &event, keyEntry->policyFlags, &event);
-
- mLock.lock();
-
- if (connection->status != Connection::STATUS_NORMAL) {
- connection->inputState.removeFallbackKey(originalKeyCode);
- return false;
- }
-
- // Latch the fallback keycode for this key on an initial down.
- // The fallback keycode cannot change at any other point in the lifecycle.
- if (initialDown) {
- if (fallback) {
- fallbackKeyCode = event.getKeyCode();
- } else {
- fallbackKeyCode = AKEYCODE_UNKNOWN;
- }
- connection->inputState.setFallbackKey(originalKeyCode, fallbackKeyCode);
- }
-
- ALOG_ASSERT(fallbackKeyCode != -1);
-
- // Cancel the fallback key if the policy decides not to send it anymore.
- // We will continue to dispatch the key to the policy but we will no
- // longer dispatch a fallback key to the application.
- if (fallbackKeyCode != AKEYCODE_UNKNOWN
- && (!fallback || fallbackKeyCode != event.getKeyCode())) {
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- if (fallback) {
- ALOGD("Unhandled key event: Policy requested to send key %d"
- "as a fallback for %d, but on the DOWN it had requested "
- "to send %d instead. Fallback canceled.",
- event.getKeyCode(), originalKeyCode, fallbackKeyCode);
- } else {
- ALOGD("Unhandled key event: Policy did not request fallback for %d, "
- "but on the DOWN it had requested to send %d. "
- "Fallback canceled.",
- originalKeyCode, fallbackKeyCode);
- }
-#endif
-
- CancelationOptions options(CancelationOptions::CANCEL_FALLBACK_EVENTS,
- "canceling fallback, policy no longer desires it");
- options.keyCode = fallbackKeyCode;
- synthesizeCancelationEventsForConnectionLocked(connection, options);
-
- fallback = false;
- fallbackKeyCode = AKEYCODE_UNKNOWN;
- if (keyEntry->action != AKEY_EVENT_ACTION_UP) {
- connection->inputState.setFallbackKey(originalKeyCode,
- fallbackKeyCode);
- }
- }
-
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- {
- String8 msg;
- const KeyedVector<int32_t, int32_t>& fallbackKeys =
- connection->inputState.getFallbackKeys();
- for (size_t i = 0; i < fallbackKeys.size(); i++) {
- msg.appendFormat(", %d->%d", fallbackKeys.keyAt(i),
- fallbackKeys.valueAt(i));
- }
- ALOGD("Unhandled key event: %d currently tracked fallback keys%s.",
- fallbackKeys.size(), msg.string());
- }
-#endif
-
- if (fallback) {
- // Restart the dispatch cycle using the fallback key.
- keyEntry->eventTime = event.getEventTime();
- keyEntry->deviceId = event.getDeviceId();
- keyEntry->source = event.getSource();
- keyEntry->flags = event.getFlags() | AKEY_EVENT_FLAG_FALLBACK;
- keyEntry->keyCode = fallbackKeyCode;
- keyEntry->scanCode = event.getScanCode();
- keyEntry->metaState = event.getMetaState();
- keyEntry->repeatCount = event.getRepeatCount();
- keyEntry->downTime = event.getDownTime();
- keyEntry->syntheticRepeat = false;
-
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Unhandled key event: Dispatching fallback key. "
- "originalKeyCode=%d, fallbackKeyCode=%d, fallbackMetaState=%08x",
- originalKeyCode, fallbackKeyCode, keyEntry->metaState);
-#endif
- return true; // restart the event
- } else {
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Unhandled key event: No fallback key.");
-#endif
- }
- }
- }
- return false;
-}
-
-bool InputDispatcher::afterMotionEventLockedInterruptible(const sp<Connection>& connection,
- DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled) {
- return false;
-}
-
-void InputDispatcher::doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry) {
- mLock.unlock();
-
- mPolicy->pokeUserActivity(commandEntry->eventTime, commandEntry->userActivityEventType);
-
- mLock.lock();
-}
-
-void InputDispatcher::initializeKeyEvent(KeyEvent* event, const KeyEntry* entry) {
- event->initialize(entry->deviceId, entry->source, entry->action, entry->flags,
- entry->keyCode, entry->scanCode, entry->metaState, entry->repeatCount,
- entry->downTime, entry->eventTime);
-}
-
-void InputDispatcher::updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
- int32_t injectionResult, nsecs_t timeSpentWaitingForApplication) {
- // TODO Write some statistics about how long we spend waiting.
-}
-
-void InputDispatcher::traceInboundQueueLengthLocked() {
-#ifdef HAVE_ANDROID_OS
- if (ATRACE_ENABLED()) {
- ATRACE_INT("iq", mInboundQueue.count());
- }
-#endif
-}
-
-void InputDispatcher::traceOutboundQueueLengthLocked(const sp<Connection>& connection) {
-#ifdef HAVE_ANDROID_OS
- if (ATRACE_ENABLED()) {
- char counterName[40];
- snprintf(counterName, sizeof(counterName), "oq:%s", connection->getWindowName());
- ATRACE_INT(counterName, connection->outboundQueue.count());
- }
-#endif
-}
-
-void InputDispatcher::traceWaitQueueLengthLocked(const sp<Connection>& connection) {
-#ifdef HAVE_ANDROID_OS
- if (ATRACE_ENABLED()) {
- char counterName[40];
- snprintf(counterName, sizeof(counterName), "wq:%s", connection->getWindowName());
- ATRACE_INT(counterName, connection->waitQueue.count());
- }
-#endif
-}
-
-void InputDispatcher::dump(String8& dump) {
- AutoMutex _l(mLock);
-
- dump.append("Input Dispatcher State:\n");
- dumpDispatchStateLocked(dump);
-
- if (!mLastANRState.isEmpty()) {
- dump.append("\nInput Dispatcher State at time of last ANR:\n");
- dump.append(mLastANRState);
- }
-}
-
-void InputDispatcher::monitor() {
- // Acquire and release the lock to ensure that the dispatcher has not deadlocked.
- mLock.lock();
- mLooper->wake();
- mDispatcherIsAliveCondition.wait(mLock);
- mLock.unlock();
-}
-
-
-// --- InputDispatcher::Queue ---
-
-template <typename T>
-uint32_t InputDispatcher::Queue<T>::count() const {
- uint32_t result = 0;
- for (const T* entry = head; entry; entry = entry->next) {
- result += 1;
- }
- return result;
-}
-
-
-// --- InputDispatcher::InjectionState ---
-
-InputDispatcher::InjectionState::InjectionState(int32_t injectorPid, int32_t injectorUid) :
- refCount(1),
- injectorPid(injectorPid), injectorUid(injectorUid),
- injectionResult(INPUT_EVENT_INJECTION_PENDING), injectionIsAsync(false),
- pendingForegroundDispatches(0) {
-}
-
-InputDispatcher::InjectionState::~InjectionState() {
-}
-
-void InputDispatcher::InjectionState::release() {
- refCount -= 1;
- if (refCount == 0) {
- delete this;
- } else {
- ALOG_ASSERT(refCount > 0);
- }
-}
-
-
-// --- InputDispatcher::EventEntry ---
-
-InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
- refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
- injectionState(NULL), dispatchInProgress(false) {
-}
-
-InputDispatcher::EventEntry::~EventEntry() {
- releaseInjectionState();
-}
-
-void InputDispatcher::EventEntry::release() {
- refCount -= 1;
- if (refCount == 0) {
- delete this;
- } else {
- ALOG_ASSERT(refCount > 0);
- }
-}
-
-void InputDispatcher::EventEntry::releaseInjectionState() {
- if (injectionState) {
- injectionState->release();
- injectionState = NULL;
- }
-}
-
-
-// --- InputDispatcher::ConfigurationChangedEntry ---
-
-InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
- EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
-}
-
-InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
-}
-
-void InputDispatcher::ConfigurationChangedEntry::appendDescription(String8& msg) const {
- msg.append("ConfigurationChangedEvent()");
-}
-
-
-// --- InputDispatcher::DeviceResetEntry ---
-
-InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
- EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
- deviceId(deviceId) {
-}
-
-InputDispatcher::DeviceResetEntry::~DeviceResetEntry() {
-}
-
-void InputDispatcher::DeviceResetEntry::appendDescription(String8& msg) const {
- msg.appendFormat("DeviceResetEvent(deviceId=%d)", deviceId);
-}
-
-
-// --- InputDispatcher::KeyEntry ---
-
-InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
- int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
- int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
- int32_t repeatCount, nsecs_t downTime) :
- EventEntry(TYPE_KEY, eventTime, policyFlags),
- deviceId(deviceId), source(source), action(action), flags(flags),
- keyCode(keyCode), scanCode(scanCode), metaState(metaState),
- repeatCount(repeatCount), downTime(downTime),
- syntheticRepeat(false), interceptKeyResult(KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN),
- interceptKeyWakeupTime(0) {
-}
-
-InputDispatcher::KeyEntry::~KeyEntry() {
-}
-
-void InputDispatcher::KeyEntry::appendDescription(String8& msg) const {
- msg.appendFormat("KeyEvent(action=%d, deviceId=%d, source=0x%08x)",
- action, deviceId, source);
-}
-
-void InputDispatcher::KeyEntry::recycle() {
- releaseInjectionState();
-
- dispatchInProgress = false;
- syntheticRepeat = false;
- interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;
- interceptKeyWakeupTime = 0;
-}
-
-
-// --- InputDispatcher::MotionEntry ---
-
-InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime,
- int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action, int32_t flags,
- int32_t metaState, int32_t buttonState,
- int32_t edgeFlags, float xPrecision, float yPrecision,
- nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
- const PointerProperties* pointerProperties, const PointerCoords* pointerCoords) :
- EventEntry(TYPE_MOTION, eventTime, policyFlags),
- eventTime(eventTime),
- deviceId(deviceId), source(source), action(action), flags(flags),
- metaState(metaState), buttonState(buttonState), edgeFlags(edgeFlags),
- xPrecision(xPrecision), yPrecision(yPrecision),
- downTime(downTime), displayId(displayId), pointerCount(pointerCount) {
- for (uint32_t i = 0; i < pointerCount; i++) {
- this->pointerProperties[i].copyFrom(pointerProperties[i]);
- this->pointerCoords[i].copyFrom(pointerCoords[i]);
- }
-}
-
-InputDispatcher::MotionEntry::~MotionEntry() {
-}
-
-void InputDispatcher::MotionEntry::appendDescription(String8& msg) const {
- msg.appendFormat("MotionEvent(action=%d, deviceId=%d, source=0x%08x, displayId=%d)",
- action, deviceId, source, displayId);
-}
-
-
-// --- InputDispatcher::DispatchEntry ---
-
-volatile int32_t InputDispatcher::DispatchEntry::sNextSeqAtomic;
-
-InputDispatcher::DispatchEntry::DispatchEntry(EventEntry* eventEntry,
- int32_t targetFlags, float xOffset, float yOffset, float scaleFactor) :
- seq(nextSeq()),
- eventEntry(eventEntry), targetFlags(targetFlags),
- xOffset(xOffset), yOffset(yOffset), scaleFactor(scaleFactor),
- deliveryTime(0), resolvedAction(0), resolvedFlags(0) {
- eventEntry->refCount += 1;
-}
-
-InputDispatcher::DispatchEntry::~DispatchEntry() {
- eventEntry->release();
-}
-
-uint32_t InputDispatcher::DispatchEntry::nextSeq() {
- // Sequence number 0 is reserved and will never be returned.
- uint32_t seq;
- do {
- seq = android_atomic_inc(&sNextSeqAtomic);
- } while (!seq);
- return seq;
-}
-
-
-// --- InputDispatcher::InputState ---
-
-InputDispatcher::InputState::InputState() {
-}
-
-InputDispatcher::InputState::~InputState() {
-}
-
-bool InputDispatcher::InputState::isNeutral() const {
- return mKeyMementos.isEmpty() && mMotionMementos.isEmpty();
-}
-
-bool InputDispatcher::InputState::isHovering(int32_t deviceId, uint32_t source,
- int32_t displayId) const {
- for (size_t i = 0; i < mMotionMementos.size(); i++) {
- const MotionMemento& memento = mMotionMementos.itemAt(i);
- if (memento.deviceId == deviceId
- && memento.source == source
- && memento.displayId == displayId
- && memento.hovering) {
- return true;
- }
- }
- return false;
-}
-
-bool InputDispatcher::InputState::trackKey(const KeyEntry* entry,
- int32_t action, int32_t flags) {
- switch (action) {
- case AKEY_EVENT_ACTION_UP: {
- if (entry->flags & AKEY_EVENT_FLAG_FALLBACK) {
- for (size_t i = 0; i < mFallbackKeys.size(); ) {
- if (mFallbackKeys.valueAt(i) == entry->keyCode) {
- mFallbackKeys.removeItemsAt(i);
- } else {
- i += 1;
- }
- }
- }
- ssize_t index = findKeyMemento(entry);
- if (index >= 0) {
- mKeyMementos.removeAt(index);
- return true;
- }
- /* FIXME: We can't just drop the key up event because that prevents creating
- * popup windows that are automatically shown when a key is held and then
- * dismissed when the key is released. The problem is that the popup will
- * not have received the original key down, so the key up will be considered
- * to be inconsistent with its observed state. We could perhaps handle this
- * by synthesizing a key down but that will cause other problems.
- *
- * So for now, allow inconsistent key up events to be dispatched.
- *
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Dropping inconsistent key up event: deviceId=%d, source=%08x, "
- "keyCode=%d, scanCode=%d",
- entry->deviceId, entry->source, entry->keyCode, entry->scanCode);
-#endif
- return false;
- */
- return true;
- }
-
- case AKEY_EVENT_ACTION_DOWN: {
- ssize_t index = findKeyMemento(entry);
- if (index >= 0) {
- mKeyMementos.removeAt(index);
- }
- addKeyMemento(entry, flags);
- return true;
- }
-
- default:
- return true;
- }
-}
-
-bool InputDispatcher::InputState::trackMotion(const MotionEntry* entry,
- int32_t action, int32_t flags) {
- int32_t actionMasked = action & AMOTION_EVENT_ACTION_MASK;
- switch (actionMasked) {
- case AMOTION_EVENT_ACTION_UP:
- case AMOTION_EVENT_ACTION_CANCEL: {
- ssize_t index = findMotionMemento(entry, false /*hovering*/);
- if (index >= 0) {
- mMotionMementos.removeAt(index);
- return true;
- }
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Dropping inconsistent motion up or cancel event: deviceId=%d, source=%08x, "
- "actionMasked=%d",
- entry->deviceId, entry->source, actionMasked);
-#endif
- return false;
- }
-
- case AMOTION_EVENT_ACTION_DOWN: {
- ssize_t index = findMotionMemento(entry, false /*hovering*/);
- if (index >= 0) {
- mMotionMementos.removeAt(index);
- }
- addMotionMemento(entry, flags, false /*hovering*/);
- return true;
- }
-
- case AMOTION_EVENT_ACTION_POINTER_UP:
- case AMOTION_EVENT_ACTION_POINTER_DOWN:
- case AMOTION_EVENT_ACTION_MOVE: {
- ssize_t index = findMotionMemento(entry, false /*hovering*/);
- if (index >= 0) {
- MotionMemento& memento = mMotionMementos.editItemAt(index);
- memento.setPointers(entry);
- return true;
- }
- if (actionMasked == AMOTION_EVENT_ACTION_MOVE
- && (entry->source & (AINPUT_SOURCE_CLASS_JOYSTICK
- | AINPUT_SOURCE_CLASS_NAVIGATION))) {
- // Joysticks and trackballs can send MOVE events without corresponding DOWN or UP.
- return true;
- }
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Dropping inconsistent motion pointer up/down or move event: "
- "deviceId=%d, source=%08x, actionMasked=%d",
- entry->deviceId, entry->source, actionMasked);
-#endif
- return false;
- }
-
- case AMOTION_EVENT_ACTION_HOVER_EXIT: {
- ssize_t index = findMotionMemento(entry, true /*hovering*/);
- if (index >= 0) {
- mMotionMementos.removeAt(index);
- return true;
- }
-#if DEBUG_OUTBOUND_EVENT_DETAILS
- ALOGD("Dropping inconsistent motion hover exit event: deviceId=%d, source=%08x",
- entry->deviceId, entry->source);
-#endif
- return false;
- }
-
- case AMOTION_EVENT_ACTION_HOVER_ENTER:
- case AMOTION_EVENT_ACTION_HOVER_MOVE: {
- ssize_t index = findMotionMemento(entry, true /*hovering*/);
- if (index >= 0) {
- mMotionMementos.removeAt(index);
- }
- addMotionMemento(entry, flags, true /*hovering*/);
- return true;
- }
-
- default:
- return true;
- }
-}
-
-ssize_t InputDispatcher::InputState::findKeyMemento(const KeyEntry* entry) const {
- for (size_t i = 0; i < mKeyMementos.size(); i++) {
- const KeyMemento& memento = mKeyMementos.itemAt(i);
- if (memento.deviceId == entry->deviceId
- && memento.source == entry->source
- && memento.keyCode == entry->keyCode
- && memento.scanCode == entry->scanCode) {
- return i;
- }
- }
- return -1;
-}
-
-ssize_t InputDispatcher::InputState::findMotionMemento(const MotionEntry* entry,
- bool hovering) const {
- for (size_t i = 0; i < mMotionMementos.size(); i++) {
- const MotionMemento& memento = mMotionMementos.itemAt(i);
- if (memento.deviceId == entry->deviceId
- && memento.source == entry->source
- && memento.displayId == entry->displayId
- && memento.hovering == hovering) {
- return i;
- }
- }
- return -1;
-}
-
-void InputDispatcher::InputState::addKeyMemento(const KeyEntry* entry, int32_t flags) {
- mKeyMementos.push();
- KeyMemento& memento = mKeyMementos.editTop();
- memento.deviceId = entry->deviceId;
- memento.source = entry->source;
- memento.keyCode = entry->keyCode;
- memento.scanCode = entry->scanCode;
- memento.metaState = entry->metaState;
- memento.flags = flags;
- memento.downTime = entry->downTime;
- memento.policyFlags = entry->policyFlags;
-}
-
-void InputDispatcher::InputState::addMotionMemento(const MotionEntry* entry,
- int32_t flags, bool hovering) {
- mMotionMementos.push();
- MotionMemento& memento = mMotionMementos.editTop();
- memento.deviceId = entry->deviceId;
- memento.source = entry->source;
- memento.flags = flags;
- memento.xPrecision = entry->xPrecision;
- memento.yPrecision = entry->yPrecision;
- memento.downTime = entry->downTime;
- memento.displayId = entry->displayId;
- memento.setPointers(entry);
- memento.hovering = hovering;
- memento.policyFlags = entry->policyFlags;
-}
-
-void InputDispatcher::InputState::MotionMemento::setPointers(const MotionEntry* entry) {
- pointerCount = entry->pointerCount;
- for (uint32_t i = 0; i < entry->pointerCount; i++) {
- pointerProperties[i].copyFrom(entry->pointerProperties[i]);
- pointerCoords[i].copyFrom(entry->pointerCoords[i]);
- }
-}
-
-void InputDispatcher::InputState::synthesizeCancelationEvents(nsecs_t currentTime,
- Vector<EventEntry*>& outEvents, const CancelationOptions& options) {
- for (size_t i = 0; i < mKeyMementos.size(); i++) {
- const KeyMemento& memento = mKeyMementos.itemAt(i);
- if (shouldCancelKey(memento, options)) {
- outEvents.push(new KeyEntry(currentTime,
- memento.deviceId, memento.source, memento.policyFlags,
- AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
- memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
- }
- }
-
- for (size_t i = 0; i < mMotionMementos.size(); i++) {
- const MotionMemento& memento = mMotionMementos.itemAt(i);
- if (shouldCancelMotion(memento, options)) {
- outEvents.push(new MotionEntry(currentTime,
- memento.deviceId, memento.source, memento.policyFlags,
- memento.hovering
- ? AMOTION_EVENT_ACTION_HOVER_EXIT
- : AMOTION_EVENT_ACTION_CANCEL,
- memento.flags, 0, 0, 0,
- memento.xPrecision, memento.yPrecision, memento.downTime,
- memento.displayId,
- memento.pointerCount, memento.pointerProperties, memento.pointerCoords));
- }
- }
-}
-
-void InputDispatcher::InputState::clear() {
- mKeyMementos.clear();
- mMotionMementos.clear();
- mFallbackKeys.clear();
-}
-
-void InputDispatcher::InputState::copyPointerStateTo(InputState& other) const {
- for (size_t i = 0; i < mMotionMementos.size(); i++) {
- const MotionMemento& memento = mMotionMementos.itemAt(i);
- if (memento.source & AINPUT_SOURCE_CLASS_POINTER) {
- for (size_t j = 0; j < other.mMotionMementos.size(); ) {
- const MotionMemento& otherMemento = other.mMotionMementos.itemAt(j);
- if (memento.deviceId == otherMemento.deviceId
- && memento.source == otherMemento.source
- && memento.displayId == otherMemento.displayId) {
- other.mMotionMementos.removeAt(j);
- } else {
- j += 1;
- }
- }
- other.mMotionMementos.push(memento);
- }
- }
-}
-
-int32_t InputDispatcher::InputState::getFallbackKey(int32_t originalKeyCode) {
- ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
- return index >= 0 ? mFallbackKeys.valueAt(index) : -1;
-}
-
-void InputDispatcher::InputState::setFallbackKey(int32_t originalKeyCode,
- int32_t fallbackKeyCode) {
- ssize_t index = mFallbackKeys.indexOfKey(originalKeyCode);
- if (index >= 0) {
- mFallbackKeys.replaceValueAt(index, fallbackKeyCode);
- } else {
- mFallbackKeys.add(originalKeyCode, fallbackKeyCode);
- }
-}
-
-void InputDispatcher::InputState::removeFallbackKey(int32_t originalKeyCode) {
- mFallbackKeys.removeItem(originalKeyCode);
-}
-
-bool InputDispatcher::InputState::shouldCancelKey(const KeyMemento& memento,
- const CancelationOptions& options) {
- if (options.keyCode != -1 && memento.keyCode != options.keyCode) {
- return false;
- }
-
- if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
- return false;
- }
-
- switch (options.mode) {
- case CancelationOptions::CANCEL_ALL_EVENTS:
- case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
- return true;
- case CancelationOptions::CANCEL_FALLBACK_EVENTS:
- return memento.flags & AKEY_EVENT_FLAG_FALLBACK;
- default:
- return false;
- }
-}
-
-bool InputDispatcher::InputState::shouldCancelMotion(const MotionMemento& memento,
- const CancelationOptions& options) {
- if (options.deviceId != -1 && memento.deviceId != options.deviceId) {
- return false;
- }
-
- switch (options.mode) {
- case CancelationOptions::CANCEL_ALL_EVENTS:
- return true;
- case CancelationOptions::CANCEL_POINTER_EVENTS:
- return memento.source & AINPUT_SOURCE_CLASS_POINTER;
- case CancelationOptions::CANCEL_NON_POINTER_EVENTS:
- return !(memento.source & AINPUT_SOURCE_CLASS_POINTER);
- default:
- return false;
- }
-}
-
-
-// --- InputDispatcher::Connection ---
-
-InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
- const sp<InputWindowHandle>& inputWindowHandle, bool monitor) :
- status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
- monitor(monitor),
- inputPublisher(inputChannel), inputPublisherBlocked(false) {
-}
-
-InputDispatcher::Connection::~Connection() {
-}
-
-const char* InputDispatcher::Connection::getWindowName() const {
- if (inputWindowHandle != NULL) {
- return inputWindowHandle->getName().string();
- }
- if (monitor) {
- return "monitor";
- }
- return "?";
-}
-
-const char* InputDispatcher::Connection::getStatusLabel() const {
- switch (status) {
- case STATUS_NORMAL:
- return "NORMAL";
-
- case STATUS_BROKEN:
- return "BROKEN";
-
- case STATUS_ZOMBIE:
- return "ZOMBIE";
-
- default:
- return "UNKNOWN";
- }
-}
-
-InputDispatcher::DispatchEntry* InputDispatcher::Connection::findWaitQueueEntry(uint32_t seq) {
- for (DispatchEntry* entry = waitQueue.head; entry != NULL; entry = entry->next) {
- if (entry->seq == seq) {
- return entry;
- }
- }
- return NULL;
-}
-
-
-// --- InputDispatcher::CommandEntry ---
-
-InputDispatcher::CommandEntry::CommandEntry(Command command) :
- command(command), eventTime(0), keyEntry(NULL), userActivityEventType(0),
- seq(0), handled(false) {
-}
-
-InputDispatcher::CommandEntry::~CommandEntry() {
-}
-
-
-// --- InputDispatcher::TouchState ---
-
-InputDispatcher::TouchState::TouchState() :
- down(false), split(false), deviceId(-1), source(0), displayId(-1) {
-}
-
-InputDispatcher::TouchState::~TouchState() {
-}
-
-void InputDispatcher::TouchState::reset() {
- down = false;
- split = false;
- deviceId = -1;
- source = 0;
- displayId = -1;
- windows.clear();
-}
-
-void InputDispatcher::TouchState::copyFrom(const TouchState& other) {
- down = other.down;
- split = other.split;
- deviceId = other.deviceId;
- source = other.source;
- displayId = other.displayId;
- windows = other.windows;
-}
-
-void InputDispatcher::TouchState::addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
- int32_t targetFlags, BitSet32 pointerIds) {
- if (targetFlags & InputTarget::FLAG_SPLIT) {
- split = true;
- }
-
- for (size_t i = 0; i < windows.size(); i++) {
- TouchedWindow& touchedWindow = windows.editItemAt(i);
- if (touchedWindow.windowHandle == windowHandle) {
- touchedWindow.targetFlags |= targetFlags;
- if (targetFlags & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) {
- touchedWindow.targetFlags &= ~InputTarget::FLAG_DISPATCH_AS_IS;
- }
- touchedWindow.pointerIds.value |= pointerIds.value;
- return;
- }
- }
-
- windows.push();
-
- TouchedWindow& touchedWindow = windows.editTop();
- touchedWindow.windowHandle = windowHandle;
- touchedWindow.targetFlags = targetFlags;
- touchedWindow.pointerIds = pointerIds;
-}
-
-void InputDispatcher::TouchState::removeWindow(const sp<InputWindowHandle>& windowHandle) {
- for (size_t i = 0; i < windows.size(); i++) {
- if (windows.itemAt(i).windowHandle == windowHandle) {
- windows.removeAt(i);
- return;
- }
- }
-}
-
-void InputDispatcher::TouchState::filterNonAsIsTouchWindows() {
- for (size_t i = 0 ; i < windows.size(); ) {
- TouchedWindow& window = windows.editItemAt(i);
- if (window.targetFlags & (InputTarget::FLAG_DISPATCH_AS_IS
- | InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER)) {
- window.targetFlags &= ~InputTarget::FLAG_DISPATCH_MASK;
- window.targetFlags |= InputTarget::FLAG_DISPATCH_AS_IS;
- i += 1;
- } else {
- windows.removeAt(i);
- }
- }
-}
-
-sp<InputWindowHandle> InputDispatcher::TouchState::getFirstForegroundWindowHandle() const {
- for (size_t i = 0; i < windows.size(); i++) {
- const TouchedWindow& window = windows.itemAt(i);
- if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
- return window.windowHandle;
- }
- }
- return NULL;
-}
-
-bool InputDispatcher::TouchState::isSlippery() const {
- // Must have exactly one foreground window.
- bool haveSlipperyForegroundWindow = false;
- for (size_t i = 0; i < windows.size(); i++) {
- const TouchedWindow& window = windows.itemAt(i);
- if (window.targetFlags & InputTarget::FLAG_FOREGROUND) {
- if (haveSlipperyForegroundWindow
- || !(window.windowHandle->getInfo()->layoutParamsFlags
- & InputWindowInfo::FLAG_SLIPPERY)) {
- return false;
- }
- haveSlipperyForegroundWindow = true;
- }
- }
- return haveSlipperyForegroundWindow;
-}
-
-
-// --- InputDispatcherThread ---
-
-InputDispatcherThread::InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher) :
- Thread(/*canCallJava*/ true), mDispatcher(dispatcher) {
-}
-
-InputDispatcherThread::~InputDispatcherThread() {
-}
-
-bool InputDispatcherThread::threadLoop() {
- mDispatcher->dispatchOnce();
- return true;
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/InputDispatcher.h b/widget/gonk/libui/InputDispatcher.h
deleted file mode 100644
index 5453421f6..000000000
--- a/widget/gonk/libui/InputDispatcher.h
+++ /dev/null
@@ -1,1117 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_INPUT_DISPATCHER_H
-#define _UI_INPUT_DISPATCHER_H
-
-#include "Input.h"
-#include "InputTransport.h"
-#include <utils/KeyedVector.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-#include <utils/Timers.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-#include <utils/Looper.h>
-#include <utils/BitSet.h>
-#include <cutils/atomic.h>
-
-#include <stddef.h>
-#include <unistd.h>
-#include <limits.h>
-
-#include "InputWindow.h"
-#include "InputApplication.h"
-#include "InputListener.h"
-
-
-namespace android {
-
-/*
- * Constants used to report the outcome of input event injection.
- */
-enum {
- /* (INTERNAL USE ONLY) Specifies that injection is pending and its outcome is unknown. */
- INPUT_EVENT_INJECTION_PENDING = -1,
-
- /* Injection succeeded. */
- INPUT_EVENT_INJECTION_SUCCEEDED = 0,
-
- /* Injection failed because the injector did not have permission to inject
- * into the application with input focus. */
- INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1,
-
- /* Injection failed because there were no available input targets. */
- INPUT_EVENT_INJECTION_FAILED = 2,
-
- /* Injection failed due to a timeout. */
- INPUT_EVENT_INJECTION_TIMED_OUT = 3
-};
-
-/*
- * Constants used to determine the input event injection synchronization mode.
- */
-enum {
- /* Injection is asynchronous and is assumed always to be successful. */
- INPUT_EVENT_INJECTION_SYNC_NONE = 0,
-
- /* Waits for previous events to be dispatched so that the input dispatcher can determine
- * whether input event injection willbe permitted based on the current input focus.
- * Does not wait for the input event to finish processing. */
- INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_RESULT = 1,
-
- /* Waits for the input event to be completely processed. */
- INPUT_EVENT_INJECTION_SYNC_WAIT_FOR_FINISHED = 2,
-};
-
-
-/*
- * An input target specifies how an input event is to be dispatched to a particular window
- * including the window's input channel, control flags, a timeout, and an X / Y offset to
- * be added to input event coordinates to compensate for the absolute position of the
- * window area.
- */
-struct InputTarget {
- enum {
- /* This flag indicates that the event is being delivered to a foreground application. */
- FLAG_FOREGROUND = 1 << 0,
-
- /* This flag indicates that the target of a MotionEvent is partly or wholly
- * obscured by another visible window above it. The motion event should be
- * delivered with flag AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED. */
- FLAG_WINDOW_IS_OBSCURED = 1 << 1,
-
- /* This flag indicates that a motion event is being split across multiple windows. */
- FLAG_SPLIT = 1 << 2,
-
- /* This flag indicates that the pointer coordinates dispatched to the application
- * will be zeroed out to avoid revealing information to an application. This is
- * used in conjunction with FLAG_DISPATCH_AS_OUTSIDE to prevent apps not sharing
- * the same UID from watching all touches. */
- FLAG_ZERO_COORDS = 1 << 3,
-
- /* This flag indicates that the event should be sent as is.
- * Should always be set unless the event is to be transmuted. */
- FLAG_DISPATCH_AS_IS = 1 << 8,
-
- /* This flag indicates that a MotionEvent with AMOTION_EVENT_ACTION_DOWN falls outside
- * of the area of this target and so should instead be delivered as an
- * AMOTION_EVENT_ACTION_OUTSIDE to this target. */
- FLAG_DISPATCH_AS_OUTSIDE = 1 << 9,
-
- /* This flag indicates that a hover sequence is starting in the given window.
- * The event is transmuted into ACTION_HOVER_ENTER. */
- FLAG_DISPATCH_AS_HOVER_ENTER = 1 << 10,
-
- /* This flag indicates that a hover event happened outside of a window which handled
- * previous hover events, signifying the end of the current hover sequence for that
- * window.
- * The event is transmuted into ACTION_HOVER_ENTER. */
- FLAG_DISPATCH_AS_HOVER_EXIT = 1 << 11,
-
- /* This flag indicates that the event should be canceled.
- * It is used to transmute ACTION_MOVE into ACTION_CANCEL when a touch slips
- * outside of a window. */
- FLAG_DISPATCH_AS_SLIPPERY_EXIT = 1 << 12,
-
- /* This flag indicates that the event should be dispatched as an initial down.
- * It is used to transmute ACTION_MOVE into ACTION_DOWN when a touch slips
- * into a new window. */
- FLAG_DISPATCH_AS_SLIPPERY_ENTER = 1 << 13,
-
- /* Mask for all dispatch modes. */
- FLAG_DISPATCH_MASK = FLAG_DISPATCH_AS_IS
- | FLAG_DISPATCH_AS_OUTSIDE
- | FLAG_DISPATCH_AS_HOVER_ENTER
- | FLAG_DISPATCH_AS_HOVER_EXIT
- | FLAG_DISPATCH_AS_SLIPPERY_EXIT
- | FLAG_DISPATCH_AS_SLIPPERY_ENTER,
- };
-
- // The input channel to be targeted.
- sp<InputChannel> inputChannel;
-
- // Flags for the input target.
- int32_t flags;
-
- // The x and y offset to add to a MotionEvent as it is delivered.
- // (ignored for KeyEvents)
- float xOffset, yOffset;
-
- // Scaling factor to apply to MotionEvent as it is delivered.
- // (ignored for KeyEvents)
- float scaleFactor;
-
- // The subset of pointer ids to include in motion events dispatched to this input target
- // if FLAG_SPLIT is set.
- BitSet32 pointerIds;
-};
-
-
-/*
- * Input dispatcher configuration.
- *
- * Specifies various options that modify the behavior of the input dispatcher.
- * The values provided here are merely defaults. The actual values will come from ViewConfiguration
- * and are passed into the dispatcher during initialization.
- */
-struct InputDispatcherConfiguration {
- // The key repeat initial timeout.
- nsecs_t keyRepeatTimeout;
-
- // The key repeat inter-key delay.
- nsecs_t keyRepeatDelay;
-
- InputDispatcherConfiguration() :
- keyRepeatTimeout(500 * 1000000LL),
- keyRepeatDelay(50 * 1000000LL) { }
-};
-
-
-/*
- * Input dispatcher policy interface.
- *
- * The input reader policy is used by the input reader to interact with the Window Manager
- * and other system components.
- *
- * The actual implementation is partially supported by callbacks into the DVM
- * via JNI. This interface is also mocked in the unit tests.
- */
-class InputDispatcherPolicyInterface : public virtual RefBase {
-protected:
- InputDispatcherPolicyInterface() { }
- virtual ~InputDispatcherPolicyInterface() { }
-
-public:
- /* Notifies the system that a configuration change has occurred. */
- virtual void notifyConfigurationChanged(nsecs_t when) = 0;
-
- /* Notifies the system that an application is not responding.
- * Returns a new timeout to continue waiting, or 0 to abort dispatch. */
- virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
- const sp<InputWindowHandle>& inputWindowHandle) = 0;
-
- /* Notifies the system that an input channel is unrecoverably broken. */
- virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
-
- /* Gets the input dispatcher configuration. */
- virtual void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) = 0;
-
- /* Returns true if automatic key repeating is enabled. */
- virtual bool isKeyRepeatEnabled() = 0;
-
- /* Filters an input event.
- * Return true to dispatch the event unmodified, false to consume the event.
- * A filter can also transform and inject events later by passing POLICY_FLAG_FILTERED
- * to injectInputEvent.
- */
- virtual bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) = 0;
-
- /* Intercepts a key event immediately before queueing it.
- * The policy can use this method as an opportunity to perform power management functions
- * and early event preprocessing such as updating policy flags.
- *
- * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
- * should be dispatched to applications.
- */
- virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags) = 0;
-
- /* Intercepts a touch, trackball or other motion event before queueing it.
- * The policy can use this method as an opportunity to perform power management functions
- * and early event preprocessing such as updating policy flags.
- *
- * This method is expected to set the POLICY_FLAG_PASS_TO_USER policy flag if the event
- * should be dispatched to applications.
- */
- virtual void interceptMotionBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
-
- /* Allows the policy a chance to intercept a key before dispatching. */
- virtual nsecs_t interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
- const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
-
- /* Allows the policy a chance to perform default processing for an unhandled key.
- * Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
- virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
- const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
-
- /* Notifies the policy about switch events.
- */
- virtual void notifySwitch(nsecs_t when,
- uint32_t switchValues, uint32_t switchMask, uint32_t policyFlags) = 0;
-
- /* Poke user activity for an event dispatched to a window. */
- virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType) = 0;
-
- /* Checks whether a given application pid/uid has permission to inject input events
- * into other applications.
- *
- * This method is special in that its implementation promises to be non-reentrant and
- * is safe to call while holding other locks. (Most other methods make no such guarantees!)
- */
- virtual bool checkInjectEventsPermissionNonReentrant(
- int32_t injectorPid, int32_t injectorUid) = 0;
-};
-
-
-/* Notifies the system about input events generated by the input reader.
- * The dispatcher is expected to be mostly asynchronous. */
-class InputDispatcherInterface : public virtual RefBase, public InputListenerInterface {
-protected:
- InputDispatcherInterface() { }
- virtual ~InputDispatcherInterface() { }
-
-public:
- /* Dumps the state of the input dispatcher.
- *
- * This method may be called on any thread (usually by the input manager). */
- virtual void dump(String8& dump) = 0;
-
- /* Called by the heatbeat to ensures that the dispatcher has not deadlocked. */
- virtual void monitor() = 0;
-
- /* Runs a single iteration of the dispatch loop.
- * Nominally processes one queued event, a timeout, or a response from an input consumer.
- *
- * This method should only be called on the input dispatcher thread.
- */
- virtual void dispatchOnce() = 0;
-
- /* Injects an input event and optionally waits for sync.
- * The synchronization mode determines whether the method blocks while waiting for
- * input injection to proceed.
- * Returns one of the INPUT_EVENT_INJECTION_XXX constants.
- *
- * This method may be called on any thread (usually by the input manager).
- */
- virtual int32_t injectInputEvent(const InputEvent* event,
- int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
- uint32_t policyFlags) = 0;
-
- /* Sets the list of input windows.
- *
- * This method may be called on any thread (usually by the input manager).
- */
- virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) = 0;
-
- /* Sets the focused application.
- *
- * This method may be called on any thread (usually by the input manager).
- */
- virtual void setFocusedApplication(
- const sp<InputApplicationHandle>& inputApplicationHandle) = 0;
-
- /* Sets the input dispatching mode.
- *
- * This method may be called on any thread (usually by the input manager).
- */
- virtual void setInputDispatchMode(bool enabled, bool frozen) = 0;
-
- /* Sets whether input event filtering is enabled.
- * When enabled, incoming input events are sent to the policy's filterInputEvent
- * method instead of being dispatched. The filter is expected to use
- * injectInputEvent to inject the events it would like to have dispatched.
- * It should include POLICY_FLAG_FILTERED in the policy flags during injection.
- */
- virtual void setInputFilterEnabled(bool enabled) = 0;
-
- /* Transfers touch focus from the window associated with one channel to the
- * window associated with the other channel.
- *
- * Returns true on success. False if the window did not actually have touch focus.
- */
- virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
- const sp<InputChannel>& toChannel) = 0;
-
- /* Registers or unregister input channels that may be used as targets for input events.
- * If monitor is true, the channel will receive a copy of all input events.
- *
- * These methods may be called on any thread (usually by the input manager).
- */
- virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
- const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
- virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
-};
-
-/* Dispatches events to input targets. Some functions of the input dispatcher, such as
- * identifying input targets, are controlled by a separate policy object.
- *
- * IMPORTANT INVARIANT:
- * Because the policy can potentially block or cause re-entrance into the input dispatcher,
- * the input dispatcher never calls into the policy while holding its internal locks.
- * The implementation is also carefully designed to recover from scenarios such as an
- * input channel becoming unregistered while identifying input targets or processing timeouts.
- *
- * Methods marked 'Locked' must be called with the lock acquired.
- *
- * Methods marked 'LockedInterruptible' must be called with the lock acquired but
- * may during the course of their execution release the lock, call into the policy, and
- * then reacquire the lock. The caller is responsible for recovering gracefully.
- *
- * A 'LockedInterruptible' method may called a 'Locked' method, but NOT vice-versa.
- */
-class InputDispatcher : public InputDispatcherInterface {
-protected:
- virtual ~InputDispatcher();
-
-public:
- explicit InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy);
-
- virtual void dump(String8& dump);
- virtual void monitor();
-
- virtual void dispatchOnce();
-
- virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
- virtual void notifyKey(const NotifyKeyArgs* args);
- virtual void notifyMotion(const NotifyMotionArgs* args);
- virtual void notifySwitch(const NotifySwitchArgs* args);
- virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
-
- virtual int32_t injectInputEvent(const InputEvent* event,
- int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
- uint32_t policyFlags);
-
- virtual void setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles);
- virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle);
- virtual void setInputDispatchMode(bool enabled, bool frozen);
- virtual void setInputFilterEnabled(bool enabled);
-
- virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
- const sp<InputChannel>& toChannel);
-
- virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
- const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
- virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
-
-private:
- template <typename T>
- struct Link {
- T* next;
- T* prev;
-
- protected:
- inline Link() : next(NULL), prev(NULL) { }
- };
-
- struct InjectionState {
- mutable int32_t refCount;
-
- int32_t injectorPid;
- int32_t injectorUid;
- int32_t injectionResult; // initially INPUT_EVENT_INJECTION_PENDING
- bool injectionIsAsync; // set to true if injection is not waiting for the result
- int32_t pendingForegroundDispatches; // the number of foreground dispatches in progress
-
- InjectionState(int32_t injectorPid, int32_t injectorUid);
- void release();
-
- private:
- ~InjectionState();
- };
-
- struct EventEntry : Link<EventEntry> {
- enum {
- TYPE_CONFIGURATION_CHANGED,
- TYPE_DEVICE_RESET,
- TYPE_KEY,
- TYPE_MOTION
- };
-
- mutable int32_t refCount;
- int32_t type;
- nsecs_t eventTime;
- uint32_t policyFlags;
- InjectionState* injectionState;
-
- bool dispatchInProgress; // initially false, set to true while dispatching
-
- inline bool isInjected() const { return injectionState != NULL; }
-
- void release();
-
- virtual void appendDescription(String8& msg) const = 0;
-
- protected:
- EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
- virtual ~EventEntry();
- void releaseInjectionState();
- };
-
- struct ConfigurationChangedEntry : EventEntry {
- ConfigurationChangedEntry(nsecs_t eventTime);
- virtual void appendDescription(String8& msg) const;
-
- protected:
- virtual ~ConfigurationChangedEntry();
- };
-
- struct DeviceResetEntry : EventEntry {
- int32_t deviceId;
-
- DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
- virtual void appendDescription(String8& msg) const;
-
- protected:
- virtual ~DeviceResetEntry();
- };
-
- struct KeyEntry : EventEntry {
- int32_t deviceId;
- uint32_t source;
- int32_t action;
- int32_t flags;
- int32_t keyCode;
- int32_t scanCode;
- int32_t metaState;
- int32_t repeatCount;
- nsecs_t downTime;
-
- bool syntheticRepeat; // set to true for synthetic key repeats
-
- enum InterceptKeyResult {
- INTERCEPT_KEY_RESULT_UNKNOWN,
- INTERCEPT_KEY_RESULT_SKIP,
- INTERCEPT_KEY_RESULT_CONTINUE,
- INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER,
- };
- InterceptKeyResult interceptKeyResult; // set based on the interception result
- nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
-
- KeyEntry(nsecs_t eventTime,
- int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t action,
- int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
- int32_t repeatCount, nsecs_t downTime);
- virtual void appendDescription(String8& msg) const;
- void recycle();
-
- protected:
- virtual ~KeyEntry();
- };
-
- struct MotionEntry : EventEntry {
- nsecs_t eventTime;
- int32_t deviceId;
- uint32_t source;
- int32_t action;
- int32_t flags;
- int32_t metaState;
- int32_t buttonState;
- int32_t edgeFlags;
- float xPrecision;
- float yPrecision;
- nsecs_t downTime;
- int32_t displayId;
- uint32_t pointerCount;
- PointerProperties pointerProperties[MAX_POINTERS];
- PointerCoords pointerCoords[MAX_POINTERS];
-
- MotionEntry(nsecs_t eventTime,
- int32_t deviceId, uint32_t source, uint32_t policyFlags,
- int32_t action, int32_t flags,
- int32_t metaState, int32_t buttonState, int32_t edgeFlags,
- float xPrecision, float yPrecision,
- nsecs_t downTime, int32_t displayId, uint32_t pointerCount,
- const PointerProperties* pointerProperties, const PointerCoords* pointerCoords);
- virtual void appendDescription(String8& msg) const;
-
- protected:
- virtual ~MotionEntry();
- };
-
- // Tracks the progress of dispatching a particular event to a particular connection.
- struct DispatchEntry : Link<DispatchEntry> {
- const uint32_t seq; // unique sequence number, never 0
-
- EventEntry* eventEntry; // the event to dispatch
- int32_t targetFlags;
- float xOffset;
- float yOffset;
- float scaleFactor;
- nsecs_t deliveryTime; // time when the event was actually delivered
-
- // Set to the resolved action and flags when the event is enqueued.
- int32_t resolvedAction;
- int32_t resolvedFlags;
-
- DispatchEntry(EventEntry* eventEntry,
- int32_t targetFlags, float xOffset, float yOffset, float scaleFactor);
- ~DispatchEntry();
-
- inline bool hasForegroundTarget() const {
- return targetFlags & InputTarget::FLAG_FOREGROUND;
- }
-
- inline bool isSplit() const {
- return targetFlags & InputTarget::FLAG_SPLIT;
- }
-
- private:
- static volatile int32_t sNextSeqAtomic;
-
- static uint32_t nextSeq();
- };
-
- // A command entry captures state and behavior for an action to be performed in the
- // dispatch loop after the initial processing has taken place. It is essentially
- // a kind of continuation used to postpone sensitive policy interactions to a point
- // in the dispatch loop where it is safe to release the lock (generally after finishing
- // the critical parts of the dispatch cycle).
- //
- // The special thing about commands is that they can voluntarily release and reacquire
- // the dispatcher lock at will. Initially when the command starts running, the
- // dispatcher lock is held. However, if the command needs to call into the policy to
- // do some work, it can release the lock, do the work, then reacquire the lock again
- // before returning.
- //
- // This mechanism is a bit clunky but it helps to preserve the invariant that the dispatch
- // never calls into the policy while holding its lock.
- //
- // Commands are implicitly 'LockedInterruptible'.
- struct CommandEntry;
- typedef void (InputDispatcher::*Command)(CommandEntry* commandEntry);
-
- class Connection;
- struct CommandEntry : Link<CommandEntry> {
- CommandEntry(Command command);
- ~CommandEntry();
-
- Command command;
-
- // parameters for the command (usage varies by command)
- sp<Connection> connection;
- nsecs_t eventTime;
- KeyEntry* keyEntry;
- sp<InputApplicationHandle> inputApplicationHandle;
- sp<InputWindowHandle> inputWindowHandle;
- int32_t userActivityEventType;
- uint32_t seq;
- bool handled;
- };
-
- // Generic queue implementation.
- template <typename T>
- struct Queue {
- T* head;
- T* tail;
-
- inline Queue() : head(NULL), tail(NULL) {
- }
-
- inline bool isEmpty() const {
- return !head;
- }
-
- inline void enqueueAtTail(T* entry) {
- entry->prev = tail;
- if (tail) {
- tail->next = entry;
- } else {
- head = entry;
- }
- entry->next = NULL;
- tail = entry;
- }
-
- inline void enqueueAtHead(T* entry) {
- entry->next = head;
- if (head) {
- head->prev = entry;
- } else {
- tail = entry;
- }
- entry->prev = NULL;
- head = entry;
- }
-
- inline void dequeue(T* entry) {
- if (entry->prev) {
- entry->prev->next = entry->next;
- } else {
- head = entry->next;
- }
- if (entry->next) {
- entry->next->prev = entry->prev;
- } else {
- tail = entry->prev;
- }
- }
-
- inline T* dequeueAtHead() {
- T* entry = head;
- head = entry->next;
- if (head) {
- head->prev = NULL;
- } else {
- tail = NULL;
- }
- return entry;
- }
-
- uint32_t count() const;
- };
-
- /* Specifies which events are to be canceled and why. */
- struct CancelationOptions {
- enum Mode {
- CANCEL_ALL_EVENTS = 0,
- CANCEL_POINTER_EVENTS = 1,
- CANCEL_NON_POINTER_EVENTS = 2,
- CANCEL_FALLBACK_EVENTS = 3,
- };
-
- // The criterion to use to determine which events should be canceled.
- Mode mode;
-
- // Descriptive reason for the cancelation.
- const char* reason;
-
- // The specific keycode of the key event to cancel, or -1 to cancel any key event.
- int32_t keyCode;
-
- // The specific device id of events to cancel, or -1 to cancel events from any device.
- int32_t deviceId;
-
- CancelationOptions(Mode mode, const char* reason) :
- mode(mode), reason(reason), keyCode(-1), deviceId(-1) { }
- };
-
- /* Tracks dispatched key and motion event state so that cancelation events can be
- * synthesized when events are dropped. */
- class InputState {
- public:
- InputState();
- ~InputState();
-
- // Returns true if there is no state to be canceled.
- bool isNeutral() const;
-
- // Returns true if the specified source is known to have received a hover enter
- // motion event.
- bool isHovering(int32_t deviceId, uint32_t source, int32_t displayId) const;
-
- // Records tracking information for a key event that has just been published.
- // Returns true if the event should be delivered, false if it is inconsistent
- // and should be skipped.
- bool trackKey(const KeyEntry* entry, int32_t action, int32_t flags);
-
- // Records tracking information for a motion event that has just been published.
- // Returns true if the event should be delivered, false if it is inconsistent
- // and should be skipped.
- bool trackMotion(const MotionEntry* entry, int32_t action, int32_t flags);
-
- // Synthesizes cancelation events for the current state and resets the tracked state.
- void synthesizeCancelationEvents(nsecs_t currentTime,
- Vector<EventEntry*>& outEvents, const CancelationOptions& options);
-
- // Clears the current state.
- void clear();
-
- // Copies pointer-related parts of the input state to another instance.
- void copyPointerStateTo(InputState& other) const;
-
- // Gets the fallback key associated with a keycode.
- // Returns -1 if none.
- // Returns AKEYCODE_UNKNOWN if we are only dispatching the unhandled key to the policy.
- int32_t getFallbackKey(int32_t originalKeyCode);
-
- // Sets the fallback key for a particular keycode.
- void setFallbackKey(int32_t originalKeyCode, int32_t fallbackKeyCode);
-
- // Removes the fallback key for a particular keycode.
- void removeFallbackKey(int32_t originalKeyCode);
-
- inline const KeyedVector<int32_t, int32_t>& getFallbackKeys() const {
- return mFallbackKeys;
- }
-
- private:
- struct KeyMemento {
- int32_t deviceId;
- uint32_t source;
- int32_t keyCode;
- int32_t scanCode;
- int32_t metaState;
- int32_t flags;
- nsecs_t downTime;
- uint32_t policyFlags;
- };
-
- struct MotionMemento {
- int32_t deviceId;
- uint32_t source;
- int32_t flags;
- float xPrecision;
- float yPrecision;
- nsecs_t downTime;
- int32_t displayId;
- uint32_t pointerCount;
- PointerProperties pointerProperties[MAX_POINTERS];
- PointerCoords pointerCoords[MAX_POINTERS];
- bool hovering;
- uint32_t policyFlags;
-
- void setPointers(const MotionEntry* entry);
- };
-
- Vector<KeyMemento> mKeyMementos;
- Vector<MotionMemento> mMotionMementos;
- KeyedVector<int32_t, int32_t> mFallbackKeys;
-
- ssize_t findKeyMemento(const KeyEntry* entry) const;
- ssize_t findMotionMemento(const MotionEntry* entry, bool hovering) const;
-
- void addKeyMemento(const KeyEntry* entry, int32_t flags);
- void addMotionMemento(const MotionEntry* entry, int32_t flags, bool hovering);
-
- static bool shouldCancelKey(const KeyMemento& memento,
- const CancelationOptions& options);
- static bool shouldCancelMotion(const MotionMemento& memento,
- const CancelationOptions& options);
- };
-
- /* Manages the dispatch state associated with a single input channel. */
- class Connection : public RefBase {
- protected:
- virtual ~Connection();
-
- public:
- enum Status {
- // Everything is peachy.
- STATUS_NORMAL,
- // An unrecoverable communication error has occurred.
- STATUS_BROKEN,
- // The input channel has been unregistered.
- STATUS_ZOMBIE
- };
-
- Status status;
- sp<InputChannel> inputChannel; // never null
- sp<InputWindowHandle> inputWindowHandle; // may be null
- bool monitor;
- InputPublisher inputPublisher;
- InputState inputState;
-
- // True if the socket is full and no further events can be published until
- // the application consumes some of the input.
- bool inputPublisherBlocked;
-
- // Queue of events that need to be published to the connection.
- Queue<DispatchEntry> outboundQueue;
-
- // Queue of events that have been published to the connection but that have not
- // yet received a "finished" response from the application.
- Queue<DispatchEntry> waitQueue;
-
- explicit Connection(const sp<InputChannel>& inputChannel,
- const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
-
- inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
-
- const char* getWindowName() const;
- const char* getStatusLabel() const;
-
- DispatchEntry* findWaitQueueEntry(uint32_t seq);
- };
-
- enum DropReason {
- DROP_REASON_NOT_DROPPED = 0,
- DROP_REASON_POLICY = 1,
- DROP_REASON_APP_SWITCH = 2,
- DROP_REASON_DISABLED = 3,
- DROP_REASON_BLOCKED = 4,
- DROP_REASON_STALE = 5,
- };
-
- sp<InputDispatcherPolicyInterface> mPolicy;
- InputDispatcherConfiguration mConfig;
-
- Mutex mLock;
-
- Condition mDispatcherIsAliveCondition;
-
- sp<Looper> mLooper;
-
- EventEntry* mPendingEvent;
- Queue<EventEntry> mInboundQueue;
- Queue<CommandEntry> mCommandQueue;
-
- void dispatchOnceInnerLocked(nsecs_t* nextWakeupTime);
-
- // Enqueues an inbound event. Returns true if mLooper->wake() should be called.
- bool enqueueInboundEventLocked(EventEntry* entry);
-
- // Cleans up input state when dropping an inbound event.
- void dropInboundEventLocked(EventEntry* entry, DropReason dropReason);
-
- // App switch latency optimization.
- bool mAppSwitchSawKeyDown;
- nsecs_t mAppSwitchDueTime;
-
- static bool isAppSwitchKeyCode(int32_t keyCode);
- bool isAppSwitchKeyEventLocked(KeyEntry* keyEntry);
- bool isAppSwitchPendingLocked();
- void resetPendingAppSwitchLocked(bool handled);
-
- // Stale event latency optimization.
- static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
-
- // Blocked event latency optimization. Drops old events when the user intends
- // to transfer focus to a new application.
- EventEntry* mNextUnblockedEvent;
-
- sp<InputWindowHandle> findTouchedWindowAtLocked(int32_t displayId, int32_t x, int32_t y);
-
- // All registered connections mapped by channel file descriptor.
- KeyedVector<int, sp<Connection> > mConnectionsByFd;
-
- ssize_t getConnectionIndexLocked(const sp<InputChannel>& inputChannel);
-
- // Input channels that will receive a copy of all input events.
- Vector<sp<InputChannel> > mMonitoringChannels;
-
- // Event injection and synchronization.
- Condition mInjectionResultAvailableCondition;
- bool hasInjectionPermission(int32_t injectorPid, int32_t injectorUid);
- void setInjectionResultLocked(EventEntry* entry, int32_t injectionResult);
-
- Condition mInjectionSyncFinishedCondition;
- void incrementPendingForegroundDispatchesLocked(EventEntry* entry);
- void decrementPendingForegroundDispatchesLocked(EventEntry* entry);
-
- // Key repeat tracking.
- struct KeyRepeatState {
- KeyEntry* lastKeyEntry; // or null if no repeat
- nsecs_t nextRepeatTime;
- } mKeyRepeatState;
-
- void resetKeyRepeatLocked();
- KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
-
- // Deferred command processing.
- bool haveCommandsLocked() const;
- bool runCommandsLockedInterruptible();
- CommandEntry* postCommandLocked(Command command);
-
- // Input filter processing.
- bool shouldSendKeyToInputFilterLocked(const NotifyKeyArgs* args);
- bool shouldSendMotionToInputFilterLocked(const NotifyMotionArgs* args);
-
- // Inbound event processing.
- void drainInboundQueueLocked();
- void releasePendingEventLocked();
- void releaseInboundEventLocked(EventEntry* entry);
-
- // Dispatch state.
- bool mDispatchEnabled;
- bool mDispatchFrozen;
- bool mInputFilterEnabled;
-
- Vector<sp<InputWindowHandle> > mWindowHandles;
-
- sp<InputWindowHandle> getWindowHandleLocked(const sp<InputChannel>& inputChannel) const;
- bool hasWindowHandleLocked(const sp<InputWindowHandle>& windowHandle) const;
-
- // Focus tracking for keys, trackball, etc.
- sp<InputWindowHandle> mFocusedWindowHandle;
-
- // Focus tracking for touch.
- struct TouchedWindow {
- sp<InputWindowHandle> windowHandle;
- int32_t targetFlags;
- BitSet32 pointerIds; // zero unless target flag FLAG_SPLIT is set
- };
- struct TouchState {
- bool down;
- bool split;
- int32_t deviceId; // id of the device that is currently down, others are rejected
- uint32_t source; // source of the device that is current down, others are rejected
- int32_t displayId; // id to the display that currently has a touch, others are rejected
- Vector<TouchedWindow> windows;
-
- TouchState();
- ~TouchState();
- void reset();
- void copyFrom(const TouchState& other);
- void addOrUpdateWindow(const sp<InputWindowHandle>& windowHandle,
- int32_t targetFlags, BitSet32 pointerIds);
- void removeWindow(const sp<InputWindowHandle>& windowHandle);
- void filterNonAsIsTouchWindows();
- sp<InputWindowHandle> getFirstForegroundWindowHandle() const;
- bool isSlippery() const;
- };
-
- TouchState mTouchState;
- TouchState mTempTouchState;
-
- // Focused application.
- sp<InputApplicationHandle> mFocusedApplicationHandle;
-
- // Dispatcher state at time of last ANR.
- String8 mLastANRState;
-
- // Dispatch inbound events.
- bool dispatchConfigurationChangedLocked(
- nsecs_t currentTime, ConfigurationChangedEntry* entry);
- bool dispatchDeviceResetLocked(
- nsecs_t currentTime, DeviceResetEntry* entry);
- bool dispatchKeyLocked(
- nsecs_t currentTime, KeyEntry* entry,
- DropReason* dropReason, nsecs_t* nextWakeupTime);
- bool dispatchMotionLocked(
- nsecs_t currentTime, MotionEntry* entry,
- DropReason* dropReason, nsecs_t* nextWakeupTime);
- void dispatchEventLocked(nsecs_t currentTime, EventEntry* entry,
- const Vector<InputTarget>& inputTargets);
-
- void logOutboundKeyDetailsLocked(const char* prefix, const KeyEntry* entry);
- void logOutboundMotionDetailsLocked(const char* prefix, const MotionEntry* entry);
-
- // Keeping track of ANR timeouts.
- enum InputTargetWaitCause {
- INPUT_TARGET_WAIT_CAUSE_NONE,
- INPUT_TARGET_WAIT_CAUSE_SYSTEM_NOT_READY,
- INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY,
- };
-
- InputTargetWaitCause mInputTargetWaitCause;
- nsecs_t mInputTargetWaitStartTime;
- nsecs_t mInputTargetWaitTimeoutTime;
- bool mInputTargetWaitTimeoutExpired;
- sp<InputApplicationHandle> mInputTargetWaitApplicationHandle;
-
- // Contains the last window which received a hover event.
- sp<InputWindowHandle> mLastHoverWindowHandle;
-
- // Finding targets for input events.
- int32_t handleTargetsNotReadyLocked(nsecs_t currentTime, const EventEntry* entry,
- const sp<InputApplicationHandle>& applicationHandle,
- const sp<InputWindowHandle>& windowHandle,
- nsecs_t* nextWakeupTime, const char* reason);
- void resumeAfterTargetsNotReadyTimeoutLocked(nsecs_t newTimeout,
- const sp<InputChannel>& inputChannel);
- nsecs_t getTimeSpentWaitingForApplicationLocked(nsecs_t currentTime);
- void resetANRTimeoutsLocked();
-
- int32_t findFocusedWindowTargetsLocked(nsecs_t currentTime, const EventEntry* entry,
- Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime);
- int32_t findTouchedWindowTargetsLocked(nsecs_t currentTime, const MotionEntry* entry,
- Vector<InputTarget>& inputTargets, nsecs_t* nextWakeupTime,
- bool* outConflictingPointerActions);
-
- void addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
- int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets);
- void addMonitoringTargetsLocked(Vector<InputTarget>& inputTargets);
-
- void pokeUserActivityLocked(const EventEntry* eventEntry);
- bool checkInjectionPermission(const sp<InputWindowHandle>& windowHandle,
- const InjectionState* injectionState);
- bool isWindowObscuredAtPointLocked(const sp<InputWindowHandle>& windowHandle,
- int32_t x, int32_t y) const;
- bool isWindowReadyForMoreInputLocked(nsecs_t currentTime,
- const sp<InputWindowHandle>& windowHandle, const EventEntry* eventEntry);
- String8 getApplicationWindowLabelLocked(const sp<InputApplicationHandle>& applicationHandle,
- const sp<InputWindowHandle>& windowHandle);
-
- // Manage the dispatch cycle for a single connection.
- // These methods are deliberately not Interruptible because doing all of the work
- // with the mutex held makes it easier to ensure that connection invariants are maintained.
- // If needed, the methods post commands to run later once the critical bits are done.
- void prepareDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
- EventEntry* eventEntry, const InputTarget* inputTarget);
- void enqueueDispatchEntriesLocked(nsecs_t currentTime, const sp<Connection>& connection,
- EventEntry* eventEntry, const InputTarget* inputTarget);
- void enqueueDispatchEntryLocked(const sp<Connection>& connection,
- EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode);
- void startDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection);
- void finishDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
- uint32_t seq, bool handled);
- void abortBrokenDispatchCycleLocked(nsecs_t currentTime, const sp<Connection>& connection,
- bool notify);
- void drainDispatchQueueLocked(Queue<DispatchEntry>* queue);
- void releaseDispatchEntryLocked(DispatchEntry* dispatchEntry);
- static int handleReceiveCallback(int fd, int events, void* data);
-
- void synthesizeCancelationEventsForAllConnectionsLocked(
- const CancelationOptions& options);
- void synthesizeCancelationEventsForInputChannelLocked(const sp<InputChannel>& channel,
- const CancelationOptions& options);
- void synthesizeCancelationEventsForConnectionLocked(const sp<Connection>& connection,
- const CancelationOptions& options);
-
- // Splitting motion events across windows.
- MotionEntry* splitMotionEvent(const MotionEntry* originalMotionEntry, BitSet32 pointerIds);
-
- // Reset and drop everything the dispatcher is doing.
- void resetAndDropEverythingLocked(const char* reason);
-
- // Dump state.
- void dumpDispatchStateLocked(String8& dump);
- void logDispatchStateLocked();
-
- // Registration.
- void removeMonitorChannelLocked(const sp<InputChannel>& inputChannel);
- status_t unregisterInputChannelLocked(const sp<InputChannel>& inputChannel, bool notify);
-
- // Add or remove a connection to the mActiveConnections vector.
- void activateConnectionLocked(Connection* connection);
- void deactivateConnectionLocked(Connection* connection);
-
- // Interesting events that we might like to log or tell the framework about.
- void onDispatchCycleFinishedLocked(
- nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled);
- void onDispatchCycleBrokenLocked(
- nsecs_t currentTime, const sp<Connection>& connection);
- void onANRLocked(
- nsecs_t currentTime, const sp<InputApplicationHandle>& applicationHandle,
- const sp<InputWindowHandle>& windowHandle,
- nsecs_t eventTime, nsecs_t waitStartTime, const char* reason);
-
- // Outbound policy interactions.
- void doNotifyConfigurationChangedInterruptible(CommandEntry* commandEntry);
- void doNotifyInputChannelBrokenLockedInterruptible(CommandEntry* commandEntry);
- void doNotifyANRLockedInterruptible(CommandEntry* commandEntry);
- void doInterceptKeyBeforeDispatchingLockedInterruptible(CommandEntry* commandEntry);
- void doDispatchCycleFinishedLockedInterruptible(CommandEntry* commandEntry);
- bool afterKeyEventLockedInterruptible(const sp<Connection>& connection,
- DispatchEntry* dispatchEntry, KeyEntry* keyEntry, bool handled);
- bool afterMotionEventLockedInterruptible(const sp<Connection>& connection,
- DispatchEntry* dispatchEntry, MotionEntry* motionEntry, bool handled);
- void doPokeUserActivityLockedInterruptible(CommandEntry* commandEntry);
- void initializeKeyEvent(KeyEvent* event, const KeyEntry* entry);
-
- // Statistics gathering.
- void updateDispatchStatisticsLocked(nsecs_t currentTime, const EventEntry* entry,
- int32_t injectionResult, nsecs_t timeSpentWaitingForApplication);
- void traceInboundQueueLengthLocked();
- void traceOutboundQueueLengthLocked(const sp<Connection>& connection);
- void traceWaitQueueLengthLocked(const sp<Connection>& connection);
-};
-
-/* Enqueues and dispatches input events, endlessly. */
-class InputDispatcherThread : public Thread {
-public:
- explicit InputDispatcherThread(const sp<InputDispatcherInterface>& dispatcher);
- ~InputDispatcherThread();
-
-private:
- virtual bool threadLoop();
-
- sp<InputDispatcherInterface> mDispatcher;
-};
-
-} // namespace android
-
-#endif // _UI_INPUT_DISPATCHER_H
diff --git a/widget/gonk/libui/InputListener.cpp b/widget/gonk/libui/InputListener.cpp
deleted file mode 100644
index 3b673f0ad..000000000
--- a/widget/gonk/libui/InputListener.cpp
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "InputListener"
-
-//#define LOG_NDEBUG 0
-
-#include "InputListener.h"
-
-#include "cutils_log.h"
-
-namespace android {
-
-// --- NotifyConfigurationChangedArgs ---
-
-NotifyConfigurationChangedArgs::NotifyConfigurationChangedArgs(nsecs_t eventTime) :
- eventTime(eventTime) {
-}
-
-NotifyConfigurationChangedArgs::NotifyConfigurationChangedArgs(
- const NotifyConfigurationChangedArgs& other) :
- eventTime(other.eventTime) {
-}
-
-void NotifyConfigurationChangedArgs::notify(const sp<InputListenerInterface>& listener) const {
- listener->notifyConfigurationChanged(this);
-}
-
-
-// --- NotifyKeyArgs ---
-
-NotifyKeyArgs::NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source,
- uint32_t policyFlags,
- int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode,
- int32_t metaState, nsecs_t downTime) :
- eventTime(eventTime), deviceId(deviceId), source(source), policyFlags(policyFlags),
- action(action), flags(flags), keyCode(keyCode), scanCode(scanCode),
- metaState(metaState), downTime(downTime) {
-}
-
-NotifyKeyArgs::NotifyKeyArgs(const NotifyKeyArgs& other) :
- eventTime(other.eventTime), deviceId(other.deviceId), source(other.source),
- policyFlags(other.policyFlags),
- action(other.action), flags(other.flags),
- keyCode(other.keyCode), scanCode(other.scanCode),
- metaState(other.metaState), downTime(other.downTime) {
-}
-
-void NotifyKeyArgs::notify(const sp<InputListenerInterface>& listener) const {
- listener->notifyKey(this);
-}
-
-
-// --- NotifyMotionArgs ---
-
-NotifyMotionArgs::NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source,
- uint32_t policyFlags,
- int32_t action, int32_t flags, int32_t metaState, int32_t buttonState,
- int32_t edgeFlags, int32_t displayId, uint32_t pointerCount,
- const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
- float xPrecision, float yPrecision, nsecs_t downTime) :
- eventTime(eventTime), deviceId(deviceId), source(source), policyFlags(policyFlags),
- action(action), flags(flags), metaState(metaState), buttonState(buttonState),
- edgeFlags(edgeFlags), displayId(displayId), pointerCount(pointerCount),
- xPrecision(xPrecision), yPrecision(yPrecision), downTime(downTime) {
- for (uint32_t i = 0; i < pointerCount; i++) {
- this->pointerProperties[i].copyFrom(pointerProperties[i]);
- this->pointerCoords[i].copyFrom(pointerCoords[i]);
- }
-}
-
-NotifyMotionArgs::NotifyMotionArgs(const NotifyMotionArgs& other) :
- eventTime(other.eventTime), deviceId(other.deviceId), source(other.source),
- policyFlags(other.policyFlags),
- action(other.action), flags(other.flags),
- metaState(other.metaState), buttonState(other.buttonState),
- edgeFlags(other.edgeFlags), displayId(other.displayId),
- pointerCount(other.pointerCount),
- xPrecision(other.xPrecision), yPrecision(other.yPrecision), downTime(other.downTime) {
- for (uint32_t i = 0; i < pointerCount; i++) {
- pointerProperties[i].copyFrom(other.pointerProperties[i]);
- pointerCoords[i].copyFrom(other.pointerCoords[i]);
- }
-}
-
-void NotifyMotionArgs::notify(const sp<InputListenerInterface>& listener) const {
- listener->notifyMotion(this);
-}
-
-
-// --- NotifySwitchArgs ---
-
-NotifySwitchArgs::NotifySwitchArgs(nsecs_t eventTime, uint32_t policyFlags,
- uint32_t switchValues, uint32_t switchMask) :
- eventTime(eventTime), policyFlags(policyFlags),
- switchValues(switchValues), switchMask(switchMask) {
-}
-
-NotifySwitchArgs::NotifySwitchArgs(const NotifySwitchArgs& other) :
- eventTime(other.eventTime), policyFlags(other.policyFlags),
- switchValues(other.switchValues), switchMask(other.switchMask) {
-}
-
-void NotifySwitchArgs::notify(const sp<InputListenerInterface>& listener) const {
- listener->notifySwitch(this);
-}
-
-
-// --- NotifyDeviceResetArgs ---
-
-NotifyDeviceResetArgs::NotifyDeviceResetArgs(nsecs_t eventTime, int32_t deviceId) :
- eventTime(eventTime), deviceId(deviceId) {
-}
-
-NotifyDeviceResetArgs::NotifyDeviceResetArgs(const NotifyDeviceResetArgs& other) :
- eventTime(other.eventTime), deviceId(other.deviceId) {
-}
-
-void NotifyDeviceResetArgs::notify(const sp<InputListenerInterface>& listener) const {
- listener->notifyDeviceReset(this);
-}
-
-
-// --- QueuedInputListener ---
-
-QueuedInputListener::QueuedInputListener(const sp<InputListenerInterface>& innerListener) :
- mInnerListener(innerListener) {
-}
-
-QueuedInputListener::~QueuedInputListener() {
- size_t count = mArgsQueue.size();
- for (size_t i = 0; i < count; i++) {
- delete mArgsQueue[i];
- }
-}
-
-void QueuedInputListener::notifyConfigurationChanged(
- const NotifyConfigurationChangedArgs* args) {
- mArgsQueue.push(new NotifyConfigurationChangedArgs(*args));
-}
-
-void QueuedInputListener::notifyKey(const NotifyKeyArgs* args) {
- mArgsQueue.push(new NotifyKeyArgs(*args));
-}
-
-void QueuedInputListener::notifyMotion(const NotifyMotionArgs* args) {
- mArgsQueue.push(new NotifyMotionArgs(*args));
-}
-
-void QueuedInputListener::notifySwitch(const NotifySwitchArgs* args) {
- mArgsQueue.push(new NotifySwitchArgs(*args));
-}
-
-void QueuedInputListener::notifyDeviceReset(const NotifyDeviceResetArgs* args) {
- mArgsQueue.push(new NotifyDeviceResetArgs(*args));
-}
-
-void QueuedInputListener::flush() {
- size_t count = mArgsQueue.size();
- for (size_t i = 0; i < count; i++) {
- NotifyArgs* args = mArgsQueue[i];
- args->notify(mInnerListener);
- delete args;
- }
- mArgsQueue.clear();
-}
-
-
-} // namespace android
diff --git a/widget/gonk/libui/InputListener.h b/widget/gonk/libui/InputListener.h
deleted file mode 100644
index de799322f..000000000
--- a/widget/gonk/libui/InputListener.h
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_INPUT_LISTENER_H
-#define _UI_INPUT_LISTENER_H
-
-#include "Input.h"
-#include <utils/RefBase.h>
-#include <utils/Vector.h>
-
-namespace android {
-
-class InputListenerInterface;
-
-
-/* Superclass of all input event argument objects */
-struct NotifyArgs {
- virtual ~NotifyArgs() { }
-
- virtual void notify(const sp<InputListenerInterface>& listener) const = 0;
-};
-
-
-/* Describes a configuration change event. */
-struct NotifyConfigurationChangedArgs : public NotifyArgs {
- nsecs_t eventTime;
-
- inline NotifyConfigurationChangedArgs() { }
-
- NotifyConfigurationChangedArgs(nsecs_t eventTime);
-
- NotifyConfigurationChangedArgs(const NotifyConfigurationChangedArgs& other);
-
- virtual ~NotifyConfigurationChangedArgs() { }
-
- virtual void notify(const sp<InputListenerInterface>& listener) const;
-};
-
-
-/* Describes a key event. */
-struct NotifyKeyArgs : public NotifyArgs {
- nsecs_t eventTime;
- int32_t deviceId;
- uint32_t source;
- uint32_t policyFlags;
- int32_t action;
- int32_t flags;
- int32_t keyCode;
- int32_t scanCode;
- int32_t metaState;
- nsecs_t downTime;
-
- inline NotifyKeyArgs() { }
-
- NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, uint32_t policyFlags,
- int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode,
- int32_t metaState, nsecs_t downTime);
-
- NotifyKeyArgs(const NotifyKeyArgs& other);
-
- virtual ~NotifyKeyArgs() { }
-
- virtual void notify(const sp<InputListenerInterface>& listener) const;
-};
-
-
-/* Describes a motion event. */
-struct NotifyMotionArgs : public NotifyArgs {
- nsecs_t eventTime;
- int32_t deviceId;
- uint32_t source;
- uint32_t policyFlags;
- int32_t action;
- int32_t flags;
- int32_t metaState;
- int32_t buttonState;
- int32_t edgeFlags;
- int32_t displayId;
- uint32_t pointerCount;
- PointerProperties pointerProperties[MAX_POINTERS];
- PointerCoords pointerCoords[MAX_POINTERS];
- float xPrecision;
- float yPrecision;
- nsecs_t downTime;
-
- inline NotifyMotionArgs() { }
-
- NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, uint32_t policyFlags,
- int32_t action, int32_t flags, int32_t metaState, int32_t buttonState,
- int32_t edgeFlags, int32_t displayId, uint32_t pointerCount,
- const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
- float xPrecision, float yPrecision, nsecs_t downTime);
-
- NotifyMotionArgs(const NotifyMotionArgs& other);
-
- virtual ~NotifyMotionArgs() { }
-
- virtual void notify(const sp<InputListenerInterface>& listener) const;
-};
-
-
-/* Describes a switch event. */
-struct NotifySwitchArgs : public NotifyArgs {
- nsecs_t eventTime;
- uint32_t policyFlags;
- uint32_t switchValues;
- uint32_t switchMask;
-
- inline NotifySwitchArgs() { }
-
- NotifySwitchArgs(nsecs_t eventTime, uint32_t policyFlags,
- uint32_t switchValues, uint32_t switchMask);
-
- NotifySwitchArgs(const NotifySwitchArgs& other);
-
- virtual ~NotifySwitchArgs() { }
-
- virtual void notify(const sp<InputListenerInterface>& listener) const;
-};
-
-
-/* Describes a device reset event, such as when a device is added,
- * reconfigured, or removed. */
-struct NotifyDeviceResetArgs : public NotifyArgs {
- nsecs_t eventTime;
- int32_t deviceId;
-
- inline NotifyDeviceResetArgs() { }
-
- NotifyDeviceResetArgs(nsecs_t eventTime, int32_t deviceId);
-
- NotifyDeviceResetArgs(const NotifyDeviceResetArgs& other);
-
- virtual ~NotifyDeviceResetArgs() { }
-
- virtual void notify(const sp<InputListenerInterface>& listener) const;
-};
-
-
-/*
- * The interface used by the InputReader to notify the InputListener about input events.
- */
-class InputListenerInterface : public virtual RefBase {
-protected:
- InputListenerInterface() { }
- virtual ~InputListenerInterface() { }
-
-public:
- virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) = 0;
- virtual void notifyKey(const NotifyKeyArgs* args) = 0;
- virtual void notifyMotion(const NotifyMotionArgs* args) = 0;
- virtual void notifySwitch(const NotifySwitchArgs* args) = 0;
- virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args) = 0;
-};
-
-
-/*
- * An implementation of the listener interface that queues up and defers dispatch
- * of decoded events until flushed.
- */
-class QueuedInputListener : public InputListenerInterface {
-protected:
- virtual ~QueuedInputListener();
-
-public:
- QueuedInputListener(const sp<InputListenerInterface>& innerListener);
-
- virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
- virtual void notifyKey(const NotifyKeyArgs* args);
- virtual void notifyMotion(const NotifyMotionArgs* args);
- virtual void notifySwitch(const NotifySwitchArgs* args);
- virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
-
- void flush();
-
-private:
- sp<InputListenerInterface> mInnerListener;
- Vector<NotifyArgs*> mArgsQueue;
-};
-
-} // namespace android
-
-#endif // _UI_INPUT_LISTENER_H
diff --git a/widget/gonk/libui/InputManager.cpp b/widget/gonk/libui/InputManager.cpp
deleted file mode 100644
index 91af056bf..000000000
--- a/widget/gonk/libui/InputManager.cpp
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "InputManager"
-
-//#define LOG_NDEBUG 0
-
-#include "InputManager.h"
-
-#include "cutils_log.h"
-
-namespace android {
-
-InputManager::InputManager(
- const sp<EventHubInterface>& eventHub,
- const sp<InputReaderPolicyInterface>& readerPolicy,
- const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {
- mDispatcher = new InputDispatcher(dispatcherPolicy);
- mReader = new InputReader(eventHub, readerPolicy, mDispatcher);
- initialize();
-}
-
-InputManager::InputManager(
- const sp<InputReaderInterface>& reader,
- const sp<InputDispatcherInterface>& dispatcher) :
- mReader(reader),
- mDispatcher(dispatcher) {
- initialize();
-}
-
-InputManager::~InputManager() {
- stop();
-}
-
-void InputManager::initialize() {
- mReaderThread = new InputReaderThread(mReader);
- mDispatcherThread = new InputDispatcherThread(mDispatcher);
-}
-
-status_t InputManager::start() {
- status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
- if (result) {
- ALOGE("Could not start InputDispatcher thread due to error %d.", result);
- return result;
- }
-
- result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);
- if (result) {
- ALOGE("Could not start InputReader thread due to error %d.", result);
-
- mDispatcherThread->requestExit();
- return result;
- }
-
- return OK;
-}
-
-status_t InputManager::stop() {
- status_t result = mReaderThread->requestExitAndWait();
- if (result) {
- ALOGW("Could not stop InputReader thread due to error %d.", result);
- }
-
- result = mDispatcherThread->requestExitAndWait();
- if (result) {
- ALOGW("Could not stop InputDispatcher thread due to error %d.", result);
- }
-
- return OK;
-}
-
-sp<InputReaderInterface> InputManager::getReader() {
- return mReader;
-}
-
-sp<InputDispatcherInterface> InputManager::getDispatcher() {
- return mDispatcher;
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/InputManager.h b/widget/gonk/libui/InputManager.h
deleted file mode 100644
index 15a5176ec..000000000
--- a/widget/gonk/libui/InputManager.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_INPUT_MANAGER_H
-#define _UI_INPUT_MANAGER_H
-
-/**
- * Native input manager.
- */
-
-#include "EventHub.h"
-#include "InputReader.h"
-#include "InputDispatcher.h"
-
-#include "Input.h"
-#include "InputTransport.h"
-#include <utils/Errors.h>
-#include <utils/Vector.h>
-#include <utils/Timers.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-
-namespace android {
-
-/*
- * The input manager is the core of the system event processing.
- *
- * The input manager uses two threads.
- *
- * 1. The InputReaderThread (called "InputReader") reads and preprocesses raw input events,
- * applies policy, and posts messages to a queue managed by the DispatcherThread.
- * 2. The InputDispatcherThread (called "InputDispatcher") thread waits for new events on the
- * queue and asynchronously dispatches them to applications.
- *
- * By design, the InputReaderThread class and InputDispatcherThread class do not share any
- * internal state. Moreover, all communication is done one way from the InputReaderThread
- * into the InputDispatcherThread and never the reverse. Both classes may interact with the
- * InputDispatchPolicy, however.
- *
- * The InputManager class never makes any calls into Java itself. Instead, the
- * InputDispatchPolicy is responsible for performing all external interactions with the
- * system, including calling DVM services.
- */
-class InputManagerInterface : public virtual RefBase {
-protected:
- InputManagerInterface() { }
- virtual ~InputManagerInterface() { }
-
-public:
- /* Starts the input manager threads. */
- virtual status_t start() = 0;
-
- /* Stops the input manager threads and waits for them to exit. */
- virtual status_t stop() = 0;
-
- /* Gets the input reader. */
- virtual sp<InputReaderInterface> getReader() = 0;
-
- /* Gets the input dispatcher. */
- virtual sp<InputDispatcherInterface> getDispatcher() = 0;
-};
-
-class InputManager : public InputManagerInterface {
-protected:
- virtual ~InputManager();
-
-public:
- InputManager(
- const sp<EventHubInterface>& eventHub,
- const sp<InputReaderPolicyInterface>& readerPolicy,
- const sp<InputDispatcherPolicyInterface>& dispatcherPolicy);
-
- // (used for testing purposes)
- InputManager(
- const sp<InputReaderInterface>& reader,
- const sp<InputDispatcherInterface>& dispatcher);
-
- virtual status_t start();
- virtual status_t stop();
-
- virtual sp<InputReaderInterface> getReader();
- virtual sp<InputDispatcherInterface> getDispatcher();
-
-private:
- sp<InputReaderInterface> mReader;
- sp<InputReaderThread> mReaderThread;
-
- sp<InputDispatcherInterface> mDispatcher;
- sp<InputDispatcherThread> mDispatcherThread;
-
- void initialize();
-};
-
-} // namespace android
-
-#endif // _UI_INPUT_MANAGER_H
diff --git a/widget/gonk/libui/InputReader.cpp b/widget/gonk/libui/InputReader.cpp
deleted file mode 100644
index 3699569aa..000000000
--- a/widget/gonk/libui/InputReader.cpp
+++ /dev/null
@@ -1,6510 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "InputReader"
-
-//#define LOG_NDEBUG 0
-#include "cutils_log.h"
-
-// Log debug messages for each raw event received from the EventHub.
-#define DEBUG_RAW_EVENTS 0
-
-// Log debug messages about touch screen filtering hacks.
-#define DEBUG_HACKS 0
-
-// Log debug messages about virtual key processing.
-#define DEBUG_VIRTUAL_KEYS 0
-
-// Log debug messages about pointers.
-#define DEBUG_POINTERS 0
-
-// Log debug messages about pointer assignment calculations.
-#define DEBUG_POINTER_ASSIGNMENT 0
-
-// Log debug messages about gesture detection.
-#define DEBUG_GESTURES 0
-
-// Log debug messages about the vibrator.
-#define DEBUG_VIBRATOR 0
-
-#include "InputReader.h"
-
-#include "Keyboard.h"
-#include "VirtualKeyMap.h"
-
-#include <stddef.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <errno.h>
-#include <limits.h>
-#include <math.h>
-
-#define INDENT " "
-#define INDENT2 " "
-#define INDENT3 " "
-#define INDENT4 " "
-#define INDENT5 " "
-
-namespace android {
-
-// --- Constants ---
-
-// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
-static const size_t MAX_SLOTS = 32;
-
-// --- Static Functions ---
-
-template<typename T>
-inline static T abs(const T& value) {
- return value < 0 ? - value : value;
-}
-
-template<typename T>
-inline static T min(const T& a, const T& b) {
- return a < b ? a : b;
-}
-
-template<typename T>
-inline static void swap(T& a, T& b) {
- T temp = a;
- a = b;
- b = temp;
-}
-
-inline static float avg(float x, float y) {
- return (x + y) / 2;
-}
-
-inline static float distance(float x1, float y1, float x2, float y2) {
- return hypotf(x1 - x2, y1 - y2);
-}
-
-inline static int32_t signExtendNybble(int32_t value) {
- return value >= 8 ? value - 16 : value;
-}
-
-static inline const char* toString(bool value) {
- return value ? "true" : "false";
-}
-
-static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
- const int32_t map[][4], size_t mapSize) {
- if (orientation != DISPLAY_ORIENTATION_0) {
- for (size_t i = 0; i < mapSize; i++) {
- if (value == map[i][0]) {
- return map[i][orientation];
- }
- }
- }
- return value;
-}
-
-static const int32_t keyCodeRotationMap[][4] = {
- // key codes enumerated counter-clockwise with the original (unrotated) key first
- // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
- { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
- { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
- { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
- { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
-};
-static const size_t keyCodeRotationMapSize =
- sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
-
-static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
- return rotateValueUsingRotationMap(keyCode, orientation,
- keyCodeRotationMap, keyCodeRotationMapSize);
-}
-
-static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
- float temp;
- switch (orientation) {
- case DISPLAY_ORIENTATION_90:
- temp = *deltaX;
- *deltaX = *deltaY;
- *deltaY = -temp;
- break;
-
- case DISPLAY_ORIENTATION_180:
- *deltaX = -*deltaX;
- *deltaY = -*deltaY;
- break;
-
- case DISPLAY_ORIENTATION_270:
- temp = *deltaX;
- *deltaX = -*deltaY;
- *deltaY = temp;
- break;
- }
-}
-
-static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
- return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
-}
-
-// Returns true if the pointer should be reported as being down given the specified
-// button states. This determines whether the event is reported as a touch event.
-static bool isPointerDown(int32_t buttonState) {
- return buttonState &
- (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
- | AMOTION_EVENT_BUTTON_TERTIARY);
-}
-
-static float calculateCommonVector(float a, float b) {
- if (a > 0 && b > 0) {
- return a < b ? a : b;
- } else if (a < 0 && b < 0) {
- return a > b ? a : b;
- } else {
- return 0;
- }
-}
-
-static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
- nsecs_t when, int32_t deviceId, uint32_t source,
- uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
- int32_t buttonState, int32_t keyCode) {
- if (
- (action == AKEY_EVENT_ACTION_DOWN
- && !(lastButtonState & buttonState)
- && (currentButtonState & buttonState))
- || (action == AKEY_EVENT_ACTION_UP
- && (lastButtonState & buttonState)
- && !(currentButtonState & buttonState))) {
- NotifyKeyArgs args(when, deviceId, source, policyFlags,
- action, 0, keyCode, 0, context->getGlobalMetaState(), when);
- context->getListener()->notifyKey(&args);
- }
-}
-
-static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
- nsecs_t when, int32_t deviceId, uint32_t source,
- uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
- synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
- lastButtonState, currentButtonState,
- AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
- synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
- lastButtonState, currentButtonState,
- AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
-}
-
-
-// --- InputReaderConfiguration ---
-
-bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const {
- const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay;
- if (viewport.displayId >= 0) {
- *outViewport = viewport;
- return true;
- }
- return false;
-}
-
-void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) {
- DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay;
- v = viewport;
-}
-
-
-// --- InputReader ---
-
-InputReader::InputReader(const sp<EventHubInterface>& eventHub,
- const sp<InputReaderPolicyInterface>& policy,
- const sp<InputListenerInterface>& listener) :
- mContext(this), mEventHub(eventHub), mPolicy(policy),
- mGlobalMetaState(0), mGeneration(1),
- mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
- mConfigurationChangesToRefresh(0) {
- mQueuedListener = new QueuedInputListener(listener);
-
- { // acquire lock
- AutoMutex _l(mLock);
-
- refreshConfigurationLocked(0);
- updateGlobalMetaStateLocked();
- } // release lock
-}
-
-InputReader::~InputReader() {
- for (size_t i = 0; i < mDevices.size(); i++) {
- delete mDevices.valueAt(i);
- }
-}
-
-void InputReader::loopOnce() {
- int32_t oldGeneration;
- int32_t timeoutMillis;
- bool inputDevicesChanged = false;
- Vector<InputDeviceInfo> inputDevices;
- { // acquire lock
- AutoMutex _l(mLock);
-
- oldGeneration = mGeneration;
- timeoutMillis = -1;
-
- uint32_t changes = mConfigurationChangesToRefresh;
- if (changes) {
- mConfigurationChangesToRefresh = 0;
- timeoutMillis = 0;
- refreshConfigurationLocked(changes);
- } else if (mNextTimeout != LLONG_MAX) {
- nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
- timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
- }
- } // release lock
-
- size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
-
- { // acquire lock
- AutoMutex _l(mLock);
- mReaderIsAliveCondition.broadcast();
-
- if (count) {
- processEventsLocked(mEventBuffer, count);
- }
-
- if (mNextTimeout != LLONG_MAX) {
- nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
- if (now >= mNextTimeout) {
-#if DEBUG_RAW_EVENTS
- ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
-#endif
- mNextTimeout = LLONG_MAX;
- timeoutExpiredLocked(now);
- }
- }
-
- if (oldGeneration != mGeneration) {
- inputDevicesChanged = true;
- getInputDevicesLocked(inputDevices);
- }
- } // release lock
-
- // Send out a message that the describes the changed input devices.
- if (inputDevicesChanged) {
- mPolicy->notifyInputDevicesChanged(inputDevices);
- }
-
- // Flush queued events out to the listener.
- // This must happen outside of the lock because the listener could potentially call
- // back into the InputReader's methods, such as getScanCodeState, or become blocked
- // on another thread similarly waiting to acquire the InputReader lock thereby
- // resulting in a deadlock. This situation is actually quite plausible because the
- // listener is actually the input dispatcher, which calls into the window manager,
- // which occasionally calls into the input reader.
- mQueuedListener->flush();
-}
-
-void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
- for (const RawEvent* rawEvent = rawEvents; count;) {
- int32_t type = rawEvent->type;
- size_t batchSize = 1;
- if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
- int32_t deviceId = rawEvent->deviceId;
- while (batchSize < count) {
- if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
- || rawEvent[batchSize].deviceId != deviceId) {
- break;
- }
- batchSize += 1;
- }
-#if DEBUG_RAW_EVENTS
- ALOGD("BatchSize: %d Count: %d", batchSize, count);
-#endif
- processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
- } else {
- switch (rawEvent->type) {
- case EventHubInterface::DEVICE_ADDED:
- addDeviceLocked(rawEvent->when, rawEvent->deviceId);
- break;
- case EventHubInterface::DEVICE_REMOVED:
- removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
- break;
- case EventHubInterface::FINISHED_DEVICE_SCAN:
- handleConfigurationChangedLocked(rawEvent->when);
- break;
- default:
- ALOG_ASSERT(false); // can't happen
- break;
- }
- }
- count -= batchSize;
- rawEvent += batchSize;
- }
-}
-
-void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
- ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
- if (deviceIndex >= 0) {
- ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
- return;
- }
-
- InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
- uint32_t classes = mEventHub->getDeviceClasses(deviceId);
-
- InputDevice* device = createDeviceLocked(deviceId, identifier, classes);
- device->configure(when, &mConfig, 0);
- device->reset(when);
-
- if (device->isIgnored()) {
- ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
- identifier.name.string());
- } else {
- ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
- identifier.name.string(), device->getSources());
- }
-
- mDevices.add(deviceId, device);
- bumpGenerationLocked();
-}
-
-void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
- InputDevice* device = NULL;
- ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
- if (deviceIndex < 0) {
- ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
- return;
- }
-
- device = mDevices.valueAt(deviceIndex);
- mDevices.removeItemsAt(deviceIndex, 1);
- bumpGenerationLocked();
-
- if (device->isIgnored()) {
- ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
- device->getId(), device->getName().string());
- } else {
- ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
- device->getId(), device->getName().string(), device->getSources());
- }
-
- device->reset(when);
- delete device;
-}
-
-InputDevice* InputReader::createDeviceLocked(int32_t deviceId,
- const InputDeviceIdentifier& identifier, uint32_t classes) {
- InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
- identifier, classes);
-
- // External devices.
- if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
- device->setExternal(true);
- }
-
- // Switch-like devices.
- if (classes & INPUT_DEVICE_CLASS_SWITCH) {
- device->addMapper(new SwitchInputMapper(device));
- }
-
- // Vibrator-like devices.
- if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
- device->addMapper(new VibratorInputMapper(device));
- }
-
- // Keyboard-like devices.
- uint32_t keyboardSource = 0;
- int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
- if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
- keyboardSource |= AINPUT_SOURCE_KEYBOARD;
- }
- if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
- keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
- }
- if (classes & INPUT_DEVICE_CLASS_DPAD) {
- keyboardSource |= AINPUT_SOURCE_DPAD;
- }
- if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
- keyboardSource |= AINPUT_SOURCE_GAMEPAD;
- }
-
- if (keyboardSource != 0) {
- device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
- }
-
- // Cursor-like devices.
- if (classes & INPUT_DEVICE_CLASS_CURSOR) {
- device->addMapper(new CursorInputMapper(device));
- }
-
- // Touchscreens and touchpad devices.
- if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
- device->addMapper(new MultiTouchInputMapper(device));
- } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
- device->addMapper(new SingleTouchInputMapper(device));
- }
-
- // Joystick-like devices.
- if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
- device->addMapper(new JoystickInputMapper(device));
- }
-
- return device;
-}
-
-void InputReader::processEventsForDeviceLocked(int32_t deviceId,
- const RawEvent* rawEvents, size_t count) {
- ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
- if (deviceIndex < 0) {
- ALOGW("Discarding event for unknown deviceId %d.", deviceId);
- return;
- }
-
- InputDevice* device = mDevices.valueAt(deviceIndex);
- if (device->isIgnored()) {
- //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
- return;
- }
-
- device->process(rawEvents, count);
-}
-
-void InputReader::timeoutExpiredLocked(nsecs_t when) {
- for (size_t i = 0; i < mDevices.size(); i++) {
- InputDevice* device = mDevices.valueAt(i);
- if (!device->isIgnored()) {
- device->timeoutExpired(when);
- }
- }
-}
-
-void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
- // Reset global meta state because it depends on the list of all configured devices.
- updateGlobalMetaStateLocked();
-
- // Enqueue configuration changed.
- NotifyConfigurationChangedArgs args(when);
- mQueuedListener->notifyConfigurationChanged(&args);
-}
-
-void InputReader::refreshConfigurationLocked(uint32_t changes) {
- mPolicy->getReaderConfiguration(&mConfig);
- mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
-
- if (changes) {
- ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
- nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
-
- if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
- mEventHub->requestReopenDevices();
- } else {
- for (size_t i = 0; i < mDevices.size(); i++) {
- InputDevice* device = mDevices.valueAt(i);
- device->configure(now, &mConfig, changes);
- }
- }
- }
-}
-
-void InputReader::updateGlobalMetaStateLocked() {
- mGlobalMetaState = 0;
-
- for (size_t i = 0; i < mDevices.size(); i++) {
- InputDevice* device = mDevices.valueAt(i);
- mGlobalMetaState |= device->getMetaState();
- }
-}
-
-int32_t InputReader::getGlobalMetaStateLocked() {
- return mGlobalMetaState;
-}
-
-void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
- mDisableVirtualKeysTimeout = time;
-}
-
-bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
- InputDevice* device, int32_t keyCode, int32_t scanCode) {
- if (now < mDisableVirtualKeysTimeout) {
- ALOGI("Dropping virtual key from device %s because virtual keys are "
- "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
- device->getName().string(),
- (mDisableVirtualKeysTimeout - now) * 0.000001,
- keyCode, scanCode);
- return true;
- } else {
- return false;
- }
-}
-
-void InputReader::fadePointerLocked() {
- for (size_t i = 0; i < mDevices.size(); i++) {
- InputDevice* device = mDevices.valueAt(i);
- device->fadePointer();
- }
-}
-
-void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
- if (when < mNextTimeout) {
- mNextTimeout = when;
- mEventHub->wake();
- }
-}
-
-int32_t InputReader::bumpGenerationLocked() {
- return ++mGeneration;
-}
-
-void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
- AutoMutex _l(mLock);
- getInputDevicesLocked(outInputDevices);
-}
-
-void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
- outInputDevices.clear();
-
- size_t numDevices = mDevices.size();
- for (size_t i = 0; i < numDevices; i++) {
- InputDevice* device = mDevices.valueAt(i);
- if (!device->isIgnored()) {
- outInputDevices.push();
- device->getDeviceInfo(&outInputDevices.editTop());
- }
- }
-}
-
-int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
- int32_t keyCode) {
- AutoMutex _l(mLock);
-
- return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
-}
-
-int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
- int32_t scanCode) {
- AutoMutex _l(mLock);
-
- return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
-}
-
-int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
- AutoMutex _l(mLock);
-
- return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
-}
-
-int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
- GetStateFunc getStateFunc) {
- int32_t result = AKEY_STATE_UNKNOWN;
- if (deviceId >= 0) {
- ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
- if (deviceIndex >= 0) {
- InputDevice* device = mDevices.valueAt(deviceIndex);
- if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
- result = (device->*getStateFunc)(sourceMask, code);
- }
- }
- } else {
- size_t numDevices = mDevices.size();
- for (size_t i = 0; i < numDevices; i++) {
- InputDevice* device = mDevices.valueAt(i);
- if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
- // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
- // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
- int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
- if (currentResult >= AKEY_STATE_DOWN) {
- return currentResult;
- } else if (currentResult == AKEY_STATE_UP) {
- result = currentResult;
- }
- }
- }
- }
- return result;
-}
-
-bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
- size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
- AutoMutex _l(mLock);
-
- memset(outFlags, 0, numCodes);
- return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
-}
-
-bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
- size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
- bool result = false;
- if (deviceId >= 0) {
- ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
- if (deviceIndex >= 0) {
- InputDevice* device = mDevices.valueAt(deviceIndex);
- if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
- result = device->markSupportedKeyCodes(sourceMask,
- numCodes, keyCodes, outFlags);
- }
- }
- } else {
- size_t numDevices = mDevices.size();
- for (size_t i = 0; i < numDevices; i++) {
- InputDevice* device = mDevices.valueAt(i);
- if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
- result |= device->markSupportedKeyCodes(sourceMask,
- numCodes, keyCodes, outFlags);
- }
- }
- }
- return result;
-}
-
-void InputReader::requestRefreshConfiguration(uint32_t changes) {
- AutoMutex _l(mLock);
-
- if (changes) {
- bool needWake = !mConfigurationChangesToRefresh;
- mConfigurationChangesToRefresh |= changes;
-
- if (needWake) {
- mEventHub->wake();
- }
- }
-}
-
-void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
- ssize_t repeat, int32_t token) {
- AutoMutex _l(mLock);
-
- ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
- if (deviceIndex >= 0) {
- InputDevice* device = mDevices.valueAt(deviceIndex);
- device->vibrate(pattern, patternSize, repeat, token);
- }
-}
-
-void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
- AutoMutex _l(mLock);
-
- ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
- if (deviceIndex >= 0) {
- InputDevice* device = mDevices.valueAt(deviceIndex);
- device->cancelVibrate(token);
- }
-}
-
-void InputReader::dump(String8& dump) {
- AutoMutex _l(mLock);
-
- mEventHub->dump(dump);
- dump.append("\n");
-
- dump.append("Input Reader State:\n");
-
- for (size_t i = 0; i < mDevices.size(); i++) {
- mDevices.valueAt(i)->dump(dump);
- }
-
- dump.append(INDENT "Configuration:\n");
- dump.append(INDENT2 "ExcludedDeviceNames: [");
- for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
- if (i != 0) {
- dump.append(", ");
- }
- dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
- }
- dump.append("]\n");
- dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
- mConfig.virtualKeyQuietTime * 0.000001f);
-
- dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
- "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
- mConfig.pointerVelocityControlParameters.scale,
- mConfig.pointerVelocityControlParameters.lowThreshold,
- mConfig.pointerVelocityControlParameters.highThreshold,
- mConfig.pointerVelocityControlParameters.acceleration);
-
- dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
- "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
- mConfig.wheelVelocityControlParameters.scale,
- mConfig.wheelVelocityControlParameters.lowThreshold,
- mConfig.wheelVelocityControlParameters.highThreshold,
- mConfig.wheelVelocityControlParameters.acceleration);
-
- dump.appendFormat(INDENT2 "PointerGesture:\n");
- dump.appendFormat(INDENT3 "Enabled: %s\n",
- toString(mConfig.pointerGesturesEnabled));
- dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
- mConfig.pointerGestureQuietInterval * 0.000001f);
- dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
- mConfig.pointerGestureDragMinSwitchSpeed);
- dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
- mConfig.pointerGestureTapInterval * 0.000001f);
- dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
- mConfig.pointerGestureTapDragInterval * 0.000001f);
- dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
- mConfig.pointerGestureTapSlop);
- dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
- mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
- dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
- mConfig.pointerGestureMultitouchMinDistance);
- dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
- mConfig.pointerGestureSwipeTransitionAngleCosine);
- dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
- mConfig.pointerGestureSwipeMaxWidthRatio);
- dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
- mConfig.pointerGestureMovementSpeedRatio);
- dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
- mConfig.pointerGestureZoomSpeedRatio);
-}
-
-void InputReader::monitor() {
- // Acquire and release the lock to ensure that the reader has not deadlocked.
- mLock.lock();
- mEventHub->wake();
- mReaderIsAliveCondition.wait(mLock);
- mLock.unlock();
-
- // Check the EventHub
- mEventHub->monitor();
-}
-
-
-// --- InputReader::ContextImpl ---
-
-InputReader::ContextImpl::ContextImpl(InputReader* reader) :
- mReader(reader) {
-}
-
-void InputReader::ContextImpl::updateGlobalMetaState() {
- // lock is already held by the input loop
- mReader->updateGlobalMetaStateLocked();
-}
-
-int32_t InputReader::ContextImpl::getGlobalMetaState() {
- // lock is already held by the input loop
- return mReader->getGlobalMetaStateLocked();
-}
-
-void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
- // lock is already held by the input loop
- mReader->disableVirtualKeysUntilLocked(time);
-}
-
-bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
- InputDevice* device, int32_t keyCode, int32_t scanCode) {
- // lock is already held by the input loop
- return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
-}
-
-void InputReader::ContextImpl::fadePointer() {
- // lock is already held by the input loop
- mReader->fadePointerLocked();
-}
-
-void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
- // lock is already held by the input loop
- mReader->requestTimeoutAtTimeLocked(when);
-}
-
-int32_t InputReader::ContextImpl::bumpGeneration() {
- // lock is already held by the input loop
- return mReader->bumpGenerationLocked();
-}
-
-InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
- return mReader->mPolicy.get();
-}
-
-InputListenerInterface* InputReader::ContextImpl::getListener() {
- return mReader->mQueuedListener.get();
-}
-
-EventHubInterface* InputReader::ContextImpl::getEventHub() {
- return mReader->mEventHub.get();
-}
-
-
-// --- InputReaderThread ---
-
-InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
- Thread(/*canCallJava*/ true), mReader(reader) {
-}
-
-InputReaderThread::~InputReaderThread() {
-}
-
-bool InputReaderThread::threadLoop() {
- mReader->loopOnce();
- return true;
-}
-
-
-// --- InputDevice ---
-
-InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
- const InputDeviceIdentifier& identifier, uint32_t classes) :
- mContext(context), mId(id), mGeneration(generation),
- mIdentifier(identifier), mClasses(classes),
- mSources(0), mIsExternal(false), mDropUntilNextSync(false) {
-}
-
-InputDevice::~InputDevice() {
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- delete mMappers[i];
- }
- mMappers.clear();
-}
-
-void InputDevice::dump(String8& dump) {
- InputDeviceInfo deviceInfo;
- getDeviceInfo(& deviceInfo);
-
- dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
- deviceInfo.getDisplayName().string());
- dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
- dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
- dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
- dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
-
- const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
- if (!ranges.isEmpty()) {
- dump.append(INDENT2 "Motion Ranges:\n");
- for (size_t i = 0; i < ranges.size(); i++) {
- const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
- const char* label = getAxisLabel(range.axis);
- char name[32];
- if (label) {
- strncpy(name, label, sizeof(name));
- name[sizeof(name) - 1] = '\0';
- } else {
- snprintf(name, sizeof(name), "%d", range.axis);
- }
- dump.appendFormat(INDENT3 "%s: source=0x%08x, "
- "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
- name, range.source, range.min, range.max, range.flat, range.fuzz,
- range.resolution);
- }
- }
-
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->dump(dump);
- }
-}
-
-void InputDevice::addMapper(InputMapper* mapper) {
- mMappers.add(mapper);
-}
-
-void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
- mSources = 0;
-
- if (!isIgnored()) {
- if (!changes) { // first time only
- mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
- }
-
- if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
- if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
- sp<KeyCharacterMap> keyboardLayout =
- mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier.descriptor);
- if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
- bumpGeneration();
- }
- }
- }
-
- if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
- if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
- String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
- if (mAlias != alias) {
- mAlias = alias;
- bumpGeneration();
- }
- }
- }
-
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->configure(when, config, changes);
- mSources |= mapper->getSources();
- }
- }
-}
-
-void InputDevice::reset(nsecs_t when) {
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->reset(when);
- }
-
- mContext->updateGlobalMetaState();
-
- notifyReset(when);
-}
-
-void InputDevice::process(const RawEvent* rawEvents, size_t count) {
- // Process all of the events in order for each mapper.
- // We cannot simply ask each mapper to process them in bulk because mappers may
- // have side-effects that must be interleaved. For example, joystick movement events and
- // gamepad button presses are handled by different mappers but they should be dispatched
- // in the order received.
- size_t numMappers = mMappers.size();
- for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
-#if DEBUG_RAW_EVENTS
- ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
- rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
- rawEvent->when);
-#endif
-
- if (mDropUntilNextSync) {
- if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
- mDropUntilNextSync = false;
-#if DEBUG_RAW_EVENTS
- ALOGD("Recovered from input event buffer overrun.");
-#endif
- } else {
-#if DEBUG_RAW_EVENTS
- ALOGD("Dropped input event while waiting for next input sync.");
-#endif
- }
- } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
- ALOGI("Detected input event buffer overrun for device %s.", getName().string());
- mDropUntilNextSync = true;
- reset(rawEvent->when);
- } else {
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->process(rawEvent);
- }
- }
- }
-}
-
-void InputDevice::timeoutExpired(nsecs_t when) {
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->timeoutExpired(when);
- }
-}
-
-void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
- outDeviceInfo->initialize(mId, mGeneration, mIdentifier, mAlias, mIsExternal);
-
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->populateDeviceInfo(outDeviceInfo);
- }
-}
-
-int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
- return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
-}
-
-int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
- return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
-}
-
-int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
- return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
-}
-
-int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
- int32_t result = AKEY_STATE_UNKNOWN;
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
- // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
- // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
- int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
- if (currentResult >= AKEY_STATE_DOWN) {
- return currentResult;
- } else if (currentResult == AKEY_STATE_UP) {
- result = currentResult;
- }
- }
- }
- return result;
-}
-
-bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags) {
- bool result = false;
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
- result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
- }
- }
- return result;
-}
-
-void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
- int32_t token) {
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->vibrate(pattern, patternSize, repeat, token);
- }
-}
-
-void InputDevice::cancelVibrate(int32_t token) {
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->cancelVibrate(token);
- }
-}
-
-int32_t InputDevice::getMetaState() {
- int32_t result = 0;
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- result |= mapper->getMetaState();
- }
- return result;
-}
-
-void InputDevice::fadePointer() {
- size_t numMappers = mMappers.size();
- for (size_t i = 0; i < numMappers; i++) {
- InputMapper* mapper = mMappers[i];
- mapper->fadePointer();
- }
-}
-
-void InputDevice::bumpGeneration() {
- mGeneration = mContext->bumpGeneration();
-}
-
-void InputDevice::notifyReset(nsecs_t when) {
- NotifyDeviceResetArgs args(when, mId);
- mContext->getListener()->notifyDeviceReset(&args);
-}
-
-
-// --- CursorButtonAccumulator ---
-
-CursorButtonAccumulator::CursorButtonAccumulator() {
- clearButtons();
-}
-
-void CursorButtonAccumulator::reset(InputDevice* device) {
- mBtnLeft = device->isKeyPressed(BTN_LEFT);
- mBtnRight = device->isKeyPressed(BTN_RIGHT);
- mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
- mBtnBack = device->isKeyPressed(BTN_BACK);
- mBtnSide = device->isKeyPressed(BTN_SIDE);
- mBtnForward = device->isKeyPressed(BTN_FORWARD);
- mBtnExtra = device->isKeyPressed(BTN_EXTRA);
- mBtnTask = device->isKeyPressed(BTN_TASK);
-}
-
-void CursorButtonAccumulator::clearButtons() {
- mBtnLeft = 0;
- mBtnRight = 0;
- mBtnMiddle = 0;
- mBtnBack = 0;
- mBtnSide = 0;
- mBtnForward = 0;
- mBtnExtra = 0;
- mBtnTask = 0;
-}
-
-void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
- if (rawEvent->type == EV_KEY) {
- switch (rawEvent->code) {
- case BTN_LEFT:
- mBtnLeft = rawEvent->value;
- break;
- case BTN_RIGHT:
- mBtnRight = rawEvent->value;
- break;
- case BTN_MIDDLE:
- mBtnMiddle = rawEvent->value;
- break;
- case BTN_BACK:
- mBtnBack = rawEvent->value;
- break;
- case BTN_SIDE:
- mBtnSide = rawEvent->value;
- break;
- case BTN_FORWARD:
- mBtnForward = rawEvent->value;
- break;
- case BTN_EXTRA:
- mBtnExtra = rawEvent->value;
- break;
- case BTN_TASK:
- mBtnTask = rawEvent->value;
- break;
- }
- }
-}
-
-uint32_t CursorButtonAccumulator::getButtonState() const {
- uint32_t result = 0;
- if (mBtnLeft) {
- result |= AMOTION_EVENT_BUTTON_PRIMARY;
- }
- if (mBtnRight) {
- result |= AMOTION_EVENT_BUTTON_SECONDARY;
- }
- if (mBtnMiddle) {
- result |= AMOTION_EVENT_BUTTON_TERTIARY;
- }
- if (mBtnBack || mBtnSide) {
- result |= AMOTION_EVENT_BUTTON_BACK;
- }
- if (mBtnForward || mBtnExtra) {
- result |= AMOTION_EVENT_BUTTON_FORWARD;
- }
- return result;
-}
-
-
-// --- CursorMotionAccumulator ---
-
-CursorMotionAccumulator::CursorMotionAccumulator() {
- clearRelativeAxes();
-}
-
-void CursorMotionAccumulator::reset(InputDevice* device) {
- clearRelativeAxes();
-}
-
-void CursorMotionAccumulator::clearRelativeAxes() {
- mRelX = 0;
- mRelY = 0;
-}
-
-void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
- if (rawEvent->type == EV_REL) {
- switch (rawEvent->code) {
- case REL_X:
- mRelX = rawEvent->value;
- break;
- case REL_Y:
- mRelY = rawEvent->value;
- break;
- }
- }
-}
-
-void CursorMotionAccumulator::finishSync() {
- clearRelativeAxes();
-}
-
-
-// --- CursorScrollAccumulator ---
-
-CursorScrollAccumulator::CursorScrollAccumulator() :
- mHaveRelWheel(false), mHaveRelHWheel(false) {
- clearRelativeAxes();
-}
-
-void CursorScrollAccumulator::configure(InputDevice* device) {
- mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
- mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
-}
-
-void CursorScrollAccumulator::reset(InputDevice* device) {
- clearRelativeAxes();
-}
-
-void CursorScrollAccumulator::clearRelativeAxes() {
- mRelWheel = 0;
- mRelHWheel = 0;
-}
-
-void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
- if (rawEvent->type == EV_REL) {
- switch (rawEvent->code) {
- case REL_WHEEL:
- mRelWheel = rawEvent->value;
- break;
- case REL_HWHEEL:
- mRelHWheel = rawEvent->value;
- break;
- }
- }
-}
-
-void CursorScrollAccumulator::finishSync() {
- clearRelativeAxes();
-}
-
-
-// --- TouchButtonAccumulator ---
-
-TouchButtonAccumulator::TouchButtonAccumulator() :
- mHaveBtnTouch(false), mHaveStylus(false) {
- clearButtons();
-}
-
-void TouchButtonAccumulator::configure(InputDevice* device) {
- mHaveBtnTouch = device->hasKey(BTN_TOUCH);
- mHaveStylus = device->hasKey(BTN_TOOL_PEN)
- || device->hasKey(BTN_TOOL_RUBBER)
- || device->hasKey(BTN_TOOL_BRUSH)
- || device->hasKey(BTN_TOOL_PENCIL)
- || device->hasKey(BTN_TOOL_AIRBRUSH);
-}
-
-void TouchButtonAccumulator::reset(InputDevice* device) {
- mBtnTouch = device->isKeyPressed(BTN_TOUCH);
- mBtnStylus = device->isKeyPressed(BTN_STYLUS);
- mBtnStylus2 = device->isKeyPressed(BTN_STYLUS);
- mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
- mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
- mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
- mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
- mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
- mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
- mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
- mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
- mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
- mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
- mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
-}
-
-void TouchButtonAccumulator::clearButtons() {
- mBtnTouch = 0;
- mBtnStylus = 0;
- mBtnStylus2 = 0;
- mBtnToolFinger = 0;
- mBtnToolPen = 0;
- mBtnToolRubber = 0;
- mBtnToolBrush = 0;
- mBtnToolPencil = 0;
- mBtnToolAirbrush = 0;
- mBtnToolMouse = 0;
- mBtnToolLens = 0;
- mBtnToolDoubleTap = 0;
- mBtnToolTripleTap = 0;
- mBtnToolQuadTap = 0;
-}
-
-void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
- if (rawEvent->type == EV_KEY) {
- switch (rawEvent->code) {
- case BTN_TOUCH:
- mBtnTouch = rawEvent->value;
- break;
- case BTN_STYLUS:
- mBtnStylus = rawEvent->value;
- break;
- case BTN_STYLUS2:
- mBtnStylus2 = rawEvent->value;
- break;
- case BTN_TOOL_FINGER:
- mBtnToolFinger = rawEvent->value;
- break;
- case BTN_TOOL_PEN:
- mBtnToolPen = rawEvent->value;
- break;
- case BTN_TOOL_RUBBER:
- mBtnToolRubber = rawEvent->value;
- break;
- case BTN_TOOL_BRUSH:
- mBtnToolBrush = rawEvent->value;
- break;
- case BTN_TOOL_PENCIL:
- mBtnToolPencil = rawEvent->value;
- break;
- case BTN_TOOL_AIRBRUSH:
- mBtnToolAirbrush = rawEvent->value;
- break;
- case BTN_TOOL_MOUSE:
- mBtnToolMouse = rawEvent->value;
- break;
- case BTN_TOOL_LENS:
- mBtnToolLens = rawEvent->value;
- break;
- case BTN_TOOL_DOUBLETAP:
- mBtnToolDoubleTap = rawEvent->value;
- break;
- case BTN_TOOL_TRIPLETAP:
- mBtnToolTripleTap = rawEvent->value;
- break;
- case BTN_TOOL_QUADTAP:
- mBtnToolQuadTap = rawEvent->value;
- break;
- }
- }
-}
-
-uint32_t TouchButtonAccumulator::getButtonState() const {
- uint32_t result = 0;
- if (mBtnStylus) {
- result |= AMOTION_EVENT_BUTTON_SECONDARY;
- }
- if (mBtnStylus2) {
- result |= AMOTION_EVENT_BUTTON_TERTIARY;
- }
- return result;
-}
-
-int32_t TouchButtonAccumulator::getToolType() const {
- if (mBtnToolMouse || mBtnToolLens) {
- return AMOTION_EVENT_TOOL_TYPE_MOUSE;
- }
- if (mBtnToolRubber) {
- return AMOTION_EVENT_TOOL_TYPE_ERASER;
- }
- if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
- return AMOTION_EVENT_TOOL_TYPE_STYLUS;
- }
- if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
- return AMOTION_EVENT_TOOL_TYPE_FINGER;
- }
- return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
-}
-
-bool TouchButtonAccumulator::isToolActive() const {
- return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
- || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
- || mBtnToolMouse || mBtnToolLens
- || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
-}
-
-bool TouchButtonAccumulator::isHovering() const {
- return mHaveBtnTouch && !mBtnTouch;
-}
-
-bool TouchButtonAccumulator::hasStylus() const {
- return mHaveStylus;
-}
-
-
-// --- RawPointerAxes ---
-
-RawPointerAxes::RawPointerAxes() {
- clear();
-}
-
-void RawPointerAxes::clear() {
- x.clear();
- y.clear();
- pressure.clear();
- touchMajor.clear();
- touchMinor.clear();
- toolMajor.clear();
- toolMinor.clear();
- orientation.clear();
- distance.clear();
- tiltX.clear();
- tiltY.clear();
- trackingId.clear();
- slot.clear();
-}
-
-
-// --- RawPointerData ---
-
-RawPointerData::RawPointerData() {
- clear();
-}
-
-void RawPointerData::clear() {
- pointerCount = 0;
- clearIdBits();
-}
-
-void RawPointerData::copyFrom(const RawPointerData& other) {
- pointerCount = other.pointerCount;
- hoveringIdBits = other.hoveringIdBits;
- touchingIdBits = other.touchingIdBits;
-
- for (uint32_t i = 0; i < pointerCount; i++) {
- pointers[i] = other.pointers[i];
-
- int id = pointers[i].id;
- idToIndex[id] = other.idToIndex[id];
- }
-}
-
-void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
- float x = 0, y = 0;
- uint32_t count = touchingIdBits.count();
- if (count) {
- for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- const Pointer& pointer = pointerForId(id);
- x += pointer.x;
- y += pointer.y;
- }
- x /= count;
- y /= count;
- }
- *outX = x;
- *outY = y;
-}
-
-
-// --- CookedPointerData ---
-
-CookedPointerData::CookedPointerData() {
- clear();
-}
-
-void CookedPointerData::clear() {
- pointerCount = 0;
- hoveringIdBits.clear();
- touchingIdBits.clear();
-}
-
-void CookedPointerData::copyFrom(const CookedPointerData& other) {
- pointerCount = other.pointerCount;
- hoveringIdBits = other.hoveringIdBits;
- touchingIdBits = other.touchingIdBits;
-
- for (uint32_t i = 0; i < pointerCount; i++) {
- pointerProperties[i].copyFrom(other.pointerProperties[i]);
- pointerCoords[i].copyFrom(other.pointerCoords[i]);
-
- int id = pointerProperties[i].id;
- idToIndex[id] = other.idToIndex[id];
- }
-}
-
-
-// --- SingleTouchMotionAccumulator ---
-
-SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
- clearAbsoluteAxes();
-}
-
-void SingleTouchMotionAccumulator::reset(InputDevice* device) {
- mAbsX = device->getAbsoluteAxisValue(ABS_X);
- mAbsY = device->getAbsoluteAxisValue(ABS_Y);
- mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
- mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
- mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
- mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
- mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
-}
-
-void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
- mAbsX = 0;
- mAbsY = 0;
- mAbsPressure = 0;
- mAbsToolWidth = 0;
- mAbsDistance = 0;
- mAbsTiltX = 0;
- mAbsTiltY = 0;
-}
-
-void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
- if (rawEvent->type == EV_ABS) {
- switch (rawEvent->code) {
- case ABS_X:
- mAbsX = rawEvent->value;
- break;
- case ABS_Y:
- mAbsY = rawEvent->value;
- break;
- case ABS_PRESSURE:
- mAbsPressure = rawEvent->value;
- break;
- case ABS_TOOL_WIDTH:
- mAbsToolWidth = rawEvent->value;
- break;
- case ABS_DISTANCE:
- mAbsDistance = rawEvent->value;
- break;
- case ABS_TILT_X:
- mAbsTiltX = rawEvent->value;
- break;
- case ABS_TILT_Y:
- mAbsTiltY = rawEvent->value;
- break;
- }
- }
-}
-
-
-// --- MultiTouchMotionAccumulator ---
-
-MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
- mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
- mHaveStylus(false) {
-}
-
-MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
- delete[] mSlots;
-}
-
-void MultiTouchMotionAccumulator::configure(InputDevice* device,
- size_t slotCount, bool usingSlotsProtocol) {
- mSlotCount = slotCount;
- mUsingSlotsProtocol = usingSlotsProtocol;
- mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
-
- delete[] mSlots;
- mSlots = new Slot[slotCount];
-}
-
-void MultiTouchMotionAccumulator::reset(InputDevice* device) {
- // Unfortunately there is no way to read the initial contents of the slots.
- // So when we reset the accumulator, we must assume they are all zeroes.
- if (mUsingSlotsProtocol) {
- // Query the driver for the current slot index and use it as the initial slot
- // before we start reading events from the device. It is possible that the
- // current slot index will not be the same as it was when the first event was
- // written into the evdev buffer, which means the input mapper could start
- // out of sync with the initial state of the events in the evdev buffer.
- // In the extremely unlikely case that this happens, the data from
- // two slots will be confused until the next ABS_MT_SLOT event is received.
- // This can cause the touch point to "jump", but at least there will be
- // no stuck touches.
- int32_t initialSlot;
- status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
- ABS_MT_SLOT, &initialSlot);
- if (status) {
- ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
- initialSlot = -1;
- }
- clearSlots(initialSlot);
- } else {
- clearSlots(-1);
- }
-}
-
-void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
- if (mSlots) {
- for (size_t i = 0; i < mSlotCount; i++) {
- mSlots[i].clear();
- }
- }
- mCurrentSlot = initialSlot;
-}
-
-void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
- if (rawEvent->type == EV_ABS) {
-#if DEBUG_POINTERS
- bool newSlot = false;
-#endif
- if (mUsingSlotsProtocol) {
- if (rawEvent->code == ABS_MT_SLOT) {
- mCurrentSlot = rawEvent->value;
-#if DEBUG_POINTERS
- newSlot = true;
-#endif
- }
- } else if (mCurrentSlot < 0) {
- mCurrentSlot = 0;
- }
-
- if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
-#if DEBUG_POINTERS
- if (newSlot) {
- ALOGW("MultiTouch device emitted invalid slot index %d but it "
- "should be between 0 and %d; ignoring this slot.",
- mCurrentSlot, mSlotCount - 1);
- }
-#endif
- } else {
- Slot* slot = &mSlots[mCurrentSlot];
-
- switch (rawEvent->code) {
- case ABS_MT_POSITION_X:
- slot->mInUse = true;
- slot->mAbsMTPositionX = rawEvent->value;
- break;
- case ABS_MT_POSITION_Y:
- slot->mInUse = true;
- slot->mAbsMTPositionY = rawEvent->value;
- break;
- case ABS_MT_TOUCH_MAJOR:
- slot->mInUse = true;
- slot->mAbsMTTouchMajor = rawEvent->value;
- break;
- case ABS_MT_TOUCH_MINOR:
- slot->mInUse = true;
- slot->mAbsMTTouchMinor = rawEvent->value;
- slot->mHaveAbsMTTouchMinor = true;
- break;
- case ABS_MT_WIDTH_MAJOR:
- slot->mInUse = true;
- slot->mAbsMTWidthMajor = rawEvent->value;
- break;
- case ABS_MT_WIDTH_MINOR:
- slot->mInUse = true;
- slot->mAbsMTWidthMinor = rawEvent->value;
- slot->mHaveAbsMTWidthMinor = true;
- break;
- case ABS_MT_ORIENTATION:
- slot->mInUse = true;
- slot->mAbsMTOrientation = rawEvent->value;
- break;
- case ABS_MT_TRACKING_ID:
- if (mUsingSlotsProtocol && rawEvent->value < 0) {
- // The slot is no longer in use but it retains its previous contents,
- // which may be reused for subsequent touches.
- slot->mInUse = false;
- } else {
- slot->mInUse = true;
- slot->mAbsMTTrackingId = rawEvent->value;
- }
- break;
- case ABS_MT_PRESSURE:
- slot->mInUse = true;
- slot->mAbsMTPressure = rawEvent->value;
- break;
- case ABS_MT_DISTANCE:
- slot->mInUse = true;
- slot->mAbsMTDistance = rawEvent->value;
- break;
- case ABS_MT_TOOL_TYPE:
- slot->mInUse = true;
- slot->mAbsMTToolType = rawEvent->value;
- slot->mHaveAbsMTToolType = true;
- break;
- }
- }
- } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
- // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
- mCurrentSlot += 1;
- }
-}
-
-void MultiTouchMotionAccumulator::finishSync() {
- if (!mUsingSlotsProtocol) {
- clearSlots(-1);
- }
-}
-
-bool MultiTouchMotionAccumulator::hasStylus() const {
- return mHaveStylus;
-}
-
-
-// --- MultiTouchMotionAccumulator::Slot ---
-
-MultiTouchMotionAccumulator::Slot::Slot() {
- clear();
-}
-
-void MultiTouchMotionAccumulator::Slot::clear() {
- mInUse = false;
- mHaveAbsMTTouchMinor = false;
- mHaveAbsMTWidthMinor = false;
- mHaveAbsMTToolType = false;
- mAbsMTPositionX = 0;
- mAbsMTPositionY = 0;
- mAbsMTTouchMajor = 0;
- mAbsMTTouchMinor = 0;
- mAbsMTWidthMajor = 0;
- mAbsMTWidthMinor = 0;
- mAbsMTOrientation = 0;
- mAbsMTTrackingId = -1;
- mAbsMTPressure = 0;
- mAbsMTDistance = 0;
- mAbsMTToolType = 0;
-}
-
-int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
- if (mHaveAbsMTToolType) {
- switch (mAbsMTToolType) {
- case MT_TOOL_FINGER:
- return AMOTION_EVENT_TOOL_TYPE_FINGER;
- case MT_TOOL_PEN:
- return AMOTION_EVENT_TOOL_TYPE_STYLUS;
- }
- }
- return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
-}
-
-
-// --- InputMapper ---
-
-InputMapper::InputMapper(InputDevice* device) :
- mDevice(device), mContext(device->getContext()) {
-}
-
-InputMapper::~InputMapper() {
-}
-
-void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
- info->addSource(getSources());
-}
-
-void InputMapper::dump(String8& dump) {
-}
-
-void InputMapper::configure(nsecs_t when,
- const InputReaderConfiguration* config, uint32_t changes) {
-}
-
-void InputMapper::reset(nsecs_t when) {
-}
-
-void InputMapper::timeoutExpired(nsecs_t when) {
-}
-
-int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
- return AKEY_STATE_UNKNOWN;
-}
-
-int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
- return AKEY_STATE_UNKNOWN;
-}
-
-int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
- return AKEY_STATE_UNKNOWN;
-}
-
-bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags) {
- return false;
-}
-
-void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
- int32_t token) {
-}
-
-void InputMapper::cancelVibrate(int32_t token) {
-}
-
-int32_t InputMapper::getMetaState() {
- return 0;
-}
-
-void InputMapper::fadePointer() {
-}
-
-status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
- return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
-}
-
-void InputMapper::bumpGeneration() {
- mDevice->bumpGeneration();
-}
-
-void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
- const RawAbsoluteAxisInfo& axis, const char* name) {
- if (axis.valid) {
- dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
- name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
- } else {
- dump.appendFormat(INDENT4 "%s: unknown range\n", name);
- }
-}
-
-
-// --- SwitchInputMapper ---
-
-SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
- InputMapper(device), mUpdatedSwitchValues(0), mUpdatedSwitchMask(0) {
-}
-
-SwitchInputMapper::~SwitchInputMapper() {
-}
-
-uint32_t SwitchInputMapper::getSources() {
- return AINPUT_SOURCE_SWITCH;
-}
-
-void SwitchInputMapper::process(const RawEvent* rawEvent) {
- switch (rawEvent->type) {
- case EV_SW:
- processSwitch(rawEvent->code, rawEvent->value);
- break;
-
- case EV_SYN:
- if (rawEvent->code == SYN_REPORT) {
- sync(rawEvent->when);
- }
- }
-}
-
-void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
- if (switchCode >= 0 && switchCode < 32) {
- if (switchValue) {
- mUpdatedSwitchValues |= 1 << switchCode;
- }
- mUpdatedSwitchMask |= 1 << switchCode;
- }
-}
-
-void SwitchInputMapper::sync(nsecs_t when) {
- if (mUpdatedSwitchMask) {
- NotifySwitchArgs args(when, 0, mUpdatedSwitchValues, mUpdatedSwitchMask);
- getListener()->notifySwitch(&args);
-
- mUpdatedSwitchValues = 0;
- mUpdatedSwitchMask = 0;
- }
-}
-
-int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
- return getEventHub()->getSwitchState(getDeviceId(), switchCode);
-}
-
-
-// --- VibratorInputMapper ---
-
-VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
- InputMapper(device), mVibrating(false) {
-}
-
-VibratorInputMapper::~VibratorInputMapper() {
-}
-
-uint32_t VibratorInputMapper::getSources() {
- return 0;
-}
-
-void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
- InputMapper::populateDeviceInfo(info);
-
- info->setVibrator(true);
-}
-
-void VibratorInputMapper::process(const RawEvent* rawEvent) {
- // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
-}
-
-void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
- int32_t token) {
-#if DEBUG_VIBRATOR
- String8 patternStr;
- for (size_t i = 0; i < patternSize; i++) {
- if (i != 0) {
- patternStr.append(", ");
- }
- patternStr.appendFormat("%lld", pattern[i]);
- }
- ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
- getDeviceId(), patternStr.string(), repeat, token);
-#endif
-
- mVibrating = true;
- memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
- mPatternSize = patternSize;
- mRepeat = repeat;
- mToken = token;
- mIndex = -1;
-
- nextStep();
-}
-
-void VibratorInputMapper::cancelVibrate(int32_t token) {
-#if DEBUG_VIBRATOR
- ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
-#endif
-
- if (mVibrating && mToken == token) {
- stopVibrating();
- }
-}
-
-void VibratorInputMapper::timeoutExpired(nsecs_t when) {
- if (mVibrating) {
- if (when >= mNextStepTime) {
- nextStep();
- } else {
- getContext()->requestTimeoutAtTime(mNextStepTime);
- }
- }
-}
-
-void VibratorInputMapper::nextStep() {
- mIndex += 1;
- if (size_t(mIndex) >= mPatternSize) {
- if (mRepeat < 0) {
- // We are done.
- stopVibrating();
- return;
- }
- mIndex = mRepeat;
- }
-
- bool vibratorOn = mIndex & 1;
- nsecs_t duration = mPattern[mIndex];
- if (vibratorOn) {
-#if DEBUG_VIBRATOR
- ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
- getDeviceId(), duration);
-#endif
- getEventHub()->vibrate(getDeviceId(), duration);
- } else {
-#if DEBUG_VIBRATOR
- ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
-#endif
- getEventHub()->cancelVibrate(getDeviceId());
- }
- nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
- mNextStepTime = now + duration;
- getContext()->requestTimeoutAtTime(mNextStepTime);
-#if DEBUG_VIBRATOR
- ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
-#endif
-}
-
-void VibratorInputMapper::stopVibrating() {
- mVibrating = false;
-#if DEBUG_VIBRATOR
- ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
-#endif
- getEventHub()->cancelVibrate(getDeviceId());
-}
-
-void VibratorInputMapper::dump(String8& dump) {
- dump.append(INDENT2 "Vibrator Input Mapper:\n");
- dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
-}
-
-
-// --- KeyboardInputMapper ---
-
-KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
- uint32_t source, int32_t keyboardType) :
- InputMapper(device), mSource(source),
- mKeyboardType(keyboardType) {
-}
-
-KeyboardInputMapper::~KeyboardInputMapper() {
-}
-
-uint32_t KeyboardInputMapper::getSources() {
- return mSource;
-}
-
-void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
- InputMapper::populateDeviceInfo(info);
-
- info->setKeyboardType(mKeyboardType);
- info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
-}
-
-void KeyboardInputMapper::dump(String8& dump) {
- dump.append(INDENT2 "Keyboard Input Mapper:\n");
- dumpParameters(dump);
- dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
- dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
- dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mKeyDowns.size());
- dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
- dump.appendFormat(INDENT3 "DownTime: %lld\n", mDownTime);
-}
-
-
-void KeyboardInputMapper::configure(nsecs_t when,
- const InputReaderConfiguration* config, uint32_t changes) {
- InputMapper::configure(when, config, changes);
-
- if (!changes) { // first time only
- // Configure basic parameters.
- configureParameters();
- }
-
- if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
- if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
- DisplayViewport v;
- if (config->getDisplayInfo(false /*external*/, &v)) {
- mOrientation = v.orientation;
- } else {
- mOrientation = DISPLAY_ORIENTATION_0;
- }
- } else {
- mOrientation = DISPLAY_ORIENTATION_0;
- }
- }
-}
-
-void KeyboardInputMapper::configureParameters() {
- mParameters.orientationAware = false;
- getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
- mParameters.orientationAware);
-
- mParameters.hasAssociatedDisplay = false;
- if (mParameters.orientationAware) {
- mParameters.hasAssociatedDisplay = true;
- }
-}
-
-void KeyboardInputMapper::dumpParameters(String8& dump) {
- dump.append(INDENT3 "Parameters:\n");
- dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
- toString(mParameters.hasAssociatedDisplay));
- dump.appendFormat(INDENT4 "OrientationAware: %s\n",
- toString(mParameters.orientationAware));
-}
-
-void KeyboardInputMapper::reset(nsecs_t when) {
- mMetaState = AMETA_NONE;
- mDownTime = 0;
- mKeyDowns.clear();
- mCurrentHidUsage = 0;
-
- resetLedState();
-
- InputMapper::reset(when);
-}
-
-void KeyboardInputMapper::process(const RawEvent* rawEvent) {
- switch (rawEvent->type) {
- case EV_KEY: {
- int32_t scanCode = rawEvent->code;
- int32_t usageCode = mCurrentHidUsage;
- mCurrentHidUsage = 0;
-
- if (isKeyboardOrGamepadKey(scanCode)) {
- int32_t keyCode;
- uint32_t flags;
- if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, &keyCode, &flags)) {
- keyCode = AKEYCODE_UNKNOWN;
- flags = 0;
- }
- processKey(rawEvent->when, rawEvent->value != 0, keyCode, scanCode, flags);
- }
- break;
- }
- case EV_MSC: {
- if (rawEvent->code == MSC_SCAN) {
- mCurrentHidUsage = rawEvent->value;
- }
- break;
- }
- case EV_SYN: {
- if (rawEvent->code == SYN_REPORT) {
- mCurrentHidUsage = 0;
- }
- }
- }
-}
-
-bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
- return scanCode < BTN_MOUSE
- || scanCode >= KEY_OK
- || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
- || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
-}
-
-void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
- int32_t scanCode, uint32_t policyFlags) {
-
- if (down) {
- // Rotate key codes according to orientation if needed.
- if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
- keyCode = rotateKeyCode(keyCode, mOrientation);
- }
-
- // Add key down.
- ssize_t keyDownIndex = findKeyDown(scanCode);
- if (keyDownIndex >= 0) {
- // key repeat, be sure to use same keycode as before in case of rotation
- keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
- } else {
- // key down
- if ((policyFlags & POLICY_FLAG_VIRTUAL)
- && mContext->shouldDropVirtualKey(when,
- getDevice(), keyCode, scanCode)) {
- return;
- }
-
- mKeyDowns.push();
- KeyDown& keyDown = mKeyDowns.editTop();
- keyDown.keyCode = keyCode;
- keyDown.scanCode = scanCode;
- }
-
- mDownTime = when;
- } else {
- // Remove key down.
- ssize_t keyDownIndex = findKeyDown(scanCode);
- if (keyDownIndex >= 0) {
- // key up, be sure to use same keycode as before in case of rotation
- keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
- mKeyDowns.removeAt(size_t(keyDownIndex));
- } else {
- // key was not actually down
- ALOGI("Dropping key up from device %s because the key was not down. "
- "keyCode=%d, scanCode=%d",
- getDeviceName().string(), keyCode, scanCode);
- return;
- }
- }
-
- bool metaStateChanged = false;
- int32_t oldMetaState = mMetaState;
- int32_t newMetaState = updateMetaState(keyCode, down, oldMetaState);
- if (oldMetaState != newMetaState) {
- mMetaState = newMetaState;
- metaStateChanged = true;
- updateLedState(false);
- }
-
- nsecs_t downTime = mDownTime;
-
- // Key down on external an keyboard should wake the device.
- // We don't do this for internal keyboards to prevent them from waking up in your pocket.
- // For internal keyboards, the key layout file should specify the policy flags for
- // each wake key individually.
- // TODO: Use the input device configuration to control this behavior more finely.
- if (down && getDevice()->isExternal()
- && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
- policyFlags |= POLICY_FLAG_WAKE_DROPPED;
- }
-
- if (metaStateChanged) {
- getContext()->updateGlobalMetaState();
- }
-
- if (down && !isMetaKey(keyCode)) {
- getContext()->fadePointer();
- }
-
- NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
- down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
- AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
- getListener()->notifyKey(&args);
-}
-
-ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
- size_t n = mKeyDowns.size();
- for (size_t i = 0; i < n; i++) {
- if (mKeyDowns[i].scanCode == scanCode) {
- return i;
- }
- }
- return -1;
-}
-
-int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
- return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
-}
-
-int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
- return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
-}
-
-bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags) {
- return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
-}
-
-int32_t KeyboardInputMapper::getMetaState() {
- return mMetaState;
-}
-
-void KeyboardInputMapper::resetLedState() {
- initializeLedState(mCapsLockLedState, LED_CAPSL);
- initializeLedState(mNumLockLedState, LED_NUML);
- initializeLedState(mScrollLockLedState, LED_SCROLLL);
-
- updateLedState(true);
-}
-
-void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
- ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
- ledState.on = false;
-}
-
-void KeyboardInputMapper::updateLedState(bool reset) {
- updateLedStateForModifier(mCapsLockLedState, LED_CAPSL,
- AMETA_CAPS_LOCK_ON, reset);
- updateLedStateForModifier(mNumLockLedState, LED_NUML,
- AMETA_NUM_LOCK_ON, reset);
- updateLedStateForModifier(mScrollLockLedState, LED_SCROLLL,
- AMETA_SCROLL_LOCK_ON, reset);
-}
-
-void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
- int32_t led, int32_t modifier, bool reset) {
- if (ledState.avail) {
- bool desiredState = (mMetaState & modifier) != 0;
- if (reset || ledState.on != desiredState) {
- getEventHub()->setLedState(getDeviceId(), led, desiredState);
- ledState.on = desiredState;
- }
- }
-}
-
-
-// --- CursorInputMapper ---
-
-CursorInputMapper::CursorInputMapper(InputDevice* device) :
- InputMapper(device) {
-}
-
-CursorInputMapper::~CursorInputMapper() {
-}
-
-uint32_t CursorInputMapper::getSources() {
- return mSource;
-}
-
-void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
- InputMapper::populateDeviceInfo(info);
-
- if (mParameters.mode == Parameters::MODE_POINTER) {
- float minX, minY, maxX, maxY;
- if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
- info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
- info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
- }
- } else {
- info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
- info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
- }
- info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
-
- if (mCursorScrollAccumulator.haveRelativeVWheel()) {
- info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
- }
- if (mCursorScrollAccumulator.haveRelativeHWheel()) {
- info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
- }
-}
-
-void CursorInputMapper::dump(String8& dump) {
- dump.append(INDENT2 "Cursor Input Mapper:\n");
- dumpParameters(dump);
- dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
- dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
- dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
- dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
- dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
- toString(mCursorScrollAccumulator.haveRelativeVWheel()));
- dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
- toString(mCursorScrollAccumulator.haveRelativeHWheel()));
- dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
- dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
- dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
- dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
- dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
- dump.appendFormat(INDENT3 "DownTime: %lld\n", mDownTime);
-}
-
-void CursorInputMapper::configure(nsecs_t when,
- const InputReaderConfiguration* config, uint32_t changes) {
- InputMapper::configure(when, config, changes);
-
- if (!changes) { // first time only
- mCursorScrollAccumulator.configure(getDevice());
-
- // Configure basic parameters.
- configureParameters();
-
- // Configure device mode.
- switch (mParameters.mode) {
- case Parameters::MODE_POINTER:
- mSource = AINPUT_SOURCE_MOUSE;
- mXPrecision = 1.0f;
- mYPrecision = 1.0f;
- mXScale = 1.0f;
- mYScale = 1.0f;
- mPointerController = getPolicy()->obtainPointerController(getDeviceId());
- break;
- case Parameters::MODE_NAVIGATION:
- mSource = AINPUT_SOURCE_TRACKBALL;
- mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
- mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
- mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
- mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
- break;
- }
-
- mVWheelScale = 1.0f;
- mHWheelScale = 1.0f;
- }
-
- if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
- mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
- mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
- mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
- }
-
- if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
- if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
- DisplayViewport v;
- if (config->getDisplayInfo(false /*external*/, &v)) {
- mOrientation = v.orientation;
- } else {
- mOrientation = DISPLAY_ORIENTATION_0;
- }
- } else {
- mOrientation = DISPLAY_ORIENTATION_0;
- }
- bumpGeneration();
- }
-}
-
-void CursorInputMapper::configureParameters() {
- mParameters.mode = Parameters::MODE_POINTER;
- String8 cursorModeString;
- if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
- if (cursorModeString == "navigation") {
- mParameters.mode = Parameters::MODE_NAVIGATION;
- } else if (cursorModeString != "pointer" && cursorModeString != "default") {
- ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
- }
- }
-
- mParameters.orientationAware = false;
- getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
- mParameters.orientationAware);
-
- mParameters.hasAssociatedDisplay = false;
- if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
- mParameters.hasAssociatedDisplay = true;
- }
-}
-
-void CursorInputMapper::dumpParameters(String8& dump) {
- dump.append(INDENT3 "Parameters:\n");
- dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
- toString(mParameters.hasAssociatedDisplay));
-
- switch (mParameters.mode) {
- case Parameters::MODE_POINTER:
- dump.append(INDENT4 "Mode: pointer\n");
- break;
- case Parameters::MODE_NAVIGATION:
- dump.append(INDENT4 "Mode: navigation\n");
- break;
- default:
- ALOG_ASSERT(false);
- }
-
- dump.appendFormat(INDENT4 "OrientationAware: %s\n",
- toString(mParameters.orientationAware));
-}
-
-void CursorInputMapper::reset(nsecs_t when) {
- mButtonState = 0;
- mDownTime = 0;
-
- mPointerVelocityControl.reset();
- mWheelXVelocityControl.reset();
- mWheelYVelocityControl.reset();
-
- mCursorButtonAccumulator.reset(getDevice());
- mCursorMotionAccumulator.reset(getDevice());
- mCursorScrollAccumulator.reset(getDevice());
-
- InputMapper::reset(when);
-}
-
-void CursorInputMapper::process(const RawEvent* rawEvent) {
- mCursorButtonAccumulator.process(rawEvent);
- mCursorMotionAccumulator.process(rawEvent);
- mCursorScrollAccumulator.process(rawEvent);
-
- if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
- sync(rawEvent->when);
- }
-}
-
-void CursorInputMapper::sync(nsecs_t when) {
- int32_t lastButtonState = mButtonState;
- int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
- mButtonState = currentButtonState;
-
- bool wasDown = isPointerDown(lastButtonState);
- bool down = isPointerDown(currentButtonState);
- bool downChanged;
- if (!wasDown && down) {
- mDownTime = when;
- downChanged = true;
- } else if (wasDown && !down) {
- downChanged = true;
- } else {
- downChanged = false;
- }
- nsecs_t downTime = mDownTime;
- bool buttonsChanged = currentButtonState != lastButtonState;
- bool buttonsPressed = currentButtonState & ~lastButtonState;
-
- float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
- float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
- bool moved = deltaX != 0 || deltaY != 0;
-
- // Rotate delta according to orientation if needed.
- if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
- && (deltaX != 0.0f || deltaY != 0.0f)) {
- rotateDelta(mOrientation, &deltaX, &deltaY);
- }
-
- // Move the pointer.
- PointerProperties pointerProperties;
- pointerProperties.clear();
- pointerProperties.id = 0;
- pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
-
- PointerCoords pointerCoords;
- pointerCoords.clear();
-
- float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
- float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
- bool scrolled = vscroll != 0 || hscroll != 0;
-
- mWheelYVelocityControl.move(when, NULL, &vscroll);
- mWheelXVelocityControl.move(when, &hscroll, NULL);
-
- mPointerVelocityControl.move(when, &deltaX, &deltaY);
-
- int32_t displayId;
- if (mPointerController != NULL) {
- if (moved || scrolled || buttonsChanged) {
- mPointerController->setPresentation(
- PointerControllerInterface::PRESENTATION_POINTER);
-
- if (moved) {
- mPointerController->move(deltaX, deltaY);
- }
-
- if (buttonsChanged) {
- mPointerController->setButtonState(currentButtonState);
- }
-
- mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
- }
-
- float x, y;
- mPointerController->getPosition(&x, &y);
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
- displayId = ADISPLAY_ID_DEFAULT;
- } else {
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
- displayId = ADISPLAY_ID_NONE;
- }
-
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
-
- // Moving an external trackball or mouse should wake the device.
- // We don't do this for internal cursor devices to prevent them from waking up
- // the device in your pocket.
- // TODO: Use the input device configuration to control this behavior more finely.
- uint32_t policyFlags = 0;
- if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
- policyFlags |= POLICY_FLAG_WAKE_DROPPED;
- }
-
- // Synthesize key down from buttons if needed.
- synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
- policyFlags, lastButtonState, currentButtonState);
-
- // Send motion event.
- if (downChanged || moved || scrolled || buttonsChanged) {
- int32_t metaState = mContext->getGlobalMetaState();
- int32_t motionEventAction;
- if (downChanged) {
- motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
- } else if (down || mPointerController == NULL) {
- motionEventAction = AMOTION_EVENT_ACTION_MOVE;
- } else {
- motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
- }
-
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- motionEventAction, 0, metaState, currentButtonState, 0,
- displayId, 1, &pointerProperties, &pointerCoords,
- mXPrecision, mYPrecision, downTime);
- getListener()->notifyMotion(&args);
-
- // Send hover move after UP to tell the application that the mouse is hovering now.
- if (motionEventAction == AMOTION_EVENT_ACTION_UP
- && mPointerController != NULL) {
- NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
- metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
- displayId, 1, &pointerProperties, &pointerCoords,
- mXPrecision, mYPrecision, downTime);
- getListener()->notifyMotion(&hoverArgs);
- }
-
- // Send scroll events.
- if (scrolled) {
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
-
- NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_SCROLL, 0, metaState, currentButtonState,
- AMOTION_EVENT_EDGE_FLAG_NONE,
- displayId, 1, &pointerProperties, &pointerCoords,
- mXPrecision, mYPrecision, downTime);
- getListener()->notifyMotion(&scrollArgs);
- }
- }
-
- // Synthesize key up from buttons if needed.
- synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
- policyFlags, lastButtonState, currentButtonState);
-
- mCursorMotionAccumulator.finishSync();
- mCursorScrollAccumulator.finishSync();
-}
-
-int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
- if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
- return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
- } else {
- return AKEY_STATE_UNKNOWN;
- }
-}
-
-void CursorInputMapper::fadePointer() {
- if (mPointerController != NULL) {
- mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
- }
-}
-
-
-// --- TouchInputMapper ---
-
-TouchInputMapper::TouchInputMapper(InputDevice* device) :
- InputMapper(device),
- mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
- mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
- mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
-}
-
-TouchInputMapper::~TouchInputMapper() {
-}
-
-uint32_t TouchInputMapper::getSources() {
- return mSource;
-}
-
-void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
- InputMapper::populateDeviceInfo(info);
-
- if (mDeviceMode != DEVICE_MODE_DISABLED) {
- info->addMotionRange(mOrientedRanges.x);
- info->addMotionRange(mOrientedRanges.y);
- info->addMotionRange(mOrientedRanges.pressure);
-
- if (mOrientedRanges.haveSize) {
- info->addMotionRange(mOrientedRanges.size);
- }
-
- if (mOrientedRanges.haveTouchSize) {
- info->addMotionRange(mOrientedRanges.touchMajor);
- info->addMotionRange(mOrientedRanges.touchMinor);
- }
-
- if (mOrientedRanges.haveToolSize) {
- info->addMotionRange(mOrientedRanges.toolMajor);
- info->addMotionRange(mOrientedRanges.toolMinor);
- }
-
- if (mOrientedRanges.haveOrientation) {
- info->addMotionRange(mOrientedRanges.orientation);
- }
-
- if (mOrientedRanges.haveDistance) {
- info->addMotionRange(mOrientedRanges.distance);
- }
-
- if (mOrientedRanges.haveTilt) {
- info->addMotionRange(mOrientedRanges.tilt);
- }
-
- if (mCursorScrollAccumulator.haveRelativeVWheel()) {
- info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
- 0.0f);
- }
- if (mCursorScrollAccumulator.haveRelativeHWheel()) {
- info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
- 0.0f);
- }
- if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
- const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
- const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
- info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
- x.fuzz, x.resolution);
- info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
- y.fuzz, y.resolution);
- info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
- x.fuzz, x.resolution);
- info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
- y.fuzz, y.resolution);
- }
- }
-}
-
-void TouchInputMapper::dump(String8& dump) {
- dump.append(INDENT2 "Touch Input Mapper:\n");
- dumpParameters(dump);
- dumpVirtualKeys(dump);
- dumpRawPointerAxes(dump);
- dumpCalibration(dump);
- dumpSurface(dump);
-
- dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
- dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
- dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
- dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
- dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
- dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
- dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
- dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
- dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
- dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
- dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
- dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
- dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
- dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
- dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
- dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
- dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
-
- dump.appendFormat(INDENT3 "Last Button State: 0x%08x\n", mLastButtonState);
-
- dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
- mLastRawPointerData.pointerCount);
- for (uint32_t i = 0; i < mLastRawPointerData.pointerCount; i++) {
- const RawPointerData::Pointer& pointer = mLastRawPointerData.pointers[i];
- dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
- "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
- "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
- "toolType=%d, isHovering=%s\n", i,
- pointer.id, pointer.x, pointer.y, pointer.pressure,
- pointer.touchMajor, pointer.touchMinor,
- pointer.toolMajor, pointer.toolMinor,
- pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
- pointer.toolType, toString(pointer.isHovering));
- }
-
- dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
- mLastCookedPointerData.pointerCount);
- for (uint32_t i = 0; i < mLastCookedPointerData.pointerCount; i++) {
- const PointerProperties& pointerProperties = mLastCookedPointerData.pointerProperties[i];
- const PointerCoords& pointerCoords = mLastCookedPointerData.pointerCoords[i];
- dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
- "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
- "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
- "toolType=%d, isHovering=%s\n", i,
- pointerProperties.id,
- pointerCoords.getX(),
- pointerCoords.getY(),
- pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
- pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
- pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
- pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
- pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
- pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
- pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
- pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
- pointerProperties.toolType,
- toString(mLastCookedPointerData.isHovering(i)));
- }
-
- if (mDeviceMode == DEVICE_MODE_POINTER) {
- dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
- dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
- mPointerXMovementScale);
- dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
- mPointerYMovementScale);
- dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
- mPointerXZoomScale);
- dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
- mPointerYZoomScale);
- dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
- mPointerGestureMaxSwipeWidth);
- }
-}
-
-void TouchInputMapper::configure(nsecs_t when,
- const InputReaderConfiguration* config, uint32_t changes) {
- InputMapper::configure(when, config, changes);
-
- mConfig = *config;
-
- if (!changes) { // first time only
- // Configure basic parameters.
- configureParameters();
-
- // Configure common accumulators.
- mCursorScrollAccumulator.configure(getDevice());
- mTouchButtonAccumulator.configure(getDevice());
-
- // Configure absolute axis information.
- configureRawPointerAxes();
-
- // Prepare input device calibration.
- parseCalibration();
- resolveCalibration();
- }
-
- if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
- // Update pointer speed.
- mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
- mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
- mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
- }
-
- bool resetNeeded = false;
- if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
- | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
- | InputReaderConfiguration::CHANGE_SHOW_TOUCHES))) {
- // Configure device sources, surface dimensions, orientation and
- // scaling factors.
- configureSurface(when, &resetNeeded);
- }
-
- if (changes && resetNeeded) {
- // Send reset, unless this is the first time the device has been configured,
- // in which case the reader will call reset itself after all mappers are ready.
- getDevice()->notifyReset(when);
- }
-}
-
-void TouchInputMapper::configureParameters() {
- // Use the pointer presentation mode for devices that do not support distinct
- // multitouch. The spot-based presentation relies on being able to accurately
- // locate two or more fingers on the touch pad.
- mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
- ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS;
-
- String8 gestureModeString;
- if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
- gestureModeString)) {
- if (gestureModeString == "pointer") {
- mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
- } else if (gestureModeString == "spots") {
- mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
- } else if (gestureModeString != "default") {
- ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
- }
- }
-
- if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
- // The device is a touch screen.
- mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
- } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
- // The device is a pointing device like a track pad.
- mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
- } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
- || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
- // The device is a cursor device with a touch pad attached.
- // By default don't use the touch pad to move the pointer.
- mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
- } else {
- // The device is a touch pad of unknown purpose.
- mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
- }
-
- String8 deviceTypeString;
- if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
- deviceTypeString)) {
- if (deviceTypeString == "touchScreen") {
- mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
- } else if (deviceTypeString == "touchPad") {
- mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
- } else if (deviceTypeString == "touchNavigation") {
- mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
- } else if (deviceTypeString == "pointer") {
- mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
- } else if (deviceTypeString != "default") {
- ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
- }
- }
-
- mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
- getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
- mParameters.orientationAware);
-
- mParameters.hasAssociatedDisplay = false;
- mParameters.associatedDisplayIsExternal = false;
- if (mParameters.orientationAware
- || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
- || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
- mParameters.hasAssociatedDisplay = true;
- mParameters.associatedDisplayIsExternal =
- mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
- && getDevice()->isExternal();
- }
-}
-
-void TouchInputMapper::dumpParameters(String8& dump) {
- dump.append(INDENT3 "Parameters:\n");
-
- switch (mParameters.gestureMode) {
- case Parameters::GESTURE_MODE_POINTER:
- dump.append(INDENT4 "GestureMode: pointer\n");
- break;
- case Parameters::GESTURE_MODE_SPOTS:
- dump.append(INDENT4 "GestureMode: spots\n");
- break;
- default:
- assert(false);
- }
-
- switch (mParameters.deviceType) {
- case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
- dump.append(INDENT4 "DeviceType: touchScreen\n");
- break;
- case Parameters::DEVICE_TYPE_TOUCH_PAD:
- dump.append(INDENT4 "DeviceType: touchPad\n");
- break;
- case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
- dump.append(INDENT4 "DeviceType: touchNavigation\n");
- break;
- case Parameters::DEVICE_TYPE_POINTER:
- dump.append(INDENT4 "DeviceType: pointer\n");
- break;
- default:
- ALOG_ASSERT(false);
- }
-
- dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n",
- toString(mParameters.hasAssociatedDisplay),
- toString(mParameters.associatedDisplayIsExternal));
- dump.appendFormat(INDENT4 "OrientationAware: %s\n",
- toString(mParameters.orientationAware));
-}
-
-void TouchInputMapper::configureRawPointerAxes() {
- mRawPointerAxes.clear();
-}
-
-void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
- dump.append(INDENT3 "Raw Touch Axes:\n");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
- dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
-}
-
-void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
- int32_t oldDeviceMode = mDeviceMode;
-
- // Determine device mode.
- if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
- && mConfig.pointerGesturesEnabled) {
- mSource = AINPUT_SOURCE_MOUSE;
- mDeviceMode = DEVICE_MODE_POINTER;
- if (hasStylus()) {
- mSource |= AINPUT_SOURCE_STYLUS;
- }
- } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
- && mParameters.hasAssociatedDisplay) {
- mSource = AINPUT_SOURCE_TOUCHSCREEN;
- mDeviceMode = DEVICE_MODE_DIRECT;
- if (hasStylus()) {
- mSource |= AINPUT_SOURCE_STYLUS;
- }
- } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
- mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
- mDeviceMode = DEVICE_MODE_NAVIGATION;
- } else {
- mSource = AINPUT_SOURCE_TOUCHPAD;
- mDeviceMode = DEVICE_MODE_UNSCALED;
- }
-
- // Ensure we have valid X and Y axes.
- if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
- ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
- "The device will be inoperable.", getDeviceName().string());
- mDeviceMode = DEVICE_MODE_DISABLED;
- return;
- }
-
- // Raw width and height in the natural orientation.
- int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
- int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
-
- // Get associated display dimensions.
- bool viewportChanged = false;
- DisplayViewport newViewport;
- if (mParameters.hasAssociatedDisplay) {
- if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) {
- ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
- "display. The device will be inoperable until the display size "
- "becomes available.",
- getDeviceName().string());
- mDeviceMode = DEVICE_MODE_DISABLED;
- return;
- }
- } else {
- newViewport.setNonDisplayViewport(rawWidth, rawHeight);
- }
- if (mViewport != newViewport) {
- mViewport = newViewport;
- viewportChanged = true;
-
- if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
- // Convert rotated viewport to natural surface coordinates.
- int32_t naturalLogicalWidth, naturalLogicalHeight;
- int32_t naturalPhysicalWidth, naturalPhysicalHeight;
- int32_t naturalPhysicalLeft, naturalPhysicalTop;
- int32_t naturalDeviceWidth, naturalDeviceHeight;
- switch (mViewport.orientation) {
- case DISPLAY_ORIENTATION_90:
- naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
- naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
- naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
- naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
- naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
- naturalPhysicalTop = mViewport.physicalLeft;
- naturalDeviceWidth = mViewport.deviceHeight;
- naturalDeviceHeight = mViewport.deviceWidth;
- break;
- case DISPLAY_ORIENTATION_180:
- naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
- naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
- naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
- naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
- naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
- naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
- naturalDeviceWidth = mViewport.deviceWidth;
- naturalDeviceHeight = mViewport.deviceHeight;
- break;
- case DISPLAY_ORIENTATION_270:
- naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
- naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
- naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
- naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
- naturalPhysicalLeft = mViewport.physicalTop;
- naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
- naturalDeviceWidth = mViewport.deviceHeight;
- naturalDeviceHeight = mViewport.deviceWidth;
- break;
- case DISPLAY_ORIENTATION_0:
- default:
- naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
- naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
- naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
- naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
- naturalPhysicalLeft = mViewport.physicalLeft;
- naturalPhysicalTop = mViewport.physicalTop;
- naturalDeviceWidth = mViewport.deviceWidth;
- naturalDeviceHeight = mViewport.deviceHeight;
- break;
- }
-
- mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
- mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
- mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
- mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
-
- mSurfaceOrientation = mParameters.orientationAware ?
- mViewport.orientation : DISPLAY_ORIENTATION_0;
- } else {
- mSurfaceWidth = rawWidth;
- mSurfaceHeight = rawHeight;
- mSurfaceLeft = 0;
- mSurfaceTop = 0;
- mSurfaceOrientation = DISPLAY_ORIENTATION_0;
- }
- }
-
- // If moving between pointer modes, need to reset some state.
- bool deviceModeChanged = mDeviceMode != oldDeviceMode;
- if (deviceModeChanged) {
- mOrientedRanges.clear();
- }
-
- // Create pointer controller if needed.
- if (mDeviceMode == DEVICE_MODE_POINTER ||
- (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
- if (mPointerController == NULL) {
- mPointerController = getPolicy()->obtainPointerController(getDeviceId());
- }
- } else {
- mPointerController.clear();
- }
-
- if (viewportChanged || deviceModeChanged) {
- ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
- "display id %d",
- getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
- mSurfaceOrientation, mDeviceMode, mViewport.displayId);
-
- // Configure X and Y factors.
- mXScale = float(mSurfaceWidth) / rawWidth;
- mYScale = float(mSurfaceHeight) / rawHeight;
- mXTranslate = -mSurfaceLeft;
- mYTranslate = -mSurfaceTop;
- mXPrecision = 1.0f / mXScale;
- mYPrecision = 1.0f / mYScale;
-
- mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
- mOrientedRanges.x.source = mSource;
- mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
- mOrientedRanges.y.source = mSource;
-
- configureVirtualKeys();
-
- // Scale factor for terms that are not oriented in a particular axis.
- // If the pixels are square then xScale == yScale otherwise we fake it
- // by choosing an average.
- mGeometricScale = avg(mXScale, mYScale);
-
- // Size of diagonal axis.
- float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
-
- // Size factors.
- if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
- if (mRawPointerAxes.touchMajor.valid
- && mRawPointerAxes.touchMajor.maxValue != 0) {
- mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
- } else if (mRawPointerAxes.toolMajor.valid
- && mRawPointerAxes.toolMajor.maxValue != 0) {
- mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
- } else {
- mSizeScale = 0.0f;
- }
-
- mOrientedRanges.haveTouchSize = true;
- mOrientedRanges.haveToolSize = true;
- mOrientedRanges.haveSize = true;
-
- mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
- mOrientedRanges.touchMajor.source = mSource;
- mOrientedRanges.touchMajor.min = 0;
- mOrientedRanges.touchMajor.max = diagonalSize;
- mOrientedRanges.touchMajor.flat = 0;
- mOrientedRanges.touchMajor.fuzz = 0;
- mOrientedRanges.touchMajor.resolution = 0;
-
- mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
- mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
-
- mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
- mOrientedRanges.toolMajor.source = mSource;
- mOrientedRanges.toolMajor.min = 0;
- mOrientedRanges.toolMajor.max = diagonalSize;
- mOrientedRanges.toolMajor.flat = 0;
- mOrientedRanges.toolMajor.fuzz = 0;
- mOrientedRanges.toolMajor.resolution = 0;
-
- mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
- mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
-
- mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
- mOrientedRanges.size.source = mSource;
- mOrientedRanges.size.min = 0;
- mOrientedRanges.size.max = 1.0;
- mOrientedRanges.size.flat = 0;
- mOrientedRanges.size.fuzz = 0;
- mOrientedRanges.size.resolution = 0;
- } else {
- mSizeScale = 0.0f;
- }
-
- // Pressure factors.
- mPressureScale = 0;
- if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
- || mCalibration.pressureCalibration
- == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
- if (mCalibration.havePressureScale) {
- mPressureScale = mCalibration.pressureScale;
- } else if (mRawPointerAxes.pressure.valid
- && mRawPointerAxes.pressure.maxValue != 0) {
- mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
- }
- }
-
- mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
- mOrientedRanges.pressure.source = mSource;
- mOrientedRanges.pressure.min = 0;
- mOrientedRanges.pressure.max = 1.0;
- mOrientedRanges.pressure.flat = 0;
- mOrientedRanges.pressure.fuzz = 0;
- mOrientedRanges.pressure.resolution = 0;
-
- // Tilt
- mTiltXCenter = 0;
- mTiltXScale = 0;
- mTiltYCenter = 0;
- mTiltYScale = 0;
- mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
- if (mHaveTilt) {
- mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
- mRawPointerAxes.tiltX.maxValue);
- mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
- mRawPointerAxes.tiltY.maxValue);
- mTiltXScale = M_PI / 180;
- mTiltYScale = M_PI / 180;
-
- mOrientedRanges.haveTilt = true;
-
- mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
- mOrientedRanges.tilt.source = mSource;
- mOrientedRanges.tilt.min = 0;
- mOrientedRanges.tilt.max = M_PI_2;
- mOrientedRanges.tilt.flat = 0;
- mOrientedRanges.tilt.fuzz = 0;
- mOrientedRanges.tilt.resolution = 0;
- }
-
- // Orientation
- mOrientationScale = 0;
- if (mHaveTilt) {
- mOrientedRanges.haveOrientation = true;
-
- mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
- mOrientedRanges.orientation.source = mSource;
- mOrientedRanges.orientation.min = -M_PI;
- mOrientedRanges.orientation.max = M_PI;
- mOrientedRanges.orientation.flat = 0;
- mOrientedRanges.orientation.fuzz = 0;
- mOrientedRanges.orientation.resolution = 0;
- } else if (mCalibration.orientationCalibration !=
- Calibration::ORIENTATION_CALIBRATION_NONE) {
- if (mCalibration.orientationCalibration
- == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
- if (mRawPointerAxes.orientation.valid) {
- if (mRawPointerAxes.orientation.maxValue > 0) {
- mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
- } else if (mRawPointerAxes.orientation.minValue < 0) {
- mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
- } else {
- mOrientationScale = 0;
- }
- }
- }
-
- mOrientedRanges.haveOrientation = true;
-
- mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
- mOrientedRanges.orientation.source = mSource;
- mOrientedRanges.orientation.min = -M_PI_2;
- mOrientedRanges.orientation.max = M_PI_2;
- mOrientedRanges.orientation.flat = 0;
- mOrientedRanges.orientation.fuzz = 0;
- mOrientedRanges.orientation.resolution = 0;
- }
-
- // Distance
- mDistanceScale = 0;
- if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
- if (mCalibration.distanceCalibration
- == Calibration::DISTANCE_CALIBRATION_SCALED) {
- if (mCalibration.haveDistanceScale) {
- mDistanceScale = mCalibration.distanceScale;
- } else {
- mDistanceScale = 1.0f;
- }
- }
-
- mOrientedRanges.haveDistance = true;
-
- mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
- mOrientedRanges.distance.source = mSource;
- mOrientedRanges.distance.min =
- mRawPointerAxes.distance.minValue * mDistanceScale;
- mOrientedRanges.distance.max =
- mRawPointerAxes.distance.maxValue * mDistanceScale;
- mOrientedRanges.distance.flat = 0;
- mOrientedRanges.distance.fuzz =
- mRawPointerAxes.distance.fuzz * mDistanceScale;
- mOrientedRanges.distance.resolution = 0;
- }
-
- // Compute oriented precision, scales and ranges.
- // Note that the maximum value reported is an inclusive maximum value so it is one
- // unit less than the total width or height of surface.
- switch (mSurfaceOrientation) {
- case DISPLAY_ORIENTATION_90:
- case DISPLAY_ORIENTATION_270:
- mOrientedXPrecision = mYPrecision;
- mOrientedYPrecision = mXPrecision;
-
- mOrientedRanges.x.min = mYTranslate;
- mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
- mOrientedRanges.x.flat = 0;
- mOrientedRanges.x.fuzz = 0;
- mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
-
- mOrientedRanges.y.min = mXTranslate;
- mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
- mOrientedRanges.y.flat = 0;
- mOrientedRanges.y.fuzz = 0;
- mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
- break;
-
- default:
- mOrientedXPrecision = mXPrecision;
- mOrientedYPrecision = mYPrecision;
-
- mOrientedRanges.x.min = mXTranslate;
- mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
- mOrientedRanges.x.flat = 0;
- mOrientedRanges.x.fuzz = 0;
- mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
-
- mOrientedRanges.y.min = mYTranslate;
- mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
- mOrientedRanges.y.flat = 0;
- mOrientedRanges.y.fuzz = 0;
- mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
- break;
- }
-
- if (mDeviceMode == DEVICE_MODE_POINTER) {
- // Compute pointer gesture detection parameters.
- float rawDiagonal = hypotf(rawWidth, rawHeight);
- float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
-
- // Scale movements such that one whole swipe of the touch pad covers a
- // given area relative to the diagonal size of the display when no acceleration
- // is applied.
- // Assume that the touch pad has a square aspect ratio such that movements in
- // X and Y of the same number of raw units cover the same physical distance.
- mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
- * displayDiagonal / rawDiagonal;
- mPointerYMovementScale = mPointerXMovementScale;
-
- // Scale zooms to cover a smaller range of the display than movements do.
- // This value determines the area around the pointer that is affected by freeform
- // pointer gestures.
- mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
- * displayDiagonal / rawDiagonal;
- mPointerYZoomScale = mPointerXZoomScale;
-
- // Max width between pointers to detect a swipe gesture is more than some fraction
- // of the diagonal axis of the touch pad. Touches that are wider than this are
- // translated into freeform gestures.
- mPointerGestureMaxSwipeWidth =
- mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
-
- // Abort current pointer usages because the state has changed.
- abortPointerUsage(when, 0 /*policyFlags*/);
- }
-
- // Inform the dispatcher about the changes.
- *outResetNeeded = true;
- bumpGeneration();
- }
-}
-
-void TouchInputMapper::dumpSurface(String8& dump) {
- dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
- "logicalFrame=[%d, %d, %d, %d], "
- "physicalFrame=[%d, %d, %d, %d], "
- "deviceSize=[%d, %d]\n",
- mViewport.displayId, mViewport.orientation,
- mViewport.logicalLeft, mViewport.logicalTop,
- mViewport.logicalRight, mViewport.logicalBottom,
- mViewport.physicalLeft, mViewport.physicalTop,
- mViewport.physicalRight, mViewport.physicalBottom,
- mViewport.deviceWidth, mViewport.deviceHeight);
-
- dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
- dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
- dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
- dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
- dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
-}
-
-void TouchInputMapper::configureVirtualKeys() {
- Vector<VirtualKeyDefinition> virtualKeyDefinitions;
- getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
-
- mVirtualKeys.clear();
-
- if (virtualKeyDefinitions.size() == 0) {
- return;
- }
-
- mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
-
- int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
- int32_t touchScreenTop = mRawPointerAxes.y.minValue;
- int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
- int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
-
- for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
- const VirtualKeyDefinition& virtualKeyDefinition =
- virtualKeyDefinitions[i];
-
- mVirtualKeys.add();
- VirtualKey& virtualKey = mVirtualKeys.editTop();
-
- virtualKey.scanCode = virtualKeyDefinition.scanCode;
- int32_t keyCode;
- uint32_t flags;
- if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, &keyCode, &flags)) {
- ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
- virtualKey.scanCode);
- mVirtualKeys.pop(); // drop the key
- continue;
- }
-
- virtualKey.keyCode = keyCode;
- virtualKey.flags = flags;
-
- // convert the key definition's display coordinates into touch coordinates for a hit box
- int32_t halfWidth = virtualKeyDefinition.width / 2;
- int32_t halfHeight = virtualKeyDefinition.height / 2;
-
- virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
- * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
- virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
- * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
- virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
- * touchScreenHeight / mSurfaceHeight + touchScreenTop;
- virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
- * touchScreenHeight / mSurfaceHeight + touchScreenTop;
- }
-}
-
-void TouchInputMapper::dumpVirtualKeys(String8& dump) {
- if (!mVirtualKeys.isEmpty()) {
- dump.append(INDENT3 "Virtual Keys:\n");
-
- for (size_t i = 0; i < mVirtualKeys.size(); i++) {
- const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
- dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
- "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
- i, virtualKey.scanCode, virtualKey.keyCode,
- virtualKey.hitLeft, virtualKey.hitRight,
- virtualKey.hitTop, virtualKey.hitBottom);
- }
- }
-}
-
-void TouchInputMapper::parseCalibration() {
- const PropertyMap& in = getDevice()->getConfiguration();
- Calibration& out = mCalibration;
-
- // Size
- out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
- String8 sizeCalibrationString;
- if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
- if (sizeCalibrationString == "none") {
- out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
- } else if (sizeCalibrationString == "geometric") {
- out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
- } else if (sizeCalibrationString == "diameter") {
- out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
- } else if (sizeCalibrationString == "box") {
- out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
- } else if (sizeCalibrationString == "area") {
- out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
- } else if (sizeCalibrationString != "default") {
- ALOGW("Invalid value for touch.size.calibration: '%s'",
- sizeCalibrationString.string());
- }
- }
-
- out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
- out.sizeScale);
- out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
- out.sizeBias);
- out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
- out.sizeIsSummed);
-
- // Pressure
- out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
- String8 pressureCalibrationString;
- if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
- if (pressureCalibrationString == "none") {
- out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
- } else if (pressureCalibrationString == "physical") {
- out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
- } else if (pressureCalibrationString == "amplitude") {
- out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
- } else if (pressureCalibrationString != "default") {
- ALOGW("Invalid value for touch.pressure.calibration: '%s'",
- pressureCalibrationString.string());
- }
- }
-
- out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
- out.pressureScale);
-
- // Orientation
- out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
- String8 orientationCalibrationString;
- if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
- if (orientationCalibrationString == "none") {
- out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
- } else if (orientationCalibrationString == "interpolated") {
- out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
- } else if (orientationCalibrationString == "vector") {
- out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
- } else if (orientationCalibrationString != "default") {
- ALOGW("Invalid value for touch.orientation.calibration: '%s'",
- orientationCalibrationString.string());
- }
- }
-
- // Distance
- out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
- String8 distanceCalibrationString;
- if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
- if (distanceCalibrationString == "none") {
- out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
- } else if (distanceCalibrationString == "scaled") {
- out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
- } else if (distanceCalibrationString != "default") {
- ALOGW("Invalid value for touch.distance.calibration: '%s'",
- distanceCalibrationString.string());
- }
- }
-
- out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
- out.distanceScale);
-
- out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
- String8 coverageCalibrationString;
- if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
- if (coverageCalibrationString == "none") {
- out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
- } else if (coverageCalibrationString == "box") {
- out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
- } else if (coverageCalibrationString != "default") {
- ALOGW("Invalid value for touch.coverage.calibration: '%s'",
- coverageCalibrationString.string());
- }
- }
-}
-
-void TouchInputMapper::resolveCalibration() {
- // Size
- if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
- if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
- mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
- }
- } else {
- mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
- }
-
- // Pressure
- if (mRawPointerAxes.pressure.valid) {
- if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
- mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
- }
- } else {
- mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
- }
-
- // Orientation
- if (mRawPointerAxes.orientation.valid) {
- if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
- mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
- }
- } else {
- mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
- }
-
- // Distance
- if (mRawPointerAxes.distance.valid) {
- if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
- mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
- }
- } else {
- mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
- }
-
- // Coverage
- if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
- mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
- }
-}
-
-void TouchInputMapper::dumpCalibration(String8& dump) {
- dump.append(INDENT3 "Calibration:\n");
-
- // Size
- switch (mCalibration.sizeCalibration) {
- case Calibration::SIZE_CALIBRATION_NONE:
- dump.append(INDENT4 "touch.size.calibration: none\n");
- break;
- case Calibration::SIZE_CALIBRATION_GEOMETRIC:
- dump.append(INDENT4 "touch.size.calibration: geometric\n");
- break;
- case Calibration::SIZE_CALIBRATION_DIAMETER:
- dump.append(INDENT4 "touch.size.calibration: diameter\n");
- break;
- case Calibration::SIZE_CALIBRATION_BOX:
- dump.append(INDENT4 "touch.size.calibration: box\n");
- break;
- case Calibration::SIZE_CALIBRATION_AREA:
- dump.append(INDENT4 "touch.size.calibration: area\n");
- break;
- default:
- ALOG_ASSERT(false);
- }
-
- if (mCalibration.haveSizeScale) {
- dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
- mCalibration.sizeScale);
- }
-
- if (mCalibration.haveSizeBias) {
- dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
- mCalibration.sizeBias);
- }
-
- if (mCalibration.haveSizeIsSummed) {
- dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
- toString(mCalibration.sizeIsSummed));
- }
-
- // Pressure
- switch (mCalibration.pressureCalibration) {
- case Calibration::PRESSURE_CALIBRATION_NONE:
- dump.append(INDENT4 "touch.pressure.calibration: none\n");
- break;
- case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
- dump.append(INDENT4 "touch.pressure.calibration: physical\n");
- break;
- case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
- dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
- break;
- default:
- ALOG_ASSERT(false);
- }
-
- if (mCalibration.havePressureScale) {
- dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
- mCalibration.pressureScale);
- }
-
- // Orientation
- switch (mCalibration.orientationCalibration) {
- case Calibration::ORIENTATION_CALIBRATION_NONE:
- dump.append(INDENT4 "touch.orientation.calibration: none\n");
- break;
- case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
- dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
- break;
- case Calibration::ORIENTATION_CALIBRATION_VECTOR:
- dump.append(INDENT4 "touch.orientation.calibration: vector\n");
- break;
- default:
- ALOG_ASSERT(false);
- }
-
- // Distance
- switch (mCalibration.distanceCalibration) {
- case Calibration::DISTANCE_CALIBRATION_NONE:
- dump.append(INDENT4 "touch.distance.calibration: none\n");
- break;
- case Calibration::DISTANCE_CALIBRATION_SCALED:
- dump.append(INDENT4 "touch.distance.calibration: scaled\n");
- break;
- default:
- ALOG_ASSERT(false);
- }
-
- if (mCalibration.haveDistanceScale) {
- dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
- mCalibration.distanceScale);
- }
-
- switch (mCalibration.coverageCalibration) {
- case Calibration::COVERAGE_CALIBRATION_NONE:
- dump.append(INDENT4 "touch.coverage.calibration: none\n");
- break;
- case Calibration::COVERAGE_CALIBRATION_BOX:
- dump.append(INDENT4 "touch.coverage.calibration: box\n");
- break;
- default:
- ALOG_ASSERT(false);
- }
-}
-
-void TouchInputMapper::reset(nsecs_t when) {
- mCursorButtonAccumulator.reset(getDevice());
- mCursorScrollAccumulator.reset(getDevice());
- mTouchButtonAccumulator.reset(getDevice());
-
- mPointerVelocityControl.reset();
- mWheelXVelocityControl.reset();
- mWheelYVelocityControl.reset();
-
- mCurrentRawPointerData.clear();
- mLastRawPointerData.clear();
- mCurrentCookedPointerData.clear();
- mLastCookedPointerData.clear();
- mCurrentButtonState = 0;
- mLastButtonState = 0;
- mCurrentRawVScroll = 0;
- mCurrentRawHScroll = 0;
- mCurrentFingerIdBits.clear();
- mLastFingerIdBits.clear();
- mCurrentStylusIdBits.clear();
- mLastStylusIdBits.clear();
- mCurrentMouseIdBits.clear();
- mLastMouseIdBits.clear();
- mPointerUsage = POINTER_USAGE_NONE;
- mSentHoverEnter = false;
- mDownTime = 0;
-
- mCurrentVirtualKey.down = false;
-
- mPointerGesture.reset();
- mPointerSimple.reset();
-
- if (mPointerController != NULL) {
- mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
- mPointerController->clearSpots();
- }
-
- InputMapper::reset(when);
-}
-
-void TouchInputMapper::process(const RawEvent* rawEvent) {
- mCursorButtonAccumulator.process(rawEvent);
- mCursorScrollAccumulator.process(rawEvent);
- mTouchButtonAccumulator.process(rawEvent);
-
- if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
- sync(rawEvent->when);
- }
-}
-
-void TouchInputMapper::sync(nsecs_t when) {
- // Sync button state.
- mCurrentButtonState = mTouchButtonAccumulator.getButtonState()
- | mCursorButtonAccumulator.getButtonState();
-
- // Sync scroll state.
- mCurrentRawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
- mCurrentRawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
- mCursorScrollAccumulator.finishSync();
-
- // Sync touch state.
- bool havePointerIds = true;
- mCurrentRawPointerData.clear();
- syncTouch(when, &havePointerIds);
-
-#if DEBUG_RAW_EVENTS
- if (!havePointerIds) {
- ALOGD("syncTouch: pointerCount %d -> %d, no pointer ids",
- mLastRawPointerData.pointerCount,
- mCurrentRawPointerData.pointerCount);
- } else {
- ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
- "hovering ids 0x%08x -> 0x%08x",
- mLastRawPointerData.pointerCount,
- mCurrentRawPointerData.pointerCount,
- mLastRawPointerData.touchingIdBits.value,
- mCurrentRawPointerData.touchingIdBits.value,
- mLastRawPointerData.hoveringIdBits.value,
- mCurrentRawPointerData.hoveringIdBits.value);
- }
-#endif
-
- // Reset state that we will compute below.
- mCurrentFingerIdBits.clear();
- mCurrentStylusIdBits.clear();
- mCurrentMouseIdBits.clear();
- mCurrentCookedPointerData.clear();
-
- if (mDeviceMode == DEVICE_MODE_DISABLED) {
- // Drop all input if the device is disabled.
- mCurrentRawPointerData.clear();
- mCurrentButtonState = 0;
- } else {
- // Preprocess pointer data.
- if (!havePointerIds) {
- assignPointerIds();
- }
-
- // Handle policy on initial down or hover events.
- uint32_t policyFlags = 0;
- bool initialDown = mLastRawPointerData.pointerCount == 0
- && mCurrentRawPointerData.pointerCount != 0;
- bool buttonsPressed = mCurrentButtonState & ~mLastButtonState;
- if (initialDown || buttonsPressed) {
- // If this is a touch screen, hide the pointer on an initial down.
- if (mDeviceMode == DEVICE_MODE_DIRECT) {
- getContext()->fadePointer();
- }
-
- // Initial downs on external touch devices should wake the device.
- // We don't do this for internal touch screens to prevent them from waking
- // up in your pocket.
- // TODO: Use the input device configuration to control this behavior more finely.
- if (getDevice()->isExternal()) {
- policyFlags |= POLICY_FLAG_WAKE_DROPPED;
- }
- }
-
- // Synthesize key down from raw buttons if needed.
- synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
- policyFlags, mLastButtonState, mCurrentButtonState);
-
- // Consume raw off-screen touches before cooking pointer data.
- // If touches are consumed, subsequent code will not receive any pointer data.
- if (consumeRawTouches(when, policyFlags)) {
- mCurrentRawPointerData.clear();
- }
-
- // Cook pointer data. This call populates the mCurrentCookedPointerData structure
- // with cooked pointer data that has the same ids and indices as the raw data.
- // The following code can use either the raw or cooked data, as needed.
- cookPointerData();
-
- // Dispatch the touches either directly or by translation through a pointer on screen.
- if (mDeviceMode == DEVICE_MODE_POINTER) {
- for (BitSet32 idBits(mCurrentRawPointerData.touchingIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
- if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
- || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
- mCurrentStylusIdBits.markBit(id);
- } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
- || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
- mCurrentFingerIdBits.markBit(id);
- } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
- mCurrentMouseIdBits.markBit(id);
- }
- }
- for (BitSet32 idBits(mCurrentRawPointerData.hoveringIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
- if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
- || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
- mCurrentStylusIdBits.markBit(id);
- }
- }
-
- // Stylus takes precedence over all tools, then mouse, then finger.
- PointerUsage pointerUsage = mPointerUsage;
- if (!mCurrentStylusIdBits.isEmpty()) {
- mCurrentMouseIdBits.clear();
- mCurrentFingerIdBits.clear();
- pointerUsage = POINTER_USAGE_STYLUS;
- } else if (!mCurrentMouseIdBits.isEmpty()) {
- mCurrentFingerIdBits.clear();
- pointerUsage = POINTER_USAGE_MOUSE;
- } else if (!mCurrentFingerIdBits.isEmpty() || isPointerDown(mCurrentButtonState)) {
- pointerUsage = POINTER_USAGE_GESTURES;
- }
-
- dispatchPointerUsage(when, policyFlags, pointerUsage);
- } else {
- if (mDeviceMode == DEVICE_MODE_DIRECT
- && mConfig.showTouches && mPointerController != NULL) {
- mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
- mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
-
- mPointerController->setButtonState(mCurrentButtonState);
- mPointerController->setSpots(mCurrentCookedPointerData.pointerCoords,
- mCurrentCookedPointerData.idToIndex,
- mCurrentCookedPointerData.touchingIdBits);
- }
-
- dispatchHoverExit(when, policyFlags);
- dispatchTouches(when, policyFlags);
- dispatchHoverEnterAndMove(when, policyFlags);
- }
-
- // Synthesize key up from raw buttons if needed.
- synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
- policyFlags, mLastButtonState, mCurrentButtonState);
- }
-
- // Copy current touch to last touch in preparation for the next cycle.
- mLastRawPointerData.copyFrom(mCurrentRawPointerData);
- mLastCookedPointerData.copyFrom(mCurrentCookedPointerData);
- mLastButtonState = mCurrentButtonState;
- mLastFingerIdBits = mCurrentFingerIdBits;
- mLastStylusIdBits = mCurrentStylusIdBits;
- mLastMouseIdBits = mCurrentMouseIdBits;
-
- // Clear some transient state.
- mCurrentRawVScroll = 0;
- mCurrentRawHScroll = 0;
-}
-
-void TouchInputMapper::timeoutExpired(nsecs_t when) {
- if (mDeviceMode == DEVICE_MODE_POINTER) {
- if (mPointerUsage == POINTER_USAGE_GESTURES) {
- dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
- }
- }
-}
-
-bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
- // Check for release of a virtual key.
- if (mCurrentVirtualKey.down) {
- if (mCurrentRawPointerData.touchingIdBits.isEmpty()) {
- // Pointer went up while virtual key was down.
- mCurrentVirtualKey.down = false;
- if (!mCurrentVirtualKey.ignored) {
-#if DEBUG_VIRTUAL_KEYS
- ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
- mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
-#endif
- dispatchVirtualKey(when, policyFlags,
- AKEY_EVENT_ACTION_UP,
- AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
- }
- return true;
- }
-
- if (mCurrentRawPointerData.touchingIdBits.count() == 1) {
- uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit();
- const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
- const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
- if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
- // Pointer is still within the space of the virtual key.
- return true;
- }
- }
-
- // Pointer left virtual key area or another pointer also went down.
- // Send key cancellation but do not consume the touch yet.
- // This is useful when the user swipes through from the virtual key area
- // into the main display surface.
- mCurrentVirtualKey.down = false;
- if (!mCurrentVirtualKey.ignored) {
-#if DEBUG_VIRTUAL_KEYS
- ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
- mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
-#endif
- dispatchVirtualKey(when, policyFlags,
- AKEY_EVENT_ACTION_UP,
- AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
- | AKEY_EVENT_FLAG_CANCELED);
- }
- }
-
- if (mLastRawPointerData.touchingIdBits.isEmpty()
- && !mCurrentRawPointerData.touchingIdBits.isEmpty()) {
- // Pointer just went down. Check for virtual key press or off-screen touches.
- uint32_t id = mCurrentRawPointerData.touchingIdBits.firstMarkedBit();
- const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
- if (!isPointInsideSurface(pointer.x, pointer.y)) {
- // If exactly one pointer went down, check for virtual key hit.
- // Otherwise we will drop the entire stroke.
- if (mCurrentRawPointerData.touchingIdBits.count() == 1) {
- const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
- if (virtualKey) {
- mCurrentVirtualKey.down = true;
- mCurrentVirtualKey.downTime = when;
- mCurrentVirtualKey.keyCode = virtualKey->keyCode;
- mCurrentVirtualKey.scanCode = virtualKey->scanCode;
- mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
- when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
-
- if (!mCurrentVirtualKey.ignored) {
-#if DEBUG_VIRTUAL_KEYS
- ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
- mCurrentVirtualKey.keyCode,
- mCurrentVirtualKey.scanCode);
-#endif
- dispatchVirtualKey(when, policyFlags,
- AKEY_EVENT_ACTION_DOWN,
- AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
- }
- }
- }
- return true;
- }
- }
-
- // Disable all virtual key touches that happen within a short time interval of the
- // most recent touch within the screen area. The idea is to filter out stray
- // virtual key presses when interacting with the touch screen.
- //
- // Problems we're trying to solve:
- //
- // 1. While scrolling a list or dragging the window shade, the user swipes down into a
- // virtual key area that is implemented by a separate touch panel and accidentally
- // triggers a virtual key.
- //
- // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
- // area and accidentally triggers a virtual key. This often happens when virtual keys
- // are layed out below the screen near to where the on screen keyboard's space bar
- // is displayed.
- if (mConfig.virtualKeyQuietTime > 0 && !mCurrentRawPointerData.touchingIdBits.isEmpty()) {
- mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
- }
- return false;
-}
-
-void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
- int32_t keyEventAction, int32_t keyEventFlags) {
- int32_t keyCode = mCurrentVirtualKey.keyCode;
- int32_t scanCode = mCurrentVirtualKey.scanCode;
- nsecs_t downTime = mCurrentVirtualKey.downTime;
- int32_t metaState = mContext->getGlobalMetaState();
- policyFlags |= POLICY_FLAG_VIRTUAL;
-
- NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
- keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
- getListener()->notifyKey(&args);
-}
-
-void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
- BitSet32 currentIdBits = mCurrentCookedPointerData.touchingIdBits;
- BitSet32 lastIdBits = mLastCookedPointerData.touchingIdBits;
- int32_t metaState = getContext()->getGlobalMetaState();
- int32_t buttonState = mCurrentButtonState;
-
- if (currentIdBits == lastIdBits) {
- if (!currentIdBits.isEmpty()) {
- // No pointer id changes so this is a move event.
- // The listener takes care of batching moves so we don't have to deal with that here.
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState,
- AMOTION_EVENT_EDGE_FLAG_NONE,
- mCurrentCookedPointerData.pointerProperties,
- mCurrentCookedPointerData.pointerCoords,
- mCurrentCookedPointerData.idToIndex,
- currentIdBits, -1,
- mOrientedXPrecision, mOrientedYPrecision, mDownTime);
- }
- } else {
- // There may be pointers going up and pointers going down and pointers moving
- // all at the same time.
- BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
- BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
- BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
- BitSet32 dispatchedIdBits(lastIdBits.value);
-
- // Update last coordinates of pointers that have moved so that we observe the new
- // pointer positions at the same time as other pointers that have just gone up.
- bool moveNeeded = updateMovedPointers(
- mCurrentCookedPointerData.pointerProperties,
- mCurrentCookedPointerData.pointerCoords,
- mCurrentCookedPointerData.idToIndex,
- mLastCookedPointerData.pointerProperties,
- mLastCookedPointerData.pointerCoords,
- mLastCookedPointerData.idToIndex,
- moveIdBits);
- if (buttonState != mLastButtonState) {
- moveNeeded = true;
- }
-
- // Dispatch pointer up events.
- while (!upIdBits.isEmpty()) {
- uint32_t upId = upIdBits.clearFirstMarkedBit();
-
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, 0,
- mLastCookedPointerData.pointerProperties,
- mLastCookedPointerData.pointerCoords,
- mLastCookedPointerData.idToIndex,
- dispatchedIdBits, upId,
- mOrientedXPrecision, mOrientedYPrecision, mDownTime);
- dispatchedIdBits.clearBit(upId);
- }
-
- // Dispatch move events if any of the remaining pointers moved from their old locations.
- // Although applications receive new locations as part of individual pointer up
- // events, they do not generally handle them except when presented in a move event.
- if (moveNeeded) {
- ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 0,
- mCurrentCookedPointerData.pointerProperties,
- mCurrentCookedPointerData.pointerCoords,
- mCurrentCookedPointerData.idToIndex,
- dispatchedIdBits, -1,
- mOrientedXPrecision, mOrientedYPrecision, mDownTime);
- }
-
- // Dispatch pointer down events using the new pointer locations.
- while (!downIdBits.isEmpty()) {
- uint32_t downId = downIdBits.clearFirstMarkedBit();
- dispatchedIdBits.markBit(downId);
-
- if (dispatchedIdBits.count() == 1) {
- // First pointer is going down. Set down time.
- mDownTime = when;
- }
-
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0,
- mCurrentCookedPointerData.pointerProperties,
- mCurrentCookedPointerData.pointerCoords,
- mCurrentCookedPointerData.idToIndex,
- dispatchedIdBits, downId,
- mOrientedXPrecision, mOrientedYPrecision, mDownTime);
- }
- }
-}
-
-void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
- if (mSentHoverEnter &&
- (mCurrentCookedPointerData.hoveringIdBits.isEmpty()
- || !mCurrentCookedPointerData.touchingIdBits.isEmpty())) {
- int32_t metaState = getContext()->getGlobalMetaState();
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0,
- mLastCookedPointerData.pointerProperties,
- mLastCookedPointerData.pointerCoords,
- mLastCookedPointerData.idToIndex,
- mLastCookedPointerData.hoveringIdBits, -1,
- mOrientedXPrecision, mOrientedYPrecision, mDownTime);
- mSentHoverEnter = false;
- }
-}
-
-void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
- if (mCurrentCookedPointerData.touchingIdBits.isEmpty()
- && !mCurrentCookedPointerData.hoveringIdBits.isEmpty()) {
- int32_t metaState = getContext()->getGlobalMetaState();
- if (!mSentHoverEnter) {
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0,
- mCurrentCookedPointerData.pointerProperties,
- mCurrentCookedPointerData.pointerCoords,
- mCurrentCookedPointerData.idToIndex,
- mCurrentCookedPointerData.hoveringIdBits, -1,
- mOrientedXPrecision, mOrientedYPrecision, mDownTime);
- mSentHoverEnter = true;
- }
-
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0,
- mCurrentCookedPointerData.pointerProperties,
- mCurrentCookedPointerData.pointerCoords,
- mCurrentCookedPointerData.idToIndex,
- mCurrentCookedPointerData.hoveringIdBits, -1,
- mOrientedXPrecision, mOrientedYPrecision, mDownTime);
- }
-}
-
-void TouchInputMapper::cookPointerData() {
- uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount;
-
- mCurrentCookedPointerData.clear();
- mCurrentCookedPointerData.pointerCount = currentPointerCount;
- mCurrentCookedPointerData.hoveringIdBits = mCurrentRawPointerData.hoveringIdBits;
- mCurrentCookedPointerData.touchingIdBits = mCurrentRawPointerData.touchingIdBits;
-
- // Walk through the the active pointers and map device coordinates onto
- // surface coordinates and adjust for display orientation.
- for (uint32_t i = 0; i < currentPointerCount; i++) {
- const RawPointerData::Pointer& in = mCurrentRawPointerData.pointers[i];
-
- // Size
- float touchMajor, touchMinor, toolMajor, toolMinor, size;
- switch (mCalibration.sizeCalibration) {
- case Calibration::SIZE_CALIBRATION_GEOMETRIC:
- case Calibration::SIZE_CALIBRATION_DIAMETER:
- case Calibration::SIZE_CALIBRATION_BOX:
- case Calibration::SIZE_CALIBRATION_AREA:
- if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
- touchMajor = in.touchMajor;
- touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
- toolMajor = in.toolMajor;
- toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
- size = mRawPointerAxes.touchMinor.valid
- ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
- } else if (mRawPointerAxes.touchMajor.valid) {
- toolMajor = touchMajor = in.touchMajor;
- toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
- ? in.touchMinor : in.touchMajor;
- size = mRawPointerAxes.touchMinor.valid
- ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
- } else if (mRawPointerAxes.toolMajor.valid) {
- touchMajor = toolMajor = in.toolMajor;
- touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
- ? in.toolMinor : in.toolMajor;
- size = mRawPointerAxes.toolMinor.valid
- ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
- } else {
- ALOG_ASSERT(false, "No touch or tool axes. "
- "Size calibration should have been resolved to NONE.");
- touchMajor = 0;
- touchMinor = 0;
- toolMajor = 0;
- toolMinor = 0;
- size = 0;
- }
-
- if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
- uint32_t touchingCount = mCurrentRawPointerData.touchingIdBits.count();
- if (touchingCount > 1) {
- touchMajor /= touchingCount;
- touchMinor /= touchingCount;
- toolMajor /= touchingCount;
- toolMinor /= touchingCount;
- size /= touchingCount;
- }
- }
-
- if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
- touchMajor *= mGeometricScale;
- touchMinor *= mGeometricScale;
- toolMajor *= mGeometricScale;
- toolMinor *= mGeometricScale;
- } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
- touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
- touchMinor = touchMajor;
- toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
- toolMinor = toolMajor;
- } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
- touchMinor = touchMajor;
- toolMinor = toolMajor;
- }
-
- mCalibration.applySizeScaleAndBias(&touchMajor);
- mCalibration.applySizeScaleAndBias(&touchMinor);
- mCalibration.applySizeScaleAndBias(&toolMajor);
- mCalibration.applySizeScaleAndBias(&toolMinor);
- size *= mSizeScale;
- break;
- default:
- touchMajor = 0;
- touchMinor = 0;
- toolMajor = 0;
- toolMinor = 0;
- size = 0;
- break;
- }
-
- // Pressure
- float pressure;
- switch (mCalibration.pressureCalibration) {
- case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
- case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
- pressure = in.pressure * mPressureScale;
- break;
- default:
- pressure = in.isHovering ? 0 : 1;
- break;
- }
-
- // Tilt and Orientation
- float tilt;
- float orientation;
- if (mHaveTilt) {
- float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
- float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
- orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
- tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
- } else {
- tilt = 0;
-
- switch (mCalibration.orientationCalibration) {
- case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
- orientation = in.orientation * mOrientationScale;
- break;
- case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
- int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
- int32_t c2 = signExtendNybble(in.orientation & 0x0f);
- if (c1 != 0 || c2 != 0) {
- orientation = atan2f(c1, c2) * 0.5f;
- float confidence = hypotf(c1, c2);
- float scale = 1.0f + confidence / 16.0f;
- touchMajor *= scale;
- touchMinor /= scale;
- toolMajor *= scale;
- toolMinor /= scale;
- } else {
- orientation = 0;
- }
- break;
- }
- default:
- orientation = 0;
- }
- }
-
- // Distance
- float distance;
- switch (mCalibration.distanceCalibration) {
- case Calibration::DISTANCE_CALIBRATION_SCALED:
- distance = in.distance * mDistanceScale;
- break;
- default:
- distance = 0;
- }
-
- // Coverage
- int32_t rawLeft, rawTop, rawRight, rawBottom;
- switch (mCalibration.coverageCalibration) {
- case Calibration::COVERAGE_CALIBRATION_BOX:
- rawLeft = (in.toolMinor & 0xffff0000) >> 16;
- rawRight = in.toolMinor & 0x0000ffff;
- rawBottom = in.toolMajor & 0x0000ffff;
- rawTop = (in.toolMajor & 0xffff0000) >> 16;
- break;
- default:
- rawLeft = rawTop = rawRight = rawBottom = 0;
- break;
- }
-
- // X, Y, and the bounding box for coverage information
- // Adjust coords for surface orientation.
- float x, y, left, top, right, bottom;
- switch (mSurfaceOrientation) {
- case DISPLAY_ORIENTATION_90:
- x = float(in.y - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
- y = float(mRawPointerAxes.x.maxValue - in.x) * mXScale + mXTranslate;
- left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
- right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
- bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
- top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
- orientation -= M_PI_2;
- if (orientation < - M_PI_2) {
- orientation += M_PI;
- }
- break;
- case DISPLAY_ORIENTATION_180:
- x = float(mRawPointerAxes.x.maxValue - in.x) * mXScale + mXTranslate;
- y = float(mRawPointerAxes.y.maxValue - in.y) * mYScale + mYTranslate;
- left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
- right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
- bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
- top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
- break;
- case DISPLAY_ORIENTATION_270:
- x = float(mRawPointerAxes.y.maxValue - in.y) * mYScale + mYTranslate;
- y = float(in.x - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
- left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
- right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
- bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
- top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
- orientation += M_PI_2;
- if (orientation > M_PI_2) {
- orientation -= M_PI;
- }
- break;
- default:
- x = float(in.x - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
- y = float(in.y - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
- left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
- right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
- bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
- top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
- break;
- }
-
- // Write output coords.
- PointerCoords& out = mCurrentCookedPointerData.pointerCoords[i];
- out.clear();
- out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
- out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
- out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
- out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
- out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
- out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
- out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
- out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
- out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
- if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
- out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
- out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
- out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
- out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
- } else {
- out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
- out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
- }
-
- // Write output properties.
- PointerProperties& properties = mCurrentCookedPointerData.pointerProperties[i];
- uint32_t id = in.id;
- properties.clear();
- properties.id = id;
- properties.toolType = in.toolType;
-
- // Write id index.
- mCurrentCookedPointerData.idToIndex[id] = i;
- }
-}
-
-void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
- PointerUsage pointerUsage) {
- if (pointerUsage != mPointerUsage) {
- abortPointerUsage(when, policyFlags);
- mPointerUsage = pointerUsage;
- }
-
- switch (mPointerUsage) {
- case POINTER_USAGE_GESTURES:
- dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
- break;
- case POINTER_USAGE_STYLUS:
- dispatchPointerStylus(when, policyFlags);
- break;
- case POINTER_USAGE_MOUSE:
- dispatchPointerMouse(when, policyFlags);
- break;
- default:
- break;
- }
-}
-
-void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
- switch (mPointerUsage) {
- case POINTER_USAGE_GESTURES:
- abortPointerGestures(when, policyFlags);
- break;
- case POINTER_USAGE_STYLUS:
- abortPointerStylus(when, policyFlags);
- break;
- case POINTER_USAGE_MOUSE:
- abortPointerMouse(when, policyFlags);
- break;
- default:
- break;
- }
-
- mPointerUsage = POINTER_USAGE_NONE;
-}
-
-void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
- bool isTimeout) {
- // Update current gesture coordinates.
- bool cancelPreviousGesture, finishPreviousGesture;
- bool sendEvents = preparePointerGestures(when,
- &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
- if (!sendEvents) {
- return;
- }
- if (finishPreviousGesture) {
- cancelPreviousGesture = false;
- }
-
- // Update the pointer presentation and spots.
- if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
- mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
- if (finishPreviousGesture || cancelPreviousGesture) {
- mPointerController->clearSpots();
- }
- mPointerController->setSpots(mPointerGesture.currentGestureCoords,
- mPointerGesture.currentGestureIdToIndex,
- mPointerGesture.currentGestureIdBits);
- } else {
- mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
- }
-
- // Show or hide the pointer if needed.
- switch (mPointerGesture.currentGestureMode) {
- case PointerGesture::NEUTRAL:
- case PointerGesture::QUIET:
- if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
- && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
- || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
- // Remind the user of where the pointer is after finishing a gesture with spots.
- mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
- }
- break;
- case PointerGesture::TAP:
- case PointerGesture::TAP_DRAG:
- case PointerGesture::BUTTON_CLICK_OR_DRAG:
- case PointerGesture::HOVER:
- case PointerGesture::PRESS:
- // Unfade the pointer when the current gesture manipulates the
- // area directly under the pointer.
- mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
- break;
- case PointerGesture::SWIPE:
- case PointerGesture::FREEFORM:
- // Fade the pointer when the current gesture manipulates a different
- // area and there are spots to guide the user experience.
- if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
- mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
- } else {
- mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
- }
- break;
- }
-
- // Send events!
- int32_t metaState = getContext()->getGlobalMetaState();
- int32_t buttonState = mCurrentButtonState;
-
- // Update last coordinates of pointers that have moved so that we observe the new
- // pointer positions at the same time as other pointers that have just gone up.
- bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
- || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
- || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
- || mPointerGesture.currentGestureMode == PointerGesture::PRESS
- || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
- || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
- bool moveNeeded = false;
- if (down && !cancelPreviousGesture && !finishPreviousGesture
- && !mPointerGesture.lastGestureIdBits.isEmpty()
- && !mPointerGesture.currentGestureIdBits.isEmpty()) {
- BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
- & mPointerGesture.lastGestureIdBits.value);
- moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
- mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
- mPointerGesture.lastGestureProperties,
- mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
- movedGestureIdBits);
- if (buttonState != mLastButtonState) {
- moveNeeded = true;
- }
- }
-
- // Send motion events for all pointers that went up or were canceled.
- BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
- if (!dispatchedGestureIdBits.isEmpty()) {
- if (cancelPreviousGesture) {
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
- AMOTION_EVENT_EDGE_FLAG_NONE,
- mPointerGesture.lastGestureProperties,
- mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
- dispatchedGestureIdBits, -1,
- 0, 0, mPointerGesture.downTime);
-
- dispatchedGestureIdBits.clear();
- } else {
- BitSet32 upGestureIdBits;
- if (finishPreviousGesture) {
- upGestureIdBits = dispatchedGestureIdBits;
- } else {
- upGestureIdBits.value = dispatchedGestureIdBits.value
- & ~mPointerGesture.currentGestureIdBits.value;
- }
- while (!upGestureIdBits.isEmpty()) {
- uint32_t id = upGestureIdBits.clearFirstMarkedBit();
-
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_POINTER_UP, 0,
- metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
- mPointerGesture.lastGestureProperties,
- mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
- dispatchedGestureIdBits, id,
- 0, 0, mPointerGesture.downTime);
-
- dispatchedGestureIdBits.clearBit(id);
- }
- }
- }
-
- // Send motion events for all pointers that moved.
- if (moveNeeded) {
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
- mPointerGesture.currentGestureProperties,
- mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
- dispatchedGestureIdBits, -1,
- 0, 0, mPointerGesture.downTime);
- }
-
- // Send motion events for all pointers that went down.
- if (down) {
- BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
- & ~dispatchedGestureIdBits.value);
- while (!downGestureIdBits.isEmpty()) {
- uint32_t id = downGestureIdBits.clearFirstMarkedBit();
- dispatchedGestureIdBits.markBit(id);
-
- if (dispatchedGestureIdBits.count() == 1) {
- mPointerGesture.downTime = when;
- }
-
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, 0,
- mPointerGesture.currentGestureProperties,
- mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
- dispatchedGestureIdBits, id,
- 0, 0, mPointerGesture.downTime);
- }
- }
-
- // Send motion events for hover.
- if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
- metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
- mPointerGesture.currentGestureProperties,
- mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
- mPointerGesture.currentGestureIdBits, -1,
- 0, 0, mPointerGesture.downTime);
- } else if (dispatchedGestureIdBits.isEmpty()
- && !mPointerGesture.lastGestureIdBits.isEmpty()) {
- // Synthesize a hover move event after all pointers go up to indicate that
- // the pointer is hovering again even if the user is not currently touching
- // the touch pad. This ensures that a view will receive a fresh hover enter
- // event after a tap.
- float x, y;
- mPointerController->getPosition(&x, &y);
-
- PointerProperties pointerProperties;
- pointerProperties.clear();
- pointerProperties.id = 0;
- pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
-
- PointerCoords pointerCoords;
- pointerCoords.clear();
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
-
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
- metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
- mViewport.displayId, 1, &pointerProperties, &pointerCoords,
- 0, 0, mPointerGesture.downTime);
- getListener()->notifyMotion(&args);
- }
-
- // Update state.
- mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
- if (!down) {
- mPointerGesture.lastGestureIdBits.clear();
- } else {
- mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
- for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
- mPointerGesture.lastGestureProperties[index].copyFrom(
- mPointerGesture.currentGestureProperties[index]);
- mPointerGesture.lastGestureCoords[index].copyFrom(
- mPointerGesture.currentGestureCoords[index]);
- mPointerGesture.lastGestureIdToIndex[id] = index;
- }
- }
-}
-
-void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
- // Cancel previously dispatches pointers.
- if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
- int32_t metaState = getContext()->getGlobalMetaState();
- int32_t buttonState = mCurrentButtonState;
- dispatchMotion(when, policyFlags, mSource,
- AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
- AMOTION_EVENT_EDGE_FLAG_NONE,
- mPointerGesture.lastGestureProperties,
- mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
- mPointerGesture.lastGestureIdBits, -1,
- 0, 0, mPointerGesture.downTime);
- }
-
- // Reset the current pointer gesture.
- mPointerGesture.reset();
- mPointerVelocityControl.reset();
-
- // Remove any current spots.
- if (mPointerController != NULL) {
- mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
- mPointerController->clearSpots();
- }
-}
-
-bool TouchInputMapper::preparePointerGestures(nsecs_t when,
- bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
- *outCancelPreviousGesture = false;
- *outFinishPreviousGesture = false;
-
- // Handle TAP timeout.
- if (isTimeout) {
-#if DEBUG_GESTURES
- ALOGD("Gestures: Processing timeout");
-#endif
-
- if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
- if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
- // The tap/drag timeout has not yet expired.
- getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
- + mConfig.pointerGestureTapDragInterval);
- } else {
- // The tap is finished.
-#if DEBUG_GESTURES
- ALOGD("Gestures: TAP finished");
-#endif
- *outFinishPreviousGesture = true;
-
- mPointerGesture.activeGestureId = -1;
- mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
- mPointerGesture.currentGestureIdBits.clear();
-
- mPointerVelocityControl.reset();
- return true;
- }
- }
-
- // We did not handle this timeout.
- return false;
- }
-
- const uint32_t currentFingerCount = mCurrentFingerIdBits.count();
- const uint32_t lastFingerCount = mLastFingerIdBits.count();
-
- // Update the velocity tracker.
- {
- VelocityTracker::Position positions[MAX_POINTERS];
- uint32_t count = 0;
- for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); count++) {
- uint32_t id = idBits.clearFirstMarkedBit();
- const RawPointerData::Pointer& pointer = mCurrentRawPointerData.pointerForId(id);
- positions[count].x = pointer.x * mPointerXMovementScale;
- positions[count].y = pointer.y * mPointerYMovementScale;
- }
- mPointerGesture.velocityTracker.addMovement(when,
- mCurrentFingerIdBits, positions);
- }
-
- // Pick a new active touch id if needed.
- // Choose an arbitrary pointer that just went down, if there is one.
- // Otherwise choose an arbitrary remaining pointer.
- // This guarantees we always have an active touch id when there is at least one pointer.
- // We keep the same active touch id for as long as possible.
- int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
- int32_t activeTouchId = lastActiveTouchId;
- if (activeTouchId < 0) {
- if (!mCurrentFingerIdBits.isEmpty()) {
- activeTouchId = mPointerGesture.activeTouchId =
- mCurrentFingerIdBits.firstMarkedBit();
- mPointerGesture.firstTouchTime = when;
- }
- } else if (!mCurrentFingerIdBits.hasBit(activeTouchId)) {
- if (!mCurrentFingerIdBits.isEmpty()) {
- activeTouchId = mPointerGesture.activeTouchId =
- mCurrentFingerIdBits.firstMarkedBit();
- } else {
- activeTouchId = mPointerGesture.activeTouchId = -1;
- }
- }
-
- // Determine whether we are in quiet time.
- bool isQuietTime = false;
- if (activeTouchId < 0) {
- mPointerGesture.resetQuietTime();
- } else {
- isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
- if (!isQuietTime) {
- if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
- || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
- || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
- && currentFingerCount < 2) {
- // Enter quiet time when exiting swipe or freeform state.
- // This is to prevent accidentally entering the hover state and flinging the
- // pointer when finishing a swipe and there is still one pointer left onscreen.
- isQuietTime = true;
- } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
- && currentFingerCount >= 2
- && !isPointerDown(mCurrentButtonState)) {
- // Enter quiet time when releasing the button and there are still two or more
- // fingers down. This may indicate that one finger was used to press the button
- // but it has not gone up yet.
- isQuietTime = true;
- }
- if (isQuietTime) {
- mPointerGesture.quietTime = when;
- }
- }
- }
-
- // Switch states based on button and pointer state.
- if (isQuietTime) {
- // Case 1: Quiet time. (QUIET)
-#if DEBUG_GESTURES
- ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
- + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
-#endif
- if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
- *outFinishPreviousGesture = true;
- }
-
- mPointerGesture.activeGestureId = -1;
- mPointerGesture.currentGestureMode = PointerGesture::QUIET;
- mPointerGesture.currentGestureIdBits.clear();
-
- mPointerVelocityControl.reset();
- } else if (isPointerDown(mCurrentButtonState)) {
- // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
- // The pointer follows the active touch point.
- // Emit DOWN, MOVE, UP events at the pointer location.
- //
- // Only the active touch matters; other fingers are ignored. This policy helps
- // to handle the case where the user places a second finger on the touch pad
- // to apply the necessary force to depress an integrated button below the surface.
- // We don't want the second finger to be delivered to applications.
- //
- // For this to work well, we need to make sure to track the pointer that is really
- // active. If the user first puts one finger down to click then adds another
- // finger to drag then the active pointer should switch to the finger that is
- // being dragged.
-#if DEBUG_GESTURES
- ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
- "currentFingerCount=%d", activeTouchId, currentFingerCount);
-#endif
- // Reset state when just starting.
- if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
- *outFinishPreviousGesture = true;
- mPointerGesture.activeGestureId = 0;
- }
-
- // Switch pointers if needed.
- // Find the fastest pointer and follow it.
- if (activeTouchId >= 0 && currentFingerCount > 1) {
- int32_t bestId = -1;
- float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
- for (BitSet32 idBits(mCurrentFingerIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- float vx, vy;
- if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
- float speed = hypotf(vx, vy);
- if (speed > bestSpeed) {
- bestId = id;
- bestSpeed = speed;
- }
- }
- }
- if (bestId >= 0 && bestId != activeTouchId) {
- mPointerGesture.activeTouchId = activeTouchId = bestId;
-#if DEBUG_GESTURES
- ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
- "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
-#endif
- }
- }
-
- if (activeTouchId >= 0 && mLastFingerIdBits.hasBit(activeTouchId)) {
- const RawPointerData::Pointer& currentPointer =
- mCurrentRawPointerData.pointerForId(activeTouchId);
- const RawPointerData::Pointer& lastPointer =
- mLastRawPointerData.pointerForId(activeTouchId);
- float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
- float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
-
- rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
- mPointerVelocityControl.move(when, &deltaX, &deltaY);
-
- // Move the pointer using a relative motion.
- // When using spots, the click will occur at the position of the anchor
- // spot and all other spots will move there.
- mPointerController->move(deltaX, deltaY);
- } else {
- mPointerVelocityControl.reset();
- }
-
- float x, y;
- mPointerController->getPosition(&x, &y);
-
- mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
- mPointerGesture.currentGestureIdBits.clear();
- mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
- mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
- mPointerGesture.currentGestureProperties[0].clear();
- mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
- mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
- mPointerGesture.currentGestureCoords[0].clear();
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
- } else if (currentFingerCount == 0) {
- // Case 3. No fingers down and button is not pressed. (NEUTRAL)
- if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
- *outFinishPreviousGesture = true;
- }
-
- // Watch for taps coming out of HOVER or TAP_DRAG mode.
- // Checking for taps after TAP_DRAG allows us to detect double-taps.
- bool tapped = false;
- if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
- || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
- && lastFingerCount == 1) {
- if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
- float x, y;
- mPointerController->getPosition(&x, &y);
- if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
- && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
-#if DEBUG_GESTURES
- ALOGD("Gestures: TAP");
-#endif
-
- mPointerGesture.tapUpTime = when;
- getContext()->requestTimeoutAtTime(when
- + mConfig.pointerGestureTapDragInterval);
-
- mPointerGesture.activeGestureId = 0;
- mPointerGesture.currentGestureMode = PointerGesture::TAP;
- mPointerGesture.currentGestureIdBits.clear();
- mPointerGesture.currentGestureIdBits.markBit(
- mPointerGesture.activeGestureId);
- mPointerGesture.currentGestureIdToIndex[
- mPointerGesture.activeGestureId] = 0;
- mPointerGesture.currentGestureProperties[0].clear();
- mPointerGesture.currentGestureProperties[0].id =
- mPointerGesture.activeGestureId;
- mPointerGesture.currentGestureProperties[0].toolType =
- AMOTION_EVENT_TOOL_TYPE_FINGER;
- mPointerGesture.currentGestureCoords[0].clear();
- mPointerGesture.currentGestureCoords[0].setAxisValue(
- AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
- mPointerGesture.currentGestureCoords[0].setAxisValue(
- AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
- mPointerGesture.currentGestureCoords[0].setAxisValue(
- AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
-
- tapped = true;
- } else {
-#if DEBUG_GESTURES
- ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
- x - mPointerGesture.tapX,
- y - mPointerGesture.tapY);
-#endif
- }
- } else {
-#if DEBUG_GESTURES
- ALOGD("Gestures: Not a TAP, %0.3fms since down",
- (when - mPointerGesture.tapDownTime) * 0.000001f);
-#endif
- }
- }
-
- mPointerVelocityControl.reset();
-
- if (!tapped) {
-#if DEBUG_GESTURES
- ALOGD("Gestures: NEUTRAL");
-#endif
- mPointerGesture.activeGestureId = -1;
- mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
- mPointerGesture.currentGestureIdBits.clear();
- }
- } else if (currentFingerCount == 1) {
- // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
- // The pointer follows the active touch point.
- // When in HOVER, emit HOVER_MOVE events at the pointer location.
- // When in TAP_DRAG, emit MOVE events at the pointer location.
- ALOG_ASSERT(activeTouchId >= 0);
-
- mPointerGesture.currentGestureMode = PointerGesture::HOVER;
- if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
- if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
- float x, y;
- mPointerController->getPosition(&x, &y);
- if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
- && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
- mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
- } else {
-#if DEBUG_GESTURES
- ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
- x - mPointerGesture.tapX,
- y - mPointerGesture.tapY);
-#endif
- }
- } else {
-#if DEBUG_GESTURES
- ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
- (when - mPointerGesture.tapUpTime) * 0.000001f);
-#endif
- }
- } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
- mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
- }
-
- if (mLastFingerIdBits.hasBit(activeTouchId)) {
- const RawPointerData::Pointer& currentPointer =
- mCurrentRawPointerData.pointerForId(activeTouchId);
- const RawPointerData::Pointer& lastPointer =
- mLastRawPointerData.pointerForId(activeTouchId);
- float deltaX = (currentPointer.x - lastPointer.x)
- * mPointerXMovementScale;
- float deltaY = (currentPointer.y - lastPointer.y)
- * mPointerYMovementScale;
-
- rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
- mPointerVelocityControl.move(when, &deltaX, &deltaY);
-
- // Move the pointer using a relative motion.
- // When using spots, the hover or drag will occur at the position of the anchor spot.
- mPointerController->move(deltaX, deltaY);
- } else {
- mPointerVelocityControl.reset();
- }
-
- bool down;
- if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
-#if DEBUG_GESTURES
- ALOGD("Gestures: TAP_DRAG");
-#endif
- down = true;
- } else {
-#if DEBUG_GESTURES
- ALOGD("Gestures: HOVER");
-#endif
- if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
- *outFinishPreviousGesture = true;
- }
- mPointerGesture.activeGestureId = 0;
- down = false;
- }
-
- float x, y;
- mPointerController->getPosition(&x, &y);
-
- mPointerGesture.currentGestureIdBits.clear();
- mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
- mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
- mPointerGesture.currentGestureProperties[0].clear();
- mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
- mPointerGesture.currentGestureProperties[0].toolType =
- AMOTION_EVENT_TOOL_TYPE_FINGER;
- mPointerGesture.currentGestureCoords[0].clear();
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
- down ? 1.0f : 0.0f);
-
- if (lastFingerCount == 0 && currentFingerCount != 0) {
- mPointerGesture.resetTap();
- mPointerGesture.tapDownTime = when;
- mPointerGesture.tapX = x;
- mPointerGesture.tapY = y;
- }
- } else {
- // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
- // We need to provide feedback for each finger that goes down so we cannot wait
- // for the fingers to move before deciding what to do.
- //
- // The ambiguous case is deciding what to do when there are two fingers down but they
- // have not moved enough to determine whether they are part of a drag or part of a
- // freeform gesture, or just a press or long-press at the pointer location.
- //
- // When there are two fingers we start with the PRESS hypothesis and we generate a
- // down at the pointer location.
- //
- // When the two fingers move enough or when additional fingers are added, we make
- // a decision to transition into SWIPE or FREEFORM mode accordingly.
- ALOG_ASSERT(activeTouchId >= 0);
-
- bool settled = when >= mPointerGesture.firstTouchTime
- + mConfig.pointerGestureMultitouchSettleInterval;
- if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
- && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
- && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
- *outFinishPreviousGesture = true;
- } else if (!settled && currentFingerCount > lastFingerCount) {
- // Additional pointers have gone down but not yet settled.
- // Reset the gesture.
-#if DEBUG_GESTURES
- ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
- "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
- + mConfig.pointerGestureMultitouchSettleInterval - when)
- * 0.000001f);
-#endif
- *outCancelPreviousGesture = true;
- } else {
- // Continue previous gesture.
- mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
- }
-
- if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
- mPointerGesture.currentGestureMode = PointerGesture::PRESS;
- mPointerGesture.activeGestureId = 0;
- mPointerGesture.referenceIdBits.clear();
- mPointerVelocityControl.reset();
-
- // Use the centroid and pointer location as the reference points for the gesture.
-#if DEBUG_GESTURES
- ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
- "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
- + mConfig.pointerGestureMultitouchSettleInterval - when)
- * 0.000001f);
-#endif
- mCurrentRawPointerData.getCentroidOfTouchingPointers(
- &mPointerGesture.referenceTouchX,
- &mPointerGesture.referenceTouchY);
- mPointerController->getPosition(&mPointerGesture.referenceGestureX,
- &mPointerGesture.referenceGestureY);
- }
-
- // Clear the reference deltas for fingers not yet included in the reference calculation.
- for (BitSet32 idBits(mCurrentFingerIdBits.value
- & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- mPointerGesture.referenceDeltas[id].dx = 0;
- mPointerGesture.referenceDeltas[id].dy = 0;
- }
- mPointerGesture.referenceIdBits = mCurrentFingerIdBits;
-
- // Add delta for all fingers and calculate a common movement delta.
- float commonDeltaX = 0, commonDeltaY = 0;
- BitSet32 commonIdBits(mLastFingerIdBits.value
- & mCurrentFingerIdBits.value);
- for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
- bool first = (idBits == commonIdBits);
- uint32_t id = idBits.clearFirstMarkedBit();
- const RawPointerData::Pointer& cpd = mCurrentRawPointerData.pointerForId(id);
- const RawPointerData::Pointer& lpd = mLastRawPointerData.pointerForId(id);
- PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
- delta.dx += cpd.x - lpd.x;
- delta.dy += cpd.y - lpd.y;
-
- if (first) {
- commonDeltaX = delta.dx;
- commonDeltaY = delta.dy;
- } else {
- commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
- commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
- }
- }
-
- // Consider transitions from PRESS to SWIPE or MULTITOUCH.
- if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
- float dist[MAX_POINTER_ID + 1];
- int32_t distOverThreshold = 0;
- for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
- dist[id] = hypotf(delta.dx * mPointerXZoomScale,
- delta.dy * mPointerYZoomScale);
- if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
- distOverThreshold += 1;
- }
- }
-
- // Only transition when at least two pointers have moved further than
- // the minimum distance threshold.
- if (distOverThreshold >= 2) {
- if (currentFingerCount > 2) {
- // There are more than two pointers, switch to FREEFORM.
-#if DEBUG_GESTURES
- ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
- currentFingerCount);
-#endif
- *outCancelPreviousGesture = true;
- mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
- } else {
- // There are exactly two pointers.
- BitSet32 idBits(mCurrentFingerIdBits);
- uint32_t id1 = idBits.clearFirstMarkedBit();
- uint32_t id2 = idBits.firstMarkedBit();
- const RawPointerData::Pointer& p1 = mCurrentRawPointerData.pointerForId(id1);
- const RawPointerData::Pointer& p2 = mCurrentRawPointerData.pointerForId(id2);
- float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
- if (mutualDistance > mPointerGestureMaxSwipeWidth) {
- // There are two pointers but they are too far apart for a SWIPE,
- // switch to FREEFORM.
-#if DEBUG_GESTURES
- ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
- mutualDistance, mPointerGestureMaxSwipeWidth);
-#endif
- *outCancelPreviousGesture = true;
- mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
- } else {
- // There are two pointers. Wait for both pointers to start moving
- // before deciding whether this is a SWIPE or FREEFORM gesture.
- float dist1 = dist[id1];
- float dist2 = dist[id2];
- if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
- && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
- // Calculate the dot product of the displacement vectors.
- // When the vectors are oriented in approximately the same direction,
- // the angle betweeen them is near zero and the cosine of the angle
- // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
- PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
- PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
- float dx1 = delta1.dx * mPointerXZoomScale;
- float dy1 = delta1.dy * mPointerYZoomScale;
- float dx2 = delta2.dx * mPointerXZoomScale;
- float dy2 = delta2.dy * mPointerYZoomScale;
- float dot = dx1 * dx2 + dy1 * dy2;
- float cosine = dot / (dist1 * dist2); // denominator always > 0
- if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
- // Pointers are moving in the same direction. Switch to SWIPE.
-#if DEBUG_GESTURES
- ALOGD("Gestures: PRESS transitioned to SWIPE, "
- "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
- "cosine %0.3f >= %0.3f",
- dist1, mConfig.pointerGestureMultitouchMinDistance,
- dist2, mConfig.pointerGestureMultitouchMinDistance,
- cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
-#endif
- mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
- } else {
- // Pointers are moving in different directions. Switch to FREEFORM.
-#if DEBUG_GESTURES
- ALOGD("Gestures: PRESS transitioned to FREEFORM, "
- "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
- "cosine %0.3f < %0.3f",
- dist1, mConfig.pointerGestureMultitouchMinDistance,
- dist2, mConfig.pointerGestureMultitouchMinDistance,
- cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
-#endif
- *outCancelPreviousGesture = true;
- mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
- }
- }
- }
- }
- }
- } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
- // Switch from SWIPE to FREEFORM if additional pointers go down.
- // Cancel previous gesture.
- if (currentFingerCount > 2) {
-#if DEBUG_GESTURES
- ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
- currentFingerCount);
-#endif
- *outCancelPreviousGesture = true;
- mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
- }
- }
-
- // Move the reference points based on the overall group motion of the fingers
- // except in PRESS mode while waiting for a transition to occur.
- if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
- && (commonDeltaX || commonDeltaY)) {
- for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
- delta.dx = 0;
- delta.dy = 0;
- }
-
- mPointerGesture.referenceTouchX += commonDeltaX;
- mPointerGesture.referenceTouchY += commonDeltaY;
-
- commonDeltaX *= mPointerXMovementScale;
- commonDeltaY *= mPointerYMovementScale;
-
- rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
- mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
-
- mPointerGesture.referenceGestureX += commonDeltaX;
- mPointerGesture.referenceGestureY += commonDeltaY;
- }
-
- // Report gestures.
- if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
- || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
- // PRESS or SWIPE mode.
-#if DEBUG_GESTURES
- ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
- "activeGestureId=%d, currentTouchPointerCount=%d",
- activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
-#endif
- ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
-
- mPointerGesture.currentGestureIdBits.clear();
- mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
- mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
- mPointerGesture.currentGestureProperties[0].clear();
- mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
- mPointerGesture.currentGestureProperties[0].toolType =
- AMOTION_EVENT_TOOL_TYPE_FINGER;
- mPointerGesture.currentGestureCoords[0].clear();
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
- mPointerGesture.referenceGestureX);
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
- mPointerGesture.referenceGestureY);
- mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
- } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
- // FREEFORM mode.
-#if DEBUG_GESTURES
- ALOGD("Gestures: FREEFORM activeTouchId=%d,"
- "activeGestureId=%d, currentTouchPointerCount=%d",
- activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
-#endif
- ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
-
- mPointerGesture.currentGestureIdBits.clear();
-
- BitSet32 mappedTouchIdBits;
- BitSet32 usedGestureIdBits;
- if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
- // Initially, assign the active gesture id to the active touch point
- // if there is one. No other touch id bits are mapped yet.
- if (!*outCancelPreviousGesture) {
- mappedTouchIdBits.markBit(activeTouchId);
- usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
- mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
- mPointerGesture.activeGestureId;
- } else {
- mPointerGesture.activeGestureId = -1;
- }
- } else {
- // Otherwise, assume we mapped all touches from the previous frame.
- // Reuse all mappings that are still applicable.
- mappedTouchIdBits.value = mLastFingerIdBits.value
- & mCurrentFingerIdBits.value;
- usedGestureIdBits = mPointerGesture.lastGestureIdBits;
-
- // Check whether we need to choose a new active gesture id because the
- // current went went up.
- for (BitSet32 upTouchIdBits(mLastFingerIdBits.value
- & ~mCurrentFingerIdBits.value);
- !upTouchIdBits.isEmpty(); ) {
- uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
- uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
- if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
- mPointerGesture.activeGestureId = -1;
- break;
- }
- }
- }
-
-#if DEBUG_GESTURES
- ALOGD("Gestures: FREEFORM follow up "
- "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
- "activeGestureId=%d",
- mappedTouchIdBits.value, usedGestureIdBits.value,
- mPointerGesture.activeGestureId);
-#endif
-
- BitSet32 idBits(mCurrentFingerIdBits);
- for (uint32_t i = 0; i < currentFingerCount; i++) {
- uint32_t touchId = idBits.clearFirstMarkedBit();
- uint32_t gestureId;
- if (!mappedTouchIdBits.hasBit(touchId)) {
- gestureId = usedGestureIdBits.markFirstUnmarkedBit();
- mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
-#if DEBUG_GESTURES
- ALOGD("Gestures: FREEFORM "
- "new mapping for touch id %d -> gesture id %d",
- touchId, gestureId);
-#endif
- } else {
- gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
-#if DEBUG_GESTURES
- ALOGD("Gestures: FREEFORM "
- "existing mapping for touch id %d -> gesture id %d",
- touchId, gestureId);
-#endif
- }
- mPointerGesture.currentGestureIdBits.markBit(gestureId);
- mPointerGesture.currentGestureIdToIndex[gestureId] = i;
-
- const RawPointerData::Pointer& pointer =
- mCurrentRawPointerData.pointerForId(touchId);
- float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
- * mPointerXZoomScale;
- float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
- * mPointerYZoomScale;
- rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
-
- mPointerGesture.currentGestureProperties[i].clear();
- mPointerGesture.currentGestureProperties[i].id = gestureId;
- mPointerGesture.currentGestureProperties[i].toolType =
- AMOTION_EVENT_TOOL_TYPE_FINGER;
- mPointerGesture.currentGestureCoords[i].clear();
- mPointerGesture.currentGestureCoords[i].setAxisValue(
- AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
- mPointerGesture.currentGestureCoords[i].setAxisValue(
- AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
- mPointerGesture.currentGestureCoords[i].setAxisValue(
- AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
- }
-
- if (mPointerGesture.activeGestureId < 0) {
- mPointerGesture.activeGestureId =
- mPointerGesture.currentGestureIdBits.firstMarkedBit();
-#if DEBUG_GESTURES
- ALOGD("Gestures: FREEFORM new "
- "activeGestureId=%d", mPointerGesture.activeGestureId);
-#endif
- }
- }
- }
-
- mPointerController->setButtonState(mCurrentButtonState);
-
-#if DEBUG_GESTURES
- ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
- "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
- "lastGestureMode=%d, lastGestureIdBits=0x%08x",
- toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
- mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
- mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
- for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
- const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
- const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
- ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
- "x=%0.3f, y=%0.3f, pressure=%0.3f",
- id, index, properties.toolType,
- coords.getAxisValue(AMOTION_EVENT_AXIS_X),
- coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
- coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
- }
- for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
- const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
- const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
- ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
- "x=%0.3f, y=%0.3f, pressure=%0.3f",
- id, index, properties.toolType,
- coords.getAxisValue(AMOTION_EVENT_AXIS_X),
- coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
- coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
- }
-#endif
- return true;
-}
-
-void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
- mPointerSimple.currentCoords.clear();
- mPointerSimple.currentProperties.clear();
-
- bool down, hovering;
- if (!mCurrentStylusIdBits.isEmpty()) {
- uint32_t id = mCurrentStylusIdBits.firstMarkedBit();
- uint32_t index = mCurrentCookedPointerData.idToIndex[id];
- float x = mCurrentCookedPointerData.pointerCoords[index].getX();
- float y = mCurrentCookedPointerData.pointerCoords[index].getY();
- mPointerController->setPosition(x, y);
-
- hovering = mCurrentCookedPointerData.hoveringIdBits.hasBit(id);
- down = !hovering;
-
- mPointerController->getPosition(&x, &y);
- mPointerSimple.currentCoords.copyFrom(mCurrentCookedPointerData.pointerCoords[index]);
- mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
- mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
- mPointerSimple.currentProperties.id = 0;
- mPointerSimple.currentProperties.toolType =
- mCurrentCookedPointerData.pointerProperties[index].toolType;
- } else {
- down = false;
- hovering = false;
- }
-
- dispatchPointerSimple(when, policyFlags, down, hovering);
-}
-
-void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
- abortPointerSimple(when, policyFlags);
-}
-
-void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
- mPointerSimple.currentCoords.clear();
- mPointerSimple.currentProperties.clear();
-
- bool down, hovering;
- if (!mCurrentMouseIdBits.isEmpty()) {
- uint32_t id = mCurrentMouseIdBits.firstMarkedBit();
- uint32_t currentIndex = mCurrentRawPointerData.idToIndex[id];
- if (mLastMouseIdBits.hasBit(id)) {
- uint32_t lastIndex = mCurrentRawPointerData.idToIndex[id];
- float deltaX = (mCurrentRawPointerData.pointers[currentIndex].x
- - mLastRawPointerData.pointers[lastIndex].x)
- * mPointerXMovementScale;
- float deltaY = (mCurrentRawPointerData.pointers[currentIndex].y
- - mLastRawPointerData.pointers[lastIndex].y)
- * mPointerYMovementScale;
-
- rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
- mPointerVelocityControl.move(when, &deltaX, &deltaY);
-
- mPointerController->move(deltaX, deltaY);
- } else {
- mPointerVelocityControl.reset();
- }
-
- down = isPointerDown(mCurrentButtonState);
- hovering = !down;
-
- float x, y;
- mPointerController->getPosition(&x, &y);
- mPointerSimple.currentCoords.copyFrom(
- mCurrentCookedPointerData.pointerCoords[currentIndex]);
- mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
- mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
- mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
- hovering ? 0.0f : 1.0f);
- mPointerSimple.currentProperties.id = 0;
- mPointerSimple.currentProperties.toolType =
- mCurrentCookedPointerData.pointerProperties[currentIndex].toolType;
- } else {
- mPointerVelocityControl.reset();
-
- down = false;
- hovering = false;
- }
-
- dispatchPointerSimple(when, policyFlags, down, hovering);
-}
-
-void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
- abortPointerSimple(when, policyFlags);
-
- mPointerVelocityControl.reset();
-}
-
-void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
- bool down, bool hovering) {
- int32_t metaState = getContext()->getGlobalMetaState();
-
- if (mPointerController != NULL) {
- if (down || hovering) {
- mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
- mPointerController->clearSpots();
- mPointerController->setButtonState(mCurrentButtonState);
- mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
- } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
- mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
- }
- }
-
- if (mPointerSimple.down && !down) {
- mPointerSimple.down = false;
-
- // Send up.
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_UP, 0, metaState, mLastButtonState, 0,
- mViewport.displayId,
- 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
- mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
- getListener()->notifyMotion(&args);
- }
-
- if (mPointerSimple.hovering && !hovering) {
- mPointerSimple.hovering = false;
-
- // Send hover exit.
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_HOVER_EXIT, 0, metaState, mLastButtonState, 0,
- mViewport.displayId,
- 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
- mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
- getListener()->notifyMotion(&args);
- }
-
- if (down) {
- if (!mPointerSimple.down) {
- mPointerSimple.down = true;
- mPointerSimple.downTime = when;
-
- // Send down.
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_DOWN, 0, metaState, mCurrentButtonState, 0,
- mViewport.displayId,
- 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
- mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
- getListener()->notifyMotion(&args);
- }
-
- // Send move.
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_MOVE, 0, metaState, mCurrentButtonState, 0,
- mViewport.displayId,
- 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
- mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
- getListener()->notifyMotion(&args);
- }
-
- if (hovering) {
- if (!mPointerSimple.hovering) {
- mPointerSimple.hovering = true;
-
- // Send hover enter.
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_HOVER_ENTER, 0, metaState, mCurrentButtonState, 0,
- mViewport.displayId,
- 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
- mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
- getListener()->notifyMotion(&args);
- }
-
- // Send hover move.
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, mCurrentButtonState, 0,
- mViewport.displayId,
- 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
- mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
- getListener()->notifyMotion(&args);
- }
-
- if (mCurrentRawVScroll || mCurrentRawHScroll) {
- float vscroll = mCurrentRawVScroll;
- float hscroll = mCurrentRawHScroll;
- mWheelYVelocityControl.move(when, NULL, &vscroll);
- mWheelXVelocityControl.move(when, &hscroll, NULL);
-
- // Send scroll.
- PointerCoords pointerCoords;
- pointerCoords.copyFrom(mPointerSimple.currentCoords);
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
- pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
-
- NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
- AMOTION_EVENT_ACTION_SCROLL, 0, metaState, mCurrentButtonState, 0,
- mViewport.displayId,
- 1, &mPointerSimple.currentProperties, &pointerCoords,
- mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
- getListener()->notifyMotion(&args);
- }
-
- // Save state.
- if (down || hovering) {
- mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
- mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
- } else {
- mPointerSimple.reset();
- }
-}
-
-void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
- mPointerSimple.currentCoords.clear();
- mPointerSimple.currentProperties.clear();
-
- dispatchPointerSimple(when, policyFlags, false, false);
-}
-
-void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
- int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
- const PointerProperties* properties, const PointerCoords* coords,
- const uint32_t* idToIndex, BitSet32 idBits,
- int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
- PointerCoords pointerCoords[MAX_POINTERS];
- PointerProperties pointerProperties[MAX_POINTERS];
- uint32_t pointerCount = 0;
- while (!idBits.isEmpty()) {
- uint32_t id = idBits.clearFirstMarkedBit();
- uint32_t index = idToIndex[id];
- pointerProperties[pointerCount].copyFrom(properties[index]);
- pointerCoords[pointerCount].copyFrom(coords[index]);
-
- if (changedId >= 0 && id == uint32_t(changedId)) {
- action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
- }
-
- pointerCount += 1;
- }
-
- ALOG_ASSERT(pointerCount != 0);
-
- if (changedId >= 0 && pointerCount == 1) {
- // Replace initial down and final up action.
- // We can compare the action without masking off the changed pointer index
- // because we know the index is 0.
- if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
- action = AMOTION_EVENT_ACTION_DOWN;
- } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
- action = AMOTION_EVENT_ACTION_UP;
- } else {
- // Can't happen.
- ALOG_ASSERT(false);
- }
- }
-
- NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
- action, flags, metaState, buttonState, edgeFlags,
- mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
- xPrecision, yPrecision, downTime);
- getListener()->notifyMotion(&args);
-}
-
-bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
- const PointerCoords* inCoords, const uint32_t* inIdToIndex,
- PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
- BitSet32 idBits) const {
- bool changed = false;
- while (!idBits.isEmpty()) {
- uint32_t id = idBits.clearFirstMarkedBit();
- uint32_t inIndex = inIdToIndex[id];
- uint32_t outIndex = outIdToIndex[id];
-
- const PointerProperties& curInProperties = inProperties[inIndex];
- const PointerCoords& curInCoords = inCoords[inIndex];
- PointerProperties& curOutProperties = outProperties[outIndex];
- PointerCoords& curOutCoords = outCoords[outIndex];
-
- if (curInProperties != curOutProperties) {
- curOutProperties.copyFrom(curInProperties);
- changed = true;
- }
-
- if (curInCoords != curOutCoords) {
- curOutCoords.copyFrom(curInCoords);
- changed = true;
- }
- }
- return changed;
-}
-
-void TouchInputMapper::fadePointer() {
- if (mPointerController != NULL) {
- mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
- }
-}
-
-bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
- return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
- && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
-}
-
-const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
- int32_t x, int32_t y) {
- size_t numVirtualKeys = mVirtualKeys.size();
- for (size_t i = 0; i < numVirtualKeys; i++) {
- const VirtualKey& virtualKey = mVirtualKeys[i];
-
-#if DEBUG_VIRTUAL_KEYS
- ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
- "left=%d, top=%d, right=%d, bottom=%d",
- x, y,
- virtualKey.keyCode, virtualKey.scanCode,
- virtualKey.hitLeft, virtualKey.hitTop,
- virtualKey.hitRight, virtualKey.hitBottom);
-#endif
-
- if (virtualKey.isHit(x, y)) {
- return & virtualKey;
- }
- }
-
- return NULL;
-}
-
-void TouchInputMapper::assignPointerIds() {
- uint32_t currentPointerCount = mCurrentRawPointerData.pointerCount;
- uint32_t lastPointerCount = mLastRawPointerData.pointerCount;
-
- mCurrentRawPointerData.clearIdBits();
-
- if (currentPointerCount == 0) {
- // No pointers to assign.
- return;
- }
-
- if (lastPointerCount == 0) {
- // All pointers are new.
- for (uint32_t i = 0; i < currentPointerCount; i++) {
- uint32_t id = i;
- mCurrentRawPointerData.pointers[i].id = id;
- mCurrentRawPointerData.idToIndex[id] = i;
- mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(i));
- }
- return;
- }
-
- if (currentPointerCount == 1 && lastPointerCount == 1
- && mCurrentRawPointerData.pointers[0].toolType
- == mLastRawPointerData.pointers[0].toolType) {
- // Only one pointer and no change in count so it must have the same id as before.
- uint32_t id = mLastRawPointerData.pointers[0].id;
- mCurrentRawPointerData.pointers[0].id = id;
- mCurrentRawPointerData.idToIndex[id] = 0;
- mCurrentRawPointerData.markIdBit(id, mCurrentRawPointerData.isHovering(0));
- return;
- }
-
- // General case.
- // We build a heap of squared euclidean distances between current and last pointers
- // associated with the current and last pointer indices. Then, we find the best
- // match (by distance) for each current pointer.
- // The pointers must have the same tool type but it is possible for them to
- // transition from hovering to touching or vice-versa while retaining the same id.
- PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
-
- uint32_t heapSize = 0;
- for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
- currentPointerIndex++) {
- for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
- lastPointerIndex++) {
- const RawPointerData::Pointer& currentPointer =
- mCurrentRawPointerData.pointers[currentPointerIndex];
- const RawPointerData::Pointer& lastPointer =
- mLastRawPointerData.pointers[lastPointerIndex];
- if (currentPointer.toolType == lastPointer.toolType) {
- int64_t deltaX = currentPointer.x - lastPointer.x;
- int64_t deltaY = currentPointer.y - lastPointer.y;
-
- uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
-
- // Insert new element into the heap (sift up).
- heap[heapSize].currentPointerIndex = currentPointerIndex;
- heap[heapSize].lastPointerIndex = lastPointerIndex;
- heap[heapSize].distance = distance;
- heapSize += 1;
- }
- }
- }
-
- // Heapify
- for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
- startIndex -= 1;
- for (uint32_t parentIndex = startIndex; ;) {
- uint32_t childIndex = parentIndex * 2 + 1;
- if (childIndex >= heapSize) {
- break;
- }
-
- if (childIndex + 1 < heapSize
- && heap[childIndex + 1].distance < heap[childIndex].distance) {
- childIndex += 1;
- }
-
- if (heap[parentIndex].distance <= heap[childIndex].distance) {
- break;
- }
-
- swap(heap[parentIndex], heap[childIndex]);
- parentIndex = childIndex;
- }
- }
-
-#if DEBUG_POINTER_ASSIGNMENT
- ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
- for (size_t i = 0; i < heapSize; i++) {
- ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
- i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
- heap[i].distance);
- }
-#endif
-
- // Pull matches out by increasing order of distance.
- // To avoid reassigning pointers that have already been matched, the loop keeps track
- // of which last and current pointers have been matched using the matchedXXXBits variables.
- // It also tracks the used pointer id bits.
- BitSet32 matchedLastBits(0);
- BitSet32 matchedCurrentBits(0);
- BitSet32 usedIdBits(0);
- bool first = true;
- for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
- while (heapSize > 0) {
- if (first) {
- // The first time through the loop, we just consume the root element of
- // the heap (the one with smallest distance).
- first = false;
- } else {
- // Previous iterations consumed the root element of the heap.
- // Pop root element off of the heap (sift down).
- heap[0] = heap[heapSize];
- for (uint32_t parentIndex = 0; ;) {
- uint32_t childIndex = parentIndex * 2 + 1;
- if (childIndex >= heapSize) {
- break;
- }
-
- if (childIndex + 1 < heapSize
- && heap[childIndex + 1].distance < heap[childIndex].distance) {
- childIndex += 1;
- }
-
- if (heap[parentIndex].distance <= heap[childIndex].distance) {
- break;
- }
-
- swap(heap[parentIndex], heap[childIndex]);
- parentIndex = childIndex;
- }
-
-#if DEBUG_POINTER_ASSIGNMENT
- ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
- for (size_t i = 0; i < heapSize; i++) {
- ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
- i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
- heap[i].distance);
- }
-#endif
- }
-
- heapSize -= 1;
-
- uint32_t currentPointerIndex = heap[0].currentPointerIndex;
- if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
-
- uint32_t lastPointerIndex = heap[0].lastPointerIndex;
- if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
-
- matchedCurrentBits.markBit(currentPointerIndex);
- matchedLastBits.markBit(lastPointerIndex);
-
- uint32_t id = mLastRawPointerData.pointers[lastPointerIndex].id;
- mCurrentRawPointerData.pointers[currentPointerIndex].id = id;
- mCurrentRawPointerData.idToIndex[id] = currentPointerIndex;
- mCurrentRawPointerData.markIdBit(id,
- mCurrentRawPointerData.isHovering(currentPointerIndex));
- usedIdBits.markBit(id);
-
-#if DEBUG_POINTER_ASSIGNMENT
- ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
- lastPointerIndex, currentPointerIndex, id, heap[0].distance);
-#endif
- break;
- }
- }
-
- // Assign fresh ids to pointers that were not matched in the process.
- for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
- uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
- uint32_t id = usedIdBits.markFirstUnmarkedBit();
-
- mCurrentRawPointerData.pointers[currentPointerIndex].id = id;
- mCurrentRawPointerData.idToIndex[id] = currentPointerIndex;
- mCurrentRawPointerData.markIdBit(id,
- mCurrentRawPointerData.isHovering(currentPointerIndex));
-
-#if DEBUG_POINTER_ASSIGNMENT
- ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
- currentPointerIndex, id);
-#endif
- }
-}
-
-int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
- if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
- return AKEY_STATE_VIRTUAL;
- }
-
- size_t numVirtualKeys = mVirtualKeys.size();
- for (size_t i = 0; i < numVirtualKeys; i++) {
- const VirtualKey& virtualKey = mVirtualKeys[i];
- if (virtualKey.keyCode == keyCode) {
- return AKEY_STATE_UP;
- }
- }
-
- return AKEY_STATE_UNKNOWN;
-}
-
-int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
- if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
- return AKEY_STATE_VIRTUAL;
- }
-
- size_t numVirtualKeys = mVirtualKeys.size();
- for (size_t i = 0; i < numVirtualKeys; i++) {
- const VirtualKey& virtualKey = mVirtualKeys[i];
- if (virtualKey.scanCode == scanCode) {
- return AKEY_STATE_UP;
- }
- }
-
- return AKEY_STATE_UNKNOWN;
-}
-
-bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags) {
- size_t numVirtualKeys = mVirtualKeys.size();
- for (size_t i = 0; i < numVirtualKeys; i++) {
- const VirtualKey& virtualKey = mVirtualKeys[i];
-
- for (size_t i = 0; i < numCodes; i++) {
- if (virtualKey.keyCode == keyCodes[i]) {
- outFlags[i] = 1;
- }
- }
- }
-
- return true;
-}
-
-
-// --- SingleTouchInputMapper ---
-
-SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
- TouchInputMapper(device) {
-}
-
-SingleTouchInputMapper::~SingleTouchInputMapper() {
-}
-
-void SingleTouchInputMapper::reset(nsecs_t when) {
- mSingleTouchMotionAccumulator.reset(getDevice());
-
- TouchInputMapper::reset(when);
-}
-
-void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
- TouchInputMapper::process(rawEvent);
-
- mSingleTouchMotionAccumulator.process(rawEvent);
-}
-
-void SingleTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) {
- if (mTouchButtonAccumulator.isToolActive()) {
- mCurrentRawPointerData.pointerCount = 1;
- mCurrentRawPointerData.idToIndex[0] = 0;
-
- bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
- && (mTouchButtonAccumulator.isHovering()
- || (mRawPointerAxes.pressure.valid
- && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
- mCurrentRawPointerData.markIdBit(0, isHovering);
-
- RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[0];
- outPointer.id = 0;
- outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
- outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
- outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
- outPointer.touchMajor = 0;
- outPointer.touchMinor = 0;
- outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
- outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
- outPointer.orientation = 0;
- outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
- outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
- outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
- outPointer.toolType = mTouchButtonAccumulator.getToolType();
- if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
- outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
- }
- outPointer.isHovering = isHovering;
- }
-}
-
-void SingleTouchInputMapper::configureRawPointerAxes() {
- TouchInputMapper::configureRawPointerAxes();
-
- getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
- getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
- getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
- getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
- getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
- getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
- getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
-}
-
-bool SingleTouchInputMapper::hasStylus() const {
- return mTouchButtonAccumulator.hasStylus();
-}
-
-
-// --- MultiTouchInputMapper ---
-
-MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
- TouchInputMapper(device) {
-}
-
-MultiTouchInputMapper::~MultiTouchInputMapper() {
-}
-
-void MultiTouchInputMapper::reset(nsecs_t when) {
- mMultiTouchMotionAccumulator.reset(getDevice());
-
- mPointerIdBits.clear();
-
- TouchInputMapper::reset(when);
-}
-
-void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
- TouchInputMapper::process(rawEvent);
-
- mMultiTouchMotionAccumulator.process(rawEvent);
-}
-
-void MultiTouchInputMapper::syncTouch(nsecs_t when, bool* outHavePointerIds) {
- size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
- size_t outCount = 0;
- BitSet32 newPointerIdBits;
-
- for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
- const MultiTouchMotionAccumulator::Slot* inSlot =
- mMultiTouchMotionAccumulator.getSlot(inIndex);
- if (!inSlot->isInUse()) {
- continue;
- }
-
- if (outCount >= MAX_POINTERS) {
-#if DEBUG_POINTERS
- ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
- "ignoring the rest.",
- getDeviceName().string(), MAX_POINTERS);
-#endif
- break; // too many fingers!
- }
-
- RawPointerData::Pointer& outPointer = mCurrentRawPointerData.pointers[outCount];
- outPointer.x = inSlot->getX();
- outPointer.y = inSlot->getY();
- outPointer.pressure = inSlot->getPressure();
- outPointer.touchMajor = inSlot->getTouchMajor();
- outPointer.touchMinor = inSlot->getTouchMinor();
- outPointer.toolMajor = inSlot->getToolMajor();
- outPointer.toolMinor = inSlot->getToolMinor();
- outPointer.orientation = inSlot->getOrientation();
- outPointer.distance = inSlot->getDistance();
- outPointer.tiltX = 0;
- outPointer.tiltY = 0;
-
- outPointer.toolType = inSlot->getToolType();
- if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
- outPointer.toolType = mTouchButtonAccumulator.getToolType();
- if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
- outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
- }
- }
-
- bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
- && (mTouchButtonAccumulator.isHovering()
- || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
- outPointer.isHovering = isHovering;
-
- // Assign pointer id using tracking id if available.
- if (*outHavePointerIds) {
- int32_t trackingId = inSlot->getTrackingId();
- int32_t id = -1;
- if (trackingId >= 0) {
- for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
- uint32_t n = idBits.clearFirstMarkedBit();
- if (mPointerTrackingIdMap[n] == trackingId) {
- id = n;
- }
- }
-
- if (id < 0 && !mPointerIdBits.isFull()) {
- id = mPointerIdBits.markFirstUnmarkedBit();
- mPointerTrackingIdMap[id] = trackingId;
- }
- }
- if (id < 0) {
- *outHavePointerIds = false;
- mCurrentRawPointerData.clearIdBits();
- newPointerIdBits.clear();
- } else {
- outPointer.id = id;
- mCurrentRawPointerData.idToIndex[id] = outCount;
- mCurrentRawPointerData.markIdBit(id, isHovering);
- newPointerIdBits.markBit(id);
- }
- }
-
- outCount += 1;
- }
-
- mCurrentRawPointerData.pointerCount = outCount;
- mPointerIdBits = newPointerIdBits;
-
- mMultiTouchMotionAccumulator.finishSync();
-}
-
-void MultiTouchInputMapper::configureRawPointerAxes() {
- TouchInputMapper::configureRawPointerAxes();
-
- getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
- getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
- getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
- getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
- getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
- getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
- getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
- getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
- getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
- getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
- getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
-
- if (mRawPointerAxes.trackingId.valid
- && mRawPointerAxes.slot.valid
- && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
- size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
- if (slotCount > MAX_SLOTS) {
- ALOGW("MultiTouch Device %s reported %d slots but the framework "
- "only supports a maximum of %d slots at this time.",
- getDeviceName().string(), slotCount, MAX_SLOTS);
- slotCount = MAX_SLOTS;
- }
- mMultiTouchMotionAccumulator.configure(getDevice(),
- slotCount, true /*usingSlotsProtocol*/);
- } else {
- mMultiTouchMotionAccumulator.configure(getDevice(),
- MAX_POINTERS, false /*usingSlotsProtocol*/);
- }
-}
-
-bool MultiTouchInputMapper::hasStylus() const {
- return mMultiTouchMotionAccumulator.hasStylus()
- || mTouchButtonAccumulator.hasStylus();
-}
-
-
-// --- JoystickInputMapper ---
-
-JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
- InputMapper(device) {
-}
-
-JoystickInputMapper::~JoystickInputMapper() {
-}
-
-uint32_t JoystickInputMapper::getSources() {
- return AINPUT_SOURCE_JOYSTICK;
-}
-
-void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
- InputMapper::populateDeviceInfo(info);
-
- for (size_t i = 0; i < mAxes.size(); i++) {
- const Axis& axis = mAxes.valueAt(i);
- addMotionRange(axis.axisInfo.axis, axis, info);
-
- if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
- addMotionRange(axis.axisInfo.highAxis, axis, info);
-
- }
- }
-}
-
-void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
- InputDeviceInfo* info) {
- info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
- axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
- /* In order to ease the transition for developers from using the old axes
- * to the newer, more semantically correct axes, we'll continue to register
- * the old axes as duplicates of their corresponding new ones. */
- int32_t compatAxis = getCompatAxis(axisId);
- if (compatAxis >= 0) {
- info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
- axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
- }
-}
-
-/* A mapping from axes the joystick actually has to the axes that should be
- * artificially created for compatibility purposes.
- * Returns -1 if no compatibility axis is needed. */
-int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
- switch(axis) {
- case AMOTION_EVENT_AXIS_LTRIGGER:
- return AMOTION_EVENT_AXIS_BRAKE;
- case AMOTION_EVENT_AXIS_RTRIGGER:
- return AMOTION_EVENT_AXIS_GAS;
- }
- return -1;
-}
-
-void JoystickInputMapper::dump(String8& dump) {
- dump.append(INDENT2 "Joystick Input Mapper:\n");
-
- dump.append(INDENT3 "Axes:\n");
- size_t numAxes = mAxes.size();
- for (size_t i = 0; i < numAxes; i++) {
- const Axis& axis = mAxes.valueAt(i);
- const char* label = getAxisLabel(axis.axisInfo.axis);
- if (label) {
- dump.appendFormat(INDENT4 "%s", label);
- } else {
- dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
- }
- if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
- label = getAxisLabel(axis.axisInfo.highAxis);
- if (label) {
- dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
- } else {
- dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
- axis.axisInfo.splitValue);
- }
- } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
- dump.append(" (invert)");
- }
-
- dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
- axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
- dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
- "highScale=%0.5f, highOffset=%0.5f\n",
- axis.scale, axis.offset, axis.highScale, axis.highOffset);
- dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
- "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
- mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
- axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
- }
-}
-
-void JoystickInputMapper::configure(nsecs_t when,
- const InputReaderConfiguration* config, uint32_t changes) {
- InputMapper::configure(when, config, changes);
-
- if (!changes) { // first time only
- // Collect all axes.
- for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
- if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
- & INPUT_DEVICE_CLASS_JOYSTICK)) {
- continue; // axis must be claimed by a different device
- }
-
- RawAbsoluteAxisInfo rawAxisInfo;
- getAbsoluteAxisInfo(abs, &rawAxisInfo);
- if (rawAxisInfo.valid) {
- // Map axis.
- AxisInfo axisInfo;
- bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
- if (!explicitlyMapped) {
- // Axis is not explicitly mapped, will choose a generic axis later.
- axisInfo.mode = AxisInfo::MODE_NORMAL;
- axisInfo.axis = -1;
- }
-
- // Apply flat override.
- int32_t rawFlat = axisInfo.flatOverride < 0
- ? rawAxisInfo.flat : axisInfo.flatOverride;
-
- // Calculate scaling factors and limits.
- Axis axis;
- if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
- float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
- float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
- axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
- scale, 0.0f, highScale, 0.0f,
- 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
- rawAxisInfo.resolution * scale);
- } else if (isCenteredAxis(axisInfo.axis)) {
- float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
- float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
- axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
- scale, offset, scale, offset,
- -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
- rawAxisInfo.resolution * scale);
- } else {
- float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
- axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
- scale, 0.0f, scale, 0.0f,
- 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
- rawAxisInfo.resolution * scale);
- }
-
- // To eliminate noise while the joystick is at rest, filter out small variations
- // in axis values up front.
- axis.filter = axis.flat * 0.25f;
-
- mAxes.add(abs, axis);
- }
- }
-
- // If there are too many axes, start dropping them.
- // Prefer to keep explicitly mapped axes.
- if (mAxes.size() > PointerCoords::MAX_AXES) {
- ALOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
- getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
- pruneAxes(true);
- pruneAxes(false);
- }
-
- // Assign generic axis ids to remaining axes.
- int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
- size_t numAxes = mAxes.size();
- for (size_t i = 0; i < numAxes; i++) {
- Axis& axis = mAxes.editValueAt(i);
- if (axis.axisInfo.axis < 0) {
- while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
- && haveAxis(nextGenericAxisId)) {
- nextGenericAxisId += 1;
- }
-
- if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
- axis.axisInfo.axis = nextGenericAxisId;
- nextGenericAxisId += 1;
- } else {
- ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
- "have already been assigned to other axes.",
- getDeviceName().string(), mAxes.keyAt(i));
- mAxes.removeItemsAt(i--);
- numAxes -= 1;
- }
- }
- }
- }
-}
-
-bool JoystickInputMapper::haveAxis(int32_t axisId) {
- size_t numAxes = mAxes.size();
- for (size_t i = 0; i < numAxes; i++) {
- const Axis& axis = mAxes.valueAt(i);
- if (axis.axisInfo.axis == axisId
- || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
- && axis.axisInfo.highAxis == axisId)) {
- return true;
- }
- }
- return false;
-}
-
-void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
- size_t i = mAxes.size();
- while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
- if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
- continue;
- }
- ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
- getDeviceName().string(), mAxes.keyAt(i));
- mAxes.removeItemsAt(i);
- }
-}
-
-bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
- switch (axis) {
- case AMOTION_EVENT_AXIS_X:
- case AMOTION_EVENT_AXIS_Y:
- case AMOTION_EVENT_AXIS_Z:
- case AMOTION_EVENT_AXIS_RX:
- case AMOTION_EVENT_AXIS_RY:
- case AMOTION_EVENT_AXIS_RZ:
- case AMOTION_EVENT_AXIS_HAT_X:
- case AMOTION_EVENT_AXIS_HAT_Y:
- case AMOTION_EVENT_AXIS_ORIENTATION:
- case AMOTION_EVENT_AXIS_RUDDER:
- case AMOTION_EVENT_AXIS_WHEEL:
- return true;
- default:
- return false;
- }
-}
-
-void JoystickInputMapper::reset(nsecs_t when) {
- // Recenter all axes.
- size_t numAxes = mAxes.size();
- for (size_t i = 0; i < numAxes; i++) {
- Axis& axis = mAxes.editValueAt(i);
- axis.resetValue();
- }
-
- InputMapper::reset(when);
-}
-
-void JoystickInputMapper::process(const RawEvent* rawEvent) {
- switch (rawEvent->type) {
- case EV_ABS: {
- ssize_t index = mAxes.indexOfKey(rawEvent->code);
- if (index >= 0) {
- Axis& axis = mAxes.editValueAt(index);
- float newValue, highNewValue;
- switch (axis.axisInfo.mode) {
- case AxisInfo::MODE_INVERT:
- newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
- * axis.scale + axis.offset;
- highNewValue = 0.0f;
- break;
- case AxisInfo::MODE_SPLIT:
- if (rawEvent->value < axis.axisInfo.splitValue) {
- newValue = (axis.axisInfo.splitValue - rawEvent->value)
- * axis.scale + axis.offset;
- highNewValue = 0.0f;
- } else if (rawEvent->value > axis.axisInfo.splitValue) {
- newValue = 0.0f;
- highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
- * axis.highScale + axis.highOffset;
- } else {
- newValue = 0.0f;
- highNewValue = 0.0f;
- }
- break;
- default:
- newValue = rawEvent->value * axis.scale + axis.offset;
- highNewValue = 0.0f;
- break;
- }
- axis.newValue = newValue;
- axis.highNewValue = highNewValue;
- }
- break;
- }
-
- case EV_SYN:
- switch (rawEvent->code) {
- case SYN_REPORT:
- sync(rawEvent->when, false /*force*/);
- break;
- }
- break;
- }
-}
-
-void JoystickInputMapper::sync(nsecs_t when, bool force) {
- if (!filterAxes(force)) {
- return;
- }
-
- int32_t metaState = mContext->getGlobalMetaState();
- int32_t buttonState = 0;
-
- PointerProperties pointerProperties;
- pointerProperties.clear();
- pointerProperties.id = 0;
- pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
-
- PointerCoords pointerCoords;
- pointerCoords.clear();
-
- size_t numAxes = mAxes.size();
- for (size_t i = 0; i < numAxes; i++) {
- const Axis& axis = mAxes.valueAt(i);
- setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
- if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
- setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
- axis.highCurrentValue);
- }
- }
-
- // Moving a joystick axis should not wake the device because joysticks can
- // be fairly noisy even when not in use. On the other hand, pushing a gamepad
- // button will likely wake the device.
- // TODO: Use the input device configuration to control this behavior more finely.
- uint32_t policyFlags = 0;
-
- NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
- AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
- ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
- getListener()->notifyMotion(&args);
-}
-
-void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
- int32_t axis, float value) {
- pointerCoords->setAxisValue(axis, value);
- /* In order to ease the transition for developers from using the old axes
- * to the newer, more semantically correct axes, we'll continue to produce
- * values for the old axes as mirrors of the value of their corresponding
- * new axes. */
- int32_t compatAxis = getCompatAxis(axis);
- if (compatAxis >= 0) {
- pointerCoords->setAxisValue(compatAxis, value);
- }
-}
-
-bool JoystickInputMapper::filterAxes(bool force) {
- bool atLeastOneSignificantChange = force;
- size_t numAxes = mAxes.size();
- for (size_t i = 0; i < numAxes; i++) {
- Axis& axis = mAxes.editValueAt(i);
- if (force || hasValueChangedSignificantly(axis.filter,
- axis.newValue, axis.currentValue, axis.min, axis.max)) {
- axis.currentValue = axis.newValue;
- atLeastOneSignificantChange = true;
- }
- if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
- if (force || hasValueChangedSignificantly(axis.filter,
- axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
- axis.highCurrentValue = axis.highNewValue;
- atLeastOneSignificantChange = true;
- }
- }
- }
- return atLeastOneSignificantChange;
-}
-
-bool JoystickInputMapper::hasValueChangedSignificantly(
- float filter, float newValue, float currentValue, float min, float max) {
- if (newValue != currentValue) {
- // Filter out small changes in value unless the value is converging on the axis
- // bounds or center point. This is intended to reduce the amount of information
- // sent to applications by particularly noisy joysticks (such as PS3).
- if (fabs(newValue - currentValue) > filter
- || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
- || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
- || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
- return true;
- }
- }
- return false;
-}
-
-bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
- float filter, float newValue, float currentValue, float thresholdValue) {
- float newDistance = fabs(newValue - thresholdValue);
- if (newDistance < filter) {
- float oldDistance = fabs(currentValue - thresholdValue);
- if (newDistance < oldDistance) {
- return true;
- }
- }
- return false;
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/InputReader.h b/widget/gonk/libui/InputReader.h
deleted file mode 100644
index 5c790fdb8..000000000
--- a/widget/gonk/libui/InputReader.h
+++ /dev/null
@@ -1,1811 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_INPUT_READER_H
-#define _UI_INPUT_READER_H
-
-#include "EventHub.h"
-#include "PointerController.h"
-#include "InputListener.h"
-
-#include "Input.h"
-#include "VelocityControl.h"
-#include "VelocityTracker.h"
-#include <utils/KeyedVector.h>
-#include <utils/threads.h>
-#include <utils/Timers.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-#include <utils/BitSet.h>
-
-#include <stddef.h>
-#include <unistd.h>
-
-// Maximum supported size of a vibration pattern.
-// Must be at least 2.
-#define MAX_VIBRATE_PATTERN_SIZE 100
-
-// Maximum allowable delay value in a vibration pattern before
-// which the delay will be truncated.
-#define MAX_VIBRATE_PATTERN_DELAY_NSECS (1000000 * 1000000000LL)
-
-namespace android {
-
-class InputDevice;
-class InputMapper;
-
-/*
- * Describes how coordinates are mapped on a physical display.
- * See com.android.server.display.DisplayViewport.
- */
-struct DisplayViewport {
- int32_t displayId; // -1 if invalid
- int32_t orientation;
- int32_t logicalLeft;
- int32_t logicalTop;
- int32_t logicalRight;
- int32_t logicalBottom;
- int32_t physicalLeft;
- int32_t physicalTop;
- int32_t physicalRight;
- int32_t physicalBottom;
- int32_t deviceWidth;
- int32_t deviceHeight;
-
- DisplayViewport() :
- displayId(ADISPLAY_ID_NONE), orientation(DISPLAY_ORIENTATION_0),
- logicalLeft(0), logicalTop(0), logicalRight(0), logicalBottom(0),
- physicalLeft(0), physicalTop(0), physicalRight(0), physicalBottom(0),
- deviceWidth(0), deviceHeight(0) {
- }
-
- bool operator==(const DisplayViewport& other) const {
- return displayId == other.displayId
- && orientation == other.orientation
- && logicalLeft == other.logicalLeft
- && logicalTop == other.logicalTop
- && logicalRight == other.logicalRight
- && logicalBottom == other.logicalBottom
- && physicalLeft == other.physicalLeft
- && physicalTop == other.physicalTop
- && physicalRight == other.physicalRight
- && physicalBottom == other.physicalBottom
- && deviceWidth == other.deviceWidth
- && deviceHeight == other.deviceHeight;
- }
-
- bool operator!=(const DisplayViewport& other) const {
- return !(*this == other);
- }
-
- inline bool isValid() const {
- return displayId >= 0;
- }
-
- void setNonDisplayViewport(int32_t width, int32_t height) {
- displayId = ADISPLAY_ID_NONE;
- orientation = DISPLAY_ORIENTATION_0;
- logicalLeft = 0;
- logicalTop = 0;
- logicalRight = width;
- logicalBottom = height;
- physicalLeft = 0;
- physicalTop = 0;
- physicalRight = width;
- physicalBottom = height;
- deviceWidth = width;
- deviceHeight = height;
- }
-};
-
-/*
- * Input reader configuration.
- *
- * Specifies various options that modify the behavior of the input reader.
- */
-struct InputReaderConfiguration {
- // Describes changes that have occurred.
- enum {
- // The pointer speed changed.
- CHANGE_POINTER_SPEED = 1 << 0,
-
- // The pointer gesture control changed.
- CHANGE_POINTER_GESTURE_ENABLEMENT = 1 << 1,
-
- // The display size or orientation changed.
- CHANGE_DISPLAY_INFO = 1 << 2,
-
- // The visible touches option changed.
- CHANGE_SHOW_TOUCHES = 1 << 3,
-
- // The keyboard layouts must be reloaded.
- CHANGE_KEYBOARD_LAYOUTS = 1 << 4,
-
- // The device name alias supplied by the may have changed for some devices.
- CHANGE_DEVICE_ALIAS = 1 << 5,
-
- // All devices must be reopened.
- CHANGE_MUST_REOPEN = 1 << 31,
- };
-
- // Gets the amount of time to disable virtual keys after the screen is touched
- // in order to filter out accidental virtual key presses due to swiping gestures
- // or taps near the edge of the display. May be 0 to disable the feature.
- nsecs_t virtualKeyQuietTime;
-
- // The excluded device names for the platform.
- // Devices with these names will be ignored.
- Vector<String8> excludedDeviceNames;
-
- // Velocity control parameters for mouse pointer movements.
- VelocityControlParameters pointerVelocityControlParameters;
-
- // Velocity control parameters for mouse wheel movements.
- VelocityControlParameters wheelVelocityControlParameters;
-
- // True if pointer gestures are enabled.
- bool pointerGesturesEnabled;
-
- // Quiet time between certain pointer gesture transitions.
- // Time to allow for all fingers or buttons to settle into a stable state before
- // starting a new gesture.
- nsecs_t pointerGestureQuietInterval;
-
- // The minimum speed that a pointer must travel for us to consider switching the active
- // touch pointer to it during a drag. This threshold is set to avoid switching due
- // to noise from a finger resting on the touch pad (perhaps just pressing it down).
- float pointerGestureDragMinSwitchSpeed; // in pixels per second
-
- // Tap gesture delay time.
- // The time between down and up must be less than this to be considered a tap.
- nsecs_t pointerGestureTapInterval;
-
- // Tap drag gesture delay time.
- // The time between the previous tap's up and the next down must be less than
- // this to be considered a drag. Otherwise, the previous tap is finished and a
- // new tap begins.
- //
- // Note that the previous tap will be held down for this entire duration so this
- // interval must be shorter than the long press timeout.
- nsecs_t pointerGestureTapDragInterval;
-
- // The distance in pixels that the pointer is allowed to move from initial down
- // to up and still be called a tap.
- float pointerGestureTapSlop; // in pixels
-
- // Time after the first touch points go down to settle on an initial centroid.
- // This is intended to be enough time to handle cases where the user puts down two
- // fingers at almost but not quite exactly the same time.
- nsecs_t pointerGestureMultitouchSettleInterval;
-
- // The transition from PRESS to SWIPE or FREEFORM gesture mode is made when
- // at least two pointers have moved at least this far from their starting place.
- float pointerGestureMultitouchMinDistance; // in pixels
-
- // The transition from PRESS to SWIPE gesture mode can only occur when the
- // cosine of the angle between the two vectors is greater than or equal to than this value
- // which indicates that the vectors are oriented in the same direction.
- // When the vectors are oriented in the exactly same direction, the cosine is 1.0.
- // (In exactly opposite directions, the cosine is -1.0.)
- float pointerGestureSwipeTransitionAngleCosine;
-
- // The transition from PRESS to SWIPE gesture mode can only occur when the
- // fingers are no more than this far apart relative to the diagonal size of
- // the touch pad. For example, a ratio of 0.5 means that the fingers must be
- // no more than half the diagonal size of the touch pad apart.
- float pointerGestureSwipeMaxWidthRatio;
-
- // The gesture movement speed factor relative to the size of the display.
- // Movement speed applies when the fingers are moving in the same direction.
- // Without acceleration, a full swipe of the touch pad diagonal in movement mode
- // will cover this portion of the display diagonal.
- float pointerGestureMovementSpeedRatio;
-
- // The gesture zoom speed factor relative to the size of the display.
- // Zoom speed applies when the fingers are mostly moving relative to each other
- // to execute a scale gesture or similar.
- // Without acceleration, a full swipe of the touch pad diagonal in zoom mode
- // will cover this portion of the display diagonal.
- float pointerGestureZoomSpeedRatio;
-
- // True to show the location of touches on the touch screen as spots.
- bool showTouches;
-
- InputReaderConfiguration() :
- virtualKeyQuietTime(0),
- pointerVelocityControlParameters(1.0f, 500.0f, 3000.0f, 3.0f),
- wheelVelocityControlParameters(1.0f, 15.0f, 50.0f, 4.0f),
- pointerGesturesEnabled(true),
- pointerGestureQuietInterval(100 * 1000000LL), // 100 ms
- pointerGestureDragMinSwitchSpeed(50), // 50 pixels per second
- pointerGestureTapInterval(150 * 1000000LL), // 150 ms
- pointerGestureTapDragInterval(150 * 1000000LL), // 150 ms
- pointerGestureTapSlop(10.0f), // 10 pixels
- pointerGestureMultitouchSettleInterval(100 * 1000000LL), // 100 ms
- pointerGestureMultitouchMinDistance(15), // 15 pixels
- pointerGestureSwipeTransitionAngleCosine(0.2588f), // cosine of 75 degrees
- pointerGestureSwipeMaxWidthRatio(0.25f),
- pointerGestureMovementSpeedRatio(0.8f),
- pointerGestureZoomSpeedRatio(0.3f),
- showTouches(false) { }
-
- bool getDisplayInfo(bool external, DisplayViewport* outViewport) const;
- void setDisplayInfo(bool external, const DisplayViewport& viewport);
-
-private:
- DisplayViewport mInternalDisplay;
- DisplayViewport mExternalDisplay;
-};
-
-
-/*
- * Input reader policy interface.
- *
- * The input reader policy is used by the input reader to interact with the Window Manager
- * and other system components.
- *
- * The actual implementation is partially supported by callbacks into the DVM
- * via JNI. This interface is also mocked in the unit tests.
- *
- * These methods must NOT re-enter the input reader since they may be called while
- * holding the input reader lock.
- */
-class InputReaderPolicyInterface : public virtual RefBase {
-protected:
- InputReaderPolicyInterface() { }
- virtual ~InputReaderPolicyInterface() { }
-
-public:
- /* Gets the input reader configuration. */
- virtual void getReaderConfiguration(InputReaderConfiguration* outConfig) = 0;
-
- /* Gets a pointer controller associated with the specified cursor device (ie. a mouse). */
- virtual sp<PointerControllerInterface> obtainPointerController(int32_t deviceId) = 0;
-
- /* Notifies the input reader policy that some input devices have changed
- * and provides information about all current input devices.
- */
- virtual void notifyInputDevicesChanged(const Vector<InputDeviceInfo>& inputDevices) = 0;
-
- /* Gets the keyboard layout for a particular input device. */
- virtual sp<KeyCharacterMap> getKeyboardLayoutOverlay(const String8& inputDeviceDescriptor) = 0;
-
- /* Gets a user-supplied alias for a particular input device, or an empty string if none. */
- virtual String8 getDeviceAlias(const InputDeviceIdentifier& identifier) = 0;
-};
-
-
-/* Processes raw input events and sends cooked event data to an input listener. */
-class InputReaderInterface : public virtual RefBase {
-protected:
- InputReaderInterface() { }
- virtual ~InputReaderInterface() { }
-
-public:
- /* Dumps the state of the input reader.
- *
- * This method may be called on any thread (usually by the input manager). */
- virtual void dump(String8& dump) = 0;
-
- /* Called by the heatbeat to ensures that the reader has not deadlocked. */
- virtual void monitor() = 0;
-
- /* Runs a single iteration of the processing loop.
- * Nominally reads and processes one incoming message from the EventHub.
- *
- * This method should be called on the input reader thread.
- */
- virtual void loopOnce() = 0;
-
- /* Gets information about all input devices.
- *
- * This method may be called on any thread (usually by the input manager).
- */
- virtual void getInputDevices(Vector<InputDeviceInfo>& outInputDevices) = 0;
-
- /* Query current input state. */
- virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask,
- int32_t scanCode) = 0;
- virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
- int32_t keyCode) = 0;
- virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask,
- int32_t sw) = 0;
-
- /* Determine whether physical keys exist for the given framework-domain key codes. */
- virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
- size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) = 0;
-
- /* Requests that a reconfiguration of all input devices.
- * The changes flag is a bitfield that indicates what has changed and whether
- * the input devices must all be reopened. */
- virtual void requestRefreshConfiguration(uint32_t changes) = 0;
-
- /* Controls the vibrator of a particular input device. */
- virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
- ssize_t repeat, int32_t token) = 0;
- virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0;
-};
-
-
-/* Internal interface used by individual input devices to access global input device state
- * and parameters maintained by the input reader.
- */
-class InputReaderContext {
-public:
- InputReaderContext() { }
- virtual ~InputReaderContext() { }
-
- virtual void updateGlobalMetaState() = 0;
- virtual int32_t getGlobalMetaState() = 0;
-
- virtual void disableVirtualKeysUntil(nsecs_t time) = 0;
- virtual bool shouldDropVirtualKey(nsecs_t now,
- InputDevice* device, int32_t keyCode, int32_t scanCode) = 0;
-
- virtual void fadePointer() = 0;
-
- virtual void requestTimeoutAtTime(nsecs_t when) = 0;
- virtual int32_t bumpGeneration() = 0;
-
- virtual InputReaderPolicyInterface* getPolicy() = 0;
- virtual InputListenerInterface* getListener() = 0;
- virtual EventHubInterface* getEventHub() = 0;
-};
-
-
-/* The input reader reads raw event data from the event hub and processes it into input events
- * that it sends to the input listener. Some functions of the input reader, such as early
- * event filtering in low power states, are controlled by a separate policy object.
- *
- * The InputReader owns a collection of InputMappers. Most of the work it does happens
- * on the input reader thread but the InputReader can receive queries from other system
- * components running on arbitrary threads. To keep things manageable, the InputReader
- * uses a single Mutex to guard its state. The Mutex may be held while calling into the
- * EventHub or the InputReaderPolicy but it is never held while calling into the
- * InputListener.
- */
-class InputReader : public InputReaderInterface {
-public:
- InputReader(const sp<EventHubInterface>& eventHub,
- const sp<InputReaderPolicyInterface>& policy,
- const sp<InputListenerInterface>& listener);
- virtual ~InputReader();
-
- virtual void dump(String8& dump);
- virtual void monitor();
-
- virtual void loopOnce();
-
- virtual void getInputDevices(Vector<InputDeviceInfo>& outInputDevices);
-
- virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask,
- int32_t scanCode);
- virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
- int32_t keyCode);
- virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask,
- int32_t sw);
-
- virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
- size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags);
-
- virtual void requestRefreshConfiguration(uint32_t changes);
-
- virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
- ssize_t repeat, int32_t token);
- virtual void cancelVibrate(int32_t deviceId, int32_t token);
-
-protected:
- // These members are protected so they can be instrumented by test cases.
- virtual InputDevice* createDeviceLocked(int32_t deviceId,
- const InputDeviceIdentifier& identifier, uint32_t classes);
-
- class ContextImpl : public InputReaderContext {
- InputReader* mReader;
-
- public:
- ContextImpl(InputReader* reader);
-
- virtual void updateGlobalMetaState();
- virtual int32_t getGlobalMetaState();
- virtual void disableVirtualKeysUntil(nsecs_t time);
- virtual bool shouldDropVirtualKey(nsecs_t now,
- InputDevice* device, int32_t keyCode, int32_t scanCode);
- virtual void fadePointer();
- virtual void requestTimeoutAtTime(nsecs_t when);
- virtual int32_t bumpGeneration();
- virtual InputReaderPolicyInterface* getPolicy();
- virtual InputListenerInterface* getListener();
- virtual EventHubInterface* getEventHub();
- } mContext;
-
- friend class ContextImpl;
-
-private:
- Mutex mLock;
-
- Condition mReaderIsAliveCondition;
-
- sp<EventHubInterface> mEventHub;
- sp<InputReaderPolicyInterface> mPolicy;
- sp<QueuedInputListener> mQueuedListener;
-
- InputReaderConfiguration mConfig;
-
- // The event queue.
- static const int EVENT_BUFFER_SIZE = 256;
- RawEvent mEventBuffer[EVENT_BUFFER_SIZE];
-
- KeyedVector<int32_t, InputDevice*> mDevices;
-
- // low-level input event decoding and device management
- void processEventsLocked(const RawEvent* rawEvents, size_t count);
-
- void addDeviceLocked(nsecs_t when, int32_t deviceId);
- void removeDeviceLocked(nsecs_t when, int32_t deviceId);
- void processEventsForDeviceLocked(int32_t deviceId, const RawEvent* rawEvents, size_t count);
- void timeoutExpiredLocked(nsecs_t when);
-
- void handleConfigurationChangedLocked(nsecs_t when);
-
- int32_t mGlobalMetaState;
- void updateGlobalMetaStateLocked();
- int32_t getGlobalMetaStateLocked();
-
- void fadePointerLocked();
-
- int32_t mGeneration;
- int32_t bumpGenerationLocked();
-
- void getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices);
-
- nsecs_t mDisableVirtualKeysTimeout;
- void disableVirtualKeysUntilLocked(nsecs_t time);
- bool shouldDropVirtualKeyLocked(nsecs_t now,
- InputDevice* device, int32_t keyCode, int32_t scanCode);
-
- nsecs_t mNextTimeout;
- void requestTimeoutAtTimeLocked(nsecs_t when);
-
- uint32_t mConfigurationChangesToRefresh;
- void refreshConfigurationLocked(uint32_t changes);
-
- // state queries
- typedef int32_t (InputDevice::*GetStateFunc)(uint32_t sourceMask, int32_t code);
- int32_t getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
- GetStateFunc getStateFunc);
- bool markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags);
-};
-
-
-/* Reads raw events from the event hub and processes them, endlessly. */
-class InputReaderThread : public Thread {
-public:
- InputReaderThread(const sp<InputReaderInterface>& reader);
- virtual ~InputReaderThread();
-
-private:
- uint32_t mFoo;
- sp<InputReaderInterface> mReader;
-
- virtual bool threadLoop();
-};
-
-
-/* Represents the state of a single input device. */
-class InputDevice {
-public:
- InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
- const InputDeviceIdentifier& identifier, uint32_t classes);
- ~InputDevice();
-
- inline InputReaderContext* getContext() { return mContext; }
- inline int32_t getId() { return mId; }
- inline int32_t getGeneration() { return mGeneration; }
- inline const String8& getName() { return mIdentifier.name; }
- inline uint32_t getClasses() { return mClasses; }
- inline uint32_t getSources() { return mSources; }
-
- inline bool isExternal() { return mIsExternal; }
- inline void setExternal(bool external) { mIsExternal = external; }
-
- inline bool isIgnored() { return mMappers.isEmpty(); }
-
- void dump(String8& dump);
- void addMapper(InputMapper* mapper);
- void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
- void reset(nsecs_t when);
- void process(const RawEvent* rawEvents, size_t count);
- void timeoutExpired(nsecs_t when);
-
- void getDeviceInfo(InputDeviceInfo* outDeviceInfo);
- int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
- int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
- int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
- bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags);
- void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token);
- void cancelVibrate(int32_t token);
-
- int32_t getMetaState();
-
- void fadePointer();
-
- void bumpGeneration();
-
- void notifyReset(nsecs_t when);
-
- inline const PropertyMap& getConfiguration() { return mConfiguration; }
- inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
-
- bool hasKey(int32_t code) {
- return getEventHub()->hasScanCode(mId, code);
- }
-
- bool hasAbsoluteAxis(int32_t code) {
- RawAbsoluteAxisInfo info;
- getEventHub()->getAbsoluteAxisInfo(mId, code, &info);
- return info.valid;
- }
-
- bool isKeyPressed(int32_t code) {
- return getEventHub()->getScanCodeState(mId, code) == AKEY_STATE_DOWN;
- }
-
- int32_t getAbsoluteAxisValue(int32_t code) {
- int32_t value;
- getEventHub()->getAbsoluteAxisValue(mId, code, &value);
- return value;
- }
-
-private:
- InputReaderContext* mContext;
- int32_t mId;
- int32_t mGeneration;
- InputDeviceIdentifier mIdentifier;
- String8 mAlias;
- uint32_t mClasses;
-
- Vector<InputMapper*> mMappers;
-
- uint32_t mSources;
- bool mIsExternal;
- bool mDropUntilNextSync;
-
- typedef int32_t (InputMapper::*GetStateFunc)(uint32_t sourceMask, int32_t code);
- int32_t getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc);
-
- PropertyMap mConfiguration;
-};
-
-
-/* Keeps track of the state of mouse or touch pad buttons. */
-class CursorButtonAccumulator {
-public:
- CursorButtonAccumulator();
- void reset(InputDevice* device);
-
- void process(const RawEvent* rawEvent);
-
- uint32_t getButtonState() const;
-
-private:
- bool mBtnLeft;
- bool mBtnRight;
- bool mBtnMiddle;
- bool mBtnBack;
- bool mBtnSide;
- bool mBtnForward;
- bool mBtnExtra;
- bool mBtnTask;
-
- void clearButtons();
-};
-
-
-/* Keeps track of cursor movements. */
-
-class CursorMotionAccumulator {
-public:
- CursorMotionAccumulator();
- void reset(InputDevice* device);
-
- void process(const RawEvent* rawEvent);
- void finishSync();
-
- inline int32_t getRelativeX() const { return mRelX; }
- inline int32_t getRelativeY() const { return mRelY; }
-
-private:
- int32_t mRelX;
- int32_t mRelY;
-
- void clearRelativeAxes();
-};
-
-
-/* Keeps track of cursor scrolling motions. */
-
-class CursorScrollAccumulator {
-public:
- CursorScrollAccumulator();
- void configure(InputDevice* device);
- void reset(InputDevice* device);
-
- void process(const RawEvent* rawEvent);
- void finishSync();
-
- inline bool haveRelativeVWheel() const { return mHaveRelWheel; }
- inline bool haveRelativeHWheel() const { return mHaveRelHWheel; }
-
- inline int32_t getRelativeX() const { return mRelX; }
- inline int32_t getRelativeY() const { return mRelY; }
- inline int32_t getRelativeVWheel() const { return mRelWheel; }
- inline int32_t getRelativeHWheel() const { return mRelHWheel; }
-
-private:
- bool mHaveRelWheel;
- bool mHaveRelHWheel;
-
- int32_t mRelX;
- int32_t mRelY;
- int32_t mRelWheel;
- int32_t mRelHWheel;
-
- void clearRelativeAxes();
-};
-
-
-/* Keeps track of the state of touch, stylus and tool buttons. */
-class TouchButtonAccumulator {
-public:
- TouchButtonAccumulator();
- void configure(InputDevice* device);
- void reset(InputDevice* device);
-
- void process(const RawEvent* rawEvent);
-
- uint32_t getButtonState() const;
- int32_t getToolType() const;
- bool isToolActive() const;
- bool isHovering() const;
- bool hasStylus() const;
-
-private:
- bool mHaveBtnTouch;
- bool mHaveStylus;
-
- bool mBtnTouch;
- bool mBtnStylus;
- bool mBtnStylus2;
- bool mBtnToolFinger;
- bool mBtnToolPen;
- bool mBtnToolRubber;
- bool mBtnToolBrush;
- bool mBtnToolPencil;
- bool mBtnToolAirbrush;
- bool mBtnToolMouse;
- bool mBtnToolLens;
- bool mBtnToolDoubleTap;
- bool mBtnToolTripleTap;
- bool mBtnToolQuadTap;
-
- void clearButtons();
-};
-
-
-/* Raw axis information from the driver. */
-struct RawPointerAxes {
- RawAbsoluteAxisInfo x;
- RawAbsoluteAxisInfo y;
- RawAbsoluteAxisInfo pressure;
- RawAbsoluteAxisInfo touchMajor;
- RawAbsoluteAxisInfo touchMinor;
- RawAbsoluteAxisInfo toolMajor;
- RawAbsoluteAxisInfo toolMinor;
- RawAbsoluteAxisInfo orientation;
- RawAbsoluteAxisInfo distance;
- RawAbsoluteAxisInfo tiltX;
- RawAbsoluteAxisInfo tiltY;
- RawAbsoluteAxisInfo trackingId;
- RawAbsoluteAxisInfo slot;
-
- RawPointerAxes();
- void clear();
-};
-
-
-/* Raw data for a collection of pointers including a pointer id mapping table. */
-struct RawPointerData {
- struct Pointer {
- uint32_t id;
- int32_t x;
- int32_t y;
- int32_t pressure;
- int32_t touchMajor;
- int32_t touchMinor;
- int32_t toolMajor;
- int32_t toolMinor;
- int32_t orientation;
- int32_t distance;
- int32_t tiltX;
- int32_t tiltY;
- int32_t toolType; // a fully decoded AMOTION_EVENT_TOOL_TYPE constant
- bool isHovering;
- };
-
- uint32_t pointerCount;
- Pointer pointers[MAX_POINTERS];
- BitSet32 hoveringIdBits, touchingIdBits;
- uint32_t idToIndex[MAX_POINTER_ID + 1];
-
- RawPointerData();
- void clear();
- void copyFrom(const RawPointerData& other);
- void getCentroidOfTouchingPointers(float* outX, float* outY) const;
-
- inline void markIdBit(uint32_t id, bool isHovering) {
- if (isHovering) {
- hoveringIdBits.markBit(id);
- } else {
- touchingIdBits.markBit(id);
- }
- }
-
- inline void clearIdBits() {
- hoveringIdBits.clear();
- touchingIdBits.clear();
- }
-
- inline const Pointer& pointerForId(uint32_t id) const {
- return pointers[idToIndex[id]];
- }
-
- inline bool isHovering(uint32_t pointerIndex) {
- return pointers[pointerIndex].isHovering;
- }
-};
-
-
-/* Cooked data for a collection of pointers including a pointer id mapping table. */
-struct CookedPointerData {
- uint32_t pointerCount;
- PointerProperties pointerProperties[MAX_POINTERS];
- PointerCoords pointerCoords[MAX_POINTERS];
- BitSet32 hoveringIdBits, touchingIdBits;
- uint32_t idToIndex[MAX_POINTER_ID + 1];
-
- CookedPointerData();
- void clear();
- void copyFrom(const CookedPointerData& other);
-
- inline const PointerCoords& pointerCoordsForId(uint32_t id) const {
- return pointerCoords[idToIndex[id]];
- }
-
- inline bool isHovering(uint32_t pointerIndex) {
- return hoveringIdBits.hasBit(pointerProperties[pointerIndex].id);
- }
-};
-
-
-/* Keeps track of the state of single-touch protocol. */
-class SingleTouchMotionAccumulator {
-public:
- SingleTouchMotionAccumulator();
-
- void process(const RawEvent* rawEvent);
- void reset(InputDevice* device);
-
- inline int32_t getAbsoluteX() const { return mAbsX; }
- inline int32_t getAbsoluteY() const { return mAbsY; }
- inline int32_t getAbsolutePressure() const { return mAbsPressure; }
- inline int32_t getAbsoluteToolWidth() const { return mAbsToolWidth; }
- inline int32_t getAbsoluteDistance() const { return mAbsDistance; }
- inline int32_t getAbsoluteTiltX() const { return mAbsTiltX; }
- inline int32_t getAbsoluteTiltY() const { return mAbsTiltY; }
-
-private:
- int32_t mAbsX;
- int32_t mAbsY;
- int32_t mAbsPressure;
- int32_t mAbsToolWidth;
- int32_t mAbsDistance;
- int32_t mAbsTiltX;
- int32_t mAbsTiltY;
-
- void clearAbsoluteAxes();
-};
-
-
-/* Keeps track of the state of multi-touch protocol. */
-class MultiTouchMotionAccumulator {
-public:
- class Slot {
- public:
- inline bool isInUse() const { return mInUse; }
- inline int32_t getX() const { return mAbsMTPositionX; }
- inline int32_t getY() const { return mAbsMTPositionY; }
- inline int32_t getTouchMajor() const { return mAbsMTTouchMajor; }
- inline int32_t getTouchMinor() const {
- return mHaveAbsMTTouchMinor ? mAbsMTTouchMinor : mAbsMTTouchMajor; }
- inline int32_t getToolMajor() const { return mAbsMTWidthMajor; }
- inline int32_t getToolMinor() const {
- return mHaveAbsMTWidthMinor ? mAbsMTWidthMinor : mAbsMTWidthMajor; }
- inline int32_t getOrientation() const { return mAbsMTOrientation; }
- inline int32_t getTrackingId() const { return mAbsMTTrackingId; }
- inline int32_t getPressure() const { return mAbsMTPressure; }
- inline int32_t getDistance() const { return mAbsMTDistance; }
- inline int32_t getToolType() const;
-
- private:
- friend class MultiTouchMotionAccumulator;
-
- bool mInUse;
- bool mHaveAbsMTTouchMinor;
- bool mHaveAbsMTWidthMinor;
- bool mHaveAbsMTToolType;
-
- int32_t mAbsMTPositionX;
- int32_t mAbsMTPositionY;
- int32_t mAbsMTTouchMajor;
- int32_t mAbsMTTouchMinor;
- int32_t mAbsMTWidthMajor;
- int32_t mAbsMTWidthMinor;
- int32_t mAbsMTOrientation;
- int32_t mAbsMTTrackingId;
- int32_t mAbsMTPressure;
- int32_t mAbsMTDistance;
- int32_t mAbsMTToolType;
-
- Slot();
- void clear();
- };
-
- MultiTouchMotionAccumulator();
- ~MultiTouchMotionAccumulator();
-
- void configure(InputDevice* device, size_t slotCount, bool usingSlotsProtocol);
- void reset(InputDevice* device);
- void process(const RawEvent* rawEvent);
- void finishSync();
- bool hasStylus() const;
-
- inline size_t getSlotCount() const { return mSlotCount; }
- inline const Slot* getSlot(size_t index) const { return &mSlots[index]; }
-
-private:
- int32_t mCurrentSlot;
- Slot* mSlots;
- size_t mSlotCount;
- bool mUsingSlotsProtocol;
- bool mHaveStylus;
-
- void clearSlots(int32_t initialSlot);
-};
-
-
-/* An input mapper transforms raw input events into cooked event data.
- * A single input device can have multiple associated input mappers in order to interpret
- * different classes of events.
- *
- * InputMapper lifecycle:
- * - create
- * - configure with 0 changes
- * - reset
- * - process, process, process (may occasionally reconfigure with non-zero changes or reset)
- * - reset
- * - destroy
- */
-class InputMapper {
-public:
- InputMapper(InputDevice* device);
- virtual ~InputMapper();
-
- inline InputDevice* getDevice() { return mDevice; }
- inline int32_t getDeviceId() { return mDevice->getId(); }
- inline const String8 getDeviceName() { return mDevice->getName(); }
- inline InputReaderContext* getContext() { return mContext; }
- inline InputReaderPolicyInterface* getPolicy() { return mContext->getPolicy(); }
- inline InputListenerInterface* getListener() { return mContext->getListener(); }
- inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
-
- virtual uint32_t getSources() = 0;
- virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
- virtual void dump(String8& dump);
- virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
- virtual void reset(nsecs_t when);
- virtual void process(const RawEvent* rawEvent) = 0;
- virtual void timeoutExpired(nsecs_t when);
-
- virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
- virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
- virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
- virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags);
- virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
- int32_t token);
- virtual void cancelVibrate(int32_t token);
-
- virtual int32_t getMetaState();
-
- virtual void fadePointer();
-
-protected:
- InputDevice* mDevice;
- InputReaderContext* mContext;
-
- status_t getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo);
- void bumpGeneration();
-
- static void dumpRawAbsoluteAxisInfo(String8& dump,
- const RawAbsoluteAxisInfo& axis, const char* name);
-};
-
-
-class SwitchInputMapper : public InputMapper {
-public:
- SwitchInputMapper(InputDevice* device);
- virtual ~SwitchInputMapper();
-
- virtual uint32_t getSources();
- virtual void process(const RawEvent* rawEvent);
-
- virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
-
-private:
- uint32_t mUpdatedSwitchValues;
- uint32_t mUpdatedSwitchMask;
-
- void processSwitch(int32_t switchCode, int32_t switchValue);
- void sync(nsecs_t when);
-};
-
-
-class VibratorInputMapper : public InputMapper {
-public:
- VibratorInputMapper(InputDevice* device);
- virtual ~VibratorInputMapper();
-
- virtual uint32_t getSources();
- virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
- virtual void process(const RawEvent* rawEvent);
-
- virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
- int32_t token);
- virtual void cancelVibrate(int32_t token);
- virtual void timeoutExpired(nsecs_t when);
- virtual void dump(String8& dump);
-
-private:
- bool mVibrating;
- nsecs_t mPattern[MAX_VIBRATE_PATTERN_SIZE];
- size_t mPatternSize;
- ssize_t mRepeat;
- int32_t mToken;
- ssize_t mIndex;
- nsecs_t mNextStepTime;
-
- void nextStep();
- void stopVibrating();
-};
-
-
-class KeyboardInputMapper : public InputMapper {
-public:
- KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType);
- virtual ~KeyboardInputMapper();
-
- virtual uint32_t getSources();
- virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
- virtual void dump(String8& dump);
- virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
- virtual void reset(nsecs_t when);
- virtual void process(const RawEvent* rawEvent);
-
- virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
- virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
- virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags);
-
- virtual int32_t getMetaState();
-
-private:
- struct KeyDown {
- int32_t keyCode;
- int32_t scanCode;
- };
-
- uint32_t mSource;
- int32_t mKeyboardType;
-
- int32_t mOrientation; // orientation for dpad keys
-
- Vector<KeyDown> mKeyDowns; // keys that are down
- int32_t mMetaState;
- nsecs_t mDownTime; // time of most recent key down
-
- int32_t mCurrentHidUsage; // most recent HID usage seen this packet, or 0 if none
-
- struct LedState {
- bool avail; // led is available
- bool on; // we think the led is currently on
- };
- LedState mCapsLockLedState;
- LedState mNumLockLedState;
- LedState mScrollLockLedState;
-
- // Immutable configuration parameters.
- struct Parameters {
- bool hasAssociatedDisplay;
- bool orientationAware;
- } mParameters;
-
- void configureParameters();
- void dumpParameters(String8& dump);
-
- bool isKeyboardOrGamepadKey(int32_t scanCode);
-
- void processKey(nsecs_t when, bool down, int32_t keyCode, int32_t scanCode,
- uint32_t policyFlags);
-
- ssize_t findKeyDown(int32_t scanCode);
-
- void resetLedState();
- void initializeLedState(LedState& ledState, int32_t led);
- void updateLedState(bool reset);
- void updateLedStateForModifier(LedState& ledState, int32_t led,
- int32_t modifier, bool reset);
-};
-
-
-class CursorInputMapper : public InputMapper {
-public:
- CursorInputMapper(InputDevice* device);
- virtual ~CursorInputMapper();
-
- virtual uint32_t getSources();
- virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
- virtual void dump(String8& dump);
- virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
- virtual void reset(nsecs_t when);
- virtual void process(const RawEvent* rawEvent);
-
- virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
-
- virtual void fadePointer();
-
-private:
- // Amount that trackball needs to move in order to generate a key event.
- static const int32_t TRACKBALL_MOVEMENT_THRESHOLD = 6;
-
- // Immutable configuration parameters.
- struct Parameters {
- enum Mode {
- MODE_POINTER,
- MODE_NAVIGATION,
- };
-
- Mode mode;
- bool hasAssociatedDisplay;
- bool orientationAware;
- } mParameters;
-
- CursorButtonAccumulator mCursorButtonAccumulator;
- CursorMotionAccumulator mCursorMotionAccumulator;
- CursorScrollAccumulator mCursorScrollAccumulator;
-
- int32_t mSource;
- float mXScale;
- float mYScale;
- float mXPrecision;
- float mYPrecision;
-
- float mVWheelScale;
- float mHWheelScale;
-
- // Velocity controls for mouse pointer and wheel movements.
- // The controls for X and Y wheel movements are separate to keep them decoupled.
- VelocityControl mPointerVelocityControl;
- VelocityControl mWheelXVelocityControl;
- VelocityControl mWheelYVelocityControl;
-
- int32_t mOrientation;
-
- sp<PointerControllerInterface> mPointerController;
-
- int32_t mButtonState;
- nsecs_t mDownTime;
-
- void configureParameters();
- void dumpParameters(String8& dump);
-
- void sync(nsecs_t when);
-};
-
-
-class TouchInputMapper : public InputMapper {
-public:
- TouchInputMapper(InputDevice* device);
- virtual ~TouchInputMapper();
-
- virtual uint32_t getSources();
- virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
- virtual void dump(String8& dump);
- virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
- virtual void reset(nsecs_t when);
- virtual void process(const RawEvent* rawEvent);
-
- virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
- virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
- virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
- const int32_t* keyCodes, uint8_t* outFlags);
-
- virtual void fadePointer();
- virtual void timeoutExpired(nsecs_t when);
-
-protected:
- CursorButtonAccumulator mCursorButtonAccumulator;
- CursorScrollAccumulator mCursorScrollAccumulator;
- TouchButtonAccumulator mTouchButtonAccumulator;
-
- struct VirtualKey {
- int32_t keyCode;
- int32_t scanCode;
- uint32_t flags;
-
- // computed hit box, specified in touch screen coords based on known display size
- int32_t hitLeft;
- int32_t hitTop;
- int32_t hitRight;
- int32_t hitBottom;
-
- inline bool isHit(int32_t x, int32_t y) const {
- return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
- }
- };
-
- // Input sources and device mode.
- uint32_t mSource;
-
- enum DeviceMode {
- DEVICE_MODE_DISABLED, // input is disabled
- DEVICE_MODE_DIRECT, // direct mapping (touchscreen)
- DEVICE_MODE_UNSCALED, // unscaled mapping (touchpad)
- DEVICE_MODE_NAVIGATION, // unscaled mapping with assist gesture (touch navigation)
- DEVICE_MODE_POINTER, // pointer mapping (pointer)
- };
- DeviceMode mDeviceMode;
-
- // The reader's configuration.
- InputReaderConfiguration mConfig;
-
- // Immutable configuration parameters.
- struct Parameters {
- enum DeviceType {
- DEVICE_TYPE_TOUCH_SCREEN,
- DEVICE_TYPE_TOUCH_PAD,
- DEVICE_TYPE_TOUCH_NAVIGATION,
- DEVICE_TYPE_POINTER,
- };
-
- DeviceType deviceType;
- bool hasAssociatedDisplay;
- bool associatedDisplayIsExternal;
- bool orientationAware;
-
- enum GestureMode {
- GESTURE_MODE_POINTER,
- GESTURE_MODE_SPOTS,
- };
- GestureMode gestureMode;
- } mParameters;
-
- // Immutable calibration parameters in parsed form.
- struct Calibration {
- // Size
- enum SizeCalibration {
- SIZE_CALIBRATION_DEFAULT,
- SIZE_CALIBRATION_NONE,
- SIZE_CALIBRATION_GEOMETRIC,
- SIZE_CALIBRATION_DIAMETER,
- SIZE_CALIBRATION_BOX,
- SIZE_CALIBRATION_AREA,
- };
-
- SizeCalibration sizeCalibration;
-
- bool haveSizeScale;
- float sizeScale;
- bool haveSizeBias;
- float sizeBias;
- bool haveSizeIsSummed;
- bool sizeIsSummed;
-
- // Pressure
- enum PressureCalibration {
- PRESSURE_CALIBRATION_DEFAULT,
- PRESSURE_CALIBRATION_NONE,
- PRESSURE_CALIBRATION_PHYSICAL,
- PRESSURE_CALIBRATION_AMPLITUDE,
- };
-
- PressureCalibration pressureCalibration;
- bool havePressureScale;
- float pressureScale;
-
- // Orientation
- enum OrientationCalibration {
- ORIENTATION_CALIBRATION_DEFAULT,
- ORIENTATION_CALIBRATION_NONE,
- ORIENTATION_CALIBRATION_INTERPOLATED,
- ORIENTATION_CALIBRATION_VECTOR,
- };
-
- OrientationCalibration orientationCalibration;
-
- // Distance
- enum DistanceCalibration {
- DISTANCE_CALIBRATION_DEFAULT,
- DISTANCE_CALIBRATION_NONE,
- DISTANCE_CALIBRATION_SCALED,
- };
-
- DistanceCalibration distanceCalibration;
- bool haveDistanceScale;
- float distanceScale;
-
- enum CoverageCalibration {
- COVERAGE_CALIBRATION_DEFAULT,
- COVERAGE_CALIBRATION_NONE,
- COVERAGE_CALIBRATION_BOX,
- };
-
- CoverageCalibration coverageCalibration;
-
- inline void applySizeScaleAndBias(float* outSize) const {
- if (haveSizeScale) {
- *outSize *= sizeScale;
- }
- if (haveSizeBias) {
- *outSize += sizeBias;
- }
- }
- } mCalibration;
-
- // Raw pointer axis information from the driver.
- RawPointerAxes mRawPointerAxes;
-
- // Raw pointer sample data.
- RawPointerData mCurrentRawPointerData;
- RawPointerData mLastRawPointerData;
-
- // Cooked pointer sample data.
- CookedPointerData mCurrentCookedPointerData;
- CookedPointerData mLastCookedPointerData;
-
- // Button state.
- int32_t mCurrentButtonState;
- int32_t mLastButtonState;
-
- // Scroll state.
- int32_t mCurrentRawVScroll;
- int32_t mCurrentRawHScroll;
-
- // Id bits used to differentiate fingers, stylus and mouse tools.
- BitSet32 mCurrentFingerIdBits; // finger or unknown
- BitSet32 mLastFingerIdBits;
- BitSet32 mCurrentStylusIdBits; // stylus or eraser
- BitSet32 mLastStylusIdBits;
- BitSet32 mCurrentMouseIdBits; // mouse or lens
- BitSet32 mLastMouseIdBits;
-
- // True if we sent a HOVER_ENTER event.
- bool mSentHoverEnter;
-
- // The time the primary pointer last went down.
- nsecs_t mDownTime;
-
- // The pointer controller, or null if the device is not a pointer.
- sp<PointerControllerInterface> mPointerController;
-
- Vector<VirtualKey> mVirtualKeys;
-
- virtual void configureParameters();
- virtual void dumpParameters(String8& dump);
- virtual void configureRawPointerAxes();
- virtual void dumpRawPointerAxes(String8& dump);
- virtual void configureSurface(nsecs_t when, bool* outResetNeeded);
- virtual void dumpSurface(String8& dump);
- virtual void configureVirtualKeys();
- virtual void dumpVirtualKeys(String8& dump);
- virtual void parseCalibration();
- virtual void resolveCalibration();
- virtual void dumpCalibration(String8& dump);
- virtual bool hasStylus() const = 0;
-
- virtual void syncTouch(nsecs_t when, bool* outHavePointerIds) = 0;
-
-private:
- // The current viewport.
- // The components of the viewport are specified in the display's rotated orientation.
- DisplayViewport mViewport;
-
- // The surface orientation, width and height set by configureSurface().
- // The width and height are derived from the viewport but are specified
- // in the natural orientation.
- // The surface origin specifies how the surface coordinates should be translated
- // to align with the logical display coordinate space.
- // The orientation may be different from the viewport orientation as it specifies
- // the rotation of the surface coordinates required to produce the viewport's
- // requested orientation, so it will depend on whether the device is orientation aware.
- int32_t mSurfaceWidth;
- int32_t mSurfaceHeight;
- int32_t mSurfaceLeft;
- int32_t mSurfaceTop;
- int32_t mSurfaceOrientation;
-
- // Translation and scaling factors, orientation-independent.
- float mXTranslate;
- float mXScale;
- float mXPrecision;
-
- float mYTranslate;
- float mYScale;
- float mYPrecision;
-
- float mGeometricScale;
-
- float mPressureScale;
-
- float mSizeScale;
-
- float mOrientationScale;
-
- float mDistanceScale;
-
- bool mHaveTilt;
- float mTiltXCenter;
- float mTiltXScale;
- float mTiltYCenter;
- float mTiltYScale;
-
- // Oriented motion ranges for input device info.
- struct OrientedRanges {
- InputDeviceInfo::MotionRange x;
- InputDeviceInfo::MotionRange y;
- InputDeviceInfo::MotionRange pressure;
-
- bool haveSize;
- InputDeviceInfo::MotionRange size;
-
- bool haveTouchSize;
- InputDeviceInfo::MotionRange touchMajor;
- InputDeviceInfo::MotionRange touchMinor;
-
- bool haveToolSize;
- InputDeviceInfo::MotionRange toolMajor;
- InputDeviceInfo::MotionRange toolMinor;
-
- bool haveOrientation;
- InputDeviceInfo::MotionRange orientation;
-
- bool haveDistance;
- InputDeviceInfo::MotionRange distance;
-
- bool haveTilt;
- InputDeviceInfo::MotionRange tilt;
-
- OrientedRanges() {
- clear();
- }
-
- void clear() {
- haveSize = false;
- haveTouchSize = false;
- haveToolSize = false;
- haveOrientation = false;
- haveDistance = false;
- haveTilt = false;
- }
- } mOrientedRanges;
-
- // Oriented dimensions and precision.
- float mOrientedXPrecision;
- float mOrientedYPrecision;
-
- struct CurrentVirtualKeyState {
- bool down;
- bool ignored;
- nsecs_t downTime;
- int32_t keyCode;
- int32_t scanCode;
- } mCurrentVirtualKey;
-
- // Scale factor for gesture or mouse based pointer movements.
- float mPointerXMovementScale;
- float mPointerYMovementScale;
-
- // Scale factor for gesture based zooming and other freeform motions.
- float mPointerXZoomScale;
- float mPointerYZoomScale;
-
- // The maximum swipe width.
- float mPointerGestureMaxSwipeWidth;
-
- struct PointerDistanceHeapElement {
- uint32_t currentPointerIndex : 8;
- uint32_t lastPointerIndex : 8;
- uint64_t distance : 48; // squared distance
- };
-
- enum PointerUsage {
- POINTER_USAGE_NONE,
- POINTER_USAGE_GESTURES,
- POINTER_USAGE_STYLUS,
- POINTER_USAGE_MOUSE,
- };
- PointerUsage mPointerUsage;
-
- struct PointerGesture {
- enum Mode {
- // No fingers, button is not pressed.
- // Nothing happening.
- NEUTRAL,
-
- // No fingers, button is not pressed.
- // Tap detected.
- // Emits DOWN and UP events at the pointer location.
- TAP,
-
- // Exactly one finger dragging following a tap.
- // Pointer follows the active finger.
- // Emits DOWN, MOVE and UP events at the pointer location.
- //
- // Detect double-taps when the finger goes up while in TAP_DRAG mode.
- TAP_DRAG,
-
- // Button is pressed.
- // Pointer follows the active finger if there is one. Other fingers are ignored.
- // Emits DOWN, MOVE and UP events at the pointer location.
- BUTTON_CLICK_OR_DRAG,
-
- // Exactly one finger, button is not pressed.
- // Pointer follows the active finger.
- // Emits HOVER_MOVE events at the pointer location.
- //
- // Detect taps when the finger goes up while in HOVER mode.
- HOVER,
-
- // Exactly two fingers but neither have moved enough to clearly indicate
- // whether a swipe or freeform gesture was intended. We consider the
- // pointer to be pressed so this enables clicking or long-pressing on buttons.
- // Pointer does not move.
- // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate.
- PRESS,
-
- // Exactly two fingers moving in the same direction, button is not pressed.
- // Pointer does not move.
- // Emits DOWN, MOVE and UP events with a single pointer coordinate that
- // follows the midpoint between both fingers.
- SWIPE,
-
- // Two or more fingers moving in arbitrary directions, button is not pressed.
- // Pointer does not move.
- // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow
- // each finger individually relative to the initial centroid of the finger.
- FREEFORM,
-
- // Waiting for quiet time to end before starting the next gesture.
- QUIET,
- };
-
- // Time the first finger went down.
- nsecs_t firstTouchTime;
-
- // The active pointer id from the raw touch data.
- int32_t activeTouchId; // -1 if none
-
- // The active pointer id from the gesture last delivered to the application.
- int32_t activeGestureId; // -1 if none
-
- // Pointer coords and ids for the current and previous pointer gesture.
- Mode currentGestureMode;
- BitSet32 currentGestureIdBits;
- uint32_t currentGestureIdToIndex[MAX_POINTER_ID + 1];
- PointerProperties currentGestureProperties[MAX_POINTERS];
- PointerCoords currentGestureCoords[MAX_POINTERS];
-
- Mode lastGestureMode;
- BitSet32 lastGestureIdBits;
- uint32_t lastGestureIdToIndex[MAX_POINTER_ID + 1];
- PointerProperties lastGestureProperties[MAX_POINTERS];
- PointerCoords lastGestureCoords[MAX_POINTERS];
-
- // Time the pointer gesture last went down.
- nsecs_t downTime;
-
- // Time when the pointer went down for a TAP.
- nsecs_t tapDownTime;
-
- // Time when the pointer went up for a TAP.
- nsecs_t tapUpTime;
-
- // Location of initial tap.
- float tapX, tapY;
-
- // Time we started waiting for quiescence.
- nsecs_t quietTime;
-
- // Reference points for multitouch gestures.
- float referenceTouchX; // reference touch X/Y coordinates in surface units
- float referenceTouchY;
- float referenceGestureX; // reference gesture X/Y coordinates in pixels
- float referenceGestureY;
-
- // Distance that each pointer has traveled which has not yet been
- // subsumed into the reference gesture position.
- BitSet32 referenceIdBits;
- struct Delta {
- float dx, dy;
- };
- Delta referenceDeltas[MAX_POINTER_ID + 1];
-
- // Describes how touch ids are mapped to gesture ids for freeform gestures.
- uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1];
-
- // A velocity tracker for determining whether to switch active pointers during drags.
- VelocityTracker velocityTracker;
-
- void reset() {
- firstTouchTime = LLONG_MIN;
- activeTouchId = -1;
- activeGestureId = -1;
- currentGestureMode = NEUTRAL;
- currentGestureIdBits.clear();
- lastGestureMode = NEUTRAL;
- lastGestureIdBits.clear();
- downTime = 0;
- velocityTracker.clear();
- resetTap();
- resetQuietTime();
- }
-
- void resetTap() {
- tapDownTime = LLONG_MIN;
- tapUpTime = LLONG_MIN;
- }
-
- void resetQuietTime() {
- quietTime = LLONG_MIN;
- }
- } mPointerGesture;
-
- struct PointerSimple {
- PointerCoords currentCoords;
- PointerProperties currentProperties;
- PointerCoords lastCoords;
- PointerProperties lastProperties;
-
- // True if the pointer is down.
- bool down;
-
- // True if the pointer is hovering.
- bool hovering;
-
- // Time the pointer last went down.
- nsecs_t downTime;
-
- void reset() {
- currentCoords.clear();
- currentProperties.clear();
- lastCoords.clear();
- lastProperties.clear();
- down = false;
- hovering = false;
- downTime = 0;
- }
- } mPointerSimple;
-
- // The pointer and scroll velocity controls.
- VelocityControl mPointerVelocityControl;
- VelocityControl mWheelXVelocityControl;
- VelocityControl mWheelYVelocityControl;
-
- void sync(nsecs_t when);
-
- bool consumeRawTouches(nsecs_t when, uint32_t policyFlags);
- void dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
- int32_t keyEventAction, int32_t keyEventFlags);
-
- void dispatchTouches(nsecs_t when, uint32_t policyFlags);
- void dispatchHoverExit(nsecs_t when, uint32_t policyFlags);
- void dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags);
- void cookPointerData();
-
- void dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage);
- void abortPointerUsage(nsecs_t when, uint32_t policyFlags);
-
- void dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout);
- void abortPointerGestures(nsecs_t when, uint32_t policyFlags);
- bool preparePointerGestures(nsecs_t when,
- bool* outCancelPreviousGesture, bool* outFinishPreviousGesture,
- bool isTimeout);
-
- void dispatchPointerStylus(nsecs_t when, uint32_t policyFlags);
- void abortPointerStylus(nsecs_t when, uint32_t policyFlags);
-
- void dispatchPointerMouse(nsecs_t when, uint32_t policyFlags);
- void abortPointerMouse(nsecs_t when, uint32_t policyFlags);
-
- void dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
- bool down, bool hovering);
- void abortPointerSimple(nsecs_t when, uint32_t policyFlags);
-
- // Dispatches a motion event.
- // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the
- // method will take care of setting the index and transmuting the action to DOWN or UP
- // it is the first / last pointer to go down / up.
- void dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
- int32_t action, int32_t flags, int32_t metaState, int32_t buttonState,
- int32_t edgeFlags,
- const PointerProperties* properties, const PointerCoords* coords,
- const uint32_t* idToIndex, BitSet32 idBits,
- int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime);
-
- // Updates pointer coords and properties for pointers with specified ids that have moved.
- // Returns true if any of them changed.
- bool updateMovedPointers(const PointerProperties* inProperties,
- const PointerCoords* inCoords, const uint32_t* inIdToIndex,
- PointerProperties* outProperties, PointerCoords* outCoords,
- const uint32_t* outIdToIndex, BitSet32 idBits) const;
-
- bool isPointInsideSurface(int32_t x, int32_t y);
- const VirtualKey* findVirtualKeyHit(int32_t x, int32_t y);
-
- void assignPointerIds();
-};
-
-
-class SingleTouchInputMapper : public TouchInputMapper {
-public:
- SingleTouchInputMapper(InputDevice* device);
- virtual ~SingleTouchInputMapper();
-
- virtual void reset(nsecs_t when);
- virtual void process(const RawEvent* rawEvent);
-
-protected:
- virtual void syncTouch(nsecs_t when, bool* outHavePointerIds);
- virtual void configureRawPointerAxes();
- virtual bool hasStylus() const;
-
-private:
- SingleTouchMotionAccumulator mSingleTouchMotionAccumulator;
-};
-
-
-class MultiTouchInputMapper : public TouchInputMapper {
-public:
- MultiTouchInputMapper(InputDevice* device);
- virtual ~MultiTouchInputMapper();
-
- virtual void reset(nsecs_t when);
- virtual void process(const RawEvent* rawEvent);
-
-protected:
- virtual void syncTouch(nsecs_t when, bool* outHavePointerIds);
- virtual void configureRawPointerAxes();
- virtual bool hasStylus() const;
-
-private:
- MultiTouchMotionAccumulator mMultiTouchMotionAccumulator;
-
- // Specifies the pointer id bits that are in use, and their associated tracking id.
- BitSet32 mPointerIdBits;
- int32_t mPointerTrackingIdMap[MAX_POINTER_ID + 1];
-};
-
-
-class JoystickInputMapper : public InputMapper {
-public:
- JoystickInputMapper(InputDevice* device);
- virtual ~JoystickInputMapper();
-
- virtual uint32_t getSources();
- virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
- virtual void dump(String8& dump);
- virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
- virtual void reset(nsecs_t when);
- virtual void process(const RawEvent* rawEvent);
-
-private:
- struct Axis {
- RawAbsoluteAxisInfo rawAxisInfo;
- AxisInfo axisInfo;
-
- bool explicitlyMapped; // true if the axis was explicitly assigned an axis id
-
- float scale; // scale factor from raw to normalized values
- float offset; // offset to add after scaling for normalization
- float highScale; // scale factor from raw to normalized values of high split
- float highOffset; // offset to add after scaling for normalization of high split
-
- float min; // normalized inclusive minimum
- float max; // normalized inclusive maximum
- float flat; // normalized flat region size
- float fuzz; // normalized error tolerance
- float resolution; // normalized resolution in units/mm
-
- float filter; // filter out small variations of this size
- float currentValue; // current value
- float newValue; // most recent value
- float highCurrentValue; // current value of high split
- float highNewValue; // most recent value of high split
-
- void initialize(const RawAbsoluteAxisInfo& rawAxisInfo, const AxisInfo& axisInfo,
- bool explicitlyMapped, float scale, float offset,
- float highScale, float highOffset,
- float min, float max, float flat, float fuzz, float resolution) {
- this->rawAxisInfo = rawAxisInfo;
- this->axisInfo = axisInfo;
- this->explicitlyMapped = explicitlyMapped;
- this->scale = scale;
- this->offset = offset;
- this->highScale = highScale;
- this->highOffset = highOffset;
- this->min = min;
- this->max = max;
- this->flat = flat;
- this->fuzz = fuzz;
- this->resolution = resolution;
- this->filter = 0;
- resetValue();
- }
-
- void resetValue() {
- this->currentValue = 0;
- this->newValue = 0;
- this->highCurrentValue = 0;
- this->highNewValue = 0;
- }
- };
-
- // Axes indexed by raw ABS_* axis index.
- KeyedVector<int32_t, Axis> mAxes;
-
- void sync(nsecs_t when, bool force);
-
- bool haveAxis(int32_t axisId);
- void pruneAxes(bool ignoreExplicitlyMappedAxes);
- bool filterAxes(bool force);
-
- static bool hasValueChangedSignificantly(float filter,
- float newValue, float currentValue, float min, float max);
- static bool hasMovedNearerToValueWithinFilteredRange(float filter,
- float newValue, float currentValue, float thresholdValue);
-
- static bool isCenteredAxis(int32_t axis);
- static int32_t getCompatAxis(int32_t axis);
-
- static void addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info);
- static void setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
- float value);
-};
-
-} // namespace android
-
-#endif // _UI_INPUT_READER_H
diff --git a/widget/gonk/libui/InputTransport.cpp b/widget/gonk/libui/InputTransport.cpp
deleted file mode 100644
index 3f0fcb047..000000000
--- a/widget/gonk/libui/InputTransport.cpp
+++ /dev/null
@@ -1,957 +0,0 @@
-//
-// Copyright 2010 The Android Open Source Project
-//
-// Provides a shared memory transport for input events.
-//
-#define LOG_TAG "InputTransport"
-
-//#define LOG_NDEBUG 0
-
-// Log debug messages about channel messages (send message, receive message)
-#define DEBUG_CHANNEL_MESSAGES 0
-
-// Log debug messages whenever InputChannel objects are created/destroyed
-#define DEBUG_CHANNEL_LIFECYCLE 0
-
-// Log debug messages about transport actions
-#define DEBUG_TRANSPORT_ACTIONS 0
-
-// Log debug messages about touch event resampling
-#define DEBUG_RESAMPLING 0
-
-
-#include "cutils_log.h"
-#include <cutils/properties.h>
-#include <errno.h>
-#include <fcntl.h>
-#include "InputTransport.h"
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <math.h>
-
-
-namespace android {
-
-// Socket buffer size. The default is typically about 128KB, which is much larger than
-// we really need. So we make it smaller. It just needs to be big enough to hold
-// a few dozen large multi-finger motion events in the case where an application gets
-// behind processing touches.
-static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
-
-// Nanoseconds per milliseconds.
-static const nsecs_t NANOS_PER_MS = 1000000;
-
-// Latency added during resampling. A few milliseconds doesn't hurt much but
-// reduces the impact of mispredicted touch positions.
-static const nsecs_t RESAMPLE_LATENCY = 5 * NANOS_PER_MS;
-
-// Minimum time difference between consecutive samples before attempting to resample.
-static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
-
-// Maximum time to predict forward from the last known state, to avoid predicting too
-// far into the future. This time is further bounded by 50% of the last time delta.
-static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
-
-template<typename T>
-inline static T min(const T& a, const T& b) {
- return a < b ? a : b;
-}
-
-inline static float lerp(float a, float b, float alpha) {
- return a + alpha * (b - a);
-}
-
-// --- InputMessage ---
-
-bool InputMessage::isValid(size_t actualSize) const {
- if (size() == actualSize) {
- switch (header.type) {
- case TYPE_KEY:
- return true;
- case TYPE_MOTION:
- return body.motion.pointerCount > 0
- && body.motion.pointerCount <= MAX_POINTERS;
- case TYPE_FINISHED:
- return true;
- }
- }
- return false;
-}
-
-size_t InputMessage::size() const {
- switch (header.type) {
- case TYPE_KEY:
- return sizeof(Header) + body.key.size();
- case TYPE_MOTION:
- return sizeof(Header) + body.motion.size();
- case TYPE_FINISHED:
- return sizeof(Header) + body.finished.size();
- }
- return sizeof(Header);
-}
-
-
-// --- InputChannel ---
-
-InputChannel::InputChannel(const String8& name, int fd) :
- mName(name), mFd(fd) {
-#if DEBUG_CHANNEL_LIFECYCLE
- ALOGD("Input channel constructed: name='%s', fd=%d",
- mName.string(), fd);
-#endif
-
- int result = fcntl(mFd, F_SETFL, O_NONBLOCK);
- LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "
- "non-blocking. errno=%d", mName.string(), errno);
-}
-
-InputChannel::~InputChannel() {
-#if DEBUG_CHANNEL_LIFECYCLE
- ALOGD("Input channel destroyed: name='%s', fd=%d",
- mName.string(), mFd);
-#endif
-
- ::close(mFd);
-}
-
-status_t InputChannel::openInputChannelPair(const String8& name,
- sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {
- int sockets[2];
- if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
- status_t result = -errno;
- ALOGE("channel '%s' ~ Could not create socket pair. errno=%d",
- name.string(), errno);
- outServerChannel.clear();
- outClientChannel.clear();
- return result;
- }
-
- int bufferSize = SOCKET_BUFFER_SIZE;
- setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
- setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
- setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
- setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
-
- String8 serverChannelName = name;
- serverChannelName.append(" (server)");
- outServerChannel = new InputChannel(serverChannelName, sockets[0]);
-
- String8 clientChannelName = name;
- clientChannelName.append(" (client)");
- outClientChannel = new InputChannel(clientChannelName, sockets[1]);
- return OK;
-}
-
-status_t InputChannel::sendMessage(const InputMessage* msg) {
- size_t msgLength = msg->size();
- ssize_t nWrite;
- do {
- nWrite = ::send(mFd, msg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
- } while (nWrite == -1 && errno == EINTR);
-
- if (nWrite < 0) {
- int error = errno;
-#if DEBUG_CHANNEL_MESSAGES
- ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.string(),
- msg->header.type, error);
-#endif
- if (error == EAGAIN || error == EWOULDBLOCK) {
- return WOULD_BLOCK;
- }
- if (error == EPIPE || error == ENOTCONN) {
- return DEAD_OBJECT;
- }
- return -error;
- }
-
- if (size_t(nWrite) != msgLength) {
-#if DEBUG_CHANNEL_MESSAGES
- ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",
- mName.string(), msg->header.type);
-#endif
- return DEAD_OBJECT;
- }
-
-#if DEBUG_CHANNEL_MESSAGES
- ALOGD("channel '%s' ~ sent message of type %d", mName.string(), msg->header.type);
-#endif
- return OK;
-}
-
-status_t InputChannel::receiveMessage(InputMessage* msg) {
- ssize_t nRead;
- do {
- nRead = ::recv(mFd, msg, sizeof(InputMessage), MSG_DONTWAIT);
- } while (nRead == -1 && errno == EINTR);
-
- if (nRead < 0) {
- int error = errno;
-#if DEBUG_CHANNEL_MESSAGES
- ALOGD("channel '%s' ~ receive message failed, errno=%d", mName.string(), errno);
-#endif
- if (error == EAGAIN || error == EWOULDBLOCK) {
- return WOULD_BLOCK;
- }
- if (error == EPIPE || error == ENOTCONN) {
- return DEAD_OBJECT;
- }
- return -error;
- }
-
- if (nRead == 0) { // check for EOF
-#if DEBUG_CHANNEL_MESSAGES
- ALOGD("channel '%s' ~ receive message failed because peer was closed", mName.string());
-#endif
- return DEAD_OBJECT;
- }
-
- if (!msg->isValid(nRead)) {
-#if DEBUG_CHANNEL_MESSAGES
- ALOGD("channel '%s' ~ received invalid message", mName.string());
-#endif
- return BAD_VALUE;
- }
-
-#if DEBUG_CHANNEL_MESSAGES
- ALOGD("channel '%s' ~ received message of type %d", mName.string(), msg->header.type);
-#endif
- return OK;
-}
-
-sp<InputChannel> InputChannel::dup() const {
- int fd = ::dup(getFd());
- return fd >= 0 ? new InputChannel(getName(), fd) : NULL;
-}
-
-
-// --- InputPublisher ---
-
-InputPublisher::InputPublisher(const sp<InputChannel>& channel) :
- mChannel(channel) {
-}
-
-InputPublisher::~InputPublisher() {
-}
-
-status_t InputPublisher::publishKeyEvent(
- uint32_t seq,
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t keyCode,
- int32_t scanCode,
- int32_t metaState,
- int32_t repeatCount,
- nsecs_t downTime,
- nsecs_t eventTime) {
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' publisher ~ publishKeyEvent: seq=%u, deviceId=%d, source=0x%x, "
- "action=0x%x, flags=0x%x, keyCode=%d, scanCode=%d, metaState=0x%x, repeatCount=%d,"
- "downTime=%lld, eventTime=%lld",
- mChannel->getName().string(), seq,
- deviceId, source, action, flags, keyCode, scanCode, metaState, repeatCount,
- downTime, eventTime);
-#endif
-
- if (!seq) {
- ALOGE("Attempted to publish a key event with sequence number 0.");
- return BAD_VALUE;
- }
-
- InputMessage msg;
- msg.header.type = InputMessage::TYPE_KEY;
- msg.body.key.seq = seq;
- msg.body.key.deviceId = deviceId;
- msg.body.key.source = source;
- msg.body.key.action = action;
- msg.body.key.flags = flags;
- msg.body.key.keyCode = keyCode;
- msg.body.key.scanCode = scanCode;
- msg.body.key.metaState = metaState;
- msg.body.key.repeatCount = repeatCount;
- msg.body.key.downTime = downTime;
- msg.body.key.eventTime = eventTime;
- return mChannel->sendMessage(&msg);
-}
-
-status_t InputPublisher::publishMotionEvent(
- uint32_t seq,
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t edgeFlags,
- int32_t metaState,
- int32_t buttonState,
- float xOffset,
- float yOffset,
- float xPrecision,
- float yPrecision,
- nsecs_t downTime,
- nsecs_t eventTime,
- size_t pointerCount,
- const PointerProperties* pointerProperties,
- const PointerCoords* pointerCoords) {
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' publisher ~ publishMotionEvent: seq=%u, deviceId=%d, source=0x%x, "
- "action=0x%x, flags=0x%x, edgeFlags=0x%x, metaState=0x%x, buttonState=0x%x, "
- "xOffset=%f, yOffset=%f, "
- "xPrecision=%f, yPrecision=%f, downTime=%lld, eventTime=%lld, "
- "pointerCount=%d",
- mChannel->getName().string(), seq,
- deviceId, source, action, flags, edgeFlags, metaState, buttonState,
- xOffset, yOffset, xPrecision, yPrecision, downTime, eventTime, pointerCount);
-#endif
-
- if (!seq) {
- ALOGE("Attempted to publish a motion event with sequence number 0.");
- return BAD_VALUE;
- }
-
- if (pointerCount > MAX_POINTERS || pointerCount < 1) {
- ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %d.",
- mChannel->getName().string(), pointerCount);
- return BAD_VALUE;
- }
-
- InputMessage msg;
- msg.header.type = InputMessage::TYPE_MOTION;
- msg.body.motion.seq = seq;
- msg.body.motion.deviceId = deviceId;
- msg.body.motion.source = source;
- msg.body.motion.action = action;
- msg.body.motion.flags = flags;
- msg.body.motion.edgeFlags = edgeFlags;
- msg.body.motion.metaState = metaState;
- msg.body.motion.buttonState = buttonState;
- msg.body.motion.xOffset = xOffset;
- msg.body.motion.yOffset = yOffset;
- msg.body.motion.xPrecision = xPrecision;
- msg.body.motion.yPrecision = yPrecision;
- msg.body.motion.downTime = downTime;
- msg.body.motion.eventTime = eventTime;
- msg.body.motion.pointerCount = pointerCount;
- for (size_t i = 0; i < pointerCount; i++) {
- msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
- msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
- }
- return mChannel->sendMessage(&msg);
-}
-
-status_t InputPublisher::receiveFinishedSignal(uint32_t* outSeq, bool* outHandled) {
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' publisher ~ receiveFinishedSignal",
- mChannel->getName().string());
-#endif
-
- InputMessage msg;
- status_t result = mChannel->receiveMessage(&msg);
- if (result) {
- *outSeq = 0;
- *outHandled = false;
- return result;
- }
- if (msg.header.type != InputMessage::TYPE_FINISHED) {
- ALOGE("channel '%s' publisher ~ Received unexpected message of type %d from consumer",
- mChannel->getName().string(), msg.header.type);
- return UNKNOWN_ERROR;
- }
- *outSeq = msg.body.finished.seq;
- *outHandled = msg.body.finished.handled;
- return OK;
-}
-
-// --- InputConsumer ---
-
-InputConsumer::InputConsumer(const sp<InputChannel>& channel) :
- mResampleTouch(isTouchResamplingEnabled()),
- mChannel(channel), mMsgDeferred(false) {
-}
-
-InputConsumer::~InputConsumer() {
-}
-
-bool InputConsumer::isTouchResamplingEnabled() {
- char value[PROPERTY_VALUE_MAX];
- int length = property_get("debug.inputconsumer.resample", value, NULL);
- if (length > 0) {
- if (!strcmp("0", value)) {
- return false;
- }
- if (strcmp("1", value)) {
- ALOGD("Unrecognized property value for 'debug.inputconsumer.resample'. "
- "Use '1' or '0'.");
- }
- }
- return true;
-}
-
-status_t InputConsumer::consume(InputEventFactoryInterface* factory,
- bool consumeBatches, nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%lld",
- mChannel->getName().string(), consumeBatches ? "true" : "false", frameTime);
-#endif
-
- *outSeq = 0;
- *outEvent = NULL;
-
- // Fetch the next input message.
- // Loop until an event can be returned or no additional events are received.
- while (!*outEvent) {
- if (mMsgDeferred) {
- // mMsg contains a valid input message from the previous call to consume
- // that has not yet been processed.
- mMsgDeferred = false;
- } else {
- // Receive a fresh message.
- status_t result = mChannel->receiveMessage(&mMsg);
- if (result) {
- // Consume the next batched event unless batches are being held for later.
- if (consumeBatches || result != WOULD_BLOCK) {
- result = consumeBatch(factory, frameTime, outSeq, outEvent);
- if (*outEvent) {
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' consumer ~ consumed batch event, seq=%u",
- mChannel->getName().string(), *outSeq);
-#endif
- break;
- }
- }
- return result;
- }
- }
-
- switch (mMsg.header.type) {
- case InputMessage::TYPE_KEY: {
- KeyEvent* keyEvent = factory->createKeyEvent();
- if (!keyEvent) return NO_MEMORY;
-
- initializeKeyEvent(keyEvent, &mMsg);
- *outSeq = mMsg.body.key.seq;
- *outEvent = keyEvent;
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' consumer ~ consumed key event, seq=%u",
- mChannel->getName().string(), *outSeq);
-#endif
- break;
- }
-
- case AINPUT_EVENT_TYPE_MOTION: {
- ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
- if (batchIndex >= 0) {
- Batch& batch = mBatches.editItemAt(batchIndex);
- if (canAddSample(batch, &mMsg)) {
- batch.samples.push(mMsg);
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' consumer ~ appended to batch event",
- mChannel->getName().string());
-#endif
- break;
- } else {
- // We cannot append to the batch in progress, so we need to consume
- // the previous batch right now and defer the new message until later.
- mMsgDeferred = true;
- status_t result = consumeSamples(factory,
- batch, batch.samples.size(), outSeq, outEvent);
- mBatches.removeAt(batchIndex);
- if (result) {
- return result;
- }
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' consumer ~ consumed batch event and "
- "deferred current event, seq=%u",
- mChannel->getName().string(), *outSeq);
-#endif
- break;
- }
- }
-
- // Start a new batch if needed.
- if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE
- || mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
- mBatches.push();
- Batch& batch = mBatches.editTop();
- batch.samples.push(mMsg);
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' consumer ~ started batch event",
- mChannel->getName().string());
-#endif
- break;
- }
-
- MotionEvent* motionEvent = factory->createMotionEvent();
- if (! motionEvent) return NO_MEMORY;
-
- updateTouchState(&mMsg);
- initializeMotionEvent(motionEvent, &mMsg);
- *outSeq = mMsg.body.motion.seq;
- *outEvent = motionEvent;
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' consumer ~ consumed motion event, seq=%u",
- mChannel->getName().string(), *outSeq);
-#endif
- break;
- }
-
- default:
- ALOGE("channel '%s' consumer ~ Received unexpected message of type %d",
- mChannel->getName().string(), mMsg.header.type);
- return UNKNOWN_ERROR;
- }
- }
- return OK;
-}
-
-status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
- nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
- status_t result;
- for (size_t i = mBatches.size(); i-- > 0; ) {
- Batch& batch = mBatches.editItemAt(i);
- if (frameTime < 0) {
- result = consumeSamples(factory, batch, batch.samples.size(),
- outSeq, outEvent);
- mBatches.removeAt(i);
- return result;
- }
-
- nsecs_t sampleTime = frameTime - RESAMPLE_LATENCY;
- ssize_t split = findSampleNoLaterThan(batch, sampleTime);
- if (split < 0) {
- continue;
- }
-
- result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
- const InputMessage* next;
- if (batch.samples.isEmpty()) {
- mBatches.removeAt(i);
- next = NULL;
- } else {
- next = &batch.samples.itemAt(0);
- }
- if (!result) {
- resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
- }
- return result;
- }
-
- return WOULD_BLOCK;
-}
-
-status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
- Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
- MotionEvent* motionEvent = factory->createMotionEvent();
- if (! motionEvent) return NO_MEMORY;
-
- uint32_t chain = 0;
- for (size_t i = 0; i < count; i++) {
- InputMessage& msg = batch.samples.editItemAt(i);
- updateTouchState(&msg);
- if (i) {
- SeqChain seqChain;
- seqChain.seq = msg.body.motion.seq;
- seqChain.chain = chain;
- mSeqChains.push(seqChain);
- addSample(motionEvent, &msg);
- } else {
- initializeMotionEvent(motionEvent, &msg);
- }
- chain = msg.body.motion.seq;
- }
- batch.samples.removeItemsAt(0, count);
-
- *outSeq = chain;
- *outEvent = motionEvent;
- return OK;
-}
-
-void InputConsumer::updateTouchState(InputMessage* msg) {
- if (!mResampleTouch ||
- !(msg->body.motion.source & AINPUT_SOURCE_CLASS_POINTER)) {
- return;
- }
-
- int32_t deviceId = msg->body.motion.deviceId;
- int32_t source = msg->body.motion.source;
- nsecs_t eventTime = msg->body.motion.eventTime;
-
- // Update the touch state history to incorporate the new input message.
- // If the message is in the past relative to the most recently produced resampled
- // touch, then use the resampled time and coordinates instead.
- switch (msg->body.motion.action & AMOTION_EVENT_ACTION_MASK) {
- case AMOTION_EVENT_ACTION_DOWN: {
- ssize_t index = findTouchState(deviceId, source);
- if (index < 0) {
- mTouchStates.push();
- index = mTouchStates.size() - 1;
- }
- TouchState& touchState = mTouchStates.editItemAt(index);
- touchState.initialize(deviceId, source);
- touchState.addHistory(msg);
- break;
- }
-
- case AMOTION_EVENT_ACTION_MOVE: {
- ssize_t index = findTouchState(deviceId, source);
- if (index >= 0) {
- TouchState& touchState = mTouchStates.editItemAt(index);
- touchState.addHistory(msg);
- if (eventTime < touchState.lastResample.eventTime) {
- rewriteMessage(touchState, msg);
- } else {
- touchState.lastResample.idBits.clear();
- }
- }
- break;
- }
-
- case AMOTION_EVENT_ACTION_POINTER_DOWN: {
- ssize_t index = findTouchState(deviceId, source);
- if (index >= 0) {
- TouchState& touchState = mTouchStates.editItemAt(index);
- touchState.lastResample.idBits.clearBit(msg->body.motion.getActionId());
- rewriteMessage(touchState, msg);
- }
- break;
- }
-
- case AMOTION_EVENT_ACTION_POINTER_UP: {
- ssize_t index = findTouchState(deviceId, source);
- if (index >= 0) {
- TouchState& touchState = mTouchStates.editItemAt(index);
- rewriteMessage(touchState, msg);
- touchState.lastResample.idBits.clearBit(msg->body.motion.getActionId());
- }
- break;
- }
-
- case AMOTION_EVENT_ACTION_SCROLL: {
- ssize_t index = findTouchState(deviceId, source);
- if (index >= 0) {
- const TouchState& touchState = mTouchStates.itemAt(index);
- rewriteMessage(touchState, msg);
- }
- break;
- }
-
- case AMOTION_EVENT_ACTION_UP:
- case AMOTION_EVENT_ACTION_CANCEL: {
- ssize_t index = findTouchState(deviceId, source);
- if (index >= 0) {
- const TouchState& touchState = mTouchStates.itemAt(index);
- rewriteMessage(touchState, msg);
- mTouchStates.removeAt(index);
- }
- break;
- }
- }
-}
-
-void InputConsumer::rewriteMessage(const TouchState& state, InputMessage* msg) {
- for (size_t i = 0; i < msg->body.motion.pointerCount; i++) {
- uint32_t id = msg->body.motion.pointers[i].properties.id;
- if (state.lastResample.idBits.hasBit(id)) {
- PointerCoords& msgCoords = msg->body.motion.pointers[i].coords;
- const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
-#if DEBUG_RESAMPLING
- ALOGD("[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
- resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
- resampleCoords.getAxisValue(AMOTION_EVENT_AXIS_Y),
- msgCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
- msgCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
-#endif
- msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
- msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
- }
- }
-}
-
-void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
- const InputMessage* next) {
- if (!mResampleTouch
- || !(event->getSource() & AINPUT_SOURCE_CLASS_POINTER)
- || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
- return;
- }
-
- ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
- if (index < 0) {
-#if DEBUG_RESAMPLING
- ALOGD("Not resampled, no touch state for device.");
-#endif
- return;
- }
-
- TouchState& touchState = mTouchStates.editItemAt(index);
- if (touchState.historySize < 1) {
-#if DEBUG_RESAMPLING
- ALOGD("Not resampled, no history for device.");
-#endif
- return;
- }
-
- // Ensure that the current sample has all of the pointers that need to be reported.
- const History* current = touchState.getHistory(0);
- size_t pointerCount = event->getPointerCount();
- for (size_t i = 0; i < pointerCount; i++) {
- uint32_t id = event->getPointerId(i);
- if (!current->idBits.hasBit(id)) {
-#if DEBUG_RESAMPLING
- ALOGD("Not resampled, missing id %d", id);
-#endif
- return;
- }
- }
-
- // Find the data to use for resampling.
- const History* other;
- History future;
- float alpha;
- if (next) {
- // Interpolate between current sample and future sample.
- // So current->eventTime <= sampleTime <= future.eventTime.
- future.initializeFrom(next);
- other = &future;
- nsecs_t delta = future.eventTime - current->eventTime;
- if (delta < RESAMPLE_MIN_DELTA) {
-#if DEBUG_RESAMPLING
- ALOGD("Not resampled, delta time is %lld ns.", delta);
-#endif
- return;
- }
- alpha = float(sampleTime - current->eventTime) / delta;
- } else if (touchState.historySize >= 2) {
- // Extrapolate future sample using current sample and past sample.
- // So other->eventTime <= current->eventTime <= sampleTime.
- other = touchState.getHistory(1);
- nsecs_t delta = current->eventTime - other->eventTime;
- if (delta < RESAMPLE_MIN_DELTA) {
-#if DEBUG_RESAMPLING
- ALOGD("Not resampled, delta time is %lld ns.", delta);
-#endif
- return;
- }
- nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
- if (sampleTime > maxPredict) {
-#if DEBUG_RESAMPLING
- ALOGD("Sample time is too far in the future, adjusting prediction "
- "from %lld to %lld ns.",
- sampleTime - current->eventTime, maxPredict - current->eventTime);
-#endif
- sampleTime = maxPredict;
- }
- alpha = float(current->eventTime - sampleTime) / delta;
- } else {
-#if DEBUG_RESAMPLING
- ALOGD("Not resampled, insufficient data.");
-#endif
- return;
- }
-
- // Resample touch coordinates.
- touchState.lastResample.eventTime = sampleTime;
- touchState.lastResample.idBits.clear();
- for (size_t i = 0; i < pointerCount; i++) {
- uint32_t id = event->getPointerId(i);
- touchState.lastResample.idToIndex[id] = i;
- touchState.lastResample.idBits.markBit(id);
- PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
- const PointerCoords& currentCoords = current->getPointerById(id);
- if (other->idBits.hasBit(id)
- && shouldResampleTool(event->getToolType(i))) {
- const PointerCoords& otherCoords = other->getPointerById(id);
- resampledCoords.copyFrom(currentCoords);
- resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
- lerp(currentCoords.getX(), otherCoords.getX(), alpha));
- resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
- lerp(currentCoords.getY(), otherCoords.getY(), alpha));
-#if DEBUG_RESAMPLING
- ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
- "other (%0.3f, %0.3f), alpha %0.3f",
- id, resampledCoords.getX(), resampledCoords.getY(),
- currentCoords.getX(), currentCoords.getY(),
- otherCoords.getX(), otherCoords.getY(),
- alpha);
-#endif
- } else {
- resampledCoords.copyFrom(currentCoords);
-#if DEBUG_RESAMPLING
- ALOGD("[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)",
- id, resampledCoords.getX(), resampledCoords.getY(),
- currentCoords.getX(), currentCoords.getY());
-#endif
- }
- }
-
- event->addSample(sampleTime, touchState.lastResample.pointers);
-}
-
-bool InputConsumer::shouldResampleTool(int32_t toolType) {
- return toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
- || toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
-}
-
-status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
-#if DEBUG_TRANSPORT_ACTIONS
- ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
- mChannel->getName().string(), seq, handled ? "true" : "false");
-#endif
-
- if (!seq) {
- ALOGE("Attempted to send a finished signal with sequence number 0.");
- return BAD_VALUE;
- }
-
- // Send finished signals for the batch sequence chain first.
- size_t seqChainCount = mSeqChains.size();
- if (seqChainCount) {
- uint32_t currentSeq = seq;
- uint32_t chainSeqs[seqChainCount];
- size_t chainIndex = 0;
- for (size_t i = seqChainCount; i-- > 0; ) {
- const SeqChain& seqChain = mSeqChains.itemAt(i);
- if (seqChain.seq == currentSeq) {
- currentSeq = seqChain.chain;
- chainSeqs[chainIndex++] = currentSeq;
- mSeqChains.removeAt(i);
- }
- }
- status_t status = OK;
- while (!status && chainIndex-- > 0) {
- status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
- }
- if (status) {
- // An error occurred so at least one signal was not sent, reconstruct the chain.
- do {
- SeqChain seqChain;
- seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
- seqChain.chain = chainSeqs[chainIndex];
- mSeqChains.push(seqChain);
- } while (chainIndex-- > 0);
- return status;
- }
- }
-
- // Send finished signal for the last message in the batch.
- return sendUnchainedFinishedSignal(seq, handled);
-}
-
-status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
- InputMessage msg;
- msg.header.type = InputMessage::TYPE_FINISHED;
- msg.body.finished.seq = seq;
- msg.body.finished.handled = handled;
- return mChannel->sendMessage(&msg);
-}
-
-bool InputConsumer::hasDeferredEvent() const {
- return mMsgDeferred;
-}
-
-bool InputConsumer::hasPendingBatch() const {
- return !mBatches.isEmpty();
-}
-
-ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
- for (size_t i = 0; i < mBatches.size(); i++) {
- const Batch& batch = mBatches.itemAt(i);
- const InputMessage& head = batch.samples.itemAt(0);
- if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
- return i;
- }
- }
- return -1;
-}
-
-ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
- for (size_t i = 0; i < mTouchStates.size(); i++) {
- const TouchState& touchState = mTouchStates.itemAt(i);
- if (touchState.deviceId == deviceId && touchState.source == source) {
- return i;
- }
- }
- return -1;
-}
-
-void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
- event->initialize(
- msg->body.key.deviceId,
- msg->body.key.source,
- msg->body.key.action,
- msg->body.key.flags,
- msg->body.key.keyCode,
- msg->body.key.scanCode,
- msg->body.key.metaState,
- msg->body.key.repeatCount,
- msg->body.key.downTime,
- msg->body.key.eventTime);
-}
-
-void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
- size_t pointerCount = msg->body.motion.pointerCount;
- PointerProperties pointerProperties[pointerCount];
- PointerCoords pointerCoords[pointerCount];
- for (size_t i = 0; i < pointerCount; i++) {
- pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
- pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
- }
-
- event->initialize(
- msg->body.motion.deviceId,
- msg->body.motion.source,
- msg->body.motion.action,
- msg->body.motion.flags,
- msg->body.motion.edgeFlags,
- msg->body.motion.metaState,
- msg->body.motion.buttonState,
- msg->body.motion.xOffset,
- msg->body.motion.yOffset,
- msg->body.motion.xPrecision,
- msg->body.motion.yPrecision,
- msg->body.motion.downTime,
- msg->body.motion.eventTime,
- pointerCount,
- pointerProperties,
- pointerCoords);
-}
-
-void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
- size_t pointerCount = msg->body.motion.pointerCount;
- PointerCoords pointerCoords[pointerCount];
- for (size_t i = 0; i < pointerCount; i++) {
- pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
- }
-
- event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
- event->addSample(msg->body.motion.eventTime, pointerCoords);
-}
-
-bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
- const InputMessage& head = batch.samples.itemAt(0);
- size_t pointerCount = msg->body.motion.pointerCount;
- if (head.body.motion.pointerCount != pointerCount
- || head.body.motion.action != msg->body.motion.action) {
- return false;
- }
- for (size_t i = 0; i < pointerCount; i++) {
- if (head.body.motion.pointers[i].properties
- != msg->body.motion.pointers[i].properties) {
- return false;
- }
- }
- return true;
-}
-
-ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
- size_t numSamples = batch.samples.size();
- size_t index = 0;
- while (index < numSamples
- && batch.samples.itemAt(index).body.motion.eventTime <= time) {
- index += 1;
- }
- return ssize_t(index) - 1;
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/InputTransport.h b/widget/gonk/libui/InputTransport.h
deleted file mode 100644
index 66ef2850a..000000000
--- a/widget/gonk/libui/InputTransport.h
+++ /dev/null
@@ -1,443 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_INPUT_TRANSPORT_H
-#define _ANDROIDFW_INPUT_TRANSPORT_H
-
-/**
- * Native input transport.
- *
- * The InputChannel provides a mechanism for exchanging InputMessage structures across processes.
- *
- * The InputPublisher and InputConsumer each handle one end-point of an input channel.
- * The InputPublisher is used by the input dispatcher to send events to the application.
- * The InputConsumer is used by the application to receive events from the input dispatcher.
- */
-
-#include "Input.h"
-#include <utils/Errors.h>
-#include <utils/Timers.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/BitSet.h>
-
-namespace android {
-
-/*
- * Intermediate representation used to send input events and related signals.
- */
-struct InputMessage {
- enum {
- TYPE_KEY = 1,
- TYPE_MOTION = 2,
- TYPE_FINISHED = 3,
- };
-
- struct Header {
- uint32_t type;
- uint32_t padding; // 8 byte alignment for the body that follows
- } header;
-
- union Body {
- struct Key {
- uint32_t seq;
- nsecs_t eventTime;
- int32_t deviceId;
- int32_t source;
- int32_t action;
- int32_t flags;
- int32_t keyCode;
- int32_t scanCode;
- int32_t metaState;
- int32_t repeatCount;
- nsecs_t downTime;
-
- inline size_t size() const {
- return sizeof(Key);
- }
- } key;
-
- struct Motion {
- uint32_t seq;
- nsecs_t eventTime;
- int32_t deviceId;
- int32_t source;
- int32_t action;
- int32_t flags;
- int32_t metaState;
- int32_t buttonState;
- int32_t edgeFlags;
- nsecs_t downTime;
- float xOffset;
- float yOffset;
- float xPrecision;
- float yPrecision;
- size_t pointerCount;
- struct Pointer {
- PointerProperties properties;
- PointerCoords coords;
- } pointers[MAX_POINTERS];
-
- int32_t getActionId() const {
- uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
- >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
- return pointers[index].properties.id;
- }
-
- inline size_t size() const {
- return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
- + sizeof(Pointer) * pointerCount;
- }
- } motion;
-
- struct Finished {
- uint32_t seq;
- bool handled;
-
- inline size_t size() const {
- return sizeof(Finished);
- }
- } finished;
- } body;
-
- bool isValid(size_t actualSize) const;
- size_t size() const;
-};
-
-/*
- * An input channel consists of a local unix domain socket used to send and receive
- * input messages across processes. Each channel has a descriptive name for debugging purposes.
- *
- * Each endpoint has its own InputChannel object that specifies its file descriptor.
- *
- * The input channel is closed when all references to it are released.
- */
-class InputChannel : public RefBase {
-protected:
- virtual ~InputChannel();
-
-public:
- InputChannel(const String8& name, int fd);
-
- /* Creates a pair of input channels.
- *
- * Returns OK on success.
- */
- static status_t openInputChannelPair(const String8& name,
- sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
-
- inline String8 getName() const { return mName; }
- inline int getFd() const { return mFd; }
-
- /* Sends a message to the other endpoint.
- *
- * If the channel is full then the message is guaranteed not to have been sent at all.
- * Try again after the consumer has sent a finished signal indicating that it has
- * consumed some of the pending messages from the channel.
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if the channel is full.
- * Returns DEAD_OBJECT if the channel's peer has been closed.
- * Other errors probably indicate that the channel is broken.
- */
- status_t sendMessage(const InputMessage* msg);
-
- /* Receives a message sent by the other endpoint.
- *
- * If there is no message present, try again after poll() indicates that the fd
- * is readable.
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if there is no message present.
- * Returns DEAD_OBJECT if the channel's peer has been closed.
- * Other errors probably indicate that the channel is broken.
- */
- status_t receiveMessage(InputMessage* msg);
-
- /* Returns a new object that has a duplicate of this channel's fd. */
- sp<InputChannel> dup() const;
-
-private:
- String8 mName;
- int mFd;
-};
-
-/*
- * Publishes input events to an input channel.
- */
-class InputPublisher {
-public:
- /* Creates a publisher associated with an input channel. */
- explicit InputPublisher(const sp<InputChannel>& channel);
-
- /* Destroys the publisher and releases its input channel. */
- ~InputPublisher();
-
- /* Gets the underlying input channel. */
- inline sp<InputChannel> getChannel() { return mChannel; }
-
- /* Publishes a key event to the input channel.
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if the channel is full.
- * Returns DEAD_OBJECT if the channel's peer has been closed.
- * Returns BAD_VALUE if seq is 0.
- * Other errors probably indicate that the channel is broken.
- */
- status_t publishKeyEvent(
- uint32_t seq,
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t keyCode,
- int32_t scanCode,
- int32_t metaState,
- int32_t repeatCount,
- nsecs_t downTime,
- nsecs_t eventTime);
-
- /* Publishes a motion event to the input channel.
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if the channel is full.
- * Returns DEAD_OBJECT if the channel's peer has been closed.
- * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
- * Other errors probably indicate that the channel is broken.
- */
- status_t publishMotionEvent(
- uint32_t seq,
- int32_t deviceId,
- int32_t source,
- int32_t action,
- int32_t flags,
- int32_t edgeFlags,
- int32_t metaState,
- int32_t buttonState,
- float xOffset,
- float yOffset,
- float xPrecision,
- float yPrecision,
- nsecs_t downTime,
- nsecs_t eventTime,
- size_t pointerCount,
- const PointerProperties* pointerProperties,
- const PointerCoords* pointerCoords);
-
- /* Receives the finished signal from the consumer in reply to the original dispatch signal.
- * If a signal was received, returns the message sequence number,
- * and whether the consumer handled the message.
- *
- * The returned sequence number is never 0 unless the operation failed.
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if there is no signal present.
- * Returns DEAD_OBJECT if the channel's peer has been closed.
- * Other errors probably indicate that the channel is broken.
- */
- status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
-
-private:
- sp<InputChannel> mChannel;
-};
-
-/*
- * Consumes input events from an input channel.
- */
-class InputConsumer {
-public:
- /* Creates a consumer associated with an input channel. */
- explicit InputConsumer(const sp<InputChannel>& channel);
-
- /* Destroys the consumer and releases its input channel. */
- ~InputConsumer();
-
- /* Gets the underlying input channel. */
- inline sp<InputChannel> getChannel() { return mChannel; }
-
- /* Consumes an input event from the input channel and copies its contents into
- * an InputEvent object created using the specified factory.
- *
- * Tries to combine a series of move events into larger batches whenever possible.
- *
- * If consumeBatches is false, then defers consuming pending batched events if it
- * is possible for additional samples to be added to them later. Call hasPendingBatch()
- * to determine whether a pending batch is available to be consumed.
- *
- * If consumeBatches is true, then events are still batched but they are consumed
- * immediately as soon as the input channel is exhausted.
- *
- * The frameTime parameter specifies the time when the current display frame started
- * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
- *
- * The returned sequence number is never 0 unless the operation failed.
- *
- * Returns OK on success.
- * Returns WOULD_BLOCK if there is no event present.
- * Returns DEAD_OBJECT if the channel's peer has been closed.
- * Returns NO_MEMORY if the event could not be created.
- * Other errors probably indicate that the channel is broken.
- */
- status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
- nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
-
- /* Sends a finished signal to the publisher to inform it that the message
- * with the specified sequence number has finished being process and whether
- * the message was handled by the consumer.
- *
- * Returns OK on success.
- * Returns BAD_VALUE if seq is 0.
- * Other errors probably indicate that the channel is broken.
- */
- status_t sendFinishedSignal(uint32_t seq, bool handled);
-
- /* Returns true if there is a deferred event waiting.
- *
- * Should be called after calling consume() to determine whether the consumer
- * has a deferred event to be processed. Deferred events are somewhat special in
- * that they have already been removed from the input channel. If the input channel
- * becomes empty, the client may need to do extra work to ensure that it processes
- * the deferred event despite the fact that the input channel's file descriptor
- * is not readable.
- *
- * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
- * This guarantees that all deferred events will be processed.
- *
- * Alternately, the caller can call hasDeferredEvent() to determine whether there is
- * a deferred event waiting and then ensure that its event loop wakes up at least
- * one more time to consume the deferred event.
- */
- bool hasDeferredEvent() const;
-
- /* Returns true if there is a pending batch.
- *
- * Should be called after calling consume() with consumeBatches == false to determine
- * whether consume() should be called again later on with consumeBatches == true.
- */
- bool hasPendingBatch() const;
-
-private:
- // True if touch resampling is enabled.
- const bool mResampleTouch;
-
- // The input channel.
- sp<InputChannel> mChannel;
-
- // The current input message.
- InputMessage mMsg;
-
- // True if mMsg contains a valid input message that was deferred from the previous
- // call to consume and that still needs to be handled.
- bool mMsgDeferred;
-
- // Batched motion events per device and source.
- struct Batch {
- Vector<InputMessage> samples;
- };
- Vector<Batch> mBatches;
-
- // Touch state per device and source, only for sources of class pointer.
- struct History {
- nsecs_t eventTime;
- BitSet32 idBits;
- int32_t idToIndex[MAX_POINTER_ID + 1];
- PointerCoords pointers[MAX_POINTERS];
-
- void initializeFrom(const InputMessage* msg) {
- eventTime = msg->body.motion.eventTime;
- idBits.clear();
- for (size_t i = 0; i < msg->body.motion.pointerCount; i++) {
- uint32_t id = msg->body.motion.pointers[i].properties.id;
- idBits.markBit(id);
- idToIndex[id] = i;
- pointers[i].copyFrom(msg->body.motion.pointers[i].coords);
- }
- }
-
- const PointerCoords& getPointerById(uint32_t id) const {
- return pointers[idToIndex[id]];
- }
- };
- struct TouchState {
- int32_t deviceId;
- int32_t source;
- size_t historyCurrent;
- size_t historySize;
- History history[2];
- History lastResample;
-
- void initialize(int32_t deviceId, int32_t source) {
- this->deviceId = deviceId;
- this->source = source;
- historyCurrent = 0;
- historySize = 0;
- lastResample.eventTime = 0;
- lastResample.idBits.clear();
- }
-
- void addHistory(const InputMessage* msg) {
- historyCurrent ^= 1;
- if (historySize < 2) {
- historySize += 1;
- }
- history[historyCurrent].initializeFrom(msg);
- }
-
- const History* getHistory(size_t index) const {
- return &history[(historyCurrent + index) & 1];
- }
- };
- Vector<TouchState> mTouchStates;
-
- // Chain of batched sequence numbers. When multiple input messages are combined into
- // a batch, we append a record here that associates the last sequence number in the
- // batch with the previous one. When the finished signal is sent, we traverse the
- // chain to individually finish all input messages that were part of the batch.
- struct SeqChain {
- uint32_t seq; // sequence number of batched input message
- uint32_t chain; // sequence number of previous batched input message
- };
- Vector<SeqChain> mSeqChains;
-
- status_t consumeBatch(InputEventFactoryInterface* factory,
- nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
- status_t consumeSamples(InputEventFactoryInterface* factory,
- Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
-
- void updateTouchState(InputMessage* msg);
- void rewriteMessage(const TouchState& state, InputMessage* msg);
- void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
- const InputMessage *next);
-
- ssize_t findBatch(int32_t deviceId, int32_t source) const;
- ssize_t findTouchState(int32_t deviceId, int32_t source) const;
-
- status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
-
- static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
- static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
- static void addSample(MotionEvent* event, const InputMessage* msg);
- static bool canAddSample(const Batch& batch, const InputMessage* msg);
- static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
- static bool shouldResampleTool(int32_t toolType);
-
- static bool isTouchResamplingEnabled();
-};
-
-} // namespace android
-
-#endif // _ANDROIDFW_INPUT_TRANSPORT_H
diff --git a/widget/gonk/libui/InputWindow.cpp b/widget/gonk/libui/InputWindow.cpp
deleted file mode 100644
index 3aea445a0..000000000
--- a/widget/gonk/libui/InputWindow.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "InputWindow"
-
-#include "InputWindow.h"
-
-#include "cutils_log.h"
-
-namespace android {
-
-// --- InputWindowInfo ---
-
-bool InputWindowInfo::touchableRegionContainsPoint(int32_t x, int32_t y) const {
- return touchableRegion.contains(x, y);
-}
-
-bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const {
- return x >= frameLeft && x <= frameRight
- && y >= frameTop && y <= frameBottom;
-}
-
-bool InputWindowInfo::isTrustedOverlay() const {
- return layoutParamsType == TYPE_INPUT_METHOD
- || layoutParamsType == TYPE_INPUT_METHOD_DIALOG
- || layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY;
-}
-
-bool InputWindowInfo::supportsSplitTouch() const {
- return layoutParamsFlags & FLAG_SPLIT_TOUCH;
-}
-
-
-// --- InputWindowHandle ---
-
-InputWindowHandle::InputWindowHandle(const sp<InputApplicationHandle>& inputApplicationHandle) :
- inputApplicationHandle(inputApplicationHandle), mInfo(NULL) {
-}
-
-InputWindowHandle::~InputWindowHandle() {
- delete mInfo;
-}
-
-void InputWindowHandle::releaseInfo() {
- if (mInfo) {
- delete mInfo;
- mInfo = NULL;
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/InputWindow.h b/widget/gonk/libui/InputWindow.h
deleted file mode 100644
index cce5fd4fe..000000000
--- a/widget/gonk/libui/InputWindow.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_INPUT_WINDOW_H
-#define _UI_INPUT_WINDOW_H
-
-#include "Input.h"
-#include "InputTransport.h"
-#include <utils/RefBase.h>
-#include <utils/Timers.h>
-#include <utils/String8.h>
-
-#include <SkRegion.h>
-
-#include "InputApplication.h"
-
-namespace android {
-
-/*
- * Describes the properties of a window that can receive input.
- */
-struct InputWindowInfo {
- // Window flags from WindowManager.LayoutParams
- enum {
- FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001,
- FLAG_DIM_BEHIND = 0x00000002,
- FLAG_BLUR_BEHIND = 0x00000004,
- FLAG_NOT_FOCUSABLE = 0x00000008,
- FLAG_NOT_TOUCHABLE = 0x00000010,
- FLAG_NOT_TOUCH_MODAL = 0x00000020,
- FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040,
- FLAG_KEEP_SCREEN_ON = 0x00000080,
- FLAG_LAYOUT_IN_SCREEN = 0x00000100,
- FLAG_LAYOUT_NO_LIMITS = 0x00000200,
- FLAG_FULLSCREEN = 0x00000400,
- FLAG_FORCE_NOT_FULLSCREEN = 0x00000800,
- FLAG_DITHER = 0x00001000,
- FLAG_SECURE = 0x00002000,
- FLAG_SCALED = 0x00004000,
- FLAG_IGNORE_CHEEK_PRESSES = 0x00008000,
- FLAG_LAYOUT_INSET_DECOR = 0x00010000,
- FLAG_ALT_FOCUSABLE_IM = 0x00020000,
- FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000,
- FLAG_SHOW_WHEN_LOCKED = 0x00080000,
- FLAG_SHOW_WALLPAPER = 0x00100000,
- FLAG_TURN_SCREEN_ON = 0x00200000,
- FLAG_DISMISS_KEYGUARD = 0x00400000,
- FLAG_SPLIT_TOUCH = 0x00800000,
- FLAG_HARDWARE_ACCELERATED = 0x01000000,
- FLAG_HARDWARE_ACCELERATED_SYSTEM = 0x02000000,
- FLAG_SLIPPERY = 0x04000000,
- FLAG_NEEDS_MENU_KEY = 0x08000000,
- FLAG_KEEP_SURFACE_WHILE_ANIMATING = 0x10000000,
- FLAG_COMPATIBLE_WINDOW = 0x20000000,
- FLAG_SYSTEM_ERROR = 0x40000000,
- };
-
- // Window types from WindowManager.LayoutParams
- enum {
- FIRST_APPLICATION_WINDOW = 1,
- TYPE_BASE_APPLICATION = 1,
- TYPE_APPLICATION = 2,
- TYPE_APPLICATION_STARTING = 3,
- LAST_APPLICATION_WINDOW = 99,
- FIRST_SUB_WINDOW = 1000,
- TYPE_APPLICATION_PANEL = FIRST_SUB_WINDOW,
- TYPE_APPLICATION_MEDIA = FIRST_SUB_WINDOW+1,
- TYPE_APPLICATION_SUB_PANEL = FIRST_SUB_WINDOW+2,
- TYPE_APPLICATION_ATTACHED_DIALOG = FIRST_SUB_WINDOW+3,
- TYPE_APPLICATION_MEDIA_OVERLAY = FIRST_SUB_WINDOW+4,
- LAST_SUB_WINDOW = 1999,
- FIRST_SYSTEM_WINDOW = 2000,
- TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW,
- TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1,
- TYPE_PHONE = FIRST_SYSTEM_WINDOW+2,
- TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3,
- TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW+4,
- TYPE_TOAST = FIRST_SYSTEM_WINDOW+5,
- TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+6,
- TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW+7,
- TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW+8,
- TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW+9,
- TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW+10,
- TYPE_INPUT_METHOD = FIRST_SYSTEM_WINDOW+11,
- TYPE_INPUT_METHOD_DIALOG= FIRST_SYSTEM_WINDOW+12,
- TYPE_WALLPAPER = FIRST_SYSTEM_WINDOW+13,
- TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW+14,
- TYPE_SECURE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+15,
- TYPE_DRAG = FIRST_SYSTEM_WINDOW+16,
- TYPE_STATUS_BAR_SUB_PANEL = FIRST_SYSTEM_WINDOW+17,
- TYPE_POINTER = FIRST_SYSTEM_WINDOW+18,
- TYPE_NAVIGATION_BAR = FIRST_SYSTEM_WINDOW+19,
- TYPE_VOLUME_OVERLAY = FIRST_SYSTEM_WINDOW+20,
- TYPE_BOOT_PROGRESS = FIRST_SYSTEM_WINDOW+21,
- LAST_SYSTEM_WINDOW = 2999,
- };
-
- enum {
- INPUT_FEATURE_DISABLE_TOUCH_PAD_GESTURES = 0x00000001,
- INPUT_FEATURE_NO_INPUT_CHANNEL = 0x00000002,
- INPUT_FEATURE_DISABLE_USER_ACTIVITY = 0x00000004,
- };
-
- sp<InputChannel> inputChannel;
- String8 name;
- int32_t layoutParamsFlags;
- int32_t layoutParamsType;
- nsecs_t dispatchingTimeout;
- int32_t frameLeft;
- int32_t frameTop;
- int32_t frameRight;
- int32_t frameBottom;
- float scaleFactor;
- SkRegion touchableRegion;
- bool visible;
- bool canReceiveKeys;
- bool hasFocus;
- bool hasWallpaper;
- bool paused;
- int32_t layer;
- int32_t ownerPid;
- int32_t ownerUid;
- int32_t inputFeatures;
- int32_t displayId;
-
- bool touchableRegionContainsPoint(int32_t x, int32_t y) const;
- bool frameContainsPoint(int32_t x, int32_t y) const;
-
- /* Returns true if the window is of a trusted type that is allowed to silently
- * overlay other windows for the purpose of implementing the secure views feature.
- * Trusted overlays, such as IME windows, can partly obscure other windows without causing
- * motion events to be delivered to them with AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED.
- */
- bool isTrustedOverlay() const;
-
- bool supportsSplitTouch() const;
-};
-
-
-/*
- * Handle for a window that can receive input.
- *
- * Used by the native input dispatcher to indirectly refer to the window manager objects
- * that describe a window.
- */
-class InputWindowHandle : public RefBase {
-public:
- const sp<InputApplicationHandle> inputApplicationHandle;
-
- inline const InputWindowInfo* getInfo() const {
- return mInfo;
- }
-
- inline sp<InputChannel> getInputChannel() const {
- return mInfo ? mInfo->inputChannel : NULL;
- }
-
- inline String8 getName() const {
- return mInfo ? mInfo->name : String8("<invalid>");
- }
-
- inline nsecs_t getDispatchingTimeout(nsecs_t defaultValue) const {
- return mInfo ? mInfo->dispatchingTimeout : defaultValue;
- }
-
- /**
- * Requests that the state of this object be updated to reflect
- * the most current available information about the application.
- *
- * This method should only be called from within the input dispatcher's
- * critical section.
- *
- * Returns true on success, or false if the handle is no longer valid.
- */
- virtual bool updateInfo() = 0;
-
- /**
- * Releases the storage used by the associated information when it is
- * no longer needed.
- */
- void releaseInfo();
-
-protected:
- InputWindowHandle(const sp<InputApplicationHandle>& inputApplicationHandle);
- virtual ~InputWindowHandle();
-
- InputWindowInfo* mInfo;
-};
-
-} // namespace android
-
-#endif // _UI_INPUT_WINDOW_H
diff --git a/widget/gonk/libui/KeyCharacterMap.cpp b/widget/gonk/libui/KeyCharacterMap.cpp
deleted file mode 100644
index cec0666ce..000000000
--- a/widget/gonk/libui/KeyCharacterMap.cpp
+++ /dev/null
@@ -1,1153 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "KeyCharacterMap"
-#include "cutils_log.h"
-
-#include <stdlib.h>
-#include <string.h>
-#include "android_keycodes.h"
-#include "Keyboard.h"
-#include "KeyCharacterMap.h"
-
-#if HAVE_ANDROID_OS
-#include <binder/Parcel.h>
-#endif
-
-#include <utils/Errors.h>
-#include "Tokenizer.h"
-#include <utils/Timers.h>
-
-// Enables debug output for the parser.
-#define DEBUG_PARSER 0
-
-// Enables debug output for parser performance.
-#define DEBUG_PARSER_PERFORMANCE 0
-
-// Enables debug output for mapping.
-#define DEBUG_MAPPING 0
-
-
-namespace android {
-
-static const char* WHITESPACE = " \t\r";
-static const char* WHITESPACE_OR_PROPERTY_DELIMITER = " \t\r,:";
-
-struct Modifier {
- const char* label;
- int32_t metaState;
-};
-static const Modifier modifiers[] = {
- { "shift", AMETA_SHIFT_ON },
- { "lshift", AMETA_SHIFT_LEFT_ON },
- { "rshift", AMETA_SHIFT_RIGHT_ON },
- { "alt", AMETA_ALT_ON },
- { "lalt", AMETA_ALT_LEFT_ON },
- { "ralt", AMETA_ALT_RIGHT_ON },
- { "ctrl", AMETA_CTRL_ON },
- { "lctrl", AMETA_CTRL_LEFT_ON },
- { "rctrl", AMETA_CTRL_RIGHT_ON },
- { "meta", AMETA_META_ON },
- { "lmeta", AMETA_META_LEFT_ON },
- { "rmeta", AMETA_META_RIGHT_ON },
- { "sym", AMETA_SYM_ON },
- { "fn", AMETA_FUNCTION_ON },
- { "capslock", AMETA_CAPS_LOCK_ON },
- { "numlock", AMETA_NUM_LOCK_ON },
- { "scrolllock", AMETA_SCROLL_LOCK_ON },
-};
-
-#if DEBUG_MAPPING
-static String8 toString(const char16_t* chars, size_t numChars) {
- String8 result;
- for (size_t i = 0; i < numChars; i++) {
- result.appendFormat(i == 0 ? "%d" : ", %d", chars[i]);
- }
- return result;
-}
-#endif
-
-
-// --- KeyCharacterMap ---
-
-sp<KeyCharacterMap> KeyCharacterMap::sEmpty = new KeyCharacterMap();
-
-KeyCharacterMap::KeyCharacterMap() :
- mType(KEYBOARD_TYPE_UNKNOWN) {
-}
-
-KeyCharacterMap::KeyCharacterMap(const KeyCharacterMap& other) :
- RefBase(), mType(other.mType), mKeysByScanCode(other.mKeysByScanCode),
- mKeysByUsageCode(other.mKeysByUsageCode) {
- for (size_t i = 0; i < other.mKeys.size(); i++) {
- mKeys.add(other.mKeys.keyAt(i), new Key(*other.mKeys.valueAt(i)));
- }
-}
-
-KeyCharacterMap::~KeyCharacterMap() {
- for (size_t i = 0; i < mKeys.size(); i++) {
- Key* key = mKeys.editValueAt(i);
- delete key;
- }
-}
-
-status_t KeyCharacterMap::load(const String8& filename,
- Format format, sp<KeyCharacterMap>* outMap) {
- outMap->clear();
-
- Tokenizer* tokenizer;
- status_t status = Tokenizer::open(filename, &tokenizer);
- if (status) {
- ALOGE("Error %d opening key character map file %s.", status, filename.string());
- } else {
- status = load(tokenizer, format, outMap);
- delete tokenizer;
- }
- return status;
-}
-
-status_t KeyCharacterMap::loadContents(const String8& filename, const char* contents,
- Format format, sp<KeyCharacterMap>* outMap) {
- outMap->clear();
-
- Tokenizer* tokenizer;
- status_t status = Tokenizer::fromContents(filename, contents, &tokenizer);
- if (status) {
- ALOGE("Error %d opening key character map.", status);
- } else {
- status = load(tokenizer, format, outMap);
- delete tokenizer;
- }
- return status;
-}
-
-status_t KeyCharacterMap::load(Tokenizer* tokenizer,
- Format format, sp<KeyCharacterMap>* outMap) {
- status_t status = OK;
- sp<KeyCharacterMap> map = new KeyCharacterMap();
- if (!map.get()) {
- ALOGE("Error allocating key character map.");
- status = NO_MEMORY;
- } else {
-#if DEBUG_PARSER_PERFORMANCE
- nsecs_t startTime = systemTime(SYSTEM_TIME_MONOTONIC);
-#endif
- Parser parser(map.get(), tokenizer, format);
- status = parser.parse();
-#if DEBUG_PARSER_PERFORMANCE
- nsecs_t elapsedTime = systemTime(SYSTEM_TIME_MONOTONIC) - startTime;
- ALOGD("Parsed key character map file '%s' %d lines in %0.3fms.",
- tokenizer->getFilename().string(), tokenizer->getLineNumber(),
- elapsedTime / 1000000.0);
-#endif
- if (!status) {
- *outMap = map;
- }
- }
- return status;
-}
-
-sp<KeyCharacterMap> KeyCharacterMap::combine(const sp<KeyCharacterMap>& base,
- const sp<KeyCharacterMap>& overlay) {
- if (overlay == NULL) {
- return base;
- }
- if (base == NULL) {
- return overlay;
- }
-
- sp<KeyCharacterMap> map = new KeyCharacterMap(*base.get());
- for (size_t i = 0; i < overlay->mKeys.size(); i++) {
- int32_t keyCode = overlay->mKeys.keyAt(i);
- Key* key = overlay->mKeys.valueAt(i);
- ssize_t oldIndex = map->mKeys.indexOfKey(keyCode);
- if (oldIndex >= 0) {
- delete map->mKeys.valueAt(oldIndex);
- map->mKeys.editValueAt(oldIndex) = new Key(*key);
- } else {
- map->mKeys.add(keyCode, new Key(*key));
- }
- }
-
- for (size_t i = 0; i < overlay->mKeysByScanCode.size(); i++) {
- map->mKeysByScanCode.replaceValueFor(overlay->mKeysByScanCode.keyAt(i),
- overlay->mKeysByScanCode.valueAt(i));
- }
-
- for (size_t i = 0; i < overlay->mKeysByUsageCode.size(); i++) {
- map->mKeysByUsageCode.replaceValueFor(overlay->mKeysByUsageCode.keyAt(i),
- overlay->mKeysByUsageCode.valueAt(i));
- }
- return map;
-}
-
-sp<KeyCharacterMap> KeyCharacterMap::empty() {
- return sEmpty;
-}
-
-int32_t KeyCharacterMap::getKeyboardType() const {
- return mType;
-}
-
-char16_t KeyCharacterMap::getDisplayLabel(int32_t keyCode) const {
- char16_t result = 0;
- const Key* key;
- if (getKey(keyCode, &key)) {
- result = key->label;
- }
-#if DEBUG_MAPPING
- ALOGD("getDisplayLabel: keyCode=%d ~ Result %d.", keyCode, result);
-#endif
- return result;
-}
-
-char16_t KeyCharacterMap::getNumber(int32_t keyCode) const {
- char16_t result = 0;
- const Key* key;
- if (getKey(keyCode, &key)) {
- result = key->number;
- }
-#if DEBUG_MAPPING
- ALOGD("getNumber: keyCode=%d ~ Result %d.", keyCode, result);
-#endif
- return result;
-}
-
-char16_t KeyCharacterMap::getCharacter(int32_t keyCode, int32_t metaState) const {
- char16_t result = 0;
- const Key* key;
- const Behavior* behavior;
- if (getKeyBehavior(keyCode, metaState, &key, &behavior)) {
- result = behavior->character;
- }
-#if DEBUG_MAPPING
- ALOGD("getCharacter: keyCode=%d, metaState=0x%08x ~ Result %d.", keyCode, metaState, result);
-#endif
- return result;
-}
-
-bool KeyCharacterMap::getFallbackAction(int32_t keyCode, int32_t metaState,
- FallbackAction* outFallbackAction) const {
- outFallbackAction->keyCode = 0;
- outFallbackAction->metaState = 0;
-
- bool result = false;
- const Key* key;
- const Behavior* behavior;
- if (getKeyBehavior(keyCode, metaState, &key, &behavior)) {
- if (behavior->fallbackKeyCode) {
- outFallbackAction->keyCode = behavior->fallbackKeyCode;
- outFallbackAction->metaState = metaState & ~behavior->metaState;
- result = true;
- }
- }
-#if DEBUG_MAPPING
- ALOGD("getFallbackKeyCode: keyCode=%d, metaState=0x%08x ~ Result %s, "
- "fallback keyCode=%d, fallback metaState=0x%08x.",
- keyCode, metaState, result ? "true" : "false",
- outFallbackAction->keyCode, outFallbackAction->metaState);
-#endif
- return result;
-}
-
-char16_t KeyCharacterMap::getMatch(int32_t keyCode, const char16_t* chars, size_t numChars,
- int32_t metaState) const {
- char16_t result = 0;
- const Key* key;
- if (getKey(keyCode, &key)) {
- // Try to find the most general behavior that maps to this character.
- // For example, the base key behavior will usually be last in the list.
- // However, if we find a perfect meta state match for one behavior then use that one.
- for (const Behavior* behavior = key->firstBehavior; behavior; behavior = behavior->next) {
- if (behavior->character) {
- for (size_t i = 0; i < numChars; i++) {
- if (behavior->character == chars[i]) {
- result = behavior->character;
- if ((behavior->metaState & metaState) == behavior->metaState) {
- goto ExactMatch;
- }
- break;
- }
- }
- }
- }
- ExactMatch: ;
- }
-#if DEBUG_MAPPING
- ALOGD("getMatch: keyCode=%d, chars=[%s], metaState=0x%08x ~ Result %d.",
- keyCode, toString(chars, numChars).string(), metaState, result);
-#endif
- return result;
-}
-
-bool KeyCharacterMap::getEvents(int32_t deviceId, const char16_t* chars, size_t numChars,
- Vector<KeyEvent>& outEvents) const {
- nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
-
- for (size_t i = 0; i < numChars; i++) {
- int32_t keyCode, metaState;
- char16_t ch = chars[i];
- if (!findKey(ch, &keyCode, &metaState)) {
-#if DEBUG_MAPPING
- ALOGD("getEvents: deviceId=%d, chars=[%s] ~ Failed to find mapping for character %d.",
- deviceId, toString(chars, numChars).string(), ch);
-#endif
- return false;
- }
-
- int32_t currentMetaState = 0;
- addMetaKeys(outEvents, deviceId, metaState, true, now, &currentMetaState);
- addKey(outEvents, deviceId, keyCode, currentMetaState, true, now);
- addKey(outEvents, deviceId, keyCode, currentMetaState, false, now);
- addMetaKeys(outEvents, deviceId, metaState, false, now, &currentMetaState);
- }
-#if DEBUG_MAPPING
- ALOGD("getEvents: deviceId=%d, chars=[%s] ~ Generated %d events.",
- deviceId, toString(chars, numChars).string(), int32_t(outEvents.size()));
- for (size_t i = 0; i < outEvents.size(); i++) {
- ALOGD(" Key: keyCode=%d, metaState=0x%08x, %s.",
- outEvents[i].getKeyCode(), outEvents[i].getMetaState(),
- outEvents[i].getAction() == AKEY_EVENT_ACTION_DOWN ? "down" : "up");
- }
-#endif
- return true;
-}
-
-status_t KeyCharacterMap::mapKey(int32_t scanCode, int32_t usageCode, int32_t* outKeyCode) const {
- if (usageCode) {
- ssize_t index = mKeysByUsageCode.indexOfKey(usageCode);
- if (index >= 0) {
-#if DEBUG_MAPPING
- ALOGD("mapKey: scanCode=%d, usageCode=0x%08x ~ Result keyCode=%d.",
- scanCode, usageCode, *outKeyCode);
-#endif
- *outKeyCode = mKeysByUsageCode.valueAt(index);
- return OK;
- }
- }
- if (scanCode) {
- ssize_t index = mKeysByScanCode.indexOfKey(scanCode);
- if (index >= 0) {
-#if DEBUG_MAPPING
- ALOGD("mapKey: scanCode=%d, usageCode=0x%08x ~ Result keyCode=%d.",
- scanCode, usageCode, *outKeyCode);
-#endif
- *outKeyCode = mKeysByScanCode.valueAt(index);
- return OK;
- }
- }
-
-#if DEBUG_MAPPING
- ALOGD("mapKey: scanCode=%d, usageCode=0x%08x ~ Failed.", scanCode, usageCode);
-#endif
- *outKeyCode = AKEYCODE_UNKNOWN;
- return NAME_NOT_FOUND;
-}
-
-bool KeyCharacterMap::getKey(int32_t keyCode, const Key** outKey) const {
- ssize_t index = mKeys.indexOfKey(keyCode);
- if (index >= 0) {
- *outKey = mKeys.valueAt(index);
- return true;
- }
- return false;
-}
-
-bool KeyCharacterMap::getKeyBehavior(int32_t keyCode, int32_t metaState,
- const Key** outKey, const Behavior** outBehavior) const {
- const Key* key;
- if (getKey(keyCode, &key)) {
- const Behavior* behavior = key->firstBehavior;
- while (behavior) {
- if (matchesMetaState(metaState, behavior->metaState)) {
- *outKey = key;
- *outBehavior = behavior;
- return true;
- }
- behavior = behavior->next;
- }
- }
- return false;
-}
-
-bool KeyCharacterMap::matchesMetaState(int32_t eventMetaState, int32_t behaviorMetaState) {
- // Behavior must have at least the set of meta states specified.
- // And if the key event has CTRL, ALT or META then the behavior must exactly
- // match those, taking into account that a behavior can specify that it handles
- // one, both or either of a left/right modifier pair.
- if ((eventMetaState & behaviorMetaState) == behaviorMetaState) {
- const int32_t EXACT_META_STATES =
- AMETA_CTRL_ON | AMETA_CTRL_LEFT_ON | AMETA_CTRL_RIGHT_ON
- | AMETA_ALT_ON | AMETA_ALT_LEFT_ON | AMETA_ALT_RIGHT_ON
- | AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON;
- int32_t unmatchedMetaState = eventMetaState & ~behaviorMetaState & EXACT_META_STATES;
- if (behaviorMetaState & AMETA_CTRL_ON) {
- unmatchedMetaState &= ~(AMETA_CTRL_LEFT_ON | AMETA_CTRL_RIGHT_ON);
- } else if (behaviorMetaState & (AMETA_CTRL_LEFT_ON | AMETA_CTRL_RIGHT_ON)) {
- unmatchedMetaState &= ~AMETA_CTRL_ON;
- }
- if (behaviorMetaState & AMETA_ALT_ON) {
- unmatchedMetaState &= ~(AMETA_ALT_LEFT_ON | AMETA_ALT_RIGHT_ON);
- } else if (behaviorMetaState & (AMETA_ALT_LEFT_ON | AMETA_ALT_RIGHT_ON)) {
- unmatchedMetaState &= ~AMETA_ALT_ON;
- }
- if (behaviorMetaState & AMETA_META_ON) {
- unmatchedMetaState &= ~(AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
- } else if (behaviorMetaState & (AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON)) {
- unmatchedMetaState &= ~AMETA_META_ON;
- }
- return !unmatchedMetaState;
- }
- return false;
-}
-
-bool KeyCharacterMap::findKey(char16_t ch, int32_t* outKeyCode, int32_t* outMetaState) const {
- if (!ch) {
- return false;
- }
-
- for (size_t i = 0; i < mKeys.size(); i++) {
- const Key* key = mKeys.valueAt(i);
-
- // Try to find the most general behavior that maps to this character.
- // For example, the base key behavior will usually be last in the list.
- const Behavior* found = NULL;
- for (const Behavior* behavior = key->firstBehavior; behavior; behavior = behavior->next) {
- if (behavior->character == ch) {
- found = behavior;
- }
- }
- if (found) {
- *outKeyCode = mKeys.keyAt(i);
- *outMetaState = found->metaState;
- return true;
- }
- }
- return false;
-}
-
-void KeyCharacterMap::addKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t keyCode, int32_t metaState, bool down, nsecs_t time) {
- outEvents.push();
- KeyEvent& event = outEvents.editTop();
- event.initialize(deviceId, AINPUT_SOURCE_KEYBOARD,
- down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
- 0, keyCode, 0, metaState, 0, time, time);
-}
-
-void KeyCharacterMap::addMetaKeys(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t* currentMetaState) {
- // Add and remove meta keys symmetrically.
- if (down) {
- addLockedMetaKey(outEvents, deviceId, metaState, time,
- AKEYCODE_CAPS_LOCK, AMETA_CAPS_LOCK_ON, currentMetaState);
- addLockedMetaKey(outEvents, deviceId, metaState, time,
- AKEYCODE_NUM_LOCK, AMETA_NUM_LOCK_ON, currentMetaState);
- addLockedMetaKey(outEvents, deviceId, metaState, time,
- AKEYCODE_SCROLL_LOCK, AMETA_SCROLL_LOCK_ON, currentMetaState);
-
- addDoubleEphemeralMetaKey(outEvents, deviceId, metaState, true, time,
- AKEYCODE_SHIFT_LEFT, AMETA_SHIFT_LEFT_ON,
- AKEYCODE_SHIFT_RIGHT, AMETA_SHIFT_RIGHT_ON,
- AMETA_SHIFT_ON, currentMetaState);
- addDoubleEphemeralMetaKey(outEvents, deviceId, metaState, true, time,
- AKEYCODE_ALT_LEFT, AMETA_ALT_LEFT_ON,
- AKEYCODE_ALT_RIGHT, AMETA_ALT_RIGHT_ON,
- AMETA_ALT_ON, currentMetaState);
- addDoubleEphemeralMetaKey(outEvents, deviceId, metaState, true, time,
- AKEYCODE_CTRL_LEFT, AMETA_CTRL_LEFT_ON,
- AKEYCODE_CTRL_RIGHT, AMETA_CTRL_RIGHT_ON,
- AMETA_CTRL_ON, currentMetaState);
- addDoubleEphemeralMetaKey(outEvents, deviceId, metaState, true, time,
- AKEYCODE_META_LEFT, AMETA_META_LEFT_ON,
- AKEYCODE_META_RIGHT, AMETA_META_RIGHT_ON,
- AMETA_META_ON, currentMetaState);
-
- addSingleEphemeralMetaKey(outEvents, deviceId, metaState, true, time,
- AKEYCODE_SYM, AMETA_SYM_ON, currentMetaState);
- addSingleEphemeralMetaKey(outEvents, deviceId, metaState, true, time,
- AKEYCODE_FUNCTION, AMETA_FUNCTION_ON, currentMetaState);
- } else {
- addSingleEphemeralMetaKey(outEvents, deviceId, metaState, false, time,
- AKEYCODE_FUNCTION, AMETA_FUNCTION_ON, currentMetaState);
- addSingleEphemeralMetaKey(outEvents, deviceId, metaState, false, time,
- AKEYCODE_SYM, AMETA_SYM_ON, currentMetaState);
-
- addDoubleEphemeralMetaKey(outEvents, deviceId, metaState, false, time,
- AKEYCODE_META_LEFT, AMETA_META_LEFT_ON,
- AKEYCODE_META_RIGHT, AMETA_META_RIGHT_ON,
- AMETA_META_ON, currentMetaState);
- addDoubleEphemeralMetaKey(outEvents, deviceId, metaState, false, time,
- AKEYCODE_CTRL_LEFT, AMETA_CTRL_LEFT_ON,
- AKEYCODE_CTRL_RIGHT, AMETA_CTRL_RIGHT_ON,
- AMETA_CTRL_ON, currentMetaState);
- addDoubleEphemeralMetaKey(outEvents, deviceId, metaState, false, time,
- AKEYCODE_ALT_LEFT, AMETA_ALT_LEFT_ON,
- AKEYCODE_ALT_RIGHT, AMETA_ALT_RIGHT_ON,
- AMETA_ALT_ON, currentMetaState);
- addDoubleEphemeralMetaKey(outEvents, deviceId, metaState, false, time,
- AKEYCODE_SHIFT_LEFT, AMETA_SHIFT_LEFT_ON,
- AKEYCODE_SHIFT_RIGHT, AMETA_SHIFT_RIGHT_ON,
- AMETA_SHIFT_ON, currentMetaState);
-
- addLockedMetaKey(outEvents, deviceId, metaState, time,
- AKEYCODE_SCROLL_LOCK, AMETA_SCROLL_LOCK_ON, currentMetaState);
- addLockedMetaKey(outEvents, deviceId, metaState, time,
- AKEYCODE_NUM_LOCK, AMETA_NUM_LOCK_ON, currentMetaState);
- addLockedMetaKey(outEvents, deviceId, metaState, time,
- AKEYCODE_CAPS_LOCK, AMETA_CAPS_LOCK_ON, currentMetaState);
- }
-}
-
-bool KeyCharacterMap::addSingleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t keyCode, int32_t keyMetaState,
- int32_t* currentMetaState) {
- if ((metaState & keyMetaState) == keyMetaState) {
- *currentMetaState = updateMetaState(keyCode, down, *currentMetaState);
- addKey(outEvents, deviceId, keyCode, *currentMetaState, down, time);
- return true;
- }
- return false;
-}
-
-void KeyCharacterMap::addDoubleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t leftKeyCode, int32_t leftKeyMetaState,
- int32_t rightKeyCode, int32_t rightKeyMetaState,
- int32_t eitherKeyMetaState,
- int32_t* currentMetaState) {
- bool specific = false;
- specific |= addSingleEphemeralMetaKey(outEvents, deviceId, metaState, down, time,
- leftKeyCode, leftKeyMetaState, currentMetaState);
- specific |= addSingleEphemeralMetaKey(outEvents, deviceId, metaState, down, time,
- rightKeyCode, rightKeyMetaState, currentMetaState);
-
- if (!specific) {
- addSingleEphemeralMetaKey(outEvents, deviceId, metaState, down, time,
- leftKeyCode, eitherKeyMetaState, currentMetaState);
- }
-}
-
-void KeyCharacterMap::addLockedMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, nsecs_t time,
- int32_t keyCode, int32_t keyMetaState,
- int32_t* currentMetaState) {
- if ((metaState & keyMetaState) == keyMetaState) {
- *currentMetaState = updateMetaState(keyCode, true, *currentMetaState);
- addKey(outEvents, deviceId, keyCode, *currentMetaState, true, time);
- *currentMetaState = updateMetaState(keyCode, false, *currentMetaState);
- addKey(outEvents, deviceId, keyCode, *currentMetaState, false, time);
- }
-}
-
-#if HAVE_ANDROID_OS
-sp<KeyCharacterMap> KeyCharacterMap::readFromParcel(Parcel* parcel) {
- sp<KeyCharacterMap> map = new KeyCharacterMap();
- map->mType = parcel->readInt32();
- size_t numKeys = parcel->readInt32();
- if (parcel->errorCheck()) {
- return NULL;
- }
-
- for (size_t i = 0; i < numKeys; i++) {
- int32_t keyCode = parcel->readInt32();
- char16_t label = parcel->readInt32();
- char16_t number = parcel->readInt32();
- if (parcel->errorCheck()) {
- return NULL;
- }
-
- Key* key = new Key();
- key->label = label;
- key->number = number;
- map->mKeys.add(keyCode, key);
-
- Behavior* lastBehavior = NULL;
- while (parcel->readInt32()) {
- int32_t metaState = parcel->readInt32();
- char16_t character = parcel->readInt32();
- int32_t fallbackKeyCode = parcel->readInt32();
- if (parcel->errorCheck()) {
- return NULL;
- }
-
- Behavior* behavior = new Behavior();
- behavior->metaState = metaState;
- behavior->character = character;
- behavior->fallbackKeyCode = fallbackKeyCode;
- if (lastBehavior) {
- lastBehavior->next = behavior;
- } else {
- key->firstBehavior = behavior;
- }
- lastBehavior = behavior;
- }
-
- if (parcel->errorCheck()) {
- return NULL;
- }
- }
- return map;
-}
-
-void KeyCharacterMap::writeToParcel(Parcel* parcel) const {
- parcel->writeInt32(mType);
-
- size_t numKeys = mKeys.size();
- parcel->writeInt32(numKeys);
- for (size_t i = 0; i < numKeys; i++) {
- int32_t keyCode = mKeys.keyAt(i);
- const Key* key = mKeys.valueAt(i);
- parcel->writeInt32(keyCode);
- parcel->writeInt32(key->label);
- parcel->writeInt32(key->number);
- for (const Behavior* behavior = key->firstBehavior; behavior != NULL;
- behavior = behavior->next) {
- parcel->writeInt32(1);
- parcel->writeInt32(behavior->metaState);
- parcel->writeInt32(behavior->character);
- parcel->writeInt32(behavior->fallbackKeyCode);
- }
- parcel->writeInt32(0);
- }
-}
-#endif
-
-
-// --- KeyCharacterMap::Key ---
-
-KeyCharacterMap::Key::Key() :
- label(0), number(0), firstBehavior(NULL) {
-}
-
-KeyCharacterMap::Key::Key(const Key& other) :
- label(other.label), number(other.number),
- firstBehavior(other.firstBehavior ? new Behavior(*other.firstBehavior) : NULL) {
-}
-
-KeyCharacterMap::Key::~Key() {
- Behavior* behavior = firstBehavior;
- while (behavior) {
- Behavior* next = behavior->next;
- delete behavior;
- behavior = next;
- }
-}
-
-
-// --- KeyCharacterMap::Behavior ---
-
-KeyCharacterMap::Behavior::Behavior() :
- next(NULL), metaState(0), character(0), fallbackKeyCode(0) {
-}
-
-KeyCharacterMap::Behavior::Behavior(const Behavior& other) :
- next(other.next ? new Behavior(*other.next) : NULL),
- metaState(other.metaState), character(other.character),
- fallbackKeyCode(other.fallbackKeyCode) {
-}
-
-
-// --- KeyCharacterMap::Parser ---
-
-KeyCharacterMap::Parser::Parser(KeyCharacterMap* map, Tokenizer* tokenizer, Format format) :
- mMap(map), mTokenizer(tokenizer), mFormat(format), mState(STATE_TOP) {
-}
-
-KeyCharacterMap::Parser::~Parser() {
-}
-
-status_t KeyCharacterMap::Parser::parse() {
- while (!mTokenizer->isEof()) {
-#if DEBUG_PARSER
- ALOGD("Parsing %s: '%s'.", mTokenizer->getLocation().string(),
- mTokenizer->peekRemainderOfLine().string());
-#endif
-
- mTokenizer->skipDelimiters(WHITESPACE);
-
- if (!mTokenizer->isEol() && mTokenizer->peekChar() != '#') {
- switch (mState) {
- case STATE_TOP: {
- String8 keywordToken = mTokenizer->nextToken(WHITESPACE);
- if (keywordToken == "type") {
- mTokenizer->skipDelimiters(WHITESPACE);
- status_t status = parseType();
- if (status) return status;
- } else if (keywordToken == "map") {
- mTokenizer->skipDelimiters(WHITESPACE);
- status_t status = parseMap();
- if (status) return status;
- } else if (keywordToken == "key") {
- mTokenizer->skipDelimiters(WHITESPACE);
- status_t status = parseKey();
- if (status) return status;
- } else {
- ALOGE("%s: Expected keyword, got '%s'.", mTokenizer->getLocation().string(),
- keywordToken.string());
- return BAD_VALUE;
- }
- break;
- }
-
- case STATE_KEY: {
- status_t status = parseKeyProperty();
- if (status) return status;
- break;
- }
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- if (!mTokenizer->isEol() && mTokenizer->peekChar() != '#') {
- ALOGE("%s: Expected end of line or trailing comment, got '%s'.",
- mTokenizer->getLocation().string(),
- mTokenizer->peekRemainderOfLine().string());
- return BAD_VALUE;
- }
- }
-
- mTokenizer->nextLine();
- }
-
- if (mState != STATE_TOP) {
- ALOGE("%s: Unterminated key description at end of file.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
-
- if (mMap->mType == KEYBOARD_TYPE_UNKNOWN) {
- ALOGE("%s: Keyboard layout missing required keyboard 'type' declaration.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
-
- if (mFormat == FORMAT_BASE) {
- if (mMap->mType == KEYBOARD_TYPE_OVERLAY) {
- ALOGE("%s: Base keyboard layout must specify a keyboard 'type' other than 'OVERLAY'.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- } else if (mFormat == FORMAT_OVERLAY) {
- if (mMap->mType != KEYBOARD_TYPE_OVERLAY) {
- ALOGE("%s: Overlay keyboard layout missing required keyboard "
- "'type OVERLAY' declaration.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- }
-
- return NO_ERROR;
-}
-
-status_t KeyCharacterMap::Parser::parseType() {
- if (mMap->mType != KEYBOARD_TYPE_UNKNOWN) {
- ALOGE("%s: Duplicate keyboard 'type' declaration.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
-
- KeyboardType type;
- String8 typeToken = mTokenizer->nextToken(WHITESPACE);
- if (typeToken == "NUMERIC") {
- type = KEYBOARD_TYPE_NUMERIC;
- } else if (typeToken == "PREDICTIVE") {
- type = KEYBOARD_TYPE_PREDICTIVE;
- } else if (typeToken == "ALPHA") {
- type = KEYBOARD_TYPE_ALPHA;
- } else if (typeToken == "FULL") {
- type = KEYBOARD_TYPE_FULL;
- } else if (typeToken == "SPECIAL_FUNCTION") {
- type = KEYBOARD_TYPE_SPECIAL_FUNCTION;
- } else if (typeToken == "OVERLAY") {
- type = KEYBOARD_TYPE_OVERLAY;
- } else {
- ALOGE("%s: Expected keyboard type label, got '%s'.", mTokenizer->getLocation().string(),
- typeToken.string());
- return BAD_VALUE;
- }
-
-#if DEBUG_PARSER
- ALOGD("Parsed type: type=%d.", type);
-#endif
- mMap->mType = type;
- return NO_ERROR;
-}
-
-status_t KeyCharacterMap::Parser::parseMap() {
- String8 keywordToken = mTokenizer->nextToken(WHITESPACE);
- if (keywordToken == "key") {
- mTokenizer->skipDelimiters(WHITESPACE);
- return parseMapKey();
- }
- ALOGE("%s: Expected keyword after 'map', got '%s'.", mTokenizer->getLocation().string(),
- keywordToken.string());
- return BAD_VALUE;
-}
-
-status_t KeyCharacterMap::Parser::parseMapKey() {
- String8 codeToken = mTokenizer->nextToken(WHITESPACE);
- bool mapUsage = false;
- if (codeToken == "usage") {
- mapUsage = true;
- mTokenizer->skipDelimiters(WHITESPACE);
- codeToken = mTokenizer->nextToken(WHITESPACE);
- }
-
- char* end;
- int32_t code = int32_t(strtol(codeToken.string(), &end, 0));
- if (*end) {
- ALOGE("%s: Expected key %s number, got '%s'.", mTokenizer->getLocation().string(),
- mapUsage ? "usage" : "scan code", codeToken.string());
- return BAD_VALUE;
- }
- KeyedVector<int32_t, int32_t>& map =
- mapUsage ? mMap->mKeysByUsageCode : mMap->mKeysByScanCode;
- if (map.indexOfKey(code) >= 0) {
- ALOGE("%s: Duplicate entry for key %s '%s'.", mTokenizer->getLocation().string(),
- mapUsage ? "usage" : "scan code", codeToken.string());
- return BAD_VALUE;
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 keyCodeToken = mTokenizer->nextToken(WHITESPACE);
- int32_t keyCode = getKeyCodeByLabel(keyCodeToken.string());
- if (!keyCode) {
- ALOGE("%s: Expected key code label, got '%s'.", mTokenizer->getLocation().string(),
- keyCodeToken.string());
- return BAD_VALUE;
- }
-
-#if DEBUG_PARSER
- ALOGD("Parsed map key %s: code=%d, keyCode=%d.",
- mapUsage ? "usage" : "scan code", code, keyCode);
-#endif
- map.add(code, keyCode);
- return NO_ERROR;
-}
-
-status_t KeyCharacterMap::Parser::parseKey() {
- String8 keyCodeToken = mTokenizer->nextToken(WHITESPACE);
- int32_t keyCode = getKeyCodeByLabel(keyCodeToken.string());
- if (!keyCode) {
- ALOGE("%s: Expected key code label, got '%s'.", mTokenizer->getLocation().string(),
- keyCodeToken.string());
- return BAD_VALUE;
- }
- if (mMap->mKeys.indexOfKey(keyCode) >= 0) {
- ALOGE("%s: Duplicate entry for key code '%s'.", mTokenizer->getLocation().string(),
- keyCodeToken.string());
- return BAD_VALUE;
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 openBraceToken = mTokenizer->nextToken(WHITESPACE);
- if (openBraceToken != "{") {
- ALOGE("%s: Expected '{' after key code label, got '%s'.",
- mTokenizer->getLocation().string(), openBraceToken.string());
- return BAD_VALUE;
- }
-
-#if DEBUG_PARSER
- ALOGD("Parsed beginning of key: keyCode=%d.", keyCode);
-#endif
- mKeyCode = keyCode;
- mMap->mKeys.add(keyCode, new Key());
- mState = STATE_KEY;
- return NO_ERROR;
-}
-
-status_t KeyCharacterMap::Parser::parseKeyProperty() {
- Key* key = mMap->mKeys.valueFor(mKeyCode);
- String8 token = mTokenizer->nextToken(WHITESPACE_OR_PROPERTY_DELIMITER);
- if (token == "}") {
- mState = STATE_TOP;
- return finishKey(key);
- }
-
- Vector<Property> properties;
-
- // Parse all comma-delimited property names up to the first colon.
- for (;;) {
- if (token == "label") {
- properties.add(Property(PROPERTY_LABEL));
- } else if (token == "number") {
- properties.add(Property(PROPERTY_NUMBER));
- } else {
- int32_t metaState;
- status_t status = parseModifier(token, &metaState);
- if (status) {
- ALOGE("%s: Expected a property name or modifier, got '%s'.",
- mTokenizer->getLocation().string(), token.string());
- return status;
- }
- properties.add(Property(PROPERTY_META, metaState));
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- if (!mTokenizer->isEol()) {
- char ch = mTokenizer->nextChar();
- if (ch == ':') {
- break;
- } else if (ch == ',') {
- mTokenizer->skipDelimiters(WHITESPACE);
- token = mTokenizer->nextToken(WHITESPACE_OR_PROPERTY_DELIMITER);
- continue;
- }
- }
-
- ALOGE("%s: Expected ',' or ':' after property name.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
-
- // Parse behavior after the colon.
- mTokenizer->skipDelimiters(WHITESPACE);
-
- Behavior behavior;
- bool haveCharacter = false;
- bool haveFallback = false;
-
- do {
- char ch = mTokenizer->peekChar();
- if (ch == '\'') {
- char16_t character;
- status_t status = parseCharacterLiteral(&character);
- if (status || !character) {
- ALOGE("%s: Invalid character literal for key.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- if (haveCharacter) {
- ALOGE("%s: Cannot combine multiple character literals or 'none'.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- behavior.character = character;
- haveCharacter = true;
- } else {
- token = mTokenizer->nextToken(WHITESPACE);
- if (token == "none") {
- if (haveCharacter) {
- ALOGE("%s: Cannot combine multiple character literals or 'none'.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- haveCharacter = true;
- } else if (token == "fallback") {
- mTokenizer->skipDelimiters(WHITESPACE);
- token = mTokenizer->nextToken(WHITESPACE);
- int32_t keyCode = getKeyCodeByLabel(token.string());
- if (!keyCode) {
- ALOGE("%s: Invalid key code label for fallback behavior, got '%s'.",
- mTokenizer->getLocation().string(),
- token.string());
- return BAD_VALUE;
- }
- if (haveFallback) {
- ALOGE("%s: Cannot combine multiple fallback key codes.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- behavior.fallbackKeyCode = keyCode;
- haveFallback = true;
- } else {
- ALOGE("%s: Expected a key behavior after ':'.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- } while (!mTokenizer->isEol() && mTokenizer->peekChar() != '#');
-
- // Add the behavior.
- for (size_t i = 0; i < properties.size(); i++) {
- const Property& property = properties.itemAt(i);
- switch (property.property) {
- case PROPERTY_LABEL:
- if (key->label) {
- ALOGE("%s: Duplicate label for key.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- key->label = behavior.character;
-#if DEBUG_PARSER
- ALOGD("Parsed key label: keyCode=%d, label=%d.", mKeyCode, key->label);
-#endif
- break;
- case PROPERTY_NUMBER:
- if (key->number) {
- ALOGE("%s: Duplicate number for key.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- key->number = behavior.character;
-#if DEBUG_PARSER
- ALOGD("Parsed key number: keyCode=%d, number=%d.", mKeyCode, key->number);
-#endif
- break;
- case PROPERTY_META: {
- for (Behavior* b = key->firstBehavior; b; b = b->next) {
- if (b->metaState == property.metaState) {
- ALOGE("%s: Duplicate key behavior for modifier.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
- }
- Behavior* newBehavior = new Behavior(behavior);
- newBehavior->metaState = property.metaState;
- newBehavior->next = key->firstBehavior;
- key->firstBehavior = newBehavior;
-#if DEBUG_PARSER
- ALOGD("Parsed key meta: keyCode=%d, meta=0x%x, char=%d, fallback=%d.", mKeyCode,
- newBehavior->metaState, newBehavior->character, newBehavior->fallbackKeyCode);
-#endif
- break;
- }
- }
- }
- return NO_ERROR;
-}
-
-status_t KeyCharacterMap::Parser::finishKey(Key* key) {
- // Fill in default number property.
- if (!key->number) {
- char16_t digit = 0;
- char16_t symbol = 0;
- for (Behavior* b = key->firstBehavior; b; b = b->next) {
- char16_t ch = b->character;
- if (ch) {
- if (ch >= '0' && ch <= '9') {
- digit = ch;
- } else if (ch == '(' || ch == ')' || ch == '#' || ch == '*'
- || ch == '-' || ch == '+' || ch == ',' || ch == '.'
- || ch == '\'' || ch == ':' || ch == ';' || ch == '/') {
- symbol = ch;
- }
- }
- }
- key->number = digit ? digit : symbol;
- }
- return NO_ERROR;
-}
-
-status_t KeyCharacterMap::Parser::parseModifier(const String8& token, int32_t* outMetaState) {
- if (token == "base") {
- *outMetaState = 0;
- return NO_ERROR;
- }
-
- int32_t combinedMeta = 0;
-
- const char* str = token.string();
- const char* start = str;
- for (const char* cur = str; ; cur++) {
- char ch = *cur;
- if (ch == '+' || ch == '\0') {
- size_t len = cur - start;
- int32_t metaState = 0;
- for (size_t i = 0; i < sizeof(modifiers) / sizeof(Modifier); i++) {
- if (strlen(modifiers[i].label) == len
- && strncmp(modifiers[i].label, start, len) == 0) {
- metaState = modifiers[i].metaState;
- break;
- }
- }
- if (!metaState) {
- return BAD_VALUE;
- }
- if (combinedMeta & metaState) {
- ALOGE("%s: Duplicate modifier combination '%s'.",
- mTokenizer->getLocation().string(), token.string());
- return BAD_VALUE;
- }
-
- combinedMeta |= metaState;
- start = cur + 1;
-
- if (ch == '\0') {
- break;
- }
- }
- }
- *outMetaState = combinedMeta;
- return NO_ERROR;
-}
-
-status_t KeyCharacterMap::Parser::parseCharacterLiteral(char16_t* outCharacter) {
- char ch = mTokenizer->nextChar();
- if (ch != '\'') {
- goto Error;
- }
-
- ch = mTokenizer->nextChar();
- if (ch == '\\') {
- // Escape sequence.
- ch = mTokenizer->nextChar();
- if (ch == 'n') {
- *outCharacter = '\n';
- } else if (ch == 't') {
- *outCharacter = '\t';
- } else if (ch == '\\') {
- *outCharacter = '\\';
- } else if (ch == '\'') {
- *outCharacter = '\'';
- } else if (ch == '"') {
- *outCharacter = '"';
- } else if (ch == 'u') {
- *outCharacter = 0;
- for (int i = 0; i < 4; i++) {
- ch = mTokenizer->nextChar();
- int digit;
- if (ch >= '0' && ch <= '9') {
- digit = ch - '0';
- } else if (ch >= 'A' && ch <= 'F') {
- digit = ch - 'A' + 10;
- } else if (ch >= 'a' && ch <= 'f') {
- digit = ch - 'a' + 10;
- } else {
- goto Error;
- }
- *outCharacter = (*outCharacter << 4) | digit;
- }
- } else {
- goto Error;
- }
- } else if (ch >= 32 && ch <= 126 && ch != '\'') {
- // ASCII literal character.
- *outCharacter = ch;
- } else {
- goto Error;
- }
-
- ch = mTokenizer->nextChar();
- if (ch != '\'') {
- goto Error;
- }
-
- // Ensure that we consumed the entire token.
- if (mTokenizer->nextToken(WHITESPACE).isEmpty()) {
- return NO_ERROR;
- }
-
-Error:
- ALOGE("%s: Malformed character literal.", mTokenizer->getLocation().string());
- return BAD_VALUE;
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/KeyCharacterMap.h b/widget/gonk/libui/KeyCharacterMap.h
deleted file mode 100644
index c7a684105..000000000
--- a/widget/gonk/libui/KeyCharacterMap.h
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_KEY_CHARACTER_MAP_H
-#define _ANDROIDFW_KEY_CHARACTER_MAP_H
-
-#include <stdint.h>
-
-#if HAVE_ANDROID_OS
-#include <binder/IBinder.h>
-#endif
-
-#include "Input.h"
-#include <utils/Errors.h>
-#include <utils/KeyedVector.h>
-#include "Tokenizer.h"
-#include <utils/String8.h>
-#include <utils/Unicode.h>
-#include <utils/RefBase.h>
-
-namespace android {
-
-/**
- * Describes a mapping from Android key codes to characters.
- * Also specifies other functions of the keyboard such as the keyboard type
- * and key modifier semantics.
- *
- * This object is immutable after it has been loaded.
- */
-class KeyCharacterMap : public RefBase {
-public:
- enum KeyboardType {
- KEYBOARD_TYPE_UNKNOWN = 0,
- KEYBOARD_TYPE_NUMERIC = 1,
- KEYBOARD_TYPE_PREDICTIVE = 2,
- KEYBOARD_TYPE_ALPHA = 3,
- KEYBOARD_TYPE_FULL = 4,
- KEYBOARD_TYPE_SPECIAL_FUNCTION = 5,
- KEYBOARD_TYPE_OVERLAY = 6,
- };
-
- enum Format {
- // Base keyboard layout, may contain device-specific options, such as "type" declaration.
- FORMAT_BASE = 0,
- // Overlay keyboard layout, more restrictive, may be published by applications,
- // cannot override device-specific options.
- FORMAT_OVERLAY = 1,
- // Either base or overlay layout ok.
- FORMAT_ANY = 2,
- };
-
- // Substitute key code and meta state for fallback action.
- struct FallbackAction {
- int32_t keyCode;
- int32_t metaState;
- };
-
- /* Loads a key character map from a file. */
- static status_t load(const String8& filename, Format format, sp<KeyCharacterMap>* outMap);
-
- /* Loads a key character map from its string contents. */
- static status_t loadContents(const String8& filename,
- const char* contents, Format format, sp<KeyCharacterMap>* outMap);
-
- /* Combines a base key character map and an overlay. */
- static sp<KeyCharacterMap> combine(const sp<KeyCharacterMap>& base,
- const sp<KeyCharacterMap>& overlay);
-
- /* Returns an empty key character map. */
- static sp<KeyCharacterMap> empty();
-
- /* Gets the keyboard type. */
- int32_t getKeyboardType() const;
-
- /* Gets the primary character for this key as in the label physically printed on it.
- * Returns 0 if none (eg. for non-printing keys). */
- char16_t getDisplayLabel(int32_t keyCode) const;
-
- /* Gets the Unicode character for the number or symbol generated by the key
- * when the keyboard is used as a dialing pad.
- * Returns 0 if no number or symbol is generated.
- */
- char16_t getNumber(int32_t keyCode) const;
-
- /* Gets the Unicode character generated by the key and meta key modifiers.
- * Returns 0 if no character is generated.
- */
- char16_t getCharacter(int32_t keyCode, int32_t metaState) const;
-
- /* Gets the fallback action to use by default if the application does not
- * handle the specified key.
- * Returns true if an action was available, false if none.
- */
- bool getFallbackAction(int32_t keyCode, int32_t metaState,
- FallbackAction* outFallbackAction) const;
-
- /* Gets the first matching Unicode character that can be generated by the key,
- * preferring the one with the specified meta key modifiers.
- * Returns 0 if no matching character is generated.
- */
- char16_t getMatch(int32_t keyCode, const char16_t* chars,
- size_t numChars, int32_t metaState) const;
-
- /* Gets a sequence of key events that could plausibly generate the specified
- * character sequence. Returns false if some of the characters cannot be generated.
- */
- bool getEvents(int32_t deviceId, const char16_t* chars, size_t numChars,
- Vector<KeyEvent>& outEvents) const;
-
- /* Maps a scan code and usage code to a key code, in case this key map overrides
- * the mapping in some way. */
- status_t mapKey(int32_t scanCode, int32_t usageCode, int32_t* outKeyCode) const;
-
-#if HAVE_ANDROID_OS
- /* Reads a key map from a parcel. */
- static sp<KeyCharacterMap> readFromParcel(Parcel* parcel);
-
- /* Writes a key map to a parcel. */
- void writeToParcel(Parcel* parcel) const;
-#endif
-
-protected:
- virtual ~KeyCharacterMap();
-
-private:
- struct Behavior {
- Behavior();
- Behavior(const Behavior& other);
-
- /* The next behavior in the list, or NULL if none. */
- Behavior* next;
-
- /* The meta key modifiers for this behavior. */
- int32_t metaState;
-
- /* The character to insert. */
- char16_t character;
-
- /* The fallback keycode if the key is not handled. */
- int32_t fallbackKeyCode;
- };
-
- struct Key {
- Key();
- Key(const Key& other);
- ~Key();
-
- /* The single character label printed on the key, or 0 if none. */
- char16_t label;
-
- /* The number or symbol character generated by the key, or 0 if none. */
- char16_t number;
-
- /* The list of key behaviors sorted from most specific to least specific
- * meta key binding. */
- Behavior* firstBehavior;
- };
-
- class Parser {
- enum State {
- STATE_TOP = 0,
- STATE_KEY = 1,
- };
-
- enum {
- PROPERTY_LABEL = 1,
- PROPERTY_NUMBER = 2,
- PROPERTY_META = 3,
- };
-
- struct Property {
- inline Property(int32_t property = 0, int32_t metaState = 0) :
- property(property), metaState(metaState) { }
-
- int32_t property;
- int32_t metaState;
- };
-
- KeyCharacterMap* mMap;
- Tokenizer* mTokenizer;
- Format mFormat;
- State mState;
- int32_t mKeyCode;
-
- public:
- Parser(KeyCharacterMap* map, Tokenizer* tokenizer, Format format);
- ~Parser();
- status_t parse();
-
- private:
- status_t parseType();
- status_t parseMap();
- status_t parseMapKey();
- status_t parseKey();
- status_t parseKeyProperty();
- status_t finishKey(Key* key);
- status_t parseModifier(const String8& token, int32_t* outMetaState);
- status_t parseCharacterLiteral(char16_t* outCharacter);
- };
-
- static sp<KeyCharacterMap> sEmpty;
-
- KeyedVector<int32_t, Key*> mKeys;
- int mType;
-
- KeyedVector<int32_t, int32_t> mKeysByScanCode;
- KeyedVector<int32_t, int32_t> mKeysByUsageCode;
-
- KeyCharacterMap();
- KeyCharacterMap(const KeyCharacterMap& other);
-
- bool getKey(int32_t keyCode, const Key** outKey) const;
- bool getKeyBehavior(int32_t keyCode, int32_t metaState,
- const Key** outKey, const Behavior** outBehavior) const;
- static bool matchesMetaState(int32_t eventMetaState, int32_t behaviorMetaState);
-
- bool findKey(char16_t ch, int32_t* outKeyCode, int32_t* outMetaState) const;
-
- static status_t load(Tokenizer* tokenizer, Format format, sp<KeyCharacterMap>* outMap);
-
- static void addKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t keyCode, int32_t metaState, bool down, nsecs_t time);
- static void addMetaKeys(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t* currentMetaState);
- static bool addSingleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t keyCode, int32_t keyMetaState,
- int32_t* currentMetaState);
- static void addDoubleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
- int32_t leftKeyCode, int32_t leftKeyMetaState,
- int32_t rightKeyCode, int32_t rightKeyMetaState,
- int32_t eitherKeyMetaState,
- int32_t* currentMetaState);
- static void addLockedMetaKey(Vector<KeyEvent>& outEvents,
- int32_t deviceId, int32_t metaState, nsecs_t time,
- int32_t keyCode, int32_t keyMetaState,
- int32_t* currentMetaState);
-};
-
-} // namespace android
-
-#endif // _ANDROIDFW_KEY_CHARACTER_MAP_H
diff --git a/widget/gonk/libui/KeyLayoutMap.cpp b/widget/gonk/libui/KeyLayoutMap.cpp
deleted file mode 100644
index 8af4b84e0..000000000
--- a/widget/gonk/libui/KeyLayoutMap.cpp
+++ /dev/null
@@ -1,446 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "KeyLayoutMap"
-#include "cutils_log.h"
-
-#include <stdlib.h>
-#include "android_keycodes.h"
-#include "Keyboard.h"
-#include "KeyLayoutMap.h"
-#include <utils/Errors.h>
-#include "Tokenizer.h"
-#include <utils/Timers.h>
-
-// Enables debug output for the parser.
-#define DEBUG_PARSER 0
-
-// Enables debug output for parser performance.
-#define DEBUG_PARSER_PERFORMANCE 0
-
-// Enables debug output for mapping.
-#define DEBUG_MAPPING 0
-
-
-namespace android {
-
-static const char* WHITESPACE = " \t\r";
-
-// --- KeyLayoutMap ---
-
-KeyLayoutMap::KeyLayoutMap() {
-}
-
-KeyLayoutMap::~KeyLayoutMap() {
-}
-
-status_t KeyLayoutMap::load(const String8& filename, sp<KeyLayoutMap>* outMap) {
- outMap->clear();
-
- Tokenizer* tokenizer;
- status_t status = Tokenizer::open(filename, &tokenizer);
- if (status) {
- ALOGE("Error %d opening key layout map file %s.", status, filename.string());
- } else {
- sp<KeyLayoutMap> map = new KeyLayoutMap();
- if (!map.get()) {
- ALOGE("Error allocating key layout map.");
- status = NO_MEMORY;
- } else {
-#if DEBUG_PARSER_PERFORMANCE
- nsecs_t startTime = systemTime(SYSTEM_TIME_MONOTONIC);
-#endif
- Parser parser(map.get(), tokenizer);
- status = parser.parse();
-#if DEBUG_PARSER_PERFORMANCE
- nsecs_t elapsedTime = systemTime(SYSTEM_TIME_MONOTONIC) - startTime;
- ALOGD("Parsed key layout map file '%s' %d lines in %0.3fms.",
- tokenizer->getFilename().string(), tokenizer->getLineNumber(),
- elapsedTime / 1000000.0);
-#endif
- if (!status) {
- *outMap = map;
- }
- }
- delete tokenizer;
- }
- return status;
-}
-
-status_t KeyLayoutMap::mapKey(int32_t scanCode, int32_t usageCode,
- int32_t* outKeyCode, uint32_t* outFlags) const {
- const Key* key = getKey(scanCode, usageCode);
- if (!key) {
-#if DEBUG_MAPPING
- ALOGD("mapKey: scanCode=%d, usageCode=0x%08x ~ Failed.", scanCode, usageCode);
-#endif
- *outKeyCode = AKEYCODE_UNKNOWN;
- *outFlags = 0;
- return NAME_NOT_FOUND;
- }
-
- *outKeyCode = key->keyCode;
- *outFlags = key->flags;
-
-#if DEBUG_MAPPING
- ALOGD("mapKey: scanCode=%d, usageCode=0x%08x ~ Result keyCode=%d, outFlags=0x%08x.",
- scanCode, usageCode, *outKeyCode, *outFlags);
-#endif
- return NO_ERROR;
-}
-
-const KeyLayoutMap::Key* KeyLayoutMap::getKey(int32_t scanCode, int32_t usageCode) const {
- if (usageCode) {
- ssize_t index = mKeysByUsageCode.indexOfKey(usageCode);
- if (index >= 0) {
- return &mKeysByUsageCode.valueAt(index);
- }
- }
- if (scanCode) {
- ssize_t index = mKeysByScanCode.indexOfKey(scanCode);
- if (index >= 0) {
- return &mKeysByScanCode.valueAt(index);
- }
- }
- return NULL;
-}
-
-status_t KeyLayoutMap::findScanCodesForKey(int32_t keyCode, Vector<int32_t>* outScanCodes) const {
- const size_t N = mKeysByScanCode.size();
- for (size_t i=0; i<N; i++) {
- if (mKeysByScanCode.valueAt(i).keyCode == keyCode) {
- outScanCodes->add(mKeysByScanCode.keyAt(i));
- }
- }
- return NO_ERROR;
-}
-
-status_t KeyLayoutMap::mapAxis(int32_t scanCode, AxisInfo* outAxisInfo) const {
- ssize_t index = mAxes.indexOfKey(scanCode);
- if (index < 0) {
-#if DEBUG_MAPPING
- ALOGD("mapAxis: scanCode=%d ~ Failed.", scanCode);
-#endif
- return NAME_NOT_FOUND;
- }
-
- *outAxisInfo = mAxes.valueAt(index);
-
-#if DEBUG_MAPPING
- ALOGD("mapAxis: scanCode=%d ~ Result mode=%d, axis=%d, highAxis=%d, "
- "splitValue=%d, flatOverride=%d.",
- scanCode,
- outAxisInfo->mode, outAxisInfo->axis, outAxisInfo->highAxis,
- outAxisInfo->splitValue, outAxisInfo->flatOverride);
-#endif
- return NO_ERROR;
-}
-
-status_t KeyLayoutMap::findScanCodeForLed(int32_t ledCode, int32_t* outScanCode) const {
- const size_t N = mLedsByScanCode.size();
- for (size_t i = 0; i < N; i++) {
- if (mLedsByScanCode.valueAt(i).ledCode == ledCode) {
- *outScanCode = mLedsByScanCode.keyAt(i);
-#if DEBUG_MAPPING
- ALOGD("findScanCodeForLed: ledCode=%d, scanCode=%d.", ledCode, *outScanCode);
-#endif
- return NO_ERROR;
- }
- }
-#if DEBUG_MAPPING
- ALOGD("findScanCodeForLed: ledCode=%d ~ Not found.", ledCode);
-#endif
- return NAME_NOT_FOUND;
-}
-
-status_t KeyLayoutMap::findUsageCodeForLed(int32_t ledCode, int32_t* outUsageCode) const {
- const size_t N = mLedsByUsageCode.size();
- for (size_t i = 0; i < N; i++) {
- if (mLedsByUsageCode.valueAt(i).ledCode == ledCode) {
- *outUsageCode = mLedsByUsageCode.keyAt(i);
-#if DEBUG_MAPPING
- ALOGD("findUsageForLed: ledCode=%d, usage=%x.", ledCode, *outUsageCode);
-#endif
- return NO_ERROR;
- }
- }
-#if DEBUG_MAPPING
- ALOGD("findUsageForLed: ledCode=%d ~ Not found.", ledCode);
-#endif
- return NAME_NOT_FOUND;
-}
-
-
-// --- KeyLayoutMap::Parser ---
-
-KeyLayoutMap::Parser::Parser(KeyLayoutMap* map, Tokenizer* tokenizer) :
- mMap(map), mTokenizer(tokenizer) {
-}
-
-KeyLayoutMap::Parser::~Parser() {
-}
-
-status_t KeyLayoutMap::Parser::parse() {
- while (!mTokenizer->isEof()) {
-#if DEBUG_PARSER
- ALOGD("Parsing %s: '%s'.", mTokenizer->getLocation().string(),
- mTokenizer->peekRemainderOfLine().string());
-#endif
-
- mTokenizer->skipDelimiters(WHITESPACE);
-
- if (!mTokenizer->isEol() && mTokenizer->peekChar() != '#') {
- String8 keywordToken = mTokenizer->nextToken(WHITESPACE);
- if (keywordToken == "key") {
- mTokenizer->skipDelimiters(WHITESPACE);
- status_t status = parseKey();
- if (status) return status;
- } else if (keywordToken == "axis") {
- mTokenizer->skipDelimiters(WHITESPACE);
- status_t status = parseAxis();
- if (status) return status;
- } else if (keywordToken == "led") {
- mTokenizer->skipDelimiters(WHITESPACE);
- status_t status = parseLed();
- if (status) return status;
- } else {
- ALOGE("%s: Expected keyword, got '%s'.", mTokenizer->getLocation().string(),
- keywordToken.string());
- return BAD_VALUE;
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- if (!mTokenizer->isEol() && mTokenizer->peekChar() != '#') {
- ALOGE("%s: Expected end of line or trailing comment, got '%s'.",
- mTokenizer->getLocation().string(),
- mTokenizer->peekRemainderOfLine().string());
- return BAD_VALUE;
- }
- }
-
- mTokenizer->nextLine();
- }
- return NO_ERROR;
-}
-
-status_t KeyLayoutMap::Parser::parseKey() {
- String8 codeToken = mTokenizer->nextToken(WHITESPACE);
- bool mapUsage = false;
- if (codeToken == "usage") {
- mapUsage = true;
- mTokenizer->skipDelimiters(WHITESPACE);
- codeToken = mTokenizer->nextToken(WHITESPACE);
- }
-
- char* end;
- int32_t code = int32_t(strtol(codeToken.string(), &end, 0));
- if (*end) {
- ALOGE("%s: Expected key %s number, got '%s'.", mTokenizer->getLocation().string(),
- mapUsage ? "usage" : "scan code", codeToken.string());
- return BAD_VALUE;
- }
- KeyedVector<int32_t, Key>& map =
- mapUsage ? mMap->mKeysByUsageCode : mMap->mKeysByScanCode;
- if (map.indexOfKey(code) >= 0) {
- ALOGE("%s: Duplicate entry for key %s '%s'.", mTokenizer->getLocation().string(),
- mapUsage ? "usage" : "scan code", codeToken.string());
- return BAD_VALUE;
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 keyCodeToken = mTokenizer->nextToken(WHITESPACE);
- int32_t keyCode = getKeyCodeByLabel(keyCodeToken.string());
- if (!keyCode) {
- ALOGE("%s: Expected key code label, got '%s'.", mTokenizer->getLocation().string(),
- keyCodeToken.string());
- return BAD_VALUE;
- }
-
- uint32_t flags = 0;
- for (;;) {
- mTokenizer->skipDelimiters(WHITESPACE);
- if (mTokenizer->isEol() || mTokenizer->peekChar() == '#') break;
-
- String8 flagToken = mTokenizer->nextToken(WHITESPACE);
- uint32_t flag = getKeyFlagByLabel(flagToken.string());
- if (!flag) {
- ALOGE("%s: Expected key flag label, got '%s'.", mTokenizer->getLocation().string(),
- flagToken.string());
- return BAD_VALUE;
- }
- if (flags & flag) {
- ALOGE("%s: Duplicate key flag '%s'.", mTokenizer->getLocation().string(),
- flagToken.string());
- return BAD_VALUE;
- }
- flags |= flag;
- }
-
-#if DEBUG_PARSER
- ALOGD("Parsed key %s: code=%d, keyCode=%d, flags=0x%08x.",
- mapUsage ? "usage" : "scan code", code, keyCode, flags);
-#endif
- Key key;
- key.keyCode = keyCode;
- key.flags = flags;
- map.add(code, key);
- return NO_ERROR;
-}
-
-status_t KeyLayoutMap::Parser::parseAxis() {
- String8 scanCodeToken = mTokenizer->nextToken(WHITESPACE);
- char* end;
- int32_t scanCode = int32_t(strtol(scanCodeToken.string(), &end, 0));
- if (*end) {
- ALOGE("%s: Expected axis scan code number, got '%s'.", mTokenizer->getLocation().string(),
- scanCodeToken.string());
- return BAD_VALUE;
- }
- if (mMap->mAxes.indexOfKey(scanCode) >= 0) {
- ALOGE("%s: Duplicate entry for axis scan code '%s'.", mTokenizer->getLocation().string(),
- scanCodeToken.string());
- return BAD_VALUE;
- }
-
- AxisInfo axisInfo;
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 token = mTokenizer->nextToken(WHITESPACE);
- if (token == "invert") {
- axisInfo.mode = AxisInfo::MODE_INVERT;
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 axisToken = mTokenizer->nextToken(WHITESPACE);
- axisInfo.axis = getAxisByLabel(axisToken.string());
- if (axisInfo.axis < 0) {
- ALOGE("%s: Expected inverted axis label, got '%s'.",
- mTokenizer->getLocation().string(), axisToken.string());
- return BAD_VALUE;
- }
- } else if (token == "split") {
- axisInfo.mode = AxisInfo::MODE_SPLIT;
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 splitToken = mTokenizer->nextToken(WHITESPACE);
- axisInfo.splitValue = int32_t(strtol(splitToken.string(), &end, 0));
- if (*end) {
- ALOGE("%s: Expected split value, got '%s'.",
- mTokenizer->getLocation().string(), splitToken.string());
- return BAD_VALUE;
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 lowAxisToken = mTokenizer->nextToken(WHITESPACE);
- axisInfo.axis = getAxisByLabel(lowAxisToken.string());
- if (axisInfo.axis < 0) {
- ALOGE("%s: Expected low axis label, got '%s'.",
- mTokenizer->getLocation().string(), lowAxisToken.string());
- return BAD_VALUE;
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 highAxisToken = mTokenizer->nextToken(WHITESPACE);
- axisInfo.highAxis = getAxisByLabel(highAxisToken.string());
- if (axisInfo.highAxis < 0) {
- ALOGE("%s: Expected high axis label, got '%s'.",
- mTokenizer->getLocation().string(), highAxisToken.string());
- return BAD_VALUE;
- }
- } else {
- axisInfo.axis = getAxisByLabel(token.string());
- if (axisInfo.axis < 0) {
- ALOGE("%s: Expected axis label, 'split' or 'invert', got '%s'.",
- mTokenizer->getLocation().string(), token.string());
- return BAD_VALUE;
- }
- }
-
- for (;;) {
- mTokenizer->skipDelimiters(WHITESPACE);
- if (mTokenizer->isEol() || mTokenizer->peekChar() == '#') {
- break;
- }
- String8 keywordToken = mTokenizer->nextToken(WHITESPACE);
- if (keywordToken == "flat") {
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 flatToken = mTokenizer->nextToken(WHITESPACE);
- axisInfo.flatOverride = int32_t(strtol(flatToken.string(), &end, 0));
- if (*end) {
- ALOGE("%s: Expected flat value, got '%s'.",
- mTokenizer->getLocation().string(), flatToken.string());
- return BAD_VALUE;
- }
- } else {
- ALOGE("%s: Expected keyword 'flat', got '%s'.",
- mTokenizer->getLocation().string(), keywordToken.string());
- return BAD_VALUE;
- }
- }
-
-#if DEBUG_PARSER
- ALOGD("Parsed axis: scanCode=%d, mode=%d, axis=%d, highAxis=%d, "
- "splitValue=%d, flatOverride=%d.",
- scanCode,
- axisInfo.mode, axisInfo.axis, axisInfo.highAxis,
- axisInfo.splitValue, axisInfo.flatOverride);
-#endif
- mMap->mAxes.add(scanCode, axisInfo);
- return NO_ERROR;
-}
-
-status_t KeyLayoutMap::Parser::parseLed() {
- String8 codeToken = mTokenizer->nextToken(WHITESPACE);
- bool mapUsage = false;
- if (codeToken == "usage") {
- mapUsage = true;
- mTokenizer->skipDelimiters(WHITESPACE);
- codeToken = mTokenizer->nextToken(WHITESPACE);
- }
- char* end;
- int32_t code = int32_t(strtol(codeToken.string(), &end, 0));
- if (*end) {
- ALOGE("%s: Expected led %s number, got '%s'.", mTokenizer->getLocation().string(),
- mapUsage ? "usage" : "scan code", codeToken.string());
- return BAD_VALUE;
- }
-
- KeyedVector<int32_t, Led>& map = mapUsage ? mMap->mLedsByUsageCode : mMap->mLedsByScanCode;
- if (map.indexOfKey(code) >= 0) {
- ALOGE("%s: Duplicate entry for led %s '%s'.", mTokenizer->getLocation().string(),
- mapUsage ? "usage" : "scan code", codeToken.string());
- return BAD_VALUE;
- }
-
- mTokenizer->skipDelimiters(WHITESPACE);
- String8 ledCodeToken = mTokenizer->nextToken(WHITESPACE);
- int32_t ledCode = getLedByLabel(ledCodeToken.string());
- if (ledCode < 0) {
- ALOGE("%s: Expected LED code label, got '%s'.", mTokenizer->getLocation().string(),
- ledCodeToken.string());
- return BAD_VALUE;
- }
-
-#if DEBUG_PARSER
- ALOGD("Parsed led %s: code=%d, ledCode=%d.",
- mapUsage ? "usage" : "scan code", code, ledCode);
-#endif
-
- Led led;
- led.ledCode = ledCode;
- map.add(code, led);
- return NO_ERROR;
-}
-};
diff --git a/widget/gonk/libui/KeyLayoutMap.h b/widget/gonk/libui/KeyLayoutMap.h
deleted file mode 100644
index 8a6113447..000000000
--- a/widget/gonk/libui/KeyLayoutMap.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_KEY_LAYOUT_MAP_H
-#define _ANDROIDFW_KEY_LAYOUT_MAP_H
-
-#include <stdint.h>
-#include <utils/Errors.h>
-#include <utils/KeyedVector.h>
-#include "Tokenizer.h"
-#include <utils/RefBase.h>
-
-namespace android {
-
-struct AxisInfo {
- enum Mode {
- // Axis value is reported directly.
- MODE_NORMAL = 0,
- // Axis value should be inverted before reporting.
- MODE_INVERT = 1,
- // Axis value should be split into two axes
- MODE_SPLIT = 2,
- };
-
- // Axis mode.
- Mode mode;
-
- // Axis id.
- // When split, this is the axis used for values smaller than the split position.
- int32_t axis;
-
- // When split, this is the axis used for values after higher than the split position.
- int32_t highAxis;
-
- // The split value, or 0 if not split.
- int32_t splitValue;
-
- // The flat value, or -1 if none.
- int32_t flatOverride;
-
- AxisInfo() : mode(MODE_NORMAL), axis(-1), highAxis(-1), splitValue(0), flatOverride(-1) {
- }
-};
-
-/**
- * Describes a mapping from keyboard scan codes and joystick axes to Android key codes and axes.
- *
- * This object is immutable after it has been loaded.
- */
-class KeyLayoutMap : public RefBase {
-public:
- static status_t load(const String8& filename, sp<KeyLayoutMap>* outMap);
-
- status_t mapKey(int32_t scanCode, int32_t usageCode,
- int32_t* outKeyCode, uint32_t* outFlags) const;
- status_t findScanCodesForKey(int32_t keyCode, Vector<int32_t>* outScanCodes) const;
- status_t findScanCodeForLed(int32_t ledCode, int32_t* outScanCode) const;
- status_t findUsageCodeForLed(int32_t ledCode, int32_t* outUsageCode) const;
-
- status_t mapAxis(int32_t scanCode, AxisInfo* outAxisInfo) const;
-
-protected:
- virtual ~KeyLayoutMap();
-
-private:
- struct Key {
- int32_t keyCode;
- uint32_t flags;
- };
-
- struct Led {
- int32_t ledCode;
- };
-
-
- KeyedVector<int32_t, Key> mKeysByScanCode;
- KeyedVector<int32_t, Key> mKeysByUsageCode;
- KeyedVector<int32_t, AxisInfo> mAxes;
- KeyedVector<int32_t, Led> mLedsByScanCode;
- KeyedVector<int32_t, Led> mLedsByUsageCode;
-
- KeyLayoutMap();
-
- const Key* getKey(int32_t scanCode, int32_t usageCode) const;
-
- class Parser {
- KeyLayoutMap* mMap;
- Tokenizer* mTokenizer;
-
- public:
- Parser(KeyLayoutMap* map, Tokenizer* tokenizer);
- ~Parser();
- status_t parse();
-
- private:
- status_t parseKey();
- status_t parseAxis();
- status_t parseLed();
- };
-};
-
-} // namespace android
-
-#endif // _ANDROIDFW_KEY_LAYOUT_MAP_H
diff --git a/widget/gonk/libui/Keyboard.cpp b/widget/gonk/libui/Keyboard.cpp
deleted file mode 100644
index 62bb53b7b..000000000
--- a/widget/gonk/libui/Keyboard.cpp
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "Keyboard"
-#include "cutils_log.h"
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <limits.h>
-
-#include "Keyboard.h"
-#include "KeycodeLabels.h"
-#include "KeyLayoutMap.h"
-#include "KeyCharacterMap.h"
-#include "InputDevice.h"
-#include <utils/Errors.h>
-#include <cutils/properties.h>
-
-namespace android {
-
-// --- KeyMap ---
-
-KeyMap::KeyMap() {
-}
-
-KeyMap::~KeyMap() {
-}
-
-status_t KeyMap::load(const InputDeviceIdentifier& deviceIdenfifier,
- const PropertyMap* deviceConfiguration) {
- // Use the configured key layout if available.
- if (deviceConfiguration) {
- String8 keyLayoutName;
- if (deviceConfiguration->tryGetProperty(String8("keyboard.layout"),
- keyLayoutName)) {
- status_t status = loadKeyLayout(deviceIdenfifier, keyLayoutName);
- if (status == NAME_NOT_FOUND) {
- ALOGE("Configuration for keyboard device '%s' requested keyboard layout '%s' but "
- "it was not found.",
- deviceIdenfifier.name.string(), keyLayoutName.string());
- }
- }
-
- String8 keyCharacterMapName;
- if (deviceConfiguration->tryGetProperty(String8("keyboard.characterMap"),
- keyCharacterMapName)) {
- status_t status = loadKeyCharacterMap(deviceIdenfifier, keyCharacterMapName);
- if (status == NAME_NOT_FOUND) {
- ALOGE("Configuration for keyboard device '%s' requested keyboard character "
- "map '%s' but it was not found.",
- deviceIdenfifier.name.string(), keyLayoutName.string());
- }
- }
-
- if (isComplete()) {
- return OK;
- }
- }
-
- // Try searching by device identifier.
- if (probeKeyMap(deviceIdenfifier, String8::empty())) {
- return OK;
- }
-
- // Fall back on the Generic key map.
- // TODO Apply some additional heuristics here to figure out what kind of
- // generic key map to use (US English, etc.) for typical external keyboards.
- if (probeKeyMap(deviceIdenfifier, String8("Generic"))) {
- return OK;
- }
-
- // Try the Virtual key map as a last resort.
- if (probeKeyMap(deviceIdenfifier, String8("Virtual"))) {
- return OK;
- }
-
- // Give up!
- ALOGE("Could not determine key map for device '%s' and no default key maps were found!",
- deviceIdenfifier.name.string());
- return NAME_NOT_FOUND;
-}
-
-bool KeyMap::probeKeyMap(const InputDeviceIdentifier& deviceIdentifier,
- const String8& keyMapName) {
- if (!haveKeyLayout()) {
- loadKeyLayout(deviceIdentifier, keyMapName);
- }
- if (!haveKeyCharacterMap()) {
- loadKeyCharacterMap(deviceIdentifier, keyMapName);
- }
- return isComplete();
-}
-
-status_t KeyMap::loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier,
- const String8& name) {
- String8 path(getPath(deviceIdentifier, name,
- INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_LAYOUT));
- if (path.isEmpty()) {
- return NAME_NOT_FOUND;
- }
-
- status_t status = KeyLayoutMap::load(path, &keyLayoutMap);
- if (status) {
- return status;
- }
-
- keyLayoutFile.setTo(path);
- return OK;
-}
-
-status_t KeyMap::loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifier,
- const String8& name) {
- String8 path(getPath(deviceIdentifier, name,
- INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_CHARACTER_MAP));
- if (path.isEmpty()) {
- return NAME_NOT_FOUND;
- }
-
- status_t status = KeyCharacterMap::load(path,
- KeyCharacterMap::FORMAT_BASE, &keyCharacterMap);
- if (status) {
- return status;
- }
-
- keyCharacterMapFile.setTo(path);
- return OK;
-}
-
-String8 KeyMap::getPath(const InputDeviceIdentifier& deviceIdentifier,
- const String8& name, InputDeviceConfigurationFileType type) {
- return name.isEmpty()
- ? getInputDeviceConfigurationFilePathByDeviceIdentifier(deviceIdentifier, type)
- : getInputDeviceConfigurationFilePathByName(name, type);
-}
-
-
-// --- Global functions ---
-
-bool isEligibleBuiltInKeyboard(const InputDeviceIdentifier& deviceIdentifier,
- const PropertyMap* deviceConfiguration, const KeyMap* keyMap) {
- if (!keyMap->haveKeyCharacterMap()
- || keyMap->keyCharacterMap->getKeyboardType()
- == KeyCharacterMap::KEYBOARD_TYPE_SPECIAL_FUNCTION) {
- return false;
- }
-
- if (deviceConfiguration) {
- bool builtIn = false;
- if (deviceConfiguration->tryGetProperty(String8("keyboard.builtIn"), builtIn)
- && builtIn) {
- return true;
- }
- }
-
- return strstr(deviceIdentifier.name.string(), "-keypad");
-}
-
-static int lookupValueByLabel(const char* literal, const KeycodeLabel *list) {
- while (list->literal) {
- if (strcmp(literal, list->literal) == 0) {
- return list->value;
- }
- list++;
- }
- return list->value;
-}
-
-static const char* lookupLabelByValue(int value, const KeycodeLabel *list) {
- while (list->literal) {
- if (list->value == value) {
- return list->literal;
- }
- list++;
- }
- return NULL;
-}
-
-int32_t getKeyCodeByLabel(const char* label) {
- return int32_t(lookupValueByLabel(label, KEYCODES));
-}
-
-uint32_t getKeyFlagByLabel(const char* label) {
- return uint32_t(lookupValueByLabel(label, FLAGS));
-}
-
-int32_t getAxisByLabel(const char* label) {
- return int32_t(lookupValueByLabel(label, AXES));
-}
-
-const char* getAxisLabel(int32_t axisId) {
- return lookupLabelByValue(axisId, AXES);
-}
-
-int32_t getLedByLabel(const char* label) {
- return int32_t(lookupValueByLabel(label, LEDS));
-}
-static int32_t setEphemeralMetaState(int32_t mask, bool down, int32_t oldMetaState) {
- int32_t newMetaState;
- if (down) {
- newMetaState = oldMetaState | mask;
- } else {
- newMetaState = oldMetaState &
- ~(mask | AMETA_ALT_ON | AMETA_SHIFT_ON | AMETA_CTRL_ON | AMETA_META_ON);
- }
-
- if (newMetaState & (AMETA_ALT_LEFT_ON | AMETA_ALT_RIGHT_ON)) {
- newMetaState |= AMETA_ALT_ON;
- }
-
- if (newMetaState & (AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_RIGHT_ON)) {
- newMetaState |= AMETA_SHIFT_ON;
- }
-
- if (newMetaState & (AMETA_CTRL_LEFT_ON | AMETA_CTRL_RIGHT_ON)) {
- newMetaState |= AMETA_CTRL_ON;
- }
-
- if (newMetaState & (AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON)) {
- newMetaState |= AMETA_META_ON;
- }
- return newMetaState;
-}
-
-static int32_t toggleLockedMetaState(int32_t mask, bool down, int32_t oldMetaState) {
- if (down) {
- return oldMetaState;
- } else {
- return oldMetaState ^ mask;
- }
-}
-
-int32_t updateMetaState(int32_t keyCode, bool down, int32_t oldMetaState) {
- switch (keyCode) {
- case AKEYCODE_ALT_LEFT:
- return setEphemeralMetaState(AMETA_ALT_LEFT_ON, down, oldMetaState);
- case AKEYCODE_ALT_RIGHT:
- return setEphemeralMetaState(AMETA_ALT_RIGHT_ON, down, oldMetaState);
- case AKEYCODE_SHIFT_LEFT:
- return setEphemeralMetaState(AMETA_SHIFT_LEFT_ON, down, oldMetaState);
- case AKEYCODE_SHIFT_RIGHT:
- return setEphemeralMetaState(AMETA_SHIFT_RIGHT_ON, down, oldMetaState);
- case AKEYCODE_SYM:
- return setEphemeralMetaState(AMETA_SYM_ON, down, oldMetaState);
- case AKEYCODE_FUNCTION:
- return setEphemeralMetaState(AMETA_FUNCTION_ON, down, oldMetaState);
- case AKEYCODE_CTRL_LEFT:
- return setEphemeralMetaState(AMETA_CTRL_LEFT_ON, down, oldMetaState);
- case AKEYCODE_CTRL_RIGHT:
- return setEphemeralMetaState(AMETA_CTRL_RIGHT_ON, down, oldMetaState);
- case AKEYCODE_META_LEFT:
- return setEphemeralMetaState(AMETA_META_LEFT_ON, down, oldMetaState);
- case AKEYCODE_META_RIGHT:
- return setEphemeralMetaState(AMETA_META_RIGHT_ON, down, oldMetaState);
- case AKEYCODE_CAPS_LOCK:
- return toggleLockedMetaState(AMETA_CAPS_LOCK_ON, down, oldMetaState);
- case AKEYCODE_NUM_LOCK:
- return toggleLockedMetaState(AMETA_NUM_LOCK_ON, down, oldMetaState);
- case AKEYCODE_SCROLL_LOCK:
- return toggleLockedMetaState(AMETA_SCROLL_LOCK_ON, down, oldMetaState);
- default:
- return oldMetaState;
- }
-}
-
-bool isMetaKey(int32_t keyCode) {
- switch (keyCode) {
- case AKEYCODE_ALT_LEFT:
- case AKEYCODE_ALT_RIGHT:
- case AKEYCODE_SHIFT_LEFT:
- case AKEYCODE_SHIFT_RIGHT:
- case AKEYCODE_SYM:
- case AKEYCODE_FUNCTION:
- case AKEYCODE_CTRL_LEFT:
- case AKEYCODE_CTRL_RIGHT:
- case AKEYCODE_META_LEFT:
- case AKEYCODE_META_RIGHT:
- case AKEYCODE_CAPS_LOCK:
- case AKEYCODE_NUM_LOCK:
- case AKEYCODE_SCROLL_LOCK:
- return true;
- default:
- return false;
- }
-}
-
-
-} // namespace android
diff --git a/widget/gonk/libui/Keyboard.h b/widget/gonk/libui/Keyboard.h
deleted file mode 100644
index 65921b25b..000000000
--- a/widget/gonk/libui/Keyboard.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_KEYBOARD_H
-#define _ANDROIDFW_KEYBOARD_H
-
-#include "Input.h"
-#include "InputDevice.h"
-#include <utils/Errors.h>
-#include <utils/String8.h>
-#include <utils/PropertyMap.h>
-
-namespace android {
-
-enum {
- /* Device id of the built in keyboard. */
- DEVICE_ID_BUILT_IN_KEYBOARD = 0,
-
- /* Device id of a generic virtual keyboard with a full layout that can be used
- * to synthesize key events. */
- DEVICE_ID_VIRTUAL_KEYBOARD = -1,
-};
-
-class KeyLayoutMap;
-class KeyCharacterMap;
-
-/**
- * Loads the key layout map and key character map for a keyboard device.
- */
-class KeyMap {
-public:
- String8 keyLayoutFile;
- sp<KeyLayoutMap> keyLayoutMap;
-
- String8 keyCharacterMapFile;
- sp<KeyCharacterMap> keyCharacterMap;
-
- KeyMap();
- ~KeyMap();
-
- status_t load(const InputDeviceIdentifier& deviceIdenfier,
- const PropertyMap* deviceConfiguration);
-
- inline bool haveKeyLayout() const {
- return !keyLayoutFile.isEmpty();
- }
-
- inline bool haveKeyCharacterMap() const {
- return !keyCharacterMapFile.isEmpty();
- }
-
- inline bool isComplete() const {
- return haveKeyLayout() && haveKeyCharacterMap();
- }
-
-private:
- bool probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, const String8& name);
- status_t loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, const String8& name);
- status_t loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifier,
- const String8& name);
- String8 getPath(const InputDeviceIdentifier& deviceIdentifier,
- const String8& name, InputDeviceConfigurationFileType type);
-};
-
-/**
- * Returns true if the keyboard is eligible for use as a built-in keyboard.
- */
-extern bool isEligibleBuiltInKeyboard(const InputDeviceIdentifier& deviceIdentifier,
- const PropertyMap* deviceConfiguration, const KeyMap* keyMap);
-
-/**
- * Gets a key code by its short form label, eg. "HOME".
- * Returns 0 if unknown.
- */
-extern int32_t getKeyCodeByLabel(const char* label);
-
-/**
- * Gets a key flag by its short form label, eg. "WAKE".
- * Returns 0 if unknown.
- */
-extern uint32_t getKeyFlagByLabel(const char* label);
-
-/**
- * Gets a axis by its short form label, eg. "X".
- * Returns -1 if unknown.
- */
-extern int32_t getAxisByLabel(const char* label);
-
-/**
- * Gets a axis label by its id.
- * Returns NULL if unknown.
- */
-extern const char* getAxisLabel(int32_t axisId);
-
-extern int32_t getLedByLabel(const char* label);
-
-/**
- * Updates a meta state field when a key is pressed or released.
- */
-extern int32_t updateMetaState(int32_t keyCode, bool down, int32_t oldMetaState);
-
-/**
- * Returns true if a key is a meta key like ALT or CAPS_LOCK.
- */
-extern bool isMetaKey(int32_t keyCode);
-
-} // namespace android
-
-#endif // _ANDROIDFW_KEYBOARD_H
diff --git a/widget/gonk/libui/KeycodeLabels.h b/widget/gonk/libui/KeycodeLabels.h
deleted file mode 100644
index 9f994597b..000000000
--- a/widget/gonk/libui/KeycodeLabels.h
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_KEYCODE_LABELS_H
-#define _ANDROIDFW_KEYCODE_LABELS_H
-
-#include "android_keycodes.h"
-
-struct KeycodeLabel {
- const char *literal;
- int value;
-};
-
-static const KeycodeLabel KEYCODES[] = {
- { "SOFT_LEFT", 1 },
- { "SOFT_RIGHT", 2 },
- { "HOME", 3 },
- { "BACK", 4 },
- { "CALL", 5 },
- { "ENDCALL", 6 },
- { "0", 7 },
- { "1", 8 },
- { "2", 9 },
- { "3", 10 },
- { "4", 11 },
- { "5", 12 },
- { "6", 13 },
- { "7", 14 },
- { "8", 15 },
- { "9", 16 },
- { "STAR", 17 },
- { "POUND", 18 },
- { "DPAD_UP", 19 },
- { "DPAD_DOWN", 20 },
- { "DPAD_LEFT", 21 },
- { "DPAD_RIGHT", 22 },
- { "DPAD_CENTER", 23 },
- { "VOLUME_UP", 24 },
- { "VOLUME_DOWN", 25 },
- { "POWER", 26 },
- { "CAMERA", 27 },
- { "CLEAR", 28 },
- { "A", 29 },
- { "B", 30 },
- { "C", 31 },
- { "D", 32 },
- { "E", 33 },
- { "F", 34 },
- { "G", 35 },
- { "H", 36 },
- { "I", 37 },
- { "J", 38 },
- { "K", 39 },
- { "L", 40 },
- { "M", 41 },
- { "N", 42 },
- { "O", 43 },
- { "P", 44 },
- { "Q", 45 },
- { "R", 46 },
- { "S", 47 },
- { "T", 48 },
- { "U", 49 },
- { "V", 50 },
- { "W", 51 },
- { "X", 52 },
- { "Y", 53 },
- { "Z", 54 },
- { "COMMA", 55 },
- { "PERIOD", 56 },
- { "ALT_LEFT", 57 },
- { "ALT_RIGHT", 58 },
- { "SHIFT_LEFT", 59 },
- { "SHIFT_RIGHT", 60 },
- { "TAB", 61 },
- { "SPACE", 62 },
- { "SYM", 63 },
- { "EXPLORER", 64 },
- { "ENVELOPE", 65 },
- { "ENTER", 66 },
- { "DEL", 67 },
- { "GRAVE", 68 },
- { "MINUS", 69 },
- { "EQUALS", 70 },
- { "LEFT_BRACKET", 71 },
- { "RIGHT_BRACKET", 72 },
- { "BACKSLASH", 73 },
- { "SEMICOLON", 74 },
- { "APOSTROPHE", 75 },
- { "SLASH", 76 },
- { "AT", 77 },
- { "NUM", 78 },
- { "HEADSETHOOK", 79 },
- { "FOCUS", 80 },
- { "PLUS", 81 },
- { "MENU", 82 },
- { "NOTIFICATION", 83 },
- { "SEARCH", 84 },
- { "MEDIA_PLAY_PAUSE", 85 },
- { "MEDIA_STOP", 86 },
- { "MEDIA_NEXT", 87 },
- { "MEDIA_PREVIOUS", 88 },
- { "MEDIA_REWIND", 89 },
- { "MEDIA_FAST_FORWARD", 90 },
- { "MUTE", 91 },
- { "PAGE_UP", 92 },
- { "PAGE_DOWN", 93 },
- { "PICTSYMBOLS", 94 },
- { "SWITCH_CHARSET", 95 },
- { "BUTTON_A", 96 },
- { "BUTTON_B", 97 },
- { "BUTTON_C", 98 },
- { "BUTTON_X", 99 },
- { "BUTTON_Y", 100 },
- { "BUTTON_Z", 101 },
- { "BUTTON_L1", 102 },
- { "BUTTON_R1", 103 },
- { "BUTTON_L2", 104 },
- { "BUTTON_R2", 105 },
- { "BUTTON_THUMBL", 106 },
- { "BUTTON_THUMBR", 107 },
- { "BUTTON_START", 108 },
- { "BUTTON_SELECT", 109 },
- { "BUTTON_MODE", 110 },
- { "ESCAPE", 111 },
- { "FORWARD_DEL", 112 },
- { "CTRL_LEFT", 113 },
- { "CTRL_RIGHT", 114 },
- { "CAPS_LOCK", 115 },
- { "SCROLL_LOCK", 116 },
- { "META_LEFT", 117 },
- { "META_RIGHT", 118 },
- { "FUNCTION", 119 },
- { "SYSRQ", 120 },
- { "BREAK", 121 },
- { "MOVE_HOME", 122 },
- { "MOVE_END", 123 },
- { "INSERT", 124 },
- { "FORWARD", 125 },
- { "MEDIA_PLAY", 126 },
- { "MEDIA_PAUSE", 127 },
- { "MEDIA_CLOSE", 128 },
- { "MEDIA_EJECT", 129 },
- { "MEDIA_RECORD", 130 },
- { "F1", 131 },
- { "F2", 132 },
- { "F3", 133 },
- { "F4", 134 },
- { "F5", 135 },
- { "F6", 136 },
- { "F7", 137 },
- { "F8", 138 },
- { "F9", 139 },
- { "F10", 140 },
- { "F11", 141 },
- { "F12", 142 },
- { "NUM_LOCK", 143 },
- { "NUMPAD_0", 144 },
- { "NUMPAD_1", 145 },
- { "NUMPAD_2", 146 },
- { "NUMPAD_3", 147 },
- { "NUMPAD_4", 148 },
- { "NUMPAD_5", 149 },
- { "NUMPAD_6", 150 },
- { "NUMPAD_7", 151 },
- { "NUMPAD_8", 152 },
- { "NUMPAD_9", 153 },
- { "NUMPAD_DIVIDE", 154 },
- { "NUMPAD_MULTIPLY", 155 },
- { "NUMPAD_SUBTRACT", 156 },
- { "NUMPAD_ADD", 157 },
- { "NUMPAD_DOT", 158 },
- { "NUMPAD_COMMA", 159 },
- { "NUMPAD_ENTER", 160 },
- { "NUMPAD_EQUALS", 161 },
- { "NUMPAD_LEFT_PAREN", 162 },
- { "NUMPAD_RIGHT_PAREN", 163 },
- { "VOLUME_MUTE", 164 },
- { "INFO", 165 },
- { "CHANNEL_UP", 166 },
- { "CHANNEL_DOWN", 167 },
- { "ZOOM_IN", 168 },
- { "ZOOM_OUT", 169 },
- { "TV", 170 },
- { "WINDOW", 171 },
- { "GUIDE", 172 },
- { "DVR", 173 },
- { "BOOKMARK", 174 },
- { "CAPTIONS", 175 },
- { "SETTINGS", 176 },
- { "TV_POWER", 177 },
- { "TV_INPUT", 178 },
- { "STB_POWER", 179 },
- { "STB_INPUT", 180 },
- { "AVR_POWER", 181 },
- { "AVR_INPUT", 182 },
- { "PROG_RED", 183 },
- { "PROG_GREEN", 184 },
- { "PROG_YELLOW", 185 },
- { "PROG_BLUE", 186 },
- { "APP_SWITCH", 187 },
- { "BUTTON_1", 188 },
- { "BUTTON_2", 189 },
- { "BUTTON_3", 190 },
- { "BUTTON_4", 191 },
- { "BUTTON_5", 192 },
- { "BUTTON_6", 193 },
- { "BUTTON_7", 194 },
- { "BUTTON_8", 195 },
- { "BUTTON_9", 196 },
- { "BUTTON_10", 197 },
- { "BUTTON_11", 198 },
- { "BUTTON_12", 199 },
- { "BUTTON_13", 200 },
- { "BUTTON_14", 201 },
- { "BUTTON_15", 202 },
- { "BUTTON_16", 203 },
- { "LANGUAGE_SWITCH", 204 },
- { "MANNER_MODE", 205 },
- { "3D_MODE", 206 },
- { "CONTACTS", 207 },
- { "CALENDAR", 208 },
- { "MUSIC", 209 },
- { "CALCULATOR", 210 },
- { "ZENKAKU_HANKAKU", 211 },
- { "EISU", 212 },
- { "MUHENKAN", 213 },
- { "HENKAN", 214 },
- { "KATAKANA_HIRAGANA", 215 },
- { "YEN", 216 },
- { "RO", 217 },
- { "KANA", 218 },
- { "ASSIST", 219 },
- { "BRIGHTNESS_DOWN", 220 },
- { "BRIGHTNESS_UP", 221 },
- { "MEDIA_AUDIO_TRACK", 222 },
- { "SLEEP", 223 },
- { "WAKEUP", 224 },
- { "PAIRING", 225 },
- { "MEDIA_TOP_MENU", 226 },
- { "11", 227 },
- { "12", 228 },
- { "LAST_CHANNEL", 229 },
- { "TV_DATA_SERVICE", 230 },
- { "VOICE_ASSIST", 231 },
- { "TV_RADIO_SERVICE", 232 },
- { "TV_TELETEXT", 233 },
- { "TV_NUMBER_ENTRY", 234 },
- { "TV_TERRESTRIAL_ANALOG", 235 },
- { "TV_TERRESTRIAL_DIGITAL", 236 },
- { "TV_SATELLITE", 237 },
- { "TV_SATELLITE_BS", 238 },
- { "TV_SATELLITE_CS", 239 },
- { "TV_SATELLITE_SERVICE", 240 },
- { "TV_NETWORK", 241 },
- { "TV_ANTENNA_CABLE", 242 },
- { "TV_INPUT_HDMI_1", 243 },
- { "TV_INPUT_HDMI_2", 244 },
- { "TV_INPUT_HDMI_3", 245 },
- { "TV_INPUT_HDMI_4", 246 },
- { "TV_INPUT_COMPOSITE_1", 247 },
- { "TV_INPUT_COMPOSITE_2", 248 },
- { "TV_INPUT_COMPONENT_1", 249 },
- { "TV_INPUT_COMPONENT_2", 250 },
- { "TV_INPUT_VGA_1", 251 },
- { "TV_AUDIO_DESCRIPTION", 252 },
- { "TV_AUDIO_DESCRIPTION_MIX_UP", 253 },
- { "TV_AUDIO_DESCRIPTION_MIX_DOWN", 254 },
- { "TV_ZOOM_MODE", 255 },
- { "TV_CONTENTS_MENU", 256 },
- { "TV_MEDIA_CONTEXT_MENU", 257 },
- { "TV_TIMER_PROGRAMMING", 258 },
- { "HELP", 259 },
-
- // NOTE: If you add a new keycode here you must also add it to several other files.
- // Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
-
- { NULL, 0 }
-};
-
-// NOTE: If you edit these flags, also edit policy flags in Input.h.
-static const KeycodeLabel FLAGS[] = {
- { "WAKE", 0x00000001 },
- { "WAKE_DROPPED", 0x00000002 },
- { "SHIFT", 0x00000004 },
- { "CAPS_LOCK", 0x00000008 },
- { "ALT", 0x00000010 },
- { "ALT_GR", 0x00000020 },
- { "MENU", 0x00000040 },
- { "LAUNCHER", 0x00000080 },
- { "VIRTUAL", 0x00000100 },
- { "FUNCTION", 0x00000200 },
- { NULL, 0 }
-};
-
-static const KeycodeLabel AXES[] = {
- { "X", 0 },
- { "Y", 1 },
- { "PRESSURE", 2 },
- { "SIZE", 3 },
- { "TOUCH_MAJOR", 4 },
- { "TOUCH_MINOR", 5 },
- { "TOOL_MAJOR", 6 },
- { "TOOL_MINOR", 7 },
- { "ORIENTATION", 8 },
- { "VSCROLL", 9 },
- { "HSCROLL", 10 },
- { "Z", 11 },
- { "RX", 12 },
- { "RY", 13 },
- { "RZ", 14 },
- { "HAT_X", 15 },
- { "HAT_Y", 16 },
- { "LTRIGGER", 17 },
- { "RTRIGGER", 18 },
- { "THROTTLE", 19 },
- { "RUDDER", 20 },
- { "WHEEL", 21 },
- { "GAS", 22 },
- { "BRAKE", 23 },
- { "DISTANCE", 24 },
- { "TILT", 25 },
- { "GENERIC_1", 32 },
- { "GENERIC_2", 33 },
- { "GENERIC_3", 34 },
- { "GENERIC_4", 35 },
- { "GENERIC_5", 36 },
- { "GENERIC_6", 37 },
- { "GENERIC_7", 38 },
- { "GENERIC_8", 39 },
- { "GENERIC_9", 40 },
- { "GENERIC_10", 41 },
- { "GENERIC_11", 42 },
- { "GENERIC_12", 43 },
- { "GENERIC_13", 44 },
- { "GENERIC_14", 45 },
- { "GENERIC_15", 46 },
- { "GENERIC_16", 47 },
-
- // NOTE: If you add a new axis here you must also add it to several other files.
- // Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list.
-
- { NULL, -1 }
-};
-
-static const KeycodeLabel LEDS[] = {
- { "NUM_LOCK", 1},
- { "CAPS_LOCK", 2},
- { "SCROLL_LOCK", 3},
- { "COMPOSE", 4},
- { "KANA", 5},
- { "SLEEP", 6},
- { "SUSPEND", 7},
- { "MUTE", 8},
- { "MISC", 9},
- { "MAIL", 10},
- { "CHARGING", 11},
- { "CONTROLLER_1", 12},
- { "CONTROLLER_2", 13},
- { "CONTROLLER_3", 14},
- { "CONTROLLER_4", 15},
-
- // NOTE: If you add new LEDs here, you must also add them to Input.h
- { NULL, 0 }
-};
-
-#endif // _ANDROIDFW_KEYCODE_LABELS_H
diff --git a/widget/gonk/libui/PointerController.cpp b/widget/gonk/libui/PointerController.cpp
deleted file mode 100644
index ff80a0a9f..000000000
--- a/widget/gonk/libui/PointerController.cpp
+++ /dev/null
@@ -1,604 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "PointerController"
-
-//#define LOG_NDEBUG 0
-
-// Log debug messages about pointer updates
-#define DEBUG_POINTER_UPDATES 0
-
-#include "PointerController.h"
-
-#include "cutils_log.h"
-
-#include <SkBitmap.h>
-#include <SkCanvas.h>
-#include <SkColor.h>
-#include <SkPaint.h>
-#include <SkXfermode.h>
-
-namespace android {
-
-// --- PointerController ---
-
-// Time to wait before starting the fade when the pointer is inactive.
-static const nsecs_t INACTIVITY_TIMEOUT_DELAY_TIME_NORMAL = 15 * 1000 * 1000000LL; // 15 seconds
-static const nsecs_t INACTIVITY_TIMEOUT_DELAY_TIME_SHORT = 3 * 1000 * 1000000LL; // 3 seconds
-
-// Time to wait between animation frames.
-static const nsecs_t ANIMATION_FRAME_INTERVAL = 1000000000LL / 60;
-
-// Time to spend fading out the spot completely.
-static const nsecs_t SPOT_FADE_DURATION = 200 * 1000000LL; // 200 ms
-
-// Time to spend fading out the pointer completely.
-static const nsecs_t POINTER_FADE_DURATION = 500 * 1000000LL; // 500 ms
-
-
-// --- PointerController ---
-
-PointerController::PointerController(const sp<PointerControllerPolicyInterface>& policy,
- const sp<Looper>& looper, const sp<SpriteController>& spriteController) :
- mPolicy(policy), mLooper(looper), mSpriteController(spriteController) {
- mHandler = new WeakMessageHandler(this);
-
- AutoMutex _l(mLock);
-
- mLocked.animationPending = false;
-
- mLocked.displayWidth = -1;
- mLocked.displayHeight = -1;
- mLocked.displayOrientation = DISPLAY_ORIENTATION_0;
-
- mLocked.presentation = PRESENTATION_POINTER;
- mLocked.presentationChanged = false;
-
- mLocked.inactivityTimeout = INACTIVITY_TIMEOUT_NORMAL;
-
- mLocked.pointerFadeDirection = 0;
- mLocked.pointerX = 0;
- mLocked.pointerY = 0;
- mLocked.pointerAlpha = 0.0f; // pointer is initially faded
- mLocked.pointerSprite = mSpriteController->createSprite();
- mLocked.pointerIconChanged = false;
-
- mLocked.buttonState = 0;
-
- loadResources();
-}
-
-PointerController::~PointerController() {
- mLooper->removeMessages(mHandler);
-
- AutoMutex _l(mLock);
-
- mLocked.pointerSprite.clear();
-
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- delete mLocked.spots.itemAt(i);
- }
- mLocked.spots.clear();
- mLocked.recycledSprites.clear();
-}
-
-bool PointerController::getBounds(float* outMinX, float* outMinY,
- float* outMaxX, float* outMaxY) const {
- AutoMutex _l(mLock);
-
- return getBoundsLocked(outMinX, outMinY, outMaxX, outMaxY);
-}
-
-bool PointerController::getBoundsLocked(float* outMinX, float* outMinY,
- float* outMaxX, float* outMaxY) const {
- if (mLocked.displayWidth <= 0 || mLocked.displayHeight <= 0) {
- return false;
- }
-
- *outMinX = 0;
- *outMinY = 0;
- switch (mLocked.displayOrientation) {
- case DISPLAY_ORIENTATION_90:
- case DISPLAY_ORIENTATION_270:
- *outMaxX = mLocked.displayHeight - 1;
- *outMaxY = mLocked.displayWidth - 1;
- break;
- default:
- *outMaxX = mLocked.displayWidth - 1;
- *outMaxY = mLocked.displayHeight - 1;
- break;
- }
- return true;
-}
-
-void PointerController::move(float deltaX, float deltaY) {
-#if DEBUG_POINTER_UPDATES
- ALOGD("Move pointer by deltaX=%0.3f, deltaY=%0.3f", deltaX, deltaY);
-#endif
- if (deltaX == 0.0f && deltaY == 0.0f) {
- return;
- }
-
- AutoMutex _l(mLock);
-
- setPositionLocked(mLocked.pointerX + deltaX, mLocked.pointerY + deltaY);
-}
-
-void PointerController::setButtonState(int32_t buttonState) {
-#if DEBUG_POINTER_UPDATES
- ALOGD("Set button state 0x%08x", buttonState);
-#endif
- AutoMutex _l(mLock);
-
- if (mLocked.buttonState != buttonState) {
- mLocked.buttonState = buttonState;
- }
-}
-
-int32_t PointerController::getButtonState() const {
- AutoMutex _l(mLock);
-
- return mLocked.buttonState;
-}
-
-void PointerController::setPosition(float x, float y) {
-#if DEBUG_POINTER_UPDATES
- ALOGD("Set pointer position to x=%0.3f, y=%0.3f", x, y);
-#endif
- AutoMutex _l(mLock);
-
- setPositionLocked(x, y);
-}
-
-void PointerController::setPositionLocked(float x, float y) {
- float minX, minY, maxX, maxY;
- if (getBoundsLocked(&minX, &minY, &maxX, &maxY)) {
- if (x <= minX) {
- mLocked.pointerX = minX;
- } else if (x >= maxX) {
- mLocked.pointerX = maxX;
- } else {
- mLocked.pointerX = x;
- }
- if (y <= minY) {
- mLocked.pointerY = minY;
- } else if (y >= maxY) {
- mLocked.pointerY = maxY;
- } else {
- mLocked.pointerY = y;
- }
- updatePointerLocked();
- }
-}
-
-void PointerController::getPosition(float* outX, float* outY) const {
- AutoMutex _l(mLock);
-
- *outX = mLocked.pointerX;
- *outY = mLocked.pointerY;
-}
-
-void PointerController::fade(Transition transition) {
- AutoMutex _l(mLock);
-
- // Remove the inactivity timeout, since we are fading now.
- removeInactivityTimeoutLocked();
-
- // Start fading.
- if (transition == TRANSITION_IMMEDIATE) {
- mLocked.pointerFadeDirection = 0;
- mLocked.pointerAlpha = 0.0f;
- updatePointerLocked();
- } else {
- mLocked.pointerFadeDirection = -1;
- startAnimationLocked();
- }
-}
-
-void PointerController::unfade(Transition transition) {
- AutoMutex _l(mLock);
-
- // Always reset the inactivity timer.
- resetInactivityTimeoutLocked();
-
- // Start unfading.
- if (transition == TRANSITION_IMMEDIATE) {
- mLocked.pointerFadeDirection = 0;
- mLocked.pointerAlpha = 1.0f;
- updatePointerLocked();
- } else {
- mLocked.pointerFadeDirection = 1;
- startAnimationLocked();
- }
-}
-
-void PointerController::setPresentation(Presentation presentation) {
- AutoMutex _l(mLock);
-
- if (mLocked.presentation != presentation) {
- mLocked.presentation = presentation;
- mLocked.presentationChanged = true;
-
- if (presentation != PRESENTATION_SPOT) {
- fadeOutAndReleaseAllSpotsLocked();
- }
-
- updatePointerLocked();
- }
-}
-
-void PointerController::setSpots(const PointerCoords* spotCoords,
- const uint32_t* spotIdToIndex, BitSet32 spotIdBits) {
-#if DEBUG_POINTER_UPDATES
- ALOGD("setSpots: idBits=%08x", spotIdBits.value);
- for (BitSet32 idBits(spotIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.firstMarkedBit();
- idBits.clearBit(id);
- const PointerCoords& c = spotCoords[spotIdToIndex[id]];
- ALOGD(" spot %d: position=(%0.3f, %0.3f), pressure=%0.3f", id,
- c.getAxisValue(AMOTION_EVENT_AXIS_X),
- c.getAxisValue(AMOTION_EVENT_AXIS_Y),
- c.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
- }
-#endif
-
- AutoMutex _l(mLock);
-
- mSpriteController->openTransaction();
-
- // Add or move spots for fingers that are down.
- for (BitSet32 idBits(spotIdBits); !idBits.isEmpty(); ) {
- uint32_t id = idBits.clearFirstMarkedBit();
- const PointerCoords& c = spotCoords[spotIdToIndex[id]];
- const SpriteIcon& icon = c.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE) > 0
- ? mResources.spotTouch : mResources.spotHover;
- float x = c.getAxisValue(AMOTION_EVENT_AXIS_X);
- float y = c.getAxisValue(AMOTION_EVENT_AXIS_Y);
-
- Spot* spot = getSpotLocked(id);
- if (!spot) {
- spot = createAndAddSpotLocked(id);
- }
-
- spot->updateSprite(&icon, x, y);
- }
-
- // Remove spots for fingers that went up.
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
- if (spot->id != Spot::INVALID_ID
- && !spotIdBits.hasBit(spot->id)) {
- fadeOutAndReleaseSpotLocked(spot);
- }
- }
-
- mSpriteController->closeTransaction();
-}
-
-void PointerController::clearSpots() {
-#if DEBUG_POINTER_UPDATES
- ALOGD("clearSpots");
-#endif
-
- AutoMutex _l(mLock);
-
- fadeOutAndReleaseAllSpotsLocked();
-}
-
-void PointerController::setInactivityTimeout(InactivityTimeout inactivityTimeout) {
- AutoMutex _l(mLock);
-
- if (mLocked.inactivityTimeout != inactivityTimeout) {
- mLocked.inactivityTimeout = inactivityTimeout;
- resetInactivityTimeoutLocked();
- }
-}
-
-void PointerController::setDisplayViewport(int32_t width, int32_t height, int32_t orientation) {
- AutoMutex _l(mLock);
-
- // Adjust to use the display's unrotated coordinate frame.
- if (orientation == DISPLAY_ORIENTATION_90
- || orientation == DISPLAY_ORIENTATION_270) {
- int32_t temp = height;
- height = width;
- width = temp;
- }
-
- if (mLocked.displayWidth != width || mLocked.displayHeight != height) {
- mLocked.displayWidth = width;
- mLocked.displayHeight = height;
-
- float minX, minY, maxX, maxY;
- if (getBoundsLocked(&minX, &minY, &maxX, &maxY)) {
- mLocked.pointerX = (minX + maxX) * 0.5f;
- mLocked.pointerY = (minY + maxY) * 0.5f;
- } else {
- mLocked.pointerX = 0;
- mLocked.pointerY = 0;
- }
-
- fadeOutAndReleaseAllSpotsLocked();
- }
-
- if (mLocked.displayOrientation != orientation) {
- // Apply offsets to convert from the pixel top-left corner position to the pixel center.
- // This creates an invariant frame of reference that we can easily rotate when
- // taking into account that the pointer may be located at fractional pixel offsets.
- float x = mLocked.pointerX + 0.5f;
- float y = mLocked.pointerY + 0.5f;
- float temp;
-
- // Undo the previous rotation.
- switch (mLocked.displayOrientation) {
- case DISPLAY_ORIENTATION_90:
- temp = x;
- x = mLocked.displayWidth - y;
- y = temp;
- break;
- case DISPLAY_ORIENTATION_180:
- x = mLocked.displayWidth - x;
- y = mLocked.displayHeight - y;
- break;
- case DISPLAY_ORIENTATION_270:
- temp = x;
- x = y;
- y = mLocked.displayHeight - temp;
- break;
- }
-
- // Perform the new rotation.
- switch (orientation) {
- case DISPLAY_ORIENTATION_90:
- temp = x;
- x = y;
- y = mLocked.displayWidth - temp;
- break;
- case DISPLAY_ORIENTATION_180:
- x = mLocked.displayWidth - x;
- y = mLocked.displayHeight - y;
- break;
- case DISPLAY_ORIENTATION_270:
- temp = x;
- x = mLocked.displayHeight - y;
- y = temp;
- break;
- }
-
- // Apply offsets to convert from the pixel center to the pixel top-left corner position
- // and save the results.
- mLocked.pointerX = x - 0.5f;
- mLocked.pointerY = y - 0.5f;
- mLocked.displayOrientation = orientation;
- }
-
- updatePointerLocked();
-}
-
-void PointerController::setPointerIcon(const SpriteIcon& icon) {
- AutoMutex _l(mLock);
-
- mLocked.pointerIcon = icon.copy();
- mLocked.pointerIconChanged = true;
-
- updatePointerLocked();
-}
-
-void PointerController::handleMessage(const Message& message) {
- switch (message.what) {
- case MSG_ANIMATE:
- doAnimate();
- break;
- case MSG_INACTIVITY_TIMEOUT:
- doInactivityTimeout();
- break;
- }
-}
-
-void PointerController::doAnimate() {
- AutoMutex _l(mLock);
-
- bool keepAnimating = false;
- mLocked.animationPending = false;
- nsecs_t frameDelay = systemTime(SYSTEM_TIME_MONOTONIC) - mLocked.animationTime;
-
- // Animate pointer fade.
- if (mLocked.pointerFadeDirection < 0) {
- mLocked.pointerAlpha -= float(frameDelay) / POINTER_FADE_DURATION;
- if (mLocked.pointerAlpha <= 0.0f) {
- mLocked.pointerAlpha = 0.0f;
- mLocked.pointerFadeDirection = 0;
- } else {
- keepAnimating = true;
- }
- updatePointerLocked();
- } else if (mLocked.pointerFadeDirection > 0) {
- mLocked.pointerAlpha += float(frameDelay) / POINTER_FADE_DURATION;
- if (mLocked.pointerAlpha >= 1.0f) {
- mLocked.pointerAlpha = 1.0f;
- mLocked.pointerFadeDirection = 0;
- } else {
- keepAnimating = true;
- }
- updatePointerLocked();
- }
-
- // Animate spots that are fading out and being removed.
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
- if (spot->id == Spot::INVALID_ID) {
- spot->alpha -= float(frameDelay) / SPOT_FADE_DURATION;
- if (spot->alpha <= 0) {
- mLocked.spots.removeAt(i--);
- releaseSpotLocked(spot);
- } else {
- spot->sprite->setAlpha(spot->alpha);
- keepAnimating = true;
- }
- }
- }
-
- if (keepAnimating) {
- startAnimationLocked();
- }
-}
-
-void PointerController::doInactivityTimeout() {
- fade(TRANSITION_GRADUAL);
-}
-
-void PointerController::startAnimationLocked() {
- if (!mLocked.animationPending) {
- mLocked.animationPending = true;
- mLocked.animationTime = systemTime(SYSTEM_TIME_MONOTONIC);
- mLooper->sendMessageDelayed(ANIMATION_FRAME_INTERVAL, mHandler, Message(MSG_ANIMATE));
- }
-}
-
-void PointerController::resetInactivityTimeoutLocked() {
- mLooper->removeMessages(mHandler, MSG_INACTIVITY_TIMEOUT);
-
- nsecs_t timeout = mLocked.inactivityTimeout == INACTIVITY_TIMEOUT_SHORT
- ? INACTIVITY_TIMEOUT_DELAY_TIME_SHORT : INACTIVITY_TIMEOUT_DELAY_TIME_NORMAL;
- mLooper->sendMessageDelayed(timeout, mHandler, MSG_INACTIVITY_TIMEOUT);
-}
-
-void PointerController::removeInactivityTimeoutLocked() {
- mLooper->removeMessages(mHandler, MSG_INACTIVITY_TIMEOUT);
-}
-
-void PointerController::updatePointerLocked() {
- mSpriteController->openTransaction();
-
- mLocked.pointerSprite->setLayer(Sprite::BASE_LAYER_POINTER);
- mLocked.pointerSprite->setPosition(mLocked.pointerX, mLocked.pointerY);
-
- if (mLocked.pointerAlpha > 0) {
- mLocked.pointerSprite->setAlpha(mLocked.pointerAlpha);
- mLocked.pointerSprite->setVisible(true);
- } else {
- mLocked.pointerSprite->setVisible(false);
- }
-
- if (mLocked.pointerIconChanged || mLocked.presentationChanged) {
- mLocked.pointerSprite->setIcon(mLocked.presentation == PRESENTATION_POINTER
- ? mLocked.pointerIcon : mResources.spotAnchor);
- mLocked.pointerIconChanged = false;
- mLocked.presentationChanged = false;
- }
-
- mSpriteController->closeTransaction();
-}
-
-PointerController::Spot* PointerController::getSpotLocked(uint32_t id) {
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
- if (spot->id == id) {
- return spot;
- }
- }
- return NULL;
-}
-
-PointerController::Spot* PointerController::createAndAddSpotLocked(uint32_t id) {
- // Remove spots until we have fewer than MAX_SPOTS remaining.
- while (mLocked.spots.size() >= MAX_SPOTS) {
- Spot* spot = removeFirstFadingSpotLocked();
- if (!spot) {
- spot = mLocked.spots.itemAt(0);
- mLocked.spots.removeAt(0);
- }
- releaseSpotLocked(spot);
- }
-
- // Obtain a sprite from the recycled pool.
- sp<Sprite> sprite;
- if (! mLocked.recycledSprites.isEmpty()) {
- sprite = mLocked.recycledSprites.top();
- mLocked.recycledSprites.pop();
- } else {
- sprite = mSpriteController->createSprite();
- }
-
- // Return the new spot.
- Spot* spot = new Spot(id, sprite);
- mLocked.spots.push(spot);
- return spot;
-}
-
-PointerController::Spot* PointerController::removeFirstFadingSpotLocked() {
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
- if (spot->id == Spot::INVALID_ID) {
- mLocked.spots.removeAt(i);
- return spot;
- }
- }
- return NULL;
-}
-
-void PointerController::releaseSpotLocked(Spot* spot) {
- spot->sprite->clearIcon();
-
- if (mLocked.recycledSprites.size() < MAX_RECYCLED_SPRITES) {
- mLocked.recycledSprites.push(spot->sprite);
- }
-
- delete spot;
-}
-
-void PointerController::fadeOutAndReleaseSpotLocked(Spot* spot) {
- if (spot->id != Spot::INVALID_ID) {
- spot->id = Spot::INVALID_ID;
- startAnimationLocked();
- }
-}
-
-void PointerController::fadeOutAndReleaseAllSpotsLocked() {
- for (size_t i = 0; i < mLocked.spots.size(); i++) {
- Spot* spot = mLocked.spots.itemAt(i);
- fadeOutAndReleaseSpotLocked(spot);
- }
-}
-
-void PointerController::loadResources() {
- mPolicy->loadPointerResources(&mResources);
-}
-
-
-// --- PointerController::Spot ---
-
-void PointerController::Spot::updateSprite(const SpriteIcon* icon, float x, float y) {
- sprite->setLayer(Sprite::BASE_LAYER_SPOT + id);
- sprite->setAlpha(alpha);
- sprite->setTransformationMatrix(SpriteTransformationMatrix(scale, 0.0f, 0.0f, scale));
- sprite->setPosition(x, y);
-
- this->x = x;
- this->y = y;
-
- if (icon != lastIcon) {
- lastIcon = icon;
- if (icon) {
- sprite->setIcon(*icon);
- sprite->setVisible(true);
- } else {
- sprite->setVisible(false);
- }
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/PointerController.h b/widget/gonk/libui/PointerController.h
deleted file mode 100644
index eb48d9a1f..000000000
--- a/widget/gonk/libui/PointerController.h
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_POINTER_CONTROLLER_H
-#define _UI_POINTER_CONTROLLER_H
-
-#include "SpriteController.h"
-
-#include <ui/DisplayInfo.h>
-#include "Input.h"
-#include <utils/BitSet.h>
-#include <utils/RefBase.h>
-#include <utils/Looper.h>
-#include <utils/String8.h>
-
-#include <SkBitmap.h>
-
-namespace android {
-
-/**
- * Interface for tracking a mouse / touch pad pointer and touch pad spots.
- *
- * The spots are sprites on screen that visually represent the positions of
- * fingers
- *
- * The pointer controller is responsible for providing synchronization and for tracking
- * display orientation changes if needed.
- */
-class PointerControllerInterface : public virtual RefBase {
-protected:
- PointerControllerInterface() { }
- virtual ~PointerControllerInterface() { }
-
-public:
- /* Gets the bounds of the region that the pointer can traverse.
- * Returns true if the bounds are available. */
- virtual bool getBounds(float* outMinX, float* outMinY,
- float* outMaxX, float* outMaxY) const = 0;
-
- /* Move the pointer. */
- virtual void move(float deltaX, float deltaY) = 0;
-
- /* Sets a mask that indicates which buttons are pressed. */
- virtual void setButtonState(int32_t buttonState) = 0;
-
- /* Gets a mask that indicates which buttons are pressed. */
- virtual int32_t getButtonState() const = 0;
-
- /* Sets the absolute location of the pointer. */
- virtual void setPosition(float x, float y) = 0;
-
- /* Gets the absolute location of the pointer. */
- virtual void getPosition(float* outX, float* outY) const = 0;
-
- enum Transition {
- // Fade/unfade immediately.
- TRANSITION_IMMEDIATE,
- // Fade/unfade gradually.
- TRANSITION_GRADUAL,
- };
-
- /* Fades the pointer out now. */
- virtual void fade(Transition transition) = 0;
-
- /* Makes the pointer visible if it has faded out.
- * The pointer never unfades itself automatically. This method must be called
- * by the client whenever the pointer is moved or a button is pressed and it
- * wants to ensure that the pointer becomes visible again. */
- virtual void unfade(Transition transition) = 0;
-
- enum Presentation {
- // Show the mouse pointer.
- PRESENTATION_POINTER,
- // Show spots and a spot anchor in place of the mouse pointer.
- PRESENTATION_SPOT,
- };
-
- /* Sets the mode of the pointer controller. */
- virtual void setPresentation(Presentation presentation) = 0;
-
- /* Sets the spots for the current gesture.
- * The spots are not subject to the inactivity timeout like the pointer
- * itself it since they are expected to remain visible for so long as
- * the fingers are on the touch pad.
- *
- * The values of the AMOTION_EVENT_AXIS_PRESSURE axis is significant.
- * For spotCoords, pressure != 0 indicates that the spot's location is being
- * pressed (not hovering).
- */
- virtual void setSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
- BitSet32 spotIdBits) = 0;
-
- /* Removes all spots. */
- virtual void clearSpots() = 0;
-};
-
-
-/*
- * Pointer resources.
- */
-struct PointerResources {
- SpriteIcon spotHover;
- SpriteIcon spotTouch;
- SpriteIcon spotAnchor;
-};
-
-
-/*
- * Pointer controller policy interface.
- *
- * The pointer controller policy is used by the pointer controller to interact with
- * the Window Manager and other system components.
- *
- * The actual implementation is partially supported by callbacks into the DVM
- * via JNI. This interface is also mocked in the unit tests.
- */
-class PointerControllerPolicyInterface : public virtual RefBase {
-protected:
- PointerControllerPolicyInterface() { }
- virtual ~PointerControllerPolicyInterface() { }
-
-public:
- virtual void loadPointerResources(PointerResources* outResources) = 0;
-};
-
-
-/*
- * Tracks pointer movements and draws the pointer sprite to a surface.
- *
- * Handles pointer acceleration and animation.
- */
-class PointerController : public PointerControllerInterface, public MessageHandler {
-protected:
- virtual ~PointerController();
-
-public:
- enum InactivityTimeout {
- INACTIVITY_TIMEOUT_NORMAL = 0,
- INACTIVITY_TIMEOUT_SHORT = 1,
- };
-
- PointerController(const sp<PointerControllerPolicyInterface>& policy,
- const sp<Looper>& looper, const sp<SpriteController>& spriteController);
-
- virtual bool getBounds(float* outMinX, float* outMinY,
- float* outMaxX, float* outMaxY) const;
- virtual void move(float deltaX, float deltaY);
- virtual void setButtonState(int32_t buttonState);
- virtual int32_t getButtonState() const;
- virtual void setPosition(float x, float y);
- virtual void getPosition(float* outX, float* outY) const;
- virtual void fade(Transition transition);
- virtual void unfade(Transition transition);
-
- virtual void setPresentation(Presentation presentation);
- virtual void setSpots(const PointerCoords* spotCoords,
- const uint32_t* spotIdToIndex, BitSet32 spotIdBits);
- virtual void clearSpots();
-
- void setDisplayViewport(int32_t width, int32_t height, int32_t orientation);
- void setPointerIcon(const SpriteIcon& icon);
- void setInactivityTimeout(InactivityTimeout inactivityTimeout);
-
-private:
- static const size_t MAX_RECYCLED_SPRITES = 12;
- static const size_t MAX_SPOTS = 12;
-
- enum {
- MSG_ANIMATE,
- MSG_INACTIVITY_TIMEOUT,
- };
-
- struct Spot {
- static const uint32_t INVALID_ID = 0xffffffff;
-
- uint32_t id;
- sp<Sprite> sprite;
- float alpha;
- float scale;
- float x, y;
-
- inline Spot(uint32_t id, const sp<Sprite>& sprite)
- : id(id), sprite(sprite), alpha(1.0f), scale(1.0f),
- x(0.0f), y(0.0f), lastIcon(NULL) { }
-
- void updateSprite(const SpriteIcon* icon, float x, float y);
-
- private:
- const SpriteIcon* lastIcon;
- };
-
- mutable Mutex mLock;
-
- sp<PointerControllerPolicyInterface> mPolicy;
- sp<Looper> mLooper;
- sp<SpriteController> mSpriteController;
- sp<WeakMessageHandler> mHandler;
-
- PointerResources mResources;
-
- struct Locked {
- bool animationPending;
- nsecs_t animationTime;
-
- int32_t displayWidth;
- int32_t displayHeight;
- int32_t displayOrientation;
-
- InactivityTimeout inactivityTimeout;
-
- Presentation presentation;
- bool presentationChanged;
-
- int32_t pointerFadeDirection;
- float pointerX;
- float pointerY;
- float pointerAlpha;
- sp<Sprite> pointerSprite;
- SpriteIcon pointerIcon;
- bool pointerIconChanged;
-
- int32_t buttonState;
-
- Vector<Spot*> spots;
- Vector<sp<Sprite> > recycledSprites;
- } mLocked;
-
- bool getBoundsLocked(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const;
- void setPositionLocked(float x, float y);
-
- void handleMessage(const Message& message);
- void doAnimate();
- void doInactivityTimeout();
-
- void startAnimationLocked();
-
- void resetInactivityTimeoutLocked();
- void removeInactivityTimeoutLocked();
- void updatePointerLocked();
-
- Spot* getSpotLocked(uint32_t id);
- Spot* createAndAddSpotLocked(uint32_t id);
- Spot* removeFirstFadingSpotLocked();
- void releaseSpotLocked(Spot* spot);
- void fadeOutAndReleaseSpotLocked(Spot* spot);
- void fadeOutAndReleaseAllSpotsLocked();
-
- void loadResources();
-};
-
-} // namespace android
-
-#endif // _UI_POINTER_CONTROLLER_H
diff --git a/widget/gonk/libui/PowerManager.h b/widget/gonk/libui/PowerManager.h
deleted file mode 100644
index ba98db07c..000000000
--- a/widget/gonk/libui/PowerManager.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_POWER_MANAGER_H
-#define _ANDROIDFW_POWER_MANAGER_H
-
-
-namespace android {
-
-enum {
- USER_ACTIVITY_EVENT_OTHER = 0,
- USER_ACTIVITY_EVENT_BUTTON = 1,
- USER_ACTIVITY_EVENT_TOUCH = 2,
-
- USER_ACTIVITY_EVENT_LAST = USER_ACTIVITY_EVENT_TOUCH, // Last valid event code.
-};
-
-} // namespace android
-
-#endif // _ANDROIDFW_POWER_MANAGER_H
diff --git a/widget/gonk/libui/SpriteController.cpp b/widget/gonk/libui/SpriteController.cpp
deleted file mode 100644
index 8677476b1..000000000
--- a/widget/gonk/libui/SpriteController.cpp
+++ /dev/null
@@ -1,515 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "Sprites"
-
-//#define LOG_NDEBUG 0
-
-#include "SpriteController.h"
-
-#include "cutils_log.h"
-#include <utils/String8.h>
-#ifdef HAVE_ANDROID_OS
-#include <gui/Surface.h>
-#endif
-
-#include <SkBitmap.h>
-#include <SkCanvas.h>
-#include <SkColor.h>
-#include <SkPaint.h>
-#include <SkXfermode.h>
-#include <android/native_window.h>
-
-namespace android {
-
-// --- SpriteController ---
-
-SpriteController::SpriteController(const sp<Looper>& looper, int32_t overlayLayer) :
- mLooper(looper), mOverlayLayer(overlayLayer) {
-#ifdef HAVE_ANDROID_OS
- mHandler = new WeakMessageHandler(this);
-#endif
-
- mLocked.transactionNestingCount = 0;
- mLocked.deferredSpriteUpdate = false;
-}
-
-SpriteController::~SpriteController() {
-#ifdef HAVE_ANDROID_OS
- mLooper->removeMessages(mHandler);
-
- if (mSurfaceComposerClient != NULL) {
- mSurfaceComposerClient->dispose();
- mSurfaceComposerClient.clear();
- }
-#endif
-}
-
-sp<Sprite> SpriteController::createSprite() {
- return new SpriteImpl(this);
-}
-
-void SpriteController::openTransaction() {
- AutoMutex _l(mLock);
-
- mLocked.transactionNestingCount += 1;
-}
-
-void SpriteController::closeTransaction() {
- AutoMutex _l(mLock);
-
- LOG_ALWAYS_FATAL_IF(mLocked.transactionNestingCount == 0,
- "Sprite closeTransaction() called but there is no open sprite transaction");
-
- mLocked.transactionNestingCount -= 1;
- if (mLocked.transactionNestingCount == 0 && mLocked.deferredSpriteUpdate) {
- mLocked.deferredSpriteUpdate = false;
-#ifdef HAVE_ANDROID_OS
- mLooper->sendMessage(mHandler, Message(MSG_UPDATE_SPRITES));
-#endif
- }
-}
-
-void SpriteController::invalidateSpriteLocked(const sp<SpriteImpl>& sprite) {
- bool wasEmpty = mLocked.invalidatedSprites.isEmpty();
- mLocked.invalidatedSprites.push(sprite);
- if (wasEmpty) {
- if (mLocked.transactionNestingCount != 0) {
- mLocked.deferredSpriteUpdate = true;
- } else {
-#ifdef HAVE_ANDROID_OS
- mLooper->sendMessage(mHandler, Message(MSG_UPDATE_SPRITES));
-#endif
- }
- }
-}
-
-#ifdef HAVE_ANDROID_OS
-void SpriteController::disposeSurfaceLocked(const sp<SurfaceControl>& surfaceControl) {
- bool wasEmpty = mLocked.disposedSurfaces.isEmpty();
- mLocked.disposedSurfaces.push(surfaceControl);
- if (wasEmpty) {
- mLooper->sendMessage(mHandler, Message(MSG_DISPOSE_SURFACES));
- }
-}
-
-void SpriteController::handleMessage(const Message& message) {
- switch (message.what) {
- case MSG_UPDATE_SPRITES:
- doUpdateSprites();
- break;
- case MSG_DISPOSE_SURFACES:
- doDisposeSurfaces();
- break;
- }
-}
-#endif
-
-void SpriteController::doUpdateSprites() {
- // Collect information about sprite updates.
- // Each sprite update record includes a reference to its associated sprite so we can
- // be certain the sprites will not be deleted while this function runs. Sprites
- // may invalidate themselves again during this time but we will handle those changes
- // in the next iteration.
- Vector<SpriteUpdate> updates;
- size_t numSprites;
- { // acquire lock
- AutoMutex _l(mLock);
-
- numSprites = mLocked.invalidatedSprites.size();
- for (size_t i = 0; i < numSprites; i++) {
- const sp<SpriteImpl>& sprite = mLocked.invalidatedSprites.itemAt(i);
-
- updates.push(SpriteUpdate(sprite, sprite->getStateLocked()));
- sprite->resetDirtyLocked();
- }
- mLocked.invalidatedSprites.clear();
- } // release lock
-
- // Create missing surfaces.
- bool surfaceChanged = false;
-#ifdef HAVE_ANDROID_OS
- for (size_t i = 0; i < numSprites; i++) {
- SpriteUpdate& update = updates.editItemAt(i);
- if (update.state.surfaceControl == NULL && update.state.wantSurfaceVisible()) {
- update.state.surfaceWidth = update.state.icon.bitmap.width();
- update.state.surfaceHeight = update.state.icon.bitmap.height();
- update.state.surfaceDrawn = false;
- update.state.surfaceVisible = false;
- update.state.surfaceControl = obtainSurface(
- update.state.surfaceWidth, update.state.surfaceHeight);
- if (update.state.surfaceControl != NULL) {
- update.surfaceChanged = surfaceChanged = true;
- }
- }
- }
-#endif
-
- // Resize sprites if needed, inside a global transaction.
-#ifdef HAVE_ANDROID_OS
- bool haveGlobalTransaction = false;
- for (size_t i = 0; i < numSprites; i++) {
- SpriteUpdate& update = updates.editItemAt(i);
- if (update.state.surfaceControl != NULL && update.state.wantSurfaceVisible()) {
- int32_t desiredWidth = update.state.icon.bitmap.width();
- int32_t desiredHeight = update.state.icon.bitmap.height();
- if (update.state.surfaceWidth < desiredWidth
- || update.state.surfaceHeight < desiredHeight) {
- if (!haveGlobalTransaction) {
- SurfaceComposerClient::openGlobalTransaction();
- haveGlobalTransaction = true;
- }
-
- status_t status = update.state.surfaceControl->setSize(desiredWidth, desiredHeight);
- if (status) {
- ALOGE("Error %d resizing sprite surface from %dx%d to %dx%d",
- status, update.state.surfaceWidth, update.state.surfaceHeight,
- desiredWidth, desiredHeight);
- } else {
- update.state.surfaceWidth = desiredWidth;
- update.state.surfaceHeight = desiredHeight;
- update.state.surfaceDrawn = false;
- update.surfaceChanged = surfaceChanged = true;
-
- if (update.state.surfaceVisible) {
- status = update.state.surfaceControl->hide();
- if (status) {
- ALOGE("Error %d hiding sprite surface after resize.", status);
- } else {
- update.state.surfaceVisible = false;
- }
- }
- }
- }
- }
- }
-#endif
-#ifdef HAVE_ANDROID_OS
- if (haveGlobalTransaction) {
- SurfaceComposerClient::closeGlobalTransaction();
- }
-#endif
-
- // Redraw sprites if needed.
- for (size_t i = 0; i < numSprites; i++) {
- SpriteUpdate& update = updates.editItemAt(i);
-
- if ((update.state.dirty & DIRTY_BITMAP) && update.state.surfaceDrawn) {
- update.state.surfaceDrawn = false;
- update.surfaceChanged = surfaceChanged = true;
- }
-
-#ifdef HAVE_ANDROID_OS
- if (update.state.surfaceControl != NULL && !update.state.surfaceDrawn
- && update.state.wantSurfaceVisible()) {
- sp<Surface> surface = update.state.surfaceControl->getSurface();
- ANativeWindow_Buffer outBuffer;
- status_t status = surface->lock(&outBuffer, NULL);
- if (status) {
- ALOGE("Error %d locking sprite surface before drawing.", status);
- } else {
- SkBitmap surfaceBitmap;
- ssize_t bpr = outBuffer.stride * bytesPerPixel(outBuffer.format);
- surfaceBitmap.setConfig(SkBitmap::kARGB_8888_Config,
- outBuffer.width, outBuffer.height, bpr);
- surfaceBitmap.setPixels(outBuffer.bits);
-
- SkCanvas surfaceCanvas(surfaceBitmap);
-
- SkPaint paint;
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
- surfaceCanvas.drawBitmap(update.state.icon.bitmap, 0, 0, &paint);
-
- if (outBuffer.width > uint32_t(update.state.icon.bitmap.width())) {
- paint.setColor(0); // transparent fill color
- surfaceCanvas.drawRectCoords(update.state.icon.bitmap.width(), 0,
- outBuffer.width, update.state.icon.bitmap.height(), paint);
- }
- if (outBuffer.height > uint32_t(update.state.icon.bitmap.height())) {
- paint.setColor(0); // transparent fill color
- surfaceCanvas.drawRectCoords(0, update.state.icon.bitmap.height(),
- outBuffer.width, outBuffer.height, paint);
- }
-
- status = surface->unlockAndPost();
- if (status) {
- ALOGE("Error %d unlocking and posting sprite surface after drawing.", status);
- } else {
- update.state.surfaceDrawn = true;
- update.surfaceChanged = surfaceChanged = true;
- }
- }
- }
-#endif
- }
-
-#ifdef HAVE_ANDROID_OS
- // Set sprite surface properties and make them visible.
- bool haveTransaction = false;
- for (size_t i = 0; i < numSprites; i++) {
- SpriteUpdate& update = updates.editItemAt(i);
- bool wantSurfaceVisibleAndDrawn = update.state.wantSurfaceVisible()
- && update.state.surfaceDrawn;
- bool becomingVisible = wantSurfaceVisibleAndDrawn && !update.state.surfaceVisible;
- bool becomingHidden = !wantSurfaceVisibleAndDrawn && update.state.surfaceVisible;
- if (update.state.surfaceControl != NULL && (becomingVisible || becomingHidden
- || (wantSurfaceVisibleAndDrawn && (update.state.dirty & (DIRTY_ALPHA
- | DIRTY_POSITION | DIRTY_TRANSFORMATION_MATRIX | DIRTY_LAYER
- | DIRTY_VISIBILITY | DIRTY_HOTSPOT))))) {
- status_t status;
- if (!haveTransaction) {
- SurfaceComposerClient::openGlobalTransaction();
- haveTransaction = true;
- }
-
- if (wantSurfaceVisibleAndDrawn
- && (becomingVisible || (update.state.dirty & DIRTY_ALPHA))) {
- status = update.state.surfaceControl->setAlpha(update.state.alpha);
- if (status) {
- ALOGE("Error %d setting sprite surface alpha.", status);
- }
- }
-
- if (wantSurfaceVisibleAndDrawn
- && (becomingVisible || (update.state.dirty & (DIRTY_POSITION
- | DIRTY_HOTSPOT)))) {
- status = update.state.surfaceControl->setPosition(
- update.state.positionX - update.state.icon.hotSpotX,
- update.state.positionY - update.state.icon.hotSpotY);
- if (status) {
- ALOGE("Error %d setting sprite surface position.", status);
- }
- }
-
- if (wantSurfaceVisibleAndDrawn
- && (becomingVisible
- || (update.state.dirty & DIRTY_TRANSFORMATION_MATRIX))) {
- status = update.state.surfaceControl->setMatrix(
- update.state.transformationMatrix.dsdx,
- update.state.transformationMatrix.dtdx,
- update.state.transformationMatrix.dsdy,
- update.state.transformationMatrix.dtdy);
- if (status) {
- ALOGE("Error %d setting sprite surface transformation matrix.", status);
- }
- }
-
- int32_t surfaceLayer = mOverlayLayer + update.state.layer;
- if (wantSurfaceVisibleAndDrawn
- && (becomingVisible || (update.state.dirty & DIRTY_LAYER))) {
- status = update.state.surfaceControl->setLayer(surfaceLayer);
- if (status) {
- ALOGE("Error %d setting sprite surface layer.", status);
- }
- }
-
- if (becomingVisible) {
- status = update.state.surfaceControl->show();
- if (status) {
- ALOGE("Error %d showing sprite surface.", status);
- } else {
- update.state.surfaceVisible = true;
- update.surfaceChanged = surfaceChanged = true;
- }
- } else if (becomingHidden) {
- status = update.state.surfaceControl->hide();
- if (status) {
- ALOGE("Error %d hiding sprite surface.", status);
- } else {
- update.state.surfaceVisible = false;
- update.surfaceChanged = surfaceChanged = true;
- }
- }
- }
- }
-#endif
-
-#ifdef HAVE_ANDROID_OS
- if (haveTransaction) {
- SurfaceComposerClient::closeGlobalTransaction();
- }
-#endif
-
-#ifdef HAVE_ANDROID_OS
- // If any surfaces were changed, write back the new surface properties to the sprites.
- if (surfaceChanged) { // acquire lock
- AutoMutex _l(mLock);
-
- for (size_t i = 0; i < numSprites; i++) {
- const SpriteUpdate& update = updates.itemAt(i);
-
- if (update.surfaceChanged) {
- update.sprite->setSurfaceLocked(update.state.surfaceControl,
- update.state.surfaceWidth, update.state.surfaceHeight,
- update.state.surfaceDrawn, update.state.surfaceVisible);
- }
- }
- } // release lock
-#endif
-
- // Clear the sprite update vector outside the lock. It is very important that
- // we do not clear sprite references inside the lock since we could be releasing
- // the last remaining reference to the sprite here which would result in the
- // sprite being deleted and the lock being reacquired by the sprite destructor
- // while already held.
- updates.clear();
-}
-
-void SpriteController::doDisposeSurfaces() {
-#ifdef HAVE_ANDROID_OS
- // Collect disposed surfaces.
- Vector<sp<SurfaceControl> > disposedSurfaces;
- { // acquire lock
- AutoMutex _l(mLock);
-
- disposedSurfaces = mLocked.disposedSurfaces;
- mLocked.disposedSurfaces.clear();
- } // release lock
-
- // Release the last reference to each surface outside of the lock.
- // We don't want the surfaces to be deleted while we are holding our lock.
- disposedSurfaces.clear();
-#endif
-}
-
-void SpriteController::ensureSurfaceComposerClient() {
-#ifdef HAVE_ANDROID_OS
- if (mSurfaceComposerClient == NULL) {
- mSurfaceComposerClient = new SurfaceComposerClient();
- }
-#endif
-}
-
-#ifdef HAVE_ANDROID_OS
-sp<SurfaceControl> SpriteController::obtainSurface(int32_t width, int32_t height) {
- ensureSurfaceComposerClient();
-
- sp<SurfaceControl> surfaceControl = mSurfaceComposerClient->createSurface(
- String8("Sprite"), width, height, PIXEL_FORMAT_RGBA_8888,
- ISurfaceComposerClient::eHidden);
- if (surfaceControl == NULL || !surfaceControl->isValid()) {
- ALOGE("Error creating sprite surface.");
- return NULL;
- }
- return surfaceControl;
-}
-#endif
-
-
-// --- SpriteController::SpriteImpl ---
-
-SpriteController::SpriteImpl::SpriteImpl(const sp<SpriteController> controller) :
- mController(controller) {
-}
-
-SpriteController::SpriteImpl::~SpriteImpl() {
- AutoMutex _m(mController->mLock);
-
-#ifdef HAVE_ANDROID_OS
- // Let the controller take care of deleting the last reference to sprite
- // surfaces so that we do not block the caller on an IPC here.
- if (mLocked.state.surfaceControl != NULL) {
- mController->disposeSurfaceLocked(mLocked.state.surfaceControl);
- mLocked.state.surfaceControl.clear();
- }
-#endif
-}
-
-void SpriteController::SpriteImpl::setIcon(const SpriteIcon& icon) {
- AutoMutex _l(mController->mLock);
-
-#ifdef HAVE_ANDROID_OS
- uint32_t dirty;
- if (icon.isValid()) {
- icon.bitmap.copyTo(&mLocked.state.icon.bitmap, SkBitmap::kARGB_8888_Config);
-
- if (!mLocked.state.icon.isValid()
- || mLocked.state.icon.hotSpotX != icon.hotSpotX
- || mLocked.state.icon.hotSpotY != icon.hotSpotY) {
- mLocked.state.icon.hotSpotX = icon.hotSpotX;
- mLocked.state.icon.hotSpotY = icon.hotSpotY;
- dirty = DIRTY_BITMAP | DIRTY_HOTSPOT;
- } else {
- dirty = DIRTY_BITMAP;
- }
- } else if (mLocked.state.icon.isValid()) {
- mLocked.state.icon.bitmap.reset();
- dirty = DIRTY_BITMAP | DIRTY_HOTSPOT;
- } else {
- return; // setting to invalid icon and already invalid so nothing to do
- }
-
- invalidateLocked(dirty);
-#endif
-}
-
-void SpriteController::SpriteImpl::setVisible(bool visible) {
- AutoMutex _l(mController->mLock);
-
- if (mLocked.state.visible != visible) {
- mLocked.state.visible = visible;
- invalidateLocked(DIRTY_VISIBILITY);
- }
-}
-
-void SpriteController::SpriteImpl::setPosition(float x, float y) {
- AutoMutex _l(mController->mLock);
-
- if (mLocked.state.positionX != x || mLocked.state.positionY != y) {
- mLocked.state.positionX = x;
- mLocked.state.positionY = y;
- invalidateLocked(DIRTY_POSITION);
- }
-}
-
-void SpriteController::SpriteImpl::setLayer(int32_t layer) {
- AutoMutex _l(mController->mLock);
-
- if (mLocked.state.layer != layer) {
- mLocked.state.layer = layer;
- invalidateLocked(DIRTY_LAYER);
- }
-}
-
-void SpriteController::SpriteImpl::setAlpha(float alpha) {
- AutoMutex _l(mController->mLock);
-
- if (mLocked.state.alpha != alpha) {
- mLocked.state.alpha = alpha;
- invalidateLocked(DIRTY_ALPHA);
- }
-}
-
-void SpriteController::SpriteImpl::setTransformationMatrix(
- const SpriteTransformationMatrix& matrix) {
- AutoMutex _l(mController->mLock);
-
- if (mLocked.state.transformationMatrix != matrix) {
- mLocked.state.transformationMatrix = matrix;
- invalidateLocked(DIRTY_TRANSFORMATION_MATRIX);
- }
-}
-
-void SpriteController::SpriteImpl::invalidateLocked(uint32_t dirty) {
- bool wasDirty = mLocked.state.dirty;
- mLocked.state.dirty |= dirty;
-
- if (!wasDirty) {
- mController->invalidateSpriteLocked(this);
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/SpriteController.h b/widget/gonk/libui/SpriteController.h
deleted file mode 100644
index 4926095ec..000000000
--- a/widget/gonk/libui/SpriteController.h
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UI_SPRITES_H
-#define _UI_SPRITES_H
-
-#include <utils/RefBase.h>
-#include <utils/Looper.h>
-
-#ifdef HAVE_ANDROID_OS
-#include <gui/SurfaceComposerClient.h>
-#endif
-
-#include <SkBitmap.h>
-
-namespace android {
-
-/*
- * Transformation matrix for a sprite.
- */
-struct SpriteTransformationMatrix {
- inline SpriteTransformationMatrix() : dsdx(1.0f), dtdx(0.0f), dsdy(0.0f), dtdy(1.0f) { }
- inline SpriteTransformationMatrix(float dsdx, float dtdx, float dsdy, float dtdy) :
- dsdx(dsdx), dtdx(dtdx), dsdy(dsdy), dtdy(dtdy) { }
-
- float dsdx;
- float dtdx;
- float dsdy;
- float dtdy;
-
- inline bool operator== (const SpriteTransformationMatrix& other) {
- return dsdx == other.dsdx
- && dtdx == other.dtdx
- && dsdy == other.dsdy
- && dtdy == other.dtdy;
- }
-
- inline bool operator!= (const SpriteTransformationMatrix& other) {
- return !(*this == other);
- }
-};
-
-/*
- * Icon that a sprite displays, including its hotspot.
- */
-struct SpriteIcon {
- inline SpriteIcon() : hotSpotX(0), hotSpotY(0) { }
-#ifdef HAVE_ANDROID_OS
- inline SpriteIcon(const SkBitmap& bitmap, float hotSpotX, float hotSpotY) :
- bitmap(bitmap), hotSpotX(hotSpotX), hotSpotY(hotSpotY) { }
-
- SkBitmap bitmap;
-#endif
- float hotSpotX;
- float hotSpotY;
-
- inline SpriteIcon copy() const {
-#ifdef HAVE_ANDROID_OS
- SkBitmap bitmapCopy;
- bitmap.copyTo(&bitmapCopy, SkBitmap::kARGB_8888_Config);
- return SpriteIcon(bitmapCopy, hotSpotX, hotSpotY);
-#else
- return SpriteIcon();
-#endif
- }
-
- inline void reset() {
-#ifdef HAVE_ANDROID_OS
- bitmap.reset();
- hotSpotX = 0;
- hotSpotY = 0;
-#endif
- }
-
- inline bool isValid() const {
-#ifdef HAVE_ANDROID_OS
- return !bitmap.isNull() && !bitmap.empty();
-#else
- return false;
-#endif
- }
-};
-
-/*
- * A sprite is a simple graphical object that is displayed on-screen above other layers.
- * The basic sprite class is an interface.
- * The implementation is provided by the sprite controller.
- */
-class Sprite : public RefBase {
-protected:
- Sprite() { }
- virtual ~Sprite() { }
-
-public:
- enum {
- // The base layer for pointer sprites.
- BASE_LAYER_POINTER = 0, // reserve space for 1 pointer
-
- // The base layer for spot sprites.
- BASE_LAYER_SPOT = 1, // reserve space for MAX_POINTER_ID spots
- };
-
- /* Sets the bitmap that is drawn by the sprite.
- * The sprite retains a copy of the bitmap for subsequent rendering. */
- virtual void setIcon(const SpriteIcon& icon) = 0;
-
- inline void clearIcon() {
- setIcon(SpriteIcon());
- }
-
- /* Sets whether the sprite is visible. */
- virtual void setVisible(bool visible) = 0;
-
- /* Sets the sprite position on screen, relative to the sprite's hot spot. */
- virtual void setPosition(float x, float y) = 0;
-
- /* Sets the layer of the sprite, relative to the system sprite overlay layer.
- * Layer 0 is the overlay layer, > 0 appear above this layer. */
- virtual void setLayer(int32_t layer) = 0;
-
- /* Sets the sprite alpha blend ratio between 0.0 and 1.0. */
- virtual void setAlpha(float alpha) = 0;
-
- /* Sets the sprite transformation matrix. */
- virtual void setTransformationMatrix(const SpriteTransformationMatrix& matrix) = 0;
-};
-
-/*
- * Displays sprites on the screen.
- *
- * This interface is used by PointerController and SpotController to draw pointers or
- * spot representations of fingers. It is not intended for general purpose use
- * by other components.
- *
- * All sprite position updates and rendering is performed asynchronously.
- *
- * Clients are responsible for animating sprites by periodically updating their properties.
- */
-class SpriteController : public MessageHandler {
-protected:
- virtual ~SpriteController();
-
-public:
- SpriteController(const sp<Looper>& looper, int32_t overlayLayer);
-
- /* Creates a new sprite, initially invisible. */
- sp<Sprite> createSprite();
-
- /* Opens or closes a transaction to perform a batch of sprite updates as part of
- * a single operation such as setPosition and setAlpha. It is not necessary to
- * open a transaction when updating a single property.
- * Calls to openTransaction() nest and must be matched by an equal number
- * of calls to closeTransaction(). */
- void openTransaction();
- void closeTransaction();
-
-private:
- enum {
- MSG_UPDATE_SPRITES,
- MSG_DISPOSE_SURFACES,
- };
-
- enum {
- DIRTY_BITMAP = 1 << 0,
- DIRTY_ALPHA = 1 << 1,
- DIRTY_POSITION = 1 << 2,
- DIRTY_TRANSFORMATION_MATRIX = 1 << 3,
- DIRTY_LAYER = 1 << 4,
- DIRTY_VISIBILITY = 1 << 5,
- DIRTY_HOTSPOT = 1 << 6,
- };
-
- /* Describes the state of a sprite.
- * This structure is designed so that it can be copied during updates so that
- * surfaces can be resized and redrawn without blocking the client by holding a lock
- * on the sprites for a long time.
- * Note that the SkBitmap holds a reference to a shared (and immutable) pixel ref. */
- struct SpriteState {
- inline SpriteState() :
- dirty(0), visible(false),
- positionX(0), positionY(0), layer(0), alpha(1.0f),
- surfaceWidth(0), surfaceHeight(0), surfaceDrawn(false), surfaceVisible(false) {
- }
-
- uint32_t dirty;
-
- SpriteIcon icon;
- bool visible;
- float positionX;
- float positionY;
- int32_t layer;
- float alpha;
- SpriteTransformationMatrix transformationMatrix;
-
-#ifdef HAVE_ANDROID_OS
- sp<SurfaceControl> surfaceControl;
-#endif
- int32_t surfaceWidth;
- int32_t surfaceHeight;
- bool surfaceDrawn;
- bool surfaceVisible;
-
- inline bool wantSurfaceVisible() const {
- return visible && alpha > 0.0f && icon.isValid();
- }
- };
-
- /* Client interface for a sprite.
- * Requests acquire a lock on the controller, update local state and request the
- * controller to invalidate the sprite.
- * The real heavy lifting of creating, resizing and redrawing surfaces happens
- * asynchronously with no locks held except in short critical section to copy
- * the sprite state before the work and update the sprite surface control afterwards.
- */
- class SpriteImpl : public Sprite {
- protected:
- virtual ~SpriteImpl();
-
- public:
- SpriteImpl(const sp<SpriteController> controller);
-
- virtual void setIcon(const SpriteIcon& icon);
- virtual void setVisible(bool visible);
- virtual void setPosition(float x, float y);
- virtual void setLayer(int32_t layer);
- virtual void setAlpha(float alpha);
- virtual void setTransformationMatrix(const SpriteTransformationMatrix& matrix);
-
- inline const SpriteState& getStateLocked() const {
- return mLocked.state;
- }
-
- inline void resetDirtyLocked() {
- mLocked.state.dirty = 0;
- }
-
-#ifdef HAVE_ANDROID_OS
- inline void setSurfaceLocked(const sp<SurfaceControl>& surfaceControl,
- int32_t width, int32_t height, bool drawn, bool visible) {
- mLocked.state.surfaceControl = surfaceControl;
- mLocked.state.surfaceWidth = width;
- mLocked.state.surfaceHeight = height;
- mLocked.state.surfaceDrawn = drawn;
- mLocked.state.surfaceVisible = visible;
- }
-#endif
-
- private:
- sp<SpriteController> mController;
-
- struct Locked {
- SpriteState state;
- } mLocked; // guarded by mController->mLock
-
- void invalidateLocked(uint32_t dirty);
- };
-
- /* Stores temporary information collected during the sprite update cycle. */
- struct SpriteUpdate {
- inline SpriteUpdate() : surfaceChanged(false) { }
- inline SpriteUpdate(const sp<SpriteImpl> sprite, const SpriteState& state) :
- sprite(sprite), state(state), surfaceChanged(false) {
- }
-
- sp<SpriteImpl> sprite;
- SpriteState state;
- bool surfaceChanged;
- };
-
- mutable Mutex mLock;
-
- sp<Looper> mLooper;
- const int32_t mOverlayLayer;
-#ifdef HAVE_ANDROID_OS
- sp<WeakMessageHandler> mHandler;
-
- sp<SurfaceComposerClient> mSurfaceComposerClient;
-#endif
-
- struct Locked {
- Vector<sp<SpriteImpl> > invalidatedSprites;
-#ifdef HAVE_ANDROID_OS
- Vector<sp<SurfaceControl> > disposedSurfaces;
-#endif
- uint32_t transactionNestingCount;
- bool deferredSpriteUpdate;
- } mLocked; // guarded by mLock
-
- void invalidateSpriteLocked(const sp<SpriteImpl>& sprite);
-#ifdef HAVE_ANDROID_OS
- void disposeSurfaceLocked(const sp<SurfaceControl>& surfaceControl);
-
- void handleMessage(const Message& message);
-#endif
- void doUpdateSprites();
- void doDisposeSurfaces();
-
- void ensureSurfaceComposerClient();
-#ifdef HAVE_ANDROID_OS
- sp<SurfaceControl> obtainSurface(int32_t width, int32_t height);
-#endif
-};
-
-} // namespace android
-
-#endif // _UI_SPRITES_H
diff --git a/widget/gonk/libui/Tokenizer.cpp b/widget/gonk/libui/Tokenizer.cpp
deleted file mode 100644
index 2f585cb4e..000000000
--- a/widget/gonk/libui/Tokenizer.cpp
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "Tokenizer"
-#include "cutils_log.h"
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include "Tokenizer.h"
-
-// Enables debug output for the tokenizer.
-#define DEBUG_TOKENIZER 0
-
-
-namespace android {
-
-static inline bool isDelimiter(char ch, const char* delimiters) {
- return strchr(delimiters, ch) != NULL;
-}
-
-Tokenizer::Tokenizer(const String8& filename, FileMap* fileMap, char* buffer,
- bool ownBuffer, size_t length) :
- mFilename(filename), mFileMap(fileMap),
- mBuffer(buffer), mOwnBuffer(ownBuffer), mLength(length),
- mCurrent(buffer), mLineNumber(1) {
-}
-
-Tokenizer::~Tokenizer() {
- if (mFileMap) {
- mFileMap->release();
- }
- if (mOwnBuffer) {
- delete[] mBuffer;
- }
-}
-
-status_t Tokenizer::open(const String8& filename, Tokenizer** outTokenizer) {
- *outTokenizer = NULL;
-
- int result = NO_ERROR;
- int fd = ::open(filename.string(), O_RDONLY);
- if (fd < 0) {
- result = -errno;
- ALOGE("Error opening file '%s', %s.", filename.string(), strerror(errno));
- } else {
- struct stat stat;
- if (fstat(fd, &stat)) {
- result = -errno;
- ALOGE("Error getting size of file '%s', %s.", filename.string(), strerror(errno));
- } else {
- size_t length = size_t(stat.st_size);
-
- FileMap* fileMap = new FileMap();
- bool ownBuffer = false;
- char* buffer;
- if (fileMap->create(NULL, fd, 0, length, true)) {
- fileMap->advise(FileMap::SEQUENTIAL);
- buffer = static_cast<char*>(fileMap->getDataPtr());
- } else {
- fileMap->release();
- fileMap = NULL;
-
- // Fall back to reading into a buffer since we can't mmap files in sysfs.
- // The length we obtained from stat is wrong too (it will always be 4096)
- // so we must trust that read will read the entire file.
- buffer = new char[length];
- ownBuffer = true;
- ssize_t nrd = read(fd, buffer, length);
- if (nrd < 0) {
- result = -errno;
- ALOGE("Error reading file '%s', %s.", filename.string(), strerror(errno));
- delete[] buffer;
- buffer = NULL;
- } else {
- length = size_t(nrd);
- }
- }
-
- if (!result) {
- *outTokenizer = new Tokenizer(filename, fileMap, buffer, ownBuffer, length);
- }
- }
- close(fd);
- }
- return result;
-}
-
-status_t Tokenizer::fromContents(const String8& filename,
- const char* contents, Tokenizer** outTokenizer) {
- *outTokenizer = new Tokenizer(filename, NULL,
- const_cast<char*>(contents), false, strlen(contents));
- return OK;
-}
-
-String8 Tokenizer::getLocation() const {
- String8 result;
- result.appendFormat("%s:%d", mFilename.string(), mLineNumber);
- return result;
-}
-
-String8 Tokenizer::peekRemainderOfLine() const {
- const char* end = getEnd();
- const char* eol = mCurrent;
- while (eol != end) {
- char ch = *eol;
- if (ch == '\n') {
- break;
- }
- eol += 1;
- }
- return String8(mCurrent, eol - mCurrent);
-}
-
-String8 Tokenizer::nextToken(const char* delimiters) {
-#if DEBUG_TOKENIZER
- ALOGD("nextToken");
-#endif
- const char* end = getEnd();
- const char* tokenStart = mCurrent;
- while (mCurrent != end) {
- char ch = *mCurrent;
- if (ch == '\n' || isDelimiter(ch, delimiters)) {
- break;
- }
- mCurrent += 1;
- }
- return String8(tokenStart, mCurrent - tokenStart);
-}
-
-void Tokenizer::nextLine() {
-#if DEBUG_TOKENIZER
- ALOGD("nextLine");
-#endif
- const char* end = getEnd();
- while (mCurrent != end) {
- char ch = *(mCurrent++);
- if (ch == '\n') {
- mLineNumber += 1;
- break;
- }
- }
-}
-
-void Tokenizer::skipDelimiters(const char* delimiters) {
-#if DEBUG_TOKENIZER
- ALOGD("skipDelimiters");
-#endif
- const char* end = getEnd();
- while (mCurrent != end) {
- char ch = *mCurrent;
- if (ch == '\n' || !isDelimiter(ch, delimiters)) {
- break;
- }
- mCurrent += 1;
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/Tokenizer.h b/widget/gonk/libui/Tokenizer.h
deleted file mode 100644
index bb25f374c..000000000
--- a/widget/gonk/libui/Tokenizer.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _UTILS_TOKENIZER_H
-#define _UTILS_TOKENIZER_H
-
-#include <assert.h>
-#include <utils/Errors.h>
-#include <utils/FileMap.h>
-#include <utils/String8.h>
-
-namespace android {
-
-/**
- * A simple tokenizer for loading and parsing ASCII text files line by line.
- */
-class Tokenizer {
- Tokenizer(const String8& filename, FileMap* fileMap, char* buffer,
- bool ownBuffer, size_t length);
-
-public:
- ~Tokenizer();
-
- /**
- * Opens a file and maps it into memory.
- *
- * Returns NO_ERROR and a tokenizer for the file, if successful.
- * Otherwise returns an error and sets outTokenizer to NULL.
- */
- static status_t open(const String8& filename, Tokenizer** outTokenizer);
-
- /**
- * Prepares to tokenize the contents of a string.
- *
- * Returns NO_ERROR and a tokenizer for the string, if successful.
- * Otherwise returns an error and sets outTokenizer to NULL.
- */
- static status_t fromContents(const String8& filename,
- const char* contents, Tokenizer** outTokenizer);
-
- /**
- * Returns true if at the end of the file.
- */
- inline bool isEof() const { return mCurrent == getEnd(); }
-
- /**
- * Returns true if at the end of the line or end of the file.
- */
- inline bool isEol() const { return isEof() || *mCurrent == '\n'; }
-
- /**
- * Gets the name of the file.
- */
- inline String8 getFilename() const { return mFilename; }
-
- /**
- * Gets a 1-based line number index for the current position.
- */
- inline int32_t getLineNumber() const { return mLineNumber; }
-
- /**
- * Formats a location string consisting of the filename and current line number.
- * Returns a string like "MyFile.txt:33".
- */
- String8 getLocation() const;
-
- /**
- * Gets the character at the current position.
- * Returns null at end of file.
- */
- inline char peekChar() const { return isEof() ? '\0' : *mCurrent; }
-
- /**
- * Gets the remainder of the current line as a string, excluding the newline character.
- */
- String8 peekRemainderOfLine() const;
-
- /**
- * Gets the character at the current position and advances past it.
- * Returns null at end of file.
- */
- inline char nextChar() { return isEof() ? '\0' : *(mCurrent++); }
-
- /**
- * Gets the next token on this line stopping at the specified delimiters
- * or the end of the line whichever comes first and advances past it.
- * Also stops at embedded nulls.
- * Returns the token or an empty string if the current character is a delimiter
- * or is at the end of the line.
- */
- String8 nextToken(const char* delimiters);
-
- /**
- * Advances to the next line.
- * Does nothing if already at the end of the file.
- */
- void nextLine();
-
- /**
- * Skips over the specified delimiters in the line.
- * Also skips embedded nulls.
- */
- void skipDelimiters(const char* delimiters);
-
-private:
- Tokenizer(const Tokenizer& other); // not copyable
-
- String8 mFilename;
- FileMap* mFileMap;
- char* mBuffer;
- bool mOwnBuffer;
- size_t mLength;
-
- const char* mCurrent;
- int32_t mLineNumber;
-
- inline const char* getEnd() const { return mBuffer + mLength; }
-
-};
-
-} // namespace android
-
-#endif // _UTILS_TOKENIZER_H
diff --git a/widget/gonk/libui/Trace.h b/widget/gonk/libui/Trace.h
deleted file mode 100644
index 24fbfb602..000000000
--- a/widget/gonk/libui/Trace.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef ANDROID_TRACE_H
-#define ANDROID_TRACE_H
-
-#include <fcntl.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/compiler.h>
-#include <utils/threads.h>
-#include "cutils_trace.h"
-
-// See <cutils/trace.h> for more ATRACE_* macros.
-
-// ATRACE_NAME traces the beginning and end of the current scope. To trace
-// the correct start and end times this macro should be declared first in the
-// scope body.
-#define ATRACE_NAME(name) android::ScopedTrace ___tracer(ATRACE_TAG, name)
-// ATRACE_CALL is an ATRACE_NAME that uses the current function name.
-#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
-
-namespace android {
-
-class ScopedTrace {
-public:
-inline ScopedTrace(uint64_t tag, const char* name)
- : mTag(tag) {
-#ifdef HAVE_ANDROID_OS
- atrace_begin(mTag,name);
-#endif
-}
-
-inline ~ScopedTrace() {
-#ifdef HAVE_ANDROID_OS
- atrace_end(mTag);
-#endif
-}
-
-private:
- uint64_t mTag;
-};
-
-}; // namespace android
-
-#endif // ANDROID_TRACE_H
diff --git a/widget/gonk/libui/VelocityControl.cpp b/widget/gonk/libui/VelocityControl.cpp
deleted file mode 100644
index 31365a220..000000000
--- a/widget/gonk/libui/VelocityControl.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "VelocityControl"
-//#define LOG_NDEBUG 0
-
-// Log debug messages about acceleration.
-#define DEBUG_ACCELERATION 0
-
-#include <math.h>
-#include <limits.h>
-
-#include "VelocityControl.h"
-#include <utils/BitSet.h>
-#include <utils/Timers.h>
-
-namespace android {
-
-// --- VelocityControl ---
-
-const nsecs_t VelocityControl::STOP_TIME;
-
-VelocityControl::VelocityControl() {
- reset();
-}
-
-void VelocityControl::setParameters(const VelocityControlParameters& parameters) {
- mParameters = parameters;
- reset();
-}
-
-void VelocityControl::reset() {
- mLastMovementTime = LLONG_MIN;
- mRawPosition.x = 0;
- mRawPosition.y = 0;
- mVelocityTracker.clear();
-}
-
-void VelocityControl::move(nsecs_t eventTime, float* deltaX, float* deltaY) {
- if ((deltaX && *deltaX) || (deltaY && *deltaY)) {
- if (eventTime >= mLastMovementTime + STOP_TIME) {
-#if DEBUG_ACCELERATION
- ALOGD("VelocityControl: stopped, last movement was %0.3fms ago",
- (eventTime - mLastMovementTime) * 0.000001f);
-#endif
- reset();
- }
-
- mLastMovementTime = eventTime;
- if (deltaX) {
- mRawPosition.x += *deltaX;
- }
- if (deltaY) {
- mRawPosition.y += *deltaY;
- }
- mVelocityTracker.addMovement(eventTime, BitSet32(BitSet32::valueForBit(0)), &mRawPosition);
-
- float vx, vy;
- float scale = mParameters.scale;
- if (mVelocityTracker.getVelocity(0, &vx, &vy)) {
- float speed = hypotf(vx, vy) * scale;
- if (speed >= mParameters.highThreshold) {
- // Apply full acceleration above the high speed threshold.
- scale *= mParameters.acceleration;
- } else if (speed > mParameters.lowThreshold) {
- // Linearly interpolate the acceleration to apply between the low and high
- // speed thresholds.
- scale *= 1 + (speed - mParameters.lowThreshold)
- / (mParameters.highThreshold - mParameters.lowThreshold)
- * (mParameters.acceleration - 1);
- }
-
-#if DEBUG_ACCELERATION
- ALOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): "
- "vx=%0.3f, vy=%0.3f, speed=%0.3f, accel=%0.3f",
- mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
- mParameters.acceleration,
- vx, vy, speed, scale / mParameters.scale);
-#endif
- } else {
-#if DEBUG_ACCELERATION
- ALOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): unknown velocity",
- mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
- mParameters.acceleration);
-#endif
- }
-
- if (deltaX) {
- *deltaX *= scale;
- }
- if (deltaY) {
- *deltaY *= scale;
- }
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/VelocityControl.h b/widget/gonk/libui/VelocityControl.h
deleted file mode 100644
index 8a2c695d6..000000000
--- a/widget/gonk/libui/VelocityControl.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_VELOCITY_CONTROL_H
-#define _ANDROIDFW_VELOCITY_CONTROL_H
-
-#include "Input.h"
-#include "VelocityTracker.h"
-#include <utils/Timers.h>
-
-namespace android {
-
-/*
- * Specifies parameters that govern pointer or wheel acceleration.
- */
-struct VelocityControlParameters {
- // A scale factor that is multiplied with the raw velocity deltas
- // prior to applying any other velocity control factors. The scale
- // factor should be used to adapt the input device resolution
- // (eg. counts per inch) to the output device resolution (eg. pixels per inch).
- //
- // Must be a positive value.
- // Default is 1.0 (no scaling).
- float scale;
-
- // The scaled speed at which acceleration begins to be applied.
- // This value establishes the upper bound of a low speed regime for
- // small precise motions that are performed without any acceleration.
- //
- // Must be a non-negative value.
- // Default is 0.0 (no low threshold).
- float lowThreshold;
-
- // The scaled speed at which maximum acceleration is applied.
- // The difference between highThreshold and lowThreshold controls
- // the range of speeds over which the acceleration factor is interpolated.
- // The wider the range, the smoother the acceleration.
- //
- // Must be a non-negative value greater than or equal to lowThreshold.
- // Default is 0.0 (no high threshold).
- float highThreshold;
-
- // The acceleration factor.
- // When the speed is above the low speed threshold, the velocity will scaled
- // by an interpolated value between 1.0 and this amount.
- //
- // Must be a positive greater than or equal to 1.0.
- // Default is 1.0 (no acceleration).
- float acceleration;
-
- VelocityControlParameters() :
- scale(1.0f), lowThreshold(0.0f), highThreshold(0.0f), acceleration(1.0f) {
- }
-
- VelocityControlParameters(float scale, float lowThreshold,
- float highThreshold, float acceleration) :
- scale(scale), lowThreshold(lowThreshold),
- highThreshold(highThreshold), acceleration(acceleration) {
- }
-};
-
-/*
- * Implements mouse pointer and wheel speed control and acceleration.
- */
-class VelocityControl {
-public:
- VelocityControl();
-
- /* Sets the various parameters. */
- void setParameters(const VelocityControlParameters& parameters);
-
- /* Resets the current movement counters to zero.
- * This has the effect of nullifying any acceleration. */
- void reset();
-
- /* Translates a raw movement delta into an appropriately
- * scaled / accelerated delta based on the current velocity. */
- void move(nsecs_t eventTime, float* deltaX, float* deltaY);
-
-private:
- // If no movements are received within this amount of time,
- // we assume the movement has stopped and reset the movement counters.
- static const nsecs_t STOP_TIME = 500 * 1000000; // 500 ms
-
- VelocityControlParameters mParameters;
-
- nsecs_t mLastMovementTime;
- VelocityTracker::Position mRawPosition;
- VelocityTracker mVelocityTracker;
-};
-
-} // namespace android
-
-#endif // _ANDROIDFW_VELOCITY_CONTROL_H
diff --git a/widget/gonk/libui/VelocityTracker.cpp b/widget/gonk/libui/VelocityTracker.cpp
deleted file mode 100644
index 11a8bf7fc..000000000
--- a/widget/gonk/libui/VelocityTracker.cpp
+++ /dev/null
@@ -1,929 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "VelocityTracker"
-//#define LOG_NDEBUG 0
-#include "cutils_log.h"
-
-// Log debug messages about velocity tracking.
-#define DEBUG_VELOCITY 0
-
-// Log debug messages about the progress of the algorithm itself.
-#define DEBUG_STRATEGY 0
-
-#include <math.h>
-#include <limits.h>
-
-#include "VelocityTracker.h"
-#include <utils/BitSet.h>
-#include <utils/String8.h>
-#include <utils/Timers.h>
-
-#include <cutils/properties.h>
-
-namespace android {
-
-// Nanoseconds per milliseconds.
-static const nsecs_t NANOS_PER_MS = 1000000;
-
-// Threshold for determining that a pointer has stopped moving.
-// Some input devices do not send ACTION_MOVE events in the case where a pointer has
-// stopped. We need to detect this case so that we can accurately predict the
-// velocity after the pointer starts moving again.
-static const nsecs_t ASSUME_POINTER_STOPPED_TIME = 40 * NANOS_PER_MS;
-
-
-static float vectorDot(const float* a, const float* b, uint32_t m) {
- float r = 0;
- while (m--) {
- r += *(a++) * *(b++);
- }
- return r;
-}
-
-static float vectorNorm(const float* a, uint32_t m) {
- float r = 0;
- while (m--) {
- float t = *(a++);
- r += t * t;
- }
- return sqrtf(r);
-}
-
-#if DEBUG_STRATEGY || DEBUG_VELOCITY
-static String8 vectorToString(const float* a, uint32_t m) {
- String8 str;
- str.append("[");
- while (m--) {
- str.appendFormat(" %f", *(a++));
- if (m) {
- str.append(",");
- }
- }
- str.append(" ]");
- return str;
-}
-
-static String8 matrixToString(const float* a, uint32_t m, uint32_t n, bool rowMajor) {
- String8 str;
- str.append("[");
- for (size_t i = 0; i < m; i++) {
- if (i) {
- str.append(",");
- }
- str.append(" [");
- for (size_t j = 0; j < n; j++) {
- if (j) {
- str.append(",");
- }
- str.appendFormat(" %f", a[rowMajor ? i * n + j : j * m + i]);
- }
- str.append(" ]");
- }
- str.append(" ]");
- return str;
-}
-#endif
-
-
-// --- VelocityTracker ---
-
-// The default velocity tracker strategy.
-// Although other strategies are available for testing and comparison purposes,
-// this is the strategy that applications will actually use. Be very careful
-// when adjusting the default strategy because it can dramatically affect
-// (often in a bad way) the user experience.
-const char* VelocityTracker::DEFAULT_STRATEGY = "lsq2";
-
-VelocityTracker::VelocityTracker(const char* strategy) :
- mLastEventTime(0), mCurrentPointerIdBits(0), mActivePointerId(-1) {
- char value[PROPERTY_VALUE_MAX];
-
- // Allow the default strategy to be overridden using a system property for debugging.
- if (!strategy) {
- int length = property_get("debug.velocitytracker.strategy", value, NULL);
- if (length > 0) {
- strategy = value;
- } else {
- strategy = DEFAULT_STRATEGY;
- }
- }
-
- // Configure the strategy.
- if (!configureStrategy(strategy)) {
- ALOGD("Unrecognized velocity tracker strategy name '%s'.", strategy);
- if (!configureStrategy(DEFAULT_STRATEGY)) {
- LOG_ALWAYS_FATAL("Could not create the default velocity tracker strategy '%s'!",
- strategy);
- }
- }
-}
-
-VelocityTracker::~VelocityTracker() {
- delete mStrategy;
-}
-
-bool VelocityTracker::configureStrategy(const char* strategy) {
- mStrategy = createStrategy(strategy);
- return mStrategy != NULL;
-}
-
-VelocityTrackerStrategy* VelocityTracker::createStrategy(const char* strategy) {
- if (!strcmp("lsq1", strategy)) {
- // 1st order least squares. Quality: POOR.
- // Frequently underfits the touch data especially when the finger accelerates
- // or changes direction. Often underestimates velocity. The direction
- // is overly influenced by historical touch points.
- return new LeastSquaresVelocityTrackerStrategy(1);
- }
- if (!strcmp("lsq2", strategy)) {
- // 2nd order least squares. Quality: VERY GOOD.
- // Pretty much ideal, but can be confused by certain kinds of touch data,
- // particularly if the panel has a tendency to generate delayed,
- // duplicate or jittery touch coordinates when the finger is released.
- return new LeastSquaresVelocityTrackerStrategy(2);
- }
- if (!strcmp("lsq3", strategy)) {
- // 3rd order least squares. Quality: UNUSABLE.
- // Frequently overfits the touch data yielding wildly divergent estimates
- // of the velocity when the finger is released.
- return new LeastSquaresVelocityTrackerStrategy(3);
- }
- if (!strcmp("wlsq2-delta", strategy)) {
- // 2nd order weighted least squares, delta weighting. Quality: EXPERIMENTAL
- return new LeastSquaresVelocityTrackerStrategy(2,
- LeastSquaresVelocityTrackerStrategy::WEIGHTING_DELTA);
- }
- if (!strcmp("wlsq2-central", strategy)) {
- // 2nd order weighted least squares, central weighting. Quality: EXPERIMENTAL
- return new LeastSquaresVelocityTrackerStrategy(2,
- LeastSquaresVelocityTrackerStrategy::WEIGHTING_CENTRAL);
- }
- if (!strcmp("wlsq2-recent", strategy)) {
- // 2nd order weighted least squares, recent weighting. Quality: EXPERIMENTAL
- return new LeastSquaresVelocityTrackerStrategy(2,
- LeastSquaresVelocityTrackerStrategy::WEIGHTING_RECENT);
- }
- if (!strcmp("int1", strategy)) {
- // 1st order integrating filter. Quality: GOOD.
- // Not as good as 'lsq2' because it cannot estimate acceleration but it is
- // more tolerant of errors. Like 'lsq1', this strategy tends to underestimate
- // the velocity of a fling but this strategy tends to respond to changes in
- // direction more quickly and accurately.
- return new IntegratingVelocityTrackerStrategy(1);
- }
- if (!strcmp("int2", strategy)) {
- // 2nd order integrating filter. Quality: EXPERIMENTAL.
- // For comparison purposes only. Unlike 'int1' this strategy can compensate
- // for acceleration but it typically overestimates the effect.
- return new IntegratingVelocityTrackerStrategy(2);
- }
- if (!strcmp("legacy", strategy)) {
- // Legacy velocity tracker algorithm. Quality: POOR.
- // For comparison purposes only. This algorithm is strongly influenced by
- // old data points, consistently underestimates velocity and takes a very long
- // time to adjust to changes in direction.
- return new LegacyVelocityTrackerStrategy();
- }
- return NULL;
-}
-
-void VelocityTracker::clear() {
- mCurrentPointerIdBits.clear();
- mActivePointerId = -1;
-
- mStrategy->clear();
-}
-
-void VelocityTracker::clearPointers(BitSet32 idBits) {
- BitSet32 remainingIdBits(mCurrentPointerIdBits.value & ~idBits.value);
- mCurrentPointerIdBits = remainingIdBits;
-
- if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) {
- mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
- }
-
- mStrategy->clearPointers(idBits);
-}
-
-void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
- while (idBits.count() > MAX_POINTERS) {
- idBits.clearLastMarkedBit();
- }
-
- if ((mCurrentPointerIdBits.value & idBits.value)
- && eventTime >= mLastEventTime + ASSUME_POINTER_STOPPED_TIME) {
-#if DEBUG_VELOCITY
- ALOGD("VelocityTracker: stopped for %0.3f ms, clearing state.",
- (eventTime - mLastEventTime) * 0.000001f);
-#endif
- // We have not received any movements for too long. Assume that all pointers
- // have stopped.
- mStrategy->clear();
- }
- mLastEventTime = eventTime;
-
- mCurrentPointerIdBits = idBits;
- if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) {
- mActivePointerId = idBits.isEmpty() ? -1 : idBits.firstMarkedBit();
- }
-
- mStrategy->addMovement(eventTime, idBits, positions);
-
-#if DEBUG_VELOCITY
- ALOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x, activePointerId=%d",
- eventTime, idBits.value, mActivePointerId);
- for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
- uint32_t id = iterBits.firstMarkedBit();
- uint32_t index = idBits.getIndexOfBit(id);
- iterBits.clearBit(id);
- Estimator estimator;
- getEstimator(id, &estimator);
- ALOGD(" %d: position (%0.3f, %0.3f), "
- "estimator (degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f)",
- id, positions[index].x, positions[index].y,
- int(estimator.degree),
- vectorToString(estimator.xCoeff, estimator.degree + 1).string(),
- vectorToString(estimator.yCoeff, estimator.degree + 1).string(),
- estimator.confidence);
- }
-#endif
-}
-
-void VelocityTracker::addMovement(const MotionEvent* event) {
- int32_t actionMasked = event->getActionMasked();
-
- switch (actionMasked) {
- case AMOTION_EVENT_ACTION_DOWN:
- case AMOTION_EVENT_ACTION_HOVER_ENTER:
- // Clear all pointers on down before adding the new movement.
- clear();
- break;
- case AMOTION_EVENT_ACTION_POINTER_DOWN: {
- // Start a new movement trace for a pointer that just went down.
- // We do this on down instead of on up because the client may want to query the
- // final velocity for a pointer that just went up.
- BitSet32 downIdBits;
- downIdBits.markBit(event->getPointerId(event->getActionIndex()));
- clearPointers(downIdBits);
- break;
- }
- case AMOTION_EVENT_ACTION_MOVE:
- case AMOTION_EVENT_ACTION_HOVER_MOVE:
- break;
- default:
- // Ignore all other actions because they do not convey any new information about
- // pointer movement. We also want to preserve the last known velocity of the pointers.
- // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
- // of the pointers that went up. ACTION_POINTER_UP does include the new position of
- // pointers that remained down but we will also receive an ACTION_MOVE with this
- // information if any of them actually moved. Since we don't know how many pointers
- // will be going up at once it makes sense to just wait for the following ACTION_MOVE
- // before adding the movement.
- return;
- }
-
- size_t pointerCount = event->getPointerCount();
- if (pointerCount > MAX_POINTERS) {
- pointerCount = MAX_POINTERS;
- }
-
- BitSet32 idBits;
- for (size_t i = 0; i < pointerCount; i++) {
- idBits.markBit(event->getPointerId(i));
- }
-
- uint32_t pointerIndex[MAX_POINTERS];
- for (size_t i = 0; i < pointerCount; i++) {
- pointerIndex[i] = idBits.getIndexOfBit(event->getPointerId(i));
- }
-
- nsecs_t eventTime;
- Position positions[pointerCount];
-
- size_t historySize = event->getHistorySize();
- for (size_t h = 0; h < historySize; h++) {
- eventTime = event->getHistoricalEventTime(h);
- for (size_t i = 0; i < pointerCount; i++) {
- uint32_t index = pointerIndex[i];
- positions[index].x = event->getHistoricalX(i, h);
- positions[index].y = event->getHistoricalY(i, h);
- }
- addMovement(eventTime, idBits, positions);
- }
-
- eventTime = event->getEventTime();
- for (size_t i = 0; i < pointerCount; i++) {
- uint32_t index = pointerIndex[i];
- positions[index].x = event->getX(i);
- positions[index].y = event->getY(i);
- }
- addMovement(eventTime, idBits, positions);
-}
-
-bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
- Estimator estimator;
- if (getEstimator(id, &estimator) && estimator.degree >= 1) {
- *outVx = estimator.xCoeff[1];
- *outVy = estimator.yCoeff[1];
- return true;
- }
- *outVx = 0;
- *outVy = 0;
- return false;
-}
-
-bool VelocityTracker::getEstimator(uint32_t id, Estimator* outEstimator) const {
- return mStrategy->getEstimator(id, outEstimator);
-}
-
-
-// --- LeastSquaresVelocityTrackerStrategy ---
-
-const nsecs_t LeastSquaresVelocityTrackerStrategy::HORIZON;
-const uint32_t LeastSquaresVelocityTrackerStrategy::HISTORY_SIZE;
-
-LeastSquaresVelocityTrackerStrategy::LeastSquaresVelocityTrackerStrategy(
- uint32_t degree, Weighting weighting) :
- mDegree(degree), mWeighting(weighting) {
- clear();
-}
-
-LeastSquaresVelocityTrackerStrategy::~LeastSquaresVelocityTrackerStrategy() {
-}
-
-void LeastSquaresVelocityTrackerStrategy::clear() {
- mIndex = 0;
- mMovements[0].idBits.clear();
-}
-
-void LeastSquaresVelocityTrackerStrategy::clearPointers(BitSet32 idBits) {
- BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
- mMovements[mIndex].idBits = remainingIdBits;
-}
-
-void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
- const VelocityTracker::Position* positions) {
- if (++mIndex == HISTORY_SIZE) {
- mIndex = 0;
- }
-
- Movement& movement = mMovements[mIndex];
- movement.eventTime = eventTime;
- movement.idBits = idBits;
- uint32_t count = idBits.count();
- for (uint32_t i = 0; i < count; i++) {
- movement.positions[i] = positions[i];
- }
-}
-
-/**
- * Solves a linear least squares problem to obtain a N degree polynomial that fits
- * the specified input data as nearly as possible.
- *
- * Returns true if a solution is found, false otherwise.
- *
- * The input consists of two vectors of data points X and Y with indices 0..m-1
- * along with a weight vector W of the same size.
- *
- * The output is a vector B with indices 0..n that describes a polynomial
- * that fits the data, such the sum of W[i] * W[i] * abs(Y[i] - (B[0] + B[1] X[i]
- * + B[2] X[i]^2 ... B[n] X[i]^n)) for all i between 0 and m-1 is minimized.
- *
- * Accordingly, the weight vector W should be initialized by the caller with the
- * reciprocal square root of the variance of the error in each input data point.
- * In other words, an ideal choice for W would be W[i] = 1 / var(Y[i]) = 1 / stddev(Y[i]).
- * The weights express the relative importance of each data point. If the weights are
- * all 1, then the data points are considered to be of equal importance when fitting
- * the polynomial. It is a good idea to choose weights that diminish the importance
- * of data points that may have higher than usual error margins.
- *
- * Errors among data points are assumed to be independent. W is represented here
- * as a vector although in the literature it is typically taken to be a diagonal matrix.
- *
- * That is to say, the function that generated the input data can be approximated
- * by y(x) ~= B[0] + B[1] x + B[2] x^2 + ... + B[n] x^n.
- *
- * The coefficient of determination (R^2) is also returned to describe the goodness
- * of fit of the model for the given data. It is a value between 0 and 1, where 1
- * indicates perfect correspondence.
- *
- * This function first expands the X vector to a m by n matrix A such that
- * A[i][0] = 1, A[i][1] = X[i], A[i][2] = X[i]^2, ..., A[i][n] = X[i]^n, then
- * multiplies it by w[i]./
- *
- * Then it calculates the QR decomposition of A yielding an m by m orthonormal matrix Q
- * and an m by n upper triangular matrix R. Because R is upper triangular (lower
- * part is all zeroes), we can simplify the decomposition into an m by n matrix
- * Q1 and a n by n matrix R1 such that A = Q1 R1.
- *
- * Finally we solve the system of linear equations given by R1 B = (Qtranspose W Y)
- * to find B.
- *
- * For efficiency, we lay out A and Q column-wise in memory because we frequently
- * operate on the column vectors. Conversely, we lay out R row-wise.
- *
- * http://en.wikipedia.org/wiki/Numerical_methods_for_linear_least_squares
- * http://en.wikipedia.org/wiki/Gram-Schmidt
- */
-static bool solveLeastSquares(const float* x, const float* y,
- const float* w, uint32_t m, uint32_t n, float* outB, float* outDet) {
-#if DEBUG_STRATEGY
- ALOGD("solveLeastSquares: m=%d, n=%d, x=%s, y=%s, w=%s", int(m), int(n),
- vectorToString(x, m).string(), vectorToString(y, m).string(),
- vectorToString(w, m).string());
-#endif
-
- // Expand the X vector to a matrix A, pre-multiplied by the weights.
- float a[n][m]; // column-major order
- for (uint32_t h = 0; h < m; h++) {
- a[0][h] = w[h];
- for (uint32_t i = 1; i < n; i++) {
- a[i][h] = a[i - 1][h] * x[h];
- }
- }
-#if DEBUG_STRATEGY
- ALOGD(" - a=%s", matrixToString(&a[0][0], m, n, false /*rowMajor*/).string());
-#endif
-
- // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
- float q[n][m]; // orthonormal basis, column-major order
- float r[n][n]; // upper triangular matrix, row-major order
- for (uint32_t j = 0; j < n; j++) {
- for (uint32_t h = 0; h < m; h++) {
- q[j][h] = a[j][h];
- }
- for (uint32_t i = 0; i < j; i++) {
- float dot = vectorDot(&q[j][0], &q[i][0], m);
- for (uint32_t h = 0; h < m; h++) {
- q[j][h] -= dot * q[i][h];
- }
- }
-
- float norm = vectorNorm(&q[j][0], m);
- if (norm < 0.000001f) {
- // vectors are linearly dependent or zero so no solution
-#if DEBUG_STRATEGY
- ALOGD(" - no solution, norm=%f", norm);
-#endif
- return false;
- }
-
- float invNorm = 1.0f / norm;
- for (uint32_t h = 0; h < m; h++) {
- q[j][h] *= invNorm;
- }
- for (uint32_t i = 0; i < n; i++) {
- r[j][i] = i < j ? 0 : vectorDot(&q[j][0], &a[i][0], m);
- }
- }
-#if DEBUG_STRATEGY
- ALOGD(" - q=%s", matrixToString(&q[0][0], m, n, false /*rowMajor*/).string());
- ALOGD(" - r=%s", matrixToString(&r[0][0], n, n, true /*rowMajor*/).string());
-
- // calculate QR, if we factored A correctly then QR should equal A
- float qr[n][m];
- for (uint32_t h = 0; h < m; h++) {
- for (uint32_t i = 0; i < n; i++) {
- qr[i][h] = 0;
- for (uint32_t j = 0; j < n; j++) {
- qr[i][h] += q[j][h] * r[j][i];
- }
- }
- }
- ALOGD(" - qr=%s", matrixToString(&qr[0][0], m, n, false /*rowMajor*/).string());
-#endif
-
- // Solve R B = Qt W Y to find B. This is easy because R is upper triangular.
- // We just work from bottom-right to top-left calculating B's coefficients.
- float wy[m];
- for (uint32_t h = 0; h < m; h++) {
- wy[h] = y[h] * w[h];
- }
- for (uint32_t i = n; i-- != 0; ) {
- outB[i] = vectorDot(&q[i][0], wy, m);
- for (uint32_t j = n - 1; j > i; j--) {
- outB[i] -= r[i][j] * outB[j];
- }
- outB[i] /= r[i][i];
- }
-#if DEBUG_STRATEGY
- ALOGD(" - b=%s", vectorToString(outB, n).string());
-#endif
-
- // Calculate the coefficient of determination as 1 - (SSerr / SStot) where
- // SSerr is the residual sum of squares (variance of the error),
- // and SStot is the total sum of squares (variance of the data) where each
- // has been weighted.
- float ymean = 0;
- for (uint32_t h = 0; h < m; h++) {
- ymean += y[h];
- }
- ymean /= m;
-
- float sserr = 0;
- float sstot = 0;
- for (uint32_t h = 0; h < m; h++) {
- float err = y[h] - outB[0];
- float term = 1;
- for (uint32_t i = 1; i < n; i++) {
- term *= x[h];
- err -= term * outB[i];
- }
- sserr += w[h] * w[h] * err * err;
- float var = y[h] - ymean;
- sstot += w[h] * w[h] * var * var;
- }
- *outDet = sstot > 0.000001f ? 1.0f - (sserr / sstot) : 1;
-#if DEBUG_STRATEGY
- ALOGD(" - sserr=%f", sserr);
- ALOGD(" - sstot=%f", sstot);
- ALOGD(" - det=%f", *outDet);
-#endif
- return true;
-}
-
-bool LeastSquaresVelocityTrackerStrategy::getEstimator(uint32_t id,
- VelocityTracker::Estimator* outEstimator) const {
- outEstimator->clear();
-
- // Iterate over movement samples in reverse time order and collect samples.
- float x[HISTORY_SIZE];
- float y[HISTORY_SIZE];
- float w[HISTORY_SIZE];
- float time[HISTORY_SIZE];
- uint32_t m = 0;
- uint32_t index = mIndex;
- const Movement& newestMovement = mMovements[mIndex];
- do {
- const Movement& movement = mMovements[index];
- if (!movement.idBits.hasBit(id)) {
- break;
- }
-
- nsecs_t age = newestMovement.eventTime - movement.eventTime;
- if (age > HORIZON) {
- break;
- }
-
- const VelocityTracker::Position& position = movement.getPosition(id);
- x[m] = position.x;
- y[m] = position.y;
- w[m] = chooseWeight(index);
- time[m] = -age * 0.000000001f;
- index = (index == 0 ? HISTORY_SIZE : index) - 1;
- } while (++m < HISTORY_SIZE);
-
- if (m == 0) {
- return false; // no data
- }
-
- // Calculate a least squares polynomial fit.
- uint32_t degree = mDegree;
- if (degree > m - 1) {
- degree = m - 1;
- }
- if (degree >= 1) {
- float xdet, ydet;
- uint32_t n = degree + 1;
- if (solveLeastSquares(time, x, w, m, n, outEstimator->xCoeff, &xdet)
- && solveLeastSquares(time, y, w, m, n, outEstimator->yCoeff, &ydet)) {
- outEstimator->time = newestMovement.eventTime;
- outEstimator->degree = degree;
- outEstimator->confidence = xdet * ydet;
-#if DEBUG_STRATEGY
- ALOGD("estimate: degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f",
- int(outEstimator->degree),
- vectorToString(outEstimator->xCoeff, n).string(),
- vectorToString(outEstimator->yCoeff, n).string(),
- outEstimator->confidence);
-#endif
- return true;
- }
- }
-
- // No velocity data available for this pointer, but we do have its current position.
- outEstimator->xCoeff[0] = x[0];
- outEstimator->yCoeff[0] = y[0];
- outEstimator->time = newestMovement.eventTime;
- outEstimator->degree = 0;
- outEstimator->confidence = 1;
- return true;
-}
-
-float LeastSquaresVelocityTrackerStrategy::chooseWeight(uint32_t index) const {
- switch (mWeighting) {
- case WEIGHTING_DELTA: {
- // Weight points based on how much time elapsed between them and the next
- // point so that points that "cover" a shorter time span are weighed less.
- // delta 0ms: 0.5
- // delta 10ms: 1.0
- if (index == mIndex) {
- return 1.0f;
- }
- uint32_t nextIndex = (index + 1) % HISTORY_SIZE;
- float deltaMillis = (mMovements[nextIndex].eventTime- mMovements[index].eventTime)
- * 0.000001f;
- if (deltaMillis < 0) {
- return 0.5f;
- }
- if (deltaMillis < 10) {
- return 0.5f + deltaMillis * 0.05;
- }
- return 1.0f;
- }
-
- case WEIGHTING_CENTRAL: {
- // Weight points based on their age, weighing very recent and very old points less.
- // age 0ms: 0.5
- // age 10ms: 1.0
- // age 50ms: 1.0
- // age 60ms: 0.5
- float ageMillis = (mMovements[mIndex].eventTime - mMovements[index].eventTime)
- * 0.000001f;
- if (ageMillis < 0) {
- return 0.5f;
- }
- if (ageMillis < 10) {
- return 0.5f + ageMillis * 0.05;
- }
- if (ageMillis < 50) {
- return 1.0f;
- }
- if (ageMillis < 60) {
- return 0.5f + (60 - ageMillis) * 0.05;
- }
- return 0.5f;
- }
-
- case WEIGHTING_RECENT: {
- // Weight points based on their age, weighing older points less.
- // age 0ms: 1.0
- // age 50ms: 1.0
- // age 100ms: 0.5
- float ageMillis = (mMovements[mIndex].eventTime - mMovements[index].eventTime)
- * 0.000001f;
- if (ageMillis < 50) {
- return 1.0f;
- }
- if (ageMillis < 100) {
- return 0.5f + (100 - ageMillis) * 0.01f;
- }
- return 0.5f;
- }
-
- case WEIGHTING_NONE:
- default:
- return 1.0f;
- }
-}
-
-
-// --- IntegratingVelocityTrackerStrategy ---
-
-IntegratingVelocityTrackerStrategy::IntegratingVelocityTrackerStrategy(uint32_t degree) :
- mDegree(degree) {
-}
-
-IntegratingVelocityTrackerStrategy::~IntegratingVelocityTrackerStrategy() {
-}
-
-void IntegratingVelocityTrackerStrategy::clear() {
- mPointerIdBits.clear();
-}
-
-void IntegratingVelocityTrackerStrategy::clearPointers(BitSet32 idBits) {
- mPointerIdBits.value &= ~idBits.value;
-}
-
-void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
- const VelocityTracker::Position* positions) {
- uint32_t index = 0;
- for (BitSet32 iterIdBits(idBits); !iterIdBits.isEmpty();) {
- uint32_t id = iterIdBits.clearFirstMarkedBit();
- State& state = mPointerState[id];
- const VelocityTracker::Position& position = positions[index++];
- if (mPointerIdBits.hasBit(id)) {
- updateState(state, eventTime, position.x, position.y);
- } else {
- initState(state, eventTime, position.x, position.y);
- }
- }
-
- mPointerIdBits = idBits;
-}
-
-bool IntegratingVelocityTrackerStrategy::getEstimator(uint32_t id,
- VelocityTracker::Estimator* outEstimator) const {
- outEstimator->clear();
-
- if (mPointerIdBits.hasBit(id)) {
- const State& state = mPointerState[id];
- populateEstimator(state, outEstimator);
- return true;
- }
-
- return false;
-}
-
-void IntegratingVelocityTrackerStrategy::initState(State& state,
- nsecs_t eventTime, float xpos, float ypos) const {
- state.updateTime = eventTime;
- state.degree = 0;
-
- state.xpos = xpos;
- state.xvel = 0;
- state.xaccel = 0;
- state.ypos = ypos;
- state.yvel = 0;
- state.yaccel = 0;
-}
-
-void IntegratingVelocityTrackerStrategy::updateState(State& state,
- nsecs_t eventTime, float xpos, float ypos) const {
- const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS;
- const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds
-
- if (eventTime <= state.updateTime + MIN_TIME_DELTA) {
- return;
- }
-
- float dt = (eventTime - state.updateTime) * 0.000000001f;
- state.updateTime = eventTime;
-
- float xvel = (xpos - state.xpos) / dt;
- float yvel = (ypos - state.ypos) / dt;
- if (state.degree == 0) {
- state.xvel = xvel;
- state.yvel = yvel;
- state.degree = 1;
- } else {
- float alpha = dt / (FILTER_TIME_CONSTANT + dt);
- if (mDegree == 1) {
- state.xvel += (xvel - state.xvel) * alpha;
- state.yvel += (yvel - state.yvel) * alpha;
- } else {
- float xaccel = (xvel - state.xvel) / dt;
- float yaccel = (yvel - state.yvel) / dt;
- if (state.degree == 1) {
- state.xaccel = xaccel;
- state.yaccel = yaccel;
- state.degree = 2;
- } else {
- state.xaccel += (xaccel - state.xaccel) * alpha;
- state.yaccel += (yaccel - state.yaccel) * alpha;
- }
- state.xvel += (state.xaccel * dt) * alpha;
- state.yvel += (state.yaccel * dt) * alpha;
- }
- }
- state.xpos = xpos;
- state.ypos = ypos;
-}
-
-void IntegratingVelocityTrackerStrategy::populateEstimator(const State& state,
- VelocityTracker::Estimator* outEstimator) const {
- outEstimator->time = state.updateTime;
- outEstimator->confidence = 1.0f;
- outEstimator->degree = state.degree;
- outEstimator->xCoeff[0] = state.xpos;
- outEstimator->xCoeff[1] = state.xvel;
- outEstimator->xCoeff[2] = state.xaccel / 2;
- outEstimator->yCoeff[0] = state.ypos;
- outEstimator->yCoeff[1] = state.yvel;
- outEstimator->yCoeff[2] = state.yaccel / 2;
-}
-
-
-// --- LegacyVelocityTrackerStrategy ---
-
-const nsecs_t LegacyVelocityTrackerStrategy::HORIZON;
-const uint32_t LegacyVelocityTrackerStrategy::HISTORY_SIZE;
-const nsecs_t LegacyVelocityTrackerStrategy::MIN_DURATION;
-
-LegacyVelocityTrackerStrategy::LegacyVelocityTrackerStrategy() {
- clear();
-}
-
-LegacyVelocityTrackerStrategy::~LegacyVelocityTrackerStrategy() {
-}
-
-void LegacyVelocityTrackerStrategy::clear() {
- mIndex = 0;
- mMovements[0].idBits.clear();
-}
-
-void LegacyVelocityTrackerStrategy::clearPointers(BitSet32 idBits) {
- BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
- mMovements[mIndex].idBits = remainingIdBits;
-}
-
-void LegacyVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
- const VelocityTracker::Position* positions) {
- if (++mIndex == HISTORY_SIZE) {
- mIndex = 0;
- }
-
- Movement& movement = mMovements[mIndex];
- movement.eventTime = eventTime;
- movement.idBits = idBits;
- uint32_t count = idBits.count();
- for (uint32_t i = 0; i < count; i++) {
- movement.positions[i] = positions[i];
- }
-}
-
-bool LegacyVelocityTrackerStrategy::getEstimator(uint32_t id,
- VelocityTracker::Estimator* outEstimator) const {
- outEstimator->clear();
-
- const Movement& newestMovement = mMovements[mIndex];
- if (!newestMovement.idBits.hasBit(id)) {
- return false; // no data
- }
-
- // Find the oldest sample that contains the pointer and that is not older than HORIZON.
- nsecs_t minTime = newestMovement.eventTime - HORIZON;
- uint32_t oldestIndex = mIndex;
- uint32_t numTouches = 1;
- do {
- uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
- const Movement& nextOldestMovement = mMovements[nextOldestIndex];
- if (!nextOldestMovement.idBits.hasBit(id)
- || nextOldestMovement.eventTime < minTime) {
- break;
- }
- oldestIndex = nextOldestIndex;
- } while (++numTouches < HISTORY_SIZE);
-
- // Calculate an exponentially weighted moving average of the velocity estimate
- // at different points in time measured relative to the oldest sample.
- // This is essentially an IIR filter. Newer samples are weighted more heavily
- // than older samples. Samples at equal time points are weighted more or less
- // equally.
- //
- // One tricky problem is that the sample data may be poorly conditioned.
- // Sometimes samples arrive very close together in time which can cause us to
- // overestimate the velocity at that time point. Most samples might be measured
- // 16ms apart but some consecutive samples could be only 0.5sm apart because
- // the hardware or driver reports them irregularly or in bursts.
- float accumVx = 0;
- float accumVy = 0;
- uint32_t index = oldestIndex;
- uint32_t samplesUsed = 0;
- const Movement& oldestMovement = mMovements[oldestIndex];
- const VelocityTracker::Position& oldestPosition = oldestMovement.getPosition(id);
- nsecs_t lastDuration = 0;
-
- while (numTouches-- > 1) {
- if (++index == HISTORY_SIZE) {
- index = 0;
- }
- const Movement& movement = mMovements[index];
- nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
-
- // If the duration between samples is small, we may significantly overestimate
- // the velocity. Consequently, we impose a minimum duration constraint on the
- // samples that we include in the calculation.
- if (duration >= MIN_DURATION) {
- const VelocityTracker::Position& position = movement.getPosition(id);
- float scale = 1000000000.0f / duration; // one over time delta in seconds
- float vx = (position.x - oldestPosition.x) * scale;
- float vy = (position.y - oldestPosition.y) * scale;
- accumVx = (accumVx * lastDuration + vx * duration) / (duration + lastDuration);
- accumVy = (accumVy * lastDuration + vy * duration) / (duration + lastDuration);
- lastDuration = duration;
- samplesUsed += 1;
- }
- }
-
- // Report velocity.
- const VelocityTracker::Position& newestPosition = newestMovement.getPosition(id);
- outEstimator->time = newestMovement.eventTime;
- outEstimator->confidence = 1;
- outEstimator->xCoeff[0] = newestPosition.x;
- outEstimator->yCoeff[0] = newestPosition.y;
- if (samplesUsed) {
- outEstimator->xCoeff[1] = accumVx;
- outEstimator->yCoeff[1] = accumVy;
- outEstimator->degree = 1;
- } else {
- outEstimator->degree = 0;
- }
- return true;
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/VelocityTracker.h b/widget/gonk/libui/VelocityTracker.h
deleted file mode 100644
index fd077d438..000000000
--- a/widget/gonk/libui/VelocityTracker.h
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_VELOCITY_TRACKER_H
-#define _ANDROIDFW_VELOCITY_TRACKER_H
-
-#include "Input.h"
-#include <utils/Timers.h>
-#include <utils/BitSet.h>
-
-namespace android {
-
-class VelocityTrackerStrategy;
-
-/*
- * Calculates the velocity of pointer movements over time.
- */
-class VelocityTracker {
-public:
- struct Position {
- float x, y;
- };
-
- struct Estimator {
- static const size_t MAX_DEGREE = 4;
-
- // Estimator time base.
- nsecs_t time;
-
- // Polynomial coefficients describing motion in X and Y.
- float xCoeff[MAX_DEGREE + 1], yCoeff[MAX_DEGREE + 1];
-
- // Polynomial degree (number of coefficients), or zero if no information is
- // available.
- uint32_t degree;
-
- // Confidence (coefficient of determination), between 0 (no fit) and 1 (perfect fit).
- float confidence;
-
- inline void clear() {
- time = 0;
- degree = 0;
- confidence = 0;
- for (size_t i = 0; i <= MAX_DEGREE; i++) {
- xCoeff[i] = 0;
- yCoeff[i] = 0;
- }
- }
- };
-
- // Creates a velocity tracker using the specified strategy.
- // If strategy is NULL, uses the default strategy for the platform.
- VelocityTracker(const char* strategy = NULL);
-
- ~VelocityTracker();
-
- // Resets the velocity tracker state.
- void clear();
-
- // Resets the velocity tracker state for specific pointers.
- // Call this method when some pointers have changed and may be reusing
- // an id that was assigned to a different pointer earlier.
- void clearPointers(BitSet32 idBits);
-
- // Adds movement information for a set of pointers.
- // The idBits bitfield specifies the pointer ids of the pointers whose positions
- // are included in the movement.
- // The positions array contains position information for each pointer in order by
- // increasing id. Its size should be equal to the number of one bits in idBits.
- void addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions);
-
- // Adds movement information for all pointers in a MotionEvent, including historical samples.
- void addMovement(const MotionEvent* event);
-
- // Gets the velocity of the specified pointer id in position units per second.
- // Returns false and sets the velocity components to zero if there is
- // insufficient movement information for the pointer.
- bool getVelocity(uint32_t id, float* outVx, float* outVy) const;
-
- // Gets an estimator for the recent movements of the specified pointer id.
- // Returns false and clears the estimator if there is no information available
- // about the pointer.
- bool getEstimator(uint32_t id, Estimator* outEstimator) const;
-
- // Gets the active pointer id, or -1 if none.
- inline int32_t getActivePointerId() const { return mActivePointerId; }
-
- // Gets a bitset containing all pointer ids from the most recent movement.
- inline BitSet32 getCurrentPointerIdBits() const { return mCurrentPointerIdBits; }
-
-private:
- static const char* DEFAULT_STRATEGY;
-
- nsecs_t mLastEventTime;
- BitSet32 mCurrentPointerIdBits;
- int32_t mActivePointerId;
- VelocityTrackerStrategy* mStrategy;
-
- bool configureStrategy(const char* strategy);
-
- static VelocityTrackerStrategy* createStrategy(const char* strategy);
-};
-
-
-/*
- * Implements a particular velocity tracker algorithm.
- */
-class VelocityTrackerStrategy {
-protected:
- VelocityTrackerStrategy() { }
-
-public:
- virtual ~VelocityTrackerStrategy() { }
-
- virtual void clear() = 0;
- virtual void clearPointers(BitSet32 idBits) = 0;
- virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const VelocityTracker::Position* positions) = 0;
- virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const = 0;
-};
-
-
-/*
- * Velocity tracker algorithm based on least-squares linear regression.
- */
-class LeastSquaresVelocityTrackerStrategy : public VelocityTrackerStrategy {
-public:
- enum Weighting {
- // No weights applied. All data points are equally reliable.
- WEIGHTING_NONE,
-
- // Weight by time delta. Data points clustered together are weighted less.
- WEIGHTING_DELTA,
-
- // Weight such that points within a certain horizon are weighed more than those
- // outside of that horizon.
- WEIGHTING_CENTRAL,
-
- // Weight such that points older than a certain amount are weighed less.
- WEIGHTING_RECENT,
- };
-
- // Degree must be no greater than Estimator::MAX_DEGREE.
- LeastSquaresVelocityTrackerStrategy(uint32_t degree, Weighting weighting = WEIGHTING_NONE);
- virtual ~LeastSquaresVelocityTrackerStrategy();
-
- virtual void clear();
- virtual void clearPointers(BitSet32 idBits);
- virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const VelocityTracker::Position* positions);
- virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
-
-private:
- // Sample horizon.
- // We don't use too much history by default since we want to react to quick
- // changes in direction.
- static const nsecs_t HORIZON = 100 * 1000000; // 100 ms
-
- // Number of samples to keep.
- static const uint32_t HISTORY_SIZE = 20;
-
- struct Movement {
- nsecs_t eventTime;
- BitSet32 idBits;
- VelocityTracker::Position positions[MAX_POINTERS];
-
- inline const VelocityTracker::Position& getPosition(uint32_t id) const {
- return positions[idBits.getIndexOfBit(id)];
- }
- };
-
- float chooseWeight(uint32_t index) const;
-
- const uint32_t mDegree;
- const Weighting mWeighting;
- uint32_t mIndex;
- Movement mMovements[HISTORY_SIZE];
-};
-
-
-/*
- * Velocity tracker algorithm that uses an IIR filter.
- */
-class IntegratingVelocityTrackerStrategy : public VelocityTrackerStrategy {
-public:
- // Degree must be 1 or 2.
- IntegratingVelocityTrackerStrategy(uint32_t degree);
- ~IntegratingVelocityTrackerStrategy();
-
- virtual void clear();
- virtual void clearPointers(BitSet32 idBits);
- virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const VelocityTracker::Position* positions);
- virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
-
-private:
- // Current state estimate for a particular pointer.
- struct State {
- nsecs_t updateTime;
- uint32_t degree;
-
- float xpos, xvel, xaccel;
- float ypos, yvel, yaccel;
- };
-
- const uint32_t mDegree;
- BitSet32 mPointerIdBits;
- State mPointerState[MAX_POINTER_ID + 1];
-
- void initState(State& state, nsecs_t eventTime, float xpos, float ypos) const;
- void updateState(State& state, nsecs_t eventTime, float xpos, float ypos) const;
- void populateEstimator(const State& state, VelocityTracker::Estimator* outEstimator) const;
-};
-
-
-/*
- * Velocity tracker strategy used prior to ICS.
- */
-class LegacyVelocityTrackerStrategy : public VelocityTrackerStrategy {
-public:
- LegacyVelocityTrackerStrategy();
- virtual ~LegacyVelocityTrackerStrategy();
-
- virtual void clear();
- virtual void clearPointers(BitSet32 idBits);
- virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const VelocityTracker::Position* positions);
- virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
-
-private:
- // Oldest sample to consider when calculating the velocity.
- static const nsecs_t HORIZON = 200 * 1000000; // 100 ms
-
- // Number of samples to keep.
- static const uint32_t HISTORY_SIZE = 20;
-
- // The minimum duration between samples when estimating velocity.
- static const nsecs_t MIN_DURATION = 10 * 1000000; // 10 ms
-
- struct Movement {
- nsecs_t eventTime;
- BitSet32 idBits;
- VelocityTracker::Position positions[MAX_POINTERS];
-
- inline const VelocityTracker::Position& getPosition(uint32_t id) const {
- return positions[idBits.getIndexOfBit(id)];
- }
- };
-
- uint32_t mIndex;
- Movement mMovements[HISTORY_SIZE];
-};
-
-} // namespace android
-
-#endif // _ANDROIDFW_VELOCITY_TRACKER_H
diff --git a/widget/gonk/libui/VirtualKeyMap.cpp b/widget/gonk/libui/VirtualKeyMap.cpp
deleted file mode 100644
index 444ab3718..000000000
--- a/widget/gonk/libui/VirtualKeyMap.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "VirtualKeyMap"
-#include "cutils_log.h"
-
-#include <stdlib.h>
-#include <string.h>
-#include "VirtualKeyMap.h"
-#include <utils/Errors.h>
-#include "Tokenizer.h"
-#include <utils/Timers.h>
-
-// Enables debug output for the parser.
-#define DEBUG_PARSER 0
-
-// Enables debug output for parser performance.
-#define DEBUG_PARSER_PERFORMANCE 0
-
-
-namespace android {
-
-static const char* WHITESPACE = " \t\r";
-static const char* WHITESPACE_OR_FIELD_DELIMITER = " \t\r:";
-
-
-// --- VirtualKeyMap ---
-
-VirtualKeyMap::VirtualKeyMap() {
-}
-
-VirtualKeyMap::~VirtualKeyMap() {
-}
-
-status_t VirtualKeyMap::load(const String8& filename, VirtualKeyMap** outMap) {
- *outMap = NULL;
-
- Tokenizer* tokenizer;
- status_t status = Tokenizer::open(filename, &tokenizer);
- if (status) {
- ALOGE("Error %d opening virtual key map file %s.", status, filename.string());
- } else {
- VirtualKeyMap* map = new VirtualKeyMap();
- if (!map) {
- ALOGE("Error allocating virtual key map.");
- status = NO_MEMORY;
- } else {
-#if DEBUG_PARSER_PERFORMANCE
- nsecs_t startTime = systemTime(SYSTEM_TIME_MONOTONIC);
-#endif
- Parser parser(map, tokenizer);
- status = parser.parse();
-#if DEBUG_PARSER_PERFORMANCE
- nsecs_t elapsedTime = systemTime(SYSTEM_TIME_MONOTONIC) - startTime;
- ALOGD("Parsed key character map file '%s' %d lines in %0.3fms.",
- tokenizer->getFilename().string(), tokenizer->getLineNumber(),
- elapsedTime / 1000000.0);
-#endif
- if (status) {
- delete map;
- } else {
- *outMap = map;
- }
- }
- delete tokenizer;
- }
- return status;
-}
-
-
-// --- VirtualKeyMap::Parser ---
-
-VirtualKeyMap::Parser::Parser(VirtualKeyMap* map, Tokenizer* tokenizer) :
- mMap(map), mTokenizer(tokenizer) {
-}
-
-VirtualKeyMap::Parser::~Parser() {
-}
-
-status_t VirtualKeyMap::Parser::parse() {
- while (!mTokenizer->isEof()) {
-#if DEBUG_PARSER
- ALOGD("Parsing %s: '%s'.", mTokenizer->getLocation().string(),
- mTokenizer->peekRemainderOfLine().string());
-#endif
-
- mTokenizer->skipDelimiters(WHITESPACE);
-
- if (!mTokenizer->isEol() && mTokenizer->peekChar() != '#') {
- // Multiple keys can appear on one line or they can be broken up across multiple lines.
- do {
- String8 token = mTokenizer->nextToken(WHITESPACE_OR_FIELD_DELIMITER);
- if (token != "0x01") {
- ALOGE("%s: Unknown virtual key type, expected 0x01.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
-
- VirtualKeyDefinition defn;
- bool success = parseNextIntField(&defn.scanCode)
- && parseNextIntField(&defn.centerX)
- && parseNextIntField(&defn.centerY)
- && parseNextIntField(&defn.width)
- && parseNextIntField(&defn.height);
- if (!success) {
- ALOGE("%s: Expected 5 colon-delimited integers in virtual key definition.",
- mTokenizer->getLocation().string());
- return BAD_VALUE;
- }
-
-#if DEBUG_PARSER
- ALOGD("Parsed virtual key: scanCode=%d, centerX=%d, centerY=%d, "
- "width=%d, height=%d",
- defn.scanCode, defn.centerX, defn.centerY, defn.width, defn.height);
-#endif
- mMap->mVirtualKeys.push(defn);
- } while (consumeFieldDelimiterAndSkipWhitespace());
-
- if (!mTokenizer->isEol()) {
- ALOGE("%s: Expected end of line, got '%s'.",
- mTokenizer->getLocation().string(),
- mTokenizer->peekRemainderOfLine().string());
- return BAD_VALUE;
- }
- }
-
- mTokenizer->nextLine();
- }
-
- return NO_ERROR;
-}
-
-bool VirtualKeyMap::Parser::consumeFieldDelimiterAndSkipWhitespace() {
- mTokenizer->skipDelimiters(WHITESPACE);
- if (mTokenizer->peekChar() == ':') {
- mTokenizer->nextChar();
- mTokenizer->skipDelimiters(WHITESPACE);
- return true;
- }
- return false;
-}
-
-bool VirtualKeyMap::Parser::parseNextIntField(int32_t* outValue) {
- if (!consumeFieldDelimiterAndSkipWhitespace()) {
- return false;
- }
-
- String8 token = mTokenizer->nextToken(WHITESPACE_OR_FIELD_DELIMITER);
- char* end;
- *outValue = strtol(token.string(), &end, 0);
- if (token.isEmpty() || *end != '\0') {
- ALOGE("Expected an integer, got '%s'.", token.string());
- return false;
- }
- return true;
-}
-
-} // namespace android
diff --git a/widget/gonk/libui/VirtualKeyMap.h b/widget/gonk/libui/VirtualKeyMap.h
deleted file mode 100644
index 79d61a536..000000000
--- a/widget/gonk/libui/VirtualKeyMap.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROIDFW_VIRTUAL_KEY_MAP_H
-#define _ANDROIDFW_VIRTUAL_KEY_MAP_H
-
-#include <stdint.h>
-
-#include "Input.h"
-#include <utils/Errors.h>
-#include <utils/KeyedVector.h>
-#include "Tokenizer.h"
-#include <utils/String8.h>
-#include <utils/Unicode.h>
-
-namespace android {
-
-/* Describes a virtual key. */
-struct VirtualKeyDefinition {
- int32_t scanCode;
-
- // configured position data, specified in display coords
- int32_t centerX;
- int32_t centerY;
- int32_t width;
- int32_t height;
-};
-
-
-/**
- * Describes a collection of virtual keys on a touch screen in terms of
- * virtual scan codes and hit rectangles.
- *
- * This object is immutable after it has been loaded.
- */
-class VirtualKeyMap {
-public:
- ~VirtualKeyMap();
-
- static status_t load(const String8& filename, VirtualKeyMap** outMap);
-
- inline const Vector<VirtualKeyDefinition>& getVirtualKeys() const {
- return mVirtualKeys;
- }
-
-private:
- class Parser {
- VirtualKeyMap* mMap;
- Tokenizer* mTokenizer;
-
- public:
- Parser(VirtualKeyMap* map, Tokenizer* tokenizer);
- ~Parser();
- status_t parse();
-
- private:
- bool consumeFieldDelimiterAndSkipWhitespace();
- bool parseNextIntField(int32_t* outValue);
- };
-
- Vector<VirtualKeyDefinition> mVirtualKeys;
-
- VirtualKeyMap();
-};
-
-} // namespace android
-
-#endif // _ANDROIDFW_KEY_CHARACTER_MAP_H
diff --git a/widget/gonk/libui/android_input.h b/widget/gonk/libui/android_input.h
deleted file mode 100644
index 00e81b28d..000000000
--- a/widget/gonk/libui/android_input.h
+++ /dev/null
@@ -1,850 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROID_INPUT_H
-#define _ANDROID_INPUT_H
-
-/******************************************************************
- *
- * IMPORTANT NOTICE:
- *
- * This file is part of Android's set of stable system headers
- * exposed by the Android NDK (Native Development Kit).
- *
- * Third-party source AND binary code relies on the definitions
- * here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
- *
- * - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
- * - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
- * - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
- * - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
- */
-
-/*
- * Structures and functions to receive and process input events in
- * native code.
- *
- * NOTE: These functions MUST be implemented by /system/lib/libui.so
- */
-
-#include <stdint.h>
-#include <sys/types.h>
-#include "android_keycodes.h"
-#include <android/looper.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Key states (may be returned by queries about the current state of a
- * particular key code, scan code or switch).
- */
-enum {
- /* The key state is unknown or the requested key itself is not supported. */
- AKEY_STATE_UNKNOWN = -1,
-
- /* The key is up. */
- AKEY_STATE_UP = 0,
-
- /* The key is down. */
- AKEY_STATE_DOWN = 1,
-
- /* The key is down but is a virtual key press that is being emulated by the system. */
- AKEY_STATE_VIRTUAL = 2
-};
-
-/*
- * Meta key / modifer state.
- */
-enum {
- /* No meta keys are pressed. */
- AMETA_NONE = 0,
-
- /* This mask is used to check whether one of the ALT meta keys is pressed. */
- AMETA_ALT_ON = 0x02,
-
- /* This mask is used to check whether the left ALT meta key is pressed. */
- AMETA_ALT_LEFT_ON = 0x10,
-
- /* This mask is used to check whether the right ALT meta key is pressed. */
- AMETA_ALT_RIGHT_ON = 0x20,
-
- /* This mask is used to check whether one of the SHIFT meta keys is pressed. */
- AMETA_SHIFT_ON = 0x01,
-
- /* This mask is used to check whether the left SHIFT meta key is pressed. */
- AMETA_SHIFT_LEFT_ON = 0x40,
-
- /* This mask is used to check whether the right SHIFT meta key is pressed. */
- AMETA_SHIFT_RIGHT_ON = 0x80,
-
- /* This mask is used to check whether the SYM meta key is pressed. */
- AMETA_SYM_ON = 0x04,
-
- /* This mask is used to check whether the FUNCTION meta key is pressed. */
- AMETA_FUNCTION_ON = 0x08,
-
- /* This mask is used to check whether one of the CTRL meta keys is pressed. */
- AMETA_CTRL_ON = 0x1000,
-
- /* This mask is used to check whether the left CTRL meta key is pressed. */
- AMETA_CTRL_LEFT_ON = 0x2000,
-
- /* This mask is used to check whether the right CTRL meta key is pressed. */
- AMETA_CTRL_RIGHT_ON = 0x4000,
-
- /* This mask is used to check whether one of the META meta keys is pressed. */
- AMETA_META_ON = 0x10000,
-
- /* This mask is used to check whether the left META meta key is pressed. */
- AMETA_META_LEFT_ON = 0x20000,
-
- /* This mask is used to check whether the right META meta key is pressed. */
- AMETA_META_RIGHT_ON = 0x40000,
-
- /* This mask is used to check whether the CAPS LOCK meta key is on. */
- AMETA_CAPS_LOCK_ON = 0x100000,
-
- /* This mask is used to check whether the NUM LOCK meta key is on. */
- AMETA_NUM_LOCK_ON = 0x200000,
-
- /* This mask is used to check whether the SCROLL LOCK meta key is on. */
- AMETA_SCROLL_LOCK_ON = 0x400000,
-};
-
-/*
- * Input events.
- *
- * Input events are opaque structures. Use the provided accessors functions to
- * read their properties.
- */
-struct AInputEvent;
-typedef struct AInputEvent AInputEvent;
-
-/*
- * Input event types.
- */
-enum {
- /* Indicates that the input event is a key event. */
- AINPUT_EVENT_TYPE_KEY = 1,
-
- /* Indicates that the input event is a motion event. */
- AINPUT_EVENT_TYPE_MOTION = 2
-};
-
-/*
- * Key event actions.
- */
-enum {
- /* The key has been pressed down. */
- AKEY_EVENT_ACTION_DOWN = 0,
-
- /* The key has been released. */
- AKEY_EVENT_ACTION_UP = 1,
-
- /* Multiple duplicate key events have occurred in a row, or a complex string is
- * being delivered. The repeat_count property of the key event contains the number
- * of times the given key code should be executed.
- */
- AKEY_EVENT_ACTION_MULTIPLE = 2
-};
-
-/*
- * Key event flags.
- */
-enum {
- /* This mask is set if the device woke because of this key event. */
- AKEY_EVENT_FLAG_WOKE_HERE = 0x1,
-
- /* This mask is set if the key event was generated by a software keyboard. */
- AKEY_EVENT_FLAG_SOFT_KEYBOARD = 0x2,
-
- /* This mask is set if we don't want the key event to cause us to leave touch mode. */
- AKEY_EVENT_FLAG_KEEP_TOUCH_MODE = 0x4,
-
- /* This mask is set if an event was known to come from a trusted part
- * of the system. That is, the event is known to come from the user,
- * and could not have been spoofed by a third party component. */
- AKEY_EVENT_FLAG_FROM_SYSTEM = 0x8,
-
- /* This mask is used for compatibility, to identify enter keys that are
- * coming from an IME whose enter key has been auto-labelled "next" or
- * "done". This allows TextView to dispatch these as normal enter keys
- * for old applications, but still do the appropriate action when
- * receiving them. */
- AKEY_EVENT_FLAG_EDITOR_ACTION = 0x10,
-
- /* When associated with up key events, this indicates that the key press
- * has been canceled. Typically this is used with virtual touch screen
- * keys, where the user can slide from the virtual key area on to the
- * display: in that case, the application will receive a canceled up
- * event and should not perform the action normally associated with the
- * key. Note that for this to work, the application can not perform an
- * action for a key until it receives an up or the long press timeout has
- * expired. */
- AKEY_EVENT_FLAG_CANCELED = 0x20,
-
- /* This key event was generated by a virtual (on-screen) hard key area.
- * Typically this is an area of the touchscreen, outside of the regular
- * display, dedicated to "hardware" buttons. */
- AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY = 0x40,
-
- /* This flag is set for the first key repeat that occurs after the
- * long press timeout. */
- AKEY_EVENT_FLAG_LONG_PRESS = 0x80,
-
- /* Set when a key event has AKEY_EVENT_FLAG_CANCELED set because a long
- * press action was executed while it was down. */
- AKEY_EVENT_FLAG_CANCELED_LONG_PRESS = 0x100,
-
- /* Set for AKEY_EVENT_ACTION_UP when this event's key code is still being
- * tracked from its initial down. That is, somebody requested that tracking
- * started on the key down and a long press has not caused
- * the tracking to be canceled. */
- AKEY_EVENT_FLAG_TRACKING = 0x200,
-
- /* Set when a key event has been synthesized to implement default behavior
- * for an event that the application did not handle.
- * Fallback key events are generated by unhandled trackball motions
- * (to emulate a directional keypad) and by certain unhandled key presses
- * that are declared in the key map (such as special function numeric keypad
- * keys when numlock is off). */
- AKEY_EVENT_FLAG_FALLBACK = 0x400,
-};
-
-/*
- * Motion event actions.
- */
-
-/* Bit shift for the action bits holding the pointer index as
- * defined by AMOTION_EVENT_ACTION_POINTER_INDEX_MASK.
- */
-#define AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT 8
-
-enum {
- /* Bit mask of the parts of the action code that are the action itself.
- */
- AMOTION_EVENT_ACTION_MASK = 0xff,
-
- /* Bits in the action code that represent a pointer index, used with
- * AMOTION_EVENT_ACTION_POINTER_DOWN and AMOTION_EVENT_ACTION_POINTER_UP. Shifting
- * down by AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT provides the actual pointer
- * index where the data for the pointer going up or down can be found.
- */
- AMOTION_EVENT_ACTION_POINTER_INDEX_MASK = 0xff00,
-
- /* A pressed gesture has started, the motion contains the initial starting location.
- */
- AMOTION_EVENT_ACTION_DOWN = 0,
-
- /* A pressed gesture has finished, the motion contains the final release location
- * as well as any intermediate points since the last down or move event.
- */
- AMOTION_EVENT_ACTION_UP = 1,
-
- /* A change has happened during a press gesture (between AMOTION_EVENT_ACTION_DOWN and
- * AMOTION_EVENT_ACTION_UP). The motion contains the most recent point, as well as
- * any intermediate points since the last down or move event.
- */
- AMOTION_EVENT_ACTION_MOVE = 2,
-
- /* The current gesture has been aborted.
- * You will not receive any more points in it. You should treat this as
- * an up event, but not perform any action that you normally would.
- */
- AMOTION_EVENT_ACTION_CANCEL = 3,
-
- /* A movement has happened outside of the normal bounds of the UI element.
- * This does not provide a full gesture, but only the initial location of the movement/touch.
- */
- AMOTION_EVENT_ACTION_OUTSIDE = 4,
-
- /* A non-primary pointer has gone down.
- * The bits in AMOTION_EVENT_ACTION_POINTER_INDEX_MASK indicate which pointer changed.
- */
- AMOTION_EVENT_ACTION_POINTER_DOWN = 5,
-
- /* A non-primary pointer has gone up.
- * The bits in AMOTION_EVENT_ACTION_POINTER_INDEX_MASK indicate which pointer changed.
- */
- AMOTION_EVENT_ACTION_POINTER_UP = 6,
-
- /* A change happened but the pointer is not down (unlike AMOTION_EVENT_ACTION_MOVE).
- * The motion contains the most recent point, as well as any intermediate points since
- * the last hover move event.
- */
- AMOTION_EVENT_ACTION_HOVER_MOVE = 7,
-
- /* The motion event contains relative vertical and/or horizontal scroll offsets.
- * Use getAxisValue to retrieve the information from AMOTION_EVENT_AXIS_VSCROLL
- * and AMOTION_EVENT_AXIS_HSCROLL.
- * The pointer may or may not be down when this event is dispatched.
- * This action is always delivered to the winder under the pointer, which
- * may not be the window currently touched.
- */
- AMOTION_EVENT_ACTION_SCROLL = 8,
-
- /* The pointer is not down but has entered the boundaries of a window or view.
- */
- AMOTION_EVENT_ACTION_HOVER_ENTER = 9,
-
- /* The pointer is not down but has exited the boundaries of a window or view.
- */
- AMOTION_EVENT_ACTION_HOVER_EXIT = 10,
-};
-
-/*
- * Motion event flags.
- */
-enum {
- /* This flag indicates that the window that received this motion event is partly
- * or wholly obscured by another visible window above it. This flag is set to true
- * even if the event did not directly pass through the obscured area.
- * A security sensitive application can check this flag to identify situations in which
- * a malicious application may have covered up part of its content for the purpose
- * of misleading the user or hijacking touches. An appropriate response might be
- * to drop the suspect touches or to take additional precautions to confirm the user's
- * actual intent.
- */
- AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED = 0x1,
-};
-
-/*
- * Motion event edge touch flags.
- */
-enum {
- /* No edges intersected */
- AMOTION_EVENT_EDGE_FLAG_NONE = 0,
-
- /* Flag indicating the motion event intersected the top edge of the screen. */
- AMOTION_EVENT_EDGE_FLAG_TOP = 0x01,
-
- /* Flag indicating the motion event intersected the bottom edge of the screen. */
- AMOTION_EVENT_EDGE_FLAG_BOTTOM = 0x02,
-
- /* Flag indicating the motion event intersected the left edge of the screen. */
- AMOTION_EVENT_EDGE_FLAG_LEFT = 0x04,
-
- /* Flag indicating the motion event intersected the right edge of the screen. */
- AMOTION_EVENT_EDGE_FLAG_RIGHT = 0x08
-};
-
-/*
- * Constants that identify each individual axis of a motion event.
- * Refer to the documentation on the MotionEvent class for descriptions of each axis.
- */
-enum {
- AMOTION_EVENT_AXIS_X = 0,
- AMOTION_EVENT_AXIS_Y = 1,
- AMOTION_EVENT_AXIS_PRESSURE = 2,
- AMOTION_EVENT_AXIS_SIZE = 3,
- AMOTION_EVENT_AXIS_TOUCH_MAJOR = 4,
- AMOTION_EVENT_AXIS_TOUCH_MINOR = 5,
- AMOTION_EVENT_AXIS_TOOL_MAJOR = 6,
- AMOTION_EVENT_AXIS_TOOL_MINOR = 7,
- AMOTION_EVENT_AXIS_ORIENTATION = 8,
- AMOTION_EVENT_AXIS_VSCROLL = 9,
- AMOTION_EVENT_AXIS_HSCROLL = 10,
- AMOTION_EVENT_AXIS_Z = 11,
- AMOTION_EVENT_AXIS_RX = 12,
- AMOTION_EVENT_AXIS_RY = 13,
- AMOTION_EVENT_AXIS_RZ = 14,
- AMOTION_EVENT_AXIS_HAT_X = 15,
- AMOTION_EVENT_AXIS_HAT_Y = 16,
- AMOTION_EVENT_AXIS_LTRIGGER = 17,
- AMOTION_EVENT_AXIS_RTRIGGER = 18,
- AMOTION_EVENT_AXIS_THROTTLE = 19,
- AMOTION_EVENT_AXIS_RUDDER = 20,
- AMOTION_EVENT_AXIS_WHEEL = 21,
- AMOTION_EVENT_AXIS_GAS = 22,
- AMOTION_EVENT_AXIS_BRAKE = 23,
- AMOTION_EVENT_AXIS_DISTANCE = 24,
- AMOTION_EVENT_AXIS_TILT = 25,
- AMOTION_EVENT_AXIS_GENERIC_1 = 32,
- AMOTION_EVENT_AXIS_GENERIC_2 = 33,
- AMOTION_EVENT_AXIS_GENERIC_3 = 34,
- AMOTION_EVENT_AXIS_GENERIC_4 = 35,
- AMOTION_EVENT_AXIS_GENERIC_5 = 36,
- AMOTION_EVENT_AXIS_GENERIC_6 = 37,
- AMOTION_EVENT_AXIS_GENERIC_7 = 38,
- AMOTION_EVENT_AXIS_GENERIC_8 = 39,
- AMOTION_EVENT_AXIS_GENERIC_9 = 40,
- AMOTION_EVENT_AXIS_GENERIC_10 = 41,
- AMOTION_EVENT_AXIS_GENERIC_11 = 42,
- AMOTION_EVENT_AXIS_GENERIC_12 = 43,
- AMOTION_EVENT_AXIS_GENERIC_13 = 44,
- AMOTION_EVENT_AXIS_GENERIC_14 = 45,
- AMOTION_EVENT_AXIS_GENERIC_15 = 46,
- AMOTION_EVENT_AXIS_GENERIC_16 = 47,
-
- // NOTE: If you add a new axis here you must also add it to several other files.
- // Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list.
-};
-
-/*
- * Constants that identify buttons that are associated with motion events.
- * Refer to the documentation on the MotionEvent class for descriptions of each button.
- */
-enum {
- AMOTION_EVENT_BUTTON_PRIMARY = 1 << 0,
- AMOTION_EVENT_BUTTON_SECONDARY = 1 << 1,
- AMOTION_EVENT_BUTTON_TERTIARY = 1 << 2,
- AMOTION_EVENT_BUTTON_BACK = 1 << 3,
- AMOTION_EVENT_BUTTON_FORWARD = 1 << 4,
-};
-
-/*
- * Constants that identify tool types.
- * Refer to the documentation on the MotionEvent class for descriptions of each tool type.
- */
-enum {
- AMOTION_EVENT_TOOL_TYPE_UNKNOWN = 0,
- AMOTION_EVENT_TOOL_TYPE_FINGER = 1,
- AMOTION_EVENT_TOOL_TYPE_STYLUS = 2,
- AMOTION_EVENT_TOOL_TYPE_MOUSE = 3,
- AMOTION_EVENT_TOOL_TYPE_ERASER = 4,
-};
-
-/*
- * Input sources.
- *
- * Refer to the documentation on android.view.InputDevice for more details about input sources
- * and their correct interpretation.
- */
-enum {
- AINPUT_SOURCE_CLASS_MASK = 0x000000ff,
-
- AINPUT_SOURCE_CLASS_NONE = 0x00000000,
- AINPUT_SOURCE_CLASS_BUTTON = 0x00000001,
- AINPUT_SOURCE_CLASS_POINTER = 0x00000002,
- AINPUT_SOURCE_CLASS_NAVIGATION = 0x00000004,
- AINPUT_SOURCE_CLASS_POSITION = 0x00000008,
- AINPUT_SOURCE_CLASS_JOYSTICK = 0x00000010,
-};
-
-enum {
- AINPUT_SOURCE_UNKNOWN = 0x00000000,
-
- AINPUT_SOURCE_KEYBOARD = 0x00000100 | AINPUT_SOURCE_CLASS_BUTTON,
- AINPUT_SOURCE_DPAD = 0x00000200 | AINPUT_SOURCE_CLASS_BUTTON,
- AINPUT_SOURCE_GAMEPAD = 0x00000400 | AINPUT_SOURCE_CLASS_BUTTON,
- AINPUT_SOURCE_TOUCHSCREEN = 0x00001000 | AINPUT_SOURCE_CLASS_POINTER,
- AINPUT_SOURCE_MOUSE = 0x00002000 | AINPUT_SOURCE_CLASS_POINTER,
- AINPUT_SOURCE_STYLUS = 0x00004000 | AINPUT_SOURCE_CLASS_POINTER,
- AINPUT_SOURCE_TRACKBALL = 0x00010000 | AINPUT_SOURCE_CLASS_NAVIGATION,
- AINPUT_SOURCE_TOUCHPAD = 0x00100000 | AINPUT_SOURCE_CLASS_POSITION,
- AINPUT_SOURCE_TOUCH_NAVIGATION = 0x00200000 | AINPUT_SOURCE_CLASS_NONE,
- AINPUT_SOURCE_JOYSTICK = 0x01000000 | AINPUT_SOURCE_CLASS_JOYSTICK,
-
- AINPUT_SOURCE_ANY = 0xffffff00,
-};
-
-/*
- * Keyboard types.
- *
- * Refer to the documentation on android.view.InputDevice for more details.
- */
-enum {
- AINPUT_KEYBOARD_TYPE_NONE = 0,
- AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC = 1,
- AINPUT_KEYBOARD_TYPE_ALPHABETIC = 2,
-};
-
-/*
- * Constants used to retrieve information about the range of motion for a particular
- * coordinate of a motion event.
- *
- * Refer to the documentation on android.view.InputDevice for more details about input sources
- * and their correct interpretation.
- *
- * DEPRECATION NOTICE: These constants are deprecated. Use AMOTION_EVENT_AXIS_* constants instead.
- */
-enum {
- AINPUT_MOTION_RANGE_X = AMOTION_EVENT_AXIS_X,
- AINPUT_MOTION_RANGE_Y = AMOTION_EVENT_AXIS_Y,
- AINPUT_MOTION_RANGE_PRESSURE = AMOTION_EVENT_AXIS_PRESSURE,
- AINPUT_MOTION_RANGE_SIZE = AMOTION_EVENT_AXIS_SIZE,
- AINPUT_MOTION_RANGE_TOUCH_MAJOR = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
- AINPUT_MOTION_RANGE_TOUCH_MINOR = AMOTION_EVENT_AXIS_TOUCH_MINOR,
- AINPUT_MOTION_RANGE_TOOL_MAJOR = AMOTION_EVENT_AXIS_TOOL_MAJOR,
- AINPUT_MOTION_RANGE_TOOL_MINOR = AMOTION_EVENT_AXIS_TOOL_MINOR,
- AINPUT_MOTION_RANGE_ORIENTATION = AMOTION_EVENT_AXIS_ORIENTATION,
-} __attribute__ ((deprecated));
-
-
-/*
- * Input event accessors.
- *
- * Note that most functions can only be used on input events that are of a given type.
- * Calling these functions on input events of other types will yield undefined behavior.
- */
-
-/*** Accessors for all input events. ***/
-
-/* Get the input event type. */
-int32_t AInputEvent_getType(const AInputEvent* event);
-
-/* Get the id for the device that an input event came from.
- *
- * Input events can be generated by multiple different input devices.
- * Use the input device id to obtain information about the input
- * device that was responsible for generating a particular event.
- *
- * An input device id of 0 indicates that the event didn't come from a physical device;
- * other numbers are arbitrary and you shouldn't depend on the values.
- * Use the provided input device query API to obtain information about input devices.
- */
-int32_t AInputEvent_getDeviceId(const AInputEvent* event);
-
-/* Get the input event source. */
-int32_t AInputEvent_getSource(const AInputEvent* event);
-
-/*** Accessors for key events only. ***/
-
-/* Get the key event action. */
-int32_t AKeyEvent_getAction(const AInputEvent* key_event);
-
-/* Get the key event flags. */
-int32_t AKeyEvent_getFlags(const AInputEvent* key_event);
-
-/* Get the key code of the key event.
- * This is the physical key that was pressed, not the Unicode character. */
-int32_t AKeyEvent_getKeyCode(const AInputEvent* key_event);
-
-/* Get the hardware key id of this key event.
- * These values are not reliable and vary from device to device. */
-int32_t AKeyEvent_getScanCode(const AInputEvent* key_event);
-
-/* Get the meta key state. */
-int32_t AKeyEvent_getMetaState(const AInputEvent* key_event);
-
-/* Get the repeat count of the event.
- * For both key up an key down events, this is the number of times the key has
- * repeated with the first down starting at 0 and counting up from there. For
- * multiple key events, this is the number of down/up pairs that have occurred. */
-int32_t AKeyEvent_getRepeatCount(const AInputEvent* key_event);
-
-/* Get the time of the most recent key down event, in the
- * java.lang.System.nanoTime() time base. If this is a down event,
- * this will be the same as eventTime.
- * Note that when chording keys, this value is the down time of the most recently
- * pressed key, which may not be the same physical key of this event. */
-int64_t AKeyEvent_getDownTime(const AInputEvent* key_event);
-
-/* Get the time this event occurred, in the
- * java.lang.System.nanoTime() time base. */
-int64_t AKeyEvent_getEventTime(const AInputEvent* key_event);
-
-/*** Accessors for motion events only. ***/
-
-/* Get the combined motion event action code and pointer index. */
-int32_t AMotionEvent_getAction(const AInputEvent* motion_event);
-
-/* Get the motion event flags. */
-int32_t AMotionEvent_getFlags(const AInputEvent* motion_event);
-
-/* Get the state of any meta / modifier keys that were in effect when the
- * event was generated. */
-int32_t AMotionEvent_getMetaState(const AInputEvent* motion_event);
-
-/* Get the button state of all buttons that are pressed. */
-int32_t AMotionEvent_getButtonState(const AInputEvent* motion_event);
-
-/* Get a bitfield indicating which edges, if any, were touched by this motion event.
- * For touch events, clients can use this to determine if the user's finger was
- * touching the edge of the display. */
-int32_t AMotionEvent_getEdgeFlags(const AInputEvent* motion_event);
-
-/* Get the time when the user originally pressed down to start a stream of
- * position events, in the java.lang.System.nanoTime() time base. */
-int64_t AMotionEvent_getDownTime(const AInputEvent* motion_event);
-
-/* Get the time when this specific event was generated,
- * in the java.lang.System.nanoTime() time base. */
-int64_t AMotionEvent_getEventTime(const AInputEvent* motion_event);
-
-/* Get the X coordinate offset.
- * For touch events on the screen, this is the delta that was added to the raw
- * screen coordinates to adjust for the absolute position of the containing windows
- * and views. */
-float AMotionEvent_getXOffset(const AInputEvent* motion_event);
-
-/* Get the precision of the Y coordinates being reported.
- * For touch events on the screen, this is the delta that was added to the raw
- * screen coordinates to adjust for the absolute position of the containing windows
- * and views. */
-float AMotionEvent_getYOffset(const AInputEvent* motion_event);
-
-/* Get the precision of the X coordinates being reported.
- * You can multiply this number with an X coordinate sample to find the
- * actual hardware value of the X coordinate. */
-float AMotionEvent_getXPrecision(const AInputEvent* motion_event);
-
-/* Get the precision of the Y coordinates being reported.
- * You can multiply this number with a Y coordinate sample to find the
- * actual hardware value of the Y coordinate. */
-float AMotionEvent_getYPrecision(const AInputEvent* motion_event);
-
-/* Get the number of pointers of data contained in this event.
- * Always >= 1. */
-size_t AMotionEvent_getPointerCount(const AInputEvent* motion_event);
-
-/* Get the pointer identifier associated with a particular pointer
- * data index in this event. The identifier tells you the actual pointer
- * number associated with the data, accounting for individual pointers
- * going up and down since the start of the current gesture. */
-int32_t AMotionEvent_getPointerId(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the tool type of a pointer for the given pointer index.
- * The tool type indicates the type of tool used to make contact such as a
- * finger or stylus, if known. */
-int32_t AMotionEvent_getToolType(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the original raw X coordinate of this event.
- * For touch events on the screen, this is the original location of the event
- * on the screen, before it had been adjusted for the containing window
- * and views. */
-float AMotionEvent_getRawX(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the original raw X coordinate of this event.
- * For touch events on the screen, this is the original location of the event
- * on the screen, before it had been adjusted for the containing window
- * and views. */
-float AMotionEvent_getRawY(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current X coordinate of this event for the given pointer index.
- * Whole numbers are pixels; the value may have a fraction for input devices
- * that are sub-pixel precise. */
-float AMotionEvent_getX(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current Y coordinate of this event for the given pointer index.
- * Whole numbers are pixels; the value may have a fraction for input devices
- * that are sub-pixel precise. */
-float AMotionEvent_getY(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current pressure of this event for the given pointer index.
- * The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure),
- * although values higher than 1 may be generated depending on the calibration of
- * the input device. */
-float AMotionEvent_getPressure(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current scaled value of the approximate size for the given pointer index.
- * This represents some approximation of the area of the screen being
- * pressed; the actual value in pixels corresponding to the
- * touch is normalized with the device specific range of values
- * and scaled to a value between 0 and 1. The value of size can be used to
- * determine fat touch events. */
-float AMotionEvent_getSize(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current length of the major axis of an ellipse that describes the touch area
- * at the point of contact for the given pointer index. */
-float AMotionEvent_getTouchMajor(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current length of the minor axis of an ellipse that describes the touch area
- * at the point of contact for the given pointer index. */
-float AMotionEvent_getTouchMinor(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current length of the major axis of an ellipse that describes the size
- * of the approaching tool for the given pointer index.
- * The tool area represents the estimated size of the finger or pen that is
- * touching the device independent of its actual touch area at the point of contact. */
-float AMotionEvent_getToolMajor(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current length of the minor axis of an ellipse that describes the size
- * of the approaching tool for the given pointer index.
- * The tool area represents the estimated size of the finger or pen that is
- * touching the device independent of its actual touch area at the point of contact. */
-float AMotionEvent_getToolMinor(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the current orientation of the touch area and tool area in radians clockwise from
- * vertical for the given pointer index.
- * An angle of 0 degrees indicates that the major axis of contact is oriented
- * upwards, is perfectly circular or is of unknown orientation. A positive angle
- * indicates that the major axis of contact is oriented to the right. A negative angle
- * indicates that the major axis of contact is oriented to the left.
- * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians
- * (finger pointing fully right). */
-float AMotionEvent_getOrientation(const AInputEvent* motion_event, size_t pointer_index);
-
-/* Get the value of the request axis for the given pointer index. */
-float AMotionEvent_getAxisValue(const AInputEvent* motion_event,
- int32_t axis, size_t pointer_index);
-
-/* Get the number of historical points in this event. These are movements that
- * have occurred between this event and the previous event. This only applies
- * to AMOTION_EVENT_ACTION_MOVE events -- all other actions will have a size of 0.
- * Historical samples are indexed from oldest to newest. */
-size_t AMotionEvent_getHistorySize(const AInputEvent* motion_event);
-
-/* Get the time that a historical movement occurred between this event and
- * the previous event, in the java.lang.System.nanoTime() time base. */
-int64_t AMotionEvent_getHistoricalEventTime(AInputEvent* motion_event,
- size_t history_index);
-
-/* Get the historical raw X coordinate of this event for the given pointer index that
- * occurred between this event and the previous motion event.
- * For touch events on the screen, this is the original location of the event
- * on the screen, before it had been adjusted for the containing window
- * and views.
- * Whole numbers are pixels; the value may have a fraction for input devices
- * that are sub-pixel precise. */
-float AMotionEvent_getHistoricalRawX(const AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical raw Y coordinate of this event for the given pointer index that
- * occurred between this event and the previous motion event.
- * For touch events on the screen, this is the original location of the event
- * on the screen, before it had been adjusted for the containing window
- * and views.
- * Whole numbers are pixels; the value may have a fraction for input devices
- * that are sub-pixel precise. */
-float AMotionEvent_getHistoricalRawY(const AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical X coordinate of this event for the given pointer index that
- * occurred between this event and the previous motion event.
- * Whole numbers are pixels; the value may have a fraction for input devices
- * that are sub-pixel precise. */
-float AMotionEvent_getHistoricalX(AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical Y coordinate of this event for the given pointer index that
- * occurred between this event and the previous motion event.
- * Whole numbers are pixels; the value may have a fraction for input devices
- * that are sub-pixel precise. */
-float AMotionEvent_getHistoricalY(AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical pressure of this event for the given pointer index that
- * occurred between this event and the previous motion event.
- * The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure),
- * although values higher than 1 may be generated depending on the calibration of
- * the input device. */
-float AMotionEvent_getHistoricalPressure(AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the current scaled value of the approximate size for the given pointer index that
- * occurred between this event and the previous motion event.
- * This represents some approximation of the area of the screen being
- * pressed; the actual value in pixels corresponding to the
- * touch is normalized with the device specific range of values
- * and scaled to a value between 0 and 1. The value of size can be used to
- * determine fat touch events. */
-float AMotionEvent_getHistoricalSize(AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical length of the major axis of an ellipse that describes the touch area
- * at the point of contact for the given pointer index that
- * occurred between this event and the previous motion event. */
-float AMotionEvent_getHistoricalTouchMajor(const AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical length of the minor axis of an ellipse that describes the touch area
- * at the point of contact for the given pointer index that
- * occurred between this event and the previous motion event. */
-float AMotionEvent_getHistoricalTouchMinor(const AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical length of the major axis of an ellipse that describes the size
- * of the approaching tool for the given pointer index that
- * occurred between this event and the previous motion event.
- * The tool area represents the estimated size of the finger or pen that is
- * touching the device independent of its actual touch area at the point of contact. */
-float AMotionEvent_getHistoricalToolMajor(const AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical length of the minor axis of an ellipse that describes the size
- * of the approaching tool for the given pointer index that
- * occurred between this event and the previous motion event.
- * The tool area represents the estimated size of the finger or pen that is
- * touching the device independent of its actual touch area at the point of contact. */
-float AMotionEvent_getHistoricalToolMinor(const AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical orientation of the touch area and tool area in radians clockwise from
- * vertical for the given pointer index that
- * occurred between this event and the previous motion event.
- * An angle of 0 degrees indicates that the major axis of contact is oriented
- * upwards, is perfectly circular or is of unknown orientation. A positive angle
- * indicates that the major axis of contact is oriented to the right. A negative angle
- * indicates that the major axis of contact is oriented to the left.
- * The full range is from -PI/2 radians (finger pointing fully left) to PI/2 radians
- * (finger pointing fully right). */
-float AMotionEvent_getHistoricalOrientation(const AInputEvent* motion_event, size_t pointer_index,
- size_t history_index);
-
-/* Get the historical value of the request axis for the given pointer index
- * that occurred between this event and the previous motion event. */
-float AMotionEvent_getHistoricalAxisValue(const AInputEvent* motion_event,
- int32_t axis, size_t pointer_index, size_t history_index);
-
-
-/*
- * Input queue
- *
- * An input queue is the facility through which you retrieve input
- * events.
- */
-struct AInputQueue;
-typedef struct AInputQueue AInputQueue;
-
-/*
- * Add this input queue to a looper for processing. See
- * ALooper_addFd() for information on the ident, callback, and data params.
- */
-void AInputQueue_attachLooper(AInputQueue* queue, ALooper* looper,
- int ident, ALooper_callbackFunc callback, void* data);
-
-/*
- * Remove the input queue from the looper it is currently attached to.
- */
-void AInputQueue_detachLooper(AInputQueue* queue);
-
-/*
- * Returns true if there are one or more events available in the
- * input queue. Returns 1 if the queue has events; 0 if
- * it does not have events; and a negative value if there is an error.
- */
-int32_t AInputQueue_hasEvents(AInputQueue* queue);
-
-/*
- * Returns the next available event from the queue. Returns a negative
- * value if no events are available or an error has occurred.
- */
-int32_t AInputQueue_getEvent(AInputQueue* queue, AInputEvent** outEvent);
-
-/*
- * Sends the key for standard pre-dispatching -- that is, possibly deliver
- * it to the current IME to be consumed before the app. Returns 0 if it
- * was not pre-dispatched, meaning you can process it right now. If non-zero
- * is returned, you must abandon the current event processing and allow the
- * event to appear again in the event queue (if it does not get consumed during
- * pre-dispatching).
- */
-int32_t AInputQueue_preDispatchEvent(AInputQueue* queue, AInputEvent* event);
-
-/*
- * Report that dispatching has finished with the given event.
- * This must be called after receiving an event with AInputQueue_get_event().
- */
-void AInputQueue_finishEvent(AInputQueue* queue, AInputEvent* event, int handled);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _ANDROID_INPUT_H
diff --git a/widget/gonk/libui/android_keycodes.h b/widget/gonk/libui/android_keycodes.h
deleted file mode 100644
index 9e63d1d01..000000000
--- a/widget/gonk/libui/android_keycodes.h
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _ANDROID_KEYCODES_H
-#define _ANDROID_KEYCODES_H
-
-/******************************************************************
- *
- * IMPORTANT NOTICE:
- *
- * This file is part of Android's set of stable system headers
- * exposed by the Android NDK (Native Development Kit).
- *
- * Third-party source AND binary code relies on the definitions
- * here to be FROZEN ON ALL UPCOMING PLATFORM RELEASES.
- *
- * - DO NOT MODIFY ENUMS (EXCEPT IF YOU ADD NEW 32-BIT VALUES)
- * - DO NOT MODIFY CONSTANTS OR FUNCTIONAL MACROS
- * - DO NOT CHANGE THE SIGNATURE OF FUNCTIONS IN ANY WAY
- * - DO NOT CHANGE THE LAYOUT OR SIZE OF STRUCTURES
- */
-
-#include <sys/types.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Key codes.
- */
-enum {
- AKEYCODE_UNKNOWN = 0,
- AKEYCODE_SOFT_LEFT = 1,
- AKEYCODE_SOFT_RIGHT = 2,
- AKEYCODE_HOME = 3,
- AKEYCODE_BACK = 4,
- AKEYCODE_CALL = 5,
- AKEYCODE_ENDCALL = 6,
- AKEYCODE_0 = 7,
- AKEYCODE_1 = 8,
- AKEYCODE_2 = 9,
- AKEYCODE_3 = 10,
- AKEYCODE_4 = 11,
- AKEYCODE_5 = 12,
- AKEYCODE_6 = 13,
- AKEYCODE_7 = 14,
- AKEYCODE_8 = 15,
- AKEYCODE_9 = 16,
- AKEYCODE_STAR = 17,
- AKEYCODE_POUND = 18,
- AKEYCODE_DPAD_UP = 19,
- AKEYCODE_DPAD_DOWN = 20,
- AKEYCODE_DPAD_LEFT = 21,
- AKEYCODE_DPAD_RIGHT = 22,
- AKEYCODE_DPAD_CENTER = 23,
- AKEYCODE_VOLUME_UP = 24,
- AKEYCODE_VOLUME_DOWN = 25,
- AKEYCODE_POWER = 26,
- AKEYCODE_CAMERA = 27,
- AKEYCODE_CLEAR = 28,
- AKEYCODE_A = 29,
- AKEYCODE_B = 30,
- AKEYCODE_C = 31,
- AKEYCODE_D = 32,
- AKEYCODE_E = 33,
- AKEYCODE_F = 34,
- AKEYCODE_G = 35,
- AKEYCODE_H = 36,
- AKEYCODE_I = 37,
- AKEYCODE_J = 38,
- AKEYCODE_K = 39,
- AKEYCODE_L = 40,
- AKEYCODE_M = 41,
- AKEYCODE_N = 42,
- AKEYCODE_O = 43,
- AKEYCODE_P = 44,
- AKEYCODE_Q = 45,
- AKEYCODE_R = 46,
- AKEYCODE_S = 47,
- AKEYCODE_T = 48,
- AKEYCODE_U = 49,
- AKEYCODE_V = 50,
- AKEYCODE_W = 51,
- AKEYCODE_X = 52,
- AKEYCODE_Y = 53,
- AKEYCODE_Z = 54,
- AKEYCODE_COMMA = 55,
- AKEYCODE_PERIOD = 56,
- AKEYCODE_ALT_LEFT = 57,
- AKEYCODE_ALT_RIGHT = 58,
- AKEYCODE_SHIFT_LEFT = 59,
- AKEYCODE_SHIFT_RIGHT = 60,
- AKEYCODE_TAB = 61,
- AKEYCODE_SPACE = 62,
- AKEYCODE_SYM = 63,
- AKEYCODE_EXPLORER = 64,
- AKEYCODE_ENVELOPE = 65,
- AKEYCODE_ENTER = 66,
- AKEYCODE_DEL = 67,
- AKEYCODE_GRAVE = 68,
- AKEYCODE_MINUS = 69,
- AKEYCODE_EQUALS = 70,
- AKEYCODE_LEFT_BRACKET = 71,
- AKEYCODE_RIGHT_BRACKET = 72,
- AKEYCODE_BACKSLASH = 73,
- AKEYCODE_SEMICOLON = 74,
- AKEYCODE_APOSTROPHE = 75,
- AKEYCODE_SLASH = 76,
- AKEYCODE_AT = 77,
- AKEYCODE_NUM = 78,
- AKEYCODE_HEADSETHOOK = 79,
- AKEYCODE_FOCUS = 80, // *Camera* focus
- AKEYCODE_PLUS = 81,
- AKEYCODE_MENU = 82,
- AKEYCODE_NOTIFICATION = 83,
- AKEYCODE_SEARCH = 84,
- AKEYCODE_MEDIA_PLAY_PAUSE= 85,
- AKEYCODE_MEDIA_STOP = 86,
- AKEYCODE_MEDIA_NEXT = 87,
- AKEYCODE_MEDIA_PREVIOUS = 88,
- AKEYCODE_MEDIA_REWIND = 89,
- AKEYCODE_MEDIA_FAST_FORWARD = 90,
- AKEYCODE_MUTE = 91,
- AKEYCODE_PAGE_UP = 92,
- AKEYCODE_PAGE_DOWN = 93,
- AKEYCODE_PICTSYMBOLS = 94,
- AKEYCODE_SWITCH_CHARSET = 95,
- AKEYCODE_BUTTON_A = 96,
- AKEYCODE_BUTTON_B = 97,
- AKEYCODE_BUTTON_C = 98,
- AKEYCODE_BUTTON_X = 99,
- AKEYCODE_BUTTON_Y = 100,
- AKEYCODE_BUTTON_Z = 101,
- AKEYCODE_BUTTON_L1 = 102,
- AKEYCODE_BUTTON_R1 = 103,
- AKEYCODE_BUTTON_L2 = 104,
- AKEYCODE_BUTTON_R2 = 105,
- AKEYCODE_BUTTON_THUMBL = 106,
- AKEYCODE_BUTTON_THUMBR = 107,
- AKEYCODE_BUTTON_START = 108,
- AKEYCODE_BUTTON_SELECT = 109,
- AKEYCODE_BUTTON_MODE = 110,
- AKEYCODE_ESCAPE = 111,
- AKEYCODE_FORWARD_DEL = 112,
- AKEYCODE_CTRL_LEFT = 113,
- AKEYCODE_CTRL_RIGHT = 114,
- AKEYCODE_CAPS_LOCK = 115,
- AKEYCODE_SCROLL_LOCK = 116,
- AKEYCODE_META_LEFT = 117,
- AKEYCODE_META_RIGHT = 118,
- AKEYCODE_FUNCTION = 119,
- AKEYCODE_SYSRQ = 120,
- AKEYCODE_BREAK = 121,
- AKEYCODE_MOVE_HOME = 122,
- AKEYCODE_MOVE_END = 123,
- AKEYCODE_INSERT = 124,
- AKEYCODE_FORWARD = 125,
- AKEYCODE_MEDIA_PLAY = 126,
- AKEYCODE_MEDIA_PAUSE = 127,
- AKEYCODE_MEDIA_CLOSE = 128,
- AKEYCODE_MEDIA_EJECT = 129,
- AKEYCODE_MEDIA_RECORD = 130,
- AKEYCODE_F1 = 131,
- AKEYCODE_F2 = 132,
- AKEYCODE_F3 = 133,
- AKEYCODE_F4 = 134,
- AKEYCODE_F5 = 135,
- AKEYCODE_F6 = 136,
- AKEYCODE_F7 = 137,
- AKEYCODE_F8 = 138,
- AKEYCODE_F9 = 139,
- AKEYCODE_F10 = 140,
- AKEYCODE_F11 = 141,
- AKEYCODE_F12 = 142,
- AKEYCODE_NUM_LOCK = 143,
- AKEYCODE_NUMPAD_0 = 144,
- AKEYCODE_NUMPAD_1 = 145,
- AKEYCODE_NUMPAD_2 = 146,
- AKEYCODE_NUMPAD_3 = 147,
- AKEYCODE_NUMPAD_4 = 148,
- AKEYCODE_NUMPAD_5 = 149,
- AKEYCODE_NUMPAD_6 = 150,
- AKEYCODE_NUMPAD_7 = 151,
- AKEYCODE_NUMPAD_8 = 152,
- AKEYCODE_NUMPAD_9 = 153,
- AKEYCODE_NUMPAD_DIVIDE = 154,
- AKEYCODE_NUMPAD_MULTIPLY = 155,
- AKEYCODE_NUMPAD_SUBTRACT = 156,
- AKEYCODE_NUMPAD_ADD = 157,
- AKEYCODE_NUMPAD_DOT = 158,
- AKEYCODE_NUMPAD_COMMA = 159,
- AKEYCODE_NUMPAD_ENTER = 160,
- AKEYCODE_NUMPAD_EQUALS = 161,
- AKEYCODE_NUMPAD_LEFT_PAREN = 162,
- AKEYCODE_NUMPAD_RIGHT_PAREN = 163,
- AKEYCODE_VOLUME_MUTE = 164,
- AKEYCODE_INFO = 165,
- AKEYCODE_CHANNEL_UP = 166,
- AKEYCODE_CHANNEL_DOWN = 167,
- AKEYCODE_ZOOM_IN = 168,
- AKEYCODE_ZOOM_OUT = 169,
- AKEYCODE_TV = 170,
- AKEYCODE_WINDOW = 171,
- AKEYCODE_GUIDE = 172,
- AKEYCODE_DVR = 173,
- AKEYCODE_BOOKMARK = 174,
- AKEYCODE_CAPTIONS = 175,
- AKEYCODE_SETTINGS = 176,
- AKEYCODE_TV_POWER = 177,
- AKEYCODE_TV_INPUT = 178,
- AKEYCODE_STB_POWER = 179,
- AKEYCODE_STB_INPUT = 180,
- AKEYCODE_AVR_POWER = 181,
- AKEYCODE_AVR_INPUT = 182,
- AKEYCODE_PROG_RED = 183,
- AKEYCODE_PROG_GREEN = 184,
- AKEYCODE_PROG_YELLOW = 185,
- AKEYCODE_PROG_BLUE = 186,
- AKEYCODE_APP_SWITCH = 187,
- AKEYCODE_BUTTON_1 = 188,
- AKEYCODE_BUTTON_2 = 189,
- AKEYCODE_BUTTON_3 = 190,
- AKEYCODE_BUTTON_4 = 191,
- AKEYCODE_BUTTON_5 = 192,
- AKEYCODE_BUTTON_6 = 193,
- AKEYCODE_BUTTON_7 = 194,
- AKEYCODE_BUTTON_8 = 195,
- AKEYCODE_BUTTON_9 = 196,
- AKEYCODE_BUTTON_10 = 197,
- AKEYCODE_BUTTON_11 = 198,
- AKEYCODE_BUTTON_12 = 199,
- AKEYCODE_BUTTON_13 = 200,
- AKEYCODE_BUTTON_14 = 201,
- AKEYCODE_BUTTON_15 = 202,
- AKEYCODE_BUTTON_16 = 203,
- AKEYCODE_LANGUAGE_SWITCH = 204,
- AKEYCODE_MANNER_MODE = 205,
- AKEYCODE_3D_MODE = 206,
- AKEYCODE_CONTACTS = 207,
- AKEYCODE_CALENDAR = 208,
- AKEYCODE_MUSIC = 209,
- AKEYCODE_CALCULATOR = 210,
- AKEYCODE_ZENKAKU_HANKAKU = 211,
- AKEYCODE_EISU = 212,
- AKEYCODE_MUHENKAN = 213,
- AKEYCODE_HENKAN = 214,
- AKEYCODE_KATAKANA_HIRAGANA = 215,
- AKEYCODE_YEN = 216,
- AKEYCODE_RO = 217,
- AKEYCODE_KANA = 218,
- AKEYCODE_ASSIST = 219,
- AKEYCODE_BRIGHTNESS_DOWN = 220,
- AKEYCODE_BRIGHTNESS_UP = 221,
- AKEYCODE_MEDIA_AUDIO_TRACK = 222,
- AKEYCODE_SLEEP = 223,
- AKEYCODE_WAKEUP = 224,
- AKEYCODE_PAIRING = 225,
- AKEYCODE_MEDIA_TOP_MENU = 226,
- AKEYCODE_11 = 227,
- AKEYCODE_12 = 228,
- AKEYCODE_LAST_CHANNEL = 229,
- AKEYCODE_TV_DATA_SERVICE = 230,
- AKEYCODE_VOICE_ASSIST = 231,
- AKEYCODE_TV_RADIO_SERVICE = 232,
- AKEYCODE_TV_TELETEXT = 233,
- AKEYCODE_TV_NUMBER_ENTRY = 234,
- AKEYCODE_TV_TERRESTRIAL_ANALOG = 235,
- AKEYCODE_TV_TERRESTRIAL_DIGITAL = 236,
- AKEYCODE_TV_SATELLITE = 237,
- AKEYCODE_TV_SATELLITE_BS = 238,
- AKEYCODE_TV_SATELLITE_CS = 239,
- AKEYCODE_TV_SATELLITE_SERVICE = 240,
- AKEYCODE_TV_NETWORK = 241,
- AKEYCODE_TV_ANTENNA_CABLE = 242,
- AKEYCODE_TV_INPUT_HDMI_1 = 243,
- AKEYCODE_TV_INPUT_HDMI_2 = 244,
- AKEYCODE_TV_INPUT_HDMI_3 = 245,
- AKEYCODE_TV_INPUT_HDMI_4 = 246,
- AKEYCODE_TV_INPUT_COMPOSITE_1 = 247,
- AKEYCODE_TV_INPUT_COMPOSITE_2 = 248,
- AKEYCODE_TV_INPUT_COMPONENT_1 = 249,
- AKEYCODE_TV_INPUT_COMPONENT_2 = 250,
- AKEYCODE_TV_INPUT_VGA_1 = 251,
- AKEYCODE_TV_AUDIO_DESCRIPTION = 252,
- AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP = 253,
- AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN = 254,
- AKEYCODE_TV_ZOOM_MODE = 255,
- AKEYCODE_TV_CONTENTS_MENU = 256,
- AKEYCODE_TV_MEDIA_CONTEXT_MENU = 257,
- AKEYCODE_TV_TIMER_PROGRAMMING = 258,
- AKEYCODE_HELP = 259,
-
- // NOTE: If you add a new keycode here you must also add it to several other files.
- // Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
-};
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _ANDROID_KEYCODES_H
diff --git a/widget/gonk/libui/cutils_log.h b/widget/gonk/libui/cutils_log.h
deleted file mode 100644
index f4252c867..000000000
--- a/widget/gonk/libui/cutils_log.h
+++ /dev/null
@@ -1,569 +0,0 @@
-/*
- * Copyright (C) 2005 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//
-// C/C++ logging functions. See the logging documentation for API details.
-//
-// We'd like these to be available from C code (in case we import some from
-// somewhere), so this has a C interface.
-//
-// The output will be correct when the log file is shared between multiple
-// threads and/or multiple processes so long as the operating system
-// supports O_APPEND. These calls have mutex-protected data structures
-// and so are NOT reentrant. Do not use LOG in a signal handler.
-//
-#if !defined(_LIBS_CUTILS_LOG_H) && !defined(_LIBS_LOG_LOG_H)
-#define _LIBS_LOG_LOG_H
-#define _LIBS_CUTILS_LOG_H
-
-#include <stdio.h>
-#include <time.h>
-#include <sys/types.h>
-#include <unistd.h>
-#ifdef HAVE_PTHREADS
-#include <pthread.h>
-#endif
-#include <stdarg.h>
-
-#if ANDROID_VERSION >= 19
-#include <log/uio.h>
-#include <log/logd.h>
-#else
-#include <cutils/uio.h>
-#include <cutils/logd.h>
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Normally we strip ALOGV (VERBOSE messages) from release builds.
- * You can modify this (for example with "#define LOG_NDEBUG 0"
- * at the top of your source file) to change that behavior.
- */
-#ifndef LOG_NDEBUG
-#ifdef NDEBUG
-#define LOG_NDEBUG 1
-#else
-#define LOG_NDEBUG 0
-#endif
-#endif
-
-/*
- * This is the local tag used for the following simplified
- * logging macros. You can change this preprocessor definition
- * before using the other macros to change the tag.
- */
-#ifndef LOG_TAG
-#define LOG_TAG NULL
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Simplified macro to send a verbose log message using the current LOG_TAG.
- */
-#ifndef ALOGV
-#if LOG_NDEBUG
-#define ALOGV(...) ((void)0)
-#else
-#define ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
-#endif
-#endif
-
-#define CONDITION(cond) (__builtin_expect((cond)!=0, 0))
-
-#ifndef ALOGV_IF
-#if LOG_NDEBUG
-#define ALOGV_IF(cond, ...) ((void)0)
-#else
-#define ALOGV_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-#endif
-
-/*
- * Simplified macro to send a debug log message using the current LOG_TAG.
- */
-#ifndef ALOGD
-#define ALOGD(...) ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef ALOGD_IF
-#define ALOGD_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)ALOG(LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an info log message using the current LOG_TAG.
- */
-#ifndef ALOGI
-#define ALOGI(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef ALOGI_IF
-#define ALOGI_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send a warning log message using the current LOG_TAG.
- */
-#ifndef ALOGW
-#define ALOGW(...) ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef ALOGW_IF
-#define ALOGW_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)ALOG(LOG_WARN, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an error log message using the current LOG_TAG.
- */
-#ifndef ALOGE
-#define ALOGE(...) ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef ALOGE_IF
-#define ALOGE_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)ALOG(LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * verbose priority.
- */
-#ifndef IF_ALOGV
-#if LOG_NDEBUG
-#define IF_ALOGV() if (false)
-#else
-#define IF_ALOGV() IF_ALOG(LOG_VERBOSE, LOG_TAG)
-#endif
-#endif
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * debug priority.
- */
-#ifndef IF_ALOGD
-#define IF_ALOGD() IF_ALOG(LOG_DEBUG, LOG_TAG)
-#endif
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * info priority.
- */
-#ifndef IF_ALOGI
-#define IF_ALOGI() IF_ALOG(LOG_INFO, LOG_TAG)
-#endif
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * warn priority.
- */
-#ifndef IF_ALOGW
-#define IF_ALOGW() IF_ALOG(LOG_WARN, LOG_TAG)
-#endif
-
-/*
- * Conditional based on whether the current LOG_TAG is enabled at
- * error priority.
- */
-#ifndef IF_ALOGE
-#define IF_ALOGE() IF_ALOG(LOG_ERROR, LOG_TAG)
-#endif
-
-
-// ---------------------------------------------------------------------
-
-/*
- * Simplified macro to send a verbose system log message using the current LOG_TAG.
- */
-#ifndef SLOGV
-#if LOG_NDEBUG
-#define SLOGV(...) ((void)0)
-#else
-#define SLOGV(...) ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
-#endif
-#endif
-
-#define CONDITION(cond) (__builtin_expect((cond)!=0, 0))
-
-#ifndef SLOGV_IF
-#if LOG_NDEBUG
-#define SLOGV_IF(cond, ...) ((void)0)
-#else
-#define SLOGV_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-#endif
-
-/*
- * Simplified macro to send a debug system log message using the current LOG_TAG.
- */
-#ifndef SLOGD
-#define SLOGD(...) ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef SLOGD_IF
-#define SLOGD_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an info system log message using the current LOG_TAG.
- */
-#ifndef SLOGI
-#define SLOGI(...) ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef SLOGI_IF
-#define SLOGI_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send a warning system log message using the current LOG_TAG.
- */
-#ifndef SLOGW
-#define SLOGW(...) ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef SLOGW_IF
-#define SLOGW_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an error system log message using the current LOG_TAG.
- */
-#ifndef SLOGE
-#define SLOGE(...) ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef SLOGE_IF
-#define SLOGE_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_SYSTEM, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Simplified macro to send a verbose radio log message using the current LOG_TAG.
- */
-#ifndef RLOGV
-#if LOG_NDEBUG
-#define RLOGV(...) ((void)0)
-#else
-#define RLOGV(...) ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
-#endif
-#endif
-
-#define CONDITION(cond) (__builtin_expect((cond)!=0, 0))
-
-#ifndef RLOGV_IF
-#if LOG_NDEBUG
-#define RLOGV_IF(cond, ...) ((void)0)
-#else
-#define RLOGV_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-#endif
-
-/*
- * Simplified macro to send a debug radio log message using the current LOG_TAG.
- */
-#ifndef RLOGD
-#define RLOGD(...) ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef RLOGD_IF
-#define RLOGD_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an info radio log message using the current LOG_TAG.
- */
-#ifndef RLOGI
-#define RLOGI(...) ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef RLOGI_IF
-#define RLOGI_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send a warning radio log message using the current LOG_TAG.
- */
-#ifndef RLOGW
-#define RLOGW(...) ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef RLOGW_IF
-#define RLOGW_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-/*
- * Simplified macro to send an error radio log message using the current LOG_TAG.
- */
-#ifndef RLOGE
-#define RLOGE(...) ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
-#endif
-
-#ifndef RLOGE_IF
-#define RLOGE_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)__android_log_buf_print(LOG_ID_RADIO, ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-
-// ---------------------------------------------------------------------
-
-/*
- * Log a fatal error. If the given condition fails, this stops program
- * execution like a normal assertion, but also generating the given message.
- * It is NOT stripped from release builds. Note that the condition test
- * is -inverted- from the normal assert() semantics.
- */
-#ifndef LOG_ALWAYS_FATAL_IF
-#define LOG_ALWAYS_FATAL_IF(cond, ...) \
- ( (CONDITION(cond)) \
- ? ((void)android_printAssert(#cond, LOG_TAG, ## __VA_ARGS__)) \
- : (void)0 )
-#endif
-
-#ifndef LOG_ALWAYS_FATAL
-#define LOG_ALWAYS_FATAL(...) \
- ( ((void)android_printAssert(NULL, LOG_TAG, ## __VA_ARGS__)) )
-#endif
-
-/*
- * Versions of LOG_ALWAYS_FATAL_IF and LOG_ALWAYS_FATAL that
- * are stripped out of release builds.
- */
-#if LOG_NDEBUG
-
-#ifndef LOG_FATAL_IF
-#define LOG_FATAL_IF(cond, ...) ((void)0)
-#endif
-#ifndef LOG_FATAL
-#define LOG_FATAL(...) ((void)0)
-#endif
-
-#else
-
-#ifndef LOG_FATAL_IF
-#define LOG_FATAL_IF(cond, ...) LOG_ALWAYS_FATAL_IF(cond, ## __VA_ARGS__)
-#endif
-#ifndef LOG_FATAL
-#define LOG_FATAL(...) LOG_ALWAYS_FATAL(__VA_ARGS__)
-#endif
-
-#endif
-
-/*
- * Assertion that generates a log message when the assertion fails.
- * Stripped out of release builds. Uses the current LOG_TAG.
- */
-#ifndef ALOG_ASSERT
-#define ALOG_ASSERT(cond, ...) LOG_FATAL_IF(!(cond), ## __VA_ARGS__)
-//#define ALOG_ASSERT(cond) LOG_FATAL_IF(!(cond), "Assertion failed: " #cond)
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Basic log message macro.
- *
- * Example:
- * ALOG(LOG_WARN, NULL, "Failed with error %d", errno);
- *
- * The second argument may be NULL or "" to indicate the "global" tag.
- */
-#ifndef ALOG
-#define ALOG(priority, tag, ...) \
- LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
-#endif
-
-/*
- * Log macro that allows you to specify a number for the priority.
- */
-#ifndef LOG_PRI
-#define LOG_PRI(priority, tag, ...) \
- android_printLog(priority, tag, __VA_ARGS__)
-#endif
-
-/*
- * Log macro that allows you to pass in a varargs ("args" is a va_list).
- */
-#ifndef LOG_PRI_VA
-#define LOG_PRI_VA(priority, tag, fmt, args) \
- android_vprintLog(priority, NULL, tag, fmt, args)
-#endif
-
-/*
- * Conditional given a desired logging priority and tag.
- */
-#ifndef IF_ALOG
-#define IF_ALOG(priority, tag) \
- if (android_testLog(ANDROID_##priority, tag))
-#endif
-
-// ---------------------------------------------------------------------
-
-/*
- * Event logging.
- */
-
-/*
- * Event log entry types. These must match up with the declarations in
- * java/android/android/util/EventLog.java.
- */
-typedef enum {
- EVENT_TYPE_INT = 0,
- EVENT_TYPE_LONG = 1,
- EVENT_TYPE_STRING = 2,
- EVENT_TYPE_LIST = 3,
-} AndroidEventLogType;
-
-
-#ifndef LOG_EVENT_INT
-#define LOG_EVENT_INT(_tag, _value) { \
- int intBuf = _value; \
- (void) android_btWriteLog(_tag, EVENT_TYPE_INT, &intBuf, \
- sizeof(intBuf)); \
- }
-#endif
-#ifndef LOG_EVENT_LONG
-#define LOG_EVENT_LONG(_tag, _value) { \
- long long longBuf = _value; \
- (void) android_btWriteLog(_tag, EVENT_TYPE_LONG, &longBuf, \
- sizeof(longBuf)); \
- }
-#endif
-#ifndef LOG_EVENT_STRING
-#define LOG_EVENT_STRING(_tag, _value) \
- ((void) 0) /* not implemented -- must combine len with string */
-#endif
-/* TODO: something for LIST */
-
-/*
- * ===========================================================================
- *
- * The stuff in the rest of this file should not be used directly.
- */
-
-#define android_printLog(prio, tag, fmt...) \
- __android_log_print(prio, tag, fmt)
-
-#define android_vprintLog(prio, cond, tag, fmt...) \
- __android_log_vprint(prio, tag, fmt)
-
-/* XXX Macros to work around syntax errors in places where format string
- * arg is not passed to ALOG_ASSERT, LOG_ALWAYS_FATAL or LOG_ALWAYS_FATAL_IF
- * (happens only in debug builds).
- */
-
-/* Returns 2nd arg. Used to substitute default value if caller's vararg list
- * is empty.
- */
-#define __android_second(dummy, second, ...) second
-
-/* If passed multiple args, returns ',' followed by all but 1st arg, otherwise
- * returns nothing.
- */
-#define __android_rest(first, ...) , ## __VA_ARGS__
-
-#define android_printAssert(cond, tag, fmt...) \
- __android_log_assert(cond, tag, \
- __android_second(0, ## fmt, NULL) __android_rest(fmt))
-
-#define android_writeLog(prio, tag, text) \
- __android_log_write(prio, tag, text)
-
-#define android_bWriteLog(tag, payload, len) \
- __android_log_bwrite(tag, payload, len)
-#define android_btWriteLog(tag, type, payload, len) \
- __android_log_btwrite(tag, type, payload, len)
-
-// TODO: remove these prototypes and their users
-#define android_testLog(prio, tag) (1)
-#define android_writevLog(vec,num) do{}while(0)
-#define android_write1Log(str,len) do{}while (0)
-#define android_setMinPriority(tag, prio) do{}while(0)
-//#define android_logToCallback(func) do{}while(0)
-#define android_logToFile(tag, file) (0)
-#define android_logToFd(tag, fd) (0)
-
-typedef enum {
- LOG_ID_MAIN = 0,
- LOG_ID_RADIO = 1,
- LOG_ID_EVENTS = 2,
- LOG_ID_SYSTEM = 3,
-
- LOG_ID_MAX
-} log_id_t;
-
-/*
- * Send a simple string to the log.
- */
-int __android_log_buf_write(int bufID, int prio, const char *tag, const char *text);
-int __android_log_buf_print(int bufID, int prio, const char *tag, const char *fmt, ...);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _LIBS_CUTILS_LOG_H
diff --git a/widget/gonk/libui/cutils_trace.h b/widget/gonk/libui/cutils_trace.h
deleted file mode 100644
index 29034cab5..000000000
--- a/widget/gonk/libui/cutils_trace.h
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _LIBS_CUTILS_TRACE_H
-#define _LIBS_CUTILS_TRACE_H
-
-#include <sys/cdefs.h>
-#include <sys/types.h>
-#include <stdint.h>
-#include <stdbool.h>
-#include <unistd.h>
-#include <cutils/compiler.h>
-
-#ifdef ANDROID_SMP
-#include <cutils/atomic-inline.h>
-#else
-#include <cutils/atomic.h>
-#endif
-
-__BEGIN_DECLS
-
-/**
- * The ATRACE_TAG macro can be defined before including this header to trace
- * using one of the tags defined below. It must be defined to one of the
- * following ATRACE_TAG_* macros. The trace tag is used to filter tracing in
- * userland to avoid some of the runtime cost of tracing when it is not desired.
- *
- * Defining ATRACE_TAG to be ATRACE_TAG_ALWAYS will result in the tracing always
- * being enabled - this should ONLY be done for debug code, as userland tracing
- * has a performance cost even when the trace is not being recorded. Defining
- * ATRACE_TAG to be ATRACE_TAG_NEVER or leaving ATRACE_TAG undefined will result
- * in the tracing always being disabled.
- *
- * ATRACE_TAG_HAL should be bitwise ORed with the relevant tags for tracing
- * within a hardware module. For example a camera hardware module would set:
- * #define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
- *
- * Keep these in sync with frameworks/base/core/java/android/os/Trace.java.
- */
-#define ATRACE_TAG_NEVER 0 // This tag is never enabled.
-#define ATRACE_TAG_ALWAYS (1<<0) // This tag is always enabled.
-#define ATRACE_TAG_GRAPHICS (1<<1)
-#define ATRACE_TAG_INPUT (1<<2)
-#define ATRACE_TAG_VIEW (1<<3)
-#define ATRACE_TAG_WEBVIEW (1<<4)
-#define ATRACE_TAG_WINDOW_MANAGER (1<<5)
-#define ATRACE_TAG_ACTIVITY_MANAGER (1<<6)
-#define ATRACE_TAG_SYNC_MANAGER (1<<7)
-#define ATRACE_TAG_AUDIO (1<<8)
-#define ATRACE_TAG_VIDEO (1<<9)
-#define ATRACE_TAG_CAMERA (1<<10)
-#define ATRACE_TAG_HAL (1<<11)
-#define ATRACE_TAG_APP (1<<12)
-#define ATRACE_TAG_RESOURCES (1<<13)
-#define ATRACE_TAG_DALVIK (1<<14)
-#define ATRACE_TAG_LAST ATRACE_TAG_DALVIK
-
-// Reserved for initialization.
-#define ATRACE_TAG_NOT_READY (1LL<<63)
-
-#define ATRACE_TAG_VALID_MASK ((ATRACE_TAG_LAST - 1) | ATRACE_TAG_LAST)
-
-#ifndef ATRACE_TAG
-#define ATRACE_TAG ATRACE_TAG_NEVER
-#elif ATRACE_TAG > ATRACE_TAG_VALID_MASK
-#error ATRACE_TAG must be defined to be one of the tags defined in cutils/trace.h
-#endif
-
-#ifdef HAVE_ANDROID_OS
-/**
- * Maximum size of a message that can be logged to the trace buffer.
- * Note this message includes a tag, the pid, and the string given as the name.
- * Names should be kept short to get the most use of the trace buffer.
- */
-#define ATRACE_MESSAGE_LENGTH 1024
-
-/**
- * Opens the trace file for writing and reads the property for initial tags.
- * The atrace.tags.enableflags property sets the tags to trace.
- * This function should not be explicitly called, the first call to any normal
- * trace function will cause it to be run safely.
- */
-void atrace_setup();
-
-/**
- * If tracing is ready, set atrace_enabled_tags to the system property
- * debug.atrace.tags.enableflags. Can be used as a sysprop change callback.
- */
-void atrace_update_tags();
-
-/**
- * Set whether the process is debuggable. By default the process is not
- * considered debuggable. If the process is not debuggable then application-
- * level tracing is not allowed unless the ro.debuggable system property is
- * set to '1'.
- */
-void atrace_set_debuggable(bool debuggable);
-
-/**
- * Set whether tracing is enabled for the current process. This is used to
- * prevent tracing within the Zygote process.
- */
-void atrace_set_tracing_enabled(bool enabled);
-
-/**
- * Flag indicating whether setup has been completed, initialized to 0.
- * Nonzero indicates setup has completed.
- * Note: This does NOT indicate whether or not setup was successful.
- */
-extern volatile int32_t atrace_is_ready;
-
-/**
- * Set of ATRACE_TAG flags to trace for, initialized to ATRACE_TAG_NOT_READY.
- * A value of zero indicates setup has failed.
- * Any other nonzero value indicates setup has succeeded, and tracing is on.
- */
-extern uint64_t atrace_enabled_tags;
-
-/**
- * Handle to the kernel's trace buffer, initialized to -1.
- * Any other value indicates setup has succeeded, and is a valid fd for tracing.
- */
-extern int atrace_marker_fd;
-
-/**
- * atrace_init readies the process for tracing by opening the trace_marker file.
- * Calling any trace function causes this to be run, so calling it is optional.
- * This can be explicitly run to avoid setup delay on first trace function.
- */
-#define ATRACE_INIT() atrace_init()
-static inline void atrace_init()
-{
- if (CC_UNLIKELY(!android_atomic_acquire_load(&atrace_is_ready))) {
- atrace_setup();
- }
-}
-
-/**
- * Get the mask of all tags currently enabled.
- * It can be used as a guard condition around more expensive trace calculations.
- * Every trace function calls this, which ensures atrace_init is run.
- */
-#define ATRACE_GET_ENABLED_TAGS() atrace_get_enabled_tags()
-static inline uint64_t atrace_get_enabled_tags()
-{
- atrace_init();
- return atrace_enabled_tags;
-}
-
-/**
- * Test if a given tag is currently enabled.
- * Returns nonzero if the tag is enabled, otherwise zero.
- * It can be used as a guard condition around more expensive trace calculations.
- */
-#define ATRACE_ENABLED() atrace_is_tag_enabled(ATRACE_TAG)
-static inline uint64_t atrace_is_tag_enabled(uint64_t tag)
-{
- return atrace_get_enabled_tags() & tag;
-}
-
-/**
- * Trace the beginning of a context. name is used to identify the context.
- * This is often used to time function execution.
- */
-#define ATRACE_BEGIN(name) atrace_begin(ATRACE_TAG, name)
-static inline void atrace_begin(uint64_t tag, const char* name)
-{
- if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
- char buf[ATRACE_MESSAGE_LENGTH];
- size_t len;
-
- len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "B|%d|%s", getpid(), name);
- write(atrace_marker_fd, buf, len);
- }
-}
-
-/**
- * Trace the end of a context.
- * This should match up (and occur after) a corresponding ATRACE_BEGIN.
- */
-#define ATRACE_END() atrace_end(ATRACE_TAG)
-static inline void atrace_end(uint64_t tag)
-{
- if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
- char c = 'E';
- write(atrace_marker_fd, &c, 1);
- }
-}
-
-/**
- * Trace the beginning of an asynchronous event. Unlike ATRACE_BEGIN/ATRACE_END
- * contexts, asynchronous events do not need to be nested. The name describes
- * the event, and the cookie provides a unique identifier for distinguishing
- * simultaneous events. The name and cookie used to begin an event must be
- * used to end it.
- */
-#define ATRACE_ASYNC_BEGIN(name, cookie) \
- atrace_async_begin(ATRACE_TAG, name, cookie)
-static inline void atrace_async_begin(uint64_t tag, const char* name,
- int32_t cookie)
-{
- if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
- char buf[ATRACE_MESSAGE_LENGTH];
- size_t len;
-
- len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "S|%d|%s|%d", getpid(),
- name, cookie);
- write(atrace_marker_fd, buf, len);
- }
-}
-
-/**
- * Trace the end of an asynchronous event.
- * This should have a corresponding ATRACE_ASYNC_BEGIN.
- */
-#define ATRACE_ASYNC_END(name, cookie) atrace_async_end(ATRACE_TAG, name, cookie)
-static inline void atrace_async_end(uint64_t tag, const char* name,
- int32_t cookie)
-{
- if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
- char buf[ATRACE_MESSAGE_LENGTH];
- size_t len;
-
- len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "F|%d|%s|%d", getpid(),
- name, cookie);
- write(atrace_marker_fd, buf, len);
- }
-}
-
-
-/**
- * Traces an integer counter value. name is used to identify the counter.
- * This can be used to track how a value changes over time.
- */
-#define ATRACE_INT(name, value) atrace_int(ATRACE_TAG, name, value)
-static inline void atrace_int(uint64_t tag, const char* name, int32_t value)
-{
- if (CC_UNLIKELY(atrace_is_tag_enabled(tag))) {
- char buf[ATRACE_MESSAGE_LENGTH];
- size_t len;
-
- len = snprintf(buf, ATRACE_MESSAGE_LENGTH, "C|%d|%s|%d",
- getpid(), name, value);
- write(atrace_marker_fd, buf, len);
- }
-}
-
-#else // not HAVE_ANDROID_OS
-
-#define ATRACE_INIT()
-#define ATRACE_GET_ENABLED_TAGS()
-#define ATRACE_ENABLED()
-#define ATRACE_BEGIN(name)
-#define ATRACE_END()
-#define ATRACE_ASYNC_BEGIN(name, cookie)
-#define ATRACE_ASYNC_END(name, cookie)
-#define ATRACE_INT(name, value)
-
-#endif // not HAVE_ANDROID_OS
-
-__END_DECLS
-
-#endif // _LIBS_CUTILS_TRACE_H
diff --git a/widget/gonk/libui/linux_input.h b/widget/gonk/libui/linux_input.h
deleted file mode 100644
index 2ba14973f..000000000
--- a/widget/gonk/libui/linux_input.h
+++ /dev/null
@@ -1,1029 +0,0 @@
-/****************************************************************************
- ****************************************************************************
- ***
- *** This header was automatically generated from a Linux kernel header
- *** of the same name, to make information necessary for userspace to
- *** call into the kernel available to libc. It contains only constants,
- *** structures, and macros generated from the original header, and thus,
- *** contains no copyrightable information.
- ***
- *** To edit the content of this header, modify the corresponding
- *** source file (e.g. under external/kernel-headers/original/) then
- *** run bionic/libc/kernel/tools/update_all.py
- ***
- *** Any manual change here will be lost the next time this script will
- *** be run. You've been warned!
- ***
- ****************************************************************************
- ****************************************************************************/
-#ifndef _INPUT_H
-#define _INPUT_H
-#include <sys/time.h>
-#include <sys/ioctl.h>
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#include <sys/types.h>
-#include <linux/types.h>
-struct input_event {
- struct timeval time;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __u16 type;
- __u16 code;
- __s32 value;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EV_VERSION 0x010001
-struct input_id {
- __u16 bustype;
- __u16 vendor;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __u16 product;
- __u16 version;
-};
-struct input_absinfo {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __s32 value;
- __s32 minimum;
- __s32 maximum;
- __s32 fuzz;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __s32 flat;
- __s32 resolution;
-};
-struct input_keymap_entry {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define INPUT_KEYMAP_BY_INDEX (1 << 0)
- __u8 flags;
- __u8 len;
- __u16 index;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __u32 keycode;
- __u8 scancode[32];
-};
-#define EVIOCGVERSION _IOR('E', 0x01, int)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EVIOCGID _IOR('E', 0x02, struct input_id)
-#define EVIOCGREP _IOR('E', 0x03, unsigned int[2])
-#define EVIOCSREP _IOW('E', 0x03, unsigned int[2])
-#define EVIOCGKEYCODE _IOR('E', 0x04, unsigned int[2])
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EVIOCGKEYCODE_V2 _IOR('E', 0x04, struct input_keymap_entry)
-#define EVIOCSKEYCODE _IOW('E', 0x04, unsigned int[2])
-#define EVIOCSKEYCODE_V2 _IOW('E', 0x04, struct input_keymap_entry)
-#define EVIOCGNAME(len) _IOC(_IOC_READ, 'E', 0x06, len)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EVIOCGPHYS(len) _IOC(_IOC_READ, 'E', 0x07, len)
-#define EVIOCGUNIQ(len) _IOC(_IOC_READ, 'E', 0x08, len)
-#define EVIOCGPROP(len) _IOC(_IOC_READ, 'E', 0x09, len)
-#define EVIOCGMTSLOTS(len) _IOC(_IOC_READ, 'E', 0x0a, len)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EVIOCGKEY(len) _IOC(_IOC_READ, 'E', 0x18, len)
-#define EVIOCGLED(len) _IOC(_IOC_READ, 'E', 0x19, len)
-#define EVIOCGSND(len) _IOC(_IOC_READ, 'E', 0x1a, len)
-#define EVIOCGSW(len) _IOC(_IOC_READ, 'E', 0x1b, len)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EVIOCGBIT(ev,len) _IOC(_IOC_READ, 'E', 0x20 + (ev), len)
-#define EVIOCGABS(abs) _IOR('E', 0x40 + (abs), struct input_absinfo)
-#define EVIOCSABS(abs) _IOW('E', 0xc0 + (abs), struct input_absinfo)
-#define EVIOCSFF _IOC(_IOC_WRITE, 'E', 0x80, sizeof(struct ff_effect))
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EVIOCRMFF _IOW('E', 0x81, int)
-#define EVIOCGEFFECTS _IOR('E', 0x84, int)
-#define EVIOCGRAB _IOW('E', 0x90, int)
-#define EVIOCGSUSPENDBLOCK _IOR('E', 0x91, int)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
-#define EVIOCSCLOCKID _IOW('E', 0xa0, int)
-#define INPUT_PROP_POINTER 0x00
-#define INPUT_PROP_DIRECT 0x01
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define INPUT_PROP_BUTTONPAD 0x02
-#define INPUT_PROP_SEMI_MT 0x03
-#define INPUT_PROP_MAX 0x1f
-#define INPUT_PROP_CNT (INPUT_PROP_MAX + 1)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EV_SYN 0x00
-#define EV_KEY 0x01
-#define EV_REL 0x02
-#define EV_ABS 0x03
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EV_MSC 0x04
-#define EV_SW 0x05
-#define EV_LED 0x11
-#define EV_SND 0x12
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EV_REP 0x14
-#define EV_FF 0x15
-#define EV_PWR 0x16
-#define EV_FF_STATUS 0x17
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define EV_MAX 0x1f
-#define EV_CNT (EV_MAX+1)
-#define SYN_REPORT 0
-#define SYN_CONFIG 1
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define SYN_MT_REPORT 2
-#define SYN_DROPPED 3
-#define SYN_TIME_SEC 4
-#define SYN_TIME_NSEC 5
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_RESERVED 0
-#define KEY_ESC 1
-#define KEY_1 2
-#define KEY_2 3
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_3 4
-#define KEY_4 5
-#define KEY_5 6
-#define KEY_6 7
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_7 8
-#define KEY_8 9
-#define KEY_9 10
-#define KEY_0 11
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_MINUS 12
-#define KEY_EQUAL 13
-#define KEY_BACKSPACE 14
-#define KEY_TAB 15
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_Q 16
-#define KEY_W 17
-#define KEY_E 18
-#define KEY_R 19
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_T 20
-#define KEY_Y 21
-#define KEY_U 22
-#define KEY_I 23
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_O 24
-#define KEY_P 25
-#define KEY_LEFTBRACE 26
-#define KEY_RIGHTBRACE 27
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_ENTER 28
-#define KEY_LEFTCTRL 29
-#define KEY_A 30
-#define KEY_S 31
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_D 32
-#define KEY_F 33
-#define KEY_G 34
-#define KEY_H 35
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_J 36
-#define KEY_K 37
-#define KEY_L 38
-#define KEY_SEMICOLON 39
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_APOSTROPHE 40
-#define KEY_GRAVE 41
-#define KEY_LEFTSHIFT 42
-#define KEY_BACKSLASH 43
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_Z 44
-#define KEY_X 45
-#define KEY_C 46
-#define KEY_V 47
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_B 48
-#define KEY_N 49
-#define KEY_M 50
-#define KEY_COMMA 51
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_DOT 52
-#define KEY_SLASH 53
-#define KEY_RIGHTSHIFT 54
-#define KEY_KPASTERISK 55
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_LEFTALT 56
-#define KEY_SPACE 57
-#define KEY_CAPSLOCK 58
-#define KEY_F1 59
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_F2 60
-#define KEY_F3 61
-#define KEY_F4 62
-#define KEY_F5 63
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_F6 64
-#define KEY_F7 65
-#define KEY_F8 66
-#define KEY_F9 67
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_F10 68
-#define KEY_NUMLOCK 69
-#define KEY_SCROLLLOCK 70
-#define KEY_KP7 71
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KP8 72
-#define KEY_KP9 73
-#define KEY_KPMINUS 74
-#define KEY_KP4 75
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KP5 76
-#define KEY_KP6 77
-#define KEY_KPPLUS 78
-#define KEY_KP1 79
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KP2 80
-#define KEY_KP3 81
-#define KEY_KP0 82
-#define KEY_KPDOT 83
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_ZENKAKUHANKAKU 85
-#define KEY_102ND 86
-#define KEY_F11 87
-#define KEY_F12 88
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_RO 89
-#define KEY_KATAKANA 90
-#define KEY_HIRAGANA 91
-#define KEY_HENKAN 92
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KATAKANAHIRAGANA 93
-#define KEY_MUHENKAN 94
-#define KEY_KPJPCOMMA 95
-#define KEY_KPENTER 96
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_RIGHTCTRL 97
-#define KEY_KPSLASH 98
-#define KEY_SYSRQ 99
-#define KEY_RIGHTALT 100
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_LINEFEED 101
-#define KEY_HOME 102
-#define KEY_UP 103
-#define KEY_PAGEUP 104
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_LEFT 105
-#define KEY_RIGHT 106
-#define KEY_END 107
-#define KEY_DOWN 108
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_PAGEDOWN 109
-#define KEY_INSERT 110
-#define KEY_DELETE 111
-#define KEY_MACRO 112
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_MUTE 113
-#define KEY_VOLUMEDOWN 114
-#define KEY_VOLUMEUP 115
-#define KEY_POWER 116
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KPEQUAL 117
-#define KEY_KPPLUSMINUS 118
-#define KEY_PAUSE 119
-#define KEY_SCALE 120
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KPCOMMA 121
-#define KEY_HANGEUL 122
-#define KEY_HANGUEL KEY_HANGEUL
-#define KEY_HANJA 123
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_YEN 124
-#define KEY_LEFTMETA 125
-#define KEY_RIGHTMETA 126
-#define KEY_COMPOSE 127
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_STOP 128
-#define KEY_AGAIN 129
-#define KEY_PROPS 130
-#define KEY_UNDO 131
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FRONT 132
-#define KEY_COPY 133
-#define KEY_OPEN 134
-#define KEY_PASTE 135
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FIND 136
-#define KEY_CUT 137
-#define KEY_HELP 138
-#define KEY_MENU 139
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_CALC 140
-#define KEY_SETUP 141
-#define KEY_SLEEP 142
-#define KEY_WAKEUP 143
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FILE 144
-#define KEY_SENDFILE 145
-#define KEY_DELETEFILE 146
-#define KEY_XFER 147
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_PROG1 148
-#define KEY_PROG2 149
-#define KEY_WWW 150
-#define KEY_MSDOS 151
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_COFFEE 152
-#define KEY_SCREENLOCK KEY_COFFEE
-#define KEY_DIRECTION 153
-#define KEY_CYCLEWINDOWS 154
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_MAIL 155
-#define KEY_BOOKMARKS 156
-#define KEY_COMPUTER 157
-#define KEY_BACK 158
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FORWARD 159
-#define KEY_CLOSECD 160
-#define KEY_EJECTCD 161
-#define KEY_EJECTCLOSECD 162
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_NEXTSONG 163
-#define KEY_PLAYPAUSE 164
-#define KEY_PREVIOUSSONG 165
-#define KEY_STOPCD 166
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_RECORD 167
-#define KEY_REWIND 168
-#define KEY_PHONE 169
-#define KEY_ISO 170
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_CONFIG 171
-#define KEY_HOMEPAGE 172
-#define KEY_REFRESH 173
-#define KEY_EXIT 174
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_MOVE 175
-#define KEY_EDIT 176
-#define KEY_SCROLLUP 177
-#define KEY_SCROLLDOWN 178
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KPLEFTPAREN 179
-#define KEY_KPRIGHTPAREN 180
-#define KEY_NEW 181
-#define KEY_REDO 182
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_F13 183
-#define KEY_F14 184
-#define KEY_F15 185
-#define KEY_F16 186
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_F17 187
-#define KEY_F18 188
-#define KEY_F19 189
-#define KEY_F20 190
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_F21 191
-#define KEY_F22 192
-#define KEY_F23 193
-#define KEY_F24 194
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_PLAYCD 200
-#define KEY_PAUSECD 201
-#define KEY_PROG3 202
-#define KEY_PROG4 203
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_DASHBOARD 204
-#define KEY_SUSPEND 205
-#define KEY_CLOSE 206
-#define KEY_PLAY 207
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FASTFORWARD 208
-#define KEY_BASSBOOST 209
-#define KEY_PRINT 210
-#define KEY_HP 211
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_CAMERA 212
-#define KEY_SOUND 213
-#define KEY_QUESTION 214
-#define KEY_EMAIL 215
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_CHAT 216
-#define KEY_SEARCH 217
-#define KEY_CONNECT 218
-#define KEY_FINANCE 219
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_SPORT 220
-#define KEY_SHOP 221
-#define KEY_ALTERASE 222
-#define KEY_CANCEL 223
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_BRIGHTNESSDOWN 224
-#define KEY_BRIGHTNESSUP 225
-#define KEY_MEDIA 226
-#define KEY_SWITCHVIDEOMODE 227
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KBDILLUMTOGGLE 228
-#define KEY_KBDILLUMDOWN 229
-#define KEY_KBDILLUMUP 230
-#define KEY_SEND 231
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_REPLY 232
-#define KEY_FORWARDMAIL 233
-#define KEY_SAVE 234
-#define KEY_DOCUMENTS 235
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_BATTERY 236
-#define KEY_BLUETOOTH 237
-#define KEY_WLAN 238
-#define KEY_UWB 239
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_UNKNOWN 240
-#define KEY_VIDEO_NEXT 241
-#define KEY_VIDEO_PREV 242
-#define KEY_BRIGHTNESS_CYCLE 243
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_BRIGHTNESS_ZERO 244
-#define KEY_DISPLAY_OFF 245
-#define KEY_WIMAX 246
-#define KEY_RFKILL 247
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_MICMUTE 248
-#define BTN_MISC 0x100
-#define BTN_0 0x100
-#define BTN_1 0x101
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_2 0x102
-#define BTN_3 0x103
-#define BTN_4 0x104
-#define BTN_5 0x105
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_6 0x106
-#define BTN_7 0x107
-#define BTN_8 0x108
-#define BTN_9 0x109
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_MOUSE 0x110
-#define BTN_LEFT 0x110
-#define BTN_RIGHT 0x111
-#define BTN_MIDDLE 0x112
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_SIDE 0x113
-#define BTN_EXTRA 0x114
-#define BTN_FORWARD 0x115
-#define BTN_BACK 0x116
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TASK 0x117
-#define BTN_JOYSTICK 0x120
-#define BTN_TRIGGER 0x120
-#define BTN_THUMB 0x121
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_THUMB2 0x122
-#define BTN_TOP 0x123
-#define BTN_TOP2 0x124
-#define BTN_PINKIE 0x125
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_BASE 0x126
-#define BTN_BASE2 0x127
-#define BTN_BASE3 0x128
-#define BTN_BASE4 0x129
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_BASE5 0x12a
-#define BTN_BASE6 0x12b
-#define BTN_DEAD 0x12f
-#define BTN_GAMEPAD 0x130
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_A 0x130
-#define BTN_B 0x131
-#define BTN_C 0x132
-#define BTN_X 0x133
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_Y 0x134
-#define BTN_Z 0x135
-#define BTN_TL 0x136
-#define BTN_TR 0x137
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TL2 0x138
-#define BTN_TR2 0x139
-#define BTN_SELECT 0x13a
-#define BTN_START 0x13b
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_MODE 0x13c
-#define BTN_THUMBL 0x13d
-#define BTN_THUMBR 0x13e
-#define BTN_DIGI 0x140
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TOOL_PEN 0x140
-#define BTN_TOOL_RUBBER 0x141
-#define BTN_TOOL_BRUSH 0x142
-#define BTN_TOOL_PENCIL 0x143
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TOOL_AIRBRUSH 0x144
-#define BTN_TOOL_FINGER 0x145
-#define BTN_TOOL_MOUSE 0x146
-#define BTN_TOOL_LENS 0x147
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TOOL_QUINTTAP 0x148
-#define BTN_TOUCH 0x14a
-#define BTN_STYLUS 0x14b
-#define BTN_STYLUS2 0x14c
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TOOL_DOUBLETAP 0x14d
-#define BTN_TOOL_TRIPLETAP 0x14e
-#define BTN_TOOL_QUADTAP 0x14f
-#define BTN_WHEEL 0x150
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_GEAR_DOWN 0x150
-#define BTN_GEAR_UP 0x151
-#define KEY_OK 0x160
-#define KEY_SELECT 0x161
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_GOTO 0x162
-#define KEY_CLEAR 0x163
-#define KEY_POWER2 0x164
-#define KEY_OPTION 0x165
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_INFO 0x166
-#define KEY_TIME 0x167
-#define KEY_VENDOR 0x168
-#define KEY_ARCHIVE 0x169
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_PROGRAM 0x16a
-#define KEY_CHANNEL 0x16b
-#define KEY_FAVORITES 0x16c
-#define KEY_EPG 0x16d
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_PVR 0x16e
-#define KEY_MHP 0x16f
-#define KEY_LANGUAGE 0x170
-#define KEY_TITLE 0x171
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_SUBTITLE 0x172
-#define KEY_ANGLE 0x173
-#define KEY_ZOOM 0x174
-#define KEY_MODE 0x175
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_KEYBOARD 0x176
-#define KEY_SCREEN 0x177
-#define KEY_PC 0x178
-#define KEY_TV 0x179
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_TV2 0x17a
-#define KEY_VCR 0x17b
-#define KEY_VCR2 0x17c
-#define KEY_SAT 0x17d
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_SAT2 0x17e
-#define KEY_CD 0x17f
-#define KEY_TAPE 0x180
-#define KEY_RADIO 0x181
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_TUNER 0x182
-#define KEY_PLAYER 0x183
-#define KEY_TEXT 0x184
-#define KEY_DVD 0x185
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_AUX 0x186
-#define KEY_MP3 0x187
-#define KEY_AUDIO 0x188
-#define KEY_VIDEO 0x189
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_DIRECTORY 0x18a
-#define KEY_LIST 0x18b
-#define KEY_MEMO 0x18c
-#define KEY_CALENDAR 0x18d
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_RED 0x18e
-#define KEY_GREEN 0x18f
-#define KEY_YELLOW 0x190
-#define KEY_BLUE 0x191
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_CHANNELUP 0x192
-#define KEY_CHANNELDOWN 0x193
-#define KEY_FIRST 0x194
-#define KEY_LAST 0x195
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_AB 0x196
-#define KEY_NEXT 0x197
-#define KEY_RESTART 0x198
-#define KEY_SLOW 0x199
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_SHUFFLE 0x19a
-#define KEY_BREAK 0x19b
-#define KEY_PREVIOUS 0x19c
-#define KEY_DIGITS 0x19d
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_TEEN 0x19e
-#define KEY_TWEN 0x19f
-#define KEY_VIDEOPHONE 0x1a0
-#define KEY_GAMES 0x1a1
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_ZOOMIN 0x1a2
-#define KEY_ZOOMOUT 0x1a3
-#define KEY_ZOOMRESET 0x1a4
-#define KEY_WORDPROCESSOR 0x1a5
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_EDITOR 0x1a6
-#define KEY_SPREADSHEET 0x1a7
-#define KEY_GRAPHICSEDITOR 0x1a8
-#define KEY_PRESENTATION 0x1a9
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_DATABASE 0x1aa
-#define KEY_NEWS 0x1ab
-#define KEY_VOICEMAIL 0x1ac
-#define KEY_ADDRESSBOOK 0x1ad
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_MESSENGER 0x1ae
-#define KEY_DISPLAYTOGGLE 0x1af
-#define KEY_SPELLCHECK 0x1b0
-#define KEY_LOGOFF 0x1b1
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_DOLLAR 0x1b2
-#define KEY_EURO 0x1b3
-#define KEY_FRAMEBACK 0x1b4
-#define KEY_FRAMEFORWARD 0x1b5
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_CONTEXT_MENU 0x1b6
-#define KEY_MEDIA_REPEAT 0x1b7
-#define KEY_10CHANNELSUP 0x1b8
-#define KEY_10CHANNELSDOWN 0x1b9
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_IMAGES 0x1ba
-#define KEY_DEL_EOL 0x1c0
-#define KEY_DEL_EOS 0x1c1
-#define KEY_INS_LINE 0x1c2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_DEL_LINE 0x1c3
-#define KEY_FN 0x1d0
-#define KEY_FN_ESC 0x1d1
-#define KEY_FN_F1 0x1d2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FN_F2 0x1d3
-#define KEY_FN_F3 0x1d4
-#define KEY_FN_F4 0x1d5
-#define KEY_FN_F5 0x1d6
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FN_F6 0x1d7
-#define KEY_FN_F7 0x1d8
-#define KEY_FN_F8 0x1d9
-#define KEY_FN_F9 0x1da
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FN_F10 0x1db
-#define KEY_FN_F11 0x1dc
-#define KEY_FN_F12 0x1dd
-#define KEY_FN_1 0x1de
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FN_2 0x1df
-#define KEY_FN_D 0x1e0
-#define KEY_FN_E 0x1e1
-#define KEY_FN_F 0x1e2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_FN_S 0x1e3
-#define KEY_FN_B 0x1e4
-#define KEY_BRL_DOT1 0x1f1
-#define KEY_BRL_DOT2 0x1f2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_BRL_DOT3 0x1f3
-#define KEY_BRL_DOT4 0x1f4
-#define KEY_BRL_DOT5 0x1f5
-#define KEY_BRL_DOT6 0x1f6
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_BRL_DOT7 0x1f7
-#define KEY_BRL_DOT8 0x1f8
-#define KEY_BRL_DOT9 0x1f9
-#define KEY_BRL_DOT10 0x1fa
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_NUMERIC_0 0x200
-#define KEY_NUMERIC_1 0x201
-#define KEY_NUMERIC_2 0x202
-#define KEY_NUMERIC_3 0x203
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_NUMERIC_4 0x204
-#define KEY_NUMERIC_5 0x205
-#define KEY_NUMERIC_6 0x206
-#define KEY_NUMERIC_7 0x207
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_NUMERIC_8 0x208
-#define KEY_NUMERIC_9 0x209
-#define KEY_NUMERIC_STAR 0x20a
-#define KEY_NUMERIC_POUND 0x20b
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_CAMERA_SNAPSHOT 0x2fe
-#define KEY_CAMERA_FOCUS 0x210
-#define KEY_WPS_BUTTON 0x211
-#define KEY_TOUCHPAD_TOGGLE 0x212
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_TOUCHPAD_ON 0x213
-#define KEY_TOUCHPAD_OFF 0x214
-#define KEY_CAMERA_ZOOMIN 0x215
-#define KEY_CAMERA_ZOOMOUT 0x216
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define KEY_CAMERA_UP 0x217
-#define KEY_CAMERA_DOWN 0x218
-#define KEY_CAMERA_LEFT 0x219
-#define KEY_CAMERA_RIGHT 0x21a
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY 0x2c0
-#define BTN_TRIGGER_HAPPY1 0x2c0
-#define BTN_TRIGGER_HAPPY2 0x2c1
-#define BTN_TRIGGER_HAPPY3 0x2c2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY4 0x2c3
-#define BTN_TRIGGER_HAPPY5 0x2c4
-#define BTN_TRIGGER_HAPPY6 0x2c5
-#define BTN_TRIGGER_HAPPY7 0x2c6
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY8 0x2c7
-#define BTN_TRIGGER_HAPPY9 0x2c8
-#define BTN_TRIGGER_HAPPY10 0x2c9
-#define BTN_TRIGGER_HAPPY11 0x2ca
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY12 0x2cb
-#define BTN_TRIGGER_HAPPY13 0x2cc
-#define BTN_TRIGGER_HAPPY14 0x2cd
-#define BTN_TRIGGER_HAPPY15 0x2ce
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY16 0x2cf
-#define BTN_TRIGGER_HAPPY17 0x2d0
-#define BTN_TRIGGER_HAPPY18 0x2d1
-#define BTN_TRIGGER_HAPPY19 0x2d2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY20 0x2d3
-#define BTN_TRIGGER_HAPPY21 0x2d4
-#define BTN_TRIGGER_HAPPY22 0x2d5
-#define BTN_TRIGGER_HAPPY23 0x2d6
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY24 0x2d7
-#define BTN_TRIGGER_HAPPY25 0x2d8
-#define BTN_TRIGGER_HAPPY26 0x2d9
-#define BTN_TRIGGER_HAPPY27 0x2da
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY28 0x2db
-#define BTN_TRIGGER_HAPPY29 0x2dc
-#define BTN_TRIGGER_HAPPY30 0x2dd
-#define BTN_TRIGGER_HAPPY31 0x2de
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY32 0x2df
-#define BTN_TRIGGER_HAPPY33 0x2e0
-#define BTN_TRIGGER_HAPPY34 0x2e1
-#define BTN_TRIGGER_HAPPY35 0x2e2
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY36 0x2e3
-#define BTN_TRIGGER_HAPPY37 0x2e4
-#define BTN_TRIGGER_HAPPY38 0x2e5
-#define BTN_TRIGGER_HAPPY39 0x2e6
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BTN_TRIGGER_HAPPY40 0x2e7
-#define KEY_MIN_INTERESTING KEY_MUTE
-#define KEY_MAX 0x2ff
-#define KEY_CNT (KEY_MAX+1)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define REL_X 0x00
-#define REL_Y 0x01
-#define REL_Z 0x02
-#define REL_RX 0x03
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define REL_RY 0x04
-#define REL_RZ 0x05
-#define REL_HWHEEL 0x06
-#define REL_DIAL 0x07
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define REL_WHEEL 0x08
-#define REL_MISC 0x09
-#define REL_MAX 0x0f
-#define REL_CNT (REL_MAX+1)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_X 0x00
-#define ABS_Y 0x01
-#define ABS_Z 0x02
-#define ABS_RX 0x03
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_RY 0x04
-#define ABS_RZ 0x05
-#define ABS_THROTTLE 0x06
-#define ABS_RUDDER 0x07
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_WHEEL 0x08
-#define ABS_GAS 0x09
-#define ABS_BRAKE 0x0a
-#define ABS_HAT0X 0x10
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_HAT0Y 0x11
-#define ABS_HAT1X 0x12
-#define ABS_HAT1Y 0x13
-#define ABS_HAT2X 0x14
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_HAT2Y 0x15
-#define ABS_HAT3X 0x16
-#define ABS_HAT3Y 0x17
-#define ABS_PRESSURE 0x18
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_DISTANCE 0x19
-#define ABS_TILT_X 0x1a
-#define ABS_TILT_Y 0x1b
-#define ABS_TOOL_WIDTH 0x1c
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_VOLUME 0x20
-#define ABS_MISC 0x28
-#define ABS_MT_SLOT 0x2f
-#define ABS_MT_TOUCH_MAJOR 0x30
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_MT_TOUCH_MINOR 0x31
-#define ABS_MT_WIDTH_MAJOR 0x32
-#define ABS_MT_WIDTH_MINOR 0x33
-#define ABS_MT_ORIENTATION 0x34
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_MT_POSITION_X 0x35
-#define ABS_MT_POSITION_Y 0x36
-#define ABS_MT_TOOL_TYPE 0x37
-#define ABS_MT_BLOB_ID 0x38
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_MT_TRACKING_ID 0x39
-#define ABS_MT_PRESSURE 0x3a
-#define ABS_MT_DISTANCE 0x3b
-#define ABS_MAX 0x3f
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ABS_CNT (ABS_MAX+1)
-#define SW_LID 0x00
-#define SW_TABLET_MODE 0x01
-#define SW_HEADPHONE_INSERT 0x02
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define SW_RFKILL_ALL 0x03
-#define SW_RADIO SW_RFKILL_ALL
-#define SW_MICROPHONE_INSERT 0x04
-#define SW_DOCK 0x05
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define SW_LINEOUT_INSERT 0x06
-#define SW_JACK_PHYSICAL_INSERT 0x07
-#define SW_VIDEOOUT_INSERT 0x08
-#define SW_CAMERA_LENS_COVER 0x09
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define SW_KEYPAD_SLIDE 0x0a
-#define SW_FRONT_PROXIMITY 0x0b
-#define SW_ROTATE_LOCK 0x0c
-#define SW_LINEIN_INSERT 0x0d
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define SW_HPHL_OVERCURRENT 0x0e
-#define SW_HPHR_OVERCURRENT 0x0f
-#define SW_UNSUPPORT_INSERT 0x10
-#define SW_MAX 0x20
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define SW_CNT (SW_MAX+1)
-#define MSC_SERIAL 0x00
-#define MSC_PULSELED 0x01
-#define MSC_GESTURE 0x02
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define MSC_RAW 0x03
-#define MSC_SCAN 0x04
-#define MSC_MAX 0x07
-#define MSC_CNT (MSC_MAX+1)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define LED_NUML 0x00
-#define LED_CAPSL 0x01
-#define LED_SCROLLL 0x02
-#define LED_COMPOSE 0x03
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define LED_KANA 0x04
-#define LED_SLEEP 0x05
-#define LED_SUSPEND 0x06
-#define LED_MUTE 0x07
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define LED_MISC 0x08
-#define LED_MAIL 0x09
-#define LED_CHARGING 0x0a
-#define LED_MAX 0x0f
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define LED_CNT (LED_MAX+1)
-#define REP_DELAY 0x00
-#define REP_PERIOD 0x01
-#define REP_MAX 0x01
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define REP_CNT (REP_MAX+1)
-#define SND_CLICK 0x00
-#define SND_BELL 0x01
-#define SND_TONE 0x02
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define SND_MAX 0x07
-#define SND_CNT (SND_MAX+1)
-#define ID_BUS 0
-#define ID_VENDOR 1
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define ID_PRODUCT 2
-#define ID_VERSION 3
-#define BUS_PCI 0x01
-#define BUS_ISAPNP 0x02
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BUS_USB 0x03
-#define BUS_HIL 0x04
-#define BUS_BLUETOOTH 0x05
-#define BUS_VIRTUAL 0x06
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BUS_ISA 0x10
-#define BUS_I8042 0x11
-#define BUS_XTKBD 0x12
-#define BUS_RS232 0x13
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BUS_GAMEPORT 0x14
-#define BUS_PARPORT 0x15
-#define BUS_AMIGA 0x16
-#define BUS_ADB 0x17
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BUS_I2C 0x18
-#define BUS_HOST 0x19
-#define BUS_GSC 0x1A
-#define BUS_ATARI 0x1B
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define BUS_SPI 0x1C
-#define MT_TOOL_FINGER 0
-#define MT_TOOL_PEN 1
-#define MT_TOOL_MAX 1
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define FF_STATUS_STOPPED 0x00
-#define FF_STATUS_PLAYING 0x01
-#define FF_STATUS_MAX 0x01
-struct ff_replay {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __u16 length;
- __u16 delay;
-};
-struct ff_trigger {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __u16 button;
- __u16 interval;
-};
-struct ff_envelope {
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __u16 attack_length;
- __u16 attack_level;
- __u16 fade_length;
- __u16 fade_level;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-};
-struct ff_constant_effect {
- __s16 level;
- struct ff_envelope envelope;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-};
-struct ff_ramp_effect {
- __s16 start_level;
- __s16 end_level;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- struct ff_envelope envelope;
-};
-struct ff_condition_effect {
- __u16 right_saturation;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __u16 left_saturation;
- __s16 right_coeff;
- __s16 left_coeff;
- __u16 deadband;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __s16 center;
-};
-struct ff_periodic_effect {
- __u16 waveform;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- __u16 period;
- __s16 magnitude;
- __s16 offset;
- __u16 phase;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- struct ff_envelope envelope;
- __u32 custom_len;
- __s16 __user *custom_data;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-struct ff_rumble_effect {
- __u16 strong_magnitude;
- __u16 weak_magnitude;
-};
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-struct ff_effect {
- __u16 type;
- __s16 id;
- __u16 direction;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- struct ff_trigger trigger;
- struct ff_replay replay;
- union {
- struct ff_constant_effect constant;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- struct ff_ramp_effect ramp;
- struct ff_periodic_effect periodic;
- struct ff_condition_effect condition[2];
- struct ff_rumble_effect rumble;
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
- } u;
-};
-#define FF_RUMBLE 0x50
-#define FF_PERIODIC 0x51
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define FF_CONSTANT 0x52
-#define FF_SPRING 0x53
-#define FF_FRICTION 0x54
-#define FF_DAMPER 0x55
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define FF_INERTIA 0x56
-#define FF_RAMP 0x57
-#define FF_EFFECT_MIN FF_RUMBLE
-#define FF_EFFECT_MAX FF_RAMP
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define FF_SQUARE 0x58
-#define FF_TRIANGLE 0x59
-#define FF_SINE 0x5a
-#define FF_SAW_UP 0x5b
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define FF_SAW_DOWN 0x5c
-#define FF_CUSTOM 0x5d
-#define FF_WAVEFORM_MIN FF_SQUARE
-#define FF_WAVEFORM_MAX FF_CUSTOM
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#define FF_GAIN 0x60
-#define FF_AUTOCENTER 0x61
-#define FF_MAX 0x7f
-#define FF_CNT (FF_MAX+1)
-/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
-#endif
diff --git a/widget/gonk/libui/sha1.c b/widget/gonk/libui/sha1.c
deleted file mode 100644
index 40a4ecaa3..000000000
--- a/widget/gonk/libui/sha1.c
+++ /dev/null
@@ -1,289 +0,0 @@
-/* $NetBSD: sha1.c,v 1.6 2009/11/06 20:31:18 joerg Exp $ */
-/* $OpenBSD: sha1.c,v 1.9 1997/07/23 21:12:32 kstailey Exp $ */
-
-/*
- * SHA-1 in C
- * By Steve Reid <steve@edmweb.com>
- * 100% Public Domain
- *
- * Test Vectors (from FIPS PUB 180-1)
- * "abc"
- * A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
- * "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
- * 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
- * A million repetitions of "a"
- * 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
- */
-
-#define SHA1HANDSOFF /* Copies data before messing with it. */
-
-#include <sys/cdefs.h>
-
-#if defined(_KERNEL) || defined(_STANDALONE)
-__KERNEL_RCSID(0, "$NetBSD: sha1.c,v 1.6 2009/11/06 20:31:18 joerg Exp $");
-
-#include <lib/libkern/libkern.h>
-
-#else
-
-#if defined(LIBC_SCCS) && !defined(lint)
-__RCSID("$NetBSD: sha1.c,v 1.6 2009/11/06 20:31:18 joerg Exp $");
-#endif /* LIBC_SCCS and not lint */
-
-#include <assert.h>
-#include <string.h>
-
-#endif
-
-#include <sys/types.h>
-#include "sha1.h"
-
-#define _DIAGASSERT assert
-
-#if HAVE_NBTOOL_CONFIG_H
-#include "nbtool_config.h"
-#endif
-
-#if !HAVE_SHA1_H
-
-#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
-
-/*
- * blk0() and blk() perform the initial expand.
- * I got the idea of expanding during the round function from SSLeay
- */
-#if BYTE_ORDER == LITTLE_ENDIAN
-# define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
- |(rol(block->l[i],8)&0x00FF00FF))
-#else
-# define blk0(i) block->l[i]
-#endif
-#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
- ^block->l[(i+2)&15]^block->l[i&15],1))
-
-/*
- * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1
- */
-#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
-#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
-#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
-#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
-#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
-
-
-#if !defined(_KERNEL) && !defined(_STANDALONE)
-#if defined(__weak_alias)
-__weak_alias(SHA1Transform,_SHA1Transform)
-__weak_alias(SHA1Init,_SHA1Init)
-__weak_alias(SHA1Update,_SHA1Update)
-__weak_alias(SHA1Final,_SHA1Final)
-#endif
-#endif
-
-typedef union {
- uint8_t c[64];
- uint32_t l[16];
-} CHAR64LONG16;
-
-/* old sparc64 gcc could not compile this */
-#undef SPARC64_GCC_WORKAROUND
-#if defined(__sparc64__) && defined(__GNUC__) && __GNUC__ < 3
-#define SPARC64_GCC_WORKAROUND
-#endif
-
-#ifdef SPARC64_GCC_WORKAROUND
-void do_R01(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
-void do_R2(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
-void do_R3(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
-void do_R4(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *);
-
-#define nR0(v,w,x,y,z,i) R0(*v,*w,*x,*y,*z,i)
-#define nR1(v,w,x,y,z,i) R1(*v,*w,*x,*y,*z,i)
-#define nR2(v,w,x,y,z,i) R2(*v,*w,*x,*y,*z,i)
-#define nR3(v,w,x,y,z,i) R3(*v,*w,*x,*y,*z,i)
-#define nR4(v,w,x,y,z,i) R4(*v,*w,*x,*y,*z,i)
-
-void
-do_R01(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
-{
- nR0(a,b,c,d,e, 0); nR0(e,a,b,c,d, 1); nR0(d,e,a,b,c, 2); nR0(c,d,e,a,b, 3);
- nR0(b,c,d,e,a, 4); nR0(a,b,c,d,e, 5); nR0(e,a,b,c,d, 6); nR0(d,e,a,b,c, 7);
- nR0(c,d,e,a,b, 8); nR0(b,c,d,e,a, 9); nR0(a,b,c,d,e,10); nR0(e,a,b,c,d,11);
- nR0(d,e,a,b,c,12); nR0(c,d,e,a,b,13); nR0(b,c,d,e,a,14); nR0(a,b,c,d,e,15);
- nR1(e,a,b,c,d,16); nR1(d,e,a,b,c,17); nR1(c,d,e,a,b,18); nR1(b,c,d,e,a,19);
-}
-
-void
-do_R2(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
-{
- nR2(a,b,c,d,e,20); nR2(e,a,b,c,d,21); nR2(d,e,a,b,c,22); nR2(c,d,e,a,b,23);
- nR2(b,c,d,e,a,24); nR2(a,b,c,d,e,25); nR2(e,a,b,c,d,26); nR2(d,e,a,b,c,27);
- nR2(c,d,e,a,b,28); nR2(b,c,d,e,a,29); nR2(a,b,c,d,e,30); nR2(e,a,b,c,d,31);
- nR2(d,e,a,b,c,32); nR2(c,d,e,a,b,33); nR2(b,c,d,e,a,34); nR2(a,b,c,d,e,35);
- nR2(e,a,b,c,d,36); nR2(d,e,a,b,c,37); nR2(c,d,e,a,b,38); nR2(b,c,d,e,a,39);
-}
-
-void
-do_R3(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
-{
- nR3(a,b,c,d,e,40); nR3(e,a,b,c,d,41); nR3(d,e,a,b,c,42); nR3(c,d,e,a,b,43);
- nR3(b,c,d,e,a,44); nR3(a,b,c,d,e,45); nR3(e,a,b,c,d,46); nR3(d,e,a,b,c,47);
- nR3(c,d,e,a,b,48); nR3(b,c,d,e,a,49); nR3(a,b,c,d,e,50); nR3(e,a,b,c,d,51);
- nR3(d,e,a,b,c,52); nR3(c,d,e,a,b,53); nR3(b,c,d,e,a,54); nR3(a,b,c,d,e,55);
- nR3(e,a,b,c,d,56); nR3(d,e,a,b,c,57); nR3(c,d,e,a,b,58); nR3(b,c,d,e,a,59);
-}
-
-void
-do_R4(uint32_t *a, uint32_t *b, uint32_t *c, uint32_t *d, uint32_t *e, CHAR64LONG16 *block)
-{
- nR4(a,b,c,d,e,60); nR4(e,a,b,c,d,61); nR4(d,e,a,b,c,62); nR4(c,d,e,a,b,63);
- nR4(b,c,d,e,a,64); nR4(a,b,c,d,e,65); nR4(e,a,b,c,d,66); nR4(d,e,a,b,c,67);
- nR4(c,d,e,a,b,68); nR4(b,c,d,e,a,69); nR4(a,b,c,d,e,70); nR4(e,a,b,c,d,71);
- nR4(d,e,a,b,c,72); nR4(c,d,e,a,b,73); nR4(b,c,d,e,a,74); nR4(a,b,c,d,e,75);
- nR4(e,a,b,c,d,76); nR4(d,e,a,b,c,77); nR4(c,d,e,a,b,78); nR4(b,c,d,e,a,79);
-}
-#endif
-
-/*
- * Hash a single 512-bit block. This is the core of the algorithm.
- */
-void SHA1Transform(uint32_t state[5], const uint8_t buffer[64])
-{
- uint32_t a, b, c, d, e;
- CHAR64LONG16 *block;
-
-#ifdef SHA1HANDSOFF
- CHAR64LONG16 workspace;
-#endif
-
- _DIAGASSERT(buffer != 0);
- _DIAGASSERT(state != 0);
-
-#ifdef SHA1HANDSOFF
- block = &workspace;
- (void)memcpy(block, buffer, 64);
-#else
- block = (CHAR64LONG16 *)(void *)buffer;
-#endif
-
- /* Copy context->state[] to working vars */
- a = state[0];
- b = state[1];
- c = state[2];
- d = state[3];
- e = state[4];
-
-#ifdef SPARC64_GCC_WORKAROUND
- do_R01(&a, &b, &c, &d, &e, block);
- do_R2(&a, &b, &c, &d, &e, block);
- do_R3(&a, &b, &c, &d, &e, block);
- do_R4(&a, &b, &c, &d, &e, block);
-#else
- /* 4 rounds of 20 operations each. Loop unrolled. */
- R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
- R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
- R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
- R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
- R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
- R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
- R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
- R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
- R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
- R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
- R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
- R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
- R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
- R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
- R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
- R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
- R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
- R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
- R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
- R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
-#endif
-
- /* Add the working vars back into context.state[] */
- state[0] += a;
- state[1] += b;
- state[2] += c;
- state[3] += d;
- state[4] += e;
-
- /* Wipe variables */
- a = b = c = d = e = 0;
-}
-
-
-/*
- * SHA1Init - Initialize new context
- */
-void SHA1Init(SHA1_CTX *context)
-{
-
- _DIAGASSERT(context != 0);
-
- /* SHA1 initialization constants */
- context->state[0] = 0x67452301;
- context->state[1] = 0xEFCDAB89;
- context->state[2] = 0x98BADCFE;
- context->state[3] = 0x10325476;
- context->state[4] = 0xC3D2E1F0;
- context->count[0] = context->count[1] = 0;
-}
-
-
-/*
- * Run your data through this.
- */
-void SHA1Update(SHA1_CTX *context, const uint8_t *data, unsigned int len)
-{
- unsigned int i, j;
-
- _DIAGASSERT(context != 0);
- _DIAGASSERT(data != 0);
-
- j = context->count[0];
- if ((context->count[0] += len << 3) < j)
- context->count[1] += (len>>29)+1;
- j = (j >> 3) & 63;
- if ((j + len) > 63) {
- (void)memcpy(&context->buffer[j], data, (i = 64-j));
- SHA1Transform(context->state, context->buffer);
- for ( ; i + 63 < len; i += 64)
- SHA1Transform(context->state, &data[i]);
- j = 0;
- } else {
- i = 0;
- }
- (void)memcpy(&context->buffer[j], &data[i], len - i);
-}
-
-
-/*
- * Add padding and return the message digest.
- */
-void SHA1Final(uint8_t digest[20], SHA1_CTX *context)
-{
- unsigned int i;
- uint8_t finalcount[8];
-
- _DIAGASSERT(digest != 0);
- _DIAGASSERT(context != 0);
-
- for (i = 0; i < 8; i++) {
- finalcount[i] = (uint8_t)((context->count[(i >= 4 ? 0 : 1)]
- >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */
- }
- SHA1Update(context, (const uint8_t *)"\200", 1);
- while ((context->count[0] & 504) != 448)
- SHA1Update(context, (const uint8_t *)"\0", 1);
- SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
-
- if (digest) {
- for (i = 0; i < 20; i++)
- digest[i] = (uint8_t)
- ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
- }
-}
-
-#endif /* HAVE_SHA1_H */
diff --git a/widget/gonk/libui/sha1.h b/widget/gonk/libui/sha1.h
deleted file mode 100644
index f7ada46a5..000000000
--- a/widget/gonk/libui/sha1.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/* $NetBSD: sha1.h,v 1.13 2005/12/26 18:41:36 perry Exp $ */
-
-/*
- * SHA-1 in C
- * By Steve Reid <steve@edmweb.com>
- * 100% Public Domain
- */
-
-#ifndef _SYS_SHA1_H_
-#define _SYS_SHA1_H_
-
-#include <sys/cdefs.h>
-#include <sys/types.h>
-
-#define SHA1_DIGEST_LENGTH 20
-#define SHA1_DIGEST_STRING_LENGTH 41
-
-typedef struct {
- uint32_t state[5];
- uint32_t count[2];
- u_char buffer[64];
-} SHA1_CTX;
-
-__BEGIN_DECLS
-void SHA1Transform(uint32_t[5], const u_char[64]);
-void SHA1Init(SHA1_CTX *);
-void SHA1Update(SHA1_CTX *, const u_char *, u_int);
-void SHA1Final(u_char[SHA1_DIGEST_LENGTH], SHA1_CTX *);
-__END_DECLS
-
-#endif /* _SYS_SHA1_H_ */
diff --git a/widget/gonk/moz.build b/widget/gonk/moz.build
deleted file mode 100644
index d539dd9a0..000000000
--- a/widget/gonk/moz.build
+++ /dev/null
@@ -1,96 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# Copyright 2013 Mozilla Foundation and Mozilla contributors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-EXPORTS += [
- 'GeckoTouchDispatcher.h',
- 'GonkPermission.h',
- 'OrientationObserver.h',
-]
-
-DIRS += ['libdisplay', 'nativewindow']
-
-# libui files
-SOURCES += ['libui/' + src for src in [
- 'EventHub.cpp',
- 'Input.cpp',
- 'InputApplication.cpp',
- 'InputDevice.cpp',
- 'InputDispatcher.cpp',
- 'InputListener.cpp',
- 'InputReader.cpp',
- 'InputTransport.cpp',
- 'InputWindow.cpp',
- 'Keyboard.cpp',
- 'KeyCharacterMap.cpp',
- 'KeyLayoutMap.cpp',
- 'PointerController.cpp',
- 'sha1.c',
- 'SpriteController.cpp',
- 'Tokenizer.cpp',
- 'VelocityControl.cpp',
- 'VelocityTracker.cpp',
- 'VirtualKeyMap.cpp',
-]]
-
-# HwcHAL files
-if CONFIG['ANDROID_VERSION'] >= '17':
- SOURCES += [
- 'hwchal/HwcHAL.cpp',
- ]
-
-SOURCES += [
- 'GeckoTouchDispatcher.cpp',
- 'GfxInfo.cpp',
- 'GonkClipboardData.cpp',
- 'GonkMemoryPressureMonitoring.cpp',
- 'GonkPermission.cpp',
- 'HwcComposer2D.cpp',
- 'HwcUtils.cpp',
- 'nsAppShell.cpp',
- 'nsClipboard.cpp',
- 'nsIdleServiceGonk.cpp',
- 'nsLookAndFeel.cpp',
- 'nsScreenManagerGonk.cpp',
- 'nsWidgetFactory.cpp',
- 'nsWindow.cpp',
- 'OrientationObserver.cpp',
- 'ProcessOrientation.cpp',
- 'WidgetTraceEvent.cpp'
-]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-FINAL_LIBRARY = 'xul'
-
-LOCAL_INCLUDES += [
- '/dom/system/android',
- '/gfx/skia/skia/include/config',
- '/gfx/skia/skia/include/core',
- '/image',
- '/widget',
-]
-
-DEFINES['HAVE_OFF64_T'] = True
-DEFINES['SK_BUILD_FOR_ANDROID_NDK'] = True
-DEFINES['HAVE_POSIX_CLOCKS'] = True
-
-LOCAL_INCLUDES += [
- '%' + '%s/%s' % (CONFIG['ANDROID_SOURCE'], d) for d in [
- 'frameworks/native/opengl/include',
- 'hardware/libhardware/include',
- 'hardware/libhardware_legacy/include',
- ]
-]
diff --git a/widget/gonk/nativewindow/FakeSurfaceComposer.cpp b/widget/gonk/nativewindow/FakeSurfaceComposer.cpp
deleted file mode 100644
index 7e4a2a9d8..000000000
--- a/widget/gonk/nativewindow/FakeSurfaceComposer.cpp
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "FakeSurfaceComposer"
-//#define LOG_NDEBUG 0
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <errno.h>
-#include <cutils/atomic.h>
-#include <cutils/log.h>
-#include <cutils/properties.h>
-#include <private/android_filesystem_config.h>
-
-#include <gui/IDisplayEventConnection.h>
-#include <gui/GraphicBufferAlloc.h>
-#include <gui/Surface.h>
-#include <ui/DisplayInfo.h>
-
-#if ANDROID_VERSION >= 21
-#include <ui/Rect.h>
-#endif
-
-#include "../libdisplay/GonkDisplay.h"
-#include "../nsScreenManagerGonk.h"
-#include "FakeSurfaceComposer.h"
-#include "gfxPrefs.h"
-#include "MainThreadUtils.h"
-#include "mozilla/Assertions.h"
-#include "mozilla/layers/CompositorBridgeParent.h"
-#include "mozilla/layers/CompositorThread.h"
-#include "nsProxyRelease.h"
-#include "nsThreadUtils.h"
-
-using namespace mozilla;
-
-namespace android {
-
-/* static */
-void FakeSurfaceComposer::instantiate() {
- defaultServiceManager()->addService(
- String16("SurfaceFlinger"), new FakeSurfaceComposer());
-}
-
-FakeSurfaceComposer::FakeSurfaceComposer()
- : BnSurfaceComposer()
-{
-}
-
-FakeSurfaceComposer::~FakeSurfaceComposer()
-{
-}
-
-status_t FakeSurfaceComposer::onTransact(uint32_t code, const Parcel& data,
- Parcel* reply, uint32_t flags)
-{
- switch (code) {
- case CREATE_CONNECTION:
- case CREATE_DISPLAY:
- case SET_TRANSACTION_STATE:
- case CAPTURE_SCREEN:
- {
- // codes that require permission check
- IPCThreadState* ipc = IPCThreadState::self();
- const int pid = ipc->getCallingPid();
- const int uid = ipc->getCallingUid();
- // Accept request only when uid is root.
- if (uid != AID_ROOT) {
- ALOGE("Permission Denial: "
- "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
- return PERMISSION_DENIED;
- }
- break;
- }
- }
-
- return BnSurfaceComposer::onTransact(code, data, reply, flags);
-}
-
-sp<ISurfaceComposerClient> FakeSurfaceComposer::createConnection()
-{
- return nullptr;
-}
-
-sp<IGraphicBufferAlloc> FakeSurfaceComposer::createGraphicBufferAlloc()
-{
- sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
- return gba;
-}
-
-class DestroyDisplayRunnable : public Runnable {
-public:
- DestroyDisplayRunnable(FakeSurfaceComposer* aComposer, ssize_t aIndex)
- : mComposer(aComposer), mIndex(aIndex) { }
- NS_IMETHOD Run() override {
- MOZ_ASSERT(NS_IsMainThread(), "Must be on main thread.");
- Mutex::Autolock _l(mComposer->mStateLock);
- RefPtr<nsScreenManagerGonk> screenManager =
- nsScreenManagerGonk::GetInstance();
- screenManager->RemoveScreen(GonkDisplay::DISPLAY_VIRTUAL);
- mComposer->mDisplays.removeItemsAt(mIndex);
- return NS_OK;
- }
- sp<FakeSurfaceComposer> mComposer;
- ssize_t mIndex;
-};
-
-sp<IBinder> FakeSurfaceComposer::createDisplay(const String8& displayName,
- bool secure)
-{
-#if ANDROID_VERSION >= 19
- class DisplayToken : public BBinder {
- sp<FakeSurfaceComposer> composer;
- virtual ~DisplayToken() {
- MOZ_ASSERT(NS_IsMainThread(), "Must be on main thread.");
- // no more references, this display must be terminated
- Mutex::Autolock _l(composer->mStateLock);
- ssize_t idx = composer->mDisplays.indexOfKey(this);
- if (idx >= 0) {
- nsCOMPtr<nsIRunnable> task(new DestroyDisplayRunnable(composer.get(), idx));
- NS_DispatchToMainThread(task);
- }
- }
- public:
- DisplayToken(const sp<FakeSurfaceComposer>& composer)
- : composer(composer) {
- }
- };
-
- sp<BBinder> token = new DisplayToken(this);
-
- Mutex::Autolock _l(mStateLock);
- DisplayDeviceState info(HWC_DISPLAY_VIRTUAL);
- info.displayName = displayName;
- info.displayId = GonkDisplay::DISPLAY_VIRTUAL;
- info.isSecure = secure;
- mDisplays.add(token, info);
- return token;
-#else
- return nullptr;
-#endif
-}
-
-#if ANDROID_VERSION >= 19
-void FakeSurfaceComposer::destroyDisplay(const sp<IBinder>& display)
-{
- Mutex::Autolock _l(mStateLock);
-
- ssize_t idx = mDisplays.indexOfKey(display);
- if (idx < 0) {
- ALOGW("destroyDisplay: invalid display token");
- return;
- }
-
- nsCOMPtr<nsIRunnable> task(new DestroyDisplayRunnable(this, idx));
- NS_DispatchToMainThread(task);
-}
-#endif
-
-sp<IBinder> FakeSurfaceComposer::getBuiltInDisplay(int32_t id)
-{
- // support only primary display
- if (uint32_t(id) != HWC_DISPLAY_PRIMARY) {
- return NULL;
- }
-
- if (!mPrimaryDisplay.get()) {
- mPrimaryDisplay = new BBinder();
- }
- return mPrimaryDisplay;
-}
-
-void FakeSurfaceComposer::setTransactionState(
- const Vector<ComposerState>& state,
- const Vector<DisplayState>& displays,
- uint32_t flags)
-{
- Mutex::Autolock _l(mStateLock);
- size_t count = displays.size();
- for (size_t i=0 ; i<count ; i++) {
- const DisplayState& s(displays[i]);
- setDisplayStateLocked(s);
- }
-}
-
-uint32_t FakeSurfaceComposer::setDisplayStateLocked(const DisplayState& s)
-{
- ssize_t dpyIdx = mDisplays.indexOfKey(s.token);
- if (dpyIdx < 0) {
- return 0;
- }
-
- uint32_t flags = 0;
- DisplayDeviceState& disp(mDisplays.editValueAt(dpyIdx));
-
- if (!disp.isValid()) {
- return 0;
- }
-
- const uint32_t what = s.what;
- if (what & DisplayState::eSurfaceChanged) {
- if (disp.surface->asBinder() != s.surface->asBinder()) {
- disp.surface = s.surface;
- flags |= eDisplayTransactionNeeded;
- }
- }
- if (what & DisplayState::eLayerStackChanged) {
- if (disp.layerStack != s.layerStack) {
- disp.layerStack = s.layerStack;
- flags |= eDisplayTransactionNeeded;
- }
- }
- if (what & DisplayState::eDisplayProjectionChanged) {
- if (disp.orientation != s.orientation) {
- disp.orientation = s.orientation;
- flags |= eDisplayTransactionNeeded;
- }
- if (disp.frame != s.frame) {
- disp.frame = s.frame;
- flags |= eDisplayTransactionNeeded;
- }
- if (disp.viewport != s.viewport) {
- disp.viewport = s.viewport;
- flags |= eDisplayTransactionNeeded;
- }
- }
-#if ANDROID_VERSION >= 21
- if (what & DisplayState::eDisplaySizeChanged) {
- if (disp.width != s.width) {
- disp.width = s.width;
- flags |= eDisplayTransactionNeeded;
- }
- if (disp.height != s.height) {
- disp.height = s.height;
- flags |= eDisplayTransactionNeeded;
- }
- }
-#endif
-
- if (what & DisplayState::eSurfaceChanged) {
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([&]() {
- MOZ_ASSERT(NS_IsMainThread(), "Must be on main thread.");
- RefPtr<nsScreenManagerGonk> screenManager = nsScreenManagerGonk::GetInstance();
- screenManager->AddScreen(GonkDisplay::DISPLAY_VIRTUAL, disp.surface.get());
- });
- NS_DispatchToMainThread(runnable, NS_DISPATCH_SYNC);
- }
-
- return flags;
-}
-
-void FakeSurfaceComposer::bootFinished()
-{
-}
-
-bool FakeSurfaceComposer::authenticateSurfaceTexture(
- const sp<IGraphicBufferProducer>& bufferProducer) const {
- return false;
-}
-
-sp<IDisplayEventConnection> FakeSurfaceComposer::createDisplayEventConnection() {
- return nullptr;
-}
-
-// ---------------------------------------------------------------------------
-// Capture screen into an IGraphiBufferProducer
-// ---------------------------------------------------------------------------
-
-class Barrier {
-public:
- inline Barrier() : state(CLOSED) { }
- inline ~Barrier() { }
-
- // Release any threads waiting at the Barrier.
- // Provides release semantics: preceding loads and stores will be visible
- // to other threads before they wake up.
- void open() {
- Mutex::Autolock _l(lock);
- state = OPENED;
- cv.broadcast();
- }
-
- // Reset the Barrier, so wait() will block until open() has been called.
- void close() {
- Mutex::Autolock _l(lock);
- state = CLOSED;
- }
-
- // Wait until the Barrier is OPEN.
- // Provides acquire semantics: no subsequent loads or stores will occur
- // until wait() returns.
- void wait() const {
- Mutex::Autolock _l(lock);
- while (state == CLOSED) {
- cv.wait(lock);
- }
- }
-private:
- enum { OPENED, CLOSED };
- mutable Mutex lock;
- mutable Condition cv;
- volatile int state;
-};
-
-/* The code below is here to handle b/8734824
- *
- * We create a IGraphicBufferProducer wrapper that forwards all calls
- * to the calling binder thread, where they are executed. This allows
- * the calling thread to be reused (on the other side) and not
- * depend on having "enough" binder threads to handle the requests.
- *
- */
-
-class GraphicProducerWrapper : public BBinder, public MessageHandler {
- sp<IGraphicBufferProducer> impl;
- sp<Looper> looper;
- status_t result;
- bool exitPending;
- bool exitRequested;
- mutable Barrier barrier;
- volatile int32_t memoryBarrier;
- uint32_t code;
- Parcel const* data;
- Parcel* reply;
-
- enum {
- MSG_API_CALL,
- MSG_EXIT
- };
-
- /*
- * this is called by our "fake" BpGraphicBufferProducer. We package the
- * data and reply Parcel and forward them to the calling thread.
- */
- virtual status_t transact(uint32_t code,
- const Parcel& data, Parcel* reply, uint32_t flags) {
- this->code = code;
- this->data = &data;
- this->reply = reply;
- android_atomic_acquire_store(0, &memoryBarrier);
- if (exitPending) {
- // if we've exited, we run the message synchronously right here
- handleMessage(Message(MSG_API_CALL));
- } else {
- barrier.close();
- looper->sendMessage(this, Message(MSG_API_CALL));
- barrier.wait();
- }
- return NO_ERROR;
- }
-
- /*
- * here we run on the binder calling thread. All we've got to do is
- * call the real BpGraphicBufferProducer.
- */
- virtual void handleMessage(const Message& message) {
- android_atomic_release_load(&memoryBarrier);
- if (message.what == MSG_API_CALL) {
- impl->asBinder()->transact(code, data[0], reply);
- barrier.open();
- } else if (message.what == MSG_EXIT) {
- exitRequested = true;
- }
- }
-
-public:
- GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) :
- impl(impl), looper(new Looper(true)), result(NO_ERROR),
- exitPending(false), exitRequested(false) {
- }
-
- status_t waitForResponse() {
- do {
- looper->pollOnce(-1);
- } while (!exitRequested);
- return result;
- }
-
- void exit(status_t result) {
- this->result = result;
- exitPending = true;
- looper->sendMessage(this, Message(MSG_EXIT));
- }
-};
-
-status_t
-FakeSurfaceComposer::captureScreen(const sp<IBinder>& display
- , const sp<IGraphicBufferProducer>& producer
-#if ANDROID_VERSION >= 21
- , Rect sourceCrop
-#endif
- , uint32_t reqWidth
- , uint32_t reqHeight
- , uint32_t minLayerZ
- , uint32_t maxLayerZ
-#if ANDROID_VERSION >= 21
- , bool useIdentityTransform
- , Rotation rotation
-#elif ANDROID_VERSION < 19
- , bool isCpuConsumer
-#endif
- )
-{
- if (display == 0 || producer == 0) {
- return BAD_VALUE;
- }
-
- // Limit only to primary display
- if (display != mPrimaryDisplay) {
- return BAD_VALUE;
- }
-
- // this creates a "fake" BBinder which will serve as a "fake" remote
- // binder to receive the marshaled calls and forward them to the
- // real remote (a BpGraphicBufferProducer)
- sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
- // the asInterface() call below creates our "fake" BpGraphicBufferProducer
- // which does the marshaling work forwards to our "fake remote" above.
- sp<IGraphicBufferProducer> fakeProducer = IGraphicBufferProducer::asInterface(wrapper);
-
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([&]() {
- captureScreenImp(fakeProducer, reqWidth, reqHeight, wrapper.get());
- });
- NS_DispatchToMainThread(runnable);
-
- status_t result = wrapper->waitForResponse();
-
- return result;
-}
-
-class RunnableCallTask final : public Runnable
-{
-public:
- explicit RunnableCallTask(nsIRunnable* aRunnable)
- : mRunnable(aRunnable) {}
-
- NS_IMETHOD Run() override
- {
- return mRunnable->Run();
- }
-protected:
- nsCOMPtr<nsIRunnable> mRunnable;
-};
-
-void
-FakeSurfaceComposer::captureScreenImp(const sp<IGraphicBufferProducer>& producer,
- uint32_t reqWidth,
- uint32_t reqHeight,
- const sp<GraphicProducerWrapper>& wrapper)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(wrapper.get());
-
- RefPtr<nsScreenGonk> screen = nsScreenManagerGonk::GetPrimaryScreen();
-
- // get screen geometry
- nsIntRect screenBounds = screen->GetNaturalBounds().ToUnknownRect();
- const uint32_t hw_w = screenBounds.width;
- const uint32_t hw_h = screenBounds.height;
-
- if (reqWidth > hw_w || reqHeight > hw_h) {
- ALOGE("size mismatch (%d, %d) > (%d, %d)",
- reqWidth, reqHeight, hw_w, hw_h);
- static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(BAD_VALUE);
- return;
- }
-
- reqWidth = (!reqWidth) ? hw_w : reqWidth;
- reqHeight = (!reqHeight) ? hw_h : reqHeight;
-
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([screen, reqWidth, reqHeight, producer, wrapper]() {
- // create a surface (because we're a producer, and we need to
- // dequeue/queue a buffer)
- sp<Surface> sur = new Surface(producer);
- ANativeWindow* window = sur.get();
- // The closure makes screen const and we can't call forget() on it.
- RefPtr<nsScreenGonk> screenAlias = screen;
-
- if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) != NO_ERROR) {
- static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(BAD_VALUE);
- NS_ReleaseOnMainThread(screenAlias.forget());
- return;
- }
- uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
-
- int err = 0;
- err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
- err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
- err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
- err |= native_window_set_usage(window, usage);
-
- status_t result = NO_ERROR;
- if (err == NO_ERROR) {
- ANativeWindowBuffer* buffer;
- result = native_window_dequeue_buffer_and_wait(window, &buffer);
- if (result == NO_ERROR) {
- nsresult rv = screen->MakeSnapshot(buffer);
- if (rv != NS_OK) {
- result = INVALID_OPERATION;
- }
- window->queueBuffer(window, buffer, -1);
- }
- } else {
- result = BAD_VALUE;
- }
- native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
- static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
- NS_ReleaseOnMainThread(screenAlias.forget());
- });
-
- layers::CompositorThreadHolder::Loop()->PostTask(
- MakeAndAddRef<RunnableCallTask>(runnable));
-}
-
-#if ANDROID_VERSION >= 21
-void
-FakeSurfaceComposer::setPowerMode(const sp<IBinder>& display, int mode)
-{
-}
-
-status_t
-FakeSurfaceComposer::getDisplayConfigs(const sp<IBinder>& display, Vector<DisplayInfo>* configs)
-{
- if (configs == NULL) {
- return BAD_VALUE;
- }
-
- // Limit DisplayConfigs only to primary display
- if (!display.get() || display != mPrimaryDisplay) {
- return NAME_NOT_FOUND;
- }
-
- configs->clear();
- DisplayInfo info = DisplayInfo();
-
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([&]() {
- MOZ_ASSERT(NS_IsMainThread());
- getPrimaryDisplayInfo(&info);
- });
- NS_DispatchToMainThread(runnable, NS_DISPATCH_SYNC);
-
- configs->push_back(info);
- return NO_ERROR;
-}
-
-status_t
-FakeSurfaceComposer::getDisplayStats(const sp<IBinder>& display, DisplayStatInfo* stats)
-{
- return INVALID_OPERATION;
-}
-
-int
-FakeSurfaceComposer::getActiveConfig(const sp<IBinder>& display)
-{
- // Only support primary display.
- if (display.get() && (display == mPrimaryDisplay)) {
- return 0;
- }
- return INVALID_OPERATION;
-}
-
-status_t
-FakeSurfaceComposer::setActiveConfig(const sp<IBinder>& display, int id)
-{
- return INVALID_OPERATION;
-}
-
-status_t
-FakeSurfaceComposer::clearAnimationFrameStats()
-{
- return INVALID_OPERATION;
-}
-
-status_t
-FakeSurfaceComposer::getAnimationFrameStats(FrameStats* outStats) const
-{
- return INVALID_OPERATION;
-}
-#else
-void
-FakeSurfaceComposer::blank(const sp<IBinder>& display)
-{
-}
-
-void
-FakeSurfaceComposer::unblank(const sp<IBinder>& display)
-{
-}
-
-status_t
-FakeSurfaceComposer::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info)
-{
- if (info == NULL) {
- return BAD_VALUE;
- }
-
- // Limit DisplayConfigs only to primary display
- if (!display.get() || display != mPrimaryDisplay) {
- return NAME_NOT_FOUND;
- }
-
- nsCOMPtr<nsIRunnable> runnable =
- NS_NewRunnableFunction([&]() {
- MOZ_ASSERT(NS_IsMainThread());
- getPrimaryDisplayInfo(info);
- });
- NS_DispatchToMainThread(runnable, NS_DISPATCH_SYNC);
-
- return NO_ERROR;
-}
-#endif
-
-#define VSYNC_EVENT_PHASE_OFFSET_NS 0
-#define SF_VSYNC_EVENT_PHASE_OFFSET_NS 0
-
-void
-FakeSurfaceComposer::getPrimaryDisplayInfo(DisplayInfo* info)
-{
- MOZ_ASSERT(NS_IsMainThread(), "Must be on main thread.");
-
- // Implementation mimic android SurfaceFlinger::getDisplayConfigs().
-
- class Density {
- static int getDensityFromProperty(char const* propName) {
- char property[PROPERTY_VALUE_MAX];
- int density = 0;
- if (property_get(propName, property, NULL) > 0) {
- density = atoi(property);
- }
- return density;
- }
- public:
- static int getEmuDensity() {
- return getDensityFromProperty("qemu.sf.lcd_density"); }
- static int getBuildDensity() {
- return getDensityFromProperty("ro.sf.lcd_density"); }
- };
-
- RefPtr<nsScreenGonk> screen = nsScreenManagerGonk::GetPrimaryScreen();
-
- float xdpi = screen->GetDpi();
- float ydpi = screen->GetDpi();
- int fps = 60; // XXX set a value from hwc hal
- nsIntRect screenBounds = screen->GetNaturalBounds().ToUnknownRect();
-
- // The density of the device is provided by a build property
- float density = Density::getBuildDensity() / 160.0f;
- if (density == 0) {
- // the build doesn't provide a density -- this is wrong!
- // use xdpi instead
- ALOGE("ro.sf.lcd_density must be defined as a build property");
- density = xdpi / 160.0f;
- }
- info->density = density;
- info->orientation = screen->EffectiveScreenRotation();
-
- info->w = screenBounds.width;
- info->h = screenBounds.height;
- info->xdpi = xdpi;
- info->ydpi = ydpi;
- info->fps = fps;
-#if ANDROID_VERSION >= 21
- info->appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
-
- // This is how far in advance a buffer must be queued for
- // presentation at a given time. If you want a buffer to appear
- // on the screen at time N, you must submit the buffer before
- // (N - presentationDeadline).
- //
- // Normally it's one full refresh period (to give SF a chance to
- // latch the buffer), but this can be reduced by configuring a
- // DispSync offset. Any additional delays introduced by the hardware
- // composer or panel must be accounted for here.
- //
- // We add an additional 1ms to allow for processing time and
- // differences between the ideal and actual refresh rate.
- info->presentationDeadline =
- (1e9 / fps) - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
-#endif
- // All non-virtual displays are currently considered secure.
- info->secure = true;
-}
-
-}; // namespace android
diff --git a/widget/gonk/nativewindow/FakeSurfaceComposer.h b/widget/gonk/nativewindow/FakeSurfaceComposer.h
deleted file mode 100644
index 97a717444..000000000
--- a/widget/gonk/nativewindow/FakeSurfaceComposer.h
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_FAKE_SURFACE_COMPOSER_H
-#define NATIVEWINDOW_FAKE_SURFACE_COMPOSER_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-#include <utils/Looper.h>
-
-#include <binder/BinderService.h>
-
-#include <gui/IGraphicBufferProducer.h>
-#include <gui/ISurfaceComposer.h>
-#include <gui/ISurfaceComposerClient.h>
-#include <hardware/hwcomposer.h>
-#include <private/gui/LayerState.h>
-#include <utils/KeyedVector.h>
-
-class nsIWidget;
-
-namespace android {
-
-// ---------------------------------------------------------------------------
-
-class GraphicProducerWrapper;
-class IGraphicBufferAlloc;
-
-enum {
- eTransactionNeeded = 0x01,
- eTraversalNeeded = 0x02,
- eDisplayTransactionNeeded = 0x04,
- eTransactionMask = 0x07
-};
-
-class FakeSurfaceComposer : public BinderService<FakeSurfaceComposer>,
- public BnSurfaceComposer
-{
-public:
- static char const* getServiceName() {
- return "FakeSurfaceComposer";
- }
-
- // Instantiate FakeSurfaceComposer and register to service manager.
- // If service manager is not present, wait until service manager becomes present.
- static void instantiate();
-
-#if ANDROID_VERSION >= 19
- virtual void destroyDisplay(const sp<android::IBinder>& display);
-#endif
-
-#if ANDROID_VERSION >= 21
- virtual status_t captureScreen(const sp<IBinder>& display,
- const sp<IGraphicBufferProducer>& producer,
- Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
- uint32_t minLayerZ, uint32_t maxLayerZ,
- bool useIdentityTransform,
- Rotation rotation = eRotateNone);
-#elif ANDROID_VERSION >= 19
- virtual status_t captureScreen(const sp<IBinder>& display,
- const sp<IGraphicBufferProducer>& producer,
- uint32_t reqWidth, uint32_t reqHeight,
- uint32_t minLayerZ, uint32_t maxLayerZ);
-#else
- virtual status_t captureScreen(const sp<IBinder>& display,
- const sp<IGraphicBufferProducer>& producer,
- uint32_t reqWidth, uint32_t reqHeight,
- uint32_t minLayerZ, uint32_t maxLayerZ, bool isCpuConsumer);
-#endif
-
-private:
- FakeSurfaceComposer();
- // We're reference counted, never destroy FakeSurfaceComposer directly
- virtual ~FakeSurfaceComposer();
-
- /* ------------------------------------------------------------------------
- * IBinder interface
- */
- virtual status_t onTransact(uint32_t code, const Parcel& data,
- Parcel* reply, uint32_t flags);
-
- /* ------------------------------------------------------------------------
- * ISurfaceComposer interface
- */
- virtual sp<ISurfaceComposerClient> createConnection();
- virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
- virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
- virtual sp<IBinder> getBuiltInDisplay(int32_t id);
- virtual void setTransactionState(const Vector<ComposerState>& state,
- const Vector<DisplayState>& displays, uint32_t flags);
- virtual void bootFinished();
- virtual bool authenticateSurfaceTexture(
- const sp<IGraphicBufferProducer>& bufferProducer) const;
- virtual sp<IDisplayEventConnection> createDisplayEventConnection();
-#if ANDROID_VERSION >= 21
- virtual void setPowerMode(const sp<IBinder>& display, int mode);
- virtual status_t getDisplayConfigs(const sp<IBinder>& display, Vector<DisplayInfo>* configs);
- virtual status_t getDisplayStats(const sp<IBinder>& display, DisplayStatInfo* stats);
- virtual int getActiveConfig(const sp<IBinder>& display);
- virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
- virtual status_t clearAnimationFrameStats();
- virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
-#elif ANDROID_VERSION >= 17
- // called when screen needs to turn off
- virtual void blank(const sp<IBinder>& display);
- // called when screen is turning back on
- virtual void unblank(const sp<IBinder>& display);
- virtual status_t getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info);
-#endif
- void getPrimaryDisplayInfo(DisplayInfo* info);
-
- /* ------------------------------------------------------------------------
- * Transactions
- */
- uint32_t setDisplayStateLocked(const DisplayState& s);
-
- void captureScreenImp(const sp<IGraphicBufferProducer>& producer,
- uint32_t reqWidth,
- uint32_t reqHeight,
- const sp<GraphicProducerWrapper>& wrapper);
-
- sp<IBinder> mPrimaryDisplay;
-
- struct DisplayDeviceState {
- enum {
- NO_LAYER_STACK = 0xFFFFFFFF,
- };
- DisplayDeviceState()
- : type(-1), displayId(-1), width(0), height(0) {
- }
- DisplayDeviceState(int type)
- : type(type), displayId(-1), layerStack(NO_LAYER_STACK), orientation(0), width(0), height(0) {
- viewport.makeInvalid();
- frame.makeInvalid();
- }
- bool isValid() const { return type >= 0; }
- int type;
- int displayId;
- sp<IGraphicBufferProducer> surface;
- uint32_t layerStack;
- Rect viewport;
- Rect frame;
- uint8_t orientation;
- uint32_t width, height;
- String8 displayName;
- bool isSecure;
- };
-
- // access must be protected by mStateLock
- mutable Mutex mStateLock;
- DefaultKeyedVector<wp<IBinder>, DisplayDeviceState> mDisplays;
-
- friend class DestroyDisplayRunnable;
-};
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-
-#endif // NATIVEWINDOW_FAKE_SURFACE_COMPOSER_H
diff --git a/widget/gonk/nativewindow/GonkBufferQueue.h b/widget/gonk/nativewindow/GonkBufferQueue.h
deleted file mode 100644
index defdb0ae2..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueue.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/* Copyright 2013 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 21
-# include "GonkBufferQueueLL.h"
-#elif defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 19
-# include "GonkBufferQueueKK.h"
-#elif defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
-# include "GonkBufferQueueJB.h"
-#endif
diff --git a/widget/gonk/nativewindow/GonkBufferQueueJB.cpp b/widget/gonk/nativewindow/GonkBufferQueueJB.cpp
deleted file mode 100644
index 81502f81e..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueJB.cpp
+++ /dev/null
@@ -1,1036 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "GonkBufferQueue"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-#define LOG_NDEBUG 0
-
-#define GL_GLEXT_PROTOTYPES
-#define EGL_EGLEXT_PROTOTYPES
-
-#include <utils/Log.h>
-
-#include "mozilla/layers/GrallocTextureClient.h"
-#include "mozilla/layers/ImageBridgeChild.h"
-
-#include "GonkBufferQueueJB.h"
-
-// Macros for including the GonkBufferQueue name in log messages
-#define ST_LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
-#define ST_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
-#define ST_LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define ST_LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
-#define ST_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-#define ATRACE_BUFFER_INDEX(index)
-
-using namespace mozilla;
-using namespace mozilla::gfx;
-using namespace mozilla::layers;
-
-namespace android {
-
-// Get an ID that's unique within this process.
-static int32_t createProcessUniqueId() {
- static volatile int32_t globalCounter = 0;
- return android_atomic_inc(&globalCounter);
-}
-
-static const char* scalingModeName(int scalingMode) {
- switch (scalingMode) {
- case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE";
- case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW";
- case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP";
- default: return "Unknown";
- }
-}
-
-GonkBufferQueue::GonkBufferQueue(bool allowSynchronousMode,
- const sp<IGraphicBufferAlloc>& allocator) :
- mDefaultWidth(1),
- mDefaultHeight(1),
- mMaxAcquiredBufferCount(1),
- mDefaultMaxBufferCount(2),
- mOverrideMaxBufferCount(0),
- mSynchronousMode(true),
- mAllowSynchronousMode(allowSynchronousMode),
- mConnectedApi(NO_CONNECTED_API),
- mAbandoned(false),
- mFrameCounter(0),
- mBufferHasBeenQueued(false),
- mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),
- mConsumerUsageBits(0),
- mTransformHint(0)
-{
- // Choose a name using the PID and a process-unique ID.
- mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
-
- ST_LOGV("GonkBufferQueue");
-}
-
-GonkBufferQueue::~GonkBufferQueue() {
- ST_LOGV("~GonkBufferQueue");
-}
-
-status_t GonkBufferQueue::setDefaultMaxBufferCountLocked(int count) {
- if (count < 2 || count > NUM_BUFFER_SLOTS)
- return BAD_VALUE;
-
- mDefaultMaxBufferCount = count;
- mDequeueCondition.broadcast();
-
- return NO_ERROR;
-}
-
-bool GonkBufferQueue::isSynchronousMode() const {
- Mutex::Autolock lock(mMutex);
- return mSynchronousMode;
-}
-
-void GonkBufferQueue::setConsumerName(const String8& name) {
- Mutex::Autolock lock(mMutex);
- mConsumerName = name;
-}
-
-status_t GonkBufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) {
- Mutex::Autolock lock(mMutex);
- mDefaultBufferFormat = defaultFormat;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setConsumerUsageBits(uint32_t usage) {
- Mutex::Autolock lock(mMutex);
- mConsumerUsageBits = usage;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setTransformHint(uint32_t hint) {
- ST_LOGV("setTransformHint: %02x", hint);
- Mutex::Autolock lock(mMutex);
- mTransformHint = hint;
- return NO_ERROR;
-}
-
-already_AddRefed<TextureClient>
-GonkBufferQueue::getTextureClientFromBuffer(ANativeWindowBuffer* buffer)
-{
- Mutex::Autolock _l(mMutex);
- if (buffer == NULL) {
- ST_LOGE("getSlotFromBufferLocked: encountered NULL buffer");
- return nullptr;
- }
-
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mGraphicBuffer != NULL && mSlots[i].mGraphicBuffer->handle == buffer->handle) {
- RefPtr<TextureClient> client(mSlots[i].mTextureClient);
- return client.forget();
- }
- }
- ST_LOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
- return nullptr;
-}
-
-int GonkBufferQueue::getSlotFromTextureClientLocked(
- TextureClient* client) const
-{
- if (client == NULL) {
- ST_LOGE("getSlotFromBufferLocked: encountered NULL buffer");
- return BAD_VALUE;
- }
-
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mTextureClient == client) {
- return i;
- }
- }
- ST_LOGE("getSlotFromBufferLocked: unknown TextureClient: %p", client);
- return BAD_VALUE;
-}
-
-
-status_t GonkBufferQueue::setBufferCount(int bufferCount) {
- ST_LOGV("setBufferCount: count=%d", bufferCount);
-
- sp<ConsumerListener> listener;
- {
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ST_LOGE("setBufferCount: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
- if (bufferCount > NUM_BUFFER_SLOTS) {
- ST_LOGE("setBufferCount: bufferCount too large (max %d)",
- NUM_BUFFER_SLOTS);
- return BAD_VALUE;
- }
-
- // Error out if the user has dequeued buffers
- int maxBufferCount = getMaxBufferCountLocked();
- for (int i=0 ; i<maxBufferCount; i++) {
- if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) {
- ST_LOGE("setBufferCount: client owns some buffers");
- return -EINVAL;
- }
- }
-
- const int minBufferSlots = getMinMaxBufferCountLocked();
- if (bufferCount == 0) {
- mOverrideMaxBufferCount = 0;
- mDequeueCondition.broadcast();
- return NO_ERROR;
- }
-
- if (bufferCount < minBufferSlots) {
- ST_LOGE("setBufferCount: requested buffer count (%d) is less than "
- "minimum (%d)", bufferCount, minBufferSlots);
- return BAD_VALUE;
- }
-
- // here we're guaranteed that the client doesn't have dequeued buffers
- // and will release all of its buffer references.
- //
- // XXX: Should this use drainQueueAndFreeBuffersLocked instead?
- freeAllBuffersLocked();
- mOverrideMaxBufferCount = bufferCount;
- mBufferHasBeenQueued = false;
- mDequeueCondition.broadcast();
- listener = mConsumerListener;
- } // scope for lock
-
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-
- return NO_ERROR;
-}
-
-int GonkBufferQueue::query(int what, int* outValue)
-{
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ST_LOGE("query: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- int value;
- switch (what) {
- case NATIVE_WINDOW_WIDTH:
- value = mDefaultWidth;
- break;
- case NATIVE_WINDOW_HEIGHT:
- value = mDefaultHeight;
- break;
- case NATIVE_WINDOW_FORMAT:
- value = mDefaultBufferFormat;
- break;
- case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
- value = getMinUndequeuedBufferCountLocked();
- break;
- case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
- value = (mQueue.size() >= 2);
- break;
- default:
- return BAD_VALUE;
- }
- outValue[0] = value;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
- ST_LOGV("requestBuffer: slot=%d", slot);
- Mutex::Autolock lock(mMutex);
- if (mAbandoned) {
- ST_LOGE("requestBuffer: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
- int maxBufferCount = getMaxBufferCountLocked();
- if (slot < 0 || maxBufferCount <= slot) {
- ST_LOGE("requestBuffer: slot index out of range [0, %d]: %d",
- maxBufferCount, slot);
- return BAD_VALUE;
- } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
- // XXX: I vaguely recall there was some reason this can be valid, but
- // for the life of me I can't recall under what circumstances that's
- // the case.
- ST_LOGE("requestBuffer: slot %d is not owned by the client (state=%d)",
- slot, mSlots[slot].mBufferState);
- return BAD_VALUE;
- }
- mSlots[slot].mRequestBufferCalled = true;
- *buf = mSlots[slot].mGraphicBuffer;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::dequeueBuffer(int *outBuf, sp<Fence>* outFence,
- uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
- ST_LOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);
-
- if ((w && !h) || (!w && h)) {
- ST_LOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
- return BAD_VALUE;
- }
-
- status_t returnFlags(OK);
- int buf = INVALID_BUFFER_SLOT;
-
- { // Scope for the lock
- Mutex::Autolock lock(mMutex);
-
- if (format == 0) {
- format = mDefaultBufferFormat;
- }
- // turn on usage bits the consumer requested
- usage |= mConsumerUsageBits;
-
- int found = -1;
- int dequeuedCount = 0;
- bool tryAgain = true;
- while (tryAgain) {
- if (mAbandoned) {
- ST_LOGE("dequeueBuffer: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- const int maxBufferCount = getMaxBufferCountLocked();
-
- // Free up any buffers that are in slots beyond the max buffer
- // count.
- //for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
- // assert(mSlots[i].mBufferState == BufferSlot::FREE);
- // if (mSlots[i].mGraphicBuffer != NULL) {
- // freeBufferLocked(i);
- // returnFlags |= IGraphicBufferProducer::RELEASE_ALL_BUFFERS;
- // }
- //}
-
- // look for a free buffer to give to the client
- found = INVALID_BUFFER_SLOT;
- dequeuedCount = 0;
- for (int i = 0; i < maxBufferCount; i++) {
- const int state = mSlots[i].mBufferState;
- if (state == BufferSlot::DEQUEUED) {
- dequeuedCount++;
- }
-
- if (state == BufferSlot::FREE) {
- /* We return the oldest of the free buffers to avoid
- * stalling the producer if possible. This is because
- * the consumer may still have pending reads of the
- * buffers in flight.
- */
- if ((found < 0) ||
- mSlots[i].mFrameNumber < mSlots[found].mFrameNumber) {
- found = i;
- }
- }
- }
-
- // clients are not allowed to dequeue more than one buffer
- // if they didn't set a buffer count.
- if (!mOverrideMaxBufferCount && dequeuedCount) {
- ST_LOGE("dequeueBuffer: can't dequeue multiple buffers without "
- "setting the buffer count");
- return -EINVAL;
- }
-
- // See whether a buffer has been queued since the last
- // setBufferCount so we know whether to perform the min undequeued
- // buffers check below.
- if (mBufferHasBeenQueued) {
- // make sure the client is not trying to dequeue more buffers
- // than allowed.
- const int newUndequeuedCount = maxBufferCount - (dequeuedCount+1);
- const int minUndequeuedCount = getMinUndequeuedBufferCountLocked();
- if (newUndequeuedCount < minUndequeuedCount) {
- ST_LOGE("dequeueBuffer: min undequeued buffer count (%d) "
- "exceeded (dequeued=%d undequeudCount=%d)",
- minUndequeuedCount, dequeuedCount,
- newUndequeuedCount);
- return -EBUSY;
- }
- }
-
- // If no buffer is found, wait for a buffer to be released or for
- // the max buffer count to change.
- tryAgain = found == INVALID_BUFFER_SLOT;
- if (tryAgain) {
- mDequeueCondition.wait(mMutex);
- }
- }
-
-
- if (found == INVALID_BUFFER_SLOT) {
- // This should not happen.
- ST_LOGE("dequeueBuffer: no available buffer slots");
- return -EBUSY;
- }
-
- buf = found;
- *outBuf = found;
-
- const bool useDefaultSize = !w && !h;
- if (useDefaultSize) {
- // use the default size
- w = mDefaultWidth;
- h = mDefaultHeight;
- }
-
- mSlots[buf].mBufferState = BufferSlot::DEQUEUED;
-
- const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
- if ((buffer == NULL) ||
- (uint32_t(buffer->width) != w) ||
- (uint32_t(buffer->height) != h) ||
- (uint32_t(buffer->format) != format) ||
- ((uint32_t(buffer->usage) & usage) != usage))
- {
- mSlots[buf].mAcquireCalled = false;
- mSlots[buf].mGraphicBuffer = NULL;
- mSlots[buf].mRequestBufferCalled = false;
- mSlots[buf].mFence = Fence::NO_FENCE;
- if (mSlots[buf].mTextureClient) {
- mSlots[buf].mTextureClient->ClearRecycleCallback();
- // release TextureClient in ImageBridge thread
- RefPtr<TextureClientReleaseTask> task =
- MakeAndAddRef<TextureClientReleaseTask>(mSlots[buf].mTextureClient);
- mSlots[buf].mTextureClient = NULL;
- ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget());
- }
- returnFlags |= IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION;
- }
-
- *outFence = mSlots[buf].mFence;
- mSlots[buf].mFence = Fence::NO_FENCE;
- } // end lock scope
-
- sp<GraphicBuffer> graphicBuffer;
- if (returnFlags & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
-
- usage |= GraphicBuffer::USAGE_HW_TEXTURE;
- RefPtr<LayersIPCChannel> allocator = ImageBridgeChild::GetSingleton();
- GrallocTextureData* texData = GrallocTextureData::Create(IntSize(w,h), format,
- gfx::BackendType::NONE, usage,
- allocator);
- if (!texData) {
- ST_LOGE("dequeueBuffer: failed to alloc gralloc buffer");
- return -ENOMEM;
- }
- RefPtr<TextureClient> textureClient = new TextureClient(texData, TextureFlags::RECYCLE | TextureFlags::DEALLOCATE_CLIENT, allocator);
- sp<GraphicBuffer> graphicBuffer = texData->GetGraphicBuffer();
-
- { // Scope for the lock
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ST_LOGE("dequeueBuffer: SurfaceTexture has been abandoned!");
- return NO_INIT;
- }
-
- mSlots[buf].mGraphicBuffer = graphicBuffer;
- mSlots[buf].mTextureClient = textureClient;
- ST_LOGD("dequeueBuffer: returning slot=%d buf=%p ", buf,
- mSlots[buf].mGraphicBuffer->handle);
- //mSlots[*outBuf].mGraphicBuffer = graphicBuffer;
- }
- }
-
- ST_LOGV("dequeueBuffer: returning slot=%d buf=%p flags=%#x", *outBuf,
- mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);
-
- return returnFlags;
-}
-
-status_t GonkBufferQueue::setSynchronousMode(bool enabled) {
- ST_LOGV("setSynchronousMode: enabled=%d", enabled);
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ST_LOGE("setSynchronousMode: BufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- if (mSynchronousMode != enabled) {
- mSynchronousMode = enabled;
- mDequeueCondition.broadcast();
- }
- return OK;
-}
-
-status_t GonkBufferQueue::queueBuffer(int buf,
- const QueueBufferInput& input, QueueBufferOutput* output) {
-
- Rect crop;
- uint32_t transform;
- int scalingMode;
- int64_t timestamp;
- sp<Fence> fence;
-
- input.deflate(&timestamp, &crop, &scalingMode, &transform, &fence);
-
-#if ANDROID_VERSION >= 18
- if (fence == NULL) {
- ST_LOGE("queueBuffer: fence is NULL");
- return BAD_VALUE;
- }
-#endif
-
- ST_LOGV("queueBuffer: slot=%d time=%#llx crop=[%d,%d,%d,%d] tr=%#x "
- "scale=%s",
- buf, timestamp, crop.left, crop.top, crop.right, crop.bottom,
- transform, scalingModeName(scalingMode));
-
- sp<ConsumerListener> listener;
-
- { // scope for the lock
- Mutex::Autolock lock(mMutex);
- if (mAbandoned) {
- ST_LOGE("queueBuffer: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
- int maxBufferCount = getMaxBufferCountLocked();
- if (buf < 0 || buf >= maxBufferCount) {
- ST_LOGE("queueBuffer: slot index out of range [0, %d]: %d",
- maxBufferCount, buf);
- return -EINVAL;
- } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
- ST_LOGE("queueBuffer: slot %d is not owned by the client "
- "(state=%d)", buf, mSlots[buf].mBufferState);
- return -EINVAL;
- } else if (!mSlots[buf].mRequestBufferCalled) {
- ST_LOGE("queueBuffer: slot %d was enqueued without requesting a "
- "buffer", buf);
- return -EINVAL;
- }
-
- const sp<GraphicBuffer>& graphicBuffer(mSlots[buf].mGraphicBuffer);
- Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
- Rect croppedCrop;
- crop.intersect(bufferRect, &croppedCrop);
- if (croppedCrop != crop) {
- ST_LOGE("queueBuffer: crop rect is not contained within the "
- "buffer in slot %d", buf);
- return -EINVAL;
- }
-
- if (mSynchronousMode) {
- // In synchronous mode we queue all buffers in a FIFO.
- mQueue.push_back(buf);
- } else {
- // In asynchronous mode we only keep the most recent buffer.
- if (mQueue.empty()) {
- mQueue.push_back(buf);
- } else {
- Fifo::iterator front(mQueue.begin());
- // buffer currently queued is freed
- mSlots[*front].mBufferState = BufferSlot::FREE;
- // and we record the new buffer index in the queued list
- *front = buf;
- }
- }
- // always signals that an additional frame should be consumed
- // to handle max acquired buffer count reached case.
- listener = mConsumerListener;
-
- mSlots[buf].mTimestamp = timestamp;
- mSlots[buf].mCrop = crop;
- mSlots[buf].mTransform = transform;
- mSlots[buf].mFence = fence;
-
- switch (scalingMode) {
- case NATIVE_WINDOW_SCALING_MODE_FREEZE:
- case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
- case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
- break;
- default:
- ST_LOGE("unknown scaling mode: %d (ignoring)", scalingMode);
- scalingMode = mSlots[buf].mScalingMode;
- break;
- }
-
- mSlots[buf].mBufferState = BufferSlot::QUEUED;
- mSlots[buf].mScalingMode = scalingMode;
- mFrameCounter++;
- mSlots[buf].mFrameNumber = mFrameCounter;
-
- mBufferHasBeenQueued = true;
- mDequeueCondition.broadcast();
-
- output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
- mQueue.size());
- } // scope for the lock
-
- // call back without lock held
- if (listener != 0) {
- listener->onFrameAvailable();
- }
- return NO_ERROR;
-}
-
-#if ANDROID_VERSION == 17
-void GonkBufferQueue::cancelBuffer(int buf, sp<Fence> fence) {
-#else
-void GonkBufferQueue::cancelBuffer(int buf, const sp<Fence>& fence) {
-#endif
-
- ST_LOGV("cancelBuffer: slot=%d", buf);
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ST_LOGW("cancelBuffer: GonkBufferQueue has been abandoned!");
- return;
- }
-
- int maxBufferCount = getMaxBufferCountLocked();
- if (buf < 0 || buf >= maxBufferCount) {
- ST_LOGE("cancelBuffer: slot index out of range [0, %d]: %d",
- maxBufferCount, buf);
- return;
- } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
- ST_LOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
- buf, mSlots[buf].mBufferState);
- return;
-#if ANDROID_VERSION >= 18
- } else if (fence == NULL) {
- ST_LOGE("cancelBuffer: fence is NULL");
- return;
-#endif
- }
- mSlots[buf].mBufferState = BufferSlot::FREE;
- mSlots[buf].mFrameNumber = 0;
- mSlots[buf].mFence = fence;
- mDequeueCondition.broadcast();
-}
-
-status_t GonkBufferQueue::connect(int api, QueueBufferOutput* output) {
- ST_LOGV("connect: api=%d", api);
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ST_LOGE("connect: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- if (mConsumerListener == NULL) {
- ST_LOGE("connect: GonkBufferQueue has no consumer!");
- return NO_INIT;
- }
-
- int err = NO_ERROR;
- switch (api) {
- case NATIVE_WINDOW_API_EGL:
- case NATIVE_WINDOW_API_CPU:
- case NATIVE_WINDOW_API_MEDIA:
- case NATIVE_WINDOW_API_CAMERA:
- if (mConnectedApi != NO_CONNECTED_API) {
- ST_LOGE("connect: already connected (cur=%d, req=%d)",
- mConnectedApi, api);
- err = -EINVAL;
- } else {
- mConnectedApi = api;
- output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
- mQueue.size());
- }
- break;
- default:
- err = -EINVAL;
- break;
- }
-
- mBufferHasBeenQueued = false;
-
- return err;
-}
-
-status_t GonkBufferQueue::disconnect(int api) {
- ST_LOGV("disconnect: api=%d", api);
-
- int err = NO_ERROR;
- sp<ConsumerListener> listener;
-
- { // Scope for the lock
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- // it is not really an error to disconnect after the surface
- // has been abandoned, it should just be a no-op.
- return NO_ERROR;
- }
-
- switch (api) {
- case NATIVE_WINDOW_API_EGL:
- case NATIVE_WINDOW_API_CPU:
- case NATIVE_WINDOW_API_MEDIA:
- case NATIVE_WINDOW_API_CAMERA:
- if (mConnectedApi == api) {
- freeAllBuffersLocked();
- mConnectedApi = NO_CONNECTED_API;
- mDequeueCondition.broadcast();
- listener = mConsumerListener;
- } else {
- ST_LOGE("disconnect: connected to another api (cur=%d, req=%d)",
- mConnectedApi, api);
- err = -EINVAL;
- }
- break;
- default:
- ST_LOGE("disconnect: unknown API %d", api);
- err = -EINVAL;
- break;
- }
- }
-
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-
- return err;
-}
-
-void GonkBufferQueue::dumpToString(String8& result) const
-{
- char buffer[1024];
- GonkBufferQueue::dumpToString(result, "", buffer, 1024);
-}
-
-void GonkBufferQueue::dumpToString(String8& result, const char* prefix,
- char* buffer, size_t SIZE) const
-{
- Mutex::Autolock _l(mMutex);
-
- String8 fifo;
- int fifoSize = 0;
- Fifo::const_iterator i(mQueue.begin());
- while (i != mQueue.end()) {
- snprintf(buffer, SIZE, "%02d ", *i++);
- fifoSize++;
- fifo.append(buffer);
- }
-
- int maxBufferCount = getMaxBufferCountLocked();
-
- snprintf(buffer, SIZE,
- "%s-BufferQueue maxBufferCount=%d, mSynchronousMode=%d, default-size=[%dx%d], "
- "default-format=%d, transform-hint=%02x, FIFO(%d)={%s}\n",
- prefix, maxBufferCount, mSynchronousMode, mDefaultWidth,
- mDefaultHeight, mDefaultBufferFormat, mTransformHint,
- fifoSize, fifo.string());
- result.append(buffer);
-
-
- struct {
- const char * operator()(int state) const {
- switch (state) {
- case BufferSlot::DEQUEUED: return "DEQUEUED";
- case BufferSlot::QUEUED: return "QUEUED";
- case BufferSlot::FREE: return "FREE";
- case BufferSlot::ACQUIRED: return "ACQUIRED";
- default: return "Unknown";
- }
- }
- } stateName;
-
- for (int i=0 ; i<maxBufferCount ; i++) {
- const BufferSlot& slot(mSlots[i]);
- snprintf(buffer, SIZE,
- "%s%s[%02d] "
- "state=%-8s, crop=[%d,%d,%d,%d], "
- "xform=0x%02x, time=%#llx, scale=%s",
- prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i,
- stateName(slot.mBufferState),
- slot.mCrop.left, slot.mCrop.top, slot.mCrop.right,
- slot.mCrop.bottom, slot.mTransform, slot.mTimestamp,
- scalingModeName(slot.mScalingMode)
- );
- result.append(buffer);
-
- const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
- if (buf != NULL) {
- snprintf(buffer, SIZE,
- ", %p [%4ux%4u:%4u,%3X]",
- buf->handle, buf->width, buf->height, buf->stride,
- buf->format);
- result.append(buffer);
- }
- result.append("\n");
- }
-}
-
-void GonkBufferQueue::freeAllBuffersLocked()
-{
- ALOGW_IF(!mQueue.isEmpty(),
- "freeAllBuffersLocked called but mQueue is not empty");
- mQueue.clear();
- mBufferHasBeenQueued = false;
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- mSlots[i].mGraphicBuffer = 0;
- if (mSlots[i].mTextureClient) {
- mSlots[i].mTextureClient->ClearRecycleCallback();
- // release TextureClient in ImageBridge thread
- RefPtr<TextureClientReleaseTask> task =
- MakeAndAddRef<TextureClientReleaseTask>(mSlots[i].mTextureClient);
- mSlots[i].mTextureClient = NULL;
- ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget());
- }
- if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
- mSlots[i].mNeedsCleanupOnRelease = true;
- }
- mSlots[i].mBufferState = BufferSlot::FREE;
- mSlots[i].mFrameNumber = 0;
- mSlots[i].mAcquireCalled = false;
- // destroy fence as GonkBufferQueue now takes ownership
- mSlots[i].mFence = Fence::NO_FENCE;
- }
-}
-
-status_t GonkBufferQueue::acquireBuffer(BufferItem *buffer) {
- Mutex::Autolock _l(mMutex);
-
- // Check that the consumer doesn't currently have the maximum number of
- // buffers acquired. We allow the max buffer count to be exceeded by one
- // buffer, so that the consumer can successfully set up the newly acquired
- // buffer before releasing the old one.
- int numAcquiredBuffers = 0;
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
- numAcquiredBuffers++;
- }
- }
- if (numAcquiredBuffers >= mMaxAcquiredBufferCount+1) {
- ST_LOGE("acquireBuffer: max acquired buffer count reached: %d (max=%d)",
- numAcquiredBuffers, mMaxAcquiredBufferCount);
- return INVALID_OPERATION;
- }
-
- // check if queue is empty
- // In asynchronous mode the list is guaranteed to be one buffer
- // deep, while in synchronous mode we use the oldest buffer.
- if (!mQueue.empty()) {
- Fifo::iterator front(mQueue.begin());
- int buf = *front;
-
- // In android, when the buffer is aquired by BufferConsumer,
- // BufferQueue releases a reference to the buffer and
- // it's ownership moves to the BufferConsumer.
- // In b2g, GonkBufferQueue continues to have a buffer ownership.
- // It is necessary to free buffer via ImageBridgeChild.
-
- //if (mSlots[buf].mAcquireCalled) {
- // buffer->mGraphicBuffer = NULL;
- //} else {
- // buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer;
- //}
- buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer;
- buffer->mCrop = mSlots[buf].mCrop;
- buffer->mTransform = mSlots[buf].mTransform;
- buffer->mScalingMode = mSlots[buf].mScalingMode;
- buffer->mFrameNumber = mSlots[buf].mFrameNumber;
- buffer->mTimestamp = mSlots[buf].mTimestamp;
- buffer->mBuf = buf;
- buffer->mFence = mSlots[buf].mFence;
-
- mSlots[buf].mAcquireCalled = true;
- mSlots[buf].mNeedsCleanupOnRelease = false;
- mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
- mSlots[buf].mFence = Fence::NO_FENCE;
-
- mQueue.erase(front);
- mDequeueCondition.broadcast();
- } else {
- return NO_BUFFER_AVAILABLE;
- }
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::releaseBuffer(int buf, const sp<Fence>& fence) {
- Mutex::Autolock _l(mMutex);
-
-#if ANDROID_VERSION == 17
- if (buf == INVALID_BUFFER_SLOT) {
-#else
- if (buf == INVALID_BUFFER_SLOT || fence == NULL) {
-#endif
- return BAD_VALUE;
- }
-
- mSlots[buf].mFence = fence;
-
- // The buffer can now only be released if its in the acquired state
- if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
- mSlots[buf].mBufferState = BufferSlot::FREE;
- } else if (mSlots[buf].mNeedsCleanupOnRelease) {
- ST_LOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState);
- mSlots[buf].mNeedsCleanupOnRelease = false;
- return STALE_BUFFER_SLOT;
- } else {
- ST_LOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState);
- return -EINVAL;
- }
-
- mDequeueCondition.broadcast();
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::consumerConnect(const sp<ConsumerListener>& consumerListener) {
- ST_LOGV("consumerConnect");
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ST_LOGE("consumerConnect: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
- if (consumerListener == NULL) {
- ST_LOGE("consumerConnect: consumerListener may not be NULL");
- return BAD_VALUE;
- }
-
- mConsumerListener = consumerListener;
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::consumerDisconnect() {
- ST_LOGV("consumerDisconnect");
- Mutex::Autolock lock(mMutex);
-
- if (mConsumerListener == NULL) {
- ST_LOGE("consumerDisconnect: No consumer is connected!");
- return -EINVAL;
- }
-
- mAbandoned = true;
- mConsumerListener = NULL;
- mQueue.clear();
- freeAllBuffersLocked();
- mDequeueCondition.broadcast();
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::getReleasedBuffers(uint32_t* slotMask) {
- ST_LOGV("getReleasedBuffers");
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ST_LOGE("getReleasedBuffers: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- uint32_t mask = 0;
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- if (!mSlots[i].mAcquireCalled) {
- mask |= 1 << i;
- }
- }
- *slotMask = mask;
-
- ST_LOGV("getReleasedBuffers: returning mask %#x", mask);
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h)
-{
- ST_LOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
- if (!w || !h) {
- ST_LOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
- w, h);
- return BAD_VALUE;
- }
-
- Mutex::Autolock lock(mMutex);
- mDefaultWidth = w;
- mDefaultHeight = h;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setDefaultMaxBufferCount(int bufferCount) {
- Mutex::Autolock lock(mMutex);
- return setDefaultMaxBufferCountLocked(bufferCount);
-}
-
-status_t GonkBufferQueue::setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
- Mutex::Autolock lock(mMutex);
- if (maxAcquiredBuffers < 1 || maxAcquiredBuffers > MAX_MAX_ACQUIRED_BUFFERS) {
- ST_LOGE("setMaxAcquiredBufferCount: invalid count specified: %d",
- maxAcquiredBuffers);
- return BAD_VALUE;
- }
- if (mConnectedApi != NO_CONNECTED_API) {
- return INVALID_OPERATION;
- }
- mMaxAcquiredBufferCount = maxAcquiredBuffers;
- return NO_ERROR;
-}
-
-int GonkBufferQueue::getMinMaxBufferCountLocked() const {
- return getMinUndequeuedBufferCountLocked() + 1;
-}
-
-int GonkBufferQueue::getMinUndequeuedBufferCountLocked() const {
- return mSynchronousMode ? mMaxAcquiredBufferCount :
- mMaxAcquiredBufferCount + 1;
-}
-
-int GonkBufferQueue::getMaxBufferCountLocked() const {
- int minMaxBufferCount = getMinMaxBufferCountLocked();
-
- int maxBufferCount = mDefaultMaxBufferCount;
- if (maxBufferCount < minMaxBufferCount) {
- maxBufferCount = minMaxBufferCount;
- }
- if (mOverrideMaxBufferCount != 0) {
- assert(mOverrideMaxBufferCount >= minMaxBufferCount);
- maxBufferCount = mOverrideMaxBufferCount;
- }
-
- // Any buffers that are dequeued by the producer or sitting in the queue
- // waiting to be consumed need to have their slots preserved. Such
- // buffers will temporarily keep the max buffer count up until the slots
- // no longer need to be preserved.
- for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
- BufferSlot::BufferState state = mSlots[i].mBufferState;
- if (state == BufferSlot::QUEUED || state == BufferSlot::DEQUEUED) {
- maxBufferCount = i + 1;
- }
- }
-
- return maxBufferCount;
-}
-
-GonkBufferQueue::ProxyConsumerListener::ProxyConsumerListener(
- const wp<GonkBufferQueue::ConsumerListener>& consumerListener):
- mConsumerListener(consumerListener) {}
-
-GonkBufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}
-
-void GonkBufferQueue::ProxyConsumerListener::onFrameAvailable() {
- sp<GonkBufferQueue::ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onFrameAvailable();
- }
-}
-
-void GonkBufferQueue::ProxyConsumerListener::onBuffersReleased() {
- sp<GonkBufferQueue::ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-}
-
-}; // namespace android
diff --git a/widget/gonk/nativewindow/GonkBufferQueueJB.h b/widget/gonk/nativewindow/GonkBufferQueueJB.h
deleted file mode 100644
index df0c4599f..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueJB.h
+++ /dev/null
@@ -1,653 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKBUFFERQUEUE_JB_H
-#define NATIVEWINDOW_GONKBUFFERQUEUE_JB_H
-
-#include <gui/IGraphicBufferAlloc.h>
-#if ANDROID_VERSION == 17
-#include <gui/ISurfaceTexture.h>
-#else
-#include <gui/IGraphicBufferProducer.h>
-#endif
-
-#include <ui/Fence.h>
-#include <ui/GraphicBuffer.h>
-
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-
-#include "mozilla/layers/LayersSurfaces.h"
-#include "mozilla/layers/TextureClient.h"
-
-#if ANDROID_VERSION == 17
-#define IGraphicBufferProducer ISurfaceTexture
-#endif
-
-namespace android {
-// ----------------------------------------------------------------------------
-
-#if ANDROID_VERSION == 17
-class GonkBufferQueue : public BnSurfaceTexture {
-#else
-class GonkBufferQueue : public BnGraphicBufferProducer {
-#endif
- typedef mozilla::layers::TextureClient TextureClient;
-
-public:
- enum { MIN_UNDEQUEUED_BUFFERS = 2 };
- enum { NUM_BUFFER_SLOTS = 32 };
- enum { NO_CONNECTED_API = 0 };
- enum { INVALID_BUFFER_SLOT = -1 };
- enum { STALE_BUFFER_SLOT = 1, NO_BUFFER_AVAILABLE };
-
- // When in async mode we reserve two slots in order to guarantee that the
- // producer and consumer can run asynchronously.
- enum { MAX_MAX_ACQUIRED_BUFFERS = NUM_BUFFER_SLOTS - 2 };
-
- // ConsumerListener is the interface through which the GonkBufferQueue notifies
- // the consumer of events that the consumer may wish to react to. Because
- // the consumer will generally have a mutex that is locked during calls from
- // the consumer to the GonkBufferQueue, these calls from the GonkBufferQueue to the
- // consumer *MUST* be called only when the GonkBufferQueue mutex is NOT locked.
- struct ConsumerListener : public virtual RefBase {
- // onFrameAvailable is called from queueBuffer each time an additional
- // frame becomes available for consumption. This means that frames that
- // are queued while in asynchronous mode only trigger the callback if no
- // previous frames are pending. Frames queued while in synchronous mode
- // always trigger the callback.
- //
- // This is called without any lock held and can be called concurrently
- // by multiple threads.
- virtual void onFrameAvailable() = 0;
-
- // onBuffersReleased is called to notify the buffer consumer that the
- // GonkBufferQueue has released its references to one or more GraphicBuffers
- // contained in its slots. The buffer consumer should then call
- // GonkBufferQueue::getReleasedBuffers to retrieve the list of buffers
- //
- // This is called without any lock held and can be called concurrently
- // by multiple threads.
- virtual void onBuffersReleased() = 0;
- };
-
- // ProxyConsumerListener is a ConsumerListener implementation that keeps a weak
- // reference to the actual consumer object. It forwards all calls to that
- // consumer object so long as it exists.
- //
- // This class exists to avoid having a circular reference between the
- // GonkBufferQueue object and the consumer object. The reason this can't be a weak
- // reference in the GonkBufferQueue class is because we're planning to expose the
- // consumer side of a GonkBufferQueue as a binder interface, which doesn't support
- // weak references.
- class ProxyConsumerListener : public GonkBufferQueue::ConsumerListener {
- public:
-
- ProxyConsumerListener(const wp<GonkBufferQueue::ConsumerListener>& consumerListener);
- virtual ~ProxyConsumerListener();
- virtual void onFrameAvailable();
- virtual void onBuffersReleased();
-
- private:
-
- // mConsumerListener is a weak reference to the ConsumerListener. This is
- // the raison d'etre of ProxyConsumerListener.
- wp<GonkBufferQueue::ConsumerListener> mConsumerListener;
- };
-
-
- // GonkBufferQueue manages a pool of gralloc memory slots to be used by
- // producers and consumers. allowSynchronousMode specifies whether or not
- // synchronous mode can be enabled by the producer. allocator is used to
- // allocate all the needed gralloc buffers.
- GonkBufferQueue(bool allowSynchronousMode = true,
- const sp<IGraphicBufferAlloc>& allocator = NULL);
- virtual ~GonkBufferQueue();
-
- // Query native window attributes. The "what" values are enumerated in
- // window.h (e.g. NATIVE_WINDOW_FORMAT).
- virtual int query(int what, int* value);
-
- // setBufferCount updates the number of available buffer slots. If this
- // method succeeds, buffer slots will be both unallocated and owned by
- // the GonkBufferQueue object (i.e. they are not owned by the producer or
- // consumer).
- //
- // This will fail if the producer has dequeued any buffers, or if
- // bufferCount is invalid. bufferCount must generally be a value
- // between the minimum undequeued buffer count and NUM_BUFFER_SLOTS
- // (inclusive). It may also be set to zero (the default) to indicate
- // that the producer does not wish to set a value. The minimum value
- // can be obtained by calling query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
- // ...).
- //
- // This may only be called by the producer. The consumer will be told
- // to discard buffers through the onBuffersReleased callback.
- virtual status_t setBufferCount(int bufferCount);
-
- // requestBuffer returns the GraphicBuffer for slot N.
- //
- // In normal operation, this is called the first time slot N is returned
- // by dequeueBuffer. It must be called again if dequeueBuffer returns
- // flags indicating that previously-returned buffers are no longer valid.
- virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
-
- // dequeueBuffer gets the next buffer slot index for the producer to use.
- // If a buffer slot is available then that slot index is written to the
- // location pointed to by the buf argument and a status of OK is returned.
- // If no slot is available then a status of -EBUSY is returned and buf is
- // unmodified.
- //
- // The fence parameter will be updated to hold the fence associated with
- // the buffer. The contents of the buffer must not be overwritten until the
- // fence signals. If the fence is Fence::NO_FENCE, the buffer may be
- // written immediately.
- //
- // The width and height parameters must be no greater than the minimum of
- // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
- // An error due to invalid dimensions might not be reported until
- // updateTexImage() is called. If width and height are both zero, the
- // default values specified by setDefaultBufferSize() are used instead.
- //
- // The pixel formats are enumerated in graphics.h, e.g.
- // HAL_PIXEL_FORMAT_RGBA_8888. If the format is 0, the default format
- // will be used.
- //
- // The usage argument specifies gralloc buffer usage flags. The values
- // are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER. These
- // will be merged with the usage flags specified by setConsumerUsageBits.
- //
- // The return value may be a negative error value or a non-negative
- // collection of flags. If the flags are set, the return values are
- // valid, but additional actions must be performed.
- //
- // If IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION is set, the
- // producer must discard cached GraphicBuffer references for the slot
- // returned in buf.
- // If IGraphicBufferProducer::RELEASE_ALL_BUFFERS is set, the producer
- // must discard cached GraphicBuffer references for all slots.
- //
- // In both cases, the producer will need to call requestBuffer to get a
- // GraphicBuffer handle for the returned slot.
-#if ANDROID_VERSION == 17
- virtual status_t dequeueBuffer(int *buf, sp<Fence>& fence,
- uint32_t width, uint32_t height, uint32_t format, uint32_t usage) {
- return dequeueBuffer(buf, &fence, width, height, format, usage);
- }
-#endif
-
- virtual status_t dequeueBuffer(int *buf, sp<Fence>* fence,
- uint32_t width, uint32_t height, uint32_t format, uint32_t usage);
-
- // queueBuffer returns a filled buffer to the GonkBufferQueue.
- //
- // Additional data is provided in the QueueBufferInput struct. Notably,
- // a timestamp must be provided for the buffer. The timestamp is in
- // nanoseconds, and must be monotonically increasing. Its other semantics
- // (zero point, etc) are producer-specific and should be documented by the
- // producer.
- //
- // The caller may provide a fence that signals when all rendering
- // operations have completed. Alternatively, NO_FENCE may be used,
- // indicating that the buffer is ready immediately.
- //
- // Some values are returned in the output struct: the current settings
- // for default width and height, the current transform hint, and the
- // number of queued buffers.
- virtual status_t queueBuffer(int buf,
- const QueueBufferInput& input, QueueBufferOutput* output);
-
- // cancelBuffer returns a dequeued buffer to the GonkBufferQueue, but doesn't
- // queue it for use by the consumer.
- //
- // The buffer will not be overwritten until the fence signals. The fence
- // will usually be the one obtained from dequeueBuffer.
-#if ANDROID_VERSION == 17
- virtual void cancelBuffer(int buf, sp<Fence> fence);
-#else
- virtual void cancelBuffer(int buf, const sp<Fence>& fence);
-#endif
-
- // setSynchronousMode sets whether dequeueBuffer is synchronous or
- // asynchronous. In synchronous mode, dequeueBuffer blocks until
- // a buffer is available, the currently bound buffer can be dequeued and
- // queued buffers will be acquired in order. In asynchronous mode,
- // a queued buffer may be replaced by a subsequently queued buffer.
- //
- // The default mode is synchronous.
- // This should be called only during initialization.
- virtual status_t setSynchronousMode(bool enabled);
-
- // connect attempts to connect a producer API to the GonkBufferQueue. This
- // must be called before any other IGraphicBufferProducer methods are
- // called except for getAllocator. A consumer must already be connected.
- //
- // This method will fail if connect was previously called on the
- // GonkBufferQueue and no corresponding disconnect call was made (i.e. if
- // it's still connected to a producer).
- //
- // APIs are enumerated in window.h (e.g. NATIVE_WINDOW_API_CPU).
- virtual status_t connect(int api, QueueBufferOutput* output);
-
- // disconnect attempts to disconnect a producer API from the GonkBufferQueue.
- // Calling this method will cause any subsequent calls to other
- // IGraphicBufferProducer methods to fail except for getAllocator and connect.
- // Successfully calling connect after this will allow the other methods to
- // succeed again.
- //
- // This method will fail if the the GonkBufferQueue is not currently
- // connected to the specified producer API.
- virtual status_t disconnect(int api);
-
- // dump our state in a String
- virtual void dumpToString(String8& result) const;
- virtual void dumpToString(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
-
- // public facing structure for BufferSlot
- struct BufferItem {
-
- BufferItem()
- :
- mTransform(0),
- mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
- mTimestamp(0),
- mFrameNumber(0),
- mBuf(INVALID_BUFFER_SLOT) {
- mCrop.makeInvalid();
- }
- // mGraphicBuffer points to the buffer allocated for this slot, or is NULL
- // if the buffer in this slot has been acquired in the past (see
- // BufferSlot.mAcquireCalled).
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mCrop is the current crop rectangle for this buffer slot.
- Rect mCrop;
-
- // mTransform is the current transform flags for this buffer slot.
- uint32_t mTransform;
-
- // mScalingMode is the current scaling mode for this buffer slot.
- uint32_t mScalingMode;
-
- // mTimestamp is the current timestamp for this buffer slot. This gets
- // to set by queueBuffer each time this slot is queued.
- int64_t mTimestamp;
-
- // mFrameNumber is the number of the queued frame for this slot.
- uint64_t mFrameNumber;
-
- // mBuf is the slot index of this buffer
- int mBuf;
-
- // mFence is a fence that will signal when the buffer is idle.
- sp<Fence> mFence;
- };
-
- // The following public functions are the consumer-facing interface
-
- // acquireBuffer attempts to acquire ownership of the next pending buffer in
- // the GonkBufferQueue. If no buffer is pending then it returns -EINVAL. If a
- // buffer is successfully acquired, the information about the buffer is
- // returned in BufferItem. If the buffer returned had previously been
- // acquired then the BufferItem::mGraphicBuffer field of buffer is set to
- // NULL and it is assumed that the consumer still holds a reference to the
- // buffer.
- status_t acquireBuffer(BufferItem *buffer);
-
- // releaseBuffer releases a buffer slot from the consumer back to the
- // GonkBufferQueue. This may be done while the buffer's contents are still
- // being accessed. The fence will signal when the buffer is no longer
- // in use.
- //
- // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
- // any references to the just-released buffer that it might have, as if it
- // had received a onBuffersReleased() call with a mask set for the released
- // buffer.
- //
- // Note that the dependencies on EGL will be removed once we switch to using
- // the Android HW Sync HAL.
- status_t releaseBuffer(int buf, const sp<Fence>& releaseFence);
-
- // consumerConnect connects a consumer to the GonkBufferQueue. Only one
- // consumer may be connected, and when that consumer disconnects the
- // GonkBufferQueue is placed into the "abandoned" state, causing most
- // interactions with the GonkBufferQueue by the producer to fail.
- //
- // consumer may not be NULL.
- status_t consumerConnect(const sp<ConsumerListener>& consumer);
-
- // consumerDisconnect disconnects a consumer from the GonkBufferQueue. All
- // buffers will be freed and the GonkBufferQueue is placed in the "abandoned"
- // state, causing most interactions with the GonkBufferQueue by the producer to
- // fail.
- status_t consumerDisconnect();
-
- // getReleasedBuffers sets the value pointed to by slotMask to a bit mask
- // indicating which buffer slots have been released by the GonkBufferQueue
- // but have not yet been released by the consumer.
- //
- // This should be called from the onBuffersReleased() callback.
- status_t getReleasedBuffers(uint32_t* slotMask);
-
- // setDefaultBufferSize is used to set the size of buffers returned by
- // dequeueBuffer when a width and height of zero is requested. Default
- // is 1x1.
- status_t setDefaultBufferSize(uint32_t w, uint32_t h);
-
- // setDefaultMaxBufferCount sets the default value for the maximum buffer
- // count (the initial default is 2). If the producer has requested a
- // buffer count using setBufferCount, the default buffer count will only
- // take effect if the producer sets the count back to zero.
- //
- // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
- status_t setDefaultMaxBufferCount(int bufferCount);
-
- // setMaxAcquiredBufferCount sets the maximum number of buffers that can
- // be acquired by the consumer at one time (default 1). This call will
- // fail if a producer is connected to the GonkBufferQueue.
- status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
-
- // isSynchronousMode returns whether the GonkBufferQueue is currently in
- // synchronous mode.
- bool isSynchronousMode() const;
-
- // setConsumerName sets the name used in logging
- void setConsumerName(const String8& name);
-
- // setDefaultBufferFormat allows the GonkBufferQueue to create
- // GraphicBuffers of a defaultFormat if no format is specified
- // in dequeueBuffer. Formats are enumerated in graphics.h; the
- // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
- status_t setDefaultBufferFormat(uint32_t defaultFormat);
-
- // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
- // These are merged with the bits passed to dequeueBuffer. The values are
- // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
- status_t setConsumerUsageBits(uint32_t usage);
-
- // setTransformHint bakes in rotation to buffers so overlays can be used.
- // The values are enumerated in window.h, e.g.
- // NATIVE_WINDOW_TRANSFORM_ROT_90. The default is 0 (no transform).
- status_t setTransformHint(uint32_t hint);
-
- already_AddRefed<TextureClient> getTextureClientFromBuffer(ANativeWindowBuffer* buffer);
-
- int getSlotFromTextureClientLocked(TextureClient* client) const;
-
-private:
- // freeBufferLocked frees the GraphicBuffer and sync resources for the
- // given slot.
- //void freeBufferLocked(int index);
-
- // freeAllBuffersLocked frees the GraphicBuffer and sync resources for
- // all slots.
- //void freeAllBuffersLocked();
- void freeAllBuffersLocked();
-
- // setDefaultMaxBufferCountLocked sets the maximum number of buffer slots
- // that will be used if the producer does not override the buffer slot
- // count. The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
- // The initial default is 2.
- status_t setDefaultMaxBufferCountLocked(int count);
-
- // getMinBufferCountLocked returns the minimum number of buffers allowed
- // given the current GonkBufferQueue state.
- int getMinMaxBufferCountLocked() const;
-
- // getMinUndequeuedBufferCountLocked returns the minimum number of buffers
- // that must remain in a state other than DEQUEUED.
- int getMinUndequeuedBufferCountLocked() const;
-
- // getMaxBufferCountLocked returns the maximum number of buffers that can
- // be allocated at once. This value depends upon the following member
- // variables:
- //
- // mSynchronousMode
- // mMaxAcquiredBufferCount
- // mDefaultMaxBufferCount
- // mOverrideMaxBufferCount
- //
- // Any time one of these member variables is changed while a producer is
- // connected, mDequeueCondition must be broadcast.
- int getMaxBufferCountLocked() const;
-
- struct BufferSlot {
-
- BufferSlot()
- : mBufferState(BufferSlot::FREE),
- mRequestBufferCalled(false),
- mTransform(0),
- mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
- mTimestamp(0),
- mFrameNumber(0),
- mAcquireCalled(false),
- mNeedsCleanupOnRelease(false) {
- mCrop.makeInvalid();
- }
-
- // mGraphicBuffer points to the buffer allocated for this slot or is NULL
- // if no buffer has been allocated.
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mTextureClient is a thin abstraction over remotely allocated GraphicBuffer.
- RefPtr<TextureClient> mTextureClient;
-
- // BufferState represents the different states in which a buffer slot
- // can be. All slots are initially FREE.
- enum BufferState {
- // FREE indicates that the buffer is available to be dequeued
- // by the producer. The buffer may be in use by the consumer for
- // a finite time, so the buffer must not be modified until the
- // associated fence is signaled.
- //
- // The slot is "owned" by GonkBufferQueue. It transitions to DEQUEUED
- // when dequeueBuffer is called.
- FREE = 0,
-
- // DEQUEUED indicates that the buffer has been dequeued by the
- // producer, but has not yet been queued or canceled. The
- // producer may modify the buffer's contents as soon as the
- // associated ready fence is signaled.
- //
- // The slot is "owned" by the producer. It can transition to
- // QUEUED (via queueBuffer) or back to FREE (via cancelBuffer).
- DEQUEUED = 1,
-
- // QUEUED indicates that the buffer has been filled by the
- // producer and queued for use by the consumer. The buffer
- // contents may continue to be modified for a finite time, so
- // the contents must not be accessed until the associated fence
- // is signaled.
- //
- // The slot is "owned" by GonkBufferQueue. It can transition to
- // ACQUIRED (via acquireBuffer) or to FREE (if another buffer is
- // queued in asynchronous mode).
- QUEUED = 2,
-
- // ACQUIRED indicates that the buffer has been acquired by the
- // consumer. As with QUEUED, the contents must not be accessed
- // by the consumer until the fence is signaled.
- //
- // The slot is "owned" by the consumer. It transitions to FREE
- // when releaseBuffer is called.
- ACQUIRED = 3
- };
-
- // mBufferState is the current state of this buffer slot.
- BufferState mBufferState;
-
- // mRequestBufferCalled is used for validating that the producer did
- // call requestBuffer() when told to do so. Technically this is not
- // needed but useful for debugging and catching producer bugs.
- bool mRequestBufferCalled;
-
- // mCrop is the current crop rectangle for this buffer slot.
- Rect mCrop;
-
- // mTransform is the current transform flags for this buffer slot.
- // (example: NATIVE_WINDOW_TRANSFORM_ROT_90)
- uint32_t mTransform;
-
- // mScalingMode is the current scaling mode for this buffer slot.
- // (example: NATIVE_WINDOW_SCALING_MODE_FREEZE)
- uint32_t mScalingMode;
-
- // mTimestamp is the current timestamp for this buffer slot. This gets
- // to set by queueBuffer each time this slot is queued.
- int64_t mTimestamp;
-
- // mFrameNumber is the number of the queued frame for this slot. This
- // is used to dequeue buffers in LRU order (useful because buffers
- // may be released before their release fence is signaled).
- uint64_t mFrameNumber;
-
- // mEglFence is the EGL sync object that must signal before the buffer
- // associated with this buffer slot may be dequeued. It is initialized
- // to EGL_NO_SYNC_KHR when the buffer is created and may be set to a
- // new sync object in releaseBuffer. (This is deprecated in favor of
- // mFence, below.)
- //EGLSyncKHR mEglFence;
-
- // mFence is a fence which will signal when work initiated by the
- // previous owner of the buffer is finished. When the buffer is FREE,
- // the fence indicates when the consumer has finished reading
- // from the buffer, or when the producer has finished writing if it
- // called cancelBuffer after queueing some writes. When the buffer is
- // QUEUED, it indicates when the producer has finished filling the
- // buffer. When the buffer is DEQUEUED or ACQUIRED, the fence has been
- // passed to the consumer or producer along with ownership of the
- // buffer, and mFence is set to NO_FENCE.
- sp<Fence> mFence;
-
- // Indicates whether this buffer has been seen by a consumer yet
- bool mAcquireCalled;
-
- // Indicates whether this buffer needs to be cleaned up by the
- // consumer. This is set when a buffer in ACQUIRED state is freed.
- // It causes releaseBuffer to return STALE_BUFFER_SLOT.
- bool mNeedsCleanupOnRelease;
- };
-
- // mSlots is the array of buffer slots that must be mirrored on the
- // producer side. This allows buffer ownership to be transferred between
- // the producer and consumer without sending a GraphicBuffer over binder.
- // The entire array is initialized to NULL at construction time, and
- // buffers are allocated for a slot when requestBuffer is called with
- // that slot's index.
- BufferSlot mSlots[NUM_BUFFER_SLOTS];
-
- // mDefaultWidth holds the default width of allocated buffers. It is used
- // in dequeueBuffer() if a width and height of zero is specified.
- uint32_t mDefaultWidth;
-
- // mDefaultHeight holds the default height of allocated buffers. It is used
- // in dequeueBuffer() if a width and height of zero is specified.
- uint32_t mDefaultHeight;
-
- // mMaxAcquiredBufferCount is the number of buffers that the consumer may
- // acquire at one time. It defaults to 1 and can be changed by the
- // consumer via the setMaxAcquiredBufferCount method, but this may only be
- // done when no producer is connected to the GonkBufferQueue.
- //
- // This value is used to derive the value returned for the
- // MIN_UNDEQUEUED_BUFFERS query by the producer.
- int mMaxAcquiredBufferCount;
-
- // mDefaultMaxBufferCount is the default limit on the number of buffers
- // that will be allocated at one time. This default limit is set by the
- // consumer. The limit (as opposed to the default limit) may be
- // overridden by the producer.
- int mDefaultMaxBufferCount;
-
- // mOverrideMaxBufferCount is the limit on the number of buffers that will
- // be allocated at one time. This value is set by the image producer by
- // calling setBufferCount. The default is zero, which means the producer
- // doesn't care about the number of buffers in the pool. In that case
- // mDefaultMaxBufferCount is used as the limit.
- int mOverrideMaxBufferCount;
-
- // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to
- // allocate new GraphicBuffer objects.
- sp<IGraphicBufferAlloc> mGraphicBufferAlloc;
-
- // mConsumerListener is used to notify the connected consumer of
- // asynchronous events that it may wish to react to. It is initially set
- // to NULL and is written by consumerConnect and consumerDisconnect.
- sp<ConsumerListener> mConsumerListener;
-
- // mSynchronousMode whether we're in synchronous mode or not
- bool mSynchronousMode;
-
- // mAllowSynchronousMode whether we allow synchronous mode or not. Set
- // when the GonkBufferQueue is created (by the consumer).
- const bool mAllowSynchronousMode;
-
- // mConnectedApi indicates the producer API that is currently connected
- // to this GonkBufferQueue. It defaults to NO_CONNECTED_API (= 0), and gets
- // updated by the connect and disconnect methods.
- int mConnectedApi;
-
- // mDequeueCondition condition used for dequeueBuffer in synchronous mode
- mutable Condition mDequeueCondition;
-
- // mQueue is a FIFO of queued buffers used in synchronous mode
- typedef Vector<int> Fifo;
- Fifo mQueue;
-
- // mAbandoned indicates that the GonkBufferQueue will no longer be used to
- // consume image buffers pushed to it using the IGraphicBufferProducer
- // interface. It is initialized to false, and set to true in the
- // consumerDisconnect method. A GonkBufferQueue that has been abandoned will
- // return the NO_INIT error from all IGraphicBufferProducer methods
- // capable of returning an error.
- bool mAbandoned;
-
- // mConsumerName is a string used to identify the GonkBufferQueue in log
- // messages. It is set by the setConsumerName method.
- String8 mConsumerName;
-
- // mMutex is the mutex used to prevent concurrent access to the member
- // variables of GonkBufferQueue objects. It must be locked whenever the
- // member variables are accessed.
- mutable Mutex mMutex;
-
- // mFrameCounter is the free running counter, incremented on every
- // successful queueBuffer call.
- uint64_t mFrameCounter;
-
- // mBufferHasBeenQueued is true once a buffer has been queued. It is
- // reset when something causes all buffers to be freed (e.g. changing the
- // buffer count).
- bool mBufferHasBeenQueued;
-
- // mDefaultBufferFormat can be set so it will override
- // the buffer format when it isn't specified in dequeueBuffer
- uint32_t mDefaultBufferFormat;
-
- // mConsumerUsageBits contains flags the consumer wants for GraphicBuffers
- uint32_t mConsumerUsageBits;
-
- // mTransformHint is used to optimize for screen rotations
- uint32_t mTransformHint;
-
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_GUI_BUFFERQUEUE_H
diff --git a/widget/gonk/nativewindow/GonkBufferQueueKK.cpp b/widget/gonk/nativewindow/GonkBufferQueueKK.cpp
deleted file mode 100644
index 0c5cdfeb9..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueKK.cpp
+++ /dev/null
@@ -1,1265 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "GonkBufferQueue"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-//#define LOG_NDEBUG 0
-
-#define GL_GLEXT_PROTOTYPES
-#define EGL_EGLEXT_PROTOTYPES
-
-#include <utils/Log.h>
-#include <utils/Trace.h>
-#include <utils/CallStack.h>
-#include <cutils/compiler.h>
-
-#include "mozilla/layers/GrallocTextureClient.h"
-#include "mozilla/layers/ImageBridgeChild.h"
-#include "GonkBufferQueueKK.h"
-
-#define ATRACE_BUFFER_INDEX(index)
-
-using namespace mozilla;
-using namespace mozilla::gfx;
-using namespace mozilla::layers;
-
-namespace android {
-
-// Get an ID that's unique within this process.
-static int32_t createProcessUniqueId() {
- static volatile int32_t globalCounter = 0;
- return android_atomic_inc(&globalCounter);
-}
-
-static const char* scalingModeName(int scalingMode) {
- switch (scalingMode) {
- case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE";
- case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW";
- case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP";
- default: return "Unknown";
- }
-}
-
-GonkBufferQueue::GonkBufferQueue(bool allowSynchronousMode,
- const sp<IGraphicBufferAlloc>& allocator) :
- mDefaultWidth(1),
- mDefaultHeight(1),
- mMaxAcquiredBufferCount(1),
- mDefaultMaxBufferCount(2),
- mOverrideMaxBufferCount(0),
- mSynchronousMode(true),
- mConsumerControlledByApp(false),
- mDequeueBufferCannotBlock(false),
- mUseAsyncBuffer(true),
- mConnectedApi(NO_CONNECTED_API),
- mAbandoned(false),
- mFrameCounter(0),
- mBufferHasBeenQueued(false),
- mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),
- mConsumerUsageBits(0),
- mTransformHint(0)
-{
- // Choose a name using the PID and a process-unique ID.
- mConsumerName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
-
- ALOGV("GonkBufferQueue");
-}
-
-GonkBufferQueue::~GonkBufferQueue() {
- ALOGV("~GonkBufferQueue");
-}
-
-status_t GonkBufferQueue::setDefaultMaxBufferCountLocked(int count) {
- if (count < 2 || count > NUM_BUFFER_SLOTS)
- return BAD_VALUE;
-
- mDefaultMaxBufferCount = count;
- mDequeueCondition.broadcast();
-
- return NO_ERROR;
-}
-
-void GonkBufferQueue::setConsumerName(const String8& name) {
- Mutex::Autolock lock(mMutex);
- mConsumerName = name;
-}
-
-status_t GonkBufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) {
- Mutex::Autolock lock(mMutex);
- mDefaultBufferFormat = defaultFormat;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setConsumerUsageBits(uint32_t usage) {
- Mutex::Autolock lock(mMutex);
- mConsumerUsageBits = usage;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setTransformHint(uint32_t hint) {
- ALOGV("setTransformHint: %02x", hint);
- Mutex::Autolock lock(mMutex);
- mTransformHint = hint;
- return NO_ERROR;
-}
-
-already_AddRefed<TextureClient>
-GonkBufferQueue::getTextureClientFromBuffer(ANativeWindowBuffer* buffer)
-{
- Mutex::Autolock _l(mMutex);
- if (buffer == NULL) {
- ALOGE("getSlotFromBufferLocked: encountered NULL buffer");
- return nullptr;
- }
-
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mGraphicBuffer != NULL && mSlots[i].mGraphicBuffer->handle == buffer->handle) {
- RefPtr<TextureClient> client(mSlots[i].mTextureClient);
- return client.forget();
- }
- }
- ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
- return nullptr;
-}
-
-int GonkBufferQueue::getSlotFromTextureClientLocked(
- TextureClient* client) const
-{
- if (client == NULL) {
- ALOGE("getSlotFromBufferLocked: encountered NULL buffer");
- return BAD_VALUE;
- }
-
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mTextureClient == client) {
- return i;
- }
- }
- ALOGE("getSlotFromBufferLocked: unknown TextureClient: %p", client);
- return BAD_VALUE;
-}
-
-status_t GonkBufferQueue::setBufferCount(int bufferCount) {
- ALOGV("setBufferCount: count=%d", bufferCount);
-
- sp<IConsumerListener> listener;
- {
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ALOGE("setBufferCount: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
- if (bufferCount > NUM_BUFFER_SLOTS) {
- ALOGE("setBufferCount: bufferCount too large (max %d)",
- NUM_BUFFER_SLOTS);
- return BAD_VALUE;
- }
-
- // Error out if the user has dequeued buffers
- for (int i=0 ; i<NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mBufferState == BufferSlot::DEQUEUED) {
- ALOGE("setBufferCount: client owns some buffers");
- return -EINVAL;
- }
- }
-
- if (bufferCount == 0) {
- mOverrideMaxBufferCount = 0;
- mDequeueCondition.broadcast();
- return NO_ERROR;
- }
-
- // fine to assume async to false before we're setting the buffer count
- const int minBufferSlots = getMinMaxBufferCountLocked(false);
- if (bufferCount < minBufferSlots) {
- ALOGE("setBufferCount: requested buffer count (%d) is less than "
- "minimum (%d)", bufferCount, minBufferSlots);
- return BAD_VALUE;
- }
-
- // here we're guaranteed that the client doesn't have dequeued buffers
- // and will release all of its buffer references. We don't clear the
- // queue, however, so currently queued buffers still get displayed.
- // XXX: Should this use drainQueueAndFreeBuffersLocked instead?
- freeAllBuffersLocked();
- mOverrideMaxBufferCount = bufferCount;
- mDequeueCondition.broadcast();
- listener = mConsumerListener;
- } // scope for lock
-
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-
- return NO_ERROR;
-}
-
-int GonkBufferQueue::query(int what, int* outValue)
-{
- ATRACE_CALL();
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ALOGE("query: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- int value;
- switch (what) {
- case NATIVE_WINDOW_WIDTH:
- value = mDefaultWidth;
- break;
- case NATIVE_WINDOW_HEIGHT:
- value = mDefaultHeight;
- break;
- case NATIVE_WINDOW_FORMAT:
- value = mDefaultBufferFormat;
- break;
- case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
- value = getMinUndequeuedBufferCount(false);
- break;
- case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
- value = (mQueue.size() >= 2);
- break;
- case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
- value = mConsumerUsageBits;
- break;
- default:
- return BAD_VALUE;
- }
- outValue[0] = value;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
- ATRACE_CALL();
- ALOGV("requestBuffer: slot=%d", slot);
- Mutex::Autolock lock(mMutex);
- if (mAbandoned) {
- ALOGE("requestBuffer: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
- if (slot < 0 || slot >= NUM_BUFFER_SLOTS) {
- ALOGE("requestBuffer: slot index out of range [0, %d]: %d",
- NUM_BUFFER_SLOTS, slot);
- return BAD_VALUE;
- } else if (mSlots[slot].mBufferState != BufferSlot::DEQUEUED) {
- ALOGE("requestBuffer: slot %d is not owned by the client (state=%d)",
- slot, mSlots[slot].mBufferState);
- return BAD_VALUE;
- }
- mSlots[slot].mRequestBufferCalled = true;
- *buf = mSlots[slot].mGraphicBuffer;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::dequeueBuffer(int *outBuf, sp<Fence>* outFence, bool async,
- uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
- ATRACE_CALL();
- ALOGV("dequeueBuffer: w=%d h=%d fmt=%#x usage=%#x", w, h, format, usage);
-
- if ((w && !h) || (!w && h)) {
- ALOGE("dequeueBuffer: invalid size: w=%u, h=%u", w, h);
- return BAD_VALUE;
- }
-
- status_t returnFlags(OK);
- int buf = INVALID_BUFFER_SLOT;
-
- { // Scope for the lock
- Mutex::Autolock lock(mMutex);
-
- if (format == 0) {
- format = mDefaultBufferFormat;
- }
- // turn on usage bits the consumer requested
- usage |= mConsumerUsageBits;
-
- int found = -1;
- bool tryAgain = true;
- while (tryAgain) {
- if (mAbandoned) {
- ALOGE("dequeueBuffer: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- const int maxBufferCount = getMaxBufferCountLocked(async);
- if (async && mOverrideMaxBufferCount) {
- // FIXME: some drivers are manually setting the buffer-count (which they
- // shouldn't), so we do this extra test here to handle that case.
- // This is TEMPORARY, until we get this fixed.
- if (mOverrideMaxBufferCount < maxBufferCount) {
- ALOGE("dequeueBuffer: async mode is invalid with buffercount override");
- return BAD_VALUE;
- }
- }
-
- // Free up any buffers that are in slots beyond the max buffer
- // count.
- //for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
- // assert(mSlots[i].mBufferState == BufferSlot::FREE);
- // if (mSlots[i].mGraphicBuffer != NULL) {
- // freeBufferLocked(i);
- // returnFlags |= IGraphicBufferProducer::RELEASE_ALL_BUFFERS;
- // }
- //}
-
- // look for a free buffer to give to the client
- found = INVALID_BUFFER_SLOT;
- int dequeuedCount = 0;
- int acquiredCount = 0;
- for (int i = 0; i < maxBufferCount; i++) {
- const int state = mSlots[i].mBufferState;
- switch (state) {
- case BufferSlot::DEQUEUED:
- dequeuedCount++;
- break;
- case BufferSlot::ACQUIRED:
- acquiredCount++;
- break;
- case BufferSlot::FREE:
- /* We return the oldest of the free buffers to avoid
- * stalling the producer if possible. This is because
- * the consumer may still have pending reads of the
- * buffers in flight.
- */
- if ((found < 0) ||
- mSlots[i].mFrameNumber < mSlots[found].mFrameNumber) {
- found = i;
- }
- break;
- }
- }
-
- // clients are not allowed to dequeue more than one buffer
- // if they didn't set a buffer count.
- if (!mOverrideMaxBufferCount && dequeuedCount) {
- ALOGE("dequeueBuffer: can't dequeue multiple buffers without "
- "setting the buffer count");
- return -EINVAL;
- }
-
- // See whether a buffer has been queued since the last
- // setBufferCount so we know whether to perform the min undequeued
- // buffers check below.
- if (mBufferHasBeenQueued) {
- // make sure the client is not trying to dequeue more buffers
- // than allowed.
- const int newUndequeuedCount = maxBufferCount - (dequeuedCount+1);
- const int minUndequeuedCount = getMinUndequeuedBufferCount(async);
- if (newUndequeuedCount < minUndequeuedCount) {
- ALOGE("dequeueBuffer: min undequeued buffer count (%d) "
- "exceeded (dequeued=%d undequeudCount=%d)",
- minUndequeuedCount, dequeuedCount,
- newUndequeuedCount);
- return -EBUSY;
- }
- }
-
- // If no buffer is found, wait for a buffer to be released or for
- // the max buffer count to change.
- tryAgain = found == INVALID_BUFFER_SLOT;
- if (tryAgain) {
- // return an error if we're in "cannot block" mode (producer and consumer
- // are controlled by the application) -- however, the consumer is allowed
- // to acquire briefly an extra buffer (which could cause us to have to wait here)
- // and that's okay because we know the wait will be brief (it happens
- // if we dequeue a buffer while the consumer has acquired one but not released
- // the old one yet -- for e.g.: see GLConsumer::updateTexImage()).
- if (mDequeueBufferCannotBlock && (acquiredCount <= mMaxAcquiredBufferCount)) {
- ALOGE("dequeueBuffer: would block! returning an error instead.");
- return WOULD_BLOCK;
- }
- mDequeueCondition.wait(mMutex);
- }
- }
-
-
- if (found == INVALID_BUFFER_SLOT) {
- // This should not happen.
- ALOGE("dequeueBuffer: no available buffer slots");
- return -EBUSY;
- }
-
- buf = found;
- *outBuf = found;
-
- const bool useDefaultSize = !w && !h;
- if (useDefaultSize) {
- // use the default size
- w = mDefaultWidth;
- h = mDefaultHeight;
- }
-
- mSlots[buf].mBufferState = BufferSlot::DEQUEUED;
-
- const sp<GraphicBuffer>& buffer(mSlots[buf].mGraphicBuffer);
- if ((buffer == NULL) ||
- (uint32_t(buffer->width) != w) ||
- (uint32_t(buffer->height) != h) ||
- (uint32_t(buffer->format) != format) ||
- ((uint32_t(buffer->usage) & usage) != usage))
- {
- mSlots[buf].mAcquireCalled = false;
- mSlots[buf].mGraphicBuffer = NULL;
- mSlots[buf].mRequestBufferCalled = false;
- mSlots[buf].mFence = Fence::NO_FENCE;
- if (mSlots[buf].mTextureClient) {
- mSlots[buf].mTextureClient->ClearRecycleCallback();
- // release TextureClient in ImageBridge thread
- RefPtr<TextureClientReleaseTask> task =
- MakeAndAddRef<TextureClientReleaseTask>(mSlots[buf].mTextureClient);
- mSlots[buf].mTextureClient = NULL;
- ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget());
- }
- returnFlags |= IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION;
- }
-
-
- if (CC_UNLIKELY(mSlots[buf].mFence == NULL)) {
- ALOGE("dequeueBuffer: about to return a NULL fence from mSlot. "
- "buf=%d, w=%d, h=%d, format=%d",
- buf, buffer->width, buffer->height, buffer->format);
- }
- *outFence = mSlots[buf].mFence;
- mSlots[buf].mFence = Fence::NO_FENCE;
- } // end lock scope
-
- if (returnFlags & IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION) {
-
- RefPtr<LayersIPCChannel> allocator = ImageBridgeChild::GetSingleton();
- usage |= GraphicBuffer::USAGE_HW_TEXTURE;
- GrallocTextureData* texData = GrallocTextureData::Create(IntSize(w, h), format,
- gfx::BackendType::NONE, usage,
- allocator);
- if (!texData) {
- return -ENOMEM;
- }
-
- RefPtr<TextureClient> textureClient = new TextureClient(texData, TextureFlags::RECYCLE | TextureFlags::DEALLOCATE_CLIENT, allocator);
-
- { // Scope for the lock
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ALOGE("dequeueBuffer: SurfaceTexture has been abandoned!");
- return NO_INIT;
- }
-
- mSlots[buf].mGraphicBuffer = texData->GetGraphicBuffer();
- mSlots[buf].mTextureClient = textureClient;
- ALOGD("dequeueBuffer: returning slot=%d buf=%p ", buf,
- mSlots[buf].mGraphicBuffer->handle);
-
- }
-
- }
-
- ALOGV("dequeueBuffer: returning slot=%d/%llu buf=%p flags=%#x", *outBuf,
- mSlots[*outBuf].mFrameNumber,
- mSlots[*outBuf].mGraphicBuffer->handle, returnFlags);
-
- return returnFlags;
-}
-
-status_t GonkBufferQueue::setSynchronousMode(bool enabled) {
- ALOGV("setSynchronousMode: enabled=%d", enabled);
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ALOGE("setSynchronousMode: BufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- if (mSynchronousMode != enabled) {
- mSynchronousMode = enabled;
- mDequeueCondition.broadcast();
- }
- return OK;
-}
-
-status_t GonkBufferQueue::queueBuffer(int buf,
- const QueueBufferInput& input, QueueBufferOutput* output) {
- ATRACE_CALL();
-
- Rect crop;
- uint32_t transform;
- int scalingMode;
- int64_t timestamp;
- bool isAutoTimestamp;
- bool async;
- sp<Fence> fence;
-
- input.deflate(&timestamp, &isAutoTimestamp, &crop, &scalingMode, &transform,
- &async, &fence);
-
- if (fence == NULL) {
- ALOGE("queueBuffer: fence is NULL");
- return BAD_VALUE;
- }
-
- ALOGV("queueBuffer: slot=%d time=%#llx crop=[%d,%d,%d,%d] tr=%#x "
- "scale=%s",
- buf, timestamp, crop.left, crop.top, crop.right, crop.bottom,
- transform, scalingModeName(scalingMode));
-
- switch (scalingMode) {
- case NATIVE_WINDOW_SCALING_MODE_FREEZE:
- case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
- case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
- case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
- break;
- default:
- ALOGE("unknown scaling mode: %d", scalingMode);
- return -EINVAL;
- }
-
- sp<IConsumerListener> listener;
-
- { // scope for the lock
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ALOGE("queueBuffer: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- const int maxBufferCount = getMaxBufferCountLocked(async);
- if (async && mOverrideMaxBufferCount) {
- // FIXME: some drivers are manually setting the buffer-count (which they
- // shouldn't), so we do this extra test here to handle that case.
- // This is TEMPORARY, until we get this fixed.
- if (mOverrideMaxBufferCount < maxBufferCount) {
- ALOGE("queueBuffer: async mode is invalid with buffercount override");
- return BAD_VALUE;
- }
- }
- if (buf < 0 || buf >= maxBufferCount) {
- ALOGE("queueBuffer: slot index out of range [0, %d]: %d",
- maxBufferCount, buf);
- return -EINVAL;
- } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
- ALOGE("queueBuffer: slot %d is not owned by the client "
- "(state=%d)", buf, mSlots[buf].mBufferState);
- return -EINVAL;
- } else if (!mSlots[buf].mRequestBufferCalled) {
- ALOGE("queueBuffer: slot %d was enqueued without requesting a "
- "buffer", buf);
- return -EINVAL;
- }
-
- ALOGV("queueBuffer: slot=%d/%llu time=%#llx crop=[%d,%d,%d,%d] "
- "tr=%#x scale=%s",
- buf, mFrameCounter + 1, timestamp,
- crop.left, crop.top, crop.right, crop.bottom,
- transform, scalingModeName(scalingMode));
-
- const sp<GraphicBuffer>& graphicBuffer(mSlots[buf].mGraphicBuffer);
- Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
- Rect croppedCrop;
- crop.intersect(bufferRect, &croppedCrop);
- if (croppedCrop != crop) {
- ALOGE("queueBuffer: crop rect is not contained within the "
- "buffer in slot %d", buf);
- return -EINVAL;
- }
-
- mSlots[buf].mFence = fence;
- mSlots[buf].mBufferState = BufferSlot::QUEUED;
- mFrameCounter++;
- mSlots[buf].mFrameNumber = mFrameCounter;
-
- BufferItem item;
- item.mAcquireCalled = mSlots[buf].mAcquireCalled;
- item.mGraphicBuffer = mSlots[buf].mGraphicBuffer;
- item.mCrop = crop;
- item.mTransform = transform & ~NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
- item.mTransformToDisplayInverse = bool(transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
- item.mScalingMode = scalingMode;
- item.mTimestamp = timestamp;
- item.mIsAutoTimestamp = isAutoTimestamp;
- item.mFrameNumber = mFrameCounter;
- item.mBuf = buf;
- item.mFence = fence;
- item.mIsDroppable = mDequeueBufferCannotBlock || async;
-
- if (mQueue.empty()) {
- // when the queue is empty, we can ignore "mDequeueBufferCannotBlock", and
- // simply queue this buffer.
- mQueue.push_back(item);
- } else {
- // when the queue is not empty, we need to look at the front buffer
- // state and see if we need to replace it.
- Fifo::iterator front(mQueue.begin());
- if (front->mIsDroppable || !mSynchronousMode) {
- // buffer slot currently queued is marked free if still tracked
- if (stillTracking(front)) {
- mSlots[front->mBuf].mBufferState = BufferSlot::FREE;
- // reset the frame number of the freed buffer so that it is the first in
- // line to be dequeued again.
- mSlots[front->mBuf].mFrameNumber = 0;
- }
- // and we record the new buffer in the queued list
- *front = item;
- } else {
- mQueue.push_back(item);
- }
- }
- // always signals that an additional frame should be consumed
- // to handle max acquired buffer count reached case.
- listener = mConsumerListener;
-
- mBufferHasBeenQueued = true;
- mDequeueCondition.broadcast();
-
- output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint,
- mQueue.size());
-
- } // scope for the lock
-
- // call back without lock held
- if (listener != 0) {
- listener->onFrameAvailable();
- }
- return NO_ERROR;
-}
-
-void GonkBufferQueue::cancelBuffer(int buf, const sp<Fence>& fence) {
- ATRACE_CALL();
- ALOGV("cancelBuffer: slot=%d", buf);
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ALOGW("cancelBuffer: GonkBufferQueue has been abandoned!");
- return;
- }
-
- if (buf < 0 || buf >= NUM_BUFFER_SLOTS) {
- ALOGE("cancelBuffer: slot index out of range [0, %d]: %d",
- NUM_BUFFER_SLOTS, buf);
- return;
- } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
- ALOGE("cancelBuffer: slot %d is not owned by the client (state=%d)",
- buf, mSlots[buf].mBufferState);
- return;
- } else if (fence == NULL) {
- ALOGE("cancelBuffer: fence is NULL");
- return;
- }
- mSlots[buf].mBufferState = BufferSlot::FREE;
- mSlots[buf].mFrameNumber = 0;
- mSlots[buf].mFence = fence;
- mDequeueCondition.broadcast();
-}
-
-
-status_t GonkBufferQueue::connect(const sp<IBinder>& token,
- int api, bool producerControlledByApp, QueueBufferOutput* output) {
- ATRACE_CALL();
- ALOGV("connect: api=%d producerControlledByApp=%s", api,
- producerControlledByApp ? "true" : "false");
- Mutex::Autolock lock(mMutex);
-
-retry:
- if (mAbandoned) {
- ALOGE("connect: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- if (mConsumerListener == NULL) {
- ALOGE("connect: GonkBufferQueue has no consumer!");
- return NO_INIT;
- }
-
- if (mConnectedApi != NO_CONNECTED_API) {
- ALOGE("connect: already connected (cur=%d, req=%d)",
- mConnectedApi, api);
- return -EINVAL;
- }
-
- // If we disconnect and reconnect quickly, we can be in a state where our slots are
- // empty but we have many buffers in the queue. This can cause us to run out of
- // memory if we outrun the consumer. Wait here if it looks like we have too many
- // buffers queued up.
- int maxBufferCount = getMaxBufferCountLocked(false); // worst-case, i.e. largest value
- if (mQueue.size() > (size_t) maxBufferCount) {
- // TODO: make this bound tighter?
- ALOGV("queue size is %d, waiting", mQueue.size());
- mDequeueCondition.wait(mMutex);
- goto retry;
- }
-
- int err = NO_ERROR;
- switch (api) {
- case NATIVE_WINDOW_API_EGL:
- case NATIVE_WINDOW_API_CPU:
- case NATIVE_WINDOW_API_MEDIA:
- case NATIVE_WINDOW_API_CAMERA:
- mConnectedApi = api;
- output->inflate(mDefaultWidth, mDefaultHeight, mTransformHint, mQueue.size());
-
- // set-up a death notification so that we can disconnect
- // automatically when/if the remote producer dies.
- if (token != NULL && token->remoteBinder() != NULL) {
- status_t err = token->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
- if (err == NO_ERROR) {
- mConnectedProducerToken = token;
- } else {
- ALOGE("linkToDeath failed: %s (%d)", strerror(-err), err);
- }
- }
- break;
- default:
- err = -EINVAL;
- break;
- }
-
- mBufferHasBeenQueued = false;
- mDequeueBufferCannotBlock = mConsumerControlledByApp && producerControlledByApp;
-
- return err;
-}
-
-void GonkBufferQueue::binderDied(const wp<IBinder>& who) {
- // If we're here, it means that a producer we were connected to died.
- // We're GUARANTEED that we still are connected to it because it has no other way
- // to get disconnected -- or -- we wouldn't be here because we're removing this
- // callback upon disconnect. Therefore, it's okay to read mConnectedApi without
- // synchronization here.
- int api = mConnectedApi;
- this->disconnect(api);
-}
-
-status_t GonkBufferQueue::disconnect(int api) {
- ATRACE_CALL();
- ALOGV("disconnect: api=%d", api);
-
- int err = NO_ERROR;
- sp<IConsumerListener> listener;
-
- { // Scope for the lock
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- // it is not really an error to disconnect after the surface
- // has been abandoned, it should just be a no-op.
- return NO_ERROR;
- }
-
- switch (api) {
- case NATIVE_WINDOW_API_EGL:
- case NATIVE_WINDOW_API_CPU:
- case NATIVE_WINDOW_API_MEDIA:
- case NATIVE_WINDOW_API_CAMERA:
- if (mConnectedApi == api) {
- freeAllBuffersLocked();
- mConnectedApi = NO_CONNECTED_API;
- mDequeueCondition.broadcast();
- listener = mConsumerListener;
- } else {
- ALOGE("disconnect: connected to another api (cur=%d, req=%d)",
- mConnectedApi, api);
- err = -EINVAL;
- }
- break;
- default:
- ALOGE("disconnect: unknown API %d", api);
- err = -EINVAL;
- break;
- }
- }
-
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-
- return err;
-}
-
-void GonkBufferQueue::dumpToString(String8& result, const char* prefix) const {
- Mutex::Autolock _l(mMutex);
-
- String8 fifo;
- int fifoSize = 0;
- Fifo::const_iterator i(mQueue.begin());
- while (i != mQueue.end()) {
- fifo.appendFormat("%02d:%p crop=[%d,%d,%d,%d], "
- "xform=0x%02x, time=%#llx, scale=%s\n",
- i->mBuf, i->mGraphicBuffer.get(),
- i->mCrop.left, i->mCrop.top, i->mCrop.right,
- i->mCrop.bottom, i->mTransform, i->mTimestamp,
- scalingModeName(i->mScalingMode)
- );
- i++;
- fifoSize++;
- }
-
-
- result.appendFormat(
- "%s-BufferQueue mMaxAcquiredBufferCount=%d, mDequeueBufferCannotBlock=%d, default-size=[%dx%d], "
- "default-format=%d, transform-hint=%02x, FIFO(%d)={%s}\n",
- prefix, mMaxAcquiredBufferCount, mDequeueBufferCannotBlock, mDefaultWidth,
- mDefaultHeight, mDefaultBufferFormat, mTransformHint,
- fifoSize, fifo.string());
-
- struct {
- const char * operator()(int state) const {
- switch (state) {
- case BufferSlot::DEQUEUED: return "DEQUEUED";
- case BufferSlot::QUEUED: return "QUEUED";
- case BufferSlot::FREE: return "FREE";
- case BufferSlot::ACQUIRED: return "ACQUIRED";
- default: return "Unknown";
- }
- }
- } stateName;
-
- // just trim the free buffers to not spam the dump
- int maxBufferCount = 0;
- for (int i=NUM_BUFFER_SLOTS-1 ; i>=0 ; i--) {
- const BufferSlot& slot(mSlots[i]);
- if ((slot.mBufferState != BufferSlot::FREE) || (slot.mGraphicBuffer != NULL)) {
- maxBufferCount = i+1;
- break;
- }
- }
-
- for (int i=0 ; i<maxBufferCount ; i++) {
- const BufferSlot& slot(mSlots[i]);
- const sp<GraphicBuffer>& buf(slot.mGraphicBuffer);
- result.appendFormat(
- "%s%s[%02d:%p] state=%-8s",
- prefix, (slot.mBufferState == BufferSlot::ACQUIRED)?">":" ", i, buf.get(),
- stateName(slot.mBufferState)
- );
-
- if (buf != NULL) {
- result.appendFormat(
- ", %p [%4ux%4u:%4u,%3X]",
- buf->handle, buf->width, buf->height, buf->stride,
- buf->format);
- }
- result.append("\n");
- }
-}
-
-void GonkBufferQueue::freeAllBuffersLocked()
-{
- ALOGW_IF(!mQueue.isEmpty(),
- "freeAllBuffersLocked called but mQueue is not empty");
- mQueue.clear();
- mBufferHasBeenQueued = false;
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- mSlots[i].mGraphicBuffer = 0;
- if (mSlots[i].mTextureClient) {
- mSlots[i].mTextureClient->ClearRecycleCallback();
- // release TextureClient in ImageBridge thread
- RefPtr<TextureClientReleaseTask> task =
- MakeAndAddRef<TextureClientReleaseTask>(mSlots[i].mTextureClient);
- mSlots[i].mTextureClient = NULL;
- ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget());
- }
- if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
- mSlots[i].mNeedsCleanupOnRelease = true;
- }
- mSlots[i].mBufferState = BufferSlot::FREE;
- mSlots[i].mFrameNumber = 0;
- mSlots[i].mAcquireCalled = false;
- // destroy fence as GonkBufferQueue now takes ownership
- mSlots[i].mFence = Fence::NO_FENCE;
- }
-}
-
-status_t GonkBufferQueue::acquireBuffer(BufferItem *buffer, nsecs_t expectedPresent) {
- ATRACE_CALL();
- Mutex::Autolock _l(mMutex);
-
- // Check that the consumer doesn't currently have the maximum number of
- // buffers acquired. We allow the max buffer count to be exceeded by one
- // buffer, so that the consumer can successfully set up the newly acquired
- // buffer before releasing the old one.
- int numAcquiredBuffers = 0;
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mBufferState == BufferSlot::ACQUIRED) {
- numAcquiredBuffers++;
- }
- }
- if (numAcquiredBuffers >= mMaxAcquiredBufferCount+1) {
- ALOGE("acquireBuffer: max acquired buffer count reached: %d (max=%d)",
- numAcquiredBuffers, mMaxAcquiredBufferCount);
- return INVALID_OPERATION;
- }
-
- // check if queue is empty
- // In asynchronous mode the list is guaranteed to be one buffer
- // deep, while in synchronous mode we use the oldest buffer.
- if (mQueue.empty()) {
- return NO_BUFFER_AVAILABLE;
- }
-
- Fifo::iterator front(mQueue.begin());
-
- // If expectedPresent is specified, we may not want to return a buffer yet.
- // If it's specified and there's more than one buffer queued, we may
- // want to drop a buffer.
- if (expectedPresent != 0) {
- const int MAX_REASONABLE_NSEC = 1000000000ULL; // 1 second
-
- // The "expectedPresent" argument indicates when the buffer is expected
- // to be presented on-screen. If the buffer's desired-present time
- // is earlier (less) than expectedPresent, meaning it'll be displayed
- // on time or possibly late if we show it ASAP, we acquire and return
- // it. If we don't want to display it until after the expectedPresent
- // time, we return PRESENT_LATER without acquiring it.
- //
- // To be safe, we don't defer acquisition if expectedPresent is
- // more than one second in the future beyond the desired present time
- // (i.e. we'd be holding the buffer for a long time).
- //
- // NOTE: code assumes monotonic time values from the system clock are
- // positive.
-
- // Start by checking to see if we can drop frames. We skip this check
- // if the timestamps are being auto-generated by Surface -- if the
- // app isn't generating timestamps explicitly, they probably don't
- // want frames to be discarded based on them.
- while (mQueue.size() > 1 && !mQueue[0].mIsAutoTimestamp) {
- // If entry[1] is timely, drop entry[0] (and repeat). We apply
- // an additional criteria here: we only drop the earlier buffer if
- // our desiredPresent falls within +/- 1 second of the expected
- // present. Otherwise, bogus desiredPresent times (e.g. 0 or
- // a small relative timestamp), which normally mean "ignore the
- // timestamp and acquire immediately", would cause us to drop
- // frames.
- //
- // We may want to add an additional criteria: don't drop the
- // earlier buffer if entry[1]'s fence hasn't signaled yet.
- //
- // (Vector front is [0], back is [size()-1])
- const BufferItem& bi(mQueue[1]);
- nsecs_t desiredPresent = bi.mTimestamp;
- if (desiredPresent < expectedPresent - MAX_REASONABLE_NSEC ||
- desiredPresent > expectedPresent) {
- // This buffer is set to display in the near future, or
- // desiredPresent is garbage. Either way we don't want to
- // drop the previous buffer just to get this on screen sooner.
- ALOGV("pts nodrop: des=%lld expect=%lld (%lld) now=%lld",
- desiredPresent, expectedPresent, desiredPresent - expectedPresent,
- systemTime(CLOCK_MONOTONIC));
- break;
- }
- ALOGV("pts drop: queue1des=%lld expect=%lld size=%d",
- desiredPresent, expectedPresent, mQueue.size());
- if (stillTracking(front)) {
- // front buffer is still in mSlots, so mark the slot as free
- mSlots[front->mBuf].mBufferState = BufferSlot::FREE;
- }
- mQueue.erase(front);
- front = mQueue.begin();
- }
-
- // See if the front buffer is due.
- nsecs_t desiredPresent = front->mTimestamp;
- if (desiredPresent > expectedPresent &&
- desiredPresent < expectedPresent + MAX_REASONABLE_NSEC) {
- ALOGV("pts defer: des=%lld expect=%lld (%lld) now=%lld",
- desiredPresent, expectedPresent, desiredPresent - expectedPresent,
- systemTime(CLOCK_MONOTONIC));
- return PRESENT_LATER;
- }
-
- ALOGV("pts accept: des=%lld expect=%lld (%lld) now=%lld",
- desiredPresent, expectedPresent, desiredPresent - expectedPresent,
- systemTime(CLOCK_MONOTONIC));
- }
-
- int buf = front->mBuf;
- buffer->mGraphicBuffer = mSlots[buf].mGraphicBuffer;
- buffer->mFrameNumber = mSlots[buf].mFrameNumber;
- buffer->mBuf = buf;
- buffer->mFence = mSlots[buf].mFence;
- ATRACE_BUFFER_INDEX(buf);
-
- ALOGV("acquireBuffer: acquiring { slot=%d/%llu, buffer=%p }",
- front->mBuf, front->mFrameNumber,
- front->mGraphicBuffer->handle);
- // if front buffer still being tracked update slot state
- if (stillTracking(front)) {
- mSlots[buf].mAcquireCalled = true;
- mSlots[buf].mNeedsCleanupOnRelease = false;
- mSlots[buf].mBufferState = BufferSlot::ACQUIRED;
- mSlots[buf].mFence = Fence::NO_FENCE;
- }
-
- // If the buffer has previously been acquired by the consumer, set
- // mGraphicBuffer to NULL to avoid unnecessarily remapping this
- // buffer on the consumer side.
- //if (buffer->mAcquireCalled) {
- // buffer->mGraphicBuffer = NULL;
- //}
-
- mQueue.erase(front);
- mDequeueCondition.broadcast();
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::releaseBuffer(int buf, uint64_t frameNumber, const sp<Fence>& fence) {
- ATRACE_CALL();
-
- if (buf == INVALID_BUFFER_SLOT || fence == NULL) {
- return BAD_VALUE;
- }
-
- Mutex::Autolock _l(mMutex);
-
- // If the frame number has changed because buffer has been reallocated,
- // we can ignore this releaseBuffer for the old buffer.
- //if (frameNumber != mSlots[buf].mFrameNumber) {
- // return STALE_BUFFER_SLOT;
- //}
-
-
- // Internal state consistency checks:
- // Make sure this buffers hasn't been queued while we were owning it (acquired)
- Fifo::iterator front(mQueue.begin());
- Fifo::const_iterator const end(mQueue.end());
- while (front != end) {
- if (front->mBuf == buf) {
- LOG_ALWAYS_FATAL("[%s] received new buffer(#%lld) on slot #%d that has not yet been "
- "acquired", mConsumerName.string(), frameNumber, buf);
- break; // never reached
- }
- front++;
- }
-
- // The buffer can now only be released if its in the acquired state
- if (mSlots[buf].mBufferState == BufferSlot::ACQUIRED) {
- mSlots[buf].mFence = fence;
- mSlots[buf].mBufferState = BufferSlot::FREE;
- } else if (mSlots[buf].mNeedsCleanupOnRelease) {
- ALOGV("releasing a stale buf %d its state was %d", buf, mSlots[buf].mBufferState);
- mSlots[buf].mNeedsCleanupOnRelease = false;
- return STALE_BUFFER_SLOT;
- } else {
- ALOGE("attempted to release buf %d but its state was %d", buf, mSlots[buf].mBufferState);
- return -EINVAL;
- }
-
- mDequeueCondition.broadcast();
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::consumerConnect(const sp<IConsumerListener>& consumerListener,
- bool controlledByApp) {
- ALOGV("consumerConnect controlledByApp=%s",
- controlledByApp ? "true" : "false");
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ALOGE("consumerConnect: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
- if (consumerListener == NULL) {
- ALOGE("consumerConnect: consumerListener may not be NULL");
- return BAD_VALUE;
- }
-
- mConsumerListener = consumerListener;
- mConsumerControlledByApp = controlledByApp;
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::consumerDisconnect() {
- ALOGV("consumerDisconnect");
- Mutex::Autolock lock(mMutex);
-
- if (mConsumerListener == NULL) {
- ALOGE("consumerDisconnect: No consumer is connected!");
- return -EINVAL;
- }
-
- mAbandoned = true;
- mConsumerListener = NULL;
- mQueue.clear();
- freeAllBuffersLocked();
- mDequeueCondition.broadcast();
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::getReleasedBuffers(uint32_t* slotMask) {
- ALOGV("getReleasedBuffers");
- Mutex::Autolock lock(mMutex);
-
- if (mAbandoned) {
- ALOGE("getReleasedBuffers: GonkBufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- uint32_t mask = 0;
- for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
- if (!mSlots[i].mAcquireCalled) {
- mask |= 1 << i;
- }
- }
-
- // Remove buffers in flight (on the queue) from the mask where acquire has
- // been called, as the consumer will not receive the buffer address, so
- // it should not free these slots.
- Fifo::iterator front(mQueue.begin());
- while (front != mQueue.end()) {
- if (front->mAcquireCalled)
- mask &= ~(1 << front->mBuf);
- front++;
- }
-
- *slotMask = mask;
-
- ALOGV("getReleasedBuffers: returning mask %#x", mask);
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h) {
- ALOGV("setDefaultBufferSize: w=%d, h=%d", w, h);
- if (!w || !h) {
- ALOGE("setDefaultBufferSize: dimensions cannot be 0 (w=%d, h=%d)",
- w, h);
- return BAD_VALUE;
- }
-
- Mutex::Autolock lock(mMutex);
- mDefaultWidth = w;
- mDefaultHeight = h;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setDefaultMaxBufferCount(int bufferCount) {
- ATRACE_CALL();
- Mutex::Autolock lock(mMutex);
- return setDefaultMaxBufferCountLocked(bufferCount);
-}
-
-status_t GonkBufferQueue::disableAsyncBuffer() {
- ATRACE_CALL();
- Mutex::Autolock lock(mMutex);
- if (mConsumerListener != NULL) {
- ALOGE("disableAsyncBuffer: consumer already connected!");
- return INVALID_OPERATION;
- }
- mUseAsyncBuffer = false;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueue::setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
- ATRACE_CALL();
- Mutex::Autolock lock(mMutex);
- if (maxAcquiredBuffers < 1 || maxAcquiredBuffers > MAX_MAX_ACQUIRED_BUFFERS) {
- ALOGE("setMaxAcquiredBufferCount: invalid count specified: %d",
- maxAcquiredBuffers);
- return BAD_VALUE;
- }
- if (mConnectedApi != NO_CONNECTED_API) {
- return INVALID_OPERATION;
- }
- mMaxAcquiredBufferCount = maxAcquiredBuffers;
- return NO_ERROR;
-}
-
-int GonkBufferQueue::getMinUndequeuedBufferCount(bool async) const {
- // if dequeueBuffer is allowed to error out, we don't have to
- // add an extra buffer.
- if (!mUseAsyncBuffer)
- return mMaxAcquiredBufferCount;
-
- // we're in async mode, or we want to prevent the app to
- // deadlock itself, we throw-in an extra buffer to guarantee it.
- if (mDequeueBufferCannotBlock || async || !mSynchronousMode)
- return mMaxAcquiredBufferCount + 1;
-
- return mMaxAcquiredBufferCount;
-}
-
-int GonkBufferQueue::getMinMaxBufferCountLocked(bool async) const {
- return getMinUndequeuedBufferCount(async) + 1;
-}
-
-int GonkBufferQueue::getMaxBufferCountLocked(bool async) const {
- int minMaxBufferCount = getMinMaxBufferCountLocked(async);
-
- int maxBufferCount = mDefaultMaxBufferCount;
- if (maxBufferCount < minMaxBufferCount) {
- maxBufferCount = minMaxBufferCount;
- }
- if (mOverrideMaxBufferCount != 0) {
- assert(mOverrideMaxBufferCount >= minMaxBufferCount);
- maxBufferCount = mOverrideMaxBufferCount;
- }
-
- // Any buffers that are dequeued by the producer or sitting in the queue
- // waiting to be consumed need to have their slots preserved. Such
- // buffers will temporarily keep the max buffer count up until the slots
- // no longer need to be preserved.
- for (int i = maxBufferCount; i < NUM_BUFFER_SLOTS; i++) {
- BufferSlot::BufferState state = mSlots[i].mBufferState;
- if (state == BufferSlot::QUEUED || state == BufferSlot::DEQUEUED) {
- maxBufferCount = i + 1;
- }
- }
-
- return maxBufferCount;
-}
-
-bool GonkBufferQueue::stillTracking(const BufferItem *item) const {
- const BufferSlot &slot = mSlots[item->mBuf];
-
- ALOGV("stillTracking?: item: { slot=%d/%llu, buffer=%p }, "
- "slot: { slot=%d/%llu, buffer=%p }",
- item->mBuf, item->mFrameNumber,
- (item->mGraphicBuffer.get() ? item->mGraphicBuffer->handle : 0),
- item->mBuf, slot.mFrameNumber,
- (slot.mGraphicBuffer.get() ? slot.mGraphicBuffer->handle : 0));
-
- // Compare item with its original buffer slot. We can check the slot
- // as the buffer would not be moved to a different slot by the producer.
- return (slot.mGraphicBuffer != NULL &&
- item->mGraphicBuffer->handle == slot.mGraphicBuffer->handle);
-}
-
-GonkBufferQueue::ProxyConsumerListener::ProxyConsumerListener(
- const wp<ConsumerListener>& consumerListener):
- mConsumerListener(consumerListener) {}
-
-GonkBufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}
-
-void GonkBufferQueue::ProxyConsumerListener::onFrameAvailable() {
- sp<ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onFrameAvailable();
- }
-}
-
-void GonkBufferQueue::ProxyConsumerListener::onBuffersReleased() {
- sp<ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-}
-
-}; // namespace android
diff --git a/widget/gonk/nativewindow/GonkBufferQueueKK.h b/widget/gonk/nativewindow/GonkBufferQueueKK.h
deleted file mode 100644
index 01905427d..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueKK.h
+++ /dev/null
@@ -1,583 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKBUFFERQUEUE_KK_H
-#define NATIVEWINDOW_GONKBUFFERQUEUE_KK_H
-
-#include <gui/IConsumerListener.h>
-#include <gui/IGraphicBufferAlloc.h>
-#include <gui/IGraphicBufferProducer.h>
-#include "IGonkGraphicBufferConsumer.h"
-
-#include <ui/Fence.h>
-#include <ui/GraphicBuffer.h>
-
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-
-#include "mozilla/layers/LayersSurfaces.h"
-#include "mozilla/layers/TextureClient.h"
-
-namespace android {
-// ----------------------------------------------------------------------------
-
-class GonkBufferQueue : public BnGraphicBufferProducer,
- public BnGonkGraphicBufferConsumer,
- private IBinder::DeathRecipient
-{
- typedef mozilla::layers::TextureClient TextureClient;
-
-public:
- enum { MIN_UNDEQUEUED_BUFFERS = 2 };
- enum { NUM_BUFFER_SLOTS = 32 };
- enum { NO_CONNECTED_API = 0 };
- enum { INVALID_BUFFER_SLOT = -1 };
- enum { STALE_BUFFER_SLOT = 1, NO_BUFFER_AVAILABLE, PRESENT_LATER };
-
- // When in async mode we reserve two slots in order to guarantee that the
- // producer and consumer can run asynchronously.
- enum { MAX_MAX_ACQUIRED_BUFFERS = NUM_BUFFER_SLOTS - 2 };
-
- // for backward source compatibility
- typedef ::android::ConsumerListener ConsumerListener;
-
- // ProxyConsumerListener is a ConsumerListener implementation that keeps a weak
- // reference to the actual consumer object. It forwards all calls to that
- // consumer object so long as it exists.
- //
- // This class exists to avoid having a circular reference between the
- // GonkBufferQueue object and the consumer object. The reason this can't be a weak
- // reference in the GonkBufferQueue class is because we're planning to expose the
- // consumer side of a GonkBufferQueue as a binder interface, which doesn't support
- // weak references.
- class ProxyConsumerListener : public BnConsumerListener {
- public:
- ProxyConsumerListener(const wp<ConsumerListener>& consumerListener);
- virtual ~ProxyConsumerListener();
- virtual void onFrameAvailable();
- virtual void onBuffersReleased();
- private:
- // mConsumerListener is a weak reference to the IConsumerListener. This is
- // the raison d'etre of ProxyConsumerListener.
- wp<ConsumerListener> mConsumerListener;
- };
-
-
- // BufferQueue manages a pool of gralloc memory slots to be used by
- // producers and consumers. allocator is used to allocate all the
- // needed gralloc buffers.
- GonkBufferQueue(bool allowSynchronousMode = true,
- const sp<IGraphicBufferAlloc>& allocator = NULL);
- virtual ~GonkBufferQueue();
-
- /*
- * IBinder::DeathRecipient interface
- */
-
- virtual void binderDied(const wp<IBinder>& who);
-
- /*
- * IGraphicBufferProducer interface
- */
-
- // Query native window attributes. The "what" values are enumerated in
- // window.h (e.g. NATIVE_WINDOW_FORMAT).
- virtual int query(int what, int* value);
-
- // setBufferCount updates the number of available buffer slots. If this
- // method succeeds, buffer slots will be both unallocated and owned by
- // the GonkBufferQueue object (i.e. they are not owned by the producer or
- // consumer).
- //
- // This will fail if the producer has dequeued any buffers, or if
- // bufferCount is invalid. bufferCount must generally be a value
- // between the minimum undequeued buffer count and NUM_BUFFER_SLOTS
- // (inclusive). It may also be set to zero (the default) to indicate
- // that the producer does not wish to set a value. The minimum value
- // can be obtained by calling query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
- // ...).
- //
- // This may only be called by the producer. The consumer will be told
- // to discard buffers through the onBuffersReleased callback.
- virtual status_t setBufferCount(int bufferCount);
-
- // requestBuffer returns the GraphicBuffer for slot N.
- //
- // In normal operation, this is called the first time slot N is returned
- // by dequeueBuffer. It must be called again if dequeueBuffer returns
- // flags indicating that previously-returned buffers are no longer valid.
- virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
-
- // dequeueBuffer gets the next buffer slot index for the producer to use.
- // If a buffer slot is available then that slot index is written to the
- // location pointed to by the buf argument and a status of OK is returned.
- // If no slot is available then a status of -EBUSY is returned and buf is
- // unmodified.
- //
- // The fence parameter will be updated to hold the fence associated with
- // the buffer. The contents of the buffer must not be overwritten until the
- // fence signals. If the fence is Fence::NO_FENCE, the buffer may be
- // written immediately.
- //
- // The width and height parameters must be no greater than the minimum of
- // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
- // An error due to invalid dimensions might not be reported until
- // updateTexImage() is called. If width and height are both zero, the
- // default values specified by setDefaultBufferSize() are used instead.
- //
- // The pixel formats are enumerated in graphics.h, e.g.
- // HAL_PIXEL_FORMAT_RGBA_8888. If the format is 0, the default format
- // will be used.
- //
- // The usage argument specifies gralloc buffer usage flags. The values
- // are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER. These
- // will be merged with the usage flags specified by setConsumerUsageBits.
- //
- // The return value may be a negative error value or a non-negative
- // collection of flags. If the flags are set, the return values are
- // valid, but additional actions must be performed.
- //
- // If IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION is set, the
- // producer must discard cached GraphicBuffer references for the slot
- // returned in buf.
- // If IGraphicBufferProducer::RELEASE_ALL_BUFFERS is set, the producer
- // must discard cached GraphicBuffer references for all slots.
- //
- // In both cases, the producer will need to call requestBuffer to get a
- // GraphicBuffer handle for the returned slot.
- virtual status_t dequeueBuffer(int *buf, sp<Fence>* fence, bool async,
- uint32_t width, uint32_t height, uint32_t format, uint32_t usage);
-
- // queueBuffer returns a filled buffer to the GonkBufferQueue.
- //
- // Additional data is provided in the QueueBufferInput struct. Notably,
- // a timestamp must be provided for the buffer. The timestamp is in
- // nanoseconds, and must be monotonically increasing. Its other semantics
- // (zero point, etc) are producer-specific and should be documented by the
- // producer.
- //
- // The caller may provide a fence that signals when all rendering
- // operations have completed. Alternatively, NO_FENCE may be used,
- // indicating that the buffer is ready immediately.
- //
- // Some values are returned in the output struct: the current settings
- // for default width and height, the current transform hint, and the
- // number of queued buffers.
- virtual status_t queueBuffer(int buf,
- const QueueBufferInput& input, QueueBufferOutput* output);
-
- // cancelBuffer returns a dequeued buffer to the GonkBufferQueue, but doesn't
- // queue it for use by the consumer.
- //
- // The buffer will not be overwritten until the fence signals. The fence
- // will usually be the one obtained from dequeueBuffer.
- virtual void cancelBuffer(int buf, const sp<Fence>& fence);
-
- // setSynchronousMode sets whether dequeueBuffer is synchronous or
- // asynchronous. In synchronous mode, dequeueBuffer blocks until
- // a buffer is available, the currently bound buffer can be dequeued and
- // queued buffers will be acquired in order. In asynchronous mode,
- // a queued buffer may be replaced by a subsequently queued buffer.
- //
- // The default mode is synchronous.
- // This should be called only during initialization.
- virtual status_t setSynchronousMode(bool enabled);
-
- // connect attempts to connect a producer API to the GonkBufferQueue. This
- // must be called before any other IGraphicBufferProducer methods are
- // called except for getAllocator. A consumer must already be connected.
- //
- // This method will fail if connect was previously called on the
- // GonkBufferQueue and no corresponding disconnect call was made (i.e. if
- // it's still connected to a producer).
- //
- // APIs are enumerated in window.h (e.g. NATIVE_WINDOW_API_CPU).
- virtual status_t connect(const sp<IBinder>& token,
- int api, bool producerControlledByApp, QueueBufferOutput* output);
-
- // disconnect attempts to disconnect a producer API from the GonkBufferQueue.
- // Calling this method will cause any subsequent calls to other
- // IGraphicBufferProducer methods to fail except for getAllocator and connect.
- // Successfully calling connect after this will allow the other methods to
- // succeed again.
- //
- // This method will fail if the the GonkBufferQueue is not currently
- // connected to the specified producer API.
- virtual status_t disconnect(int api);
-
- /*
- * IGraphicBufferConsumer interface
- */
-
- // acquireBuffer attempts to acquire ownership of the next pending buffer in
- // the GonkBufferQueue. If no buffer is pending then it returns -EINVAL. If a
- // buffer is successfully acquired, the information about the buffer is
- // returned in BufferItem. If the buffer returned had previously been
- // acquired then the BufferItem::mGraphicBuffer field of buffer is set to
- // NULL and it is assumed that the consumer still holds a reference to the
- // buffer.
- //
- // If presentWhen is nonzero, it indicates the time when the buffer will
- // be displayed on screen. If the buffer's timestamp is farther in the
- // future, the buffer won't be acquired, and PRESENT_LATER will be
- // returned. The presentation time is in nanoseconds, and the time base
- // is CLOCK_MONOTONIC.
- virtual status_t acquireBuffer(BufferItem *buffer, nsecs_t presentWhen);
-
- // releaseBuffer releases a buffer slot from the consumer back to the
- // GonkBufferQueue. This may be done while the buffer's contents are still
- // being accessed. The fence will signal when the buffer is no longer
- // in use. frameNumber is used to indentify the exact buffer returned.
- //
- // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
- // any references to the just-released buffer that it might have, as if it
- // had received a onBuffersReleased() call with a mask set for the released
- // buffer.
- //
- // Note that the dependencies on EGL will be removed once we switch to using
- // the Android HW Sync HAL.
- virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
- const sp<Fence>& releaseFence);
-
- // consumerConnect connects a consumer to the GonkBufferQueue. Only one
- // consumer may be connected, and when that consumer disconnects the
- // GonkBufferQueue is placed into the "abandoned" state, causing most
- // interactions with the GonkBufferQueue by the producer to fail.
- // controlledByApp indicates whether the consumer is controlled by
- // the application.
- //
- // consumer may not be NULL.
- virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp);
-
- // consumerDisconnect disconnects a consumer from the GonkBufferQueue. All
- // buffers will be freed and the GonkBufferQueue is placed in the "abandoned"
- // state, causing most interactions with the GonkBufferQueue by the producer to
- // fail.
- virtual status_t consumerDisconnect();
-
- // getReleasedBuffers sets the value pointed to by slotMask to a bit mask
- // indicating which buffer slots have been released by the GonkBufferQueue
- // but have not yet been released by the consumer.
- //
- // This should be called from the onBuffersReleased() callback.
- virtual status_t getReleasedBuffers(uint32_t* slotMask);
-
- // setDefaultBufferSize is used to set the size of buffers returned by
- // dequeueBuffer when a width and height of zero is requested. Default
- // is 1x1.
- virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h);
-
- // setDefaultMaxBufferCount sets the default value for the maximum buffer
- // count (the initial default is 2). If the producer has requested a
- // buffer count using setBufferCount, the default buffer count will only
- // take effect if the producer sets the count back to zero.
- //
- // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
- virtual status_t setDefaultMaxBufferCount(int bufferCount);
-
- // disableAsyncBuffer disables the extra buffer used in async mode
- // (when both producer and consumer have set their "isControlledByApp"
- // flag) and has dequeueBuffer() return WOULD_BLOCK instead.
- //
- // This can only be called before consumerConnect().
- virtual status_t disableAsyncBuffer();
-
- // setMaxAcquiredBufferCount sets the maximum number of buffers that can
- // be acquired by the consumer at one time (default 1). This call will
- // fail if a producer is connected to the GonkBufferQueue.
- virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
-
- // setConsumerName sets the name used in logging
- virtual void setConsumerName(const String8& name);
-
- // setDefaultBufferFormat allows the GonkBufferQueue to create
- // GraphicBuffers of a defaultFormat if no format is specified
- // in dequeueBuffer. Formats are enumerated in graphics.h; the
- // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
- virtual status_t setDefaultBufferFormat(uint32_t defaultFormat);
-
- // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
- // These are merged with the bits passed to dequeueBuffer. The values are
- // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
- virtual status_t setConsumerUsageBits(uint32_t usage);
-
- // setTransformHint bakes in rotation to buffers so overlays can be used.
- // The values are enumerated in window.h, e.g.
- // NATIVE_WINDOW_TRANSFORM_ROT_90. The default is 0 (no transform).
- virtual status_t setTransformHint(uint32_t hint);
-
- // dump our state in a String
- virtual void dumpToString(String8& result, const char* prefix) const;
-
- already_AddRefed<TextureClient> getTextureClientFromBuffer(ANativeWindowBuffer* buffer);
-
- int getSlotFromTextureClientLocked(TextureClient* client) const;
-
-private:
- // freeBufferLocked frees the GraphicBuffer and sync resources for the
- // given slot.
- //void freeBufferLocked(int index);
-
- // freeAllBuffersLocked frees the GraphicBuffer and sync resources for
- // all slots.
- void freeAllBuffersLocked();
-
- // setDefaultMaxBufferCountLocked sets the maximum number of buffer slots
- // that will be used if the producer does not override the buffer slot
- // count. The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
- // The initial default is 2.
- status_t setDefaultMaxBufferCountLocked(int count);
-
- // getMinUndequeuedBufferCount returns the minimum number of buffers
- // that must remain in a state other than DEQUEUED.
- // The async parameter tells whether we're in asynchronous mode.
- int getMinUndequeuedBufferCount(bool async) const;
-
- // getMinBufferCountLocked returns the minimum number of buffers allowed
- // given the current GonkBufferQueue state.
- // The async parameter tells whether we're in asynchronous mode.
- int getMinMaxBufferCountLocked(bool async) const;
-
- // getMaxBufferCountLocked returns the maximum number of buffers that can
- // be allocated at once. This value depends upon the following member
- // variables:
- //
- // mDequeueBufferCannotBlock
- // mMaxAcquiredBufferCount
- // mDefaultMaxBufferCount
- // mOverrideMaxBufferCount
- // async parameter
- //
- // Any time one of these member variables is changed while a producer is
- // connected, mDequeueCondition must be broadcast.
- int getMaxBufferCountLocked(bool async) const;
-
- // stillTracking returns true iff the buffer item is still being tracked
- // in one of the slots.
- bool stillTracking(const BufferItem *item) const;
-
- struct BufferSlot {
-
- BufferSlot()
- : mBufferState(BufferSlot::FREE),
- mRequestBufferCalled(false),
- mFrameNumber(0),
- mAcquireCalled(false),
- mNeedsCleanupOnRelease(false) {
- }
-
- // mGraphicBuffer points to the buffer allocated for this slot or is NULL
- // if no buffer has been allocated.
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mTextureClient is a thin abstraction over remotely allocated GraphicBuffer.
- RefPtr<TextureClient> mTextureClient;
-
- // BufferState represents the different states in which a buffer slot
- // can be. All slots are initially FREE.
- enum BufferState {
- // FREE indicates that the buffer is available to be dequeued
- // by the producer. The buffer may be in use by the consumer for
- // a finite time, so the buffer must not be modified until the
- // associated fence is signaled.
- //
- // The slot is "owned" by GonkBufferQueue. It transitions to DEQUEUED
- // when dequeueBuffer is called.
- FREE = 0,
-
- // DEQUEUED indicates that the buffer has been dequeued by the
- // producer, but has not yet been queued or canceled. The
- // producer may modify the buffer's contents as soon as the
- // associated ready fence is signaled.
- //
- // The slot is "owned" by the producer. It can transition to
- // QUEUED (via queueBuffer) or back to FREE (via cancelBuffer).
- DEQUEUED = 1,
-
- // QUEUED indicates that the buffer has been filled by the
- // producer and queued for use by the consumer. The buffer
- // contents may continue to be modified for a finite time, so
- // the contents must not be accessed until the associated fence
- // is signaled.
- //
- // The slot is "owned" by GonkBufferQueue. It can transition to
- // ACQUIRED (via acquireBuffer) or to FREE (if another buffer is
- // queued in asynchronous mode).
- QUEUED = 2,
-
- // ACQUIRED indicates that the buffer has been acquired by the
- // consumer. As with QUEUED, the contents must not be accessed
- // by the consumer until the fence is signaled.
- //
- // The slot is "owned" by the consumer. It transitions to FREE
- // when releaseBuffer is called.
- ACQUIRED = 3
- };
-
- // mBufferState is the current state of this buffer slot.
- BufferState mBufferState;
-
- // mRequestBufferCalled is used for validating that the producer did
- // call requestBuffer() when told to do so. Technically this is not
- // needed but useful for debugging and catching producer bugs.
- bool mRequestBufferCalled;
-
- // mFrameNumber is the number of the queued frame for this slot. This
- // is used to dequeue buffers in LRU order (useful because buffers
- // may be released before their release fence is signaled).
- uint64_t mFrameNumber;
-
- // mFence is a fence which will signal when work initiated by the
- // previous owner of the buffer is finished. When the buffer is FREE,
- // the fence indicates when the consumer has finished reading
- // from the buffer, or when the producer has finished writing if it
- // called cancelBuffer after queueing some writes. When the buffer is
- // QUEUED, it indicates when the producer has finished filling the
- // buffer. When the buffer is DEQUEUED or ACQUIRED, the fence has been
- // passed to the consumer or producer along with ownership of the
- // buffer, and mFence is set to NO_FENCE.
- sp<Fence> mFence;
-
- // Indicates whether this buffer has been seen by a consumer yet
- bool mAcquireCalled;
-
- // Indicates whether this buffer needs to be cleaned up by the
- // consumer. This is set when a buffer in ACQUIRED state is freed.
- // It causes releaseBuffer to return STALE_BUFFER_SLOT.
- bool mNeedsCleanupOnRelease;
- };
-
- // mSlots is the array of buffer slots that must be mirrored on the
- // producer side. This allows buffer ownership to be transferred between
- // the producer and consumer without sending a GraphicBuffer over binder.
- // The entire array is initialized to NULL at construction time, and
- // buffers are allocated for a slot when requestBuffer is called with
- // that slot's index.
- BufferSlot mSlots[NUM_BUFFER_SLOTS];
-
- // mDefaultWidth holds the default width of allocated buffers. It is used
- // in dequeueBuffer() if a width and height of zero is specified.
- uint32_t mDefaultWidth;
-
- // mDefaultHeight holds the default height of allocated buffers. It is used
- // in dequeueBuffer() if a width and height of zero is specified.
- uint32_t mDefaultHeight;
-
- // mMaxAcquiredBufferCount is the number of buffers that the consumer may
- // acquire at one time. It defaults to 1 and can be changed by the
- // consumer via the setMaxAcquiredBufferCount method, but this may only be
- // done when no producer is connected to the GonkBufferQueue.
- //
- // This value is used to derive the value returned for the
- // MIN_UNDEQUEUED_BUFFERS query by the producer.
- int mMaxAcquiredBufferCount;
-
- // mDefaultMaxBufferCount is the default limit on the number of buffers
- // that will be allocated at one time. This default limit is set by the
- // consumer. The limit (as opposed to the default limit) may be
- // overridden by the producer.
- int mDefaultMaxBufferCount;
-
- // mOverrideMaxBufferCount is the limit on the number of buffers that will
- // be allocated at one time. This value is set by the image producer by
- // calling setBufferCount. The default is zero, which means the producer
- // doesn't care about the number of buffers in the pool. In that case
- // mDefaultMaxBufferCount is used as the limit.
- int mOverrideMaxBufferCount;
-
- // mGraphicBufferAlloc is the connection to SurfaceFlinger that is used to
- // allocate new GraphicBuffer objects.
- sp<IGraphicBufferAlloc> mGraphicBufferAlloc;
-
- // mConsumerListener is used to notify the connected consumer of
- // asynchronous events that it may wish to react to. It is initially set
- // to NULL and is written by consumerConnect and consumerDisconnect.
- sp<IConsumerListener> mConsumerListener;
-
- // mSynchronousMode whether we're in synchronous mode or not
- bool mSynchronousMode;
-
- // mConsumerControlledByApp whether the connected consumer is controlled by the
- // application.
- bool mConsumerControlledByApp;
-
- // mDequeueBufferCannotBlock whether dequeueBuffer() isn't allowed to block.
- // this flag is set during connect() when both consumer and producer are controlled
- // by the application.
- bool mDequeueBufferCannotBlock;
-
- // mUseAsyncBuffer whether an extra buffer is used in async mode to prevent
- // dequeueBuffer() from ever blocking.
- bool mUseAsyncBuffer;
-
- // mConnectedApi indicates the producer API that is currently connected
- // to this GonkBufferQueue. It defaults to NO_CONNECTED_API (= 0), and gets
- // updated by the connect and disconnect methods.
- int mConnectedApi;
-
- // mDequeueCondition condition used for dequeueBuffer in synchronous mode
- mutable Condition mDequeueCondition;
-
- // mQueue is a FIFO of queued buffers used in synchronous mode
- typedef Vector<BufferItem> Fifo;
- Fifo mQueue;
-
- // mAbandoned indicates that the GonkBufferQueue will no longer be used to
- // consume image buffers pushed to it using the IGraphicBufferProducer
- // interface. It is initialized to false, and set to true in the
- // consumerDisconnect method. A GonkBufferQueue that has been abandoned will
- // return the NO_INIT error from all IGraphicBufferProducer methods
- // capable of returning an error.
- bool mAbandoned;
-
- // mConsumerName is a string used to identify the GonkBufferQueue in log
- // messages. It is set by the setConsumerName method.
- String8 mConsumerName;
-
- // mMutex is the mutex used to prevent concurrent access to the member
- // variables of GonkBufferQueue objects. It must be locked whenever the
- // member variables are accessed.
- mutable Mutex mMutex;
-
- // mFrameCounter is the free running counter, incremented on every
- // successful queueBuffer call, and buffer allocation.
- uint64_t mFrameCounter;
-
- // mBufferHasBeenQueued is true once a buffer has been queued. It is
- // reset when something causes all buffers to be freed (e.g. changing the
- // buffer count).
- bool mBufferHasBeenQueued;
-
- // mDefaultBufferFormat can be set so it will override
- // the buffer format when it isn't specified in dequeueBuffer
- uint32_t mDefaultBufferFormat;
-
- // mConsumerUsageBits contains flags the consumer wants for GraphicBuffers
- uint32_t mConsumerUsageBits;
-
- // mTransformHint is used to optimize for screen rotations
- uint32_t mTransformHint;
-
- // mConnectedProducerToken is used to set a binder death notification on the producer
- sp<IBinder> mConnectedProducerToken;
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_GUI_BUFFERQUEUE_H
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.cpp b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.cpp
deleted file mode 100644
index 7df72bf68..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.cpp
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "GonkBufferItem.h"
-
-#include <ui/Fence.h>
-#include <ui/GraphicBuffer.h>
-
-#include <system/window.h>
-
-namespace android {
-
-GonkBufferItem::GonkBufferItem() :
- mTransform(0),
- mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
- mTimestamp(0),
- mIsAutoTimestamp(false),
- mFrameNumber(0),
- mSlot(INVALID_BUFFER_SLOT),
- mIsDroppable(false),
- mAcquireCalled(false),
- mTransformToDisplayInverse(false) {
- mCrop.makeInvalid();
-}
-
-GonkBufferItem::operator IGonkGraphicBufferConsumer::BufferItem() const {
- IGonkGraphicBufferConsumer::BufferItem bufferItem;
- bufferItem.mGraphicBuffer = mGraphicBuffer;
- bufferItem.mFence = mFence;
- bufferItem.mCrop = mCrop;
- bufferItem.mTransform = mTransform;
- bufferItem.mScalingMode = mScalingMode;
- bufferItem.mTimestamp = mTimestamp;
- bufferItem.mIsAutoTimestamp = mIsAutoTimestamp;
- bufferItem.mFrameNumber = mFrameNumber;
- bufferItem.mBuf = mSlot;
- bufferItem.mIsDroppable = mIsDroppable;
- bufferItem.mAcquireCalled = mAcquireCalled;
- bufferItem.mTransformToDisplayInverse = mTransformToDisplayInverse;
- return bufferItem;
-}
-
-size_t GonkBufferItem::getPodSize() const {
- size_t c = sizeof(mCrop) +
- sizeof(mTransform) +
- sizeof(mScalingMode) +
- sizeof(mTimestamp) +
- sizeof(mIsAutoTimestamp) +
- sizeof(mFrameNumber) +
- sizeof(mSlot) +
- sizeof(mIsDroppable) +
- sizeof(mAcquireCalled) +
- sizeof(mTransformToDisplayInverse);
- return c;
-}
-
-size_t GonkBufferItem::getFlattenedSize() const {
- size_t c = 0;
- if (mGraphicBuffer != 0) {
- c += mGraphicBuffer->getFlattenedSize();
- FlattenableUtils::align<4>(c);
- }
- if (mFence != 0) {
- c += mFence->getFlattenedSize();
- FlattenableUtils::align<4>(c);
- }
- return sizeof(int32_t) + c + getPodSize();
-}
-
-size_t GonkBufferItem::getFdCount() const {
- size_t c = 0;
- if (mGraphicBuffer != 0) {
- c += mGraphicBuffer->getFdCount();
- }
- if (mFence != 0) {
- c += mFence->getFdCount();
- }
- return c;
-}
-
-status_t GonkBufferItem::flatten(
- void*& buffer, size_t& size, int*& fds, size_t& count) const {
-
- // make sure we have enough space
- if (count < GonkBufferItem::getFlattenedSize()) {
- return NO_MEMORY;
- }
-
- // content flags are stored first
- uint32_t& flags = *static_cast<uint32_t*>(buffer);
-
- // advance the pointer
- FlattenableUtils::advance(buffer, size, sizeof(uint32_t));
-
- flags = 0;
- if (mGraphicBuffer != 0) {
- status_t err = mGraphicBuffer->flatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- flags |= 1;
- }
- if (mFence != 0) {
- status_t err = mFence->flatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- flags |= 2;
- }
-
- // check we have enough space (in case flattening the fence/graphicbuffer lied to us)
- if (size < getPodSize()) {
- return NO_MEMORY;
- }
-
- FlattenableUtils::write(buffer, size, mCrop);
- FlattenableUtils::write(buffer, size, mTransform);
- FlattenableUtils::write(buffer, size, mScalingMode);
- FlattenableUtils::write(buffer, size, mTimestamp);
- FlattenableUtils::write(buffer, size, mIsAutoTimestamp);
- FlattenableUtils::write(buffer, size, mFrameNumber);
- FlattenableUtils::write(buffer, size, mSlot);
- FlattenableUtils::write(buffer, size, mIsDroppable);
- FlattenableUtils::write(buffer, size, mAcquireCalled);
- FlattenableUtils::write(buffer, size, mTransformToDisplayInverse);
-
- return NO_ERROR;
-}
-
-status_t GonkBufferItem::unflatten(
- void const*& buffer, size_t& size, int const*& fds, size_t& count) {
-
- if (size < sizeof(uint32_t))
- return NO_MEMORY;
-
- uint32_t flags = 0;
- FlattenableUtils::read(buffer, size, flags);
-
- if (flags & 1) {
- mGraphicBuffer = new GraphicBuffer();
- status_t err = mGraphicBuffer->unflatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- }
-
- if (flags & 2) {
- mFence = new Fence();
- status_t err = mFence->unflatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- }
-
- // check we have enough space
- if (size < getPodSize()) {
- return NO_MEMORY;
- }
-
- FlattenableUtils::read(buffer, size, mCrop);
- FlattenableUtils::read(buffer, size, mTransform);
- FlattenableUtils::read(buffer, size, mScalingMode);
- FlattenableUtils::read(buffer, size, mTimestamp);
- FlattenableUtils::read(buffer, size, mIsAutoTimestamp);
- FlattenableUtils::read(buffer, size, mFrameNumber);
- FlattenableUtils::read(buffer, size, mSlot);
- FlattenableUtils::read(buffer, size, mIsDroppable);
- FlattenableUtils::read(buffer, size, mAcquireCalled);
- FlattenableUtils::read(buffer, size, mTransformToDisplayInverse);
-
- return NO_ERROR;
-}
-
-const char* GonkBufferItem::scalingModeName(uint32_t scalingMode) {
- switch (scalingMode) {
- case NATIVE_WINDOW_SCALING_MODE_FREEZE: return "FREEZE";
- case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW: return "SCALE_TO_WINDOW";
- case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP: return "SCALE_CROP";
- default: return "Unknown";
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.h b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.h
deleted file mode 100644
index b2d6d3068..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferItem.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKBUFFERITEM_LL_H
-#define NATIVEWINDOW_GONKBUFFERITEM_LL_H
-
-#include "IGonkGraphicBufferConsumerLL.h"
-
-#include <ui/Rect.h>
-
-#include <utils/Flattenable.h>
-#include <utils/StrongPointer.h>
-
-namespace android {
-
-class Fence;
-class GraphicBuffer;
-
-class GonkBufferItem : public Flattenable<GonkBufferItem> {
- friend class Flattenable<GonkBufferItem>;
- size_t getPodSize() const;
- size_t getFlattenedSize() const;
- size_t getFdCount() const;
- status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
- status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
-
- public:
- // The default value of mBuf, used to indicate this doesn't correspond to a slot.
- enum { INVALID_BUFFER_SLOT = -1 };
- GonkBufferItem();
- operator IGonkGraphicBufferConsumer::BufferItem() const;
-
- static const char* scalingModeName(uint32_t scalingMode);
-
- // mGraphicBuffer points to the buffer allocated for this slot, or is NULL
- // if the buffer in this slot has been acquired in the past (see
- // BufferSlot.mAcquireCalled).
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mFence is a fence that will signal when the buffer is idle.
- sp<Fence> mFence;
-
- // mCrop is the current crop rectangle for this buffer slot.
- Rect mCrop;
-
- // mTransform is the current transform flags for this buffer slot.
- // refer to NATIVE_WINDOW_TRANSFORM_* in <window.h>
- uint32_t mTransform;
-
- // mScalingMode is the current scaling mode for this buffer slot.
- // refer to NATIVE_WINDOW_SCALING_* in <window.h>
- uint32_t mScalingMode;
-
- // mTimestamp is the current timestamp for this buffer slot. This gets
- // to set by queueBuffer each time this slot is queued. This value
- // is guaranteed to be monotonically increasing for each newly
- // acquired buffer.
- int64_t mTimestamp;
-
- // mIsAutoTimestamp indicates whether mTimestamp was generated
- // automatically when the buffer was queued.
- bool mIsAutoTimestamp;
-
- // mFrameNumber is the number of the queued frame for this slot.
- uint64_t mFrameNumber;
-
- // mSlot is the slot index of this buffer (default INVALID_BUFFER_SLOT).
- int mSlot;
-
- // mIsDroppable whether this buffer was queued with the
- // property that it can be replaced by a new buffer for the purpose of
- // making sure dequeueBuffer() won't block.
- // i.e.: was the BufferQueue in "mDequeueBufferCannotBlock" when this buffer
- // was queued.
- bool mIsDroppable;
-
- // Indicates whether this buffer has been seen by a consumer yet
- bool mAcquireCalled;
-
- // Indicates this buffer must be transformed by the inverse transform of the screen
- // it is displayed onto. This is applied after mTransform.
- bool mTransformToDisplayInverse;
-};
-
-} // namespace android
-
-#endif
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.cpp b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.cpp
deleted file mode 100644
index 1d7eb2702..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.cpp
+++ /dev/null
@@ -1,559 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <inttypes.h>
-
-#define LOG_TAG "GonkBufferQueueConsumer"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-//#define LOG_NDEBUG 0
-
-#include "GonkBufferItem.h"
-#include "GonkBufferQueueConsumer.h"
-#include "GonkBufferQueueCore.h"
-#include <gui/IConsumerListener.h>
-#include <gui/IProducerListener.h>
-
-namespace android {
-
-GonkBufferQueueConsumer::GonkBufferQueueConsumer(const sp<GonkBufferQueueCore>& core) :
- mCore(core),
- mSlots(core->mSlots),
- mConsumerName() {}
-
-GonkBufferQueueConsumer::~GonkBufferQueueConsumer() {}
-
-status_t GonkBufferQueueConsumer::acquireBuffer(BufferItem* outBuffer,
- nsecs_t expectedPresent) {
- ATRACE_CALL();
- Mutex::Autolock lock(mCore->mMutex);
-
- // Check that the consumer doesn't currently have the maximum number of
- // buffers acquired. We allow the max buffer count to be exceeded by one
- // buffer so that the consumer can successfully set up the newly acquired
- // buffer before releasing the old one.
- int numAcquiredBuffers = 0;
- for (int s = 0; s < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
- if (mSlots[s].mBufferState == GonkBufferSlot::ACQUIRED) {
- ++numAcquiredBuffers;
- }
- }
- if (numAcquiredBuffers >= mCore->mMaxAcquiredBufferCount + 1) {
- ALOGE("acquireBuffer: max acquired buffer count reached: %d (max %d)",
- numAcquiredBuffers, mCore->mMaxAcquiredBufferCount);
- return INVALID_OPERATION;
- }
-
- // Check if the queue is empty.
- // In asynchronous mode the list is guaranteed to be one buffer deep,
- // while in synchronous mode we use the oldest buffer.
- if (mCore->mQueue.empty()) {
- return NO_BUFFER_AVAILABLE;
- }
-
- GonkBufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());
-
- // If expectedPresent is specified, we may not want to return a buffer yet.
- // If it's specified and there's more than one buffer queued, we may want
- // to drop a buffer.
- if (expectedPresent != 0) {
- const int MAX_REASONABLE_NSEC = 1000000000ULL; // 1 second
-
- // The 'expectedPresent' argument indicates when the buffer is expected
- // to be presented on-screen. If the buffer's desired present time is
- // earlier (less) than expectedPresent -- meaning it will be displayed
- // on time or possibly late if we show it as soon as possible -- we
- // acquire and return it. If we don't want to display it until after the
- // expectedPresent time, we return PRESENT_LATER without acquiring it.
- //
- // To be safe, we don't defer acquisition if expectedPresent is more
- // than one second in the future beyond the desired present time
- // (i.e., we'd be holding the buffer for a long time).
- //
- // NOTE: Code assumes monotonic time values from the system clock
- // are positive.
-
- // Start by checking to see if we can drop frames. We skip this check if
- // the timestamps are being auto-generated by Surface. If the app isn't
- // generating timestamps explicitly, it probably doesn't want frames to
- // be discarded based on them.
- while (mCore->mQueue.size() > 1 && !mCore->mQueue[0].mIsAutoTimestamp) {
- // If entry[1] is timely, drop entry[0] (and repeat). We apply an
- // additional criterion here: we only drop the earlier buffer if our
- // desiredPresent falls within +/- 1 second of the expected present.
- // Otherwise, bogus desiredPresent times (e.g., 0 or a small
- // relative timestamp), which normally mean "ignore the timestamp
- // and acquire immediately", would cause us to drop frames.
- //
- // We may want to add an additional criterion: don't drop the
- // earlier buffer if entry[1]'s fence hasn't signaled yet.
- const BufferItem& bufferItem(mCore->mQueue[1]);
- nsecs_t desiredPresent = bufferItem.mTimestamp;
- if (desiredPresent < expectedPresent - MAX_REASONABLE_NSEC ||
- desiredPresent > expectedPresent) {
- // This buffer is set to display in the near future, or
- // desiredPresent is garbage. Either way we don't want to drop
- // the previous buffer just to get this on the screen sooner.
- ALOGV("acquireBuffer: nodrop desire=%" PRId64 " expect=%"
- PRId64 " (%" PRId64 ") now=%" PRId64,
- desiredPresent, expectedPresent,
- desiredPresent - expectedPresent,
- systemTime(CLOCK_MONOTONIC));
- break;
- }
-
- ALOGV("acquireBuffer: drop desire=%" PRId64 " expect=%" PRId64
- " size=%zu",
- desiredPresent, expectedPresent, mCore->mQueue.size());
- if (mCore->stillTracking(front)) {
- // Front buffer is still in mSlots, so mark the slot as free
- mSlots[front->mSlot].mBufferState = GonkBufferSlot::FREE;
- }
- mCore->mQueue.erase(front);
- front = mCore->mQueue.begin();
- }
-
- // See if the front buffer is due
- nsecs_t desiredPresent = front->mTimestamp;
- if (desiredPresent > expectedPresent &&
- desiredPresent < expectedPresent + MAX_REASONABLE_NSEC) {
- ALOGV("acquireBuffer: defer desire=%" PRId64 " expect=%" PRId64
- " (%" PRId64 ") now=%" PRId64,
- desiredPresent, expectedPresent,
- desiredPresent - expectedPresent,
- systemTime(CLOCK_MONOTONIC));
- return PRESENT_LATER;
- }
-
- ALOGV("acquireBuffer: accept desire=%" PRId64 " expect=%" PRId64 " "
- "(%" PRId64 ") now=%" PRId64, desiredPresent, expectedPresent,
- desiredPresent - expectedPresent,
- systemTime(CLOCK_MONOTONIC));
- }
-
- int slot = front->mSlot;
- //*outBuffer = *front;
- outBuffer->mGraphicBuffer = mSlots[slot].mGraphicBuffer;
- outBuffer->mFrameNumber = mSlots[slot].mFrameNumber;
- outBuffer->mBuf = slot;
- outBuffer->mFence = mSlots[slot].mFence;
-
- ATRACE_BUFFER_INDEX(slot);
-
- ALOGV("acquireBuffer: acquiring { slot=%d/%" PRIu64 " buffer=%p }",
- slot, front->mFrameNumber, front->mGraphicBuffer->handle);
- // If the front buffer is still being tracked, update its slot state
- if (mCore->stillTracking(front)) {
- mSlots[slot].mAcquireCalled = true;
- mSlots[slot].mNeedsCleanupOnRelease = false;
- mSlots[slot].mBufferState = GonkBufferSlot::ACQUIRED;
- mSlots[slot].mFence = Fence::NO_FENCE;
- }
-
- // If the buffer has previously been acquired by the consumer, set
- // mGraphicBuffer to NULL to avoid unnecessarily remapping this buffer
- // on the consumer side
- //if (outBuffer->mAcquireCalled) {
- // outBuffer->mGraphicBuffer = NULL;
- //}
-
- mCore->mQueue.erase(front);
-
- // We might have freed a slot while dropping old buffers, or the producer
- // may be blocked waiting for the number of buffers in the queue to
- // decrease.
- mCore->mDequeueCondition.broadcast();
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::detachBuffer(int slot) {
- ATRACE_CALL();
- ATRACE_BUFFER_INDEX(slot);
- ALOGV("detachBuffer(C): slot %d", slot);
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("detachBuffer(C): GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- if (slot < 0 || slot >= GonkBufferQueueDefs::NUM_BUFFER_SLOTS) {
- ALOGE("detachBuffer(C): slot index %d out of range [0, %d)",
- slot, GonkBufferQueueDefs::NUM_BUFFER_SLOTS);
- return BAD_VALUE;
- } else if (mSlots[slot].mBufferState != GonkBufferSlot::ACQUIRED) {
- ALOGE("detachBuffer(C): slot %d is not owned by the consumer "
- "(state = %d)", slot, mSlots[slot].mBufferState);
- return BAD_VALUE;
- }
-
- mCore->freeBufferLocked(slot);
- mCore->mDequeueCondition.broadcast();
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::attachBuffer(int* outSlot,
- const sp<android::GraphicBuffer>& buffer) {
- ATRACE_CALL();
-
- if (outSlot == NULL) {
- ALOGE("attachBuffer(P): outSlot must not be NULL");
- return BAD_VALUE;
- } else if (buffer == NULL) {
- ALOGE("attachBuffer(P): cannot attach NULL buffer");
- return BAD_VALUE;
- }
-
- Mutex::Autolock lock(mCore->mMutex);
-
- // Make sure we don't have too many acquired buffers and find a free slot
- // to put the buffer into (the oldest if there are multiple).
- int numAcquiredBuffers = 0;
- int found = GonkBufferQueueCore::INVALID_BUFFER_SLOT;
- for (int s = 0; s < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
- if (mSlots[s].mBufferState == GonkBufferSlot::ACQUIRED) {
- ++numAcquiredBuffers;
- } else if (mSlots[s].mBufferState == GonkBufferSlot::FREE) {
- if (found == GonkBufferQueueCore::INVALID_BUFFER_SLOT ||
- mSlots[s].mFrameNumber < mSlots[found].mFrameNumber) {
- found = s;
- }
- }
- }
-
- if (numAcquiredBuffers >= mCore->mMaxAcquiredBufferCount + 1) {
- ALOGE("attachBuffer(P): max acquired buffer count reached: %d "
- "(max %d)", numAcquiredBuffers,
- mCore->mMaxAcquiredBufferCount);
- return INVALID_OPERATION;
- }
- if (found == GonkBufferQueueCore::INVALID_BUFFER_SLOT) {
- ALOGE("attachBuffer(P): could not find free buffer slot");
- return NO_MEMORY;
- }
-
- *outSlot = found;
- ATRACE_BUFFER_INDEX(*outSlot);
- ALOGV("attachBuffer(C): returning slot %d", *outSlot);
-
- mSlots[*outSlot].mGraphicBuffer = buffer;
- mSlots[*outSlot].mBufferState = GonkBufferSlot::ACQUIRED;
- mSlots[*outSlot].mAttachedByConsumer = true;
- mSlots[*outSlot].mNeedsCleanupOnRelease = false;
- mSlots[*outSlot].mFence = Fence::NO_FENCE;
- mSlots[*outSlot].mFrameNumber = 0;
-
- // mAcquireCalled tells GonkBufferQueue that it doesn't need to send a valid
- // GraphicBuffer pointer on the next acquireBuffer call, which decreases
- // Binder traffic by not un/flattening the GraphicBuffer. However, it
- // requires that the consumer maintain a cached copy of the slot <--> buffer
- // mappings, which is why the consumer doesn't need the valid pointer on
- // acquire.
- //
- // The StreamSplitter is one of the primary users of the attach/detach
- // logic, and while it is running, all buffers it acquires are immediately
- // detached, and all buffers it eventually releases are ones that were
- // attached (as opposed to having been obtained from acquireBuffer), so it
- // doesn't make sense to maintain the slot/buffer mappings, which would
- // become invalid for every buffer during detach/attach. By setting this to
- // false, the valid GraphicBuffer pointer will always be sent with acquire
- // for attached buffers.
- mSlots[*outSlot].mAcquireCalled = false;
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::releaseBuffer(int slot, uint64_t frameNumber,
- const sp<Fence>& releaseFence) {
- ATRACE_CALL();
-
- if (slot < 0 || slot >= GonkBufferQueueDefs::NUM_BUFFER_SLOTS ||
- releaseFence == NULL) {
- return BAD_VALUE;
- }
-
- sp<IProducerListener> listener;
- { // Autolock scope
- Mutex::Autolock lock(mCore->mMutex);
-
- // If the frame number has changed because the buffer has been reallocated,
- // we can ignore this releaseBuffer for the old buffer
- //if (frameNumber != mSlots[slot].mFrameNumber) {
- // return STALE_BUFFER_SLOT;
- //}
-
- // Make sure this buffer hasn't been queued while acquired by the consumer
- GonkBufferQueueCore::Fifo::iterator current(mCore->mQueue.begin());
- while (current != mCore->mQueue.end()) {
- if (current->mSlot == slot) {
- ALOGE("releaseBuffer: buffer slot %d pending release is "
- "currently queued", slot);
- return BAD_VALUE;
- }
- ++current;
- }
-
- if (mSlots[slot].mBufferState == GonkBufferSlot::ACQUIRED) {
- mSlots[slot].mFence = releaseFence;
- mSlots[slot].mBufferState = GonkBufferSlot::FREE;
- listener = mCore->mConnectedProducerListener;
- ALOGV("releaseBuffer: releasing slot %d", slot);
- } else if (mSlots[slot].mNeedsCleanupOnRelease) {
- ALOGV("releaseBuffer: releasing a stale buffer slot %d "
- "(state = %d)", slot, mSlots[slot].mBufferState);
- mSlots[slot].mNeedsCleanupOnRelease = false;
- return STALE_BUFFER_SLOT;
- } else {
- ALOGV("releaseBuffer: attempted to release buffer slot %d "
- "but its state was %d", slot, mSlots[slot].mBufferState);
- return BAD_VALUE;
- }
-
- mCore->mDequeueCondition.broadcast();
- } // Autolock scope
-
- // Call back without lock held
- if (listener != NULL) {
- listener->onBufferReleased();
- }
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::connect(
- const sp<IConsumerListener>& consumerListener, bool controlledByApp) {
- ATRACE_CALL();
-
- if (consumerListener == NULL) {
- ALOGE("connect(C): consumerListener may not be NULL");
- return BAD_VALUE;
- }
-
- ALOGV("connect(C): controlledByApp=%s",
- controlledByApp ? "true" : "false");
-
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("connect(C): GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- mCore->mConsumerListener = consumerListener;
- mCore->mConsumerControlledByApp = controlledByApp;
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::disconnect() {
- ATRACE_CALL();
-
- ALOGV("disconnect(C)");
-
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mConsumerListener == NULL) {
- ALOGE("disconnect(C): no consumer is connected");
- return BAD_VALUE;
- }
-
- mCore->mIsAbandoned = true;
- mCore->mConsumerListener = NULL;
- mCore->mQueue.clear();
- mCore->freeAllBuffersLocked();
- mCore->mDequeueCondition.broadcast();
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::getReleasedBuffers(uint64_t *outSlotMask) {
- ATRACE_CALL();
-
- if (outSlotMask == NULL) {
- ALOGE("getReleasedBuffers: outSlotMask may not be NULL");
- return BAD_VALUE;
- }
-
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("getReleasedBuffers: GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- uint64_t mask = 0;
- for (int s = 0; s < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
- if (!mSlots[s].mAcquireCalled) {
- mask |= (1ULL << s);
- }
- }
-
- // Remove from the mask queued buffers for which acquire has been called,
- // since the consumer will not receive their buffer addresses and so must
- // retain their cached information
- GonkBufferQueueCore::Fifo::iterator current(mCore->mQueue.begin());
- while (current != mCore->mQueue.end()) {
- if (current->mAcquireCalled) {
- mask &= ~(1ULL << current->mSlot);
- }
- ++current;
- }
-
- ALOGV("getReleasedBuffers: returning mask %#" PRIx64, mask);
- *outSlotMask = mask;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::setDefaultBufferSize(uint32_t width,
- uint32_t height) {
- ATRACE_CALL();
-
- if (width == 0 || height == 0) {
- ALOGV("setDefaultBufferSize: dimensions cannot be 0 (width=%u "
- "height=%u)", width, height);
- return BAD_VALUE;
- }
-
- ALOGV("setDefaultBufferSize: width=%u height=%u", width, height);
-
- Mutex::Autolock lock(mCore->mMutex);
- mCore->mDefaultWidth = width;
- mCore->mDefaultHeight = height;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::setDefaultMaxBufferCount(int bufferCount) {
- ATRACE_CALL();
- Mutex::Autolock lock(mCore->mMutex);
- return mCore->setDefaultMaxBufferCountLocked(bufferCount);
-}
-
-status_t GonkBufferQueueConsumer::disableAsyncBuffer() {
- ATRACE_CALL();
-
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mConsumerListener != NULL) {
- ALOGE("disableAsyncBuffer: consumer already connected");
- return INVALID_OPERATION;
- }
-
- ALOGV("disableAsyncBuffer");
- mCore->mUseAsyncBuffer = false;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::setMaxAcquiredBufferCount(
- int maxAcquiredBuffers) {
- ATRACE_CALL();
-
- if (maxAcquiredBuffers < 1 ||
- maxAcquiredBuffers > GonkBufferQueueCore::MAX_MAX_ACQUIRED_BUFFERS) {
- ALOGE("setMaxAcquiredBufferCount: invalid count %d",
- maxAcquiredBuffers);
- return BAD_VALUE;
- }
-
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mConnectedApi != GonkBufferQueueCore::NO_CONNECTED_API) {
- ALOGE("setMaxAcquiredBufferCount: producer is already connected");
- return INVALID_OPERATION;
- }
-
- ALOGV("setMaxAcquiredBufferCount: %d", maxAcquiredBuffers);
- mCore->mMaxAcquiredBufferCount = maxAcquiredBuffers;
- return NO_ERROR;
-}
-
-void GonkBufferQueueConsumer::setConsumerName(const String8& name) {
- ATRACE_CALL();
- ALOGV("setConsumerName: '%s'", name.string());
- Mutex::Autolock lock(mCore->mMutex);
- mCore->mConsumerName = name;
- mConsumerName = name;
-}
-
-status_t GonkBufferQueueConsumer::setDefaultBufferFormat(uint32_t defaultFormat) {
- ATRACE_CALL();
- ALOGV("setDefaultBufferFormat: %u", defaultFormat);
- Mutex::Autolock lock(mCore->mMutex);
- mCore->mDefaultBufferFormat = defaultFormat;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::setConsumerUsageBits(uint32_t usage) {
- ATRACE_CALL();
- ALOGV("setConsumerUsageBits: %#x", usage);
- Mutex::Autolock lock(mCore->mMutex);
- mCore->mConsumerUsageBits = usage;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueConsumer::setTransformHint(uint32_t hint) {
- ATRACE_CALL();
- ALOGV("setTransformHint: %#x", hint);
- Mutex::Autolock lock(mCore->mMutex);
- mCore->mTransformHint = hint;
- return NO_ERROR;
-}
-
-sp<NativeHandle> GonkBufferQueueConsumer::getSidebandStream() const {
- return mCore->mSidebandStream;
-}
-
-void GonkBufferQueueConsumer::dumpToString(String8& result, const char* prefix) const {
- mCore->dump(result, prefix);
-}
-
-already_AddRefed<GonkBufferSlot::TextureClient>
-GonkBufferQueueConsumer::getTextureClientFromBuffer(ANativeWindowBuffer* buffer)
-{
- Mutex::Autolock _l(mCore->mMutex);
- if (buffer == NULL) {
- ALOGE("getSlotFromBufferLocked: encountered NULL buffer");
- return nullptr;
- }
-
- for (int i = 0; i < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mGraphicBuffer != NULL && mSlots[i].mGraphicBuffer->handle == buffer->handle) {
- RefPtr<TextureClient> client(mSlots[i].mTextureClient);
- return client.forget();
- }
- }
- ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
- return nullptr;
-}
-
-int
-GonkBufferQueueConsumer::getSlotFromTextureClientLocked(GonkBufferSlot::TextureClient* client) const
-{
- if (client == NULL) {
- ALOGE("getSlotFromBufferLocked: encountered NULL buffer");
- return BAD_VALUE;
- }
-
- for (int i = 0; i < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; i++) {
- if (mSlots[i].mTextureClient == client) {
- return i;
- }
- }
- ALOGE("getSlotFromBufferLocked: unknown TextureClient: %p", client);
- return BAD_VALUE;
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.h b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.h
deleted file mode 100644
index a97cfab42..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.h
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKBUFFERQUEUECONSUMER_LL_H
-#define NATIVEWINDOW_GONKBUFFERQUEUECONSUMER_LL_H
-
-#include "GonkBufferQueueDefs.h"
-#include "IGonkGraphicBufferConsumerLL.h"
-
-namespace android {
-
-class GonkBufferQueueCore;
-
-class GonkBufferQueueConsumer : public BnGonkGraphicBufferConsumer {
-
-public:
- GonkBufferQueueConsumer(const sp<GonkBufferQueueCore>& core);
- virtual ~GonkBufferQueueConsumer();
-
- // acquireBuffer attempts to acquire ownership of the next pending buffer in
- // the GonkBufferQueue. If no buffer is pending then it returns
- // NO_BUFFER_AVAILABLE. If a buffer is successfully acquired, the
- // information about the buffer is returned in BufferItem. If the buffer
- // returned had previously been acquired then the BufferItem::mGraphicBuffer
- // field of buffer is set to NULL and it is assumed that the consumer still
- // holds a reference to the buffer.
- //
- // If expectedPresent is nonzero, it indicates the time when the buffer
- // will be displayed on screen. If the buffer's timestamp is farther in the
- // future, the buffer won't be acquired, and PRESENT_LATER will be
- // returned. The presentation time is in nanoseconds, and the time base
- // is CLOCK_MONOTONIC.
- virtual status_t acquireBuffer(BufferItem* outBuffer,
- nsecs_t expectedPresent);
-
- // See IGonkGraphicBufferConsumer::detachBuffer
- virtual status_t detachBuffer(int slot);
-
- // See IGonkGraphicBufferConsumer::attachBuffer
- virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer);
-
- // releaseBuffer releases a buffer slot from the consumer back to the
- // GonkBufferQueue. This may be done while the buffer's contents are still
- // being accessed. The fence will signal when the buffer is no longer
- // in use. frameNumber is used to indentify the exact buffer returned.
- //
- // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
- // any references to the just-released buffer that it might have, as if it
- // had received a onBuffersReleased() call with a mask set for the released
- // buffer.
- virtual status_t releaseBuffer(int slot, uint64_t frameNumber,
- const sp<Fence>& releaseFence);
-
- // connect connects a consumer to the GonkBufferQueue. Only one
- // consumer may be connected, and when that consumer disconnects the
- // GonkBufferQueue is placed into the "abandoned" state, causing most
- // interactions with the GonkBufferQueue by the producer to fail.
- // controlledByApp indicates whether the consumer is controlled by
- // the application.
- //
- // consumerListener may not be NULL.
- virtual status_t connect(const sp<IConsumerListener>& consumerListener,
- bool controlledByApp);
-
- // disconnect disconnects a consumer from the GonkBufferQueue. All
- // buffers will be freed and the GonkBufferQueue is placed in the "abandoned"
- // state, causing most interactions with the GonkBufferQueue by the producer to
- // fail.
- virtual status_t disconnect();
-
- // getReleasedBuffers sets the value pointed to by outSlotMask to a bit mask
- // indicating which buffer slots have been released by the GonkBufferQueue
- // but have not yet been released by the consumer.
- //
- // This should be called from the onBuffersReleased() callback.
- virtual status_t getReleasedBuffers(uint64_t* outSlotMask);
-
- // setDefaultBufferSize is used to set the size of buffers returned by
- // dequeueBuffer when a width and height of zero is requested. Default
- // is 1x1.
- virtual status_t setDefaultBufferSize(uint32_t width, uint32_t height);
-
- // setDefaultMaxBufferCount sets the default value for the maximum buffer
- // count (the initial default is 2). If the producer has requested a
- // buffer count using setBufferCount, the default buffer count will only
- // take effect if the producer sets the count back to zero.
- //
- // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
- virtual status_t setDefaultMaxBufferCount(int bufferCount);
-
- // disableAsyncBuffer disables the extra buffer used in async mode
- // (when both producer and consumer have set their "isControlledByApp"
- // flag) and has dequeueBuffer() return WOULD_BLOCK instead.
- //
- // This can only be called before connect().
- virtual status_t disableAsyncBuffer();
-
- // setMaxAcquiredBufferCount sets the maximum number of buffers that can
- // be acquired by the consumer at one time (default 1). This call will
- // fail if a producer is connected to the GonkBufferQueue.
- virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
-
- // setConsumerName sets the name used in logging
- virtual void setConsumerName(const String8& name);
-
- // setDefaultBufferFormat allows the GonkBufferQueue to create
- // GraphicBuffers of a defaultFormat if no format is specified
- // in dequeueBuffer. Formats are enumerated in graphics.h; the
- // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
- virtual status_t setDefaultBufferFormat(uint32_t defaultFormat);
-
- // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
- // These are merged with the bits passed to dequeueBuffer. The values are
- // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
- virtual status_t setConsumerUsageBits(uint32_t usage);
-
- // setTransformHint bakes in rotation to buffers so overlays can be used.
- // The values are enumerated in window.h, e.g.
- // NATIVE_WINDOW_TRANSFORM_ROT_90. The default is 0 (no transform).
- virtual status_t setTransformHint(uint32_t hint);
-
- // Retrieve the sideband buffer stream, if any.
- virtual sp<NativeHandle> getSidebandStream() const;
-
- // dump our state in a String
- virtual void dumpToString(String8& result, const char* prefix) const;
-
- // Added by mozilla
- virtual already_AddRefed<GonkBufferSlot::TextureClient> getTextureClientFromBuffer(ANativeWindowBuffer* buffer);
-
- virtual int getSlotFromTextureClientLocked(GonkBufferSlot::TextureClient* client) const;
-
- // Functions required for backwards compatibility.
- // These will be modified/renamed in IGonkGraphicBufferConsumer and will be
- // removed from this class at that time. See b/13306289.
- virtual status_t consumerConnect(const sp<IConsumerListener>& consumer,
- bool controlledByApp) {
- return connect(consumer, controlledByApp);
- }
-
- virtual status_t consumerDisconnect() { return disconnect(); }
-
- // End functions required for backwards compatibility
-
-private:
- sp<GonkBufferQueueCore> mCore;
-
- // This references mCore->mSlots. Lock mCore->mMutex while accessing.
- GonkBufferQueueDefs::SlotsType& mSlots;
-
- // This is a cached copy of the name stored in the GonkBufferQueueCore.
- // It's updated during setConsumerName.
- String8 mConsumerName;
-
-}; // class GonkBufferQueueConsumer
-
-} // namespace android
-
-#endif
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp
deleted file mode 100644
index 9e8e337f6..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.cpp
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "GonkBufferQueueCore"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-//#define LOG_NDEBUG 0
-
-#include <inttypes.h>
-
-#include "GonkBufferItem.h"
-#include "GonkBufferQueueCore.h"
-#include <gui/IConsumerListener.h>
-#include <gui/IGraphicBufferAlloc.h>
-#include <gui/IProducerListener.h>
-#include <gui/ISurfaceComposer.h>
-#include <private/gui/ComposerService.h>
-
-#include <cutils/compiler.h>
-#include "mozilla/layers/GrallocTextureClient.h"
-#include "mozilla/layers/ImageBridgeChild.h"
-
-template <typename T>
-static inline T max(T a, T b) { return a > b ? a : b; }
-
-namespace android {
-
-static String8 getUniqueName() {
- static volatile int32_t counter = 0;
- return String8::format("unnamed-%d-%d", getpid(),
- android_atomic_inc(&counter));
-}
-
-GonkBufferQueueCore::GonkBufferQueueCore(const sp<IGraphicBufferAlloc>& allocator) :
- mAllocator(allocator),
- mMutex(),
- mIsAbandoned(false),
- mConsumerControlledByApp(false),
- mConsumerName(getUniqueName()),
- mConsumerListener(),
- mConsumerUsageBits(0),
- mConnectedApi(NO_CONNECTED_API),
- mConnectedProducerListener(),
- mSlots(),
- mQueue(),
- mOverrideMaxBufferCount(0),
- mDequeueCondition(),
- mUseAsyncBuffer(true),
- mDequeueBufferCannotBlock(false),
- mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),
- mDefaultWidth(1),
- mDefaultHeight(1),
- mDefaultMaxBufferCount(2),
- mMaxAcquiredBufferCount(1),
- mBufferHasBeenQueued(false),
- mFrameCounter(0),
- mTransformHint(0),
- mIsAllocating(false),
- mIsAllocatingCondition()
-{
- ALOGV("GonkBufferQueueCore");
-}
-
-GonkBufferQueueCore::~GonkBufferQueueCore() {}
-
-void GonkBufferQueueCore::dump(String8& result, const char* prefix) const {
- Mutex::Autolock lock(mMutex);
-
- String8 fifo;
- Fifo::const_iterator current(mQueue.begin());
- while (current != mQueue.end()) {
- fifo.appendFormat("%02d:%p crop=[%d,%d,%d,%d], "
- "xform=0x%02x, time=%#" PRIx64 ", scale=%s\n",
- current->mSlot, current->mGraphicBuffer.get(),
- current->mCrop.left, current->mCrop.top, current->mCrop.right,
- current->mCrop.bottom, current->mTransform, current->mTimestamp,
- GonkBufferItem::scalingModeName(current->mScalingMode));
- ++current;
- }
-
- result.appendFormat("%s-GonkBufferQueue mMaxAcquiredBufferCount=%d, "
- "mDequeueBufferCannotBlock=%d, default-size=[%dx%d], "
- "default-format=%d, transform-hint=%02x, FIFO(%zu)={%s}\n",
- prefix, mMaxAcquiredBufferCount, mDequeueBufferCannotBlock,
- mDefaultWidth, mDefaultHeight, mDefaultBufferFormat, mTransformHint,
- mQueue.size(), fifo.string());
-
- // Trim the free buffers so as to not spam the dump
- int maxBufferCount = 0;
- for (int s = GonkBufferQueueDefs::NUM_BUFFER_SLOTS - 1; s >= 0; --s) {
- const GonkBufferSlot& slot(mSlots[s]);
- if (slot.mBufferState != GonkBufferSlot::FREE ||
- slot.mGraphicBuffer != NULL) {
- maxBufferCount = s + 1;
- break;
- }
- }
-
- for (int s = 0; s < maxBufferCount; ++s) {
- const GonkBufferSlot& slot(mSlots[s]);
- const sp<GraphicBuffer>& buffer(slot.mGraphicBuffer);
- result.appendFormat("%s%s[%02d:%p] state=%-8s", prefix,
- (slot.mBufferState == GonkBufferSlot::ACQUIRED) ? ">" : " ",
- s, buffer.get(),
- GonkBufferSlot::bufferStateName(slot.mBufferState));
-
- if (buffer != NULL) {
- result.appendFormat(", %p [%4ux%4u:%4u,%3X]", buffer->handle,
- buffer->width, buffer->height, buffer->stride,
- buffer->format);
- }
-
- result.append("\n");
- }
-}
-
-int GonkBufferQueueCore::getMinUndequeuedBufferCountLocked(bool async) const {
- // If dequeueBuffer is allowed to error out, we don't have to add an
- // extra buffer.
- if (!mUseAsyncBuffer) {
- return mMaxAcquiredBufferCount;
- }
-
- if (mDequeueBufferCannotBlock || async) {
- return mMaxAcquiredBufferCount + 1;
- }
-
- return mMaxAcquiredBufferCount;
-}
-
-int GonkBufferQueueCore::getMinMaxBufferCountLocked(bool async) const {
- return getMinUndequeuedBufferCountLocked(async) + 1;
-}
-
-int GonkBufferQueueCore::getMaxBufferCountLocked(bool async) const {
- int minMaxBufferCount = getMinMaxBufferCountLocked(async);
-
- int maxBufferCount = max(mDefaultMaxBufferCount, minMaxBufferCount);
- if (mOverrideMaxBufferCount != 0) {
- assert(mOverrideMaxBufferCount >= minMaxBufferCount);
- maxBufferCount = mOverrideMaxBufferCount;
- }
-
- // Any buffers that are dequeued by the producer or sitting in the queue
- // waiting to be consumed need to have their slots preserved. Such buffers
- // will temporarily keep the max buffer count up until the slots no longer
- // need to be preserved.
- for (int s = maxBufferCount; s < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
- GonkBufferSlot::BufferState state = mSlots[s].mBufferState;
- if (state == GonkBufferSlot::QUEUED || state == GonkBufferSlot::DEQUEUED) {
- maxBufferCount = s + 1;
- }
- }
-
- return maxBufferCount;
-}
-
-status_t GonkBufferQueueCore::setDefaultMaxBufferCountLocked(int count) {
- const int minBufferCount = 2;
- if (count < minBufferCount || count > GonkBufferQueueDefs::NUM_BUFFER_SLOTS) {
- ALOGV("setDefaultMaxBufferCount: invalid count %d, should be in "
- "[%d, %d]",
- count, minBufferCount, GonkBufferQueueDefs::NUM_BUFFER_SLOTS);
- return BAD_VALUE;
- }
-
- ALOGV("setDefaultMaxBufferCount: setting count to %d", count);
- mDefaultMaxBufferCount = count;
- mDequeueCondition.broadcast();
-
- return NO_ERROR;
-}
-
-void GonkBufferQueueCore::freeBufferLocked(int slot) {
- ALOGV("freeBufferLocked: slot %d", slot);
-
- if (mSlots[slot].mTextureClient) {
- mSlots[slot].mTextureClient->ClearRecycleCallback();
- // release TextureClient in ImageBridge thread
- RefPtr<TextureClientReleaseTask> task =
- MakeAndAddRef<TextureClientReleaseTask>(mSlots[slot].mTextureClient);
- mSlots[slot].mTextureClient = NULL;
- ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget());
- }
- mSlots[slot].mGraphicBuffer.clear();
- if (mSlots[slot].mBufferState == GonkBufferSlot::ACQUIRED) {
- mSlots[slot].mNeedsCleanupOnRelease = true;
- }
- mSlots[slot].mBufferState = GonkBufferSlot::FREE;
- mSlots[slot].mFrameNumber = UINT32_MAX;
- mSlots[slot].mAcquireCalled = false;
-
- // Destroy fence as GonkBufferQueue now takes ownership
- mSlots[slot].mFence = Fence::NO_FENCE;
-}
-
-void GonkBufferQueueCore::freeAllBuffersLocked() {
- ALOGW_IF(!mQueue.isEmpty(),
- "freeAllBuffersLocked called but mQueue is not empty");
- mQueue.clear();
- mBufferHasBeenQueued = false;
- for (int s = 0; s < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
- freeBufferLocked(s);
- }
-}
-
-bool GonkBufferQueueCore::stillTracking(const GonkBufferItem* item) const {
- const GonkBufferSlot& slot = mSlots[item->mSlot];
-
- ALOGV("stillTracking: item { slot=%d/%" PRIu64 " buffer=%p } "
- "slot { slot=%d/%" PRIu64 " buffer=%p }",
- item->mSlot, item->mFrameNumber,
- (item->mGraphicBuffer.get() ? item->mGraphicBuffer->handle : 0),
- item->mSlot, slot.mFrameNumber,
- (slot.mGraphicBuffer.get() ? slot.mGraphicBuffer->handle : 0));
-
- // Compare item with its original buffer slot. We can check the slot as
- // the buffer would not be moved to a different slot by the producer.
- return (slot.mGraphicBuffer != NULL) &&
- (item->mGraphicBuffer->handle == slot.mGraphicBuffer->handle);
-}
-
-void GonkBufferQueueCore::waitWhileAllocatingLocked() const {
- ATRACE_CALL();
- while (mIsAllocating) {
- mIsAllocatingCondition.wait(mMutex);
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.h b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.h
deleted file mode 100644
index 936e11686..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueCore.h
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKBUFFERQUEUECORE_LL_H
-#define NATIVEWINDOW_GONKBUFFERQUEUECORE_LL_H
-
-#include "GonkBufferQueueDefs.h"
-#include "GonkBufferSlot.h"
-
-#include <utils/Condition.h>
-#include <utils/Mutex.h>
-#include <utils/NativeHandle.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-#include <utils/StrongPointer.h>
-#include <utils/Trace.h>
-#include <utils/Vector.h>
-
-#include "mozilla/layers/TextureClient.h"
-
-#define ATRACE_BUFFER_INDEX(index)
-
-using namespace mozilla;
-using namespace mozilla::gfx;
-using namespace mozilla::layers;
-
-namespace android {
-
-class GonkBufferItem;
-class IConsumerListener;
-class IGraphicBufferAlloc;
-class IProducerListener;
-
-class GonkBufferQueueCore : public virtual RefBase {
-
- friend class GonkBufferQueueProducer;
- friend class GonkBufferQueueConsumer;
-
-public:
- // Used as a placeholder slot number when the value isn't pointing to an
- // existing buffer.
- enum { INVALID_BUFFER_SLOT = -1 }; // TODO: Extract from IGBC::BufferItem
-
- // We reserve two slots in order to guarantee that the producer and
- // consumer can run asynchronously.
- enum { MAX_MAX_ACQUIRED_BUFFERS = GonkBufferQueueDefs::NUM_BUFFER_SLOTS - 2 };
-
- // The default API number used to indicate that no producer is connected
- enum { NO_CONNECTED_API = 0 };
-
- typedef Vector<GonkBufferItem> Fifo;
- typedef mozilla::layers::TextureClient TextureClient;
-
- // GonkBufferQueueCore manages a pool of gralloc memory slots to be used by
- // producers and consumers. allocator is used to allocate all the needed
- // gralloc buffers.
- GonkBufferQueueCore(const sp<IGraphicBufferAlloc>& allocator = NULL);
- virtual ~GonkBufferQueueCore();
-
-private:
- // Dump our state in a string
- void dump(String8& result, const char* prefix) const;
-
- int getSlotFromTextureClientLocked(TextureClient* client) const;
-
- // getMinUndequeuedBufferCountLocked returns the minimum number of buffers
- // that must remain in a state other than DEQUEUED. The async parameter
- // tells whether we're in asynchronous mode.
- int getMinUndequeuedBufferCountLocked(bool async) const;
-
- // getMinMaxBufferCountLocked returns the minimum number of buffers allowed
- // given the current GonkBufferQueue state. The async parameter tells whether
- // we're in asynchonous mode.
- int getMinMaxBufferCountLocked(bool async) const;
-
- // getMaxBufferCountLocked returns the maximum number of buffers that can be
- // allocated at once. This value depends on the following member variables:
- //
- // mDequeueBufferCannotBlock
- // mMaxAcquiredBufferCount
- // mDefaultMaxBufferCount
- // mOverrideMaxBufferCount
- // async parameter
- //
- // Any time one of these member variables is changed while a producer is
- // connected, mDequeueCondition must be broadcast.
- int getMaxBufferCountLocked(bool async) const;
-
- // setDefaultMaxBufferCountLocked sets the maximum number of buffer slots
- // that will be used if the producer does not override the buffer slot
- // count. The count must be between 2 and NUM_BUFFER_SLOTS, inclusive. The
- // initial default is 2.
- status_t setDefaultMaxBufferCountLocked(int count);
-
- // freeBufferLocked frees the GraphicBuffer and sync resources for the
- // given slot.
- void freeBufferLocked(int slot);
-
- // freeAllBuffersLocked frees the GraphicBuffer and sync resources for
- // all slots.
- void freeAllBuffersLocked();
-
- // stillTracking returns true iff the buffer item is still being tracked
- // in one of the slots.
- bool stillTracking(const GonkBufferItem* item) const;
-
- // waitWhileAllocatingLocked blocks until mIsAllocating is false.
- void waitWhileAllocatingLocked() const;
-
- // mAllocator is the connection to SurfaceFlinger that is used to allocate
- // new GraphicBuffer objects.
- sp<IGraphicBufferAlloc> mAllocator;
-
- // mMutex is the mutex used to prevent concurrent access to the member
- // variables of GonkBufferQueueCore objects. It must be locked whenever any
- // member variable is accessed.
- mutable Mutex mMutex;
-
- // mIsAbandoned indicates that the GonkBufferQueue will no longer be used to
- // consume image buffers pushed to it using the IGraphicBufferProducer
- // interface. It is initialized to false, and set to true in the
- // consumerDisconnect method. A GonkBufferQueue that is abandoned will return
- // the NO_INIT error from all IGraphicBufferProducer methods capable of
- // returning an error.
- bool mIsAbandoned;
-
- // mConsumerControlledByApp indicates whether the connected consumer is
- // controlled by the application.
- bool mConsumerControlledByApp;
-
- // mConsumerName is a string used to identify the GonkBufferQueue in log
- // messages. It is set by the IGraphicBufferConsumer::setConsumerName
- // method.
- String8 mConsumerName;
-
- // mConsumerListener is used to notify the connected consumer of
- // asynchronous events that it may wish to react to. It is initially
- // set to NULL and is written by consumerConnect and consumerDisconnect.
- sp<IConsumerListener> mConsumerListener;
-
- // mConsumerUsageBits contains flags that the consumer wants for
- // GraphicBuffers.
- uint32_t mConsumerUsageBits;
-
- // mConnectedApi indicates the producer API that is currently connected
- // to this GonkBufferQueue. It defaults to NO_CONNECTED_API, and gets updated
- // by the connect and disconnect methods.
- int mConnectedApi;
-
- // mConnectedProducerToken is used to set a binder death notification on
- // the producer.
- sp<IProducerListener> mConnectedProducerListener;
-
- // mSlots is an array of buffer slots that must be mirrored on the producer
- // side. This allows buffer ownership to be transferred between the producer
- // and consumer without sending a GraphicBuffer over Binder. The entire
- // array is initialized to NULL at construction time, and buffers are
- // allocated for a slot when requestBuffer is called with that slot's index.
- GonkBufferQueueDefs::SlotsType mSlots;
-
- // mQueue is a FIFO of queued buffers used in synchronous mode.
- Fifo mQueue;
-
- // mOverrideMaxBufferCount is the limit on the number of buffers that will
- // be allocated at one time. This value is set by the producer by calling
- // setBufferCount. The default is 0, which means that the producer doesn't
- // care about the number of buffers in the pool. In that case,
- // mDefaultMaxBufferCount is used as the limit.
- int mOverrideMaxBufferCount;
-
- // mDequeueCondition is a condition variable used for dequeueBuffer in
- // synchronous mode.
- mutable Condition mDequeueCondition;
-
- // mUseAsyncBuffer indicates whether an extra buffer is used in async mode
- // to prevent dequeueBuffer from blocking.
- bool mUseAsyncBuffer;
-
- // mDequeueBufferCannotBlock indicates whether dequeueBuffer is allowed to
- // block. This flag is set during connect when both the producer and
- // consumer are controlled by the application.
- bool mDequeueBufferCannotBlock;
-
- // mDefaultBufferFormat can be set so it will override the buffer format
- // when it isn't specified in dequeueBuffer.
- uint32_t mDefaultBufferFormat;
-
- // mDefaultWidth holds the default width of allocated buffers. It is used
- // in dequeueBuffer if a width and height of 0 are specified.
- int mDefaultWidth;
-
- // mDefaultHeight holds the default height of allocated buffers. It is used
- // in dequeueBuffer if a width and height of 0 are specified.
- int mDefaultHeight;
-
- // mDefaultMaxBufferCount is the default limit on the number of buffers that
- // will be allocated at one time. This default limit is set by the consumer.
- // The limit (as opposed to the default limit) may be overriden by the
- // producer.
- int mDefaultMaxBufferCount;
-
- // mMaxAcquiredBufferCount is the number of buffers that the consumer may
- // acquire at one time. It defaults to 1, and can be changed by the consumer
- // via setMaxAcquiredBufferCount, but this may only be done while no
- // producer is connected to the GonkBufferQueue. This value is used to derive
- // the value returned for the MIN_UNDEQUEUED_BUFFERS query to the producer.
- int mMaxAcquiredBufferCount;
-
- // mBufferHasBeenQueued is true once a buffer has been queued. It is reset
- // when something causes all buffers to be freed (e.g., changing the buffer
- // count).
- bool mBufferHasBeenQueued;
-
- // mFrameCounter is the free running counter, incremented on every
- // successful queueBuffer call and buffer allocation.
- uint64_t mFrameCounter;
-
- // mTransformHint is used to optimize for screen rotations.
- uint32_t mTransformHint;
-
- // mSidebandStream is a handle to the sideband buffer stream, if any
- sp<NativeHandle> mSidebandStream;
-
- // mIsAllocating indicates whether a producer is currently trying to allocate buffers (which
- // releases mMutex while doing the allocation proper). Producers should not modify any of the
- // FREE slots while this is true. mIsAllocatingCondition is signaled when this value changes to
- // false.
- bool mIsAllocating;
-
- // mIsAllocatingCondition is a condition variable used by producers to wait until mIsAllocating
- // becomes false.
- mutable Condition mIsAllocatingCondition;
-}; // class GonkBufferQueueCore
-
-} // namespace android
-
-#endif
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueDefs.h b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueDefs.h
deleted file mode 100644
index 60085706f..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueDefs.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_BUFFERQUEUECOREDEFS_H
-#define NATIVEWINDOW_BUFFERQUEUECOREDEFS_H
-
-#include "GonkBufferSlot.h"
-
-namespace android {
- class GonkBufferQueueCore;
-
- namespace GonkBufferQueueDefs {
- // GonkBufferQueue will keep track of at most this value of buffers.
- // Attempts at runtime to increase the number of buffers past this
- // will fail.
- enum { NUM_BUFFER_SLOTS = 64 };
-
- typedef GonkBufferSlot SlotsType[NUM_BUFFER_SLOTS];
- } // namespace GonkBufferQueueDefs
-} // namespace android
-
-#endif
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.cpp b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.cpp
deleted file mode 100644
index 649d06bee..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "GonkBufferQueue"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-#define LOG_NDEBUG 0
-
-#include "GonkBufferQueue.h"
-#include "GonkBufferQueueConsumer.h"
-#include "GonkBufferQueueCore.h"
-#include "GonkBufferQueueProducer.h"
-
-namespace android {
-
-GonkBufferQueue::ProxyConsumerListener::ProxyConsumerListener(
- const wp<ConsumerListener>& consumerListener):
- mConsumerListener(consumerListener) {}
-
-GonkBufferQueue::ProxyConsumerListener::~ProxyConsumerListener() {}
-
-#if ANDROID_VERSION == 21
-void GonkBufferQueue::ProxyConsumerListener::onFrameAvailable() {
- sp<ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onFrameAvailable();
- }
-}
-#else
-void GonkBufferQueue::ProxyConsumerListener::onFrameAvailable(const ::android::BufferItem& item) {
- sp<ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onFrameAvailable(item);
- }
-}
-
-void GonkBufferQueue::ProxyConsumerListener::onFrameReplaced(const ::android::BufferItem& item) {
- sp<ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onFrameReplaced(item);
- }
-}
-#endif
-
-void GonkBufferQueue::ProxyConsumerListener::onBuffersReleased() {
- sp<ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-}
-
-void GonkBufferQueue::ProxyConsumerListener::onSidebandStreamChanged() {
- sp<ConsumerListener> listener(mConsumerListener.promote());
- if (listener != NULL) {
- listener->onSidebandStreamChanged();
- }
-}
-
-void GonkBufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
- sp<IGonkGraphicBufferConsumer>* outConsumer,
- const sp<IGraphicBufferAlloc>& allocator) {
- LOG_ALWAYS_FATAL_IF(outProducer == NULL,
- "GonkBufferQueue: outProducer must not be NULL");
- LOG_ALWAYS_FATAL_IF(outConsumer == NULL,
- "GonkBufferQueue: outConsumer must not be NULL");
-
- sp<GonkBufferQueueCore> core(new GonkBufferQueueCore(allocator));
- LOG_ALWAYS_FATAL_IF(core == NULL,
- "GonkBufferQueue: failed to create GonkBufferQueueCore");
-
- sp<IGraphicBufferProducer> producer(new GonkBufferQueueProducer(core));
- LOG_ALWAYS_FATAL_IF(producer == NULL,
- "GonkBufferQueue: failed to create GonkBufferQueueProducer");
-
- sp<IGonkGraphicBufferConsumer> consumer(new GonkBufferQueueConsumer(core));
- LOG_ALWAYS_FATAL_IF(consumer == NULL,
- "GonkBufferQueue: failed to create GonkBufferQueueConsumer");
-
- *outProducer = producer;
- *outConsumer = consumer;
-}
-
-}; // namespace android
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.h b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.h
deleted file mode 100644
index b1b4e06b5..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueLL.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKBUFFERQUEUE_LL_H
-#define NATIVEWINDOW_GONKBUFFERQUEUE_LL_H
-
-#include "GonkBufferQueueDefs.h"
-#include "IGonkGraphicBufferConsumerLL.h"
-#include <gui/IGraphicBufferProducer.h>
-#include <gui/IConsumerListener.h>
-
-// These are only required to keep other parts of the framework with incomplete
-// dependencies building successfully
-#include <gui/IGraphicBufferAlloc.h>
-
-namespace android {
-
-class GonkBufferQueue {
-public:
- // GonkBufferQueue will keep track of at most this value of buffers.
- // Attempts at runtime to increase the number of buffers past this will fail.
- enum { NUM_BUFFER_SLOTS = GonkBufferQueueDefs::NUM_BUFFER_SLOTS };
- // Used as a placeholder slot# when the value isn't pointing to an existing buffer.
- enum { INVALID_BUFFER_SLOT = IGonkGraphicBufferConsumer::BufferItem::INVALID_BUFFER_SLOT };
- // Alias to <IGonkGraphicBufferConsumer.h> -- please scope from there in future code!
- enum {
- NO_BUFFER_AVAILABLE = IGonkGraphicBufferConsumer::NO_BUFFER_AVAILABLE,
- PRESENT_LATER = IGonkGraphicBufferConsumer::PRESENT_LATER,
- };
-
- // When in async mode we reserve two slots in order to guarantee that the
- // producer and consumer can run asynchronously.
- enum { MAX_MAX_ACQUIRED_BUFFERS = NUM_BUFFER_SLOTS - 2 };
-
- // for backward source compatibility
- typedef ::android::ConsumerListener ConsumerListener;
- typedef IGonkGraphicBufferConsumer::BufferItem BufferItem;
-
- // ProxyConsumerListener is a ConsumerListener implementation that keeps a weak
- // reference to the actual consumer object. It forwards all calls to that
- // consumer object so long as it exists.
- //
- // This class exists to avoid having a circular reference between the
- // GonkBufferQueue object and the consumer object. The reason this can't be a weak
- // reference in the GonkBufferQueue class is because we're planning to expose the
- // consumer side of a GonkBufferQueue as a binder interface, which doesn't support
- // weak references.
- class ProxyConsumerListener : public BnConsumerListener {
- public:
- ProxyConsumerListener(const wp<ConsumerListener>& consumerListener);
- virtual ~ProxyConsumerListener();
-#if ANDROID_VERSION == 21
- virtual void onFrameAvailable();
-#else
- virtual void onFrameAvailable(const ::android::BufferItem& item);
- virtual void onFrameReplaced(const ::android::BufferItem& item);
-#endif
- virtual void onBuffersReleased();
- virtual void onSidebandStreamChanged();
- private:
- // mConsumerListener is a weak reference to the IConsumerListener. This is
- // the raison d'etre of ProxyConsumerListener.
- wp<ConsumerListener> mConsumerListener;
- };
-
- // GonkBufferQueue manages a pool of gralloc memory slots to be used by
- // producers and consumers. allocator is used to allocate all the
- // needed gralloc buffers.
- static void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
- sp<IGonkGraphicBufferConsumer>* outConsumer,
- const sp<IGraphicBufferAlloc>& allocator = NULL);
-
-private:
- GonkBufferQueue(); // Create through createBufferQueue
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // NATIVEWINDOW_GONKBUFFERQUEUE_LL_H
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp
deleted file mode 100644
index d3436756f..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.cpp
+++ /dev/null
@@ -1,886 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <inttypes.h>
-
-#define LOG_TAG "GonkBufferQueueProducer"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-//#define LOG_NDEBUG 0
-
-#include "GonkBufferItem.h"
-#include "GonkBufferQueueCore.h"
-#include "GonkBufferQueueProducer.h"
-#include <gui/IConsumerListener.h>
-#include <gui/IGraphicBufferAlloc.h>
-#include <gui/IProducerListener.h>
-
-#include <cutils/compiler.h>
-#include <utils/Log.h>
-#include <utils/Trace.h>
-
-#include "mozilla/layers/GrallocTextureClient.h"
-#include "mozilla/layers/ImageBridgeChild.h"
-#include "mozilla/layers/TextureClient.h"
-
-namespace android {
-
-GonkBufferQueueProducer::GonkBufferQueueProducer(const sp<GonkBufferQueueCore>& core) :
- mCore(core),
- mSlots(core->mSlots),
- mConsumerName(),
- mSynchronousMode(true),
- mStickyTransform(0) {}
-
-GonkBufferQueueProducer::~GonkBufferQueueProducer() {}
-
-status_t GonkBufferQueueProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
- ATRACE_CALL();
- ALOGV("requestBuffer: slot %d", slot);
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("requestBuffer: GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- if (slot < 0 || slot >= GonkBufferQueueDefs::NUM_BUFFER_SLOTS) {
- ALOGE("requestBuffer: slot index %d out of range [0, %d)",
- slot, GonkBufferQueueDefs::NUM_BUFFER_SLOTS);
- return BAD_VALUE;
- } else if (mSlots[slot].mBufferState != GonkBufferSlot::DEQUEUED) {
- ALOGE("requestBuffer: slot %d is not owned by the producer "
- "(state = %d)", slot, mSlots[slot].mBufferState);
- return BAD_VALUE;
- }
-
- mSlots[slot].mRequestBufferCalled = true;
- *buf = mSlots[slot].mGraphicBuffer;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueProducer::setBufferCount(int bufferCount) {
- ATRACE_CALL();
- ALOGV("setBufferCount: count = %d", bufferCount);
-
- sp<IConsumerListener> listener;
- { // Autolock scope
- Mutex::Autolock lock(mCore->mMutex);
- mCore->waitWhileAllocatingLocked();
-
- if (mCore->mIsAbandoned) {
- ALOGE("setBufferCount: GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- if (bufferCount > GonkBufferQueueDefs::NUM_BUFFER_SLOTS) {
- ALOGE("setBufferCount: bufferCount %d too large (max %d)",
- bufferCount, GonkBufferQueueDefs::NUM_BUFFER_SLOTS);
- return BAD_VALUE;
- }
-
- // There must be no dequeued buffers when changing the buffer count.
- for (int s = 0; s < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
- if (mSlots[s].mBufferState == GonkBufferSlot::DEQUEUED) {
- ALOGE("setBufferCount: buffer owned by producer");
- return BAD_VALUE;
- }
- }
-
- if (bufferCount == 0) {
- mCore->mOverrideMaxBufferCount = 0;
- mCore->mDequeueCondition.broadcast();
- return NO_ERROR;
- }
-
- const int minBufferSlots = mCore->getMinMaxBufferCountLocked(false);
- if (bufferCount < minBufferSlots) {
- ALOGE("setBufferCount: requested buffer count %d is less than "
- "minimum %d", bufferCount, minBufferSlots);
- return BAD_VALUE;
- }
-
- // Here we are guaranteed that the producer doesn't have any dequeued
- // buffers and will release all of its buffer references. We don't
- // clear the queue, however, so that currently queued buffers still
- // get displayed.
- mCore->freeAllBuffersLocked();
- mCore->mOverrideMaxBufferCount = bufferCount;
- mCore->mDequeueCondition.broadcast();
- listener = mCore->mConsumerListener;
- } // Autolock scope
-
- // Call back without lock held
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueProducer::waitForFreeSlotThenRelock(const char* caller,
- bool async, int* found, status_t* returnFlags) const {
- bool tryAgain = true;
- while (tryAgain) {
- if (mCore->mIsAbandoned) {
- ALOGE("%s: GonkBufferQueue has been abandoned", caller);
- return NO_INIT;
- }
-
- const int maxBufferCount = mCore->getMaxBufferCountLocked(async);
- if (async && mCore->mOverrideMaxBufferCount) {
- // FIXME: Some drivers are manually setting the buffer count
- // (which they shouldn't), so we do this extra test here to
- // handle that case. This is TEMPORARY until we get this fixed.
- if (mCore->mOverrideMaxBufferCount < maxBufferCount) {
- ALOGE("%s: async mode is invalid with buffer count override",
- caller);
- return BAD_VALUE;
- }
- }
-
- // Free up any buffers that are in slots beyond the max buffer count
- //for (int s = maxBufferCount; s < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
- // assert(mSlots[s].mBufferState == GonkBufferSlot::FREE);
- // if (mSlots[s].mGraphicBuffer != NULL) {
- // mCore->freeBufferLocked(s);
- // *returnFlags |= RELEASE_ALL_BUFFERS;
- // }
- //}
-
- // Look for a free buffer to give to the client
- *found = GonkBufferQueueCore::INVALID_BUFFER_SLOT;
- int dequeuedCount = 0;
- int acquiredCount = 0;
- for (int s = 0; s < maxBufferCount; ++s) {
- switch (mSlots[s].mBufferState) {
- case GonkBufferSlot::DEQUEUED:
- ++dequeuedCount;
- break;
- case GonkBufferSlot::ACQUIRED:
- ++acquiredCount;
- break;
- case GonkBufferSlot::FREE:
- // We return the oldest of the free buffers to avoid
- // stalling the producer if possible, since the consumer
- // may still have pending reads of in-flight buffers
- if (*found == GonkBufferQueueCore::INVALID_BUFFER_SLOT ||
- mSlots[s].mFrameNumber < mSlots[*found].mFrameNumber) {
- *found = s;
- }
- break;
- default:
- break;
- }
- }
-
- // Producers are not allowed to dequeue more than one buffer if they
- // did not set a buffer count
- if (!mCore->mOverrideMaxBufferCount && dequeuedCount) {
- ALOGE("%s: can't dequeue multiple buffers without setting the "
- "buffer count", caller);
- return INVALID_OPERATION;
- }
-
- // See whether a buffer has been queued since the last
- // setBufferCount so we know whether to perform the min undequeued
- // buffers check below
- if (mCore->mBufferHasBeenQueued) {
- // Make sure the producer is not trying to dequeue more buffers
- // than allowed
- const int newUndequeuedCount =
- maxBufferCount - (dequeuedCount + 1);
- const int minUndequeuedCount =
- mCore->getMinUndequeuedBufferCountLocked(async);
- if (newUndequeuedCount < minUndequeuedCount) {
- ALOGE("%s: min undequeued buffer count (%d) exceeded "
- "(dequeued=%d undequeued=%d)",
- caller, minUndequeuedCount,
- dequeuedCount, newUndequeuedCount);
- return INVALID_OPERATION;
- }
- }
-
- // If we disconnect and reconnect quickly, we can be in a state where
- // our slots are empty but we have many buffers in the queue. This can
- // cause us to run out of memory if we outrun the consumer. Wait here if
- // it looks like we have too many buffers queued up.
- bool tooManyBuffers = mCore->mQueue.size()
- > static_cast<size_t>(maxBufferCount);
- if (tooManyBuffers) {
- ALOGV("%s: queue size is %zu, waiting", caller,
- mCore->mQueue.size());
- }
-
- // If no buffer is found, or if the queue has too many buffers
- // outstanding, wait for a buffer to be acquired or released, or for the
- // max buffer count to change.
- tryAgain = (*found == GonkBufferQueueCore::INVALID_BUFFER_SLOT) ||
- tooManyBuffers;
- if (tryAgain) {
- // Return an error if we're in non-blocking mode (producer and
- // consumer are controlled by the application).
- // However, the consumer is allowed to briefly acquire an extra
- // buffer (which could cause us to have to wait here), which is
- // okay, since it is only used to implement an atomic acquire +
- // release (e.g., in GLConsumer::updateTexImage())
- if (mCore->mDequeueBufferCannotBlock &&
- (acquiredCount <= mCore->mMaxAcquiredBufferCount)) {
- return WOULD_BLOCK;
- }
- mCore->mDequeueCondition.wait(mCore->mMutex);
- }
- } // while (tryAgain)
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueProducer::dequeueBuffer(int *outSlot,
- sp<android::Fence> *outFence, bool async,
- uint32_t width, uint32_t height, uint32_t format, uint32_t usage) {
- ATRACE_CALL();
- { // Autolock scope
- Mutex::Autolock lock(mCore->mMutex);
- mConsumerName = mCore->mConsumerName;
- } // Autolock scope
-
- ALOGV("dequeueBuffer: async=%s w=%u h=%u format=%#x, usage=%#x",
- async ? "true" : "false", width, height, format, usage);
-
- if ((width && !height) || (!width && height)) {
- ALOGE("dequeueBuffer: invalid size: w=%u h=%u", width, height);
- return BAD_VALUE;
- }
-
- status_t returnFlags = NO_ERROR;
- // Reset slot
- *outSlot = GonkBufferQueueCore::INVALID_BUFFER_SLOT;
-
- bool attachedByConsumer = false;
-
- { // Autolock scope
- Mutex::Autolock lock(mCore->mMutex);
- mCore->waitWhileAllocatingLocked();
-
- if (format == 0) {
- format = mCore->mDefaultBufferFormat;
- }
-
- // Enable the usage bits the consumer requested
- usage |= mCore->mConsumerUsageBits;
-
- int found;
- status_t status = waitForFreeSlotThenRelock("dequeueBuffer", async,
- &found, &returnFlags);
- if (status != NO_ERROR) {
- return status;
- }
-
- // This should not happen
- if (found == GonkBufferQueueCore::INVALID_BUFFER_SLOT) {
- ALOGE("dequeueBuffer: no available buffer slots");
- return -EBUSY;
- }
-
- *outSlot = found;
-
- attachedByConsumer = mSlots[found].mAttachedByConsumer;
-
- const bool useDefaultSize = !width && !height;
- if (useDefaultSize) {
- width = mCore->mDefaultWidth;
- height = mCore->mDefaultHeight;
- }
-
- mSlots[found].mBufferState = GonkBufferSlot::DEQUEUED;
-
- const sp<GraphicBuffer>& buffer(mSlots[found].mGraphicBuffer);
- if ((buffer == NULL) ||
- (static_cast<uint32_t>(buffer->width) != width) ||
- (static_cast<uint32_t>(buffer->height) != height) ||
- (static_cast<uint32_t>(buffer->format) != format) ||
- ((static_cast<uint32_t>(buffer->usage) & usage) != usage))
- {
- mSlots[found].mAcquireCalled = false;
- mSlots[found].mGraphicBuffer = NULL;
- mSlots[found].mRequestBufferCalled = false;
- mSlots[found].mFence = Fence::NO_FENCE;
-
- if (mSlots[found].mTextureClient) {
- mSlots[found].mTextureClient->ClearRecycleCallback();
- // release TextureClient in ImageBridge thread
- RefPtr<TextureClientReleaseTask> task =
- MakeAndAddRef<TextureClientReleaseTask>(mSlots[found].mTextureClient);
- mSlots[found].mTextureClient = NULL;
- ImageBridgeChild::GetSingleton()->GetMessageLoop()->PostTask(task.forget());
- }
-
- returnFlags |= BUFFER_NEEDS_REALLOCATION;
- }
-
- if (CC_UNLIKELY(mSlots[found].mFence == NULL)) {
- ALOGE("dequeueBuffer: about to return a NULL fence - "
- "slot=%d w=%d h=%d format=%u",
- found, buffer->width, buffer->height, buffer->format);
- }
-
- *outFence = mSlots[found].mFence;
- mSlots[found].mFence = Fence::NO_FENCE;
- } // Autolock scope
-
- if (returnFlags & BUFFER_NEEDS_REALLOCATION) {
- RefPtr<LayersIPCChannel> allocator = ImageBridgeChild::GetSingleton();
- usage |= GraphicBuffer::USAGE_HW_TEXTURE;
- GrallocTextureData* texData = GrallocTextureData::Create(IntSize(width,height), format,
- gfx::BackendType::NONE,
- usage, allocator);
- if (!texData) {
- ALOGE("dequeueBuffer: failed to alloc gralloc buffer");
- return -ENOMEM;
- }
- RefPtr<TextureClient> textureClient = TextureClient::CreateWithData(
- texData, TextureFlags::RECYCLE | TextureFlags::DEALLOCATE_CLIENT, allocator);
-
- sp<GraphicBuffer> graphicBuffer = texData->GetGraphicBuffer();
-
- { // Autolock scope
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("dequeueBuffer: GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- mSlots[*outSlot].mFrameNumber = UINT32_MAX;
- mSlots[*outSlot].mGraphicBuffer = graphicBuffer;
- mSlots[*outSlot].mTextureClient = textureClient;
- } // Autolock scope
- }
-
- if (attachedByConsumer) {
- returnFlags |= BUFFER_NEEDS_REALLOCATION;
- }
-
- ALOGV("dequeueBuffer: returning slot=%d/%" PRIu64 " buf=%p flags=%#x",
- *outSlot,
- mSlots[*outSlot].mFrameNumber,
- mSlots[*outSlot].mGraphicBuffer->handle, returnFlags);
-
- return returnFlags;
-}
-
-status_t GonkBufferQueueProducer::detachBuffer(int slot) {
- ATRACE_CALL();
- ATRACE_BUFFER_INDEX(slot);
- ALOGV("detachBuffer(P): slot %d", slot);
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("detachBuffer(P): GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- if (slot < 0 || slot >= GonkBufferQueueDefs::NUM_BUFFER_SLOTS) {
- ALOGE("detachBuffer(P): slot index %d out of range [0, %d)",
- slot, GonkBufferQueueDefs::NUM_BUFFER_SLOTS);
- return BAD_VALUE;
- } else if (mSlots[slot].mBufferState != GonkBufferSlot::DEQUEUED) {
- ALOGE("detachBuffer(P): slot %d is not owned by the producer "
- "(state = %d)", slot, mSlots[slot].mBufferState);
- return BAD_VALUE;
- } else if (!mSlots[slot].mRequestBufferCalled) {
- ALOGE("detachBuffer(P): buffer in slot %d has not been requested",
- slot);
- return BAD_VALUE;
- }
-
- mCore->freeBufferLocked(slot);
- mCore->mDequeueCondition.broadcast();
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueProducer::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
- sp<Fence>* outFence) {
- ATRACE_CALL();
-
- if (outBuffer == NULL) {
- ALOGE("detachNextBuffer: outBuffer must not be NULL");
- return BAD_VALUE;
- } else if (outFence == NULL) {
- ALOGE("detachNextBuffer: outFence must not be NULL");
- return BAD_VALUE;
- }
-
- Mutex::Autolock lock(mCore->mMutex);
- mCore->waitWhileAllocatingLocked();
-
- if (mCore->mIsAbandoned) {
- ALOGE("detachNextBuffer: GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- // Find the oldest valid slot
- int found = GonkBufferQueueCore::INVALID_BUFFER_SLOT;
- for (int s = 0; s < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
- if (mSlots[s].mBufferState == GonkBufferSlot::FREE &&
- mSlots[s].mGraphicBuffer != NULL) {
- if (found == GonkBufferQueueCore::INVALID_BUFFER_SLOT ||
- mSlots[s].mFrameNumber < mSlots[found].mFrameNumber) {
- found = s;
- }
- }
- }
-
- if (found == GonkBufferQueueCore::INVALID_BUFFER_SLOT) {
- return NO_MEMORY;
- }
-
- ALOGV("detachNextBuffer detached slot %d", found);
-
- *outBuffer = mSlots[found].mGraphicBuffer;
- *outFence = mSlots[found].mFence;
- mCore->freeBufferLocked(found);
-
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueProducer::attachBuffer(int* outSlot,
- const sp<android::GraphicBuffer>& buffer) {
- ATRACE_CALL();
-
- if (outSlot == NULL) {
- ALOGE("attachBuffer(P): outSlot must not be NULL");
- return BAD_VALUE;
- } else if (buffer == NULL) {
- ALOGE("attachBuffer(P): cannot attach NULL buffer");
- return BAD_VALUE;
- }
-
- Mutex::Autolock lock(mCore->mMutex);
- mCore->waitWhileAllocatingLocked();
-
- status_t returnFlags = NO_ERROR;
- int found;
- // TODO: Should we provide an async flag to attachBuffer? It seems
- // unlikely that buffers which we are attaching to a GonkBufferQueue will
- // be asynchronous (droppable), but it may not be impossible.
- status_t status = waitForFreeSlotThenRelock("attachBuffer(P)", false,
- &found, &returnFlags);
- if (status != NO_ERROR) {
- return status;
- }
-
- // This should not happen
- if (found == GonkBufferQueueCore::INVALID_BUFFER_SLOT) {
- ALOGE("attachBuffer(P): no available buffer slots");
- return -EBUSY;
- }
-
- *outSlot = found;
- ATRACE_BUFFER_INDEX(*outSlot);
- ALOGV("attachBuffer(P): returning slot %d flags=%#x",
- *outSlot, returnFlags);
-
- mSlots[*outSlot].mGraphicBuffer = buffer;
- mSlots[*outSlot].mBufferState = GonkBufferSlot::DEQUEUED;
- mSlots[*outSlot].mFence = Fence::NO_FENCE;
- mSlots[*outSlot].mRequestBufferCalled = true;
-
- return returnFlags;
-}
-
-status_t GonkBufferQueueProducer::setSynchronousMode(bool enabled) {
- ALOGV("setSynchronousMode: enabled=%d", enabled);
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("setSynchronousMode: BufferQueue has been abandoned!");
- return NO_INIT;
- }
-
- if (mSynchronousMode != enabled) {
- mSynchronousMode = enabled;
- mCore->mDequeueCondition.broadcast();
- }
- return OK;
-}
-
-status_t GonkBufferQueueProducer::queueBuffer(int slot,
- const QueueBufferInput &input, QueueBufferOutput *output) {
- ATRACE_CALL();
-
- int64_t timestamp;
- bool isAutoTimestamp;
- Rect crop;
- int scalingMode;
- uint32_t transform;
- uint32_t stickyTransform;
- bool async;
- sp<Fence> fence;
- input.deflate(&timestamp, &isAutoTimestamp, &crop, &scalingMode, &transform,
- &async, &fence, &stickyTransform);
-
- if (fence == NULL) {
- ALOGE("queueBuffer: fence is NULL");
- // Temporary workaround for b/17946343: soldier-on instead of returning an error. This
- // prevents the client from dying, at the risk of visible corruption due to hwcomposer
- // reading the buffer before the producer is done rendering it. Unless the buffer is the
- // last frame of an animation, the corruption will be transient.
- fence = Fence::NO_FENCE;
- // return BAD_VALUE;
- }
-
- switch (scalingMode) {
- case NATIVE_WINDOW_SCALING_MODE_FREEZE:
- case NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW:
- case NATIVE_WINDOW_SCALING_MODE_SCALE_CROP:
- case NATIVE_WINDOW_SCALING_MODE_NO_SCALE_CROP:
- break;
- default:
- ALOGE("queueBuffer: unknown scaling mode %d", scalingMode);
- return BAD_VALUE;
- }
-
- GonkBufferItem item;
- sp<IConsumerListener> listener;
- { // Autolock scope
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("queueBuffer: GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- const int maxBufferCount = mCore->getMaxBufferCountLocked(async);
- if (async && mCore->mOverrideMaxBufferCount) {
- // FIXME: Some drivers are manually setting the buffer count
- // (which they shouldn't), so we do this extra test here to
- // handle that case. This is TEMPORARY until we get this fixed.
- if (mCore->mOverrideMaxBufferCount < maxBufferCount) {
- ALOGE("queueBuffer: async mode is invalid with "
- "buffer count override");
- return BAD_VALUE;
- }
- }
-
- if (slot < 0 || slot >= maxBufferCount) {
- ALOGE("queueBuffer: slot index %d out of range [0, %d)",
- slot, maxBufferCount);
- return BAD_VALUE;
- } else if (mSlots[slot].mBufferState != GonkBufferSlot::DEQUEUED) {
- ALOGE("queueBuffer: slot %d is not owned by the producer "
- "(state = %d)", slot, mSlots[slot].mBufferState);
- return BAD_VALUE;
- } else if (!mSlots[slot].mRequestBufferCalled) {
- ALOGE("queueBuffer: slot %d was queued without requesting "
- "a buffer", slot);
- return BAD_VALUE;
- }
-
- ALOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64
- " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
- slot, mCore->mFrameCounter + 1, timestamp,
- crop.left, crop.top, crop.right, crop.bottom,
- transform, GonkBufferItem::scalingModeName(scalingMode));
-
- const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
- Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
- Rect croppedRect;
- crop.intersect(bufferRect, &croppedRect);
- if (croppedRect != crop) {
- ALOGE("queueBuffer: crop rect is not contained within the "
- "buffer in slot %d", slot);
- return BAD_VALUE;
- }
-
- mSlots[slot].mFence = fence;
- mSlots[slot].mBufferState = GonkBufferSlot::QUEUED;
- ++mCore->mFrameCounter;
- mSlots[slot].mFrameNumber = mCore->mFrameCounter;
-
- item.mAcquireCalled = mSlots[slot].mAcquireCalled;
- item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
- item.mCrop = crop;
- item.mTransform = transform & ~NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
- item.mTransformToDisplayInverse =
- bool(transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
- item.mScalingMode = scalingMode;
- item.mTimestamp = timestamp;
- item.mIsAutoTimestamp = isAutoTimestamp;
- item.mFrameNumber = mCore->mFrameCounter;
- item.mSlot = slot;
- item.mFence = fence;
- item.mIsDroppable = mCore->mDequeueBufferCannotBlock || async;
-
- mStickyTransform = stickyTransform;
-
- if (mCore->mQueue.empty()) {
- // When the queue is empty, we can ignore mDequeueBufferCannotBlock
- // and simply queue this buffer
- mCore->mQueue.push_back(item);
- listener = mCore->mConsumerListener;
- } else {
- // When the queue is not empty, we need to look at the front buffer
- // state to see if we need to replace it
- GonkBufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());
- if (front->mIsDroppable || !mSynchronousMode) {
- // If the front queued buffer is still being tracked, we first
- // mark it as freed
- if (mCore->stillTracking(front)) {
- mSlots[front->mSlot].mBufferState = GonkBufferSlot::FREE;
- // Reset the frame number of the freed buffer so that it is
- // the first in line to be dequeued again
- mSlots[front->mSlot].mFrameNumber = 0;
- }
- // Overwrite the droppable buffer with the incoming one
- *front = item;
- listener = mCore->mConsumerListener;
- } else {
- mCore->mQueue.push_back(item);
- listener = mCore->mConsumerListener;
- }
- }
-
- mCore->mBufferHasBeenQueued = true;
- mCore->mDequeueCondition.broadcast();
-
- output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
- mCore->mTransformHint, mCore->mQueue.size());
-
- item.mGraphicBuffer.clear();
- item.mSlot = GonkBufferItem::INVALID_BUFFER_SLOT;
- } // Autolock scope
-
- // Call back without lock held
- if (listener != NULL) {
-#if ANDROID_VERSION == 21
- listener->onFrameAvailable();
-#else
- listener->onFrameAvailable(reinterpret_cast<::android::BufferItem&>(item));
-#endif
- }
-
- return NO_ERROR;
-}
-
-void GonkBufferQueueProducer::cancelBuffer(int slot, const sp<Fence>& fence) {
- ATRACE_CALL();
- ALOGV("cancelBuffer: slot %d", slot);
- Mutex::Autolock lock(mCore->mMutex);
-
- if (mCore->mIsAbandoned) {
- ALOGE("cancelBuffer: GonkBufferQueue has been abandoned");
- return;
- }
-
- if (slot < 0 || slot >= GonkBufferQueueDefs::NUM_BUFFER_SLOTS) {
- ALOGE("cancelBuffer: slot index %d out of range [0, %d)",
- slot, GonkBufferQueueDefs::NUM_BUFFER_SLOTS);
- return;
- } else if (mSlots[slot].mBufferState != GonkBufferSlot::DEQUEUED) {
- ALOGE("cancelBuffer: slot %d is not owned by the producer "
- "(state = %d)", slot, mSlots[slot].mBufferState);
- return;
- } else if (fence == NULL) {
- ALOGE("cancelBuffer: fence is NULL");
- return;
- }
-
- mSlots[slot].mBufferState = GonkBufferSlot::FREE;
- mSlots[slot].mFrameNumber = 0;
- mSlots[slot].mFence = fence;
- mCore->mDequeueCondition.broadcast();
-}
-
-int GonkBufferQueueProducer::query(int what, int *outValue) {
- ATRACE_CALL();
- Mutex::Autolock lock(mCore->mMutex);
-
- if (outValue == NULL) {
- ALOGE("query: outValue was NULL");
- return BAD_VALUE;
- }
-
- if (mCore->mIsAbandoned) {
- ALOGE("query: GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- int value;
- switch (what) {
- case NATIVE_WINDOW_WIDTH:
- value = mCore->mDefaultWidth;
- break;
- case NATIVE_WINDOW_HEIGHT:
- value = mCore->mDefaultHeight;
- break;
- case NATIVE_WINDOW_FORMAT:
- value = mCore->mDefaultBufferFormat;
- break;
- case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
- value = mCore->getMinUndequeuedBufferCountLocked(false);
- break;
- case NATIVE_WINDOW_STICKY_TRANSFORM:
- value = static_cast<int>(mStickyTransform);
- break;
- case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
- value = (mCore->mQueue.size() > 1);
- break;
- case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
- value = mCore->mConsumerUsageBits;
- break;
- default:
- return BAD_VALUE;
- }
-
- ALOGV("query: %d? %d", what, value);
- *outValue = value;
- return NO_ERROR;
-}
-
-status_t GonkBufferQueueProducer::connect(const sp<IProducerListener>& listener,
- int api, bool producerControlledByApp, QueueBufferOutput *output) {
- ATRACE_CALL();
- Mutex::Autolock lock(mCore->mMutex);
- mConsumerName = mCore->mConsumerName;
- ALOGV("connect(P): api=%d producerControlledByApp=%s", api,
- producerControlledByApp ? "true" : "false");
-
- if (mCore->mIsAbandoned) {
- ALOGE("connect(P): GonkBufferQueue has been abandoned");
- return NO_INIT;
- }
-
- if (mCore->mConsumerListener == NULL) {
- ALOGE("connect(P): GonkBufferQueue has no consumer");
- return NO_INIT;
- }
-
- if (output == NULL) {
- ALOGE("connect(P): output was NULL");
- return BAD_VALUE;
- }
-
- if (mCore->mConnectedApi != GonkBufferQueueCore::NO_CONNECTED_API) {
- ALOGE("connect(P): already connected (cur=%d req=%d)", mCore->mConnectedApi,
- api);
- return BAD_VALUE;
- }
-
- int status = NO_ERROR;
- switch (api) {
- case NATIVE_WINDOW_API_EGL:
- case NATIVE_WINDOW_API_CPU:
- case NATIVE_WINDOW_API_MEDIA:
- case NATIVE_WINDOW_API_CAMERA:
- mCore->mConnectedApi = api;
- output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
- mCore->mTransformHint, mCore->mQueue.size());
-
- // Set up a death notification so that we can disconnect
- // automatically if the remote producer dies
- if (listener != NULL &&
- listener->asBinder()->remoteBinder() != NULL) {
- status = listener->asBinder()->linkToDeath(
- static_cast<IBinder::DeathRecipient*>(this));
- if (status != NO_ERROR) {
- ALOGE("connect(P): linkToDeath failed: %s (%d)",
- strerror(-status), status);
- }
- }
- mCore->mConnectedProducerListener = listener;
- break;
- default:
- ALOGE("connect(P): unknown API %d", api);
- status = BAD_VALUE;
- break;
- }
-
- mCore->mBufferHasBeenQueued = false;
- mCore->mDequeueBufferCannotBlock =
- mCore->mConsumerControlledByApp && producerControlledByApp;
-
- return status;
-}
-
-status_t GonkBufferQueueProducer::disconnect(int api) {
- ATRACE_CALL();
- ALOGV("disconnect(P): api %d", api);
-
- int status = NO_ERROR;
- sp<IConsumerListener> listener;
- { // Autolock scope
- Mutex::Autolock lock(mCore->mMutex);
- mCore->waitWhileAllocatingLocked();
-
- if (mCore->mIsAbandoned) {
- // It's not really an error to disconnect after the surface has
- // been abandoned; it should just be a no-op.
- return NO_ERROR;
- }
-
- switch (api) {
- case NATIVE_WINDOW_API_EGL:
- case NATIVE_WINDOW_API_CPU:
- case NATIVE_WINDOW_API_MEDIA:
- case NATIVE_WINDOW_API_CAMERA:
- if (mCore->mConnectedApi == api) {
- mCore->freeAllBuffersLocked();
- mCore->mConnectedApi = GonkBufferQueueCore::NO_CONNECTED_API;
- mCore->mSidebandStream.clear();
- mCore->mDequeueCondition.broadcast();
- listener = mCore->mConsumerListener;
- } else {
- ALOGE("disconnect(P): connected to another API "
- "(cur=%d req=%d)", mCore->mConnectedApi, api);
- status = BAD_VALUE;
- }
- break;
- default:
- ALOGE("disconnect(P): unknown API %d", api);
- status = BAD_VALUE;
- break;
- }
- } // Autolock scope
-
- // Call back without lock held
- if (listener != NULL) {
- listener->onBuffersReleased();
- }
-
- return status;
-}
-
-status_t GonkBufferQueueProducer::setSidebandStream(const sp<NativeHandle>& stream) {
- return INVALID_OPERATION;
-}
-
-void GonkBufferQueueProducer::allocateBuffers(bool async, uint32_t width,
- uint32_t height, uint32_t format, uint32_t usage) {
- ALOGE("allocateBuffers: no op");
-}
-
-void GonkBufferQueueProducer::binderDied(const wp<android::IBinder>& /* who */) {
- // If we're here, it means that a producer we were connected to died.
- // We're guaranteed that we are still connected to it because we remove
- // this callback upon disconnect. It's therefore safe to read mConnectedApi
- // without synchronization here.
- int api = mCore->mConnectedApi;
- disconnect(api);
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.h b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.h
deleted file mode 100644
index a1a22416a..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueProducer.h
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKBUFFERQUEUEPRODUCER_LL_H
-#define NATIVEWINDOW_GONKBUFFERQUEUEPRODUCER_LL_H
-
-#include "GonkBufferQueueDefs.h"
-#include <gui/IGraphicBufferProducer.h>
-
-namespace android {
-
-class GonkBufferQueueProducer : public BnGraphicBufferProducer,
- private IBinder::DeathRecipient {
-public:
- friend class GonkBufferQueue; // Needed to access binderDied
-
- GonkBufferQueueProducer(const sp<GonkBufferQueueCore>& core);
- virtual ~GonkBufferQueueProducer();
-
- // requestBuffer returns the GraphicBuffer for slot N.
- //
- // In normal operation, this is called the first time slot N is returned
- // by dequeueBuffer. It must be called again if dequeueBuffer returns
- // flags indicating that previously-returned buffers are no longer valid.
- virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
-
- // setBufferCount updates the number of available buffer slots. If this
- // method succeeds, buffer slots will be both unallocated and owned by
- // the GonkBufferQueue object (i.e. they are not owned by the producer or
- // consumer).
- //
- // This will fail if the producer has dequeued any buffers, or if
- // bufferCount is invalid. bufferCount must generally be a value
- // between the minimum undequeued buffer count (exclusive) and NUM_BUFFER_SLOTS
- // (inclusive). It may also be set to zero (the default) to indicate
- // that the producer does not wish to set a value. The minimum value
- // can be obtained by calling query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
- // ...).
- //
- // This may only be called by the producer. The consumer will be told
- // to discard buffers through the onBuffersReleased callback.
- virtual status_t setBufferCount(int bufferCount);
-
- // dequeueBuffer gets the next buffer slot index for the producer to use.
- // If a buffer slot is available then that slot index is written to the
- // location pointed to by the buf argument and a status of OK is returned.
- // If no slot is available then a status of -EBUSY is returned and buf is
- // unmodified.
- //
- // The outFence parameter will be updated to hold the fence associated with
- // the buffer. The contents of the buffer must not be overwritten until the
- // fence signals. If the fence is Fence::NO_FENCE, the buffer may be
- // written immediately.
- //
- // The width and height parameters must be no greater than the minimum of
- // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
- // An error due to invalid dimensions might not be reported until
- // updateTexImage() is called. If width and height are both zero, the
- // default values specified by setDefaultBufferSize() are used instead.
- //
- // The pixel formats are enumerated in graphics.h, e.g.
- // HAL_PIXEL_FORMAT_RGBA_8888. If the format is 0, the default format
- // will be used.
- //
- // The usage argument specifies gralloc buffer usage flags. The values
- // are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER. These
- // will be merged with the usage flags specified by setConsumerUsageBits.
- //
- // The return value may be a negative error value or a non-negative
- // collection of flags. If the flags are set, the return values are
- // valid, but additional actions must be performed.
- //
- // If IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION is set, the
- // producer must discard cached GraphicBuffer references for the slot
- // returned in buf.
- // If IGraphicBufferProducer::RELEASE_ALL_BUFFERS is set, the producer
- // must discard cached GraphicBuffer references for all slots.
- //
- // In both cases, the producer will need to call requestBuffer to get a
- // GraphicBuffer handle for the returned slot.
- virtual status_t dequeueBuffer(int *outSlot, sp<Fence>* outFence, bool async,
- uint32_t width, uint32_t height, uint32_t format, uint32_t usage);
-
- // See IGraphicBufferProducer::detachBuffer
- virtual status_t detachBuffer(int slot);
-
- // See IGraphicBufferProducer::detachNextBuffer
- virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
- sp<Fence>* outFence);
-
- // See IGraphicBufferProducer::attachBuffer
- virtual status_t attachBuffer(int* outSlot, const sp<GraphicBuffer>& buffer);
-
- // queueBuffer returns a filled buffer to the GonkBufferQueue.
- //
- // Additional data is provided in the QueueBufferInput struct. Notably,
- // a timestamp must be provided for the buffer. The timestamp is in
- // nanoseconds, and must be monotonically increasing. Its other semantics
- // (zero point, etc) are producer-specific and should be documented by the
- // producer.
- //
- // The caller may provide a fence that signals when all rendering
- // operations have completed. Alternatively, NO_FENCE may be used,
- // indicating that the buffer is ready immediately.
- //
- // Some values are returned in the output struct: the current settings
- // for default width and height, the current transform hint, and the
- // number of queued buffers.
- virtual status_t queueBuffer(int slot,
- const QueueBufferInput& input, QueueBufferOutput* output);
-
- // cancelBuffer returns a dequeued buffer to the GonkBufferQueue, but doesn't
- // queue it for use by the consumer.
- //
- // The buffer will not be overwritten until the fence signals. The fence
- // will usually be the one obtained from dequeueBuffer.
- virtual void cancelBuffer(int slot, const sp<Fence>& fence);
-
- // Query native window attributes. The "what" values are enumerated in
- // window.h (e.g. NATIVE_WINDOW_FORMAT).
- virtual int query(int what, int* outValue);
-
- // connect attempts to connect a producer API to the GonkBufferQueue. This
- // must be called before any other IGraphicBufferProducer methods are
- // called except for getAllocator. A consumer must already be connected.
- //
- // This method will fail if connect was previously called on the
- // GonkBufferQueue and no corresponding disconnect call was made (i.e. if
- // it's still connected to a producer).
- //
- // APIs are enumerated in window.h (e.g. NATIVE_WINDOW_API_CPU).
- virtual status_t connect(const sp<IProducerListener>& listener,
- int api, bool producerControlledByApp, QueueBufferOutput* output);
-
- // disconnect attempts to disconnect a producer API from the GonkBufferQueue.
- // Calling this method will cause any subsequent calls to other
- // IGraphicBufferProducer methods to fail except for getAllocator and connect.
- // Successfully calling connect after this will allow the other methods to
- // succeed again.
- //
- // This method will fail if the the GonkBufferQueue is not currently
- // connected to the specified producer API.
- virtual status_t disconnect(int api);
-
- // Attaches a sideband buffer stream to the IGraphicBufferProducer.
- //
- // A sideband stream is a device-specific mechanism for passing buffers
- // from the producer to the consumer without using dequeueBuffer/
- // queueBuffer. If a sideband stream is present, the consumer can choose
- // whether to acquire buffers from the sideband stream or from the queued
- // buffers.
- //
- // Passing NULL or a different stream handle will detach the previous
- // handle if any.
- virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
-
- // See IGraphicBufferProducer::allocateBuffers
- virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
- uint32_t format, uint32_t usage);
-
- // setSynchronousMode sets whether dequeueBuffer is synchronous or
- // asynchronous. In synchronous mode, dequeueBuffer blocks until
- // a buffer is available, the currently bound buffer can be dequeued and
- // queued buffers will be acquired in order. In asynchronous mode,
- // a queued buffer may be replaced by a subsequently queued buffer.
- //
- // The default mode is synchronous.
- // This should be called only during initialization.
- virtual status_t setSynchronousMode(bool enabled);
-
-private:
- // This is required by the IBinder::DeathRecipient interface
- virtual void binderDied(const wp<IBinder>& who);
-
- // waitForFreeSlotThenRelock finds the oldest slot in the FREE state. It may
- // block if there are no available slots and we are not in non-blocking
- // mode (producer and consumer controlled by the application). If it blocks,
- // it will release mCore->mMutex while blocked so that other operations on
- // the GonkBufferQueue may succeed.
- status_t waitForFreeSlotThenRelock(const char* caller, bool async,
- int* found, status_t* returnFlags) const;
-
- sp<GonkBufferQueueCore> mCore;
-
- // This references mCore->mSlots. Lock mCore->mMutex while accessing.
- GonkBufferQueueDefs::SlotsType& mSlots;
-
- // This is a cached copy of the name stored in the GonkBufferQueueCore.
- // It's updated during connect and dequeueBuffer (which should catch
- // most updates).
- String8 mConsumerName;
-
- // mSynchronousMode whether we're in synchronous mode or not
- bool mSynchronousMode;
-
- uint32_t mStickyTransform;
-
-}; // class GonkBufferQueueProducer
-
-} // namespace android
-
-#endif
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.cpp b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.cpp
deleted file mode 100644
index 9e4a424a9..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.cpp
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "GonkBufferSlot.h"
-
-namespace android {
-
-const char* GonkBufferSlot::bufferStateName(BufferState state) {
- switch (state) {
- case GonkBufferSlot::DEQUEUED: return "DEQUEUED";
- case GonkBufferSlot::QUEUED: return "QUEUED";
- case GonkBufferSlot::FREE: return "FREE";
- case GonkBufferSlot::ACQUIRED: return "ACQUIRED";
- default: return "Unknown";
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.h b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.h
deleted file mode 100644
index 759bb7b23..000000000
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferSlot.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright 2014 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKBUFFERSLOT_LL_H
-#define NATIVEWINDOW_GONKBUFFERSLOT_LL_H
-
-#include <ui/Fence.h>
-#include <ui/GraphicBuffer.h>
-
-#include <utils/StrongPointer.h>
-
-#include "mozilla/layers/TextureClient.h"
-
-namespace android {
-
-struct GonkBufferSlot {
- typedef mozilla::layers::TextureClient TextureClient;
-
- GonkBufferSlot()
- : mBufferState(GonkBufferSlot::FREE),
- mRequestBufferCalled(false),
- mFrameNumber(0),
- mAcquireCalled(false),
- mNeedsCleanupOnRelease(false),
- mAttachedByConsumer(false) {
- }
-
- // mGraphicBuffer points to the buffer allocated for this slot or is NULL
- // if no buffer has been allocated.
- sp<GraphicBuffer> mGraphicBuffer;
-
- // BufferState represents the different states in which a buffer slot
- // can be. All slots are initially FREE.
- enum BufferState {
- // FREE indicates that the buffer is available to be dequeued
- // by the producer. The buffer may be in use by the consumer for
- // a finite time, so the buffer must not be modified until the
- // associated fence is signaled.
- //
- // The slot is "owned" by BufferQueue. It transitions to DEQUEUED
- // when dequeueBuffer is called.
- FREE = 0,
-
- // DEQUEUED indicates that the buffer has been dequeued by the
- // producer, but has not yet been queued or canceled. The
- // producer may modify the buffer's contents as soon as the
- // associated ready fence is signaled.
- //
- // The slot is "owned" by the producer. It can transition to
- // QUEUED (via queueBuffer) or back to FREE (via cancelBuffer).
- DEQUEUED = 1,
-
- // QUEUED indicates that the buffer has been filled by the
- // producer and queued for use by the consumer. The buffer
- // contents may continue to be modified for a finite time, so
- // the contents must not be accessed until the associated fence
- // is signaled.
- //
- // The slot is "owned" by BufferQueue. It can transition to
- // ACQUIRED (via acquireBuffer) or to FREE (if another buffer is
- // queued in asynchronous mode).
- QUEUED = 2,
-
- // ACQUIRED indicates that the buffer has been acquired by the
- // consumer. As with QUEUED, the contents must not be accessed
- // by the consumer until the fence is signaled.
- //
- // The slot is "owned" by the consumer. It transitions to FREE
- // when releaseBuffer is called.
- ACQUIRED = 3
- };
-
- static const char* bufferStateName(BufferState state);
-
- // mBufferState is the current state of this buffer slot.
- BufferState mBufferState;
-
- // mRequestBufferCalled is used for validating that the producer did
- // call requestBuffer() when told to do so. Technically this is not
- // needed but useful for debugging and catching producer bugs.
- bool mRequestBufferCalled;
-
- // mFrameNumber is the number of the queued frame for this slot. This
- // is used to dequeue buffers in LRU order (useful because buffers
- // may be released before their release fence is signaled).
- uint64_t mFrameNumber;
-
- // mFence is a fence which will signal when work initiated by the
- // previous owner of the buffer is finished. When the buffer is FREE,
- // the fence indicates when the consumer has finished reading
- // from the buffer, or when the producer has finished writing if it
- // called cancelBuffer after queueing some writes. When the buffer is
- // QUEUED, it indicates when the producer has finished filling the
- // buffer. When the buffer is DEQUEUED or ACQUIRED, the fence has been
- // passed to the consumer or producer along with ownership of the
- // buffer, and mFence is set to NO_FENCE.
- sp<Fence> mFence;
-
- // Indicates whether this buffer has been seen by a consumer yet
- bool mAcquireCalled;
-
- // Indicates whether this buffer needs to be cleaned up by the
- // consumer. This is set when a buffer in ACQUIRED state is freed.
- // It causes releaseBuffer to return STALE_BUFFER_SLOT.
- bool mNeedsCleanupOnRelease;
-
- // Indicates whether the buffer was attached on the consumer side.
- // If so, it needs to set the BUFFER_NEEDS_REALLOCATION flag when dequeued
- // to prevent the producer from using a stale cached buffer.
- bool mAttachedByConsumer;
-
- // mTextureClient is a thin abstraction over remotely allocated GraphicBuffer.
- RefPtr<TextureClient> mTextureClient;
-};
-
-} // namespace android
-
-#endif
diff --git a/widget/gonk/nativewindow/GonkConsumerBaseJB.cpp b/widget/gonk/nativewindow/GonkConsumerBaseJB.cpp
deleted file mode 100644
index 1ee37e4e2..000000000
--- a/widget/gonk/nativewindow/GonkConsumerBaseJB.cpp
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "GonkConsumerBase"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-//#define LOG_NDEBUG 0
-
-#define EGL_EGLEXT_PROTOTYPES
-
-#include <hardware/hardware.h>
-
-#include <gui/IGraphicBufferAlloc.h>
-#include <utils/Log.h>
-#include <utils/String8.h>
-
-#include "GonkConsumerBaseJB.h"
-
-// Macros for including the GonkConsumerBase name in log messages
-#define CB_LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
-#define CB_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
-#define CB_LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define CB_LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
-#define CB_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-namespace android {
-
-// Get an ID that's unique within this process.
-static int32_t createProcessUniqueId() {
- static volatile int32_t globalCounter = 0;
- return android_atomic_inc(&globalCounter);
-}
-
-GonkConsumerBase::GonkConsumerBase(const sp<GonkBufferQueue>& bufferQueue) :
- mAbandoned(false),
- mBufferQueue(bufferQueue) {
- // Choose a name using the PID and a process-unique ID.
- mName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
-
- // Note that we can't create an sp<...>(this) in a ctor that will not keep a
- // reference once the ctor ends, as that would cause the refcount of 'this'
- // dropping to 0 at the end of the ctor. Since all we need is a wp<...>
- // that's what we create.
- wp<GonkBufferQueue::ConsumerListener> listener;
- sp<GonkBufferQueue::ConsumerListener> proxy;
- listener = static_cast<GonkBufferQueue::ConsumerListener*>(this);
- proxy = new GonkBufferQueue::ProxyConsumerListener(listener);
-
- status_t err = mBufferQueue->consumerConnect(proxy);
- if (err != NO_ERROR) {
- CB_LOGE("GonkConsumerBase: error connecting to GonkBufferQueue: %s (%d)",
- strerror(-err), err);
- } else {
- mBufferQueue->setConsumerName(mName);
- }
-}
-
-GonkConsumerBase::~GonkConsumerBase() {
- CB_LOGV("~GonkConsumerBase");
- Mutex::Autolock lock(mMutex);
-
- // Verify that abandon() has been called before we get here. This should
- // be done by GonkConsumerBase::onLastStrongRef(), but it's possible for a
- // derived class to override that method and not call
- // GonkConsumerBase::onLastStrongRef().
- LOG_ALWAYS_FATAL_IF(!mAbandoned, "[%s] ~GonkConsumerBase was called, but the "
- "consumer is not abandoned!", mName.string());
-}
-
-void GonkConsumerBase::onLastStrongRef(const void* id) {
- abandon();
-}
-
-void GonkConsumerBase::freeBufferLocked(int slotIndex) {
- CB_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
- mSlots[slotIndex].mGraphicBuffer = 0;
- mSlots[slotIndex].mFence = Fence::NO_FENCE;
-}
-
-// Used for refactoring, should not be in final interface
-sp<GonkBufferQueue> GonkConsumerBase::getBufferQueue() const {
- Mutex::Autolock lock(mMutex);
- return mBufferQueue;
-}
-
-void GonkConsumerBase::onFrameAvailable() {
- CB_LOGV("onFrameAvailable");
-
- sp<FrameAvailableListener> listener;
- { // scope for the lock
- Mutex::Autolock lock(mMutex);
-#if ANDROID_VERSION == 17
- listener = mFrameAvailableListener;
-#else
- listener = mFrameAvailableListener.promote();
-#endif
- }
-
- if (listener != NULL) {
- CB_LOGV("actually calling onFrameAvailable");
- listener->onFrameAvailable();
- }
-}
-
-void GonkConsumerBase::onBuffersReleased() {
- Mutex::Autolock lock(mMutex);
-
- CB_LOGV("onBuffersReleased");
-
- if (mAbandoned) {
- // Nothing to do if we're already abandoned.
- return;
- }
-
- uint32_t mask = 0;
- mBufferQueue->getReleasedBuffers(&mask);
- for (int i = 0; i < GonkBufferQueue::NUM_BUFFER_SLOTS; i++) {
- if (mask & (1 << i)) {
- freeBufferLocked(i);
- }
- }
-}
-
-void GonkConsumerBase::abandon() {
- CB_LOGV("abandon");
- Mutex::Autolock lock(mMutex);
-
- if (!mAbandoned) {
- abandonLocked();
- mAbandoned = true;
- }
-}
-
-void GonkConsumerBase::abandonLocked() {
- CB_LOGV("abandonLocked");
- for (int i =0; i < GonkBufferQueue::NUM_BUFFER_SLOTS; i++) {
- freeBufferLocked(i);
- }
- // disconnect from the GonkBufferQueue
- mBufferQueue->consumerDisconnect();
- mBufferQueue.clear();
-}
-
-void GonkConsumerBase::setFrameAvailableListener(
-#if ANDROID_VERSION == 17
- const sp<FrameAvailableListener>& listener) {
-#else
- const wp<FrameAvailableListener>& listener) {
-#endif
- CB_LOGV("setFrameAvailableListener");
- Mutex::Autolock lock(mMutex);
- mFrameAvailableListener = listener;
-}
-
-void GonkConsumerBase::dump(String8& result) const {
- char buffer[1024];
- dump(result, "", buffer, 1024);
-}
-
-void GonkConsumerBase::dump(String8& result, const char* prefix,
- char* buffer, size_t size) const {
- Mutex::Autolock _l(mMutex);
- dumpLocked(result, prefix, buffer, size);
-}
-
-void GonkConsumerBase::dumpLocked(String8& result, const char* prefix,
- char* buffer, size_t SIZE) const {
- snprintf(buffer, SIZE, "%smAbandoned=%d\n", prefix, int(mAbandoned));
- result.append(buffer);
-
- if (!mAbandoned) {
- mBufferQueue->dumpToString(result, prefix, buffer, SIZE);
- }
-}
-
-status_t GonkConsumerBase::acquireBufferLocked(GonkBufferQueue::BufferItem *item) {
- status_t err = mBufferQueue->acquireBuffer(item);
- if (err != NO_ERROR) {
- return err;
- }
-
- if (item->mGraphicBuffer != NULL) {
- mSlots[item->mBuf].mGraphicBuffer = item->mGraphicBuffer;
- }
-
- mSlots[item->mBuf].mFence = item->mFence;
-
- CB_LOGV("acquireBufferLocked: -> slot=%d", item->mBuf);
-
- return OK;
-}
-
-status_t GonkConsumerBase::addReleaseFence(int slot, const sp<Fence>& fence) {
- Mutex::Autolock lock(mMutex);
- return addReleaseFenceLocked(slot, fence);
-}
-
-status_t GonkConsumerBase::addReleaseFenceLocked(int slot, const sp<Fence>& fence) {
- CB_LOGV("addReleaseFenceLocked: slot=%d", slot);
-
- if (!mSlots[slot].mFence.get()) {
- mSlots[slot].mFence = fence;
- } else {
- sp<Fence> mergedFence = Fence::merge(
- String8::format("%.28s:%d", mName.string(), slot),
- mSlots[slot].mFence, fence);
- if (!mergedFence.get()) {
- CB_LOGE("failed to merge release fences");
- // synchronization is broken, the best we can do is hope fences
- // signal in order so the new fence will act like a union
- mSlots[slot].mFence = fence;
- return BAD_VALUE;
- }
- mSlots[slot].mFence = mergedFence;
- }
-
- return OK;
-}
-
-status_t GonkConsumerBase::releaseBufferLocked(int slot) {
- CB_LOGV("releaseBufferLocked: slot=%d", slot);
- status_t err = mBufferQueue->releaseBuffer(slot, mSlots[slot].mFence);
- if (err == GonkBufferQueue::STALE_BUFFER_SLOT) {
- freeBufferLocked(slot);
- }
-
- mSlots[slot].mFence = Fence::NO_FENCE;
-
- return err;
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkConsumerBaseJB.h b/widget/gonk/nativewindow/GonkConsumerBaseJB.h
deleted file mode 100644
index 8f523af37..000000000
--- a/widget/gonk/nativewindow/GonkConsumerBaseJB.h
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKCONSUMERBASE_JB_H
-#define NATIVEWINDOW_GONKCONSUMERBASE_JB_H
-
-#include <ui/GraphicBuffer.h>
-
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-
-#include "GonkBufferQueueJB.h"
-
-namespace android {
-// ----------------------------------------------------------------------------
-
-class String8;
-
-// GonkConsumerBase is a base class for GonkBufferQueue consumer end-points. It
-// handles common tasks like management of the connection to the GonkBufferQueue
-// and the buffer pool.
-class GonkConsumerBase : public virtual RefBase,
- protected GonkBufferQueue::ConsumerListener {
-public:
- struct FrameAvailableListener : public virtual RefBase {
- // onFrameAvailable() is called each time an additional frame becomes
- // available for consumption. This means that frames that are queued
- // while in asynchronous mode only trigger the callback if no previous
- // frames are pending. Frames queued while in synchronous mode always
- // trigger the callback.
- //
- // This is called without any lock held and can be called concurrently
- // by multiple threads.
- virtual void onFrameAvailable() = 0;
- };
-
- virtual ~GonkConsumerBase();
-
- // abandon frees all the buffers and puts the GonkConsumerBase into the
- // 'abandoned' state. Once put in this state the GonkConsumerBase can never
- // leave it. When in the 'abandoned' state, all methods of the
- // IGraphicBufferProducer interface will fail with the NO_INIT error.
- //
- // Note that while calling this method causes all the buffers to be freed
- // from the perspective of the the GonkConsumerBase, if there are additional
- // references on the buffers (e.g. if a buffer is referenced by a client
- // or by OpenGL ES as a texture) then those buffer will remain allocated.
- void abandon();
-
- // set the name of the GonkConsumerBase that will be used to identify it in
- // log messages.
- void setName(const String8& name);
-
- // getBufferQueue returns the GonkBufferQueue object to which this
- // GonkConsumerBase is connected.
- sp<GonkBufferQueue> getBufferQueue() const;
-
- // dump writes the current state to a string. Child classes should add
- // their state to the dump by overriding the dumpLocked method, which is
- // called by these methods after locking the mutex.
- void dump(String8& result) const;
- void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
-
- // setFrameAvailableListener sets the listener object that will be notified
- // when a new frame becomes available.
-#if ANDROID_VERSION == 17
- void setFrameAvailableListener(const sp<FrameAvailableListener>& listener);
-#else
- void setFrameAvailableListener(const wp<FrameAvailableListener>& listener);
-#endif
-
-private:
- GonkConsumerBase(const GonkConsumerBase&);
- void operator=(const GonkConsumerBase&);
-
-protected:
-
- // GonkConsumerBase constructs a new GonkConsumerBase object to consume image
- // buffers from the given GonkBufferQueue.
- GonkConsumerBase(const sp<GonkBufferQueue> &bufferQueue);
-
- // onLastStrongRef gets called by RefBase just before the dtor of the most
- // derived class. It is used to clean up the buffers so that GonkConsumerBase
- // can coordinate the clean-up by calling into virtual methods implemented
- // by the derived classes. This would not be possible from the
- // ConsuemrBase dtor because by the time that gets called the derived
- // classes have already been destructed.
- //
- // This methods should not need to be overridden by derived classes, but
- // if they are overridden the GonkConsumerBase implementation must be called
- // from the derived class.
- virtual void onLastStrongRef(const void* id);
-
- // Implementation of the GonkBufferQueue::ConsumerListener interface. These
- // calls are used to notify the GonkConsumerBase of asynchronous events in the
- // GonkBufferQueue. These methods should not need to be overridden by derived
- // classes, but if they are overridden the GonkConsumerBase implementation
- // must be called from the derived class.
- virtual void onFrameAvailable();
- virtual void onBuffersReleased();
-
- // freeBufferLocked frees up the given buffer slot. If the slot has been
- // initialized this will release the reference to the GraphicBuffer in that
- // slot. Otherwise it has no effect.
- //
- // Derived classes should override this method to clean up any state they
- // keep per slot. If it is overridden, the derived class's implementation
- // must call GonkConsumerBase::freeBufferLocked.
- //
- // This method must be called with mMutex locked.
- virtual void freeBufferLocked(int slotIndex);
-
- // abandonLocked puts the GonkBufferQueue into the abandoned state, causing
- // all future operations on it to fail. This method rather than the public
- // abandon method should be overridden by child classes to add abandon-
- // time behavior.
- //
- // Derived classes should override this method to clean up any object
- // state they keep (as opposed to per-slot state). If it is overridden,
- // the derived class's implementation must call GonkConsumerBase::abandonLocked.
- //
- // This method must be called with mMutex locked.
- virtual void abandonLocked();
-
- // dumpLocked dumps the current state of the GonkConsumerBase object to the
- // result string. Each line is prefixed with the string pointed to by the
- // prefix argument. The buffer argument points to a buffer that may be
- // used for intermediate formatting data, and the size of that buffer is
- // indicated by the size argument.
- //
- // Derived classes should override this method to dump their internal
- // state. If this method is overridden the derived class's implementation
- // should call GonkConsumerBase::dumpLocked.
- //
- // This method must be called with mMutex locked.
- virtual void dumpLocked(String8& result, const char* prefix, char* buffer,
- size_t size) const;
-
- // acquireBufferLocked fetches the next buffer from the GonkBufferQueue and
- // updates the buffer slot for the buffer returned.
- //
- // Derived classes should override this method to perform any
- // initialization that must take place the first time a buffer is assigned
- // to a slot. If it is overridden the derived class's implementation must
- // call GonkConsumerBase::acquireBufferLocked.
- virtual status_t acquireBufferLocked(GonkBufferQueue::BufferItem *item);
-
- // releaseBufferLocked relinquishes control over a buffer, returning that
- // control to the GonkBufferQueue.
- //
- // Derived classes should override this method to perform any cleanup that
- // must take place when a buffer is released back to the GonkBufferQueue. If
- // it is overridden the derived class's implementation must call
- // GonkConsumerBase::releaseBufferLocked.
- virtual status_t releaseBufferLocked(int buf);
-
- // addReleaseFence* adds the sync points associated with a fence to the set
- // of sync points that must be reached before the buffer in the given slot
- // may be used after the slot has been released. This should be called by
- // derived classes each time some asynchronous work is kicked off that
- // references the buffer.
- status_t addReleaseFence(int slot, const sp<Fence>& fence);
- status_t addReleaseFenceLocked(int slot, const sp<Fence>& fence);
-
- // Slot contains the information and object references that
- // GonkConsumerBase maintains about a GonkBufferQueue buffer slot.
- struct Slot {
- // mGraphicBuffer is the Gralloc buffer store in the slot or NULL if
- // no Gralloc buffer is in the slot.
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mFence is a fence which will signal when the buffer associated with
- // this buffer slot is no longer being used by the consumer and can be
- // overwritten. The buffer can be dequeued before the fence signals;
- // the producer is responsible for delaying writes until it signals.
- sp<Fence> mFence;
- };
-
- // mSlots stores the buffers that have been allocated by the GonkBufferQueue
- // for each buffer slot. It is initialized to null pointers, and gets
- // filled in with the result of GonkBufferQueue::acquire when the
- // client dequeues a buffer from a
- // slot that has not yet been used. The buffer allocated to a slot will also
- // be replaced if the requested buffer usage or geometry differs from that
- // of the buffer allocated to a slot.
- Slot mSlots[GonkBufferQueue::NUM_BUFFER_SLOTS];
-
- // mAbandoned indicates that the GonkBufferQueue will no longer be used to
- // consume images buffers pushed to it using the IGraphicBufferProducer
- // interface. It is initialized to false, and set to true in the abandon
- // method. A GonkBufferQueue that has been abandoned will return the NO_INIT
- // error from all IGonkConsumerBase methods capable of returning an error.
- bool mAbandoned;
-
- // mName is a string used to identify the GonkConsumerBase in log messages.
- // It can be set by the setName method.
- String8 mName;
-
- // mFrameAvailableListener is the listener object that will be called when a
- // new frame becomes available. If it is not NULL it will be called from
- // queueBuffer.
-#if ANDROID_VERSION == 17
- sp<FrameAvailableListener> mFrameAvailableListener;
-#else
- wp<FrameAvailableListener> mFrameAvailableListener;
-#endif
-
- // The GonkConsumerBase has-a GonkBufferQueue and is responsible for creating this object
- // if none is supplied
- sp<GonkBufferQueue> mBufferQueue;
-
- // mMutex is the mutex used to prevent concurrent access to the member
- // variables of GonkConsumerBase objects. It must be locked whenever the
- // member variables are accessed or when any of the *Locked methods are
- // called.
- //
- // This mutex is intended to be locked by derived classes.
- mutable Mutex mMutex;
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // NATIVEWINDOW_GONKCONSUMERBASE_H
diff --git a/widget/gonk/nativewindow/GonkConsumerBaseKK.cpp b/widget/gonk/nativewindow/GonkConsumerBaseKK.cpp
deleted file mode 100644
index 3fc9fc16c..000000000
--- a/widget/gonk/nativewindow/GonkConsumerBaseKK.cpp
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "GonkConsumerBase"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-//#define LOG_NDEBUG 0
-
-#define EGL_EGLEXT_PROTOTYPES
-
-#include <hardware/hardware.h>
-
-#include <gui/IGraphicBufferAlloc.h>
-#include <utils/Log.h>
-#include <utils/String8.h>
-
-#include "GonkConsumerBaseKK.h"
-
-namespace android {
-
-// Get an ID that's unique within this process.
-static int32_t createProcessUniqueId() {
- static volatile int32_t globalCounter = 0;
- return android_atomic_inc(&globalCounter);
-}
-
-GonkConsumerBase::GonkConsumerBase(const sp<GonkBufferQueue>& bufferQueue, bool controlledByApp) :
- mAbandoned(false),
- mConsumer(bufferQueue) {
- // Choose a name using the PID and a process-unique ID.
- mName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
-
- // Note that we can't create an sp<...>(this) in a ctor that will not keep a
- // reference once the ctor ends, as that would cause the refcount of 'this'
- // dropping to 0 at the end of the ctor. Since all we need is a wp<...>
- // that's what we create.
- wp<ConsumerListener> listener = static_cast<ConsumerListener*>(this);
- sp<IConsumerListener> proxy = new GonkBufferQueue::ProxyConsumerListener(listener);
-
- status_t err = mConsumer->consumerConnect(proxy, controlledByApp);
- if (err != NO_ERROR) {
- ALOGE("GonkConsumerBase: error connecting to GonkBufferQueue: %s (%d)",
- strerror(-err), err);
- } else {
- mConsumer->setConsumerName(mName);
- }
-}
-
-GonkConsumerBase::~GonkConsumerBase() {
- ALOGV("~GonkConsumerBase");
- Mutex::Autolock lock(mMutex);
-
- // Verify that abandon() has been called before we get here. This should
- // be done by GonkConsumerBase::onLastStrongRef(), but it's possible for a
- // derived class to override that method and not call
- // GonkConsumerBase::onLastStrongRef().
- LOG_ALWAYS_FATAL_IF(!mAbandoned, "[%s] ~GonkConsumerBase was called, but the "
- "consumer is not abandoned!", mName.string());
-}
-
-void GonkConsumerBase::onLastStrongRef(const void* id) {
- abandon();
-}
-
-void GonkConsumerBase::freeBufferLocked(int slotIndex) {
- ALOGV("freeBufferLocked: slotIndex=%d", slotIndex);
- mSlots[slotIndex].mGraphicBuffer = 0;
- mSlots[slotIndex].mFence = Fence::NO_FENCE;
- mSlots[slotIndex].mFrameNumber = 0;
-}
-
-// Used for refactoring, should not be in final interface
-sp<GonkBufferQueue> GonkConsumerBase::getBufferQueue() const {
- Mutex::Autolock lock(mMutex);
- return mConsumer;
-}
-
-void GonkConsumerBase::onFrameAvailable() {
- ALOGV("onFrameAvailable");
-
- sp<FrameAvailableListener> listener;
- { // scope for the lock
- Mutex::Autolock lock(mMutex);
- listener = mFrameAvailableListener.promote();
- }
-
- if (listener != NULL) {
- ALOGV("actually calling onFrameAvailable");
- listener->onFrameAvailable();
- }
-}
-
-void GonkConsumerBase::onBuffersReleased() {
- Mutex::Autolock lock(mMutex);
-
- ALOGV("onBuffersReleased");
-
- if (mAbandoned) {
- // Nothing to do if we're already abandoned.
- return;
- }
-
- uint32_t mask = 0;
- mConsumer->getReleasedBuffers(&mask);
- for (int i = 0; i < GonkBufferQueue::NUM_BUFFER_SLOTS; i++) {
- if (mask & (1 << i)) {
- freeBufferLocked(i);
- }
- }
-}
-
-void GonkConsumerBase::abandon() {
- ALOGV("abandon");
- Mutex::Autolock lock(mMutex);
-
- if (!mAbandoned) {
- abandonLocked();
- mAbandoned = true;
- }
-}
-
-void GonkConsumerBase::abandonLocked() {
- ALOGV("abandonLocked");
- for (int i =0; i < GonkBufferQueue::NUM_BUFFER_SLOTS; i++) {
- freeBufferLocked(i);
- }
- // disconnect from the BufferQueue
- mConsumer->consumerDisconnect();
- mConsumer.clear();
-}
-
-void GonkConsumerBase::setFrameAvailableListener(
- const wp<FrameAvailableListener>& listener) {
- ALOGV("setFrameAvailableListener");
- Mutex::Autolock lock(mMutex);
- mFrameAvailableListener = listener;
-}
-
-void GonkConsumerBase::dump(String8& result) const {
- dump(result, "");
-}
-
-void GonkConsumerBase::dump(String8& result, const char* prefix) const {
- Mutex::Autolock _l(mMutex);
- dumpLocked(result, prefix);
-}
-
-void GonkConsumerBase::dumpLocked(String8& result, const char* prefix) const {
- result.appendFormat("%smAbandoned=%d\n", prefix, int(mAbandoned));
-
- if (!mAbandoned) {
- mConsumer->dumpToString(result, prefix);
- }
-}
-
-status_t GonkConsumerBase::acquireBufferLocked(IGonkGraphicBufferConsumer::BufferItem *item,
- nsecs_t presentWhen) {
- status_t err = mConsumer->acquireBuffer(item, presentWhen);
- if (err != NO_ERROR) {
- return err;
- }
-
- if (item->mGraphicBuffer != NULL) {
- mSlots[item->mBuf].mGraphicBuffer = item->mGraphicBuffer;
- }
-
- mSlots[item->mBuf].mFrameNumber = item->mFrameNumber;
- mSlots[item->mBuf].mFence = item->mFence;
-
- ALOGV("acquireBufferLocked: -> slot=%d", item->mBuf);
-
- return OK;
-}
-
-status_t GonkConsumerBase::addReleaseFence(int slot,
- const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence) {
- Mutex::Autolock lock(mMutex);
- return addReleaseFenceLocked(slot, graphicBuffer, fence);
-}
-
-status_t GonkConsumerBase::addReleaseFenceLocked(int slot,
- const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence) {
- ALOGV("addReleaseFenceLocked: slot=%d", slot);
-
- // If consumer no longer tracks this graphicBuffer, we can safely
- // drop this fence, as it will never be received by the producer.
- if (!stillTracking(slot, graphicBuffer)) {
- return OK;
- }
-
- if (!mSlots[slot].mFence.get()) {
- mSlots[slot].mFence = fence;
- } else {
- sp<Fence> mergedFence = Fence::merge(
- String8::format("%.28s:%d", mName.string(), slot),
- mSlots[slot].mFence, fence);
- if (!mergedFence.get()) {
- ALOGE("failed to merge release fences");
- // synchronization is broken, the best we can do is hope fences
- // signal in order so the new fence will act like a union
- mSlots[slot].mFence = fence;
- return BAD_VALUE;
- }
- mSlots[slot].mFence = mergedFence;
- }
-
- return OK;
-}
-
-status_t GonkConsumerBase::releaseBufferLocked(int slot, const sp<GraphicBuffer> graphicBuffer) {
- // If consumer no longer tracks this graphicBuffer (we received a new
- // buffer on the same slot), the buffer producer is definitely no longer
- // tracking it.
- if (!stillTracking(slot, graphicBuffer)) {
- return OK;
- }
-
- ALOGV("releaseBufferLocked: slot=%d/%llu",
- slot, mSlots[slot].mFrameNumber);
- status_t err = mConsumer->releaseBuffer(slot, mSlots[slot].mFrameNumber, mSlots[slot].mFence);
- if (err == GonkBufferQueue::STALE_BUFFER_SLOT) {
- freeBufferLocked(slot);
- }
-
- mSlots[slot].mFence = Fence::NO_FENCE;
-
- return err;
-}
-
-bool GonkConsumerBase::stillTracking(int slot,
- const sp<GraphicBuffer> graphicBuffer) {
- if (slot < 0 || slot >= GonkBufferQueue::NUM_BUFFER_SLOTS) {
- return false;
- }
- return (mSlots[slot].mGraphicBuffer != NULL &&
- mSlots[slot].mGraphicBuffer->handle == graphicBuffer->handle);
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkConsumerBaseKK.h b/widget/gonk/nativewindow/GonkConsumerBaseKK.h
deleted file mode 100644
index e198ad843..000000000
--- a/widget/gonk/nativewindow/GonkConsumerBaseKK.h
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKCONSUMERBASE_KK_H
-#define NATIVEWINDOW_GONKCONSUMERBASE_KK_H
-
-#include <ui/GraphicBuffer.h>
-
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-#include <gui/IConsumerListener.h>
-
-#include "GonkBufferQueueKK.h"
-
-namespace android {
-// ----------------------------------------------------------------------------
-
-class String8;
-
-// GonkConsumerBase is a base class for GonkBufferQueue consumer end-points. It
-// handles common tasks like management of the connection to the GonkBufferQueue
-// and the buffer pool.
-class GonkConsumerBase : public virtual RefBase,
- protected ConsumerListener {
-public:
- struct FrameAvailableListener : public virtual RefBase {
- // onFrameAvailable() is called each time an additional frame becomes
- // available for consumption. This means that frames that are queued
- // while in asynchronous mode only trigger the callback if no previous
- // frames are pending. Frames queued while in synchronous mode always
- // trigger the callback.
- //
- // This is called without any lock held and can be called concurrently
- // by multiple threads.
- virtual void onFrameAvailable() = 0;
- };
-
- virtual ~GonkConsumerBase();
-
- // abandon frees all the buffers and puts the GonkConsumerBase into the
- // 'abandoned' state. Once put in this state the GonkConsumerBase can never
- // leave it. When in the 'abandoned' state, all methods of the
- // IGraphicBufferProducer interface will fail with the NO_INIT error.
- //
- // Note that while calling this method causes all the buffers to be freed
- // from the perspective of the the GonkConsumerBase, if there are additional
- // references on the buffers (e.g. if a buffer is referenced by a client
- // or by OpenGL ES as a texture) then those buffer will remain allocated.
- void abandon();
-
- // set the name of the GonkConsumerBase that will be used to identify it in
- // log messages.
- void setName(const String8& name);
-
- // getBufferQueue returns the GonkBufferQueue object to which this
- // GonkConsumerBase is connected.
- sp<GonkBufferQueue> getBufferQueue() const;
-
- // dump writes the current state to a string. Child classes should add
- // their state to the dump by overriding the dumpLocked method, which is
- // called by these methods after locking the mutex.
- void dump(String8& result) const;
- void dump(String8& result, const char* prefix) const;
-
- // setFrameAvailableListener sets the listener object that will be notified
- // when a new frame becomes available.
- void setFrameAvailableListener(const wp<FrameAvailableListener>& listener);
-
-private:
- GonkConsumerBase(const GonkConsumerBase&);
- void operator=(const GonkConsumerBase&);
-
-protected:
-
- // GonkConsumerBase constructs a new GonkConsumerBase object to consume image
- // buffers from the given GonkBufferQueue.
- GonkConsumerBase(const sp<GonkBufferQueue>& bufferQueue, bool controlledByApp = false);
-
- // onLastStrongRef gets called by RefBase just before the dtor of the most
- // derived class. It is used to clean up the buffers so that GonkConsumerBase
- // can coordinate the clean-up by calling into virtual methods implemented
- // by the derived classes. This would not be possible from the
- // ConsuemrBase dtor because by the time that gets called the derived
- // classes have already been destructed.
- //
- // This methods should not need to be overridden by derived classes, but
- // if they are overridden the GonkConsumerBase implementation must be called
- // from the derived class.
- virtual void onLastStrongRef(const void* id);
-
- // Implementation of the GonkBufferQueue::ConsumerListener interface. These
- // calls are used to notify the GonkConsumerBase of asynchronous events in the
- // GonkBufferQueue. These methods should not need to be overridden by derived
- // classes, but if they are overridden the GonkConsumerBase implementation
- // must be called from the derived class.
- virtual void onFrameAvailable();
- virtual void onBuffersReleased();
-
- // freeBufferLocked frees up the given buffer slot. If the slot has been
- // initialized this will release the reference to the GraphicBuffer in that
- // slot. Otherwise it has no effect.
- //
- // Derived classes should override this method to clean up any state they
- // keep per slot. If it is overridden, the derived class's implementation
- // must call GonkConsumerBase::freeBufferLocked.
- //
- // This method must be called with mMutex locked.
- virtual void freeBufferLocked(int slotIndex);
-
- // abandonLocked puts the GonkBufferQueue into the abandoned state, causing
- // all future operations on it to fail. This method rather than the public
- // abandon method should be overridden by child classes to add abandon-
- // time behavior.
- //
- // Derived classes should override this method to clean up any object
- // state they keep (as opposed to per-slot state). If it is overridden,
- // the derived class's implementation must call GonkConsumerBase::abandonLocked.
- //
- // This method must be called with mMutex locked.
- virtual void abandonLocked();
-
- // dumpLocked dumps the current state of the GonkConsumerBase object to the
- // result string. Each line is prefixed with the string pointed to by the
- // prefix argument. The buffer argument points to a buffer that may be
- // used for intermediate formatting data, and the size of that buffer is
- // indicated by the size argument.
- //
- // Derived classes should override this method to dump their internal
- // state. If this method is overridden the derived class's implementation
- // should call GonkConsumerBase::dumpLocked.
- //
- // This method must be called with mMutex locked.
- virtual void dumpLocked(String8& result, const char* prefix) const;
-
- // acquireBufferLocked fetches the next buffer from the GonkBufferQueue and
- // updates the buffer slot for the buffer returned.
- //
- // Derived classes should override this method to perform any
- // initialization that must take place the first time a buffer is assigned
- // to a slot. If it is overridden the derived class's implementation must
- // call GonkConsumerBase::acquireBufferLocked.
- virtual status_t acquireBufferLocked(IGonkGraphicBufferConsumer::BufferItem *item,
- nsecs_t presentWhen);
-
- // releaseBufferLocked relinquishes control over a buffer, returning that
- // control to the GonkBufferQueue.
- //
- // Derived classes should override this method to perform any cleanup that
- // must take place when a buffer is released back to the GonkBufferQueue. If
- // it is overridden the derived class's implementation must call
- // GonkConsumerBase::releaseBufferLocked.
- virtual status_t releaseBufferLocked(int slot, const sp<GraphicBuffer> graphicBuffer);
-
- // returns true iff the slot still has the graphicBuffer in it.
- bool stillTracking(int slot, const sp<GraphicBuffer> graphicBuffer);
-
- // addReleaseFence* adds the sync points associated with a fence to the set
- // of sync points that must be reached before the buffer in the given slot
- // may be used after the slot has been released. This should be called by
- // derived classes each time some asynchronous work is kicked off that
- // references the buffer.
- status_t addReleaseFence(int slot,
- const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence);
- status_t addReleaseFenceLocked(int slot,
- const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence);
-
- // Slot contains the information and object references that
- // GonkConsumerBase maintains about a GonkBufferQueue buffer slot.
- struct Slot {
- // mGraphicBuffer is the Gralloc buffer store in the slot or NULL if
- // no Gralloc buffer is in the slot.
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mFence is a fence which will signal when the buffer associated with
- // this buffer slot is no longer being used by the consumer and can be
- // overwritten. The buffer can be dequeued before the fence signals;
- // the producer is responsible for delaying writes until it signals.
- sp<Fence> mFence;
-
- // the frame number of the last acquired frame for this slot
- uint64_t mFrameNumber;
- };
-
- // mSlots stores the buffers that have been allocated by the GonkBufferQueue
- // for each buffer slot. It is initialized to null pointers, and gets
- // filled in with the result of GonkBufferQueue::acquire when the
- // client dequeues a buffer from a
- // slot that has not yet been used. The buffer allocated to a slot will also
- // be replaced if the requested buffer usage or geometry differs from that
- // of the buffer allocated to a slot.
- Slot mSlots[GonkBufferQueue::NUM_BUFFER_SLOTS];
-
- // mAbandoned indicates that the GonkBufferQueue will no longer be used to
- // consume images buffers pushed to it using the IGraphicBufferProducer
- // interface. It is initialized to false, and set to true in the abandon
- // method. A GonkBufferQueue that has been abandoned will return the NO_INIT
- // error from all IGonkConsumerBase methods capable of returning an error.
- bool mAbandoned;
-
- // mName is a string used to identify the GonkConsumerBase in log messages.
- // It can be set by the setName method.
- String8 mName;
-
- // mFrameAvailableListener is the listener object that will be called when a
- // new frame becomes available. If it is not NULL it will be called from
- // queueBuffer.
- wp<FrameAvailableListener> mFrameAvailableListener;
-
- // The GonkConsumerBase has-a GonkBufferQueue and is responsible for creating this object
- // if none is supplied
- sp<GonkBufferQueue> mConsumer;
-
- // mMutex is the mutex used to prevent concurrent access to the member
- // variables of GonkConsumerBase objects. It must be locked whenever the
- // member variables are accessed or when any of the *Locked methods are
- // called.
- //
- // This mutex is intended to be locked by derived classes.
- mutable Mutex mMutex;
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // NATIVEWINDOW_GONKCONSUMERBASE_H
diff --git a/widget/gonk/nativewindow/GonkConsumerBaseLL.cpp b/widget/gonk/nativewindow/GonkConsumerBaseLL.cpp
deleted file mode 100644
index 5b1166b57..000000000
--- a/widget/gonk/nativewindow/GonkConsumerBaseLL.cpp
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <inttypes.h>
-
-#define LOG_TAG "GonkConsumerBase"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-//#define LOG_NDEBUG 0
-
-#define EGL_EGLEXT_PROTOTYPES
-
-#include <hardware/hardware.h>
-
-#include <gui/IGraphicBufferAlloc.h>
-
-#include <utils/Log.h>
-#include <utils/String8.h>
-
-#include "GonkConsumerBaseLL.h"
-
-namespace android {
-
-// Get an ID that's unique within this process.
-static int32_t createProcessUniqueId() {
- static volatile int32_t globalCounter = 0;
- return android_atomic_inc(&globalCounter);
-}
-
-GonkConsumerBase::GonkConsumerBase(const sp<IGonkGraphicBufferConsumer>& bufferQueue, bool controlledByApp) :
- mAbandoned(false),
- mConsumer(bufferQueue) {
- // Choose a name using the PID and a process-unique ID.
- mName = String8::format("unnamed-%d-%d", getpid(), createProcessUniqueId());
-
- // Note that we can't create an sp<...>(this) in a ctor that will not keep a
- // reference once the ctor ends, as that would cause the refcount of 'this'
- // dropping to 0 at the end of the ctor. Since all we need is a wp<...>
- // that's what we create.
- wp<ConsumerListener> listener = static_cast<ConsumerListener*>(this);
- sp<IConsumerListener> proxy = new GonkBufferQueue::ProxyConsumerListener(listener);
-
- status_t err = mConsumer->consumerConnect(proxy, controlledByApp);
- if (err != NO_ERROR) {
- ALOGE("GonkConsumerBase: error connecting to GonkBufferQueue: %s (%d)",
- strerror(-err), err);
- } else {
- mConsumer->setConsumerName(mName);
- }
-}
-
-GonkConsumerBase::~GonkConsumerBase() {
- ALOGV("~GonkConsumerBase");
- Mutex::Autolock lock(mMutex);
-
- // Verify that abandon() has been called before we get here. This should
- // be done by GonkConsumerBase::onLastStrongRef(), but it's possible for a
- // derived class to override that method and not call
- // GonkConsumerBase::onLastStrongRef().
- LOG_ALWAYS_FATAL_IF(!mAbandoned, "[%s] ~GonkConsumerBase was called, but the "
- "consumer is not abandoned!", mName.string());
-}
-
-void GonkConsumerBase::onLastStrongRef(const void* id __attribute__((unused))) {
- abandon();
-}
-
-void GonkConsumerBase::freeBufferLocked(int slotIndex) {
- ALOGV("freeBufferLocked: slotIndex=%d", slotIndex);
- mSlots[slotIndex].mGraphicBuffer = 0;
- mSlots[slotIndex].mFence = Fence::NO_FENCE;
- mSlots[slotIndex].mFrameNumber = 0;
-}
-
-#if ANDROID_VERSION == 21
-void GonkConsumerBase::onFrameAvailable() {
-#else
-void GonkConsumerBase::onFrameAvailable(const ::android::BufferItem& item) {
-#endif
- ALOGV("onFrameAvailable");
-
- sp<FrameAvailableListener> listener;
- { // scope for the lock
- Mutex::Autolock lock(mMutex);
- listener = mFrameAvailableListener.promote();
- }
-
- if (listener != NULL) {
- ALOGV("actually calling onFrameAvailable");
- listener->onFrameAvailable();
- }
-}
-
-void GonkConsumerBase::onBuffersReleased() {
- Mutex::Autolock lock(mMutex);
-
- ALOGV("onBuffersReleased");
-
- if (mAbandoned) {
- // Nothing to do if we're already abandoned.
- return;
- }
-
- uint64_t mask = 0;
- mConsumer->getReleasedBuffers(&mask);
- for (int i = 0; i < GonkBufferQueue::NUM_BUFFER_SLOTS; i++) {
- if (mask & (1ULL << i)) {
- freeBufferLocked(i);
- }
- }
-}
-
-void GonkConsumerBase::onSidebandStreamChanged() {
-}
-
-void GonkConsumerBase::abandon() {
- ALOGV("abandon");
- Mutex::Autolock lock(mMutex);
-
- if (!mAbandoned) {
- abandonLocked();
- mAbandoned = true;
- }
-}
-
-void GonkConsumerBase::abandonLocked() {
- ALOGV("abandonLocked");
- for (int i =0; i < GonkBufferQueue::NUM_BUFFER_SLOTS; i++) {
- freeBufferLocked(i);
- }
- // disconnect from the BufferQueue
- mConsumer->consumerDisconnect();
- mConsumer.clear();
-}
-
-void GonkConsumerBase::setFrameAvailableListener(
- const wp<FrameAvailableListener>& listener) {
- ALOGV("setFrameAvailableListener");
- Mutex::Autolock lock(mMutex);
- mFrameAvailableListener = listener;
-}
-
-void GonkConsumerBase::dump(String8& result) const {
- dump(result, "");
-}
-
-void GonkConsumerBase::dump(String8& result, const char* prefix) const {
- Mutex::Autolock _l(mMutex);
- dumpLocked(result, prefix);
-}
-
-void GonkConsumerBase::dumpLocked(String8& result, const char* prefix) const {
- result.appendFormat("%smAbandoned=%d\n", prefix, int(mAbandoned));
-
- if (!mAbandoned) {
- mConsumer->dumpToString(result, prefix);
- }
-}
-
-status_t GonkConsumerBase::acquireBufferLocked(GonkBufferQueue::BufferItem *item,
- nsecs_t presentWhen) {
- status_t err = mConsumer->acquireBuffer(item, presentWhen);
- if (err != NO_ERROR) {
- return err;
- }
-
- if (item->mGraphicBuffer != NULL) {
- mSlots[item->mBuf].mGraphicBuffer = item->mGraphicBuffer;
- }
-
- mSlots[item->mBuf].mFrameNumber = item->mFrameNumber;
- mSlots[item->mBuf].mFence = item->mFence;
-
- ALOGV("acquireBufferLocked: -> slot=%d/%" PRIu64,
- item->mBuf, item->mFrameNumber);
-
- return OK;
-}
-
-status_t GonkConsumerBase::addReleaseFence(int slot,
- const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence) {
- Mutex::Autolock lock(mMutex);
- return addReleaseFenceLocked(slot, graphicBuffer, fence);
-}
-
-status_t GonkConsumerBase::addReleaseFenceLocked(int slot,
- const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence) {
- ALOGV("addReleaseFenceLocked: slot=%d", slot);
-
- // If consumer no longer tracks this graphicBuffer, we can safely
- // drop this fence, as it will never be received by the producer.
- if (!stillTracking(slot, graphicBuffer)) {
- return OK;
- }
-
- if (!mSlots[slot].mFence.get()) {
- mSlots[slot].mFence = fence;
- } else {
- sp<Fence> mergedFence = Fence::merge(
- String8::format("%.28s:%d", mName.string(), slot),
- mSlots[slot].mFence, fence);
- if (!mergedFence.get()) {
- ALOGE("failed to merge release fences");
- // synchronization is broken, the best we can do is hope fences
- // signal in order so the new fence will act like a union
- mSlots[slot].mFence = fence;
- return BAD_VALUE;
- }
- mSlots[slot].mFence = mergedFence;
- }
-
- return OK;
-}
-
-status_t GonkConsumerBase::releaseBufferLocked(int slot, const sp<GraphicBuffer> graphicBuffer) {
- // If consumer no longer tracks this graphicBuffer (we received a new
- // buffer on the same slot), the buffer producer is definitely no longer
- // tracking it.
- if (!stillTracking(slot, graphicBuffer)) {
- return OK;
- }
-
- ALOGV("releaseBufferLocked: slot=%d/%" PRIu64,
- slot, mSlots[slot].mFrameNumber);
- status_t err = mConsumer->releaseBuffer(slot, mSlots[slot].mFrameNumber, mSlots[slot].mFence);
- if (err == IGonkGraphicBufferConsumer::STALE_BUFFER_SLOT) {
- freeBufferLocked(slot);
- }
-
- mSlots[slot].mFence = Fence::NO_FENCE;
-
- return err;
-}
-
-bool GonkConsumerBase::stillTracking(int slot,
- const sp<GraphicBuffer> graphicBuffer) {
- if (slot < 0 || slot >= GonkBufferQueue::NUM_BUFFER_SLOTS) {
- return false;
- }
- return (mSlots[slot].mGraphicBuffer != NULL &&
- mSlots[slot].mGraphicBuffer->handle == graphicBuffer->handle);
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkConsumerBaseLL.h b/widget/gonk/nativewindow/GonkConsumerBaseLL.h
deleted file mode 100644
index 0b2c2d166..000000000
--- a/widget/gonk/nativewindow/GonkConsumerBaseLL.h
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKCONSUMERBASE_LL_H
-#define NATIVEWINDOW_GONKCONSUMERBASE_LL_H
-
-#include <ui/GraphicBuffer.h>
-
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-#include <gui/IConsumerListener.h>
-
-#include "GonkBufferQueueLL.h"
-
-namespace android {
-// ----------------------------------------------------------------------------
-
-class String8;
-
-// GonkConsumerBase is a base class for GonkBufferQueue consumer end-points. It
-// handles common tasks like management of the connection to the GonkBufferQueue
-// and the buffer pool.
-class GonkConsumerBase : public virtual RefBase,
- protected ConsumerListener {
-public:
- struct FrameAvailableListener : public virtual RefBase {
- // onFrameAvailable() is called each time an additional frame becomes
- // available for consumption. This means that frames that are queued
- // while in asynchronous mode only trigger the callback if no previous
- // frames are pending. Frames queued while in synchronous mode always
- // trigger the callback.
- //
- // This is called without any lock held and can be called concurrently
- // by multiple threads.
- virtual void onFrameAvailable() = 0;
- };
-
- virtual ~GonkConsumerBase();
-
- // abandon frees all the buffers and puts the GonkConsumerBase into the
- // 'abandoned' state. Once put in this state the GonkConsumerBase can never
- // leave it. When in the 'abandoned' state, all methods of the
- // IGraphicBufferProducer interface will fail with the NO_INIT error.
- //
- // Note that while calling this method causes all the buffers to be freed
- // from the perspective of the the GonkConsumerBase, if there are additional
- // references on the buffers (e.g. if a buffer is referenced by a client
- // or by OpenGL ES as a texture) then those buffer will remain allocated.
- void abandon();
-
- // set the name of the GonkConsumerBase that will be used to identify it in
- // log messages.
- void setName(const String8& name);
-
- // dump writes the current state to a string. Child classes should add
- // their state to the dump by overriding the dumpLocked method, which is
- // called by these methods after locking the mutex.
- void dump(String8& result) const;
- void dump(String8& result, const char* prefix) const;
-
- // setFrameAvailableListener sets the listener object that will be notified
- // when a new frame becomes available.
- void setFrameAvailableListener(const wp<FrameAvailableListener>& listener);
-
-private:
- GonkConsumerBase(const GonkConsumerBase&);
- void operator=(const GonkConsumerBase&);
-
-protected:
- // GonkConsumerBase constructs a new GonkConsumerBase object to consume image
- // buffers from the given IGonkGraphicBufferConsumer.
- // The controlledByApp flag indicates that this consumer is under the application's
- // control.
- GonkConsumerBase(const sp<IGonkGraphicBufferConsumer>& consumer, bool controlledByApp = false);
-
- // onLastStrongRef gets called by RefBase just before the dtor of the most
- // derived class. It is used to clean up the buffers so that GonkConsumerBase
- // can coordinate the clean-up by calling into virtual methods implemented
- // by the derived classes. This would not be possible from the
- // ConsuemrBase dtor because by the time that gets called the derived
- // classes have already been destructed.
- //
- // This methods should not need to be overridden by derived classes, but
- // if they are overridden the GonkConsumerBase implementation must be called
- // from the derived class.
- virtual void onLastStrongRef(const void* id);
-
- // Implementation of the IConsumerListener interface. These
- // calls are used to notify the GonkConsumerBase of asynchronous events in the
- // GonkBufferQueue. The onFrameAvailable and onBuffersReleased methods should
- // not need to be overridden by derived classes, but if they are overridden
- // the GonkConsumerBase implementation must be called from the derived class.
- // The GonkConsumerBase version of onSidebandStreamChanged does nothing and can
- // be overriden by derived classes if they want the notification.
-#if ANDROID_VERSION == 21
- virtual void onFrameAvailable();
-#else
- virtual void onFrameAvailable(const ::android::BufferItem& item);
- virtual void onFrameReplaced(const ::android::BufferItem& item) {};
-#endif
- virtual void onBuffersReleased();
- virtual void onSidebandStreamChanged();
-
- // freeBufferLocked frees up the given buffer slot. If the slot has been
- // initialized this will release the reference to the GraphicBuffer in that
- // slot. Otherwise it has no effect.
- //
- // Derived classes should override this method to clean up any state they
- // keep per slot. If it is overridden, the derived class's implementation
- // must call GonkConsumerBase::freeBufferLocked.
- //
- // This method must be called with mMutex locked.
- virtual void freeBufferLocked(int slotIndex);
-
- // abandonLocked puts the GonkBufferQueue into the abandoned state, causing
- // all future operations on it to fail. This method rather than the public
- // abandon method should be overridden by child classes to add abandon-
- // time behavior.
- //
- // Derived classes should override this method to clean up any object
- // state they keep (as opposed to per-slot state). If it is overridden,
- // the derived class's implementation must call GonkConsumerBase::abandonLocked.
- //
- // This method must be called with mMutex locked.
- virtual void abandonLocked();
-
- // dumpLocked dumps the current state of the GonkConsumerBase object to the
- // result string. Each line is prefixed with the string pointed to by the
- // prefix argument. The buffer argument points to a buffer that may be
- // used for intermediate formatting data, and the size of that buffer is
- // indicated by the size argument.
- //
- // Derived classes should override this method to dump their internal
- // state. If this method is overridden the derived class's implementation
- // should call GonkConsumerBase::dumpLocked.
- //
- // This method must be called with mMutex locked.
- virtual void dumpLocked(String8& result, const char* prefix) const;
-
- // acquireBufferLocked fetches the next buffer from the GonkBufferQueue and
- // updates the buffer slot for the buffer returned.
- //
- // Derived classes should override this method to perform any
- // initialization that must take place the first time a buffer is assigned
- // to a slot. If it is overridden the derived class's implementation must
- // call GonkConsumerBase::acquireBufferLocked.
- virtual status_t acquireBufferLocked(IGonkGraphicBufferConsumer::BufferItem *item,
- nsecs_t presentWhen);
-
- // releaseBufferLocked relinquishes control over a buffer, returning that
- // control to the GonkBufferQueue.
- //
- // Derived classes should override this method to perform any cleanup that
- // must take place when a buffer is released back to the GonkBufferQueue. If
- // it is overridden the derived class's implementation must call
- // GonkConsumerBase::releaseBufferLocked.
- virtual status_t releaseBufferLocked(int slot, const sp<GraphicBuffer> graphicBuffer);
-
- // returns true iff the slot still has the graphicBuffer in it.
- bool stillTracking(int slot, const sp<GraphicBuffer> graphicBuffer);
-
- // addReleaseFence* adds the sync points associated with a fence to the set
- // of sync points that must be reached before the buffer in the given slot
- // may be used after the slot has been released. This should be called by
- // derived classes each time some asynchronous work is kicked off that
- // references the buffer.
- status_t addReleaseFence(int slot,
- const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence);
- status_t addReleaseFenceLocked(int slot,
- const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence);
-
- // Slot contains the information and object references that
- // GonkConsumerBase maintains about a GonkBufferQueue buffer slot.
- struct Slot {
- // mGraphicBuffer is the Gralloc buffer store in the slot or NULL if
- // no Gralloc buffer is in the slot.
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mFence is a fence which will signal when the buffer associated with
- // this buffer slot is no longer being used by the consumer and can be
- // overwritten. The buffer can be dequeued before the fence signals;
- // the producer is responsible for delaying writes until it signals.
- sp<Fence> mFence;
-
- // the frame number of the last acquired frame for this slot
- uint64_t mFrameNumber;
- };
-
- // mSlots stores the buffers that have been allocated by the GonkBufferQueue
- // for each buffer slot. It is initialized to null pointers, and gets
- // filled in with the result of GonkBufferQueue::acquire when the
- // client dequeues a buffer from a
- // slot that has not yet been used. The buffer allocated to a slot will also
- // be replaced if the requested buffer usage or geometry differs from that
- // of the buffer allocated to a slot.
- Slot mSlots[GonkBufferQueue::NUM_BUFFER_SLOTS];
-
- // mAbandoned indicates that the GonkBufferQueue will no longer be used to
- // consume images buffers pushed to it using the IGraphicBufferProducer
- // interface. It is initialized to false, and set to true in the abandon
- // method. A GonkBufferQueue that has been abandoned will return the NO_INIT
- // error from all IConsumerBase methods capable of returning an error.
- bool mAbandoned;
-
- // mName is a string used to identify the GonkConsumerBase in log messages.
- // It can be set by the setName method.
- String8 mName;
-
- // mFrameAvailableListener is the listener object that will be called when a
- // new frame becomes available. If it is not NULL it will be called from
- // queueBuffer.
- wp<FrameAvailableListener> mFrameAvailableListener;
-
- // The GonkConsumerBase has-a GonkBufferQueue and is responsible for creating this object
- // if none is supplied
- sp<IGonkGraphicBufferConsumer> mConsumer;
-
- // mMutex is the mutex used to prevent concurrent access to the member
- // variables of GonkConsumerBase objects. It must be locked whenever the
- // member variables are accessed or when any of the *Locked methods are
- // called.
- //
- // This mutex is intended to be locked by derived classes.
- mutable Mutex mMutex;
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // NATIVEWINDOW_GONKCONSUMERBASE_LL_H
diff --git a/widget/gonk/nativewindow/GonkNativeWindow.h b/widget/gonk/nativewindow/GonkNativeWindow.h
deleted file mode 100644
index 61b6780b8..000000000
--- a/widget/gonk/nativewindow/GonkNativeWindow.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/* Copyright 2013 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 21
-# include "GonkNativeWindowLL.h"
-#elif defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 19
-# include "GonkNativeWindowKK.h"
-#elif defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 17
-# include "GonkNativeWindowJB.h"
-#endif
diff --git a/widget/gonk/nativewindow/GonkNativeWindowJB.cpp b/widget/gonk/nativewindow/GonkNativeWindowJB.cpp
deleted file mode 100644
index e38642009..000000000
--- a/widget/gonk/nativewindow/GonkNativeWindowJB.cpp
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "GonkNativeWindow"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-#include <utils/Log.h>
-
-#include "GonkNativeWindowJB.h"
-#include "GrallocImages.h"
-#include "mozilla/layers/ImageBridgeChild.h"
-#include "mozilla/RefPtr.h"
-
-#define BI_LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
-#define BI_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
-#define BI_LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define BI_LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
-#define BI_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
-using namespace mozilla;
-using namespace mozilla::layers;
-
-namespace android {
-
-GonkNativeWindow::GonkNativeWindow(int bufferCount) :
- GonkConsumerBase(new GonkBufferQueue(true) ),
- mNewFrameCallback(nullptr)
-{
- mBufferQueue->setMaxAcquiredBufferCount(bufferCount);
-}
-
-GonkNativeWindow::~GonkNativeWindow() {
-}
-
-void GonkNativeWindow::setName(const String8& name) {
- Mutex::Autolock _l(mMutex);
- mName = name;
- mBufferQueue->setConsumerName(name);
-}
-#if ANDROID_VERSION >= 18
-status_t GonkNativeWindow::acquireBuffer(BufferItem *item, bool waitForFence) {
- status_t err;
-
- if (!item) return BAD_VALUE;
-
- Mutex::Autolock _l(mMutex);
-
- err = acquireBufferLocked(item);
- if (err != OK) {
- if (err != NO_BUFFER_AVAILABLE) {
- BI_LOGE("Error acquiring buffer: %s (%d)", strerror(err), err);
- }
- return err;
- }
-
- if (waitForFence) {
- err = item->mFence->waitForever("GonkNativeWindow::acquireBuffer");
- if (err != OK) {
- BI_LOGE("Failed to wait for fence of acquired buffer: %s (%d)",
- strerror(-err), err);
- return err;
- }
- }
-
- item->mGraphicBuffer = mSlots[item->mBuf].mGraphicBuffer;
-
- return OK;
-}
-
-status_t GonkNativeWindow::releaseBuffer(const BufferItem &item,
- const sp<Fence>& releaseFence) {
- status_t err;
-
- Mutex::Autolock _l(mMutex);
-
- err = addReleaseFenceLocked(item.mBuf, releaseFence);
-
- err = releaseBufferLocked(item.mBuf);
- if (err != OK) {
- BI_LOGE("Failed to release buffer: %s (%d)",
- strerror(-err), err);
- }
- return err;
-}
-#endif
-
-status_t GonkNativeWindow::setDefaultBufferSize(uint32_t w, uint32_t h) {
- Mutex::Autolock _l(mMutex);
- return mBufferQueue->setDefaultBufferSize(w, h);
-}
-
-status_t GonkNativeWindow::setDefaultBufferFormat(uint32_t defaultFormat) {
- Mutex::Autolock _l(mMutex);
- return mBufferQueue->setDefaultBufferFormat(defaultFormat);
-}
-
-already_AddRefed<TextureClient>
-GonkNativeWindow::getCurrentBuffer() {
- Mutex::Autolock _l(mMutex);
- GonkBufferQueue::BufferItem item;
-
- // In asynchronous mode the list is guaranteed to be one buffer
- // deep, while in synchronous mode we use the oldest buffer.
- status_t err = acquireBufferLocked(&item);
- if (err != NO_ERROR) {
- return NULL;
- }
-
- RefPtr<TextureClient> textureClient =
- mBufferQueue->getTextureClientFromBuffer(item.mGraphicBuffer.get());
- if (!textureClient) {
- return NULL;
- }
- textureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
- return textureClient.forget();
-}
-
-/* static */ void
-GonkNativeWindow::RecycleCallback(TextureClient* client, void* closure) {
- GonkNativeWindow* nativeWindow =
- static_cast<GonkNativeWindow*>(closure);
-
- MOZ_ASSERT(client && !client->IsDead());
- client->ClearRecycleCallback();
- nativeWindow->returnBuffer(client);
-}
-
-void GonkNativeWindow::returnBuffer(TextureClient* client) {
- BI_LOGD("GonkNativeWindow::returnBuffer");
- Mutex::Autolock lock(mMutex);
-
- int index = mBufferQueue->getSlotFromTextureClientLocked(client);
- if (index < 0) {
- }
-
- FenceHandle handle = client->GetAndResetReleaseFenceHandle();
- RefPtr<FenceHandle::FdObj> fdObj = handle.GetAndResetFdObj();
- sp<Fence> fence = new Fence(fdObj->GetAndResetFd());
-
- addReleaseFenceLocked(index, fence);
-
- releaseBufferLocked(index);
-}
-
-already_AddRefed<TextureClient>
-GonkNativeWindow::getTextureClientFromBuffer(ANativeWindowBuffer* buffer) {
- Mutex::Autolock lock(mMutex);
- return mBufferQueue->getTextureClientFromBuffer(buffer);
-}
-
-void GonkNativeWindow::setNewFrameCallback(
- GonkNativeWindowNewFrameCallback* callback) {
- BI_LOGD("setNewFrameCallback");
- Mutex::Autolock lock(mMutex);
- mNewFrameCallback = callback;
-}
-
-void GonkNativeWindow::onFrameAvailable() {
- GonkConsumerBase::onFrameAvailable();
-
- if (mNewFrameCallback) {
- mNewFrameCallback->OnNewFrame();
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkNativeWindowJB.h b/widget/gonk/nativewindow/GonkNativeWindowJB.h
deleted file mode 100644
index e63a7527d..000000000
--- a/widget/gonk/nativewindow/GonkNativeWindowJB.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKNATIVEWINDOW_JB_H
-#define NATIVEWINDOW_GONKNATIVEWINDOW_JB_H
-
-#include <ui/GraphicBuffer.h>
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-
-#include "GonkConsumerBaseJB.h"
-#include "GrallocImages.h"
-#include "mozilla/layers/LayersSurfaces.h"
-
-namespace mozilla {
-namespace layers {
- class PGrallocBufferChild;
-}
-}
-
-namespace android {
-
-// The user of GonkNativeWindow who wants to receive notification of
-// new frames should implement this interface.
-class GonkNativeWindowNewFrameCallback {
-public:
- virtual void OnNewFrame() = 0;
-};
-
-/**
- * GonkNativeWindow is a GonkBufferQueue consumer endpoint that allows clients
- * access to the whole BufferItem entry from GonkBufferQueue. Multiple buffers may
- * be acquired at once, to be used concurrently by the client. This consumer can
- * operate either in synchronous or asynchronous mode.
- */
-class GonkNativeWindow: public GonkConsumerBase
-{
- typedef mozilla::layers::TextureClient TextureClient;
- public:
- typedef GonkConsumerBase::FrameAvailableListener FrameAvailableListener;
-
- typedef GonkBufferQueue::BufferItem BufferItem;
-
- enum { INVALID_BUFFER_SLOT = GonkBufferQueue::INVALID_BUFFER_SLOT };
- enum { NO_BUFFER_AVAILABLE = GonkBufferQueue::NO_BUFFER_AVAILABLE };
-
- // Create a new buffer item consumer. The consumerUsage parameter determines
- // the consumer usage flags passed to the graphics allocator. The
- // bufferCount parameter specifies how many buffers can be locked for user
- // access at the same time.
- GonkNativeWindow(int bufferCount = GonkBufferQueue::MIN_UNDEQUEUED_BUFFERS);
-
- virtual ~GonkNativeWindow();
-
- // set the name of the GonkNativeWindow that will be used to identify it in
- // log messages.
- void setName(const String8& name);
-
- // Gets the next graphics buffer from the producer, filling out the
- // passed-in BufferItem structure. Returns NO_BUFFER_AVAILABLE if the queue
- // of buffers is empty, and INVALID_OPERATION if the maximum number of
- // buffers is already acquired.
- //
- // Only a fixed number of buffers can be acquired at a time, determined by
- // the construction-time bufferCount parameter. If INVALID_OPERATION is
- // returned by acquireBuffer, then old buffers must be returned to the
- // queue by calling releaseBuffer before more buffers can be acquired.
- //
- // If waitForFence is true, and the acquired BufferItem has a valid fence object,
- // acquireBuffer will wait on the fence with no timeout before returning.
-#if ANDROID_VERSION >= 18
- status_t acquireBuffer(BufferItem *item, bool waitForFence = true);
-#endif
- // Returns an acquired buffer to the queue, allowing it to be reused. Since
- // only a fixed number of buffers may be acquired at a time, old buffers
- // must be released by calling releaseBuffer to ensure new buffers can be
- // acquired by acquireBuffer. Once a BufferItem is released, the caller must
- // not access any members of the BufferItem, and should immediately remove
- // all of its references to the BufferItem itself.
-#if ANDROID_VERSION >= 18
- status_t releaseBuffer(const BufferItem &item,
- const sp<Fence>& releaseFence = Fence::NO_FENCE);
-#endif
-
- sp<IGraphicBufferProducer> getProducerInterface() const { return getBufferQueue(); }
-
- // setDefaultBufferSize is used to set the size of buffers returned by
- // requestBuffers when a with and height of zero is requested.
- status_t setDefaultBufferSize(uint32_t w, uint32_t h);
-
- // setDefaultBufferFormat allows the BufferQueue to create
- // GraphicBuffers of a defaultFormat if no format is specified
- // in dequeueBuffer
- status_t setDefaultBufferFormat(uint32_t defaultFormat);
-
- // Get next frame from the queue, caller owns the returned buffer.
- already_AddRefed<TextureClient> getCurrentBuffer();
-
- // Return the buffer to the queue and mark it as FREE. After that
- // the buffer is useable again for the decoder.
- void returnBuffer(TextureClient* client);
-
- already_AddRefed<TextureClient> getTextureClientFromBuffer(ANativeWindowBuffer* buffer);
-
- void setNewFrameCallback(GonkNativeWindowNewFrameCallback* callback);
-
- static void RecycleCallback(TextureClient* client, void* closure);
-
-protected:
- virtual void onFrameAvailable();
-
-private:
- GonkNativeWindowNewFrameCallback* mNewFrameCallback;
-};
-
-} // namespace android
-
-#endif // NATIVEWINDOW_GONKNATIVEWINDOW_JB_H
diff --git a/widget/gonk/nativewindow/GonkNativeWindowKK.cpp b/widget/gonk/nativewindow/GonkNativeWindowKK.cpp
deleted file mode 100644
index cf34d6539..000000000
--- a/widget/gonk/nativewindow/GonkNativeWindowKK.cpp
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "GonkNativeWindow"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-#include <utils/Log.h>
-
-#include "GonkNativeWindowKK.h"
-#include "GrallocImages.h"
-
-using namespace mozilla;
-using namespace mozilla::layers;
-
-namespace android {
-
-GonkNativeWindow::GonkNativeWindow(int bufferCount) :
- GonkConsumerBase(new GonkBufferQueue(true), false),
- mNewFrameCallback(nullptr)
-{
- mConsumer->setMaxAcquiredBufferCount(bufferCount);
-}
-
-GonkNativeWindow::GonkNativeWindow(const sp<GonkBufferQueue>& bq,
- uint32_t consumerUsage, int bufferCount, bool controlledByApp) :
- GonkConsumerBase(bq, controlledByApp)
-{
- mConsumer->setConsumerUsageBits(consumerUsage);
- mConsumer->setMaxAcquiredBufferCount(bufferCount);
-}
-
-GonkNativeWindow::~GonkNativeWindow() {
-}
-
-void GonkNativeWindow::setName(const String8& name) {
- Mutex::Autolock _l(mMutex);
- mName = name;
- mConsumer->setConsumerName(name);
-}
-
-status_t GonkNativeWindow::acquireBuffer(BufferItem *item,
- nsecs_t presentWhen, bool waitForFence) {
- status_t err;
-
- if (!item) return BAD_VALUE;
-
- Mutex::Autolock _l(mMutex);
-
- err = acquireBufferLocked(item, presentWhen);
- if (err != OK) {
- if (err != NO_BUFFER_AVAILABLE) {
- ALOGE("Error acquiring buffer: %s (%d)", strerror(err), err);
- }
- return err;
- }
-
- if (waitForFence) {
- err = item->mFence->waitForever("GonkNativeWindow::acquireBuffer");
- if (err != OK) {
- ALOGE("Failed to wait for fence of acquired buffer: %s (%d)",
- strerror(-err), err);
- return err;
- }
- }
-
- item->mGraphicBuffer = mSlots[item->mBuf].mGraphicBuffer;
-
- return OK;
-}
-
-status_t GonkNativeWindow::releaseBuffer(const BufferItem &item,
- const sp<Fence>& releaseFence) {
- status_t err;
-
- Mutex::Autolock _l(mMutex);
-
- err = addReleaseFenceLocked(item.mBuf, item.mGraphicBuffer, releaseFence);
-
- err = releaseBufferLocked(item.mBuf, item.mGraphicBuffer);
- if (err != OK) {
- ALOGE("Failed to release buffer: %s (%d)",
- strerror(-err), err);
- }
- return err;
-}
-
-status_t GonkNativeWindow::setDefaultBufferSize(uint32_t w, uint32_t h) {
- Mutex::Autolock _l(mMutex);
- return mConsumer->setDefaultBufferSize(w, h);
-}
-
-status_t GonkNativeWindow::setDefaultBufferFormat(uint32_t defaultFormat) {
- Mutex::Autolock _l(mMutex);
- return mConsumer->setDefaultBufferFormat(defaultFormat);
-}
-
-already_AddRefed<TextureClient>
-GonkNativeWindow::getCurrentBuffer() {
- Mutex::Autolock _l(mMutex);
- BufferItem item;
-
- // In asynchronous mode the list is guaranteed to be one buffer
- // deep, while in synchronous mode we use the oldest buffer.
- status_t err = acquireBufferLocked(&item, 0); //???
- if (err != NO_ERROR) {
- return NULL;
- }
-
- RefPtr<TextureClient> textureClient =
- mConsumer->getTextureClientFromBuffer(item.mGraphicBuffer.get());
- if (!textureClient) {
- return NULL;
- }
- textureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
- return textureClient.forget();
-}
-
-/* static */ void
-GonkNativeWindow::RecycleCallback(TextureClient* client, void* closure) {
- GonkNativeWindow* nativeWindow =
- static_cast<GonkNativeWindow*>(closure);
-
- MOZ_ASSERT(client && !client->IsDead());
- client->ClearRecycleCallback();
- nativeWindow->returnBuffer(client);
-}
-
-void GonkNativeWindow::returnBuffer(TextureClient* client) {
- ALOGD("GonkNativeWindow::returnBuffer");
- Mutex::Autolock lock(mMutex);
-
- int index = mConsumer->getSlotFromTextureClientLocked(client);
- if (index < 0) {
- }
-
- FenceHandle handle = client->GetAndResetReleaseFenceHandle();
- RefPtr<FenceHandle::FdObj> fdObj = handle.GetAndResetFdObj();
- sp<Fence> fence = new Fence(fdObj->GetAndResetFd());
-
- addReleaseFenceLocked(index,
- mSlots[index].mGraphicBuffer,
- fence);
-
- releaseBufferLocked(index, mSlots[index].mGraphicBuffer);
-}
-
-already_AddRefed<TextureClient>
-GonkNativeWindow::getTextureClientFromBuffer(ANativeWindowBuffer* buffer) {
- Mutex::Autolock lock(mMutex);
- return mConsumer->getTextureClientFromBuffer(buffer);
-}
-
-void GonkNativeWindow::setNewFrameCallback(
- GonkNativeWindowNewFrameCallback* callback) {
- ALOGD("setNewFrameCallback");
- Mutex::Autolock lock(mMutex);
- mNewFrameCallback = callback;
-}
-
-void GonkNativeWindow::onFrameAvailable() {
- GonkConsumerBase::onFrameAvailable();
-
- if (mNewFrameCallback) {
- mNewFrameCallback->OnNewFrame();
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkNativeWindowKK.h b/widget/gonk/nativewindow/GonkNativeWindowKK.h
deleted file mode 100644
index e36788b41..000000000
--- a/widget/gonk/nativewindow/GonkNativeWindowKK.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2013 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKNATIVEWINDOW_KK_H
-#define NATIVEWINDOW_GONKNATIVEWINDOW_KK_H
-
-#include <ui/GraphicBuffer.h>
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-
-#include "GonkConsumerBaseKK.h"
-#include "GrallocImages.h"
-#include "IGonkGraphicBufferConsumer.h"
-#include "mozilla/layers/ImageBridgeChild.h"
-#include "mozilla/layers/LayersSurfaces.h"
-
-namespace mozilla {
-namespace layers {
- class PGrallocBufferChild;
-}
-}
-
-namespace android {
-
-// The user of GonkNativeWindow who wants to receive notification of
-// new frames should implement this interface.
-class GonkNativeWindowNewFrameCallback {
-public:
- virtual void OnNewFrame() = 0;
-};
-
-/**
- * GonkNativeWindow is a GonkBufferQueue consumer endpoint that allows clients
- * access to the whole BufferItem entry from GonkBufferQueue. Multiple buffers may
- * be acquired at once, to be used concurrently by the client. This consumer can
- * operate either in synchronous or asynchronous mode.
- */
-class GonkNativeWindow: public GonkConsumerBase
-{
- typedef mozilla::layers::TextureClient TextureClient;
- public:
- typedef GonkConsumerBase::FrameAvailableListener FrameAvailableListener;
- typedef IGonkGraphicBufferConsumer::BufferItem BufferItem;
-
- enum { INVALID_BUFFER_SLOT = GonkBufferQueue::INVALID_BUFFER_SLOT };
- enum { NO_BUFFER_AVAILABLE = GonkBufferQueue::NO_BUFFER_AVAILABLE };
-
- // Create a new buffer item consumer. The consumerUsage parameter determines
- // the consumer usage flags passed to the graphics allocator. The
- // bufferCount parameter specifies how many buffers can be locked for user
- // access at the same time.
- // controlledByApp tells whether this consumer is controlled by the
- // application.
- GonkNativeWindow(int bufferCount = GonkBufferQueue::MIN_UNDEQUEUED_BUFFERS);
- GonkNativeWindow(const sp<GonkBufferQueue>& bq, uint32_t consumerUsage,
- int bufferCount = GonkBufferQueue::MIN_UNDEQUEUED_BUFFERS,
- bool controlledByApp = false);
-
- virtual ~GonkNativeWindow();
-
- // set the name of the GonkNativeWindow that will be used to identify it in
- // log messages.
- void setName(const String8& name);
-
- // Gets the next graphics buffer from the producer, filling out the
- // passed-in BufferItem structure. Returns NO_BUFFER_AVAILABLE if the queue
- // of buffers is empty, and INVALID_OPERATION if the maximum number of
- // buffers is already acquired.
- //
- // Only a fixed number of buffers can be acquired at a time, determined by
- // the construction-time bufferCount parameter. If INVALID_OPERATION is
- // returned by acquireBuffer, then old buffers must be returned to the
- // queue by calling releaseBuffer before more buffers can be acquired.
- //
- // If waitForFence is true, and the acquired BufferItem has a valid fence object,
- // acquireBuffer will wait on the fence with no timeout before returning.
- status_t acquireBuffer(BufferItem *item, nsecs_t presentWhen,
- bool waitForFence = true);
-
- // Returns an acquired buffer to the queue, allowing it to be reused. Since
- // only a fixed number of buffers may be acquired at a time, old buffers
- // must be released by calling releaseBuffer to ensure new buffers can be
- // acquired by acquireBuffer. Once a BufferItem is released, the caller must
- // not access any members of the BufferItem, and should immediately remove
- // all of its references to the BufferItem itself.
- status_t releaseBuffer(const BufferItem &item,
- const sp<Fence>& releaseFence = Fence::NO_FENCE);
-
- // setDefaultBufferSize is used to set the size of buffers returned by
- // requestBuffers when a with and height of zero is requested.
- status_t setDefaultBufferSize(uint32_t w, uint32_t h);
-
- // setDefaultBufferFormat allows the BufferQueue to create
- // GraphicBuffers of a defaultFormat if no format is specified
- // in dequeueBuffer
- status_t setDefaultBufferFormat(uint32_t defaultFormat);
-
- // Get next frame from the queue, caller owns the returned buffer.
- already_AddRefed<TextureClient> getCurrentBuffer();
-
- // Return the buffer to the queue and mark it as FREE. After that
- // the buffer is useable again for the decoder.
- void returnBuffer(TextureClient* client);
-
- already_AddRefed<TextureClient> getTextureClientFromBuffer(ANativeWindowBuffer* buffer);
-
- void setNewFrameCallback(GonkNativeWindowNewFrameCallback* callback);
-
- static void RecycleCallback(TextureClient* client, void* closure);
-
-protected:
- virtual void onFrameAvailable();
-
-private:
- GonkNativeWindowNewFrameCallback* mNewFrameCallback;
-};
-
-} // namespace android
-
-#endif // NATIVEWINDOW_GONKNATIVEWINDOW_JB_H
diff --git a/widget/gonk/nativewindow/GonkNativeWindowLL.cpp b/widget/gonk/nativewindow/GonkNativeWindowLL.cpp
deleted file mode 100644
index 48644a22f..000000000
--- a/widget/gonk/nativewindow/GonkNativeWindowLL.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "GonkNativeWindow"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-#include <utils/Log.h>
-
-#include "GonkNativeWindowLL.h"
-
-using namespace mozilla;
-using namespace mozilla::layers;
-
-namespace android {
-
-GonkNativeWindow::GonkNativeWindow(
- const sp<IGonkGraphicBufferConsumer>& consumer, int bufferCount) :
- GonkConsumerBase(consumer, false),
- mNewFrameCallback(nullptr)
-{
- if (bufferCount != DEFAULT_MAX_BUFFERS) {
- status_t err = mConsumer->setMaxAcquiredBufferCount(bufferCount);
- LOG_ALWAYS_FATAL_IF(err != OK,
- "Failed to set max acquired buffer count to %d", bufferCount);
- }
-}
-
-GonkNativeWindow::GonkNativeWindow(
- const sp<IGonkGraphicBufferConsumer>& consumer, uint32_t consumerUsage,
- int bufferCount, bool controlledByApp) :
- GonkConsumerBase(consumer, controlledByApp)
-{
- status_t err = mConsumer->setConsumerUsageBits(consumerUsage);
- LOG_ALWAYS_FATAL_IF(err != OK,
- "Failed to set consumer usage bits to %#x", consumerUsage);
- if (bufferCount != DEFAULT_MAX_BUFFERS) {
- err = mConsumer->setMaxAcquiredBufferCount(bufferCount);
- LOG_ALWAYS_FATAL_IF(err != OK,
- "Failed to set max acquired buffer count to %d", bufferCount);
- }
-}
-
-GonkNativeWindow::~GonkNativeWindow() {
-}
-
-void GonkNativeWindow::setName(const String8& name) {
- Mutex::Autolock _l(mMutex);
- mName = name;
- mConsumer->setConsumerName(name);
-}
-
-status_t GonkNativeWindow::acquireBuffer(BufferItem *item,
- nsecs_t presentWhen, bool waitForFence) {
- status_t err;
-
- if (!item) return BAD_VALUE;
-
- Mutex::Autolock _l(mMutex);
-
- err = acquireBufferLocked(item, presentWhen);
- if (err != OK) {
- if (err != NO_BUFFER_AVAILABLE) {
- ALOGE("Error acquiring buffer: %s (%d)", strerror(err), err);
- }
- return err;
- }
-
- if (waitForFence) {
- err = item->mFence->waitForever("GonkNativeWindow::acquireBuffer");
- if (err != OK) {
- ALOGE("Failed to wait for fence of acquired buffer: %s (%d)",
- strerror(-err), err);
- return err;
- }
- }
-
- item->mGraphicBuffer = mSlots[item->mBuf].mGraphicBuffer;
-
- return OK;
-}
-
-status_t GonkNativeWindow::releaseBuffer(const BufferItem &item,
- const sp<Fence>& releaseFence) {
- status_t err;
-
- Mutex::Autolock _l(mMutex);
-
- err = addReleaseFenceLocked(item.mBuf, item.mGraphicBuffer, releaseFence);
-
- err = releaseBufferLocked(item.mBuf, item.mGraphicBuffer);
- if (err != OK) {
- ALOGE("Failed to release buffer: %s (%d)",
- strerror(-err), err);
- }
- return err;
-}
-
-status_t GonkNativeWindow::setDefaultBufferSize(uint32_t w, uint32_t h) {
- Mutex::Autolock _l(mMutex);
- return mConsumer->setDefaultBufferSize(w, h);
-}
-
-status_t GonkNativeWindow::setDefaultBufferFormat(uint32_t defaultFormat) {
- Mutex::Autolock _l(mMutex);
- return mConsumer->setDefaultBufferFormat(defaultFormat);
-}
-
-already_AddRefed<TextureClient>
-GonkNativeWindow::getCurrentBuffer() {
- Mutex::Autolock _l(mMutex);
- BufferItem item;
-
- // In asynchronous mode the list is guaranteed to be one buffer
- // deep, while in synchronous mode we use the oldest buffer.
- status_t err = acquireBufferLocked(&item, 0); //???
- if (err != NO_ERROR) {
- return NULL;
- }
-
- RefPtr<TextureClient> textureClient =
- mConsumer->getTextureClientFromBuffer(item.mGraphicBuffer.get());
- if (!textureClient) {
- return NULL;
- }
- textureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
- return textureClient.forget();
-}
-
-/* static */ void
-GonkNativeWindow::RecycleCallback(TextureClient* client, void* closure) {
- GonkNativeWindow* nativeWindow =
- static_cast<GonkNativeWindow*>(closure);
-
- MOZ_ASSERT(client && !client->IsDead());
- client->ClearRecycleCallback();
- nativeWindow->returnBuffer(client);
-}
-
-void GonkNativeWindow::returnBuffer(TextureClient* client) {
- ALOGD("GonkNativeWindow::returnBuffer");
- Mutex::Autolock lock(mMutex);
-
- int index = mConsumer->getSlotFromTextureClientLocked(client);
- if (index < 0) {
- return;
- }
-
- FenceHandle handle = client->GetAndResetReleaseFenceHandle();
- RefPtr<FenceHandle::FdObj> fdObj = handle.GetAndResetFdObj();
- sp<Fence> fence = new Fence(fdObj->GetAndResetFd());
-
- status_t err;
- err = addReleaseFenceLocked(index,
- mSlots[index].mGraphicBuffer,
- fence);
-
- err = releaseBufferLocked(index, mSlots[index].mGraphicBuffer);
-
- if (err != OK) {
- ALOGE("Failed to return buffer: %s (%d)", strerror(-err), err);
- }
-}
-
-already_AddRefed<TextureClient>
-GonkNativeWindow::getTextureClientFromBuffer(ANativeWindowBuffer* buffer) {
- Mutex::Autolock lock(mMutex);
- return mConsumer->getTextureClientFromBuffer(buffer);
-}
-
-void GonkNativeWindow::setNewFrameCallback(
- GonkNativeWindowNewFrameCallback* callback) {
- ALOGD("setNewFrameCallback");
- Mutex::Autolock lock(mMutex);
- mNewFrameCallback = callback;
-}
-
-#if ANDROID_VERSION == 21
-void GonkNativeWindow::onFrameAvailable() {
- GonkConsumerBase::onFrameAvailable();
-#else
-void GonkNativeWindow::onFrameAvailable(const ::android::BufferItem &item) {
- GonkConsumerBase::onFrameAvailable(item);
-#endif
-
- if (mNewFrameCallback) {
- mNewFrameCallback->OnNewFrame();
- }
-}
-
-} // namespace android
diff --git a/widget/gonk/nativewindow/GonkNativeWindowLL.h b/widget/gonk/nativewindow/GonkNativeWindowLL.h
deleted file mode 100644
index 64cd6482d..000000000
--- a/widget/gonk/nativewindow/GonkNativeWindowLL.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- * Copyright (C) 2014 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_GONKNATIVEWINDOW_LL_H
-#define NATIVEWINDOW_GONKNATIVEWINDOW_LL_H
-
-#include <ui/GraphicBuffer.h>
-
-#include <utils/String8.h>
-#include <utils/Vector.h>
-#include <utils/threads.h>
-
-#include "GonkConsumerBaseLL.h"
-#include "IGonkGraphicBufferConsumerLL.h"
-
-namespace android {
-
-// The user of GonkNativeWindow who wants to receive notification of
-// new frames should implement this interface.
-class GonkNativeWindowNewFrameCallback {
-public:
- virtual void OnNewFrame() = 0;
-};
-
-/**
- * GonkNativeWindow is a GonkBufferQueue consumer endpoint that allows clients
- * access to the whole BufferItem entry from GonkBufferQueue. Multiple buffers may
- * be acquired at once, to be used concurrently by the client. This consumer can
- * operate either in synchronous or asynchronous mode.
- */
-class GonkNativeWindow: public GonkConsumerBase
-{
- typedef mozilla::layers::TextureClient TextureClient;
- public:
- typedef GonkConsumerBase::FrameAvailableListener FrameAvailableListener;
- typedef GonkBufferQueue::BufferItem BufferItem;
-
- enum { DEFAULT_MAX_BUFFERS = -1 };
- enum { INVALID_BUFFER_SLOT = GonkBufferQueue::INVALID_BUFFER_SLOT };
- enum { NO_BUFFER_AVAILABLE = GonkBufferQueue::NO_BUFFER_AVAILABLE };
-
- // Create a new buffer item consumer. The consumerUsage parameter determines
- // the consumer usage flags passed to the graphics allocator. The
- // bufferCount parameter specifies how many buffers can be locked for user
- // access at the same time.
- // controlledByApp tells whether this consumer is controlled by the
- // application.
- GonkNativeWindow(const sp<IGonkGraphicBufferConsumer>& consumer,
- int bufferCount = DEFAULT_MAX_BUFFERS);
- GonkNativeWindow(const sp<IGonkGraphicBufferConsumer>& consumer,
- uint32_t consumerUsage, int bufferCount = DEFAULT_MAX_BUFFERS,
- bool controlledByApp = false);
-
- virtual ~GonkNativeWindow();
-
- // set the name of the GonkNativeWindow that will be used to identify it in
- // log messages.
- void setName(const String8& name);
-
- // Gets the next graphics buffer from the producer, filling out the
- // passed-in BufferItem structure. Returns NO_BUFFER_AVAILABLE if the queue
- // of buffers is empty, and INVALID_OPERATION if the maximum number of
- // buffers is already acquired.
- //
- // Only a fixed number of buffers can be acquired at a time, determined by
- // the construction-time bufferCount parameter. If INVALID_OPERATION is
- // returned by acquireBuffer, then old buffers must be returned to the
- // queue by calling releaseBuffer before more buffers can be acquired.
- //
- // If waitForFence is true, and the acquired BufferItem has a valid fence object,
- // acquireBuffer will wait on the fence with no timeout before returning.
- status_t acquireBuffer(BufferItem *item, nsecs_t presentWhen,
- bool waitForFence = true);
-
- // Returns an acquired buffer to the queue, allowing it to be reused. Since
- // only a fixed number of buffers may be acquired at a time, old buffers
- // must be released by calling releaseBuffer to ensure new buffers can be
- // acquired by acquireBuffer. Once a BufferItem is released, the caller must
- // not access any members of the BufferItem, and should immediately remove
- // all of its references to the BufferItem itself.
- status_t releaseBuffer(const BufferItem &item,
- const sp<Fence>& releaseFence = Fence::NO_FENCE);
-
- // setDefaultBufferSize is used to set the size of buffers returned by
- // requestBuffers when a with and height of zero is requested.
- status_t setDefaultBufferSize(uint32_t w, uint32_t h);
-
- // setDefaultBufferFormat allows the GonkBufferQueue to create
- // GraphicBuffers of a defaultFormat if no format is specified
- // in dequeueBuffer
- status_t setDefaultBufferFormat(uint32_t defaultFormat);
-
- // Get next frame from the queue, caller owns the returned buffer.
- already_AddRefed<TextureClient> getCurrentBuffer();
-
- // Return the buffer to the queue and mark it as FREE. After that
- // the buffer is useable again for the decoder.
- void returnBuffer(TextureClient* client);
-
- already_AddRefed<TextureClient> getTextureClientFromBuffer(ANativeWindowBuffer* buffer);
-
- void setNewFrameCallback(GonkNativeWindowNewFrameCallback* callback);
-
- static void RecycleCallback(TextureClient* client, void* closure);
-
-protected:
-#if ANDROID_VERSION == 21
- virtual void onFrameAvailable();
-#else
- virtual void onFrameAvailable(const ::android::BufferItem &item);
-#endif
-
-private:
- GonkNativeWindowNewFrameCallback* mNewFrameCallback;
-};
-
-} // namespace android
-
-#endif // NATIVEWINDOW_GONKNATIVEWINDOW_LL_H
diff --git a/widget/gonk/nativewindow/IGonkGraphicBufferConsumer.h b/widget/gonk/nativewindow/IGonkGraphicBufferConsumer.h
deleted file mode 100644
index 14541c9b4..000000000
--- a/widget/gonk/nativewindow/IGonkGraphicBufferConsumer.h
+++ /dev/null
@@ -1,20 +0,0 @@
-/* Copyright 2013 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#if defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 21
-# include "IGonkGraphicBufferConsumerLL.h"
-#elif defined(MOZ_WIDGET_GONK) && ANDROID_VERSION >= 19
-# include "IGonkGraphicBufferConsumerKK.h"
-#endif
diff --git a/widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.cpp b/widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.cpp
deleted file mode 100644
index c4c9f6578..000000000
--- a/widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.cpp
+++ /dev/null
@@ -1,480 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define EGL_EGLEXT_PROTOTYPES
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-
-#include <binder/Parcel.h>
-#include <binder/IInterface.h>
-
-#include <gui/IConsumerListener.h>
-#include "IGonkGraphicBufferConsumerKK.h"
-
-#include <ui/GraphicBuffer.h>
-#include <ui/Fence.h>
-
-#include <system/window.h>
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-IGonkGraphicBufferConsumer::BufferItem::BufferItem() :
- mTransform(0),
- mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
- mTimestamp(0),
- mIsAutoTimestamp(false),
- mFrameNumber(0),
- mBuf(INVALID_BUFFER_SLOT),
- mIsDroppable(false),
- mAcquireCalled(false),
- mTransformToDisplayInverse(false) {
- mCrop.makeInvalid();
-}
-
-size_t IGonkGraphicBufferConsumer::BufferItem::getPodSize() const {
- size_t c = sizeof(mCrop) +
- sizeof(mTransform) +
- sizeof(mScalingMode) +
- sizeof(mTimestamp) +
- sizeof(mIsAutoTimestamp) +
- sizeof(mFrameNumber) +
- sizeof(mBuf) +
- sizeof(mIsDroppable) +
- sizeof(mAcquireCalled) +
- sizeof(mTransformToDisplayInverse);
- return c;
-}
-
-size_t IGonkGraphicBufferConsumer::BufferItem::getFlattenedSize() const {
- size_t c = 0;
- if (mGraphicBuffer != 0) {
- c += mGraphicBuffer->getFlattenedSize();
- FlattenableUtils::align<4>(c);
- }
- if (mFence != 0) {
- c += mFence->getFlattenedSize();
- FlattenableUtils::align<4>(c);
- }
- return sizeof(int32_t) + c + getPodSize();
-}
-
-size_t IGonkGraphicBufferConsumer::BufferItem::getFdCount() const {
- size_t c = 0;
- if (mGraphicBuffer != 0) {
- c += mGraphicBuffer->getFdCount();
- }
- if (mFence != 0) {
- c += mFence->getFdCount();
- }
- return c;
-}
-
-status_t IGonkGraphicBufferConsumer::BufferItem::flatten(
- void*& buffer, size_t& size, int*& fds, size_t& count) const {
-
- // make sure we have enough space
- if (count < BufferItem::getFlattenedSize()) {
- return NO_MEMORY;
- }
-
- // content flags are stored first
- uint32_t& flags = *static_cast<uint32_t*>(buffer);
-
- // advance the pointer
- FlattenableUtils::advance(buffer, size, sizeof(uint32_t));
-
- flags = 0;
- if (mGraphicBuffer != 0) {
- status_t err = mGraphicBuffer->flatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- flags |= 1;
- }
- if (mFence != 0) {
- status_t err = mFence->flatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- flags |= 2;
- }
-
- // check we have enough space (in case flattening the fence/graphicbuffer lied to us)
- if (size < getPodSize()) {
- return NO_MEMORY;
- }
-
- FlattenableUtils::write(buffer, size, mCrop);
- FlattenableUtils::write(buffer, size, mTransform);
- FlattenableUtils::write(buffer, size, mScalingMode);
- FlattenableUtils::write(buffer, size, mTimestamp);
- FlattenableUtils::write(buffer, size, mIsAutoTimestamp);
- FlattenableUtils::write(buffer, size, mFrameNumber);
- FlattenableUtils::write(buffer, size, mBuf);
- FlattenableUtils::write(buffer, size, mIsDroppable);
- FlattenableUtils::write(buffer, size, mAcquireCalled);
- FlattenableUtils::write(buffer, size, mTransformToDisplayInverse);
-
- return NO_ERROR;
-}
-
-status_t IGonkGraphicBufferConsumer::BufferItem::unflatten(
- void const*& buffer, size_t& size, int const*& fds, size_t& count) {
-
- if (size < sizeof(uint32_t))
- return NO_MEMORY;
-
- uint32_t flags = 0;
- FlattenableUtils::read(buffer, size, flags);
-
- if (flags & 1) {
- mGraphicBuffer = new GraphicBuffer();
- status_t err = mGraphicBuffer->unflatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- }
-
- if (flags & 2) {
- mFence = new Fence();
- status_t err = mFence->unflatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- }
-
- // check we have enough space
- if (size < getPodSize()) {
- return NO_MEMORY;
- }
-
- FlattenableUtils::read(buffer, size, mCrop);
- FlattenableUtils::read(buffer, size, mTransform);
- FlattenableUtils::read(buffer, size, mScalingMode);
- FlattenableUtils::read(buffer, size, mTimestamp);
- FlattenableUtils::read(buffer, size, mIsAutoTimestamp);
- FlattenableUtils::read(buffer, size, mFrameNumber);
- FlattenableUtils::read(buffer, size, mBuf);
- FlattenableUtils::read(buffer, size, mIsDroppable);
- FlattenableUtils::read(buffer, size, mAcquireCalled);
- FlattenableUtils::read(buffer, size, mTransformToDisplayInverse);
-
- return NO_ERROR;
-}
-
-// ---------------------------------------------------------------------------
-
-enum {
- ACQUIRE_BUFFER = IBinder::FIRST_CALL_TRANSACTION,
- RELEASE_BUFFER,
- CONSUMER_CONNECT,
- CONSUMER_DISCONNECT,
- GET_RELEASED_BUFFERS,
- SET_DEFAULT_BUFFER_SIZE,
- SET_DEFAULT_MAX_BUFFER_COUNT,
- DISABLE_ASYNC_BUFFER,
- SET_MAX_ACQUIRED_BUFFER_COUNT,
- SET_CONSUMER_NAME,
- SET_DEFAULT_BUFFER_FORMAT,
- SET_CONSUMER_USAGE_BITS,
- SET_TRANSFORM_HINT,
- DUMP,
-};
-
-class BpGonkGraphicBufferConsumer : public BpInterface<IGonkGraphicBufferConsumer>
-{
-public:
- BpGonkGraphicBufferConsumer(const sp<IBinder>& impl)
- : BpInterface<IGonkGraphicBufferConsumer>(impl)
- {
- }
-
- virtual status_t acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt64(presentWhen);
- status_t result = remote()->transact(ACQUIRE_BUFFER, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- result = reply.read(*buffer);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
- const sp<Fence>& releaseFence) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(buf);
- data.writeInt64(frameNumber);
- data.write(*releaseFence);
- status_t result = remote()->transact(RELEASE_BUFFER, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeStrongBinder(consumer->asBinder());
- data.writeInt32(controlledByApp);
- status_t result = remote()->transact(CONSUMER_CONNECT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t consumerDisconnect() {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- status_t result = remote()->transact(CONSUMER_DISCONNECT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t getReleasedBuffers(uint32_t* slotMask) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- status_t result = remote()->transact(GET_RELEASED_BUFFERS, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- *slotMask = reply.readInt32();
- return reply.readInt32();
- }
-
- virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(w);
- data.writeInt32(h);
- status_t result = remote()->transact(SET_DEFAULT_BUFFER_SIZE, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t setDefaultMaxBufferCount(int bufferCount) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(bufferCount);
- status_t result = remote()->transact(SET_DEFAULT_MAX_BUFFER_COUNT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t disableAsyncBuffer() {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- status_t result = remote()->transact(DISABLE_ASYNC_BUFFER, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(maxAcquiredBuffers);
- status_t result = remote()->transact(SET_MAX_ACQUIRED_BUFFER_COUNT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual void setConsumerName(const String8& name) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeString8(name);
- remote()->transact(SET_CONSUMER_NAME, data, &reply);
- }
-
- virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(defaultFormat);
- status_t result = remote()->transact(SET_DEFAULT_BUFFER_FORMAT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t setConsumerUsageBits(uint32_t usage) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(usage);
- status_t result = remote()->transact(SET_CONSUMER_USAGE_BITS, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t setTransformHint(uint32_t hint) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(hint);
- status_t result = remote()->transact(SET_TRANSFORM_HINT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual void dumpToString(String8& result, const char* prefix) const {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeString8(result);
- data.writeString8(String8(prefix ? prefix : ""));
- remote()->transact(DUMP, data, &reply);
- reply.readString8();
- }
-};
-
-IMPLEMENT_META_INTERFACE(GonkGraphicBufferConsumer, "android.gui.IGonkGraphicBufferConsumer");
-// ----------------------------------------------------------------------
-
-status_t BnGonkGraphicBufferConsumer::onTransact(
- uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
- switch(code) {
- case ACQUIRE_BUFFER: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- BufferItem item;
- int64_t presentWhen = data.readInt64();
- status_t result = acquireBuffer(&item, presentWhen);
- status_t err = reply->write(item);
- if (err) return err;
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case RELEASE_BUFFER: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- int buf = data.readInt32();
- uint64_t frameNumber = data.readInt64();
- sp<Fence> releaseFence = new Fence();
- status_t err = data.read(*releaseFence);
- if (err) return err;
- status_t result = releaseBuffer(buf, frameNumber, releaseFence);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
-
- case CONSUMER_CONNECT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() );
- bool controlledByApp = data.readInt32();
- status_t result = consumerConnect(consumer, controlledByApp);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
-
- case CONSUMER_DISCONNECT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- status_t result = consumerDisconnect();
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case GET_RELEASED_BUFFERS: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t slotMask;
- status_t result = getReleasedBuffers(&slotMask);
- reply->writeInt32(slotMask);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_DEFAULT_BUFFER_SIZE: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t w = data.readInt32();
- uint32_t h = data.readInt32();
- status_t result = setDefaultBufferSize(w, h);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_DEFAULT_MAX_BUFFER_COUNT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t bufferCount = data.readInt32();
- status_t result = setDefaultMaxBufferCount(bufferCount);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case DISABLE_ASYNC_BUFFER: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- status_t result = disableAsyncBuffer();
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_MAX_ACQUIRED_BUFFER_COUNT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t maxAcquiredBuffers = data.readInt32();
- status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_CONSUMER_NAME: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- setConsumerName( data.readString8() );
- return NO_ERROR;
- } break;
- case SET_DEFAULT_BUFFER_FORMAT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t defaultFormat = data.readInt32();
- status_t result = setDefaultBufferFormat(defaultFormat);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_CONSUMER_USAGE_BITS: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t usage = data.readInt32();
- status_t result = setConsumerUsageBits(usage);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_TRANSFORM_HINT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t hint = data.readInt32();
- status_t result = setTransformHint(hint);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
-
- case DUMP: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- String8 result = data.readString8();
- String8 prefix = data.readString8();
- static_cast<IGonkGraphicBufferConsumer*>(this)->dumpToString(result, prefix);
- reply->writeString8(result);
- return NO_ERROR;
- }
- }
- return BBinder::onTransact(code, data, reply, flags);
-}
-
-}; // namespace android
diff --git a/widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.h b/widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.h
deleted file mode 100644
index ce51e1ef2..000000000
--- a/widget/gonk/nativewindow/IGonkGraphicBufferConsumerKK.h
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_IGONKGRAPHICBUFFERCONSUMER_KK_H
-#define NATIVEWINDOW_IGONKGRAPHICBUFFERCONSUMER_KK_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-#include <utils/RefBase.h>
-#include <utils/Timers.h>
-
-#include <binder/IInterface.h>
-#include <ui/Rect.h>
-
-#include "mozilla/Types.h"
-#include "mozilla/layers/LayersSurfaces.h"
-
-namespace mozilla {
-
-namespace layers {
-class TextureClient;
-}
-}
-
-namespace android {
-// ----------------------------------------------------------------------------
-
-class MOZ_EXPORT IConsumerListener;
-class MOZ_EXPORT GraphicBuffer;
-class MOZ_EXPORT Fence;
-
-class IGonkGraphicBufferConsumer : public IInterface {
- typedef mozilla::layers::TextureClient TextureClient;
-public:
-
- // public facing structure for BufferSlot
- class BufferItem : public Flattenable<BufferItem> {
- friend class Flattenable<BufferItem>;
- size_t getPodSize() const;
- size_t getFlattenedSize() const;
- size_t getFdCount() const;
- status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
- status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
-
- public:
- enum { INVALID_BUFFER_SLOT = -1 };
- BufferItem();
-
- // mGraphicBuffer points to the buffer allocated for this slot, or is NULL
- // if the buffer in this slot has been acquired in the past (see
- // BufferSlot.mAcquireCalled).
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mFence is a fence that will signal when the buffer is idle.
- sp<Fence> mFence;
-
- // mCrop is the current crop rectangle for this buffer slot.
- Rect mCrop;
-
- // mTransform is the current transform flags for this buffer slot.
- uint32_t mTransform;
-
- // mScalingMode is the current scaling mode for this buffer slot.
- uint32_t mScalingMode;
-
- // mTimestamp is the current timestamp for this buffer slot. This gets
- // to set by queueBuffer each time this slot is queued.
- int64_t mTimestamp;
-
- // mIsAutoTimestamp indicates whether mTimestamp was generated
- // automatically when the buffer was queued.
- bool mIsAutoTimestamp;
-
- // mFrameNumber is the number of the queued frame for this slot.
- uint64_t mFrameNumber;
-
- // mBuf is the slot index of this buffer
- int mBuf;
-
- // mIsDroppable whether this buffer was queued with the
- // property that it can be replaced by a new buffer for the purpose of
- // making sure dequeueBuffer() won't block.
- // i.e.: was the BufferQueue in "mDequeueBufferCannotBlock" when this buffer
- // was queued.
- bool mIsDroppable;
-
- // Indicates whether this buffer has been seen by a consumer yet
- bool mAcquireCalled;
-
- // Indicates this buffer must be transformed by the inverse transform of the screen
- // it is displayed onto. This is applied after mTransform.
- bool mTransformToDisplayInverse;
- };
-
-
- // acquireBuffer attempts to acquire ownership of the next pending buffer in
- // the BufferQueue. If no buffer is pending then it returns -EINVAL. If a
- // buffer is successfully acquired, the information about the buffer is
- // returned in BufferItem. If the buffer returned had previously been
- // acquired then the BufferItem::mGraphicBuffer field of buffer is set to
- // NULL and it is assumed that the consumer still holds a reference to the
- // buffer.
- //
- // If presentWhen is nonzero, it indicates the time when the buffer will
- // be displayed on screen. If the buffer's timestamp is farther in the
- // future, the buffer won't be acquired, and PRESENT_LATER will be
- // returned. The presentation time is in nanoseconds, and the time base
- // is CLOCK_MONOTONIC.
- virtual status_t acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) = 0;
-
- // releaseBuffer releases a buffer slot from the consumer back to the
- // BufferQueue. This may be done while the buffer's contents are still
- // being accessed. The fence will signal when the buffer is no longer
- // in use. frameNumber is used to indentify the exact buffer returned.
- //
- // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
- // any references to the just-released buffer that it might have, as if it
- // had received a onBuffersReleased() call with a mask set for the released
- // buffer.
- //
- // Note that the dependencies on EGL will be removed once we switch to using
- // the Android HW Sync HAL.
- virtual status_t releaseBuffer(int buf, uint64_t frameNumber, const sp<Fence>& releaseFence) = 0;
-
- // consumerConnect connects a consumer to the BufferQueue. Only one
- // consumer may be connected, and when that consumer disconnects the
- // BufferQueue is placed into the "abandoned" state, causing most
- // interactions with the BufferQueue by the producer to fail.
- // controlledByApp indicates whether the consumer is controlled by
- // the application.
- //
- // consumer may not be NULL.
- virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp) = 0;
-
- // consumerDisconnect disconnects a consumer from the BufferQueue. All
- // buffers will be freed and the BufferQueue is placed in the "abandoned"
- // state, causing most interactions with the BufferQueue by the producer to
- // fail.
- virtual status_t consumerDisconnect() = 0;
-
- // getReleasedBuffers sets the value pointed to by slotMask to a bit mask
- // indicating which buffer slots have been released by the BufferQueue
- // but have not yet been released by the consumer.
- //
- // This should be called from the onBuffersReleased() callback.
- virtual status_t getReleasedBuffers(uint32_t* slotMask) = 0;
-
- // setDefaultBufferSize is used to set the size of buffers returned by
- // dequeueBuffer when a width and height of zero is requested. Default
- // is 1x1.
- virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h) = 0;
-
- // setDefaultMaxBufferCount sets the default value for the maximum buffer
- // count (the initial default is 2). If the producer has requested a
- // buffer count using setBufferCount, the default buffer count will only
- // take effect if the producer sets the count back to zero.
- //
- // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
- virtual status_t setDefaultMaxBufferCount(int bufferCount) = 0;
-
- // disableAsyncBuffer disables the extra buffer used in async mode
- // (when both producer and consumer have set their "isControlledByApp"
- // flag) and has dequeueBuffer() return WOULD_BLOCK instead.
- //
- // This can only be called before consumerConnect().
- virtual status_t disableAsyncBuffer() = 0;
-
- // setMaxAcquiredBufferCount sets the maximum number of buffers that can
- // be acquired by the consumer at one time (default 1). This call will
- // fail if a producer is connected to the BufferQueue.
- virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers) = 0;
-
- // setConsumerName sets the name used in logging
- virtual void setConsumerName(const String8& name) = 0;
-
- // setDefaultBufferFormat allows the BufferQueue to create
- // GraphicBuffers of a defaultFormat if no format is specified
- // in dequeueBuffer. Formats are enumerated in graphics.h; the
- // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
- virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) = 0;
-
- // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
- // These are merged with the bits passed to dequeueBuffer. The values are
- // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
- virtual status_t setConsumerUsageBits(uint32_t usage) = 0;
-
- // setTransformHint bakes in rotation to buffers so overlays can be used.
- // The values are enumerated in window.h, e.g.
- // NATIVE_WINDOW_TRANSFORM_ROT_90. The default is 0 (no transform).
- virtual status_t setTransformHint(uint32_t hint) = 0;
-
- // dump state into a string
- virtual void dumpToString(String8& result, const char* prefix) const = 0;
-
-public:
- DECLARE_META_INTERFACE(GonkGraphicBufferConsumer);
-};
-
-// ----------------------------------------------------------------------------
-
-class BnGonkGraphicBufferConsumer : public BnInterface<IGonkGraphicBufferConsumer>
-{
-public:
- virtual status_t onTransact( uint32_t code,
- const Parcel& data,
- Parcel* reply,
- uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_GUI_IGRAPHICBUFFERCONSUMER_H
diff --git a/widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.cpp b/widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.cpp
deleted file mode 100644
index 729ed6736..000000000
--- a/widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.cpp
+++ /dev/null
@@ -1,565 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-#include <utils/NativeHandle.h>
-
-#include <binder/Parcel.h>
-#include <binder/IInterface.h>
-
-#include <gui/IConsumerListener.h>
-#include "IGonkGraphicBufferConsumerLL.h"
-
-#include <ui/GraphicBuffer.h>
-#include <ui/Fence.h>
-
-#include <system/window.h>
-
-#include "mozilla/layers/TextureClient.h"
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-IGonkGraphicBufferConsumer::BufferItem::BufferItem() :
- mTransform(0),
- mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
- mTimestamp(0),
- mIsAutoTimestamp(false),
- mFrameNumber(0),
- mBuf(INVALID_BUFFER_SLOT),
- mIsDroppable(false),
- mAcquireCalled(false),
- mTransformToDisplayInverse(false) {
- mCrop.makeInvalid();
-}
-
-size_t IGonkGraphicBufferConsumer::BufferItem::getPodSize() const {
- size_t c = sizeof(mCrop) +
- sizeof(mTransform) +
- sizeof(mScalingMode) +
- sizeof(mTimestamp) +
- sizeof(mIsAutoTimestamp) +
- sizeof(mFrameNumber) +
- sizeof(mBuf) +
- sizeof(mIsDroppable) +
- sizeof(mAcquireCalled) +
- sizeof(mTransformToDisplayInverse);
- return c;
-}
-
-size_t IGonkGraphicBufferConsumer::BufferItem::getFlattenedSize() const {
- size_t c = 0;
- if (mGraphicBuffer != 0) {
- c += mGraphicBuffer->getFlattenedSize();
- c = FlattenableUtils::align<4>(c);
- }
- if (mFence != 0) {
- c += mFence->getFlattenedSize();
- c = FlattenableUtils::align<4>(c);
- }
- return sizeof(int32_t) + c + getPodSize();
-}
-
-size_t IGonkGraphicBufferConsumer::BufferItem::getFdCount() const {
- size_t c = 0;
- if (mGraphicBuffer != 0) {
- c += mGraphicBuffer->getFdCount();
- }
- if (mFence != 0) {
- c += mFence->getFdCount();
- }
- return c;
-}
-
-static void writeBoolAsInt(void*& buffer, size_t& size, bool b) {
- FlattenableUtils::write(buffer, size, static_cast<int32_t>(b));
-}
-
-static bool readBoolFromInt(void const*& buffer, size_t& size) {
- int32_t i;
- FlattenableUtils::read(buffer, size, i);
- return static_cast<bool>(i);
-}
-
-status_t IGonkGraphicBufferConsumer::BufferItem::flatten(
- void*& buffer, size_t& size, int*& fds, size_t& count) const {
-
- // make sure we have enough space
- if (size < BufferItem::getFlattenedSize()) {
- return NO_MEMORY;
- }
-
- // content flags are stored first
- uint32_t& flags = *static_cast<uint32_t*>(buffer);
-
- // advance the pointer
- FlattenableUtils::advance(buffer, size, sizeof(uint32_t));
-
- flags = 0;
- if (mGraphicBuffer != 0) {
- status_t err = mGraphicBuffer->flatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- flags |= 1;
- }
- if (mFence != 0) {
- status_t err = mFence->flatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- flags |= 2;
- }
-
- // check we have enough space (in case flattening the fence/graphicbuffer lied to us)
- if (size < getPodSize()) {
- return NO_MEMORY;
- }
-
- FlattenableUtils::write(buffer, size, mCrop);
- FlattenableUtils::write(buffer, size, mTransform);
- FlattenableUtils::write(buffer, size, mScalingMode);
- FlattenableUtils::write(buffer, size, mTimestamp);
- writeBoolAsInt(buffer, size, mIsAutoTimestamp);
- FlattenableUtils::write(buffer, size, mFrameNumber);
- FlattenableUtils::write(buffer, size, mBuf);
- writeBoolAsInt(buffer, size, mIsDroppable);
- writeBoolAsInt(buffer, size, mAcquireCalled);
- writeBoolAsInt(buffer, size, mTransformToDisplayInverse);
-
- return NO_ERROR;
-}
-
-status_t IGonkGraphicBufferConsumer::BufferItem::unflatten(
- void const*& buffer, size_t& size, int const*& fds, size_t& count) {
-
- if (size < sizeof(uint32_t))
- return NO_MEMORY;
-
- uint32_t flags = 0;
- FlattenableUtils::read(buffer, size, flags);
-
- if (flags & 1) {
- mGraphicBuffer = new GraphicBuffer();
- status_t err = mGraphicBuffer->unflatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- }
-
- if (flags & 2) {
- mFence = new Fence();
- status_t err = mFence->unflatten(buffer, size, fds, count);
- if (err) return err;
- size -= FlattenableUtils::align<4>(buffer);
- }
-
- // check we have enough space
- if (size < getPodSize()) {
- return NO_MEMORY;
- }
-
- FlattenableUtils::read(buffer, size, mCrop);
- FlattenableUtils::read(buffer, size, mTransform);
- FlattenableUtils::read(buffer, size, mScalingMode);
- FlattenableUtils::read(buffer, size, mTimestamp);
- mIsAutoTimestamp = readBoolFromInt(buffer, size);
- FlattenableUtils::read(buffer, size, mFrameNumber);
- FlattenableUtils::read(buffer, size, mBuf);
- mIsDroppable = readBoolFromInt(buffer, size);
- mAcquireCalled = readBoolFromInt(buffer, size);
- mTransformToDisplayInverse = readBoolFromInt(buffer, size);
-
- return NO_ERROR;
-}
-
-// ---------------------------------------------------------------------------
-
-enum {
- ACQUIRE_BUFFER = IBinder::FIRST_CALL_TRANSACTION,
- DETACH_BUFFER,
- ATTACH_BUFFER,
- RELEASE_BUFFER,
- CONSUMER_CONNECT,
- CONSUMER_DISCONNECT,
- GET_RELEASED_BUFFERS,
- SET_DEFAULT_BUFFER_SIZE,
- SET_DEFAULT_MAX_BUFFER_COUNT,
- DISABLE_ASYNC_BUFFER,
- SET_MAX_ACQUIRED_BUFFER_COUNT,
- SET_CONSUMER_NAME,
- SET_DEFAULT_BUFFER_FORMAT,
- SET_CONSUMER_USAGE_BITS,
- SET_TRANSFORM_HINT,
- GET_SIDEBAND_STREAM,
- DUMP,
-};
-
-
-class BpGonkGraphicBufferConsumer : public BpInterface<IGonkGraphicBufferConsumer>
-{
-public:
- BpGonkGraphicBufferConsumer(const sp<IBinder>& impl)
- : BpInterface<IGonkGraphicBufferConsumer>(impl)
- {
- }
-
- virtual status_t acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt64(presentWhen);
- status_t result = remote()->transact(ACQUIRE_BUFFER, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- result = reply.read(*buffer);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t detachBuffer(int slot) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(slot);
- status_t result = remote()->transact(DETACH_BUFFER, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- result = reply.readInt32();
- return result;
- }
-
- virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.write(*buffer.get());
- status_t result = remote()->transact(ATTACH_BUFFER, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- *slot = reply.readInt32();
- result = reply.readInt32();
- return result;
- }
-
- virtual status_t releaseBuffer(int buf, uint64_t frameNumber, const sp<Fence>& releaseFence) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(buf);
- data.writeInt64(frameNumber);
- data.write(*releaseFence);
- status_t result = remote()->transact(RELEASE_BUFFER, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeStrongBinder(consumer->asBinder());
- data.writeInt32(controlledByApp);
- status_t result = remote()->transact(CONSUMER_CONNECT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t consumerDisconnect() {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- status_t result = remote()->transact(CONSUMER_DISCONNECT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t getReleasedBuffers(uint64_t* slotMask) {
- Parcel data, reply;
- if (slotMask == NULL) {
- ALOGE("getReleasedBuffers: slotMask must not be NULL");
- return BAD_VALUE;
- }
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- status_t result = remote()->transact(GET_RELEASED_BUFFERS, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- *slotMask = reply.readInt64();
- return reply.readInt32();
- }
-
- virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(w);
- data.writeInt32(h);
- status_t result = remote()->transact(SET_DEFAULT_BUFFER_SIZE, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t setDefaultMaxBufferCount(int bufferCount) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(bufferCount);
- status_t result = remote()->transact(SET_DEFAULT_MAX_BUFFER_COUNT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t disableAsyncBuffer() {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- status_t result = remote()->transact(DISABLE_ASYNC_BUFFER, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(maxAcquiredBuffers);
- status_t result = remote()->transact(SET_MAX_ACQUIRED_BUFFER_COUNT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual void setConsumerName(const String8& name) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeString8(name);
- remote()->transact(SET_CONSUMER_NAME, data, &reply);
- }
-
- virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(defaultFormat);
- status_t result = remote()->transact(SET_DEFAULT_BUFFER_FORMAT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t setConsumerUsageBits(uint32_t usage) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(usage);
- status_t result = remote()->transact(SET_CONSUMER_USAGE_BITS, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual status_t setTransformHint(uint32_t hint) {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeInt32(hint);
- status_t result = remote()->transact(SET_TRANSFORM_HINT, data, &reply);
- if (result != NO_ERROR) {
- return result;
- }
- return reply.readInt32();
- }
-
- virtual sp<NativeHandle> getSidebandStream() const {
- Parcel data, reply;
- status_t err;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- if ((err = remote()->transact(GET_SIDEBAND_STREAM, data, &reply)) != NO_ERROR) {
- return NULL;
- }
- sp<NativeHandle> stream;
- if (reply.readInt32()) {
- stream = NativeHandle::create(reply.readNativeHandle(), true);
- }
- return stream;
- }
-
- virtual void dumpToString(String8& result, const char* prefix) const {
- Parcel data, reply;
- data.writeInterfaceToken(IGonkGraphicBufferConsumer::getInterfaceDescriptor());
- data.writeString8(result);
- data.writeString8(String8(prefix ? prefix : ""));
- remote()->transact(DUMP, data, &reply);
- reply.readString8();
- }
-
- // Added by mozilla
- virtual already_AddRefed<mozilla::layers::TextureClient>
- getTextureClientFromBuffer(ANativeWindowBuffer* buffer)
- {
- return nullptr;
- }
-
- virtual int
- getSlotFromTextureClientLocked(mozilla::layers::TextureClient* client) const
- {
- return BAD_VALUE;
- }
-};
-
-IMPLEMENT_META_INTERFACE(GonkGraphicBufferConsumer, "android.gui.IGonkGraphicBufferConsumer");
-
-// ----------------------------------------------------------------------
-
-status_t BnGonkGraphicBufferConsumer::onTransact(
- uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
-{
- switch(code) {
- case ACQUIRE_BUFFER: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- BufferItem item;
- int64_t presentWhen = data.readInt64();
- status_t result = acquireBuffer(&item, presentWhen);
- status_t err = reply->write(item);
- if (err) return err;
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case DETACH_BUFFER: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- int slot = data.readInt32();
- int result = detachBuffer(slot);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case ATTACH_BUFFER: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- sp<GraphicBuffer> buffer = new GraphicBuffer();
- data.read(*buffer.get());
- int slot;
- int result = attachBuffer(&slot, buffer);
- reply->writeInt32(slot);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case RELEASE_BUFFER: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- int buf = data.readInt32();
- uint64_t frameNumber = data.readInt64();
- sp<Fence> releaseFence = new Fence();
- status_t err = data.read(*releaseFence);
- if (err) return err;
- status_t result = releaseBuffer(buf, frameNumber, releaseFence);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case CONSUMER_CONNECT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() );
- bool controlledByApp = data.readInt32();
- status_t result = consumerConnect(consumer, controlledByApp);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case CONSUMER_DISCONNECT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- status_t result = consumerDisconnect();
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case GET_RELEASED_BUFFERS: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint64_t slotMask;
- status_t result = getReleasedBuffers(&slotMask);
- reply->writeInt64(slotMask);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_DEFAULT_BUFFER_SIZE: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t w = data.readInt32();
- uint32_t h = data.readInt32();
- status_t result = setDefaultBufferSize(w, h);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_DEFAULT_MAX_BUFFER_COUNT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t bufferCount = data.readInt32();
- status_t result = setDefaultMaxBufferCount(bufferCount);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case DISABLE_ASYNC_BUFFER: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- status_t result = disableAsyncBuffer();
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_MAX_ACQUIRED_BUFFER_COUNT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t maxAcquiredBuffers = data.readInt32();
- status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_CONSUMER_NAME: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- setConsumerName( data.readString8() );
- return NO_ERROR;
- } break;
- case SET_DEFAULT_BUFFER_FORMAT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t defaultFormat = data.readInt32();
- status_t result = setDefaultBufferFormat(defaultFormat);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_CONSUMER_USAGE_BITS: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t usage = data.readInt32();
- status_t result = setConsumerUsageBits(usage);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case SET_TRANSFORM_HINT: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- uint32_t hint = data.readInt32();
- status_t result = setTransformHint(hint);
- reply->writeInt32(result);
- return NO_ERROR;
- } break;
- case DUMP: {
- CHECK_INTERFACE(IGonkGraphicBufferConsumer, data, reply);
- String8 result = data.readString8();
- String8 prefix = data.readString8();
- static_cast<IGonkGraphicBufferConsumer*>(this)->dumpToString(result, prefix);
- reply->writeString8(result);
- return NO_ERROR;
- }
- }
- return BBinder::onTransact(code, data, reply, flags);
-}
-
-}; // namespace android
diff --git a/widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.h b/widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.h
deleted file mode 100644
index 8a93a0849..000000000
--- a/widget/gonk/nativewindow/IGonkGraphicBufferConsumerLL.h
+++ /dev/null
@@ -1,337 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef NATIVEWINDOW_IGONKGRAPHICBUFFERCONSUMER_LL_H
-#define NATIVEWINDOW_IGONKGRAPHICBUFFERCONSUMER_LL_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Errors.h>
-#include <utils/RefBase.h>
-#include <utils/Timers.h>
-
-#include <binder/IInterface.h>
-#include <ui/Rect.h>
-
-#include "mozilla/RefPtr.h"
-
-class ANativeWindowBuffer;
-
-namespace mozilla {
-namespace layers {
-class TextureClient;
-}
-}
-
-namespace android {
-// ----------------------------------------------------------------------------
-
-class Fence;
-class GraphicBuffer;
-class IConsumerListener;
-class NativeHandle;
-
-class IGonkGraphicBufferConsumer : public IInterface {
-public:
-
- // public facing structure for BufferSlot
- class BufferItem : public Flattenable<BufferItem> {
- friend class Flattenable<BufferItem>;
- size_t getPodSize() const;
- size_t getFlattenedSize() const;
- size_t getFdCount() const;
- status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
- status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
-
- public:
- // The default value of mBuf, used to indicate this doesn't correspond to a slot.
- enum { INVALID_BUFFER_SLOT = -1 };
- BufferItem();
-
- // mGraphicBuffer points to the buffer allocated for this slot, or is NULL
- // if the buffer in this slot has been acquired in the past (see
- // BufferSlot.mAcquireCalled).
- sp<GraphicBuffer> mGraphicBuffer;
-
- // mFence is a fence that will signal when the buffer is idle.
- sp<Fence> mFence;
-
- // mCrop is the current crop rectangle for this buffer slot.
- Rect mCrop;
-
- // mTransform is the current transform flags for this buffer slot.
- // refer to NATIVE_WINDOW_TRANSFORM_* in <window.h>
- uint32_t mTransform;
-
- // mScalingMode is the current scaling mode for this buffer slot.
- // refer to NATIVE_WINDOW_SCALING_* in <window.h>
- uint32_t mScalingMode;
-
- // mTimestamp is the current timestamp for this buffer slot. This gets
- // to set by queueBuffer each time this slot is queued. This value
- // is guaranteed to be monotonically increasing for each newly
- // acquired buffer.
- int64_t mTimestamp;
-
- // mIsAutoTimestamp indicates whether mTimestamp was generated
- // automatically when the buffer was queued.
- bool mIsAutoTimestamp;
-
- // mFrameNumber is the number of the queued frame for this slot.
- uint64_t mFrameNumber;
-
- // mBuf is the slot index of this buffer (default INVALID_BUFFER_SLOT).
- int mBuf;
-
- // mIsDroppable whether this buffer was queued with the
- // property that it can be replaced by a new buffer for the purpose of
- // making sure dequeueBuffer() won't block.
- // i.e.: was the BufferQueue in "mDequeueBufferCannotBlock" when this buffer
- // was queued.
- bool mIsDroppable;
-
- // Indicates whether this buffer has been seen by a consumer yet
- bool mAcquireCalled;
-
- // Indicates this buffer must be transformed by the inverse transform of the screen
- // it is displayed onto. This is applied after mTransform.
- bool mTransformToDisplayInverse;
- };
-
- enum {
- // Returned by releaseBuffer, after which the consumer must
- // free any references to the just-released buffer that it might have.
- STALE_BUFFER_SLOT = 1,
- // Returned by dequeueBuffer if there are no pending buffers available.
- NO_BUFFER_AVAILABLE,
- // Returned by dequeueBuffer if it's too early for the buffer to be acquired.
- PRESENT_LATER,
- };
-
- // acquireBuffer attempts to acquire ownership of the next pending buffer in
- // the BufferQueue. If no buffer is pending then it returns
- // NO_BUFFER_AVAILABLE. If a buffer is successfully acquired, the
- // information about the buffer is returned in BufferItem.
- //
- // If the buffer returned had previously been
- // acquired then the BufferItem::mGraphicBuffer field of buffer is set to
- // NULL and it is assumed that the consumer still holds a reference to the
- // buffer.
- //
- // If presentWhen is non-zero, it indicates the time when the buffer will
- // be displayed on screen. If the buffer's timestamp is farther in the
- // future, the buffer won't be acquired, and PRESENT_LATER will be
- // returned. The presentation time is in nanoseconds, and the time base
- // is CLOCK_MONOTONIC.
- //
- // Return of NO_ERROR means the operation completed as normal.
- //
- // Return of a positive value means the operation could not be completed
- // at this time, but the user should try again later:
- // * NO_BUFFER_AVAILABLE - no buffer is pending (nothing queued by producer)
- // * PRESENT_LATER - the buffer's timestamp is farther in the future
- //
- // Return of a negative value means an error has occurred:
- // * INVALID_OPERATION - too many buffers have been acquired
- virtual status_t acquireBuffer(BufferItem* buffer, nsecs_t presentWhen) = 0;
-
- // detachBuffer attempts to remove all ownership of the buffer in the given
- // slot from the buffer queue. If this call succeeds, the slot will be
- // freed, and there will be no way to obtain the buffer from this interface.
- // The freed slot will remain unallocated until either it is selected to
- // hold a freshly allocated buffer in dequeueBuffer or a buffer is attached
- // to the slot. The buffer must have already been acquired.
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * BAD_VALUE - the given slot number is invalid, either because it is
- // out of the range [0, NUM_BUFFER_SLOTS) or because the slot
- // it refers to is not currently acquired.
- virtual status_t detachBuffer(int slot) = 0;
-
- // attachBuffer attempts to transfer ownership of a buffer to the buffer
- // queue. If this call succeeds, it will be as if this buffer was acquired
- // from the returned slot number. As such, this call will fail if attaching
- // this buffer would cause too many buffers to be simultaneously acquired.
- //
- // If the buffer is successfully attached, its frameNumber is initialized
- // to 0. This must be passed into the releaseBuffer call or else the buffer
- // will be deallocated as stale.
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * BAD_VALUE - outSlot or buffer were NULL
- // * INVALID_OPERATION - cannot attach the buffer because it would cause too
- // many buffers to be acquired.
- // * NO_MEMORY - no free slots available
- virtual status_t attachBuffer(int *outSlot,
- const sp<GraphicBuffer>& buffer) = 0;
-
- // releaseBuffer releases a buffer slot from the consumer back to the
- // BufferQueue. This may be done while the buffer's contents are still
- // being accessed. The fence will signal when the buffer is no longer
- // in use. frameNumber is used to indentify the exact buffer returned.
- //
- // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
- // any references to the just-released buffer that it might have, as if it
- // had received a onBuffersReleased() call with a mask set for the released
- // buffer.
- //
- // Note that the dependencies on EGL will be removed once we switch to using
- // the Android HW Sync HAL.
- //
- // Return of NO_ERROR means the operation completed as normal.
- //
- // Return of a positive value means the operation could not be completed
- // at this time, but the user should try again later:
- // * STALE_BUFFER_SLOT - see above (second paragraph)
- //
- // Return of a negative value means an error has occurred:
- // * BAD_VALUE - one of the following could've happened:
- // * the buffer slot was invalid
- // * the fence was NULL
- // * the buffer slot specified is not in the acquired state
- virtual status_t releaseBuffer(int buf, uint64_t frameNumber, const sp<Fence>& releaseFence) = 0;
-
- // consumerConnect connects a consumer to the BufferQueue. Only one
- // consumer may be connected, and when that consumer disconnects the
- // BufferQueue is placed into the "abandoned" state, causing most
- // interactions with the BufferQueue by the producer to fail.
- // controlledByApp indicates whether the consumer is controlled by
- // the application.
- //
- // consumer may not be NULL.
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * NO_INIT - the buffer queue has been abandoned
- // * BAD_VALUE - a NULL consumer was provided
- virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp) = 0;
-
- // consumerDisconnect disconnects a consumer from the BufferQueue. All
- // buffers will be freed and the BufferQueue is placed in the "abandoned"
- // state, causing most interactions with the BufferQueue by the producer to
- // fail.
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * BAD_VALUE - no consumer is currently connected
- virtual status_t consumerDisconnect() = 0;
-
- // getReleasedBuffers sets the value pointed to by slotMask to a bit set.
- // Each bit index with a 1 corresponds to a released buffer slot with that
- // index value. In particular, a released buffer is one that has
- // been released by the BufferQueue but have not yet been released by the consumer.
- //
- // This should be called from the onBuffersReleased() callback.
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * NO_INIT - the buffer queue has been abandoned.
- virtual status_t getReleasedBuffers(uint64_t* slotMask) = 0;
-
- // setDefaultBufferSize is used to set the size of buffers returned by
- // dequeueBuffer when a width and height of zero is requested. Default
- // is 1x1.
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * BAD_VALUE - either w or h was zero
- virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h) = 0;
-
- // setDefaultMaxBufferCount sets the default value for the maximum buffer
- // count (the initial default is 2). If the producer has requested a
- // buffer count using setBufferCount, the default buffer count will only
- // take effect if the producer sets the count back to zero.
- //
- // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * BAD_VALUE - bufferCount was out of range (see above).
- virtual status_t setDefaultMaxBufferCount(int bufferCount) = 0;
-
- // disableAsyncBuffer disables the extra buffer used in async mode
- // (when both producer and consumer have set their "isControlledByApp"
- // flag) and has dequeueBuffer() return WOULD_BLOCK instead.
- //
- // This can only be called before consumerConnect().
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * INVALID_OPERATION - attempting to call this after consumerConnect.
- virtual status_t disableAsyncBuffer() = 0;
-
- // setMaxAcquiredBufferCount sets the maximum number of buffers that can
- // be acquired by the consumer at one time (default 1). This call will
- // fail if a producer is connected to the BufferQueue.
- //
- // maxAcquiredBuffers must be (inclusive) between 1 and MAX_MAX_ACQUIRED_BUFFERS.
- //
- // Return of a value other than NO_ERROR means an error has occurred:
- // * BAD_VALUE - maxAcquiredBuffers was out of range (see above).
- // * INVALID_OPERATION - attempting to call this after a producer connected.
- virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers) = 0;
-
- // setConsumerName sets the name used in logging
- virtual void setConsumerName(const String8& name) = 0;
-
- // setDefaultBufferFormat allows the BufferQueue to create
- // GraphicBuffers of a defaultFormat if no format is specified
- // in dequeueBuffer. Formats are enumerated in graphics.h; the
- // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
- //
- // Return of a value other than NO_ERROR means an unknown error has occurred.
- virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) = 0;
-
- // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
- // These are merged with the bits passed to dequeueBuffer. The values are
- // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
- //
- // Return of a value other than NO_ERROR means an unknown error has occurred.
- virtual status_t setConsumerUsageBits(uint32_t usage) = 0;
-
- // setTransformHint bakes in rotation to buffers so overlays can be used.
- // The values are enumerated in window.h, e.g.
- // NATIVE_WINDOW_TRANSFORM_ROT_90. The default is 0 (no transform).
- //
- // Return of a value other than NO_ERROR means an unknown error has occurred.
- virtual status_t setTransformHint(uint32_t hint) = 0;
-
- // Retrieve the sideband buffer stream, if any.
- virtual sp<NativeHandle> getSidebandStream() const = 0;
-
- // dump state into a string
- virtual void dumpToString(String8& result, const char* prefix) const = 0;
-
- // Added by mozilla
- virtual already_AddRefed<mozilla::layers::TextureClient>
- getTextureClientFromBuffer(ANativeWindowBuffer* buffer) = 0;
-
- virtual int getSlotFromTextureClientLocked(mozilla::layers::TextureClient* client) const = 0;
-
-public:
- DECLARE_META_INTERFACE(GonkGraphicBufferConsumer);
-};
-
-// ----------------------------------------------------------------------------
-
-class BnGonkGraphicBufferConsumer : public BnInterface<IGonkGraphicBufferConsumer>
-{
-public:
- virtual status_t onTransact( uint32_t code,
- const Parcel& data,
- Parcel* reply,
- uint32_t flags = 0);
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_GUI_IGONKGRAPHICBUFFERCONSUMER_H
diff --git a/widget/gonk/nativewindow/moz.build b/widget/gonk/nativewindow/moz.build
deleted file mode 100644
index fbcee601c..000000000
--- a/widget/gonk/nativewindow/moz.build
+++ /dev/null
@@ -1,104 +0,0 @@
-# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# Copyright 2013 Mozilla Foundation and Mozilla contributors
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-EXPORTS += [
- 'GonkBufferQueue.h',
- 'GonkNativeWindow.h',
-]
-
-if CONFIG['ANDROID_VERSION'] >= '19':
- EXPORTS += [
- 'IGonkGraphicBufferConsumer.h',
- ]
-
-if CONFIG['ANDROID_VERSION'] >= '21':
- EXPORTS += [
- 'GonkBufferQueueLL/GonkBufferQueueDefs.h',
- 'GonkBufferQueueLL/GonkBufferQueueLL.h',
- 'GonkBufferQueueLL/GonkBufferQueueProducer.h',
- 'GonkBufferQueueLL/GonkBufferSlot.h',
- 'GonkConsumerBaseLL.h',
- 'GonkNativeWindowLL.h',
- 'IGonkGraphicBufferConsumerLL.h',
- ]
-elif CONFIG['ANDROID_VERSION'] >= '19':
- EXPORTS += [
- 'GonkBufferQueueKK.h',
- 'GonkConsumerBaseKK.h',
- 'GonkNativeWindowKK.h',
- 'IGonkGraphicBufferConsumerKK.h',
- ]
-elif CONFIG['ANDROID_VERSION'] in ('17', '18'):
- EXPORTS += [
- 'GonkBufferQueueJB.h',
- 'GonkConsumerBaseJB.h',
- 'GonkNativeWindowJB.h',
- ]
-
-if CONFIG['MOZ_WEBRTC']:
- if CONFIG['ANDROID_VERSION'] >= '21':
- SOURCES += [
- 'GonkBufferQueueLL/GonkBufferItem.cpp',
- 'GonkBufferQueueLL/GonkBufferQueueConsumer.cpp',
- 'GonkBufferQueueLL/GonkBufferQueueCore.cpp',
- 'GonkBufferQueueLL/GonkBufferQueueLL.cpp',
- 'GonkBufferQueueLL/GonkBufferQueueProducer.cpp',
- 'GonkBufferQueueLL/GonkBufferSlot.cpp',
- 'GonkConsumerBaseLL.cpp',
- 'GonkNativeWindowLL.cpp',
- 'IGonkGraphicBufferConsumerLL.cpp',
- ]
- elif CONFIG['ANDROID_VERSION'] >= '19':
- SOURCES += [
- 'GonkBufferQueueKK.cpp',
- 'GonkConsumerBaseKK.cpp',
- 'GonkNativeWindowKK.cpp',
- 'IGonkGraphicBufferConsumerKK.cpp',
- ]
- elif CONFIG['ANDROID_VERSION'] in ('17', '18'):
- SOURCES += [
- 'GonkBufferQueueJB.cpp',
- 'GonkConsumerBaseJB.cpp',
- 'GonkNativeWindowJB.cpp',
- ]
-
-if CONFIG['ANDROID_VERSION'] >= '18':
- SOURCES += [
- 'FakeSurfaceComposer.cpp',
- ]
-
-include('/ipc/chromium/chromium-config.mozbuild')
-
-if CONFIG['ANDROID_VERSION'] >= '18':
- LOCAL_INCLUDES += [
- '%' + '%s/%s' % (CONFIG['ANDROID_SOURCE'], d) for d in [
- 'frameworks/native/opengl/include',
- ]
- ]
-
-DEFINES['HAVE_ANDROID_OS'] = True
-
-# Suppress some GCC warnings being treated as errors:
-# - about attributes on forward declarations for types that are already
-# defined, which complains about an important MOZ_EXPORT for android::AString
-if CONFIG['GNU_CC']:
- CXXFLAGS += ['-Wno-error=attributes', '-Wno-overloaded-virtual']
-
-FINAL_LIBRARY = 'xul'
-
-DISABLE_STL_WRAPPING = True
-
-NO_VISIBILITY_FLAGS = True
diff --git a/widget/gonk/nsAppShell.cpp b/widget/gonk/nsAppShell.cpp
deleted file mode 100644
index 24e791b4b..000000000
--- a/widget/gonk/nsAppShell.cpp
+++ /dev/null
@@ -1,1087 +0,0 @@
-/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 sw=4 sts=4 tw=80 et: */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _GNU_SOURCE
-#define _GNU_SOURCE
-#endif
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <hardware_legacy/power.h>
-#include <signal.h>
-#include <sys/epoll.h>
-#include <sys/ioctl.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <utils/BitSet.h>
-
-#include "base/basictypes.h"
-#include "GonkPermission.h"
-#include "libdisplay/BootAnimation.h"
-#include "nscore.h"
-#include "mozilla/TouchEvents.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/Hal.h"
-#include "mozilla/MouseEvents.h"
-#include "mozilla/Mutex.h"
-#include "mozilla/Services.h"
-#include "mozilla/TextEvents.h"
-#if ANDROID_VERSION >= 18
-#include "nativewindow/FakeSurfaceComposer.h"
-#endif
-#include "nsAppShell.h"
-#include "mozilla/DebugOnly.h"
-#include "mozilla/dom/Touch.h"
-#include "nsGkAtoms.h"
-#include "nsIObserverService.h"
-#include "nsIScreen.h"
-#include "nsScreenManagerGonk.h"
-#include "nsThreadUtils.h"
-#include "nsWindow.h"
-#include "OrientationObserver.h"
-#include "GonkMemoryPressureMonitoring.h"
-
-#include "android/log.h"
-#include "libui/EventHub.h"
-#include "libui/InputReader.h"
-#include "libui/InputDispatcher.h"
-
-#include "mozilla/Preferences.h"
-#include "GeckoProfiler.h"
-
-// Defines kKeyMapping and GetKeyNameIndex()
-#include "GonkKeyMapping.h"
-#include "mozilla/layers/CompositorBridgeParent.h"
-#include "GeckoTouchDispatcher.h"
-
-#undef LOG
-#define LOG(args...) \
- __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
-#ifdef VERBOSE_LOG_ENABLED
-# define VERBOSE_LOG(args...) \
- __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
-#else
-# define VERBOSE_LOG(args...) \
- (void)0
-#endif
-
-using namespace android;
-using namespace mozilla;
-using namespace mozilla::dom;
-using namespace mozilla::services;
-using namespace mozilla::widget;
-
-bool gDrawRequest = false;
-static nsAppShell *gAppShell = nullptr;
-static int epollfd = 0;
-static int signalfds[2] = {0};
-static bool sDevInputAudioJack;
-static int32_t sHeadphoneState;
-static int32_t sMicrophoneState;
-
-// Amount of time in MS before an input is considered expired.
-static const uint64_t kInputExpirationThresholdMs = 1000;
-static const char kKey_WAKE_LOCK_ID[] = "GeckoKeyEvent";
-
-NS_IMPL_ISUPPORTS_INHERITED(nsAppShell, nsBaseAppShell, nsIObserver)
-
-static uint64_t
-nanosecsToMillisecs(nsecs_t nsecs)
-{
- return nsecs / 1000000;
-}
-
-namespace mozilla {
-
-bool ProcessNextEvent()
-{
- return gAppShell->ProcessNextNativeEvent(true);
-}
-
-void NotifyEvent()
-{
- gAppShell->NotifyNativeEvent();
-}
-
-} // namespace mozilla
-
-static void
-pipeHandler(int fd, FdHandler *data)
-{
- ssize_t len;
- do {
- char tmp[32];
- len = read(fd, tmp, sizeof(tmp));
- } while (len > 0);
-}
-
-struct Touch {
- int32_t id;
- PointerCoords coords;
-};
-
-struct UserInputData {
- uint64_t timeMs;
- enum {
- MOTION_DATA,
- KEY_DATA
- } type;
- int32_t action;
- int32_t flags;
- int32_t metaState;
- int32_t deviceId;
- union {
- struct {
- int32_t keyCode;
- int32_t scanCode;
- } key;
- struct {
- int32_t touchCount;
- ::Touch touches[MAX_POINTERS];
- } motion;
- };
-};
-
-static mozilla::Modifiers
-getDOMModifiers(int32_t metaState)
-{
- mozilla::Modifiers result = 0;
- if (metaState & (AMETA_ALT_ON | AMETA_ALT_LEFT_ON | AMETA_ALT_RIGHT_ON)) {
- result |= MODIFIER_ALT;
- }
- if (metaState & (AMETA_SHIFT_ON |
- AMETA_SHIFT_LEFT_ON | AMETA_SHIFT_RIGHT_ON)) {
- result |= MODIFIER_SHIFT;
- }
- if (metaState & AMETA_FUNCTION_ON) {
- result |= MODIFIER_FN;
- }
- if (metaState & (AMETA_CTRL_ON |
- AMETA_CTRL_LEFT_ON | AMETA_CTRL_RIGHT_ON)) {
- result |= MODIFIER_CONTROL;
- }
- if (metaState & (AMETA_META_ON |
- AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON)) {
- result |= MODIFIER_META;
- }
- if (metaState & AMETA_CAPS_LOCK_ON) {
- result |= MODIFIER_CAPSLOCK;
- }
- if (metaState & AMETA_NUM_LOCK_ON) {
- result |= MODIFIER_NUMLOCK;
- }
- if (metaState & AMETA_SCROLL_LOCK_ON) {
- result |= MODIFIER_SCROLLLOCK;
- }
- return result;
-}
-
-class MOZ_STACK_CLASS KeyEventDispatcher
-{
-public:
- KeyEventDispatcher(const UserInputData& aData,
- KeyCharacterMap* aKeyCharMap);
- void Dispatch();
-
-private:
- const UserInputData& mData;
- sp<KeyCharacterMap> mKeyCharMap;
-
- char16_t mChar;
- char16_t mUnmodifiedChar;
-
- uint32_t mDOMKeyCode;
- uint32_t mDOMKeyLocation;
- KeyNameIndex mDOMKeyNameIndex;
- CodeNameIndex mDOMCodeNameIndex;
- char16_t mDOMPrintableKeyValue;
-
- bool IsKeyPress() const
- {
- return mData.action == AKEY_EVENT_ACTION_DOWN;
- }
- bool IsRepeat() const
- {
- return IsKeyPress() && (mData.flags & AKEY_EVENT_FLAG_LONG_PRESS);
- }
-
- char16_t PrintableKeyValue() const;
-
- int32_t UnmodifiedMetaState() const
- {
- return mData.metaState &
- ~(AMETA_ALT_ON | AMETA_ALT_LEFT_ON | AMETA_ALT_RIGHT_ON |
- AMETA_CTRL_ON | AMETA_CTRL_LEFT_ON | AMETA_CTRL_RIGHT_ON |
- AMETA_META_ON | AMETA_META_LEFT_ON | AMETA_META_RIGHT_ON);
- }
-
- static bool IsControlChar(char16_t aChar)
- {
- return (aChar < ' ' || aChar == 0x7F);
- }
-
- void DispatchKeyDownEvent();
- void DispatchKeyUpEvent();
- nsEventStatus DispatchKeyEventInternal(EventMessage aEventMessage);
-};
-
-KeyEventDispatcher::KeyEventDispatcher(const UserInputData& aData,
- KeyCharacterMap* aKeyCharMap)
- : mData(aData)
- , mKeyCharMap(aKeyCharMap)
- , mChar(0)
- , mUnmodifiedChar(0)
- , mDOMPrintableKeyValue(0)
-{
- // XXX Printable key's keyCode value should be computed with actual
- // input character.
- mDOMKeyCode = (mData.key.keyCode < (ssize_t)ArrayLength(kKeyMapping)) ?
- kKeyMapping[mData.key.keyCode] : 0;
- mDOMKeyNameIndex = GetKeyNameIndex(mData.key.keyCode);
- mDOMCodeNameIndex = GetCodeNameIndex(mData.key.scanCode);
- mDOMKeyLocation =
- WidgetKeyboardEvent::ComputeLocationFromCodeValue(mDOMCodeNameIndex);
-
- if (!mKeyCharMap.get()) {
- return;
- }
-
- mChar = mKeyCharMap->getCharacter(mData.key.keyCode, mData.metaState);
- if (IsControlChar(mChar)) {
- mChar = 0;
- }
- int32_t unmodifiedMetaState = UnmodifiedMetaState();
- if (mData.metaState == unmodifiedMetaState) {
- mUnmodifiedChar = mChar;
- } else {
- mUnmodifiedChar = mKeyCharMap->getCharacter(mData.key.keyCode,
- unmodifiedMetaState);
- if (IsControlChar(mUnmodifiedChar)) {
- mUnmodifiedChar = 0;
- }
- }
-
- mDOMPrintableKeyValue = PrintableKeyValue();
-}
-
-char16_t
-KeyEventDispatcher::PrintableKeyValue() const
-{
- if (mDOMKeyNameIndex != KEY_NAME_INDEX_USE_STRING) {
- return 0;
- }
- return mChar ? mChar : mUnmodifiedChar;
-}
-
-nsEventStatus
-KeyEventDispatcher::DispatchKeyEventInternal(EventMessage aEventMessage)
-{
- WidgetKeyboardEvent event(true, aEventMessage, nullptr);
- if (aEventMessage == eKeyPress) {
- // XXX If the charCode is not a printable character, the charCode
- // should be computed without Ctrl/Alt/Meta modifiers.
- event.mCharCode = static_cast<uint32_t>(mChar);
- }
- if (!event.mCharCode) {
- event.mKeyCode = mDOMKeyCode;
- }
- event.mIsChar = !!event.mCharCode;
- event.mIsRepeat = IsRepeat();
- event.mKeyNameIndex = mDOMKeyNameIndex;
- if (mDOMPrintableKeyValue) {
- event.mKeyValue = mDOMPrintableKeyValue;
- }
- event.mCodeNameIndex = mDOMCodeNameIndex;
- event.mModifiers = getDOMModifiers(mData.metaState);
- event.mLocation = mDOMKeyLocation;
- event.mTime = mData.timeMs;
- return nsWindow::DispatchKeyInput(event);
-}
-
-void
-KeyEventDispatcher::Dispatch()
-{
- // XXX Even if unknown key is pressed, DOM key event should be
- // dispatched since Gecko for the other platforms are implemented
- // as so.
- if (!mDOMKeyCode && mDOMKeyNameIndex == KEY_NAME_INDEX_Unidentified) {
- VERBOSE_LOG("Got unknown key event code. "
- "type 0x%04x code 0x%04x value %d",
- mData.action, mData.key.keyCode, IsKeyPress());
- return;
- }
-
- if (IsKeyPress()) {
- DispatchKeyDownEvent();
- } else {
- DispatchKeyUpEvent();
- }
-}
-
-void
-KeyEventDispatcher::DispatchKeyDownEvent()
-{
- nsEventStatus status = DispatchKeyEventInternal(eKeyDown);
- if (status != nsEventStatus_eConsumeNoDefault) {
- DispatchKeyEventInternal(eKeyPress);
- }
-}
-
-void
-KeyEventDispatcher::DispatchKeyUpEvent()
-{
- DispatchKeyEventInternal(eKeyUp);
-}
-
-class SwitchEventRunnable : public mozilla::Runnable {
-public:
- SwitchEventRunnable(hal::SwitchEvent& aEvent) : mEvent(aEvent)
- {}
-
- NS_IMETHOD Run() override
- {
- hal::NotifySwitchStateFromInputDevice(mEvent.device(),
- mEvent.status());
- return NS_OK;
- }
-private:
- hal::SwitchEvent mEvent;
-};
-
-static void
-updateHeadphoneSwitch()
-{
- hal::SwitchEvent event;
-
- switch (sHeadphoneState) {
- case AKEY_STATE_UP:
- event.status() = hal::SWITCH_STATE_OFF;
- break;
- case AKEY_STATE_DOWN:
- event.status() = sMicrophoneState == AKEY_STATE_DOWN ?
- hal::SWITCH_STATE_HEADSET : hal::SWITCH_STATE_HEADPHONE;
- break;
- default:
- return;
- }
-
- event.device() = hal::SWITCH_HEADPHONES;
- NS_DispatchToMainThread(new SwitchEventRunnable(event));
-}
-
-class GeckoPointerController : public PointerControllerInterface {
- float mX;
- float mY;
- int32_t mButtonState;
- InputReaderConfiguration* mConfig;
-public:
- GeckoPointerController(InputReaderConfiguration* config)
- : mX(0)
- , mY(0)
- , mButtonState(0)
- , mConfig(config)
- {}
-
- virtual bool getBounds(float* outMinX, float* outMinY,
- float* outMaxX, float* outMaxY) const;
- virtual void move(float deltaX, float deltaY);
- virtual void setButtonState(int32_t buttonState);
- virtual int32_t getButtonState() const;
- virtual void setPosition(float x, float y);
- virtual void getPosition(float* outX, float* outY) const;
- virtual void fade(Transition transition) {}
- virtual void unfade(Transition transition) {}
- virtual void setPresentation(Presentation presentation) {}
- virtual void setSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
- BitSet32 spotIdBits) {}
- virtual void clearSpots() {}
-};
-
-bool
-GeckoPointerController::getBounds(float* outMinX,
- float* outMinY,
- float* outMaxX,
- float* outMaxY) const
-{
- DisplayViewport viewport;
-
- mConfig->getDisplayInfo(false, &viewport);
-
- *outMinX = *outMinY = 0;
- *outMaxX = viewport.logicalRight;
- *outMaxY = viewport.logicalBottom;
- return true;
-}
-
-void
-GeckoPointerController::move(float deltaX, float deltaY)
-{
- float minX, minY, maxX, maxY;
- getBounds(&minX, &minY, &maxX, &maxY);
-
- mX = clamped(mX + deltaX, minX, maxX);
- mY = clamped(mY + deltaY, minY, maxY);
-}
-
-void
-GeckoPointerController::setButtonState(int32_t buttonState)
-{
- mButtonState = buttonState;
-}
-
-int32_t
-GeckoPointerController::getButtonState() const
-{
- return mButtonState;
-}
-
-void
-GeckoPointerController::setPosition(float x, float y)
-{
- mX = x;
- mY = y;
-}
-
-void
-GeckoPointerController::getPosition(float* outX, float* outY) const
-{
- *outX = mX;
- *outY = mY;
-}
-
-class GeckoInputReaderPolicy : public InputReaderPolicyInterface {
- InputReaderConfiguration mConfig;
-public:
- GeckoInputReaderPolicy() {}
-
- virtual void getReaderConfiguration(InputReaderConfiguration* outConfig);
- virtual sp<PointerControllerInterface> obtainPointerController(int32_t
-deviceId)
- {
- return new GeckoPointerController(&mConfig);
- };
- virtual void notifyInputDevicesChanged(const android::Vector<InputDeviceInfo>& inputDevices) {};
- virtual sp<KeyCharacterMap> getKeyboardLayoutOverlay(const String8& inputDeviceDescriptor)
- {
- return nullptr;
- };
- virtual String8 getDeviceAlias(const InputDeviceIdentifier& identifier)
- {
- return String8::empty();
- };
-
- void setDisplayInfo();
-
-protected:
- virtual ~GeckoInputReaderPolicy() {}
-};
-
-class GeckoInputDispatcher : public InputDispatcherInterface {
-public:
- GeckoInputDispatcher(sp<EventHub> &aEventHub)
- : mQueueLock("GeckoInputDispatcher::mQueueMutex")
- , mEventHub(aEventHub)
- , mKeyDownCount(0)
- , mKeyEventsFiltered(false)
- , mPowerWakelock(false)
- {
- mTouchDispatcher = GeckoTouchDispatcher::GetInstance();
- }
-
- virtual void dump(String8& dump);
-
- virtual void monitor() {}
-
- // Called on the main thread
- virtual void dispatchOnce();
-
- // notify* methods are called on the InputReaderThread
- virtual void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args);
- virtual void notifyKey(const NotifyKeyArgs* args);
- virtual void notifyMotion(const NotifyMotionArgs* args);
- virtual void notifySwitch(const NotifySwitchArgs* args);
- virtual void notifyDeviceReset(const NotifyDeviceResetArgs* args);
-
- virtual int32_t injectInputEvent(const InputEvent* event,
- int32_t injectorPid, int32_t injectorUid, int32_t syncMode, int32_t timeoutMillis,
- uint32_t policyFlags);
-
- virtual void setInputWindows(const android::Vector<sp<InputWindowHandle> >& inputWindowHandles);
- virtual void setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle);
-
- virtual void setInputDispatchMode(bool enabled, bool frozen);
- virtual void setInputFilterEnabled(bool enabled) {}
- virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
- const sp<InputChannel>& toChannel) { return true; }
-
- virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
- const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
- virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
-
-
-
-protected:
- virtual ~GeckoInputDispatcher() { }
-
-private:
- // mQueueLock should generally be locked while using mEventQueue.
- // UserInputData is pushed on on the InputReaderThread and
- // popped and dispatched on the main thread.
- mozilla::Mutex mQueueLock;
- std::queue<UserInputData> mEventQueue;
- sp<EventHub> mEventHub;
- RefPtr<GeckoTouchDispatcher> mTouchDispatcher;
-
- int mKeyDownCount;
- bool mKeyEventsFiltered;
- bool mPowerWakelock;
-};
-
-// GeckoInputReaderPolicy
-void
-GeckoInputReaderPolicy::setDisplayInfo()
-{
- static_assert(static_cast<int>(nsIScreen::ROTATION_0_DEG) ==
- static_cast<int>(DISPLAY_ORIENTATION_0),
- "Orientation enums not matched!");
- static_assert(static_cast<int>(nsIScreen::ROTATION_90_DEG) ==
- static_cast<int>(DISPLAY_ORIENTATION_90),
- "Orientation enums not matched!");
- static_assert(static_cast<int>(nsIScreen::ROTATION_180_DEG) ==
- static_cast<int>(DISPLAY_ORIENTATION_180),
- "Orientation enums not matched!");
- static_assert(static_cast<int>(nsIScreen::ROTATION_270_DEG) ==
- static_cast<int>(DISPLAY_ORIENTATION_270),
- "Orientation enums not matched!");
-
- RefPtr<nsScreenGonk> screen = nsScreenManagerGonk::GetPrimaryScreen();
-
- uint32_t rotation = nsIScreen::ROTATION_0_DEG;
- DebugOnly<nsresult> rv = screen->GetRotation(&rotation);
- MOZ_ASSERT(NS_SUCCEEDED(rv));
- LayoutDeviceIntRect screenBounds = screen->GetNaturalBounds();
-
- DisplayViewport viewport;
- viewport.displayId = 0;
- viewport.orientation = rotation;
- viewport.physicalRight = viewport.deviceWidth = screenBounds.width;
- viewport.physicalBottom = viewport.deviceHeight = screenBounds.height;
- if (viewport.orientation == DISPLAY_ORIENTATION_90 ||
- viewport.orientation == DISPLAY_ORIENTATION_270) {
- viewport.logicalRight = screenBounds.height;
- viewport.logicalBottom = screenBounds.width;
- } else {
- viewport.logicalRight = screenBounds.width;
- viewport.logicalBottom = screenBounds.height;
- }
- mConfig.setDisplayInfo(false, viewport);
-}
-
-void GeckoInputReaderPolicy::getReaderConfiguration(InputReaderConfiguration* outConfig)
-{
- *outConfig = mConfig;
-}
-
-
-// GeckoInputDispatcher
-void
-GeckoInputDispatcher::dump(String8& dump)
-{
-}
-
-static bool
-isExpired(const UserInputData& data)
-{
- uint64_t timeNowMs =
- nanosecsToMillisecs(systemTime(SYSTEM_TIME_MONOTONIC));
- return (timeNowMs - data.timeMs) > kInputExpirationThresholdMs;
-}
-
-void
-GeckoInputDispatcher::dispatchOnce()
-{
- UserInputData data;
- {
- MutexAutoLock lock(mQueueLock);
- if (mEventQueue.empty())
- return;
- data = mEventQueue.front();
- mEventQueue.pop();
- if (!mEventQueue.empty())
- gAppShell->NotifyNativeEvent();
- }
-
- switch (data.type) {
- case UserInputData::MOTION_DATA: {
- MOZ_ASSERT_UNREACHABLE("Should not dispatch touch events here anymore");
- break;
- }
- case UserInputData::KEY_DATA: {
- if (!mKeyDownCount) {
- // No pending events, the filter state can be updated.
- mKeyEventsFiltered = isExpired(data);
- }
-
- mKeyDownCount += (data.action == AKEY_EVENT_ACTION_DOWN) ? 1 : -1;
- if (mKeyEventsFiltered) {
- return;
- }
-
- sp<KeyCharacterMap> kcm = mEventHub->getKeyCharacterMap(data.deviceId);
- KeyEventDispatcher dispatcher(data, kcm.get());
- dispatcher.Dispatch();
- break;
- }
- }
- MutexAutoLock lock(mQueueLock);
- if (mPowerWakelock && mEventQueue.empty()) {
- release_wake_lock(kKey_WAKE_LOCK_ID);
- mPowerWakelock = false;
- }
-}
-
-void
-GeckoInputDispatcher::notifyConfigurationChanged(const NotifyConfigurationChangedArgs*)
-{
- gAppShell->CheckPowerKey();
-}
-
-void
-GeckoInputDispatcher::notifyKey(const NotifyKeyArgs* args)
-{
- UserInputData data;
- data.timeMs = nanosecsToMillisecs(args->eventTime);
- data.type = UserInputData::KEY_DATA;
- data.action = args->action;
- data.flags = args->flags;
- data.metaState = args->metaState;
- data.deviceId = args->deviceId;
- data.key.keyCode = args->keyCode;
- data.key.scanCode = args->scanCode;
- {
- MutexAutoLock lock(mQueueLock);
- mEventQueue.push(data);
- if (!mPowerWakelock) {
- mPowerWakelock =
- acquire_wake_lock(PARTIAL_WAKE_LOCK, kKey_WAKE_LOCK_ID);
- }
- }
- gAppShell->NotifyNativeEvent();
-}
-
-static void
-addMultiTouch(MultiTouchInput& aMultiTouch,
- const NotifyMotionArgs* args, int aIndex)
-{
- int32_t id = args->pointerProperties[aIndex].id;
- PointerCoords coords = args->pointerCoords[aIndex];
- float force = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
-
- float orientation = coords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
- float rotationAngle = orientation * 180 / M_PI;
- if (rotationAngle == 90) {
- rotationAngle = -90;
- }
-
- float radiusX, radiusY;
- if (rotationAngle < 0) {
- radiusX = coords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR) / 2;
- radiusY = coords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR) / 2;
- rotationAngle += 90;
- } else {
- radiusX = coords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR) / 2;
- radiusY = coords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR) / 2;
- }
-
- ScreenIntPoint point = ScreenIntPoint::Round(coords.getX(),
- coords.getY());
-
- SingleTouchData touchData(id, point, ScreenSize(radiusX, radiusY),
- rotationAngle, force);
-
- aMultiTouch.mTouches.AppendElement(touchData);
-}
-
-void
-GeckoInputDispatcher::notifyMotion(const NotifyMotionArgs* args)
-{
- uint32_t time = nanosecsToMillisecs(args->eventTime);
- int32_t action = args->action & AMOTION_EVENT_ACTION_MASK;
- int touchCount = args->pointerCount;
- MOZ_ASSERT(touchCount <= MAX_POINTERS);
- TimeStamp timestamp = mozilla::TimeStamp::FromSystemTime(args->eventTime);
- Modifiers modifiers = getDOMModifiers(args->metaState);
-
- MultiTouchInput::MultiTouchType touchType = MultiTouchInput::MULTITOUCH_CANCEL;
- switch (action) {
- case AMOTION_EVENT_ACTION_DOWN:
- case AMOTION_EVENT_ACTION_POINTER_DOWN:
- touchType = MultiTouchInput::MULTITOUCH_START;
- break;
- case AMOTION_EVENT_ACTION_MOVE:
- touchType = MultiTouchInput::MULTITOUCH_MOVE;
- break;
- case AMOTION_EVENT_ACTION_UP:
- case AMOTION_EVENT_ACTION_POINTER_UP:
- touchType = MultiTouchInput::MULTITOUCH_END;
- break;
- case AMOTION_EVENT_ACTION_OUTSIDE:
- case AMOTION_EVENT_ACTION_CANCEL:
- touchType = MultiTouchInput::MULTITOUCH_CANCEL;
- break;
- case AMOTION_EVENT_ACTION_HOVER_EXIT:
- case AMOTION_EVENT_ACTION_HOVER_ENTER:
- case AMOTION_EVENT_ACTION_HOVER_MOVE:
- NS_WARNING("Ignoring hover touch events");
- return;
- default:
- MOZ_ASSERT_UNREACHABLE("Could not assign a touch type");
- break;
- }
-
- MultiTouchInput touchData(touchType, time, timestamp, modifiers);
-
- // For touch ends, we have to filter out which finger is actually
- // the touch end since the touch array has all fingers, not just the touch
- // that we want to end
- if (touchType == MultiTouchInput::MULTITOUCH_END) {
- int touchIndex = args->action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK;
- touchIndex >>= AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
- addMultiTouch(touchData, args, touchIndex);
- } else {
- for (int32_t i = 0; i < touchCount; ++i) {
- addMultiTouch(touchData, args, i);
- }
- }
-
- mTouchDispatcher->NotifyTouch(touchData, timestamp);
-}
-
-void GeckoInputDispatcher::notifySwitch(const NotifySwitchArgs* args)
-{
- if (!sDevInputAudioJack)
- return;
-
- bool needSwitchUpdate = false;
-
- if (args->switchMask & (1 << SW_HEADPHONE_INSERT)) {
- sHeadphoneState = (args->switchValues & (1 << SW_HEADPHONE_INSERT)) ?
- AKEY_STATE_DOWN : AKEY_STATE_UP;
- needSwitchUpdate = true;
- }
-
- if (args->switchMask & (1 << SW_MICROPHONE_INSERT)) {
- sMicrophoneState = (args->switchValues & (1 << SW_MICROPHONE_INSERT)) ?
- AKEY_STATE_DOWN : AKEY_STATE_UP;
- needSwitchUpdate = true;
- }
-
- if (needSwitchUpdate)
- updateHeadphoneSwitch();
-}
-
-void GeckoInputDispatcher::notifyDeviceReset(const NotifyDeviceResetArgs* args)
-{
-}
-
-int32_t GeckoInputDispatcher::injectInputEvent(
- const InputEvent* event,
- int32_t injectorPid, int32_t injectorUid, int32_t syncMode,
- int32_t timeoutMillis, uint32_t policyFlags)
-{
- return INPUT_EVENT_INJECTION_SUCCEEDED;
-}
-
-void
-GeckoInputDispatcher::setInputWindows(const android::Vector<sp<InputWindowHandle> >& inputWindowHandles)
-{
-}
-
-void
-GeckoInputDispatcher::setFocusedApplication(const sp<InputApplicationHandle>& inputApplicationHandle)
-{
-}
-
-void
-GeckoInputDispatcher::setInputDispatchMode(bool enabled, bool frozen)
-{
-}
-
-status_t
-GeckoInputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
- const sp<InputWindowHandle>& inputWindowHandle, bool monitor)
-{
- return OK;
-}
-
-status_t
-GeckoInputDispatcher::unregisterInputChannel(const sp<InputChannel>& inputChannel)
-{
- return OK;
-}
-
-nsAppShell::nsAppShell()
- : mNativeCallbackRequest(false)
- , mEnableDraw(false)
- , mHandlers()
- , mPowerKeyChecked(false)
-{
- gAppShell = this;
- if (XRE_IsParentProcess()) {
- Preferences::SetCString("b2g.safe_mode", "unset");
- }
-}
-
-nsAppShell::~nsAppShell()
-{
- // mReaderThread and mEventHub will both be null if InitInputDevices
- // is not called.
- if (mReaderThread.get()) {
- // We separate requestExit() and join() here so we can wake the EventHub's
- // input loop, and stop it from polling for input events
- mReaderThread->requestExit();
- mEventHub->wake();
-
- status_t result = mReaderThread->requestExitAndWait();
- if (result)
- LOG("Could not stop reader thread - %d", result);
- }
- gAppShell = nullptr;
-}
-
-nsresult
-nsAppShell::Init()
-{
- nsresult rv = nsBaseAppShell::Init();
- NS_ENSURE_SUCCESS(rv, rv);
-
- epollfd = epoll_create(16);
- NS_ENSURE_TRUE(epollfd >= 0, NS_ERROR_UNEXPECTED);
-
- int ret = pipe2(signalfds, O_NONBLOCK);
- NS_ENSURE_FALSE(ret, NS_ERROR_UNEXPECTED);
-
- rv = AddFdHandler(signalfds[0], pipeHandler, "");
- NS_ENSURE_SUCCESS(rv, rv);
-
- InitGonkMemoryPressureMonitoring();
-
- if (XRE_IsParentProcess()) {
- printf("*****************************************************************\n");
- printf("***\n");
- printf("*** This is stdout. Most of the useful output will be in logcat.\n");
- printf("***\n");
- printf("*****************************************************************\n");
- GonkPermissionService::instantiate();
-
- // Causes the kernel timezone to be set, which in turn causes the
- // timestamps on SD cards to have the local time rather than UTC time.
- hal::SetTimezone(hal::GetTimezone());
- }
-
- nsCOMPtr<nsIObserverService> obsServ = GetObserverService();
- if (obsServ) {
- obsServ->AddObserver(this, "browser-ui-startup-complete", false);
- obsServ->AddObserver(this, "network-connection-state-changed", false);
- }
-
- // Delay initializing input devices until the screen has been
- // initialized (and we know the resolution).
- return rv;
-}
-
-void
-nsAppShell::CheckPowerKey()
-{
- if (mPowerKeyChecked) {
- return;
- }
-
- uint32_t deviceId = 0;
- int32_t powerState = AKEY_STATE_UNKNOWN;
-
- // EventHub doesn't report the number of devices.
- while (powerState != AKEY_STATE_DOWN && deviceId < 32) {
- powerState = mEventHub->getKeyCodeState(deviceId++, AKEYCODE_POWER);
- }
-
- // If Power is pressed while we startup, mark safe mode.
- // Consumers of the b2g.safe_mode preference need to listen on this
- // preference change to prevent startup races.
- nsCOMPtr<nsIRunnable> prefSetter =
- NS_NewRunnableFunction([powerState] () -> void {
- Preferences::SetCString("b2g.safe_mode",
- (powerState == AKEY_STATE_DOWN) ? "yes" : "no");
- });
- NS_DispatchToMainThread(prefSetter.forget());
-
- mPowerKeyChecked = true;
-}
-
-NS_IMETHODIMP
-nsAppShell::Observe(nsISupports* aSubject,
- const char* aTopic,
- const char16_t* aData)
-{
- if (!strcmp(aTopic, "network-connection-state-changed")) {
- NS_ConvertUTF16toUTF8 type(aData);
- if (!type.IsEmpty()) {
- hal::NotifyNetworkChange(hal::NetworkInformation(atoi(type.get()), 0, 0));
- }
- return NS_OK;
- } else if (!strcmp(aTopic, "browser-ui-startup-complete")) {
- if (sDevInputAudioJack) {
- sHeadphoneState = mReader->getSwitchState(-1, AINPUT_SOURCE_SWITCH, SW_HEADPHONE_INSERT);
- sMicrophoneState = mReader->getSwitchState(-1, AINPUT_SOURCE_SWITCH, SW_MICROPHONE_INSERT);
- updateHeadphoneSwitch();
- }
- mEnableDraw = true;
-
- // System is almost booting up. Stop the bootAnim now.
- StopBootAnimation();
-
- NotifyEvent();
- return NS_OK;
- }
-
- return nsBaseAppShell::Observe(aSubject, aTopic, aData);
-}
-
-NS_IMETHODIMP
-nsAppShell::Exit()
-{
- OrientationObserver::ShutDown();
- nsCOMPtr<nsIObserverService> obsServ = GetObserverService();
- if (obsServ) {
- obsServ->RemoveObserver(this, "browser-ui-startup-complete");
- obsServ->RemoveObserver(this, "network-connection-state-changed");
- }
- return nsBaseAppShell::Exit();
-}
-
-void
-nsAppShell::InitInputDevices()
-{
- sDevInputAudioJack = hal::IsHeadphoneEventFromInputDev();
- sHeadphoneState = AKEY_STATE_UNKNOWN;
- sMicrophoneState = AKEY_STATE_UNKNOWN;
-
- mEventHub = new EventHub();
- mReaderPolicy = new GeckoInputReaderPolicy();
- mReaderPolicy->setDisplayInfo();
- mDispatcher = new GeckoInputDispatcher(mEventHub);
-
- mReader = new InputReader(mEventHub, mReaderPolicy, mDispatcher);
- mReaderThread = new InputReaderThread(mReader);
-
- status_t result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);
- if (result) {
- LOG("Failed to initialize InputReader thread, bad things are going to happen...");
- }
-}
-
-nsresult
-nsAppShell::AddFdHandler(int fd, FdHandlerCallback handlerFunc,
- const char* deviceName)
-{
- epoll_event event = {
- EPOLLIN,
- { 0 }
- };
-
- FdHandler *handler = mHandlers.AppendElement();
- handler->fd = fd;
- strncpy(handler->name, deviceName, sizeof(handler->name) - 1);
- handler->func = handlerFunc;
- event.data.u32 = mHandlers.Length() - 1;
- return epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event) ?
- NS_ERROR_UNEXPECTED : NS_OK;
-}
-
-void
-nsAppShell::ScheduleNativeEventCallback()
-{
- mNativeCallbackRequest = true;
- NotifyEvent();
-}
-
-bool
-nsAppShell::ProcessNextNativeEvent(bool mayWait)
-{
- PROFILER_LABEL("nsAppShell", "ProcessNextNativeEvent",
- js::ProfileEntry::Category::EVENTS);
-
- epoll_event events[16] = {{ 0 }};
-
- int event_count;
- {
- PROFILER_LABEL("nsAppShell", "ProcessNextNativeEvent::Wait",
- js::ProfileEntry::Category::EVENTS);
-
- if ((event_count = epoll_wait(epollfd, events, 16, mayWait ? -1 : 0)) <= 0)
- return true;
- }
-
- for (int i = 0; i < event_count; i++)
- mHandlers[events[i].data.u32].run();
-
- if (mDispatcher.get())
- mDispatcher->dispatchOnce();
-
- // NativeEventCallback always schedules more if it needs it
- // so we can coalesce these.
- // See the implementation in nsBaseAppShell.cpp for more info
- if (mNativeCallbackRequest) {
- mNativeCallbackRequest = false;
- NativeEventCallback();
- }
-
- if (gDrawRequest && mEnableDraw) {
- gDrawRequest = false;
- nsWindow::DoDraw();
- }
-
- return true;
-}
-
-void
-nsAppShell::NotifyNativeEvent()
-{
- write(signalfds[1], "w", 1);
-}
-
-/* static */ void
-nsAppShell::NotifyScreenInitialized()
-{
- gAppShell->InitInputDevices();
-
- // Getting the instance of OrientationObserver to initialize it.
- OrientationObserver::GetInstance();
-}
-
-/* static */ void
-nsAppShell::NotifyScreenRotation()
-{
- gAppShell->mReaderPolicy->setDisplayInfo();
- gAppShell->mReader->requestRefreshConfiguration(InputReaderConfiguration::CHANGE_DISPLAY_INFO);
-
- RefPtr<nsScreenGonk> screen = nsScreenManagerGonk::GetPrimaryScreen();
- hal::NotifyScreenConfigurationChange(screen->GetConfiguration());
-}
diff --git a/widget/gonk/nsAppShell.h b/widget/gonk/nsAppShell.h
deleted file mode 100644
index 046a99ea1..000000000
--- a/widget/gonk/nsAppShell.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef nsAppShell_h
-#define nsAppShell_h
-
-#include <queue>
-
-#include "mozilla/Mutex.h"
-#include "nsBaseAppShell.h"
-#include "nsTArray.h"
-
-#include "utils/RefBase.h"
-
-namespace mozilla {
-bool ProcessNextEvent();
-void NotifyEvent();
-}
-
-extern bool gDrawRequest;
-
-class FdHandler;
-typedef void(*FdHandlerCallback)(int, FdHandler *);
-
-class FdHandler {
-public:
- FdHandler()
- {
- memset(name, 0, sizeof(name));
- }
-
- int fd;
- char name[64];
- FdHandlerCallback func;
- void run()
- {
- func(fd, this);
- }
-};
-
-namespace android {
-class EventHub;
-class InputReader;
-class InputReaderThread;
-}
-
-class GeckoInputReaderPolicy;
-class GeckoInputDispatcher;
-
-class nsAppShell : public nsBaseAppShell {
-public:
- nsAppShell();
-
- NS_DECL_ISUPPORTS_INHERITED
- NS_DECL_NSIOBSERVER
-
- nsresult Init();
-
- NS_IMETHOD Exit() override;
-
- virtual bool ProcessNextNativeEvent(bool maywait);
-
- void NotifyNativeEvent();
-
- static void NotifyScreenInitialized();
- static void NotifyScreenRotation();
-
- void CheckPowerKey();
-
-protected:
- virtual ~nsAppShell();
-
- virtual void ScheduleNativeEventCallback();
-
-private:
- nsresult AddFdHandler(int fd, FdHandlerCallback handlerFunc,
- const char* deviceName);
- void InitInputDevices();
-
- // This is somewhat racy but is perfectly safe given how the callback works
- bool mNativeCallbackRequest;
-
- // This gets flipped when we observe a browser-ui-startup-complete.
- // browser-ui-startup-complete means that we're really ready to draw
- // and can stop the boot animation
- bool mEnableDraw;
- nsTArray<FdHandler> mHandlers;
-
- android::sp<android::EventHub> mEventHub;
- android::sp<GeckoInputReaderPolicy> mReaderPolicy;
- android::sp<GeckoInputDispatcher> mDispatcher;
- android::sp<android::InputReader> mReader;
- android::sp<android::InputReaderThread> mReaderThread;
-
- // Guard against checking power key after the first configuration change.
- bool mPowerKeyChecked;
-};
-
-#endif /* nsAppShell_h */
-
diff --git a/widget/gonk/nsClipboard.cpp b/widget/gonk/nsClipboard.cpp
deleted file mode 100644
index a1eabe8e5..000000000
--- a/widget/gonk/nsClipboard.cpp
+++ /dev/null
@@ -1,366 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 "nsClipboard.h"
-
-#include "gfxDrawable.h"
-#include "gfxUtils.h"
-#include "ImageOps.h"
-#include "imgIContainer.h"
-#include "imgTools.h"
-#include "mozilla/dom/ContentChild.h"
-#include "mozilla/Preferences.h"
-#include "nsArrayUtils.h"
-#include "nsClipboardProxy.h"
-#include "nsISupportsPrimitives.h"
-#include "nsComponentManagerUtils.h"
-#include "nsCOMPtr.h"
-#include "nsServiceManagerUtils.h"
-#include "nsStringStream.h"
-#include "nsXULAppAPI.h"
-
-using namespace mozilla;
-using mozilla::dom::ContentChild;
-
-#define LOG_TAG "Clipboard"
-#define LOGI(args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, ## args)
-#define LOGE(args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, ## args)
-
-
-NS_IMPL_ISUPPORTS(nsClipboard, nsIClipboard)
-
-nsClipboard::nsClipboard()
- : mClipboard(mozilla::MakeUnique<GonkClipboardData>())
-{
-}
-
-NS_IMETHODIMP
-nsClipboard::SetData(nsITransferable *aTransferable,
- nsIClipboardOwner *anOwner,
- int32_t aWhichClipboard)
-{
- if (aWhichClipboard != kGlobalClipboard) {
- return NS_ERROR_NOT_IMPLEMENTED;
- }
-
- if (!XRE_IsParentProcess()) {
- // Re-direct to the clipboard proxy.
- RefPtr<nsClipboardProxy> clipboardProxy = new nsClipboardProxy();
- return clipboardProxy->SetData(aTransferable, anOwner, aWhichClipboard);
- }
-
- // Clear out the clipboard in order to set the new data.
- EmptyClipboard(aWhichClipboard);
-
- // Use a pref to toggle rich text/non-text support.
- if (Preferences::GetBool("clipboard.plainTextOnly")) {
- nsCOMPtr<nsISupports> clip;
- uint32_t len;
- nsresult rv = aTransferable->GetTransferData(kUnicodeMime,
- getter_AddRefs(clip),
- &len);
- if (NS_FAILED(rv)) {
- return rv;
- }
- nsCOMPtr<nsISupportsString> wideString = do_QueryInterface(clip);
- if (!wideString) {
- return NS_ERROR_NOT_IMPLEMENTED;
- }
- nsAutoString utf16string;
- wideString->GetData(utf16string);
- mClipboard->SetText(utf16string);
- return NS_OK;
- }
-
- // Get the types of supported flavors.
- nsCOMPtr<nsIArray> flavorList;
- nsresult rv = aTransferable->FlavorsTransferableCanExport(getter_AddRefs(flavorList));
- if (!flavorList || NS_FAILED(rv)) {
- return NS_ERROR_FAILURE;
- }
-
- uint32_t flavorCount = 0;
- flavorList->GetLength(&flavorCount);
- bool imageAdded = false;
- for (uint32_t i = 0; i < flavorCount; ++i) {
- nsCOMPtr<nsISupportsCString> currentFlavor = do_QueryElementAt(flavorList, i);
-
- if (currentFlavor) {
- // MIME type
- nsXPIDLCString flavorStr;
- currentFlavor->ToString(getter_Copies(flavorStr));
-
- // Clip is the data which will be sent to the clipboard.
- nsCOMPtr<nsISupports> clip;
- uint32_t len;
-
- if (flavorStr.EqualsLiteral(kUnicodeMime)) {
- // text/plain
- rv = aTransferable->GetTransferData(flavorStr, getter_AddRefs(clip), &len);
- nsCOMPtr<nsISupportsString> wideString = do_QueryInterface(clip);
- if (!wideString || NS_FAILED(rv)) {
- continue;
- }
-
- nsAutoString utf16string;
- wideString->GetData(utf16string);
- mClipboard->SetText(utf16string);
- } else if (flavorStr.EqualsLiteral(kHTMLMime)) {
- // text/html
- rv = aTransferable->GetTransferData(flavorStr, getter_AddRefs(clip), &len);
- nsCOMPtr<nsISupportsString> wideString = do_QueryInterface(clip);
- if (!wideString || NS_FAILED(rv)) {
- continue;
- }
-
- nsAutoString utf16string;
- wideString->GetData(utf16string);
- mClipboard->SetHTML(utf16string);
- } else if (!imageAdded && // image is added only once to the clipboard.
- (flavorStr.EqualsLiteral(kNativeImageMime) ||
- flavorStr.EqualsLiteral(kPNGImageMime) ||
- flavorStr.EqualsLiteral(kJPEGImageMime) ||
- flavorStr.EqualsLiteral(kJPGImageMime))) {
- // image/[png|jpeg|jpg] or application/x-moz-nativeimage
-
- // Look through our transfer data for the image.
- static const char* const imageMimeTypes[] = {
- kNativeImageMime, kPNGImageMime, kJPEGImageMime, kJPGImageMime };
-
- nsCOMPtr<nsISupportsInterfacePointer> imgPtr;
- for (uint32_t i = 0; !imgPtr && i < ArrayLength(imageMimeTypes); ++i) {
- aTransferable->GetTransferData(imageMimeTypes[i], getter_AddRefs(clip), &len);
- imgPtr = do_QueryInterface(clip);
- }
- if (!imgPtr) {
- continue;
- }
-
- nsCOMPtr<nsISupports> imageData;
- imgPtr->GetData(getter_AddRefs(imageData));
- nsCOMPtr<imgIContainer> image(do_QueryInterface(imageData));
- if (!image) {
- continue;
- }
-
- RefPtr<gfx::SourceSurface> surface =
- image->GetFrame(imgIContainer::FRAME_CURRENT,
- imgIContainer::FLAG_SYNC_DECODE);
- if (!surface) {
- continue;
- }
-
- RefPtr<gfx::DataSourceSurface> dataSurface;
- if (surface->GetFormat() == gfx::SurfaceFormat::B8G8R8A8) {
- dataSurface = surface->GetDataSurface();
- } else {
- // Convert format to SurfaceFormat::B8G8R8A8.
- dataSurface = gfxUtils::CopySurfaceToDataSourceSurfaceWithFormat(surface, gfx::SurfaceFormat::B8G8R8A8);
- }
-
- mClipboard->SetImage(dataSurface);
- imageAdded = true;
- }
- }
- }
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsClipboard::GetData(nsITransferable *aTransferable,
- int32_t aWhichClipboard)
-{
- if (aWhichClipboard != kGlobalClipboard) {
- return NS_ERROR_NOT_IMPLEMENTED;
- }
-
- if (!XRE_IsParentProcess()) {
- // Re-direct to the clipboard proxy.
- RefPtr<nsClipboardProxy> clipboardProxy = new nsClipboardProxy();
- return clipboardProxy->GetData(aTransferable, aWhichClipboard);
- }
-
- // Use a pref to toggle rich text/non-text support.
- if (Preferences::GetBool("clipboard.plainTextOnly")) {
- nsresult rv;
- nsCOMPtr<nsISupportsString> dataWrapper =
- do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv);
- rv = dataWrapper->SetData(mClipboard->GetText());
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
- nsCOMPtr<nsISupports> genericDataWrapper = do_QueryInterface(dataWrapper);
- uint32_t len = mClipboard->GetText().Length() * sizeof(char16_t);
- rv = aTransferable->SetTransferData(kUnicodeMime, genericDataWrapper, len);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
- return NS_OK;
- }
-
- // Get flavor list that includes all acceptable flavors (including
- // ones obtained through conversion).
- // Note: We don't need to call nsITransferable::AddDataFlavor here
- // because ContentParent already did.
- nsCOMPtr<nsIArray> flavorList;
- nsresult rv = aTransferable->FlavorsTransferableCanImport(getter_AddRefs(flavorList));
-
- if (!flavorList || NS_FAILED(rv)) {
- return NS_ERROR_FAILURE;
- }
-
- // Walk through flavors and see which flavor matches the one being pasted.
- uint32_t flavorCount;
- flavorList->GetLength(&flavorCount);
-
- for (uint32_t i = 0; i < flavorCount; ++i) {
- nsCOMPtr<nsISupportsCString> currentFlavor = do_QueryElementAt(flavorList, i);
-
- if (currentFlavor) {
- // flavorStr is the mime type.
- nsXPIDLCString flavorStr;
- currentFlavor->ToString(getter_Copies(flavorStr));
-
- // text/plain, text/Unicode
- if (flavorStr.EqualsLiteral(kUnicodeMime) && mClipboard->HasText()) {
- nsresult rv;
- nsCOMPtr<nsISupportsString> dataWrapper = do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv);
- rv = dataWrapper->SetData(mClipboard->GetText());
- if (NS_WARN_IF(NS_FAILED(rv))) {
- continue;
- }
-
- nsCOMPtr<nsISupports> genericDataWrapper = do_QueryInterface(dataWrapper);
- uint32_t len = mClipboard->GetText().Length() * sizeof(char16_t);
- rv = aTransferable->SetTransferData(flavorStr, genericDataWrapper, len);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- continue;
- }
- break;
- }
-
- // text/html
- if (flavorStr.EqualsLiteral(kHTMLMime) && mClipboard->HasHTML()) {
- nsresult rv;
- nsCOMPtr<nsISupportsString> dataWrapper = do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID, &rv);
- rv = dataWrapper->SetData(mClipboard->GetHTML());
- if (NS_WARN_IF(NS_FAILED(rv))) {
- continue;
- }
-
- nsCOMPtr<nsISupports> genericDataWrapper = do_QueryInterface(dataWrapper);
- uint32_t len = mClipboard->GetHTML().Length() * sizeof(char16_t);
- rv = aTransferable->SetTransferData(flavorStr, genericDataWrapper, len);
- if (NS_WARN_IF(NS_FAILED(rv))) {
- continue;
- }
- break;
- }
-
- // image/[png|jpeg|jpg]
- if ((flavorStr.EqualsLiteral(kPNGImageMime) ||
- flavorStr.EqualsLiteral(kJPEGImageMime) ||
- flavorStr.EqualsLiteral(kJPGImageMime)) &&
- mClipboard->HasImage() ) {
- // Get image buffer from clipboard.
- RefPtr<gfx::DataSourceSurface> image = mClipboard->GetImage();
-
- // Encode according to MIME type.
- RefPtr<gfxDrawable> drawable = new gfxSurfaceDrawable(image, image->GetSize());
- nsCOMPtr<imgIContainer> imageContainer(image::ImageOps::CreateFromDrawable(drawable));
- nsCOMPtr<imgITools> imgTool = do_GetService(NS_IMGTOOLS_CID);
-
- nsCOMPtr<nsIInputStream> byteStream;
- nsresult rv = imgTool->EncodeImage(imageContainer,
- flavorStr,
- EmptyString(),
- getter_AddRefs(byteStream));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- continue;
- }
-
- // Set transferable.
- rv = aTransferable->SetTransferData(flavorStr,
- byteStream,
- sizeof(nsIInputStream*));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- continue;
- }
- break;
- }
- }
- }
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsClipboard::EmptyClipboard(int32_t aWhichClipboard)
-{
- if (aWhichClipboard != kGlobalClipboard) {
- return NS_ERROR_NOT_IMPLEMENTED;
- }
- if (XRE_IsParentProcess()) {
- mClipboard->Clear();
- } else {
- ContentChild::GetSingleton()->SendEmptyClipboard(aWhichClipboard);
- }
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsClipboard::HasDataMatchingFlavors(const char **aFlavorList,
- uint32_t aLength, int32_t aWhichClipboard,
- bool *aHasType)
-{
- *aHasType = false;
- if (aWhichClipboard != kGlobalClipboard) {
- return NS_ERROR_NOT_IMPLEMENTED;
- }
- if (XRE_IsParentProcess()) {
- // Retrieve the union of all aHasType in aFlavorList
- for (uint32_t i = 0; i < aLength; ++i) {
- const char *flavor = aFlavorList[i];
- if (!flavor) {
- continue;
- }
- if (!strcmp(flavor, kUnicodeMime) && mClipboard->HasText()) {
- *aHasType = true;
- } else if (!strcmp(flavor, kHTMLMime) && mClipboard->HasHTML()) {
- *aHasType = true;
- } else if (!strcmp(flavor, kJPEGImageMime) ||
- !strcmp(flavor, kJPGImageMime) ||
- !strcmp(flavor, kPNGImageMime)) {
- // We will encode the image into any format you want, so we don't
- // need to check each specific format
- if (mClipboard->HasImage()) {
- *aHasType = true;
- }
- }
- }
- } else {
- RefPtr<nsClipboardProxy> clipboardProxy = new nsClipboardProxy();
- return clipboardProxy->HasDataMatchingFlavors(aFlavorList, aLength, aWhichClipboard, aHasType);
- }
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsClipboard::SupportsSelectionClipboard(bool *aIsSupported)
-{
- *aIsSupported = false;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsClipboard::SupportsFindClipboard(bool* _retval)
-{
- NS_ENSURE_ARG_POINTER(_retval);
-
- *_retval = false;
- return NS_OK;
-}
-
diff --git a/widget/gonk/nsClipboard.h b/widget/gonk/nsClipboard.h
deleted file mode 100644
index cd2e0dbd5..000000000
--- a/widget/gonk/nsClipboard.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.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 nsClipbard_h__
-#define nsClipbard_h__
-
-#include "GonkClipboardData.h"
-#include "mozilla/UniquePtr.h"
-#include "nsIClipboard.h"
-
-class nsClipboard final : public nsIClipboard
-{
-public:
- NS_DECL_ISUPPORTS
- NS_DECL_NSICLIPBOARD
-
- nsClipboard();
-
-protected:
- ~nsClipboard() {}
-
-private:
- mozilla::UniquePtr<mozilla::GonkClipboardData> mClipboard;
-};
-
-#endif
diff --git a/widget/gonk/nsIdleServiceGonk.cpp b/widget/gonk/nsIdleServiceGonk.cpp
deleted file mode 100644
index dc7588e5e..000000000
--- a/widget/gonk/nsIdleServiceGonk.cpp
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:expandtab:shiftwidth=4:tabstop=4: */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nsIdleServiceGonk.h"
-#include "nsIServiceManager.h"
-
-NS_IMPL_ISUPPORTS_INHERITED0(nsIdleServiceGonk, nsIdleService)
-
-bool
-nsIdleServiceGonk::PollIdleTime(uint32_t *aIdleTime)
-{
- return false;
-}
-
-bool
-nsIdleServiceGonk::UsePollMode()
-{
- return false;
-}
diff --git a/widget/gonk/nsIdleServiceGonk.h b/widget/gonk/nsIdleServiceGonk.h
deleted file mode 100644
index 32520dce6..000000000
--- a/widget/gonk/nsIdleServiceGonk.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:expandtab:shiftwidth=4:tabstop=4: */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef nsIdleServiceGonk_h__
-#define nsIdleServiceGonk_h__
-
-#include "nsIdleService.h"
-
-class nsIdleServiceGonk : public nsIdleService
-{
-public:
- NS_DECL_ISUPPORTS_INHERITED
-
- bool PollIdleTime(uint32_t* aIdleTime);
-
- static already_AddRefed<nsIdleServiceGonk> GetInstance()
- {
- RefPtr<nsIdleServiceGonk> idleService =
- nsIdleService::GetInstance().downcast<nsIdleServiceGonk>();
- if (!idleService) {
- idleService = new nsIdleServiceGonk();
- }
-
- return idleService.forget();
- }
-
-protected:
- nsIdleServiceGonk() { }
- virtual ~nsIdleServiceGonk() { }
- bool UsePollMode();
-};
-
-#endif // nsIdleServiceGonk_h__
diff --git a/widget/gonk/nsLookAndFeel.cpp b/widget/gonk/nsLookAndFeel.cpp
deleted file mode 100644
index 120f257df..000000000
--- a/widget/gonk/nsLookAndFeel.cpp
+++ /dev/null
@@ -1,465 +0,0 @@
-/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nsLookAndFeel.h"
-#include "nsStyleConsts.h"
-#include "gfxFont.h"
-#include "gfxFontConstants.h"
-#include "mozilla/gfx/2D.h"
-#include "cutils/properties.h"
-
-static const char16_t UNICODE_BULLET = 0x2022;
-
-nsLookAndFeel::nsLookAndFeel()
- : nsXPLookAndFeel()
-{
-}
-
-nsLookAndFeel::~nsLookAndFeel()
-{
-}
-
-nsresult
-nsLookAndFeel::NativeGetColor(ColorID aID, nscolor &aColor)
-{
- nsresult rv = NS_OK;
-
-#define BASE_ACTIVE_COLOR NS_RGB(0xaa,0xaa,0xaa)
-#define BASE_NORMAL_COLOR NS_RGB(0xff,0xff,0xff)
-#define BASE_SELECTED_COLOR NS_RGB(0xaa,0xaa,0xaa)
-#define BG_ACTIVE_COLOR NS_RGB(0xff,0xff,0xff)
-#define BG_INSENSITIVE_COLOR NS_RGB(0xaa,0xaa,0xaa)
-#define BG_NORMAL_COLOR NS_RGB(0xff,0xff,0xff)
-#define BG_PRELIGHT_COLOR NS_RGB(0xee,0xee,0xee)
-#define BG_SELECTED_COLOR NS_RGB(0x99,0x99,0x99)
-#define DARK_NORMAL_COLOR NS_RGB(0x88,0x88,0x88)
-#define FG_INSENSITIVE_COLOR NS_RGB(0x44,0x44,0x44)
-#define FG_NORMAL_COLOR NS_RGB(0x00,0x00,0x00)
-#define FG_PRELIGHT_COLOR NS_RGB(0x77,0x77,0x77)
-#define FG_SELECTED_COLOR NS_RGB(0xaa,0xaa,0xaa)
-#define LIGHT_NORMAL_COLOR NS_RGB(0xaa,0xaa,0xaa)
-#define TEXT_ACTIVE_COLOR NS_RGB(0x99,0x99,0x99)
-#define TEXT_NORMAL_COLOR NS_RGB(0x00,0x00,0x00)
-#define TEXT_SELECTED_COLOR NS_RGB(0x00,0x00,0x00)
-
- switch (aID) {
- // These colors don't seem to be used for anything anymore in Mozilla
- // (except here at least TextSelectBackground and TextSelectForeground)
- // The CSS2 colors below are used.
- case eColorID_WindowBackground:
- aColor = BASE_NORMAL_COLOR;
- break;
- case eColorID_WindowForeground:
- aColor = TEXT_NORMAL_COLOR;
- break;
- case eColorID_WidgetBackground:
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID_WidgetForeground:
- aColor = FG_NORMAL_COLOR;
- break;
- case eColorID_WidgetSelectBackground:
- aColor = BG_SELECTED_COLOR;
- break;
- case eColorID_WidgetSelectForeground:
- aColor = FG_SELECTED_COLOR;
- break;
- case eColorID_Widget3DHighlight:
- aColor = NS_RGB(0xa0,0xa0,0xa0);
- break;
- case eColorID_Widget3DShadow:
- aColor = NS_RGB(0x40,0x40,0x40);
- break;
- case eColorID_TextBackground:
- // not used?
- aColor = BASE_NORMAL_COLOR;
- break;
- case eColorID_TextForeground:
- // not used?
- aColor = TEXT_NORMAL_COLOR;
- break;
- case eColorID_TextSelectBackground:
- aColor = NS_RGBA(0x33,0xb5,0xe5,0x66);
- break;
- case eColorID_IMESelectedRawTextBackground:
- case eColorID_IMESelectedConvertedTextBackground:
- // still used
- aColor = BASE_SELECTED_COLOR;
- break;
- case eColorID_TextSelectForegroundCustom:
- aColor = NS_RGB(0x4d,0x4d,0x4d);
- break;
- case eColorID_TextSelectForeground:
- aColor = NS_CHANGE_COLOR_IF_SAME_AS_BG;
- break;
- case eColorID_IMESelectedRawTextForeground:
- case eColorID_IMESelectedConvertedTextForeground:
- // still used
- aColor = TEXT_SELECTED_COLOR;
- break;
- case eColorID_IMERawInputBackground:
- case eColorID_IMEConvertedTextBackground:
- aColor = NS_TRANSPARENT;
- break;
- case eColorID_IMERawInputForeground:
- case eColorID_IMEConvertedTextForeground:
- aColor = NS_SAME_AS_FOREGROUND_COLOR;
- break;
- case eColorID_IMERawInputUnderline:
- case eColorID_IMEConvertedTextUnderline:
- aColor = NS_SAME_AS_FOREGROUND_COLOR;
- break;
- case eColorID_IMESelectedRawTextUnderline:
- case eColorID_IMESelectedConvertedTextUnderline:
- aColor = NS_TRANSPARENT;
- break;
- case eColorID_SpellCheckerUnderline:
- aColor = NS_RGB(0xff, 0, 0);
- break;
-
- // css2 http://www.w3.org/TR/REC-CSS2/ui.html#system-colors
- case eColorID_activeborder:
- // active window border
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID_activecaption:
- // active window caption background
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID_appworkspace:
- // MDI background color
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID_background:
- // desktop background
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID_captiontext:
- // text in active window caption, size box, and scrollbar arrow box (!)
- aColor = FG_NORMAL_COLOR;
- break;
- case eColorID_graytext:
- // disabled text in windows, menus, etc.
- aColor = FG_INSENSITIVE_COLOR;
- break;
- case eColorID_highlight:
- // background of selected item
- aColor = BASE_SELECTED_COLOR;
- break;
- case eColorID_highlighttext:
- // text of selected item
- aColor = TEXT_SELECTED_COLOR;
- break;
- case eColorID_inactiveborder:
- // inactive window border
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID_inactivecaption:
- // inactive window caption
- aColor = BG_INSENSITIVE_COLOR;
- break;
- case eColorID_inactivecaptiontext:
- // text in inactive window caption
- aColor = FG_INSENSITIVE_COLOR;
- break;
- case eColorID_infobackground:
- // tooltip background color
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID_infotext:
- // tooltip text color
- aColor = TEXT_NORMAL_COLOR;
- break;
- case eColorID_menu:
- // menu background
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID_menutext:
- // menu text
- aColor = TEXT_NORMAL_COLOR;
- break;
- case eColorID_scrollbar:
- // scrollbar gray area
- aColor = BG_ACTIVE_COLOR;
- break;
-
- case eColorID_threedface:
- case eColorID_buttonface:
- // 3-D face color
- aColor = BG_NORMAL_COLOR;
- break;
-
- case eColorID_buttontext:
- // text on push buttons
- aColor = TEXT_NORMAL_COLOR;
- break;
-
- case eColorID_buttonhighlight:
- // 3-D highlighted edge color
- case eColorID_threedhighlight:
- // 3-D highlighted outer edge color
- aColor = LIGHT_NORMAL_COLOR;
- break;
-
- case eColorID_threedlightshadow:
- // 3-D highlighted inner edge color
- aColor = BG_NORMAL_COLOR;
- break;
-
- case eColorID_buttonshadow:
- // 3-D shadow edge color
- case eColorID_threedshadow:
- // 3-D shadow inner edge color
- aColor = DARK_NORMAL_COLOR;
- break;
-
- case eColorID_threeddarkshadow:
- // 3-D shadow outer edge color
- aColor = NS_RGB(0,0,0);
- break;
-
- case eColorID_window:
- case eColorID_windowframe:
- aColor = BG_NORMAL_COLOR;
- break;
-
- case eColorID_windowtext:
- aColor = FG_NORMAL_COLOR;
- break;
-
- case eColorID__moz_eventreerow:
- case eColorID__moz_field:
- aColor = BASE_NORMAL_COLOR;
- break;
- case eColorID__moz_fieldtext:
- aColor = TEXT_NORMAL_COLOR;
- break;
- case eColorID__moz_dialog:
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID__moz_dialogtext:
- aColor = FG_NORMAL_COLOR;
- break;
- case eColorID__moz_dragtargetzone:
- aColor = BG_SELECTED_COLOR;
- break;
- case eColorID__moz_buttondefault:
- // default button border color
- aColor = NS_RGB(0,0,0);
- break;
- case eColorID__moz_buttonhoverface:
- aColor = BG_PRELIGHT_COLOR;
- break;
- case eColorID__moz_buttonhovertext:
- aColor = FG_PRELIGHT_COLOR;
- break;
- case eColorID__moz_cellhighlight:
- case eColorID__moz_html_cellhighlight:
- aColor = BASE_ACTIVE_COLOR;
- break;
- case eColorID__moz_cellhighlighttext:
- case eColorID__moz_html_cellhighlighttext:
- aColor = TEXT_ACTIVE_COLOR;
- break;
- case eColorID__moz_menuhover:
- aColor = BG_PRELIGHT_COLOR;
- break;
- case eColorID__moz_menuhovertext:
- aColor = FG_PRELIGHT_COLOR;
- break;
- case eColorID__moz_oddtreerow:
- aColor = NS_TRANSPARENT;
- break;
- case eColorID__moz_nativehyperlinktext:
- aColor = NS_SAME_AS_FOREGROUND_COLOR;
- break;
- case eColorID__moz_comboboxtext:
- aColor = TEXT_NORMAL_COLOR;
- break;
- case eColorID__moz_combobox:
- aColor = BG_NORMAL_COLOR;
- break;
- case eColorID__moz_menubartext:
- aColor = TEXT_NORMAL_COLOR;
- break;
- case eColorID__moz_menubarhovertext:
- aColor = FG_PRELIGHT_COLOR;
- break;
- default:
- /* default color is BLACK */
- aColor = 0;
- rv = NS_ERROR_FAILURE;
- break;
- }
-
- return rv;
-}
-
-nsresult
-nsLookAndFeel::GetIntImpl(IntID aID, int32_t &aResult)
-{
- nsresult rv = nsXPLookAndFeel::GetIntImpl(aID, aResult);
- if (NS_SUCCEEDED(rv))
- return rv;
-
- rv = NS_OK;
-
- switch (aID) {
- case eIntID_CaretBlinkTime:
- aResult = 500;
- break;
-
- case eIntID_CaretWidth:
- aResult = 1;
- break;
-
- case eIntID_ShowCaretDuringSelection:
- aResult = 0;
- break;
-
- case eIntID_SelectTextfieldsOnKeyFocus:
- // Select textfield content when focused by kbd
- // used by EventStateManager::sTextfieldSelectModel
- aResult = 1;
- break;
-
- case eIntID_SubmenuDelay:
- aResult = 200;
- break;
-
- case eIntID_TooltipDelay:
- aResult = 500;
- break;
-
- case eIntID_MenusCanOverlapOSBar:
- // we want XUL popups to be able to overlap the task bar.
- aResult = 1;
- break;
-
- case eIntID_ScrollArrowStyle:
- aResult = eScrollArrowStyle_Single;
- break;
-
- case eIntID_ScrollSliderStyle:
- aResult = eScrollThumbStyle_Proportional;
- break;
-
- case eIntID_TouchEnabled:
- aResult = 1;
- break;
-
- case eIntID_WindowsDefaultTheme:
- case eIntID_WindowsThemeIdentifier:
- case eIntID_OperatingSystemVersionIdentifier:
- aResult = 0;
- rv = NS_ERROR_NOT_IMPLEMENTED;
- break;
-
- case eIntID_IMERawInputUnderlineStyle:
- case eIntID_IMEConvertedTextUnderlineStyle:
- aResult = NS_STYLE_TEXT_DECORATION_STYLE_SOLID;
- break;
-
- case eIntID_IMESelectedRawTextUnderlineStyle:
- case eIntID_IMESelectedConvertedTextUnderline:
- aResult = NS_STYLE_TEXT_DECORATION_STYLE_NONE;
- break;
-
- case eIntID_SpellCheckerUnderlineStyle:
- aResult = NS_STYLE_TEXT_DECORATION_STYLE_WAVY;
- break;
-
- case eIntID_ScrollbarButtonAutoRepeatBehavior:
- aResult = 0;
- break;
-
- case eIntID_PhysicalHomeButton: {
- char propValue[PROPERTY_VALUE_MAX];
- property_get("ro.moz.has_home_button", propValue, "1");
- aResult = atoi(propValue);
- break;
- }
-
- case eIntID_ContextMenuOffsetVertical:
- case eIntID_ContextMenuOffsetHorizontal:
- aResult = 2;
- break;
-
- default:
- aResult = 0;
- rv = NS_ERROR_FAILURE;
- }
-
- return rv;
-}
-
-nsresult
-nsLookAndFeel::GetFloatImpl(FloatID aID, float &aResult)
-{
- nsresult res = nsXPLookAndFeel::GetFloatImpl(aID, aResult);
- if (NS_SUCCEEDED(res))
- return res;
- res = NS_OK;
-
- switch (aID) {
- case eFloatID_IMEUnderlineRelativeSize:
- aResult = 1.0f;
- break;
- case eFloatID_SpellCheckerUnderlineRelativeSize:
- aResult = 1.0f;
- break;
- default:
- aResult = -1.0;
- res = NS_ERROR_FAILURE;
- }
- return res;
-}
-
-/*virtual*/
-bool
-nsLookAndFeel::GetFontImpl(FontID aID, nsString& aFontName,
- gfxFontStyle& aFontStyle,
- float aDevPixPerCSSPixel)
-{
- aFontName.AssignLiteral("\"Fira Sans\"");
- aFontStyle.style = NS_FONT_STYLE_NORMAL;
- aFontStyle.weight = NS_FONT_WEIGHT_NORMAL;
- aFontStyle.stretch = NS_FONT_STRETCH_NORMAL;
- aFontStyle.size = 9.0 * 96.0f / 72.0f;
- aFontStyle.systemFont = true;
- return true;
-}
-
-/*virtual*/
-bool
-nsLookAndFeel::GetEchoPasswordImpl() {
- return true;
-}
-
-/*virtual*/
-uint32_t
-nsLookAndFeel::GetPasswordMaskDelayImpl()
-{
- // Same value on Android framework
- return 1500;
-}
-
-/* virtual */
-char16_t
-nsLookAndFeel::GetPasswordCharacterImpl()
-{
- return UNICODE_BULLET;
-}
diff --git a/widget/gonk/nsLookAndFeel.h b/widget/gonk/nsLookAndFeel.h
deleted file mode 100644
index aa7dce823..000000000
--- a/widget/gonk/nsLookAndFeel.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef __nsLookAndFeel
-#define __nsLookAndFeel
-
-#include "nsXPLookAndFeel.h"
-
-class nsLookAndFeel : public nsXPLookAndFeel
-{
-public:
- nsLookAndFeel();
- virtual ~nsLookAndFeel();
-
- virtual bool GetFontImpl(FontID aID, nsString& aName, gfxFontStyle& aStyle,
- float aDevPixPerCSSPixel);
- virtual nsresult GetIntImpl(IntID aID, int32_t &aResult);
- virtual nsresult GetFloatImpl(FloatID aID, float &aResult);
- virtual bool GetEchoPasswordImpl();
- virtual uint32_t GetPasswordMaskDelayImpl();
- virtual char16_t GetPasswordCharacterImpl();
-
-protected:
- virtual nsresult NativeGetColor(ColorID aID, nscolor &aColor);
-};
-
-#endif
diff --git a/widget/gonk/nsScreenManagerGonk.cpp b/widget/gonk/nsScreenManagerGonk.cpp
deleted file mode 100644
index e359fd195..000000000
--- a/widget/gonk/nsScreenManagerGonk.cpp
+++ /dev/null
@@ -1,1081 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "android/log.h"
-#include "GLContext.h"
-#include "gfxPrefs.h"
-#include "gfxUtils.h"
-#include "mozilla/MouseEvents.h"
-#include "mozilla/TouchEvents.h"
-#include "mozilla/Hal.h"
-#include "libdisplay/BootAnimation.h"
-#include "libdisplay/GonkDisplay.h"
-#include "nsScreenManagerGonk.h"
-#include "nsThreadUtils.h"
-#include "HwcComposer2D.h"
-#include "VsyncSource.h"
-#include "nsWindow.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "mozilla/layers/CompositorBridgeParent.h"
-#include "mozilla/layers/CompositorThread.h"
-#include "mozilla/Services.h"
-#include "mozilla/ProcessPriorityManager.h"
-#include "nsIdleService.h"
-#include "nsIObserverService.h"
-#include "nsAppShell.h"
-#include "nsProxyRelease.h"
-#include "nsTArray.h"
-#include "pixelflinger/format.h"
-#include "nsIDisplayInfo.h"
-#include "base/task.h"
-
-#if ANDROID_VERSION >= 17
-#include "libdisplay/DisplaySurface.h"
-#endif
-
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "nsScreenGonk" , ## args)
-#define LOGW(args...) __android_log_print(ANDROID_LOG_WARN, "nsScreenGonk", ## args)
-#define LOGE(args...) __android_log_print(ANDROID_LOG_ERROR, "nsScreenGonk", ## args)
-
-using namespace mozilla;
-using namespace mozilla::hal;
-using namespace mozilla::gfx;
-using namespace mozilla::gl;
-using namespace mozilla::layers;
-using namespace mozilla::dom;
-
-namespace {
-
-class ScreenOnOffEvent : public mozilla::Runnable {
-public:
- ScreenOnOffEvent(bool on)
- : mIsOn(on)
- {}
-
- NS_IMETHOD Run() override {
- // Notify observers that the screen state has just changed.
- nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
- if (observerService) {
- observerService->NotifyObservers(
- nullptr, "screen-state-changed",
- mIsOn ? u"on" : u"off"
- );
- }
-
- RefPtr<nsScreenGonk> screen = nsScreenManagerGonk::GetPrimaryScreen();
- const nsTArray<nsWindow*>& windows = screen->GetTopWindows();
-
- for (uint32_t i = 0; i < windows.Length(); i++) {
- nsWindow *win = windows[i];
-
- if (nsIWidgetListener* listener = win->GetWidgetListener()) {
- listener->SizeModeChanged(mIsOn ? nsSizeMode_Fullscreen : nsSizeMode_Minimized);
- }
- }
-
- return NS_OK;
- }
-
-private:
- bool mIsOn;
-};
-
-static void
-displayEnabledCallback(bool enabled)
-{
- RefPtr<nsScreenManagerGonk> screenManager = nsScreenManagerGonk::GetInstance();
- screenManager->DisplayEnabled(enabled);
-}
-
-} // namespace
-
-static uint32_t
-SurfaceFormatToColorDepth(int32_t aSurfaceFormat)
-{
- switch (aSurfaceFormat) {
- case GGL_PIXEL_FORMAT_RGB_565:
- return 16;
- case GGL_PIXEL_FORMAT_RGBA_8888:
- return 32;
- }
- return 24; // GGL_PIXEL_FORMAT_RGBX_8888
-}
-
-// nsScreenGonk.cpp
-
-nsScreenGonk::nsScreenGonk(uint32_t aId,
- GonkDisplay::DisplayType aDisplayType,
- const GonkDisplay::NativeData& aNativeData,
- NotifyDisplayChangedEvent aEventVisibility)
- : mId(aId)
- , mEventVisibility(aEventVisibility)
- , mNativeWindow(aNativeData.mNativeWindow)
- , mDpi(aNativeData.mXdpi)
- , mScreenRotation(nsIScreen::ROTATION_0_DEG)
- , mPhysicalScreenRotation(nsIScreen::ROTATION_0_DEG)
-#if ANDROID_VERSION >= 17
- , mDisplaySurface(aNativeData.mDisplaySurface)
-#endif
- , mIsMirroring(false)
- , mDisplayType(aDisplayType)
- , mEGLDisplay(EGL_NO_DISPLAY)
- , mEGLSurface(EGL_NO_SURFACE)
- , mGLContext(nullptr)
- , mFramebuffer(nullptr)
- , mMappedBuffer(nullptr)
-{
- if (mNativeWindow->query(mNativeWindow.get(), NATIVE_WINDOW_WIDTH, &mVirtualBounds.width) ||
- mNativeWindow->query(mNativeWindow.get(), NATIVE_WINDOW_HEIGHT, &mVirtualBounds.height) ||
- mNativeWindow->query(mNativeWindow.get(), NATIVE_WINDOW_FORMAT, &mSurfaceFormat)) {
- NS_RUNTIMEABORT("Failed to get native window size, aborting...");
- }
-
- mNaturalBounds = mVirtualBounds;
-
- if (IsPrimaryScreen()) {
- char propValue[PROPERTY_VALUE_MAX];
- property_get("ro.sf.hwrotation", propValue, "0");
- mPhysicalScreenRotation = atoi(propValue) / 90;
- }
-
- mColorDepth = SurfaceFormatToColorDepth(mSurfaceFormat);
-}
-
-static void
-ReleaseGLContextSync(mozilla::gl::GLContext* aGLContext)
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- aGLContext->Release();
-}
-
-nsScreenGonk::~nsScreenGonk()
-{
- // Release GLContext on compositor thread
- if (mGLContext) {
- CompositorThreadHolder::Loop()->PostTask(
- NewRunnableFunction(&ReleaseGLContextSync,
- mGLContext.forget().take()));
- mGLContext = nullptr;
- }
-}
-
-bool
-nsScreenGonk::IsPrimaryScreen()
-{
- return mDisplayType == GonkDisplay::DISPLAY_PRIMARY;
-}
-
-NS_IMETHODIMP
-nsScreenGonk::GetId(uint32_t *outId)
-{
- *outId = mId;
- return NS_OK;
-}
-
-uint32_t
-nsScreenGonk::GetId()
-{
- return mId;
-}
-
-NotifyDisplayChangedEvent
-nsScreenGonk::GetEventVisibility()
-{
- return mEventVisibility;
-}
-
-NS_IMETHODIMP
-nsScreenGonk::GetRect(int32_t *outLeft, int32_t *outTop,
- int32_t *outWidth, int32_t *outHeight)
-{
- *outLeft = mVirtualBounds.x;
- *outTop = mVirtualBounds.y;
-
- *outWidth = mVirtualBounds.width;
- *outHeight = mVirtualBounds.height;
-
- return NS_OK;
-}
-
-LayoutDeviceIntRect
-nsScreenGonk::GetRect()
-{
- return mVirtualBounds;
-}
-
-NS_IMETHODIMP
-nsScreenGonk::GetAvailRect(int32_t *outLeft, int32_t *outTop,
- int32_t *outWidth, int32_t *outHeight)
-{
- return GetRect(outLeft, outTop, outWidth, outHeight);
-}
-
-NS_IMETHODIMP
-nsScreenGonk::GetPixelDepth(int32_t *aPixelDepth)
-{
- // XXX: this should actually return 32 when we're using 24-bit
- // color, because we use RGBX.
- *aPixelDepth = mColorDepth;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsScreenGonk::GetColorDepth(int32_t *aColorDepth)
-{
- *aColorDepth = mColorDepth;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsScreenGonk::GetRotation(uint32_t* aRotation)
-{
- *aRotation = mScreenRotation;
- return NS_OK;
-}
-
-float
-nsScreenGonk::GetDpi()
-{
- return mDpi;
-}
-
-int32_t
-nsScreenGonk::GetSurfaceFormat()
-{
- return mSurfaceFormat;
-}
-
-ANativeWindow*
-nsScreenGonk::GetNativeWindow()
-{
- return mNativeWindow.get();
-}
-
-NS_IMETHODIMP
-nsScreenGonk::SetRotation(uint32_t aRotation)
-{
- if (!(aRotation <= ROTATION_270_DEG)) {
- return NS_ERROR_ILLEGAL_VALUE;
- }
-
- if (mScreenRotation == aRotation) {
- return NS_OK;
- }
-
- mScreenRotation = aRotation;
- uint32_t rotation = EffectiveScreenRotation();
- if (rotation == nsIScreen::ROTATION_90_DEG ||
- rotation == nsIScreen::ROTATION_270_DEG) {
- mVirtualBounds = LayoutDeviceIntRect(0, 0,
- mNaturalBounds.height,
- mNaturalBounds.width);
- } else {
- mVirtualBounds = mNaturalBounds;
- }
-
- nsAppShell::NotifyScreenRotation();
-
- for (unsigned int i = 0; i < mTopWindows.Length(); i++) {
- mTopWindows[i]->Resize(mVirtualBounds.width,
- mVirtualBounds.height,
- true);
- }
-
- return NS_OK;
-}
-
-LayoutDeviceIntRect
-nsScreenGonk::GetNaturalBounds()
-{
- return mNaturalBounds;
-}
-
-uint32_t
-nsScreenGonk::EffectiveScreenRotation()
-{
- return (mScreenRotation + mPhysicalScreenRotation) % (360 / 90);
-}
-
-// NB: This isn't gonk-specific, but gonk is the only widget backend
-// that does this calculation itself, currently.
-static ScreenOrientationInternal
-ComputeOrientation(uint32_t aRotation, const LayoutDeviceIntSize& aScreenSize)
-{
- bool naturallyPortrait = (aScreenSize.height > aScreenSize.width);
- switch (aRotation) {
- case nsIScreen::ROTATION_0_DEG:
- return (naturallyPortrait ? eScreenOrientation_PortraitPrimary :
- eScreenOrientation_LandscapePrimary);
- case nsIScreen::ROTATION_90_DEG:
- // Arbitrarily choosing 90deg to be primary "unnatural"
- // rotation.
- return (naturallyPortrait ? eScreenOrientation_LandscapePrimary :
- eScreenOrientation_PortraitPrimary);
- case nsIScreen::ROTATION_180_DEG:
- return (naturallyPortrait ? eScreenOrientation_PortraitSecondary :
- eScreenOrientation_LandscapeSecondary);
- case nsIScreen::ROTATION_270_DEG:
- return (naturallyPortrait ? eScreenOrientation_LandscapeSecondary :
- eScreenOrientation_PortraitSecondary);
- default:
- MOZ_CRASH("Gonk screen must always have a known rotation");
- }
-}
-
-static uint16_t
-RotationToAngle(uint32_t aRotation)
-{
- uint16_t angle = 90 * aRotation;
- MOZ_ASSERT(angle == 0 || angle == 90 || angle == 180 || angle == 270);
- return angle;
-}
-
-ScreenConfiguration
-nsScreenGonk::GetConfiguration()
-{
- ScreenOrientationInternal orientation =
- ComputeOrientation(mScreenRotation, mNaturalBounds.Size());
-
- // NB: perpetuating colorDepth == pixelDepth illusion here, for
- // consistency.
- return ScreenConfiguration(mVirtualBounds.ToUnknownRect(), orientation,
- RotationToAngle(mScreenRotation),
- mColorDepth, mColorDepth);
-}
-
-void
-nsScreenGonk::RegisterWindow(nsWindow* aWindow)
-{
- mTopWindows.AppendElement(aWindow);
-}
-
-void
-nsScreenGonk::UnregisterWindow(nsWindow* aWindow)
-{
- mTopWindows.RemoveElement(aWindow);
-}
-
-void
-nsScreenGonk::BringToTop(nsWindow* aWindow)
-{
- mTopWindows.RemoveElement(aWindow);
- mTopWindows.InsertElementAt(0, aWindow);
-}
-
-static gralloc_module_t const*
-gralloc_module()
-{
- hw_module_t const *module;
- if (hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module)) {
- return nullptr;
- }
- return reinterpret_cast<gralloc_module_t const*>(module);
-}
-
-static SurfaceFormat
-HalFormatToSurfaceFormat(int aHalFormat)
-{
- switch (aHalFormat) {
- case HAL_PIXEL_FORMAT_RGBA_8888:
- // Needs RB swap
- return SurfaceFormat::B8G8R8A8;
- case HAL_PIXEL_FORMAT_RGBX_8888:
- // Needs RB swap
- return SurfaceFormat::B8G8R8X8;
- case HAL_PIXEL_FORMAT_BGRA_8888:
- return SurfaceFormat::B8G8R8A8;
- case HAL_PIXEL_FORMAT_RGB_565:
- return SurfaceFormat::R5G6B5_UINT16;
- default:
- MOZ_CRASH("Unhandled HAL pixel format");
- return SurfaceFormat::UNKNOWN; // not reached
- }
-}
-
-static bool
-NeedsRBSwap(int aHalFormat)
-{
- switch (aHalFormat) {
- case HAL_PIXEL_FORMAT_RGBA_8888:
- return true;
- case HAL_PIXEL_FORMAT_RGBX_8888:
- return true;
- case HAL_PIXEL_FORMAT_BGRA_8888:
- return false;
- case HAL_PIXEL_FORMAT_RGB_565:
- return false;
- default:
- MOZ_CRASH("Unhandled HAL pixel format");
- return false; // not reached
- }
-}
-
-already_AddRefed<DrawTarget>
-nsScreenGonk::StartRemoteDrawing()
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- MOZ_ASSERT(!mFramebuffer);
- MOZ_ASSERT(!mMappedBuffer);
-
- mFramebuffer = DequeueBuffer();
- int width = mFramebuffer->width, height = mFramebuffer->height;
- if (gralloc_module()->lock(gralloc_module(), mFramebuffer->handle,
- GRALLOC_USAGE_SW_READ_NEVER |
- GRALLOC_USAGE_SW_WRITE_OFTEN |
- GRALLOC_USAGE_HW_FB,
- 0, 0, width, height,
- reinterpret_cast<void**>(&mMappedBuffer))) {
- EndRemoteDrawing();
- return nullptr;
- }
- SurfaceFormat format = HalFormatToSurfaceFormat(GetSurfaceFormat());
- mFramebufferTarget = Factory::CreateDrawTargetForData(
- BackendType::CAIRO,
- mMappedBuffer,
- IntSize(width, height),
- mFramebuffer->stride * gfx::BytesPerPixel(format),
- format);
- if (!mFramebufferTarget) {
- MOZ_CRASH("nsWindow::StartRemoteDrawing failed in CreateDrawTargetForData");
- }
- if (!mBackBuffer ||
- mBackBuffer->GetSize() != mFramebufferTarget->GetSize() ||
- mBackBuffer->GetFormat() != mFramebufferTarget->GetFormat()) {
- mBackBuffer = mFramebufferTarget->CreateSimilarDrawTarget(
- mFramebufferTarget->GetSize(), mFramebufferTarget->GetFormat());
- }
- RefPtr<DrawTarget> buffer(mBackBuffer);
- return buffer.forget();
-}
-
-void
-nsScreenGonk::EndRemoteDrawing()
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
-
- if (mFramebufferTarget && mFramebuffer) {
- IntSize size = mFramebufferTarget->GetSize();
- Rect rect(0, 0, size.width, size.height);
- RefPtr<SourceSurface> source = mBackBuffer->Snapshot();
- mFramebufferTarget->DrawSurface(source, rect, rect);
-
- // Convert from BGR to RGB
- // XXX this is a temporary solution. It consumes extra cpu cycles,
- // it should not be used on product device.
- if (NeedsRBSwap(GetSurfaceFormat())) {
- LOGE("Very slow composition path, it should not be used on product!!!");
- SurfaceFormat format = HalFormatToSurfaceFormat(GetSurfaceFormat());
- gfxUtils::ConvertBGRAtoRGBA(
- mMappedBuffer,
- mFramebuffer->stride * mFramebuffer->height * gfx::BytesPerPixel(format));
- }
- }
- if (mMappedBuffer) {
- MOZ_ASSERT(mFramebuffer);
- gralloc_module()->unlock(gralloc_module(), mFramebuffer->handle);
- mMappedBuffer = nullptr;
- }
- if (mFramebuffer) {
- QueueBuffer(mFramebuffer);
- }
- mFramebuffer = nullptr;
- mFramebufferTarget = nullptr;
-}
-
-ANativeWindowBuffer*
-nsScreenGonk::DequeueBuffer()
-{
- ANativeWindowBuffer* buf = nullptr;
-#if ANDROID_VERSION >= 17
- int fenceFd = -1;
- mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf, &fenceFd);
- android::sp<android::Fence> fence(new android::Fence(fenceFd));
-#if ANDROID_VERSION == 17
- fence->waitForever(1000, "nsScreenGonk_DequeueBuffer");
- // 1000 is what Android uses. It is a warning timeout in ms.
- // This timeout was removed in ANDROID_VERSION 18.
-#else
- fence->waitForever("nsScreenGonk_DequeueBuffer");
-#endif
-#else
- mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
-#endif
- return buf;
-}
-
-bool
-nsScreenGonk::QueueBuffer(ANativeWindowBuffer* buf)
-{
-#if ANDROID_VERSION >= 17
- int ret = mNativeWindow->queueBuffer(mNativeWindow.get(), buf, -1);
- return ret == 0;
-#else
- int ret = mNativeWindow->queueBuffer(mNativeWindow.get(), buf);
- return ret == 0;
-#endif
-}
-
-nsresult
-nsScreenGonk::MakeSnapshot(ANativeWindowBuffer* aBuffer)
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- MOZ_ASSERT(aBuffer);
-
- layers::CompositorBridgeParent* compositorParent = mCompositorBridgeParent;
- if (!compositorParent) {
- return NS_ERROR_FAILURE;
- }
-
- int width = aBuffer->width, height = aBuffer->height;
- uint8_t* mappedBuffer = nullptr;
- if (gralloc_module()->lock(gralloc_module(), aBuffer->handle,
- GRALLOC_USAGE_SW_READ_OFTEN |
- GRALLOC_USAGE_SW_WRITE_OFTEN,
- 0, 0, width, height,
- reinterpret_cast<void**>(&mappedBuffer))) {
- return NS_ERROR_FAILURE;
- }
-
- SurfaceFormat format = HalFormatToSurfaceFormat(GetSurfaceFormat());
- RefPtr<DrawTarget> mTarget =
- Factory::CreateDrawTargetForData(
- BackendType::CAIRO,
- mappedBuffer,
- IntSize(width, height),
- aBuffer->stride * gfx::BytesPerPixel(format),
- format);
- if (!mTarget) {
- return NS_ERROR_FAILURE;
- }
-
- gfx::IntRect rect = GetRect().ToUnknownRect();
- compositorParent->ForceComposeToTarget(mTarget, &rect);
-
- // Convert from BGR to RGB
- // XXX this is a temporary solution. It consumes extra cpu cycles,
- if (NeedsRBSwap(GetSurfaceFormat())) {
- LOGE("Slow path of making Snapshot!!!");
- SurfaceFormat format = HalFormatToSurfaceFormat(GetSurfaceFormat());
- gfxUtils::ConvertBGRAtoRGBA(
- mappedBuffer,
- aBuffer->stride * aBuffer->height * gfx::BytesPerPixel(format));
- mappedBuffer = nullptr;
- }
- gralloc_module()->unlock(gralloc_module(), aBuffer->handle);
- return NS_OK;
-}
-
-void
-nsScreenGonk::SetCompositorBridgeParent(layers::CompositorBridgeParent* aCompositorBridgeParent)
-{
- MOZ_ASSERT(NS_IsMainThread());
- mCompositorBridgeParent = aCompositorBridgeParent;
-}
-
-#if ANDROID_VERSION >= 17
-android::DisplaySurface*
-nsScreenGonk::GetDisplaySurface()
-{
- return mDisplaySurface.get();
-}
-
-int
-nsScreenGonk::GetPrevDispAcquireFd()
-{
- if (!mDisplaySurface.get()) {
- return -1;
- }
- return mDisplaySurface->GetPrevDispAcquireFd();
-}
-#endif
-
-GonkDisplay::DisplayType
-nsScreenGonk::GetDisplayType()
-{
- return mDisplayType;
-}
-
-void
-nsScreenGonk::SetEGLInfo(hwc_display_t aDisplay,
- hwc_surface_t aSurface,
- gl::GLContext* aGLContext)
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- mEGLDisplay = aDisplay;
- mEGLSurface = aSurface;
- mGLContext = aGLContext;
-}
-
-hwc_display_t
-nsScreenGonk::GetEGLDisplay()
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- return mEGLDisplay;
-}
-
-hwc_surface_t
-nsScreenGonk::GetEGLSurface()
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- return mEGLSurface;
-}
-
-already_AddRefed<mozilla::gl::GLContext>
-nsScreenGonk::GetGLContext()
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- RefPtr<mozilla::gl::GLContext>glContext = mGLContext;
- return glContext.forget();
-}
-
-static void
-UpdateMirroringWidgetSync(nsMainThreadPtrHandle<nsScreenGonk>&& aScreen, nsWindow* aWindow)
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- already_AddRefed<nsWindow> window(aWindow);
- aScreen->UpdateMirroringWidget(window);
-}
-
-bool
-nsScreenGonk::EnableMirroring()
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!IsPrimaryScreen());
-
- RefPtr<nsScreenGonk> primaryScreen = nsScreenManagerGonk::GetPrimaryScreen();
- NS_ENSURE_TRUE(primaryScreen, false);
-
- bool ret = primaryScreen->SetMirroringScreen(this);
- NS_ENSURE_TRUE(ret, false);
-
- // Create a widget for mirroring
- nsWidgetInitData initData;
- initData.mScreenId = mId;
- RefPtr<nsWindow> window = new nsWindow();
- nsresult rv = window->Create(nullptr, nullptr, mNaturalBounds, &initData);
- NS_ENSURE_SUCCESS(rv, false);
- MOZ_ASSERT(static_cast<nsWindow*>(window)->GetScreen() == this);
-
- // Update mMirroringWidget on compositor thread
- nsMainThreadPtrHandle<nsScreenGonk> primary =
- nsMainThreadPtrHandle<nsScreenGonk>(new nsMainThreadPtrHolder<nsScreenGonk>(primaryScreen, false));
- CompositorThreadHolder::Loop()->PostTask(
- NewRunnableFunction(&UpdateMirroringWidgetSync,
- primary,
- window.forget().take()));
-
- mIsMirroring = true;
- return true;
-}
-
-bool
-nsScreenGonk::DisableMirroring()
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(!IsPrimaryScreen());
-
- mIsMirroring = false;
- RefPtr<nsScreenGonk> primaryScreen = nsScreenManagerGonk::GetPrimaryScreen();
- NS_ENSURE_TRUE(primaryScreen, false);
-
- bool ret = primaryScreen->ClearMirroringScreen(this);
- NS_ENSURE_TRUE(ret, false);
-
- // Update mMirroringWidget on compositor thread
- nsMainThreadPtrHandle<nsScreenGonk> primary =
- nsMainThreadPtrHandle<nsScreenGonk>(new nsMainThreadPtrHolder<nsScreenGonk>(primaryScreen, false));
- CompositorThreadHolder::Loop()->PostTask(
- NewRunnableFunction(&UpdateMirroringWidgetSync,
- primary,
- nullptr));
- return true;
-}
-
-bool
-nsScreenGonk::SetMirroringScreen(nsScreenGonk* aScreen)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(IsPrimaryScreen());
-
- if (mMirroringScreen) {
- return false;
- }
- mMirroringScreen = aScreen;
- return true;
-}
-
-bool
-nsScreenGonk::ClearMirroringScreen(nsScreenGonk* aScreen)
-{
- MOZ_ASSERT(NS_IsMainThread());
- MOZ_ASSERT(IsPrimaryScreen());
-
- if (mMirroringScreen != aScreen) {
- return false;
- }
- mMirroringScreen = nullptr;
- return true;
-}
-
-void
-nsScreenGonk::UpdateMirroringWidget(already_AddRefed<nsWindow>& aWindow)
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- MOZ_ASSERT(IsPrimaryScreen());
-
- if (mMirroringWidget) {
- nsCOMPtr<nsIWidget> widget = mMirroringWidget.forget();
- NS_ReleaseOnMainThread(widget.forget());
- }
- mMirroringWidget = aWindow;
-}
-
-nsWindow*
-nsScreenGonk::GetMirroringWidget()
-{
- MOZ_ASSERT(CompositorThreadHolder::IsInCompositorThread());
- MOZ_ASSERT(IsPrimaryScreen());
-
- return mMirroringWidget;
-}
-
-NS_IMPL_ISUPPORTS(nsScreenManagerGonk, nsIScreenManager)
-
-nsScreenManagerGonk::nsScreenManagerGonk()
- : mInitialized(false)
-#if ANDROID_VERSION >= 19
- , mDisplayEnabled(false)
-#endif
-{
-}
-
-nsScreenManagerGonk::~nsScreenManagerGonk()
-{
-}
-
-static StaticRefPtr<nsScreenManagerGonk> sScreenManagerGonk;
-
-/* static */ already_AddRefed<nsScreenManagerGonk>
-nsScreenManagerGonk::GetInstance()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- // Avoid creating nsScreenManagerGonk from content process.
- if (!XRE_IsParentProcess()) {
- MOZ_CRASH("Non-chrome processes should not get here.");
- }
-
- // Avoid creating multiple nsScreenManagerGonk instance inside main process.
- if (!sScreenManagerGonk) {
- sScreenManagerGonk = new nsScreenManagerGonk();
- ClearOnShutdown(&sScreenManagerGonk);
- }
-
- RefPtr<nsScreenManagerGonk> screenMgr = sScreenManagerGonk.get();
- return screenMgr.forget();
-}
-
-/* static */ already_AddRefed< nsScreenGonk>
-nsScreenManagerGonk::GetPrimaryScreen()
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- RefPtr<nsScreenManagerGonk> manager = nsScreenManagerGonk::GetInstance();
- nsCOMPtr<nsIScreen> screen;
- manager->GetPrimaryScreen(getter_AddRefs(screen));
- MOZ_ASSERT(screen);
- return already_AddRefed<nsScreenGonk>(
- static_cast<nsScreenGonk*>(screen.forget().take()));
-}
-
-void
-nsScreenManagerGonk::Initialize()
-{
- if (mInitialized) {
- return;
- }
-
- mScreenOnEvent = new ScreenOnOffEvent(true);
- mScreenOffEvent = new ScreenOnOffEvent(false);
- GetGonkDisplay()->OnEnabled(displayEnabledCallback);
-
- AddScreen(GonkDisplay::DISPLAY_PRIMARY);
-
- nsAppShell::NotifyScreenInitialized();
- mInitialized = true;
-}
-
-void
-nsScreenManagerGonk::DisplayEnabled(bool aEnabled)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
-#if ANDROID_VERSION >= 19
- /* Bug 1244044
- * This function could be called before |mCompositorVsyncScheduler| is set.
- * To avoid this issue, keep the value stored in |mDisplayEnabled|.
- */
- mDisplayEnabled = aEnabled;
- if (mCompositorVsyncScheduler) {
- mCompositorVsyncScheduler->SetDisplay(mDisplayEnabled);
- }
-#endif
-
- VsyncControl(aEnabled);
- NS_DispatchToMainThread(aEnabled ? mScreenOnEvent : mScreenOffEvent);
-}
-
-NS_IMETHODIMP
-nsScreenManagerGonk::GetPrimaryScreen(nsIScreen **outScreen)
-{
- NS_IF_ADDREF(*outScreen = mScreens[0].get());
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsScreenManagerGonk::ScreenForId(uint32_t aId,
- nsIScreen **outScreen)
-{
- for (size_t i = 0; i < mScreens.Length(); i++) {
- if (mScreens[i]->GetId() == aId) {
- NS_IF_ADDREF(*outScreen = mScreens[i].get());
- return NS_OK;
- }
- }
-
- *outScreen = nullptr;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsScreenManagerGonk::ScreenForRect(int32_t inLeft,
- int32_t inTop,
- int32_t inWidth,
- int32_t inHeight,
- nsIScreen **outScreen)
-{
- // Since all screens have independent coordinate system, we could
- // only return the primary screen no matter what rect is given.
- return GetPrimaryScreen(outScreen);
-}
-
-NS_IMETHODIMP
-nsScreenManagerGonk::ScreenForNativeWidget(void *aWidget, nsIScreen **outScreen)
-{
- for (size_t i = 0; i < mScreens.Length(); i++) {
- if (aWidget == mScreens[i]->GetNativeWindow()) {
- NS_IF_ADDREF(*outScreen = mScreens[i].get());
- return NS_OK;
- }
- }
-
- *outScreen = nullptr;
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsScreenManagerGonk::GetNumberOfScreens(uint32_t *aNumberOfScreens)
-{
- *aNumberOfScreens = mScreens.Length();
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsScreenManagerGonk::GetSystemDefaultScale(float *aDefaultScale)
-{
- *aDefaultScale = 1.0f;
- return NS_OK;
-}
-
-void
-nsScreenManagerGonk::VsyncControl(bool aEnabled)
-{
- if (!NS_IsMainThread()) {
- NS_DispatchToMainThread(
- NewRunnableMethod<bool>(this,
- &nsScreenManagerGonk::VsyncControl,
- aEnabled));
- return;
- }
-
- MOZ_ASSERT(NS_IsMainThread());
- VsyncSource::Display &display = gfxPlatform::GetPlatform()->GetHardwareVsync()->GetGlobalDisplay();
- if (aEnabled) {
- display.EnableVsync();
- } else {
- display.DisableVsync();
- }
-}
-
-uint32_t
-nsScreenManagerGonk::GetIdFromType(GonkDisplay::DisplayType aDisplayType)
-{
- // This is the only place where we make the assumption that
- // display type is equivalent to screen id.
-
- // Bug 1138287 will address the conversion from type to id.
- return aDisplayType;
-}
-
-bool
-nsScreenManagerGonk::IsScreenConnected(uint32_t aId)
-{
- for (size_t i = 0; i < mScreens.Length(); ++i) {
- if (mScreens[i]->GetId() == aId) {
- return true;
- }
- }
-
- return false;
-}
-
-namespace {
-
-// A concrete class as a subject for 'display-changed' observer event.
-class DisplayInfo : public nsIDisplayInfo {
-public:
- NS_DECL_ISUPPORTS
-
- DisplayInfo(uint32_t aId, bool aConnected)
- : mId(aId)
- , mConnected(aConnected)
- {
- }
-
- NS_IMETHODIMP GetId(int32_t *aId)
- {
- *aId = mId;
- return NS_OK;
- }
-
- NS_IMETHODIMP GetConnected(bool *aConnected)
- {
- *aConnected = mConnected;
- return NS_OK;
- }
-
-private:
- virtual ~DisplayInfo() {}
-
- uint32_t mId;
- bool mConnected;
-};
-
-NS_IMPL_ISUPPORTS(DisplayInfo, nsIDisplayInfo, nsISupports)
-
-class NotifyTask : public mozilla::Runnable {
-public:
- NotifyTask(uint32_t aId, bool aConnected)
- : mDisplayInfo(new DisplayInfo(aId, aConnected))
- {
- }
-
- NS_IMETHOD Run() override
- {
- nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
- if (os) {
- os->NotifyObservers(mDisplayInfo, "display-changed", nullptr);
- }
-
- return NS_OK;
- }
-private:
- RefPtr<DisplayInfo> mDisplayInfo;
-};
-
-void
-NotifyDisplayChange(uint32_t aId, bool aConnected)
-{
- NS_DispatchToMainThread(new NotifyTask(aId, aConnected));
-}
-
-} // end of unnamed namespace.
-
-nsresult
-nsScreenManagerGonk::AddScreen(GonkDisplay::DisplayType aDisplayType,
- android::IGraphicBufferProducer* aSink,
- NotifyDisplayChangedEvent aEventVisibility)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- NS_ENSURE_TRUE(aDisplayType < GonkDisplay::DisplayType::NUM_DISPLAY_TYPES,
- NS_ERROR_FAILURE);
-
- uint32_t id = GetIdFromType(aDisplayType);
- NS_ENSURE_TRUE(!IsScreenConnected(id), NS_ERROR_FAILURE);
-
- GonkDisplay::NativeData nativeData =
- GetGonkDisplay()->GetNativeData(aDisplayType, aSink);
- nsScreenGonk* screen = new nsScreenGonk(id,
- aDisplayType,
- nativeData,
- aEventVisibility);
- mScreens.AppendElement(screen);
-
- if (aEventVisibility == NotifyDisplayChangedEvent::Observable) {
- NotifyDisplayChange(id, true);
- }
-
- // By default, non primary screen does mirroring.
- if (aDisplayType != GonkDisplay::DISPLAY_PRIMARY &&
- gfxPrefs::ScreenMirroringEnabled()) {
- screen->EnableMirroring();
- }
-
- return NS_OK;
-}
-
-nsresult
-nsScreenManagerGonk::RemoveScreen(GonkDisplay::DisplayType aDisplayType)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- NS_ENSURE_TRUE(aDisplayType < GonkDisplay::DisplayType::NUM_DISPLAY_TYPES,
- NS_ERROR_FAILURE);
-
- NotifyDisplayChangedEvent eventVisibility = NotifyDisplayChangedEvent::Observable;
- uint32_t screenId = GetIdFromType(aDisplayType);
- NS_ENSURE_TRUE(IsScreenConnected(screenId), NS_ERROR_FAILURE);
-
- for (size_t i = 0; i < mScreens.Length(); i++) {
- if (mScreens[i]->GetId() == screenId) {
- if (mScreens[i]->IsMirroring()) {
- mScreens[i]->DisableMirroring();
- }
- eventVisibility = mScreens[i]->GetEventVisibility();
- mScreens.RemoveElementAt(i);
- break;
- }
- }
-
- if (eventVisibility == NotifyDisplayChangedEvent::Observable) {
- NotifyDisplayChange(screenId, false);
- }
- return NS_OK;
-}
-
-#if ANDROID_VERSION >= 19
-void
-nsScreenManagerGonk::SetCompositorVsyncScheduler(mozilla::layers::CompositorVsyncScheduler *aObserver)
-{
- MOZ_ASSERT(NS_IsMainThread());
-
- // We assume on b2g that there is only 1 CompositorBridgeParent
- MOZ_ASSERT(mCompositorVsyncScheduler == nullptr);
- MOZ_ASSERT(aObserver);
- mCompositorVsyncScheduler = aObserver;
- mCompositorVsyncScheduler->SetDisplay(mDisplayEnabled);
-}
-#endif
diff --git a/widget/gonk/nsScreenManagerGonk.h b/widget/gonk/nsScreenManagerGonk.h
deleted file mode 100644
index 33ef5edb8..000000000
--- a/widget/gonk/nsScreenManagerGonk.h
+++ /dev/null
@@ -1,228 +0,0 @@
-/* -*- Mode: C++; tab-width: 40; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef nsScreenManagerGonk_h___
-#define nsScreenManagerGonk_h___
-
-#include "cutils/properties.h"
-#include "hardware/hwcomposer.h"
-
-#include "libdisplay/GonkDisplay.h"
-#include "mozilla/Atomics.h"
-#include "mozilla/Hal.h"
-#include "mozilla/Mutex.h"
-#include "nsBaseScreen.h"
-#include "nsCOMPtr.h"
-#include "nsIScreenManager.h"
-#include "nsProxyRelease.h"
-
-#include <android/native_window.h>
-
-class nsWindow;
-
-namespace android {
- class DisplaySurface;
- class IGraphicBufferProducer;
-};
-
-namespace mozilla {
- class Runnable;
-namespace gl {
- class GLContext;
-}
-namespace layers {
-class CompositorVsyncScheduler;
-class CompositorBridgeParent;
-}
-}
-
-enum class NotifyDisplayChangedEvent : int8_t {
- Observable,
- Suppressed
-};
-
-class nsScreenGonk : public nsBaseScreen
-{
- typedef mozilla::hal::ScreenConfiguration ScreenConfiguration;
- typedef mozilla::GonkDisplay GonkDisplay;
- typedef mozilla::LayoutDeviceIntRect LayoutDeviceIntRect;
- typedef mozilla::layers::CompositorBridgeParent CompositorBridgeParent;
- typedef mozilla::gfx::DrawTarget DrawTarget;
-
-public:
- nsScreenGonk(uint32_t aId,
- GonkDisplay::DisplayType aDisplayType,
- const GonkDisplay::NativeData& aNativeData,
- NotifyDisplayChangedEvent aEventVisibility);
-
- ~nsScreenGonk();
-
- NS_IMETHOD GetId(uint32_t* aId);
- NS_IMETHOD GetRect(int32_t* aLeft, int32_t* aTop, int32_t* aWidth, int32_t* aHeight);
- NS_IMETHOD GetAvailRect(int32_t* aLeft, int32_t* aTop, int32_t* aWidth, int32_t* aHeight);
- NS_IMETHOD GetPixelDepth(int32_t* aPixelDepth);
- NS_IMETHOD GetColorDepth(int32_t* aColorDepth);
- NS_IMETHOD GetRotation(uint32_t* aRotation);
- NS_IMETHOD SetRotation(uint32_t aRotation);
-
- uint32_t GetId();
- NotifyDisplayChangedEvent GetEventVisibility();
- LayoutDeviceIntRect GetRect();
- float GetDpi();
- int32_t GetSurfaceFormat();
- ANativeWindow* GetNativeWindow();
- LayoutDeviceIntRect GetNaturalBounds();
- uint32_t EffectiveScreenRotation();
- ScreenConfiguration GetConfiguration();
- bool IsPrimaryScreen();
-
- already_AddRefed<DrawTarget> StartRemoteDrawing();
- void EndRemoteDrawing();
-
- nsresult MakeSnapshot(ANativeWindowBuffer* aBuffer);
- void SetCompositorBridgeParent(CompositorBridgeParent* aCompositorBridgeParent);
-
-#if ANDROID_VERSION >= 17
- android::DisplaySurface* GetDisplaySurface();
- int GetPrevDispAcquireFd();
-#endif
- GonkDisplay::DisplayType GetDisplayType();
-
- void RegisterWindow(nsWindow* aWindow);
- void UnregisterWindow(nsWindow* aWindow);
- void BringToTop(nsWindow* aWindow);
-
- const nsTArray<nsWindow*>& GetTopWindows() const
- {
- return mTopWindows;
- }
-
- // Non-primary screen only
- bool EnableMirroring();
- bool DisableMirroring();
- bool IsMirroring()
- {
- return mIsMirroring;
- }
-
- // Primary screen only
- bool SetMirroringScreen(nsScreenGonk* aScreen);
- bool ClearMirroringScreen(nsScreenGonk* aScreen);
-
- // Called only on compositor thread
- void SetEGLInfo(hwc_display_t aDisplay, hwc_surface_t aSurface,
- mozilla::gl::GLContext* aGLContext);
- hwc_display_t GetEGLDisplay();
- hwc_surface_t GetEGLSurface();
- already_AddRefed<mozilla::gl::GLContext> GetGLContext();
- void UpdateMirroringWidget(already_AddRefed<nsWindow>& aWindow); // Primary screen only
- nsWindow* GetMirroringWidget(); // Primary screen only
-
-protected:
- ANativeWindowBuffer* DequeueBuffer();
- bool QueueBuffer(ANativeWindowBuffer* buf);
-
- uint32_t mId;
- NotifyDisplayChangedEvent mEventVisibility;
- int32_t mColorDepth;
- android::sp<ANativeWindow> mNativeWindow;
- float mDpi;
- int32_t mSurfaceFormat;
- LayoutDeviceIntRect mNaturalBounds; // Screen bounds w/o rotation taken into account.
- LayoutDeviceIntRect mVirtualBounds; // Screen bounds w/ rotation taken into account.
- uint32_t mScreenRotation;
- uint32_t mPhysicalScreenRotation;
- nsTArray<nsWindow*> mTopWindows;
-#if ANDROID_VERSION >= 17
- android::sp<android::DisplaySurface> mDisplaySurface;
-#endif
- bool mIsMirroring; // Non-primary screen only
- RefPtr<nsScreenGonk> mMirroringScreen; // Primary screen only
- mozilla::Atomic<CompositorBridgeParent*> mCompositorBridgeParent;
-
- // Accessed and updated only on compositor thread
- GonkDisplay::DisplayType mDisplayType;
- hwc_display_t mEGLDisplay;
- hwc_surface_t mEGLSurface;
- RefPtr<mozilla::gl::GLContext> mGLContext;
- RefPtr<nsWindow> mMirroringWidget; // Primary screen only
-
- // If we're using a BasicCompositor, these fields are temporarily
- // set during frame composition. They wrap the hardware
- // framebuffer.
- RefPtr<DrawTarget> mFramebufferTarget;
- ANativeWindowBuffer* mFramebuffer;
- /**
- * Points to a mapped gralloc buffer between calls to lock and unlock.
- * Should be null outside of the lock-unlock pair.
- */
- uint8_t* mMappedBuffer;
- // If we're using a BasicCompositor, this is our window back
- // buffer. The gralloc framebuffer driver expects us to draw the
- // entire framebuffer on every frame, but gecko expects the
- // windowing system to be tracking buffer updates for invalidated
- // regions. We get stuck holding that bag.
- //
- // Only accessed on the compositor thread, except during
- // destruction.
- RefPtr<DrawTarget> mBackBuffer;
-};
-
-class nsScreenManagerGonk final : public nsIScreenManager
-{
-public:
- typedef mozilla::GonkDisplay GonkDisplay;
-
-public:
- nsScreenManagerGonk();
-
- NS_DECL_ISUPPORTS
- NS_DECL_NSISCREENMANAGER
-
- static already_AddRefed<nsScreenManagerGonk> GetInstance();
- static already_AddRefed<nsScreenGonk> GetPrimaryScreen();
-
- void Initialize();
- void DisplayEnabled(bool aEnabled);
-
- nsresult AddScreen(GonkDisplay::DisplayType aDisplayType,
- android::IGraphicBufferProducer* aSink = nullptr,
- NotifyDisplayChangedEvent aEventVisibility = NotifyDisplayChangedEvent::Observable);
-
- nsresult RemoveScreen(GonkDisplay::DisplayType aDisplayType);
-
-#if ANDROID_VERSION >= 19
- void SetCompositorVsyncScheduler(mozilla::layers::CompositorVsyncScheduler* aObserver);
-#endif
-
-protected:
- ~nsScreenManagerGonk();
- void VsyncControl(bool aEnabled);
- uint32_t GetIdFromType(GonkDisplay::DisplayType aDisplayType);
- bool IsScreenConnected(uint32_t aId);
-
- bool mInitialized;
- nsTArray<RefPtr<nsScreenGonk>> mScreens;
- RefPtr<mozilla::Runnable> mScreenOnEvent;
- RefPtr<mozilla::Runnable> mScreenOffEvent;
-
-#if ANDROID_VERSION >= 19
- bool mDisplayEnabled;
- RefPtr<mozilla::layers::CompositorVsyncScheduler> mCompositorVsyncScheduler;
-#endif
-};
-
-#endif /* nsScreenManagerGonk_h___ */
diff --git a/widget/gonk/nsWidgetFactory.cpp b/widget/gonk/nsWidgetFactory.cpp
deleted file mode 100644
index 1c7525544..000000000
--- a/widget/gonk/nsWidgetFactory.cpp
+++ /dev/null
@@ -1,128 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "base/basictypes.h"
-
-#include "mozilla/ModuleUtils.h"
-#include "mozilla/WidgetUtils.h"
-
-#include "nsCOMPtr.h"
-#include "nsWidgetsCID.h"
-#include "nsAppShell.h"
-
-#include "nsWindow.h"
-#include "nsLookAndFeel.h"
-#include "nsAppShellSingleton.h"
-#include "nsScreenManagerGonk.h"
-#include "nsIdleServiceGonk.h"
-#include "nsTransferable.h"
-#include "nsClipboard.h"
-#include "nsClipboardHelper.h"
-
-#include "nsHTMLFormatConverter.h"
-#include "nsXULAppAPI.h"
-
-#include "PuppetWidget.h"
-
-using namespace mozilla::widget;
-
-// taken from android/nsWidgetFactory.cpp. GfxInfo is a legacy kludge, unfortunately
-// for the time being we still have to implement it on all platforms.
-#include "GfxInfo.h"
-namespace mozilla {
-namespace widget {
-// This constructor should really be shared with all platforms.
-NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(GfxInfo, Init)
-}
-}
-
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsWindow)
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsScreenManagerGonk, nsScreenManagerGonk::GetInstance)
-NS_GENERIC_FACTORY_CONSTRUCTOR(PuppetScreenManager)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsHTMLFormatConverter)
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIdleServiceGonk, nsIdleServiceGonk::GetInstance)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsTransferable)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboard)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboardHelper)
-
-NS_DEFINE_NAMED_CID(NS_APPSHELL_CID);
-NS_DEFINE_NAMED_CID(NS_WINDOW_CID);
-NS_DEFINE_NAMED_CID(NS_CHILD_CID);
-NS_DEFINE_NAMED_CID(NS_SCREENMANAGER_CID);
-NS_DEFINE_NAMED_CID(NS_HTMLFORMATCONVERTER_CID);
-NS_DEFINE_NAMED_CID(NS_IDLE_SERVICE_CID);
-NS_DEFINE_NAMED_CID(NS_TRANSFERABLE_CID);
-NS_DEFINE_NAMED_CID(NS_GFXINFO_CID);
-NS_DEFINE_NAMED_CID(NS_CLIPBOARD_CID);
-NS_DEFINE_NAMED_CID(NS_CLIPBOARDHELPER_CID);
-
-static nsresult
-ScreenManagerConstructor(nsISupports *aOuter, REFNSIID aIID, void **aResult)
-{
- return (XRE_IsParentProcess()) ?
- nsScreenManagerGonkConstructor(aOuter, aIID, aResult) :
- PuppetScreenManagerConstructor(aOuter, aIID, aResult);
-}
-
-static const mozilla::Module::CIDEntry kWidgetCIDs[] = {
- { &kNS_WINDOW_CID, false, nullptr, nsWindowConstructor },
- { &kNS_CHILD_CID, false, nullptr, nsWindowConstructor },
- { &kNS_APPSHELL_CID, false, nullptr, nsAppShellConstructor },
- { &kNS_SCREENMANAGER_CID, false, nullptr, ScreenManagerConstructor },
- { &kNS_HTMLFORMATCONVERTER_CID, false, nullptr, nsHTMLFormatConverterConstructor },
- { &kNS_IDLE_SERVICE_CID, false, nullptr, nsIdleServiceGonkConstructor },
- { &kNS_TRANSFERABLE_CID, false, nullptr, nsTransferableConstructor },
- { &kNS_GFXINFO_CID, false, nullptr, mozilla::widget::GfxInfoConstructor },
- { &kNS_CLIPBOARD_CID, false, nullptr, nsClipboardConstructor },
- { &kNS_CLIPBOARDHELPER_CID, false, nullptr, nsClipboardHelperConstructor },
- { nullptr }
-};
-
-static const mozilla::Module::ContractIDEntry kWidgetContracts[] = {
- { "@mozilla.org/widgets/window/gonk;1", &kNS_WINDOW_CID },
- { "@mozilla.org/widgets/child_window/gonk;1", &kNS_CHILD_CID },
- { "@mozilla.org/widget/appshell/gonk;1", &kNS_APPSHELL_CID },
- { "@mozilla.org/gfx/screenmanager;1", &kNS_SCREENMANAGER_CID },
- { "@mozilla.org/widget/htmlformatconverter;1", &kNS_HTMLFORMATCONVERTER_CID },
- { "@mozilla.org/widget/idleservice;1", &kNS_IDLE_SERVICE_CID },
- { "@mozilla.org/widget/transferable;1", &kNS_TRANSFERABLE_CID },
- { "@mozilla.org/gfx/info;1", &kNS_GFXINFO_CID },
- { "@mozilla.org/widget/clipboard;1", &kNS_CLIPBOARD_CID },
- { "@mozilla.org/widget/clipboardhelper;1", &kNS_CLIPBOARDHELPER_CID },
- { nullptr }
-};
-
-static void
-nsWidgetGonkModuleDtor()
-{
- // Shutdown all XP level widget classes.
- WidgetUtils::Shutdown();
-
- nsLookAndFeel::Shutdown();
- nsAppShellShutdown();
-}
-
-static const mozilla::Module kWidgetModule = {
- mozilla::Module::kVersion,
- kWidgetCIDs,
- kWidgetContracts,
- nullptr,
- nullptr,
- nsAppShellInit,
- nsWidgetGonkModuleDtor
-};
-
-NSMODULE_DEFN(nsWidgetGonkModule) = &kWidgetModule;
diff --git a/widget/gonk/nsWindow.cpp b/widget/gonk/nsWindow.cpp
deleted file mode 100644
index e11b7f233..000000000
--- a/widget/gonk/nsWindow.cpp
+++ /dev/null
@@ -1,744 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "nsWindow.h"
-
-#include "mozilla/DebugOnly.h"
-
-#include <fcntl.h>
-
-#include "android/log.h"
-#include "mozilla/dom/TabParent.h"
-#include "mozilla/Preferences.h"
-#include "mozilla/RefPtr.h"
-#include "mozilla/Services.h"
-#include "mozilla/FileUtils.h"
-#include "mozilla/ClearOnShutdown.h"
-#include "gfxContext.h"
-#include "gfxPlatform.h"
-#include "GLContextProvider.h"
-#include "GLContext.h"
-#include "GLContextEGL.h"
-#include "nsAppShell.h"
-#include "nsScreenManagerGonk.h"
-#include "nsTArray.h"
-#include "nsIWidgetListener.h"
-#include "ClientLayerManager.h"
-#include "BasicLayers.h"
-#include "libdisplay/GonkDisplay.h"
-#include "mozilla/TextEvents.h"
-#include "mozilla/gfx/2D.h"
-#include "mozilla/gfx/Logging.h"
-#include "mozilla/layers/APZCTreeManager.h"
-#include "mozilla/layers/APZThreadUtils.h"
-#include "mozilla/layers/CompositorBridgeParent.h"
-#include "mozilla/layers/CompositorThread.h"
-#include "mozilla/layers/CompositorSession.h"
-#include "mozilla/TouchEvents.h"
-#include "HwcComposer2D.h"
-
-#define LOG(args...) __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
-#define LOGW(args...) __android_log_print(ANDROID_LOG_WARN, "Gonk", ## args)
-#define LOGE(args...) __android_log_print(ANDROID_LOG_ERROR, "Gonk", ## args)
-
-#define IS_TOPLEVEL() (mWindowType == eWindowType_toplevel || mWindowType == eWindowType_dialog)
-
-using namespace mozilla;
-using namespace mozilla::dom;
-using namespace mozilla::hal;
-using namespace mozilla::gfx;
-using namespace mozilla::gl;
-using namespace mozilla::layers;
-using namespace mozilla::widget;
-
-static nsWindow *gFocusedWindow = nullptr;
-
-NS_IMPL_ISUPPORTS_INHERITED0(nsWindow, nsBaseWidget)
-
-nsWindow::nsWindow()
-{
- RefPtr<nsScreenManagerGonk> screenManager = nsScreenManagerGonk::GetInstance();
- screenManager->Initialize();
-
- // This is a hack to force initialization of the compositor
- // resources, if we're going to use omtc.
- //
- // NB: GetPlatform() will create the gfxPlatform, which wants
- // to know the color depth, which asks our native window.
- // This has to happen after other init has finished.
- gfxPlatform::GetPlatform();
- if (!ShouldUseOffMainThreadCompositing()) {
- MOZ_CRASH("How can we render apps, then?");
- }
-}
-
-nsWindow::~nsWindow()
-{
- if (mScreen->IsPrimaryScreen()) {
- mComposer2D->SetCompositorBridgeParent(nullptr);
- }
-}
-
-void
-nsWindow::DoDraw(void)
-{
- if (!hal::GetScreenEnabled()) {
- gDrawRequest = true;
- return;
- }
-
- RefPtr<nsScreenGonk> screen = nsScreenManagerGonk::GetPrimaryScreen();
- const nsTArray<nsWindow*>& windows = screen->GetTopWindows();
-
- if (windows.IsEmpty()) {
- LOG(" no window to draw, bailing");
- return;
- }
-
- RefPtr<nsWindow> targetWindow = (nsWindow *)windows[0];
- while (targetWindow->GetLastChild()) {
- targetWindow = (nsWindow *)targetWindow->GetLastChild();
- }
-
- nsIWidgetListener* listener = targetWindow->GetWidgetListener();
- if (listener) {
- listener->WillPaintWindow(targetWindow);
- }
-
- listener = targetWindow->GetWidgetListener();
- if (listener) {
- LayerManager* lm = targetWindow->GetLayerManager();
- if (mozilla::layers::LayersBackend::LAYERS_CLIENT == lm->GetBackendType()) {
- // No need to do anything, the compositor will handle drawing
- } else {
- NS_RUNTIMEABORT("Unexpected layer manager type");
- }
-
- listener->DidPaintWindow();
- }
-}
-
-void
-nsWindow::ConfigureAPZControllerThread()
-{
- APZThreadUtils::SetControllerThread(CompositorThreadHolder::Loop());
-}
-
-/*static*/ nsEventStatus
-nsWindow::DispatchKeyInput(WidgetKeyboardEvent& aEvent)
-{
- if (!gFocusedWindow) {
- return nsEventStatus_eIgnore;
- }
-
- gFocusedWindow->UserActivity();
-
- nsEventStatus status;
- aEvent.mWidget = gFocusedWindow;
- gFocusedWindow->DispatchEvent(&aEvent, status);
- return status;
-}
-
-/*static*/ void
-nsWindow::DispatchTouchInput(MultiTouchInput& aInput)
-{
- APZThreadUtils::AssertOnControllerThread();
-
- if (!gFocusedWindow) {
- return;
- }
-
- gFocusedWindow->DispatchTouchInputViaAPZ(aInput);
-}
-
-class DispatchTouchInputOnMainThread : public mozilla::Runnable
-{
-public:
- DispatchTouchInputOnMainThread(const MultiTouchInput& aInput,
- const ScrollableLayerGuid& aGuid,
- const uint64_t& aInputBlockId,
- nsEventStatus aApzResponse)
- : mInput(aInput)
- , mGuid(aGuid)
- , mInputBlockId(aInputBlockId)
- , mApzResponse(aApzResponse)
- {}
-
- NS_IMETHOD Run() override {
- if (gFocusedWindow) {
- gFocusedWindow->DispatchTouchEventForAPZ(mInput, mGuid, mInputBlockId, mApzResponse);
- }
- return NS_OK;
- }
-
-private:
- MultiTouchInput mInput;
- ScrollableLayerGuid mGuid;
- uint64_t mInputBlockId;
- nsEventStatus mApzResponse;
-};
-
-void
-nsWindow::DispatchTouchInputViaAPZ(MultiTouchInput& aInput)
-{
- APZThreadUtils::AssertOnControllerThread();
-
- if (!mAPZC) {
- // In general mAPZC should not be null, but during initial setup
- // it might be, so we handle that case by ignoring touch input there.
- return;
- }
-
- // First send it through the APZ code
- mozilla::layers::ScrollableLayerGuid guid;
- uint64_t inputBlockId;
- nsEventStatus result = mAPZC->ReceiveInputEvent(aInput, &guid, &inputBlockId);
- // If the APZ says to drop it, then we drop it
- if (result == nsEventStatus_eConsumeNoDefault) {
- return;
- }
-
- // Can't use NS_NewRunnableMethod because it only takes up to one arg and
- // we need more. Also we can't pass in |this| to the task because nsWindow
- // refcounting is not threadsafe. Instead we just use the gFocusedWindow
- // static ptr inside the task.
- NS_DispatchToMainThread(new DispatchTouchInputOnMainThread(
- aInput, guid, inputBlockId, result));
-}
-
-void
-nsWindow::DispatchTouchEventForAPZ(const MultiTouchInput& aInput,
- const ScrollableLayerGuid& aGuid,
- const uint64_t aInputBlockId,
- nsEventStatus aApzResponse)
-{
- MOZ_ASSERT(NS_IsMainThread());
- UserActivity();
-
- // Convert it to an event we can send to Gecko
- WidgetTouchEvent event = aInput.ToWidgetTouchEvent(this);
-
- // Dispatch the event into the gecko root process for "normal" flow.
- // The event might get sent to a child process,
- // but if it doesn't we need to notify the APZ of various things.
- // All of that happens in ProcessUntransformedAPZEvent
- ProcessUntransformedAPZEvent(&event, aGuid, aInputBlockId, aApzResponse);
-}
-
-class DispatchTouchInputOnControllerThread : public Runnable
-{
-public:
- DispatchTouchInputOnControllerThread(const MultiTouchInput& aInput)
- : mInput(aInput)
- {}
-
- NS_IMETHOD Run() override {
- if (gFocusedWindow) {
- gFocusedWindow->DispatchTouchInputViaAPZ(mInput);
- }
- return NS_OK;
- }
-
-private:
- MultiTouchInput mInput;
-};
-
-nsresult
-nsWindow::SynthesizeNativeTouchPoint(uint32_t aPointerId,
- TouchPointerState aPointerState,
- LayoutDeviceIntPoint aPoint,
- double aPointerPressure,
- uint32_t aPointerOrientation,
- nsIObserver* aObserver)
-{
- AutoObserverNotifier notifier(aObserver, "touchpoint");
-
- if (aPointerState == TOUCH_HOVER) {
- return NS_ERROR_UNEXPECTED;
- }
-
- if (!mSynthesizedTouchInput) {
- mSynthesizedTouchInput = MakeUnique<MultiTouchInput>();
- }
-
- // We should probably use a real timestamp here, but this is B2G and
- // so this probably never even exercised any more.
- uint32_t time = 0;
- TimeStamp timestamp = TimeStamp::FromSystemTime(time);
-
- MultiTouchInput inputToDispatch = UpdateSynthesizedTouchState(
- mSynthesizedTouchInput.get(), time, timestamp, aPointerId, aPointerState,
- aPoint, aPointerPressure, aPointerOrientation);
-
- // Can't use NewRunnableMethod here because that will pass a const-ref
- // argument to DispatchTouchInputViaAPZ whereas that function takes a
- // non-const ref. At this callsite we don't care about the mutations that
- // the function performs so this is fine. Also we can't pass |this| to the
- // task because nsWindow refcounting is not threadsafe. Instead we just use
- // the gFocusedWindow static ptr instead the task.
- APZThreadUtils::RunOnControllerThread(
- MakeAndAddRef<DispatchTouchInputOnControllerThread>(inputToDispatch));
-
- return NS_OK;
-}
-
-nsresult
-nsWindow::Create(nsIWidget* aParent,
- void* aNativeParent,
- const LayoutDeviceIntRect& aRect,
- nsWidgetInitData* aInitData)
-{
- BaseCreate(aParent, aInitData);
-
- nsCOMPtr<nsIScreen> screen;
-
- uint32_t screenId = aParent ? ((nsWindow*)aParent)->mScreen->GetId() :
- aInitData->mScreenId;
-
- RefPtr<nsScreenManagerGonk> screenManager = nsScreenManagerGonk::GetInstance();
- screenManager->ScreenForId(screenId, getter_AddRefs(screen));
-
- mScreen = static_cast<nsScreenGonk*>(screen.get());
-
- mBounds = aRect;
-
- mParent = (nsWindow *)aParent;
- mVisible = false;
-
- if (!aParent) {
- mBounds = mScreen->GetRect();
- }
-
- mComposer2D = HwcComposer2D::GetInstance();
-
- if (!IS_TOPLEVEL()) {
- return NS_OK;
- }
-
- mScreen->RegisterWindow(this);
-
- Resize(0, 0, mBounds.width, mBounds.height, false);
-
- return NS_OK;
-}
-
-void
-nsWindow::Destroy()
-{
- mOnDestroyCalled = true;
- mScreen->UnregisterWindow(this);
- if (this == gFocusedWindow) {
- gFocusedWindow = nullptr;
- }
- nsBaseWidget::OnDestroy();
-}
-
-NS_IMETHODIMP
-nsWindow::Show(bool aState)
-{
- if (mWindowType == eWindowType_invisible) {
- return NS_OK;
- }
-
- if (mVisible == aState) {
- return NS_OK;
- }
-
- mVisible = aState;
- if (!IS_TOPLEVEL()) {
- return mParent ? mParent->Show(aState) : NS_OK;
- }
-
- if (aState) {
- BringToTop();
- } else {
- const nsTArray<nsWindow*>& windows =
- mScreen->GetTopWindows();
- for (unsigned int i = 0; i < windows.Length(); i++) {
- nsWindow *win = windows[i];
- if (!win->mVisible) {
- continue;
- }
- win->BringToTop();
- break;
- }
- }
-
- return NS_OK;
-}
-
-bool
-nsWindow::IsVisible() const
-{
- return mVisible;
-}
-
-NS_IMETHODIMP
-nsWindow::Move(double aX,
- double aY)
-{
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::Resize(double aWidth,
- double aHeight,
- bool aRepaint)
-{
- return Resize(0, 0, aWidth, aHeight, aRepaint);
-}
-
-NS_IMETHODIMP
-nsWindow::Resize(double aX,
- double aY,
- double aWidth,
- double aHeight,
- bool aRepaint)
-{
- mBounds = LayoutDeviceIntRect(NSToIntRound(aX), NSToIntRound(aY),
- NSToIntRound(aWidth), NSToIntRound(aHeight));
- if (mWidgetListener) {
- mWidgetListener->WindowResized(this, mBounds.width, mBounds.height);
- }
-
- if (aRepaint) {
- Invalidate(mBounds);
- }
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::Enable(bool aState)
-{
- return NS_OK;
-}
-
-bool
-nsWindow::IsEnabled() const
-{
- return true;
-}
-
-NS_IMETHODIMP
-nsWindow::SetFocus(bool aRaise)
-{
- if (aRaise) {
- BringToTop();
- }
-
- if (!IS_TOPLEVEL() && mScreen->IsPrimaryScreen()) {
- // We should only set focused window on non-toplevel primary window.
- gFocusedWindow = this;
- }
-
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::ConfigureChildren(const nsTArray<nsIWidget::Configuration>&)
-{
- return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::Invalidate(const LayoutDeviceIntRect& aRect)
-{
- nsWindow *top = mParent;
- while (top && top->mParent) {
- top = top->mParent;
- }
- const nsTArray<nsWindow*>& windows = mScreen->GetTopWindows();
- if (top != windows[0] && this != windows[0]) {
- return NS_OK;
- }
-
- gDrawRequest = true;
- mozilla::NotifyEvent();
- return NS_OK;
-}
-
-LayoutDeviceIntPoint
-nsWindow::WidgetToScreenOffset()
-{
- LayoutDeviceIntPoint p(0, 0);
- nsWindow *w = this;
-
- while (w && w->mParent) {
- p.x += w->mBounds.x;
- p.y += w->mBounds.y;
-
- w = w->mParent;
- }
-
- return p;
-}
-
-void*
-nsWindow::GetNativeData(uint32_t aDataType)
-{
- switch (aDataType) {
- case NS_NATIVE_WINDOW:
- // Called before primary display's EGLSurface creation.
- return mScreen->GetNativeWindow();
- case NS_NATIVE_OPENGL_CONTEXT:
- return mScreen->GetGLContext().take();
- case NS_RAW_NATIVE_IME_CONTEXT: {
- void* pseudoIMEContext = GetPseudoIMEContext();
- if (pseudoIMEContext) {
- return pseudoIMEContext;
- }
- // There is only one IME context on Gonk.
- return NS_ONLY_ONE_NATIVE_IME_CONTEXT;
- }
- }
-
- return nullptr;
-}
-
-void
-nsWindow::SetNativeData(uint32_t aDataType, uintptr_t aVal)
-{
- switch (aDataType) {
- case NS_NATIVE_OPENGL_CONTEXT:
- GLContext* context = reinterpret_cast<GLContext*>(aVal);
- if (!context) {
- mScreen->SetEGLInfo(EGL_NO_DISPLAY,
- EGL_NO_SURFACE,
- nullptr);
- return;
- }
- mScreen->SetEGLInfo(GLContextEGL::Cast(context)->GetEGLDisplay(),
- GLContextEGL::Cast(context)->GetEGLSurface(),
- context);
- return;
- }
-}
-
-NS_IMETHODIMP
-nsWindow::DispatchEvent(WidgetGUIEvent* aEvent, nsEventStatus& aStatus)
-{
- if (mWidgetListener) {
- aStatus = mWidgetListener->HandleEvent(aEvent, mUseAttachedEvents);
- }
- return NS_OK;
-}
-
-NS_IMETHODIMP_(void)
-nsWindow::SetInputContext(const InputContext& aContext,
- const InputContextAction& aAction)
-{
- mInputContext = aContext;
-}
-
-NS_IMETHODIMP_(InputContext)
-nsWindow::GetInputContext()
-{
- return mInputContext;
-}
-
-nsresult
-nsWindow::MakeFullScreen(bool aFullScreen, nsIScreen*)
-{
- if (mWindowType != eWindowType_toplevel) {
- // Ignore fullscreen request for non-toplevel windows.
- NS_WARNING("MakeFullScreen() on a dialog or child widget?");
- nsBaseWidget::InfallibleMakeFullScreen(aFullScreen);
- return NS_OK;
- }
-
- if (aFullScreen) {
- // Fullscreen is "sticky" for toplevel widgets on gonk: we
- // must paint the entire screen, and should only have one
- // toplevel widget, so it doesn't make sense to ever "exit"
- // fullscreen. If we do, we can leave parts of the screen
- // unpainted.
- nsIntRect virtualBounds;
- mScreen->GetRect(&virtualBounds.x, &virtualBounds.y,
- &virtualBounds.width, &virtualBounds.height);
- Resize(virtualBounds.x, virtualBounds.y,
- virtualBounds.width, virtualBounds.height,
- /*repaint*/true);
- }
-
- if (nsIWidgetListener* listener = GetWidgetListener()) {
- listener->FullscreenChanged(aFullScreen);
- }
- return NS_OK;
-}
-
-already_AddRefed<DrawTarget>
-nsWindow::StartRemoteDrawing()
-{
- RefPtr<DrawTarget> buffer = mScreen->StartRemoteDrawing();
- return buffer.forget();
-}
-
-void
-nsWindow::EndRemoteDrawing()
-{
- mScreen->EndRemoteDrawing();
-}
-
-float
-nsWindow::GetDPI()
-{
- return mScreen->GetDpi();
-}
-
-double
-nsWindow::GetDefaultScaleInternal()
-{
- float dpi = GetDPI();
- // The mean pixel density for mdpi devices is 160dpi, 240dpi for hdpi,
- // and 320dpi for xhdpi, respectively.
- // We'll take the mid-value between these three numbers as the boundary.
- if (dpi < 200.0) {
- return 1.0; // mdpi devices.
- }
- if (dpi < 280.0) {
- return 1.5; // hdpi devices.
- }
- // xhdpi devices and beyond.
- return floor(dpi / 150.0 + 0.5);
-}
-
-LayerManager *
-nsWindow::GetLayerManager(PLayerTransactionChild* aShadowManager,
- LayersBackend aBackendHint,
- LayerManagerPersistence aPersistence)
-{
- if (mLayerManager) {
- // This layer manager might be used for painting outside of DoDraw(), so we need
- // to set the correct rotation on it.
- if (ClientLayerManager* manager = mLayerManager->AsClientLayerManager()) {
- uint32_t rotation = mScreen->EffectiveScreenRotation();
- manager->SetDefaultTargetConfiguration(mozilla::layers::BufferMode::BUFFER_NONE,
- ScreenRotation(rotation));
- }
- return mLayerManager;
- }
-
- const nsTArray<nsWindow*>& windows = mScreen->GetTopWindows();
- nsWindow *topWindow = windows[0];
-
- if (!topWindow) {
- LOGW(" -- no topwindow\n");
- return nullptr;
- }
-
- CreateCompositor();
- if (RefPtr<CompositorBridgeParent> bridge = GetCompositorBridgeParent()) {
- mScreen->SetCompositorBridgeParent(bridge);
- if (mScreen->IsPrimaryScreen()) {
- mComposer2D->SetCompositorBridgeParent(bridge);
- }
- }
- MOZ_ASSERT(mLayerManager);
- return mLayerManager;
-}
-
-void
-nsWindow::DestroyCompositor()
-{
- if (RefPtr<CompositorBridgeParent> bridge = GetCompositorBridgeParent()) {
- mScreen->SetCompositorBridgeParent(nullptr);
- if (mScreen->IsPrimaryScreen()) {
- // Unset CompositorBridgeParent
- mComposer2D->SetCompositorBridgeParent(nullptr);
- }
- }
- nsBaseWidget::DestroyCompositor();
-}
-
-void
-nsWindow::BringToTop()
-{
- const nsTArray<nsWindow*>& windows = mScreen->GetTopWindows();
- if (!windows.IsEmpty()) {
- if (nsIWidgetListener* listener = windows[0]->GetWidgetListener()) {
- listener->WindowDeactivated();
- }
- }
-
- mScreen->BringToTop(this);
-
- if (mWidgetListener) {
- mWidgetListener->WindowActivated();
- }
-
- Invalidate(mBounds);
-}
-
-void
-nsWindow::UserActivity()
-{
- if (!mIdleService) {
- mIdleService = do_GetService("@mozilla.org/widget/idleservice;1");
- }
-
- if (mIdleService) {
- mIdleService->ResetIdleTimeOut(0);
- }
-}
-
-uint32_t
-nsWindow::GetGLFrameBufferFormat()
-{
- if (mLayerManager &&
- mLayerManager->GetBackendType() == mozilla::layers::LayersBackend::LAYERS_OPENGL) {
- // We directly map the hardware fb on Gonk. The hardware fb
- // has RGB format.
- return LOCAL_GL_RGB;
- }
- return LOCAL_GL_NONE;
-}
-
-LayoutDeviceIntRect
-nsWindow::GetNaturalBounds()
-{
- return mScreen->GetNaturalBounds();
-}
-
-nsScreenGonk*
-nsWindow::GetScreen()
-{
- return mScreen;
-}
-
-bool
-nsWindow::NeedsPaint()
-{
- if (!mLayerManager) {
- return false;
- }
- return nsIWidget::NeedsPaint();
-}
-
-Composer2D*
-nsWindow::GetComposer2D()
-{
- if (mScreen->GetDisplayType() == GonkDisplay::DISPLAY_VIRTUAL) {
- return nullptr;
- }
-
- return mComposer2D;
-}
-
-CompositorBridgeParent*
-nsWindow::GetCompositorBridgeParent() const
-{
- return mCompositorSession ? mCompositorSession->GetInProcessBridge() : nullptr;
-}
diff --git a/widget/gonk/nsWindow.h b/widget/gonk/nsWindow.h
deleted file mode 100644
index 6106982f9..000000000
--- a/widget/gonk/nsWindow.h
+++ /dev/null
@@ -1,154 +0,0 @@
-/* Copyright 2012 Mozilla Foundation and Mozilla contributors
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef nsWindow_h
-#define nsWindow_h
-
-#include "InputData.h"
-#include "mozilla/UniquePtr.h"
-#include "nsBaseWidget.h"
-#include "nsRegion.h"
-#include "nsIIdleServiceInternal.h"
-#include "Units.h"
-
-class ANativeWindowBuffer;
-
-namespace widget {
-struct InputContext;
-struct InputContextAction;
-}
-
-namespace mozilla {
-class HwcComposer2D;
-}
-
-class nsScreenGonk;
-
-class nsWindow : public nsBaseWidget
-{
-public:
- nsWindow();
-
- NS_DECL_ISUPPORTS_INHERITED
-
- static void DoDraw(void);
- static nsEventStatus DispatchKeyInput(mozilla::WidgetKeyboardEvent& aEvent);
- static void DispatchTouchInput(mozilla::MultiTouchInput& aInput);
-
- using nsBaseWidget::Create; // for Create signature not overridden here
- virtual MOZ_MUST_USE nsresult Create(nsIWidget* aParent,
- void* aNativeParent,
- const LayoutDeviceIntRect& aRect,
- nsWidgetInitData* aInitData) override;
- virtual void Destroy();
-
- NS_IMETHOD Show(bool aState);
- virtual bool IsVisible() const;
- NS_IMETHOD Move(double aX,
- double aY);
- NS_IMETHOD Resize(double aWidth,
- double aHeight,
- bool aRepaint);
- NS_IMETHOD Resize(double aX,
- double aY,
- double aWidth,
- double aHeight,
- bool aRepaint);
- NS_IMETHOD Enable(bool aState);
- virtual bool IsEnabled() const;
- NS_IMETHOD SetFocus(bool aRaise = false);
- NS_IMETHOD ConfigureChildren(const nsTArray<nsIWidget::Configuration>&);
- NS_IMETHOD Invalidate(const LayoutDeviceIntRect& aRect);
- virtual void* GetNativeData(uint32_t aDataType);
- virtual void SetNativeData(uint32_t aDataType, uintptr_t aVal);
- NS_IMETHOD SetTitle(const nsAString& aTitle)
- {
- return NS_OK;
- }
- virtual LayoutDeviceIntPoint WidgetToScreenOffset();
- void DispatchTouchInputViaAPZ(mozilla::MultiTouchInput& aInput);
- void DispatchTouchEventForAPZ(const mozilla::MultiTouchInput& aInput,
- const ScrollableLayerGuid& aGuid,
- const uint64_t aInputBlockId,
- nsEventStatus aApzResponse);
- NS_IMETHOD DispatchEvent(mozilla::WidgetGUIEvent* aEvent,
- nsEventStatus& aStatus);
- virtual nsresult SynthesizeNativeTouchPoint(uint32_t aPointerId,
- TouchPointerState aPointerState,
- LayoutDeviceIntPoint aPoint,
- double aPointerPressure,
- uint32_t aPointerOrientation,
- nsIObserver* aObserver) override;
-
- virtual nsresult MakeFullScreen(
- bool aFullScreen, nsIScreen* aTargetScreen = nullptr) override;
-
- virtual already_AddRefed<mozilla::gfx::DrawTarget>
- StartRemoteDrawing() override;
- virtual void EndRemoteDrawing() override;
-
- virtual float GetDPI();
- virtual double GetDefaultScaleInternal();
- virtual mozilla::layers::LayerManager*
- GetLayerManager(PLayerTransactionChild* aShadowManager = nullptr,
- LayersBackend aBackendHint = mozilla::layers::LayersBackend::LAYERS_NONE,
- LayerManagerPersistence aPersistence = LAYER_MANAGER_CURRENT);
- virtual void DestroyCompositor();
-
- NS_IMETHOD_(void) SetInputContext(const InputContext& aContext,
- const InputContextAction& aAction);
- NS_IMETHOD_(InputContext) GetInputContext();
-
- virtual uint32_t GetGLFrameBufferFormat() override;
-
- virtual LayoutDeviceIntRect GetNaturalBounds() override;
- virtual bool NeedsPaint();
-
- virtual Composer2D* GetComposer2D() override;
-
- void ConfigureAPZControllerThread() override;
-
- nsScreenGonk* GetScreen();
-
-protected:
- nsWindow* mParent;
- bool mVisible;
- InputContext mInputContext;
- nsCOMPtr<nsIIdleServiceInternal> mIdleService;
-
- virtual ~nsWindow();
-
- void BringToTop();
-
- // Call this function when the users activity is the direct cause of an
- // event (like a keypress or mouse click).
- void UserActivity();
-
- bool UseExternalCompositingSurface() const override {
- return true;
- }
- CompositorBridgeParent* GetCompositorBridgeParent() const;
-
-private:
- // This is used by SynthesizeNativeTouchPoint to maintain state between
- // multiple synthesized points
- mozilla::UniquePtr<mozilla::MultiTouchInput> mSynthesizedTouchInput;
-
- RefPtr<nsScreenGonk> mScreen;
-
- RefPtr<mozilla::HwcComposer2D> mComposer2D;
-};
-
-#endif /* nsWindow_h */
diff --git a/widget/moz.build b/widget/moz.build
index f69f2d87c..b156346eb 100644
--- a/widget/moz.build
+++ b/widget/moz.build
@@ -6,9 +6,9 @@
toolkit = CONFIG['MOZ_WIDGET_TOOLKIT']
-if toolkit in ('cocoa', 'android', 'gonk', 'uikit'):
+if toolkit in ('cocoa', 'android', 'uikit'):
DIRS += [toolkit]
-if toolkit in ('android', 'gonk', 'gtk2', 'gtk3'):
+if toolkit in ('android', 'gtk2', 'gtk3'):
EXPORTS += ['nsIPrintDialogService.h']
if toolkit == 'windows':
@@ -222,7 +222,7 @@ if toolkit in ('cocoa', 'windows'):
]
if toolkit in {'gtk2', 'gtk3', 'cocoa', 'windows',
- 'android', 'gonk', 'uikit'}:
+ 'android', 'uikit'}:
UNIFIED_SOURCES += [
'nsBaseFilePicker.cpp',
]
@@ -236,8 +236,7 @@ if toolkit == 'gtk3':
'nsIApplicationChooser.idl',
]
-if not CONFIG['MOZ_B2G']:
- DEFINES['MOZ_CROSS_PROCESS_IME'] = True
+DEFINES['MOZ_CROSS_PROCESS_IME'] = True
include('/ipc/chromium/chromium-config.mozbuild')
diff --git a/widget/nsBaseWidget.cpp b/widget/nsBaseWidget.cpp
index b820fed3c..909660f71 100644
--- a/widget/nsBaseWidget.cpp
+++ b/widget/nsBaseWidget.cpp
@@ -3086,6 +3086,7 @@ case _value: eventName.AssignLiteral(_name) ; break
_ASSIGN_eventName(eMouseDown,"eMouseDown");
_ASSIGN_eventName(eMouseUp,"eMouseUp");
_ASSIGN_eventName(eMouseClick,"eMouseClick");
+ _ASSIGN_eventName(eMouseAuxClick,"eMouseAuxClick");
_ASSIGN_eventName(eMouseDoubleClick,"eMouseDoubleClick");
_ASSIGN_eventName(eMouseMove,"eMouseMove");
_ASSIGN_eventName(eLoad,"eLoad");
diff --git a/widget/nsContentProcessWidgetFactory.cpp b/widget/nsContentProcessWidgetFactory.cpp
index 2f00f1c83..7430721f2 100644
--- a/widget/nsContentProcessWidgetFactory.cpp
+++ b/widget/nsContentProcessWidgetFactory.cpp
@@ -17,8 +17,6 @@
using namespace mozilla;
using namespace mozilla::widget;
-#ifndef MOZ_WIDGET_GONK
-
NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboardProxy)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsColorPickerProxy)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsDragServiceProxy)
@@ -68,4 +66,3 @@ static const mozilla::Module kWidgetModule = {
NSMODULE_DEFN(nsContentProcessWidgetModule) = &kWidgetModule;
-#endif /* MOZ_WIDGET_GONK */
diff --git a/widget/tests/TestAppShellSteadyState.cpp b/widget/tests/TestAppShellSteadyState.cpp
index 03888fc0a..162343e38 100644
--- a/widget/tests/TestAppShellSteadyState.cpp
+++ b/widget/tests/TestAppShellSteadyState.cpp
@@ -310,7 +310,7 @@ already_AddRefed<nsIAppShell>
GetAppShell()
{
static const char* platforms[] = {
- "android", "mac", "gonk", "gtk", "qt", "win"
+ "android", "mac", "gtk", "qt", "win"
};
NS_NAMED_LITERAL_CSTRING(contractPrefix, "@mozilla.org/widget/appshell/");
diff --git a/widget/windows/WinUtils.cpp b/widget/windows/WinUtils.cpp
index 0a57ad439..bd42e78f6 100644
--- a/widget/windows/WinUtils.cpp
+++ b/widget/windows/WinUtils.cpp
@@ -1138,7 +1138,8 @@ WinUtils::GetIsMouseFromTouch(EventMessage aEventMessage)
const uint32_t MOZ_T_I_SIGNATURE = TABLET_INK_TOUCH | TABLET_INK_SIGNATURE;
const uint32_t MOZ_T_I_CHECK_TCH = TABLET_INK_TOUCH | TABLET_INK_CHECK;
return ((aEventMessage == eMouseMove || aEventMessage == eMouseDown ||
- aEventMessage == eMouseUp || aEventMessage == eMouseDoubleClick) &&
+ aEventMessage == eMouseUp || aEventMessage == eMouseAuxClick ||
+ aEventMessage == eMouseDoubleClick) &&
(GetMessageExtraInfo() & MOZ_T_I_SIGNATURE) == MOZ_T_I_CHECK_TCH);
}
diff --git a/xpcom/base/nsMemoryReporterManager.cpp b/xpcom/base/nsMemoryReporterManager.cpp
index aa3d74dfd..7c62e2af5 100644
--- a/xpcom/base/nsMemoryReporterManager.cpp
+++ b/xpcom/base/nsMemoryReporterManager.cpp
@@ -439,13 +439,11 @@ static MOZ_MUST_USE nsresult
ResidentDistinguishedAmountHelper(int64_t* aN, bool aDoPurge)
{
#ifdef HAVE_JEMALLOC_STATS
-#ifndef MOZ_JEMALLOC4
if (aDoPurge) {
Telemetry::AutoTimer<Telemetry::MEMORY_FREE_PURGED_PAGES_MS> timer;
jemalloc_purge_freed_pages();
}
#endif
-#endif
task_basic_info ti;
if (!GetTaskBasicInfo(&ti)) {
@@ -1598,10 +1596,6 @@ nsMemoryReporterManager::~nsMemoryReporterManager()
NS_ASSERTION(!mSavedWeakReporters, "failed to restore weak reporters");
}
-#ifdef MOZ_WIDGET_GONK
-#define DEBUG_CHILD_PROCESS_MEMORY_REPORTING 1
-#endif
-
#ifdef DEBUG_CHILD_PROCESS_MEMORY_REPORTING
#define MEMORY_REPORTING_LOG(format, ...) \
printf_stderr("++++ MEMORY REPORTING: " format, ##__VA_ARGS__);
diff --git a/xpcom/base/nsSystemInfo.cpp b/xpcom/base/nsSystemInfo.cpp
index f6d9fd5ad..4a92a2eb4 100644
--- a/xpcom/base/nsSystemInfo.cpp
+++ b/xpcom/base/nsSystemInfo.cpp
@@ -50,12 +50,6 @@
#include "mozilla/dom/ContentChild.h"
#endif
-#ifdef MOZ_WIDGET_GONK
-#include <sys/system_properties.h>
-#include "mozilla/Preferences.h"
-#include "nsPrintfCString.h"
-#endif
-
#ifdef ANDROID
extern "C" {
NS_EXPORT int android_sdk_version;
@@ -66,10 +60,6 @@ NS_EXPORT int android_sdk_version;
#include <sys/sysctl.h>
#endif
-#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
-#include "mozilla/SandboxInfo.h"
-#endif
-
// Slot for NS_InitXPCOM2 to pass information to nsSystemInfo::Init.
// Only set to nonzero (potentially) if XP_UNIX. On such systems, the
// system call to discover the appropriate value is not thread-safe,
@@ -751,67 +741,6 @@ nsSystemInfo::Init()
}
#endif
-#ifdef MOZ_WIDGET_GONK
- char sdk[PROP_VALUE_MAX];
- if (__system_property_get("ro.build.version.sdk", sdk)) {
- android_sdk_version = atoi(sdk);
- SetPropertyAsInt32(NS_LITERAL_STRING("sdk_version"), android_sdk_version);
-
- SetPropertyAsACString(NS_LITERAL_STRING("secondaryLibrary"),
- nsPrintfCString("SDK %u", android_sdk_version));
- }
-
- char characteristics[PROP_VALUE_MAX];
- if (__system_property_get("ro.build.characteristics", characteristics)) {
- if (!strcmp(characteristics, "tablet")) {
- SetPropertyAsBool(NS_LITERAL_STRING("tablet"), true);
- } else if (!strcmp(characteristics, "tv")) {
- SetPropertyAsBool(NS_LITERAL_STRING("tv"), true);
- }
- }
-
- nsAutoString str;
- rv = GetPropertyAsAString(NS_LITERAL_STRING("version"), str);
- if (NS_SUCCEEDED(rv)) {
- SetPropertyAsAString(NS_LITERAL_STRING("kernel_version"), str);
- }
-
- const nsAdoptingString& b2g_os_name =
- mozilla::Preferences::GetString("b2g.osName");
- if (b2g_os_name) {
- SetPropertyAsAString(NS_LITERAL_STRING("name"), b2g_os_name);
- }
-
- const nsAdoptingString& b2g_version =
- mozilla::Preferences::GetString("b2g.version");
- if (b2g_version) {
- SetPropertyAsAString(NS_LITERAL_STRING("version"), b2g_version);
- }
-#endif
-
-#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
- SandboxInfo sandInfo = SandboxInfo::Get();
-
- SetPropertyAsBool(NS_LITERAL_STRING("hasSeccompBPF"),
- sandInfo.Test(SandboxInfo::kHasSeccompBPF));
- SetPropertyAsBool(NS_LITERAL_STRING("hasSeccompTSync"),
- sandInfo.Test(SandboxInfo::kHasSeccompTSync));
- SetPropertyAsBool(NS_LITERAL_STRING("hasUserNamespaces"),
- sandInfo.Test(SandboxInfo::kHasUserNamespaces));
- SetPropertyAsBool(NS_LITERAL_STRING("hasPrivilegedUserNamespaces"),
- sandInfo.Test(SandboxInfo::kHasPrivilegedUserNamespaces));
-
- if (sandInfo.Test(SandboxInfo::kEnabledForContent)) {
- SetPropertyAsBool(NS_LITERAL_STRING("canSandboxContent"),
- sandInfo.CanSandboxContent());
- }
-
- if (sandInfo.Test(SandboxInfo::kEnabledForMedia)) {
- SetPropertyAsBool(NS_LITERAL_STRING("canSandboxMedia"),
- sandInfo.CanSandboxMedia());
- }
-#endif // XP_LINUX && MOZ_SANDBOX
-
return NS_OK;
}
diff --git a/xpcom/build/BinaryPath.h b/xpcom/build/BinaryPath.h
index 374763c79..53034fcd8 100644
--- a/xpcom/build/BinaryPath.h
+++ b/xpcom/build/BinaryPath.h
@@ -90,11 +90,6 @@ private:
// On Android, we use the GRE_HOME variable that is set by the Java
// bootstrap code.
const char* greHome = getenv("GRE_HOME");
-#if defined(MOZ_WIDGET_GONK)
- if (!greHome) {
- greHome = "/system/b2g";
- }
-#endif
if (!greHome) {
return NS_ERROR_FAILURE;
diff --git a/xpcom/build/XPCOMInit.cpp b/xpcom/build/XPCOMInit.cpp
index 6ead5cdc7..7b220558f 100644
--- a/xpcom/build/XPCOMInit.cpp
+++ b/xpcom/build/XPCOMInit.cpp
@@ -171,9 +171,7 @@ extern nsresult nsStringInputStreamConstructor(nsISupports*, REFNSIID, void**);
#include "gfxPlatform.h"
-#if EXPOSE_INTL_API
#include "unicode/putil.h"
-#endif
using namespace mozilla;
using base::AtExitManager;
@@ -689,7 +687,7 @@ NS_InitXPCOM2(nsIServiceManager** aResult,
memmove);
#endif
-#if EXPOSE_INTL_API && defined(MOZ_ICU_DATA_ARCHIVE)
+#if defined(MOZ_ICU_DATA_ARCHIVE)
nsCOMPtr<nsIFile> greDir;
nsDirectoryService::gService->Get(NS_GRE_DIR,
NS_GET_IID(nsIFile),
@@ -1106,17 +1104,6 @@ ShutdownXPCOM(nsIServiceManager* aServMgr)
NS_LogTerm();
-#if defined(MOZ_WIDGET_GONK)
- // This _exit(0) call is intended to be temporary, to get shutdown leak
- // checking working on non-B2G platforms.
- // On debug B2G, the child process crashes very late. Instead, just
- // give up so at least we exit cleanly. See bug 1071866.
- if (XRE_IsContentProcess()) {
- NS_WARNING("Exiting child process early!");
- _exit(0);
- }
-#endif
-
return NS_OK;
}
diff --git a/xpcom/build/XREChildData.h b/xpcom/build/XREChildData.h
index 487fede94..c849131d6 100644
--- a/xpcom/build/XREChildData.h
+++ b/xpcom/build/XREChildData.h
@@ -9,14 +9,6 @@
#include "mozilla/UniquePtr.h"
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-#include "mozilla/sandboxing/loggingTypes.h"
-
-namespace sandbox {
-class TargetServices;
-}
-#endif
-
namespace mozilla {
namespace gmp {
class GMPLoader;
@@ -28,24 +20,13 @@ class GMPLoader;
*/
struct XREChildData
{
-#if !defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_WIDGET_GONK)
+#if !defined(MOZ_WIDGET_ANDROID)
/**
* Used to load the GMP binary.
*/
mozilla::UniquePtr<mozilla::gmp::GMPLoader> gmpLoader;
#endif
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- /**
- * Chromium sandbox TargetServices.
- */
- sandbox::TargetServices* sandboxTargetServices = nullptr;
-
- /**
- * Function to provide a logging function to the chromium sandbox code.
- */
- mozilla::sandboxing::ProvideLogFunctionCb ProvideLogFunction = nullptr;
-#endif
};
#endif // XREChildData_h
diff --git a/xpcom/build/XREShellData.h b/xpcom/build/XREShellData.h
deleted file mode 100644
index 11bc162d9..000000000
--- a/xpcom/build/XREShellData.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/* -*- 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 XREShellData_h
-#define XREShellData_h
-
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-namespace sandbox {
-class BrokerServices;
-}
-#endif
-
-/**
- * Data needed by XRE_XPCShellMain.
- */
-struct XREShellData
-{
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- /**
- * Chromium sandbox BrokerServices.
- */
- sandbox::BrokerServices* sandboxBrokerServices;
-#endif
-};
-
-#endif // XREShellData_h
diff --git a/xpcom/build/moz.build b/xpcom/build/moz.build
index 68bd001a2..e0adba0a2 100644
--- a/xpcom/build/moz.build
+++ b/xpcom/build/moz.build
@@ -12,7 +12,6 @@ EXPORTS += [
'nsXULAppAPI.h',
'XREChildData.h',
'xrecore.h',
- 'XREShellData.h',
]
EXPORTS.mozilla += [
diff --git a/xpcom/build/nsXREAppData.h b/xpcom/build/nsXREAppData.h
index fbc7adb8f..129336ac9 100644
--- a/xpcom/build/nsXREAppData.h
+++ b/xpcom/build/nsXREAppData.h
@@ -12,12 +12,6 @@
class nsIFile;
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
-namespace sandbox {
-class BrokerServices;
-}
-#endif
-
/**
* Application-specific data needed to start the apprunner.
*
@@ -134,13 +128,6 @@ struct nsXREAppData
* The application name to use in the User Agent string.
*/
const char* UAName;
-
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- /**
- * Chromium sandbox BrokerServices.
- */
- sandbox::BrokerServices* sandboxBrokerServices;
-#endif
};
/**
diff --git a/xpcom/build/nsXULAppAPI.h b/xpcom/build/nsXULAppAPI.h
index aae248ca1..c077c7e36 100644
--- a/xpcom/build/nsXULAppAPI.h
+++ b/xpcom/build/nsXULAppAPI.h
@@ -20,7 +20,6 @@
#include "mozilla/Vector.h"
#include "mozilla/TimeStamp.h"
#include "XREChildData.h"
-#include "XREShellData.h"
/**
* A directory service key which provides the platform-correct "application
@@ -504,8 +503,7 @@ XRE_API(void,
XRE_EnableSameExecutableForContentProc, ())
XRE_API(int,
- XRE_XPCShellMain, (int argc, char** argv, char** envp,
- const XREShellData* aShellData))
+ XRE_XPCShellMain, (int argc, char** argv, char** envp))
#if MOZ_WIDGET_GTK == 2
XRE_API(void,
diff --git a/xpcom/glue/AppData.cpp b/xpcom/glue/AppData.cpp
index 845267e60..2fdb6b009 100644
--- a/xpcom/glue/AppData.cpp
+++ b/xpcom/glue/AppData.cpp
@@ -65,10 +65,6 @@ ScopedAppData::ScopedAppData(const nsXREAppData* aAppData)
if (aAppData->size > offsetof(nsXREAppData, UAName)) {
SetAllocatedString(this->UAName, aAppData->UAName);
}
-
-#if defined(XP_WIN) && defined(MOZ_SANDBOX)
- sandboxBrokerServices = aAppData->sandboxBrokerServices;
-#endif
}
ScopedAppData::~ScopedAppData()
diff --git a/xpcom/glue/FileUtils.h b/xpcom/glue/FileUtils.h
index aaf912b21..b808d52e0 100644
--- a/xpcom/glue/FileUtils.h
+++ b/xpcom/glue/FileUtils.h
@@ -161,7 +161,7 @@ void ReadAhead(filedesc_t aFd, const size_t aOffset = 0,
const size_t aCount = SIZE_MAX);
-#if defined(MOZ_WIDGET_GONK) || defined(XP_UNIX)
+#if defined(XP_UNIX)
#define MOZ_TEMP_FAILURE_RETRY(exp) (__extension__({ \
typeof (exp) _rc; \
do { \
@@ -171,10 +171,9 @@ void ReadAhead(filedesc_t aFd, const size_t aOffset = 0,
}))
#endif
-/* Define ReadSysFile() and WriteSysFile() only on GONK to avoid unnecessary
- * libxul bloat. Also define it in debug builds, so that unit tests for it can
- * be written and run in non-GONK builds. */
-#if (defined(MOZ_WIDGET_GONK) || defined(DEBUG)) && defined(XP_UNIX)
+/* Define ReadSysFile() and WriteSysFile() only in debug builds, so that
+ * unit tests for it can be written and run. */
+#if defined(DEBUG) && defined(XP_UNIX)
#ifndef ReadSysFile_PRESENT
#define ReadSysFile_PRESENT
@@ -213,7 +212,7 @@ bool ReadSysFile(const char* aFilename, bool* aVal);
bool WriteSysFile(const char* aFilename, const char* aBuf);
-#endif /* (MOZ_WIDGET_GONK || DEBUG) && XP_UNIX */
+#endif /* DEBUG && XP_UNIX */
} // namespace mozilla
diff --git a/xpcom/idl-parser/xpidl/xpidl.py b/xpcom/idl-parser/xpidl/xpidl.py
index 8b2d8c884..6bb1ad5de 100755
--- a/xpcom/idl-parser/xpidl/xpidl.py
+++ b/xpcom/idl-parser/xpidl/xpidl.py
@@ -529,7 +529,7 @@ class Interface(object):
raise IDLError("interface '%s' inherits from non-interface type '%s'" % (self.name, self.base), self.location)
if self.attributes.scriptable and not realbase.attributes.scriptable:
- print >>sys.stderr, IDLError("interface '%s' is scriptable but derives from non-scriptable '%s'" % (self.name, self.base), self.location, warning=True)
+ raise IDLError("interface '%s' is scriptable but derives from non-scriptable '%s'" % (self.name, self.base), self.location, warning=True)
if self.attributes.scriptable and realbase.attributes.builtinclass and not self.attributes.builtinclass:
raise IDLError("interface '%s' is not builtinclass but derives from builtinclass '%s'" % (self.name, self.base), self.location)
diff --git a/xpcom/io/SpecialSystemDirectory.cpp b/xpcom/io/SpecialSystemDirectory.cpp
index ab65d38f9..158431088 100644
--- a/xpcom/io/SpecialSystemDirectory.cpp
+++ b/xpcom/io/SpecialSystemDirectory.cpp
@@ -705,12 +705,6 @@ GetSpecialSystemDirectory(SystemDirectories aSystemSystemDirectory,
}
return rv;
}
-#if defined(MOZ_CONTENT_SANDBOX)
- case Win_LocalAppdataLow: {
- GUID localAppDataLowGuid = FOLDERID_LocalAppDataLow;
- return GetKnownFolder(&localAppDataLowGuid, aFile);
- }
-#endif
case Win_Documents: {
return GetLibrarySaveToPath(CSIDL_MYDOCUMENTS,
FOLDERID_DocumentsLibrary,
diff --git a/xpcom/io/SpecialSystemDirectory.h b/xpcom/io/SpecialSystemDirectory.h
index 7c7f8fa42..b1ce31b74 100644
--- a/xpcom/io/SpecialSystemDirectory.h
+++ b/xpcom/io/SpecialSystemDirectory.h
@@ -76,9 +76,6 @@ enum SystemDirectories {
Win_Pictures = 233,
Win_Music = 234,
Win_Videos = 235,
-#if defined(MOZ_CONTENT_SANDBOX)
- Win_LocalAppdataLow = 236,
-#endif
Unix_LocalDirectory = 301,
Unix_LibDirectory = 302,
diff --git a/xpcom/io/nsAppDirectoryServiceDefs.h b/xpcom/io/nsAppDirectoryServiceDefs.h
index aa0a68816..3da85c987 100644
--- a/xpcom/io/nsAppDirectoryServiceDefs.h
+++ b/xpcom/io/nsAppDirectoryServiceDefs.h
@@ -84,35 +84,6 @@
#define NS_APP_PERMISSION_PARENT_DIR "permissionDBPDir"
-#if (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
-//
-// NS_APP_CONTENT_PROCESS_TEMP_DIR refers to a directory that is read and
-// write accessible from a sandboxed content process. The key may be used in
-// either process, but the directory is intended to be used for short-lived
-// files that need to be saved to the filesystem by the content process and
-// don't need to survive browser restarts. The directory is reset on startup.
-// The key is only valid when MOZ_CONTENT_SANDBOX is defined. When
-// MOZ_CONTENT_SANDBOX is defined, the directory the key refers to differs
-// depending on whether or not content sandboxing is enabled.
-//
-// When MOZ_CONTENT_SANDBOX is defined and sandboxing is enabled (versus
-// manually disabled via prefs), the content process replaces NS_OS_TEMP_DIR
-// with NS_APP_CONTENT_PROCESS_TEMP_DIR so that legacy code in content
-// attempting to write to NS_OS_TEMP_DIR will write to
-// NS_APP_CONTENT_PROCESS_TEMP_DIR instead. When MOZ_CONTENT_SANDBOX is
-// defined but sandboxing is disabled, NS_APP_CONTENT_PROCESS_TEMP_DIR
-// falls back to NS_OS_TEMP_DIR in both content and chrome processes.
-//
-// New code should avoid writing to the filesystem from the content process
-// and should instead proxy through the parent process whenever possible.
-//
-// At present, all sandboxed content processes use the same directory for
-// NS_APP_CONTENT_PROCESS_TEMP_DIR, but that should not be relied upon.
-//
-#define NS_APP_CONTENT_PROCESS_TEMP_DIR "ContentTmpD"
-#else
-// Otherwise NS_APP_CONTENT_PROCESS_TEMP_DIR must match NS_OS_TEMP_DIR.
#define NS_APP_CONTENT_PROCESS_TEMP_DIR "TmpD"
-#endif // (defined(XP_WIN) || defined(XP_MACOSX)) && defined(MOZ_CONTENT_SANDBOX)
#endif // nsAppDirectoryServiceDefs_h___
diff --git a/xpcom/io/nsDirectoryService.cpp b/xpcom/io/nsDirectoryService.cpp
index a4d962395..cfcce096d 100644
--- a/xpcom/io/nsDirectoryService.cpp
+++ b/xpcom/io/nsDirectoryService.cpp
@@ -490,27 +490,6 @@ nsDirectoryService::UnregisterProvider(nsIDirectoryServiceProvider* aProv)
return NS_OK;
}
-#if defined(MOZ_CONTENT_SANDBOX) && defined(XP_WIN)
-static nsresult
-GetLowIntegrityTempBase(nsIFile** aLowIntegrityTempBase)
-{
- nsCOMPtr<nsIFile> localFile;
- nsresult rv = GetSpecialSystemDirectory(Win_LocalAppdataLow,
- getter_AddRefs(localFile));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
-
- rv = localFile->Append(NS_LITERAL_STRING(MOZ_USER_DIR));
- if (NS_WARN_IF(NS_FAILED(rv))) {
- return rv;
- }
-
- localFile.forget(aLowIntegrityTempBase);
- return rv;
-}
-#endif
-
// DO NOT ADD ANY LOCATIONS TO THIS FUNCTION UNTIL YOU TALK TO: dougt@netscape.com.
// This is meant to be a place of xpcom or system specific file locations, not
// application specific locations. If you need the later, register a callback for
@@ -684,12 +663,6 @@ nsDirectoryService::GetFile(const char* aProp, bool* aPersistent,
rv = GetSpecialSystemDirectory(Win_Appdata, getter_AddRefs(localFile));
} else if (inAtom == nsDirectoryService::sLocalAppdata) {
rv = GetSpecialSystemDirectory(Win_LocalAppdata, getter_AddRefs(localFile));
-#if defined(MOZ_CONTENT_SANDBOX)
- } else if (inAtom == nsDirectoryService::sLocalAppdataLow) {
- rv = GetSpecialSystemDirectory(Win_LocalAppdataLow, getter_AddRefs(localFile));
- } else if (inAtom == nsDirectoryService::sLowIntegrityTempBase) {
- rv = GetLowIntegrityTempBase(getter_AddRefs(localFile));
-#endif
} else if (inAtom == nsDirectoryService::sPrinthood) {
rv = GetSpecialSystemDirectory(Win_Printhood, getter_AddRefs(localFile));
} else if (inAtom == nsDirectoryService::sWinCookiesDirectory) {
diff --git a/xpcom/io/nsDirectoryServiceAtomList.h b/xpcom/io/nsDirectoryServiceAtomList.h
index 38a2f0e9d..f636f60d8 100644
--- a/xpcom/io/nsDirectoryServiceAtomList.h
+++ b/xpcom/io/nsDirectoryServiceAtomList.h
@@ -72,10 +72,6 @@ DIR_ATOM(sCommon_Desktopdirectory, NS_WIN_COMMON_DESKTOP_DIRECTORY)
DIR_ATOM(sCommon_AppData, NS_WIN_COMMON_APPDATA_DIR)
DIR_ATOM(sAppdata, NS_WIN_APPDATA_DIR)
DIR_ATOM(sLocalAppdata, NS_WIN_LOCAL_APPDATA_DIR)
-#if defined(MOZ_CONTENT_SANDBOX)
-DIR_ATOM(sLocalAppdataLow, NS_WIN_LOCAL_APPDATA_LOW_DIR)
-DIR_ATOM(sLowIntegrityTempBase, NS_WIN_LOW_INTEGRITY_TEMP_BASE)
-#endif
DIR_ATOM(sPrinthood, NS_WIN_PRINTHOOD)
DIR_ATOM(sWinCookiesDirectory, NS_WIN_COOKIES_DIR)
DIR_ATOM(sDefaultDownloadDirectory, NS_WIN_DEFAULT_DOWNLOAD_DIR)
diff --git a/xpcom/io/nsDirectoryServiceDefs.h b/xpcom/io/nsDirectoryServiceDefs.h
index 0bdc5e390..4c62e0a7c 100644
--- a/xpcom/io/nsDirectoryServiceDefs.h
+++ b/xpcom/io/nsDirectoryServiceDefs.h
@@ -129,10 +129,6 @@
#define NS_WIN_COMMON_APPDATA_DIR "CmAppData"
#define NS_WIN_APPDATA_DIR "AppData"
#define NS_WIN_LOCAL_APPDATA_DIR "LocalAppData"
-#if defined(MOZ_CONTENT_SANDBOX)
- #define NS_WIN_LOCAL_APPDATA_LOW_DIR "LocalAppDataLow"
- #define NS_WIN_LOW_INTEGRITY_TEMP_BASE "LowTmpDBase"
-#endif
#define NS_WIN_PRINTHOOD "PrntHd"
#define NS_WIN_COOKIES_DIR "CookD"
#define NS_WIN_DEFAULT_DOWNLOAD_DIR "DfltDwnld"
diff --git a/xpcom/reflect/xptcall/xptcall.h b/xpcom/reflect/xptcall/xptcall.h
index 1f2367b5d..304787635 100644
--- a/xpcom/reflect/xptcall/xptcall.h
+++ b/xpcom/reflect/xptcall/xptcall.h
@@ -39,7 +39,7 @@ struct nsXPTCMiniVariant
// Types below here are unknown to the assembly implementations, and
// therefore _must_ be passed with indirect semantics. We put them in
// the union here for type safety, so that we can avoid void* tricks.
- JS::Value j;
+ JS::UninitializedValue j;
} val;
};
diff --git a/xpcom/threads/ThreadStackHelper.cpp b/xpcom/threads/ThreadStackHelper.cpp
index d31bf6359..1713c9194 100644
--- a/xpcom/threads/ThreadStackHelper.cpp
+++ b/xpcom/threads/ThreadStackHelper.cpp
@@ -359,11 +359,6 @@ ThreadStackHelper::PrepareStackBuffer(Stack& aStack)
profiler_register_thread). However, on B2G, profiling secondary threads
may be disabled despite profiler being enabled. This is by-design and
is not an error. */
-#ifdef MOZ_WIDGET_GONK
- if (!mPseudoStack) {
- return false;
- }
-#endif
MOZ_ASSERT(mPseudoStack);
if (!aStack.reserve(mMaxStackSize) ||
!aStack.reserve(aStack.capacity()) || // reserve up to the capacity
diff --git a/xpcom/threads/moz.build b/xpcom/threads/moz.build
index 5d54a4bf4..53e6b5922 100644
--- a/xpcom/threads/moz.build
+++ b/xpcom/threads/moz.build
@@ -76,11 +76,9 @@ LOCAL_INCLUDES += [
# BHR disabled for Release builds because of bug 965392.
# BHR disabled for debug builds because of bug 979069.
-# BHR disabled on gonk because of bug 1180533
# BHR disabled for TSan builds because of bug 1121216.
if CONFIG['MOZ_UPDATE_CHANNEL'] not in ('release') and \
not CONFIG['MOZ_DEBUG'] and \
- not CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk' and \
not CONFIG['MOZ_TSAN']:
DEFINES['MOZ_ENABLE_BACKGROUND_HANG_MONITOR'] = 1
diff --git a/xpfe/appshell/nsAppShellService.cpp b/xpfe/appshell/nsAppShellService.cpp
index 7e1ddf16c..f2497d0e0 100644
--- a/xpfe/appshell/nsAppShellService.cpp
+++ b/xpfe/appshell/nsAppShellService.cpp
@@ -732,13 +732,6 @@ nsAppShellService::JustCreateTopWindow(nsIXULWindow *aParent,
widgetInitData.mRTL = isRTL;
}
-#ifdef MOZ_WIDGET_GONK
- // B2G multi-screen support. Screen ID is for differentiating screens of
- // windows, and due to the hardware limitation, it is platform-specific for
- // now, which align with the value of display type defined in HWC.
- widgetInitData.mScreenId = mScreenId;
-#endif
-
nsresult rv = window->Initialize(parent, center ? aParent : nullptr,
aUrl, aInitialWidth, aInitialHeight,
aIsHiddenWindow, aOpeningTab,
diff --git a/xpfe/appshell/nsContentTreeOwner.cpp b/xpfe/appshell/nsContentTreeOwner.cpp
index b39b7610f..f0fcdef9a 100644
--- a/xpfe/appshell/nsContentTreeOwner.cpp
+++ b/xpfe/appshell/nsContentTreeOwner.cpp
@@ -390,6 +390,7 @@ NS_IMETHODIMP nsContentTreeOwner::OnBeforeLinkTraversal(const nsAString &origina
NS_IMETHODIMP nsContentTreeOwner::ShouldLoadURI(nsIDocShell *aDocShell,
nsIURI *aURI,
nsIURI *aReferrer,
+ nsIPrincipal* aTriggeringPrincipal,
bool *_retval)
{
NS_ENSURE_STATE(mXULWindow);
@@ -398,7 +399,8 @@ NS_IMETHODIMP nsContentTreeOwner::ShouldLoadURI(nsIDocShell *aDocShell,
mXULWindow->GetXULBrowserWindow(getter_AddRefs(xulBrowserWindow));
if (xulBrowserWindow)
- return xulBrowserWindow->ShouldLoadURI(aDocShell, aURI, aReferrer, _retval);
+ return xulBrowserWindow->ShouldLoadURI(aDocShell, aURI, aReferrer,
+ aTriggeringPrincipal, _retval);
*_retval = true;
return NS_OK;
@@ -407,6 +409,7 @@ NS_IMETHODIMP nsContentTreeOwner::ShouldLoadURI(nsIDocShell *aDocShell,
NS_IMETHODIMP nsContentTreeOwner::ReloadInFreshProcess(nsIDocShell* aDocShell,
nsIURI* aURI,
nsIURI* aReferrer,
+ nsIPrincipal* aTriggeringPrincipal,
bool* aRetVal)
{
NS_WARNING("Cannot reload in fresh process from a nsContentTreeOwner!");
diff --git a/xpfe/appshell/nsIXULBrowserWindow.idl b/xpfe/appshell/nsIXULBrowserWindow.idl
index 40f1898c8..5dbc2d409 100644
--- a/xpfe/appshell/nsIXULBrowserWindow.idl
+++ b/xpfe/appshell/nsIXULBrowserWindow.idl
@@ -13,6 +13,7 @@ interface nsIDOMElement;
interface nsIInputStream;
interface nsIDocShell;
interface nsITabParent;
+interface nsIPrincipal;
interface mozIDOMWindowProxy;
/**
@@ -60,10 +61,13 @@ interface nsIXULBrowserWindow : nsISupports
* The URI being loaded.
* @param aReferrer
* The referrer of the load.
+ * @param aTriggeringPrincipal
+ * The principal that initiated the load of aURI.
*/
bool shouldLoadURI(in nsIDocShell aDocShell,
in nsIURI aURI,
- in nsIURI aReferrer);
+ in nsIURI aReferrer,
+ in nsIPrincipal aTriggeringPrincipal);
/**
* Show/hide a tooltip (when the user mouses over a link, say).
*/
diff --git a/xpfe/appshell/nsWindowMediator.cpp b/xpfe/appshell/nsWindowMediator.cpp
index 6d69bc764..35ae550ae 100644
--- a/xpfe/appshell/nsWindowMediator.cpp
+++ b/xpfe/appshell/nsWindowMediator.cpp
@@ -616,12 +616,10 @@ nsWindowMediator::GetZLevel(nsIXULWindow *aWindow, uint32_t *_retval)
{
NS_ENSURE_ARG_POINTER(_retval);
*_retval = nsIXULWindow::normalZ;
+ // This can fail during window destruction.
nsWindowInfo *info = GetInfoFor(aWindow);
if (info) {
*_retval = info->mZLevel;
- } else {
- NS_WARNING("getting z level of unregistered window");
- // this goes off during window destruction
}
return NS_OK;
}